diff --git a/.gitattributes b/.gitattributes index bfa8f4f80c71ea617037560b4410b617de1dce07..dd8d9257cfe90492a6ab63615c1ed6e4c3152979 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,6 +2,13 @@ *.pdf filter=lfs diff=lfs merge=lfs -text pdfs/**/*.json filter=lfs diff=lfs merge=lfs -text pdfs/**/*.txt filter=lfs diff=lfs merge=lfs -text +# ppocr +*.pdopt filter=lfs diff=lfs merge=lfs -text +*.pdparams filter=lfs diff=lfs merge=lfs -text +*.pdiparams filter=lfs diff=lfs merge=lfs -text +*.pdmodel filter=lfs diff=lfs merge=lfs -text +*.states filter=lfs diff=lfs merge=lfs -text +*.info filter=lfs diff=lfs merge=lfs -text *.arrow filter=lfs diff=lfs merge=lfs -text *.bin filter=lfs diff=lfs merge=lfs -text *.bz2 filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index 320c02a3cfa3b9fff7876736dfce95dd5c407ac4..856205e73154013f6bf43ad084138eb98ef5a52d 100644 --- a/.gitignore +++ b/.gitignore @@ -31,4 +31,5 @@ daciling_pre.json daciling_zh.txt *.aac bt.jpeg -*log.txt \ No newline at end of file +*log.txt +paddleocr.egg-info/ \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitattributes b/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..3abc057ba70f9d9ba8f0789a6ca81c58c48b6d35 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitattributes @@ -0,0 +1,57 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.so filter=lfs diff=lfs merge=lfs -text +*.so.[0-9] filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +*.jpg filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.db filter=lfs diff=lfs merge=lfs -text +# ppocr +*.pdopt filter=lfs diff=lfs merge=lfs -text +*.pdparams filter=lfs diff=lfs merge=lfs -text +*.pdiparams filter=lfs diff=lfs merge=lfs -text +*.pdmodel filter=lfs diff=lfs merge=lfs -text +*.states filter=lfs diff=lfs merge=lfs -text +*.info filter=lfs diff=lfs merge=lfs -text +# font +*.ttf filter=lfs diff=lfs merge=lfs -text +*.ttc filter=lfs diff=lfs merge=lfs -text + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitignore b/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fb3a0a6420953a941591d430bb42f06f2268d1c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/.gitignore @@ -0,0 +1,47 @@ +# node_modules +# __pycache__ +# flagged +# exported +# package-lock.json +# package.json +# output.mp4 +# #config.json + +# ######### PaddleOCR_ali1k_det_rec_300epoch begin ######################## + +# # Byte-compiled / optimized / DLL files +# __pycache__/ +# .ipynb_checkpoints/ +# *.py[cod] +# *$py.class + +# # C extensions +# # *.so + +# # inference/ +# inference_results/ +# # output/ +# # train_data/ +# log/ +# *.DS_Store +# *.vs +# *.user +# *~ +# *.vscode +# *.idea + +# # *.log +# .clang-format +# .clang_format.hook + +# build/ +# dist/ +# paddleocr.egg-info/ +# /deploy/android_demo/app/OpenCV/ +# /deploy/android_demo/app/PaddleLite/ +# /deploy/android_demo/app/.cxx/ +# /deploy/android_demo/app/cache/ +# test_tipc/web/models/ +# test_tipc/web/node_modules/ + +# ######### PaddleOCR_ali1k_det_rec_300epoch end ######################## diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/README.md b/PaddleOCR_ali1k_det_rec_300epoch_standalone/README.md new file mode 100644 index 0000000000000000000000000000000000000000..20043fc1adfa7eebc084f4fc265e6f7d89a71bcb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/README.md @@ -0,0 +1,289 @@ +English | [简体中文](README_ch.md) + +see 深入理解神经网络:从逻辑回归到CNN.md -> PaddleOCR_ali1k_det_rec_300epoch + +Illegal instruction 错误 + +It can be fixed by PR , We skip SelfAttentionFusePass on non-avx512 platform + +pip uninstall paddlepaddle + +pip install paddlepaddle==2.4.2 + +pip install -r requirements.txt + +python tools/infer/predict_rec.py --image_dir=train_data/rec/test/1_crop_5.jpg --rec_model_dir=output/rec_model/Student --rec_char_dict_path=train_data/keys.txt + +PaddleOCR_ali1k_det_rec_300epoch.7z + + +``` +source activate PP && \ +pip uninstall opencv-python && \ +pip install opencv-python==4.6.0.66 && \ +pip install pyyaml + +cp autodl-tmp/train_data.zip . && \ +unzip train_data.zip -d PaddleOCR + +# 空间不够用软链接 +ln -s /root/autodl-tmp/train_data /root/PaddleOCR/train_data + +cd PPOCRLabel && \ +python gen_ocr_train_val_test.py + +# 训练 +source activate PP && \ +python tools/train.py -c configs/rec/PP-OCRv3/ch_PP-OCRv3_rec_distillation.yml + +# 继续上一次训练(epoch 接着上一次的断点开始) +source activate PP && \ +python tools/train.py -c configs/rec/PP-OCRv3/ch_PP-OCRv3_rec_distillation.yml -o Global.checkpoints=output/rec_ppocr_v3_distillation/best_accuracy + +# 微调 (epoch 从一开始) +source activate PP && \ +python tools/train.py -c configs/rec/PP-OCRv3/ch_PP-OCRv3_rec_distillation.yml -o Global.pretrained_model=output/rec_ppocr_v3_distillation/best_accuracy + +# 导出模型 +python tools/export_model.py -c configs/rec/PP-OCRv3/ch_PP-OCRv3_rec_distillation.yml -o Global.checkpoints=output/rec_ppocr_v3_distillation/best_accuracy Global.save_inference_dir=output/model + +# 推断 +python tools/infer/predict_rec.py --image_dir=train_data/rec/test/1_crop_0.jpg --rec_model_dir=output/model/Student --rec_char_dict_path=train_data/keys.txt + # train_data/keys.txt 是自已生成的自定义词典,训练的时侯也要指定这个词典 +``` + + +

+ +

+

+ + + + + + + +

+ +## Introduction + +PaddleOCR aims to create multilingual, awesome, leading, and practical OCR tools that help users train better models and apply them into practice. + +
+ +
+ +
+ +
+ +## 📣 Recent updates +- **🔥2022.8.24 Release PaddleOCR [release/2.6](https://github.com/PaddlePaddle/PaddleOCR/tree/release/2.6)** + - Release [PP-Structurev2](./ppstructure/),with functions and performance fully upgraded, adapted to Chinese scenes, and new support for [Layout Recovery](./ppstructure/recovery) and **one line command to convert PDF to Word**; + - [Layout Analysis](./ppstructure/layout) optimization: model storage reduced by 95%, while speed increased by 11 times, and the average CPU time-cost is only 41ms; + - [Table Recognition](./ppstructure/table) optimization: 3 optimization strategies are designed, and the model accuracy is improved by 6% under comparable time consumption; + - [Key Information Extraction](./ppstructure/kie) optimization:a visual-independent model structure is designed, the accuracy of semantic entity recognition is increased by 2.8%, and the accuracy of relation extraction is increased by 9.1%. +- **🔥2022.8 Release [OCR scene application collection](./applications/README_en.md)** + - Release **9 vertical models** such as digital tube, LCD screen, license plate, handwriting recognition model, high-precision SVTR model, etc, covering the main OCR vertical applications in general, manufacturing, finance, and transportation industries. +- **2022.8 Add implementation of [8 cutting-edge algorithms](doc/doc_en/algorithm_overview_en.md)** + - Text Detection: [FCENet](doc/doc_en/algorithm_det_fcenet_en.md), [DB++](doc/doc_en/algorithm_det_db_en.md) + - Text Recognition: [ViTSTR](doc/doc_en/algorithm_rec_vitstr_en.md), [ABINet](doc/doc_en/algorithm_rec_abinet_en.md), [VisionLAN](doc/doc_en/algorithm_rec_visionlan_en.md), [SPIN](doc/doc_en/algorithm_rec_spin_en.md), [RobustScanner](doc/doc_en/algorithm_rec_robustscanner_en.md) + - Table Recognition: [TableMaster](doc/doc_en/algorithm_table_master_en.md) +- **2022.5.9 Release PaddleOCR [release/2.5](https://github.com/PaddlePaddle/PaddleOCR/tree/release/2.5)** + - Release [PP-OCRv3](./doc/doc_en/ppocr_introduction_en.md#pp-ocrv3): With comparable speed, the effect of Chinese scene is further improved by 5% compared with PP-OCRv2, the effect of English scene is improved by 11%, and the average recognition accuracy of 80 language multilingual models is improved by more than 5%. + - Release [PPOCRLabelv2](./PPOCRLabel): Add the annotation function for table recognition task, key information extraction task and irregular text image. + - Release interactive e-book [*"Dive into OCR"*](./doc/doc_en/ocr_book_en.md), covers the cutting-edge theory and code practice of OCR full stack technology. +- [more](./doc/doc_en/update_en.md) + + +## 🌟 Features + +PaddleOCR support a variety of cutting-edge algorithms related to OCR, and developed industrial featured models/solution [PP-OCR](./doc/doc_en/ppocr_introduction_en.md) and [PP-Structure](./ppstructure/README.md) on this basis, and get through the whole process of data production, model training, compression, inference and deployment. + +
+ +
+ +> It is recommended to start with the “quick experience” in the document tutorial + + +## ⚡ Quick Experience + +- Web online experience for the ultra-lightweight OCR: [Online Experience](https://www.paddlepaddle.org.cn/hub/scene/ocr) +- Mobile DEMO experience (based on EasyEdge and Paddle-Lite, supports iOS and Android systems): [Sign in to the website to obtain the QR code for installing the App](https://ai.baidu.com/easyedge/app/openSource?from=paddlelite) +- One line of code quick use: [Quick Start](./doc/doc_en/quickstart_en.md) + + + +## 📚 E-book: *Dive Into OCR* +- [Dive Into OCR ](./doc/doc_en/ocr_book_en.md) + + +## 👫 Community + +- For international developers, we regard [PaddleOCR Discussions](https://github.com/PaddlePaddle/PaddleOCR/discussions) as our international community platform. All ideas and questions can be discussed here in English. + +- For Chinese develops, Scan the QR code below with your Wechat, you can join the official technical discussion group. For richer community content, please refer to [中文README](README_ch.md), looking forward to your participation. + +
+ +
+ + + +## 🛠️ PP-OCR Series Model List(Update on September 8th) + +| Model introduction | Model name | Recommended scene | Detection model | Direction classifier | Recognition model | +| ------------------------------------------------------------ | ---------------------------- | ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Chinese and English ultra-lightweight PP-OCRv3 model(16.2M) | ch_PP-OCRv3_xx | Mobile & Server | [inference model](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_distill_train.tar) | [inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_train.tar) | [inference model](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_train.tar) | +| English ultra-lightweight PP-OCRv3 model(13.4M) | en_PP-OCRv3_xx | Mobile & Server | [inference model](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_det_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_det_distill_train.tar) | [inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_train.tar) | [inference model](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_rec_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_rec_train.tar) | +| Chinese and English ultra-lightweight PP-OCRv2 model(11.6M) | ch_PP-OCRv2_xx |Mobile & Server|[inference model](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_det_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_det_distill_train.tar)| [inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_train.tar) |[inference model](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_rec_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_rec_train.tar)| +| Chinese and English ultra-lightweight PP-OCR model (9.4M) | ch_ppocr_mobile_v2.0_xx | Mobile & server |[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_det_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_det_train.tar)|[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_train.tar) |[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_rec_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_rec_train.tar) | +| Chinese and English general PP-OCR model (143.4M) | ch_ppocr_server_v2.0_xx | Server |[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_det_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_det_train.tar) |[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_train.tar) |[inference model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_rec_infer.tar) / [trained model](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_rec_train.tar) | + + +- For more model downloads (including multiple languages), please refer to [PP-OCR series model downloads](./doc/doc_en/models_list_en.md). +- For a new language request, please refer to [Guideline for new language_requests](#language_requests). +- For structural document analysis models, please refer to [PP-Structure models](./ppstructure/docs/models_list_en.md). + +## 📖 Tutorials +- [Environment Preparation](./doc/doc_en/environment_en.md) +- [PP-OCR 🔥](./doc/doc_en/ppocr_introduction_en.md) + - [Quick Start](./doc/doc_en/quickstart_en.md) + - [Model Zoo](./doc/doc_en/models_en.md) + - [Model training](./doc/doc_en/training_en.md) + - [Text Detection](./doc/doc_en/detection_en.md) + - [Text Recognition](./doc/doc_en/recognition_en.md) + - [Text Direction Classification](./doc/doc_en/angle_class_en.md) + - Model Compression + - [Model Quantization](./deploy/slim/quantization/README_en.md) + - [Model Pruning](./deploy/slim/prune/README_en.md) + - [Knowledge Distillation](./doc/doc_en/knowledge_distillation_en.md) + - [Inference and Deployment](./deploy/README.md) + - [Python Inference](./doc/doc_en/inference_ppocr_en.md) + - [C++ Inference](./deploy/cpp_infer/readme.md) + - [Serving](./deploy/pdserving/README.md) + - [Mobile](./deploy/lite/readme.md) + - [Paddle2ONNX](./deploy/paddle2onnx/readme.md) + - [PaddleCloud](./deploy/paddlecloud/README.md) + - [Benchmark](./doc/doc_en/benchmark_en.md) +- [PP-Structure 🔥](./ppstructure/README.md) + - [Quick Start](./ppstructure/docs/quickstart_en.md) + - [Model Zoo](./ppstructure/docs/models_list_en.md) + - [Model training](./doc/doc_en/training_en.md) + - [Layout Analysis](./ppstructure/layout/README.md) + - [Table Recognition](./ppstructure/table/README.md) + - [Key Information Extraction](./ppstructure/kie/README.md) + - [Inference and Deployment](./deploy/README.md) + - [Python Inference](./ppstructure/docs/inference_en.md) + - [C++ Inference](./deploy/cpp_infer/readme.md) + - [Serving](./deploy/hubserving/readme_en.md) +- [Academic Algorithms](./doc/doc_en/algorithm_overview_en.md) + - [Text detection](./doc/doc_en/algorithm_overview_en.md) + - [Text recognition](./doc/doc_en/algorithm_overview_en.md) + - [End-to-end OCR](./doc/doc_en/algorithm_overview_en.md) + - [Table Recognition](./doc/doc_en/algorithm_overview_en.md) + - [Key Information Extraction](./doc/doc_en/algorithm_overview_en.md) + - [Add New Algorithms to PaddleOCR](./doc/doc_en/add_new_algorithm_en.md) +- Data Annotation and Synthesis + - [Semi-automatic Annotation Tool: PPOCRLabel](./PPOCRLabel/README.md) + - [Data Synthesis Tool: Style-Text](./StyleText/README.md) + - [Other Data Annotation Tools](./doc/doc_en/data_annotation_en.md) + - [Other Data Synthesis Tools](./doc/doc_en/data_synthesis_en.md) +- Datasets + - [General OCR Datasets(Chinese/English)](doc/doc_en/dataset/datasets_en.md) + - [HandWritten_OCR_Datasets(Chinese)](doc/doc_en/dataset/handwritten_datasets_en.md) + - [Various OCR Datasets(multilingual)](doc/doc_en/dataset/vertical_and_multilingual_datasets_en.md) + - [Layout Analysis](doc/doc_en/dataset/layout_datasets_en.md) + - [Table Recognition](doc/doc_en/dataset/table_datasets_en.md) + - [Key Information Extraction](doc/doc_en/dataset/kie_datasets_en.md) +- [Code Structure](./doc/doc_en/tree_en.md) +- [Visualization](#Visualization) +- [Community](#Community) +- [New language requests](#language_requests) +- [FAQ](./doc/doc_en/FAQ_en.md) +- [References](./doc/doc_en/reference_en.md) +- [License](#LICENSE) + + + +## 👀 Visualization [more](./doc/doc_en/visualization_en.md) + +
+PP-OCRv3 Chinese model +
+ + + +
+
+ +
+PP-OCRv3 English model +
+ + +
+
+ +
+PP-OCRv3 Multilingual model +
+ + +
+
+ +
+PP-Structurev2 + +- layout analysis + table recognition +
+ +
+ +- SER (Semantic entity recognition) +
+ +
+ +
+ +
+ +
+ +
+ +- RE (Relation Extraction) +
+ +
+ +
+ +
+ +
+ +
+ +
+ + +## 🇺🇳 Guideline for New Language Requests + +If you want to request a new language support, a PR with 1 following files are needed: + +1. In folder [ppocr/utils/dict](./ppocr/utils/dict), +it is necessary to submit the dict text to this path and name it with `{language}_dict.txt` that contains a list of all characters. Please see the format example from other files in that folder. + +If your language has unique elements, please tell me in advance within any way, such as useful links, wikipedia and so on. + +More details, please refer to [Multilingual OCR Development Plan](https://github.com/PaddlePaddle/PaddleOCR/issues/1048). + + + +## 📄 License +This project is released under Apache 2.0 license diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/arabic.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/arabic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5ed05bdb338c4c489605c8f636b9a1477eb65819 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/arabic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd25bfc3c6d745a8a4b4d415321aa5b43d99b61744b50d20e32931811ec7e268 +size 102000 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/chinese_cht.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/chinese_cht.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ab4597cc93bb8f97639c249ec7a27aa88ddfd7d7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/chinese_cht.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ce814960d0cdea1dd647180636babc1cf6a0acf0a9a9019424f4689acedd9ea +size 7376416 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/cyrillic.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/cyrillic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0200182fe2a0b4a91979cebee37bee55d4236264 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/cyrillic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:084768d29859a62b735387fb5946dfe61fb3d844031c7c51c1668d8afbe3b802 +size 56198 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/french.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/french.ttf new file mode 100644 index 0000000000000000000000000000000000000000..475c90f422ea2c98c787694cc5c6438ee73e9717 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/french.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9 +size 773236 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/german.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/german.ttf new file mode 100644 index 0000000000000000000000000000000000000000..475c90f422ea2c98c787694cc5c6438ee73e9717 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/german.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9 +size 773236 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/hindi.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/hindi.ttf new file mode 100644 index 0000000000000000000000000000000000000000..beac58beeb9c113b753d6614cf044065a1f97953 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/hindi.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d519981fc26e2fe934bd25ec9dfe478e082c99063d868008b20996809e13ccc +size 222356 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/japan.ttc b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/japan.ttc new file mode 100644 index 0000000000000000000000000000000000000000..7e5f6d5d7fdd0c42fd633153df81e1ef8b5735d8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/japan.ttc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11122490a5e3a862015c8894183750de59abf95c3936d63d5978293d92f23dba +size 3478068 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/kannada.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/kannada.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ec581758e1cf14207e1f490e23798585aea81065 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/kannada.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b337386a8e853ccba53c0c248bd06f025d7667b800ba74c72c66040d67315c6e +size 797016 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/korean.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/korean.ttf new file mode 100644 index 0000000000000000000000000000000000000000..1337e3e44414c852ea6d1f51239c74d22205abc7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/korean.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0897316bdb2e308cea2841c54940f2ef5707856000aa07910c8bff39a47e40bd +size 1222780 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/latin.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/latin.ttf new file mode 100644 index 0000000000000000000000000000000000000000..5ba5fe5d5764d97ca4cf4677446514ed59ac1959 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/latin.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1562fe5cbdaacab4a5880d6404ba05245d12f3a4478fe16021e976bc725ce5d5 +size 54948 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/marathi.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/marathi.ttf new file mode 100644 index 0000000000000000000000000000000000000000..23ac069e48c8f6878828077c2b4b6893e0a99378 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/marathi.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0de62f3fe6c7de77d8d1ffbde4980969bd1f20347019ce8136b492e93d7ea9e6 +size 68684 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/nepali.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/nepali.ttf new file mode 100644 index 0000000000000000000000000000000000000000..beac58beeb9c113b753d6614cf044065a1f97953 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/nepali.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d519981fc26e2fe934bd25ec9dfe478e082c99063d868008b20996809e13ccc +size 222356 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/persian.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/persian.ttf new file mode 100644 index 0000000000000000000000000000000000000000..75684edd6a5d9c262a08d7dbdec8289b2f9b9f7b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/persian.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:233ec81460a1c2ccd51d3187b1cf27b1dd5a5a8131a7931357aa95b81ab2a8c3 +size 31564 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b1905868c15c38c3aa3161a3b1e17447a38fe201 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:521c6f7546b4eb64fa4b0cd604bbd36333a20a57e388c8e2ad2ad07b9e593864 +size 10576012 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/spanish.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/spanish.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4d8c99a93e9e6dcdea46927934098f7d8f37a29d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/spanish.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3e632f80a2918e0536585ce52ecf2f379dc0f6b65b5b88d731ae52f9ac0d54 +size 336452 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/tamil.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/tamil.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d7b5c6db68a002c45a7313768ab6c3a8a3ae7705 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/tamil.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b771ac413157f6b1f1a52fb8ff1b56057f4b492fcce385ddd32ca12eee0c73b0 +size 142512 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/telugu.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/telugu.ttf new file mode 100644 index 0000000000000000000000000000000000000000..daaf538e88f5b5019e428bec5145340310b8bcd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/telugu.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f82ab141b77d263f9ea9b31b47faf50c11310f42fce6d9dffeaaa334909bbf9 +size 990048 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/urdu.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/urdu.ttf new file mode 100644 index 0000000000000000000000000000000000000000..03d1c2954872b6f147de72196549c35712a5acc3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/urdu.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b21f221262edff3cf4fd95b92123125d9368a38a382b1d6c9e502fe776b44254 +size 38788 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/uyghur.ttf b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/uyghur.ttf new file mode 100644 index 0000000000000000000000000000000000000000..03d1c2954872b6f147de72196549c35712a5acc3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/uyghur.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b21f221262edff3cf4fd95b92123125d9368a38a382b1d6c9e502fe776b44254 +size 38788 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/freeze.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/freeze.txt new file mode 100644 index 0000000000000000000000000000000000000000..520b926961e6788a5919c7ee8a2129e7c5e91218 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/freeze.txt @@ -0,0 +1,59 @@ +astor==0.8.1 +attrdict==2.0.1 +babel==2.16.0 +bce-python-sdk==0.9.21 +blinker==1.8.2 +cachetools==5.5.0 +certifi==2024.8.30 +charset-normalizer==3.3.2 +click==8.1.7 +contourpy==1.3.0 +cssselect==1.2.0 +cssutils==2.11.1 +cycler==0.12.1 +Cython==3.0.11 +decorator==5.1.1 +et-xmlfile==1.1.0 +Flask==3.0.3 +flask-babel==4.0.0 +fonttools==4.53.1 +future==1.0.0 +idna==3.8 +imageio==2.35.1 +imgaug==0.4.0 +itsdangerous==2.2.0 +Jinja2==3.1.4 +kiwisolver==1.4.5 +lazy_loader==0.4 +lmdb==1.5.1 +lxml==5.3.0 +MarkupSafe==2.1.5 +matplotlib==3.9.2 +more-itertools==10.4.0 +networkx==3.3 +numpy==1.26.4 +opencv-contrib-python==4.10.0.84 +opencv-python==4.6.0.66 +openpyxl==3.1.5 +opt-einsum==3.3.0 +packaging==24.1 +pillow==10.4.0 +premailer==3.10.0 +psutil==6.0.0 +pyclipper==1.3.0.post5 +pycryptodome==3.20.0 +pyparsing==3.1.4 +python-dateutil==2.9.0.post0 +pytz==2024.1 +rapidfuzz==3.9.7 +rarfile==4.2 +requests==2.32.3 +scikit-image==0.24.0 +scipy==1.14.1 +shapely==2.0.6 +six==1.16.0 +tifffile==2024.8.30 +tqdm==4.66.5 +tzdata==2024.1 +urllib3==2.2.2 +Werkzeug==3.0.4 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39555e643e2edc5a434cfff0d5f9d443c3e92259 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/__init__.py @@ -0,0 +1,33 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Copyright 2007 Google Inc. All Rights Reserved. + +__version__ = '3.20.0' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/any_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/any_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..9121193d1104e6c1742c6bee68f38aa0d68e26c1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/any_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/any.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"&\n\x03\x41ny\x12\x10\n\x08type_url\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c\x42v\n\x13\x63om.google.protobufB\x08\x41nyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.any_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\010AnyProtoP\001Z,google.golang.org/protobuf/types/known/anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _ANY._serialized_start=46 + _ANY._serialized_end=84 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/api_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/api_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1721b10a750bb66cb600526ffa13e85e1390c69d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/api_pb2.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/api.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import source_context_pb2 as google_dot_protobuf_dot_source__context__pb2 +from google.protobuf import type_pb2 as google_dot_protobuf_dot_type__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/api.proto\x12\x0fgoogle.protobuf\x1a$google/protobuf/source_context.proto\x1a\x1agoogle/protobuf/type.proto\"\x81\x02\n\x03\x41pi\x12\x0c\n\x04name\x18\x01 \x01(\t\x12(\n\x07methods\x18\x02 \x03(\x0b\x32\x17.google.protobuf.Method\x12(\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.Option\x12\x0f\n\x07version\x18\x04 \x01(\t\x12\x36\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContext\x12&\n\x06mixins\x18\x06 \x03(\x0b\x32\x16.google.protobuf.Mixin\x12\'\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.Syntax\"\xd5\x01\n\x06Method\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x18\n\x10request_type_url\x18\x02 \x01(\t\x12\x19\n\x11request_streaming\x18\x03 \x01(\x08\x12\x19\n\x11response_type_url\x18\x04 \x01(\t\x12\x1a\n\x12response_streaming\x18\x05 \x01(\x08\x12(\n\x07options\x18\x06 \x03(\x0b\x32\x17.google.protobuf.Option\x12\'\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.Syntax\"#\n\x05Mixin\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04root\x18\x02 \x01(\tBv\n\x13\x63om.google.protobufB\x08\x41piProtoP\x01Z,google.golang.org/protobuf/types/known/apipb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.api_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\010ApiProtoP\001Z,google.golang.org/protobuf/types/known/apipb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _API._serialized_start=113 + _API._serialized_end=370 + _METHOD._serialized_start=373 + _METHOD._serialized_end=586 + _MIXIN._serialized_start=588 + _MIXIN._serialized_end=623 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/compiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/compiler/plugin_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/compiler/plugin_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..715a8913705fe62913ab66084a5a9090bbc5da2b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/compiler/plugin_pb2.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/compiler/plugin.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"F\n\x07Version\x12\r\n\x05major\x18\x01 \x01(\x05\x12\r\n\x05minor\x18\x02 \x01(\x05\x12\r\n\x05patch\x18\x03 \x01(\x05\x12\x0e\n\x06suffix\x18\x04 \x01(\t\"\xba\x01\n\x14\x43odeGeneratorRequest\x12\x18\n\x10\x66ile_to_generate\x18\x01 \x03(\t\x12\x11\n\tparameter\x18\x02 \x01(\t\x12\x38\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\x12;\n\x10\x63ompiler_version\x18\x03 \x01(\x0b\x32!.google.protobuf.compiler.Version\"\xc1\x02\n\x15\x43odeGeneratorResponse\x12\r\n\x05\x65rror\x18\x01 \x01(\t\x12\x1a\n\x12supported_features\x18\x02 \x01(\x04\x12\x42\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.File\x1a\x7f\n\x04\x46ile\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0finsertion_point\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x0f \x01(\t\x12?\n\x13generated_code_info\x18\x10 \x01(\x0b\x32\".google.protobuf.GeneratedCodeInfo\"8\n\x07\x46\x65\x61ture\x12\x10\n\x0c\x46\x45\x41TURE_NONE\x10\x00\x12\x1b\n\x17\x46\x45\x41TURE_PROTO3_OPTIONAL\x10\x01\x42W\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtosZ)google.golang.org/protobuf/types/pluginpb') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.compiler.plugin_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\034com.google.protobuf.compilerB\014PluginProtosZ)google.golang.org/protobuf/types/pluginpb' + _VERSION._serialized_start=101 + _VERSION._serialized_end=171 + _CODEGENERATORREQUEST._serialized_start=174 + _CODEGENERATORREQUEST._serialized_end=360 + _CODEGENERATORRESPONSE._serialized_start=363 + _CODEGENERATORRESPONSE._serialized_end=684 + _CODEGENERATORRESPONSE_FILE._serialized_start=499 + _CODEGENERATORRESPONSE_FILE._serialized_end=626 + _CODEGENERATORRESPONSE_FEATURE._serialized_start=628 + _CODEGENERATORRESPONSE_FEATURE._serialized_end=684 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor.py new file mode 100644 index 0000000000000000000000000000000000000000..ad70be9a11488066a8ff8090b9d92b707039de27 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor.py @@ -0,0 +1,1224 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Descriptors essentially contain exactly the information found in a .proto +file, in types that make this information accessible in Python. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import threading +import warnings + +from google.protobuf.internal import api_implementation + +_USE_C_DESCRIPTORS = False +if api_implementation.Type() == 'cpp': + # Used by MakeDescriptor in cpp mode + import binascii + import os + from google.protobuf.pyext import _message + _USE_C_DESCRIPTORS = True + + +class Error(Exception): + """Base error for this module.""" + + +class TypeTransformationError(Error): + """Error transforming between python proto type and corresponding C++ type.""" + + +if _USE_C_DESCRIPTORS: + # This metaclass allows to override the behavior of code like + # isinstance(my_descriptor, FieldDescriptor) + # and make it return True when the descriptor is an instance of the extension + # type written in C++. + class DescriptorMetaclass(type): + def __instancecheck__(cls, obj): + if super(DescriptorMetaclass, cls).__instancecheck__(obj): + return True + if isinstance(obj, cls._C_DESCRIPTOR_CLASS): + return True + return False +else: + # The standard metaclass; nothing changes. + DescriptorMetaclass = type + + +class _Lock(object): + """Wrapper class of threading.Lock(), which is allowed by 'with'.""" + + def __new__(cls): + self = object.__new__(cls) + self._lock = threading.Lock() # pylint: disable=protected-access + return self + + def __enter__(self): + self._lock.acquire() + + def __exit__(self, exc_type, exc_value, exc_tb): + self._lock.release() + + +_lock = threading.Lock() + + +def _Deprecated(name): + if _Deprecated.count > 0: + _Deprecated.count -= 1 + warnings.warn( + 'Call to deprecated create function %s(). Note: Create unlinked ' + 'descriptors is going to go away. Please use get/find descriptors from ' + 'generated code or query the descriptor_pool.' + % name, + category=DeprecationWarning, stacklevel=3) + + +# Deprecated warnings will print 100 times at most which should be enough for +# users to notice and do not cause timeout. +_Deprecated.count = 100 + + +_internal_create_key = object() + + +class DescriptorBase(metaclass=DescriptorMetaclass): + + """Descriptors base class. + + This class is the base of all descriptor classes. It provides common options + related functionality. + + Attributes: + has_options: True if the descriptor has non-default options. Usually it + is not necessary to read this -- just call GetOptions() which will + happily return the default instance. However, it's sometimes useful + for efficiency, and also useful inside the protobuf implementation to + avoid some bootstrapping issues. + """ + + if _USE_C_DESCRIPTORS: + # The class, or tuple of classes, that are considered as "virtual + # subclasses" of this descriptor class. + _C_DESCRIPTOR_CLASS = () + + def __init__(self, options, serialized_options, options_class_name): + """Initialize the descriptor given its options message and the name of the + class of the options message. The name of the class is required in case + the options message is None and has to be created. + """ + self._options = options + self._options_class_name = options_class_name + self._serialized_options = serialized_options + + # Does this descriptor have non-default options? + self.has_options = (options is not None) or (serialized_options is not None) + + def _SetOptions(self, options, options_class_name): + """Sets the descriptor's options + + This function is used in generated proto2 files to update descriptor + options. It must not be used outside proto2. + """ + self._options = options + self._options_class_name = options_class_name + + # Does this descriptor have non-default options? + self.has_options = options is not None + + def GetOptions(self): + """Retrieves descriptor options. + + This method returns the options set or creates the default options for the + descriptor. + """ + if self._options: + return self._options + + from google.protobuf import descriptor_pb2 + try: + options_class = getattr(descriptor_pb2, + self._options_class_name) + except AttributeError: + raise RuntimeError('Unknown options class name %s!' % + (self._options_class_name)) + + with _lock: + if self._serialized_options is None: + self._options = options_class() + else: + self._options = _ParseOptions(options_class(), + self._serialized_options) + + return self._options + + +class _NestedDescriptorBase(DescriptorBase): + """Common class for descriptors that can be nested.""" + + def __init__(self, options, options_class_name, name, full_name, + file, containing_type, serialized_start=None, + serialized_end=None, serialized_options=None): + """Constructor. + + Args: + options: Protocol message options or None + to use default message options. + options_class_name (str): The class name of the above options. + name (str): Name of this protocol message type. + full_name (str): Fully-qualified name of this protocol message type, + which will include protocol "package" name and the name of any + enclosing types. + file (FileDescriptor): Reference to file info. + containing_type: if provided, this is a nested descriptor, with this + descriptor as parent, otherwise None. + serialized_start: The start index (inclusive) in block in the + file.serialized_pb that describes this descriptor. + serialized_end: The end index (exclusive) in block in the + file.serialized_pb that describes this descriptor. + serialized_options: Protocol message serialized options or None. + """ + super(_NestedDescriptorBase, self).__init__( + options, serialized_options, options_class_name) + + self.name = name + # TODO(falk): Add function to calculate full_name instead of having it in + # memory? + self.full_name = full_name + self.file = file + self.containing_type = containing_type + + self._serialized_start = serialized_start + self._serialized_end = serialized_end + + def CopyToProto(self, proto): + """Copies this to the matching proto in descriptor_pb2. + + Args: + proto: An empty proto instance from descriptor_pb2. + + Raises: + Error: If self couldn't be serialized, due to to few constructor + arguments. + """ + if (self.file is not None and + self._serialized_start is not None and + self._serialized_end is not None): + proto.ParseFromString(self.file.serialized_pb[ + self._serialized_start:self._serialized_end]) + else: + raise Error('Descriptor does not contain serialization.') + + +class Descriptor(_NestedDescriptorBase): + + """Descriptor for a protocol message type. + + Attributes: + name (str): Name of this protocol message type. + full_name (str): Fully-qualified name of this protocol message type, + which will include protocol "package" name and the name of any + enclosing types. + containing_type (Descriptor): Reference to the descriptor of the type + containing us, or None if this is top-level. + fields (list[FieldDescriptor]): Field descriptors for all fields in + this type. + fields_by_number (dict(int, FieldDescriptor)): Same + :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed + by "number" attribute in each FieldDescriptor. + fields_by_name (dict(str, FieldDescriptor)): Same + :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by + "name" attribute in each :class:`FieldDescriptor`. + nested_types (list[Descriptor]): Descriptor references + for all protocol message types nested within this one. + nested_types_by_name (dict(str, Descriptor)): Same Descriptor + objects as in :attr:`nested_types`, but indexed by "name" attribute + in each Descriptor. + enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references + for all enums contained within this type. + enum_types_by_name (dict(str, EnumDescriptor)): Same + :class:`EnumDescriptor` objects as in :attr:`enum_types`, but + indexed by "name" attribute in each EnumDescriptor. + enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping + from enum value name to :class:`EnumValueDescriptor` for that value. + extensions (list[FieldDescriptor]): All extensions defined directly + within this message type (NOT within a nested type). + extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor + objects as :attr:`extensions`, but indexed by "name" attribute of each + FieldDescriptor. + is_extendable (bool): Does this type define any extension ranges? + oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields + in this message. + oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in + :attr:`oneofs`, but indexed by "name" attribute. + file (FileDescriptor): Reference to file descriptor. + + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.Descriptor + + def __new__( + cls, + name=None, + full_name=None, + filename=None, + containing_type=None, + fields=None, + nested_types=None, + enum_types=None, + extensions=None, + options=None, + serialized_options=None, + is_extendable=True, + extension_ranges=None, + oneofs=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + syntax=None, + create_key=None): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindMessageTypeByName(full_name) + + # NOTE(tmarek): The file argument redefining a builtin is nothing we can + # fix right now since we don't know how many clients already rely on the + # name of the argument. + def __init__(self, name, full_name, filename, containing_type, fields, + nested_types, enum_types, extensions, options=None, + serialized_options=None, + is_extendable=True, extension_ranges=None, oneofs=None, + file=None, serialized_start=None, serialized_end=None, # pylint: disable=redefined-builtin + syntax=None, create_key=None): + """Arguments to __init__() are as described in the description + of Descriptor fields above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + if create_key is not _internal_create_key: + _Deprecated('Descriptor') + + super(Descriptor, self).__init__( + options, 'MessageOptions', name, full_name, file, + containing_type, serialized_start=serialized_start, + serialized_end=serialized_end, serialized_options=serialized_options) + + # We have fields in addition to fields_by_name and fields_by_number, + # so that: + # 1. Clients can index fields by "order in which they're listed." + # 2. Clients can easily iterate over all fields with the terse + # syntax: for f in descriptor.fields: ... + self.fields = fields + for field in self.fields: + field.containing_type = self + self.fields_by_number = dict((f.number, f) for f in fields) + self.fields_by_name = dict((f.name, f) for f in fields) + self._fields_by_camelcase_name = None + + self.nested_types = nested_types + for nested_type in nested_types: + nested_type.containing_type = self + self.nested_types_by_name = dict((t.name, t) for t in nested_types) + + self.enum_types = enum_types + for enum_type in self.enum_types: + enum_type.containing_type = self + self.enum_types_by_name = dict((t.name, t) for t in enum_types) + self.enum_values_by_name = dict( + (v.name, v) for t in enum_types for v in t.values) + + self.extensions = extensions + for extension in self.extensions: + extension.extension_scope = self + self.extensions_by_name = dict((f.name, f) for f in extensions) + self.is_extendable = is_extendable + self.extension_ranges = extension_ranges + self.oneofs = oneofs if oneofs is not None else [] + self.oneofs_by_name = dict((o.name, o) for o in self.oneofs) + for oneof in self.oneofs: + oneof.containing_type = self + self.syntax = syntax or "proto2" + + @property + def fields_by_camelcase_name(self): + """Same FieldDescriptor objects as in :attr:`fields`, but indexed by + :attr:`FieldDescriptor.camelcase_name`. + """ + if self._fields_by_camelcase_name is None: + self._fields_by_camelcase_name = dict( + (f.camelcase_name, f) for f in self.fields) + return self._fields_by_camelcase_name + + def EnumValueName(self, enum, value): + """Returns the string name of an enum value. + + This is just a small helper method to simplify a common operation. + + Args: + enum: string name of the Enum. + value: int, value of the enum. + + Returns: + string name of the enum value. + + Raises: + KeyError if either the Enum doesn't exist or the value is not a valid + value for the enum. + """ + return self.enum_types_by_name[enum].values_by_number[value].name + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.DescriptorProto. + + Args: + proto: An empty descriptor_pb2.DescriptorProto. + """ + # This function is overridden to give a better doc comment. + super(Descriptor, self).CopyToProto(proto) + + +# TODO(robinson): We should have aggressive checking here, +# for example: +# * If you specify a repeated field, you should not be allowed +# to specify a default value. +# * [Other examples here as needed]. +# +# TODO(robinson): for this and other *Descriptor classes, we +# might also want to lock things down aggressively (e.g., +# prevent clients from setting the attributes). Having +# stronger invariants here in general will reduce the number +# of runtime checks we must do in reflection.py... +class FieldDescriptor(DescriptorBase): + + """Descriptor for a single field in a .proto file. + + Attributes: + name (str): Name of this field, exactly as it appears in .proto. + full_name (str): Name of this field, including containing scope. This is + particularly relevant for extensions. + index (int): Dense, 0-indexed index giving the order that this + field textually appears within its message in the .proto file. + number (int): Tag number declared for this field in the .proto file. + + type (int): (One of the TYPE_* constants below) Declared type. + cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to + represent this field. + + label (int): (One of the LABEL_* constants below) Tells whether this + field is optional, required, or repeated. + has_default_value (bool): True if this field has a default value defined, + otherwise false. + default_value (Varies): Default value of this field. Only + meaningful for non-repeated scalar fields. Repeated fields + should always set this to [], and non-repeated composite + fields should always set this to None. + + containing_type (Descriptor): Descriptor of the protocol message + type that contains this field. Set by the Descriptor constructor + if we're passed into one. + Somewhat confusingly, for extension fields, this is the + descriptor of the EXTENDED message, not the descriptor + of the message containing this field. (See is_extension and + extension_scope below). + message_type (Descriptor): If a composite field, a descriptor + of the message type contained in this field. Otherwise, this is None. + enum_type (EnumDescriptor): If this field contains an enum, a + descriptor of that enum. Otherwise, this is None. + + is_extension: True iff this describes an extension field. + extension_scope (Descriptor): Only meaningful if is_extension is True. + Gives the message that immediately contains this extension field. + Will be None iff we're a top-level (file-level) extension field. + + options (descriptor_pb2.FieldOptions): Protocol message field options or + None to use default field options. + + containing_oneof (OneofDescriptor): If the field is a member of a oneof + union, contains its descriptor. Otherwise, None. + + file (FileDescriptor): Reference to file descriptor. + """ + + # Must be consistent with C++ FieldDescriptor::Type enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + TYPE_DOUBLE = 1 + TYPE_FLOAT = 2 + TYPE_INT64 = 3 + TYPE_UINT64 = 4 + TYPE_INT32 = 5 + TYPE_FIXED64 = 6 + TYPE_FIXED32 = 7 + TYPE_BOOL = 8 + TYPE_STRING = 9 + TYPE_GROUP = 10 + TYPE_MESSAGE = 11 + TYPE_BYTES = 12 + TYPE_UINT32 = 13 + TYPE_ENUM = 14 + TYPE_SFIXED32 = 15 + TYPE_SFIXED64 = 16 + TYPE_SINT32 = 17 + TYPE_SINT64 = 18 + MAX_TYPE = 18 + + # Must be consistent with C++ FieldDescriptor::CppType enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + CPPTYPE_INT32 = 1 + CPPTYPE_INT64 = 2 + CPPTYPE_UINT32 = 3 + CPPTYPE_UINT64 = 4 + CPPTYPE_DOUBLE = 5 + CPPTYPE_FLOAT = 6 + CPPTYPE_BOOL = 7 + CPPTYPE_ENUM = 8 + CPPTYPE_STRING = 9 + CPPTYPE_MESSAGE = 10 + MAX_CPPTYPE = 10 + + _PYTHON_TO_CPP_PROTO_TYPE_MAP = { + TYPE_DOUBLE: CPPTYPE_DOUBLE, + TYPE_FLOAT: CPPTYPE_FLOAT, + TYPE_ENUM: CPPTYPE_ENUM, + TYPE_INT64: CPPTYPE_INT64, + TYPE_SINT64: CPPTYPE_INT64, + TYPE_SFIXED64: CPPTYPE_INT64, + TYPE_UINT64: CPPTYPE_UINT64, + TYPE_FIXED64: CPPTYPE_UINT64, + TYPE_INT32: CPPTYPE_INT32, + TYPE_SFIXED32: CPPTYPE_INT32, + TYPE_SINT32: CPPTYPE_INT32, + TYPE_UINT32: CPPTYPE_UINT32, + TYPE_FIXED32: CPPTYPE_UINT32, + TYPE_BYTES: CPPTYPE_STRING, + TYPE_STRING: CPPTYPE_STRING, + TYPE_BOOL: CPPTYPE_BOOL, + TYPE_MESSAGE: CPPTYPE_MESSAGE, + TYPE_GROUP: CPPTYPE_MESSAGE + } + + # Must be consistent with C++ FieldDescriptor::Label enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + LABEL_OPTIONAL = 1 + LABEL_REQUIRED = 2 + LABEL_REPEATED = 3 + MAX_LABEL = 3 + + # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber, + # and kLastReservedNumber in descriptor.h + MAX_FIELD_NUMBER = (1 << 29) - 1 + FIRST_RESERVED_FIELD_NUMBER = 19000 + LAST_RESERVED_FIELD_NUMBER = 19999 + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.FieldDescriptor + + def __new__(cls, name, full_name, index, number, type, cpp_type, label, + default_value, message_type, enum_type, containing_type, + is_extension, extension_scope, options=None, + serialized_options=None, + has_default_value=True, containing_oneof=None, json_name=None, + file=None, create_key=None): # pylint: disable=redefined-builtin + _message.Message._CheckCalledFromGeneratedFile() + if is_extension: + return _message.default_pool.FindExtensionByName(full_name) + else: + return _message.default_pool.FindFieldByName(full_name) + + def __init__(self, name, full_name, index, number, type, cpp_type, label, + default_value, message_type, enum_type, containing_type, + is_extension, extension_scope, options=None, + serialized_options=None, + has_default_value=True, containing_oneof=None, json_name=None, + file=None, create_key=None): # pylint: disable=redefined-builtin + """The arguments are as described in the description of FieldDescriptor + attributes above. + + Note that containing_type may be None, and may be set later if necessary + (to deal with circular references between message types, for example). + Likewise for extension_scope. + """ + if create_key is not _internal_create_key: + _Deprecated('FieldDescriptor') + + super(FieldDescriptor, self).__init__( + options, serialized_options, 'FieldOptions') + self.name = name + self.full_name = full_name + self.file = file + self._camelcase_name = None + if json_name is None: + self.json_name = _ToJsonName(name) + else: + self.json_name = json_name + self.index = index + self.number = number + self.type = type + self.cpp_type = cpp_type + self.label = label + self.has_default_value = has_default_value + self.default_value = default_value + self.containing_type = containing_type + self.message_type = message_type + self.enum_type = enum_type + self.is_extension = is_extension + self.extension_scope = extension_scope + self.containing_oneof = containing_oneof + if api_implementation.Type() == 'cpp': + if is_extension: + self._cdescriptor = _message.default_pool.FindExtensionByName(full_name) + else: + self._cdescriptor = _message.default_pool.FindFieldByName(full_name) + else: + self._cdescriptor = None + + @property + def camelcase_name(self): + """Camelcase name of this field. + + Returns: + str: the name in CamelCase. + """ + if self._camelcase_name is None: + self._camelcase_name = _ToCamelCase(self.name) + return self._camelcase_name + + @property + def has_presence(self): + """Whether the field distinguishes between unpopulated and default values. + + Raises: + RuntimeError: singular field that is not linked with message nor file. + """ + if self.label == FieldDescriptor.LABEL_REPEATED: + return False + if (self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE or + self.containing_oneof): + return True + if hasattr(self.file, 'syntax'): + return self.file.syntax == 'proto2' + if hasattr(self.message_type, 'syntax'): + return self.message_type.syntax == 'proto2' + raise RuntimeError( + 'has_presence is not ready to use because field %s is not' + ' linked with message type nor file' % self.full_name) + + @staticmethod + def ProtoTypeToCppProtoType(proto_type): + """Converts from a Python proto type to a C++ Proto Type. + + The Python ProtocolBuffer classes specify both the 'Python' datatype and the + 'C++' datatype - and they're not the same. This helper method should + translate from one to another. + + Args: + proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) + Returns: + int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. + Raises: + TypeTransformationError: when the Python proto type isn't known. + """ + try: + return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] + except KeyError: + raise TypeTransformationError('Unknown proto_type: %s' % proto_type) + + +class EnumDescriptor(_NestedDescriptorBase): + + """Descriptor for an enum defined in a .proto file. + + Attributes: + name (str): Name of the enum type. + full_name (str): Full name of the type, including package name + and any enclosing type(s). + + values (list[EnumValueDescriptor]): List of the values + in this enum. + values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`, + but indexed by the "name" field of each EnumValueDescriptor. + values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`, + but indexed by the "number" field of each EnumValueDescriptor. + containing_type (Descriptor): Descriptor of the immediate containing + type of this enum, or None if this is an enum defined at the + top level in a .proto file. Set by Descriptor's constructor + if we're passed into one. + file (FileDescriptor): Reference to file descriptor. + options (descriptor_pb2.EnumOptions): Enum options message or + None to use default enum options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.EnumDescriptor + + def __new__(cls, name, full_name, filename, values, + containing_type=None, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin + serialized_start=None, serialized_end=None, create_key=None): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindEnumTypeByName(full_name) + + def __init__(self, name, full_name, filename, values, + containing_type=None, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin + serialized_start=None, serialized_end=None, create_key=None): + """Arguments are as described in the attribute description above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + if create_key is not _internal_create_key: + _Deprecated('EnumDescriptor') + + super(EnumDescriptor, self).__init__( + options, 'EnumOptions', name, full_name, file, + containing_type, serialized_start=serialized_start, + serialized_end=serialized_end, serialized_options=serialized_options) + + self.values = values + for value in self.values: + value.type = self + self.values_by_name = dict((v.name, v) for v in values) + # Values are reversed to ensure that the first alias is retained. + self.values_by_number = dict((v.number, v) for v in reversed(values)) + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.EnumDescriptorProto. + + Args: + proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto. + """ + # This function is overridden to give a better doc comment. + super(EnumDescriptor, self).CopyToProto(proto) + + +class EnumValueDescriptor(DescriptorBase): + + """Descriptor for a single value within an enum. + + Attributes: + name (str): Name of this value. + index (int): Dense, 0-indexed index giving the order that this + value appears textually within its enum in the .proto file. + number (int): Actual number assigned to this enum value. + type (EnumDescriptor): :class:`EnumDescriptor` to which this value + belongs. Set by :class:`EnumDescriptor`'s constructor if we're + passed into one. + options (descriptor_pb2.EnumValueOptions): Enum value options message or + None to use default enum value options options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor + + def __new__(cls, name, index, number, + type=None, # pylint: disable=redefined-builtin + options=None, serialized_options=None, create_key=None): + _message.Message._CheckCalledFromGeneratedFile() + # There is no way we can build a complete EnumValueDescriptor with the + # given parameters (the name of the Enum is not known, for example). + # Fortunately generated files just pass it to the EnumDescriptor() + # constructor, which will ignore it, so returning None is good enough. + return None + + def __init__(self, name, index, number, + type=None, # pylint: disable=redefined-builtin + options=None, serialized_options=None, create_key=None): + """Arguments are as described in the attribute description above.""" + if create_key is not _internal_create_key: + _Deprecated('EnumValueDescriptor') + + super(EnumValueDescriptor, self).__init__( + options, serialized_options, 'EnumValueOptions') + self.name = name + self.index = index + self.number = number + self.type = type + + +class OneofDescriptor(DescriptorBase): + """Descriptor for a oneof field. + + Attributes: + name (str): Name of the oneof field. + full_name (str): Full name of the oneof field, including package name. + index (int): 0-based index giving the order of the oneof field inside + its containing type. + containing_type (Descriptor): :class:`Descriptor` of the protocol message + type that contains this field. Set by the :class:`Descriptor` constructor + if we're passed into one. + fields (list[FieldDescriptor]): The list of field descriptors this + oneof can contain. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.OneofDescriptor + + def __new__( + cls, name, full_name, index, containing_type, fields, options=None, + serialized_options=None, create_key=None): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindOneofByName(full_name) + + def __init__( + self, name, full_name, index, containing_type, fields, options=None, + serialized_options=None, create_key=None): + """Arguments are as described in the attribute description above.""" + if create_key is not _internal_create_key: + _Deprecated('OneofDescriptor') + + super(OneofDescriptor, self).__init__( + options, serialized_options, 'OneofOptions') + self.name = name + self.full_name = full_name + self.index = index + self.containing_type = containing_type + self.fields = fields + + +class ServiceDescriptor(_NestedDescriptorBase): + + """Descriptor for a service. + + Attributes: + name (str): Name of the service. + full_name (str): Full name of the service, including package name. + index (int): 0-indexed index giving the order that this services + definition appears within the .proto file. + methods (list[MethodDescriptor]): List of methods provided by this + service. + methods_by_name (dict(str, MethodDescriptor)): Same + :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but + indexed by "name" attribute in each :class:`MethodDescriptor`. + options (descriptor_pb2.ServiceOptions): Service options message or + None to use default service options. + file (FileDescriptor): Reference to file info. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor + + def __new__( + cls, + name=None, + full_name=None, + index=None, + methods=None, + options=None, + serialized_options=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + create_key=None): + _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access + return _message.default_pool.FindServiceByName(full_name) + + def __init__(self, name, full_name, index, methods, options=None, + serialized_options=None, file=None, # pylint: disable=redefined-builtin + serialized_start=None, serialized_end=None, create_key=None): + if create_key is not _internal_create_key: + _Deprecated('ServiceDescriptor') + + super(ServiceDescriptor, self).__init__( + options, 'ServiceOptions', name, full_name, file, + None, serialized_start=serialized_start, + serialized_end=serialized_end, serialized_options=serialized_options) + self.index = index + self.methods = methods + self.methods_by_name = dict((m.name, m) for m in methods) + # Set the containing service for each method in this service. + for method in self.methods: + method.containing_service = self + + def FindMethodByName(self, name): + """Searches for the specified method, and returns its descriptor. + + Args: + name (str): Name of the method. + Returns: + MethodDescriptor or None: the descriptor for the requested method, if + found. + """ + return self.methods_by_name.get(name, None) + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.ServiceDescriptorProto. + + Args: + proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto. + """ + # This function is overridden to give a better doc comment. + super(ServiceDescriptor, self).CopyToProto(proto) + + +class MethodDescriptor(DescriptorBase): + + """Descriptor for a method in a service. + + Attributes: + name (str): Name of the method within the service. + full_name (str): Full name of method. + index (int): 0-indexed index of the method inside the service. + containing_service (ServiceDescriptor): The service that contains this + method. + input_type (Descriptor): The descriptor of the message that this method + accepts. + output_type (Descriptor): The descriptor of the message that this method + returns. + client_streaming (bool): Whether this method uses client streaming. + server_streaming (bool): Whether this method uses server streaming. + options (descriptor_pb2.MethodOptions or None): Method options message, or + None to use default method options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.MethodDescriptor + + def __new__(cls, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None): + _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access + return _message.default_pool.FindMethodByName(full_name) + + def __init__(self, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None): + """The arguments are as described in the description of MethodDescriptor + attributes above. + + Note that containing_service may be None, and may be set later if necessary. + """ + if create_key is not _internal_create_key: + _Deprecated('MethodDescriptor') + + super(MethodDescriptor, self).__init__( + options, serialized_options, 'MethodOptions') + self.name = name + self.full_name = full_name + self.index = index + self.containing_service = containing_service + self.input_type = input_type + self.output_type = output_type + self.client_streaming = client_streaming + self.server_streaming = server_streaming + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.MethodDescriptorProto. + + Args: + proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto. + + Raises: + Error: If self couldn't be serialized, due to too few constructor + arguments. + """ + if self.containing_service is not None: + from google.protobuf import descriptor_pb2 + service_proto = descriptor_pb2.ServiceDescriptorProto() + self.containing_service.CopyToProto(service_proto) + proto.CopyFrom(service_proto.method[self.index]) + else: + raise Error('Descriptor does not contain a service.') + + +class FileDescriptor(DescriptorBase): + """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto. + + Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and + :attr:`dependencies` fields are only set by the + :py:mod:`google.protobuf.message_factory` module, and not by the generated + proto code. + + Attributes: + name (str): Name of file, relative to root of source tree. + package (str): Name of the package + syntax (str): string indicating syntax of the file (can be "proto2" or + "proto3") + serialized_pb (bytes): Byte string of serialized + :class:`descriptor_pb2.FileDescriptorProto`. + dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor` + objects this :class:`FileDescriptor` depends on. + public_dependencies (list[FileDescriptor]): A subset of + :attr:`dependencies`, which were declared as "public". + message_types_by_name (dict(str, Descriptor)): Mapping from message names + to their :class:`Descriptor`. + enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to + their :class:`EnumDescriptor`. + extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension + names declared at file scope to their :class:`FieldDescriptor`. + services_by_name (dict(str, ServiceDescriptor)): Mapping from services' + names to their :class:`ServiceDescriptor`. + pool (DescriptorPool): The pool this descriptor belongs to. When not + passed to the constructor, the global default pool is used. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.FileDescriptor + + def __new__(cls, name, package, options=None, + serialized_options=None, serialized_pb=None, + dependencies=None, public_dependencies=None, + syntax=None, pool=None, create_key=None): + # FileDescriptor() is called from various places, not only from generated + # files, to register dynamic proto files and messages. + # pylint: disable=g-explicit-bool-comparison + if serialized_pb == b'': + # Cpp generated code must be linked in if serialized_pb is '' + try: + return _message.default_pool.FindFileByName(name) + except KeyError: + raise RuntimeError('Please link in cpp generated lib for %s' % (name)) + elif serialized_pb: + return _message.default_pool.AddSerializedFile(serialized_pb) + else: + return super(FileDescriptor, cls).__new__(cls) + + def __init__(self, name, package, options=None, + serialized_options=None, serialized_pb=None, + dependencies=None, public_dependencies=None, + syntax=None, pool=None, create_key=None): + """Constructor.""" + if create_key is not _internal_create_key: + _Deprecated('FileDescriptor') + + super(FileDescriptor, self).__init__( + options, serialized_options, 'FileOptions') + + if pool is None: + from google.protobuf import descriptor_pool + pool = descriptor_pool.Default() + self.pool = pool + self.message_types_by_name = {} + self.name = name + self.package = package + self.syntax = syntax or "proto2" + self.serialized_pb = serialized_pb + + self.enum_types_by_name = {} + self.extensions_by_name = {} + self.services_by_name = {} + self.dependencies = (dependencies or []) + self.public_dependencies = (public_dependencies or []) + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.FileDescriptorProto. + + Args: + proto: An empty descriptor_pb2.FileDescriptorProto. + """ + proto.ParseFromString(self.serialized_pb) + + +def _ParseOptions(message, string): + """Parses serialized options. + + This helper function is used to parse serialized options in generated + proto2 files. It must not be used outside proto2. + """ + message.ParseFromString(string) + return message + + +def _ToCamelCase(name): + """Converts name to camel-case and returns it.""" + capitalize_next = False + result = [] + + for c in name: + if c == '_': + if result: + capitalize_next = True + elif capitalize_next: + result.append(c.upper()) + capitalize_next = False + else: + result += c + + # Lower-case the first letter. + if result and result[0].isupper(): + result[0] = result[0].lower() + return ''.join(result) + + +def _OptionsOrNone(descriptor_proto): + """Returns the value of the field `options`, or None if it is not set.""" + if descriptor_proto.HasField('options'): + return descriptor_proto.options + else: + return None + + +def _ToJsonName(name): + """Converts name to Json name and returns it.""" + capitalize_next = False + result = [] + + for c in name: + if c == '_': + capitalize_next = True + elif capitalize_next: + result.append(c.upper()) + capitalize_next = False + else: + result += c + + return ''.join(result) + + +def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, + syntax=None): + """Make a protobuf Descriptor given a DescriptorProto protobuf. + + Handles nested descriptors. Note that this is limited to the scope of defining + a message inside of another message. Composite fields can currently only be + resolved if the message is defined in the same scope as the field. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: Optional package name for the new message Descriptor (string). + build_file_if_cpp: Update the C++ descriptor pool if api matches. + Set to False on recursion, so no duplicates are created. + syntax: The syntax/semantics that should be used. Set to "proto3" to get + proto3 field presence semantics. + Returns: + A Descriptor for protobuf messages. + """ + if api_implementation.Type() == 'cpp' and build_file_if_cpp: + # The C++ implementation requires all descriptors to be backed by the same + # definition in the C++ descriptor pool. To do this, we build a + # FileDescriptorProto with the same definition as this descriptor and build + # it into the pool. + from google.protobuf import descriptor_pb2 + file_descriptor_proto = descriptor_pb2.FileDescriptorProto() + file_descriptor_proto.message_type.add().MergeFrom(desc_proto) + + # Generate a random name for this proto file to prevent conflicts with any + # imported ones. We need to specify a file name so the descriptor pool + # accepts our FileDescriptorProto, but it is not important what that file + # name is actually set to. + proto_name = binascii.hexlify(os.urandom(16)).decode('ascii') + + if package: + file_descriptor_proto.name = os.path.join(package.replace('.', '/'), + proto_name + '.proto') + file_descriptor_proto.package = package + else: + file_descriptor_proto.name = proto_name + '.proto' + + _message.default_pool.Add(file_descriptor_proto) + result = _message.default_pool.FindFileByName(file_descriptor_proto.name) + + if _USE_C_DESCRIPTORS: + return result.message_types_by_name[desc_proto.name] + + full_message_name = [desc_proto.name] + if package: full_message_name.insert(0, package) + + # Create Descriptors for enum types + enum_types = {} + for enum_proto in desc_proto.enum_type: + full_name = '.'.join(full_message_name + [enum_proto.name]) + enum_desc = EnumDescriptor( + enum_proto.name, full_name, None, [ + EnumValueDescriptor(enum_val.name, ii, enum_val.number, + create_key=_internal_create_key) + for ii, enum_val in enumerate(enum_proto.value)], + create_key=_internal_create_key) + enum_types[full_name] = enum_desc + + # Create Descriptors for nested types + nested_types = {} + for nested_proto in desc_proto.nested_type: + full_name = '.'.join(full_message_name + [nested_proto.name]) + # Nested types are just those defined inside of the message, not all types + # used by fields in the message, so no loops are possible here. + nested_desc = MakeDescriptor(nested_proto, + package='.'.join(full_message_name), + build_file_if_cpp=False, + syntax=syntax) + nested_types[full_name] = nested_desc + + fields = [] + for field_proto in desc_proto.field: + full_name = '.'.join(full_message_name + [field_proto.name]) + enum_desc = None + nested_desc = None + if field_proto.json_name: + json_name = field_proto.json_name + else: + json_name = None + if field_proto.HasField('type_name'): + type_name = field_proto.type_name + full_type_name = '.'.join(full_message_name + + [type_name[type_name.rfind('.')+1:]]) + if full_type_name in nested_types: + nested_desc = nested_types[full_type_name] + elif full_type_name in enum_types: + enum_desc = enum_types[full_type_name] + # Else type_name references a non-local type, which isn't implemented + field = FieldDescriptor( + field_proto.name, full_name, field_proto.number - 1, + field_proto.number, field_proto.type, + FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), + field_proto.label, None, nested_desc, enum_desc, None, False, None, + options=_OptionsOrNone(field_proto), has_default_value=False, + json_name=json_name, create_key=_internal_create_key) + fields.append(field) + + desc_name = '.'.join(full_message_name) + return Descriptor(desc_proto.name, desc_name, None, None, fields, + list(nested_types.values()), list(enum_types.values()), [], + options=_OptionsOrNone(desc_proto), + create_key=_internal_create_key) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_database.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_database.py new file mode 100644 index 0000000000000000000000000000000000000000..073eddc711571a7f510ff8b189e2a9a863d53454 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_database.py @@ -0,0 +1,177 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides a container for DescriptorProtos.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import warnings + + +class Error(Exception): + pass + + +class DescriptorDatabaseConflictingDefinitionError(Error): + """Raised when a proto is added with the same name & different descriptor.""" + + +class DescriptorDatabase(object): + """A container accepting FileDescriptorProtos and maps DescriptorProtos.""" + + def __init__(self): + self._file_desc_protos_by_file = {} + self._file_desc_protos_by_symbol = {} + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this database. + + Args: + file_desc_proto: The FileDescriptorProto to add. + Raises: + DescriptorDatabaseConflictingDefinitionError: if an attempt is made to + add a proto with the same name but different definition than an + existing proto in the database. + """ + proto_name = file_desc_proto.name + if proto_name not in self._file_desc_protos_by_file: + self._file_desc_protos_by_file[proto_name] = file_desc_proto + elif self._file_desc_protos_by_file[proto_name] != file_desc_proto: + raise DescriptorDatabaseConflictingDefinitionError( + '%s already added, but with different descriptor.' % proto_name) + else: + return + + # Add all the top-level descriptors to the index. + package = file_desc_proto.package + for message in file_desc_proto.message_type: + for name in _ExtractSymbols(message, package): + self._AddSymbol(name, file_desc_proto) + for enum in file_desc_proto.enum_type: + self._AddSymbol(('.'.join((package, enum.name))), file_desc_proto) + for enum_value in enum.value: + self._file_desc_protos_by_symbol[ + '.'.join((package, enum_value.name))] = file_desc_proto + for extension in file_desc_proto.extension: + self._AddSymbol(('.'.join((package, extension.name))), file_desc_proto) + for service in file_desc_proto.service: + self._AddSymbol(('.'.join((package, service.name))), file_desc_proto) + + def FindFileByName(self, name): + """Finds the file descriptor proto by file name. + + Typically the file name is a relative path ending to a .proto file. The + proto with the given name will have to have been added to this database + using the Add method or else an error will be raised. + + Args: + name: The file name to find. + + Returns: + The file descriptor proto matching the name. + + Raises: + KeyError if no file by the given name was added. + """ + + return self._file_desc_protos_by_file[name] + + def FindFileContainingSymbol(self, symbol): + """Finds the file descriptor proto containing the specified symbol. + + The symbol should be a fully qualified name including the file descriptor's + package and any containing messages. Some examples: + + 'some.package.name.Message' + 'some.package.name.Message.NestedEnum' + 'some.package.name.Message.some_field' + + The file descriptor proto containing the specified symbol must be added to + this database using the Add method or else an error will be raised. + + Args: + symbol: The fully qualified symbol name. + + Returns: + The file descriptor proto containing the symbol. + + Raises: + KeyError if no file contains the specified symbol. + """ + try: + return self._file_desc_protos_by_symbol[symbol] + except KeyError: + # Fields, enum values, and nested extensions are not in + # _file_desc_protos_by_symbol. Try to find the top level + # descriptor. Non-existent nested symbol under a valid top level + # descriptor can also be found. The behavior is the same with + # protobuf C++. + top_level, _, _ = symbol.rpartition('.') + try: + return self._file_desc_protos_by_symbol[top_level] + except KeyError: + # Raise the original symbol as a KeyError for better diagnostics. + raise KeyError(symbol) + + def FindFileContainingExtension(self, extendee_name, extension_number): + # TODO(jieluo): implement this API. + return None + + def FindAllExtensionNumbers(self, extendee_name): + # TODO(jieluo): implement this API. + return [] + + def _AddSymbol(self, name, file_desc_proto): + if name in self._file_desc_protos_by_symbol: + warn_msg = ('Conflict register for file "' + file_desc_proto.name + + '": ' + name + + ' is already defined in file "' + + self._file_desc_protos_by_symbol[name].name + '"') + warnings.warn(warn_msg, RuntimeWarning) + self._file_desc_protos_by_symbol[name] = file_desc_proto + + +def _ExtractSymbols(desc_proto, package): + """Pulls out all the symbols from a descriptor proto. + + Args: + desc_proto: The proto to extract symbols from. + package: The package containing the descriptor type. + + Yields: + The fully qualified name found in the descriptor. + """ + message_name = package + '.' + desc_proto.name if package else desc_proto.name + yield message_name + for nested_type in desc_proto.nested_type: + for symbol in _ExtractSymbols(nested_type, message_name): + yield symbol + for enum_type in desc_proto.enum_type: + yield '.'.join((message_name, enum_type.name)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..f57038643260fb13b70705c7f807a465f1f1129b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pb2.py @@ -0,0 +1,1925 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/descriptor.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/descriptor.proto', + package='google.protobuf', + syntax='proto2', + serialized_options=None, + create_key=_descriptor._internal_create_key, + serialized_pb=b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_outer_classname\x18\x08 \x01(\t\x12\"\n\x13java_multiple_files\x18\n \x01(\x08:\x05\x66\x61lse\x12)\n\x1djava_generate_equals_and_hash\x18\x14 \x01(\x08\x42\x02\x18\x01\x12%\n\x16java_string_check_utf8\x18\x1b \x01(\x08:\x05\x66\x61lse\x12\x46\n\x0coptimize_for\x18\t \x01(\x0e\x32).google.protobuf.FileOptions.OptimizeMode:\x05SPEED\x12\x12\n\ngo_package\x18\x0b \x01(\t\x12\"\n\x13\x63\x63_generic_services\x18\x10 \x01(\x08:\x05\x66\x61lse\x12$\n\x15java_generic_services\x18\x11 \x01(\x08:\x05\x66\x61lse\x12\"\n\x13py_generic_services\x18\x12 \x01(\x08:\x05\x66\x61lse\x12#\n\x14php_generic_services\x18* \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x17 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x10\x63\x63_enable_arenas\x18\x1f \x01(\x08:\x04true\x12\x19\n\x11objc_class_prefix\x18$ \x01(\t\x12\x18\n\x10\x63sharp_namespace\x18% \x01(\t\x12\x14\n\x0cswift_prefix\x18\' \x01(\t\x12\x18\n\x10php_class_prefix\x18( \x01(\t\x12\x15\n\rphp_namespace\x18) \x01(\t\x12\x1e\n\x16php_metadata_namespace\x18, \x01(\t\x12\x14\n\x0cruby_package\x18- \x01(\t\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\":\n\x0cOptimizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08&\x10\'\"\x84\x02\n\x0eMessageOptions\x12&\n\x17message_set_wire_format\x18\x01 \x01(\x08:\x05\x66\x61lse\x12.\n\x1fno_standard_descriptor_accessor\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x11\n\tmap_entry\x18\x07 \x01(\x08\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xbe\x03\n\x0c\x46ieldOptions\x12:\n\x05\x63type\x18\x01 \x01(\x0e\x32#.google.protobuf.FieldOptions.CType:\x06STRING\x12\x0e\n\x06packed\x18\x02 \x01(\x08\x12?\n\x06jstype\x18\x06 \x01(\x0e\x32$.google.protobuf.FieldOptions.JSType:\tJS_NORMAL\x12\x13\n\x04lazy\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0funverified_lazy\x18\x0f \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04weak\x18\n \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\"/\n\x05\x43Type\x12\n\n\x06STRING\x10\x00\x12\x08\n\x04\x43ORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\x06JSType\x12\r\n\tJS_NORMAL\x10\x00\x12\r\n\tJS_STRING\x10\x01\x12\r\n\tJS_NUMBER\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05\"^\n\x0cOneofOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x93\x01\n\x0b\x45numOptions\x12\x13\n\x0b\x61llow_alias\x18\x02 \x01(\x08\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x05\x10\x06\"}\n\x10\x45numValueOptions\x12\x19\n\ndeprecated\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"{\n\x0eServiceOptions\x12\x19\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xad\x02\n\rMethodOptions\x12\x19\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lse\x12_\n\x11idempotency_level\x18\" \x01(\x0e\x32/.google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UNKNOWN\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\"P\n\x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\x00\x12\x13\n\x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9e\x02\n\x13UninterpretedOption\x12;\n\x04name\x18\x02 \x03(\x0b\x32-.google.protobuf.UninterpretedOption.NamePart\x12\x18\n\x10identifier_value\x18\x03 \x01(\t\x12\x1a\n\x12positive_int_value\x18\x04 \x01(\x04\x12\x1a\n\x12negative_int_value\x18\x05 \x01(\x03\x12\x14\n\x0c\x64ouble_value\x18\x06 \x01(\x01\x12\x14\n\x0cstring_value\x18\x07 \x01(\x0c\x12\x17\n\x0f\x61ggregate_value\x18\x08 \x01(\t\x1a\x33\n\x08NamePart\x12\x11\n\tname_part\x18\x01 \x02(\t\x12\x14\n\x0cis_extension\x18\x02 \x02(\x08\"\xd5\x01\n\x0eSourceCodeInfo\x12:\n\x08location\x18\x01 \x03(\x0b\x32(.google.protobuf.SourceCodeInfo.Location\x1a\x86\x01\n\x08Location\x12\x10\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01\x12\x10\n\x04span\x18\x02 \x03(\x05\x42\x02\x10\x01\x12\x18\n\x10leading_comments\x18\x03 \x01(\t\x12\x19\n\x11trailing_comments\x18\x04 \x01(\t\x12!\n\x19leading_detached_comments\x18\x06 \x03(\t\"\xa7\x01\n\x11GeneratedCodeInfo\x12\x41\n\nannotation\x18\x01 \x03(\x0b\x32-.google.protobuf.GeneratedCodeInfo.Annotation\x1aO\n\nAnnotation\x12\x10\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01\x12\x13\n\x0bsource_file\x18\x02 \x01(\t\x12\r\n\x05\x62\x65gin\x18\x03 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x04 \x01(\x05\x42~\n\x13\x63om.google.protobufB\x10\x44\x65scriptorProtosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.Reflection' + ) +else: + DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xdb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\x12\x0e\n\x06syntax\x18\x0c \x01(\t\"\xa9\x05\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x39\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProto\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x12\x46\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRange\x12\x15\n\rreserved_name\x18\n \x03(\t\x1a\x65\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\x12\x37\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptions\x1a+\n\rReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"g\n\x15\x45xtensionRangeOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12\x13\n\x0boneof_index\x18\t \x01(\x05\x12\x11\n\tjson_name\x18\n \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\x12\x17\n\x0fproto3_optional\x18\x11 \x01(\x08\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"T\n\x14OneofDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12.\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptions\"\xa4\x02\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\x12N\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRange\x12\x15\n\rreserved_name\x18\x05 \x03(\t\x1a/\n\x11\x45numReservedRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\xc1\x01\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\x12\x1f\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xa5\x06\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_outer_classname\x18\x08 \x01(\t\x12\"\n\x13java_multiple_files\x18\n \x01(\x08:\x05\x66\x61lse\x12)\n\x1djava_generate_equals_and_hash\x18\x14 \x01(\x08\x42\x02\x18\x01\x12%\n\x16java_string_check_utf8\x18\x1b \x01(\x08:\x05\x66\x61lse\x12\x46\n\x0coptimize_for\x18\t \x01(\x0e\x32).google.protobuf.FileOptions.OptimizeMode:\x05SPEED\x12\x12\n\ngo_package\x18\x0b \x01(\t\x12\"\n\x13\x63\x63_generic_services\x18\x10 \x01(\x08:\x05\x66\x61lse\x12$\n\x15java_generic_services\x18\x11 \x01(\x08:\x05\x66\x61lse\x12\"\n\x13py_generic_services\x18\x12 \x01(\x08:\x05\x66\x61lse\x12#\n\x14php_generic_services\x18* \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x17 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x10\x63\x63_enable_arenas\x18\x1f \x01(\x08:\x04true\x12\x19\n\x11objc_class_prefix\x18$ \x01(\t\x12\x18\n\x10\x63sharp_namespace\x18% \x01(\t\x12\x14\n\x0cswift_prefix\x18\' \x01(\t\x12\x18\n\x10php_class_prefix\x18( \x01(\t\x12\x15\n\rphp_namespace\x18) \x01(\t\x12\x1e\n\x16php_metadata_namespace\x18, \x01(\t\x12\x14\n\x0cruby_package\x18- \x01(\t\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\":\n\x0cOptimizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08&\x10\'\"\x84\x02\n\x0eMessageOptions\x12&\n\x17message_set_wire_format\x18\x01 \x01(\x08:\x05\x66\x61lse\x12.\n\x1fno_standard_descriptor_accessor\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x11\n\tmap_entry\x18\x07 \x01(\x08\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xbe\x03\n\x0c\x46ieldOptions\x12:\n\x05\x63type\x18\x01 \x01(\x0e\x32#.google.protobuf.FieldOptions.CType:\x06STRING\x12\x0e\n\x06packed\x18\x02 \x01(\x08\x12?\n\x06jstype\x18\x06 \x01(\x0e\x32$.google.protobuf.FieldOptions.JSType:\tJS_NORMAL\x12\x13\n\x04lazy\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0funverified_lazy\x18\x0f \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04weak\x18\n \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\"/\n\x05\x43Type\x12\n\n\x06STRING\x10\x00\x12\x08\n\x04\x43ORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\x06JSType\x12\r\n\tJS_NORMAL\x10\x00\x12\r\n\tJS_STRING\x10\x01\x12\r\n\tJS_NUMBER\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05\"^\n\x0cOneofOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x93\x01\n\x0b\x45numOptions\x12\x13\n\x0b\x61llow_alias\x18\x02 \x01(\x08\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x05\x10\x06\"}\n\x10\x45numValueOptions\x12\x19\n\ndeprecated\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"{\n\x0eServiceOptions\x12\x19\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xad\x02\n\rMethodOptions\x12\x19\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lse\x12_\n\x11idempotency_level\x18\" \x01(\x0e\x32/.google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UNKNOWN\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\"P\n\x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\x00\x12\x13\n\x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9e\x02\n\x13UninterpretedOption\x12;\n\x04name\x18\x02 \x03(\x0b\x32-.google.protobuf.UninterpretedOption.NamePart\x12\x18\n\x10identifier_value\x18\x03 \x01(\t\x12\x1a\n\x12positive_int_value\x18\x04 \x01(\x04\x12\x1a\n\x12negative_int_value\x18\x05 \x01(\x03\x12\x14\n\x0c\x64ouble_value\x18\x06 \x01(\x01\x12\x14\n\x0cstring_value\x18\x07 \x01(\x0c\x12\x17\n\x0f\x61ggregate_value\x18\x08 \x01(\t\x1a\x33\n\x08NamePart\x12\x11\n\tname_part\x18\x01 \x02(\t\x12\x14\n\x0cis_extension\x18\x02 \x02(\x08\"\xd5\x01\n\x0eSourceCodeInfo\x12:\n\x08location\x18\x01 \x03(\x0b\x32(.google.protobuf.SourceCodeInfo.Location\x1a\x86\x01\n\x08Location\x12\x10\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01\x12\x10\n\x04span\x18\x02 \x03(\x05\x42\x02\x10\x01\x12\x18\n\x10leading_comments\x18\x03 \x01(\t\x12\x19\n\x11trailing_comments\x18\x04 \x01(\t\x12!\n\x19leading_detached_comments\x18\x06 \x03(\t\"\xa7\x01\n\x11GeneratedCodeInfo\x12\x41\n\nannotation\x18\x01 \x03(\x0b\x32-.google.protobuf.GeneratedCodeInfo.Annotation\x1aO\n\nAnnotation\x12\x10\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01\x12\x13\n\x0bsource_file\x18\x02 \x01(\t\x12\r\n\x05\x62\x65gin\x18\x03 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x04 \x01(\x05\x42~\n\x13\x63om.google.protobufB\x10\x44\x65scriptorProtosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.Reflection') + +if _descriptor._USE_C_DESCRIPTORS == False: + _FIELDDESCRIPTORPROTO_TYPE = _descriptor.EnumDescriptor( + name='Type', + full_name='google.protobuf.FieldDescriptorProto.Type', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='TYPE_DOUBLE', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FLOAT', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_INT64', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT64', index=3, number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_INT32', index=4, number=5, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED64', index=5, number=6, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED32', index=6, number=7, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_BOOL', index=7, number=8, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_STRING', index=8, number=9, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_GROUP', index=9, number=10, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_MESSAGE', index=10, number=11, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_BYTES', index=11, number=12, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT32', index=12, number=13, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_ENUM', index=13, number=14, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED32', index=14, number=15, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED64', index=15, number=16, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT32', index=16, number=17, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT64', index=17, number=18, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDDESCRIPTORPROTO_TYPE) + + _FIELDDESCRIPTORPROTO_LABEL = _descriptor.EnumDescriptor( + name='Label', + full_name='google.protobuf.FieldDescriptorProto.Label', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='LABEL_OPTIONAL', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LABEL_REQUIRED', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LABEL_REPEATED', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDDESCRIPTORPROTO_LABEL) + + _FILEOPTIONS_OPTIMIZEMODE = _descriptor.EnumDescriptor( + name='OptimizeMode', + full_name='google.protobuf.FileOptions.OptimizeMode', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='SPEED', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='CODE_SIZE', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LITE_RUNTIME', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FILEOPTIONS_OPTIMIZEMODE) + + _FIELDOPTIONS_CTYPE = _descriptor.EnumDescriptor( + name='CType', + full_name='google.protobuf.FieldOptions.CType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='STRING', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='CORD', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='STRING_PIECE', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_CTYPE) + + _FIELDOPTIONS_JSTYPE = _descriptor.EnumDescriptor( + name='JSType', + full_name='google.protobuf.FieldOptions.JSType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='JS_NORMAL', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='JS_STRING', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='JS_NUMBER', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_JSTYPE) + + _METHODOPTIONS_IDEMPOTENCYLEVEL = _descriptor.EnumDescriptor( + name='IdempotencyLevel', + full_name='google.protobuf.MethodOptions.IdempotencyLevel', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='IDEMPOTENCY_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='NO_SIDE_EFFECTS', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='IDEMPOTENT', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_METHODOPTIONS_IDEMPOTENCYLEVEL) + + + _FILEDESCRIPTORSET = _descriptor.Descriptor( + name='FileDescriptorSet', + full_name='google.protobuf.FileDescriptorSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='file', full_name='google.protobuf.FileDescriptorSet.file', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _FILEDESCRIPTORPROTO = _descriptor.Descriptor( + name='FileDescriptorProto', + full_name='google.protobuf.FileDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FileDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='package', full_name='google.protobuf.FileDescriptorProto.package', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='dependency', full_name='google.protobuf.FileDescriptorProto.dependency', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='public_dependency', full_name='google.protobuf.FileDescriptorProto.public_dependency', index=3, + number=10, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='weak_dependency', full_name='google.protobuf.FileDescriptorProto.weak_dependency', index=4, + number=11, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='message_type', full_name='google.protobuf.FileDescriptorProto.message_type', index=5, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.FileDescriptorProto.enum_type', index=6, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='service', full_name='google.protobuf.FileDescriptorProto.service', index=7, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.FileDescriptorProto.extension', index=8, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FileDescriptorProto.options', index=9, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='source_code_info', full_name='google.protobuf.FileDescriptorProto.source_code_info', index=10, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='syntax', full_name='google.protobuf.FileDescriptorProto.syntax', index=11, + number=12, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _DESCRIPTORPROTO_EXTENSIONRANGE = _descriptor.Descriptor( + name='ExtensionRange', + full_name='google.protobuf.DescriptorProto.ExtensionRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.DescriptorProto.ExtensionRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.DescriptorProto.ExtensionRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.DescriptorProto.ExtensionRange.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _DESCRIPTORPROTO_RESERVEDRANGE = _descriptor.Descriptor( + name='ReservedRange', + full_name='google.protobuf.DescriptorProto.ReservedRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.DescriptorProto.ReservedRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.DescriptorProto.ReservedRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _DESCRIPTORPROTO = _descriptor.Descriptor( + name='DescriptorProto', + full_name='google.protobuf.DescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.DescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='field', full_name='google.protobuf.DescriptorProto.field', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.DescriptorProto.extension', index=2, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='nested_type', full_name='google.protobuf.DescriptorProto.nested_type', index=3, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.DescriptorProto.enum_type', index=4, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension_range', full_name='google.protobuf.DescriptorProto.extension_range', index=5, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='oneof_decl', full_name='google.protobuf.DescriptorProto.oneof_decl', index=6, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.DescriptorProto.options', index=7, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_range', full_name='google.protobuf.DescriptorProto.reserved_range', index=8, + number=9, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_name', full_name='google.protobuf.DescriptorProto.reserved_name', index=9, + number=10, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_DESCRIPTORPROTO_EXTENSIONRANGE, _DESCRIPTORPROTO_RESERVEDRANGE, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _EXTENSIONRANGEOPTIONS = _descriptor.Descriptor( + name='ExtensionRangeOptions', + full_name='google.protobuf.ExtensionRangeOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.ExtensionRangeOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _FIELDDESCRIPTORPROTO = _descriptor.Descriptor( + name='FieldDescriptorProto', + full_name='google.protobuf.FieldDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FieldDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.FieldDescriptorProto.number', index=1, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='label', full_name='google.protobuf.FieldDescriptorProto.label', index=2, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='type', full_name='google.protobuf.FieldDescriptorProto.type', index=3, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='type_name', full_name='google.protobuf.FieldDescriptorProto.type_name', index=4, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extendee', full_name='google.protobuf.FieldDescriptorProto.extendee', index=5, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='default_value', full_name='google.protobuf.FieldDescriptorProto.default_value', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='oneof_index', full_name='google.protobuf.FieldDescriptorProto.oneof_index', index=7, + number=9, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='json_name', full_name='google.protobuf.FieldDescriptorProto.json_name', index=8, + number=10, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FieldDescriptorProto.options', index=9, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='proto3_optional', full_name='google.protobuf.FieldDescriptorProto.proto3_optional', index=10, + number=17, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FIELDDESCRIPTORPROTO_TYPE, + _FIELDDESCRIPTORPROTO_LABEL, + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _ONEOFDESCRIPTORPROTO = _descriptor.Descriptor( + name='OneofDescriptorProto', + full_name='google.protobuf.OneofDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.OneofDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.OneofDescriptorProto.options', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE = _descriptor.Descriptor( + name='EnumReservedRange', + full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _ENUMDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumDescriptorProto', + full_name='google.protobuf.EnumDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='value', full_name='google.protobuf.EnumDescriptorProto.value', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_range', full_name='google.protobuf.EnumDescriptorProto.reserved_range', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_name', full_name='google.protobuf.EnumDescriptorProto.reserved_name', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _ENUMVALUEDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumValueDescriptorProto', + full_name='google.protobuf.EnumValueDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumValueDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.EnumValueDescriptorProto.number', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumValueDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _SERVICEDESCRIPTORPROTO = _descriptor.Descriptor( + name='ServiceDescriptorProto', + full_name='google.protobuf.ServiceDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.ServiceDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='method', full_name='google.protobuf.ServiceDescriptorProto.method', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.ServiceDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _METHODDESCRIPTORPROTO = _descriptor.Descriptor( + name='MethodDescriptorProto', + full_name='google.protobuf.MethodDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.MethodDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='input_type', full_name='google.protobuf.MethodDescriptorProto.input_type', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='output_type', full_name='google.protobuf.MethodDescriptorProto.output_type', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.MethodDescriptorProto.options', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='client_streaming', full_name='google.protobuf.MethodDescriptorProto.client_streaming', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='server_streaming', full_name='google.protobuf.MethodDescriptorProto.server_streaming', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _FILEOPTIONS = _descriptor.Descriptor( + name='FileOptions', + full_name='google.protobuf.FileOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='java_package', full_name='google.protobuf.FileOptions.java_package', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_outer_classname', full_name='google.protobuf.FileOptions.java_outer_classname', index=1, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_multiple_files', full_name='google.protobuf.FileOptions.java_multiple_files', index=2, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_generate_equals_and_hash', full_name='google.protobuf.FileOptions.java_generate_equals_and_hash', index=3, + number=20, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_string_check_utf8', full_name='google.protobuf.FileOptions.java_string_check_utf8', index=4, + number=27, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='optimize_for', full_name='google.protobuf.FileOptions.optimize_for', index=5, + number=9, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='go_package', full_name='google.protobuf.FileOptions.go_package', index=6, + number=11, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='cc_generic_services', full_name='google.protobuf.FileOptions.cc_generic_services', index=7, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_generic_services', full_name='google.protobuf.FileOptions.java_generic_services', index=8, + number=17, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='py_generic_services', full_name='google.protobuf.FileOptions.py_generic_services', index=9, + number=18, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_generic_services', full_name='google.protobuf.FileOptions.php_generic_services', index=10, + number=42, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.FileOptions.deprecated', index=11, + number=23, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='cc_enable_arenas', full_name='google.protobuf.FileOptions.cc_enable_arenas', index=12, + number=31, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='objc_class_prefix', full_name='google.protobuf.FileOptions.objc_class_prefix', index=13, + number=36, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='csharp_namespace', full_name='google.protobuf.FileOptions.csharp_namespace', index=14, + number=37, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='swift_prefix', full_name='google.protobuf.FileOptions.swift_prefix', index=15, + number=39, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_class_prefix', full_name='google.protobuf.FileOptions.php_class_prefix', index=16, + number=40, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_namespace', full_name='google.protobuf.FileOptions.php_namespace', index=17, + number=41, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_metadata_namespace', full_name='google.protobuf.FileOptions.php_metadata_namespace', index=18, + number=44, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='ruby_package', full_name='google.protobuf.FileOptions.ruby_package', index=19, + number=45, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FileOptions.uninterpreted_option', index=20, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FILEOPTIONS_OPTIMIZEMODE, + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _MESSAGEOPTIONS = _descriptor.Descriptor( + name='MessageOptions', + full_name='google.protobuf.MessageOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='message_set_wire_format', full_name='google.protobuf.MessageOptions.message_set_wire_format', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='no_standard_descriptor_accessor', full_name='google.protobuf.MessageOptions.no_standard_descriptor_accessor', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.MessageOptions.deprecated', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='map_entry', full_name='google.protobuf.MessageOptions.map_entry', index=3, + number=7, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MessageOptions.uninterpreted_option', index=4, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _FIELDOPTIONS = _descriptor.Descriptor( + name='FieldOptions', + full_name='google.protobuf.FieldOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='ctype', full_name='google.protobuf.FieldOptions.ctype', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='packed', full_name='google.protobuf.FieldOptions.packed', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='jstype', full_name='google.protobuf.FieldOptions.jstype', index=2, + number=6, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='lazy', full_name='google.protobuf.FieldOptions.lazy', index=3, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='unverified_lazy', full_name='google.protobuf.FieldOptions.unverified_lazy', index=4, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.FieldOptions.deprecated', index=5, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='weak', full_name='google.protobuf.FieldOptions.weak', index=6, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FieldOptions.uninterpreted_option', index=7, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FIELDOPTIONS_CTYPE, + _FIELDOPTIONS_JSTYPE, + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ONEOFOPTIONS = _descriptor.Descriptor( + name='OneofOptions', + full_name='google.protobuf.OneofOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.OneofOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ENUMOPTIONS = _descriptor.Descriptor( + name='EnumOptions', + full_name='google.protobuf.EnumOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='allow_alias', full_name='google.protobuf.EnumOptions.allow_alias', index=0, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.EnumOptions.deprecated', index=1, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumOptions.uninterpreted_option', index=2, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ENUMVALUEOPTIONS = _descriptor.Descriptor( + name='EnumValueOptions', + full_name='google.protobuf.EnumValueOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.EnumValueOptions.deprecated', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumValueOptions.uninterpreted_option', index=1, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _SERVICEOPTIONS = _descriptor.Descriptor( + name='ServiceOptions', + full_name='google.protobuf.ServiceOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.ServiceOptions.deprecated', index=0, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.ServiceOptions.uninterpreted_option', index=1, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _METHODOPTIONS = _descriptor.Descriptor( + name='MethodOptions', + full_name='google.protobuf.MethodOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.MethodOptions.deprecated', index=0, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='idempotency_level', full_name='google.protobuf.MethodOptions.idempotency_level', index=1, + number=34, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MethodOptions.uninterpreted_option', index=2, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _METHODOPTIONS_IDEMPOTENCYLEVEL, + ], + serialized_options=None, + is_extendable=True, + syntax='proto2', + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _UNINTERPRETEDOPTION_NAMEPART = _descriptor.Descriptor( + name='NamePart', + full_name='google.protobuf.UninterpretedOption.NamePart', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name_part', full_name='google.protobuf.UninterpretedOption.NamePart.name_part', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='is_extension', full_name='google.protobuf.UninterpretedOption.NamePart.is_extension', index=1, + number=2, type=8, cpp_type=7, label=2, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _UNINTERPRETEDOPTION = _descriptor.Descriptor( + name='UninterpretedOption', + full_name='google.protobuf.UninterpretedOption', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.UninterpretedOption.name', index=0, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='identifier_value', full_name='google.protobuf.UninterpretedOption.identifier_value', index=1, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='positive_int_value', full_name='google.protobuf.UninterpretedOption.positive_int_value', index=2, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='negative_int_value', full_name='google.protobuf.UninterpretedOption.negative_int_value', index=3, + number=5, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='double_value', full_name='google.protobuf.UninterpretedOption.double_value', index=4, + number=6, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='string_value', full_name='google.protobuf.UninterpretedOption.string_value', index=5, + number=7, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=b"", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='aggregate_value', full_name='google.protobuf.UninterpretedOption.aggregate_value', index=6, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_UNINTERPRETEDOPTION_NAMEPART, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _SOURCECODEINFO_LOCATION = _descriptor.Descriptor( + name='Location', + full_name='google.protobuf.SourceCodeInfo.Location', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='path', full_name='google.protobuf.SourceCodeInfo.Location.path', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='span', full_name='google.protobuf.SourceCodeInfo.Location.span', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='leading_comments', full_name='google.protobuf.SourceCodeInfo.Location.leading_comments', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='trailing_comments', full_name='google.protobuf.SourceCodeInfo.Location.trailing_comments', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='leading_detached_comments', full_name='google.protobuf.SourceCodeInfo.Location.leading_detached_comments', index=4, + number=6, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _SOURCECODEINFO = _descriptor.Descriptor( + name='SourceCodeInfo', + full_name='google.protobuf.SourceCodeInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='location', full_name='google.protobuf.SourceCodeInfo.location', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_SOURCECODEINFO_LOCATION, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + + _GENERATEDCODEINFO_ANNOTATION = _descriptor.Descriptor( + name='Annotation', + full_name='google.protobuf.GeneratedCodeInfo.Annotation', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='path', full_name='google.protobuf.GeneratedCodeInfo.Annotation.path', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='source_file', full_name='google.protobuf.GeneratedCodeInfo.Annotation.source_file', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='begin', full_name='google.protobuf.GeneratedCodeInfo.Annotation.begin', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.GeneratedCodeInfo.Annotation.end', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _GENERATEDCODEINFO = _descriptor.Descriptor( + name='GeneratedCodeInfo', + full_name='google.protobuf.GeneratedCodeInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='annotation', full_name='google.protobuf.GeneratedCodeInfo.annotation', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_GENERATEDCODEINFO_ANNOTATION, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + ) + + _FILEDESCRIPTORSET.fields_by_name['file'].message_type = _FILEDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['message_type'].message_type = _DESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['service'].message_type = _SERVICEDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['options'].message_type = _FILEOPTIONS + _FILEDESCRIPTORPROTO.fields_by_name['source_code_info'].message_type = _SOURCECODEINFO + _DESCRIPTORPROTO_EXTENSIONRANGE.fields_by_name['options'].message_type = _EXTENSIONRANGEOPTIONS + _DESCRIPTORPROTO_EXTENSIONRANGE.containing_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO_RESERVEDRANGE.containing_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['field'].message_type = _FIELDDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['nested_type'].message_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['extension_range'].message_type = _DESCRIPTORPROTO_EXTENSIONRANGE + _DESCRIPTORPROTO.fields_by_name['oneof_decl'].message_type = _ONEOFDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['options'].message_type = _MESSAGEOPTIONS + _DESCRIPTORPROTO.fields_by_name['reserved_range'].message_type = _DESCRIPTORPROTO_RESERVEDRANGE + _EXTENSIONRANGEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FIELDDESCRIPTORPROTO.fields_by_name['label'].enum_type = _FIELDDESCRIPTORPROTO_LABEL + _FIELDDESCRIPTORPROTO.fields_by_name['type'].enum_type = _FIELDDESCRIPTORPROTO_TYPE + _FIELDDESCRIPTORPROTO.fields_by_name['options'].message_type = _FIELDOPTIONS + _FIELDDESCRIPTORPROTO_TYPE.containing_type = _FIELDDESCRIPTORPROTO + _FIELDDESCRIPTORPROTO_LABEL.containing_type = _FIELDDESCRIPTORPROTO + _ONEOFDESCRIPTORPROTO.fields_by_name['options'].message_type = _ONEOFOPTIONS + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE.containing_type = _ENUMDESCRIPTORPROTO + _ENUMDESCRIPTORPROTO.fields_by_name['value'].message_type = _ENUMVALUEDESCRIPTORPROTO + _ENUMDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMOPTIONS + _ENUMDESCRIPTORPROTO.fields_by_name['reserved_range'].message_type = _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE + _ENUMVALUEDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMVALUEOPTIONS + _SERVICEDESCRIPTORPROTO.fields_by_name['method'].message_type = _METHODDESCRIPTORPROTO + _SERVICEDESCRIPTORPROTO.fields_by_name['options'].message_type = _SERVICEOPTIONS + _METHODDESCRIPTORPROTO.fields_by_name['options'].message_type = _METHODOPTIONS + _FILEOPTIONS.fields_by_name['optimize_for'].enum_type = _FILEOPTIONS_OPTIMIZEMODE + _FILEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FILEOPTIONS_OPTIMIZEMODE.containing_type = _FILEOPTIONS + _MESSAGEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FIELDOPTIONS.fields_by_name['ctype'].enum_type = _FIELDOPTIONS_CTYPE + _FIELDOPTIONS.fields_by_name['jstype'].enum_type = _FIELDOPTIONS_JSTYPE + _FIELDOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FIELDOPTIONS_CTYPE.containing_type = _FIELDOPTIONS + _FIELDOPTIONS_JSTYPE.containing_type = _FIELDOPTIONS + _ONEOFOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _ENUMOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _ENUMVALUEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _SERVICEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _METHODOPTIONS.fields_by_name['idempotency_level'].enum_type = _METHODOPTIONS_IDEMPOTENCYLEVEL + _METHODOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _METHODOPTIONS_IDEMPOTENCYLEVEL.containing_type = _METHODOPTIONS + _UNINTERPRETEDOPTION_NAMEPART.containing_type = _UNINTERPRETEDOPTION + _UNINTERPRETEDOPTION.fields_by_name['name'].message_type = _UNINTERPRETEDOPTION_NAMEPART + _SOURCECODEINFO_LOCATION.containing_type = _SOURCECODEINFO + _SOURCECODEINFO.fields_by_name['location'].message_type = _SOURCECODEINFO_LOCATION + _GENERATEDCODEINFO_ANNOTATION.containing_type = _GENERATEDCODEINFO + _GENERATEDCODEINFO.fields_by_name['annotation'].message_type = _GENERATEDCODEINFO_ANNOTATION + DESCRIPTOR.message_types_by_name['FileDescriptorSet'] = _FILEDESCRIPTORSET + DESCRIPTOR.message_types_by_name['FileDescriptorProto'] = _FILEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['DescriptorProto'] = _DESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['ExtensionRangeOptions'] = _EXTENSIONRANGEOPTIONS + DESCRIPTOR.message_types_by_name['FieldDescriptorProto'] = _FIELDDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['OneofDescriptorProto'] = _ONEOFDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['EnumDescriptorProto'] = _ENUMDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['EnumValueDescriptorProto'] = _ENUMVALUEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['ServiceDescriptorProto'] = _SERVICEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['MethodDescriptorProto'] = _METHODDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['FileOptions'] = _FILEOPTIONS + DESCRIPTOR.message_types_by_name['MessageOptions'] = _MESSAGEOPTIONS + DESCRIPTOR.message_types_by_name['FieldOptions'] = _FIELDOPTIONS + DESCRIPTOR.message_types_by_name['OneofOptions'] = _ONEOFOPTIONS + DESCRIPTOR.message_types_by_name['EnumOptions'] = _ENUMOPTIONS + DESCRIPTOR.message_types_by_name['EnumValueOptions'] = _ENUMVALUEOPTIONS + DESCRIPTOR.message_types_by_name['ServiceOptions'] = _SERVICEOPTIONS + DESCRIPTOR.message_types_by_name['MethodOptions'] = _METHODOPTIONS + DESCRIPTOR.message_types_by_name['UninterpretedOption'] = _UNINTERPRETEDOPTION + DESCRIPTOR.message_types_by_name['SourceCodeInfo'] = _SOURCECODEINFO + DESCRIPTOR.message_types_by_name['GeneratedCodeInfo'] = _GENERATEDCODEINFO + _sym_db.RegisterFileDescriptor(DESCRIPTOR) + +else: + _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.descriptor_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _FILEDESCRIPTORSET._serialized_start=53 + _FILEDESCRIPTORSET._serialized_end=124 + _FILEDESCRIPTORPROTO._serialized_start=127 + _FILEDESCRIPTORPROTO._serialized_end=602 + _DESCRIPTORPROTO._serialized_start=605 + _DESCRIPTORPROTO._serialized_end=1286 + _DESCRIPTORPROTO_EXTENSIONRANGE._serialized_start=1140 + _DESCRIPTORPROTO_EXTENSIONRANGE._serialized_end=1241 + _DESCRIPTORPROTO_RESERVEDRANGE._serialized_start=1243 + _DESCRIPTORPROTO_RESERVEDRANGE._serialized_end=1286 + _EXTENSIONRANGEOPTIONS._serialized_start=1288 + _EXTENSIONRANGEOPTIONS._serialized_end=1391 + _FIELDDESCRIPTORPROTO._serialized_start=1394 + _FIELDDESCRIPTORPROTO._serialized_end=2119 + _FIELDDESCRIPTORPROTO_TYPE._serialized_start=1740 + _FIELDDESCRIPTORPROTO_TYPE._serialized_end=2050 + _FIELDDESCRIPTORPROTO_LABEL._serialized_start=2052 + _FIELDDESCRIPTORPROTO_LABEL._serialized_end=2119 + _ONEOFDESCRIPTORPROTO._serialized_start=2121 + _ONEOFDESCRIPTORPROTO._serialized_end=2205 + _ENUMDESCRIPTORPROTO._serialized_start=2208 + _ENUMDESCRIPTORPROTO._serialized_end=2500 + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE._serialized_start=2453 + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE._serialized_end=2500 + _ENUMVALUEDESCRIPTORPROTO._serialized_start=2502 + _ENUMVALUEDESCRIPTORPROTO._serialized_end=2610 + _SERVICEDESCRIPTORPROTO._serialized_start=2613 + _SERVICEDESCRIPTORPROTO._serialized_end=2757 + _METHODDESCRIPTORPROTO._serialized_start=2760 + _METHODDESCRIPTORPROTO._serialized_end=2953 + _FILEOPTIONS._serialized_start=2956 + _FILEOPTIONS._serialized_end=3761 + _FILEOPTIONS_OPTIMIZEMODE._serialized_start=3686 + _FILEOPTIONS_OPTIMIZEMODE._serialized_end=3744 + _MESSAGEOPTIONS._serialized_start=3764 + _MESSAGEOPTIONS._serialized_end=4024 + _FIELDOPTIONS._serialized_start=4027 + _FIELDOPTIONS._serialized_end=4473 + _FIELDOPTIONS_CTYPE._serialized_start=4354 + _FIELDOPTIONS_CTYPE._serialized_end=4401 + _FIELDOPTIONS_JSTYPE._serialized_start=4403 + _FIELDOPTIONS_JSTYPE._serialized_end=4456 + _ONEOFOPTIONS._serialized_start=4475 + _ONEOFOPTIONS._serialized_end=4569 + _ENUMOPTIONS._serialized_start=4572 + _ENUMOPTIONS._serialized_end=4719 + _ENUMVALUEOPTIONS._serialized_start=4721 + _ENUMVALUEOPTIONS._serialized_end=4846 + _SERVICEOPTIONS._serialized_start=4848 + _SERVICEOPTIONS._serialized_end=4971 + _METHODOPTIONS._serialized_start=4974 + _METHODOPTIONS._serialized_end=5275 + _METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_start=5184 + _METHODOPTIONS_IDEMPOTENCYLEVEL._serialized_end=5264 + _UNINTERPRETEDOPTION._serialized_start=5278 + _UNINTERPRETEDOPTION._serialized_end=5564 + _UNINTERPRETEDOPTION_NAMEPART._serialized_start=5513 + _UNINTERPRETEDOPTION_NAMEPART._serialized_end=5564 + _SOURCECODEINFO._serialized_start=5567 + _SOURCECODEINFO._serialized_end=5780 + _SOURCECODEINFO_LOCATION._serialized_start=5646 + _SOURCECODEINFO_LOCATION._serialized_end=5780 + _GENERATEDCODEINFO._serialized_start=5783 + _GENERATEDCODEINFO._serialized_end=5950 + _GENERATEDCODEINFO_ANNOTATION._serialized_start=5871 + _GENERATEDCODEINFO_ANNOTATION._serialized_end=5950 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pool.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..911372a8b00e5d08fadcead0f6a9b47c01f12b23 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/descriptor_pool.py @@ -0,0 +1,1295 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides DescriptorPool to use as a container for proto2 descriptors. + +The DescriptorPool is used in conjection with a DescriptorDatabase to maintain +a collection of protocol buffer descriptors for use when dynamically creating +message types at runtime. + +For most applications protocol buffers should be used via modules generated by +the protocol buffer compiler tool. This should only be used when the type of +protocol buffers used in an application or library cannot be predetermined. + +Below is a straightforward example on how to use this class:: + + pool = DescriptorPool() + file_descriptor_protos = [ ... ] + for file_descriptor_proto in file_descriptor_protos: + pool.Add(file_descriptor_proto) + my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType') + +The message descriptor can be used in conjunction with the message_factory +module in order to create a protocol buffer class that can be encoded and +decoded. + +If you want to get a Python class for the specified proto, use the +helper functions inside google.protobuf.message_factory +directly instead of this class. +""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import collections +import warnings + +from google.protobuf import descriptor +from google.protobuf import descriptor_database +from google.protobuf import text_encoding + + +_USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access + + +def _Deprecated(func): + """Mark functions as deprecated.""" + + def NewFunc(*args, **kwargs): + warnings.warn( + 'Call to deprecated function %s(). Note: Do add unlinked descriptors ' + 'to descriptor_pool is wrong. Use Add() or AddSerializedFile() ' + 'instead.' % func.__name__, + category=DeprecationWarning) + return func(*args, **kwargs) + NewFunc.__name__ = func.__name__ + NewFunc.__doc__ = func.__doc__ + NewFunc.__dict__.update(func.__dict__) + return NewFunc + + +def _NormalizeFullyQualifiedName(name): + """Remove leading period from fully-qualified type name. + + Due to b/13860351 in descriptor_database.py, types in the root namespace are + generated with a leading period. This function removes that prefix. + + Args: + name (str): The fully-qualified symbol name. + + Returns: + str: The normalized fully-qualified symbol name. + """ + return name.lstrip('.') + + +def _OptionsOrNone(descriptor_proto): + """Returns the value of the field `options`, or None if it is not set.""" + if descriptor_proto.HasField('options'): + return descriptor_proto.options + else: + return None + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL) + + +class DescriptorPool(object): + """A collection of protobufs dynamically constructed by descriptor protos.""" + + if _USE_C_DESCRIPTORS: + + def __new__(cls, descriptor_db=None): + # pylint: disable=protected-access + return descriptor._message.DescriptorPool(descriptor_db) + + def __init__(self, descriptor_db=None): + """Initializes a Pool of proto buffs. + + The descriptor_db argument to the constructor is provided to allow + specialized file descriptor proto lookup code to be triggered on demand. An + example would be an implementation which will read and compile a file + specified in a call to FindFileByName() and not require the call to Add() + at all. Results from this database will be cached internally here as well. + + Args: + descriptor_db: A secondary source of file descriptors. + """ + + self._internal_db = descriptor_database.DescriptorDatabase() + self._descriptor_db = descriptor_db + self._descriptors = {} + self._enum_descriptors = {} + self._service_descriptors = {} + self._file_descriptors = {} + self._toplevel_extensions = {} + # TODO(jieluo): Remove _file_desc_by_toplevel_extension after + # maybe year 2020 for compatibility issue (with 3.4.1 only). + self._file_desc_by_toplevel_extension = {} + self._top_enum_values = {} + # We store extensions in two two-level mappings: The first key is the + # descriptor of the message being extended, the second key is the extension + # full name or its tag number. + self._extensions_by_name = collections.defaultdict(dict) + self._extensions_by_number = collections.defaultdict(dict) + + def _CheckConflictRegister(self, desc, desc_name, file_name): + """Check if the descriptor name conflicts with another of the same name. + + Args: + desc: Descriptor of a message, enum, service, extension or enum value. + desc_name (str): the full name of desc. + file_name (str): The file name of descriptor. + """ + for register, descriptor_type in [ + (self._descriptors, descriptor.Descriptor), + (self._enum_descriptors, descriptor.EnumDescriptor), + (self._service_descriptors, descriptor.ServiceDescriptor), + (self._toplevel_extensions, descriptor.FieldDescriptor), + (self._top_enum_values, descriptor.EnumValueDescriptor)]: + if desc_name in register: + old_desc = register[desc_name] + if isinstance(old_desc, descriptor.EnumValueDescriptor): + old_file = old_desc.type.file.name + else: + old_file = old_desc.file.name + + if not isinstance(desc, descriptor_type) or ( + old_file != file_name): + error_msg = ('Conflict register for file "' + file_name + + '": ' + desc_name + + ' is already defined in file "' + + old_file + '". Please fix the conflict by adding ' + 'package name on the proto file, or use different ' + 'name for the duplication.') + if isinstance(desc, descriptor.EnumValueDescriptor): + error_msg += ('\nNote: enum values appear as ' + 'siblings of the enum type instead of ' + 'children of it.') + + raise TypeError(error_msg) + + return + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this pool. + + Args: + file_desc_proto (FileDescriptorProto): The file descriptor to add. + """ + + self._internal_db.Add(file_desc_proto) + + def AddSerializedFile(self, serialized_file_desc_proto): + """Adds the FileDescriptorProto and its types to this pool. + + Args: + serialized_file_desc_proto (bytes): A bytes string, serialization of the + :class:`FileDescriptorProto` to add. + + Returns: + FileDescriptor: Descriptor for the added file. + """ + + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( + serialized_file_desc_proto) + file_desc = self._ConvertFileProtoToFileDescriptor(file_desc_proto) + file_desc.serialized_pb = serialized_file_desc_proto + return file_desc + + # Add Descriptor to descriptor pool is dreprecated. Please use Add() + # or AddSerializedFile() to add a FileDescriptorProto instead. + @_Deprecated + def AddDescriptor(self, desc): + self._AddDescriptor(desc) + + # Never call this method. It is for internal usage only. + def _AddDescriptor(self, desc): + """Adds a Descriptor to the pool, non-recursively. + + If the Descriptor contains nested messages or enums, the caller must + explicitly register them. This method also registers the FileDescriptor + associated with the message. + + Args: + desc: A Descriptor. + """ + if not isinstance(desc, descriptor.Descriptor): + raise TypeError('Expected instance of descriptor.Descriptor.') + + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + + self._descriptors[desc.full_name] = desc + self._AddFileDescriptor(desc.file) + + # Add EnumDescriptor to descriptor pool is dreprecated. Please use Add() + # or AddSerializedFile() to add a FileDescriptorProto instead. + @_Deprecated + def AddEnumDescriptor(self, enum_desc): + self._AddEnumDescriptor(enum_desc) + + # Never call this method. It is for internal usage only. + def _AddEnumDescriptor(self, enum_desc): + """Adds an EnumDescriptor to the pool. + + This method also registers the FileDescriptor associated with the enum. + + Args: + enum_desc: An EnumDescriptor. + """ + + if not isinstance(enum_desc, descriptor.EnumDescriptor): + raise TypeError('Expected instance of descriptor.EnumDescriptor.') + + file_name = enum_desc.file.name + self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name) + self._enum_descriptors[enum_desc.full_name] = enum_desc + + # Top enum values need to be indexed. + # Count the number of dots to see whether the enum is toplevel or nested + # in a message. We cannot use enum_desc.containing_type at this stage. + if enum_desc.file.package: + top_level = (enum_desc.full_name.count('.') + - enum_desc.file.package.count('.') == 1) + else: + top_level = enum_desc.full_name.count('.') == 0 + if top_level: + file_name = enum_desc.file.name + package = enum_desc.file.package + for enum_value in enum_desc.values: + full_name = _NormalizeFullyQualifiedName( + '.'.join((package, enum_value.name))) + self._CheckConflictRegister(enum_value, full_name, file_name) + self._top_enum_values[full_name] = enum_value + self._AddFileDescriptor(enum_desc.file) + + # Add ServiceDescriptor to descriptor pool is dreprecated. Please use Add() + # or AddSerializedFile() to add a FileDescriptorProto instead. + @_Deprecated + def AddServiceDescriptor(self, service_desc): + self._AddServiceDescriptor(service_desc) + + # Never call this method. It is for internal usage only. + def _AddServiceDescriptor(self, service_desc): + """Adds a ServiceDescriptor to the pool. + + Args: + service_desc: A ServiceDescriptor. + """ + + if not isinstance(service_desc, descriptor.ServiceDescriptor): + raise TypeError('Expected instance of descriptor.ServiceDescriptor.') + + self._CheckConflictRegister(service_desc, service_desc.full_name, + service_desc.file.name) + self._service_descriptors[service_desc.full_name] = service_desc + + # Add ExtensionDescriptor to descriptor pool is dreprecated. Please use Add() + # or AddSerializedFile() to add a FileDescriptorProto instead. + @_Deprecated + def AddExtensionDescriptor(self, extension): + self._AddExtensionDescriptor(extension) + + # Never call this method. It is for internal usage only. + def _AddExtensionDescriptor(self, extension): + """Adds a FieldDescriptor describing an extension to the pool. + + Args: + extension: A FieldDescriptor. + + Raises: + AssertionError: when another extension with the same number extends the + same message. + TypeError: when the specified extension is not a + descriptor.FieldDescriptor. + """ + if not (isinstance(extension, descriptor.FieldDescriptor) and + extension.is_extension): + raise TypeError('Expected an extension descriptor.') + + if extension.extension_scope is None: + self._toplevel_extensions[extension.full_name] = extension + + try: + existing_desc = self._extensions_by_number[ + extension.containing_type][extension.number] + except KeyError: + pass + else: + if extension is not existing_desc: + raise AssertionError( + 'Extensions "%s" and "%s" both try to extend message type "%s" ' + 'with field number %d.' % + (extension.full_name, existing_desc.full_name, + extension.containing_type.full_name, extension.number)) + + self._extensions_by_number[extension.containing_type][ + extension.number] = extension + self._extensions_by_name[extension.containing_type][ + extension.full_name] = extension + + # Also register MessageSet extensions with the type name. + if _IsMessageSetExtension(extension): + self._extensions_by_name[extension.containing_type][ + extension.message_type.full_name] = extension + + @_Deprecated + def AddFileDescriptor(self, file_desc): + self._InternalAddFileDescriptor(file_desc) + + # Never call this method. It is for internal usage only. + def _InternalAddFileDescriptor(self, file_desc): + """Adds a FileDescriptor to the pool, non-recursively. + + If the FileDescriptor contains messages or enums, the caller must explicitly + register them. + + Args: + file_desc: A FileDescriptor. + """ + + self._AddFileDescriptor(file_desc) + # TODO(jieluo): This is a temporary solution for FieldDescriptor.file. + # FieldDescriptor.file is added in code gen. Remove this solution after + # maybe 2020 for compatibility reason (with 3.4.1 only). + for extension in file_desc.extensions_by_name.values(): + self._file_desc_by_toplevel_extension[ + extension.full_name] = file_desc + + def _AddFileDescriptor(self, file_desc): + """Adds a FileDescriptor to the pool, non-recursively. + + If the FileDescriptor contains messages or enums, the caller must explicitly + register them. + + Args: + file_desc: A FileDescriptor. + """ + + if not isinstance(file_desc, descriptor.FileDescriptor): + raise TypeError('Expected instance of descriptor.FileDescriptor.') + self._file_descriptors[file_desc.name] = file_desc + + def FindFileByName(self, file_name): + """Gets a FileDescriptor by file name. + + Args: + file_name (str): The path to the file to get a descriptor for. + + Returns: + FileDescriptor: The descriptor for the named file. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + + try: + return self._file_descriptors[file_name] + except KeyError: + pass + + try: + file_proto = self._internal_db.FindFileByName(file_name) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileByName(file_name) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file named %s' % file_name) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def FindFileContainingSymbol(self, symbol): + """Gets the FileDescriptor for the file containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: Descriptor for the file that contains the specified + symbol. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + + symbol = _NormalizeFullyQualifiedName(symbol) + try: + return self._InternalFindFileContainingSymbol(symbol) + except KeyError: + pass + + try: + # Try fallback database. Build and find again if possible. + self._FindFileContainingSymbolInDb(symbol) + return self._InternalFindFileContainingSymbol(symbol) + except KeyError: + raise KeyError('Cannot find a file containing %s' % symbol) + + def _InternalFindFileContainingSymbol(self, symbol): + """Gets the already built FileDescriptor containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: Descriptor for the file that contains the specified + symbol. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + try: + return self._descriptors[symbol].file + except KeyError: + pass + + try: + return self._enum_descriptors[symbol].file + except KeyError: + pass + + try: + return self._service_descriptors[symbol].file + except KeyError: + pass + + try: + return self._top_enum_values[symbol].type.file + except KeyError: + pass + + try: + return self._file_desc_by_toplevel_extension[symbol] + except KeyError: + pass + + # Try fields, enum values and nested extensions inside a message. + top_name, _, sub_name = symbol.rpartition('.') + try: + message = self.FindMessageTypeByName(top_name) + assert (sub_name in message.extensions_by_name or + sub_name in message.fields_by_name or + sub_name in message.enum_values_by_name) + return message.file + except (KeyError, AssertionError): + raise KeyError('Cannot find a file containing %s' % symbol) + + def FindMessageTypeByName(self, full_name): + """Loads the named descriptor from the pool. + + Args: + full_name (str): The full name of the descriptor to load. + + Returns: + Descriptor: The descriptor for the named type. + + Raises: + KeyError: if the message cannot be found in the pool. + """ + + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._descriptors[full_name] + + def FindEnumTypeByName(self, full_name): + """Loads the named enum descriptor from the pool. + + Args: + full_name (str): The full name of the enum descriptor to load. + + Returns: + EnumDescriptor: The enum descriptor for the named type. + + Raises: + KeyError: if the enum cannot be found in the pool. + """ + + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._enum_descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._enum_descriptors[full_name] + + def FindFieldByName(self, full_name): + """Loads the named field descriptor from the pool. + + Args: + full_name (str): The full name of the field descriptor to load. + + Returns: + FieldDescriptor: The field descriptor for the named field. + + Raises: + KeyError: if the field cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + message_name, _, field_name = full_name.rpartition('.') + message_descriptor = self.FindMessageTypeByName(message_name) + return message_descriptor.fields_by_name[field_name] + + def FindOneofByName(self, full_name): + """Loads the named oneof descriptor from the pool. + + Args: + full_name (str): The full name of the oneof descriptor to load. + + Returns: + OneofDescriptor: The oneof descriptor for the named oneof. + + Raises: + KeyError: if the oneof cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + message_name, _, oneof_name = full_name.rpartition('.') + message_descriptor = self.FindMessageTypeByName(message_name) + return message_descriptor.oneofs_by_name[oneof_name] + + def FindExtensionByName(self, full_name): + """Loads the named extension descriptor from the pool. + + Args: + full_name (str): The full name of the extension descriptor to load. + + Returns: + FieldDescriptor: The field descriptor for the named extension. + + Raises: + KeyError: if the extension cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + try: + # The proto compiler does not give any link between the FileDescriptor + # and top-level extensions unless the FileDescriptorProto is added to + # the DescriptorDatabase, but this can impact memory usage. + # So we registered these extensions by name explicitly. + return self._toplevel_extensions[full_name] + except KeyError: + pass + message_name, _, extension_name = full_name.rpartition('.') + try: + # Most extensions are nested inside a message. + scope = self.FindMessageTypeByName(message_name) + except KeyError: + # Some extensions are defined at file scope. + scope = self._FindFileContainingSymbolInDb(full_name) + return scope.extensions_by_name[extension_name] + + def FindExtensionByNumber(self, message_descriptor, number): + """Gets the extension of the specified message with the specified number. + + Extensions have to be registered to this pool by calling :func:`Add` or + :func:`AddExtensionDescriptor`. + + Args: + message_descriptor (Descriptor): descriptor of the extended message. + number (int): Number of the extension field. + + Returns: + FieldDescriptor: The descriptor for the extension. + + Raises: + KeyError: when no extension with the given number is known for the + specified message. + """ + try: + return self._extensions_by_number[message_descriptor][number] + except KeyError: + self._TryLoadExtensionFromDB(message_descriptor, number) + return self._extensions_by_number[message_descriptor][number] + + def FindAllExtensions(self, message_descriptor): + """Gets all the known extensions of a given message. + + Extensions have to be registered to this pool by build related + :func:`Add` or :func:`AddExtensionDescriptor`. + + Args: + message_descriptor (Descriptor): Descriptor of the extended message. + + Returns: + list[FieldDescriptor]: Field descriptors describing the extensions. + """ + # Fallback to descriptor db if FindAllExtensionNumbers is provided. + if self._descriptor_db and hasattr( + self._descriptor_db, 'FindAllExtensionNumbers'): + full_name = message_descriptor.full_name + all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name) + for number in all_numbers: + if number in self._extensions_by_number[message_descriptor]: + continue + self._TryLoadExtensionFromDB(message_descriptor, number) + + return list(self._extensions_by_number[message_descriptor].values()) + + def _TryLoadExtensionFromDB(self, message_descriptor, number): + """Try to Load extensions from descriptor db. + + Args: + message_descriptor: descriptor of the extended message. + number: the extension number that needs to be loaded. + """ + if not self._descriptor_db: + return + # Only supported when FindFileContainingExtension is provided. + if not hasattr( + self._descriptor_db, 'FindFileContainingExtension'): + return + + full_name = message_descriptor.full_name + file_proto = self._descriptor_db.FindFileContainingExtension( + full_name, number) + + if file_proto is None: + return + + try: + self._ConvertFileProtoToFileDescriptor(file_proto) + except: + warn_msg = ('Unable to load proto file %s for extension number %d.' % + (file_proto.name, number)) + warnings.warn(warn_msg, RuntimeWarning) + + def FindServiceByName(self, full_name): + """Loads the named service descriptor from the pool. + + Args: + full_name (str): The full name of the service descriptor to load. + + Returns: + ServiceDescriptor: The service descriptor for the named service. + + Raises: + KeyError: if the service cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._service_descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._service_descriptors[full_name] + + def FindMethodByName(self, full_name): + """Loads the named service method descriptor from the pool. + + Args: + full_name (str): The full name of the method descriptor to load. + + Returns: + MethodDescriptor: The method descriptor for the service method. + + Raises: + KeyError: if the method cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + service_name, _, method_name = full_name.rpartition('.') + service_descriptor = self.FindServiceByName(service_name) + return service_descriptor.methods_by_name[method_name] + + def _FindFileContainingSymbolInDb(self, symbol): + """Finds the file in descriptor DB containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: The file that contains the specified symbol. + + Raises: + KeyError: if the file cannot be found in the descriptor database. + """ + try: + file_proto = self._internal_db.FindFileContainingSymbol(symbol) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file containing %s' % symbol) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def _ConvertFileProtoToFileDescriptor(self, file_proto): + """Creates a FileDescriptor from a proto or returns a cached copy. + + This method also has the side effect of loading all the symbols found in + the file into the appropriate dictionaries in the pool. + + Args: + file_proto: The proto to convert. + + Returns: + A FileDescriptor matching the passed in proto. + """ + if file_proto.name not in self._file_descriptors: + built_deps = list(self._GetDeps(file_proto.dependency)) + direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] + public_deps = [direct_deps[i] for i in file_proto.public_dependency] + + file_descriptor = descriptor.FileDescriptor( + pool=self, + name=file_proto.name, + package=file_proto.package, + syntax=file_proto.syntax, + options=_OptionsOrNone(file_proto), + serialized_pb=file_proto.SerializeToString(), + dependencies=direct_deps, + public_dependencies=public_deps, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + scope = {} + + # This loop extracts all the message and enum types from all the + # dependencies of the file_proto. This is necessary to create the + # scope of available message types when defining the passed in + # file proto. + for dependency in built_deps: + scope.update(self._ExtractSymbols( + dependency.message_types_by_name.values())) + scope.update((_PrefixWithDot(enum.full_name), enum) + for enum in dependency.enum_types_by_name.values()) + + for message_type in file_proto.message_type: + message_desc = self._ConvertMessageDescriptor( + message_type, file_proto.package, file_descriptor, scope, + file_proto.syntax) + file_descriptor.message_types_by_name[message_desc.name] = ( + message_desc) + + for enum_type in file_proto.enum_type: + file_descriptor.enum_types_by_name[enum_type.name] = ( + self._ConvertEnumDescriptor(enum_type, file_proto.package, + file_descriptor, None, scope, True)) + + for index, extension_proto in enumerate(file_proto.extension): + extension_desc = self._MakeFieldDescriptor( + extension_proto, file_proto.package, index, file_descriptor, + is_extension=True) + extension_desc.containing_type = self._GetTypeFromScope( + file_descriptor.package, extension_proto.extendee, scope) + self._SetFieldType(extension_proto, extension_desc, + file_descriptor.package, scope) + file_descriptor.extensions_by_name[extension_desc.name] = ( + extension_desc) + self._file_desc_by_toplevel_extension[extension_desc.full_name] = ( + file_descriptor) + + for desc_proto in file_proto.message_type: + self._SetAllFieldTypes(file_proto.package, desc_proto, scope) + + if file_proto.package: + desc_proto_prefix = _PrefixWithDot(file_proto.package) + else: + desc_proto_prefix = '' + + for desc_proto in file_proto.message_type: + desc = self._GetTypeFromScope( + desc_proto_prefix, desc_proto.name, scope) + file_descriptor.message_types_by_name[desc_proto.name] = desc + + for index, service_proto in enumerate(file_proto.service): + file_descriptor.services_by_name[service_proto.name] = ( + self._MakeServiceDescriptor(service_proto, index, scope, + file_proto.package, file_descriptor)) + + self._file_descriptors[file_proto.name] = file_descriptor + + # Add extensions to the pool + file_desc = self._file_descriptors[file_proto.name] + for extension in file_desc.extensions_by_name.values(): + self._AddExtensionDescriptor(extension) + for message_type in file_desc.message_types_by_name.values(): + for extension in message_type.extensions: + self._AddExtensionDescriptor(extension) + + return file_desc + + def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, + scope=None, syntax=None): + """Adds the proto to the pool in the specified package. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: The package the proto should be located in. + file_desc: The file containing this message. + scope: Dict mapping short and full symbols to message and enum types. + syntax: string indicating syntax of the file ("proto2" or "proto3") + + Returns: + The added descriptor. + """ + + if package: + desc_name = '.'.join((package, desc_proto.name)) + else: + desc_name = desc_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + if scope is None: + scope = {} + + nested = [ + self._ConvertMessageDescriptor( + nested, desc_name, file_desc, scope, syntax) + for nested in desc_proto.nested_type] + enums = [ + self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, + scope, False) + for enum in desc_proto.enum_type] + fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc) + for index, field in enumerate(desc_proto.field)] + extensions = [ + self._MakeFieldDescriptor(extension, desc_name, index, file_desc, + is_extension=True) + for index, extension in enumerate(desc_proto.extension)] + oneofs = [ + # pylint: disable=g-complex-comprehension + descriptor.OneofDescriptor( + desc.name, + '.'.join((desc_name, desc.name)), + index, + None, + [], + _OptionsOrNone(desc), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + for index, desc in enumerate(desc_proto.oneof_decl) + ] + extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] + if extension_ranges: + is_extendable = True + else: + is_extendable = False + desc = descriptor.Descriptor( + name=desc_proto.name, + full_name=desc_name, + filename=file_name, + containing_type=None, + fields=fields, + oneofs=oneofs, + nested_types=nested, + enum_types=enums, + extensions=extensions, + options=_OptionsOrNone(desc_proto), + is_extendable=is_extendable, + extension_ranges=extension_ranges, + file=file_desc, + serialized_start=None, + serialized_end=None, + syntax=syntax, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + for nested in desc.nested_types: + nested.containing_type = desc + for enum in desc.enum_types: + enum.containing_type = desc + for field_index, field_desc in enumerate(desc_proto.field): + if field_desc.HasField('oneof_index'): + oneof_index = field_desc.oneof_index + oneofs[oneof_index].fields.append(fields[field_index]) + fields[field_index].containing_oneof = oneofs[oneof_index] + + scope[_PrefixWithDot(desc_name)] = desc + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._descriptors[desc_name] = desc + return desc + + def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, + containing_type=None, scope=None, top_level=False): + """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. + + Args: + enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. + package: Optional package name for the new message EnumDescriptor. + file_desc: The file containing the enum descriptor. + containing_type: The type containing this enum. + scope: Scope containing available types. + top_level: If True, the enum is a top level symbol. If False, the enum + is defined inside a message. + + Returns: + The added descriptor + """ + + if package: + enum_name = '.'.join((package, enum_proto.name)) + else: + enum_name = enum_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + values = [self._MakeEnumValueDescriptor(value, index) + for index, value in enumerate(enum_proto.value)] + desc = descriptor.EnumDescriptor(name=enum_proto.name, + full_name=enum_name, + filename=file_name, + file=file_desc, + values=values, + containing_type=containing_type, + options=_OptionsOrNone(enum_proto), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + scope['.%s' % enum_name] = desc + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._enum_descriptors[enum_name] = desc + + # Add top level enum values. + if top_level: + for value in values: + full_name = _NormalizeFullyQualifiedName( + '.'.join((package, value.name))) + self._CheckConflictRegister(value, full_name, file_name) + self._top_enum_values[full_name] = value + + return desc + + def _MakeFieldDescriptor(self, field_proto, message_name, index, + file_desc, is_extension=False): + """Creates a field descriptor from a FieldDescriptorProto. + + For message and enum type fields, this method will do a look up + in the pool for the appropriate descriptor for that type. If it + is unavailable, it will fall back to the _source function to + create it. If this type is still unavailable, construction will + fail. + + Args: + field_proto: The proto describing the field. + message_name: The name of the containing message. + index: Index of the field + file_desc: The file containing the field descriptor. + is_extension: Indication that this field is for an extension. + + Returns: + An initialized FieldDescriptor object + """ + + if message_name: + full_name = '.'.join((message_name, field_proto.name)) + else: + full_name = field_proto.name + + if field_proto.json_name: + json_name = field_proto.json_name + else: + json_name = None + + return descriptor.FieldDescriptor( + name=field_proto.name, + full_name=full_name, + index=index, + number=field_proto.number, + type=field_proto.type, + cpp_type=None, + message_type=None, + enum_type=None, + containing_type=None, + label=field_proto.label, + has_default_value=False, + default_value=None, + is_extension=is_extension, + extension_scope=None, + options=_OptionsOrNone(field_proto), + json_name=json_name, + file=file_desc, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _SetAllFieldTypes(self, package, desc_proto, scope): + """Sets all the descriptor's fields's types. + + This method also sets the containing types on any extensions. + + Args: + package: The current package of desc_proto. + desc_proto: The message descriptor to update. + scope: Enclosing scope of available types. + """ + + package = _PrefixWithDot(package) + + main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) + + if package == '.': + nested_package = _PrefixWithDot(desc_proto.name) + else: + nested_package = '.'.join([package, desc_proto.name]) + + for field_proto, field_desc in zip(desc_proto.field, main_desc.fields): + self._SetFieldType(field_proto, field_desc, nested_package, scope) + + for extension_proto, extension_desc in ( + zip(desc_proto.extension, main_desc.extensions)): + extension_desc.containing_type = self._GetTypeFromScope( + nested_package, extension_proto.extendee, scope) + self._SetFieldType(extension_proto, extension_desc, nested_package, scope) + + for nested_type in desc_proto.nested_type: + self._SetAllFieldTypes(nested_package, nested_type, scope) + + def _SetFieldType(self, field_proto, field_desc, package, scope): + """Sets the field's type, cpp_type, message_type and enum_type. + + Args: + field_proto: Data about the field in proto format. + field_desc: The descriptor to modify. + package: The package the field's container is in. + scope: Enclosing scope of available types. + """ + if field_proto.type_name: + desc = self._GetTypeFromScope(package, field_proto.type_name, scope) + else: + desc = None + + if not field_proto.HasField('type'): + if isinstance(desc, descriptor.Descriptor): + field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE + else: + field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM + + field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( + field_proto.type) + + if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE + or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): + field_desc.message_type = desc + + if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.enum_type = desc + + if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: + field_desc.has_default_value = False + field_desc.default_value = [] + elif field_proto.HasField('default_value'): + field_desc.has_default_value = True + if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or + field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): + field_desc.default_value = float(field_proto.default_value) + elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: + field_desc.default_value = field_proto.default_value + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: + field_desc.default_value = field_proto.default_value.lower() == 'true' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.default_value = field_desc.enum_type.values_by_name[ + field_proto.default_value].number + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: + field_desc.default_value = text_encoding.CUnescape( + field_proto.default_value) + elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE: + field_desc.default_value = None + else: + # All other types are of the "int" type. + field_desc.default_value = int(field_proto.default_value) + else: + field_desc.has_default_value = False + if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or + field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): + field_desc.default_value = 0.0 + elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: + field_desc.default_value = u'' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: + field_desc.default_value = False + elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.default_value = field_desc.enum_type.values[0].number + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: + field_desc.default_value = b'' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE: + field_desc.default_value = None + elif field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP: + field_desc.default_value = None + else: + # All other types are of the "int" type. + field_desc.default_value = 0 + + field_desc.type = field_proto.type + + def _MakeEnumValueDescriptor(self, value_proto, index): + """Creates a enum value descriptor object from a enum value proto. + + Args: + value_proto: The proto describing the enum value. + index: The index of the enum value. + + Returns: + An initialized EnumValueDescriptor object. + """ + + return descriptor.EnumValueDescriptor( + name=value_proto.name, + index=index, + number=value_proto.number, + options=_OptionsOrNone(value_proto), + type=None, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _MakeServiceDescriptor(self, service_proto, service_index, scope, + package, file_desc): + """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. + + Args: + service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. + service_index: The index of the service in the File. + scope: Dict mapping short and full symbols to message and enum types. + package: Optional package name for the new message EnumDescriptor. + file_desc: The file containing the service descriptor. + + Returns: + The added descriptor. + """ + + if package: + service_name = '.'.join((package, service_proto.name)) + else: + service_name = service_proto.name + + methods = [self._MakeMethodDescriptor(method_proto, service_name, package, + scope, index) + for index, method_proto in enumerate(service_proto.method)] + desc = descriptor.ServiceDescriptor( + name=service_proto.name, + full_name=service_name, + index=service_index, + methods=methods, + options=_OptionsOrNone(service_proto), + file=file_desc, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._service_descriptors[service_name] = desc + return desc + + def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, + index): + """Creates a method descriptor from a MethodDescriptorProto. + + Args: + method_proto: The proto describing the method. + service_name: The name of the containing service. + package: Optional package name to look up for types. + scope: Scope containing available types. + index: Index of the method in the service. + + Returns: + An initialized MethodDescriptor object. + """ + full_name = '.'.join((service_name, method_proto.name)) + input_type = self._GetTypeFromScope( + package, method_proto.input_type, scope) + output_type = self._GetTypeFromScope( + package, method_proto.output_type, scope) + return descriptor.MethodDescriptor( + name=method_proto.name, + full_name=full_name, + index=index, + containing_service=None, + input_type=input_type, + output_type=output_type, + client_streaming=method_proto.client_streaming, + server_streaming=method_proto.server_streaming, + options=_OptionsOrNone(method_proto), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _ExtractSymbols(self, descriptors): + """Pulls out all the symbols from descriptor protos. + + Args: + descriptors: The messages to extract descriptors from. + Yields: + A two element tuple of the type name and descriptor object. + """ + + for desc in descriptors: + yield (_PrefixWithDot(desc.full_name), desc) + for symbol in self._ExtractSymbols(desc.nested_types): + yield symbol + for enum in desc.enum_types: + yield (_PrefixWithDot(enum.full_name), enum) + + def _GetDeps(self, dependencies, visited=None): + """Recursively finds dependencies for file protos. + + Args: + dependencies: The names of the files being depended on. + visited: The names of files already found. + + Yields: + Each direct and indirect dependency. + """ + + visited = visited or set() + for dependency in dependencies: + if dependency not in visited: + visited.add(dependency) + dep_desc = self.FindFileByName(dependency) + yield dep_desc + public_files = [d.name for d in dep_desc.public_dependencies] + yield from self._GetDeps(public_files, visited) + + def _GetTypeFromScope(self, package, type_name, scope): + """Finds a given type name in the current scope. + + Args: + package: The package the proto should be located in. + type_name: The name of the type to be found in the scope. + scope: Dict mapping short and full symbols to message and enum types. + + Returns: + The descriptor for the requested type. + """ + if type_name not in scope: + components = _PrefixWithDot(package).split('.') + while components: + possible_match = '.'.join(components + [type_name]) + if possible_match in scope: + type_name = possible_match + break + else: + components.pop(-1) + return scope[type_name] + + +def _PrefixWithDot(name): + return name if name.startswith('.') else '.%s' % name + + +if _USE_C_DESCRIPTORS: + # TODO(amauryfa): This pool could be constructed from Python code, when we + # support a flag like 'use_cpp_generated_pool=True'. + # pylint: disable=protected-access + _DEFAULT = descriptor._message.default_pool +else: + _DEFAULT = DescriptorPool() + + +def Default(): + return _DEFAULT diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/duration_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/duration_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ecc07bdf79992915c3c6dab5e9d8302b5ffb8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/duration_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/duration.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\"*\n\x08\x44uration\x12\x0f\n\x07seconds\x18\x01 \x01(\x03\x12\r\n\x05nanos\x18\x02 \x01(\x05\x42\x83\x01\n\x13\x63om.google.protobufB\rDurationProtoP\x01Z1google.golang.org/protobuf/types/known/durationpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.duration_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\rDurationProtoP\001Z1google.golang.org/protobuf/types/known/durationpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _DURATION._serialized_start=51 + _DURATION._serialized_end=93 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/empty_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/empty_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..0b4d554db317b55bfdaf23f8f6359d836d52337a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/empty_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/empty.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bgoogle/protobuf/empty.proto\x12\x0fgoogle.protobuf\"\x07\n\x05\x45mptyB}\n\x13\x63om.google.protobufB\nEmptyProtoP\x01Z.google.golang.org/protobuf/types/known/emptypb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.empty_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\nEmptyProtoP\001Z.google.golang.org/protobuf/types/known/emptypb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _EMPTY._serialized_start=48 + _EMPTY._serialized_end=55 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/field_mask_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/field_mask_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..80a4e96e598f1b88a4359dbaf7589c1490fed0be --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/field_mask_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/field_mask.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/field_mask.proto\x12\x0fgoogle.protobuf\"\x1a\n\tFieldMask\x12\r\n\x05paths\x18\x01 \x03(\tB\x85\x01\n\x13\x63om.google.protobufB\x0e\x46ieldMaskProtoP\x01Z2google.golang.org/protobuf/types/known/fieldmaskpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.field_mask_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\016FieldMaskProtoP\001Z2google.golang.org/protobuf/types/known/fieldmaskpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _FIELDMASK._serialized_start=53 + _FIELDMASK._serialized_end=79 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/api_implementation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/api_implementation.py new file mode 100644 index 0000000000000000000000000000000000000000..7fef2376707df2419f413c17c8159108134e3b61 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/api_implementation.py @@ -0,0 +1,112 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Determine which implementation of the protobuf API is used in this process. +""" + +import os +import sys +import warnings + +try: + # pylint: disable=g-import-not-at-top + from google.protobuf.internal import _api_implementation + # The compile-time constants in the _api_implementation module can be used to + # switch to a certain implementation of the Python API at build time. + _api_version = _api_implementation.api_version +except ImportError: + _api_version = -1 # Unspecified by compiler flags. + +if _api_version == 1: + raise ValueError('api_version=1 is no longer supported.') + + +_default_implementation_type = ('cpp' if _api_version > 0 else 'python') + + +# This environment variable can be used to switch to a certain implementation +# of the Python API, overriding the compile-time constants in the +# _api_implementation module. Right now only 'python' and 'cpp' are valid +# values. Any other value will be ignored. +_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', + _default_implementation_type) + +if _implementation_type != 'python': + _implementation_type = 'cpp' + +if 'PyPy' in sys.version and _implementation_type == 'cpp': + warnings.warn('PyPy does not work yet with cpp protocol buffers. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + + +# Detect if serialization should be deterministic by default +try: + # The presence of this module in a build allows the proto implementation to + # be upgraded merely via build deps. + # + # NOTE: Merely importing this automatically enables deterministic proto + # serialization for C++ code, but we still need to export it as a boolean so + # that we can do the same for `_implementation_type == 'python'`. + # + # NOTE2: It is possible for C++ code to enable deterministic serialization by + # default _without_ affecting Python code, if the C++ implementation is not in + # use by this module. That is intended behavior, so we don't actually expose + # this boolean outside of this module. + # + # pylint: disable=g-import-not-at-top,unused-import + from google.protobuf import enable_deterministic_proto_serialization + _python_deterministic_proto_serialization = True +except ImportError: + _python_deterministic_proto_serialization = False + + +# Usage of this function is discouraged. Clients shouldn't care which +# implementation of the API is in use. Note that there is no guarantee +# that differences between APIs will be maintained. +# Please don't use this function if possible. +def Type(): + return _implementation_type + + +def _SetType(implementation_type): + """Never use! Only for protobuf benchmark.""" + global _implementation_type + _implementation_type = implementation_type + + +# See comment on 'Type' above. +def Version(): + return 2 + + +# For internal use only +def IsPythonDefaultSerializationDeterministic(): + return _python_deterministic_proto_serialization diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/builder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..64353ee4af6024b9f8ee5991c7d03d377ac3cad5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/builder.py @@ -0,0 +1,130 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Builds descriptors, message classes and services for generated _pb2.py. + +This file is only called in python generated _pb2.py files. It builds +descriptors, message classes and services that users can directly use +in generated code. +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database + +_sym_db = _symbol_database.Default() + + +def BuildMessageAndEnumDescriptors(file_des, module): + """Builds message and enum descriptors. + + Args: + file_des: FileDescriptor of the .proto file + module: Generated _pb2 module + """ + + def BuildNestedDescriptors(msg_des, prefix): + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + module_name = prefix + name.upper() + module[module_name] = nested_msg + BuildNestedDescriptors(nested_msg, module_name + '_') + for enum_des in msg_des.enum_types: + module[prefix + enum_des.name.upper()] = enum_des + + for (name, msg_des) in file_des.message_types_by_name.items(): + module_name = '_' + name.upper() + module[module_name] = msg_des + BuildNestedDescriptors(msg_des, module_name + '_') + + +def BuildTopDescriptorsAndMessages(file_des, module_name, module): + """Builds top level descriptors and message classes. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + + def BuildMessage(msg_des): + create_dict = {} + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + create_dict[name] = BuildMessage(nested_msg) + create_dict['DESCRIPTOR'] = msg_des + create_dict['__module__'] = module_name + message_class = _reflection.GeneratedProtocolMessageType( + msg_des.name, (_message.Message,), create_dict) + _sym_db.RegisterMessage(message_class) + return message_class + + # top level enums + for (name, enum_des) in file_des.enum_types_by_name.items(): + module['_' + name.upper()] = enum_des + module[name] = enum_type_wrapper.EnumTypeWrapper(enum_des) + for enum_value in enum_des.values: + module[enum_value.name] = enum_value.number + + # top level extensions + for (name, extension_des) in file_des.extensions_by_name.items(): + module[name.upper() + '_FIELD_NUMBER'] = extension_des.number + module[name] = extension_des + + # services + for (name, service) in file_des.services_by_name.items(): + module['_' + name.upper()] = service + + # Build messages. + for (name, msg_des) in file_des.message_types_by_name.items(): + module[name] = BuildMessage(msg_des) + + +def BuildServices(file_des, module_name, module): + """Builds services classes and services stub class. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import service as _service + from google.protobuf import service_reflection + # pylint: enable=g-import-not-at-top + for (name, service) in file_des.services_by_name.items(): + module[name] = service_reflection.GeneratedServiceType( + name, (_service.Service,), + dict(DESCRIPTOR=service, __module__=module_name)) + stub_name = name + '_Stub' + module[stub_name] = service_reflection.GeneratedServiceStubType( + stub_name, (module[name],), + dict(DESCRIPTOR=service, __module__=module_name)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/containers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/containers.py new file mode 100644 index 0000000000000000000000000000000000000000..29fbb53d2fce4fffff12a765a52c1083fdfea363 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/containers.py @@ -0,0 +1,710 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains container classes to represent different protocol buffer types. + +This file defines container classes which represent categories of protocol +buffer field types which need extra maintenance. Currently these categories +are: + +- Repeated scalar fields - These are all repeated fields which aren't + composite (e.g. they are of simple types like int32, string, etc). +- Repeated composite fields - Repeated fields which are composite. This + includes groups and nested messages. +""" + +import collections.abc +import copy +import pickle +from typing import ( + Any, + Iterable, + Iterator, + List, + MutableMapping, + MutableSequence, + NoReturn, + Optional, + Sequence, + TypeVar, + Union, + overload, +) + + +_T = TypeVar('_T') +_K = TypeVar('_K') +_V = TypeVar('_V') + + +class BaseContainer(Sequence[_T]): + """Base container class.""" + + # Minimizes memory usage and disallows assignment to other attributes. + __slots__ = ['_message_listener', '_values'] + + def __init__(self, message_listener: Any) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The RepeatedScalarFieldContainer will call this object's + Modified() method when it is modified. + """ + self._message_listener = message_listener + self._values = [] + + @overload + def __getitem__(self, key: int) -> _T: + ... + + @overload + def __getitem__(self, key: slice) -> List[_T]: + ... + + def __getitem__(self, key): + """Retrieves item by the specified key.""" + return self._values[key] + + def __len__(self) -> int: + """Returns the number of elements in the container.""" + return len(self._values) + + def __ne__(self, other: Any) -> bool: + """Checks if another instance isn't equal to this one.""" + # The concrete classes should define __eq__. + return not self == other + + __hash__ = None + + def __repr__(self) -> str: + return repr(self._values) + + def sort(self, *args, **kwargs) -> None: + # Continue to support the old sort_function keyword argument. + # This is expected to be a rare occurrence, so use LBYL to avoid + # the overhead of actually catching KeyError. + if 'sort_function' in kwargs: + kwargs['cmp'] = kwargs.pop('sort_function') + self._values.sort(*args, **kwargs) + + def reverse(self) -> None: + self._values.reverse() + + +# TODO(slebedev): Remove this. BaseContainer does *not* conform to +# MutableSequence, only its subclasses do. +collections.abc.MutableSequence.register(BaseContainer) + + +class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, type-checked, list-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_type_checker'] + + def __init__( + self, + message_listener: Any, + type_checker: Any, + ) -> None: + """Args: + + message_listener: A MessageListener implementation. The + RepeatedScalarFieldContainer will call this object's Modified() method + when it is modified. + type_checker: A type_checkers.ValueChecker instance to run on elements + inserted into this container. + """ + super().__init__(message_listener) + self._type_checker = type_checker + + def append(self, value: _T) -> None: + """Appends an item to the list. Similar to list.append().""" + self._values.append(self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position. Similar to list.insert().""" + self._values.insert(key, self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given iterable. Similar to list.extend().""" + if elem_seq is None: + return + try: + elem_seq_iter = iter(elem_seq) + except TypeError: + if not elem_seq: + # silently ignore falsy inputs :-/. + # TODO(ptucker): Deprecate this behavior. b/18413862 + return + raise + + new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] + if new_values: + self._values.extend(new_values) + self._message_listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one. We do not check the types of the individual fields. + """ + self._values.extend(other) + self._message_listener.Modified() + + def remove(self, elem: _T): + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value) -> None: + """Sets the item on the specified position.""" + if isinstance(key, slice): + if key.step is not None: + raise ValueError('Extended slices not supported') + self._values[key] = map(self._type_checker.CheckValue, value) + self._message_listener.Modified() + else: + self._values[key] = self._type_checker.CheckValue(value) + self._message_listener.Modified() + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + # Special case for the same type which should be common and fast. + if isinstance(other, self.__class__): + return other._values == self._values + # We are presumably comparing against some other sequence type. + return other == self._values + + def __deepcopy__( + self, + unused_memo: Any = None, + ) -> 'RepeatedScalarFieldContainer[_T]': + clone = RepeatedScalarFieldContainer( + copy.deepcopy(self._message_listener), self._type_checker) + clone.MergeFrom(self) + return clone + + def __reduce__(self, **kwargs) -> NoReturn: + raise pickle.PickleError( + "Can't pickle repeated scalar fields, convert to list first") + + +# TODO(slebedev): Constrain T to be a subtype of Message. +class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, list-like container for holding repeated composite fields.""" + + # Disallows assignment to other attributes. + __slots__ = ['_message_descriptor'] + + def __init__(self, message_listener: Any, message_descriptor: Any) -> None: + """ + Note that we pass in a descriptor instead of the generated directly, + since at the time we construct a _RepeatedCompositeFieldContainer we + haven't yet necessarily initialized the type that will be contained in the + container. + + Args: + message_listener: A MessageListener implementation. + The RepeatedCompositeFieldContainer will call this object's + Modified() method when it is modified. + message_descriptor: A Descriptor instance describing the protocol type + that should be present in this container. We'll use the + _concrete_class field of this descriptor when the client calls add(). + """ + super().__init__(message_listener) + self._message_descriptor = message_descriptor + + def add(self, **kwargs: Any) -> _T: + """Adds a new element at the end of the list and returns it. Keyword + arguments may be used to initialize the element. + """ + new_element = self._message_descriptor._concrete_class(**kwargs) + new_element._SetListener(self._message_listener) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + return new_element + + def append(self, value: _T) -> None: + """Appends one element by copying the message.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position by copying.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.insert(key, new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given sequence of elements of the same type + + as this one, copying each individual message. + """ + message_class = self._message_descriptor._concrete_class + listener = self._message_listener + values = self._values + for message in elem_seq: + new_element = message_class() + new_element._SetListener(listener) + new_element.MergeFrom(message) + values.append(new_element) + listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one, copying each individual message. + """ + self.extend(other) + + def remove(self, elem: _T) -> None: + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value): + # This method is implemented to make RepeatedCompositeFieldContainer + # structurally compatible with typing.MutableSequence. It is + # otherwise unsupported and will always raise an error. + raise TypeError( + f'{self.__class__.__name__} object does not support item assignment') + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + if not isinstance(other, self.__class__): + raise TypeError('Can only compare repeated composite fields against ' + 'other repeated composite fields.') + return self._values == other._values + + +class ScalarMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener', + '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + key_checker: Any, + value_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._key_checker = key_checker + self._value_checker = value_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + try: + return self._values[key] + except KeyError: + key = self._key_checker.CheckValue(key) + val = self._value_checker.DefaultValue() + self._values[key] = val + return val + + def __contains__(self, item: _K) -> bool: + # We check the key's type to match the strong-typing flavor of the API. + # Also this makes it easier to match the behavior of the C++ implementation. + self._key_checker.CheckValue(item) + return item in self._values + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __setitem__(self, key: _K, value: _V) -> _T: + checked_key = self._key_checker.CheckValue(key) + checked_value = self._value_checker.CheckValue(value) + self._values[checked_key] = checked_value + self._message_listener.Modified() + + def __delitem__(self, key: _K) -> None: + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None: + self._values.update(other._values) + self._message_listener.Modified() + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class MessageMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for with submessage values.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_values', '_message_listener', + '_message_descriptor', '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + message_descriptor: Any, + key_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._message_descriptor = message_descriptor + self._key_checker = key_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + key = self._key_checker.CheckValue(key) + try: + return self._values[key] + except KeyError: + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + self._values[key] = new_element + self._message_listener.Modified() + return new_element + + def get_or_create(self, key: _K) -> _V: + """get_or_create() is an alias for getitem (ie. map[key]). + + Args: + key: The key to get or create in the map. + + This is useful in cases where you want to be explicit that the call is + mutating the map. This can avoid lint errors for statements like this + that otherwise would appear to be pointless statements: + + msg.my_map[key] + """ + return self[key] + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __contains__(self, item: _K) -> bool: + item = self._key_checker.CheckValue(item) + return item in self._values + + def __setitem__(self, key: _K, value: _V) -> NoReturn: + raise ValueError('May not set values directly, call my_map[key].foo = 5') + + def __delitem__(self, key: _K) -> None: + key = self._key_checker.CheckValue(key) + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None: + # pylint: disable=protected-access + for key in other._values: + # According to documentation: "When parsing from the wire or when merging, + # if there are duplicate map keys the last key seen is used". + if key in self: + del self[key] + self[key].CopyFrom(other[key]) + # self._message_listener.Modified() not required here, because + # mutations to submessages already propagate. + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class _UnknownField: + """A parsed unknown field.""" + + # Disallows assignment to other attributes. + __slots__ = ['_field_number', '_wire_type', '_data'] + + def __init__(self, field_number, wire_type, data): + self._field_number = field_number + self._wire_type = wire_type + self._data = data + return + + def __lt__(self, other): + # pylint: disable=protected-access + return self._field_number < other._field_number + + def __eq__(self, other): + if self is other: + return True + # pylint: disable=protected-access + return (self._field_number == other._field_number and + self._wire_type == other._wire_type and + self._data == other._data) + + +class UnknownFieldRef: # pylint: disable=missing-class-docstring + + def __init__(self, parent, index): + self._parent = parent + self._index = index + + def _check_valid(self): + if not self._parent: + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + if self._index >= len(self._parent): + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + + @property + def field_number(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._field_number + + @property + def wire_type(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._wire_type + + @property + def data(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._data + + +class UnknownFieldSet: + """UnknownField container""" + + # Disallows assignment to other attributes. + __slots__ = ['_values'] + + def __init__(self): + self._values = [] + + def __getitem__(self, index): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + size = len(self._values) + if index < 0: + index += size + if index < 0 or index >= size: + raise IndexError('index %d out of range'.index) + + return UnknownFieldRef(self, index) + + def _internal_get(self, index): + return self._values[index] + + def __len__(self): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + return len(self._values) + + def _add(self, field_number, wire_type, data): + unknown_field = _UnknownField(field_number, wire_type, data) + self._values.append(unknown_field) + return unknown_field + + def __iter__(self): + for i in range(len(self)): + yield UnknownFieldRef(self, i) + + def _extend(self, other): + if other is None: + return + # pylint: disable=protected-access + self._values.extend(other._values) + + def __eq__(self, other): + if self is other: + return True + # Sort unknown fields because their order shouldn't + # affect equality test. + values = list(self._values) + if other is None: + return not values + values.sort() + # pylint: disable=protected-access + other_values = sorted(other._values) + return values == other_values + + def _clear(self): + for value in self._values: + # pylint: disable=protected-access + if isinstance(value._data, UnknownFieldSet): + value._data._clear() # pylint: disable=protected-access + self._values = None diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/decoder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1b7b785cf0f6b001db2a650eb0eac15a2eb82b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/decoder.py @@ -0,0 +1,1029 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Code for decoding protocol buffer primitives. + +This code is very similar to encoder.py -- read the docs for that module first. + +A "decoder" is a function with the signature: + Decode(buffer, pos, end, message, field_dict) +The arguments are: + buffer: The string containing the encoded message. + pos: The current position in the string. + end: The position in the string where the current message ends. May be + less than len(buffer) if we're reading a sub-message. + message: The message object into which we're parsing. + field_dict: message._fields (avoids a hashtable lookup). +The decoder reads the field and stores it into field_dict, returning the new +buffer position. A decoder for a repeated field may proactively decode all of +the elements of that field, if they appear consecutively. + +Note that decoders may throw any of the following: + IndexError: Indicates a truncated message. + struct.error: Unpacking of a fixed-width field failed. + message.DecodeError: Other errors. + +Decoders are expected to raise an exception if they are called with pos > end. +This allows callers to be lax about bounds checking: it's fineto read past +"end" as long as you are sure that someone else will notice and throw an +exception later on. + +Something up the call stack is expected to catch IndexError and struct.error +and convert them to message.DecodeError. + +Decoders are constructed using decoder constructors with the signature: + MakeDecoder(field_number, is_repeated, is_packed, key, new_default) +The arguments are: + field_number: The field number of the field we want to decode. + is_repeated: Is the field a repeated field? (bool) + is_packed: Is the field a packed field? (bool) + key: The key to use when looking up the field within field_dict. + (This is actually the FieldDescriptor but nothing in this + file should depend on that.) + new_default: A function which takes a message object as a parameter and + returns a new instance of the default value for this field. + (This is called for repeated fields and sub-messages, when an + instance does not already exist.) + +As with encoders, we define a decoder constructor for every type of field. +Then, for every field of every message class we construct an actual decoder. +That decoder goes into a dict indexed by tag, so when we decode a message +we repeatedly read a tag, look up the corresponding decoder, and invoke it. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import math +import struct + +from google.protobuf.internal import containers +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format +from google.protobuf import message + + +# This is not for optimization, but rather to avoid conflicts with local +# variables named "message". +_DecodeError = message.DecodeError + + +def _VarintDecoder(mask, result_type): + """Return an encoder for a basic varint value (does not include tag). + + Decoded values will be bitwise-anded with the given mask before being + returned, e.g. to limit them to 32 bits. The returned decoder does not + take the usual "end" parameter -- the caller is expected to do bounds checking + after the fact (often the caller can defer such checking until later). The + decoder returns a (value, new_pos) pair. + """ + + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + result &= mask + result = result_type(result) + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + + +def _SignedVarintDecoder(bits, result_type): + """Like _VarintDecoder() but decodes signed values.""" + + signbit = 1 << (bits - 1) + mask = (1 << bits) - 1 + + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + result &= mask + result = (result ^ signbit) - signbit + result = result_type(result) + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + +# All 32-bit and 64-bit values are represented as int. +_DecodeVarint = _VarintDecoder((1 << 64) - 1, int) +_DecodeSignedVarint = _SignedVarintDecoder(64, int) + +# Use these versions for values which must be limited to 32 bits. +_DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int) +_DecodeSignedVarint32 = _SignedVarintDecoder(32, int) + + +def ReadTag(buffer, pos): + """Read a tag from the memoryview, and return a (tag_bytes, new_pos) tuple. + + We return the raw bytes of the tag rather than decoding them. The raw + bytes can then be used to look up the proper decoder. This effectively allows + us to trade some work that would be done in pure-python (decoding a varint) + for work that is done in C (searching for a byte string in a hash table). + In a low-level language it would be much cheaper to decode the varint and + use that, but not in Python. + + Args: + buffer: memoryview object of the encoded bytes + pos: int of the current position to start from + + Returns: + Tuple[bytes, int] of the tag data and new position. + """ + start = pos + while buffer[pos] & 0x80: + pos += 1 + pos += 1 + + tag_bytes = buffer[start:pos].tobytes() + return tag_bytes, pos + + +# -------------------------------------------------------------------- + + +def _SimpleDecoder(wire_type, decode_value): + """Return a constructor for a decoder for fields of a particular type. + + Args: + wire_type: The field's wire type. + decode_value: A function which decodes an individual value, e.g. + _DecodeVarint() + """ + + def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + if is_packed: + local_DecodeVarint = _DecodeVarint + def DecodePackedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + (endpoint, pos) = local_DecodeVarint(buffer, pos) + endpoint += pos + if endpoint > end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + (element, pos) = decode_value(buffer, pos) + value.append(element) + if pos > endpoint: + del value[-1] # Discard corrupt value. + raise _DecodeError('Packed element was truncated.') + return pos + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_type) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = decode_value(buffer, pos) + value.append(element) + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (new_value, pos) = decode_value(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and not new_value: + field_dict.pop(key, None) + else: + field_dict[key] = new_value + return pos + return DecodeField + + return SpecificDecoder + + +def _ModifiedDecoder(wire_type, decode_value, modify_value): + """Like SimpleDecoder but additionally invokes modify_value on every value + before storing it. Usually modify_value is ZigZagDecode. + """ + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + def InnerDecode(buffer, pos): + (result, new_pos) = decode_value(buffer, pos) + return (modify_value(result), new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _StructPackDecoder(wire_type, format): + """Return a constructor for a decoder for a fixed-width field. + + Args: + wire_type: The field's wire type. + format: The format string to pass to struct.unpack(). + """ + + value_size = struct.calcsize(format) + local_unpack = struct.unpack + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + + def InnerDecode(buffer, pos): + new_pos = pos + value_size + result = local_unpack(format, buffer[pos:new_pos])[0] + return (result, new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _FloatDecoder(): + """Returns a decoder for a float field. + + This code works around a bug in struct.unpack for non-finite 32-bit + floating-point values. + """ + + local_unpack = struct.unpack + + def InnerDecode(buffer, pos): + """Decode serialized float to a float and new position. + + Args: + buffer: memoryview of the serialized bytes + pos: int, position in the memory view to start at. + + Returns: + Tuple[float, int] of the deserialized float value and new position + in the serialized data. + """ + # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign + # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. + new_pos = pos + 4 + float_bytes = buffer[pos:new_pos].tobytes() + + # If this value has all its exponent bits set, then it's non-finite. + # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. + # To avoid that, we parse it specially. + if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'): + # If at least one significand bit is set... + if float_bytes[0:3] != b'\x00\x00\x80': + return (math.nan, new_pos) + # If sign bit is set... + if float_bytes[3:4] == b'\xFF': + return (-math.inf, new_pos) + return (math.inf, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack('= b'\xF0') + and (double_bytes[0:7] != b'\x00\x00\x00\x00\x00\x00\xF0')): + return (math.nan, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack(' end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + value_start_pos = pos + (element, pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + if message._unknown_field_set is None: + message._unknown_field_set = containers.UnknownFieldSet() + message._unknown_field_set._add( + field_number, wire_format.WIRETYPE_VARINT, element) + # pylint: enable=protected-access + if pos > endpoint: + if element in enum_type.values_by_number: + del value[-1] # Discard corrupt value. + else: + del message._unknown_fields[-1] + # pylint: disable=protected-access + del message._unknown_field_set._values[-1] + # pylint: enable=protected-access + raise _DecodeError('Packed element was truncated.') + return pos + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (tag_bytes, buffer[pos:new_pos].tobytes())) + if message._unknown_field_set is None: + message._unknown_field_set = containers.UnknownFieldSet() + message._unknown_field_set._add( + field_number, wire_format.WIRETYPE_VARINT, element) + # pylint: enable=protected-access + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + value_start_pos = pos + (enum_value, pos) = _DecodeSignedVarint32(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and not enum_value: + field_dict.pop(key, None) + return pos + # pylint: disable=protected-access + if enum_value in enum_type.values_by_number: + field_dict[key] = enum_value + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + if message._unknown_field_set is None: + message._unknown_field_set = containers.UnknownFieldSet() + message._unknown_field_set._add( + field_number, wire_format.WIRETYPE_VARINT, enum_value) + # pylint: enable=protected-access + return pos + return DecodeField + + +# -------------------------------------------------------------------- + + +Int32Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32) + +Int64Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint) + +UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32) +UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint) + +SInt32Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode) +SInt64Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, ' end: + raise _DecodeError('Truncated string.') + value.append(_ConvertToUnicode(buffer[pos:new_pos])) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and not size: + field_dict.pop(key, None) + else: + field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos]) + return new_pos + return DecodeField + + +def BytesDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + """Returns a decoder for a bytes field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + value.append(buffer[pos:new_pos].tobytes()) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and not size: + field_dict.pop(key, None) + else: + field_dict[key] = buffer[pos:new_pos].tobytes() + return new_pos + return DecodeField + + +def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a group field.""" + + end_tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_END_GROUP) + end_tag_len = len(end_tag_bytes) + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_START_GROUP) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + pos = value.add()._InternalParse(buffer, pos, end) + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + pos = value._InternalParse(buffer, pos, end) + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + return new_pos + return DecodeField + + +def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a message field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + if value.add()._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + if value._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + return new_pos + return DecodeField + + +# -------------------------------------------------------------------- + +MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP) + +def MessageSetItemDecoder(descriptor): + """Returns a decoder for a MessageSet item. + + The parameter is the message Descriptor. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + local_ReadTag = ReadTag + local_DecodeVarint = _DecodeVarint + local_SkipField = SkipField + + def DecodeItem(buffer, pos, end, message, field_dict): + """Decode serialized message set to its value and new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + message_set_item_start = pos + type_id = -1 + message_start = -1 + message_end = -1 + + # Technically, type_id and message can appear in any order, so we need + # a little loop here. + while 1: + (tag_bytes, pos) = local_ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = local_DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = local_DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + pos = SkipField(buffer, pos, end, tag_bytes) + if pos == -1: + raise _DecodeError('Missing group end tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + extension = message.Extensions._FindExtensionByNumber(type_id) + # pylint: disable=protected-access + if extension is not None: + value = field_dict.get(extension) + if value is None: + message_type = extension.message_type + if not hasattr(message_type, '_concrete_class'): + # pylint: disable=protected-access + message._FACTORY.GetPrototype(message_type) + value = field_dict.setdefault( + extension, message_type._concrete_class()) + if value._InternalParse(buffer, message_start,message_end) != message_end: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes())) + if message._unknown_field_set is None: + message._unknown_field_set = containers.UnknownFieldSet() + message._unknown_field_set._add( + type_id, + wire_format.WIRETYPE_LENGTH_DELIMITED, + buffer[message_start:message_end].tobytes()) + # pylint: enable=protected-access + + return pos + + return DecodeItem + +# -------------------------------------------------------------------- + +def MapDecoder(field_descriptor, new_default, is_message_map): + """Returns a decoder for a map field.""" + + key = field_descriptor + tag_bytes = encoder.TagBytes(field_descriptor.number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + local_DecodeVarint = _DecodeVarint + # Can't read _concrete_class yet; might not be initialized. + message_type = field_descriptor.message_type + + def DecodeMap(buffer, pos, end, message, field_dict): + submsg = message_type._concrete_class() + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + submsg.Clear() + if submsg._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + + if is_message_map: + value[submsg.key].CopyFrom(submsg.value) + else: + value[submsg.key] = submsg.value + + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeMap + +# -------------------------------------------------------------------- +# Optimization is not as heavy here because calls to SkipField() are rare, +# except for handling end-group tags. + +def _SkipVarint(buffer, pos, end): + """Skip a varint value. Returns the new position.""" + # Previously ord(buffer[pos]) raised IndexError when pos is out of range. + # With this code, ord(b'') raises TypeError. Both are handled in + # python_message.py to generate a 'Truncated message' error. + while ord(buffer[pos:pos+1].tobytes()) & 0x80: + pos += 1 + pos += 1 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + +def _SkipFixed64(buffer, pos, end): + """Skip a fixed64 value. Returns the new position.""" + + pos += 8 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + + +def _DecodeFixed64(buffer, pos): + """Decode a fixed64.""" + new_pos = pos + 8 + return (struct.unpack(' end: + raise _DecodeError('Truncated message.') + return pos + + +def _SkipGroup(buffer, pos, end): + """Skip sub-group. Returns the new position.""" + + while 1: + (tag_bytes, pos) = ReadTag(buffer, pos) + new_pos = SkipField(buffer, pos, end, tag_bytes) + if new_pos == -1: + return pos + pos = new_pos + + +def _DecodeUnknownFieldSet(buffer, pos, end_pos=None): + """Decode UnknownFieldSet. Returns the UnknownFieldSet and new position.""" + + unknown_field_set = containers.UnknownFieldSet() + while end_pos is None or pos < end_pos: + (tag_bytes, pos) = ReadTag(buffer, pos) + (tag, _) = _DecodeVarint(tag_bytes, 0) + field_number, wire_type = wire_format.UnpackTag(tag) + if wire_type == wire_format.WIRETYPE_END_GROUP: + break + (data, pos) = _DecodeUnknownField(buffer, pos, wire_type) + # pylint: disable=protected-access + unknown_field_set._add(field_number, wire_type, data) + + return (unknown_field_set, pos) + + +def _DecodeUnknownField(buffer, pos, wire_type): + """Decode a unknown field. Returns the UnknownField and new position.""" + + if wire_type == wire_format.WIRETYPE_VARINT: + (data, pos) = _DecodeVarint(buffer, pos) + elif wire_type == wire_format.WIRETYPE_FIXED64: + (data, pos) = _DecodeFixed64(buffer, pos) + elif wire_type == wire_format.WIRETYPE_FIXED32: + (data, pos) = _DecodeFixed32(buffer, pos) + elif wire_type == wire_format.WIRETYPE_LENGTH_DELIMITED: + (size, pos) = _DecodeVarint(buffer, pos) + data = buffer[pos:pos+size].tobytes() + pos += size + elif wire_type == wire_format.WIRETYPE_START_GROUP: + (data, pos) = _DecodeUnknownFieldSet(buffer, pos) + elif wire_type == wire_format.WIRETYPE_END_GROUP: + return (0, -1) + else: + raise _DecodeError('Wrong wire type in tag.') + + return (data, pos) + + +def _EndGroup(buffer, pos, end): + """Skipping an END_GROUP tag returns -1 to tell the parent loop to break.""" + + return -1 + + +def _SkipFixed32(buffer, pos, end): + """Skip a fixed32 value. Returns the new position.""" + + pos += 4 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + + +def _DecodeFixed32(buffer, pos): + """Decode a fixed32.""" + + new_pos = pos + 4 + return (struct.unpack('B').pack + + def EncodeVarint(write, value, unused_deterministic=None): + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeVarint + + +def _SignedVarintEncoder(): + """Return an encoder for a basic signed varint value (does not include + tag).""" + + local_int2byte = struct.Struct('>B').pack + + def EncodeSignedVarint(write, value, unused_deterministic=None): + if value < 0: + value += (1 << 64) + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeSignedVarint + + +_EncodeVarint = _VarintEncoder() +_EncodeSignedVarint = _SignedVarintEncoder() + + +def _VarintBytes(value): + """Encode the given integer as a varint and return the bytes. This is only + called at startup time so it doesn't need to be fast.""" + + pieces = [] + _EncodeVarint(pieces.append, value, True) + return b"".join(pieces) + + +def TagBytes(field_number, wire_type): + """Encode the given tag and return the bytes. Only called at startup.""" + + return bytes(_VarintBytes(wire_format.PackTag(field_number, wire_type))) + +# -------------------------------------------------------------------- +# As with sizers (see above), we have a number of common encoder +# implementations. + + +def _SimpleEncoder(wire_type, encode_value, compute_value_size): + """Return a constructor for an encoder for fields of a particular type. + + Args: + wire_type: The field's wire type, for encoding tags. + encode_value: A function which encodes an individual value, e.g. + _EncodeVarint(). + compute_value_size: A function which computes the size of an individual + value, e.g. _VarintSize(). + """ + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(element) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, element, deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, element, deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, value, deterministic) + return EncodeField + + return SpecificEncoder + + +def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value): + """Like SimpleEncoder but additionally invokes modify_value on every value + before passing it to encode_value. Usually modify_value is ZigZagEncode.""" + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(modify_value(element)) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, modify_value(element), deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, modify_value(element), deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, modify_value(value), deterministic) + return EncodeField + + return SpecificEncoder + + +def _StructPackEncoder(wire_type, format): + """Return a constructor for an encoder for a fixed-width field. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + write(local_struct_pack(format, element)) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + write(local_struct_pack(format, element)) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + return write(local_struct_pack(format, value)) + return EncodeField + + return SpecificEncoder + + +def _FloatingPointEncoder(wire_type, format): + """Return a constructor for an encoder for float fields. + + This is like StructPackEncoder, but catches errors that may be due to + passing non-finite floating-point values to struct.pack, and makes a + second attempt to encode those values. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + if value_size == 4: + def EncodeNonFiniteOrRaise(write, value): + # Remember that the serialized form uses little-endian byte order. + if value == _POS_INF: + write(b'\x00\x00\x80\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x80\xFF') + elif value != value: # NaN + write(b'\x00\x00\xC0\x7F') + else: + raise + elif value_size == 8: + def EncodeNonFiniteOrRaise(write, value): + if value == _POS_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF') + elif value != value: # NaN + write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F') + else: + raise + else: + raise ValueError('Can\'t encode floating-point values that are ' + '%d bytes long (only 4 or 8)' % value_size) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + # This try/except block is going to be faster than any code that + # we could write to check whether element is finite. + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + try: + write(local_struct_pack(format, value)) + except SystemError: + EncodeNonFiniteOrRaise(write, value) + return EncodeField + + return SpecificEncoder + + +# ==================================================================== +# Here we declare an encoder constructor for each field type. These work +# very similarly to sizer constructors, described earlier. + + +Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize) + +UInt32Encoder = UInt64Encoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize) + +SInt32Encoder = SInt64Encoder = _ModifiedEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize, + wire_format.ZigZagEncode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, ' str + ValueType = int + + def __init__(self, enum_type): + """Inits EnumTypeWrapper with an EnumDescriptor.""" + self._enum_type = enum_type + self.DESCRIPTOR = enum_type # pylint: disable=invalid-name + + def Name(self, number): # pylint: disable=invalid-name + """Returns a string containing the name of an enum value.""" + try: + return self._enum_type.values_by_number[number].name + except KeyError: + pass # fall out to break exception chaining + + if not isinstance(number, int): + raise TypeError( + 'Enum value for {} must be an int, but got {} {!r}.'.format( + self._enum_type.name, type(number), number)) + else: + # repr here to handle the odd case when you pass in a boolean. + raise ValueError('Enum {} has no name defined for value {!r}'.format( + self._enum_type.name, number)) + + def Value(self, name): # pylint: disable=invalid-name + """Returns the value corresponding to the given enum name.""" + try: + return self._enum_type.values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise ValueError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) + + def keys(self): + """Return a list of the string names in the enum. + + Returns: + A list of strs, in the order they were defined in the .proto file. + """ + + return [value_descriptor.name + for value_descriptor in self._enum_type.values] + + def values(self): + """Return a list of the integer values in the enum. + + Returns: + A list of ints, in the order they were defined in the .proto file. + """ + + return [value_descriptor.number + for value_descriptor in self._enum_type.values] + + def items(self): + """Return a list of the (name, value) pairs of the enum. + + Returns: + A list of (str, int) pairs, in the order they were defined + in the .proto file. + """ + return [(value_descriptor.name, value_descriptor.number) + for value_descriptor in self._enum_type.values] + + def __getattr__(self, name): + """Returns the value corresponding to the given enum name.""" + try: + return super( + EnumTypeWrapper, + self).__getattribute__('_enum_type').values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise AttributeError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/extension_dict.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/extension_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..b346cf283e2ca7d76306d99ecf153d61709fd1ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/extension_dict.py @@ -0,0 +1,213 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains _ExtensionDict class to represent extensions. +""" + +from google.protobuf.internal import type_checkers +from google.protobuf.descriptor import FieldDescriptor + + +def _VerifyExtensionHandle(message, extension_handle): + """Verify that the given extension handle is valid.""" + + if not isinstance(extension_handle, FieldDescriptor): + raise KeyError('HasExtension() expects an extension handle, got: %s' % + extension_handle) + + if not extension_handle.is_extension: + raise KeyError('"%s" is not an extension.' % extension_handle.full_name) + + if not extension_handle.containing_type: + raise KeyError('"%s" is missing a containing_type.' + % extension_handle.full_name) + + if extension_handle.containing_type is not message.DESCRIPTOR: + raise KeyError('Extension "%s" extends message type "%s", but this ' + 'message is of type "%s".' % + (extension_handle.full_name, + extension_handle.containing_type.full_name, + message.DESCRIPTOR.full_name)) + + +# TODO(robinson): Unify error handling of "unknown extension" crap. +# TODO(robinson): Support iteritems()-style iteration over all +# extensions with the "has" bits turned on? +class _ExtensionDict(object): + + """Dict-like container for Extension fields on proto instances. + + Note that in all cases we expect extension handles to be + FieldDescriptors. + """ + + def __init__(self, extended_message): + """ + Args: + extended_message: Message instance for which we are the Extensions dict. + """ + self._extended_message = extended_message + + def __getitem__(self, extension_handle): + """Returns the current value of the given extension handle.""" + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + result = self._extended_message._fields.get(extension_handle) + if result is not None: + return result + + if extension_handle.label == FieldDescriptor.LABEL_REPEATED: + result = extension_handle._default_constructor(self._extended_message) + elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + message_type = extension_handle.message_type + if not hasattr(message_type, '_concrete_class'): + # pylint: disable=protected-access + self._extended_message._FACTORY.GetPrototype(message_type) + assert getattr(extension_handle.message_type, '_concrete_class', None), ( + 'Uninitialized concrete class found for field %r (message type %r)' + % (extension_handle.full_name, + extension_handle.message_type.full_name)) + result = extension_handle.message_type._concrete_class() + try: + result._SetListener(self._extended_message._listener_for_children) + except ReferenceError: + pass + else: + # Singular scalar -- just return the default without inserting into the + # dict. + return extension_handle.default_value + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + result = self._extended_message._fields.setdefault( + extension_handle, result) + + return result + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + + my_fields = self._extended_message.ListFields() + other_fields = other._extended_message.ListFields() + + # Get rid of non-extension fields. + my_fields = [field for field in my_fields if field.is_extension] + other_fields = [field for field in other_fields if field.is_extension] + + return my_fields == other_fields + + def __ne__(self, other): + return not self == other + + def __len__(self): + fields = self._extended_message.ListFields() + # Get rid of non-extension fields. + extension_fields = [field for field in fields if field[0].is_extension] + return len(extension_fields) + + def __hash__(self): + raise TypeError('unhashable object') + + # Note that this is only meaningful for non-repeated, scalar extension + # fields. Note also that we may have to call _Modified() when we do + # successfully set a field this way, to set any necessary "has" bits in the + # ancestors of the extended message. + def __setitem__(self, extension_handle, value): + """If extension_handle specifies a non-repeated, scalar extension + field, sets the value of that field. + """ + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if (extension_handle.label == FieldDescriptor.LABEL_REPEATED or + extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE): + raise TypeError( + 'Cannot assign to extension "%s" because it is a repeated or ' + 'composite type.' % extension_handle.full_name) + + # It's slightly wasteful to lookup the type checker each time, + # but we expect this to be a vanishingly uncommon case anyway. + type_checker = type_checkers.GetTypeChecker(extension_handle) + # pylint: disable=protected-access + self._extended_message._fields[extension_handle] = ( + type_checker.CheckValue(value)) + self._extended_message._Modified() + + def __delitem__(self, extension_handle): + self._extended_message.ClearExtension(extension_handle) + + def _FindExtensionByName(self, name): + """Tries to find a known extension with the specified name. + + Args: + name: Extension full name. + + Returns: + Extension field descriptor. + """ + return self._extended_message._extensions_by_name.get(name, None) + + def _FindExtensionByNumber(self, number): + """Tries to find a known extension with the field number. + + Args: + number: Extension field number. + + Returns: + Extension field descriptor. + """ + return self._extended_message._extensions_by_number.get(number, None) + + def __iter__(self): + # Return a generator over the populated extension fields + return (f[0] for f in self._extended_message.ListFields() + if f[0].is_extension) + + def __contains__(self, extension_handle): + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if extension_handle not in self._extended_message._fields: + return False + + if extension_handle.label == FieldDescriptor.LABEL_REPEATED: + return bool(self._extended_message._fields.get(extension_handle)) + + if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + value = self._extended_message._fields.get(extension_handle) + # pylint: disable=protected-access + return value is not None and value._is_present_in_parent + + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/message_listener.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/message_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc255a774563473edb7c0c4315d5a60a98b419a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/message_listener.py @@ -0,0 +1,78 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Defines a listener interface for observing certain +state transitions on Message objects. + +Also defines a null implementation of this interface. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +class MessageListener(object): + + """Listens for modifications made to a message. Meant to be registered via + Message._SetListener(). + + Attributes: + dirty: If True, then calling Modified() would be a no-op. This can be + used to avoid these calls entirely in the common case. + """ + + def Modified(self): + """Called every time the message is modified in such a way that the parent + message may need to be updated. This currently means either: + (a) The message was modified for the first time, so the parent message + should henceforth mark the message as present. + (b) The message's cached byte size became dirty -- i.e. the message was + modified for the first time after a previous call to ByteSize(). + Therefore the parent should also mark its byte size as dirty. + Note that (a) implies (b), since new objects start out with a client cached + size (zero). However, we document (a) explicitly because it is important. + + Modified() will *only* be called in response to one of these two events -- + not every time the sub-message is modified. + + Note that if the listener's |dirty| attribute is true, then calling + Modified at the moment would be a no-op, so it can be skipped. Performance- + sensitive callers should check this attribute directly before calling since + it will be true most of the time. + """ + + raise NotImplementedError + + +class NullMessageListener(object): + + """No-op MessageListener implementation.""" + + def Modified(self): + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/python_message.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/python_message.py new file mode 100644 index 0000000000000000000000000000000000000000..2921d5cb6ef197bb89f8aa81ab9368e04762a29b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/python_message.py @@ -0,0 +1,1539 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This code is meant to work on Python 2.4 and above only. +# +# TODO(robinson): Helpers for verbose, common checks like seeing if a +# descriptor's cpp_type is CPPTYPE_MESSAGE. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +from io import BytesIO +import struct +import sys +import weakref + +# We use "as" to avoid name collisions with variables. +from google.protobuf.internal import api_implementation +from google.protobuf.internal import containers +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import enum_type_wrapper +from google.protobuf.internal import extension_dict +from google.protobuf.internal import message_listener as message_listener_mod +from google.protobuf.internal import type_checkers +from google.protobuf.internal import well_known_types +from google.protobuf.internal import wire_format +from google.protobuf import descriptor as descriptor_mod +from google.protobuf import message as message_mod +from google.protobuf import text_format + +_FieldDescriptor = descriptor_mod.FieldDescriptor +_AnyFullTypeName = 'google.protobuf.Any' +_ExtensionDict = extension_dict._ExtensionDict + +class GeneratedProtocolMessageType(type): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + We add implementations for all methods described in the Message class. We + also create properties to allow getting/setting all fields in the protocol + message. Finally, we create slots to prevent users from accidentally + "setting" nonexistent fields in the protocol message, which then wouldn't get + serialized / deserialized properly. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = factory.GetPrototype(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __new__(cls, name, bases, dictionary): + """Custom allocation for runtime-generated class types. + + We override __new__ because this is apparently the only place + where we can meaningfully set __slots__ on the class we're creating(?). + (The interplay between metaclasses and slots is not very well-documented). + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + + Returns: + Newly-allocated class. + + Raises: + RuntimeError: Generated code only work with python cpp extension. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + if isinstance(descriptor, str): + raise RuntimeError('The generated code only work with python cpp ' + 'extension, but it is using pure python runtime.') + + # If a concrete class already exists for this descriptor, don't try to + # create another. Doing so will break any messages that already exist with + # the existing class. + # + # The C++ implementation appears to have its own internal `PyMessageFactory` + # to achieve similar results. + # + # This most commonly happens in `text_format.py` when using descriptors from + # a custom pool; it calls symbol_database.Global().getPrototype() on a + # descriptor which already has an existing concrete class. + new_class = getattr(descriptor, '_concrete_class', None) + if new_class: + return new_class + + if descriptor.full_name in well_known_types.WKTBASES: + bases += (well_known_types.WKTBASES[descriptor.full_name],) + _AddClassAttributesForNestedExtensions(descriptor, dictionary) + _AddSlots(descriptor, dictionary) + + superclass = super(GeneratedProtocolMessageType, cls) + new_class = superclass.__new__(cls, name, bases, dictionary) + return new_class + + def __init__(cls, name, bases, dictionary): + """Here we perform the majority of our work on the class. + We add enum getters, an __init__ method, implementations + of all Message methods, and properties for all fields + in the protocol type. + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + # If this is an _existing_ class looked up via `_concrete_class` in the + # __new__ method above, then we don't need to re-initialize anything. + existing_class = getattr(descriptor, '_concrete_class', None) + if existing_class: + assert existing_class is cls, ( + 'Duplicate `GeneratedProtocolMessageType` created for descriptor %r' + % (descriptor.full_name)) + return + + cls._decoders_by_tag = {} + if (descriptor.has_options and + descriptor.GetOptions().message_set_wire_format): + cls._decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = ( + decoder.MessageSetItemDecoder(descriptor), None) + + # Attach stuff to each FieldDescriptor for quick lookup later on. + for field in descriptor.fields: + _AttachFieldHelpers(cls, field) + + descriptor._concrete_class = cls # pylint: disable=protected-access + _AddEnumValues(descriptor, cls) + _AddInitMethod(descriptor, cls) + _AddPropertiesForFields(descriptor, cls) + _AddPropertiesForExtensions(descriptor, cls) + _AddStaticMethods(cls) + _AddMessageMethods(descriptor, cls) + _AddPrivateHelperMethods(descriptor, cls) + + superclass = super(GeneratedProtocolMessageType, cls) + superclass.__init__(name, bases, dictionary) + + +# Stateless helpers for GeneratedProtocolMessageType below. +# Outside clients should not access these directly. +# +# I opted not to make any of these methods on the metaclass, to make it more +# clear that I'm not really using any state there and to keep clients from +# thinking that they have direct access to these construction helpers. + + +def _PropertyName(proto_field_name): + """Returns the name of the public property attribute which + clients can use to get and (in some cases) set the value + of a protocol message field. + + Args: + proto_field_name: The protocol message field name, exactly + as it appears (or would appear) in a .proto file. + """ + # TODO(robinson): Escape Python keywords (e.g., yield), and test this support. + # nnorwitz makes my day by writing: + # """ + # FYI. See the keyword module in the stdlib. This could be as simple as: + # + # if keyword.iskeyword(proto_field_name): + # return proto_field_name + "_" + # return proto_field_name + # """ + # Kenton says: The above is a BAD IDEA. People rely on being able to use + # getattr() and setattr() to reflectively manipulate field values. If we + # rename the properties, then every such user has to also make sure to apply + # the same transformation. Note that currently if you name a field "yield", + # you can still access it just fine using getattr/setattr -- it's not even + # that cumbersome to do so. + # TODO(kenton): Remove this method entirely if/when everyone agrees with my + # position. + return proto_field_name + + +def _AddSlots(message_descriptor, dictionary): + """Adds a __slots__ entry to dictionary, containing the names of all valid + attributes for this message type. + + Args: + message_descriptor: A Descriptor instance describing this message type. + dictionary: Class dictionary to which we'll add a '__slots__' entry. + """ + dictionary['__slots__'] = ['_cached_byte_size', + '_cached_byte_size_dirty', + '_fields', + '_unknown_fields', + '_unknown_field_set', + '_is_present_in_parent', + '_listener', + '_listener_for_children', + '__weakref__', + '_oneofs'] + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == _FieldDescriptor.TYPE_MESSAGE and + field.label == _FieldDescriptor.LABEL_OPTIONAL) + + +def _IsMapField(field): + return (field.type == _FieldDescriptor.TYPE_MESSAGE and + field.message_type.has_options and + field.message_type.GetOptions().map_entry) + + +def _IsMessageMapField(field): + value_type = field.message_type.fields_by_name['value'] + return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE + + +def _AttachFieldHelpers(cls, field_descriptor): + is_repeated = (field_descriptor.label == _FieldDescriptor.LABEL_REPEATED) + is_packable = (is_repeated and + wire_format.IsTypePackable(field_descriptor.type)) + is_proto3 = field_descriptor.containing_type.syntax == 'proto3' + if not is_packable: + is_packed = False + elif field_descriptor.containing_type.syntax == 'proto2': + is_packed = (field_descriptor.has_options and + field_descriptor.GetOptions().packed) + else: + has_packed_false = (field_descriptor.has_options and + field_descriptor.GetOptions().HasField('packed') and + field_descriptor.GetOptions().packed == False) + is_packed = not has_packed_false + is_map_entry = _IsMapField(field_descriptor) + + if is_map_entry: + field_encoder = encoder.MapEncoder(field_descriptor) + sizer = encoder.MapSizer(field_descriptor, + _IsMessageMapField(field_descriptor)) + elif _IsMessageSetExtension(field_descriptor): + field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number) + sizer = encoder.MessageSetItemSizer(field_descriptor.number) + else: + field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + + field_descriptor._encoder = field_encoder + field_descriptor._sizer = sizer + field_descriptor._default_constructor = _DefaultValueConstructorForField( + field_descriptor) + + def AddDecoder(wiretype, is_packed): + tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype) + decode_type = field_descriptor.type + if (decode_type == _FieldDescriptor.TYPE_ENUM and + type_checkers.SupportsOpenEnums(field_descriptor)): + decode_type = _FieldDescriptor.TYPE_INT32 + + oneof_descriptor = None + clear_if_default = False + if field_descriptor.containing_oneof is not None: + oneof_descriptor = field_descriptor + elif (is_proto3 and not is_repeated and + field_descriptor.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE): + clear_if_default = True + + if is_map_entry: + is_message_map = _IsMessageMapField(field_descriptor) + + field_decoder = decoder.MapDecoder( + field_descriptor, _GetInitializeDefaultForMap(field_descriptor), + is_message_map) + elif decode_type == _FieldDescriptor.TYPE_STRING: + field_decoder = decoder.StringDecoder( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor, + clear_if_default) + elif field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor) + else: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + # pylint: disable=protected-access + field_descriptor, field_descriptor._default_constructor, + clear_if_default) + + cls._decoders_by_tag[tag_bytes] = (field_decoder, oneof_descriptor) + + AddDecoder(type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], + False) + + if is_repeated and wire_format.IsTypePackable(field_descriptor.type): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddDecoder(wire_format.WIRETYPE_LENGTH_DELIMITED, True) + + +def _AddClassAttributesForNestedExtensions(descriptor, dictionary): + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + assert extension_name not in dictionary + dictionary[extension_name] = extension_field + + +def _AddEnumValues(descriptor, cls): + """Sets class-level attributes for all enum fields defined in this message. + + Also exporting a class-level object that can name enum values. + + Args: + descriptor: Descriptor object for this message type. + cls: Class we're constructing for this message type. + """ + for enum_type in descriptor.enum_types: + setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) + for enum_value in enum_type.values: + setattr(cls, enum_value.name, enum_value.number) + + +def _GetInitializeDefaultForMap(field): + if field.label != _FieldDescriptor.LABEL_REPEATED: + raise ValueError('map_entry set on non-repeated field %s' % ( + field.name)) + fields_by_name = field.message_type.fields_by_name + key_checker = type_checkers.GetTypeChecker(fields_by_name['key']) + + value_field = fields_by_name['value'] + if _IsMessageMapField(field): + def MakeMessageMapDefault(message): + return containers.MessageMap( + message._listener_for_children, value_field.message_type, key_checker, + field.message_type) + return MakeMessageMapDefault + else: + value_checker = type_checkers.GetTypeChecker(value_field) + def MakePrimitiveMapDefault(message): + return containers.ScalarMap( + message._listener_for_children, key_checker, value_checker, + field.message_type) + return MakePrimitiveMapDefault + +def _DefaultValueConstructorForField(field): + """Returns a function which returns a default value for a field. + + Args: + field: FieldDescriptor object for this field. + + The returned function has one argument: + message: Message instance containing this field, or a weakref proxy + of same. + + That function in turn returns a default value for this field. The default + value may refer back to |message| via a weak reference. + """ + + if _IsMapField(field): + return _GetInitializeDefaultForMap(field) + + if field.label == _FieldDescriptor.LABEL_REPEATED: + if field.has_default_value and field.default_value != []: + raise ValueError('Repeated field default value not empty list: %s' % ( + field.default_value)) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # We can't look at _concrete_class yet since it might not have + # been set. (Depends on order in which we initialize the classes). + message_type = field.message_type + def MakeRepeatedMessageDefault(message): + return containers.RepeatedCompositeFieldContainer( + message._listener_for_children, field.message_type) + return MakeRepeatedMessageDefault + else: + type_checker = type_checkers.GetTypeChecker(field) + def MakeRepeatedScalarDefault(message): + return containers.RepeatedScalarFieldContainer( + message._listener_for_children, type_checker) + return MakeRepeatedScalarDefault + + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # _concrete_class may not yet be initialized. + message_type = field.message_type + def MakeSubMessageDefault(message): + assert getattr(message_type, '_concrete_class', None), ( + 'Uninitialized concrete class found for field %r (message type %r)' + % (field.full_name, message_type.full_name)) + result = message_type._concrete_class() + result._SetListener( + _OneofListener(message, field) + if field.containing_oneof is not None + else message._listener_for_children) + return result + return MakeSubMessageDefault + + def MakeScalarDefault(message): + # TODO(protobuf-team): This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return field.default_value + return MakeScalarDefault + + +def _ReraiseTypeErrorWithFieldName(message_name, field_name): + """Re-raise the currently-handled TypeError with the field name added.""" + exc = sys.exc_info()[1] + if len(exc.args) == 1 and type(exc) is TypeError: + # simple TypeError; add field name to exception message + exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) + + # re-raise possibly-amended exception with original traceback: + raise exc.with_traceback(sys.exc_info()[2]) + + +def _AddInitMethod(message_descriptor, cls): + """Adds an __init__ method to cls.""" + + def _GetIntegerEnumValue(enum_type, value): + """Convert a string or integer enum value to an integer. + + If the value is a string, it is converted to the enum value in + enum_type with the same name. If the value is not a string, it's + returned as-is. (No conversion or bounds-checking is done.) + """ + if isinstance(value, str): + try: + return enum_type.values_by_name[value].number + except KeyError: + raise ValueError('Enum type %s: unknown label "%s"' % ( + enum_type.full_name, value)) + return value + + def init(self, **kwargs): + self._cached_byte_size = 0 + self._cached_byte_size_dirty = len(kwargs) > 0 + self._fields = {} + # Contains a mapping from oneof field descriptors to the descriptor + # of the currently set field in that oneof field. + self._oneofs = {} + + # _unknown_fields is () when empty for efficiency, and will be turned into + # a list if fields are added. + self._unknown_fields = () + # _unknown_field_set is None when empty for efficiency, and will be + # turned into UnknownFieldSet struct if fields are added. + self._unknown_field_set = None # pylint: disable=protected-access + self._is_present_in_parent = False + self._listener = message_listener_mod.NullMessageListener() + self._listener_for_children = _Listener(self) + for field_name, field_value in kwargs.items(): + field = _GetFieldByName(message_descriptor, field_name) + if field is None: + raise TypeError('%s() got an unexpected keyword argument "%s"' % + (message_descriptor.name, field_name)) + if field_value is None: + # field=None is the same as no field at all. + continue + if field.label == _FieldDescriptor.LABEL_REPEATED: + copy = field._default_constructor(self) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite + if _IsMapField(field): + if _IsMessageMapField(field): + for key in field_value: + copy[key].MergeFrom(field_value[key]) + else: + copy.update(field_value) + else: + for val in field_value: + if isinstance(val, dict): + copy.add(**val) + else: + copy.add().MergeFrom(val) + else: # Scalar + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = [_GetIntegerEnumValue(field.enum_type, val) + for val in field_value] + copy.extend(field_value) + self._fields[field] = copy + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + copy = field._default_constructor(self) + new_val = field_value + if isinstance(field_value, dict): + new_val = field.message_type._concrete_class(**field_value) + try: + copy.MergeFrom(new_val) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + self._fields[field] = copy + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = _GetIntegerEnumValue(field.enum_type, field_value) + try: + setattr(self, field_name, field_value) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + + init.__module__ = None + init.__doc__ = None + cls.__init__ = init + + +def _GetFieldByName(message_descriptor, field_name): + """Returns a field descriptor by field name. + + Args: + message_descriptor: A Descriptor describing all fields in message. + field_name: The name of the field to retrieve. + Returns: + The field descriptor associated with the field name. + """ + try: + return message_descriptor.fields_by_name[field_name] + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + +def _AddPropertiesForFields(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + for field in descriptor.fields: + _AddPropertiesForField(field, cls) + + if descriptor.is_extendable: + # _ExtensionDict is just an adaptor with no state so we allocate a new one + # every time it is accessed. + cls.Extensions = property(lambda self: _ExtensionDict(self)) + + +def _AddPropertiesForField(field, cls): + """Adds a public property for a protocol message field. + Clients can use this property to get and (in the case + of non-repeated scalar fields) directly set the value + of a protocol message field. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # Catch it if we add other types that we should + # handle specially here. + assert _FieldDescriptor.MAX_CPPTYPE == 10 + + constant_name = field.name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, field.number) + + if field.label == _FieldDescriptor.LABEL_REPEATED: + _AddPropertiesForRepeatedField(field, cls) + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + _AddPropertiesForNonRepeatedCompositeField(field, cls) + else: + _AddPropertiesForNonRepeatedScalarField(field, cls) + + +class _FieldProperty(property): + __slots__ = ('DESCRIPTOR',) + + def __init__(self, descriptor, getter, setter, doc): + property.__init__(self, getter, setter, doc=doc) + self.DESCRIPTOR = descriptor + + +def _AddPropertiesForRepeatedField(field, cls): + """Adds a public property for a "repeated" protocol message field. Clients + can use this property to get the value of the field, which will be either a + RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see + below). + + Note that when clients add values to these containers, we perform + type-checking in the case of repeated scalar fields, and we also set any + necessary "has" bits as a side-effect. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % proto_field_name) + + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedScalarField(field, cls): + """Adds a public property for a nonrepeated, scalar protocol message field. + Clients can use this property to get and directly set the value of the field. + Note that when the client sets the value of a field by using this property, + all necessary "has" bits are set as a side-effect, and we also perform + type-checking. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + type_checker = type_checkers.GetTypeChecker(field) + default_value = field.default_value + is_proto3 = field.containing_type.syntax == 'proto3' + + def getter(self): + # TODO(protobuf-team): This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return self._fields.get(field, default_value) + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + clear_when_set_to_default = is_proto3 and not field.containing_oneof + + def field_setter(self, new_value): + # pylint: disable=protected-access + # Testing the value for truthiness captures all of the proto3 defaults + # (0, 0.0, enum 0, and False). + try: + new_value = type_checker.CheckValue(new_value) + except TypeError as e: + raise TypeError( + 'Cannot set %s to %.1024r: %s' % (field.full_name, new_value, e)) + if clear_when_set_to_default and not new_value: + self._fields.pop(field, None) + else: + self._fields[field] = new_value + # Check _cached_byte_size_dirty inline to improve performance, since scalar + # setters are called frequently. + if not self._cached_byte_size_dirty: + self._Modified() + + if field.containing_oneof: + def setter(self, new_value): + field_setter(self, new_value) + self._UpdateOneofState(field) + else: + setter = field_setter + + setter.__module__ = None + setter.__doc__ = 'Setter for %s.' % proto_field_name + + # Add a property to encapsulate the getter/setter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedCompositeField(field, cls): + """Adds a public property for a nonrepeated, composite protocol message field. + A composite field is a "group" or "message" field. + + Clients can use this property to get the value of the field, but cannot + assign to the property directly. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # TODO(robinson): Remove duplication with similar method + # for non-repeated scalars. + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to composite field ' + '"%s" in protocol message object.' % proto_field_name) + + # Add a property to encapsulate the getter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForExtensions(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + constant_name = extension_name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, extension_field.number) + + # TODO(amauryfa): Migrate all users of these attributes to functions like + # pool.FindExtensionByNumber(descriptor). + if descriptor.file is not None: + # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available. + pool = descriptor.file.pool + cls._extensions_by_number = pool._extensions_by_number[descriptor] + cls._extensions_by_name = pool._extensions_by_name[descriptor] + +def _AddStaticMethods(cls): + # TODO(robinson): This probably needs to be thread-safe(?) + def RegisterExtension(extension_handle): + extension_handle.containing_type = cls.DESCRIPTOR + # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available. + # pylint: disable=protected-access + cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle) + _AttachFieldHelpers(cls, extension_handle) + cls.RegisterExtension = staticmethod(RegisterExtension) + + def FromString(s): + message = cls() + message.MergeFromString(s) + return message + cls.FromString = staticmethod(FromString) + + +def _IsPresent(item): + """Given a (FieldDescriptor, value) tuple from _fields, return true if the + value should be included in the list returned by ListFields().""" + + if item[0].label == _FieldDescriptor.LABEL_REPEATED: + return bool(item[1]) + elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + return item[1]._is_present_in_parent + else: + return True + + +def _AddListFieldsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ListFields(self): + all_fields = [item for item in self._fields.items() if _IsPresent(item)] + all_fields.sort(key = lambda item: item[0].number) + return all_fields + + cls.ListFields = ListFields + +_PROTO3_ERROR_TEMPLATE = \ + ('Protocol message %s has no non-repeated submessage field "%s" ' + 'nor marked as optional') +_PROTO2_ERROR_TEMPLATE = 'Protocol message %s has no non-repeated field "%s"' + +def _AddHasFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + is_proto3 = (message_descriptor.syntax == "proto3") + error_msg = _PROTO3_ERROR_TEMPLATE if is_proto3 else _PROTO2_ERROR_TEMPLATE + + hassable_fields = {} + for field in message_descriptor.fields: + if field.label == _FieldDescriptor.LABEL_REPEATED: + continue + # For proto3, only submessages and fields inside a oneof have presence. + if (is_proto3 and field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE and + not field.containing_oneof): + continue + hassable_fields[field.name] = field + + # Has methods are supported for oneof descriptors. + for oneof in message_descriptor.oneofs: + hassable_fields[oneof.name] = oneof + + def HasField(self, field_name): + try: + field = hassable_fields[field_name] + except KeyError: + raise ValueError(error_msg % (message_descriptor.full_name, field_name)) + + if isinstance(field, descriptor_mod.OneofDescriptor): + try: + return HasField(self, self._oneofs[field].name) + except KeyError: + return False + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field) + return value is not None and value._is_present_in_parent + else: + return field in self._fields + + cls.HasField = HasField + + +def _AddClearFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def ClearField(self, field_name): + try: + field = message_descriptor.fields_by_name[field_name] + except KeyError: + try: + field = message_descriptor.oneofs_by_name[field_name] + if field in self._oneofs: + field = self._oneofs[field] + else: + return + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + if field in self._fields: + # To match the C++ implementation, we need to invalidate iterators + # for map fields when ClearField() happens. + if hasattr(self._fields[field], 'InvalidateIterators'): + self._fields[field].InvalidateIterators() + + # Note: If the field is a sub-message, its listener will still point + # at us. That's fine, because the worst than can happen is that it + # will call _Modified() and invalidate our byte size. Big deal. + del self._fields[field] + + if self._oneofs.get(field.containing_oneof, None) is field: + del self._oneofs[field.containing_oneof] + + # Always call _Modified() -- even if nothing was changed, this is + # a mutating method, and thus calling it should cause the field to become + # present in the parent message. + self._Modified() + + cls.ClearField = ClearField + + +def _AddClearExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def ClearExtension(self, extension_handle): + extension_dict._VerifyExtensionHandle(self, extension_handle) + + # Similar to ClearField(), above. + if extension_handle in self._fields: + del self._fields[extension_handle] + self._Modified() + cls.ClearExtension = ClearExtension + + +def _AddHasExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def HasExtension(self, extension_handle): + extension_dict._VerifyExtensionHandle(self, extension_handle) + if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: + raise KeyError('"%s" is repeated.' % extension_handle.full_name) + + if extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(extension_handle) + return value is not None and value._is_present_in_parent + else: + return extension_handle in self._fields + cls.HasExtension = HasExtension + +def _InternalUnpackAny(msg): + """Unpacks Any message and returns the unpacked message. + + This internal method is different from public Any Unpack method which takes + the target message as argument. _InternalUnpackAny method does not have + target message type and need to find the message type in descriptor pool. + + Args: + msg: An Any message to be unpacked. + + Returns: + The unpacked message. + """ + # TODO(amauryfa): Don't use the factory of generated messages. + # To make Any work with custom factories, use the message factory of the + # parent message. + # pylint: disable=g-import-not-at-top + from google.protobuf import symbol_database + factory = symbol_database.Default() + + type_url = msg.type_url + + if not type_url: + return None + + # TODO(haberman): For now we just strip the hostname. Better logic will be + # required. + type_name = type_url.split('/')[-1] + descriptor = factory.pool.FindMessageTypeByName(type_name) + + if descriptor is None: + return None + + message_class = factory.GetPrototype(descriptor) + message = message_class() + + message.ParseFromString(msg.value) + return message + + +def _AddEqualsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __eq__(self, other): + if (not isinstance(other, message_mod.Message) or + other.DESCRIPTOR != self.DESCRIPTOR): + return False + + if self is other: + return True + + if self.DESCRIPTOR.full_name == _AnyFullTypeName: + any_a = _InternalUnpackAny(self) + any_b = _InternalUnpackAny(other) + if any_a and any_b: + return any_a == any_b + + if not self.ListFields() == other.ListFields(): + return False + + # TODO(jieluo): Fix UnknownFieldSet to consider MessageSet extensions, + # then use it for the comparison. + unknown_fields = list(self._unknown_fields) + unknown_fields.sort() + other_unknown_fields = list(other._unknown_fields) + other_unknown_fields.sort() + return unknown_fields == other_unknown_fields + + cls.__eq__ = __eq__ + + +def _AddStrMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __str__(self): + return text_format.MessageToString(self) + cls.__str__ = __str__ + + +def _AddReprMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __repr__(self): + return text_format.MessageToString(self) + cls.__repr__ = __repr__ + + +def _AddUnicodeMethod(unused_message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def __unicode__(self): + return text_format.MessageToString(self, as_utf8=True).decode('utf-8') + cls.__unicode__ = __unicode__ + + +def _BytesForNonRepeatedElement(value, field_number, field_type): + """Returns the number of bytes needed to serialize a non-repeated element. + The returned byte count includes space for tag information and any + other additional space associated with serializing value. + + Args: + value: Value we're serializing. + field_number: Field number of this value. (Since the field number + is stored as part of a varint-encoded tag, this has an impact + on the total bytes required to serialize the value). + field_type: The type of the field. One of the TYPE_* constants + within FieldDescriptor. + """ + try: + fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] + return fn(field_number, value) + except KeyError: + raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) + + +def _AddByteSizeMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ByteSize(self): + if not self._cached_byte_size_dirty: + return self._cached_byte_size + + size = 0 + descriptor = self.DESCRIPTOR + if descriptor.GetOptions().map_entry: + # Fields of map entry should always be serialized. + size = descriptor.fields_by_name['key']._sizer(self.key) + size += descriptor.fields_by_name['value']._sizer(self.value) + else: + for field_descriptor, field_value in self.ListFields(): + size += field_descriptor._sizer(field_value) + for tag_bytes, value_bytes in self._unknown_fields: + size += len(tag_bytes) + len(value_bytes) + + self._cached_byte_size = size + self._cached_byte_size_dirty = False + self._listener_for_children.dirty = False + return size + + cls.ByteSize = ByteSize + + +def _AddSerializeToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializeToString(self, **kwargs): + # Check if the message has all of its required fields set. + if not self.IsInitialized(): + raise message_mod.EncodeError( + 'Message %s is missing required fields: %s' % ( + self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) + return self.SerializePartialToString(**kwargs) + cls.SerializeToString = SerializeToString + + +def _AddSerializePartialToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializePartialToString(self, **kwargs): + out = BytesIO() + self._InternalSerialize(out.write, **kwargs) + return out.getvalue() + cls.SerializePartialToString = SerializePartialToString + + def InternalSerialize(self, write_bytes, deterministic=None): + if deterministic is None: + deterministic = ( + api_implementation.IsPythonDefaultSerializationDeterministic()) + else: + deterministic = bool(deterministic) + + descriptor = self.DESCRIPTOR + if descriptor.GetOptions().map_entry: + # Fields of map entry should always be serialized. + descriptor.fields_by_name['key']._encoder( + write_bytes, self.key, deterministic) + descriptor.fields_by_name['value']._encoder( + write_bytes, self.value, deterministic) + else: + for field_descriptor, field_value in self.ListFields(): + field_descriptor._encoder(write_bytes, field_value, deterministic) + for tag_bytes, value_bytes in self._unknown_fields: + write_bytes(tag_bytes) + write_bytes(value_bytes) + cls._InternalSerialize = InternalSerialize + + +def _AddMergeFromStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def MergeFromString(self, serialized): + serialized = memoryview(serialized) + length = len(serialized) + try: + if self._InternalParse(serialized, 0, length) != length: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise message_mod.DecodeError('Unexpected end-group tag.') + except (IndexError, TypeError): + # Now ord(buf[p:p+1]) == ord('') gets TypeError. + raise message_mod.DecodeError('Truncated message.') + except struct.error as e: + raise message_mod.DecodeError(e) + return length # Return this for legacy reasons. + cls.MergeFromString = MergeFromString + + local_ReadTag = decoder.ReadTag + local_SkipField = decoder.SkipField + decoders_by_tag = cls._decoders_by_tag + + def InternalParse(self, buffer, pos, end): + """Create a message from serialized bytes. + + Args: + self: Message, instance of the proto message object. + buffer: memoryview of the serialized data. + pos: int, position to start in the serialized data. + end: int, end position of the serialized data. + + Returns: + Message object. + """ + # Guard against internal misuse, since this function is called internally + # quite extensively, and its easy to accidentally pass bytes. + assert isinstance(buffer, memoryview) + self._Modified() + field_dict = self._fields + # pylint: disable=protected-access + unknown_field_set = self._unknown_field_set + while pos != end: + (tag_bytes, new_pos) = local_ReadTag(buffer, pos) + field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None)) + if field_decoder is None: + if not self._unknown_fields: # pylint: disable=protected-access + self._unknown_fields = [] # pylint: disable=protected-access + if unknown_field_set is None: + # pylint: disable=protected-access + self._unknown_field_set = containers.UnknownFieldSet() + # pylint: disable=protected-access + unknown_field_set = self._unknown_field_set + # pylint: disable=protected-access + (tag, _) = decoder._DecodeVarint(tag_bytes, 0) + field_number, wire_type = wire_format.UnpackTag(tag) + if field_number == 0: + raise message_mod.DecodeError('Field number 0 is illegal.') + # TODO(jieluo): remove old_pos. + old_pos = new_pos + (data, new_pos) = decoder._DecodeUnknownField( + buffer, new_pos, wire_type) # pylint: disable=protected-access + if new_pos == -1: + return pos + # pylint: disable=protected-access + unknown_field_set._add(field_number, wire_type, data) + # TODO(jieluo): remove _unknown_fields. + new_pos = local_SkipField(buffer, old_pos, end, tag_bytes) + if new_pos == -1: + return pos + self._unknown_fields.append( + (tag_bytes, buffer[old_pos:new_pos].tobytes())) + pos = new_pos + else: + pos = field_decoder(buffer, new_pos, end, self, field_dict) + if field_desc: + self._UpdateOneofState(field_desc) + return pos + cls._InternalParse = InternalParse + + +def _AddIsInitializedMethod(message_descriptor, cls): + """Adds the IsInitialized and FindInitializationError methods to the + protocol message class.""" + + required_fields = [field for field in message_descriptor.fields + if field.label == _FieldDescriptor.LABEL_REQUIRED] + + def IsInitialized(self, errors=None): + """Checks if all required fields of a message are set. + + Args: + errors: A list which, if provided, will be populated with the field + paths of all missing required fields. + + Returns: + True iff the specified message has all required fields set. + """ + + # Performance is critical so we avoid HasField() and ListFields(). + + for field in required_fields: + if (field not in self._fields or + (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and + not self._fields[field]._is_present_in_parent)): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + for field, value in list(self._fields.items()): # dict can change size! + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.label == _FieldDescriptor.LABEL_REPEATED: + if (field.message_type.has_options and + field.message_type.GetOptions().map_entry): + continue + for element in value: + if not element.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + elif value._is_present_in_parent and not value.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + return True + + cls.IsInitialized = IsInitialized + + def FindInitializationErrors(self): + """Finds required fields which are not initialized. + + Returns: + A list of strings. Each string is a path to an uninitialized field from + the top-level message, e.g. "foo.bar[5].baz". + """ + + errors = [] # simplify things + + for field in required_fields: + if not self.HasField(field.name): + errors.append(field.name) + + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_extension: + name = '(%s)' % field.full_name + else: + name = field.name + + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + element = value[key] + prefix = '%s[%s].' % (name, key) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + # ScalarMaps can't have any initialization errors. + pass + elif field.label == _FieldDescriptor.LABEL_REPEATED: + for i in range(len(value)): + element = value[i] + prefix = '%s[%d].' % (name, i) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + prefix = name + '.' + sub_errors = value.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + + return errors + + cls.FindInitializationErrors = FindInitializationErrors + + +def _FullyQualifiedClassName(klass): + module = klass.__module__ + name = getattr(klass, '__qualname__', klass.__name__) + if module in (None, 'builtins', '__builtin__'): + return name + return module + '.' + name + + +def _AddMergeFromMethod(cls): + LABEL_REPEATED = _FieldDescriptor.LABEL_REPEATED + CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE + + def MergeFrom(self, msg): + if not isinstance(msg, cls): + raise TypeError( + 'Parameter to MergeFrom() must be instance of same class: ' + 'expected %s got %s.' % (_FullyQualifiedClassName(cls), + _FullyQualifiedClassName(msg.__class__))) + + assert msg is not self + self._Modified() + + fields = self._fields + + for field, value in msg._fields.items(): + if field.label == LABEL_REPEATED: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + elif field.cpp_type == CPPTYPE_MESSAGE: + if value._is_present_in_parent: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + else: + self._fields[field] = value + if field.containing_oneof: + self._UpdateOneofState(field) + + if msg._unknown_fields: + if not self._unknown_fields: + self._unknown_fields = [] + self._unknown_fields.extend(msg._unknown_fields) + # pylint: disable=protected-access + if self._unknown_field_set is None: + self._unknown_field_set = containers.UnknownFieldSet() + self._unknown_field_set._extend(msg._unknown_field_set) + + cls.MergeFrom = MergeFrom + + +def _AddWhichOneofMethod(message_descriptor, cls): + def WhichOneof(self, oneof_name): + """Returns the name of the currently set field inside a oneof, or None.""" + try: + field = message_descriptor.oneofs_by_name[oneof_name] + except KeyError: + raise ValueError( + 'Protocol message has no oneof "%s" field.' % oneof_name) + + nested_field = self._oneofs.get(field, None) + if nested_field is not None and self.HasField(nested_field.name): + return nested_field.name + else: + return None + + cls.WhichOneof = WhichOneof + + +def _Clear(self): + # Clear fields. + self._fields = {} + self._unknown_fields = () + # pylint: disable=protected-access + if self._unknown_field_set is not None: + self._unknown_field_set._clear() + self._unknown_field_set = None + + self._oneofs = {} + self._Modified() + + +def _UnknownFields(self): + if self._unknown_field_set is None: # pylint: disable=protected-access + # pylint: disable=protected-access + self._unknown_field_set = containers.UnknownFieldSet() + return self._unknown_field_set # pylint: disable=protected-access + + +def _DiscardUnknownFields(self): + self._unknown_fields = [] + self._unknown_field_set = None # pylint: disable=protected-access + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + value[key].DiscardUnknownFields() + elif field.label == _FieldDescriptor.LABEL_REPEATED: + for sub_message in value: + sub_message.DiscardUnknownFields() + else: + value.DiscardUnknownFields() + + +def _SetListener(self, listener): + if listener is None: + self._listener = message_listener_mod.NullMessageListener() + else: + self._listener = listener + + +def _AddMessageMethods(message_descriptor, cls): + """Adds implementations of all Message methods to cls.""" + _AddListFieldsMethod(message_descriptor, cls) + _AddHasFieldMethod(message_descriptor, cls) + _AddClearFieldMethod(message_descriptor, cls) + if message_descriptor.is_extendable: + _AddClearExtensionMethod(cls) + _AddHasExtensionMethod(cls) + _AddEqualsMethod(message_descriptor, cls) + _AddStrMethod(message_descriptor, cls) + _AddReprMethod(message_descriptor, cls) + _AddUnicodeMethod(message_descriptor, cls) + _AddByteSizeMethod(message_descriptor, cls) + _AddSerializeToStringMethod(message_descriptor, cls) + _AddSerializePartialToStringMethod(message_descriptor, cls) + _AddMergeFromStringMethod(message_descriptor, cls) + _AddIsInitializedMethod(message_descriptor, cls) + _AddMergeFromMethod(cls) + _AddWhichOneofMethod(message_descriptor, cls) + # Adds methods which do not depend on cls. + cls.Clear = _Clear + cls.UnknownFields = _UnknownFields + cls.DiscardUnknownFields = _DiscardUnknownFields + cls._SetListener = _SetListener + + +def _AddPrivateHelperMethods(message_descriptor, cls): + """Adds implementation of private helper methods to cls.""" + + def Modified(self): + """Sets the _cached_byte_size_dirty bit to true, + and propagates this to our listener iff this was a state change. + """ + + # Note: Some callers check _cached_byte_size_dirty before calling + # _Modified() as an extra optimization. So, if this method is ever + # changed such that it does stuff even when _cached_byte_size_dirty is + # already true, the callers need to be updated. + if not self._cached_byte_size_dirty: + self._cached_byte_size_dirty = True + self._listener_for_children.dirty = True + self._is_present_in_parent = True + self._listener.Modified() + + def _UpdateOneofState(self, field): + """Sets field as the active field in its containing oneof. + + Will also delete currently active field in the oneof, if it is different + from the argument. Does not mark the message as modified. + """ + other_field = self._oneofs.setdefault(field.containing_oneof, field) + if other_field is not field: + del self._fields[other_field] + self._oneofs[field.containing_oneof] = field + + cls._Modified = Modified + cls.SetInParent = Modified + cls._UpdateOneofState = _UpdateOneofState + + +class _Listener(object): + + """MessageListener implementation that a parent message registers with its + child message. + + In order to support semantics like: + + foo.bar.baz.qux = 23 + assert foo.HasField('bar') + + ...child objects must have back references to their parents. + This helper class is at the heart of this support. + """ + + def __init__(self, parent_message): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + """ + # This listener establishes a back reference from a child (contained) object + # to its parent (containing) object. We make this a weak reference to avoid + # creating cyclic garbage when the client finishes with the 'parent' object + # in the tree. + if isinstance(parent_message, weakref.ProxyType): + self._parent_message_weakref = parent_message + else: + self._parent_message_weakref = weakref.proxy(parent_message) + + # As an optimization, we also indicate directly on the listener whether + # or not the parent message is dirty. This way we can avoid traversing + # up the tree in the common case. + self.dirty = False + + def Modified(self): + if self.dirty: + return + try: + # Propagate the signal to our parents iff this is the first field set. + self._parent_message_weakref._Modified() + except ReferenceError: + # We can get here if a client has kept a reference to a child object, + # and is now setting a field on it, but the child's parent has been + # garbage-collected. This is not an error. + pass + + +class _OneofListener(_Listener): + """Special listener implementation for setting composite oneof fields.""" + + def __init__(self, parent_message, field): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + field: The descriptor of the field being set in the parent message. + """ + super(_OneofListener, self).__init__(parent_message) + self._field = field + + def Modified(self): + """Also updates the state of the containing oneof in the parent message.""" + try: + self._parent_message_weakref._UpdateOneofState(self._field) + super(_OneofListener, self).Modified() + except ReferenceError: + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/type_checkers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/type_checkers.py new file mode 100644 index 0000000000000000000000000000000000000000..a53e71fe8e57659803f94605db0c6a859b63ac6b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/type_checkers.py @@ -0,0 +1,435 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides type checking routines. + +This module defines type checking utilities in the forms of dictionaries: + +VALUE_CHECKERS: A dictionary of field types and a value validation object. +TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing + function. +TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization + function. +FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their + corresponding wire types. +TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization + function. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import ctypes +import numbers + +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format +from google.protobuf import descriptor + +_FieldDescriptor = descriptor.FieldDescriptor + + +def TruncateToFourByteFloat(original): + return ctypes.c_float(original).value + + +def ToShortestFloat(original): + """Returns the shortest float that has same value in wire.""" + # All 4 byte floats have between 6 and 9 significant digits, so we + # start with 6 as the lower bound. + # It has to be iterative because use '.9g' directly can not get rid + # of the noises for most values. For example if set a float_field=0.9 + # use '.9g' will print 0.899999976. + precision = 6 + rounded = float('{0:.{1}g}'.format(original, precision)) + while TruncateToFourByteFloat(rounded) != original: + precision += 1 + rounded = float('{0:.{1}g}'.format(original, precision)) + return rounded + + +def SupportsOpenEnums(field_descriptor): + return field_descriptor.containing_type.syntax == 'proto3' + + +def GetTypeChecker(field): + """Returns a type checker for a message field of the specified types. + + Args: + field: FieldDescriptor object for this field. + + Returns: + An instance of TypeChecker which can be used to verify the types + of values assigned to a field of the specified type. + """ + if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and + field.type == _FieldDescriptor.TYPE_STRING): + return UnicodeValueChecker() + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + if SupportsOpenEnums(field): + # When open enums are supported, any int32 can be assigned. + return _VALUE_CHECKERS[_FieldDescriptor.CPPTYPE_INT32] + else: + return EnumValueChecker(field.enum_type) + return _VALUE_CHECKERS[field.cpp_type] + + +# None of the typecheckers below make any attempt to guard against people +# subclassing builtin types and doing weird things. We're not trying to +# protect against malicious clients here, just people accidentally shooting +# themselves in the foot in obvious ways. +class TypeChecker(object): + + """Type checker used to catch type errors as early as possible + when the client is setting scalar fields in protocol messages. + """ + + def __init__(self, *acceptable_types): + self._acceptable_types = acceptable_types + + def CheckValue(self, proposed_value): + """Type check the provided value and return it. + + The returned value might have been normalized to another type. + """ + if not isinstance(proposed_value, self._acceptable_types): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), self._acceptable_types)) + raise TypeError(message) + return proposed_value + + +class TypeCheckerWithDefault(TypeChecker): + + def __init__(self, default_value, *acceptable_types): + TypeChecker.__init__(self, *acceptable_types) + self._default_value = default_value + + def DefaultValue(self): + return self._default_value + + +class BoolValueChecker(object): + """Type checker used for bool fields.""" + + def CheckValue(self, proposed_value): + if not hasattr(proposed_value, '__index__') or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (bool, int))) + raise TypeError(message) + return bool(proposed_value) + + def DefaultValue(self): + return False + + +# IntValueChecker and its subclasses perform integer type-checks +# and bounds-checks. +class IntValueChecker(object): + + """Checker used for integer fields. Performs type-check and range check.""" + + def CheckValue(self, proposed_value): + if not hasattr(proposed_value, '__index__') or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + + if not self._MIN <= int(proposed_value) <= self._MAX: + raise ValueError('Value out of range: %d' % proposed_value) + # We force all values to int to make alternate implementations where the + # distinction is more significant (e.g. the C++ implementation) simpler. + proposed_value = int(proposed_value) + return proposed_value + + def DefaultValue(self): + return 0 + + +class EnumValueChecker(object): + + """Checker used for enum fields. Performs type-check and range check.""" + + def __init__(self, enum_type): + self._enum_type = enum_type + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, numbers.Integral): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + if int(proposed_value) not in self._enum_type.values_by_number: + raise ValueError('Unknown enum value: %d' % proposed_value) + return proposed_value + + def DefaultValue(self): + return self._enum_type.values[0].number + + +class UnicodeValueChecker(object): + + """Checker used for string fields. + + Always returns a unicode value, even if the input is of type str. + """ + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, (bytes, str)): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (bytes, str))) + raise TypeError(message) + + # If the value is of type 'bytes' make sure that it is valid UTF-8 data. + if isinstance(proposed_value, bytes): + try: + proposed_value = proposed_value.decode('utf-8') + except UnicodeDecodeError: + raise ValueError('%.1024r has type bytes, but isn\'t valid UTF-8 ' + 'encoding. Non-UTF-8 strings must be converted to ' + 'unicode objects before being added.' % + (proposed_value)) + else: + try: + proposed_value.encode('utf8') + except UnicodeEncodeError: + raise ValueError('%.1024r isn\'t a valid unicode string and ' + 'can\'t be encoded in UTF-8.'% + (proposed_value)) + + return proposed_value + + def DefaultValue(self): + return u"" + + +class Int32ValueChecker(IntValueChecker): + # We're sure to use ints instead of longs here since comparison may be more + # efficient. + _MIN = -2147483648 + _MAX = 2147483647 + + +class Uint32ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 32) - 1 + + +class Int64ValueChecker(IntValueChecker): + _MIN = -(1 << 63) + _MAX = (1 << 63) - 1 + + +class Uint64ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 64) - 1 + + +# The max 4 bytes float is about 3.4028234663852886e+38 +_FLOAT_MAX = float.fromhex('0x1.fffffep+127') +_FLOAT_MIN = -_FLOAT_MAX +_INF = float('inf') +_NEG_INF = float('-inf') + + +class DoubleValueChecker(object): + """Checker used for double fields. + + Performs type-check and range check. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + if (not hasattr(proposed_value, '__float__') and + not hasattr(proposed_value, '__index__')) or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: int, float' % + (proposed_value, type(proposed_value))) + raise TypeError(message) + return float(proposed_value) + + def DefaultValue(self): + return 0.0 + + +class FloatValueChecker(DoubleValueChecker): + """Checker used for float fields. + + Performs type-check and range check. + + Values exceeding a 32-bit float will be converted to inf/-inf. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + converted_value = super().CheckValue(proposed_value) + # This inf rounding matches the C++ proto SafeDoubleToFloat logic. + if converted_value > _FLOAT_MAX: + return _INF + if converted_value < _FLOAT_MIN: + return _NEG_INF + + return TruncateToFourByteFloat(converted_value) + +# Type-checkers for all scalar CPPTYPEs. +_VALUE_CHECKERS = { + _FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(), + _FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(), + _FieldDescriptor.CPPTYPE_DOUBLE: DoubleValueChecker(), + _FieldDescriptor.CPPTYPE_FLOAT: FloatValueChecker(), + _FieldDescriptor.CPPTYPE_BOOL: BoolValueChecker(), + _FieldDescriptor.CPPTYPE_STRING: TypeCheckerWithDefault(b'', bytes), +} + + +# Map from field type to a function F, such that F(field_num, value) +# gives the total byte size for a value of the given type. This +# byte size includes tag information and any other additional space +# associated with serializing "value". +TYPE_TO_BYTE_SIZE_FN = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize, + _FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize, + _FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize, + _FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize, + _FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize, + _FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize, + _FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize, + _FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize, + _FieldDescriptor.TYPE_STRING: wire_format.StringByteSize, + _FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize, + _FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize, + _FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize, + _FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize, + _FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize, + _FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize, + _FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize, + _FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize, + _FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize + } + + +# Maps from field types to encoder constructors. +TYPE_TO_ENCODER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder, + _FieldDescriptor.TYPE_INT64: encoder.Int64Encoder, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder, + _FieldDescriptor.TYPE_INT32: encoder.Int32Encoder, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder, + _FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder, + _FieldDescriptor.TYPE_STRING: encoder.StringEncoder, + _FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder, + _FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder, + _FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder, + } + + +# Maps from field types to sizer constructors. +TYPE_TO_SIZER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer, + _FieldDescriptor.TYPE_INT64: encoder.Int64Sizer, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer, + _FieldDescriptor.TYPE_INT32: encoder.Int32Sizer, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer, + _FieldDescriptor.TYPE_BOOL: encoder.BoolSizer, + _FieldDescriptor.TYPE_STRING: encoder.StringSizer, + _FieldDescriptor.TYPE_GROUP: encoder.GroupSizer, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer, + _FieldDescriptor.TYPE_BYTES: encoder.BytesSizer, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer, + _FieldDescriptor.TYPE_ENUM: encoder.EnumSizer, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer, + } + + +# Maps from field type to a decoder constructor. +TYPE_TO_DECODER = { + _FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder, + _FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder, + _FieldDescriptor.TYPE_INT64: decoder.Int64Decoder, + _FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder, + _FieldDescriptor.TYPE_INT32: decoder.Int32Decoder, + _FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder, + _FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder, + _FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder, + _FieldDescriptor.TYPE_STRING: decoder.StringDecoder, + _FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder, + _FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder, + _FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder, + _FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder, + _FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder, + _FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder, + _FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder, + _FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder, + _FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder, + } + +# Maps from field type to expected wiretype. +FIELD_TYPE_TO_WIRE_TYPE = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_STRING: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP, + _FieldDescriptor.TYPE_MESSAGE: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_BYTES: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT, + } diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/well_known_types.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/well_known_types.py new file mode 100644 index 0000000000000000000000000000000000000000..b581ab750a39a3d62d8266f3c6f718f18da92401 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/well_known_types.py @@ -0,0 +1,878 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains well known classes. + +This files defines well known classes which need extra maintenance including: + - Any + - Duration + - FieldMask + - Struct + - Timestamp +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +import calendar +import collections.abc +import datetime + +from google.protobuf.descriptor import FieldDescriptor + +_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' +_NANOS_PER_SECOND = 1000000000 +_NANOS_PER_MILLISECOND = 1000000 +_NANOS_PER_MICROSECOND = 1000 +_MILLIS_PER_SECOND = 1000 +_MICROS_PER_SECOND = 1000000 +_SECONDS_PER_DAY = 24 * 3600 +_DURATION_SECONDS_MAX = 315576000000 + + +class Any(object): + """Class for Any Message type.""" + + __slots__ = () + + def Pack(self, msg, type_url_prefix='type.googleapis.com/', + deterministic=None): + """Packs the specified message into current Any message.""" + if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': + self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + else: + self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + self.value = msg.SerializeToString(deterministic=deterministic) + + def Unpack(self, msg): + """Unpacks the current Any message into specified message.""" + descriptor = msg.DESCRIPTOR + if not self.Is(descriptor): + return False + msg.ParseFromString(self.value) + return True + + def TypeName(self): + """Returns the protobuf type name of the inner message.""" + # Only last part is to be used: b/25630112 + return self.type_url.split('/')[-1] + + def Is(self, descriptor): + """Checks if this Any represents the given protobuf type.""" + return '/' in self.type_url and self.TypeName() == descriptor.full_name + + +_EPOCH_DATETIME_NAIVE = datetime.datetime.utcfromtimestamp(0) +_EPOCH_DATETIME_AWARE = datetime.datetime.fromtimestamp( + 0, tz=datetime.timezone.utc) + + +class Timestamp(object): + """Class for Timestamp message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Timestamp to RFC 3339 date string format. + + Returns: + A string converted from timestamp. The string is always Z-normalized + and uses 3, 6 or 9 fractional digits as required to represent the + exact time. Example of the return format: '1972-01-01T10:00:20.021Z' + """ + nanos = self.nanos % _NANOS_PER_SECOND + total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND + seconds = total_sec % _SECONDS_PER_DAY + days = (total_sec - seconds) // _SECONDS_PER_DAY + dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(days, seconds) + + result = dt.isoformat() + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 'Z' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03dZ' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06dZ' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09dZ' % nanos + + def FromJsonString(self, value): + """Parse a RFC 3339 date string format to Timestamp. + + Args: + value: A date string. Any fractional digits (or none) and any offset are + accepted as long as they fit into nano-seconds precision. + Example of accepted format: '1972-01-01T10:00:20.021-05:00' + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Timestamp JSON value not a string: {!r}'.format(value)) + timezone_offset = value.find('Z') + if timezone_offset == -1: + timezone_offset = value.find('+') + if timezone_offset == -1: + timezone_offset = value.rfind('-') + if timezone_offset == -1: + raise ValueError( + 'Failed to parse timestamp: missing valid timezone offset.') + time_value = value[0:timezone_offset] + # Parse datetime and nanos. + point_position = time_value.find('.') + if point_position == -1: + second_value = time_value + nano_value = '' + else: + second_value = time_value[:point_position] + nano_value = time_value[point_position + 1:] + if 't' in second_value: + raise ValueError( + 'time data \'{0}\' does not match format \'%Y-%m-%dT%H:%M:%S\', ' + 'lowercase \'t\' is not accepted'.format(second_value)) + date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFOMAT) + td = date_object - datetime.datetime(1970, 1, 1) + seconds = td.seconds + td.days * _SECONDS_PER_DAY + if len(nano_value) > 9: + raise ValueError( + 'Failed to parse Timestamp: nanos {0} more than ' + '9 fractional digits.'.format(nano_value)) + if nano_value: + nanos = round(float('0.' + nano_value) * 1e9) + else: + nanos = 0 + # Parse timezone offsets. + if value[timezone_offset] == 'Z': + if len(value) != timezone_offset + 1: + raise ValueError('Failed to parse timestamp: invalid trailing' + ' data {0}.'.format(value)) + else: + timezone = value[timezone_offset:] + pos = timezone.find(':') + if pos == -1: + raise ValueError( + 'Invalid timezone offset value: {0}.'.format(timezone)) + if timezone[0] == '+': + seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60 + else: + seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60 + # Set seconds and nanos + self.seconds = int(seconds) + self.nanos = int(nanos) + + def GetCurrentTime(self): + """Get the current UTC into Timestamp.""" + self.FromDatetime(datetime.datetime.utcnow()) + + def ToNanoseconds(self): + """Converts Timestamp to nanoseconds since epoch.""" + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts Timestamp to microseconds since epoch.""" + return (self.seconds * _MICROS_PER_SECOND + + self.nanos // _NANOS_PER_MICROSECOND) + + def ToMilliseconds(self): + """Converts Timestamp to milliseconds since epoch.""" + return (self.seconds * _MILLIS_PER_SECOND + + self.nanos // _NANOS_PER_MILLISECOND) + + def ToSeconds(self): + """Converts Timestamp to seconds since epoch.""" + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds since epoch to Timestamp.""" + self.seconds = nanos // _NANOS_PER_SECOND + self.nanos = nanos % _NANOS_PER_SECOND + + def FromMicroseconds(self, micros): + """Converts microseconds since epoch to Timestamp.""" + self.seconds = micros // _MICROS_PER_SECOND + self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND + + def FromMilliseconds(self, millis): + """Converts milliseconds since epoch to Timestamp.""" + self.seconds = millis // _MILLIS_PER_SECOND + self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND + + def FromSeconds(self, seconds): + """Converts seconds since epoch to Timestamp.""" + self.seconds = seconds + self.nanos = 0 + + def ToDatetime(self, tzinfo=None): + """Converts Timestamp to a datetime. + + Args: + tzinfo: A datetime.tzinfo subclass; defaults to None. + + Returns: + If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone + information, i.e. not aware that it's UTC). + + Otherwise, returns a timezone-aware datetime in the input timezone. + """ + delta = datetime.timedelta( + seconds=self.seconds, + microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)) + if tzinfo is None: + return _EPOCH_DATETIME_NAIVE + delta + else: + return _EPOCH_DATETIME_AWARE.astimezone(tzinfo) + delta + + def FromDatetime(self, dt): + """Converts datetime to Timestamp. + + Args: + dt: A datetime. If it's timezone-naive, it's assumed to be in UTC. + """ + # Using this guide: http://wiki.python.org/moin/WorkingWithTime + # And this conversion guide: http://docs.python.org/library/time.html + + # Turn the date parameter into a tuple (struct_time) that can then be + # manipulated into a long value of seconds. During the conversion from + # struct_time to long, the source date in UTC, and so it follows that the + # correct transformation is calendar.timegm() + self.seconds = calendar.timegm(dt.utctimetuple()) + self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND + + +class Duration(object): + """Class for Duration message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Duration to string format. + + Returns: + A string converted from self. The string format will contains + 3, 6, or 9 fractional digits depending on the precision required to + represent the exact Duration value. For example: "1s", "1.010s", + "1.000000100s", "-3.100s" + """ + _CheckDurationValid(self.seconds, self.nanos) + if self.seconds < 0 or self.nanos < 0: + result = '-' + seconds = - self.seconds + int((0 - self.nanos) // 1e9) + nanos = (0 - self.nanos) % 1e9 + else: + result = '' + seconds = self.seconds + int(self.nanos // 1e9) + nanos = self.nanos % 1e9 + result += '%d' % seconds + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 's' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03ds' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06ds' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09ds' % nanos + + def FromJsonString(self, value): + """Converts a string to Duration. + + Args: + value: A string to be converted. The string must end with 's'. Any + fractional digits (or none) are accepted as long as they fit into + precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Duration JSON value not a string: {!r}'.format(value)) + if len(value) < 1 or value[-1] != 's': + raise ValueError( + 'Duration must end with letter "s": {0}.'.format(value)) + try: + pos = value.find('.') + if pos == -1: + seconds = int(value[:-1]) + nanos = 0 + else: + seconds = int(value[:pos]) + if value[0] == '-': + nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9)) + else: + nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9)) + _CheckDurationValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + except ValueError as e: + raise ValueError( + 'Couldn\'t parse duration: {0} : {1}.'.format(value, e)) + + def ToNanoseconds(self): + """Converts a Duration to nanoseconds.""" + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts a Duration to microseconds.""" + micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) + return self.seconds * _MICROS_PER_SECOND + micros + + def ToMilliseconds(self): + """Converts a Duration to milliseconds.""" + millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) + return self.seconds * _MILLIS_PER_SECOND + millis + + def ToSeconds(self): + """Converts a Duration to seconds.""" + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds to Duration.""" + self._NormalizeDuration(nanos // _NANOS_PER_SECOND, + nanos % _NANOS_PER_SECOND) + + def FromMicroseconds(self, micros): + """Converts microseconds to Duration.""" + self._NormalizeDuration( + micros // _MICROS_PER_SECOND, + (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND) + + def FromMilliseconds(self, millis): + """Converts milliseconds to Duration.""" + self._NormalizeDuration( + millis // _MILLIS_PER_SECOND, + (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND) + + def FromSeconds(self, seconds): + """Converts seconds to Duration.""" + self.seconds = seconds + self.nanos = 0 + + def ToTimedelta(self): + """Converts Duration to timedelta.""" + return datetime.timedelta( + seconds=self.seconds, microseconds=_RoundTowardZero( + self.nanos, _NANOS_PER_MICROSECOND)) + + def FromTimedelta(self, td): + """Converts timedelta to Duration.""" + self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, + td.microseconds * _NANOS_PER_MICROSECOND) + + def _NormalizeDuration(self, seconds, nanos): + """Set Duration by seconds and nanos.""" + # Force nanos to be negative if the duration is negative. + if seconds < 0 and nanos > 0: + seconds += 1 + nanos -= _NANOS_PER_SECOND + self.seconds = seconds + self.nanos = nanos + + +def _CheckDurationValid(seconds, nanos): + if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX: + raise ValueError( + 'Duration is not valid: Seconds {0} must be in range ' + '[-315576000000, 315576000000].'.format(seconds)) + if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND: + raise ValueError( + 'Duration is not valid: Nanos {0} must be in range ' + '[-999999999, 999999999].'.format(nanos)) + if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0): + raise ValueError( + 'Duration is not valid: Sign mismatch.') + + +def _RoundTowardZero(value, divider): + """Truncates the remainder part after division.""" + # For some languages, the sign of the remainder is implementation + # dependent if any of the operands is negative. Here we enforce + # "rounded toward zero" semantics. For example, for (-5) / 2 an + # implementation may give -3 as the result with the remainder being + # 1. This function ensures we always return -2 (closer to zero). + result = value // divider + remainder = value % divider + if result < 0 and remainder > 0: + return result + 1 + else: + return result + + +class FieldMask(object): + """Class for FieldMask message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts FieldMask to string according to proto3 JSON spec.""" + camelcase_paths = [] + for path in self.paths: + camelcase_paths.append(_SnakeCaseToCamelCase(path)) + return ','.join(camelcase_paths) + + def FromJsonString(self, value): + """Converts string to FieldMask according to proto3 JSON spec.""" + if not isinstance(value, str): + raise ValueError('FieldMask JSON value not a string: {!r}'.format(value)) + self.Clear() + if value: + for path in value.split(','): + self.paths.append(_CamelCaseToSnakeCase(path)) + + def IsValidForDescriptor(self, message_descriptor): + """Checks whether the FieldMask is valid for Message Descriptor.""" + for path in self.paths: + if not _IsValidPath(message_descriptor, path): + return False + return True + + def AllFieldsFromDescriptor(self, message_descriptor): + """Gets all direct fields of Message Descriptor to FieldMask.""" + self.Clear() + for field in message_descriptor.fields: + self.paths.append(field.name) + + def CanonicalFormFromMask(self, mask): + """Converts a FieldMask to the canonical form. + + Removes paths that are covered by another path. For example, + "foo.bar" is covered by "foo" and will be removed if "foo" + is also in the FieldMask. Then sorts all paths in alphabetical order. + + Args: + mask: The original FieldMask to be converted. + """ + tree = _FieldMaskTree(mask) + tree.ToFieldMask(self) + + def Union(self, mask1, mask2): + """Merges mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + tree.MergeFromFieldMask(mask2) + tree.ToFieldMask(self) + + def Intersect(self, mask1, mask2): + """Intersects mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + intersection = _FieldMaskTree() + for path in mask2.paths: + tree.IntersectPath(path, intersection) + intersection.ToFieldMask(self) + + def MergeMessage( + self, source, destination, + replace_message_field=False, replace_repeated_field=False): + """Merges fields specified in FieldMask from source to destination. + + Args: + source: Source message. + destination: The destination message to be merged into. + replace_message_field: Replace message field if True. Merge message + field if False. + replace_repeated_field: Replace repeated field if True. Append + elements of repeated field if False. + """ + tree = _FieldMaskTree(self) + tree.MergeMessage( + source, destination, replace_message_field, replace_repeated_field) + + +def _IsValidPath(message_descriptor, path): + """Checks whether the path is valid for Message Descriptor.""" + parts = path.split('.') + last = parts.pop() + for name in parts: + field = message_descriptor.fields_by_name.get(name) + if (field is None or + field.label == FieldDescriptor.LABEL_REPEATED or + field.type != FieldDescriptor.TYPE_MESSAGE): + return False + message_descriptor = field.message_type + return last in message_descriptor.fields_by_name + + +def _CheckFieldMaskMessage(message): + """Raises ValueError if message is not a FieldMask.""" + message_descriptor = message.DESCRIPTOR + if (message_descriptor.name != 'FieldMask' or + message_descriptor.file.name != 'google/protobuf/field_mask.proto'): + raise ValueError('Message {0} is not a FieldMask.'.format( + message_descriptor.full_name)) + + +def _SnakeCaseToCamelCase(path_name): + """Converts a path name from snake_case to camelCase.""" + result = [] + after_underscore = False + for c in path_name: + if c.isupper(): + raise ValueError( + 'Fail to print FieldMask to Json string: Path name ' + '{0} must not contain uppercase letters.'.format(path_name)) + if after_underscore: + if c.islower(): + result.append(c.upper()) + after_underscore = False + else: + raise ValueError( + 'Fail to print FieldMask to Json string: The ' + 'character after a "_" must be a lowercase letter ' + 'in path name {0}.'.format(path_name)) + elif c == '_': + after_underscore = True + else: + result += c + + if after_underscore: + raise ValueError('Fail to print FieldMask to Json string: Trailing "_" ' + 'in path name {0}.'.format(path_name)) + return ''.join(result) + + +def _CamelCaseToSnakeCase(path_name): + """Converts a field name from camelCase to snake_case.""" + result = [] + for c in path_name: + if c == '_': + raise ValueError('Fail to parse FieldMask: Path name ' + '{0} must not contain "_"s.'.format(path_name)) + if c.isupper(): + result += '_' + result += c.lower() + else: + result += c + return ''.join(result) + + +class _FieldMaskTree(object): + """Represents a FieldMask in a tree structure. + + For example, given a FieldMask "foo.bar,foo.baz,bar.baz", + the FieldMaskTree will be: + [_root] -+- foo -+- bar + | | + | +- baz + | + +- bar --- baz + In the tree, each leaf node represents a field path. + """ + + __slots__ = ('_root',) + + def __init__(self, field_mask=None): + """Initializes the tree by FieldMask.""" + self._root = {} + if field_mask: + self.MergeFromFieldMask(field_mask) + + def MergeFromFieldMask(self, field_mask): + """Merges a FieldMask to the tree.""" + for path in field_mask.paths: + self.AddPath(path) + + def AddPath(self, path): + """Adds a field path into the tree. + + If the field path to add is a sub-path of an existing field path + in the tree (i.e., a leaf node), it means the tree already matches + the given path so nothing will be added to the tree. If the path + matches an existing non-leaf node in the tree, that non-leaf node + will be turned into a leaf node with all its children removed because + the path matches all the node's children. Otherwise, a new path will + be added. + + Args: + path: The field path to add. + """ + node = self._root + for name in path.split('.'): + if name not in node: + node[name] = {} + elif not node[name]: + # Pre-existing empty node implies we already have this entire tree. + return + node = node[name] + # Remove any sub-trees we might have had. + node.clear() + + def ToFieldMask(self, field_mask): + """Converts the tree to a FieldMask.""" + field_mask.Clear() + _AddFieldPaths(self._root, '', field_mask) + + def IntersectPath(self, path, intersection): + """Calculates the intersection part of a field path with this tree. + + Args: + path: The field path to calculates. + intersection: The out tree to record the intersection part. + """ + node = self._root + for name in path.split('.'): + if name not in node: + return + elif not node[name]: + intersection.AddPath(path) + return + node = node[name] + intersection.AddLeafNodes(path, node) + + def AddLeafNodes(self, prefix, node): + """Adds leaf nodes begin with prefix to this tree.""" + if not node: + self.AddPath(prefix) + for name in node: + child_path = prefix + '.' + name + self.AddLeafNodes(child_path, node[name]) + + def MergeMessage( + self, source, destination, + replace_message, replace_repeated): + """Merge all fields specified by this tree from source to destination.""" + _MergeMessage( + self._root, source, destination, replace_message, replace_repeated) + + +def _StrConvert(value): + """Converts value to str if it is not.""" + # This file is imported by c extension and some methods like ClearField + # requires string for the field name. py2/py3 has different text + # type and may use unicode. + if not isinstance(value, str): + return value.encode('utf-8') + return value + + +def _MergeMessage( + node, source, destination, replace_message, replace_repeated): + """Merge all fields specified by a sub-tree from source to destination.""" + source_descriptor = source.DESCRIPTOR + for name in node: + child = node[name] + field = source_descriptor.fields_by_name[name] + if field is None: + raise ValueError('Error: Can\'t find field {0} in message {1}.'.format( + name, source_descriptor.full_name)) + if child: + # Sub-paths are only allowed for singular message fields. + if (field.label == FieldDescriptor.LABEL_REPEATED or + field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE): + raise ValueError('Error: Field {0} in message {1} is not a singular ' + 'message field and cannot have sub-fields.'.format( + name, source_descriptor.full_name)) + if source.HasField(name): + _MergeMessage( + child, getattr(source, name), getattr(destination, name), + replace_message, replace_repeated) + continue + if field.label == FieldDescriptor.LABEL_REPEATED: + if replace_repeated: + destination.ClearField(_StrConvert(name)) + repeated_source = getattr(source, name) + repeated_destination = getattr(destination, name) + repeated_destination.MergeFrom(repeated_source) + else: + if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + if replace_message: + destination.ClearField(_StrConvert(name)) + if source.HasField(name): + getattr(destination, name).MergeFrom(getattr(source, name)) + else: + setattr(destination, name, getattr(source, name)) + + +def _AddFieldPaths(node, prefix, field_mask): + """Adds the field paths descended from node to field_mask.""" + if not node and prefix: + field_mask.paths.append(prefix) + return + for name in sorted(node): + if prefix: + child_path = prefix + '.' + name + else: + child_path = name + _AddFieldPaths(node[name], child_path, field_mask) + + +def _SetStructValue(struct_value, value): + if value is None: + struct_value.null_value = 0 + elif isinstance(value, bool): + # Note: this check must come before the number check because in Python + # True and False are also considered numbers. + struct_value.bool_value = value + elif isinstance(value, str): + struct_value.string_value = value + elif isinstance(value, (int, float)): + struct_value.number_value = value + elif isinstance(value, (dict, Struct)): + struct_value.struct_value.Clear() + struct_value.struct_value.update(value) + elif isinstance(value, (list, ListValue)): + struct_value.list_value.Clear() + struct_value.list_value.extend(value) + else: + raise ValueError('Unexpected type') + + +def _GetStructValue(struct_value): + which = struct_value.WhichOneof('kind') + if which == 'struct_value': + return struct_value.struct_value + elif which == 'null_value': + return None + elif which == 'number_value': + return struct_value.number_value + elif which == 'string_value': + return struct_value.string_value + elif which == 'bool_value': + return struct_value.bool_value + elif which == 'list_value': + return struct_value.list_value + elif which is None: + raise ValueError('Value not set') + + +class Struct(object): + """Class for Struct message type.""" + + __slots__ = () + + def __getitem__(self, key): + return _GetStructValue(self.fields[key]) + + def __contains__(self, item): + return item in self.fields + + def __setitem__(self, key, value): + _SetStructValue(self.fields[key], value) + + def __delitem__(self, key): + del self.fields[key] + + def __len__(self): + return len(self.fields) + + def __iter__(self): + return iter(self.fields) + + def keys(self): # pylint: disable=invalid-name + return self.fields.keys() + + def values(self): # pylint: disable=invalid-name + return [self[key] for key in self] + + def items(self): # pylint: disable=invalid-name + return [(key, self[key]) for key in self] + + def get_or_create_list(self, key): + """Returns a list for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('list_value'): + # Clear will mark list_value modified which will indeed create a list. + self.fields[key].list_value.Clear() + return self.fields[key].list_value + + def get_or_create_struct(self, key): + """Returns a struct for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('struct_value'): + # Clear will mark struct_value modified which will indeed create a struct. + self.fields[key].struct_value.Clear() + return self.fields[key].struct_value + + def update(self, dictionary): # pylint: disable=invalid-name + for key, value in dictionary.items(): + _SetStructValue(self.fields[key], value) + +collections.abc.MutableMapping.register(Struct) + + +class ListValue(object): + """Class for ListValue message type.""" + + __slots__ = () + + def __len__(self): + return len(self.values) + + def append(self, value): + _SetStructValue(self.values.add(), value) + + def extend(self, elem_seq): + for value in elem_seq: + self.append(value) + + def __getitem__(self, index): + """Retrieves item by the specified index.""" + return _GetStructValue(self.values.__getitem__(index)) + + def __setitem__(self, index, value): + _SetStructValue(self.values.__getitem__(index), value) + + def __delitem__(self, key): + del self.values[key] + + def items(self): + for i in range(len(self)): + yield self[i] + + def add_struct(self): + """Appends and returns a struct value as the next value in the list.""" + struct_value = self.values.add().struct_value + # Clear will mark struct_value modified which will indeed create a struct. + struct_value.Clear() + return struct_value + + def add_list(self): + """Appends and returns a list value as the next value in the list.""" + list_value = self.values.add().list_value + # Clear will mark list_value modified which will indeed create a list. + list_value.Clear() + return list_value + +collections.abc.MutableSequence.register(ListValue) + + +WKTBASES = { + 'google.protobuf.Any': Any, + 'google.protobuf.Duration': Duration, + 'google.protobuf.FieldMask': FieldMask, + 'google.protobuf.ListValue': ListValue, + 'google.protobuf.Struct': Struct, + 'google.protobuf.Timestamp': Timestamp, +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/wire_format.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/wire_format.py new file mode 100644 index 0000000000000000000000000000000000000000..883f525585139493438c3c8922bbb82cf1b0084e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/internal/wire_format.py @@ -0,0 +1,268 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Constants and static functions to support protocol buffer wire format.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import struct +from google.protobuf import descriptor +from google.protobuf import message + + +TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. +TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 + +# These numbers identify the wire type of a protocol buffer value. +# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded +# tag-and-type to store one of these WIRETYPE_* constants. +# These values must match WireType enum in google/protobuf/wire_format.h. +WIRETYPE_VARINT = 0 +WIRETYPE_FIXED64 = 1 +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 +WIRETYPE_END_GROUP = 4 +WIRETYPE_FIXED32 = 5 +_WIRETYPE_MAX = 5 + + +# Bounds for various integer types. +INT32_MAX = int((1 << 31) - 1) +INT32_MIN = int(-(1 << 31)) +UINT32_MAX = (1 << 32) - 1 + +INT64_MAX = (1 << 63) - 1 +INT64_MIN = -(1 << 63) +UINT64_MAX = (1 << 64) - 1 + +# "struct" format strings that will encode/decode the specified formats. +FORMAT_UINT32_LITTLE_ENDIAN = '> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) + + +def ZigZagEncode(value): + """ZigZag Transform: Encodes signed integers so that they can be + effectively used with varint encoding. See wire_format.h for + more details. + """ + if value >= 0: + return value << 1 + return (value << 1) ^ (~0) + + +def ZigZagDecode(value): + """Inverse of ZigZagEncode().""" + if not value & 0x1: + return value >> 1 + return (value >> 1) ^ (~0) + + + +# The *ByteSize() functions below return the number of bytes required to +# serialize "field number + type" information and then serialize the value. + + +def Int32ByteSize(field_number, int32): + return Int64ByteSize(field_number, int32) + + +def Int32ByteSizeNoTag(int32): + return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) + + +def Int64ByteSize(field_number, int64): + # Have to convert to uint before calling UInt64ByteSize(). + return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) + + +def UInt32ByteSize(field_number, uint32): + return UInt64ByteSize(field_number, uint32) + + +def UInt64ByteSize(field_number, uint64): + return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) + + +def SInt32ByteSize(field_number, int32): + return UInt32ByteSize(field_number, ZigZagEncode(int32)) + + +def SInt64ByteSize(field_number, int64): + return UInt64ByteSize(field_number, ZigZagEncode(int64)) + + +def Fixed32ByteSize(field_number, fixed32): + return TagByteSize(field_number) + 4 + + +def Fixed64ByteSize(field_number, fixed64): + return TagByteSize(field_number) + 8 + + +def SFixed32ByteSize(field_number, sfixed32): + return TagByteSize(field_number) + 4 + + +def SFixed64ByteSize(field_number, sfixed64): + return TagByteSize(field_number) + 8 + + +def FloatByteSize(field_number, flt): + return TagByteSize(field_number) + 4 + + +def DoubleByteSize(field_number, double): + return TagByteSize(field_number) + 8 + + +def BoolByteSize(field_number, b): + return TagByteSize(field_number) + 1 + + +def EnumByteSize(field_number, enum): + return UInt32ByteSize(field_number, enum) + + +def StringByteSize(field_number, string): + return BytesByteSize(field_number, string.encode('utf-8')) + + +def BytesByteSize(field_number, b): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(len(b)) + + len(b)) + + +def GroupByteSize(field_number, message): + return (2 * TagByteSize(field_number) # START and END group. + + message.ByteSize()) + + +def MessageByteSize(field_number, message): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(message.ByteSize()) + + message.ByteSize()) + + +def MessageSetItemByteSize(field_number, msg): + # First compute the sizes of the tags. + # There are 2 tags for the beginning and ending of the repeated group, that + # is field number 1, one with field number 2 (type_id) and one with field + # number 3 (message). + total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) + + # Add the number of bytes for type_id. + total_size += _VarUInt64ByteSizeNoTag(field_number) + + message_size = msg.ByteSize() + + # The number of bytes for encoding the length of the message. + total_size += _VarUInt64ByteSizeNoTag(message_size) + + # The size of the message. + total_size += message_size + return total_size + + +def TagByteSize(field_number): + """Returns the bytes required to serialize a tag with this field number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) + + +# Private helper function for the *ByteSize() functions above. + +def _VarUInt64ByteSizeNoTag(uint64): + """Returns the number of bytes required to serialize a single varint + using boundary value comparisons. (unrolled loop optimization -WPierce) + uint64 must be unsigned. + """ + if uint64 <= 0x7f: return 1 + if uint64 <= 0x3fff: return 2 + if uint64 <= 0x1fffff: return 3 + if uint64 <= 0xfffffff: return 4 + if uint64 <= 0x7ffffffff: return 5 + if uint64 <= 0x3ffffffffff: return 6 + if uint64 <= 0x1ffffffffffff: return 7 + if uint64 <= 0xffffffffffffff: return 8 + if uint64 <= 0x7fffffffffffffff: return 9 + if uint64 > UINT64_MAX: + raise message.EncodeError('Value out of range: %d' % uint64) + return 10 + + +NON_PACKABLE_TYPES = ( + descriptor.FieldDescriptor.TYPE_STRING, + descriptor.FieldDescriptor.TYPE_GROUP, + descriptor.FieldDescriptor.TYPE_MESSAGE, + descriptor.FieldDescriptor.TYPE_BYTES +) + + +def IsTypePackable(field_type): + """Return true iff packable = true is valid for fields of this type. + + Args: + field_type: a FieldDescriptor::Type value. + + Returns: + True iff fields of this type are packable. + """ + return field_type not in NON_PACKABLE_TYPES diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/json_format.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/json_format.py new file mode 100644 index 0000000000000000000000000000000000000000..5024ed89d7d3a7f0165b1ef9fe661b78c4c1d37f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/json_format.py @@ -0,0 +1,912 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains routines for printing protocol messages in JSON format. + +Simple usage example: + + # Create a proto object and serialize it to a json format string. + message = my_proto_pb2.MyMessage(foo='bar') + json_string = json_format.MessageToJson(message) + + # Parse a json format string to proto object. + message = json_format.Parse(json_string, my_proto_pb2.MyMessage()) +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + + +import base64 +from collections import OrderedDict +import json +import math +from operator import methodcaller +import re +import sys + +from google.protobuf.internal import type_checkers +from google.protobuf import descriptor +from google.protobuf import symbol_database + + +_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S' +_INT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT32, + descriptor.FieldDescriptor.CPPTYPE_UINT32, + descriptor.FieldDescriptor.CPPTYPE_INT64, + descriptor.FieldDescriptor.CPPTYPE_UINT64]) +_INT64_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_INT64, + descriptor.FieldDescriptor.CPPTYPE_UINT64]) +_FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT, + descriptor.FieldDescriptor.CPPTYPE_DOUBLE]) +_INFINITY = 'Infinity' +_NEG_INFINITY = '-Infinity' +_NAN = 'NaN' + +_UNPAIRED_SURROGATE_PATTERN = re.compile( + u'[\ud800-\udbff](?![\udc00-\udfff])|(? self.max_recursion_depth: + raise ParseError('Message too deep. Max recursion depth is {0}'.format( + self.max_recursion_depth)) + message_descriptor = message.DESCRIPTOR + full_name = message_descriptor.full_name + if not path: + path = message_descriptor.name + if _IsWrapperMessage(message_descriptor): + self._ConvertWrapperMessage(value, message, path) + elif full_name in _WKTJSONMETHODS: + methodcaller(_WKTJSONMETHODS[full_name][1], value, message, path)(self) + else: + self._ConvertFieldValuePair(value, message, path) + self.recursion_depth -= 1 + + def _ConvertFieldValuePair(self, js, message, path): + """Convert field value pairs into regular message. + + Args: + js: A JSON object to convert the field value pairs. + message: A regular protocol message to record the data. + path: parent path to log parse error info. + + Raises: + ParseError: In case of problems converting. + """ + names = [] + message_descriptor = message.DESCRIPTOR + fields_by_json_name = dict((f.json_name, f) + for f in message_descriptor.fields) + for name in js: + try: + field = fields_by_json_name.get(name, None) + if not field: + field = message_descriptor.fields_by_name.get(name, None) + if not field and _VALID_EXTENSION_NAME.match(name): + if not message_descriptor.is_extendable: + raise ParseError( + 'Message type {0} does not have extensions at {1}'.format( + message_descriptor.full_name, path)) + identifier = name[1:-1] # strip [] brackets + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(identifier) + # pylint: enable=protected-access + if not field: + # Try looking for extension by the message type name, dropping the + # field name following the final . separator in full_name. + identifier = '.'.join(identifier.split('.')[:-1]) + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(identifier) + # pylint: enable=protected-access + if not field: + if self.ignore_unknown_fields: + continue + raise ParseError( + ('Message type "{0}" has no field named "{1}" at "{2}".\n' + ' Available Fields(except extensions): "{3}"').format( + message_descriptor.full_name, name, path, + [f.json_name for f in message_descriptor.fields])) + if name in names: + raise ParseError('Message type "{0}" should not have multiple ' + '"{1}" fields at "{2}".'.format( + message.DESCRIPTOR.full_name, name, path)) + names.append(name) + value = js[name] + # Check no other oneof field is parsed. + if field.containing_oneof is not None and value is not None: + oneof_name = field.containing_oneof.name + if oneof_name in names: + raise ParseError('Message type "{0}" should not have multiple ' + '"{1}" oneof fields at "{2}".'.format( + message.DESCRIPTOR.full_name, oneof_name, + path)) + names.append(oneof_name) + + if value is None: + if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE + and field.message_type.full_name == 'google.protobuf.Value'): + sub_message = getattr(message, field.name) + sub_message.null_value = 0 + elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM + and field.enum_type.full_name == 'google.protobuf.NullValue'): + setattr(message, field.name, 0) + else: + message.ClearField(field.name) + continue + + # Parse field value. + if _IsMapEntry(field): + message.ClearField(field.name) + self._ConvertMapFieldValue(value, message, field, + '{0}.{1}'.format(path, name)) + elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + message.ClearField(field.name) + if not isinstance(value, list): + raise ParseError('repeated field {0} must be in [] which is ' + '{1} at {2}'.format(name, value, path)) + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + # Repeated message field. + for index, item in enumerate(value): + sub_message = getattr(message, field.name).add() + # None is a null_value in Value. + if (item is None and + sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'): + raise ParseError('null is not allowed to be used as an element' + ' in a repeated field at {0}.{1}[{2}]'.format( + path, name, index)) + self.ConvertMessage(item, sub_message, + '{0}.{1}[{2}]'.format(path, name, index)) + else: + # Repeated scalar field. + for index, item in enumerate(value): + if item is None: + raise ParseError('null is not allowed to be used as an element' + ' in a repeated field at {0}.{1}[{2}]'.format( + path, name, index)) + getattr(message, field.name).append( + _ConvertScalarFieldValue( + item, field, '{0}.{1}[{2}]'.format(path, name, index))) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_extension: + sub_message = message.Extensions[field] + else: + sub_message = getattr(message, field.name) + sub_message.SetInParent() + self.ConvertMessage(value, sub_message, '{0}.{1}'.format(path, name)) + else: + if field.is_extension: + message.Extensions[field] = _ConvertScalarFieldValue( + value, field, '{0}.{1}'.format(path, name)) + else: + setattr( + message, field.name, + _ConvertScalarFieldValue(value, field, + '{0}.{1}'.format(path, name))) + except ParseError as e: + if field and field.containing_oneof is None: + raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) + else: + raise ParseError(str(e)) + except ValueError as e: + raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) + except TypeError as e: + raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) + + def _ConvertAnyMessage(self, value, message, path): + """Convert a JSON representation into Any message.""" + if isinstance(value, dict) and not value: + return + try: + type_url = value['@type'] + except KeyError: + raise ParseError( + '@type is missing when parsing any message at {0}'.format(path)) + + try: + sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool) + except TypeError as e: + raise ParseError('{0} at {1}'.format(e, path)) + message_descriptor = sub_message.DESCRIPTOR + full_name = message_descriptor.full_name + if _IsWrapperMessage(message_descriptor): + self._ConvertWrapperMessage(value['value'], sub_message, + '{0}.value'.format(path)) + elif full_name in _WKTJSONMETHODS: + methodcaller(_WKTJSONMETHODS[full_name][1], value['value'], sub_message, + '{0}.value'.format(path))( + self) + else: + del value['@type'] + self._ConvertFieldValuePair(value, sub_message, path) + value['@type'] = type_url + # Sets Any message + message.value = sub_message.SerializeToString() + message.type_url = type_url + + def _ConvertGenericMessage(self, value, message, path): + """Convert a JSON representation into message with FromJsonString.""" + # Duration, Timestamp, FieldMask have a FromJsonString method to do the + # conversion. Users can also call the method directly. + try: + message.FromJsonString(value) + except ValueError as e: + raise ParseError('{0} at {1}'.format(e, path)) + + def _ConvertValueMessage(self, value, message, path): + """Convert a JSON representation into Value message.""" + if isinstance(value, dict): + self._ConvertStructMessage(value, message.struct_value, path) + elif isinstance(value, list): + self._ConvertListValueMessage(value, message.list_value, path) + elif value is None: + message.null_value = 0 + elif isinstance(value, bool): + message.bool_value = value + elif isinstance(value, str): + message.string_value = value + elif isinstance(value, _INT_OR_FLOAT): + message.number_value = value + else: + raise ParseError('Value {0} has unexpected type {1} at {2}'.format( + value, type(value), path)) + + def _ConvertListValueMessage(self, value, message, path): + """Convert a JSON representation into ListValue message.""" + if not isinstance(value, list): + raise ParseError('ListValue must be in [] which is {0} at {1}'.format( + value, path)) + message.ClearField('values') + for index, item in enumerate(value): + self._ConvertValueMessage(item, message.values.add(), + '{0}[{1}]'.format(path, index)) + + def _ConvertStructMessage(self, value, message, path): + """Convert a JSON representation into Struct message.""" + if not isinstance(value, dict): + raise ParseError('Struct must be in a dict which is {0} at {1}'.format( + value, path)) + # Clear will mark the struct as modified so it will be created even if + # there are no values. + message.Clear() + for key in value: + self._ConvertValueMessage(value[key], message.fields[key], + '{0}.{1}'.format(path, key)) + return + + def _ConvertWrapperMessage(self, value, message, path): + """Convert a JSON representation into Wrapper message.""" + field = message.DESCRIPTOR.fields_by_name['value'] + setattr( + message, 'value', + _ConvertScalarFieldValue(value, field, path='{0}.value'.format(path))) + + def _ConvertMapFieldValue(self, value, message, field, path): + """Convert map field value for a message map field. + + Args: + value: A JSON object to convert the map field value. + message: A protocol message to record the converted data. + field: The descriptor of the map field to be converted. + path: parent path to log parse error info. + + Raises: + ParseError: In case of convert problems. + """ + if not isinstance(value, dict): + raise ParseError( + 'Map field {0} must be in a dict which is {1} at {2}'.format( + field.name, value, path)) + key_field = field.message_type.fields_by_name['key'] + value_field = field.message_type.fields_by_name['value'] + for key in value: + key_value = _ConvertScalarFieldValue(key, key_field, + '{0}.key'.format(path), True) + if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + self.ConvertMessage(value[key], + getattr(message, field.name)[key_value], + '{0}[{1}]'.format(path, key_value)) + else: + getattr(message, field.name)[key_value] = _ConvertScalarFieldValue( + value[key], value_field, path='{0}[{1}]'.format(path, key_value)) + + +def _ConvertScalarFieldValue(value, field, path, require_str=False): + """Convert a single scalar field value. + + Args: + value: A scalar value to convert the scalar field value. + field: The descriptor of the field to convert. + path: parent path to log parse error info. + require_str: If True, the field value must be a str. + + Returns: + The converted scalar field value + + Raises: + ParseError: In case of convert problems. + """ + try: + if field.cpp_type in _INT_TYPES: + return _ConvertInteger(value) + elif field.cpp_type in _FLOAT_TYPES: + return _ConvertFloat(value, field) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: + return _ConvertBool(value, require_str) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: + if field.type == descriptor.FieldDescriptor.TYPE_BYTES: + if isinstance(value, str): + encoded = value.encode('utf-8') + else: + encoded = value + # Add extra padding '=' + padded_value = encoded + b'=' * (4 - len(encoded) % 4) + return base64.urlsafe_b64decode(padded_value) + else: + # Checking for unpaired surrogates appears to be unreliable, + # depending on the specific Python version, so we check manually. + if _UNPAIRED_SURROGATE_PATTERN.search(value): + raise ParseError('Unpaired surrogate') + return value + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + # Convert an enum value. + enum_value = field.enum_type.values_by_name.get(value, None) + if enum_value is None: + try: + number = int(value) + enum_value = field.enum_type.values_by_number.get(number, None) + except ValueError: + raise ParseError('Invalid enum value {0} for enum type {1}'.format( + value, field.enum_type.full_name)) + if enum_value is None: + if field.file.syntax == 'proto3': + # Proto3 accepts unknown enums. + return number + raise ParseError('Invalid enum value {0} for enum type {1}'.format( + value, field.enum_type.full_name)) + return enum_value.number + except ParseError as e: + raise ParseError('{0} at {1}'.format(e, path)) + + +def _ConvertInteger(value): + """Convert an integer. + + Args: + value: A scalar value to convert. + + Returns: + The integer value. + + Raises: + ParseError: If an integer couldn't be consumed. + """ + if isinstance(value, float) and not value.is_integer(): + raise ParseError('Couldn\'t parse integer: {0}'.format(value)) + + if isinstance(value, str) and value.find(' ') != -1: + raise ParseError('Couldn\'t parse integer: "{0}"'.format(value)) + + if isinstance(value, bool): + raise ParseError('Bool value {0} is not acceptable for ' + 'integer field'.format(value)) + + return int(value) + + +def _ConvertFloat(value, field): + """Convert an floating point number.""" + if isinstance(value, float): + if math.isnan(value): + raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead') + if math.isinf(value): + if value > 0: + raise ParseError('Couldn\'t parse Infinity or value too large, ' + 'use quoted "Infinity" instead') + else: + raise ParseError('Couldn\'t parse -Infinity or value too small, ' + 'use quoted "-Infinity" instead') + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT: + # pylint: disable=protected-access + if value > type_checkers._FLOAT_MAX: + raise ParseError('Float value too large') + # pylint: disable=protected-access + if value < type_checkers._FLOAT_MIN: + raise ParseError('Float value too small') + if value == 'nan': + raise ParseError('Couldn\'t parse float "nan", use "NaN" instead') + try: + # Assume Python compatible syntax. + return float(value) + except ValueError: + # Check alternative spellings. + if value == _NEG_INFINITY: + return float('-inf') + elif value == _INFINITY: + return float('inf') + elif value == _NAN: + return float('nan') + else: + raise ParseError('Couldn\'t parse float: {0}'.format(value)) + + +def _ConvertBool(value, require_str): + """Convert a boolean value. + + Args: + value: A scalar value to convert. + require_str: If True, value must be a str. + + Returns: + The bool parsed. + + Raises: + ParseError: If a boolean value couldn't be consumed. + """ + if require_str: + if value == 'true': + return True + elif value == 'false': + return False + else: + raise ParseError('Expected "true" or "false", not {0}'.format(value)) + + if not isinstance(value, bool): + raise ParseError('Expected true or false without quotes') + return value + +_WKTJSONMETHODS = { + 'google.protobuf.Any': ['_AnyMessageToJsonObject', + '_ConvertAnyMessage'], + 'google.protobuf.Duration': ['_GenericMessageToJsonObject', + '_ConvertGenericMessage'], + 'google.protobuf.FieldMask': ['_GenericMessageToJsonObject', + '_ConvertGenericMessage'], + 'google.protobuf.ListValue': ['_ListValueMessageToJsonObject', + '_ConvertListValueMessage'], + 'google.protobuf.Struct': ['_StructMessageToJsonObject', + '_ConvertStructMessage'], + 'google.protobuf.Timestamp': ['_GenericMessageToJsonObject', + '_ConvertGenericMessage'], + 'google.protobuf.Value': ['_ValueMessageToJsonObject', + '_ConvertValueMessage'] +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message.py new file mode 100644 index 0000000000000000000000000000000000000000..76c6802f7096639c67471fbbd923d5616053068c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message.py @@ -0,0 +1,424 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# TODO(robinson): We should just make these methods all "pure-virtual" and move +# all implementation out, into reflection.py for now. + + +"""Contains an abstract base class for protocol messages.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +class Error(Exception): + """Base error type for this module.""" + pass + + +class DecodeError(Error): + """Exception raised when deserializing messages.""" + pass + + +class EncodeError(Error): + """Exception raised when serializing messages.""" + pass + + +class Message(object): + + """Abstract base class for protocol messages. + + Protocol message classes are almost always generated by the protocol + compiler. These generated types subclass Message and implement the methods + shown below. + """ + + # TODO(robinson): Link to an HTML document here. + + # TODO(robinson): Document that instances of this class will also + # have an Extensions attribute with __getitem__ and __setitem__. + # Again, not sure how to best convey this. + + # TODO(robinson): Document that the class must also have a static + # RegisterExtension(extension_field) method. + # Not sure how to best express at this point. + + # TODO(robinson): Document these fields and methods. + + __slots__ = [] + + #: The :class:`google.protobuf.descriptor.Descriptor` for this message type. + DESCRIPTOR = None + + def __deepcopy__(self, memo=None): + clone = type(self)() + clone.MergeFrom(self) + return clone + + def __eq__(self, other_msg): + """Recursively compares two messages by value and structure.""" + raise NotImplementedError + + def __ne__(self, other_msg): + # Can't just say self != other_msg, since that would infinitely recurse. :) + return not self == other_msg + + def __hash__(self): + raise TypeError('unhashable object') + + def __str__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def __unicode__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def MergeFrom(self, other_msg): + """Merges the contents of the specified message into current message. + + This method merges the contents of the specified message into the current + message. Singular fields that are set in the specified message overwrite + the corresponding fields in the current message. Repeated fields are + appended. Singular sub-messages and groups are recursively merged. + + Args: + other_msg (Message): A message to merge into the current message. + """ + raise NotImplementedError + + def CopyFrom(self, other_msg): + """Copies the content of the specified message into the current message. + + The method clears the current message and then merges the specified + message using MergeFrom. + + Args: + other_msg (Message): A message to copy into the current one. + """ + if self is other_msg: + return + self.Clear() + self.MergeFrom(other_msg) + + def Clear(self): + """Clears all data that was set in the message.""" + raise NotImplementedError + + def SetInParent(self): + """Mark this as present in the parent. + + This normally happens automatically when you assign a field of a + sub-message, but sometimes you want to make the sub-message + present while keeping it empty. If you find yourself using this, + you may want to reconsider your design. + """ + raise NotImplementedError + + def IsInitialized(self): + """Checks if the message is initialized. + + Returns: + bool: The method returns True if the message is initialized (i.e. all of + its required fields are set). + """ + raise NotImplementedError + + # TODO(robinson): MergeFromString() should probably return None and be + # implemented in terms of a helper that returns the # of bytes read. Our + # deserialization routines would use the helper when recursively + # deserializing, but the end user would almost always just want the no-return + # MergeFromString(). + + def MergeFromString(self, serialized): + """Merges serialized protocol buffer data into this message. + + When we find a field in `serialized` that is already present + in this message: + + - If it's a "repeated" field, we append to the end of our list. + - Else, if it's a scalar, we overwrite our field. + - Else, (it's a nonrepeated composite), we recursively merge + into the existing composite. + + Args: + serialized (bytes): Any object that allows us to call + ``memoryview(serialized)`` to access a string of bytes using the + buffer interface. + + Returns: + int: The number of bytes read from `serialized`. + For non-group messages, this will always be `len(serialized)`, + but for messages which are actually groups, this will + generally be less than `len(serialized)`, since we must + stop when we reach an ``END_GROUP`` tag. Note that if + we *do* stop because of an ``END_GROUP`` tag, the number + of bytes returned does not include the bytes + for the ``END_GROUP`` tag information. + + Raises: + DecodeError: if the input cannot be parsed. + """ + # TODO(robinson): Document handling of unknown fields. + # TODO(robinson): When we switch to a helper, this will return None. + raise NotImplementedError + + def ParseFromString(self, serialized): + """Parse serialized protocol buffer data into this message. + + Like :func:`MergeFromString()`, except we clear the object first. + + Raises: + message.DecodeError if the input cannot be parsed. + """ + self.Clear() + return self.MergeFromString(serialized) + + def SerializeToString(self, **kwargs): + """Serializes the protocol message to a binary string. + + Keyword Args: + deterministic (bool): If true, requests deterministic serialization + of the protobuf, with predictable ordering of map keys. + + Returns: + A binary string representation of the message if all of the required + fields in the message are set (i.e. the message is initialized). + + Raises: + EncodeError: if the message isn't initialized (see :func:`IsInitialized`). + """ + raise NotImplementedError + + def SerializePartialToString(self, **kwargs): + """Serializes the protocol message to a binary string. + + This method is similar to SerializeToString but doesn't check if the + message is initialized. + + Keyword Args: + deterministic (bool): If true, requests deterministic serialization + of the protobuf, with predictable ordering of map keys. + + Returns: + bytes: A serialized representation of the partial message. + """ + raise NotImplementedError + + # TODO(robinson): Decide whether we like these better + # than auto-generated has_foo() and clear_foo() methods + # on the instances themselves. This way is less consistent + # with C++, but it makes reflection-type access easier and + # reduces the number of magically autogenerated things. + # + # TODO(robinson): Be sure to document (and test) exactly + # which field names are accepted here. Are we case-sensitive? + # What do we do with fields that share names with Python keywords + # like 'lambda' and 'yield'? + # + # nnorwitz says: + # """ + # Typically (in python), an underscore is appended to names that are + # keywords. So they would become lambda_ or yield_. + # """ + def ListFields(self): + """Returns a list of (FieldDescriptor, value) tuples for present fields. + + A message field is non-empty if HasField() would return true. A singular + primitive field is non-empty if HasField() would return true in proto2 or it + is non zero in proto3. A repeated field is non-empty if it contains at least + one element. The fields are ordered by field number. + + Returns: + list[tuple(FieldDescriptor, value)]: field descriptors and values + for all fields in the message which are not empty. The values vary by + field type. + """ + raise NotImplementedError + + def HasField(self, field_name): + """Checks if a certain field is set for the message. + + For a oneof group, checks if any field inside is set. Note that if the + field_name is not defined in the message descriptor, :exc:`ValueError` will + be raised. + + Args: + field_name (str): The name of the field to check for presence. + + Returns: + bool: Whether a value has been set for the named field. + + Raises: + ValueError: if the `field_name` is not a member of this message. + """ + raise NotImplementedError + + def ClearField(self, field_name): + """Clears the contents of a given field. + + Inside a oneof group, clears the field set. If the name neither refers to a + defined field or oneof group, :exc:`ValueError` is raised. + + Args: + field_name (str): The name of the field to check for presence. + + Raises: + ValueError: if the `field_name` is not a member of this message. + """ + raise NotImplementedError + + def WhichOneof(self, oneof_group): + """Returns the name of the field that is set inside a oneof group. + + If no field is set, returns None. + + Args: + oneof_group (str): the name of the oneof group to check. + + Returns: + str or None: The name of the group that is set, or None. + + Raises: + ValueError: no group with the given name exists + """ + raise NotImplementedError + + def HasExtension(self, extension_handle): + """Checks if a certain extension is present for this message. + + Extensions are retrieved using the :attr:`Extensions` mapping (if present). + + Args: + extension_handle: The handle for the extension to check. + + Returns: + bool: Whether the extension is present for this message. + + Raises: + KeyError: if the extension is repeated. Similar to repeated fields, + there is no separate notion of presence: a "not present" repeated + extension is an empty list. + """ + raise NotImplementedError + + def ClearExtension(self, extension_handle): + """Clears the contents of a given extension. + + Args: + extension_handle: The handle for the extension to clear. + """ + raise NotImplementedError + + def UnknownFields(self): + """Returns the UnknownFieldSet. + + Returns: + UnknownFieldSet: The unknown fields stored in this message. + """ + raise NotImplementedError + + def DiscardUnknownFields(self): + """Clears all fields in the :class:`UnknownFieldSet`. + + This operation is recursive for nested message. + """ + raise NotImplementedError + + def ByteSize(self): + """Returns the serialized size of this message. + + Recursively calls ByteSize() on all contained messages. + + Returns: + int: The number of bytes required to serialize this message. + """ + raise NotImplementedError + + @classmethod + def FromString(cls, s): + raise NotImplementedError + + @staticmethod + def RegisterExtension(extension_handle): + raise NotImplementedError + + def _SetListener(self, message_listener): + """Internal method used by the protocol message implementation. + Clients should not call this directly. + + Sets a listener that this message will call on certain state transitions. + + The purpose of this method is to register back-edges from children to + parents at runtime, for the purpose of setting "has" bits and + byte-size-dirty bits in the parent and ancestor objects whenever a child or + descendant object is modified. + + If the client wants to disconnect this Message from the object tree, she + explicitly sets callback to None. + + If message_listener is None, unregisters any existing listener. Otherwise, + message_listener must implement the MessageListener interface in + internal/message_listener.py, and we discard any listener registered + via a previous _SetListener() call. + """ + raise NotImplementedError + + def __getstate__(self): + """Support the pickle protocol.""" + return dict(serialized=self.SerializePartialToString()) + + def __setstate__(self, state): + """Support the pickle protocol.""" + self.__init__() + serialized = state['serialized'] + # On Python 3, using encoding='latin1' is required for unpickling + # protos pickled by Python 2. + if not isinstance(serialized, bytes): + serialized = serialized.encode('latin1') + self.ParseFromString(serialized) + + def __reduce__(self): + message_descriptor = self.DESCRIPTOR + if message_descriptor.containing_type is None: + return type(self), (), self.__getstate__() + # the message type must be nested. + # Python does not pickle nested classes; use the symbol_database on the + # receiving end. + container = message_descriptor + return (_InternalConstructMessage, (container.full_name,), + self.__getstate__()) + + +def _InternalConstructMessage(full_name): + """Constructs a nested message.""" + from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top + + return symbol_database.Default().GetSymbol(full_name)() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..3656fa68747d520cd166c36b4752bc15cc211015 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/message_factory.py @@ -0,0 +1,185 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides a factory class for generating dynamic messages. + +The easiest way to use this class is if you have access to the FileDescriptor +protos containing the messages you want to create you can just do the following: + +message_classes = message_factory.GetMessages(iterable_of_file_descriptors) +my_proto_instance = message_classes['some.proto.package.MessageName']() +""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +from google.protobuf.internal import api_implementation +from google.protobuf import descriptor_pool +from google.protobuf import message + +if api_implementation.Type() == 'cpp': + from google.protobuf.pyext import cpp_message as message_impl +else: + from google.protobuf.internal import python_message as message_impl + + +# The type of all Message classes. +_GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType + + +class MessageFactory(object): + """Factory for creating Proto2 messages from descriptors in a pool.""" + + def __init__(self, pool=None): + """Initializes a new factory.""" + self.pool = pool or descriptor_pool.DescriptorPool() + + # local cache of all classes built from protobuf descriptors + self._classes = {} + + def GetPrototype(self, descriptor): + """Obtains a proto2 message class based on the passed in descriptor. + + Passing a descriptor with a fully qualified name matching a previous + invocation will cause the same class to be returned. + + Args: + descriptor: The descriptor to build from. + + Returns: + A class describing the passed in descriptor. + """ + if descriptor not in self._classes: + result_class = self.CreatePrototype(descriptor) + # The assignment to _classes is redundant for the base implementation, but + # might avoid confusion in cases where CreatePrototype gets overridden and + # does not call the base implementation. + self._classes[descriptor] = result_class + return result_class + return self._classes[descriptor] + + def CreatePrototype(self, descriptor): + """Builds a proto2 message class based on the passed in descriptor. + + Don't call this function directly, it always creates a new class. Call + GetPrototype() instead. This method is meant to be overridden in subblasses + to perform additional operations on the newly constructed class. + + Args: + descriptor: The descriptor to build from. + + Returns: + A class describing the passed in descriptor. + """ + descriptor_name = descriptor.name + result_class = _GENERATED_PROTOCOL_MESSAGE_TYPE( + descriptor_name, + (message.Message,), + { + 'DESCRIPTOR': descriptor, + # If module not set, it wrongly points to message_factory module. + '__module__': None, + }) + result_class._FACTORY = self # pylint: disable=protected-access + # Assign in _classes before doing recursive calls to avoid infinite + # recursion. + self._classes[descriptor] = result_class + for field in descriptor.fields: + if field.message_type: + self.GetPrototype(field.message_type) + for extension in result_class.DESCRIPTOR.extensions: + if extension.containing_type not in self._classes: + self.GetPrototype(extension.containing_type) + extended_class = self._classes[extension.containing_type] + extended_class.RegisterExtension(extension) + return result_class + + def GetMessages(self, files): + """Gets all the messages from a specified file. + + This will find and resolve dependencies, failing if the descriptor + pool cannot satisfy them. + + Args: + files: The file names to extract messages from. + + Returns: + A dictionary mapping proto names to the message classes. This will include + any dependent messages as well as any messages defined in the same file as + a specified message. + """ + result = {} + for file_name in files: + file_desc = self.pool.FindFileByName(file_name) + for desc in file_desc.message_types_by_name.values(): + result[desc.full_name] = self.GetPrototype(desc) + + # While the extension FieldDescriptors are created by the descriptor pool, + # the python classes created in the factory need them to be registered + # explicitly, which is done below. + # + # The call to RegisterExtension will specifically check if the + # extension was already registered on the object and either + # ignore the registration if the original was the same, or raise + # an error if they were different. + + for extension in file_desc.extensions_by_name.values(): + if extension.containing_type not in self._classes: + self.GetPrototype(extension.containing_type) + extended_class = self._classes[extension.containing_type] + extended_class.RegisterExtension(extension) + return result + + +_FACTORY = MessageFactory() + + +def GetMessages(file_protos): + """Builds a dictionary of all the messages available in a set of files. + + Args: + file_protos: Iterable of FileDescriptorProto to build messages out of. + + Returns: + A dictionary mapping proto names to the message classes. This will include + any dependent messages as well as any messages defined in the same file as + a specified message. + """ + # The cpp implementation of the protocol buffer library requires to add the + # message in topological order of the dependency graph. + file_by_name = {file_proto.name: file_proto for file_proto in file_protos} + def _AddFile(file_proto): + for dependency in file_proto.dependency: + if dependency in file_by_name: + # Remove from elements to be visited, in order to cut cycles. + _AddFile(file_by_name.pop(dependency)) + _FACTORY.pool.Add(file_proto) + while file_by_name: + _AddFile(file_by_name.popitem()[1]) + return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/proto_builder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/proto_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a4667ce63ec3c971a7233961da9a3adf100aa6b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/proto_builder.py @@ -0,0 +1,134 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Dynamic Protobuf class creator.""" + +from collections import OrderedDict +import hashlib +import os + +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor +from google.protobuf import message_factory + + +def _GetMessageFromFactory(factory, full_name): + """Get a proto class from the MessageFactory by name. + + Args: + factory: a MessageFactory instance. + full_name: str, the fully qualified name of the proto type. + Returns: + A class, for the type identified by full_name. + Raises: + KeyError, if the proto is not found in the factory's descriptor pool. + """ + proto_descriptor = factory.pool.FindMessageTypeByName(full_name) + proto_cls = factory.GetPrototype(proto_descriptor) + return proto_cls + + +def MakeSimpleProtoClass(fields, full_name=None, pool=None): + """Create a Protobuf class whose fields are basic types. + + Note: this doesn't validate field names! + + Args: + fields: dict of {name: field_type} mappings for each field in the proto. If + this is an OrderedDict the order will be maintained, otherwise the + fields will be sorted by name. + full_name: optional str, the fully-qualified name of the proto type. + pool: optional DescriptorPool instance. + Returns: + a class, the new protobuf class with a FileDescriptor. + """ + factory = message_factory.MessageFactory(pool=pool) + + if full_name is not None: + try: + proto_cls = _GetMessageFromFactory(factory, full_name) + return proto_cls + except KeyError: + # The factory's DescriptorPool doesn't know about this class yet. + pass + + # Get a list of (name, field_type) tuples from the fields dict. If fields was + # an OrderedDict we keep the order, but otherwise we sort the field to ensure + # consistent ordering. + field_items = fields.items() + if not isinstance(fields, OrderedDict): + field_items = sorted(field_items) + + # Use a consistent file name that is unlikely to conflict with any imported + # proto files. + fields_hash = hashlib.sha1() + for f_name, f_type in field_items: + fields_hash.update(f_name.encode('utf-8')) + fields_hash.update(str(f_type).encode('utf-8')) + proto_file_name = fields_hash.hexdigest() + '.proto' + + # If the proto is anonymous, use the same hash to name it. + if full_name is None: + full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' + + fields_hash.hexdigest()) + try: + proto_cls = _GetMessageFromFactory(factory, full_name) + return proto_cls + except KeyError: + # The factory's DescriptorPool doesn't know about this class yet. + pass + + # This is the first time we see this proto: add a new descriptor to the pool. + factory.pool.Add( + _MakeFileDescriptorProto(proto_file_name, full_name, field_items)) + return _GetMessageFromFactory(factory, full_name) + + +def _MakeFileDescriptorProto(proto_file_name, full_name, field_items): + """Populate FileDescriptorProto for MessageFactory's DescriptorPool.""" + package, name = full_name.rsplit('.', 1) + file_proto = descriptor_pb2.FileDescriptorProto() + file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name) + file_proto.package = package + desc_proto = file_proto.message_type.add() + desc_proto.name = name + for f_number, (f_name, f_type) in enumerate(field_items, 1): + field_proto = desc_proto.field.add() + field_proto.name = f_name + # # If the number falls in the reserved range, reassign it to the correct + # # number after the range. + if f_number >= descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER: + f_number += ( + descriptor.FieldDescriptor.LAST_RESERVED_FIELD_NUMBER - + descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER + 1) + field_proto.number = f_number + field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL + field_proto.type = f_type + return file_proto diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/pyext/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/pyext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/pyext/cpp_message.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/pyext/cpp_message.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8eb32d79f60ff95b328ec5a828593ab78e1802 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/pyext/cpp_message.py @@ -0,0 +1,65 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Protocol message implementation hooks for C++ implementation. + +Contains helper functions used to create protocol message classes from +Descriptor objects at runtime backed by the protocol buffer C++ API. +""" + +__author__ = 'tibell@google.com (Johan Tibell)' + +from google.protobuf.pyext import _message + + +class GeneratedProtocolMessageType(_message.MessageMeta): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = factory.GetPrototype(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + + The above example will not work for nested types. If you wish to include them, + use reflection.MakeClass() instead of manually instantiating the class in + order to create the appropriate class structure. + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/reflection.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..81e18859a804d589d67b0a0642de718ba1bbce13 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/reflection.py @@ -0,0 +1,95 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This code is meant to work on Python 2.4 and above only. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +from google.protobuf import message_factory +from google.protobuf import symbol_database + +# The type of all Message classes. +# Part of the public interface, but normally only used by message factories. +GeneratedProtocolMessageType = message_factory._GENERATED_PROTOCOL_MESSAGE_TYPE + +MESSAGE_CLASS_CACHE = {} + + +# Deprecated. Please NEVER use reflection.ParseMessage(). +def ParseMessage(descriptor, byte_str): + """Generate a new Message instance from this Descriptor and a byte string. + + DEPRECATED: ParseMessage is deprecated because it is using MakeClass(). + Please use MessageFactory.GetPrototype() instead. + + Args: + descriptor: Protobuf Descriptor object + byte_str: Serialized protocol buffer byte string + + Returns: + Newly created protobuf Message object. + """ + result_class = MakeClass(descriptor) + new_msg = result_class() + new_msg.ParseFromString(byte_str) + return new_msg + + +# Deprecated. Please NEVER use reflection.MakeClass(). +def MakeClass(descriptor): + """Construct a class object for a protobuf described by descriptor. + + DEPRECATED: use MessageFactory.GetPrototype() instead. + + Args: + descriptor: A descriptor.Descriptor object describing the protobuf. + Returns: + The Message class object described by the descriptor. + """ + # Original implementation leads to duplicate message classes, which won't play + # well with extensions. Message factory info is also missing. + # Redirect to message_factory. + return symbol_database.Default().GetPrototype(descriptor) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service.py new file mode 100644 index 0000000000000000000000000000000000000000..5625246324cad3c71108a4466466d1d3b1568907 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service.py @@ -0,0 +1,228 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""DEPRECATED: Declares the RPC service interfaces. + +This module declares the abstract interfaces underlying proto2 RPC +services. These are intended to be independent of any particular RPC +implementation, so that proto2 services can be used on top of a variety +of implementations. Starting with version 2.3.0, RPC implementations should +not try to build on these, but should instead provide code generator plugins +which generate code specific to the particular RPC implementation. This way +the generated code can be more appropriate for the implementation in use +and can avoid unnecessary layers of indirection. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class RpcException(Exception): + """Exception raised on failed blocking RPC method call.""" + pass + + +class Service(object): + + """Abstract base interface for protocol-buffer-based RPC services. + + Services themselves are abstract classes (implemented either by servers or as + stubs), but they subclass this base interface. The methods of this + interface can be used to call the methods of the service without knowing + its exact type at compile time (analogous to the Message interface). + """ + + def GetDescriptor(): + """Retrieves this service's descriptor.""" + raise NotImplementedError + + def CallMethod(self, method_descriptor, rpc_controller, + request, done): + """Calls a method of the service specified by method_descriptor. + + If "done" is None then the call is blocking and the response + message will be returned directly. Otherwise the call is asynchronous + and "done" will later be called with the response value. + + In the blocking case, RpcException will be raised on error. + + Preconditions: + + * method_descriptor.service == GetDescriptor + * request is of the exact same classes as returned by + GetRequestClass(method). + * After the call has started, the request must not be modified. + * "rpc_controller" is of the correct type for the RPC implementation being + used by this Service. For stubs, the "correct type" depends on the + RpcChannel which the stub is using. + + Postconditions: + + * "done" will be called when the method is complete. This may be + before CallMethod() returns or it may be at some point in the future. + * If the RPC failed, the response value passed to "done" will be None. + Further details about the failure can be found by querying the + RpcController. + """ + raise NotImplementedError + + def GetRequestClass(self, method_descriptor): + """Returns the class of the request message for the specified method. + + CallMethod() requires that the request is of a particular subclass of + Message. GetRequestClass() gets the default instance of this required + type. + + Example: + method = service.GetDescriptor().FindMethodByName("Foo") + request = stub.GetRequestClass(method)() + request.ParseFromString(input) + service.CallMethod(method, request, callback) + """ + raise NotImplementedError + + def GetResponseClass(self, method_descriptor): + """Returns the class of the response message for the specified method. + + This method isn't really needed, as the RpcChannel's CallMethod constructs + the response protocol message. It's provided anyway in case it is useful + for the caller to know the response type in advance. + """ + raise NotImplementedError + + +class RpcController(object): + + """An RpcController mediates a single method call. + + The primary purpose of the controller is to provide a way to manipulate + settings specific to the RPC implementation and to find out about RPC-level + errors. The methods provided by the RpcController interface are intended + to be a "least common denominator" set of features which we expect all + implementations to support. Specific implementations may provide more + advanced features (e.g. deadline propagation). + """ + + # Client-side methods below + + def Reset(self): + """Resets the RpcController to its initial state. + + After the RpcController has been reset, it may be reused in + a new call. Must not be called while an RPC is in progress. + """ + raise NotImplementedError + + def Failed(self): + """Returns true if the call failed. + + After a call has finished, returns true if the call failed. The possible + reasons for failure depend on the RPC implementation. Failed() must not + be called before a call has finished. If Failed() returns true, the + contents of the response message are undefined. + """ + raise NotImplementedError + + def ErrorText(self): + """If Failed is true, returns a human-readable description of the error.""" + raise NotImplementedError + + def StartCancel(self): + """Initiate cancellation. + + Advises the RPC system that the caller desires that the RPC call be + canceled. The RPC system may cancel it immediately, may wait awhile and + then cancel it, or may not even cancel the call at all. If the call is + canceled, the "done" callback will still be called and the RpcController + will indicate that the call failed at that time. + """ + raise NotImplementedError + + # Server-side methods below + + def SetFailed(self, reason): + """Sets a failure reason. + + Causes Failed() to return true on the client side. "reason" will be + incorporated into the message returned by ErrorText(). If you find + you need to return machine-readable information about failures, you + should incorporate it into your response protocol buffer and should + NOT call SetFailed(). + """ + raise NotImplementedError + + def IsCanceled(self): + """Checks if the client cancelled the RPC. + + If true, indicates that the client canceled the RPC, so the server may + as well give up on replying to it. The server should still call the + final "done" callback. + """ + raise NotImplementedError + + def NotifyOnCancel(self, callback): + """Sets a callback to invoke on cancel. + + Asks that the given callback be called when the RPC is canceled. The + callback will always be called exactly once. If the RPC completes without + being canceled, the callback will be called after completion. If the RPC + has already been canceled when NotifyOnCancel() is called, the callback + will be called immediately. + + NotifyOnCancel() must be called no more than once per request. + """ + raise NotImplementedError + + +class RpcChannel(object): + + """Abstract interface for an RPC channel. + + An RpcChannel represents a communication line to a service which can be used + to call that service's methods. The service may be running on another + machine. Normally, you should not use an RpcChannel directly, but instead + construct a stub {@link Service} wrapping it. Example: + + Example: + RpcChannel channel = rpcImpl.Channel("remotehost.example.com:1234") + RpcController controller = rpcImpl.Controller() + MyService service = MyService_Stub(channel) + service.MyMethod(controller, request, callback) + """ + + def CallMethod(self, method_descriptor, rpc_controller, + request, response_class, done): + """Calls the method identified by the descriptor. + + Call the given method of the remote service. The signature of this + procedure looks the same as Service.CallMethod(), but the requirements + are less strict in one important way: the request object doesn't have to + be of any specific class as long as its descriptor is method.input_type. + """ + raise NotImplementedError diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service_reflection.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service_reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..f82ab7145a60111fcf8712c6e0d9c71c899e9d3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/service_reflection.py @@ -0,0 +1,295 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains metaclasses used to create protocol service and service stub +classes from ServiceDescriptor objects at runtime. + +The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to +inject all useful functionality into the classes output by the protocol +compiler at compile-time. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class GeneratedServiceType(type): + + """Metaclass for service classes created at runtime from ServiceDescriptors. + + Implementations for all methods described in the Service class are added here + by this class. We also create properties to allow getting/setting all fields + in the protocol message. + + The protocol compiler currently uses this metaclass to create protocol service + classes at runtime. Clients can also manually create their own classes at + runtime, as in this example:: + + mydescriptor = ServiceDescriptor(.....) + class MyProtoService(service.Service): + __metaclass__ = GeneratedServiceType + DESCRIPTOR = mydescriptor + myservice_instance = MyProtoService() + # ... + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service class. + + Args: + name: Name of the class (ignored, but required by the metaclass + protocol). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service class is subclassed. + if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: + return + + descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] + service_builder = _ServiceBuilder(descriptor) + service_builder.BuildService(cls) + cls.DESCRIPTOR = descriptor + + +class GeneratedServiceStubType(GeneratedServiceType): + + """Metaclass for service stubs created at runtime from ServiceDescriptors. + + This class has similar responsibilities as GeneratedServiceType, except that + it creates the service stub classes. + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service stub class. + + Args: + name: Name of the class (ignored, here). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service stub is subclassed. + if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: + return + + descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] + service_stub_builder = _ServiceStubBuilder(descriptor) + service_stub_builder.BuildServiceStub(cls) + + +class _ServiceBuilder(object): + + """This class constructs a protocol service class using a service descriptor. + + Given a service descriptor, this class constructs a class that represents + the specified service descriptor. One service builder instance constructs + exactly one service class. That means all instances of that class share the + same builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + service class. + """ + self.descriptor = service_descriptor + + def BuildService(builder, cls): + """Constructs the service class. + + Args: + cls: The class that will be constructed. + """ + + # CallMethod needs to operate with an instance of the Service class. This + # internal wrapper function exists only to be able to pass the service + # instance to the method that does the real CallMethod work. + # Making sure to use exact argument names from the abstract interface in + # service.py to match the type signature + def _WrapCallMethod(self, method_descriptor, rpc_controller, request, done): + return builder._CallMethod(self, method_descriptor, rpc_controller, + request, done) + + def _WrapGetRequestClass(self, method_descriptor): + return builder._GetRequestClass(method_descriptor) + + def _WrapGetResponseClass(self, method_descriptor): + return builder._GetResponseClass(method_descriptor) + + builder.cls = cls + cls.CallMethod = _WrapCallMethod + cls.GetDescriptor = staticmethod(lambda: builder.descriptor) + cls.GetDescriptor.__doc__ = 'Returns the service descriptor.' + cls.GetRequestClass = _WrapGetRequestClass + cls.GetResponseClass = _WrapGetResponseClass + for method in builder.descriptor.methods: + setattr(cls, method.name, builder._GenerateNonImplementedMethod(method)) + + def _CallMethod(self, srvc, method_descriptor, + rpc_controller, request, callback): + """Calls the method described by a given method descriptor. + + Args: + srvc: Instance of the service for which this method is called. + method_descriptor: Descriptor that represent the method to call. + rpc_controller: RPC controller to use for this method's execution. + request: Request protocol message. + callback: A callback to invoke after the method has completed. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'CallMethod() given method descriptor for wrong service type.') + method = getattr(srvc, method_descriptor.name) + return method(rpc_controller, request, callback) + + def _GetRequestClass(self, method_descriptor): + """Returns the class of the request protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + request protocol message class. + + Returns: + A class that represents the input protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetRequestClass() given method descriptor for wrong service type.') + return method_descriptor.input_type._concrete_class + + def _GetResponseClass(self, method_descriptor): + """Returns the class of the response protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + response protocol message class. + + Returns: + A class that represents the output protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetResponseClass() given method descriptor for wrong service type.') + return method_descriptor.output_type._concrete_class + + def _GenerateNonImplementedMethod(self, method): + """Generates and returns a method that can be set for a service methods. + + Args: + method: Descriptor of the service method for which a method is to be + generated. + + Returns: + A method that can be added to the service class. + """ + return lambda inst, rpc_controller, request, callback: ( + self._NonImplementedMethod(method.name, rpc_controller, callback)) + + def _NonImplementedMethod(self, method_name, rpc_controller, callback): + """The body of all methods in the generated service class. + + Args: + method_name: Name of the method being executed. + rpc_controller: RPC controller used to execute this method. + callback: A callback which will be invoked when the method finishes. + """ + rpc_controller.SetFailed('Method %s not implemented.' % method_name) + callback(None) + + +class _ServiceStubBuilder(object): + + """Constructs a protocol service stub class using a service descriptor. + + Given a service descriptor, this class constructs a suitable stub class. + A stub is just a type-safe wrapper around an RpcChannel which emulates a + local implementation of the service. + + One service stub builder instance constructs exactly one class. It means all + instances of that class share the same service stub builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service stub class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + stub class. + """ + self.descriptor = service_descriptor + + def BuildServiceStub(self, cls): + """Constructs the stub class. + + Args: + cls: The class that will be constructed. + """ + + def _ServiceStubInit(stub, rpc_channel): + stub.rpc_channel = rpc_channel + self.cls = cls + cls.__init__ = _ServiceStubInit + for method in self.descriptor.methods: + setattr(cls, method.name, self._GenerateStubMethod(method)) + + def _GenerateStubMethod(self, method): + return (lambda inst, rpc_controller, request, callback=None: + self._StubMethod(inst, method, rpc_controller, request, callback)) + + def _StubMethod(self, stub, method_descriptor, + rpc_controller, request, callback): + """The body of all service methods in the generated stub class. + + Args: + stub: Stub instance. + method_descriptor: Descriptor of the invoked method. + rpc_controller: Rpc controller to execute the method. + request: Request protocol message. + callback: A callback to execute when the method finishes. + Returns: + Response message (in case of blocking call). + """ + return stub.rpc_channel.CallMethod( + method_descriptor, rpc_controller, request, + method_descriptor.output_type._concrete_class, callback) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/source_context_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/source_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..30cca2e06e7bbf4dab98e53a1e920dc74d22e99f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/source_context_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/source_context.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n$google/protobuf/source_context.proto\x12\x0fgoogle.protobuf\"\"\n\rSourceContext\x12\x11\n\tfile_name\x18\x01 \x01(\tB\x8a\x01\n\x13\x63om.google.protobufB\x12SourceContextProtoP\x01Z6google.golang.org/protobuf/types/known/sourcecontextpb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.source_context_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\022SourceContextProtoP\001Z6google.golang.org/protobuf/types/known/sourcecontextpb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _SOURCECONTEXT._serialized_start=57 + _SOURCECONTEXT._serialized_end=91 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/struct_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/struct_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..149728ca084e764b49d1a834f9326cc5730d2726 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/struct_pb2.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/struct.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cgoogle/protobuf/struct.proto\x12\x0fgoogle.protobuf\"\x84\x01\n\x06Struct\x12\x33\n\x06\x66ields\x18\x01 \x03(\x0b\x32#.google.protobuf.Struct.FieldsEntry\x1a\x45\n\x0b\x46ieldsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\"\xea\x01\n\x05Value\x12\x30\n\nnull_value\x18\x01 \x01(\x0e\x32\x1a.google.protobuf.NullValueH\x00\x12\x16\n\x0cnumber_value\x18\x02 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x03 \x01(\tH\x00\x12\x14\n\nbool_value\x18\x04 \x01(\x08H\x00\x12/\n\x0cstruct_value\x18\x05 \x01(\x0b\x32\x17.google.protobuf.StructH\x00\x12\x30\n\nlist_value\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x00\x42\x06\n\x04kind\"3\n\tListValue\x12&\n\x06values\x18\x01 \x03(\x0b\x32\x16.google.protobuf.Value*\x1b\n\tNullValue\x12\x0e\n\nNULL_VALUE\x10\x00\x42\x7f\n\x13\x63om.google.protobufB\x0bStructProtoP\x01Z/google.golang.org/protobuf/types/known/structpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.struct_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\013StructProtoP\001Z/google.golang.org/protobuf/types/known/structpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _STRUCT_FIELDSENTRY._options = None + _STRUCT_FIELDSENTRY._serialized_options = b'8\001' + _NULLVALUE._serialized_start=474 + _NULLVALUE._serialized_end=501 + _STRUCT._serialized_start=50 + _STRUCT._serialized_end=182 + _STRUCT_FIELDSENTRY._serialized_start=113 + _STRUCT_FIELDSENTRY._serialized_end=182 + _VALUE._serialized_start=185 + _VALUE._serialized_end=419 + _LISTVALUE._serialized_start=421 + _LISTVALUE._serialized_end=472 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/symbol_database.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/symbol_database.py new file mode 100644 index 0000000000000000000000000000000000000000..fdcf8cf06ced70c01d291c672a08850238e5d3c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/symbol_database.py @@ -0,0 +1,194 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""A database of Python protocol buffer generated symbols. + +SymbolDatabase is the MessageFactory for messages generated at compile time, +and makes it easy to create new instances of a registered type, given only the +type's protocol buffer symbol name. + +Example usage:: + + db = symbol_database.SymbolDatabase() + + # Register symbols of interest, from one or multiple files. + db.RegisterFileDescriptor(my_proto_pb2.DESCRIPTOR) + db.RegisterMessage(my_proto_pb2.MyMessage) + db.RegisterEnumDescriptor(my_proto_pb2.MyEnum.DESCRIPTOR) + + # The database can be used as a MessageFactory, to generate types based on + # their name: + types = db.GetMessages(['my_proto.proto']) + my_message_instance = types['MyMessage']() + + # The database's underlying descriptor pool can be queried, so it's not + # necessary to know a type's filename to be able to generate it: + filename = db.pool.FindFileContainingSymbol('MyMessage') + my_message_instance = db.GetMessages([filename])['MyMessage']() + + # This functionality is also provided directly via a convenience method: + my_message_instance = db.GetSymbol('MyMessage')() +""" + + +from google.protobuf.internal import api_implementation +from google.protobuf import descriptor_pool +from google.protobuf import message_factory + + +class SymbolDatabase(message_factory.MessageFactory): + """A database of Python generated symbols.""" + + def RegisterMessage(self, message): + """Registers the given message type in the local database. + + Calls to GetSymbol() and GetMessages() will return messages registered here. + + Args: + message: A :class:`google.protobuf.message.Message` subclass (or + instance); its descriptor will be registered. + + Returns: + The provided message. + """ + + desc = message.DESCRIPTOR + self._classes[desc] = message + self.RegisterMessageDescriptor(desc) + return message + + def RegisterMessageDescriptor(self, message_descriptor): + """Registers the given message descriptor in the local database. + + Args: + message_descriptor (Descriptor): the message descriptor to add. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddDescriptor(message_descriptor) + + def RegisterEnumDescriptor(self, enum_descriptor): + """Registers the given enum descriptor in the local database. + + Args: + enum_descriptor (EnumDescriptor): The enum descriptor to register. + + Returns: + EnumDescriptor: The provided descriptor. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddEnumDescriptor(enum_descriptor) + return enum_descriptor + + def RegisterServiceDescriptor(self, service_descriptor): + """Registers the given service descriptor in the local database. + + Args: + service_descriptor (ServiceDescriptor): the service descriptor to + register. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddServiceDescriptor(service_descriptor) + + def RegisterFileDescriptor(self, file_descriptor): + """Registers the given file descriptor in the local database. + + Args: + file_descriptor (FileDescriptor): The file descriptor to register. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._InternalAddFileDescriptor(file_descriptor) + + def GetSymbol(self, symbol): + """Tries to find a symbol in the local database. + + Currently, this method only returns message.Message instances, however, if + may be extended in future to support other symbol types. + + Args: + symbol (str): a protocol buffer symbol. + + Returns: + A Python class corresponding to the symbol. + + Raises: + KeyError: if the symbol could not be found. + """ + + return self._classes[self.pool.FindMessageTypeByName(symbol)] + + def GetMessages(self, files): + # TODO(amauryfa): Fix the differences with MessageFactory. + """Gets all registered messages from a specified file. + + Only messages already created and registered will be returned; (this is the + case for imported _pb2 modules) + But unlike MessageFactory, this version also returns already defined nested + messages, but does not register any message extensions. + + Args: + files (list[str]): The file names to extract messages from. + + Returns: + A dictionary mapping proto names to the message classes. + + Raises: + KeyError: if a file could not be found. + """ + + def _GetAllMessages(desc): + """Walk a message Descriptor and recursively yields all message names.""" + yield desc + for msg_desc in desc.nested_types: + for nested_desc in _GetAllMessages(msg_desc): + yield nested_desc + + result = {} + for file_name in files: + file_desc = self.pool.FindFileByName(file_name) + for msg_desc in file_desc.message_types_by_name.values(): + for desc in _GetAllMessages(msg_desc): + try: + result[desc.full_name] = self._classes[desc] + except KeyError: + # This descriptor has no registered class, skip it. + pass + return result + + +_DEFAULT = SymbolDatabase(pool=descriptor_pool.Default()) + + +def Default(): + """Returns the default SymbolDatabase.""" + return _DEFAULT diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_encoding.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..759cf11f62bc4f1dac7f73af45fc4d3c892580d2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_encoding.py @@ -0,0 +1,110 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Encoding related utilities.""" +import re + +_cescape_chr_to_symbol_map = {} +_cescape_chr_to_symbol_map[9] = r'\t' # optional escape +_cescape_chr_to_symbol_map[10] = r'\n' # optional escape +_cescape_chr_to_symbol_map[13] = r'\r' # optional escape +_cescape_chr_to_symbol_map[34] = r'\"' # necessary escape +_cescape_chr_to_symbol_map[39] = r"\'" # optional escape +_cescape_chr_to_symbol_map[92] = r'\\' # necessary escape + +# Lookup table for unicode +_cescape_unicode_to_str = [chr(i) for i in range(0, 256)] +for byte, string in _cescape_chr_to_symbol_map.items(): + _cescape_unicode_to_str[byte] = string + +# Lookup table for non-utf8, with necessary escapes at (o >= 127 or o < 32) +_cescape_byte_to_str = ([r'\%03o' % i for i in range(0, 32)] + + [chr(i) for i in range(32, 127)] + + [r'\%03o' % i for i in range(127, 256)]) +for byte, string in _cescape_chr_to_symbol_map.items(): + _cescape_byte_to_str[byte] = string +del byte, string + + +def CEscape(text, as_utf8): + # type: (...) -> str + """Escape a bytes string for use in an text protocol buffer. + + Args: + text: A byte string to be escaped. + as_utf8: Specifies if result may contain non-ASCII characters. + In Python 3 this allows unescaped non-ASCII Unicode characters. + In Python 2 the return value will be valid UTF-8 rather than only ASCII. + Returns: + Escaped string (str). + """ + # Python's text.encode() 'string_escape' or 'unicode_escape' codecs do not + # satisfy our needs; they encodes unprintable characters using two-digit hex + # escapes whereas our C++ unescaping function allows hex escapes to be any + # length. So, "\0011".encode('string_escape') ends up being "\\x011", which + # will be decoded in C++ as a single-character string with char code 0x11. + text_is_unicode = isinstance(text, str) + if as_utf8 and text_is_unicode: + # We're already unicode, no processing beyond control char escapes. + return text.translate(_cescape_chr_to_symbol_map) + ord_ = ord if text_is_unicode else lambda x: x # bytes iterate as ints. + if as_utf8: + return ''.join(_cescape_unicode_to_str[ord_(c)] for c in text) + return ''.join(_cescape_byte_to_str[ord_(c)] for c in text) + + +_CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])') + + +def CUnescape(text): + # type: (str) -> bytes + """Unescape a text string with C-style escape sequences to UTF-8 bytes. + + Args: + text: The data to parse in a str. + Returns: + A byte string. + """ + + def ReplaceHex(m): + # Only replace the match if the number of leading back slashes is odd. i.e. + # the slash itself is not escaped. + if len(m.group(1)) & 1: + return m.group(1) + 'x0' + m.group(2) + return m.group(0) + + # This is required because the 'string_escape' encoding doesn't + # allow single-digit hex escapes (like '\xf'). + result = _CUNESCAPE_HEX.sub(ReplaceHex, text) + + return (result.encode('utf-8') # Make it bytes to allow decode. + .decode('unicode_escape') + # Make it bytes again to return the proper type. + .encode('raw_unicode_escape')) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_format.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_format.py new file mode 100644 index 0000000000000000000000000000000000000000..412385c26f995e2fea4fa868c79a07c80f315f18 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/text_format.py @@ -0,0 +1,1795 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# https://developers.google.com/protocol-buffers/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains routines for printing protocol messages in text format. + +Simple usage example:: + + # Create a proto object and serialize it to a text proto string. + message = my_proto_pb2.MyMessage(foo='bar') + text_proto = text_format.MessageToString(message) + + # Parse a text proto string. + message = text_format.Parse(text_proto, my_proto_pb2.MyMessage()) +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +# TODO(b/129989314) Import thread contention leads to test failures. +import encodings.raw_unicode_escape # pylint: disable=unused-import +import encodings.unicode_escape # pylint: disable=unused-import +import io +import math +import re + +from google.protobuf.internal import decoder +from google.protobuf.internal import type_checkers +from google.protobuf import descriptor +from google.protobuf import text_encoding + +# pylint: disable=g-import-not-at-top +__all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField', + 'PrintFieldValue', 'Merge', 'MessageToBytes'] + +_INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(), + type_checkers.Int32ValueChecker(), + type_checkers.Uint64ValueChecker(), + type_checkers.Int64ValueChecker()) +_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?$', re.IGNORECASE) +_FLOAT_NAN = re.compile('nanf?$', re.IGNORECASE) +_QUOTES = frozenset(("'", '"')) +_ANY_FULL_TYPE_NAME = 'google.protobuf.Any' + + +class Error(Exception): + """Top-level module error for text_format.""" + + +class ParseError(Error): + """Thrown in case of text parsing or tokenizing error.""" + + def __init__(self, message=None, line=None, column=None): + if message is not None and line is not None: + loc = str(line) + if column is not None: + loc += ':{0}'.format(column) + message = '{0} : {1}'.format(loc, message) + if message is not None: + super(ParseError, self).__init__(message) + else: + super(ParseError, self).__init__() + self._line = line + self._column = column + + def GetLine(self): + return self._line + + def GetColumn(self): + return self._column + + +class TextWriter(object): + + def __init__(self, as_utf8): + self._writer = io.StringIO() + + def write(self, val): + return self._writer.write(val) + + def close(self): + return self._writer.close() + + def getvalue(self): + return self._writer.getvalue() + + +def MessageToString( + message, + as_utf8=False, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + indent=0, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + # type: (...) -> str + """Convert protobuf message to text format. + + Double values can be formatted compactly with 15 digits of + precision (which is the most that IEEE 754 "double" can guarantee) + using double_format='.15g'. To ensure that converting to text and back to a + proto will result in an identical value, double_format='.17g' should be used. + + Args: + message: The protocol buffers message. + as_utf8: Return unescaped Unicode for non-ASCII characters. + In Python 3 actual Unicode characters may appear as is in strings. + In Python 2 the return value will be valid UTF-8 rather than only ASCII. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, fields of a proto message will be printed using + the order defined in source code instead of the field number, extensions + will be printed at the end of the message and their relative order is + determined by the extension number. By default, use the field number + order. + float_format (str): If set, use this to specify float field formatting + (per the "Format Specification Mini-Language"); otherwise, shortest float + that has same value in wire will be printed. Also affect double field + if double_format is not set but float_format is set. + double_format (str): If set, use this to specify double field formatting + (per the "Format Specification Mini-Language"); if it is not set but + float_format is set, use float_format. Otherwise, use ``str()`` + use_field_number: If True, print field numbers instead of names. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + indent (int): The initial indent level, in terms of spaces, for pretty + print. + message_formatter (function(message, indent, as_one_line) -> unicode|None): + Custom formatter for selected sub-messages (usually based on message + type). Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if the + field is a proto message. + + Returns: + str: A string of the text formatted protocol buffer message. + """ + out = TextWriter(as_utf8) + printer = _Printer( + out, + indent, + as_utf8, + as_one_line, + use_short_repeated_primitives, + pointy_brackets, + use_index_order, + float_format, + double_format, + use_field_number, + descriptor_pool, + message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintMessage(message) + result = out.getvalue() + out.close() + if as_one_line: + return result.rstrip() + return result + + +def MessageToBytes(message, **kwargs): + # type: (...) -> bytes + """Convert protobuf message to encoded text format. See MessageToString.""" + text = MessageToString(message, **kwargs) + if isinstance(text, bytes): + return text + codec = 'utf-8' if kwargs.get('as_utf8') else 'ascii' + return text.encode(codec) + + +def _IsMapEntry(field): + return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + field.message_type.has_options and + field.message_type.GetOptions().map_entry) + + +def PrintMessage(message, + out, + indent=0, + as_utf8=False, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + printer = _Printer( + out=out, indent=indent, as_utf8=as_utf8, + as_one_line=as_one_line, + use_short_repeated_primitives=use_short_repeated_primitives, + pointy_brackets=pointy_brackets, + use_index_order=use_index_order, + float_format=float_format, + double_format=double_format, + use_field_number=use_field_number, + descriptor_pool=descriptor_pool, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintMessage(message) + + +def PrintField(field, + value, + out, + indent=0, + as_utf8=False, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Print a single field name/value pair.""" + printer = _Printer(out, indent, as_utf8, as_one_line, + use_short_repeated_primitives, pointy_brackets, + use_index_order, float_format, double_format, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintField(field, value) + + +def PrintFieldValue(field, + value, + out, + indent=0, + as_utf8=False, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Print a single field value (not including name).""" + printer = _Printer(out, indent, as_utf8, as_one_line, + use_short_repeated_primitives, pointy_brackets, + use_index_order, float_format, double_format, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintFieldValue(field, value) + + +def _BuildMessageFromTypeName(type_name, descriptor_pool): + """Returns a protobuf message instance. + + Args: + type_name: Fully-qualified protobuf message type name string. + descriptor_pool: DescriptorPool instance. + + Returns: + A Message instance of type matching type_name, or None if the a Descriptor + wasn't found matching type_name. + """ + # pylint: disable=g-import-not-at-top + if descriptor_pool is None: + from google.protobuf import descriptor_pool as pool_mod + descriptor_pool = pool_mod.Default() + from google.protobuf import symbol_database + database = symbol_database.Default() + try: + message_descriptor = descriptor_pool.FindMessageTypeByName(type_name) + except KeyError: + return None + message_type = database.GetPrototype(message_descriptor) + return message_type() + + +# These values must match WireType enum in google/protobuf/wire_format.h. +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 + + +class _Printer(object): + """Text format printer for protocol message.""" + + def __init__( + self, + out, + indent=0, + as_utf8=False, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Initialize the Printer. + + Double values can be formatted compactly with 15 digits of precision + (which is the most that IEEE 754 "double" can guarantee) using + double_format='.15g'. To ensure that converting to text and back to a proto + will result in an identical value, double_format='.17g' should be used. + + Args: + out: To record the text format result. + indent: The initial indent level for pretty print. + as_utf8: Return unescaped Unicode for non-ASCII characters. + In Python 3 actual Unicode characters may appear as is in strings. + In Python 2 the return value will be valid UTF-8 rather than ASCII. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, print fields of a proto message using the order + defined in source code instead of the field number. By default, use the + field number order. + float_format: If set, use this to specify float field formatting + (per the "Format Specification Mini-Language"); otherwise, shortest + float that has same value in wire will be printed. Also affect double + field if double_format is not set but float_format is set. + double_format: If set, use this to specify double field formatting + (per the "Format Specification Mini-Language"); if it is not set but + float_format is set, use float_format. Otherwise, str() is used. + use_field_number: If True, print field numbers instead of names. + descriptor_pool: A DescriptorPool used to resolve Any types. + message_formatter: A function(message, indent, as_one_line): unicode|None + to custom format selected sub-messages (usually based on message type). + Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if + the field is a proto message. + """ + self.out = out + self.indent = indent + self.as_utf8 = as_utf8 + self.as_one_line = as_one_line + self.use_short_repeated_primitives = use_short_repeated_primitives + self.pointy_brackets = pointy_brackets + self.use_index_order = use_index_order + self.float_format = float_format + if double_format is not None: + self.double_format = double_format + else: + self.double_format = float_format + self.use_field_number = use_field_number + self.descriptor_pool = descriptor_pool + self.message_formatter = message_formatter + self.print_unknown_fields = print_unknown_fields + self.force_colon = force_colon + + def _TryPrintAsAnyMessage(self, message): + """Serializes if message is a google.protobuf.Any field.""" + if '/' not in message.type_url: + return False + packed_message = _BuildMessageFromTypeName(message.TypeName(), + self.descriptor_pool) + if packed_message: + packed_message.MergeFromString(message.value) + colon = ':' if self.force_colon else '' + self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon)) + self._PrintMessageFieldValue(packed_message) + self.out.write(' ' if self.as_one_line else '\n') + return True + else: + return False + + def _TryCustomFormatMessage(self, message): + formatted = self.message_formatter(message, self.indent, self.as_one_line) + if formatted is None: + return False + + out = self.out + out.write(' ' * self.indent) + out.write(formatted) + out.write(' ' if self.as_one_line else '\n') + return True + + def PrintMessage(self, message): + """Convert protobuf message to text format. + + Args: + message: The protocol buffers message. + """ + if self.message_formatter and self._TryCustomFormatMessage(message): + return + if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and + self._TryPrintAsAnyMessage(message)): + return + fields = message.ListFields() + if self.use_index_order: + fields.sort( + key=lambda x: x[0].number if x[0].is_extension else x[0].index) + for field, value in fields: + if _IsMapEntry(field): + for key in sorted(value): + # This is slow for maps with submessage entries because it copies the + # entire tree. Unfortunately this would take significant refactoring + # of this file to work around. + # + # TODO(haberman): refactor and optimize if this becomes an issue. + entry_submsg = value.GetEntryClass()(key=key, value=value[key]) + self.PrintField(field, entry_submsg) + elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if (self.use_short_repeated_primitives + and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE + and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_STRING): + self._PrintShortRepeatedPrimitivesValue(field, value) + else: + for element in value: + self.PrintField(field, element) + else: + self.PrintField(field, value) + + if self.print_unknown_fields: + self._PrintUnknownFields(message.UnknownFields()) + + def _PrintUnknownFields(self, unknown_fields): + """Print unknown fields.""" + out = self.out + for field in unknown_fields: + out.write(' ' * self.indent) + out.write(str(field.field_number)) + if field.wire_type == WIRETYPE_START_GROUP: + if self.as_one_line: + out.write(' { ') + else: + out.write(' {\n') + self.indent += 2 + + self._PrintUnknownFields(field.data) + + if self.as_one_line: + out.write('} ') + else: + self.indent -= 2 + out.write(' ' * self.indent + '}\n') + elif field.wire_type == WIRETYPE_LENGTH_DELIMITED: + try: + # If this field is parseable as a Message, it is probably + # an embedded message. + # pylint: disable=protected-access + (embedded_unknown_message, pos) = decoder._DecodeUnknownFieldSet( + memoryview(field.data), 0, len(field.data)) + except Exception: # pylint: disable=broad-except + pos = 0 + + if pos == len(field.data): + if self.as_one_line: + out.write(' { ') + else: + out.write(' {\n') + self.indent += 2 + + self._PrintUnknownFields(embedded_unknown_message) + + if self.as_one_line: + out.write('} ') + else: + self.indent -= 2 + out.write(' ' * self.indent + '}\n') + else: + # A string or bytes field. self.as_utf8 may not work. + out.write(': \"') + out.write(text_encoding.CEscape(field.data, False)) + out.write('\" ' if self.as_one_line else '\"\n') + else: + # varint, fixed32, fixed64 + out.write(': ') + out.write(str(field.data)) + out.write(' ' if self.as_one_line else '\n') + + def _PrintFieldName(self, field): + """Print field name.""" + out = self.out + out.write(' ' * self.indent) + if self.use_field_number: + out.write(str(field.number)) + else: + if field.is_extension: + out.write('[') + if (field.containing_type.GetOptions().message_set_wire_format and + field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL): + out.write(field.message_type.full_name) + else: + out.write(field.full_name) + out.write(']') + elif field.type == descriptor.FieldDescriptor.TYPE_GROUP: + # For groups, use the capitalized name. + out.write(field.message_type.name) + else: + out.write(field.name) + + if (self.force_colon or + field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE): + # The colon is optional in this case, but our cross-language golden files + # don't include it. Here, the colon is only included if force_colon is + # set to True + out.write(':') + + def PrintField(self, field, value): + """Print a single field name/value pair.""" + self._PrintFieldName(field) + self.out.write(' ') + self.PrintFieldValue(field, value) + self.out.write(' ' if self.as_one_line else '\n') + + def _PrintShortRepeatedPrimitivesValue(self, field, value): + """"Prints short repeated primitives value.""" + # Note: this is called only when value has at least one element. + self._PrintFieldName(field) + self.out.write(' [') + for i in range(len(value) - 1): + self.PrintFieldValue(field, value[i]) + self.out.write(', ') + self.PrintFieldValue(field, value[-1]) + self.out.write(']') + self.out.write(' ' if self.as_one_line else '\n') + + def _PrintMessageFieldValue(self, value): + if self.pointy_brackets: + openb = '<' + closeb = '>' + else: + openb = '{' + closeb = '}' + + if self.as_one_line: + self.out.write('%s ' % openb) + self.PrintMessage(value) + self.out.write(closeb) + else: + self.out.write('%s\n' % openb) + self.indent += 2 + self.PrintMessage(value) + self.indent -= 2 + self.out.write(' ' * self.indent + closeb) + + def PrintFieldValue(self, field, value): + """Print a single field value (not including name). + + For repeated fields, the value should be a single element. + + Args: + field: The descriptor of the field to be printed. + value: The value of the field. + """ + out = self.out + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + self._PrintMessageFieldValue(value) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + enum_value = field.enum_type.values_by_number.get(value, None) + if enum_value is not None: + out.write(enum_value.name) + else: + out.write(str(value)) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: + out.write('\"') + if isinstance(value, str) and not self.as_utf8: + out_value = value.encode('utf-8') + else: + out_value = value + if field.type == descriptor.FieldDescriptor.TYPE_BYTES: + # We always need to escape all binary data in TYPE_BYTES fields. + out_as_utf8 = False + else: + out_as_utf8 = self.as_utf8 + out.write(text_encoding.CEscape(out_value, out_as_utf8)) + out.write('\"') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: + if value: + out.write('true') + else: + out.write('false') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT: + if self.float_format is not None: + out.write('{1:{0}}'.format(self.float_format, value)) + else: + if math.isnan(value): + out.write(str(value)) + else: + out.write(str(type_checkers.ToShortestFloat(value))) + elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_DOUBLE and + self.double_format is not None): + out.write('{1:{0}}'.format(self.double_format, value)) + else: + out.write(str(value)) + + +def Parse(text, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + NOTE: for historical reasons this function does not clear the input + message. This is different from what the binary msg.ParseFrom(...) does. + If text contains a field already set in message, the value is appended if the + field is repeated. Otherwise, an error is raised. + + Example:: + + a = MyProto() + a.repeated_field.append('test') + b = MyProto() + + # Repeated fields are combined + text_format.Parse(repr(a), b) + text_format.Parse(repr(a), b) # repeated_field contains ["test", "test"] + + # Non-repeated fields cannot be overwritten + a.singular_field = 1 + b.singular_field = 2 + text_format.Parse(repr(a), b) # ParseError + + # Binary version: + b.ParseFromString(a.SerializeToString()) # repeated_field is now "test" + + Caller is responsible for clearing the message as needed. + + Args: + text (str): Message text representation. + message (Message): A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + Message: The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + return ParseLines(text.split(b'\n' if isinstance(text, bytes) else u'\n'), + message, + allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + + +def Merge(text, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + Like Parse(), but allows repeated values for a non-repeated field, and uses + the last one. This means any non-repeated, top-level fields specified in text + replace those in the message. + + Args: + text (str): Message text representation. + message (Message): A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + Message: The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + return MergeLines( + text.split(b'\n' if isinstance(text, bytes) else u'\n'), + message, + allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + + +def ParseLines(lines, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + See Parse() for caveats. + + Args: + lines: An iterable of lines of a message's text representation. + message: A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool: A DescriptorPool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + parser = _Parser(allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + return parser.ParseLines(lines, message) + + +def MergeLines(lines, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + See Merge() for more details. + + Args: + lines: An iterable of lines of a message's text representation. + message: A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool: A DescriptorPool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + parser = _Parser(allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + return parser.MergeLines(lines, message) + + +class _Parser(object): + """Text format parser for protocol message.""" + + def __init__(self, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + self.allow_unknown_extension = allow_unknown_extension + self.allow_field_number = allow_field_number + self.descriptor_pool = descriptor_pool + self.allow_unknown_field = allow_unknown_field + + def ParseLines(self, lines, message): + """Parses a text representation of a protocol message into a message.""" + self._allow_multiple_scalars = False + self._ParseOrMerge(lines, message) + return message + + def MergeLines(self, lines, message): + """Merges a text representation of a protocol message into a message.""" + self._allow_multiple_scalars = True + self._ParseOrMerge(lines, message) + return message + + def _ParseOrMerge(self, lines, message): + """Converts a text representation of a protocol message into a message. + + Args: + lines: Lines of a message's text representation. + message: A protocol buffer message to merge into. + + Raises: + ParseError: On text parsing problems. + """ + # Tokenize expects native str lines. + str_lines = ( + line if isinstance(line, str) else line.decode('utf-8') + for line in lines) + tokenizer = Tokenizer(str_lines) + while not tokenizer.AtEnd(): + self._MergeField(tokenizer, message) + + def _MergeField(self, tokenizer, message): + """Merges a single protocol message field into a message. + + Args: + tokenizer: A tokenizer to parse the field name and values. + message: A protocol message to record the data. + + Raises: + ParseError: In case of text parsing problems. + """ + message_descriptor = message.DESCRIPTOR + if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and + tokenizer.TryConsume('[')): + type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer) + tokenizer.Consume(']') + tokenizer.TryConsume(':') + if tokenizer.TryConsume('<'): + expanded_any_end_token = '>' + else: + tokenizer.Consume('{') + expanded_any_end_token = '}' + expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name, + self.descriptor_pool) + if not expanded_any_sub_message: + raise ParseError('Type %s not found in descriptor pool' % + packed_type_name) + while not tokenizer.TryConsume(expanded_any_end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % + (expanded_any_end_token,)) + self._MergeField(tokenizer, expanded_any_sub_message) + deterministic = False + + message.Pack(expanded_any_sub_message, + type_url_prefix=type_url_prefix, + deterministic=deterministic) + return + + if tokenizer.TryConsume('['): + name = [tokenizer.ConsumeIdentifier()] + while tokenizer.TryConsume('.'): + name.append(tokenizer.ConsumeIdentifier()) + name = '.'.join(name) + + if not message_descriptor.is_extendable: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" does not have extensions.' % + message_descriptor.full_name) + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(name) + # pylint: enable=protected-access + + + if not field: + if self.allow_unknown_extension: + field = None + else: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" not registered. ' + 'Did you import the _pb2 module which defines it? ' + 'If you are trying to place the extension in the MessageSet ' + 'field of another message that is in an Any or MessageSet field, ' + 'that message\'s _pb2 module must be imported as well' % name) + elif message_descriptor != field.containing_type: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" does not extend message type "%s".' % + (name, message_descriptor.full_name)) + + tokenizer.Consume(']') + + else: + name = tokenizer.ConsumeIdentifierOrNumber() + if self.allow_field_number and name.isdigit(): + number = ParseInteger(name, True, True) + field = message_descriptor.fields_by_number.get(number, None) + if not field and message_descriptor.is_extendable: + field = message.Extensions._FindExtensionByNumber(number) + else: + field = message_descriptor.fields_by_name.get(name, None) + + # Group names are expected to be capitalized as they appear in the + # .proto file, which actually matches their type names, not their field + # names. + if not field: + field = message_descriptor.fields_by_name.get(name.lower(), None) + if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP: + field = None + + if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and + field.message_type.name != name): + field = None + + if not field and not self.allow_unknown_field: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" has no field named "%s".' % + (message_descriptor.full_name, name)) + + if field: + if not self._allow_multiple_scalars and field.containing_oneof: + # Check if there's a different field set in this oneof. + # Note that we ignore the case if the same field was set before, and we + # apply _allow_multiple_scalars to non-scalar fields as well. + which_oneof = message.WhichOneof(field.containing_oneof.name) + if which_oneof is not None and which_oneof != field.name: + raise tokenizer.ParseErrorPreviousToken( + 'Field "%s" is specified along with field "%s", another member ' + 'of oneof "%s" for message type "%s".' % + (field.name, which_oneof, field.containing_oneof.name, + message_descriptor.full_name)) + + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + tokenizer.TryConsume(':') + merger = self._MergeMessageField + else: + tokenizer.Consume(':') + merger = self._MergeScalarField + + if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and + tokenizer.TryConsume('[')): + # Short repeated format, e.g. "foo: [1, 2, 3]" + if not tokenizer.TryConsume(']'): + while True: + merger(tokenizer, message, field) + if tokenizer.TryConsume(']'): + break + tokenizer.Consume(',') + + else: + merger(tokenizer, message, field) + + else: # Proto field is unknown. + assert (self.allow_unknown_extension or self.allow_unknown_field) + _SkipFieldContents(tokenizer) + + # For historical reasons, fields may optionally be separated by commas or + # semicolons. + if not tokenizer.TryConsume(','): + tokenizer.TryConsume(';') + + + def _ConsumeAnyTypeUrl(self, tokenizer): + """Consumes a google.protobuf.Any type URL and returns the type name.""" + # Consume "type.googleapis.com/". + prefix = [tokenizer.ConsumeIdentifier()] + tokenizer.Consume('.') + prefix.append(tokenizer.ConsumeIdentifier()) + tokenizer.Consume('.') + prefix.append(tokenizer.ConsumeIdentifier()) + tokenizer.Consume('/') + # Consume the fully-qualified type name. + name = [tokenizer.ConsumeIdentifier()] + while tokenizer.TryConsume('.'): + name.append(tokenizer.ConsumeIdentifier()) + return '.'.join(prefix), '.'.join(name) + + def _MergeMessageField(self, tokenizer, message, field): + """Merges a single scalar field into a message. + + Args: + tokenizer: A tokenizer to parse the field value. + message: The message of which field is a member. + field: The descriptor of the field to be merged. + + Raises: + ParseError: In case of text parsing problems. + """ + is_map_entry = _IsMapEntry(field) + + if tokenizer.TryConsume('<'): + end_token = '>' + else: + tokenizer.Consume('{') + end_token = '}' + + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if field.is_extension: + sub_message = message.Extensions[field].add() + elif is_map_entry: + sub_message = getattr(message, field.name).GetEntryClass()() + else: + sub_message = getattr(message, field.name).add() + else: + if field.is_extension: + if (not self._allow_multiple_scalars and + message.HasExtension(field)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" extensions.' % + (message.DESCRIPTOR.full_name, field.full_name)) + sub_message = message.Extensions[field] + else: + # Also apply _allow_multiple_scalars to message field. + # TODO(jieluo): Change to _allow_singular_overwrites. + if (not self._allow_multiple_scalars and + message.HasField(field.name)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" fields.' % + (message.DESCRIPTOR.full_name, field.name)) + sub_message = getattr(message, field.name) + sub_message.SetInParent() + + while not tokenizer.TryConsume(end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,)) + self._MergeField(tokenizer, sub_message) + + if is_map_entry: + value_cpptype = field.message_type.fields_by_name['value'].cpp_type + if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + value = getattr(message, field.name)[sub_message.key] + value.CopyFrom(sub_message.value) + else: + getattr(message, field.name)[sub_message.key] = sub_message.value + + @staticmethod + def _IsProto3Syntax(message): + message_descriptor = message.DESCRIPTOR + return (hasattr(message_descriptor, 'syntax') and + message_descriptor.syntax == 'proto3') + + def _MergeScalarField(self, tokenizer, message, field): + """Merges a single scalar field into a message. + + Args: + tokenizer: A tokenizer to parse the field value. + message: A protocol message to record the data. + field: The descriptor of the field to be merged. + + Raises: + ParseError: In case of text parsing problems. + RuntimeError: On runtime errors. + """ + _ = self.allow_unknown_extension + value = None + + if field.type in (descriptor.FieldDescriptor.TYPE_INT32, + descriptor.FieldDescriptor.TYPE_SINT32, + descriptor.FieldDescriptor.TYPE_SFIXED32): + value = _ConsumeInt32(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_INT64, + descriptor.FieldDescriptor.TYPE_SINT64, + descriptor.FieldDescriptor.TYPE_SFIXED64): + value = _ConsumeInt64(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32, + descriptor.FieldDescriptor.TYPE_FIXED32): + value = _ConsumeUint32(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64, + descriptor.FieldDescriptor.TYPE_FIXED64): + value = _ConsumeUint64(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT, + descriptor.FieldDescriptor.TYPE_DOUBLE): + value = tokenizer.ConsumeFloat() + elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: + value = tokenizer.ConsumeBool() + elif field.type == descriptor.FieldDescriptor.TYPE_STRING: + value = tokenizer.ConsumeString() + elif field.type == descriptor.FieldDescriptor.TYPE_BYTES: + value = tokenizer.ConsumeByteString() + elif field.type == descriptor.FieldDescriptor.TYPE_ENUM: + value = tokenizer.ConsumeEnum(field) + else: + raise RuntimeError('Unknown field type %d' % field.type) + + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if field.is_extension: + message.Extensions[field].append(value) + else: + getattr(message, field.name).append(value) + else: + if field.is_extension: + if (not self._allow_multiple_scalars and + not self._IsProto3Syntax(message) and + message.HasExtension(field)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" extensions.' % + (message.DESCRIPTOR.full_name, field.full_name)) + else: + message.Extensions[field] = value + else: + duplicate_error = False + if not self._allow_multiple_scalars: + if self._IsProto3Syntax(message): + # Proto3 doesn't represent presence so we try best effort to check + # multiple scalars by compare to default values. + duplicate_error = bool(getattr(message, field.name)) + else: + duplicate_error = message.HasField(field.name) + + if duplicate_error: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" fields.' % + (message.DESCRIPTOR.full_name, field.name)) + else: + setattr(message, field.name, value) + + +def _SkipFieldContents(tokenizer): + """Skips over contents (value or message) of a field. + + Args: + tokenizer: A tokenizer to parse the field name and values. + """ + # Try to guess the type of this field. + # If this field is not a message, there should be a ":" between the + # field name and the field value and also the field value should not + # start with "{" or "<" which indicates the beginning of a message body. + # If there is no ":" or there is a "{" or "<" after ":", this field has + # to be a message or the input is ill-formed. + if tokenizer.TryConsume(':') and not tokenizer.LookingAt( + '{') and not tokenizer.LookingAt('<'): + _SkipFieldValue(tokenizer) + else: + _SkipFieldMessage(tokenizer) + + +def _SkipField(tokenizer): + """Skips over a complete field (name and value/message). + + Args: + tokenizer: A tokenizer to parse the field name and values. + """ + if tokenizer.TryConsume('['): + # Consume extension name. + tokenizer.ConsumeIdentifier() + while tokenizer.TryConsume('.'): + tokenizer.ConsumeIdentifier() + tokenizer.Consume(']') + else: + tokenizer.ConsumeIdentifierOrNumber() + + _SkipFieldContents(tokenizer) + + # For historical reasons, fields may optionally be separated by commas or + # semicolons. + if not tokenizer.TryConsume(','): + tokenizer.TryConsume(';') + + +def _SkipFieldMessage(tokenizer): + """Skips over a field message. + + Args: + tokenizer: A tokenizer to parse the field name and values. + """ + + if tokenizer.TryConsume('<'): + delimiter = '>' + else: + tokenizer.Consume('{') + delimiter = '}' + + while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'): + _SkipField(tokenizer) + + tokenizer.Consume(delimiter) + + +def _SkipFieldValue(tokenizer): + """Skips over a field value. + + Args: + tokenizer: A tokenizer to parse the field name and values. + + Raises: + ParseError: In case an invalid field value is found. + """ + # String/bytes tokens can come in multiple adjacent string literals. + # If we can consume one, consume as many as we can. + if tokenizer.TryConsumeByteString(): + while tokenizer.TryConsumeByteString(): + pass + return + + if (not tokenizer.TryConsumeIdentifier() and + not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and + not tokenizer.TryConsumeFloat()): + raise ParseError('Invalid field value: ' + tokenizer.token) + + +class Tokenizer(object): + """Protocol buffer text representation tokenizer. + + This class handles the lower level string parsing by splitting it into + meaningful tokens. + + It was directly ported from the Java protocol buffer API. + """ + + _WHITESPACE = re.compile(r'\s+') + _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE) + _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE) + _TOKEN = re.compile('|'.join([ + r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier + r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number + ] + [ # quoted str for each quote mark + # Avoid backtracking! https://stackoverflow.com/a/844267 + r'{qt}[^{qt}\n\\]*((\\.)+[^{qt}\n\\]*)*({qt}|\\?$)'.format(qt=mark) + for mark in _QUOTES + ])) + + _IDENTIFIER = re.compile(r'[^\d\W]\w*') + _IDENTIFIER_OR_NUMBER = re.compile(r'\w+') + + def __init__(self, lines, skip_comments=True): + self._position = 0 + self._line = -1 + self._column = 0 + self._token_start = None + self.token = '' + self._lines = iter(lines) + self._current_line = '' + self._previous_line = 0 + self._previous_column = 0 + self._more_lines = True + self._skip_comments = skip_comments + self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT + or self._WHITESPACE) + self._SkipWhitespace() + self.NextToken() + + def LookingAt(self, token): + return self.token == token + + def AtEnd(self): + """Checks the end of the text was reached. + + Returns: + True iff the end was reached. + """ + return not self.token + + def _PopLine(self): + while len(self._current_line) <= self._column: + try: + self._current_line = next(self._lines) + except StopIteration: + self._current_line = '' + self._more_lines = False + return + else: + self._line += 1 + self._column = 0 + + def _SkipWhitespace(self): + while True: + self._PopLine() + match = self._whitespace_pattern.match(self._current_line, self._column) + if not match: + break + length = len(match.group(0)) + self._column += length + + def TryConsume(self, token): + """Tries to consume a given piece of text. + + Args: + token: Text to consume. + + Returns: + True iff the text was consumed. + """ + if self.token == token: + self.NextToken() + return True + return False + + def Consume(self, token): + """Consumes a piece of text. + + Args: + token: Text to consume. + + Raises: + ParseError: If the text couldn't be consumed. + """ + if not self.TryConsume(token): + raise self.ParseError('Expected "%s".' % token) + + def ConsumeComment(self): + result = self.token + if not self._COMMENT.match(result): + raise self.ParseError('Expected comment.') + self.NextToken() + return result + + def ConsumeCommentOrTrailingComment(self): + """Consumes a comment, returns a 2-tuple (trailing bool, comment str).""" + + # Tokenizer initializes _previous_line and _previous_column to 0. As the + # tokenizer starts, it looks like there is a previous token on the line. + just_started = self._line == 0 and self._column == 0 + + before_parsing = self._previous_line + comment = self.ConsumeComment() + + # A trailing comment is a comment on the same line than the previous token. + trailing = (self._previous_line == before_parsing + and not just_started) + + return trailing, comment + + def TryConsumeIdentifier(self): + try: + self.ConsumeIdentifier() + return True + except ParseError: + return False + + def ConsumeIdentifier(self): + """Consumes protocol message field identifier. + + Returns: + Identifier string. + + Raises: + ParseError: If an identifier couldn't be consumed. + """ + result = self.token + if not self._IDENTIFIER.match(result): + raise self.ParseError('Expected identifier.') + self.NextToken() + return result + + def TryConsumeIdentifierOrNumber(self): + try: + self.ConsumeIdentifierOrNumber() + return True + except ParseError: + return False + + def ConsumeIdentifierOrNumber(self): + """Consumes protocol message field identifier. + + Returns: + Identifier string. + + Raises: + ParseError: If an identifier couldn't be consumed. + """ + result = self.token + if not self._IDENTIFIER_OR_NUMBER.match(result): + raise self.ParseError('Expected identifier or number, got %s.' % result) + self.NextToken() + return result + + def TryConsumeInteger(self): + try: + self.ConsumeInteger() + return True + except ParseError: + return False + + def ConsumeInteger(self): + """Consumes an integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an integer couldn't be consumed. + """ + try: + result = _ParseAbstractInteger(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def TryConsumeFloat(self): + try: + self.ConsumeFloat() + return True + except ParseError: + return False + + def ConsumeFloat(self): + """Consumes an floating point number. + + Returns: + The number parsed. + + Raises: + ParseError: If a floating point number couldn't be consumed. + """ + try: + result = ParseFloat(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ConsumeBool(self): + """Consumes a boolean value. + + Returns: + The bool parsed. + + Raises: + ParseError: If a boolean value couldn't be consumed. + """ + try: + result = ParseBool(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def TryConsumeByteString(self): + try: + self.ConsumeByteString() + return True + except ParseError: + return False + + def ConsumeString(self): + """Consumes a string value. + + Returns: + The string parsed. + + Raises: + ParseError: If a string value couldn't be consumed. + """ + the_bytes = self.ConsumeByteString() + try: + return str(the_bytes, 'utf-8') + except UnicodeDecodeError as e: + raise self._StringParseError(e) + + def ConsumeByteString(self): + """Consumes a byte array value. + + Returns: + The array parsed (as a string). + + Raises: + ParseError: If a byte array value couldn't be consumed. + """ + the_list = [self._ConsumeSingleByteString()] + while self.token and self.token[0] in _QUOTES: + the_list.append(self._ConsumeSingleByteString()) + return b''.join(the_list) + + def _ConsumeSingleByteString(self): + """Consume one token of a string literal. + + String literals (whether bytes or text) can come in multiple adjacent + tokens which are automatically concatenated, like in C or Python. This + method only consumes one token. + + Returns: + The token parsed. + Raises: + ParseError: When the wrong format data is found. + """ + text = self.token + if len(text) < 1 or text[0] not in _QUOTES: + raise self.ParseError('Expected string but found: %r' % (text,)) + + if len(text) < 2 or text[-1] != text[0]: + raise self.ParseError('String missing ending quote: %r' % (text,)) + + try: + result = text_encoding.CUnescape(text[1:-1]) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ConsumeEnum(self, field): + try: + result = ParseEnum(field, self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ParseErrorPreviousToken(self, message): + """Creates and *returns* a ParseError for the previously read token. + + Args: + message: A message to set for the exception. + + Returns: + A ParseError instance. + """ + return ParseError(message, self._previous_line + 1, + self._previous_column + 1) + + def ParseError(self, message): + """Creates and *returns* a ParseError for the current token.""" + return ParseError('\'' + self._current_line + '\': ' + message, + self._line + 1, self._column + 1) + + def _StringParseError(self, e): + return self.ParseError('Couldn\'t parse string: ' + str(e)) + + def NextToken(self): + """Reads the next meaningful token.""" + self._previous_line = self._line + self._previous_column = self._column + + self._column += len(self.token) + self._SkipWhitespace() + + if not self._more_lines: + self.token = '' + return + + match = self._TOKEN.match(self._current_line, self._column) + if not match and not self._skip_comments: + match = self._COMMENT.match(self._current_line, self._column) + if match: + token = match.group(0) + self.token = token + else: + self.token = self._current_line[self._column] + +# Aliased so it can still be accessed by current visibility violators. +# TODO(dbarnett): Migrate violators to textformat_tokenizer. +_Tokenizer = Tokenizer # pylint: disable=invalid-name + + +def _ConsumeInt32(tokenizer): + """Consumes a signed 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=True, is_long=False) + + +def _ConsumeUint32(tokenizer): + """Consumes an unsigned 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=False, is_long=False) + + +def _TryConsumeInt64(tokenizer): + try: + _ConsumeInt64(tokenizer) + return True + except ParseError: + return False + + +def _ConsumeInt64(tokenizer): + """Consumes a signed 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=True, is_long=True) + + +def _TryConsumeUint64(tokenizer): + try: + _ConsumeUint64(tokenizer) + return True + except ParseError: + return False + + +def _ConsumeUint64(tokenizer): + """Consumes an unsigned 64bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 64bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=False, is_long=True) + + +def _ConsumeInteger(tokenizer, is_signed=False, is_long=False): + """Consumes an integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + is_signed: True if a signed integer must be parsed. + is_long: True if a long integer must be parsed. + + Returns: + The integer parsed. + + Raises: + ParseError: If an integer with given characteristics couldn't be consumed. + """ + try: + result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long) + except ValueError as e: + raise tokenizer.ParseError(str(e)) + tokenizer.NextToken() + return result + + +def ParseInteger(text, is_signed=False, is_long=False): + """Parses an integer. + + Args: + text: The text to parse. + is_signed: True if a signed integer must be parsed. + is_long: True if a long integer must be parsed. + + Returns: + The integer value. + + Raises: + ValueError: Thrown Iff the text is not a valid integer. + """ + # Do the actual parsing. Exception handling is propagated to caller. + result = _ParseAbstractInteger(text) + + # Check if the integer is sane. Exceptions handled by callers. + checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] + checker.CheckValue(result) + return result + + +def _ParseAbstractInteger(text): + """Parses an integer without checking size/signedness. + + Args: + text: The text to parse. + + Returns: + The integer value. + + Raises: + ValueError: Thrown Iff the text is not a valid integer. + """ + # Do the actual parsing. Exception handling is propagated to caller. + orig_text = text + c_octal_match = re.match(r'(-?)0(\d+)$', text) + if c_octal_match: + # Python 3 no longer supports 0755 octal syntax without the 'o', so + # we always use the '0o' prefix for multi-digit numbers starting with 0. + text = c_octal_match.group(1) + '0o' + c_octal_match.group(2) + try: + return int(text, 0) + except ValueError: + raise ValueError('Couldn\'t parse integer: %s' % orig_text) + + +def ParseFloat(text): + """Parse a floating point number. + + Args: + text: Text to parse. + + Returns: + The number parsed. + + Raises: + ValueError: If a floating point number couldn't be parsed. + """ + try: + # Assume Python compatible syntax. + return float(text) + except ValueError: + # Check alternative spellings. + if _FLOAT_INFINITY.match(text): + if text[0] == '-': + return float('-inf') + else: + return float('inf') + elif _FLOAT_NAN.match(text): + return float('nan') + else: + # assume '1.0f' format + try: + return float(text.rstrip('f')) + except ValueError: + raise ValueError('Couldn\'t parse float: %s' % text) + + +def ParseBool(text): + """Parse a boolean value. + + Args: + text: Text to parse. + + Returns: + Boolean values parsed + + Raises: + ValueError: If text is not a valid boolean. + """ + if text in ('true', 't', '1', 'True'): + return True + elif text in ('false', 'f', '0', 'False'): + return False + else: + raise ValueError('Expected "true" or "false".') + + +def ParseEnum(field, value): + """Parse an enum value. + + The value can be specified by a number (the enum value), or by + a string literal (the enum name). + + Args: + field: Enum field descriptor. + value: String value. + + Returns: + Enum value number. + + Raises: + ValueError: If the enum value could not be parsed. + """ + enum_descriptor = field.enum_type + try: + number = int(value, 0) + except ValueError: + # Identifier. + enum_value = enum_descriptor.values_by_name.get(value, None) + if enum_value is None: + raise ValueError('Enum type "%s" has no value named %s.' % + (enum_descriptor.full_name, value)) + else: + # Numeric value. + if hasattr(field.file, 'syntax'): + # Attribute is checked for compatibility. + if field.file.syntax == 'proto3': + # Proto3 accept numeric unknown enums. + return number + enum_value = enum_descriptor.values_by_number.get(number, None) + if enum_value is None: + raise ValueError('Enum type "%s" has no value with number %d.' % + (enum_descriptor.full_name, number)) + return enum_value.number diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/timestamp_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/timestamp_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..558d49694181846b56a00110c0efa054c6bb9834 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/timestamp_pb2.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/timestamp.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1fgoogle/protobuf/timestamp.proto\x12\x0fgoogle.protobuf\"+\n\tTimestamp\x12\x0f\n\x07seconds\x18\x01 \x01(\x03\x12\r\n\x05nanos\x18\x02 \x01(\x05\x42\x85\x01\n\x13\x63om.google.protobufB\x0eTimestampProtoP\x01Z2google.golang.org/protobuf/types/known/timestamppb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.timestamp_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\016TimestampProtoP\001Z2google.golang.org/protobuf/types/known/timestamppb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _TIMESTAMP._serialized_start=52 + _TIMESTAMP._serialized_end=95 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/type_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/type_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..19903fb6b4be5708bf24d34ebcc99cda33368f31 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/type_pb2.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/type.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import source_context_pb2 as google_dot_protobuf_dot_source__context__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1agoogle/protobuf/type.proto\x12\x0fgoogle.protobuf\x1a\x19google/protobuf/any.proto\x1a$google/protobuf/source_context.proto\"\xd7\x01\n\x04Type\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x16.google.protobuf.Field\x12\x0e\n\x06oneofs\x18\x03 \x03(\t\x12(\n\x07options\x18\x04 \x03(\x0b\x32\x17.google.protobuf.Option\x12\x36\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContext\x12\'\n\x06syntax\x18\x06 \x01(\x0e\x32\x17.google.protobuf.Syntax\"\xd5\x05\n\x05\x46ield\x12)\n\x04kind\x18\x01 \x01(\x0e\x32\x1b.google.protobuf.Field.Kind\x12\x37\n\x0b\x63\x61rdinality\x18\x02 \x01(\x0e\x32\".google.protobuf.Field.Cardinality\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12\x0c\n\x04name\x18\x04 \x01(\t\x12\x10\n\x08type_url\x18\x06 \x01(\t\x12\x13\n\x0boneof_index\x18\x07 \x01(\x05\x12\x0e\n\x06packed\x18\x08 \x01(\x08\x12(\n\x07options\x18\t \x03(\x0b\x32\x17.google.protobuf.Option\x12\x11\n\tjson_name\x18\n \x01(\t\x12\x15\n\rdefault_value\x18\x0b \x01(\t\"\xc8\x02\n\x04Kind\x12\x10\n\x0cTYPE_UNKNOWN\x10\x00\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"t\n\x0b\x43\x61rdinality\x12\x17\n\x13\x43\x41RDINALITY_UNKNOWN\x10\x00\x12\x18\n\x14\x43\x41RDINALITY_OPTIONAL\x10\x01\x12\x18\n\x14\x43\x41RDINALITY_REQUIRED\x10\x02\x12\x18\n\x14\x43\x41RDINALITY_REPEATED\x10\x03\"\xce\x01\n\x04\x45num\x12\x0c\n\x04name\x18\x01 \x01(\t\x12-\n\tenumvalue\x18\x02 \x03(\x0b\x32\x1a.google.protobuf.EnumValue\x12(\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.Option\x12\x36\n\x0esource_context\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.SourceContext\x12\'\n\x06syntax\x18\x05 \x01(\x0e\x32\x17.google.protobuf.Syntax\"S\n\tEnumValue\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12(\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.Option\";\n\x06Option\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x05value\x18\x02 \x01(\x0b\x32\x14.google.protobuf.Any*.\n\x06Syntax\x12\x11\n\rSYNTAX_PROTO2\x10\x00\x12\x11\n\rSYNTAX_PROTO3\x10\x01\x42{\n\x13\x63om.google.protobufB\tTypeProtoP\x01Z-google.golang.org/protobuf/types/known/typepb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.type_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\tTypeProtoP\001Z-google.golang.org/protobuf/types/known/typepb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _SYNTAX._serialized_start=1413 + _SYNTAX._serialized_end=1459 + _TYPE._serialized_start=113 + _TYPE._serialized_end=328 + _FIELD._serialized_start=331 + _FIELD._serialized_end=1056 + _FIELD_KIND._serialized_start=610 + _FIELD_KIND._serialized_end=938 + _FIELD_CARDINALITY._serialized_start=940 + _FIELD_CARDINALITY._serialized_end=1056 + _ENUM._serialized_start=1059 + _ENUM._serialized_end=1265 + _ENUMVALUE._serialized_start=1267 + _ENUMVALUE._serialized_end=1350 + _OPTION._serialized_start=1352 + _OPTION._serialized_end=1411 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..66a5836c82084c2a65999345cce06ccf4b5d8a2b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_pb2.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/util/json_format.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n&google/protobuf/util/json_format.proto\x12\x11protobuf_unittest\"\x89\x01\n\x13TestFlagsAndStrings\x12\t\n\x01\x41\x18\x01 \x02(\x05\x12K\n\rrepeatedgroup\x18\x02 \x03(\n24.protobuf_unittest.TestFlagsAndStrings.RepeatedGroup\x1a\x1a\n\rRepeatedGroup\x12\t\n\x01\x66\x18\x03 \x02(\t\"!\n\x14TestBase64ByteArrays\x12\t\n\x01\x61\x18\x01 \x02(\x0c\"G\n\x12TestJavaScriptJSON\x12\t\n\x01\x61\x18\x01 \x01(\x05\x12\r\n\x05\x66inal\x18\x02 \x01(\x02\x12\n\n\x02in\x18\x03 \x01(\t\x12\x0b\n\x03Var\x18\x04 \x01(\t\"Q\n\x18TestJavaScriptOrderJSON1\x12\t\n\x01\x64\x18\x01 \x01(\x05\x12\t\n\x01\x63\x18\x02 \x01(\x05\x12\t\n\x01x\x18\x03 \x01(\x08\x12\t\n\x01\x62\x18\x04 \x01(\x05\x12\t\n\x01\x61\x18\x05 \x01(\x05\"\x89\x01\n\x18TestJavaScriptOrderJSON2\x12\t\n\x01\x64\x18\x01 \x01(\x05\x12\t\n\x01\x63\x18\x02 \x01(\x05\x12\t\n\x01x\x18\x03 \x01(\x08\x12\t\n\x01\x62\x18\x04 \x01(\x05\x12\t\n\x01\x61\x18\x05 \x01(\x05\x12\x36\n\x01z\x18\x06 \x03(\x0b\x32+.protobuf_unittest.TestJavaScriptOrderJSON1\"$\n\x0cTestLargeInt\x12\t\n\x01\x61\x18\x01 \x02(\x03\x12\t\n\x01\x62\x18\x02 \x02(\x04\"\xa0\x01\n\x0bTestNumbers\x12\x30\n\x01\x61\x18\x01 \x01(\x0e\x32%.protobuf_unittest.TestNumbers.MyType\x12\t\n\x01\x62\x18\x02 \x01(\x05\x12\t\n\x01\x63\x18\x03 \x01(\x02\x12\t\n\x01\x64\x18\x04 \x01(\x08\x12\t\n\x01\x65\x18\x05 \x01(\x01\x12\t\n\x01\x66\x18\x06 \x01(\r\"(\n\x06MyType\x12\x06\n\x02OK\x10\x00\x12\x0b\n\x07WARNING\x10\x01\x12\t\n\x05\x45RROR\x10\x02\"T\n\rTestCamelCase\x12\x14\n\x0cnormal_field\x18\x01 \x01(\t\x12\x15\n\rCAPITAL_FIELD\x18\x02 \x01(\x05\x12\x16\n\x0e\x43\x61melCaseField\x18\x03 \x01(\x05\"|\n\x0bTestBoolMap\x12=\n\x08\x62ool_map\x18\x01 \x03(\x0b\x32+.protobuf_unittest.TestBoolMap.BoolMapEntry\x1a.\n\x0c\x42oolMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\"O\n\rTestRecursion\x12\r\n\x05value\x18\x01 \x01(\x05\x12/\n\x05\x63hild\x18\x02 \x01(\x0b\x32 .protobuf_unittest.TestRecursion\"\x86\x01\n\rTestStringMap\x12\x43\n\nstring_map\x18\x01 \x03(\x0b\x32/.protobuf_unittest.TestStringMap.StringMapEntry\x1a\x30\n\x0eStringMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xc4\x01\n\x14TestStringSerializer\x12\x15\n\rscalar_string\x18\x01 \x01(\t\x12\x17\n\x0frepeated_string\x18\x02 \x03(\t\x12J\n\nstring_map\x18\x03 \x03(\x0b\x32\x36.protobuf_unittest.TestStringSerializer.StringMapEntry\x1a\x30\n\x0eStringMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"$\n\x18TestMessageWithExtension*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"z\n\rTestExtension\x12\r\n\x05value\x18\x01 \x01(\t2Z\n\x03\x65xt\x12+.protobuf_unittest.TestMessageWithExtension\x18\x64 \x01(\x0b\x32 .protobuf_unittest.TestExtension\"Q\n\x14TestDefaultEnumValue\x12\x39\n\nenum_value\x18\x01 \x01(\x0e\x32\x1c.protobuf_unittest.EnumValue:\x07\x44\x45\x46\x41ULT*2\n\tEnumValue\x12\x0c\n\x08PROTOCOL\x10\x00\x12\n\n\x06\x42UFFER\x10\x01\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x02') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.util.json_format_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + TestMessageWithExtension.RegisterExtension(_TESTEXTENSION.extensions_by_name['ext']) + + DESCRIPTOR._options = None + _TESTBOOLMAP_BOOLMAPENTRY._options = None + _TESTBOOLMAP_BOOLMAPENTRY._serialized_options = b'8\001' + _TESTSTRINGMAP_STRINGMAPENTRY._options = None + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_options = b'8\001' + _TESTSTRINGSERIALIZER_STRINGMAPENTRY._options = None + _TESTSTRINGSERIALIZER_STRINGMAPENTRY._serialized_options = b'8\001' + _ENUMVALUE._serialized_start=1607 + _ENUMVALUE._serialized_end=1657 + _TESTFLAGSANDSTRINGS._serialized_start=62 + _TESTFLAGSANDSTRINGS._serialized_end=199 + _TESTFLAGSANDSTRINGS_REPEATEDGROUP._serialized_start=173 + _TESTFLAGSANDSTRINGS_REPEATEDGROUP._serialized_end=199 + _TESTBASE64BYTEARRAYS._serialized_start=201 + _TESTBASE64BYTEARRAYS._serialized_end=234 + _TESTJAVASCRIPTJSON._serialized_start=236 + _TESTJAVASCRIPTJSON._serialized_end=307 + _TESTJAVASCRIPTORDERJSON1._serialized_start=309 + _TESTJAVASCRIPTORDERJSON1._serialized_end=390 + _TESTJAVASCRIPTORDERJSON2._serialized_start=393 + _TESTJAVASCRIPTORDERJSON2._serialized_end=530 + _TESTLARGEINT._serialized_start=532 + _TESTLARGEINT._serialized_end=568 + _TESTNUMBERS._serialized_start=571 + _TESTNUMBERS._serialized_end=731 + _TESTNUMBERS_MYTYPE._serialized_start=691 + _TESTNUMBERS_MYTYPE._serialized_end=731 + _TESTCAMELCASE._serialized_start=733 + _TESTCAMELCASE._serialized_end=817 + _TESTBOOLMAP._serialized_start=819 + _TESTBOOLMAP._serialized_end=943 + _TESTBOOLMAP_BOOLMAPENTRY._serialized_start=897 + _TESTBOOLMAP_BOOLMAPENTRY._serialized_end=943 + _TESTRECURSION._serialized_start=945 + _TESTRECURSION._serialized_end=1024 + _TESTSTRINGMAP._serialized_start=1027 + _TESTSTRINGMAP._serialized_end=1161 + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_start=1113 + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_end=1161 + _TESTSTRINGSERIALIZER._serialized_start=1164 + _TESTSTRINGSERIALIZER._serialized_end=1360 + _TESTSTRINGSERIALIZER_STRINGMAPENTRY._serialized_start=1113 + _TESTSTRINGSERIALIZER_STRINGMAPENTRY._serialized_end=1161 + _TESTMESSAGEWITHEXTENSION._serialized_start=1362 + _TESTMESSAGEWITHEXTENSION._serialized_end=1398 + _TESTEXTENSION._serialized_start=1400 + _TESTEXTENSION._serialized_end=1522 + _TESTDEFAULTENUMVALUE._serialized_start=1524 + _TESTDEFAULTENUMVALUE._serialized_end=1605 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_proto3_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_proto3_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5498deafa9ea4150f3b5bf213503cf60eb30a36a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/util/json_format_proto3_pb2.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/util/json_format_proto3.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 +from google.protobuf import unittest_pb2 as google_dot_protobuf_dot_unittest__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n-google/protobuf/util/json_format_proto3.proto\x12\x06proto3\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x1egoogle/protobuf/unittest.proto\"\x1c\n\x0bMessageType\x12\r\n\x05value\x18\x01 \x01(\x05\"\x94\x05\n\x0bTestMessage\x12\x12\n\nbool_value\x18\x01 \x01(\x08\x12\x13\n\x0bint32_value\x18\x02 \x01(\x05\x12\x13\n\x0bint64_value\x18\x03 \x01(\x03\x12\x14\n\x0cuint32_value\x18\x04 \x01(\r\x12\x14\n\x0cuint64_value\x18\x05 \x01(\x04\x12\x13\n\x0b\x66loat_value\x18\x06 \x01(\x02\x12\x14\n\x0c\x64ouble_value\x18\x07 \x01(\x01\x12\x14\n\x0cstring_value\x18\x08 \x01(\t\x12\x13\n\x0b\x62ytes_value\x18\t \x01(\x0c\x12$\n\nenum_value\x18\n \x01(\x0e\x32\x10.proto3.EnumType\x12*\n\rmessage_value\x18\x0b \x01(\x0b\x32\x13.proto3.MessageType\x12\x1b\n\x13repeated_bool_value\x18\x15 \x03(\x08\x12\x1c\n\x14repeated_int32_value\x18\x16 \x03(\x05\x12\x1c\n\x14repeated_int64_value\x18\x17 \x03(\x03\x12\x1d\n\x15repeated_uint32_value\x18\x18 \x03(\r\x12\x1d\n\x15repeated_uint64_value\x18\x19 \x03(\x04\x12\x1c\n\x14repeated_float_value\x18\x1a \x03(\x02\x12\x1d\n\x15repeated_double_value\x18\x1b \x03(\x01\x12\x1d\n\x15repeated_string_value\x18\x1c \x03(\t\x12\x1c\n\x14repeated_bytes_value\x18\x1d \x03(\x0c\x12-\n\x13repeated_enum_value\x18\x1e \x03(\x0e\x32\x10.proto3.EnumType\x12\x33\n\x16repeated_message_value\x18\x1f \x03(\x0b\x32\x13.proto3.MessageType\"\x8c\x02\n\tTestOneof\x12\x1b\n\x11oneof_int32_value\x18\x01 \x01(\x05H\x00\x12\x1c\n\x12oneof_string_value\x18\x02 \x01(\tH\x00\x12\x1b\n\x11oneof_bytes_value\x18\x03 \x01(\x0cH\x00\x12,\n\x10oneof_enum_value\x18\x04 \x01(\x0e\x32\x10.proto3.EnumTypeH\x00\x12\x32\n\x13oneof_message_value\x18\x05 \x01(\x0b\x32\x13.proto3.MessageTypeH\x00\x12\x36\n\x10oneof_null_value\x18\x06 \x01(\x0e\x32\x1a.google.protobuf.NullValueH\x00\x42\r\n\x0boneof_value\"\xe1\x04\n\x07TestMap\x12.\n\x08\x62ool_map\x18\x01 \x03(\x0b\x32\x1c.proto3.TestMap.BoolMapEntry\x12\x30\n\tint32_map\x18\x02 \x03(\x0b\x32\x1d.proto3.TestMap.Int32MapEntry\x12\x30\n\tint64_map\x18\x03 \x03(\x0b\x32\x1d.proto3.TestMap.Int64MapEntry\x12\x32\n\nuint32_map\x18\x04 \x03(\x0b\x32\x1e.proto3.TestMap.Uint32MapEntry\x12\x32\n\nuint64_map\x18\x05 \x03(\x0b\x32\x1e.proto3.TestMap.Uint64MapEntry\x12\x32\n\nstring_map\x18\x06 \x03(\x0b\x32\x1e.proto3.TestMap.StringMapEntry\x1a.\n\x0c\x42oolMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a/\n\rInt32MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a/\n\rInt64MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eUint32MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eUint64MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eStringMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\"\x85\x06\n\rTestNestedMap\x12\x34\n\x08\x62ool_map\x18\x01 \x03(\x0b\x32\".proto3.TestNestedMap.BoolMapEntry\x12\x36\n\tint32_map\x18\x02 \x03(\x0b\x32#.proto3.TestNestedMap.Int32MapEntry\x12\x36\n\tint64_map\x18\x03 \x03(\x0b\x32#.proto3.TestNestedMap.Int64MapEntry\x12\x38\n\nuint32_map\x18\x04 \x03(\x0b\x32$.proto3.TestNestedMap.Uint32MapEntry\x12\x38\n\nuint64_map\x18\x05 \x03(\x0b\x32$.proto3.TestNestedMap.Uint64MapEntry\x12\x38\n\nstring_map\x18\x06 \x03(\x0b\x32$.proto3.TestNestedMap.StringMapEntry\x12\x32\n\x07map_map\x18\x07 \x03(\x0b\x32!.proto3.TestNestedMap.MapMapEntry\x1a.\n\x0c\x42oolMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a/\n\rInt32MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a/\n\rInt64MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x03\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eUint32MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eUint64MapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eStringMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x44\n\x0bMapMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12$\n\x05value\x18\x02 \x01(\x0b\x32\x15.proto3.TestNestedMap:\x02\x38\x01\"{\n\rTestStringMap\x12\x38\n\nstring_map\x18\x01 \x03(\x0b\x32$.proto3.TestStringMap.StringMapEntry\x1a\x30\n\x0eStringMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xee\x07\n\x0bTestWrapper\x12.\n\nbool_value\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\x0bint32_value\x18\x02 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bint64_value\x18\x03 \x01(\x0b\x32\x1b.google.protobuf.Int64Value\x12\x32\n\x0cuint32_value\x18\x04 \x01(\x0b\x32\x1c.google.protobuf.UInt32Value\x12\x32\n\x0cuint64_value\x18\x05 \x01(\x0b\x32\x1c.google.protobuf.UInt64Value\x12\x30\n\x0b\x66loat_value\x18\x06 \x01(\x0b\x32\x1b.google.protobuf.FloatValue\x12\x32\n\x0c\x64ouble_value\x18\x07 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x32\n\x0cstring_value\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0b\x62ytes_value\x18\t \x01(\x0b\x32\x1b.google.protobuf.BytesValue\x12\x37\n\x13repeated_bool_value\x18\x0b \x03(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x14repeated_int32_value\x18\x0c \x03(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x39\n\x14repeated_int64_value\x18\r \x03(\x0b\x32\x1b.google.protobuf.Int64Value\x12;\n\x15repeated_uint32_value\x18\x0e \x03(\x0b\x32\x1c.google.protobuf.UInt32Value\x12;\n\x15repeated_uint64_value\x18\x0f \x03(\x0b\x32\x1c.google.protobuf.UInt64Value\x12\x39\n\x14repeated_float_value\x18\x10 \x03(\x0b\x32\x1b.google.protobuf.FloatValue\x12;\n\x15repeated_double_value\x18\x11 \x03(\x0b\x32\x1c.google.protobuf.DoubleValue\x12;\n\x15repeated_string_value\x18\x12 \x03(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14repeated_bytes_value\x18\x13 \x03(\x0b\x32\x1b.google.protobuf.BytesValue\"n\n\rTestTimestamp\x12)\n\x05value\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x32\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x1a.google.protobuf.Timestamp\"k\n\x0cTestDuration\x12(\n\x05value\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x31\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x19.google.protobuf.Duration\":\n\rTestFieldMask\x12)\n\x05value\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"e\n\nTestStruct\x12&\n\x05value\x18\x01 \x01(\x0b\x32\x17.google.protobuf.Struct\x12/\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x17.google.protobuf.Struct\"\\\n\x07TestAny\x12#\n\x05value\x18\x01 \x01(\x0b\x32\x14.google.protobuf.Any\x12,\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x14.google.protobuf.Any\"b\n\tTestValue\x12%\n\x05value\x18\x01 \x01(\x0b\x32\x16.google.protobuf.Value\x12.\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x16.google.protobuf.Value\"n\n\rTestListValue\x12)\n\x05value\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.ListValue\x12\x32\n\x0erepeated_value\x18\x02 \x03(\x0b\x32\x1a.google.protobuf.ListValue\"\x89\x01\n\rTestBoolValue\x12\x12\n\nbool_value\x18\x01 \x01(\x08\x12\x34\n\x08\x62ool_map\x18\x02 \x03(\x0b\x32\".proto3.TestBoolValue.BoolMapEntry\x1a.\n\x0c\x42oolMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\x08\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\"+\n\x12TestCustomJsonName\x12\x15\n\x05value\x18\x01 \x01(\x05R\x06@value\"J\n\x0eTestExtensions\x12\x38\n\nextensions\x18\x01 \x01(\x0b\x32$.protobuf_unittest.TestAllExtensions\"\x84\x01\n\rTestEnumValue\x12%\n\x0b\x65num_value1\x18\x01 \x01(\x0e\x32\x10.proto3.EnumType\x12%\n\x0b\x65num_value2\x18\x02 \x01(\x0e\x32\x10.proto3.EnumType\x12%\n\x0b\x65num_value3\x18\x03 \x01(\x0e\x32\x10.proto3.EnumType*\x1c\n\x08\x45numType\x12\x07\n\x03\x46OO\x10\x00\x12\x07\n\x03\x42\x41R\x10\x01\x42,\n\x18\x63om.google.protobuf.utilB\x10JsonFormatProto3b\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.util.json_format_proto3_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\030com.google.protobuf.utilB\020JsonFormatProto3' + _TESTMAP_BOOLMAPENTRY._options = None + _TESTMAP_BOOLMAPENTRY._serialized_options = b'8\001' + _TESTMAP_INT32MAPENTRY._options = None + _TESTMAP_INT32MAPENTRY._serialized_options = b'8\001' + _TESTMAP_INT64MAPENTRY._options = None + _TESTMAP_INT64MAPENTRY._serialized_options = b'8\001' + _TESTMAP_UINT32MAPENTRY._options = None + _TESTMAP_UINT32MAPENTRY._serialized_options = b'8\001' + _TESTMAP_UINT64MAPENTRY._options = None + _TESTMAP_UINT64MAPENTRY._serialized_options = b'8\001' + _TESTMAP_STRINGMAPENTRY._options = None + _TESTMAP_STRINGMAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_BOOLMAPENTRY._options = None + _TESTNESTEDMAP_BOOLMAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_INT32MAPENTRY._options = None + _TESTNESTEDMAP_INT32MAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_INT64MAPENTRY._options = None + _TESTNESTEDMAP_INT64MAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_UINT32MAPENTRY._options = None + _TESTNESTEDMAP_UINT32MAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_UINT64MAPENTRY._options = None + _TESTNESTEDMAP_UINT64MAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_STRINGMAPENTRY._options = None + _TESTNESTEDMAP_STRINGMAPENTRY._serialized_options = b'8\001' + _TESTNESTEDMAP_MAPMAPENTRY._options = None + _TESTNESTEDMAP_MAPMAPENTRY._serialized_options = b'8\001' + _TESTSTRINGMAP_STRINGMAPENTRY._options = None + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_options = b'8\001' + _TESTBOOLVALUE_BOOLMAPENTRY._options = None + _TESTBOOLVALUE_BOOLMAPENTRY._serialized_options = b'8\001' + _ENUMTYPE._serialized_start=4849 + _ENUMTYPE._serialized_end=4877 + _MESSAGETYPE._serialized_start=277 + _MESSAGETYPE._serialized_end=305 + _TESTMESSAGE._serialized_start=308 + _TESTMESSAGE._serialized_end=968 + _TESTONEOF._serialized_start=971 + _TESTONEOF._serialized_end=1239 + _TESTMAP._serialized_start=1242 + _TESTMAP._serialized_end=1851 + _TESTMAP_BOOLMAPENTRY._serialized_start=1557 + _TESTMAP_BOOLMAPENTRY._serialized_end=1603 + _TESTMAP_INT32MAPENTRY._serialized_start=1605 + _TESTMAP_INT32MAPENTRY._serialized_end=1652 + _TESTMAP_INT64MAPENTRY._serialized_start=1654 + _TESTMAP_INT64MAPENTRY._serialized_end=1701 + _TESTMAP_UINT32MAPENTRY._serialized_start=1703 + _TESTMAP_UINT32MAPENTRY._serialized_end=1751 + _TESTMAP_UINT64MAPENTRY._serialized_start=1753 + _TESTMAP_UINT64MAPENTRY._serialized_end=1801 + _TESTMAP_STRINGMAPENTRY._serialized_start=1803 + _TESTMAP_STRINGMAPENTRY._serialized_end=1851 + _TESTNESTEDMAP._serialized_start=1854 + _TESTNESTEDMAP._serialized_end=2627 + _TESTNESTEDMAP_BOOLMAPENTRY._serialized_start=1557 + _TESTNESTEDMAP_BOOLMAPENTRY._serialized_end=1603 + _TESTNESTEDMAP_INT32MAPENTRY._serialized_start=1605 + _TESTNESTEDMAP_INT32MAPENTRY._serialized_end=1652 + _TESTNESTEDMAP_INT64MAPENTRY._serialized_start=1654 + _TESTNESTEDMAP_INT64MAPENTRY._serialized_end=1701 + _TESTNESTEDMAP_UINT32MAPENTRY._serialized_start=1703 + _TESTNESTEDMAP_UINT32MAPENTRY._serialized_end=1751 + _TESTNESTEDMAP_UINT64MAPENTRY._serialized_start=1753 + _TESTNESTEDMAP_UINT64MAPENTRY._serialized_end=1801 + _TESTNESTEDMAP_STRINGMAPENTRY._serialized_start=1803 + _TESTNESTEDMAP_STRINGMAPENTRY._serialized_end=1851 + _TESTNESTEDMAP_MAPMAPENTRY._serialized_start=2559 + _TESTNESTEDMAP_MAPMAPENTRY._serialized_end=2627 + _TESTSTRINGMAP._serialized_start=2629 + _TESTSTRINGMAP._serialized_end=2752 + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_start=2704 + _TESTSTRINGMAP_STRINGMAPENTRY._serialized_end=2752 + _TESTWRAPPER._serialized_start=2755 + _TESTWRAPPER._serialized_end=3761 + _TESTTIMESTAMP._serialized_start=3763 + _TESTTIMESTAMP._serialized_end=3873 + _TESTDURATION._serialized_start=3875 + _TESTDURATION._serialized_end=3982 + _TESTFIELDMASK._serialized_start=3984 + _TESTFIELDMASK._serialized_end=4042 + _TESTSTRUCT._serialized_start=4044 + _TESTSTRUCT._serialized_end=4145 + _TESTANY._serialized_start=4147 + _TESTANY._serialized_end=4239 + _TESTVALUE._serialized_start=4241 + _TESTVALUE._serialized_end=4339 + _TESTLISTVALUE._serialized_start=4341 + _TESTLISTVALUE._serialized_end=4451 + _TESTBOOLVALUE._serialized_start=4454 + _TESTBOOLVALUE._serialized_end=4591 + _TESTBOOLVALUE_BOOLMAPENTRY._serialized_start=1557 + _TESTBOOLVALUE_BOOLMAPENTRY._serialized_end=1603 + _TESTCUSTOMJSONNAME._serialized_start=4593 + _TESTCUSTOMJSONNAME._serialized_end=4636 + _TESTEXTENSIONS._serialized_start=4638 + _TESTEXTENSIONS._serialized_end=4712 + _TESTENUMVALUE._serialized_start=4715 + _TESTENUMVALUE._serialized_end=4847 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/wrappers_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/wrappers_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..e49eb4c15d926cd2563aa63d90b31dd118b28da3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/google/protobuf/wrappers_pb2.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/wrappers.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/wrappers.proto\x12\x0fgoogle.protobuf\"\x1c\n\x0b\x44oubleValue\x12\r\n\x05value\x18\x01 \x01(\x01\"\x1b\n\nFloatValue\x12\r\n\x05value\x18\x01 \x01(\x02\"\x1b\n\nInt64Value\x12\r\n\x05value\x18\x01 \x01(\x03\"\x1c\n\x0bUInt64Value\x12\r\n\x05value\x18\x01 \x01(\x04\"\x1b\n\nInt32Value\x12\r\n\x05value\x18\x01 \x01(\x05\"\x1c\n\x0bUInt32Value\x12\r\n\x05value\x18\x01 \x01(\r\"\x1a\n\tBoolValue\x12\r\n\x05value\x18\x01 \x01(\x08\"\x1c\n\x0bStringValue\x12\r\n\x05value\x18\x01 \x01(\t\"\x1b\n\nBytesValue\x12\r\n\x05value\x18\x01 \x01(\x0c\x42\x83\x01\n\x13\x63om.google.protobufB\rWrappersProtoP\x01Z1google.golang.org/protobuf/types/known/wrapperspb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.wrappers_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\023com.google.protobufB\rWrappersProtoP\001Z1google.golang.org/protobuf/types/known/wrapperspb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _DOUBLEVALUE._serialized_start=51 + _DOUBLEVALUE._serialized_end=79 + _FLOATVALUE._serialized_start=81 + _FLOATVALUE._serialized_end=108 + _INT64VALUE._serialized_start=110 + _INT64VALUE._serialized_end=137 + _UINT64VALUE._serialized_start=139 + _UINT64VALUE._serialized_end=167 + _INT32VALUE._serialized_start=169 + _INT32VALUE._serialized_end=196 + _UINT32VALUE._serialized_start=198 + _UINT32VALUE._serialized_end=226 + _BOOLVALUE._serialized_start=228 + _BOOLVALUE._serialized_end=254 + _STRINGVALUE._serialized_start=256 + _STRINGVALUE._serialized_end=284 + _BYTESVALUE._serialized_start=286 + _BYTESVALUE._serialized_end=313 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ocr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ocr.py new file mode 100644 index 0000000000000000000000000000000000000000..7e4c5253d6eee6caebb295a3e460176ea15933ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ocr.py @@ -0,0 +1,352 @@ + +# PaddleOCR_ali1k_det_rec_300epoch/tools/infer/predict_system.py + +import os, sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +# sys.path.insert(0, os.path.abspath(os.path.join(__dir__, 'PaddleOCR_ali1k_det_rec_300epoch'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import copy +import numpy as np +import json +import time +import logging +from PIL import Image +import tools.infer.utility as utility + +import tools.infer.predict_rec as predict_rec +import tools.infer.predict_det as predict_det +import tools.infer.predict_cls as predict_cls +from ppocr.utils.utility import get_image_file_list, check_and_read +from ppocr.utils.logging import get_logger +from tools.infer.utility import draw_ocr_box_txt, get_rotate_crop_image +logger = get_logger() + + +class TextSystem(object): + def __init__(self, args): + if not args.show_log: + logger.setLevel(logging.INFO) + + self.text_detector = predict_det.TextDetector(args) + self.text_recognizer = predict_rec.TextRecognizer(args) + self.use_angle_cls = args.use_angle_cls + self.drop_score = args.drop_score + if self.use_angle_cls: + self.text_classifier = predict_cls.TextClassifier(args) + + self.args = args + self.crop_image_res_index = 0 + + def draw_crop_rec_res(self, output_dir, img_crop_list, rec_res): + os.makedirs(output_dir, exist_ok=True) + bbox_num = len(img_crop_list) + for bno in range(bbox_num): + cv2.imwrite( + os.path.join(output_dir, + f"mg_crop_{bno+self.crop_image_res_index}.jpg"), + img_crop_list[bno]) + logger.debug(f"{bno}, {rec_res[bno]}") + self.crop_image_res_index += bbox_num + + def __call__(self, img, cls=True): + time_dict = {'det': 0, 'rec': 0, 'csl': 0, 'all': 0} + start = time.time() + ori_im = img.copy() + dt_boxes, elapse = self.text_detector(img) + time_dict['det'] = elapse + logger.debug("dt_boxes num : {}, elapse : {}".format( + len(dt_boxes), elapse)) + if dt_boxes is None: + return None, None + img_crop_list = [] + + dt_boxes = sorted_boxes(dt_boxes) + + for bno in range(len(dt_boxes)): + tmp_box = copy.deepcopy(dt_boxes[bno]) + img_crop = get_rotate_crop_image(ori_im, tmp_box) + img_crop_list.append(img_crop) + if self.use_angle_cls and cls: + img_crop_list, angle_list, elapse = self.text_classifier( + img_crop_list) + time_dict['cls'] = elapse + logger.debug("cls num : {}, elapse : {}".format( + len(img_crop_list), elapse)) + + rec_res, elapse = self.text_recognizer(img_crop_list) + time_dict['rec'] = elapse + logger.debug("rec_res num : {}, elapse : {}".format( + len(rec_res), elapse)) + if self.args.save_crop_res: + self.draw_crop_rec_res(self.args.crop_res_save_dir, img_crop_list, + rec_res) + filter_boxes, filter_rec_res = [], [] + for box, rec_result in zip(dt_boxes, rec_res): + text, score = rec_result + if score >= self.drop_score: + filter_boxes.append(box) + filter_rec_res.append(rec_result) + end = time.time() + time_dict['all'] = end - start + return filter_boxes, filter_rec_res, time_dict + + +def sorted_boxes(dt_boxes): + """ + Sort text boxes in order from top to bottom, left to right + args: + dt_boxes(array):detected text boxes with shape [4, 2] + return: + sorted boxes(array) with shape [4, 2] + """ + num_boxes = dt_boxes.shape[0] + sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0])) + _boxes = list(sorted_boxes) + + for i in range(num_boxes - 1): + for j in range(i, 0, -1): + if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \ + (_boxes[j + 1][0][0] < _boxes[j][0][0]): + tmp = _boxes[j] + _boxes[j] = _boxes[j + 1] + _boxes[j + 1] = tmp + else: + break + return _boxes + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + image_file_list = image_file_list[args.process_id::args.total_process_num] + text_sys = TextSystem(args) + is_visualize = True + font_path = args.vis_font_path + drop_score = args.drop_score + draw_img_save_dir = args.draw_img_save_dir + os.makedirs(draw_img_save_dir, exist_ok=True) + save_results = [] + + logger.info( + "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', " + "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320" + ) + + # warm up 10 times + if args.warmup: + img = np.random.uniform(0, 255, [640, 640, 3]).astype(np.uint8) + for i in range(10): + res = text_sys(img) + + total_time = 0 + cpu_mem, gpu_mem, gpu_util = 0, 0, 0 + _st = time.time() + count = 0 + for idx, image_file in enumerate(image_file_list): + + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.debug("error in loading image:{}".format(image_file)) + continue + starttime = time.time() + dt_boxes, rec_res, time_dict = text_sys(img) + elapse = time.time() - starttime + total_time += elapse + + logger.debug( + str(idx) + " Predict time of %s: %.3fs" % (image_file, elapse)) + for text, score in rec_res: + logger.debug("{}, {:.3f}".format(text, score)) + + res = [{ + "transcription": rec_res[idx][0], + "points": np.array(dt_boxes[idx]).astype(np.int32).tolist(), + } for idx in range(len(dt_boxes))] + save_pred = os.path.basename(image_file) + "\t" + json.dumps( + res, ensure_ascii=False) + "\n" + save_results.append(save_pred) + + if is_visualize: + image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + boxes = dt_boxes + txts = [rec_res[i][0] for i in range(len(rec_res))] + scores = [rec_res[i][1] for i in range(len(rec_res))] + + draw_img = draw_ocr_box_txt( + image, + boxes, + txts, + scores, + drop_score=drop_score, + font_path=font_path) + if flag: + image_file = image_file[:-3] + "png" + cv2.imwrite( + os.path.join(draw_img_save_dir, os.path.basename(image_file)), + draw_img[:, :, ::-1]) + logger.debug("The visualized image saved in {}".format( + os.path.join(draw_img_save_dir, os.path.basename(image_file)))) + + logger.info("The predict total time is {}".format(time.time() - _st)) + if args.benchmark: + text_sys.text_detector.autolog.report() + text_sys.text_recognizer.autolog.report() + + with open( + os.path.join(draw_img_save_dir, "system_results.txt"), + 'w', + encoding='utf-8') as f: + f.writelines(save_results) + + +class AttributeDict(dict): + def __getattr__(self, attr): + return self[attr] + def __setattr__(self, attr, value): + self[attr] = value + +if __name__ == "__main__": + + # text_detector = predict_det.TextDetector( AttributeDict({"det_algorithm": "DB"}) ) + #text_recognizer = predict_rec.TextRecognizer(args) + + # img = cv2.imread(image_file) + # starttime = time.time() + # dt_boxes, rec_res, time_dict = text_sys(img) + # elapse = time.time() - starttime + + + """ + python3 tools/infer/predict_system.py \ + --image_dir="train_data/det/test/25.jpg" \ + --det_algorithm="DB" \ + --det_model_dir="output/det_model" \ + --det_limit_side_len=960 \ + --det_db_unclip_ratio=3.5 \ + --rec_model_dir="output/rec_model/Student" \ + --rec_char_dict_path="train_data/keys.txt" \ + --use_gpu False \ + --enable_mkldnn=True + + """ + import sys + sys.argv.append( '--image_dir' ) + # sys.argv.append( 'train_data/det/test/12.jpg' ) + sys.argv.append( 'train_data/det/train/3.jpg' ) + sys.argv.append( '--det_algorithm' ) + sys.argv.append( 'DB' ) + sys.argv.append( '--det_model_dir' ) + # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/output/det_model' ) # 自已训练的 + sys.argv.append( 'official_models/ch_PP-OCRv3_det_infer' ) # 官方的 + sys.argv.append( '--det_limit_side_len' ) + # sys.argv.append( '960' ) # 自已的 + sys.argv.append( '1024' ) # 官方的 + sys.argv.append( '--det_db_unclip_ratio' ) + sys.argv.append( '3.5' ) + sys.argv.append( '--rec_model_dir' ) + # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/output/rec_model/Student' ) # 自已的 + sys.argv.append( 'official_models/ch_PP-OCRv3_rec_infer' ) # 官方的 + sys.argv.append( '--rec_char_dict_path' ) + # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/train_data/keys.txt' ) # 自已的 + sys.argv.append( 'official_models/ppocr_keys.txt' ) # 官方的词表 + sys.argv.append( '--use_gpu' ) + sys.argv.append( 'False' ) + sys.argv.append( '--enable_mkldnn' ) + sys.argv.append( 'True' ) + sys.argv.append( '--vis_font_path' ) + sys.argv.append( 'fonts/simfang.ttf' ) + + + args = utility.parse_args() + + text_sys = TextSystem(args) + img = cv2.imread('train_data/det/train/3.jpg') + #img = cv2.imread('images/ch.png') + + dt_boxes, rec_res, time_dict = text_sys(img) + + res = [{ + "transcription": rec_res[idx][0], + "points": np.array(dt_boxes[idx]).astype(np.int32).tolist(), + } for idx in range(len(dt_boxes))] + + image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + boxes = dt_boxes + txts = [rec_res[i][0] for i in range(len(rec_res))] + scores = [rec_res[i][1] for i in range(len(rec_res))] + + font_path = args.vis_font_path + drop_score = args.drop_score + draw_img = draw_ocr_box_txt( + image, + boxes, + txts, + scores, + drop_score=drop_score, + font_path=font_path) + + # 缩放图片, 统一 800 宽 + height, width, colorNum = img.shape + + newWidth = 800 + if width > newWidth: + rate = newWidth / width + newHeight = int(rate * height) + dim = (newWidth, newHeight) + img_des = cv2.resize(draw_img, dim, interpolation=cv2.INTER_LINEAR) #img.resize (new OpenCvSharp.Size(0, 0), rate, rate, InterpolationFlags.Linear); + else: + img_des = draw_img.copy() + + cv2.imshow("result", draw_img) + cv2.waitKey(0) + + main(args) + + + + + + + + + + + + + + + + + + + + + + + + +# pip install paddlepaddle "paddleocr==2.7.0.0" -i https://mirror.baidu.com/pypi/simple + +# apt install python3.10-dev + +# pip install paddlepaddle "paddleocr==2.7.5" -i https://mirror.baidu.com/pypi/simple + +# from paddleocr import PaddleOCR, draw_ocr + +# # `ch`, `en`, `fr`, `german`, `korean`, `japan` +# ocr = PaddleOCR(use_angle_cls=True, lang="ch") # need to run only once to download and load model into memory +# img_path = './images/ch.png' +# result = ocr.ocr(img_path, cls=True) +# for idx in range(len(result)): +# res = result[idx] +# for line in res: +# print(line) + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..242660e2e7e8b39d5cafcf0eeb3332bd4d955d60 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b341a2f775e294a30df12fed0441a7ec405fcfe4e0aca4e52f6688ea9ec0ce73 +size 212 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..242660e2e7e8b39d5cafcf0eeb3332bd4d955d60 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b341a2f775e294a30df12fed0441a7ec405fcfe4e0aca4e52f6688ea9ec0ce73 +size 212 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..242660e2e7e8b39d5cafcf0eeb3332bd4d955d60 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/._inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b341a2f775e294a30df12fed0441a7ec405fcfe4e0aca4e52f6688ea9ec0ce73 +size 212 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..269760eae0bfeb635f385c257020a920580f7d34 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e9518c6ab706fe87842a8de1c098f990e67f9212b67c9ef8bc4bca6dc17b91a +size 2377917 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..835fb5f0429bc51dc77b82e4916243f943e223ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fe414d9eadf914bf44e3f9ba212988a6f26f364e4f87c6d0af57438ffffc0c4 +size 26392 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..c0a044c9779ad81d39117a443ab1af052bf4173e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer/inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:601c6efd83e882bc53ab1df89ce20f9024d9ac8e71022b1dc7d61136cdff5bee +size 1253654 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..b398d1f288cb7514cc069469e8e7df137747aaf4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d99d4279f7c64471b8f0be426ee09a46c0f1ecb344406bf0bb9571f670e8d0c7 +size 10614098 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..9a83a5c51a58ff9b80bf80fa6ff88f34a2cea303 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d463655101b254cdee5166c3351b57c91536043f79f01851c49c778dc998b7f5 +size 22034 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..ba592fe80043fd68de46e183b44c27aab43e61dc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer/inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b9beb0b9520d34bde2a0f92581ed64db7e4d6c76abead8b859189ea72db9ee20 +size 1266415 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..675fcdcb09bc533d915bc482a867bb3a2d6f8ce5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4837832ace0e71df968caeb1fbd0dae3a4105a015712a139b110c9a5b99bd23a +size 539978 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..becf14733af93a9be3213de2da98f97c1fbf026d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b9a6de4da312115a7ad68b633e1ce8088800f7c6f53df5cf8b7562f64f8e837 +size 19841 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..860d9db2ef3f5360736507c30ac34041500bce7c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_ppocr_mobile_v2.0_cls_infer/inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fa20a45c21feb2bf68a08459feaee4008bcb9ac72aa86ed9d858e063a627a53 +size 886703 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..20a81595e7adfb446baef6a2fffdfd6ced98ef6b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e137a00dee48b713bd88aeacf02d01fc3d32b49f7e4d4d9ecfeaf92b59644ca4 +size 10035858 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..d43fe3ecca2d535a4aa80f100168c51fa5e58cf2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf79f0b9689b4d6b8094d8bfe2481dc4b4d1699adb622568384695b5f56dc600 +size 21964 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..1211a99c8318d6dc30f4d7b9121113c1a41ea258 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer/inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19d399099a85e0610d489cb5dd4e39f7fa7700e0ed8bfe083a788a7422a9babe +size 1313930 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..339d4b89e5159a346636641a0814874faa59754a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_dict.txt @@ -0,0 +1,4399 @@ +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +] +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +© +° +² +´ +½ +Á +Ä +Å +Ç +È +É +Í +Ó +Ö +× +Ü +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +í +ð +ñ +ò +ó +ô +õ +ö +ø +ú +û +ü +ý +ā +ă +ą +ć +Č +č +đ +ē +ė +ę +ğ +ī +ı +Ł +ł +ń +ň +ō +ř +Ş +ş +Š +š +ţ +ū +ż +Ž +ž +Ș +ș +ț +Δ +α +λ +μ +φ +Г +О +а +в +л +о +р +с +т +я +ồ +​ +— +― +’ +“ +” +… +℃ +→ +∇ +− +■ +☆ +  +、 +。 +々 +〆 +〈 +〉 +「 +」 +『 +』 +〔 +〕 +〜 +ぁ +あ +ぃ +い +う +ぇ +え +ぉ +お +か +が +き +ぎ +く +ぐ +け +げ +こ +ご +さ +ざ +し +じ +す +ず +せ +ぜ +そ +ぞ +た +だ +ち +ぢ +っ +つ +づ +て +で +と +ど +な +に +ぬ +ね +の +は +ば +ぱ +ひ +び +ぴ +ふ +ぶ +ぷ +へ +べ +ぺ +ほ +ぼ +ぽ +ま +み +む +め +も +ゃ +や +ゅ +ゆ +ょ +よ +ら +り +る +れ +ろ +わ +ゑ +を +ん +ゝ +ゞ +ァ +ア +ィ +イ +ゥ +ウ +ェ +エ +ォ +オ +カ +ガ +キ +ギ +ク +グ +ケ +ゲ +コ +ゴ +サ +ザ +シ +ジ +ス +ズ +セ +ゼ +ソ +ゾ +タ +ダ +チ +ヂ +ッ +ツ +ヅ +テ +デ +ト +ド +ナ +ニ +ヌ +ネ +ノ +ハ +バ +パ +ヒ +ビ +ピ +フ +ブ +プ +ヘ +ベ +ペ +ホ +ボ +ポ +マ +ミ +ム +メ +モ +ャ +ヤ +ュ +ユ +ョ +ヨ +ラ +リ +ル +レ +ロ +ワ +ヰ +ン +ヴ +ヵ +ヶ +・ +ー +㈱ +一 +丁 +七 +万 +丈 +三 +上 +下 +不 +与 +丑 +且 +世 +丘 +丙 +丞 +両 +並 +中 +串 +丸 +丹 +主 +丼 +丿 +乃 +久 +之 +乎 +乏 +乗 +乘 +乙 +九 +乞 +也 +乱 +乳 +乾 +亀 +了 +予 +争 +事 +二 +于 +互 +五 +井 +亘 +亙 +些 +亜 +亟 +亡 +交 +亥 +亦 +亨 +享 +京 +亭 +亮 +人 +什 +仁 +仇 +今 +介 +仍 +仏 +仔 +仕 +他 +仗 +付 +仙 +代 +令 +以 +仮 +仰 +仲 +件 +任 +企 +伊 +伍 +伎 +伏 +伐 +休 +会 +伝 +伯 +估 +伴 +伶 +伸 +伺 +似 +伽 +佃 +但 +位 +低 +住 +佐 +佑 +体 +何 +余 +佚 +佛 +作 +佩 +佳 +併 +佶 +使 +侈 +例 +侍 +侏 +侑 +侘 +供 +依 +侠 +価 +侮 +侯 +侵 +侶 +便 +係 +促 +俄 +俊 +俔 +俗 +俘 +保 +信 +俣 +俤 +修 +俯 +俳 +俵 +俸 +俺 +倉 +個 +倍 +倒 +候 +借 +倣 +値 +倫 +倭 +倶 +倹 +偃 +假 +偈 +偉 +偏 +偐 +偕 +停 +健 +側 +偵 +偶 +偽 +傀 +傅 +傍 +傑 +傘 +備 +催 +傭 +傲 +傳 +債 +傷 +傾 +僊 +働 +像 +僑 +僕 +僚 +僧 +僭 +僮 +儀 +億 +儇 +儒 +儛 +償 +儡 +優 +儲 +儺 +儼 +兀 +允 +元 +兄 +充 +兆 +先 +光 +克 +兌 +免 +兎 +児 +党 +兜 +入 +全 +八 +公 +六 +共 +兵 +其 +具 +典 +兼 +内 +円 +冊 +再 +冑 +冒 +冗 +写 +冠 +冤 +冥 +冨 +冬 +冲 +决 +冶 +冷 +准 +凉 +凋 +凌 +凍 +凛 +凝 +凞 +几 +凡 +処 +凪 +凰 +凱 +凶 +凸 +凹 +出 +函 +刀 +刃 +分 +切 +刈 +刊 +刎 +刑 +列 +初 +判 +別 +利 +刪 +到 +制 +刷 +券 +刹 +刺 +刻 +剃 +則 +削 +剋 +前 +剖 +剛 +剣 +剤 +剥 +剪 +副 +剰 +割 +創 +剽 +劇 +劉 +劔 +力 +功 +加 +劣 +助 +努 +劫 +劭 +励 +労 +効 +劾 +勃 +勅 +勇 +勉 +勒 +動 +勘 +務 +勝 +募 +勢 +勤 +勧 +勲 +勺 +勾 +勿 +匁 +匂 +包 +匏 +化 +北 +匙 +匝 +匠 +匡 +匣 +匯 +匲 +匹 +区 +医 +匿 +十 +千 +升 +午 +卉 +半 +卍 +卑 +卒 +卓 +協 +南 +単 +博 +卜 +占 +卦 +卯 +印 +危 +即 +却 +卵 +卸 +卿 +厄 +厚 +原 +厠 +厨 +厩 +厭 +厳 +去 +参 +又 +叉 +及 +友 +双 +反 +収 +叔 +取 +受 +叙 +叛 +叟 +叡 +叢 +口 +古 +句 +叩 +只 +叫 +召 +可 +台 +叱 +史 +右 +叶 +号 +司 +吃 +各 +合 +吉 +吊 +同 +名 +后 +吏 +吐 +向 +君 +吝 +吟 +吠 +否 +含 +吸 +吹 +吻 +吽 +吾 +呂 +呆 +呈 +呉 +告 +呑 +周 +呪 +呰 +味 +呼 +命 +咀 +咄 +咋 +和 +咒 +咫 +咲 +咳 +咸 +哀 +品 +哇 +哉 +員 +哨 +哩 +哭 +哲 +哺 +唄 +唆 +唇 +唐 +唖 +唯 +唱 +唳 +唸 +唾 +啄 +商 +問 +啓 +啼 +善 +喋 +喚 +喜 +喝 +喧 +喩 +喪 +喫 +喬 +單 +喰 +営 +嗅 +嗇 +嗔 +嗚 +嗜 +嗣 +嘆 +嘉 +嘗 +嘘 +嘩 +嘯 +嘱 +嘲 +嘴 +噂 +噌 +噛 +器 +噴 +噺 +嚆 +嚢 +囀 +囃 +囉 +囚 +四 +回 +因 +団 +困 +囲 +図 +固 +国 +圀 +圃 +國 +圏 +園 +圓 +團 +圜 +土 +圧 +在 +圭 +地 +址 +坂 +均 +坊 +坐 +坑 +坡 +坤 +坦 +坪 +垂 +型 +垢 +垣 +埃 +埋 +城 +埒 +埔 +域 +埠 +埴 +埵 +執 +培 +基 +埼 +堀 +堂 +堅 +堆 +堕 +堤 +堪 +堯 +堰 +報 +場 +堵 +堺 +塀 +塁 +塊 +塑 +塔 +塗 +塘 +塙 +塚 +塞 +塩 +填 +塵 +塾 +境 +墉 +墓 +増 +墜 +墟 +墨 +墳 +墺 +墻 +墾 +壁 +壇 +壊 +壌 +壕 +士 +壬 +壮 +声 +壱 +売 +壷 +壹 +壺 +壽 +変 +夏 +夕 +外 +夙 +多 +夜 +夢 +夥 +大 +天 +太 +夫 +夬 +夭 +央 +失 +夷 +夾 +奄 +奇 +奈 +奉 +奎 +奏 +契 +奔 +奕 +套 +奘 +奠 +奢 +奥 +奨 +奪 +奮 +女 +奴 +奸 +好 +如 +妃 +妄 +妊 +妍 +妓 +妖 +妙 +妥 +妨 +妬 +妲 +妹 +妻 +妾 +姉 +始 +姐 +姓 +委 +姚 +姜 +姞 +姥 +姦 +姨 +姪 +姫 +姶 +姻 +姿 +威 +娑 +娘 +娟 +娠 +娩 +娯 +娼 +婆 +婉 +婚 +婢 +婦 +婬 +婿 +媄 +媒 +媓 +媚 +媛 +媞 +媽 +嫁 +嫄 +嫉 +嫌 +嫐 +嫗 +嫡 +嬉 +嬌 +嬢 +嬪 +嬬 +嬾 +孁 +子 +孔 +字 +存 +孚 +孝 +孟 +季 +孤 +学 +孫 +孵 +學 +宅 +宇 +守 +安 +宋 +完 +宍 +宏 +宕 +宗 +官 +宙 +定 +宛 +宜 +宝 +実 +客 +宣 +室 +宥 +宮 +宰 +害 +宴 +宵 +家 +宸 +容 +宿 +寂 +寄 +寅 +密 +寇 +富 +寒 +寓 +寔 +寛 +寝 +察 +寡 +實 +寧 +審 +寮 +寵 +寶 +寸 +寺 +対 +寿 +封 +専 +射 +将 +尉 +尊 +尋 +對 +導 +小 +少 +尖 +尚 +尤 +尪 +尭 +就 +尹 +尺 +尻 +尼 +尽 +尾 +尿 +局 +居 +屈 +届 +屋 +屍 +屎 +屏 +屑 +屓 +展 +属 +屠 +層 +履 +屯 +山 +岐 +岑 +岡 +岩 +岫 +岬 +岳 +岷 +岸 +峠 +峡 +峨 +峯 +峰 +島 +峻 +崇 +崋 +崎 +崑 +崖 +崗 +崛 +崩 +嵌 +嵐 +嵩 +嵯 +嶂 +嶋 +嶠 +嶺 +嶼 +嶽 +巀 +巌 +巒 +巖 +川 +州 +巡 +巣 +工 +左 +巧 +巨 +巫 +差 +己 +巳 +巴 +巷 +巻 +巽 +巾 +市 +布 +帆 +希 +帖 +帚 +帛 +帝 +帥 +師 +席 +帯 +帰 +帳 +帷 +常 +帽 +幄 +幅 +幇 +幌 +幔 +幕 +幟 +幡 +幢 +幣 +干 +平 +年 +并 +幸 +幹 +幻 +幼 +幽 +幾 +庁 +広 +庄 +庇 +床 +序 +底 +庖 +店 +庚 +府 +度 +座 +庫 +庭 +庵 +庶 +康 +庸 +廂 +廃 +廉 +廊 +廓 +廟 +廠 +廣 +廬 +延 +廷 +建 +廻 +廼 +廿 +弁 +弄 +弉 +弊 +弌 +式 +弐 +弓 +弔 +引 +弖 +弗 +弘 +弛 +弟 +弥 +弦 +弧 +弱 +張 +強 +弼 +弾 +彈 +彊 +彌 +彎 +当 +彗 +彙 +彝 +形 +彦 +彩 +彫 +彬 +彭 +彰 +影 +彷 +役 +彼 +往 +征 +徂 +径 +待 +律 +後 +徐 +徑 +徒 +従 +得 +徠 +御 +徧 +徨 +復 +循 +徭 +微 +徳 +徴 +德 +徹 +徽 +心 +必 +忉 +忌 +忍 +志 +忘 +忙 +応 +忠 +快 +忯 +念 +忻 +忽 +忿 +怒 +怖 +思 +怠 +怡 +急 +性 +怨 +怪 +怯 +恂 +恋 +恐 +恒 +恕 +恣 +恤 +恥 +恨 +恩 +恬 +恭 +息 +恵 +悉 +悌 +悍 +悔 +悟 +悠 +患 +悦 +悩 +悪 +悲 +悼 +情 +惇 +惑 +惚 +惜 +惟 +惠 +惣 +惧 +惨 +惰 +想 +惹 +惺 +愈 +愉 +愍 +意 +愔 +愚 +愛 +感 +愷 +愿 +慈 +態 +慌 +慎 +慕 +慢 +慣 +慧 +慨 +慮 +慰 +慶 +憂 +憎 +憐 +憑 +憙 +憤 +憧 +憩 +憬 +憲 +憶 +憾 +懇 +應 +懌 +懐 +懲 +懸 +懺 +懽 +懿 +戈 +戊 +戌 +戎 +成 +我 +戒 +戔 +或 +戚 +戟 +戦 +截 +戮 +戯 +戴 +戸 +戻 +房 +所 +扁 +扇 +扈 +扉 +手 +才 +打 +払 +托 +扮 +扱 +扶 +批 +承 +技 +抄 +把 +抑 +抓 +投 +抗 +折 +抜 +択 +披 +抱 +抵 +抹 +押 +抽 +担 +拇 +拈 +拉 +拍 +拏 +拐 +拒 +拓 +拘 +拙 +招 +拝 +拠 +拡 +括 +拭 +拳 +拵 +拶 +拾 +拿 +持 +挂 +指 +按 +挑 +挙 +挟 +挨 +振 +挺 +挽 +挿 +捉 +捕 +捗 +捜 +捧 +捨 +据 +捺 +捻 +掃 +掄 +授 +掌 +排 +掖 +掘 +掛 +掟 +採 +探 +掣 +接 +控 +推 +掩 +措 +掬 +掲 +掴 +掻 +掾 +揃 +揄 +揆 +揉 +描 +提 +揖 +揚 +換 +握 +揮 +援 +揶 +揺 +損 +搦 +搬 +搭 +携 +搾 +摂 +摘 +摩 +摸 +摺 +撃 +撒 +撞 +撤 +撥 +撫 +播 +撮 +撰 +撲 +撹 +擁 +操 +擔 +擦 +擬 +擾 +攘 +攝 +攣 +支 +收 +改 +攻 +放 +政 +故 +敏 +救 +敗 +教 +敢 +散 +敦 +敬 +数 +整 +敵 +敷 +斂 +文 +斉 +斎 +斐 +斑 +斗 +料 +斜 +斟 +斤 +斥 +斧 +斬 +断 +斯 +新 +方 +於 +施 +旁 +旅 +旋 +旌 +族 +旗 +旛 +无 +旡 +既 +日 +旦 +旧 +旨 +早 +旬 +旭 +旺 +旻 +昂 +昆 +昇 +昉 +昌 +明 +昏 +易 +昔 +星 +映 +春 +昧 +昨 +昪 +昭 +是 +昵 +昼 +晁 +時 +晃 +晋 +晏 +晒 +晟 +晦 +晧 +晩 +普 +景 +晴 +晶 +智 +暁 +暇 +暈 +暉 +暑 +暖 +暗 +暘 +暢 +暦 +暫 +暮 +暲 +暴 +暹 +暾 +曄 +曇 +曉 +曖 +曙 +曜 +曝 +曠 +曰 +曲 +曳 +更 +書 +曹 +曼 +曽 +曾 +替 +最 +會 +月 +有 +朋 +服 +朏 +朔 +朕 +朗 +望 +朝 +期 +朧 +木 +未 +末 +本 +札 +朱 +朴 +机 +朽 +杁 +杉 +李 +杏 +材 +村 +杓 +杖 +杜 +杞 +束 +条 +杢 +杣 +来 +杭 +杮 +杯 +東 +杲 +杵 +杷 +杼 +松 +板 +枅 +枇 +析 +枓 +枕 +林 +枚 +果 +枝 +枠 +枡 +枢 +枯 +枳 +架 +柄 +柊 +柏 +某 +柑 +染 +柔 +柘 +柚 +柯 +柱 +柳 +柴 +柵 +査 +柾 +柿 +栂 +栃 +栄 +栖 +栗 +校 +株 +栲 +栴 +核 +根 +栻 +格 +栽 +桁 +桂 +桃 +框 +案 +桐 +桑 +桓 +桔 +桜 +桝 +桟 +桧 +桴 +桶 +桾 +梁 +梅 +梆 +梓 +梔 +梗 +梛 +條 +梟 +梢 +梧 +梨 +械 +梱 +梲 +梵 +梶 +棄 +棋 +棒 +棗 +棘 +棚 +棟 +棠 +森 +棲 +棹 +棺 +椀 +椅 +椋 +植 +椎 +椏 +椒 +椙 +検 +椥 +椹 +椿 +楊 +楓 +楕 +楚 +楞 +楠 +楡 +楢 +楨 +楪 +楫 +業 +楮 +楯 +楳 +極 +楷 +楼 +楽 +概 +榊 +榎 +榕 +榛 +榜 +榮 +榱 +榴 +槃 +槇 +槊 +構 +槌 +槍 +槐 +様 +槙 +槻 +槽 +槿 +樂 +樋 +樓 +樗 +標 +樟 +模 +権 +横 +樫 +樵 +樹 +樺 +樽 +橇 +橋 +橘 +機 +橿 +檀 +檄 +檎 +檐 +檗 +檜 +檣 +檥 +檬 +檮 +檸 +檻 +櫃 +櫓 +櫛 +櫟 +櫨 +櫻 +欄 +欅 +欠 +次 +欣 +欧 +欲 +欺 +欽 +款 +歌 +歎 +歓 +止 +正 +此 +武 +歩 +歪 +歯 +歳 +歴 +死 +殆 +殉 +殊 +残 +殖 +殯 +殴 +段 +殷 +殺 +殻 +殿 +毀 +毅 +母 +毎 +毒 +比 +毘 +毛 +毫 +毬 +氈 +氏 +民 +気 +水 +氷 +永 +氾 +汀 +汁 +求 +汎 +汐 +汗 +汚 +汝 +江 +池 +汪 +汰 +汲 +決 +汽 +沂 +沃 +沅 +沆 +沈 +沌 +沐 +沓 +沖 +沙 +没 +沢 +沱 +河 +沸 +油 +治 +沼 +沽 +沿 +況 +泉 +泊 +泌 +法 +泗 +泡 +波 +泣 +泥 +注 +泯 +泰 +泳 +洋 +洒 +洗 +洛 +洞 +津 +洩 +洪 +洲 +洸 +洹 +活 +洽 +派 +流 +浄 +浅 +浙 +浚 +浜 +浣 +浦 +浩 +浪 +浮 +浴 +海 +浸 +涅 +消 +涌 +涙 +涛 +涯 +液 +涵 +涼 +淀 +淄 +淆 +淇 +淋 +淑 +淘 +淡 +淤 +淨 +淫 +深 +淳 +淵 +混 +淹 +添 +清 +済 +渉 +渋 +渓 +渕 +渚 +減 +渟 +渠 +渡 +渤 +渥 +渦 +温 +渫 +測 +港 +游 +渾 +湊 +湖 +湘 +湛 +湧 +湫 +湯 +湾 +湿 +満 +源 +準 +溜 +溝 +溢 +溥 +溪 +溶 +溺 +滄 +滅 +滋 +滌 +滑 +滕 +滝 +滞 +滴 +滸 +滹 +滿 +漁 +漂 +漆 +漉 +漏 +漑 +演 +漕 +漠 +漢 +漣 +漫 +漬 +漱 +漸 +漿 +潅 +潔 +潙 +潜 +潟 +潤 +潭 +潮 +潰 +潴 +澁 +澂 +澄 +澎 +澗 +澤 +澪 +澱 +澳 +激 +濁 +濃 +濟 +濠 +濡 +濤 +濫 +濯 +濱 +濾 +瀉 +瀋 +瀑 +瀕 +瀞 +瀟 +瀧 +瀬 +瀾 +灌 +灑 +灘 +火 +灯 +灰 +灸 +災 +炉 +炊 +炎 +炒 +炭 +炮 +炷 +点 +為 +烈 +烏 +烙 +烝 +烹 +焔 +焙 +焚 +無 +焦 +然 +焼 +煇 +煉 +煌 +煎 +煕 +煙 +煤 +煥 +照 +煩 +煬 +煮 +煽 +熈 +熊 +熙 +熟 +熨 +熱 +熹 +熾 +燃 +燈 +燎 +燔 +燕 +燗 +燥 +燭 +燻 +爆 +爐 +爪 +爬 +爲 +爵 +父 +爺 +爼 +爽 +爾 +片 +版 +牌 +牒 +牘 +牙 +牛 +牝 +牟 +牡 +牢 +牧 +物 +牲 +特 +牽 +犂 +犠 +犬 +犯 +状 +狂 +狄 +狐 +狗 +狙 +狛 +狡 +狩 +独 +狭 +狷 +狸 +狼 +猊 +猛 +猟 +猥 +猨 +猩 +猪 +猫 +献 +猴 +猶 +猷 +猾 +猿 +獄 +獅 +獏 +獣 +獲 +玄 +玅 +率 +玉 +王 +玖 +玩 +玲 +珀 +珂 +珈 +珉 +珊 +珍 +珎 +珞 +珠 +珣 +珥 +珪 +班 +現 +球 +理 +琉 +琢 +琥 +琦 +琮 +琲 +琳 +琴 +琵 +琶 +瑁 +瑋 +瑙 +瑚 +瑛 +瑜 +瑞 +瑠 +瑤 +瑩 +瑪 +瑳 +瑾 +璃 +璋 +璜 +璞 +璧 +璨 +環 +璵 +璽 +璿 +瓊 +瓔 +瓜 +瓢 +瓦 +瓶 +甍 +甑 +甕 +甘 +甚 +甞 +生 +産 +甥 +用 +甫 +田 +由 +甲 +申 +男 +町 +画 +界 +畏 +畑 +畔 +留 +畜 +畝 +畠 +畢 +略 +番 +異 +畳 +當 +畷 +畸 +畺 +畿 +疆 +疇 +疋 +疎 +疏 +疑 +疫 +疱 +疲 +疹 +疼 +疾 +病 +症 +痒 +痔 +痕 +痘 +痙 +痛 +痢 +痩 +痴 +痺 +瘍 +瘡 +瘧 +療 +癇 +癌 +癒 +癖 +癡 +癪 +発 +登 +白 +百 +的 +皆 +皇 +皋 +皐 +皓 +皮 +皺 +皿 +盂 +盃 +盆 +盈 +益 +盒 +盗 +盛 +盞 +盟 +盡 +監 +盤 +盥 +盧 +目 +盲 +直 +相 +盾 +省 +眉 +看 +県 +眞 +真 +眠 +眷 +眺 +眼 +着 +睡 +督 +睦 +睨 +睿 +瞋 +瞑 +瞞 +瞬 +瞭 +瞰 +瞳 +瞻 +瞼 +瞿 +矍 +矛 +矜 +矢 +知 +矧 +矩 +短 +矮 +矯 +石 +砂 +砌 +研 +砕 +砥 +砦 +砧 +砲 +破 +砺 +硝 +硫 +硬 +硯 +碁 +碇 +碌 +碑 +碓 +碕 +碗 +碣 +碧 +碩 +確 +碾 +磁 +磐 +磔 +磧 +磨 +磬 +磯 +礁 +礎 +礒 +礙 +礫 +礬 +示 +礼 +社 +祀 +祁 +祇 +祈 +祉 +祐 +祓 +祕 +祖 +祗 +祚 +祝 +神 +祟 +祠 +祢 +祥 +票 +祭 +祷 +祺 +禁 +禄 +禅 +禊 +禍 +禎 +福 +禔 +禖 +禛 +禦 +禧 +禮 +禰 +禹 +禽 +禿 +秀 +私 +秋 +科 +秒 +秘 +租 +秤 +秦 +秩 +称 +移 +稀 +程 +税 +稔 +稗 +稙 +稚 +稜 +稠 +種 +稱 +稲 +稷 +稻 +稼 +稽 +稿 +穀 +穂 +穆 +積 +穎 +穏 +穗 +穜 +穢 +穣 +穫 +穴 +究 +空 +突 +窃 +窄 +窒 +窓 +窟 +窠 +窩 +窪 +窮 +窯 +竃 +竄 +竈 +立 +站 +竜 +竝 +竟 +章 +童 +竪 +竭 +端 +竴 +競 +竹 +竺 +竽 +竿 +笄 +笈 +笏 +笑 +笙 +笛 +笞 +笠 +笥 +符 +第 +笹 +筅 +筆 +筇 +筈 +等 +筋 +筌 +筍 +筏 +筐 +筑 +筒 +答 +策 +筝 +筥 +筧 +筬 +筮 +筯 +筰 +筵 +箆 +箇 +箋 +箏 +箒 +箔 +箕 +算 +箙 +箜 +管 +箪 +箭 +箱 +箸 +節 +篁 +範 +篆 +篇 +築 +篋 +篌 +篝 +篠 +篤 +篥 +篦 +篩 +篭 +篳 +篷 +簀 +簒 +簡 +簧 +簪 +簫 +簺 +簾 +簿 +籀 +籃 +籌 +籍 +籐 +籟 +籠 +籤 +籬 +米 +籾 +粂 +粉 +粋 +粒 +粕 +粗 +粘 +粛 +粟 +粥 +粧 +粮 +粳 +精 +糊 +糖 +糜 +糞 +糟 +糠 +糧 +糯 +糸 +糺 +系 +糾 +紀 +約 +紅 +紋 +納 +紐 +純 +紗 +紘 +紙 +級 +紛 +素 +紡 +索 +紫 +紬 +累 +細 +紳 +紵 +紹 +紺 +絁 +終 +絃 +組 +絅 +経 +結 +絖 +絞 +絡 +絣 +給 +統 +絲 +絵 +絶 +絹 +絽 +綏 +經 +継 +続 +綜 +綟 +綬 +維 +綱 +網 +綴 +綸 +綺 +綽 +綾 +綿 +緊 +緋 +総 +緑 +緒 +線 +締 +緥 +編 +緩 +緬 +緯 +練 +緻 +縁 +縄 +縅 +縒 +縛 +縞 +縢 +縣 +縦 +縫 +縮 +縹 +總 +績 +繁 +繊 +繋 +繍 +織 +繕 +繝 +繦 +繧 +繰 +繹 +繼 +纂 +纈 +纏 +纐 +纒 +纛 +缶 +罔 +罠 +罧 +罪 +置 +罰 +署 +罵 +罷 +罹 +羂 +羅 +羆 +羇 +羈 +羊 +羌 +美 +群 +羨 +義 +羯 +羲 +羹 +羽 +翁 +翅 +翌 +習 +翔 +翛 +翠 +翡 +翫 +翰 +翺 +翻 +翼 +耀 +老 +考 +者 +耆 +而 +耐 +耕 +耗 +耨 +耳 +耶 +耽 +聊 +聖 +聘 +聚 +聞 +聟 +聡 +聨 +聯 +聰 +聲 +聴 +職 +聾 +肄 +肆 +肇 +肉 +肋 +肌 +肖 +肘 +肛 +肝 +股 +肢 +肥 +肩 +肪 +肯 +肱 +育 +肴 +肺 +胃 +胆 +背 +胎 +胖 +胚 +胝 +胞 +胡 +胤 +胱 +胴 +胸 +能 +脂 +脅 +脆 +脇 +脈 +脊 +脚 +脛 +脩 +脱 +脳 +腋 +腎 +腐 +腑 +腔 +腕 +腫 +腰 +腱 +腸 +腹 +腺 +腿 +膀 +膏 +膚 +膜 +膝 +膠 +膣 +膨 +膩 +膳 +膵 +膾 +膿 +臂 +臆 +臈 +臍 +臓 +臘 +臚 +臣 +臥 +臨 +自 +臭 +至 +致 +臺 +臼 +舂 +舅 +與 +興 +舌 +舍 +舎 +舒 +舖 +舗 +舘 +舜 +舞 +舟 +舩 +航 +般 +舳 +舶 +船 +艇 +艘 +艦 +艮 +良 +色 +艶 +芋 +芒 +芙 +芝 +芥 +芦 +芬 +芭 +芯 +花 +芳 +芸 +芹 +芻 +芽 +芿 +苅 +苑 +苔 +苗 +苛 +苞 +苡 +若 +苦 +苧 +苫 +英 +苴 +苻 +茂 +范 +茄 +茅 +茎 +茗 +茘 +茜 +茨 +茲 +茵 +茶 +茸 +茹 +草 +荊 +荏 +荒 +荘 +荷 +荻 +荼 +莞 +莪 +莫 +莬 +莱 +莵 +莽 +菅 +菊 +菌 +菓 +菖 +菘 +菜 +菟 +菩 +菫 +華 +菱 +菴 +萄 +萊 +萌 +萍 +萎 +萠 +萩 +萬 +萱 +落 +葉 +著 +葛 +葡 +董 +葦 +葩 +葬 +葭 +葱 +葵 +葺 +蒋 +蒐 +蒔 +蒙 +蒟 +蒡 +蒲 +蒸 +蒻 +蒼 +蒿 +蓄 +蓆 +蓉 +蓋 +蓑 +蓬 +蓮 +蓼 +蔀 +蔑 +蔓 +蔚 +蔡 +蔦 +蔬 +蔭 +蔵 +蔽 +蕃 +蕉 +蕊 +蕎 +蕨 +蕩 +蕪 +蕭 +蕾 +薄 +薇 +薊 +薔 +薗 +薙 +薛 +薦 +薨 +薩 +薪 +薫 +薬 +薭 +薮 +藁 +藉 +藍 +藏 +藐 +藝 +藤 +藩 +藪 +藷 +藹 +藺 +藻 +蘂 +蘆 +蘇 +蘊 +蘭 +虎 +虐 +虔 +虚 +虜 +虞 +號 +虫 +虹 +虻 +蚊 +蚕 +蛇 +蛉 +蛍 +蛎 +蛙 +蛛 +蛟 +蛤 +蛭 +蛮 +蛸 +蛹 +蛾 +蜀 +蜂 +蜃 +蜆 +蜊 +蜘 +蜜 +蜷 +蜻 +蝉 +蝋 +蝕 +蝙 +蝠 +蝦 +蝶 +蝿 +螂 +融 +螣 +螺 +蟄 +蟇 +蟠 +蟷 +蟹 +蟻 +蠢 +蠣 +血 +衆 +行 +衍 +衒 +術 +街 +衙 +衛 +衝 +衞 +衡 +衢 +衣 +表 +衫 +衰 +衵 +衷 +衽 +衾 +衿 +袁 +袈 +袋 +袍 +袒 +袖 +袙 +袞 +袢 +被 +袰 +袱 +袴 +袷 +袿 +裁 +裂 +裃 +装 +裏 +裔 +裕 +裘 +裙 +補 +裟 +裡 +裲 +裳 +裴 +裸 +裹 +製 +裾 +褂 +褄 +複 +褌 +褐 +褒 +褥 +褪 +褶 +褻 +襄 +襖 +襞 +襟 +襠 +襦 +襪 +襲 +襴 +襷 +西 +要 +覆 +覇 +覈 +見 +規 +視 +覗 +覚 +覧 +親 +覲 +観 +覺 +觀 +角 +解 +触 +言 +訂 +計 +討 +訓 +託 +記 +訛 +訟 +訢 +訥 +訪 +設 +許 +訳 +訴 +訶 +診 +註 +証 +詐 +詔 +評 +詛 +詞 +詠 +詢 +詣 +試 +詩 +詫 +詮 +詰 +話 +該 +詳 +誄 +誅 +誇 +誉 +誌 +認 +誓 +誕 +誘 +語 +誠 +誡 +誣 +誤 +誥 +誦 +説 +読 +誰 +課 +誼 +誾 +調 +談 +請 +諌 +諍 +諏 +諒 +論 +諚 +諜 +諟 +諡 +諦 +諧 +諫 +諭 +諮 +諱 +諶 +諷 +諸 +諺 +諾 +謀 +謄 +謌 +謎 +謗 +謙 +謚 +講 +謝 +謡 +謫 +謬 +謹 +證 +識 +譚 +譛 +譜 +警 +譬 +譯 +議 +譲 +譴 +護 +讀 +讃 +讐 +讒 +谷 +谿 +豅 +豆 +豊 +豎 +豐 +豚 +象 +豪 +豫 +豹 +貌 +貝 +貞 +負 +財 +貢 +貧 +貨 +販 +貪 +貫 +責 +貯 +貰 +貴 +買 +貸 +費 +貼 +貿 +賀 +賁 +賂 +賃 +賄 +資 +賈 +賊 +賎 +賑 +賓 +賛 +賜 +賞 +賠 +賢 +賣 +賤 +賦 +質 +賭 +購 +賽 +贄 +贅 +贈 +贋 +贔 +贖 +赤 +赦 +走 +赴 +起 +超 +越 +趙 +趣 +足 +趺 +趾 +跋 +跏 +距 +跡 +跨 +跪 +路 +跳 +践 +踊 +踏 +踐 +踞 +踪 +踵 +蹄 +蹉 +蹊 +蹟 +蹲 +蹴 +躅 +躇 +躊 +躍 +躑 +躙 +躪 +身 +躬 +躯 +躰 +車 +軋 +軌 +軍 +軒 +軟 +転 +軸 +軻 +軽 +軾 +較 +載 +輌 +輔 +輜 +輝 +輦 +輩 +輪 +輯 +輸 +輿 +轄 +轍 +轟 +轢 +辛 +辞 +辟 +辥 +辦 +辨 +辰 +辱 +農 +辺 +辻 +込 +迂 +迅 +迎 +近 +返 +迢 +迦 +迪 +迫 +迭 +述 +迷 +迹 +追 +退 +送 +逃 +逅 +逆 +逍 +透 +逐 +逓 +途 +逕 +逗 +這 +通 +逝 +逞 +速 +造 +逢 +連 +逮 +週 +進 +逸 +逼 +遁 +遂 +遅 +遇 +遊 +運 +遍 +過 +遐 +道 +達 +違 +遙 +遜 +遠 +遡 +遣 +遥 +適 +遭 +遮 +遯 +遵 +遷 +選 +遺 +遼 +避 +邀 +邁 +邂 +邃 +還 +邇 +邉 +邊 +邑 +那 +邦 +邨 +邪 +邯 +邵 +邸 +郁 +郊 +郎 +郡 +郢 +部 +郭 +郴 +郵 +郷 +都 +鄂 +鄙 +鄭 +鄰 +鄲 +酉 +酋 +酌 +配 +酎 +酒 +酔 +酢 +酥 +酪 +酬 +酵 +酷 +酸 +醍 +醐 +醒 +醗 +醜 +醤 +醪 +醵 +醸 +采 +釈 +釉 +釋 +里 +重 +野 +量 +釐 +金 +釘 +釜 +針 +釣 +釧 +釿 +鈍 +鈎 +鈐 +鈔 +鈞 +鈦 +鈴 +鈷 +鈸 +鈿 +鉄 +鉇 +鉉 +鉋 +鉛 +鉢 +鉤 +鉦 +鉱 +鉾 +銀 +銃 +銅 +銈 +銑 +銕 +銘 +銚 +銜 +銭 +鋏 +鋒 +鋤 +鋭 +鋲 +鋳 +鋸 +鋺 +鋼 +錆 +錍 +錐 +錘 +錠 +錣 +錦 +錫 +錬 +錯 +録 +錵 +鍋 +鍍 +鍑 +鍔 +鍛 +鍬 +鍮 +鍵 +鍼 +鍾 +鎌 +鎖 +鎗 +鎚 +鎧 +鎬 +鎮 +鎰 +鎹 +鏃 +鏑 +鏡 +鐃 +鐇 +鐐 +鐔 +鐘 +鐙 +鐚 +鐡 +鐵 +鐸 +鑁 +鑊 +鑑 +鑒 +鑚 +鑠 +鑢 +鑰 +鑵 +鑷 +鑼 +鑽 +鑿 +長 +門 +閃 +閇 +閉 +開 +閏 +閑 +間 +閔 +閘 +関 +閣 +閤 +閥 +閦 +閨 +閬 +閲 +閻 +閼 +閾 +闇 +闍 +闔 +闕 +闘 +關 +闡 +闢 +闥 +阜 +阪 +阮 +阯 +防 +阻 +阿 +陀 +陂 +附 +陌 +降 +限 +陛 +陞 +院 +陣 +除 +陥 +陪 +陬 +陰 +陳 +陵 +陶 +陸 +険 +陽 +隅 +隆 +隈 +隊 +隋 +階 +随 +隔 +際 +障 +隠 +隣 +隧 +隷 +隻 +隼 +雀 +雁 +雄 +雅 +集 +雇 +雉 +雊 +雋 +雌 +雍 +雑 +雖 +雙 +雛 +離 +難 +雨 +雪 +雫 +雰 +雲 +零 +雷 +雹 +電 +需 +震 +霊 +霍 +霖 +霜 +霞 +霧 +霰 +露 +靈 +青 +靖 +静 +靜 +非 +面 +革 +靫 +靭 +靱 +靴 +靺 +鞁 +鞄 +鞆 +鞋 +鞍 +鞏 +鞘 +鞠 +鞨 +鞭 +韋 +韓 +韜 +韮 +音 +韶 +韻 +響 +頁 +頂 +頃 +項 +順 +須 +頌 +預 +頑 +頒 +頓 +領 +頚 +頬 +頭 +頴 +頸 +頻 +頼 +顆 +題 +額 +顎 +顔 +顕 +顗 +願 +顛 +類 +顧 +顯 +風 +飛 +食 +飢 +飩 +飫 +飯 +飲 +飴 +飼 +飽 +飾 +餃 +餅 +餉 +養 +餌 +餐 +餓 +餘 +餝 +餡 +館 +饂 +饅 +饉 +饋 +饌 +饒 +饗 +首 +馗 +香 +馨 +馬 +馳 +馴 +駄 +駅 +駆 +駈 +駐 +駒 +駕 +駝 +駿 +騁 +騎 +騏 +騒 +験 +騙 +騨 +騰 +驕 +驚 +驛 +驢 +骨 +骸 +髄 +體 +高 +髙 +髢 +髪 +髭 +髮 +髷 +髻 +鬘 +鬚 +鬢 +鬨 +鬯 +鬱 +鬼 +魁 +魂 +魄 +魅 +魏 +魔 +魚 +魯 +鮎 +鮑 +鮒 +鮪 +鮫 +鮭 +鮮 +鯉 +鯔 +鯖 +鯛 +鯨 +鯰 +鯱 +鰐 +鰒 +鰭 +鰯 +鰰 +鰹 +鰻 +鱈 +鱒 +鱗 +鱧 +鳥 +鳩 +鳰 +鳳 +鳴 +鳶 +鴈 +鴉 +鴎 +鴛 +鴟 +鴦 +鴨 +鴫 +鴻 +鵄 +鵜 +鵞 +鵡 +鵬 +鵲 +鵺 +鶉 +鶏 +鶯 +鶴 +鷄 +鷙 +鷲 +鷹 +鷺 +鸚 +鸞 +鹸 +鹽 +鹿 +麁 +麒 +麓 +麗 +麝 +麞 +麟 +麦 +麩 +麹 +麺 +麻 +麾 +麿 +黄 +黌 +黍 +黒 +黙 +黛 +黠 +鼈 +鼉 +鼎 +鼓 +鼠 +鼻 +齊 +齋 +齟 +齢 +齬 +龍 +龕 +龗 +! +# +% +& +( +) ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; += +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +R +S +T +U +V +W +X +Z +a +c +d +e +f +h +i +j +k +l +m +n +o +p +r +s +t +u +y +z +~ +・ + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams new file mode 100644 index 0000000000000000000000000000000000000000..e7194ebddb108e1132c8ebc561be9a1962188394 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b08f266ec3f6ea687a089677146cefddee6d6e823abb2aeb66667be0e3707a4b +size 9850998 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams.info b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams.info new file mode 100644 index 0000000000000000000000000000000000000000..d43fe3ecca2d535a4aa80f100168c51fa5e58cf2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdiparams.info @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf79f0b9689b4d6b8094d8bfe2481dc4b4d1699adb622568384695b5f56dc600 +size 21964 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdmodel b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdmodel new file mode 100644 index 0000000000000000000000000000000000000000..f3100f0681391609069386d5bf41f17c07930003 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_PP-OCRv3_rec_infer/inference.pdmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3308556362e7f225b62a3bcac06ce90914082d814c78496fa4b206f4df2b6913 +size 1067029 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..a13899f14dfe3bfc25b34904390c7b1e4ed8674b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/korean_dict.txt @@ -0,0 +1,3688 @@ +! +" +# +$ +% +& +' +* ++ +- +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +\ +] +^ +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +| +} +~ +© +° +² +½ +Á +Ä +Å +Ç +É +Í +Î +Ó +Ö +× +Ü +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +ì +í +î +ï +ð +ñ +ò +ó +ô +õ +ö +ø +ú +û +ü +ý +ā +ă +ą +ć +Č +č +đ +ē +ė +ę +ě +ğ +ī +İ +ı +Ł +ł +ń +ň +ō +ř +Ş +ş +Š +š +ţ +ū +ź +ż +Ž +ž +Ș +ș +Α +Δ +α +λ +φ +Г +О +а +в +л +о +р +с +т +я +​ +’ +“ +” +→ +∇ +∼ +「 +」 +ア +カ +グ +ニ +ラ +ン +ㄱ +ㄴ +ㄷ +ㄸ +ㄹ +ㅂ +ㅅ +ㅆ +ㅇ +ㅈ +ㅊ +ㅋ +ㅌ +ㅎ +ㅓ +ㅜ +ㅣ +一 +丁 +七 +三 +上 +下 +不 +丑 +世 +丘 +丞 +中 +丸 +丹 +主 +乃 +久 +之 +乎 +乘 +九 +也 +乳 +乾 +事 +二 +云 +互 +五 +井 +亞 +亡 +交 +亥 +亨 +享 +京 +亭 +人 +仁 +今 +他 +仙 +代 +令 +以 +仰 +仲 +件 +任 +企 +伊 +伍 +伎 +伏 +伐 +休 +伯 +伴 +伸 +佃 +佈 +位 +低 +住 +佐 +何 +佛 +作 +使 +來 +供 +依 +侯 +侵 +侶 +便 +俗 +保 +俠 +信 +修 +俱 +俳 +倉 +個 +倍 +倒 +候 +借 +値 +倫 +倭 +假 +偈 +偉 +偏 +停 +偶 +傅 +傑 +傳 +傷 +傾 +像 +僞 +僥 +僧 +價 +儀 +儉 +儒 +優 +儼 +兀 +允 +元 +兆 +先 +光 +克 +兒 +入 +內 +全 +八 +公 +六 +共 +兵 +其 +具 +典 +兼 +再 +冠 +冥 +冶 +准 +凞 +凡 +凱 +出 +函 +刀 +分 +刊 +刑 +列 +初 +判 +別 +利 +到 +制 +券 +刺 +刻 +則 +前 +剛 +副 +創 +劃 +劑 +力 +功 +加 +劣 +助 +劫 +勇 +動 +務 +勝 +勢 +勳 +勸 +匈 +化 +北 +匠 +區 +十 +千 +午 +半 +卍 +卑 +卒 +卓 +南 +博 +卜 +占 +卦 +印 +危 +卵 +卷 +卽 +卿 +厄 +原 +厦 +去 +參 +又 +叉 +友 +反 +叔 +受 +口 +古 +句 +可 +台 +史 +右 +司 +各 +合 +吉 +同 +名 +后 +吏 +吐 +君 +吠 +吳 +呂 +告 +周 +味 +呵 +命 +和 +咳 +咸 +咽 +哀 +品 +哨 +哮 +哲 +唐 +唯 +唱 +商 +問 +啼 +善 +喆 +喉 +喜 +喩 +喪 +嘗 +器 +嚴 +囊 +四 +回 +因 +困 +固 +圈 +國 +圍 +園 +圓 +圖 +團 +土 +在 +地 +均 +坊 +坐 +坑 +坵 +型 +垢 +城 +域 +埴 +執 +培 +基 +堂 +堅 +堆 +堤 +堯 +報 +場 +塔 +塚 +塞 +塵 +境 +墜 +墟 +墨 +墳 +墾 +壁 +壇 +壓 +壤 +士 +壬 +壯 +壺 +壽 +夏 +夕 +外 +多 +夜 +夢 +大 +天 +太 +夫 +央 +失 +夷 +奄 +奇 +奉 +奎 +奏 +契 +奔 +奮 +女 +奴 +好 +如 +妄 +妊 +妖 +妙 +始 +姑 +姓 +姚 +姜 +威 +婆 +婚 +婦 +媒 +媚 +子 +孔 +字 +存 +孝 +孟 +季 +孤 +孫 +學 +孺 +宇 +守 +安 +宋 +宗 +官 +宙 +定 +客 +宣 +室 +宮 +害 +家 +容 +寂 +寃 +寄 +寅 +密 +寇 +富 +寒 +寓 +實 +審 +寫 +寬 +寶 +寸 +寺 +封 +將 +專 +尊 +對 +小 +少 +尙 +尹 +尼 +尿 +局 +居 +屈 +屋 +屍 +屎 +屛 +層 +屬 +山 +岐 +岡 +岩 +岳 +岸 +峙 +峰 +島 +峻 +峽 +崇 +崔 +崖 +崩 +嶋 +巖 +川 +州 +巢 +工 +左 +巧 +巨 +巫 +差 +己 +巷 +市 +布 +帝 +師 +帶 +常 +帽 +幕 +干 +平 +年 +幹 +幻 +幼 +幽 +庇 +序 +店 +府 +度 +座 +庫 +庭 +康 +廟 +廣 +廳 +延 +廷 +建 +廻 +弁 +式 +弑 +弓 +引 +弘 +弟 +弱 +張 +强 +弼 +彌 +彛 +形 +彬 +影 +役 +彼 +彿 +往 +征 +待 +律 +後 +徐 +徑 +得 +從 +循 +微 +德 +徹 +心 +必 +忌 +忍 +志 +忠 +思 +怡 +急 +性 +恐 +恒 +恨 +恩 +悅 +悖 +患 +悲 +情 +惑 +惟 +惠 +惡 +想 +惺 +愁 +意 +愚 +愛 +感 +愼 +慈 +態 +慕 +慣 +慧 +慾 +憂 +憤 +憺 +應 +懸 +戎 +成 +我 +戟 +戮 +戰 +戴 +戶 +房 +所 +手 +才 +打 +批 +承 +技 +抄 +把 +抗 +抱 +抽 +拇 +拓 +拘 +拙 +拜 +拾 +持 +指 +捌 +捨 +捿 +授 +掌 +排 +接 +推 +提 +揚 +揭 +援 +損 +搗 +摩 +播 +操 +擒 +擔 +擘 +據 +擧 +攘 +攝 +攬 +支 +改 +攻 +放 +政 +故 +敍 +敎 +救 +敗 +散 +敬 +整 +數 +文 +斗 +料 +斛 +斜 +斧 +斯 +新 +斷 +方 +於 +施 +旋 +族 +旗 +日 +旨 +早 +旱 +昌 +明 +易 +昔 +星 +春 +昧 +昭 +是 +時 +晉 +晋 +晩 +普 +景 +晴 +晶 +智 +暈 +暑 +暗 +暘 +曉 +曜 +曠 +曦 +曰 +曲 +書 +曹 +曼 +曾 +最 +會 +月 +有 +朋 +服 +望 +朝 +期 +木 +未 +末 +本 +朱 +朴 +李 +材 +村 +杖 +杜 +杞 +杭 +杯 +東 +松 +板 +林 +果 +枝 +枯 +枰 +枾 +柏 +柑 +柱 +栗 +校 +栢 +核 +根 +格 +桀 +桂 +案 +桎 +桑 +桓 +桔 +梁 +梏 +梓 +梗 +條 +梨 +梵 +棗 +棟 +森 +植 +椒 +楊 +楓 +楚 +業 +楮 +極 +榮 +槃 +槍 +樂 +樓 +樗 +樣 +樸 +樹 +樺 +樽 +橄 +橋 +橘 +機 +橡 +檀 +檎 +權 +欌 +欖 +次 +欲 +歌 +歐 +止 +正 +此 +步 +武 +歲 +歸 +死 +殖 +段 +殷 +殺 +殿 +毅 +母 +毒 +比 +毛 +氏 +民 +氣 +水 +永 +求 +汎 +汗 +江 +池 +沅 +沒 +沖 +沙 +沛 +河 +油 +治 +沼 +沿 +泉 +泊 +法 +泗 +泡 +波 +注 +泰 +洋 +洙 +洛 +洞 +津 +洲 +活 +派 +流 +浅 +浦 +浮 +浴 +海 +涅 +涇 +消 +涌 +液 +淑 +淡 +淨 +淫 +深 +淳 +淵 +淸 +渠 +渡 +游 +渾 +湖 +湯 +源 +溪 +溫 +溶 +滄 +滅 +滋 +滯 +滿 +漁 +漆 +漢 +漫 +漸 +潑 +潤 +潭 +澄 +澎 +澤 +澳 +澹 +濁 +濕 +濟 +濤 +濯 +瀋 +瀝 +灣 +火 +灰 +灸 +災 +炎 +炭 +点 +烈 +烏 +烙 +焚 +無 +焦 +然 +煌 +煎 +照 +煬 +煮 +熟 +熱 +燁 +燈 +燔 +燕 +燥 +燧 +燮 +爲 +爵 +父 +片 +版 +牌 +牛 +牝 +牟 +牡 +物 +特 +犧 +犬 +狀 +狗 +猥 +猩 +猪 +獨 +獵 +獸 +獻 +玄 +玉 +王 +玲 +珍 +珠 +珪 +班 +現 +球 +理 +琴 +瑞 +瑟 +瑪 +璃 +璋 +璽 +瓜 +瓦 +甑 +甘 +生 +産 +用 +甫 +田 +由 +甲 +申 +男 +界 +畏 +留 +畜 +畢 +略 +番 +異 +畵 +當 +畸 +疏 +疑 +疫 +疹 +疼 +病 +症 +痔 +痛 +痺 +瘀 +瘍 +瘡 +療 +癌 +癖 +登 +發 +白 +百 +的 +皆 +皇 +皮 +盂 +盆 +益 +盛 +盜 +盟 +盡 +盤 +盧 +目 +直 +相 +省 +看 +眞 +眼 +睡 +督 +瞋 +矢 +矣 +知 +短 +石 +破 +碍 +碑 +磁 +磨 +磬 +示 +社 +祇 +祖 +祝 +神 +祥 +祭 +祺 +禁 +禅 +禍 +福 +禦 +禪 +禮 +禹 +禽 +禾 +秀 +私 +秉 +秋 +科 +秘 +秤 +秦 +秩 +移 +稀 +稗 +種 +稱 +稷 +稼 +稽 +穀 +穆 +積 +空 +窮 +竅 +立 +章 +童 +竭 +端 +竹 +笑 +符 +第 +筆 +等 +筍 +答 +策 +箋 +箕 +管 +箱 +節 +篇 +簡 +米 +粉 +粘 +粥 +精 +糖 +糞 +系 +紀 +紂 +約 +紅 +紋 +純 +紙 +級 +素 +索 +紫 +紬 +累 +細 +紳 +終 +組 +結 +絡 +統 +絲 +絶 +絹 +經 +綠 +維 +綱 +網 +綸 +綽 +緖 +線 +緣 +緯 +縣 +縱 +總 +織 +繡 +繩 +繪 +繭 +纂 +續 +罕 +置 +罰 +羅 +羊 +美 +群 +義 +羽 +翁 +習 +翟 +老 +考 +者 +而 +耐 +耕 +耳 +聃 +聖 +聞 +聰 +聲 +職 +肇 +肉 +肖 +肝 +股 +肥 +育 +肺 +胃 +胎 +胚 +胞 +胡 +胥 +能 +脂 +脈 +脚 +脛 +脣 +脩 +脫 +脯 +脾 +腋 +腎 +腫 +腸 +腹 +膜 +膠 +膨 +膽 +臆 +臟 +臣 +臥 +臨 +自 +至 +致 +臺 +臼 +臾 +與 +興 +舊 +舌 +舍 +舒 +舜 +舟 +般 +船 +艦 +良 +色 +芋 +花 +芳 +芽 +苑 +苔 +苕 +苛 +苞 +若 +苦 +英 +茂 +茵 +茶 +茹 +荀 +荇 +草 +荒 +荷 +莊 +莫 +菊 +菌 +菜 +菩 +菫 +華 +菴 +菽 +萊 +萍 +萬 +落 +葉 +著 +葛 +董 +葬 +蒙 +蒜 +蒲 +蒸 +蒿 +蓮 +蔓 +蔘 +蔡 +蔬 +蕃 +蕉 +蕓 +薄 +薑 +薛 +薩 +薪 +薺 +藏 +藝 +藤 +藥 +藩 +藻 +蘆 +蘇 +蘊 +蘚 +蘭 +虎 +處 +虛 +虞 +虹 +蜀 +蜂 +蜜 +蝕 +蝶 +融 +蟬 +蟲 +蠶 +蠻 +血 +衆 +行 +術 +衛 +衡 +衣 +表 +袁 +裔 +裕 +裙 +補 +製 +複 +襄 +西 +要 +見 +視 +親 +覺 +觀 +角 +解 +言 +訂 +訊 +訓 +託 +記 +訣 +設 +診 +註 +評 +詩 +話 +詵 +誅 +誌 +認 +誕 +語 +誠 +誤 +誥 +誦 +說 +調 +談 +諍 +論 +諡 +諫 +諭 +諸 +謙 +講 +謝 +謠 +證 +識 +譚 +譜 +譯 +議 +護 +讀 +變 +谷 +豆 +豊 +豚 +象 +豪 +豫 +貝 +貞 +財 +貧 +貨 +貪 +貫 +貴 +貸 +費 +資 +賊 +賓 +賞 +賢 +賣 +賦 +質 +贍 +赤 +赫 +走 +起 +超 +越 +趙 +趣 +趨 +足 +趾 +跋 +跡 +路 +踏 +蹟 +身 +躬 +車 +軍 +軒 +軟 +載 +輓 +輕 +輪 +輯 +輸 +輻 +輿 +轅 +轉 +辨 +辭 +辯 +辰 +農 +近 +迦 +述 +追 +逆 +透 +逐 +通 +逝 +造 +逢 +連 +進 +逵 +遂 +遊 +運 +遍 +過 +道 +達 +遠 +遡 +適 +遷 +選 +遺 +遽 +還 +邊 +邑 +那 +邪 +郞 +郡 +部 +都 +鄒 +鄕 +鄭 +鄲 +配 +酒 +酸 +醉 +醫 +醯 +釋 +里 +重 +野 +量 +釐 +金 +針 +鈍 +鈴 +鉞 +銀 +銅 +銘 +鋼 +錄 +錢 +錦 +鎭 +鏡 +鐘 +鐵 +鑑 +鑛 +長 +門 +閃 +開 +間 +閔 +閣 +閥 +閭 +閻 +闕 +關 +阪 +防 +阿 +陀 +降 +限 +陝 +院 +陰 +陳 +陵 +陶 +陸 +陽 +隆 +隊 +隋 +階 +際 +障 +隣 +隨 +隱 +隷 +雀 +雄 +雅 +集 +雇 +雌 +雖 +雙 +雜 +離 +難 +雨 +雪 +雲 +電 +霜 +露 +靈 +靑 +靖 +靜 +非 +面 +革 +靴 +鞏 +韓 +音 +韶 +韻 +順 +須 +頊 +頌 +領 +頭 +顔 +願 +顚 +類 +顯 +風 +飛 +食 +飢 +飮 +飯 +飾 +養 +餓 +餘 +首 +香 +馨 +馬 +駒 +騫 +騷 +驕 +骨 +骸 +髓 +體 +高 +髥 +髮 +鬪 +鬱 +鬼 +魏 +魔 +魚 +魯 +鮮 +鰍 +鰐 +鳥 +鳧 +鳳 +鴨 +鵲 +鶴 +鷄 +鷹 +鹽 +鹿 +麗 +麥 +麻 +黃 +黑 +默 +點 +黨 +鼎 +齊 +齋 +齒 +龍 +龜 +가 +각 +간 +갇 +갈 +갉 +감 +갑 +값 +갓 +갔 +강 +갖 +갗 +같 +갚 +갛 +개 +객 +갠 +갤 +갬 +갭 +갯 +갰 +갱 +갸 +걀 +걔 +걘 +거 +걱 +건 +걷 +걸 +검 +겁 +것 +겄 +겅 +겆 +겉 +겊 +겋 +게 +겐 +겔 +겟 +겠 +겡 +겨 +격 +겪 +견 +결 +겸 +겹 +겻 +겼 +경 +곁 +계 +곕 +곗 +고 +곡 +곤 +곧 +골 +곪 +곬 +곯 +곰 +곱 +곳 +공 +곶 +과 +곽 +관 +괄 +괌 +광 +괘 +괜 +괭 +괴 +괸 +굉 +교 +구 +국 +군 +굳 +굴 +굵 +굶 +굼 +굽 +굿 +궁 +궂 +궈 +권 +궐 +궜 +궝 +궤 +귀 +귄 +귈 +귓 +규 +균 +귤 +그 +극 +근 +글 +긁 +금 +급 +긋 +긍 +기 +긴 +길 +김 +깁 +깃 +깅 +깊 +까 +깍 +깎 +깐 +깔 +깜 +깝 +깟 +깡 +깥 +깨 +깬 +깰 +깻 +깼 +깽 +꺄 +꺼 +꺽 +꺾 +껀 +껄 +껌 +껍 +껏 +껐 +껑 +께 +껴 +꼈 +꼍 +꼐 +꼬 +꼭 +꼴 +꼼 +꼽 +꼿 +꽁 +꽂 +꽃 +꽉 +꽝 +꽤 +꽥 +꾀 +꾜 +꾸 +꾹 +꾼 +꿀 +꿇 +꿈 +꿉 +꿋 +꿍 +꿎 +꿔 +꿨 +꿩 +꿰 +꿴 +뀄 +뀌 +뀐 +뀔 +뀜 +뀝 +끄 +끈 +끊 +끌 +끓 +끔 +끕 +끗 +끙 +끝 +끼 +끽 +낀 +낄 +낌 +낍 +낏 +낑 +나 +낙 +낚 +난 +낟 +날 +낡 +남 +납 +낫 +났 +낭 +낮 +낯 +낱 +낳 +내 +낵 +낸 +낼 +냄 +냅 +냇 +냈 +냉 +냐 +냔 +냘 +냥 +너 +넉 +넋 +넌 +널 +넓 +넘 +넙 +넛 +넜 +넝 +넣 +네 +넥 +넨 +넬 +넴 +넵 +넷 +넸 +넹 +녀 +녁 +년 +념 +녔 +녕 +녘 +녜 +노 +녹 +논 +놀 +놈 +놋 +농 +높 +놓 +놔 +놨 +뇌 +뇨 +뇩 +뇽 +누 +눅 +눈 +눌 +눔 +눕 +눗 +눠 +눴 +뉘 +뉜 +뉩 +뉴 +늄 +늅 +늉 +느 +늑 +는 +늘 +늙 +늠 +늡 +능 +늦 +늪 +늬 +니 +닉 +닌 +닐 +님 +닙 +닛 +닝 +닢 +다 +닥 +닦 +단 +닫 +달 +닭 +닮 +닯 +닳 +담 +답 +닷 +당 +닻 +닿 +대 +댁 +댄 +댈 +댐 +댑 +댓 +댔 +댕 +댜 +더 +덕 +덖 +던 +덜 +덟 +덤 +덥 +덧 +덩 +덫 +덮 +데 +덱 +덴 +델 +뎀 +뎃 +뎅 +뎌 +뎠 +뎨 +도 +독 +돈 +돋 +돌 +돔 +돕 +돗 +동 +돛 +돝 +돼 +됐 +되 +된 +될 +됨 +됩 +됴 +두 +둑 +둔 +둘 +둠 +둡 +둣 +둥 +둬 +뒀 +뒤 +뒬 +뒷 +뒹 +듀 +듈 +듐 +드 +득 +든 +듣 +들 +듦 +듬 +듭 +듯 +등 +듸 +디 +딕 +딘 +딛 +딜 +딤 +딥 +딧 +딨 +딩 +딪 +따 +딱 +딴 +딸 +땀 +땄 +땅 +때 +땐 +땔 +땜 +땝 +땠 +땡 +떠 +떡 +떤 +떨 +떫 +떰 +떱 +떳 +떴 +떵 +떻 +떼 +떽 +뗀 +뗄 +뗍 +뗏 +뗐 +뗑 +또 +똑 +똘 +똥 +뙤 +뚜 +뚝 +뚤 +뚫 +뚱 +뛰 +뛴 +뛸 +뜀 +뜁 +뜨 +뜩 +뜬 +뜯 +뜰 +뜸 +뜻 +띄 +띈 +띌 +띔 +띕 +띠 +띤 +띨 +띱 +띵 +라 +락 +란 +랄 +람 +랍 +랏 +랐 +랑 +랒 +랗 +래 +랙 +랜 +랠 +램 +랩 +랫 +랬 +랭 +랴 +략 +량 +러 +럭 +런 +럴 +럼 +럽 +럿 +렀 +렁 +렇 +레 +렉 +렌 +렐 +렘 +렙 +렛 +렝 +려 +력 +련 +렬 +렴 +렵 +렷 +렸 +령 +례 +로 +록 +론 +롤 +롬 +롭 +롯 +롱 +롸 +롹 +뢰 +뢴 +뢸 +룃 +료 +룐 +룡 +루 +룩 +룬 +룰 +룸 +룹 +룻 +룽 +뤄 +뤘 +뤼 +류 +륙 +륜 +률 +륨 +륭 +르 +륵 +른 +를 +름 +릅 +릇 +릉 +릎 +리 +릭 +린 +릴 +림 +립 +릿 +링 +마 +막 +만 +많 +맏 +말 +맑 +맘 +맙 +맛 +망 +맞 +맡 +맣 +매 +맥 +맨 +맬 +맴 +맵 +맷 +맸 +맹 +맺 +먀 +먁 +머 +먹 +먼 +멀 +멈 +멋 +멍 +멎 +메 +멕 +멘 +멜 +멤 +멥 +멧 +멩 +며 +멱 +면 +멸 +몄 +명 +몇 +모 +목 +몫 +몬 +몰 +몸 +몹 +못 +몽 +뫼 +묘 +무 +묵 +묶 +문 +묻 +물 +묽 +뭄 +뭅 +뭇 +뭉 +뭍 +뭏 +뭐 +뭔 +뭘 +뭡 +뭣 +뮈 +뮌 +뮐 +뮤 +뮬 +므 +믈 +믐 +미 +믹 +민 +믿 +밀 +밈 +밉 +밋 +밌 +밍 +및 +밑 +바 +박 +밖 +반 +받 +발 +밝 +밟 +밤 +밥 +밧 +방 +밭 +배 +백 +밴 +밸 +뱀 +뱁 +뱃 +뱄 +뱅 +뱉 +뱍 +뱐 +버 +벅 +번 +벌 +범 +법 +벗 +벙 +벚 +베 +벡 +벤 +벨 +벰 +벱 +벳 +벵 +벼 +벽 +변 +별 +볍 +볏 +볐 +병 +볕 +보 +복 +볶 +본 +볼 +봄 +봅 +봇 +봉 +봐 +봤 +뵈 +뵐 +뵙 +부 +북 +분 +붇 +불 +붉 +붐 +붓 +붕 +붙 +뷔 +뷰 +뷴 +뷸 +브 +븐 +블 +비 +빅 +빈 +빌 +빔 +빕 +빗 +빙 +빚 +빛 +빠 +빡 +빤 +빨 +빳 +빴 +빵 +빻 +빼 +빽 +뺀 +뺄 +뺌 +뺏 +뺐 +뺑 +뺨 +뻐 +뻑 +뻔 +뻗 +뻘 +뻣 +뻤 +뻥 +뻬 +뼈 +뼉 +뼘 +뽀 +뽈 +뽐 +뽑 +뽕 +뾰 +뿌 +뿍 +뿐 +뿔 +뿜 +쁘 +쁜 +쁠 +쁨 +삐 +삔 +삘 +사 +삭 +삯 +산 +살 +삵 +삶 +삼 +삽 +삿 +샀 +상 +샅 +새 +색 +샌 +샐 +샘 +샙 +샛 +샜 +생 +샤 +샨 +샬 +샴 +샵 +샷 +샹 +서 +석 +섞 +선 +섣 +설 +섬 +섭 +섯 +섰 +성 +섶 +세 +섹 +센 +셀 +셈 +셉 +셋 +셌 +셍 +셔 +션 +셜 +셨 +셰 +셴 +셸 +소 +속 +손 +솔 +솜 +솝 +솟 +송 +솥 +쇄 +쇠 +쇤 +쇳 +쇼 +숀 +숄 +숍 +수 +숙 +순 +숟 +술 +숨 +숩 +숫 +숭 +숯 +숱 +숲 +숴 +쉐 +쉘 +쉬 +쉭 +쉰 +쉴 +쉼 +쉽 +슈 +슐 +슘 +슛 +슝 +스 +슥 +슨 +슬 +슭 +슴 +습 +슷 +승 +시 +식 +신 +싣 +실 +싫 +심 +십 +싯 +싱 +싶 +싸 +싹 +싼 +쌀 +쌈 +쌉 +쌌 +쌍 +쌓 +쌔 +쌘 +쌩 +써 +썩 +썬 +썰 +썸 +썹 +썼 +썽 +쎄 +쎈 +쏘 +쏙 +쏜 +쏟 +쏠 +쏭 +쏴 +쐈 +쐐 +쐬 +쑤 +쑥 +쑨 +쒀 +쒔 +쓰 +쓱 +쓴 +쓸 +씀 +씁 +씌 +씨 +씩 +씬 +씰 +씸 +씹 +씻 +씽 +아 +악 +안 +앉 +않 +알 +앎 +앓 +암 +압 +앗 +았 +앙 +앞 +애 +액 +앤 +앨 +앰 +앱 +앳 +앴 +앵 +야 +약 +얀 +얄 +얇 +얌 +얍 +얏 +양 +얕 +얗 +얘 +얜 +어 +억 +언 +얹 +얻 +얼 +얽 +엄 +업 +없 +엇 +었 +엉 +엊 +엌 +엎 +에 +엑 +엔 +엘 +엠 +엡 +엣 +엥 +여 +역 +엮 +연 +열 +엷 +염 +엽 +엾 +엿 +였 +영 +옅 +옆 +옇 +예 +옌 +옐 +옙 +옛 +오 +옥 +온 +올 +옭 +옮 +옳 +옴 +옵 +옷 +옹 +옻 +와 +왁 +완 +왈 +왑 +왓 +왔 +왕 +왜 +왠 +왱 +외 +왼 +요 +욕 +욘 +욜 +욤 +용 +우 +욱 +운 +울 +움 +웁 +웃 +웅 +워 +웍 +원 +월 +웜 +웠 +웡 +웨 +웬 +웰 +웸 +웹 +위 +윅 +윈 +윌 +윔 +윗 +윙 +유 +육 +윤 +율 +윱 +윳 +융 +으 +윽 +은 +을 +읊 +음 +읍 +응 +의 +읜 +읠 +이 +익 +인 +일 +읽 +잃 +임 +입 +잇 +있 +잉 +잊 +잎 +자 +작 +잔 +잖 +잘 +잠 +잡 +잣 +잤 +장 +잦 +재 +잭 +잰 +잴 +잽 +잿 +쟀 +쟁 +쟈 +쟉 +쟤 +저 +적 +전 +절 +젊 +점 +접 +젓 +정 +젖 +제 +젝 +젠 +젤 +젬 +젭 +젯 +져 +젼 +졀 +졌 +졍 +조 +족 +존 +졸 +좀 +좁 +종 +좇 +좋 +좌 +좍 +좽 +죄 +죠 +죤 +주 +죽 +준 +줄 +줌 +줍 +줏 +중 +줘 +줬 +쥐 +쥔 +쥘 +쥬 +쥴 +즈 +즉 +즌 +즐 +즘 +즙 +증 +지 +직 +진 +짇 +질 +짊 +짐 +집 +짓 +징 +짖 +짙 +짚 +짜 +짝 +짠 +짢 +짤 +짧 +짬 +짭 +짰 +짱 +째 +짹 +짼 +쨀 +쨉 +쨋 +쨌 +쨍 +쩄 +쩌 +쩍 +쩐 +쩔 +쩜 +쩝 +쩡 +쩨 +쪄 +쪘 +쪼 +쪽 +쪾 +쫀 +쫄 +쫑 +쫓 +쫙 +쬐 +쭈 +쭉 +쭐 +쭙 +쯔 +쯤 +쯧 +찌 +찍 +찐 +찔 +찜 +찝 +찡 +찢 +찧 +차 +착 +찬 +찮 +찰 +참 +찹 +찻 +찼 +창 +찾 +채 +책 +챈 +챌 +챔 +챕 +챗 +챘 +챙 +챠 +챤 +처 +척 +천 +철 +첨 +첩 +첫 +청 +체 +첵 +첸 +첼 +쳄 +쳇 +쳉 +쳐 +쳔 +쳤 +초 +촉 +촌 +촘 +촛 +총 +촨 +촬 +최 +쵸 +추 +축 +춘 +출 +춤 +춥 +춧 +충 +춰 +췄 +췌 +취 +췬 +츄 +츠 +측 +츨 +츰 +층 +치 +칙 +친 +칠 +칡 +침 +칩 +칫 +칭 +카 +칵 +칸 +칼 +캄 +캅 +캇 +캉 +캐 +캔 +캘 +캠 +캡 +캣 +캤 +캥 +캬 +커 +컥 +컨 +컫 +컬 +컴 +컵 +컷 +컸 +컹 +케 +켄 +켈 +켐 +켓 +켕 +켜 +켠 +켤 +켭 +켯 +켰 +코 +콕 +콘 +콜 +콤 +콥 +콧 +콩 +콰 +콱 +콴 +콸 +쾅 +쾌 +쾡 +쾨 +쾰 +쿄 +쿠 +쿡 +쿤 +쿨 +쿰 +쿵 +쿼 +퀀 +퀄 +퀘 +퀭 +퀴 +퀵 +퀸 +퀼 +큐 +큘 +크 +큰 +클 +큼 +큽 +키 +킥 +킨 +킬 +킴 +킵 +킷 +킹 +타 +탁 +탄 +탈 +탉 +탐 +탑 +탓 +탔 +탕 +태 +택 +탠 +탤 +탬 +탭 +탯 +탰 +탱 +터 +턱 +턴 +털 +텀 +텁 +텃 +텄 +텅 +테 +텍 +텐 +텔 +템 +텝 +텡 +텨 +톈 +토 +톡 +톤 +톨 +톰 +톱 +톳 +통 +퇴 +툇 +투 +툭 +툰 +툴 +툼 +퉁 +퉈 +퉜 +튀 +튄 +튈 +튕 +튜 +튠 +튤 +튬 +트 +특 +튼 +튿 +틀 +틈 +틉 +틋 +틔 +티 +틱 +틴 +틸 +팀 +팁 +팅 +파 +팍 +팎 +판 +팔 +팜 +팝 +팟 +팠 +팡 +팥 +패 +팩 +팬 +팰 +팸 +팻 +팼 +팽 +퍼 +퍽 +펀 +펄 +펌 +펍 +펐 +펑 +페 +펙 +펜 +펠 +펨 +펩 +펫 +펭 +펴 +편 +펼 +폄 +폈 +평 +폐 +포 +폭 +폰 +폴 +폼 +폿 +퐁 +표 +푭 +푸 +푹 +푼 +풀 +품 +풋 +풍 +퓨 +퓬 +퓰 +퓸 +프 +픈 +플 +픔 +픕 +피 +픽 +핀 +필 +핌 +핍 +핏 +핑 +하 +학 +한 +할 +핥 +함 +합 +핫 +항 +해 +핵 +핸 +핼 +햄 +햅 +햇 +했 +행 +햐 +향 +헀 +허 +헉 +헌 +헐 +험 +헙 +헛 +헝 +헤 +헥 +헨 +헬 +헴 +헵 +헷 +헹 +혀 +혁 +현 +혈 +혐 +협 +혓 +혔 +형 +혜 +호 +혹 +혼 +홀 +홈 +홉 +홋 +홍 +홑 +화 +확 +환 +활 +홧 +황 +홰 +홱 +횃 +회 +획 +횝 +횟 +횡 +효 +후 +훅 +훈 +훌 +훑 +훔 +훗 +훤 +훨 +훼 +휄 +휑 +휘 +휙 +휜 +휠 +휩 +휭 +휴 +휼 +흄 +흉 +흐 +흑 +흔 +흘 +흙 +흠 +흡 +흣 +흥 +흩 +희 +흰 +흽 +히 +힉 +힌 +힐 +힘 +힙 +힝 +車 +滑 +金 +奈 +羅 +洛 +卵 +欄 +蘭 +郎 +來 +盧 +老 +魯 +綠 +鹿 +論 +雷 +樓 +縷 +凌 +樂 +不 +參 +葉 +沈 +若 +兩 +凉 +梁 +呂 +女 +廬 +麗 +黎 +曆 +歷 +戀 +蓮 +連 +列 +烈 +裂 +念 +獵 +靈 +領 +例 +禮 +醴 +惡 +尿 +料 +遼 +龍 +暈 +柳 +流 +類 +六 +陸 +倫 +律 +栗 +利 +李 +梨 +理 +離 +燐 +林 +臨 +立 +茶 +切 +宅 + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt new file mode 100644 index 0000000000000000000000000000000000000000..84b885d8352226e49b1d5d791b8f43a663e246aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt @@ -0,0 +1,6623 @@ +' +疗 +绚 +诚 +娇 +溜 +题 +贿 +者 +廖 +更 +纳 +加 +奉 +公 +一 +就 +汴 +计 +与 +路 +房 +原 +妇 +2 +0 +8 +- +7 +其 +> +: +] +, +, +骑 +刈 +全 +消 +昏 +傈 +安 +久 +钟 +嗅 +不 +影 +处 +驽 +蜿 +资 +关 +椤 +地 +瘸 +专 +问 +忖 +票 +嫉 +炎 +韵 +要 +月 +田 +节 +陂 +鄙 +捌 +备 +拳 +伺 +眼 +网 +盎 +大 +傍 +心 +东 +愉 +汇 +蹿 +科 +每 +业 +里 +航 +晏 +字 +平 +录 +先 +1 +3 +彤 +鲶 +产 +稍 +督 +腴 +有 +象 +岳 +注 +绍 +在 +泺 +文 +定 +核 +名 +水 +过 +理 +让 +偷 +率 +等 +这 +发 +” +为 +含 +肥 +酉 +相 +鄱 +七 +编 +猥 +锛 +日 +镀 +蒂 +掰 +倒 +辆 +栾 +栗 +综 +涩 +州 +雌 +滑 +馀 +了 +机 +块 +司 +宰 +甙 +兴 +矽 +抚 +保 +用 +沧 +秩 +如 +收 +息 +滥 +页 +疑 +埠 +! +! +姥 +异 +橹 +钇 +向 +下 +跄 +的 +椴 +沫 +国 +绥 +獠 +报 +开 +民 +蜇 +何 +分 +凇 +长 +讥 +藏 +掏 +施 +羽 +中 +讲 +派 +嘟 +人 +提 +浼 +间 +世 +而 +古 +多 +倪 +唇 +饯 +控 +庚 +首 +赛 +蜓 +味 +断 +制 +觉 +技 +替 +艰 +溢 +潮 +夕 +钺 +外 +摘 +枋 +动 +双 +单 +啮 +户 +枇 +确 +锦 +曜 +杜 +或 +能 +效 +霜 +盒 +然 +侗 +电 +晁 +放 +步 +鹃 +新 +杖 +蜂 +吒 +濂 +瞬 +评 +总 +隍 +对 +独 +合 +也 +是 +府 +青 +天 +诲 +墙 +组 +滴 +级 +邀 +帘 +示 +已 +时 +骸 +仄 +泅 +和 +遨 +店 +雇 +疫 +持 +巍 +踮 +境 +只 +亨 +目 +鉴 +崤 +闲 +体 +泄 +杂 +作 +般 +轰 +化 +解 +迂 +诿 +蛭 +璀 +腾 +告 +版 +服 +省 +师 +小 +规 +程 +线 +海 +办 +引 +二 +桧 +牌 +砺 +洄 +裴 +修 +图 +痫 +胡 +许 +犊 +事 +郛 +基 +柴 +呼 +食 +研 +奶 +律 +蛋 +因 +葆 +察 +戏 +褒 +戒 +再 +李 +骁 +工 +貂 +油 +鹅 +章 +啄 +休 +场 +给 +睡 +纷 +豆 +器 +捎 +说 +敏 +学 +会 +浒 +设 +诊 +格 +廓 +查 +来 +霓 +室 +溆 +¢ +诡 +寥 +焕 +舜 +柒 +狐 +回 +戟 +砾 +厄 +实 +翩 +尿 +五 +入 +径 +惭 +喹 +股 +宇 +篝 +| +; +美 +期 +云 +九 +祺 +扮 +靠 +锝 +槌 +系 +企 +酰 +阊 +暂 +蚕 +忻 +豁 +本 +羹 +执 +条 +钦 +H +獒 +限 +进 +季 +楦 +于 +芘 +玖 +铋 +茯 +未 +答 +粘 +括 +样 +精 +欠 +矢 +甥 +帷 +嵩 +扣 +令 +仔 +风 +皈 +行 +支 +部 +蓉 +刮 +站 +蜡 +救 +钊 +汗 +松 +嫌 +成 +可 +. +鹤 +院 +从 +交 +政 +怕 +活 +调 +球 +局 +验 +髌 +第 +韫 +谗 +串 +到 +圆 +年 +米 +/ +* +友 +忿 +检 +区 +看 +自 +敢 +刃 +个 +兹 +弄 +流 +留 +同 +没 +齿 +星 +聆 +轼 +湖 +什 +三 +建 +蛔 +儿 +椋 +汕 +震 +颧 +鲤 +跟 +力 +情 +璺 +铨 +陪 +务 +指 +族 +训 +滦 +鄣 +濮 +扒 +商 +箱 +十 +召 +慷 +辗 +所 +莞 +管 +护 +臭 +横 +硒 +嗓 +接 +侦 +六 +露 +党 +馋 +驾 +剖 +高 +侬 +妪 +幂 +猗 +绺 +骐 +央 +酐 +孝 +筝 +课 +徇 +缰 +门 +男 +西 +项 +句 +谙 +瞒 +秃 +篇 +教 +碲 +罚 +声 +呐 +景 +前 +富 +嘴 +鳌 +稀 +免 +朋 +啬 +睐 +去 +赈 +鱼 +住 +肩 +愕 +速 +旁 +波 +厅 +健 +茼 +厥 +鲟 +谅 +投 +攸 +炔 +数 +方 +击 +呋 +谈 +绩 +别 +愫 +僚 +躬 +鹧 +胪 +炳 +招 +喇 +膨 +泵 +蹦 +毛 +结 +5 +4 +谱 +识 +陕 +粽 +婚 +拟 +构 +且 +搜 +任 +潘 +比 +郢 +妨 +醪 +陀 +桔 +碘 +扎 +选 +哈 +骷 +楷 +亿 +明 +缆 +脯 +监 +睫 +逻 +婵 +共 +赴 +淝 +凡 +惦 +及 +达 +揖 +谩 +澹 +减 +焰 +蛹 +番 +祁 +柏 +员 +禄 +怡 +峤 +龙 +白 +叽 +生 +闯 +起 +细 +装 +谕 +竟 +聚 +钙 +上 +导 +渊 +按 +艾 +辘 +挡 +耒 +盹 +饪 +臀 +记 +邮 +蕙 +受 +各 +医 +搂 +普 +滇 +朗 +茸 +带 +翻 +酚 +( +光 +堤 +墟 +蔷 +万 +幻 +〓 +瑙 +辈 +昧 +盏 +亘 +蛀 +吉 +铰 +请 +子 +假 +闻 +税 +井 +诩 +哨 +嫂 +好 +面 +琐 +校 +馊 +鬣 +缂 +营 +访 +炖 +占 +农 +缀 +否 +经 +钚 +棵 +趟 +张 +亟 +吏 +茶 +谨 +捻 +论 +迸 +堂 +玉 +信 +吧 +瞠 +乡 +姬 +寺 +咬 +溏 +苄 +皿 +意 +赉 +宝 +尔 +钰 +艺 +特 +唳 +踉 +都 +荣 +倚 +登 +荐 +丧 +奇 +涵 +批 +炭 +近 +符 +傩 +感 +道 +着 +菊 +虹 +仲 +众 +懈 +濯 +颞 +眺 +南 +释 +北 +缝 +标 +既 +茗 +整 +撼 +迤 +贲 +挎 +耱 +拒 +某 +妍 +卫 +哇 +英 +矶 +藩 +治 +他 +元 +领 +膜 +遮 +穗 +蛾 +飞 +荒 +棺 +劫 +么 +市 +火 +温 +拈 +棚 +洼 +转 +果 +奕 +卸 +迪 +伸 +泳 +斗 +邡 +侄 +涨 +屯 +萋 +胭 +氡 +崮 +枞 +惧 +冒 +彩 +斜 +手 +豚 +随 +旭 +淑 +妞 +形 +菌 +吲 +沱 +争 +驯 +歹 +挟 +兆 +柱 +传 +至 +包 +内 +响 +临 +红 +功 +弩 +衡 +寂 +禁 +老 +棍 +耆 +渍 +织 +害 +氵 +渑 +布 +载 +靥 +嗬 +虽 +苹 +咨 +娄 +库 +雉 +榜 +帜 +嘲 +套 +瑚 +亲 +簸 +欧 +边 +6 +腿 +旮 +抛 +吹 +瞳 +得 +镓 +梗 +厨 +继 +漾 +愣 +憨 +士 +策 +窑 +抑 +躯 +襟 +脏 +参 +贸 +言 +干 +绸 +鳄 +穷 +藜 +音 +折 +详 +) +举 +悍 +甸 +癌 +黎 +谴 +死 +罩 +迁 +寒 +驷 +袖 +媒 +蒋 +掘 +模 +纠 +恣 +观 +祖 +蛆 +碍 +位 +稿 +主 +澧 +跌 +筏 +京 +锏 +帝 +贴 +证 +糠 +才 +黄 +鲸 +略 +炯 +饱 +四 +出 +园 +犀 +牧 +容 +汉 +杆 +浈 +汰 +瑷 +造 +虫 +瘩 +怪 +驴 +济 +应 +花 +沣 +谔 +夙 +旅 +价 +矿 +以 +考 +s +u +呦 +晒 +巡 +茅 +准 +肟 +瓴 +詹 +仟 +褂 +译 +桌 +混 +宁 +怦 +郑 +抿 +些 +余 +鄂 +饴 +攒 +珑 +群 +阖 +岔 +琨 +藓 +预 +环 +洮 +岌 +宀 +杲 +瀵 +最 +常 +囡 +周 +踊 +女 +鼓 +袭 +喉 +简 +范 +薯 +遐 +疏 +粱 +黜 +禧 +法 +箔 +斤 +遥 +汝 +奥 +直 +贞 +撑 +置 +绱 +集 +她 +馅 +逗 +钧 +橱 +魉 +[ +恙 +躁 +唤 +9 +旺 +膘 +待 +脾 +惫 +购 +吗 +依 +盲 +度 +瘿 +蠖 +俾 +之 +镗 +拇 +鲵 +厝 +簧 +续 +款 +展 +啃 +表 +剔 +品 +钻 +腭 +损 +清 +锶 +统 +涌 +寸 +滨 +贪 +链 +吠 +冈 +伎 +迥 +咏 +吁 +览 +防 +迅 +失 +汾 +阔 +逵 +绀 +蔑 +列 +川 +凭 +努 +熨 +揪 +利 +俱 +绉 +抢 +鸨 +我 +即 +责 +膦 +易 +毓 +鹊 +刹 +玷 +岿 +空 +嘞 +绊 +排 +术 +估 +锷 +违 +们 +苟 +铜 +播 +肘 +件 +烫 +审 +鲂 +广 +像 +铌 +惰 +铟 +巳 +胍 +鲍 +康 +憧 +色 +恢 +想 +拷 +尤 +疳 +知 +S +Y +F +D +A +峄 +裕 +帮 +握 +搔 +氐 +氘 +难 +墒 +沮 +雨 +叁 +缥 +悴 +藐 +湫 +娟 +苑 +稠 +颛 +簇 +后 +阕 +闭 +蕤 +缚 +怎 +佞 +码 +嘤 +蔡 +痊 +舱 +螯 +帕 +赫 +昵 +升 +烬 +岫 +、 +疵 +蜻 +髁 +蕨 +隶 +烛 +械 +丑 +盂 +梁 +强 +鲛 +由 +拘 +揉 +劭 +龟 +撤 +钩 +呕 +孛 +费 +妻 +漂 +求 +阑 +崖 +秤 +甘 +通 +深 +补 +赃 +坎 +床 +啪 +承 +吼 +量 +暇 +钼 +烨 +阂 +擎 +脱 +逮 +称 +P +神 +属 +矗 +华 +届 +狍 +葑 +汹 +育 +患 +窒 +蛰 +佼 +静 +槎 +运 +鳗 +庆 +逝 +曼 +疱 +克 +代 +官 +此 +麸 +耧 +蚌 +晟 +例 +础 +榛 +副 +测 +唰 +缢 +迹 +灬 +霁 +身 +岁 +赭 +扛 +又 +菡 +乜 +雾 +板 +读 +陷 +徉 +贯 +郁 +虑 +变 +钓 +菜 +圾 +现 +琢 +式 +乐 +维 +渔 +浜 +左 +吾 +脑 +钡 +警 +T +啵 +拴 +偌 +漱 +湿 +硕 +止 +骼 +魄 +积 +燥 +联 +踢 +玛 +则 +窿 +见 +振 +畿 +送 +班 +钽 +您 +赵 +刨 +印 +讨 +踝 +籍 +谡 +舌 +崧 +汽 +蔽 +沪 +酥 +绒 +怖 +财 +帖 +肱 +私 +莎 +勋 +羔 +霸 +励 +哼 +帐 +将 +帅 +渠 +纪 +婴 +娩 +岭 +厘 +滕 +吻 +伤 +坝 +冠 +戊 +隆 +瘁 +介 +涧 +物 +黍 +并 +姗 +奢 +蹑 +掣 +垸 +锴 +命 +箍 +捉 +病 +辖 +琰 +眭 +迩 +艘 +绌 +繁 +寅 +若 +毋 +思 +诉 +类 +诈 +燮 +轲 +酮 +狂 +重 +反 +职 +筱 +县 +委 +磕 +绣 +奖 +晋 +濉 +志 +徽 +肠 +呈 +獐 +坻 +口 +片 +碰 +几 +村 +柿 +劳 +料 +获 +亩 +惕 +晕 +厌 +号 +罢 +池 +正 +鏖 +煨 +家 +棕 +复 +尝 +懋 +蜥 +锅 +岛 +扰 +队 +坠 +瘾 +钬 +@ +卧 +疣 +镇 +譬 +冰 +彷 +频 +黯 +据 +垄 +采 +八 +缪 +瘫 +型 +熹 +砰 +楠 +襁 +箐 +但 +嘶 +绳 +啤 +拍 +盥 +穆 +傲 +洗 +盯 +塘 +怔 +筛 +丿 +台 +恒 +喂 +葛 +永 +¥ +烟 +酒 +桦 +书 +砂 +蚝 +缉 +态 +瀚 +袄 +圳 +轻 +蛛 +超 +榧 +遛 +姒 +奘 +铮 +右 +荽 +望 +偻 +卡 +丶 +氰 +附 +做 +革 +索 +戚 +坨 +桷 +唁 +垅 +榻 +岐 +偎 +坛 +莨 +山 +殊 +微 +骇 +陈 +爨 +推 +嗝 +驹 +澡 +藁 +呤 +卤 +嘻 +糅 +逛 +侵 +郓 +酌 +德 +摇 +※ +鬃 +被 +慨 +殡 +羸 +昌 +泡 +戛 +鞋 +河 +宪 +沿 +玲 +鲨 +翅 +哽 +源 +铅 +语 +照 +邯 +址 +荃 +佬 +顺 +鸳 +町 +霭 +睾 +瓢 +夸 +椁 +晓 +酿 +痈 +咔 +侏 +券 +噎 +湍 +签 +嚷 +离 +午 +尚 +社 +锤 +背 +孟 +使 +浪 +缦 +潍 +鞅 +军 +姹 +驶 +笑 +鳟 +鲁 +》 +孽 +钜 +绿 +洱 +礴 +焯 +椰 +颖 +囔 +乌 +孔 +巴 +互 +性 +椽 +哞 +聘 +昨 +早 +暮 +胶 +炀 +隧 +低 +彗 +昝 +铁 +呓 +氽 +藉 +喔 +癖 +瑗 +姨 +权 +胱 +韦 +堑 +蜜 +酋 +楝 +砝 +毁 +靓 +歙 +锲 +究 +屋 +喳 +骨 +辨 +碑 +武 +鸠 +宫 +辜 +烊 +适 +坡 +殃 +培 +佩 +供 +走 +蜈 +迟 +翼 +况 +姣 +凛 +浔 +吃 +飘 +债 +犟 +金 +促 +苛 +崇 +坂 +莳 +畔 +绂 +兵 +蠕 +斋 +根 +砍 +亢 +欢 +恬 +崔 +剁 +餐 +榫 +快 +扶 +‖ +濒 +缠 +鳜 +当 +彭 +驭 +浦 +篮 +昀 +锆 +秸 +钳 +弋 +娣 +瞑 +夷 +龛 +苫 +拱 +致 +% +嵊 +障 +隐 +弑 +初 +娓 +抉 +汩 +累 +蓖 +" +唬 +助 +苓 +昙 +押 +毙 +破 +城 +郧 +逢 +嚏 +獭 +瞻 +溱 +婿 +赊 +跨 +恼 +璧 +萃 +姻 +貉 +灵 +炉 +密 +氛 +陶 +砸 +谬 +衔 +点 +琛 +沛 +枳 +层 +岱 +诺 +脍 +榈 +埂 +征 +冷 +裁 +打 +蹴 +素 +瘘 +逞 +蛐 +聊 +激 +腱 +萘 +踵 +飒 +蓟 +吆 +取 +咙 +簋 +涓 +矩 +曝 +挺 +揣 +座 +你 +史 +舵 +焱 +尘 +苏 +笈 +脚 +溉 +榨 +诵 +樊 +邓 +焊 +义 +庶 +儋 +蟋 +蒲 +赦 +呷 +杞 +诠 +豪 +还 +试 +颓 +茉 +太 +除 +紫 +逃 +痴 +草 +充 +鳕 +珉 +祗 +墨 +渭 +烩 +蘸 +慕 +璇 +镶 +穴 +嵘 +恶 +骂 +险 +绋 +幕 +碉 +肺 +戳 +刘 +潞 +秣 +纾 +潜 +銮 +洛 +须 +罘 +销 +瘪 +汞 +兮 +屉 +r +林 +厕 +质 +探 +划 +狸 +殚 +善 +煊 +烹 +〒 +锈 +逯 +宸 +辍 +泱 +柚 +袍 +远 +蹋 +嶙 +绝 +峥 +娥 +缍 +雀 +徵 +认 +镱 +谷 += +贩 +勉 +撩 +鄯 +斐 +洋 +非 +祚 +泾 +诒 +饿 +撬 +威 +晷 +搭 +芍 +锥 +笺 +蓦 +候 +琊 +档 +礁 +沼 +卵 +荠 +忑 +朝 +凹 +瑞 +头 +仪 +弧 +孵 +畏 +铆 +突 +衲 +车 +浩 +气 +茂 +悖 +厢 +枕 +酝 +戴 +湾 +邹 +飚 +攘 +锂 +写 +宵 +翁 +岷 +无 +喜 +丈 +挑 +嗟 +绛 +殉 +议 +槽 +具 +醇 +淞 +笃 +郴 +阅 +饼 +底 +壕 +砚 +弈 +询 +缕 +庹 +翟 +零 +筷 +暨 +舟 +闺 +甯 +撞 +麂 +茌 +蔼 +很 +珲 +捕 +棠 +角 +阉 +媛 +娲 +诽 +剿 +尉 +爵 +睬 +韩 +诰 +匣 +危 +糍 +镯 +立 +浏 +阳 +少 +盆 +舔 +擘 +匪 +申 +尬 +铣 +旯 +抖 +赘 +瓯 +居 +ˇ +哮 +游 +锭 +茏 +歌 +坏 +甚 +秒 +舞 +沙 +仗 +劲 +潺 +阿 +燧 +郭 +嗖 +霏 +忠 +材 +奂 +耐 +跺 +砀 +输 +岖 +媳 +氟 +极 +摆 +灿 +今 +扔 +腻 +枝 +奎 +药 +熄 +吨 +话 +q +额 +慑 +嘌 +协 +喀 +壳 +埭 +视 +著 +於 +愧 +陲 +翌 +峁 +颅 +佛 +腹 +聋 +侯 +咎 +叟 +秀 +颇 +存 +较 +罪 +哄 +岗 +扫 +栏 +钾 +羌 +己 +璨 +枭 +霉 +煌 +涸 +衿 +键 +镝 +益 +岢 +奏 +连 +夯 +睿 +冥 +均 +糖 +狞 +蹊 +稻 +爸 +刿 +胥 +煜 +丽 +肿 +璃 +掸 +跚 +灾 +垂 +樾 +濑 +乎 +莲 +窄 +犹 +撮 +战 +馄 +软 +络 +显 +鸢 +胸 +宾 +妲 +恕 +埔 +蝌 +份 +遇 +巧 +瞟 +粒 +恰 +剥 +桡 +博 +讯 +凯 +堇 +阶 +滤 +卖 +斌 +骚 +彬 +兑 +磺 +樱 +舷 +两 +娱 +福 +仃 +差 +找 +桁 +÷ +净 +把 +阴 +污 +戬 +雷 +碓 +蕲 +楚 +罡 +焖 +抽 +妫 +咒 +仑 +闱 +尽 +邑 +菁 +爱 +贷 +沥 +鞑 +牡 +嗉 +崴 +骤 +塌 +嗦 +订 +拮 +滓 +捡 +锻 +次 +坪 +杩 +臃 +箬 +融 +珂 +鹗 +宗 +枚 +降 +鸬 +妯 +阄 +堰 +盐 +毅 +必 +杨 +崃 +俺 +甬 +状 +莘 +货 +耸 +菱 +腼 +铸 +唏 +痤 +孚 +澳 +懒 +溅 +翘 +疙 +杷 +淼 +缙 +骰 +喊 +悉 +砻 +坷 +艇 +赁 +界 +谤 +纣 +宴 +晃 +茹 +归 +饭 +梢 +铡 +街 +抄 +肼 +鬟 +苯 +颂 +撷 +戈 +炒 +咆 +茭 +瘙 +负 +仰 +客 +琉 +铢 +封 +卑 +珥 +椿 +镧 +窨 +鬲 +寿 +御 +袤 +铃 +萎 +砖 +餮 +脒 +裳 +肪 +孕 +嫣 +馗 +嵇 +恳 +氯 +江 +石 +褶 +冢 +祸 +阻 +狈 +羞 +银 +靳 +透 +咳 +叼 +敷 +芷 +啥 +它 +瓤 +兰 +痘 +懊 +逑 +肌 +往 +捺 +坊 +甩 +呻 +〃 +沦 +忘 +膻 +祟 +菅 +剧 +崆 +智 +坯 +臧 +霍 +墅 +攻 +眯 +倘 +拢 +骠 +铐 +庭 +岙 +瓠 +′ +缺 +泥 +迢 +捶 +? +? +郏 +喙 +掷 +沌 +纯 +秘 +种 +听 +绘 +固 +螨 +团 +香 +盗 +妒 +埚 +蓝 +拖 +旱 +荞 +铀 +血 +遏 +汲 +辰 +叩 +拽 +幅 +硬 +惶 +桀 +漠 +措 +泼 +唑 +齐 +肾 +念 +酱 +虚 +屁 +耶 +旗 +砦 +闵 +婉 +馆 +拭 +绅 +韧 +忏 +窝 +醋 +葺 +顾 +辞 +倜 +堆 +辋 +逆 +玟 +贱 +疾 +董 +惘 +倌 +锕 +淘 +嘀 +莽 +俭 +笏 +绑 +鲷 +杈 +择 +蟀 +粥 +嗯 +驰 +逾 +案 +谪 +褓 +胫 +哩 +昕 +颚 +鲢 +绠 +躺 +鹄 +崂 +儒 +俨 +丝 +尕 +泌 +啊 +萸 +彰 +幺 +吟 +骄 +苣 +弦 +脊 +瑰 +〈 +诛 +镁 +析 +闪 +剪 +侧 +哟 +框 +螃 +守 +嬗 +燕 +狭 +铈 +缮 +概 +迳 +痧 +鲲 +俯 +售 +笼 +痣 +扉 +挖 +满 +咋 +援 +邱 +扇 +歪 +便 +玑 +绦 +峡 +蛇 +叨 +〖 +泽 +胃 +斓 +喋 +怂 +坟 +猪 +该 +蚬 +炕 +弥 +赞 +棣 +晔 +娠 +挲 +狡 +创 +疖 +铕 +镭 +稷 +挫 +弭 +啾 +翔 +粉 +履 +苘 +哦 +楼 +秕 +铂 +土 +锣 +瘟 +挣 +栉 +习 +享 +桢 +袅 +磨 +桂 +谦 +延 +坚 +蔚 +噗 +署 +谟 +猬 +钎 +恐 +嬉 +雒 +倦 +衅 +亏 +璩 +睹 +刻 +殿 +王 +算 +雕 +麻 +丘 +柯 +骆 +丸 +塍 +谚 +添 +鲈 +垓 +桎 +蚯 +芥 +予 +飕 +镦 +谌 +窗 +醚 +菀 +亮 +搪 +莺 +蒿 +羁 +足 +J +真 +轶 +悬 +衷 +靛 +翊 +掩 +哒 +炅 +掐 +冼 +妮 +l +谐 +稚 +荆 +擒 +犯 +陵 +虏 +浓 +崽 +刍 +陌 +傻 +孜 +千 +靖 +演 +矜 +钕 +煽 +杰 +酗 +渗 +伞 +栋 +俗 +泫 +戍 +罕 +沾 +疽 +灏 +煦 +芬 +磴 +叱 +阱 +榉 +湃 +蜀 +叉 +醒 +彪 +租 +郡 +篷 +屎 +良 +垢 +隗 +弱 +陨 +峪 +砷 +掴 +颁 +胎 +雯 +绵 +贬 +沐 +撵 +隘 +篙 +暖 +曹 +陡 +栓 +填 +臼 +彦 +瓶 +琪 +潼 +哪 +鸡 +摩 +啦 +俟 +锋 +域 +耻 +蔫 +疯 +纹 +撇 +毒 +绶 +痛 +酯 +忍 +爪 +赳 +歆 +嘹 +辕 +烈 +册 +朴 +钱 +吮 +毯 +癜 +娃 +谀 +邵 +厮 +炽 +璞 +邃 +丐 +追 +词 +瓒 +忆 +轧 +芫 +谯 +喷 +弟 +半 +冕 +裙 +掖 +墉 +绮 +寝 +苔 +势 +顷 +褥 +切 +衮 +君 +佳 +嫒 +蚩 +霞 +佚 +洙 +逊 +镖 +暹 +唛 +& +殒 +顶 +碗 +獗 +轭 +铺 +蛊 +废 +恹 +汨 +崩 +珍 +那 +杵 +曲 +纺 +夏 +薰 +傀 +闳 +淬 +姘 +舀 +拧 +卷 +楂 +恍 +讪 +厩 +寮 +篪 +赓 +乘 +灭 +盅 +鞣 +沟 +慎 +挂 +饺 +鼾 +杳 +树 +缨 +丛 +絮 +娌 +臻 +嗳 +篡 +侩 +述 +衰 +矛 +圈 +蚜 +匕 +筹 +匿 +濞 +晨 +叶 +骋 +郝 +挚 +蚴 +滞 +增 +侍 +描 +瓣 +吖 +嫦 +蟒 +匾 +圣 +赌 +毡 +癞 +恺 +百 +曳 +需 +篓 +肮 +庖 +帏 +卿 +驿 +遗 +蹬 +鬓 +骡 +歉 +芎 +胳 +屐 +禽 +烦 +晌 +寄 +媾 +狄 +翡 +苒 +船 +廉 +终 +痞 +殇 +々 +畦 +饶 +改 +拆 +悻 +萄 +£ +瓿 +乃 +訾 +桅 +匮 +溧 +拥 +纱 +铍 +骗 +蕃 +龋 +缬 +父 +佐 +疚 +栎 +醍 +掳 +蓄 +x +惆 +颜 +鲆 +榆 +〔 +猎 +敌 +暴 +谥 +鲫 +贾 +罗 +玻 +缄 +扦 +芪 +癣 +落 +徒 +臾 +恿 +猩 +托 +邴 +肄 +牵 +春 +陛 +耀 +刊 +拓 +蓓 +邳 +堕 +寇 +枉 +淌 +啡 +湄 +兽 +酷 +萼 +碚 +濠 +萤 +夹 +旬 +戮 +梭 +琥 +椭 +昔 +勺 +蜊 +绐 +晚 +孺 +僵 +宣 +摄 +冽 +旨 +萌 +忙 +蚤 +眉 +噼 +蟑 +付 +契 +瓜 +悼 +颡 +壁 +曾 +窕 +颢 +澎 +仿 +俑 +浑 +嵌 +浣 +乍 +碌 +褪 +乱 +蔟 +隙 +玩 +剐 +葫 +箫 +纲 +围 +伐 +决 +伙 +漩 +瑟 +刑 +肓 +镳 +缓 +蹭 +氨 +皓 +典 +畲 +坍 +铑 +檐 +塑 +洞 +倬 +储 +胴 +淳 +戾 +吐 +灼 +惺 +妙 +毕 +珐 +缈 +虱 +盖 +羰 +鸿 +磅 +谓 +髅 +娴 +苴 +唷 +蚣 +霹 +抨 +贤 +唠 +犬 +誓 +逍 +庠 +逼 +麓 +籼 +釉 +呜 +碧 +秧 +氩 +摔 +霄 +穸 +纨 +辟 +妈 +映 +完 +牛 +缴 +嗷 +炊 +恩 +荔 +茆 +掉 +紊 +慌 +莓 +羟 +阙 +萁 +磐 +另 +蕹 +辱 +鳐 +湮 +吡 +吩 +唐 +睦 +垠 +舒 +圜 +冗 +瞿 +溺 +芾 +囱 +匠 +僳 +汐 +菩 +饬 +漓 +黑 +霰 +浸 +濡 +窥 +毂 +蒡 +兢 +驻 +鹉 +芮 +诙 +迫 +雳 +厂 +忐 +臆 +猴 +鸣 +蚪 +栈 +箕 +羡 +渐 +莆 +捍 +眈 +哓 +趴 +蹼 +埕 +嚣 +骛 +宏 +淄 +斑 +噜 +严 +瑛 +垃 +椎 +诱 +压 +庾 +绞 +焘 +廿 +抡 +迄 +棘 +夫 +纬 +锹 +眨 +瞌 +侠 +脐 +竞 +瀑 +孳 +骧 +遁 +姜 +颦 +荪 +滚 +萦 +伪 +逸 +粳 +爬 +锁 +矣 +役 +趣 +洒 +颔 +诏 +逐 +奸 +甭 +惠 +攀 +蹄 +泛 +尼 +拼 +阮 +鹰 +亚 +颈 +惑 +勒 +〉 +际 +肛 +爷 +刚 +钨 +丰 +养 +冶 +鲽 +辉 +蔻 +画 +覆 +皴 +妊 +麦 +返 +醉 +皂 +擀 +〗 +酶 +凑 +粹 +悟 +诀 +硖 +港 +卜 +z +杀 +涕 +± +舍 +铠 +抵 +弛 +段 +敝 +镐 +奠 +拂 +轴 +跛 +袱 +e +t +沉 +菇 +俎 +薪 +峦 +秭 +蟹 +历 +盟 +菠 +寡 +液 +肢 +喻 +染 +裱 +悱 +抱 +氙 +赤 +捅 +猛 +跑 +氮 +谣 +仁 +尺 +辊 +窍 +烙 +衍 +架 +擦 +倏 +璐 +瑁 +币 +楞 +胖 +夔 +趸 +邛 +惴 +饕 +虔 +蝎 +§ +哉 +贝 +宽 +辫 +炮 +扩 +饲 +籽 +魏 +菟 +锰 +伍 +猝 +末 +琳 +哚 +蛎 +邂 +呀 +姿 +鄞 +却 +歧 +仙 +恸 +椐 +森 +牒 +寤 +袒 +婆 +虢 +雅 +钉 +朵 +贼 +欲 +苞 +寰 +故 +龚 +坭 +嘘 +咫 +礼 +硷 +兀 +睢 +汶 +’ +铲 +烧 +绕 +诃 +浃 +钿 +哺 +柜 +讼 +颊 +璁 +腔 +洽 +咐 +脲 +簌 +筠 +镣 +玮 +鞠 +谁 +兼 +姆 +挥 +梯 +蝴 +谘 +漕 +刷 +躏 +宦 +弼 +b +垌 +劈 +麟 +莉 +揭 +笙 +渎 +仕 +嗤 +仓 +配 +怏 +抬 +错 +泯 +镊 +孰 +猿 +邪 +仍 +秋 +鼬 +壹 +歇 +吵 +炼 +< +尧 +射 +柬 +廷 +胧 +霾 +凳 +隋 +肚 +浮 +梦 +祥 +株 +堵 +退 +L +鹫 +跎 +凶 +毽 +荟 +炫 +栩 +玳 +甜 +沂 +鹿 +顽 +伯 +爹 +赔 +蛴 +徐 +匡 +欣 +狰 +缸 +雹 +蟆 +疤 +默 +沤 +啜 +痂 +衣 +禅 +w +i +h +辽 +葳 +黝 +钗 +停 +沽 +棒 +馨 +颌 +肉 +吴 +硫 +悯 +劾 +娈 +马 +啧 +吊 +悌 +镑 +峭 +帆 +瀣 +涉 +咸 +疸 +滋 +泣 +翦 +拙 +癸 +钥 +蜒 ++ +尾 +庄 +凝 +泉 +婢 +渴 +谊 +乞 +陆 +锉 +糊 +鸦 +淮 +I +B +N +晦 +弗 +乔 +庥 +葡 +尻 +席 +橡 +傣 +渣 +拿 +惩 +麋 +斛 +缃 +矮 +蛏 +岘 +鸽 +姐 +膏 +催 +奔 +镒 +喱 +蠡 +摧 +钯 +胤 +柠 +拐 +璋 +鸥 +卢 +荡 +倾 +^ +_ +珀 +逄 +萧 +塾 +掇 +贮 +笆 +聂 +圃 +冲 +嵬 +M +滔 +笕 +值 +炙 +偶 +蜱 +搐 +梆 +汪 +蔬 +腑 +鸯 +蹇 +敞 +绯 +仨 +祯 +谆 +梧 +糗 +鑫 +啸 +豺 +囹 +猾 +巢 +柄 +瀛 +筑 +踌 +沭 +暗 +苁 +鱿 +蹉 +脂 +蘖 +牢 +热 +木 +吸 +溃 +宠 +序 +泞 +偿 +拜 +檩 +厚 +朐 +毗 +螳 +吞 +媚 +朽 +担 +蝗 +橘 +畴 +祈 +糟 +盱 +隼 +郜 +惜 +珠 +裨 +铵 +焙 +琚 +唯 +咚 +噪 +骊 +丫 +滢 +勤 +棉 +呸 +咣 +淀 +隔 +蕾 +窈 +饨 +挨 +煅 +短 +匙 +粕 +镜 +赣 +撕 +墩 +酬 +馁 +豌 +颐 +抗 +酣 +氓 +佑 +搁 +哭 +递 +耷 +涡 +桃 +贻 +碣 +截 +瘦 +昭 +镌 +蔓 +氚 +甲 +猕 +蕴 +蓬 +散 +拾 +纛 +狼 +猷 +铎 +埋 +旖 +矾 +讳 +囊 +糜 +迈 +粟 +蚂 +紧 +鲳 +瘢 +栽 +稼 +羊 +锄 +斟 +睁 +桥 +瓮 +蹙 +祉 +醺 +鼻 +昱 +剃 +跳 +篱 +跷 +蒜 +翎 +宅 +晖 +嗑 +壑 +峻 +癫 +屏 +狠 +陋 +袜 +途 +憎 +祀 +莹 +滟 +佶 +溥 +臣 +约 +盛 +峰 +磁 +慵 +婪 +拦 +莅 +朕 +鹦 +粲 +裤 +哎 +疡 +嫖 +琵 +窟 +堪 +谛 +嘉 +儡 +鳝 +斩 +郾 +驸 +酊 +妄 +胜 +贺 +徙 +傅 +噌 +钢 +栅 +庇 +恋 +匝 +巯 +邈 +尸 +锚 +粗 +佟 +蛟 +薹 +纵 +蚊 +郅 +绢 +锐 +苗 +俞 +篆 +淆 +膀 +鲜 +煎 +诶 +秽 +寻 +涮 +刺 +怀 +噶 +巨 +褰 +魅 +灶 +灌 +桉 +藕 +谜 +舸 +薄 +搀 +恽 +借 +牯 +痉 +渥 +愿 +亓 +耘 +杠 +柩 +锔 +蚶 +钣 +珈 +喘 +蹒 +幽 +赐 +稗 +晤 +莱 +泔 +扯 +肯 +菪 +裆 +腩 +豉 +疆 +骜 +腐 +倭 +珏 +唔 +粮 +亡 +润 +慰 +伽 +橄 +玄 +誉 +醐 +胆 +龊 +粼 +塬 +陇 +彼 +削 +嗣 +绾 +芽 +妗 +垭 +瘴 +爽 +薏 +寨 +龈 +泠 +弹 +赢 +漪 +猫 +嘧 +涂 +恤 +圭 +茧 +烽 +屑 +痕 +巾 +赖 +荸 +凰 +腮 +畈 +亵 +蹲 +偃 +苇 +澜 +艮 +换 +骺 +烘 +苕 +梓 +颉 +肇 +哗 +悄 +氤 +涠 +葬 +屠 +鹭 +植 +竺 +佯 +诣 +鲇 +瘀 +鲅 +邦 +移 +滁 +冯 +耕 +癔 +戌 +茬 +沁 +巩 +悠 +湘 +洪 +痹 +锟 +循 +谋 +腕 +鳃 +钠 +捞 +焉 +迎 +碱 +伫 +急 +榷 +奈 +邝 +卯 +辄 +皲 +卟 +醛 +畹 +忧 +稳 +雄 +昼 +缩 +阈 +睑 +扌 +耗 +曦 +涅 +捏 +瞧 +邕 +淖 +漉 +铝 +耦 +禹 +湛 +喽 +莼 +琅 +诸 +苎 +纂 +硅 +始 +嗨 +傥 +燃 +臂 +赅 +嘈 +呆 +贵 +屹 +壮 +肋 +亍 +蚀 +卅 +豹 +腆 +邬 +迭 +浊 +} +童 +螂 +捐 +圩 +勐 +触 +寞 +汊 +壤 +荫 +膺 +渌 +芳 +懿 +遴 +螈 +泰 +蓼 +蛤 +茜 +舅 +枫 +朔 +膝 +眙 +避 +梅 +判 +鹜 +璜 +牍 +缅 +垫 +藻 +黔 +侥 +惚 +懂 +踩 +腰 +腈 +札 +丞 +唾 +慈 +顿 +摹 +荻 +琬 +~ +斧 +沈 +滂 +胁 +胀 +幄 +莜 +Z +匀 +鄄 +掌 +绰 +茎 +焚 +赋 +萱 +谑 +汁 +铒 +瞎 +夺 +蜗 +野 +娆 +冀 +弯 +篁 +懵 +灞 +隽 +芡 +脘 +俐 +辩 +芯 +掺 +喏 +膈 +蝈 +觐 +悚 +踹 +蔗 +熠 +鼠 +呵 +抓 +橼 +峨 +畜 +缔 +禾 +崭 +弃 +熊 +摒 +凸 +拗 +穹 +蒙 +抒 +祛 +劝 +闫 +扳 +阵 +醌 +踪 +喵 +侣 +搬 +仅 +荧 +赎 +蝾 +琦 +买 +婧 +瞄 +寓 +皎 +冻 +赝 +箩 +莫 +瞰 +郊 +笫 +姝 +筒 +枪 +遣 +煸 +袋 +舆 +痱 +涛 +母 +〇 +启 +践 +耙 +绲 +盘 +遂 +昊 +搞 +槿 +诬 +纰 +泓 +惨 +檬 +亻 +越 +C +o +憩 +熵 +祷 +钒 +暧 +塔 +阗 +胰 +咄 +娶 +魔 +琶 +钞 +邻 +扬 +杉 +殴 +咽 +弓 +〆 +髻 +】 +吭 +揽 +霆 +拄 +殖 +脆 +彻 +岩 +芝 +勃 +辣 +剌 +钝 +嘎 +甄 +佘 +皖 +伦 +授 +徕 +憔 +挪 +皇 +庞 +稔 +芜 +踏 +溴 +兖 +卒 +擢 +饥 +鳞 +煲 +‰ +账 +颗 +叻 +斯 +捧 +鳍 +琮 +讹 +蛙 +纽 +谭 +酸 +兔 +莒 +睇 +伟 +觑 +羲 +嗜 +宜 +褐 +旎 +辛 +卦 +诘 +筋 +鎏 +溪 +挛 +熔 +阜 +晰 +鳅 +丢 +奚 +灸 +呱 +献 +陉 +黛 +鸪 +甾 +萨 +疮 +拯 +洲 +疹 +辑 +叙 +恻 +谒 +允 +柔 +烂 +氏 +逅 +漆 +拎 +惋 +扈 +湟 +纭 +啕 +掬 +擞 +哥 +忽 +涤 +鸵 +靡 +郗 +瓷 +扁 +廊 +怨 +雏 +钮 +敦 +E +懦 +憋 +汀 +拚 +啉 +腌 +岸 +f +痼 +瞅 +尊 +咀 +眩 +飙 +忌 +仝 +迦 +熬 +毫 +胯 +篑 +茄 +腺 +凄 +舛 +碴 +锵 +诧 +羯 +後 +漏 +汤 +宓 +仞 +蚁 +壶 +谰 +皑 +铄 +棰 +罔 +辅 +晶 +苦 +牟 +闽 +\ +烃 +饮 +聿 +丙 +蛳 +朱 +煤 +涔 +鳖 +犁 +罐 +荼 +砒 +淦 +妤 +黏 +戎 +孑 +婕 +瑾 +戢 +钵 +枣 +捋 +砥 +衩 +狙 +桠 +稣 +阎 +肃 +梏 +诫 +孪 +昶 +婊 +衫 +嗔 +侃 +塞 +蜃 +樵 +峒 +貌 +屿 +欺 +缫 +阐 +栖 +诟 +珞 +荭 +吝 +萍 +嗽 +恂 +啻 +蜴 +磬 +峋 +俸 +豫 +谎 +徊 +镍 +韬 +魇 +晴 +U +囟 +猜 +蛮 +坐 +囿 +伴 +亭 +肝 +佗 +蝠 +妃 +胞 +滩 +榴 +氖 +垩 +苋 +砣 +扪 +馏 +姓 +轩 +厉 +夥 +侈 +禀 +垒 +岑 +赏 +钛 +辐 +痔 +披 +纸 +碳 +“ +坞 +蠓 +挤 +荥 +沅 +悔 +铧 +帼 +蒌 +蝇 +a +p +y +n +g +哀 +浆 +瑶 +凿 +桶 +馈 +皮 +奴 +苜 +佤 +伶 +晗 +铱 +炬 +优 +弊 +氢 +恃 +甫 +攥 +端 +锌 +灰 +稹 +炝 +曙 +邋 +亥 +眶 +碾 +拉 +萝 +绔 +捷 +浍 +腋 +姑 +菖 +凌 +涞 +麽 +锢 +桨 +潢 +绎 +镰 +殆 +锑 +渝 +铬 +困 +绽 +觎 +匈 +糙 +暑 +裹 +鸟 +盔 +肽 +迷 +綦 +『 +亳 +佝 +俘 +钴 +觇 +骥 +仆 +疝 +跪 +婶 +郯 +瀹 +唉 +脖 +踞 +针 +晾 +忒 +扼 +瞩 +叛 +椒 +疟 +嗡 +邗 +肆 +跆 +玫 +忡 +捣 +咧 +唆 +艄 +蘑 +潦 +笛 +阚 +沸 +泻 +掊 +菽 +贫 +斥 +髂 +孢 +镂 +赂 +麝 +鸾 +屡 +衬 +苷 +恪 +叠 +希 +粤 +爻 +喝 +茫 +惬 +郸 +绻 +庸 +撅 +碟 +宄 +妹 +膛 +叮 +饵 +崛 +嗲 +椅 +冤 +搅 +咕 +敛 +尹 +垦 +闷 +蝉 +霎 +勰 +败 +蓑 +泸 +肤 +鹌 +幌 +焦 +浠 +鞍 +刁 +舰 +乙 +竿 +裔 +。 +茵 +函 +伊 +兄 +丨 +娜 +匍 +謇 +莪 +宥 +似 +蝽 +翳 +酪 +翠 +粑 +薇 +祢 +骏 +赠 +叫 +Q +噤 +噻 +竖 +芗 +莠 +潭 +俊 +羿 +耜 +O +郫 +趁 +嗪 +囚 +蹶 +芒 +洁 +笋 +鹑 +敲 +硝 +啶 +堡 +渲 +揩 +』 +携 +宿 +遒 +颍 +扭 +棱 +割 +萜 +蔸 +葵 +琴 +捂 +饰 +衙 +耿 +掠 +募 +岂 +窖 +涟 +蔺 +瘤 +柞 +瞪 +怜 +匹 +距 +楔 +炜 +哆 +秦 +缎 +幼 +茁 +绪 +痨 +恨 +楸 +娅 +瓦 +桩 +雪 +嬴 +伏 +榔 +妥 +铿 +拌 +眠 +雍 +缇 +‘ +卓 +搓 +哌 +觞 +噩 +屈 +哧 +髓 +咦 +巅 +娑 +侑 +淫 +膳 +祝 +勾 +姊 +莴 +胄 +疃 +薛 +蜷 +胛 +巷 +芙 +芋 +熙 +闰 +勿 +窃 +狱 +剩 +钏 +幢 +陟 +铛 +慧 +靴 +耍 +k +浙 +浇 +飨 +惟 +绗 +祜 +澈 +啼 +咪 +磷 +摞 +诅 +郦 +抹 +跃 +壬 +吕 +肖 +琏 +颤 +尴 +剡 +抠 +凋 +赚 +泊 +津 +宕 +殷 +倔 +氲 +漫 +邺 +涎 +怠 +$ +垮 +荬 +遵 +俏 +叹 +噢 +饽 +蜘 +孙 +筵 +疼 +鞭 +羧 +牦 +箭 +潴 +c +眸 +祭 +髯 +啖 +坳 +愁 +芩 +驮 +倡 +巽 +穰 +沃 +胚 +怒 +凤 +槛 +剂 +趵 +嫁 +v +邢 +灯 +鄢 +桐 +睽 +檗 +锯 +槟 +婷 +嵋 +圻 +诗 +蕈 +颠 +遭 +痢 +芸 +怯 +馥 +竭 +锗 +徜 +恭 +遍 +籁 +剑 +嘱 +苡 +龄 +僧 +桑 +潸 +弘 +澶 +楹 +悲 +讫 +愤 +腥 +悸 +谍 +椹 +呢 +桓 +葭 +攫 +阀 +翰 +躲 +敖 +柑 +郎 +笨 +橇 +呃 +魁 +燎 +脓 +葩 +磋 +垛 +玺 +狮 +沓 +砜 +蕊 +锺 +罹 +蕉 +翱 +虐 +闾 +巫 +旦 +茱 +嬷 +枯 +鹏 +贡 +芹 +汛 +矫 +绁 +拣 +禺 +佃 +讣 +舫 +惯 +乳 +趋 +疲 +挽 +岚 +虾 +衾 +蠹 +蹂 +飓 +氦 +铖 +孩 +稞 +瑜 +壅 +掀 +勘 +妓 +畅 +髋 +W +庐 +牲 +蓿 +榕 +练 +垣 +唱 +邸 +菲 +昆 +婺 +穿 +绡 +麒 +蚱 +掂 +愚 +泷 +涪 +漳 +妩 +娉 +榄 +讷 +觅 +旧 +藤 +煮 +呛 +柳 +腓 +叭 +庵 +烷 +阡 +罂 +蜕 +擂 +猖 +咿 +媲 +脉 +【 +沏 +貅 +黠 +熏 +哲 +烁 +坦 +酵 +兜 +× +潇 +撒 +剽 +珩 +圹 +乾 +摸 +樟 +帽 +嗒 +襄 +魂 +轿 +憬 +锡 +〕 +喃 +皆 +咖 +隅 +脸 +残 +泮 +袂 +鹂 +珊 +囤 +捆 +咤 +误 +徨 +闹 +淙 +芊 +淋 +怆 +囗 +拨 +梳 +渤 +R +G +绨 +蚓 +婀 +幡 +狩 +麾 +谢 +唢 +裸 +旌 +伉 +纶 +裂 +驳 +砼 +咛 +澄 +樨 +蹈 +宙 +澍 +倍 +貔 +操 +勇 +蟠 +摈 +砧 +虬 +够 +缁 +悦 +藿 +撸 +艹 +摁 +淹 +豇 +虎 +榭 +ˉ +吱 +d +° +喧 +荀 +踱 +侮 +奋 +偕 +饷 +犍 +惮 +坑 +璎 +徘 +宛 +妆 +袈 +倩 +窦 +昂 +荏 +乖 +K +怅 +撰 +鳙 +牙 +袁 +酞 +X +痿 +琼 +闸 +雁 +趾 +荚 +虻 +涝 +《 +杏 +韭 +偈 +烤 +绫 +鞘 +卉 +症 +遢 +蓥 +诋 +杭 +荨 +匆 +竣 +簪 +辙 +敕 +虞 +丹 +缭 +咩 +黟 +m +淤 +瑕 +咂 +铉 +硼 +茨 +嶂 +痒 +畸 +敬 +涿 +粪 +窘 +熟 +叔 +嫔 +盾 +忱 +裘 +憾 +梵 +赡 +珙 +咯 +娘 +庙 +溯 +胺 +葱 +痪 +摊 +荷 +卞 +乒 +髦 +寐 +铭 +坩 +胗 +枷 +爆 +溟 +嚼 +羚 +砬 +轨 +惊 +挠 +罄 +竽 +菏 +氧 +浅 +楣 +盼 +枢 +炸 +阆 +杯 +谏 +噬 +淇 +渺 +俪 +秆 +墓 +泪 +跻 +砌 +痰 +垡 +渡 +耽 +釜 +讶 +鳎 +煞 +呗 +韶 +舶 +绷 +鹳 +缜 +旷 +铊 +皱 +龌 +檀 +霖 +奄 +槐 +艳 +蝶 +旋 +哝 +赶 +骞 +蚧 +腊 +盈 +丁 +` +蜚 +矸 +蝙 +睨 +嚓 +僻 +鬼 +醴 +夜 +彝 +磊 +笔 +拔 +栀 +糕 +厦 +邰 +纫 +逭 +纤 +眦 +膊 +馍 +躇 +烯 +蘼 +冬 +诤 +暄 +骶 +哑 +瘠 +」 +臊 +丕 +愈 +咱 +螺 +擅 +跋 +搏 +硪 +谄 +笠 +淡 +嘿 +骅 +谧 +鼎 +皋 +姚 +歼 +蠢 +驼 +耳 +胬 +挝 +涯 +狗 +蒽 +孓 +犷 +凉 +芦 +箴 +铤 +孤 +嘛 +坤 +V +茴 +朦 +挞 +尖 +橙 +诞 +搴 +碇 +洵 +浚 +帚 +蜍 +漯 +柘 +嚎 +讽 +芭 +荤 +咻 +祠 +秉 +跖 +埃 +吓 +糯 +眷 +馒 +惹 +娼 +鲑 +嫩 +讴 +轮 +瞥 +靶 +褚 +乏 +缤 +宋 +帧 +删 +驱 +碎 +扑 +俩 +俄 +偏 +涣 +竹 +噱 +皙 +佰 +渚 +唧 +斡 +# +镉 +刀 +崎 +筐 +佣 +夭 +贰 +肴 +峙 +哔 +艿 +匐 +牺 +镛 +缘 +仡 +嫡 +劣 +枸 +堀 +梨 +簿 +鸭 +蒸 +亦 +稽 +浴 +{ +衢 +束 +槲 +j +阁 +揍 +疥 +棋 +潋 +聪 +窜 +乓 +睛 +插 +冉 +阪 +苍 +搽 +「 +蟾 +螟 +幸 +仇 +樽 +撂 +慢 +跤 +幔 +俚 +淅 +覃 +觊 +溶 +妖 +帛 +侨 +曰 +妾 +泗 +· +: +瀘 +風 +Ë +( +) +∶ +紅 +紗 +瑭 +雲 +頭 +鶏 +財 +許 +• +¥ +樂 +焗 +麗 +— +; +滙 +東 +榮 +繪 +興 +… +門 +業 +π +楊 +國 +顧 +é +盤 +寳 +Λ +龍 +鳳 +島 +誌 +緣 +結 +銭 +萬 +勝 +祎 +璟 +優 +歡 +臨 +時 +購 += +★ +藍 +昇 +鐵 +觀 +勅 +農 +聲 +畫 +兿 +術 +發 +劉 +記 +專 +耑 +園 +書 +壴 +種 +Ο +● +褀 +號 +銀 +匯 +敟 +锘 +葉 +橪 +廣 +進 +蒄 +鑽 +阝 +祙 +貢 +鍋 +豊 +夬 +喆 +團 +閣 +開 +燁 +賓 +館 +酡 +沔 +順 ++ +硚 +劵 +饸 +陽 +車 +湓 +復 +萊 +氣 +軒 +華 +堃 +迮 +纟 +戶 +馬 +學 +裡 +電 +嶽 +獨 +マ +シ +サ +ジ +燘 +袪 +環 +❤ +臺 +灣 +専 +賣 +孖 +聖 +攝 +線 +▪ +α +傢 +俬 +夢 +達 +莊 +喬 +貝 +薩 +劍 +羅 +壓 +棛 +饦 +尃 +璈 +囍 +醫 +G +I +A +# +N +鷄 +髙 +嬰 +啓 +約 +隹 +潔 +賴 +藝 +~ +寶 +籣 +麺 +  +嶺 +√ +義 +網 +峩 +長 +∧ +魚 +機 +構 +② +鳯 +偉 +L +B +㙟 +畵 +鴿 +' +詩 +溝 +嚞 +屌 +藔 +佧 +玥 +蘭 +織 +1 +3 +9 +0 +7 +點 +砭 +鴨 +鋪 +銘 +廳 +弍 +‧ +創 +湯 +坶 +℃ +卩 +骝 +& +烜 +荘 +當 +潤 +扞 +係 +懷 +碶 +钅 +蚨 +讠 +☆ +叢 +爲 +埗 +涫 +塗 +→ +楽 +現 +鯨 +愛 +瑪 +鈺 +忄 +悶 +藥 +飾 +樓 +視 +孬 +ㆍ +燚 +苪 +師 +① +丼 +锽 +│ +韓 +標 +è +兒 +閏 +匋 +張 +漢 +Ü +髪 +會 +閑 +檔 +習 +裝 +の +峯 +菘 +輝 +И +雞 +釣 +億 +浐 +K +O +R +8 +H +E +P +T +W +D +S +C +M +F +姌 +饹 +» +晞 +廰 +ä +嵯 +鷹 +負 +飲 +絲 +冚 +楗 +澤 +綫 +區 +❋ +← +質 +靑 +揚 +③ +滬 +統 +産 +協 +﹑ +乸 +畐 +經 +運 +際 +洺 +岽 +為 +粵 +諾 +崋 +豐 +碁 +ɔ +V +2 +6 +齋 +誠 +訂 +´ +勑 +雙 +陳 +無 +í +泩 +媄 +夌 +刂 +i +c +t +o +r +a +嘢 +耄 +燴 +暃 +壽 +媽 +靈 +抻 +體 +唻 +É +冮 +甹 +鎮 +錦 +ʌ +蜛 +蠄 +尓 +駕 +戀 +飬 +逹 +倫 +貴 +極 +Я +Й +寬 +磚 +嶪 +郎 +職 +| +間 +n +d +剎 +伈 +課 +飛 +橋 +瘊 +№ +譜 +骓 +圗 +滘 +縣 +粿 +咅 +養 +濤 +彳 +® +% +Ⅱ +啰 +㴪 +見 +矞 +薬 +糁 +邨 +鲮 +顔 +罱 +З +選 +話 +贏 +氪 +俵 +競 +瑩 +繡 +枱 +β +綉 +á +獅 +爾 +™ +麵 +戋 +淩 +徳 +個 +劇 +場 +務 +簡 +寵 +h +實 +膠 +轱 +圖 +築 +嘣 +樹 +㸃 +營 +耵 +孫 +饃 +鄺 +飯 +麯 +遠 +輸 +坫 +孃 +乚 +閃 +鏢 +㎡ +題 +廠 +關 +↑ +爺 +將 +軍 +連 +篦 +覌 +參 +箸 +- +窠 +棽 +寕 +夀 +爰 +歐 +呙 +閥 +頡 +熱 +雎 +垟 +裟 +凬 +勁 +帑 +馕 +夆 +疌 +枼 +馮 +貨 +蒤 +樸 +彧 +旸 +靜 +龢 +暢 +㐱 +鳥 +珺 +鏡 +灡 +爭 +堷 +廚 +Ó +騰 +診 +┅ +蘇 +褔 +凱 +頂 +豕 +亞 +帥 +嘬 +⊥ +仺 +桖 +複 +饣 +絡 +穂 +顏 +棟 +納 +▏ +濟 +親 +設 +計 +攵 +埌 +烺 +ò +頤 +燦 +蓮 +撻 +節 +講 +濱 +濃 +娽 +洳 +朿 +燈 +鈴 +護 +膚 +铔 +過 +補 +Z +U +5 +4 +坋 +闿 +䖝 +餘 +缐 +铞 +貿 +铪 +桼 +趙 +鍊 +[ +㐂 +垚 +菓 +揸 +捲 +鐘 +滏 +𣇉 +爍 +輪 +燜 +鴻 +鮮 +動 +鹞 +鷗 +丄 +慶 +鉌 +翥 +飮 +腸 +⇋ +漁 +覺 +來 +熘 +昴 +翏 +鲱 +圧 +鄉 +萭 +頔 +爐 +嫚 +г +貭 +類 +聯 +幛 +輕 +訓 +鑒 +夋 +锨 +芃 +珣 +䝉 +扙 +嵐 +銷 +處 +ㄱ +語 +誘 +苝 +歸 +儀 +燒 +楿 +內 +粢 +葒 +奧 +麥 +礻 +滿 +蠔 +穵 +瞭 +態 +鱬 +榞 +硂 +鄭 +黃 +煙 +祐 +奓 +逺 +* +瑄 +獲 +聞 +薦 +讀 +這 +樣 +決 +問 +啟 +們 +執 +説 +轉 +單 +隨 +唘 +帶 +倉 +庫 +還 +贈 +尙 +皺 +■ +餅 +產 +○ +∈ +報 +狀 +楓 +賠 +琯 +嗮 +禮 +` +傳 +> +≤ +嗞 +Φ +≥ +換 +咭 +∣ +↓ +曬 +ε +応 +寫 +″ +終 +様 +純 +費 +療 +聨 +凍 +壐 +郵 +ü +黒 +∫ +製 +塊 +調 +軽 +確 +撃 +級 +馴 +Ⅲ +涇 +繹 +數 +碼 +證 +狒 +処 +劑 +< +晧 +賀 +衆 +] +櫥 +兩 +陰 +絶 +對 +鯉 +憶 +◎ +p +e +Y +蕒 +煖 +頓 +測 +試 +鼽 +僑 +碩 +妝 +帯 +≈ +鐡 +舖 +權 +喫 +倆 +ˋ +該 +悅 +ā +俫 +. +f +s +b +m +k +g +u +j +貼 +淨 +濕 +針 +適 +備 +l +/ +給 +謢 +強 +觸 +衛 +與 +⊙ +$ +緯 +變 +⑴ +⑵ +⑶ +㎏ +殺 +∩ +幚 +─ +價 +▲ +離 +ú +ó +飄 +烏 +関 +閟 +﹝ +﹞ +邏 +輯 +鍵 +驗 +訣 +導 +歷 +屆 +層 +▼ +儱 +錄 +熳 +ē +艦 +吋 +錶 +辧 +飼 +顯 +④ +禦 +販 +気 +対 +枰 +閩 +紀 +幹 +瞓 +貊 +淚 +△ +眞 +墊 +Ω +獻 +褲 +縫 +緑 +亜 +鉅 +餠 +{ +} +◆ +蘆 +薈 +█ +◇ +溫 +彈 +晳 +粧 +犸 +穩 +訊 +崬 +凖 +熥 +П +舊 +條 +紋 +圍 +Ⅳ +筆 +尷 +難 +雜 +錯 +綁 +識 +頰 +鎖 +艶 +□ +殁 +殼 +⑧ +├ +▕ +鵬 +ǐ +ō +ǒ +糝 +綱 +▎ +μ +盜 +饅 +醬 +籤 +蓋 +釀 +鹽 +據 +à +ɡ +辦 +◥ +彐 +┌ +婦 +獸 +鲩 +伱 +ī +蒟 +蒻 +齊 +袆 +腦 +寧 +凈 +妳 +煥 +詢 +偽 +謹 +啫 +鯽 +騷 +鱸 +損 +傷 +鎻 +髮 +買 +冏 +儥 +両 +﹢ +∞ +載 +喰 +z +羙 +悵 +燙 +曉 +員 +組 +徹 +艷 +痠 +鋼 +鼙 +縮 +細 +嚒 +爯 +≠ +維 +" +鱻 +壇 +厍 +帰 +浥 +犇 +薡 +軎 +² +應 +醜 +刪 +緻 +鶴 +賜 +噁 +軌 +尨 +镔 +鷺 +槗 +彌 +葚 +濛 +請 +溇 +緹 +賢 +訪 +獴 +瑅 +資 +縤 +陣 +蕟 +栢 +韻 +祼 +恁 +伢 +謝 +劃 +涑 +總 +衖 +踺 +砋 +凉 +籃 +駿 +苼 +瘋 +昽 +紡 +驊 +腎 +﹗ +響 +杋 +剛 +嚴 +禪 +歓 +槍 +傘 +檸 +檫 +炣 +勢 +鏜 +鎢 +銑 +尐 +減 +奪 +惡 +θ +僮 +婭 +臘 +ū +ì +殻 +鉄 +∑ +蛲 +焼 +緖 +續 +紹 +懮 \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_C_ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_C_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..aa501051e734cb47e1edcb3b6451790bc01ad7fd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_C_ops.py @@ -0,0 +1,22 @@ +# Copyright (c) 2021 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. + +from paddle.fluid import core +from .fluid import framework + +__all__ = [] + +for name in dir(core.eager.ops): + globals()[name] = getattr(core.eager.ops, name) + __all__.append(name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8286c09b10fac0aad7cd3452dc3e74a3be85678 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/__init__.py @@ -0,0 +1,670 @@ +# 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. +try: + from paddle.version import full_version as __version__ + from paddle.version import commit as __git_commit__ + from paddle.cuda_env import * +except ImportError: + import sys + sys.stderr.write('''Warning with import paddle: you should not + import paddle from the source directory; please install paddlepaddle*.whl firstly.''' + ) + +from .batch import batch # noqa: F401 +from .framework import monkey_patch_variable +from .framework import monkey_patch_math_varbase + +monkey_patch_variable() +monkey_patch_math_varbase() + +from .framework import disable_signal_handler # noqa: F401 +from .framework import get_flags # noqa: F401 +from .framework import set_flags # noqa: F401 + +from .framework import disable_static # noqa: F401 +from .framework import enable_static # noqa: F401 +from .framework import in_dynamic_mode # noqa: F401 +from .fluid.dataset import * # noqa: F401 +from .fluid.lazy_init import LazyGuard # noqa: F401 + +from .framework.dtype import iinfo # noqa: F401 +from .framework.dtype import dtype as dtype # noqa: F401 +from .framework.dtype import uint8 # noqa: F401 +from .framework.dtype import int8 # noqa: F401 +from .framework.dtype import int16 # noqa: F401 +from .framework.dtype import int32 # noqa: F401 +from .framework.dtype import int64 # noqa: F401 +from .framework.dtype import float16 # noqa: F401 +from .framework.dtype import float32 # noqa: F401 +from .framework.dtype import float64 # noqa: F401 +from .framework.dtype import bfloat16 # noqa: F401 +from .framework.dtype import bool # noqa: F401 +from .framework.dtype import complex64 # noqa: F401 +from .framework.dtype import complex128 # noqa: F401 +if fluid.framework._in_eager_mode_: + Tensor = framework.core.eager.Tensor +else: + from .framework import VarBase as Tensor # noqa: F401 + +Tensor.__qualname__ = 'Tensor' # noqa: F401 +import paddle.compat # noqa: F401 +import paddle.distributed # noqa: F401 +import paddle.sysconfig # noqa: F401 +import paddle.distribution # noqa: F401 +import paddle.nn # noqa: F401 +import paddle.distributed.fleet # noqa: F401 +import paddle.optimizer # noqa: F401 +import paddle.metric # noqa: F401 +import paddle.regularizer # noqa: F401 +import paddle.incubate # noqa: F401 +import paddle.autograd # noqa: F401 +import paddle.device # noqa: F401 + +import paddle.jit # noqa: F401 +import paddle.amp # noqa: F401 +import paddle.dataset # noqa: F401 +import paddle.inference # noqa: F401 +import paddle.io # noqa: F401 +import paddle.onnx # noqa: F401 +import paddle.reader # noqa: F401 +import paddle.static # noqa: F401 +import paddle.vision # noqa: F401 +import paddle.audio # noqa: F401 +import paddle.geometric # noqa: F401 +import paddle.sparse + +from .tensor.attribute import is_complex # noqa: F401 +from .tensor.attribute import is_integer # noqa: F401 +from .tensor.attribute import rank # noqa: F401 +from .tensor.attribute import shape # noqa: F401 +from .tensor.attribute import real # noqa: F401 +from .tensor.attribute import imag # noqa: F401 +from .tensor.attribute import is_floating_point # noqa: F401 +from .tensor.creation import to_tensor # noqa: F401 +from .tensor.creation import diag # noqa: F401 +from .tensor.creation import diagflat # noqa: F401 +from .tensor.creation import eye # noqa: F401 +from .tensor.creation import linspace # noqa: F401 +from .tensor.creation import logspace # noqa: F401 +from .tensor.creation import ones # noqa: F401 +from .tensor.creation import ones_like # noqa: F401 +from .tensor.creation import zeros # noqa: F401 +from .tensor.creation import zeros_like # noqa: F401 +from .tensor.creation import arange # noqa: F401 +from .tensor.creation import full # noqa: F401 +from .tensor.creation import full_like # noqa: F401 +from .tensor.creation import triu # noqa: F401 +from .tensor.creation import tril # noqa: F401 +from .tensor.creation import meshgrid # noqa: F401 +from .tensor.creation import empty # noqa: F401 +from .tensor.creation import empty_like # noqa: F401 +from .tensor.creation import assign # noqa: F401 +from .tensor.creation import complex # noqa: F401 +from .tensor.creation import clone # noqa: F401 +from .tensor.creation import tril_indices #noqa: F401 +from .tensor.creation import triu_indices #noqa: F401 +from .tensor.linalg import matmul # noqa: F401 +from .tensor.linalg import dot # noqa: F401 +from .tensor.linalg import norm # noqa: F401 +from .tensor.linalg import transpose # noqa: F401 +from .tensor.linalg import dist # noqa: F401 +from .tensor.linalg import t # noqa: F401 +from .tensor.linalg import cross # noqa: F401 +from .tensor.linalg import cholesky # noqa: F401 +from .tensor.linalg import bmm # noqa: F401 +from .tensor.linalg import histogram # noqa: F401 +from .tensor.linalg import bincount # noqa: F401 +from .tensor.linalg import mv # noqa: F401 +from .tensor.logic import equal # noqa: F401 +from .tensor.linalg import eigvalsh # noqa: F401 +from .tensor.logic import greater_equal # noqa: F401 +from .tensor.logic import greater_than # noqa: F401 +from .tensor.logic import is_empty # noqa: F401 +from .tensor.logic import less_equal # noqa: F401 +from .tensor.logic import less_than # noqa: F401 +from .tensor.logic import logical_and # noqa: F401 +from .tensor.logic import logical_not # noqa: F401 +from .tensor.logic import logical_or # noqa: F401 +from .tensor.logic import logical_xor # noqa: F401 +from .tensor.logic import bitwise_and # noqa: F401 +from .tensor.logic import bitwise_not # noqa: F401 +from .tensor.logic import bitwise_or # noqa: F401 +from .tensor.logic import bitwise_xor # noqa: F401 +from .tensor.logic import not_equal # noqa: F401 +from .tensor.logic import allclose # noqa: F401 +from .tensor.logic import isclose # noqa: F401 +from .tensor.logic import equal_all # noqa: F401 +from .tensor.logic import is_tensor # noqa: F401 +from .tensor.manipulation import cast # noqa: F401 +from .tensor.manipulation import concat # noqa: F401 +from .tensor.manipulation import broadcast_tensors # noqa: F401 +from .tensor.manipulation import expand # noqa: F401 +from .tensor.manipulation import broadcast_to # noqa: F401 +from .tensor.manipulation import expand_as # noqa: F401 +from .tensor.manipulation import tile # noqa: F401 +from .tensor.manipulation import flatten # noqa: F401 +from .tensor.manipulation import gather # noqa: F401 +from .tensor.manipulation import gather_nd # noqa: F401 +from .tensor.manipulation import reshape # noqa: F401 +from .tensor.manipulation import reshape_ # noqa: F401 +from .tensor.manipulation import flip as reverse # noqa: F401 +from .tensor.manipulation import scatter # noqa: F401 +from .tensor.manipulation import scatter_ # noqa: F401 +from .tensor.manipulation import scatter_nd_add # noqa: F401 +from .tensor.manipulation import scatter_nd # noqa: F401 +from .tensor.manipulation import shard_index # noqa: F401 +from .tensor.manipulation import slice # noqa: F401 +from .tensor.manipulation import crop # noqa: F401 +from .tensor.manipulation import split # noqa: F401 +from .tensor.manipulation import squeeze # noqa: F401 +from .tensor.manipulation import squeeze_ # noqa: F401 +from .tensor.manipulation import stack # noqa: F401 +from .tensor.manipulation import strided_slice # noqa: F401 +from .tensor.manipulation import unique # noqa: F401 +from .tensor.manipulation import unique_consecutive # noqa: F401 +from .tensor.manipulation import unsqueeze # noqa: F401 +from .tensor.manipulation import unsqueeze_ # noqa: F401 +from .tensor.manipulation import unstack # noqa: F401 +from .tensor.manipulation import flip # noqa: F401 +from .tensor.manipulation import rot90 # noqa: F401 +from .tensor.manipulation import unbind # noqa: F401 +from .tensor.manipulation import roll # noqa: F401 +from .tensor.manipulation import chunk # noqa: F401 +from .tensor.manipulation import tolist # noqa: F401 +from .tensor.manipulation import take_along_axis # noqa: F401 +from .tensor.manipulation import put_along_axis # noqa: F401 +from .tensor.manipulation import tensordot # noqa: F401 +from .tensor.manipulation import as_complex # noqa: F401 +from .tensor.manipulation import as_real # noqa: F401 +from .tensor.manipulation import moveaxis # noqa: F401 +from .tensor.manipulation import repeat_interleave # noqa: F401 +from .tensor.manipulation import index_add # noqa: F401 +from .tensor.manipulation import index_add_ # noqa: F401 +from .tensor.math import abs # noqa: F401 +from .tensor.math import acos # noqa: F401 +from .tensor.math import asin # noqa: F401 +from .tensor.math import atan # noqa: F401 +from .tensor.math import atan2 # noqa: F401 +from .tensor.math import ceil # noqa: F401 +from .tensor.math import cos # noqa: F401 +from .tensor.math import tan # noqa: F401 +from .tensor.math import cosh # noqa: F401 +from .tensor.math import cumsum # noqa: F401 +from .tensor.math import cumprod # noqa: F401 +from .tensor.math import logcumsumexp # noqa: F401 +from .tensor.math import logit # noqa: F401 +from .tensor.math import exp # noqa: F401 +from .tensor.math import expm1 # noqa: F401 +from .tensor.math import floor # noqa: F401 +from .tensor.math import increment # noqa: F401 +from .tensor.math import log # noqa: F401 +from .tensor.math import log2 # noqa: F401 +from .tensor.math import log10 # noqa: F401 +from .tensor.math import multiplex # noqa: F401 +from .tensor.math import pow # noqa: F401 +from .tensor.math import reciprocal # noqa: F401 +from .tensor.math import all # noqa: F401 +from .tensor.math import any # noqa: F401 +from .tensor.math import round # noqa: F401 +from .tensor.math import rsqrt # noqa: F401 +from .tensor.math import scale # noqa: F401 +from .tensor.math import sign # noqa: F401 +from .tensor.math import sin # noqa: F401 +from .tensor.math import sinh # noqa: F401 +from .tensor.math import sqrt # noqa: F401 +from .tensor.math import square # noqa: F401 +from .tensor.math import stanh # noqa: F401 +from .tensor.math import sum # noqa: F401 +from .tensor.math import nansum # noqa: F401 +from .tensor.math import nanmean # noqa: F401 +from .tensor.math import count_nonzero # noqa: F401 +from .tensor.math import tanh # noqa: F401 +from .tensor.math import tanh_ # noqa: F401 +from .tensor.math import add_n # noqa: F401 +from .tensor.math import max # noqa: F401 +from .tensor.math import maximum # noqa: F401 +from .tensor.math import amax # noqa: F401 +from .tensor.math import min # noqa: F401 +from .tensor.math import minimum # noqa: F401 +from .tensor.math import amin # noqa: F401 +from .tensor.math import mm # noqa: F401 +from .tensor.math import divide # noqa: F401 +from .tensor.math import floor_divide # noqa: F401 +from .tensor.math import remainder # noqa: F401 +from .tensor.math import remainder_ # noqa: F401 +from .tensor.math import mod # noqa: F401 +from .tensor.math import floor_mod # noqa: F401 +from .tensor.math import multiply # noqa: F401 +from .tensor.math import renorm # noqa: F401 +from .tensor.math import add # noqa: F401 +from .tensor.math import subtract # noqa: F401 +from .tensor.math import logsumexp # noqa: F401 +from .tensor.math import inverse # noqa: F401 +from .tensor.math import log1p # noqa: F401 +from .tensor.math import erf # noqa: F401 +from .tensor.math import addmm # noqa: F401 +from .tensor.math import clip # noqa: F401 +from .tensor.math import trace # noqa: F401 +from .tensor.math import diagonal # noqa: F401 +from .tensor.math import kron # noqa: F401 +from .tensor.math import isfinite # noqa: F401 +from .tensor.math import isinf # noqa: F401 +from .tensor.math import isnan # noqa: F401 +from .tensor.math import prod # noqa: F401 +from .tensor.math import broadcast_shape # noqa: F401 +from .tensor.math import conj # noqa: F401 +from .tensor.math import trunc # noqa: F401 +from .tensor.math import digamma # noqa: F401 +from .tensor.math import neg # noqa: F401 +from .tensor.math import lgamma # noqa: F401 +from .tensor.math import acosh # noqa: F401 +from .tensor.math import asinh # noqa: F401 +from .tensor.math import atanh # noqa: F401 +from .tensor.math import lerp # noqa: F401 +from .tensor.math import erfinv # noqa: F401 +from .tensor.math import rad2deg # noqa: F401 +from .tensor.math import deg2rad # noqa: F401 +from .tensor.math import gcd # noqa: F401 +from .tensor.math import lcm # noqa: F401 +from .tensor.math import diff # noqa: F401 +from .tensor.math import angle # noqa: F401 +from .tensor.math import fmax # noqa: F401 +from .tensor.math import fmin # noqa: F401 +from .tensor.math import inner # noqa: F401 +from .tensor.math import outer # noqa: F401 +from .tensor.math import heaviside # noqa: F401 +from .tensor.math import frac # noqa: F401 +from .tensor.math import sgn # noqa: F401 +from .tensor.math import take # noqa: F401 + +from .tensor.random import bernoulli # noqa: F401 +from .tensor.random import poisson # noqa: F401 +from .tensor.random import multinomial # noqa: F401 +from .tensor.random import standard_normal # noqa: F401 +from .tensor.random import normal # noqa: F401 +from .tensor.random import uniform # noqa: F401 +from .tensor.random import randn # noqa: F401 +from .tensor.random import rand # noqa: F401 +from .tensor.random import randint # noqa: F401 +from .tensor.random import randint_like # noqa: F401 +from .tensor.random import randperm # noqa: F401 +from .tensor.search import argmax # noqa: F401 +from .tensor.search import argmin # noqa: F401 +from .tensor.search import argsort # noqa: F401 +from .tensor.search import searchsorted # noqa: F401 +from .tensor.search import bucketize # noqa: F401 +from .tensor.search import masked_select # noqa: F401 +from .tensor.search import topk # noqa: F401 +from .tensor.search import where # noqa: F401 +from .tensor.search import index_select # noqa: F401 +from .tensor.search import nonzero # noqa: F401 +from .tensor.search import sort # noqa: F401 +from .tensor.search import kthvalue # noqa: F401 +from .tensor.search import mode # noqa: F401 + +from .tensor.to_string import set_printoptions # noqa: F401 + +from .tensor.einsum import einsum # noqa: F401 + +from .framework.random import seed # noqa: F401 +from .framework.random import get_cuda_rng_state # noqa: F401 +from .framework.random import set_cuda_rng_state # noqa: F401 +from .framework import ParamAttr # noqa: F401 +from .framework import create_parameter # noqa: F401 +from .framework import CPUPlace # noqa: F401 +from .framework import IPUPlace # noqa: F401 +from .framework import CUDAPlace # noqa: F401 +from .framework import NPUPlace # noqa: F401 +from .framework import CUDAPinnedPlace # noqa: F401 +from .framework import MLUPlace # noqa: F401 +from .framework import CustomPlace # noqa: F401 + +from .autograd import grad # noqa: F401 +from .autograd import no_grad # noqa: F401 +from .autograd import set_grad_enabled # noqa: F401 +from .autograd import is_grad_enabled # noqa: F401 +from .framework import save # noqa: F401 +from .framework import load # noqa: F401 +from .framework import DataParallel # noqa: F401 + +from .framework import set_default_dtype # noqa: F401 +from .framework import get_default_dtype # noqa: F401 + +from .tensor.search import index_sample # noqa: F401 +from .tensor.stat import mean # noqa: F401 +from .tensor.stat import std # noqa: F401 +from .tensor.stat import var # noqa: F401 +from .tensor.stat import numel # noqa: F401 +from .tensor.stat import median # noqa: F401 +from .tensor.stat import nanmedian # noqa: F401 +from .tensor.stat import quantile # noqa: F401 +from .tensor.stat import nanquantile # noqa: F401 +from .device import get_cudnn_version # noqa: F401 +from .device import set_device # noqa: F401 +from .device import get_device # noqa: F401 +from .device import is_compiled_with_xpu # noqa: F401 +from .device import is_compiled_with_npu # noqa: F401 +from .device import is_compiled_with_ipu # noqa: F401 +from .device import is_compiled_with_mlu # noqa: F401 +from .device import is_compiled_with_cinn # noqa: F401 +from .device import is_compiled_with_cuda # noqa: F401 +from .device import is_compiled_with_rocm # noqa: F401 +from .device import XPUPlace # noqa: F401 + +# high-level api +from .hapi import Model # noqa: F401 +from . import callbacks # noqa: F401 +from .hapi import summary # noqa: F401 +from .hapi import flops # noqa: F401 +from . import hub # noqa: F401 +from . import linalg # noqa: F401 +from . import fft # noqa: F401 +from . import signal # noqa: F401 + +import paddle.text # noqa: F401 +import paddle.vision # noqa: F401 + +from .tensor.random import check_shape # noqa: F401 + +# CINN has to set a flag to include a lib +if is_compiled_with_cinn(): + import os + package_dir = os.path.dirname(os.path.abspath(__file__)) + runtime_include_dir = os.path.join(package_dir, "libs") + cuh_file = os.path.join(runtime_include_dir, "cinn_cuda_runtime_source.cuh") + if os.path.exists(cuh_file): + os.environ.setdefault('runtime_include_dir', runtime_include_dir) + +disable_static() + +__all__ = [ # noqa + 'iinfo', + 'dtype', + 'uint8', + 'int8', + 'int16', + 'int32', + 'int64', + 'float16', + 'float32', + 'float64', + 'bfloat16', + 'bool', + 'complex64', + 'complex128', + 'addmm', + 'allclose', + 'isclose', + 't', + 'add', + 'subtract', + 'diag', + 'diagflat', + 'isnan', + 'scatter_nd_add', + 'unstack', + 'get_default_dtype', + 'save', + 'multinomial', + 'get_cuda_rng_state', + 'rank', + 'empty_like', + 'eye', + 'cumsum', + 'cumprod', + 'logcumsumexp', + 'logit', + 'LazyGuard', + 'sign', + 'is_empty', + 'equal', + 'equal_all', + 'is_tensor', + 'is_complex', + 'is_integer', + 'cross', + 'where', + 'log1p', + 'cos', + 'tan', + 'mean', + 'mode', + 'mv', + 'in_dynamic_mode', + 'min', + 'amin', + 'any', + 'slice', + 'normal', + 'logsumexp', + 'full', + 'unsqueeze', + 'unsqueeze_', + 'argmax', + 'Model', + 'summary', + 'flops', + 'sort', + 'searchsorted', + 'bucketize', + 'split', + 'logical_and', + 'full_like', + 'less_than', + 'kron', + 'clip', + 'Tensor', + 'crop', + 'ParamAttr', + 'stanh', + 'randint', + 'randint_like', + 'assign', + 'gather', + 'scale', + 'zeros', + 'rsqrt', + 'squeeze', + 'squeeze_', + 'to_tensor', + 'gather_nd', + 'isinf', + 'uniform', + 'floor_divide', + 'remainder', + 'floor_mod', + 'roll', + 'batch', + 'max', + 'amax', + 'logical_or', + 'bitwise_and', + 'bitwise_or', + 'bitwise_xor', + 'bitwise_not', + 'mm', + 'flip', + 'rot90', + 'bincount', + 'histogram', + 'multiplex', + 'CUDAPlace', + 'NPUPlace', + 'empty', + 'shape', + 'real', + 'imag', + 'is_floating_point', + 'complex', + 'reciprocal', + 'rand', + 'less_equal', + 'triu', + 'sin', + 'dist', + 'unbind', + 'meshgrid', + 'arange', + 'load', + 'numel', + 'median', + 'nanmedian', + 'quantile', + 'nanquantile', + 'no_grad', + 'set_grad_enabled', + 'is_grad_enabled', + 'mod', + 'abs', + 'tril', + 'pow', + 'zeros_like', + 'maximum', + 'topk', + 'index_select', + 'CPUPlace', + 'matmul', + 'seed', + 'acos', + 'logical_xor', + 'exp', + 'expm1', + 'bernoulli', + 'poisson', + 'sinh', + 'round', + 'DataParallel', + 'argmin', + 'prod', + 'broadcast_shape', + 'conj', + 'neg', + 'lgamma', + 'lerp', + 'erfinv', + 'inner', + 'outer', + 'square', + 'divide', + 'ceil', + 'atan', + 'atan2', + 'rad2deg', + 'deg2rad', + 'gcd', + 'lcm', + 'expand', + 'broadcast_to', + 'ones_like', + 'index_sample', + 'cast', + 'grad', + 'all', + 'ones', + 'not_equal', + 'sum', + 'nansum', + 'nanmean', + 'count_nonzero', + 'tile', + 'greater_equal', + 'isfinite', + 'create_parameter', + 'dot', + 'increment', + 'erf', + 'bmm', + 'chunk', + 'tolist', + 'tensordot', + 'greater_than', + 'shard_index', + 'argsort', + 'tanh', + 'tanh_', + 'transpose', + 'randn', + 'strided_slice', + 'unique', + 'unique_consecutive', + 'set_cuda_rng_state', + 'set_printoptions', + 'std', + 'flatten', + 'asin', + 'multiply', + 'disable_static', + 'masked_select', + 'var', + 'trace', + 'enable_static', + 'scatter_nd', + 'set_default_dtype', + 'disable_signal_handler', + 'expand_as', + 'stack', + 'sqrt', + 'randperm', + 'linspace', + 'logspace', + 'reshape', + 'reshape_', + 'reverse', + 'nonzero', + 'CUDAPinnedPlace', + 'logical_not', + 'add_n', + 'minimum', + 'scatter', + 'scatter_', + 'floor', + 'cosh', + 'log', + 'log2', + 'log10', + 'concat', + 'check_shape', + 'trunc', + 'frac', + 'digamma', + 'standard_normal', + 'diagonal', + 'broadcast_tensors', + 'einsum', + 'set_flags', + 'get_flags', + 'asinh', + 'acosh', + 'atanh', + 'as_complex', + 'as_real', + 'diff', + 'angle', + 'fmax', + 'fmin', + 'moveaxis', + 'repeat_interleave', + 'clone', + 'kthvalue', + 'renorm', + 'take_along_axis', + 'put_along_axis', + 'heaviside', + 'tril_indices', + 'index_add', + "index_add_", + 'sgn', + 'triu_indices', + 'take', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_legacy_C_ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_legacy_C_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ace90e62edfb806a5c102c3180e30df042711e83 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/_legacy_C_ops.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022 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. + +from paddle.fluid import core +from .fluid import framework + +__all__ = [] + +_already_switch_to_eager_ = False + +if not framework._in_eager_mode_: + for name in dir(core.ops): + globals()[name] = getattr(core.ops, name) + __all__.append(name) + _already_switch_to_eager_ = False +else: + for name in dir(core.eager.ops.legacy): + globals()[name] = getattr(core.eager.ops.legacy, name) + __all__.append(name) + _already_switch_to_eager_ = True + + +def switch_to_core_ops(): + global _already_switch_to_eager_ + if _already_switch_to_eager_: + for name in dir(core.eager.ops.legacy): + del globals()[name] + __all__.remove(name) + for name in dir(core.ops): + globals()[name] = getattr(core.ops, name) + __all__.append(name) + _already_switch_to_eager_ = False + + +def switch_to_eager_ops(): + global _already_switch_to_eager_ + if not _already_switch_to_eager_: + for name in dir(core.ops): + del globals()[name] + __all__.remove(name) + for name in dir(core.eager.ops.legacy): + globals()[name] = getattr(core.eager.ops.legacy, name) + __all__.append(name) + _already_switch_to_eager_ = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..381aad8850bc133cb327cd391425638e83701036 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/__init__.py @@ -0,0 +1,19 @@ +# 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. + +from .auto_cast import auto_cast # noqa: F401 +from .grad_scaler import GradScaler # noqa: F401 +from .auto_cast import decorate # noqa: F401 + +__all__ = ['auto_cast', 'GradScaler', 'decorate'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/auto_cast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/auto_cast.py new file mode 100644 index 0000000000000000000000000000000000000000..96a94d898467f882fdd6526b1e5a7885970a0de9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/auto_cast.py @@ -0,0 +1,148 @@ +# 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. + +from paddle.fluid.dygraph.amp import amp_guard +from paddle.fluid.dygraph.amp import amp_decorate + +__all__ = [] + + +def auto_cast(enable=True, + custom_white_list=None, + custom_black_list=None, + level='O1', + dtype='float16'): + """ + Create a context which enables auto-mixed-precision(AMP) of operators executed in dynamic graph mode. + If enabled, the input data type (float32 or float16) of each operator is decided + by autocast algorithm for better performance. + + Commonly, it is used together with `GradScaler` to achieve Auto-Mixed-Precision in + imperative mode. It is used together with `decorator` to achieve Pure fp16 in imperative mode. + + Args: + enable(bool, optional): Enable auto-mixed-precision or not. Default is True. + custom_white_list(set|list|tuple, optional): The custom white_list. It's the set of ops that support + fp16 calculation and are considered numerically-safe and performance-critical. These ops + will be converted to fp16. + custom_black_list(set|list|tuple, optional): The custom black_list. The set of ops that support fp16 + calculation and are considered numerically-dangerous and whose effects may also be + observed in downstream ops. These ops will not be converted to fp16. + level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the input data type of each operator will be casted by white_list and black_list; + O2 represent Pure fp16, all operators parameters and input data will be casted to fp16, except operators in black_list, don't support fp16 kernel and batchnorm. Default is O1(amp) + dtype(str, optional): Whether to use 'float16' or 'bfloat16'. Default is 'float16'. + + Examples: + + .. code-block:: python + + import paddle + + conv2d = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(): + conv = conv2d(data) + print(conv.dtype) # paddle.float32 + + with paddle.amp.auto_cast(enable=False): + conv = conv2d(data) + print(conv.dtype) # paddle.float32 + + with paddle.amp.auto_cast(custom_black_list={'conv2d'}): + conv = conv2d(data) + print(conv.dtype) # paddle.float32 + + a = paddle.rand([2,3]) + b = paddle.rand([2,3]) + with paddle.amp.auto_cast(custom_white_list={'elementwise_add'}): + c = a + b + print(c.dtype) # paddle.float32 + + with paddle.amp.auto_cast(custom_white_list={'elementwise_add'}, level='O2'): + d = a + b + print(d.dtype) # paddle.float32 + + """ + return amp_guard(enable, custom_white_list, custom_black_list, level, dtype) + + +def decorate(models, + optimizers=None, + level='O1', + master_weight=None, + save_dtype=None): + """ + Decorate models and optimizers for auto-mixed-precision. When level is O1(amp), the decorate will do nothing. + When level is O2(pure fp16), the decorate will cast all parameters of models to FP16, except BatchNorm and LayerNorm. + + Commonly, it is used together with `auto_cast` to achieve Pure fp16 in imperative mode. + + Args: + models(Layer|list of Layer, optional): The defined models by user, models must be either a single model or a list of models. Default is None. + optimizers(Optimizer|list of Optimizer, optional): The defined optimizers by user, optimizers must be either a single optimizer or a list of optimizers. Default is None. + level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the decorator will do nothing; + O2 represent Pure fp16, the decorator will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Default is O1(amp) + master_weight(bool, optinal): For level='O2', whether to use multi-precision during weight updating. If master_weight is None, in O2 level optimizer will use multi-precision. Default is None. + save_dtype(float, optional): The save model parameter dtype when use `paddle.save` or `paddle.jit.save`,it should be float16, float32, float64 or None. + The save_dtype will not change model parameters dtype, it just change the state_dict dtype. When save_dtype is None, the save dtype is same as model dtype. Default is None. + + Examples: + + .. code-block:: python + + # required: gpu + # Demo1: single model and optimizer: + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer = paddle.optimizer.SGD(parameters=model.parameters()) + + model, optimizer = paddle.amp.decorate(models=model, optimizers=optimizer, level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = model(data) + print(output.dtype) # FP16 + + # required: gpu + # Demo2: multi models and optimizers: + model2 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer2 = paddle.optimizer.Adam(parameters=model2.parameters()) + + models, optimizers = paddle.amp.decorate(models=[model, model2], optimizers=[optimizer, optimizer2], level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = models[0](data) + output2 = models[1](data) + print(output.dtype) # FP16 + print(output2.dtype) # FP16 + + # required: gpu + # Demo3: optimizers is None: + model3 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer3 = paddle.optimizer.Adam(parameters=model3.parameters()) + + model = paddle.amp.decorate(models=model3, level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = model(data) + print(output.dtype) # FP16 + """ + return amp_decorate(models, optimizers, level, master_weight, save_dtype) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/grad_scaler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/grad_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..46582b1770b462c583ff3e80d0606c874d98e777 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/amp/grad_scaler.py @@ -0,0 +1,634 @@ +# 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. + +from paddle.fluid.dygraph.amp import AmpScaler +from paddle.fluid.dygraph.amp import OptimizerState +from collections import defaultdict + +__all__ = [] + + +def _refresh_optimizer_state(): + return {"state": OptimizerState.INIT} + + +class GradScaler(AmpScaler): + """ + GradScaler is used for Auto-Mixed-Precision training in dynamic graph mode. + It controls the scaling of loss, helps avoiding numerical overflow. + The object of this class has nineteen methods `scale()`, `unscale_()`, `minimize()`, `step()`, `update()` and `get`/`set` api of parameters. + + `scale()` is used to multiply the loss by a scale ratio. + `unscale_()` is used to unscale the gradients of parameters, multiplies the gradients of parameters by 1/(scale ratio) + `minimize()` is similar as `optimizer.minimize()`, performs parameters updating, and it will update the loss_scaling, it equal to `step()` + `update()`. + `step()` is similar as `optimizer.step()`, which performs parameters updating. + `update` is used to update the loss_scaling. + + + Commonly, it is used together with `paddle.amp.auto_cast` to achieve Auto-Mixed-Precision in + dynamic graph mode. + + Args: + enable(bool, optional): Enable loss scaling or not. Default is True. + init_loss_scaling (float, optional): The initial loss scaling factor. Default is 2**15. + incr_ratio(float, optional): The multiplier to use when increasing the loss + scaling. Default is 2.0. + decr_ratio(float, optional): The less-than-one-multiplier to use when decreasing + the loss scaling. Default is 0.5. + incr_every_n_steps(int, optional): Increases loss scaling every n consecutive + steps with finite gradients. Default is 1000. + decr_every_n_nan_or_inf(int, optional): Decreases loss scaling every n + accumulated steps with nan or inf gradients. Default is 2. + use_dynamic_loss_scaling(bool, optional): Whether to use dynamic loss scaling. If False, fixed loss_scaling is used. If True, the loss scaling is updated dynamicly. Default is True. + Returns: + An GradScaler object. + + Examples: + + .. code-block:: python + + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.minimize(optimizer, scaled) # update parameters + optimizer.clear_grad() + """ + + def __init__(self, + enable=True, + init_loss_scaling=2.**15, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True): + super(GradScaler, + self).__init__(enable, init_loss_scaling, incr_ratio, decr_ratio, + incr_every_n_steps, decr_every_n_nan_or_inf, + use_dynamic_loss_scaling) + + def scale(self, var): + """ + Multiplies a Tensor by the scale factor and returns scaled outputs. + If this instance of :class:`GradScaler` is not enabled, output are returned unmodified. + + Args: + var (Tensor): The tensor to scale. + Returns: + The scaled tensor or original tensor. + + Examples: + + .. code-block:: python + + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.minimize(optimizer, scaled) # update parameters + optimizer.clear_grad() + """ + return super(GradScaler, self).scale(var) + + def minimize(self, optimizer, *args, **kwargs): + """ + This function is similar as `optimizer.minimize()`, which performs parameters updating. + + If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. + Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters. + + Finally, the loss scaling ratio is updated. + + Args: + optimizer(Optimizer): The optimizer used to update parameters. + args: Arguments, which will be forward to `optimizer.minimize()`. + kwargs: Keyword arguments, which will be forward to `optimizer.minimize()`. + + Examples: + + .. code-block:: python + + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.minimize(optimizer, scaled) # update parameters + optimizer.clear_grad() + """ + return super(GradScaler, self).minimize(optimizer, *args, **kwargs) + + def step(self, optimizer): + """ + This function is similar as `optimizer.step()`, which performs parameters updating. + + If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. + Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters. + + Args: + optimizer(Optimizer): The optimizer used to update parameters. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.step(optimizer) # update parameters + scaler.update() # update the loss scaling ratio + optimizer.clear_grad() + """ + if not self._enable: + return optimizer.step() + + optimizer_state = self._optimizer_states[id(optimizer)] + if optimizer_state["state"] is OptimizerState.STEPPED: + raise RuntimeError( + "step() has already been called since the last update().") + + # unscale the grad + if optimizer_state["state"] is OptimizerState.INIT: + self._unscale(optimizer) + + if self._found_inf: + self._cache_founf_inf = True + else: + optimizer.step() + self._cache_founf_inf = False + + optimizer_state["state"] = OptimizerState.STEPPED + + if not self._use_dynamic_loss_scaling: + self._optimizer_states = defaultdict(_refresh_optimizer_state) + + def update(self): + """ + Updates the loss_scaling. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.step(optimizer) # update parameters + scaler.update() # update the loss scaling ratio + optimizer.clear_grad() + """ + if not self._enable: + return + if self._use_dynamic_loss_scaling: + self._update() + self._optimizer_states = defaultdict(_refresh_optimizer_state) + return + + def unscale_(self, optimizer): + """ + Unscale the gradients of parameters, multiplies the gradients of parameters by 1/(loss scaling ratio). + If this instance of :class:`GradScaler` is not enabled, output are returned unmodified. + + Args: + optimizer(Optimizer): The optimizer used to update parameters. + + Returns: + The unscaled parameters or original parameters. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=True) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + scaler = paddle.amp.GradScaler(init_loss_scaling=1024) + data = paddle.rand([10, 3, 32, 32]) + with paddle.amp.auto_cast(): + conv = model(data) + loss = paddle.mean(conv) + scaled = scaler.scale(loss) # scale the loss + scaled.backward() # do backward + scaler.unscale_(optimizer) # unscale the parameter + scaler.step(optimizer) + scaler.update() + optimizer.clear_grad() + """ + return super(GradScaler, self)._unscale(optimizer) + + def is_enable(self): + """ + Enable loss scaling or not. + + Returns: + bool: enable loss scaling return True else return False. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + enable = scaler.is_enable() + print(enable) # True + """ + return super(GradScaler, self).is_enable() + + def is_use_dynamic_loss_scaling(self): + """ + Whether to use dynamic loss scaling. + + Returns: + bool: if fixed loss_scaling is used return False, if the loss scaling is updated dynamicly return true. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + use_dynamic_loss_scaling = scaler.is_use_dynamic_loss_scaling() + print(use_dynamic_loss_scaling) # True + """ + return super(GradScaler, self).is_use_dynamic_loss_scaling() + + def get_init_loss_scaling(self): + """ + Return the initial loss scaling factor. + + Reurns: + float: the initial loss scaling factor. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + init_loss_scaling = scaler.get_init_loss_scaling() + print(init_loss_scaling) # 1024 + """ + return super(GradScaler, self).get_init_loss_scaling() + + def set_init_loss_scaling(self, new_init_loss_scaling): + """ + Set the initial loss scaling factor by `new_init_loss_scaling`. + + Args: + new_init_loss_scaling(float): The new_init_loss_scaling used to update initial loss scaling factor. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + print(scaler.get_init_loss_scaling()) # 1024 + new_init_loss_scaling = 1000 + scaler.set_init_loss_scaling(new_init_loss_scaling) + print(scaler.get_init_loss_scaling()) # 1000 + """ + super(GradScaler, self).set_init_loss_scaling(new_init_loss_scaling) + + def get_incr_ratio(self): + """ + Return the multiplier to use when increasing the loss scaling. + + Reurns: + float: the multiplier to use when increasing the loss scaling. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + incr_ratio = scaler.get_incr_ratio() + print(incr_ratio) # 2.0 + """ + return super(GradScaler, self).get_incr_ratio() + + def set_incr_ratio(self, new_incr_ratio): + """ + Set the multiplier to use when increasing the loss scaling by `new_incr_ratio`, `new_incr_ratio` should > 1.0. + + Args: + new_incr_ratio(float): The new_incr_ratio used to update the multiplier to use when increasing the loss scaling. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + print(scaler.get_incr_ratio()) # 2.0 + new_incr_ratio = 3.0 + scaler.set_incr_ratio(new_incr_ratio) + print(scaler.get_incr_ratio()) # 3.0 + """ + super(GradScaler, self).set_incr_ratio(new_incr_ratio) + + def get_decr_ratio(self): + """ + Get the less-than-one-multiplier to use when decreasing the loss scaling. + + Reurns: + float: the less-than-one-multiplier to use when decreasing the loss scaling. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + decr_ratio = scaler.get_decr_ratio() + print(decr_ratio) # 0.5 + """ + return super(GradScaler, self).get_decr_ratio() + + def set_decr_ratio(self, new_decr_ratio): + """ + Set the less-than-one-multiplier to use when decreasing the loss scaling by `new_incr_ratio`, `new_decr_ratio` should < 1.0. + + Args: + new_decr_ratio(float): The new_decr_ratio used to update the less-than-one-multiplier to use when decreasing the loss scaling. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + print(scaler.get_decr_ratio()) # 0.5 + new_decr_ratio = 0.1 + scaler.set_decr_ratio(new_decr_ratio) + print(scaler.get_decr_ratio()) # 0.1 + """ + super(GradScaler, self).set_decr_ratio(new_decr_ratio) + + def get_incr_every_n_steps(self): + """ + Return the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Reurns: + int: the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + incr_every_n_steps = scaler.get_incr_every_n_steps() + print(incr_every_n_steps) # 1000 + """ + return super(GradScaler, self).get_incr_every_n_steps() + + def set_incr_every_n_steps(self, new_incr_every_n_steps): + """ + Set the num `n` by `new_incr_every_n_steps`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Args: + new_incr_every_n_steps(int): The new_incr_every_n_steps used to update the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + print(scaler.get_incr_every_n_steps()) # 1000 + new_incr_every_n_steps = 2000 + scaler.set_incr_every_n_steps(new_incr_every_n_steps) + print(scaler.get_incr_every_n_steps()) # 2000 + """ + super(GradScaler, self).set_incr_every_n_steps(new_incr_every_n_steps) + + def get_decr_every_n_nan_or_inf(self): + """ + Return the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Reurns: + int: the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + decr_every_n_nan_or_inf = scaler.get_decr_every_n_nan_or_inf() + print(decr_every_n_nan_or_inf) # 2 + """ + return super(GradScaler, self).get_decr_every_n_nan_or_inf() + + def set_decr_every_n_nan_or_inf(self, new_decr_every_n_nan_or_inf): + """ + Set the num `n` by `new_decr_every_n_nan_or_inf`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Args: + new_decr_every_n_nan_or_inf(int): The new_decr_every_n_nan_or_inf used to update the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Examples: + .. code-block:: python + + # required: gpu,xpu + import paddle + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + print(scaler.get_decr_every_n_nan_or_inf()) # 2 + new_decr_every_n_nan_or_inf = 3 + scaler.set_decr_every_n_nan_or_inf(new_decr_every_n_nan_or_inf) + print(scaler.get_decr_every_n_nan_or_inf()) # 3 + """ + super(GradScaler, + self).set_decr_every_n_nan_or_inf(new_decr_every_n_nan_or_inf) + + def state_dict(self): + """ + Returns the state of the scaler as a `dict`, If this instance is not enabled, returns an empty dict. + + Reurns: + A dict of scaler includes: + scale (tensor): The loss scaling factor. + incr_ratio(float): The multiplier to use when increasing the loss scaling. + decr_ratio(float): The less-than-one-multiplier to use when decreasing the loss scaling. + incr_every_n_steps(int): Increases loss scaling every n consecutive steps with finite gradients. + decr_every_n_nan_or_inf(int): Decreases loss scaling every n accumulated steps with nan or inf gradients. + incr_count(int): The number of recent consecutive unskipped steps. + decr_count(int): The number of recent consecutive skipped steps. + use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling. If False, fixed loss_scaling is used. If True, the loss scaling is updated dynamicly. Default is True. + + + Examples: + + .. code-block:: python + + # required: gpu,xpu + import paddle + + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + scaler_state = scaler.state_dict() + """ + return super(GradScaler, self).state_dict() + + def load_state_dict(self, state_dict): + """ + Loads the scaler state. + + Args: + state_dict(dict): scaler state. Should be an object returned from a call to `GradScaler.state_dict()`. + + Examples: + + .. code-block:: python + + # required: gpu,xpu + import paddle + + scaler = paddle.amp.GradScaler(enable=True, + init_loss_scaling=1024, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + use_dynamic_loss_scaling=True) + scaler_state = scaler.state_dict() + scaler.load_state_dict(scaler_state) + """ + super(GradScaler, self).load_state_dict(state_dict) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee768ab6d029c723dc8faf1e0e8124cbe312cabc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/__init__.py @@ -0,0 +1,24 @@ +# Copyright (c) 2022 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. + +from . import features +from . import functional +from . import datasets +from . import backends + +from .backends.backend import info, load, save + +__all__ = [ + "functional", "features", "datasets", "backends", "load", "info", "save" +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac19a14c69a01a48b4ebd031749cf4a62c39f7ee --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022 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. +from . import init_backend +from .init_backend import get_current_backend # noqa: F401 +from .init_backend import list_available_backends # noqa: F401 +from .init_backend import set_backend + +init_backend._init_set_audio_backend() + +__all__ = [ + 'get_current_backend', + 'list_available_backends', + 'set_backend', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/backend.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..fbfd11d20e0b54f87b2e53a6ab7e94b3bbccc592 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/backend.py @@ -0,0 +1,146 @@ +# Copyright (c) 2022 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 + +import paddle + +from pathlib import Path +from typing import Optional, Tuple, Union + + +class AudioInfo: + """ Audio info, return type of backend info function """ + + def __init__(self, sample_rate: int, num_samples: int, num_channels: int, + bits_per_sample: int, encoding: str): + self.sample_rate = sample_rate + self.num_samples = num_samples + self.num_channels = num_channels + self.bits_per_sample = bits_per_sample + self.encoding = encoding + + +def info(filepath: str) -> AudioInfo: + """Get signal information of input audio file. + + Args: + filepath: audio path or file object. + + Returns: + AudioInfo: info of the given audio. + + Example: + .. code-block:: python + + import os + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + base_dir = os.getcwd() + filepath = os.path.join(base_dir, "test.wav") + + paddle.audio.save(filepath, waveform, sample_rate) + wav_info = paddle.audio.info(filepath) + """ + # for API doc + raise NotImplementedError("please set audio backend") + + +def load(filepath: Union[str, Path], + frame_offset: int = 0, + num_frames: int = -1, + normalize: bool = True, + channels_first: bool = True) -> Tuple[paddle.Tensor, int]: + """Load audio data from file.Load the audio content start form frame_offset, and get num_frames. + + Args: + frame_offset: from 0 to total frames, + num_frames: from -1 (means total frames) or number frames which want to read, + normalize: + if True: return audio which norm to (-1, 1), dtype=float32 + if False: return audio with raw data, dtype=int16 + + channels_first: + if True: return audio with shape (channels, time) + + Return: + Tuple[paddle.Tensor, int]: (audio_content, sample rate) + + Exampels: + .. code-block:: python + + import os + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + base_dir = os.getcwd() + filepath = os.path.join(base_dir, "test.wav") + + paddle.audio.save(filepath, waveform, sample_rate) + wav_data_read, sr = paddle.audio.load(filepath) + """ + # for API doc + raise NotImplementedError("please set audio backend") + + +def save( + filepath: str, + src: paddle.Tensor, + sample_rate: int, + channels_first: bool = True, + encoding: Optional[str] = None, + bits_per_sample: Optional[int] = 16, +): + """ + Save audio tensor to file. + + Args: + filepath: saved path + src: the audio tensor + sample_rate: the number of samples of audio per second. + channels_first: src channel infomation + if True, means input tensor is (channels, time) + if False, means input tensor is (time, channels) + encoding:encoding format, wave_backend only support PCM16 now. + bits_per_sample: bits per sample, wave_backend only support 16 bits now. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + filepath = "./test.wav" + + paddle.audio.save(filepath, waveform, sample_rate) + """ + # for API doc + raise NotImplementedError("please set audio backend") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/init_backend.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/init_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..a066e4e23a64e5c6baaf931abfa9d05dbccb15bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/init_backend.py @@ -0,0 +1,185 @@ +# Copyright (c) 2022 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. + +import sys +import warnings +from . import wave_backend +from . import backend +from typing import List + +import paddle + + +def _check_version(version: str) -> bool: + # require paddleaudio >= 1.0.2 + ver_arr = version.split('.') + v0 = int(ver_arr[0]) + v1 = int(ver_arr[1]) + v2 = int(ver_arr[2]) + if v0 < 1: + return False + if v0 == 1 and v1 == 0 and v2 <= 1: + return False + return True + + +def list_available_backends() -> List[str]: + """ List available backends, the backends in paddleaudio and the default backend. + + Returns: + List[str]: The list of available backends. + + Examples: + .. code-block:: python + + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + wav_path = "./test.wav" + + current_backend = paddle.audio.backends.get_current_backend() + print(current_backend) # wave_backend, the default backend. + backends = paddle.audio.backends.list_available_backends() + # default backends is ['wave_backend'] + # backends is ['wave_backend', 'soundfile'], if have installed paddleaudio >= 1.0.2 + if 'soundfile' in backends: + paddle.audio.backends.set_backend('soundfile') + + paddle.audio.save(wav_path, waveform, sample_rate) + + """ + backends = [] + try: + import paddleaudio + except ImportError: + package = "paddleaudio" + warn_msg = ( + "Failed importing {}. \n" + "only wave_banckend(only can deal with PCM16 WAV) supportted.\n" + "if want soundfile_backend(more audio type suppported),\n" + "please manually installed (usually with `pip install {} >= 1.0.2`). " + ).format(package, package) + warnings.warn(warn_msg) + + if "paddleaudio" in sys.modules: + version = paddleaudio.__version__ + if _check_version(version) == False: + err_msg = ( + "the version of paddleaudio installed is {},\n" + "please ensure the paddleaudio >= 1.0.2.").format(version) + raise ImportError(err_msg) + backends = paddleaudio.backends.list_audio_backends() + backends.append("wave_backend") + return backends + + +def get_current_backend() -> str: + """ Get the name of the current audio backend + + Returns: + str: The name of the current backend, + the wave_backend or backend imported from paddleaudio + + Examples: + .. code-block:: python + + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + wav_path = "./test.wav" + + current_backend = paddle.audio.backends.get_current_backend() + print(current_backend) # wave_backend, the default backend. + backends = paddle.audio.backends.list_available_backends() + # default backends is ['wave_backend'] + # backends is ['wave_backend', 'soundfile'], if have installed paddleaudio >= 1.0.2 + + if 'soundfile' in backends: + paddle.audio.backends.set_backend('soundfile') + + paddle.audio.save(wav_path, waveform, sample_rate) + + """ + current_backend = None + if "paddleaudio" in sys.modules: + import paddleaudio + current_backend = paddleaudio.backends.get_audio_backend() + if paddle.audio.load == paddleaudio.load: + return current_backend + return "wave_backend" + + +def set_backend(backend_name: str): + """Set the backend by one of the list_audio_backend return. + + Args: + backend (str): one of the list_audio_backend. "wave_backend" is the default. "soundfile" imported from paddleaudio. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + wav_path = "./test.wav" + + current_backend = paddle.audio.backends.get_current_backend() + print(current_backend) # wave_backend, the default backend. + backends = paddle.audio.backends.list_available_backends() + # default backends is ['wave_backend'] + # backends is ['wave_backend', 'soundfile'], if have installed paddleaudio >= 1.0.2 + + if 'soundfile' in backends: + paddle.audio.backends.set_backend('soundfile') + + paddle.audio.save(wav_path, waveform, sample_rate) + + """ + if backend_name not in list_available_backends(): + raise NotImplementedError() + + if backend_name == "wave_backend": + module = wave_backend + else: + import paddleaudio + paddleaudio.backends.set_audio_backend(backend_name) + module = paddleaudio + + for func in ["save", "load", "info"]: + setattr(backend, func, getattr(module, func)) + setattr(paddle.audio, func, getattr(module, func)) + + +def _init_set_audio_backend(): + # init the default wave_backend. + for func in ["save", "load", "info"]: + setattr(backend, func, getattr(wave_backend, func)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/wave_backend.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/wave_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..66f2d48fe19a55b6a2f4b52dbd7091fdfb2fcaea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/backends/wave_backend.py @@ -0,0 +1,226 @@ +# Copyright (c) 2022 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. + +import paddle + +import wave +import numpy as np +from pathlib import Path + +from typing import Optional, Tuple, Union +from .backend import AudioInfo + + +def _error_message(): + package = "paddleaudio" + warn_msg = ( + "only PCM16 WAV supportted. \n" + "if want support more other audio types, please " + "manually installed (usually with `pip install {}`). \n " + "and use paddle.audio.backends.set_backend('soundfile') to set audio backend" + ).format(package) + return warn_msg + + +def info(filepath: str) -> AudioInfo: + """Get signal information of input audio file. + + Args: + filepath: audio path or file object. + + Returns: + AudioInfo: info of the given audio. + + Example: + .. code-block:: python + + import os + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + base_dir = os.getcwd() + filepath = os.path.join(base_dir, "test.wav") + + paddle.audio.save(filepath, waveform, sample_rate) + wav_info = paddle.audio.info(filepath) + """ + + if hasattr(filepath, 'read'): + file_obj = filepath + else: + file_obj = open(filepath, 'rb') + + try: + file_ = wave.open(file_obj) + except wave.Error: + file_obj.seek(0) + file_obj.close() + err_msg = _error_message() + raise NotImplementedError(err_msg) + + channels = file_.getnchannels() + sample_rate = file_.getframerate() + sample_frames = file_.getnframes() # audio frame + bits_per_sample = file_.getsampwidth() * 8 + encoding = "PCM_S" # default WAV encoding, only support + file_obj.close() + return AudioInfo(sample_rate, sample_frames, channels, bits_per_sample, + encoding) + + +def load(filepath: Union[str, Path], + frame_offset: int = 0, + num_frames: int = -1, + normalize: bool = True, + channels_first: bool = True) -> Tuple[paddle.Tensor, int]: + """Load audio data from file. load the audio content start form frame_offset, and get num_frames. + + Args: + frame_offset: from 0 to total frames, + num_frames: from -1 (means total frames) or number frames which want to read, + normalize: + if True: return audio which norm to (-1, 1), dtype=float32 + if False: return audio with raw data, dtype=int16 + + channels_first: + if True: return audio with shape (channels, time) + + Return: + Tuple[paddle.Tensor, int]: (audio_content, sample rate) + + Exampels: + .. code-block:: python + + import os + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + base_dir = os.getcwd() + filepath = os.path.join(base_dir, "test.wav") + + paddle.audio.save(filepath, waveform, sample_rate) + wav_data_read, sr = paddle.audio.load(filepath) + """ + if hasattr(filepath, 'read'): + file_obj = filepath + else: + file_obj = open(filepath, 'rb') + + try: + file_ = wave.open(file_obj) + except wave.Error: + file_obj.seek(0) + file_obj.close() + err_msg = _error_message() + raise NotImplementedError(err_msg) + + channels = file_.getnchannels() + sample_rate = file_.getframerate() + frames = file_.getnframes() # audio frame + + audio_content = file_.readframes(frames) + file_obj.close() + + # default_subtype = "PCM_16", only support PCM16 WAV + audio_as_np16 = np.frombuffer(audio_content, dtype=np.int16) + audio_as_np32 = audio_as_np16.astype(np.float32) + if normalize: + # dtype = "float32" + audio_norm = audio_as_np32 / (2**15) + else: + # dtype = "int16" + audio_norm = audio_as_np32 + + waveform = np.reshape(audio_norm, (frames, channels)) + if num_frames != -1: + waveform = waveform[frame_offset:frame_offset + num_frames, :] + waveform = paddle.to_tensor(waveform) + if channels_first: + waveform = paddle.transpose(waveform, perm=[1, 0]) + return waveform, sample_rate + + +def save( + filepath: str, + src: paddle.Tensor, + sample_rate: int, + channels_first: bool = True, + encoding: Optional[str] = None, + bits_per_sample: Optional[int] = 16, +): + """ + Save audio tensor to file. + + Args: + filepath: saved path + src: the audio tensor + sample_rate: the number of samples of audio per second. + channels_first: src channel infomation + if True, means input tensor is (channels, time) + if False, means input tensor is (time, channels) + encoding: audio encoding format, wave_backend only support PCM16 now. + bits_per_sample: bits per sample, wave_backend only support 16 bits now. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + filepath = "./test.wav" + + paddle.audio.save(filepath, waveform, sample_rate) + """ + assert src.ndim == 2, "Expected 2D tensor" + + audio_numpy = src.numpy() + + # change src shape to (time, channels) + if channels_first: + audio_numpy = np.transpose(audio_numpy) + + channels = audio_numpy.shape[1] + + # only support PCM16 + if bits_per_sample not in (None, 16): + raise ValueError("Invalid bits_per_sample, only supprt 16 bit") + + sample_width = int(bits_per_sample / 8) # 2 + + if src.dtype == paddle.float32: + audio_numpy = (audio_numpy * (2**15)).astype(" List[collections.namedtuple]: + ret = [] + with open(os.path.join(DATA_HOME, self.meta), 'r') as rf: + for line in rf.readlines()[1:]: + ret.append(self.meta_info(*line.strip().split(','))) + return ret + + def _get_data(self, mode: str, split: int) -> Tuple[List[str], List[int]]: + if not os.path.isdir( + os.path.join(DATA_HOME, self.audio_path) + ) or not os.path.isfile(os.path.join(DATA_HOME, self.meta)): + download.get_path_from_url( + self.archive['url'], + DATA_HOME, + self.archive['md5'], + decompress=True, + ) + + meta_info = self._get_meta_info() + + files = [] + labels = [] + for sample in meta_info: + filename, fold, target, _, _, _, _ = sample + if mode == 'train' and int(fold) != split: + files.append(os.path.join(DATA_HOME, self.audio_path, filename)) + labels.append(int(target)) + + if mode != 'train' and int(fold) == split: + files.append(os.path.join(DATA_HOME, self.audio_path, filename)) + labels.append(int(target)) + + return files, labels diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/datasets/tess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/datasets/tess.py new file mode 100644 index 0000000000000000000000000000000000000000..a379aedc6026bc5379d148cb7e263005ec8cec8c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/datasets/tess.py @@ -0,0 +1,155 @@ +# Copyright (c) 2022 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. +import collections +import os +from typing import List +from typing import Tuple + +from paddle.utils import download +from paddle.dataset.common import DATA_HOME +from .dataset import AudioClassificationDataset + +__all__ = [] + + +class TESS(AudioClassificationDataset): + """ + TESS is a set of 200 target words were spoken in the carrier phrase + "Say the word _____' by two actresses (aged 26 and 64 years) and + recordings were made of the set portraying each of seven emotions(anger, + disgust, fear, happiness, pleasant surprise, sadness, and neutral). + There are 2800 stimuli in total. + + Reference: + Toronto emotional speech set (TESS) https://tspace.library.utoronto.ca/handle/1807/24487 + https://doi.org/10.5683/SP2/E8H2MF + + Args: + mode (str, optional): It identifies the dataset mode (train or dev). Defaults to train. + n_folds (int, optional): Split the dataset into n folds. 1 fold for dev dataset and n-1 for train dataset. Defaults to 5. + split (int, optional): It specify the fold of dev dataset. Defaults to 1. + feat_type (str, optional): It identifies the feature type that user wants to extrace of an audio file. Defaults to raw. + archive(dict): it tells where to download the audio archive. Defaults to None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of TESS dataset. + + Examples: + + .. code-block:: python + + import paddle + + mode = 'dev' + tess_dataset = paddle.audio.datasets.TESS(mode=mode, + feat_type='raw') + for idx in range(5): + audio, label = tess_dataset[idx] + # do something with audio, label + print(audio.shape, label) + # [audio_data_length] , label_id + + tess_dataset = paddle.audio.datasets.TESS(mode=mode, + feat_type='mfcc', + n_mfcc=40) + for idx in range(5): + audio, label = tess_dataset[idx] + # do something with mfcc feature, label + print(audio.shape, label) + # [feature_dim, num_frames] , label_id + """ + + archive = { + 'url': 'https://bj.bcebos.com/paddleaudio/datasets/TESS_Toronto_emotional_speech_set.zip', + 'md5': '1465311b24d1de704c4c63e4ccc470c7', + } + + label_list = [ + 'angry', + 'disgust', + 'fear', + 'happy', + 'neutral', + 'ps', # pleasant surprise + 'sad', + ] + meta_info = collections.namedtuple( + 'META_INFO', ('speaker', 'word', 'emotion') + ) + audio_path = 'TESS_Toronto_emotional_speech_set' + + def __init__( + self, + mode: str = 'train', + n_folds: int = 5, + split: int = 1, + feat_type: str = 'raw', + archive=None, + **kwargs, + ): + assert isinstance(n_folds, int) and ( + n_folds >= 1 + ), f'the n_folds should be integer and n_folds >= 1, but got {n_folds}' + assert split in range( + 1, n_folds + 1 + ), f'The selected split should be integer and should be 1 <= split <= {n_folds}, but got {split}' + if archive is not None: + self.archive = archive + files, labels = self._get_data(mode, n_folds, split) + super(TESS, self).__init__( + files=files, labels=labels, feat_type=feat_type, **kwargs + ) + + def _get_meta_info(self, files) -> List[collections.namedtuple]: + ret = [] + for file in files: + basename_without_extend = os.path.basename(file)[:-4] + ret.append(self.meta_info(*basename_without_extend.split('_'))) + return ret + + def _get_data( + self, mode: str, n_folds: int, split: int + ) -> Tuple[List[str], List[int]]: + if not os.path.isdir(os.path.join(DATA_HOME, self.audio_path)): + download.get_path_from_url( + self.archive['url'], + DATA_HOME, + self.archive['md5'], + decompress=True, + ) + + wav_files = [] + for root, _, files in os.walk(os.path.join(DATA_HOME, self.audio_path)): + for file in files: + if file.endswith('.wav'): + wav_files.append(os.path.join(root, file)) + + meta_info = self._get_meta_info(wav_files) + + files = [] + labels = [] + for idx, sample in enumerate(meta_info): + _, _, emotion = sample + target = self.label_list.index(emotion) + fold = idx % n_folds + 1 + + if mode == 'train' and int(fold) != split: + files.append(wav_files[idx]) + labels.append(target) + + if mode != 'train' and int(fold) == split: + files.append(wav_files[idx]) + labels.append(target) + + return files, labels diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3c0bf499f1eff46f9f3b40f164c7cb66ecc39e75 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/__init__.py @@ -0,0 +1,24 @@ +# Copyright (c) 2022 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. +from .layers import LogMelSpectrogram # noqa: F401 +from .layers import MelSpectrogram # noqa: F401 +from .layers import MFCC # noqa: F401 +from .layers import Spectrogram # noqa: F401 + +__all__ = [ # noqa + 'LogMelSpectrogram', + 'MelSpectrogram', + 'MFCC', + 'Spectrogram', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..d21a24d34241fec6e921f258b3ea26de8e124bfe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/features/layers.py @@ -0,0 +1,394 @@ +# Copyright (c) 2022 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. +from functools import partial +from typing import Optional +from typing import Union + +import paddle +import paddle.nn as nn +from paddle import Tensor + +from ..functional import compute_fbank_matrix +from ..functional import create_dct +from ..functional import power_to_db +from ..functional.window import get_window + + +class Spectrogram(nn.Layer): + """Compute spectrogram of given signals, typically audio waveforms. + The spectorgram is defined as the complex norm of the short-time Fourier transformation. + + Args: + n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512. + hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None. + win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None. + window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'. + power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0. + center (bool, optional): Whether to pad `x` to make that the :math:`t \times hop\\_length` at the center of `t`-th frame. Defaults to True. + pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'. + dtype (str, optional): Data type of input and window. Defaults to 'float32'. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of Spectrogram. + + + + Examples: + .. code-block:: python + + import paddle + from paddle.audio.features import Spectrogram + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + + feature_extractor = Spectrogram(n_fft=512, window = 'hann', power = 1.0) + feats = feature_extractor(waveform) + """ + + def __init__(self, + n_fft: int = 512, + hop_length: Optional[int] = 512, + win_length: Optional[int] = None, + window: str = 'hann', + power: float = 1.0, + center: bool = True, + pad_mode: str = 'reflect', + dtype: str = 'float32') -> None: + super(Spectrogram, self).__init__() + + assert power > 0, 'Power of spectrogram must be > 0.' + self.power = power + + if win_length is None: + win_length = n_fft + + self.fft_window = get_window(window, + win_length, + fftbins=True, + dtype=dtype) + self._stft = partial(paddle.signal.stft, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=self.fft_window, + center=center, + pad_mode=pad_mode) + self.register_buffer('fft_window', self.fft_window) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor of waveforms with shape `(N, T)` + + Returns: + Tensor: Spectrograms with shape `(N, n_fft//2 + 1, num_frames)`. + """ + stft = self._stft(x) + spectrogram = paddle.pow(paddle.abs(stft), self.power) + return spectrogram + + +class MelSpectrogram(nn.Layer): + """Compute the melspectrogram of given signals, typically audio waveforms. It is computed by multiplying spectrogram with Mel filter bank matrix. + + Args: + sr (int, optional): Sample rate. Defaults to 22050. + n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512. + hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None. + win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None. + window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'. + power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0. + center (bool, optional): Whether to pad `x` to make that the :math:`t \times hop\\_length` at the center of `t`-th frame. Defaults to True. + pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'. + n_mels (int, optional): Number of mel bins. Defaults to 64. + f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0. + f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None. + htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False. + norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'. + dtype (str, optional): Data type of input and window. Defaults to 'float32'. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MelSpectrogram. + + Examples: + .. code-block:: python + + import paddle + from paddle.audio.features import MelSpectrogram + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + + feature_extractor = MelSpectrogram(sr=sample_rate, n_fft=512, window = 'hann', power = 1.0) + feats = feature_extractor(waveform) + """ + + def __init__(self, + sr: int = 22050, + n_fft: int = 2048, + hop_length: Optional[int] = 512, + win_length: Optional[int] = None, + window: str = 'hann', + power: float = 2.0, + center: bool = True, + pad_mode: str = 'reflect', + n_mels: int = 64, + f_min: float = 50.0, + f_max: Optional[float] = None, + htk: bool = False, + norm: Union[str, float] = 'slaney', + dtype: str = 'float32') -> None: + super(MelSpectrogram, self).__init__() + + self._spectrogram = Spectrogram(n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + power=power, + center=center, + pad_mode=pad_mode, + dtype=dtype) + self.n_mels = n_mels + self.f_min = f_min + self.f_max = f_max + self.htk = htk + self.norm = norm + if f_max is None: + f_max = sr // 2 + self.fbank_matrix = compute_fbank_matrix(sr=sr, + n_fft=n_fft, + n_mels=n_mels, + f_min=f_min, + f_max=f_max, + htk=htk, + norm=norm, + dtype=dtype) + self.register_buffer('fbank_matrix', self.fbank_matrix) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor of waveforms with shape `(N, T)` + + Returns: + Tensor: Mel spectrograms with shape `(N, n_mels, num_frames)`. + """ + spect_feature = self._spectrogram(x) + mel_feature = paddle.matmul(self.fbank_matrix, spect_feature) + return mel_feature + + +class LogMelSpectrogram(nn.Layer): + """Compute log-mel-spectrogram feature of given signals, typically audio waveforms. + + Args: + sr (int, optional): Sample rate. Defaults to 22050. + n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512. + hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None. + win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None. + window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'. + power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0. + center (bool, optional): Whether to pad `x` to make that the :math:`t \times hop\\_length` at the center of `t`-th frame. Defaults to True. + pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'. + n_mels (int, optional): Number of mel bins. Defaults to 64. + f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0. + f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None. + htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False. + norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'. + ref_value (float, optional): The reference value. If smaller than 1.0, the db level of the signal will be pulled up accordingly. Otherwise, the db level is pushed down. Defaults to 1.0. + amin (float, optional): The minimum value of input magnitude. Defaults to 1e-10. + top_db (Optional[float], optional): The maximum db value of spectrogram. Defaults to None. + dtype (str, optional): Data type of input and window. Defaults to 'float32'. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of LogMelSpectrogram. + + Examples: + .. code-block:: python + + import paddle + from paddle.audio.features import LogMelSpectrogram + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + + feature_extractor = LogMelSpectrogram(sr=sample_rate, n_fft=512, window = 'hann', power = 1.0) + feats = feature_extractor(waveform) + """ + + def __init__(self, + sr: int = 22050, + n_fft: int = 512, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: str = 'hann', + power: float = 2.0, + center: bool = True, + pad_mode: str = 'reflect', + n_mels: int = 64, + f_min: float = 50.0, + f_max: Optional[float] = None, + htk: bool = False, + norm: Union[str, float] = 'slaney', + ref_value: float = 1.0, + amin: float = 1e-10, + top_db: Optional[float] = None, + dtype: str = 'float32') -> None: + super(LogMelSpectrogram, self).__init__() + + self._melspectrogram = MelSpectrogram(sr=sr, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + power=power, + center=center, + pad_mode=pad_mode, + n_mels=n_mels, + f_min=f_min, + f_max=f_max, + htk=htk, + norm=norm, + dtype=dtype) + + self.ref_value = ref_value + self.amin = amin + self.top_db = top_db + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor of waveforms with shape `(N, T)` + + Returns: + Tensor: Log mel spectrograms with shape `(N, n_mels, num_frames)`. + """ + mel_feature = self._melspectrogram(x) + log_mel_feature = power_to_db(mel_feature, + ref_value=self.ref_value, + amin=self.amin, + top_db=self.top_db) + return log_mel_feature + + +class MFCC(nn.Layer): + """Compute mel frequency cepstral coefficients(MFCCs) feature of given waveforms. + + Args: + sr (int, optional): Sample rate. Defaults to 22050. + n_mfcc (int, optional): [description]. Defaults to 40. + n_fft (int, optional): The number of frequency components of the discrete Fourier transform. Defaults to 512. + hop_length (Optional[int], optional): The hop length of the short time FFT. If `None`, it is set to `win_length//4`. Defaults to None. + win_length (Optional[int], optional): The window length of the short time FFT. If `None`, it is set to same as `n_fft`. Defaults to None. + window (str, optional): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'kaiser', 'gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. Defaults to 'hann'. + power (float, optional): Exponent for the magnitude spectrogram. Defaults to 2.0. + center (bool, optional): Whether to pad `x` to make that the :math:`t \times hop\\_length` at the center of `t`-th frame. Defaults to True. + pad_mode (str, optional): Choose padding pattern when `center` is `True`. Defaults to 'reflect'. + n_mels (int, optional): Number of mel bins. Defaults to 64. + f_min (float, optional): Minimum frequency in Hz. Defaults to 50.0. + f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None. + htk (bool, optional): Use HTK formula in computing fbank matrix. Defaults to False. + norm (Union[str, float], optional): Type of normalization in computing fbank matrix. Slaney-style is used by default. You can specify norm=1.0/2.0 to use customized p-norm normalization. Defaults to 'slaney'. + ref_value (float, optional): The reference value. If smaller than 1.0, the db level of the signal will be pulled up accordingly. Otherwise, the db level is pushed down. Defaults to 1.0. + amin (float, optional): The minimum value of input magnitude. Defaults to 1e-10. + top_db (Optional[float], optional): The maximum db value of spectrogram. Defaults to None. + dtype (str, optional): Data type of input and window. Defaults to 'float32'. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MFCC. + + Examples: + .. code-block:: python + + import paddle + from paddle.audio.features import MFCC + + sample_rate = 16000 + wav_duration = 0.5 + num_channels = 1 + num_frames = sample_rate * wav_duration + wav_data = paddle.linspace(-1.0, 1.0, num_frames) * 0.1 + waveform = wav_data.tile([num_channels, 1]) + + feature_extractor = MFCC(sr=sample_rate, n_fft=512, window = 'hann') + feats = feature_extractor(waveform) + """ + + def __init__(self, + sr: int = 22050, + n_mfcc: int = 40, + n_fft: int = 512, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: str = 'hann', + power: float = 2.0, + center: bool = True, + pad_mode: str = 'reflect', + n_mels: int = 64, + f_min: float = 50.0, + f_max: Optional[float] = None, + htk: bool = False, + norm: Union[str, float] = 'slaney', + ref_value: float = 1.0, + amin: float = 1e-10, + top_db: Optional[float] = None, + dtype: str = 'float32') -> None: + super(MFCC, self).__init__() + assert n_mfcc <= n_mels, 'n_mfcc cannot be larger than n_mels: %d vs %d' % ( + n_mfcc, n_mels) + self._log_melspectrogram = LogMelSpectrogram(sr=sr, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + power=power, + center=center, + pad_mode=pad_mode, + n_mels=n_mels, + f_min=f_min, + f_max=f_max, + htk=htk, + norm=norm, + ref_value=ref_value, + amin=amin, + top_db=top_db, + dtype=dtype) + self.dct_matrix = create_dct(n_mfcc=n_mfcc, n_mels=n_mels, dtype=dtype) + self.register_buffer('dct_matrix', self.dct_matrix) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor of waveforms with shape `(N, T)` + + Returns: + Tensor: Mel frequency cepstral coefficients with shape `(N, n_mfcc, num_frames)`. + """ + log_mel_feature = self._log_melspectrogram(x) + mfcc = paddle.matmul(log_mel_feature.transpose( + (0, 2, 1)), self.dct_matrix).transpose((0, 2, 1)) # (B, n_mels, L) + return mfcc diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7db53d6c22a6f1206e8f615252bc4ba73c4647b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/__init__.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022 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. +from .functional import compute_fbank_matrix # noqa: F401 +from .functional import create_dct # noqa: F401 +from .functional import fft_frequencies # noqa: F401 +from .functional import hz_to_mel # noqa: F401 +from .functional import mel_frequencies # noqa: F401 +from .functional import mel_to_hz # noqa: F401 +from .functional import power_to_db # noqa: F401 +from .window import get_window # noqa: F401 + +__all__ = [ # noqa + 'compute_fbank_matrix', + 'create_dct', + 'fft_frequencies', + 'hz_to_mel', + 'mel_frequencies', + 'mel_to_hz', + 'power_to_db', + 'get_window', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/functional.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6a7856f429cb07c4d6292e8e51dd893ea213f3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/functional.py @@ -0,0 +1,327 @@ +# Copyright (c) 2022 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. +# Modified from librosa(https://github.com/librosa/librosa) +import math +from typing import Optional +from typing import Union + +import paddle +from paddle import Tensor + + +def hz_to_mel(freq: Union[Tensor, float], + htk: bool = False) -> Union[Tensor, float]: + """Convert Hz to Mels. + + Args: + freq (Union[Tensor, float]): The input tensor with arbitrary shape. + htk (bool, optional): Use htk scaling. Defaults to False. + + Returns: + Union[Tensor, float]: Frequency in mels. + + Examples: + .. code-block:: python + + import paddle + + val = 3.0 + htk_flag = True + mel_paddle_tensor = paddle.audio.functional.hz_to_mel( + paddle.to_tensor(val), htk_flag) + """ + + if htk: + if isinstance(freq, Tensor): + return 2595.0 * paddle.log10(1.0 + freq / 700.0) + else: + return 2595.0 * math.log10(1.0 + freq / 700.0) + + # Fill in the linear part + f_min = 0.0 + f_sp = 200.0 / 3 + + mels = (freq - f_min) / f_sp + + # Fill in the log-scale part + + min_log_hz = 1000.0 # beginning of log region (Hz) + min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) + logstep = math.log(6.4) / 27.0 # step size for log region + + if isinstance(freq, Tensor): + target = min_log_mel + paddle.log( + freq / min_log_hz + 1e-10) / logstep # prevent nan with 1e-10 + mask = (freq > min_log_hz).astype(freq.dtype) + mels = target * mask + mels * ( + 1 - mask) # will replace by masked_fill OP in future + else: + if freq >= min_log_hz: + mels = min_log_mel + math.log(freq / min_log_hz + 1e-10) / logstep + + return mels + + +def mel_to_hz(mel: Union[float, Tensor], + htk: bool = False) -> Union[float, Tensor]: + """Convert mel bin numbers to frequencies. + + Args: + mel (Union[float, Tensor]): The mel frequency represented as a tensor with arbitrary shape. + htk (bool, optional): Use htk scaling. Defaults to False. + + Returns: + Union[float, Tensor]: Frequencies in Hz. + + Examples: + .. code-block:: python + + import paddle + + val = 3.0 + htk_flag = True + mel_paddle_tensor = paddle.audio.functional.mel_to_hz( + paddle.to_tensor(val), htk_flag) + + """ + if htk: + return 700.0 * (10.0**(mel / 2595.0) - 1.0) + + f_min = 0.0 + f_sp = 200.0 / 3 + freqs = f_min + f_sp * mel + # And now the nonlinear scale + min_log_hz = 1000.0 # beginning of log region (Hz) + min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) + logstep = math.log(6.4) / 27.0 # step size for log region + if isinstance(mel, Tensor): + target = min_log_hz * paddle.exp(logstep * (mel - min_log_mel)) + mask = (mel > min_log_mel).astype(mel.dtype) + freqs = target * mask + freqs * ( + 1 - mask) # will replace by masked_fill OP in future + else: + if mel >= min_log_mel: + freqs = min_log_hz * math.exp(logstep * (mel - min_log_mel)) + return freqs + + +def mel_frequencies(n_mels: int = 64, + f_min: float = 0.0, + f_max: float = 11025.0, + htk: bool = False, + dtype: str = 'float32') -> Tensor: + """Compute mel frequencies. + + Args: + n_mels (int, optional): Number of mel bins. Defaults to 64. + f_min (float, optional): Minimum frequency in Hz. Defaults to 0.0. + fmax (float, optional): Maximum frequency in Hz. Defaults to 11025.0. + htk (bool, optional): Use htk scaling. Defaults to False. + dtype (str, optional): The data type of the return frequencies. Defaults to 'float32'. + + Returns: + Tensor: Tensor of n_mels frequencies in Hz with shape `(n_mels,)`. + + Examples: + .. code-block:: python + + import paddle + + n_mels = 64 + f_min = 0.5 + f_max = 10000 + htk_flag = True + + paddle_mel_freq = paddle.audio.functional.mel_frequencies( + n_mels, f_min, f_max, htk_flag, 'float64') + """ + # 'Center freqs' of mel bands - uniformly spaced between limits + min_mel = hz_to_mel(f_min, htk=htk) + max_mel = hz_to_mel(f_max, htk=htk) + mels = paddle.linspace(min_mel, max_mel, n_mels, dtype=dtype) + freqs = mel_to_hz(mels, htk=htk) + return freqs + + +def fft_frequencies(sr: int, n_fft: int, dtype: str = 'float32') -> Tensor: + """Compute fourier frequencies. + + Args: + sr (int): Sample rate. + n_fft (int): Number of fft bins. + dtype (str, optional): The data type of the return frequencies. Defaults to 'float32'. + + Returns: + Tensor: FFT frequencies in Hz with shape `(n_fft//2 + 1,)`. + + Examples: + .. code-block:: python + + import paddle + + sr = 16000 + n_fft = 128 + fft_freq = paddle.audio.functional.fft_frequencies(sr, n_fft) + """ + return paddle.linspace(0, float(sr) / 2, int(1 + n_fft // 2), dtype=dtype) + + +def compute_fbank_matrix(sr: int, + n_fft: int, + n_mels: int = 64, + f_min: float = 0.0, + f_max: Optional[float] = None, + htk: bool = False, + norm: Union[str, float] = 'slaney', + dtype: str = 'float32') -> Tensor: + """Compute fbank matrix. + + Args: + sr (int): Sample rate. + n_fft (int): Number of fft bins. + n_mels (int, optional): Number of mel bins. Defaults to 64. + f_min (float, optional): Minimum frequency in Hz. Defaults to 0.0. + f_max (Optional[float], optional): Maximum frequency in Hz. Defaults to None. + htk (bool, optional): Use htk scaling. Defaults to False. + norm (Union[str, float], optional): Type of normalization. Defaults to 'slaney'. + dtype (str, optional): The data type of the return matrix. Defaults to 'float32'. + + Returns: + Tensor: Mel transform matrix with shape `(n_mels, n_fft//2 + 1)`. + + Examples: + .. code-block:: python + + import paddle + + n_mfcc = 23 + n_mels = 51 + paddle_dct = paddle.audio.functional.create_dct(n_mfcc, n_mels) + """ + + if f_max is None: + f_max = float(sr) / 2 + + # Initialize the weights + weights = paddle.zeros((n_mels, int(1 + n_fft // 2)), dtype=dtype) + + # Center freqs of each FFT bin + fftfreqs = fft_frequencies(sr=sr, n_fft=n_fft, dtype=dtype) + + # 'Center freqs' of mel bands - uniformly spaced between limits + mel_f = mel_frequencies(n_mels + 2, + f_min=f_min, + f_max=f_max, + htk=htk, + dtype=dtype) + + fdiff = mel_f[1:] - mel_f[:-1] #np.diff(mel_f) + ramps = mel_f.unsqueeze(1) - fftfreqs.unsqueeze(0) + #ramps = np.subtract.outer(mel_f, fftfreqs) + + for i in range(n_mels): + # lower and upper slopes for all bins + lower = -ramps[i] / fdiff[i] + upper = ramps[i + 2] / fdiff[i + 1] + + # .. then intersect them with each other and zero + weights[i] = paddle.maximum(paddle.zeros_like(lower), + paddle.minimum(lower, upper)) + + # Slaney-style mel is scaled to be approx constant energy per channel + if norm == 'slaney': + enorm = 2.0 / (mel_f[2:n_mels + 2] - mel_f[:n_mels]) + weights *= enorm.unsqueeze(1) + elif isinstance(norm, int) or isinstance(norm, float): + weights = paddle.nn.functional.normalize(weights, p=norm, axis=-1) + + return weights + + +def power_to_db(spect: Tensor, + ref_value: float = 1.0, + amin: float = 1e-10, + top_db: Optional[float] = 80.0) -> Tensor: + """Convert a power spectrogram (amplitude squared) to decibel (dB) units. The function computes the scaling `10 * log10(x / ref)` in a numerically stable way. + + Args: + spect (Tensor): STFT power spectrogram. + ref_value (float, optional): The reference value. If smaller than 1.0, the db level of the signal will be pulled up accordingly. Otherwise, the db level is pushed down. Defaults to 1.0. + amin (float, optional): Minimum threshold. Defaults to 1e-10. + top_db (Optional[float], optional): Threshold the output at `top_db` below the peak. Defaults to None. + + Returns: + Tensor: Power spectrogram in db scale. + + Examples: + .. code-block:: python + + import paddle + + val = 3.0 + decibel_paddle = paddle.audio.functional.power_to_db( + paddle.to_tensor(val)) + """ + if amin <= 0: + raise Exception("amin must be strictly positive") + + if ref_value <= 0: + raise Exception("ref_value must be strictly positive") + + ones = paddle.ones_like(spect) + log_spec = 10.0 * paddle.log10(paddle.maximum(ones * amin, spect)) + log_spec -= 10.0 * math.log10(max(ref_value, amin)) + + if top_db is not None: + if top_db < 0: + raise Exception("top_db must be non-negative") + log_spec = paddle.maximum(log_spec, ones * (log_spec.max() - top_db)) + + return log_spec + + +def create_dct(n_mfcc: int, + n_mels: int, + norm: Optional[str] = 'ortho', + dtype: str = 'float32') -> Tensor: + """Create a discrete cosine transform(DCT) matrix. + + Args: + n_mfcc (int): Number of mel frequency cepstral coefficients. + n_mels (int): Number of mel filterbanks. + norm (Optional[str], optional): Normalizaiton type. Defaults to 'ortho'. + dtype (str, optional): The data type of the return matrix. Defaults to 'float32'. + + Returns: + Tensor: The DCT matrix with shape `(n_mels, n_mfcc)`. + + Examples: + .. code-block:: python + + import paddle + n_mfcc = 23 + n_mels = 257 + dct = paddle.audio.functional.create_dct(n_mfcc, n_mels) + """ + n = paddle.arange(n_mels, dtype=dtype) + k = paddle.arange(n_mfcc, dtype=dtype).unsqueeze(1) + dct = paddle.cos(math.pi / float(n_mels) * (n + 0.5) * + k) # size (n_mfcc, n_mels) + if norm is None: + dct *= 2.0 + else: + assert norm == "ortho" + dct[0] *= 1.0 / math.sqrt(2.0) + dct *= math.sqrt(2.0 / float(n_mels)) + return dct.T diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/window.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/window.py new file mode 100644 index 0000000000000000000000000000000000000000..472c56b87acf95db0dc0c04f487af90caa5a3bb4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/audio/functional/window.py @@ -0,0 +1,385 @@ +# Copyright (c) 2022 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 +import math +from typing import List +from typing import Tuple +from typing import Union + +import paddle +from paddle import Tensor + + +class WindowFunctionRegister(object): + def __init__(self): + self._functions_dict = dict() + + def register(self, func=None): + def add_subfunction(func): + name = func.__name__ + self._functions_dict[name] = func + return func + + return add_subfunction + + def get(self, name): + return self._functions_dict[name] + + +window_function_register = WindowFunctionRegister() + + +@window_function_register.register() +def _cat(x: List[Tensor], data_type: str) -> Tensor: + l = [paddle.to_tensor(_, data_type) for _ in x] + return paddle.concat(l) + + +@window_function_register.register() +def _acosh(x: Union[Tensor, float]) -> Tensor: + if isinstance(x, float): + return math.log(x + math.sqrt(x**2 - 1)) + return paddle.log(x + paddle.sqrt(paddle.square(x) - 1)) + + +@window_function_register.register() +def _extend(M: int, sym: bool) -> bool: + """Extend window by 1 sample if needed for DFT-even symmetry.""" + if not sym: + return M + 1, True + else: + return M, False + + +@window_function_register.register() +def _len_guards(M: int) -> bool: + """Handle small or incorrect window lengths.""" + if int(M) != M or M < 0: + raise ValueError('Window length M must be a non-negative integer') + + return M <= 1 + + +@window_function_register.register() +def _truncate(w: Tensor, needed: bool) -> Tensor: + """Truncate window by 1 sample if needed for DFT-even symmetry.""" + if needed: + return w[:-1] + else: + return w + + +@window_function_register.register() +def _general_gaussian( + M: int, p, sig, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a window with a generalized Gaussian shape. + This function is consistent with scipy.signal.windows.general_gaussian(). + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + + n = paddle.arange(0, M, dtype=dtype) - (M - 1.0) / 2.0 + w = paddle.exp(-0.5 * paddle.abs(n / sig) ** (2 * p)) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _general_cosine( + M: int, a: float, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a generic weighted sum of cosine terms window. + This function is consistent with scipy.signal.windows.general_cosine(). + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + fac = paddle.linspace(-math.pi, math.pi, M, dtype=dtype) + w = paddle.zeros((M,), dtype=dtype) + for k in range(len(a)): + w += a[k] * paddle.cos(k * fac) + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _general_hamming( + M: int, alpha: float, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a generalized Hamming window. + This function is consistent with scipy.signal.windows.general_hamming() + """ + return _general_cosine(M, [alpha, 1.0 - alpha], sym, dtype=dtype) + + +@window_function_register.register() +def _taylor( + M: int, nbar=4, sll=30, norm=True, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a Taylor window. + The Taylor window taper function approximates the Dolph-Chebyshev window's + constant sidelobe level for a parameterized number of near-in sidelobes. + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + # Original text uses a negative sidelobe level parameter and then negates + # it in the calculation of B. To keep consistent with other methods we + # assume the sidelobe level parameter to be positive. + B = 10 ** (sll / 20) + A = _acosh(B) / math.pi + s2 = nbar**2 / (A**2 + (nbar - 0.5) ** 2) + ma = paddle.arange(1, nbar, dtype=dtype) + + Fm = paddle.empty((nbar - 1,), dtype=dtype) + signs = paddle.empty_like(ma) + signs[::2] = 1 + signs[1::2] = -1 + m2 = ma * ma + for mi in range(len(ma)): + numer = signs[mi] * paddle.prod( + 1 - m2[mi] / s2 / (A**2 + (ma - 0.5) ** 2) + ) + if mi == 0: + denom = 2 * paddle.prod(1 - m2[mi] / m2[mi + 1 :]) + elif mi == len(ma) - 1: + denom = 2 * paddle.prod(1 - m2[mi] / m2[:mi]) + else: + denom = ( + 2 + * paddle.prod(1 - m2[mi] / m2[:mi]) + * paddle.prod(1 - m2[mi] / m2[mi + 1 :]) + ) + + Fm[mi] = numer / denom + + def W(n): + return 1 + 2 * paddle.matmul( + Fm.unsqueeze(0), + paddle.cos(2 * math.pi * ma.unsqueeze(1) * (n - M / 2.0 + 0.5) / M), + ) + + w = W(paddle.arange(0, M, dtype=dtype)) + + # normalize (Note that this is not described in the original text [1]) + if norm: + scale = 1.0 / W((M - 1) / 2) + w *= scale + w = w.squeeze() + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _hamming(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a Hamming window. + The Hamming window is a taper formed by using a raised cosine with + non-zero endpoints, optimized to minimize the nearest side lobe. + """ + return _general_hamming(M, 0.54, sym, dtype=dtype) + + +@window_function_register.register() +def _hann(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a Hann window. + The Hann window is a taper formed by using a raised cosine or sine-squared + with ends that touch zero. + """ + return _general_hamming(M, 0.5, sym, dtype=dtype) + + +@window_function_register.register() +def _tukey( + M: int, alpha=0.5, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a Tukey window. + The Tukey window is also known as a tapered cosine window. + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + + if alpha <= 0: + return paddle.ones((M,), dtype=dtype) + elif alpha >= 1.0: + return hann(M, sym=sym) + + M, needs_trunc = _extend(M, sym) + + n = paddle.arange(0, M, dtype=dtype) + width = int(alpha * (M - 1) / 2.0) + n1 = n[0 : width + 1] + n2 = n[width + 1 : M - width - 1] + n3 = n[M - width - 1 :] + + w1 = 0.5 * (1 + paddle.cos(math.pi * (-1 + 2.0 * n1 / alpha / (M - 1)))) + w2 = paddle.ones(n2.shape, dtype=dtype) + w3 = 0.5 * ( + 1 + + paddle.cos(math.pi * (-2.0 / alpha + 1 + 2.0 * n3 / alpha / (M - 1))) + ) + w = paddle.concat([w1, w2, w3]) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _gaussian( + M: int, std: float, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute a Gaussian window. + The Gaussian widows has a Gaussian shape defined by the standard deviation(std). + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + + n = paddle.arange(0, M, dtype=dtype) - (M - 1.0) / 2.0 + sig2 = 2 * std * std + w = paddle.exp(-(n**2) / sig2) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _exponential( + M: int, center=None, tau=1.0, sym: bool = True, dtype: str = 'float64' +) -> Tensor: + """Compute an exponential (or Poisson) window.""" + if sym and center is not None: + raise ValueError("If sym==True, center must be None.") + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + + if center is None: + center = (M - 1) / 2 + + n = paddle.arange(0, M, dtype=dtype) + w = paddle.exp(-paddle.abs(n - center) / tau) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _triang(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a triangular window.""" + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + + n = paddle.arange(1, (M + 1) // 2 + 1, dtype=dtype) + if M % 2 == 0: + w = (2 * n - 1.0) / M + w = paddle.concat([w, w[::-1]]) + else: + w = 2 * n / (M + 1.0) + w = paddle.concat([w, w[-2::-1]]) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _bohman(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a Bohman window. + The Bohman window is the autocorrelation of a cosine window. + """ + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + + fac = paddle.abs(paddle.linspace(-1, 1, M, dtype=dtype)[1:-1]) + w = (1 - fac) * paddle.cos(math.pi * fac) + 1.0 / math.pi * paddle.sin( + math.pi * fac + ) + w = _cat([0, w, 0], dtype) + + return _truncate(w, needs_trunc) + + +@window_function_register.register() +def _blackman(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a Blackman window. + The Blackman window is a taper formed by using the first three terms of + a summation of cosines. It was designed to have close to the minimal + leakage possible. It is close to optimal, only slightly worse than a + Kaiser window. + """ + return _general_cosine(M, [0.42, 0.50, 0.08], sym, dtype=dtype) + + +@window_function_register.register() +def _cosine(M: int, sym: bool = True, dtype: str = 'float64') -> Tensor: + """Compute a window with a simple cosine shape.""" + if _len_guards(M): + return paddle.ones((M,), dtype=dtype) + M, needs_trunc = _extend(M, sym) + w = paddle.sin(math.pi / M * (paddle.arange(0, M, dtype=dtype) + 0.5)) + + return _truncate(w, needs_trunc) + + +def get_window( + window: Union[str, Tuple[str, float]], + win_length: int, + fftbins: bool = True, + dtype: str = 'float64', +) -> Tensor: + """Return a window of a given length and type. + + Args: + window (Union[str, Tuple[str, float]]): The window function applied to the signal before the Fourier transform. Supported window functions: 'hamming', 'hann', 'gaussian', 'general_gaussian', 'exponential', 'triang', 'bohman', 'blackman', 'cosine', 'tukey', 'taylor'. + win_length (int): Number of samples. + fftbins (bool, optional): If True, create a "periodic" window. Otherwise, create a "symmetric" window, for use in filter design. Defaults to True. + dtype (str, optional): The data type of the return window. Defaults to 'float64'. + + Returns: + Tensor: The window represented as a tensor. + + Examples: + .. code-block:: python + + import paddle + + n_fft = 512 + cosine_window = paddle.audio.functional.get_window('cosine', n_fft) + + std = 7 + gaussian_window = paddle.audio.functional.get_window(('gaussian',std), n_fft) + """ + sym = not fftbins + + args = () + if isinstance(window, tuple): + winstr = window[0] + if len(window) > 1: + args = window[1:] + elif isinstance(window, str): + if window in ['gaussian', 'exponential']: + raise ValueError( + "The '" + window + "' window needs one or " + "more parameters -- pass a tuple." + ) + else: + winstr = window + else: + raise ValueError( + "%s as window type is not supported." % str(type(window)) + ) + + try: + winfunc = window_function_register.get('_' + winstr) + except KeyError as e: + raise ValueError("Unknown window type.") from e + + params = (win_length,) + args + kwargs = {'sym': sym} + return winfunc(*params, dtype=dtype, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc7b11368680e7f714e2b15a0033b0a21068fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/__init__.py @@ -0,0 +1,34 @@ +# Copyright (c) 2021 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. + +from ..fluid.dygraph.base import grad # noqa: F401 +from ..fluid.dygraph.base import no_grad_ as no_grad # noqa: F401 +from ..framework import is_grad_enabled, set_grad_enabled # noqa: F401 +from . import backward_mode # noqa: F401 +from .backward_mode import backward # noqa: F401 +from ..fluid.framework import _in_eager_mode_ +if _in_eager_mode_: + from .py_layer import EagerPyLayer as PyLayer # noqa: F401 + from .py_layer import EagerPyLayerContext as PyLayerContext # noqa: F401 +else: + from .py_layer import LegacyPyLayer as PyLayer # noqa: F401 + from .py_layer import LegacyPyLayerContext as PyLayerContext # noqa: F401 +from ..framework import set_grad_enabled, is_grad_enabled # noqa: F401 +from ..fluid.dygraph.base import no_grad_ as no_grad # noqa: F401 + +__all__ = [ # noqa + 'backward', + 'PyLayer', + 'PyLayerContext', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/backward_mode.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/backward_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..d2c2beadf386bc3bd1150ed3e6199b500975a1ec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/backward_mode.py @@ -0,0 +1,128 @@ +# Copyright (c) 2021 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. + +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid.backward import gradients_with_optimizer +import paddle + +__all__ = [] + + +@framework.dygraph_only +def backward(tensors, grad_tensors=None, retain_graph=False): + """ + Compute the backward gradients of given tensors. + + Args: + tensors(list of Tensors): the tensors which the gradient to be computed. The tensors can not contain the same tensor. + + grad_tensors(list of Tensors of None, optional): the init gradients of the `tensors`` .If not None, it must have the same length with ``tensors`` , + and if any of the elements is None, then the init gradient is the default value which is filled with 1.0. + If None, all the gradients of the ``tensors`` is the default value which is filled with 1.0. + Defaults to None. + + retain_graph(bool, optional): If False, the graph used to compute grads will be freed. If you would + like to add more ops to the built graph after calling this method( :code:`backward` ), set the parameter + :code:`retain_graph` to True, then the grads will be retained. Thus, seting it to False is much more memory-efficient. + Defaults to False. + + Returns: + NoneType: None + + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([[1, 2], [3, 4]], dtype='float32', stop_gradient=False) + y = paddle.to_tensor([[3, 2], [3, 4]], dtype='float32') + + grad_tensor1 = paddle.to_tensor([[1,2], [2, 3]], dtype='float32') + grad_tensor2 = paddle.to_tensor([[1,1], [1, 1]], dtype='float32') + + z1 = paddle.matmul(x, y) + z2 = paddle.matmul(x, y) + + paddle.autograd.backward([z1, z2], [grad_tensor1, grad_tensor2], True) + print(x.grad) + #[[12. 18.] + # [17. 25.]] + + x.clear_grad() + + paddle.autograd.backward([z1, z2], [grad_tensor1, None], True) + print(x.grad) + #[[12. 18.] + # [17. 25.]] + + x.clear_grad() + + paddle.autograd.backward([z1, z2]) + print(x.grad) + #[[10. 14.] + # [10. 14.]] + + """ + + def check_tensors(in_out_list, name): + assert in_out_list is not None, "{} should not be None".format(name) + + if isinstance(in_out_list, (list, tuple)): + assert len(in_out_list) > 0, "{} connot be empyt".format(name) + for each_var in in_out_list: + assert isinstance( + each_var, + (paddle.Tensor, core.eager.Tensor + )), "Elements of {} must be paddle.Tensor".format(name) + return in_out_list + else: + assert isinstance( + in_out_list, + (paddle.Tensor, core.eager.Tensor + )), "{} must be Tensor or list of Tensor".format(name) + return [in_out_list] + + tensors = check_tensors(tensors, "tensors") + + assert len(tensors) == len( + set(tensors) + ), "The argument 'tensors' of paddle.autograd.backward contains duplicate paddle.Tensor object." + + if grad_tensors is not None: + if not isinstance(grad_tensors, (list, tuple)): + grad_tensors = [grad_tensors] + + for each_tensor in grad_tensors: + if each_tensor is not None: + assert isinstance( + each_tensor, (paddle.Tensor, core.eager.Tensor) + ), "The argument 'grad_tensors' of paddle.autograd.backward is invalid, it can be 'None', 'paddle.Tensor' or 'list[None/paddle.Tensor]'." + else: + if framework._in_eager_mode_: + grad_tensors = [] + else: + grad_tensors = [None] * len(tensors) + + if len(grad_tensors) > 0: + assert len(tensors) == len( + grad_tensors), "The length of grad_tensors must be equal to tensors" + + assert isinstance(retain_graph, bool), "retain_graph must be True or False" + + if framework._in_eager_mode_: + core.eager.run_backward(tensors, grad_tensors, retain_graph) + else: + core.dygraph_run_backward(tensors, grad_tensors, retain_graph, + framework._dygraph_tracer()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/py_layer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/py_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..254aabb04b3cb136ae624c70916112a449cbfaf1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/autograd/py_layer.py @@ -0,0 +1,648 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.fluid.framework import dygraph_only +from paddle.fluid.dygraph.amp.auto_cast import amp_state +from paddle.amp.auto_cast import auto_cast +from paddle.fluid import core + +__all__ = [] + + +class LegacyPyLayerContext(object): + """ + The object of this class is a context that is used in PyLayer to enhance the function. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + # ctx is a object of PyLayerContext. + y = paddle.tanh(x) + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # ctx is a object of PyLayerContext. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + + def __init__(self): + self.container = None + self._amp_state = amp_state() + + def save_for_backward(self, *tensors): + """ + Saves given tensors that backward need. Use ``saved_tensor`` in the `backward` to get the saved tensors. + + Note: + This API should be called at most once, and only inside `forward`. + + Args: + tensors(list of Tensors): Tensors to be stored. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + # ctx is a context object that store some objects for backward. + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + + """ + self.container = tensors + + def saved_tensor(self): + """ + Get the tensors stored by ``save_for_backward``. + + Returns: + list of Tensors or None: If context contains tensors stored by `save_for_backward`, + then return these tensors, otherwise return None. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + # ctx is a context object that store some objects for backward. + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + + return self.container + + +def with_mateclass(meta, *bases): + class impl(meta): + def __new__(cls, name, temp_bases, attrs): + return meta(name, bases, attrs) + + return type.__new__(impl, "impl", (), {}) + + +class CPyLayer(object): + @classmethod + @dygraph_only + def apply(cls, *args, **kwargs): + """ + After building the custom PyLayer, run it through the ``apply``. + + Args: + *args(tuple): input of PyLayer. + **kwargs(dict): input of PyLayer. + + Returns: + tensors or other types : output of PyLayer. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x, func1, func2=paddle.square): + ctx.func = func2 + y = func1(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - ctx.func(y)) + return grad + + + data = paddle.randn([2, 3], dtype="float64") + data.stop_gradient = False + # run custom Layer. + z = cus_tanh.apply(data, func1=paddle.tanh) + """ + place = paddle.fluid.framework._current_expected_place() + with paddle.fluid.dygraph.no_grad(): + return core.pylayer_apply(place, cls, *args, **kwargs) + + +class PyLayerBackward(LegacyPyLayerContext): + def backward(self, *args, **kwargs): + with paddle.fluid.dygraph.guard(): + with paddle.fluid.dygraph.no_grad(): + if ( + self._amp_state + and 'enable' in self._amp_state + and self._amp_state['enable'] + ): + with auto_cast(**args[0]._amp_state): + return self._forward_cls.backward(*args, **kwargs) + else: + + return self._forward_cls.backward(*args, **kwargs) + return self._forward_cls.backward(*args, **kwargs) + + +class LayerMeta(type): + def __init__(cls, name, bases, attrs): + cls._backward_function = type( + name + '_backward', (PyLayerBackward,), {"_forward_cls": cls} + ) + + return super(LayerMeta, cls).__init__(name, bases, attrs) + + +class LegacyPyLayer(with_mateclass(LayerMeta, CPyLayer)): + """ + Build a custom `Layer` by creating subclasses. Subclasses need to follow the following rules: + 1. Subclasses contain `forward` and `backward` function. Both forward and backward are @staticmethod. + Their first argument should be a context and `None` can not be included in the returned result. + 2. Input of backward contains a context as the first argument, and the rest arguments are the + gradient of forward's output tensors. so the number of backward's input tensors equal to + the number of forward output tensors. If you need the forward's inputs or outputs in `backward`, + you can use `save_for_backward` to store the required tensors, and then use them in the backward. + 3. Output of backward function can only be `Tensor` or tuple/list of `Tensor`. + Output tensors of backward are the gradient of forward's input tensors, + so the number of backward's output tensors equal to the number of forward input tensors. + After building the custom Layer, run it through the `apply` method. + + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + # Inherit from PyLayer + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x, func1, func2=paddle.square): + # ctx is a context object that store some objects for backward. + ctx.func = func2 + y = func1(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + # forward has only one output, so there is only one gradient in the input of backward. + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - ctx.func(y)) + # forward has only one input, so only one gradient tensor is returned. + return grad + + + data = paddle.randn([2, 3], dtype="float64") + data.stop_gradient = False + z = cus_tanh.apply(data, func1=paddle.tanh) + z.mean().backward() + + print(data.grad) + + """ + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + It is to be overloaded by subclasses. It must accept a object of `PyLayerContext` as + the first argument, followed by any number of arguments (tensors or other types). + `None` can not be included in the returned result. + + Args: + *args(tuple): input of PyLayer. + **kwargs(dict): input of PyLayer. + + Returns: + tensors or other types : output of PyLayer. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + raise NotImplementedError( + "You must implement the forward function for PyLayer." + ) + + @staticmethod + def backward(ctx, *args, **kwargs): + """ + This is a function to calculate the gradient. It is to be overloaded by subclasses. + It must accept a object of `PyLayerContext` as the first argument, and the rest + arguments are the gradient of forward's output tensors. Output tensors of backward + are the gradient of forward's input tensors. + + Args: + *args(tuple): The gradient of forward's output tensor(s). + **kwargs(dict): The gradient of forward's output tensor(s). + + Returns: + Tensor or list of Tensors: The gradient of forward's input tensor(s). + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + + raise NotImplementedError( + "You must implement the backward function for PyLayer." + ) + + +class EagerPyLayerContext(object): + def save_for_backward(self, *tensors): + """ + Saves given tensors that backward need. Use ``saved_tensor`` in the `backward` to get the saved tensors. + + Note: + This API should be called at most once, and only inside `forward`. + + Args: + tensors(list of Tensors): Tensors to be stored. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + # ctx is a context object that store some objects for backward. + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + + """ + self.container = tensors + + def saved_tensor(self): + """ + Get the tensors stored by ``save_for_backward``. + + Returns: + list of Tensors or None: If context contains tensors stored by `save_for_backward`, + then return these tensors, otherwise return None. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + # ctx is a context object that store some objects for backward. + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + return self.container + + def mark_not_inplace(self, *args): + """ + Marks inputs as not inplace. + This should be called at most once, only from inside the `forward` method, + and all arguments should be Tensor inputs. + + If the Tensor returned by `forward` method is the same as the Tensor input of forward, + and this Tensor is marked as not_inplace, then Paddle will help the user create a new Tensor as output. + Thereby preventing the auto grad information of the input Tensor from being overwritten. + + Examples: + .. code-block:: python + + import paddle + + class Exp(paddle.autograd.PyLayer): + @staticmethod + def forward(ctx, x): + ctx.mark_not_inplace(x) + return x + + @staticmethod + def backward(ctx, grad_output): + out = grad_output.exp() + return out + + x = paddle.randn((1, 1)) + x.stop_gradient = False + attn_layers = [] + for idx in range(0, 2): + attn_layers.append(Exp()) + + for step in range(0, 2): + a = x + for j in range(0,2): + a = attn_layers[j].apply(x) + a.backward() + """ + self.not_inplace_tensors = args + + def mark_non_differentiable(self, *args): + """ + Marks outputs as non-differentiable. + This should be called at most once, only from inside the `forward` method, + and all arguments should be tensor outputs. + + This will mark outputs as not requiring gradients, increasing the + efficiency of backward computation. You still need to accept a gradient + for each output in `backward`, but it's always going to + be a zero tensor with the same shape as the shape of a corresponding + output. + + Examples: + .. code-block:: python + + import os + os.environ['FLAGS_enable_eager_mode'] = '1' + import paddle + from paddle.autograd import PyLayer + import numpy as np + + class Tanh(PyLayer): + @staticmethod + def forward(ctx, x): + a = x + x + b = x + x + x + ctx.mark_non_differentiable(a) + return a, b + + @staticmethod + def backward(ctx, grad_a, grad_b): + assert np.equal(grad_a.numpy(), paddle.zeros([1]).numpy()) + assert np.equal(grad_b.numpy(), paddle.ones([1], dtype="float64").numpy()) + return grad_b + + x = paddle.ones([1], dtype="float64") + x.stop_gradient = False + a, b = Tanh.apply(x) + b.sum().backward() + """ + self.non_differentiable = args + + def set_materialize_grads(self, value: bool): + """ + Sets whether to materialize output grad tensors. Default is True. + + This should be called only from inside the `forward` method. + + If True, undefined output grad tensors will be expanded to tensors full + of zeros prior to calling the `backward` method. + + If False, undefined output grad tensors will be None. + + Examples: + .. code-block:: python + + import os + os.environ['FLAGS_enable_eager_mode'] = '1' + import paddle + from paddle.autograd import PyLayer + import numpy as np + + class Tanh(PyLayer): + @staticmethod + def forward(ctx, x): + return x+x+x, x+x + + @staticmethod + def backward(ctx, grad, grad2): + assert np.equal(grad2.numpy(), paddle.zeros([1]).numpy()) + return grad + + class Tanh2(PyLayer): + @staticmethod + def forward(ctx, x): + ctx.set_materialize_grads(False) + return x+x+x, x+x + + @staticmethod + def backward(ctx, grad, grad2): + assert grad2==None + return grad + + x = paddle.ones([1], dtype="float64") + x.stop_gradient = False + Tanh.apply(x)[0].backward() + + x2 = paddle.ones([1], dtype="float64") + x2.stop_gradient = False + Tanh2.apply(x2)[0].backward() + """ + self.materialize_grads = value + + +class EagerPyLayerBackward(core.eager.PyLayer, EagerPyLayerContext): + def backward(self, *args): + return self._forward_cls.backward(self, *args) + + +class EagerPyLayerMeta(type): + def __init__(cls, name, bases, attrs): + cls._backward_function = type( + name + '_backward', (EagerPyLayerBackward,), {"_forward_cls": cls} + ) + + return super(EagerPyLayerMeta, cls).__init__(name, bases, attrs) + + +class EagerPyLayer( + with_mateclass(EagerPyLayerMeta, core.eager.PyLayer, EagerPyLayerContext) +): + @staticmethod + def forward(ctx, *args, **kwargs): + """ + It is to be overloaded by subclasses. It must accept a object of `PyLayerContext` as + the first argument, followed by any number of arguments (tensors or other types). + `None` can not be included in the returned result. + + Args: + *args(tuple): input of PyLayer. + **kwargs(dict): input of PyLayer. + + Returns: + tensors or other types : output of PyLayer. + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + raise NotImplementedError( + "You must implement the forward function for PyLayer." + ) + + @staticmethod + def backward(ctx, *args): + """ + This is a function to calculate the gradient. It is to be overloaded by subclasses. + It must accept a object of `PyLayerContext` as the first argument, and the rest + arguments are the gradient of forward's output tensors. Output tensors of backward + are the gradient of forward's input tensors. + + Args: + *args(tuple): The gradient of forward's output tensor(s). + **kwargs(dict): The gradient of forward's output tensor(s). + + Returns: + Tensor or list of Tensors: The gradient of forward's input tensor(s). + + Examples: + .. code-block:: python + + import paddle + from paddle.autograd import PyLayer + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + y = paddle.tanh(x) + # Pass tensors to backward. + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + # Get the tensors passed by forward. + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + """ + + raise NotImplementedError( + "You must implement the backward function for PyLayer." + ) + + +def once_differentiable(backward): + def wrapper(ctx, *args): + with paddle.fluid.dygraph.no_grad(): + outputs = backward(ctx, *args) + return outputs + + return wrapper diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/batch.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..f787f603f7e3ae0a6aa205596add48d192f54451 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/batch.py @@ -0,0 +1,72 @@ +# 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. + +__all__ = [] + + +def batch(reader, batch_size, drop_last=False): + """ + This operator creates a batched reader which combines the data from the + input reader to batched data. + + Args: + reader(generator): the data reader to read from. + batch_size(int): size of each mini-batch. + drop_last(bool, optional): If set to True, the last batch is dropped when + the size of last batch is not equal to batch_size, if set to False, + it will not. Default: False. + Returns: + The batched reader. + + Return Type: + generator + + Examples: + .. code-block:: python + + import paddle + def reader(): + for i in range(10): + yield i + batch_reader = paddle.batch(reader, batch_size=2) + + for data in batch_reader(): + print(data) + + # Output is + # [0, 1] + # [2, 3] + # [4, 5] + # [6, 7] + # [8, 9] + """ + + def batch_reader(): + r = reader() + b = [] + for instance in r: + b.append(instance) + if len(b) == batch_size: + yield b + b = [] + if drop_last is False and len(b) != 0: + yield b + + # Batch size check + batch_size = int(batch_size) + if batch_size <= 0: + raise ValueError("batch_size should be a positive integeral value, " + "but got batch_size={}".format(batch_size)) + + return batch_reader diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/callbacks.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..46f69aae1bbfa48d018f039e36f5f8ddd62ec465 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/callbacks.py @@ -0,0 +1,26 @@ +# Copyright (c) 2021 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. + +from .hapi.callbacks import Callback # noqa: F401 +from .hapi.callbacks import ProgBarLogger # noqa: F401 +from .hapi.callbacks import ModelCheckpoint # noqa: F401 +from .hapi.callbacks import VisualDL # noqa: F401 +from .hapi.callbacks import LRScheduler # noqa: F401 +from .hapi.callbacks import EarlyStopping # noqa: F401 +from .hapi.callbacks import ReduceLROnPlateau # noqa: F401 + +__all__ = [ #noqa + 'Callback', 'ProgBarLogger', 'ModelCheckpoint', 'VisualDL', 'LRScheduler', + 'EarlyStopping', 'ReduceLROnPlateau' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/check_import_scipy.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/check_import_scipy.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e13e2a670856a1b4af288521dd9d7920747c42 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/check_import_scipy.py @@ -0,0 +1,29 @@ +# 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. + + +def check_import_scipy(OsName): + print_info = "" + if OsName == 'nt': + try: + import scipy.io as scio + except ImportError as e: + print_info = str(e) + if (len(print_info) > 0): + if 'DLL load failed' in print_info: + raise ImportError( + print_info + + "\nplease download Visual C++ Redistributable from https://support.microsoft.com/en-us/topic/the-latest-supported-visual-c-downloads-2647da03-1eea-4433-9aff-95f26a218cc0" + ) + return diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/common_ops_import.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/common_ops_import.py new file mode 100644 index 0000000000000000000000000000000000000000..d8fdac59df48f4e5f00b8c5a7a37ab6e80e62c16 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/common_ops_import.py @@ -0,0 +1,28 @@ +# 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. +from six.moves import reduce +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.param_attr import ParamAttr +from paddle.fluid.framework import convert_np_dtype_to_dtype_, _non_static_mode, _varbase_creator, in_dygraph_mode, _in_legacy_dygraph +from paddle.fluid.framework import device_guard, default_main_program, dygraph_only, _dygraph_tracer +from paddle.fluid.framework import OpProtoHolder, Variable +from paddle.fluid.initializer import Constant +from paddle.fluid.core import VarDesc +from paddle.fluid import core, dygraph_utils +from paddle.fluid.data_feeder import check_type, check_dtype, check_variable_and_dtype, convert_dtype +from paddle.fluid.layers import fill_constant, utils, scale +from paddle.tensor.layer_function_generator import templatedoc +import paddle.fluid as fluid +import numpy +import warnings diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/compat.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..82e6491b8095505f0aed99f117bdd9eba6e8f3d7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/compat.py @@ -0,0 +1,261 @@ +# Copyright (c) 2018 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. + +import six +import math + +__all__ = [] + +int_type = int +long_type = int + + +# str and bytes related functions +def to_text(obj, encoding='utf-8', inplace=False): + """ + All string in PaddlePaddle should be represented as a literal string. + + This function will convert object to a literal string without any encoding. + Especially, if the object type is a list or set container, we will iterate + all items in the object and convert them to literal string. + + In Python3: + Decode the bytes type object to str type with specific encoding + + In Python2: + Decode the str type object to unicode type with specific encoding + + Args: + obj(unicode|str|bytes|list|set) : The object to be decoded. + encoding(str) : The encoding format to decode a string + inplace(bool) : If we change the original object or we create a new one + + Returns: + Decoded result of obj + + Examples: + + .. code-block:: python + + import paddle + + data = "paddlepaddle" + data = paddle.compat.to_text(data) + # paddlepaddle + + """ + if obj is None: + return obj + + if isinstance(obj, list): + if inplace: + for i in six.moves.xrange(len(obj)): + obj[i] = _to_text(obj[i], encoding) + return obj + else: + return [_to_text(item, encoding) for item in obj] + elif isinstance(obj, set): + if inplace: + for item in obj: + obj.remove(item) + obj.add(_to_text(item, encoding)) + return obj + else: + return set([_to_text(item, encoding) for item in obj]) + elif isinstance(obj, dict): + if inplace: + new_obj = {} + for key, value in six.iteritems(obj): + new_obj[_to_text(key, encoding)] = _to_text(value, encoding) + obj.update(new_obj) + return obj + else: + new_obj = {} + for key, value in six.iteritems(obj): + new_obj[_to_text(key, encoding)] = _to_text(value, encoding) + return new_obj + else: + return _to_text(obj, encoding) + + +def _to_text(obj, encoding): + """ + In Python3: + Decode the bytes type object to str type with specific encoding + + In Python2: + Decode the str type object to unicode type with specific encoding, + or we just return the unicode string of object + + Args: + obj(unicode|str|bytes) : The object to be decoded. + encoding(str) : The encoding format + + Returns: + decoded result of obj + """ + if obj is None: + return obj + + if isinstance(obj, six.binary_type): + return obj.decode(encoding) + elif isinstance(obj, six.text_type): + return obj + elif isinstance(obj, (bool, float)): + return obj + else: + return six.u(obj) + + +def to_bytes(obj, encoding='utf-8', inplace=False): + """ + All string in PaddlePaddle should be represented as a literal string. + + This function will convert object to a bytes with specific encoding. + Especially, if the object type is a list or set container, we will iterate + all items in the object and convert them to bytes. + + In Python3: + Encode the str type object to bytes type with specific encoding + + In Python2: + Encode the unicode type object to str type with specific encoding, + or we just return the 8-bit string of object + + Args: + obj(unicode|str|bytes|list|set) : The object to be encoded. + encoding(str) : The encoding format to encode a string + inplace(bool) : If we change the original object or we create a new one + + Returns: + Decoded result of obj + + Examples: + + .. code-block:: python + + import paddle + + data = "paddlepaddle" + data = paddle.compat.to_bytes(data) + # b'paddlepaddle' + + """ + if obj is None: + return obj + + if isinstance(obj, list): + if inplace: + for i in six.moves.xrange(len(obj)): + obj[i] = _to_bytes(obj[i], encoding) + return obj + else: + return [_to_bytes(item, encoding) for item in obj] + elif isinstance(obj, set): + if inplace: + for item in obj: + obj.remove(item) + obj.add(_to_bytes(item, encoding)) + return obj + else: + return set([_to_bytes(item, encoding) for item in obj]) + else: + return _to_bytes(obj, encoding) + + +def _to_bytes(obj, encoding): + """ + In Python3: + Encode the str type object to bytes type with specific encoding + + In Python2: + Encode the unicode type object to str type with specific encoding, + or we just return the 8-bit string of object + + Args: + obj(unicode|str|bytes) : The object to be encoded. + encoding(str) : The encoding format + + Returns: + encoded result of obj + """ + if obj is None: + return obj + + assert encoding is not None + if isinstance(obj, six.text_type): + return obj.encode(encoding) + elif isinstance(obj, six.binary_type): + return obj + else: + return six.b(obj) + + +# math related functions +def round(x, d=0): + """ + Compatible round which act the same behaviour in Python3. + + Args: + x(float) : The number to round halfway. + + Returns: + round result of x + """ + if six.PY3: + # The official walkaround of round in Python3 is incorrect + # we implement according this answer: https://www.techforgeek.info/round_python.html + if x > 0.0: + p = 10**d + return float(math.floor((x * p) + math.copysign(0.5, x))) / p + elif x < 0.0: + p = 10**d + return float(math.ceil((x * p) + math.copysign(0.5, x))) / p + else: + return math.copysign(0.0, x) + else: + import __builtin__ + return __builtin__.round(x, d) + + +def floor_division(x, y): + """ + Compatible division which act the same behaviour in Python3 and Python2, + whose result will be a int value of floor(x / y) in Python3 and value of + (x / y) in Python2. + + Args: + x(int|float) : The number to divide. + y(int|float) : The number to be divided + + Returns: + division result of x // y + """ + return x // y + + +# exception related functions +def get_exception_message(exc): + """ + Get the error message of a specific exception + + Args: + exec(Exception) : The exception to get error message. + + Returns: + the error message of exec + """ + assert exc is not None + + return str(exc) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6907128642c66bd43df150f8bb496317bd7b011 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2021 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. + +from .cost_model import CostModel # noqa: F401 + +__all__ = ['CostModel'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/cost_model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/cost_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a59ff31a683a43c3f5d9d34ae4ed8e54c0ab4735 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/cost_model.py @@ -0,0 +1,88 @@ +# Copyright (c) 2021 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. + +import paddle +import paddle.static as static +import numpy as np +import json +import os +from paddle.fluid import core + + +class CostModel(): + + def __init__(self): + pass + + def build_program(self): + paddle.enable_static() + + main_program = static.Program() + startup_program = static.Program() + with static.program_guard(main_program=main_program, + startup_program=startup_program): + data = paddle.static.data(name='X', + shape=[None, 1], + dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + print("main program is: {}".format(main_program)) + + return startup_program, main_program + + def profile_measure(self, + startup_program, + main_program, + device='gpu', + fetch_cost_list=['time']): + + place = paddle.set_device('gpu') + x = np.random.random(size=(10, 1)).astype('float32') + exe = paddle.static.Executor(place) + + exe.run(startup_program) + paddle.fluid.profiler.start_profiler("All") + exe.run(main_program, feed={"X": x}, fetch_list=[]) + + cost_model = core.CostModel() + cost_data = cost_model.ProfileMeasure(device) + + def static_cost_data(self): + static_cost_data_path = os.path.join(os.path.dirname(__file__), + "static_op_benchmark.json") + with open(static_cost_data_path, 'r') as load_f: + load_dict = json.load(load_f) + self._static_cost_data = load_dict + # return all static cost data + return load_dict + + def get_static_op_time(self, op_name, forward=True, dtype="float32"): + # if forward is True, return op forward time, otherwise return op backward time. + if op_name == None: + raise ValueError( + 'op_name should not be empty when you want to get static op time' + ) + + op_cost = {} + for op_data in self._static_cost_data: + if (op_data["op"] == op_name) and (dtype in op_data["config"]): + if (forward): + op_cost["op_time"] = op_data["paddle_gpu_time"] + else: + op_cost["op_time"] = op_data["paddle_gpu_time_backward"] + op_cost["config"] = op_data["config"] + + return op_cost diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/static_op_benchmark.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/static_op_benchmark.json new file mode 100644 index 0000000000000000000000000000000000000000..b516f810e53e8c6b4f6b6c42416956e945d98661 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cost_model/static_op_benchmark.json @@ -0,0 +1 @@ +[{"name":"abs_0","op":"abs","op_count":2,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.331090353772731","paddle_perf_backwards":"3.3697429305326962","paddle_gpu_time":"1.3211645008562505","paddle_gpu_time_backward":"3.387969185379446"},{"name":"abs_1","op":"abs","op_count":2,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/abs_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6877529119441886","paddle_perf_backwards":"2.01086037622425","paddle_gpu_time":"0.6747270346494761","paddle_gpu_time_backward":"2.078491124260355"},{"name":"accuracy_0","op":"accuracy","op_count":62,"config":"input (Variable) - dtype: float16, shape: [16, 3]\nlabel (Variable) - dtype: int64, shape: [16, 1]\ntotal (Variable) - dtype: int64, shape: []\ncorrect (string): None\nk (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.08176540841861646","paddle_perf_backwards":"--","paddle_gpu_time":"0.03162362718907688","paddle_gpu_time_backward":"--"},{"name":"accuracy_1","op":"accuracy","op_count":62,"config":"input (Variable) - dtype: float32, shape: [16, 1000]\nlabel (Variable) - dtype: int64, shape: [16, 1]\ncorrect (string): None\nk (int): 1\ntotal (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/accuracy_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.09902667026130521","paddle_perf_backwards":"--","paddle_gpu_time":"0.05448726932959588","paddle_gpu_time_backward":"--"},{"name":"add_0","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08375929879235315","paddle_perf_backwards":"0.19740152645397474","paddle_gpu_time":"0.06437907840578255","paddle_gpu_time_backward":"0.16722634967805844"},{"name":"add_1","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0836590487875776","paddle_perf_backwards":"0.19311931185827463","paddle_gpu_time":"0.06452402538531278","paddle_gpu_time_backward":"0.16717375093214018"},{"name":"add_2","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.038008699436225965","paddle_perf_backwards":"0.10008589777057778","paddle_gpu_time":"0.01757676432095037","paddle_gpu_time_backward":"0.04874236252545825"},{"name":"add_3","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.14193958653237873","paddle_perf_backwards":"0.26894370635191284","paddle_gpu_time":"0.121376489598061","paddle_gpu_time_backward":"0.25036374246255594"},{"name":"add_4","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06155439751420566","paddle_perf_backwards":"0.14206386042501262","paddle_gpu_time":"0.04269137792103142","paddle_gpu_time_backward":"0.11509082102203923"},{"name":"add_5","op":"add","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2454338905089843","paddle_perf_backwards":"0.6398088468578392","paddle_gpu_time":"0.22470623803285297","paddle_gpu_time_backward":"0.6160299727520435"},{"name":"add_6","op":"add","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13866807562280373","paddle_perf_backwards":"0.42508208608052817","paddle_gpu_time":"0.12125367684349325","paddle_gpu_time_backward":"0.39961179007907977"},{"name":"add_7","op":"add","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.05299101871658998","paddle_perf_backwards":"0.11762414112627266","paddle_gpu_time":"0.03463261376304855","paddle_gpu_time_backward":"0.09322676781360066"},{"name":"add_8","op":"add","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"False","paddle_perf":"0.05768260401570965","paddle_perf_backwards":"0.1170390832400274","paddle_gpu_time":"0.04146914691469147","paddle_gpu_time_backward":"0.09352805887764491"},{"name":"add_n_0","op":"add_n","op_count":0,"config":"inputs (list[2]) - dtype: float32, shape: [1]; \n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02119030271257673","paddle_perf_backwards":"--","paddle_gpu_time":"0.001314003261312678","paddle_gpu_time_backward":"--"},{"name":"add_n_1","op":"add_n","op_count":0,"config":"inputs (list[8]) - dtype: float32, shape: [1]; \n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.03457020740119778","paddle_perf_backwards":"--","paddle_gpu_time":"0.004663965424095083","paddle_gpu_time_backward":"--"},{"name":"add_n_2","op":"add_n","op_count":0,"config":"inputs (list[4]) - dtype: float32, shape: [16, 256]; \n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/add_n_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.033566903094856104","paddle_perf_backwards":"--","paddle_gpu_time":"0.004455732567249934","paddle_gpu_time_backward":"--"},{"name":"affine_grid_0","op":"affine_grid","op_count":0,"config":"theta (Variable) - dtype: float32, shape: [32, 2, 3]\nalign_corners (bool): True\nout_shape (list): [32, 3, 128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.025103321994643615","paddle_perf_backwards":"0.05442976472846954","paddle_gpu_time":"0.008732239343606164","paddle_gpu_time_backward":"0.02619939577039275"},{"name":"affine_grid_1","op":"affine_grid","op_count":0,"config":"theta (Variable) - dtype: float32, shape: [32, 2, 3]\nalign_corners (bool): False\nout_shape (list): [32, 3, 128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/affine_grid_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.02413375310629726","paddle_perf_backwards":"3.074037597840091","paddle_gpu_time":"0.008943471735867934","paddle_gpu_time_backward":"3.0098403454162064"},{"name":"any_0","op":"any","op_count":0,"config":"x (Variable) - dtype: bool, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.09390927985579313","paddle_perf_backwards":"--","paddle_gpu_time":"0.08013408609738885","paddle_gpu_time_backward":"--"},{"name":"any_1","op":"any","op_count":0,"config":"x (Variable) - dtype: bool, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.04386244987954899","paddle_perf_backwards":"--","paddle_gpu_time":"0.0015045274188625493","paddle_gpu_time_backward":"--"},{"name":"any_2","op":"any","op_count":0,"config":"x (Variable) - dtype: bool, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.024226490332155813","paddle_perf_backwards":"--","paddle_gpu_time":"0.0016181301967146623","paddle_gpu_time_backward":"--"},{"name":"any_3","op":"any","op_count":0,"config":"x (Variable) - dtype: bool, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/any_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.06490458467441475","paddle_perf_backwards":"--","paddle_gpu_time":"0.04269003332974949","paddle_gpu_time_backward":"--"},{"name":"arange_0","op":"arange","op_count":0,"config":"dtype (string): None\nend (int): 65536\nstart (int): 0\nstep (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/arange_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.05341379009947485","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013192679206914084","paddle_gpu_time_backward":"--"},{"name":"argmax_0","op":"argmax","op_count":4,"config":"x (Variable) - dtype: float32, shape: [16, 513, 513, 19]\naxis (int): 3\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"5.978440877163049","paddle_perf_backwards":"--","paddle_gpu_time":"5.975735959007335","paddle_gpu_time_backward":"--"},{"name":"argmax_1","op":"argmax","op_count":4,"config":"x (Variable) - dtype: float32, shape: [16, 513, 513, 19]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"3.04252150082829","paddle_perf_backwards":"--","paddle_gpu_time":"3.0681368591037543","paddle_gpu_time_backward":"--"},{"name":"argmax_2","op":"argmax","op_count":4,"config":"x (Variable) - dtype: float32, shape: [1000, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0355234049787425","paddle_perf_backwards":"--","paddle_gpu_time":"0.02124123208295212","paddle_gpu_time_backward":"--"},{"name":"argmax_3","op":"argmax","op_count":4,"config":"x (Variable) - dtype: float32, shape: [1000000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmax_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.30277931328975793","paddle_perf_backwards":"--","paddle_gpu_time":"0.2796205446535843","paddle_gpu_time_backward":"--"},{"name":"argmin_0","op":"argmin","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 513, 513, 19]\naxis (int): 3\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"5.970599795832779","paddle_perf_backwards":"--","paddle_gpu_time":"5.9837235004521245","paddle_gpu_time_backward":"--"},{"name":"argmin_1","op":"argmin","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 513, 513, 19]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"3.0515416704042995","paddle_perf_backwards":"--","paddle_gpu_time":"3.0645906934490768","paddle_gpu_time_backward":"--"},{"name":"argmin_2","op":"argmin","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1000, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.03490568411470664","paddle_perf_backwards":"--","paddle_gpu_time":"0.021399898373983737","paddle_gpu_time_backward":"--"},{"name":"argmin_3","op":"argmin","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1000000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argmin_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.29497230895841964","paddle_perf_backwards":"--","paddle_gpu_time":"0.2901381657989588","paddle_gpu_time_backward":"--"},{"name":"argsort_0","op":"argsort","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1785]\naxis (int): 1\ndescending (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.07801299192467515","paddle_perf_backwards":"--","paddle_gpu_time":"0.04899283219996324","paddle_gpu_time_backward":"--"},{"name":"argsort_1","op":"argsort","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1700971, 1]\naxis (int): 0\ndescending (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/argsort_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"1.512936426668751","paddle_perf_backwards":"--","paddle_gpu_time":"0.8877671333824613","paddle_gpu_time_backward":"--"},{"name":"assign_0","op":"assign","op_count":75,"config":"input (Variable) - dtype: float32, shape: [2, 768]\noutput (Variable) - dtype: float32, shape: [2, 768]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02295970916748047","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013110930019354181","paddle_gpu_time_backward":"--"},{"name":"assign_1","op":"assign","op_count":75,"config":"input (Variable) - dtype: float32, shape: [30522, 1024]\noutput (Variable) - dtype: float32, shape: [30522, 1024]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.3451830412010591","paddle_perf_backwards":"--","paddle_gpu_time":"0.32475108993206936","paddle_gpu_time_backward":"--"},{"name":"assign_2","op":"assign","op_count":75,"config":"input (Variable) - dtype: float32, shape: [1]\noutput (Variable) - dtype: float32, shape: [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/assign_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.024633991475007968","paddle_perf_backwards":"--","paddle_gpu_time":"0.0012902208201892745","paddle_gpu_time_backward":"--"},{"name":"avg_pool2d_0","op":"avg_pool2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\nceil_mode (bool): False\ndata_format (string): NCHW\nkernel_size (list): [7, 7]\npadding (list): [0, 0]\nstride (list): [1, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0295015702764672","paddle_perf_backwards":"0.1579984603636715","paddle_gpu_time":"0.008882733148661125","paddle_gpu_time_backward":"0.13906863314365345"},{"name":"avg_pool2d_1","op":"avg_pool2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256, 16, 16]\nceil_mode (bool): False\ndata_format (string): NCHW\nkernel_size (list): [2, 2]\npadding (list): [0, 0]\nstride (list): [2, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.031752744036351505","paddle_perf_backwards":"0.057186034017192106","paddle_gpu_time":"0.005965454361260257","paddle_gpu_time_backward":"0.030319879417183046"},{"name":"avg_pool2d_2","op":"avg_pool2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1024, 16, 16]\nceil_mode (bool): True\ndata_format (string): NCHW\nkernel_size (list): [2, 2]\npadding (list): [0, 0]\nstride (list): [2, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/avg_pool2d_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.054760781939856285","paddle_perf_backwards":"0.10909902786682985","paddle_gpu_time":"0.029859567589412002","paddle_gpu_time_backward":"0.08597355003186744"},{"name":"batch_norm_0","op":"batch_norm","op_count":85,"config":"x (Variable) - dtype: float32, shape: [16, 256]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nmomentum (float): 0.9\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.04047812247762875","paddle_perf_backwards":"0.05833007851425483","paddle_gpu_time":"0.004966265441875198","paddle_gpu_time_backward":"0.009052583447645176"},{"name":"batch_norm_1","op":"batch_norm","op_count":85,"config":"x (Variable) - dtype: float32, shape: [16, 32768]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nmomentum (float): 0.9\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.041234493255615234","paddle_perf_backwards":"0.062144289211351046","paddle_gpu_time":"0.011674594395280236","paddle_gpu_time_backward":"0.02364326765188834"},{"name":"batch_norm_2","op":"batch_norm","op_count":85,"config":"x (Variable) - dtype: float32, shape: [16, 1536, 33, 33]\ndata_format (string): NCHW\nepsilon (float): 0.001\nmomentum (float): 0.99\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.5401310671764205","paddle_perf_backwards":"1.2945437048333717","paddle_gpu_time":"0.5109449929478138","paddle_gpu_time_backward":"1.2523399932272266"},{"name":"batch_norm_3","op":"batch_norm","op_count":85,"config":"x (Variable) - dtype: float32, shape: [16, 256, 1, 1]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nmomentum (float): 0.99\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.04015749238102312","paddle_perf_backwards":"0.06386807644702346","paddle_gpu_time":"0.005085971396432589","paddle_gpu_time_backward":"0.0090054819552307"},{"name":"batch_norm_4","op":"batch_norm","op_count":85,"config":"x (Variable) - dtype: float32, shape: [16, 32, 256, 256]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nmomentum (float): 0.9\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/batch_norm_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.7429562419293875","paddle_perf_backwards":"2.1714267003009597","paddle_gpu_time":"0.7165747080144986","paddle_gpu_time_backward":"2.1268894911171334"},{"name":"bernoulli_0","op":"bernoulli","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1785]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03951682623131687","paddle_perf_backwards":"--","paddle_gpu_time":"0.012009806864805362","paddle_gpu_time_backward":"--"},{"name":"bernoulli_1","op":"bernoulli","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.7047428184723759","paddle_perf_backwards":"--","paddle_gpu_time":"0.681329196276649","paddle_gpu_time_backward":"--"},{"name":"bernoulli_2","op":"bernoulli","op_count":0,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/bernoulli_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"4.935687421316124","paddle_perf_backwards":"--","paddle_gpu_time":"4.891302171954759","paddle_gpu_time_backward":"--"},{"name":"binary_cross_entropy_with_logits_0","op":"binary_cross_entropy_with_logits","op_count":0,"config":"label (Variable) - dtype: float32, shape: [16, 3, 64, 64, 80]\nlogit (Variable) - dtype: float32, shape: [16, 3, 64, 64, 80]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.3616172440198003","paddle_perf_backwards":"0.7916302097087003","paddle_gpu_time":"0.36139619414154367","paddle_gpu_time_backward":"0.7699570013086557"},{"name":"binary_cross_entropy_with_logits_1","op":"binary_cross_entropy_with_logits","op_count":0,"config":"label (Variable) - dtype: float32, shape: [16, 900]\nlogit (Variable) - dtype: float32, shape: [16, 900]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/binary_cross_entropy_with_logits_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03756382027450873","paddle_perf_backwards":"0.04715554568232322","paddle_gpu_time":"0.002957526780680323","paddle_gpu_time_backward":"0.004496260683760684"},{"name":"case_0","op":"case","op_count":0,"config":"input (Variable) - dtype: float32, shape: [1]\nx (Variable) - dtype: float32, shape: [16, 256, 6, 6]\ny (Variable) - dtype: float32, shape: [16, 256, 6, 6]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/case_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.26228841470212355","paddle_perf_backwards":"0.46846355710710796","paddle_gpu_time":"0.019793856402664695","paddle_gpu_time_backward":"0.04631597591215019"},{"name":"cast_0","op":"cast","op_count":154,"config":"x (Variable) - dtype: bool, shape: [16, 1785]\ndtype (string): bool\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.019454469486158723","paddle_perf_backwards":"--","paddle_gpu_time":"0.0012923970648185893","paddle_gpu_time_backward":"--"},{"name":"cast_1","op":"cast","op_count":154,"config":"x (Variable) - dtype: int32, shape: [16, 1]\ndtype (string): int64\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.01880149452053771","paddle_perf_backwards":"--","paddle_gpu_time":"0.001318357783211084","paddle_gpu_time_backward":"--"},{"name":"cast_2","op":"cast","op_count":154,"config":"x (Variable) - dtype: int32, shape: [16, 1, 513, 513]\ndtype (string): float32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.058897192698405924","paddle_perf_backwards":"--","paddle_gpu_time":"0.04410708853057499","paddle_gpu_time_backward":"--"},{"name":"cast_3","op":"cast","op_count":154,"config":"x (Variable) - dtype: float16, shape: [30522, 1024]\ndtype (string): float32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.2635867241396004","paddle_perf_backwards":"--","paddle_gpu_time":"0.24973197127541216","paddle_gpu_time_backward":"--"},{"name":"cast_4","op":"cast","op_count":154,"config":"x (Variable) - dtype: int64, shape: [1]\ndtype (string): float32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.01859932529683016","paddle_perf_backwards":"--","paddle_gpu_time":"0.001314701690083486","paddle_gpu_time_backward":"--"},{"name":"cast_5","op":"cast","op_count":154,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1]\ndtype (string): float16\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.018823390104332753","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013060393115388532","paddle_gpu_time_backward":"--"},{"name":"cast_6","op":"cast","op_count":154,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1024]\ndtype (string): float16\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cast_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.01965110081745439","paddle_perf_backwards":"--","paddle_gpu_time":"0.001813003159074697","paddle_gpu_time_backward":"--"},{"name":"cholesky_0","op":"cholesky","op_count":0,"config":"x (Variable) - dtype: float32, shape: [200, 200]\nupper (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.21754843848092215","paddle_perf_backwards":"0.4098045582673988","paddle_gpu_time":"0.12430577531645567","paddle_gpu_time_backward":"0.31029067706487057"},{"name":"cholesky_1","op":"cholesky","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 10, 20]\nupper (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cholesky_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1542894207701391","paddle_perf_backwards":"0.3933154806798818","paddle_gpu_time":"0.02254530386740331","paddle_gpu_time_backward":"0.14846453210684593"},{"name":"clip_by_norm_0","op":"clip_by_norm","op_count":0,"config":"","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/clip_by_norm_0-tensorflow_gpu_speed_forward.txt","tensorflow_consistency":"--","tensorflow_consistency_backwards":"--","tensorflow_perf":"0.07725905398933254","tensorflow_perf_backwards":"--","tensorflow_gpu_time":"0.016432170542635658","tensorflow_gpu_time_backward":"--"},{"name":"concat_0","op":"concat","op_count":207,"config":"x (list[2]) - dtype: float32, shape: [16, 256, 129, 129]; dtype: float32, shape: [16, 48, 129, 129]; \naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.948416947360977","paddle_perf_backwards":"1.8728502304199708","paddle_gpu_time":"0.9265941660737879","paddle_gpu_time_backward":"1.8538063740228503"},{"name":"concat_1","op":"concat","op_count":207,"config":"x (list[5]) - dtype: float32, shape: [16, 16, 1]; \naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.030198145885856783","paddle_perf_backwards":"0.053738574592434626","paddle_gpu_time":"0.003917914586799778","paddle_gpu_time_backward":"0.007942266264541146"},{"name":"concat_2","op":"concat","op_count":207,"config":"x (list[201]) - dtype: float32, shape: [1]; \naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.10845588178050761","paddle_perf_backwards":"0.34467979353301376","paddle_gpu_time":"0.004424460431654676","paddle_gpu_time_backward":"0.008462154585502603"},{"name":"concat_3","op":"concat","op_count":207,"config":"x (list[2]) - dtype: float32, shape: [1, 16, 200]; \naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.029992570682447785","paddle_perf_backwards":"0.054718523609394935","paddle_gpu_time":"0.0025547024952015354","paddle_gpu_time_backward":"0.005137355455002514"},{"name":"concat_4","op":"concat","op_count":207,"config":"x (list[4]) - dtype: float32, shape: [16, 256, 14, 14]; \naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/concat_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06534588863571963","paddle_perf_backwards":"0.10642852170400352","paddle_gpu_time":"0.04283491614467569","paddle_gpu_time_backward":"0.07899617783142224"},{"name":"cond_0","op":"cond","op_count":0,"config":"input (Variable) - dtype: float32, shape: [1]\nx (Variable) - dtype: float32, shape: [16, 256, 6, 6]\ny (Variable) - dtype: float32, shape: [16, 256, 6, 6]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cond_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2421449641792142","paddle_perf_backwards":"0.40900707244873047","paddle_gpu_time":"0.015987691383968775","paddle_gpu_time_backward":"0.038438516590761224"},{"name":"conv2d_0","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [512, 512, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 512, 7, 7]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (int): 1\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.310855009117905","paddle_perf_backwards":"0.7684639522007534","paddle_gpu_time":"0.2683156654888104","paddle_gpu_time_backward":"0.7073700543056634"},{"name":"conv2d_1","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [5, 2048, 2, 2]\nx (Variable) - dtype: float32, shape: [16, 2048, 2, 2]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (int): 0\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.47340076796862546","paddle_perf_backwards":"0.5542210170200893","paddle_gpu_time":"0.4259777933380014","paddle_gpu_time_backward":"0.4552249946683728"},{"name":"conv2d_2","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [1024, 512, 1, 1]\nx (Variable) - dtype: float32, shape: [16, 512, 64, 402]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (int): 0\nstride (tuple): [2, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"16.446034032471324","paddle_perf_backwards":"53.39936504558641","paddle_gpu_time":"16.638510445049956","paddle_gpu_time_backward":"53.42495921696574"},{"name":"conv2d_3","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [128, 128, 1, 1]\nx (Variable) - dtype: float32, shape: [16, 128, 257, 257]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (int): 1\npadding (int): 0\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"2.8805257804901245","paddle_perf_backwards":"9.568641942188922","paddle_gpu_time":"2.849249370277078","paddle_gpu_time_backward":"9.46820342205323"},{"name":"conv2d_4","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [256, 2048, 1, 1]\nx (Variable) - dtype: float32, shape: [16, 2048, 1, 1]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (int): 1\npadding (int): 0\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1551832471575056","paddle_perf_backwards":"0.23110594068254742","paddle_gpu_time":"0.10960650471792811","paddle_gpu_time_backward":"0.18311956361491963"},{"name":"conv2d_5","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [64, 3, 4, 4]\nx (Variable) - dtype: float32, shape: [16, 3, 128, 128]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (list): [1, 1]\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1062653502639459","paddle_perf_backwards":"0.3358765524260852","paddle_gpu_time":"0.06659271957245134","paddle_gpu_time_backward":"0.2899744572158365"},{"name":"conv2d_6","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [32, 3, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 3, 513, 513]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (int): 1\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.41322154228133384","paddle_perf_backwards":"2.01024106054595","paddle_gpu_time":"0.36629671112921297","paddle_gpu_time_backward":"1.9432972614840986"},{"name":"conv2d_7","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [32, 1, 7, 1]\nx (Variable) - dtype: float32, shape: [16, 1, 512, 402]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (tuple): [3, 0]\nstride (tuple): [2, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.39066295234524473","paddle_perf_backwards":"1.8467893405836457","paddle_gpu_time":"0.33348572589657627","paddle_gpu_time_backward":"1.7525220372184134"},{"name":"conv2d_8","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [256, 8, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 256, 56, 56]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (int): 32\npadding (int): 1\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.37124473221448007","paddle_perf_backwards":"1.9316305919569365","paddle_gpu_time":"0.4329995913363302","paddle_gpu_time_backward":"6.0645422357106735"},{"name":"conv2d_9","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [512, 1024, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 1024, 8, 8]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\npadding (list): [1, 1]\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_9-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.5592431340898787","paddle_perf_backwards":"1.4172532120529486","paddle_gpu_time":"0.5389499566097773","paddle_gpu_time_backward":"1.3585378323108386"},{"name":"conv2d_10","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float16, shape: [1, 1, 3, 32]\nx (Variable) - dtype: float16, shape: [1, 1, 80, 1008]\ndata_format (string): NCHW\ndilation (tuple): [1, 1]\ngroups (int): 1\npadding (tuple): [1, 8]\nstride (tuple): [1, 16]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_10-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06094124852394572","paddle_perf_backwards":"0.8485815962966607","paddle_gpu_time":"0.009655744295909138","paddle_gpu_time_backward":"0.6963649238758409"},{"name":"conv2d_11","op":"conv2d","op_count":135,"config":"weight (Variable) - dtype: float32, shape: [512, 512, 3, 3]\nx (Variable) - dtype: float32, shape: [2, 512, 129, 129]\ndata_format (string): NCHW\ndilation (tuple): [16, 16]\ngroups (int): 1\npadding (tuple): [0, 0]\nstride (tuple): [1, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_11-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"6.61750180380685","paddle_perf_backwards":"168.68680204663957","paddle_gpu_time":"6.587961106655974","paddle_gpu_time_backward":"169.36035741527735"},{"name":"conv2d_transpose_0","op":"conv2d_transpose","op_count":7,"config":"weight (Variable) - dtype: float32, shape: [1549, 512, 4, 4]\nx (Variable) - dtype: float32, shape: [16, 1549, 8, 8]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\noutput_size (list): [16, 16]\npadding (list): [1, 1]\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"3.3510884460137818","paddle_perf_backwards":"8.04602321313352","paddle_gpu_time":"3.2952342569269524","paddle_gpu_time_backward":"8.044063126252505"},{"name":"conv2d_transpose_1","op":"conv2d_transpose","op_count":7,"config":"weight (Variable) - dtype: float32, shape: [128, 64, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 128, 64, 64]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\noutput_size (list): [127, 127]\npadding (list): [1, 1]\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.5625759046904895","paddle_perf_backwards":"3.229873764271639","paddle_gpu_time":"1.5274933190807056","paddle_gpu_time_backward":"3.2251096491228073"},{"name":"conv2d_transpose_2","op":"conv2d_transpose","op_count":7,"config":"weight (Variable) - dtype: float32, shape: [512, 512, 4, 4]\nx (Variable) - dtype: float32, shape: [16, 512, 1, 1]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\noutput_size (list): [2, 2]\npadding (int): 1\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.0706354160698093","paddle_perf_backwards":"2.0013972204558708","paddle_gpu_time":"1.0121723410665864","paddle_gpu_time_backward":"1.9265515903801396"},{"name":"conv2d_transpose_3","op":"conv2d_transpose","op_count":7,"config":"weight (Variable) - dtype: float32, shape: [256, 256, 2, 2]\nx (Variable) - dtype: float32, shape: [32, 256, 14, 14]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (string): None\noutput_size (list): [28, 28]\npadding (int): 0\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6111553737095424","paddle_perf_backwards":"1.2583662052543796","paddle_gpu_time":"0.5752676659528908","paddle_gpu_time_backward":"1.2029733959311424"},{"name":"conv2d_transpose_4","op":"conv2d_transpose","op_count":7,"config":"weight (Variable) - dtype: float32, shape: [1, 1, 3, 32]\nx (Variable) - dtype: float32, shape: [1, 1, 80, 63]\ndata_format (string): NCHW\ndilation (list): [1, 1]\ngroups (int): 1\noutput_size (string): None\npadding (list): [1, 8]\nstride (list): [1, 16]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv2d_transpose_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.05015864664194536","paddle_perf_backwards":"0.6130943492967255","paddle_gpu_time":"0.013404064219153475","paddle_gpu_time_backward":"0.5153545868575147"},{"name":"conv3d_0","op":"conv3d","op_count":2,"config":"weight (Variable) - dtype: float32, shape: [128, 64, 3, 3, 3]\nx (Variable) - dtype: float32, shape: [1, 64, 5, 360, 360]\ndata_format (string): NCDHW\ndilation (int): 1\ngroups (int): 1\npadding (int): 0\nstride (list): [1, 2, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"3.5029351711273193","paddle_perf_backwards":"68.78609657287598","paddle_gpu_time":"3.700387331966279","paddle_gpu_time_backward":"70.30565232048545"},{"name":"conv3d_transpose_0","op":"conv3d_transpose","op_count":0,"config":"input (Variable) - dtype: float32, shape: [16, 3, 8, 8, 8]\nact (string): None\ndata_format (string): NCDHW\ndilation (int): 1\nfilter_size (int): 3\ngroups (string): None\nnum_filters (int): 6\noutput_size (list): [10, 10, 10]\npadding (int): 0\nstride (int): 1\nuse_cudnn (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/conv3d_transpose_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08663644596022002","paddle_perf_backwards":"0.24809472414912007","paddle_gpu_time":"0.04269474589019018","paddle_gpu_time_backward":"0.2125585754451734"},{"name":"cos_0","op":"cos","op_count":3,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3334699288637701","paddle_perf_backwards":"3.2444036078596405","paddle_gpu_time":"1.3231815434213179","paddle_gpu_time_backward":"3.229014227642276"},{"name":"cos_1","op":"cos","op_count":3,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cos_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6916530624420226","paddle_perf_backwards":"1.6653602252264539","paddle_gpu_time":"0.6782866639806607","paddle_gpu_time_backward":"1.6492914188615122"},{"name":"cosine_similarity_0","op":"cosine_similarity","op_count":0,"config":"x1 (Variable) - dtype: float32, shape: [16, 256]\nx2 (Variable) - dtype: float32, shape: [16, 256]\naxis (int): 1\neps (float): 1e-08\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cosine_similarity_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.12081958809677434","paddle_perf_backwards":"0.27974089797662227","paddle_gpu_time":"0.01432777149321267","paddle_gpu_time_backward":"0.04033333333333334"},{"name":"cumsum_0","op":"cumsum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1700971, 1]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0724313210467903","paddle_perf_backwards":"--","paddle_gpu_time":"0.02262709966405375","paddle_gpu_time_backward":"--"},{"name":"cumsum_1","op":"cumsum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1700971, 100]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/cumsum_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"10.890969634056091","paddle_perf_backwards":"--","paddle_gpu_time":"12.299464316571624","paddle_gpu_time_backward":"--"},{"name":"data_norm_0","op":"data_norm","op_count":0,"config":"x (Variable) - dtype: float32, shape: [100, 1785]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/data_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.029009215685786034","paddle_perf_backwards":"0.05558923799164441","paddle_gpu_time":"0.004954785229841749","paddle_gpu_time_backward":"0.014293701657458562"},{"name":"depthwise_conv2d_0","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [2048, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\ndata_format (string): NCHW\ndilation (int): 18\ngroups (long): 2048\npadding (int): 18\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.43426046566087373","paddle_perf_backwards":"3.7328143509066836","paddle_gpu_time":"0.4443133503401361","paddle_gpu_time_backward":"3.7436203818156844"},{"name":"depthwise_conv2d_1","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [2048, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [16, 33, 33, 2048]\ndata_format (string): NHWC\ndilation (int): 18\ngroups (long): 2048\npadding (int): 18\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.5845999231143874","paddle_perf_backwards":"1.9711740162907814","paddle_gpu_time":"0.5683715523618303","paddle_gpu_time_backward":"1.9434684684684687"},{"name":"depthwise_conv2d_2","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [2048, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 2048, 64, 128]\ndata_format (string): NCHW\ndilation (int): 12\ngroups (long): 2048\npadding (int): 12\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.7685410733125648","paddle_perf_backwards":"5.95715654139616","paddle_gpu_time":"0.7922445060806486","paddle_gpu_time_backward":"5.936238797340272"},{"name":"depthwise_conv2d_3","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [2048, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 64, 128, 2048]\ndata_format (string): NHWC\ndilation (int): 12\ngroups (long): 2048\npadding (int): 12\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.5200675750265316","paddle_perf_backwards":"4.812486074408706","paddle_gpu_time":"1.509220078821821","paddle_gpu_time_backward":"4.890282131661442"},{"name":"depthwise_conv2d_4","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [728, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [8, 728, 65, 65]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (long): 728\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.35119835211306205","paddle_perf_backwards":"2.4080191339765276","paddle_gpu_time":"0.33802445709466583","paddle_gpu_time_backward":"2.4072117524855314"},{"name":"depthwise_conv2d_5","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [728, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [8, 65, 65, 728]\ndata_format (string): NHWC\ndilation (int): 1\ngroups (long): 728\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.563528586407097","paddle_perf_backwards":"1.7572308073238452","paddle_gpu_time":"0.5410089332632684","paddle_gpu_time_backward":"1.7080296678490807"},{"name":"depthwise_conv2d_6","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [128, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [8, 128, 257, 257]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (long): 128\npadding (int): 1\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.49675484092868105","paddle_perf_backwards":"3.044777500386141","paddle_gpu_time":"0.5214900662251656","paddle_gpu_time_backward":"3.046329526916803"},{"name":"depthwise_conv2d_7","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [128, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [8, 257, 257, 128]\ndata_format (string): NHWC\ndilation (int): 1\ngroups (long): 128\npadding (int): 1\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.6079625110236966","paddle_perf_backwards":"2.484661948924162","paddle_gpu_time":"0.6178194993412385","paddle_gpu_time_backward":"2.4841522157996145"},{"name":"depthwise_conv2d_8","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [304, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 304, 128, 256]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (long): 304\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.4766225814819336","paddle_perf_backwards":"2.5614524374202805","paddle_gpu_time":"0.485045140732873","paddle_gpu_time_backward":"2.572104144527099"},{"name":"depthwise_conv2d_9","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [304, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 128, 256, 304]\ndata_format (string): NHWC\ndilation (int): 1\ngroups (long): 304\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_9-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.140820736787757","paddle_perf_backwards":"3.47914525440761","paddle_gpu_time":"1.1070727929788333","paddle_gpu_time_backward":"3.459722659943271"},{"name":"depthwise_conv2d_10","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [256, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 256, 128, 256]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (long): 256\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_10-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.4326187834447744","paddle_perf_backwards":"2.279125914281728","paddle_gpu_time":"0.43586922018833985","paddle_gpu_time_backward":"2.27520572450805"},{"name":"depthwise_conv2d_11","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [256, 1, 3, 3]\nx (Variable) - dtype: float32, shape: [4, 128, 256, 256]\ndata_format (string): NHWC\ndilation (int): 1\ngroups (long): 256\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_11-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.6356820768239547","paddle_perf_backwards":"1.9307727716406997","paddle_gpu_time":"0.6124776245130041","paddle_gpu_time_backward":"1.9250651890482398"},{"name":"depthwise_conv2d_12","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [256, 1, 5, 5]\nx (Variable) - dtype: float32, shape: [4, 256, 128, 256]\ndata_format (string): NCHW\ndilation (int): 1\ngroups (long): 256\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_12-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.8036460195268903","paddle_perf_backwards":"4.661791178644919","paddle_gpu_time":"0.8048330585325639","paddle_gpu_time_backward":"4.650039815257207"},{"name":"depthwise_conv2d_13","op":"depthwise_conv2d","op_count":0,"config":"weight (Variable) - dtype: float32, shape: [256, 1, 5, 5]\nx (Variable) - dtype: float32, shape: [4, 128, 256, 256]\ndata_format (string): NHWC\ndilation (int): 1\ngroups (long): 256\npadding (int): 1\nstride (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_13-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.4924990887544594","paddle_perf_backwards":"4.679340245772382","paddle_gpu_time":"1.4495046471249107","paddle_gpu_time_backward":"4.671232876712329"},{"name":"depthwise_conv2d_transpose_0","op":"depthwise_conv2d_transpose","op_count":0,"config":"input (Variable) - dtype: float32, shape: [16, 256, 8, 8]\ndata_format (string): NCHW\ndilation (int): 1\nfilter_size (int): 4\ngroups (int): 128\nnum_filters (int): 128\noutput_size (list): [16, 16]\npadding (list): [1, 1]\nstride (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/depthwise_conv2d_transpose_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.0863104450459383","paddle_perf_backwards":"0.14083580094940806","paddle_gpu_time":"0.05643294212057379","paddle_gpu_time_backward":"0.09976872415377545"},{"name":"diag_0","op":"diag","op_count":2,"config":"x (Variable) - dtype: float32, shape: [1000]\noffset (int): 0\npadding_value (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.025036140364043565","paddle_perf_backwards":"--","paddle_gpu_time":"0.006701951819940215","paddle_gpu_time_backward":"--"},{"name":"diag_1","op":"diag","op_count":2,"config":"x (Variable) - dtype: int64, shape: [1000]\noffset (int): 0\npadding_value (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.027585516170579562","paddle_perf_backwards":"--","paddle_gpu_time":"0.013081013655462187","paddle_gpu_time_backward":"--"},{"name":"diag_2","op":"diag","op_count":2,"config":"x (Variable) - dtype: float32, shape: [1000]\noffset (int): 5\npadding_value (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.025799323101432958","paddle_perf_backwards":"--","paddle_gpu_time":"0.0066919156414762745","paddle_gpu_time_backward":"--"},{"name":"diag_3","op":"diag","op_count":2,"config":"x (Variable) - dtype: float32, shape: [1000]\noffset (int): 0\npadding_value (int): 9\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/diag_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02306748409660495","paddle_perf_backwards":"--","paddle_gpu_time":"0.006686291739894552","paddle_gpu_time_backward":"--"},{"name":"dist_0","op":"dist","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1000, 1000]\ny (Variable) - dtype: float32, shape: [1000, 1000]\np (float): 2.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.1180021130308813","paddle_perf_backwards":"0.1907808440072196","paddle_gpu_time":"0.10002602398732746","paddle_gpu_time_backward":"0.1782452010141253"},{"name":"dist_1","op":"dist","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1000, 1000]\ny (Variable) - dtype: float32, shape: [1000, 1000]\np (float): inf\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.07541325627541057","paddle_perf_backwards":"0.14050517763410295","paddle_gpu_time":"0.05691709314227225","paddle_gpu_time_backward":"0.1274175715695953"},{"name":"dist_2","op":"dist","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1000, 1000]\ny (Variable) - dtype: float32, shape: [1000, 1000]\np (float): 0.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dist_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.07628445722618882","paddle_perf_backwards":"0.12399274475720462","paddle_gpu_time":"0.06029667519181585","paddle_gpu_time_backward":"0.09524459438736392"},{"name":"divide_0","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08323659171332587","paddle_perf_backwards":"0.2511458592610555","paddle_gpu_time":"0.06488759534323564","paddle_gpu_time_backward":"0.22392268694550058"},{"name":"divide_1","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08376612214143864","paddle_perf_backwards":"0.2444098851007068","paddle_gpu_time":"0.06524529062153724","paddle_gpu_time_backward":"0.22379870129870133"},{"name":"divide_2","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.037375839057570706","paddle_perf_backwards":"0.09080319700833551","paddle_gpu_time":"0.017779792485141534","paddle_gpu_time_backward":"0.06764565043894652"},{"name":"divide_3","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13824632029256267","paddle_perf_backwards":"0.3580100550680218","paddle_gpu_time":"0.12188989898989898","paddle_gpu_time_backward":"0.3311556118410638"},{"name":"divide_4","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06182458931076264","paddle_perf_backwards":"4.226368319295451","paddle_gpu_time":"0.042980159129821734","paddle_gpu_time_backward":"4.2174628825371165"},{"name":"divide_5","op":"divide","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2457542027643544","paddle_perf_backwards":"2.8514309254342423","paddle_gpu_time":"0.22795365239294707","paddle_gpu_time_backward":"2.822320069580343"},{"name":"divide_6","op":"divide","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"divide_7","op":"divide","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"divide_8","op":"divide","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/divide_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"dropout_0","op":"dropout","op_count":151,"config":"x (Variable) - dtype: float32, shape: [16, 36864]\naxis (string): None\nmode (string): downscale_in_infer\np (float): 0.5\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.026738282405968872","paddle_perf_backwards":"0.0391202743607338","paddle_gpu_time":"0.005506079185285254","paddle_gpu_time_backward":"0.013207371556217422"},{"name":"dropout_1","op":"dropout","op_count":151,"config":"x (Variable) - dtype: float32, shape: [16, 16, 16, 16]\naxis (string): None\nmode (string): downscale_in_infer\np (float): 0.1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.025975945019962816","paddle_perf_backwards":"0.07928381062517262","paddle_gpu_time":"0.0028879057538679343","paddle_gpu_time_backward":"0.004261524690437118"},{"name":"dropout_2","op":"dropout","op_count":151,"config":"x (Variable) - dtype: float32, shape: [16, 35, 1500]\naxis (string): None\nmode (string): upscale_in_train\np (float): 0.65\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03055574918034101","paddle_perf_backwards":"0.04656615883412987","paddle_gpu_time":"0.010632041343669251","paddle_gpu_time_backward":"0.01932886557886558"},{"name":"dropout_3","op":"dropout","op_count":151,"config":"x (Variable) - dtype: float32, shape: [32, 128, 768]\naxis (string): None\nmode (string): upscale_in_train\np (float): 0.1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.05879548131203165","paddle_perf_backwards":"0.0966923577444894","paddle_gpu_time":"0.04038380207231973","paddle_gpu_time_backward":"0.07795755968169761"},{"name":"dropout_4","op":"dropout","op_count":151,"config":"x (Variable) - dtype: float16, shape: [32, 128, 768]\naxis (string): None\nmode (string): upscale_in_train\np (float): 0.1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/dropout_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04361989546795281","paddle_perf_backwards":"0.06851979664393834","paddle_gpu_time":"0.025809663557279112","paddle_gpu_time_backward":"0.04777950612482987"},{"name":"elu_0","op":"elu","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.333071688611904","paddle_perf_backwards":"3.259305461852966","paddle_gpu_time":"1.3226150901581544","paddle_gpu_time_backward":"3.2286077235772352"},{"name":"elu_1","op":"elu","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/elu_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6918176859318613","paddle_perf_backwards":"1.6651800018035339","paddle_gpu_time":"0.6800674858984689","paddle_gpu_time_backward":"1.6487527650161646"},{"name":"embedding_0","op":"embedding","op_count":99,"config":"weight (Variable) - dtype: float16, shape: [2, 768]\nx (Variable) - dtype: int64, shape: [16, 128]\npadding_idx (string): None\nsparse (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.038689496565838255","paddle_perf_backwards":"1.0400660183964943","paddle_gpu_time":"0.006286876192388794","paddle_gpu_time_backward":"1.0182413376309427"},{"name":"embedding_1","op":"embedding","op_count":99,"config":"weight (Variable) - dtype: float32, shape: [37007, 1024]\nx (Variable) - dtype: int64, shape: [16, 16]\npadding_idx (int): 0\nsparse (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.024465824671948855","paddle_perf_backwards":"0.22513989703891255","paddle_gpu_time":"0.003002562197188122","paddle_gpu_time_backward":"0.20019169928682504"},{"name":"embedding_2","op":"embedding","op_count":99,"config":"weight (Variable) - dtype: float32, shape: [10000, 1500]\nx (Variable) - dtype: int64, shape: [16, 35, 1]\npadding_idx (string): None\nsparse (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03266325233506784","paddle_perf_backwards":"0.16424649237251013","paddle_gpu_time":"0.011698263678578636","paddle_gpu_time_backward":"0.14137664440396683"},{"name":"embedding_3","op":"embedding","op_count":99,"config":"weight (Variable) - dtype: float32, shape: [2, 768]\nx (Variable) - dtype: int64, shape: [16, 128]\npadding_idx (string): None\nsparse (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/embedding_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04492389912507973","paddle_perf_backwards":"0.14276017948072783","paddle_gpu_time":"0.009297934215804252","paddle_gpu_time_backward":"0.10268521585513968"},{"name":"empty_0","op":"empty","op_count":0,"config":"dtype (string): float32\nshape (list): [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/empty_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.01054977884097975","paddle_perf_backwards":"--","paddle_gpu_time":"2.259325044404973e-05","paddle_gpu_time_backward":"--"},{"name":"equal_0","op":"equal","op_count":12,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.021166529110772814","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013521042084168335","paddle_gpu_time_backward":"--"},{"name":"equal_1","op":"equal","op_count":12,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.021524300317248266","paddle_perf_backwards":"--","paddle_gpu_time":"0.002615563886918634","paddle_gpu_time_backward":"--"},{"name":"equal_2","op":"equal","op_count":12,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.024002061817115672","paddle_perf_backwards":"--","paddle_gpu_time":"0.0028576175611720873","paddle_gpu_time_backward":"--"},{"name":"equal_all_0","op":"equal_all","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1000, 2000]\ny (Variable) - dtype: float32, shape: [16, 1000, 2000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.42210647038051063","paddle_perf_backwards":"--","paddle_gpu_time":"0.4457207490260149","paddle_gpu_time_backward":"--"},{"name":"equal_all_1","op":"equal_all","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1000]\ny (Variable) - dtype: float32, shape: [16, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.035654282083316724","paddle_perf_backwards":"--","paddle_gpu_time":"0.00542569776213226","paddle_gpu_time_backward":"--"},{"name":"equal_all_2","op":"equal_all","op_count":0,"config":"x (Variable) - dtype: int32, shape: [16, 1000]\ny (Variable) - dtype: int32, shape: [16, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03613622821107203","paddle_perf_backwards":"--","paddle_gpu_time":"0.005278946096204979","paddle_gpu_time_backward":"--"},{"name":"equal_all_3","op":"equal_all","op_count":0,"config":"x (Variable) - dtype: int64, shape: [16, 1000]\ny (Variable) - dtype: int64, shape: [16, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/equal_all_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.0344853011929259","paddle_perf_backwards":"--","paddle_gpu_time":"0.005342283563362609","paddle_gpu_time_backward":"--"},{"name":"exp_0","op":"exp","op_count":7,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3392261608330187","paddle_perf_backwards":"3.2573307444432933","paddle_gpu_time":"1.322446101148499","paddle_gpu_time_backward":"3.2279376904842536"},{"name":"exp_1","op":"exp","op_count":7,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/exp_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6928261630759688","paddle_perf_backwards":"1.6666504806411528","paddle_gpu_time":"0.678978749118743","paddle_gpu_time_backward":"1.640249146757679"},{"name":"expand_0","op":"expand","op_count":25,"config":"x (Variable) - dtype: float32, shape: [16, 1785, 1]\nshape (list): [1785, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.022324493953159878","paddle_perf_backwards":"0.03478016172136579","paddle_gpu_time":"0.002523275949882856","paddle_gpu_time_backward":"0.005592423473702012"},{"name":"expand_1","op":"expand","op_count":25,"config":"x (Variable) - dtype: float32, shape: [16, 5, 1, 1]\nshape (list): [5, 128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03326498732274892","paddle_perf_backwards":"6.035813993337203","paddle_gpu_time":"0.017062180835085608","paddle_gpu_time_backward":"5.98336174907231"},{"name":"expand_2","op":"expand","op_count":25,"config":"x (Variable) - dtype: float32, shape: [32, 807, 1]\nshape (list): [807, 807]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.11817411500580458","paddle_perf_backwards":"0.728682109287807","paddle_gpu_time":"0.10151060424169668","paddle_gpu_time_backward":"0.7138475836431227"},{"name":"expand_as_0","op":"expand_as","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1785, 1]\ny (Variable) - dtype: float32, shape: [1785, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03571267030677017","paddle_perf_backwards":"0.13750207667448083","paddle_gpu_time":"0.004719107719401232","paddle_gpu_time_backward":"0.11357570663024064"},{"name":"expand_as_1","op":"expand_as","op_count":0,"config":"x (Variable) - dtype: float32, shape: [5, 1, 1]\ny (Variable) - dtype: float32, shape: [5, 128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03656951748594946","paddle_perf_backwards":"4.012747443452173","paddle_gpu_time":"0.0038263436790310374","paddle_gpu_time_backward":"3.983383383383383"},{"name":"expand_as_2","op":"expand_as","op_count":0,"config":"x (Variable) - dtype: float32, shape: [32, 807, 1]\ny (Variable) - dtype: float32, shape: [32, 807, 807]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/expand_as_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.4109163673556581","paddle_perf_backwards":"1.0003987623720754","paddle_gpu_time":"0.36247785198309934","paddle_gpu_time_backward":"0.9843564673825933"},{"name":"feed_0","op":"feed","op_count":0,"config":"None","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/feed_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.1870459634430555","paddle_perf_backwards":"--","paddle_gpu_time":"0.95568","paddle_gpu_time_backward":"--"},{"name":"fetch_0","op":"fetch","op_count":0,"config":"None","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/fetch_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.4941086574476592","paddle_perf_backwards":"--","paddle_gpu_time":"1.1962959255180698","paddle_gpu_time_backward":"--"},{"name":"flatten_0","op":"flatten","op_count":6,"config":"x (Variable) - dtype: float32, shape: [100, 1785, 100]\nstart_axis (int): 1\nstop_axis (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flatten_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2052234143626933","paddle_perf_backwards":"0.39470536368233816","paddle_gpu_time":"0.19870698867279332","paddle_gpu_time_backward":"0.3846774193548387"},{"name":"flip_0","op":"flip","op_count":0,"config":"x (Variable) - dtype: float32, shape: [100, 1785]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/flip_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.038005624498639784","paddle_perf_backwards":"0.05868308398188377","paddle_gpu_time":"0.012275830678197541","paddle_gpu_time_backward":"0.02507102593010146"},{"name":"floor_0","op":"floor","op_count":1,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"1.3394457065987444","paddle_perf_backwards":"1.9435950176032608","paddle_gpu_time":"1.3214364863503576","paddle_gpu_time_backward":"1.9249046081596712"},{"name":"floor_1","op":"floor","op_count":1,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.6903533706206357","paddle_perf_backwards":"1.0030668101950972","paddle_gpu_time":"0.6758086606243705","paddle_gpu_time_backward":"0.9779023323615161"},{"name":"floor_divide_0","op":"floor_divide","op_count":0,"config":"x (Variable) - dtype: int64, shape: [16, 128, 8]\ny (Variable) - dtype: int64, shape: [16, 128, 8]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.022743429456438338","paddle_perf_backwards":"--","paddle_gpu_time":"0.0018792762815846937","paddle_gpu_time_backward":"--"},{"name":"floor_divide_1","op":"floor_divide","op_count":0,"config":"x (Variable) - dtype: int32, shape: [300, 128, 100]\ny (Variable) - dtype: int32, shape: [300, 128, 100]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.08261674391721675","paddle_perf_backwards":"--","paddle_gpu_time":"0.057438408723747975","paddle_gpu_time_backward":"--"},{"name":"floor_divide_2","op":"floor_divide","op_count":0,"config":"x (Variable) - dtype: int64, shape: [300, 128, 100]\ny (Variable) - dtype: int64, shape: [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/floor_divide_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.10862849757284344","paddle_perf_backwards":"--","paddle_gpu_time":"0.07756653225806451","paddle_gpu_time_backward":"--"},{"name":"full_0","op":"full","op_count":0,"config":"dtype (string): float32\nfill_value (float): 210000.0\nshape (list): [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.025311538151332313","paddle_perf_backwards":"--","paddle_gpu_time":"0.001291967830601649","paddle_gpu_time_backward":"--"},{"name":"full_1","op":"full","op_count":0,"config":"dtype (string): int32\nfill_value (int): 0\nshape (list): [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/full_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02579737682731784","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013547534316217592","paddle_gpu_time_backward":"--"},{"name":"gather_0","op":"gather","op_count":35,"config":"index (Variable) - dtype: int32, shape: [16]\ninput (Variable) - dtype: float32, shape: [16, 1]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.021042872448356786","paddle_perf_backwards":"0.04101845682883749","paddle_gpu_time":"0.0034056613276921524","paddle_gpu_time_backward":"0.005989716312056738"},{"name":"gather_1","op":"gather","op_count":35,"config":"index (Variable) - dtype: int32, shape: [16, 1]\ninput (Variable) - dtype: float32, shape: [16, 256, 14, 14]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.023766119317357316","paddle_perf_backwards":"0.04980880093861775","paddle_gpu_time":"0.00678702570379437","paddle_gpu_time_backward":"0.02527811023622047"},{"name":"gather_nd_0","op":"gather_nd","op_count":0,"config":"index (Variable) - dtype: int32, shape: [16, 2]\ninput (Variable) - dtype: float32, shape: [16, 10, 10]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02819883580110511","paddle_perf_backwards":"0.05324762694689693","paddle_gpu_time":"0.003556058036555492","paddle_gpu_time_backward":"0.00862923832923833"},{"name":"gather_nd_1","op":"gather_nd","op_count":0,"config":"index (Variable) - dtype: int32, shape: [16, 3]\ninput (Variable) - dtype: float32, shape: [16, 256, 14, 14]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/gather_nd_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.029893237424184045","paddle_perf_backwards":"0.04806949431637683","paddle_gpu_time":"0.005825424721734036","paddle_gpu_time_backward":"0.010443475733798316"},{"name":"greater_equal_0","op":"greater_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.024361911422026185","paddle_perf_backwards":"--","paddle_gpu_time":"0.0022884172589848835","paddle_gpu_time_backward":"--"},{"name":"greater_equal_1","op":"greater_equal","op_count":0,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020867789197780325","paddle_perf_backwards":"--","paddle_gpu_time":"0.0025632218844984797","paddle_gpu_time_backward":"--"},{"name":"greater_equal_2","op":"greater_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_equal_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.025900045712151844","paddle_perf_backwards":"--","paddle_gpu_time":"0.0034325955734406436","paddle_gpu_time_backward":"--"},{"name":"greater_than_0","op":"greater_than","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.022114780479538177","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013094880272517782","paddle_gpu_time_backward":"--"},{"name":"greater_than_1","op":"greater_than","op_count":0,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.027605383572931998","paddle_perf_backwards":"--","paddle_gpu_time":"0.003134035229803604","paddle_gpu_time_backward":"--"},{"name":"greater_than_2","op":"greater_than","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/greater_than_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.031637404868024625","paddle_perf_backwards":"--","paddle_gpu_time":"0.00285287310053336","paddle_gpu_time_backward":"--"},{"name":"grid_sample_0","op":"grid_sample","op_count":0,"config":"grid (Variable) - dtype: float32, shape: [4, 12, 16, 2]\nx (Variable) - dtype: float32, shape: [4, 1, 32, 32]\nalign_corners (bool): True\nmode (string): bilinear\nout_shape (list): [4, 1, 12, 16]\npadding_mode (string): zeros\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.024002668808917615","paddle_perf_backwards":"0.041827133723667684","paddle_gpu_time":"0.0018206788511749348","paddle_gpu_time_backward":"0.006088800530152419"},{"name":"grid_sample_1","op":"grid_sample","op_count":0,"config":"grid (Variable) - dtype: float32, shape: [4, 128, 128, 2]\nx (Variable) - dtype: float32, shape: [4, 1, 64, 64]\nalign_corners (bool): True\nmode (string): nearest\nout_shape (list): [4, 1, 128, 128]\npadding_mode (string): zeros\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.023510261457793565","paddle_perf_backwards":"0.048361019212372444","paddle_gpu_time":"0.004799011997177136","paddle_gpu_time_backward":"0.015757652072839985"},{"name":"grid_sample_2","op":"grid_sample","op_count":0,"config":"grid (Variable) - dtype: float32, shape: [4, 256, 246, 2]\nx (Variable) - dtype: float32, shape: [4, 1, 128, 128]\nalign_corners (bool): False\nmode (string): bilinear\nout_shape (list): [4, 1, 256, 256]\npadding_mode (string): zeros\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.032491100077726404","paddle_perf_backwards":"0.08906685576146964","paddle_gpu_time":"0.015161632845681925","paddle_gpu_time_backward":"0.06789697802197803"},{"name":"grid_sample_3","op":"grid_sample","op_count":0,"config":"grid (Variable) - dtype: float32, shape: [4, 256, 246, 2]\nx (Variable) - dtype: float32, shape: [4, 1, 128, 128]\nalign_corners (bool): False\nmode (string): bilinear\nout_shape (list): [4, 1, 256, 256]\npadding_mode (string): reflection\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.035432406834193644","paddle_perf_backwards":"0.09401379799356266","paddle_gpu_time":"0.017641325536062378","paddle_gpu_time_backward":"0.07483816964285712"},{"name":"grid_sample_4","op":"grid_sample","op_count":0,"config":"grid (Variable) - dtype: float32, shape: [4, 256, 246, 2]\nx (Variable) - dtype: float32, shape: [4, 1, 128, 128]\nalign_corners (bool): False\nmode (string): bilinear\nout_shape (list): [4, 1, 256, 256]\npadding_mode (string): border\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/grid_sample_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.033201003561214526","paddle_perf_backwards":"0.09058251672861528","paddle_gpu_time":"0.015051062331259538","paddle_gpu_time_backward":"0.05826056921801602"},{"name":"group_norm_0","op":"group_norm","op_count":3,"config":"x (Variable) - dtype: float32, shape: [8, 6, 10, 10]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nnum_groups (int): 3\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/group_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.039115730597048384","paddle_perf_backwards":"0.07276024137224471","paddle_gpu_time":"0.006600294623127915","paddle_gpu_time_backward":"0.016712980269989616"},{"name":"histogram_0","op":"histogram","op_count":0,"config":"input (Variable) - dtype: int32, shape: [16, 64]\nbins (int32): 100\nmax (int32): 0\nmin (int32): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.12597259210080516","paddle_perf_backwards":"0.12511525835309711","paddle_gpu_time":"0.05507212657049791","paddle_gpu_time_backward":"0.055234867959803695"},{"name":"histogram_1","op":"histogram","op_count":0,"config":"input (Variable) - dtype: int64, shape: [16, 64]\nbins (int32): 100\nmax (int32): 0\nmin (int32): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.12825532835357042","paddle_perf_backwards":"0.1258419484508281","paddle_gpu_time":"0.0611083180987203","paddle_gpu_time_backward":"0.061410902427851584"},{"name":"histogram_2","op":"histogram","op_count":0,"config":"input (Variable) - dtype: float32, shape: [16, 64]\nbins (int32): 100\nmax (int32): 0\nmin (int32): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/histogram_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.08051541386818399","paddle_perf_backwards":"0.07784220637107382","paddle_gpu_time":"0.0126065188172043","paddle_gpu_time_backward":"0.012797489263296994"},{"name":"increment_0","op":"increment","op_count":11,"config":"x (Variable) - dtype: int32, shape: [1]\nin_place (bool): True\nvalue (float): 1.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/increment_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.017014085030069154","paddle_perf_backwards":"--","paddle_gpu_time":"0.001333706492977814","paddle_gpu_time_backward":"--"},{"name":"index_sample_0","op":"index_sample","op_count":0,"config":"index (Variable) - dtype: int64, shape: [5100, 1]\nx (Variable) - dtype: float32, shape: [5100, 38506]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.020728347537753822","paddle_perf_backwards":"1.0043110814061131","paddle_gpu_time":"0.009198625858838226","paddle_gpu_time_backward":"0.9757478957509382"},{"name":"index_sample_1","op":"index_sample","op_count":0,"config":"index (Variable) - dtype: int64, shape: [100, 64]\nx (Variable) - dtype: float32, shape: [100, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.019601899750378664","paddle_perf_backwards":"0.037160941532679966","paddle_gpu_time":"0.0015662502559901702","paddle_gpu_time_backward":"0.0046728314665277415"},{"name":"index_sample_2","op":"index_sample","op_count":0,"config":"index (Variable) - dtype: int64, shape: [5100, 96]\nx (Variable) - dtype: float32, shape: [5100, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_sample_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.02770572302331886","paddle_perf_backwards":"0.044789898347663115","paddle_gpu_time":"0.013315280464216633","paddle_gpu_time_backward":"0.02855679093089165"},{"name":"index_select_0","op":"index_select","op_count":0,"config":"index (Variable) - dtype: int64, shape: [10]\nx (Variable) - dtype: float32, shape: [100, 1785]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03041004648013991","paddle_perf_backwards":"0.05556904539770009","paddle_gpu_time":"0.0024032584389308913","paddle_gpu_time_backward":"0.00918456980937661"},{"name":"index_select_1","op":"index_select","op_count":0,"config":"index (Variable) - dtype: int, shape: [10]\nx (Variable) - dtype: float32, shape: [100, 100, 100]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/index_select_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.032358266869369816","paddle_perf_backwards":"0.08342047126925721","paddle_gpu_time":"0.004383363471971067","paddle_gpu_time_backward":"0.0404170403587444"},{"name":"instance_norm_0","op":"instance_norm","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256, 32, 32]\neps (float): 1e-05\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/instance_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.10722511743445952","paddle_perf_backwards":"0.19126249604435808","paddle_gpu_time":"0.07680715748625634","paddle_gpu_time_backward":"0.1610071663761379"},{"name":"interp_area_0","op":"interp_area","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 512, 64, 64]\nalign_corners (bool): False\ndata_format (string): NHWC\ninterp_mode (string): area\nscale_factor (string): None\nsize (list): [128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"3.817060772253542","paddle_perf_backwards":"5.061308461792615","paddle_gpu_time":"4.030509156771986","paddle_gpu_time_backward":"5.285037603905528"},{"name":"interp_area_1","op":"interp_area","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 64, 64]\nalign_corners (bool): True\ndata_format (string): NCHW\ninterp_mode (string): area\nscale_factor (string): None\nsize (list): [32, 64]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.1044382854383819","paddle_perf_backwards":"0.20921716884690889","paddle_gpu_time":"0.09818303755674783","paddle_gpu_time_backward":"0.2090782800441014"},{"name":"interp_area_2","op":"interp_area","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2, 5, 12, 12]\nalign_corners (bool): False\ndata_format (string): NDHWC\ninterp_mode (string): area\nscale_factor (string): None\nsize (list): [10, 6, 4]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_area_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.02519281543031031","paddle_perf_backwards":"0.042801487202547034","paddle_gpu_time":"0.0062362775707523405","paddle_gpu_time_backward":"0.013821175950486294"},{"name":"interp_bicubic_0","op":"interp_bicubic","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 512, 64, 64]\nalign_corners (bool): False\ndata_format (string): NHWC\ninterp_mode (string): bicubic\nscale_factor (string): None\nsize (list): [128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.8012362888881138","paddle_perf_backwards":"2.5448738312234687","paddle_gpu_time":"0.8278441879637263","paddle_gpu_time_backward":"2.5320562560620754"},{"name":"interp_bicubic_1","op":"interp_bicubic","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 64, 64]\nalign_corners (bool): True\ndata_format (string): NCHW\ninterp_mode (string): bicubic\nscale_factor (float32): 2.0\nsize (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.6469135381737534","paddle_perf_backwards":"2.1377130430571887","paddle_gpu_time":"0.639441430580671","paddle_gpu_time_backward":"2.135330548754141"},{"name":"interp_bicubic_2","op":"interp_bicubic","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 64, 64]\nalign_corners (bool): False\ndata_format (string): NHWC\ninterp_mode (string): bicubic\nscale_factor (list): [2, 3]\nsize (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bicubic_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.1511053357805523","paddle_perf_backwards":"2.6090643843825982","paddle_gpu_time":"1.107781789009226","paddle_gpu_time_backward":"2.5848727531589253"},{"name":"interp_bilinear_0","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 512, 64, 402]\nalign_corners (bool): True\ndata_format (string): NCHW\nscale_factor (string): None\nsize (list): [128, 402]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"8.696240308333415","paddle_perf_backwards":"33.324586371986236","paddle_gpu_time":"8.824231943031535","paddle_gpu_time_backward":"33.34018426647768"},{"name":"interp_bilinear_1","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 402, 512]\nalign_corners (bool): True\ndata_format (string): NHWC\nscale_factor (string): None\nsize (list): [128, 402]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"11.210425289309754","paddle_perf_backwards":"32.068995067051475","paddle_gpu_time":"11.353298875038005","paddle_gpu_time_backward":"32.096297499188054"},{"name":"interp_bilinear_2","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256, 1, 1]\nalign_corners (bool): True\ndata_format (string): NCHW\nscale_factor (string): None\nsize (tuple): [33, 33]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.10739394596644809","paddle_perf_backwards":"1.6636850882549674","paddle_gpu_time":"0.09763028908672601","paddle_gpu_time_backward":"1.658714918759232"},{"name":"interp_bilinear_3","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 1, 256]\nalign_corners (bool): True\ndata_format (string): NHWC\nscale_factor (string): None\nsize (tuple): [33, 33]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.14252200418589067","paddle_perf_backwards":"0.5603838940056003","paddle_gpu_time":"0.11390278055611121","paddle_gpu_time_backward":"0.5767805732882714"},{"name":"interp_bilinear_4","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 19, 129, 129]\nalign_corners (bool): True\ndata_format (string): NCHW\nscale_factor (string): None\nsize (tuple): [513, 513]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.5597649982997348","paddle_perf_backwards":"4.268120016370501","paddle_gpu_time":"1.520406935952691","paddle_gpu_time_backward":"4.187873045949787"},{"name":"interp_bilinear_5","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 129, 129, 19]\nalign_corners (bool): True\ndata_format (string): NHWC\nscale_factor (string): None\nsize (tuple): [513, 513]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.9198765560072295","paddle_perf_backwards":"3.837694440569196","paddle_gpu_time":"1.8958016032064129","paddle_gpu_time_backward":"3.814294330518697"},{"name":"interp_bilinear_6","op":"interp_bilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [4, 256, 1, 1]\nalign_corners (bool): False\ndata_format (string): NCHW\nscale_factor (string): None\nsize (tuple): [64, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_bilinear_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.2006504000449667","paddle_perf_backwards":"4.9196644705169055","paddle_gpu_time":"0.15369073814762954","paddle_gpu_time_backward":"4.929890518487916"},{"name":"interp_linear_0","op":"interp_linear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 512, 64]\nalign_corners (bool): False\ndata_format (string): NCW\ninterp_mode (string): linear\nscale_factor (string): None\nsize (list): [128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.036274900241773954","paddle_perf_backwards":"0.0617457895862813","paddle_gpu_time":"0.01837799140928615","paddle_gpu_time_backward":"0.03985640805829405"},{"name":"interp_linear_1","op":"interp_linear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 64]\nalign_corners (bool): True\ndata_format (string): NCW\ninterp_mode (string): linear\nscale_factor (float32): 2.0\nsize (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_linear_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.02454494943424147","paddle_perf_backwards":"0.04094717453937141","paddle_gpu_time":"0.004960742544126598","paddle_gpu_time_backward":"0.010877189093327421"},{"name":"interp_nearest_0","op":"interp_nearest","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256, 16, 16]\nalign_corners (bool): False\ndata_format (string): NCHW\nscale_factor (string): None\nsize (list): [32, 32]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.09962125700347278","paddle_perf_backwards":"0.17396308937851263","paddle_gpu_time":"0.08315327140549274","paddle_gpu_time_backward":"0.16094248234106961"},{"name":"interp_nearest_1","op":"interp_nearest","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 16, 16, 256]\nalign_corners (bool): False\ndata_format (string): NHWC\nscale_factor (string): None\nsize (list): [32, 32]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_nearest_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.11432998034418847","paddle_perf_backwards":"0.20904881613595144","paddle_gpu_time":"0.10488664987405541","paddle_gpu_time_backward":"0.20972809667673714"},{"name":"interp_trilinear_0","op":"interp_trilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 25, 12, 32, 64]\nalign_corners (bool): False\ndata_format (string): NCDHW\ninterp_mode (string): trilinear\nscale_factor (string): None\nsize (list): [64, 16, 32]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.461788323460793","paddle_perf_backwards":"1.2910850194035743","paddle_gpu_time":"0.4185230393652731","paddle_gpu_time_backward":"1.2455647734524569"},{"name":"interp_trilinear_1","op":"interp_trilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 25, 7, 8, 9]\nalign_corners (bool): True\ndata_format (string): NCDHW\ninterp_mode (string): trilinear\nscale_factor (float32): 2.0\nsize (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.07926468946495835","paddle_perf_backwards":"0.21818827609626615","paddle_gpu_time":"0.05245561239843515","paddle_gpu_time_backward":"0.17359583092067168"},{"name":"interp_trilinear_2","op":"interp_trilinear","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 5, 12, 24, 8]\nalign_corners (bool): False\ndata_format (string): NCDHW\ninterp_mode (string): trilinear\nscale_factor (list): [2, 3, 4]\nsize (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/interp_trilinear_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.15537787456901708","paddle_perf_backwards":"0.4412288568457779","paddle_gpu_time":"0.14975975975975975","paddle_gpu_time_backward":"0.41418031577394127"},{"name":"inverse_0","op":"inverse","op_count":0,"config":"x (Variable) - dtype: float32, shape: [128, 64, 64]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/inverse_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.33941998773691606","paddle_perf_backwards":"0.3875311540097606","paddle_gpu_time":"0.3068543689320388","paddle_gpu_time_backward":"0.3396419995634141"},{"name":"isfinite_0","op":"isfinite","op_count":6,"config":"x (Variable) - dtype: float32, shape: [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.03277160683456733","paddle_perf_backwards":"--","paddle_gpu_time":"0.004143530644316396","paddle_gpu_time_backward":"--"},{"name":"isfinite_1","op":"isfinite","op_count":6,"config":"x (Variable) - dtype: float32, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.029468049808424344","paddle_perf_backwards":"--","paddle_gpu_time":"0.006800171037628278","paddle_gpu_time_backward":"--"},{"name":"isfinite_2","op":"isfinite","op_count":6,"config":"x (Variable) - dtype: float16, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isfinite_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.030615135115020134","paddle_perf_backwards":"--","paddle_gpu_time":"0.0064143126177024475","paddle_gpu_time_backward":"--"},{"name":"isinf_0","op":"isinf","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.01952721148121114","paddle_perf_backwards":"--","paddle_gpu_time":"0.001327466937945066","paddle_gpu_time_backward":"--"},{"name":"isinf_1","op":"isinf","op_count":0,"config":"x (Variable) - dtype: float32, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020951397564946385","paddle_perf_backwards":"--","paddle_gpu_time":"0.002009669889963321","paddle_gpu_time_backward":"--"},{"name":"isinf_2","op":"isinf","op_count":0,"config":"x (Variable) - dtype: float16, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isinf_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020397196010667452","paddle_perf_backwards":"--","paddle_gpu_time":"0.001816211020931226","paddle_gpu_time_backward":"--"},{"name":"isnan_0","op":"isnan","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.01970918811097437","paddle_perf_backwards":"--","paddle_gpu_time":"0.001351002136534744","paddle_gpu_time_backward":"--"},{"name":"isnan_1","op":"isnan","op_count":0,"config":"x (Variable) - dtype: float32, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.018678149398492303","paddle_perf_backwards":"--","paddle_gpu_time":"0.002005590339892666","paddle_gpu_time_backward":"--"},{"name":"isnan_2","op":"isnan","op_count":0,"config":"x (Variable) - dtype: float16, shape: [300, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/isnan_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020170211791992188","paddle_perf_backwards":"--","paddle_gpu_time":"0.0017497854077253218","paddle_gpu_time_backward":"--"},{"name":"layer_norm_0","op":"layer_norm","op_count":20,"config":"x (Variable) - dtype: float32, shape: [16, 128, 768]\nepsilon (float): 1e-05\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/layer_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.13521642101054288","paddle_perf_backwards":"0.36057014854586855","paddle_gpu_time":"0.1100323297635886","paddle_gpu_time_backward":"0.33689263033525335"},{"name":"leaky_relu_0","op":"leaky_relu","op_count":3,"config":"x (Variable) - dtype: float32, shape: [16, 512, 31, 31]\nnegative_slope (float): 0.1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.09324076664016907","paddle_perf_backwards":"0.20965026564387432","paddle_gpu_time":"0.07900791235544735","paddle_gpu_time_backward":"0.19197085239789868"},{"name":"leaky_relu_1","op":"leaky_relu","op_count":3,"config":"x (Variable) - dtype: float16, shape: [16, 512, 31, 31]\nnegative_slope (float): 0.1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/leaky_relu_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.054547154759786214","paddle_perf_backwards":"0.11477183146649096","paddle_gpu_time":"0.041238075908260605","paddle_gpu_time_backward":"0.09906842818428184"},{"name":"less_equal_0","op":"less_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0410406527395","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013217400020046105","paddle_gpu_time_backward":"--"},{"name":"less_equal_1","op":"less_equal","op_count":0,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020836398214519856","paddle_perf_backwards":"--","paddle_gpu_time":"0.00220711743772242","paddle_gpu_time_backward":"--"},{"name":"less_equal_2","op":"less_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_equal_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.029476324398675282","paddle_perf_backwards":"--","paddle_gpu_time":"0.0028485305958132045","paddle_gpu_time_backward":"--"},{"name":"less_than_0","op":"less_than","op_count":23,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.014719098268864386","paddle_perf_backwards":"--","paddle_gpu_time":"0.001259897764859176","paddle_gpu_time_backward":"--"},{"name":"less_than_1","op":"less_than","op_count":23,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.021601559403903018","paddle_perf_backwards":"--","paddle_gpu_time":"0.0025733252254991385","paddle_gpu_time_backward":"--"},{"name":"less_than_2","op":"less_than","op_count":23,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/less_than_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02500320484260758","paddle_perf_backwards":"--","paddle_gpu_time":"0.0033214321633309864","paddle_gpu_time_backward":"--"},{"name":"lgamma_0","op":"lgamma","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3457936848810537","paddle_perf_backwards":"4.0218410606613615","paddle_gpu_time":"1.329283771532185","paddle_gpu_time_backward":"4.1104329835968665"},{"name":"lgamma_1","op":"lgamma","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lgamma_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"linear_0","op":"linear","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [2048]\nweight (Variable) - dtype: float32, shape: [36864, 2048]\nx (Variable) - dtype: float32, shape: [16, 36864]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.449491277032969","paddle_perf_backwards":"1.321918623788016","paddle_gpu_time":"0.4374772405421809","paddle_gpu_time_backward":"1.2757328072153327"},{"name":"linear_1","op":"linear","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [1024]\nweight (Variable) - dtype: float32, shape: [1024, 1024]\nx (Variable) - dtype: float32, shape: [16, 16, 1024]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.10060801797983597","paddle_perf_backwards":"0.2169280636067293","paddle_gpu_time":"0.06479671232876713","paddle_gpu_time_backward":"0.17398142414860684"},{"name":"linear_2","op":"linear","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [1024]\nweight (Variable) - dtype: float32, shape: [12544, 1024]\nx (Variable) - dtype: float32, shape: [16, 12544]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.12507908272020743","paddle_perf_backwards":"0.3091891606648763","paddle_gpu_time":"0.10488331892826273","paddle_gpu_time_backward":"0.2647800504342953"},{"name":"linear_3","op":"linear","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [256]\nweight (Variable) - dtype: float32, shape: [16, 256]\nx (Variable) - dtype: float32, shape: [16, 16]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linear_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.040891949011355025","paddle_perf_backwards":"0.10224288823653241","paddle_gpu_time":"0.004309962497961846","paddle_gpu_time_backward":"0.013321499800558434"},{"name":"linspace_0","op":"linspace","op_count":0,"config":"dtype (string): float32\nnum (int): 5\nstart (float64): -100.0\nstop (float64): 100.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.049633882483657535","paddle_perf_backwards":"--","paddle_gpu_time":"0.0012627885691040375","paddle_gpu_time_backward":"--"},{"name":"linspace_1","op":"linspace","op_count":0,"config":"dtype (string): float32\nnum (int): 1000\nstart (float64): 32.0\nstop (float64): 82.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/linspace_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.04977863662096919","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013703364847006201","paddle_gpu_time_backward":"--"},{"name":"log_0","op":"log","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.340620025604187","paddle_perf_backwards":"3.2543008456488174","paddle_gpu_time":"1.322904915390814","paddle_gpu_time_backward":"3.229098915989159"},{"name":"log_1","op":"log","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.0603.112711.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.0603.112711.gcc82.post107.develop/log_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"log_softmax_0","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.019272492856395488","paddle_perf_backwards":"0.028342130232830436","paddle_gpu_time":"0.0057528169014084505","paddle_gpu_time_backward":"0.00923935052531041"},{"name":"log_softmax_1","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"False","paddle_perf":"0.0211384831642618","paddle_perf_backwards":"0.02587887705588827","paddle_gpu_time":"0.007826928865255343","paddle_gpu_time_backward":"0.012914138902701808"},{"name":"log_softmax_2","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float32, shape: [32, 12, 128, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0784462235538835","paddle_perf_backwards":"0.17099332617947374","paddle_gpu_time":"0.06363765469669304","paddle_gpu_time_backward":"0.15468924640135479"},{"name":"log_softmax_3","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"False","paddle_consistency_backwards":"False","paddle_perf":"0.04895312719076991","paddle_perf_backwards":"0.09749850116101613","paddle_gpu_time":"0.03363663998378762","paddle_gpu_time_backward":"0.08140840278959006"},{"name":"log_softmax_4","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float32, shape: [15, 16, 33, 33]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.019455601074891478","paddle_perf_backwards":"0.029212105011414434","paddle_gpu_time":"0.005085014553849242","paddle_gpu_time_backward":"0.009998027613412229"},{"name":"log_softmax_5","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float16, shape: [15, 16, 33, 33]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"False","paddle_consistency_backwards":"False","paddle_perf":"0.01930910981967597","paddle_perf_backwards":"0.02980210738096065","paddle_gpu_time":"0.004378771173699509","paddle_gpu_time_backward":"0.01007200791295747"},{"name":"log_softmax_6","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float32, shape: [128, 128, 16, 16]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.21445142979524573","paddle_perf_backwards":"1.1767450644045458","paddle_gpu_time":"0.2026585489599188","paddle_gpu_time_backward":"1.187977420129714"},{"name":"log_softmax_7","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float16, shape: [128, 128, 16, 16]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"False","paddle_consistency_backwards":"False","paddle_perf":"0.20630529948643275","paddle_perf_backwards":"0.7982173744513064","paddle_gpu_time":"0.18132311415893507","paddle_gpu_time_backward":"0.7899249870667356"},{"name":"log_softmax_8","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.7913399715812839","paddle_perf_backwards":"14.760586193629672","paddle_gpu_time":"0.7667415042351261","paddle_gpu_time_backward":"14.744752663221178"},{"name":"log_softmax_9","op":"log_softmax","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/log_softmax_9-tensorflow_gpu_speed_forward.txt","paddle_consistency":"False","paddle_consistency_backwards":"False","paddle_perf":"0.624443803514753","paddle_perf_backwards":"14.446062457804777","paddle_gpu_time":"0.632985724410246","paddle_gpu_time_backward":"14.357635262168374"},{"name":"logical_and_0","op":"logical_and","op_count":4,"config":"x (Variable) - dtype: bool, shape: [16, 1785]\ny (Variable) - dtype: bool, shape: [16, 1785]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.021037763478804605","paddle_perf_backwards":"--","paddle_gpu_time":"0.0014450465187608628","paddle_gpu_time_backward":"--"},{"name":"logical_and_1","op":"logical_and","op_count":4,"config":"x (Variable) - dtype: bool, shape: [1]\ny (Variable) - dtype: bool, shape: [1]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_and_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.021480008929908152","paddle_perf_backwards":"--","paddle_gpu_time":"0.001342951608055305","paddle_gpu_time_backward":"--"},{"name":"logical_not_0","op":"logical_not","op_count":2,"config":"x (Variable) - dtype: bool, shape: [1]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_not_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020251225452033842","paddle_perf_backwards":"--","paddle_gpu_time":"0.0013275704261161395","paddle_gpu_time_backward":"--"},{"name":"logical_or_0","op":"logical_or","op_count":0,"config":"x (Variable) - dtype: bool, shape: [16, 1785]\ny (Variable) - dtype: bool, shape: [16, 1785]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02388662221480389","paddle_perf_backwards":"--","paddle_gpu_time":"0.0014454219948849105","paddle_gpu_time_backward":"--"},{"name":"logical_or_1","op":"logical_or","op_count":0,"config":"x (Variable) - dtype: bool, shape: [1]\ny (Variable) - dtype: bool, shape: [1]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logical_or_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.024704799384535677","paddle_perf_backwards":"--","paddle_gpu_time":"0.0012268764405251027","paddle_gpu_time_backward":"--"},{"name":"logsumexp_0","op":"logsumexp","op_count":0,"config":"x (Variable) - dtype: float32, shape: [64, 64]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.047530933302275986","paddle_perf_backwards":"0.05550408849910815","paddle_gpu_time":"0.026229007633587785","paddle_gpu_time_backward":"0.03236606116348586"},{"name":"logsumexp_1","op":"logsumexp","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1024, 512]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/logsumexp_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.09582845532164282","paddle_perf_backwards":"0.10422589827557","paddle_gpu_time":"0.07801795173631548","paddle_gpu_time_backward":"0.08362762099952704"},{"name":"lstm_0","op":"lstm","op_count":1,"config":"inital_states (Variable) - dtype: float32, shape: [2, 20, 200]\ninputs (Variable) - dtype: float32, shape: [20, 20, 200]\ndirection (string): forward\nhidden_size (int): 200\nnum_layers (int): 2\nsequence_length (int): 20\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/lstm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"37.90393362239916","paddle_perf_backwards":"--","paddle_gpu_time":"2.858360491351216","paddle_gpu_time_backward":"--"},{"name":"masked_select_0","op":"masked_select","op_count":0,"config":"mask (Variable) - dtype: bool, shape: [524288]\nx (Variable) - dtype: int32, shape: [524288]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.8505439271732252","paddle_perf_backwards":"4.249060883813975","paddle_gpu_time":"0.03860883720930233","paddle_gpu_time_backward":"0.0714328743545611"},{"name":"masked_select_1","op":"masked_select","op_count":0,"config":"mask (Variable) - dtype: bool, shape: [524288, 2]\nx (Variable) - dtype: float32, shape: [524288, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/masked_select_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.9208954002962534","paddle_perf_backwards":"1.3770919248282192","paddle_gpu_time":"0.06021037253469686","paddle_gpu_time_backward":"0.11727630838491841"},{"name":"matmul_0","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [16, 128, 8]\ny (Variable) - dtype: float32, shape: [16, 8, 32]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02391192377830038","paddle_perf_backwards":"0.05573910109850825","paddle_gpu_time":"0.005289309442319308","paddle_gpu_time_backward":"0.02840518816222141"},{"name":"matmul_1","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [16, 35, 1500]\ny (Variable) - dtype: float32, shape: [1500, 10000]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.4757951911614864","paddle_perf_backwards":"4.188800101377526","paddle_gpu_time":"1.448476286579213","paddle_gpu_time_backward":"4.178450704225352"},{"name":"matmul_2","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [16, 3000]\ny (Variable) - dtype: float32, shape: [3000, 6000]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13569729600497382","paddle_perf_backwards":"0.36570089374611037","paddle_gpu_time":"0.11201809396525134","paddle_gpu_time_backward":"0.3400709040263358"},{"name":"matmul_3","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [16, 1, 512]\ny (Variable) - dtype: float32, shape: [16, 16, 512]\ntranspose_x (bool): False\ntranspose_y (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02594379463581124","paddle_perf_backwards":"0.04593158009076359","paddle_gpu_time":"0.003687982527427875","paddle_gpu_time_backward":"0.012859339758047978"},{"name":"matmul_4","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [16, 1024]\ny (Variable) - dtype: float32, shape: [37007, 1024]\ntranspose_x (bool): False\ntranspose_y (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.26045815500324376","paddle_perf_backwards":"0.6984235528475774","paddle_gpu_time":"0.23884417029022148","paddle_gpu_time_backward":"0.6687573303546496"},{"name":"matmul_5","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [512, 4, 896, 2]\ny (Variable) - dtype: float32, shape: [512, 4, 12, 2]\ntranspose_x (bool): False\ntranspose_y (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6028146159892179","paddle_perf_backwards":"3.433480554697465","paddle_gpu_time":"0.587262682069312","paddle_gpu_time_backward":"3.430220514533912"},{"name":"matmul_6","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float16, shape: [512, 4, 896, 2]\ny (Variable) - dtype: float16, shape: [512, 4, 12, 2]\ntranspose_x (bool): False\ntranspose_y (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.415692037465621","paddle_perf_backwards":"2.0259876640475527","paddle_gpu_time":"0.39826392373306574","paddle_gpu_time_backward":"1.9641432791728215"},{"name":"matmul_7","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float16, shape: [512, 4, 896, 8]\ny (Variable) - dtype: float16, shape: [512, 4, 16, 8]\ntranspose_x (bool): False\ntranspose_y (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.26750296962504483","paddle_perf_backwards":"0.7261492768112494","paddle_gpu_time":"0.27538743882544864","paddle_gpu_time_backward":"0.7251646149441741"},{"name":"matmul_8","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float32, shape: [4, 12, 64, 85]\ny (Variable) - dtype: float32, shape: [4, 12, 85, 512]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.05597873609893176","paddle_perf_backwards":"0.16441369543270187","paddle_gpu_time":"0.03829849498327759","paddle_gpu_time_backward":"0.14591898297780653"},{"name":"matmul_9","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float16, shape: [4, 12, 64, 85]\ny (Variable) - dtype: float16, shape: [4, 12, 85, 512]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_9-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04513069074981067","paddle_perf_backwards":"0.13665617728719906","paddle_gpu_time":"0.023698458975426905","paddle_gpu_time_backward":"0.1255202156334232"},{"name":"matmul_10","op":"matmul","op_count":126,"config":"x (Variable) - dtype: float16, shape: [4, 12, 64, 88]\ny (Variable) - dtype: float16, shape: [4, 12, 88, 512]\ntranspose_x (bool): False\ntranspose_y (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/matmul_10-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03124280851714465","paddle_perf_backwards":"0.07538162932103994","paddle_gpu_time":"0.013614432109308282","paddle_gpu_time_backward":"0.05356629966491144"},{"name":"max_0","op":"max","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1996272312615343","paddle_perf_backwards":"1.6810679722405626","paddle_gpu_time":"0.1831203731873035","paddle_gpu_time_backward":"1.6361644454483848"},{"name":"max_1","op":"max","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02513029137436225","paddle_perf_backwards":"0.03712907129404496","paddle_gpu_time":"0.0015795060216370687","paddle_gpu_time_backward":"0.005473691384950927"},{"name":"max_2","op":"max","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.024892359363789456","paddle_perf_backwards":"0.03859777839816346","paddle_gpu_time":"0.0016271564846762733","paddle_gpu_time_backward":"0.0060422764227642265"},{"name":"max_3","op":"max","op_count":0,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"False","paddle_perf":"0.1707858934192237","paddle_perf_backwards":"0.5447126342681701","paddle_gpu_time":"0.1477621364248007","paddle_gpu_time_backward":"0.5022187050359712"},{"name":"max_pool2d_0","op":"max_pool2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 64, 112, 112]\nceil_mode (bool): False\ndata_format (string): NCHW\nkernel_size (list): [3, 3]\npadding (list): [1, 1]\nreturn_indices (bool): False\nstride (list): [2, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/max_pool2d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.1351168835498243","paddle_perf_backwards":"0.466054271023915","paddle_gpu_time":"0.115032002438281","paddle_gpu_time_backward":"0.43973380035026255"},{"name":"maximum_0","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08477045370413137","paddle_perf_backwards":"0.2148625967619536","paddle_gpu_time":"0.06434112806101967","paddle_gpu_time_backward":"0.19760766260766258"},{"name":"maximum_1","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0842081759879011","paddle_perf_backwards":"0.216521385437501","paddle_gpu_time":"0.06455680902497984","paddle_gpu_time_backward":"0.1983405012605665"},{"name":"maximum_2","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03605414488033684","paddle_perf_backwards":"0.0872597665729408","paddle_gpu_time":"0.017323262839879155","paddle_gpu_time_backward":"0.06688649500788228"},{"name":"maximum_3","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13847967426858113","paddle_perf_backwards":"0.3543486337145727","paddle_gpu_time":"0.12139682860317139","paddle_gpu_time_backward":"0.3307553729456384"},{"name":"maximum_4","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06175253816501411","paddle_perf_backwards":"2.0458938602455152","paddle_gpu_time":"0.042671701913393756","paddle_gpu_time_backward":"1.9967626633986926"},{"name":"maximum_5","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.24409814922508594","paddle_perf_backwards":"2.8593028236725524","paddle_gpu_time":"0.22475163727959693","paddle_gpu_time_backward":"2.818225263386554"},{"name":"maximum_6","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"maximum_7","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"maximum_8","op":"maximum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/maximum_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"mean_0","op":"mean","op_count":89,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.19941306066417502","paddle_perf_backwards":"0.8797586083651067","paddle_gpu_time":"0.17356331168831166","paddle_gpu_time_backward":"0.8514483020780537"},{"name":"mean_1","op":"mean","op_count":89,"config":"x (Variable) - dtype: float32, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02769718364793427","paddle_perf_backwards":"0.03843818392072405","paddle_gpu_time":"0.0014884505314799671","paddle_gpu_time_backward":"0.003995257763500076"},{"name":"mean_2","op":"mean","op_count":89,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.024625476525754343","paddle_perf_backwards":"0.03720108343630421","paddle_gpu_time":"0.0018345498783454988","paddle_gpu_time_backward":"0.0038994013967409377"},{"name":"mean_3","op":"mean","op_count":89,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mean_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.17038841763574755","paddle_perf_backwards":"0.33359004404836284","paddle_gpu_time":"0.14776168804302853","paddle_gpu_time_backward":"0.30683249749247743"},{"name":"min_0","op":"min","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2019447649648051","paddle_perf_backwards":"1.6795070950158375","paddle_gpu_time":"0.18284729263841004","paddle_gpu_time_backward":"1.638775971093044"},{"name":"min_1","op":"min","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.025422475775893856","paddle_perf_backwards":"0.037416876578817565","paddle_gpu_time":"0.00158078022875817","paddle_gpu_time_backward":"0.006353684776761698"},{"name":"min_2","op":"min","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.028192510410230985","paddle_perf_backwards":"0.03805306493019571","paddle_gpu_time":"0.0016269156602050138","paddle_gpu_time_backward":"0.005136037114636337"},{"name":"min_3","op":"min","op_count":0,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/min_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.17143982445787573","paddle_perf_backwards":"0.5299362247597001","paddle_gpu_time":"0.14782977842203354","paddle_gpu_time_backward":"0.5029080972242197"},{"name":"minimum_0","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0823591803167914","paddle_perf_backwards":"0.22396069985848885","paddle_gpu_time":"0.06434012444801285","paddle_gpu_time_backward":"0.19712989138521056"},{"name":"minimum_1","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08796587257920381","paddle_perf_backwards":"0.2209703764600123","paddle_gpu_time":"0.06456679427765465","paddle_gpu_time_backward":"0.19724758364312267"},{"name":"minimum_2","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04870748233221815","paddle_perf_backwards":"0.09130344601097948","paddle_gpu_time":"0.01732749068197844","paddle_gpu_time_backward":"0.06639831623257038"},{"name":"minimum_3","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13916365847081125","paddle_perf_backwards":"0.3519819829172505","paddle_gpu_time":"0.12137850939204199","paddle_gpu_time_backward":"0.32924904942965777"},{"name":"minimum_4","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06165571346550523","paddle_perf_backwards":"1.9735966034547123","paddle_gpu_time":"0.04274889157597743","paddle_gpu_time_backward":"1.941657300500664"},{"name":"minimum_5","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.24310541535188293","paddle_perf_backwards":"2.8595978129125075","paddle_gpu_time":"0.22472899455974207","paddle_gpu_time_backward":"2.816858570497501"},{"name":"minimum_6","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"minimum_7","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"minimum_8","op":"minimum","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/minimum_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"multiply_0","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08440452056365448","paddle_perf_backwards":"0.23651508478311684","paddle_gpu_time":"0.06434256749974906","paddle_gpu_time_backward":"0.21253546353345745"},{"name":"multiply_1","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08386289906167316","paddle_perf_backwards":"0.23416803929514304","paddle_gpu_time":"0.06465491183879093","paddle_gpu_time_backward":"0.21090241796200343"},{"name":"multiply_2","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03712829463706466","paddle_perf_backwards":"0.09263433769852938","paddle_gpu_time":"0.017599919460384576","paddle_gpu_time_backward":"0.0671187106918239"},{"name":"multiply_3","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13811268166215243","paddle_perf_backwards":"0.3538968090065018","paddle_gpu_time":"0.12137749949505153","paddle_gpu_time_backward":"0.32916270218839194"},{"name":"multiply_4","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06350551196234021","paddle_perf_backwards":"2.1210637503492094","paddle_gpu_time":"0.04271555197421434","paddle_gpu_time_backward":"2.0728673469387755"},{"name":"multiply_5","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.24462634910323577","paddle_perf_backwards":"2.8581989074278926","paddle_gpu_time":"0.22480854494155583","paddle_gpu_time_backward":"2.8198957428323195"},{"name":"multiply_6","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.137971491220007","paddle_perf_backwards":"2.7506839798157476","paddle_gpu_time":"0.12108020304568529","paddle_gpu_time_backward":"2.7189833699403825"},{"name":"multiply_7","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.05289493315669906","paddle_perf_backwards":"0.6155840364325955","paddle_gpu_time":"0.03507854464376203","paddle_gpu_time_backward":"0.6160071904409433"},{"name":"multiply_8","op":"multiply","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/multiply_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"False","paddle_perf":"0.0582324001258743","paddle_perf_backwards":"0.49774570312194205","paddle_gpu_time":"0.039291929192919295","paddle_gpu_time_backward":"0.4732974683544304"},{"name":"mv_0","op":"mv","op_count":0,"config":"vec (Variable) - dtype: float32, shape: [8]\nx (Variable) - dtype: float32, shape: [128, 8]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.01991476331438337","paddle_perf_backwards":"0.038805543159951966","paddle_gpu_time":"0.0017147205031956985","paddle_gpu_time_backward":"0.005088160569105691"},{"name":"mv_1","op":"mv","op_count":0,"config":"vec (Variable) - dtype: float32, shape: [200]\nx (Variable) - dtype: float32, shape: [128, 200]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/mv_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.019750781431943476","paddle_perf_backwards":"0.039230367702568214","paddle_gpu_time":"0.0027869591346153843","paddle_gpu_time_backward":"0.006279323797139141"},{"name":"normalize_0","op":"normalize","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256, 128]\naxis (int): 1\nepsilon (float): 1e-12\np (int): 2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/normalize_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06518315295783841","paddle_perf_backwards":"0.1653454741653131","paddle_gpu_time":"0.020839288429375095","paddle_gpu_time_backward":"0.10400046114825916"},{"name":"not_equal_0","op":"not_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1]\ny (Variable) - dtype: int32, shape: [1]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.02238812570820352","paddle_perf_backwards":"--","paddle_gpu_time":"0.0012246492985971945","paddle_gpu_time_backward":"--"},{"name":"not_equal_1","op":"not_equal","op_count":0,"config":"x (Variable) - dtype: float32, shape: [256, 1024]\ny (Variable) - dtype: float32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.020734580580839414","paddle_perf_backwards":"--","paddle_gpu_time":"0.0026132495948136144","paddle_gpu_time_backward":"--"},{"name":"not_equal_2","op":"not_equal","op_count":0,"config":"x (Variable) - dtype: int32, shape: [1024]\ny (Variable) - dtype: int32, shape: [256, 1024]\ncond (string): None\nforce_cpu (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/not_equal_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0250883952888076","paddle_perf_backwards":"--","paddle_gpu_time":"0.0033313216656608324","paddle_gpu_time_backward":"--"},{"name":"null_0","op":"null","op_count":0,"config":"None","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/null_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.023322689289949378","paddle_perf_backwards":"--","paddle_gpu_time":"2.176057390524585e-05","paddle_gpu_time_backward":"--"},{"name":"one_hot_0","op":"one_hot","op_count":17,"config":"x (Variable) - dtype: int64, shape: [16, 1]\nallow_out_of_range (bool): False\nnum_classes (int): 37007\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/one_hot_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0258462769644601","paddle_perf_backwards":"--","paddle_gpu_time":"0.0036748108448928125","paddle_gpu_time_backward":"--"},{"name":"p_norm_0","op":"p_norm","op_count":0,"config":"x (Variable) - dtype: float32, shape: [300, 128, 128]\nasvector (bool): False\naxis (int): -1\nkeepdim (bool): False\nporder (float): 2.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.18662676519277144","paddle_perf_backwards":"0.3870771855724101","paddle_gpu_time":"0.1713993871297242","paddle_gpu_time_backward":"0.3919901997738409"},{"name":"p_norm_1","op":"p_norm","op_count":0,"config":"x (Variable) - dtype: float32, shape: [300, 128, 128]\naxis (int): -1\nkeepdim (bool): False\nporder (float): 3.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/p_norm_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.18432140350341797","paddle_perf_backwards":"0.3860587976416763","paddle_gpu_time":"0.17128561217195956","paddle_gpu_time_backward":"0.3804253717297196"},{"name":"pad2d_0","op":"pad2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 32, 255, 255]\ndata_format (string): NCHW\nmode (string): constant\npad (list): [0, 1, 0, 1]\nvalue (float): 0.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.127137860141126","paddle_perf_backwards":"2.3177146432868927","paddle_gpu_time":"1.1096286687206096","paddle_gpu_time_backward":"2.3614466918066506"},{"name":"pad2d_1","op":"pad2d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 3, 256, 256]\ndata_format (string): NCHW\nmode (string): reflect\npad (list): [3, 3, 3, 3]\nvalue (float): 0.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad2d_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.14496395386845232","paddle_perf_backwards":"0.2669577617721864","paddle_gpu_time":"0.1202021876035797","paddle_gpu_time_backward":"0.26161453782980953"},{"name":"pad3d_0","op":"pad3d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 3, 64, 64, 64]\ndata_format (string): NCDHW\nmode (string): constant\npad (list): [1, 2, 3, 4, 5, 6]\nvalue (float): 0.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.219306313847921","paddle_perf_backwards":"0.4417245646557176","paddle_gpu_time":"0.21139283913262735","paddle_gpu_time_backward":"0.42658866249747823"},{"name":"pad3d_1","op":"pad3d","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 3, 64, 64, 64]\ndata_format (string): NCDHW\nmode (string): reflect\npad (list): [1, 2, 3, 4, 5, 6]\nvalue (float): 0.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pad3d_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.24192002882440405","paddle_perf_backwards":"0.523554991526776","paddle_gpu_time":"0.24101944192606026","paddle_gpu_time_backward":"0.52451541361721"},{"name":"pixel_shuffle_0","op":"pixel_shuffle","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 9, 224, 224]\ndata_format (string): NCHW\nupscale_factor (int): 3\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.09757499305569395","paddle_perf_backwards":"0.18823536074891384","paddle_gpu_time":"0.08605851063829786","paddle_gpu_time_backward":"0.1760717230008244"},{"name":"pixel_shuffle_1","op":"pixel_shuffle","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 224, 224, 9]\ndata_format (string): NHWC\nupscale_factor (int): 3\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pixel_shuffle_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.10350018131489656","paddle_perf_backwards":"0.18658346059371014","paddle_gpu_time":"0.09141768937790944","paddle_gpu_time_backward":"0.174027448147766"},{"name":"pow_0","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08901823032367695","paddle_perf_backwards":"0.3645169723021972","paddle_gpu_time":"0.0690232768134845","paddle_gpu_time_backward":"0.34638958594730235"},{"name":"pow_1","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0888666791285207","paddle_perf_backwards":"0.36444738059340115","paddle_gpu_time":"0.07177536231884057","paddle_gpu_time_backward":"0.34487266340484257"},{"name":"pow_2","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.042710705606158604","paddle_perf_backwards":"0.10708952714541632","paddle_gpu_time":"0.02342716396903589","paddle_gpu_time_backward":"0.08629624718207134"},{"name":"pow_3","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.14131343914177233","paddle_perf_backwards":"0.3729744282418597","paddle_gpu_time":"0.1251433764135703","paddle_gpu_time_backward":"0.356313761750655"},{"name":"pow_4","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06607878423167135","paddle_perf_backwards":"7.065717586295638","paddle_gpu_time":"0.047508051529790665","paddle_gpu_time_backward":"6.987447151197906"},{"name":"pow_5","op":"pow","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2567394462998262","paddle_perf_backwards":"2.8715810221517253","paddle_gpu_time":"0.23971299093655588","paddle_gpu_time_backward":"2.830946403231088"},{"name":"pow_6","op":"pow","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"pow_7","op":"pow","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"pow_8","op":"pow","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/pow_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"prod_0","op":"prod","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.19167279432675163","paddle_perf_backwards":"1.4833468712403446","paddle_gpu_time":"0.17441152597402598","paddle_gpu_time_backward":"1.4523652114442036"},{"name":"prod_1","op":"prod","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.037770855183504065","paddle_perf_backwards":"0.0542852343345175","paddle_gpu_time":"0.0015629977537267713","paddle_gpu_time_backward":"0.006177145169994603"},{"name":"prod_2","op":"prod","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02424570978904257","paddle_perf_backwards":"0.06208784726201272","paddle_gpu_time":"0.0018288406972030804","paddle_gpu_time_backward":"0.005902794117647057"},{"name":"prod_3","op":"prod","op_count":0,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/prod_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.19732632474574394","paddle_perf_backwards":"0.5815793373780642","paddle_gpu_time":"0.1486355120732723","paddle_gpu_time_backward":"0.5069722142652535"},{"name":"relu_0","op":"relu","op_count":27,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3539744761281596","paddle_perf_backwards":"3.2837433662108766","paddle_gpu_time":"1.3219915339649264","paddle_gpu_time_backward":"3.228794037940379"},{"name":"relu_1","op":"relu","op_count":27,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.700526796505303","paddle_perf_backwards":"1.6603213512825823","paddle_gpu_time":"0.6743392425463336","paddle_gpu_time_backward":"1.6361017525948616"},{"name":"relu6_0","op":"relu6","op_count":6,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.337684920890059","paddle_perf_backwards":"3.2740882737842014","paddle_gpu_time":"1.3216436700574075","paddle_gpu_time_backward":"3.228281117696867"},{"name":"relu6_1","op":"relu6","op_count":6,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/relu6_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6879717649104361","paddle_perf_backwards":"1.6782909213660475","paddle_gpu_time":"0.674664115218048","paddle_gpu_time_backward":"1.6369525267993874"},{"name":"remainder_0","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0941829041795091","paddle_perf_backwards":"--","paddle_gpu_time":"0.0690914107967088","paddle_gpu_time_backward":"--"},{"name":"remainder_1","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.09341003421791091","paddle_perf_backwards":"--","paddle_gpu_time":"0.06994762288477036","paddle_gpu_time_backward":"--"},{"name":"remainder_2","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.043435947211806436","paddle_perf_backwards":"--","paddle_gpu_time":"0.021873868436934216","paddle_gpu_time_backward":"--"},{"name":"remainder_3","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.14694152709716307","paddle_perf_backwards":"--","paddle_gpu_time":"0.12395191433478128","paddle_gpu_time_backward":"--"},{"name":"remainder_4","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.06608585556427797","paddle_perf_backwards":"--","paddle_gpu_time":"0.045551192993053456","paddle_gpu_time_backward":"--"},{"name":"remainder_5","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.2603802031171107","paddle_perf_backwards":"--","paddle_gpu_time":"0.2364695809830782","paddle_gpu_time_backward":"--"},{"name":"remainder_6","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"remainder_7","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"remainder_8","op":"remainder","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/remainder_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"--","paddle_perf_backwards":"--","paddle_gpu_time":"--","paddle_gpu_time_backward":"--"},{"name":"reshape_0","op":"reshape","op_count":287,"config":"x (Variable) - dtype: float32, shape: [16, 513, 513, 19]\nshape (list): [-1, 19]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.855584928717432","paddle_perf_backwards":"1.6878441065609495","paddle_gpu_time":"0.8182404437316225","paddle_gpu_time_backward":"1.633052996929649"},{"name":"reshape_1","op":"reshape","op_count":287,"config":"x (Variable) - dtype: float32, shape: [16]\nshape (list): [-1, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/reshape_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04028008908641581","paddle_perf_backwards":"0.04433198850982044","paddle_gpu_time":"0.0013458210322712003","paddle_gpu_time_backward":"0.002718598546042003"},{"name":"roll_0","op":"roll","op_count":0,"config":"x (Variable) - dtype: float32, shape: [100, 1785]\naxis (int): 0\nshifts (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/roll_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.020183592426533604","paddle_perf_backwards":"0.02882310322352818","paddle_gpu_time":"0.0031274674506509875","paddle_gpu_time_backward":"0.006149310168625448"},{"name":"rsqrt_0","op":"rsqrt","op_count":4,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3449997605685002","paddle_perf_backwards":"3.2522294468774584","paddle_gpu_time":"1.321507001108089","paddle_gpu_time_backward":"3.2274420179448113"},{"name":"rsqrt_1","op":"rsqrt","op_count":4,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/rsqrt_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6905950381903945","paddle_perf_backwards":"1.6573372011433145","paddle_gpu_time":"0.6760489475274447","paddle_gpu_time_backward":"1.6377482541304718"},{"name":"scale_0","op":"scale","op_count":49,"config":"x (Variable) - dtype: float16, shape: [16, 16, 16]\nact (string): None\nbias (float): -1.0\nbias_after_scale (bool): False\nscale (float): 10000.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.019928143948924785","paddle_perf_backwards":"--","paddle_gpu_time":"0.0014838742496693456","paddle_gpu_time_backward":"--"},{"name":"scale_1","op":"scale","op_count":49,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1024]\nact (string): None\nbias (float): 0.0\nbias_after_scale (bool): True\nscale (float): 32.0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scale_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.0204150935253465","paddle_perf_backwards":"--","paddle_gpu_time":"0.002393779223419394","paddle_gpu_time_backward":"--"},{"name":"scatter_0","op":"scatter","op_count":2,"config":"index (Variable) - dtype: int32, shape: [16]\ninput (Variable) - dtype: float32, shape: [16, 64]\nupdates (Variable) - dtype: float32, shape: [16, 64]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03119536808558873","paddle_perf_backwards":"0.05172977642137177","paddle_gpu_time":"0.0027572708981159683","paddle_gpu_time_backward":"0.0076618748128182085"},{"name":"scatter_1","op":"scatter","op_count":2,"config":"index (Variable) - dtype: int32, shape: [16]\ninput (Variable) - dtype: float32, shape: [16, 1024, 16]\nupdates (Variable) - dtype: float32, shape: [16, 1024, 16]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03731126287376067","paddle_perf_backwards":"0.052826088595103064","paddle_gpu_time":"0.006187780922257366","paddle_gpu_time_backward":"0.015309523809523811"},{"name":"scatter_nd_add_0","op":"scatter_nd_add","op_count":0,"config":"index (Variable) - dtype: int32, shape: [8, 2]\ninput (Variable) - dtype: float32, shape: [16, 10, 10]\nupdates (Variable) - dtype: float32, shape: [8, 10]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03767086535084004","paddle_perf_backwards":"0.06033279457870794","paddle_gpu_time":"0.0051713098729227755","paddle_gpu_time_backward":"0.010682750301568157"},{"name":"scatter_nd_add_1","op":"scatter_nd_add","op_count":0,"config":"index (Variable) - dtype: int32, shape: [16, 3]\ninput (Variable) - dtype: float32, shape: [16, 256, 14, 14]\nupdates (Variable) - dtype: float32, shape: [16, 14]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/scatter_nd_add_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03855802926672511","paddle_perf_backwards":"0.06191792737049272","paddle_gpu_time":"0.010380659490859388","paddle_gpu_time_backward":"0.025543127095397744"},{"name":"sequence_mask_0","op":"sequence_mask","op_count":8,"config":"maxlen (Variable) - dtype: int32, shape: [1]\nx (Variable) - dtype: int32, shape: [16]\ndtype (string): float32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sequence_mask_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.06304638726370675","paddle_perf_backwards":"--","paddle_gpu_time":"0.004525942241801272","paddle_gpu_time_backward":"--"},{"name":"shape_0","op":"shape","op_count":0,"config":"input (Variable) - dtype: float32, shape: [16, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/shape_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.010757057034239476","paddle_perf_backwards":"--","paddle_gpu_time":"2.4158582876423452e-05","paddle_gpu_time_backward":"--"},{"name":"sigmoid_0","op":"sigmoid","op_count":31,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3364945719380656","paddle_perf_backwards":"3.2512845161682615","paddle_gpu_time":"1.3252795969773299","paddle_gpu_time_backward":"3.231389830508475"},{"name":"sigmoid_1","op":"sigmoid","op_count":31,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sigmoid_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6992435168646619","paddle_perf_backwards":"1.6663444066095447","paddle_gpu_time":"0.6854613215149072","paddle_gpu_time_backward":"1.6467054794520548"},{"name":"sigmoid_cross_entropy_with_logits_0","op":"sigmoid_cross_entropy_with_logits","op_count":12,"config":"label (Variable) - dtype: float32, shape: [16, 900]\nx (Variable) - dtype: float32, shape: [16, 900]\nignore_index (int): -100\nnormalize (bool): False\n","timestamp":"2021.0312.104831.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.020173861055958024","paddle_perf_backwards":"0.03149825699475346","paddle_gpu_time":"0.001556322786766979","paddle_gpu_time_backward":"0.003836954431840031"},{"name":"sigmoid_cross_entropy_with_logits_1","op":"sigmoid_cross_entropy_with_logits","op_count":12,"config":"label (Variable) - dtype: float32, shape: [16, 63504]\nx (Variable) - dtype: float32, shape: [16, 63504]\nignore_index (int): -1\nnormalize (bool): True\n","timestamp":"2021.0312.104831.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.0312.104831.gcc82.post107.develop/sigmoid_cross_entropy_with_logits_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.037319593161464215","paddle_perf_backwards":"0.0659092363104763","paddle_gpu_time":"0.022909495849362218","paddle_gpu_time_backward":"0.04957171496263897"},{"name":"sin_0","op":"sin","op_count":2,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3346246105874469","paddle_perf_backwards":"3.247939178604401","paddle_gpu_time":"1.3233225871448722","paddle_gpu_time_backward":"3.2298492292054886"},{"name":"sin_1","op":"sin","op_count":2,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sin_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6946616277904931","paddle_perf_backwards":"1.7008365753418457","paddle_gpu_time":"0.6788213961922032","paddle_gpu_time_backward":"1.6506847918436702"},{"name":"sinh_0","op":"sinh","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.336435468975671","paddle_perf_backwards":"3.2544358937678215","paddle_gpu_time":"1.3222166246851383","paddle_gpu_time_backward":"3.2282133784928027"},{"name":"sinh_1","op":"sinh","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sinh_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6919448982498688","paddle_perf_backwards":"1.6677965859850805","paddle_gpu_time":"0.6773282288938143","paddle_gpu_time_backward":"1.6445003399048266"},{"name":"slice_0","op":"slice","op_count":76,"config":"input (Variable) - dtype: float32, shape: [16, 800]\naxes (list): [1]\nends (list): [400]\nstarts (list): [200]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.024388031083710338","paddle_perf_backwards":"0.04004702276113081","paddle_gpu_time":"0.0015134887508907663","paddle_gpu_time_backward":"0.004098848203541345"},{"name":"slice_1","op":"slice","op_count":76,"config":"input (Variable) - dtype: float32, shape: [35, 16, 1500]\naxes (list): [0]\nends (list): [35]\nstarts (list): [34]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02390215466091702","paddle_perf_backwards":"0.035558639465270936","paddle_gpu_time":"0.0016510644799837017","paddle_gpu_time_backward":"0.006055302919172657"},{"name":"slice_2","op":"slice","op_count":76,"config":"input (Variable) - dtype: float32, shape: [2, 16, 1500]\naxes (list): [0]\nends (list): [1]\nstarts (list): [0]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02398515234188158","paddle_perf_backwards":"0.037946992990921954","paddle_gpu_time":"0.0016330095080611823","paddle_gpu_time_backward":"0.003978765759787658"},{"name":"slice_3","op":"slice","op_count":76,"config":"input (Variable) - dtype: float32, shape: [512, 1407, 4, 12]\naxes (list): [0, 1, 2, 3]\nends (list): [100000000, 896, 100000000, 100000000]\nstarts (list): [0, 0, 0, 0]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.2660661337366066","paddle_perf_backwards":"0.5811898105115776","paddle_gpu_time":"0.24909629327070357","paddle_gpu_time_backward":"0.5615384615384614"},{"name":"slice_4","op":"slice","op_count":76,"config":"input (Variable) - dtype: float16, shape: [512, 1407, 4, 12]\naxes (list): [0, 1, 2, 3]\nends (list): [100000000, 896, 100000000, 100000000]\nstarts (list): [0, 0, 0, 0]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/slice_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1637374540888162","paddle_perf_backwards":"0.39486650482239016","paddle_gpu_time":"0.14581762608252674","paddle_gpu_time_backward":"0.37392044524472084"},{"name":"softmax_0","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float32, shape: [16, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.020836567392154618","paddle_perf_backwards":"0.03165103951278998","paddle_gpu_time":"0.0026560760902559952","paddle_gpu_time_backward":"0.0062670386608210445"},{"name":"softmax_1","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float16, shape: [16, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.021432370555644134","paddle_perf_backwards":"0.028021238288100884","paddle_gpu_time":"0.0044968313046977165","paddle_gpu_time_backward":"0.008498803009575924"},{"name":"softmax_2","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float32, shape: [32, 12, 128, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0773188579513366","paddle_perf_backwards":"0.1804336007819118","paddle_gpu_time":"0.06412624314998984","paddle_gpu_time_backward":"0.15515646258503402"},{"name":"softmax_3","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.04906151668134942","paddle_perf_backwards":"0.09678362842544495","paddle_gpu_time":"0.0353683997162258","paddle_gpu_time_backward":"0.08267462267462268"},{"name":"softmax_4","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float32, shape: [15, 16, 33, 33]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02298211764715955","paddle_perf_backwards":"0.027381131548680857","paddle_gpu_time":"0.005265201685731487","paddle_gpu_time_backward":"0.008984078068823833"},{"name":"softmax_5","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float16, shape: [15, 16, 33, 33]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.018159301581984772","paddle_perf_backwards":"0.029898095943168074","paddle_gpu_time":"0.004538384445780717","paddle_gpu_time_backward":"0.008705998356614626"},{"name":"softmax_6","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float32, shape: [128, 128, 16, 16]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.19006729125976562","paddle_perf_backwards":"0.3240252027706224","paddle_gpu_time":"0.17661701693531934","paddle_gpu_time_backward":"0.3162762022194821"},{"name":"softmax_7","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float16, shape: [128, 128, 16, 16]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.16897478882147343","paddle_perf_backwards":"0.26627681693252253","paddle_gpu_time":"0.14603720177921553","paddle_gpu_time_backward":"0.2403442986193966"},{"name":"softmax_8","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.214469695577816","paddle_perf_backwards":"2.1376079442549725","paddle_gpu_time":"1.205351712953578","paddle_gpu_time_backward":"2.1142730966260377"},{"name":"softmax_9","op":"softmax","op_count":57,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_9-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.0450976235525948","paddle_perf_backwards":"2.0851050104413713","paddle_gpu_time":"1.0414675939925413","paddle_gpu_time_backward":"2.089928343949044"},{"name":"softmax_with_cross_entropy_0","op":"softmax_with_cross_entropy","op_count":56,"config":"label (Variable) - dtype: float32, shape: [16, 37007]\nlogits (Variable) - dtype: float32, shape: [16, 37007]\naxis (int): -1\nignore_index (int): -100\nsoft_label (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.11570477972225268","paddle_perf_backwards":"0.13766240100471341","paddle_gpu_time":"0.10620450241952452","paddle_gpu_time_backward":"0.12376018626309661"},{"name":"softmax_with_cross_entropy_1","op":"softmax_with_cross_entropy","op_count":56,"config":"label (Variable) - dtype: int64, shape: [8, 512, 1024, 1]\nlogits (Variable) - dtype: float32, shape: [8, 512, 1024, 19]\naxis (int): -1\nignore_index (int): -100\nsoft_label (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3898168701723397","paddle_perf_backwards":"3.384454135435173","paddle_gpu_time":"1.4024381875063074","paddle_gpu_time_backward":"3.3998303777949115"},{"name":"softmax_with_cross_entropy_2","op":"softmax_with_cross_entropy","op_count":56,"config":"label (Variable) - dtype: int64, shape: [8, 1, 512, 1024]\nlogits (Variable) - dtype: float32, shape: [8, 19, 512, 1024]\naxis (int): 1\nignore_index (int): -100\nsoft_label (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softmax_with_cross_entropy_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"3.911814397695113","paddle_perf_backwards":"6.74598606265321","paddle_gpu_time":"3.9189571544058213","paddle_gpu_time_backward":"6.785400731626205"},{"name":"softplus_0","op":"softplus","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3426620162321714","paddle_perf_backwards":"3.2649486002797836","paddle_gpu_time":"1.330907991534818","paddle_gpu_time_backward":"3.2381324278438033"},{"name":"softplus_1","op":"softplus","op_count":0,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softplus_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.8669820720542647","paddle_perf_backwards":"1.805807139448269","paddle_gpu_time":"0.8647334540333937","paddle_gpu_time_backward":"1.8003173431734318"},{"name":"softsign_0","op":"softsign","op_count":1,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3378798842191217","paddle_perf_backwards":"3.251453845916626","paddle_gpu_time":"1.323639661426844","paddle_gpu_time_backward":"3.2297475859732336"},{"name":"softsign_1","op":"softsign","op_count":1,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/softsign_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6950900406541233","paddle_perf_backwards":"1.670726339420479","paddle_gpu_time":"0.6816433249370277","paddle_gpu_time_backward":"1.6515659574468082"},{"name":"split_0","op":"split","op_count":34,"config":"x (Variable) - dtype: float32, shape: [16, 35, 1500]\naxis (int): 1\nnum_or_sections (int): 35\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.054610262111741664","paddle_perf_backwards":"0.4886919138382892","paddle_gpu_time":"0.011020939734422882","paddle_gpu_time_backward":"0.06521407442005292"},{"name":"split_1","op":"split","op_count":34,"config":"x (Variable) - dtype: float32, shape: [16, 800]\naxis (int): -1\nnum_or_sections (int): 4\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/split_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.029759990925691565","paddle_perf_backwards":"0.07541276970688178","paddle_gpu_time":"0.0019985806974858068","paddle_gpu_time_backward":"0.007737397888025502"},{"name":"sqrt_0","op":"sqrt","op_count":5,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3336197885578285","paddle_perf_backwards":"3.2463036940427488","paddle_gpu_time":"1.322317380352645","paddle_gpu_time_backward":"3.228885878767355"},{"name":"sqrt_1","op":"sqrt","op_count":5,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sqrt_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6916114228044101","paddle_perf_backwards":"1.6631993119845647","paddle_gpu_time":"0.6780821917808219","paddle_gpu_time_backward":"1.645970403129784"},{"name":"square_0","op":"square","op_count":41,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3314448998781867","paddle_perf_backwards":"3.2442415644506175","paddle_gpu_time":"1.3219836710009072","paddle_gpu_time_backward":"3.2272773450728076"},{"name":"square_1","op":"square","op_count":41,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/square_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.686971123567325","paddle_perf_backwards":"1.6558408020493502","paddle_gpu_time":"0.6744191435768262","paddle_gpu_time_backward":"1.6360802311745706"},{"name":"squeeze_0","op":"squeeze","op_count":37,"config":"x (Variable) - dtype: float32, shape: [16, 1, 512]\naxis (list): [1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/squeeze_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.0236944276459363","paddle_perf_backwards":"0.03825158488993742","paddle_gpu_time":"0.0012546938775510204","paddle_gpu_time_backward":"0.002617771936918722"},{"name":"stack_0","op":"stack","op_count":30,"config":"x (list[16]) - dtype: float32, shape: [16, 16, 16]; \naxis (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/stack_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.030216392205685984","paddle_perf_backwards":"0.05751653593413684","paddle_gpu_time":"0.0038309537407195888","paddle_gpu_time_backward":"0.008363758389261743"},{"name":"subtract_0","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [128, 1000]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08278990889693405","paddle_perf_backwards":"0.1823334961204796","paddle_gpu_time":"0.06432744428829552","paddle_gpu_time_backward":"0.164159211398277"},{"name":"subtract_1","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [50, 128, 1000]\ny (Variable) - dtype: float32, shape: [1, 128, 1000]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.09056750184787299","paddle_perf_backwards":"0.1825693136226677","paddle_gpu_time":"0.0645345557122708","paddle_gpu_time_backward":"0.16769821808075855"},{"name":"subtract_2","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 7, 7]\ny (Variable) - dtype: float32, shape: [16, 2048]\naxis (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03610620039976192","paddle_perf_backwards":"0.08771085070225901","paddle_gpu_time":"0.017470546772731847","paddle_gpu_time_backward":"0.06801374477833176"},{"name":"subtract_3","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\ny (Variable) - dtype: float32, shape: [16, 2048, 16, 16]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1372949871606005","paddle_perf_backwards":"0.273771109227427","paddle_gpu_time":"0.12144690310195005","paddle_gpu_time_backward":"0.25142829457364335"},{"name":"subtract_4","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1, 513, 513]\ny (Variable) - dtype: float32, shape: [1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.06103095167385553","paddle_perf_backwards":"1.6685241926648096","paddle_gpu_time":"0.04268285311303647","paddle_gpu_time_backward":"1.628483417188623"},{"name":"subtract_5","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float32, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float32, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.24455671081084285","paddle_perf_backwards":"2.8568513407735883","paddle_gpu_time":"0.2249828594474692","paddle_gpu_time_backward":"2.818928610235792"},{"name":"subtract_6","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float16, shape: [512, 896, 4, 12]\ny (Variable) - dtype: float16, shape: [512, 896, 4, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.13806637989948076","paddle_perf_backwards":"2.7510071854036013","paddle_gpu_time":"0.12149618320610686","paddle_gpu_time_backward":"2.7186355550905095"},{"name":"subtract_7","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 12, 128, 128]\ny (Variable) - dtype: float16, shape: [32, 1, 1, 128]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_7-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.05736279200358563","paddle_perf_backwards":"0.4702519700230365","paddle_gpu_time":"0.034752103822366424","paddle_gpu_time_backward":"0.45278996865203763"},{"name":"subtract_8","op":"subtract","op_count":0,"config":"x (Variable) - dtype: float16, shape: [32, 1, 1, 128]\ny (Variable) - dtype: float16, shape: [1, 12, 128, 1]\naxis (int): -1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/subtract_8-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"False","paddle_perf":"0.06094506842817715","paddle_perf_backwards":"0.3341202745456734","paddle_gpu_time":"0.039277927792779284","paddle_gpu_time_backward":"0.3115570862032978"},{"name":"sum_0","op":"sum","op_count":5,"config":"x (Variable) - dtype: float32, shape: [16, 2048, 33, 33]\naxis (list): [2, 3]\nkeepdim (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.18815435245185194","paddle_perf_backwards":"0.8324546661071166","paddle_gpu_time":"0.1739560886359016","paddle_gpu_time_backward":"0.8088945949415842"},{"name":"sum_1","op":"sum","op_count":5,"config":"x (Variable) - dtype: float32, shape: [16, 8, 128]\naxis (list): [1]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02590320548232721","paddle_perf_backwards":"0.03718478339059012","paddle_gpu_time":"0.001390094146541138","paddle_gpu_time_backward":"0.004471009975062344"},{"name":"sum_2","op":"sum","op_count":5,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1, 1]\naxis (list): [0]\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02345308965566207","paddle_perf_backwards":"0.037146831045345385","paddle_gpu_time":"0.001770214061073349","paddle_gpu_time_backward":"0.003938223938223939"},{"name":"sum_3","op":"sum","op_count":5,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\naxis (string): None\nkeepdim (bool): False\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sum_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.1701762537679118","paddle_perf_backwards":"0.3294186506099357","paddle_gpu_time":"0.14803752850922663","paddle_gpu_time_backward":"0.30286993690209646"},{"name":"switch_case_0","op":"switch_case","op_count":0,"config":"input (Variable) - dtype: int32, shape: [1]\nx (Variable) - dtype: float32, shape: [16, 256, 6, 6]\ny (Variable) - dtype: float32, shape: [16, 256, 6, 6]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/switch_case_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.45750579055474727","paddle_perf_backwards":"0.8581339096536441","paddle_gpu_time":"0.034866225999370476","paddle_gpu_time_backward":"0.08377721678763017"},{"name":"sync_batch_norm_0","op":"sync_batch_norm","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 256]\ndata_format (string): NCHW\nepsilon (float): 1e-05\nmomentum (float): 0.9\ntraining (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/sync_batch_norm_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.036811585329016856","paddle_perf_backwards":"0.06529871298342335","paddle_gpu_time":"0.0064332638164754955","paddle_gpu_time_backward":"0.015762620837808806"},{"name":"tanh_0","op":"tanh","op_count":15,"config":"x (Variable) - dtype: float32, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.3358249931870578","paddle_perf_backwards":"3.2478842085492396","paddle_gpu_time":"1.324355098750504","paddle_gpu_time_backward":"3.230057607590647"},{"name":"tanh_1","op":"tanh","op_count":15,"config":"x (Variable) - dtype: float16, shape: [16, 128, 257, 257]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tanh_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.69619720588944","paddle_perf_backwards":"1.6641721935692673","paddle_gpu_time":"0.6832198610131935","paddle_gpu_time_backward":"1.6443382352941178"},{"name":"temporal_shift_0","op":"temporal_shift","op_count":0,"config":"x (Variable) - dtype: float32, shape: [32, 64, 24, 42]\nseg_num (int): 2\nshift_ratio (float): 0.2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.04302454760754444","paddle_perf_backwards":"0.06815343496789894","paddle_gpu_time":"0.027037636584378792","paddle_gpu_time_backward":"0.05493472584856396"},{"name":"temporal_shift_1","op":"temporal_shift","op_count":0,"config":"x (Variable) - dtype: float32, shape: [128, 64, 24, 24]\nseg_num (int): 2\nshift_ratio (float): 0.2\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/temporal_shift_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.07505359419857163","paddle_perf_backwards":"0.12881779766465767","paddle_gpu_time":"0.05825928549741929","paddle_gpu_time_backward":"0.12082412060301508"},{"name":"tile_0","op":"tile","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1785, 1]\nrepeat_times (list): [1, 1, 2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.020698868498510242","paddle_perf_backwards":"0.03389485028325295","paddle_gpu_time":"0.0025193774794018916","paddle_gpu_time_backward":"0.006220121539500337"},{"name":"tile_1","op":"tile","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 5, 1, 1]\nrepeat_times (list): [1, 1, 128, 128]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.03281929055038764","paddle_perf_backwards":"6.094040676039093","paddle_gpu_time":"0.017126551862234683","paddle_gpu_time_backward":"5.999087353324642"},{"name":"tile_2","op":"tile","op_count":0,"config":"x (Variable) - dtype: float32, shape: [32, 807, 1]\nrepeat_times (list): [4, 1, 807]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tile_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.6788959308546417","paddle_perf_backwards":"9.610410612456652","paddle_gpu_time":"0.6588158815881588","paddle_gpu_time_backward":"9.552288354103997"},{"name":"topk_0","op":"topk","op_count":12,"config":"x (Variable) - dtype: float32, shape: [16, 1000]\nk (int): 5\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.09244534434104451","paddle_perf_backwards":"0.08933106247259646","paddle_gpu_time":"0.05498392282958199","paddle_gpu_time_backward":"0.05690897729639659"},{"name":"topk_1","op":"topk","op_count":12,"config":"x (Variable) - dtype: float32, shape: [16, 3]\nk (int): 1\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/topk_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.07954762906444317","paddle_perf_backwards":"0.07401826430340203","paddle_gpu_time":"0.04202742002492729","paddle_gpu_time_backward":"0.04434896401308615"},{"name":"trace_0","op":"trace","op_count":0,"config":"x (Variable) - dtype: float32, shape: [100, 1785]\naxis1 (int): 0\naxis2 (int): 1\noffset (int): 0\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/trace_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.08990837603199239","paddle_perf_backwards":"0.15245603055370097","paddle_gpu_time":"0.006681853734845523","paddle_gpu_time_backward":"0.0172659793814433"},{"name":"transpose_0","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float32, shape: [16, 14, 1, 1]\nperm (list): [0, 2, 3, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02262957242070412","paddle_perf_backwards":"0.03082800884636081","paddle_gpu_time":"0.0013323840520748577","paddle_gpu_time_backward":"0.0027402807230132277"},{"name":"transpose_1","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float32, shape: [16, 19, 513, 513]\nperm (list): [0, 2, 3, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.9620216955621559","paddle_perf_backwards":"1.9231419965445278","paddle_gpu_time":"0.9506863737598704","paddle_gpu_time_backward":"1.9007526665325014"},{"name":"transpose_2","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float32, shape: [16, 128, 256]\nperm (list): [0, 2, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.02143153225082949","paddle_perf_backwards":"0.03245566264692559","paddle_gpu_time":"0.00413495056569157","paddle_gpu_time_backward":"0.009788465416414599"},{"name":"transpose_3","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float32, shape: [4, 12, 512, 896]\nperm (list): [2, 3, 0, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.25761429085788956","paddle_perf_backwards":"0.4812271240724617","paddle_gpu_time":"0.24031246829664196","paddle_gpu_time_backward":"0.4626727089627392"},{"name":"transpose_4","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float16, shape: [4, 12, 512, 896]\nperm (list): [2, 3, 0, 1]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_4-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.16231450689844337","paddle_perf_backwards":"0.2966718980107442","paddle_gpu_time":"0.14974322684997976","paddle_gpu_time_backward":"0.2881886754500654"},{"name":"transpose_5","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float32, shape: [4, 512, 512, 1]\nperm (list): [1, 2, 0, 3]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_5-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.029926462824564858","paddle_perf_backwards":"0.049997333541931394","paddle_gpu_time":"0.013135020242914979","paddle_gpu_time_backward":"0.03339831189710611"},{"name":"transpose_6","op":"transpose","op_count":150,"config":"x (Variable) - dtype: float16, shape: [4, 512, 512, 1]\nperm (list): [1, 2, 0, 3]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/transpose_6-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.023686981584173608","paddle_perf_backwards":"0.03205121281635331","paddle_gpu_time":"0.005528862737141118","paddle_gpu_time_backward":"0.01375133286389699"},{"name":"tril_0","op":"tril","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1024, 2048]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/tril_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03392780670011887","paddle_perf_backwards":"0.05546218217021287","paddle_gpu_time":"0.02166424870466321","paddle_gpu_time_backward":"0.04251655291840684"},{"name":"triu_0","op":"triu","op_count":0,"config":"x (Variable) - dtype: float32, shape: [1024, 2048]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/triu_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.03963889497699159","paddle_perf_backwards":"0.0609138999322448","paddle_gpu_time":"0.02687120666598087","paddle_gpu_time_backward":"0.05307489344428658"},{"name":"unique_0","op":"unique","op_count":0,"config":"x (Variable) - dtype: float32, shape: [100, 100]\naxis (string): None\ndtype (string): int64\nreturn_counts (bool): True\nreturn_index (bool): True\nreturn_inverse (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"1.0880377827858438","paddle_perf_backwards":"--","paddle_gpu_time":"0.3859603415834419","paddle_gpu_time_backward":"--"},{"name":"unique_1","op":"unique","op_count":0,"config":"x (Variable) - dtype: float32, shape: [4, 50, 30]\naxis (int): 1\ndtype (string): int64\nreturn_counts (bool): True\nreturn_index (bool): True\nreturn_inverse (bool): True\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unique_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.7353597757767658","paddle_perf_backwards":"--","paddle_gpu_time":"0.40334484924623115","paddle_gpu_time_backward":"--"},{"name":"unsqueeze_0","op":"unsqueeze","op_count":44,"config":"x (Variable) - dtype: float32, shape: [16, 16, 1]\naxis (list): [2]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/unsqueeze_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.025111801770268657","paddle_perf_backwards":"0.03830121487987284","paddle_gpu_time":"0.0013793068297655454","paddle_gpu_time_backward":"0.002551115147845393"},{"name":"where_index_0","op":"where_index","op_count":0,"config":"x (Variable) - dtype: bool, shape: [16, 100, 100]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.06352468412749622","paddle_perf_backwards":"--","paddle_gpu_time":"0.02116631130063966","paddle_gpu_time_backward":"--"},{"name":"where_index_1","op":"where_index","op_count":0,"config":"x (Variable) - dtype: int32, shape: [16, 10]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.07170098168509348","paddle_perf_backwards":"--","paddle_gpu_time":"0.010370146243066064","paddle_gpu_time_backward":"--"},{"name":"where_index_2","op":"where_index","op_count":0,"config":"x (Variable) - dtype: float32, shape: [16, 1000]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/where_index_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.059839414090526344","paddle_perf_backwards":"--","paddle_gpu_time":"0.011010791366906475","paddle_gpu_time_backward":"--"},{"name":"while_loop_0","op":"while_loop","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [2048]\nweight (Variable) - dtype: float32, shape: [36864, 2048]\nx (Variable) - dtype: float32, shape: [16, 36864]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"1.4588034882837413","paddle_perf_backwards":"3.955042605497399","paddle_gpu_time":"1.2018284106891701","paddle_gpu_time_backward":"3.54094759962347"},{"name":"while_loop_1","op":"while_loop","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [1024]\nweight (Variable) - dtype: float32, shape: [1024, 1024]\nx (Variable) - dtype: float32, shape: [16, 16, 1024]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.38945991165783944","paddle_perf_backwards":"0.6976341714664381","paddle_gpu_time":"0.09498564593301435","paddle_gpu_time_backward":"0.26178486055776895"},{"name":"while_loop_2","op":"while_loop","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [1024]\nweight (Variable) - dtype: float32, shape: [12544, 1024]\nx (Variable) - dtype: float32, shape: [16, 12544]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_2-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.5039649780350502","paddle_perf_backwards":"1.0877628519077494","paddle_gpu_time":"0.2427589367552704","paddle_gpu_time_backward":"0.6757570483814829"},{"name":"while_loop_3","op":"while_loop","op_count":0,"config":"bias (Variable) - dtype: float32, shape: [256]\nweight (Variable) - dtype: float32, shape: [16, 256]\nx (Variable) - dtype: float32, shape: [16, 16]\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/while_loop_3-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"True","paddle_perf":"0.35235419565317583","paddle_perf_backwards":"0.6417615073067802","paddle_gpu_time":"0.020852953325072282","paddle_gpu_time_backward":"0.041831088664422"},{"name":"yolo_box_0","op":"yolo_box","op_count":1,"config":"img_size (Variable) - dtype: int32, shape: [32, 2]\nx (Variable) - dtype: float32, shape: [32, 21, 13, 13]\nanchors (list): [10, 13, 16, 30, 33, 23]\nclass_num (int): 2\nconf_thresh (float): 0.01\ndownsample_ratio (int): 32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.04008721156292651","paddle_perf_backwards":"--","paddle_gpu_time":"0.013164809723628997","paddle_gpu_time_backward":"--"},{"name":"yolo_box_1","op":"yolo_box","op_count":1,"config":"img_size (Variable) - dtype: int32, shape: [128, 2]\nx (Variable) - dtype: float32, shape: [128, 21, 26, 26]\nanchors (list): [10, 13, 16, 30, 33, 23]\nclass_num (int): 2\nconf_thresh (float): 0.01\ndownsample_ratio (int): 32\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/yolo_box_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"--","paddle_consistency_backwards":"--","paddle_perf":"0.07906146796352892","paddle_perf_backwards":"--","paddle_gpu_time":"0.05594174757281553","paddle_gpu_time_backward":"--"},{"name":"zeros_like_0","op":"zeros_like","op_count":5,"config":"x (Variable) - dtype: float32, shape: [30522, 1024]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_0-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.15890951863749472","paddle_perf_backwards":"--","paddle_gpu_time":"0.14643060353586668","paddle_gpu_time_backward":"--"},{"name":"zeros_like_1","op":"zeros_like","op_count":5,"config":"x (Variable) - dtype: float32, shape: [3]\nout (string): None\n","timestamp":"2021.1023.160715.gcc82.post107.develop","paddle_accuracy_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-paddle_gpu_accuracy_backward.txt","paddle_accuracy_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-paddle_gpu_accuracy_forward.txt","paddle_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-paddle_gpu_speed_backward.txt","paddle_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-paddle_gpu_speed_forward.txt","tf_speed_backward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-tensorflow_gpu_speed_backward.txt","tf_speed_forward_log_url":"logs/op_benchmark/2021.1023.160715.gcc82.post107.develop/zeros_like_1-tensorflow_gpu_speed_forward.txt","paddle_consistency":"True","paddle_consistency_backwards":"--","paddle_perf":"0.018170415138711735","paddle_perf_backwards":"--","paddle_gpu_time":"0.001253539777936233","paddle_gpu_time_backward":"--"}] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cuda_env.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/cuda_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b71ff6ac66f1e75f9aad0b49c6618b52c30c4a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/__init__.py @@ -0,0 +1,32 @@ +# 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. +""" +Dataset package. +""" + +import paddle.dataset.mnist # noqa: F401 +import paddle.dataset.imikolov # noqa: F401 +import paddle.dataset.imdb # noqa: F401 +import paddle.dataset.cifar # noqa: F401 +import paddle.dataset.movielens # noqa: F401 +import paddle.dataset.conll05 # noqa: F401 +import paddle.dataset.uci_housing # noqa: F401 +import paddle.dataset.wmt14 # noqa: F401 +import paddle.dataset.wmt16 # noqa: F401 +import paddle.dataset.flowers # noqa: F401 +import paddle.dataset.voc2012 # noqa: F401 +import paddle.dataset.image # noqa: F401 + +# set __all__ as empty for not showing APIs under paddle.dataset +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/cifar.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4f4adccd26e05aa99af4a5d439b89ef8e019f5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/cifar.py @@ -0,0 +1,169 @@ +# 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. +""" +CIFAR dataset. + +This module will download dataset from https://dataset.bj.bcebos.com/cifar/cifar-10-python.tar.gz and https://dataset.bj.bcebos.com/cifar/cifar-100-python.tar.gz, parse train/test set into +paddle reader creators. + +The CIFAR-10 dataset consists of 60000 32x32 color images in 10 classes, +with 6000 images per class. There are 50000 training images and 10000 test +images. + +The CIFAR-100 dataset is just like the CIFAR-10, except it has 100 classes +containing 600 images each. There are 500 training images and 100 testing +images per class. + +""" + +from __future__ import print_function + +import itertools +import numpy +import paddle.dataset.common +import paddle.utils.deprecated as deprecated +import tarfile +import six +from six.moves import cPickle as pickle + +__all__ = [] + +URL_PREFIX = 'https://dataset.bj.bcebos.com/cifar/' +CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz' +CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a' +CIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz' +CIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85' + + +def reader_creator(filename, sub_name, cycle=False): + + def read_batch(batch): + data = batch[six.b('data')] + labels = batch.get(six.b('labels'), batch.get(six.b('fine_labels'), + None)) + assert labels is not None + for sample, label in six.moves.zip(data, labels): + yield (sample / 255.0).astype(numpy.float32), int(label) + + def reader(): + while True: + with tarfile.open(filename, mode='r') as f: + names = (each_item.name for each_item in f + if sub_name in each_item.name) + + for name in names: + batch = pickle.load(f.extractfile(name), encoding='bytes') + for item in read_batch(batch): + yield item + + if not cycle: + break + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Cifar100", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train100(): + """ + CIFAR-100 training set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [0, 1] and label in [0, 99]. + + :return: Training reader creator + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5), + 'train') + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Cifar100", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test100(): + """ + CIFAR-100 test set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [0, 1] and label in [0, 99]. + + :return: Test reader creator. + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5), + 'test') + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Cifar10", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train10(cycle=False): + """ + CIFAR-10 training set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [0, 1] and label in [0, 9]. + + :param cycle: whether to cycle through the dataset + :type cycle: bool + :return: Training reader creator + :rtype: callable + """ + return reader_creator(paddle.dataset.common.download( + CIFAR10_URL, 'cifar', CIFAR10_MD5), + 'data_batch', + cycle=cycle) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Cifar10", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test10(cycle=False): + """ + CIFAR-10 test set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [0, 1] and label in [0, 9]. + + :param cycle: whether to cycle through the dataset + :type cycle: bool + :return: Test reader creator. + :rtype: callable + """ + return reader_creator(paddle.dataset.common.download( + CIFAR10_URL, 'cifar', CIFAR10_MD5), + 'test_batch', + cycle=cycle) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Cifar10", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5) + paddle.dataset.common.download(CIFAR100_URL, 'cifar', CIFAR100_MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/common.py new file mode 100644 index 0000000000000000000000000000000000000000..cebe77e55052b5223a7b321853782f6faa11effe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/common.py @@ -0,0 +1,223 @@ +# 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. + +from __future__ import print_function + +import requests +import hashlib +import os +import errno +import shutil +import six +import sys +import importlib +import paddle.dataset +import six.moves.cPickle as pickle +import tempfile +import glob +import paddle + +__all__ = [] + +HOME = os.path.expanduser('~') + +# If the default HOME dir does not support writing, we +# will create a temporary folder to store the cache files. +if not os.access(HOME, os.W_OK): + """ + gettempdir() return the name of the directory used for temporary files. + On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order. + On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order. + For more details, please refer to https://docs.python.org/3/library/tempfile.html + """ + HOME = tempfile.gettempdir() + +DATA_HOME = os.path.join(HOME, '.cache', 'paddle', 'dataset') + + +# When running unit tests, there could be multiple processes that +# trying to create DATA_HOME directory simultaneously, so we cannot +# use a if condition to check for the existence of the directory; +# instead, we use the filesystem as the synchronization mechanism by +# catching returned errors. +def must_mkdirs(path): + try: + os.makedirs(DATA_HOME) + except OSError as exc: + if exc.errno != errno.EEXIST: + raise + pass + + +must_mkdirs(DATA_HOME) + + +def md5file(fname): + hash_md5 = hashlib.md5() + f = open(fname, "rb") + for chunk in iter(lambda: f.read(4096), b""): + hash_md5.update(chunk) + f.close() + return hash_md5.hexdigest() + + +def download(url, module_name, md5sum, save_name=None): + dirname = os.path.join(DATA_HOME, module_name) + if not os.path.exists(dirname): + os.makedirs(dirname) + + filename = os.path.join( + dirname, + url.split('/')[-1] if save_name is None else save_name) + + if os.path.exists(filename) and md5file(filename) == md5sum: + return filename + + retry = 0 + retry_limit = 3 + while not (os.path.exists(filename) and md5file(filename) == md5sum): + if os.path.exists(filename): + sys.stderr.write("file %s md5 %s\n" % (md5file(filename), md5sum)) + if retry < retry_limit: + retry += 1 + else: + raise RuntimeError( + "Cannot download {0} within retry limit {1}".format( + url, retry_limit)) + sys.stderr.write("Cache file %s not found, downloading %s \n" % + (filename, url)) + sys.stderr.write("Begin to download\n") + try: + r = requests.get(url, stream=True) + total_length = r.headers.get('content-length') + + if total_length is None: + with open(filename, 'wb') as f: + shutil.copyfileobj(r.raw, f) + else: + with open(filename, 'wb') as f: + chunk_size = 4096 + total_length = int(total_length) + total_iter = total_length / chunk_size + 1 + log_interval = total_iter // 20 if total_iter > 20 else 1 + log_index = 0 + bar = paddle.hapi.progressbar.ProgressBar(total_iter, + name='item') + for data in r.iter_content(chunk_size=chunk_size): + f.write(data) + log_index += 1 + bar.update(log_index, {}) + if log_index % log_interval == 0: + bar.update(log_index) + + except Exception as e: + # re-try + continue + sys.stderr.write("\nDownload finished\n") + sys.stdout.flush() + return filename + + +def fetch_all(): + for module_name in [ + x for x in dir(paddle.dataset) if not x.startswith("__") + ]: + if "fetch" in dir( + importlib.import_module("paddle.dataset.%s" % module_name)): + getattr(importlib.import_module("paddle.dataset.%s" % module_name), + "fetch")() + + +def split(reader, line_count, suffix="%05d.pickle", dumper=pickle.dump): + """ + you can call the function as: + + split(paddle.dataset.cifar.train10(), line_count=1000, + suffix="imikolov-train-%05d.pickle") + + the output files as: + + |-imikolov-train-00000.pickle + |-imikolov-train-00001.pickle + |- ... + |-imikolov-train-00480.pickle + + :param reader: is a reader creator + :param line_count: line count for each file + :param suffix: the suffix for the output files, should contain "%d" + means the id for each file. Default is "%05d.pickle" + :param dumper: is a callable function that dump object to file, this + function will be called as dumper(obj, f) and obj is the object + will be dumped, f is a file object. Default is cPickle.dump. + """ + if not callable(dumper): + raise TypeError("dumper should be callable.") + lines = [] + indx_f = 0 + for i, d in enumerate(reader()): + lines.append(d) + if i >= line_count and i % line_count == 0: + with open(suffix % indx_f, "w") as f: + dumper(lines, f) + lines = [] + indx_f += 1 + if lines: + with open(suffix % indx_f, "w") as f: + dumper(lines, f) + + +def cluster_files_reader(files_pattern, + trainer_count, + trainer_id, + loader=pickle.load): + """ + Create a reader that yield element from the given files, select + a file set according trainer count and trainer_id + + :param files_pattern: the files which generating by split(...) + :param trainer_count: total trainer count + :param trainer_id: the trainer rank id + :param loader: is a callable function that load object from file, this + function will be called as loader(f) and f is a file object. + Default is cPickle.load + """ + + def reader(): + if not callable(loader): + raise TypeError("loader should be callable.") + file_list = glob.glob(files_pattern) + file_list.sort() + my_file_list = [] + for idx, fn in enumerate(file_list): + if idx % trainer_count == trainer_id: + print("append file: %s" % fn) + my_file_list.append(fn) + for fn in my_file_list: + with open(fn, "r") as f: + lines = loader(f) + for line in lines: + yield line + + return reader + + +def _check_exists_and_download(path, url, md5, module_name, download=True): + if path and os.path.exists(path): + return path + + if download: + return paddle.dataset.common.download(url, module_name, md5) + else: + raise ValueError( + '{} not exists and auto download disabled'.format(path)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/conll05.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/conll05.py new file mode 100644 index 0000000000000000000000000000000000000000..eb43eaf742e115eb8f2520de625d05ee5c55fa00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/conll05.py @@ -0,0 +1,272 @@ +# 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. +""" +Conll05 dataset. +Paddle semantic role labeling Book and demo use this dataset as an example. +Because Conll05 is not free in public, the default downloaded URL is test set +of Conll05 (which is public). Users can change URL and MD5 to their Conll +dataset. And a pre-trained word vector model based on Wikipedia corpus is used +to initialize SRL model. +""" + +from __future__ import print_function + +import tarfile +import gzip +import itertools +import paddle.dataset.common +import paddle.compat as cpt +import paddle.utils.deprecated as deprecated +from six.moves import zip, range + +__all__ = [] + +DATA_URL = 'http://paddlemodels.bj.bcebos.com/conll05st/conll05st-tests.tar.gz' +DATA_MD5 = '387719152ae52d60422c016e92a742fc' +WORDDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FwordDict.txt' +WORDDICT_MD5 = 'ea7fb7d4c75cc6254716f0177a506baa' +VERBDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FverbDict.txt' +VERBDICT_MD5 = '0d2977293bbb6cbefab5b0f97db1e77c' +TRGDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FtargetDict.txt' +TRGDICT_MD5 = 'd8c7f03ceb5fc2e5a0fa7503a4353751' +EMB_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2Femb' +EMB_MD5 = 'bf436eb0faa1f6f9103017f8be57cdb7' + +UNK_IDX = 0 + + +def load_label_dict(filename): + d = dict() + tag_dict = set() + with open(filename, 'r') as f: + for i, line in enumerate(f): + line = line.strip() + if line.startswith("B-"): + tag_dict.add(line[2:]) + elif line.startswith("I-"): + tag_dict.add(line[2:]) + index = 0 + for tag in tag_dict: + d["B-" + tag] = index + index += 1 + d["I-" + tag] = index + index += 1 + d["O"] = index + return d + + +def load_dict(filename): + d = dict() + with open(filename, 'r') as f: + for i, line in enumerate(f): + d[line.strip()] = i + return d + + +def corpus_reader(data_path, words_name, props_name): + """ + Read one corpus. It returns an iterator. Each element of + this iterator is a tuple including sentence and labels. The sentence is + consist of a list of word IDs. The labels include a list of label IDs. + :return: a iterator of data. + :rtype: iterator + """ + + def reader(): + tf = tarfile.open(data_path) + wf = tf.extractfile(words_name) + pf = tf.extractfile(props_name) + with gzip.GzipFile(fileobj=wf) as words_file, gzip.GzipFile( + fileobj=pf) as props_file: + sentences = [] + labels = [] + one_seg = [] + for word, label in zip(words_file, props_file): + word = cpt.to_text(word.strip()) + label = cpt.to_text(label.strip().split()) + + if len(label) == 0: # end of sentence + for i in range(len(one_seg[0])): + a_kind_lable = [x[i] for x in one_seg] + labels.append(a_kind_lable) + + if len(labels) >= 1: + verb_list = [] + for x in labels[0]: + if x != '-': + verb_list.append(x) + + for i, lbl in enumerate(labels[1:]): + cur_tag = 'O' + is_in_bracket = False + lbl_seq = [] + verb_word = '' + for l in lbl: + if l == '*' and is_in_bracket == False: + lbl_seq.append('O') + elif l == '*' and is_in_bracket == True: + lbl_seq.append('I-' + cur_tag) + elif l == '*)': + lbl_seq.append('I-' + cur_tag) + is_in_bracket = False + elif l.find('(') != -1 and l.find(')') != -1: + cur_tag = l[1:l.find('*')] + lbl_seq.append('B-' + cur_tag) + is_in_bracket = False + elif l.find('(') != -1 and l.find(')') == -1: + cur_tag = l[1:l.find('*')] + lbl_seq.append('B-' + cur_tag) + is_in_bracket = True + else: + raise RuntimeError('Unexpected label: %s' % + l) + + yield sentences, verb_list[i], lbl_seq + + sentences = [] + labels = [] + one_seg = [] + else: + sentences.append(word) + one_seg.append(label) + + pf.close() + wf.close() + tf.close() + + return reader + + +def reader_creator(corpus_reader, + word_dict=None, + predicate_dict=None, + label_dict=None): + + def reader(): + for sentence, predicate, labels in corpus_reader(): + + sen_len = len(sentence) + + verb_index = labels.index('B-V') + mark = [0] * len(labels) + if verb_index > 0: + mark[verb_index - 1] = 1 + ctx_n1 = sentence[verb_index - 1] + else: + ctx_n1 = 'bos' + + if verb_index > 1: + mark[verb_index - 2] = 1 + ctx_n2 = sentence[verb_index - 2] + else: + ctx_n2 = 'bos' + + mark[verb_index] = 1 + ctx_0 = sentence[verb_index] + + if verb_index < len(labels) - 1: + mark[verb_index + 1] = 1 + ctx_p1 = sentence[verb_index + 1] + else: + ctx_p1 = 'eos' + + if verb_index < len(labels) - 2: + mark[verb_index + 2] = 1 + ctx_p2 = sentence[verb_index + 2] + else: + ctx_p2 = 'eos' + + word_idx = [word_dict.get(w, UNK_IDX) for w in sentence] + + ctx_n2_idx = [word_dict.get(ctx_n2, UNK_IDX)] * sen_len + ctx_n1_idx = [word_dict.get(ctx_n1, UNK_IDX)] * sen_len + ctx_0_idx = [word_dict.get(ctx_0, UNK_IDX)] * sen_len + ctx_p1_idx = [word_dict.get(ctx_p1, UNK_IDX)] * sen_len + ctx_p2_idx = [word_dict.get(ctx_p2, UNK_IDX)] * sen_len + + pred_idx = [predicate_dict.get(predicate)] * sen_len + label_idx = [label_dict.get(w) for w in labels] + + yield word_idx, ctx_n2_idx, ctx_n1_idx, \ + ctx_0_idx, ctx_p1_idx, ctx_p2_idx, pred_idx, mark, label_idx + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Conll05st", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def get_dict(): + """ + Get the word, verb and label dictionary of Wikipedia corpus. + """ + word_dict = load_dict( + paddle.dataset.common.download(WORDDICT_URL, 'conll05st', WORDDICT_MD5)) + verb_dict = load_dict( + paddle.dataset.common.download(VERBDICT_URL, 'conll05st', VERBDICT_MD5)) + label_dict = load_label_dict( + paddle.dataset.common.download(TRGDICT_URL, 'conll05st', TRGDICT_MD5)) + return word_dict, verb_dict, label_dict + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Conll05st", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def get_embedding(): + """ + Get the trained word vector based on Wikipedia corpus. + """ + return paddle.dataset.common.download(EMB_URL, 'conll05st', EMB_MD5) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Conll05st", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(): + """ + Conll05 test set creator. + + Because the training dataset is not free, the test dataset is used for + training. It returns a reader creator, each sample in the reader is nine + features, including sentence sequence, predicate, predicate context, + predicate context flag and tagged sequence. + + :return: Training reader creator + :rtype: callable + """ + word_dict, verb_dict, label_dict = get_dict() + reader = corpus_reader( + paddle.dataset.common.download(DATA_URL, 'conll05st', DATA_MD5), + words_name='conll05st-release/test.wsj/words/test.wsj.words.gz', + props_name='conll05st-release/test.wsj/props/test.wsj.props.gz') + return reader_creator(reader, word_dict, verb_dict, label_dict) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Conll05st", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(WORDDICT_URL, 'conll05st', WORDDICT_MD5) + paddle.dataset.common.download(VERBDICT_URL, 'conll05st', VERBDICT_MD5) + paddle.dataset.common.download(TRGDICT_URL, 'conll05st', TRGDICT_MD5) + paddle.dataset.common.download(EMB_URL, 'conll05st', EMB_MD5) + paddle.dataset.common.download(DATA_URL, 'conll05st', DATA_MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/flowers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/flowers.py new file mode 100644 index 0000000000000000000000000000000000000000..04b3a4cfc175411c67828bb77e066555f8deaf3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/flowers.py @@ -0,0 +1,243 @@ +# 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. +""" +This module will download dataset from +http://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html +and parse train/test set intopaddle reader creators. + +This set contains images of flowers belonging to 102 different categories. +The images were acquired by searching the web and taking pictures. There are a +minimum of 40 images for each category. + +The database was used in: + +Nilsback, M-E. and Zisserman, A. Automated flower classification over a large + number of classes.Proceedings of the Indian Conference on Computer Vision, +Graphics and Image Processing (2008) +http://www.robots.ox.ac.uk/~vgg/publications/papers/nilsback08.{pdf,ps.gz}. + +""" + +from __future__ import print_function + +import itertools +import functools +from .common import download +import tarfile + +from paddle.dataset.image import load_image_bytes +from paddle.dataset.image import load_image +from paddle.dataset.image import simple_transform +from paddle.dataset.image import batch_images_from_tar + +from paddle.reader import map_readers, xmap_readers +from paddle import compat as cpt +import paddle.utils.deprecated as deprecated +import os +import numpy as np +from multiprocessing import cpu_count +import six +from six.moves import cPickle as pickle +from paddle.utils import try_import + +__all__ = [] + +DATA_URL = 'http://paddlemodels.bj.bcebos.com/flowers/102flowers.tgz' +LABEL_URL = 'http://paddlemodels.bj.bcebos.com/flowers/imagelabels.mat' +SETID_URL = 'http://paddlemodels.bj.bcebos.com/flowers/setid.mat' +DATA_MD5 = '52808999861908f626f3c1f4e79d11fa' +LABEL_MD5 = 'e0620be6f572b9609742df49c70aed4d' +SETID_MD5 = 'a5357ecc9cb78c4bef273ce3793fc85c' +# In official 'readme', tstid is the flag of test data +# and trnid is the flag of train data. But test data is more than train data. +# So we exchange the train data and test data. +TRAIN_FLAG = 'tstid' +TEST_FLAG = 'trnid' +VALID_FLAG = 'valid' + + +def default_mapper(is_train, sample): + ''' + map image bytes data to type needed by model input layer + ''' + img, label = sample + img = load_image_bytes(img) + img = simple_transform(img, + 256, + 224, + is_train, + mean=[103.94, 116.78, 123.68]) + return img.flatten().astype('float32'), label + + +train_mapper = functools.partial(default_mapper, True) +test_mapper = functools.partial(default_mapper, False) + + +def reader_creator(data_file, + label_file, + setid_file, + dataset_name, + mapper, + buffered_size=1024, + use_xmap=True, + cycle=False): + ''' + 1. read images from tar file and + merge images into batch files in 102flowers.tgz_batch/ + 2. get a reader to read sample from batch file + + :param data_file: downloaded data file + :type data_file: string + :param label_file: downloaded label file + :type label_file: string + :param setid_file: downloaded setid file containing information + about how to split dataset + :type setid_file: string + :param dataset_name: data set name (tstid|trnid|valid) + :type dataset_name: string + :param mapper: a function to map image bytes data to type + needed by model input layer + :type mapper: callable + :param buffered_size: the size of buffer used to process images + :type buffered_size: int + :param cycle: whether to cycle through the dataset + :type cycle: bool + :return: data reader + :rtype: callable + ''' + + def reader(): + scio = try_import('scipy.io') + + labels = scio.loadmat(label_file)['labels'][0] + indexes = scio.loadmat(setid_file)[dataset_name][0] + + img2label = {} + for i in indexes: + img = "jpg/image_%05d.jpg" % i + img2label[img] = labels[i - 1] + + tf = tarfile.open(data_file) + mems = tf.getmembers() + file_id = 0 + for mem in mems: + if mem.name in img2label: + image = tf.extractfile(mem).read() + label = img2label[mem.name] + yield image, int(label) - 1 + + if use_xmap: + return xmap_readers(mapper, reader, min(4, cpu_count()), buffered_size) + else: + return map_readers(mapper, reader) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Flowers", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(mapper=train_mapper, buffered_size=1024, use_xmap=True, cycle=False): + ''' + Create flowers training set reader. + It returns a reader, each sample in the reader is + image pixels in [0, 1] and label in [1, 102] + translated from original color image by steps: + 1. resize to 256*256 + 2. random crop to 224*224 + 3. flatten + :param mapper: a function to map sample. + :type mapper: callable + :param buffered_size: the size of buffer used to process images + :type buffered_size: int + :param cycle: whether to cycle through the dataset + :type cycle: bool + :return: train data reader + :rtype: callable + ''' + return reader_creator(download(DATA_URL, 'flowers', DATA_MD5), + download(LABEL_URL, 'flowers', LABEL_MD5), + download(SETID_URL, 'flowers', SETID_MD5), + TRAIN_FLAG, + mapper, + buffered_size, + use_xmap, + cycle=cycle) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Flowers", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(mapper=test_mapper, buffered_size=1024, use_xmap=True, cycle=False): + ''' + Create flowers test set reader. + It returns a reader, each sample in the reader is + image pixels in [0, 1] and label in [1, 102] + translated from original color image by steps: + 1. resize to 256*256 + 2. random crop to 224*224 + 3. flatten + :param mapper: a function to map sample. + :type mapper: callable + :param buffered_size: the size of buffer used to process images + :type buffered_size: int + :param cycle: whether to cycle through the dataset + :type cycle: bool + :return: test data reader + :rtype: callable + ''' + return reader_creator(download(DATA_URL, 'flowers', DATA_MD5), + download(LABEL_URL, 'flowers', LABEL_MD5), + download(SETID_URL, 'flowers', SETID_MD5), + TEST_FLAG, + mapper, + buffered_size, + use_xmap, + cycle=cycle) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.Flowers", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def valid(mapper=test_mapper, buffered_size=1024, use_xmap=True): + ''' + Create flowers validation set reader. + It returns a reader, each sample in the reader is + image pixels in [0, 1] and label in [1, 102] + translated from original color image by steps: + 1. resize to 256*256 + 2. random crop to 224*224 + 3. flatten + :param mapper: a function to map sample. + :type mapper: callable + :param buffered_size: the size of buffer used to process images + :type buffered_size: int + :return: test data reader + :rtype: callable + ''' + return reader_creator(download(DATA_URL, 'flowers', DATA_MD5), + download(LABEL_URL, 'flowers', LABEL_MD5), + download(SETID_URL, 'flowers', SETID_MD5), VALID_FLAG, + mapper, buffered_size, use_xmap) + + +def fetch(): + download(DATA_URL, 'flowers', DATA_MD5) + download(LABEL_URL, 'flowers', LABEL_MD5) + download(SETID_URL, 'flowers', SETID_MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/image.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/image.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0d7d95b11a8de5510e0737cbf17c447a65d6ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/image.py @@ -0,0 +1,420 @@ +# Copyright (c) 2018 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. +""" +This file contains some common interfaces for image preprocess. +Many users are confused about the image layout. We introduce +the image layout as follows. + +- CHW Layout + + - The abbreviations: C=channel, H=Height, W=Width + - The default layout of image opened by cv2 or PIL is HWC. + PaddlePaddle only supports the CHW layout. And CHW is simply + a transpose of HWC. It must transpose the input image. + +- Color format: RGB or BGR + + OpenCV use BGR color format. PIL use RGB color format. Both + formats can be used for training. Noted that, the format should + be keep consistent between the training and inference period. +""" + +from __future__ import print_function + +import six +import numpy as np +# FIXME(minqiyang): this is an ugly fix for the numpy bug reported here +# https://github.com/numpy/numpy/issues/12497 +if six.PY3: + import subprocess + import sys + import os + interpreter = sys.executable + # Note(zhouwei): if use Python/C 'PyRun_SimpleString', 'sys.executable' + # will be the C++ execubable on Windows + if sys.platform == 'win32' and 'python.exe' not in interpreter: + interpreter = sys.exec_prefix + os.sep + 'python.exe' + import_cv2_proc = subprocess.Popen([interpreter, "-c", "import cv2"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + out, err = import_cv2_proc.communicate() + retcode = import_cv2_proc.poll() + if retcode != 0: + cv2 = None + else: + try: + import cv2 + except ImportError: + cv2 = None +else: + try: + import cv2 + except ImportError: + cv2 = None +import os +import tarfile +import six.moves.cPickle as pickle + +__all__ = [] + + +def _check_cv2(): + if cv2 is None: + import sys + sys.stderr.write( + '''Warning with paddle image module: opencv-python should be imported, + or paddle image module could NOT work; please install opencv-python first.''' + ) + return False + else: + return True + + +def batch_images_from_tar(data_file, + dataset_name, + img2label, + num_per_batch=1024): + """ + Read images from tar file and batch them into batch file. + + :param data_file: path of image tar file + :type data_file: string + :param dataset_name: 'train','test' or 'valid' + :type dataset_name: string + :param img2label: a dic with image file name as key + and image's label as value + :type img2label: dic + :param num_per_batch: image number per batch file + :type num_per_batch: int + :return: path of list file containing paths of batch file + :rtype: string + """ + batch_dir = data_file + "_batch" + out_path = "%s/%s_%s" % (batch_dir, dataset_name, os.getpid()) + meta_file = "%s/%s_%s.txt" % (batch_dir, dataset_name, os.getpid()) + + if os.path.exists(out_path): + return meta_file + else: + os.makedirs(out_path) + + tf = tarfile.open(data_file) + mems = tf.getmembers() + data = [] + labels = [] + file_id = 0 + for mem in mems: + if mem.name in img2label: + data.append(tf.extractfile(mem).read()) + labels.append(img2label[mem.name]) + if len(data) == num_per_batch: + output = {} + output['label'] = labels + output['data'] = data + pickle.dump(output, + open('%s/batch_%d' % (out_path, file_id), 'wb'), + protocol=2) + file_id += 1 + data = [] + labels = [] + if len(data) > 0: + output = {} + output['label'] = labels + output['data'] = data + pickle.dump(output, + open('%s/batch_%d' % (out_path, file_id), 'wb'), + protocol=2) + + with open(meta_file, 'a') as meta: + for file in os.listdir(out_path): + meta.write(os.path.abspath("%s/%s" % (out_path, file)) + "\n") + return meta_file + + +def load_image_bytes(bytes, is_color=True): + """ + Load an color or gray image from bytes array. + + Example usage: + + .. code-block:: python + + with open('cat.jpg') as f: + im = load_image_bytes(f.read()) + + :param bytes: the input image bytes array. + :type bytes: str + :param is_color: If set is_color True, it will load and + return a color image. Otherwise, it will + load and return a gray image. + :type is_color: bool + """ + assert _check_cv2() is True + + flag = 1 if is_color else 0 + file_bytes = np.asarray(bytearray(bytes), dtype=np.uint8) + img = cv2.imdecode(file_bytes, flag) + return img + + +def load_image(file, is_color=True): + """ + Load an color or gray image from the file path. + + Example usage: + + .. code-block:: python + + im = load_image('cat.jpg') + + :param file: the input image path. + :type file: string + :param is_color: If set is_color True, it will load and + return a color image. Otherwise, it will + load and return a gray image. + :type is_color: bool + """ + assert _check_cv2() is True + + # cv2.IMAGE_COLOR for OpenCV3 + # cv2.CV_LOAD_IMAGE_COLOR for older OpenCV Version + # cv2.IMAGE_GRAYSCALE for OpenCV3 + # cv2.CV_LOAD_IMAGE_GRAYSCALE for older OpenCV Version + # Here, use constant 1 and 0 + # 1: COLOR, 0: GRAYSCALE + flag = 1 if is_color else 0 + im = cv2.imread(file, flag) + return im + + +def resize_short(im, size): + """ + Resize an image so that the length of shorter edge is size. + + Example usage: + + .. code-block:: python + + im = load_image('cat.jpg') + im = resize_short(im, 256) + + :param im: the input image with HWC layout. + :type im: ndarray + :param size: the shorter edge size of image after resizing. + :type size: int + """ + assert _check_cv2() is True + + h, w = im.shape[:2] + h_new, w_new = size, size + if h > w: + h_new = size * h // w + else: + w_new = size * w // h + im = cv2.resize(im, (w_new, h_new), interpolation=cv2.INTER_CUBIC) + return im + + +def to_chw(im, order=(2, 0, 1)): + """ + Transpose the input image order. The image layout is HWC format + opened by cv2 or PIL. Transpose the input image to CHW layout + according the order (2,0,1). + + Example usage: + + .. code-block:: python + + im = load_image('cat.jpg') + im = resize_short(im, 256) + im = to_chw(im) + + :param im: the input image with HWC layout. + :type im: ndarray + :param order: the transposed order. + :type order: tuple|list + """ + assert len(im.shape) == len(order) + im = im.transpose(order) + return im + + +def center_crop(im, size, is_color=True): + """ + Crop the center of image with size. + + Example usage: + + .. code-block:: python + + im = center_crop(im, 224) + + :param im: the input image with HWC layout. + :type im: ndarray + :param size: the cropping size. + :type size: int + :param is_color: whether the image is color or not. + :type is_color: bool + """ + h, w = im.shape[:2] + h_start = (h - size) // 2 + w_start = (w - size) // 2 + h_end, w_end = h_start + size, w_start + size + if is_color: + im = im[h_start:h_end, w_start:w_end, :] + else: + im = im[h_start:h_end, w_start:w_end] + return im + + +def random_crop(im, size, is_color=True): + """ + Randomly crop input image with size. + + Example usage: + + .. code-block:: python + + im = random_crop(im, 224) + + :param im: the input image with HWC layout. + :type im: ndarray + :param size: the cropping size. + :type size: int + :param is_color: whether the image is color or not. + :type is_color: bool + """ + h, w = im.shape[:2] + h_start = np.random.randint(0, h - size + 1) + w_start = np.random.randint(0, w - size + 1) + h_end, w_end = h_start + size, w_start + size + if is_color: + im = im[h_start:h_end, w_start:w_end, :] + else: + im = im[h_start:h_end, w_start:w_end] + return im + + +def left_right_flip(im, is_color=True): + """ + Flip an image along the horizontal direction. + Return the flipped image. + + Example usage: + + .. code-block:: python + + im = left_right_flip(im) + + :param im: input image with HWC layout or HW layout for gray image + :type im: ndarray + :param is_color: whether input image is color or not + :type is_color: bool + """ + if len(im.shape) == 3 and is_color: + return im[:, ::-1, :] + else: + return im[:, ::-1] + + +def simple_transform(im, + resize_size, + crop_size, + is_train, + is_color=True, + mean=None): + """ + Simply data argumentation for training. These operations include + resizing, croping and flipping. + + Example usage: + + .. code-block:: python + + im = simple_transform(im, 256, 224, True) + + :param im: The input image with HWC layout. + :type im: ndarray + :param resize_size: The shorter edge length of the resized image. + :type resize_size: int + :param crop_size: The cropping size. + :type crop_size: int + :param is_train: Whether it is training or not. + :type is_train: bool + :param is_color: whether the image is color or not. + :type is_color: bool + :param mean: the mean values, which can be element-wise mean values or + mean values per channel. + :type mean: numpy array | list + """ + im = resize_short(im, resize_size) + if is_train: + im = random_crop(im, crop_size, is_color=is_color) + if np.random.randint(2) == 0: + im = left_right_flip(im, is_color) + else: + im = center_crop(im, crop_size, is_color=is_color) + if len(im.shape) == 3: + im = to_chw(im) + + im = im.astype('float32') + if mean is not None: + mean = np.array(mean, dtype=np.float32) + # mean value, may be one value per channel + if mean.ndim == 1 and is_color: + mean = mean[:, np.newaxis, np.newaxis] + elif mean.ndim == 1: + mean = mean + else: + # elementwise mean + assert len(mean.shape) == len(im) + im -= mean + + return im + + +def load_and_transform(filename, + resize_size, + crop_size, + is_train, + is_color=True, + mean=None): + """ + Load image from the input file `filename` and transform image for + data argumentation. Please refer to the `simple_transform` interface + for the transform operations. + + Example usage: + + .. code-block:: python + + im = load_and_transform('cat.jpg', 256, 224, True) + + :param filename: The file name of input image. + :type filename: string + :param resize_size: The shorter edge length of the resized image. + :type resize_size: int + :param crop_size: The cropping size. + :type crop_size: int + :param is_train: Whether it is training or not. + :type is_train: bool + :param is_color: whether the image is color or not. + :type is_color: bool + :param mean: the mean values, which can be element-wise mean values or + mean values per channel. + :type mean: numpy array | list + """ + im = load_image(filename, is_color) + im = simple_transform(im, resize_size, crop_size, is_train, is_color, mean) + return im diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imdb.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imdb.py new file mode 100644 index 0000000000000000000000000000000000000000..b45cf4f6474bf25fa640a2ffe760576887e40eca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imdb.py @@ -0,0 +1,167 @@ +# 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. +""" +IMDB dataset. + +This module downloads IMDB dataset from +http://ai.stanford.edu/%7Eamaas/data/sentiment/. This dataset contains a set +of 25,000 highly polar movie reviews for training, and 25,000 for testing. +Besides, this module also provides API for building dictionary. +""" + +from __future__ import print_function + +import paddle.dataset.common +import paddle.utils.deprecated as deprecated +import collections +import tarfile +import re +import string +import six + +__all__ = [] + +#URL = 'http://ai.stanford.edu/%7Eamaas/data/sentiment/aclImdb_v1.tar.gz' +URL = 'https://dataset.bj.bcebos.com/imdb%2FaclImdb_v1.tar.gz' +MD5 = '7c2ac02c03563afcf9b574c7e56c153a' + + +def tokenize(pattern): + """ + Read files that match the given pattern. Tokenize and yield each file. + """ + + with tarfile.open(paddle.dataset.common.download(URL, 'imdb', MD5)) as tarf: + # Note that we should use tarfile.next(), which does + # sequential access of member files, other than + # tarfile.extractfile, which does random access and might + # destroy hard disks. + tf = tarf.next() + while tf != None: + if bool(pattern.match(tf.name)): + # newline and punctuations removal and ad-hoc tokenization. + yield tarf.extractfile(tf).read().rstrip( + six.b("\n\r")).translate(None, six.b( + string.punctuation)).lower().split() + tf = tarf.next() + + +def build_dict(pattern, cutoff): + """ + Build a word dictionary from the corpus. Keys of the dictionary are words, + and values are zero-based IDs of these words. + """ + word_freq = collections.defaultdict(int) + for doc in tokenize(pattern): + for word in doc: + word_freq[word] += 1 + + # Not sure if we should prune less-frequent words here. + word_freq = [x for x in six.iteritems(word_freq) if x[1] > cutoff] + + dictionary = sorted(word_freq, key=lambda x: (-x[1], x[0])) + words, _ = list(zip(*dictionary)) + word_idx = dict(list(zip(words, six.moves.range(len(words))))) + word_idx[''] = len(words) + return word_idx + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imdb", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def reader_creator(pos_pattern, neg_pattern, word_idx): + UNK = word_idx[''] + INS = [] + + def load(pattern, out, label): + for doc in tokenize(pattern): + out.append(([word_idx.get(w, UNK) for w in doc], label)) + + load(pos_pattern, INS, 0) + load(neg_pattern, INS, 1) + + def reader(): + for doc, label in INS: + yield doc, label + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imdb", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(word_idx): + """ + IMDB training set creator. + + It returns a reader creator, each sample in the reader is an zero-based ID + sequence and label in [0, 1]. + + :param word_idx: word dictionary + :type word_idx: dict + :return: Training reader creator + :rtype: callable + """ + return reader_creator(re.compile(r"aclImdb/train/pos/.*\.txt$"), + re.compile(r"aclImdb/train/neg/.*\.txt$"), word_idx) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imdb", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(word_idx): + """ + IMDB test set creator. + + It returns a reader creator, each sample in the reader is an zero-based ID + sequence and label in [0, 1]. + + :param word_idx: word dictionary + :type word_idx: dict + :return: Test reader creator + :rtype: callable + """ + return reader_creator(re.compile(r"aclImdb/test/pos/.*\.txt$"), + re.compile(r"aclImdb/test/neg/.*\.txt$"), word_idx) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imdb", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def word_dict(): + """ + Build a word dictionary from the corpus. + + :return: Word dictionary + :rtype: dict + """ + return build_dict( + re.compile(r"aclImdb/((train)|(test))/((pos)|(neg))/.*\.txt$"), 150) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imdb", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(URL, 'imdb', MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imikolov.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imikolov.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6b1d7493bed1524de2bc27aea2e73a26f41218 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/imikolov.py @@ -0,0 +1,172 @@ +# 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. +""" +imikolov's simple dataset. + +This module will download dataset from +http://www.fit.vutbr.cz/~imikolov/rnnlm/ and parse training set and test set +into paddle reader creators. +""" + +from __future__ import print_function + +import paddle.dataset.common +import paddle.utils.deprecated as deprecated +import collections +import tarfile +import six + +__all__ = [] + +#URL = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz' +URL = 'https://dataset.bj.bcebos.com/imikolov%2Fsimple-examples.tgz' +MD5 = '30177ea32e27c525793142b6bf2c8e2d' + + +class DataType(object): + NGRAM = 1 + SEQ = 2 + + +def word_count(f, word_freq=None): + if word_freq is None: + word_freq = collections.defaultdict(int) + + for l in f: + for w in l.strip().split(): + word_freq[w] += 1 + word_freq[''] += 1 + word_freq[''] += 1 + + return word_freq + + +def build_dict(min_word_freq=50): + """ + Build a word dictionary from the corpus, Keys of the dictionary are words, + and values are zero-based IDs of these words. + """ + train_filename = './simple-examples/data/ptb.train.txt' + test_filename = './simple-examples/data/ptb.valid.txt' + with tarfile.open( + paddle.dataset.common.download(paddle.dataset.imikolov.URL, + 'imikolov', + paddle.dataset.imikolov.MD5)) as tf: + trainf = tf.extractfile(train_filename) + testf = tf.extractfile(test_filename) + word_freq = word_count(testf, word_count(trainf)) + if '' in word_freq: + # remove for now, since we will set it as last index + del word_freq[''] + + word_freq = [ + x for x in six.iteritems(word_freq) if x[1] > min_word_freq + ] + + word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0])) + words, _ = list(zip(*word_freq_sorted)) + word_idx = dict(list(zip(words, six.moves.range(len(words))))) + word_idx[''] = len(words) + + return word_idx + + +def reader_creator(filename, word_idx, n, data_type): + + def reader(): + with tarfile.open( + paddle.dataset.common.download( + paddle.dataset.imikolov.URL, 'imikolov', + paddle.dataset.imikolov.MD5)) as tf: + f = tf.extractfile(filename) + + UNK = word_idx[''] + for l in f: + if DataType.NGRAM == data_type: + assert n > -1, 'Invalid gram length' + l = [''] + l.strip().split() + [''] + if len(l) >= n: + l = [word_idx.get(w, UNK) for w in l] + for i in six.moves.range(n, len(l) + 1): + yield tuple(l[i - n:i]) + elif DataType.SEQ == data_type: + l = l.strip().split() + l = [word_idx.get(w, UNK) for w in l] + src_seq = [word_idx['']] + l + trg_seq = l + [word_idx['']] + if n > 0 and len(src_seq) > n: continue + yield src_seq, trg_seq + else: + assert False, 'Unknow data type' + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imikolov", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(word_idx, n, data_type=DataType.NGRAM): + """ + imikolov training set creator. + + It returns a reader creator, each sample in the reader is a word ID + tuple. + + :param word_idx: word dictionary + :type word_idx: dict + :param n: sliding window size if type is ngram, otherwise max length of sequence + :type n: int + :param data_type: data type (ngram or sequence) + :type data_type: member variable of DataType (NGRAM or SEQ) + :return: Training reader creator + :rtype: callable + """ + return reader_creator('./simple-examples/data/ptb.train.txt', word_idx, n, + data_type) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imikolov", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(word_idx, n, data_type=DataType.NGRAM): + """ + imikolov test set creator. + + It returns a reader creator, each sample in the reader is a word ID + tuple. + + :param word_idx: word dictionary + :type word_idx: dict + :param n: sliding window size if type is ngram, otherwise max length of sequence + :type n: int + :param data_type: data type (ngram or sequence) + :type data_type: member variable of DataType (NGRAM or SEQ) + :return: Test reader creator + :rtype: callable + """ + return reader_creator('./simple-examples/data/ptb.valid.txt', word_idx, n, + data_type) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Imikolov", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(URL, "imikolov", MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/mnist.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..5c81d5d25cf80d299e12a1231c8c09335430cd66 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/mnist.py @@ -0,0 +1,147 @@ +# 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. +""" +MNIST dataset. + +This module will download dataset from http://yann.lecun.com/exdb/mnist/ and +parse training set and test set into paddle reader creators. +""" + +from __future__ import print_function + +import paddle.dataset.common +import paddle.utils.deprecated as deprecated +import gzip +import numpy +import struct +from six.moves import range + +__all__ = [] + +URL_PREFIX = 'https://dataset.bj.bcebos.com/mnist/' +TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz' +TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3' +TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz' +TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c' +TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz' +TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873' +TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz' +TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432' + + +def reader_creator(image_filename, label_filename, buffer_size): + + def reader(): + with gzip.GzipFile(image_filename, 'rb') as image_file: + img_buf = image_file.read() + with gzip.GzipFile(label_filename, 'rb') as label_file: + lab_buf = label_file.read() + + step_label = 0 + + offset_img = 0 + # read from Big-endian + # get file info from magic byte + # image file : 16B + magic_byte_img = '>IIII' + magic_img, image_num, rows, cols = struct.unpack_from( + magic_byte_img, img_buf, offset_img) + offset_img += struct.calcsize(magic_byte_img) + + offset_lab = 0 + # label file : 8B + magic_byte_lab = '>II' + magic_lab, label_num = struct.unpack_from( + magic_byte_lab, lab_buf, offset_lab) + offset_lab += struct.calcsize(magic_byte_lab) + + while True: + if step_label >= label_num: + break + fmt_label = '>' + str(buffer_size) + 'B' + labels = struct.unpack_from(fmt_label, lab_buf, offset_lab) + offset_lab += struct.calcsize(fmt_label) + step_label += buffer_size + + fmt_images = '>' + str(buffer_size * rows * cols) + 'B' + images_temp = struct.unpack_from(fmt_images, img_buf, + offset_img) + images = numpy.reshape( + images_temp, + (buffer_size, rows * cols)).astype('float32') + offset_img += struct.calcsize(fmt_images) + + images = images / 255.0 + images = images * 2.0 + images = images - 1.0 + + for i in range(buffer_size): + yield images[i, :], int(labels[i]) + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.MNIST", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(): + """ + MNIST training set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [-1, 1] and label in [0, 9]. + + :return: Training reader creator + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(TRAIN_IMAGE_URL, 'mnist', + TRAIN_IMAGE_MD5), + paddle.dataset.common.download(TRAIN_LABEL_URL, 'mnist', + TRAIN_LABEL_MD5), 100) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.MNIST", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(): + """ + MNIST test set creator. + + It returns a reader creator, each sample in the reader is image pixels in + [-1, 1] and label in [0, 9]. + + :return: Test reader creator. + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(TEST_IMAGE_URL, 'mnist', TEST_IMAGE_MD5), + paddle.dataset.common.download(TEST_LABEL_URL, 'mnist', TEST_LABEL_MD5), + 100) + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.MNIST", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(TRAIN_IMAGE_URL, 'mnist', TRAIN_IMAGE_MD5) + paddle.dataset.common.download(TRAIN_LABEL_URL, 'mnist', TRAIN_LABEL_MD5) + paddle.dataset.common.download(TEST_IMAGE_URL, 'mnist', TEST_IMAGE_MD5) + paddle.dataset.common.download(TEST_LABEL_URL, 'mnist', TEST_LABEL_MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/movielens.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/movielens.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf9a95436b16b70f7d830660e4114a4101322b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/movielens.py @@ -0,0 +1,308 @@ +# 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. +""" +Movielens 1-M dataset. + +Movielens 1-M dataset contains 1 million ratings from 6000 users on 4000 +movies, which was collected by GroupLens Research. This module will download +Movielens 1-M dataset from +http://files.grouplens.org/datasets/movielens/ml-1m.zip and parse training +set and test set into paddle reader creators. + +""" + +from __future__ import print_function + +import numpy as np +import zipfile +import paddle.dataset.common +import paddle.utils.deprecated as deprecated +import re +import random +import functools +import six +import paddle.compat as cpt + +__all__ = [] + +age_table = [1, 18, 25, 35, 45, 50, 56] + +#URL = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip' +URL = 'https://dataset.bj.bcebos.com/movielens%2Fml-1m.zip' +MD5 = 'c4d9eecfca2ab87c1945afe126590906' + + +class MovieInfo(object): + """ + Movie id, title and categories information are stored in MovieInfo. + """ + + def __init__(self, index, categories, title): + self.index = int(index) + self.categories = categories + self.title = title + + def value(self): + """ + Get information from a movie. + """ + return [ + self.index, [CATEGORIES_DICT[c] for c in self.categories], + [MOVIE_TITLE_DICT[w.lower()] for w in self.title.split()] + ] + + def __str__(self): + return "" % ( + self.index, self.title, self.categories) + + def __repr__(self): + return self.__str__() + + +class UserInfo(object): + """ + User id, gender, age, and job information are stored in UserInfo. + """ + + def __init__(self, index, gender, age, job_id): + self.index = int(index) + self.is_male = gender == 'M' + self.age = age_table.index(int(age)) + self.job_id = int(job_id) + + def value(self): + """ + Get information from a user. + """ + return [self.index, 0 if self.is_male else 1, self.age, self.job_id] + + def __str__(self): + return "" % ( + self.index, "M" if self.is_male else "F", age_table[self.age], + self.job_id) + + def __repr__(self): + return str(self) + + +MOVIE_INFO = None +MOVIE_TITLE_DICT = None +CATEGORIES_DICT = None +USER_INFO = None + + +def __initialize_meta_info__(): + fn = paddle.dataset.common.download(URL, "movielens", MD5) + global MOVIE_INFO + if MOVIE_INFO is None: + pattern = re.compile(r'^(.*)\((\d+)\)$') + with zipfile.ZipFile(file=fn) as package: + for info in package.infolist(): + assert isinstance(info, zipfile.ZipInfo) + MOVIE_INFO = dict() + title_word_set = set() + categories_set = set() + with package.open('ml-1m/movies.dat') as movie_file: + for i, line in enumerate(movie_file): + line = cpt.to_text(line, encoding='latin') + movie_id, title, categories = line.strip().split('::') + categories = categories.split('|') + for c in categories: + categories_set.add(c) + title = pattern.match(title).group(1) + MOVIE_INFO[int(movie_id)] = MovieInfo( + index=movie_id, categories=categories, title=title) + for w in title.split(): + title_word_set.add(w.lower()) + + global MOVIE_TITLE_DICT + MOVIE_TITLE_DICT = dict() + for i, w in enumerate(title_word_set): + MOVIE_TITLE_DICT[w] = i + + global CATEGORIES_DICT + CATEGORIES_DICT = dict() + for i, c in enumerate(categories_set): + CATEGORIES_DICT[c] = i + + global USER_INFO + USER_INFO = dict() + with package.open('ml-1m/users.dat') as user_file: + for line in user_file: + line = cpt.to_text(line, encoding='latin') + uid, gender, age, job, _ = line.strip().split("::") + USER_INFO[int(uid)] = UserInfo(index=uid, + gender=gender, + age=age, + job_id=job) + return fn + + +def __reader__(rand_seed=0, test_ratio=0.1, is_test=False): + fn = __initialize_meta_info__() + np.random.seed(rand_seed) + with zipfile.ZipFile(file=fn) as package: + with package.open('ml-1m/ratings.dat') as rating: + for line in rating: + line = cpt.to_text(line, encoding='latin') + if (np.random.random() < test_ratio) == is_test: + uid, mov_id, rating, _ = line.strip().split("::") + uid = int(uid) + mov_id = int(mov_id) + rating = float(rating) * 2 - 5.0 + + mov = MOVIE_INFO[mov_id] + usr = USER_INFO[uid] + yield usr.value() + mov.value() + [[rating]] + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def __reader_creator__(**kwargs): + return lambda: __reader__(**kwargs) + + +train = functools.partial(__reader_creator__, is_test=False) +test = functools.partial(__reader_creator__, is_test=True) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def get_movie_title_dict(): + """ + Get movie title dictionary. + """ + __initialize_meta_info__() + return MOVIE_TITLE_DICT + + +def __max_index_info__(a, b): + if a.index > b.index: + return a + else: + return b + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def max_movie_id(): + """ + Get the maximum value of movie id. + """ + __initialize_meta_info__() + return six.moves.reduce(__max_index_info__, list(MOVIE_INFO.values())).index + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def max_user_id(): + """ + Get the maximum value of user id. + """ + __initialize_meta_info__() + return six.moves.reduce(__max_index_info__, list(USER_INFO.values())).index + + +def __max_job_id_impl__(a, b): + if a.job_id > b.job_id: + return a + else: + return b + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def max_job_id(): + """ + Get the maximum value of job id. + """ + __initialize_meta_info__() + return six.moves.reduce(__max_job_id_impl__, + list(USER_INFO.values())).job_id + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def movie_categories(): + """ + Get movie categories dictionary. + """ + __initialize_meta_info__() + return CATEGORIES_DICT + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def user_info(): + """ + Get user info dictionary. + """ + __initialize_meta_info__() + return USER_INFO + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def movie_info(): + """ + Get movie info dictionary. + """ + __initialize_meta_info__() + return MOVIE_INFO + + +def unittest(): + for train_count, _ in enumerate(train()()): + pass + for test_count, _ in enumerate(test()()): + pass + + print(train_count, test_count) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.Movielens", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(URL, "movielens", MD5) + + +if __name__ == '__main__': + unittest() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/uci_housing.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/uci_housing.py new file mode 100644 index 0000000000000000000000000000000000000000..ae72c8e88ea0d3b90f165e034da94c56ad7243d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/uci_housing.py @@ -0,0 +1,173 @@ +# 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. +""" +UCI Housing dataset. + +This module will download dataset from +https://archive.ics.uci.edu/ml/machine-learning-databases/housing/ and +parse training set and test set into paddle reader creators. +""" + +from __future__ import print_function + +import numpy as np +import six +import tempfile +import tarfile +import os +import paddle.dataset.common +import paddle.utils.deprecated as deprecated + +__all__ = [] + +URL = 'http://paddlemodels.bj.bcebos.com/uci_housing/housing.data' +MD5 = 'd4accdce7a25600298819f8e28e8d593' +feature_names = [ + 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', + 'PTRATIO', 'B', 'LSTAT' +] + +UCI_TRAIN_DATA = None +UCI_TEST_DATA = None + +FLUID_URL_MODEL = 'https://github.com/PaddlePaddle/book/raw/develop/01.fit_a_line/fluid/fit_a_line.fluid.tar' +FLUID_MD5_MODEL = '6e6dd637ccd5993961f68bfbde46090b' + + +def feature_range(maximums, minimums): + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig, ax = plt.subplots() + feature_num = len(maximums) + ax.bar(list(range(feature_num)), + maximums - minimums, + color='r', + align='center') + ax.set_title('feature scale') + plt.xticks(list(range(feature_num)), feature_names) + plt.xlim([-1, feature_num]) + fig.set_figheight(6) + fig.set_figwidth(10) + if not os.path.exists('./image'): + os.makedirs('./image') + fig.savefig('image/ranges.png', dpi=48) + plt.close(fig) + + +def load_data(filename, feature_num=14, ratio=0.8): + global UCI_TRAIN_DATA, UCI_TEST_DATA + if UCI_TRAIN_DATA is not None and UCI_TEST_DATA is not None: + return + + data = np.fromfile(filename, sep=' ') + data = data.reshape(data.shape[0] // feature_num, feature_num) + maximums, minimums, avgs = data.max(axis=0), data.min( + axis=0), data.sum(axis=0) / data.shape[0] + # if you want to print the distribution of input data, you could use function of feature_range + #feature_range(maximums[:-1], minimums[:-1]) + for i in six.moves.range(feature_num - 1): + data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i]) + offset = int(data.shape[0] * ratio) + UCI_TRAIN_DATA = data[:offset] + UCI_TEST_DATA = data[offset:] + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.UCIHousing", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(): + """ + UCI_HOUSING training set creator. + + It returns a reader creator, each sample in the reader is features after + normalization and price number. + + :return: Training reader creator + :rtype: callable + """ + global UCI_TRAIN_DATA + load_data(paddle.dataset.common.download(URL, 'uci_housing', MD5)) + + def reader(): + for d in UCI_TRAIN_DATA: + yield d[:-1], d[-1:] + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.UCIHousing", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(): + """ + UCI_HOUSING test set creator. + + It returns a reader creator, each sample in the reader is features after + normalization and price number. + + :return: Test reader creator + :rtype: callable + """ + global UCI_TEST_DATA + load_data(paddle.dataset.common.download(URL, 'uci_housing', MD5)) + + def reader(): + for d in UCI_TEST_DATA: + yield d[:-1], d[-1:] + + return reader + + +def fluid_model(): + parameter_tar = paddle.dataset.common.download(FLUID_URL_MODEL, + 'uci_housing', + FLUID_MD5_MODEL, + 'fit_a_line.fluid.tar') + + tar = tarfile.TarFile(parameter_tar, mode='r') + dirpath = tempfile.mkdtemp() + tar.extractall(path=dirpath) + + return dirpath + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.UCIHousing", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def predict_reader(): + """ + It returns just one tuple data to do inference. + + :return: one tuple data + :rtype: tuple + """ + global UCI_TEST_DATA + load_data(paddle.dataset.common.download(URL, 'uci_housing', MD5)) + return (UCI_TEST_DATA[0][:-1], ) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.UCIHousing", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(URL, 'uci_housing', MD5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/voc2012.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/voc2012.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab91db2cc36d85ddad9e760f07c40a9634834d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/voc2012.py @@ -0,0 +1,102 @@ +# 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. +""" +Image dataset for segmentation. +The 2012 dataset contains images from 2008-2011 for which additional +segmentations have been prepared. As in previous years the assignment +to training/test sets has been maintained. The total number of images +with segmentation has been increased from 7,062 to 9,993. +""" + +from __future__ import print_function + +import tarfile +import io +import numpy as np +from paddle.dataset.common import download +import paddle.utils.deprecated as deprecated +from PIL import Image + +__all__ = [] + +VOC_URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/\ +VOCtrainval_11-May-2012.tar' + +VOC_MD5 = '6cd6e144f989b92b3379bac3b3de84fd' +SET_FILE = 'VOCdevkit/VOC2012/ImageSets/Segmentation/{}.txt' +DATA_FILE = 'VOCdevkit/VOC2012/JPEGImages/{}.jpg' +LABEL_FILE = 'VOCdevkit/VOC2012/SegmentationClass/{}.png' + +CACHE_DIR = 'voc2012' + + +def reader_creator(filename, sub_name): + + tarobject = tarfile.open(filename) + name2mem = {} + for ele in tarobject.getmembers(): + name2mem[ele.name] = ele + + def reader(): + set_file = SET_FILE.format(sub_name) + sets = tarobject.extractfile(name2mem[set_file]) + for line in sets: + line = line.strip() + data_file = DATA_FILE.format(line) + label_file = LABEL_FILE.format(line) + data = tarobject.extractfile(name2mem[data_file]).read() + label = tarobject.extractfile(name2mem[label_file]).read() + data = Image.open(io.BytesIO(data)) + label = Image.open(io.BytesIO(label)) + data = np.array(data) + label = np.array(label) + yield data, label + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.VOC2012", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(): + """ + Create a train dataset reader containing 2913 images in HWC order. + """ + return reader_creator(download(VOC_URL, CACHE_DIR, VOC_MD5), 'trainval') + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.VOC2012", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(): + """ + Create a test dataset reader containing 1464 images in HWC order. + """ + return reader_creator(download(VOC_URL, CACHE_DIR, VOC_MD5), 'train') + + +@deprecated( + since="2.0.0", + update_to="paddle.vision.datasets.VOC2012", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def val(): + """ + Create a val dataset reader containing 1449 images in HWC order. + """ + return reader_creator(download(VOC_URL, CACHE_DIR, VOC_MD5), 'val') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt14.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt14.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0a77b4f20d5b1ede263332abe503912c2fb82e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt14.py @@ -0,0 +1,192 @@ +# 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. +""" +WMT14 dataset. +The original WMT14 dataset is too large and a small set of data for set is +provided. This module will download dataset from +http://paddlepaddle.bj.bcebos.com/demo/wmt_shrinked_data/wmt14.tgz and +parse training set and test set into paddle reader creators. + +""" + +from __future__ import print_function + +import six +import tarfile +import gzip + +import paddle.dataset.common +import paddle.compat as cpt +import paddle.utils.deprecated as deprecated + +__all__ = [] + +URL_DEV_TEST = ('http://www-lium.univ-lemans.fr/~schwenk/' + 'cslm_joint_paper/data/dev+test.tgz') +MD5_DEV_TEST = '7d7897317ddd8ba0ae5c5fa7248d3ff5' +# this is a small set of data for test. The original data is too large and +# will be add later. +URL_TRAIN = ('http://paddlemodels.bj.bcebos.com/wmt/wmt14.tgz') +MD5_TRAIN = '0791583d57d5beb693b9414c5b36798c' +# BLEU of this trained model is 26.92 +URL_MODEL = 'http://paddlemodels.bj.bcebos.com/wmt%2Fwmt14.tgz' +MD5_MODEL = '0cb4a5366189b6acba876491c8724fa3' + +START = "" +END = "" +UNK = "" +UNK_IDX = 2 + + +def __read_to_dict(tar_file, dict_size): + + def __to_dict(fd, size): + out_dict = dict() + for line_count, line in enumerate(fd): + if line_count < size: + out_dict[cpt.to_text(line.strip())] = line_count + else: + break + return out_dict + + with tarfile.open(tar_file, mode='r') as f: + names = [ + each_item.name for each_item in f + if each_item.name.endswith("src.dict") + ] + assert len(names) == 1 + src_dict = __to_dict(f.extractfile(names[0]), dict_size) + names = [ + each_item.name for each_item in f + if each_item.name.endswith("trg.dict") + ] + assert len(names) == 1 + trg_dict = __to_dict(f.extractfile(names[0]), dict_size) + return src_dict, trg_dict + + +def reader_creator(tar_file, file_name, dict_size): + + def reader(): + src_dict, trg_dict = __read_to_dict(tar_file, dict_size) + with tarfile.open(tar_file, mode='r') as f: + names = [ + each_item.name for each_item in f + if each_item.name.endswith(file_name) + ] + for name in names: + for line in f.extractfile(name): + line = cpt.to_text(line) + line_split = line.strip().split('\t') + if len(line_split) != 2: + continue + src_seq = line_split[0] # one source sequence + src_words = src_seq.split() + src_ids = [ + src_dict.get(w, UNK_IDX) + for w in [START] + src_words + [END] + ] + + trg_seq = line_split[1] # one target sequence + trg_words = trg_seq.split() + trg_ids = [trg_dict.get(w, UNK_IDX) for w in trg_words] + + # remove sequence whose length > 80 in training mode + if len(src_ids) > 80 or len(trg_ids) > 80: + continue + trg_ids_next = trg_ids + [trg_dict[END]] + trg_ids = [trg_dict[START]] + trg_ids + + yield src_ids, trg_ids, trg_ids_next + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT14", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(dict_size): + """ + WMT14 training set creator. + + It returns a reader creator, each sample in the reader is source language + word ID sequence, target language word ID sequence and next word ID + sequence. + + :return: Training reader creator + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN), + 'train/train', dict_size) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT14", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(dict_size): + """ + WMT14 test set creator. + + It returns a reader creator, each sample in the reader is source language + word ID sequence, target language word ID sequence and next word ID + sequence. + + :return: Test reader creator + :rtype: callable + """ + return reader_creator( + paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN), + 'test/test', dict_size) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT14", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def gen(dict_size): + return reader_creator( + paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN), + 'gen/gen', dict_size) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT14", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def get_dict(dict_size, reverse=True): + # if reverse = False, return dict = {'a':'001', 'b':'002', ...} + # else reverse = true, return dict = {'001':'a', '002':'b', ...} + tar_file = paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN) + src_dict, trg_dict = __read_to_dict(tar_file, dict_size) + if reverse: + src_dict = {v: k for k, v in six.iteritems(src_dict)} + trg_dict = {v: k for k, v in six.iteritems(trg_dict)} + return src_dict, trg_dict + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT14", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + paddle.dataset.common.download(URL_TRAIN, 'wmt14', MD5_TRAIN) + paddle.dataset.common.download(URL_MODEL, 'wmt14', MD5_MODEL) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt16.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt16.py new file mode 100644 index 0000000000000000000000000000000000000000..80e35d9fde952faec779725019b896c3485192ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/dataset/wmt16.py @@ -0,0 +1,344 @@ +# 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. +""" +ACL2016 Multimodal Machine Translation. Please see this website for more +details: http://www.statmt.org/wmt16/multimodal-task.html#task1 + +If you use the dataset created for your task, please cite the following paper: +Multi30K: Multilingual English-German Image Descriptions. + +@article{elliott-EtAl:2016:VL16, + author = {{Elliott}, D. and {Frank}, S. and {Sima"an}, K. and {Specia}, L.}, + title = {Multi30K: Multilingual English-German Image Descriptions}, + booktitle = {Proceedings of the 6th Workshop on Vision and Language}, + year = {2016}, + pages = {70--74}, + year = 2016 +} +""" + +from __future__ import print_function + +import os +import six +import tarfile +import gzip +from collections import defaultdict + +import paddle +import paddle.compat as cpt +import paddle.utils.deprecated as deprecated + +__all__ = [] + +DATA_URL = ("http://paddlemodels.bj.bcebos.com/wmt/wmt16.tar.gz") +DATA_MD5 = "0c38be43600334966403524a40dcd81e" + +TOTAL_EN_WORDS = 11250 +TOTAL_DE_WORDS = 19220 + +START_MARK = "" +END_MARK = "" +UNK_MARK = "" + + +def __build_dict(tar_file, dict_size, save_path, lang): + word_dict = defaultdict(int) + with tarfile.open(tar_file, mode="r") as f: + for line in f.extractfile("wmt16/train"): + line = cpt.to_text(line) + line_split = line.strip().split("\t") + if len(line_split) != 2: continue + sen = line_split[0] if lang == "en" else line_split[1] + for w in sen.split(): + word_dict[w] += 1 + + with open(save_path, "wb") as fout: + fout.write( + cpt.to_bytes("%s\n%s\n%s\n" % (START_MARK, END_MARK, UNK_MARK))) + for idx, word in enumerate( + sorted(six.iteritems(word_dict), + key=lambda x: x[1], + reverse=True)): + if idx + 3 == dict_size: break + fout.write(cpt.to_bytes(word[0])) + fout.write(cpt.to_bytes('\n')) + + +def __load_dict(tar_file, dict_size, lang, reverse=False): + dict_path = os.path.join(paddle.dataset.common.DATA_HOME, + "wmt16/%s_%d.dict" % (lang, dict_size)) + if not os.path.exists(dict_path) or (len(open(dict_path, "rb").readlines()) + != dict_size): + __build_dict(tar_file, dict_size, dict_path, lang) + + word_dict = {} + with open(dict_path, "rb") as fdict: + for idx, line in enumerate(fdict): + if reverse: + word_dict[idx] = cpt.to_text(line.strip()) + else: + word_dict[cpt.to_text(line.strip())] = idx + return word_dict + + +def __get_dict_size(src_dict_size, trg_dict_size, src_lang): + src_dict_size = min( + src_dict_size, (TOTAL_EN_WORDS if src_lang == "en" else TOTAL_DE_WORDS)) + trg_dict_size = min( + trg_dict_size, (TOTAL_DE_WORDS if src_lang == "en" else TOTAL_EN_WORDS)) + return src_dict_size, trg_dict_size + + +def reader_creator(tar_file, file_name, src_dict_size, trg_dict_size, src_lang): + + def reader(): + src_dict = __load_dict(tar_file, src_dict_size, src_lang) + trg_dict = __load_dict(tar_file, trg_dict_size, + ("de" if src_lang == "en" else "en")) + + # the index for start mark, end mark, and unk are the same in source + # language and target language. Here uses the source language + # dictionary to determine their indices. + start_id = src_dict[START_MARK] + end_id = src_dict[END_MARK] + unk_id = src_dict[UNK_MARK] + + src_col = 0 if src_lang == "en" else 1 + trg_col = 1 - src_col + + with tarfile.open(tar_file, mode="r") as f: + for line in f.extractfile(file_name): + line = cpt.to_text(line) + line_split = line.strip().split("\t") + if len(line_split) != 2: + continue + src_words = line_split[src_col].split() + src_ids = [start_id + ] + [src_dict.get(w, unk_id) + for w in src_words] + [end_id] + + trg_words = line_split[trg_col].split() + trg_ids = [trg_dict.get(w, unk_id) for w in trg_words] + + trg_ids_next = trg_ids + [end_id] + trg_ids = [start_id] + trg_ids + + yield src_ids, trg_ids, trg_ids_next + + return reader + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT16", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def train(src_dict_size, trg_dict_size, src_lang="en"): + """ + WMT16 train set reader. + + This function returns the reader for train data. Each sample the reader + returns is made up of three fields: the source language word index sequence, + target language word index sequence and next word index sequence. + + + NOTE: + The original like for training data is: + http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz + + paddle.dataset.wmt16 provides a tokenized version of the original dataset by + using moses's tokenization script: + https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl + + Args: + src_dict_size(int): Size of the source language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + trg_dict_size(int): Size of the target language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + src_lang(string): A string indicating which language is the source + language. Available options are: "en" for English + and "de" for Germany. + + Returns: + callable: The train reader. + """ + + if src_lang not in ["en", "de"]: + raise ValueError("An error language type. Only support: " + "en (for English); de(for Germany).") + src_dict_size, trg_dict_size = __get_dict_size(src_dict_size, trg_dict_size, + src_lang) + + return reader_creator(tar_file=paddle.dataset.common.download( + DATA_URL, "wmt16", DATA_MD5, "wmt16.tar.gz"), + file_name="wmt16/train", + src_dict_size=src_dict_size, + trg_dict_size=trg_dict_size, + src_lang=src_lang) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT16", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def test(src_dict_size, trg_dict_size, src_lang="en"): + """ + WMT16 test set reader. + + This function returns the reader for test data. Each sample the reader + returns is made up of three fields: the source language word index sequence, + target language word index sequence and next word index sequence. + + NOTE: + The original like for test data is: + http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/mmt16_task1_test.tar.gz + + paddle.dataset.wmt16 provides a tokenized version of the original dataset by + using moses's tokenization script: + https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl + + Args: + src_dict_size(int): Size of the source language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + trg_dict_size(int): Size of the target language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + src_lang(string): A string indicating which language is the source + language. Available options are: "en" for English + and "de" for Germany. + + Returns: + callable: The test reader. + """ + + if src_lang not in ["en", "de"]: + raise ValueError("An error language type. " + "Only support: en (for English); de(for Germany).") + + src_dict_size, trg_dict_size = __get_dict_size(src_dict_size, trg_dict_size, + src_lang) + + return reader_creator(tar_file=paddle.dataset.common.download( + DATA_URL, "wmt16", DATA_MD5, "wmt16.tar.gz"), + file_name="wmt16/test", + src_dict_size=src_dict_size, + trg_dict_size=trg_dict_size, + src_lang=src_lang) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT16", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def validation(src_dict_size, trg_dict_size, src_lang="en"): + """ + WMT16 validation set reader. + + This function returns the reader for validation data. Each sample the reader + returns is made up of three fields: the source language word index sequence, + target language word index sequence and next word index sequence. + + NOTE: + The original like for validation data is: + http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz + + paddle.dataset.wmt16 provides a tokenized version of the original dataset by + using moses's tokenization script: + https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl + + Args: + src_dict_size(int): Size of the source language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + trg_dict_size(int): Size of the target language dictionary. Three + special tokens will be added into the dictionary: + for start mark, for end mark, and for + unknown word. + src_lang(string): A string indicating which language is the source + language. Available options are: "en" for English + and "de" for Germany. + + Returns: + callable: The validation reader. + """ + if src_lang not in ["en", "de"]: + raise ValueError("An error language type. " + "Only support: en (for English); de(for Germany).") + src_dict_size, trg_dict_size = __get_dict_size(src_dict_size, trg_dict_size, + src_lang) + + return reader_creator(tar_file=paddle.dataset.common.download( + DATA_URL, "wmt16", DATA_MD5, "wmt16.tar.gz"), + file_name="wmt16/val", + src_dict_size=src_dict_size, + trg_dict_size=trg_dict_size, + src_lang=src_lang) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT16", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def get_dict(lang, dict_size, reverse=False): + """ + return the word dictionary for the specified language. + + Args: + lang(string): A string indicating which language is the source + language. Available options are: "en" for English + and "de" for Germany. + dict_size(int): Size of the specified language dictionary. + reverse(bool): If reverse is set to False, the returned python + dictionary will use word as key and use index as value. + If reverse is set to True, the returned python + dictionary will use index as key and word as value. + + Returns: + dict: The word dictionary for the specific language. + """ + + if lang == "en": dict_size = min(dict_size, TOTAL_EN_WORDS) + else: dict_size = min(dict_size, TOTAL_DE_WORDS) + + dict_path = os.path.join(paddle.dataset.common.DATA_HOME, + "wmt16/%s_%d.dict" % (lang, dict_size)) + assert os.path.exists(dict_path), "Word dictionary does not exist. " + "Please invoke paddle.dataset.wmt16.train/test/validation first " + "to build the dictionary." + tar_file = os.path.join(paddle.dataset.common.DATA_HOME, "wmt16.tar.gz") + return __load_dict(tar_file, dict_size, lang, reverse) + + +@deprecated( + since="2.0.0", + update_to="paddle.text.datasets.WMT16", + level=1, + reason="Please use new dataset API which supports paddle.io.DataLoader") +def fetch(): + """download the entire dataset. + """ + paddle.v4.dataset.common.download(DATA_URL, "wmt16", DATA_MD5, + "wmt16.tar.gz") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa959150cec3c5a0d8e977e69b123d4fcd22df75 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/__init__.py @@ -0,0 +1,462 @@ +# Copyright (c) 2021 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. + +# TODO: define the functions to manipulate devices +import re +import os +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.fluid.framework import is_compiled_with_cinn # noqa: F401 +from paddle.fluid.framework import is_compiled_with_cuda # noqa: F401 +from paddle.fluid.framework import is_compiled_with_rocm # noqa: F401 +from . import cuda + +__all__ = [ # noqa + 'get_cudnn_version', + 'set_device', + 'get_device', + 'XPUPlace', + 'IPUPlace', + 'MLUPlace', + 'is_compiled_with_xpu', + 'is_compiled_with_ipu', + 'is_compiled_with_cinn', + 'is_compiled_with_cuda', + 'is_compiled_with_rocm', + 'is_compiled_with_npu', + 'is_compiled_with_mlu', + 'get_all_device_type', + 'get_all_custom_device_type', + 'get_available_device', + 'get_available_custom_device', +] + +_cudnn_version = None + + +# TODO: WITH_ASCEND_CL may changed to WITH_NPU or others in the future +# for consistent. +def is_compiled_with_npu(): + """ + Whether paddle was built with WITH_ASCEND_CL=ON to support Ascend NPU. + + Returns (bool): `True` if NPU is supported, otherwise `False`. + + Examples: + .. code-block:: python + + import paddle + support_npu = paddle.device.is_compiled_with_npu() + """ + return core.is_compiled_with_npu() + + +def is_compiled_with_ipu(): + """ + Whether paddle was built with WITH_IPU=ON to support Graphcore IPU. + + Returns (bool): `True` if IPU is supported, otherwise `False`. + + Examples: + .. code-block:: python + + import paddle + support_ipu = paddle.is_compiled_with_ipu() + """ + return core.is_compiled_with_ipu() + + +def IPUPlace(): + """ + Return a Graphcore IPU Place + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + place = paddle.device.IPUPlace() + """ + return core.IPUPlace() + + +def is_compiled_with_xpu(): + """ + Whether paddle was built with WITH_XPU=ON to support Baidu Kunlun + + Returns (bool): whether paddle was built with WITH_XPU=ON + + Examples: + .. code-block:: python + + import paddle + support_xpu = paddle.device.is_compiled_with_xpu() + """ + return core.is_compiled_with_xpu() + + +def XPUPlace(dev_id): + """ + Return a Baidu Kunlun Place + + Parameters: + dev_id(int): Baidu Kunlun device id + + Examples: + .. code-block:: python + + # required: xpu + + import paddle + place = paddle.device.XPUPlace(0) + """ + return core.XPUPlace(dev_id) + + +def is_compiled_with_mlu(): + """ + Whether paddle was built with WITH_MLU=ON to support Cambricon MLU + + Returns (bool): whether paddle was built with WITH_MLU=ON + + Examples: + .. code-block:: python + + # required: mlu + + import paddle + support_mlu = paddle.device.is_compiled_with_mlu() + """ + return core.is_compiled_with_mlu() + + +def MLUPlace(dev_id): + """ + Return a Cambricon MLU Place + + Parameters: + dev_id(int): MLU device id + + Examples: + .. code-block:: python + + # required: mlu + + import paddle + place = paddle.device.MLUPlace(0) + """ + return core.MLUPlace(dev_id) + + +def get_cudnn_version(): + """ + This funciton return the version of cudnn. the retuen value is int which represents the + cudnn version. For example, if it return 7600, it represents the version of cudnn is 7.6. + + Returns: + int: A int value which represents the cudnn version. If cudnn version is not installed, it return None. + + Examples: + .. code-block:: python + + import paddle + + cudnn_version = paddle.device.get_cudnn_version() + + + + """ + global _cudnn_version + if not core.is_compiled_with_cuda(): + return None + if _cudnn_version is None: + cudnn_version = int(core.cudnn_version()) + _cudnn_version = cudnn_version + if _cudnn_version < 0: + return None + else: + return cudnn_version + else: + return _cudnn_version + + +def _convert_to_place(device): + lower_device = device.lower() + if lower_device == 'cpu': + place = core.CPUPlace() + elif lower_device == 'gpu': + if not core.is_compiled_with_cuda(): + raise ValueError("The device should not be 'gpu', " + "since PaddlePaddle is not compiled with CUDA") + place = core.CUDAPlace(ParallelEnv().dev_id) + elif lower_device == 'xpu': + if not core.is_compiled_with_xpu(): + raise ValueError("The device should not be 'xpu', " + "since PaddlePaddle is not compiled with XPU") + selected_xpus = os.getenv("FLAGS_selected_xpus", "0").split(",") + device_id = int(selected_xpus[0]) + place = core.XPUPlace(device_id) + elif lower_device == 'npu': + if not core.is_compiled_with_npu(): + raise ValueError("The device should not be 'npu', " + "since PaddlePaddle is not compiled with NPU") + selected_npus = os.getenv("FLAGS_selected_npus", "0").split(",") + device_id = int(selected_npus[0]) + place = core.NPUPlace(device_id) + elif lower_device == 'ipu': + if not core.is_compiled_with_ipu(): + raise ValueError( + "The device should not be 'ipu', " \ + "since PaddlePaddle is not compiled with IPU") + place = core.IPUPlace() + elif lower_device == 'mlu': + if not core.is_compiled_with_mlu(): + raise ValueError("The device should not be 'mlu', " + "since PaddlePaddle is not compiled with MLU") + selected_mlus = os.getenv("FLAGS_selected_mlus", "0").split(",") + device_id = int(selected_mlus[0]) + place = core.MLUPlace(device_id) + elif device in core.get_all_custom_device_type(): + selected_devices = os.getenv("FLAGS_selected_{}s".format(device), + "0").split(",") + device_id = int(selected_devices[0]) + place = core.CustomPlace(device, device_id) + else: + avaliable_gpu_device = re.match(r'gpu:\d+', lower_device) + avaliable_xpu_device = re.match(r'xpu:\d+', lower_device) + avaliable_npu_device = re.match(r'npu:\d+', lower_device) + avaliable_mlu_device = re.match(r'mlu:\d+', lower_device) + if not avaliable_gpu_device and not avaliable_xpu_device and not avaliable_npu_device and not avaliable_mlu_device: + device_info_list = device.split(':', 1) + device_type = device_info_list[0] + if device_type in core.get_all_custom_device_type(): + device_id = device_info_list[1] + device_id = int(device_id) + place = core.CustomPlace(device_type, device_id) + else: + raise ValueError( + "The device must be a string which is like 'cpu', {}". + format(', '.join("'{}', '{}:x'".format(x, x) + for x in ['gpu', 'xpu', 'npu', 'mlu'] + + core.get_all_custom_device_type()))) + if avaliable_gpu_device: + if not core.is_compiled_with_cuda(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with CUDA".format(avaliable_gpu_device)) + device_info_list = device.split(':', 1) + device_id = device_info_list[1] + device_id = int(device_id) + place = core.CUDAPlace(device_id) + if avaliable_xpu_device: + if not core.is_compiled_with_xpu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with XPU".format(avaliable_xpu_device)) + device_info_list = device.split(':', 1) + device_id = device_info_list[1] + device_id = int(device_id) + place = core.XPUPlace(device_id) + if avaliable_npu_device: + if not core.is_compiled_with_npu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with NPU".format(avaliable_npu_device)) + device_info_list = device.split(':', 1) + device_id = device_info_list[1] + device_id = int(device_id) + place = core.NPUPlace(device_id) + if avaliable_mlu_device: + if not core.is_compiled_with_mlu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with mlu".format(avaliable_mlu_device)) + device_info_list = device.split(':', 1) + device_id = device_info_list[1] + device_id = int(device_id) + place = core.MLUPlace(device_id) + return place + + +def set_device(device): + """ + Paddle supports running calculations on various types of devices, including CPU, GPU, XPU, NPU, MLU and IPU. + They are represented by string identifiers. This function can specify the global device + which the OP will run. + + Parameters: + device(str): This parameter determines the specific running device. + It can be ``cpu``, ``gpu``, ``xpu``, ``npu``, ``mlu``, ``gpu:x``, ``xpu:x``, ``npu:x``, ``mlu:x`` and ``ipu``, + where ``x`` is the index of the GPUs, XPUs, NPUs or MLUs. + + Examples: + + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + x1 = paddle.ones(name='x1', shape=[1, 2], dtype='int32') + x2 = paddle.zeros(name='x2', shape=[1, 2], dtype='int32') + data = paddle.stack([x1,x2], axis=1) + """ + place = _convert_to_place(device) + framework._set_expected_place(place) + return place + + +def get_device(): + """ + This funciton can get the current global device of the program is running. + It's a string which is like 'cpu', 'gpu:x', 'xpu:x', 'mlu:x' and 'npu:x'. if the global device is not + set, it will return a string which is 'gpu:x' when cuda is avaliable or it + will return a string which is 'cpu' when cuda is not avaliable. + + Examples: + + .. code-block:: python + + import paddle + device = paddle.device.get_device() + + """ + device = '' + place = framework._current_expected_place() + if isinstance(place, core.CPUPlace): + device = 'cpu' + elif isinstance(place, core.CUDAPlace): + device_id = place.get_device_id() + device = 'gpu:' + str(device_id) + elif isinstance(place, core.XPUPlace): + device_id = place.get_device_id() + device = 'xpu:' + str(device_id) + elif isinstance(place, core.NPUPlace): + device_id = place.get_device_id() + device = 'npu:' + str(device_id) + elif isinstance(place, core.IPUPlace): + num_devices = core.get_ipu_device_count() + device = "ipus:{{0-{}}}".format(num_devices - 1) + elif isinstance(place, core.MLUPlace): + device_id = place.get_device_id() + device = 'mlu:' + str(device_id) + elif isinstance(place, core.CustomPlace): + device_id = place.get_device_id() + device_type = place.get_device_type() + device = device_type + ':' + str(device_id) + else: + raise ValueError("The device specification {} is invalid".format(place)) + + return device + + +def get_all_device_type(): + """ + Get all available device types. + + Returns: + A list of all available device types. + + Examples: + .. code-block:: python + + import paddle + paddle.device.get_all_device_type() + + # Case 1: paddlepaddle-cpu package installed, and no custom device registerd. + # Output: ['cpu'] + + # Case 2: paddlepaddle-gpu package installed, and no custom device registerd. + # Output: ['cpu', 'gpu'] + + # Case 3: paddlepaddle-cpu package installed, and custom deivce 'CustomCPU' is registerd. + # Output: ['cpu', 'CustomCPU'] + + # Case 4: paddlepaddle-gpu package installed, and custom deivce 'CustomCPU' and 'CustomGPU' is registerd. + # Output: ['cpu', 'gpu', 'CustomCPU', 'CustomGPU'] + """ + return core.get_all_device_type() + + +def get_all_custom_device_type(): + """ + Get all available custom device types. + + Returns: + A list of all available custom device types. + + Examples: + .. code-block:: python + + import paddle + paddle.device.get_all_custom_device_type() + + # Case 1: paddlepaddle-gpu package installed, and no custom device registerd. + # Output: None + + # Case 2: paddlepaddle-gpu package installed, and custom deivce 'CustomCPU' and 'CustomGPU' is registerd. + # Output: ['CustomCPU', 'CustomGPU'] + """ + return core.get_all_custom_device_type() + + +def get_available_device(): + """ + Get all available devices. + + Returns: + A list of all available devices. + + Examples: + .. code-block:: python + + import paddle + paddle.device.get_available_device() + + # Case 1: paddlepaddle-cpu package installed, and no custom device registerd. + # Output: ['cpu'] + + # Case 2: paddlepaddle-gpu package installed, and no custom device registerd. + # Output: ['cpu', 'gpu:0', 'gpu:1'] + + # Case 3: paddlepaddle-cpu package installed, and custom deivce 'CustomCPU' is registerd. + # Output: ['cpu', 'CustomCPU'] + + # Case 4: paddlepaddle-gpu package installed, and custom deivce 'CustomCPU' and 'CustomGPU' is registerd. + # Output: ['cpu', 'gpu:0', 'gpu:1', 'CustomCPU', 'CustomGPU:0', 'CustomGPU:1'] + """ + return core.get_available_device() + + +def get_available_custom_device(): + """ + Get all available custom devices. + + Returns: + A list of all available custom devices. + + Examples: + .. code-block:: python + + import paddle + paddle.device.get_available_custom_device() + + # Case 1: paddlepaddle-gpu package installed, and no custom device registerd. + # Output: None + + # Case 2: paddlepaddle-gpu package installed, and custom deivce 'CustomCPU' and 'CustomGPU' is registerd. + # Output: ['CustomCPU', 'CustomGPU:0', 'CustomGPU:1'] + """ + return core.get_available_custom_device() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..316f9de61226543a7a9b8b50b92fbbff64f7b253 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/__init__.py @@ -0,0 +1,518 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.fluid import core +from paddle.fluid.wrapped_decorator import signature_safe_contextmanager + +from .streams import Stream # noqa: F401 +from .streams import Event # noqa: F401 + +__all__ = [ + 'Stream', + 'Event', + 'current_stream', + 'synchronize', + 'device_count', + 'empty_cache', + 'max_memory_allocated', + 'max_memory_reserved', + 'memory_allocated', + 'memory_reserved', + 'stream_guard', + 'get_device_properties', + 'get_device_name', + 'get_device_capability', +] + + +def current_stream(device=None): + ''' + Return the current CUDA stream by the device. + + Parameters: + device(paddle.CUDAPlace()|int, optional): The device or the ID of the device which want to get stream from. + If device is None, the device is the current device. Default: None. + + Returns: + CUDAStream: the stream to the device. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + s1 = paddle.device.cuda.current_stream() + + s2 = paddle.device.cuda.current_stream(0) + + s3 = paddle.device.cuda.current_stream(paddle.CUDAPlace(0)) + + ''' + + device_id = -1 + + if device is not None: + if isinstance(device, int): + device_id = device + elif isinstance(device, core.CUDAPlace): + device_id = device.get_device_id() + else: + raise ValueError("device type must be int or paddle.CUDAPlace") + + return core._get_current_stream(device_id) + + +def synchronize(device=None): + ''' + Wait for the compute on the given CUDA device to finish. + + Parameters: + device(paddle.CUDAPlace()|int, optional): The device or the ID of the device. + If device is None, the device is the current device. Default: None. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + paddle.device.cuda.synchronize() + paddle.device.cuda.synchronize(0) + paddle.device.cuda.synchronize(paddle.CUDAPlace(0)) + + ''' + + device_id = -1 + + if device is not None: + if isinstance(device, int): + device_id = device + elif isinstance(device, core.CUDAPlace): + device_id = device.get_device_id() + else: + raise ValueError("device type must be int or paddle.CUDAPlace") + + return core._device_synchronize(device_id) + + +def device_count(): + ''' + Return the number of GPUs available. + + Returns: + int: the number of GPUs available. + + Examples: + .. code-block:: python + + import paddle + + paddle.device.cuda.device_count() + + ''' + + num_gpus = ( + core.get_cuda_device_count() + if hasattr(core, 'get_cuda_device_count') + else 0 + ) + + return num_gpus + + +def empty_cache(): + ''' + Releases idle cached memory held by the allocator so that those can be used in other GPU + application and visible in `nvidia-smi`. In most cases you don't need to use this function, + Paddle does not release the memory back to the OS when you remove Tensors on the GPU, + Because it keeps gpu memory in a pool so that next allocations can be done much faster. + + Examples: + .. code-block:: python + + import paddle + + # required: gpu + paddle.set_device("gpu") + tensor = paddle.randn([512, 512, 512], "float") + del tensor + paddle.device.cuda.empty_cache() + ''' + + if core.is_compiled_with_cuda(): + core.cuda_empty_cache() + + +def extract_cuda_device_id(device, op_name): + ''' + Return the id of the given cuda device. It is just a utility that will not be exposed to users. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x'. + Default: None. + + Return: + int: The id of the given device. If device is None, return the id of current device. + ''' + if device is None: + return core.get_cuda_current_device_id() + + if isinstance(device, int): + device_id = device + elif isinstance(device, core.CUDAPlace): + device_id = device.get_device_id() + elif isinstance(device, str): + if device.startswith('gpu:'): + device_id = int(device[4:]) + else: + raise ValueError( + "The current string {} is not expected. Because {} only support string which is like 'gpu:x'. " + "Please input appropriate string again!".format(device, op_name) + ) + else: + raise ValueError( + "The device type {} is not expected. Because {} only support int, str or paddle.CUDAPlace. " + "Please input appropriate device again!".format(device, op_name) + ) + + assert ( + device_id >= 0 + ), f"The device id must be not less than 0, but got id = {device_id}." + assert ( + device_id < device_count() + ), f"The device id {device_id} exceeds gpu card number {device_count()}" + + return device_id + + +def max_memory_allocated(device=None): + ''' + Return the peak size of gpu memory that is allocated to tensor of the given device. + + Note: + The size of GPU memory allocated to tensor is 256-byte aligned in Paddle, which may larger than the memory size that tensor actually need. + For instance, a float32 tensor with shape [1] in GPU will take up 256 bytes memory, even though storing a float32 data requires only 4 bytes. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x'. If device is None, the device is the current device. + Default: None. + + Return: + int: The peak size of gpu memory that is allocated to tensor of the given device, in bytes. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + max_memory_allocated_size = paddle.device.cuda.max_memory_allocated(paddle.CUDAPlace(0)) + max_memory_allocated_size = paddle.device.cuda.max_memory_allocated(0) + max_memory_allocated_size = paddle.device.cuda.max_memory_allocated("gpu:0") + ''' + name = "paddle.device.cuda.max_memory_allocated" + if not core.is_compiled_with_cuda(): + raise ValueError( + f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API." + ) + device_id = extract_cuda_device_id(device, op_name=name) + return core.device_memory_stat_peak_value("Allocated", device_id) + + +def max_memory_reserved(device=None): + ''' + Return the peak size of GPU memory that is held by the allocator of the given device. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x'. If device is None, the device is the current device. + Default: None. + + Return: + int: The peak size of GPU memory that is held by the allocator of the given device, in bytes. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + max_memory_reserved_size = paddle.device.cuda.max_memory_reserved(paddle.CUDAPlace(0)) + max_memory_reserved_size = paddle.device.cuda.max_memory_reserved(0) + max_memory_reserved_size = paddle.device.cuda.max_memory_reserved("gpu:0") + ''' + name = "paddle.device.cuda.max_memory_reserved" + if not core.is_compiled_with_cuda(): + raise ValueError( + f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API." + ) + device_id = extract_cuda_device_id(device, op_name=name) + return core.device_memory_stat_peak_value("Reserved", device_id) + + +def memory_allocated(device=None): + ''' + Return the current size of gpu memory that is allocated to tensor of the given device. + + Note: + The size of GPU memory allocated to tensor is 256-byte aligned in Paddle, which may be larger than the memory size that tensor actually need. + For instance, a float32 tensor with shape [1] in GPU will take up 256 bytes memory, even though storing a float32 data requires only 4 bytes. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x'. If device is None, the device is the current device. + Default: None. + + Return: + int: The current size of gpu memory that is allocated to tensor of the given device, in bytes. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + memory_allocated_size = paddle.device.cuda.memory_allocated(paddle.CUDAPlace(0)) + memory_allocated_size = paddle.device.cuda.memory_allocated(0) + memory_allocated_size = paddle.device.cuda.memory_allocated("gpu:0") + ''' + name = "paddle.device.cuda.memory_allocated" + if not core.is_compiled_with_cuda(): + raise ValueError( + f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API." + ) + device_id = extract_cuda_device_id(device, op_name=name) + return core.device_memory_stat_current_value("Allocated", device_id) + + +def memory_reserved(device=None): + ''' + Return the current size of GPU memory that is held by the allocator of the given device. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x'. If device is None, the device is the current device. + Default: None. + + Return: + int: The current size of GPU memory that is held by the allocator of the given device, in bytes. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + memory_reserved_size = paddle.device.cuda.memory_reserved(paddle.CUDAPlace(0)) + memory_reserved_size = paddle.device.cuda.memory_reserved(0) + memory_reserved_size = paddle.device.cuda.memory_reserved("gpu:0") + ''' + name = "paddle.device.cuda.memory_reserved" + if not core.is_compiled_with_cuda(): + raise ValueError( + f"The API {name} is not supported in CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support to call this API." + ) + device_id = extract_cuda_device_id(device, op_name=name) + return core.device_memory_stat_current_value("Reserved", device_id) + + +def _set_current_stream(stream): + ''' + Set the current stream. + + Parameters: + stream(paddle.device.cuda.Stream): The selected stream. + + Returns: + CUDAStream: The previous stream. + + ''' + + if not isinstance(stream, paddle.device.cuda.Stream): + raise TypeError("stream type should be paddle.device.cuda.Stream") + + cur_stream = current_stream() + if id(stream) == id(cur_stream): + return stream + return core._set_current_stream(stream) + + +@signature_safe_contextmanager +def stream_guard(stream): + ''' + **Notes**: + **This API only supports dygraph mode currently.** + + A context manager that specifies the current stream context by the given stream. + + Parameters: + stream(paddle.device.cuda.Stream): the selected stream. If stream is None, just yield. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + s = paddle.device.cuda.Stream() + data1 = paddle.ones(shape=[20]) + data2 = paddle.ones(shape=[20]) + with paddle.device.cuda.stream_guard(s): + data3 = data1 + data2 + + ''' + + if stream is not None and not isinstance(stream, paddle.device.cuda.Stream): + raise TypeError("stream type should be paddle.device.cuda.Stream") + + cur_stream = current_stream() + if stream is None or id(stream) == id(cur_stream): + yield + else: + pre_stream = _set_current_stream(stream) + try: + yield + finally: + stream = _set_current_stream(pre_stream) + + +def get_device_properties(device=None): + ''' + Return the properties of given device. + + Args: + device(paddle.CUDAPlace or int or str): The device, the id of the device or + the string name of device like 'gpu:x' which to get the properties of the + device from. If device is None, the device is the current device. + Default: None. + + Returns: + _gpuDeviceProperties: The properties of the device which include ASCII string + identifying device, major compute capability, minor compute capability, global + memory available and the number of multiprocessors on the device. + + Examples: + + .. code-block:: python + + # required: gpu + + import paddle + paddle.device.cuda.get_device_properties() + # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108) + + paddle.device.cuda.get_device_properties(0) + # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108) + + paddle.device.cuda.get_device_properties('gpu:0') + # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108) + + paddle.device.cuda.get_device_properties(paddle.CUDAPlace(0)) + # _gpuDeviceProperties(name='A100-SXM4-40GB', major=8, minor=0, total_memory=40536MB, multi_processor_count=108) + + ''' + + if not core.is_compiled_with_cuda(): + raise ValueError( + "The API paddle.device.cuda.get_device_properties is not supported in " + "CPU-only PaddlePaddle. Please reinstall PaddlePaddle with GPU support " + "to call this API." + ) + + if device is not None: + if isinstance(device, int): + device_id = device + elif isinstance(device, core.CUDAPlace): + device_id = device.get_device_id() + elif isinstance(device, str): + if device.startswith('gpu:'): + device_id = int(device[4:]) + else: + raise ValueError( + "The current string {} is not expected. Because paddle.device." + "cuda.get_device_properties only support string which is like 'gpu:x'. " + "Please input appropriate string again!".format(device) + ) + else: + raise ValueError( + "The device type {} is not expected. Because paddle.device.cuda." + "get_device_properties only support int, str or paddle.CUDAPlace. " + "Please input appropriate device again!".format(device) + ) + else: + device_id = -1 + + return core.get_device_properties(device_id) + + +def get_device_name(device=None): + ''' + Return the name of the device which is got from CUDA function `cudaDeviceProp `_. + + Parameters: + device(paddle.CUDAPlace|int, optional): The device or the ID of the device. If device is None (default), the device is the current device. + + Returns: + str: The name of the device. + + Examples: + + .. code-block:: python + + # required: gpu + + import paddle + + paddle.device.cuda.get_device_name() + + paddle.device.cuda.get_device_name(0) + + paddle.device.cuda.get_device_name(paddle.CUDAPlace(0)) + + ''' + + return get_device_properties(device).name + + +def get_device_capability(device=None): + ''' + Return the major and minor revision numbers defining the device's compute capability which are got from CUDA function `cudaDeviceProp `_. + + Parameters: + device(paddle.CUDAPlace|int, optional): The device or the ID of the device. If device is None (default), the device is the current device. + + Returns: + tuple(int,int): the major and minor revision numbers defining the device's compute capability. + + Examples: + + .. code-block:: python + + # required: gpu + + import paddle + + paddle.device.cuda.get_device_capability() + + paddle.device.cuda.get_device_capability(0) + + paddle.device.cuda.get_device_capability(paddle.CUDAPlace(0)) + + ''' + prop = get_device_properties(device) + return prop.major, prop.minor diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/graphs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..44ce2c5eea7d04f10ce445197ea7c626891b8323 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/graphs.py @@ -0,0 +1,442 @@ +# Copyright (c) 2021 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. + +import os +import paddle +from paddle.fluid import core +from paddle.fluid.layers.utils import _hash_with_id +from paddle.fluid.core import is_compiled_with_cuda, is_compiled_with_rocm, CUDAPlace +import warnings + +if is_compiled_with_cuda() and not is_compiled_with_rocm(): + from paddle.fluid.core import CUDAGraph as CoreCUDAGraph + + def is_cuda_graph_supported(): + return True +else: + CoreCUDAGraph = None + + def is_cuda_graph_supported(): + return False + + +ALL_MODES = ["global", "thread_local", "relaxed"] +cuda_graph_id = 0 + + +class CUDAGraph: + + def __init__(self, place=None, mode="thread_local"): + assert CoreCUDAGraph is not None, "CUDA Graph is only supported on PaddlePaddle compiled with NVIDIA GPU." + + self._graph = None + if place is None: + device_id = int(os.environ.get('FLAGS_selected_gpus', 0)) + place = CUDAPlace(device_id) + self._place = place + assert mode in ALL_MODES + self._mode = ALL_MODES.index(mode) + + def capture_begin(self): + CoreCUDAGraph.begin_capture(self._place, self._mode) + + def capture_end(self): + self._graph = CoreCUDAGraph.end_capture() + + def replay(self): + self._graph.replay() + + def reset(self): + self._graph.reset() + + def print_to_dot_files(self, dirname, flags=None): + if not isinstance(dirname, (str, bytes)): + dirname = dirname.name + os.makedirs(name=dirname, exist_ok=True) + assert os.path.isdir( + dirname), "The dirname {} should be a directory".format(dirname) + if flags is None: + flags = 2047 # only all information. It can be any integer inside [1, 2048) + self._graph.print_to_dot_files(dirname, flags) + + +def wrap_cuda_graph(function, mode="thread_local", memory_pool="default"): + assert mode in ALL_MODES + if not paddle.in_dynamic_mode(): + # static mode + from paddle.fluid.framework import _cuda_graph_guard + global cuda_graph_id + graph_id = str(cuda_graph_id) + cuda_graph_id += 1 + if memory_pool == 'default': + memory_pool_id = 0 + elif memory_pool == 'new': + memory_pool_id = CoreCUDAGraph.gen_new_memory_pool_id() + else: + raise ValueError( + "memory_pool should be one of default or new under static mode, but got", + memory_pool) + return _cuda_graph_guard( + mode + ';' + str(memory_pool_id) + ';' + + graph_id)(lambda *args, **kwargs: function(*args, **kwargs)) + + from paddle.jit import to_static + from paddle.nn import Layer + new_function = to_static(function) + if isinstance(function, Layer): + mock_func = new_function.forward + else: + mock_func = new_function + mock_func._cuda_graph_capture_mode = mode + if memory_pool == "default": + mock_func._cuda_graph_pool_id = 0 + elif memory_pool == "new": + mock_func._cuda_graph_pool_id = CoreCUDAGraph.gen_new_memory_pool_id() + else: + if isinstance(memory_pool, Layer): + mock_func._cuda_graph_pool_id = memory_pool.forward._cuda_graph_pool_id + else: + mock_func._cuda_graph_pool_id = memory_pool._cuda_graph_pool_id + return new_function + + +def copy_var_desc(dst, src): + """ + copy var desc from src to dst + + :param dst: framework.VarDesc(cpp), dst var desc, cpp VarDesc instance + :param src: framework.VarDesc(cpp), src var desc, cpp VarDesc instance + :return: no return + """ + dst.set_shape(src.shape) + dst.set_dtype(src.dtype) + dst.set_lod_level(src.lod_level) + dst.set_type(src.type) + dst.set_persistable(src.persistable) + dst.set_is_parameter(src.is_parameter) + dst.set_stop_gradient(src.stop_gradient) + + +def all_inputs_of_later_op(block, begin_idx): + """ + find all inputs of ops after an idx, used to determine the logical output of a cuda graph section + + :param block: framework.Block, the original block + :param begin_idx: int, from which idx (not include) to find the later ins + :return: a list of inputs names for all ops behind begin_idx + """ + ins = [] + for idx, op in enumerate(block.ops): + if idx <= begin_idx: + continue + for in_name in op.input_arg_names: + ins.append(in_name) + return list(set(ins)) + + +def construct_program_and_find_ins_outs(section, origin_program, section_idx): + """ + 1. Construct a new program for corresponding section + 2. Find all the logical inputs and outputs of a program section + + :param section: list, one cuda graph section, list of ops + :param origin_program: framework.Program, origin program + :param section_idx: list, the section ops' idx corresponding to the cuda graph section, a list of idx + :return: a new program for the cuda graph section + the logical ins and outs of the cuda graph section + """ + program = paddle.static.Program() + block = program.global_block() + origin_block = origin_program.global_block() + ins = [] + outs = [] + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + later_ins = all_inputs_of_later_op(origin_block, section_idx[-1]) + + for op in section: + for in_name in op.input_arg_names: + var = origin_block.var(in_name) + new_var_desc = block.desc.var(var.name.encode("ascii")) + copy_var_desc(new_var_desc, var) + if outs.count(in_name) == 0 and ins.count(in_name) == 0: + # This in var is generated from op outside this section + # Only record once for same input + ins.append(in_name) + elif later_ins.count(in_name) == 0 and outs.count(in_name) > 0: + # this is var is generated from op inside this section, and only will be used inside this section + outs.remove(in_name) + for out_name in op.output_arg_names: + var = origin_block.var(out_name) + new_var_desc = block.desc.var(var.name.encode("ascii")) + copy_var_desc(new_var_desc, var) + # for every output, we add it to the section's outs + if outs.count(out_name) == 0: + # Only record one out var even if it will be generated by multi ops. + # For scenario like this: + # A = op1(a) + # A = op2(b) + # B = op3(A) + outs.append(out_name) + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(op.desc) + new_op_desc._set_attr(op_role_attr_name, op.attr(op_role_attr_name)) + + program._sync_with_cpp() + + return program, [ins, outs] + + +def get_cuda_graph_sections(program): + """ + get all sections that should run under cuda graph and the corresponding idx + + :param program: framework.Program, the original program + :return: A list of cuda graph sections and the corresponding ops' idx in the block. + The program is under is test or not. + """ + block = program.global_block() + cuda_graph_sections = [] # record all ops in every cuda graph sections + sections_idx = [] # idx of all ops in every cuda graph sections + is_test = False # will be set to True is any op's 'is_test' attr is True + + # ops and it's idx between cuda graph wrapped op, may belong to a section + internal_section = [] + internal_idx = [] + + current_section = [] # current recording cuda graph sections + current_idx = [] # current recording cuda graph ops' idx + current_cuda_graph_id = -1 # current recording cuda graph id + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + loss_op_role = int(core.op_proto_and_checker_maker.OpRole.Loss) + backward_op_role = int(core.op_proto_and_checker_maker.OpRole.Backward) + loss_grad_op_role = loss_op_role | backward_op_role + + for idx, op in enumerate(block.ops): + if op.type == 'conditional_block' or op.type == 'while': + assert op._cuda_graph_attr is None, "Cuda graph not support conditional block op and while op." + if op.has_attr('is_test') and op.attr('is_test'): + is_test = True + # find cuda graph sections + if op._cuda_graph_attr is not None: + assert isinstance(op._cuda_graph_attr, + str), "cuda_graph_attr should be a str" + cuda_graph_attrs = op._cuda_graph_attr.split(';') + assert len(cuda_graph_attrs) == 3, "cuda graph attr should have three fields: " \ + "cuda graph mode, cuda graph memory pool id, cuda graph id" + local_cuda_graph_id = int(cuda_graph_attrs[2]) + if local_cuda_graph_id == current_cuda_graph_id: + if len(internal_section) > 0: + assert len(internal_section) == len( + internal_idx + ), "len of internal section should be equal with len of internal idx" + for internal_op in internal_section: + loss_related = (int(internal_op.attr(op_role_attr_name)) + == loss_op_role) or int( + (internal_op.attr(op_role_attr_name) + ) == loss_grad_op_role) + sub_block_related = (op.type == 'conditional_block' + or op.type == 'while') + if loss_related or sub_block_related: + # If loss_related is True + # The internal section contains loss related ops, + # although these ops are between two cuda graph sections with same graph id, + # they belong to none of these two sections. + # The loss related op should be wrapped by user explicitly. + + # If sub_block_related is True + # The internal section contains while op or conditional block op. + # These two ops are not supported by cuda graph. Won't extend the section. + internal_section = [] + internal_idx = [] + # Beside clear the internal section, a new cuda graph section should be recorded + assert len(current_section) == len(current_idx), \ + "num of section's op is not equal with the idx" + if len(current_section) > 0: + # store previous section + cuda_graph_sections.append(current_section) + sections_idx.append(current_idx) + current_section = [] + current_idx = [] + break + # some ops inserted by some optimizer, should be added to current section + for i in range(len(internal_section)): + current_section.append(internal_section[i]) + current_idx.append(internal_idx[i]) + internal_section = [] + internal_idx = [] + current_section.append(op) + current_idx.append(idx) + else: + # current graph id is different with previous, start a new section of cuda graph + # internal ops and idx belong to no section, just clear it + internal_section = [] + internal_idx = [] + current_cuda_graph_id = local_cuda_graph_id # start record a new section + assert len(current_section) == len( + current_idx + ), "num of section's op is not equal with num of idx" + if len(current_section) > 0: + # store previous section + cuda_graph_sections.append(current_section) + sections_idx.append(current_idx) + current_section = [op] + current_idx = [idx] + else: + # recode ops which cuda_graph_attr is None, may belong to a section + internal_section.append(op) + internal_idx.append(idx) + + # handle the last section + assert len(current_section) == len( + current_idx), "num of section's op is not equal with num of idx" + if len(current_section) > 0: + # store previous section + cuda_graph_sections.append(current_section) + sections_idx.append(current_idx) + + return cuda_graph_sections, sections_idx, is_test + + +def replace_cuda_graph_section(ins_and_outs, section_program, section_idx, + origin_program, cuda_graph_section, order, + is_test): + """ + Use section_program and ins_and_outs to initialize a run_program_op, + and replace the section_idx marks ops in the origin program. + + :param ins_and_outs: list, the logical ins and outs of the section program + :param section_program: framework.Program, the partial program need to run under cuda graph + :param section_idx: list, the idx need to be removed from origin program + :param origin_program: framework.Program, the origin program + :param cuda_graph_section: list, the ops in current sections, used to get the mode, memory pool id and is_test + :param order: int, the order of current section, used to create unique cuda graph var + :param is_test: bool, the program is running under is_test or not + :return: no return + """ + ins = ins_and_outs[0] + outs = ins_and_outs[1] + insert_idx = section_idx[0] + origin_block = origin_program.global_block() + + for idx in reversed(section_idx): + # remove all cuda graph marked ops from origin block + origin_block._remove_op(idx, sync=False) + + mode = None + memory_pool_id = None + + for op in cuda_graph_section: + # find the cuda graph mode and memory pool id, determine is test or not + if op._cuda_graph_attr is not None: + attrs = op._cuda_graph_attr.split(';') + mode = attrs[0] + memory_pool_id = int(attrs[1]) + break + + assert mode is not None and memory_pool_id is not None, \ + "mode and memory pool id should be specified in cuda graph attr" + + cuda_graph_var = origin_block.create_var( + name="cuda_graph_" + str(order), + type=core.VarDesc.VarType.RAW, + persistable=True, + stop_gradient=True, + ) + + # not used for the run_program_op, just needed by the op, but won't be used + out_scope_var = origin_block.create_var( + name="program_out_scope_" + str(order), + type=core.VarDesc.VarType.STEP_SCOPES, + persistable=True, + stop_gradient=True, + ) + + program_id = _hash_with_id(section_program, ins_and_outs) + + # insert the run_program_op into the block + origin_block._insert_op( + insert_idx, + type='run_program', + inputs={'X': ins}, + outputs={ + 'Out': outs, + 'OutScope': out_scope_var, + 'CUDAGraph': cuda_graph_var + }, + attrs={ + 'global_block': section_program.global_block(), + 'start_op_index': 0, + 'end_op_index': len(section_program.global_block().ops), + 'is_test': is_test, + 'program_id': program_id, + 'cuda_graph_capture_mode': mode, + 'cuda_graph_pool_id': memory_pool_id, + # Todo: now not support use interpretercore + 'use_interpretorcore': False, + 'forward_global_block': section_program.global_block(), + 'backward_global_block': section_program.global_block(), + }) + + +def cuda_graph_transform(program): + """ + replace the ops marked with cuda_graph_attr to run_program_op to use cuda graph + + :param program: framework.Program, the program to be transformed + :return: the cuda graph section program, user should hold these programs! + """ + + if len(program.blocks) > 1: + # some sub blocks may be inserted by optimizer but will not use during training, just warn here + warnings.warn( + "Sub block(s) has been detected in the program. " + "Cuda graph not support op with sub block, and it will only handle the global block." + ) + + # step 1: get all cuda graph sections. + # A cuda graph section contains all ops marked with same cuda graph id and + # some ops inserted by some optimizers (amp, sharding for example) between ops with same id. + cuda_graph_sections, sections_idx, is_test = get_cuda_graph_sections( + program) + assert len(cuda_graph_sections) == len(sections_idx), \ + "num of cuda graph sections is not equal with num of idx sections" + + # step 2: construct new program for each section and find inputs and outputs of each section. + # The inputs are variables generated outside the section but will be used by this section. + # The outputs are variables generated by this section and will be used after the end of the section. + ins_and_outs = [] + section_programs = [] + for i in range(len(cuda_graph_sections)): + # creating new program for current section + section_program, ins_outs = construct_program_and_find_ins_outs( + cuda_graph_sections[i], program, sections_idx[i]) + ins_and_outs.append(ins_outs) + section_programs.append(section_program) + assert len(section_programs) == len(cuda_graph_sections), \ + "the num of cuda graph sections should be equal with the num of new program" + + # step 3: replace the ops in original program with run_program_op. + # Will remove all ops in the section from origin program, and use run_program_op to replace them. + for i in reversed(range(len(cuda_graph_sections))): + # carry out the replacement in reversed order, to keep the previous idx intact + replace_cuda_graph_section(ins_and_outs[i], + section_programs[i], + sections_idx[i], + program, + cuda_graph_sections[i], + order=i, + is_test=is_test) + + # NOTE: user should hold these program, for now just return these program back to caller + return section_programs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/streams.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..d25355056e8d546c8a556e5395ab781f042b199f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/device/cuda/streams.py @@ -0,0 +1,16 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.core import CUDAStream as Stream +from paddle.fluid.core import CUDAEvent as Event diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43f819dd770a13a3a3fa8ad69b5a6576a18fe690 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/__init__.py @@ -0,0 +1,108 @@ +# 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. + +from .spawn import spawn # noqa: F401 +from .launch.main import launch # noqa: F401 + +from .parallel import init_parallel_env # noqa: F401 +from .parallel import get_rank # noqa: F401 +from .parallel import get_world_size # noqa: F401 + +from .parallel_with_gloo import gloo_init_parallel_env +from .parallel_with_gloo import gloo_barrier +from .parallel_with_gloo import gloo_release + +from paddle.distributed.fleet.dataset import InMemoryDataset # noqa: F401 +from paddle.distributed.fleet.dataset import QueueDataset # noqa: F401 +from paddle.distributed.fleet.base.topology import ParallelMode # noqa: F401 + +from .collective import broadcast # noqa: F401 +from .collective import all_reduce # noqa: F401 +from .collective import reduce # noqa: F401 +from .collective import all_gather # noqa: F401 +from .collective import all_gather_object # noqa: F401 +from .collective import scatter # noqa: F401 +from .collective import barrier # noqa: F401 +from .collective import ReduceOp # noqa: F401 +from .collective import split # noqa: F401 +from .collective import new_group # noqa: F401 +from .collective import alltoall # noqa: F401 +from .collective import recv # noqa: F401 +from .collective import get_group # noqa: F401 +from .collective import send # noqa: F401 +from .collective import wait # noqa: F401 +from .collective import is_initialized # noqa: F401 +from .collective import destroy_process_group # noqa: F401 +from .collective import alltoall_single # noqa: F401 +from .collective import isend # noqa: F401 +from .collective import irecv # noqa: F401 +from .collective import batch_isend_irecv # noqa: F401 +from .collective import P2POp # noqa: F401 +from .collective import reduce_scatter # noqa: F401 + +from .communication import stream + +from .auto_parallel import shard_op # noqa: F401 +from .auto_parallel import shard_tensor # noqa: F401 + +from .fleet import BoxPSDataset # noqa: F401 + +from .entry_attr import ProbabilityEntry # noqa: F401 +from .entry_attr import CountFilterEntry # noqa: F401 +from .entry_attr import ShowClickEntry # noqa: F401 + +from paddle.fluid.dygraph.parallel import ParallelEnv # noqa: F401 + +from . import cloud_utils # noqa: F401 + +from .sharding import group_sharded_parallel, save_group_sharded_model + +__all__ = [ # noqa + "spawn", + "launch", + "scatter", + "broadcast", + "ParallelEnv", + "new_group", + "init_parallel_env", + "gloo_init_parallel_env", + "gloo_barrier", + "gloo_release", + "QueueDataset", + "split", + "CountFilterEntry", + "ShowClickEntry", + "get_world_size", + "get_group", + "all_gather", + "all_gather_object", + "InMemoryDataset", + "barrier", + "all_reduce", + "alltoall", + "alltoall_single", + "send", + "reduce", + "recv", + "ReduceOp", + "wait", + "get_rank", + "ProbabilityEntry", + "ParallelMode", + "is_initialized", + "destroy_process_group", + "isend", + "irecv", + "reduce_scatter", +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..269a0ec644dbd2e54ab255fa88f2e80ae744985f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/__init__.py @@ -0,0 +1,23 @@ +# Copyright (c) 2021 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. + +from .strategy import Strategy +from .process_mesh import ProcessMesh +from .engine import Engine +from .interface import shard_tensor +from .interface import shard_op +from .interface import recompute +from .interface import fetch + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/callbacks.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..17ce5bd71b8168608f19af4a0f1b9860856c6091 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/callbacks.py @@ -0,0 +1,226 @@ +# Copyright (c) 2022 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. + +import os +import time + +import paddle +from paddle.hapi.callbacks import ProgBarLogger, ModelCheckpoint, LRScheduler, CallbackList, Callback +from .interface import CollectionNames, get_collection + + +def config_callbacks(callbacks=None, + engine=None, + batch_size=None, + epochs=None, + steps=None, + log_freq=2, + verbose=2, + save_freq=1, + save_dir=None, + metrics=None, + acc_step=1, + mode='train'): + cbks = callbacks or [] + cbks = cbks if isinstance(cbks, (list, tuple)) else [cbks] + + if not any(isinstance(k, ProgBarLogger) for k in cbks) and verbose: + cbks = [ProgBarLoggerAuto(log_freq, verbose=verbose)] + cbks + + if not any(isinstance(k, LRScheduler) for k in cbks): + cbks = [LRSchedulerAuto()] + cbks + + if not any(isinstance(k, ModelCheckpoint) for k in cbks): + cbks = cbks + [ModelCheckpointAuto(save_freq, save_dir)] + + if not any(isinstance(k, Profiler) for k in cbks) and verbose == 3: + cbks = cbks + [Profiler(timer_only=True)] + + if not any(isinstance(k, History) for k in cbks): + cbks = cbks + [History()] + + for i, k in enumerate(cbks): + if isinstance(k, ProgBarLogger): + cbks[i] = ProgBarLoggerAuto(k.log_freq, k.verbose) + if isinstance(k, LRScheduler): + cbks[i] = LRSchedulerAuto(k.by_step, k.by_epoch) + if isinstance(k, ModelCheckpoint): + cbks[i] = ModelCheckpointAuto(k.save_freq, k.save_dir) + + cbk_list = CallbackList(cbks) + cbk_list.set_model(engine) + metrics = metrics or [] if mode != 'test' else [] + params = { + 'batch_size': batch_size, + 'epochs': epochs, + 'steps': steps, + 'verbose': verbose, + 'metrics': metrics, + 'acc_step': acc_step, + } + cbk_list.set_params(params) + return cbk_list + + +class ProgBarLoggerAuto(ProgBarLogger): + + def __init__(self, log_freq=1, verbose=2): + super(ProgBarLoggerAuto, self).__init__(log_freq, verbose) + + def _is_print(self): + return True + + def _updates(self, logs, mode): + values = [] + metrics = getattr(self, '%s_metrics' % (mode)) + progbar = getattr(self, '%s_progbar' % (mode)) + steps = getattr(self, '%s_step' % (mode)) + + for k in metrics: + if k in logs: + values.append((k, logs[k])) + + if 'lr' in logs: + values.append(('lr', logs['lr'])) + + fetches_logs = logs.get('fetches', {}) + collect_logging = get_collection(CollectionNames.LOGGING) + for name, var in collect_logging: + k = name or var.name + if k in fetches_logs: + values.append((k, fetches_logs[k])) + + out_logs = logs.get('outputs', {}) + for k in out_logs: + values.append((k, out_logs[k])) + + if self.verbose == 3 and hasattr(self, '_%s_timer' % (mode)): + timer = getattr(self, '_%s_timer' % (mode)) + cnt = timer['count'] if timer['count'] > 0 else 1.0 + samples = timer['samples'] if timer['samples'] > 0 else 1.0 + values.append( + ('avg_reader_cost', "%.5f sec" % (timer['data_time'] / cnt))) + values.append( + ('avg_batch_cost', "%.5f sec" % (timer['batch_time'] / cnt))) + values.append( + ('ips', "%.5f samples/sec" % + (samples / (timer['data_time'] + timer['batch_time'])))) + timer['count'] = 0 + timer['samples'] = 0 + timer['data_time'] = 0. + timer['batch_time'] = 0. + + progbar.update(steps, values) + + def on_eval_batch_end(self, step, logs=None): + logs = logs or {} + self.eval_step += 1 + samples = self.params['batch_size'] + self.evaled_samples += samples + + self._eval_timer['batch_time'] += ( + time.time() - self._eval_timer['batch_data_end_time']) + self._eval_timer['count'] += 1 + samples = self.params['batch_size'] + self._eval_timer['samples'] += samples + + if self._is_print() and self.eval_step % self.log_freq == 0: + if self.eval_steps is None or self.eval_step < self.eval_steps: + self._updates(logs, 'eval') + + self._eval_timer['batch_start_time'] = time.time() + + +class LRSchedulerAuto(LRScheduler): + + def __init__(self, by_step=True, by_epoch=False): + super(LRSchedulerAuto, self).__init__(by_step, by_epoch) + + def on_epoch_begin(self, epoch=None, logs=None): + self.acc_step = self.params["acc_step"] + self.epoch = epoch + self.train_step = 0 + + def on_train_batch_end(self, step, logs=None): + self.train_step += 1 + + if self.by_step and self.train_step % self.acc_step == 0: + if self.model._optimizer and \ + hasattr(self.model._optimizer, '_learning_rate') and \ + isinstance(self.model._optimizer._learning_rate, + paddle.optimizer.lr.LRScheduler): + self.model._optimizer._learning_rate.step() + + +class History(Callback): + + def __init__(self): + self.history = {} + + def on_train_begin(self, logs=None): + self.epoch = [] + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + self.epoch.append(epoch) + for k, v in logs.items(): + self.history.setdefault(k, []).append(v) + + self.model.history = self + + +class Profiler(Callback): + + def __init__(self, *args, **kwargs): + self.prof = paddle.profiler.Profiler(*args, **kwargs) + + def on_epoch_begin(self, epoch=None, logs=None): + self.epoch = epoch + self.train_step = 0 + self.batch_size = self.params["batch_size"] + self.steps = self.params['steps'] + + def on_train_begin(self, logs=None): + self.prof.start() + + def on_train_batch_end(self, step, logs=None): + self.train_step += 1 + self.prof.step(num_samples=self.batch_size) + print("step {}:{}".format(self.train_step, + self.prof.step_info(unit='samples'))) + + def on_train_end(self, logs=None): + self.prof.stop() + self.prof.summary() + + +class ModelCheckpointAuto(ModelCheckpoint): + + def __init__(self, *args, **kwargs): + super(ModelCheckpointAuto, self).__init__(*args, **kwargs) + + def _is_save(self): + return self.model and self.save_dir + + def on_epoch_end(self, epoch, logs=None): + if self._is_save() and (self.epoch + 1) % self.save_freq == 0: + path = '{}/epoch{}'.format(self.save_dir, epoch) + print('save checkpoint at {}'.format(os.path.abspath(path))) + self.model.save(path) + + def on_train_end(self, logs=None): + if self._is_save(): + path = '{}/final'.format(self.save_dir) + print('save checkpoint at {}'.format(os.path.abspath(path))) + self.model.save(path) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..e17f83eb419072f23350db6c0788769bbc1a5ebd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster.py @@ -0,0 +1,825 @@ +# Copyright (c) 2022 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. + +import os +import json +from enum import IntEnum +from enum import unique +import paddle + + +@unique +class DeviceType(IntEnum): + UNKNOWN = 0 + CPU = 1 + GPU = 2 + XPU = 3 + NPU = 4 + DCU = 5 + NIC = 6 + + +@unique +class LinkType(IntEnum): + UNKNOWN = 0 + LOC = 1 + SYS = 2 + PHB = 3 + PIX = 4 + PIB = 5 + NVL = 6 + NVB = 7 + NET = 8 + + +class Device: + NON_ACCELERATOR_TYPE = [DeviceType.CPU, DeviceType.NIC, DeviceType.UNKNOWN] + + def __init__(self, global_id, local_id, machine): + self._global_id = global_id + self._local_id = local_id + self._machine = machine + self._type = None + # Different device have different models, such as + # "Tesla V100-SXM2-32GB" and "A100-SXM4-40GB" etc. + self._model = None + # Double precision GFLOPS + self._dp_gflops = None + # Single precision GFLOPS + self._sp_gflops = None + # Memory is stored by GB + self._memory = None + + @property + def global_id(self): + return self._global_id + + @global_id.setter + def global_id(self, value): + self._global_id = value + + @property + def local_id(self): + return self._local_id + + @local_id.setter + def local_id(self, value): + self._local_id = value + + @property + def machine(self): + return self._machine + + @machine.setter + def machine(self, value): + self._machine = value + + @property + def type(self): + return self._type + + @type.setter + def type(self, value): + self._type = value + + @property + def model(self): + return self._model + + @model.setter + def model(self, value): + self._model = value + + @property + def dp_gflops(self): + return self._dp_gflops + + @dp_gflops.setter + def dp_gflops(self, value): + self._dp_gflops = value + + @property + def sp_gflops(self): + return self._sp_gflops + + @sp_gflops.setter + def sp_gflops(self, value): + self._sp_gflops = value + + @property + def memory(self): + return self._memory + + @memory.setter + def memory(self, value): + self._memory = value + + def __str__(self): + str = "" + str += "global_id: {}, local_id: {}, machine_id: {}, type: {}, model: {}, dp_flops: {}, sp_flops: {}, memory: {}".format( + self.global_id, self.local_id, self.machine.id, self.type.name, + self.model, self.dp_gflops, self.sp_gflops, self.memory) + return str + + def __repr__(self): + return self.__str__() + + +class Link: + + default_hop = 1 + default_nic_bandwidth = 24 + + def __init__(self, source, target): + self._src = source + self._tgt = target + self._type = None + # bandwidth is stored by GB/s + self._bandwidth = None + # latency is stored by millisecond + self._latency = None + self._hop = None + + @property + def source(self): + return self._src + + @source.setter + def source(self, value): + self._source = value + + @property + def target(self): + return self._tgt + + @target.setter + def target(self, value): + self._target = value + + @property + def type(self): + return self._type + + @type.setter + def type(self, value): + self._type = value + + @property + def bandwidth(self): + return self._bandwidth + + @bandwidth.setter + def bandwidth(self, value): + self._bandwidth = value + + @property + def latency(self): + return self._latency + + @latency.setter + def latency(self, value): + self._latency = value + + @property + def hop(self): + return self._hop + + @hop.setter + def hop(self, value): + self._hop = value + + def __str__(self): + str = "" + str += "source_global_id: {}, target_global_id: {}, type: {}, bandwidth: {}, latency: {}".format( + self.source.global_id, self.target.global_id, self.type, + self.bandwidth, self.latency) + return str + + def __repr__(self): + return self.__str__() + + +class Machine: + + def __init__(self, id): + self._id = id + self._hostname = None + self._addr = None + self._port = None + self._devices = {} + self._links = {} + self._accelerators = {} + self._non_accelerator_cumulative_count = 0 + + @property + def id(self): + return self._id + + @id.setter + def id(self, value): + self._id = value + + @property + def hostname(self): + return self._hostname + + @hostname.setter + def hostname(self, value): + self._hostname = value + + @property + def addr(self): + return self._addr + + @addr.setter + def addr(self, value): + self._addr = value + + @property + def port(self): + return self._port + + @port.setter + def port(self, value): + self._port = value + + @property + def devices(self): + return self._devices + + @property + def links(self): + return self._links + + @property + def accelerators(self): + return self._accelerators + + def add_device(self, device): + # Use the device global_id as the key + self._devices[device.global_id] = device + if device.type not in Device.NON_ACCELERATOR_TYPE: + self._accelerators[device.global_id] = device + + def add_link(self, link): + # Use the source device global_id and target device global_id as the key + self._links[(link.source.global_id, link.target.global_id)] = link + + def get_link(self, source_global_id, target_global_id): + return self._links.get((source_global_id, target_global_id), None) + + def __str__(self): + str = "" + for device in self.devices.values(): + str += ", device: {}".format(device) + for link in self.links.values(): + str += ", link: {}".format(link) + return str + + def __repr__(self): + return self.__str__() + + +class AlphaLatency: + + def __init__(self, alpha_latency): + assert isinstance(alpha_latency, dict) + self._base = alpha_latency.get("base", None) + self._inter = alpha_latency.get("inter", None) + self._intra = alpha_latency.get("intra", None) + self._switch = alpha_latency.get("switch", None) + if self._switch is not None: + try: + self._switch = float(self._switch) + except: + raise TypeError("The switch latency must be float") + self._base_ring = self._base.get( + "ring", None) if self._base is not None else None + self._base_tree = self._base.get( + "tree", None) if self._base is not None else None + self._base_inter = self._base.get( + "inter", None) if self._base is not None else None + if self._base_ring is not None: + try: + self._base_ring = float(self._base_ring) + except: + raise TypeError("The base ring latency must be float.") + if self._base_tree is not None: + try: + self._base_tree = float(self._base_tree) + except: + raise TypeError("The base ring latency must be float.") + + self._inter_ring = self._inter.get("ring", None) + self._inter_tree = self._inter.get("tree", None) + self._intra_ring = self._intra.get("ring", None) + self._intra_tree = self._intra.get("tree", None) + + if self._inter_ring is not None: + if isinstance(self._inter_ring, str): + assert self._inter_ring in ["NET"] + self._inter_ring = LinkType[self._inter_ring] + else: + try: + self._inter_ring = float(self._inter_ring) + except: + raise TypeError("The inter ring latency must be float.") + + if self._inter_tree is not None: + if isinstance(self._inter_tree, str): + assert self._inter_tree in ["NET"] + self._inter_tree = LinkType[self._inter_tree] + else: + try: + self._inter_tree = float(self._inter_tree) + except: + raise TypeError("The inter tree latency must be float.") + + if self._intra_ring is not None: + if isinstance(self._intra_ring, str): + assert self._intra_ring in ["NVL", "PHB"] + self._intra_ring = LinkType[self._intra_ring] + else: + try: + self._intra_ring = float(self._intra_ring) + except: + raise TypeError("The intra ring latency must be float.") + + if self._intra_tree is not None: + if isinstance(self._intra_tree, str): + assert self._intra_tree in ["NVL", "PHB"] + self._intra_tree = LinkType[self._intra_tree] + else: + try: + self._intra_tree = float(self._intra_tree) + except: + raise TypeError("The intra tree latency must be float.") + + @property + def base_ring(self): + return self._base_ring + + @property + def base_tree(self): + return self._base_tree + + @property + def switch(self): + return self._switch + + @property + def inter_ring(self): + return self._inter_ring + + @property + def inter_tree(self): + return self._inter_tree + + @property + def intra_ring(self): + return self._intra_ring + + @property + def intra_tree(self): + return self._intra_tree + + +class Cluster: + """ + The cluster is an abstract of the hardware resource for training, which contains the cluster topology and + related hardware information. It will serve the task mapping, cost model and auto searching. + """ + + def __init__(self): + # Used to compute machine id + self._num_machines = 0 + # Store all machines within the cluster + self._machines = {} + # Cluster graph topology + self._topology = None + # Latency for communication cost model + self._alpha_latency = None + self._rank_to_device_id = {} + self._device_id_to_rank = {} + # This property only be valid when the cluster consists of machines, + # which have the same number accelerators. + self._num_devices_per_machine = None + + def gen_default_config_cluster(self, + gpu_model="V100", + cpu_model="6271C", + node_count=1, + device_count=1, + gpu_memory=32, + cpu_memory=503, + inter_bandwidth=24, + intra_bandwidth=235, + gpu_dp_gflops=7800, + gpu_sp_gflops=15700, + cpu_dp_gflops=75, + cpu_sp_gflops=150): + """Generate cluster by default config.""" + gpu_models = ["V100", "A100", "H100", "A2", "A10", "A16", "A30", "A40"] + xpu_models = ["XPU"] + npu_models = ["NPU"] + dcu_models = ["DCU"] + all_gpu_models = gpu_models + xpu_models + npu_models + dcu_models + assert gpu_model in all_gpu_models + self._num_devices_per_machine = device_count + + def _convert_to_type(gpu_model): + type = None + if gpu_model in gpu_models: + type = "GPU" + elif gpu_model in xpu_models: + type = "XPU" + elif gpu_model in npu_models: + type = "NPU" + elif gpu_model in dcu_models: + type = "DCU" + assert type is not None + + return type + + def _convert_to_model(gpu_model, gpu_memory): + model = None + if gpu_model == "V100": + model = "Tesla V100-SXM2-" + str(gpu_memory) + "GB" + assert model is not None + + return model + + def _convert_to_cpu_info(cpu_model): + arch, vendor, model = None, None, None + if cpu_model == "6271C": + arch = "x86_64" + vendor = "GenuineIntel" + model = "Intel(R) Xeon(R) Gold 6271C CPU @ 2.60G" + elif cpu_model == "6148": + arch = "x86_64" + vendor = "GenuineIntel" + model = "Intel(R) Xeon(R) Gold 6148 CPU @ 2.40G" + assert arch is not None + assert vendor is not None + assert model is not None + + return arch, vendor, model + + cluster_info = {} + cluster_info["machines"] = [] + global_id = 0 + global_id_to_device_type = {} + global_id_to_node = {} + # NOTE: It will support NPU, XPU, DCU models in the future, it is just a fake value now + for i in range(node_count): + machine = {} + # NOTE: The hostname is host_0, host_1, ... + machine["hostname"] = "host_" + str(i) + # NOTE: The addr is localhost, if need actual addr, it should be reset manually + machine["addr"] = "127.0.0.1" + # NOTE: The port is a default value + machine["port"] = 60009 + machine["links"] = [] + + devices = [] + local_id = 0 + + for j in range(device_count): + device = {} + global_id = global_id if i == 0 and j == 0 else global_id + 1 + + local_id += 1 + type = _convert_to_type(gpu_model) + model = _convert_to_model(gpu_model, gpu_memory) + dp_gflops = gpu_dp_gflops + sp_gflops = gpu_dp_gflops + memory = gpu_memory + + device["global_id"] = global_id + device["local_id"] = local_id + device["type"] = type + device["model"] = model + device["memory"] = memory + device["sp_gflops"] = sp_gflops + device["dp_gflops"] = dp_gflops + global_id_to_device_type[global_id] = type + global_id_to_node[global_id] = i + devices.append(device) + + # add cpu device and nic device, just one cpu + cpu_device = {} + arch, vendor, model = _convert_to_cpu_info(cpu_model) + sp_gflops = cpu_sp_gflops + dp_gflops = cpu_dp_gflops + global_id += 1 + local_id = 0 + memory = cpu_memory + type = "CPU" + cpu_device["arch"] = arch + cpu_device["vendor"] = vendor + cpu_device["model"] = model + cpu_device["sp_gflops"] = sp_gflops + cpu_device["dp_gflops"] = dp_gflops + cpu_device["global_id"] = global_id + cpu_device["local_id"] = local_id + cpu_device["memory"] = memory + cpu_device["type"] = type + global_id_to_node[global_id] = i + global_id_to_device_type[global_id] = type + devices.append(cpu_device) + + nic_device = {} + global_id += 1 + + # add NIC + type = "NIC" + width = 12.5 + ip = "127.0.0.1" + local_id = 0 + nic_device["type"] = type + nic_device["local_id"] = type + nic_device["global_id"] = global_id + global_id_to_device_type[global_id] = type + global_id_to_node[global_id] = i + devices.append(nic_device) + machine["devices"] = devices + cluster_info["machines"].append(machine) + + # build link + for i in range(0, global_id + 1): + for j in range(0, global_id + 1): + if i == j: + continue + node_id_i = global_id_to_node[i] + node_id_j = global_id_to_node[j] + device_type_i = global_id_to_device_type[i] + device_type_j = global_id_to_device_type[j] + link = {} + source_global_id = i + target_global_id = j + link["source_global_id"] = source_global_id + link["target_global_id"] = target_global_id + # the same node and device_type, set intra_bandwidth, NVL + if node_id_i == node_id_j and device_type_i == device_type_j: + link["type"] = "NVL" + link["bandwidth"] = intra_bandwidth + else: + link["type"] = "PHB" + link["bandwidth"] = inter_bandwidth + cluster_info["machines"][node_id_i]["links"].append(link) + + self._build_from_dict(cluster_info) + + @property + def rank_to_device_id(self): + return self._rank_to_device_id + + @property + def device_id_to_rank(self): + return self._device_id_to_rank + + @property + def machines(self): + return self._machines + + def add_machine(self, machine): + assert isinstance(machine, Machine) + self._machines[machine.id] = machine + + # map rank to device id and map device id to rank + if machine.id != 0: + prev_machine = self._machines[machine.id - 1] + offset = prev_machine._non_accelerator_cumulative_count + for global_id in machine.devices: + if machine.devices[ + global_id].type not in Device.NON_ACCELERATOR_TYPE: + rank_id = global_id - offset + self._rank_to_device_id[rank_id] = global_id + self._device_id_to_rank[global_id] = rank_id + machine._non_accelerator_cumulative_count = len( + machine.devices) - len( + machine.accelerators + ) + prev_machine._non_accelerator_cumulative_count + else: + for global_id in machine.devices: + if machine.devices[ + global_id].type not in Device.NON_ACCELERATOR_TYPE: + rank_id = global_id + self._rank_to_device_id[rank_id] = global_id + self._device_id_to_rank[global_id] = rank_id + machine.accelerators[global_id] = machine.devices[global_id] + machine._non_accelerator_cumulative_count = len( + machine.devices) - len(machine.accelerators) + + @property + def alpha_latency(self): + return self._alpha_latency + + def add_device(self, device): + assert isinstance(device, Device) + device.machine.add_device(device) + + def add_link(self, link): + assert isinstance(link, Link) + # Only add the link to the source machine + link.source.machine.add_link(link) + + def get_device(self, device_global_id): + device = None + for machine in self.machines.values(): + if device_global_id in machine.devices.keys(): + device = machine.devices[device_global_id] + return device + + def _build_from_dict(self, cluster_info): + machines_info = cluster_info["machines"] + for machine_info in machines_info: + machine_id = self._generate_machine_id() + machine = Machine(machine_id) + machine.hostname = machine_info.get("hostname") + machine.addr = machine_info.get("addr") + machine.port = machine_info.get("port") + devices_info = machine_info.get("devices", []) + for device_info in devices_info: + device_global_id = device_info.get("global_id") + device_local_id = device_info.get("local_id") + device = Device(device_global_id, device_local_id, machine) + device_type = device_info.get("type", None) + if device_type is not None: + device_type = DeviceType[device_type] + else: + device_type = DeviceType.UNKNOWN + device.type = device_type + device.model = device_info.get("model", None) + device.dp_gflops = float(device_info.get("dp_gflops", 0)) + device.sp_gflops = float(device_info.get("sp_gflops", 0)) + device.memory = float(device_info.get("memory", 0)) + self.add_device(device) + self.add_machine(machine) + for machine_info in machines_info: + links_info = machine_info.get("links", []) + for link_info in links_info: + source_global_id = link_info.get("source_global_id") + target_global_id = link_info.get("target_global_id") + source = self.get_device(source_global_id) + target = self.get_device(target_global_id) + link = Link(source, target) + link_type = link_info.get("type", None) + if link_type is not None: + link_type = LinkType[link_type] + else: + link_type = LinkType.UNKNOWN + link.type = link_type + link.bandwidth = float(link_info.get("bandwidth", 0)) + link.latency = float(link_info.get("latency", 0)) + link.hop = link_info.get("hop", None) + if link.hop is None: + # Set the default of hop: If in the same machine, hop is 0. And if in the different machine, hop is 1. + source_machine = source.machine + target_machine = target.machine + if source_machine.id == target_machine.id: + link.hop = 0 + else: + link.hop = Link.default_hop + self.add_link(link) + + if "alpha_latency" in cluster_info: + self._alpha_latency = AlphaLatency( + cluster_info.get("alpha_latency")) + else: + self._alpha_latecy = None + + def build_from_file(self, json_file_path): + with open(json_file_path) as json_file: + cluster_info = json.load(json_file) + self._build_from_dict(cluster_info) + + def _generate_machine_id(self): + cur_machine_id = self._num_machines + self._num_machines += 1 + return cur_machine_id + + def get_all_devices(self, device_type): + devices = [] + for machine in self.machines.values(): + for device in machine.devices.values(): + if device.type == DeviceType[device_type]: + devices.append(device) + return devices + + def get_beta(self, source_device_id, target_device_id): + # beta means the time transferring a byte, us/B + beta = None + convert_base = 1000 + device = self.get_device(source_device_id) + machine = device.machine + link = machine.get_link(source_device_id, target_device_id) + bandwidth = None + # None means the source and target are not connected directly, set NIC in default + if link is None: + bandwidth = Link.default_nic_bandwidth + else: + bandwidth = link.bandwidth + + if bandwidth == 0.: + beta = 0 + else: + beta = 1 / (bandwidth * (convert_base**3 / 10**6)) + + return beta + + def get_hop(self, source_device_id, target_device_id): + beta = None + hop = None + device = self.get_device(source_device_id) + machine = device.machine + link = machine.get_link(source_device_id, target_device_id) + if link is not None: + hop = link.hop + else: + hop = Link.default_hop + return hop + + def cross_machine(self, device_ids): + machine_ids = set() + for device_id in device_ids: + device = self.get_device(device_id) + machine_id = device.machine.id + machine_ids.add(machine_id) + if len(machine_ids) == 1: + return False + else: + return True + + def convert_rank_to_device_id(self, group_ranks): + # group_ranks is global id of the rank in paddle + # task will use all of machine in this cluster with accelerators in default + device_ids = [] + for rank in group_ranks: + device_ids.append(self.rank_to_device_id[rank]) + return device_ids + + def get_involved_machine_count(self, device_ids): + machine_ids = set() + for device_id in device_ids: + device = self.get_device(device_id) + machine_id = device.machine.id + machine_ids.add(machine_id) + count = len(machine_ids) + assert count > 0 + return count + + def get_num_machines(self): + return len(self._machines) + + def get_num_devices_per_machine(self): + # Only return the number of accelerators of each machine. + # All machines must has the same number of devices and same type of devices. + assert self._num_devices_per_machine + return self._num_devices_per_machine + + def __str__(self): + str = "" + for machine in self.machines.values(): + str += "machine: {}\n".format(machine) + return str + + def __repr__(self): + return self.__str__() + + +def get_default_cluster(): + cluster = Cluster() + local_device_count = os.getenv("PADDLE_LOCAL_SIZE") + if local_device_count is None: + local_device_count = 1 + else: + local_device_count = int(local_device_count) + global_device_count = os.getenv("PADDLE_GLOBAL_SIZE") + if global_device_count is None: + node_count = 1 + else: + global_device_count = int(global_device_count) + assert global_device_count % local_device_count == 0 + node_count = int(global_device_count) // local_device_count + print("Node Count: ", + node_count, + "Local Device Size: ", + local_device_count, + "World size: ", + paddle.distributed.get_world_size(), + flush=True) + cluster.gen_default_config_cluster(node_count=node_count, + device_count=local_device_count) + return cluster diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster_v2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..bdaf18ee650a9d509af102aeb5dd8789db585a26 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cluster_v2.py @@ -0,0 +1,128 @@ +# Copyright (c) 2022 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. + +import copy +import numpy as np +from enum import IntEnum +from enum import unique + +import paddle +from paddle.fluid import core +from paddle.fluid.core import Device +from paddle.fluid.core import Link + + +@unique +class DeviceType(IntEnum): + UNKNOWN = 0 + CPU = 1 + GPU = 2 + XPU = 3 + NPU = 4 + DCU = 5 + NIC = 6 + + +@unique +class LinkType(IntEnum): + UNKNOWN = 0 + LOC = 1 + SYS = 2 + PHB = 3 + PIX = 4 + PIB = 5 + NVL = 6 + NVB = 7 + NET = 8 + + +class DeviceMesh(core.DeviceMesh): + r""" + The class `DeviceMesh` describes the topology of physical devices. + + Args: + mesh (list|numpy.array): an N-dimensional array describes the toplogy + of logical processes. + dim_names (list, optional): the i-th element of this list gives the name of the + i-th dimension. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed as dist + + paddle.enable_static() + + mesh = dist.DeviceMesh([[2, 4, 5], [0, 1, 3]]) + assert mesh.shape == [2, 3] + assert mesh.device_ids == [2, 4, 5, 0, 1, 3] + + """ + + def __init__(self, name, mesh, dim_names=None): + self._name = name + + if not isinstance(mesh, list) and \ + not isinstance(mesh, np.ndarray): + raise ValueError( + 'The mesh must be an instance of list or np.ndarray.') + if isinstance(mesh, list): + mesh = np.array(mesh) + + self._mesh = mesh + + self._shape = list(self._mesh.shape) + + self._device_ids = self._mesh.flatten().tolist() + assert all(isinstance(p, int) for p in self._device_ids), \ + ("All elements of the mesh be integer") + assert min( + self._device_ids) >= 0, ('All elements of the mesh must be >= 0.') + unique_device_ids = set(self._device_ids) + assert len(unique_device_ids) == len( + self._device_ids), ('All elements of the mesh must be unique.') + + if dim_names is not None: + assert len(dim_names) == len(self._shape), \ + ("The length of dims_names must be same as the shape of the mesh.") + self._dim_names = dim_names + else: + self._dim_names = ["d" + str(i) for i in range(len(self._shape))] + + # Follow the requirement for using pybind11 + core.DeviceMesh.__init__(self, self._name, self._shape, + self._device_ids, self._dim_names) + + @property + def mesh(self): + return self._mesh + + +# class Cluster(object): +# """ +# The cluster represents the hardware resource. +# """ + +# def __init__(self): +# self._device_meshes = {} + +# def device_mesh(self, device_mesh_name): +# return self._device_meshes[device_mesh_name] + +# def add_device_mesh(self, device_mesh): +# self._device_meshes[device_mesh.name] = device_mesh diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/completion.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..f420a06cfbc743fa43ef2003aacf77def69d4da8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/completion.py @@ -0,0 +1,1613 @@ +# Copyright (c) 2021 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. + +import copy +from copy import deepcopy +import time + +from paddle.fluid import core +from paddle.fluid import framework + +from .utils import is_gradient_clip_op, __not_shape_var_type__ +from .operators import find_compatible_distributed_operator_impls +from .dist_context import get_default_distributed_context, _node_id +from .dist_tensor import DistributedTensor +from .dist_op import DistributedOperator +from .dist_attribute import TensorDistributedAttribute +from .dist_attribute import OperatorDistributedAttribute +from .process_mesh import ProcessMesh +from .process_group import get_world_process_group +from paddle.distributed.fleet.meta_optimizers.common import OpRole + + +def compute_compatible_process_mesh(process_mesh_list): + """Compute the compatible process mesh given a list of process meshes.""" + if not process_mesh_list: + return None + + def _compute_compatible_process_mesh_two(pm1, pm2): + if pm1 is None: + return True, pm2 + if pm2 is None: + return True, pm1 + if pm1 == pm2: + return True, pm1 + if pm1.processes == pm2.processes: + if len(pm1.topology) >= len(pm2.topology): + return True, pm1 + else: + return True, pm2 + process_set1 = set(pm1.processes) + process_set2 = set(pm2.processes) + if process_set1.issubset(process_set2): + return True, pm2 + if process_set2.issubset(process_set1): + return True, pm1 + return False, None + + compatible_result = None + for process_mesh in process_mesh_list: + compatible, compatible_result = _compute_compatible_process_mesh_two( + compatible_result, process_mesh) + if not compatible: + return None + return copy.deepcopy(compatible_result) + + +def compute_compatible_dim_mapping(dim_mapping_list): + """Compute the compatible dim mapping given a list of dim mapping.""" + if not dim_mapping_list: + return None + + def _compute_compatible_dim_mapping_two(dm1, dm2): + if dm1 == -1: + return True, dm2 + if dm2 == -1: + return True, dm1 + if dm1 == dm2: + return True, dm1 + return False, None + + compatible_result = -1 + for mapping in dim_mapping_list: + compatible, compatible_result = _compute_compatible_dim_mapping_two( + compatible_result, mapping) + if not compatible: + return None + return compatible_result + + +def compute_compatible_dims_mapping(dims_mapping_list): + """Compute the compatible dims mapping given a list of dims mapping. + Each of dims mapping is also a list. + """ + if not dims_mapping_list: + return None + length = len(dims_mapping_list[0]) + for dims_mapping in dims_mapping_list: + if dims_mapping is None: + return None + if len(dims_mapping) != length: + return None + compatible_result = [] + for dim_mappings in zip(*dims_mapping_list): + compatible_dim_mapping = compute_compatible_dim_mapping( + list(dim_mappings)) + if compatible_dim_mapping is None: + return None + compatible_result.append(compatible_dim_mapping) + return compatible_result + + +def merge_process_mesh_two(pm1, pm2): + process_set1 = set() + process_set2 = set() + if pm1 is None and pm2 is None: + return None + if pm1 is not None: + process_set1 = set(pm1.processes) + if pm2 is not None: + process_set2 = set(pm2.processes) + merged_process_set = process_set1.union(process_set2) + merged_process_mesh = ProcessMesh(list(merged_process_set)) + return merged_process_mesh + + +def _validate_dims_mapping(dims_mapping, process_mesh): + if dims_mapping is None: + return False + for i in range(len(dims_mapping)): + if dims_mapping[i] < -1 or dims_mapping[i] >= len( + process_mesh.topology): + return False + for i in range(len(process_mesh.topology)): + if dims_mapping.count(i) > 1: + return False + return True + + +class Completer: + + def __init__(self, dist_context): + assert dist_context is not None + self._dist_context = dist_context + self._has_prepared = False + + def _update_tensor_node_dims_mapping(self, tensor_node, fwd=True): + changed = False + if (not tensor_node.is_var()) or (tensor_node.var() is None): + return False + tensor_desc = tensor_node.var() + # Skip reader tensor + if tensor_desc.type() == core.VarDesc.VarType.READER \ + or tensor_desc.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or tensor_desc.type == core.VarDesc.VarType.STEP_SCOPES: + return False + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + assert tensor_dist_attr is not None + if tensor_dist_attr.is_annotated("dims_mapping"): + return False + tensor_dims_mapping = tensor_dist_attr.dims_mapping + if fwd: + dims_mapping_list = [] + for pred_op_node in tensor_node.inputs: + if pred_op_node.op() is not None: + if pred_op_node.op().type() == "create_py_reader" \ + or pred_op_node.op().type() == "create_double_buffer_reader" \ + or pred_op_node.op().type() == "read": + continue + op_dist_attr = self._dist_context.get_op_dist_attr_for_graph( + pred_op_node) + if op_dist_attr.process_mesh == tensor_dist_attr.process_mesh: + op_dims_mapping = op_dist_attr.get_output_dims_mapping( + tensor_desc.name()) + dims_mapping_list.append(op_dims_mapping) + dims_mapping_list.append(tensor_dims_mapping) + compatible_dims_mapping = compute_compatible_dims_mapping( + dims_mapping_list) + if not _validate_dims_mapping(compatible_dims_mapping, + tensor_dist_attr.process_mesh): + return False + if (compatible_dims_mapping is not None) and \ + (compatible_dims_mapping != tensor_dims_mapping): + tensor_dist_attr.dims_mapping = compatible_dims_mapping + changed = True + else: + dims_mapping_list = [] + for succ_op_node in tensor_node.outputs: + if succ_op_node.op() is not None: + if succ_op_node.op().type() == "create_py_reader" \ + or succ_op_node.op().type() == "create_double_buffer_reader" \ + or succ_op_node.op().type() == "read": + continue + op_dist_attr = self._dist_context.get_op_dist_attr_for_graph( + succ_op_node) + if op_dist_attr.process_mesh == tensor_dist_attr.process_mesh: + op_dims_mapping = op_dist_attr.get_input_dims_mapping( + tensor_desc.name()) + dims_mapping_list.append(op_dims_mapping) + dims_mapping_list.append(tensor_dims_mapping) + compatible_dims_mapping = compute_compatible_dims_mapping( + dims_mapping_list) + if not _validate_dims_mapping(compatible_dims_mapping, + tensor_dist_attr.process_mesh): + return False + if (compatible_dims_mapping is not None) and \ + (compatible_dims_mapping != tensor_dims_mapping): + tensor_dist_attr.dims_mapping = compatible_dims_mapping + changed = True + return changed + + def _update_op_node_dims_mapping(self, op_node, fwd=True): + changed = False + if (not op_node.is_op()) or (op_node.op() is None): + return False + # Skip reader op + op_desc = op_node.op() + if op_desc.type() == "create_py_reader" \ + or op_desc.type() == "create_double_buffer_reader" \ + or op_desc.type() == "while" \ + or op_desc.type() == "read": + return False + dist_op = self._dist_context.get_dist_op_for_graph(op_node) + op_dist_attr = dist_op.dist_attr + original_op_dist_attr = copy.deepcopy(op_dist_attr) + if fwd: + for tensor_node in op_node.inputs: + if tensor_node.is_var() and tensor_node.var() is not None: + if tensor_node.var().type() == core.VarDesc.VarType.READER: + continue + tensor_desc = tensor_node.var() + if op_dist_attr.is_annotated_input_dims_mapping( + tensor_desc.name()): + continue + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if op_dist_attr.process_mesh == tensor_dist_attr.process_mesh: + tensor_dims_mapping = tensor_dist_attr.dims_mapping + op_dims_mapping = op_dist_attr.get_input_dims_mapping( + tensor_desc.name()) + compatible_dims_mapping = compute_compatible_dims_mapping( + [op_dims_mapping, tensor_dims_mapping]) + if not _validate_dims_mapping( + compatible_dims_mapping, + op_dist_attr.process_mesh): + continue + if (compatible_dims_mapping is not None) and \ + (compatible_dims_mapping != op_dims_mapping): + op_dist_attr.set_input_dims_mapping( + tensor_desc.name(), compatible_dims_mapping) + changed = True + # Find the most compatible implemenetations from the distributed operator + op_dist_impls = find_compatible_distributed_operator_impls(dist_op, + fwd=True) + if op_dist_impls is not None: + not_compatible = True + backup_op_dist_attr = copy.deepcopy(op_dist_attr) + backup_changed = changed + for op_dist_impl in op_dist_impls: + dim_changed = op_dist_impl.update_dims_mapping(dist_op) + if dim_changed: + changed = True + if op_dist_impl.is_auto_compatible(dist_op) \ + and dist_op.validate_dist_attr(): + if op_dist_impl.type == "elementwise": + op_dist_attr.impl_type = "default" + else: + op_dist_attr.impl_type = op_dist_impl.type + # op_dist_attr.impl_type = op_dist_impl.type + op_dist_attr.impl_idx = op_dist_impl.idx + not_compatible = False + break + else: + dist_op.dist_attr = backup_op_dist_attr + changed = backup_changed + if not_compatible: + dist_op.dist_attr = original_op_dist_attr + changed = False + else: + dist_op.dist_attr = original_op_dist_attr + changed = False + else: + for tensor_node in op_node.outputs: + if tensor_node.is_var() and tensor_node.var() is not None: + if tensor_node.var().type() == core.VarDesc.VarType.READER: + continue + tensor_desc = tensor_node.var() + if op_dist_attr.is_annotated_output_dims_mapping( + tensor_desc.name()): + continue + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if op_dist_attr.process_mesh == tensor_dist_attr.process_mesh: + tensor_dims_mapping = tensor_dist_attr.dims_mapping + op_dims_mapping = op_dist_attr.get_output_dims_mapping( + tensor_desc.name()) + compatible_dims_mapping = compute_compatible_dims_mapping( + [op_dims_mapping, tensor_dims_mapping]) + if not _validate_dims_mapping( + compatible_dims_mapping, + op_dist_attr.process_mesh): + continue + if (compatible_dims_mapping is not None) and \ + (compatible_dims_mapping != op_dims_mapping): + op_dist_attr.set_output_dims_mapping( + tensor_desc.name(), compatible_dims_mapping) + changed = True + # Find the most compatible implemenetations from the distributed operator + op_dist_impls = find_compatible_distributed_operator_impls( + dist_op, fwd=False) + if op_dist_impls is not None: + not_compatible = True + backup_op_dist_attr = copy.deepcopy(op_dist_attr) + backup_changed = changed + for op_dist_impl in op_dist_impls: + dim_changed = op_dist_impl.update_dims_mapping(dist_op) + if dim_changed: + changed = True + if op_dist_impl.is_auto_compatible(dist_op) \ + and dist_op.validate_dist_attr(): + if op_dist_impl.type == "elementwise": + op_dist_attr.impl_type = "default" + else: + op_dist_attr.impl_type = op_dist_impl.type + # op_dist_attr.impl_type = op_dist_impl.type + op_dist_attr.impl_idx = op_dist_impl.idx + not_compatible = False + break + else: + dist_op.dist_attr = backup_op_dist_attr + changed = backup_changed + if not_compatible: + dist_op.dist_attr = original_op_dist_attr + changed = False + else: + dist_op.dist_attr = original_op_dist_attr + changed = False + return changed + + def _update_dims_mapping_between_graphs(self): + changed = False + for parent_node, child_node in self._node_pairs_between_graphs: + parent_node_dist_attr = self._dist_context.get_dist_attr_for_graph( + parent_node) + child_node_dist_attr = self._dist_context.get_dist_attr_for_graph( + child_node) + if parent_node_dist_attr.process_mesh != child_node_dist_attr.process_mesh: + continue + parent_node_dims_mapping = parent_node_dist_attr.dims_mapping + child_node_dims_mapping = child_node_dist_attr.dims_mapping + compatible_dims_mapping = compute_compatible_dims_mapping( + [parent_node_dims_mapping, child_node_dims_mapping]) + if not _validate_dims_mapping(compatible_dims_mapping, + parent_node_dist_attr.process_mesh): + return False + if (compatible_dims_mapping is not None) \ + and (compatible_dims_mapping != parent_node_dims_mapping): + parent_node_dist_attr.dims_mapping = compatible_dims_mapping + changed = True + if (compatible_dims_mapping is not None) \ + and (compatible_dims_mapping != child_node_dims_mapping): + child_node_dist_attr.dims_mapping = compatible_dims_mapping + changed = True + return changed + + def _update_dims_mapping_for_special(self): + # Set the dims_mapping of a tensor to the dims_mapping inside the op which produces it + op_nodes = self._dist_context._serial_ordered_op_nodes + # NOTE: this list may be changed if Paddle changes the existing rules. + related_reader_ops = [ + "create_py_reader", "create_double_buffer_reader", "read" + ] + for op_node in op_nodes: + if op_node.op() is not None \ + and op_node.op().type() in related_reader_ops: + continue + op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node) + for tensor_node in op_node.outputs: + if tensor_node.is_var() and tensor_node.var() is not None: + if tensor_node.var().type() == core.VarDesc.VarType.READER: + continue + tensor_desc = tensor_node.var() + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if op_dist_attr.process_mesh == tensor_dist_attr.process_mesh: + op_dims_mapping = op_dist_attr.get_output_dims_mapping( + tensor_desc.name()) + tensor_dist_attr.dims_mapping = op_dims_mapping + + def _update_dims_mapping(self): + # Complete dims_mapping for each node + reach_fix_point = False + while not reach_fix_point: + changed = False + for is_fwd in [True, False]: + all_nodes = self._dist_context.serial_ordered_nodes \ + if is_fwd else reversed(self._dist_context.serial_ordered_nodes) + for node in all_nodes: + if node.is_var() and node.var() is not None: + tensor_changed = self._update_tensor_node_dims_mapping( + node, fwd=is_fwd) + if tensor_changed: + changed = True + if node.is_op() and node.op() is not None: + op_changed = self._update_op_node_dims_mapping( + node, fwd=is_fwd) + if op_changed: + changed = True + graph_changed = self._update_dims_mapping_between_graphs() + if graph_changed: + changed = True + if changed: + reach_fix_point = False + else: + reach_fix_point = True + # NOTE: this will be removed after changing the reshard rule + self._update_dims_mapping_for_special() + + def _update_process_mesh_by_nearest(self, op_node, nearest_op_node): + op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node) + # Set the process mesh of the op node by its nearest op node + if not op_dist_attr.is_annotated("process_mesh"): + process_mesh = op_dist_attr.process_mesh + nearest_op_dis_attr = self._dist_context.get_dist_attr_for_graph( + nearest_op_node) + nearest_process_mesh = nearest_op_dis_attr.process_mesh + compatible_process_mesh = compute_compatible_process_mesh( + [process_mesh, nearest_process_mesh]) + if compatible_process_mesh is not None \ + and process_mesh != compatible_process_mesh: + op_dist_attr.process_mesh = compatible_process_mesh + # Skip the process_mesh setting of inputs and outputs of while_op + if op_dist_attr.op_type == "while": + return + # Set the process mesh of the op node's leaf-inputs + for tensor_node in op_node.inputs: + if tensor_node.is_var() and tensor_node.var() is not None: + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if tensor_dist_attr.is_annotated("process_mesh"): + continue + # Skip the non-leaf var node + if len(tensor_node.inputs) != 0: + continue + compatible_process_mesh = compute_compatible_process_mesh( + [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]) + if compatible_process_mesh is not None \ + and tensor_dist_attr.process_mesh != compatible_process_mesh: + tensor_dist_attr.process_mesh = compatible_process_mesh + # Set the process mesh of the op node's outputs + for tensor_node in op_node.outputs: + if tensor_node.is_var() and tensor_node.var() is not None: + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if tensor_dist_attr.is_annotated("process_mesh"): + continue + compatible_process_mesh = compute_compatible_process_mesh( + [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]) + if compatible_process_mesh is not None \ + and tensor_dist_attr.process_mesh != compatible_process_mesh: + tensor_dist_attr.process_mesh = compatible_process_mesh + + def _update_process_mesh_for_specials(self): + + def _find_nearest_tensor_node_before(nodes, idx, var_name): + for node in reversed(nodes[:idx]): + if node.is_var() and node.var() is not None \ + and node.var().name() == var_name: + return node + + def _find_nearest_tensor_node_after(nodes, idx, var_name): + for node in nodes[idx + 1:]: + if node.is_var() and node.var() is not None \ + and node.var().name() == var_name: + return node + + def _find_nodes_related_to_cond(source_node): + related_nodes = [] + visited = set() + frontier = list() + frontier.append(source_node) + # BFS + while len(frontier) != 0: + cur = frontier[0] + frontier = frontier[1:] + if _node_id(cur) in visited: + continue + # TODO: need more restrictions + neighbors = cur.inputs + cur.outputs + for node in neighbors: + if node.is_var() and node.var() is not None: + if node.var().type() != core.VarDesc.VarType.READER \ + and len(node.var().shape()) == 1: + frontier.append(node) + related_nodes.append(node) + if node.is_op() and node.op() is not None: + flag = True + if node.op().type() == "create_py_reader" \ + or node.op().type() == "create_double_buffer_reader" \ + or node.op().type() == "read": + flag = False + for tensor_node in node.inputs: + if tensor_node.is_var() and tensor_node.var( + ) is not None: + if tensor_node.var().type() in __not_shape_var_type__ \ + or len(tensor_node.var().shape()) != 1: + flag = False + break + for tensor_node in node.outputs: + if tensor_node.is_var() and tensor_node.var( + ) is not None: + if tensor_node.var().type() in __not_shape_var_type__ \ + or len(tensor_node.var().shape()) != 1: + flag = False + break + if flag: + frontier.append(node) + related_nodes.append(node) + visited.add(_node_id(cur)) + return related_nodes + + def _make_dims_mapping_replicate(dist_attr): + if isinstance(dist_attr, TensorDistributedAttribute): + for i, _ in enumerate(dist_attr.dims_mapping): + dist_attr.dims_mapping[i] = -1 + if isinstance(dist_attr, OperatorDistributedAttribute): + for arg_name in dist_attr.inputs_dist_attrs.keys(): + new_dims_mapping = [] + dims_mapping = dist_attr.get_input_dims_mapping(arg_name) + for _ in dims_mapping: + new_dims_mapping.append(-1) + dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping) + for arg_name in dist_attr.outputs_dist_attrs.keys(): + new_dims_mapping = [] + dims_mapping = dist_attr.get_output_dims_mapping(arg_name) + for _ in dims_mapping: + new_dims_mapping.append(-1) + dist_attr.set_output_dims_mapping(arg_name, + new_dims_mapping) + + # Amend the process meshes related to while_op + for while_op_node, while_op_node_idx in self._while_op_nodes.values(): + sub_graph_id = while_op_node.op()._block_attr_id("sub_block") + sub_graph = self._dist_context.serial_graph.get_sub_graph( + sub_graph_id) + sub_graph_nodes = list(sub_graph.all_nodes()) + while_dist_op = self._dist_context.get_dist_op_for_graph( + while_op_node) + while_op_dist_attr = while_dist_op.dist_attr + + # Step 1: set the process mesh of while_op to the merged process mesh of its subblock + merged_process_mesh = while_op_dist_attr.process_mesh + for node in sub_graph_nodes: + if (node.is_var() and node.var() is not None) \ + or (node.is_op() and node.op() is not None): + dist_attr = self._dist_context.get_dist_attr_for_graph(node) + merged_process_mesh = merge_process_mesh_two( + merged_process_mesh, dist_attr.process_mesh) + while_op_dist_attr.process_mesh = merged_process_mesh + _make_dims_mapping_replicate(while_op_dist_attr) + + # Step 2: set the related nodes of while_op to the process mesh of while_op + # Step 2.1: Find related nodes of cond var the graph of while_op + cond_tensor_related_nodes = [] + cond_tensor_name = while_op_node.op().input("Condition")[0] + cond_tensor_node = None + for node in while_op_node.inputs: + if node.is_var() and node.var() is not None \ + and node.var().name() == cond_tensor_name: + cond_tensor_node = node + cond_tensor_related_nodes.append(cond_tensor_node) + break + + cond_tensor_related_nodes.extend( + _find_nodes_related_to_cond(cond_tensor_node)) + + # Step 2.2: Find related nodes of cond var in the subgraph of while_op + cond_tensor_node = None + for node in reversed(sub_graph_nodes): + if node.is_var() and node.var() is not None \ + and node.var().name() == cond_tensor_name \ + and len(node.outputs) == 0: + cond_tensor_node = node + break + + cond_tensor_related_nodes.extend( + _find_nodes_related_to_cond(cond_tensor_node)) + # Step 2.3: Add the StepScops output of while_op + stepscopes_tensor_name = while_op_node.op().output("StepScopes")[0] + stepscopes_tensor_node = None + for output_node in while_op_node.outputs: + if output_node.is_var() and output_node.var() is not None \ + and output_node.var().name() == stepscopes_tensor_name: + stepscopes_tensor_node = output_node + cond_tensor_related_nodes.append(stepscopes_tensor_node) + # Step 2.4: Set the process meshes of all nodes related to cond var to the process mesh of while op + for node in cond_tensor_related_nodes: + tensor_dist_attr = self._dist_context.get_dist_attr_for_graph( + node) + tensor_dist_attr.process_mesh = merged_process_mesh + _make_dims_mapping_replicate(tensor_dist_attr) + + # Step 3: set the process meshes of the inputs in while_op to the process meshes of the outside input nodes + while_op_inputs_dist_attrs = while_op_dist_attr.inputs_dist_attrs + for tensor_name, tensor_dist_attr in while_op_inputs_dist_attrs.items( + ): + nearest_tensor_node = _find_nearest_tensor_node_before( + self._dist_context.serial_ordered_nodes, while_op_node_idx, + tensor_name) + nearest_tensor_dist_attr = self._dist_context.get_dist_attr_for_graph( + nearest_tensor_node) + tensor_dist_attr.process_mesh = nearest_tensor_dist_attr.process_mesh + + # Step 4: set the process meshes of the outputs in while_op to the process meshes of the outside output nodes + while_op_outputs_dist_attrs = while_op_dist_attr.outputs_dist_attrs + for tensor_name, tensor_dist_attr in while_op_outputs_dist_attrs.items( + ): + nearest_tensor_node = _find_nearest_tensor_node_before( + self._dist_context.serial_ordered_nodes, while_op_node_idx, + tensor_name) + if nearest_tensor_node is None: + nearest_tensor_node = _find_nearest_tensor_node_after( + self._dist_context.serial_ordered_nodes, + while_op_node_idx, tensor_name) + nearest_tensor_dist_attr = self._dist_context.get_dist_attr_for_graph( + nearest_tensor_node) + tensor_dist_attr.process_mesh = nearest_tensor_dist_attr.process_mesh + + # Amend the process meshes related to array + for array_node_list in self._array_nodes.values(): + merged_process_mesh = None + for array_node in array_node_list: + dist_attr = self._dist_context.get_dist_attr_for_graph( + array_node) + merged_process_mesh = merge_process_mesh_two( + merged_process_mesh, dist_attr.process_mesh) + for array_node in array_node_list: + dist_attr = self._dist_context.get_dist_attr_for_graph( + array_node) + dist_attr.process_mesh = merged_process_mesh + _make_dims_mapping_replicate(dist_attr) + + def _update_process_mesh_between_graphs(self): + for parent_node, child_node in self._node_pairs_between_graphs: + parent_node_dist_attr = self._dist_context.get_dist_attr_for_graph( + parent_node) + child_node_dist_attr = self._dist_context.get_dist_attr_for_graph( + child_node) + parent_node_dist_attr.process_mesh = child_node_dist_attr.process_mesh + compatible_process_mesh = compute_compatible_process_mesh([ + parent_node_dist_attr.process_mesh, + child_node_dist_attr.process_mesh + ]) + if compatible_process_mesh is not None \ + and parent_node_dist_attr.process_mesh != compatible_process_mesh: + parent_node_dist_attr.process_mesh = compatible_process_mesh + if compatible_process_mesh is not None \ + and child_node_dist_attr.process_mesh != compatible_process_mesh: + child_node_dist_attr.process_mesh = compatible_process_mesh + + def _update_process_mesh(self): + ordered_op_nodes = self._dist_context._serial_ordered_op_nodes + + # Step 1: Set the annotated process meshes from tensors to the first ops using them + ordered_tensor_nodes = self._dist_context._serial_ordered_tensor_nodes + for tensor_node in ordered_tensor_nodes: + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + if not tensor_dist_attr.is_annotated("process_mesh"): + continue + first_op_node = None + for op_node in ordered_op_nodes: + # TODO: Need a better rule for the control flow ops. + # For now, do not set the process mesh of while_op from its inputs + if op_node.op().type() == "while": + continue + for input_tensor_node in op_node.inputs: + if _node_id(tensor_node) == _node_id(input_tensor_node): + first_op_node = op_node + break + if first_op_node is not None: + break + if first_op_node is None: + continue + op_dist_attr = self._dist_context.get_dist_attr_for_graph( + first_op_node) + if op_dist_attr is not None and not op_dist_attr.is_annotated( + "process_mesh"): + compatible_process_mesh = compute_compatible_process_mesh( + [tensor_dist_attr.process_mesh, op_dist_attr.process_mesh]) + if compatible_process_mesh is not None \ + and op_dist_attr.process_mesh != compatible_process_mesh: + op_dist_attr.process_mesh = compatible_process_mesh + + # Step 2: set the process meshes of ops with the nearest op before them + # Step 2.1: find the first op node which has the process mesh + idx_of_first_op_node_has_process_mesh = -1 + for idx, op_node in enumerate(ordered_op_nodes): + op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node) + if op_dist_attr.process_mesh is not None \ + and idx_of_first_op_node_has_process_mesh == -1: + idx_of_first_op_node_has_process_mesh = idx + # Reuse the following method to set the related tensors for same op node + self._update_process_mesh_by_nearest(op_node, op_node) + # Step 2.2: set the process meshes of ops by the nearest op node after the first op node + if idx_of_first_op_node_has_process_mesh + 1 > len(ordered_op_nodes): + return None + for idx, op_node in enumerate( + ordered_op_nodes[idx_of_first_op_node_has_process_mesh + 1:]): + original_idx = idx_of_first_op_node_has_process_mesh + idx + 1 + nearest_op_node = ordered_op_nodes[original_idx - 1] + nearest_op_dist_attr = self._dist_context.get_dist_attr_for_graph( + nearest_op_node) + op_dist_attr = self._dist_context.get_dist_attr_for_graph(op_node) + assert nearest_op_dist_attr.process_mesh is not None + self._update_process_mesh_by_nearest(op_node, nearest_op_node) + # Step 2.3: set the process meshes of ops by the nearest op node before the first op node + nearest_op_node = ordered_op_nodes[ + idx_of_first_op_node_has_process_mesh] + for op_node in ordered_op_nodes[:idx_of_first_op_node_has_process_mesh]: + self._update_process_mesh_by_nearest(op_node, nearest_op_node) + + # Step 3: adjust the process meshes for special ops + self._update_process_mesh_for_specials() + + # Step 4: adjust the process meshes between graphs + self._update_process_mesh_between_graphs() + + def _prepare(self): + if self._has_prepared: + return + self._while_op_nodes = {} + self._array_nodes = {} + self._node_pairs_between_graphs = [] + all_nodes = self._dist_context.serial_ordered_nodes + for idx, node in enumerate(all_nodes): + if node.is_op(): + if node.op().type() == "while": + self._while_op_nodes[_node_id(node)] = (node, idx) + if node.op().type() == "read_from_array": + array_var_name = node.op().input("X")[0] + if self._array_nodes.get(array_var_name, None) is None: + self._array_nodes[array_var_name] = [] + self._array_nodes[array_var_name].append(node) + # Add the array input node + self._array_nodes[array_var_name].append(node.inputs[0]) + if node.op().type() == "write_to_array": + array_var_name = node.op().output("Out")[0] + if self._array_nodes.get(array_var_name, None) is None: + self._array_nodes[array_var_name] = [] + self._array_nodes[array_var_name].append(node) + self._array_nodes[array_var_name].append(node.outputs[0]) + if node.is_var() and node.var() is not None: + if node.node.graph_id() != 0: + for before_node in reversed(all_nodes[:idx]): + if before_node.is_var() and before_node.var() is not None \ + and before_node.node.graph_id() == node.node.graph_id() - 1 \ + and before_node.var().name() == node.var().name(): + self._node_pairs_between_graphs.append( + (before_node, node)) + for after_node in all_nodes[idx + 1:]: + if after_node.is_var() and after_node.var() is not None \ + and after_node.node.graph_id() == node.node.graph_id() - 1 \ + and after_node.var().name() == node.var().name(): + self._node_pairs_between_graphs.append( + (after_node, node)) + self._has_prepared = True + + def complete_forward_annotation(self, serial_main_program=None): + """ Complete annotation for the partial annotated serial_main_program. + Arguments: + serial_main_program: partial annotated serial_main_program. + Returns:e + serial_main_program: completed annotated serial_main_program. + """ + + if serial_main_program is None: + serial_main_program = self._dist_context.serial_main_program + else: + self._dist_context._serial_main_program = serial_main_program + + start_time = time.time() + # print("start time", start_time, flush=True) + if not self._dist_context.data_parallel: + self._dist_context.initialize(with_graph=True) + + # self._dist_context.validate_dist_attr_for_program() + + self._prepare() + + self._update_process_mesh() + + self._update_dims_mapping() + + # Copy the corresponding distributed attribute from graph to serial_main_program + self._dist_context.copy_dist_attr_from_graph_to_program() + else: + self._dist_context.initialize(with_graph=False) + + # A fast and special completion for data parallel + self._update_dist_attr_for_dp() + + # print_program_with_dist_attr(self._dist_context.serial_main_program, + # self._dist_context) + + # NOTE:[HighOrderGrad] update vars and ops distributed attribute in high order gradient + self._complete_high_order_grad_annotation(serial_main_program) + + # Do the validation check and amend some completion + self._dist_context.amend_dist_attr_for_program() + + self._dist_context.validate_dist_attr_for_program() + + end_time = time.time() + # print("end time", end_time, flush=True) + # print("elapsed time", end_time - start_time, flush=True) + + return serial_main_program + + def _update_dist_attr_for_dp(self): + # TODO: we must ensure the world process group contains all ranks + ranks = get_world_process_group().ranks + process_mesh = ProcessMesh(ranks) + for dist_tensor in self._dist_context._dist_tensors_for_program.values( + ): + serial_tensor = dist_tensor.serial_tensor + tensor_dist_attr = dist_tensor.dist_attr + tensor_dist_attr.process_mesh = process_mesh + + for dist_op in self._dist_context._dist_ops_for_program.values(): + serial_op = dist_op.serial_op + op_desc = serial_op.desc + op_dist_attr = dist_op.dist_attr + op_dist_attr.process_mesh = process_mesh + original_op_dist_attr = copy.deepcopy(op_dist_attr) + input_xshape_arg_names = [] + if "XShape" in op_desc.input_names(): + input_xshape_arg_names = op_desc.input("XShape") + for arg_name in serial_op.input_arg_names: + serial_tensor = dist_op.get_serial_input(arg_name) + if not serial_tensor.is_parameter: + if arg_name not in input_xshape_arg_names: + old_dims_mapping = op_dist_attr.get_input_dims_mapping( + arg_name) + if len(old_dims_mapping) > 0: + new_dims_mapping = [0] + [ + -1 for _ in range(len(old_dims_mapping) - 1) + ] + op_dist_attr.set_input_dims_mapping( + arg_name, new_dims_mapping) + else: + old_dims_mapping = op_dist_attr.get_input_dims_mapping( + arg_name) + if len(old_dims_mapping) > 1: + new_dims_mapping = [-1, 0] + [ + -1 for _ in range(len(old_dims_mapping) - 2) + ] + op_dist_attr.set_input_dims_mapping( + arg_name, new_dims_mapping) + # Set tensor's dims_mapping by the op's + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + serial_tensor) + tensor_dist_attr.dims_mapping = op_dist_attr.get_input_dims_mapping( + arg_name) + output_xshape_arg_names = [] + if "XShape" in op_desc.output_names(): + output_xshape_arg_names = op_desc.output("XShape") + for arg_name in serial_op.output_arg_names: + serial_tensor = dist_op.get_serial_output(arg_name) + if not serial_tensor.is_parameter: + if arg_name not in output_xshape_arg_names: + old_dims_mapping = op_dist_attr.get_output_dims_mapping( + arg_name) + if len(old_dims_mapping) > 0: + new_dims_mapping = [0] + [ + -1 for _ in range(len(old_dims_mapping) - 1) + ] + op_dist_attr.set_output_dims_mapping( + arg_name, new_dims_mapping) + else: + old_dims_mapping = op_dist_attr.get_output_dims_mapping( + arg_name) + if len(old_dims_mapping) > 1: + new_dims_mapping = [-1, 0] + [ + -1 for _ in range(len(old_dims_mapping) - 2) + ] + op_dist_attr.set_output_dims_mapping( + arg_name, new_dims_mapping) + # Set tensor's dims_mapping by the op's + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + serial_tensor) + tensor_dist_attr.dims_mapping = op_dist_attr.get_output_dims_mapping( + arg_name) + + op_dist_impls = find_compatible_distributed_operator_impls( + dist_op, partial=False) + if op_dist_impls is not None: + not_compatible = True + backup_op_dist_attr = copy.deepcopy(op_dist_attr) + for op_dist_impl in op_dist_impls: + op_dist_impl.update_dims_mapping(dist_op) + if op_dist_impl.is_auto_compatible(dist_op) \ + and dist_op.validate_dist_attr(): + op_dist_attr.impl_type = op_dist_impl.type + op_dist_attr.impl_idx = op_dist_impl.idx + not_compatible = False + break + else: + dist_op.dist_attr = backup_op_dist_attr + if not_compatible: + dist_op.dist_attr = original_op_dist_attr + else: + dist_op.dist_attr = original_op_dist_attr + + def _complete_tensor_dist_attr_by_op(self, serial_main_program=None): + if serial_main_program is None: + serial_main_program = self._dist_context.serial_main_program + else: + self._dist_context._serial_main_program = serial_main_program + + self._dist_context.initialize() + + self._prepare() + + has_set_dist_attr = set() + + all_nodes = self._dist_context.serial_ordered_nodes + for node in all_nodes: + if node.is_op(): + if node.op().type() in ["while"]: + continue + dist_op = self._dist_context.get_dist_op_for_graph(node) + op_dist_attr = dist_op.dist_attr + for tensor_node in node.inputs: + if tensor_node.is_var() and tensor_node.var() is not None: + # Skip the non-leaf var node + if len(tensor_node.inputs) != 0: + continue + tensor_desc = tensor_node.var() + tensor_name = tensor_desc.name() + tensor = dist_op.get_serial_input(tensor_name) + # Use the first op to set the tensor dist attr + if tensor_name in has_set_dist_attr: + continue + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + tensor_dist_attr.process_mesh = op_dist_attr.process_mesh + tensor_dist_attr.dims_mapping = op_dist_attr.get_input_dims_mapping( + tensor_name) if tensor.is_parameter else [ + -1 for i in tensor_desc.shape() + ] + has_set_dist_attr.add(tensor_name) + for tensor_node in node.outputs: + if tensor_node.is_var() and tensor_node.var() is not None: + tensor_name = tensor_node.var().name() + if tensor_name in has_set_dist_attr: + continue + tensor_dist_attr = self._dist_context.get_tensor_dist_attr_for_graph( + tensor_node) + tensor_dist_attr.process_mesh = op_dist_attr.process_mesh + tensor_dist_attr.dims_mapping = op_dist_attr.get_output_dims_mapping( + tensor_name) + has_set_dist_attr.add(tensor_name) + + self._update_process_mesh_for_specials() + + self._update_process_mesh_between_graphs() + + self._update_dims_mapping_for_special() + + self._update_dims_mapping_between_graphs() + + # Copy the corresponding distributed attribute from graph to serial_main_program + self._dist_context.copy_dist_attr_from_graph_to_program() + + # Do the validation check and amend some completion + self._dist_context.amend_dist_attr_for_program() + + self._dist_context.validate_dist_attr_for_program() + + def _complete_high_order_grad_annotation(self, serial_main_program=None): + """ + NOTE: + [HighOrderGrad] Complete the annotation of vars and ops only for high order gradient. + This function is temporary to support high order gradient, and will be removed in the future. + """ + + if serial_main_program is None: + serial_main_program = self._dist_context.serial_main_program + else: + self._dist_context._serial_main_program = serial_main_program + + def _is_grad_var_name(name): + if "@GRAD" in name: + return True + return False + + def _get_op_by_id(ops, id): + for op in ops: + if op.desc.original_id() == id: + return op + return None + + ops = list(serial_main_program.global_block().ops) + vars = serial_main_program.global_block().vars + dist_op_context = self._dist_context.dist_op_context + grad_var_to_var = dist_op_context.grad_var_to_var + + appended_grad_times = 0 + for idx in range(0, len(ops)): + op = ops[idx] + if int(op.attr('op_role')) == int( + core.op_proto_and_checker_maker.OpRole.Forward): + continue + + if int(op.attr('op_role')) == int( + core.op_proto_and_checker_maker.OpRole.Backward) and int( + ops[idx - 1].attr('op_role')) == int( + core.op_proto_and_checker_maker.OpRole.Forward): + appended_grad_times += 1 + + if int(op.attr('op_role')) == int( + int(core.op_proto_and_checker_maker.OpRole.Backward) + | int(core.op_proto_and_checker_maker.OpRole.Loss)): + assert op.type == "fill_constant" + break + + # complete the annotation of grad op (xxx_grad op or sum op) + # xxx_grad op will have a corresponding forward op in grad_op_id_to_op_id + grad_op = ops[idx] + if grad_op.desc.original_id( + ) in dist_op_context.grad_op_id_to_op_id: + # TODO support the case where one forward op corresponding to multiple xxx_grad op + forward_op = _get_op_by_id( + ops, dist_op_context.grad_op_id_to_op_id[ + grad_op.desc.original_id()]) + assert forward_op is not None + + fwd_op_dist_attr = self._dist_context.get_op_dist_attr_for_program( + forward_op) + fwd_op_process_mesh = fwd_op_dist_attr.process_mesh + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = fwd_op_process_mesh + + for input_name in grad_op.input_arg_names: + if input_name not in forward_op.input_arg_names and input_name not in forward_op.output_arg_names: + if input_name in grad_var_to_var[appended_grad_times]: + fwd_name = grad_var_to_var[appended_grad_times][ + input_name] + ref_dims_mapping = fwd_op_dist_attr.get_output_dims_mapping( + fwd_name) + else: + input_var = vars[input_name] + ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program( + input_var).dims_mapping + else: + if fwd_op_dist_attr.get_input_dims_mapping(input_name): + ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping( + input_name) + else: + ref_dims_mapping = fwd_op_dist_attr.get_output_dims_mapping( + input_name) + assert ref_dims_mapping is not None, "[{}] 's dims mapping is NONE".format( + input_name) + grad_op_dist_attr.set_input_dims_mapping( + input_name, ref_dims_mapping) + + for output_name in grad_op.output_arg_names: + assert output_name in grad_var_to_var[appended_grad_times] + fwd_name = grad_var_to_var[appended_grad_times][output_name] + ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping( + fwd_name) + # var + output_var = vars[output_name] + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_dims_mapping + tensor_dist_attr.process_mesh = fwd_op_process_mesh + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + # op + grad_op_dist_attr.set_output_dims_mapping( + output_name, ref_dims_mapping) + + self._dist_context.set_op_dist_attr_for_program( + grad_op, grad_op_dist_attr) + + # grad ops that have not a corresponding mapping in grad_op_id_to_op_id + else: + + if grad_op.type == 'sum': + assert all(map(_is_grad_var_name, grad_op.input_arg_names)) + output_name = grad_op.output_arg_names[0] + assert output_name in grad_var_to_var[appended_grad_times], \ + "sum op's output '{}' has no corresponding var".format( + output_name) + ref_fwd_var_name = grad_var_to_var[appended_grad_times][ + output_name] + ref_fwd_var = vars[ref_fwd_var_name] + ref_fwd_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + ref_fwd_var) + ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping + ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh + # output + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_fwd_dims_mapping + tensor_dist_attr.process_mesh = ref_fwd_process_mesh + output_var = vars[output_name] + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + # op + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = ref_fwd_process_mesh + for var_name in grad_op.input_arg_names: + grad_op_dist_attr.set_input_dims_mapping( + var_name, ref_fwd_dims_mapping) + grad_op_dist_attr.set_output_dims_mapping( + output_name, ref_fwd_dims_mapping) + + elif grad_op.type == 'fill_any_like': + ref_var_name = grad_op.input_arg_names[0] + ref_var = vars[ref_var_name] + ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + ref_var) + ref_dims_mapping = ref_dist_attr.dims_mapping + ref_process_mesh = ref_dist_attr.process_mesh + # output + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_dims_mapping + tensor_dist_attr.process_mesh = ref_process_mesh + output_var_name = grad_op.output_arg_names[0] + output_var = vars[output_var_name] + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + # op + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = ref_process_mesh + grad_op_dist_attr.set_input_dims_mapping( + ref_var_name, ref_dims_mapping) + grad_op_dist_attr.set_output_dims_mapping( + output_var_name, ref_dims_mapping) + + elif grad_op.type in ['shape', 'fill_constant']: + continue + + else: + raise ValueError("got unexpect op [{}]".format( + str(grad_op.type))) + + self._dist_context.set_op_dist_attr_for_program( + grad_op, grad_op_dist_attr) + + def complete_backward_annotation(self, serial_main_program=None): + """Complete the annotation of vars and ops in the backward phase for parallel program.""" + + if serial_main_program is None: + serial_main_program = self._dist_context.serial_main_program + else: + self._dist_context._serial_main_program = serial_main_program + + def _is_grad_var_name(name): + if "@GRAD" in name: + return True + return False + + def _get_forward_varname_from_grad_varname(grad_var_name): + assert _is_grad_var_name( + grad_var_name), "[{}] is not a grad varnme.".format( + grad_var_name) + return grad_var_name[:grad_var_name.find("@GRAD")] + + def _get_op_by_id(ops, id): + for op in ops: + if op.desc.original_id() == id: + return op + return None + + first_backward_op_idx = -1 + for idx, op in enumerate(serial_main_program.global_block().ops): + if int(op.attr('op_role')) == int( + int(core.op_proto_and_checker_maker.OpRole.Backward) + | int(core.op_proto_and_checker_maker.OpRole.Loss)): + assert op.type == "fill_constant" + first_backward_op_idx = idx + break + + assert first_backward_op_idx >= 0, "No backward procedure found in this program." + + ops = list(serial_main_program.global_block().ops) + vars = serial_main_program.global_block().vars + dist_op_context = self._dist_context.dist_op_context + grad_var_to_var = dist_op_context.grad_var_to_var[len( + dist_op_context.grad_var_to_var)] + + for idx in range(first_backward_op_idx, len(ops)): + + # complete the initial grad loss op + if idx == first_backward_op_idx: + assert ops[idx].type == "fill_constant" + assert len( + ops[idx].input_arg_names + ) == 0, "first backward op should has only ONE output, but got [{}]".format( + len(ops[idx].input_arg_names)) + assert len( + ops[idx].output_arg_names + ) == 1, "first backward op should has only ONE output, but got [{}]".format( + len(ops[idx].output_arg_names)) + + grad_var = vars[ops[idx].output_arg_names[0]] + forward_var_name = _get_forward_varname_from_grad_varname( + grad_var.name) + forward_var = vars[forward_var_name] + + # TODO complete other attribte for grad var + tensor_dist_attr = TensorDistributedAttribute() + process_mesh = self._dist_context.get_tensor_dist_attr_for_program( + forward_var).process_mesh + dims_mapping = self._dist_context.get_tensor_dist_attr_for_program( + forward_var).dims_mapping + tensor_dist_attr.dims_mapping = dims_mapping + tensor_dist_attr.process_mesh = process_mesh + self._dist_context.set_tensor_dist_attr_for_program( + grad_var, tensor_dist_attr) + + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = process_mesh + op_dist_attr.set_output_dims_mapping(grad_var.name, + dims_mapping) + self._dist_context.set_op_dist_attr_for_program( + ops[idx], op_dist_attr) + continue + + # complete the annotation of grad op (xxx_grad op or sum op) + # xxx_grad op will have a corresponding forward op in grad_op_id_to_op_id + grad_op = ops[idx] + if grad_op.desc.original_id( + ) in dist_op_context.grad_op_id_to_op_id: + # TODO support the case where one forward op corresponding to multiple xxx_grad op + forward_op = _get_op_by_id( + ops[:first_backward_op_idx], + dist_op_context.grad_op_id_to_op_id[ + grad_op.desc.original_id()]) + assert forward_op is not None + + if grad_op.type == "concat" and forward_op.type == "split": + forward_op_dist_attr = self._dist_context.get_op_dist_attr_for_program( + forward_op) + output_var = vars[grad_op.desc.output('Out')[0]] + split_input_var_name = forward_op.input("X")[0] + ref_dims_mapping = forward_op_dist_attr.get_input_dims_mapping( + split_input_var_name) + ref_mesh = forward_op_dist_attr.process_mesh + + grad_op_dist_attr = OperatorDistributedAttribute() + for input_name in grad_op.input_arg_names: + grad_op_dist_attr.set_input_dims_mapping( + input_name, ref_dims_mapping) + + output_var_dist_attr = TensorDistributedAttribute() + output_var_dist_attr.dims_mapping = ref_dims_mapping + output_var_dist_attr.process_mesh = ref_mesh + self._dist_context.set_tensor_dist_attr_for_program( + output_var, output_var_dist_attr) + + grad_op_dist_attr.set_output_dims_mapping( + output_var.name, ref_dims_mapping) + grad_op_dist_attr.process_mesh = ref_mesh + self._dist_context.set_op_dist_attr_for_program( + grad_op, grad_op_dist_attr) + grad_op_dist_attr.impl_type = fwd_op_dist_attr.impl_type + grad_op_dist_attr.impl_idx = fwd_op_dist_attr.impl_idx + + continue + + fwd_op_dist_attr = self._dist_context.get_op_dist_attr_for_program( + forward_op) + fwd_op_process_mesh = fwd_op_dist_attr.process_mesh + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = fwd_op_process_mesh + + for input_name in grad_op.input_arg_names: + if input_name not in forward_op.input_arg_names and input_name not in forward_op.output_arg_names: + if input_name in grad_var_to_var: + fwd_name = grad_var_to_var[input_name] + ref_dims_mapping = fwd_op_dist_attr.get_output_dims_mapping( + fwd_name) + else: + input_var = vars[input_name] + ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program( + input_var).dims_mapping + else: + if fwd_op_dist_attr.get_input_dims_mapping(input_name): + ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping( + input_name) + else: + ref_dims_mapping = fwd_op_dist_attr.get_output_dims_mapping( + input_name) + assert ref_dims_mapping is not None, "[{}] 's dims mapping is NONE".format( + input_name) + grad_op_dist_attr.set_input_dims_mapping( + input_name, ref_dims_mapping) + + for output_name in grad_op.output_arg_names: + assert output_name in grad_var_to_var + fwd_name = grad_var_to_var[output_name] + ref_dims_mapping = fwd_op_dist_attr.get_input_dims_mapping( + fwd_name) + # var + output_var = vars[output_name] + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_dims_mapping + tensor_dist_attr.process_mesh = fwd_op_process_mesh + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + # op + grad_op_dist_attr.set_output_dims_mapping( + output_name, ref_dims_mapping) + + grad_op_dist_attr.impl_type = fwd_op_dist_attr.impl_type + grad_op_dist_attr.impl_idx = fwd_op_dist_attr.impl_idx + self._dist_context.set_op_dist_attr_for_program( + grad_op, grad_op_dist_attr) + + # grad ops that have not a corresponding mapping in grad_op_id_to_op_id + else: + if grad_op.type == 'sum': + assert all(map(_is_grad_var_name, grad_op.input_arg_names)) + output_name = grad_op.output_arg_names[0] + assert output_name in grad_var_to_var, "sum op's output '{}' has no corresponding var".format( + output_name) + ref_fwd_var_name = grad_var_to_var[output_name] + ref_fwd_var = vars[ref_fwd_var_name] + ref_fwd_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + ref_fwd_var) + ref_fwd_dims_mapping = ref_fwd_dist_attr.dims_mapping + ref_fwd_process_mesh = ref_fwd_dist_attr.process_mesh + + # output + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_fwd_dims_mapping + tensor_dist_attr.process_mesh = ref_fwd_process_mesh + output_var = vars[output_name] + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + + # op + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = ref_fwd_process_mesh + for var_name in grad_op.input_arg_names: + grad_op_dist_attr.set_input_dims_mapping( + var_name, ref_fwd_dims_mapping) + grad_op_dist_attr.set_output_dims_mapping( + output_name, ref_fwd_dims_mapping) + grad_op_dist_attr.impl_type = "default" + grad_op_dist_attr.impl_idx = 0 + + elif grad_op.type == 'fill_any_like': + ref_var_name = grad_op.input_arg_names[0] + ref_var = vars[ref_var_name] + ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + ref_var) + ref_dims_mapping = ref_dist_attr.dims_mapping + ref_process_mesh = ref_dist_attr.process_mesh + # output + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = ref_dims_mapping + tensor_dist_attr.process_mesh = ref_process_mesh + output_var_name = grad_op.output_arg_names[0] + output_var = vars[output_var_name] + self._dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + # op + grad_op_dist_attr = OperatorDistributedAttribute() + grad_op_dist_attr.process_mesh = ref_process_mesh + grad_op_dist_attr.set_input_dims_mapping( + ref_var_name, ref_dims_mapping) + grad_op_dist_attr.set_output_dims_mapping( + output_var_name, ref_dims_mapping) + + else: + raise ValueError("got unexpect op [{}]".format( + str(grad_op.type))) + + self._dist_context.set_op_dist_attr_for_program( + grad_op, grad_op_dist_attr) + + def complete_update_annotation(self, serial_main_program): + """Complete the annotation of vars and ops in the update phase for parallel program.""" + # Copy the dist tensors and dist ops annotated by users from the default context + # global mesh + from paddle.distributed.auto_parallel.process_group import get_world_process_group + world_ranks = get_world_process_group().ranks + + # Notice: serial_main_program is actually a dist_main_program of current rank, + # and must be passed into this function. + # TODO: We should fix this behavior. + + ops = list(serial_main_program.global_block().ops) + vars = serial_main_program.global_block().vars + learning_rate_completed = False + + for idx in range(len(ops)): + + # complete the annotation of the optimizer op. + # TODO to add attribute for moment var + op = ops[idx] + if int(op.attr('op_role')) == int(OpRole.Optimize): + if is_gradient_clip_op(op): + if op.type in [ + "sum", "sqrt", "fill_constant", "elementwise_max", + "elementwise_div" + ]: + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = world_ranks + for in_name in op.input_arg_names: + in_var = vars[in_name] + in_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + in_var) + op_dist_attr.set_input_dist_attr( + in_name, in_dist_attr) + for out_name in op.output_arg_names: + out_var = vars[out_name] + out_dist_attr = TensorDistributedAttribute() + out_dist_attr.process_mesh = world_ranks + out_dist_attr.dims_mapping = [ + -1 for _ in range(len(out_var.shape)) + ] + self._dist_context.set_tensor_dist_attr_for_program( + out_var, out_dist_attr) + op_dist_attr.set_output_dist_attr( + out_name, out_dist_attr) + else: + in_var = vars[op.input("X")[0]] + in_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + in_var) + assert in_dist_attr is not None + ref_process_mesh = in_dist_attr.process_mesh + ref_dims_mapping = in_dist_attr.dims_mapping + + if op.type == "cast" and \ + ops[idx + 1].type == "elementwise_mul": + ref_var = vars[ops[idx + 1].input("X")[0]] + ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + ref_var) + assert ref_dist_attr is not None + ref_process_mesh = ref_dist_attr.process_mesh + + out_var = vars[op.output("Out")[0]] + out_dist_attr = TensorDistributedAttribute() + out_dist_attr.process_mesh = ref_process_mesh + if out_var.shape == in_var.shape: + out_dist_attr.dims_mapping = ref_dims_mapping + else: + assert len( + out_var.shape) == 1 and out_var.shape[0] == 1 + out_dist_attr.dims_mapping = [-1] + self._dist_context.set_tensor_dist_attr_for_program( + out_var, out_dist_attr) + + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = ref_process_mesh + op_dist_attr.set_input_dist_attr( + in_var.name, in_dist_attr) + op_dist_attr.set_output_dist_attr( + out_var.name, out_dist_attr) + + self._dist_context.set_op_dist_attr_for_program( + op, op_dist_attr) + + if "Grad" in op.input_names and "Param" in ops[idx].input_names: + assert len( + op.input("Param")) == 1, "Only support one-to-one now." + assert len( + op.input("Grad")) == 1, "Only support one-to-one now." + param = vars[op.input("Param")[0]] + grad_var = vars[op.input("Grad")[0]] + + param_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + param) + assert param_dist_attr is not None + ref_process_mesh = self._dist_context.get_tensor_dist_attr_for_program( + param).process_mesh + assert ref_process_mesh is not None + ref_dims_mapping = self._dist_context.get_tensor_dist_attr_for_program( + param).dims_mapping + assert ref_dims_mapping is not None + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = ref_process_mesh + op_dist_attr.set_input_dims_mapping(grad_var.name, + ref_dims_mapping) + op_dist_attr.set_input_dims_mapping(param.name, + ref_dims_mapping) + op_dist_attr.set_output_dims_mapping( + param.name, ref_dims_mapping) + learning_var = vars[op.input("LearningRate")[0]] + op_dist_attr.set_input_dims_mapping(learning_var.name, [-1]) + op_dist_attr.set_output_dims_mapping( + learning_var.name, [-1]) + + if not learning_rate_completed: + learning_rate_completed = True + var_dist_attr = TensorDistributedAttribute() + var_dist_attr.process_mesh = world_ranks + var_dist_attr.dims_mapping = [-1] + self._dist_context.set_tensor_dist_attr_for_program( + learning_var, var_dist_attr) + + for input_name in op.desc.input_names(): + + if input_name in [ + 'Param', + 'Grad', + 'LearningRate', + "SkipUpdate", + "Beta1Tensor", + "Beta2Tensor", + "EpsilonTensor", + ]: + continue + if len(op.desc.input(input_name)) == 0: + continue + + assert len(op.desc.input(input_name)) == 1 + input_var = vars[op.desc.input(input_name)[0]] + input_var_attr = TensorDistributedAttribute() + + if "Beta1Pow" in input_name or "Beta2Pow" in input_name: + input_var_attr.dims_mapping = [-1] + op_dist_attr.set_input_dims_mapping( + input_var.name, [-1]) + op_dist_attr.set_output_dims_mapping( + input_var.name, [-1]) + else: + input_var_attr.dims_mapping = ref_dims_mapping + op_dist_attr.set_input_dims_mapping( + input_var.name, ref_dims_mapping) + op_dist_attr.set_output_dims_mapping( + input_var.name, ref_dims_mapping) + + input_var_attr.process_mesh = ref_process_mesh + self._dist_context.set_tensor_dist_attr_for_program( + input_var, input_var_attr) + + self._dist_context.set_op_dist_attr_for_program( + op, op_dist_attr) + continue + + def complete_prim_annotation(self, serial_main_program=None): + """ + fill default data parallel annotation for program with primitive operators. + + Arguments: + serial_main_program: partial annotated serial_main_program. + Returns: + serial_main_program: completed annotated serial_main_program. + """ + if serial_main_program is None: + serial_main_program = self._dist_context.serial_main_program + else: + self._dist_context._serial_main_program = serial_main_program + + import time + + start_time = time.time() + self._dist_context._is_initialized = True + + start_time = time.time() + self._dist_context._init_dist_attr_for_program() + + start_time = time.time() + self._init_global_mesh_for_program() + + # Do the validation check and amend some completion + start_time = time.time() + self._dist_context.amend_dist_attr_for_program() + self._dist_context.validate_dist_attr_for_program() + + def _init_global_mesh_for_program(self): + # Copy the dist tensors and dist ops annotated by users from the default context + # global mesh + from paddle.distributed.auto_parallel.process_group import get_world_process_group + world_ranks = get_world_process_group().ranks + + for block in self._dist_context._serial_main_program.blocks: + for tensor in block.vars.values(): + # Copy the distributed tensors in the default context + dist_tensor = self._dist_context.get_dist_tensor_for_program( + tensor) + assert dist_tensor is not None + dist_tensor.dist_attr.process_mesh = world_ranks + for op in block.ops: + # Copy the distributed operators in the default context + dist_op = self._dist_context.get_dist_op_for_program(op) + assert dist_op is not None + dist_op.dist_attr.process_mesh = world_ranks + + # Find the most compatible implemenetations from the distributed operator + op_dist_impls = find_compatible_distributed_operator_impls( + dist_op, fwd=True) + if op_dist_impls is not None: + backup_op_dist_attr = copy.deepcopy(dist_op.dist_attr) + for op_dist_impl in op_dist_impls: + dim_changed = op_dist_impl.update_dims_mapping(dist_op) + if op_dist_impl.is_auto_compatible(dist_op): + if op_dist_impl.type == "elementwise": + dist_op.dist_attr.impl_type = "default" + else: + dist_op.dist_attr.impl_type = op_dist_impl.type + # op_dist_attr.impl_type = op_dist_impl.type + dist_op.dist_attr.impl_idx = op_dist_impl.idx + break + else: + dist_op.dist_attr = backup_op_dist_attr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/constants.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..82c5011faf0af7aad1e8b812af1a4bb880178dc5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/constants.py @@ -0,0 +1,125 @@ +# Copyright (c) 2022 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 + +from collections import defaultdict + +# _g_default_config[category][field] = default_value +_g_default_config = defaultdict(dict) + + +def get_category_default_config(category): + return _g_default_config[category] + + +def set_category_default_config(category, default_value): + _g_default_config[category] = default_value + + +def get_field_default_config(category, field): + return _g_default_config[category][field] + + +def set_field_default_config(category, field, default_value): + _g_default_config[category][field] = default_value + + +NOT_FOUND = "not_found" + +######################################### +# base configuration +######################################### +BASE = "base" +set_field_default_config(BASE, "auto_mode", "semi") +set_field_default_config(BASE, "gradient_scale", True) +set_field_default_config(BASE, "use_cache", True) +set_field_default_config(BASE, "return_numpy", True) +set_field_default_config(BASE, "all_ranks", False) +set_field_default_config(BASE, "split_data", True) +set_field_default_config(BASE, "seed", None) +set_field_default_config(BASE, "reinit", False) # Only for debug + +######################################### +# recompute configuration +######################################### +RECOMPUTE = "recompute" +set_field_default_config(RECOMPUTE, "enable", False) +set_field_default_config(RECOMPUTE, "checkpoints", None) +set_field_default_config(RECOMPUTE, "enable_tuning", False) + +######################################### +# AMP configuration +######################################### +AMP = "amp" +set_field_default_config(AMP, "enable", False) +set_field_default_config(AMP, "init_loss_scaling", 32768.0) +set_field_default_config(AMP, "incr_every_n_steps", 1000) +set_field_default_config(AMP, "decr_every_n_nan_or_inf", 2) +set_field_default_config(AMP, "incr_ratio", 2.0) +set_field_default_config(AMP, "decr_ratio", 0.8) +set_field_default_config(AMP, "use_dynamic_loss_scaling", True) +set_field_default_config(AMP, "custom_white_list", []) +set_field_default_config(AMP, "custom_black_list", []) +set_field_default_config(AMP, "custom_black_varnames", []) +set_field_default_config(AMP, "use_pure_fp16", False) +set_field_default_config(AMP, "use_fp16_guard", True) +set_field_default_config(AMP, "use_optimizer_fp16", False) + +######################################### +# sharding configuration +######################################### +SHARDING = "sharding" +set_field_default_config(SHARDING, "enable", False) +set_field_default_config(SHARDING, "stage", 1) +set_field_default_config(SHARDING, "degree", 8) +set_field_default_config(SHARDING, "segment_broadcast_MB", 32.0) +set_field_default_config(SHARDING, "enable_tuning", False) +set_field_default_config(SHARDING, "tuning_range", []) + +######################################### +# gradient merge configuration +######################################### +GRADIENT_MERGE = "gradient_merge" +set_field_default_config(GRADIENT_MERGE, "enable", False) +set_field_default_config(GRADIENT_MERGE, "k_steps", 1) +set_field_default_config(GRADIENT_MERGE, "avg", True) + +######################################### +# quantization configuration +######################################### +QAT = "qat" +set_field_default_config(QAT, "enable", False) +set_field_default_config(QAT, "channel_wise_abs_max", True) +set_field_default_config(QAT, "weight_bits", 8) +set_field_default_config(QAT, "activation_bits", 8) +set_field_default_config(QAT, "not_quant_pattern", ['skip_quant']) +set_field_default_config(QAT, "algo", None) + +# ######################################### +# auto tuning configuration +# ######################################### +TUNING = "tuning" +set_field_default_config(TUNING, "enable", False) +set_field_default_config(TUNING, "batch_size", 1) +set_field_default_config(TUNING, "dataset", None) +set_field_default_config(TUNING, "profile_start_step", 1) +set_field_default_config(TUNING, "profile_end_step", 1) +set_field_default_config(TUNING, "run_after_tuning", True) +set_field_default_config(TUNING, "verbose", True) + +######################################### +# dataset configuration +######################################### +DATASET = "dataset" +set_field_default_config(DATASET, "enable", False) +set_field_default_config(DATASET, "num_shards", 1) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/converter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..35674be05b0d2f4f6d22b05b0fc6663b96431214 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/converter.py @@ -0,0 +1,457 @@ +# Copyright (c) 2022 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. + +import paddle +import warnings +import logging +import numpy as np +from ..utils.log_utils import get_logger + + +class Converter(object): + """ + Converter is a class object for auto parallel to convert tensors from + one parallel strategy to another one. Tensors will merge and slice value + with their strategy when strategies are different. + """ + + def __init__(self, tensors_dict, pre_strategy, cur_strategy): + """ + Args: + tensors_dict(dict): tensors' value of all ranks that to be converted. + key is tensor's name(str), value is all ranks' data(list(numpy.ndarray)) + pre_strategy(dict): tensors' distributed attribute of last training process. + key is tensor's name(str), value is tensor's distributed attribute in last + training process. + cur_strategy(dict): tensors' distributed attribute of current rank. + key is tensor's name(str), value is tensor's distributed attribute in current + rank. + """ + self._tensors_dict = self._check_tensor_dict(tensors_dict) + self._pre_strategy = self._check_pre_strategy(pre_strategy) + self._cur_strategy = self._check_cur_strategy(cur_strategy) + self._logger = get_logger(logging.INFO) + + def _check_tensor_dict(self, tensors_dict): + if not tensors_dict: + raise ValueError("'tensors_dict' is None, " + "the tensors to be converted cannot be None.") + if not isinstance(tensors_dict, dict): + raise TypeError( + "The type of 'tensors_dict' should be 'dict', but got '{}'.". + format(str(type(tensors_dict)))) + return tensors_dict + + def _check_pre_strategy(self, pre_strategy): + if not pre_strategy: + raise ValueError("'pre_strategy' is None, " + "there are not tensors in pre process.") + if not isinstance(pre_strategy, dict): + raise TypeError("The type of 'pre_strategy' should be 'dict', " + "but got '{}'.".format(str(type(pre_strategy)))) + return pre_strategy + + def _check_cur_strategy(self, cur_strategy): + if not cur_strategy: + warnings.warn("'cur_strategy' is None, " + "there are not tensors in cur process") + if not isinstance(cur_strategy, dict): + raise TypeError("The type of 'cur_strategy' should be 'dict', " + "but got '{}'.".format(str(type(cur_strategy)))) + return cur_strategy + + def convert(self, strict=True): + """ + Convert tensors + + Args: + strict(bool): whether to strict convert tensor with tensor's name. If False, it will + convert tensors by prefix matching. Otherwise, tensors will be converted with + their name strictly. + + Returns: + converted tensors(dict) + + Examples: + .. code-block:: python + + import numpy as np + complete_tensors = np.arange(4).reshape([2, 2]) + partitial_tensors = np.split(complete_tensors, 2, axis=0) + name = "tmp_0" + tensors_dict = {name: partitial_tensors} + strategy_1 = { + name: { + "process_shape": [2], + "process_group": [0, 1], + "dims_mapping": [0, -1] + } + } + strategy_2 = { + name: { + "process_shape": [2], + "process_group": [0, 1], + "dims_mapping": [-1, -1] + } + } + converter = Converter(tensors_dict, strategy_1, strategy_2) + result = converter.convert() + # the result's value is equal to `complete_tensors` + """ + tensors_dict = {} + # the name which is in cur_process but not in pre_process + tensor_not_in_pre = [] + # the name which is in pre_process but not in cur_process + tensor_not_in_cur = [] + # the name which is in strategy but not in ckpt files + tensor_not_in_ckpt = [] + self._logger.info("Start to convert tensors.") + for tensor_name in self._cur_strategy: + if tensor_name not in self._pre_strategy: + tensor_not_in_pre.append(tensor_name) + continue + if tensor_name not in self._tensors_dict: + tensor_not_in_ckpt.append(tensor_name) + continue + self._pre_name = tensor_name + self._cur_name = tensor_name + tensor_list = self._tensors_dict[tensor_name] + pre_dist_attr = self._pre_strategy[tensor_name] + cur_dist_attr = self._cur_strategy[tensor_name] + try: + tensors_dict[tensor_name] = Converter.merge_and_slice( + tensor_list, pre_dist_attr, cur_dist_attr) + except ValueError as err: + raise ValueError( + "Fail to convert tensor '{}'. ".format(str(tensor_name)) + + str(err)) + + for tensor_name in self._pre_strategy: + if tensor_name not in self._cur_strategy: + tensor_not_in_cur.append(tensor_name) + + if not strict: + tensors_dict, tensor_match_with_pre, tensor_match_with_cur = self.convert_with_prefix_match( + tensors_dict, tensor_not_in_pre, tensor_not_in_cur) + else: + tensors_dict, tensor_match_with_pre, tensor_match_with_cur = tensors_dict, [], [] + + tensor_not_in_pre = set(tensor_not_in_pre) - set(tensor_match_with_pre) + tensor_not_in_cur = set(tensor_not_in_cur) - set(tensor_match_with_cur) + if tensor_not_in_pre: + warnings.warn( + "tensors [{}] are not found in last training strategy.".format( + str(tensor_not_in_pre))) + if tensor_not_in_cur: + warnings.warn( + "tensors [{}] are not found in current training strategy.". + format(str(tensor_not_in_cur))) + if tensor_not_in_ckpt: + warnings.warn( + "tensors [{}] are found in pre_strategy, but are not found" + "in checkpoint files, please check your checkpoint files.". + format(str(tensor_not_in_ckpt))) + + return tensors_dict + + def convert_with_prefix_match(self, tensors_dict, tensor_not_in_pre, + tensor_not_in_cur): + # the name which in cur_process and can match with pre_process + tensor_match_with_pre = [] + # the name which in pre_process and can match with cur_process + tensor_match_with_cur = [] + for cur_name in tensor_not_in_pre: + prefix_name = cur_name + while prefix_name.find("_") != -1: + prefix_name = prefix_name[:prefix_name.rfind("_")] + for pre_name in tensor_not_in_cur: + if prefix_name in pre_name: + # 'cur_name' of cur_process can match with 'pre_name' of pre_process + self._pre_name = pre_name + self._cur_name = cur_name + pre_tensor_list = self._tensors_dict[pre_name] + pre_dist_attr = self._pre_strategy[pre_name] + cur_dist_attr = self._cur_strategy[cur_name] + try: + tensors_dict[cur_name] = Converter.merge_and_slice( + pre_tensor_list, pre_dist_attr, cur_dist_attr) + except ValueError as err: + raise ValueError( + "Fail to convert tensor '{}' by '{}'. ".format( + str(cur_name), str(pre_name)) + str(err)) + self._logger.info( + "tensor [{}] is matched with tensor [{}]".format( + cur_name, pre_name)) + tensor_match_with_pre.append(cur_name) + tensor_match_with_cur.append(pre_name) + break + break + + return tensors_dict, tensor_match_with_pre, tensor_match_with_cur + + @staticmethod + def merge_and_slice(tensor_list, pre_dist_attr, cur_dist_attr): + """ + Merge tensors with previous dist_attr and slice tensors with current dist_attr + + Returns: + tensor(numpy.narray): a tensor's value of current rank. + """ + assert isinstance(tensor_list, list) + assert all(isinstance(p, np.ndarray) for p in tensor_list) + + if pre_dist_attr == cur_dist_attr: + # skip merge and slice tensor + rank_id = paddle.distributed.get_rank() + index = cur_dist_attr["process_group"].index(rank_id) + tensor = tensor_list[index] + else: + pre_dims_mapping = pre_dist_attr["dims_mapping"] + cur_dims_mapping = cur_dist_attr["dims_mapping"] + if len(set(pre_dims_mapping)) > 1 or -1 not in pre_dims_mapping: + # merge tensor + tensor = Converter.merge_with_dist_attr(tensor_list, + pre_dist_attr) + else: + # skip merge tensor + tensor = tensor_list[0] + + if len(set(cur_dims_mapping)) > 1 or -1 not in cur_dims_mapping: + # slice tensor + tensor = Converter.slice_with_dist_attr(tensor, cur_dist_attr) + + return tensor + + @staticmethod + def merge_with_dist_attr(tensor_list, dist_attr): + """ Merge tensor with distributed attribute """ + from .reshard import Resharder + + dims_mapping = dist_attr["dims_mapping"] + process_shape = dist_attr["process_shape"] + process_group = dist_attr["process_group"] + # get the complete shape of the tensor + complete_shape = Resharder.compute_complete_shape( + tensor_list[0].shape, process_shape, dims_mapping) + # merge the tensor with dist_attr + partition_tensor_list = [] + merged_partiton = [] + for process in process_group: + partition_index = Resharder.compute_partition_index( + process, complete_shape, dims_mapping, process_shape, + process_group) + index = process_group.index(process) + if partition_index not in merged_partiton: + merged_partiton.append(partition_index) + Converter.merge(partition_tensor_list, tensor_list[index], + partition_index, complete_shape) + + if len(partition_tensor_list) != 1: + raise ValueError("Fail to merge tensor with dist_attr '{}'.".format( + str(dist_attr))) + complete_tensor = partition_tensor_list[0][0] + return complete_tensor + + @staticmethod + def slice_with_dist_attr(tensor, dist_attr): + """ Slice tensor with distributed attribute """ + dims_mapping = dist_attr["dims_mapping"] + process_shape = dist_attr["process_shape"] + process_group = dist_attr["process_group"] + # slice the tensor with dist_attr + partition_index_list = Converter._get_split_indices( + tensor.shape, dims_mapping, process_shape, process_group) + sliced_tensor_list = Converter.split(tensor, partition_index_list, + len(partition_index_list)) + # get the current tensor's index in sliced_tensor_list + rank_id = paddle.distributed.get_rank() + sliced_tensor_index = Converter._get_sliced_index( + rank_id, tensor.shape, dims_mapping, process_shape, process_group) + if sliced_tensor_index not in range(len(sliced_tensor_list)): + raise ValueError("Fail to slice tensor with dist_attr '{}'.".format( + str(dist_attr))) + sliced_tensor = sliced_tensor_list[sliced_tensor_index] + return sliced_tensor + + @staticmethod + def merge(partition_tensor_list, tensor, partition_index, complete_shape): + """ + Merge partitial tensors to a complete. + + Returns: + None + + Examples: + .. code-block:: python + + import numpy as np + partition_tensor_list = [(np.array([[[1.11, 1.12]]]), [[0,1],[0,1],[0,2]])] + tensor = np.array([[[1.13, 1.14]]]) + partition_index = [[0,1],[0,1],[2,4]] + + _merge_tensor(partition_tensor_list, tensor, partition_index) + # partition_tensor_list: [(np.array([[[1.11, 1.12, 1.13, 1.14]]]), [[0,1],[0,1],[0,4]])] + """ + from .reshard import Resharder + + if len(partition_tensor_list) == 1: + is_complete_data = True + for idx, item in enumerate(partition_tensor_list[0][1]): + if item[0] != 0 or item[1] != complete_shape[idx]: + is_complete_data = False + break + if is_complete_data: + return + + if not partition_tensor_list: + partition_tensor_list.append((tensor, partition_index)) + else: + i = 0 + while i < len(partition_tensor_list): + concat_axis, first_order, new_partition = Resharder.compute_concat_info( + partition_tensor_list[i][1], partition_index) + if concat_axis != -1: + if first_order == 0: + new_tensor = np.concatenate( + (partition_tensor_list[i][0], tensor), + axis=concat_axis) + else: + new_tensor = np.concatenate( + (tensor, partition_tensor_list[i][0]), + axis=concat_axis) + + partition_tensor_list.pop(i) + Converter.merge(partition_tensor_list, new_tensor, + new_partition, complete_shape) + break + i += 1 + + @staticmethod + def split(complete_tensor, partition_index_list, length): + """ + Slice a complete tensor. + + Returns: + sliced_tensor_list(list): sliced tensors with 'partition_index_list' + + Examples: + .. code-block:: python + + import numpy as np + complete_tensor = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + rank = 2 + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + sliced_tensor_list = split(complete_tensor, [[], [], [2, 4]], 3) + # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])] + """ + sliced_tensor_list = [] + axis = len(complete_tensor.shape) - length + sliced_tensor = np.split(complete_tensor, + partition_index_list[axis], + axis=axis) + if length == 1: + return sliced_tensor + for tensor in sliced_tensor: + sliced_tensor_list.extend( + Converter.split(tensor, partition_index_list, length - 1)) + return sliced_tensor_list + + @staticmethod + def _get_split_indices(complete_shape, dims_mapping, process_shape, + process_group): + """ + Get split indices of every dimension. + + Returns: + split_indices_list(list): the split indices of every dimension of the tensor + + Examples: + .. code-block:: python + + import numpy as np + complete_tensor = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + index = _get_split_indices(complete_shape, dims_mapping, process_shape, process_group) + # index: [[], [], [2, 4]] + """ + from .reshard import Resharder + + split_indices_list = [] + for process in process_group: + partition_index = Resharder.compute_partition_index( + process, complete_shape, dims_mapping, process_shape, + process_group) + if split_indices_list: + for dim in range(len(partition_index)): + split_indices_list[dim].extend(partition_index[dim]) + else: + split_indices_list = partition_index + split_indices_list = list( + map(lambda x, y: list(set(x) - set([y]) - set([0])), + split_indices_list, complete_shape)) + split_indices_list = [sorted(x) for x in split_indices_list] + return split_indices_list + + @staticmethod + def _get_sliced_index(rank_id, complete_shape, dims_mapping, process_shape, + process_group): + """ + Get sliced_tensor's index of current rank in all sliced tensors list. + + Returns: + sliced_tensor_index(int): the index of sliced tensor in sliced_tensor_list + + Examples: + .. code-block:: python + + import numpy as np + complete_tensor = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + rank = 2 + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + slice_tensor = _slice_tensor(complete_tensor, [[], [], [2, 4]], 3) + # slice_tensor: + # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])] + + index = _get_sliced_index(rank, complete_shape, dims_mapping + process_shape, process_group) + # index: 2 + """ + from .reshard import Resharder + + partition_index = Resharder.compute_partition_index( + rank_id, complete_shape, dims_mapping, process_shape, process_group) + sliced_index = 0 + for i, shape in enumerate(complete_shape): + if dims_mapping[i] == -1: + slice_shape = shape + else: + slice_shape = shape // process_shape[dims_mapping[i]] + if slice_shape == 1: + index = partition_index[i][0] + else: + index = (partition_index[i][0] + 1) // slice_shape + sliced_index = sliced_index * (shape // slice_shape) + index + return sliced_index diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ba0300d45dfede0855a43a9e53d1cc138693c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/__init__.py @@ -0,0 +1,54 @@ +# Copyright (c) 2022 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 + +from .base_cost import Cost +from .base_cost import CommContext +from .base_cost import _g_op_cost_factory +from .base_cost import build_comm_desc +from .base_cost import build_dp_costs +from .base_cost import build_comp_desc_str_for_predict +from .base_cost import build_comp_desc_from_dist_op +from .base_cost import build_comm_desc_from_dist_op +from .base_cost import build_comm_costs_from_descs +from .base_cost import build_comp_costs_from_descs + +from .comp_op_cost import EmbeddingOpCost +from .comp_op_cost import EmbeddingGradOpCost +from .comp_op_cost import ConcatOpCost +from .comp_op_cost import MatmulOpCost +from .comp_op_cost import MatmulGradOpCost +from .comp_op_cost import MatmulV2OpCost +from .comp_op_cost import MatmulV2GradOpCost +from .comp_op_cost import MulOpCost +from .comp_op_cost import MulGradOpCost +from .comp_op_cost import Reshape2OpCost +from .comp_op_cost import Reshape2GradOpCost +from .comp_op_cost import SliceOpCost +from .comp_op_cost import SplitOpCost +from .comp_op_cost import SoftmaxOpCost +from .comp_op_cost import SoftmaxGradOpCost +from .comp_op_cost import Transpose2OpCost +from .comp_op_cost import Transpose2GradOpCost +from .comp_op_cost import FillConstantBatchSizeLikeOpCost + +from .tensor_cost import TensorCost + +from .estimate_cost import CostEstimator + +from .comm_op_cost import SendOpCost +from .comm_op_cost import RecvOpCost +from .comm_op_cost import IdentityOpCost +from .comm_op_cost import BroadcastOpCost +from .comm_op_cost import AllgatherOpCost +from .comm_op_cost import AllreduceSumOpCost diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/base_cost.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/base_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..deac76e45a8b0d35ad68cfd593a1e894f7428d0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/base_cost.py @@ -0,0 +1,832 @@ +# Copyright (c) 2022 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 + +from collections import OrderedDict +from functools import reduce + +import paddle + +from ..utils import _get_comm_group, _get_corresponding_rank +from ..process_group import get_process_group +from ..cluster import LinkType +from ..dist_tensor import DistributedTensor +from ..utils import _get_idx_in_axis +from ..dist_tensor import DistributedTensor + +COMM_OP_TYPE = [ + "send_v2", "recv_v2", "c_broadcast", "c_allgather", "c_allreduce_sum", + "c_identity" +] +NON_COMP_TYPE = ["while"] + COMM_OP_TYPE +_g_op_cost_factory = {} + + +def build_comp_desc_from_op(op): + """Build the description of computation op.""" + # NOTE: The desc is for serial op. + from ..reshard import get_var_with_recursion + + desc = {} + # The desc of concat op is {"op": "concat", "inputs": {"X": [(paddle.float32, [20, 20]), (paddle.float32, [20, 20])]}, "outputs": {"Out": [(paddle.float32, [20, 40])], "attrs": {"axis": -1}}} + vars = op.block.vars + desc["op"] = op.type + input_desc = OrderedDict() + for input_name in op.input_names: + var_name_list = op.input(input_name) + var_desc = [] + for var_name in var_name_list: + var = get_var_with_recursion(var_name, op.block, op.block.program) + shape = var.shape + var_desc.append((var.dtype, shape)) + input_desc[input_name] = var_desc + desc["inputs"] = input_desc + + output_desc = OrderedDict() + for out_name in op.output_names: + var_name_list = op.output(out_name) + var_desc = [] + for var_name in var_name_list: + var = get_var_with_recursion(var_name, op.block, op.block.program) + shape = var.shape + var_desc.append((var.dtype, shape)) + output_desc[out_name] = var_desc + desc["outputs"] = output_desc + + attr_desc = op.all_attrs + desc["attrs"] = attr_desc + + return desc + + +def build_comp_desc_from_dist_op(dist_op, dist_context): + """Build descriptions of computation op distributed on the processes.""" + from ..reshard import get_var_with_recursion + + op_descs = {} + op = dist_op.serial_op + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + assert process_mesh, "Process mesh must not be None." + processes = process_mesh.processes + for process in processes: + desc = {} + desc["op"] = op.type + attr_desc = op.all_attrs() + # NOTE: The attrs of desc is replica of serial op, there may be a bug if shape need to be partitioned involved in attrs. + desc["attrs"] = attr_desc + input_desc = OrderedDict() + output_desc = OrderedDict() + + # Get partitioned shape of input + for input_name in op.input_names: + var_name_list = op.input(input_name) + var_desc = [] + for var_name in var_name_list: + var = get_var_with_recursion(var_name, op.block, + op.block.program) + # Use op input_dims_mapping + dims_mapping = dist_attr.get_input_dims_mapping(var_name) + global_sizes = var.shape + # NOTE: When support uneven partition, the shard_sizes will be got from dist_attr. + shard_sizes = None + topology = process_mesh.topology + shape = DistributedTensor.get_local_sizes( + global_sizes, dims_mapping, topology, processes, process, + shard_sizes) + var_desc.append((var.dtype, shape)) + + # For special op such as embedding and its grad op + if op.type == "c_embedding" or op.type == "lookup_table_v2" or op.type == "c_embedding_grad" or op.type == "lookup_table_v2_grad": + if input_name == "W": + embedding_row_dim_mapping = dist_attr.get_input_dims_mapping( + op.input(input_name)[0])[0] + relative_idx = _get_idx_in_axis( + processes, dist_attr.process_mesh.topology, + embedding_row_dim_mapping, process) + per_part_size = shape[0] + relative_idx = relative_idx * per_part_size + desc["attrs"]["start_index"] = relative_idx + + input_desc[input_name] = var_desc + desc["inputs"] = input_desc + + for out_name in op.output_names: + var_name_list = op.output(out_name) + var_desc = [] + for var_name in var_name_list: + # Use op output_dims_mapping + var = get_var_with_recursion(var_name, op.block, + op.block.program) + dist_attr = dist_op.dist_attr + dims_mapping = dist_attr.get_output_dims_mapping(var_name) + process_mesh = dist_attr.process_mesh + global_sizes = var.shape + shard_sizes = None + processes = process_mesh.processes + topology = process_mesh.topology + shape = DistributedTensor.get_local_sizes( + global_sizes, dims_mapping, topology, processes, process, + shard_sizes) + var_desc.append((var.dtype, shape)) + + # For special op such as fill_constant_batch_size_like + if op.type == "fill_constant_batch_size_like": + # Modify shape attr according to how output are partitioned + out_name = var_name_list[0] + dims_mapping = dist_attr.get_output_dims_mapping(out_name) + process_mesh_shape = dist_attr.process_mesh.topology + shape_list = op.attr("shape") + # Modify target shape + for idx, axis in enumerate(dims_mapping): + if axis >= 0: + shape_list[idx] = shape_list[ + idx] // process_mesh_shape[axis] + desc["attrs"]["shape"] = shape_list + output_desc[out_name] = var_desc + + desc["outputs"] = output_desc + + op_descs[process] = desc + + return op_descs + + +def build_comp_desc_str_for_predict(desc): + # NOTE: The description format may change in the future. + def _parse_dtype(dtype): + dtype_str = "" + if dtype == paddle.float32: + dtype_str = "float32" + elif dtype == paddle.float16: + dtype_str = "float16" + elif dtype == paddle.int32: + dtype_str = "int32" + elif dtype == paddle.int64: + dtype_str = "int64" + elif dtype == paddle.unit8: + dtype_str = "unit8" + else: + raise TypeError("Unsupported dtype {}".format(dtype)) + return dtype_str + + assert isinstance(desc, dict) + desc_str_list = [] + desc_str = None + dtype_str_list = [] + dims_list = [] + shape_list = [] + + desc_str_list.append(desc["op"]) + inputs = desc["inputs"] + for key, item in inputs.items(): + for dtype, shape in item: + dtype_str_list.append(_parse_dtype(dtype)) + shape_list += list(shape) + dims = len(shape) + dims_list.append(dims) + + dtype_str = "*".join(dtype_str_list) + dims_list = [str(item) for item in dims_list] + dims_str = "*".join(dims_list) + + shape_list = [str(item) for item in shape_list] + shape_str = "[" + ",".join(shape_list) + "]" + desc_str_list += [dtype_str, dims_str, shape_str] + desc_str = "_".join(desc_str_list) + attrs = desc["attrs"] + parse_result = (desc_str, attrs) + return parse_result + + +def build_comm_desc_from_dist_op(op_type, + dist_op, + ctx, + var_names, + attrs=None, + parallel_axis=None, + group_ranks=None): + """Build descriptions of communication op distributed on the processes.""" + from ..reshard import get_var_with_recursion + + specific_op_type = [] + dist_attr = dist_op.dist_attr + assert dist_attr, "Dist attr must not be None." + process_mesh = dist_attr.process_mesh + assert process_mesh, "Process mesh must not be None." + + processes = process_mesh.processes + op_descs = {} + for process in processes: + rank_id = process + desc = {} + desc["op"] = op_type + op_attrs = None + comm_group_ranks = None + + if op_type not in specific_op_type: + serial_op = dist_op.serial_op + input_list = [] + # The var_names usually contain just one item. + for var_name in var_names: + dist_attr = dist_op.dist_attr + has_found = False + # Find var_name in serial op input or output + for name in dist_op.serial_op.input_arg_names: + # If a tensor is the input of multi ops, sum the grad of all ops, so the name will be varname@RENAME@block@0 and so on. + if var_name in name: + var_name = name + has_found = True + break + + if not has_found: + for name in dist_op.serial_op.output_arg_names: + if var_name in name: + var_name = name + has_found = True + break + assert has_found + var = get_var_with_recursion(var_name, serial_op.block, + serial_op.block.program) + + dims_mapping = dist_attr.get_input_dims_mapping( + var_name + ) if var_name in dist_op.serial_op.input_arg_names else dist_attr.get_output_dims_mapping( + var_name) + global_sizes = var.shape + shard_sizes = None + topology = process_mesh.topology + shape = DistributedTensor.get_local_sizes( + global_sizes, dims_mapping, topology, processes, process, + shard_sizes) + input_list.append((var.dtype, shape)) + + # NOTE: The input_name of comm ops used usually is X. + desc["inputs"] = {"X": input_list} + + # Get comm group by parallel_axis or the given group_ranks. + if parallel_axis is not None: + process_mesh_shape = process_mesh.topology + process_mesh_group = process_mesh.processes + comm_group_ranks = _get_comm_group(process_mesh_group, + process_mesh_shape, + parallel_axis, rank_id) + elif group_ranks is not None: + comm_group_ranks = group_ranks + else: + raise ValueError( + "The parallel_axis and group_ranks can not be None in the same." + ) + + if attrs is not None: + assert isinstance(attrs, dict) + op_attrs = attrs + else: + op_attrs = {} + + desc["attrs"] = op_attrs + desc["group_ranks"] = comm_group_ranks + + op_descs[rank_id] = desc + + return op_descs + + +def build_comm_desc(op_type, group_ranks, dtype, shape, attrs=None): + """Build a comm desc directly.""" + desc = {} + desc["op"] = op_type + desc["group_ranks"] = group_ranks + desc["inputs"] = {"X": [(dtype, shape)]} + desc["attrs"] = attrs + return desc + + +def build_comm_costs_from_descs(op_cost_class, ctx, processes, descs, cluster): + """Build comm costs by descriptions""" + comm_context = CommContext(cluster) + group_ranks_list = [] + comm_op_cost_list = [] + for process in processes: + desc = descs[process] + group_ranks = desc["group_ranks"] + if group_ranks not in group_ranks_list: + group_ranks_list.append(group_ranks) + comm_op_cost = op_cost_class(op_desc=desc, + comm_context=comm_context) + comm_op_cost_list.append(comm_op_cost) + return comm_op_cost_list + + +def build_comp_costs_from_descs(op_cost_class, ctx, processes, descs, cluster): + """Build comp costs by descriptions.""" + costs = {} + for process in processes: + costs[process] = op_cost_class(op_desc=descs[process], cluster=cluster) + return costs + + +def build_dp_costs(result, dist_op, ctx, var_names, attrs, parallel_axis, + cluster): + """DP cost contains a allreduce_sum op cost and a scale op cost""" + # The costs will be appended in the given result. + from ..reshard import get_var_with_recursion + + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + assert len(var_names) == 1 + vars = dist_op.serial_op.block.vars + var_name = var_names[0] + has_found = False + for name in dist_op.serial_op.input_arg_names: + if var_name in name: + var_name = name + has_found = True + break + + if not has_found: + for name in dist_op.serial_op.output_arg_names: + if var_name in name: + var_name = name + has_found = True + break + if not has_found: + return + + c_allreduce_sum_descs = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_cost_list = build_comm_costs_from_descs( + _g_op_cost_factory["c_allreduce_sum"], ctx, processes, + c_allreduce_sum_descs, cluster) + result.append(comm_cost_list) + + # The scale op just on the group_ranks + for comm_cost in comm_cost_list: + group_ranks = comm_cost.group_ranks + dp_degree = len(group_ranks) + scale_costs = {} + op_type = "scale" + for rank in group_ranks: + desc = {} + desc["op"] = op_type + desc["inputs"] = {} + dims_mapping = dist_attr.get_input_dims_mapping( + var_name) if dist_attr.get_input_dims_mapping( + var_name + ) is not None else dist_attr.get_output_dims_mapping(var_name) + var = get_var_with_recursion(var_name, dist_op.serial_op.block, + dist_op.serial_op.block.program) + global_sizes = var.shape + shard_sizes = None + topology = process_mesh.topology + shape = DistributedTensor.get_local_sizes(global_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + desc["inputs"]["X"] = [(var.dtype, shape)] + attrs = {"scale": 1.0 / dp_degree} + desc["attrs"] = attrs + scale_op_cost = _g_op_cost_factory["scale"](op_desc=desc, + cluster=cluster) + scale_costs[rank] = scale_op_cost + result.append(scale_costs) + + +class CommContext: + _instance = None + _has_instance = False + + def __new__(cls, *args, **kwargs): + if cls._instance is None: + cls._instance = super().__new__(cls) + _has_instance = True + return cls._instance + + def __init__(self, cluster): + if CommContext._has_instance: + return + self.beta = {} + self.hops = {} + assert cluster is not None + self.cluster = cluster + # if cluster has no info about those vars, it will be set by default + self.base_ring = None + self.base_tree = None + # self.base_inter_ring = None + # self.base_inter_tree = None + self.intra_ring = None + self.intra_tree = None + self.inter_ring = None + self.inter_tree = None + self.switch = None + self._post_init() + + def _post_init(self): + alpha_latency = self.cluster.alpha_latency + if alpha_latency is None: + # set default + self.base_ring = 8.4 + self.base_tree = 0. + # self.base_inter_ring = 9.6 + # self.base_inter_tree = 28 + # NVL in default + self.intra_ring = 3.4 + self.intra_tree = 28 + # NET in default + self.inter_ring = 9.6 + self.inter_tree = 28 + self.switch = 10.0 + else: + base_ring = alpha_latency.base_ring + self.base_ring = base_ring if base_ring is not None else 8.4 + + base_tree = alpha_latency.base_tree + self.base_tree = base_tree if base_tree is not None else 0. + + intra_ring = alpha_latency.intra_ring + if intra_ring == LinkType.NVL: + self.intra_ring = 3.4 + elif intra_ring == LinkType.PHB: + self.intra_ring = 5.7 + elif intra_ring is not None: + self.intra_ring = intra_ring + else: + # NVL Default + self.intra_ring = 3.4 + + intra_tree = alpha_latency.intra_tree + if intra_tree == LinkType.NVL: + self.intra_tree = 28 + elif intra_tree == LinkType.PHB: + self.intra_tree = 28 + elif intra_tree is not None: + self.intra_tree = intra_tree + else: + # NVL Default + self.intra_tree = 28 + + inter_ring = alpha_latency.inter_ring + if inter_ring == LinkType.NET: + self.inter_ring = 9.6 + elif inter_ring is not None: + self.inter_ring = inter_ring + else: + # NET Default + self.inter_ring = 9.6 + + inter_tree = alpha_latency.inter_tree + if inter_tree == LinkType.NET: + self.inter_tree = 28 + elif inter_tree is not None: + self.inter_tree = inter_tree + else: + # NET Default + self.inter_tree = 28 + + switch = alpha_latency.switch + self.switch = switch if switch is not None else 10 + + assert self.base_ring is not None + assert self.base_tree is not None + assert self.intra_ring is not None + assert self.intra_tree is not None + assert self.inter_ring is not None + assert self.inter_tree is not None + assert self.switch is not None + + def get_max_beta(self, ranks): + # NOTE: Get beta by ring, even in the case of tree such as tree broadcast + ranks = self.cluster.convert_rank_to_device_id(ranks) + key = ','.join(map(str, sorted(ranks))) + max_beta = None + if key in self.beta: + max_beta = self.beta[key] + else: + for i in range(len(ranks)): + for j in range(i + 1, len(ranks)): + forward_order_beta = self.cluster.get_beta( + ranks[i], ranks[j]) + backward_order_beta = self.cluster.get_beta( + ranks[j], ranks[i]) + beta = forward_order_beta if forward_order_beta > backward_order_beta else backward_order_beta + if max_beta == None: + max_beta = beta + else: + if beta > max_beta: + max_beta = beta + self.beta[key] = max_beta + + return max_beta + + def get_hops(self, ranks): + key = ','.join(map(str, sorted(ranks))) + hops = 0 + for i in range(len(ranks)): + for j in range(i + 1, len(ranks)): + hop = self.cluster.get_hop(ranks[i], ranks[j]) + hops += hop + self.hops[key] = hops + + return hops + + +class Cost: + + def __init__(self, time=0, memory=0, flops=0): + self.time = time + self.memory = memory + self.flops = flops + + def _check_time(self, val): + assert val >= 0, "Time must be greater than or equal to 0." + + def _check_memory(self, val): + assert isinstance( + val, + int) and val >= 0, "Memory must be int and greater than equal to 0." + + def _check_flops(self, val): + assert isinstance( + val, + int) and val >= 0, "FLOPs must be int and greater than equal to 0." + + @property + def time(self): + return self._time + + @time.setter + def time(self, val): + self._check_time(val) + self._time = val + + @property + def memory(self): + return self._memory + + @memory.setter + def memory(self, val): + self._check_memory(val) + self._memory = val + + @property + def flops(self): + return self._flops + + @flops.setter + def flops(self, val): + self._check_flops(val) + self._flops = val + + def __add__(self, rhs): + assert isinstance(rhs, Cost) + time = self.time + rhs.time + memory = self.memory + rhs.memory + flops = self.flops + rhs.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + return Cost(time, memory, flops) + + def __sub__(self, rhs): + assert isinstance(rhs, Cost) + time = self.time - rhs.time + memory = self.memory - rhs.memory + flops = self.flops - rhs.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + return Cost(time, memory, flops) + + +class OpCost: + + def __init__(self, op=None, op_desc=None): + self._op = op + self._op_desc = op_desc + self._cost = None + + @property + def op(self): + return self._op + + @property + def op_desc(self): + return self._op_desc + + @property + def time(self): + return self.cost.time + + @property + def memory(self): + return self.cost.memory + + @property + def flops(self): + return self.cost.flops + + @property + def cost(self): + return self._cost + + def calc_time(self): + return 0 + + def calc_memory(self): + return 0 + + def calc_flops(self): + return 0 + + def calc_cost(self): + time = self.calc_time() + memory = self.calc_memory() + flops = self.calc_flops() + cost = Cost(time, memory, flops) + return cost + + def __add__(self, rhs): + assert isinstance(rhs, (OpCost, Cost)) + time = 0 + memory = 0 + flops = 0 + if isinstance(rhs, OpCost): + time = self.cost.time + rhs.cost.time + memory = self.cost.memory + rhs.cost.memory + flops = self.cost.flops + rhs.cost.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + elif isinstance(rhs, Cost): + time = self.time + rhs.time + memory = self.memory + rhs.memory + flops = self.flops + rhs.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + return Cost(time, memory, flops) + + def __sub__(self, rhs): + assert isinstance(rhs, (OpCost, Cost)) + time = 0 + memory = 0 + flops = 0 + if isinstance(rhs, OpCost): + time = self.cost.time - rhs.cost.time + memory = self.cost.memory - rhs.cost.memory + flops = self.cost.flops - rhs.cost.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + elif isinstance(rhs, Cost): + time = self.time - rhs.time + memory = self.memory - rhs.memory + flops = self.flops - rhs.flops + assert (time >= 0 and memory >= 0 and flops >= 0) + return Cost(time, memory, flops) + + +class CommOpCost(OpCost): + OP_TYPE = "COMM" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(CommOpCost, self).__init__(op=op, op_desc=op_desc) + self._check_comm_op_type() + self._comm_context = comm_context + self._group_ranks = None + self._comm_count = None + self._hops = None + self._rank_count = len(self.group_ranks) + self._machine_count = None + self._cost = self.calc_cost() + + @property + def comm_context(self): + return self._comm_context + + @property + def comm_count(self): + from ..reshard import get_var_with_recursion + + if self._comm_count is None: + dtype = None + shape = None + if self.op is not None: + vars = self.op.block.vars + # NOTE: The tensor communicated input_name is "X" in default. Otherwise, this function should be overrided + var_name = self.op.input("X")[0] + var = get_var_with_recursion(var_name, self.op.block, + self.program) + dtype = var.dtype + shape = var.shape + elif self.op_desc is not None: + dtype = self.op_desc["inputs"]["X"][0][0] + shape = self.op_desc["inputs"]["X"][0][1] + + factor = None + if dtype == paddle.float32 or dtype == paddle.int32: + factor = 4 + elif dtype == paddle.int64: + factor = 8 + elif dtype == paddle.uint8: + factor = 1 + elif dtype == paddle.float16: + factor = 2 + elif dtype == paddle.bool: + factor = 8 + else: + raise ValueError("Unsupported comm dtype {}".format(dtype)) + comm_count = reduce(lambda x, y: x * y, shape) * factor + self._comm_count = comm_count + + return self._comm_count + + @property + def rank_count(self): + return self._rank_count + + @property + def machine_count(self): + if self._machine_count is None: + cluster = self._comm_context.cluster + self._machine_count = cluster.get_involved_machine_count( + self.group_ranks) + return self._machine_count + + @property + def hops(self): + if self._hops is None: + self._hops = self.comm_context.get_hops(self.group_ranks) + return self._hops + + @property + def group_ranks(self): + if self._group_ranks is None: + if self.op_desc is not None: + self._group_ranks = self.op_desc["group_ranks"] + elif self.op is not None: + ring_id = op.attrs("ring_id") + process_group = get_process_group(ring_id) + if process_group is None: + raise ValueError( + "There not exists process group whose ring_id is {}.". + format(ring_id)) + self._group_ranks = process_group.ranks + return self._group_ranks + + @classmethod + def _check_comm_op_type(cls): + if cls.OP_TYPE != "COMM": + if cls.OP_TYPE not in COMM_OP_TYPE: + raise TypeError( + "Please Check op type in {}, but got {}.".format( + COMM_OP_TYPE, cls.OP_TYPE)) + + +class CompOpCost(OpCost): + OP_TYPE = "COMP" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(CompOpCost, self).__init__(op=op, op_desc=op_desc) + self._check_comp_op_type() + self._cost = self.calc_cost() + self.cluster = cluster + + @classmethod + def _check_comp_op_type(cls): + if cls.OP_TYPE != "COMP": + if cls.OP_TYPE in NON_COMP_TYPE: + raise TypeError( + "Please Check op type not in {}, but got {}.".format( + NON_COMP_TYPE, cls.OP_TYPE)) + + +def register_op_cost(cls): + op_type = cls.OP_TYPE + + def register(op_type): + global _g_op_cost_factory + _g_op_cost_factory[op_type] = cls + + register(op_type) + return cls + + +def calc_time_by_modeling(op=None, desc=None, cluster=None): + op_type = op.type if op is not None else desc["op"] + if op_type in COMM_OP_TYPE: + op_cost = _g_op_cost_factory[op_type](op=op, + op_desc=desc, + comm_context=CommContext(cluster)) + elif op_type not in NON_COMP_TYPE: + op_cost = _g_op_cost_factory[op_type](op=op, + op_desc=desc, + cluster=cluster) + time = op_cost.calc_time() + return time diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comm_op_cost.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comm_op_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..0f92bcc8facf28395cbdc52cef1ba6eb4205d75a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comm_op_cost.py @@ -0,0 +1,166 @@ +# Copyright (c) 2022 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 + +import math + +from .base_cost import register_op_cost, CommOpCost, _g_op_cost_factory + + +@register_op_cost +class AllreduceSumOpCost(CommOpCost): + OP_TYPE = "c_allreduce_sum" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(AllreduceSumOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + # use tree if cross machine and use ring if in a single machine + time = None + cluster = self.comm_context.cluster + if not cluster.cross_machine(self.group_ranks): + time = self.calc_time_ring() + else: + time = self.calc_time_tree() + + return time + + def calc_time_ring(self): + alpha = self.comm_context.base_ring + alpha += 2 * (self.rank_count - + self.machine_count) * self.comm_context.intra_ring + alpha += 2 * (self.machine_count - 1) * ( + self.comm_context.inter_ring + self.hops * self.comm_context.switch) + beta = self.comm_context.get_max_beta(self.group_ranks) + time = alpha + 2 * (self.rank_count - + 1) / self.rank_count * self.comm_count * beta + + return time + + def calc_time_tree(self): + alpha = self.comm_context.base_tree + alpha += 2 * (self.rank_count / self.machine_count - + 1) * self.comm_context.intra_tree + alpha += math.log2(self.machine_count) * ( + self.comm_context.inter_tree + self.hops * self.comm_context.switch) + beta = self.comm_context.get_max_beta(self.group_ranks) + + time = alpha + 2 * self.comm_count * beta + + return time + + +@register_op_cost +class AllgatherOpCost(CommOpCost): + OP_TYPE = "c_allgather" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(AllgatherOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + time = self.calc_time_ring() + return time + + def calc_time_ring(self): + alpha = self.comm_context.base_ring + alpha += (self.rank_count - + self.machine_count) * self.comm_context.intra_ring + alpha += (self.machine_count - 1) * ( + self.comm_context.inter_ring + self.hops * self.comm_context.switch) + beta = self.comm_context.get_max_beta(self.group_ranks) + time = alpha + (self.rank_count - + 1) / self.rank_count * self.comm_count * beta + return time + + +@register_op_cost +class BroadcastOpCost(CommOpCost): + OP_TYPE = "c_broadcast" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(BroadcastOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + time = self.calc_time_ring() + return time + + def calc_time_ring(self): + alpha = self.comm_context.base_ring + if self.machine_count > 1: + alpha += self.comm_context.inter_ring + self.hops * self.comm_context.switch + else: + alpha += self.comm_context.intra_ring + beta = self.comm_context.get_max_beta(self.group_ranks) + time = alpha + self.comm_count * beta + + return time + + +@register_op_cost +class IdentityOpCost(CommOpCost): + OP_TYPE = "c_identity" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(IdentityOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + return 0 + + +@register_op_cost +class RecvOpCost(CommOpCost): + OP_TYPE = "recv_v2" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(RecvOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + alpha = self.comm_context.base_ring + if self.machine_count > 1: + alpha += self.comm_context.inter_ring + self.hops * self.comm_context.switch + else: + alpha += self.comm_context.intra_ring + beta = self.comm_context.get_max_beta(self.group_ranks) + time = alpha + self.comm_count * beta + return time + + +@register_op_cost +class SendOpCost(CommOpCost): + OP_TYPE = "send_v2" + + def __init__(self, op=None, op_desc=None, comm_context=None): + super(SendOpCost, self).__init__(op=op, + op_desc=op_desc, + comm_context=comm_context) + + def calc_time(self): + alpha = self.comm_context.base_ring + if self.machine_count > 1: + alpha += self.comm_context.inter_ring + self.hops * self.comm_context.switch + else: + alpha += self.comm_context.intra_ring + beta = self.comm_context.get_max_beta(self.group_ranks) + time = alpha + self.comm_count * beta + + return time diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comp_op_cost.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comp_op_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..1217a0b4d0bf7b3fac53e51e97f91191fa4563fc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/comp_op_cost.py @@ -0,0 +1,1369 @@ +# Copyright (c) 2022 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 + +from .base_cost import Cost, register_op_cost, CompOpCost, _g_op_cost_factory + + +@register_op_cost +class AdamOpCost(CompOpCost): + OP_TYPE = "adam" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(AdamOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ArgsortOpCost(CompOpCost): + OP_TYPE = "argsort" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ArgsortOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class AssignOpCost(CompOpCost): + OP_TYPE = "assign" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(AssignOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class AssignValueOpCost(CompOpCost): + OP_TYPE = "assign_value" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(AssignValueOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class BeamSearchOpCost(CompOpCost): + OP_TYPE = "beam_search" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(BeamSearchOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class BeamSearchDecodeOpCost(CompOpCost): + OP_TYPE = "beam_search_decode" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(BeamSearchDecodeOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class CastOpCost(CompOpCost): + OP_TYPE = "cast" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(CastOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ConcatOpCost(CompOpCost): + OP_TYPE = "concat" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ConcatOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class DropoutOpCost(CompOpCost): + OP_TYPE = "dropout" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(DropoutOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class DropoutGradOpCost(CompOpCost): + OP_TYPE = "dropout_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(DropoutGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseAddOpCost(CompOpCost): + OP_TYPE = "elementwise_add" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseAddOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseAddGradOpCost(CompOpCost): + OP_TYPE = "elementwise_add_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseAddGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseDivOpCost(CompOpCost): + OP_TYPE = "elementwise_div" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseDivOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseDivGradOpCost(CompOpCost): + OP_TYPE = "elementwise_div_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseDivGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseMulOpCost(CompOpCost): + OP_TYPE = "elementwise_mul" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseMulOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseMulGradOpCost(CompOpCost): + OP_TYPE = "elementwise_mul_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseMulGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseSubOpCost(CompOpCost): + OP_TYPE = "elementwise_sub" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseSubOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ElementwiseSubGradOpCost(CompOpCost): + OP_TYPE = "elementwise_sub_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ElementwiseSubGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class EqualOpCost(CompOpCost): + OP_TYPE = "equal" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(EqualOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class EmbeddingOpCost(CompOpCost): + OP_TYPE = "c_embedding" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(EmbeddingOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class EmbeddingGradOpCost(CompOpCost): + OP_TYPE = "c_embedding_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(EmbeddingGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class FillConstantOpCost(CompOpCost): + OP_TYPE = "fill_constant" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(FillConstantOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class FillConstantBatchSizeLikeOpCost(CompOpCost): + OP_TYPE = "fill_constant_batch_size_like" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(FillConstantBatchSizeLikeOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class FusedSoftmaxMaskUpperTriangleOpCost(CompOpCost): + OP_TYPE = "fused_softmax_mask_upper_triangle" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(FusedSoftmaxMaskUpperTriangleOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class FusedSoftmaxMaskUpperTriangleGradOpCost(CompOpCost): + OP_TYPE = "fused_softmax_mask_upper_triangle_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(FusedSoftmaxMaskUpperTriangleGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class GatherOpCost(CompOpCost): + OP_TYPE = "gather" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(GatherOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class GeluOpCost(CompOpCost): + OP_TYPE = "gelu" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(GeluOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class GeluGradOpCost(CompOpCost): + OP_TYPE = "gelu_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(GeluGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class GreaterEqualOpCost(CompOpCost): + OP_TYPE = "greater_equal" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(GreaterEqualOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class IncrementOpCost(CompOpCost): + OP_TYPE = "increment" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(IncrementOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class IsEmptyOpCost(CompOpCost): + OP_TYPE = "is_empty" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(IsEmptyOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LayerNormOpCost(CompOpCost): + OP_TYPE = "layer_norm" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LayerNormOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LayerNormGradOpCost(CompOpCost): + OP_TYPE = "layer_norm_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LayerNormGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LessThanOpCost(CompOpCost): + OP_TYPE = "less_than" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LessThanOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LogicalNotOpCost(CompOpCost): + OP_TYPE = "logical_not" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LogicalNotOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LogicalAndOpCost(CompOpCost): + OP_TYPE = "logical_and" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LogicalAndOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LodResetOpCost(CompOpCost): + OP_TYPE = "lod_reset" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LodResetOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LogOpCost(CompOpCost): + OP_TYPE = "log" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LogOpCost, self).__init__(op=op, op_desc=op_desc, cluster=cluster) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LookupTableV2OpCost(CompOpCost): + OP_TYPE = "lookup_table_v2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LookupTableV2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class LookupTableV2GradOpCost(CompOpCost): + OP_TYPE = "lookup_table_v2_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(LookupTableV2GradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MatmulOpCost(CompOpCost): + OP_TYPE = "matmul" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MatmulOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MatmulGradOpCost(CompOpCost): + OP_TYPE = "matmul_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MatmulGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MatmulV2OpCost(CompOpCost): + OP_TYPE = "matmul_v2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MatmulV2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MatmulV2GradOpCost(CompOpCost): + OP_TYPE = "matmul_v2_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MatmulV2GradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MemcpyOpCost(CompOpCost): + OP_TYPE = "memcpy" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MemcpyOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MulOpCost(CompOpCost): + OP_TYPE = "mul" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MulOpCost, self).__init__(op=op, op_desc=op_desc, cluster=cluster) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class MulGradOpCost(CompOpCost): + OP_TYPE = "mul_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(MulGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class OneHotOpCost(CompOpCost): + OP_TYPE = "one_hot" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(OneHotOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ReadFromArrayOpCost(CompOpCost): + OP_TYPE = "read_from_array" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ReadFromArrayOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ReduceSumOpCost(CompOpCost): + OP_TYPE = "reduce_sum" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ReduceSumOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ReduceSumGradOpCost(CompOpCost): + OP_TYPE = "reduce_sum_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ReduceSumGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Reshape2OpCost(CompOpCost): + OP_TYPE = "reshape2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Reshape2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Reshape2GradOpCost(CompOpCost): + OP_TYPE = "reshape2_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Reshape2GradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ReduceMeanOpCost(CompOpCost): + OP_TYPE = "reduce_mean" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ReduceMeanOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ReduceMeanGradOpCost(CompOpCost): + OP_TYPE = "reduce_mean_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ReduceMeanGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SamplingIdOpCost(CompOpCost): + OP_TYPE = "sampling_id" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SamplingIdOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class ScaleOpCost(CompOpCost): + OP_TYPE = "scale" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(ScaleOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SliceOpCost(CompOpCost): + OP_TYPE = "slice" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SliceOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SoftmaxOpCost(CompOpCost): + OP_TYPE = "softmax" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SoftmaxOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SoftmaxGradOpCost(CompOpCost): + OP_TYPE = "softmax_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SoftmaxGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SoftmaxWithCrossEntropyOpCost(CompOpCost): + OP_TYPE = "softmax_with_cross_entropy" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SoftmaxWithCrossEntropyOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SoftmaxWithCrossEntropyGradOpCost(CompOpCost): + OP_TYPE = "softmax_with_cross_entropy_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SoftmaxWithCrossEntropyGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SplitOpCost(CompOpCost): + OP_TYPE = "split" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SplitOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Squeeze2OpCost(CompOpCost): + OP_TYPE = "squeeze2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Squeeze2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SquareOpCost(CompOpCost): + OP_TYPE = "square" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SquareOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SquareGradOpCost(CompOpCost): + OP_TYPE = "square_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SquareGradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class SumOpCost(CompOpCost): + OP_TYPE = "sum" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(SumOpCost, self).__init__(op=op, op_desc=op_desc, cluster=cluster) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class TopKOpCost(CompOpCost): + OP_TYPE = "top_k" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(TopKOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Transpose2OpCost(CompOpCost): + OP_TYPE = "transpose2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Transpose2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Transpose2GradOpCost(CompOpCost): + OP_TYPE = "transpose2_grad" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Transpose2GradOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class Unsqueeze2OpCost(CompOpCost): + OP_TYPE = "unsqueeze2" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(Unsqueeze2OpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 + + +@register_op_cost +class WriteToArrayOpCost(CompOpCost): + OP_TYPE = "write_to_array" + + def __init__(self, op=None, op_desc=None, cluster=None): + super(WriteToArrayOpCost, self).__init__( + op=op, op_desc=op_desc, cluster=cluster + ) + + # For a concrete COMP OP, the calc_time and calc_flops function need to be overrided + def calc_flops(self): + # NOTE: The actual formula will be filled in the future + return 0 + + def calc_time(self): + # NOTE: The actual formula will be filled in the future + return 0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/estimate_cost.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/estimate_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d737769d01c8ac8019ae7f2891670ceb6389bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/estimate_cost.py @@ -0,0 +1,625 @@ +# Copyright (c) 2022 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 + +from collections import OrderedDict +from functools import reduce + +import paddle +import paddle.fluid.core as core +from paddle.distributed.fleet.meta_optimizers.common import OpRole + +from .base_cost import Cost +from ..operators.common import get_distributed_operator_impl_container +from ..dist_tensor import DistributedTensor + + +class CostEstimator: + _sepical_op_type = ["fused_attention", "fused_feedforward"] + + def __init__( + self, program, cluster, mode="modeling", rank=None, loop_count=10 + ): + self._program = program + self._cluster = cluster + self._check_mode(mode) + self._mode = mode + self._rank = rank if rank is not None else paddle.distributed.get_rank() + self._loop_count = loop_count + self._global_cost = Cost() + self._local_cost_mapping = {} + self._detailed_cost = ( + OrderedDict() + ) # {`op_id`: {"reshard": [], "dist_op": [], "local_cost": local_cost}}} + self._bubble_time_mapping = {} + self._ordered_ops = [] + self.max_memories = {} + self.max_memory = None + + @property + def loop_count(self): + return self._loop_count + + @property + def detailed_cost(self): + return self._detailed_cost + + @property + def program(self): + return self._program + + @property + def rank(self): + return self._rank + + @property + def dist_context(self): + return self._dist_context + + @property + def cluster(self): + return self._cluster + + @property + def mode(self): + return self._mode + + @property + def global_cost(self): + max_time = 0 + memory = 0 + flops = 0 + for rank in self._local_cost_mapping: + cost = self._local_cost_mapping[rank] + if cost.time > max_time: + max_time = cost.time + memory += cost.memory + flops += cost.flops + self._global_cost.time = max_time + self._global_cost.memory = memory + self._global_cost.flops = flops + return self._global_cost + + def local_cost(self, rank=None): + rank = self.rank if rank is None else rank + if rank not in self._local_cost_mapping: + self._local_cost_mapping[rank] = Cost() + + return self._local_cost_mapping[rank] + + def local_bubble_time(self, rank=None): + rank = self.rank if rank is None else rank + return self._bubble_time_mapping[rank] + + def _check_mode(self, mode): + if mode not in ["modeling", "profiling"]: + raise ValueError( + "Just support modeling and profiling, but got {}".format(mode) + ) + + def _is_special_var_name(self, var_name): + special_var_name = ["lod_tensor_blocking_queue_0"] + if var_name in special_var_name: + return True + return False + + def _estimate_core(self, dist_context, resharder, block): + from ..reshard import get_var_with_recursion + + ops = block.ops + loop_count = None + if block.desc.id != self.program.global_block().desc.id: + loop_count = self.loop_count + else: + loop_count = 1 + for i in range(loop_count): + for op in ops: + self._detailed_cost[op.desc.id()] = OrderedDict() + # If in the while sub block, the detail of cost is the last cost + detail = self._detailed_cost[op.desc.id()] + detail["reshard_cost"] = OrderedDict() # + detail["dist_op_cost"] = [] + if int(op.attr('op_role')) == int(OpRole.Optimize): + continue + if op.type in [ + "create_py_reader", + "create_double_buffer_reader", + "read", + ]: + continue + + # NOTE: It does not support nested loop and just supports while op when op has sub block now. + if op.type == "while": + while_block = self.program.blocks[op.attr("sub_block").id] + self._estimate_core(dist_context, resharder, while_block) + continue + + for var_name in op.input_arg_names: + if self._is_special_var_name(var_name): + continue + var = get_var_with_recursion(var_name, block, self.program) + reshard_cost = resharder.get_cost(op, var, self.cluster) + + # Calc reshard cost + if reshard_cost is not None: + detail["reshard_cost"][var_name] = reshard_cost + + comm_costs = reshard_cost[0] + local_comp_cost = reshard_cost[1] + for comm_cost in comm_costs: + # Time is cumulative in global cost and local cost, but memory and flops just are cumulative in global cost. + # Comm sync + for item in comm_cost: + group_ranks, cost = item + max_time = None + cost_time = {} + for rank in group_ranks: + rank_cost = self.local_cost(rank) + cost_time[rank] = rank_cost.time + if max_time is None: + max_time = rank_cost.time + else: + if max_time < rank_cost.time: + max_time = rank_cost.time + + for rank in group_ranks: + self.local_cost(rank).time = ( + max_time + cost.time + ) + + if rank not in self._bubble_time_mapping: + self._bubble_time_mapping[rank] = 0 + + self._bubble_time_mapping[rank] += ( + max_time - cost_time[rank] + ) + + for rank in local_comp_cost: + for comp_cost in local_comp_cost[rank]: + self.local_cost(rank).time += comp_cost.time + + # Calc dist op cost + dist_op = dist_context.get_dist_op_for_program(op) + op_dist_attr = dist_op.dist_attr + processes = op_dist_attr.process_mesh.processes + + container = get_distributed_operator_impl_container( + op_dist_attr.impl_type + ) + dist_impl = container.impls[op_dist_attr.impl_idx] + + dist_op_cost = dist_impl.calc_cost( + op.attr('op_role'), dist_op, dist_context, self.cluster + ) + detail["dist_op_cost"] = dist_op_cost + + if dist_op_cost is None: + assert ( + dist_op.serial_op.type in CostEstimator._sepical_op_type + ) + continue + for item in dist_op_cost: + if isinstance(item, list): + # Comm sync + for comm_op_cost in item: + max_time = None + cost_time = {} + group_ranks = comm_op_cost.group_ranks + for rank in comm_op_cost.group_ranks: + rank_cost = self.local_cost(rank) + cost_time[rank] = rank_cost.time + if max_time is None: + max_time = rank_cost.time + else: + if max_time < rank_cost.time: + max_time = rank_cost.time + for rank in group_ranks: + self.local_cost(rank).time = ( + max_time + comm_op_cost.time + ) + if rank not in self._bubble_time_mapping: + self._bubble_time_mapping[rank] = 0 + self._bubble_time_mapping[rank] += ( + max_time - cost_time[rank] + ) + elif isinstance(item, dict): + # Op just one + for rank in processes: + # DP+PP+MP + if rank not in item: + continue + self.local_cost(rank).time += item[rank].time + + def prepare(self): + self._global_cost = Cost() + self._local_cost_mapping = {} + self._detailed_cost = OrderedDict() + self._bubble_time_mapping = {} + + def _calculate_bytes(self, sizes, dtype): + if sizes: + total_count = reduce(lambda x, y: x * y, sizes) + else: + total_count = 0 + + if dtype == paddle.float64 or dtype == paddle.int64: + dtype_factor = 8 + elif dtype == paddle.float32 or dtype == paddle.int32: + dtype_factor = 4 + elif ( + dtype == paddle.float16 + or dtype == paddle.bfloat16 + or dtype == paddle.int16 + ): + dtype_factor = 2 + elif dtype == paddle.int8 or dtype == paddle.uint8: + dtype_factor = 1 + else: + dtype_factor = 8 + + memory = total_count * dtype_factor + return memory + + def _estimate_max_memory_by_dist_op(self, dist_context): + # This estimation will be improved, now reshard and inplace are not considered. + # Persist var is not free. + def _convert_pm_and_dm_to_str(process_mesh, dims_mapping): + processes = ",".join([str(x) for x in process_mesh.processes]) + topology = ",".join([str(x) for x in process_mesh.topology]) + dims_mapping = ",".join([str(x) for x in dims_mapping]) + result = processes + topology + dims_mapping + return result + + memories = {} + self.max_memories = {} + var_info = ( + {} + ) # var_name: [[process_mesh, dims_mapping], [id]], [[process_mesh, dims_mapping], [id]]} + + for block in self.program.blocks: + for op in block.ops: + self._ordered_ops.append([op.desc.id(), op]) + self._ordered_ops.sort(key=lambda x: x[0]) + + for op_id, op in self._ordered_ops: + if op.type in [ + "create_py_reader", + "create_double_buffer_reader", + "read", + ]: + continue + dist_op = dist_context.get_dist_op_for_program(op) + process_mesh = dist_op.dist_attr.process_mesh + for var_name in op.input_arg_names: + input_dims_mapping = dist_op.dist_attr.get_input_dims_mapping( + var_name + ) + if var_name not in var_info: + var_info[var_name] = {} + key = _convert_pm_and_dm_to_str( + process_mesh, input_dims_mapping + ) + if key not in var_info[var_name]: + var_info[var_name][key] = {} + # It is even partition now + if "memory" not in var_info[var_name][key]: + var = dist_op.get_serial_input(var_name) + global_sizes = var.shape + dtype = var.dtype + sizes = DistributedTensor.get_local_sizes( + global_sizes, + input_dims_mapping, + process_mesh.topology, + process_mesh.processes, + ) + var_info[var_name][key]["memory"] = self._calculate_bytes( + sizes, dtype + ) + if "position" not in var_info[var_name][key]: + var_info[var_name][key]["position"] = [] + var_info[var_name][key]["position"].append(op_id) + + for var_name in op.output_arg_names: + output_dims_mapping = dist_op.dist_attr.get_output_dims_mapping( + var_name + ) + if var_name not in var_info: + var_info[var_name] = {} + key = _convert_pm_and_dm_to_str( + process_mesh, output_dims_mapping + ) + if key not in var_info[var_name]: + var_info[var_name][key] = {} + if "memory" not in var_info[var_name][key]: + var = dist_op.get_serial_output(var_name) + global_sizes = var.shape + dtype = var.dtype + sizes = DistributedTensor.get_local_sizes( + global_sizes, + output_dims_mapping, + process_mesh.topology, + process_mesh.processes, + ) + var_info[var_name][key]["memory"] = self._calculate_bytes( + sizes, dtype + ) + if "position" not in var_info[var_name][key]: + var_info[var_name][key]["position"] = [] + var_info[var_name][key]["position"].append(op_id) + + has_used_vars = set() + for op_id, op in self._ordered_ops: + if op.type in [ + "create_py_reader", + "create_double_buffer_reader", + "read", + ]: + continue + can_free_memories = {} + can_free_vars = set() + dist_op = dist_context.get_dist_op_for_program(op) + process_mesh = dist_op.dist_attr.process_mesh + for var_name in op.input_arg_names: + input_dims_mapping = dist_op.dist_attr.get_input_dims_mapping( + var_name + ) + key = _convert_pm_and_dm_to_str( + process_mesh, input_dims_mapping + ) + has_used_var = var_name + key + var = dist_op.get_serial_input(var_name) + # Not used + if var_name + key not in has_used_vars: + has_used_vars.add(has_used_var) + for process in process_mesh.processes: + if process not in memories: + memories[process] = 0 + memories[process] += var_info[var_name][key]["memory"] + # Used + else: + if op_id == var_info[var_name][key]["position"][-1]: + if has_used_var not in can_free_vars: + can_free_vars.add(has_used_var) + if not var.persistable: + for process in process_mesh.processes: + if process not in can_free_memories: + can_free_memories[process] = 0 + can_free_memories[process] += var_info[ + var_name + ][key]["memory"] + + for var_name in op.output_arg_names: + output_dims_mapping = dist_op.dist_attr.get_output_dims_mapping( + var_name + ) + key = _convert_pm_and_dm_to_str( + process_mesh, output_dims_mapping + ) + has_used_var = var_name + key + var = dist_op.get_serial_output(var_name) + # Not used + if var_name + key not in has_used_vars: + has_used_vars.add(has_used_var) + for process in process_mesh.processes: + if process not in memories: + memories[process] = 0 + memories[process] += var_info[var_name][key]["memory"] + # Used + else: + if op_id == var_info[var_name][key]["position"][-1]: + if has_used_var not in can_free_vars: + can_free_vars.add(has_used_var) + if not var.persistable: + for process in process_mesh.processes: + if process not in can_free_memories: + can_free_memories[process] = 0 + can_free_memories[process] += var_info[ + var_name + ][key]["memory"] + + # Calc peak memory + for process in memories: + if process not in self.max_memories: + self.max_memories[process] = memories[process] + else: + if memories[process] > self.max_memories[process]: + self.max_memories[process] = memories[process] + + # Free memory + for process in can_free_memories: + if process in memories: + memories[process] -= can_free_memories[process] + + # Calculate the max memory in all ranks + max_memory = max(self.max_memories.values()) + self.max_memory = max_memory + + return max_memory + + def estimate(self, dist_context, resharder=None): + self.prepare() + from ..reshard import Resharder + + resharder = ( + Resharder(self.program, None, self.rank, dist_context, []) + if resharder is None + else resharder + ) + + block = self.program.global_block() + self._estimate_core(dist_context, resharder, block) + + return self.global_cost + + def _print_tag(self, max_len, length): + tag = "+" + "-" * max_len + for i in range(length): + print(tag, end="") + if i == length - 1: + print("+") + + def _print_vals(self, vals, max_len): + for idx, val in enumerate(vals): + s = "|" + str(val).center(max_len) + print(s, end="") + if idx == len(vals) - 1: + print("|") + + def _pretty_print_memory_cost(self): + """Print memory of every rank prettily.""" + if not self.max_memories or not self.max_memory: + raise ValueError("Please calculate memory cost before print.") + + # Padding automatically + max_len = 0 + header = ["Rank", "Memory(MiB)"] + memories = [ + int(item // 1e6) for item in list(self.max_memories.values()) + ] + for memory in memories + header: + if len(str(memory)) > max_len: + max_len = len(str(memory)) + max_len += 4 # for pretty print of center + + # Print tag + self._print_tag(max_len, len(header)) + + # Print header + self._print_vals(header, max_len) + + # Print tag + self._print_tag(max_len, len(header)) + + # Print rank and its memory + for i in range(len(self.max_memories)): + memory = memories[i] + vals = [i, memory] + self._print_vals(vals, max_len) + self._print_tag(max_len, len(header)) + + def _pretty_print_global(self): + """Print global execution time and max memory prettily.""" + if not self.max_memories or not self.max_memory: + raise ValueError("Please calculate cost before print.") + + # Padding automatically + max_len = 0 + header = ["Execution Time(ms)", "Max Memory(MiB)"] + vals = [round(self.global_cost.time, 3), int(self.max_memory // 1e6)] + for memory in vals + header: + if len(str(memory)) > max_len: + max_len = len(str(memory)) + max_len += 4 # for pretty print of center + + # Print tag + self._print_tag(max_len, len(header)) + + # Print header + self._print_vals(header, max_len) + + # Print tag + self._print_tag(max_len, len(header)) + + # Print exec time and max memory + self._print_vals(vals, max_len) + + # Print tag + self._print_tag(max_len, len(header)) + + def pretty_print_cost(self): + """Print cost prettily.""" + print("The global execution time and max memory are as follows:") + self._pretty_print_global() + print("The memory of every rank is as follows:") + self._pretty_print_memory_cost() + + +def get_cost_from_engine(engine, mode): + from ..utils import to_list + import copy + + # Construct cost estimator by original main program + serial_main_prog = ( + engine._fwd_main_progs[mode].clone() + if mode in engine._fwd_main_progs + else engine._orig_main_prog.clone() + ) + + serial_startup_prog = ( + engine._serial_startup_progs[mode].clone() + if mode in engine._serial_startup_progs + else engine._orig_startup_prog.clone() + ) + losses = ( + to_list(engine._loss) + if ( + not isinstance(engine._loss, paddle.nn.Layer) + and not callable(engine._loss) + ) + else engine._losses + ) + serial_optimizer = copy.deepcopy(engine._orig_optimizer) + if mode in engine._fwd_dist_contexts: + dist_context = copy.deepcopy(engine._fwd_dist_contexts[mode]) + else: + from ..dist_context import DistributedContext + + dist_context = DistributedContext( + serial_main_prog, + serial_startup_prog, + serial_optimizer, + losses, + {}, + {"loss": losses}, + engine._cluster, + engine._strategy, + ) + from ..completion import Completer + + completer = Completer(dist_context) + completer.complete_forward_annotation() + dist_context.block_state.parse_forward_blocks( + dist_context.serial_main_program + ) + + if mode == "eval" or mode == "predict": + cost_estimator = CostEstimator(serial_main_prog, engine._cluster) + elif mode == "train": + from ..parallelizer_v2 import Parallelizer + + # Get serial main program with backward + parallelizer = Parallelizer(mode, completer, dist_context) + # Generate backward + loss_name = dist_context.serial_loss.name + serial_loss = serial_main_prog.global_block()._var_recursive(loss_name) + params_grads = parallelizer._generate_backward( + serial_main_prog, serial_startup_prog, serial_loss + ) + + # Generate optimizer + optimizer_ops = parallelizer._generate_optimizer( + serial_main_prog, + serial_startup_prog, + serial_optimizer, + params_grads, + ) + cost_estimator = CostEstimator(serial_main_prog, engine._cluster) + + # Estimate global_cost and max memory + global_cost = cost_estimator.estimate(dist_context) + max_memory = cost_estimator._estimate_max_memory_by_dist_op(dist_context) + + # Print the cost + cost_estimator.pretty_print_cost() + + return global_cost, max_memory diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/tensor_cost.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/tensor_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..9741020da65127b2d9198674d9271774cbb5ccba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost/tensor_cost.py @@ -0,0 +1,111 @@ +# Copyright (c) 2022 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 + +from functools import reduce + +import paddle +from paddle.fluid.framework import Variable +from paddle.distributed.auto_parallel.dist_tensor import DistributedTensor + +from .base_cost import Cost + + +class TensorCost: + + def __init__(self, tensor=None, dist_tensor=None, shape=None, dtype=None): + self._check_args(tensor, dist_tensor, shape, dtype) + self._tensor = tensor + self._dist_tensor = dist_tensor + self._shape = shape + self._dtype = dtype + self._cost = self.calc_cost() + + @property + def tensor(self): + return self._tensor + + @property + def dist_tensor(self): + return self._dist_tensor + + @property + def shape(self): + return self._shape + + @property + def dtype(self): + return self._dtype + + def _check_args(self, tensor, dist_tensor, shape, dtype): + if tensor is not None: + assert (shape is None and dist_tensor is None and dtype is None) + + if not isinstance(tensor, Variable): + raise TypeError( + "Please check tensor type is Variable, but got {}".format( + type(tensor))) + + elif dist_tensor is not None: + assert (tensor is None and shape is None) + if not isinstance(dist_tensor, DistributedTensor): + raise TypeError( + "Please check dist_tensor type is DistributedTensor, but got {}" + .format(type(dist_tensor))) + + elif shape is not None: + assert (tensor is None and dist_tensor is None + and dtype is not None) + if not isinstance(shape, (list, set)): + raise TypeError( + "Please check shape type is list or set, but got {}".format( + type(shape))) + + elif dtype is not None: + assert (tensor is None and dist_tensor is None + and shape is not None) + + @property + def cost(self): + return self._cost + + def calc_cost(self): + dtype = None + shape = None + + if self.dist_tensor: + shape = self.dist_tensor.local_sizes() + dtype = self.dist_tensor.serial_tensor.dtype + elif self.tensor: + shape = self.tensor.shape + dtype = self.tensor.dtype + elif self.shape and self.dtype: + shape = self.shape + dtype = self.dtype + + total_count = reduce(lambda x, y: x * y, shape) + + if dtype == paddle.float32 or dtype == paddle.int32: + dtype_factor = 4 + elif node.dtype == paddle.int64: + dtype_factor = 8 + elif node.dtype == paddle.uint8: + dtype_factor = 1 + else: + dtype_factor = 2 + + memory = total_count * dtype_factor + assert memory >= 0 + cost = Cost(memory=memory) + + return cost diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost_model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e35fae57caec691a19ab84c5d667ce8a5432a19b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/cost_model.py @@ -0,0 +1,808 @@ +# Copyright (c) 2021 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. + +import json +import queue +import copy +from enum import Enum + +import numpy as np + +import paddle +from paddle.fluid import core +from paddle.distributed.fleet.meta_optimizers.common import OpRole + +SUCC = 0 # successor +PRED = 1 # predecessor + + +class CostNodeType(Enum): + DEFAULT = 0 + COMPUTATION = 1 + COMMUNICATION = 2 + VARIABLE = 3 + MERGED = 4 + NOP = 5 + + +class Cost(object): + + def __init__(self): + self.runtime = None + self.static_mem = None + self.peak_mem = None + + +class CostModelMode(Enum): + DEFAULT = 0 + BENCHMARKING = 1 # costs based on trial runs + ANALYSIS = 2 # costs based on analysis + MIXED = 3 + + +class CostNode(object): + + def __init__(self, node, node_type, id=None): + self.id = id + self.node = node + self.type = node_type + self._cost = 0 + self.is_optim = False + self.is_bwd = False + + @property + def cost(self): + return self._cost + + @cost.setter + def cost(self, cost): + if cost < 0: + raise ValueError('Cost must be above 0.') + self._cost = cost + + +class MergedOpsCostNode(CostNode): + + def __init__(self, node_type, id=None, base_node_list=None, is_bwd=False): + super(MergedOpsCostNode, self).__init__(None, node_type, id) + self.node_list = base_node_list + self.is_bwd = is_bwd + + +class CommOpCostNode(CostNode): + + def __init__(self, + node, + node_type, + id=None, + comm_node_list=None, + is_bwd=False): + super(CommOpCostNode, self).__init__(node, node_type, id) + self.node_list = comm_node_list + self.ranks = [] + self.comm_type = node.type + self.is_bwd = is_bwd + + def set_ranks(self, ranks): + self.ranks = ranks + + def set_shapes(self, input_shape, output_shape): + self.input_shape = input_shape + self.output_shape = output_shape + + def init_comm_cost(self, cluster=None): + # ref: https://github.com/NVIDIA/nccl-tests/blob/master/doc/PERFORMANCE.md + # should get from `cluster` + BANDWIDTH = 32 * 1024 / 1000 # MB/ms, V100 PCIe + num_ranks = len(self.ranks) + comm_volumn = np.prod(self.input_shape) * 4 + + if 'allreduce' in self.comm_type: + self._cost = comm_volumn / (BANDWIDTH * num_ranks / + (2 * (num_ranks - 1))) + elif 'gather' in self.comm_type: + self._cost = comm_volumn / (BANDWIDTH * num_ranks / (num_ranks - 1)) + elif 'broadcast' in self.comm_type: + self._cost = comm_volumn / BANDWIDTH + elif 'send' in self.comm_type or 'recv' in self.comm_type: + self._cost = comm_volumn / BANDWIDTH + else: + self._cost = 0 + + +class TensorCostNode(CostNode): + + def __init__(self, + node, + node_type, + id=None, + base_node_list=None, + batch_size=None, + shared_node_id=None): + super(TensorCostNode, self).__init__(node, node_type, id) + if node.name == "create_py_reader_0" or node.name == "double_buffer_0": + self.shape = [2, 2] + self.dtype = paddle.float32 + else: + self.shape = node.shape + self.dtype = node.dtype + self.dtype_factor = 1 + self.persistable = None + self.shared_node_id = shared_node_id + if self.dtype == paddle.float32 or node.dtype == paddle.int32: + self.dtype_factor *= 4 + elif node.dtype == paddle.int64: + self.dtype_factor *= 8 + elif node.dtype == paddle.uint8: + self.dtype_factor = 1 + else: + self.dtype_factor = 2 + # raise NotImplementedError("{} not counted".format(node.dtype)) + self.batch_size = None + if batch_size is not None: + self.batch_size = batch_size + + def get_size(self): + p = 1 + for i in self.node.shape: + if i == -1: # deal with placeholder + assert self.batch_size is not None, "Batch size not decided." + i = self.batch_size + p *= i + return p + + +class CompOpCostNode(CostNode): + + def __init__(self, node, node_type, id=None, is_bwd=False, is_optim=False): + super(CompOpCostNode, self).__init__(node, node_type, id) + self.is_bwd = is_bwd + self.is_optim = is_optim + + def init_comp_cost(self, cost_data): + # TODO: improve fluid.CostModel for more specific cost_data + op_id = self.node.desc.id() + if op_id in cost_data.keys(): + self.cost = cost_data[op_id] + else: + self.cost = 0.0 + + +class PipeEvent(object): + + def __init__(self, stage_id, event_name, duration, start_time=-1): + self.stage_id = stage_id + self.name = event_name + self.duration = duration + self.s_time = start_time + self.e_time = -1 + + +class CostModel(object): + + def __init__(self, + mode=CostModelMode.BENCHMARKING, + cluster=None, + batch_size=1, + microbatch_num=1, + opcall_overhead=0, + standalone_cost_data=None, + pipeline_config=None): + self.mode = mode + + # parameters + self.opcall_overhead = opcall_overhead + self.batch_size = batch_size + self.microbatch_num = microbatch_num + + self.nodes = {} # name -> node + + self.origin_graph = {} # original graph + self.op_graph = {} # op graph (no variables nodes) + self.runtime_graph = {} # runtime graph, for simulation + + self.cluster = cluster + self.cost_data = standalone_cost_data + self.pp2rank = pipeline_config + if self.pp2rank is not None: + self.rank2pp = {} + for stage_idx, ranks in enumerate(self.pp2rank): + for rank in ranks: + self.rank2pp[rank] = stage_idx + else: + self.rank2pp = None + + self.ring2rank = {} + + self.fwd_time = [] + self.bwd_time = [] + self.optim_time = [] + + def _parse_sub_program(self, program, nodes, graph, cost_data, sub_idx): + assert len( + program.blocks) == 1, "Program more than 1 block not supported." + block = program.blocks[0] + + var_id = "lod_tensor_blocking_queue_0" + new_var = program.global_block().create_var( + name=var_id, + dtype=paddle.float32, + type=core.VarDesc.VarType.LOD_TENSOR) + nodes[var_id] = TensorCostNode(new_var, CostNodeType.VARIABLE, + "lod_tensor_blocking_queue_0") + for var in block.vars.values(): + var_id = var.name + # if var.name == "create_py_reader_0" or var.name == "double_buffer_0": + # continue + nodes[var_id] = TensorCostNode(var, CostNodeType.VARIABLE, var_id) + graph[var_id] = [[], []] + + for op in block.ops: + op_id = op.type + "_" + str(op.idx) + if op.type.startswith('c_') or op.type.startswith( + 'send') or op.type.startswith('recv'): + is_bwd = False + if op.type.startswith( + 'c_' + ) and op.type != "c_sync_calc_stream" and not op.type.startswith( + 'c_embedding'): + ring_id = op.attr('ring_id') + if ring_id not in self.ring2rank: + self.ring2rank[ring_id] = set() + self.ring2rank[ring_id].add(sub_idx) + is_bwd = '@GRAD' in op.output('Out')[0] + elif op.type.startswith('recv'): + is_bwd = '@GRAD' in op.output('Out')[0] + elif op.type.startswith('send'): + is_bwd = '@GRAD' in op.input('X')[0] + op_node = CommOpCostNode(op, CostNodeType.COMMUNICATION, op_id, + is_bwd) + else: + is_bwd = (int(op.attr('op_role')) == int( + OpRole.Backward)) or "@GRAD" in op.input_arg_names + is_optim = 'LearningRate' in op.input_names + op_node = CompOpCostNode(op, CostNodeType.COMPUTATION, op_id, + is_bwd, is_optim) + op_node.init_comp_cost(cost_data) + + nodes[op_id] = op_node + graph[op_id] = [[], []] + + comm_input_shape = [0] + comm_output_shape = [0] + for i in range(len(op.input_names)): + try: + var_id = op.input(op.input_names[i])[0] + var_node = nodes[var_id] + graph[op_id][PRED].append(var_node.id) + graph[var_id][SUCC].append(op_node.id) + comm_input_shape = var_node.shape + except: + continue + + for i in range(len(op.output_names)): + try: + var_id = op.output(op.output_names[i])[0] + var_node = nodes[var_id] + graph[op_id][SUCC].append(var_node.id) + graph[var_id][PRED].append(op_node.id) + comm_output_shape = var_node.shape + except: + continue + if op_node.type == CostNodeType.COMMUNICATION: + op_node.set_shapes(comm_input_shape, comm_output_shape) + + # resolve hazard: rename the r/w hazard variable nodes to ensure self.origin_graph is a DAG + new_var_dict = {} + for node_id, node in nodes.items(): + if node.type == CostNodeType.VARIABLE and node.node.persistable: + write_op_cnt = 0 + for pred_id in graph[node_id][PRED]: + pred = nodes[pred_id] + if pred.type == CostNodeType.COMPUTATION and ( + pred_id in graph[node_id][SUCC]): + + graph[pred_id][SUCC].remove(node_id) + graph[node_id][PRED].remove(pred_id) + + write_op_cnt += 1 + new_var_id = node_id + '_write_{}'.format(write_op_cnt) + new_var = TensorCostNode(node.node, + CostNodeType.VARIABLE, + new_var_id, + shared_node_id=node_id) + + graph[new_var_id] = [[], []] + graph[pred_id][SUCC].append(new_var_id) + graph[new_var_id][PRED].append(pred_id) + + new_var_dict[new_var_id] = new_var + for k, v in new_var_dict.items(): + nodes[k] = v + return nodes + + def parse_program(self, distributed_program): + self.distributed_program = distributed_program + self.total_rank = len(self.distributed_program) + sub_prog_cnt = len(distributed_program) + self.nodes = [] * sub_prog_cnt + self.origin_graph = [] * sub_prog_cnt # original graph + self.op_graph = [] * sub_prog_cnt # op graph (no variables nodes) + self.runtime_graph = [] * sub_prog_cnt # runtime graph, for simulation + + for sub_idx, sub_prog in enumerate(distributed_program): + self.nodes.append({}) + self.origin_graph.append({}) + self.op_graph.append({}) + self.runtime_graph.append({}) + self._parse_sub_program( + sub_prog, self.nodes[sub_idx], self.origin_graph[sub_idx], + self.cost_data[0 if self.rank2pp is None else self. + rank2pp[sub_idx]], sub_idx) + return self.nodes + + def _find_succ_op(self, node_id, sub_idx=0): + succ_ops_id = [] + for succ_id in self.origin_graph[sub_idx][node_id][SUCC]: + succ = self.nodes[sub_idx][succ_id] + if succ.type == CostNodeType.COMMUNICATION or \ + succ.type == CostNodeType.COMPUTATION: + succ_ops_id.append(succ_id) + elif succ.type == CostNodeType.VARIABLE: + succ_ops_id = succ_ops_id + self._find_succ_op(succ_id, sub_idx) + else: + raise NotImplementedError( + 'This type of node not supported yet:{}'.format(succ.type)) + return succ_ops_id + + def build_op_graph(self): + for sub_idx in range(self.total_rank): + op_nodes_id = [] + for node_id, node in self.nodes[sub_idx].items(): + if node.type == CostNodeType.VARIABLE: + continue + self.op_graph[sub_idx][node_id] = [[], []] + op_nodes_id.append(node_id) + for op_id in op_nodes_id: + succ_nodes_id = self._find_succ_op(op_id, sub_idx) + + self.op_graph[sub_idx][op_id][SUCC] = succ_nodes_id + for succ_id in succ_nodes_id: + self.op_graph[sub_idx][succ_id][PRED].append(op_id) + + def build_runtime_graph(self): + self.runtime_graph = copy.deepcopy(self.op_graph) + + def eliminate_multi_edges(self, graph=None): + for node_id, edges in graph.items(): + graph[node_id][PRED] = list(set(edges[PRED])) + graph[node_id][SUCC] = list(set(edges[SUCC])) + + def merge_comm(self): + for sub_idx in range(self.total_rank): + for node_id, edges in self.op_graph[sub_idx].items(): + node = self.nodes[sub_idx][node_id] + if node_id.startswith('c_') and not node.id.startswith( + "c_sync_calc_stream") and not node.id.startswith( + 'c_embedding'): + ring_id = node.node.attr('ring_id') + node.set_ranks(list(self.ring2rank[ring_id])) + node.init_comm_cost(self.cluster) + elif node_id.startswith('send') or node_id.startswith('recv'): + peer_rank = node.node.attr('peer') + node.set_ranks([sub_idx, peer_rank]) + node.init_comm_cost(self.cluster) + else: + pass # Not communication op + + def _merge_node(self, to_merge_node_list, merge_type='linear', nodes=None): + nodes_list = [] + node_cost = 0 + for node in to_merge_node_list: + if isinstance(node, MergedOpsCostNode): + nodes_list += node.node_list + else: + nodes_list.append(node.id) + if merge_type == 'linear': + node_cost += node.cost + elif merge_type == 'branch': + node_cost = max(node_cost, node.cost) + else: + raise NotImplementedError( + 'This type of merging is not supported:{}'.format( + merge_type)) + merged_node_id = 'merged_' + str(len(nodes)) + is_bwd = to_merge_node_list[0].is_bwd + merged_node = MergedOpsCostNode(CostNodeType.MERGED, + id=merged_node_id, + base_node_list=nodes_list, + is_bwd=is_bwd) + merged_node.cost = node_cost + return merged_node_id, merged_node + + def merge_linear(self): + r''' + This method does the following: + If X depends on Y only, they must be run sequentially. + [ e.g. A ->- C ->- D D and E depends on C only.] + [ B ->-/ \->- E C depends on A and B. ] + We merge X and Y into a new node and sum up their cost time. + ''' + cnt = 0 + for sub_idx in range(self.total_rank): + cnt += self._merge_linear(self.nodes[sub_idx], + self.runtime_graph[sub_idx], + is_bwd=False) + cnt += self._merge_linear(self.nodes[sub_idx], + self.runtime_graph[sub_idx], + is_bwd=True) + return cnt + + def merge_branch(self): + r''' + This method does the following: + If a node has more than one successor, there is *branch*. + [ e.g. A ->- B ->- D ] + [ \->- C ->- / , B and C can be run at the same time ] + case 1: if B or C is null (or D is directly dependent on A), + it's equivalent to A->C->D or A->B->D, fall back to self.merge_linear + case 2: if both B and C are some op, + merged_cost = max(cost(B), cost(C)) + ''' + cnt = 0 + for sub_idx in range(self.total_rank): + cnt += self._merge_branch(self.nodes[sub_idx], + self.runtime_graph[sub_idx], + is_bwd=False) + cnt += self._merge_branch(self.nodes[sub_idx], + self.runtime_graph[sub_idx], + is_bwd=True) + return cnt + + def _merge_linear(self, nodes, runtime_graph, is_bwd=False): + reduct_cnt = 0 + rt_nodes_id = list(runtime_graph.keys()) + for node_id in rt_nodes_id: + if node_id not in runtime_graph.keys(): + continue + node = nodes[node_id] + if not is_bwd == node.is_bwd or node.is_optim: + continue + edges = runtime_graph[node_id] + ind = len(edges[PRED]) # in_degree + if ind == 1: # only depend on one node + pred_id = edges[PRED][0] + pred = nodes[pred_id] + merged_node_id, merged_node = self._merge_node( + [node, pred], merge_type='linear', nodes=nodes) + nodes[merged_node_id] = merged_node + runtime_graph[merged_node_id] = [[], []] + + # delete edges and add new edges + succ = None + try: + runtime_graph[merged_node_id][SUCC] = copy.deepcopy( + edges[SUCC]) + + if len(runtime_graph[pred_id][SUCC]) > 1: + # predecessor has more than 1 successor + # the merged_node is to inherit the rest of its successors + succ = runtime_graph[pred_id][SUCC] + succ.remove(node_id) + runtime_graph[merged_node_id][SUCC] += succ + runtime_graph[merged_node_id][PRED] = runtime_graph[ + pred_id][PRED] + except: + pass + try: + for i in runtime_graph[pred_id][PRED]: + try: + runtime_graph[i][SUCC].remove(pred_id) + except: + continue + runtime_graph[i][SUCC].append(merged_node_id) + except: + pass + + try: + for i in edges[SUCC]: + runtime_graph[i][PRED].remove(node_id) + runtime_graph[i][PRED].append(merged_node_id) + except: + pass + if succ is not None: + for i in succ: + try: + runtime_graph[i][PRED].remove(pred_id) + except: + continue + runtime_graph[i][PRED].append(merged_node_id) + + runtime_graph.pop(node_id) + try: + runtime_graph.pop(pred_id) + except: + continue + reduct_cnt += 1 + self.eliminate_multi_edges(runtime_graph) + break + return reduct_cnt # the number of nodes that have been reduced + + def _merge_branch(self, nodes, runtime_graph, is_bwd=False): + reduct_cnt = 0 + rt_nodes_id = list(runtime_graph.keys()) + for node_id in rt_nodes_id: + node = nodes[node_id] + if not is_bwd == node.is_bwd or node.is_optim: + continue + edges = runtime_graph[node_id] + outd = len(edges[SUCC]) # out_degree + if outd > 1: # branch out + succ_nodes_id = edges[SUCC] + + succ_to_elim = [] + for succ_id in succ_nodes_id: + for succ_2_id in succ_nodes_id: + try: + tmp = runtime_graph[succ_2_id][SUCC] + except: + continue + if succ_id in tmp: + succ_to_elim.append(succ_id) + break + for id in succ_to_elim: + edges[SUCC].remove(id) + runtime_graph[id][PRED].remove(node_id) + reduct_cnt += 1 + + to_merge = True + try: + if len(edges[SUCC]) < 1 or len( + runtime_graph[edges[SUCC][0]][SUCC]) < 1: + continue + except: + continue + end_node_id = runtime_graph[edges[SUCC][0]][SUCC][0] + for i in succ_nodes_id: + try: + if len(runtime_graph[i][SUCC]) != 1 or \ + runtime_graph[i][SUCC][0] != end_node_id: + to_merge = False # if branches has different end node, we don't merge them + break + except: + continue + if to_merge and len(succ_nodes_id) > 1: + to_merge_node_list = [nodes[i] for i in succ_nodes_id] + merged_node_id, merged_node = self._merge_node( + to_merge_node_list, merge_type='branch', nodes=nodes) + nodes[merged_node_id] = merged_node + runtime_graph[merged_node_id] = [[], []] + + # delete edges and add new edges + runtime_graph[merged_node_id][SUCC] = [end_node_id] + runtime_graph[merged_node_id][PRED] = edges[PRED] + + runtime_graph[end_node_id][PRED] = [merged_node_id] + runtime_graph[node_id][SUCC] = [merged_node_id] + + try: + for i in succ_nodes_id: + runtime_graph.pop(i) + reduct_cnt += len(to_merge_node_list) - 1 + break + except: + pass + return reduct_cnt + + def get_runtime_cost(self): + + def get_node_cost(node): + node_cost = node.cost + self.opcall_overhead + if isinstance(node, MergedOpsCostNode): + for it in node.node_list: + node_cost += self.opcall_overhead + return node_cost + + for sub_idx in range(self.total_rank): + fwd_cost = 0 + bwd_cost = 0 + optim_cost = 0 + for node_id in self.runtime_graph[sub_idx].keys(): + node = self.nodes[sub_idx][node_id] + if node.is_optim: + optim_cost += get_node_cost(node) + elif node.is_bwd: + bwd_cost += get_node_cost(node) + else: + fwd_cost += get_node_cost(node) + self.fwd_time.append(fwd_cost) + self.bwd_time.append(bwd_cost) + self.optim_time.append(optim_cost) + return self.fwd_time, self.bwd_time, self.optim_time + + def get_mem(self): + static_list = [] + top_list = [] + for sub_idx in range(self.total_rank): + static_mem, cur_mem, top_mem = self._simulate_mem( + self.nodes[sub_idx], self.origin_graph[sub_idx]) + static_list.append(static_mem) + top_list.append(top_mem) + return static_list, top_list + + def _simulate_mem(self, nodes, origin_graph): + q = queue.Queue(1024) + sim_graph = copy.deepcopy(origin_graph) + for node_id, node in nodes.items(): + if len(sim_graph[node_id][PRED]) == 0: + q.put(node_id) + + q.put('nop') + cur_mem = 0 + top_mem = -1 + static_mem = 0 + while not q.empty(): + node_id = q.get() + node = None + size = 0 + if node_id == 'nop': + top_mem = max(cur_mem, top_mem) + if q.empty(): + break + else: + q.put(node_id) + continue + else: + node = nodes[node_id] + if node.type == CostNodeType.VARIABLE: + size = node.get_size() + if node.node.persistable: + static_mem += size + cur_mem += size + edges = sim_graph[node_id] + if not (node.type == CostNodeType.VARIABLE + and node.node.persistable): + for succ_id in edges[SUCC]: + sim_graph[succ_id][PRED].remove(node_id) + if len(sim_graph[succ_id][PRED]) == 0: + q.put(succ_id) + for pred_id in edges[PRED]: + pred = nodes + if pred.type == CostNodeType.VARIABLE: + sim_graph[pred_id][SUCC].remove(node_id) + if len(sim_graph[pred_id] + [SUCC]) == 0 and not pred.node.persistable: + cur_mem -= pred.get_size() + return static_mem, cur_mem, top_mem + + def get_pipeline_time(self): + if self.pp2rank is None: + return self.fwd_time[0] + self.bwd_time[0] + self.optim_time[0] + else: + return self._simulate_pipeline() + + def _simulate_pipeline(self): + stage_num = len(self.pp2rank) + event_list = [] + global_time = [0] * stage_num + total_time = 0 + fwd_cnt = list(range(stage_num, 0, -1)) + bwd_cnt = [self.microbatch_num] * stage_num + q = queue.Queue(1024) + + for i in range(self.microbatch_num): + q.put(PipeEvent(0, 'fwd', self.fwd_time[0])) + + while not q.empty(): + e = q.get() + stid = e.stage_id + if e.name == 'fwd': + if fwd_cnt[stid] > 0: + e.s_time = max(global_time[stid], e.s_time) + e.e_time = e.s_time + e.duration + event_list.append(e) + if stid != stage_num - 1: + q.put( + PipeEvent(stid + 1, + 'fwd', + self.fwd_time[stid + 1], + start_time=e.e_time)) + else: + q.put( + PipeEvent(stid, + 'bwd', + self.bwd_time[stid], + start_time=e.e_time)) + fwd_cnt[stid] -= 1 + global_time[stid] = e.e_time + else: + q.put(e) + elif e.name == 'bwd': + e.s_time = max(global_time[stid], e.s_time) + e.e_time = e.s_time + e.duration + event_list.append(e) + if stid != 0: + q.put( + PipeEvent(stid - 1, + 'bwd', + self.bwd_time[stid - 1], + start_time=e.e_time)) + fwd_cnt[stid] += 1 + bwd_cnt[stid] -= 1 + if bwd_cnt[stid] == 0: + q.put( + PipeEvent(stid, + 'optim', + self.optim_time[stid], + start_time=e.e_time)) + global_time[stid] = e.e_time + elif e.name == 'optim': + e.s_time = max(global_time[stid], e.s_time) + e.e_time = e.s_time + e.duration + event_list.append(e) + global_time[stid] = e.e_time + else: + raise NotImplementedError( + 'This type of pipe event is not supported yet.{}'.format( + e.name)) + + for t in global_time: + total_time = max(total_time, t) + return total_time + + def get_cost(self): + cost = Cost() + static_mem, peak_mem = self.get_mem() + cost.static_mem = static_mem + cost.peak_mem = peak_mem + self.merge_comm() + while True: + cnt = 0 + cnt += self.merge_linear() + cnt += self.merge_branch() + if cnt == 0: # can't be further merged + break + self.get_runtime_cost() + cost.runtime = self.get_pipeline_time() + return cost + + def init(self, distributed_program): + self.parse_program(distributed_program) + self.build_op_graph() + for sub_idx in range(self.total_rank): + self.eliminate_multi_edges(self.op_graph[sub_idx]) + self.build_runtime_graph() + + +def estimate_cost(distributed_program, cluster, pipeline_config, + standalone_cost_data, batch_size): + """ + Estimated cost from distributed program, cluster model and distributed settings. + + Args: + distributed_program(list): list of paddle programs + cluster(Cluster): cluster model + standalone_cost_data(CostData): cost data given by paddle.core + batch_size(int): batch size of the training workload + pipeline_config(list): configuration of pipeline stage allocation + """ + # the following line is left for now, cluster model will be involved in the future + assert cluster is None, "For now, cluster remains None" + cm_ctx = CostModel(cluster=cluster, + batch_size=batch_size, + standalone_cost_data=standalone_cost_data, + pipeline_config=pipeline_config) + cm_ctx.init(distributed_program) + cost = cm_ctx.get_cost() + return cost diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_attribute.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..92d0304eaf6138371261fe4781d31656e3c1185d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_attribute.py @@ -0,0 +1,539 @@ +# Copyright (c) 2021 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 + +import copy +from collections import defaultdict +from paddle.fluid.framework import Variable +from .process_mesh import ProcessMesh + +_g_tensor_dist_attr_field_keys = [ + "process_mesh", "dims_mapping", "shard_sizes", "device_placement" +] + +_g_op_dist_attr_field_keys = [ + "process_mesh", "impl_type", "impl_idx", "is_recompute" +] + +_g_op_input_suffix = "@input" + +_g_op_output_suffix = "@output" + + +def get_tensor_dist_attr_field_keys(): + global _g_tensor_dist_attr_field_keys + return _g_tensor_dist_attr_field_keys + + +def get_op_dist_attr_field_keys(): + global _g_op_dist_attr_field_keys + return _g_op_dist_attr_field_keys + + +def append_op_input_suffix(name): + global _g_op_input_suffix + return name + _g_op_input_suffix + + +def append_op_output_suffix(name): + global _g_op_output_suffix + return name + _g_op_output_suffix + + +class TensorDistributedAttribute: + + def __init__(self): + # The process mesh of distributed operator attribute must is the same as + # the process meshes of all input and output distributed attributed + self._process_mesh = None + self._dims_mapping = None + self._shard_sizes = None + self._device_placement = None + self._is_annotated = {} + + @property + def process_mesh(self): + return self._process_mesh + + @process_mesh.setter + def process_mesh(self, process_mesh): + if process_mesh is not None: + assert isinstance(process_mesh, (list, ProcessMesh)), \ + "The type of process_mesh must be list or ProcessMesh." + if isinstance(process_mesh, list): + process_mesh = ProcessMesh(process_mesh) + self._process_mesh = copy.deepcopy(process_mesh) + + @property + def dims_mapping(self): + return self._dims_mapping + + @dims_mapping.setter + def dims_mapping(self, dims_mapping): + if dims_mapping is not None: + assert isinstance(dims_mapping, list), \ + "The type of dims_mapping must be list." + assert all(isinstance(x, int) for x in dims_mapping), \ + ("All elements of dims_mapping must be integer") + assert all(x >= -1 for x in dims_mapping), \ + ("All elements of dims_mapping must be greater than or equal to -1.") + self._dims_mapping = copy.deepcopy(dims_mapping) + + @property + def shard_sizes(self): + return self._shard_sizes + + @shard_sizes.setter + def shard_sizes(self, shard_sizes): + if shard_sizes is not None: + self._shard_sizes = copy.deepcopy(shard_sizes) + + @property + def device_placement(self): + return self._device_placement + + @device_placement.setter + def device_placement(self, device_placement): + if device_placement is not None: + self._device_placement = copy.deepcopy(device_placement) + + def init(self, dist_attr): + if dist_attr is None: + return + assert isinstance(dist_attr, (dict, TensorDistributedAttribute)), \ + "The type of dist_attr must be dict or TensorDistributedAttribute." + if isinstance(dist_attr, dict): + for key, value in dist_attr.items(): + if key in get_tensor_dist_attr_field_keys(): + field_property = TensorDistributedAttribute.__dict__.get( + key, None) + if field_property: + field_property.fset(self, value) + else: + assert False, "No setter for {} in args {}.".format( + key, dist_attr) + elif isinstance(dist_attr, TensorDistributedAttribute): + for key in get_tensor_dist_attr_field_keys(): + field_property = TensorDistributedAttribute.__dict__.get( + key, None) + if field_property: + field_property.fset(self, field_property.fget(dist_attr)) + else: + assert False, "No setter for {} in args {}.".format( + key, dist_attr) + self._is_annotated = copy.deepcopy(dist_attr._is_annotated) + + def reset(self, skip_dist_attr_field_names=None): + if skip_dist_attr_field_names is None or \ + (skip_dist_attr_field_names is not None \ + and "process_mesh" not in skip_dist_attr_field_names): + self._process_mesh = None + if skip_dist_attr_field_names is None or \ + (skip_dist_attr_field_names is not None \ + and "dims_mapping" not in skip_dist_attr_field_names): + for i, _ in enumerate(self._dims_mapping): + self._dims_mapping[i] = -1 + self._is_annotated = {} + + def is_annotated(self, dist_attr_field_name): + return self._is_annotated.get(dist_attr_field_name, False) + + # def mark_annotated_all(self): + # for key in get_tensor_dist_attr_field_keys(): + # self.mark_annotated(key) + + def mark_annotated(self, dist_attr_field_name): + self._is_annotated[dist_attr_field_name] = True + + # def unmark_annotated(self, dist_attr_field_name): + # self._is_annotated[dist_attr_field_name] = False + + def mark_annotated_as(self, dist_attr): + if dist_attr is None: + return + assert isinstance(dist_attr, (dict, TensorDistributedAttribute)), \ + "The type of dist_attr must be dict or TensorDistributedAttribute." + if isinstance(dist_attr, dict): + for key in dist_attr.keys(): + if key in get_tensor_dist_attr_field_keys(): + self.mark_annotated(key) + elif isinstance(dist_attr, TensorDistributedAttribute): + self._is_annotated = copy.deepcopy(dist_attr._is_annotated) + + def clear_annotated(self): + self._is_annotated.clear() + + def __eq__(self, other): + if not isinstance(other, TensorDistributedAttribute): + return False + if self.process_mesh != other.process_mesh: + return False + if self.dims_mapping != other.dims_mapping: + return False + if self._is_annotated != other._is_annotated: + return False + return True + + def __str__(self): + str = "\n\ttensor_dist_attr = {" + if self.is_annotated("process_mesh"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += "\n\t\tprocess_mesh ({}): {},".format(annotated_str, + self.process_mesh) + + if self.is_annotated("dims_mapping"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += "\n\t\tdims_mapping ({}): {}".format(annotated_str, + self.dims_mapping) + str += "\n\t}" + return str + + +class OperatorDistributedAttribute: + + def __init__(self): + self._process_mesh = None + self._op_type = None + self._impl_type = None + self._impl_idx = None + self._inputs_dist_attrs = {} + self._outputs_dist_attrs = {} + self._is_annotated = {} + self._is_recompute = False + + @property + def process_mesh(self): + return self._process_mesh + + @process_mesh.setter + def process_mesh(self, process_mesh): + if process_mesh is not None: + assert isinstance(process_mesh, (list, ProcessMesh)), \ + "The type of process_mesh must be list or ProcessMesh." + if isinstance(process_mesh, list): + process_mesh = ProcessMesh(process_mesh) + self._process_mesh = copy.deepcopy(process_mesh) + # In while op, the proess mesh is not shared by all inputs and outputs + if self._op_type == "while": + return None + for dist_attr in self._inputs_dist_attrs.values(): + dist_attr.process_mesh = process_mesh + for dist_attr in self._outputs_dist_attrs.values(): + dist_attr.process_mesh = process_mesh + + @property + def op_type(self): + return self._op_type + + @op_type.setter + def op_type(self, op_type): + if op_type is not None: + self._op_type = op_type + + @property + def impl_type(self): + return self._impl_type + + @impl_type.setter + def impl_type(self, impl_type): + if impl_type is not None: + self._impl_type = impl_type + + @property + def impl_idx(self): + return self._impl_idx + + @impl_idx.setter + def impl_idx(self, impl_idx): + if impl_idx is not None: + self._impl_idx = impl_idx + + @property + def is_recompute(self): + return self._is_recompute + + @is_recompute.setter + def is_recompute(self, is_recompute): + assert isinstance(is_recompute, bool) + self._is_recompute = is_recompute + + @property + def inputs_dist_attrs(self): + return self._inputs_dist_attrs + + @property + def outputs_dist_attrs(self): + return self._outputs_dist_attrs + + def get_input_dist_attr(self, name): + return self._inputs_dist_attrs.get(name, None) + + def set_input_dist_attr(self, name, dist_attr): + dist_attr_object = TensorDistributedAttribute() + dist_attr_object.init(dist_attr) + self._inputs_dist_attrs[name] = dist_attr_object + + def del_input_dist_attr(self, name): + del self._inputs_dist_attrs[name] + + def get_output_dist_attr(self, name): + return self._outputs_dist_attrs.get(name, None) + + def set_output_dist_attr(self, name, dist_attr): + dist_attr_object = TensorDistributedAttribute() + dist_attr_object.init(dist_attr) + self._outputs_dist_attrs[name] = dist_attr_object + + def del_output_dist_attr(self, name): + del self._outputs_dist_attrs[name] + + def get_input_dims_mapping(self, name): + input_dist_attr = self.get_input_dist_attr(name) + if input_dist_attr: + dims_mapping = input_dist_attr.dims_mapping + else: + dims_mapping = None + return dims_mapping + + def set_input_dims_mapping(self, name, dims_mapping): + input_dist_attr = self.get_input_dist_attr(name) + if input_dist_attr: + input_dist_attr.dims_mapping = dims_mapping + else: + dist_attr = TensorDistributedAttribute() + dist_attr.dims_mapping = dims_mapping + self._inputs_dist_attrs[name] = dist_attr + + def get_output_dims_mapping(self, name): + output_dist_attr = self.get_output_dist_attr(name) + if output_dist_attr: + dims_mapping = output_dist_attr.dims_mapping + else: + dims_mapping = None + return dims_mapping + + def set_output_dims_mapping(self, name, dims_mapping): + output_dist_attr = self.get_output_dist_attr(name) + if output_dist_attr: + output_dist_attr.dims_mapping = dims_mapping + else: + dist_attr = TensorDistributedAttribute() + dist_attr.dims_mapping = dims_mapping + self._outputs_dist_attrs[name] = dist_attr + + def init(self, dist_attr): + if dist_attr is None: + return + assert isinstance(dist_attr, (dict, OperatorDistributedAttribute)), \ + "The type of dist_attr must be dict or OperatorDistributedAttribute." + if isinstance(dist_attr, dict): + for key, value in dist_attr.items(): + if isinstance(key, Variable): + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.init(value) + if dist_attr.get(append_op_input_suffix(key.name), False): + self.set_input_dist_attr(key.name, tensor_dist_attr) + if dist_attr.get(append_op_output_suffix(key.name), False): + self.set_output_dist_attr(key.name, tensor_dist_attr) + else: + if key in get_op_dist_attr_field_keys(): + field_property = OperatorDistributedAttribute.__dict__.get( + key, None) + if field_property: + field_property.fset(self, value) + else: + assert False, "No setter for {} in args {}.".format( + key, dist_attr) + elif isinstance(dist_attr, OperatorDistributedAttribute): + for tensor_name, tensor_dist_attr in dist_attr.inputs_dist_attrs.items( + ): + self.set_input_dist_attr( + tensor_name, dist_attr.get_input_dist_attr(tensor_name)) + for tensor_name, tensor_dist_attr in dist_attr.outputs_dist_attrs.items( + ): + self.set_output_dist_attr( + tensor_name, dist_attr.get_output_dist_attr(tensor_name)) + self._is_annotated = copy.deepcopy(dist_attr._is_annotated) + for key in get_op_dist_attr_field_keys(): + field_property = OperatorDistributedAttribute.__dict__.get( + key, None) + if field_property: + field_property.fset(self, field_property.fget(dist_attr)) + else: + assert False, "No setter for {} in args {}.".format( + key, dist_attr) + # Make sure proscess_meshes in dist op be same + if self.op_type == "while": + return None + process_meshes = [] + process_meshes.append(self.process_mesh) + for tensor_dist_attr in self.inputs_dist_attrs.values(): + process_meshes.append(tensor_dist_attr.process_mesh) + for tensor_dist_attr in self.outputs_dist_attrs.values(): + process_meshes.append(tensor_dist_attr.process_mesh) + shared_process_mesh = None + for process_mesh in process_meshes: + if process_mesh is not None: + if shared_process_mesh is None: + shared_process_mesh = process_mesh + else: + assert process_mesh == shared_process_mesh, \ + "ProcessMeshes in DistributedOperator must be the same." + self.process_mesh = shared_process_mesh + + def reset(self, skip_dist_attr_field_names=None): + for tensor_dist_attr in self.inputs_dist_attrs.values(): + tensor_dist_attr.reset(skip_dist_attr_field_names) + for tensor_dist_attr in self.outputs_dist_attrs.values(): + tensor_dist_attr.reset(skip_dist_attr_field_names) + if skip_dist_attr_field_names is None or \ + (skip_dist_attr_field_names is not None \ + and "process_mesh" not in skip_dist_attr_field_names): + self._process_mesh = None + self.impl_type = "default" + self.impl_idx = 0 + self._is_annotated = {} + + def is_annotated(self, attr_name): + return self._is_annotated.get(attr_name, False) + + # def mark_annotated_all(self): + # for key in get_op_dist_attr_field_keys(): + # self.mark_annotated(key) + + def mark_annotated(self, attr_name): + if attr_name == "process_mesh": + # Make sure proscess_mesh be annotated consistently + self._is_annotated[attr_name] = True + for tensor_dist_attr in self.inputs_dist_attrs.values(): + tensor_dist_attr.mark_annotated(attr_name) + for tensor_dist_attr in self.outputs_dist_attrs.values(): + tensor_dist_attr.mark_annotated(attr_name) + else: + self._is_annotated[attr_name] = True + + def mark_annotated_as(self, dist_attr): + if dist_attr is None: + return + assert isinstance(dist_attr, (dict, OperatorDistributedAttribute)), \ + "The type of dist_attr must be dict or OperatorDistributedAttribute." + if isinstance(dist_attr, dict): + for key, value in dist_attr.items(): + if isinstance(key, Variable): + input_dist_attr = self.get_input_dist_attr(key.name) + if input_dist_attr is not None: + input_dist_attr.mark_annotated_as(value) + output_dist_attr = self.get_output_dist_attr(key.name) + if output_dist_attr is not None: + output_dist_attr.mark_annotated_as(value) + else: + if key in get_op_dist_attr_field_keys(): + self.mark_annotated(key) + process_mesh_annotated = False + if self.is_annotated("process_mesh"): + process_mesh_annotated = True + for tensor_dist_attr in self.inputs_dist_attrs.values(): + if tensor_dist_attr.is_annotated("process_mesh"): + process_mesh_annotated = True + for tensor_dist_attr in self.outputs_dist_attrs.values(): + if tensor_dist_attr.is_annotated("process_mesh"): + process_mesh_annotated = True + if process_mesh_annotated: + self.mark_annotated("process_mesh") + elif isinstance(dist_attr, OperatorDistributedAttribute): + process_mesh_annotated = False + self._is_annotated = copy.deepcopy(dist_attr._is_annotated) + if self.is_annotated("process_mesh"): + process_mesh_annotated = True + for tensor_name, tensor_dist_attr in dist_attr.inputs_dist_attrs.items( + ): + input_dist_attr = self.get_input_dist_attr(tensor_name) + if input_dist_attr is not None: + input_dist_attr.mark_annotated_as(tensor_dist_attr) + if input_dist_attr.is_annotated("process_mesh"): + process_mesh_annotated = True + for tensor_name, tensor_dist_attr in dist_attr.outputs_dist_attrs.items( + ): + output_dist_attr = self.get_output_dist_attr(tensor_name) + if output_dist_attr is not None: + output_dist_attr.mark_annotated_as(tensor_dist_attr) + if output_dist_attr.is_annotated("process_mesh"): + process_mesh_annotated = True + if process_mesh_annotated: + self.mark_annotated("process_mesh") + + def clear_annotated(self): + self._is_annotated.clear() + for tensor_dist_attr in self.inputs_dist_attrs.values(): + tensor_dist_attr.clear_annotated() + for tensor_dist_attr in self.outputs_dist_attrs.values(): + tensor_dist_attr.clear_annotated() + + def is_annotated_input_dims_mapping(self, name): + input_dist_attr = self.get_input_dist_attr(name) + if input_dist_attr: + return input_dist_attr.is_annotated("dims_mapping") + else: + return False + + def is_annotated_output_dims_mapping(self, name): + output_dist_attr = self.get_output_dist_attr(name) + if output_dist_attr: + return output_dist_attr.is_annotated("dims_mapping") + else: + return False + + def __eq__(self, other): + if not isinstance(other, OperatorDistributedAttribute): + return False + if self.process_mesh != other.process_mesh: + return False + if self.op_type != other.op_type: + return False + if self.impl_type != other.impl_type: + return False + if self.impl_idx != other.impl_idx: + return False + if self._is_annotated != other._is_annotated: + return False + if self._is_recompute != other._is_recompute: + return False + if self.inputs_dist_attrs != other.inputs_dist_attrs: + return False + if self.outputs_dist_attrs != other.outputs_dist_attrs: + return False + return True + + def __str__(self): + str = "\n\top_dist_attr = {" + if self.is_annotated("process_mesh"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += "\n\t\tprocess_mesh ({}): {},".format(annotated_str, + self.process_mesh) + + for arg_name, tensor_dist_attr in self.inputs_dist_attrs.items(): + str += "\n\t\t{}'s (input): {},".format(arg_name, tensor_dist_attr) + + for arg_name, tensor_dist_attr in self.outputs_dist_attrs.items(): + str += "\n\t\t{}'s (output): {},".format(arg_name, tensor_dist_attr) + + str += "\n\t\timpl type: {}, ".format(self._impl_type) + str += "impl idx: {}".format(self._impl_idx) + str += "\n\t}" + return str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_context.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_context.py new file mode 100644 index 0000000000000000000000000000000000000000..387c964f0aa35eb15733f4ba2474d4e6ec4caac0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_context.py @@ -0,0 +1,1041 @@ +# Copyright (c) 2021 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 + +import copy +from collections import defaultdict +import paddle.fluid +from paddle.fluid import framework +from paddle.fluid.framework import get_flags, set_flags +from paddle.fluid import core +from paddle.distributed.passes import PassContext +from .dist_attribute import TensorDistributedAttribute +from .dist_attribute import OperatorDistributedAttribute +from .dist_tensor import DistributedTensor +from .dist_op import DistributedOperator +from .process_mesh import ProcessMesh +from .utils import is_loss_grad_op, is_loss_op + +# There always exists a default context for user. And user can set it to another one. +_g_default_distributed_context = None + + +def get_default_distributed_context(): + global _g_default_distributed_context + if _g_default_distributed_context is None: + dist_context = DistributedContext() + set_default_distributed_context(dist_context) + return _g_default_distributed_context + + +def set_default_distributed_context(dist_context): + global _g_default_distributed_context + _g_default_distributed_context = dist_context + + +def _node_id(node): + return (node.node.graph_id(), node.node.id()) + + +class DistributedContext: + """ + DistributedContext is used to collect related distributed information for program and graph. + One auto-parallel run should use its own DistributedContext to avoid interfering other run. + """ + + def __init__(self, + serial_main_prog=None, + serial_startup_prog=None, + serial_optimizer=None, + serial_loss=None, + feed_vars={}, + fetch_vars={}, + cluster=None, + strategy=None): + # Data members related to original programs (unchanged) + self._original_serial_main_program = serial_main_prog + self._original_serial_startup_program = serial_startup_prog + self._original_serial_optimizer = serial_optimizer + self._original_serial_loss = serial_loss + self._original_serial_feed_vars = feed_vars + self._original_serial_fetch_vars = fetch_vars + + # Data members related to programs (changed) + self._serial_main_program = None + self._serial_startup_program = None + self._serial_loss = None + self._serial_optimizer = None + self._serial_feed_vars = {} + self._serial_fetch_vars = {} + + # Data members related to the program + self._dist_tensors_for_program = {} + self._dist_ops_for_program = {} + + # Data members related to the graph + self._serial_graph = None + self._dist_tensors_for_graph = {} + self._dist_ops_for_graph = {} + self._node_id_to_tensor_id = {} + self._node_id_to_op_id = {} + + # Data members related to the distributed programs + # Distributed programs + self._dist_main_programs = {} + self._dist_startup_programs = {} + self._dist_op_context = DistributedOperatorContext() + self._process_meshes = [] + + self._cluster = cluster + self._strategy = strategy + + # Pass Context + self._pass_context = PassContext() + self._block_state = BlockState() + + # Other data members + self._serial_ordered_tensor_nodes = [] + self._serial_ordered_op_nodes = [] + self._serial_ordered_nodes = [] + # self._tensor_id_to_tensor_node_ids = {} + + self._is_initialized = False + #TODO: need a better way to remove the following flag + self._need_copy_dist_attr_to_graph = False + self._backup_pass_context_stack = [] + self._backup_block_state_stack = [] + self._backup_dist_tensors_for_program_stack = [] + self._backup_dist_ops_for_program_stack = [] + self._backup_serial_main_program_stack = [] + self._backup_serial_startup_program_stack = [] + + # flag whether scale gradient with dp size + self._gradient_scale = True + + # A flag indicates whether the used parallelism is data parallel + self._data_parallel = False + + @property + def serial_main_program(self): + return self._serial_main_program + + @property + def serial_startup_program(self): + return self._serial_startup_program + + @property + def serial_loss(self): + return self._serial_loss + + @property + def serial_optimizer(self): + return self._serial_optimizer + + @property + def serial_feed_vars(self): + return self._serial_feed_vars + + @property + def serial_fetch_vars(self): + return self._serial_fetch_vars + + @property + def dist_main_programs(self): + return self._dist_main_programs + + @property + def dist_startup_programs(self): + return self._dist_startup_programs + + @property + def cluster(self): + return self._cluster + + @property + def strategy(self): + return self._strategy + + @property + def serial_graph(self): + return self._serial_graph + + @property + def serial_ordered_nodes(self): + return self._serial_ordered_nodes + + @property + def process_meshes(self): + return self._process_meshes + + @property + def pass_context(self): + return self._pass_context + + @property + def dist_op_context(self): + return self._dist_op_context + + @property + def block_state(self): + return self._block_state + + @property + def has_annotation(self): + return len(self._dist_tensors_for_program) or len( + self._dist_ops_for_program) + + @property + def gradient_scale(self): + return self._gradient_scale + + @gradient_scale.setter + def gradient_scale(self, gs): + self._gradient_scale = gs + + @property + def data_parallel(self): + return self._data_parallel + + @data_parallel.setter + def data_parallel(self, dp): + self._data_parallel = dp + + def _backup_serial_info(self, mode): + self._backup_serial_main_program_stack.append( + self._serial_main_program.clone()) + self._backup_serial_startup_program_stack.append( + self._serial_startup_program.clone()) + self._backup_pass_context_stack.append(copy.deepcopy( + self._pass_context)) + self._backup_block_state_stack.append(copy.deepcopy(self._block_state)) + + def _backup_dist_info(self, mode): + self._backup_dist_tensors_for_program_stack.append( + copy.deepcopy(self._dist_tensors_for_program)) + self._backup_dist_ops_for_program_stack.append( + copy.deepcopy(self._dist_ops_for_program)) + + def _backup(self, serial=True, serial_mode=None, dist=True, dist_mode=None): + # Use this function carefully + if serial: + self._backup_serial_info(serial_mode) + if dist: + self._backup_dist_info(dist_mode) + + def _restore_serial_loss(self): + if self._original_serial_loss: + if isinstance(self._original_serial_loss, list): + if len(self._original_serial_loss) == 1: + loss = self._original_serial_loss[0] + block_idx = loss.block.idx + var_name = loss.name + var = self._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + self._serial_loss = var + elif len(self._original_serial_loss) == 0: + self._serial_loss = [] + else: + raise ValueError("multi loss vars are not supported.") + else: + block_idx = self._original_serial_loss.block.idx + var_name = self._original_serial_loss.name + var = self._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + self._serial_loss = var + + def _restore_serial_feed_vars(self): + for key, var_list in self._original_serial_feed_vars.items(): + new_var_list = [] + for var in var_list: + block_idx = var.block.idx + var_name = var.name + var = self._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_var_list.append(var) + self._serial_feed_vars[key] = new_var_list + + def _restore_serial_fetch_vars(self): + for key, var_list in self._original_serial_fetch_vars.items(): + new_var_list = [] + # metrics is a list of list + if key == "metrics": + for inner_var_list in var_list: + new_inner_var_list = [] + for var in inner_var_list: + block_idx = var.block.idx + var_name = var.name + var = self._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_inner_var_list.append(var) + new_var_list.append(new_inner_var_list) + else: + for var in var_list: + block_idx = var.block.idx + var_name = var.name + var = self._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_var_list.append(var) + self._serial_fetch_vars[key] = new_var_list + + def _restore_serial_info(self, mode="to_backup"): + if mode == "to_backup": + self._serial_main_program = self._backup_serial_main_program_stack.pop( + ) + self._serial_startup_program = self._backup_serial_startup_program_stack.pop( + ) + elif mode == "to_original": + assert self._original_serial_main_program is not None + assert self._original_serial_startup_program is not None + self._serial_main_program = self._original_serial_main_program.clone( + ) + self._serial_startup_program = self._original_serial_startup_program.clone( + ) + + self._restore_serial_loss() + self._restore_serial_feed_vars() + self._restore_serial_fetch_vars() + self._serial_optimizer = self._original_serial_optimizer + self._pass_context = self._backup_pass_context_stack.pop() + self._block_state = self._backup_block_state_stack.pop() + + def _restore_dist_info(self, mode="to_backup"): + if mode == "to_backup": + self._dist_tensors_for_program = self._backup_dist_tensors_for_program_stack.pop( + ) + self._dist_ops_for_program = self._backup_dist_ops_for_program_stack.pop( + ) + elif mode == "to_original": + assert self._original_dist_tensors_for_program + assert self._original_dist_ops_for_program + self._dist_tensors_for_program = copy.deepcopy( + self._original_dist_tensors_for_program) + self._dist_ops_for_program = copy.deepcopy( + self._original_dist_ops_for_program) + elif mode == "to_default": + new_tensors_ids = [] + for tensor_id, dist_tensor in self._dist_tensors_for_program.items( + ): + if tensor_id in self._tensors_ids: + dist_tensor.dist_attr.reset() + else: + new_tensors_ids.append(tensor_id) + for tensor_id in new_tensors_ids: + self._dist_tensors_for_program.pop(tensor_id) + new_ops_ids = [] + for op_id, dist_op in self._dist_ops_for_program.items(): + if op_id in self._ops_ids: + dist_op.dist_attr.reset() + else: + new_ops_ids.append(op_id) + for op_id in new_ops_ids: + self._dist_ops_for_program.pop(op_id) + else: + new_tensors_ids = [] + for tensor_id, dist_tensor in self._dist_tensors_for_program.items( + ): + new_tensors_ids.append(tensor_id) + for tensor_id in new_tensors_ids: + self._dist_tensors_for_program.pop(tensor_id) + new_ops_ids = [] + for op_id, dist_op in self._dist_ops_for_program.items(): + new_ops_ids.append(op_id) + for op_id in new_ops_ids: + self._dist_ops_for_program.pop(op_id) + self._dist_main_programs = {} + self._dist_startup_programs = {} + self._dist_op_context = DistributedOperatorContext() + self._need_copy_dist_attr_to_graph = True + self._process_meshes = [] + + def _restore(self, + serial=True, + serial_mode="to_backup", + dist=True, + dist_mode="to_backup"): + # Use this function carefully + if serial: + self._restore_serial_info(serial_mode) + if dist: + self._restore_dist_info(dist_mode) + + def initialize(self, with_graph=True): + if not self._is_initialized: + if not self._serial_main_program: + if self._original_serial_main_program: + self._serial_main_program = self._original_serial_main_program.clone( + ) + if not self._serial_startup_program: + if self._original_serial_startup_program: + self._serial_startup_program = self._original_serial_startup_program.clone( + ) + if not self._serial_loss: + self._restore_serial_loss() + if not self._serial_optimizer: + self._serial_optimizer = self._original_serial_optimizer + if not self._serial_feed_vars: + self._restore_serial_feed_vars() + if not self._serial_fetch_vars: + self._restore_serial_fetch_vars() + + self._init_dist_attr_for_program() + # Backup the original distributed information for later restore + self._original_dist_tensors_for_program = copy.deepcopy( + self._dist_tensors_for_program) + self._original_dist_ops_for_program = copy.deepcopy( + self._dist_ops_for_program) + self._tensors_ids = list(self._dist_tensors_for_program.keys()) + self._ops_ids = list(self._dist_ops_for_program.keys()) + self._is_initialized = True + + if with_graph: + set_flags({"FLAGS_convert_all_blocks": True}) + self._serial_graph = framework.IrGraph( + core.Graph(self._serial_main_program.desc)) + self._init_dist_attr_for_graph() + self._need_copy_dist_attr_to_graph = False + + if self._need_copy_dist_attr_to_graph and with_graph: + self.copy_dist_attr_from_program_to_graph() + + def add_process_mesh(self, process_mesh): + assert isinstance(process_mesh, ProcessMesh), \ + 'The type of dim_mapping must be ProcessMesh.' + if process_mesh not in self.process_meshes: + self._process_meshes.append(process_mesh) + + def add_dist_tensor_for_program(self, dist_tensor): + inner_serial_tensor = dist_tensor.serial_tensor + inner_serial_tensor_id = inner_serial_tensor.desc.original_id() + self._dist_tensors_for_program[inner_serial_tensor_id] = dist_tensor + + def add_dist_op_for_program(self, dist_op): + inner_serial_op = dist_op.serial_op + inner_serial_op_id = inner_serial_op.desc.original_id() + self._dist_ops_for_program[inner_serial_op_id] = dist_op + + def get_dist_tensor_for_program(self, serial_tensor): + serial_tensor_id = serial_tensor.desc.id() + dist_tensor = self._dist_tensors_for_program.get(serial_tensor_id, None) + if dist_tensor: + return dist_tensor + else: + serial_tensor_id = serial_tensor.desc.original_id() + dist_tensor = self._dist_tensors_for_program.get( + serial_tensor_id, None) + if dist_tensor: + return dist_tensor + else: + return None + + def get_dist_tensor_for_graph(self, serial_tensor_node): + serial_tensor_node_id = _node_id(serial_tensor_node) + return self._dist_tensors_for_graph.get(serial_tensor_node_id, None) + + def get_dist_op_for_program(self, serial_op): + serial_op_id = serial_op.desc.id() + dist_op = self._dist_ops_for_program.get(serial_op_id, None) + if dist_op: + return dist_op + else: + serial_op_id = serial_op.desc.original_id() + dist_op = self._dist_ops_for_program.get(serial_op_id, None) + if dist_op: + return dist_op + else: + return None + + def del_dist_op_for_program(self, serial_tensor): + serial_tensor_id = serial_tensor.desc.id() + if self._dist_ops_for_program.get(serial_tensor_id, None): + del self._dist_ops_for_program[serial_tensor_id] + + def get_dist_op_for_graph(self, serial_op_node): + serial_op_node_id = _node_id(serial_op_node) + return self._dist_ops_for_graph.get(serial_op_node_id, None) + + def get_tensor_dist_attr_for_program(self, serial_tensor): + serial_tensor_id = serial_tensor.desc.id() + dist_tensor = self._dist_tensors_for_program.get(serial_tensor_id, None) + if dist_tensor: + return dist_tensor.dist_attr + else: + serial_tensor_id = serial_tensor.desc.original_id() + dist_tensor = self._dist_tensors_for_program.get( + serial_tensor_id, None) + if dist_tensor: + return dist_tensor.dist_attr + else: + return None + + def get_tensor_dist_attr_for_program_with_id(self, tensor_id): + dist_tensor = self._dist_tensors_for_program.get(tensor_id, None) + if dist_tensor: + return dist_tensor.dist_attr + else: + return None + + def set_tensor_dist_attr_for_program(self, serial_tensor, dist_attr): + dist_tensor = DistributedTensor(serial_tensor, dist_attr) + self.add_dist_tensor_for_program(dist_tensor) + + def get_tensor_dist_attr_for_graph(self, serial_tensor_node): + serial_tensor_node_id = _node_id(serial_tensor_node) + dist_tensor = self._dist_tensors_for_graph.get(serial_tensor_node_id, + None) + if dist_tensor: + return dist_tensor.dist_attr + else: + return None + + def get_op_dist_attr_for_program(self, serial_op): + serial_op_id = serial_op.desc.id() + dist_op = self._dist_ops_for_program.get(serial_op_id, None) + if dist_op: + return dist_op.dist_attr + else: + serial_op_id = serial_op.desc.original_id() + dist_op = self._dist_ops_for_program.get(serial_op_id, None) + if dist_op: + return dist_op.dist_attr + else: + return None + + def get_op_dist_attr_for_program_with_id(self, op_id): + dist_op = self._dist_ops_for_program.get(op_id, None) + if dist_op: + return dist_op.dist_attr + else: + return None + + def set_op_dist_attr_for_program(self, serial_op, dist_attr): + dist_op = DistributedOperator(serial_op, dist_attr) + self.add_dist_op_for_program(dist_op) + + def get_op_dist_attr_for_graph(self, serial_op_node): + serial_op_node_id = _node_id(serial_op_node) + dist_op = self._dist_ops_for_graph.get(serial_op_node_id, None) + if dist_op: + return dist_op.dist_attr + else: + return None + + def get_dist_attr_for_graph(self, serial_node): + if serial_node.is_var() and serial_node.var() is not None: + serial_tensor_node_id = _node_id(serial_node) + dist_tensor = self._dist_tensors_for_graph.get( + serial_tensor_node_id, None) + if dist_tensor: + return dist_tensor.dist_attr + else: + return None + if serial_node.is_op() and serial_node.op() is not None: + serial_op_node_id = _node_id(serial_node) + dist_op = self._dist_ops_for_graph.get(serial_op_node_id, None) + if dist_op: + return dist_op.dist_attr + else: + return None + return None + + def _init_dist_attr_for_program(self, no_default=False): + # Copy the dist tensors and dist ops annotated by users from the default context + if not no_default: + default_ctx = get_default_distributed_context() + self._process_meshes = copy.deepcopy(default_ctx.process_meshes) + else: + default_ctx = self + # Copy the data parallel flag from the default context + self._data_parallel = default_ctx.data_parallel + for block in self._serial_main_program.blocks: + for tensor in block.vars.values(): + # Copy the distributed tensors in the default context + default_dist_tensor = default_ctx.get_dist_tensor_for_program( + tensor) + if default_dist_tensor and default_ctx is not self: + self.add_dist_tensor_for_program(default_dist_tensor) + current_dist_tensor = self.get_dist_tensor_for_program(tensor) + if current_dist_tensor is None: + dist_tensor = DistributedTensor(tensor) + self.add_dist_tensor_for_program(dist_tensor) + for op in block.ops: + # Copy the distributed operators in the default context + default_dist_op = default_ctx.get_dist_op_for_program(op) + if default_dist_op and default_ctx is not self: + self.add_dist_op_for_program(default_dist_op) + current_dist_op = self.get_dist_op_for_program(op) + if current_dist_op is None: + dist_op = DistributedOperator(op) + self.add_dist_op_for_program(dist_op) + self._original_dist_tensors_for_program = copy.deepcopy( + self._dist_tensors_for_program) + self._original_dist_ops_for_program = copy.deepcopy( + self._dist_ops_for_program) + + def _order_nodes_by_program_order(self): + + def _contains(nodes, target_node): + for node in nodes: + if _node_id(node) == _node_id(target_node): + return True + return False + + serial_ordered_tensor_nodes = [] + serial_ordered_op_nodes = [] + all_nodes = [] + for idx, graph in enumerate(self._serial_graph.all_sub_graphs()): + for node in graph.all_nodes(): + all_nodes.append(node) + for node in all_nodes: + if node.is_var() and node.var() is not None: + serial_ordered_tensor_nodes.append(node) + if node.is_op() and node.op() is not None: + serial_ordered_op_nodes.append(node) + serial_ordered_tensor_nodes.sort( + key=lambda node: node.node.original_desc_id()) + serial_ordered_op_nodes.sort( + key=lambda node: node.node.original_desc_id()) + num_nodes_before = len(serial_ordered_tensor_nodes) + len( + serial_ordered_op_nodes) + + new_serial_ordered_tensor_nodes = [] + new_serial_ordered_op_nodes = [] + new_serial_ordered_nodes = [] + for op_node in serial_ordered_op_nodes: + tensor_nodes = [] + for tensor_node in op_node.inputs: + if tensor_node.is_var() \ + and tensor_node.var() is not None \ + and not _contains(new_serial_ordered_nodes, tensor_node): + tensor_nodes.append(tensor_node) + new_serial_ordered_tensor_nodes.append(tensor_node) + tensor_nodes.sort(key=lambda node: node.node.original_desc_id()) + new_serial_ordered_nodes.extend(tensor_nodes) + new_serial_ordered_nodes.append(op_node) + new_serial_ordered_op_nodes.append(op_node) + tensor_nodes = [] + for tensor_node in op_node.outputs: + if tensor_node.is_var() \ + and tensor_node.var() is not None \ + and not _contains(new_serial_ordered_nodes, tensor_node): + tensor_nodes.append(tensor_node) + new_serial_ordered_tensor_nodes.append(tensor_node) + tensor_nodes.sort(key=lambda node: node.node.original_desc_id()) + new_serial_ordered_nodes.extend(tensor_nodes) + new_serial_ordered_tensor_nodes.sort( + key=lambda node: node.node.original_desc_id()) + new_serial_ordered_op_nodes.sort( + key=lambda node: node.node.original_desc_id()) + self._serial_ordered_tensor_nodes = new_serial_ordered_tensor_nodes + self._serial_ordered_op_nodes = new_serial_ordered_op_nodes + self._serial_ordered_nodes = new_serial_ordered_nodes + assert len(self._serial_ordered_nodes) == len( + self._serial_ordered_tensor_nodes) + len( + self._serial_ordered_op_nodes) + self._serial_orphan_tensor_nodes = [] + for tensor_node in serial_ordered_tensor_nodes: + if not _contains(self._serial_ordered_tensor_nodes, tensor_node): + self._serial_orphan_tensor_nodes.append(tensor_node) + if len(self._serial_ordered_nodes) != num_nodes_before: + print( + "WARNING: there are some orphan tensors or ops which are not used in the execution." + ) + + def _init_dist_attr_for_graph(self): + # Convert program to graph and initialize the distributed attributes + self._order_nodes_by_program_order() + for node in self.serial_ordered_nodes: + if node.is_var() and node.var() is not None: + dist_tensor = None + tensor_id = node.node.original_desc_id() + for cur_tensor_id, cur_dist_tensor in self._dist_tensors_for_program.items( + ): + if tensor_id == cur_tensor_id \ + or tensor_id == cur_dist_tensor.serial_tensor.desc.original_id(): + dist_tensor = cur_dist_tensor + self._node_id_to_tensor_id[_node_id( + node)] = cur_tensor_id + assert dist_tensor is not None, \ + "Tensor must have a distributed tensor after the initialization for program." + serial_tensor_node_id = _node_id(node) + new_dist_tensor = DistributedTensor(dist_tensor.serial_tensor, + dist_tensor.dist_attr) + self._dist_tensors_for_graph[ + serial_tensor_node_id] = new_dist_tensor + if node.is_op() and node.op() is not None: + dist_op = None + op_id = node.node.original_desc_id() + for cur_op_id, cur_dist_op in self._dist_ops_for_program.items( + ): + if op_id == cur_op_id \ + or op_id == cur_dist_op.serial_op.desc.original_id(): + dist_op = cur_dist_op + self._node_id_to_op_id[_node_id(node)] = cur_op_id + assert dist_op is not None, \ + "Operator must have a distributed operator after the initialization for program." + serial_op_node_id = _node_id(node) + new_dist_op = DistributedOperator(dist_op.serial_op, + dist_op.dist_attr) + self._dist_ops_for_graph[serial_op_node_id] = new_dist_op + + def clear_dist_info_for_program(self): + self._dist_tensors_for_program.clear() + self._dist_ops_for_program.clear() + + def clear_dist_info_for_graph(self): + self._dist_tensors_for_graph.clear() + self._dist_ops_for_graph.clear() + + def copy_dist_attr_from_program_to_graph(self): + for node in self.serial_ordered_nodes: + if node.is_var() and node.var() is not None: + dist_tensor = None + tensor_id = node.node.original_desc_id() + for cur_tensor_id, cur_dist_tensor in self._dist_tensors_for_program.items( + ): + if tensor_id == cur_tensor_id \ + or tensor_id == cur_dist_tensor.serial_tensor.desc.original_id(): + dist_tensor = cur_dist_tensor + assert dist_tensor is not None, \ + "Tensor must have a distributed tensor after the initialization for program." + serial_tensor_node_id = _node_id(node) + new_dist_tensor = DistributedTensor(dist_tensor.serial_tensor, + dist_tensor.dist_attr) + self._dist_tensors_for_graph[ + serial_tensor_node_id] = new_dist_tensor + if node.is_op() and node.op() is not None: + dist_op = None + op_id = node.node.original_desc_id() + for cur_op_id, cur_dist_op in self._dist_ops_for_program.items( + ): + if op_id == cur_op_id \ + or op_id == cur_dist_op.serial_op.desc.original_id(): + dist_op = cur_dist_op + assert dist_op is not None, \ + "Operator must have a distributed operator after the initialization for program." + serial_op_node_id = _node_id(node) + new_dist_op = DistributedOperator(dist_op.serial_op, + dist_op.dist_attr) + self._dist_ops_for_graph[serial_op_node_id] = new_dist_op + + def copy_dist_attr_from_graph_to_program(self): + assert self._is_initialized, \ + "Both program and graph must be initialized." + updated_tensors = {} + # all_nodes = self._serial_graph.all_nodes() + all_nodes = self._serial_ordered_nodes + for node in all_nodes: + if node.is_var() and node.var() is not None: + tensor_id = self._node_id_to_tensor_id[_node_id(node)] + updated = updated_tensors.get(tensor_id, False) + # If a var has multiples var nodes in graph, only use the first one for now + if not updated: + tensor_dist_attr_for_graph = self.get_tensor_dist_attr_for_graph( + node) + dist_tensor_for_program = self._dist_tensors_for_program[ + tensor_id] + dist_tensor_for_program.dist_attr = tensor_dist_attr_for_graph + updated_tensors[tensor_id] = True + if node.is_op() and node.op() is not None: + op_id = self._node_id_to_op_id[_node_id(node)] + op_dist_attr_for_graph = self.get_op_dist_attr_for_graph(node) + dist_op_for_program = self._dist_ops_for_program[op_id] + dist_op_for_program.dist_attr = op_dist_attr_for_graph + # TODO: the completion algorithm will skipped orphan tensors, + # here we just set there process_mesh to the first one. + for orphan_node in self._serial_orphan_tensor_nodes: + serial_tensor_id = orphan_node.var().id() + dist_tensor = self._dist_tensors_for_program.get( + serial_tensor_id, None) + if dist_tensor: + dist_tensor.dist_attr.process_mesh = self._process_meshes[0] + else: + serial_tensor_id = orphan_node.var().original_id() + dist_tensor = self._dist_tensors_for_program.get( + serial_tensor_id, None) + dist_tensor.dist_attr.process_mesh = self._process_meshes[0] + + def amend_dist_attr_for_program(self): + for dist_tensor in self._dist_tensors_for_program.values(): + serial_tensor = dist_tensor.serial_tensor + dist_attr = dist_tensor.dist_attr + if serial_tensor.type == core.VarDesc.VarType.READER \ + or serial_tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or serial_tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = serial_tensor.shape + dims_mapping = dist_attr.dims_mapping + process_mesh_shape = dist_attr.process_mesh.topology + process_mesh_processes = dist_attr.process_mesh.processes + # If the dimension of tensor is less than the sharding dimension of process mesh, + # we just amend the dimension mapping to -1. (Is this really OK?) + for i in range(len(tensor_shape)): + if dims_mapping[i] != -1 and tensor_shape[i] > 0 \ + and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]: + dims_mapping[i] = -1 + if dims_mapping[i] != -1 and len(process_mesh_processes) == 1: + dims_mapping[i] = -1 + + for dist_op in self._dist_ops_for_program.values(): + serial_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + process_mesh_shape = dist_attr.process_mesh.topology + process_mesh_processes = dist_attr.process_mesh.processes + for arg_name in serial_op.input_arg_names: + if dist_op.get_serial_input(arg_name) is None: + tensor_shape = [] + else: + if dist_op.get_serial_input(arg_name).type == core.VarDesc.VarType.READER \ + or dist_op.get_serial_input(arg_name).type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or dist_op.serial_op.type == "create_py_reader": + tensor_shape = [] + else: + tensor_shape = dist_op.get_serial_input(arg_name).shape + dims_mapping = dist_attr.get_input_dims_mapping(arg_name) + # If the dimension of tensor is less than the sharding dimension of process mesh, + # we just amend the dimension mapping to -1. (Is this really OK?) + for i in range(len(tensor_shape)): + if dims_mapping[i] != -1 and tensor_shape[i] > 0 \ + and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]: + dims_mapping[i] = -1 + if dims_mapping[i] != -1 and len( + process_mesh_processes) == 1: + dims_mapping[i] = -1 + for arg_name in serial_op.output_arg_names: + if dist_op.get_serial_output(arg_name).type == core.VarDesc.VarType.READER \ + or dist_op.get_serial_output(arg_name).type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or dist_op.get_serial_output(arg_name).type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = dist_op.get_serial_output(arg_name).shape + dims_mapping = dist_attr.get_output_dims_mapping(arg_name) + # If the dimension of tensor is less than the sharding dimension of process mesh, + # we just amend the dimension mapping to -1. (Is this really OK?) + for i in range(len(tensor_shape)): + if dims_mapping[i] != -1 and tensor_shape[i] > 0 \ + and process_mesh_shape[dims_mapping[i]] > tensor_shape[i]: + dims_mapping[i] = -1 + if dims_mapping[i] != -1 and len( + process_mesh_processes) == 1: + dims_mapping[i] = -1 + if len(process_mesh_processes) == 1: + dist_op.dist_attr.impl_type = "default" + dist_op.dist_attr.impl_idx = 0 + + def validate_dist_attr_for_program(self): + if not self._is_initialized: + assert False, \ + "Program must be initialized before validating its distributed attributes" + for block in self.serial_main_program.blocks: + for tensor in block.vars.values(): + dist_tensor = self.get_dist_tensor_for_program(tensor) + assert dist_tensor is not None, \ + "Tensor {} does not have a distributed attribute.".format( + dist_tensor.serial_tensor.name) + if (dist_tensor + is not None) and (not dist_tensor.validate_dist_attr()): + assert False, "Tensor {} (id: {}, original_id: {}) has a wrong distributed attributes {}.".format( + dist_tensor.serial_tensor.name, + dist_tensor.serial_tensor.desc.id(), + dist_tensor.serial_tensor.desc.original_id(), + dist_tensor.dist_attr) + for op in block.ops: + dist_op = self.get_dist_op_for_program(op) + assert dist_op is not None, \ + "Operator {} does not have a distributed attribute.".format( + dist_op.serial_op.type) + if (dist_op is not None) and (not dist_op.validate_dist_attr()): + assert False, "Operator {} (id: {}, original_id: {}) has a wrong distributed attributes {} .".format( + dist_op.serial_op.type, dist_op.serial_op.desc.id(), + dist_op.serial_op.desc.original_id(), dist_op.dist_attr) + return True + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k in [ + "_original_serial_main_program", "_original_serial_startup_program", \ + "_serial_main_program", "_serial_startup_program", "_serial_graph", \ + "_dist_main_programs", "_dist_startup_programs", \ + "_serial_ordered_nodes", "_serial_ordered_tensor_nodes", \ + "_serial_ordered_op_nodes", "_original_serial_loss", \ + "_original_serial_feed_vars", "_original_serial_fetch_vars", \ + "_serial_loss", "_serial_feed_vars", "_serial_fetch_vars", "_serial_optimizer", \ + "_backup_serial_main_program_stack", "_backup_serial_startup_program_stack", \ + "_pass_context"]: + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + + # update dist tensor's dist_context + for key in result._dist_tensors_for_program.keys(): + result._dist_tensors_for_program[key]._dist_context = result + return result + + +class DistributedOperatorContext: + """ + DistributedOperatorContext is used to create a dist op desc in Program. + Every time to create a new dist op, the context should be updated for it accordingly. + """ + + def __init__(self): + self._dst_main_program = None + self._main_block = None + self._dst_startup_program = None + self._startup_block = None + self._cur_src_op = None + self._cur_dist_attr = None + self.grad_op_id_to_op_id = {} + self.grad_var_to_var = defaultdict(dict) + self._work_block = None + self.already_init_sync_vars = set() + self.varname_mapping = None + self.rank_id = None + # NOTE Support correct parallelism for high-order differential model. + # by default exceed_backward_init_op is False and it means we are in Forward phase; After exceed_backward_init_op = True, + # it means we are in Backward phase. + # And the final sulotion should be revise high-order differential logic for these two phases in future. + self._exceed_backward_init_op = False + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k in [ + "_dst_main_program", "_dst_startup_program", "_cur_src_op", + "_work_block", "_main_block", "_startup_block" + ]: + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + return result + + @property + def dst_main_program(self): + return self._dst_main_program + + @dst_main_program.setter + def dst_main_program(self, prog): + self._dst_main_program = prog + self._main_block = prog.blocks[0] + + @property + def main_block(self): + return self._main_block + + @property + def dst_startup_program(self): + return self._dst_startup_program + + @dst_startup_program.setter + def dst_startup_program(self, prog): + self._dst_startup_program = prog + self._startup_block = prog.blocks[0] + + @property + def startup_block(self): + return self._startup_block + + @property + def work_block(self): + assert self._work_block is not None + return self._work_block + + @work_block.setter + def work_block(self, block): + assert block is not None + self._work_block = block + + @property + def cur_src_op(self): + assert self._cur_src_op is not None + return self._cur_src_op + + def in_backward_phase(self): + return self._exceed_backward_init_op + + def prepare_context(self, src_op): + + self._cur_src_op = src_op + + if is_loss_grad_op(src_op): + self._exceed_backward_init_op = True + + # build input varname mapping + kinputs = {} + for input_name in src_op.desc.input_names(): + varnames = [] + for varname in src_op.desc.input(input_name): + assert varname in self.varname_mapping + varnames.append(self.varname_mapping[varname]) + kinputs[input_name] = varnames + + # build output varname mapping + koutputs = {} + for output_name in src_op.desc.output_names(): + varnames = [] + for varname in src_op.desc.output(output_name): + assert varname in self.varname_mapping + varnames.append(self.varname_mapping[varname]) + koutputs[output_name] = varnames + + return kinputs, koutputs + + +class BlockState(object): + + def __init__(self): + self.nblock = 0 + self.forward_indices = [] + self.backward_indices = [] + self.backward_to_forward_index_map = {} + + def parse_forward_blocks(self, program): + + while program.current_block_idx != 0: + program._rollback() + + assert program.current_block_idx == 0 + + for idx, block in enumerate(program.blocks): + + assert idx == block.idx, "index doesn't match" + assert block.forward_block_idx == -1, "forward_block_idx of forward block [{}] is not [{}]".format( + idx, block.forward_block_idx) + self.forward_indices.append(idx) + self.nblock += 1 + + assert self.nblock >= 1 + + def parse_backward_blocks(self, program): + + assert 0 in self.forward_indices, "forward block idx are{}".format( + self.forward_indices) + self.backward_to_forward_index_map[0] = 0 + + for idx, block in enumerate(program.blocks): + + if idx < len(self.forward_indices): + continue + + assert idx == block.idx, "index doesn't match" + assert block.forward_block_idx in self.forward_indices + self.backward_indices.append(idx) + self.backward_to_forward_index_map[idx] = block.forward_block_idx + self.nblock += 1 + + assert self.nblock == len(program.blocks) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_loader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..38b537799e546f2e6bf9fdfc76043e2d5ea4df9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_loader.py @@ -0,0 +1,269 @@ +# Copyright (c) 2022 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 + +import abc +import numpy as np + +import paddle +from paddle.io import BatchSampler, IterableDataset +from paddle.fluid.dataloader.batch_sampler import _InfiniteIterableSampler, DistributedBatchSampler +from paddle.fluid.dataloader.dataloader_iter import _DatasetKind, default_collate_fn, default_convert_fn + + +class DistributedDataLoaderBase(metaclass=abc.ABCMeta): + + @abc.abstractmethod + def __iter__(self): + raise NotImplementedError + + @abc.abstractmethod + def __next__(self): + raise NotImplementedError + + @property + def index_sampler(self): + if self.auto_collate_batch: + return self.batch_sampler + else: + if self.dataset_kind == _DatasetKind.MAP: + return list(range(len(self.dataset))) + else: + return _InfiniteIterableSampler(self.dataset, 1) + + +class DistributedDataLoaderFromGenerator(DistributedDataLoaderBase): + + def __init__(self, + dataset, + feed_list=None, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=False, + use_multiprocess=False, + drop_last=True, + places=None, + batch_size=1, + epochs=1, + steps_per_epoch=None, + collate_fn=None, + split_data=True, + data_parallel_world_size=[], + data_parallel_rank=[]): + self.dataset = dataset + self.feed_list = feed_list + self.capacity = capacity + self.use_double_buffer = use_double_buffer + self.iterable = iterable + self.return_list = return_list + self.use_multiprocess = use_multiprocess + self.drop_last = drop_last + self.places = places + self.batch_size = batch_size + self.epochs = epochs + self.steps_per_epoch = steps_per_epoch + self.collate_fn = collate_fn + self.split_data = split_data + assert len(data_parallel_world_size) == len(feed_list) + assert len(data_parallel_rank) == len(feed_list) + self.dp_world_sizes = data_parallel_world_size + self.dp_ranks = data_parallel_rank + + if isinstance(dataset, IterableDataset): + self.dataset_kind = _DatasetKind.ITER + else: + self.dataset_kind = _DatasetKind.MAP + + if self.batch_size is None: + self.batch_sampler = None + else: + if isinstance(dataset, IterableDataset): + self.batch_sampler = _InfiniteIterableSampler( + dataset, batch_size) + else: + self.batch_sampler = BatchSampler(dataset, + batch_size=batch_size, + shuffle=False, + drop_last=drop_last) + + self.auto_collate_batch = self.batch_sampler is not None + self.sampler_iter = iter(self.index_sampler) + + if self.auto_collate_batch: + self.collate_fn = collate_fn or default_collate_fn + else: + self.collate_fn = collate_fn or default_convert_fn + + self.dataset_fetcher = _DatasetKind.create_fetcher( + self.dataset_kind, self.dataset, self.auto_collate_batch, + self.collate_fn, self.drop_last) + + self._steps = self._infer_steps() + self._inner_dataloader = self._create_inner_dataloader() + + def __iter__(self): + self._cur_step = 0 + self._inner_dataloader.start() + return self + + def __next__(self): + if not self._steps: + self._cur_step += 1 + return None + elif self._cur_step < self._steps: + self._cur_step += 1 + return None + else: + self._inner_dataloader.reset() + self.sampler_iter = iter(self.index_sampler) + raise StopIteration + + def _infer_steps(self): + if self.steps_per_epoch is not None: + return self.steps_per_epoch + try: + if isinstance(self.dataset, IterableDataset): + steps_per_epoch = None + elif self.batch_size is None: + steps_per_epoch = len(self.dataset) + else: + steps_per_epoch = len(self.dataset) // self.batch_size + except: + raise ValueError( + "Pleace set `steps_per_epoch` or implement `__len__` methond in dataset class." + ) + return steps_per_epoch + + @property + def index_sampler(self): + if self.auto_collate_batch: + return self.batch_sampler + else: + if self.dataset_kind == _DatasetKind.MAP: + return list(range(len(self.dataset))) + else: + return _InfiniteIterableSampler(self.dataset, 1) + + def _create_inner_dataloader(self): + + def data_generator(): + while True: + try: + indices = next(self.sampler_iter) + batch = self.dataset_fetcher.fetch(indices) + if batch is None: break + except StopIteration: + self.dataset_fetcher = _DatasetKind.create_fetcher( + self.dataset_kind, self.dataset, + self.auto_collate_batch, self.collate_fn, + self.drop_last) + break + + partial_data = [] + for i, d in enumerate(batch): + array = np.array(d) + if not self.split_data: + partial_data.append(array) + continue + + batch_size = array.shape[0] + assert batch_size % self.dp_world_sizes[i] == 0, \ + "batch_size [{}] is not divisible by dp_world_size [{}]".format(str(batch_size), str(self.dp_world_sizes[i])) + partial_data.append( + np.split(array, + self.dp_world_sizes[i])[self.dp_ranks[i]]) + + yield partial_data + + dataloader = paddle.fluid.io.DataLoader.from_generator( + feed_list=self.feed_list, + capacity=self.capacity, + use_double_buffer=self.use_double_buffer, + # iterable=self.iterable, + iterable=False, + return_list=self.return_list, + use_multiprocess=self.use_multiprocess, + drop_last=self.drop_last) + dataloader.set_batch_generator(data_generator, self.places) + + return dataloader + + +class DistributedDataLoader(DistributedDataLoaderBase): + + def __init__(self, + dataset, + feed_list=None, + places=None, + return_list=True, + batch_size=1, + shuffle=False, + drop_last=False, + collate_fn=None, + num_workers=0, + use_buffer_reader=True, + use_shared_memory=True, + timeout=0, + worker_init_fn=None, + epochs=1, + steps_per_epoch=None, + split_data=True, + data_parallel_world_size=[], + data_parallel_rank=[]): + self.dataset = dataset + self.feed_list = feed_list + self.return_list = return_list + self.places = places + self.batch_size = batch_size + self.shuffle = shuffle + self.drop_last = drop_last + self.collate_fn = collate_fn + self.num_workers = num_workers + self.use_buffer_reader = use_buffer_reader + self.use_shared_memory = use_shared_memory + self.timeout = timeout + self.worker_init_fn = worker_init_fn + self.epochs = epochs + self.steps_per_epoch = steps_per_epoch + self.dp_world_sizes = data_parallel_world_size + self.dp_ranks = data_parallel_rank + self.split_data = split_data + # TODO: rank info + self.batch_sampler = DistributedBatchSampler( + self.dataset, self.batch_size, self.dp_world_sizes[0], + self.dp_ranks[0], self.shuffle, self.drop_last) + self._inner_dataloader = self._create_inner_dataloader() + + def __iter__(self): + return self + + def __next__(self): + return next(self.data) + + def _create_inner_dataloader(self): + dataloader = paddle.fluid.io.DataLoader( + self.dataset, + feed_list=self.feed_list, + places=self.places, + return_list=self.return_list, + batch_sampler=self.batch_sampler, + collate_fn=self.collate_fn, + num_workers=self.num_workers, + use_buffer_reader=self.use_buffer_reader, + use_shared_memory=self.use_shared_memory, + timeout=self.timeout, + worker_init_fn=self.worker_init_fn) + self.data = (x for x in dataloader) + + return dataloader diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_op.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_op.py new file mode 100644 index 0000000000000000000000000000000000000000..300c80ec71878b4ab8e00cf822e739801f54f243 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_op.py @@ -0,0 +1,354 @@ +# Copyright (c) 2021 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 + +import copy +from collections import defaultdict +import paddle +from paddle.fluid import core +from paddle.fluid.framework import Variable +from .dist_attribute import TensorDistributedAttribute +from .dist_attribute import OperatorDistributedAttribute +from .dist_attribute import append_op_input_suffix +from .dist_attribute import append_op_output_suffix +from .dist_attribute import get_tensor_dist_attr_field_keys +from .dist_attribute import get_op_dist_attr_field_keys +from .utils import convert_to_shard_spec, verify_shard_spec + + +class DistributedOperator: + + def __init__(self, serial_op, dist_attr=None): + self._serial_op = serial_op + self._serial_inputs = {} + self._serial_outputs = {} + self._dist_attr = None + # Reuse the dist_attr setter to initialize _dist_attr + self.dist_attr = dist_attr + + @property + def serial_op(self): + return self._serial_op + + @property + def dist_attr(self): + return self._dist_attr + + @dist_attr.setter + def dist_attr(self, dist_attr): + if self._dist_attr is None: + self._dist_attr = OperatorDistributedAttribute() + # Create new dist_attr related to current serial_op + dist_attr = self._filter_dist_attr(dist_attr) + # Append suffix to mark the inputs or outputs + if isinstance(dist_attr, dict): + # Copy the keys since we may add new ones + for key in list(dist_attr.keys()): + if isinstance(key, Variable): + if key.name in self._serial_op.input_arg_names: + dist_attr[append_op_input_suffix(key.name)] = True + if key.name in self._serial_op.output_arg_names: + dist_attr[append_op_output_suffix(key.name)] = True + self._dist_attr.init(dist_attr) + self._init_default_dist_attr() + + def get_serial_input(self, name): + return self._serial_inputs.get(name, None) + + def get_serial_output(self, name): + return self._serial_outputs.get(name, None) + + def _init_default_dist_attr(self): + for tensor_name in self._serial_op.input_arg_names: + if self._serial_op.type == "create_py_reader": + tensor = None + else: + tensor = self._serial_op.block._var_recursive(tensor_name) + self._serial_inputs[tensor_name] = tensor + if tensor is None: + tensor_shape = [] + else: + if tensor.type == core.VarDesc.VarType.READER \ + or tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + tensor_shape = [] + else: + tensor_shape = tensor.shape + if self._dist_attr.get_input_dims_mapping(tensor_name) is None: + tensor_dims_mapping = [-1 for _ in range(len(tensor_shape))] + self._dist_attr.set_input_dims_mapping(tensor_name, + tensor_dims_mapping) + for tensor_name in self._serial_op.output_arg_names: + tensor = self._serial_op.block._var_recursive(tensor_name) + if tensor.type == core.VarDesc.VarType.READER \ + or tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = tensor.shape + self._serial_outputs[tensor_name] = tensor + if self._dist_attr.get_output_dims_mapping(tensor_name) is None: + tensor_dims_mapping = [-1 for _ in range(len(tensor_shape))] + self._dist_attr.set_output_dims_mapping(tensor_name, + tensor_dims_mapping) + if self._dist_attr.op_type is None: + self._dist_attr.op_type = self.serial_op.type + if self._dist_attr.impl_type is None: + self._dist_attr.impl_type = "default" + if self._dist_attr.impl_idx is None: + self._dist_attr.impl_idx = 0 + if self._dist_attr.is_recompute is None: + self._dist_attr.is_recompute = False + + def _filter_dist_attr(self, dist_attr): + if dist_attr is None: + return None + new_dist_attr = None + if isinstance(dist_attr, dict): + new_dist_attr = {} + for key, value in dist_attr.items(): + if isinstance(key, Variable): + if key.name in self._serial_op.input_arg_names \ + or key.name in self._serial_op.output_arg_names: + new_dist_attr[key] = value + else: + new_dist_attr[key] = value + elif isinstance(dist_attr, OperatorDistributedAttribute): + new_dist_attr = copy.deepcopy(dist_attr) + new_dist_attr._inputs_dist_attrs.clear() + new_dist_attr._outputs_dist_attrs.clear() + for tensor_name in self._serial_op.input_arg_names: + tensor_dist_attr = dist_attr.get_input_dist_attr(tensor_name) + if tensor_dist_attr: + new_dist_attr.set_input_dist_attr(tensor_name, + tensor_dist_attr) + for tensor_name in self._serial_op.output_arg_names: + tensor_dist_attr = dist_attr.get_output_dist_attr(tensor_name) + if tensor_dist_attr: + new_dist_attr.set_output_dist_attr(tensor_name, + tensor_dist_attr) + else: + assert False, "Cannot recognize the {} parameter.".format(dist_attr) + return new_dist_attr + + def validate_dist_attr(self): + if "read" in self.serial_op.type or "while" == self.serial_op.type: + return True + for name in self.serial_op.input_arg_names: + input_dist_attr = self.dist_attr.get_input_dist_attr(name) + dims_mapping = input_dist_attr.dims_mapping + if self.get_serial_input( + name).type == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + shape = [] + else: + shape = self.get_serial_input(name).shape + if len(shape) != len(dims_mapping): + return False + for i in range(len(dims_mapping)): + if dims_mapping[i] < -1 or dims_mapping[i] >= len( + self.dist_attr.process_mesh.topology): + return False + for i in range(len(self.dist_attr.process_mesh.topology)): + if dims_mapping.count(i) > 1: + return False + if self.dist_attr.process_mesh != input_dist_attr.process_mesh: + return False + + for name in self.serial_op.output_arg_names: + output_dist_attr = self.dist_attr.get_output_dist_attr(name) + dims_mapping = output_dist_attr.dims_mapping + if self.get_serial_output(name).type == core.VarDesc.VarType.LOD_TENSOR_ARRAY\ + or self.get_serial_output(name).type == core.VarDesc.VarType.STEP_SCOPES: + shape = [] + else: + shape = self.get_serial_output(name).shape + if len(shape) != len(dims_mapping): + return False + for i in range(len(dims_mapping)): + if dims_mapping[i] < -1 or dims_mapping[i] >= len( + self.dist_attr.process_mesh.topology): + return False + for i in range(len(self.dist_attr.process_mesh.topology)): + if dims_mapping.count(i) > 1: + return False + if self.dist_attr.process_mesh != output_dist_attr.process_mesh: + return False + return True + + def __str__(self): + str = "{{op type: {}, op id: {}".format(self.serial_op.desc.type(), + self.serial_op.desc.id()) + + # str += ", {}".format(self.dist_attr) + # return str + + if self.dist_attr.is_annotated("process_mesh"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += ", process_mesh ({}): {}".format(annotated_str, + self.dist_attr.process_mesh) + + for arg_name in self.serial_op.desc.input_arg_names(): + dims_mapping = self.dist_attr.get_input_dims_mapping(arg_name) + if self.dist_attr.is_annotated_input_dims_mapping(arg_name): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + if self.get_serial_input(arg_name) is not None: + if self.get_serial_input(arg_name).is_parameter: + is_parameter_str = "parameter" + else: + is_parameter_str = "non-parameter" + else: + is_parameter_str = "non-parameter" + str += ", {}'s dims_mapping (input, {}, {}): {}".format( + arg_name, annotated_str, is_parameter_str, dims_mapping) + + for arg_name in self.serial_op.desc.output_arg_names(): + dims_mapping = self.dist_attr.get_output_dims_mapping(arg_name) + if self.dist_attr.is_annotated_output_dims_mapping(arg_name): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + if self.get_serial_output(arg_name) is not None: + if self.get_serial_output(arg_name).is_parameter: + is_parameter_str = "parameter" + else: + is_parameter_str = "non-parameter" + else: + is_parameter_str = "non-parameter" + str += ", {}'s dims_mapping (output, {}, {}): {}".format( + arg_name, annotated_str, is_parameter_str, dims_mapping) + + str += ", pipeline stage: {}".format(None) + + str += ", dist_impl idx: {} , dist_impl type {} }}".format( + self.dist_attr._impl_idx, self.dist_attr._impl_type) + + return str + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k == "_serial_op" or k == "_serial_inputs" or k == "_serial_outputs": + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + return result + + +class DistributedOperatorHelper: + + def __init__(self, serial_op, process_mesh, in_dims_mappings, + out_dims_mappings): + self._serial_op = serial_op + self._process_mesh = process_mesh + self._in_dims_mappings = in_dims_mappings + self._out_dims_mappings = out_dims_mappings + + def __call__(self, *args, **kwargs): + tensor_to_dims_mapping = {} + index = 0 + if self._in_dims_mappings: + assert len(args) + len(kwargs) == len(self._in_dims_mappings), \ + "The length of dims_mapping {} does not matching the length output {}.".format(len(self._in_dims_mappings), len(args) + len(kwargs)) + for arg in args: + if isinstance(arg, Variable) and self._in_dims_mappings: + tensor_to_dims_mapping[arg.name] = self._in_dims_mappings[index] + index += 1 + for arg in kwargs.values() and self._in_dims_mappings: + if isinstance(arg, Variable): + tensor_to_dims_mapping[arg.name] = self._in_dims_mappings[index] + index += 1 + + default_prog = paddle.fluid.default_main_program() + cur_block = default_prog.current_block() + op_size = len(cur_block.ops) + output = self._serial_op(*args, **kwargs) + new_op_size = len(cur_block.ops) + + if isinstance(output, tuple) or isinstance(output, list): + new_output = list(output) + elif isinstance(output, Variable): + new_output = [output] + else: + raise ValueError("Unrecognized outpout.") + + if self._out_dims_mappings: + assert len(new_output) == len(self._out_dims_mappings), \ + "The length of dims_mapping {} does not matching the length output {}.".format(len(self._out_dims_mappings), len(new_output)) + for i, item in enumerate(new_output): + if isinstance(item, Variable) and self._out_dims_mappings: + tensor_to_dims_mapping[item.name] = self._out_dims_mappings[i] + + from .dist_context import get_default_distributed_context + default_dist_ctx = get_default_distributed_context() + for idx in range(op_size, new_op_size): + op = cur_block.ops[idx] + dist_op = DistributedOperator(op) + for name in dist_op.serial_op.input_arg_names: + if name in tensor_to_dims_mapping.keys(): + tensor = dist_op.get_serial_input(name) + tensor_dist_attr = dist_op.dist_attr.get_input_dist_attr( + name) + dims_mapping = tensor_to_dims_mapping[name] + if tensor is None: + tensor_shape = [] + else: + if tensor.type == core.VarDesc.VarType.READER \ + or tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = tensor.shape + if dims_mapping is not None: + dims_mapping = tensor_to_dims_mapping[name] + shard_spec = convert_to_shard_spec( + dims_mapping, self._process_mesh) + assert verify_shard_spec(shard_spec, tensor_shape, self._process_mesh), \ + "For tensor {}, shard_spec {} is invalid with tensor_shape {} and process_mesh {}.".format( + name, shard_spec, tensor_shape, self._process_mesh) + tensor_dist_attr.dims_mapping = dims_mapping + tensor_dist_attr.mark_annotated("dims_mapping") + for name in dist_op.serial_op.output_arg_names: + if name in tensor_to_dims_mapping.keys(): + tensor = dist_op.get_serial_output(name) + tensor_dist_attr = dist_op.dist_attr.get_output_dist_attr( + name) + dims_mapping = tensor_to_dims_mapping[name] + if tensor is None: + tensor_shape = [] + else: + if tensor.type == core.VarDesc.VarType.READER \ + or tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = tensor.shape + if dims_mapping is not None: + dims_mapping = tensor_to_dims_mapping[name] + shard_spec = convert_to_shard_spec( + dims_mapping, self._process_mesh) + assert verify_shard_spec(shard_spec, tensor_shape, self._process_mesh), \ + "For tensor {}, shard_spec {} is invalid with tensor_shape {} and process_mesh {}.".format( + name, shard_spec, tensor_shape, self._process_mesh) + tensor_dist_attr.dims_mapping = dims_mapping + tensor_dist_attr.mark_annotated("dims_mapping") + dist_op.dist_attr.process_mesh = self._process_mesh + if self._process_mesh is not None: + dist_op.dist_attr.mark_annotated("process_mesh") + default_dist_ctx.add_dist_op_for_program(dist_op) + + return output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_saver.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..350e5ac44e724d3051b74eaa3c784e19361ad669 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_saver.py @@ -0,0 +1,243 @@ +# Copyright (c) 2022 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 + +import re +import os +import errno +import pickle +import warnings +import logging +import numpy as np +import paddle + +from paddle import fluid +from paddle.fluid import core +from paddle.fluid.framework import static_only +from .utils import get_dist_attr +from .converter import Converter +from .process_group import _g_process_group_map +from ..utils.log_utils import get_logger + + +def check_filename(re_exp, filename): + if re.search(re_exp, filename): + return True + else: + return False + + +def _process_path(path): + filename = os.path.basename(path) + if filename == "": + raise ValueError( + "path should be of 'dirname/filename' format, but received filename is empty string" + ) + try: + dirname = os.path.dirname(path) + os.makedirs(dirname) + except OSError as e: + if e.errno != errno.EEXIST: + raise + return dirname, filename + + +class DistributedSaver: + + def __init__(self): + self._logger = get_logger(logging.INFO) + + def save(self, path, serial_program, dist_main_program, dist_context): + + def _save_state(program, path, mode="param"): + state = { + k: np.array(v) + for k, v in program.state_dict(mode).items() + } + with open(path, "wb") as f: + pickle.dump(state, f) + + dirname, filename = _process_path(path) + + rank_id = paddle.distributed.get_rank() + # save serial program when rank id is 0 + if rank_id == 0: + self._save_rank_mapping(dirname) + serial_model_filename = filename + "_serial.pdmodel" + serial_model_path = os.path.join(dirname, serial_model_filename) + with open(serial_model_path, "wb") as f: + f.write(serial_program.desc.serialize_to_string()) + + # save distributed main program + dist_model_filename = filename + "_dist" + str(rank_id) + ".pdmodel" + dist_model_path = os.path.join(dirname, dist_model_filename) + with open(dist_model_path, "wb") as f: + f.write(dist_main_program.desc.serialize_to_string()) + + # save distributed attribute + dist_attr_filename = filename + "_dist" + str(rank_id) + ".pdattr" + dist_attr_path = os.path.join(dirname, dist_attr_filename) + dist_attrs = get_dist_attr(dist_main_program, dist_context) + with open(dist_attr_path, "wb") as f: + pickle.dump(dist_attrs, f) + + # save distributed params + dist_param_filename = filename + "_dist" + str(rank_id) + ".pdparams" + dist_param_path = os.path.join(dirname, dist_param_filename) + _save_state(dist_main_program, dist_param_path) + + # save distributed opt states + dist_opt_filename = filename + "_dist" + str(rank_id) + ".pdopt" + dist_opt_path = os.path.join(dirname, dist_opt_filename) + _save_state(dist_main_program, dist_opt_path, "opt") + + # TODO:save cluster.json + + def load(self, path, load_optimizer=True): + # TODO: if `program` is None, load `path.pdmodel`. + def _load_file(filename, dirname, suffix="pdparams"): + file_list = [] + for file in os.listdir(dirname): + if check_filename('{}(.*)_dist(.*).{}'.format(filename, suffix), + file): + file_list.append(os.path.join(dirname, file)) + file_list.sort() + return file_list + + def _load_state(filename, dirname, suffix="pdparams"): + file_list = _load_file(filename, dirname, suffix) + state_dict = {} + for file in file_list: + with open(file, 'rb') as f: + state_dict_info = pickle.load(f, encoding='latin1') + for name, value in state_dict_info.items(): + if name in state_dict: + state_dict[name].append(np.array(value)) + else: + state_dict[name] = [np.array(value)] + self._logger.info("Load param file: {}".format(file_list)) + return state_dict + + filename = os.path.basename(path) + if filename == "": + raise ValueError( + "path should be of 'dirname/filename' format, but received filename is empty string" + ) + dirname = os.path.dirname(path) + + # load path.pdparam and path.pdopt + param_state_dict = _load_state(filename, dirname) + opt_state_dict = _load_state(filename, dirname, + "pdopt") if load_optimizer else {} + state_dict = dict(param_state_dict, **opt_state_dict) + + # load path.pdattr + dist_attr_file_list = _load_file(filename, dirname, "pdattr") + self._logger.info( + "Load distributed attribute file: {}".format(dist_attr_file_list)) + dist_attr = {} + for dist_attr_file in dist_attr_file_list: + with open(dist_attr_file, 'rb') as f: + dist_attr_info = pickle.load(f, encoding='latin1') + for name, attr in dist_attr_info.items(): + if name not in dist_attr: + dist_attr[name] = attr + + return state_dict, dist_attr + + def save_inference_model(self, path, feed_vars, fetch_vars, exe, **kwargs): + + dirname, filename = _process_path(path) + + # save distributed inference program + rank_id = paddle.distributed.get_rank() + if rank_id == 0: + self._save_rank_mapping(dirname) + op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName() + op_role_forward = int(core.op_proto_and_checker_maker.OpRole.Forward) + + dist_main_prog = kwargs.get('program', None) + if not dist_main_prog: + dist_main_prog = fluid.default_main_program() + global_block = dist_main_prog.global_block() + + ops = global_block.ops + feed_vars_names = list(map(lambda x: x.name, feed_vars)) + fetch_vars_names = list(map(lambda x: x.name, fetch_vars)) + + last_idx = -1 + for idx, op in enumerate(ops): + if op.attr(op_role_key) != op_role_forward: + continue + if op.type == "read" or op.type == "feed" or op.type == 'recv_v2': + feed_vars_names += op.output("Out") + if op.type == "send_v2": + fetch_vars_names += op.input("X") + last_idx = max(idx, last_idx) + for out_name in op.output_arg_names: + if out_name in fetch_vars_names: + last_idx = max(idx, last_idx) + + used_inputs = [] + used_outputs = [] + for idx, op in enumerate(ops): + if idx > last_idx: + break + used_inputs += op.input_arg_names + used_outputs += op.output_arg_names + + dist_feed_vars_names = list(set(feed_vars_names) & set(used_inputs)) + dist_fetch_vars_names = list(set(fetch_vars_names) & set(used_outputs)) + + dist_feed_vars = [ + global_block.vars[name] for name in dist_feed_vars_names + ] + dist_fetch_vars = [ + global_block.vars[name] for name in dist_fetch_vars_names + ] + + # NOTE: `paddle.static.save_inference_model` does not support subblock. + dist_filename = filename + "_dist" + str(rank_id) + dist_path = os.path.join(dirname, dist_filename) + paddle.static.save_inference_model(dist_path, + dist_feed_vars, + dist_fetch_vars, + exe, + program=dist_main_prog) + + def _save_rank_mapping(self, dirname): + path = os.path.join(dirname, 'rank_mapping.csv') + f = open(path, 'w') + f.write('[ring_id -> ranks]\n') + for process_group in _g_process_group_map.values(): + ring_id = process_group._group_id + ranks = [str(rank) for rank in process_group._ranks] + id_to_rank = str(ring_id) + "," + ",".join(ranks) + '\n' + f.write(id_to_rank) + id_to_rank = "" + f.write('[rank -> ring_ids]\n') + rank_to_id_dict = {} + for process_group in _g_process_group_map.values(): + ring_id = process_group._group_id + for rank in process_group._ranks: + if rank in rank_to_id_dict: + rank_to_id_dict[rank].append(str(ring_id)) + else: + rank_to_id_dict[rank] = [str(ring_id)] + rank_to_id = "" + for item, val in rank_to_id_dict.items(): + rank_to_id += str(item) + "," + rank_to_id += ",".join(val) + "\n" + f.write(rank_to_id) + rank_to_id = "" + f.close() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_tensor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..59a2d7a582331cd4af5e6efe8ee08fab3cfd507f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/dist_tensor.py @@ -0,0 +1,403 @@ +# Copyright (c) 2021 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 + +import copy +import inspect + +import paddle +from paddle.fluid import core +from paddle.fluid.framework import Parameter, Block, Variable +from .dist_attribute import TensorDistributedAttribute +from .dist_attribute import get_tensor_dist_attr_field_keys +from .utils import _linear_idx2coordinate + + +class DistributedTensor: + """ + DistributedTensor represents the distribution of tensor on the process group and + local tensors can be created by DistributedTensor. + Only support even sharding now and uneven sharding will be supported in the future. + Local tensor information can be obtained from the DistributedTensor instance object, + or obtained by the static methods provided by DistributedTensor, + including shard (i.e. the index in the serial tensor), offsets, and sizes. + """ + + @staticmethod + def _validate_sizes_and_dist_attr(sizes, + dims_mapping, + topology, + processes, + rank=None, + shard_sizes=None): + if not (isinstance(sizes, (list, tuple)) + and all(map(lambda x: isinstance(x, int) and x >= 0, sizes))): + raise ValueError( + "The sizes must be list or tuple and item in sizes must be non-negative integer, but got {}" + .format(sizes)) + if not (isinstance(dims_mapping, (list, tuple)) and all( + map(lambda x: isinstance(x, int) and x >= -1, dims_mapping))): + raise ValueError( + "The dims_mapping must be list or tuple and item in dims_mapping must >= -1, but got {}" + .format(dims_mapping)) + if not (isinstance(processes, (list, tuple)) and all( + map(lambda x: isinstance(x, int) and x >= 0, processes))): + raise ValueError( + "The processes must be list or tuple and item in processes must be integer, but got {}" + .format(processes)) + if not (isinstance(topology, (list, tuple)) + and all(map(lambda x: isinstance(x, int) and x > 0, topology))): + raise ValueError( + "The topology must be list or tuple and item in topology must be non-negative integer, but got {}" + .format(topology)) + if rank is not None and not (isinstance(rank, int) and rank >= 0): + raise ValueError("The rank must >= 0, but got {}".format(rank)) + + # NOTE: Only support even sharding now + if shard_sizes is not None: + raise ValueError("Only support even sharding now.") + + @staticmethod + def get_local_sizes(global_sizes, + dims_mapping, + topology, + processes, + rank=None, + shard_sizes=None): + DistributedTensor._validate_sizes_and_dist_attr(global_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + + local_sizes = [] + # for even sharding, the local sizes of every rank are equal + + for idx, item in enumerate(global_sizes): + # This is a trick to avoid dims_mapping is [] + val = dims_mapping[idx] if idx < len(dims_mapping) else -1 + if val == -1: + local_sizes.append(item) + else: + local_sizes.append(item // topology[dims_mapping[idx]]) + + return local_sizes + + @staticmethod + def get_local_offsets(global_sizes, + dims_mapping, + topology, + processes, + rank, + shard_sizes=None): + local_sizes = DistributedTensor.get_local_sizes(global_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + local_offsets = [] + rank_relatvie = processes.index(rank) + coordinate = _linear_idx2coordinate(topology, rank_relatvie) + + for i in range(len(global_sizes)): + if dims_mapping[i] == -1: + local_offsets.append(0) + else: + local_offsets.append(coordinate[dims_mapping[i]] * + local_sizes[i]) + return local_offsets + + @staticmethod + def get_global_sizes(local_sizes, + dims_mapping, + topology, + processes, + rank=None, + shard_sizes=None): + DistributedTensor._validate_sizes_and_dist_attr(local_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + global_sizes = [] + for idx, item in enumerate(local_sizes): + if dims_mapping[idx] == -1: + global_sizes.append(item) + else: + global_sizes.append(item * topology[dims_mapping[idx]]) + return global_sizes + + @staticmethod + def get_local_shard(global_sizes, + dims_mapping, + topology, + processes, + rank, + shard_sizes=None): + local_offsets = DistributedTensor.get_local_offsets( + global_sizes, dims_mapping, topology, processes, rank, shard_sizes) + local_sizes = DistributedTensor.get_local_sizes(global_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + assert len(local_sizes) == len( + local_offsets + ), "The length of local_sizes must be equal to local_offsets, but got {} and {}.".format( + len(local_sizes), len(local_offsets)) + + local_end_offsets = list( + map(lambda x: x[0] + x[1], zip(local_offsets, local_sizes))) + local_shard = list(zip(local_offsets, local_end_offsets)) + return local_shard + + def __init__(self, serial_tensor, dist_attr=None, dist_context=None): + self._serial_tensor = serial_tensor + self._dist_attr = None + self._batch_dim = 0 + # Reuse the dist_attr setter to initialize _dist_attr + self.dist_attr = dist_attr + self._local_offsets_map = {} + self._local_shard_map = {} + self._local_tensor_map = {} + + from .dist_context import get_default_distributed_context + self._dist_context = dist_context if dist_context is not None else get_default_distributed_context( + ) + # TODO: Add Automatically to dist_context after initialized and it will be adapted in the future. + # self._dist_context.add_dist_tensor_for_program(self) + + @property + def serial_tensor(self): + return self._serial_tensor + + @property + def dist_attr(self): + return self._dist_attr + + @property + def dist_context(self): + return self._dist_context + + @dist_attr.setter + def dist_attr(self, dist_attr): + if self._dist_attr is None: + self._dist_attr = TensorDistributedAttribute() + self._dist_attr.init(dist_attr) + self._init_default_dist_attr() + + def _init_default_dist_attr(self): + if self._dist_attr.dims_mapping is None: + if self.serial_tensor.type == core.VarDesc.VarType.READER \ + or self.serial_tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or self.serial_tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = self._serial_tensor.shape + tensor_dims_mapping = [-1 for _ in range(len(tensor_shape))] + self._dist_attr.dims_mapping = tensor_dims_mapping + + def validate_dist_attr(self): + if self.serial_tensor.type == core.VarDesc.VarType.READER \ + or self.serial_tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or self.serial_tensor.type == core.VarDesc.VarType.STEP_SCOPES: + return True + tensor_shape = self.serial_tensor.shape + if len(tensor_shape) != len(self.dist_attr.dims_mapping): + return False + for i in range(len(self.dist_attr.dims_mapping)): + if self.dist_attr.dims_mapping[ + i] < -1 or self.dist_attr.dims_mapping[i] >= len( + self.dist_attr.process_mesh.topology): + return False + for i in range(len(self.dist_attr.process_mesh.topology)): + if self.dist_attr.dims_mapping.count(i) > 1: + return False + return True + + def local_sizes(self, rank=None): + """Get local sizes of the given rank.""" + rank = paddle.distributed.get_rank() if rank is None else rank + global_sizes = self.serial_tensor.shape + dims_mapping = self.dist_attr.dims_mapping + shard_sizes = self.dist_attr.shard_sizes + processes = self.dist_attr.process_mesh.processes + topology = self.dist_attr.process_mesh.topology + local_sizes = DistributedTensor.get_local_sizes(global_sizes, + dims_mapping, topology, + processes, rank, + shard_sizes) + + return local_sizes + + def local_offsets(self, rank=None): + rank = paddle.distributed.get_rank() if rank is None else rank + local_offsets = None + if rank in self._local_offsets_map.keys(): + local_offsets = self._local_offsets_map[rank] + else: + global_sizes = self.serial_tensor.shape + dims_mapping = self.dist_attr.dims_mapping + shard_sizes = self.dist_attr.shard_sizes + processes = self.dist_attr.process_mesh.processes + topology = self.dist_attr.process_mesh.topology + local_offsets = DistributedTensor.get_local_offsets( + global_sizes, dims_mapping, topology, processes, rank, + shard_sizes) + self._local_offsets_map[rank] = local_offsets + + return local_offsets + + def global_sizes(self): + return self.serial_tensor.shape + + def local_shard(self, rank=None): + rank = paddle.distributed.get_rank() if rank is None else rank + local_shard = None + if rank in self._local_shard_map.keys(): + local_shard = self._local_shard_map[rank] + else: + global_sizes = self.serial_tensor.shape + dims_mapping = self.dist_attr.dims_mapping + shard_sizes = self.dist_attr.shard_sizes + processes = self.dist_attr.process_mesh.processes + topology = self.dist_attr.process_mesh.topology + local_shard = DistributedTensor.get_local_shard( + global_sizes, dims_mapping, topology, processes, rank, + shard_sizes) + self._local_shard_map[rank] = local_shard + + return local_shard + + def new_local_tensor(self, block=None, rank=None, name=None): + """ + Create a new local tensor of serial tensor corresponding to rank. + Args: + block (Block): The block contains the new tensor. Default value is recommend and it will be created in the block of dist main program corresponding to the serial tensor block id. Default: None. + rank (int): The rank id. Default value is recommend and it will be the current rank. Default: None. + """ + + def _copy_kwargs(serial_tensor): + kwargs = {} + no_need_copy_args = ["self", "block", "shape", "name"] + arg_spec = inspect.getargspec(Variable.__init__) + + for key in arg_spec.args: + # TODO: Check the copied attribute from serial tensor whether valid + if key in no_need_copy_args: + continue + elif key not in kwargs: + if key == "type": + kwargs[key] = serial_tensor.desc.type() + elif key == "dtype": + kwargs[key] = serial_tensor.desc.dtype() + elif key == "lod_level": + kwargs[key] = serial_tensor.desc.lod_level() + elif key == "persistable": + kwargs[key] = serial_tensor.desc.persistable() + elif key == "stop_gradient": + kwargs[key] = serial_tensor.desc.stop_gradient() + elif key == "need_check_feed": + kwargs[key] = serial_tensor.desc.need_check_feed() + # TODO: Get capacity by framework + elif key == "capacity": + continue + else: + kwargs[key] = self.serial_tensor.__dict__[key] + + if isinstance(serial_tensor, Parameter): + kwargs["trainable"] = serial_tensor.trainable + kwargs["optimize_attr"] = serial_tensor.trainable + kwargs["regularizer"] = serial_tensor.regularizer + kwargs["do_model_average"] = serial_tensor.do_model_average + kwargs["need_clip"] = serial_tensor.need_clip + kwargs["is_distributed"] = serial_tensor.is_distributed + kwargs["is_parameter"] = serial_tensor.is_parameter + + return kwargs + + if rank is not None and not (isinstance(rank, int) and rank >= 0): + raise ValueError("The rank must >= 0, but got {}".format(rank)) + if block is not None and not isinstance(block, Block): + raise TypeError("The block must be Block, but got {}.".format( + type(block))) + rank = paddle.distributed.get_rank() if rank is None else rank + + if block is None: + block_id = self.serial_tensor.block.idx + block = self.dist_context.dist_main_programs[rank].block(block_id) + + # copy serial tensor attribute + kwargs = _copy_kwargs(self.serial_tensor) + kwargs["name"] = name + kwargs["shape"] = self.local_sizes(rank) + + if isinstance(self.serial_tensor, Parameter): + kwargs.pop("persistable") + local_tensor = Parameter(block=block, **kwargs) + else: + local_tensor = block.create_var(**kwargs) + + # TODO: Set original id when set original_id is approved + local_tensor.desc.set_original_id(self.serial_tensor.desc.id()) + self._local_tensor_map[rank] = local_tensor + return local_tensor + + def local_tensor(self, rank=None): + rank = paddle.distributed.get_rank() if rank is None else rank + assert rank in self._local_tensor_map, "The rank {} local tensor has not been created.".format( + rank) + return self._local_tensor_map[rank] + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k == "_serial_tensor" or k == "_local_tensor_map": + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + return result + + def __str__(self): + str = "{{tensor name: {}, tensor id: {}".format( + self.serial_tensor.desc.name(), self.serial_tensor.desc.id()) + + # str += ", {}".format(self.dist_attr) + # return str + + if self.dist_attr.is_annotated("process_mesh"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += ", process_mesh ({}): {}".format(annotated_str, + self.dist_attr.process_mesh) + + str += ", is_parameter: {}".format(self.serial_tensor.is_parameter) + + if self.dist_attr.is_annotated("dims_mapping"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += ", dims_mapping ({}): {}".format(annotated_str, + self.dist_attr.dims_mapping) + + if self.dist_attr.is_annotated("shard_mask"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += ", shard_mask ({}): {}".format(annotated_str, None) + + if self.dist_attr.is_annotated("offload_device"): + annotated_str = "annotated" + else: + annotated_str = "non-annotated" + str += ", offload_device ({}): {} }}".format(annotated_str, None) + return str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/engine.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f1b249d12831fdc3f665bbee8424cc32eb6502 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/engine.py @@ -0,0 +1,1789 @@ +# Copyright (c) 2022 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. + +import os +import copy +import logging +import random +import numbers +import numpy as np +from collections import defaultdict + +import paddle +import paddle.utils as utils + +from paddle import fluid, static +from paddle.metric import Metric +from paddle.static import InputSpec +from paddle.fluid import core +from paddle.fluid import Variable +from paddle.fluid.layers.utils import flatten +from paddle.fluid.executor import global_scope, _to_name_str +from paddle.fluid.framework import Operator, _non_static_mode +from paddle.fluid.framework import _current_expected_place as _get_device +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.distributed import fleet + +from .callbacks import config_callbacks +from .converter import Converter +from .helper import ProgramHelper +from .cluster import Cluster, get_default_cluster +from .planner_v2 import Planner +from .parallelizer_v2 import Parallelizer +from .dist_op import DistributedOperator +from .dist_saver import DistributedSaver +from .dist_loader import ( + DistributedDataLoaderFromGenerator, + DistributedDataLoader, +) +from .process_group import new_process_group, get_all_process_groups +from .dist_context import DistributedContext, get_default_distributed_context +from .strategy import Strategy +from .interface import CollectionNames, get_collection +from .utils import to_list, get_dist_attr, get_lr, validate_opt +from .utils import initialize_pg_in_full_mode, get_input_split_info +from .cost.estimate_cost import get_cost_from_engine + +from ..utils.log_utils import get_logger + + +class Engine: + """ + An Engine object can provide the full power of auto parallel to users. + With the help of it, users can easily obtain the abilities of the + distributed training and inference. It also support the dynamic graph and + static graph at the same time. + + Args: + model (paddle.nn.Layer, optional): The model is an instance of + paddle.nn.Layer. + loss (Loss|Callable|None, optional): The loss can be a `paddle.nn.Layer` + instance or any callable function taken the predicted values and + ground truth values as input. It can be None when there is no loss. + Default: None. + optimizer (Optimizer|None, optional): The optimizer need to be set in training + and should be None in eval and predict mode. Default: None. + metrics (Metric|list[Metric]|None, optional): If metrics is set, all + metrics will be calculated and output in train/eval mode. Default: None. + cluster (Cluster|None, optional): The cluster represents the topology information + about the used physical devices. Default: None. (Unused for now) + strategy (Strategy|None, optional): The strategy is used to configure the + parallelization and optimization behaviors. Default: None. + + Examples: + + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + valid_dataset = MNIST(mode='test', transform=transform) + + model = paddle.vision.models.LeNet() + loss = paddle.nn.CrossEntropyLoss() + optimizer = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + metrics = paddle.metric.Accuracy(topk=(1, 2)) + + engine = auto.Engine(model, loss, optimizer, metrics) + # fit + engine.fit(train_dataset, + epochs=2, + batch_size=64) + # evaluate + engine.evaluate(valid_dataset, + batch_size=64) + # predict + engine.predict(valid_dataset, + batch_size=64) + # save + engine.save("./my_model") + # load + engine.load("./my_model") + + """ + + def __init__( + self, + model=None, + loss=None, + optimizer=None, + metrics=None, + cluster=None, + strategy=None, + ): + + if ( + model + and not isinstance(model, paddle.nn.Layer) + and not callable(model) + ): + raise TypeError( + "'model must be sub classes of `paddle.nn.Layer` or any callable function." + ) + self._model = model + + if ( + loss + and not isinstance(loss, (paddle.nn.Layer, Variable)) + and not callable(loss) + ): + raise TypeError( + "'loss' must be sub classes of `paddle.nn.Layer` or any callable function or a Variable." + ) + self._loss = loss + + if optimizer and not isinstance( + optimizer, + (paddle.optimizer.Optimizer, paddle.fluid.optimizer.Optimizer), + ): + raise TypeError( + "'optimizer' must be object of class `paddle.optimizer.Optimizer`" + " or `paddle.fluid.optimizer.Optimizer`." + ) + self._optimizer = validate_opt(optimizer) + self._orig_optimizer = copy.deepcopy(self._optimizer) + + metrics = metrics or [] + for metric in to_list(metrics): + if metric and not isinstance(metric, Metric): + raise TypeError( + "{} is not sub class of Metric".format( + metric.__class__.__name__ + ) + ) + self._metrics = to_list(metrics) + + if cluster and not isinstance(cluster, Cluster): + raise TypeError( + "'cluster' must be the object or class `paddle.distributed.auto_parallel.Cluster`" + ) + self._cluster = cluster or get_default_cluster() + + if strategy and not isinstance(strategy, Strategy): + raise TypeError( + "'strategy' must be object of class `paddle.distributed.auto_parallel.Strategy`" + ) + self._strategy = strategy or Strategy() + + self._logger = get_logger(logging.INFO) + if os.getenv("POD_NAME"): + self._logger.info( + "Distribute training by paddle.distributed.launch" + ) + fleet.init(is_collective=True) + + self._executor = None + self._cur_rank = paddle.distributed.get_rank() + self._nranks = paddle.distributed.get_world_size() + self._saver = DistributedSaver() + + self._orig_main_prog = static.default_main_program() + self._orig_startup_prog = static.default_startup_program() + self._orig_dist_context = get_default_distributed_context() + self._dist_contexts = {} + self._fwd_main_progs = {} + self._fwd_dist_contexts = {} + self._serial_main_progs = {} + self._serial_startup_progs = {} + self._dist_main_progs = defaultdict(dict) # dist main programs + self._dist_startup_progs = defaultdict(dict) # dist startup programs + self._feed_vars = {} + self._fetch_vars = {} + self._planners = {} + self._has_prepared = {"train": False, "eval": False, "predict": False} + self._has_prepared_reader = { + "train": False, + "eval": False, + "predict": False, + } + self._inputs_spec = [] + self._labels_spec = [] + self._inputs = [] + self._labels = [] + self._losses = [] + + self._mode = None + self._skip_build = False + self._outside_dataloader = False + self._planned_mode = None + self._dygraph_mode = False + self._tuning = self._strategy.tuning + + self.history = None + + def _prepare_data_spec(self, data, split, batch_size): + inputs_spec = [] + labels_spec = [] + if isinstance(data, paddle.io.IterableDataset): + if split is None: + inputs, labels = next(iter(data)) + else: + sample = next(iter(data)) + inputs = sample[:split] + labels = sample[split:] + elif isinstance(data, paddle.io.Dataset): + if split is None: + inputs, labels = data[0] + else: + sample = data[0] + inputs = sample[:split] + labels = sample[split:] + else: + raise TypeError( + "Data should be a Dataset or IterableDatset, but received {}.".format( + type(data).__name__ + ) + ) + inputs = to_list(inputs) + labels = to_list(labels) + + num_shards = self._strategy.dataset.num_shards + + def _adjust_item_spec(num_shards, spec): + if num_shards > 1 and len(spec.shape) > 1: + spec.shape[0] = spec.shape[0] * num_shards + + def _infer_item_spec(item, name, batch_size, specs): + if isinstance(item, np.ndarray): + spec = InputSpec.from_numpy(item, name) + if batch_size is None: + _adjust_item_spec(num_shards, spec) + specs.append(spec) + else: + specs.append(spec.batch(batch_size)) + elif isinstance(item, (Variable, core.VarBase, core.eager.Tensor)): + spec = InputSpec.from_tensor(item, name) + _adjust_item_spec(num_shards, spec) + if batch_size is None: + specs.append(spec) + else: + specs.append(spec.batch(batch_size)) + elif isinstance(item, numbers.Number): + specs.append(InputSpec([batch_size], type(item), name)) + else: + raise TypeError( + "The sample's dtype returned of dataset should be number, np.ndarray or Tensor, but got {}".format( + type(item).__name__ + ) + ) + + if inputs is not None: + for i, item in enumerate(inputs): + assert item is not None, "Receive None input." + name = "input" + str(i) + _infer_item_spec(item, name, batch_size, inputs_spec) + if labels is not None: + for i, item in enumerate(labels): + assert item is not None, "Receive None input." + name = "label" + str(i) + _infer_item_spec(item, name, batch_size, labels_spec) + + inputs_spec = self._validate_spec(inputs_spec) + labels_spec = self._validate_spec(labels_spec) + return inputs_spec, labels_spec + + def _prepare_data_tensor(self, inputs_spec, labels_spec, inputs, labels): + if _non_static_mode() or self._dygraph_mode: + raise ValueError("Only support static graph mode.") + + if inputs_spec: + assert isinstance( + inputs_spec, list + ), "inputs should be list, but received {}".format( + type(inputs_spec) + ) + assert isinstance( + inputs, list + ), "inputs should be list, but received {}".format(type(inputs)) + assert len(inputs_spec) == len( + inputs + ), "the number of `inputs_spec` should be equal to `inputs`'s." + for input_spec, input in zip(inputs_spec, inputs): + if input_spec.shape != input.shape: + input.desc.set_shape(input_spec.shape) + if labels_spec: + assert isinstance( + labels_spec, list + ), "labels should be list, but received {}".format( + type(labels_spec) + ) + assert isinstance( + labels, list + ), "labels should be list, but received {}".format(type(labels)) + assert len(labels_spec) == len( + labels + ), "the number of `labels_spec` should be equal to `labels`'s." + for label_spec, label in zip(labels_spec, labels): + if label_spec.shape != label.shape: + label.desc.set_shape(label_spec.shape) + + return inputs, labels + + def _prepare_reader(self): + dist_main_prog = self._dist_main_progs[self._mode][self._cur_rank] + dist_context = self._dist_contexts[self._mode] + dist_main_block = dist_main_prog.global_block() + + # NOTE: this list may be changed if Paddle changes the existing rules. + related_reader_ops = [ + "create_py_reader", + "create_double_buffer_reader", + "read", + ] + # remove the first three ops if multiple run fit/evaluate/predict + if dist_main_block.ops[0].type == 'create_py_reader': + for i in range(len(related_reader_ops)): + if dist_main_block.ops[0].type in related_reader_ops: + dist_main_block._remove_op(0, sync=False) + dist_main_block._sync_with_cpp() + # Step 1: find the reader ops + reader_op_indices = [] + for idx, op in enumerate(dist_main_block.ops): + if op.type in related_reader_ops: + reader_op_indices.append(idx) + # Step 2: insert the new reader ops to cpp + new_reader_ops = [] + for idx in reversed(reader_op_indices): + new_op_desc = dist_main_block.desc._prepend_op() + new_op_desc.copy_from(dist_main_block.ops[idx].desc) + new_op = Operator( + dist_main_block, new_op_desc, type=new_op_desc.type() + ) + new_reader_ops.append(new_op) + dist_op = DistributedOperator(new_op) + dist_context.add_dist_op_for_program(dist_op) + # Step 3: insert the new reader ops to python + for new_op in new_reader_ops: + dist_main_block.ops.insert(0, new_op) + for i in range(len(reader_op_indices)): + reader_op_indices[i] += len(reader_op_indices) + # Step 4: remove the old reader ops from python and cpp + for idx in reversed(reader_op_indices): + op = dist_main_block.ops.pop(idx) + dist_main_block.desc._remove_op(idx, idx + 1) + dist_main_block._sync_with_cpp() + self._has_prepared_reader[self._mode] = True + + def _prepare_feed(self, data, user_feeds, mode): + feeds = {} + if data is not None: + if isinstance(data, (list, tuple)): + if len(data) == 1 and isinstance(data[0], dict): + for name, data in data[0].items(): + feeds[name] = data + else: + raise ValueError("Unsupported data {}".format(data)) + elif isinstance(data, dict): + for name, data in data.items(): + feeds[name] = data + else: + raise ValueError("Unsupported data {}".format(data)) + if user_feeds is not None: + assert isinstance( + user_feeds, dict + ), "user_feeds must be a dict, but receive {}".format( + type(user_feeds).__name__ + ) + for name, data in user_feeds.items(): + feeds[name] = data + return feeds + + def _prepare_fetch(self, user_fetches, mode): + if user_fetches is not None: + assert isinstance( + user_fetches, list + ), "user_fetches must be a list, but receive {}".format( + type(user_fetches).__name__ + ) + fetch_names = [] + fetch_indices = [] + + def _process_fetch_group(group_name, var_list): + group_indices = [] + for var in var_list: + # Remove duplicate var_names + if self._is_local_var(var): + var_name = _to_name_str(var) + if var_name not in fetch_names: + fetch_names.append(var_name) + group_indices.append(fetch_names.index(var_name)) + if not group_indices: + fetch_names.append([]) + fetch_indices.append(group_indices) + + if mode != "predict": + _process_fetch_group("loss", self._fetch_vars[mode]["loss"]) + if mode != "predict": + metrics = self._fetch_vars[mode]["metrics"] + for i, var_list in enumerate(metrics): + _process_fetch_group("metrics_" + str(i), var_list) + if mode == "predict": + _process_fetch_group("outputs", self._fetch_vars[mode]["outputs"]) + user_fetches_collection = [ + item[1] for item in get_collection(CollectionNames.FETCHES) + ] + var_list = (user_fetches_collection or []) + (user_fetches or []) + _process_fetch_group("fetches", var_list) + return fetch_names, fetch_indices + + def _prepare_logger( + self, + outs, + epoch=None, + step=None, + lr=None, + fetch_names=None, + fetch_indices=None, + mode=None, + ): + logs = {} + if epoch is not None: + logs["epoch"] = epoch + if step is not None: + logs["step"] = step + 1 + if lr is not None: + logs["lr"] = lr + group_idx = 0 + if mode != "predict": + # logging loss + loss_indices = fetch_indices[group_idx] + assert len(loss_indices) <= 1 + for idx in loss_indices: + logs["loss"] = outs[idx][0] + group_idx += 1 + # logging metrics + metric_vars = self._fetch_vars[mode]["metrics"] + if metric_vars: + for metric in self._metrics: + metrics_indices = fetch_indices[group_idx] + metric_out = [] + for idx in metrics_indices: + metric_out.append(outs[idx]) + if metric_out: + metric.update(*metric_out) + results = metric.accumulate() + for i, res in enumerate(to_list(results)): + logs[metric.name()[i]] = res + group_idx += 1 + # logging outputs + elif mode == "predict": + outputs_indices = fetch_indices[group_idx] + logs_out = {} + for idx in outputs_indices: + logs_out["out%d" % (idx)] = outs[idx] + logs["outputs"] = logs_out + group_idx += 1 + # logging user fetches + collect_fetches = get_collection(CollectionNames.FETCHES) + logs_fetch = {} + for name, var in collect_fetches: + if var.name in fetch_names: + idx = fetch_names.index(var.name) + logs_fetch[name or var.name] = outs[idx] + logs["fetches"] = logs_fetch + return logs + + def _prepare_program(self, mode): + # Do the build process + self._build(mode) + # Do the planning process + self._plan(mode) + # Do the parallel process + self._parallel(mode) + # Init comm and startup program + self._initialize(mode) + self._has_prepared[mode] = True + + def _build(self, mode): + if _non_static_mode() or self._dygraph_mode: + paddle.disable_static() + self._dygraph_mode = True + self._logger.info("Building model with 'to_static' method.") + + self.program_helper = ProgramHelper( + self._model, + self._loss, + self._metrics, + self._inputs_spec, + self._labels_spec, + ) + # build forward main program + self.program_helper.build_program(mode) + + self.concrete_program = self.program_helper.concrete_program + serial_main_prog = self.program_helper.main_program + serial_startup_prog = self.program_helper.startup_program + + self._inputs = self.program_helper.input_vars + self._labels = self.program_helper.label_vars + outputs = self.program_helper.output_vars + self._losses = self.program_helper.loss_vars + metrics = self.program_helper.metric_vars + + paddle.enable_static() + else: + # build program in static mode + serial_main_prog = self._serial_main_progs.get(mode, None) + if serial_main_prog is not None: + return + + outputs = [] + metrics = [] + self._losses = [] + serial_main_prog = self._orig_main_prog.clone() + serial_startup_prog = self._orig_startup_prog.clone() + if not self._skip_build: + with static.program_guard( + serial_main_prog, serial_startup_prog + ), utils.unique_name.guard(): + self._inputs = [ + s._create_feed_layer() for s in self._inputs_spec + ] + self._labels = [ + s._create_feed_layer() for s in self._labels_spec + ] + + outputs = to_list(self._model(*self._inputs)) + + if mode != "predict" and self._loss: + assert isinstance( + self._loss, paddle.nn.Layer + ) or callable( + self._loss + ), "the type of `loss` of the Engine arguments should be sub classes of `paddle.nn.Layer` or any callable function." + self._losses = to_list( + self._loss(*(outputs + self._labels)) + ) + + if mode != "predict" and (outputs or self._labels): + for metric in self._metrics: + metrics.append( + to_list( + metric.compute(*(outputs + self._labels)) + ) + ) + else: + assert isinstance( + self._loss, Variable + ), "the type of `loss` of the Engine arguments should be Variable." + self._losses = to_list(self._loss) + + default_ctx = get_default_distributed_context() + if not default_ctx.has_annotation: + # We build the world process group because the data parallel + # needs all ranks by default. + new_process_group(list(range(self._nranks))) + default_ctx.data_parallel = True + + feed_vars = {"inputs": self._inputs, "labels": self._labels} + + fetch_vars = { + "outputs": flatten(outputs), + "loss": self._losses, + "metrics": metrics, + } + + if mode != "train": + serial_main_prog = serial_main_prog.clone(for_test=True) + + self._set_recompute_ckpts() + self._dist_contexts[mode] = DistributedContext( + serial_main_prog, + serial_startup_prog, + self._optimizer, + self._losses, + feed_vars, + fetch_vars, + self._cluster, + self._strategy, + ) + self._fwd_dist_contexts[mode] = DistributedContext( + serial_main_prog, + serial_startup_prog, + self._optimizer, + self._losses, + feed_vars, + fetch_vars, + self._cluster, + self._strategy, + ) + self._dist_contexts[mode].gradient_scale = self._strategy.gradient_scale + self._fwd_main_progs[mode] = serial_main_prog.clone() + + def _optimization_tuning(self, mode, dataset, batch_size): + if not self._tuning.enable: + raise ValueError("Please set `tuning.enable=True`.") + + assert mode == "train" + # Do the build process + self._build(mode) + # Do the planning process + self._plan(mode) + + dataset.dp_world_size = self._dp_world_sizes + dataset.dp_rank = self._dp_ranks + + from .tuner.optimization_tuner import OptimizationTuner + + self._optimization_tuner = OptimizationTuner( + self._tuning.to_dict(), + self._dist_contexts[mode], + dataset, + self._inputs_spec, + self._labels_spec, + batch_size=batch_size, + rank=self._cur_rank, + ) + + self._optimization_tuner.tune() + + if self._tuning.run_after_tuning: + # update the strategy + self._dist_contexts[ + mode + ]._strategy = self._optimization_tuner.get_best_config() + + def _plan(self, mode): + if self._planned_mode is None: + self._planned_mode = mode + else: + self._init_dist_context(mode) + + self._planners[mode] = Planner(mode, self._dist_contexts[mode]) + self._planners[mode].plan() + + # infer data parallel info + inputs_var = self._dist_contexts[mode].serial_feed_vars["inputs"] + labels_var = self._dist_contexts[mode].serial_feed_vars["labels"] + block = self._dist_contexts[mode].serial_main_program.global_block() + # TODO: check this feed_list + feed_list = [] + for var in inputs_var + labels_var: + if var.name in block.vars: + feed_list.append(block.vars[var.name]) + + self._dp_world_sizes = [] + self._dp_ranks = [] + for feed_var in feed_list: + dp_world_size, dp_rank = get_input_split_info( + self._cur_rank, feed_var, self._dist_contexts[mode] + ) + self._dp_world_sizes.append(dp_world_size) + self._dp_ranks.append(dp_rank) + + def _parallel(self, mode, all_ranks=False): + # Parallelize program based on the planner's results + # For now, the completer has to be passed to the planner, + # because we may use it to complete the annotation of the backwarkward and update. + parallelizer = Parallelizer( + mode, self._planners[mode].completer, self._dist_contexts[mode] + ) + if not all_ranks: + parallelizer.parallel(self._cur_rank) + else: + parallelizer.parallel_all() + + def _init_dist_context(self, mode): + # Init dist_context['mode'] with the first planned dist_context + # to guarantee that train/eval/predict mode have same parallel strategy + dist_context = self._dist_contexts[mode] + origin_main_prog = dist_context._original_serial_main_program + ref_mode = self._planned_mode + ref_dist_context = self._dist_contexts[ref_mode] + ref_origin_main_prog = ref_dist_context._original_serial_main_program + ref_blocks = ref_origin_main_prog.blocks + for ib, block in enumerate(origin_main_prog.blocks): + for iop, op in enumerate(block.ops): + ref_op = ref_blocks[ib].ops[iop] + assert ( + op.type == ref_op.type + ), "'{}' mode op '{}' is different with '{}' op '{}'. ".format( + mode, op.type, ref_mode, ref_op.type + ) + ref_op_dist_attr = ( + ref_dist_context.get_op_dist_attr_for_program(ref_op) + ) + dist_context.set_op_dist_attr_for_program(op, ref_op_dist_attr) + + def _initialize(self, mode): + # Get the current content from the distributed context + self._serial_main_progs[mode] = self._dist_contexts[ + mode + ].serial_main_program + self._serial_startup_progs[mode] = self._dist_contexts[ + mode + ].serial_startup_program + self._dist_main_progs[mode] = self._dist_contexts[ + mode + ].dist_main_programs + self._dist_startup_progs[mode] = self._dist_contexts[ + mode + ].dist_startup_programs + self._feed_vars[mode] = self._dist_contexts[mode].serial_feed_vars + self._fetch_vars[mode] = self._dist_contexts[mode].serial_fetch_vars + self._optimizer = self._dist_contexts[mode]._serial_optimizer + + if self._nranks > 1: + # Traverse different rank programs and traverse each op of them, + # instantiate communication by process_mapping. + all_process_groups = get_all_process_groups() + + if self._strategy.auto_mode == "full": + initialize_pg_in_full_mode(all_process_groups, cur_rank) + else: + for process_group in all_process_groups: + if self._cur_rank not in process_group.ranks: + continue + process_group.instantiate() + + place = _get_device() + if isinstance(place, fluid.CUDAPlace): + place = fluid.CUDAPlace(ParallelEnv().dev_id) + + if self._strategy.seed: + paddle.seed(self._strategy.seed + self._dp_ranks[0]) + np.random.seed(self._strategy.seed + self._dp_ranks[0]) + random.seed(self._strategy.seed + self._dp_ranks[0]) + + if self._dygraph_mode: + dist_context = self._dist_contexts[mode] + dist_main_program = self._dist_main_progs[mode][self._cur_rank] + self.program_helper.init(dist_main_program, place, dist_context) + + if self._executor is None: + self._executor = paddle.static.Executor(place) + uninitialized = [] + dist_startup_prog = self._dist_startup_progs[mode][self._cur_rank] + for var in dist_startup_prog.list_vars(): + scope_var = global_scope().find_var(var.name) + if scope_var and scope_var.get_tensor()._is_initialized(): + continue + uninitialized.append(var) + if uninitialized: + prune_startup_prog = dist_startup_prog._prune(uninitialized) + self._executor.run(prune_startup_prog) + + if hasattr(self, "_state_dict") and hasattr(self, "_dist_attr"): + self._set_state_dict( + mode, self._strict, self._state_dict, self._dist_attr + ) + + if self._strategy.reinit: + self._logger.info("NOTE: parameters will be re-initialized.") + dist_startup_prog = self._dist_startup_progs[mode][self._cur_rank] + self._executor.run(dist_startup_prog) + + def fit( + self, + train_data, + train_sample_split=None, + batch_size=1, + epochs=1, + steps_per_epoch=None, + log_freq=10, + save_dir=None, + save_freq=1, + valid_data=None, + valid_sample_split=None, + valid_freq=1, + valid_steps=None, + collate_fn=None, + callbacks=None, + verbose=2, + ): + """ + Trains the model for a fixed number of epochs. If `valid_data` is set, + evaluation will be done at the end of each epoch. + + Args: + train_data (Dataset): An instance of paddle paddle.io.Dataset. Default: None. + train_sample_split (int, optional): Each sample of the train dataset is assumed + to be a (input, label) pair by default and has two items. If each sample has + more than two items, train_sample_split specifies how to split these items into + input and label. The items before it are input and the left are label. Default: None. + batch_size (int, optional): The batch size of train_data and valid_data if provided. + The user's data will be used directly without batching if set to None. Default: 1. + epochs (int, optional): The number of epochs to train the model. Default: 1. + steps_per_epoch (int, optional): The total number of steps (batches of samples) + is executed in one epoch before stating the next one. If None, it is equal to + the number samples in your dataset divided by the batch size. Default: None. + valid_data (Dataset, optional): An instance of paddle paddle.io.Dataset used for + evaluation at the end of epoch. No evaluation will be done if set to None. + Default: None. (Unsupported for now) + valid_freq (int, optional): Only relevant if valid_data is provided. This specifies + how many training epochs before a new evaluation is performed. Default: 1. + valid_sample_split (int, optional): Only relevant if valid_data is provided. + Each sample of the valid dataset is assumed to be a (input, label) pair + by default and has two items. If each sample has more than two items, + valid_sample_split specifies how to split these items into input and label. + The items before it are input and the left are label. Default: None. + valid_steps (int, optional): Only relevant if valid_data is provided. + It is the total number of steps (batches of samples) to draw before + stopping validation at the end of every epoch. If None, validation will run until the + `valid_data` dataset is exhausted. The validation will start from the + beginning of the dataset at each epoch. Default: None. + collate_fn(callable, optional): function to generate mini-batch data by merging + the sample list, None for only stack each fields of sample in axis + 0. Default None. + callbacks (Callback|None, optional): A list of `Callback` instances to apply + during training. Default: None. (Unused for now) + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + + model = paddle.vision.models.LeNet() + loss = paddle.nn.CrossEntropyLoss() + optimizer = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + metrics = paddle.metric.Accuracy(topk=(1, 2)) + + engine = auto.Engine(model, loss, optimizer, metrics) + engine.fit(train_dataset, + epochs=2, + batch_size=64) + """ + self._mode = 'train' + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + train_data, train_sample_split, batch_size + ) + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + train_dataloader = self._prepare_dataloader_from_generator( + dataset=train_data, + capacity=70, + iterable=False, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + collate_fn=collate_fn, + ) + + fetch_names, fetch_indices = self._prepare_fetch(None, mode=self._mode) + + cbks = config_callbacks( + callbacks, + engine=self, + batch_size=batch_size, + epochs=epochs, + steps=train_dataloader._steps, + log_freq=log_freq, + save_freq=save_freq, + save_dir=save_dir, + verbose=verbose, + metrics=self._metrics_name(), + acc_step=self._k_steps, + ) + + cbks.on_begin('train') + for epoch in range(epochs): + logs = {} + cbks.on_epoch_begin(epoch) + for step, _ in enumerate(train_dataloader): + cbks.on_batch_begin('train', step, logs) + try: + outs = self._executor.run( + self.main_program, + fetch_list=fetch_names, + use_program_cache=self._strategy.use_cache, + return_numpy=self._strategy.return_numpy, + ) + except core.EOFException: + break + lr = get_lr(self._optimizer) + logs = self._prepare_logger( + outs, + epoch, + step, + lr, + fetch_names, + fetch_indices, + self._mode, + ) + cbks.on_batch_end('train', step, logs) + + if valid_data and (epoch + 1) % valid_freq == 0: + val_logs = self.evaluate( + valid_data, + valid_sample_split, + batch_size, + valid_steps, + log_freq, + collate_fn, + callbacks, + verbose, + ) + val_logs = { + "val_" + name: val for name, val in val_logs.items() + } + logs.update(val_logs) + self._switch_mode("train") + else: + self._reset_metrics() + + cbks.on_epoch_end(epoch, logs) + + cbks.on_end('train', logs) + return self.history + + def evaluate( + self, + valid_data, + valid_sample_split=None, + batch_size=1, + steps=None, + log_freq=10, + collate_fn=None, + callbacks=None, + verbose=2, + ): + """ + Evaluate the loss and metrics of the model on evaluation data. + + Args: + valid_data (Dataset): An instance of paddle paddle.io.Dataset. Default: None. + valid_sample_split (int, optional): Each sample of the eval dataset is assumed + to be a (input, label) pair by default and has two items. If each sample has + more than two items, valid_sample_split specifies how to split these items into + input and label. The items before it are input and the left are label. Default: None. + batch_size (int, optional): The batch size of valid_data. The user's data will + be used directly without batching if set to None. Default: 1. + steps (int, optional): It is the total number of steps (batches of samples) to draw before + stopping evaluation. If None, evaluation will run until the `valid_data` dataset is exhausted. + The evaluation will start from the beginning of the dataset in each run. Default: None. + collate_fn(callable, optional): function to generate mini-batch data by merging + the sample list, None for only stack each fields of sample in axis + 0. Default None. + callbacks (Callback|None, optional): A list of `Callback` instances to apply + during evaluating. Default: None. (Unused for now) + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + valid_dataset = MNIST(mode='test', transform=transform) + + model = paddle.vision.models.LeNet() + loss = paddle.nn.CrossEntropyLoss() + metrics = paddle.metric.Accuracy(topk=(1, 2)) + + engine = auto.Engine(model, loss, metrics=metrics) + engine.evaluate(valid_dataset, batch_size=64) + + """ + self._mode = 'eval' + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + valid_data, valid_sample_split, batch_size + ) + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + valid_dataloader = self._prepare_dataloader_from_generator( + dataset=valid_data, + capacity=70, + iterable=False, + batch_size=batch_size, + steps_per_epoch=steps, + collate_fn=collate_fn, + ) + + fetch_names, fetch_indices = self._prepare_fetch(None, mode=self._mode) + + cbks = config_callbacks( + callbacks, + engine=self, + batch_size=batch_size, + log_freq=log_freq, + verbose=verbose, + metrics=self._metrics_name(), + ) + + eval_steps = valid_dataloader._steps + cbks.on_begin( + 'eval', {'steps': eval_steps, 'metrics': self._metrics_name()} + ) + logs = {} + for step, _ in enumerate(valid_dataloader): + cbks.on_batch_begin('eval', step, logs) + try: + outs = self._executor.run( + self.main_program, + fetch_list=fetch_names, + use_program_cache=self._strategy.use_cache, + return_numpy=self._strategy.return_numpy, + ) + except core.EOFException: + break + logs = self._prepare_logger( + outs, None, step, None, fetch_names, fetch_indices, self._mode + ) + cbks.on_batch_end('eval', step, logs) + cbks.on_end('eval', logs) + self._reset_metrics() + return logs + + def predict( + self, + test_data, + test_sample_split=None, + batch_size=1, + steps=None, + collate_fn=None, + callbacks=None, + verbose=2, + ): + """ + Compute the output predictions on testing data. + + Args: + test_data (Dataset): An instance of paddle paddle.io.Dataset. Default: None. + test_sample_split (int, optional): Each sample of the test dataset is assumed + to be a (input, label) pair by default and has two items. If each sample has + more than two items, test_sample_split specifies how to split these items into + input and label. The items before it are input and the left are label. Default: None. + batch_size (int, optional): The batch size of test_data. The user's data will + be used directly without batching if set to None. Default: 1. + steps (int, optional): It is the total number of steps (batches of samples) to draw before + stopping predict. If None, predict will run until the `test_data` dataset is exhausted. + The predict will start from the beginning of the dataset in each run. Default: None. + collate_fn(callable, optional): function to generate mini-batch data by merging + the sample list, None for only stack each fields of sample in axis + 0. Default None. + callbacks (Callback|None, optional): A list of `Callback` instances to apply + during testing. Default: None. (Unused for now) + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + valid_dataset = MNIST(mode='test', transform=transform) + + model = paddle.vision.models.LeNet() + + engine = auto.Engine(model) + engine.predict(valid_dataset, batch_size=64) + """ + self._mode = 'predict' + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + test_data, test_sample_split, batch_size + ) + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + test_dataloader = self._prepare_dataloader_from_generator( + dataset=test_data, + capacity=70, + iterable=False, + batch_size=batch_size, + steps_per_epoch=steps, + collate_fn=collate_fn, + ) + + fetch_names, fetch_indices = self._prepare_fetch(None, mode=self._mode) + + outputs = [] + cbks = config_callbacks(callbacks, engine=self, verbose=verbose) + test_steps = test_dataloader._steps + cbks.on_begin('predict', {'steps': test_steps}) + logs = {} + for step, _ in enumerate(test_dataloader): + cbks.on_batch_begin('predict', step, logs) + try: + outs = self._executor.run( + self.main_program, + fetch_list=fetch_names, + use_program_cache=self._strategy.use_cache, + return_numpy=self._strategy.return_numpy, + ) + except core.EOFException: + break + logs = self._prepare_logger( + outs, None, step, None, fetch_names, fetch_indices, self._mode + ) + cbks.on_batch_end('predict', step, logs) + outputs.append(list(logs["outputs"].values())) + cbks.on_end('predict', logs) + return outputs + + def dataloader( + self, + dataset, + batch_size=1, + shuffle=False, + drop_last=False, + collate_fn=None, + num_workers=0, + use_buffer_reader=True, + use_shared_memory=True, + timeout=0, + worker_init_fn=None, + epochs=1, + steps_per_epoch=None, + sample_split=1, + mode=None, + ): + if mode is not None: + self.to_mode(mode) + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + dataset, sample_split, batch_size + ) + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + dataloader = self._prepare_dataloader( + dataset, + return_list=False, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last, + collate_fn=collate_fn, + num_workers=num_workers, + use_buffer_reader=use_buffer_reader, + use_shared_memory=use_shared_memory, + timeout=timeout, + worker_init_fn=worker_init_fn, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + ) + return dataloader + + def dataloader_from_generator( + self, + dataset, + capacity=70, + use_double_buffer=True, + iterable=True, + use_multiprocess=False, + drop_last=True, + batch_size=1, + epochs=1, + steps_per_epoch=None, + collate_fn=None, + sample_split=1, + mode=None, + ): + if mode is not None: + self.to_mode(mode) + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + dataset, sample_split, batch_size + ) + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + dataloader = self._prepare_dataloader_from_generator( + dataset=dataset, + capacity=capacity, + use_double_buffer=use_double_buffer, + iterable=iterable, + return_list=False, + use_multiprocess=use_multiprocess, + drop_last=drop_last, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + collate_fn=collate_fn, + ) + return dataloader + + def prepare( + self, + inputs_spec=None, + labels_spec=None, + inputs=None, + labels=None, + main_program=None, + startup_program=None, + mode=None, + ): + if mode is not None: + self.to_mode(mode) + + if not self._mode: + raise ValueError( + "Please set mode to be prepared with `prepare(mode=...)`" + ) + + if self._has_prepared[self._mode]: + return + + inputs_spec = self._validate_spec(inputs_spec) + labels_spec = self._validate_spec(labels_spec) + inputs = self._validate_vars(inputs) + labels = self._validate_vars(labels) + + self._orig_main_prog = main_program + self._orig_startup_prog = startup_program + if inputs or labels: + self._skip_build = True + inputs, labels = self._prepare_data_tensor( + inputs_spec, labels_spec, inputs, labels + ) + if self._orig_main_prog is None: + self._orig_main_prog = static.default_main_program() + if self._orig_startup_prog is None: + self._orig_startup_prog = static.default_startup_program() + elif inputs_spec or labels_spec: + self._outside_dataloader = True + if self._orig_main_prog is None: + self._orig_main_prog = static.default_main_program() + if self._orig_startup_prog is None: + self._orig_startup_prog = static.default_startup_program() + else: + assert ( + self._inputs_spec and self._labels_spec + ), "Please call the dataloader(...) before calling prepare(...)" + + self._inputs_spec, self._labels_spec = inputs_spec, labels_spec + self._inputs, self._labels = inputs, labels + if not self._has_prepared[self._mode]: + self._prepare_program(self._mode) + else: + self._switch_mode(self._mode) + + def run(self, data=None, feed=None, fetch_list=None, mode=None): + if mode is not None: + self.to_mode(mode) + feed_dict = self._prepare_feed(data, feed, self._mode) + fetch_names, fetch_indices = self._prepare_fetch(fetch_list, self._mode) + if ( + self._outside_dataloader + and not self._has_prepared_reader[self._mode] + ): + self._prepare_reader() + outs = self._executor.run( + self.main_program, + feed=feed_dict, + fetch_list=fetch_names, + use_program_cache=self._strategy.use_cache, + return_numpy=self._strategy.return_numpy, + ) + logs = self._prepare_logger( + outs, None, None, None, fetch_names, fetch_indices, self._mode + ) + return logs + + def _prepare_dataloader( + self, + dataset, + return_list=True, + batch_size=1, + shuffle=False, + drop_last=False, + collate_fn=None, + num_workers=0, + use_buffer_reader=True, + use_shared_memory=True, + timeout=0, + worker_init_fn=None, + epochs=1, + steps_per_epoch=None, + ): + + if self._strategy.gradient_merge and batch_size is not None: + assert ( + batch_size % self._k_steps == 0 + ), "Requires batch_size:[{}] to be divisible by k_steps:[{}].".format( + batch_size, self._k_steps + ) + batch_size //= self._k_steps + + dist_main_prog = self._dist_main_progs[self._mode][self._cur_rank] + dist_startup_prog = self._dist_startup_progs[self._mode][self._cur_rank] + dist_main_block = dist_main_prog.global_block() + + # NOTE: Get feed_list, then insert dataloader op with sharded var shape. + # Cause predict_program does not contain labels var, + # then we will add labels var from serial_program to dist_program, + # that maintains the length of feed_list equal to the length of dataset's values. + inputs_var = self._feed_vars[self._mode]["inputs"] + labels_var = self._feed_vars[self._mode]["labels"] + feed_list = [] + for var in inputs_var + labels_var: + if var.name in dist_main_block.vars: + feed_list.append(dist_main_block.vars[var.name]) + else: + copy_var = dist_main_block._clone_variable(var, var.persistable) + copy_var.desc.set_original_id(var.desc.original_id()) + feed_list.append(copy_var) + + # insert read op at the end of program + places = paddle.static.cuda_places() + with static.program_guard(dist_main_prog, dist_startup_prog): + dataloader = DistributedDataLoader( + dataset, + feed_list=feed_list, + places=places, + return_list=return_list, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last, + collate_fn=collate_fn, + num_workers=num_workers, + use_buffer_reader=use_buffer_reader, + use_shared_memory=use_shared_memory, + timeout=timeout, + worker_init_fn=worker_init_fn, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + split_data=self._strategy.split_data, + data_parallel_world_size=self._dp_world_sizes, + data_parallel_rank=self._dp_ranks, + ) + + return dataloader + + def _prepare_dataloader_from_generator( + self, + dataset, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=False, + use_multiprocess=False, + drop_last=True, + batch_size=1, + epochs=1, + steps_per_epoch=None, + collate_fn=None, + ): + + if self._strategy.gradient_merge and batch_size is not None: + assert ( + batch_size % self._k_steps == 0 + ), "Requires batch_size:[{}] to be divisible by k_steps:[{}].".format( + batch_size, self._k_steps + ) + batch_size //= self._k_steps + + dist_main_prog = self._dist_main_progs[self._mode][self._cur_rank] + dist_startup_prog = self._dist_startup_progs[self._mode][self._cur_rank] + dist_main_block = dist_main_prog.global_block() + + # NOTE: Get feed_list, then insert dataloader op with sharded var shape. + # Cause predict_program does not contain labels var, + # then we will add labels var from serial_program to dist_program, + # that maintains the length of feed_list equal to the length of dataset's values. + inputs_var = self._feed_vars[self._mode]["inputs"] + labels_var = self._feed_vars[self._mode]["labels"] + feed_list = [] + for var in inputs_var + labels_var: + if var.name in dist_main_block.vars: + feed_list.append(dist_main_block.vars[var.name]) + else: + copy_var = dist_main_block._clone_variable(var, var.persistable) + copy_var.desc.set_original_id(var.desc.original_id()) + feed_list.append(copy_var) + + places = paddle.static.cuda_places() + with static.program_guard(dist_main_prog, dist_startup_prog): + dataloader = DistributedDataLoaderFromGenerator( + dataset=dataset, + feed_list=feed_list, + capacity=capacity, + use_double_buffer=use_double_buffer, + iterable=iterable, + return_list=return_list, + use_multiprocess=use_multiprocess, + drop_last=drop_last, + places=places, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + collate_fn=collate_fn, + split_data=self._strategy.split_data, + data_parallel_world_size=self._dp_world_sizes, + data_parallel_rank=self._dp_ranks, + ) + self._prepare_reader() + return dataloader + + def _tune(self, tune_data, tune_sample_split=None, batch_size=1): + self._mode = 'train' + self._inputs_spec, self._labels_spec = self._prepare_data_spec( + tune_data, tune_sample_split, batch_size + ) + self._optimization_tuning(self._mode, tune_data, batch_size) + + def _validate_spec(self, specs): + specs = to_list(specs) + self._k_steps = self._strategy.gradient_merge.k_steps + if specs is not None: + for i, spec in enumerate(specs): + if not isinstance(spec, InputSpec): + raise TypeError( + "'spec' must be object of class `paddle.static.InputSpec`." + ) + if spec.name is None: + raise ValueError( + "Requires Input[{}].name != None, but receive `None` with {}.".format( + i, spec + ) + ) + if self._k_steps > 1: + shape = list(spec.shape) + assert ( + shape[0] % self._k_steps == 0 + ), "Requires batch_size[{}] to be divisible by k_steps[{}].".format( + spec.shape[0], self._k_steps + ) + shape[0] //= self._k_steps + spec.shape = shape + return specs or [] + + def _validate_vars(self, vars): + vars = to_list(vars) + if vars is not None: + for i, var in enumerate(vars): + if not isinstance(var, Variable): + raise TypeError("'var' must be a `Variable`.") + return vars or [] + + def _is_local_var(self, var): + var_name = _to_name_str(var) + return var_name in self.main_program.global_block().vars + + def _set_recompute_ckpts(self): + # NOTE hack to enable recompute in engine api for GPT-3 + # TODO support more PaddleNLP/CV models here + + recompute = self._strategy.recompute + + # extract ckpts by specific model + if isinstance(self._model, paddle.nn.Layer): + if hasattr( + self._model, "gpt" + ) and self._model.__class__.__name__ in [ + 'GPTForPretraining', + 'GPTForPretrainingAuto', + ]: + exact_ckpts = self._model.gpt.checkpoints + else: + exact_ckpts = recompute.checkpoints + else: + exact_ckpts = recompute.checkpoints + + # modify strategy + if recompute.enable: + recompute.checkpoints = exact_ckpts[:] + logs = { + 'Model Class': self._model.__class__.__name__, + 'Applied Recompute ckpts': exact_ckpts, + } + self._logger.info(logs) + + def _reset_metrics(self): + for metric in self._metrics: + metric.reset() + + def _metrics_name(self): + metrics_name = ['loss'] if self._loss else [] + for m in self._metrics: + metrics_name.extend(to_list(m.name())) + return metrics_name + + def _switch_mode(self, mode): + assert ( + mode in self._dist_main_progs + ), "{} model is not ready, please call `prepare()` first.".format(mode) + self.to_mode(mode) + self._optimizer = self._dist_contexts[mode]._serial_optimizer + + def to_mode(self, mode): + assert mode in [ + "train", + "eval", + "predict", + ], "mode {} should be one of ['train', 'eval', 'predict']".format(mode) + self._mode = mode + + def _set_state_dict(self, mode, strict, state_dict, dist_attr): + program = self._dist_main_progs[mode][self._cur_rank] + dist_context = self._dist_contexts[mode] + cur_dist_attr = get_dist_attr(program, dist_context) + converter = Converter(state_dict, dist_attr, cur_dist_attr) + state_dict = converter.convert(strict=strict) + program.set_state_dict(state_dict) + + def save(self, path, training=True): + """ + Saves the model, parameters, optimizer state to path. + If `training` is set to False, only inference model will be saved. + + Args: + path (str): The file prefix to save model. The format + is 'dirname/file_prefix' or 'file_prefix'. if empty str. + A exception will be raised. + training (bool, optional): Whether to save for training. If not, save + for inference only. If `training` is set to True, the optimizer state + will be saved. Otherwise, only the model and parameters are saved. + This function will silently overwrite existing file at the target + location. Default: True. + + Returns: + None + + Examples: + + .. code-block:: python + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + + model = paddle.vision.models.LeNet() + loss = paddle.nn.CrossEntropyLoss() + optimizer = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + metrics = paddle.metric.Accuracy(topk=(1, 2)) + + engine = auto.Engine(model, loss, optimizer, metrics) + engine.fit(train_dataset, + epochs=1, + batch_size=64) + engine.save("./my_model") + + """ + if training: + assert self._mode in self._serial_main_progs + serial_program = self._serial_main_progs[self._mode] + dist_main_prog = self._dist_main_progs[self._mode][self._cur_rank] + dist_context = self._dist_contexts[self._mode] + self._saver.save( + path, + serial_program=serial_program, + dist_main_program=dist_main_prog, + dist_context=dist_context, + ) + else: + assert "predict" in self._dist_main_progs + feed_vars = self._feed_vars["predict"]['inputs'] + fetch_vars = self._fetch_vars["predict"]['outputs'] + dist_main_prog = self._dist_main_progs["predict"][self._cur_rank] + self._saver.save_inference_model( + path, + feed_vars, + fetch_vars, + self._executor, + program=dist_main_prog, + ) + + def load(self, path, strict=True, load_optimizer=True): + """ + Load the stored model, parameters and optimizer states. + + Args: + path (str): The prefix of files storing the model states and + optimizer states. + strict (bool, optional): Whether to skip the loading of mismatch + parameter or raise an error when mismatch happens (not found + the parameter in file storing model states of or receives a + mismatch shape). Default: True. + load_optimizer (bool, optional): If True, the stored optimizer + states is restored. Otherwise, the optimizer states is initialized + from scratch. Default: True. + + Returns: + None + + Examples: + + .. code-block:: python + import paddle + import paddle.vision.transforms as T + from paddle.distributed.fleet import auto + from paddle.vision.datasets import MNIST + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + + model = paddle.vision.models.LeNet() + loss = paddle.nn.CrossEntropyLoss() + optimizer = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + metrics = paddle.metric.Accuracy(topk=(1, 2)) + + engine = auto.Engine(model, loss, optimizer, metrics) + engine.fit(train_dataset, + epochs=1, + batch_size=64) + engine.save("./my_model") + engine.load("./my_model") + + """ + self._strict = strict + self._state_dict, self._dist_attr = self._saver.load( + path, load_optimizer + ) + return self._state_dict, self._dist_attr + + def cost(self, inputs_spec=None, labels_spec=None, mode=None): + """ + Get and Print cost, including memory of every rank, + max memory among all ranks, and the global cost of one step based on + communication cost(computation cost is 0 by default). + In the future, the flops information of every rank and global cost including + computation cost will be added. + + Args: + inputs_spec(InputSpec): The specification of inputs. Default: None. + labels_spec(InputSpec): The specification of labels. Default: None. + mode (str): The engine mode must be in ["train", "predict", "eval"]. Default: None. + + Returns: + Return the global execution time (ms) and max memory (B). + + """ + # Check parallel mode + if self._strategy.auto_mode == "full": + self._logger.info( + "The cost will be calcudated in the search process when the auto mode is full." + ) + return + + # Check mode + mode = mode if mode is not None else self._mode + assert mode is not None, "Please set mode." + if mode not in self._has_prepared: + raise ValueError( + "The mode {} is not in accepted modes {}".format( + mode, list(self._has_prepared.keys()) + ) + ) + self.to_mode(mode) + + if inputs_spec is not None and not self._has_prepared[mode]: + self._inputs_spec = self._validate_spec(inputs_spec) + self._labels_spec = self._validate_spec(labels_spec) + self._build(mode) + self._plan(mode) + else: + if _non_static_mode() or self._dygraph_mode: + raise ValueError( + "Please call `prepare()` or `fit()` or `evaluate()` or `predict()` before calling `cost()`." + ) + else: + self._logger.info( + "The program whose cost to be estimated must be static default program. Otherwise, please call `prepare()`before calling `cost()`." + ) + program = paddle.static.default_main_program() + if ( + not program.global_block().ops + or not program.global_block().ops + ) and not self._has_prepared[mode]: + raise ValueError( + "Please call `prepare()` or `fit()` or `evaluate()` or `predict()` before calling `cost()`." + ) + + # Estimate the exec cost and max memory + global_cost, max_memory = get_cost_from_engine(self, mode) + + return global_cost.time, max_memory + + @property + def main_program(self): + return self._dist_main_progs[self._mode][self._cur_rank] + + @property + def startup_program(self): + return self._dist_startup_progs[self._mode][self._cur_rank] + + @property + def dist_context(self): + return self._dist_contexts[self._mode] + + @property + def serial_main_program(self): + return self._serial_main_progs[self._mode] + + @property + def serial_startup_program(self): + return self._serial_startup_progs[self._mode] + + @property + def fetch_vars(self): + return self._fetch_vars[self._mode] + + @property + def inputs(self): + return self._inputs + + @property + def labels(self): + return self._labels diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/graph.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..de6505071abfe1501b72bbc4591c684b77fe1a4e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/graph.py @@ -0,0 +1,175 @@ +# Copyright (c) 2021 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 + + +class Node: + + def __init__(self, id, **attrs): + # Each node must has a unique id + self._id = id + # Attributes for Node + self._attrs = {} + self._attrs.update(attrs) + + @property + def id(self): + return self._id + + @property + def attrs(self): + return self._attrs + + def __getitem__(self, attr_name): + return self._attrs[attr_name] + + def __setitem__(self, attr_name, attr_value): + self._attrs[attr_name] = attr_value + + def __contains__(self, attr_name): + try: + return attr_name in self._attrs + except TypeError: + return False + + def __str__(self): + str = "(id: {}, attrs: {})".format(self.id, self.attrs) + return str + + +class Edge: + + def __init__(self, src_id, tgt_id, **attrs): + # The id of source node in an Edge + self._src_id = src_id + # The id of target node in an Edge + self._tgt_id = tgt_id + # Attributes for Edge + self._attrs = {} + self._attrs.update(attrs) + + @property + def src_id(self): + return self._src_id + + @property + def tgt_id(self): + return self._tgt_id + + @property + def attrs(self): + return self._attrs + + def __getitem__(self, attr_name): + return self._attrs[attr_name] + + def __setitem__(self, attr_name, attr_value): + self._attrs[attr_name] = attr_value + + def __contains__(self, attr_name): + try: + return attr_name in self._attrs + except TypeError: + return False + + def __str__(self): + str = "" + str += "(src_id: {}, tgt_id: {}, attrs: {})".format( + self.src_id, self.tgt_id, self._attrs) + return str + + +class Graph: + + def __init__(self, **attrs): + # _nodes is dict for storing the nodes of the graph. + # The key of this dict is the node id. + self._nodes = {} + # _adjs is a dict of dict for storing the adjacency of the graph. + # The key of the outer dict is the node id of the source node and + # the key of the inner dict is the node id of the target node. + self._adjs = {} + # Attributes for Graph + self._attrs = {} + self._attrs.update(attrs) + + @property + def nodes(self): + return self._nodes + + @property + def attrs(self): + return self._attrs + + @property + def adjs(self): + return self._adjs + + def add_node(self, node_id, **attrs): + if node_id is None: + raise ValueError("None cannot be a node") + if node_id not in self._nodes: + node = Node(node_id, **attrs) + self._nodes[node_id] = node + self._adjs[node_id] = {} + else: + self._nodes[node_id].attrs.update(attrs) + + def add_edge(self, src_id, tgt_id, **attrs): + # add nodes + if src_id is None: + raise ValueError("None cannot be a node") + if tgt_id is None: + raise ValueError("None cannot be a node") + if src_id not in self._nodes: + src_node = Node(src_id) + self._nodes[src_id] = src_node + self._adjs[src_id] = {} + if tgt_id not in self._nodes: + tgt_node = Node(tgt_id) + self._nodes[tgt_id] = tgt_node + self._adjs[tgt_id] = {} + # add the edge + edge = Edge(src_id, tgt_id, **attrs) + self._adjs[src_id][tgt_id] = edge + + def __len__(self): + return len(self._nodes) + + def __iter__(self): + return iter(self._nodes.values()) + + def __getitem__(self, node_id): + # Return the adjacency of a node + return self._adjs[node_id] + + def __contains__(self, node_id): + # Check whether a node in the graph + try: + return node_id in self._nodes + except TypeError: + return False + + def __str__(self): + str = "" + str += "**************Nodes**************\n" + for node_id in self.nodes: + str += "{}\n".format(self.nodes[node_id]) + + str += "**************Edges**************\n" + for src_id in self.adjs: + str += "--------------{}--------------\n".format(src_id) + for idx, tgt_id in enumerate(self.adjs[src_id]): + str += "{}\n".format(self.adjs[src_id][tgt_id]) + + return str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..7faa426ed3430cc79da57d2863d98f09e320712b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/helper.py @@ -0,0 +1,367 @@ +# Copyright (c) 2022 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. + +import logging +from collections import defaultdict + +import paddle + +from paddle.nn import Layer +from paddle.jit import to_static, not_to_static +from paddle.fluid.framework import Operator, Parameter, _non_static_mode +from paddle.fluid.framework import program_guard +from paddle.fluid.executor import global_scope +from paddle.fluid.dygraph.dygraph_to_static.program_translator import StaticFunction + +from .utils import to_list +from .utils import get_logger +from .converter import Converter + + +class ProxyLayer(Layer): + """ + ProxyLayer implements all logic for converting dygraph model into + static Program IR. Meanwhile, it provides conviential interfaces for + auto parallel to visit feed/fetch/loss/metric variables. + """ + + def __init__(self, layer, loss_func, metrics): + super(ProxyLayer, self).__init__() + # NOTE: All verify logics are finished in Engine.Prepare + self.inner_layer = layer + self.loss_func = loss_func + self.metrics = metrics + # train / eval / predict + self.mode = None + + # generated program vars + self._input_vars = defaultdict(list) + self._label_vars = defaultdict(list) + self._output_vars = defaultdict(list) + self._loss_vars = defaultdict(list) + self._metric_vars = defaultdict(list) + + def _train(self, inputs, labels): + """ + Train process of inner_layer with forward/loss/metric logic. + """ + # step 1. save feed variables of Program + mode = 'train' + self._input_vars[mode] = inputs + self._label_vars[mode] = labels + + # step 2. call inner_layer.forward + self._output_vars[mode] = self.inner_layer(*inputs) + + # step 3. calculate loss if needed + new_inputs = self._prepare(self.output_vars, labels) + self._loss_vars[mode] = self.call_loss(new_inputs) + + # step 4. calculate metrics if needed + self._metric_vars[mode] = self.call_metrics(new_inputs) + + def _eval(self, inputs, labels): + """ + Evaluate process of inner_layer with forward/loss/metric logic. + """ + # TODO(dev): we can reuse codes with self._train after making + # sure if they can. + + # step 1. save feed variables of Program + mode = 'eval' + self._input_vars[mode] = inputs + self._label_vars[mode] = labels + + # step 2. call inner_layer.forward + self._output_vars[mode] = self.inner_layer(*inputs) + + # step 3. calculate loss if needed + new_inputs = self._prepare(self.output_vars, labels) + self._loss_vars[mode] = self.call_loss(new_inputs) + + # step 4. calculate metrics if needed + self._metric_vars[mode] = self.call_metrics(new_inputs) + + def _predict(self, inputs, labels): + """ + Predict process of inner_layer with forward logic. + """ + # step 1. save feed variables of Program + mode = 'predict' + self._input_vars[mode] = inputs + self._label_vars[mode] = labels + + # step 2. call inner_layer.forward + self._output_vars[mode] = self.inner_layer(*inputs) + + @not_to_static + def _prepare(self, outputs, labels): + """ + Concat outputs and labels as a single list + + NOTE(dev): We use @not_to_static to avoid AST Analysis. + """ + return to_list(outputs) + to_list(labels) + + def call_loss(self, inputs): + """ + Apply Loss Function on outputs and labels. + + Args: + inputs: List[Variable] + + Returns: List[Variable] + """ + res = [] + if self.loss_func is not None: + res = self.loss_func(*inputs) + return res + + def call_metrics(self, inputs): + """ + Apply Metrics Function on outputs and labels. + + Args: + inputs: List[Variable] + + Returns: List[Variable] + """ + outs = [] + for metric in self.metrics: + outs.append(to_list(metric.compute(*inputs))) + + return outs + + def set_mode(self, mode): + self.mode = mode + self.training = mode == 'train' + + def clone(self): + return ProxyLayer(self.inner_layer, self.loss_func, self.metrics) + + @property + def input_vars(self): + return self._input_vars[self.mode] + + @property + def label_vars(self): + return self._label_vars[self.mode] + + @property + def output_vars(self): + return self._output_vars[self.mode] + + @property + def loss_vars(self): + return self._loss_vars[self.mode] + + @property + def metric_vars(self): + return self._metric_vars[self.mode] + + @property + def startup_program(self): + return self.inner_layer._startup_program() + + +class BuildInfo: + + def __init__(self): + self.clear() + + def has_cache(self, mode, update=False): + is_cache = self.states[mode] + if update: + self.cache(mode) + return is_cache + + def cache(self, mode): + self.states[mode] = True + + def clear(self): + self.states = defaultdict(bool) + + +class ProgramHelper(object): + """ + A Helper class for Engine to provides different Program IR according specified 'mode'. + """ + + def __init__(self, layer, loss_func, metrics, inputs_spec, labels_spec): + # original model config information + # TODO(Aurelius84): Implenet append_backward and optimizer in ProxyLayer + # after distribute engine satisify basic condition. + self.proxy_layer = ProxyLayer(layer, loss_func, metrics) + self.inputs_spec = inputs_spec + self.labels_spec = labels_spec + + self.build_info = BuildInfo() + self._logger = get_logger(logging.INFO) + self.lazy_init = False + + def reset(self): + """ + Reset all state of current Object. + """ + self.build_info.clear() + self.proxy_layer = self.proxy_layer.clone() + + def build_program(self, mode): + """ + Convert dygraph model into static Program IR. + """ + assert mode in ['train', 'eval', 'predict'] + self.proxy_layer.set_mode(mode) + # skip if we has already built program. + if self.build_info.has_cache(mode, True): + self._logger.info( + "Already build program with mode = %s, use cached program." % + mode) + return + + self._logger.info("start to build program for mode = %s." % mode) + input_spec = [self.inputs_spec, self.labels_spec] + static_func = to_static(self.static_func(), input_spec=input_spec) + + func_name = '_' + mode + setattr(self.proxy_layer, func_name, static_func) + + # NOTE(dev): Because @to_static is a Lazy mechanism, so we explicitly call this to trigger + # generating Program IR immediately. + getattr(self.proxy_layer, func_name).concrete_program + + self._build_startup_program() + + def _build_startup_program(self): + """ + Create and Sync parameters into startup program. + """ + if len(self.startup_program.global_block().ops) > 1: + self.lazy_init = True + return + for param in self.concrete_program.parameters: + Parameter(name=param.name, + desc=param, + type=param.type, + shape=param.shape, + dtype=param.dtype, + stop_gradient=param.stop_gradient, + block=self.startup_program.global_block()) + + def apply_optimizer(self, optimizer): + """ + Append backward and generate optimizer operations. + """ + self._verify_optimizer(optimizer) + self._logger.info("start to apply optimizer: %s ", + type(optimizer).__name__) + # clear optimizer parameters + original_params = optimizer._parameter_list + optimizer._parameter_list = None + with program_guard(self.main_program, self.startup_program): + res = optimizer.minimize(self.loss_vars[0]) + + # restore optimizer parameters + optimizer._parameter_list = original_params + return res + + def _verify_optimizer(self, optimizer): + assert optimizer is not None + assert hasattr(optimizer, + "minimize"), "Optimizer must have minimize() method." + assert self.proxy_layer.mode == 'train', "Required mode == 'train', but received '%s'" % self.proxy_layer.mode + assert len( + self.loss_vars + ) == 1, "Required len(loss_vars) == 1, but received len(loss_vars) = %s" % len( + self.loss_vars) + + def to(self, mode): + """ + Switch underly proxy layer mode into target mode. + """ + assert mode in ['train', 'eval', 'predict'] + func = getattr(self.proxy_layer, '_' + mode) + assert isinstance( + func, StaticFunction), "Please call build_program(mode) firstly." + self.proxy_layer.set_mode(mode) + + def static_func(self): + """ + Return StaticFunction instance with underly target mode. + """ + assert self.proxy_layer.mode in [ + 'train', 'eval', 'predict' + ], "Please call build_program(mode) firstly." + func_name = '_' + self.proxy_layer.mode + return getattr(self.proxy_layer, func_name) + + def init(self, main_program, place, dist_context): + if self.lazy_init: + return + for param in self.concrete_program.parameters: + # create var in scope and share parameters to scope + if param.name not in main_program.global_block().vars: + continue + # get param_var's dist_attr + var = main_program.global_block().vars[param.name] + var_dist_attr = dist_context.get_tensor_dist_attr_for_program(var) + dist_attr = { + "dims_mapping": var_dist_attr.dims_mapping, + "process_shape": var_dist_attr.process_mesh.topology, + "process_group": var_dist_attr.process_mesh.processes + } + # slice param_value with dist_attr + # share sliced_param_value with param_tensor in global_scope + param_tensor = global_scope().var(param.name).get_tensor() + sliced_param = Converter.slice_with_dist_attr( + param.numpy(), dist_attr) + param_tensor.set(sliced_param, place) + + @property + def concrete_program(self): + return self.static_func().concrete_program + + @property + def main_program(self): + return self.concrete_program.main_program + + @property + def startup_program(self): + try: + return self.proxy_layer.startup_program + except Exception as err: + self._logger.warning("`lazy init` failed.") + if isinstance(err, AssertionError): + return self.concrete_program.startup_program + raise err + + @property + def input_vars(self): + return to_list(self.proxy_layer.input_vars) + + @property + def output_vars(self): + return to_list(self.proxy_layer.output_vars) + + @property + def label_vars(self): + return to_list(self.proxy_layer.label_vars) + + @property + def loss_vars(self): + return to_list(self.proxy_layer.loss_vars) + + @property + def metric_vars(self): + return to_list(self.proxy_layer.metric_vars) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/interface.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..a0dcb488658b8d56ac1bb3d2cadbb685b59a167e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/interface.py @@ -0,0 +1,233 @@ +# Copyright (c) 2021 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. + +from collections import defaultdict + +import paddle +from paddle.fluid import core +from .process_mesh import ProcessMesh +from .process_mesh import get_current_process_mesh +from .process_mesh import set_current_process_mesh +from .process_mesh import reset_current_process_mesh +from .dist_context import get_default_distributed_context +from .dist_tensor import DistributedTensor +from .dist_op import DistributedOperatorHelper +from .utils import verify_shard_spec, convert_to_dims_mapping + + +def shard_tensor(x, process_mesh=None, shard_spec=None): + """ + Shard a tensor on a process mesh according to the shard specification. + + Args: + x (Tensor): the tensor to be sharded. + process_mesh (ProcessMesh, optional): An instance of ProcessMesh describes a mesh + topology of the used logical processes where the tensor is sharded. If it is None, + the found current process mesh will be used. And an error will be raised if the + current process mesh cannot be found. Default: None. + shard_spec (list, optional): a list to describe the sharding mapping between `x` and `process_mesh`, + which means the dimension `i` of `x` is split across the dimension `shard_spec[i]` of `process_mesh`, + where `None` means that tensor dimension is not split. For example, given a tensor wih + the shape [6, 12] and a process mesh with the shape [2, 3] and the dimension names ["x", "y"]: + If `shard_spec=["x", "y"]`, each shard of the tensor will have a shape [3, 4]; + If `shard_spec=["y", "x"]`, each shard of the tensor will have a shape [2, 6]; + If `shard_spec=["x", None]`, each shard of the tensor will have a shape [3, 12]; + If `shard_spec=[None, "x"]`, each shard of the tensor will have a shape [6, 4]; + If `shard_spec=["y", None]`, each shard of the tensor will have a shape [2, 12]; + If `shard_spec=[None, "y"]`, each shard of the tensor will have a shape [6, 4]; + If `shard_spec=[None, None]`, each shard of the tensor will have a shape [6, 12]; + If the `shard_spec` is None, the tensor will be replicated across all the processes of `process_mesh`. + In the above example, the `shard_spec=None` is same as 'shard_spec=[None, None]'. Defaults: None. + + Returns: + Tensor: the tensor `x` annotated with sharding information. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed.fleet import auto + + mesh = auto.ProcessMesh([[0, 1], [2, 3]], dim_names=["x", "y"]) + x = paddle.ones([4, 6]) + shard_spec = ["x", "y"] + auto.shard_tensor(x, mesh, shard_spec) + + """ + + if process_mesh is not None: + assert isinstance(process_mesh, ProcessMesh), \ + "Argument process_mesh {} is not an instance of ProcessMesh".format(process_mesh) + else: + process_mesh = get_current_process_mesh() + assert process_mesh is not None, \ + "Specify the process mesh argument or use ProcessMesh context manager first." + assert isinstance(shard_spec, list), \ + "Argument shard_spec {} is not an instance of list".format(shard_spec) + dist_tensor = DistributedTensor(x) + serial_tensor = dist_tensor.serial_tensor + dist_tensor.dist_attr.process_mesh = process_mesh + if serial_tensor.type == core.VarDesc.VarType.READER \ + or serial_tensor.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY \ + or serial_tensor.type == core.VarDesc.VarType.STEP_SCOPES: + tensor_shape = [] + else: + tensor_shape = serial_tensor.shape + if shard_spec is not None: + assert verify_shard_spec(shard_spec, tensor_shape, process_mesh), \ + "For tensor {}, shard_spec {} is invalid with tensor_shape {} and process_mesh {}.".format( + serial_tensor.name, shard_spec, tensor_shape, process_mesh) + dist_tensor.dist_attr.dims_mapping = convert_to_dims_mapping( + shard_spec, process_mesh) + if process_mesh is not None: + dist_tensor.dist_attr.mark_annotated("process_mesh") + if shard_spec is not None: + dist_tensor.dist_attr.mark_annotated("dims_mapping") + default_dist_ctx = get_default_distributed_context() + default_dist_ctx.add_dist_tensor_for_program(dist_tensor) + dist_tensor = default_dist_ctx.get_dist_tensor_for_program(x) + return x + + +def shard_op(op, process_mesh=None, in_shard_specs=None, out_shard_specs=None): + """ + Shard an operation on a process mesh according to its input and output shard specification. + + Args: + op (Callable): a callable operator or module to be sharded. + process_mesh (ProcessMesh, optional): An instance of ProcessMesh describes a mesh + topology of the used logical processes where the op is sharded. All of its inputs and + outputs are sharded by this process mesh. If it is None, the found current process mesh + will be used. And an error will be raised if the current process mesh cannot be found. + Default: None. + in_shard_specs (list of list, optional): a list of list to describe the sharding specifications + for the inputs. Each item of `in_shard_specs` is a `shard_spec` between the correspoinding input + and `process_mesh`. If one item is None, the cooresponding input is replicated across all processes + If it is None, all inputs are replicated accross all processes. Note that the lenght of the + `in_shard_specs` should be equal to the actual number of inputs when calling this operation. + Default: None. + out_shard_specs (list of list, optional): a list of list to describe the sharding specifications + for the outputs. Each item of `out_shard_specs` is a `shard_spec` between the correspoinding output + and `process_mesh`. If one item is None, the cooresponding output is replicated across all processes + If it is None, all outputs are replicated accross all processes. Note that the lenght of the + `in_shard_specs` should be equal to the actual number of inputs when calling this operation. + Default: None. Default: None. + + Returns: + Outputs of `op`, each of which is annotated with sharding information. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed.fleet import auto + + x = paddle.ones([4, 6]) + y = paddle.zeros([4, 6]) + mesh = auto.ProcessMesh([[0, 1], [2, 3]], dim_names=["x", "y"]) + dist_add = auto.shard_op(paddle.add, + in_shard_specs=[["x", "y"], ["y", None]], + out_shard_specs=[[None, "x"]]) + dist_add(x, y) + + """ + + if process_mesh is not None: + assert isinstance(process_mesh, ProcessMesh), \ + "Argument process_mesh {} is not an instance of ProcessMesh".format(process_mesh) + else: + process_mesh = get_current_process_mesh() + assert process_mesh is not None, \ + "Specify the process mesh argument or use ProcessMesh context manager first." + in_dims_mappings = [] + if in_shard_specs is not None: + assert all((isinstance(shard_spec, list) or shard_spec is None) for shard_spec in in_shard_specs), \ + "in_shard_spec {} is not a list of list or None".format(in_shard_specs) + for shard_spec in in_shard_specs: + if shard_spec is not None: + in_dims_mappings.append( + convert_to_dims_mapping(shard_spec, process_mesh)) + else: + in_dims_mappings.append(None) + out_dims_mappings = [] + if out_shard_specs is not None: + assert all((isinstance(shard_spec, list) or shard_spec is None) for shard_spec in out_shard_specs), \ + "out_shard_spec {} is not a list of list or None".format(out_shard_specs) + for shard_spec in out_shard_specs: + if shard_spec is not None: + out_dims_mappings.append( + convert_to_dims_mapping(shard_spec, process_mesh)) + else: + out_dims_mappings.append(None) + op = DistributedOperatorHelper(op, process_mesh, in_dims_mappings, + out_dims_mappings) + return op + + +def recompute(op): + + class RecomputeOperator: + + def __init__(self, op): + self._op = op + + def __call__(self, *args, **kwargs): + default_prog = paddle.fluid.default_main_program() + cur_block = default_prog.current_block() + op_size = len(cur_block.ops) + output = self._op(*args, **kwargs) + new_op_size = len(cur_block.ops) + + for idx in range(op_size, new_op_size): + op = cur_block.ops[idx] + op._set_attr("is_recompute@auto_parallel", True) + + return output + + return RecomputeOperator(op) + + +_g_collections = {} + + +class CollectionNames(object): + FETCHES = "fetches" + LOGGING = "logging" + + +def get_collection(name): + collection = _g_collections.get(name, None) + if collection is None: + collection = [] + _g_collections[name] = collection + return _g_collections[name] + + +def add_to_collection(collection_name, value, name=None): + if collection_name not in _g_collections: + _g_collections[collection_name] = [] + if name is not None: + for _, v in _g_collections[collection_name]: + if v == value: return + _g_collections[collection_name].append((name, value)) + else: + for _, v in _g_collections[collection_name]: + if v == value: return + _g_collections[collection_name].append((None, value)) + + +def fetch(tensor, name=None, logging=False): + add_to_collection(CollectionNames.FETCHES, tensor, name) + if logging: + add_to_collection(CollectionNames.LOGGING, tensor, name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/mapper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..da76ae8127192c8839a5eac8887dd12906bcec4d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/mapper.py @@ -0,0 +1,306 @@ +# Copyright (c) 2021 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 + +import os +import operator +import functools +import json +import paddle +from collections import deque +from .graph import Node +from .graph import Edge +from .graph import Graph +from .cluster import DeviceType +from .process_group import get_process_group + + +def is_collective_comm_op(op): + comm_list = [ + "c_allreduce_sum", "c_allreduce_min", "c_allreduce_max", + "c_allreduce_prod", "c_reduce_sum", "c_reduce_min", "c_reduce_max", + "c_reduce_prod", "c_broadcast", "c_allgather" + ] + if op.type in comm_list: + return True + else: + return False + + +def is_p2p_comm_op(op): + comm_list = ["send_v2", "recv_v2"] + if op.type in comm_list: + return True + else: + return False + + +def get_dtype_bytes(dtype): + num_bytes = 0 + if dtype == paddle.float64: + num_bytes = 8 + elif dtype == paddle.float32: + num_bytes = 4 + elif dtype == paddle.float16: + num_bytes = 2 + elif dtype == paddle.bfloat16: + num_bytes = 2 + elif dtype == paddle.int64: + num_bytes = 8 + elif dtype == paddle.int32: + num_bytes = 4 + elif dtype == paddle.int16: + num_bytes = 2 + elif dtype == paddle.int8: + num_bytes = 1 + elif dtype == paddle.uint8: + num_bytes = 1 + else: + raise ValueError("Unrecognized dtype {}.".format(dtype)) + return num_bytes + + +def get_comm_volume(comm_op, src_rank, tgt_rank): + comm_volume = None + if src_rank == tgt_rank: + return comm_volume + comm_op_type = comm_op.type + if comm_op_type != "recv_v2": + tensor_name = comm_op.input_arg_names[0] + else: + tensor_name = comm_op.output_arg_names[0] + tensor = comm_op.block._find_var_recursive(tensor_name) + assert tensor is not None + tensor_shape = tensor.shape + # Skip the batch dim + new_tensor_shape = [] + for val in tensor_shape: + if val == -1: + print("Warning: -1 in the tensor shape.") + new_tensor_shape.append(1) + else: + new_tensor_shape.append(val) + tensor_size = functools.reduce(operator.mul, new_tensor_shape, 1) + tensor_bytes = tensor_size * get_dtype_bytes(tensor.dtype) + if "c_allreduce" in comm_op_type: + comm_volume = 2 * tensor_bytes + elif "c_allgather" in comm_op_type: + comm_volume = tensor_bytes + elif "c_broadcast" in comm_op_type: + if comm_op.attr("root") == src_rank: + comm_volume = tensor_bytes + else: + comm_volume = None + elif "c_reduce" in comm_op_type: + if comm_op.attr("root_id") == src_rank: + comm_volume = None + else: + comm_volume = tensor_bytes + elif "send_v2" in comm_op_type: + if comm_op.attr("peer") == tgt_rank: + comm_volume = tensor_bytes + else: + comm_volume = None + elif "recv_v2" in comm_op_type: + comm_volume = None + else: + raise ValueError("Unrecognized communication operator.") + return comm_volume + + +def analyze_comm_requirements_from_op(op, rank, g_process_group_map): + comm_requirements_to_ranks = {} + if is_collective_comm_op(op): + process_group_id = op.attr("ring_id") + process_group = get_process_group(process_group_id, g_process_group_map) + if rank not in process_group.ranks: + return comm_requirements_to_ranks + for tgt_rank in process_group.ranks: + comm_volume = get_comm_volume(op, rank, tgt_rank) + if comm_volume is not None: + comm_requirements_to_ranks[tgt_rank] = {} + comm_requirements_to_ranks[tgt_rank][ + "comm_volume"] = comm_volume + elif is_p2p_comm_op(op): + tgt_rank = op.attr("peer") + comm_volume = get_comm_volume(op, rank, tgt_rank) + if comm_volume is not None: + comm_requirements_to_ranks[tgt_rank] = {} + comm_requirements_to_ranks[tgt_rank]["comm_volume"] = comm_volume + else: + comm_requirements_to_ranks = {} + return comm_requirements_to_ranks + + +def analyze_requirements_for_program(src_info, rank): + program = src_info[0] + g_process_group_map = src_info[1] + resource_requirements = {} + comm_requirements_to_ranks = {} + # only support device_type and only support GPU for now + resource_requirements["device_type"] = DeviceType.GPU + for block in program.blocks: + for op in block.ops: + cur_comm_requirements_to_ranks = analyze_comm_requirements_from_op( + op, rank, g_process_group_map) + for tgt_rank, link_info in cur_comm_requirements_to_ranks.items(): + if tgt_rank in comm_requirements_to_ranks: + comm_requirements_to_ranks[tgt_rank][ + "comm_volume"] += link_info["comm_volume"] + else: + comm_requirements_to_ranks[tgt_rank] = {} + comm_requirements_to_ranks[tgt_rank][ + "comm_volume"] = link_info["comm_volume"] + return resource_requirements, comm_requirements_to_ranks + + +def build_process_graph(distributed_program): + graph = Graph() + for src_rank, src_info in distributed_program.items(): + resource_requirements, comm_requirements_to_ranks = analyze_requirements_for_program( + src_info, src_rank) + graph.add_node(src_rank, resource_requirements=resource_requirements) + for tgt_rank, comm_requirements in comm_requirements_to_ranks.items(): + graph.add_edge(src_rank, + tgt_rank, + comm_requirements=comm_requirements) + return graph + + +def build_cluster_graph(cluster): + graph = Graph() + cuda_visible_devices_env = os.getenv("CUDA_VISIBLE_DEVICES") + cuda_visible_devices = [] + if cuda_visible_devices_env is not None and cuda_visible_devices_env != "": + cuda_visible_devices = [ + int(d.strip()) for d in cuda_visible_devices_env.split(",") + ] + for machine in cluster.machines.values(): + for device in machine.devices.values(): + graph.add_node(device.global_id, device=device) + if cuda_visible_devices and device.local_id not in cuda_visible_devices: + graph.nodes[device.global_id]["occupied"] = True + else: + graph.nodes[device.global_id]["occupied"] = False + for link in machine.links.values(): + graph.add_edge(link.source.global_id, + link.target.global_id, + link=link) + return graph + + +def mapping(distributed_program, cluster): + # A very simple mapping algorithm only for GPUs. + # Here we assume one process will be mapped to one GPU. + # In the future, more mapping configurations and algorithms will be supported. + process_graph = build_process_graph(distributed_program) + + cluster_graph = build_cluster_graph(cluster) + + for cur_rank_node in process_graph: + cur_rank_node["visited"] = False + + def sort_by_comm_volume(rank_edge): + return rank_edge["comm_requirements"]["comm_volume"] + + def sort_by_comm_bandwidth(device_edge): + return device_edge["link"].bandwidth + + def select_unvisited_rank_node(rank_node_list): + selected_rank_node = None + for rank_node in rank_node_list: + if rank_node["visited"] is False: + selected_rank_node = rank_node + return selected_rank_node + + queue = deque() + root_rank_node = select_unvisited_rank_node( + list(process_graph.nodes.values())) + while root_rank_node is not None: + queue.append(root_rank_node) + while queue: + cur_rank_node = queue.popleft() + if cur_rank_node["visited"]: + continue + device_type = cur_rank_node["resource_requirements"]["device_type"] + cur_device_node = None + for device_node in cluster_graph.nodes.values(): + if (device_node["device"].type + == device_type) and (not device_node["occupied"]): + device_node["occupied"] = True + cur_rank_node["visited"] = True + cur_rank_node["device"] = device_node["device"] + cur_device_node = device_node + break + assert cur_device_node, "Cannot find a device to satisfy the requirement." + + nbr_rank_edges = [] + for nbr_rank_node_id, nbr_rank_edge in process_graph.adjs[ + cur_rank_node.id].items(): + assert nbr_rank_edge.src_id == cur_rank_node.id and nbr_rank_edge.tgt_id == nbr_rank_node_id + queue.append(process_graph.nodes[nbr_rank_node_id]) + nbr_rank_edges.append(nbr_rank_edge) + nbr_rank_edges.sort(key=sort_by_comm_volume) + + nbr_device_edges = [] + for nbr_device_edge in cluster_graph.adjs[ + cur_device_node.id].values(): + nbr_device_edges.append(nbr_device_edge) + nbr_device_edges.sort(key=sort_by_comm_bandwidth) + + for nbr_rank_edge in nbr_rank_edges: + src_rank_node = process_graph.nodes[ + nbr_rank_edge.src_id]["visited"] + if src_rank_node: + continue + device_type = src_rank_node["resource_requirements"][ + "device_type"] + nbr_rank_node = process_graph.nodes[nbr_rank_edge.tgt_id] + for nbr_device_edge in nbr_device_edges: + nbr_device_node = cluster_graph.nodes[ + nbr_device_edge.tgt_id] + if (nbr_device_node["device"].type == device_type) and ( + not nbr_device_node["occupied"]): + nbr_device_node["occupied"] = True + nbr_rank_node["visited"] = True + nbr_rank_node["device"] = nbr_device_node["device"] + break + root_rank_node = select_unvisited_rank_node( + list(process_graph.nodes.values())) + + rank_mapping = {} + for rank, rank_node in process_graph.nodes.items(): + device = rank_node["device"] + machine = device.machine + if machine.id in rank_mapping: + rank_mapping[machine.id]["hostname"] = machine.hostname + rank_mapping[machine.id]["addr"] = machine.addr + rank_mapping[machine.id]["port"] = machine.port + if rank not in rank_mapping[machine.id]["ranks"]: + rank_mapping[machine.id]["ranks"][rank] = [] + rank_mapping[machine.id]["ranks"][rank].append(device.local_id) + else: + rank_mapping[machine.id]["ranks"][rank].append(device.local_id) + else: + rank_mapping[machine.id] = {} + rank_mapping[machine.id]["hostname"] = machine.hostname + rank_mapping[machine.id]["addr"] = machine.addr + rank_mapping[machine.id]["port"] = machine.port + rank_mapping[machine.id]["ranks"] = {} + rank_mapping[machine.id]["ranks"][rank] = [] + rank_mapping[machine.id]["ranks"][rank].append(device.local_id) + for machine_mapping in rank_mapping.values(): + for rank_devices in machine_mapping["ranks"].values(): + rank_devices.sort() + + return rank_mapping diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0a05a4f1cd4cadba41df1aa220af8c2bdf8fd1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .common import find_compatible_distributed_operator_impls +from . import dist_embedding +from . import dist_matmul +from . import dist_reshape +from . import dist_softmax +from . import dist_transpose +from . import dist_default +from . import dist_eltwise +from . import dist_check_finite_and_unscale +from . import dist_update_loss_scaling +from . import dist_split +from . import dist_fill_constant_batch_size_like +from . import dist_pnorm +from . import dist_slice +from . import dist_fused_feedforward +from . import dist_fused_attention +from . import dist_reduce_sum_p +from . import dist_shape +from . import dist_assign diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/common.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e7ad1e0ea268d7faf2a1d0ac6fe67ae1c0e24f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/common.py @@ -0,0 +1,462 @@ +# Copyright (c) 2021 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 + +import abc +import paddle +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..dist_attribute import OperatorDistributedAttribute +from ..utils import _get_comm_group, _get_corresponding_rank, is_optimize_op +from ..process_group import new_process_group + +_g_distributed_operator_impl_containers = {} + +_g_elementwise_ops = [ + "elementwise", "gelu", "dropout", "cast", "gather", "concat", + "fused_softmax_mask_upper_triangle" +] +BACKWARD_ONLY_DIST_OPS = {'check_finite_and_unscale', 'update_loss_scaling'} + + +class ParallelMode(): + """ + the parallel mode for communication or auxiliary operator + """ + DataParallel = "auto_parallel/data_parallel" + ModelParallel = "auto_parallel/model_parallel" + PipelineParalel = "auto_parallel/pipeline_paralel" + MoEParallel = "auto_parallel/moe_parallel" + + +def is_elementwise_op(op_type): + if op_type in _g_elementwise_ops: + return True + if "elementwise" in op_type: + return True + return False + + +class DistributedOperatorImplContainer: + + def __init__(self, op_type): + self._type = op_type + self._impls = [] + + @property + def type(self): + return self._type + + @type.setter + def type(self, op_type): + self._type = op_type + + @property + def impls(self): + return self._impls + + def register_impl(self, dist_impl): + assert self.type == dist_impl.type, \ + "Op type of container must be same as that of the implementation." + impl_idx = len(self.impls) + dist_impl.idx = impl_idx + self._impls.append(dist_impl) + + def get_impl(self, impl_idx): + return self._impls[impl_idx] + + def get_input_compatible_impls(self, dist_op): + compatible_impls = [] + for impl in self.impls: + if impl.is_input_compatible(dist_op): + compatible_impls.append(impl) + return compatible_impls + + def get_output_compatible_impls(self, dist_op): + compatible_impls = [] + for impl in self.impls: + if impl.is_output_compatible(dist_op): + compatible_impls.append(impl) + return compatible_impls + + def get_compatible_impls(self, dist_op): + compatible_impls = [] + for impl in self.impls: + if impl.is_auto_compatible(dist_op): + compatible_impls.append(impl) + return compatible_impls + + +class DistributedOperatorImpl(abc.ABC): + + def __init__(self, name): + self._name = name + self._type = None + self._idx = None + self._forward_implemented = False + self._backward_implemented = False + + @property + def name(self): + return self._name + + @name.setter + def name(self, name): + self._name = name + + @property + def type(self): + return self._type + + @type.setter + def type(self, op_type): + self._type = op_type + + @property + def idx(self): + return self._idx + + @idx.setter + def idx(self, impl_idx): + self._idx = impl_idx + + @abc.abstractmethod + def is_input_compatible(self, dist_op): + raise NotImplementedError("Please Implement this method in Subclass.") + + @abc.abstractmethod + def is_output_compatible(self, dist_op): + raise NotImplementedError("Please Implement this method in Subclass.") + + @abc.abstractmethod + def is_auto_compatible(self, dist_op): + raise NotImplementedError("Please Implement this method in Subclass.") + + @staticmethod + @abc.abstractmethod + def forward(dist_ctx, *args, **kwargs): + raise NotImplementedError("Please Implement this method in Subclass.") + + @staticmethod + @abc.abstractmethod + def backward(dist_ctx, *grad_outputs, **kwargs): + raise NotImplementedError("Please Implement this method in Subclass.") + + def update_dims_mapping(self, dist_op): + raise NotImplementedError("Please Implement this method in Subclass.") + + +def register_distributed_operator_impl_container(container): + global _g_distributed_operator_impl_containers + _g_distributed_operator_impl_containers[container.type] = container + + +def get_distributed_operator_impl_container(op_type): + global _g_distributed_operator_impl_containers + return _g_distributed_operator_impl_containers.get(op_type, None) + + +def register_distributed_operator_impl(op_type, dist_impl): + dist_op_impl_container = get_distributed_operator_impl_container(op_type) + if dist_op_impl_container is not None: + dist_impl.type = op_type + dist_op_impl_container.register_impl(dist_impl) + else: + assert False, "Must register distributed operator registry first." + + +def find_compatible_distributed_operator_impls(dist_op, fwd=True, partial=True): + """ + Here just return the first compatible implemention. + This will be improved by cost model in the future. + """ + op_type = dist_op.serial_op.type + dist_op_impl_container = get_distributed_operator_impl_container(op_type) + dist_op_eltwise_impl_container = get_distributed_operator_impl_container( + "elementwise") + dist_op_default_impl_container = get_distributed_operator_impl_container( + "default") + compatible_impls = [] + if partial: + if fwd: + # First, find impls in the corresponding container + if dist_op_impl_container: + compatible_impls.extend( + dist_op_impl_container.get_input_compatible_impls(dist_op)) + # Second, find impls in the elementwise container + if dist_op_eltwise_impl_container and is_elementwise_op(op_type): + compatible_impls.extend( + dist_op_eltwise_impl_container.get_input_compatible_impls( + dist_op)) + # Third, find impls in the default container + if dist_op_default_impl_container: + compatible_impls.extend( + dist_op_default_impl_container.get_input_compatible_impls( + dist_op)) + else: + # First, find impls in the corresponding container + if dist_op_impl_container: + compatible_impls.extend( + dist_op_impl_container.get_output_compatible_impls(dist_op)) + # Second, find impls in the elementwise container + if dist_op_eltwise_impl_container and is_elementwise_op(op_type): + compatible_impls.extend( + dist_op_eltwise_impl_container.get_output_compatible_impls( + dist_op)) + # Third, find impls in the default container + if dist_op_default_impl_container: + compatible_impls.extend( + dist_op_default_impl_container.get_output_compatible_impls( + dist_op)) + else: + # First, find impls in the corresponding container + if dist_op_impl_container: + compatible_impls.extend( + dist_op_impl_container.get_compatible_impls(dist_op)) + # Second, find impls in the elementwise container + if dist_op_eltwise_impl_container and is_elementwise_op(op_type): + compatible_impls.extend( + dist_op_eltwise_impl_container.get_compatible_impls(dist_op)) + # Third, find impls in the default container + if dist_op_default_impl_container: + compatible_impls.extend( + dist_op_default_impl_container.get_compatible_impls(dist_op)) + + if compatible_impls: + # For now, just return the first compatible impl + # best_compatible_impl = compatible_impls[0] + best_compatible_impl = compatible_impls + else: + best_compatible_impl = None + return best_compatible_impl + + +def is_parameter_related(varname, block): + if ".subprog_" in varname: + varname = varname[:varname.index(".subprog_")] + if ".cast_fp" in varname: + varname = varname[:varname.index(".cast_fp")] + if ".quantized" in varname: + varname = varname[:varname.index(".quantized")] + assert block.has_var(varname) + var = block.var(varname) + return var.is_parameter + + +def infer_shape(block, src_var, src_var_dist_attr, op_input_dist_attr): + var_shape = block.var(src_var.name).shape + var_topoloy = src_var_dist_attr.process_mesh.topology + var_dims_mapping = src_var_dist_attr.dims_mapping + + complete_shape = [] + for idx, shape in enumerate(var_shape): + if var_dims_mapping[idx] == -1: + complete_shape.append(shape) + else: + new_shape = shape * var_topoloy[var_dims_mapping[idx]] + complete_shape.append(new_shape) + + exact_shape = [] + input_topology = op_input_dist_attr.process_mesh.topology + input_dims_mapping = op_input_dist_attr.dims_mapping + for idx, shape in enumerate(complete_shape): + if input_dims_mapping[idx] == -1: + exact_shape.append(shape) + else: + new_shape = shape // input_topology[input_dims_mapping[idx]] + exact_shape.append(new_shape) + + return exact_shape + + +def set_comm_op_dist_attr_for_program(new_op, process_mesh, tensor_dist_attr, + ctx): + assert process_mesh is not None + assert tensor_dist_attr is not None + + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = process_mesh + for input_varname in new_op.desc.input_arg_names(): + new_op_dist_attr.set_input_dist_attr(input_varname, tensor_dist_attr) + for output_varname in new_op.desc.output_arg_names(): + new_op_dist_attr.set_output_dist_attr(output_varname, tensor_dist_attr) + ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + + +def naive_copy_op_dist_attr_for_program(new_op, ref_op, ctx): + + ref_dist_attr = ctx.get_op_dist_attr_for_program(ref_op) + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = ref_dist_attr.process_mesh + + for input_name in ref_op.input_names: + assert input_name in new_op.input_names + assert len(ref_op.input(input_name)) == 1 + assert len(new_op.input(input_name)) == 1 + + ref_tensor_dist_attr = ref_dist_attr.get_input_dist_attr( + ref_op.input(input_name)[0]) + new_op_dist_attr.set_input_dist_attr( + new_op.input(input_name)[0], ref_tensor_dist_attr) + + for output_name in ref_op.output_names: + assert output_name in new_op.output_names + assert len(ref_op.output(output_name)) == 1 + assert len(new_op.output(output_name)) == 1 + + ref_tensor_dist_attr = ref_dist_attr.get_output_dist_attr( + ref_op.output(output_name)[0]) + new_op_dist_attr.set_output_dist_attr( + new_op.output(output_name)[0], ref_tensor_dist_attr) + + ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + + +def get_data_parallel_group(dist_ctx, op, act_grad_names, rank): + """ + deduce the data parallel communication group for current operator. + + Args: + dist_ctx (DistributedContext): dist context. + op (Operator): the current (backward) operator which might need. + act_grad_names (list): list of input activation grads variable name to the current operator. + out_grad_names (list): list of the output parameter's grads variable name of the current operator. + rank (int): global ranks index for current process. + """ + dp_group = None + + op_dist_attr = dist_ctx.get_op_dist_attr_for_program(op) + process_mesh = op_dist_attr.process_mesh + mesh_shape = process_mesh.topology + # FIXME Hack for Pipeline Parallelism where the current operator + # not belong to the mesh the current rank belong to. + if rank not in process_mesh.processes: + rank = _get_corresponding_rank(dist_ctx, process_mesh, rank) + + for var_name in act_grad_names: + var_dim_mapping = op_dist_attr.get_input_dims_mapping(var_name) + # consider that the variable's shape is None + # TODO utilize the batch_dim attr instead of "0" in future + batch_size_axis = var_dim_mapping[0] if len(var_dim_mapping) > 0 else -1 + + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + group_ranks = _get_comm_group(process_mesh.processes, + process_mesh.topology, + batch_size_axis, rank) + dp_group = new_process_group(group_ranks) + break + + return dp_group + + +def sync_and_scale_gradients(dist_ctx, op, dp_group, allreduce_var_names): + """ + insert the allreudce and scale ops for gradients of model + parameters for operator in data parallelism. + + Args: + dist_ctx (DistributedContext): dist context. + op (Operator): the current (backward) operator which might need. + allreduce_var_names (list): list of the parameter's grads variable name in the current operator output. + """ + + op_dist_attr = dist_ctx.get_op_dist_attr_for_program(op) + process_mesh = op_dist_attr.process_mesh + dist_op_context = dist_ctx.dist_op_context + main_block = dist_op_context.work_block + dp_degree = len(dp_group.ranks) + + for var_name in allreduce_var_names: + added_ops = [] + grad_var = main_block.var(var_name) + allreduce_op = main_block.append_op(type='c_allreduce_sum', + inputs={'X': [grad_var]}, + outputs={'Out': [grad_var]}, + attrs={ + 'ring_id': dp_group.id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Backward + }) + allreduce_op._set_attr('op_namescope', + str('/') + ParallelMode.DataParallel) + added_ops.append(allreduce_op) + + if dist_ctx.gradient_scale: + scale_op = main_block.append_op(type='scale', + inputs={'X': grad_var}, + outputs={'Out': grad_var}, + attrs={ + 'scale': 1.0 / dp_degree, + OP_ROLE_KEY: OpRole.Backward + }) + scale_op._set_attr('op_namescope', + str('/') + ParallelMode.DataParallel) + added_ops.append(scale_op) + + dims_mapping = op_dist_attr.get_output_dims_mapping(grad_var.name) + assert dims_mapping is not None, "Unexception: dims_mapping of output [{}] of op [{}] is None".format( + grad_var.name, op_dist_attr.op_type) + # NOTE auxiliary op's dist attr should follow dist_op not dist_tensor + for new_op in added_ops: + new_op_attr = OperatorDistributedAttribute() + new_op_attr.process_mesh = process_mesh + new_op_attr.set_output_dims_mapping(grad_var.name, dims_mapping) + new_op_attr.set_input_dims_mapping(grad_var.name, dims_mapping) + dist_ctx.set_op_dist_attr_for_program(new_op, new_op_attr) + + +def gradient_synchronization(dist_ctx, op, act_grad_names, out_grad_names, + rank): + """ + conduct the allreudce and scaling(dp size)for gradients of model + parameters for operator in data parallelism. + + Args: + dist_ctx (DistributedContext): dist context. + op (Operator): the current (backward) operator which might need. + act_grad_names (list): list of input activation grads variable name to the current operator. + out_grad_names (list): list of the output parameter's grads variable name of the current operator. + rank (int): global ranks index for current process. + """ + + if not is_in_backward_phase(dist_ctx): + return + + if is_optimize_op(op) or len(act_grad_names) == 0 or len( + out_grad_names) == 0: + return + + dp_group = get_data_parallel_group(dist_ctx, op, act_grad_names, rank) + + if not dp_group: + return + + sync_and_scale_gradients(dist_ctx, op, dp_group, out_grad_names) + + +def is_data_parallel_scale_op(op): + return op.type == "scale" and op.desc.has_attr("op_namescope") \ + and ParallelMode.DataParallel in op.desc.attr("op_namescope") + + +def is_data_parallel_reduce_op(op): + return op.type in ["c_reduce_sum", "c_allreduce_sum"] and op.desc.has_attr("op_namescope") \ + and ParallelMode.DataParallel in op.desc.attr("op_namescope") + + +def is_in_backward_phase(dist_ctx): + # NOTE currently high-order differential in Paddle dose NOT distinguish gradient computation operators + # in Forward phase and operators in Backward phase (both with op_role=1), which will mislead + # auto parallel to add gradient synchronization for gradient computation operators in Forward phase. + # we use this FLAG to distinguish these two phases temporarily. + + return dist_ctx.dist_op_context.in_backward_phase() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_assign.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_assign.py new file mode 100644 index 0000000000000000000000000000000000000000..96923f461a73d3bbf3f83b502035cb1ea831f721 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_assign.py @@ -0,0 +1,88 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .dist_default import DistributedDefaultImpl0 +from ..utils import compute_compatible_and_update_dim_mapping + + +class DistributedAssign(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedAssign, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedAssign("assign")) + + +class DistributedAssignImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedAssignImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + return True + + def is_output_compatible(self, dist_op): + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if x_dims_mapping != out_dims_mapping: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("assign", DistributedAssignImpl("assign")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_check_finite_and_unscale.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_check_finite_and_unscale.py new file mode 100644 index 0000000000000000000000000000000000000000..108b99fdce613bdc33a4af4dfdc4ee47bfdfd9b8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_check_finite_and_unscale.py @@ -0,0 +1,177 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..utils import set_var_dist_attr +from ..utils import set_dist_op_desc_original_id +from ..process_group import new_process_group +from ..dist_attribute import OperatorDistributedAttribute +from paddle.distributed.auto_parallel.process_group import get_world_process_group + +world_process_group = get_world_process_group() + + +class DistributedCheckFiniteAndUnscale(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedCheckFiniteAndUnscale, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedCheckFiniteAndUnscale("check_finite_and_unscale")) + + +class DistributedCheckFiniteAndUnscaleImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedCheckFiniteAndUnscaleImpl, self).__init__(name) + self._name = name + self._forward_implemented = False + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + raise RuntimeError( + "DistributedCheckFiniteAndUnscaleImpl's is_input_compatible should not be called !" + ) + + def is_output_compatible(self, dist_op): + raise RuntimeError( + "DistributedCheckFiniteAndUnscaleImpl's is_output_compatible should not be called !" + ) + + def is_auto_compatible(self, dist_op): + raise RuntimeError( + "DistributedCheckFiniteAndUnscaleImpl's is_auto_compatible should not be called !" + ) + + def update_dims_mapping(self, dist_op): + raise RuntimeError( + "DistributedCheckFiniteAndUnscaleImpl's update_dims_mapping should not be called !" + ) + + @staticmethod + def forward(ctx, *args, **kwargs): + raise RuntimeError( + "DistributedCheckFiniteAndUnscaleImpl's forward should not be called !" + ) + + @staticmethod + def backward(ctx, *args, **kwargs): + + # by now the backward function only insert the gradient allreduce for dist op itself + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.main_block + backward_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(backward_op)) + + assert rank_id in dist_attr.process_mesh.processes + + assert 'X' in kwargs, "input [{}] is not given".format('X') + assert 'Scale' in kwargs, "input [{}] is not given".format('Scale') + assert 'Out' in kwargs, "input [{}] is not given".format('Out') + assert 'FoundInfinite' in kwargs, "output [{}] is not given".format( + 'FoundInfinite') + + assert len( + kwargs['Scale'] + ) == 1, "check_finite_and_unscale input Scale take 1 variable but got {}".format( + kwargs['Scale']) + assert len( + kwargs['FoundInfinite'] + ) == 1, "check_finite_and_unscale input FoundInfinite take 1 variable but got {}".format( + kwargs['FoundInfinite']) + assert len(kwargs['X']) == len( + kwargs['Out'] + ), "check_finite_and_unscale got [{}] X and [{}] Out, which are supposed to be equal".format( + len(kwargs['X']), len(kwargs['Out'])) + + filter_vars = [] + for varname in kwargs['X']: + if rank_id in ctx.get_tensor_dist_attr_for_program( + main_block.var(varname)).process_mesh.processes: + filter_vars.append(varname) + + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(backward_op.desc) + set_dist_op_desc_original_id(dist_op_desc, backward_op.desc, ctx) + dist_op_desc.set_input('X', filter_vars) + dist_op_desc.set_output('Out', filter_vars) + + # sync result + group = new_process_group(world_process_group.ranks) + + inf_var = main_block.var(kwargs['FoundInfinite'][0]) + inf_var_int32 = main_block.create_var(name=inf_var.name + "@cast_int32", + shape=inf_var.shape, + dtype=core.VarDesc.VarType.INT32) + set_var_dist_attr( + ctx, inf_var_int32, + ctx.get_tensor_dist_attr_for_program(inf_var).dims_mapping, + ctx.get_tensor_dist_attr_for_program(inf_var).process_mesh) + cast_op1 = main_block.append_op(type='cast', + inputs={'X': inf_var}, + outputs={'Out': inf_var_int32}, + attrs={ + "in_dtype": inf_var.dtype, + "out_dtype": inf_var_int32.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + allreduce_op = main_block.append_op(type='c_allreduce_max', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var_int32}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize + }) + cast_op2 = main_block.append_op(type='cast', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var}, + attrs={ + "in_dtype": inf_var_int32.dtype, + "out_dtype": inf_var.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + + for op in [cast_op1, allreduce_op, cast_op2]: + new_op_dist_attr = OperatorDistributedAttribute() + for varname in op.input_arg_names: + var_dist_attr = ctx.get_tensor_dist_attr_for_program( + main_block.var(varname)) + assert var_dist_attr is not None + new_op_dist_attr.set_input_dims_mapping( + varname, var_dist_attr.dims_mapping) + for varname in op.output_arg_names: + var_dist_attr = ctx.get_tensor_dist_attr_for_program( + main_block.var(varname)) + new_op_dist_attr.set_output_dims_mapping( + varname, var_dist_attr.dims_mapping) + new_op_dist_attr.process_mesh = var_dist_attr.process_mesh + ctx.set_op_dist_attr_for_program(op, new_op_dist_attr) + + +register_distributed_operator_impl( + "check_finite_and_unscale", + DistributedCheckFiniteAndUnscaleImpl("check_finite_and_unscale")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_default.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_default.py new file mode 100644 index 0000000000000000000000000000000000000000..a5139e001894bb30c1502439d1052e4947e2c388 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_default.py @@ -0,0 +1,564 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import gradient_synchronization +from .common import register_distributed_operator_impl, is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index, is_prim_op +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..utils import set_dist_op_desc_original_id +from ..dist_attribute import OperatorDistributedAttribute +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..process_group import new_process_group +from ..utils import _get_comm_group, _get_corresponding_rank +from ..cost import _g_op_cost_factory +from ..cost import build_comp_desc_from_dist_op, build_dp_costs +from ..cost import build_comp_costs_from_descs + +__op_not_need_param_init__ = ["while", "cond"] + + +def prim_operator_data_parallel_functor(ctx, src_op): + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + + var_name = src_op.output_arg_names[0] + if var_name in ctx.grads_params: + assert var_name not in ctx.synced_gradient, "in primtive mode, grad is already {} synced".format( + var_name) + ctx.synced_gradient.add(var_name) + sync_group = new_process_group(ctx.data_parallel_group) + + allreduce_op = main_block.append_op(type='c_allreduce_sum', + inputs={'X': [var_name]}, + outputs={'Out': [var_name]}, + attrs={ + 'ring_id': sync_group.id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Backward + }) + + param = ctx.grads_params[var_name] + startup_block = dist_op_context.startup_block + new_op = startup_block.append_op(type='c_broadcast', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'ring_id': sync_group.id, + 'root': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + + grad_var = main_block.var(var_name) + dims_mapping = ctx.get_tensor_dist_attr_for_program( + grad_var).dims_mapping + dist_attr = ctx.get_op_dist_attr_for_program(src_op) + process_mesh = dist_attr.process_mesh + op_attr = OperatorDistributedAttribute() + op_attr.process_mesh = process_mesh + op_attr.set_output_dims_mapping(grad_var.name, dims_mapping) + op_attr.set_input_dims_mapping(grad_var.name, dims_mapping) + ctx.set_op_dist_attr_for_program(allreduce_op, op_attr) + + return + + +class DistributedDefault(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedDefault, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedDefault("default")) + + +# Replicated Default +class DistributedDefaultImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedDefaultImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + """Calculate the cost by the op role.""" + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + op_type = dist_op.serial_op.type + cost_mapping = build_comp_costs_from_descs(_g_op_cost_factory[op_type], + ctx, processes, desc_mapping, + cluster) + res_cost = [cost_mapping] + + return res_cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + backward_op = dist_op.serial_op + op_type = backward_op.type + cost_mapping = build_comp_costs_from_descs(_g_op_cost_factory[op_type], + ctx, processes, desc_mapping, + cluster) + res.append(cost_mapping) + + main_block = backward_op.block + vars = main_block.vars + need_gradient_allreduce = False + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and not is_parameter_related( + varname, main_block): + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + need_gradient_allreduce = True + break + + if need_gradient_allreduce: + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and is_parameter_related( + varname, main_block): + var_dim_mapping = dist_attr.get_input_dims_mapping( + varname) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + batch_dim_mappings = [] + input_names = op_desc.input_names() + xshape_arg_names = [] + if "XShape" in input_names: + xshape_arg_names = op_desc.input("XShape") + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if serial_tensor.is_parameter: + for mapping in dims_mapping: + if mapping != -1: + return False + continue + if arg_name not in xshape_arg_names: + if len(dims_mapping) > 1: + for mapping in dims_mapping[1:]: + if mapping != -1: + return False + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + if dims_mapping[0] != -1: + return False + if len(dims_mapping) > 2: + for mapping in dims_mapping[2:]: + if mapping != -1: + return False + if len(dims_mapping) >= 2: + batch_dim_mappings.append(dims_mapping[1]) + + if compute_compatible_dim_mapping(batch_dim_mappings) is None: + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + output_names = op_desc.output_names() + batch_dim_mappings = [] + xshape_arg_names = [] + if "XShape" in output_names: + xshape_arg_names = op_desc.output("XShape") + for arg_name in op_desc.output_arg_names(): + serial_tensor = dist_op.get_serial_output(arg_name) + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if serial_tensor.is_parameter: + for mapping in dims_mapping: + if mapping != -1: + return False + continue + if arg_name not in xshape_arg_names: + if len(dims_mapping) > 1: + for mapping in dims_mapping[1:]: + if mapping != -1: + return False + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + if dims_mapping[0] != -1: + return False + if len(dims_mapping) > 2: + for mapping in dims_mapping[2:]: + if mapping != -1: + return False + if len(dims_mapping) >= 2: + batch_dim_mappings.append(dims_mapping[1]) + + if compute_compatible_dim_mapping(batch_dim_mappings) is None: + return False + + return True + + def is_auto_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + batch_dim_mappings = [] + # Check input compatibility + input_names = op_desc.input_names() + xshape_arg_names = [] + if "XShape" in input_names: + xshape_arg_names = op_desc.input("XShape") + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if serial_tensor is not None and serial_tensor.is_parameter: + for mapping in dims_mapping: + if mapping != -1: + return False + continue + if arg_name not in xshape_arg_names: + if len(dims_mapping) > 1: + for mapping in dims_mapping[1:]: + if mapping != -1: + return False + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + if dims_mapping[0] != -1: + return False + if len(dims_mapping) > 2: + for mapping in dims_mapping[2:]: + if mapping != -1: + return False + if len(dims_mapping) >= 2: + batch_dim_mappings.append(dims_mapping[1]) + + # Check output compatibility + output_names = op_desc.output_names() + xshape_arg_names = [] + if "XShape" in output_names: + xshape_arg_names = op_desc.output("XShape") + for arg_name in op_desc.output_arg_names(): + serial_tensor = dist_op.get_serial_output(arg_name) + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if serial_tensor is not None and serial_tensor.is_parameter: + for mapping in dims_mapping: + if mapping != -1: + return False + continue + if arg_name not in xshape_arg_names: + if len(dims_mapping) > 1: + for mapping in dims_mapping[1:]: + if mapping != -1: + return False + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + if dims_mapping[0] != -1: + return False + if len(dims_mapping) > 2: + for mapping in dims_mapping[2:]: + if mapping != -1: + return False + if len(dims_mapping) >= 2: + batch_dim_mappings.append(dims_mapping[1]) + + # Check batch dim mapping compatibility + if not all(batch_dim_mappings[0] == dim_mapping + for dim_mapping in batch_dim_mappings): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + if op_desc.type() == "while": + return False + + input_names = op_desc.input_names() + input_xshape_arg_names = [] + if "XShape" in input_names: + input_xshape_arg_names = op_desc.input("XShape") + + output_names = op_desc.output_names() + output_xshape_arg_names = [] + if "XShape" in output_names: + output_xshape_arg_names = op_desc.output("XShape") + + batch_dim_mappings = [] + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if arg_name not in input_xshape_arg_names: + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + batch_dim_mappings.append(dims_mapping[1]) + for arg_name in op_desc.output_arg_names(): + if op_desc.type() == 'fill_any_like': + input_tensor = dist_op.get_serial_input( + op_desc.input_arg_names()[0]) + if input_tensor.is_parameter: + continue + serial_tensor = dist_op.get_serial_output(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if arg_name not in output_xshape_arg_names: + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + else: + batch_dim_mappings.append(dims_mapping[1]) + + if not batch_dim_mappings: + return changed + + compatible_dim_mapping = compute_compatible_dim_mapping( + batch_dim_mappings) + if compatible_dim_mapping is None: + return False + + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if arg_name not in input_xshape_arg_names: + if len(dims_mapping) >= 1 and \ + compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + else: + if len(dims_mapping) >= 2 and \ + compatible_dim_mapping != dims_mapping[1]: + dims_mapping[1] = compatible_dim_mapping + changed = True + for arg_name in op_desc.output_arg_names(): + if op_desc.type() == 'fill_any_like': + input_tensor = dist_op.get_serial_input( + op_desc.input_arg_names()[0]) + if input_tensor.is_parameter: + continue + if op_desc.type() in ["shape", "slice"]: + continue + serial_tensor = dist_op.get_serial_output(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if arg_name not in output_xshape_arg_names: + if len(dims_mapping + ) >= 1 and compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + else: + if len(dims_mapping + ) >= 2 and compatible_dim_mapping != dims_mapping[1]: + dims_mapping[1] = compatible_dim_mapping + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(dist_op_desc, src_op.desc, ctx) + for input_name in src_op.desc.input_names(): + dist_op_desc.set_input(input_name, kwargs[input_name]) + for output_name in src_op.desc.output_names(): + dist_op_desc.set_output(output_name, kwargs[output_name]) + + # data parallel synchronization for primtive operators + from paddle.incubate.autograd import prim_enabled + if prim_enabled(): + assert is_prim_op(src_op) + prim_operator_data_parallel_functor(ctx, src_op) + return + + # param initialization sync + if src_op.type in __op_not_need_param_init__: + return + + for varname in dist_op_desc.input_arg_names(): + if startup_block.has_var(varname) and startup_block.var( + varname + ).is_parameter and varname not in dist_op_context.already_init_sync_vars: + dist_op_context.already_init_sync_vars.add(varname) + param = startup_block.var(varname) + param_dist_attr = ctx.get_tensor_dist_attr_for_program(param) + process_mesh = param_dist_attr.process_mesh + dims_mapping = param_dist_attr.dims_mapping + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, process_mesh, + rank_id) + + # NOTE all not splited axis should be presented in mesh + for axis, size in enumerate(process_mesh.topology): + if size <= 1 or axis in dims_mapping: + pass + else: + group_ranks = _get_comm_group(process_mesh.processes, + process_mesh.topology, + axis, rank_id) + sync_group = new_process_group(group_ranks) + + new_op = startup_block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': + sync_group.id, + 'root': + 0, + 'use_calc_stream': + True, + OP_ROLE_KEY: + OpRole.Forward + }) + + # set distributed attribute + op_attr = OperatorDistributedAttribute() + op_attr.process_mesh = process_mesh + op_attr.set_output_dims_mapping(param.name, + dims_mapping) + op_attr.set_input_dims_mapping(param.name, dims_mapping) + ctx.set_op_dist_attr_for_program(new_op, op_attr) + + @staticmethod + def backward(ctx, *args, **kwargs): + + # by now the backward function only insert the gradient allreduce for dist op itself + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + backward_op = dist_op_context.cur_src_op + dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(backward_op)) + rank_id = dist_op_context.rank_id + + # check validation of inputs / outputs + for input_name in backward_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + backward_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in backward_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + backward_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(backward_op.desc) + # Refer to the related dist op + set_dist_op_desc_original_id(dist_op_desc, backward_op.desc, ctx) + for input_name in backward_op.desc.input_names(): + dist_op_desc.set_input(input_name, kwargs[input_name]) + for output_name in backward_op.desc.output_names(): + dist_op_desc.set_output(output_name, kwargs[output_name]) + + # data parallel gradient synchronization + act_grad_names = [] + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and not is_parameter_related( + varname, main_block): + act_grad_names.append(varname) + + out_grad_names = [] + for output_name in backward_op.desc.output_names(): + for varname in backward_op.desc.output(output_name): + if varname in kwargs["grad_var_to_var"]: + fwd_name = kwargs["grad_var_to_var"][varname] + if fwd_name not in main_block.vars: + continue + if is_parameter_related(fwd_name, main_block): + out_grad_names.append(varname) + + gradient_synchronization(ctx, backward_op, act_grad_names, + out_grad_names, rank_id) + + +register_distributed_operator_impl( + "default", DistributedDefaultImpl0("replicate_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_eltwise.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_eltwise.py new file mode 100644 index 0000000000000000000000000000000000000000..348e2ee4573398998f13355a2e86560427919310 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_eltwise.py @@ -0,0 +1,319 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl, is_parameter_related +from .common import is_elementwise_op +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..dist_attribute import OperatorDistributedAttribute +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..process_group import new_process_group +from ..utils import _get_comm_group, _get_corresponding_rank +from .dist_default import DistributedDefaultImpl0 +from ..cost import _g_op_cost_factory +from ..cost import build_comp_desc_from_dist_op, build_dp_costs +from ..cost import build_comp_costs_from_descs + + +class DistributedElementwise(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedElementwise, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedElementwise("elementwise")) + + +# Replicated Elementwise +class DistributedElementwiseImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedElementwiseImpl0, self).__init__(name) + self._forward_implemented = False + self._backward_implemented = False + + def calc_cost(self, op_role, dist_op, ctx, cluster): + """Calculate the cost by the op role.""" + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + op_type = dist_op.serial_op.type + cost_mapping = build_comp_costs_from_descs(_g_op_cost_factory[op_type], + ctx, processes, desc_mapping, + cluster) + res_cost = [cost_mapping] + + return res_cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + backward_op = dist_op.serial_op + op_type = backward_op.type + cost_mapping = build_comp_costs_from_descs(_g_op_cost_factory[op_type], + ctx, processes, desc_mapping, + cluster) + res.append(cost_mapping) + + main_block = backward_op.block + vars = main_block.vars + need_gradient_allreduce = False + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and not is_parameter_related( + varname, main_block): + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + need_gradient_allreduce = True + break + + if need_gradient_allreduce: + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and is_parameter_related( + varname, main_block): + var_dim_mapping = dist_attr.get_input_dims_mapping( + varname) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + if not is_elementwise_op(op_desc.type()): + return False + op_dist_attr = dist_op.dist_attr + dims_mapping_list = [] + input_arg_names = op_desc.input_arg_names() + max_dims_mapping_len = -1 + for arg_name in input_arg_names: + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if max_dims_mapping_len < len(dims_mapping): + max_dims_mapping_len = len(dims_mapping) + dims_mapping_list.append(dims_mapping) + + for idx in range(max_dims_mapping_len): + dim_mappings = [] + for dims_mapping in dims_mapping_list: + if idx < len(dims_mapping): + dim_mappings.append(dims_mapping[-(idx + 1)]) + if compute_compatible_dim_mapping(dim_mappings) is None: + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + if not is_elementwise_op(op_desc.type()): + return False + op_dist_attr = dist_op.dist_attr + dims_mapping_list = [] + output_arg_names = op_desc.output_arg_names() + max_dims_mapping_len = -1 + for arg_name in output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if max_dims_mapping_len < len(dims_mapping): + max_dims_mapping_len = len(dims_mapping) + dims_mapping_list.append(dims_mapping) + + for idx in range(max_dims_mapping_len): + dim_mappings = [] + for dims_mapping in dims_mapping_list: + if idx < len(dims_mapping): + dim_mappings.append(dims_mapping[-(idx + 1)]) + if compute_compatible_dim_mapping(dim_mappings) is None: + return False + return True + + def is_auto_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + if not is_elementwise_op(op_desc.type()): + return False + op_dist_attr = dist_op.dist_attr + dims_mapping_list = [] + + input_arg_names = op_desc.input_arg_names() + input_max_dims_mapping_len = -1 + for arg_name in input_arg_names: + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if input_max_dims_mapping_len < len(dims_mapping): + input_max_dims_mapping_len = len(dims_mapping) + dims_mapping_list.append(dims_mapping) + + output_arg_names = op_desc.output_arg_names() + output_max_dims_mapping_len = -1 + for arg_name in output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if output_max_dims_mapping_len < len(dims_mapping): + output_max_dims_mapping_len = len(dims_mapping) + dims_mapping_list.append(dims_mapping) + + assert input_max_dims_mapping_len == output_max_dims_mapping_len + max_dims_mapping_len = input_max_dims_mapping_len + + for idx in range(max_dims_mapping_len): + dim_mappings = [] + for dims_mapping in dims_mapping_list: + if idx < len(dims_mapping): + dim_mappings.append(dims_mapping[-(idx + 1)]) + if not all(dim_mappings[0] == dim_mapping + for dim_mapping in dim_mappings): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + dims_mapping_list = [] + + input_arg_names = op_desc.input_arg_names() + input_dims_mapping_dict = {} + input_dims_mapping_lens = {} + input_max_dims_mapping_len = -1 + for arg_name in input_arg_names: + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if input_max_dims_mapping_len < len(dims_mapping): + input_max_dims_mapping_len = len(dims_mapping) + input_dims_mapping_dict[arg_name] = dims_mapping + input_dims_mapping_lens[arg_name] = len(dims_mapping) + for arg_name in input_arg_names: + if input_dims_mapping_lens[arg_name] < input_max_dims_mapping_len: + new_dims_mapping = [ + -1 for _ in range(input_max_dims_mapping_len) + ] + for i in range(input_dims_mapping_lens[arg_name]): + new_idx = (input_max_dims_mapping_len - + input_dims_mapping_lens[arg_name]) + i + new_dims_mapping[new_idx] = input_dims_mapping_dict[ + arg_name][i] + dims_mapping_list.append(new_dims_mapping) + else: + dims_mapping_list.append(input_dims_mapping_dict[arg_name]) + + output_arg_names = op_desc.output_arg_names() + output_dims_mapping_dict = {} + output_dims_mapping_lens = {} + output_max_dims_mapping_len = -1 + for arg_name in output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if output_max_dims_mapping_len < len(dims_mapping): + output_max_dims_mapping_len = len(dims_mapping) + output_dims_mapping_dict[arg_name] = dims_mapping + output_dims_mapping_lens[arg_name] = len(dims_mapping) + for arg_name in output_arg_names: + if output_dims_mapping_lens[arg_name] < output_max_dims_mapping_len: + new_dims_mapping = [ + -1 for _ in range(output_max_dims_mapping_len) + ] + for i in range(output_dims_mapping_lens[arg_name]): + new_idx = (output_max_dims_mapping_len - + output_dims_mapping_lens[arg_name]) + i + new_dims_mapping[new_idx] = output_dims_mapping_dict[ + arg_name][i] + dims_mapping_list.append(new_dims_mapping) + else: + dims_mapping_list.append(output_dims_mapping_dict[arg_name]) + + assert input_max_dims_mapping_len == output_max_dims_mapping_len + max_dims_mapping_len = input_max_dims_mapping_len + compatible_dims_mapping = compute_compatible_dims_mapping( + dims_mapping_list) + if compatible_dims_mapping is None: + return False + + for arg_name in input_arg_names: + if input_dims_mapping_lens[arg_name] < max_dims_mapping_len: + new_dims_mapping = [ + -1 for _ in range(input_dims_mapping_lens[arg_name]) + ] + for i in range(input_dims_mapping_lens[arg_name]): + new_idx = (max_dims_mapping_len - + input_dims_mapping_lens[arg_name]) + i + new_dims_mapping[i] = compatible_dims_mapping[new_idx] + if new_dims_mapping != input_dims_mapping_dict[arg_name]: + op_dist_attr.set_input_dims_mapping(arg_name, + new_dims_mapping) + changed = True + else: + if compatible_dims_mapping != input_dims_mapping_dict[arg_name]: + op_dist_attr.set_input_dims_mapping( + arg_name, compatible_dims_mapping) + changed = True + + for arg_name in output_arg_names: + if output_dims_mapping_lens[arg_name] < max_dims_mapping_len: + new_dims_mapping = [ + -1 for _ in range(output_dims_mapping_lens[arg_name]) + ] + for i in range(output_dims_mapping_lens[arg_name]): + new_idx = (max_dims_mapping_len - + output_dims_mapping_lens[arg_name]) + i + new_dims_mapping[i] = compatible_dims_mapping[new_idx] + if new_dims_mapping != output_dims_mapping_dict[arg_name]: + op_dist_attr.set_output_dims_mapping( + arg_name, new_dims_mapping) + changed = True + else: + if compatible_dims_mapping != output_dims_mapping_dict[arg_name]: + op_dist_attr.set_output_dims_mapping( + arg_name, compatible_dims_mapping) + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl( + "elementwise", DistributedElementwiseImpl0("replicate_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_embedding.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..856d9c36bb4e17d7354918a065aaf745df39ec3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_embedding.py @@ -0,0 +1,613 @@ +# Copyright (c) 2021 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 + +from .common import infer_shape +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import gradient_synchronization +from .common import register_distributed_operator_impl, set_comm_op_dist_attr_for_program, naive_copy_op_dist_attr_for_program, is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..dist_attribute import OperatorDistributedAttribute, TensorDistributedAttribute +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..process_group import new_process_group +from ..utils import _get_comm_group, _get_idx_in_axis, _get_corresponding_rank, set_var_dist_attr +from ..cost import build_comp_desc_from_dist_op, build_comm_desc_from_dist_op +from ..cost import build_comm_costs_from_descs, build_comp_costs_from_descs, build_dp_costs +from ..cost import EmbeddingOpCost, EmbeddingGradOpCost +from paddle.distributed.auto_parallel.cost.comm_op_cost import AllreduceSumOpCost, IdentityOpCost + + +class DistributedEmbedding(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedEmbedding, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedEmbedding("lookup_table_v2")) +register_distributed_operator_impl_container( + DistributedEmbedding("c_embedding")) +register_distributed_operator_impl_container( + DistributedEmbedding("lookup_table")) + + +def adopt_lookup_table_v1(ctx, main_block, src_op, Ids_var): + + assert len( + Ids_var.shape + ) == 3, "input Ids to lookup_table should have 3 dimensions but got [{}] with shape [{}]".format( + Ids_var.name, Ids_var.shape) + if not Ids_var.stop_gradient: + raise NotImplementedError( + 'Requiring the gradient of Ids of lookup_table(v1)dist op is not currently supported. Please open an issue with details on your use case so that we can prioritize adding this (for instance, adversarial training for language model).' + ) + + target_shape = list(Ids_var.shape[:-1]) + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["dist_reshape", 'tmp'])), + dtype=Ids_var.dtype, + shape=target_shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + + target_shape = [0] + list(Ids_var.shape[:-1]) + xshape_var = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["dist_Xshape", 'tmp'])), + dtype=Ids_var.dtype, + shape=target_shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + + # TODO use inplace reshape for memory saving + reshape_op = main_block.append_op(type='reshape2', + inputs={'X': [Ids_var]}, + outputs={ + 'Out': [intermediate_var_0], + 'XShape': [xshape_var] + }, + attrs={ + "shape": [0, -1], + }) + + # set dist attr + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + Ids_var_dist_attr = op_dist_attr.get_input_dist_attr(Ids_var.name) + assert Ids_var_dist_attr is not None + intermediate_var_0_dist_attr = set_var_dist_attr( + ctx, intermediate_var_0, Ids_var_dist_attr.dims_mapping, + Ids_var_dist_attr.process_mesh) + set_var_dist_attr(ctx, xshape_var, + [-1] + list(Ids_var_dist_attr.dims_mapping), + Ids_var_dist_attr.process_mesh) + op_dist_attr.del_input_dist_attr(Ids_var.name) + op_dist_attr.set_input_dist_attr(intermediate_var_0.name, + intermediate_var_0_dist_attr) + + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = Ids_var_dist_attr.process_mesh + new_op_dist_attr.impl_type = "default" + new_op_dist_attr.impl_idx = 0 + new_op_dist_attr.set_input_dims_mapping(Ids_var.name, + Ids_var_dist_attr.dims_mapping) + new_op_dist_attr.set_output_dims_mapping(intermediate_var_0.name, + Ids_var_dist_attr.dims_mapping) + new_op_dist_attr.set_output_dims_mapping( + xshape_var.name, [-1] + list(Ids_var_dist_attr.dims_mapping)) + ctx.set_op_dist_attr_for_program(reshape_op, new_op_dist_attr) + + return intermediate_var_0 + + +# RowParallel +class DistributedEmbeddingImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedEmbeddingImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + """Calculate the cost by the op role.""" + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + # embedding need start_index + cost_mapping = build_comp_costs_from_descs(EmbeddingOpCost, ctx, + processes, desc_mapping, + cluster) + + serial_op = dist_op.serial_op + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("W")[0])[0] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = serial_op.output("Out") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, c_allreduce_sum_desc_mapping, + cluster) + + res_cost = [cost_mapping, comm_op_cost_list] + + return res_cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + main_block = backward_op.block + dist_attr = dist_op.dist_attr + + embedding_row_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("W")[0])[0] + parallel_axis = embedding_row_dim_mapping + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = [backward_op.input("Out@GRAD")[0]] + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + cost_mapping = build_comp_costs_from_descs(EmbeddingGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Ids")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('W@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + ids_name = op_desc.input('Ids')[0] + w_name = op_desc.input('W')[0] + ids_dims_mapping = op_dist_attr.get_input_dims_mapping(ids_name) + w_dims_mapping = op_dist_attr.get_input_dims_mapping(w_name) + if is_dim_replicate(w_dims_mapping[-2]) or is_dim_shard( + w_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in ids_dims_mapping[1:]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + # Other dimensions must be replicate except the batch dimension + for mapping in out_dims_mapping[1:]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + ids_name = op_desc.input('Ids')[0] + w_name = op_desc.input('W')[0] + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + ids_dims_mapping = op_dist_attr.get_input_dims_mapping(ids_name) + w_dims_mapping = op_dist_attr.get_input_dims_mapping(w_name) + + if ids_dims_mapping != out_dims_mapping[:len(ids_dims_mapping)]: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + ids_name = op_desc.input('Ids')[0] + w_name = op_desc.input('W')[0] + out_name = op_desc.output('Out')[0] + ids_dims_mapping = op_dist_attr.get_input_dims_mapping(ids_name) + w_dims_mapping = op_dist_attr.get_input_dims_mapping(w_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + for i in range(len(ids_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [ids_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + dim_changed = compute_compatible_and_update_dim_mapping( + [w_dims_mapping, out_dims_mapping], [-1, -1]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # check validation of inputs / outputs + assert 'Ids' in kwargs, "input [{}] is not given".format('Ids') + assert 'W' in kwargs, "input [{}] is not given".format('W') + assert 'Out' in kwargs, "output [{}] is not given".format('Out') + + assert len( + kwargs['Ids'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['Ids']) + assert len( + kwargs['W'] + ) == 1, "row_parallel_embedding input W take 1 variable but got {}".format( + kwargs['W']) + assert len( + kwargs['Out'] + ) == 1, "row_parallel_embedding output Out take 1 variable but got {}".format( + kwargs['Out']) + + Ids_var = main_block.var(kwargs['Ids'][0]) + Weight_var = main_block._var_recursive(kwargs['W'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + + # support lookup_table_v1 + if src_op.type == 'lookup_table': + Ids_var = adopt_lookup_table_v1(ctx, main_block, src_op, Ids_var) + + # got dist attribute info + embedding_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[0] + assert embedding_row_dim_mapping >= 0, "row_parallel_embedding's row should be divided by a specific mesh axis, but got [{}]".format( + embedding_row_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in process_mesh_group: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # A generalized method to caculate embedding offset using cartisian product + relative_idx = _get_idx_in_axis(process_mesh_group, process_mesh_shape, + embedding_row_dim_mapping, rank_id) + + per_part_size = Weight_var.shape[0] + relative_idx = relative_idx * per_part_size + + # TODO caculate ring id + parallel_axis = embedding_row_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # append op + check_variable_and_dtype(Ids_var, 'input', ['int32', 'int64'], + 'c_embedding') + + # infer new var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_embedding", 'tmp'])), + dtype=Weight_var.dtype, + shape=Out_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=Out_var.stop_gradient) + # set intermediate_var_0's dist_attr with Out_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_var_dist_attr) + + check_variable_and_dtype( + Out_var, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'c_allreduce_sum') + + c_embedding_op = main_block.append_op( + type='c_embedding', + inputs={ + 'Ids': [Ids_var], + 'W': [Weight_var] + }, + outputs={'Out': [intermediate_var_0]}, + attrs={ + "start_index": relative_idx, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if intermediate_var_0.shape != ref_shape: + intermediate_var_0.desc.set_shape(ref_shape) + + # use_model_parallel + c_allreduce_sum_op = main_block.append_op( + type='c_allreduce_sum', + inputs={'X': [intermediate_var_0]}, + outputs={'Out': [Out_var]}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if Out_var.shape != ref_shape: + Out_var.desc.set_shape(ref_shape) + + # set dist op's dist_attr with serial op's dist_attr + # matmulv2 + embedding_op_dist_attr = OperatorDistributedAttribute() + embedding_op_dist_attr.process_mesh = op_dist_attr.process_mesh + embedding_op_dist_attr.impl_type = op_dist_attr.impl_type + embedding_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in c_embedding_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + embedding_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + output_varname = c_embedding_op.desc.output_arg_names()[0] + output_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + embedding_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(c_embedding_op, embedding_op_dist_attr) + + # allreduce + allreduce_op_dist_attr = OperatorDistributedAttribute() + allreduce_op_dist_attr.process_mesh = op_dist_attr.process_mesh + allreduce_op_dist_attr.impl_type = op_dist_attr.impl_type + allreduce_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in c_allreduce_sum_op.desc.input_arg_names(): + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(input_var) + assert tensor_dist_attr is not None + allreduce_op_dist_attr.set_input_dist_attr(input_varname, + tensor_dist_attr) + for output_varname in c_allreduce_sum_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + allreduce_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(c_allreduce_sum_op, + allreduce_op_dist_attr) + + # param initialization sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + if Weight_var.name in dist_op_context.already_init_sync_vars: + return + dist_op_context.already_init_sync_vars.add(Weight_var.name) + param = startup_block.var(Weight_var.name) + param_dist_attr = ctx.get_tensor_dist_attr_for_program(param) + process_mesh = param_dist_attr.process_mesh + dim_mapping = param_dist_attr.dims_mapping + + # NOTE all not splited axis should be presented in mesh + for axis, size in enumerate(process_mesh.topology): + if size <= 1 or axis in dim_mapping: + pass + else: + group_ranks = _get_comm_group(process_mesh.processes, + process_mesh.topology, axis, + rank_id) + sync_group = new_process_group(group_ranks) + + startup_block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': sync_group.id, + 'root': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + + @staticmethod + def backward(ctx, *args, **kwargs): + + # by now the backward function only insert the gradient allreduce for dist op itself + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + backward_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(backward_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, dist_attr.process_mesh, + rank_id) + + assert 'Ids' in kwargs, "input [{}] is not given".format('Ids') + assert 'W' in kwargs, "input [{}] is not given".format('W') + assert 'Out@GRAD' in kwargs, "input [{}] is not given".format('Out') + assert 'W@GRAD' in kwargs, "output [{}] is not given".format('W@GRAD') + + assert len( + kwargs['Ids'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['Ids']) + assert len( + kwargs['W'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['W']) + assert len( + kwargs['Out@GRAD'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['Out']) + assert len( + kwargs['W@GRAD'] + ) == 1, "row_parallel_embedding output Ids take 1 variable but got {}".format( + kwargs['W@GRAD']) + + Ids_var = main_block.var(kwargs['Ids'][0]) + Weight_var = main_block.var(kwargs['W'][0]) + Out_grad = main_block.var(kwargs['Out@GRAD'][0]) + Weight_grad = main_block.var(kwargs['W@GRAD'][0]) + + embedding_row_dim_mapping = dist_attr.get_input_dims_mapping( + Weight_var.name)[0] + assert embedding_row_dim_mapping >= 0, "row_parallel_embedding's row should be divided by a specific mesh axis, but got [{}]".format( + embedding_row_dim_mapping) + process_mesh_shape = dist_attr.process_mesh.topology + process_mesh_group = dist_attr.process_mesh.processes + + # A generalized method to caculate embedding offset using cartisian product + relative_idx = _get_idx_in_axis(process_mesh_group, process_mesh_shape, + embedding_row_dim_mapping, rank_id) + per_part_size = Weight_var.shape[0] + relative_idx = relative_idx * per_part_size + + check_variable_and_dtype( + Out_grad, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], '_c_identity') + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_embedding", '@tmp_0@GRAD'])), + dtype=Out_grad.dtype, + shape=Out_grad.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=Out_grad.stop_gradient) + + # copy X_var's dist_attr to intermediate_var_0's dist_attr + out_grad_dist_attr = dist_attr.get_input_dist_attr(Out_grad.name) + assert out_grad_dist_attr is not None + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_grad_dist_attr) + + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + embedding_row_dim_mapping, rank_id) + group = new_process_group(group_ranks) + + c_identity_op = main_block.append_op( + type='c_identity', + inputs={'X': [Out_grad]}, + outputs={'Out': intermediate_var_0}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: OpRole.Backward, + }) + check_variable_and_dtype(intermediate_var_0, 'x', + ['float16', 'float32', 'float64'], 'linear') + check_dtype(intermediate_var_0.dtype, 'dtype', + ['float16', 'float32', 'float64'], 'linear') + + set_comm_op_dist_attr_for_program(c_identity_op, dist_attr.process_mesh, + out_grad_dist_attr, ctx) + + c_embedding_grad_op_desc = main_block.append_op(type='nop').desc + c_embedding_grad_op_desc.set_type("c_embedding_grad") + c_embedding_grad_op_desc.set_input('Ids', [Ids_var.name]) + c_embedding_grad_op_desc.set_input('W', [Weight_var.name]) + c_embedding_grad_op_desc.set_input('Out@GRAD', + [intermediate_var_0.name]) + c_embedding_grad_op_desc.set_output('W@GRAD', [Weight_grad.name]) + c_embedding_grad_op_desc._set_attr('start_index', relative_idx) + c_embedding_grad_op_desc._set_attr(OP_ROLE_KEY, OpRole.Backward) + + c_embedding_grad_op = main_block.ops[-1] + assert c_embedding_grad_op.type == "c_embedding_grad" + naive_copy_op_dist_attr_for_program(c_embedding_grad_op, backward_op, + ctx) + + # data parallel gradient synchronization + act_grad_names = [Ids_var.name] + out_grad_names = [kwargs['W@GRAD'][0]] + + gradient_synchronization(ctx, backward_op, act_grad_names, + out_grad_names, rank_id) + + +register_distributed_operator_impl("lookup_table_v2", + DistributedEmbeddingImpl("row_parallel")) +register_distributed_operator_impl("c_embedding", + DistributedEmbeddingImpl("row_parallel")) +register_distributed_operator_impl("lookup_table", + DistributedEmbeddingImpl("row_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fill_constant_batch_size_like.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fill_constant_batch_size_like.py new file mode 100644 index 0000000000000000000000000000000000000000..3b519c2cc5b16fa2b600588b0b3f02d7d0fe3fcd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fill_constant_batch_size_like.py @@ -0,0 +1,157 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..utils import set_dist_op_desc_original_id +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole +from .dist_default import DistributedDefaultImpl0 +from ..cost import FillConstantBatchSizeLikeOpCost +from ..cost import build_comp_desc_from_dist_op, build_dp_costs +from ..cost import build_comp_costs_from_descs +from paddle.distributed.auto_parallel.cost.comm_op_cost import AllreduceSumOpCost + + +class DistributedFillConstantBatchSizeLike(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedFillConstantBatchSizeLike, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedFillConstantBatchSizeLike("fill_constant_batch_size_like")) + + +class DistributedFillConstantBatchSizeLikeImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedFillConstantBatchSizeLikeImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + raise ValueError( + "The fill_constant_batch_size_like has no grad op.") + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + op_type = dist_op.serial_op.type + cost_mapping = build_comp_costs_from_descs( + FillConstantBatchSizeLikeOpCost, ctx, processes, desc_mapping, + cluster) + + res_cost = [cost_mapping] + return res_cost + + def is_input_compatible(self, dist_op): + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + shape_list = op_desc.attr("shape") + + if len(shape_list) != len(out_dims_mapping): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + in_name = op_desc.input('Input')[0] + in_dims_mapping = op_dist_attr.get_input_dims_mapping(in_name) + + # the dim_mapping of batch dimension should be the same + return out_dims_mapping[0] == in_dims_mapping[0] + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('Input')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + # only the batch size dimemsion of input and output are relative. + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [0, 0]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + dist_op_context = ctx.dist_op_context + src_op = dist_op_context.cur_src_op + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + main_block = dist_op_context.work_block + op = main_block.ops[-1] + assert op.type == "fill_constant_batch_size_like" + + # modify shape attr according to how output are partitioned + out_name = op.output('Out')[0] + dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + process_mesh_shape = op_dist_attr.process_mesh.topology + shape_list = op.attr("shape") + # modify target shape + for idx, axis in enumerate(dims_mapping): + if axis >= 0: + shape_list[idx] = shape_list[idx] // process_mesh_shape[axis] + + op._set_attr("shape", shape_list) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl( + "fill_constant_batch_size_like", + DistributedFillConstantBatchSizeLikeImpl0("fill_by_shape")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_attention.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..23519647d33987173202f52538ce4a9b7a8bb4a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_attention.py @@ -0,0 +1,213 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import is_dim_shard, is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 +from ..utils import _get_comm_group, _get_corresponding_rank +from ..process_group import new_process_group + + +class DistributedFusedAttention(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedFusedAttention, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedFusedAttention("fused_attention")) + + +class DistributedFusedAttentionImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedFusedAttentionImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + qkv_w = op_desc.input('QKVW')[0] + qkv_bias = op_desc.input('QKVBias')[0] + out_w = op_desc.input('OutLinearW')[0] + out_bias = op_desc.input('OutLinearBias')[0] + + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + qkv_w_dims_mapping = op_dist_attr.get_input_dims_mapping(qkv_w) + qkv_bias_dims_mapping = op_dist_attr.get_input_dims_mapping(qkv_bias) + out_w_dims_mapping = op_dist_attr.get_input_dims_mapping(out_w) + out_bias_dims_mapping = op_dist_attr.get_input_dims_mapping(out_bias) + + head_axis = 1 + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + if len(qkv_w_dims_mapping) != 4 or is_dim_replicate( + qkv_w_dims_mapping[head_axis]): + return False + if len(qkv_bias_dims_mapping) != 3 or is_dim_replicate( + qkv_bias_dims_mapping[head_axis]): + return False + if is_dim_replicate(out_w_dims_mapping[0]): + return False + if is_dim_shard(out_bias_dims_mapping[-1]): + return False + + replicated_dims = [ + qkv_w_dims_mapping[0], qkv_w_dims_mapping[-2], + qkv_w_dims_mapping[-1], qkv_bias_dims_mapping[0], + qkv_bias_dims_mapping[-1], out_w_dims_mapping[-1], + out_bias_dims_mapping[-1] + ] + for mapping in replicated_dims: + if is_dim_shard(mapping): + return False + if qkv_bias_dims_mapping[head_axis] != qkv_w_dims_mapping[head_axis]: + return False + if qkv_bias_dims_mapping[head_axis] != out_w_dims_mapping[0]: + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + # none of output should be sharded + for out_name in op_desc.output_names(): + out = op_desc.output(out_name)[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out) + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_names = op_desc.output('Y') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if x_dims_mapping != out_dims_mapping: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_names = op_desc.output('Y') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # infer logic comm presentation + head_axis = 1 + qkv_w = src_op.input('QKVW')[0] + qkv_w_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + qkv_w)[head_axis] + assert qkv_w_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + qkv_w_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = qkv_w_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # insert op + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + # setting comm id + new_op = main_block.ops[-1] + assert new_op.type == "fused_attention" + new_op._set_attr("ring_id", int(group.id)) + + @staticmethod + def backward(ctx, *args, **kwargs): + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # infer logic comm presentation + out_w = src_op.input('OutLinearW')[0] + out_w_col_dim_mapping = op_dist_attr.get_input_dims_mapping(out_w)[-1] + assert out_w_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + out_w_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = out_w_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # insert op + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + # setting comm id + new_op = main_block.ops[-1] + assert new_op.type == "fused_attention_grad" + new_op._set_attr("ring_id", int(group.id)) + + +register_distributed_operator_impl( + "fused_attention", DistributedFusedAttentionImpl("tensor_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_feedforward.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_feedforward.py new file mode 100644 index 0000000000000000000000000000000000000000..50735cf285754e45f5d70f1b2d4ca834d1c7d1ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_fused_feedforward.py @@ -0,0 +1,205 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import is_dim_shard, is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 +from ..utils import _get_comm_group, _get_corresponding_rank +from ..process_group import new_process_group + + +class DistributedFusedFeedForward(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedFusedFeedForward, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedFusedFeedForward("fused_feedforward")) + + +class DistributedFusedFeedForwardImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedFusedFeedForwardImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + linear1_weight = op_desc.input('Linear1Weight')[0] + linear1_bias = op_desc.input('Linear1Bias')[0] + linear2_weight = op_desc.input('Linear2Weight')[0] + linear2_bias = op_desc.input('Linear2Bias')[0] + + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + linear1_weight_dims_mapping = op_dist_attr.get_input_dims_mapping( + linear1_weight) + linear1_bias_dims_mapping = op_dist_attr.get_input_dims_mapping( + linear1_bias) + linear2_weight_dims_mapping = op_dist_attr.get_input_dims_mapping( + linear2_weight) + linear2_bias_dims_mapping = op_dist_attr.get_input_dims_mapping( + linear2_bias) + + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + if is_dim_shard(linear1_weight_dims_mapping[-2]) or is_dim_replicate( + linear1_weight_dims_mapping[-1]): + return False + if is_dim_replicate(linear1_bias_dims_mapping[-1]): + return False + if is_dim_replicate(linear2_weight_dims_mapping[-2]) or is_dim_shard( + linear2_weight_dims_mapping[-1]): + return False + if is_dim_shard(linear2_bias_dims_mapping[-1]): + return False + if linear1_weight_dims_mapping[-1] != linear2_weight_dims_mapping[-2]: + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + # none of output should be sharded + for out_name in op_desc.output_names(): + out = op_desc.output(out_name)[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out) + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_names = op_desc.output('Out') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if x_dims_mapping != out_dims_mapping: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_names = op_desc.output('Out') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # infer logic comm presentation + linear1_weight = src_op.input('Linear1Weight')[0] + linear1_weight_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + linear1_weight)[-1] + assert linear1_weight_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + linear1_weight_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = linear1_weight_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # insert op + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + # setting comm id + new_op = main_block.ops[-1] + assert new_op.type == "fused_feedforward" + new_op._set_attr("ring_id", int(group.id)) + + @staticmethod + def backward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # infer logic comm presentation + linear2_weight = src_op.input('Linear2Weight')[0] + linear2_weight_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + linear2_weight)[-1] + assert linear2_weight_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + linear2_weight_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = linear2_weight_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # insert op + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + # setting comm id + new_op = main_block.ops[-1] + assert new_op.type == "fused_feedforward_grad" + new_op._set_attr("ring_id", int(group.id)) + + +register_distributed_operator_impl( + "fused_feedforward", DistributedFusedFeedForwardImpl("tensor_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_matmul.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..8f2db1a3b2637e7f7f093aaa67de34727c338426 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_matmul.py @@ -0,0 +1,2862 @@ +# Copyright (c) 2021 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 + +import copy + +from .common import infer_shape +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .common import gradient_synchronization +from .common import set_comm_op_dist_attr_for_program, naive_copy_op_dist_attr_for_program, is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..utils import set_dist_op_desc_original_id +from ..dist_attribute import OperatorDistributedAttribute +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..process_group import new_process_group +from ..utils import _get_comm_group, _get_corresponding_rank +from .dist_default import DistributedDefaultImpl0 +from ..cost import build_comp_desc_from_dist_op, build_comm_desc_from_dist_op, build_dp_costs +from ..cost import build_comm_costs_from_descs, build_comp_costs_from_descs +from ..cost import MatmulV2OpCost, MatmulOpCost, MulOpCost +from ..cost import MatmulV2GradOpCost, MatmulGradOpCost, MulGradOpCost +from paddle.distributed.auto_parallel.cost.comm_op_cost import AllreduceSumOpCost, IdentityOpCost + + +def trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping): + if trans_x: + x_dims_mapping[-1], x_dims_mapping[-2] = x_dims_mapping[ + -2], x_dims_mapping[-1] + if trans_y: + y_dims_mapping[-1], y_dims_mapping[-2] = y_dims_mapping[ + -2], y_dims_mapping[-1] + + +def copy_op_with_new_input_output(ctx, block, src_op, **kwargs): + dist_op_desc = block.append_op(type='nop').desc + dist_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(dist_op_desc, src_op.desc, ctx) + for input_name in src_op.desc.input_names(): + assert input_name in kwargs + dist_op_desc.set_input(input_name, kwargs[input_name]) + for output_name in src_op.desc.output_names(): + assert input_name in kwargs + dist_op_desc.set_output(output_name, kwargs[output_name]) + + return dist_op_desc + + +def _update_dims_mapping_for_matmul(dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + out_name = op_desc.output('Out')[0] + trans_x = None + trans_y = None + if op_desc.type() == "matmul_v2": + trans_x = op_desc.attr('trans_x') + trans_y = op_desc.attr('trans_y') + elif op_desc.type() == "matmul": + trans_x = op_desc.attr('transpose_X') + trans_y = op_desc.attr('transpose_Y') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_dims_mapping_len = len(x_dims_mapping) + y_dims_mapping_len = len(y_dims_mapping) + out_dims_mapping_len = len(out_dims_mapping) + + # Add dim mapping to Make sure the length dims_mapping be at least 2 + if x_dims_mapping_len == 1: + assert trans_x is False + x_dims_mapping.insert(0, -1) + out_dims_mapping.insert(out_dims_mapping_len - 1, 0) + if y_dims_mapping_len == 1: + assert trans_y is False + y_dims_mapping.insert(1, -1) + out_dims_mapping.insert(out_dims_mapping_len, 0) + + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + + new_x_dims_mapping_len = len(x_dims_mapping) + new_y_dims_mapping_len = len(y_dims_mapping) + new_out_dims_mapping_len = len(out_dims_mapping) + # Deal with dim > 2 and take care of broadcasting + if new_out_dims_mapping_len > 2: + broadcast_x_dims_mapping = [] + broadcast_y_dims_mapping = [] + broadcast_out_dims_mapping = [] + + for i in range(new_out_dims_mapping_len - new_x_dims_mapping_len): + broadcast_x_dims_mapping.append(out_dims_mapping[i]) + for i in range(new_x_dims_mapping_len - 2): + broadcast_x_dims_mapping.append(x_dims_mapping[i]) + + for i in range(new_out_dims_mapping_len - new_y_dims_mapping_len): + broadcast_y_dims_mapping.append(out_dims_mapping[i]) + for i in range(new_y_dims_mapping_len - 2): + broadcast_y_dims_mapping.append(y_dims_mapping[i]) + + for i in range(new_out_dims_mapping_len - 2): + broadcast_out_dims_mapping.append(out_dims_mapping[i]) + + compatible_dims_mapping = compute_compatible_dims_mapping([ + broadcast_x_dims_mapping, broadcast_y_dims_mapping, + broadcast_out_dims_mapping + ]) + if compatible_dims_mapping is None: + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, + y_dims_mapping) + return False + + for i in range(new_x_dims_mapping_len - 2): + new_idx = i + (out_dims_mapping_len - new_x_dims_mapping_len) + if x_dims_mapping[i] != compatible_dims_mapping[new_idx]: + x_dims_mapping[i] = compatible_dims_mapping[new_idx] + changed = True + + for i in range(new_y_dims_mapping_len - 2): + new_idx = i + (out_dims_mapping_len - new_y_dims_mapping_len) + if y_dims_mapping[i] != compatible_dims_mapping[new_idx]: + y_dims_mapping[i] = compatible_dims_mapping[new_idx] + changed = True + + for i in range(new_out_dims_mapping_len - 2): + if out_dims_mapping[i] != compatible_dims_mapping[i]: + out_dims_mapping[i] = compatible_dims_mapping[i] + changed = True + + # The following which uses negative index can be work + # when len(out_dims_mapping) > 2 and len(out_dims_mapping) <=2 + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, y_dims_mapping], [-1, -2]) + if dim_changed: + changed = True + + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [-2, -2]) + if dim_changed: + changed = True + + dim_changed = compute_compatible_and_update_dim_mapping( + [y_dims_mapping, out_dims_mapping], [-1, -1]) + if dim_changed: + changed = True + + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + + # Remove unnecessary dim mapping to make sure the length of dims_mapping is same as its tensor + if x_dims_mapping_len == 1: + x_dims_mapping.pop(0) + out_dims_mapping.pop(out_dims_mapping_len - 1) + if y_dims_mapping_len == 1: + y_dims_mapping.pop(1) + out_dims_mapping.pop(out_dims_mapping_len) + + assert len(x_dims_mapping) == x_dims_mapping_len + assert len(y_dims_mapping) == y_dims_mapping_len + assert len(out_dims_mapping) == out_dims_mapping_len + + return changed + + +def _is_auto_compatible_for_matmul(dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + out_name = op_desc.output('Out')[0] + trans_x = None + trans_y = None + if op_desc.type() == "matmul_v2": + trans_x = op_desc.attr('trans_x') + trans_y = op_desc.attr('trans_y') + elif op_desc.type() == "matmul": + trans_x = op_desc.attr('transpose_X') + trans_y = op_desc.attr('transpose_Y') + + # Deep copy these dims_mappings for keeping them unchanged. + x_dims_mapping = copy.deepcopy(op_dist_attr.get_input_dims_mapping(x_name)) + y_dims_mapping = copy.deepcopy(op_dist_attr.get_input_dims_mapping(y_name)) + out_dims_mapping = copy.deepcopy( + op_dist_attr.get_output_dims_mapping(out_name)) + x_dims_mapping_len = len(x_dims_mapping) + y_dims_mapping_len = len(y_dims_mapping) + out_dims_mapping_len = len(out_dims_mapping) + + # Add dim mapping to Make sure the length dims_mapping be at least 2 + if x_dims_mapping_len == 1: + x_dims_mapping.insert(0, -1) + if y_dims_mapping_len == 1: + y_dims_mapping.insert(1, -1) + + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + + # Deal with dim > 2 and take care of broadcasting + if out_dims_mapping_len > 2: + broadcast_x_dims_mapping = [] + broadcast_y_dims_mapping = [] + broadcast_out_dims_mapping = [] + + for i in range(out_dims_mapping_len - x_dims_mapping_len): + broadcast_x_dims_mapping.append(out_dims_mapping[i]) + for i in range(x_dims_mapping_len - 2): + broadcast_x_dims_mapping.append(x_dims_mapping[i]) + + for i in range(out_dims_mapping_len - y_dims_mapping_len): + broadcast_y_dims_mapping.append(out_dims_mapping[i]) + for i in range(y_dims_mapping_len - 2): + broadcast_y_dims_mapping.append(y_dims_mapping[i]) + + for i in range(out_dims_mapping_len - 2): + broadcast_out_dims_mapping.append(out_dims_mapping[i]) + + is_same = ((broadcast_x_dims_mapping == broadcast_y_dims_mapping) + and (broadcast_x_dims_mapping == broadcast_out_dims_mapping)) + if not is_same: + return False + + # The following which uses negative index can be work + # when len(out_dims_mapping) > 2 and len(out_dims_mapping) <=2 + is_same = (x_dims_mapping[-1] == y_dims_mapping[-2]) + if not is_same: + return False + + is_same = (x_dims_mapping[-2] == out_dims_mapping[-2]) + if not is_same: + return False + + is_same = (y_dims_mapping[-1] == out_dims_mapping[-1]) + if not is_same: + return False + + return True + + +def _right_operand_parameter_matmul_backward(ctx, *args, **kwargs): + + # by now the backward function only insert the gradient allreduce for dist op itself + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + backward_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(backward_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, dist_attr.process_mesh, rank_id) + + assert 'Y' in kwargs, "input [{}] is not given".format('Y') + assert 'X' in kwargs, "input [{}] is not given".format('X') + assert 'Out@GRAD' in kwargs, "input [{}] is not given".format('Out@GRAD') + assert 'Y@GRAD' in kwargs, "output [{}] is not given".format('Y@GRAD') + assert 'X@GRAD' in kwargs, "output [{}] is not given".format('X@GRAD') + assert len( + kwargs['Y'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['Y']) + assert len( + kwargs['X'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['X']) + assert len( + kwargs['Out@GRAD'] + ) == 1, "row_parallel_embedding input Ids take 1 variable but got {}".format( + kwargs['Out']) + assert len( + kwargs['Y@GRAD'] + ) == 1, "row_parallel_embedding output Ids take 1 variable but got {}".format( + kwargs['Y@GRAD']) + + X_var = main_block.var(kwargs['X'][0]) + Y_var = main_block._var_recursive(kwargs['Y'][0]) + Out_grad = main_block.var(kwargs['Out@GRAD'][0]) + Y_grad = main_block.var(kwargs['Y@GRAD'][0]) + + assert not is_parameter_related( + X_var.name, main_block + ), "left operand(X) [{}] of dist matmul should not be parameter".format( + X_var.name) + + X_var_dims_mapping = dist_attr.get_input_dims_mapping(X_var.name) + Y_var_dim_mapping = dist_attr.get_input_dims_mapping(Y_var.name) + process_mesh_shape = dist_attr.process_mesh.topology + process_mesh_group = dist_attr.process_mesh.processes + + trans_x = None + trans_y = None + if backward_op.desc.type() == "matmul_v2_grad": + trans_x = backward_op.desc.attr('trans_x') + trans_y = backward_op.desc.attr('trans_y') + elif backward_op.desc.type() == "matmul_grad": + trans_x = backward_op.desc.attr('transpose_X') + trans_y = backward_op.desc.attr('transpose_Y') + + if trans_y: + trans_x_y_dims_mapping(False, True, None, Y_var_dim_mapping) + + # assert len( + # Y_var_dim_mapping + # ) == 2, "dist matmual only support Y operand with 2 dims now but Y({})'s dim is [{}]".format( + # Y_var.name, Y_var_dim_mapping) + Y_var_partitioned = False + for dim in Y_var_dim_mapping: + if dim >= 0 and process_mesh_shape[dim] > 0: + Y_var_partitioned = True + break + + if is_parameter_related(Y_var.name, main_block) and Y_var_partitioned: + + if Y_var_dim_mapping[0] >= 0: + # row parallel: c_identity + matmul + assert Y_var_dim_mapping[1] < 0 + parallel_axis = Y_var_dim_mapping[0] + + check_variable_and_dtype( + Out_grad, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], + '_c_identity') + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_identity", 'tmp'])) + "@GRAD", + dtype=Out_grad.dtype, + shape=Out_grad.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=Out_grad.stop_gradient) + + # copy X_var's dist_attr to intermediate_var_0's dist_attr + out_grad_dist_attr = dist_attr.get_input_dist_attr(Out_grad.name) + assert out_grad_dist_attr is not None + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_grad_dist_attr) + + group_ranks = _get_comm_group(process_mesh_group, + process_mesh_shape, parallel_axis, + rank_id) + group = new_process_group(group_ranks) + c_identity_op = main_block.append_op( + type='c_identity', + inputs={'X': [Out_grad]}, + outputs={'Out': intermediate_var_0}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: OpRole.Backward, + }) + check_variable_and_dtype(intermediate_var_0, 'x', + ['float16', 'float32', 'float64'], + 'linear') + check_dtype(intermediate_var_0.dtype, 'dtype', + ['float16', 'float32', 'float64'], 'linear') + set_comm_op_dist_attr_for_program(c_identity_op, + dist_attr.process_mesh, + out_grad_dist_attr, ctx) + + new_kwargs = copy.deepcopy(kwargs) + new_kwargs['Out@GRAD'] = [intermediate_var_0.name] + matmul_op_desc = copy_op_with_new_input_output( + ctx, main_block, backward_op, **new_kwargs) + else: + # col parallel: matmul + allreduce + assert Y_var_dim_mapping[0] < 0 + parallel_axis = Y_var_dim_mapping[1] + new_kwargs = copy.deepcopy(kwargs) + + # NOTE (JZ-LIANG) should allow left operand be empty for matmul grad + has_x_grad = len(kwargs['X@GRAD']) > 0 + if has_x_grad: + assert len(kwargs['X@GRAD']) == 1 + X_grad = main_block.var(kwargs['X@GRAD'][0]) + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_identity", 'tmp'])) + "@GRAD", + dtype=X_grad.dtype, + shape=X_grad.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_grad.stop_gradient) + + X_grad_dist_attr = dist_attr.get_output_dist_attr(X_grad.name) + assert X_grad_dist_attr is not None + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + X_grad_dist_attr) + new_kwargs['X@GRAD'] = [intermediate_var_0.name] + + matmul_op_desc = copy_op_with_new_input_output( + ctx, main_block, backward_op, **new_kwargs) + + # NOTE (JZ-LIANG) trick to skip one allreduce if left operand has not grad + if has_x_grad: + group_ranks = _get_comm_group(process_mesh_group, + process_mesh_shape, parallel_axis, + rank_id) + group = new_process_group(group_ranks) + c_allreduce_sum_op = main_block.append_op( + type='c_allreduce_sum', + inputs={'X': [intermediate_var_0.name]}, + outputs={'Out': kwargs['X@GRAD']}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: OpRole.Backward + }) + set_comm_op_dist_attr_for_program(c_allreduce_sum_op, + dist_attr.process_mesh, + X_grad_dist_attr, ctx) + else: + # replicate + matmul_op_desc = copy_op_with_new_input_output(ctx, main_block, + backward_op, **kwargs) + + # data parallel gradient synchronization + act_grad_names = [X_var.name] + + out_grad_names = [] + if is_parameter_related(Y_var.name, main_block): + out_grad_names = [kwargs['Y@GRAD'][0]] + + if trans_x: + trans_x_y_dims_mapping(True, False, X_var_dims_mapping, None) + + gradient_synchronization(ctx, backward_op, act_grad_names, out_grad_names, + rank_id) + + if trans_x: + trans_x_y_dims_mapping(True, False, X_var_dims_mapping, None) + if trans_y: + trans_x_y_dims_mapping(False, True, None, Y_var_dim_mapping) + + +def _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, rank_id): + + if Weight_var.name in dist_op_context.already_init_sync_vars: + return + assert startup_block.has_var(Weight_var.name) + dist_op_context.already_init_sync_vars.add(Weight_var.name) + param = startup_block.var(Weight_var.name) + param_dist_attr = ctx.get_tensor_dist_attr_for_program(param) + process_mesh = param_dist_attr.process_mesh + dim_mapping = param_dist_attr.dims_mapping + + for axis, size in enumerate(process_mesh.topology): + if size <= 1 or axis in dim_mapping: + pass + else: + group_ranks = _get_comm_group(process_mesh.processes, + process_mesh.topology, axis, rank_id) + sync_group = new_process_group(group_ranks) + + startup_block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': sync_group.id, + 'root': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + + +class DistributedMatmul(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedMatmul, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedMatmul("matmul")) + + +# ColumnParallel +class DistributedMatmulImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + # col parallel: matmul + allreduce + assert Y_var_dim_mapping[0] < 0 + parallel_axis = Y_var_dim_mapping[1] + + has_x_grad = len(backward_op.output("X@GRAD")) > 0 + if has_x_grad: + assert len(backward_op.output("X@GRAD")) == 1 + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # calc comm op cost + if has_x_grad: + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = backward_op.output("X@GRAD") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, + c_allreduce_sum_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulOpCost, ctx, processes, + desc_mapping, cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-1] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = serial_op.input("X") + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res_cost = [comm_op_cost_list, cost_mapping] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(x_name)) + y_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(y_name)) + trans_x = op_desc.attr('transpose_X') + trans_y = op_desc.attr('transpose_Y') + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_dim_shard(y_dims_mapping[-2]) or is_dim_replicate( + y_dims_mapping[-1]): + return False + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_replicate(out_dims_mapping[-1]): + return False + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + if not _is_auto_compatible_for_matmul(dist_op): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block.var(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + trans_x = src_op.attr("transpose_X") + trans_y = src_op.attr("transpose_Y") + + # TODO infer logic comm presentation + matmul_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-1] + if trans_y: + matmul_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-2] + assert matmul_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # infer new var shape with op dist attr + x_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(X_var) + assert x_tensor_dist_attr is not None + identity_var_dist_attr = op_dist_attr.get_input_dist_attr(X_var.name) + assert identity_var_dist_attr is not None + ref_shape_x = infer_shape(main_block, X_var, x_tensor_dist_attr, + identity_var_dist_attr) + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape_out = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_identity", 'tmp'])), + dtype=X_var.dtype, + shape=X_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_var.stop_gradient) + # set intermediate_var_0's dist_attr with X_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + identity_var_dist_attr) + + check_variable_and_dtype( + X_var, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], '_c_identity') + + c_identity_op = main_block.append_op( + type='c_identity', + inputs={'X': [X_var]}, + outputs={'Out': intermediate_var_0}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if intermediate_var_0.shape != ref_shape_x: + intermediate_var_0.desc.set_shape(ref_shape_x) + + check_variable_and_dtype(intermediate_var_0, 'x', + ['float16', 'float32', 'float64'], 'linear') + check_dtype(intermediate_var_0.dtype, 'dtype', + ['float16', 'float32', 'float64'], 'linear') + attrs = { + 'transpose_X': trans_x, + 'transpose_Y': trans_y, + 'alpha': 1, + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': [intermediate_var_0], 'Y': [Weight_var]} + matmul_op = main_block.append_op(type='matmul', + inputs=inputs, + outputs={'Out': Out_var}, + attrs=attrs) + if Out_var.shape != ref_shape_out: + Out_var.desc.set_shape(ref_shape_out) + + # set dist op's dist_attr with serial op's dist_attr + # c_identity + identity_op_dist_attr = OperatorDistributedAttribute() + identity_op_dist_attr.process_mesh = op_dist_attr.process_mesh + identity_op_dist_attr.impl_type = op_dist_attr.impl_type + identity_op_dist_attr.impl_idx = op_dist_attr.impl_idx + # input + input_varname = c_identity_op.desc.input_arg_names()[0] + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + identity_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + # output + output_varname = c_identity_op.desc.output_arg_names()[0] + identity_op_dist_attr.set_output_dist_attr(output_varname, + input_dist_attr) + # set op dist attr + ctx.set_op_dist_attr_for_program(c_identity_op, identity_op_dist_attr) + + # matmul + matmul_op_dist_attr = OperatorDistributedAttribute() + matmul_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmul_op_dist_attr.impl_type = op_dist_attr.impl_type + matmul_op_dist_attr.impl_idx = op_dist_attr.impl_idx + # input + for input_varname in matmul_op.desc.input_arg_names(): + if input_varname in src_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr( + input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmul_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + else: + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program( + input_var) + matmul_op_dist_attr.set_input_dist_attr(input_varname, + tensor_dist_attr) + # output + output_varname = matmul_op.desc.output_arg_names()[0] + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmul_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + # set op dist attr + ctx.set_op_dist_attr_for_program(matmul_op, matmul_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# RowParallel +class DistributedMatmulImpl1(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulImpl1, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + assert Y_var_dim_mapping[1] < 0 + parallel_axis = Y_var_dim_mapping[0] + + # calc comm op cost + var_names = [backward_op.input("Out@GRAD")[0]] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + cost_mapping = build_comp_costs_from_descs(MatmulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulOpCost, ctx, processes, + desc_mapping, cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-2] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + + var_names = serial_op.output("Out") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, c_allreduce_sum_desc_mapping, + cluster) + + res_cost = [cost_mapping, comm_op_cost_list] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(x_name)) + y_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(y_name)) + trans_x = op_desc.attr('transpose_X') + trans_y = op_desc.attr('transpose_Y') + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + if is_dim_replicate(x_dims_mapping[-1]): + return False + if is_dim_replicate(y_dims_mapping[-2]) or is_dim_shard( + y_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_shard(out_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + if not _is_auto_compatible_for_matmul(dist_op): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block.var(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + trans_x = src_op.attr('transpose_X') + trans_y = src_op.attr('transpose_Y') + + # TODO infer logic comm presentation + matmul_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-2] + if trans_y: + matmul_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-1] + assert matmul_row_dim_mapping >= 0, "row_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_row_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_row_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + check_variable_and_dtype(X_var, 'x', ['float16', 'float32', 'float64'], + 'linear') + check_dtype(X_var.dtype, 'dtype', ['float16', 'float32', 'float64'], + 'linear') + attrs = { + 'transpose_X': trans_x, + 'transpose_Y': trans_y, + 'alpha': 1, + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': X_var, 'Y': Weight_var} + + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_allreduce_sum", 'tmp'])), + shape=Out_var.shape, + dtype=Out_var.dtype, + type=Out_var.type, + lod_level=Out_var.lod_level, + persistable=False, + is_data=False, + need_check_feed=Out_var.desc.need_check_feed()) + # set intermediate_var_0's dist_attr with Out_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_var_dist_attr) + + matmul_op = main_block.append_op(type='matmul', + inputs=inputs, + outputs={'Out': intermediate_var_0}, + attrs=attrs) + if intermediate_var_0.shape != ref_shape: + intermediate_var_0.desc.set_shape(ref_shape) + + c_allreduce_sum_op = main_block.append_op( + type='c_allreduce_sum', + inputs={'X': intermediate_var_0}, + outputs={'Out': Out_var}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if Out_var.shape != ref_shape: + Out_var.desc.set_shape(ref_shape) + + # set dist op's dist_attr with serial op's dist_attr + # matmul + matmul_op_dist_attr = OperatorDistributedAttribute() + matmul_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmul_op_dist_attr.impl_type = op_dist_attr.impl_type + matmul_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in matmul_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmul_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + output_varname = matmul_op.desc.output_arg_names()[0] + output_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmul_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(matmul_op, matmul_op_dist_attr) + + # allreduce + allreduce_op_dist_attr = OperatorDistributedAttribute() + allreduce_op_dist_attr.process_mesh = op_dist_attr.process_mesh + allreduce_op_dist_attr.impl_type = op_dist_attr.impl_type + allreduce_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in c_allreduce_sum_op.desc.input_arg_names(): + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(input_var) + assert tensor_dist_attr is not None + allreduce_op_dist_attr.set_input_dist_attr(input_varname, + tensor_dist_attr) + for output_varname in c_allreduce_sum_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + allreduce_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(c_allreduce_sum_op, + allreduce_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# ReplicateParallel +class DistributedMatmulImpl2(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulImpl2, self).__init__(name) + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulOpCost, ctx, processes, + desc_mapping, cluster) + + res_cost = [cost_mapping] + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_valid_list_index(x_dims_mapping, -2) and is_dim_shard( + x_dims_mapping[-2]): + return False + + if is_dim_shard(y_dims_mapping[-1]): + return False + if is_valid_list_index(y_dims_mapping, -2) and is_dim_shard( + y_dims_mapping[-2]): + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if is_dim_shard(out_dims_mapping[-1]): + return False + if is_valid_list_index(out_dims_mapping, -2) and is_dim_shard( + out_dims_mapping[-2]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + if not _is_auto_compatible_for_matmul(dist_op): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("matmul", + DistributedMatmulImpl0("column_parallel")) +register_distributed_operator_impl("matmul", + DistributedMatmulImpl1("row_parallel")) +register_distributed_operator_impl("matmul", + DistributedMatmulImpl2("replicate_parallel")) + + +class DistributedMatmulV2(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedMatmulV2, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedMatmulV2("matmul_v2")) + + +# ColumnParallel +class DistributedMatmulV2Impl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulV2Impl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + # col parallel: matmul + allreduce + if backward_op.attr("trans_y"): + Y_var_dim_mapping.reverse() + assert Y_var_dim_mapping[0] < 0 + parallel_axis = Y_var_dim_mapping[1] + + has_x_grad = len(backward_op.output("X@GRAD")) > 0 + if has_x_grad: + assert len(backward_op.output("X@GRAD")) == 1 + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + + cost_mapping = build_comp_costs_from_descs(MatmulV2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # calc comm op cost + if has_x_grad: + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = backward_op.output("X@GRAD") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, + c_allreduce_sum_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # need gradient allreduce + process_mesh = dist_attr.process_mesh + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + # TODO: trans shape if trans_x or trans_y is True + comp_desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + comp_cost_mapping = build_comp_costs_from_descs(MatmulV2OpCost, ctx, + processes, + comp_desc_mapping, + cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-1] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + + var_names = serial_op.input("X") + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + + res_cost = [comm_op_cost_list, comp_cost_mapping] + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(x_name)) + y_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(y_name)) + trans_x = op_desc.attr('trans_x') + trans_y = op_desc.attr('trans_y') + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_dim_shard(y_dims_mapping[-2]) or is_dim_replicate( + y_dims_mapping[-1]): + return False + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_replicate(out_dims_mapping[-1]): + return False + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + if not _is_auto_compatible_for_matmul(dist_op): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block._var_recursive(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + trans_x = src_op.attr('trans_x') + trans_y = src_op.attr('trans_y') + + # TODO infer logic comm presentation + matmul_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-1] + if trans_y: + matmul_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-2] + assert matmul_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # infer new var shape with op dist attr + x_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(X_var) + assert x_tensor_dist_attr is not None + identity_var_dist_attr = op_dist_attr.get_input_dist_attr(X_var.name) + assert identity_var_dist_attr is not None + ref_shape_x = infer_shape(main_block, X_var, x_tensor_dist_attr, + identity_var_dist_attr) + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape_out = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_identity", 'tmp'])), + dtype=X_var.dtype, + shape=X_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_var.stop_gradient) + # set intermediate_var_0's dist_attr with X_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + identity_var_dist_attr) + + check_variable_and_dtype( + X_var, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], '_c_identity') + c_identity_op = main_block.append_op( + type='c_identity', + inputs={'X': [X_var]}, + outputs={'Out': intermediate_var_0}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role'), + }) + if intermediate_var_0.shape != ref_shape_x: + intermediate_var_0.desc.set_shape(ref_shape_x) + + check_variable_and_dtype(intermediate_var_0, 'x', + ['float16', 'float32', 'float64'], 'linear') + check_dtype(intermediate_var_0.dtype, 'dtype', + ['float16', 'float32', 'float64'], 'linear') + attrs = { + 'trans_x': trans_x, + 'trans_y': trans_y, + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': [intermediate_var_0], 'Y': [Weight_var]} + matmul_v2_op = main_block.append_op(type='matmul_v2', + inputs=inputs, + outputs={'Out': Out_var}, + attrs=attrs) + if Out_var.shape != ref_shape_out: + Out_var.desc.set_shape(ref_shape_out) + + # set dist op's dist_attr with serial op's dist_attr + # c_identity + identity_op_dist_attr = OperatorDistributedAttribute() + identity_op_dist_attr.process_mesh = op_dist_attr.process_mesh + identity_op_dist_attr.impl_type = op_dist_attr.impl_type + identity_op_dist_attr.impl_idx = op_dist_attr.impl_idx + # input + input_varname = c_identity_op.desc.input_arg_names()[0] + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + identity_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + # output + output_varname = c_identity_op.desc.output_arg_names()[0] + identity_op_dist_attr.set_output_dist_attr(output_varname, + input_dist_attr) + ctx.set_op_dist_attr_for_program(c_identity_op, identity_op_dist_attr) + + # matmulv2 + matmulv2_op_dist_attr = OperatorDistributedAttribute() + matmulv2_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmulv2_op_dist_attr.impl_type = op_dist_attr.impl_type + matmulv2_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in matmul_v2_op.desc.input_arg_names(): + if input_varname in src_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr( + input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_input_dist_attr( + input_varname, input_dist_attr) + else: + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program( + input_var) + matmulv2_op_dist_attr.set_input_dist_attr( + input_varname, tensor_dist_attr) + for output_varname in matmul_v2_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(matmul_v2_op, matmulv2_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# RowParallel +class DistributedMatmulV2Impl1(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulV2Impl1, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + assert Y_var_dim_mapping[1] < 0 + parallel_axis = Y_var_dim_mapping[0] + + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + # calc comm op cost + var_names = [backward_op.input("Out@GRAD")[0]] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + cost_mapping = build_comp_costs_from_descs(MatmulV2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + process_mesh = dist_attr.process_mesh + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulV2OpCost, ctx, + processes, desc_mapping, + cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-2] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + + var_names = serial_op.output("Out") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, c_allreduce_sum_desc_mapping, + cluster) + res_cost = [cost_mapping, comm_op_cost_list] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(x_name)) + y_dims_mapping = copy.deepcopy( + op_dist_attr.get_input_dims_mapping(y_name)) + trans_x = op_desc.attr('trans_x') + trans_y = op_desc.attr('trans_y') + trans_x_y_dims_mapping(trans_x, trans_y, x_dims_mapping, y_dims_mapping) + if is_dim_replicate(x_dims_mapping[-1]): + return False + if is_dim_replicate(y_dims_mapping[-2]) or is_dim_shard( + y_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_shard(out_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + if not _is_auto_compatible_for_matmul(dist_op): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block._var_recursive(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + trans_x = src_op.attr('trans_x') + trans_y = src_op.attr('trans_y') + + # TODO infer logic comm presentation + matmul_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-2] + if trans_y: + matmul_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-1] + assert matmul_row_dim_mapping >= 0, "row_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_row_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_row_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + check_variable_and_dtype(X_var, 'x', ['float16', 'float32', 'float64'], + 'linear') + check_dtype(X_var.dtype, 'dtype', ['float16', 'float32', 'float64'], + 'linear') + attrs = { + 'trans_x': trans_x, + 'trans_y': trans_y, + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': X_var, 'Y': Weight_var} + + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_allreduce_sum", 'tmp'])), + shape=Out_var.shape, + dtype=Out_var.dtype, + type=Out_var.type, + lod_level=Out_var.lod_level, + persistable=False, + is_data=False, + need_check_feed=Out_var.desc.need_check_feed()) + # set intermediate_var_0's dist_attr with Out_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_var_dist_attr) + + matmul_v2_op = main_block.append_op(type='matmul_v2', + inputs=inputs, + outputs={'Out': intermediate_var_0}, + attrs=attrs) + if intermediate_var_0.shape != ref_shape: + intermediate_var_0.desc.set_shape(ref_shape) + + c_allreduce_sum_op = main_block.append_op( + type='c_allreduce_sum', + inputs={'X': intermediate_var_0}, + outputs={'Out': Out_var}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if Out_var.shape != ref_shape: + Out_var.desc.set_shape(ref_shape) + + # set dist op's dist_attr with serial op's dist_attr + # matmulv2 + matmulv2_op_dist_attr = OperatorDistributedAttribute() + matmulv2_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmulv2_op_dist_attr.impl_type = op_dist_attr.impl_type + matmulv2_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in matmul_v2_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + output_varname = matmul_v2_op.desc.output_arg_names()[0] + output_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(matmul_v2_op, matmulv2_op_dist_attr) + + # allreduce + allreduce_op_dist_attr = OperatorDistributedAttribute() + allreduce_op_dist_attr.process_mesh = op_dist_attr.process_mesh + allreduce_op_dist_attr.impl_type = op_dist_attr.impl_type + allreduce_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in c_allreduce_sum_op.desc.input_arg_names(): + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(input_var) + assert tensor_dist_attr is not None + allreduce_op_dist_attr.set_input_dist_attr(input_varname, + tensor_dist_attr) + for output_varname in c_allreduce_sum_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + allreduce_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(c_allreduce_sum_op, + allreduce_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# ReplicateParallel +class DistributedMatmulV2Impl2(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMatmulV2Impl2, self).__init__(name) + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + process_mesh = dist_attr.process_mesh + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulV2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MatmulV2OpCost, ctx, + processes, desc_mapping, + cluster) + + res_cost = [cost_mapping] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_valid_list_index(x_dims_mapping, -2) and is_dim_shard( + x_dims_mapping[-2]): + return False + + if is_dim_shard(y_dims_mapping[-1]): + return False + if is_valid_list_index(y_dims_mapping, -2) and is_dim_shard( + y_dims_mapping[-2]): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if is_dim_shard(out_dims_mapping[-1]): + return False + if is_valid_list_index(out_dims_mapping, -2) and is_dim_shard( + out_dims_mapping[-2]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + if not _is_auto_compatible_for_matmul(dist_op): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("matmul_v2", + DistributedMatmulV2Impl0("column_parallel")) +register_distributed_operator_impl("matmul_v2", + DistributedMatmulV2Impl1("row_parallel")) +register_distributed_operator_impl( + "matmul_v2", DistributedMatmulV2Impl2("replicate_parallel")) + + +class DistributedMul(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedMul, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedMul("mul")) + + +# ColumnParallel +class DistributedMulImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMulImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + # col parallel: matmul + allreduce + assert Y_var_dim_mapping[0] < 0 + parallel_axis = Y_var_dim_mapping[1] + + has_x_grad = len(backward_op.output("X@GRAD")) > 0 + if has_x_grad: + assert len(backward_op.output("X@GRAD")) == 1 + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # calc comm op cost + if has_x_grad: + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = backward_op.output("X@GRAD") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, + c_allreduce_sum_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MulOpCost, ctx, processes, + desc_mapping, cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-1] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + var_names = serial_op.input("X") + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res_cost = [comm_op_cost_list, cost_mapping] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_dim_shard(y_dims_mapping[-2]) or is_dim_replicate( + y_dims_mapping[-1]): + return False + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_replicate(out_dims_mapping[-1]): + return False + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + if not _is_auto_compatible_for_matmul(dist_op): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block._var_recursive(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + + # TODO infer logic comm presentation + matmul_col_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-1] + assert matmul_col_dim_mapping >= 0, "col_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_col_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_col_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + # infer new var shape with op dist attr + x_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(X_var) + assert x_tensor_dist_attr is not None + identity_var_dist_attr = op_dist_attr.get_input_dist_attr(X_var.name) + assert identity_var_dist_attr is not None + ref_shape_x = infer_shape(main_block, X_var, x_tensor_dist_attr, + identity_var_dist_attr) + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape_out = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_identity", 'tmp'])), + dtype=X_var.dtype, + shape=X_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_var.stop_gradient) + # set intermediate_var_0's dist_attr with X_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + identity_var_dist_attr) + + check_variable_and_dtype( + X_var, 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], '_c_identity') + c_identity_op = main_block.append_op( + type='c_identity', + inputs={'X': [X_var]}, + outputs={'Out': intermediate_var_0}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + if intermediate_var_0.shape != ref_shape_x: + intermediate_var_0.desc.set_shape(ref_shape_x) + + check_variable_and_dtype(intermediate_var_0, 'x', + ['float16', 'float32', 'float64'], 'linear') + check_dtype(intermediate_var_0.dtype, 'dtype', + ['float16', 'float32', 'float64'], 'linear') + # attrs = {'trans_x': False, 'trans_y': False} + attrs = { + "x_num_col_dims": src_op.desc.attr("x_num_col_dims"), + "y_num_col_dims": src_op.desc.attr("y_num_col_dims"), + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': intermediate_var_0, 'Y': Weight_var} + + inputs_ref_shape = {} + inputs_original_shape = {} + for var_name in inputs: + if var_name == "X": + var = X_var + else: + var = inputs[var_name] + inputs_original_shape[var_name] = var.shape + input_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(var) + input_var_dist_attr = op_dist_attr.get_input_dist_attr(var.name) + input_ref_shape = infer_shape(main_block, var, + input_tensor_dist_attr, + input_var_dist_attr) + inputs_ref_shape[var_name] = input_ref_shape + var.desc.set_shape(input_ref_shape) + + mul_op = main_block.append_op(type='mul', + inputs=inputs, + outputs={'Out': Out_var}, + attrs=attrs) + if Out_var.shape != ref_shape_out: + Out_var.desc.set_shape(ref_shape_out) + + for var_name in inputs: + var = inputs[var_name] + original_shape = inputs_original_shape[var_name] + var.desc.set_shape(original_shape) + + # set dist op's dist_attr with serial op's dist_attr + # c_identity + identity_op_dist_attr = OperatorDistributedAttribute() + identity_op_dist_attr.process_mesh = op_dist_attr.process_mesh + identity_op_dist_attr.impl_type = op_dist_attr.impl_type + identity_op_dist_attr.impl_idx = op_dist_attr.impl_idx + # input + input_varname = c_identity_op.desc.input_arg_names()[0] + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + identity_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + # output + output_varname = c_identity_op.desc.output_arg_names()[0] + identity_op_dist_attr.set_output_dist_attr(output_varname, + input_dist_attr) + ctx.set_op_dist_attr_for_program(c_identity_op, identity_op_dist_attr) + + # matmulv2 + matmulv2_op_dist_attr = OperatorDistributedAttribute() + matmulv2_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmulv2_op_dist_attr.impl_type = op_dist_attr.impl_type + matmulv2_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in mul_op.desc.input_arg_names(): + if input_varname in src_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr( + input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_input_dist_attr( + input_varname, input_dist_attr) + else: + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program( + input_var) + matmulv2_op_dist_attr.set_input_dist_attr( + input_varname, tensor_dist_attr) + for output_varname in mul_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(mul_op, matmulv2_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# RowParallel +class DistributedMulImpl1(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMulImpl1, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # by now the backward function only insert the gradient allreduce for dist op itself + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + main_block = backward_op.block + vars = main_block.vars + Y_var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("Y")[0]) + assert Y_var_dim_mapping[1] < 0 + parallel_axis = Y_var_dim_mapping[0] + + # calc comm op cost + var_names = [backward_op.input("Out@GRAD")[0]] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + c_identity_desc_mapping = build_comm_desc_from_dist_op( + "c_identity", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + processes = process_mesh.processes + comm_op_cost_list = build_comm_costs_from_descs( + IdentityOpCost, ctx, processes, c_identity_desc_mapping, cluster) + res.append(comm_op_cost_list) + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + cost_mapping = build_comp_costs_from_descs(MulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MulOpCost, ctx, processes, + desc_mapping, cluster) + + # calc comm op cost + serial_op = dist_op.serial_op + vars = serial_op.block.vars + + parallel_axis = dist_op.dist_attr.get_input_dims_mapping( + serial_op.input("Y")[0])[-2] + attrs = {"use_calc_stream": True, "use_model_parallel": True} + + var_names = serial_op.output("Out") + c_allreduce_sum_desc_mapping = build_comm_desc_from_dist_op( + "c_allreduce_sum", + dist_op, + ctx, + var_names, + attrs=attrs, + parallel_axis=parallel_axis) + + # print("dist_matmul.py dist_op: ", dist_op) + comm_op_cost_list = build_comm_costs_from_descs( + AllreduceSumOpCost, ctx, processes, c_allreduce_sum_desc_mapping, + cluster) + + res_cost = [cost_mapping, comm_op_cost_list] + + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + if is_dim_replicate(x_dims_mapping[-1]): + return False + if is_dim_replicate(y_dims_mapping[-2]) or is_dim_shard( + y_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in x_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_shard(out_dims_mapping[-1]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in out_dims_mapping[1:-1]: + if is_dim_shard(mapping): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + if not _is_auto_compatible_for_matmul(dist_op): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # FIXME (JZ-LIANG) Remove this hack to support any op mesh group for Pipeline Parallelism + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Weight_var = main_block._var_recursive(kwargs['Y'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + + # TODO infer logic comm presentation + matmul_row_dim_mapping = op_dist_attr.get_input_dims_mapping( + Weight_var.name)[-2] + assert matmul_row_dim_mapping >= 0, "row_parallel_matmul's row should be divided by a specific mesh axis, but got [{}]".format( + matmul_row_dim_mapping) + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + + parallel_axis = matmul_row_dim_mapping + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + parallel_axis, rank_id) + group = new_process_group(group_ranks) + + check_variable_and_dtype(X_var, 'x', ['float16', 'float32', 'float64'], + 'linear') + check_dtype(X_var.dtype, 'dtype', ['float16', 'float32', 'float64'], + 'linear') + # attrs = {'trans_x': False, 'trans_y': False} + attrs = { + "x_num_col_dims": src_op.desc.attr("x_num_col_dims"), + "y_num_col_dims": src_op.desc.attr("y_num_col_dims"), + OP_ROLE_KEY: src_op.attr('op_role') + } + inputs = {'X': X_var, 'Y': Weight_var} + + # infer out var shape with op dist attr + out_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(Out_var) + assert out_tensor_dist_attr is not None + out_var_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert out_var_dist_attr is not None + ref_shape = infer_shape(main_block, Out_var, out_tensor_dist_attr, + out_var_dist_attr) + + intermediate_var_0 = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ["c_allreduce_sum", 'tmp'])), + shape=Out_var.shape, + dtype=Out_var.dtype, + type=Out_var.type, + lod_level=Out_var.lod_level, + persistable=False, + is_data=False, + need_check_feed=Out_var.desc.need_check_feed()) + # set intermediate_var_0's dist_attr with Out_var's dist_attr + ctx.set_tensor_dist_attr_for_program(intermediate_var_0, + out_var_dist_attr) + + inputs_ref_shape = {} + inputs_original_shape = {} + for var_name in inputs: + var = inputs[var_name] + inputs_original_shape[var_name] = var.shape + input_tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(var) + input_var_dist_attr = op_dist_attr.get_input_dist_attr(var.name) + input_ref_shape = infer_shape(main_block, var, + input_tensor_dist_attr, + input_var_dist_attr) + inputs_ref_shape[var_name] = input_ref_shape + var.desc.set_shape(input_ref_shape) + + mul_op = main_block.append_op(type='mul', + inputs=inputs, + outputs={'Out': intermediate_var_0}, + attrs=attrs) + + if intermediate_var_0.shape != ref_shape: + intermediate_var_0.desc.set_shape(ref_shape) + + for var_name in inputs: + var = inputs[var_name] + original_shape = inputs_original_shape[var_name] + var.desc.set_shape(original_shape) + + c_allreduce_sum_op = main_block.append_op( + type='c_allreduce_sum', + inputs={'X': intermediate_var_0}, + outputs={'Out': Out_var}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'use_model_parallel': True, + OP_ROLE_KEY: src_op.attr('op_role') + }) + + if Out_var.shape != ref_shape: + Out_var.desc.set_shape(ref_shape) + + # set dist op's dist_attr with serial op's dist_attr + # matmulv2 + matmulv2_op_dist_attr = OperatorDistributedAttribute() + matmulv2_op_dist_attr.process_mesh = op_dist_attr.process_mesh + matmulv2_op_dist_attr.impl_type = op_dist_attr.impl_type + matmulv2_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in mul_op.desc.input_arg_names(): + input_dist_attr = op_dist_attr.get_input_dist_attr(input_varname) + assert input_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_input_dist_attr(input_varname, + input_dist_attr) + output_varname = mul_op.desc.output_arg_names()[0] + output_dist_attr = op_dist_attr.get_output_dist_attr(Out_var.name) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + matmulv2_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(mul_op, matmulv2_op_dist_attr) + + # allreduce + allreduce_op_dist_attr = OperatorDistributedAttribute() + allreduce_op_dist_attr.process_mesh = op_dist_attr.process_mesh + allreduce_op_dist_attr.impl_type = op_dist_attr.impl_type + allreduce_op_dist_attr.impl_idx = op_dist_attr.impl_idx + for input_varname in c_allreduce_sum_op.desc.input_arg_names(): + input_var = main_block.var(input_varname) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(input_var) + assert tensor_dist_attr is not None + allreduce_op_dist_attr.set_input_dist_attr(input_varname, + tensor_dist_attr) + for output_varname in c_allreduce_sum_op.desc.output_arg_names(): + output_dist_attr = op_dist_attr.get_output_dist_attr(output_varname) + assert output_dist_attr is not None, "dist_attr is {}".format( + op_dist_attr) + allreduce_op_dist_attr.set_output_dist_attr(output_varname, + output_dist_attr) + ctx.set_op_dist_attr_for_program(c_allreduce_sum_op, + allreduce_op_dist_attr) + + # init param sync + if Weight_var.is_parameter and not op_dist_attr.is_recompute: + _init_param_sync(Weight_var, dist_op_context, startup_block, ctx, + rank_id) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +# ReplicateParallel +class DistributedMulImpl2(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedMulImpl2, self).__init__(name) + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Forward): + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + elif int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + res = [] + backward_op = dist_op.serial_op + dist_attr = dist_op.dist_attr + main_block = backward_op.block + vars = main_block.vars + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MulGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + # need gradient allreduce + var_dim_mapping = dist_attr.get_input_dims_mapping( + backward_op.input("X")[0]) + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[ + batch_size_axis] > 1 and is_parameter_related( + backward_op.input("Y")[0], main_block): + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [backward_op.output('Y@GRAD')[0]] + build_dp_costs(res, dist_op, ctx, var_names, attrs, parallel_axis, + cluster) + + return res + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(MulOpCost, ctx, processes, + desc_mapping, cluster) + + res_cost = [cost_mapping] + return res_cost + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + y_name = op_desc.input('Y')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + y_dims_mapping = op_dist_attr.get_input_dims_mapping(y_name) + + if is_dim_shard(x_dims_mapping[-1]): + return False + if is_valid_list_index(x_dims_mapping, -2) and is_dim_shard( + x_dims_mapping[-2]): + return False + if is_dim_shard(y_dims_mapping[-1]): + return False + if is_valid_list_index(y_dims_mapping, -2) and is_dim_shard( + y_dims_mapping[-2]): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if is_dim_shard(out_dims_mapping[-1]): + return False + if is_valid_list_index(out_dims_mapping, -2) and is_dim_shard( + out_dims_mapping[-2]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + if not _is_auto_compatible_for_matmul(dist_op): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + dim_changed = _update_dims_mapping_for_matmul(dist_op) + if dim_changed: + changed = True + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + _right_operand_parameter_matmul_backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("mul", + DistributedMulImpl0("column_parallel")) +register_distributed_operator_impl("mul", DistributedMulImpl1("row_parallel")) +register_distributed_operator_impl("mul", + DistributedMulImpl2("replicate_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_pnorm.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_pnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..77efa7fe67d82bea4f9dd3aed10e85eab5113239 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_pnorm.py @@ -0,0 +1,313 @@ +# Copyright (c) 2022 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. + +import copy +import paddle +import paddle.fluid.layers.utils as utils + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .common import set_comm_op_dist_attr_for_program +from .dist_default import DistributedDefaultImpl0 +from ..process_group import new_process_group +from ..utils import is_dim_shard, is_dim_replicate, _get_corresponding_rank +from ..utils import compute_compatible_dim_mapping, set_dist_op_desc_original_id, _get_comm_group +from ..dist_attribute import TensorDistributedAttribute, OperatorDistributedAttribute + +from paddle.fluid import core, unique_name +from paddle.fluid.framework import Operator +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype + + +class DistributedPNorm(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedPNorm, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedPNorm("p_norm")) + + +# Row Parallel +class DistributedPNormImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedPNormImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + if is_dim_replicate(x_dims_mapping[0]): + return False + # Other dimensions must be replicate except the batch dimension + for mapping in x_dims_mapping[1:]: + if is_dim_shard(mapping): + return False + return True + + def is_output_compatible(self, dist_op): + return True + + def is_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)) or \ + (not self.is_compatible(dist_op)): + return False + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + batch_dim_mappings = [] + for arg_name in op_desc.input_arg_names(): + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + for arg_name in op_desc.output_arg_names(): + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if len(dims_mapping) >= 1: + batch_dim_mappings.append(dims_mapping[0]) + + compatible_dim_mapping = compute_compatible_dim_mapping( + batch_dim_mappings) + if compatible_dim_mapping is None: + return False + + for arg_name in op_desc.input_arg_names(): + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if len(dims_mapping + ) >= 1 and compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + for arg_name in op_desc.output_arg_names(): + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if len(dims_mapping + ) >= 1 and compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + if rank_id not in op_dist_attr.process_mesh.processes: + rank_id = _get_corresponding_rank(ctx, op_dist_attr.process_mesh, + rank_id) + + X_var = main_block.var(kwargs['X'][0]) + in_dims_mapping = op_dist_attr.get_input_dims_mapping(X_var.name) + for axis in range(len(in_dims_mapping)): + if in_dims_mapping[axis] != -1: + break + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + group_ranks = _get_comm_group(process_mesh_group, process_mesh_shape, + axis, rank_id) + group = new_process_group(group_ranks) + + check_variable_and_dtype(X_var, 'x', ['float16', 'float32', 'float64'], + 'norm') + check_dtype(X_var.dtype, 'dtype', ['float16', 'float32', 'float64'], + 'norm') + + # 2. insert c_allgather op + # create c_allgather output var + allgather_out = main_block.create_var( + name=".".join(["c_allgather", X_var.name]), + dtype=X_var.dtype, + shape=X_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_var.stop_gradient) + # set allgather_out tensor dist_attr + allgather_out_dist_attr = TensorDistributedAttribute() + allgather_out_dist_attr.process_mesh = op_dist_attr.process_mesh + allgather_out_dist_attr.dims_mapping = [ + -1 for i in range(len(allgather_out.shape)) + ] + ctx.set_tensor_dist_attr_for_program(allgather_out, + allgather_out_dist_attr) + c_allgather_op = main_block.append_op(type='c_allgather', + inputs={'X': [X_var]}, + outputs={'Out': [allgather_out]}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'nranks': group.nranks, + 'op_role': + src_op.attr('op_role') + }) + # set c_allgather op dist_attr + allgather_op_dist_attr = OperatorDistributedAttribute() + allgather_op_dist_attr.process_mesh = op_dist_attr.process_mesh + allgather_op_dist_attr.set_input_dims_mapping(X_var.name, + in_dims_mapping) + allgather_op_dist_attr.set_output_dims_mapping( + allgather_out.name, allgather_out_dist_attr.dims_mapping) + ctx.set_op_dist_attr_for_program(c_allgather_op, allgather_op_dist_attr) + + # 3. copy p_norm op desc and reset input name + # rename input + kwargs['X'] = [allgather_out.name] + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(dist_op_desc, src_op.desc, ctx) + for input_name in src_op.desc.input_names(): + dist_op_desc.set_input(input_name, kwargs[input_name]) + for output_name in src_op.desc.output_names(): + dist_op_desc.set_output(output_name, kwargs[output_name]) + pnorm_op = Operator(main_block, dist_op_desc) + op_dist_attr.set_input_dims_mapping( + allgather_out.name, allgather_out_dist_attr.dims_mapping) + ctx.set_op_dist_attr_for_program(pnorm_op, op_dist_attr) + + @staticmethod + def backward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + backward_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert op_dist_attr is not None + + # check validation of inputs / outputs + for input_name in backward_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + backward_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in backward_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + backward_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + X_grad_var = main_block.var(kwargs['X@GRAD'][0]) + + # 1. copy p_norm_grad op and reset input name and output name + new_kwargs = copy.deepcopy(kwargs) + new_kwargs['X'] = [".".join(["c_allgather", X_var.name])] + new_X_var = main_block.var(new_kwargs['X'][0]) + new_X_grad = main_block.create_var( + name=".".join(["c_allgather", X_grad_var.name]), + dtype=X_grad_var.dtype, + shape=new_X_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=X_grad_var.stop_gradient) + new_kwargs['X@GRAD'] = [new_X_grad.name] + new_X_var_dist_attr = ctx.get_tensor_dist_attr_for_program(new_X_var) + ctx.set_tensor_dist_attr_for_program(new_X_grad, new_X_var_dist_attr) + # replicate op in dist program with new kwargs + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(backward_op.desc) + # Refer to the related dist op + set_dist_op_desc_original_id(dist_op_desc, backward_op.desc, ctx) + for input_name in backward_op.desc.input_names(): + dist_op_desc.set_input(input_name, new_kwargs[input_name]) + for output_name in backward_op.desc.output_names(): + dist_op_desc.set_output(output_name, new_kwargs[output_name]) + p_norm_grad_op = Operator(main_block, dist_op_desc) + op_dist_attr.set_input_dims_mapping(new_X_var.name, + new_X_var_dist_attr.dims_mapping) + op_dist_attr.set_output_dims_mapping(new_X_grad.name, + new_X_var_dist_attr.dims_mapping) + ctx.set_op_dist_attr_for_program(p_norm_grad_op, op_dist_attr) + + # 2. insert slice op + process_mesh_shape = op_dist_attr.process_mesh.topology + process_mesh_group = op_dist_attr.process_mesh.processes + dims_mapping = [0] + [-1 for _ in range(len(new_X_grad.shape) - 1)] + from ..reshard import Resharder + + partition_idx = Resharder.compute_partition_index( + rank_id, new_X_grad.shape, dims_mapping, process_mesh_shape, + process_mesh_group) + slice_starts = [] + slice_ends = [] + slices_axes = [] + for idx, item in enumerate(partition_idx): + slice_starts.append(item[0]) + slice_ends.append(item[1]) + slices_axes.append(idx) + + infer_flags = list(1 for i in range(len(slices_axes))) + attrs = { + "axes": slices_axes, + "starts": slice_starts, + "ends": slice_ends, + "infer_flags": infer_flags, + "op_role": backward_op.attr('op_role') + } + slice_op = main_block.append_op(type='slice', + inputs={'Input': [new_X_grad]}, + outputs={'Out': [X_grad_var]}, + attrs=attrs) + X_grad_var_dims_mapping = op_dist_attr.get_output_dims_mapping( + X_grad_var.name) + slice_op_dist_attr = OperatorDistributedAttribute() + slice_op_dist_attr.process_mesh = op_dist_attr.process_mesh + slice_op_dist_attr.set_input_dims_mapping( + new_X_grad.name, new_X_var_dist_attr.dims_mapping) + slice_op_dist_attr.set_output_dims_mapping(X_grad_var.name, + X_grad_var_dims_mapping) + ctx.set_op_dist_attr_for_program(slice_op, slice_op_dist_attr) + + +register_distributed_operator_impl("p_norm", + DistributedPNormImpl("row_parallel")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reduce_sum_p.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reduce_sum_p.py new file mode 100644 index 0000000000000000000000000000000000000000..6b53b2eed7ad00eb9a351a290027572dedae36e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reduce_sum_p.py @@ -0,0 +1,153 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl, is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..utils import set_dist_op_desc_original_id +from ..dist_attribute import OperatorDistributedAttribute +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from ..process_group import new_process_group +from ..utils import _get_comm_group, _get_corresponding_rank + + +class DistributedReduceSumPrimtive(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedReduceSumPrimtive, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedReduceSumPrimtive("reduce_sum_p")) + + +# Batch Dimension ReduceSum Primitive +class DistributedReduceSumPrimtiveImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedReduceSumPrimtiveImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + return len(op_desc.input_arg_names()) == 1 + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + outputs = op_desc.output_arg_names() + + if len(outputs) != 1: + return False + + output_name = outputs[0] + output_var = dist_op.serial_op.block.var(output_name) + if output_var.shape != (1, ): + return False + + return True + + def is_auto_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + + return self.is_input_compatible(dist_op) and self.is_output_compatible( + dist_op) + + def update_dims_mapping(self, dist_op): + changed = False + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + startup_block = dist_op_context.startup_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(dist_op_desc, src_op.desc, ctx) + for input_name in src_op.desc.input_names(): + dist_op_desc.set_input(input_name, kwargs[input_name]) + for output_name in src_op.desc.output_names(): + dist_op_desc.set_output(output_name, kwargs[output_name]) + + # batch dimension synchronization + var_name = src_op.output_arg_names[0] + sync_group = new_process_group(ctx.data_parallel_group) + allreduce_op = main_block.append_op(type='c_allreduce_sum', + inputs={'X': [var_name]}, + outputs={'Out': [var_name]}, + attrs={ + 'ring_id': sync_group.id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + + # dist attr + var = main_block.var(var_name) + tensor_dist_attr = ctx.get_tensor_dist_attr_for_program(var) + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + new_op_attr = OperatorDistributedAttribute() + new_op_attr.process_mesh = op_dist_attr.process_mesh + new_op_attr.set_output_dims_mapping(var.name, + tensor_dist_attr.dims_mapping) + new_op_attr.set_input_dims_mapping(var.name, + tensor_dist_attr.dims_mapping) + ctx.set_op_dist_attr_for_program(allreduce_op, new_op_attr) + + @staticmethod + def backward(ctx, *args, **kwargs): + raise RuntimeError( + "primitive operator does NOT have backward function, op type: {}". + format(str(op.type))) + + +register_distributed_operator_impl( + "reduce_sum_p", + DistributedReduceSumPrimtiveImpl0("batch_dimension_reduce_sum_p")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reshape.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reshape.py new file mode 100644 index 0000000000000000000000000000000000000000..d896667008c1ec73f80a156cfc4bbed630b1f3c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_reshape.py @@ -0,0 +1,744 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl, is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from ..utils import set_dist_op_desc_original_id +from paddle.fluid import core, unique_name +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from .dist_default import DistributedDefaultImpl0 +from ..cost import build_comp_desc_from_dist_op, build_comp_costs_from_descs +from ..cost import build_comm_costs_from_descs +from ..cost import Reshape2OpCost +from ..cost import Reshape2GradOpCost +from paddle.distributed.fleet.meta_optimizers.common import OpRole + + +class DistributedReshape2(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedReshape2, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedReshape2("reshape2")) + + +class DistributedReshapeImpl0(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedReshapeImpl0, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = False + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + res = [] + op = dist_op.serial_op + vars = op.block.vars + dist_attr = dist_op.dist_attr + + shape_list = op.desc.attr("shape") + # got dist attribute info + dim_mapping = dist_attr.get_output_dims_mapping(op.output("Out")[0]) + process_mesh_shape = dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_attr.process_mesh.processes + for key in desc_mapping: + desc_mapping[key]["shape"] = shape_list + + cost_mapping = build_comp_costs_from_descs(Reshape2OpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + return res + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + op_type = dist_op.serial_op.type + + cost_mapping = build_comp_costs_from_descs(Reshape2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + backward_op = dist_op.serial_op + main_block = backward_op.block + need_gradient_allreduce = False + vars = main_block.vars + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and is_parameter_related( + varname, main_block): + # NOTE input var's dim_mapping of backward op should be the same with input var instead of corresponding varname of forward op + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping) - 1: + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping) - 1: + return False + + if is_dim_shard(out_dims_mapping[-1]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + for idx, dim_mapping in enumerate(out_dims_mapping[:-1]): + if x_dims_mapping[idx] != dim_mapping: + return False + + if x_shape_dims_mapping[0] != -1: + return False + + if x_shape_dims_mapping[1:] != x_dims_mapping[:]: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + for i in range(len(x_dims_mapping)): + x_shape_dims_mapping[i + 1] = x_dims_mapping[i] + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + XShape_var = main_block.var(kwargs['XShape'][0]) + shape_list = src_op.desc.attr("shape") + ShapeTensor_var_list = [] + for name in kwargs['ShapeTensor']: + ShapeTensor_var_list.append(name) + Shape_var_list = [] + for name in kwargs['Shape']: + Shape_var_list.append(name) + + # got dist attribute info + dim_mapping = op_dist_attr.get_output_dims_mapping(Out_var.name) + process_mesh_shape = op_dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # create op + new_op_desc = main_block.append_op(type='nop').desc + new_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(new_op_desc, src_op.desc, ctx) + new_op_desc.set_input('ShapeTensor', ShapeTensor_var_list) + new_op_desc.set_input('Shape', Shape_var_list) + new_op_desc.set_input('X', [X_var.name]) + new_op_desc.set_output('XShape', [XShape_var.name]) + new_op_desc.set_output('Out', [Out_var.name]) + new_op_desc._set_attr('shape', shape_list) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +class DistributedReshapeImpl1(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedReshapeImpl1, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = False + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + res = [] + op = dist_op.serial_op + vars = op.block.vars + dist_attr = dist_op.dist_attr + + shape_list = op.desc.attr("shape") + # got dist attribute info + dim_mapping = dist_attr.get_output_dims_mapping(op.output("Out")[0]) + process_mesh_shape = dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_attr.process_mesh.processes + for key in desc_mapping: + desc_mapping[key]["shape"] = shape_list + + cost_mapping = build_comp_costs_from_descs(Reshape2OpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + return res + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + op_type = dist_op.serial_op.type + + cost_mapping = build_comp_costs_from_descs(Reshape2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + backward_op = dist_op.serial_op + main_block = backward_op.block + need_gradient_allreduce = False + vars = main_block.vars + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and not is_parameter_related( + varname, main_block): + # NOTE input var's dim_mapping of backward op should be the same with input var instead of corresponding varname of forward op + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping) + 1: + return False + + if is_dim_shard(x_dims_mapping[-1]): + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping) + 1: + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + + if is_dim_shard(x_dims_mapping[-1]): + return False + + for idx, item in enumerate(x_dims_mapping[:-1]): + if out_dims_mapping[idx] != item: + return False + + if x_shape_dims_mapping[0] != -1: + return False + + if x_shape_dims_mapping[1:] != x_dims_mapping[:]: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + + for i in range(len(out_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + for i in range(len(x_dims_mapping)): + x_shape_dims_mapping[i + 1] = x_dims_mapping[i] + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + src_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + XShape_var = main_block.var(kwargs['XShape'][0]) + shape_list = src_op.desc.attr("shape") + ShapeTensor_var_list = [] + for name in kwargs['ShapeTensor']: + ShapeTensor_var_list.append(name) + Shape_var_list = [] + for name in kwargs['Shape']: + Shape_var_list.append(name) + + # got dist attribute info + dim_mapping = op_dist_attr.get_output_dims_mapping(Out_var.name) + process_mesh_shape = op_dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # create op + new_op_desc = main_block.append_op(type='nop').desc + new_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(new_op_desc, src_op.desc, ctx) + new_op_desc.set_input('ShapeTensor', ShapeTensor_var_list) + new_op_desc.set_input('Shape', Shape_var_list) + new_op_desc.set_input('X', [X_var.name]) + new_op_desc.set_output('XShape', [XShape_var.name]) + new_op_desc.set_output('Out', [Out_var.name]) + new_op_desc._set_attr('shape', shape_list) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +class DistributedReshapeImpl2(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedReshapeImpl2, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = False + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + res = [] + op = dist_op.serial_op + vars = op.block.vars + dist_attr = dist_op.dist_attr + + shape_list = op.desc.attr("shape") + # got dist attribute info + dim_mapping = dist_attr.get_output_dims_mapping(op.output("Out")[0]) + process_mesh_shape = dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_attr.process_mesh.processes + for key in desc_mapping: + desc_mapping[key]["shape"] = shape_list + + cost_mapping = build_comp_costs_from_descs(Reshape2OpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + return res + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + op_type = dist_op.serial_op.type + + cost_mapping = build_comp_costs_from_descs(Reshape2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + backward_op = dist_op.serial_op + main_block = backward_op.block + need_gradient_allreduce = False + vars = main_block.vars + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and not is_parameter_related( + varname, main_block): + # NOTE input var's dim_mapping of backward op should be the same with input var instead of corresponding varname of forward op + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping): + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + x_name = op_desc.input('X')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + if len(x_dims_mapping) != len(out_dims_mapping): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + + for idx, item in enumerate(x_dims_mapping[:-1]): + if out_dims_mapping[idx] != item: + return False + + if x_shape_dims_mapping[0] != -1: + return False + + if x_shape_dims_mapping[1:] != out_dims_mapping[:]: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + + for i in range(len(out_dims_mapping) - 1): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + for i in range(len(out_dims_mapping)): + x_shape_dims_mapping[i + 1] = out_dims_mapping[i] + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + """ + kwargs: inputname_mapping & outputname_mapping + """ + + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.work_block + src_op = dist_op_context.cur_src_op + op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) + assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(src_op)) + + # check validation of inputs / outputs + for input_name in src_op.desc.input_names(): + assert input_name in kwargs, "input [{}] is not given".format( + input_name) + assert len(kwargs[input_name]) == len( + src_op.desc.input(input_name) + ), "number of tensor for input [{}] is not match".format(input_name) + for output_name in src_op.desc.output_names(): + assert output_name in kwargs, "input [{}] is not given".format( + output_name) + assert len(kwargs[output_name]) == len( + src_op.desc.output(output_name) + ), "number of tensor for input [{}] is not match".format( + output_name) + + X_var = main_block.var(kwargs['X'][0]) + Out_var = main_block.var(kwargs['Out'][0]) + XShape_var = main_block.var(kwargs['XShape'][0]) + shape_list = src_op.desc.attr("shape") + ShapeTensor_var_list = [] + for name in kwargs['ShapeTensor']: + ShapeTensor_var_list.append(name) + Shape_var_list = [] + for name in kwargs['Shape']: + Shape_var_list.append(name) + + # got dist attribute info + out_dim_mapping = op_dist_attr.get_output_dims_mapping(Out_var.name) + process_mesh_shape = op_dist_attr.process_mesh.topology + + # modify target shape + for idx, axis in enumerate(out_dim_mapping): + if axis >= 0: + if len(shape_list) > idx: + shape_list[ + idx] = shape_list[idx] // process_mesh_shape[axis] + + # create op + new_op_desc = main_block.append_op(type='nop').desc + new_op_desc.copy_from(src_op.desc) + set_dist_op_desc_original_id(new_op_desc, src_op.desc, ctx) + new_op_desc.set_input('ShapeTensor', ShapeTensor_var_list) + new_op_desc.set_input('Shape', Shape_var_list) + new_op_desc.set_input('X', [X_var.name]) + new_op_desc.set_output('XShape', [XShape_var.name]) + new_op_desc.set_output('Out', [Out_var.name]) + new_op_desc._set_attr('shape', shape_list) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("reshape2", + DistributedReshapeImpl0("add_one_dim_back")) +register_distributed_operator_impl( + "reshape2", DistributedReshapeImpl1("remove_one_dim_back")) +register_distributed_operator_impl("reshape2", + DistributedReshapeImpl2("same_dim_shape")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_shape.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..313f296ab96246061056cb5d2da801bea610add0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_shape.py @@ -0,0 +1,73 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .dist_default import DistributedDefaultImpl0 +from ..utils import is_dim_shard + + +class DistributedShape(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedShape, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedShape("shape")) + + +class DistributedShapeImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedShapeImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + assert len(out_dims_mapping) == 1 + if is_dim_shard(out_dims_mapping[0]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + return True + + def update_dims_mapping(self, dist_op): + return False + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("shape", DistributedShapeImpl("shape")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_slice.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_slice.py new file mode 100644 index 0000000000000000000000000000000000000000..a37421ce6124749e7f5da7de0516108591c60ee3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_slice.py @@ -0,0 +1,161 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import is_dim_shard +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 + + +class DistributedSlice(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedSlice, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedSlice("slice")) + + +class DistributedSliceImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedSliceImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + in_name = op_desc.input('Input')[0] + axes = op_desc.attr('axes') + in_dims_mapping = op_dist_attr.get_input_dims_mapping(in_name) + for axis in axes: + if is_dim_shard(in_dims_mapping[axis]): + return False + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + in_name = op_desc.input('Input')[0] + out_name = op_desc.output('Out')[0] + axes = op_desc.attr('axes') + decrease_axis = op_desc.attr('decrease_axis') + in_dims_mapping = op_dist_attr.get_input_dims_mapping(in_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + ref_indices = [] + for i in range(len(in_dims_mapping)): + if i not in decrease_axis: + ref_indices.append(i) + if ref_indices == []: + assert len(out_dims_mapping) == 1 + if is_dim_shard(out_dims_mapping[0]): + return False + else: + for i in range(len(out_dims_mapping)): + ref_index = ref_indices[i] + if ref_index in axes and is_dim_shard(out_dims_mapping[i]): + return False + + return True + + def is_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + in_name = op_desc.input('Input')[0] + out_name = op_desc.output('Out')[0] + decrease_axis = op_desc.attr('decrease_axis') + in_dims_mapping = op_dist_attr.get_input_dims_mapping(in_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if len(in_dims_mapping) - len(decrease_axis) != 0 and len( + out_dims_mapping) != len(in_dims_mapping) - len(decrease_axis): + return False + + new_out_dims_mapping = [] + for i in range(len(in_dims_mapping)): + if i not in decrease_axis: + new_out_dims_mapping.append(in_dims_mapping[i]) + if new_out_dims_mapping == []: + new_out_dims_mapping = [-1] + if new_out_dims_mapping != out_dims_mapping: + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)) or \ + (not self.is_compatible(dist_op)): + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + in_name = op_desc.input('Input')[0] + out_name = op_desc.output('Out')[0] + decrease_axis = op_desc.attr('decrease_axis') + in_dims_mapping = op_dist_attr.get_input_dims_mapping(in_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + ref_dims_mapping = [] + ref_indices = [] + for i in range(len(in_dims_mapping)): + if i not in decrease_axis: + ref_dims_mapping.append(in_dims_mapping[i]) + ref_indices.append(i) + + if ref_dims_mapping == []: + ref_dims_mapping = [-1] + assert len(ref_dims_mapping) == len(out_dims_mapping) + assert ref_dims_mapping[0] == out_dims_mapping[0] + changed = False + else: + assert len(ref_dims_mapping) == len(out_dims_mapping) + for i in range(len(out_dims_mapping)): + compatible_dim_mapping = compute_compatible_dim_mapping( + [out_dims_mapping[i], ref_dims_mapping[i]]) + if compatible_dim_mapping is None: + continue + if ref_dims_mapping[i] != compatible_dim_mapping: + in_dims_mapping[ref_indices[i]] = compatible_dim_mapping + changed = True + if out_dims_mapping[i] != compatible_dim_mapping: + out_dims_mapping[i] = compatible_dim_mapping + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("slice", + DistributedSliceImpl("decrease_in_axis")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_softmax.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..890eb670def09564832843c5ee83487c6ee0d24f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_softmax.py @@ -0,0 +1,184 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .common import is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 +from ..cost import _g_op_cost_factory +from ..cost import build_comp_desc_from_dist_op, build_dp_costs +from ..cost import build_comp_costs_from_descs +from ..cost import SoftmaxOpCost, SoftmaxGradOpCost +from paddle.distributed.fleet.meta_optimizers.common import OpRole +from paddle.distributed.auto_parallel.cost.comm_op_cost import AllreduceSumOpCost + + +class DistributedSoftmax(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedSoftmax, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedSoftmax("softmax")) + + +class DistributedSoftmaxImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedSoftmaxImpl, self).__init__(name) + self._forward_implemented = False + self._backward_implemented = False + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + cost_mapping = build_comp_costs_from_descs(SoftmaxOpCost, ctx, + processes, desc_mapping, + cluster) + + res_cost = [cost_mapping] + return res_cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + cost_mapping = build_comp_costs_from_descs(SoftmaxGradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + backward_op = dist_op.serial_op + main_block = backward_op.block + need_gradient_allreduce = False + vars = main_block.vars + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and is_parameter_related( + varname, main_block): + # NOTE input var's dim_mapping of backward op should be the same with input var instead of corresponding varname of forward op + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + + return res + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + axis = op_desc.attr('axis') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + + # if axis != -1 and axis != len(x_dims_mapping) - 1: + # return False + + if is_dim_shard(x_dims_mapping[axis]): + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_name = op_desc.output('Out')[0] + axis = op_desc.attr('axis') + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + # if axis != -1 and axis != len(out_dims_mapping) - 1: + # return False + + if is_dim_shard(out_dims_mapping[axis]): + return False + + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + axis = op_desc.attr('axis') + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + # if axis != -1 and axis != len(x_dims_mapping) - 1: + # return False + + if x_dims_mapping != out_dims_mapping: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + return changed + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl( + "softmax", DistributedSoftmaxImpl("replicate_last_axis")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_split.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_split.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7c680d7921d3437ae964816d48209a77fd792c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_split.py @@ -0,0 +1,121 @@ +# Copyright (c) 2022 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. + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import is_dim_shard +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 + + +class DistributedSplit(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedSplit, self).__init__(op_type) + + +register_distributed_operator_impl_container(DistributedSplit("split")) + + +class DistributedSplitImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedSplitImpl, self).__init__(name) + self._forward_implemented = True + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + axis = op_desc.attr('axis') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + + if is_dim_shard(x_dims_mapping[axis]): + return False + + return True + + def is_output_compatible(self, dist_op): + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + out_names = op_desc.output('Out') + axis = op_desc.attr('axis') + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if is_dim_shard(out_dims_mapping[axis]): + return False + + return True + + def is_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + axis = op_desc.attr('axis') + out_names = op_desc.output('Out') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + if x_dims_mapping != out_dims_mapping: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_names = op_desc.output('Out') + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + + for out_name in out_names: + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + for i in range(len(x_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [x_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + return changed + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)) or \ + (not self.is_compatible(dist_op)): + return False + + return True + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl("split", + DistributedSplitImpl("replicate_in_axis")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_transpose.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_transpose.py new file mode 100644 index 0000000000000000000000000000000000000000..88024f3777fb953d28d30363f42a4a840916d8ce --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_transpose.py @@ -0,0 +1,192 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from .common import is_parameter_related +from ..utils import is_dim_shard +from ..utils import is_dim_replicate +from ..utils import is_valid_list_index +from ..utils import compute_compatible_dim_mapping +from ..utils import compute_compatible_dims_mapping +from ..utils import compute_compatible_and_update_dim_mapping +from .dist_default import DistributedDefaultImpl0 +from ..cost import Transpose2OpCost, Transpose2GradOpCost +from ..cost import build_comp_desc_from_dist_op, build_comm_desc_from_dist_op, build_dp_costs +from ..cost import build_comp_costs_from_descs +from paddle.distributed.fleet.meta_optimizers.common import OpRole +from paddle.distributed.auto_parallel.cost.comm_op_cost import AllreduceSumOpCost + + +class DistributedTranspose2(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedTranspose2, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedTranspose2("transpose2")) + + +class DistributedTranspose2Impl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedTranspose2Impl, self).__init__(name) + self._forward_implemented = False + self._backward_implemented = False + + def is_input_compatible(self, dist_op): + return True + + def is_output_compatible(self, dist_op): + return True + + def is_auto_compatible(self, dist_op): + if (not self.is_input_compatible(dist_op)) or \ + (not self.is_output_compatible(dist_op)): + return False + + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + perm = op_desc.attr('axis') + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + new_dims_mapping = [-1 for i in range(len(x_dims_mapping))] + for i in range(len(x_dims_mapping)): + new_dims_mapping[i] = x_dims_mapping[perm[i]] + + if len(x_dims_mapping) != len(out_dims_mapping): + return False + + if new_dims_mapping != out_dims_mapping: + return False + + if x_shape_dims_mapping[0] != -1: + return False + + if x_shape_dims_mapping[1:] != x_dims_mapping[:]: + return False + + return True + + def update_dims_mapping(self, dist_op): + changed = False + op_desc = dist_op.serial_op.desc + op_dist_attr = dist_op.dist_attr + x_name = op_desc.input('X')[0] + out_name = op_desc.output('Out')[0] + x_shape_name = op_desc.output('XShape')[0] + x_dims_mapping = op_dist_attr.get_input_dims_mapping(x_name) + out_dims_mapping = op_dist_attr.get_output_dims_mapping(out_name) + x_shape_dims_mapping = op_dist_attr.get_output_dims_mapping( + x_shape_name) + perm = op_desc.attr('axis') + + assert len(x_dims_mapping) == len(perm) + + new_dims_mapping = [-1 for i in range(len(x_dims_mapping))] + for i in range(len(x_dims_mapping)): + new_dims_mapping[i] = x_dims_mapping[perm[i]] + + for i in range(len(out_dims_mapping)): + dim_changed = compute_compatible_and_update_dim_mapping( + [new_dims_mapping, out_dims_mapping], [i, i]) + if dim_changed: + changed = True + + for i in range(len(x_dims_mapping)): + if x_dims_mapping[perm[i]] != new_dims_mapping[i]: + x_dims_mapping[perm[i]] = new_dims_mapping[i] + changed = True + + for i in range(len(x_dims_mapping)): + x_shape_dims_mapping[i + 1] = x_dims_mapping[i] + + return changed + + def calc_cost(self, op_role, dist_op, ctx, cluster): + cost = None + if int(op_role) == int(OpRole.Backward): + cost = self.calc_bwd_cost(dist_op, ctx, cluster) + else: + cost = self.calc_fwd_cost(dist_op, ctx, cluster) + assert cost is not None + return cost + + def calc_fwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + processes = dist_op.dist_attr.process_mesh.processes + op_type = dist_op.serial_op.type + cost_mapping = build_comp_costs_from_descs(Transpose2OpCost, ctx, + processes, desc_mapping, + cluster) + + res_cost = [cost_mapping] + return res_cost + + def calc_bwd_cost(self, dist_op, ctx, cluster): + # calc comp op cost + res = [] + desc_mapping = build_comp_desc_from_dist_op(dist_op=dist_op, + dist_context=ctx) + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + processes = process_mesh.processes + op_type = dist_op.serial_op.type + cost_mapping = build_comp_costs_from_descs(Transpose2GradOpCost, ctx, + processes, desc_mapping, + cluster) + res.append(cost_mapping) + + backward_op = dist_op.serial_op + main_block = backward_op.block + need_gradient_allreduce = False + vars = main_block.vars + for input_name in backward_op.desc.input_names(): + for varname in backward_op.desc.input(input_name): + if "@GRAD" not in varname and is_parameter_related( + varname, main_block): + # NOTE input var's dim_mapping of backward op should be the same with input var instead of corresponding varname of forward op + var_dim_mapping = dist_attr.get_input_dims_mapping(varname) + + mesh_shape = process_mesh.topology + batch_size_axis = var_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + parallel_axis = batch_size_axis + attrs = {"use_calc_stream": True} + var_names = [varname + "@GRAD"] + build_dp_costs(res, dist_op, ctx, var_names, attrs, + parallel_axis, cluster) + return res + + @staticmethod + def forward(ctx, *args, **kwargs): + DistributedDefaultImpl0.forward(ctx, *args, **kwargs) + + @staticmethod + def backward(ctx, *args, **kwargs): + DistributedDefaultImpl0.backward(ctx, *args, **kwargs) + + +register_distributed_operator_impl( + "transpose2", DistributedTranspose2Impl("same_mapping_transpose")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_update_loss_scaling.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_update_loss_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbcaef5ee47f667935e90e647dd667fa8200b1d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/operators/dist_update_loss_scaling.py @@ -0,0 +1,139 @@ +# Copyright (c) 2021 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 + +from .common import DistributedOperatorImplContainer +from .common import DistributedOperatorImpl +from .common import register_distributed_operator_impl_container +from .common import register_distributed_operator_impl +from ..utils import set_dist_op_desc_original_id + + +class DistributedUpdateLossScaling(DistributedOperatorImplContainer): + + def __init__(self, op_type): + super(DistributedUpdateLossScaling, self).__init__(op_type) + + +register_distributed_operator_impl_container( + DistributedUpdateLossScaling("update_loss_scaling")) + + +class DistributedUpdateLossScalingImpl(DistributedOperatorImpl): + + def __init__(self, name): + super(DistributedUpdateLossScalingImpl, self).__init__(name) + self._name = name + self._forward_implemented = False + self._backward_implemented = True + + def is_input_compatible(self, dist_op): + raise RuntimeError( + "DistributedUpdateLossScalingImpl's is_input_compatible should not be called !" + ) + + def is_output_compatible(self, dist_op): + raise RuntimeError( + "DistributedUpdateLossScalingImpl's is_output_compatible should not be called !" + ) + + def is_auto_compatible(self, dist_op): + raise RuntimeError( + "DistributedUpdateLossScalingImpl's is_auto_compatible should not be called !" + ) + + def update_dims_mapping(self, dist_op): + raise RuntimeError( + "DistributedUpdateLossScalingImpl's update_dims_mapping should not be called !" + ) + + @staticmethod + def forward(ctx, *args, **kwargs): + raise RuntimeError( + "DistributedUpdateLossScalingImpl's forward should not be called !") + + @staticmethod + def backward(ctx, *args, **kwargs): + + # the backward function only filte the gradient with current rank id + dist_op_context = ctx.dist_op_context + main_block = dist_op_context.main_block + backward_op = dist_op_context.cur_src_op + rank_id = dist_op_context.rank_id + dist_attr = ctx.get_op_dist_attr_for_program(backward_op) + assert dist_attr is not None, "backward op [{}] don't have dist attribute !".format( + str(backward_op)) + + assert rank_id in dist_attr.process_mesh.processes + + assert 'X' in kwargs, "input [{}] is not given".format('X') + assert 'FoundInfinite' in kwargs, "input [{}] is not given".format( + 'FoundInfinite') + assert 'PrevLossScaling' in kwargs, "input [{}] is not given".format( + 'PrevLossScaling') + assert 'InGoodSteps' in kwargs, "input [{}] is not given".format( + 'InGoodSteps') + assert 'InBadSteps' in kwargs, "input [{}] is not given".format( + 'InBadSteps') + + assert 'Out' in kwargs, "output [{}] is not given".format('Out') + assert 'LossScaling' in kwargs, "output [{}] is not given".format( + 'LossScaling') + assert 'OutGoodSteps' in kwargs, "output [{}] is not given".format( + 'OutGoodSteps') + assert 'OutBadSteps' in kwargs, "output [{}] is not given".format( + 'OutBadSteps') + + assert len(kwargs['FoundInfinite']) == 1, \ + "update_loss_scaling input FoundInfinite take 1 variable but got {}".format( + kwargs['FoundInfinite']) + assert len(kwargs['PrevLossScaling']) == 1, \ + "update_loss_scaling input PrevLossScaling take 1 variable but got {}".format( + kwargs['PrevLossScaling']) + assert len(kwargs['InGoodSteps']) == 1, \ + "update_loss_scaling input InGoodSteps take 1 variable but got {}".format( + kwargs['InGoodSteps']) + assert len(kwargs['InBadSteps']) == 1, \ + "update_loss_scaling input InBadSteps take 1 variable but got {}".format( + kwargs['InBadSteps']) + assert len(kwargs['LossScaling']) == 1, \ + "update_loss_scaling output LossScaling take 1 variable but got {}".format( + kwargs['LossScaling']) + assert len(kwargs['OutGoodSteps']) == 1, \ + "update_loss_scaling output OutGoodSteps take 1 variable but got {}".format( + kwargs['OutGoodSteps']) + assert len(kwargs['OutBadSteps']) == 1, \ + "update_loss_scaling output OutBadSteps take 1 variable but got {}".format( + kwargs['OutBadSteps']) + + assert len(kwargs['X']) == len(kwargs['Out']), \ + "update_loss_scaling got [{}] X and [{}] Out, which are supposed to be equal".format( + len(kwargs['X']), len(kwargs['Out'])) + + filter_vars = [] + for varname in kwargs['X']: + if rank_id in ctx.get_tensor_dist_attr_for_program( + main_block.var(varname)).process_mesh.processes: + filter_vars.append(varname) + + # replicate op in dist program + dist_op_desc = main_block.append_op(type='nop').desc + dist_op_desc.copy_from(backward_op.desc) + set_dist_op_desc_original_id(dist_op_desc, backward_op.desc, ctx) + dist_op_desc.set_input('X', filter_vars) + dist_op_desc.set_output('Out', filter_vars) + + +register_distributed_operator_impl( + "update_loss_scaling", + DistributedUpdateLossScalingImpl("update_loss_scaling")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer.py new file mode 100644 index 0000000000000000000000000000000000000000..75fb3d1ec5200333071f0ca01c3f4881e03308dc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer.py @@ -0,0 +1,436 @@ +# Copyright (c) 2021 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. + +import os +import sys +import json +import shlex +import copy +import pathlib +import subprocess +import logging +import pickle +import time +import paddle +import paddle.fluid.core as core +from paddle.fluid import program_guard +from paddle.fluid.backward import append_backward +from paddle.distributed.utils.log_utils import get_logger +from paddle.distributed.passes import new_pass, PassContext +from .dist_context import DistributedContext +from .dist_context import set_default_distributed_context +from .completion import Completer +from .partitioner import Partitioner +from .process_group import get_all_process_groups +from .process_group import get_process_group +from .process_group import get_world_process_group +from .process_group import _g_process_group_map, ProcessGroup +from .utils import make_data_unshard +from .utils import set_grad_var_shape +from .utils import SerialProgramInfo +from .reshard import Resharder +from .cluster import Cluster +from .mapper import mapping +from .dist_op import DistributedOperator +from .dist_tensor import DistributedTensor +from .planner import Planner + +_logger = get_logger(logging.INFO) + + +class AutoParallelizer: + """ + AutoParallelizer is the main controller class to do the auto parallel process. + And the auto parallel process will be triggered in the wrapped parallelize function. + To facilitate the auto parallelization, it will contain information about program, cluster and the + related context. In this basic version, the program information will be retrevied from + Fleet object, and the cluster information can be retrevied in the new created Cluster object, + and the context information can be retrevied in the new created DistributedContext. + """ + + def __init__(self, fleet): + self._fleet = fleet + self._optimizer = self._fleet.user_defined_optimizer + self._dist_strategy = self._fleet._user_defined_strategy + self._dist_context = DistributedContext() + self._cluster = None + self._cluster_topo_path = os.getenv("PADDLE_CLUSTER_TOPO_PATH", None) + if self._cluster_topo_path is not None: + self._cluster = Cluster() + self._cluster.build_from_file(self._cluster_topo_path) + # Prepare information for auto mapping + self._rank_mapping_path = os.getenv("PADDLE_RANK_MAPPING_PATH", None) + enable_auto_mapping_env = os.getenv("PADDLE_ENABLE_AUTO_MAPPING", None) + if enable_auto_mapping_env is None: + self._enable_auto_mapping = False + else: + self._enable_auto_mapping = True + self._pass_context = PassContext() + + self._need_rank_mapping = os.getenv("PADDLE_NEED_RANK_MAPPING") + self._need_rank_mapping = True if self._need_rank_mapping and \ + self._need_rank_mapping.lower() == 'true' else False + # self._pass_context = None + + def _remove_distributed_attrs(self, main_program): + suffix = core.kAutoParallelSuffix() + # distributed attributes for variable have been removed + # in previous process. + for block in main_program.blocks: + for op in block.ops: + for attr_name in op.attr_names: + if suffix in attr_name: + op._remove_attr(attr_name) + + def _apply_pre_optimization_passes(self, main_program, startup_program, + loss, params_grads, no_grad_set): + # apply amp pass + if self._dist_strategy.amp: + config = copy.deepcopy(self._dist_strategy.amp_configs) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["loss"] = loss + if config["use_pure_fp16"]: + config["base_opt"] = self._optimizer + auto_parallel_fp16_pass = new_pass("auto_parallel_fp16", config) + auto_parallel_fp16_pass.apply([main_program], [startup_program], + self._pass_context) + else: + auto_parallel_amp_pass = new_pass("auto_parallel_amp", config) + auto_parallel_amp_pass.apply([main_program], [startup_program], + self._pass_context) + + # apply recompute pass + if self._dist_strategy.recompute: + config = copy.deepcopy(self._dist_strategy.recompute_configs) + config["dist_context"] = self._dist_context + config["no_grad_set"] = copy.deepcopy(no_grad_set) + config["loss"] = loss + auto_parallel_recompute_pass = new_pass("auto_parallel_recompute", + config) + auto_parallel_recompute_pass.apply([main_program], + [startup_program], + self._pass_context) + + def _generate_backward(self, main_program, startup_program, loss, + parameter_list, no_grad_set, callbacks): + + with program_guard(main_program, startup_program): + params_grads = append_backward( + loss, + parameter_list, + no_grad_set, + callbacks, + distop_context=self._dist_context.dist_op_context) + self._completer = Completer(self._dist_context) + self._completer.complete_backward_annotation(main_program) + self._dist_context.block_state.parse_backward_blocks(main_program) + return params_grads + + def _apply_optimize(self, main_program, startup_program, params_grads): + + optimizer = copy.deepcopy(self._optimizer) + with program_guard(main_program, startup_program): + optimize_ops = optimizer.apply_gradients(params_grads) + + self._dist_context._serial_optimizer = optimizer + # update completion + self._completer = Completer(self._dist_context) + self._completer.complete_update_annotation(main_program) + + return optimize_ops + + def _apply_post_optimization_passes(self, main_program, startup_program, + rank, params_grads): + + if self._dist_strategy.sharding: + config = copy.deepcopy(self._dist_strategy.sharding_configs) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["global_rank"] = rank + auto_parallel_sharding_pass = new_pass("auto_parallel_sharding", + config) + auto_parallel_sharding_pass.apply([main_program], [startup_program], + self._pass_context) + params_grads = self._pass_context.get_attr("params_grads") + + config = copy.deepcopy(self._dist_strategy.sharding_configs) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["rank_id"] = rank + auto_parallel_clip_pass = new_pass("auto_parallel_grad_clip", config) + auto_parallel_clip_pass.apply([main_program], [startup_program], + self._pass_context) + + if self._dist_strategy.gradient_merge: + config = copy.deepcopy(self._dist_strategy.gradient_merge_configs) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + auto_parallel_gradient_merge_pass = new_pass( + "auto_parallel_gradient_merge_pass", config) + auto_parallel_gradient_merge_pass.apply([main_program], + [startup_program], + self._pass_context) + + def _get_dist_program(self, rank, dist_context=None, relaunch_phase=False): + completed_main_program = None + serial_main_program = self._main_program.clone() + serial_startup_program = self._startup_program.clone() + serial_loss = serial_main_program.global_block().var(self._loss.name) + + # generating serial + if dist_context is None: + # Annotation completion + self._dist_context = DistributedContext() + _logger.info("Start annotation dist attr.") + self._completer = Completer(self._dist_context) + completed_main_program = self._completer.complete_forward_annotation( + serial_main_program) + else: + completed_main_program = serial_main_program + self._dist_context = copy.deepcopy(dist_context) + + # parse forward sub block + self._dist_context.block_state.parse_forward_blocks(serial_main_program) + + # serial backward pass + params_grads = self._generate_backward( + completed_main_program, serial_startup_program, serial_loss, + self._parameter_list, self._no_grad_set, self._callbacks) + + # serial forward pass + self._apply_pre_optimization_passes(completed_main_program, + serial_startup_program, serial_loss, + params_grads, self._no_grad_set) + # Logical partition + partitioner = Partitioner(self._dist_context, rank) + dist_main_prog, dist_startup_prog, dist_params_grads = partitioner.partition( + completed_main_program, serial_startup_program, params_grads) + + # TODO refactor the placement of optimizer + # generate optimize program + dist_optimize_ops = self._apply_optimize(dist_main_prog, + dist_startup_prog, + dist_params_grads) + + set_grad_var_shape(dist_main_prog, self._dist_context) + + make_data_unshard(dist_main_prog, dist_startup_prog, self._dist_context) + + resharder = Resharder(dist_main_prog, dist_startup_prog, rank, + self._dist_context, dist_params_grads) + resharder.reshard() + + self._apply_post_optimization_passes(dist_main_prog, dist_startup_prog, + rank, dist_params_grads) + g_process_group_map = None + if not relaunch_phase: + g_process_group_map = copy.deepcopy(_g_process_group_map) + _g_process_group_map.clear() + _g_process_group_map[0] = ProcessGroup(0, []) + for process_mesh in self._dist_context._process_meshes: + _g_process_group_map[0].add_ranks(process_mesh.processes) + return dist_optimize_ops, dist_params_grads, dist_startup_prog, dist_main_prog, g_process_group_map + + def parallelize(self, + loss, + startup_program, + parameter_list=None, + no_grad_set=None, + callbacks=None): + assert startup_program is not None + self._loss = loss + self._startup_program = startup_program + self._main_program = loss.block.program + self._parameter_list = parameter_list + self._no_grad_set = no_grad_set + self._callbacks = callbacks + + if self._enable_auto_mapping and self._need_rank_mapping: + # Do the mapping pass before parallelization + assert self._cluster is not None, \ + "The cluster must not be none when using auto mapping." + dist_programs = {} + world_process_group = get_world_process_group() + dist_context = None + # auto search + if self._dist_strategy.auto_search: + logging.info("Start searching dist attr.") + serial_program_info = SerialProgramInfo(self._main_program, + self._startup_program, + self._loss, + self._optimizer, + self._cluster) + planner = Planner(serial_program_info, + self, + algorithm_config={ + "name": "mcmc", + "max_search_times": 5 + }) + dist_context, _ = planner.search() + logging.info("End searching dist attr.") + + # serialize the dist context by planner + if dist_context is not None: + logging.info("Start serialize searched dist attr") + cwd = pathlib.Path().resolve() + searched_dist_context_path = os.path.join( + cwd, f"searched_dist_context_{time.time()}.pkl") + saved_dist_context = {} + ops_dist_attr = {} + tensors_dist_attr = {} + for key, dist_op in dist_context._dist_ops_for_program.items(): + ops_dist_attr[key] = dist_op.dist_attr + for key, dist_tensor in dist_context._dist_tensors_for_program.items( + ): + tensors_dist_attr[key] = dist_tensor.dist_attr + saved_dist_context["ops_dist_attr"] = ops_dist_attr + saved_dist_context["tensors_dist_attr"] = tensors_dist_attr + saved_dist_context[ + "process_meshes"] = dist_context._process_meshes + with open(searched_dist_context_path, + "wb") as dist_context_file: + pickle.dump(saved_dist_context, dist_context_file) + os.environ[ + 'PADDLE_SEARCHED_DIST_CONTEXT_PATH'] = searched_dist_context_path + logging.info( + f"End serialize searched dist attr to {searched_dist_context_path}" + ) + + for rank in world_process_group.ranks: + dist_optimize_ops, dist_params_grads, dist_startup_prog, dist_main_prog, g_process_group_map = self._get_dist_program( + rank, dist_context) + dist_programs[rank] = [dist_main_prog, g_process_group_map] + + # Do the mapping between the distributed program graph and the cluster graph + rank_mapping_dict = mapping(dist_programs, self._cluster) + rank_mapping = list(rank_mapping_dict.values()) + + # Relaunch the training by using the rank mapping file + with open(self._rank_mapping_path, "w") as rank_mapping_file: + json.dump(rank_mapping, rank_mapping_file) + + enable_elastic = os.getenv("PADDLE_ENABLE_ELASTIC") + enable_elastic = True if enable_elastic and enable_elastic.lower( + ) == 'true' else False + if enable_elastic: + print("Auto mapping finished, now do elastic re-launch") + sys.exit(paddle.distributed.fleet.elastic.manager. + ELASTIC_AUTO_PARALLEL_EXIT_CODE) + + original_cmd_args = os.getenv("PADDLE_ORIGINAL_CMD_ARGS") + rank_mapping_args = " ".join( + ["--rank_mapping_path", self._rank_mapping_path]) + if os.environ.get("WITH_COVERAGE", "OFF") == "ON": + coverage_args = ["-m", "coverage", "run", "--branch", "-p"] + else: + coverage_args = [] + new_cmd_args = "-m paddle.distributed.fleet.launch" + " " + rank_mapping_args + " " + original_cmd_args + new_cmd = [sys.executable, "-u" + ] + coverage_args + shlex.split(new_cmd_args) + new_process = subprocess.Popen(new_cmd) + new_process.wait() + assert new_process.returncode == 0, \ + "Launch failed with rank mapping" + print("Successfully do the second launch for auto mapping!") + sys.exit(0) + else: + # Parallelization after the mapping pass + rank = paddle.distributed.get_rank() + dist_context = None + searched_dist_context_path = os.getenv( + "PADDLE_SEARCHED_DIST_CONTEXT_PATH", None) + if searched_dist_context_path is not None: + with open(searched_dist_context_path, + "rb") as dist_context_file: + saved_dist_context = pickle.load(dist_context_file) + dist_context = DistributedContext() + for op in self._main_program.global_block().ops: + dist_attr = saved_dist_context["ops_dist_attr"][ + op.desc.id()] + dist_op = DistributedOperator(op, dist_attr) + dist_context.add_dist_op_for_program(dist_op) + + vars = self._main_program.global_block().vars + for var in vars.values(): + dist_attr = saved_dist_context["tensors_dist_attr"][ + var.desc.id()] + dist_tensor = DistributedTensor(var, dist_attr) + dist_context.add_dist_tensor_for_program(dist_tensor) + + dist_context._process_meshes = saved_dist_context[ + "process_meshes"] + + else: + if self._dist_strategy.auto_search: + serial_program_info = SerialProgramInfo( + self._main_program, + self._startup_program, + self._loss, + self._optimizer, + cluster=self._cluster) + planner = Planner(serial_program_info, + self, + algorithm_config={ + "name": "mcmc", + "max_search_times": 5 + }) + dist_context, _ = planner.search() + + # rebuild g_process_group + if dist_context is not None: + pg0 = get_process_group(0) + for process_mesh in dist_context._process_meshes: + pg0.add_ranks(process_mesh.processes) + dist_optimize_ops, dist_params_grads, dist_startup_prog, dist_main_prog, _ = self._get_dist_program( + rank, dist_context, relaunch_phase=True) + + # NOTE: This is a trick to fix hang in pipeline mode when dist context is searched by planner + if self._dist_strategy.auto_search: + is_pipeline = False + for op in dist_main_prog.global_block().ops: + if op.type == "send_v2" or op.type == "recv_v2": + is_pipeline = True + break + if is_pipeline: + with paddle.static.program_guard(dist_main_prog): + paddle.distributed.barrier() + + # Traverse different rank programs and traverse each op of them, + # instantiate communication by process_mapping. + all_process_groups = get_all_process_groups() + for process_group in all_process_groups: + if rank not in process_group.ranks: + continue + process_group.instantiate() + + # Copy distributed info to the default context + set_default_distributed_context(self._dist_context) + + # The last step: remove all distributed attributes to be compatible + # with inference. + self._remove_distributed_attrs(dist_main_prog) + + return dist_optimize_ops, dist_params_grads, dist_startup_prog, dist_main_prog + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k == "_main_program" or k == "_startup_program" or k == "_dist_context" or k == "_fleet" or k == "_loss": + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer_v2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..e87c401055e754e27485d776afffe4d19443d29a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/parallelizer_v2.py @@ -0,0 +1,250 @@ +# Copyright (c) 2022 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. + +import copy +import time +import logging + +from paddle.fluid import program_guard +from paddle.fluid.backward import append_backward +from paddle.fluid.framework import unique_name +from paddle.distributed.passes import new_pass + +from .reshard import Resharder +from .partitioner import Partitioner +from .utils import set_grad_var_shape +from .process_group import get_world_process_group +from ..utils.log_utils import get_logger + + +class Parallelizer: + + def __init__(self, mode, completer, dist_context): + self._mode = mode + self._completer = completer + self._dist_context = dist_context + assert self._dist_context._is_initialized + self._pass_context = self._dist_context.pass_context + self._strategy = self._dist_context.strategy + self._logger = get_logger(logging.INFO) + + def parallel_all(self): + world_process_group = get_world_process_group() + all_ranks = world_process_group.ranks + for rank in all_ranks: + # self._dist_context._backup(serial=True, dist=True) + self.parallel(rank) + # self._dist_context._restore(serial=True, dist=True) + + def parallel(self, rank): + serial_main_program = self._dist_context.serial_main_program + serial_startup_program = self._dist_context.serial_startup_program + serial_optimizer = self._dist_context.serial_optimizer + if self._mode == "train" and serial_optimizer: + # Generate backward + serial_loss = self._dist_context.serial_loss + params_grads = self._generate_backward(serial_main_program, + serial_startup_program, + serial_loss) + # Apply pre optimization passes + time0 = time.time() + serial_main_program, serial_startup_program, params_grads = self._apply_pre_optimization( + serial_main_program, serial_startup_program, serial_loss, + serial_optimizer, params_grads) + self._logger.debug( + "within parallel apply_pre_optimization time: {}, mode {}". + format(time.time() - time0, self._mode)) + # Do logical partition + time0 = time.time() + partitioner = Partitioner(self._dist_context, rank) + dist_main_prog, dist_startup_prog, dist_params_grads = partitioner.partition( + serial_main_program, serial_startup_program, params_grads) + self._logger.debug( + "within parallel partitioner time: {}, mode {}".format( + time.time() - time0, self._mode)) + # Generate optimizer + time0 = time.time() + self._generate_optimizer(dist_main_prog, dist_startup_prog, + serial_optimizer, dist_params_grads) + self._logger.debug( + "within parallel optimizer time: {}, mode {}".format( + time.time() - time0, self._mode)) + # Do reshard process + time0 = time.time() + set_grad_var_shape(dist_main_prog, self._dist_context) + resharder = Resharder(dist_main_prog, dist_startup_prog, rank, + self._dist_context, dist_params_grads) + resharder.reshard() + self._logger.debug( + "within parallel reshard time: {}, mode {}".format( + time.time() - time0, self._mode)) + # Apply post optimization passes + time0 = time.time() + self._apply_post_optimization(dist_main_prog, dist_startup_prog, + rank, dist_params_grads) + self._logger.debug( + "within parallel apply_post_optimization time: {}, mode {}". + format(time.time() - time0, self._mode)) + else: + # Apply pre optimization passes + time0 = time.time() + self._apply_pre_optimization(serial_main_program, + serial_startup_program, None, None, + None) + self._logger.debug( + "within parallel apply_pre_optimization time: {}, mode {}". + format(time.time() - time0, self._mode)) + # Do logical partition + time0 = time.time() + partitioner = Partitioner(self._dist_context, rank) + dist_main_prog, dist_startup_prog, dist_params_grads = partitioner.partition( + serial_main_program, serial_startup_program, []) + # Do reshard process + self._logger.debug( + "within parallel partitioner time: {}, mode {}".format( + time.time() - time0, self._mode)) + time0 = time.time() + resharder = Resharder(dist_main_prog, dist_startup_prog, rank, + self._dist_context, [], 1) + resharder.reshard() + self._logger.debug( + "within parallel reshard time: {}, mode {}".format( + time.time() - time0, self._mode)) + # Clone program for test + if self._mode != 'train': + dist_main_prog = dist_main_prog.clone(for_test=True) + dist_startup_prog = dist_startup_prog.clone(for_test=True) + + # Store the distributed programs for further usages + self._dist_context.dist_main_programs[rank] = dist_main_prog + self._dist_context.dist_startup_programs[rank] = dist_startup_prog + + def _generate_backward(self, main_program, startup_program, loss): + with program_guard(main_program, startup_program): + params_grads = append_backward( + loss, distop_context=self._dist_context.dist_op_context) + self._completer.complete_backward_annotation(main_program) + self._dist_context.block_state.parse_backward_blocks(main_program) + return params_grads + + def _generate_optimizer(self, main_program, startup_program, optimizer, + params_grads): + # NOTE: `apply_gradients` will add an Accumulator for a parameter only once, + # but optimizer will be called repeatedly in re-launch, so optimizer need to be copied. + optimizer = copy.deepcopy(optimizer) + self._dist_context._serial_optimizer = optimizer + with program_guard(main_program, startup_program): + with unique_name.guard("opt_"): + optimizer_ops = optimizer.apply_gradients(params_grads) + self._completer.complete_update_annotation(main_program) + return optimizer_ops + + def _apply_pre_optimization(self, main_program, startup_program, loss, + optimizer, params_grads): + if self._strategy is None: + return + + # apply quantization pass + # The pass can be applied when mode must be 'train' + if self._mode == 'train' and self._strategy.qat.enable: + config = copy.deepcopy(self._strategy.qat.to_dict()) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + auto_parallel_quantization_pass = new_pass( + "auto_parallel_quantization", config) + auto_parallel_quantization_pass.apply([main_program], + [startup_program], + self._pass_context) + main_program = self._pass_context.get_attr("main_program") + startup_program = self._pass_context.get_attr("startup_program") + params_grads = self._pass_context.get_attr("params_grads") + + # apply amp pass on train/eval/predict + if self._strategy.amp.enable: + config = copy.deepcopy(self._strategy.amp.to_dict()) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["loss"] = loss + config["input_data"] = self._dist_context.serial_feed_vars["inputs"] \ + + self._dist_context.serial_feed_vars["labels"] + if config["use_pure_fp16"]: + config["base_opt"] = optimizer + auto_parallel_fp16_pass = new_pass("auto_parallel_fp16", config) + auto_parallel_fp16_pass.apply([main_program], [startup_program], + self._pass_context) + else: + auto_parallel_amp_pass = new_pass("auto_parallel_amp", config) + auto_parallel_amp_pass.apply([main_program], [startup_program], + self._pass_context) + + # apply recompute pass + # recompute is then train-only optimization + if self._mode == "train" and self._strategy.recompute.enable: + config = copy.deepcopy(self._strategy.recompute.to_dict()) + config["dist_context"] = self._dist_context + config["no_grad_set"] = None + config["loss"] = loss + auto_parallel_recompute_pass = new_pass("auto_parallel_recompute", + config) + auto_parallel_recompute_pass.apply([main_program], + [startup_program], + self._pass_context) + + return main_program, startup_program, params_grads + + def _apply_post_optimization(self, main_program, startup_program, rank, + params_grads): + if self._strategy is None: + return + + # data parallel optimization + config = {} + config["dist_context"] = self._dist_context + config["global_rank"] = rank + config["use_sharding"] = self._strategy.sharding.enable + dp_pass = new_pass("auto_parallel_data_parallel_optimization", config) + dp_pass.apply([main_program], [startup_program], self._pass_context) + + if self._strategy.sharding.enable: + config = copy.deepcopy(self._strategy.sharding.to_dict()) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["global_rank"] = rank + auto_parallel_sharding_pass = new_pass("auto_parallel_sharding", + config) + auto_parallel_sharding_pass.apply([main_program], [startup_program], + self._pass_context) + params_grads = self._pass_context.get_attr("params_grads") + + # GradClip is train-only optimization + if self._mode == "train": + config = copy.deepcopy(self._strategy.sharding.to_dict()) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + config["rank_id"] = rank + auto_parallel_clip_pass = new_pass("auto_parallel_grad_clip", + config) + auto_parallel_clip_pass.apply([main_program], [startup_program], + self._pass_context) + + # gradient_merge is then train-only optimization + if self._mode == "train" and self._strategy.gradient_merge.enable: + config = copy.deepcopy(self._strategy.gradient_merge.to_dict()) + config["dist_context"] = self._dist_context + config["params_grads"] = params_grads + auto_parallel_gradient_merge_pass = new_pass( + "auto_parallel_gradient_merge_pass", config) + auto_parallel_gradient_merge_pass.apply([main_program], + [startup_program], + self._pass_context) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/partitioner.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/partitioner.py new file mode 100644 index 0000000000000000000000000000000000000000..e12a111dd2a61ef777df83a801dbbd343c8bbde3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/partitioner.py @@ -0,0 +1,453 @@ +# Copyright (c) 2021 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 + +import copy +import numpy as np +import paddle +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid import framework as framework +from paddle.fluid import core, unique_name +from paddle.fluid.framework import Program, Parameter, Variable, program_guard +from paddle.distributed.auto_parallel.operators.common import get_distributed_operator_impl_container +from paddle.distributed.auto_parallel.dist_context import DistributedContext, DistributedOperatorContext +from .dist_attribute import OperatorDistributedAttribute +from .process_group import new_process_group +from .utils import set_dist_op_desc_original_id +from .utils import print_program_with_dist_attr, is_forward_op, is_backward_op, is_loss_op, is_optimize_op +from .operators.common import BACKWARD_ONLY_DIST_OPS + +__varname_not_in_block__ = ["lod_tensor_blocking_queue"] +__not_shape_var_type__ = [ + core.VarDesc.VarType.READER, core.VarDesc.VarType.STEP_SCOPES +] + + +class Partitioner(object): + """ + warning:: Partitioner is experimental and subject to change. + + Partitioner convert a program into another program. + Given a serial program which has been auto completed with shard annotation, the Partitioner + convert the serial program into a "distributed" program. The Partitioner will modify the serial + program in following two ways, which is also the major difference between serial and distributed program: + 1. partition op: replace a serial op into its corresponding dist op infered from the shard annotation + 2. partition var: if a var is sharded, modify the shape of var according to its shard annotation + + Partitioner is supposed to be call by the auto parallel framework, and not supposed to be directly called by user. + """ + + def __init__(self, dist_context, rank_id=0): + """ + Args: + dist_context (paddle.fluid.DistributedContext): used to access the distributed_attr of var & op, every Partitioner object could maintain its own DistributedContext member, and partition program base on that shard scenario. + rank_id (int): global rank id to which the partitioned distributed program belong. + """ + if not isinstance(dist_context, DistributedContext): + raise TypeError( + "dist_context be paddle.fluid.DistributedContext, got %s here" % + type(dist_context)) + + self._dist_context = dist_context + self._rank_id = rank_id + self._serial2dist_varname_mapping = {} + self._dist_varname_suffix = "" + + def partition(self, serial_main_program, serial_startup_program, + params_grads): + if not isinstance(serial_main_program, (Program)): + raise TypeError( + "main_program be paddle.fluid.framework.program, got %s here" % + type(serial_main_program)) + + # check if shard annotated serial program valid + if not self._is_valid_annotated_program(serial_main_program): + raise RuntimeError( + "Not all vars or ops are annotated in main program !") + + # init distop helper + dist_op_context = self._dist_context.dist_op_context + dist_op_context.varname_mapping = self._serial2dist_varname_mapping + dist_op_context.rank_id = self._rank_id + + # partition startup program + if serial_startup_program == None: + partitioned_startup_prog = None + else: + partitioned_startup_prog = self.partition_startup_program( + serial_main_program, serial_startup_program) + dist_op_context.dst_startup_program = partitioned_startup_prog + + # partition main program + partitioned_main_prog, partitioned_params_grads = self.partition_main_program( + serial_main_program, params_grads) + + return partitioned_main_prog, partitioned_startup_prog, partitioned_params_grads + + def partition_startup_program(self, serial_main_program, + serial_startup_program): + + if not isinstance(serial_startup_program, (Program)): + raise TypeError( + "dist_context be paddle.fluid.framework.program, got %s here" % + type(serial_startup_program)) + + partitioned_startup_prog = fluid.Program() + ref_block = serial_main_program.global_block() + target_block = partitioned_startup_prog.global_block() + var2shape = {} + temp_varname_map = {} + + # tensors + for var in serial_startup_program.list_vars(): + assert var.persistable + new_name = var.name + self._dist_varname_suffix + temp_varname_map[var.name] = new_name + target_shape = _partition_var(self._dist_context, ref_block, + target_block, var.name, new_name) + var2shape[new_name] = target_shape + + # ops + for op in serial_startup_program.global_block().ops: + # TODO if var not belong to this rank, should be filtered + output_vars = op.desc.output_arg_names() + assert len( + output_vars + ) == 1, "initializer should output only ONE variable, but got [{}]".format( + str(op.desc)) + assert temp_varname_map[output_vars[ + 0]] in var2shape, "try to initialize [{}] which is not a persistable var".format( + output_vars[0]) + new_op_desc = target_block.desc.append_op() + new_op_desc.copy_from(op.desc) + new_op_desc._rename_output(output_vars[0], + temp_varname_map[output_vars[0]]) + new_op_desc._set_attr("shape", + var2shape[temp_varname_map[output_vars[0]]]) + target_block._sync_with_cpp() + + # set distribute atrribute + new_op = target_block.ops[-1] + assert new_op.type == new_op_desc.type() + assert new_op.desc == new_op_desc + output_var = target_block.var(output_vars[0]) + output_var_attr = self._dist_context.get_tensor_dist_attr_for_program( + output_var) + op_attr = OperatorDistributedAttribute() + op_attr.process_mesh = output_var_attr.process_mesh + op_attr.set_output_dims_mapping(output_var.name, + output_var_attr.dims_mapping) + op_attr.set_input_dims_mapping(output_var.name, + output_var_attr.dims_mapping) + self._dist_context.set_op_dist_attr_for_program(new_op, op_attr) + + return partitioned_startup_prog + + def partition_main_program(self, serial_main_program, params_and_grads): + """ + 1. partition variables + 2. replace local op with corresponding dist op + """ + + partitioned_main_prog = fluid.Program() + dist_op_context = self._dist_context.dist_op_context + dist_op_context.dst_main_program = partitioned_main_prog + + for idx in range(self._dist_context.block_state.nblock): + ref_block = serial_main_program.blocks[idx] + + if idx == 0: + target_block = partitioned_main_prog.blocks[0] + else: + target_block = partitioned_main_prog._create_block( + parent_idx=ref_block.parent_idx) + assert ref_block.idx == target_block.idx + target_block._set_forward_block_idx(ref_block.forward_block_idx) + dist_op_context.work_block = target_block + self.partition_block(ref_block, target_block) + + partitioned_main_prog.current_block_idx = 0 + + # should reconnect the block_attr ptr to the correct block + for block_id in range(self._dist_context.block_state.nblock): + block = partitioned_main_prog.block(block_id) + for op in block.ops: + for attr_name in op.all_attrs(): + if op.attr_type(attr_name) == core.AttrType.BLOCK: + relative_id = op._block_attr_id(attr_name) + op._set_attr(attr_name, + partitioned_main_prog.block(relative_id)) + + partitioned_params_and_grads = [] + for p, g in params_and_grads: + assert p.name in self._serial2dist_varname_mapping + dist_p = self._get_dist_var_by_serial_var(p, partitioned_main_prog) + if g is None: + dist_g = None + else: + assert g.name in self._serial2dist_varname_mapping + dist_g = self._get_dist_var_by_serial_var( + g, partitioned_main_prog) + partitioned_params_and_grads.append((dist_p, dist_g)) + + return partitioned_main_prog, partitioned_params_and_grads + + def partition_block(self, ref_block, target_block): + + dist_op_context = self._dist_context.dist_op_context + serial_ops = ref_block.ops + + last_fwd_op_idx = -1 + for idx, op in enumerate(ref_block.ops): + if is_loss_op(op): + last_fwd_op_idx = idx + break + + if last_fwd_op_idx == -1: + last_fwd_op_idx = len(ref_block.ops) + + # init mapping + forward_op_id2forward_op = {} + for idx in range(len(serial_ops)): + if idx <= last_fwd_op_idx: + forward_op_id2forward_op[ + serial_ops[idx].desc.original_id()] = serial_ops[idx] + + # partiiton + appended_grad_times = 0 + for idx, op in enumerate(serial_ops): + + op_dist_attr = self._dist_context.get_op_dist_attr_for_program(op) + if is_backward_op(op) and (is_forward_op(serial_ops[idx - 1]) + or is_loss_op(serial_ops[idx - 1])): + if not op_dist_attr.is_recompute: + appended_grad_times += 1 + + # partititon input variables + for serial_input_varname in op.desc.input_arg_names(): + if serial_input_varname not in self._serial2dist_varname_mapping: + new_varname = serial_input_varname + self._dist_varname_suffix + if ref_block.has_var(serial_input_varname): + _partition_var(self._dist_context, ref_block, + target_block, serial_input_varname, + new_varname) + else: + for varname_not_in_block in __varname_not_in_block__: + assert varname_not_in_block in serial_input_varname, \ + "{} is not found".format(serial_input_varname) + + self._serial2dist_varname_mapping[ + serial_input_varname] = new_varname + + # partition output vars + for serial_output_varname in op.desc.output_arg_names(): + if serial_output_varname not in self._serial2dist_varname_mapping: + new_varname = serial_output_varname + self._dist_varname_suffix + _partition_var(self._dist_context, ref_block, target_block, + serial_output_varname, new_varname) + self._serial2dist_varname_mapping[ + serial_output_varname] = new_varname + + # partition op + if is_forward_op(op) or op_dist_attr.is_recompute: + kinputs, koutputs = dist_op_context.prepare_context(op) + dist_op_forward_impl = _get_dist_op_forward_implement( + op, self._dist_context) + dist_op_forward_impl.forward(self._dist_context, **kinputs, + **koutputs) + + elif is_backward_op(op): + kinputs, koutputs = dist_op_context.prepare_context(op) + dist_op_backward_impl = _get_dist_op_backward_implement( + op, self._dist_context, forward_op_id2forward_op) + grad_var_to_var = self._dist_context.dist_op_context.grad_var_to_var[ + appended_grad_times] + dist_op_backward_impl.backward( + self._dist_context, **kinputs, **koutputs, + **{"grad_var_to_var": grad_var_to_var}) + elif is_optimize_op(op): + # NOTE: BACKWARD_ONLY_DIST_OPS's op_role must 2 because of 1F1B PASS + kinputs, koutputs = dist_op_context.prepare_context(op) + dist_op_opt_impl = _get_dist_op_backward_implement( + op, self._dist_context, forward_op_id2forward_op) + dist_op_opt_impl.backward(self._dist_context, **kinputs, + **koutputs, **{"grad_var_to_var": {}}) + else: + raise NotImplementedError( + "partitioner only support forward and backward, optimize ops, but got {}" + .format(str(op))) + + def _is_valid_annotated_program(self, program): + + # TODO (ZJ-LIANG) should check all block + ops = program.global_block().ops + vars_ = program.list_vars() + op_dist_attrs = [ + self._dist_context.get_op_dist_attr_for_program(op) for op in ops + ] + var_dist_attrs = [ + self._dist_context.get_tensor_dist_attr_for_program(var) + for var in vars_ if (var.type not in __not_shape_var_type__) + ] + + all_ops_annotated = all(dist_attr is not None + for dist_attr in op_dist_attrs) + all_vars_annotated = all(dist_attr is not None + for dist_attr in var_dist_attrs) + + return all_ops_annotated and all_vars_annotated + + def _get_dist_var_by_serial_var(self, serial_var, partitioned_main_prog): + + block_idx = serial_var.block.idx + target_block = partitioned_main_prog.blocks[block_idx] + dist_var_name = self._serial2dist_varname_mapping[serial_var.name] + assert target_block.has_var(dist_var_name) + return target_block.var(dist_var_name) + + +def _get_dist_shape(var, dist_attr): + + var_shape = var.shape + mapping = dist_attr.dims_mapping + mesh = dist_attr.process_mesh.topology + if mapping == []: + return var_shape + + assert len(var_shape) == len( + mapping + ), "variable shape [{}] and dim_mapping [{}] is NOT match !".format( + var_shape, mapping) + new_shape = [] + for idx in range(len(var_shape)): + if var_shape[idx] == -1 or mapping[idx] == -1: + new_shape.append(var_shape[idx]) + else: + assert var_shape[idx] % mesh[mapping[ + idx]] == 0, "un-event partition: var_shape[idx]=[{}], mesh[{}]".format( + var_shape[idx], mesh[mapping[idx]]) + new_shape.append(var_shape[idx] // mesh[mapping[idx]]) + + return new_shape + + +def _partition_parameter(dist_context, src_var, dst_block, dst_varname, + dst_shape): + # NOTE hack to copied Parameter + # not initialized parameter, need to initialize it + copied_kwargs = {} + copied_kwargs['trainable'] = src_var.trainable + copied_kwargs['optimize_attr'] = src_var.optimize_attr + copied_kwargs['regularizer'] = src_var.regularizer + copied_kwargs['do_model_average'] = src_var.do_model_average + copied_kwargs['need_clip'] = src_var.need_clip + + param = Parameter(block=dst_block, + type=src_var.type, + name=dst_varname, + shape=dst_shape, + dtype=src_var.dtype, + lod_level=src_var.lod_level, + error_clip=src_var.error_clip, + stop_gradient=src_var.stop_gradient, + is_data=src_var.is_data, + belong_to_optimizer=src_var.belong_to_optimizer, + **copied_kwargs) + + return param + + +def _partition_intermediate_var(dist_context, src_var, dst_block, dst_varname, + dst_shape): + var = dst_block.create_var(type=src_var.type, + name=dst_varname, + shape=dst_shape, + dtype=src_var.dtype, + lod_level=src_var.lod_level, + persistable=src_var.persistable, + error_clip=src_var.error_clip, + stop_gradient=src_var.stop_gradient, + is_data=src_var.is_data, + belong_to_optimizer=src_var.belong_to_optimizer) + + return var + + +def _partition_var(dist_context, src_block, dst_block, src_varname, + dst_varname): + """ + partition include: split + replicate + """ + src_var = src_block.var(src_varname) + + if src_var.type in __not_shape_var_type__: + persist = getattr(src_var, 'persistable', False) + new_var = dst_block.create_var(type=src_var.type, + name=dst_varname, + persistable=persist, + stop_gradient=True) + target_shape = None + else: + dist_attr = dist_context.get_tensor_dist_attr_for_program(src_var) + target_shape = _get_dist_shape(src_var, dist_attr) + + if isinstance(src_var, Parameter): + new_var = _partition_parameter(dist_context, src_var, dst_block, + dst_varname, target_shape) + else: + new_var = _partition_intermediate_var(dist_context, src_var, + dst_block, dst_varname, + target_shape) + + dist_attr = copy.deepcopy( + dist_context.get_tensor_dist_attr_for_program(src_var)) + assert dist_attr is not None + dist_context.set_tensor_dist_attr_for_program(new_var, dist_attr) + + return target_shape + + +def _get_dist_op_backward_implement(backward_op, dist_context, + forward_op_id2forward_op): + dist_op_context = dist_context.dist_op_context + if backward_op.desc.original_id() in dist_op_context.grad_op_id_to_op_id: + forward_op_id = dist_op_context.grad_op_id_to_op_id[ + backward_op.desc.original_id()] + forward_op = forward_op_id2forward_op[forward_op_id] + forward_op_dist_attr = dist_context.get_op_dist_attr_for_program( + forward_op) + dist_op_impl_container = get_distributed_operator_impl_container( + forward_op_dist_attr.impl_type) + dist_op_impl = dist_op_impl_container.get_impl( + forward_op_dist_attr.impl_idx) + return dist_op_impl + + # # NOTE trick for dist ops that only have backward implement + if backward_op.type in BACKWARD_ONLY_DIST_OPS: + op_dist_attr = dist_context.get_op_dist_attr_for_program(backward_op) + assert op_dist_attr.impl_idx >= 0 + dist_op_impl = get_distributed_operator_impl_container( + op_dist_attr.impl_type).get_impl(op_dist_attr.impl_idx) + return dist_op_impl + + dist_op = get_distributed_operator_impl_container("default") + return dist_op.get_impl(0) + + +def _get_dist_op_forward_implement(forward_op, dist_context): + dist_attr = dist_context.get_op_dist_attr_for_program(forward_op) + dist_op_impl_container = get_distributed_operator_impl_container( + dist_attr.impl_type) + dist_op_impl = dist_op_impl_container.get_impl(dist_attr.impl_idx) + return dist_op_impl diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..0425424b0d7ae3da397bc72c7250481a5c7de033 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner.py @@ -0,0 +1,876 @@ +# Copyright (c) 2021 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. + +import copy +import time +import random +from functools import reduce +from itertools import chain, product +from collections import OrderedDict + +import numpy as np + +import paddle +from paddle.distributed.fleet import auto +from .cost_model import estimate_cost +from .dist_op import DistributedOperator +from .process_group import _g_process_group_map +from .process_group import ProcessGroup, get_process_group +from .operators.common import is_elementwise_op +from .operators.common import get_distributed_operator_impl_container +from .utils import update_op_dims_mapping_by_default_dist_impl +from .utils import update_op_dims_mapping_by_elementwise_like_dist_impl +from .utils import get_all_distributed_main_program +from .dist_context import DistributedContext, DistributedOperatorContext +from .dist_attribute import OperatorDistributedAttribute, TensorDistributedAttribute + +paddle.seed(123) +random.seed(123) +np.random.seed(123) + + +class PlanFilter: + + @staticmethod + def check_dims_mapping_for_tensor(process_mesh_topology, tensor_shape, + dims_mapping): + valid = True + assert len(tensor_shape) == len(dims_mapping) + + for idx, dim_mapping in enumerate(dims_mapping): + if dim_mapping != -1: + if tensor_shape[idx] % process_mesh_topology[ + dim_mapping] != 0 or dims_mapping.count( + dim_mapping) > 1: + valid = False + if dim_mapping != -1 and process_mesh_topology[0] == 1: + valid = False + + return valid + + @staticmethod + def check_dims_mapping_for_op(op, op_dist_attr, vars): + process_mesh = op_dist_attr.process_mesh + assert process_mesh is not None, "The process mesh should not be None." + for var_name in op.input_arg_names: + dims_mapping = op_dist_attr.get_input_dims_mapping(var_name) + if not PlanFilter.check_dims_mapping_for_tensor( + process_mesh.topology, vars[var_name].shape, dims_mapping): + return False + if vars[var_name].is_data and len(dims_mapping) > 1: + for dim in dims_mapping[1:]: + if dim != -1: + return False + + for var_name in op.output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(var_name) + if not PlanFilter.check_dims_mapping_for_tensor( + process_mesh.topology, vars[var_name].shape, dims_mapping): + return False + + return True + + @staticmethod + def check_dims_mapping_for_special_op(op, op_dist_attr, vars): + # NOTE: Those ops has some partition limits, and will be solved when corresponding dist op implemented in the future. + if op.type == "elementwise_add" or op.type == 'layer_norm' or op.type == "softmax_with_cross_entropy": + for name in op.input_arg_names: + for item in op_dist_attr.get_input_dims_mapping(name): + if item != -1: + return False + for name in op.output_arg_names: + for item in op_dist_attr.get_output_dims_mapping(name): + if item != -1: + return False + if op.type == "lookup_table_v2": + for name in op.input_arg_names: + if name == 'pos_embeddings': + for item in op_dist_attr.get_input_dims_mapping(name): + if item != -1: + return False + return True + + +class PlanSpace: + not_enum_ops = ["create_py_reader", "create_double_buffer_reader", "read"] + special_vars = [ + "lod_tensor_blocking_queue_0", "create_py_reader_0", "double_buffer_0" + ] + + @staticmethod + def _enum_dims_mapping(process_mesh_topology, visited, path, depth, res, + tensor_shape): + """Enumerate dims mapping of tensor by the given process_mesh_topology""" + nums = list(range(-1, len(process_mesh_topology))) + if depth == len(tensor_shape): + valid = True + for idx, item in enumerate(path): + if item != -1: + if tensor_shape[idx] % process_mesh_topology[ + item] != 0 or path.count(item) > 1: + valid = False + if valid: + res.append(copy.deepcopy(path)) + return + + for i in range(len(nums)): + if not visited[i]: + if i != 0: + visited[i] = True + path.append(nums[i]) + PlanSpace._enum_dims_mapping(process_mesh_topology, visited, + path, depth + 1, res, tensor_shape) + visited[i] = False + path.pop() + + @staticmethod + def enum_process_mesh_topology(processes): + """Enumerate all process meshes with the given processes.""" + assert processes >= 1, "The processes must be number and greater than 0." + # compute divisors + divisors = [] + for i in range(1, processes + 1): + if processes % i == 0: + divisors.append(i) + + # compute valid process mesh + results = [] + for i in range(len(divisors) - 1, 0, -1): + result = [] + result.append(divisors[i]) + if i == len(divisors) - 1: + results.append(copy.deepcopy(result)) + continue + + j = 1 + while j < len(divisors): + if len(result) == 1: + result.append(divisors[j]) + elif len(result) == 2: + if processes % (result[0] * result[1]) == 0: + if processes // (result[0] * result[1]) == 1: + results.append(copy.deepcopy(result)) + break + else: + result.append(processes // (result[0] * result[1])) + results.append(copy.deepcopy(result)) + result.pop(-1) + result.pop(-1) + j += 1 + else: + if result[0] * result[1] < processes: + result.pop(-1) + j += 1 + else: + break + return results + + @staticmethod + def _enum_valid_dist_attr_for_op(program, op, process_mesh): + """Enumerate the valid distributed attribute for op based on the given process mesh.""" + vars = program.global_block().vars + dims_mapping_dict = OrderedDict() + op_valid_dist_attrs = [] + dist_op_impl_container = get_distributed_operator_impl_container( + op.type) + + # enumerate all valid dims mapping of tensor when process mesh given + for var_name in chain(op.input_arg_names, op.output_arg_names): + visited = [ + False + for _ in range(len(list(range(-1, len(process_mesh.topology))))) + ] + depth = 0 + path = [] + dims_mapping_list = [] + PlanSpace._enum_dims_mapping(process_mesh.topology, visited, path, + depth, dims_mapping_list, + vars[var_name].shape) + dims_mapping_dict[var_name] = copy.deepcopy(dims_mapping_list) + + # compose dims mapping + composed_dims_mapping_list = list( + product( + *[dims_mapping_dict[key] for key in dims_mapping_dict.keys()])) + for composed_dims_mapping in composed_dims_mapping_list: + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = process_mesh + var_names = list(dims_mapping_dict.keys()) + + for idx, dims_mapping in enumerate(composed_dims_mapping): + if var_names[idx] in op.input_arg_names: + op_dist_attr.set_input_dims_mapping(var_names[idx], + dims_mapping) + elif var_names[idx] in op.output_arg_names: + op_dist_attr.set_output_dims_mapping( + var_names[idx], dims_mapping) + else: + raise ValueError( + "The {varname} is not input or output of op {op}.". + format(varname='var_names[idx]', op='op')) + + dist_op = DistributedOperator(op, op_dist_attr) + if dist_op_impl_container is None: + if is_elementwise_op(op.type): + changed = True + valid = True + try: + changed = update_op_dims_mapping_by_elementwise_like_dist_impl( + dist_op) + except Exception as e: + valid = False + if valid and not changed: + if PlanFilter.check_dims_mapping_for_op( + op, dist_op.dist_attr, vars + ) and PlanFilter.check_dims_mapping_for_special_op( + op, dist_op.dist_attr, vars): + dist_op.dist_attr.impl_type = "elementwise" + dist_op.dist_attr.impl_idx = 0 + op_valid_dist_attrs.append(dist_op.dist_attr) + continue + else: + changed = True + valid = True + try: + changed = update_op_dims_mapping_by_default_dist_impl( + dist_op) + except Exception as e: + valid = False + if valid and not changed: + if PlanFilter.check_dims_mapping_for_op( + op, dist_op.dist_attr, vars + ) and PlanFilter.check_dims_mapping_for_special_op( + op, dist_op.dist_attr, vars): + dist_op.dist_attr.impl_type = "default" + dist_op.dist_attr.impl_idx = 0 + op_valid_dist_attrs.append(dist_op.dist_attr) + continue + + # if op has distributed implements, find all valid dist attr of this op + impls = dist_op_impl_container.impls + for idx, impl in enumerate(impls): + if impl.is_auto_compatible(dist_op): + if PlanFilter.check_dims_mapping_for_op( + op, dist_op.dist_attr, vars): + dist_op.dist_attr.impl_type = dist_op.serial_op.type + dist_op.dist_attr.impl_idx = idx + op_valid_dist_attrs.append(dist_op.dist_attr) + + # set default dist attr for some special ops whose distributed attributes can not be enumerated + if not op_valid_dist_attrs: + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = process_mesh + dist_op = DistributedOperator(op, op_dist_attr) + for var_name in op.input_arg_names: + op_dist_attr.set_input_dims_mapping( + vars[var_name], [-1 for i in vars[var_name].shape]) + for var_name in op.output_arg_names: + op_dist_attr.set_output_dims_mapping( + vars[var_name], [-1 for i in vars[var_name].shape]) + dist_op.dist_attr.impl_type = "default" + dist_op.dist_attr.impl_idx = 0 + op_valid_dist_attrs.append(dist_op.dist_attr) + + return op_valid_dist_attrs + + @staticmethod + def enum_valid_dist_attr_for_program(program, + process_mesh_topology, + is_pipeline=False): + """Enumerate valid distributed attributes for all ops in program.""" + valid_dist_attr_dict = OrderedDict() + ops = program.global_block().ops + vars = program.global_block().vars + + processes = reduce(lambda x, y: x * y, process_mesh_topology) + global_group = [i for i in range(processes)] + global_process_mesh = None + pipeline_process_meshes = None + + # in the pipeline mode, there are some process meshes + if is_pipeline: + pipeline_stages = process_mesh_topology[-1] + op_count_per_stage = len(ops) // pipeline_stages + if len(process_mesh_topology) > 1: + process_mesh_shape = process_mesh_topology[:-1] + per_process_mesh_group = processes // pipeline_stages + pipeline_process_meshes = [auto.ProcessMesh(mesh=np.array(global_group[i*per_process_mesh_group: \ + (i+1)*per_process_mesh_group]).reshape(process_mesh_shape).tolist()) for i in range(pipeline_stages)] + elif len(process_mesh_topology) == 1: + pipeline_process_meshes = [ + auto.ProcessMesh(mesh=[i]) for i in range(pipeline_stages) + ] + else: + if len(process_mesh_topology) > 1: + global_process_mesh = auto.ProcessMesh(mesh=np.array( + global_group).reshape(process_mesh_topology).tolist()) + else: + global_process_mesh = auto.ProcessMesh(mesh=global_group) + + # enumerate valid distributed attribute for each op in the program + for idx, op in enumerate(ops): + op_valid_dist_attrs = None + op_process_mesh = global_process_mesh + pipeline_stage = -1 + if pipeline_process_meshes is not None: + pipeline_stage = idx // op_count_per_stage if idx // op_count_per_stage < len( + pipeline_process_meshes) else idx // op_count_per_stage - 1 + if pipeline_stage >= len(pipeline_process_meshes): + pipeline_stage = len(pipeline_process_meshes) - 1 + op_process_mesh = pipeline_process_meshes[pipeline_stage] + + if op.type in PlanSpace.not_enum_ops: + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = op_process_mesh + for var_name in op.input_arg_names: + if var_name in PlanSpace.special_vars: + op_dist_attr.set_input_dims_mapping(var_name, []) + else: + dims_mapping = [-1 for i in vars[var_name].shape] + op_dist_attr.set_input_dims_mapping( + var_name, dims_mapping) + + for var_name in op.output_arg_names: + if var_name in PlanSpace.special_vars: + op_dist_attr.set_output_dims_mapping(var_name, []) + else: + dims_mapping = [-1 for i in vars[var_name].shape] + op_dist_attr.set_output_dims_mapping( + var_name, dims_mapping) + op_valid_dist_attrs = [op_dist_attr] + pipeline_stage = 0 if pipeline_stage != -1 else pipeline_stage + else: + op_valid_dist_attrs = PlanSpace._enum_valid_dist_attr_for_op( + program, op, op_process_mesh) + + assert op_valid_dist_attrs is not None, "Enumerate {} valid distributed attribute failed.".format( + op) + valid_dist_attr_dict[op.desc.id()] = [ + op_valid_dist_attrs, pipeline_stage + ] + + return valid_dist_attr_dict, pipeline_process_meshes, global_process_mesh + + +class SearchAlgorithm: + + def __init__(self, name): + self._name = name + + @property + def name(self): + self.name = name + + def search(self): + raise NotImplementedError("Please Implement this method in subclass.") + + +class MCMC(SearchAlgorithm): + + def __init__(self, serial_program_info, parallelizer, max_search_times=5): + super(MCMC, self).__init__("mcmc") + self._serial_program_info = serial_program_info + self._max_search_times = max_search_times + self._parallelizer = parallelizer + + @property + def serial_program_info(self): + return self._serial_program_info + + @property + def parallelizer(self): + return self._parallelizer + + @property + def max_search_times(self): + return self._max_search_times + + def make_special_op_unshard(self, op, ops, vars, dist_context, + valid_dist_attr_dict): + if op.type == "softmax_with_cross_entropy": + for var_name in op.input_arg_names: + dims_mapping = dist_context.get_op_dist_attr_for_program( + op).get_input_dims_mapping(var_name) + if dims_mapping != dist_context.get_tensor_dist_attr_for_program( + vars[var_name]).dims_mapping: + has_changed = False + for search_op in ops: + if var_name in search_op.output_arg_names: + op_dist_attr_list = valid_dist_attr_dict[ + search_op.desc.id()][0] + for op_dist_attr in op_dist_attr_list: + if op_dist_attr.get_output_dims_mapping( + var_name) == dims_mapping: + dist_context.set_op_dist_attr_for_program( + search_op, op_dist_attr) + for name in search_op.output_arg_names: + tensor_dist_attr = TensorDistributedAttribute( + ) + tensor_dist_attr.process_mesh = op_dist_attr.process_mesh + tensor_dist_attr.dims_mapping = op_dist_attr.get_output_dims_mapping( + name) + dist_context.set_tensor_dist_attr_for_program( + vars[name], tensor_dist_attr) + has_changed = True + break + if has_changed: + break + if not has_changed: + raise ValueError( + "Change softmax_with_cross_entropy dist attr failed" + ) + + def init_program(self, valid_dist_attr_dict, program, + pipeline_process_meshes, global_process_mesh): + ops = program.global_block().ops + vars = program.global_block().vars + new_dist_context = DistributedContext() + + for op in ops: + op_valid_dist_attr_list = valid_dist_attr_dict[op.desc.id()][0] + random_op_dist_attr = np.random.randint( + len(op_valid_dist_attr_list)) + init_op_dist_attr = op_valid_dist_attr_list[random_op_dist_attr] + new_dist_context.set_op_dist_attr_for_program(op, init_op_dist_attr) + for var_name in op.input_arg_names: + if var_name == "lod_tensor_blocking_queue_0": + continue + if new_dist_context.get_tensor_dist_attr_for_program( + vars[var_name]) is None: + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = init_op_dist_attr.process_mesh + tensor_dist_attr.dims_mapping = init_op_dist_attr.get_input_dims_mapping( + var_name) + new_dist_context.set_tensor_dist_attr_for_program( + vars[var_name], tensor_dist_attr) + + for var_name in op.output_arg_names: + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = init_op_dist_attr.process_mesh + tensor_dist_attr.dims_mapping = init_op_dist_attr.get_output_dims_mapping( + var_name) + new_dist_context.set_tensor_dist_attr_for_program( + vars[var_name], tensor_dist_attr) + + # NOTE: this is a temporary solution to make softmax_with_cross_entropy unshard + self.make_special_op_unshard(op, ops, vars, new_dist_context, + valid_dist_attr_dict) + + # add process meshes to distributed context + if global_process_mesh is not None: + new_dist_context.add_process_mesh(global_process_mesh) + elif pipeline_process_meshes is not None: + for process_mesh in pipeline_process_meshes: + new_dist_context.add_process_mesh(process_mesh) + + return new_dist_context + + def estimate_searched_strategy_cost(self, + dist_context, + pipeline_process_meshes=None): + cost = None + # get all distributed programs + all_dist_main_program = get_all_distributed_main_program( + self.serial_program_info, dist_context, self.parallelizer) + pipeline_config = [ + process_mesh.processes for process_mesh in pipeline_process_meshes + ] if pipeline_process_meshes is not None else None + microbatch_size = 1 + for program in all_dist_main_program: + searched_batch_size = False + for var in program.list_vars(): + if var.is_data and "@RESHARD" in var.name: + microbatch_size = var.shape[0] + searched_batch_size = True + break + if searched_batch_size: + break + + from .utils import get_standalone_cost_data + standalone_cost_data = get_standalone_cost_data(all_dist_main_program) + + # cost model does not support cluster argument + cost = estimate_cost(all_dist_main_program, + cluster=None, + pipeline_config=pipeline_config, + standalone_cost_data=standalone_cost_data, + batch_size=microbatch_size) + + return cost + + def set_tensor_dist_attr(self, op, op_dist_attr, vars, dist_context): + # set output tensor distributed attribute + for var_name in op.output_arg_names: + process_mesh = op_dist_attr.process_mesh + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = process_mesh + tensor_dist_attr.dims_mapping = op_dist_attr.get_output_dims_mapping( + var_name) + dist_context.set_tensor_dist_attr_for_program( + vars[var_name], tensor_dist_attr) + + # set input tensor distributed attribute if input is data or parameter + for var_name in op.input_arg_names: + if vars[var_name].is_parameter or vars[var_name].is_data: + process_mesh = op_dist_attr.process_mesh + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = process_mesh + tensor_dist_attr.dims_mapping = op_dist_attr.get_input_dims_mapping( + var_name) + dist_context.set_tensor_dist_attr_for_program( + vars[var_name], tensor_dist_attr) + + def change_process_mesh(self, op, changed_process_mesh, vars, dist_context): + dist_context.get_op_dist_attr_for_program( + op).process_mesh = changed_process_mesh + for var_name in op.output_arg_names: + dist_context.get_tensor_dist_attr_for_program( + vars[var_name]).process_mesh = changed_process_mesh + for var_name in op.input_arg_names: + if vars[var_name].is_parameter or vars[var_name].is_data: + dist_context.get_tensor_dist_attr_for_program( + vars[var_name]).process_mesh = changed_process_mesh + + def search_once(self, + program, + valid_dist_attr_dict, + dist_context, + pipeline_process_meshes=None): + raw_ops = program.global_block().ops + ops = [] + for op in raw_ops: + if op.type not in PlanSpace.not_enum_ops: + ops.append(op) + assert ops, "The ops of program have no distributed attributes." + vars = program.global_block().vars + new_dist_context = copy.deepcopy(dist_context) + new_dist_context._dist_op_context = DistributedOperatorContext() + new_valid_dist_attr_dict = None + random_selected_op_idx = np.random.randint(len(ops)) + selected_op = ops[random_selected_op_idx] + op_valid_dist_attr_list = valid_dist_attr_dict[selected_op.desc.id()][0] + pipeline_stage = valid_dist_attr_dict[selected_op.desc.id()][1] + random_selected_dist_attr_idx = np.random.randint( + len(op_valid_dist_attr_list)) + selected_op_dist_attr = copy.deepcopy( + op_valid_dist_attr_list[random_selected_dist_attr_idx]) + + start_idx = ops[0].desc.id() + if pipeline_stage > -1: + # in pipeline mode, the above phase just select a dims mapping + # 0 represents not changed, 1 represents to be the same with before stage, 2 represents to be the same with the latter stage + new_valid_dist_attr_dict = copy.deepcopy(valid_dist_attr_dict) + changed_mode = np.random.randint(3) + if changed_mode == 0: + # not change the process mesh, just change dims mapping + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + self.set_tensor_dist_attr(selected_op, selected_op_dist_attr, + vars, new_dist_context) + + elif changed_mode == 1: + changed_stage = pipeline_stage - 1 + if changed_stage == -1 or random_selected_op_idx == len(ops) - 1 or \ + (random_selected_op_idx + 1 == len(ops) - 1 and new_valid_dist_attr_dict[ops[random_selected_op_idx + 1].desc.id()][1] == pipeline_stage + 1 ): + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + self.set_tensor_dist_attr(selected_op, + selected_op_dist_attr, vars, + new_dist_context) + + else: + selected_op_process_mesh = pipeline_process_meshes[ + pipeline_stage] + next_op_id = ops[random_selected_op_idx + 1].desc.id() + if new_valid_dist_attr_dict[next_op_id][ + 1] == pipeline_stage + 1 and random_selected_op_idx + 1 != len( + ops) - 1: + new_valid_dist_attr_dict[next_op_id][1] = pipeline_stage + for op_dist_attr in new_valid_dist_attr_dict[ + next_op_id][0]: + op_dist_attr.process_mesh = selected_op_process_mesh + # set next op dist attr in the discontext and output/input tensor process mesh + self.change_process_mesh( + ops[random_selected_op_idx + 1], + selected_op_process_mesh, vars, new_dist_context) + + # change the selected op stage and output dist attr + new_valid_dist_attr_dict[ + selected_op.desc.id()][1] = changed_stage + new_process_mesh = pipeline_process_meshes[changed_stage] + selected_op_dist_attr.process_mesh = new_process_mesh + for op_dist_attr in new_valid_dist_attr_dict[ + selected_op.desc.id()][0]: + op_dist_attr.process_mesh = new_process_mesh + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + + self.set_tensor_dist_attr(selected_op, + selected_op_dist_attr, vars, + new_dist_context) + + # change the pre op stage + for idx in range(random_selected_op_idx - 1, -1, -1): + stage = new_valid_dist_attr_dict[ops[idx].desc.id()][1] + valid_dist_attr_list = new_valid_dist_attr_dict[ + ops[idx].desc.id()][0] + new_process_mesh = pipeline_process_meshes[ + changed_stage] + if stage == changed_stage + 1: + new_valid_dist_attr_dict[ + ops[idx].desc.id()][1] = changed_stage + for op_dist_attr in valid_dist_attr_list: + op_dist_attr.process_mesh = new_process_mesh + new_dist_context.get_op_dist_attr_for_program( + ops[idx]).process_mesh = new_process_mesh + # change process mesh of the output and input tensor + self.change_process_mesh(ops[idx], new_process_mesh, + vars, new_dist_context) + else: + break + + else: + changed_stage = pipeline_stage + 1 + if changed_stage == len( + pipeline_process_meshes) or random_selected_op_idx == 0 or \ + (new_valid_dist_attr_dict[ops[random_selected_op_idx - 1].desc.id()][1] == pipeline_stage - 1 and (random_selected_op_idx == 1)): + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + self.set_tensor_dist_attr(selected_op, + selected_op_dist_attr, vars, + new_dist_context) + + else: + selected_op_process_mesh = pipeline_process_meshes[ + pipeline_stage] + pre_op_id = ops[random_selected_op_idx - 1].desc.id() + if new_valid_dist_attr_dict[pre_op_id][ + 1] == pipeline_stage - 1 and random_selected_op_idx != 1: + new_valid_dist_attr_dict[pre_op_id][1] = pipeline_stage + for op_dist_attr in new_valid_dist_attr_dict[pre_op_id][ + 0]: + op_dist_attr.process_mesh = selected_op_process_mesh + # set pre op dist attr in the discontext and output tensor process mesh + self.change_process_mesh( + ops[random_selected_op_idx - 1], + selected_op_process_mesh, vars, new_dist_context) + + # change the selected op stage and output tensor dist attr + new_valid_dist_attr_dict[ + selected_op.desc.id()][1] = changed_stage + new_process_mesh = pipeline_process_meshes[changed_stage] + selected_op_dist_attr.process_mesh = new_process_mesh + for op_dist_attr in new_valid_dist_attr_dict[ + selected_op.desc.id()][0]: + op_dist_attr.process_mesh = new_process_mesh + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + self.set_tensor_dist_attr(selected_op, + selected_op_dist_attr, vars, + new_dist_context) + + # change the next op stage + for idx in range(random_selected_op_idx + 1, len(ops)): + stage = new_valid_dist_attr_dict[ops[idx].desc.id()][1] + valid_dist_attr_list = new_valid_dist_attr_dict[ + ops[idx].desc.id()][0] + new_process_mesh = pipeline_process_meshes[ + changed_stage] + if stage == changed_stage - 1: + new_valid_dist_attr_dict[ + ops[idx].desc.id()][1] = changed_stage + for op_dist_attr in valid_dist_attr_list: + op_dist_attr.process_mesh = new_process_mesh + + new_dist_context.get_op_dist_attr_for_program( + ops[idx]).process_mesh = new_process_mesh + # change the output tensor dist attr + self.change_process_mesh(ops[idx], new_process_mesh, + vars, new_dist_context) + else: + break + else: + new_dist_context.set_op_dist_attr_for_program( + selected_op, selected_op_dist_attr) + self.set_tensor_dist_attr(selected_op, selected_op_dist_attr, vars, + new_dist_context) + + for op in ops: + # make softmax_with_cross_entropy unshard + if op.type == "softmax_with_cross_entropy": + self.make_special_op_unshard(op, ops, vars, new_dist_context, + valid_dist_attr_dict) + break + + if new_valid_dist_attr_dict is None: + return valid_dist_attr_dict, new_dist_context + else: + return new_valid_dist_attr_dict, new_dist_context + + def _search_core(self, + valid_dist_attr_dict, + init_dist_context, + pipeline_process_meshes=None): + times = 0 + best_dist_context = init_dist_context + cost = self.estimate_searched_strategy_cost( + init_dist_context, pipeline_process_meshes).runtime + min_cost = cost + while times < self.max_search_times: + times += 1 + new_dist_context = self.search_once( + self.serial_program_info.train_program, valid_dist_attr_dict, + best_dist_context, pipeline_process_meshes)[1] + cur_cost = self.estimate_searched_strategy_cost( + new_dist_context, pipeline_process_meshes).runtime + if (min_cost - cur_cost) > 0: + best_dist_context = copy.deepcopy(new_dist_context) + min_cost = cur_cost + times = 0 + return best_dist_context, min_cost + + def search(self): + print("Start MCMC searching.") + start_time = time.time() + train_program = self.serial_program_info.train_program + cluster = self.serial_program_info.cluster + processes = paddle.distributed.get_world_size( + ) if cluster is None else len(cluster.get_all_devices("GPU")) + assert processes > 0, "Get process failed." + + process_mesh_topology_list = PlanSpace.enum_process_mesh_topology( + processes) + searched_dist_context = None + min_cost = None + + searched_pipeline_dist_context = None + pipeline_min_cost = None + for process_mesh_topology in process_mesh_topology_list: + print("MCMC search: search process mesh {} with pipeline mode.". + format(process_mesh_topology)) + valid_dist_attr_dict, pipeline_process_meshes, global_process_mesh = PlanSpace.enum_valid_dist_attr_for_program( + train_program, process_mesh_topology, True) + init_dist_context = self.init_program(valid_dist_attr_dict, + train_program, + pipeline_process_meshes, + global_process_mesh) + best_dist_context, cost = self._search_core( + valid_dist_attr_dict, init_dist_context, + pipeline_process_meshes) + print( + "MCMC search: the min cost is {} in the process mesh {} with pipeline mode." + .format(cost, process_mesh_topology)) + best_dist_context._dist_op_context = DistributedOperatorContext() + pipeline_min_cost = cost if pipeline_min_cost is None else pipeline_min_cost + searched_pipeline_dist_context = best_dist_context if searched_pipeline_dist_context is None else searched_pipeline_dist_context + if pipeline_min_cost > cost: + searched_pipeline_dist_context = best_dist_context + pipeline_min_cost = cost + + searched_non_pipeline_dist_context = None + non_pipeline_min_cost = None + for process_mesh_topology in process_mesh_topology_list: + # if process_mesh_topology shape is 3, include pipeline mode by default + if len(process_mesh_topology) == 3: + continue + print("MCMC search: search process mesh {} without pipeline mode.". + format(process_mesh_topology)) + valid_dist_attr_dict, pipeline_process_meshes, global_process_mesh = PlanSpace.enum_valid_dist_attr_for_program( + train_program, process_mesh_topology, False) + init_dist_context = self.init_program(valid_dist_attr_dict, + train_program, + pipeline_process_meshes, + global_process_mesh) + best_dist_context, cost = self._search_core( + valid_dist_attr_dict, init_dist_context, + pipeline_process_meshes) + print( + "MCMC search: the min cost is {} in the process mesh {} without pipeline mode." + .format(cost, process_mesh_topology)) + best_dist_context._dist_op_context = DistributedOperatorContext() + non_pipeline_min_cost = cost if non_pipeline_min_cost is None else non_pipeline_min_cost + searched_non_pipeline_dist_context = best_dist_context if searched_non_pipeline_dist_context is None else searched_non_pipeline_dist_context + if non_pipeline_min_cost > cost: + searched_non_pipeline_dist_context = best_dist_context + non_pipeline_min_cost = cost + + if non_pipeline_min_cost > pipeline_min_cost: + searched_dist_context = searched_pipeline_dist_context + min_cost = pipeline_min_cost + print( + "Better set FLAGS_benchmark=1 to avoid hang problem in the pipeline mode." + ) + else: + searched_dist_context = searched_non_pipeline_dist_context + min_cost = non_pipeline_min_cost + + # rebuild g_process_group + pg0 = get_process_group(0) + for process_mesh in searched_dist_context._process_meshes: + pg0.add_ranks(process_mesh.processes) + end_time = time.time() + print( + "End MCMC searching: the min cost is {} and the search time is {}s." + .format(min_cost, end_time - start_time)) + return searched_dist_context, min_cost + + +class Planner: + + def __init__(self, + serial_program_info, + parallelizer, + algorithm_config=None): + self._serial_program_info = serial_program_info + self._parallelizer = parallelizer + self._algorithm_config = algorithm_config + self._algorithm_searcher = self.create_algorithm_searcher( + algorithm_config) + + @property + def serial_program_info(self): + return self._serial_program_info + + @property + def algorithm_config(self): + return self._algorithm_config + + @property + def algorithm_searcher(self): + return self._algorithm_searcher + + @property + def parallelizer(self): + return self._parallelizer + + def create_algorithm_searcher(self, algorithm_config): + name = algorithm_config.get("name", None) + assert name is not None, "Invalid algorithm config." + + algorithm_searcher = None + if name == "mcmc": + # NOTE: Only GPU clusters are supported now. + max_search_times = algorithm_config.get("max_search_times", None) + algorithm_searcher = MCMC( + self.serial_program_info, self.parallelizer, + max_search_times) if max_search_times is not None else MCMC( + self.serial_program_info, self.parallelizer) + else: + raise NotImplementedError( + "Other search algorithms have not been supported now.") + + return algorithm_searcher + + def search(self): + return self.algorithm_searcher.search() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner_v2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2c0c4617b0f8d83bfcd906f4903011bd944dd3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/planner_v2.py @@ -0,0 +1,56 @@ +# Copyright (c) 2022 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. + +from .completion import Completer +from .dist_context import get_default_distributed_context +from .tuner.parallel_tuner import ParallelTuner + + +class Planner: + + def __init__(self, mode, dist_context): + self._mode = mode + self._dist_context = dist_context + + # NOTE: [HighOrderGrad]. There are grad ops in forward phase, and it need + # dependency of backward-forward ops in forward completion. + default_ctx = get_default_distributed_context() + self._dist_context._dist_op_context = default_ctx.dist_op_context + if not default_ctx.data_parallel: + # Use SSA graph for complex parallism + self._dist_context.initialize(with_graph=True) + else: + # Use program for data parallel parallism + self._dist_context.initialize(with_graph=False) + + self._completer = Completer(self._dist_context) + + self._strategy = dist_context.strategy + # set parallel tuner for auto search + if self._strategy.auto_mode == "full": + self._parallel_tuner = ParallelTuner(self._dist_context, + mode=self._mode) + + @property + def completer(self): + return self._completer + + def plan(self): + if self._strategy.auto_mode == "full": + self._parallel_tuner.tune() + else: + self._completer.complete_forward_annotation() + # parse forward sub block + self._dist_context.block_state.parse_forward_blocks( + self._dist_context.serial_main_program) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_group.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_group.py new file mode 100644 index 0000000000000000000000000000000000000000..10ff0d36fcee9554d3a398013b4b3de554fd0972 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_group.py @@ -0,0 +1,185 @@ +# Copyright (c) 2021 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 + +from collections import OrderedDict + +import paddle +import paddle.fluid.core as core + +from ..collective import _get_global_env +from ..collective import _new_ring_id +from ...fluid.framework import _non_static_mode +from ...fluid.layers.tensor import fill_constant +from paddle.fluid.framework import _enable_legacy_dygraph + + +def get_all_process_groups(): + global _g_process_group_map + return _g_process_group_map.values() + + +def get_process_group(group_id, g_process_group_map=None): + global _g_process_group_map + return _g_process_group_map.get( + group_id, + None) if g_process_group_map is None else g_process_group_map.get( + group_id, None) + + +def get_world_process_group(): + global _g_process_group_map + return _g_process_group_map[0] + + +def clear_all_process_groups(): + global _g_process_group_map + _g_process_group_map = {} + _g_process_group_map[0] = ProcessGroup(0, []) + + +def new_process_group(ranks, group_id=None): + global _g_process_group_map + # A key constructed from ranks is used for avoiding duplication + new_key = ''.join(map(str, sorted(ranks))) + for pg_id, pg in _g_process_group_map.items(): + cur_key = ''.join(map(str, sorted(pg.ranks))) + if pg_id != 0 and new_key == cur_key: + return pg + # If not matching the existing one, construt a new process group + num_groups = len(_g_process_group_map) + # Note: our process group may interfere with the original implementation + # so the created group id should start from the original _new_ring_id() + if group_id == None: + group_id = _new_ring_id() + num_groups + 1 + + new_pg = ProcessGroup(group_id, ranks) + _g_process_group_map[group_id] = new_pg + return new_pg + + +# This implementation refers to lots of Paddle/python/paddle/distributed/collective.py, +# Fleet also has a collective helper which uses ops to initialize communication in +# Paddle/python/paddle/distributed/fleet/meta_optimizers/common.py. We use the first one +# because it seems simple. This should be enhanced to manage the process membership and +# the instantiation process in a more general way. In the future, the process group may +# handle the communication implementation choice. +class ProcessGroup: + + def __init__(self, group_id, ranks): + if group_id == 0 and get_process_group(0) is not None: + assert group_id != 0, "Process group id 0 is reserved for all ranks." + self._group_id = group_id + self._ranks = sorted(ranks) + # Add the current ranks into group 0 + if group_id != 0: + global _g_process_group_map + _g_process_group_map[0].add_ranks(ranks) + self._is_instantiate = False + + @property + def id(self): + return self._group_id + + @property + def ranks(self): + return self._ranks + + @property + def nranks(self): + return len(self._ranks) + + def add_ranks(self, new_ranks): + if set(new_ranks) <= set(self.ranks): + return + else: + assert self.is_instantiate() == False, \ + "Cannot add new ranks after instantiating the process group" + self._ranks.extend(new_ranks) + self._ranks = sorted(list(set(self.ranks))) + + def local_rank(self, global_rank): + if global_rank in self.ranks: + return self.ranks.index(global_rank) + else: + assert False, \ + "Rank {} doesn't belong to this group".format(global_rank) + + def is_instantiate(self): + return self._is_instantiate + + def instantiate(self): + if self._is_instantiate: + return + ring_id = self.id + genv = _get_global_env() + global_rank = genv.rank + + if self.nranks >= 2: + strategy = core.ParallelStrategy() + strategy.nranks = self.nranks + strategy.local_rank = self.local_rank(global_rank) + strategy.trainer_endpoints = [ + genv.trainer_endpoints[i] for i in self.ranks + ] + strategy.current_endpoint = genv.current_endpoint + strategy.nrings = 1 + + if core.is_compiled_with_cuda(): + place = core.CUDAPlace(genv.device_id) + core.NCCLParallelContext(strategy, + place).init_with_ring_id(ring_id) + else: + assert False, ("No CUDA device found") + + # TODO(shenliang03): This is a temporary solution to solve the problem of + # hang caused by cross-creation of new_group + paddle.disable_static() + _enable_legacy_dygraph() + paddle.set_device('gpu:%d' % + paddle.distributed.ParallelEnv().dev_id) + tmp = paddle.to_tensor( + [1], dtype="int32") if _non_static_mode() else fill_constant( + [0], dtype="int32", value="1") + paddle.distributed.all_reduce(tmp, sync_op=True, group=self) + paddle.distributed.wait(tmp, group=self) + paddle.enable_static() + + self._is_instantiate = True + + def is_member(self): + return True + + def __eq__(self, other): + if not isinstance(other, ProcessGroup): + return False + if self.id != other.id: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def __str__(self): + string = "id: {}, nranks: {}, ranks: {}.".format( + self.id, self.nranks, ", ".join(map(str, self.ranks))) + return string + + def __hash__(self): + return hash(self.__str__()) + + +# Note that Process group 0 is reserved for representing all ranks. +# At the beginning, group 0 is empty and new ranks will be added automatically. +_g_process_group_map = OrderedDict() +_g_process_group_map[0] = ProcessGroup(0, []) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..a18fc196477da7d0f1cc8ae26d7b247d05f88fd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh.py @@ -0,0 +1,233 @@ +# Copyright (c) 2021 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. + +import numpy as np +import copy +import paddle + +# Use to store the previous and current process mesh +_g_previous_process_mesh = None +_g_current_process_mesh = None + + +def get_current_process_mesh(): + global _g_current_process_mesh + return _g_current_process_mesh + + +def set_current_process_mesh(process_mesh): + global _g_previous_process_mesh + global _g_current_process_mesh + _g_previous_process_mesh = _g_current_process_mesh + _g_current_process_mesh = process_mesh + + +def reset_current_process_mesh(): + global _g_previous_process_mesh + global _g_current_process_mesh + _g_current_process_mesh = _g_previous_process_mesh + + +class ProcessMesh(object): + """ + The `Processmesh` object describes the topology of the used processes. + + Args: + mesh (list|numpy.array): an n-dimensional array describes the toplogy + of the processes. + dim_names (list, optional): the i-th element of this list gives the name of the + i-th dimension of the mesh. + + Examples: + .. code-block:: python + + import paddle + + mesh = auto.ProcessMesh([[2, 4, 5], [0, 1, 3]], dim_names=["x", "y"]) + assert mesh.shape == [2, 3] + assert mesh.processe_ids == [2, 4, 5, 0, 1, 3] + + """ + + def __init__(self, mesh=None, dim_names=None, shape=None, process_ids=None): + # Use shape and process_ids just for compatibility + # Users should not use these directly + if mesh is None: + assert shape is not None + assert process_ids is not None + mesh = np.array(process_ids).reshape(shape) + + if not isinstance(mesh, list) and \ + not isinstance(mesh, np.ndarray): + raise ValueError( + 'The mesh must be an instance of list or np.ndarray.') + if isinstance(mesh, list): + mesh = np.array(mesh) + + self._mesh = mesh + self._shape = list(self._mesh.shape) + self._process_ids = self._mesh.flatten().tolist() + + assert all(isinstance(p, int) for p in self._process_ids), \ + ("All elements of the mesh must be integer") + assert min( + self._process_ids) >= 0, ('All elements of the mesh must be >= 0.') + unique_process_ids = set(self._process_ids) + assert len(unique_process_ids) == len( + self._process_ids), ('All elements of the mesh must be unique.') + + if dim_names is not None: + assert len(dim_names) == len(self._shape), \ + ("The length of dims_names must be same as the shape of the mesh.") + self._dim_names = copy.deepcopy(dim_names) + else: + self._dim_names = ["d" + str(i) for i in range(len(self._shape))] + unique_dim_names = set(self._dim_names) + assert len(unique_dim_names) == len(self._dim_names), ( + 'All dim_names {} must be unique.'.format(dim_names)) + + # Store all process meshes + from .dist_context import get_default_distributed_context + default_dist_cxt = get_default_distributed_context() + default_dist_cxt.add_process_mesh(self) + # Add new processes to process group 0 + from .process_group import get_process_group + pg0 = get_process_group(0) + pg0.add_ranks(self.processes) + + @property + def shape(self): + """ + Get the shape of this ProcessMesh. + """ + return self._shape + + @property + def process_ids(self): + """ + Get the process ids belonging to this ProcessMesh. + """ + return self._process_ids + + @property + def dim_names(self): + """ + Get the dimension names of this ProcessMesh. + """ + return self._dim_names + + @property + def ndim(self): + """ + Get the number of dimension of this ProcessMesh. + """ + return len(self._shape) + + @property + def mesh(self): + """ + Get the underlying mesh of ProcessMesh. + """ + return self._mesh + + @property + def topology(self): + return self._shape + + @property + def processes(self): + return self._process_ids + + def __getitem__(self, index): + if isinstance(index, tuple): + new_dim_names = [] + for i, item in enumerate(index): + if isinstance(item, slice): + new_dim_names.append(self._dim_names[i]) + new_mesh = self._mesh[index] + if new_mesh.shape: + return ProcessMesh(new_mesh, new_dim_names) + else: + # Wrap a scalar into a list but without dim_names + return ProcessMesh([new_mesh]) + elif isinstance(index, slice): + new_mesh = self._mesh[index] + new_dim_names = self._dim_names + return ProcessMesh(new_mesh, new_dim_names) + else: + new_mesh = self._mesh[index] + new_dim_names = self._dim_names[1:] + if new_mesh.shape: + return ProcessMesh(new_mesh, new_dim_names) + else: + return ProcessMesh([new_mesh]) + + def __enter__(self): + set_current_process_mesh(self) + default_prog = paddle.fluid.default_main_program() + cur_block = default_prog.current_block() + self._old_var_names = list(cur_block.vars.keys()) + self._old_op_size = len(cur_block.ops) + + def __exit__(self, exc_type, exc_value, exc_traceback): + from .dist_tensor import DistributedTensor + from .dist_op import DistributedOperator + default_prog = paddle.fluid.default_main_program() + cur_block = default_prog.current_block() + new_var_names = list(cur_block.vars.keys()) + new_op_size = len(cur_block.ops) + from .dist_context import get_default_distributed_context + default_dist_ctx = get_default_distributed_context() + for name in new_var_names: + if name not in self._old_var_names: + tensor = cur_block.vars[name] + dist_tensor = default_dist_ctx.get_dist_tensor_for_program( + tensor) + if dist_tensor is None: + dist_tensor = DistributedTensor(cur_block.vars[name], + {"process_mesh": self}) + dist_tensor.dist_attr.mark_annotated("process_mesh") + default_dist_ctx.add_dist_tensor_for_program(dist_tensor) + else: + if dist_tensor.dist_attr.process_mesh is None: + dist_tensor.dist_attr.process_mesh = self + dist_tensor.dist_attr.mark_annotated("process_mesh") + + for idx in range(self._old_op_size, new_op_size): + op = cur_block.ops[idx] + dist_op = default_dist_ctx.get_dist_op_for_program(op) + if dist_op is None: + dist_op = DistributedOperator(op, {"process_mesh": self}) + dist_op.dist_attr.mark_annotated("process_mesh") + default_dist_ctx.add_dist_op_for_program(dist_op) + else: + if dist_op.dist_attr.process_mesh is None: + dist_op.dist_attr.process_mesh = self + dist_op.dist_attr.mark_annotated("process_mesh") + reset_current_process_mesh() + + def __eq__(self, other): + if not isinstance(other, ProcessMesh): + return False + if self.shape != other.shape or self.process_ids != other.process_ids: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + def __str__(self): + str = "shape {}, process_ids {}, dim_nams {}".format( + self.shape, self.process_ids, self.dim_names) + return str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh_v2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f3ce83e8bc457d7ef7ec99a0dc2d381f1066a488 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/process_mesh_v2.py @@ -0,0 +1,137 @@ +# Copyright (c) 2021 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. + +import copy +import numpy as np +from paddle.fluid import core + + +class ProcessMesh(core.ProcessMesh): + r""" + The class `Processmesh` describes the topology of logical processes. + + Args: + mesh (list|numpy.array): an N-dimensional array describes the toplogy + of logical processes. + dim_names (list, optional): the i-th element of this list gives the name of the + i-th dimension. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed as dist + + paddle.enable_static() + + mesh = dist.ProcessMesh([[2, 4, 5], [0, 1, 3]]) + assert mesh.shape == [2, 3] + assert mesh.processe_ids == [2, 4, 5, 0, 1, 3] + + """ + + def __init__(self, mesh, dim_names=None): + if not isinstance(mesh, list) and \ + not isinstance(mesh, np.ndarray): + raise ValueError( + 'The mesh must be an instance of list or np.ndarray.') + if isinstance(mesh, list): + mesh = np.array(mesh) + + self._mesh = mesh + + self._shape = list(self._mesh.shape) + + self._process_ids = self._mesh.flatten().tolist() + assert all(isinstance(p, int) for p in self._process_ids), \ + ("All elements of the mesh must be integer") + assert min( + self._process_ids) >= 0, ('All elements of the mesh must be >= 0.') + unique_process_ids = set(self._process_ids) + assert len(unique_process_ids) == len( + self._process_ids), ('All elements of the mesh must be unique.') + + if dim_names is not None: + assert len(dim_names) == len(self._shape), \ + ("The length of dims_names must be same as the shape of the mesh.") + self._dim_names = dim_names + else: + self._dim_names = ["d" + str(i) for i in range(len(self._shape))] + + # Follow the requirement for using pybind11 + core.ProcessMesh.__init__(self, self._shape, self._process_ids, + self._dim_names) + + @property + def mesh(self): + return self._mesh + + +def compute_compatible_process_mesh(process_meshes): + """Compute the compatible process mesh given a list of process meshes.""" + if not process_meshes: + return None + + def _compute_compatible_of_two_process_meshes(pm1, pm2): + if pm1 is None: + return True, pm2 + if pm2 is None: + return True, pm1 + if pm1 == pm2: + return True, pm1 + if pm1.process_ids == pm2.process_ids: + if len(pm1.shape) >= len(pm2.shape): + return True, pm1 + else: + return True, pm2 + process_set1 = set(pm1.process_ids) + process_set2 = set(pm2.process_ids) + if process_set1.issubset(process_set2): + return True, pm2 + if process_set2.issubset(process_set1): + return True, pm1 + return False, None + + compatible_result = None + for process_mesh in process_meshes: + compatible, compatible_result = _compute_compatible_of_two_process_meshes( + compatible_result, process_mesh) + if not compatible: + return None + if compatible_result.empty(): + return None + if isinstance(compatible_result, core.ProcessMesh): + mesh = np.array(compatible_result.process_ids).reshape( + compatible_result.shape) + return ProcessMesh(mesh, compatible_result.dim_names) + elif isinstance(compatible_result, ProcessMesh): + return ProcessMesh(compatible_result.mesh, compatible_result.dim_names) + else: + raise ValueError("Unrecognized ProcessMesh.") + + +def merge_process_mesh(process_meshes): + """Merge a list of process meshes.""" + merged_process_mesh = None + merged_process_ids = set() + for process_mesh in process_meshes: + if process_mesh is not None: + process_ids = set(process_mesh.process_ids) + merged_process_ids = merged_process_ids.union(process_ids) + if len(merged_process_ids) != 0: + merged_process_mesh = ProcessMesh(list(merged_process_ids)) + return merged_process_mesh diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/reshard.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/reshard.py new file mode 100644 index 0000000000000000000000000000000000000000..bb3d2d6cfbaffaa0aac399e3d7b20f85b095cd8f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/reshard.py @@ -0,0 +1,2316 @@ +# Copyright (c) 2021 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 + +import copy +from functools import reduce + +import paddle +import paddle.fluid.core as core +from paddle.utils import unique_name +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import Program, OpProtoHolder +from paddle.distributed.fleet.meta_optimizers.common import OpRole +import paddle.fluid.layers.utils as utils +from ..collective import _get_global_env +from .dist_context import DistributedContext +from .dist_attribute import OperatorDistributedAttribute, TensorDistributedAttribute +from .process_group import new_process_group, ProcessGroup, _g_process_group_map +from .cost import build_comm_desc, CommContext +from .cost import AllgatherOpCost, SendOpCost +from .cost import SliceOpCost, SplitOpCost, ConcatOpCost +from .cluster import Cluster +from .utils import print_program_with_dist_attr, is_gradient_clip_op + +# NOTE: If op in _g_special_ops or _g_gradient_clip_ops, it will not be resharded. +_g_special_ops = ['check_finite_and_unscale', 'update_loss_scaling'] +_g_gradient_clip_ops = [ + "sum", "sqrt", "fill_constant", "elementwise_max", "elementwise_div" +] +_g_subblock_ops = ["while", "conditional_block"] + + +def get_var_with_recursion(var_name, block, program): + """Get var in the parent block if not found in the current block""" + var = None + if var_name in block.vars: + var = block.vars[var_name] + else: + var = block._var_recursive(var_name) + # parent_block = program.blocks[block.parent_idx] + # if var_name in parent_block.vars: + # var = parent_block.vars[var_name] + assert var is not None, "{} is not found".format(var.name) + + return var + + +class AllGatherOpDesc: + """ + Describe the allgather op in the reshard phase. + + Args: + group (list): Process group. + shape (list): The tensor shape. + is_bool (bool): Whether allgather bool data. Default: False. + """ + + def __init__(self, group, shape, is_bool=False): + self._group = group + self._desc = "all_gather" + self._shape = shape + self._is_bool = is_bool + + @property + def is_bool(self): + return self._is_bool + + @property + def group(self): + return self._group + + @property + def desc(self): + return self._desc + + @property + def shape(self): + return self._shape + + def __repr__(self): + return f"op: {self._desc}, group: {self._group}, shape: {self._shape}, is_bool: {self._is_bool}." + + +class SendOpDesc: + """ + Describe the send op in the reshard phase. + + Args: + partition_index (list): The index of partition in complete tensor. + src (int): The source process to send. + dst (int): The destination process to receive. + is_bool (bool): Whether send bool data. Default: False. + """ + + def __init__(self, partition_index, src, dst, is_bool=False): + self._dst = dst + self._partition_index = partition_index + self._desc = "send" + self._shape = [] + self._is_bool = is_bool + self._src = src + + @property + def src(self): + return self._src + + @property + def is_bool(self): + return self._is_bool + + @property + def partition_index(self): + return self._partition_index + + @property + def dst(self): + return self._dst + + @property + def desc(self): + return self._desc + + @property + def shape(self): + if not self._shape: + for item in self.partition_index: + self._shape.append(item[1] - item[0]) + return self._shape + + def __repr__(self): + return f"op: {self._desc}, partition_index: {self._partition_index}, dst: {self._dst}, shape: {self._shape}, is_bool: {self._is_bool}." + + +class RecvOpDesc: + """ + Describe the recv op in the reshard op. + + Args: + partition_index (list): The index of partition in complete tensor. + src (int): The source process to send. + dst (int): The destination process to receive. + is_bool (bool): Whether receive bool data. Default: False. + """ + + def __init__(self, partition_index, src, dst, is_bool=False): + self._src = src + self._partition_index = partition_index + self._desc = "recv" + self._shape = [] + self._is_bool = is_bool + self._dst = dst + + @property + def dst(self): + return self._dst + + @property + def is_bool(self): + return self._is_bool + + @property + def partition_index(self): + return self._partition_index + + @property + def src(self): + return self._src + + @property + def desc(self): + return self._desc + + @property + def shape(self): + if not self._shape: + for item in self.partition_index: + self._shape.append(item[1] - item[0]) + return self._shape + + def __repr__(self): + return f"op: {self._desc}, partition_index: {self._partition_index}, dst: {self._dst}, shape: {self._shape}, is_bool: {self._is_bool}." + + +class SliceOpDesc: + """ + Describe the slice op in the reshard phase. + + Args: + starts (list): It represents start indices of corresponding axis in ``axes``. + ends (list): It represents end indices of corresponding axis in ``axes``. + axes (list): Axes that `starts` and `ends` apply to. + shape (list): The shape of the tensor to be sliced. + """ + + def __init__(self, starts, ends, axes, shape=None): + self._starts = starts + self._ends = ends + self._axes = axes + self._desc = "slice" + self._shape = shape + + @property + def starts(self): + return self._starts + + @property + def ends(self): + return self._ends + + @property + def axes(self): + return self._axes + + @property + def desc(self): + return self._desc + + @property + def shape(self): + return self._shape + + def __repr__(self): + if self._shape is not None: + return f"op: {self._desc}, starts: {self._starts}, ends: {self._ends}, axes: {self._axes}, shape: {self._shape}." + else: + return f"op: {self._desc}, starts: {self._starts}, ends: {self._ends}, axes: {self._axes}." + + +class ConcatOpDesc: + """ + Describe the concat op in the reshard phase. + + Args: + partition_index_list (list): The list contains all partition index. + """ + + def __init__(self, partition_index_list): + self._partition_index_list = partition_index_list + self._desc = "concat" + + @property + def partition_index_list(self): + return self._partition_index_list + + @property + def desc(self): + return self._desc + + def __repr__(self): + return f"op: {self._desc}, partition_index_list: {self._partition_index_list}." + + +class Inserter: + """Insert op required in the reshard process.""" + + @staticmethod + def insert_cast_op(block, idx, tensor, op_role, tensor_type): + # to avoid name conflict with framework + new_var_name = paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join(["cast@RESHARD", 'tmp'])) + out = block.create_var(name=new_var_name, + dtype=tensor_type, + type=tensor.type, + lod_level=tensor.lod_level) + cast_op = block._insert_op(idx, + type='cast', + inputs={'X': [tensor]}, + outputs={'Out': [out]}, + attrs={ + 'in_dtype': tensor.dtype, + 'out_dtype': out.dtype, + 'op_role': op_role + }) + cast_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + @staticmethod + def insert_send_op(block, idx, tensor, src, dst, op_role): + """Insert send op into block at the given index.""" + op_type = 'send_v2' + # use pair comm group + process_group = new_process_group([src, dst]) + send_op = block._insert_op(idx, + type=op_type, + inputs={'X': [tensor]}, + attrs={ + 'ring_id': process_group.id, + 'peer': process_group.ranks.index(dst), + 'use_calc_stream': True, + 'op_role': op_role, + 'dynamic_shape': True + }) + send_op._set_attr('op_namescope', "/auto_parallel/reshard") + + @staticmethod + def insert_recv_op(block, idx, tensor, src, dst, op_role): + """Insert recv op into block at the given index.""" + op_type = 'recv_v2' + # use pair group + process_group = new_process_group([src, dst]) + recv_op = block._insert_op(idx, + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + attrs={ + 'ring_id': process_group.id, + 'peer': process_group.ranks.index(src), + 'out_shape': tensor.shape, + 'dtype': tensor.dtype, + 'use_calc_stream': True, + 'op_role': op_role, + 'dynamic_shape': True + }) + recv_op._set_attr('op_namescope', "/auto_parallel/reshard") + + @staticmethod + def insert_reset_lod_op(block, idx, X, Y, op_role): + """Insert reset_lod op into block at the given index.""" + + new_var_name = paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join(["reset_lod@RESHARD", 'tmp'])) + reset_lod_out = block.create_var(name=new_var_name, + shape=X.shape, + type=X.type, + dtype=X.dtype, + lod_level=X.lod_level) + + reset_op = block._insert_op(idx, + type="lod_reset", + inputs={ + 'X': X, + 'Y': Y + }, + outputs={'Out': reset_lod_out}, + attrs={'op_role': op_role}) + reset_op._set_attr('op_namescope', "/auto_parallel/reshard") + return reset_lod_out + + @staticmethod + def insert_concat_op(block, idx, tensors, axis, op_role): + """Insert concat op into block at the given block.""" + inputs = {'X': tensors} + attrs = {} + attrs['axis'] = axis + attrs['op_role'] = op_role + # to avoid name conflict with framework + helper = LayerHelper('concat@RESHARD', **locals()) + with paddle.static.program_guard(block.program): + out = block.create_var( + name=paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp'])), + dtype=tensors[0].dtype, + shape=None, + lod_level=tensors[0].lod_level, + type=tensors[0].type, + persistable=False, + stop_gradient=False) + concat_op = block._insert_op(idx, + type='concat', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + concat_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + @staticmethod + def insert_slice_op(block, idx, tensor, starts, ends, axes, new_var_name, + op_role): + """Insert slice op into block at the given block.""" + # This is a hack to insert split op to get slice tensor + # 1. [128, 128] => [64, 128]: split + # 2. [128, 128] => [128, 128]: assign + # 3. [128, 128] => [64, 64]: slice, it will replaced by multi split + global_shape = tensor.shape + slice_shape = [ends[i] - starts[i] for i in range(len(starts))] + diff_dims = [] + for index, item in enumerate(slice_shape): + if item != global_shape[index]: + diff_dims.append(index) + + # use assign + if len(diff_dims) == 0: + out = block.create_var(name=new_var_name, + dtype=tensor.dtype, + type=tensor.type, + shape=slice_shape, + lod_level=tensor.lod_level) + inputs = {'X': [tensor]} + outputs = {"Out": [out]} + attrs = {"in_place": False} + slice_op = block._insert_op(idx, + type="assign", + inputs=inputs, + outputs=outputs, + attrs=attrs) + slice_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + # use split once + elif len(diff_dims) == 1: + diff_dim = diff_dims[0] + num_or_sections = global_shape[diff_dim] // slice_shape[diff_dim] + axis = diff_dim + cur_idx = starts[diff_dim] // slice_shape[diff_dim] + input_shape = global_shape + inputs = {'X': tensor} + attrs = {'num': num_or_sections, 'axis': axis, 'op_role': op_role} + new_shape = [] + for index, item in enumerate(tensor.shape): + if index != axis: + new_shape.append(item) + else: + new_shape.append(item // num_or_sections) + with paddle.static.program_guard(block.program): + outs = [ + block.create_var(name=paddle.fluid.unique_name. + generate_with_ignorable_key(".".join( + ['split@RESHARD', 'tmp'])), + dtype=tensor.dtype, + shape=None, + type=tensor.type, + persistable=False, + lod_level=tensor.lod_level, + stop_gradient=False) + for i in range(num_or_sections) + ] + out = outs[cur_idx] + split_op = block._insert_op(idx, + type="split", + inputs=inputs, + outputs={'Out': outs}, + attrs=attrs) + split_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + # use slice + else: + inputs = {'Input': tensor} + infer_flags = list(1 for i in range(len(axes))) + attrs = { + "axes": axes, + "starts": starts, + "ends": ends, + "infer_flags": infer_flags, + 'op_role': op_role + } + out = block.create_var(name=new_var_name, + dtype=tensor.dtype, + type=tensor.type, + lod_level=tensor.lod_level) + slice_op = block._insert_op(idx, + type="slice", + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + slice_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + @staticmethod + def insert_split_op(block, idx, tensor, num_or_sections, op_role, axis=0): + """Insert split op into block at the given index.""" + helper = LayerHelper('split@RESHARD', **locals()) + input_shape = tensor.shape + inputs = {'X': tensor} + attrs = {'num': num_or_sections, 'axis': axis, 'op_role': op_role} + new_shape = [] + for index, item in enumerate(tensor.shape): + if index != axis: + new_shape.append(item) + else: + new_shape.append(item // num_or_sections) + with paddle.static.program_guard(block.program): + outs = [ + block.create_var( + name=paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp'])), + dtype=tensor.dtype, + shape=None, + lod_level=tensor.lod_level, + type=tensor.type, + persistable=False, + stop_gradient=False) for i in range(num_or_sections) + ] + split_op = block._insert_op(idx, + type="split", + inputs=inputs, + outputs={'Out': outs}, + attrs=attrs) + split_op._set_attr('op_namescope', "/auto_parallel/reshard") + return outs + + @staticmethod + def insert_fill_constant_op(block, idx, op_role): + """Insert fill constant op into block at the given index.""" + # to avoid name conflict with framework + helper = LayerHelper('fill_constant@RESHARD', **locals()) + # use paddle.int64 as dtype + with paddle.static.program_guard(block.program): + out = block.create_var( + name=paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp'])), + dtype=paddle.int64, + shape=None, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + inputs = {} + attrs = {'force_cpu': False} + attrs['str_value'] = str(int("1")) + attrs['value'] = int("1") + attrs['dtype'] = out.dtype + attrs['op_role'] = op_role + utils.get_shape_tensor_inputs(inputs=inputs, + attrs=attrs, + shape=[0], + op_type='fill_constant') + fillconstant_op = block._insert_op(idx, + type='fill_constant', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + out.stop_gradient = True + fillconstant_op._set_attr('op_namescope', "/auto_parallel/reshard") + return out + + @staticmethod + def insert_allgather_op(block, idx, tensor, ranks, op_role): + """Insert allgather op into block at the given index.""" + tensor_list = [] + group = new_process_group(ranks) + idx_offset = 0 + + # instant process group before insert allgather op. + if not group.is_instantiate(): + # insert fill_constant op + fill_constant_out = Inserter.insert_fill_constant_op( + block, idx, op_role) + fill_constant_out.stop_gradient = True + + # insert c_allreduce_sum op + allreduce_op = block._insert_op( + idx + 1, + type="c_allreduce_sum", + inputs={'X': [fill_constant_out]}, + outputs={'Out': [fill_constant_out]}, + attrs={ + 'ring_id': 0, + 'use_calc_stream': True, + 'op_role': op_role + }) + allreduce_op._set_attr('op_namescope', "/auto_parallel/reshard") + # insert c_sync_calc_stream op + sync_calc_op = block._insert_op( + idx + 2, + type="c_sync_calc_stream", + inputs={'X': [fill_constant_out]}, + outputs={'Out': [fill_constant_out]}, + attrs={'op_role': op_role}) + sync_calc_op._set_attr('op_namescope', "/auto_parallel/reshard") + idx_offset = 3 + + # insert c_allgather op + op_type = 'c_allgather' + # to avoid name conflict with framework + helper = LayerHelper(op_type + "@RESHARD", **locals()) + with paddle.static.program_guard(block.program): + allgather_out = block.create_var( + name=paddle.fluid.unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp'])), + dtype=tensor.dtype, + shape=None, + lod_level=tensor.lod_level, + type=tensor.type, + persistable=False, + stop_gradient=False) + allgather_op = block._insert_op(idx + idx_offset, + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [allgather_out]}, + attrs={ + 'ring_id': group.id, + 'use_calc_stream': True, + 'nranks': group.nranks, + 'op_role': op_role + }) + allgather_op._set_attr('op_namescope', "/auto_parallel/reshard") + idx_offset += 1 + + # insert split op + split_out = Inserter.insert_split_op(block, idx + idx_offset, + allgather_out, group.nranks, + op_role) + idx_offset += 1 + tensor_list.extend(split_out) + return tensor_list, idx_offset + + @staticmethod + def concat_partitions_with_op(partition_tensor_list, tensor, + partition_index, block, idx, op_role): + """Concat the tensors and insert concat op.""" + if not partition_tensor_list: + partition_tensor_list.append((tensor, partition_index)) + else: + i = 0 + has_concat = False + while i < len(partition_tensor_list): + concat_axis, first_order, new_partition = Resharder.compute_concat_info( + partition_tensor_list[i][1], partition_index) + if concat_axis != -1: + has_concat = True + _ = Inserter.insert_concat_op(block, idx[0], [partition_tensor_list[i][0], tensor], concat_axis, op_role) \ + if first_order == 0 else \ + Inserter.insert_concat_op(block, idx[0], [tensor, partition_tensor_list[i][0]], concat_axis, op_role) + partition_tensor_list.pop(i) + idx[0] += 1 + Inserter.concat_partitions_with_op(partition_tensor_list, _, + new_partition, block, + idx, op_role) + break + i += 1 + if not has_concat: + partition_tensor_list.append((tensor, partition_index)) + + +class Remover: + """Remove var and op in the reshard process.""" + + @staticmethod + def remove_no_need_ops(auto_parallel_main_prog, dist_context, rank_id): + """Remove no need ops in the main program""" + not_remove_op_ref = [ + "create_py_reader", "create_double_buffer_reader", "read" + ] + + # NOTE: The nested sub block is not be supported now. + remove_block_order = [] + for block_idx in Resharder.while_block_info: + remove_block_order.append(block_idx) + + for block_idx, block in enumerate(auto_parallel_main_prog.blocks): + if block_idx not in remove_block_order: + remove_block_order.append(block_idx) + + # the sub block should be removed first + for block_idx in remove_block_order: + remove_op_idx = [] + block = auto_parallel_main_prog.blocks[block_idx] + ops = block.ops + vars = block.vars + for idx, op in enumerate(ops): + if op.type == "read": + dim_list = [] + for var_name in op.output_arg_names: + dim_list.extend( + get_var_with_recursion( + var_name, block, auto_parallel_main_prog).shape) + for i in range(idx, -1, -1): + if ops[i].type == "create_py_reader": + ops[i]._set_attr("shape_concat", dim_list) + break + continue + + # replace the input and output of c_sync_comm_stream op when in pipeline scene. + if op.type == "c_sync_comm_stream": + need_save = [] + for var_name in op.input_arg_names: + process_mesh = dist_context.get_tensor_dist_attr_for_program( + get_var_with_recursion( + var_name, block, + auto_parallel_main_prog)).process_mesh + if rank_id in process_mesh.processes: + need_save.append(var_name) + if not need_save: + remove_op_idx.append(idx) + continue + + proto = OpProtoHolder.instance().get_op_proto(op.type) + op.desc.set_input(proto.inputs[0].name, need_save) + op.desc.set_output(proto.outputs[0].name, need_save) + continue + + # judge the other op whether should be removed. + op_dist_attr = dist_context.get_op_dist_attr_for_program(op) + if op_dist_attr is not None: + op_process_mesh = op_dist_attr.process_mesh + if rank_id not in op_process_mesh.processes and op.type not in not_remove_op_ref: + remove_op_idx.append(idx) + + for idx in remove_op_idx[::-1]: + block._remove_op(idx) + + @staticmethod + def remove_no_need_vars(auto_parallel_main_prog, dist_params_grads, + feed_var_names): + """Remove no need vars in the main program""" + for block_idx, block in enumerate(auto_parallel_main_prog.blocks): + remove_vars = set() + ops = block.ops + vars = block.vars + need_vars = set() + for op in ops: + for var_name in op.input_arg_names: + if var_name in vars: + need_vars.add(var_name) + for var_name in op.output_arg_names: + if var_name in vars: + need_vars.add(var_name) + for var in vars: + if var not in need_vars: + remove_vars.add(var) + + # change dist_params_grads, the optimize op just in block 0. + if block_idx == 0: + param_grad_map = {} + for op in ops: + if int(op.attr('op_role')) == int(OpRole.Optimize): + if "Param" in op.input_names and "Grad" in op.input_names: + param_name = op.input("Param")[0] + grad_name = op.input("Grad")[0] + param_grad_map[param_name] = grad_name + + need_remove_idx = [] + for idx, item in enumerate(dist_params_grads): + if item[0].name not in param_grad_map.keys(): + need_remove_idx.append(idx) + + for idx in need_remove_idx[::-1]: + dist_params_grads.pop(idx) + + idx = 0 + while idx < len(dist_params_grads): + param_name = dist_params_grads[idx][0].name + grad_name = dist_params_grads[idx][1].name + if grad_name != param_grad_map[param_name]: + dist_params_grads[idx] = ( + vars[param_name], vars[param_grad_map[param_name]]) + idx += 1 + + for var in remove_vars: + if var in feed_var_names: + continue + block._remove_var(var) + + @staticmethod + def remove_no_need_in_main(auto_parallel_main_prog, dist_context, rank_id, + dist_params_grads): + """Remove no need vars and ops in the main program.""" + Remover.remove_no_need_ops(auto_parallel_main_prog, dist_context, + rank_id) + Resharder.change_while_op_input_and_output(auto_parallel_main_prog, + dist_context) + # 'feed_var_names' cannot be removed from auto_parallel_main_prog + feed_var_names = [] + for var in sum(list(dist_context.serial_feed_vars.values()), []): + feed_var_names.append(var.name) + Remover.remove_no_need_vars(auto_parallel_main_prog, dist_params_grads, + feed_var_names) + + @staticmethod + def remove_no_need_in_startup(auto_parallel_main_prog, + auto_parallel_startup_prog): + """Remove no need vars and ops in the startup program.""" + main_input_vars = set() + main_ops = auto_parallel_main_prog.global_block().ops + for op in main_ops: + for var_name in op.input_arg_names: + main_input_vars.add(var_name) + + startup_block = auto_parallel_startup_prog.global_block() + startup_output_vars = set() + startup_ops = startup_block.ops + for op in startup_ops: + # skip c_sync_comm_stream op + if op.type == "c_sync_comm_stream": + continue + for var_name in op.output_arg_names: + startup_output_vars.add(var_name) + + need_vars = set() + for var_name in startup_output_vars: + if var_name in main_input_vars: + need_vars.add(var_name) + + startup_ops = startup_block.ops + actual_need_vars = set() + for idx, op in enumerate(startup_ops): + is_need_op = False + if op.type == "c_sync_comm_stream": + continue + for var_name in op.output_arg_names: + if var_name in need_vars: + is_need_op = True + break + if is_need_op: + for var_name in op.output_arg_names: + actual_need_vars.add(var_name) + for var_name in op.input_arg_names: + actual_need_vars.add(var_name) + + remove_vars = set() + for var_name in startup_block.vars: + if var_name not in actual_need_vars: + remove_vars.add(var_name) + for var in remove_vars: + startup_block._remove_var(var) + + remove_op_idx = [] + vars = startup_block.vars + for idx, op in enumerate(startup_block.ops): + is_no_need_op = False + if op.type == "c_sync_comm_stream": + var_names = [] + for var_name in op.input_arg_names: + if var_name in vars: + var_names.append(var_name) + if not var_names: + remove_op_idx.append(idx) + else: + proto = OpProtoHolder.instance().get_op_proto(op.type) + op.desc.set_input(proto.inputs[0].name, var_names) + op.desc.set_output(proto.outputs[0].name, var_names) + continue + + for var_name in op.output_arg_names: + if var_name not in vars: + is_no_need_op = True + break + if is_no_need_op: + remove_op_idx.append(idx) + for idx in remove_op_idx[::-1]: + startup_block._remove_op(idx) + + +class Resharder: + """ + Reshard tensor in the program according to its distributed attribute and corresponding op distributed attribute. + + Args: + auto_parallel_main_prog (Program): An auto parallel main program. + auto_parallel_startup_prog (Program): An auto parallel startup program. + rank_id (int): The process id. + dist_context (DistributedContext): The distributed context of this rank. + dist_params_grads (list): The list contains the tuple of param and grad. + batch_size (int): The batch size. Default: None. + """ + while_block_info = {} + + def __init__(self, + auto_parallel_main_prog, + auto_parallel_startup_prog, + rank_id, + dist_context, + dist_params_grads, + batch_size=None): + assert isinstance(auto_parallel_main_prog, Program), "The type of auto_parallel_main_prog should be Program, " \ + "but got {}.".format(type(auto_parallel_main_prog)) + if auto_parallel_startup_prog is not None: + assert isinstance(auto_parallel_main_prog, Program), "The type of auto_parallel_startup_prog should be Program or None, " \ + "but got {}.".format(type(auto_parallel_startup_prog)) + assert isinstance(rank_id, int), "The type of rank_id should be int, " \ + "but got {}.".format(type(rank_id)) + assert isinstance(dist_context, DistributedContext), "The type of dist_context should be DistributedContext, " \ + "but got {}.".format(type(dist_context)) + + if batch_size is not None: + assert isinstance(batch_size, int), "The type of batch_size should be int, " \ + "but got {}.".format(type(batch_size)) + + self._auto_parallel_main_prog = auto_parallel_main_prog + self._auto_parallel_startup_prog = auto_parallel_startup_prog + self._rank_id = rank_id + self._dist_context = dist_context + self._dist_params_grads = dist_params_grads + self._batch_size = batch_size + self._has_sent = {} + self._has_recv = {} + self._has_allgather = {} + # to avoid reshard repeatly + self._has_resharded = {} + + @property + def auto_parallel_main_prog(self): + return self._auto_parallel_main_prog + + @property + def auto_parallel_startup_prog(self): + return self._auto_parallel_startup_prog + + @property + def rank_id(self): + return self._rank_id + + @property + def dist_context(self): + return self._dist_context + + @property + def dist_params_grads(self): + return self._dist_params_grads + + @property + def batch_size(self): + return self._batch_size + + @property + def has_sent(self): + return self._has_sent + + @property + def has_recv(self): + return self._has_recv + + @property + def has_allgather(self): + return self._has_allgather + + @staticmethod + def compute_partition_shape(complete_shape, dims_mapping, process_shape): + """Compute the shape of partition.""" + partition_shape = [] + for idx, item in enumerate(complete_shape): + if dims_mapping[idx] == -1: + partition_shape.append(item) + else: + partition_shape.append(item // process_shape[dims_mapping[idx]]) + + return partition_shape + + @staticmethod + def compute_process_index(process, process_group, process_shape): + """Compute the index of process_shape corresponding to the process.""" + relative_process = process_group.index(process) + process_index = [] + product = reduce(lambda x, y: x * y, process_shape) + + for i in range(len(process_shape)): + idx = relative_process // (product // process_shape[i]) + product = product // process_shape[i] + relative_process = relative_process - relative_process // product * product + process_index.append(idx) + + return process_index + + @staticmethod + def compute_partition_index(process, complete_shape, dims_mapping, + process_shape, process_group): + """Compute the partition index in complete tensor.""" + partition_shape = Resharder.compute_partition_shape( + complete_shape, dims_mapping, process_shape) + process_index = Resharder.compute_process_index(process, process_group, + process_shape) + partition_index = [] + + for i in range(len(complete_shape)): + if dims_mapping[i] == -1: + partition_index.append([0, partition_shape[i]]) + else: + partition_index.append([ + process_index[dims_mapping[i]] * partition_shape[i], + (process_index[dims_mapping[i]] + 1) * partition_shape[i] + ]) + + return partition_index + + @staticmethod + def compute_concat_info(partition_index_x, partition_index_y): + """Judge whether two partition can be concatenated and compute concatenated partition index.""" + differ_count = 0 + concat_axis = -1 + first_order = 0 + new_partition = [] + + for idx, item in enumerate(partition_index_x): + if item != partition_index_y[idx]: + differ_count += 1 + if item[1] == partition_index_y[idx][ + 0] and item[0] < partition_index_y[idx][1]: + concat_axis = idx + new_partition.append([item[0], partition_index_y[idx][1]]) + elif item[0] == partition_index_y[idx][ + 1] and item[1] > partition_index_y[idx][0]: + first_order = 1 + concat_axis = idx + new_partition.append([partition_index_y[idx][0], item[1]]) + else: + new_partition.append(item) + + if differ_count == 1: + return concat_axis, first_order, new_partition + else: + return -1, first_order, new_partition + + @staticmethod + def compute_complete_shape(slice_shape, process_shape, dims_mapping): + """compute the complete shape of the slice tensor with its process mesh and dims mapping""" + complete_shape = [] + for idx, item in enumerate(slice_shape): + if dims_mapping[idx] == -1: + complete_shape.append(item) + else: + complete_shape.append(item * process_shape[dims_mapping[idx]]) + return complete_shape + + @staticmethod + def concat_partitions(partition_index_list, partition_index): + """Concat the given partitions without inserting concat op.""" + if not partition_index_list: + partition_index_list.append(partition_index) + else: + i = 0 + has_concat = False + while i < len(partition_index_list): + concat_axis, _, new_partition = Resharder.compute_concat_info( + partition_index_list[i], partition_index) + if concat_axis != -1: + has_concat = True + partition_index_list.pop(i) + Resharder.concat_partitions(partition_index_list, + new_partition) + break + i += 1 + if not has_concat: + partition_index_list.append(partition_index) + + @staticmethod + def change_while_op_input_and_output(auto_parallel_main_prog, dist_context): + """Change while op input and output after the corresponding sub block ops removed""" + for sub_block_idx in Resharder.while_block_info: + sub_block = auto_parallel_main_prog.blocks[sub_block_idx] + parent_while_op_id = Resharder.while_block_info[sub_block_idx][ + "op_id"] + parent_block = auto_parallel_main_prog.blocks[sub_block.parent_idx] + + sub_block_op_inputs = set() + sub_block_op_outputs = [] + for op in sub_block.ops: + # skip the input and output of operators inserted in the reshard phase + dist_op = dist_context.get_dist_op_for_program(op) + if dist_op or (op.type == "slice" and not dist_op) or ( + op.type == "split" + and not dist_op) or (op.type == "assign" + and not dist_op): + for var_name in op.output_arg_names: + if var_name not in sub_block_op_outputs: + sub_block_op_outputs.append(var_name) + for var_name in op.input_arg_names: + sub_block_op_inputs.add(var_name) + + # find the while op + while_op = None + for op in parent_block.ops: + if op.desc.id() == parent_while_op_id and op.type == "while": + while_op = op + break + + if while_op is None: + continue + + # find the actual input and output of while op + proto = OpProtoHolder.instance().get_op_proto(while_op.type) + new_X = [] + for var_name in while_op.input("X"): + if var_name in sub_block_op_inputs: + new_X.append(var_name) + assert new_X + new_X.sort() + while_op.desc.set_input(proto.inputs[0].name, new_X) + + new_Out = [] + for var_name in while_op.output("Out"): + for output_name in sub_block_op_outputs[::-1]: + if output_name.find(var_name) != -1 and ( + len(var_name) == len(output_name) + or "@RESHARD" in output_name): + if output_name not in new_Out: + new_Out.append(output_name) + assert new_Out + while_op.desc.set_output(proto.outputs[0].name, new_Out) + + def is_overlapped(self, shape_x, shape_y): + """Judge whether two partitions intersect on the specified dimension.""" + overlapped = False + if (shape_y[0] <= shape_x[0] < shape_y[1]) or (shape_x[0] <= shape_y[0] + < shape_x[1]): + overlapped = True + return overlapped + + def is_unshard(self, dims_mapping): + for dim in dims_mapping: + if dim != -1: + return False + return True + + def is_special_op(self, op): + global _g_special_ops, _g_gradient_clip_ops + if op.type in _g_special_ops: + return True + if is_gradient_clip_op(op) and op.type in _g_gradient_clip_ops: + return True + return False + + def is_condition_replicative(self, op): + sub_block = self.auto_parallel_main_prog.blocks[op.attr("sub_block").id] + + if op.type == "while": + input_cond = op.input("Condition") + elif op.type == "conditional_block": + input_cond = op.input("Cond") + + # the dims mapping of condition tensor should be replicative + for var_name in input_cond: + var = get_var_with_recursion(var_name, sub_block, + self.auto_parallel_main_prog) + dist_tensor = self.dist_context.get_dist_tensor_for_program(var) + tensor_dist_attr = dist_tensor.dist_attr + var_dims_mapping = tensor_dist_attr.dims_mapping + for dim in var_dims_mapping: + if dim != -1: + return False + + return True + + def need_reshard(self, dist_tensor, dist_attr, op_input=True, dist_op=None): + """Judge the tensor whether needs to be resharded.""" + is_reshard = False + tensor_dist_attr = dist_tensor.dist_attr + tensor_dims_mapping = tensor_dist_attr.dims_mapping + tensor_process_mesh = tensor_dist_attr.process_mesh + + # dist_attr is [process_mesh, dims_mapping] and process_mesh is not a union + op_process_mesh = dist_attr[0] + + if op_input: + op_input_dims_mapping = dist_attr[1] + if all( + map(lambda x: x, [ + tensor_dims_mapping, tensor_process_mesh, + op_input_dims_mapping, op_process_mesh + ])): + # judge whether need reshard by dims_mapping + if tensor_dims_mapping != op_input_dims_mapping: + if tensor_process_mesh not in self.dist_context.process_meshes: + # assert whether -1 when union. + for item in tensor_dims_mapping: + if item != -1: + raise ValueError( + "The dim must be -1 when tensor process mesh is a union." + ) + # tensor process_mesh: [0, 1, 2, 3], dims_mapping: [-1, -1] + # op process_mesh: [4, 5], dims_mapping: [0, -1] + # reshard is not supported such as above + if not is_reshard: + return is_reshard + else: + raise ValueError( + "it is not supported that tensor process mesh is a union and needs reshard." + ) + is_reshard = True + + # judge whether need reshard by process_mesh + if tensor_process_mesh != op_process_mesh: + is_reshard = True + else: + op_output_dims_mapping = dist_attr[1] + if all( + map(lambda x: x, [ + tensor_dims_mapping, tensor_process_mesh, + op_output_dims_mapping, op_process_mesh + ])): + if tensor_dims_mapping != op_output_dims_mapping: + raise ValueError( + "It is not supported that tensor dims mapping is different from op output dims mapping." + ) + if tensor_process_mesh != op_process_mesh: + is_reshard = True + + return is_reshard + + def get_op_process_meshes(self, op): + """Get sub process meshes of the given op if op process mesh is a union.""" + process_meshes = [] + dist_op = self.dist_context.get_dist_op_for_program(op) + op_process_mesh = dist_op.dist_attr.process_mesh + + for process_mesh in self.dist_context.process_meshes: + if set(process_mesh.processes) & (set( + op_process_mesh.processes)) and len( + process_mesh.processes) < len( + op_process_mesh.processes): + process_meshes.append(process_mesh) + + # it means the process mesh is not a union when process meshes is null + if not process_meshes: + process_meshes.append(op_process_mesh) + + return process_meshes + + def find_op_desc_seq(self, dist_tensor, dist_attr, serial=False): + """ + Find the op description sequence to reshard the source tensor for matching the op requirement. + + Args: + dist_tensor (DistributedTensor): A distributed tensor. + dist_attr (list): A list contains process_mesh and dims_mapping such as [process_mesh, dims_mapping]. + serial (bool): If serial is true, the dist tensor and dist op come from serial program. Otherwise, they come from auto program. + + Returns: + Dict, the dict represents the required op description sequence corresponding to process, The key of dict is + process and value is a list containing op description. + """ + tensor_dist_attr = dist_tensor.dist_attr + source_tensor = dist_tensor.serial_tensor + tensor_name = source_tensor.name + + source_dims_mapping = tensor_dist_attr.dims_mapping + source_process_mesh = tensor_dist_attr.process_mesh + source_process_group = source_process_mesh.processes + source_process_shape = source_process_mesh.topology + + target_process_mesh = dist_attr[0] + target_dims_mapping = dist_attr[1] + target_process_group = target_process_mesh.processes + target_process_shape = target_process_mesh.topology + + if source_tensor.shape[0] < 0: + assert source_tensor.shape[0] == -1 + new_shape = list(source_tensor.shape) + new_shape[0] = self.batch_size + source_tensor.desc.set_shape(new_shape) + + complete_shape = Resharder.compute_complete_shape( + source_tensor.shape, source_process_shape, + source_dims_mapping) if not serial else source_tensor.shape + op_desc_seq = {} + + # TODO: if the target process group has the same process with source process group + if set(target_process_group).intersection(set( + source_process_group)) and set(target_process_group).difference( + set(source_process_group)): + pass + + elif target_process_group != source_process_group: + partition_process_mapping_list = [] + for source_process in source_process_group: + # get partition index of source process + source_partition_index = Resharder.compute_partition_index(source_process, complete_shape, source_dims_mapping, \ + source_process_shape, source_process_group) + if not partition_process_mapping_list: + # the item in partition_process_mapping_list is source_partition_index, which processes and whether has been used + partition_process_mapping_list.append( + [source_partition_index, [source_process], [False]]) + else: + partition_list = list( + [item[0] for item in partition_process_mapping_list]) + process_list = list( + [item[1] for item in partition_process_mapping_list]) + has_used = list( + [item[2] for item in partition_process_mapping_list]) + + if partition_list.count(source_partition_index) == 1: + index = partition_list.index(source_partition_index) + process_list[index].append(source_process) + has_used[index].append(False) + else: + partition_process_mapping_list.append( + [source_partition_index, [source_process], [False]]) + + for target_process in target_process_group: + # has_sent means the source_partition_index has been sent to target_process + has_sent = [] + target_partition_index = Resharder.compute_partition_index( + target_process, complete_shape, target_dims_mapping, + target_process_shape, target_process_group) + partition_index_list = [] + all_partition_index_list = [] + for source_process in source_process_group: + source_partition_index = Resharder.compute_partition_index( + source_process, complete_shape, source_dims_mapping, + source_process_shape, source_process_group) + to_send_process = None + if all(_ for _ in list(map(self.is_overlapped, source_partition_index, target_partition_index))) \ + and source_partition_index not in has_sent: + idx = list([ + item[0] for item in partition_process_mapping_list + ]).index(source_partition_index) + has_used = list([ + item[2] for item in partition_process_mapping_list + ])[idx] + process_list = list([ + item[1] for item in partition_process_mapping_list + ])[idx] + i = 0 + while i < len(has_used): + if not has_used[i]: + to_send_process = process_list[i] + has_used[i] = True + break + i += 1 + + if i == len(has_used): + has_used = list(map(lambda x: False, has_used)) + to_send_process = process_list[0] + has_used[0] = True + assert to_send_process is not None, "Failed to find the send process." + + if to_send_process not in op_desc_seq.keys(): + op_desc_seq[to_send_process] = [] + if target_process not in op_desc_seq.keys(): + op_desc_seq[target_process] = [] + all_partition_index_list.append(source_partition_index) + + # append send and recv op desc + is_bool = ( + dist_tensor.serial_tensor.dtype == paddle.bool) + send_op_desc = SendOpDesc(source_partition_index, + to_send_process, + target_process, + is_bool=is_bool) + recv_op_desc = RecvOpDesc(source_partition_index, + to_send_process, + target_process, + is_bool=is_bool) + op_desc_seq[to_send_process].append(send_op_desc) + op_desc_seq[target_process].append(recv_op_desc) + has_sent.append(source_partition_index) + Resharder.concat_partitions(partition_index_list, + source_partition_index) + + # append concat op desc + op_desc_seq[target_process].append( + ConcatOpDesc(all_partition_index_list)) + + # append slice op desc + slice_starts = [] + slice_ends = [] + slices_axes = [] + concatenated_partition_index = partition_index_list[0] + to_slice_tensor_shape = [] + + for idx, item in enumerate(concatenated_partition_index): + slice_starts.append(target_partition_index[idx][0] - + item[0]) + slice_ends.append(target_partition_index[idx][1] - item[0]) + slices_axes.append(idx) + to_slice_tensor_shape.append(item[1] - item[0]) + + op_desc_seq[target_process].append( + SliceOpDesc(slice_starts, + slice_ends, + slices_axes, + shape=to_slice_tensor_shape)) + + # in the same process group, it will use allgahther and slice op. + else: + # NOTE: It just supports even partition scene. + partition_index_list = [] + all_partition_index_list = [] + process_index = [] + for source_process in source_process_group: + source_partition_index = Resharder.compute_partition_index( + source_process, complete_shape, source_dims_mapping, + source_process_shape, source_process_group) + if source_partition_index not in partition_index_list: + partition_index_list.append(source_partition_index) + process_index.append([[ + source_process, + ], source_partition_index]) + else: + process_index[partition_index_list.index( + source_partition_index)][0].append(source_process) + + for i in range(len(process_index[0][0])): + group = [] + for j in range(len(process_index)): + group.append(process_index[j][0][i]) + if i == 0: + all_partition_index_list.append(process_index[j][1]) + for process in group: + # append slice op desc + slice_starts = [] + slice_ends = [] + slices_axes = [] + target_partition_index = Resharder.compute_partition_index( + process, complete_shape, target_dims_mapping, + target_process_shape, target_process_group) + for idx, item in enumerate(target_partition_index): + slice_starts.append(item[0]) + slice_ends.append(item[1]) + slices_axes.append(idx) + + to_slice_tensor_shape = dist_tensor.global_sizes() + slice_op_desc = SliceOpDesc(starts=slice_starts, + ends=slice_ends, + axes=slices_axes, + shape=to_slice_tensor_shape) + allgather_shape = None if not serial else dist_tensor.local_sizes( + rank=process) + op_desc_seq[process] = [AllGatherOpDesc(group=group, shape=allgather_shape, is_bool=(source_tensor.dtype == paddle.bool)), + ConcatOpDesc(partition_index_list=all_partition_index_list), slice_op_desc] \ + if len(group) > 1 else [slice_op_desc] + + return op_desc_seq + + def parse_op_desc(self, block, op_desc_seq, var_name, reshard_op, + dist_attr): + """Parse op desc sequence and insert op in the block""" + tensor_list = [] + partition_tensor_list = [] + if self.rank_id not in op_desc_seq.keys(): + return + op_desc_list = op_desc_seq[self.rank_id] + + idx = None + for index, op in list(enumerate(block.ops)): + if op.desc.id == reshard_op.desc.id: + idx = index + break + assert idx is not None, "The op for reshard cannot be found in the rank {} program.".format( + self.rank_id) + + matched_op = block.ops[idx] + source_tensor = get_var_with_recursion(var_name, block, + self.auto_parallel_main_prog) + for op_desc in op_desc_list: + if isinstance(op_desc, AllGatherOpDesc): # noqa: F401 + if var_name not in self.has_allgather.keys(): + self.has_allgather[var_name] = [] + if not self.has_allgather[var_name] or op_desc.group not in list( + map(lambda x: x[0], self.has_allgather[var_name])): + if op_desc.is_bool: + # for bool data allgather, cast to int64 -> allgather -> cast bool + out_cast = Inserter.insert_cast_op( + block, idx, source_tensor, + reshard_op.attr('op_role'), paddle.int64) + tensor_list, idx_offset = Inserter.insert_allgather_op( + block, idx + 1, out_cast, op_desc.group, + reshard_op.attr('op_role')) + idx += idx_offset + tensor_name_list = [] + for var in tensor_list: + out_cast = Inserter.insert_cast_op( + block, idx, var, reshard_op.attr('op_role'), + paddle.bool) + tensor_name_list.append(out_cast.name) + idx += 1 + self.has_allgather[var_name].append( + [op_desc.group, tensor_name_list]) + else: + tensor_list, idx_offset = Inserter.insert_allgather_op( + block, idx, source_tensor, op_desc.group, + reshard_op.attr('op_role')) + idx += idx_offset + tensor_name_list = [var.name for var in tensor_list] + self.has_allgather[var_name].append( + [op_desc.group, tensor_name_list]) + else: + for item in self.has_allgather[var_name]: + if op_desc.group == item[0]: + tensor_list = [ + get_var_with_recursion( + var_name, block, + self.auto_parallel_main_prog) + for var_name in item[1] + ] + break + assert tensor_list, "The result of parsing allgather op should not be None." + + elif isinstance(op_desc, SendOpDesc): + if var_name not in self.has_sent.keys(): + self.has_sent[var_name] = [] + if op_desc.dst not in self.has_sent[var_name]: + if op_desc.is_bool: + out_cast = Inserter.insert_cast_op( + block, idx, source_tensor, + reshard_op.attr('op_role'), paddle.int64) + Inserter.insert_send_op(block, idx + 1, out_cast, + op_desc.src, op_desc.dst, + reshard_op.attr('op_role')) + idx += 2 + else: + Inserter.insert_send_op(block, idx, source_tensor, + op_desc.src, op_desc.dst, + reshard_op.attr('op_role')) + idx += 1 + self.has_sent[var_name].append(op_desc.dst) + + elif isinstance(op_desc, RecvOpDesc): + if var_name not in self.has_recv.keys(): + self.has_recv[var_name] = {} + if op_desc.src not in self.has_recv[var_name].keys(): + partition_index = op_desc.partition_index + shape = [] + for index in partition_index: + shape.append(index[1] - index[0]) + if op_desc.is_bool: + # for bool data, recv int64 -> cast to bool + recv_tensor = block.create_var( + name=unique_name.generate(var_name + "@recv"), + shape=shape, + lod_level=source_tensor.lod_level, + dtype=paddle.int64, + type=source_tensor.type) + Inserter.insert_recv_op(block, idx, recv_tensor, + op_desc.src, op_desc.dst, + reshard_op.attr('op_role')) + out_cast = Inserter.insert_cast_op( + block, idx + 1, recv_tensor, + reshard_op.attr('op_role'), paddle.bool) + tensor_list.append(out_cast) + idx += 2 + self.has_recv[var_name][op_desc.src] = out_cast + else: + recv_tensor = block.create_var( + name=unique_name.generate(var_name + "@recv"), + shape=shape, + lod_level=source_tensor.lod_level, + dtype=source_tensor.dtype, + type=source_tensor.type) + Inserter.insert_recv_op(block, idx, recv_tensor, + op_desc.src, op_desc.dst, + reshard_op.attr('op_role')) + + # for lod tensor, need reset lod after received + if recv_tensor.lod_level != 0: + set_lod = False + # use data lod to reset tensor lod + for tmp_block in self.auto_parallel_main_prog.blocks: + for tmp_var_name in tmp_block.vars: + tmp_var = tmp_block.vars[tmp_var_name] + if tmp_var.is_data and tmp_var.lod_level == recv_tensor.lod_level: + reset_lod_out = Inserter.insert_reset_lod_op( + block, idx + 1, recv_tensor, + tmp_var, reshard_op.attr('op_role')) + tensor_list.append(reset_lod_out) + idx += 2 + self.has_recv[var_name][ + op_desc.src] = reset_lod_out + set_lod = True + break + if set_lod: + break + assert set_lod is True + else: + tensor_list.append(recv_tensor) + idx += 1 + self.has_recv[var_name][op_desc.src] = recv_tensor + else: + tensor_list.append(self.has_recv[var_name][op_desc.src]) + + elif isinstance(op_desc, ConcatOpDesc): + partition_index_list = op_desc.partition_index_list + idx_list = [idx] + for index, tensor in enumerate(tensor_list): + Inserter.concat_partitions_with_op( + partition_tensor_list, tensor, + partition_index_list[index], block, idx_list, + reshard_op.attr('op_role')) + idx = idx_list[0] + + elif isinstance(op_desc, SliceOpDesc): + assert len( + partition_tensor_list) == 1 or not partition_tensor_list + to_slice_tensor = partition_tensor_list[0][0] if len( + partition_tensor_list) == 1 else source_tensor + new_name = unique_name.generate(var_name + "@RESHARD") + target_tensor = Inserter.insert_slice_op( + block, + idx, + to_slice_tensor, + starts=op_desc.starts, + ends=op_desc.ends, + axes=op_desc.axes, + new_var_name=new_name, + op_role=reshard_op.attr('op_role')) + + process_mesh = dist_attr[0] + dims_mapping = dist_attr[1] + + tensor_attr = TensorDistributedAttribute() + tensor_attr.dims_mapping = dims_mapping + tensor_attr.process_mesh = process_mesh + self.dist_context.set_tensor_dist_attr_for_program( + target_tensor, tensor_attr) + + if matched_op.type == "while": + # var_reshard_mapping means the while op input need be changed to + if "var_reshard_mapping" not in Resharder.while_block_info[ + op.attr("sub_block").id].keys(): + Resharder.while_block_info[op.attr( + "sub_block").id]["var_reshard_mapping"] = {} + if var_name not in Resharder.while_block_info[op.attr( + "sub_block").id]["var_reshard_mapping"].keys(): + Resharder.while_block_info[op.attr("sub_block").id][ + "var_reshard_mapping"][var_name] = [] + Resharder.while_block_info[op.attr("sub_block").id][ + "var_reshard_mapping"][var_name].append( + [dist_attr, target_tensor.name]) + + # rename op input name according to new name + for op in block.ops: + # just for while op + while_op_X_append = [] + for name in op.input_arg_names: + op_dist_attr = self.dist_context.get_op_dist_attr_for_program( + op) + if name == var_name and op_dist_attr is not None: + if op.desc.id() == matched_op.desc.id(): + if matched_op.type == "while": + old_name = name + new_name = target_tensor.name + assert old_name != new_name + op_input_dist_attr = op_dist_attr.get_input_dist_attr( + old_name) + op_dist_attr.set_input_dist_attr( + new_name, op_input_dist_attr) + op_dist_attr.set_input_dims_mapping( + new_name, dims_mapping) + if old_name in op_dist_attr._inputs_dist_attrs: + op_dist_attr.del_input_dist_attr( + old_name) + while_op_X_append.append(new_name) + continue + else: + op.desc._rename_input( + name, target_tensor.name) + old_name = name + new_name = target_tensor.name + assert old_name != new_name + op_input_dist_attr = op_dist_attr.get_input_dist_attr( + old_name) + op_dist_attr.set_input_dist_attr( + new_name, op_input_dist_attr) + op_dist_attr.set_input_dims_mapping( + new_name, dims_mapping) + op_dist_attr.del_input_dist_attr(old_name) + continue + + op_process_mesh = op_dist_attr.process_mesh + op_input_dims_mapping = op_dist_attr.get_input_dims_mapping( + var_name) + # NOTE: For op whose process mesh is a union, its input will not be renamed by other op reshard result now which means that it will have more reshard operation. + if op_process_mesh == process_mesh and op_input_dims_mapping == dims_mapping: + op.desc._rename_input(name, target_tensor.name) + old_name = name + new_name = target_tensor.name + assert old_name != new_name + op_input_dist_attr = op_dist_attr.get_input_dist_attr( + old_name) + op_dist_attr.set_input_dist_attr( + new_name, op_input_dist_attr) + op_dist_attr.set_input_dims_mapping( + new_name, dims_mapping) + op_dist_attr.del_input_dist_attr(old_name) + + # for while op, the input X should reset + if while_op_X_append: + proto = OpProtoHolder.instance().get_op_proto(op.type) + op.desc.set_input(proto.inputs[0].name, + op.input("X") + while_op_X_append) + + def _get_subblock_input_attrs(self, op, var_name): + # NOTE: Multi while loop is not supported + assert op.type in _g_subblock_ops + sub_block = self.auto_parallel_main_prog.blocks[op.attr("sub_block").id] + ops = sub_block.ops + input_attrs = [] + + for op in ops: + dist_op = self.dist_context.get_dist_op_for_program(op) + if not dist_op: + continue + dist_attr = dist_op.dist_attr + for name in op.input_arg_names: + if name == var_name: + process_mesh = dist_attr.process_mesh + input_dims_mapping = dist_attr.get_input_dims_mapping( + var_name) + has_exist = False + for input_attr in input_attrs: + if process_mesh == input_attr[ + 0] and input_dims_mapping == input_attr[1]: + has_exist = True + break + if not has_exist: + input_attrs.append([process_mesh, input_dims_mapping]) + return input_attrs + + def _get_common_op_input_attrs(self, op, var_name): + process_meshes = [] + dist_op = self.dist_context.get_dist_op_for_program(op) + dist_attr = dist_op.dist_attr + op_process_mesh = dist_attr.process_mesh + for process_mesh in self.dist_context.process_meshes: + if set(process_mesh.processes) & (set( + op_process_mesh.processes)) and len( + process_mesh.processes) < len( + op_process_mesh.processes): + process_meshes.append(process_mesh) + + # it means that the process mesh is not a union when process meshes is none + if not process_meshes: + process_meshes.append(op_process_mesh) + + input_dims_mapping = dist_attr.get_input_dims_mapping(var_name) + input_attrs = [] + for process_mesh in process_meshes: + input_attrs.append([process_mesh, input_dims_mapping]) + + return input_attrs + + def get_op_input_attrs(self, op, var_name): + op_input_attrs = [] + + if op.type in _g_subblock_ops: + op_input_attrs = self._get_subblock_input_attrs(op, var_name) + else: + op_input_attrs = self._get_common_op_input_attrs(op, var_name) + + assert op_input_attrs + + return op_input_attrs + + def _remove_global_process_mesh(self): + """Remove global process mesh from dist_context.process_meshes""" + processes = set() + process_mesh_count = len(self.dist_context.process_meshes) + if process_mesh_count > 1: + global_process_mesh_idx = None + for process_mesh in self.dist_context.process_meshes: + for process in process_mesh.processes: + processes.add(process) + for idx, process_mesh in enumerate( + self.dist_context.process_meshes): + if len(set(process_mesh.processes)) == len(processes): + global_process_mesh_idx = idx + break + + if global_process_mesh_idx is not None: + is_removed = False + global_mesh = self.dist_context.process_meshes[idx] + for i, mesh in enumerate(self.dist_context.process_meshes): + if i == idx: + continue + if set(mesh.processes) < set(global_mesh.processes): + is_removed = True + + if is_removed: + self.dist_context.process_meshes.pop(idx) + + def _change_subblock_op_input_and_output(self, block_idx, block): + if "var_reshard_mapping" in Resharder.while_block_info[block_idx]: + var_reshard_mapping = Resharder.while_block_info[block_idx][ + "var_reshard_mapping"] + for op in block.ops: + for var_name in op.input_arg_names: + if var_name in var_reshard_mapping: + # in while sub block, the union process mesh is not split before reshard sub block + dist_op = self.dist_context.get_dist_op_for_program(op) + dist_attr = dist_op.dist_attr + target_name = None + for item in var_reshard_mapping[var_name]: + if dist_attr.process_mesh == item[0][ + 0] and dist_attr.get_input_dims_mapping( + var_name) == item[0][1]: + target_name = item[1] + break + if target_name is None: + continue + else: + op.desc._rename_input(var_name, target_name) + dist_op = self.dist_context.get_dist_op_for_program( + op) + op_dist_attr = dist_op.dist_attr + old_name = var_name + new_name = target_name + assert old_name != new_name + op_input_dist_attr = op_dist_attr.get_input_dist_attr( + old_name) + op_dist_attr.set_input_dist_attr( + new_name, op_input_dist_attr) + op_dist_attr.del_input_dist_attr(old_name) + + # the outputs also need to be renamed when the output name is the same with input name in inplace op + for var_name in op.output_arg_names: + # if the tensor has been resharded multiply, it is not supported now. + if var_name in var_reshard_mapping: + if len(var_reshard_mapping[var_name]) > 1: + raise ValueError( + "The scene is not supported that the output is inplaced and the tensor has been resharded multiply when as input." + ) + target_name = var_reshard_mapping[var_name][0][1] + + op.desc._rename_output(var_name, target_name) + dist_op = self.dist_context.get_dist_op_for_program(op) + op_dist_attr = dist_op.dist_attr + old_name = var_name + new_name = target_name + assert old_name != new_name + op_output_dist_attr = op_dist_attr.get_output_dist_attr( + old_name) + op_dist_attr.set_output_dist_attr( + new_name, op_output_dist_attr) + op_dist_attr.del_output_dist_attr(old_name) + + def _reshard_input(self, block): + idx = 0 + while idx < len(block.ops): + pre_op_count = len(block.ops) + op = block.ops[idx] + + if self.is_special_op(op): + idx += 1 + continue + + dist_op = self.dist_context.get_dist_op_for_program(op) + if dist_op is not None: + op_input_dist_attrs = [ + ] # [(op_process_mesh, op_input_dims_mapping), (op_process_mesh, op_input_dims_mapping)] + if op.type in _g_subblock_ops: + if not self.is_condition_replicative(op): + raise ValueError( + "Please check the condition due to the dims mapping is not replicative." + ) + if op.attr( + "sub_block").id not in Resharder.while_block_info: + Resharder.while_block_info[op.attr("sub_block").id] = {} + Resharder.while_block_info[op.attr( + "sub_block").id]["op_id"] = op.desc.id() + + if op.type == "while": + # condition var process mesh is the same with op and dims_mapping is replicative, so it do not need reshard + input_var_names = op.input("X") + elif op.type == "conditional_block": + input_var_names = op.input("Input") + else: + input_var_names = op.input_arg_names + # to avoid while op X order different + input_var_names.sort() + + idx_offset = 0 + for var_name in input_var_names: + # skip lod_tensor_blocking_queue_? name + if "lod_tensor_blocking_queue" in var_name: + continue + var = get_var_with_recursion(var_name, block, + self.auto_parallel_main_prog) + dist_tensor = self.dist_context.get_dist_tensor_for_program( + var) + + # judge whether union tensor dims_mapping all -1 + is_union_process_mesh_tensor = False + if dist_tensor.dist_attr.process_mesh not in self.dist_context.process_meshes and self.dist_context.process_meshes: + is_union_process_mesh_tensor = True + assert dist_tensor.dist_attr.dims_mapping.count( + -1) == len(dist_tensor.dist_attr.dims_mapping) + + op_input_attrs = self.get_op_input_attrs(op, var_name) + for input_attr in op_input_attrs: + input_process_mesh = None + + # deal with union tensor + if is_union_process_mesh_tensor: + # if op process mesh is subset of union tensor process mesh, need no reshard + if set(input_attr[0].processes) <= set( + dist_tensor.dist_attr.process_mesh.processes + ): + continue + + if dist_tensor is not None and self.need_reshard( + dist_tensor, input_attr): + reshard_op_desc = self.find_op_desc_seq( + dist_tensor, input_attr) + self.parse_op_desc(block, reshard_op_desc, var_name, + op, input_attr) + cur_op_count = len(block.ops) + idx_offset = idx_offset + cur_op_count - pre_op_count + pre_op_count = cur_op_count + idx = idx + idx_offset + 1 + else: + idx += 1 + + def _hadnle_recv(self, block, idx, var, op, send_rank, recv_rank): + if self.rank_id == recv_rank: + # if recv bool data, recv then cast + if var.dtype == paddle.bool: + recv_cast_out = block.create_var( + name=unique_name.generate(var.name + "@recv"), + shape=var.shape, + lod_level=var.lod_level, + dtype=paddle.int64, + type=var.type) + Inserter.insert_recv_op(block, idx + 1, + recv_cast_out, send_rank, recv_rank, + op.attr('op_role')) + reset_lod_out = None + if var.lod_level != 0: + set_lod = False + for tmp_block in self.auto_parallel_main_prog.blocks: + for tmp_var_name in tmp_block.vars: + tmp_var = tmp_block.vars[tmp_var_name] + if tmp_var.is_data and tmp_var.lod_level == var.lod_level: + reset_lod_out = block.create_var( + name=unique_name.generate(var.name + + "@RESETLOD"), + shape=recv_cast_out.shape, + type=recv_cast_out.type, + dtype=recv_cast_out.dtype, + lod_level=recv_cast_out.lod_level) + idx += 1 + block._insert_op( + idx, + type="lod_reset", + inputs={ + 'X': recv_cast_out, + 'Y': tmp_var + }, + outputs={'Out': reset_lod_out}, + attrs={'op_role': op.attr("op_role")}) + set_lod = True + break + if set_lod: + break + assert set_lod is True + + # cast int64 to bool + block._insert_op(idx + 2, + type='cast', + inputs={ + 'X': [recv_cast_out] if + reset_lod_out is None else [reset_lod_out] + }, + outputs={'Out': [var]}, + attrs={ + 'in_dtype': recv_cast_out.dtype, + 'out_dtype': var.dtype, + 'op_role': op.attr('op_role') + }) + else: + if var.lod_level != 0: + recv_out = block.create_var( + name=unique_name.generate(var.name + "@recv"), + shape=var.shape, + lod_level=var.lod_level, + dtype=var.int64, + type=var.type) + Inserter.insert_recv_op(block, idx + 1, recv_out, send_rank, + recv_rank, op.attr('op_role')) + set_lod = False + for tmp_block in self.auto_parallel_main_prog.blocks: + for tmp_var_name in tmp_block.vars: + tmp_var = tmp_block.vars[tmp_var_name] + if tmp_var.is_data and tmp_var.lod_level == var.lod_level: + idx += 1 + block._insert_op( + idx, + type="lod_reset", + inputs={ + 'X': recv_out, + 'Y': tmp_var + }, + outputs={'Out': var}, + attrs={'op_role': op.attr("op_role")}) + set_lod = True + break + if set_lod: + break + assert set_lod is True + else: + Inserter.insert_recv_op(block, idx + 1, var, send_rank, + recv_rank, op.attr('op_role')) + + def _handle_send(self, block, idx, var, op, send_rank, recv_rank): + if var.dtype == paddle.bool: + cast_out = Inserter.insert_cast_op(block, idx + 1, var, + op.attr('op_role'), paddle.int64) + Inserter.insert_send_op(block, idx + 2, cast_out, send_rank, + recv_rank, op.attr('op_role')) + else: + Inserter.insert_send_op(block, idx + 1, var, send_rank, recv_rank, + op.attr('op_role')) + + def _reshard_output(self, block): + # insert send and recv op if output process mesh is different from tensor process mesh + idx = 0 + # skip reader and ops whose process mesh is union + skip_ops = [ + "create_py_reader", "create_double_buffer_reader", "read", + "write_to_array", "read_from_array" + ] + global _g_special_ops + skip_ops += _g_special_ops + skip_ops += _g_subblock_ops + while idx < len(block.ops): + pre_op_count = len(block.ops) + op = block.ops[idx] + dist_op = self.dist_context.get_dist_op_for_program(op) + if dist_op is not None and op.type not in skip_ops: + idx_offset = 0 + for var_name in op.output_arg_names: + var = get_var_with_recursion(var_name, block, + self.auto_parallel_main_prog) + dist_tensor = self.dist_context.get_dist_tensor_for_program( + var) + tensor_process_mesh = dist_tensor.dist_attr.process_mesh + output_attr = [ + dist_op.dist_attr.process_mesh, + dist_op.dist_attr.get_output_dims_mapping(var_name) + ] + if dist_tensor is not None and self.need_reshard( + dist_tensor, output_attr, False): + tensor_processes = set( + tensor_process_mesh.processes) - ( + set(tensor_process_mesh.processes) + & set(output_attr[0].processes)) + if tensor_processes: + if len(tensor_processes) != len( + output_attr[0].processes): + if dist_tensor.dist_attr.dims_mapping.count( + -1) != len( + dist_tensor.dist_attr.dims_mapping + ) or output_attr[1].count(-1) != len( + output_attr[1]): + raise ValueError( + "The dims_mapping must be -1") + else: + for index, tensor_process in enumerate( + tensor_processes): + recv_rank = tensor_process + actual_index = index + if index >= len( + output_attr[0].processes): + actual_index = ( + index - + len(output_attr[0].processes) + ) % len(output_attr[0].processes) + item = output_attr[0].processes[ + actual_index] + if recv_rank == item: + continue + if self.rank_id == item: + # if send bool data, cast then send + self._handle_send( + block, idx, var, op, item, + recv_rank) + if self.rank_id == recv_rank: + # if recv bool data, recv then cast + self._hadnle_recv( + block, idx, var, op, item, + recv_rank) + else: + for index, tensor_process in enumerate( + tensor_processes): + recv_rank = tensor_process + item = output_attr[0].processes[index] + if recv_rank == item: + continue + if self.rank_id == item: + # if send bool data, cast then send + self._handle_send( + block, idx, var, op, item, + recv_rank) + if self.rank_id == recv_rank: + # if recv bool data, recv then cast + self._hadnle_recv( + block, idx, var, op, item, + recv_rank) + + cur_op_count = len(block.ops) + idx_offset = idx_offset + cur_op_count - pre_op_count + pre_op_count = cur_op_count + + idx = idx + idx_offset + 1 + else: + idx += 1 + + def reshard(self): + self._remove_global_process_mesh() + for block_idx, block in enumerate(self.auto_parallel_main_prog.blocks): + # change the var_name before resharding sub block + if block_idx in Resharder.while_block_info: + self._change_subblock_op_input_and_output(block_idx, block) + + # reshard input + self._reshard_input(block) + + # reshard output + # NOTE: Only support that insert send and recv op if output process mesh is different from tensor process mesh + self._reshard_output(block) + + # remove no need vars and ops in the main program + Remover.remove_no_need_in_main(self.auto_parallel_main_prog, + self.dist_context, self.rank_id, + self.dist_params_grads) + + # remove no need vars and ops in the startip program + Remover.remove_no_need_in_startup(self.auto_parallel_main_prog, + self.auto_parallel_startup_prog) + + # reset some variable when remove operation ended + Resharder.while_block_info = {} + + def get_cost(self, op, tensor, cluster): + # NOTE: The program should be the serial_program which is not been parted + global _g_special_ops + not_supported_op_type = _g_special_ops + ["while"] + reshard_op_cost = None + if op.type in not_supported_op_type: + return reshard_op_cost + else: + tensor_name = tensor.name + if tensor_name == "lod_tensor_blocking_queue_0": + return reshard_op_cost + else: + dist_tensor = self.dist_context.get_dist_tensor_for_program( + tensor) + # simplified processing: ignore union process mesh and output reshard + dist_op = self.dist_context.get_dist_op_for_program(op) + dims_mapping = dist_op.dist_attr.get_input_dims_mapping( + tensor.name) + process_mesh = dist_op.dist_attr.process_mesh + dist_attr = [process_mesh, dims_mapping] + if dist_tensor is not None and self.need_reshard( + dist_tensor, dist_attr): + if tensor_name not in self._has_resharded: + self._has_resharded[tensor_name] = [dist_op] + else: + for item in self._has_resharded[tensor_name]: + item_dist_attr = item.dist_attr + item_dims_mapping = item_dist_attr.get_input_dims_mapping( + tensor_name) + item_process_mesh = item_dist_attr.process_mesh + if dims_mapping == item_dims_mapping and item_process_mesh == process_mesh: + return reshard_op_cost + self._has_resharded[tensor_name].append(dist_op) + + reshard_op_desc = self.find_op_desc_seq(dist_tensor, + dist_attr, + serial=True) + dtype = dist_tensor.serial_tensor.dtype + reshard_op_cost = self.parse_op_desc_for_cost( + reshard_op_desc, dtype, cluster) + + return reshard_op_cost + + def _concat_partitions_for_cost(self, partition_tensor_list, + partition_index, dtype, rank_id, + local_rank_comp_cost, cluster): + if not partition_tensor_list: + partition_tensor_list.append(partition_index) + else: + i = 0 + has_concat = False + while i < len(partition_tensor_list): + concat_axis, first_order, new_partition = Resharder.compute_concat_info( + partition_tensor_list[i], partition_index) + if concat_axis != -1: + has_concat = True + concat_desc = {} + concat_desc["op"] = "concat" + concat_desc["attrs"] = {"axis": concat_axis} + if first_order == 0: + concat_desc["inputs"] = { + "X": [(dtype, partition_tensor_list[i]), + (dtype, partition_index)] + } + else: + concat_desc["inputs"] = { + "X": [(dtype, partition_index), + (dtype, partition_tensor_list[i])] + } + partition_tensor_list.pop(i) + if rank_id not in local_rank_comp_cost: + local_rank_comp_cost[rank_id] = [] + local_rank_comp_cost[rank_id].append( + ConcatOpCost(op_desc=concat_desc, cluster=cluster)) + self._concat_partitions_for_cost(partition_tensor_list, + new_partition, dtype, + rank_id, + local_rank_comp_cost, + cluster) + break + i += 1 + if not has_concat: + partition_tensor_list.append(partition_index) + + def parse_op_desc_for_cost(self, reshard_op_desc, dtype, cluster): + + def _get_idx(comm_ranks, group_ranks): + res, is_the_same = None, False + idx = 0 + while idx < len(comm_ranks): + if comm_ranks[idx] == set(group_ranks): + is_the_same = True + + for rank in group_ranks: + if rank in comm_ranks[idx]: + res = idx + comm_ranks[idx].add(rank) + if res is None: + idx += 1 + else: + break + return res, is_the_same + + comm_context = CommContext(cluster) + # run communication op before computation op + # TODO: Communication cost is not calculated when the var has been transfered by the same group in the past + comm_costs = [] + comm_ranks = [] + local_rank_comp_cost = {} + for key in reshard_op_desc: + partition_tensor_list = [] + op_desc_list = reshard_op_desc[key] + for op_desc in op_desc_list: + if isinstance(op_desc, SendOpDesc): + group_ranks = [key, op_desc.dst] + shape = op_desc.shape + send_desc = build_comm_desc("send_v2", group_ranks, dtype, + shape) + idx, is_the_same = _get_idx(comm_ranks, group_ranks) + if idx is None: + comm_costs.append([ + (group_ranks, + SendOpCost(op_desc=send_desc, + comm_context=comm_context)) + ]) + comm_ranks.append(set(group_ranks)) + else: + if not is_the_same: + comm_costs[idx].append( + (group_ranks, + SendOpCost(op_desc=send_desc, + comm_context=comm_context))) + elif isinstance(op_desc, AllGatherOpDesc): + # NOTE: fill_const and other unnecessary op is not calculated because those cost is very small + group_ranks = op_desc.group + shape = op_desc.shape + allgather_desc = build_comm_desc("c_allgather", group_ranks, + dtype, shape) + split_inputs_shape = [] + for idx, dim in enumerate(shape): + if idx == 0: + split_inputs_shape.append(dim * len(group_ranks)) + else: + split_inputs_shape.append(dim) + idx, is_the_same = _get_idx(comm_ranks, group_ranks) + if idx is None: + comm_costs.append([ + (group_ranks, + AllgatherOpCost(op_desc=allgather_desc, + comm_context=comm_context)) + ]) + comm_ranks.append(set(group_ranks)) + else: + if not is_the_same: + comm_costs[idx].append( + (group_ranks, + AllgatherOpCost(op_desc=allgather_desc, + comm_context=comm_context))) + # calc the split op cost + if key not in local_rank_comp_cost: + local_rank_comp_cost[key] = [] + split_desc = {} + split_desc["op"] = "split" + split_desc["inputs"] = { + "inputs": [(dtype, split_inputs_shape)] + } + split_desc["attrs"] = {"num": len(group_ranks), "axis": 0} + local_rank_comp_cost[key].append( + SplitOpCost(op_desc=split_desc, cluster=cluster)) + elif isinstance(op_desc, ConcatOpDesc): + partition_index_list = op_desc._partition_index_list + for idx, partion_idex in enumerate(partition_index_list): + self._concat_partitions_for_cost( + partition_tensor_list, partion_idex, dtype, key, + local_rank_comp_cost, cluster) + + elif isinstance(op_desc, SliceOpDesc): + if key not in local_rank_comp_cost: + local_rank_comp_cost[key] = [] + assert len( + partition_tensor_list) == 1 or not partition_tensor_list + to_slice_tensor_shape = [] + if len(partition_tensor_list) == 1: + for item in partition_tensor_list[0]: + to_slice_tensor_shape.append(item[1] - item[0]) + else: + to_slice_tensor_shape = op_desc.shape + slice_desc = {} + slice_desc["op"] = "slice" + infer_flags = list(1 for i in range(len(op_desc.axes))) + slice_desc["attrs"] = { + "axes": op_desc.axes, + "starts": op_desc.starts, + "ends": op_desc.ends, + "infer_flags": infer_flags + } + slice_desc["inputs"] = { + "Input": [(dtype, to_slice_tensor_shape)] + } + local_rank_comp_cost[key].append( + SliceOpCost(op_desc=slice_desc, cluster=cluster)) + + res = (comm_costs, local_rank_comp_cost) + + return res diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/strategy.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..927aa25dbfba7136478cc3c2b40fdcb82f4872b5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/strategy.py @@ -0,0 +1,192 @@ +# Copyright (c) 2022 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 + +import os +import copy +import argparse +from . import constants + + +class BaseConfig(object): + + def __init__(self, category, config_dict=None): + self._category = category + self._config_dict = None + if config_dict is not None: + if isinstance(config_dict, dict): + self._config_dict = config_dict + else: + raise ValueError( + "Expected a dictionary. But received: {}".format( + config_dict)) + # Initialize attributes by the default config + config = constants.get_category_default_config(self._category) + for field, default_value in config.items(): + setattr(self, field, default_value) + + # Overide attributes by the config_dict + if self._config_dict: + self.from_dict(self._config_dict) + + def from_dict(self, config_dict): + config = constants.get_category_default_config(self._category) + for field in config.keys(): + value = config_dict.get(field, constants.NOT_FOUND) + # Use the default value if we cannot found the value + if value != constants.NOT_FOUND: + setattr(self, field, value) + + def to_dict(self): + result_dict = {} + config = constants.get_category_default_config(self._category) + for field in config.keys(): + value = getattr(self, field) + result_dict[field] = value + for field, value in self.__dict__.items(): + if isinstance(value, BaseConfig): + result_dict[field] = value.to_dict() + return result_dict + + def __repr__(self): + result_dict = self.to_dict() + string = "{" + for k, v in result_dict.items(): + string += "\"%s\":\"%s\"," % (k, v) + return string + "}" + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + setattr(result, k, copy.deepcopy(v, memo)) + return result + + +class RecomputeConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.RECOMPUTE + super(RecomputeConfig, self).__init__(category, config_dict) + + +class AMPConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.AMP + super(AMPConfig, self).__init__(category, config_dict) + + +class ShardingConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.SHARDING + super(ShardingConfig, self).__init__(category, config_dict) + + +class GradientMergeConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.GRADIENT_MERGE + super(GradientMergeConfig, self).__init__(category, config_dict) + + +class QATConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.QAT + super(QATConfig, self).__init__(category, config_dict) + + +class TuningConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.TUNING + super(TuningConfig, self).__init__(category, config_dict) + + +class DatasetConfig(BaseConfig): + + def __init__(self, config_dict=None): + category = constants.DATASET + super(DatasetConfig, self).__init__(category, config_dict) + + +class Strategy(BaseConfig): + """ + The `Strategy` object is used to configure the paralleization and optimization beheviors. + + Args: + config (dict|string, optional): If this is None, the default configurations will used. + If this is a dictionary, the recognized key-value of it will be used to override the default + configurations while other default configurations are left unchanged. If this is a string, + it is interpreted as the path to a YAML configuration and will be loaded to override the + corresponding default configurations. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed.fleet import auto + + strategy = auto.Strategy() + sharding = strategy.sharding + self.assertEqual(sharding.enabled, False) + self.assertEqual(sharding.stage, 1) + self.assertEqual(sharding.degree, 8) + sharding.enabled = True + sharding.stage = 2 + sharding.degree = 2 + self.assertEqual(sharding.enabled, True) + self.assertEqual(sharding.stage, 2) + self.assertEqual(sharding.degree, 2) + + """ + + def __init__(self, config=None): + if config is not None: + if isinstance(config, dict): + self._config_dict = copy.deepcopy(config) + # elif os.path.exists(config): + # with open(config, "rb") as yaml_file: + # self._config_dict = yaml.load(yaml_file, Loader=yaml.Loader) + else: + raise ValueError( + "Expected a dictionary. But received: {}".format(config)) + else: + self._config_dict = {} + + category = constants.BASE + super(Strategy, self).__init__(category, self._config_dict) + + config_dict = self._config_dict.get(constants.RECOMPUTE, None) + self.recompute = RecomputeConfig(config_dict) + + config_dict = self._config_dict.get(constants.AMP, None) + self.amp = AMPConfig(config_dict) + + config_dict = self._config_dict.get(constants.SHARDING, None) + self.sharding = ShardingConfig(config_dict) + + config_dict = self._config_dict.get(constants.GRADIENT_MERGE, None) + self.gradient_merge = GradientMergeConfig(config_dict) + + config_dict = self._config_dict.get(constants.QAT, None) + self.qat = QATConfig(config_dict) + + config_dict = self._config_dict.get(constants.TUNING, None) + self.tuning = TuningConfig(config_dict) + + config_dict = self._config_dict.get(constants.DATASET, None) + self.dataset = DatasetConfig(config_dict) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..23559cd2ad0dddca31b255c4d5f18fa91fb7915f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022 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. + +from .profiler import profiler + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/algorithms.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..16b0cea342dfb65a35363b7d2c156caed21785f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/algorithms.py @@ -0,0 +1,158 @@ +# Copyright (c) 2022 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. + +import copy +from abc import ABC, abstractmethod +import logging + +from ..utils import get_logger +from .trial import TrialStatus +from .trial import OptimizationTunerTrial as Trial + + +class AlgorithmBase(ABC): + """ + An Tuning alogrithm is a class to find out an optimal configuration + given the selected tuning optimization pass(es) and the arguments to be tuned. + Different optimization pass(es) will correspond to a different algorithm, + where different search space **pruning rules** will applied. + + In another word, the key "algorithm" for this class is the + search space pruning rules specific for the given optimization scenario. + """ + _REGISTERED_ALGORITHMS = {} + + name = None + + @staticmethod + def _register(algo_name, algo_class): + assert issubclass(algo_class, AlgorithmBase) + AlgorithmBase._REGISTERED_ALGORITHMS[algo_name] = algo_class + + def __init__(self, config): + self._config = config + self._init_spaces() + self._logger = get_logger(logging.INFO) + self._changed_configs = [] + + @property + def changed_configs(self): + return self._changed_configs[:] + + def collect_model_info(self, main_prog, startup_prog): + """ + Collect the model static info (from programs) that could be used to + pruning candidate trials and saving tuning time.For instance, + model info like number of model parameters and activation memory could be + used to prune candidated trial and decide the next trial. + """ + pass + + @abstractmethod + def _init_spaces(self): + pass + + @abstractmethod + def next_trial(self): + pass + + @abstractmethod + def update(self, results): + """ + Update the algorthim with the results of last trial. Using this information is used to + pruning the search space of the future trial. + """ + pass + + def get_config_from_trial(self, trial): + """ + Return a new fleet.DistributedStrategy with the configurations in trial. + """ + assert len(self._changed_configs) > 0 + new_strategy = copy.deepcopy(self._config.dist_strategy) + for name in self._changed_configs: + config = getattr(trial.space, name) + setattr(new_strategy, name, config) + return new_strategy + + +def register_algor(name): + + def impl(cls): + AlgorithmBase._register(name, cls) + cls.name = name + return cls + + return impl + + +def new_algorithm(name, config): + algor_class = AlgorithmBase._REGISTERED_ALGORITHMS.get(name) + assert algor_class is not None, "Algorithm {} is not defined.".format(name) + algor_obj = algor_class(config) + return algor_obj + + +@register_algor("sharding") +class ShardingStageAlgorithm(AlgorithmBase): + + # TODO import trial class & copy strategy + def __init__(self, config): + super().__init__(config) + self._changed_configs = ["sharding"] + + def _init_spaces(self): + self._max_stage = 3 + self._trial_idx = 0 + + stage_range = self._config.sharding.to_dict().get("tuning_range", None) + if stage_range: + assert set(stage_range).issubset( + set([0, 1, 2, 3]) + ), "Sharding Stage should belong into range within 0 - 3 but got {}.".format( + stage_range) + stage_range.sort(reverse=True) + else: + stage_range = list(range(self._max_stage + 1)).sort(reverse=True) + + self._stage_range = stage_range[:] + self._total_num_trial = len(self._stage_range) + + def next_trial(self): + + if self._trial_idx < self._total_num_trial: + + stage = self._stage_range[self._trial_idx] + + new_strategy = copy.deepcopy(self._config.dist_strategy) + sharding = new_strategy.sharding + sharding.stage = stage + + name = "trial-sharding-stage{}".format(stage) + trial = Trial(new_strategy, name, self.changed_configs) + + return trial + else: + return Trial(None, None, None, status=TrialStatus.STOPPED) + + def update(self, results): + + et = results.get("ErrorType", None) + if et and et == "ResourceExhaustedError": + self._trial_idx = self._total_num_trial + self._logger.info( + "Last trial is failed with OOM, all remaining trials are pruned to save time !" + ) + else: + self._trial_idx += 1 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/optimization_tuner.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/optimization_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3c53ef30b43e33e2bbfcc7d503ecab9453d48b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/optimization_tuner.py @@ -0,0 +1,565 @@ +# Copyright (c) 2022 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. + +# import yaml +import os +import sys +import copy +import shlex +import pathlib +import time +import shutil +import pickle +import json +import logging +import subprocess +import traceback + +import paddle +from paddle.fluid import program_guard +from paddle.fluid.backward import append_backward +from paddle.distributed.passes import new_pass, PassContext + +from paddle.distributed.auto_parallel.dist_context import DistributedContext, get_default_distributed_context +from paddle.distributed.auto_parallel.completion import Completer +from paddle.distributed.auto_parallel.reshard import Resharder +from paddle.distributed.auto_parallel.partitioner import Partitioner +from paddle.distributed.auto_parallel.process_group import clear_all_process_groups, get_all_process_groups +from paddle.distributed.auto_parallel.utils import debug_program +from paddle.distributed.auto_parallel.utils import make_data_unshard, set_grad_var_shape + +from ..utils import get_logger +from .config import TuningConfig +from .algorithms import new_algorithm +from .trial import TrialStatus + + +def _get_new_params_grads(target_program, ref_program, ref_params_grads): + ref_block = ref_program.global_block() + target_block = target_program.global_block() + target_params_grads = [] + + for p, g in ref_params_grads: + # NOTE grad var might not be generated + assert ref_block.has_var(p.name) + assert target_block.has_var(p.name) + new_p = target_block.var(p.name) + if g: + new_g = target_block.var(g.name) + else: + new_g = None + + target_params_grads.append((new_p, new_g)) + + return target_params_grads + + +def _get_new_loss(target_program, ref_program, loss): + ref_block = ref_program.global_block() + target_block = target_program.global_block() + assert ref_block.has_var(loss.name) + + return target_block.var(loss.name) + + +def parse_process_groups(): + group_map = {} + all_process_groups = get_all_process_groups() + for process_group in all_process_groups: + group_map[process_group.id] = process_group.ranks + return group_map + + +def get_metric(results): + assert isinstance( + results, + dict), "results should be type of dictionary, but got {}.".format( + type(results)) + if 'Throughtput' in results and isinstance(results['Throughtput'], float): + return float(results['Throughtput']) + else: + return -1.0 + + +def parse_results(results): + if results['Throughtput'] > 0: + return "Throughtput: {} step / s.".format(results['Throughtput']) + et = results.get("ErrorType", None) + if et == "ResourceExhaustedError": + return "Fail with OOM" + else: + return "Fail with UNKWON ERROR" + + +# TODO only dependent on dist context +# all env need to be start a new pass are member of dist context +def _copy_context(ref_dist_context): + + clear_all_process_groups() + + new_dist_context = DistributedContext() + new_dist_context._serial_main_program = ref_dist_context.serial_main_program.clone( + for_test=False) + new_dist_context._serial_startup_program = ref_dist_context.serial_startup_program.clone( + for_test=False) + + # mapping variable into new dist context + if getattr(ref_dist_context, '_params_grads', None): + new_dist_context._params_grads = _get_new_params_grads( + new_dist_context.serial_main_program, + ref_dist_context.serial_main_program, + ref_dist_context._params_grads) + new_dist_context._serial_loss = _get_new_loss( + new_dist_context.serial_main_program, + ref_dist_context.serial_main_program, ref_dist_context.serial_loss) + + for key, var_list in ref_dist_context._serial_feed_vars.items(): + new_var_list = [] + for var in var_list: + block_idx = var.block.idx + var_name = var.name + var = new_dist_context._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_var_list.append(var) + new_dist_context._serial_feed_vars[key] = new_var_list + + for key, var_list in ref_dist_context._serial_fetch_vars.items(): + new_var_list = [] + # metrics is a list of list + if key == "metrics": + for inner_var_list in var_list: + new_inner_var_list = [] + for var in inner_var_list: + block_idx = var.block.idx + var_name = var.name + var = new_dist_context._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_inner_var_list.append(var) + new_var_list.append(new_inner_var_list) + else: + for var in var_list: + block_idx = var.block.idx + var_name = var.name + var = new_dist_context._serial_main_program.blocks[ + block_idx]._var_recursive(var_name) + new_var_list.append(var) + new_dist_context._serial_fetch_vars[key] = new_var_list + + # copy information in forward and backward + new_dist_context._serial_optimizer = copy.deepcopy( + ref_dist_context.serial_optimizer) + new_dist_context._dist_tensors_for_program = copy.deepcopy( + ref_dist_context._dist_tensors_for_program) + new_dist_context._dist_ops_for_program = copy.deepcopy( + ref_dist_context._dist_ops_for_program) + for pm in ref_dist_context.process_meshes: + new_dist_context.add_process_mesh(pm) + new_dist_context._dist_op_context = copy.deepcopy( + ref_dist_context._dist_op_context) + new_dist_context._block_state = copy.deepcopy(ref_dist_context.block_state) + + return new_dist_context + + +class OptimizationTuner: + """ + OptimizationTuner is used to manage the tuning procedure of hyper-parameters (configs) + of Optimization Pass in AutoParallel. + """ + + def __init__( + self, + user_configs, + dist_context, + dataset, + inputs_spec, + labels_spec, + batch_size, + rank, + ): + + self._config = TuningConfig(user_configs, dist_context._strategy) + # should not modify dist context from calling function + self._baseline_dist_context = _copy_context(dist_context) + self._baseline_completer = Completer(self._baseline_dist_context) + + self._rank = rank + self._inputs_spec = inputs_spec + self._labels_spec = labels_spec + self._dataset = dataset + self._batch_size = batch_size + + self._finished_trials = [] + self._best_metric = None + self._best_iter = float("-inf") + + self._logger = get_logger(logging.INFO) + + self._build_programs_without_optimization() + self._select_tuning_algorithm() + + @property + def project_dir(self): + dirname = self._config.project_dir + if not os.path.exists(dirname): + if self.rank == 0: + pathlib.Path(dirname).mkdir(parents=True, exist_ok=True) + return dirname + + @property + def rank(self): + return self._rank + + @property + def device_id(self): + return paddle.distributed.ParallelEnv().device_id + + # TODO Generate compelet program with all parts like forward, backward, update + # as well as parallelism transformation. + def _build_programs_without_optimization(self): + + serial_main_program = self._baseline_dist_context.serial_main_program + serial_startup_program = self._baseline_dist_context.serial_startup_program + serial_loss = self._baseline_dist_context.serial_loss + + with program_guard(serial_main_program, serial_startup_program): + params_grads = append_backward( + serial_loss, + distop_context=self._baseline_dist_context.dist_op_context) + + self._baseline_completer.complete_backward_annotation( + serial_main_program) + self._baseline_dist_context.block_state.parse_backward_blocks( + serial_main_program) + self._baseline_dist_context._params_grads = params_grads + + if self._config.verbose: + baseline_dir = os.path.join(self.project_dir, "baseline") + if not os.path.exists(baseline_dir): + pathlib.Path(baseline_dir).mkdir(parents=True, exist_ok=True) + debug_program(self._baseline_dist_context._serial_main_program, + baseline_dir, "main") + debug_program(self._baseline_dist_context._serial_startup_program, + baseline_dir, "startup") + + def _select_tuning_algorithm(self): + + selected_passes_set = self._config.tuning_passes_name + algorithm_name = "_".join(sorted(selected_passes_set)) + self._algorithm = new_algorithm(algorithm_name, self._config) + + def _apply_optimization(self, trial): + new_strategy = trial.space + dist_context = _copy_context(self._baseline_dist_context) + pass_context = PassContext() + completer = Completer(dist_context) + + main_program = dist_context.serial_main_program + startup_program = dist_context.serial_startup_program + + # applying optimization pass + if new_strategy.amp.enable: + config = copy.deepcopy(new_strategy.amp.to_dict()) + config["dist_context"] = dist_context + config["params_grads"] = dist_context._params_grads + + # TODO AMP Pass should not use loss var + config["loss"] = dist_context.serial_loss + config["input_data"] = self._baseline_dist_context.serial_feed_vars["inputs"] \ + + self._baseline_dist_context.serial_feed_vars["labels"] + if config["use_pure_fp16"]: + config["base_opt"] = dist_context.serial_optimizer + auto_parallel_fp16_pass = new_pass("auto_parallel_fp16", config) + auto_parallel_fp16_pass.apply([main_program], [startup_program], + pass_context) + else: + auto_parallel_amp_pass = new_pass("auto_parallel_amp", config) + auto_parallel_amp_pass.apply([main_program], [startup_program], + pass_context) + + if new_strategy.recompute.enable: + config = copy.deepcopy(new_strategy.recompute.to_dict()) + config["dist_context"] = dist_context + config["no_grad_set"] = None + config["loss"] = dist_context.serial_loss + auto_parallel_recompute_pass = new_pass("auto_parallel_recompute", + config) + auto_parallel_recompute_pass.apply([main_program], + [startup_program], pass_context) + + # Do logical partition + partitioner = Partitioner(dist_context, self.rank) + dist_main_prog, dist_startup_prog, dist_params_grads = partitioner.partition( + main_program, startup_program, dist_context._params_grads) + + # Generate optimizer + # FIXME should be remove from apply pass after pass support optimizers + with program_guard(dist_main_prog, dist_startup_prog): + optimizer_ops = dist_context.serial_optimizer.apply_gradients( + dist_params_grads) + completer.complete_update_annotation(dist_main_prog) + + # Do reshard process + set_grad_var_shape(dist_main_prog, dist_context) + resharder = Resharder(dist_main_prog, dist_startup_prog, self.rank, + dist_context, dist_params_grads) + resharder.reshard() + + if new_strategy.sharding.enable: + config = copy.deepcopy(new_strategy.sharding.to_dict()) + config["dist_context"] = dist_context + config["params_grads"] = dist_params_grads + config["global_rank"] = self.rank + auto_parallel_sharding_pass = new_pass("auto_parallel_sharding", + config) + auto_parallel_sharding_pass.apply([dist_main_prog], + [dist_startup_prog], pass_context) + + if new_strategy.gradient_merge.enable: + config = copy.deepcopy(new_strategy.gradient_merge.to_dict()) + config["dist_context"] = dist_context + config["params_grads"] = dist_params_grads + auto_parallel_gradient_merge_pass = new_pass( + "auto_parallel_gradient_merge_pass", config) + auto_parallel_gradient_merge_pass.apply([dist_main_prog], + [dist_startup_prog], + pass_context) + trial.main_program, trial.startup_program = dist_main_prog, dist_startup_prog + return trial + + def _get_profile_context(self, trial, result_path): + + profile_ctx = {} + + profile_ctx['distributed_env'] = copy.deepcopy( + paddle.distributed.ParallelEnv()) + profile_ctx['group_map'] = parse_process_groups() + profile_ctx[ + "loss_var_name"] = self._baseline_dist_context.serial_loss.name + profile_ctx[ + "main_program_decs"] = trial.main_program.desc.serialize_to_string( + ) + profile_ctx[ + "startup_program_decs"] = trial.startup_program.desc.serialize_to_string( + ) + self._dataset.batch_size = self._batch_size + self._dataset.input_names = self._get_input_names() + + profile_ctx["dataset"] = self._dataset + profile_ctx["result_filename"] = result_path + + return profile_ctx + + def _get_input_names(self): + input_names = [] + for input_spec in self._inputs_spec[:] + self._labels_spec[:]: + input_names.append(input_spec.name) + return input_names + + def _launch_profile(self, ctx_path, trial_dir): + + if os.environ.get("WITH_COVERAGE", "OFF") == "ON": + coverage_args = ["-m", "coverage", "run", "--branch", "-p"] + else: + coverage_args = [] + + profile_args = " ".join([ + "--rank", + str(self.rank), + "--device_id", + str(self.device_id), + "--ctx_filename", + ctx_path, + "--profile_start_step", + str(self._config.profile_start_step), + "--profile_end_step", + str(self._config.profile_end_step), + ]) + cmd_args = "-m paddle.distributed.auto_parallel.tuner.profiler" + " " + profile_args + cmd = [sys.executable, "-u"] + coverage_args + shlex.split(cmd_args) + + parent_env = copy.copy(os.environ.copy()) + # env flags need for profile + new_env = { + "FLAGS_USE_STANDALONE_EXECUTOR": "False", + } + new_env.update(parent_env) + + # TODO if any rank hang or fail, kill all processes + self._logger.debug("Executing cmd:\n{} .".format(" ".join(cmd))) + # new_process = subprocess.Popen(cmd, env=new_env) + with open(os.path.join(trial_dir, "stdout.log" + str(self.rank)), + "wb") as out, open( + os.path.join(trial_dir, "stderr.log" + str(self.rank)), + "wb") as err: + result = subprocess.Popen(cmd, stdout=out, stderr=err, env=new_env) + result.wait() + out.flush() + err.flush() + os.fsync(out) + os.fsync(err) + + def _profile_trial(self, trial): + # Making working directory + trial_dir = self._get_trial_dir(trial) + if not os.path.exists(trial_dir): + if self.rank == 0: + pathlib.Path(trial_dir).mkdir(parents=True, exist_ok=True) + else: + while not os.path.exists(trial_dir): + pass + ctx_filename = "profile_ctx." + str(self.rank) + ctx_path = os.path.join(trial_dir, ctx_filename) + result_path = os.path.join(trial_dir, "result.json") + + # Prepare Profile Context + profile_ctx = self._get_profile_context(trial, result_path) + with open(ctx_path, 'wb') as f: + pickle.dump(profile_ctx, f, protocol=4) + + if self._config.verbose: + debug_program(trial.main_program, trial_dir, "main_program") + debug_program(trial.startup_program, trial_dir, "startup_program") + + # Run + self._launch_profile(ctx_path, trial_dir) + + # Load results + try: + with open(result_path, 'r') as fp: + results = json.load(fp) + return results + except FileNotFoundError: + Error_results = {"Throughtput": -1, "ErrorType": 'FatalError'} + return Error_results + + def _evaluate_trial(self, trial): + + self._logger.info("Trial {} evaluation start.".format(trial.name)) + self._apply_optimization(trial) + + if self._config.mode == "PROFILE": + results = self._profile_trial(trial) + + elif self._config.mode == "COSTMODEL": + raise NotImplementedError( + "COSTMODEL mode for optimization tuning is not supported yet!") + else: + raise NotImplementedError("invalid evaluation mode: {}".format( + self._config.mode)) + + self._logger.info("Trial {} evaluation finish with {}.".format( + trial.name, parse_results(results))) + return results + + def _update(self, i, trial, results): + self._finished_trials.append(trial) + + cur_mertic = get_metric(results) + if self._best_metric == None or cur_mertic > self._best_metric: + self._best_metric = cur_mertic + self._best_iter = i + + def _get_trial_dir(self, trial): + return os.path.join(self.project_dir, trial.name) + + def get_best_config(self): + """ + Return the best optimization configuration found in the tuning. + + Returns: + A object of fleet.DistributedStrategy with best configuration. + """ + assert self._best_iter >= 0, "The best configuration is not found yet !" + best_trial = self._finished_trials[self._best_iter] + return self._algorithm.get_config_from_trial(best_trial) + + def summary(self): + """ + Display tuning result summary. + """ + # TODO summary with the trial_name with metric_of_trial + best_trial = self._finished_trials[self._best_iter] + summary_ = """ +Tuning Result Summary +Run total {} trials with {} min. +The best trial is: [{}], whose configuration is following: + """.format(len(self._finished_trials), + (time.time() - self._tuning_start_time) / 60, + best_trial.name) + summary_ += "\n" + best_trial.summary() + "\n"\ + + self._logger.info(summary_) + with open(os.path.join(self.project_dir, "summary.txt"), "w+") as fw: + for line in summary_.split("\n"): + fw.write(line + "\n") + + # full_strategy = self.get_best_config() + # path = os.path.join(self.project_dir, "tuned_dist_strategy.yaml") + # with open(path, 'w') as outfile: + # yaml.dump(full_strategy, outfile, default_flow_style=False) + + def clear(self): + """ + Clear the temporary file generated in tuning procedure. + """ + # TODO clear up zombie process created by tuning + if not self._config.verbose: + for trial in self._finished_trials: + trial_dir = self._get_trial_dir(trial) + shutil.rmtree(trial_dir, ignore_errors=True) + + def tune(self): + """ + Performs the search for best hyperparameter configuations + for the selected optimization pass(es). + """ + + # step1: collect model info which might be used for + # pruning the search space of the algorithm + self._tuning_start_time = time.time() + self._algorithm.collect_model_info( + self._baseline_dist_context.serial_main_program, + self._baseline_dist_context.serial_startup_program) + + # main search loop + i = 0 + while i < self._config.max_num_trial: + # step2: create a new trial + trial = self._algorithm.next_trial() + + if trial.status == TrialStatus.STOPPED: + break + + # step3: evaluate the trial + results = self._evaluate_trial(trial) + + # step4: update the algorithm with last result, + # which could be used by algorithm to pruning the + # remaining search space. + self._algorithm.update(results) + self._update(i, trial, results) + + # early stop + i += 1 + if self._config.early_stop and self._config.early_stop <= i - self._best_iter: + self._logger.info( + "Early stop the Tuning since there is no better trial found within [{}] trials" + .format(self._config.early_stop)) + break + + # step5: summary the best config and return + self.summary() + + self.clear() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/parallel_tuner.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/parallel_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..24ee382f7f75aa0f3e7c7e87fbade0fa7a958167 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/parallel_tuner.py @@ -0,0 +1,968 @@ +# Copyright (c) 2022 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. + +import time +import math +import copy +import hashlib +import itertools +from collections import defaultdict +import numpy as np +from ..process_mesh import ProcessMesh +from ..completion import Completer +from ..parallelizer_v2 import Parallelizer +from ..dist_context import _node_id +from ..dist_op import DistributedOperator +from ..operators.common import find_compatible_distributed_operator_impls +from .trial import Trial, TrialStatus +from .tunable_space import TunableSpace +from .tunable_variable import Boolean, IntRange +from ..cost import CostEstimator +from .tunable_variable import Boolean, IntRange + + +class ParallelTuner: + + def __init__(self, + dist_context, + mode="train", + max_trials=25, + tuner_id=None, + seed=None, + logger=None, + loop_count=10): + self._loop_count = loop_count + self._estimator = None + self._dist_context = dist_context + assert self._dist_context._is_initialized + self._mode = mode + self._cluster = self._dist_context.cluster + self._num_machines = self._cluster.get_num_machines() + self._num_devices_per_machine = self._cluster.get_num_devices_per_machine( + ) + self._space = TunableSpace() + self._objective = "time" + self._direction = "min" + self._max_trials = max_trials + self._tuner_id = tuner_id + self._seed = seed if seed is not None else 9999 + + print("seed", + self._seed, + "mode", + self._mode, + "num_machies", + self._num_machines, + "num_devices_per_machine", + self._num_devices_per_machine, + flush=True) + self._seed_state = self._seed + self._logger = logger + self._max_collisions = 3 + self._tried_values = set() + self._num_trials = 0 + self._rng = np.random.default_rng(self._seed) + + # Search the op types in the include_op_types, + # and will search all op types if it is empty. + # Exclude the op types in the exclude_op_types + # from the search list. + self._exclude_op_types = [] + self._include_op_types = [] + # The final dist ops will be searched after considering + # the include_op_types and exclude_op_types. + self._concerned_dist_ops = {} + + self._op_id_to_dist_attr_candidates = defaultdict(list) + self._cached_dims_mapping_candidates = {} + self._cached_candidates_info = defaultdict(list) + + self._special_ops = [ + "create_py_reader", "create_double_buffer_reader", "read", "while", + "read_from_array", "write_to_array" + ] + + # Each parallel strategy has two elements. The First one is for distributed tensors, + # the second element is for distributed tensors, the third element is for process meshes. + self._init_parallel_strategy = [None, None, None] + self._best_parallel_strategy = [None, None, None] + + self._completer = Completer(self._dist_context) + + self._parallelizer = Parallelizer(self._mode, self._completer, + self._dist_context) + + def _generate_combination(self, + elements, + target, + idx, + partial_candidate, + candidates, + num_candidates=None): + if target == 0: + candidates.append(copy.deepcopy(partial_candidate)) + return + + if target < 0 or idx == len(elements) \ + or len(candidates) > num_candidates: + return + + # Use + partial_candidate.append(elements[idx]) + self._generate_combination(elements, target - elements[idx], idx, + partial_candidate, candidates, + num_candidates) + # Not use + partial_candidate.pop() + self._generate_combination(elements, target, idx + 1, partial_candidate, + candidates, num_candidates) + + def _permute_combination(self, + combination, + target, + check, + partial_candidate, + candidates, + num_candidates=None, + skip_prob=None): + if num_candidates is not None \ + and len(candidates) == num_candidates: + return + + if len(partial_candidate) == len(combination): + candidates.append(partial_candidate) + return + + for i in range(len(combination)): + if check[i] == 1: + continue + if self._rng.choice([True, False], p=[skip_prob, 1 - skip_prob]): + continue + if i > 0 and combination[i] == combination[i - 1] \ + and check[i -1] == 0: + continue + check[i] = 1 + self._permute_combination(combination, target, check, + partial_candidate + [combination[i]], + candidates, num_candidates, skip_prob) + check[i] = 0 + + def _partition_number(self, target): + log2_target = int(math.log2(target)) + elements = [pow(2, i) for i in range(log2_target)] + if pow(2, log2_target) == target: + elements.append(target) + seed_candidates = [] + num_seed_candidates = 1000 + partial_results = [] + self._generate_combination(elements, target, 0, partial_results, + seed_candidates, num_seed_candidates) + + candidates = [] + for seed_candidate in seed_candidates: + cur_candidates = [] + num_cur_candidates = 16 + seed_candidate.sort() + check = [0 for i in range(len(seed_candidate))] + if target <= 8: + skip_prob = 0.0 + else: + skip_prob = (len(seed_candidate) / target) + self._permute_combination(seed_candidate, target, check, [], + cur_candidates, num_cur_candidates, + skip_prob) + candidates.extend(cur_candidates) + return candidates + + def _partition_devices(self, num_machines, num_devices_per_machine): + inter_node_partitions = self._partition_number(num_machines) + intra_node_partitions = self._partition_number(num_devices_per_machine) + return inter_node_partitions, intra_node_partitions + + def _generate_process_mesh_list(self, inter_node_partition, + intra_node_partition): + process_mesh_list = [] + start_row = 0 + start_col = 0 + for m in inter_node_partition: + start_col = 0 + for n in intra_node_partition: + process_mesh = [] + for p in range(m): + start = (start_row + + p) * self._num_devices_per_machine + start_col + tmp = [] + for q in range(n): + tmp.append(start + q) + process_mesh.append(tmp) + process_mesh_list.append(copy.deepcopy(process_mesh)) + start_col += n + start_row += m + return process_mesh_list + + def _generate_dims_mapping_candidates_helper(self, dims_mapping, dims_list, + start, visited, candidates): + if start == len(dims_mapping) or all(visited): + candidates.append(copy.deepcopy(dims_mapping)) + return + + for idx, dim in enumerate(dims_list): + if visited[idx] == False: + dims_mapping[start] = dim + visited[idx] = True + self._generate_dims_mapping_candidates_helper( + dims_mapping, dims_list, start + 1, visited, candidates) + visited[idx] = False + dims_mapping[start] = -1 + self._generate_dims_mapping_candidates_helper(dims_mapping, dims_list, + start + 1, visited, + candidates) + + def _generate_dims_mapping_candidates(self, dims_mapping_len, + process_mesh_len): + assert dims_mapping_len >= 1 and process_mesh_len >= 1 + key = (dims_mapping_len, process_mesh_len) + if key in self._cached_dims_mapping_candidates: + return self._cached_dims_mapping_candidates[key] + candidates = [] + dims_mapping = [-1 for i in range(dims_mapping_len)] + dims_list = [i for i in range(process_mesh_len)] + visited = [False for i in range(process_mesh_len)] + self._generate_dims_mapping_candidates_helper(dims_mapping, dims_list, + 0, visited, candidates) + self._cached_dims_mapping_candidates[key] = candidates + return candidates + + def _generate_dist_attr_candidates(self, op_id, dist_op): + # For now, only allow the process meshes have two dimensions + process_mesh_len = 2 + serial_op = dist_op.serial_op + op_dist_attr = dist_op.dist_attr + if serial_op.type in self._special_ops: + return [copy.deepcopy(op_dist_attr)] + key = [] + key.append(serial_op.type) + for input_name in serial_op.input_names: + key.append(input_name) + for input_arg_name in serial_op.input(input_name): + key.append( + len(op_dist_attr.get_input_dims_mapping(input_arg_name))) + for output_name in serial_op.output_names: + key.append(output_name) + for output_arg_name in serial_op.output(output_name): + key.append( + len(op_dist_attr.get_output_dims_mapping(output_arg_name))) + key = tuple(key) + + if key in self._cached_candidates_info: + cached_dist_attr_candidates = [] + cached_input_arg_names = self._cached_candidates_info[key][0] + cached_output_arg_names = self._cached_candidates_info[key][1] + for cached_dist_attr in self._cached_candidates_info[key][2]: + new_op_dist_attr = copy.deepcopy(dist_op.dist_attr) + i = 0 + for input_name in serial_op.input_names: + for input_arg_name in serial_op.input(input_name): + cached_dims_mapping = cached_dist_attr.get_input_dims_mapping( + cached_input_arg_names[i]) + new_op_dist_attr.set_input_dims_mapping( + input_arg_name, cached_dims_mapping) + i += 1 + i = 0 + for output_name in serial_op.output_names: + for output_arg_name in serial_op.output(output_name): + cached_dims_mapping = cached_dist_attr.get_output_dims_mapping( + cached_output_arg_names[i]) + new_op_dist_attr.set_output_dims_mapping( + output_arg_name, cached_dims_mapping) + i += 1 + cached_dist_attr_candidates.append(new_op_dist_attr) + return cached_dist_attr_candidates + + # cached_candidates_info = [] + input_arg_names = [] + for input_name in serial_op.input_names: + for input_arg_name in serial_op.input(input_name): + input_arg_names.append(input_arg_name) + self._cached_candidates_info[key].append(input_arg_names) + # cached_candidates_info.append(input_arg_names) + output_arg_names = [] + for output_name in serial_op.output_names: + for output_arg_name in serial_op.output(output_name): + output_arg_names.append(output_arg_name) + self._cached_candidates_info[key].append(output_arg_names) + # cached_candidates_info.append(output_arg_names) + + new_op_dist_attr = copy.deepcopy(dist_op.dist_attr) + # Find valid dims_mapping candidates for inputs + input_names = [] + dims_mapping_generated = [] + inputs_dist_attrs = op_dist_attr.inputs_dist_attrs + for tensor_name, tensor_dist_attr in inputs_dist_attrs.items(): + original_dims_mapping = tensor_dist_attr.dims_mapping + dims_mapping_len = len(original_dims_mapping) + input_names.append(tensor_name) + if dims_mapping_len < 1: + dims_mapping_generated.append( + [copy.deepcopy(original_dims_mapping)]) + else: + dims_mapping_generated.append( + self._generate_dims_mapping_candidates( + dims_mapping_len, process_mesh_len)) + input_dims_mapping_candidates = [] + for dims_mapping_list in itertools.product(*dims_mapping_generated): + dims_mapping_list = list(dims_mapping_list) + assert len(dims_mapping_list) == len(input_names) + for i, dims_mapping in enumerate(dims_mapping_list): + new_op_dist_attr.set_input_dims_mapping(input_names[i], + dims_mapping) + new_dist_op = DistributedOperator(dist_op.serial_op, + new_op_dist_attr) + dist_op_impls = find_compatible_distributed_operator_impls( + new_dist_op, fwd=True) + if dist_op_impls is not None: + input_dims_mapping_candidates.append(dims_mapping_list) + + # Find valid dims_mapping candidates for outputs + output_names = [] + dims_mapping_generated = [] + outputs_dist_attrs = op_dist_attr.outputs_dist_attrs + for tensor_name, tensor_dist_attr in outputs_dist_attrs.items(): + original_dims_mapping = tensor_dist_attr.dims_mapping + dims_mapping_len = len(original_dims_mapping) + output_names.append(tensor_name) + if dims_mapping_len < 1: + dims_mapping_generated.append( + [copy.deepcopy(original_dims_mapping)]) + else: + dims_mapping_generated.append( + self._generate_dims_mapping_candidates( + dims_mapping_len, process_mesh_len)) + output_dims_mapping_candidates = [] + for dims_mapping_list in itertools.product(*dims_mapping_generated): + dims_mapping_list = list(dims_mapping_list) + assert len(dims_mapping_list) == len(output_names) + for i, dims_mapping in enumerate(dims_mapping_list): + new_op_dist_attr.set_output_dims_mapping( + output_names[i], dims_mapping) + new_dist_op = DistributedOperator(dist_op.serial_op, + new_op_dist_attr) + dist_op_impls = find_compatible_distributed_operator_impls( + new_dist_op, fwd=False) + if dist_op_impls is not None: + output_dims_mapping_candidates.append(dims_mapping_list) + + if not input_dims_mapping_candidates and output_dims_mapping_candidates: + inout_dims_mapping_generated = [[[[-2]]], + output_dims_mapping_candidates] + elif input_dims_mapping_candidates and not output_dims_mapping_candidates: + inout_dims_mapping_generated = [ + input_dims_mapping_candidates, [[[-2]]] + ] + elif not input_dims_mapping_candidates and not output_dims_mapping_candidates: + inout_dims_mapping_generated = [[[[-2]]], [[[-2]]]] + else: + inout_dims_mapping_generated = [ + input_dims_mapping_candidates, output_dims_mapping_candidates + ] + # Find valid dims_mapping generated for both inputs and outputs + cached_dist_attr_candidates = [] + for inout_dims_mapping_list in itertools.product( + *inout_dims_mapping_generated): + assert len(inout_dims_mapping_list) == 2 + if input_dims_mapping_candidates: + assert len(inout_dims_mapping_list[0]) == len(input_names) + if output_dims_mapping_candidates: + assert len(inout_dims_mapping_list[1]) == len(output_names) + # set the dims_mappings for inputs + for i, dims_mapping in enumerate(inout_dims_mapping_list[0]): + if dims_mapping != [-2]: + new_op_dist_attr.set_input_dims_mapping( + input_names[i], dims_mapping) + # set the dims_mappings for outputs + for i, dims_mapping in enumerate(inout_dims_mapping_list[1]): + if dims_mapping != [-2]: + new_op_dist_attr.set_output_dims_mapping( + output_names[i], dims_mapping) + new_dist_op = DistributedOperator(dist_op.serial_op, + new_op_dist_attr) + dist_op_impls = find_compatible_distributed_operator_impls( + new_dist_op, partial=False) + if dist_op_impls is None: + continue + for dist_op_impl in dist_op_impls: + new_op_dist_attr.impl_type = dist_op_impl.type + new_op_dist_attr.impl_idx = dist_op_impl.idx + cached_dist_attr_candidates.append( + copy.deepcopy(new_op_dist_attr)) + self._cached_candidates_info[key].append(cached_dist_attr_candidates) + return self._cached_candidates_info[key][2] + + def construct_space(self): + inter_node_partitions, intra_node_partitions = self._partition_devices( + self._num_machines, self._num_devices_per_machine) + self._space.choice("inter_node_partitions", + inter_node_partitions, + default=inter_node_partitions[0]) + self._space.choice("intra_node_partitions", + intra_node_partitions, + default=intra_node_partitions[0]) + + dist_ops = self._dist_context._dist_ops_for_program + for op_id, dist_op in dist_ops.items(): + op_type = dist_op.serial_op.type + if self._include_op_types: + if op_type in self._include_op_types: + self._concerned_dist_ops[op_id] = dist_op + else: + self._concerned_dist_ops[op_id] = dist_op + + for op_id, dist_op in self._concerned_dist_ops.items(): + op_type = dist_op.serial_op.type + if op_type in self._exclude_op_types: + del self._concerned_dist_ops[op_id] + + print("Number of the concered dist ops", + len(self._concerned_dist_ops), + flush=True) + search_space = 1 + for op_id, dist_op in self._concerned_dist_ops.items(): + op_dist_attr_candidates = self._generate_dist_attr_candidates( + op_id, dist_op) + search_space *= len(op_dist_attr_candidates) + self._space.choice(str(op_id), + op_dist_attr_candidates, + default=op_dist_attr_candidates[0]) + + def _compute_values_hash(self, values): + keys = sorted(values.keys()) + s = "".join(str(k) + "=" + str(values[k]) for k in keys) + return hashlib.sha256(s.encode("utf-8")).hexdigest()[:32] + + def _random_values(self): + space = TunableSpace() + collisions = 0 + while True: + for v in self._space.variables.values(): + space._register(v) + space.values[v.name] = v.random(self._seed_state) + self._seed_state += 1 + values = space.values + values_hash = self._compute_values_hash(values) + if values_hash in self._tried_values: + collisions += 1 + if collisions > self._max_collisions: + return None + continue + self._tried_values.add(values_hash) + break + return values + + def _populate_space(self): + values = self._random_values() + if values is None: + return {"status": TrialStatus.STOPPED, "values": None} + return {"status": TrialStatus.RUNNING, "values": values} + + def _create_trial(self): + trial_id = "{{:0{}d}}".format(len(str(self._max_trials))) + trial_id = trial_id.format(self._num_trials) + + if self._max_trials and self._num_trials >= self._max_trials: + status = TrialStatus.STOPPED + values = None + else: + results = self._populate_space() + status = results["status"] + values = results["values"] + + space = TunableSpace() + space.variables = self._space.variables + space.values = values + trial = Trial(tunable_space=space, trial_id=trial_id, status=status) + self._num_trials += 1 + return trial + + def _generate_pipeline_starts(self, process_mesh_list): + total_ops = len(self._dist_context._dist_ops_for_program) + total_stages = len(process_mesh_list) + ops_per_stage = total_ops // total_stages + if ops_per_stage == 0: + return None + # Compute the initial pipeline starts + pipeline_starts = [] + start = 0 + pipeline_starts.append(0) + # The pipeline_starts have total_stages+1 items, and + # at least have 2 items. + for _ in process_mesh_list: + start += ops_per_stage + pipeline_starts.append(start) + pipeline_starts[-1] = total_ops + # Adjust the pipeline starts by random selection + directions = [] + sizes = [] + half_ops_per_stage = ops_per_stage // 2 + if half_ops_per_stage > 0 and total_stages > 1: + new_pipeline_starts = [] + # Don't change the first start + new_pipeline_starts.append(0) + # Consider the starts except the first and the last one + for _ in pipeline_starts[1:-1]: + directions.append(Boolean("direction")) + sizes.append( + IntRange("size", + start=0, + stop=half_ops_per_stage, + endpoint=True)) + for i, start in enumerate(pipeline_starts[1:-1]): + direction = directions[i].random(self._seed) + size = sizes[i].random(self._seed) + if direction: + # Substract 1 from size to avoid the overlapping of new starts + new_start = start - (size - 1) + else: + new_start = start + size + new_pipeline_starts.append(new_start) + # Don't change the last start + new_pipeline_starts.append(pipeline_starts[-1]) + # Validate the new starts + print("Adjusted pipeline starts", + new_pipeline_starts, + half_ops_per_stage, + pipeline_starts, + flush=True) + for i, new_start in enumerate(new_pipeline_starts[1:]): + assert new_start > new_pipeline_starts[i] + return new_pipeline_starts + else: + print("Non-adjusted pipeline starts", + pipeline_starts, + half_ops_per_stage, + flush=True) + return pipeline_starts + + def _apply_pipeline_partition(self, process_mesh_list): + op_id_to_process_mesh = {} + total_ops = len(self._dist_context._dist_ops_for_program) + total_stages = len(process_mesh_list) + ops_per_stage = total_ops // total_stages + if ops_per_stage == 0: + return None + pipeline_starts = self._generate_pipeline_starts(process_mesh_list) + start_idx = 1 + sorted_op_ids = sorted(self._dist_context._dist_ops_for_program.keys()) + for idx, op_id in enumerate(sorted_op_ids): + if idx < pipeline_starts[start_idx]: + op_id_to_process_mesh[op_id] = process_mesh_list[start_idx - 1] + else: + start_idx += 1 + op_id_to_process_mesh[op_id] = process_mesh_list[start_idx - 1] + return op_id_to_process_mesh + + def _amend_dist_attr(self): + # 1) Reshape the process mesh of [1, x] to [x] or [x, 1] to [x], + # and amend the corresponding dims_mapping. + # 2) Set the dim_mapping to -1 when the shape cannot be divided + # by the corresponding processes. + for dist_op in self._dist_context._dist_ops_for_program.values(): + dist_attr = dist_op.dist_attr + process_mesh = dist_attr.process_mesh + if process_mesh is None: + continue + assert process_mesh.ndim == 2 + dim_of_one = None + dim_of_other = None + if process_mesh.topology[0] == 1: + dim_of_one = 0 + dim_of_other = 1 + elif process_mesh.topology[1] == 1: + dim_of_one = 1 + dim_of_other = 0 + + if dim_of_one is not None: + dist_attr.process_mesh = ProcessMesh(process_mesh.processes) + self._dist_context.add_process_mesh(dist_attr.process_mesh) + + for arg_name in dist_attr.inputs_dist_attrs.keys(): + new_dims_mapping = [] + dims_mapping = dist_attr.get_input_dims_mapping(arg_name) + for dim_mapping in dims_mapping: + if dim_mapping == dim_of_one: + new_dims_mapping.append(-1) + elif dim_mapping == dim_of_other: + new_dims_mapping.append(0) + else: + new_dims_mapping.append(dim_mapping) + dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping) + + dims_mapping = dist_attr.get_input_dims_mapping(arg_name) + # dynamic_dims = dist_attr.get_input_dynamic_dims(arg_name) + process_mesh = dist_attr.process_mesh + process_shape = process_mesh.topology + tensor = dist_op.get_serial_input(arg_name) + if dims_mapping: + tensor_shape = tensor.shape + else: + continue + for i, dim_mapping in enumerate(dims_mapping): + # if dim_mapping != -1 \ + # and (tensor_shape[i] % process_shape[dim_mapping] != 0 \ + # or dynamic_dims[i] == 1): + if dim_mapping != -1 \ + and (tensor_shape[i] % process_shape[dim_mapping] != 0): + dims_mapping[i] = -1 + # it is a fix-bug + if dim_mapping != -1 \ + and process_shape[dim_mapping] == 1: + dims_mapping[i] = -1 + + for arg_name in dist_attr.outputs_dist_attrs.keys(): + new_dims_mapping = [] + dims_mapping = dist_attr.get_output_dims_mapping(arg_name) + for dim_mapping in dims_mapping: + if dim_mapping == dim_of_one: + new_dims_mapping.append(-1) + elif dim_mapping == dim_of_other: + new_dims_mapping.append(0) + else: + new_dims_mapping.append(dim_mapping) + dist_attr.set_output_dims_mapping(arg_name, new_dims_mapping) + + dims_mapping = dist_attr.get_output_dims_mapping(arg_name) + # dynamic_dims = dist_attr.get_output_dynamic_dims(arg_name) + process_mesh = dist_attr.process_mesh + process_shape = process_mesh.topology + + tensor = dist_op.get_serial_output(arg_name) + if dims_mapping: + tensor_shape = tensor.shape + else: + continue + for i, dim_mapping in enumerate(dims_mapping): + if dim_mapping != -1 \ + and (tensor_shape[i] % process_shape[dim_mapping] != 0): + dims_mapping[i] = -1 + # it is a fix-bug + if dim_mapping != -1 \ + and process_shape[dim_mapping] == 1: + dims_mapping[i] = -1 + dist_op_impls = find_compatible_distributed_operator_impls( + dist_op, partial=False) + serial_op_type = dist_op.serial_op.type + + if dist_op_impls is not None and ( + serial_op_type != "fused_softmax_mask_upper_triangle" + or self._check_fused_softmax_mask_upper_triangle(dist_op)): + dist_op.dist_attr.impl_type = dist_op_impls[0].type + dist_op.dist_attr.impl_idx = dist_op_impls[0].idx + else: + # Use the default dist op impl + for arg_name in dist_attr.inputs_dist_attrs.keys(): + dims_mapping = dist_attr.get_input_dims_mapping(arg_name) + for i, _ in enumerate(dims_mapping): + dims_mapping[i] = -1 + for arg_name in dist_attr.outputs_dist_attrs.keys(): + dims_mapping = dist_attr.get_output_dims_mapping(arg_name) + for i, _ in enumerate(dims_mapping): + dims_mapping[i] = -1 + dist_op.dist_attr.impl_type = "default" + dist_op.dist_attr.impl_idx = 0 + + def _check_fused_softmax_mask_upper_triangle(self, dist_op): + """The last_but_one dim shoule be equal to last dim.""" + input_name = dist_op.serial_op.input_arg_names[0] + input_dims_mapping = dist_op.dist_attr.get_input_dims_mapping( + input_name) + topology = dist_op.dist_attr.process_mesh.topology + input_tensor = dist_op.get_serial_input(input_name) + last_but_one_dim = input_tensor.shape[-2] // topology[ + input_dims_mapping[-2]] if input_dims_mapping[ + -2] != -1 else input_tensor.shape[-2] + last_dim = input_tensor.shape[-1] // topology[input_dims_mapping[ + -1]] if input_dims_mapping[-1] != -1 else input_tensor.shape[-1] + if last_but_one_dim == last_dim: + return True + return False + + def _eval_trial(self, trial): + if self._num_trials == 0: + num_prev_trials = 0 + else: + num_prev_trials = self._num_trials - 1 + + results = None + + start_time = time.time() + + inter_node_partition = trial.space.values["inter_node_partitions"] + intra_node_partition = trial.space.values["intra_node_partitions"] + process_mesh_list = self._generate_process_mesh_list( + inter_node_partition, intra_node_partition) + print("\tprocess_mesh list", process_mesh_list, flush=True) + op_id_to_process_mesh = self._apply_pipeline_partition( + process_mesh_list) + if op_id_to_process_mesh is None: + print("Operators are less than pipeline stages", flush=True) + return results + + op_id_to_dist_attr = {} + for name, value in trial.space.values.items(): + if name != "inter_node_partitions" \ + and name !="intra_node_partitions": + op_id_to_dist_attr[int(name)] = value + + end_time = time.time() + cur_sample_time = end_time - start_time + self._sample_time = (num_prev_trials * self._sample_time + + cur_sample_time) / self._num_trials + print("\tsample_time", + num_prev_trials, + self._num_trials, + self._sample_time, + cur_sample_time, + flush=True) + + assert len(op_id_to_process_mesh) == len(op_id_to_dist_attr) + + start_time = time.time() + for op_id, process_mesh in op_id_to_process_mesh.items(): + dist_op = self._dist_context._dist_ops_for_program[op_id] + dist_op.dist_attr = copy.deepcopy(op_id_to_dist_attr[op_id]) + assert dist_op.dist_attr.impl_type == op_id_to_dist_attr[ + op_id].impl_type + assert dist_op.dist_attr.impl_idx == op_id_to_dist_attr[ + op_id].impl_idx + dist_op.dist_attr.process_mesh = process_mesh + self._amend_dist_attr() + + self._completer._complete_tensor_dist_attr_by_op() + + self._dist_context.block_state.parse_forward_blocks( + self._dist_context.serial_main_program) + + end_time = time.time() + cur_complete_time = end_time - start_time + self._complete_time = (num_prev_trials * self._complete_time + + cur_complete_time) / self._num_trials + print("\tcomplete_time", + num_prev_trials, + self._num_trials, + self._complete_time, + cur_complete_time, + flush=True) + + start_time = time.time() + estimate_time = self._estimate_trial() + end_time = time.time() + cur_estimate_time = end_time - start_time + self._estimate_time = (num_prev_trials * self._estimate_time + + cur_estimate_time) / self._num_trials + print("\testimate_time", + num_prev_trials, + self._num_trials, + self._estimate_time, + cur_estimate_time, + estimate_time, + flush=True) + + results = {"estimate_time": estimate_time} + return results + + def _update_trail(self, trial, metrics, step=0): + for metric_name, metric_value in metrics.items(): + trial.recorder.update(metric_name, metric_value, step=step) + return trial.status + + def _estimate_trial(self): + assert self._cluster is not None + if self._mode == "eval": + self._estimator = CostEstimator( + self._dist_context.serial_main_program, + self._cluster, + loop_count=self._loop_count) + elif self._mode == "predict": + self._estimator = CostEstimator( + self._dist_context.serial_main_program, + self._cluster, + loop_count=self._loop_count) + elif self._mode == "train": + # get serial main program with backward + serial_main_program = self._dist_context.serial_main_program + serial_startup_program = self._dist_context.serial_startup_program + serial_optimizer = self._dist_context.serial_optimizer + + # Generate backward + serial_loss = self._dist_context.serial_fetch_vars["loss"][0] + params_grads = self._parallelizer._generate_backward( + serial_main_program, serial_startup_program, serial_loss) + + # Generate optimizer + optimizer_ops = self._parallelizer._generate_optimizer( + serial_main_program, serial_startup_program, serial_optimizer, + params_grads) + self._estimator = CostEstimator(serial_main_program, + self._cluster, + loop_count=self._loop_count) + + max_memory = self._estimator._estimate_max_memory_by_dist_op( + self._dist_context) + print("\tmax_memory", "{:,}".format(max_memory), flush=True) + # The max memory must be less than 80% 32GB (hard code) + if max_memory > 32 * 0.8 * 1024 * 1024 * 1024: + return math.inf + else: + global_cost = self._estimator.estimate(self._dist_context) + return global_cost.time + + def _store_init_parallel_strategy(self): + # If there is no annotation information, use the dp as the initial parallel strategy. + # TODO: we should need a better way to set up the initial parallel strategy. + if not self._dist_context.has_annotation \ + or not self._dist_context.process_meshes: + ranks = self._num_machines * self._num_devices_per_machine + tensor_node = self._dist_context._serial_ordered_tensor_nodes[0] + tensor_node_id = _node_id(tensor_node) + tensor = self._dist_context._dist_tensors_for_graph[ + tensor_node_id].serial_tensor + tensor_dist_attr = self._dist_context._dist_tensors_for_graph[ + tensor_node_id].dist_attr + tensor_dist_attr.process_mesh = ProcessMesh(list(range(ranks))) + self._dist_context._process_meshes.append( + tensor_dist_attr.process_mesh) + tensor_dist_attr.dims_mapping = [0] + [ + -1 for _ in range(len(tensor.shape) - 1) + ] + tensor_dist_attr.mark_annotated("process_mesh") + tensor_dist_attr.mark_annotated("dims_mapping") + print("Use dp as the init parallel strategy!", flush=True) + + # Do the sharding propagation + self._completer.complete_forward_annotation() + self._dist_context.block_state.parse_forward_blocks( + self._dist_context.serial_main_program) + + # Backup the intital parallel strategy + self._init_parallel_strategy[0] = copy.deepcopy( + self._dist_context._dist_tensors_for_program) + self._init_parallel_strategy[1] = copy.deepcopy( + self._dist_context._dist_ops_for_program) + self._init_parallel_strategy[2] = copy.deepcopy( + self._dist_context.process_meshes) + + # Initialize the best parallel strategy to the initial one + self._best_parallel_strategy[0] = copy.deepcopy( + self._dist_context._dist_tensors_for_program) + self._best_parallel_strategy[1] = copy.deepcopy( + self._dist_context._dist_ops_for_program) + self._best_parallel_strategy[2] = copy.deepcopy( + self._dist_context._process_meshes) + + def _store_best_parallel_strategy(self): + # Swap the best and the current parallel strategy + tmp = [None, None, None] + tmp[0] = self._best_parallel_strategy[0] + tmp[1] = self._best_parallel_strategy[1] + tmp[2] = self._best_parallel_strategy[2] + self._best_parallel_strategy[ + 0] = self._dist_context._dist_tensors_for_program + self._best_parallel_strategy[ + 1] = self._dist_context._dist_ops_for_program + self._best_parallel_strategy[2] = self._dist_context._process_meshes + self._dist_context._dist_tensors_for_program = tmp[0] + self._dist_context._dist_ops_for_program = tmp[1] + self._dist_context._process_meshes = tmp[2] + + def tune(self): + global_start_time = time.time() + self._dist_context._backup(serial=True, dist=True) + # This store statement must follow the above backup statement + self._store_init_parallel_strategy() + init_time = self._estimate_trial() # estimate_trial when init + # print_program_with_dist_attr(self._dist_context.serial_main_program, self._dist_context) + # We have to restore the distributed context, because the estimation of one trail need to + # generate the backward and update parts. Since we will do the tuning process, + # here we only need to reset all distributed information to the default one. + self._dist_context._restore(serial=True, + serial_mode="to_backup", + dist=True, + dist_mode="to_default") + + best_time = init_time + start_time = time.time() + self.construct_space() + end_time = time.time() + print("construct_space time", + self._num_trials, + end_time - start_time, + flush=True) + create_trial_time = 0.0 + eval_trial_time = 0.0 + self._sample_time = 0.0 + self._complete_time = 0.0 + self._estimate_time = 0.0 + while True: + start_time = time.time() + trial = self._create_trial() + if self._num_trials == 0: + num_prev_trials = 0 + else: + num_prev_trials = self._num_trials - 1 + end_time = time.time() + cur_create_trial_time = end_time - start_time + create_trial_time = (num_prev_trials * create_trial_time + + cur_create_trial_time) / self._num_trials + print("create_trial time", + num_prev_trials, + self._num_trials, + create_trial_time, + cur_create_trial_time, + flush=True) + if trial.status == TrialStatus.STOPPED: + break + # We need to backup the distributed context, because the evaluation of one trail will + # generate the backward and update parts which may change the context. + # However, the distributed information of the context aren't backup since a new one is used. + self._dist_context._backup(serial=True, dist=False) + + start_time = time.time() + results = self._eval_trial(trial) + end_time = time.time() + cur_eval_trial_time = end_time - start_time + eval_trial_time = (num_prev_trials * eval_trial_time + + cur_eval_trial_time) / self._num_trials + print("eval_trial time", + num_prev_trials, + self._num_trials, + eval_trial_time, + cur_eval_trial_time, + "\n", + flush=True) + + cur_time = results["estimate_time"] + if cur_time < best_time: + self._update_trail(trial, results) + self._store_best_parallel_strategy() + best_time = cur_time + # We need to restore the distributed context and reset the distributed information to the default. + self._dist_context._restore(serial=True, + serial_mode="to_backup", + dist=True, + dist_mode="to_default") + # Select the best parallel strategy + self._dist_context._dist_tensors_for_program = self._best_parallel_strategy[ + 0] + self._dist_context._dist_ops_for_program = self._best_parallel_strategy[ + 1] + self._dist_context._process_meshes = self._best_parallel_strategy[2] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2655028bf7f07b3accbdde0098f2e57ef6719d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/profiler.py @@ -0,0 +1,285 @@ +# Copyright (c) 2022 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. + +import os +import argparse +import traceback +import pickle +import json +import time + +import paddle +from paddle.fluid.framework import Program, _current_expected_place +from paddle.fluid.framework import Operator +from paddle.distributed.auto_parallel.process_group import get_all_process_groups, new_process_group +from paddle.distributed.auto_parallel.dist_loader import DistributedDataLoaderFromGenerator +from paddle.distributed.collective import _get_global_env + +paddle.enable_static() + + +def str2bool(v): + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise argparse.ArgumentTypeError('Unsupported value encountered.') + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--profile_start_step", + default=10, + type=int, + help="integer indicates the warmup step before starting profile.") + parser.add_argument("--profile_end_step", + default=30, + type=int, + help="integer indicates at the end step of profile.") + parser.add_argument("--rank", + type=int, + required=True, + help="the rank id of the this process.") + parser.add_argument("--device_id", + type=int, + required=True, + help="the device id of the this process.") + parser.add_argument( + "--ctx_filename", + type=str, + required=True, + help= + "the filename to the profile context file saved by optimizaiton tuner") + + args = parser.parse_args() + + return args + + +def init_process_groups(group_map, rank): + for group_id, ranks in group_map.items(): + if group_id == 0: + continue + new_process_group(ranks=ranks, group_id=group_id) + + # TODO should instantiate global group first + all_process_groups = get_all_process_groups() + for process_group in all_process_groups: + if process_group.id == 0 or rank not in process_group.ranks: + continue + print(process_group) + process_group.instantiate() + + +def get_cpp_error_type(error): + + msg = str(error).splitlines() + cpp_error_types = [ + 'InvalidArgumentError', + 'NotFoundError', + 'OutOfRangeError', + 'AlreadyExistsError', + 'ResourceExhaustedError', + 'PreconditionNotMetError', + 'PermissionDeniedError', + 'ExecutionTimeoutError', + 'UnimplementedError', + 'UnavailableError', + 'FatalError', + 'ExternalError', + ] + error_type = 'FatalError' + for et in cpp_error_types: + for line in msg: + if et in line: + return et + return error_type + + +def create_dataloader(main_program, + startup_program, + profile_ctx, + epochs=1, + steps_per_epoch=None): + + dataset = profile_ctx["dataset"] + main_block = main_program.global_block() + feed_list = [] + for name in dataset.input_names: + if name in main_block.vars: + feed_list.append(main_block.vars[name]) + + # remove the first three ops if multi run fit/evaluate/predict + op_size = len(main_block.ops) + if main_block.ops[0].type == 'create_py_reader': + op_size -= 3 + for _ in range(3): + main_block._remove_op(0, sync=False) + + # insert read op at the end of program + places = paddle.static.cuda_places() + with paddle.static.program_guard(main_program, startup_program): + dataloader = DistributedDataLoaderFromGenerator( + dataset=dataset, + feed_list=feed_list, + capacity=70, + places=places, + batch_size=dataset.batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + data_parallel_world_size=dataset.dp_world_size, + data_parallel_rank=dataset.dp_rank) + + # move read op from the end of program to the start of program + new_op_size = len(main_block.ops) + for _ in range(new_op_size - 1, op_size - 1, -1): + op = main_block.ops[new_op_size - 1] + new_op_desc = main_block.desc._prepend_op() + new_op_desc.copy_from(op.desc) + new_op = Operator(main_block, new_op_desc, type=new_op_desc.type()) + main_block.ops.insert(0, new_op) + for _ in range(new_op_size - op_size): + main_block._remove_op(new_op_size, sync=False) + main_block._sync_with_cpp() + return dataloader + + +def init_comm(profile_ctx): + # override the env for current process + dist_env = profile_ctx['distributed_env'] + genv = _get_global_env() + genv = dist_env + print("current process rank: {}, device_id: {}, ip: {}.", genv.rank, + genv.device_id, genv.current_endpoint) + + # init nccl comm + group_map = profile_ctx['group_map'] + init_process_groups(group_map, args.rank) + + +def load_programs(profile_ctx): + main_program_desc_str = profile_ctx['main_program_decs'] + main_program = Program.parse_from_string(main_program_desc_str) + + startup_program_decs_str = profile_ctx['startup_program_decs'] + startup_program = Program.parse_from_string(startup_program_decs_str) + + loss_var_name = profile_ctx["loss_var_name"] + assert main_program.global_block().has_var(loss_var_name) + loss_var = main_program.global_block().var(loss_var_name) + + return main_program, startup_program, loss_var + + +def get_executor(): + place_type = _current_expected_place() + if not isinstance(place_type, paddle.CUDAPlace): + raise RuntimeError("OptimizationTuner only support CUDA GPU right now.") + + genv = _get_global_env() + place = paddle.CUDAPlace(genv.device_id) + exe = paddle.static.Executor(place) + return exe + + +def profiler(args): + """ + main function to profile experiment for each pass hyper-parameter. + """ + # load ctx + if not os.path.isfile(args.ctx_filename): + raise ValueError("There is no profile context named {}.".format( + args.ctx_filename)) + with open(args.ctx_filename, 'rb') as f: + profile_ctx = pickle.load(f, encoding='latin1') + + init_comm(profile_ctx) + + main_program, startup_program, loss_var = load_programs(profile_ctx) + + data_loader = create_dataloader(main_program, startup_program, profile_ctx) + + result_path = profile_ctx["result_filename"] + + exe = get_executor() + + exe.run(startup_program) + + # profile main + duration = 0 + eval_step = 0 + data_loader._inner_dataloader.start() + try: + while eval_step < args.profile_end_step: + start_time = time.time() + + loss = exe.run( + main_program, + fetch_list=[loss_var], + use_program_cache=True, + ) + + end_time = time.time() + + if eval_step >= args.profile_start_step: + duration += end_time - start_time + + print("step: %d, loss_print: %f" % (eval_step, loss[0])) + eval_step += 1 + + avg_tput = 1.0 * (args.profile_end_step - + args.profile_start_step) / duration + + result_dict = { + "Throughtput": avg_tput, + "ErrorType": None, + } + + if paddle.distributed.get_rank() == 0: + with open(result_path, 'w') as fp: + json.dump(result_dict, fp) + + print("profile done! avg speed : {} step / s.".format((avg_tput))) + + except paddle.framework.core.EOFException: + data_loader._inner_dataloader.reset() + + except Exception as e: + + error_type = get_cpp_error_type(e) + result_dict = { + "Throughtput": -1, + "ErrorType": error_type, + } + if not os.path.isfile(result_path): + with open(result_path, 'w') as fp: + json.dump(result_dict, fp) + + print("profile failed with error: [{}]".format(error_type)) + print(e) + print(traceback.format_exc()) + + data_loader._inner_dataloader.reset() + del data_loader._inner_dataloader + exit(1) + + data_loader._inner_dataloader.reset() + del data_loader._inner_dataloader + + +if __name__ == "__main__": + args = parse_args() + profiler(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/recorder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..de3c9cb84295b9e6aab9c9f929d3e1dfcc19be4d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/recorder.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022 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. + +# Notice that the following codes are modified from KerasTuner for a different purpose. +# Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/metrics_tracking.py. + +import numpy as np + + +class MetricRecord(object): + """ + One record for a single metric at a given execution step. + """ + + def __init__(self, value, step): + self._value = value + self._step = step + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + + @property + def step(self): + return self._step + + @step.setter + def step(self, step): + self._step = step + + def mean(self): + return np.mean(self.value) + + def get_state(self): + return {"value": self.value, "step": self.step} + + @classmethod + def from_state(cls, state): + return cls(**state) + + def __eq__(self, other): + if not isinstance(other, MetricRecord): + return False + return other.value == self.value and other.step == self.step + + def __repr__(self): + return "MetricRecord(value={}, step={})".format(self.value, self.step) + + +class MetricRecords(object): + """ + Records of a single metric across different executions. + """ + + def __init__(self, direction="min"): + if direction not in {"min", "max"}: + raise ValueError( + "direction should be one of {min, max}, but got: {}.".format( + direction)) + self._direction = direction + self._records = {} + + @property + def records(self): + return sorted(self._records.values(), key=lambda r: r.step) + + @records.setter + def records(self, records): + for r in records: + self.update(r.value, step=r.step) + + @property + def direction(self): + return self._direction + + @direction.setter + def direction(self, direction): + self._direction = direction + + def update(self, value, step=0): + if step in self._records: + self._records[step].set_value(value) + else: + self._records[step] = MetricRecord(value, step=step) + + def get_best_value(self): + values = list(r.mean() for r in self._records.values()) + if not values: + return None + if self._direction == "min": + return np.nanmin(values) + return np.nanmax(values) + + def get_best_step(self): + best_value = self.get_best_value() + if best_value is None: + return None + for r in self._records.values(): + if r.mean() == best_value: + return r.step + + def get_statistics(self): + records = self.records + records_values = [r.mean() for r in records] + if not len(records_values): + return {} + return { + "min": float(np.nanmin(records_values)), + "max": float(np.nanmax(records_values)), + "mean": float(np.nanmean(records_values)), + "median": float(np.nanmedian(records_values)), + "var": float(np.nanvar(records_values)), + "std": float(np.nanstd(records_values)), + } + + def get_state(self): + state = {} + state["direction"] = self._direction + state["records"] = [r.get_state() for r in self.records] + return state + + @classmethod + def from_state(cls, state): + records = cls(state["direction"]) + records.records = [MetricRecord.from_state(r) for r in state["records"]] + return records + + +class MetricsRecorder(object): + """ + Record the values for all metrics. + """ + + def __init__(self, metrics=None): + self._records = {} + self.register_metrics(metrics) + + @property + def records(self): + return self._records + + def exists(self, name): + return name in self._records + + def register_metrics(self, metrics=None): + metrics = metrics or [] + for metric in metrics: + self.register(metric.name) + + def register(self, name, direction=None): + if self.exists(name): + raise ValueError("Metric {} have been registered.".format(name)) + if direction is None: + direction = "min" + self._records[name] = MetricRecords(direction) + + def update(self, name, value, step=0): + value = float(value) + if not self.exists(name): + self.register(name) + + prev_best = self._records[name].get_best_value() + self._records[name].update(value, step=step) + new_best = self._records[name].get_best_value() + + improved = new_best != prev_best + return improved + + def get_records(self, name): + return self._records[name].records + + def set_records(self, name, records): + if not self.exists(name): + self.register(name) + self._records[name].records = records + + def get_best_value(self, name): + return self._records[name].get_best_value() + + def get_best_step(self, name): + return self._records[name].get_best_step() + + def get_statistics(self, name): + return self._records[name].get_statistics() + + def get_state(self): + return { + "metrics": { + name: metric_records.get_state() + for name, metric_records in self._records.items() + } + } + + @classmethod + def from_state(cls, state): + recorder = cls() + recorder._records = { + name: MetricRecords.from_state(metric_records) + for name, metric_records in state["metrics"].items() + } + return recorder diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/storable.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/storable.py new file mode 100644 index 0000000000000000000000000000000000000000..18a0669d62286b104cc2119bac8e15817e986725 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/storable.py @@ -0,0 +1,40 @@ +# Copyright (c) 2022 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. + +# Notice that the following codes are modified from KerasTuner for a different purpose. +# Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/metrics_tracking.py. + +import json + + +class Storable(object): + + def get_state(self): + raise NotImplementedError + + def set_state(self, state): + raise NotImplementedError + + def save(self, path): + state = self.get_state() + state_json = json.dumps(state) + with open(path, "w") as f: + f.write(state_json) + return str(path) + + def load(self, path): + with open(path, "r") as f: + state_data = f.read() + state = json.loads(state_data) + self.set_state(state) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/trial.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/trial.py new file mode 100644 index 0000000000000000000000000000000000000000..edc588b4c70fec3de995bae616961e6b1f87c81e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/trial.py @@ -0,0 +1,170 @@ +# Copyright (c) 2022 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. + +# Notice that the following codes are modified from KerasTuner to implement our own tuner. +# Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/trial.py. + +import hashlib +import random +import time +from enum import Enum + +from .storable import Storable +from .recorder import MetricsRecorder +from .tunable_space import TunableSpace + + +class TrialStatus: + RUNNING = "RUNNING" + COMPLETED = "COMPLETED" + STOPPED = "STOPPED" + INVALID = "INVALID" + + +class Trial(Storable): + + def __init__(self, + tunable_space, + trial_id=None, + status=TrialStatus.RUNNING): + self._id = _generate_trial_id() if trial_id is None else trial_id + self._space = tunable_space + self._recorder = MetricsRecorder() + self._score = None + self._best_step = None + self._status = status + + @property + def id(self): + return self._id + + @property + def space(self): + return self._space + + @property + def recorder(self): + return self._recorder + + @property + def score(self): + return self._score + + @score.setter + def score(self, score): + self._score = score + + @property + def best_step(self): + return self._best_step + + @best_step.setter + def best_step(self, best_step): + self._best_step = best_step + + @property + def status(self): + return self._status + + @status.setter + def status(self, status): + self._status = status + + def summary(self): + print("Tunable space:") + if self.space.values: + for tv, value in self.space.values.items(): + print(tv + ":", value) + + if self.score is not None: + print("Score: {}".format(self.score)) + + def get_state(self): + return { + "id": self.id, + "space": self.space.get_state(), + "recorder": self.recorder.get_state(), + "score": self.score, + "best_step": self.best_step, + "status": self.status, + } + + def set_state(self, state): + self._id = state["id"] + self._space = TunableSpace.from_state(state["space"]) + self._recorder = MetricsRecorder.from_state(state["recorder"]) + self._score = state["score"] + self._best_step = state["best_step"] + self._status = state["status"] + + @classmethod + def from_state(cls, state): + trial = cls(tunable_space=None) + trial.set_state(state) + return trial + + +class OptimizationTunerTrial(Trial): + + def __init__(self, + config, + name, + changed_configs, + trial_id=None, + status=TrialStatus.RUNNING): + super(OptimizationTunerTrial, self).__init__(config, trial_id, status) + self._name = name + self._changed_configs = changed_configs + + @property + def name(self): + return self._name + + def summary(self): + + spacing = 2 + max_k = 38 + max_v = 38 + + length = max_k + max_v + spacing + + h1_format = " " + "|{{:^{}s}}|\n".format(length) + h2_format = " " + "|{{:>{}s}}{}{{:^{}s}}|\n".format( + max_k, " " * spacing, max_v) + + border = " +" + "".join(["="] * length) + "+" + line = " +" + "".join(["-"] * length) + "+" + + draws = border + "\n" + draws += h1_format.format("") + draws += h1_format.format("Tuned Configuartions Overview") + draws += h1_format.format("") + + for name in self._changed_configs: + draws += border + "\n" + draws += h1_format.format("{} auto=True <-> {}".format(name, name)) + draws += line + "\n" + my_configs = getattr(self.space, name) + keys = my_configs.to_dict().keys() + for key in keys: + draws += h2_format.format( + key, str(my_configs.to_dict().get(key, None))) + + result_res = draws + border + return result_res + + +def _generate_trial_id(): + s = str(time.time()) + str(random.randint(1, int(1e7))) + return hashlib.sha256(s.encode("utf-8")).hexdigest()[:32] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_space.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_space.py new file mode 100644 index 0000000000000000000000000000000000000000..38dc142468e8aa906db4e615e5c1d53efc738e25 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_space.py @@ -0,0 +1,169 @@ +# Copyright (c) 2022 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. + +# Notice that the following codes are modified from KerasTuner to implement our own tuner. +# Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/hyperparameters.py. + +import collections +import contextlib +import copy +import math +import random +import numpy as np + +from .tunable_variable import Boolean +from .tunable_variable import Fixed +from .tunable_variable import Choice +from .tunable_variable import IntRange +from .tunable_variable import FloatRange + + +class TunableSpace(object): + """ + A TunableSpace is constructed by the tunable variables. + """ + + def __init__(self): + # Tunable variables for this tunable variables + self._variables = {} + # Specific values coresponding to each tunable variable + self._values = {} + + @property + def variables(self): + return self._variables + + @variables.setter + def variables(self, variables): + self._variables = variables + + @property + def values(self): + return self._values + + @values.setter + def values(self, values): + self._values = values + + def get_value(self, name): + if name in self.values: + return self.values[name] + else: + raise KeyError("{} does not exist.".format(name)) + + def set_value(self, name, value): + if name in self.values: + self.values[name] = value + else: + raise KeyError("{} does not exist.".format(name)) + + def _exists(self, name): + if name in self._variables: + return True + return False + + def _retrieve(self, tv): + tv = tv.__class__.from_state(tv.get_state()) + if self._exists(tv.name): + return self.get_value(tv.name) + return self._register(tv) + + def _register(self, tv): + self._variables[tv.name] = tv + if tv.name not in self.values: + self.values[tv.name] = tv.default + return self.values[tv.name] + + def __getitem__(self, name): + return self.get_value(name) + + def __setitem__(self, name, value): + self.set_value(name, value) + + def __contains__(self, name): + try: + self.get_value(name) + return True + except (KeyError, ValueError): + return False + + def fixed(self, name, default): + tv = Fixed(name=name, default=default) + return self._retrieve(tv) + + def boolean(self, name, default=False): + tv = Boolean(name=name, default=default) + return self._retrieve(tv) + + def choice(self, name, values, default=None): + tv = Choice(name=name, values=values, default=default) + return self._retrieve(tv) + + def int_range(self, name, start, stop, step=1, default=None): + tv = IntRange(name=name, + start=start, + stop=stop, + step=step, + default=default) + return self._retrieve(tv) + + def float_range(self, name, start, stop, step=None, default=None): + tv = FloatRange(name=name, + start=start, + stop=stop, + step=step, + default=default) + return self._retrieve(tv) + + def get_state(self): + return { + "variables": [{ + "class_name": v.__class__.__name__, + "state": v.get_state() + } for v in self._variables.values()], + "values": + dict((k, v) for (k, v) in self.values.items()) + } + + @classmethod + def from_state(cls, state): + ts = cls() + for v in state["variables"]: + v = _deserialize_tunable_variable(v) + ts._variables[v.name] = v + ts._values = dict((k, v) for (k, v) in state["values"].items()) + return ts + + +def _deserialize_tunable_variable(state): + classes = (Boolean, Fixed, Choice, IntRange, FloatRange) + cls_name_to_cls = {cls.__name__: cls for cls in classes} + + if isinstance(state, classes): + return state + + if (not isinstance(state, dict) or "class_name" not in state + or "state" not in state): + raise ValueError( + "Expect state to be a python dict containing class_name and state as keys, but found {}" + .format(state)) + + cls_name = state["class_name"] + cls = cls_name_to_cls[cls_name] + if cls is None: + raise ValueError("Unknown class name {}".format(cls_name)) + + cls_state = state["state"] + deserialized_object = cls.from_state(cls_state) + return deserialized_object diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_variable.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..31dd07aad374c335ae109016e82beaf699483368 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/tuner/tunable_variable.py @@ -0,0 +1,250 @@ +# Copyright (c) 2022 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. + +# Notice that the following codes are modified from KerasTuner to implement our own tuner. +# Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/hyperparameters.py. + +import numpy as np + + +class TunableVariable(object): + """ + Tunablevariable base class. + """ + + def __init__(self, name, default=None): + self.name = name + self._default = default + + @property + def default(self): + return self._default + + def get_state(self): + return {"name": self.name, "default": self.default} + + @classmethod + def from_state(cls, state): + return cls(**state) + + +class Fixed(TunableVariable): + """ + Fixed variable which cannot be changed. + """ + + def __init__(self, name, default): + super(Fixed, self).__init__(name=name, default=default) + self.name = name + if not isinstance(default, (str, int, float, bool)): + raise ValueError( + "Fixed must be an str, int, float or bool, but found {}".format( + default)) + self._default = default + + def random(self, seed=None): + return self._default + + def __repr__(self): + return "Fixed(name: {}, value: {})".format(self.name, self.default) + + +class Boolean(TunableVariable): + """ + Choice between True and False. + """ + + def __init__(self, name, default=False): + super(Boolean, self).__init__(name=name, default=default) + if default not in {True, False}: + raise ValueError( + "default must be a Python boolean, but got {}".format(default)) + + def random(self, seed=None): + rng = np.random.default_rng(seed) + return rng.choice((True, False)) + + def __repr__(self): + return 'Boolean(name: "{}", default: {})'.format( + self.name, self.default) + + +class Choice(TunableVariable): + + def __init__(self, name, values, default=None): + super(Choice, self).__init__(name=name, default=default) + + types = set(type(v) for v in values) + if len(types) > 1: + raise TypeError( + "Choice can contain only one type of value, but found values: {} with types: {}." + .format(str(values), str(types))) + self._is_unknown_type = False + + if isinstance(values[0], str): + values = [str(v) for v in values] + if default is not None: + default = str(default) + elif isinstance(values[0], int): + values = [int(v) for v in values] + if default is not None: + default = int(default) + elif isinstance(values[0], float): + values = [float(v) for v in values] + if default is not None: + default = float(default) + elif isinstance(values[0], bool): + values = [bool(v) for v in values] + if default is not None: + default = bool(default) + else: + self._is_unknown_type = True + self._indices = [i for i in range(len(values))] + self.values = values + + if default is not None and default not in values: + raise ValueError( + "The default value should be one of the choices {}, but found {}" + .format(values, default)) + self._default = default + + @property + def default(self): + if self._default is None: + if None in self.values: + return None + return self.values[0] + return self._default + + def random(self, seed=None): + rng = np.random.default_rng(seed) + if self._is_unknown_type: + indice = rng.choice(self._indices) + return self.values[indice] + else: + return rng.choice(self.values) + + def get_state(self): + state = super(Choice, self).get_state() + state["values"] = self.values + return state + + def __repr__(self): + return 'Choice(name: "{}", values: {}, default: {})'.format( + self.name, self.values, self.default) + + +class IntRange(TunableVariable): + """ + Integer range. + """ + + def __init__(self, name, start, stop, step=1, default=None, endpoint=False): + super(IntRange, self).__init__(name=name, default=default) + self.start = self._check_int(start) + self.stop = self._check_int(stop) + self.step = self._check_int(step) + self._default = default + self.endpoint = endpoint + + @property + def default(self): + if self._default is not None: + return self._default + return self.start + + def random(self, seed=None): + rng = np.random.default_rng(seed) + value = (self.stop - self.start) * rng.random() + self.start + if self.step is not None: + if self.endpoint: + values = np.arange(self.start, self.stop + 1e-7, step=self.step) + else: + values = np.arange(self.start, self.stop, step=self.step) + closest_index = np.abs(values - value).argmin() + value = values[closest_index] + return int(value) + + def get_state(self): + state = super(IntRange, self).get_state() + state["start"] = self.start + state["stop"] = self.stop + state["step"] = self.step + state["default"] = self._default + return state + + def _check_int(self, val): + int_val = int(val) + if int_val != val: + raise ValueError("Expects val is an int, but found: {}.".format( + str(val))) + return int_val + + def __repr__(self): + return "IntRange(name: {}, start: {}, stop: {}, step: {}, default: {})".format( + self.name, self.start, self.stop, self.step, self.default) + + +class FloatRange(TunableVariable): + """ + Float range. + """ + + def __init__(self, + name, + start, + stop, + step=None, + default=None, + endpoint=False): + super(FloatRange, self).__init__(name=name, default=default) + self.stop = float(stop) + self.start = float(start) + if step is not None: + self.step = float(step) + else: + self.step = None + self._default = default + self.endpoint = endpoint + + @property + def default(self): + if self._default is not None: + return self._default + return self.start + + def random(self, seed=None): + rng = np.random.default_rng(seed) + value = (self.stop - self.start) * rng.random() + self.start + if self.step is not None: + if self.endpoint: + values = np.arange(self.start, self.stop + 1e-7, step=self.step) + else: + values = np.arange(self.start, self.stop, step=self.step) + closest_index = np.abs(values - value).argmin() + value = values[closest_index] + return value + + def get_state(self): + state = super(FloatRange, self).get_state() + state["start"] = self.start + state["stop"] = self.stop + state["step"] = self.step + state["endpoint"] = self.endpoint + return state + + def __repr__(self): + return "FloatRange(name: {}, start: {}, stop: {}, step: {}, default: {}, endpoint: {})".format( + self.name, self.start, self.stop, self.step, self.default, + self.endpoint) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc722b53eadee098046dfad364f723dd5662587 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/auto_parallel/utils.py @@ -0,0 +1,1909 @@ +# Copyright (c) 2021 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 + +import os +import copy +import paddle +import threading +import numpy as np +import warnings +import logging +from functools import reduce + +import paddle.fluid.core as core +from paddle.distributed.fleet.meta_optimizers.common import OpRole +from paddle.distributed.auto_parallel.process_group import ( + get_all_process_groups, +) +from paddle.fluid.io import is_parameter, is_belong_to_optimizer +from paddle.distributed.auto_parallel.dist_attribute import ( + TensorDistributedAttribute, + OperatorDistributedAttribute, +) + +__not_shape_var_type__ = [ + core.VarDesc.VarType.READER, + core.VarDesc.VarType.STEP_SCOPES, +] + + +def get_logger(log_level, name="auto_parallel"): + logger = logging.getLogger(name) + logger.propagate = False + if not logger.handlers: + logger.setLevel(log_level) + log_handler = logging.StreamHandler() + log_format = logging.Formatter( + '%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s' + ) + log_handler.setFormatter(log_format) + logger.addHandler(log_handler) + return logger + + +def is_valid_list_index(list, index): + if index >= -len(list) and index < len(list): + return True + else: + return False + + +def is_dim_shard(mapping): + if mapping != -1: + return True + else: + return False + + +def is_dim_replicate(mapping): + if mapping == -1: + return True + else: + return False + + +def verify_dims_mapping(dims_mapping, process_mesh): + if dims_mapping is None: + return False + if not all(isinstance(d, int) for d in dims_mapping): + return False + for i in range(len(dims_mapping)): + if dims_mapping[i] < -1 or dims_mapping[i] >= len(process_mesh.shape): + return False + for i in range(len(process_mesh.shape)): + if dims_mapping.count(i) > 1: + return False + return True + + +def convert_to_dims_mapping(shard_spec, process_mesh): + dims_mapping = [] + for shard in shard_spec: + if shard is None: + dims_mapping.append(-1) + elif process_mesh.topology[process_mesh.dim_names.index(shard)] == 1: + dims_mapping.append(-1) + else: + dims_mapping.append(process_mesh.dim_names.index(shard)) + return dims_mapping + + +def convert_to_shard_spec(dims_mapping, process_mesh): + shard_spec = [] + for dim_mapping in dims_mapping: + if dim_mapping == -1: + shard_spec.append(None) + else: + shard_spec.append(process_mesh.dim_names[dim_mapping]) + return shard_spec + + +def verify_shard_spec(shard_spec, tensor_shape, process_mesh): + if len(shard_spec) != len(tensor_shape): + return False + for shard in shard_spec: + if shard is not None and not isinstance(shard, str): + return False + if shard is not None and shard not in process_mesh.dim_names: + return False + dims_mapping = convert_to_dims_mapping(shard_spec, process_mesh) + if not verify_dims_mapping(dims_mapping, process_mesh): + return False + for i in range(len(tensor_shape)): + if ( + dims_mapping[i] != -1 + and tensor_shape[i] > 0 + and tensor_shape[i] % process_mesh.shape[dims_mapping[i]] != 0 + ): + return False + return True + + +def compute_compatible_dim_mapping(dim_mappings): + if not dim_mappings: + return None + compatible_mapping = dim_mappings[0] + for mapping in dim_mappings: + if compatible_mapping == -1: + compatible_mapping = mapping + elif mapping == -1: + continue + elif compatible_mapping == mapping: + continue + else: + return None + return compatible_mapping + + +def compute_compatible_dims_mapping(dims_mapping_list): + if not dims_mapping_list: + return None + length = len(dims_mapping_list[0]) + for dims_mapping in dims_mapping_list: + assert ( + dims_mapping is not None + ), "Dims mapping must not be None for compatible computation" + assert ( + len(dims_mapping) == length + ), "The length of dims_mapping in list must be same for compatible computation." + compatible_result = [] + for dim_mappings in zip(*dims_mapping_list): + compatible_dim_mapping = compute_compatible_dim_mapping( + list(dim_mappings) + ) + if compatible_dim_mapping is None: + return None + compatible_result.append(compatible_dim_mapping) + return compatible_result + + +def compute_compatible_process_mesh(process_mesh_list): + compatible_process_mesh = None + if not process_mesh_list: + return compatible_process_mesh + for process_mesh in process_mesh_list: + if process_mesh is not None: + if ( + compatible_process_mesh is None + or compatible_process_mesh == process_mesh + ): + compatible_process_mesh = process_mesh + else: + return None + return compatible_process_mesh + + +def compute_compatible_and_update_dim_mapping(dims_mapping_list, index_list): + assert len(dims_mapping_list) == len(index_list) + changed = False + dim_mappings = [] + for i in range(len(dims_mapping_list)): + assert is_valid_list_index(dims_mapping_list[i], index_list[i]) + dim_mappings.append(dims_mapping_list[i][index_list[i]]) + compatible_dim_mapping = compute_compatible_dim_mapping(dim_mappings) + if compatible_dim_mapping is None: + return False + for i in range(len(dims_mapping_list)): + if compatible_dim_mapping != dims_mapping_list[i][index_list[i]]: + dims_mapping_list[i][index_list[i]] = compatible_dim_mapping + changed = True + return changed + + +def append_distributed_attr_suffix(name): + """ + Append auto parallel suffix for distributed attribute name. + """ + return name + core.kAutoParallelSuffix() + + +def remove_distributed_attr_suffix(name): + """ + Remove auto parallel suffix from distributed attribute name. + """ + return name.strip(core.kAutoParallelSuffix()) + + +def check_distributed_attr_for_program(program, dist_context=None): + from .dist_context import get_default_distributed_context + + if dist_context is None: + dist_context = get_default_distributed_context() + assert ( + dist_context.is_initialized_for_program() + ), "Distributed attributes must be initialized before check." + for block in program.blocks: + for tensor in block.vars.values(): + dist_tensor = dist_context.get_dist_tensor_for_graph(tensor) + tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program( + tensor + ) + if (tensor_dist_attr is not None) and (not dist_tensor.is_valid()): + return False + for op in block.ops: + dist_op = dist_context.get_dist_op_for_graph(tensor) + op_dist_attr = dist_context.get_op_dist_attr_for_program(op) + if (op_dist_attr is not None) and (not dist_op.is_valid()): + return False + return True + + +def print_program_with_dist_attr(program, dist_context=None): + """ + This function reuses the original program output ability with a distributed context. + Using lock can avoid multiple threads change the default distributed context simultaneously. + """ + lock = threading.Lock() + lock.acquire() + from .dist_context import get_default_distributed_context + from .dist_context import set_default_distributed_context + + if dist_context is None: + dist_context = get_default_distributed_context() + print(program, flush=True) + else: + original_default_context = get_default_distributed_context() + set_default_distributed_context(dist_context) + print(program, flush=True) + set_default_distributed_context(original_default_context) + lock.release() + + +def _get_comm_group(processes, shape, axis, rank): + """ + Given a rank and the processes mesh the rank belongs to, + compute the communication peers of the rank based on the give axis in the mesh. + + Example: 16 processes managed in a 4-Dimensinal mesh with shape of [2, 2, 2, 2]. + the rank communication peers of rank 0 (included) are following: + in axis 0: [0, 1] + in axis 1: [0, 2] + in axis 2: [0, 4] + in axis 3: [0, 8] + """ + + # NOTE _linear_idx2coordinate assume processes mesh start with 0 and continuous + # tricks to support processes mesh when it is not start with 0 or continuous + assert rank in processes, "rank [{}] is NOT in processes group {}".format( + rank, processes + ) + rank_relatvie = processes.index(rank) + coordinate = _linear_idx2coordinate(shape, rank_relatvie) + coordinates_in_group = [coordinate[:] for i in range(shape[axis])] + + # select comm group + for i in range(shape[axis]): + coordinates_in_group[i][axis] = i + + ranks_in_group_relative = [ + _coordinate2linear_idx(shape, coordinate) + for coordinate in coordinates_in_group + ] + ranks_in_group = [processes[idx] for idx in ranks_in_group_relative] + + return sorted(ranks_in_group) + + +def _get_idx_in_axis(processes, shape, axis, rank): + """ + Given a rank and the processes mesh the rank belongs to, + compute the index of the rank in given axis. + + Example: 27 processes managed in a 3-Dimensinal mesh with shape of [3, 3, 3]. + the index of rank 22 are: + in axis 0: 1 + in axis 1: 1 + in axis 2: 2 + """ + + # NOTE _linear_idx2coordinate assume processes mesh start with 0 and continuous + # tricks to support processes mesh when it is not start with 0 or continuous + rank_relatvie = processes.index(rank) + coordinate = _linear_idx2coordinate(shape, rank_relatvie) + return coordinate[axis] + + +def _coordinate2linear_idx(mesh_shape, coordinate): + """ + convert a coordinate in multidimensional mesh space into a scala idx in linear space. + + it use Row-major order for dimension conversion. + so it has: [most_significant_dim, ..., least_significant_dim] + assume: + + the size of i-th dimension to be: S[i] + the index of j-th dimension is: I[j] + + linear_idx of a n dimensional coordinate is: + + I[n-1] * (S[n-2] * S[n-3] * S[n-4] * .... S[0]) + + I[n-2] * ( S[n-3] * S[n-4] * .... S[0]) + + I[n-3] * ( S[n-4] * .... S[0]) + + ... + I[1] * ( S[0]) + + I[0] + + """ + # NOTE the following function work based on a strong an assumption + # that the processes in mesh are + # 1. starts from 0 + # 2. continuous + # it will be wrong if ths above condition doesnot meet, + # e.g. process_mesh = { process_groups = [7, 8, 9,10, 12, 13, 14, 15], mesh = [2, 4]} + # if you want a more general mapping, you should use cartesian product + + assert len(mesh_shape) == len( + coordinate + ), "coordinate should have the same size as mesh shape, but got shape: {}, coordinate: {}".format( + mesh_shape, coordinate + ) + for i in range(len(mesh_shape)): + assert ( + coordinate[i] >= 0 + ), "index in dimension [{}] is least than zero. coordinate: {}".format( + i, coordinate + ) + assert ( + coordinate[i] < mesh_shape[i] + ), "index beyond extent in dimension [{}]. shape: {}, coordinate: {}".format( + i, mesh_shape, coordinate + ) + + base = mesh_shape[-1] + linear_idx = coordinate[-1] + + # row major order + for i in range(len(mesh_shape) - 2, -1, -1): + linear_idx += base * coordinate[i] + base *= mesh_shape[i] + + return linear_idx + + +def _linear_idx2coordinate(mesh_shape, linear_idx): + """ + mapping a linear scala into multidimensional mesh space, return it coordinate in that space. + + it is the inverse function of _coordinate2linear_idx. + assume: + + the size of i-th dimension to be: S[i] + the index of j-th dimension is: I[j] + + the coordinate given linear_idx is: + + I[0] = linear_idx % S[0] + I[0] = (linear_idx / S[0]) % S[1] + I[0] = (linear_idx / (S[0] * S[1])) % S[2] + .... + + """ + + assert linear_idx >= 0, "linear index [{}] is least than zero".format( + linear_idx + ) + assert linear_idx < np.prod( + mesh_shape + ), "linear index beyond the extent of mesh shape. shape: {}, linear index: {}".format( + mesh_shape, linear_idx + ) + + base = 1 + coordinate = [-1] * len(mesh_shape) + + for i in reversed(range(len(mesh_shape))): + offset = linear_idx / base + coordinate[i] = int(offset % mesh_shape[i]) + base *= mesh_shape[i] + + # row major order + return coordinate + + +def _get_corresponding_rank(dist_context, target_mesh, rank): + + # TODO(JZ-LIANG) a hack method to support varying mesh in Pipeline parallelism case. + # we assume that all mesh are evenly divide from a parent mesh and should have same size. + # to revise this in future. + + coordinate = None + for mesh in dist_context.process_meshes: + if rank in mesh.processes and mesh.topology == target_mesh.topology: + coordinate = _linear_idx2coordinate( + mesh.topology, mesh.processes.index(rank) + ) + break + + # assert coordinate is not None, "could NOT found rank [{}] in any registered mesh".format( + # rank) + if coordinate is not None: + return target_mesh.processes[ + _coordinate2linear_idx(mesh.topology, coordinate) + ] + else: + return target_mesh.processes[0] + + +def _get_unshard_dist_shape(var, dist_attr): + var_shape = var.shape + mapping = dist_attr.dims_mapping + mesh = dist_attr.process_mesh.topology + assert len(var_shape) == len( + mapping + ), "variable shape [{}] and dim_mapping [{}] is NOT match !".format( + var_shape, mapping + ) + new_shape = [] + for idx in range(len(var_shape)): + if var_shape[idx] == -1 or mapping[idx] == -1: + new_shape.append(var_shape[idx]) + else: + new_shape.append(var_shape[idx] * mesh[mapping[idx]]) + + return new_shape + + +def make_data_unshard(dist_main_prog, dist_startup_prog, dist_context=None): + from .dist_context import get_default_distributed_context + + if dist_context is None: + dist_context = get_default_distributed_context() + + for var in dist_main_prog.list_vars(): + if var.is_data: + tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program( + var + ) + inverse_shape = _get_unshard_dist_shape(var, tensor_dist_attr) + var.desc.set_shape(inverse_shape) + dim_mapping = tensor_dist_attr.dims_mapping + dim_mapping = [-1] * len(dim_mapping) + tensor_dist_attr.dims_mapping = dim_mapping + dist_context.set_tensor_dist_attr_for_program(var, tensor_dist_attr) + + +def _update_addition_info(addition_info): + """Update default addition_info with inputs""" + add_info = {"epoch": 0, "batch": 0, "batch_size": 0} + if not addition_info: + return add_info + elif not isinstance(addition_info, dict): + raise TypeError( + "The type of 'addition_info' should be 'dict', " + "but got '{}'.".format(str(type(addition_info))) + ) + else: + for item, value in addition_info.items(): + if item not in ["epoch", "batch", "batch_size"]: + raise ValueError( + "The key of 'addition_info' should be one of the " + "['epoch', 'batch', 'batch_size'], but got '{}'.".format( + str(item) + ) + ) + if not isinstance(value, int): + raise ValueError( + "The value of 'addition_info' should be 'int', " + "but got '{}'.".format(str(type(value))) + ) + add_info[item] = value + return add_info + + +def _check_valid_path(file_path): + """Validity check of input file path""" + if not file_path: + return file_path + elif isinstance(file_path, list): + for file in file_path: + if not isinstance(file, str): + raise TypeError( + "The type of file path should be 'str', " + "but got '{}'.".format(str(type(file))) + ) + if not os.path.exists(file): + raise ValueError( + "The file path '{}' does not exist.".format(file) + ) + return file_path + else: + raise TypeError( + "The type of file path should be 'list', " + "but got '{}'.".format(str(type(file_path))) + ) + + +def _check_param_dict(param_dict): + if not param_dict: + raise ValueError("'param_dict' cannot be None.") + elif not isinstance(param_dict, dict): + raise TypeError( + "The type of 'param_dict' should be 'dict', " + "but got '{}'.".format(str(type(param_dict))) + ) + else: + for name, value in param_dict.items(): + if not isinstance(name, str): + raise TypeError( + "The type of key of 'param_dict' should be 'str', " + "but got '{}'.".format(str(type(name))) + ) + if not isinstance(value, paddle.fluid.LoDTensor): + raise TypeError( + "The type of value of 'param_dict' should be 'LoDTensor', " + "but got '{}'.".format(str(type(value))) + ) + return param_dict + + +def _check_dist_attr(dist_attr): + if not dist_attr: + return dist_attr + elif not isinstance(dist_attr, dict): + raise TypeError( + "The type of 'dist_attr' should be 'dict', " + "but got '{}'.".format(str(type(dist_attr))) + ) + else: + for name, value in dist_attr.items(): + if not isinstance(name, str): + raise TypeError( + "The type of param name of 'dist_attr' should be 'str', " + "but got '{}'.".format(str(type(name))) + ) + if not isinstance(value, dict): + raise TypeError( + "The type of distributed attribute should be 'dict', " + "but got '{}'".format(str(type(value))) + ) + attr = ['process_shape', 'process_group', 'dims_mapping'] + if list(value.keys()) != attr: + raise ValueError( + "The key of distributed attribute should be " + "'['process_shape', 'process_group', 'dims_mapping']', " + "but got {}.".format(str(value.keys())) + ) + return dist_attr + + +def save_distributed_checkpoint( + program, + checkpoint_path, + dist_attr_path, + addition_info=None, + is_integrated=False, + dist_context=None, +): + """ + Save model parameter state, optimzer state, distributed attribute and + additional information of each rank. + + Args: + program(Program): The program to be saved. + checkpoint_path(str): The path of the checkpoint file to be saved. + dist_attr_path(str): The path of distributed attribute file to be saved. + addition_info(dict, optional): Additional information, key should be selected in ['epoch', 'batch', 'batch_size']. + Default values are 0, when 'addition_info' is None. Default: None. + is_integrated(bool, optional): Whether to integrate param before save. Default: False. + dist_context(DistributedContext ,optional): collect related distributed information for program + + Returns: + None + + Examples: + .. code-block:: python + + path = os.path.join("./output", "step_%d" % step) + os.makedirs(path, exist_ok=True) + add_info = {'batch': step, "batch_size": global_batch_size} + save_distributed_checkpoint(program, path, path, add_info) + """ + from .dist_context import get_default_distributed_context + + assert isinstance(program, paddle.fluid.framework.Program) + assert isinstance(is_integrated, bool) + if dist_context is None: + dist_context = get_default_distributed_context() + addition_info = _update_addition_info(addition_info) + + if not is_integrated: + _save_distributed_state_dict(program, addition_info, checkpoint_path) + _save_distributed_attribute(program, dist_attr_path, dist_context) + else: + # TODO: integrate param before save + raise NotImplementedError( + "Integrating parameter has not been implemented." + ) + + +def load_distributed_checkpoint(checkpoint_path, dist_attr_path): + """ + Load parameter, optimizer, distributed attribute and addition_info. + + Args: + checkpoint_path(list[str]): model parameter file path, must be in order of rank id. + dist_attr_path(list[str]): distributed attribute file path, must be in order of rank id. + + Returns: + param_dict(dict): parameters' value of all ranks. + dist_attr(dict): parameters' distributed attribute. + addition_info(dict): additional information user saved in last training. + + Notes: + The return, 'addition_info', is belonging to the first file of checkpoint_path by default. + + Examples: + .. code-block:: python + + ckpt_path = ['./model_state_rank0.pdmodel', + './model_state_rank1.pdmodel'] + dist_attr_path = ['./dist_attr_rank0.pdattr', + './dist_attr_rank1.pdattr'] + param_dict, dist_attr, add_info = load_distributed_checkpoint(ckpt_path, dist_attr_path) + """ + assert _check_valid_path( + checkpoint_path + ), "'checkpoint_path' cannot be None." + assert _check_valid_path(dist_attr_path), "'dist_attr_path' cannot be None." + + state_dict_info = _load_distributed_state_dict(checkpoint_path) + dist_attr = _load_distributed_attribute(dist_attr_path) + param_dict = state_dict_info["model"] + addition_info = state_dict_info["addition_info"] + return param_dict, dist_attr, addition_info + + +def load_checkpoint_into_program( + checkpoint_path, dist_attr_path, program, dist_context=None +): + """ + Load parameter, optimizer, distributed attribute and addition_info into model. + + Args: + checkpoint_path(list[str]): model parameter file path, must be in order of rank id. + dist_attr_path(list[str]): distributed attribute file path, must be in order of rank id. + program(Program): the program to be updated with checkpoint_path. + dist_context(DistributedContext ,optional): collect related distributed information for program + + Returns: + addition_info(dict): user saved in last train. + + Notes: + The return, 'addition_info', is belonging to the first file of checkpoint_path by default. + + Examples: + .. code-block:: python + + exe.run(startup_program) + ckpt_path = ['./model_state_rank0.pdmodel', + './model_state_rank1.pdmodel'] + dist_attr_path = ['./dist_attr_rank0.pdattr', + './dist_attr_rank1.pdattr'] + load_checkpoint_into_program(ckpt_path, dist_attr_path, main_program) + """ + from .dist_context import get_default_distributed_context + + assert isinstance(program, paddle.fluid.framework.Program) + assert _check_valid_path( + checkpoint_path + ), "'checkpoint_path' cannot be None." + assert _check_valid_path(dist_attr_path), "'dist_attr_path' cannot be None." + if dist_context is None: + dist_context = get_default_distributed_context() + all_state_dict_info = _load_distributed_state_dict(checkpoint_path) + all_pre_dist_attr = _load_distributed_attribute(dist_attr_path) + all_cur_dist_attr = get_dist_attr(program, dist_context) + all_param_dict = all_state_dict_info["model"] + addition_info = all_state_dict_info["addition_info"] + sliced_param_dict = merge_and_slice_parameter( + all_param_dict, all_pre_dist_attr, all_cur_dist_attr + ) + load_parameter_into_program(sliced_param_dict, program) + + return addition_info + + +def load_parameter_into_program(param_dict, program): + """ + Load parameters into program. + + Args: + param_dict(dict): parameters' name and value. + program(Program): the program to be updated + """ + assert isinstance(param_dict, dict) + assert program and isinstance(program, paddle.fluid.framework.Program) + if not param_dict: + return + program.set_state_dict(param_dict) + + +def _save_distributed_attribute(program, dist_attr_path, dist_context): + """Save distributed attribute of all parameters""" + # TODO: just save a complete distributed attribute file + rank_id = paddle.distributed.get_rank() + dist_attr_name = os.path.join( + dist_attr_path, "dist_attr_rank{}.pdattr".format(rank_id) + ) + dist_attr_dict = { + "model": get_dist_attr(program, dist_context), + "world_size": paddle.distributed.get_world_size(), + } + paddle.save(dist_attr_dict, dist_attr_name) + logging.info( + "Already saved distributed attribute to '{}'.".format(dist_attr_path) + ) + + +def _load_distributed_attribute(dist_attr_path): + """Load parameters' distributed attribute from dist_attr_path""" + total_dist_attr = {} + for dist_attr_file in dist_attr_path: + dist_attr = paddle.load(dist_attr_file) + pre_world_size = dist_attr["world_size"] + assert pre_world_size == len( + dist_attr_path + ), "The number of 'dist_attr_path' must be equal to the last training world size." + for name, attr in dist_attr["model"].items(): + if name not in total_dist_attr: + total_dist_attr[name] = attr + + return total_dist_attr + + +def _save_distributed_state_dict(program, addition_info, checkpoint_path): + """Save parameters' state_dict""" + rank = paddle.distributed.get_rank() + ckpt_file_name = os.path.join( + checkpoint_path, "model_state_rank{}.pdmodel".format(rank) + ) + state_dict = { + "model": program.state_dict(), + "world_size": paddle.distributed.get_world_size(), + "addition_info": addition_info, + } + paddle.save(state_dict, ckpt_file_name) + logging.info("Already saved model to '{}'.".format(checkpoint_path)) + + +def _load_distributed_state_dict(checkpoint_path): + """Load parameters' state_dict from checkpoint_path""" + all_state_dict = {} + for idx, ckpt_file in enumerate(checkpoint_path): + state_dict_info = paddle.load(ckpt_file, return_numpy=True) + pre_world_size = state_dict_info["world_size"] + assert pre_world_size == len( + checkpoint_path + ), "The number of 'checkpoint_path' must be equal to the last training world size." + if idx == 0: + addition_info = state_dict_info["addition_info"] + for name, value in state_dict_info["model"].items(): + if name in all_state_dict: + all_state_dict[name].append(np.array(value)) + else: + all_state_dict[name] = [np.array(value)] + + all_state_dict_info = { + "model": all_state_dict, + "addition_info": addition_info, + } + return all_state_dict_info + + +def get_dist_attr(program, dist_context=None): + """ + Get distributed attribute of current rank. + + Args: + program(Program): main program for training + """ + from .dist_context import get_default_distributed_context + + assert isinstance(program, paddle.fluid.framework.Program) + if dist_context is None: + dist_context = get_default_distributed_context() + dist_attr = {} + for var in program.list_vars(): + if is_parameter(var) or is_belong_to_optimizer(var): + tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program( + var + ) + process_mesh = tensor_dist_attr.process_mesh + dims_mapping = tensor_dist_attr.dims_mapping + dist_attr[var.name] = { + "process_shape": process_mesh.topology, + "process_group": process_mesh.processes, + "dims_mapping": dims_mapping, + } + return dist_attr + + +def merge_and_slice_parameter(dist_param_dict, pre_dist_attr, cur_dist_attr): + """ + Merge parameters with previous dist_attr and slice parameters with current dist_attr + + Arags: + dist_param_dict(dict): parameters' value of all ranks. + pre_dist_attr(dict): parameters' dist_attr of last training process. + cur_dist_attr(dict): parameters' dist_attr of current training process. + + Returns: + dist_param_dict(dict): parameters' value of current rank. + """ + assert _check_dist_attr(pre_dist_attr), "'pre_dist_attr' cannot be None." + assert isinstance( + dist_param_dict, dict + ), "The type of 'dist_param_dict' should be 'dict', but got {}.".format( + str(type(dist_param_dict)) + ) + for name, value in dist_param_dict.items(): + if not isinstance(name, str): + raise TypeError( + "The key of 'dist_param_dict' is parameter's name, " + "and its type should be 'str', but got {}.".format( + str(type(name)) + ) + ) + if not isinstance(value, list) or not all( + isinstance(v, np.ndarray) for v in value + ): + raise TypeError( + "The value of 'dist_param_dict' is parameter's value of all ranks, " + "and its type should be 'list(numpy.ndarray)'." + ) + + if cur_dist_attr is None: + return {} + + param_not_in_pre = [] + param_not_in_cur = [] + logging.info("Start to merge and slice parameters.") + for var_name in cur_dist_attr.keys(): + if var_name not in pre_dist_attr: + param_not_in_pre.append(var_name) + continue + + pre_attr = pre_dist_attr[var_name] + cur_attr = cur_dist_attr[var_name] + if pre_attr == cur_attr: + # skip merge and slice + rank_id = paddle.distributed.get_rank() + index = cur_attr["process_group"].index(rank_id) + param = dist_param_dict[var_name][index] + dist_param_dict[var_name] = param + continue + + pre_param = dist_param_dict[var_name] + pre_dims_mapping = pre_attr["dims_mapping"] + cur_dims_mapping = cur_attr["dims_mapping"] + if len(set(pre_dims_mapping)) > 1 or -1 not in pre_dims_mapping: + complete_param = _merge_parameter_with_dist_attr( + pre_param, pre_attr + ) + dist_param_dict[var_name] = complete_param + else: + complete_param = pre_param[0] + dist_param_dict[var_name] = complete_param + + if len(set(cur_dims_mapping)) > 1 or -1 not in cur_dims_mapping: + sliced_param = _slice_parameter_with_dist_attr( + complete_param, cur_attr + ) + dist_param_dict[var_name] = sliced_param + + for var_name in pre_dist_attr: + if var_name not in cur_dist_attr: + param_not_in_cur.append(var_name) + dist_param_dict.pop(var_name) + + if param_not_in_pre: + warnings.warn( + "Parameters '{}' are not found in last training process.".format( + str(param_not_in_pre) + ) + ) + if param_not_in_cur: + warnings.warn( + "Parameters '{}' are not found in current training process.".format( + str(param_not_in_cur) + ) + ) + + return dist_param_dict + + +def _merge_parameter_with_dist_attr(param_list, dist_attr): + """Merge parameter with distributed attribute""" + from .reshard import Resharder + + dims_mapping = dist_attr["dims_mapping"] + process_shape = dist_attr["process_shape"] + process_group = dist_attr["process_group"] + # get the complete shape of the parameter + complete_shape = Resharder.compute_complete_shape( + param_list[0].shape, process_shape, dims_mapping + ) + # merge the parameter with dist_attr + partition_param_list = [] + merged_partiton = [] + for process in process_group: + partition_index = Resharder.compute_partition_index( + process, complete_shape, dims_mapping, process_shape, process_group + ) + index = process_group.index(process) + if partition_index not in merged_partiton: + merged_partiton.append(partition_index) + _merge_parameter( + partition_param_list, + param_list[index], + partition_index, + complete_shape, + ) + + assert ( + len(partition_param_list) == 1 or not partition_param_list + ), "Fail to merge parameter" + complete_param = partition_param_list[0][0] + return complete_param + + +def _slice_parameter_with_dist_attr(param, dist_attr): + """Slice parameter with distributed attribute""" + param = ( + np.array(param) if isinstance(param, paddle.fluid.LoDTensor) else param + ) + dims_mapping = dist_attr["dims_mapping"] + process_shape = dist_attr["process_shape"] + process_group = dist_attr["process_group"] + # slice the parameter with dist_attr + partition_index_list = _get_split_indices( + param.shape, dims_mapping, process_shape, process_group + ) + sliced_param_list = _slice_parameter( + param, partition_index_list, len(partition_index_list) + ) + # get the current parameter's index in sliced_param_list + rank_id = paddle.distributed.get_rank() + sliced_param_index = _get_sliced_param_index( + rank_id, param.shape, dims_mapping, process_shape, process_group + ) + sliced_param = sliced_param_list[sliced_param_index] + return sliced_param + + +def _merge_parameter( + partition_param_list, param, partition_index, complete_shape +): + """ + Merge partitial parameters to a complete one. + + Returns: + None + + Examples: + .. code-block:: python + + import numpy as np + partition_param_list = [(np.array([[[1.11, 1.12]]]), [[0,1],[0,1],[0,2]])] + param = np.array([[[1.13, 1.14]]]) + partition_index = [[0,1],[0,1],[2,4]] + + _merge_parameter(partition_param_list, param, partition_index) + # partition_param_list: [(np.array([[[1.11, 1.12, 1.13, 1.14]]]), [[0,1],[0,1],[0,4]])] + """ + from .reshard import Resharder + + if len(partition_param_list) == 1: + is_complete_data = True + for idx, item in enumerate(partition_param_list[0][1]): + if item[0] != 0 or item[1] != complete_shape[idx]: + is_complete_data = False + break + if is_complete_data: + return + + if not partition_param_list: + partition_param_list.append((param, partition_index)) + else: + i = 0 + while i < len(partition_param_list): + ( + concat_axis, + first_order, + new_partition, + ) = Resharder.compute_concat_info( + partition_param_list[i][1], partition_index + ) + if concat_axis != -1: + if first_order == 0: + new_param = np.concatenate( + (partition_param_list[i][0], param), axis=concat_axis + ) + else: + new_param = np.concatenate( + (param, partition_param_list[i][0]), axis=concat_axis + ) + + partition_param_list.pop(i) + _merge_parameter( + partition_param_list, + new_param, + new_partition, + complete_shape, + ) + break + i += 1 + + +def _slice_parameter(complete_param, partition_index_list, length): + """ + Slice a complete parameter. + + Returns: + sliced_param_list(list): sliced parameters with 'partition_index_list' + + Examples: + .. code-block:: python + + import numpy as np + complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + rank = 2 + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + sliced_param_list = _slice_parameter(complete_param, [[], [], [2, 4]], 3) + # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])] + """ + sliced_param_list = [] + axis = len(complete_param.shape) - length + sliced_param = np.split( + complete_param, partition_index_list[axis], axis=axis + ) + if length == 1: + return sliced_param + for param in sliced_param: + sliced_param_list.extend( + _slice_parameter(param, partition_index_list, length - 1) + ) + return sliced_param_list + + +def _get_sliced_param_index( + rank, complete_shape, dims_mapping, process_shape, process_group +): + """ + Get sliced_param's index of current rank in all sliced parameters list. + + Returns: + sliced_param_index(int): the index of sliced param in sliced_param_list + + Examples: + .. code-block:: python + + import numpy as np + complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + rank = 2 + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + slice_param = _slice_parameter(complete_param, [[], [], [2, 4]], 3) + # slice_param: + # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])] + + index = _get_sliced_param_index(rank, complete_shape, dims_mapping + process_shape, process_group) + # index: 2 + """ + from .reshard import Resharder + + partition_index = Resharder.compute_partition_index( + rank, complete_shape, dims_mapping, process_shape, process_group + ) + sliced_param_index = 0 + for i, shape in enumerate(complete_shape): + if dims_mapping[i] == -1: + slice_shape = shape + else: + slice_shape = shape // process_shape[dims_mapping[i]] + if slice_shape == 1: + index = partition_index[i][0] + else: + index = (partition_index[i][0] + 1) // slice_shape + sliced_param_index = sliced_param_index * (shape // slice_shape) + index + return sliced_param_index + + +def _get_split_indices( + complete_shape, dims_mapping, process_shape, process_group +): + """ + Get split indices of every dimension. + + Returns: + split_indices_list(list): the split indices of every dimension of the parameter + + Examples: + .. code-block:: python + + import numpy as np + complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]]) + complete_shape = [1, 1, 6] + dims_mapping = [-1, -1, 0] + process_shape = [3] + process_group = [0, 1, 2] + + index = _get_split_indices(complete_shape, dims_mapping, process_shape, process_group) + # index: [[], [], [2, 4]] + """ + from .reshard import Resharder + + split_indices_list = [] + for process in process_group: + partition_index = Resharder.compute_partition_index( + process, complete_shape, dims_mapping, process_shape, process_group + ) + if split_indices_list: + for dim in range(len(partition_index)): + split_indices_list[dim].extend(partition_index[dim]) + else: + split_indices_list = partition_index + split_indices_list = list( + map( + lambda x, y: list(set(x) - set([y]) - set([0])), + split_indices_list, + complete_shape, + ) + ) + split_indices_list = [sorted(x) for x in split_indices_list] + return split_indices_list + + +def set_grad_var_shape(program, dist_context): + from .operators.common import infer_shape + from paddle.distributed.fleet.meta_optimizers.common import OpRole + + block = program.global_block() + vars = block.vars + appended_grad_times = 0 + grad_var_to_var = dist_context.dist_op_context.grad_var_to_var + + for idx, op in enumerate(block.ops): + + if int(op.attr('op_role')) != int(OpRole.Backward): + continue + + if ( + int(block.ops[idx - 1].attr('op_role')) == int(OpRole.Forward) + or int(block.ops[idx - 1].attr('op_role')) == 257 + ): + appended_grad_times += 1 + + if op.type in ["check_finite_and_unscale", "update_loss_scaling"]: + break + + if op.type in ["sum", "concat", "shape"]: + continue + + op_dist_attr = dist_context.get_op_dist_attr_for_program(op) + assert op_dist_attr is not None + + for var_name in op.output_arg_names: + + if "@GRAD" not in var_name: + continue + if var_name in grad_var_to_var[appended_grad_times]: + forward_var_name = grad_var_to_var[appended_grad_times][ + var_name + ] + else: + forward_var_name = var_name[: var_name.find("@GRAD")] + + if op.type in [ + "c_allreduce_sum", + "c_identity", + "scale", + "cast", + "fill_any_like", + ]: + forward_var_name = op.input_arg_names[0] + elif ( + op.type == "matmul_v2_grad" + or op.type == "matmul_grad" + or op.type == "mul_grad" + ): + forward_var_name = None + for output_name in op.output_names: + if var_name in op.output(output_name): + assert "@GRAD" in output_name + input_name = output_name[: output_name.find("@GRAD")] + assert len(op.input(input_name)) == 1 + forward_var_name = op.input(input_name)[0] + assert forward_var_name is not None + + need_set_shape_list = [ + "reshape2_grad", + "softmax_with_cross_entropy_grad", + "transpose2_grad", + "softmax_grad", + "cross_entropy_grad2", + "dropout_grad", + "tanh_grad", + "slice", + "assign", + "matmul_v2_triple_grad", + "elementwise_add_triple_grad", + "fill_constant", + "sqrt_grad", + "fused_softmax_mask_upper_triangle_grad", + "flatten_contiguous_range_grad", + "relu_grad", + ] + forward_list = [ + "reshape2", + "softmax_with_cross_entropy", + "transpose2", + "softmax", + "cross_entropy2", + "dropout", + "tanh", + ["slice_grad", "c_allgather"], + "assign", + "matmul_v2_grad_grad", + "elementwise_add_grad_grad", + "shape", + "sqrt", + "fused_softmax_mask_upper_triangle", + "flatten_contiguous_range", + "relu", + ] + if op.type in need_set_shape_list: + for forward_op in block.ops: + idx = need_set_shape_list.index(op.type) + forward_op_name = forward_list[idx] + if ( + forward_op.type in forward_op_name + and forward_var_name in forward_op.input_arg_names + ): + op_dist_attr = ( + dist_context.get_op_dist_attr_for_program( + forward_op + ) + ) + break + + forward_input_dist_attr = op_dist_attr.get_input_dist_attr( + forward_var_name + ) + assert ( + forward_input_dist_attr is not None + ), f"{forward_var_name, str(op)}" + forward_var = vars[forward_var_name] + forward_var_dist_attr = ( + dist_context.get_tensor_dist_attr_for_program(forward_var) + ) + assert forward_var_dist_attr is not None + grad_var = vars[var_name] + ref_shape = infer_shape( + block, + forward_var, + forward_var_dist_attr, + forward_input_dist_attr, + ) + + if list(grad_var.shape) != ref_shape: + grad_var.desc.set_shape(ref_shape) + + +OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() +OpRole = core.op_proto_and_checker_maker.OpRole + + +def is_forward_op(op): + op_role = int(op.attr('op_role')) + return OP_ROLE_KEY in op.attr_names and ( + op_role == int(OpRole.Forward) or op_role == int(OpRole.Loss) + ) + + +def is_backward_op(op): + return OP_ROLE_KEY in op.attr_names and int( + op.all_attrs()[OP_ROLE_KEY] + ) & int(OpRole.Backward) + + +def is_optimize_op(op): + return OP_ROLE_KEY in op.attr_names and int( + op.all_attrs()[OP_ROLE_KEY] + ) & int(OpRole.Optimize) + + +def is_lr_sched_op(op): + return OP_ROLE_KEY in op.attr_names and int( + op.all_attrs()[OP_ROLE_KEY] + ) & int(OpRole.Optimize.LRSched) + + +def is_loss_op(op): + return OP_ROLE_KEY in op.attr_names and int( + op.all_attrs()[OP_ROLE_KEY] + ) == (int(OpRole.Forward) | int(OpRole.Loss)) + + +def is_loss_grad_op(op): + if OP_ROLE_KEY not in op.attr_names: + return False + op_role = int(op.all_attrs()[OP_ROLE_KEY]) + return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss) + + +def is_gradient_clip_op(op): + return op.desc.has_attr("op_namescope") and op.desc.attr( + "op_namescope" + ).startswith("/gradient_clip") + + +def is_prim_op(op): + return op.type.endswith("_p") + + +def get_loss_op(block): + loss_ops = [] + for op in block.ops: + if is_loss_op(op): + assert ( + len(op.desc.output_arg_names()) == 1 + ), "loss op should only output loss var" + loss_ops.append(op) + + assert len(loss_ops) == 1, "num of loss op is not equal to one" + return loss_ops[0] + + +def set_var_dist_attr(dist_context, var, dims_mapping, process_mesh, **kwargs): + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.dims_mapping = dims_mapping + # TODO get global mesh group + tensor_dist_attr.process_mesh = process_mesh + if "mark_annotated" in kwargs and kwargs["mark_annotated"]: + tensor_dist_attr.mark_annotated("dims_mapping") + tensor_dist_attr.mark_annotated("process_mesh") + dist_context.set_tensor_dist_attr_for_program(var, tensor_dist_attr) + return tensor_dist_attr + + +def naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, process_mesh, ref_mapping, ctx +): + assert process_mesh is not None + assert ref_mapping is not None + + new_op_dist_attr = OperatorDistributedAttribute() + + for input_varname in new_op.desc.input_arg_names(): + new_op_dist_attr.set_input_dims_mapping(input_varname, ref_mapping) + for output_varname in new_op.desc.output_arg_names(): + new_op_dist_attr.set_output_dims_mapping(output_varname, ref_mapping) + + new_op_dist_attr.process_mesh = process_mesh + ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + + +def update_op_dims_mapping_by_default_dist_impl(dist_op): + changed = False + op_dist_attr = dist_op.dist_attr + op_desc = dist_op.serial_op.desc + # The following statement will be replaced by a more elegent way + if op_desc.type() == "shape" or op_desc.type() == "slice": + return False + output_names = op_desc.output_names() + xshape_arg_names = [] + if "XShape" in output_names: + xshape_arg_names = op_desc.output("XShape") + batch_dim_mappings = [] + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if len(dims_mapping) > 1: + for idx, mapping in enumerate(dims_mapping[1:]): + assert ( + mapping == -1 + ), "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part.".format( + op_desc.type(), idx, mapping + ) + batch_dim_mappings.append(dims_mapping[0]) + for arg_name in op_desc.output_arg_names(): + serial_tensor = dist_op.get_serial_output(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if arg_name not in xshape_arg_names: + if len(dims_mapping) > 1: + for idx, mapping in enumerate(dims_mapping[1:]): + assert ( + mapping == -1 + ), "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part.".format( + op_desc.type(), idx, mapping + ) + batch_dim_mappings.append(dims_mapping[0]) + else: + assert ( + dims_mapping[0] == -1 + ), "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension 0 is sharded by {} part.".format( + op_desc.type(), mapping + ) + if len(dims_mapping) > 2: + for idx, mapping in enumerate(dims_mapping[2:]): + assert ( + mapping == -1 + ), "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension {} is sharded by {} part.".format( + op_desc.type(), idx, mapping + ) + batch_dim_mappings.append(dims_mapping[1]) + + compatible_dim_mapping = compute_compatible_dim_mapping(batch_dim_mappings) + assert ( + compatible_dim_mapping is not None + ), "There is no compatible dim mapping." + for arg_name in op_desc.input_arg_names(): + serial_tensor = dist_op.get_serial_input(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + for arg_name in op_desc.output_arg_names(): + serial_tensor = dist_op.get_serial_output(arg_name) + if serial_tensor.is_parameter: + continue + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if arg_name not in xshape_arg_names: + if compatible_dim_mapping != dims_mapping[0]: + dims_mapping[0] = compatible_dim_mapping + changed = True + else: + if compatible_dim_mapping != dims_mapping[1]: + dims_mapping[1] = compatible_dim_mapping + changed = True + + return changed + + +def update_op_dims_mapping_by_elementwise_like_dist_impl(dist_op): + changed = False + op_dist_attr = dist_op.dist_attr + op_desc = dist_op.serial_op.desc + input_arg_names = op_desc.input_arg_names() + input_dims_mapping_dict = {} + input_dims_mapping_lens = {} + max_dims_mapping_len = -1 + for arg_name in input_arg_names: + dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name) + if max_dims_mapping_len < len(dims_mapping): + max_dims_mapping_len = len(dims_mapping) + input_dims_mapping_dict[arg_name] = dims_mapping + input_dims_mapping_lens[arg_name] = len(dims_mapping) + + dims_mapping_list = [] + for arg_name in input_arg_names: + if input_dims_mapping_lens[arg_name] < max_dims_mapping_len: + new_dims_mapping = [-1 for _ in range(max_dims_mapping_len)] + for i in range(input_dims_mapping_lens[arg_name]): + new_idx = ( + max_dims_mapping_len - input_dims_mapping_lens[arg_name] + ) + i + new_dims_mapping[new_idx] = input_dims_mapping_dict[arg_name][i] + dims_mapping_list.append(new_dims_mapping) + else: + dims_mapping_list.append(input_dims_mapping_dict[arg_name]) + output_arg_names = op_desc.output_arg_names() + for arg_name in output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + assert len(dims_mapping) == max_dims_mapping_len + dims_mapping_list.append(dims_mapping) + + compatible_dims_mapping = compute_compatible_dims_mapping(dims_mapping_list) + assert ( + compatible_dims_mapping is not None + ), "There is no compatible dim mapping." + + for arg_name in input_arg_names: + if input_dims_mapping_lens[arg_name] < max_dims_mapping_len: + new_dims_mapping = [ + -1 for _ in range(input_dims_mapping_lens[arg_name]) + ] + for i in range(input_dims_mapping_lens[arg_name]): + new_idx = ( + max_dims_mapping_len - input_dims_mapping_lens[arg_name] + ) + i + new_dims_mapping[i] = compatible_dims_mapping[new_idx] + if new_dims_mapping != input_dims_mapping_dict[arg_name]: + op_dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping) + changed = True + else: + if compatible_dims_mapping != input_dims_mapping_dict[arg_name]: + op_dist_attr.set_input_dims_mapping( + arg_name, compatible_dims_mapping + ) + changed = True + + for arg_name in output_arg_names: + dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name) + if compatible_dims_mapping != dims_mapping: + op_dist_attr.set_output_dims_mapping( + arg_name, compatible_dims_mapping + ) + changed = True + + return changed + + +def get_all_distributed_main_program( + serial_program_info, dist_context, parallelizer +): + "Get all distributed main programs by dist_context." + from .dist_context import DistributedOperatorContext, DistributedContext + + cluster = serial_program_info.cluster + copied_parallelizer = copy.deepcopy(parallelizer) + all_dist_main_program = [] + ranks = ( + paddle.distributed.get_world_size() + if cluster is None + else len(cluster.get_all_devices("GPU")) + ) + for rank_id in range(ranks): + used_dist_context = copy.deepcopy(dist_context) + used_dist_context._dist_op_context = DistributedOperatorContext() + ( + _, + _, + dist_startup_program, + dist_main_program, + _, + ) = copied_parallelizer._get_dist_program(rank_id, used_dist_context) + all_dist_main_program.append(dist_main_program) + + return all_dist_main_program + + +class SerialProgramInfo: + def __init__( + self, train_program, satrtup_program, loss, optimizer, cluster=None + ): + self._train_program = train_program + self._startup_program = satrtup_program + self._loss = loss + self._optimizer = optimizer + self._cluster = cluster + + @property + def train_program(self): + return self._train_program + + @property + def startup_program(self): + return self._startup_program + + @property + def loss(self): + return self._loss + + @property + def optimizer(self): + return self._optimizer + + @property + def cluster(self): + return self._cluster + + +def get_standalone_cost_data(distributed_programs): + def _compute_runtime(op_cost, op, vars): + runtime = 0 + try: + runtime = float(op_cost["op_time"]) + except: + return runtime + op_config = op_cost["config"] + total_static_input_size = 0 + total_actual_input_size = 0 + parsed_info = op_config.split("\n") + variable = "(Variable)" + for info in parsed_info: + variable = ( + "(Variable)" if "(Variable)" in info else "(list" + ) + if variable in info: + arg_name_lower = info[: info.find(variable) - 1] + shape_left_boundary = info.find("[") + shape_right_boundary = info.find("]") + assert ( + shape_left_boundary > 0 + and shape_right_boundary > 0 + and shape_right_boundary > shape_left_boundary + ), "Get shape failed." + shape = info[ + shape_left_boundary + 1 : shape_right_boundary + ].split(",") + shape = list(map(lambda x: int(x.strip()), shape)) + dtype_factor = 1 + total_static_input_size += reduce(lambda x, y: x * y, shape) + if op.type == "c_embedding": + arg_name_lower = ( + "w" if arg_name_lower == "weight" else "ids" + ) + for arg_name in op.input_names: + if arg_name.lower() == arg_name_lower: + for var_name in op.input(arg_name): + var = vars[var_name] + total_actual_input_size += reduce( + lambda x, y: x * y, var.shape + ) + break + assert ( + total_static_input_size > 0 and total_actual_input_size > 0 + ), "Get input size failed." + + actual_runtime = ( + total_actual_input_size / total_static_input_size * runtime + ) + return actual_runtime + + import paddle.cost_model as cm + + cost_model = cm.CostModel() + cost_model.static_cost_data() + DEFAULT_MULTIPLE = 2 + OP_NAME_MAPPING = { + "c_embedding": "embedding", + "matmul_v2": "matmul", + "transpose2": "transpose", + "reshape2": "reshape", + "unsqueeze2": "unsqueeze", + "reduce_sum": "sum", + "elementwise_div": "divide", + } + + standalone_cost_data = [] + # skip ops + not_enum_ops = [ + "create_py_reader", + "create_double_buffer_reader", + "read", + "assign", + ] + for distributed_program in distributed_programs: + cost_data = {} + vars = distributed_program.global_block().vars + for op in distributed_program.global_block().ops: + runtime = 0 + if op.type in not_enum_ops: + cost_data[op.desc.id()] = runtime + continue + dtype = ( + str(vars[op.input_arg_names[0]].dtype) + if op.input_arg_names + else "float32" + ) + if int(op.attr('op_role')) == int(OpRole.Backward): + if "_grad" in op.type: + forward_op_name = op.type[:-5] + if forward_op_name in OP_NAME_MAPPING.keys(): + forward_op_name = OP_NAME_MAPPING[forward_op_name] + op_cost = cost_model.get_static_op_time( + forward_op_name, forward=False, dtype=dtype + ) + if op_cost: + runtime = _compute_runtime(op_cost, op, vars) + else: + op_cost = cost_model.get_static_op_time( + forward_op_name, dtype=dtype + ) + if op_cost: + runtime = 2 * _compute_runtime(op_cost, op, vars) + elif int(op.attr('op_role')) == int(OpRole.Forward): + op_name = ( + OP_NAME_MAPPING[op.type] + if op.type in OP_NAME_MAPPING.keys() + else op.type + ) + op_cost = cost_model.get_static_op_time(op_name) + if op_cost: + runtime = _compute_runtime(op_cost, op, vars) + + cost_data[op.desc.id()] = runtime + + standalone_cost_data.append(cost_data) + + return standalone_cost_data + + +def set_dist_op_desc_original_id(dist_op_desc, op_desc, dist_context): + op_id = op_desc.id() + op_original_id = op_desc.original_id() + # First, try to set the original id to the id of the op_desc + if op_id in dist_context._dist_ops_for_program: + dist_op_desc.set_original_id(op_id) + return + # Second, try to set the original id to the original_id of the op_desc + elif op_original_id in dist_context._dist_ops_for_program: + dist_op_desc.set_original_id(op_original_id) + return + # Third, print error infomation if we cannot find the original id + else: + assert False, "Cannot find the original id in the distributed context" + + +def to_list(value): + if value is None: + return value + if isinstance(value, (list, tuple)): + return list(value) + return [value] + + +def debug_program(program, path, name): + + filename = os.path.join( + path, name + '_program' + ".%d" % (paddle.distributed.get_rank()) + ) + with open(filename, 'w') as f: + f.write(str(program)) + + +def ring_id_to_process_group(ring_id): + for g in get_all_process_groups(): + if g.id == ring_id: + return g + return None + + +def find_higher_order_backward_op(program): + + higher_order_op_suffix = ['_grad_grad', 'triple_grad'] + for block in program.blocks: + for op in block.ops: + for suffix in higher_order_op_suffix: + if suffix in op.type: + return True + + return False + + +def get_lr(optimizer): + if isinstance(optimizer, paddle.optimizer.Optimizer): + return optimizer.get_lr() + elif isinstance(optimizer, paddle.fluid.optimizer.Optimizer): + if isinstance(optimizer._learning_rate, float): + return optimizer._learning_rate + else: + return optimizer._learning_rate() + else: + raise TypeError( + "'optimizer' must be object of class `paddle.optimizer.Optimizer`" + " or `paddle.fluid.optimizer.Optimizer`, but got {}.".format( + type(optimizer) + ) + ) + + +def initialize_pg_in_full_mode(all_process_groups, cur_rank): + import socket + from ..collective import _get_global_env + + has_recv_by_socket = [] + # This is a magic number + magic_num = 500 + genv = _get_global_env() + cur_rank_ip, cur_rank_port = genv.current_endpoint.split(":") + cur_rank_recv_port = int(cur_rank_port) + magic_num + server_socket = None + # Large enough for recv rank + buff_size = 1024 + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_socket.bind((cur_rank_ip, cur_rank_recv_port)) + # The 10 is an empirical value + server_socket.listen(10) + client_sockets = {} + for process_group in all_process_groups: + if cur_rank not in process_group.ranks: + continue + if len(process_group.ranks) == 2: + index = process_group.ranks.index(cur_rank) + is_send = True if index == 0 else False + if is_send: + recv_rank = process_group.ranks[1] + recv_rank_ip, recv_rank_port = genv.trainer_endpoints[ + recv_rank + ].split(":") + connect_port = int(recv_rank_port) + magic_num + client_socket = socket.socket( + socket.AF_INET, socket.SOCK_STREAM + ) + client_socket.connect((recv_rank_ip, connect_port)) + client_socket.send(str(cur_rank).encode('utf-8')) + rank = client_socket.recv(buff_size).decode('utf-8') + rank = int(rank) + if rank != recv_rank: + raise ValueError( + "Please check comm pair, the recv rank should be {} but got {}.".format( + recv_rank, rank + ) + ) + else: + print( + "It is able to instantiate {} as sender now.".format( + process_group.ranks + ) + ) + client_socket.close() + else: + send_rank = process_group.ranks[0] + while True: + if send_rank not in has_recv_by_socket: + client_socket, recv_addr = server_socket.accept() + rank = int(client_socket.recv(buff_size).decode()) + client_sockets[rank] = client_socket + has_recv_by_socket.append(rank) + else: + client_sockets[send_rank].send( + str(cur_rank).encode("utf-8") + ) + client_sockets[send_rank].close() + print( + "It is able to instantiate {} as recver now.".format( + process_group.ranks + ) + ) + break + process_group.instantiate() + server_socket.close() + + +def get_input_split_info(cur_rank, var, dist_context): + # deduce how the input data is split among the cluster + tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(var) + process_mesh = tensor_dist_attr.process_mesh + dims_mapping = tensor_dist_attr.dims_mapping + + if cur_rank not in process_mesh.processes: + rank_id = _get_corresponding_rank(dist_context, process_mesh, cur_rank) + else: + rank_id = cur_rank + + batch_size_axis = dims_mapping[0] + if batch_size_axis > -1 and process_mesh.topology[batch_size_axis] > 1: + group_ranks = _get_comm_group( + process_mesh.processes, + process_mesh.topology, + batch_size_axis, + rank_id, + ) + return len(group_ranks), group_ranks.index(rank_id) + + return 1, 0 + + +def validate_opt(optimizer): + if optimizer is not None: + optimizer._parameter_list = None + optimizer._param_groups = None + return optimizer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/cloud_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/cloud_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..651298d6d766f62ac729f253c20c5fb537953e74 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/cloud_utils.py @@ -0,0 +1,123 @@ +# 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. + +import os +import paddle +from paddle.distributed.utils.launch_utils import get_cluster, get_gpus, get_cluster_from_args +from paddle.distributed.utils.launch_utils import logger + +__all__ = [] + + +def get_cloud_cluster(args_node_ips, args_node_ip, args_port, selected_devices): + """ + args_node_ips:string, args_node_ip:string, args_port: int, selected_devices:list + """ + #you can automatically get ip info while using paddlecloud multi nodes mode. + node_ips = os.getenv("PADDLE_TRAINERS") + assert node_ips is not None, "PADDLE_TRAINERS should not be None" + + node_ip = os.getenv("POD_IP") + assert node_ip is not None, "POD_IP should not be None" + + node_rank = os.getenv("PADDLE_TRAINER_ID") + assert node_rank is not None, "PADDLE_TRAINER_ID should not be None" + + paddle_ports_num = int(os.getenv("TRAINER_PORTS_NUM")) + assert paddle_ports_num is not None, "TRAINER_PORTS_NUM should not be None" + + node_ips = node_ips.split(",") + num_nodes = len(node_ips) + node_rank = int(node_rank) + + if node_ip != "127.0.0.1" and node_ip != args_node_ip: + logger.warning("Please NOTE: When using paddlecloud, node_ip is \ +automatically got from POD_IP. Your input node_ip: {} doesn't equals to \ +node_ip: {} from paddlecloud environment.".format(args_node_ip, node_ip)) + + if args_node_ips != "127.0.0.1" and args_node_ips != ",".join(node_ips): + logger.warning( + "Please NOTE: When using paddlecloud, cluster_node_ips is \ +automatically got from PADDLE_TRAINERS(multi nodes) or POD_IP(single node).\ +Your input cluster_node_ips: {} doesn't equals to IPs: {} from \ +paddlecloud environment.".format(args_node_ips, node_ips)) + + # DISTRIBUTED_TRAINER_ENDPOINTS: new environment since paddlecloud 1.8.4 + # e.g: DISTRIBUTED_TRAINER_ENDPOINTS="ip1:port1,ip1:port2,ip1:port3,ip1:port4,ip2:port5,ip2:port6,ip2:port7,ip2:port8" + trainer_endpoints = os.getenv("DISTRIBUTED_TRAINER_ENDPOINTS") + if trainer_endpoints is None: + started_port = args_port + if num_nodes > 1: + try: + paddle_port = int(os.getenv("PADDLE_PORT", "")) + + if paddle_ports_num >= len( + selected_devices) and paddle_port != args_port: + logger.warning( + "Use Cloud specified port:{}.".format(paddle_port)) + started_port = paddle_port + + except Exception as e: + print(e) + pass + + if started_port is None: + started_port = 6170 + ports = [ + x for x in range(started_port, started_port + len(selected_devices)) + ] + trainer_endpoints = [] + for ip in node_ips: + trainer_endpoints.append(["%s:%d" % (ip, port) for port in ports]) + else: + trainer_endpoints_ori = trainer_endpoints.split(",") + trainer_endpoints = [] + assert num_nodes * paddle_ports_num == len(trainer_endpoints_ori) + for i in range(num_nodes): + trainer_endpoints.append( + trainer_endpoints_ori[i * paddle_ports_num:(i + 1) * + paddle_ports_num]) + + logger.debug("parsed from args: node_ips:{} \ + node_ip:{} node_rank:{} trainer_endpoints:{}".format( + node_ips, node_ip, node_rank, trainer_endpoints)) + + cluster, pod = get_cluster(node_ips, node_ip, trainer_endpoints, + selected_devices) + return cluster, cluster.pods[node_rank] + + +def _get_trainers_num(): + return int(os.getenv("PADDLE_TRAINERS_NUM", "1")) + + +def get_cluster_and_pod(args): + # parse arguments, used for cloud-single-machine and local + selected_devices = get_gpus(args.selected_devices) + trainers_num = _get_trainers_num() + logger.debug("parsed from args trainerss_num:{} selected_devices:{}".format( + trainers_num, selected_devices)) + + cluster = None + pod = None + + if args.use_paddlecloud and trainers_num != 1: + cluster, pod = get_cloud_cluster(args.cluster_node_ips, args.node_ip, + args.started_port, selected_devices) + logger.info("get cluster from cloud:{}".format(cluster)) + else: + cluster, pod = get_cluster_from_args(args, selected_devices) + logger.info("get cluster from args:{}".format(cluster)) + + return cluster, pod diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/collective.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e972c4d02792a443c250364a19b4bdde23afca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/collective.py @@ -0,0 +1,1978 @@ +# 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. + +import numpy as np +import os +import pickle +import io +import datetime +import time +from ..fluid.layer_helper import LayerHelper +from ..fluid.framework import Variable +from ..fluid.framework import in_dygraph_mode +from ..fluid.framework import OpProtoHolder +from ..fluid.framework import _non_static_mode +from ..fluid.framework import _in_legacy_dygraph +from ..fluid.framework import convert_np_dtype_to_dtype_ +from ..fluid.framework import _varbase_creator +from ..fluid.data_feeder import convert_dtype +from ..fluid.data_feeder import check_variable_and_dtype +from ..fluid.data_feeder import check_type +from ..fluid.data_feeder import check_dtype +from ..fluid.layers.tensor import fill_constant +from ..fluid.layers import utils +from ..fluid.dygraph import layers +from ..fluid.dygraph.parallel import prepare_context +import paddle +import paddle.fluid as fluid +import paddle.fluid.core as core +from paddle import _C_ops, _legacy_C_ops +import paddle.fluid.dygraph_utils as dygraph_utils +import contextlib +from .fleet.layers.mpu.mp_ops import split +from .fleet.layers.mpu.mp_ops import _c_identity +from .fleet.layers.mpu.mp_ops import _c_concat +from .fleet.layers.mpu.mp_ops import _c_split +from .fleet.layers.mpu.mp_ops import _mp_allreduce +from .fleet.layers.mpu.mp_ops import _c_lookup_table +from .fleet.layers.mpu.mp_ops import _Linear +from .fleet.layers.mpu.mp_ops import _set_var_distributed +from .fleet.layers.mpu.mp_ops import _c_softmax_with_cross_entropy +from .fleet.layers.mpu.mp_ops import _linear +from .fleet.layers.mpu.mp_ops import _parallel_linear +from .fleet.layers.mpu.mp_ops import _parallel_embedding +from .communication.group import Group, _add_new_group +from .communication.all_reduce import all_reduce +from .communication.reduce import _get_reduce_op, ReduceOp + +__all__ = [] + +_global_env = None + + +def _get_global_env(): + global _global_env + if not _global_env: + _global_env = paddle.distributed.ParallelEnv() + return _global_env + + +# group map : the map of all group, 0 for GlobalGroup +# Dict[int, Group] +_group_map = {} +_global_env_gid = 0 + +# group map by name : the map of all groups from their names +# Dict[name, Group] +_group_map_by_name = {} + +# backend map by group : the map of all backend from their groups +# Dict[group, backend] +_group_map_backend = {} + +# Name of the default group for init_parallel_env +_default_group_name = "_default_pg" + +_valid_backend_list = ['nccl', 'gloo', 'hccl', 'heter', 'xccl'] +_default_store = None # the default tcp store +_default_backend = None +_default_timeout = datetime.timedelta(seconds=1800) +_start_ring_id = 0 + + +def _set_default_backend(backend): + global _default_backend + _default_backend = backend + + +def _set_default_store(store): + global _default_store + _default_store = store + + +def _get_group_map(): + global _group_map + if _global_env_gid not in _group_map: + genv = _get_global_env() + _group_map[_global_env_gid] = Group( + genv.rank, 0, list(range(genv.world_size)) + ) + return _group_map + + +def _get_global_group(): + return _get_group_map()[_global_env_gid] + + +def _get_group_map_by_name(): + global _group_map_by_name + return _group_map_by_name + + +def _get_default_group(): + global _group_map_by_name + assert is_initialized(), ( + "Call paddle.distributed.init_parallel_env first " + "to initialize the distributed environment." + ) + return _get_group_map_by_name()[_default_group_name] + + +def _set_group_map(gid, group): + global _group_map + assert gid not in _group_map + _group_map[gid] = group + + +def _set_group_map_by_name(name, group): + global _group_map_by_name + assert name not in _group_map_by_name + _group_map_by_name[name] = group + + +def _set_group_map_backend(group, backend): + global _group_map_backend + assert group not in _group_map_backend + _group_map_backend[group] = backend + + +def _new_ring_id(): + # NOTE(liyurui): For compatible reason, auto parallel and eager mode relay on previous syntax. + if in_dygraph_mode(): + global _start_ring_id + _start_ring_id += 1 + return _start_ring_id + max(_get_global_env().nrings, 9) + else: + return len(_get_group_map()) + max(_get_global_env().nrings, 9) + + +def get_group(id=0): + """ + + Get group instance by group id. + + Args: + id (int): the group id. Default value is 0. + + Returns: + Group: the group instance. + + Examples: + .. code-block:: python + + ... + gid = paddle.distributed.new_group([2,4,6]) + paddle.distributed.get_group(gid.id) + + """ + + gm = _get_group_map() + return gm[id] if id in gm else None + + +def _new_process_group_impl( + backend, + store, + rank, + world_size, + group_name, + pg_options, + group_id=0, + src_rank=None, + dst_rank=None, +): + pg = None + genv = _get_global_env() + if backend != 'heter': + assert src_rank is None and dst_rank is None, ( + "src_rank and dst_rank " "can only be set for heter backend." + ) + assert backend in _valid_backend_list, "Unsupported backend: %s." % backend + if backend == "gloo": + place = core.CPUPlace() + pg = core.ProcessGroupGloo(store, rank, world_size, place, group_id) + elif backend == "nccl": + place = core.CUDAPlace(genv.device_id) + pg = core.ProcessGroupNCCL(store, rank, world_size, place, group_id) + elif backend == "hccl": + place = core.NPUPlace(genv.device_id) + pg = core.ProcessGroupHCCL(store, rank, world_size, place, group_id) + elif backend == "xccl": + place = core.CustomPlace(genv.device_type, genv.device_id) + pg = core.ProcessGroupCustom(store, rank, world_size, place, group_id) + elif backend == "heter": + place = None + if core.is_compiled_with_cuda(): + place = core.CUDAPlace(genv.device_id) + elif core.is_compiled_with_npu(): + place = core.NPUPlace(genv.device_id) + cluster_id = int(os.getenv("CLUSTER_ID", "-1")) + assert cluster_id >= 0, "please set the CLUSTER_ID variable." + cluster_size = os.getenv("CLUSTER_SIZE", None) + assert cluster_size, "please set the CLUSTER_SIZE variable." + cluster_size = cluster_size.split(",") + cluster_size = [int(s) for s in cluster_size] + switch_ep = os.getenv("CLUSTER_SWITCH", None) + assert switch_ep, "please set the CLUSTER_SWITCH variable." + cluster_size_cumsum = np.cumsum(cluster_size) + cluster_offset = ( + 0 if cluster_id == 0 else cluster_size_cumsum[cluster_id - 1] + ) + global_rank = cluster_offset + rank + global_world_size = cluster_size_cumsum[-1] + global_rank, global_world_size = _get_global_config(backend, rank) + pg = core.ProcessGroupHeter( + store, + rank=global_rank, + world_size=global_world_size, + place=place, + gid=group_id, + local_rank=rank, + local_size=world_size, + gloo_rank=cluster_id, + gloo_size=len(cluster_size), + with_switch=True, + switch_endpoint=switch_ep, + src_rank=src_rank, + dst_rank=dst_rank, + ) + + return pg + + +def barrier(group=None): + """ + + Barrier among all participators in the group. + + Args: + group (Group): The group instance return by new_group or None for global default group. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed import init_parallel_env + + paddle.set_device('gpu:%d'%paddle.distributed.ParallelEnv().dev_id) + init_parallel_env() + paddle.distributed.barrier() + """ + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + task = group.process_group.barrier() + task.wait() + return + + ring_id = 0 if group is None else group.id + + temp = fill_constant([1], dtype="int32", value="1") + if _non_static_mode(): + return _legacy_C_ops.barrier(temp, temp, 'ring_id', ring_id) + + op_type = 'barrier' + + if not isinstance(ring_id, int): + raise ValueError("The type of 'group' for barrier must be int.") + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [temp]}, + outputs={'Out': [temp]}, + attrs={'ring_id': ring_id}, + ) + + +# _custom_gid provides a way for users to +# set the group id, which is usually useful +# to be compatible with the static mode. +_custom_gid = None + + +def _set_custom_gid(gid): + global _custom_gid + _custom_gid = gid + + +def _barrier_by_tcp_store(group_name, store, timeout): + global_rank = paddle.distributed.get_rank() + global_world_size = paddle.distributed.get_world_size() + + if global_world_size < 2: + return + + barrier_prefix = "Barrier/" + group_name + "/" + is_master = global_rank == 0 + + def _check_keys_ready(wait_keys): + start_time = time.time() + while len(wait_keys) > 0: + time.sleep(0.1) + elapse_time = time.time() - start_time + if datetime.timedelta(seconds=elapse_time) > timeout: + raise RuntimeError( + "Timeout while initializing process group {}." + "Keys {} are not ready sinck rank {} is waiting them." + "Two reason may cause this error:\n 1. The create process group api should be called by all ranks.\n" + " 2. Try to increase the waiting time.\n".format( + group_name, wait_keys, global_rank + ) + ) + wait_keys = list( + filter(lambda key: int(store.get(key)) != 1, wait_keys) + ) + + # all the workers set their exiting key and exit + # the master will wait for all workers' exiting key, ensure to exit in the end + if is_master: + wait_keys = [ + barrier_prefix + str(rank) for rank in range(1, global_world_size) + ] + _check_keys_ready(wait_keys) + else: + store.add(barrier_prefix + str(global_rank), 1) + + +def new_group(ranks=None, backend=None, timeout=_default_timeout): + """ + + Creates a new distributed communication group. + + Args: + ranks (list): The global ranks of group members. + backend (str): The backend used to create group, only nccl is supported now. + timeout (datetime.timedelta, optional): The waiting timeout for store relevant options, default is 30 minutes. + + Returns: + Group: The group instance. + + Examples: + .. code-block:: python + + import paddle + + paddle.distributed.init_parallel_env() + tindata = paddle.randn(shape=[2, 3]) + gp = paddle.distributed.new_group([2,4,6]) + paddle.distributed.all_reduce(tindata, group=gp, sync_op=False) + + """ + global _custom_gid + global _group_map + if in_dygraph_mode(): + global _default_group_name + gid = _custom_gid if _custom_gid else _new_ring_id() + group_name = _default_group_name + str(gid) + if backend != 'heter' and (ranks is None or len(ranks) > 1): + global_group = _get_default_group() + global_rank = global_group.rank + global_ranks = global_group.ranks + backend = _default_backend if backend is None else backend + if ranks is None: + ranks = global_ranks + assert len(ranks) <= len(global_ranks), ( + "Size of new group must be less than or " + "equal to that of the default global group." + ) + size = len(ranks) + ranks = sorted(ranks) + if backend == 'heter' or (size > 1 and global_rank in ranks): + rank = 0 if backend == 'heter' else ranks.index(global_rank) + src_rank = ranks[0] if backend == 'heter' else None + dst_rank = ranks[1] if backend == 'heter' else None + pg = _new_process_group_impl( + backend, + _default_store, + rank, + size, + group_name, + pg_options=None, + group_id=gid, + src_rank=src_rank, + dst_rank=dst_rank, + ) + else: + rank = -1 + pg = None + group = Group(rank, gid, ranks, pg=pg, name=group_name) + _group_map_by_name[group_name] = group + _group_map[gid] = group + _group_map_backend[group] = backend + # TODO: The method below is a new method for group management, will replace the previous + # three in the future. + _add_new_group(group) + + # TODO(shenliang03): This is a temporary solution to solve the problem of + # hang caused by tcp + paddle.distributed.barrier(group=group) + # NOTE(liyurui): All processors should hang and wait using tcp store, in case master exit before sub-group is created. + if backend != 'heter': + _barrier_by_tcp_store(group_name, _default_store, timeout) + else: + print("Warning: store barrier is not supported for heter backend.") + return group + + if not backend: + backend = 'nccl' + assert backend == 'nccl', "backend other than nccl is not supported yet" + + genv = _get_global_env() + global_rank = genv.rank + + ring_id = _new_ring_id() + + if global_rank not in ranks: + gp = Group(-1, ring_id, ranks) + _group_map[ring_id] = gp + else: + ranks = sorted(ranks) + group_rank = ranks.index(global_rank) + group_size = len(ranks) + gp = Group(group_rank, ring_id, ranks) + _group_map[ring_id] = gp + + if group_size >= 2: + strategy = core.ParallelStrategy() + strategy.nranks = group_size + strategy.local_rank = group_rank + strategy.trainer_endpoints = [ + genv.trainer_endpoints[i] for i in ranks + ] + strategy.current_endpoint = genv.current_endpoint + strategy.nrings = 1 + + if core.is_compiled_with_cuda(): + place = core.CUDAPlace(genv.device_id) + core.NCCLParallelContext(strategy, place).init_with_ring_id( + ring_id + ) + elif core.is_compiled_with_npu(): + place = core.NPUPlace(genv.device_id) + core.HCCLParallelContext(strategy, place).init_with_ring_id( + ring_id + ) + elif core.is_compiled_with_mlu(): + place = core.MLUPlace(genv.device_id) + core.CNCLParallelContext(strategy, place).init_with_ring_id( + ring_id + ) + elif core.is_compiled_with_xpu(): + place = core.XPUPlace(genv.device_id) + core.BKCLParallelContext(strategy, place).init_with_ring_id( + ring_id + ) + else: + assert False, "no cuda device found" + else: + return gp + + # TODO(shenliang03): This is a temporary solution to solve the problem of + # hang caused by cross-creation of new_group + tmp = ( + paddle.to_tensor([1], dtype="int32") + if _non_static_mode() + else fill_constant([0], dtype="int32", value="1") + ) + paddle.distributed.all_reduce(tmp, sync_op=True) + paddle.distributed.wait(tmp) + return gp + + +def is_initialized(): + """ + + Check whether the distributed environment has been initialized + + Returns: + `True` if distributed environment has been initialized, otherwise `False`. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + + print(paddle.distributed.is_initialized()) + # False + + paddle.distributed.init_parallel_env() + print(paddle.distributed.is_initialized()) + # True + + """ + global _group_map_by_name + return _default_group_name in _group_map_by_name + + +def destroy_process_group(group=None): + """ + Destroy a given group for communication + + Args: + group (ProcessGroup, optional): The group to be destroyed. All of process groups, including + the default group, will be destroyed and the distributed + environment will be deinitialized. + + Returns : None + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + group = dist.new_group([0, 1]) + + dist.destroy_process_group(group) + print(dist.is_initialized()) + # True + dist.destroy_process_group() + print(dist.is_initialized()) + # False + + """ + global _group_map + global _group_map_by_name + + pg = _get_default_group() if group is None else group + assert _group_map.get(pg.id, None) is not None, "Invalid group." + + if group is None: + _group_map.clear() + _group_map_by_name.clear() + _group_map_backend.clear() + else: + del _group_map[pg.id] + del _group_map_by_name[pg.name] + del _group_map_backend[pg] + + +def wait(tensor, group=None, use_calc_stream=True): + """ + + wait to sync stream for group. + + Args: + tensor (Tensor): The Tensor used before sync. + group (Group): The Group instance to perform sync. + use_calc_stream (bool): Wether to use calculation stream (True) or communication stream (False). + Default to True. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + + paddle.distributed.init_parallel_env() + tindata = paddle.randn(shape=[2, 3]) + paddle.distributed.all_reduce(tindata, sync_op=True) + paddle.distributed.wait(tindata) + + """ + + if group is not None and not group.is_member(): + return + + ring_id = 0 if group is None else group.id + + if use_calc_stream: + _sync_calc_stream(tensor) + else: + _sync_comm_stream(tensor, ring_id) + + +def _sync_calc_stream(tensor): + + if _non_static_mode(): + return _legacy_C_ops.c_sync_calc_stream(tensor, tensor) + + op_type = 'c_sync_calc_stream' + + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + ) + + +def _sync_comm_stream(tensor, ring_id=0): + + if _non_static_mode(): + return _legacy_C_ops.c_sync_comm_stream( + [tensor], [tensor], 'ring_id', ring_id + ) + + op_type = 'c_sync_comm_stream' + + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + attrs={'ring_id': ring_id}, + ) + + +def broadcast(tensor, src, group=None, sync_op=True): + """ + + Broadcast a tensor from the source to all others. + As shown below, one process is started with a GPU and GPU0 owns data 0. Through broadcast operator, + data 0 will be sent to all GPUs from GPU0. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/broadcast.png + :width: 800 + :alt: broadcast + :align: center + + Args: + tensor (Tensor): The Tensor to send if current rank is the source, or the Tensor to receive otherwise. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + src (int): The source rank. + group (Group, optional): The group instance return by new_group or None for global default group. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + dist.broadcast(data, src=1) + print(data) + # [[1, 2, 3], [1, 2, 3]] (2 GPUs) + """ + + if group is not None and not group.is_member(): + return + + if not isinstance(src, int): + raise ValueError("src should be int.") + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + gsrc = group.get_group_rank(src) + assert gsrc >= 0, "src rank out of group, need global rank" + task = group.process_group.broadcast(tensor, gsrc) + if sync_op: + task.wait() + return None + else: + return task + + use_calc_stream = sync_op + ring_id = ring_id = 0 if group is None else group.id + gsrc = src if group is None else group.get_group_rank(src) + assert gsrc >= 0, "src rank out of group, need global rank" + + if _non_static_mode(): + return _legacy_C_ops.c_broadcast( + tensor, + tensor, + 'root', + gsrc, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + ) + + op_type = 'c_broadcast' + check_variable_and_dtype( + tensor, + 'tensor', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'int8', + 'uint8', + 'bool', + ], + 'broadcast', + ) + + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + attrs={ + 'root': gsrc, + 'use_calc_stream': use_calc_stream, + 'ring_id': ring_id, + }, + ) + + +def reduce(tensor, dst, op=ReduceOp.SUM, group=None, sync_op=True): + """ + + Reduce a tensor to the destination from all others. As shown below, one process is started with a GPU and the data of this process is represented + by its group rank. The destination of the reduce operator is GPU0 and the process is sum. Through reduce operator, + the GPU0 will owns the sum of all data from all GPUs. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/reduce.png + :width: 800 + :alt: reduce + :align: center + + Args: + tensor (Tensor): The output Tensor for the destination and the input Tensor otherwise. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + dst (int): The destination rank id. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The operation used. Default value is ReduceOp.SUM. + group (Group, optional): The group instance return by new_group or None for global default group. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + dist.reduce(data, dst=0) + print(data) + # [[5, 7, 9], [5, 7, 9]] (2 GPUs, out for rank 0) + # [[1, 2, 3], [1, 2, 3]] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + op_type = _get_reduce_op(op, "reduce") + group = _get_default_group() if group is None else group + gdst = group.get_group_rank(dst) + assert gdst >= 0, "dst rank out of group, need global rank" + task = group.process_group.reduce(tensor, gdst, op_type) + if sync_op: + task.wait() + return None + else: + return task + + use_calc_stream = sync_op + ring_id = 0 if group is None else group.id + gdst = dst if group is None else group.get_group_rank(dst) + assert gdst >= 0, "dst rank out of group, need global rank" + + if _non_static_mode(): + if op == ReduceOp.SUM: + return _legacy_C_ops.c_reduce_sum( + tensor, + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'root_id', + gdst, + ) + elif op == ReduceOp.MAX: + return _legacy_C_ops.c_reduce_max( + tensor, + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'root_id', + gdst, + ) + elif op == ReduceOp.MIN: + return _legacy_C_ops.c_reduce_min( + tensor, + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'root_id', + gdst, + ) + elif op == ReduceOp.PROD: + return _legacy_C_ops.c_reduce_prod( + tensor, + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'root_id', + gdst, + ) + else: + raise ValueError("Unknown parameter: {}.".format(op)) + + op_type = 'c_reduce' + check_variable_and_dtype( + tensor, + 'tensor', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'int8', + 'uint8', + 'bool', + ], + 'reduce', + ) + + if op == ReduceOp.SUM: + op_type = 'c_reduce_sum' + elif op == ReduceOp.MAX: + op_type = 'c_reduce_max' + elif op == ReduceOp.MIN: + op_type = 'c_reduce_min' + elif op == ReduceOp.PROD: + op_type = 'c_reduce_prod' + + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream, + 'root_id': gdst, + }, + ) + + +def all_gather(tensor_list, tensor, group=None, sync_op=True): + """ + + Gather tensors from all participators and all get the result. As shown + below, one process is started with a GPU and the data of this process is represented + by its group rank. Through the all_gather operator, each GPU will have data + from all GPUs. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/allgather.png + :width: 800 + :alt: all_gather + :align: center + + Args: + tensor_list (list): A list of output Tensors. Every element in the list must be a Tensor whose data type + should be float16, float32, float64, int32, int64, int8, uint8, bool, bfloat16, complex64 or complex128. + tensor (Tensor): The Tensor to send. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool, complex64 or complex128. + group (Group, optional): The group instance return by new_group or None for global default group. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + tensor_list = [] + if dist.get_rank() == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + dist.all_gather(tensor_list, data) + print(tensor_list) + # [[[4, 5, 6], [4, 5, 6]], [[1, 2, 3], [1, 2, 3]]] (2 GPUs) + """ + if group is not None and not group.is_member(): + return + + def convert_to_complex(list_of_tensor): + list_of_complex = [] + for tensor in list_of_tensor: + list_of_complex.append(paddle.as_complex(tensor)) + return list_of_complex + + is_input_complex = ( + tensor.dtype == paddle.complex64 or tensor.dtype == paddle.complex128 + ) + if is_input_complex: + tensor = paddle.as_real(tensor) + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + if len(tensor_list) == 0: + tensor_shape = list(tensor.shape) + tensor_shape[0] *= group.nranks + out = paddle.empty(tensor_shape, tensor.dtype) + else: + out = paddle.concat(tensor_list, axis=0) + task = group.process_group.all_gather(tensor, out) + task.wait() + tensor_list.clear() + list_of_tensor = paddle.split(out, group.nranks, 0) + if is_input_complex: + tensor_list.extend(convert_to_complex(list_of_tensor)) + else: + tensor_list.extend(list_of_tensor) + return + + use_calc_stream = sync_op + ring_id = 0 if group is None else group.id + nranks = _get_global_group().nranks if group is None else group.nranks + + if _non_static_mode(): + out = _legacy_C_ops.c_allgather( + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'nranks', + nranks, + ) + else: + op_type = 'c_allgather' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=tensor.dtype) + if not isinstance(tensor_list, list): + raise ValueError( + "The type of 'tensor_list' for all_gather " "should be list." + ) + for elem in tensor_list: + check_variable_and_dtype( + elem, + 'tensor_list', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'bool', + 'int8', + 'uint8', + 'complex64', + 'complex128', + ], + 'all_gather', + ) + check_variable_and_dtype( + tensor, + 'tensor', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'bool', + 'int8', + 'uint8', + 'complex64', + 'complex128', + ], + 'all_gather', + ) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [out]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream, + 'nranks': nranks, + }, + ) + + list_of_tensor = paddle.split(out, nranks, 0) + if is_input_complex: + tensor_list.extend(convert_to_complex(list_of_tensor)) + else: + tensor_list.extend(list_of_tensor) + + +def _convert_object_to_tensor(obj): + _pickler = pickle.Pickler + f = io.BytesIO() + _pickler(f).dump(obj) + data = np.frombuffer(f.getvalue(), dtype=np.uint8) + tensor = paddle.to_tensor(data) + return tensor, tensor.numel() + + +def _convert_tensor_to_object(tensor, len_of_tensor): + _unpickler = pickle.Unpickler + return _unpickler(io.BytesIO(tensor.numpy()[:len_of_tensor])).load() + + +def all_gather_object(object_list, obj, group=None): + """ + + Gather picklable objects from all participators and all get the result. Similiar to all_gather(), but python object can be passed in. + + Args: + object_list (list): A list of output object. The datatype of every element in the list is same as the input obj. + obj (Any): The picklable object to send. + group (Group): The group instance return by new_group or None for global default group. + + Returns: + None. + + Warning: + This API only supports the dygraph mode. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + object_list = [] + if dist.get_rank() == 0: + obj = {"foo": [1, 2, 3]} + else: + obj = {"bar": [4, 5, 6]} + dist.all_gather_object(object_list, obj) + print(object_list) + # [{'foo': [1, 2, 3]}, {'bar': [4, 5, 6]}] (2 GPUs) + """ + assert ( + in_dygraph_mode() + ), "all_gather_object doesn't support static graph mode." + + tensor, len_of_tensor = _convert_object_to_tensor(obj) + + # gather len_of_tensor from all ranks + list_len_of_tensor = [] + all_gather(list_len_of_tensor, len_of_tensor, group) + # get the max length from list + max_len_of_tensor = int(max(list_len_of_tensor).item()) + # resize the input tensor to max length avoid hang in all gather + # Note(liyurui): Maybe we should support various length all_gather? + # Now this operation is efficient for we don't support resize in python. + numpy_data = tensor.numpy() + numpy_data = np.resize(numpy_data, [max_len_of_tensor]) + input_tensor = paddle.to_tensor(numpy_data) + + tensor_list = [] + all_gather(tensor_list, input_tensor, group) + for i, tensor in enumerate(tensor_list): + object_list.append( + _convert_tensor_to_object(tensor, list_len_of_tensor[i]) + ) + + +def scatter(tensor, tensor_list=None, src=0, group=None, sync_op=True): + """ + + Scatter a tensor to all participators. As shown below, one process is started with a GPU and the source of the scatter + is GPU0. Through scatter operator, the data in GPU0 will be sent to all GPUs averagely. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/scatter.png + :width: 800 + :alt: scatter + :align: center + + Args: + tensor (Tensor): The output Tensor. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + tensor_list (list|tuple): A list/tuple of Tensors to scatter. Every element in the list must be a Tensor whose data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. Default value is None. + src (int): The source rank id. Default value is 0. + group (Group, optional): The group instance return by new_group or None for global default group. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data1 = paddle.to_tensor([7, 8, 9]) + data2 = paddle.to_tensor([10, 11, 12]) + dist.scatter(data1, src=1) + else: + data1 = paddle.to_tensor([1, 2, 3]) + data2 = paddle.to_tensor([4, 5, 6]) + dist.scatter(data1, tensor_list=[data1, data2], src=1) + print(data1, data2) + # [1, 2, 3] [10, 11, 12] (2 GPUs, out for rank 0) + # [4, 5, 6] [4, 5, 6] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + return + + if not isinstance(src, int): + raise ValueError("src should be int.") + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + gsrc = group.get_group_rank(src) + rank = group.rank + nranks = group.nranks + else: + ring_id = 0 if group is None else group.id + gsrc = src if group is None else group.get_group_rank(src) + rank = _get_global_group().rank if group is None else group.rank + nranks = _get_global_group().nranks if group is None else group.nranks + assert gsrc >= 0, "src rank out of group, need global rank" + + if rank != gsrc: + tensor_list = [] + for _ in range(nranks): + tensor_list.append(tensor) + temp = paddle.concat(tensor_list, axis=0) + if in_dygraph_mode(): + task = group.process_group.scatter(temp, tensor, gsrc) + if sync_op: + task.wait() + return None + else: + return task + + use_calc_stream = sync_op + if _non_static_mode(): + return _legacy_C_ops.c_scatter( + temp, + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'nranks', + nranks, + 'root', + gsrc, + ) + op_type = 'c_scatter' + check_variable_and_dtype( + tensor, + 'tensor', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'int8', + 'uint8', + 'bool', + ], + 'scatter', + ) + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [temp]}, + outputs={'Out': [tensor]}, + attrs={ + 'ring_id': ring_id, + 'root': gsrc, + 'use_calc_stream': use_calc_stream, + 'nranks': nranks, + }, + ) + + +def alltoall(in_tensor_list, out_tensor_list, group=None, sync_op=True): + """ + Scatter tensors in in_tensor_list to all participators averagely and gather the result tensors in out_tensor_list. + As shown below, the in_tensor_list in GPU0 includes 0_0 and 0_1, and GPU1 includes 1_0 and 1_1. + Through alltoall operator, the 0_0 in GPU0 will be sent to GPU0 and 0_1 to GPU1, 1_0 in GPU1 sent to GPU0 and 1_1 to GPU1. + Finally the out_tensor_list in GPU0 includes 0_0 and 1_0, and GPU1 includes 0_1 and 1_1. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/alltoall.png + :width: 800 + :alt: alltoall + :align: center + + Args: + in_tensor_list (list): A list of input Tensors. Every element in the list must be a Tensor whose data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + out_tensor_list (list): A list of output Tensors. The data type of its elements should be the same as the + data type of the input Tensors. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + out_tensor_list = [] + if dist.get_rank() == 0: + data1 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) + data2 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]]) + else: + data1 = paddle.to_tensor([[13, 14, 15], [16, 17, 18]]) + data2 = paddle.to_tensor([[19, 20, 21], [22, 23, 24]]) + dist.alltoall([data1, data2], out_tensor_list) + print(out_tensor_list) + # [[[1, 2, 3], [4, 5, 6]], [[13, 14, 15], [16, 17, 18]]] (2 GPUs, out for rank 0) + # [[[7, 8, 9], [10, 11, 12]], [[19, 20, 21], [22, 23, 24]]] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + else: + ring_id = 0 if group is None else group.id + + temp = paddle.concat(in_tensor_list, axis=0) + nranks = len(in_tensor_list) + if in_dygraph_mode(): + if len(out_tensor_list) == 0: + tensor_shape = list(in_tensor_list[0].shape) + tensor_shape[0] *= nranks + out = paddle.empty(tensor_shape, in_tensor_list[0].dtype) + else: + out = paddle.concat(out_tensor_list, axis=0) + task = group.process_group.alltoall(temp, out) + task.wait() + out_tensor_list.clear() + out_tensor_list.extend(paddle.split(out, nranks, 0)) + return + + use_calc_stream = sync_op + if _non_static_mode(): + out = _legacy_C_ops.alltoall( + temp, 'use_calc_stream', use_calc_stream, 'ring_id', ring_id + ) + else: + op_type = 'alltoall' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference( + dtype=in_tensor_list[0].dtype + ) + + if not isinstance(in_tensor_list, list): + raise ValueError( + "The type of 'in_tensor_list' for all_to_all " "should be list." + ) + for elem in in_tensor_list: + check_variable_and_dtype( + elem, + 'in_tensor_list', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'all_to_all', + ) + if not isinstance(out_tensor_list, list): + raise ValueError( + "The type of 'out_tensor_list' for all_to_all " + "should be list." + ) + if len(out_tensor_list) != 0: + raise ValueError( + "The 'out_tensor_list' for all_to_all " "must be an empty list." + ) + helper.append_op( + type=op_type, + inputs={'X': [temp]}, + outputs={'Out': [out]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream, + }, + ) + out_tensor_list.extend(paddle.split(out, nranks, 0)) + + +def alltoall_single( + in_tensor, + out_tensor, + in_split_sizes=None, + out_split_sizes=None, + group=None, + sync_op=True, +): + """ + Scatter a single input tensor to all participators and gather the received tensors in out_tensor. + + Note: + ``alltoall_single`` is only supported in eager mode. + + Args: + in_tensor (Tensor): Input tensor. The data type should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + out_tensor (Tensor): Output Tensor. The data type should be the same as the data type of the input Tensor. + in_split_sizes (list[int], optional): Split sizes of ``in_tensor`` for dim[0]. If not given, dim[0] of ``in_tensor`` + must be divisible by group size and ``in_tensor`` will be scattered averagely to all participators. Default: None. + out_split_sizes (list[int], optional): Split sizes of ``out_tensor`` for dim[0]. If not given, dim[0] of ``out_tensor`` + must be divisible by group size and ``out_tensor`` will be gathered averagely from all participators. Default: None. + group (Group, optional): The group instance return by ``new_group`` or None for global default group. Default: None. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None, if ``sync_op`` is set to ``True``; ``Task`` of ``group``, if ``sync_op`` is set to ``False``. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + rank = dist.get_rank() + size = dist.get_world_size() + + # case 1 (2 GPUs) + data = paddle.arange(2, dtype='int64') + rank * 2 + # data for rank 0: [0, 1] + # data for rank 1: [2, 3] + output = paddle.empty([2], dtype='int64') + dist.alltoall_single(data, output) + print(output) + # output for rank 0: [0, 2] + # output for rank 1: [1, 3] + + # case 2 (2 GPUs) + in_split_sizes = [i + 1 for i in range(size)] + # in_split_sizes for rank 0: [1, 2] + # in_split_sizes for rank 1: [1, 2] + out_split_sizes = [rank + 1 for i in range(size)] + # out_split_sizes for rank 0: [1, 1] + # out_split_sizes for rank 1: [2, 2] + data = paddle.ones([sum(in_split_sizes), size], dtype='float32') * rank + # data for rank 0: [[0., 0.], [0., 0.], [0., 0.]] + # data for rank 1: [[1., 1.], [1., 1.], [1., 1.]] + output = paddle.empty([(rank + 1) * size, size], dtype='float32') + group = dist.new_group([0, 1]) + task = dist.alltoall_single(data, + output, + in_split_sizes, + out_split_sizes, + sync_op=False, + group=group) + task.wait() + print(output) + # output for rank 0: [[0., 0.], [1., 1.]] + # output for rank 1: [[0., 0.], [0., 0.], [1., 1.], [1., 1.]] + + """ + if group is not None and not group.is_member(): + return + + assert in_dygraph_mode(), "Only suppport alltoall_single in eager mode." + # _check_single_tensor + + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + + in_split_sizes = [] if in_split_sizes is None else in_split_sizes + out_split_sizes = [] if out_split_sizes is None else out_split_sizes + + task = group.process_group.alltoall_single( + in_tensor, out_tensor, in_split_sizes, out_split_sizes + ) + if sync_op: + task.wait() + return + else: + return task + + +def _get_group_rank(global_rank, group=None): + return global_rank if group is None else group.get_group_rank(global_rank) + + +def send(tensor, dst=0, group=None, sync_op=True): + """ + Send a tensor to the receiver. + + Args: + tensor (Tensor): The Tensor to send. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + dst (int): The destination rank id. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([7, 8, 9]) + dist.send(data, dst=1) + else: + data = paddle.to_tensor([1, 2, 3]) + dist.recv(data, src=0) + print(data) + # [7, 8, 9] (2 GPUs) + """ + if group is not None and not group.is_member(): + return + dst = _get_group_rank(dst, group) + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + task = group.process_group.send(tensor, dst) + if sync_op: + task.wait() + return None + else: + return task + + use_calc_stream = sync_op + ring_id = 0 if group is None else group.id + + if _non_static_mode(): + return _legacy_C_ops.send_v2( + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'peer', + dst, + ) + op_type = 'send_v2' + check_variable_and_dtype( + tensor, + 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'send', + ) + + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + inputs={'X': [tensor]}, + attrs={ + 'ring_id': ring_id, + 'peer': dst, + 'use_calc_stream': use_calc_stream, + }, + ) + + +def recv(tensor, src=0, group=None, sync_op=True): + """ + Receive a tensor to the sender. + + Args: + tensor (Tensor): The Tensor to receive. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + src (int): The source rank id. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([7, 8, 9]) + dist.send(data, dst=1) + else: + data = paddle.to_tensor([1, 2, 3]) + dist.recv(data, src=0) + print(data) + # [7, 8, 9] (2 GPUs) + """ + if group is not None and not group.is_member(): + return + + src = _get_group_rank(src, group) + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + task = group.process_group.recv(tensor, src) + if sync_op: + task.wait() + return None + else: + return task + + use_calc_stream = sync_op + ring_id = 0 if group is None else group.id + + if _non_static_mode(): + return _legacy_C_ops.recv_v2( + tensor, + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'peer', + src, + 'dtype', + tensor.dtype, + 'out_shape', + tensor.shape, + ) + op_type = 'recv_v2' + check_variable_and_dtype( + tensor, + 'tensor', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'recv', + ) + helper = LayerHelper(op_type, **locals()) + helper.append_op( + type=op_type, + outputs={'Out': [tensor]}, + attrs={ + 'ring_id': ring_id, + 'peer': src, + 'out_shape': tensor.shape, + 'dtype': tensor.dtype, + 'use_calc_stream': use_calc_stream, + }, + ) + + +def _check_single_tensor(tensor, tensor_name): + if not isinstance(tensor, (core.eager.Tensor, paddle.Tensor)): + raise RuntimeError( + "Invalid function argument. Expected parameter {}" + "to be of type paddle.Tensor, but it's {}".format( + tensor_name, type(tensor) + ) + ) + + +def _check_tensor_list(tensor_list, tensor_name): + if not isinstance(tensor_list, list) or not all( + isinstance(t, (core.eager.Tensor, paddle.Tensor)) for t in tensor_list + ): + raise RuntimeError( + "Invalid function argument. Expected parameter {}" + "to be of type paddle.Tensor".format(tensor_name) + ) + + +def isend(tensor, dst, group=None): + """ + Sends a tensor asynchronously + + Args: + tensor (Tensor): The Tensor to send. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + dst (int): The destination rank. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + + Returns: + A distributed task object. + + Warning: + This API only supports the dygraph mode. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([7, 8, 9]) + task = dist.isend(data, dst=1) + else: + data = paddle.to_tensor([1, 2, 3]) + task = dist.irecv(data, src=0) + task.wait() + print(data) + # [7, 8, 9] (2 GPUs) + + """ + _check_single_tensor(tensor, "tensor") + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + group_dst_rank = group.get_group_rank(dst) + assert group_dst_rank >= 0, "dst rank out of group, need global rank" + return group.process_group.send(tensor, group_dst_rank) + else: + raise RuntimeError("Only support eager dygraph mode.") + + +def irecv(tensor, src=None, group=None): + """ + Receive a tensor to the sender. + + Args: + tensor (Tensor): The Tensor to receive. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + src (int): The source rank id. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + + Returns: + A distributed task object. + + Warning: + This API only supports the dygraph mode. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([7, 8, 9]) + task = dist.isend(data, dst=1) + else: + data = paddle.to_tensor([1, 2, 3]) + task = dist.irecv(data, src=0) + task.wait() + print(data) + # [7, 8, 9] (2 GPUs) + """ + _check_single_tensor(tensor, "tensor") + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + group_src_rank = group.get_group_rank(src) + assert group_src_rank >= 0, "src rank out of group, need global rank" + return group.process_group.recv(tensor, group_src_rank) + else: + raise RuntimeError("Only support eager dygraph mode.") + + +class P2POp(object): + """ + A class that makes point-to-point operations for "batch_isend_irecv". + + This class creates the type of P2P operation, communication buffer, peer rank, + Group. Instances of this class will be passed to + ``paddle.distributed.batch_isend_irecv`` for point-to-point communication. + + Args: + op (callable): A function to send data to or receive data from a peer process. + The type of ``op`` is either ``paddle.distributed.isend`` or ``paddle.distributed.irecv``. + tensor (Tensor): Tensor to send or receive. + peer (int): The destination or source rank. + group (Group, optional): The group instance return by new_group or None for global + default group. Default: None. + + """ + + def __init__(self, op, tensor, peer, group=None): + if op not in [isend, irecv]: + raise RuntimeError( + "Invalid ``op`` function. Expected ``op`` " + "to be of type ``paddle.distributed.isend`` or " + "``paddle.distributed.irecv``." + ) + _check_single_tensor(tensor, "tensor") + + self.op = op + self.tensor = tensor + self.peer = peer + self.group = _get_default_group() if group is None else group + + +@contextlib.contextmanager +def _with_batch_p2p_guard(backend): + if backend == "nccl": + core.ProcessGroupNCCL.group_start() + try: + yield + finally: + if backend == "nccl": + core.ProcessGroupNCCL.group_end() + + +def _check_p2p_op_list(p2p_op_list): + """ + Helper to check that the ``p2p_op_list`` is a list of P2POp instances and + all ops use the same backend. + """ + if not isinstance(p2p_op_list, list) or not all( + isinstance(p2p_op, P2POp) for p2p_op in p2p_op_list + ): + raise RuntimeError( + "Invalid ``p2p_op_list``. Each op is expected to " + "to be of type ``paddle.distributed.P2POp``." + ) + + backend = _group_map_backend[p2p_op_list[0].group] + if not all( + backend == _group_map_backend[p2p_op.group] for p2p_op in p2p_op_list + ): + raise RuntimeError("All groups need to use the same backend.") + + +def batch_isend_irecv(p2p_op_list): + """ + Send or Receive a batch of tensors asynchronously and return a list of requests. + + Process each of the point-to-point operations in ``p2p_op_list`` and return the + corresponding tasks. NCCL are currently supported. + + Args: + p2p_op_list (List[P2POp]): A list of point-to-point operations(type of each operator is + ``paddle.distributed.P2POp``). The order of the isend/irecv in the list + matters and it needs to match with corresponding isend/irecv on the + remote end. + + Returns: + A list of distributed tasks returned by calling the corresponding + op in the op_list. + + Warning: + This API only supports the dygraph mode. + + Examples: + .. code-block:: python + + # required: distributed + + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + rank = dist.get_rank() + world_size = dist.get_world_size() + + send_t = paddle.arange(2) + rank + # paddle.tensor([0, 1]) # Rank-0 + # paddle.tensor([1, 2]) # Rank-1 + + recv_t = paddle.empty(shape=[2], dtype=send_t.dtype) + + send_op = dist.P2POp(dist.isend, send_t, (rank + 1) % world_size) + recv_op = dist.P2POp(dist.irecv, recv_t, (rank - 1 + world_size) % world_size) + + tasks = dist.batch_isend_irecv([send_op, recv_op]) + + for task in tasks: + task.wait() + + print(recv_t) + # paddle.tensor([1, 2]) # Rank-0 + # paddle.tensor([0, 1]) # Rank-1 + """ + _check_p2p_op_list(p2p_op_list) + group = p2p_op_list[0].group + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + tasks = [] + with _with_batch_p2p_guard(backend): + for p2p_op in p2p_op_list: + op = p2p_op.op + tensor = p2p_op.tensor + peer = p2p_op.peer + comm_group = p2p_op.group + task = op(tensor, peer, comm_group) + if task is not None: + tasks.append(task) + return tasks + else: + raise RuntimeError("Don't support static graph mode currently.") + + +def reduce_scatter( + tensor, tensor_list, op=ReduceOp.SUM, group=None, sync_op=True +): + """ + Reduces, then scatters a list of tensors to all processes in a group + + Args: + tensor (Tensor): Output tensor. Its data type should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + tensor_list (list[Tensor]): List of tensors to reduce and scatter. Every element in the list must be a Tensor whose data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD): Optional. The operation used. Default: ReduceOp.SUM. + group (Group, optional): The group instance return by new_group or None for global + default group. Default: None. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + Async task handle, if sync_op is set to False. + None, if sync_op or if not part of the group. + + Warning: + This API only supports the dygraph mode. + + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data1 = paddle.to_tensor([0, 1]) + data2 = paddle.to_tensor([2, 3]) + else: + data1 = paddle.to_tensor([4, 5]) + data2 = paddle.to_tensor([6, 7]) + dist.reduce_scatter(data1, [data1, data2]) + print(data1) + # [4, 6] (2 GPUs, out for rank 0) + # [8, 10] (2 GPUs, out for rank 1) + + """ + _check_single_tensor(tensor, "tensor") + _check_tensor_list(tensor_list, "tensor_list") + + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + op_type = _get_reduce_op(op, "reduce_scatter") + group = _get_default_group() if group is None else group + backend = _group_map_backend[group] + assert backend != 'gloo', "backend gloo is not supported yet" + + temp = paddle.concat(tensor_list, axis=0) + task = group.process_group._reduce_scatter_base(tensor, temp, op_type) + if sync_op: + task.wait() + return None + else: + return task + else: + raise RuntimeError("Don't support static graph mode currently.") + + +def _reduce_scatter_base( + output, input, op=ReduceOp.SUM, group=None, sync_op=True +): + """ + Reduces, then scatters a flattened tensor to all processes in a group. + + Args: + output (Tensor): Output tensor. Its data type should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + input (Tensor): Input tensor that is of size output tensor size times world size. Its data type + should be float16, float32, float64, int32, int64, int8, uint8, bool or bfloat16. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD): Optional. The operation used. Default: ReduceOp.SUM. + group (ProcessGroup, optional): The process group to work on. If None, + the default process group will be used. + sync_op (bool, optional): Whether this op is a sync op. The default value is True. + + Returns: + Async task handle, if sync_op is set to False. + None, if sync_op or if not part of the group. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + rank = dist.get_rank() + data = paddle.arange(4) + rank + # [0, 1, 2, 3] (2 GPUs, for rank 0) + # [1, 2, 3, 4] (2 GPUs, for rank 1) + output = paddle.empty(shape=[2], dtype=data.dtype) + dist.collective._reduce_scatter_base(output, data) + print(output) + # [1, 3] (2 GPUs, out for rank 0) + # [5, 7] (2 GPUs, out for rank 1) + + """ + _check_single_tensor(output, "output") + _check_single_tensor(input, "input") + + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + op_type = _get_reduce_op(op, "_reduce_scatter_base") + group = _get_default_group() if group is None else group + task = group.process_group._reduce_scatter_base(output, input, op_type) + if sync_op: + task.wait() + return None + else: + return task + else: + raise RuntimeError("Don't support static graph mode currently.") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/all_reduce.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..737e0cbbfb56c070687fa18b9df30df0cec890d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/all_reduce.py @@ -0,0 +1,87 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.fluid.framework as framework +from paddle.distributed.communication import stream as stream +from paddle.distributed.communication.reduce import ReduceOp + + +def all_reduce(tensor, op=ReduceOp.SUM, group=None, sync_op=True): + """ + + Reduce a tensor over all ranks so that all get the result. + As shown below, one process is started with a GPU and the data of this process is represented + by its group rank. The reduce operator is sum. Through all_reduce operator, + each GPU will have the sum of the data from all GPUs. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/allreduce.png + :width: 800 + :alt: all_reduce + :align: center + + Args: + tensor (Tensor): The input Tensor. It also works as the output Tensor. Its data type + should be float16, float32, float64, int32, int64, int8, uint8 or bool. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The operation used. Default value is ReduceOp.SUM. + group (Group, optional): The group instance return by new_group or None for global default group. + sync_op (bool, optional): Wether this op is a sync op. Default value is True. + + Returns: + Return a task object. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + dist.all_reduce(data) + print(data) + # [[5, 7, 9], [5, 7, 9]] (2 GPUs) + """ + if not framework._in_legacy_dygraph(): + return stream.all_reduce(tensor, + op=op, + group=group, + sync_op=sync_op, + use_calc_stream=False) + + # code below will be removed after we remove the old dygraph + use_calc_stream = sync_op + ring_id = 0 if group is None else group.id + if op == ReduceOp.SUM: + return paddle._legacy_C_ops.c_allreduce_sum_(tensor, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id) + elif op == ReduceOp.MAX: + return paddle._legacy_C_ops.c_allreduce_max_(tensor, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id) + elif op == ReduceOp.MIN: + return paddle._legacy_C_ops.c_allreduce_min_(tensor, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id) + elif op == ReduceOp.PROD: + return paddle._legacy_C_ops.c_allreduce_prod_(tensor, 'use_calc_stream', + use_calc_stream, + 'ring_id', ring_id) + else: + raise ValueError("Unknown parameter: {}.".format(op)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/group.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/group.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4e545b245d1e987fedcd62e3331a96354930d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/group.py @@ -0,0 +1,94 @@ +# Copyright (c) 2022 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. + + +class Group(): + """ + The abstract representation of group. + """ + + def __init__(self, rank_in_group, id, ranks, pg=None, name=None): + self._rank_in_group = rank_in_group + self._world_size = len(ranks) if rank_in_group >= 0 else -1 + self._id = id + self._ranks = ranks + self._pg = pg + self._name = name + + @property + def rank(self): + return self._rank_in_group + + @property + def ranks(self): + return self._ranks + + @property + def nranks(self): + return len(self._ranks) + + @property + def name(self): + return self._name + + @property + def process_group(self): + return self._pg + + @property + def world_size(self): + return self._world_size + + @property + def id(self): + return self._id + + def is_member(self): + if self.rank < 0: + return False + if self.nranks < 2: + return False + return True + + def get_group_rank(self, rank): + if self.is_member(): + return self.ranks.index(rank) + else: + return -1 + + def __repr__(self): + debug_str = "rank: {}, nranks: {}, id: {}, ranks: ".format( + self.rank, self.nranks, self.id) + debug_str += ", ".join(map(str, self.ranks)) + debug_str += "; name: " + debug_str += self.name if self.name else "None" + return debug_str + + +class _GroupManager(): + global_group_id = 0 + group_map_by_id = {} + + +def _get_global_group(): + if _GroupManager.global_group_id not in _GroupManager.group_map_by_id: + raise RuntimeError("The global group is not initialized.") + return _GroupManager.group_map_by_id[_GroupManager.global_group_id] + + +def _add_new_group(group): + if group.id in _GroupManager.group_map_by_id: + raise RuntimeError("The group with id {} already exist.".format( + group.id)) + _GroupManager.group_map_by_id[group.id] = group diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/reduce.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..5caa5bebedfd8115f34252c3f490b49c32131778 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/reduce.py @@ -0,0 +1,76 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +import paddle.fluid.core as core + + +class ReduceOp: + """ + + Specify the type of operation used for element-wise reductions. + It should be one of the following values: + + ReduceOp.SUM + + ReduceOp.MAX + + ReduceOp.MIN + + ReduceOp.PROD + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + dist.all_reduce(data, op=dist.ReduceOp.SUM) + print(data) + # [[5, 7, 9], [5, 7, 9]] (2 GPUs) + """ + SUM = 0 + MAX = 1 + MIN = 2 + PROD = 3 + AVG = 4 + + +def _get_reduce_op(reduce_op, func_name): + if framework.in_dygraph_mode(): + if reduce_op == ReduceOp.SUM: + return core.ReduceOp.SUM + elif reduce_op == ReduceOp.MAX: + return core.ReduceOp.MAX + elif reduce_op == ReduceOp.MIN: + return core.ReduceOp.MIN + elif reduce_op == ReduceOp.PROD: + return core.ReduceOp.PRODUCT + else: + if reduce_op == ReduceOp.SUM: + return 'c_allreduce_sum' + elif reduce_op == ReduceOp.MAX: + return 'c_allreduce_max' + elif reduce_op == ReduceOp.MIN: + return 'c_allreduce_min' + elif reduce_op == ReduceOp.PROD: + return 'c_allreduce_prod' + + raise ValueError("Unknown reduce_op type for {}.".format(func_name)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43952ce5541a339f817e67237db5fc0a099baca3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/__init__.py @@ -0,0 +1,29 @@ +# Copyright (c) 2022 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. + +from .all_gather import all_gather +from .all_reduce import all_reduce +from .alltoall import alltoall +from .alltoall_single import alltoall_single +from .broadcast import broadcast +from .reduce import reduce +from .reduce_scatter import reduce_scatter +from .recv import recv +from .scatter import scatter +from .send import send + +__all__ = [ + "all_gather", "all_reduce", "alltoall", "alltoall_single", "broadcast", + "reduce", "reduce_scatter", "recv", "scatter", "send" +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_gather.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_gather.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb961cda171d42bb38c84ae16067dd65e1e5e69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_gather.py @@ -0,0 +1,138 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _check_tensor_shape(tensor, shape, nranks=1): + expect_shape = list(shape) + expect_shape[0] *= nranks + if list(tensor.shape) != expect_shape: + raise RuntimeError('The tensor for all_gather is not correctly-sized.') + + +def _check_tensor_list_shape(tensor_list, shape, nranks=1): + if len(tensor_list) != nranks: + raise RuntimeError( + 'The tensor_list for all_gather is not correctly-sized.') + for tensor in tensor_list: + if tensor.shape != shape: + raise RuntimeError( + 'The tensor_list for all_gather is not correctly-sized.') + + +def _all_gather_into_tensor_in_dygraph(out_tensor, in_tensor, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + _check_tensor_shape(out_tensor, in_tensor.shape, group.nranks) + + if use_calc_stream: + return group.process_group.allgather_into_tensor_on_calc_stream( + in_tensor, out_tensor) + + task = group.process_group.allgather_into_tensor(in_tensor, out_tensor, + sync_op) + if sync_op: + task.wait() + + return task + + +def _all_gather_in_dygraph(tensor_list, tensor, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + if len(tensor_list) == 0: + tensor_list += [paddle.empty_like(tensor) for _ in range(group.nranks)] + else: + _check_tensor_list_shape(tensor_list, tensor.shape, group.nranks) + + if use_calc_stream: + return group.process_group.allgather_on_calc_stream(tensor, tensor_list) + + task = group.process_group.allgather(tensor, tensor_list, sync_op) + if sync_op: + task.wait() + + return task + + +def all_gather(tensor_or_tensor_list, + tensor, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Gather tensors across devices to a correctly-sized tensor or a tensor list. + + Args: + tensor_or_tensor_list (Union[Tensor, List[Tensor]]): The output. If it is a tensor, it should be correctly-sized. If it is a list, it + should be empty or contain correctly-sized tensors. + tensor (Tensor): The input tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + tensor_list = [] + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.all_gather(tensor_list, data, sync_op=False) + task.wait() + print(tensor_list) + # [[[4, 5, 6], [4, 5, 6]], [[1, 2, 3], [1, 2, 3]]] (2 GPUs) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + if paddle.is_tensor(tensor_or_tensor_list): + return _all_gather_into_tensor_in_dygraph(tensor_or_tensor_list, + tensor, group, sync_op, + use_calc_stream) + else: + return _all_gather_in_dygraph(tensor_or_tensor_list, tensor, group, + sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.all_gather is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_reduce.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba161a078ab89e82631aedd623d7934f160d3df --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/all_reduce.py @@ -0,0 +1,116 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +import paddle.fluid.data_feeder as data_feeder +import paddle.fluid.layer_helper as layer_helper +from paddle.distributed.communication.reduce import _get_reduce_op, ReduceOp +from paddle.distributed.communication.group import _get_global_group + + +def _all_reduce_in_dygraph(tensor, op, group, sync_op, use_calc_stream): + op_type = _get_reduce_op(op, "all_reduce") + + group = _get_global_group() if group is None else group + if use_calc_stream: + return group.process_group.allreduce_on_calc_stream(tensor, op_type) + + task = group.process_group.allreduce(tensor, op_type, sync_op) + if sync_op: + task.wait() + + return task + + +def _all_reduce_in_static_mode(tensor, op, group, sync_op, use_calc_stream): + data_feeder.check_variable_and_dtype(tensor, 'tensor', [ + 'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8', + 'bool' + ], 'all_reduce') + + op_type = _get_reduce_op(op, "all_reduce") + ring_id = 0 if group is None else group.id + + if not isinstance(ring_id, int): + raise ValueError("The type of 'ring_id' for all_reduce should be int.") + + # TODO: Support task and use task.wait in static mode + # Use use_calc_stream rather than sync_op + helper = layer_helper.LayerHelper(op_type, **locals()) + helper.append_op(type=op_type, + inputs={'X': [tensor]}, + outputs={'Out': [tensor]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': sync_op + }) + + return None + + +def all_reduce(tensor, + op=ReduceOp.SUM, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Perform specific reduction (for example, sum, max) on inputs across devices. + + Args: + tensor (Tensor): The input tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The reduction used. If none is given, use ReduceOp.SUM as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + data = None + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.all_reduce(data, sync_op=False) + task.wait() + out = data.numpy() + # [[5, 7, 9], [5, 7, 9]] + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + return _all_reduce_in_dygraph(tensor, op, group, sync_op, + use_calc_stream) + else: + return _all_reduce_in_static_mode(tensor, op, group, sync_op, + use_calc_stream) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall.py new file mode 100644 index 0000000000000000000000000000000000000000..b216906d0456888285405f170b48a090b03a61a9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall.py @@ -0,0 +1,157 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _check_tensor_shape(tensor, shape, nranks=1): + if tensor.shape != shape: + raise RuntimeError('The tensor for alltoall is not correctly-sized.') + + +def _check_tensor_list_shape(tensor_list, shape, nranks=1): + if len(tensor_list) != nranks: + raise RuntimeError( + 'The tensor_list for alltoall is not correctly-sized.') + for tensor in tensor_list: + if tensor.shape != shape: + raise RuntimeError( + 'The tensor_list for alltoall is not correctly-sized.') + + +def _alltoall_tensor_in_dygraph(out_tensor, in_tensor, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + _check_tensor_shape(out_tensor, in_tensor.shape, group.nranks) + + if use_calc_stream: + return group.process_group.alltoall_tensor_on_calc_stream( + in_tensor, out_tensor) + + task = group.process_group.alltoall_tensor(in_tensor, out_tensor, sync_op) + if sync_op: + task.wait() + + return task + + +def _alltoall_in_dygraph(out_tensor_list, in_tensor_list, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + if len(in_tensor_list) == 0: + raise RuntimeError("The input tensor_list should not be empty.") + + if len(out_tensor_list) == 0: + out_tensor_list += [ + paddle.empty_like(tensor) for tensor in in_tensor_list + ] + else: + _check_tensor_list_shape(out_tensor_list, in_tensor_list[0].shape, + group.nranks) + + if use_calc_stream: + return group.process_group.alltoall_on_calc_stream( + in_tensor_list, out_tensor_list) + + task = group.process_group.alltoall(in_tensor_list, out_tensor_list, + sync_op) + if sync_op: + task.wait() + + return task + + +def alltoall(out_tensor_or_tensor_list, + in_tensor_or_tensor_list, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Scatter a tensor (or a tensor list) across devices and gather outputs to another tensor (or a tensor list, respectively). + + Args: + out_tensor_or_tensor_list (Union[Tensor, List[Tensor]]): The output. If it is a tensor, it should be correctly-sized. + If it is a list, it should be empty or contain correctly-sized tensors. Its data type should be the same as the input. + in_tensor_or_tensor_list (Union[Tensor, List[Tensor]]): The input to scatter (must be specified on the source rank). + If it is a tensor, it should be correctly-sized. If it is a list, it should contain correctly-sized tensors. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + out_tensor_list = [] + if dist.get_rank() == 0: + data1 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) + data2 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]]) + else: + data1 = paddle.to_tensor([[13, 14, 15], [16, 17, 18]]) + data2 = paddle.to_tensor([[19, 20, 21], [22, 23, 24]]) + task = dist.stream.alltoall(out_tensor_list, [data1, data2], sync_op=False) + task.wait() + print(out_tensor_list) + # [[[1, 2, 3], [4, 5, 6]], [[13, 14, 15], [16, 17, 18]]] (2 GPUs, out for rank 0) + # [[[7, 8, 9], [10, 11, 12]], [[19, 20, 21], [22, 23, 24]]] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if out_tensor_or_tensor_list is None: + raise RuntimeError("The output should be specified.") + if in_tensor_or_tensor_list is None: + raise RuntimeError("The input should be specified.") + + if framework.in_dygraph_mode(): + out_is_tensor = paddle.is_tensor(out_tensor_or_tensor_list) + in_is_tensor = paddle.is_tensor(in_tensor_or_tensor_list) + if out_is_tensor and in_is_tensor: + return _alltoall_tensor_in_dygraph(out_tensor_or_tensor_list, + in_tensor_or_tensor_list, group, + sync_op, use_calc_stream) + elif not out_is_tensor and not in_is_tensor: + return _alltoall_in_dygraph(out_tensor_or_tensor_list, + in_tensor_or_tensor_list, group, + sync_op, use_calc_stream) + else: + raise RuntimeError( + "The output and input should be both tensor or tensor list.") + + raise RuntimeError( + "paddle.distributed.stream.alltoall is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall_single.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall_single.py new file mode 100644 index 0000000000000000000000000000000000000000..b2187cc06e343984ae11d005a0ffb5bc27bb8d6f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/alltoall_single.py @@ -0,0 +1,128 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _alltoall_single_in_dygraph(out_tensor, in_tensor, out_split_sizes, + in_split_sizes, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + if out_split_sizes is None: + out_split_sizes = [] + if in_split_sizes is None: + in_split_sizes = [] + + if use_calc_stream: + return group.process_group.alltoall_single_on_calc_stream( + in_tensor, out_tensor, in_split_sizes, out_split_sizes) + + task = group.process_group.alltoall_single(in_tensor, out_tensor, + in_split_sizes, out_split_sizes, + sync_op) + if sync_op: + task.wait() + + return task + + +def alltoall_single(out_tensor, + in_tensor, + out_split_sizes=None, + in_split_sizes=None, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Split and Scatter the splitted input tensor to the out tensor across devices. + + Args: + out_tensor(Tensor): The output tensor. Its data type should be the same as the input. + in_tensor (Tensor): The input tensor. Its data type should be float16, float32, float64, int32, int64, int8, uint8 or bool. + out_split_sizes (List[int], optional): Split sizes of out_tensor for dim[0]. If not given, dim[0] of out_tensor must be divisible + by group size and out_tensor will be gathered averagely from all participators. If none is given, use a empty list as default. + in_split_sizes (List[int], optional): Split sizes of in_tensor for dim[0]. If not given, dim[0] of in_tensor must be divisible + by group size and in_tensor will be scattered averagely to all participators. If none is given, use a empty list as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + + # case 1 + output = paddle.empty([2], dtype="int64") + if local_rank == 0: + data = paddle.to_tensor([0, 1]) + else: + data = paddle.to_tensor([2, 3]) + task = dist.stream.alltoall_single(output, data, sync_op=False) + task.wait() + out = output.numpy() + # [0, 2] (2 GPUs, out for rank 0) + # [1, 3] (2 GPUs, out for rank 1) + + # case 2 + size = dist.get_world_size() + output = paddle.empty([(local_rank + 1) * size, size], dtype='float32') + if local_rank == 0: + data = paddle.to_tensor([[0., 0.], [0., 0.], [0., 0.]]) + else: + data = paddle.to_tensor([[1., 1.], [1., 1.], [1., 1.]]) + out_split_sizes = [local_rank + 1 for i in range(size)] + in_split_sizes = [i + 1 for i in range(size)] + task = dist.stream.alltoall_single(output, + data, + out_split_sizes, + in_split_sizes, + sync_op=False) + task.wait() + out = output.numpy() + # [[0., 0.], [1., 1.]] (2 GPUs, out for rank 0) + # [[0., 0.], [0., 0.], [1., 1.], [1., 1.]] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + return _alltoall_single_in_dygraph(out_tensor, in_tensor, + out_split_sizes, in_split_sizes, + group, sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.alltoall_single is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/broadcast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/broadcast.py new file mode 100644 index 0000000000000000000000000000000000000000..06bde316937a9d92325969324c249225991d10e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/broadcast.py @@ -0,0 +1,83 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _broadcast_in_dygraph(tensor, src, group, sync_op, use_calc_stream): + group = collective._get_default_group() if group is None else group + if use_calc_stream: + return group.process_group.broadcast_on_calc_stream(tensor, src) + + task = group.process_group.broadcast(tensor, src, sync_op) + if sync_op: + task.wait() + + return task + + +def broadcast(tensor, src=0, group=None, sync_op=True, use_calc_stream=False): + """ + + Broadcast a tensor to all devices. + + Args: + tensor (Tensor): The tensor to broadcast. Support float16, float32, float64, int32, int64, int8, uint8 or bool as its data type. + src (int, optional): Rank of the source device. If none is given, use `0` as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.broadcast(data, src=1, sync_op=False) + task.wait() + out = data.numpy() + # [[1, 2, 3], [1, 2, 3]] (2 GPUs) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be True in sync op behavior.") + + if framework.in_dygraph_mode(): + return _broadcast_in_dygraph(tensor, src, group, sync_op, + use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.broadcast is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/recv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/recv.py new file mode 100644 index 0000000000000000000000000000000000000000..25a8173788473aa79f9f32ddae9945d69156fb80 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/recv.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _recv_in_dygraph(tensor, src, group, sync_op, use_calc_stream): + group = collective._get_default_group() if group is None else group + if use_calc_stream: + return group.process_group.recv_on_calc_stream(tensor, src) + + task = group.process_group.recv(tensor, src, sync_op) + if sync_op: + task.wait() + + return task + + +def recv(tensor, src=0, group=None, sync_op=True, use_calc_stream=False): + """ + + Receive a tensor from the source device. + + Args: + tensor (Tensor): The tensor to receive. Support float16, float32, float64, int32, int64, int8, uint8 or bool as its data type. + src (int, optional): Rank of the source device. If none is given, use `0` as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + task = dist.stream.send(data, dst=1, sync_op=False) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.recv(data, src=0, sync_op=False) + task.wait() + out = data.numpy() + # [[4, 5, 6], [4, 5, 6]] (2 GPUs) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be True in sync op behavior.") + + if framework.in_dygraph_mode(): + return _recv_in_dygraph(tensor, src, group, sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.recv is only supported in dygraph mode now.") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f7f5c884743d3bd1332e9679c45ff52c868b77 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +from paddle.distributed.communication.group import _get_global_group +from paddle.distributed.communication.reduce import _get_reduce_op, ReduceOp + + +def _reduce_in_dygraph(tensor, dst, op, group, sync_op, use_calc_stream): + op_type = _get_reduce_op(op, "reduce") + group = _get_global_group() if group is None else group + if use_calc_stream: + return group.process_group.reduce_on_calc_stream(tensor, dst, op_type) + + task = group.process_group.reduce(tensor, dst, op_type, sync_op) + if sync_op: + task.wait() + + return task + + +def reduce(tensor, + dst=0, + op=ReduceOp.SUM, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Perform specific reduction (for example, sum, max) on a tensor across devices and send to the destintion device. + + Args: + tensor (Tensor): The input tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + dst (int, optional): Rank of the destination device. If none is given, use `0` as default. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The reduction used. If none is given, use ReduceOp.SUM as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.reduce(data, dst=0, sync_op=False) + task.wait() + out = data.numpy() + # [[5, 7, 9], [5, 7, 9]] (2 GPUs, out for rank 0) + # [[1, 2, 3], [1, 2, 3]] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + return _reduce_in_dygraph(tensor, dst, op, group, sync_op, + use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.reduce is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce_scatter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce_scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..71fc93478448fcd51e55a72951505cac22a790a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/reduce_scatter.py @@ -0,0 +1,215 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.fluid.framework as framework +from paddle.distributed.communication.group import _get_global_group +from paddle.distributed.communication.reduce import _get_reduce_op, ReduceOp + + +def _check_tensor_shape(tensor, shape, nranks=1): + expect_shape = list(shape) + expect_shape[0] //= nranks + if list(tensor.shape) != expect_shape: + raise RuntimeError( + "The in_tensor for reduce_scatter is not correctly-sized.") + + +def _check_tensor_list_shape(tensor_list, shape, nranks=1): + if len(tensor_list) != nranks: + raise RuntimeError( + f"The tensor_list for reduce_scatter is not correctly-sized.") + for tensor in tensor_list: + if tensor.shape != shape: + raise RuntimeError( + f"The tensor_list for reduce_scatter is not correctly-sized.") + + +def _reduce_scatter_tensor_in_dygraph(out_tensor, + in_tensor, + op, + group, + sync_op, + use_calc_stream, + caller="reduce_scatter"): + op_type = _get_reduce_op(op, caller) + group = _get_global_group() if group is None else group + + _check_tensor_shape(out_tensor, in_tensor.shape, group.nranks) + + if use_calc_stream: + return group.process_group.reduce_scatter_tensor_on_calc_stream( + in_tensor, out_tensor, op_type) + + task = group.process_group.reduce_scatter_tensor(in_tensor, out_tensor, + op_type, sync_op) + if sync_op: + task.wait() + + return task + + +def _reduce_scatter_in_dygraph(tensor, tensor_list, op, group, sync_op, + use_calc_stream): + op_type = _get_reduce_op(op, "reduce_scatter") + group = _get_global_group() if group is None else group + + _check_tensor_list_shape(tensor_list, tensor.shape, group.nranks) + + if use_calc_stream: + return group.process_group.reduce_scatter_on_calc_stream( + tensor_list, tensor, op_type) + + task = group.process_group.reduce_scatter(tensor_list, tensor, op_type, + sync_op) + if sync_op: + task.wait() + + return task + + +def reduce_scatter(tensor, + tensor_or_tensor_list, + op=ReduceOp.SUM, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Reduce, then scatter a tensor (or a tensor list) across devices. + + Args: + tensor (Tensor): The output tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + tensor_list (List[Tensor]]): The input to scatter. + If it is a tensor, it should be correctly-sized. If it is a list, it should contain correctly-sized tensors. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The reduction used. If none is given, use ReduceOp.SUM as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data1 = paddle.to_tensor([0, 1]) + data2 = paddle.to_tensor([2, 3]) + else: + data1 = paddle.to_tensor([4, 5]) + data2 = paddle.to_tensor([6, 7]) + dist.stream.reduce_scatter(data1, [data1, data2]) + out = data1.numpy() + # [4, 6] (2 GPUs, out for rank 0) + # [8, 10] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + if paddle.is_tensor(tensor_or_tensor_list): + return _reduce_scatter_tensor_in_dygraph(tensor, + tensor_or_tensor_list, op, + group, sync_op, + use_calc_stream) + else: + return _reduce_scatter_in_dygraph(tensor, tensor_or_tensor_list, op, + group, sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.reduce_scatter is only supported in dygraph mode now." + ) + + +def _reduce_scatter_base(out_tensor, + in_tensor, + op=ReduceOp.SUM, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Reduce, then scatter a flattened tensor across devices. + + Args: + out_tensor (Tensor): The output tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32 or int64 as the input data type. + in_tensor (Tensor): The input tensor to reduce and scatter. + op (ReduceOp.SUM|ReduceOp.MAX|ReduceOp.MIN|ReduceOp.PROD, optional): The reduction used. If none is given, use ReduceOp.SUM as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API will be deprecated in the future, and only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data1 = paddle.to_tensor([7, 8, 9]) + data2 = paddle.to_tensor([10, 11, 12]) + dist.stream.scatter(data1, src=1) + else: + data1 = paddle.to_tensor([1, 2, 3]) + data2 = paddle.to_tensor([4, 5, 6]) + dist.stream.scatter(data1, [data1, data2], src=1) + out = data1.numpy() + # [1, 2, 3] (2 GPUs, out for rank 0) + # [4, 5, 6] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if framework.in_dygraph_mode(): + return _reduce_scatter_tensor_in_dygraph(out_tensor, in_tensor, op, + group, sync_op, + use_calc_stream, + "_reduce_scatter_base") + + raise RuntimeError( + "paddle.distributed.stream._reduce_scatter_base is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/scatter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/scatter.py new file mode 100644 index 0000000000000000000000000000000000000000..ee75583d1614483c679a58b4cb56185100448072 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/scatter.py @@ -0,0 +1,161 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _check_tensor_shape(tensor, shape, nranks=1): + expect_shape = list(shape) + expect_shape[0] //= nranks + if list(tensor.shape) != expect_shape: + raise RuntimeError("The in_tensor for scatter is not correctly-sized.") + + +def _check_tensor_list_shape(tensor_list, shape, nranks=1): + if len(tensor_list) != nranks: + raise RuntimeError( + f"The tensor_list for scatter is not correctly-sized.") + for tensor in tensor_list: + if tensor.shape != shape: + raise RuntimeError( + f"The tensor_list for scatter is not correctly-sized.") + + +def _scatter_tensor_in_dygraph(out_tensor, in_tensor, src, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + src_rank = group.get_group_rank(src) + if src_rank == -1: + raise RuntimeError("Src rank out of group.") + + nranks = group.nranks + rank = paddle.distributed.get_rank() + if rank == src_rank: + _check_tensor_shape(out_tensor, in_tensor.shape, nranks) + + if use_calc_stream: + return group.process_group.scatter_tensor_on_calc_stream( + in_tensor, out_tensor, src) + + task = group.process_group.scatter_tensor(in_tensor, out_tensor, src, + sync_op) + if sync_op: + task.wait() + + return task + + +def _scatter_in_dygraph(tensor, tensor_list, src, group, sync_op, + use_calc_stream): + group = collective._get_default_group() if group is None else group + + src_rank = group.get_group_rank(src) + if src_rank == -1: + raise RuntimeError("Src rank out of group.") + + nranks = group.nranks + rank = paddle.distributed.get_rank() + if rank == src_rank: + if len(tensor_list) == 0: + raise RuntimeError( + "The tensor_list should not be empty on src rank.") + _check_tensor_list_shape(tensor_list, tensor.shape, nranks) + else: + tensor_list = [tensor for _ in range(nranks)] + + if use_calc_stream: + return group.process_group.scatter_on_calc_stream( + tensor_list, tensor, src) + + task = group.process_group.scatter(tensor_list, tensor, src, sync_op) + if sync_op: + task.wait() + + return task + + +def scatter(tensor, + tensor_or_tensor_list=None, + src=0, + group=None, + sync_op=True, + use_calc_stream=False): + """ + + Scatter a tensor (or a tensor list) across devices. + + Args: + tensor (Tensor): The output tensor on each rank. The result will overwrite this tenor after communication. Support + float16, float32, float64, int32, int64, int8, uint8 or bool as the input data type. + tensor_or_tensor_list (Union[Tensor, List[Tensor]]): The input to scatter (default is `None`, must be specified on the source rank). + If it is a tensor, it should be correctly-sized. If it is a list, it should contain correctly-sized tensors. + src (int, optional): Rank of the source device. If none is given, use `0` as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + if dist.get_rank() == 0: + data1 = paddle.to_tensor([7, 8, 9]) + data2 = paddle.to_tensor([10, 11, 12]) + dist.stream.scatter(data1, src=1) + else: + data1 = paddle.to_tensor([1, 2, 3]) + data2 = paddle.to_tensor([4, 5, 6]) + dist.stream.scatter(data1, [data1, data2], src=1) + out = data1.numpy() + # [1, 2, 3] (2 GPUs, out for rank 0) + # [4, 5, 6] (2 GPUs, out for rank 1) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be true in sync op behavior.") + + if tensor_or_tensor_list is None: + raise RuntimeError("The input should be specified.") + + if framework.in_dygraph_mode(): + if paddle.is_tensor(tensor_or_tensor_list): + return _scatter_tensor_in_dygraph(tensor, tensor_or_tensor_list, + src, group, sync_op, + use_calc_stream) + else: + return _scatter_in_dygraph(tensor, tensor_or_tensor_list, src, + group, sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.scatter is only supported in dygraph mode now." + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/send.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/send.py new file mode 100644 index 0000000000000000000000000000000000000000..41ec2c0141b1227933a4df5c523455f2e02a8e9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/communication/stream/send.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022 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. + +import paddle.fluid.framework as framework +from paddle.distributed import collective + + +def _send_in_dygraph(tensor, dst, group, sync_op, use_calc_stream): + group = collective._get_default_group() if group is None else group + if use_calc_stream: + return group.process_group.send_on_calc_stream(tensor, dst) + + task = group.process_group.send(tensor, dst, sync_op) + if sync_op: + task.wait() + + return task + + +def send(tensor, dst=0, group=None, sync_op=True, use_calc_stream=False): + """ + + Send a tensor to the destination device. + + Args: + tensor (Tensor): The tensor to send. Support float16, float32, float64, int32, int64, int8, uint8 or bool as its data type. + dst (int, optional): Rank of the destination device. If none is given, use `0` as default. + group (Group, optional): Communicate in which group. If none is given, use the global group as default. + sync_op (bool, optional): Indicate whether the communication is sync or not. If none is given, use true as default. + use_calc_stream (bool, optional): Indicate whether the communication is done on calculation stream. If none is given, use false as default. This + option is designed for high performance demand, be careful to turn it on except you are clearly know its meaning. + + Returns: + Return a task object. + + Warning: + This API only supports the dygraph mode now. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + local_rank = dist.get_rank() + if local_rank == 0: + data = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + task = dist.stream.send(data, dst=1, sync_op=False) + else: + data = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + task = dist.stream.recv(data, src=0, sync_op=False) + task.wait() + out = data.numpy() + # [[4, 5, 6], [4, 5, 6]] (2 GPUs) + """ + if group is not None and not group.is_member(): + raise RuntimeError( + "The group should not be None and all ranks which invoke this operation should be the member of this group." + ) + + if not sync_op and use_calc_stream: + raise RuntimeError( + "use_calc_stream can only be True in sync op behavior.") + + if framework.in_dygraph_mode(): + return _send_in_dygraph(tensor, dst, group, sync_op, use_calc_stream) + + raise RuntimeError( + "paddle.distributed.stream.send is only supported in dygraph mode now.") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/elastic.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/elastic.py new file mode 100644 index 0000000000000000000000000000000000000000..933550b75ad5b5a9e13eb5767e3e4889502de52f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/elastic.py @@ -0,0 +1,78 @@ +# Copyright (c) 2021 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. + +import argparse +import six +import os + + +class Command(object): + + def __init__(self, server, name): + import etcd3 + + srv, port = server.split(':') + self.etcd = etcd3.client(host=srv, port=port) + + self.prefix = "/paddle/" + name + self.node_prefix = self.prefix + '/nodes' + self.np_path = self.prefix + '/np' + + def set_np(self, np): + self.etcd.put(self.np_path, six.b('{}'.format(np))) + + def scale_np(self, np): + if self.etcd.get(self.np_path)[0] != None: + self.set_np(np) + return True + return False + + def clean(self): + self.etcd.delete_prefix(self.prefix) + + def close(self): + self.etcd.close() + + +if __name__ == '__main__': + + parser = argparse.ArgumentParser(description='Elastic Command') + parser.add_argument("--elastic_server", + type=str, + help="etcd server host:port") + parser.add_argument("--job_id", type=str, help="job unique id") + parser.add_argument( + "--np", + type=str, + help="job pod/node number, need to be 'MIN' or 'MIN:MAX' format") + parser.add_argument("action", type=str, help="action to take") + + args = parser.parse_args() + + server = args.elastic_server or os.getenv('PADDLE_ELASTIC_SERVER') + name = args.job_id or os.getenv('PADDLE_ELASTIC_JOB_ID') + + np = int(args.np.split(":")[0]) or int(os.getenv('PADDLE_ELASTIC_NP', 0)) + + cmd = Command(server, name) + + if args.action == "scale": + cmd.scale_np(np) + + if args.action == "clean": + cmd.clean() + + print("action {} done".format(args.action)) + + cmd.close() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/entry_attr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/entry_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..1b3e40ec346e6c9fda68e2cef71eeb58b02ff6cc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/entry_attr.py @@ -0,0 +1,181 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +__all__ = [] + + +class EntryAttr(object): + """ + Entry Config for paddle.static.nn.sparse_embedding with Parameter Server. + + Examples: + .. code-block:: python + + import paddle + + sparse_feature_dim = 1024 + embedding_size = 64 + + entry = paddle.distributed.ProbabilityEntry(0.1) + + input = paddle.static.data(name='ins', shape=[1], dtype='int64') + + emb = paddle.static.nn.sparse_embedding(( + input=input, + size=[sparse_feature_dim, embedding_size], + is_test=False, + entry=entry, + param_attr=paddle.ParamAttr(name="SparseFeatFactors", + initializer=paddle.nn.initializer.Uniform())) + + """ + + def __init__(self): + self._name = None + + def _to_attr(self): + """ + Returns the attributes of this parameter. + + Returns: + Parameter attributes(map): The attributes of this parameter. + """ + raise NotImplementedError("EntryAttr is base class") + + +class ProbabilityEntry(EntryAttr): + """ + Examples: + .. code-block:: python + + import paddle + + sparse_feature_dim = 1024 + embedding_size = 64 + + entry = paddle.distributed.ProbabilityEntry(0.1) + + input = paddle.static.data(name='ins', shape=[1], dtype='int64') + + emb = paddle.static.nn.sparse_embedding(( + input=input, + size=[sparse_feature_dim, embedding_size], + is_test=False, + entry=entry, + param_attr=paddle.ParamAttr(name="SparseFeatFactors", + initializer=paddle.nn.initializer.Uniform())) + + + """ + + def __init__(self, probability): + super(ProbabilityEntry, self).__init__() + + if not isinstance(probability, float): + raise ValueError("probability must be a float in (0,1)") + + if probability <= 0 or probability >= 1: + raise ValueError("probability must be a float in (0,1)") + + self._name = "probability_entry" + self._probability = probability + + def _to_attr(self): + return ":".join([self._name, str(self._probability)]) + + +class CountFilterEntry(EntryAttr): + """ + Examples: + .. code-block:: python + + import paddle + + sparse_feature_dim = 1024 + embedding_size = 64 + + entry = paddle.distributed.CountFilterEntry(10) + + input = paddle.static.data(name='ins', shape=[1], dtype='int64') + + emb = paddle.static.nn.sparse_embedding(( + input=input, + size=[sparse_feature_dim, embedding_size], + is_test=False, + entry=entry, + param_attr=paddle.ParamAttr(name="SparseFeatFactors", + initializer=paddle.nn.initializer.Uniform())) + + """ + + def __init__(self, count_filter): + super(CountFilterEntry, self).__init__() + + if not isinstance(count_filter, int): + raise ValueError( + "count_filter must be a valid integer greater than 0") + + if count_filter < 0: + raise ValueError( + "count_filter must be a valid integer greater or equal than 0") + + self._name = "count_filter_entry" + self._count_filter = count_filter + + def _to_attr(self): + return ":".join([self._name, str(self._count_filter)]) + + +class ShowClickEntry(EntryAttr): + """ + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + sparse_feature_dim = 1024 + embedding_size = 64 + + shows = paddle.static.data(name='show', shape=[1], dtype='int64') + clicks = paddle.static.data(name='click', shape=[1], dtype='int64') + input = paddle.static.data(name='ins', shape=[1], dtype='int64') + + entry = paddle.distributed.ShowClickEntry("show", "click") + + emb = paddle.static.nn.sparse_embedding( + input=input, + size=[sparse_feature_dim, embedding_size], + is_test=False, + entry=entry, + param_attr=paddle.ParamAttr(name="SparseFeatFactors", + initializer=paddle.nn.initializer.Uniform())) + + + """ + + def __init__(self, show_name, click_name): + super(ShowClickEntry, self).__init__() + + if not isinstance(show_name, str) or not isinstance(click_name, str): + raise ValueError("show_name click_name must be a str") + + self._name = "show_click_entry" + self._show_name = show_name + self._click_name = click_name + + def _to_attr(self): + return ":".join([self._name, self._show_name, self._click_name]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b75d84edf29b289be02c31a71def6d6b6652eabe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/__init__.py @@ -0,0 +1,97 @@ +# 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. + +# TODO: define distributed api under this directory, +from .base.role_maker import Role # noqa: F401 +from .base.role_maker import UserDefinedRoleMaker # noqa: F401 +from .base.role_maker import PaddleCloudRoleMaker # noqa: F401 +from .base.distributed_strategy import DistributedStrategy # noqa: F401 +from .base.util_factory import UtilBase # noqa: F401 +from .dataset import DatasetBase # noqa: F401 +from .dataset import InMemoryDataset # noqa: F401 +from .dataset import QueueDataset # noqa: F401 +from .dataset import FileInstantDataset # noqa: F401 +from .dataset import BoxPSDataset # noqa: F401 +from .data_generator.data_generator import MultiSlotDataGenerator # noqa: F401 +from .data_generator.data_generator import MultiSlotStringDataGenerator # noqa: F401 +from . import metrics # noqa: F401 +from .base.topology import CommunicateTopology +from .base.topology import HybridCommunicateGroup # noqa: F401 +from .fleet import Fleet +from .model import distributed_model +from .optimizer import distributed_optimizer +from .scaler import distributed_scaler +from .utils import log_util + +__all__ = [ #noqa + "CommunicateTopology", "UtilBase", "HybridCommunicateGroup", + "MultiSlotStringDataGenerator", "UserDefinedRoleMaker", + "DistributedStrategy", "Role", "MultiSlotDataGenerator", + "PaddleCloudRoleMaker", "Fleet" +] + +fleet = Fleet() +_final_strategy = fleet._final_strategy +_get_applied_meta_list = fleet._get_applied_meta_list +_get_applied_graph_list = fleet._get_applied_graph_list +init = fleet.init +is_first_worker = fleet.is_first_worker +worker_index = fleet.worker_index +worker_num = fleet.worker_num +node_num = fleet.node_num +rank = fleet.worker_index +nranks = fleet.worker_num +world_size = fleet.worker_num +# device id in current trainer +local_device_ids = fleet.local_device_ids +# device ids in world +world_device_ids = fleet.world_device_ids +# rank in node +local_rank = fleet.local_rank +rank_in_node = local_rank +is_worker = fleet.is_worker +is_coordinator = fleet.is_coordinator +init_coordinator = fleet.init_coordinator +make_fl_strategy = fleet.make_fl_strategy +get_fl_client = fleet.get_fl_client +worker_endpoints = fleet.worker_endpoints +server_num = fleet.server_num +server_index = fleet.server_index +server_endpoints = fleet.server_endpoints +is_server = fleet.is_server +util = UtilBase() +barrier_worker = fleet.barrier_worker +init_worker = fleet.init_worker +init_server = fleet.init_server +run_server = fleet.run_server +stop_worker = fleet.stop_worker +distributed_optimizer = distributed_optimizer +save_inference_model = fleet.save_inference_model +save_persistables = fleet.save_persistables +save_cache_model = fleet.save_cache_model +check_save_pre_patch_done = fleet.check_save_pre_patch_done +save_one_table = fleet.save_one_table +save_dense_params = fleet.save_dense_params +load_model = fleet.load_model +load_inference_model = fleet.load_inference_model +load_one_table = fleet.load_one_table +minimize = fleet.minimize +distributed_model = distributed_model +shrink = fleet.shrink +get_hybrid_communicate_group = fleet.get_hybrid_communicate_group +distributed_scaler = distributed_scaler +set_log_level = log_util.set_log_level +get_log_level_code = log_util.get_log_level_code +get_log_level_name = log_util.get_log_level_name +from .. import auto_parallel as auto diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/ascend_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/ascend_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6c210165ec15c0b73efd370a399b386b84f484 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/ascend_utils.py @@ -0,0 +1,132 @@ +# Copyright (c) 2021 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. + +import os +import json +import paddle +from paddle.distributed.fleet.launch_utils import get_cluster, logger, get_host_name_ip, DeviceMode + +__all__ = [] + + +def _get_ascend_rankfile(rank_table_file_path): + """ + Args: + rank_table_file_path: ascend npu rank file json + { + "status": "completed", + "version": "1.0", + "server_count": "2", + "server_list": [ + { + "server_id": "192.168.24.217", + "device": [ + { + "device_id": "0", + "device_ip": "192.1.184.23", + "rank_id": "0" + }, + { + "device_id": "1", + "device_ip": "192.2.21.93", + "rank_id": "1" + } + ] + }, + { + "server_id": "192.168.26.177", + "device": [ + { + "device_id": "0", + "device_ip": "192.1.94.132", + "rank_id": "2" + }, + { + "device_id": "1", + "device_ip": "192.2.94.30", + "rank_id": "3" + } + ] + } + ] + } + + Returns: + node_ips: node ip list + device_count: number of npu per machine + """ + json_data = None + with open(rank_table_file_path) as json_file: + json_data = json.load(json_file) + + node_ips = [] + device_count = 0 + server_list = json_data['server_list'] + for server in server_list: + device_list = server['device'] + device_count = len(device_list) + if os.getenv("FLAGS_MODELARTS", None): + nodes = os.getenv("DLS_TASK_NUMBER", None) + assert nodes is not None, "DLS_TASK_NUMBER didn't set!" + for node in range(int(nodes)): + node_ip = os.getenv("VC_CUSTOM{}_HOSTS".format(node), None) + assert node_ip is not None, "VC_CUSTOM{}_HOSTS didn't set!".format( + node) + node_ips.append(node_ip) + return node_ips, device_count + node_ips.append(server['server_id']) + return node_ips, device_count + + +def get_cloud_cluster(rank_table_file=None, + device_mode=DeviceMode.ASCEND_NPU, + start_port=6070): + """ + Args: + rank_table_file: string, ascend npu rank file path + device_mode: DeviceMode(Int) + start_port: the start port of current runtime env + """ + if rank_table_file: + # multi trainers + node_ips, device_count = _get_ascend_rankfile(rank_table_file) + if len(node_ips) == 1: + node_ip = node_ips[0] + else: + node_index = os.environ.get("PADDLE_TRAINER_ID") + node_ip = None + if node_index: + node_ip = node_ips[int(node_index)] + else: + _, node_ip = get_host_name_ip() + + assert node_ip in node_ips, "Can't find your local ip {%s} in node_ips: {%s}" \ + % (node_ip, node_ips) + else: + # single trainer (single ascend card) + node_ips = ["127.0.0.1"] + node_ip = node_ips[0] + device_count = 1 + + devices_per_proc = [str(x) for x in range(device_count)] + free_ports = [ + x for x in range(start_port, start_port + len(devices_per_proc)) + ] + + trainer_endpoints = [] + for ip in node_ips: + trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports]) + + return get_cluster(node_ips, node_ip, trainer_endpoints, device_mode, + devices_per_proc) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abf198b97e6e818e1fbe59006f98492640bcee54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/distributed_strategy.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/distributed_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..2cfded8c96013d5b32a3943f7f93cd6b49b9e24a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/distributed_strategy.py @@ -0,0 +1,2545 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +import paddle +from paddle.distributed.fleet.proto import distributed_strategy_pb2 +from paddle.fluid.framework import Variable, set_flags, core, _global_flags +from paddle.fluid.wrapped_decorator import wrap_decorator +import google.protobuf.text_format +import google.protobuf + +__all__ = [] + +non_auto_func_called = True + + +def __non_auto_func_called__(func): + def __impl__(*args, **kwargs): + global non_auto_func_called + non_auto_func_called = False + return func(*args, **kwargs) + + return __impl__ + + +is_strict_auto = wrap_decorator(__non_auto_func_called__) + + +def get_msg_dict(msg): + res_dict = {} + fields = msg.DESCRIPTOR.fields + for f in fields: + res_dict[f.name] = getattr(msg, f.name) + return res_dict + + +def assign_configs_value(msg, config): + fields = msg.DESCRIPTOR.fields + for key in config: + for f in fields: + if key == f.name: + # LABEL_OPTIONAL = 1 + # LABEL_REPEATED = 3 + # LABEL_REQUIRED = 2 + if f.label == 3: + getattr(msg, f.name).extend(config[f.name]) + elif f.label == 1 or f.label == 2: + setattr(msg, f.name, config[f.name]) + + +def check_configs_key(msg, config, field_name): + key_list = msg.DESCRIPTOR.fields_by_name.keys() + for key in config: + assert key in key_list, "key:{} not in {}".format(key, field_name) + + +class DistributedJobInfo(object): + """ + DistributedJobInfo will serialize all distributed training information + Just for inner use: 1) debug 2) replicate experiments + """ + + def __init__(self): + self.job_info = distributed_strategy_pb2.DistributedJobInfo() + + def _set_worker_num(self, worker_num): + self.job_info.worker_num = worker_num + + def _set_server_num(self, server_num): + self.job_info.server_num = server_num + + def _set_worker_ips(self, worker_ips): + self.job_info.worker_ips.extend(worker_ips) + + def _set_server_endpoints(self, server_endpoints): + self.job_info.server_endpoints.extend(server_endpoints) + + def _set_origin_startup(self, origin_startup_prog): + self.job_info.origin_startup = str(origin_startup_prog) + + def _set_origin_main(self, origin_main_prog): + self.job_info.origin_main = str(origin_main_prog) + + def _distributed_main(self, distributed_main_prog): + self.job_info.distributed_main = str(distributed_main_prog) + + def _optimizer_name(self, optimizer_name): + self.job_info.optimizer_name = optimizer_name + + def _set_distributed_strategy(self, dist_strategy): + self.job_info.strategy = dist_strategy + + +ReduceStrategyFluid = paddle.fluid.BuildStrategy.ReduceStrategy +ReduceStrategyFleet = int + + +class DistributedStrategy(object): + __lock_attr = False + + def __init__(self): + """ + + DistributedStrategy is the main configuration entry for distributed training of Paddle. + All of the distributed training configurations can be configured in DistributedStrategy, + such as automatic mixed precision (AMP), Layer-wise Adaptive Rate Scaling (LARS), + asynchronous update parameter server(ASGD), etc. + + DistributedStrategy can be serialized into protobuf file or deserialized from protobuf file + + Users who run local training usually configure BuildStrategy and ExecutionStrategy, and + DistributedStrategy supports configurations from BuildStrategy and ExecutionStrategy + + """ + self.strategy = distributed_strategy_pb2.DistributedStrategy() + + # Set the default values of the following flags to the ones set by users + key = 'FLAGS_cudnn_batchnorm_spatial_persistent' + if _global_flags().is_public(key): + self.strategy.cudnn_batchnorm_spatial_persistent = bool( + _global_flags()[key] + ) + key = 'FLAGS_conv_workspace_size_limit' + if _global_flags().is_public(key): + self.strategy.conv_workspace_size_limit = int(_global_flags()[key]) + key = 'FLAGS_cudnn_exhaustive_search' + if _global_flags().is_public(key): + self.strategy.cudnn_exhaustive_search = bool(_global_flags()[key]) + key = 'FLAGS_sync_nccl_allreduce' + if _global_flags().is_public(key): + self.strategy.sync_nccl_allreduce = bool(_global_flags()[key]) + + self.__lock_attr = True + + def __setattr__(self, key, value): + if self.__lock_attr and not hasattr(self, key): + raise TypeError( + "%s is not a attribute of %s" % (key, self.__class__.__name__) + ) + object.__setattr__(self, key, value) + + def save_to_prototxt(self, output): + """ + + Serialize current DistributedStrategy to string and save to output file + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.dgc = True + strategy.recompute = True + strategy.recompute_configs = {"checkpoints": ["x"]} + strategy.save_to_prototxt("dist_strategy.prototxt") + + """ + with open(output, "w") as fout: + fout.write(str(self.strategy)) + + def load_from_prototxt(self, pb_file): + """ + + Load from prototxt file for DistributedStrategy initialization + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.load_from_prototxt("dist_strategy.prototxt") + + """ + with open(pb_file, 'r') as f: + self.strategy = google.protobuf.text_format.Merge( + str(f.read()), self.strategy + ) + + @property + def execution_strategy(self): + """ + Configure ExecutionStrategy for DistributedStrategy + + Examples: + .. code-block:: python + + import paddle + exe_strategy = paddle.static.ExecutionStrategy() + exe_strategy.num_threads = 10 + exe_strategy.num_iteration_per_drop_scope = 10 + exe_strategy.num_iteration_per_run = 10 + + strategy = paddle.distributed.fleet.DistributedStrategy() + strategy.execution_strategy = exe_strategy + + """ + execution_strategy = paddle.fluid.ExecutionStrategy() + fields = self.strategy.execution_strategy.DESCRIPTOR.fields + for f in fields: + setattr( + execution_strategy, + f.name, + getattr(self.strategy.execution_strategy, f.name), + ) + return execution_strategy + + @execution_strategy.setter + @is_strict_auto + def execution_strategy(self, strategy): + fields = self.strategy.execution_strategy.DESCRIPTOR.fields + for f in fields: + setattr( + self.strategy.execution_strategy, + f.name, + getattr(strategy, f.name), + ) + + @property + def build_strategy(self): + """ + + Configure BuildStrategy for DistributedStrategy + Note that the properties of BuildStrategy are valid in DistributedStrategy + only if the property is non-distributed strategy. + + Examples: + .. code-block:: python + + import paddle + build_strategy = paddle.static.BuildStrategy() + build_strategy.enable_sequential_execution = True + build_strategy.fuse_elewise_add_act_ops = True + build_strategy.fuse_bn_act_ops = True + build_strategy.enable_auto_fusion = True + build_strategy.fuse_relu_depthwise_conv = True + build_strategy.fuse_broadcast_ops = True + build_strategy.fuse_all_optimizer_ops = True + build_strategy.enable_inplace = True + + strategy = paddle.distributed.fleet.DistributedStrategy() + strategy.build_strategy = build_strategy + + """ + + build_strategy = paddle.fluid.BuildStrategy() + fields = self.strategy.build_strategy.DESCRIPTOR.fields + for f in fields: + value = getattr(self.strategy.build_strategy, f.name) + if f.name == 'reduce_strategy': + value = ReduceStrategyFluid(value) + setattr(build_strategy, f.name, value) + return build_strategy + + @build_strategy.setter + @is_strict_auto + def build_strategy(self, strategy): + fields = self.strategy.build_strategy.DESCRIPTOR.fields + for f in fields: + if f.label == 1 or f.label == 2: # optional and required field + value = getattr(strategy, f.name) + if f.name == 'reduce_strategy': + value = ReduceStrategyFleet(value) + setattr(self.strategy.build_strategy, f.name, value) + elif f.label == 3: # repeated field + getattr(self.strategy.build_strategy, f.name).extend( + getattr(strategy, f.name) + ) + + @property + def gradient_scale_configs(self): + """ + + Set the strategy of gradient scale + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.gradient_scale_configs = {'scale_strategy': 'avg'} + + Note that, strategy must be in 'avg', 'sum' or 'customized' + + """ + return get_msg_dict(self.strategy.gradient_scale_configs) + + @gradient_scale_configs.setter + @is_strict_auto + def gradient_scale_configs(self, config): + check_configs_key( + self.strategy.gradient_scale_configs, + config, + 'gradient_scale_configs', + ) + assign_configs_value(self.strategy.gradient_scale_configs, config) + + @property + def a_sync(self): + """ + + Indicating whether we are using asynchronous stocastic gradient descent updates + for training. This property is valid when we are using parameter server training, + which is implied by setting approperate RoleMaker + Default value: True + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + role_maker = fleet.PaddleCloudRoleMaker() + fleet.init(role_maker) + + strategy = fleet.DistributedStrategy() + strategy.a_sync = True # by default this is True + + # code block for defining loss and local optimizer + # sgd = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.a_sync + + @a_sync.setter + @is_strict_auto + def a_sync(self, flag): + if isinstance(flag, bool): + self.strategy.a_sync = flag + self.a_sync_configs = {"k_steps": 0} + else: + raise ValueError( + "The type of `flag` is invalid, expected type is bool, but received {}".format( + type(flag) + ) + ) + + @property + def a_sync_configs(self): + """ + + Set a_sync update configurations. In general, asynchronous parameter server + training has serveral configurable settings that can be configured through + a dict. + + **Notes**: + k_step(int): number of local optimization updates before communication + + max_merge_var_num(int): maximum number of merged gradients before communication + + send_queue_size(int): a buffer size of worker communication + + independent_recv_thread(bool): if we are using independent recv thread for communication + + thread_pool_size(int): number of thread pool + + send_wait_times(int): waiting time for sending gradients + + runtime_split_send_recv(bool): if we are using Tensor split for send and recv during runtime + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + role_maker = fleet.PaddleCloudRoleMaker() + fleet.init(role_maker) + + strategy = fleet.DistributedStrategy() + strategy.a_sync = True # by default this is True + configs = {"k_steps": 1024, "send_queue_size": 32} + strategy.a_sync_configs = configs + + # code block for defining loss and local optimizer + # sgd = fleet.distributed_optimizer(optimizer, strategy) + + """ + return get_msg_dict(self.strategy.a_sync_configs) + + @a_sync_configs.setter + @is_strict_auto + def a_sync_configs(self, configs): + check_configs_key( + self.strategy.a_sync_configs, configs, "a_sync_configs" + ) + assign_configs_value(self.strategy.a_sync_configs, configs) + + @property + def trainer_desc_configs(self): + """ + + Set trainer desc configurations. + + **Notes**: + dump_fields_path(str): the path of dump fields + + dump_fields(list(str)): the fields that you want to dump + + dump_param(list(str)): the param that you want to dump + + stat_var_names(list(str)): + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + role_maker = fleet.PaddleCloudRoleMaker() + fleet.init(role_maker) + + strategy = fleet.DistributedStrategy() + configs = {"dump_fields_path": "./dump_data", "dump_fields": ["xxx", "yyy"]} + strategy.trainer_desc_configs = configs + + # code block for defining loss and local optimizer + # sgd = fleet.distributed_optimizer(optimizer, strategy) + + """ + return get_msg_dict(self.strategy.trainer_desc_configs) + + @property + def adam_d2sum(self): + """ + + set adam_d2sum + Default value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + role_maker = fleet.PaddleCloudRoleMaker() + fleet.init(role_maker) + + strategy = fleet.DistributedStrategy() + strategy.adam_d2sum = True # by default this is False + + # code block for defining loss and local optimizer + # sgd = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.adam_d2sum + + @adam_d2sum.setter + @is_strict_auto + def adam_d2sum(self, flag): + if isinstance(flag, bool): + self.strategy.adam_d2sum = flag + else: + raise ValueError( + "The type of `flag` is invalid, expected type is bool, but received {}".format( + type(flag) + ) + ) + + @trainer_desc_configs.setter + @is_strict_auto + def trainer_desc_configs(self, configs): + check_configs_key( + self.strategy.trainer_desc_configs, configs, "trainer_desc_configs" + ) + assign_configs_value(self.strategy.trainer_desc_configs, configs) + + @property + def fs_client_param(self): + """ + + Set fs client configurations. + + Note: + uri(str): the uri of fs client + + user(str): the user_name of fs client + + passwd(str): the passwd of fs client + + hadoop_bin(str): + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + role_maker = fleet.PaddleCloudRoleMaker() + fleet.init(role_maker) + strategy = fleet.DistributedStrategy() + configs = {"uri": "xxx", "user": "xxx", passwd: "xxx"} + strategy.fs_client_param = configs + # code block for defining loss and local optimizer + # sgd = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.fs_client_param + + @fs_client_param.setter + @is_strict_auto + def fs_client_param(self, configs): + check_configs_key( + self.strategy.fs_client_param, configs, "fs_client_param" + ) + assign_configs_value(self.strategy.fs_client_param, configs) + + @property + def sparse_table_configs(self): + return self.strategy.downpour_table_param + + @sparse_table_configs.setter + @is_strict_auto + def sparse_table_configs(self, configs): + from google.protobuf.descriptor import FieldDescriptor + + table_param = self.strategy.downpour_table_param + + def set_table_config(msg, config_name, configs, index=0): + for field in msg.DESCRIPTOR.fields: + name = config_name + "." + field.name + if field.type == FieldDescriptor.TYPE_MESSAGE: + # print("message:", name) + if field.label == FieldDescriptor.LABEL_REPEATED: + if name + ".num" not in configs: + continue + num = configs[name + ".num"] + # print("message num:", name, num) + for i in range(num): + data = getattr(msg, field.name).add() + set_table_config(data, name, configs, i) + else: + set_table_config( + getattr(msg, field.name), name, configs + ) + else: + # print("not message:", name) + if name not in configs: + continue + if field.label == FieldDescriptor.LABEL_REPEATED: + getattr(msg, field.name).extend(configs[name]) + else: + if type(configs[name]) == list: + setattr(msg, field.name, configs[name][index]) + else: + setattr(msg, field.name, configs[name]) + + if not configs: + print("table configs is empty") + else: + for table_name in configs: + table_data = table_param.add() + table_data.table_name = table_name + set_table_config( + table_data, + "table_parameters." + table_name, + configs[table_name], + ) + + @sparse_table_configs.setter + def fleet_desc_configs(self, configs): + support_sparse_key_list = [ + 'sparse_table_class', + 'sparse_compress_in_save', + 'sparse_shard_num', + 'sparse_accessor_class', + 'sparse_learning_rate', + 'sparse_initial_g2sum', + 'sparse_initial_range', + 'sparse_weight_bounds', + 'sparse_fea_dim', + 'sparse_embedx_dim', + 'sparse_embedx_threshold', + 'sparse_nonclk_coeff', + 'sparse_click_coeff', + 'sparse_base_threshold', + 'sparse_delta_threshold', + 'sparse_delta_keep_days', + 'sparse_delete_after_unseen_days', + 'sparse_show_click_decay_rate', + 'sparse_delete_threshold', + 'sparse_converter', + 'sparse_deconverter', + 'sparse_enable_cache', + 'sparse_cache_rate', + 'sparse_cache_file_num', + 'sparse_beta1_decay_rate', + 'sparse_beta2_decay_rate', + 'sparse_ada_epsilon', + 'sparse_optimizer', + 'sparse_ssd_unseenday_threshold', + 'embed_sparse_optimizer', + 'embed_sparse_learning_rate', + 'embed_sparse_weight_bounds', + 'embed_sparse_initial_range', + 'embed_sparse_initial_g2sum', + 'embed_sparse_beta1_decay_rate', + 'embed_sparse_beta2_decay_rate', + 'embedx_sparse_optimizer', + 'embedx_sparse_learning_rate', + 'embedx_sparse_weight_bounds', + 'embedx_sparse_initial_range', + 'embedx_sparse_initial_g2sum', + 'embedx_sparse_beta1_decay_rate', + 'embedx_sparse_beta2_decay_rate', + 'feature_learning_rate', + 'nodeid_slot', + ] + support_sparse_table_class = ['DownpourSparseTable'] + support_sparse_accessor_class = [ + 'DownpourSparseValueAccessor', + 'DownpourCtrAccessor', + 'DownpourCtrDoubleAccessor', + 'DownpourUnitAccessor', + 'DownpourDoubleUnitAccessor', + 'DownpourCtrDymfAccessor', + ] + from google.protobuf.descriptor import FieldDescriptor + + table_param = self.strategy.downpour_table_param + + def add_graph_config(graph, strategy): + graph.feature_learning_rate = strategy.get( + 'feature_learning_rate', 0.05 + ) + graph.nodeid_slot = strategy.get('nodeid_slot', 9008) + + def sparse_optimizer_config(sgd, strategy, prefix): + optimizer_name = strategy.get( + prefix + "sparse_optimizer", "adagrad" + ) + sgd.name = optimizer_name + if optimizer_name == "naive": + sgd.name = "SparseNaiveSGDRule" + sgd.naive.learning_rate = strategy.get( + prefix + 'sparse_learning_rate', 0.05 + ) + sgd.naive.initial_range = strategy.get( + prefix + 'sparse_initial_range', 1e-4 + ) + bounds = strategy.get( + prefix + 'sparse_weight_bounds', [-10, 10] + ) + sgd.naive.weight_bounds.extend(bounds) + elif optimizer_name == "adagrad": + sgd.name = 'SparseAdaGradSGDRule' + sgd.adagrad.learning_rate = strategy.get( + prefix + 'sparse_learning_rate', 0.05 + ) + sgd.adagrad.initial_range = strategy.get( + prefix + 'sparse_initial_range', 1e-4 + ) + if prefix == "embed_": + sgd.adagrad.initial_range = 0 + sgd.adagrad.initial_g2sum = strategy.get( + prefix + 'sparse_initial_g2sum', 3 + ) + bounds = strategy.get( + prefix + 'sparse_weight_bounds', [-10, 10] + ) + sgd.adagrad.weight_bounds.extend(bounds) + elif optimizer_name == "std_adagrad": + sgd.name = 'StdAdaGradSGDRule' + sgd.adagrad.learning_rate = strategy.get( + prefix + 'sparse_learning_rate', 0.05 + ) + sgd.adagrad.initial_range = strategy.get( + prefix + 'sparse_initial_range', 1e-4 + ) + if prefix == "embed_": + sgd.adagrad.initial_range = 0 + sgd.adagrad.initial_g2sum = strategy.get( + prefix + 'sparse_initial_g2sum', 3 + ) + bounds = strategy.get( + prefix + 'sparse_weight_bounds', [-10, 10] + ) + sgd.adagrad.weight_bounds.extend(bounds) + elif optimizer_name == "adam": + sgd.name = 'SparseAdamSGDRule' + sgd.adam.learning_rate = strategy.get( + prefix + 'sparse_learning_rate', 0.001 + ) + sgd.adam.initial_range = strategy.get( + prefix + 'sparse_initial_range', 1e-4 + ) + sgd.adam.beta1_decay_rate = strategy.get( + prefix + 'sparse_beta1_decay_rate', 0.9 + ) + sgd.adam.beta2_decay_rate = strategy.get( + prefix + 'sparse_beta2_decay_rate', 0.999 + ) + sgd.adam.ada_epsilon = strategy.get( + prefix + 'sparse_ada_epsilon', 1e-8 + ) + bounds = strategy.get( + prefix + 'sparse_weight_bounds', [-10, 10] + ) + sgd.adam.weight_bounds.extend(bounds) + elif optimizer_name == "shared_adam": + sgd.name = 'SparseSharedAdamSGDRule' + sgd.adam.learning_rate = strategy.get( + prefix + 'sparse_learning_rate', 0.001 + ) + sgd.adam.initial_range = strategy.get( + prefix + 'sparse_initial_range', 1e-4 + ) + sgd.adam.beta1_decay_rate = strategy.get( + prefix + 'sparse_beta1_decay_rate', 0.9 + ) + sgd.adam.beta2_decay_rate = strategy.get( + prefix + 'sparse_beta2_decay_rate', 0.999 + ) + sgd.adam.ada_epsilon = strategy.get( + prefix + 'sparse_ada_epsilon', 1e-8 + ) + bounds = strategy.get( + prefix + 'sparse_weight_bounds', [-10, 10] + ) + sgd.adam.weight_bounds.extend(bounds) + + def set_sparse_table_config(table_data, config): + for key in config: + if key not in support_sparse_key_list: + raise ValueError("strategy key '%s' not support" % (key)) + table_class = config.get( + "sparse_table_class", "DownpourSparseTable" + ) + if table_class not in support_sparse_table_class: + raise ValueError( + "support sparse_table_class: ['DownpourSparseTable'], but actual %s" + % (table_class) + ) + table_data.table_class = 'MemorySparseTable' + table_data.shard_num = config.get('sparse_shard_num', 1000) + table_data.enable_sparse_table_cache = config.get( + 'sparse_enable_cache', True + ) + table_data.sparse_table_cache_rate = config.get( + 'sparse_cache_rate', 0.00055 + ) + table_data.sparse_table_cache_file_num = config.get( + 'sparse_cache_file_num', 16 + ) + + accessor_class = config.get( + "sparse_accessor_class", "DownpourCtrAccessor" + ) + if accessor_class not in support_sparse_accessor_class: + raise ValueError( + "support sparse_accessor_class: ['DownpourSparseValueAccessor', 'DownpourCtrAccessor', 'DownpourCtrDoubleAccessor', 'DownpourUnitAccessor', 'DownpourDoubleUnitAccessor'], but actual %s" + % (accessor_class) + ) + + if accessor_class.find("Double") >= 0: + table_data.accessor.accessor_class = 'CtrDoubleAccessor' + elif accessor_class.find("Dymf") >= 0: + table_data.accessor.accessor_class = 'CtrDymfAccessor' + else: + table_data.accessor.accessor_class = 'CtrCommonAccessor' + + if not configs.get("use_cvm", True): + table_data.accessor.accessor_class = 'SparseAccessor' + + table_data.accessor.embedx_dim = config.get('sparse_embedx_dim', 8) + table_data.accessor.fea_dim = table_data.accessor.embedx_dim + 3 + table_data.accessor.embedx_threshold = config.get( + 'sparse_embedx_threshold', 10 + ) + + if accessor_class == 'DownpourUnitAccessor': + table_data.accessor.ctr_accessor_param.show_scale = False + else: + table_data.accessor.ctr_accessor_param.show_scale = True + + table_data.accessor.ctr_accessor_param.nonclk_coeff = config.get( + 'sparse_nonclk_coeff', 0.1 + ) + table_data.accessor.ctr_accessor_param.click_coeff = config.get( + 'sparse_click_coeff', 1 + ) + table_data.accessor.ctr_accessor_param.base_threshold = config.get( + 'sparse_base_threshold', 1.5 + ) + table_data.accessor.ctr_accessor_param.delta_threshold = config.get( + 'sparse_delta_threshold', 0.25 + ) + table_data.accessor.ctr_accessor_param.delta_keep_days = config.get( + 'sparse_delta_keep_days', 16 + ) + table_data.accessor.ctr_accessor_param.show_click_decay_rate = ( + config.get('sparse_show_click_decay_rate', 0.98) + ) + table_data.accessor.ctr_accessor_param.delete_threshold = ( + config.get('sparse_delete_threshold', 0.8) + ) + table_data.accessor.ctr_accessor_param.delete_after_unseen_days = ( + config.get('sparse_delete_after_unseen_days', 30) + ) + table_data.accessor.ctr_accessor_param.ssd_unseenday_threshold = ( + config.get('sparse_ssd_unseenday_threshold', 1) + ) + converter = config.get('sparse_converter', "") + deconverter = config.get('sparse_deconverter', "") + + save_data1 = table_data.accessor.table_accessor_save_param.add() + save_data1.param = 1 + save_data1.converter = converter + save_data1.deconverter = deconverter + + save_data2 = table_data.accessor.table_accessor_save_param.add() + save_data2.param = 2 + save_data2.converter = converter + save_data2.deconverter = deconverter + + if ( + accessor_class == 'DownpourCtrAccessor' + or accessor_class == 'DownpourCtrDoubleAccessor' + ): + sparse_optimizer_config( + table_data.accessor.embed_sgd_param, config, '' + ) + sparse_optimizer_config( + table_data.accessor.embedx_sgd_param, config, '' + ) + else: + sparse_optimizer_config( + table_data.accessor.embed_sgd_param, config, 'embed_' + ) + sparse_optimizer_config( + table_data.accessor.embedx_sgd_param, config, 'embedx_' + ) + add_graph_config(table_data.accessor.graph_sgd_param, config) + + if not configs: + print("fleet desc config is empty") + else: + for table_name in configs: + if ( + table_name == 'dense_table' + or table_name == 'datanorm_table' + ): + continue + if type(configs[table_name]) != dict: + continue + table_data = table_param.add() + table_data.table_name = table_name + set_sparse_table_config(table_data, configs[table_name]) + + @property + def amp(self): + """ + Indicating whether we are using automatic mixed precision training + Default Value: False + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.amp = True # by default this is false + + """ + return self.strategy.amp + + @amp.setter + @is_strict_auto + def amp(self, flag): + if isinstance(flag, bool): + self.strategy.amp = flag + else: + print("WARNING: amp should have value of bool type") + + @property + def amp_configs(self): + """ + + Set automatic mixed precision training configurations. In general, amp has serveral configurable + settings that can be configured through a dict. + + **Notes**: + init_loss_scaling(float): The initial loss scaling factor. Default 32768. + + use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling. Default True. + + incr_every_n_steps(int): Increases loss scaling every n consecutive steps with finite gradients. Default 1000. + + decr_every_n_nan_or_inf(int): Decreases loss scaling every n accumulated steps with nan or inf gradients. Default 2. + + incr_ratio(float): The multiplier to use when increasing the loss scaling. Default 2.0. + + decr_ratio(float): The less-than-one-multiplier to use when decreasing the loss scaling. Default 0.5. + + custom_white_list(list[str]): Users' custom white list which always execution fp16. + + custom_black_list(list[str]): Users' custom black list which forbidden execution fp16. + + custom_black_varnames(list[str]): Users' custom black varibles' names. + + use_pure_fp16(bool): Whether to use the pure fp16 training. Default False. + + use_fp16_guard(bool): Whether to use `fp16_guard` when constructing the program. + Default True. Only takes effect when `use_pure_fp16` is turned on. + + Examples 1: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.amp = True + strategy.amp_configs = { + "init_loss_scaling": 32768, + "custom_white_list": ['conv2d']} + + Examples 2: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.amp = True + # pure fp16 + strategy.amp_configs = { + "init_loss_scaling": 32768, + "use_pure_fp16": True + } + + """ + return get_msg_dict(self.strategy.amp_configs) + + @amp_configs.setter + @is_strict_auto + def amp_configs(self, configs): + check_configs_key(self.strategy.amp_configs, configs, "amp_configs") + assign_configs_value(self.strategy.amp_configs, configs) + + @property + def asp(self): + """ + + Indicating whether we are using automatic sparsity training + Default Value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.asp = True # by default this is false + + """ + return self.strategy.asp + + @asp.setter + @is_strict_auto + def asp(self, flag): + if isinstance(flag, bool): + self.strategy.asp = flag + else: + print("WARNING: asp should have value of bool type") + + @property + def recompute(self): + """ + Indicating whether we are using forward recomputation for memory optimization + Default value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.recompute = True + # suppose x and y are names of checkpoint tensors for recomputation + strategy.recompute_configs = {"checkpoints": ["x", "y"]} + + """ + return self.strategy.recompute + + @property + def sync_nccl_allreduce(self): + """ + + Indicating whether we are using synchronized all reduce in each communication thread + We note that system overhead is usually lower when sync_nccl_allreduce = True + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.sync_nccl_allreduce = True + + """ + return self.strategy.sync_nccl_allreduce + + @sync_nccl_allreduce.setter + @is_strict_auto + def sync_nccl_allreduce(self, flag): + if isinstance(flag, bool): + self.strategy.sync_nccl_allreduce = flag + else: + print("WARNING: sync_nccl_allreduce should have value of bool type") + + @property + def use_hierarchical_allreduce(self): + """ + + Indicating whether we are using hierarchical allreduce in collective communication + Hierarchical allreduce often does allreduce within a certain node group and then do + allreduce among the leaders of each group + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.use_hierarchical_allreduce = True + + """ + return self.strategy.use_hierarchical_allreduce + + @use_hierarchical_allreduce.setter + @is_strict_auto + def use_hierarchical_allreduce(self, flag): + if isinstance(flag, bool): + self.strategy.use_hierarchical_allreduce = flag + else: + print( + "WARNING: use_hierarchical_allreduce should have value of bool type" + ) + + @property + def hierarchical_allreduce_inter_nranks(self): + """ + + Number of ranks for low level node groups in hierarchical allreduce + Default value: number of GPU cards on each single GPU machine + + Example: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.hierarchical_allreduce_inter_nranks = 8 + + """ + return self.strategy.hierarchical_allreduce_inter_nranks + + @hierarchical_allreduce_inter_nranks.setter + @is_strict_auto + def hierarchical_allreduce_inter_nranks(self, value): + if isinstance(value, int): + self.strategy.hierarchical_allreduce_inter_nranks = value + else: + print( + "WARNING: hierarchical_allreduce_inter_nranks should have value of int type" + ) + + @property + def sync_batch_norm(self): + """ + + Indicating whether we are using sync_batch_norm to do synchronous batch normalization among all training nodes. + + Default value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.sync_batch_norm = True + + """ + + return self.strategy.sync_batch_norm + + @sync_batch_norm.setter + @is_strict_auto + def sync_batch_norm(self, flag): + if isinstance(flag, bool): + self.strategy.sync_batch_norm = flag + else: + print("WARNING: sync_batch_norm should have value of bool type") + + @property + def fuse_all_reduce_ops(self): + """ + + Indicating whether we are using fuse_all_reduce_ops for gradient fusion during backward phase of training + Default value: True + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.fuse_all_reduce_ops = False + + """ + return self.strategy.fuse_all_reduce_ops + + @fuse_all_reduce_ops.setter + @is_strict_auto + def fuse_all_reduce_ops(self, flag): + if isinstance(flag, bool): + self.strategy.fuse_all_reduce_ops = flag + else: + print("WARNING: fuse_all_reduce_ops should have value of bool type") + + @property + def fuse_grad_size_in_MB(self): + """ + + Specifying the size of gradient to fuse in Mega-Bytes + + Default value: 32 + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.fuse_grad_size_in_MB = 50 + + """ + return self.strategy.fuse_grad_size_in_MB + + @fuse_grad_size_in_MB.setter + @is_strict_auto + def fuse_grad_size_in_MB(self, value): + if isinstance(value, int): + self.strategy.fuse_grad_size_in_MB = value + else: + print("WARNING: fuse_grad_size_in_MB should have value of int type") + + @property + def last_comm_group_size_MB(self): + """ + + Specifying the size of gradient to fuse in Mega-Bytes when + the last group of each batch communicates. Making the last group + small is useful to improve performance. + + Default value: 1 + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.last_comm_group_size_MB = 2 + + """ + return self.strategy.last_comm_group_size_MB + + @last_comm_group_size_MB.setter + @is_strict_auto + def last_comm_group_size_MB(self, value): + if value > 0: + self.strategy.last_comm_group_size_MB = value + else: + raise ValueError("last_comm_group_size_MB should be greater than 0") + + @property + def find_unused_parameters(self): + """ + + Indicating whether we are using find_unused_parameters to + find unused parameters in DataParallel. + + Default value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.find_unused_parameters = True + + """ + + return self.strategy.find_unused_parameters + + @find_unused_parameters.setter + @is_strict_auto + def find_unused_parameters(self, flag): + if isinstance(flag, bool): + self.strategy.find_unused_parameters = flag + else: + print( + "WARNING: find_unused_parameters should have value of bool type" + ) + + @property + def _fuse_grad_size_in_TFLOPS(self): + return self.strategy.fuse_grad_size_in_TFLOPS + + @_fuse_grad_size_in_TFLOPS.setter + @is_strict_auto + def _fuse_grad_size_in_TFLOPS(self, value): + if isinstance(value, float): + self.strategy.fuse_grad_size_in_TFLOPS = value + else: + print( + "WARNING: fuse_grad_size_in_TFLOPS should have value of float type" + ) + + @property + def nccl_comm_num(self): + """ + + Specifying the number of NCCL communicator + + Default value: 1 + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.nccl_comm_num = 2 + + """ + + return self.strategy.nccl_comm_num + + @nccl_comm_num.setter + @is_strict_auto + def nccl_comm_num(self, value): + if isinstance(value, int): + self.strategy.nccl_comm_num = value + else: + print("WARNING: nccl_comm_num should have value of int type") + + @recompute.setter + @is_strict_auto + def recompute(self, flag): + if isinstance(flag, bool): + self.strategy.recompute = flag + else: + print("WARNING: recompute should have value of bool type") + + @property + def recompute_configs(self): + """ + + Set recompute configurations. + + **Note**: + checkpoints(list): list of string name of checkpoints. In general, the recompute + strategy of current implementation should have some manually assign checkpoints. + + enable_offload(bool): enable recompute checkpoints offload feature. this feature + will offload the checkpoint to host memory to allow even larger batch size. since + the memcpy from host to device takes time, it is a trade off between larger batch + size and training speed. + + checkpoint_shape(list): list of int that specific the shape of checkpoint. so far + recompute-offload requires that all checkpoint to be same shape, and every dimension + specific here should be determined ("-1" is not allowed). + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.recompute = True + strategy.recompute_configs = { + "checkpoints": ["x", "y"], + "enable_offload": True, + "checkpoint_shape": [100, 512, 1024] } + + """ + return get_msg_dict(self.strategy.recompute_configs) + + @recompute_configs.setter + @is_strict_auto + def recompute_configs(self, configs): + check_configs_key( + self.strategy.recompute_configs, configs, "checkpoint_configs" + ) + assign_configs_value(self.strategy.recompute_configs, configs) + + @property + def sharding(self): + """ + + Indicating whether we are using sharding Optimizer for memory + optimization. We implement the sharding optimizer following the ZeRO-DP + idea from [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054). + Model parameters and Optimizer State are sharded into different ranks allowing to fit larger model. + + In Hybrid parallelism scenario, we use sharding config as uniform API to set each parallelism. + + Default value: False + + Examples: + .. code-block:: python + + import paddle.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.sharding = True + + """ + return self.strategy.sharding + + @sharding.setter + @is_strict_auto + def sharding(self, flag): + if isinstance(flag, bool): + self.strategy.sharding = flag + else: + print("WARNING: sharding should have value of bool type") + + @property + def sharding_configs(self): + """ + + Set sharding configurations. + + **Note**: + sharding_segment_strategy(string, optional): strategy used to segment the program(forward & backward operations). two strategise are + available: "segment_broadcast_MB" and "segment_anchors". segment is a concept used in sharding to overlap computation and + communication. Default is segment_broadcast_MB. + + segment_broadcast_MB(float, optional): segment by the parameters broadcast volume. sharding will introduce parameter broadcast operations into program, and + after every segment_broadcast_MB size parameter being broadcasted, the program will be cutted into one segment. + This configuration will affect the communication speed in sharding training, and should be an empirical value decided by your model size and network topology. + Only enable when sharding_segment_strategy = segment_broadcast_MB. Default is 32.0 . + + segment_anchors(list): list of anchors used to segment the program, which allows a finner control of program segmentation. + this strategy is experimental by now. Only enable when sharding_segment_strategy = segment_anchors. + + sharding_degree(int, optional): specific the number of gpus within each sharding parallelism group; and sharding will be turn off if sharding_degree=1. Default is 8. + + gradient_merge_acc_step(int, optional): specific the accumulation steps in gradient merge; and gradient merge will be turn off if gradient_merge_acc_step=1. Default is 1. + + optimize_offload(bool, optional): enable the optimizer offload which will offload the moment vars to Host memory in order to saving GPU memory for fitting larger model. + the moment var will be prefetch from and offloaded to Host memory during update stage. it is a stragtegy that trades off between training speed and GPU memory, and is recommened to be turn on only when gradient_merge_acc_step large, where + the number of time of update stage will be relatively small compared with forward&backward's. Default is False. + + dp_degree(int, optional): specific the number of data parallelism group; when dp_degree >= 2, it will introduce dp_degree ways data parallelism as the outer parallelsim for the inner parallelsim. User is responsible to ensure global_world_size = mp_degree * sharding_degree * pp_degree * dp_degree. Default is 1. + + mp_degree(int, optional): [Hybrid parallelism ONLY] specific the number of gpus within each megatron parallelism group; and megatron parallelism will turn be off if mp_degree=1. Default is 1. + + pp_degree(int, optional): [Hybrid parallelism ONLY] specific the number of gpus within each pipeline parallelism group; and pipeline parallelism will turn be off if pp_degree=1. Default is 1. + + pp_allreduce_in_optimize(bool, optional): [Hybrid parallelism ONLY] move the allreduce operations from backward stage to update(optimize) stage when pipeline parallelsim is on. + This configuration will affect the communication speed of Hybrid parallelism training depeneded on network topology. this strategy is experimental by now.. Default is False. + + optimize_cast(bool, optional): [Hybrid parallelism ONLY] Move the cast op of AMP which cast fp32 param to fp16 param to optimizer. optimize_cast will persist fp16 param, it + will take more memory, but will be faster, trade space for time. Recommend to turn on only when using pipeline or gradient_merge_acc_step large. + + + Examples: + .. code-block:: python + + # sharding-DP, 2 nodes with 8 gpus per node + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.sharding = True + strategy.sharding_configs = { + "sharding_segment_strategy": "segment_broadcast_MB", + "segment_broadcast_MB": 32, + "sharding_degree": 8, + "dp_degree": 2, + "gradient_merge_acc_step": 4, + } + + """ + return get_msg_dict(self.strategy.sharding_configs) + + @sharding_configs.setter + @is_strict_auto + def sharding_configs(self, configs): + check_configs_key( + self.strategy.sharding_configs, configs, "sharding_configs" + ) + assign_configs_value(self.strategy.sharding_configs, configs) + + @property + def without_graph_optimization(self): + """ + + Run program using Executor other than ParallelExecutor. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.without_graph_optimization = True + + """ + return self.strategy.without_graph_optimization + + @without_graph_optimization.setter + @is_strict_auto + def without_graph_optimization(self, flag): + if isinstance(flag, bool): + self.strategy.without_graph_optimization = flag + else: + print( + "WARNING: without_graph_optimization should have value of bool type" + ) + + @property + def _calc_comm_same_stream(self): + """ + + This based on raw_program_optimizer program + Set whether use same stream for calc and comm when fuse allreduce + The default value for the calc_comm_same_stream is False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.calc_comm_same_stream = True + + """ + return self.strategy.calc_comm_same_stream + + @_calc_comm_same_stream.setter + @is_strict_auto + def _calc_comm_same_stream(self, same): + if isinstance(same, bool): + self.strategy.calc_comm_same_stream = same + else: + print( + "WARNING: calc_comm_same_stream should have value of boolean type" + ) + + @property + def fuse_grad_merge(self): + """ + + Set whether fuse the grad for gradient merge. + Note: this flag will only effect the gradient merge under pipeline mode + The default value for the fuse_grad_merge is False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.fuse_param_grad = True + + """ + return self.strategy.fuse_grad_merge + + @fuse_grad_merge.setter + @is_strict_auto + def fuse_grad_merge(self, fuse_grad_merge): + if isinstance(fuse_grad_merge, bool): + self.strategy.fuse_grad_merge = fuse_grad_merge + else: + print("WARNING: fuse_grad_merge should have value of boolean type") + + @property + def fuse_grad_size_in_num(self): + """ + + This based on raw_program_optimizer program and allreduce the num of the fused op + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.fuse_grad_size_in_num = 2 + + """ + return self.strategy.fuse_grad_size_in_num + + @fuse_grad_size_in_num.setter + @is_strict_auto + def fuse_grad_size_in_num(self, num): + if isinstance(num, int): + self.strategy.fuse_grad_size_in_num = num + else: + print( + "WARNING: fuse_grad_size_in_num should have value of int32 type" + ) + + @property + def pipeline(self): + """ + + Indicating whether we are using pipeline parallelism for distributed training. + Current implementation mainly focus on single GPU machine pipeline parallelism and + data parallelism across GPU machine. The pipeline information is indicated through + device_guard information in user-defined program. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.pipeline = True + + """ + return self.strategy.pipeline + + @property + def is_fl_ps_mode(self): + return self.strategy.is_fl_ps_mode + + @is_fl_ps_mode.setter + @is_strict_auto + def is_fl_ps_mode(self, flag): + if isinstance(flag, bool): + self.strategy.is_fl_ps_mode = flag + else: + print("WARNING: is_fl_ps_mode should have value of bool type") + + @property + def is_with_coordinator(self): + return self.strategy.with_coordinator + + @is_with_coordinator.setter + @is_strict_auto + def is_with_coordinator(self, flag): + if isinstance(flag, bool): + self.strategy.with_coordinator = flag + else: + print("WARNING: with_coordinator should have value of bool type") + + @pipeline.setter + @is_strict_auto + def pipeline(self, flag): + if isinstance(flag, bool): + self.strategy.pipeline = flag + else: + print("WARNING: pipeline should have value of bool type") + + @property + def pipeline_configs(self): + """ + + Set pipeline parallelism configurations. In pipeline parallelism, + different parts of neural networks are running on different GPUS. + There are Tensor queue buffer between each pair of neighborhood GPUS + that are responsible for synchronizing hidden Tensor results between + GPUs. Pipeline parallelism consists of serveral producer-consumer style + hardware pairs, such as GPU-GPU, CPU-GPU, GPU-XPU. The best way to speedup + pipeline parallelism is to make the size of Tensor in Tensor queue smaller, + so that we will have a faster producer for downstream consumers. + + **Notes**: + **Detailed arguments for pipeline_configs** + + **micro_batch_size**: the number of small batches in each user defined batch + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.pipeline = True + strategy.pipeline_configs = {"micro_batch_size": 12} + + """ + + return get_msg_dict(self.strategy.pipeline_configs) + + @pipeline_configs.setter + @is_strict_auto + def pipeline_configs(self, configs): + check_configs_key( + self.strategy.pipeline_configs, configs, "pipeline_configs" + ) + assign_configs_value(self.strategy.pipeline_configs, configs) + + @property + def tensor_parallel(self): + """ + + Indicating whether we are using tensor parallel for distributed training. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.tensor_parallel = True + + """ + return self.strategy.tensor_parallel + + @tensor_parallel.setter + @is_strict_auto + def tensor_parallel(self, flag): + if isinstance(flag, bool): + self.strategy.tensor_parallel = flag + else: + print("WARNING: tensor_parallel should have value of bool type") + + @property + def tensor_parallel_configs(self): + """ + + Set tensor_parallel configurations. + + **Notes**: + **Detailed arguments for tensor_parallel_configs** + + **tensor_parallel_degree**: degree of tensor parallel + + **tensor_init_seed**: parameter initialization random seed + + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.tensor_parallel = True + strategy.tensor_parallel_configs = {"tensor_parallel_degree": 4, + "tensor_init_seed": 123} + + """ + return get_msg_dict(self.strategy.tensor_parallel_configs) + + @tensor_parallel_configs.setter + @is_strict_auto + def tensor_parallel_configs(self, configs): + check_configs_key( + self.strategy.tensor_parallel_configs, + configs, + "tensor_parallel_configs", + ) + assign_configs_value(self.strategy.tensor_parallel_configs, configs) + + @property + def hybrid_configs(self): + """ + + Dynamic graph hybrid parallel strategy configuration. Three-way hybrid parallelism + needs to meet the following relationships + + total_number_GPUs = dp_degree * mp_degree * pp_degree + + **Note**: + **dp_degree(int)**: set number of GPUs in a data parallel group. Default -1. + This value should be an integer greater than 0. + If it is not set, or set to -1, its value will be inferred + based on the total number of cards. + + **mp_degree(int)**: set number of GPUs in a model parallel group. Default 1 + + **pp_degree(int)**: set number of GPUs in a pipeline parallel group. Default 1 + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.hybrid_configs = { + "dp_degree": 1, + "mp_degree": 2, + "pp_degree": 1} + + """ + return get_msg_dict(self.strategy.hybrid_configs) + + @hybrid_configs.setter + def hybrid_configs(self, configs): + check_configs_key( + self.strategy.hybrid_configs, configs, "hybrid_configs" + ) + assign_configs_value(self.strategy.hybrid_configs, configs) + + @property + def localsgd(self): + """ + + Indicating whether we are using Local SGD training. Default Value: False + For more details, please refer to + `Don't Use Large Mini-Batches, Use Local SGD `_. + + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.localsgd = True # by default this is false + + """ + return self.strategy.localsgd + + @localsgd.setter + @is_strict_auto + def localsgd(self, flag): + if isinstance(flag, bool): + self.strategy.localsgd = flag + else: + print("WARNING: localsgd should have value of bool type") + + @property + def localsgd_configs(self): + """ + + Set LocalSGD training configurations. LocalSGD has a configurable + setting that can be configured through a dict. + + **Notes**: + k_steps(int) The local steps for training before parameter synchronization. Default 1. + begin_step(int) The step of beginning training by localsgd. Default 1. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.localsgd = True + strategy.localsgd_configs = {"k_steps": 4, + "begin_step": 30} + + """ + + return get_msg_dict(self.strategy.localsgd_configs) + + @localsgd_configs.setter + @is_strict_auto + def localsgd_configs(self, configs): + check_configs_key( + self.strategy.localsgd_configs, configs, "localsgd_configs" + ) + assign_configs_value(self.strategy.localsgd_configs, configs) + + @property + def adaptive_localsgd(self): + """ + + Indicating whether we are using Adaptive Local SGD training. Default Value: False + For more details, please refer to `Adaptive Communication Strategies to Achieve + the Best Error-Runtime Trade-off in Local-Update SGD `_. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.adaptive_localsgd = True # by default this is false + + """ + return self.strategy.adaptive_localsgd + + @adaptive_localsgd.setter + @is_strict_auto + def adaptive_localsgd(self, flag): + if isinstance(flag, bool): + self.strategy.adaptive_localsgd = flag + else: + print("WARNING: adaptive_localsgd should have value of bool type") + + @property + def adaptive_localsgd_configs(self): + """ + + Set AdaptiveLocalSGD training configurations. AdaptiveLocalSGD has a configurable + setting that can be configured through a dict. + + **Notes**: + init_k_steps(int) The initial steps for training before adaptive localsgd. + Then, the adaptive localsgd method will modify init_k_steps automatically. + Default 1. + + begin_step(int) The step of beginning training by adaptive localsgd. Default 1. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.adaptive_localsgd = True + strategy.adaptive_localsgd_configs = {"init_k_steps": 1, + "begin_step": 30} + + """ + + return get_msg_dict(self.strategy.adaptive_localsgd_configs) + + @adaptive_localsgd_configs.setter + @is_strict_auto + def adaptive_localsgd_configs(self, configs): + check_configs_key( + self.strategy.adaptive_localsgd_configs, + configs, + "adaptive_localsgd_configs", + ) + assign_configs_value(self.strategy.adaptive_localsgd_configs, configs) + + @property + def dgc(self): + """ + + Indicating whether we are using Deep Gradient Compression training. For more details, please refer to + [Deep Gradient Compression](https://arxiv.org/abs/1712.01887). + + Default Value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.dgc = True # by default this is false + + """ + return self.strategy.dgc + + @dgc.setter + @is_strict_auto + def dgc(self, flag): + if isinstance(flag, bool): + self.strategy.dgc = flag + else: + print("WARNING: dgc should have value of bool type") + + @property + def dgc_configs(self): + r""" + + Set Deep Gradient Compression training configurations. In general, dgc has serveral configurable + settings that can be configured through a dict. + + **Notes**: + rampup_begin_step(int): The beginning step from which gradient compression is implemented. Default 0. + + rampup_step(int): Time steps used in sparsity warm-up periods. Default is 1. \ + For example, if the sparsity is [0.75, 0.9375, 0.984375, 0.996, 0.999], and the rampup_step is 100, \ + it will use 0.75 at 0~19 steps, and 0.9375 at 20~39 steps, and so on. And when reach sparsity array \ + ends, it will use 0.999 then and after. + + sparsity(list[float]): Get top important element from gradient tensor, the ratio is (1 - sparsity). \ + Default is [0.999]. For example, if the sparsity is [0.99, 0.999], the top [1%, 0.1%] important \ + element will be transmitted. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.dgc = True + strategy.dgc_configs = {"rampup_begin_step": 1252} + + """ + return get_msg_dict(self.strategy.dgc_configs) + + @dgc_configs.setter + @is_strict_auto + def dgc_configs(self, configs): + check_configs_key(self.strategy.dgc_configs, configs, "dgc_configs") + assign_configs_value(self.strategy.dgc_configs, configs) + + @property + def fp16_allreduce(self): + """ + + Indicating whether we are using fp16 gradient allreduce training + Default Value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.fp16_allreduce = True # by default this is false + + """ + return self.strategy.fp16_allreduce + + @fp16_allreduce.setter + @is_strict_auto + def fp16_allreduce(self, flag): + if not isinstance(flag, bool): + raise TypeError('fp16_allreduce must be value of bool type') + self.strategy.fp16_allreduce = flag + + @property + def gradient_merge(self): + """ + + Gradient Merge, also called as Gradient Accumulation, + is a strategy for large batch training. With this strategy, + model parameter will not be updated until user-defined steps. + For each step, the forward network and the backward network + will run to calculate the gradient of model parameters. + For every k step, the optimization network will run, + applying a specific optimization method (such as SGD, Adam) + to model parameters. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.gradient_merge = True + strategy.gradient_merge_configs = {"k_steps": 4, "avg": True} + + """ + return self.strategy.gradient_merge + + @gradient_merge.setter + @is_strict_auto + def gradient_merge(self, flag): + if isinstance(flag, bool): + self.strategy.gradient_merge = flag + else: + print("WARNING: gradient_merge should have value of bool type") + + @property + def gradient_merge_configs(self): + """ + + the key-value configs of distribute_strategy + + **Note**: + k_steps(int): the update period of the parameters. + + avg(bool): whether to average the gradients of each mini-batch, the default value is `True` + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.gradient_merge = True + strategy.gradient_merge_configs = {"k_steps": 4, "avg": True} + + """ + return get_msg_dict(self.strategy.gradient_merge_configs) + + @gradient_merge_configs.setter + @is_strict_auto + def gradient_merge_configs(self, configs): + check_configs_key( + self.strategy.gradient_merge_configs, configs, "gradient_configs" + ) + assign_configs_value(self.strategy.gradient_merge_configs, configs) + + @property + def lars(self): + """ + + Set lars configurations. lars is used to deal with the convergence problems when the global + batch size is larger than 8k. For more details, please refer to + [Large Batch Training of Convolutional Networks](https://arxiv.org/abs/1708.03888). + + Default Value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.lars = True # by default this is false + + """ + return self.strategy.lars + + @lars.setter + @is_strict_auto + def lars(self, flag): + if isinstance(flag, bool): + self.strategy.lars = flag + else: + print("WARNING: lars should have value of bool type") + + @property + def lars_configs(self): + """ + + Set Lars training configurations. + + **Notes**: + **lars_coeff (float)**: trust ratio in lars formula. + **lars_weight_decay** (float): weight decay coefficient in lars formula. + **epsilon (float)**: argument is used to avoid potential devision-by-zero + when compute the local lr; + **exclude_from_weight_decay ([string])**: is a list of name strings of layers which + will be exclude from weight decay in lars formula. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.lars = True + strategy.lars_configs = { + "lars_coeff": 0.01, + "lars_weight_decay": 0.0005, + "epsilon": 0, + "exclude_from_weight_decay": ['batch_norm', '.b_0'] + } + + """ + return get_msg_dict(self.strategy.lars_configs) + + @lars_configs.setter + @is_strict_auto + def lars_configs(self, configs): + check_configs_key(self.strategy.lars_configs, configs, "lars_configs") + assign_configs_value(self.strategy.lars_configs, configs) + + @property + def lamb(self): + """ + + Set lamb configurations. lamb is used to deal with the convergence problems for large + batch size training, specially for attention-related model like BERT. For more details, + please refer to + [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962). + + Default Value: False + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.lamb = True # by default this is false + + """ + + return self.strategy.lamb + + @lamb.setter + @is_strict_auto + def lamb(self, flag): + if isinstance(flag, bool): + self.strategy.lamb = flag + else: + print("WARNING: lamb should have value of bool type") + + @property + def lamb_configs(self): + """ + + Set Lars training configurations. + + **Notes**: + **lamb_weight_decay** (float): weight decay coefficient in lamb formula. + **exclude_from_weight_decay ([string])**: is a list of name strings of layers which + will be exclude from weight decay in lamb formula. + + Examples: + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.lamb = True + strategy.lamb_configs = { + 'lamb_weight_decay': 0.01, + 'exclude_from_weight_decay': [], + } + + """ + return get_msg_dict(self.strategy.lamb_configs) + + @lamb_configs.setter + @is_strict_auto + def lamb_configs(self, configs): + check_configs_key(self.strategy.lamb_configs, configs, "lamb_configs") + assign_configs_value(self.strategy.lamb_configs, configs) + + @property + def elastic(self): + """ + + Indicating whether we want to do current distributed training on clusters with elastic resources. + Currently, this is configuration is not valid. + + """ + return self.strategy.elastic + + @elastic.setter + @is_strict_auto + def elastic(self, flag): + if isinstance(flag, bool): + self.strategy.elastic = flag + else: + print("WARNING: elastic should have value of bool type") + + @property + def auto(self): + """ + + Indicating whether we are using auto-parallel configuration + This feature is currently an experimental feature. Currently, + auto-parallelism can be used only when a user does not set any other + strategy configs except auto. For details, please reference the following + code example + Default Value: False + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.auto = True + # if set other strategy at the same time, auto will not apply + # strategy.amp = True + + optimizer = paddle.optimizer.SGD(learning_rate=0.01) + optimizer = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.auto + + @auto.setter + def auto(self, flag): + if isinstance(flag, bool): + self.strategy.auto = flag + else: + print("WARNING: auto should have value of bool type") + + @property + def semi_auto(self): + """ + + Indicating whether we are using semi-auto parallel function + This feature is currently an experimental feature. Currently, + auto-parallelism can be used only when a user does not set any other + strategy configs except semi-auto. For details, please reference the following + code example + Default Value: False + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.semi_auto = True + # if set other strategy at the same time, auto will not apply + # strategy.amp = True + + optimizer = paddle.optimizer.SGD(learning_rate=0.01) + optimizer = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.semi_auto + + @semi_auto.setter + def semi_auto(self, flag): + if isinstance(flag, bool): + self.strategy.semi_auto = flag + else: + print("WARNING: semi-auto should have value of bool type") + + @property + def auto_search(self): + """ + + Indicating whether we are using auto-search parallel function + For details, please reference the following code example + Default Value: False + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.auto_search = True + + """ + return self.strategy.auto_search + + @auto_search.setter + def auto_search(self, flag): + if isinstance(flag, bool): + self.strategy.auto_search = flag + else: + print("WARNING: auto-search should have value of bool type") + + @property + def split_data(self): + """ + + Indicating whether we split the data. If True, we split the data. + Default Value: True + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + strategy.split_data = True + + """ + return self.strategy.split_data + + @split_data.setter + def split_data(self, flag): + if isinstance(flag, bool): + self.strategy.split_data = flag + else: + print("WARNING: split_data should have value of bool type") + + @property + def qat(self): + """ + + Indicating whether we are using quantization training + Default Value: False + + """ + return self.strategy.qat + + @qat.setter + def qat(self, flag): + if isinstance(flag, bool): + self.strategy.qat = flag + else: + print("WARNING: qat should have value of bool type") + + @property + def qat_configs(self): + """ + + Set quantization training configurations. In general, qat has serveral configurable + settings that can be configured through a dict. + + **Notes**: + channel_wise_abs_max(bool): Whether to use `per_channel` quantization training. Default is True. + + weight_bits(int): quantization bit number for weight. Default is 8. + + activation_bits(int): quantization bit number for activation. Default is 8. + + not_quant_pattern(list[str]): When the skip pattern is detected in an op's name scope, + the corresponding op will not be quantized. + + algo(str): Other quantization training algorithm. + + Exampless: + .. code-block:: python + + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.qat = True + strategy.qat_configs = { + "channel_wise_abs_max": True, + "weight_bits": 8, + "activation_bits: 8, + "not_quant_pattern": ['skip_quant']} + + """ + return get_msg_dict(self.strategy.qat_configs) + + @qat_configs.setter + def qat_configs(self, configs): + check_configs_key(self.strategy.qat_configs, configs, "qat_configs") + assign_configs_value(self.strategy.qat_configs, configs) + + @property + def heter_ccl_mode(self): + """ + + Indicating whether we are using heter_ccl_mode for model training. + This feature is currently an experimental feature. Currently, + heter_ccl_mode can be used only for dataparallel with dygraph mode. + Default Value: False + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.heter_ccl_mode = True + + # for initialize parallel env, only need to call + paddle.distributed.init_parallel_env() + # then the heterogenous context will be created. + + """ + return self.strategy.heter_ccl_mode + + @heter_ccl_mode.setter + def heter_ccl_mode(self, flag): + if isinstance(flag, bool): + self.strategy.heter_ccl_mode = flag + else: + print("WARNING: heter_ccl_mode should have value of bool type") + + @property + def cudnn_exhaustive_search(self): + """ + + Indicating whether to use exhaustive search method to choose convolution algorithms. + Exhaustive search attempts all cuDNN algorithms to choose the fastest algorithm. + This method is time-consuming, the choosed algorithm will be cached for the given layer specifications. + Once the layer specifications (like batch size, feature map size) are changed, it will search again. + Default Value: True + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.cudnn_exhaustive_search = False + + optimizer = paddle.optimizer.SGD(learning_rate=0.01) + optimizer = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.cudnn_exhaustive_search + + @cudnn_exhaustive_search.setter + @is_strict_auto + def cudnn_exhaustive_search(self, flag): + if isinstance(flag, bool): + self.strategy.cudnn_exhaustive_search = flag + else: + print( + "WARNING: cudnn_exhaustive_search should have value of bool type" + ) + + @property + def conv_workspace_size_limit(self): + """ + + The workspace limit size in MB unit for choosing cuDNN convolution algorithms. + The inner funciton of cuDNN obtain the fastest suited algorithm that fits within this memory limit. + Usually, large workspace size may lead to choose faster algorithms, + but significant increasing memory workspace. Users need to trade-off between memory and speed. + Default Value: 4000 + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.conv_workspace_size_limit = 1024 + + optimizer = paddle.optimizer.SGD(learning_rate=0.01) + optimizer = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.conv_workspace_size_limit + + @conv_workspace_size_limit.setter + @is_strict_auto + def conv_workspace_size_limit(self, value): + if isinstance(value, int): + self.strategy.conv_workspace_size_limit = value + else: + print( + "WARNING: conv_workspace_size_limit should have value of int type" + ) + + @property + def cudnn_batchnorm_spatial_persistent(self): + """ + + Indicates whether to use the mode CUDNN_BATCHNORM_SPATIAL_PERSISTENT function in batchnorm. + This is only useful in cudnn. + Default Value: True + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + strategy = fleet.DistributedStrategy() + strategy.cudnn_batchnorm_spatial_persistent = True + + optimizer = paddle.optimizer.SGD(learning_rate=0.01) + optimizer = fleet.distributed_optimizer(optimizer, strategy) + + """ + return self.strategy.cudnn_batchnorm_spatial_persistent + + @cudnn_batchnorm_spatial_persistent.setter + @is_strict_auto + def cudnn_batchnorm_spatial_persistent(self, flag): + if isinstance(flag, bool): + self.strategy.cudnn_batchnorm_spatial_persistent = flag + else: + print( + "WARNING: cudnn_batchnorm_spatial_persistent should have value of bool type" + ) + + def _enable_env(self): + strategy = self.strategy + keys = [ + "FLAGS_cudnn_batchnorm_spatial_persistent", + "FLAGS_conv_workspace_size_limit", + "FLAGS_cudnn_exhaustive_search", + "FLAGS_sync_nccl_allreduce", + "FLAGS_fuse_parameter_memory_size", + "FLAGS_fuse_parameter_groups_size", + ] + values = [ + bool(strategy.cudnn_batchnorm_spatial_persistent), + int(strategy.conv_workspace_size_limit), + bool(strategy.cudnn_exhaustive_search), + bool(strategy.sync_nccl_allreduce), + int(strategy.fuse_grad_size_in_MB), + int(strategy.fuse_grad_size_in_TFLOPS), + ] + + for i, key in enumerate(keys): + if _global_flags().is_public(key): + _global_flags()[key] = values[i] + + def _is_strict_auto(self): + global non_auto_func_called + if self.strategy.auto and non_auto_func_called: + return True + return False + + def __repr__(self): + spacing = 2 + max_k = 38 + max_v = 38 + + length = max_k + max_v + spacing + + h1_format = " " + "|{{:^{}s}}|\n".format(length) + h2_format = " " + "|{{:>{}s}}{}{{:^{}s}}|\n".format( + max_k, " " * spacing, max_v + ) + + border = " +" + "".join(["="] * length) + "+" + line = " +" + "".join(["-"] * length) + "+" + + draws = border + "\n" + draws += h1_format.format("") + draws += h1_format.format("DistributedStrategy Overview") + draws += h1_format.format("") + + fields = self.strategy.DESCRIPTOR.fields + str_res = "" + + env_draws = line + "\n" + for f in fields: + if "build_strategy" in f.name or "execution_strategy" in f.name: + continue + if "_configs" in f.name: + continue + else: + if isinstance(getattr(self.strategy, f.name), bool): + if hasattr(self.strategy, f.name + "_configs"): + if getattr(self.strategy, f.name): + draws += border + "\n" + draws += h1_format.format( + "{}=True <-> {}_configs".format(f.name, f.name) + ) + draws += line + "\n" + my_configs = getattr( + self.strategy, f.name + "_configs" + ) + config_fields = my_configs.DESCRIPTOR.fields + for ff in config_fields: + if isinstance( + getattr(my_configs, ff.name), + google.protobuf.pyext._message.RepeatedScalarContainer, + ): + values = getattr(my_configs, ff.name) + for i, v in enumerate(values): + if i == 0: + draws += h2_format.format( + ff.name, str(v) + ) + else: + draws += h2_format.format( + "", str(v) + ) + else: + draws += h2_format.format( + ff.name, + str(getattr(my_configs, ff.name)), + ) + else: + env_draws += h2_format.format( + f.name, str(getattr(self.strategy, f.name)) + ) + else: + env_draws += h2_format.format( + f.name, str(getattr(self.strategy, f.name)) + ) + + result_res = ( + draws + + border + + "\n" + + h1_format.format("Environment Flags, Communication Flags") + ) + result_res += env_draws + + build_strategy_str = border + "\n" + build_strategy_str += h1_format.format("Build Strategy") + build_strategy_str += line + "\n" + + fields = self.strategy.build_strategy.DESCRIPTOR.fields + for f in fields: + build_strategy_str += h2_format.format( + f.name, str(getattr(self.strategy.build_strategy, f.name)) + ) + build_strategy_str += border + "\n" + + execution_strategy_str = h1_format.format("Execution Strategy") + execution_strategy_str += line + "\n" + + fields = self.strategy.execution_strategy.DESCRIPTOR.fields + for f in fields: + execution_strategy_str += h2_format.format( + f.name, str(getattr(self.strategy.execution_strategy, f.name)) + ) + execution_strategy_str += border + "\n" + + result_res += build_strategy_str + execution_strategy_str + return result_res diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/meta_optimizer_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/meta_optimizer_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a3e4047b3990c2b9dbda280b011b36ac2d1e36 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/meta_optimizer_factory.py @@ -0,0 +1,37 @@ +# 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. + +from ..meta_optimizers import * + +__all__ = [] + +meta_optimizer_names = list( + filter(lambda name: name.endswith("Optimizer"), dir())) + +# Because HybridParallelOptimizer is dygraph optimizer, it +# should be removed +meta_optimizer_names.remove("HybridParallelOptimizer") +meta_optimizer_names.remove("HeterParallelOptimizer") + + +class MetaOptimizerFactory(object): + + def __init__(self): + pass + + def _get_valid_meta_optimizers(self, user_defined_optimizer): + opt_list = [] + for opt_name in meta_optimizer_names: + opt_list.append(globals()[opt_name](user_defined_optimizer)) + return opt_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/private_helper_function.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/private_helper_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ff18a44ac0c42d1726e60796ffe73feecf0a5ab9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/private_helper_function.py @@ -0,0 +1,63 @@ +# 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. +import sys +import time +import socket +from contextlib import closing +from six import string_types + +__all__ = [] + + +def wait_server_ready(endpoints): + """ + Wait until parameter servers are ready, use connext_ex to detect + port readiness. + + Args: + endpoints (list|tuple): endpoints string list, like: + ["127.0.0.1:8080", "127.0.0.1:8081"] + + Examples: + .. code-block:: python + + wait_server_ready(["127.0.0.1:8080", "127.0.0.1:8081"]) + """ + assert not isinstance(endpoints, str) + while True: + all_ok = True + not_ready_endpoints = [] + for ep in endpoints: + ip_port = ep.split(":") + with closing( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) + ) as sock: + sock.settimeout(2) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + result = sock.connect_ex((ip_port[0], int(ip_port[1]))) + if result != 0: + all_ok = False + not_ready_endpoints.append(ep) + if not all_ok: + sys.stderr.write("server not ready, wait 3 sec to retry...\n") + sys.stderr.write( + "not ready endpoints:" + str(not_ready_endpoints) + "\n" + ) + sys.stderr.flush() + time.sleep(3) + else: + break diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/role_maker.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/role_maker.py new file mode 100644 index 0000000000000000000000000000000000000000..67350be6210c65c35acbc51f2b8877e07c5cc901 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/role_maker.py @@ -0,0 +1,1157 @@ +# 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. +"""Defination of Role Makers.""" +import os +import time +import numpy as np +import warnings +from multiprocessing import Process, Manager + +import paddle +import paddle.fluid as fluid +from paddle.distributed.fleet.base.private_helper_function import wait_server_ready + +__all__ = [] + + +class Role: + WORKER = 1 + SERVER = 2 + HETER_WORKER = 3 + ALL = 4 + COORDINATOR = 5 + + +class Gloo(object): + """ + Gloo is a universal class for barrier and collective communication + """ + + class RENDEZVOUS: + HDFS = 1 + FILE = 2 + HTTP = 3 + + def __init__(self): + self._worker_comm = None + self._server_comm = None + self._nodes_comm = None + + self._comm_world = ["worker", "server", "all"] + self._err_init = "gloo is not initialized, will not communicator with other nodes" + self._err_type = "gloo initialized error, please check arguments" + self._err_world = "argument error, comm_world must in {}".format( + self._comm_world) + + self._is_initialized = False + self._init_timeout_seconds = 3600 + self._run_timeout_seconds = 9999999 + + self._rendezvous = None + self._role = None + self._iface = None + + self._role_id = -1 + self._worker_num = -1 + self._server_num = -1 + self._need_init_all = False + + def init(self, + rendezvous, + role, + role_id, + worker_num, + server_num, + need_init_all=False, + kwargs=None): + + self._rendezvous = rendezvous + self._role = role + self._role_id = role_id + self._worker_num = worker_num + self._server_num = server_num + self._need_init_all = need_init_all + self._iface = "" + self._prefix = kwargs.get("store.prefix", "") + + http_server = None + if self._rendezvous == Gloo.RENDEZVOUS.HDFS: + dfs_name = kwargs.get("dfs.name", "") + dfs_ugi = kwargs.get("dfs.ugi", "") + dfs_path = kwargs.get("dfs.path", "") + + if not dfs_name or not dfs_ugi or not dfs_path: + raise ValueError(self._err_type) + self._init_dfs(dfs_name, dfs_ugi, dfs_path, self._prefix) + + elif self._rendezvous == Gloo.RENDEZVOUS.FILE: + fs_path = kwargs.get("dfs.path", "") + + if not fs_path: + raise ValueError(self._err_type) + self._init_fs(fs_path, self._prefix) + + elif self._rendezvous == Gloo.RENDEZVOUS.HTTP: + ip = kwargs.get("http.host", "") + port = kwargs.get("http.port", "") + start_http_server = kwargs.get("start_http_server", False) + http_server_d = kwargs.get("http_server_d") + + if not ip or not port: + raise ValueError(self._err_type) + http_server = self._init_http(ip, port, self._prefix, + start_http_server, http_server_d) + else: + raise ValueError(self._err_type) + + self._is_initialized = True + self._http_server = http_server + + def _init_fs(self, fs_path, prefix): + + def init(rank, nodes, role): + gloo = fluid.core.Gloo() + gloo.set_rank(rank) + gloo.set_size(nodes) + gloo.set_prefix(prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store(os.path.join(fs_path, role), "", "") + gloo.init() + return gloo + + if self._role == Role.WORKER: + rank, nodes = self._get_rank_nodes(Role.WORKER) + gloo = init(rank, nodes, "WORKER") + self._worker_comm = gloo + else: + rank, nodes = self._get_rank_nodes(Role.SERVER) + gloo = init(rank, nodes, "SERVER") + self._server_comm = gloo + + if self._need_init_all: + rank, nodes = self._get_rank_nodes(Role.ALL) + gloo = init(rank, nodes, "ALL") + self._nodes_comm = gloo + + def _init_dfs(self, dfs_name, dfs_ugi, dfs_path, prefix): + + def init(rank, nodes, role): + gloo = fluid.core.Gloo() + gloo.set_rank(rank) + gloo.set_size(nodes) + gloo.set_prefix(prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store(os.path.join(dfs_path, role), dfs_name, dfs_ugi) + gloo.init() + return gloo + + if self._role == Role.WORKER: + rank, nodes = self._get_rank_nodes(Role.WORKER) + gloo = init(rank, nodes, "WORKER") + self._worker_comm = gloo + else: + rank, nodes = self._get_rank_nodes(Role.SERVER) + gloo = init(rank, nodes, "SERVER") + self._server_comm = gloo + + if self._need_init_all: + rank, nodes = self._get_rank_nodes(Role.ALL) + gloo = init(rank, nodes, "ALL") + self._nodes_comm = gloo + + def _init_http(self, ip, port, prefix, start_http_server, http_server_d): + + def __start_kv_server(http_server_d, size_d): + print("start http_server: {}, {}".format(port, size_d)) + from paddle.distributed.fleet.utils.http_server import KVServer + http_server = KVServer(port, size_d) + http_server.start() + wait_seconds = 5 + while http_server_d.get("running", + False) or not http_server.should_stop(): + time.sleep(wait_seconds) + http_server.stop() + + def init_kv_server(http_server_d): + worker_key = prefix + '_' + 'worker' + size_d = { + worker_key: self._worker_num, + } + print("worker_key:{}, size: {}".format(worker_key, size_d)) + + http_server_d["running"] = True + # child process for http server + _http_server = Process(target=__start_kv_server, + args=(http_server_d, size_d)) + _http_server.daemon = True + # set running status to True + # start child process + _http_server.start() + return _http_server + + def init(rank, nodes, role): + gloo = fluid.core.Gloo() + gloo.set_rank(rank) + gloo.set_size(nodes) + gloo.set_prefix(prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_http_store(ip, port, 'worker') + ep = ":".join([ip, str(port)]) + wait_server_ready([ep]) + gloo.init() + return gloo + + port = int(port) + + if start_http_server: + print("to start http_server") + http_server = init_kv_server(http_server_d) + + if self._role == Role.WORKER: + rank, nodes = self._get_rank_nodes(Role.WORKER) + gloo = init(rank, nodes, "WORKER") + self._worker_comm = gloo + # TODO (sandyhouse): initialize gloo for server and all + + # the closing of kv server may cause gloo init failure + # since it depend on the full mesh connection + # e.g. 0 connected with 1,2,3 while 2-3 not connected yet + # TODO(kuizhiqing) + if start_http_server: + http_server_d["running"] = False + http_server.join() + + def _get_rank_nodes(self, role): + nodes = 0 + rank = -1 + + if role == Role.WORKER: + nodes = self._worker_num + rank = self._role_id + elif role == Role.SERVER: + nodes = self._server_num + rank = self._role_id + elif role == Role.ALL: + nodes = self._worker_num + self._server_num + + if self._role == Role.WORKER: + rank = self._role_id + else: + rank = self._worker_num + self._role_id + else: + ValueError(self._err_type) + + return rank, nodes + + def __get_default_iface(self): + """ + get default physical interface + """ + default1 = self.__get_default_iface_from_gateway() + default2 = self.__get_default_iface_from_interfaces() + return default2 if default1 == "lo" else default1 + + def __get_default_iface_from_gateway(self): + """ + get default physical interface + """ + res = os.popen("route -A inet").read().strip().split("\n") + + gateway_idx = None + iface_idx = None + for item in res: + item = item.split() + if "Gateway" in item and "Iface" in item: + gateway_idx = item.index("Gateway") + iface_idx = item.index("Iface") + elif gateway_idx != None and iface_idx != None: + gateway = None + if len(item) > gateway_idx: + gateway = item[gateway_idx] + if gateway and gateway != '*' and gateway != "0.0.0.0" and len( + item) > iface_idx: + return item[iface_idx] + return "lo" + + def __get_default_iface_from_interfaces(self): + """ + get default physical interface + """ + res = os.popen("ip -f inet addr | awk NR%3==1").read().strip().split( + "\n") + for item in res: + if "BROADCAST" in item: + return item.split(":")[1].strip() + return "lo" + + def barrier(self, comm_world): + """ + dummy barrier, do nothing + """ + if not self._is_initialized: + warnings.warn(self._err_init) + return + + if comm_world not in self._comm_world: + raise ValueError(self._err_world) + + if comm_world == "worker": + self._worker_comm.barrier() + elif comm_world == "server": + self._server_comm.barrier() + else: + self._nodes_comm.barrier() + + def all_reduce(self, input, mode="sum", comm_world="worker"): + if not self._is_initialized: + warnings.warn(self._err_init) + return input + + if comm_world not in self._comm_world: + raise ValueError(self._err_world) + + input = np.array(input) + input_shape = input.shape + input_list = input.reshape(-1).tolist() + + self.barrier(comm_world) + + if comm_world == "worker": + ans = self._worker_comm.all_reduce(input_list, mode) + elif comm_world == "server": + ans = self._server_comm.all_reduce(input_list, mode) + else: + ans = self._nodes_comm.all_reduce(input_list, mode) + + output = np.array(ans).reshape(input_shape) + return output + + def all_gather(self, input, comm_world="worker"): + """ + dummy all gather, do nothing + Args: + obj(any): obj to do all gather + """ + if not self._is_initialized: + warnings.warn(self._err_init) + return input + + if comm_world not in self._comm_world: + raise ValueError(self._err_world) + + if comm_world == "worker": + output = self._worker_comm.all_gather(input) + elif comm_world == "server": + output = self._server_comm.all_gather(input) + else: + output = self._nodes_comm.all_gather(input) + + return output + + +class RoleMakerBase(object): + """ + RoleMakerBase is a base class for assigning a role to current process + in distributed training. + A paddle developer can implement RoleMakerBase to design a role maker + for worker or pserver assignment. + """ + + def __init__(self): + self._worker_endpoints = [] + self._server_endpoints = [] + self._cur_endpoint = "" + self._role_is_generated = False + self._role = None + self._current_id = -1 + + def _is_worker(self): + """ + return is_worker() of current process + """ + raise NotImplementedError("Please implement this method in child class") + + def _is_server(self): + """ + return is_server() of current process + """ + raise NotImplementedError("Please implement this method in child class") + + def _is_first_worker(self): + """ + Check whether the node is the first instance of worker. + Returns: + bool: True if this is the first node of worker, + False if not. + """ + raise NotImplementedError("Please implement this method in child class") + + def _worker_num(self): + """ + Get current total worker number. + + Returns: + int: worker number + """ + raise NotImplementedError("Please implement this method in child class") + + def _server_num(self): + """ + Get current total server number. + + Returns: + int: server number + """ + raise NotImplementedError("Please implement this method in child class") + + def _worker_index(self): + """ + Get current worker id. + + Returns: + int: node id + """ + raise NotImplementedError("Please implement this method in child class") + + def _server_index(self): + """ + Get current server id. + + Returns: + int: node id + """ + raise NotImplementedError("Please implement this method in child class") + + def _role_id(self): + """ + Get current id. + + Returns: + int: node id + """ + raise NotImplementedError("Please implement this method in child class") + + def _node_num(self): + """ + Get the training node number + Returns: + int: node num + """ + raise NotImplementedError("Please implement this method in child class") + + def _get_trainer_endpoints(self): + """ + return trainer endpoints + """ + return self._worker_endpoints + + def _get_pserver_endpoints(self): + """ + return pserver endpoints + """ + return self._server_endpoints + + def to_string(self): + return "role: {}, current_id: {}, worker_endpoints: {}, server_endpoints: {}".format( + self._role, self._current_id, self._worker_endpoints, + self._server_endpoints) + + def _all_gather(self, input, comm_world="worker"): + print("warning: RoleMakerBase does not have all gather worker.") + return None + + def _all_reduce(self, input, mode="sum", comm_world="worker"): + """ + Args: + input(list/numpy.array): array of one dim + output(list/numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + print("warning: RoleMakerBase does not have all reduce worker.") + return None + + def _barrier(self, comm_world): + """ + barrier between trainers if current role is TRAINER + """ + print("warning: RoleMakerBase does not have barrier worker.") + + #def _is_heter_worker(self): + # """ + # Return is_heter_worker() of current process + # """ + # raise NotImplementedError("Please implement this method in child class") + + #def _heter_worker_num(self): + # """ + # Get current total heter-worker number. + # + # Returns: + # int: heter_worker number + # """ + # raise NotImplementedError("Please implement this method in child class") + + #def _get_heter_worker_endpoints(self): + # """ + # Returns: + # string: all heter_trainers'endpoints + # """ + # raise NotImplementedError("Please implement this method in child class") + + #def _get_heter_worker_endpoint(self): + # """ + # Returns: + # int: corresponding heter_trainer's endpoint + # """ + # raise NotImplementedError("Please implement this method in child class") + + +class PaddleCloudRoleMaker(RoleMakerBase): + + def __init__(self, is_collective=False, **kwargs): + super(PaddleCloudRoleMaker, self).__init__() + self._is_collective = is_collective + self._non_distributed = False + + self._kwargs = kwargs + self._role_is_generated = False + + # for heterps + self._stage_id = 1 + self._stage_num = 1 + self._next_heter_trainer_endpoints = [] + self._previous_heter_trainer_endpoints = [] + self._heter_trainer_endpoints = [] + self._heter_trainer_device = "cpu" + self._heter_trainer_device_type = "cpu" + self._is_heter_parameter_server_mode = False + self._stage_trainers = [] + + self._server_endpoints = [] + self._worker_endpoints = [] + self._coordinator_endpoints = None + self._with_coordinator = False + + self._gloo = Gloo() # gloo instance + + def _barrier(self, comm_world): + self._gloo.barrier(comm_world) + + def _all_gather(self, input, comm_world="worker"): + return self._gloo.all_gather(input, comm_world) + + def _all_reduce(self, input, mode="sum", comm_world="worker"): + return self._gloo.all_reduce(input, mode, comm_world) + + def _heter_device(self): + """ + return the heter device that current heter worker is using + """ + if not self._role_is_generated: + self._generate_role() + return self._heter_trainer_device + + def _heter_device_type(self): + """ + return the heter device type that current heter worker is using + """ + if not self._role_is_generated: + self._generate_role() + return self._heter_trainer_device_type + + def _get_stage_id(self): + """ + return stage id of current heter worker + """ + if not self._role_is_generated: + self._generate_role() + return self._stage_id + + def _get_stage_trainers(self): + """ + return trainer num of all stages + """ + if not self._role_is_generated: + self._generate_role() + return self._stage_trainers + + def _get_num_stage(self): + """ + return stage num + """ + if not self._role_is_generated: + self._generate_role() + return self._stage_num + + def _is_worker(self): + """ + whether current process is worker + """ + if not self._role_is_generated: + self._generate_role() + return self._role == Role.WORKER + + def _is_server(self): + """ + whether current process is server + """ + if not self._role_is_generated: + self._generate_role() + return self._role == Role.SERVER + + def _is_coordinator(self): + if not self._role_is_generated: + self._generate_role() + return self._role == Role.COORDINATOR + + def _is_first_worker(self): + """ + whether current process is worker of rank 0 + """ + if not self._role_is_generated: + self._generate_role() + return self._role == Role.WORKER and self._current_id == 0 + + def _worker_index(self): + """ + get index of current worker + """ + if not self._role_is_generated: + self._generate_role() + return self._current_id + + def _server_index(self): + """ + get index of current server + """ + if not self._role_is_generated: + self._generate_role() + return self._current_id + + def _role_id(self): + """ + get index of current node + """ + if not self._role_is_generated: + self._generate_role() + return self._current_id + + def _worker_num(self): + """ + retrun the current number of worker + """ + if not self._role_is_generated: + self._generate_role() + return self._trainers_num + + def _server_num(self): + """ + return the current number of server + """ + if not self._role_is_generated: + self._generate_role() + return len(self._get_pserver_endpoints() + ) if self._get_pserver_endpoints() is not None else 0 + + def _node_num(self): + """ + return the training node number + """ + if not self._role_is_generated: + self._generate_role() + return self._nodes_num + + def _get_node_num(self): + """ + return the training node number + """ + if not self._role_is_generated: + self._generate_role() + return self._nodes_num + + def _get_local_rank(self): + if not self._role_is_generated: + self._generate_role() + return self._local_rank + + def _get_local_device_ids(self): + if not self._role_is_generated: + self._generate_role() + return self._local_device_ids + + def _get_world_device_ids(self): + if not self._role_is_generated: + self._generate_role() + return self._world_device_ids + + def _get_trainer_endpoints(self): + """ + get endpoint of all trainers + """ + if not self._role_is_generated: + self._generate_role() + return self._worker_endpoints + + def _get_trainer_endpoint(self): + if not self._role_is_generated: + self._generate_role() + assert self._role == Role.WORKER, "get_trainer_endpoint should be called by trainer" + return self._cur_endpoint + + def _get_heter_worker_endpoints(self): + """ + Returns: + string: all heter_trainers'endpoints + """ + if not self._role_is_generated: + self._generate_role() + assert self._heter_trainer_endpoints != [], "Heter Worker Endpoints Not initialized" + return self._heter_trainer_endpoints + + def _get_heter_worker_endpoint(self): + """ + Returns: + int: corresponding heter_trainer's endpoint + """ + if not self._role_is_generated: + self._generate_role() + assert self._role == Role.HETER_WORKER, "_get_heter_worker_endpoint should be invoked by heter worker" + return self._cur_endpoint + + def _get_pserver_endpoints(self): + """ + get endpoint of all pservers + """ + if not self._role_is_generated: + self._generate_role() + return self._server_endpoints + + def _get_coordinator_endpoints(self): + if not self._role_is_generated: + self._generate_role() + return self._coordinator_endpoints + + def _get_previous_trainers(self): + """ + invoked by heter worker + """ + if not self._role_is_generated: + self._generate_role() + assert self._role in ( + Role.WORKER, Role.HETER_WORKER + ), "_get_previous_trainers should be invoked by trainer or heter worker" + return self._previous_heter_trainer_endpoints + + def _get_next_trainers(self): + """ + invoked by heter worker + """ + if not self._role_is_generated: + self._generate_role() + assert self._role in ( + Role.WORKER, Role.HETER_WORKER + ), "_get_next_trainers should be invoked by trainer or heter worker" + return self._next_heter_trainer_endpoints + + def _is_non_distributed(self): + """ + Return True if indispensable environment for fleetrun is not found + (use python-run to launch fleet-code directly) + """ + if not self._role_is_generated: + self._generate_role() + return self._non_distributed + + def _heter_worker_num(self): + """ + get heter worker nums + """ + if not self._role_is_generated: + self._generate_role() + return self._heter_trainers_num + + def _is_heter_worker(self): + """ + whether current process is heter worker + """ + if not self._role_is_generated: + self._generate_role() + return self._role == Role.HETER_WORKER + + def _ps_env(self): # each role will execute it + # Environment variable PADDLE_PSERVERS_IP_PORT_LIST must be set + # format: string(ip:port,ip:port), eg. 127.0.0.1:6001,127.0.0.1:6002 + self._server_endpoints = os.getenv("PADDLE_PSERVERS_IP_PORT_LIST", None) + + if self._server_endpoints is None: + # back to non_distributed execution. + self._server_endpoints = "" + self._trainers_num = 1 + self._role = Role.WORKER + self._current_id = 0 + self._nodes_num = 1 + self._heter_trainers_num = 0 + self._heter_trainer_endpoints = None + self._non_distributed = True + return + + self._server_endpoints = self._server_endpoints.split(",") + + self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS", None) + if self._worker_endpoints != None: + self._worker_endpoints = self._worker_endpoints.split(",") + else: + self._worker_endpoints = [] + + self._coordinator_endpoints = os.getenv("PADDLE_COORDINATOR_ENDPOINTS", + "") + if self._coordinator_endpoints == "": + print("fl-ps > coordinator address is null!") + else: + self._with_coordinator = True + self._coordinator_endpoints = self._coordinator_endpoints.split(",") + + trainers_num = os.getenv("PADDLE_TRAINERS_NUM", None) + if trainers_num == None: + raise ValueError( + "Can not find PADDLE_TRAINERS_NUM, please check your environment." + ) + trainers_num = int(trainers_num) + + training_role = os.getenv("TRAINING_ROLE", None) + if training_role == None: + raise ValueError( + "Can not find TRAINING_ROLE, please check your environment.") + + if training_role not in [ + "TRAINER", "PSERVER", "HETER_TRAINER", "COORDINATOR" + ]: + raise ValueError( + "TRAINING_ROLE must be PSERVER or TRAINER or HETER_TRAINER or COORDINATOR, but get {}, please check your environment." + .format(training_role)) + + # For Heter Parameter Server env setting + next_heter_trainer_eplist = os.getenv( + "PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST", "") + previous_heter_trainer_eplist = os.getenv( + "PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST", "") + all_heter_trainer_eplist = os.getenv( + "PADDLE_ALL_HETER_TRAINER_IP_PORT_LIST", "") + + if all_heter_trainer_eplist != "": + self._heter_trainer_endpoints = all_heter_trainer_eplist.split(",") + self._is_heter_parameter_server_mode = True + self._heter_trainers_num = len(self._heter_trainer_endpoints) + + if previous_heter_trainer_eplist == "": + assert training_role in ( + "TRAINER", + "PSERVER"), "training_role should be trainer or pserver" + else: + try: + self._previous_heter_trainer_endpoints = previous_heter_trainer_eplist.split( + ",") + except: + raise ValueError( + "Can not Find PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST in env or its format doesn't match the requirement: 'IP:PORT,IP:PORT' ." + ) + + if next_heter_trainer_eplist == "": + assert training_role in ( + "HETER_TRAINER", "PSERVER" + ), "training_role should be heter trainer or pserver" + else: + try: + self._next_heter_trainer_endpoints = next_heter_trainer_eplist.split( + ",") + except: + raise ValueError( + "Can not Find PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST in env or its format doesn't match the requirement: 'IP:PORT,IP:PORT' ." + ) + + else: + self._is_heter_parameter_server_mode = False + self._heter_trainers_num = 0 + + if training_role == "TRAINER": + role = Role.WORKER + current_id = os.getenv("PADDLE_TRAINER_ID", None) + if current_id == None: + raise ValueError( + "Can not find PADDLE_TRAINER_ID, please check your environment." + ) + current_id = int(current_id) + if self._is_heter_parameter_server_mode: + self._stage_id = os.getenv("STAGE_ID", None) + if self._stage_id == None: + raise ValueError( + "Can not find STAGE_ID, please check your environment.") + self._stage_id = int(self._stage_id) + self._stage_num = os.getenv("STAGE_NUM", None) + if self._stage_num == None: + raise ValueError( + "Can not find STAGE_NUM, please check your environment." + ) + self._stage_num = int(self._stage_num) + self._stage_trainers = os.getenv("PADDLE_STAGE_TRAINERS_NUM", + None) + if self._stage_trainers == None: + raise ValueError( + "Can not find PADDLE_STAGE_TRAINERS_NUM, please check your environment." + ) + self._stage_trainers = eval(self._stage_trainers) + cur_port = os.getenv("PADDLE_PORT", None) + if cur_port == None: + raise ValueError( + "Can not find PADDLE_PORT, please check your environment.") + cur_ip = os.getenv("POD_IP", None) + if cur_ip == None: + raise ValueError( + "Can not find POD_IP, please check your environment.") + curr_endpoint = ":".join([cur_ip, cur_port]) + self._cur_endpoint = curr_endpoint + elif training_role == "COORDINATOR": + print(">>> curr node is coordinator!") + role = Role.COORDINATOR + current_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) + elif training_role == "PSERVER": + role = Role.SERVER + cur_port = os.getenv("PADDLE_PORT", None) + if cur_port == None: + raise ValueError( + "Can not find PADDLE_PORT, please check your environment.") + cur_ip = os.getenv("POD_IP", None) + if cur_ip == None: + raise ValueError( + "Can not find POD_IP, please check your environment.") + curr_endpoint = ":".join([cur_ip, cur_port]) + self._cur_endpoint = curr_endpoint + current_id = self._server_endpoints.index(self._cur_endpoint) + elif training_role == "HETER_TRAINER": + role = Role.HETER_WORKER + self._stage_id = os.getenv("STAGE_ID", None) + if self._stage_id == None: + raise ValueError( + "Can not find STAGE_ID, please check your environment.") + self._stage_id = int(self._stage_id) + self._stage_num = os.getenv("STAGE_NUM", None) + if self._stage_num == None: + raise ValueError( + "Can not find STAGE_NUM, please check your environment.") + self._stage_num = int(self._stage_num) + + self._stage_trainers = os.getenv("PADDLE_STAGE_TRAINERS_NUM", None) + if self._stage_trainers == None: + raise ValueError( + "Can not find PADDLE_STAGE_TRAINERS_NUM, please check your environment." + ) + self._stage_trainers = eval(self._stage_trainers) + + self._heter_trainer_device_type = os.getenv("HETER_DEVICE_TYPE", + None) + if self._heter_trainer_device_type == None: + raise ValueError( + "Can not find HETER_DEVICE_TYPE, please check your environment." + ) + assert self._heter_trainer_device_type in ( + "cpu", "gpu", + "xpu"), "HETER_DEVICE_TYPE should be cpu,gpu or xpu" + if self._heter_trainer_device_type == "gpu": + heter_device_id = os.getenv("FLAGS_selected_gpus", "0") + self._heter_trainer_device = ":".join( + (self._heter_trainer_device_type, heter_device_id)) + if self._heter_trainer_device == "xpu": + heter_device_id = os.getenv("FLAGS_selected_xpus", "0") + self._heter_trainer_device = ":".join( + (self._heter_trainer_device_type, heter_device_id)) + + cur_port = os.getenv("PADDLE_PORT", None) + if cur_port == None: + raise ValueError( + "Can not find PADDLE_PORT, please check your environment.") + cur_ip = os.getenv("POD_IP", None) + if cur_ip == None: + raise ValueError( + "Can not find POD_IP, please check your environment.") + curr_endpoint = ":".join([cur_ip, cur_port]) + self._cur_endpoint = curr_endpoint + current_id = all_heter_trainer_eplist.split(",").index( + curr_endpoint) + trainers_num + + self._trainers_num = trainers_num + self._role = role + self._current_id = current_id + self._nodes_num = len( + set([x.split(':')[0] for x in self._worker_endpoints])) + + def _collective_env(self): + self._current_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) + self._training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER") + assert (self._training_role == "TRAINER") + self._role = Role.WORKER + self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS") + self._cur_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT") + if self._worker_endpoints is None: + # back to non_distributed execution. + self._worker_endpoints = "127.0.0.1:6170" + self._cur_endpoint = self._worker_endpoints + self._non_distributed = True + self._worker_endpoints = self._worker_endpoints.split(",") + self._trainers_num = len(self._worker_endpoints) + self._nodes_num = len( + set([x.split(':')[0] for x in self._worker_endpoints])) + self._local_rank = os.getenv("PADDLE_RANK_IN_NODE") + self._local_device_ids = os.getenv("PADDLE_LOCAL_DEVICE_IDS") + self._world_device_ids = os.getenv("PADDLE_WORLD_DEVICE_IDS") + + def _gloo_init(self): + # PADDLE_WITH_GLOO 1: trainer barrier, 2: all barrier + use_gloo = int(os.getenv("PADDLE_WITH_GLOO", "0")) + if use_gloo not in [1, 2]: + return + + # PADDLE_GLOO_RENDEZVOUS 1: HDFS 2: FILE 3: HTTP + rendezvous_type = int(os.getenv("PADDLE_GLOO_RENDEZVOUS", "0")) + prefix = os.getenv("SYS_JOB_ID", "") + if rendezvous_type not in [ + Gloo.RENDEZVOUS.HDFS, Gloo.RENDEZVOUS.HTTP, Gloo.RENDEZVOUS.FILE + ]: + raise ValueError(self._gloo._err_type) + + need_init_all = True if use_gloo == 2 else False + + if rendezvous_type == Gloo.RENDEZVOUS.HDFS: + dfs_name = os.getenv("PADDLE_GLOO_FS_NAME", "") + dfs_ugi = os.getenv("PADDLE_GLOO_FS_UGI", "") + dfs_path = os.getenv("PADDLE_GLOO_FS_PATH", "") + kwargs = { + "dfs.name": dfs_name, + "dfs.ugi": dfs_ugi, + "dfs.path": dfs_path, + "store.prefix": prefix, + } + elif rendezvous_type == Gloo.RENDEZVOUS.HTTP: + start_http_server = False + manager = Manager() + http_server_d = manager.dict() + http_server_d["running"] = False + if self._is_collective: + ep_rank_0 = self._worker_endpoints[0] + if self._is_first_worker(): + start_http_server = True + else: + ep_rank_0 = os.getenv("PADDLE_GLOO_HTTP_ENDPOINT", "") + if self._is_server() and self._server_index() == 0: + start_http_server = True + ip, port = ep_rank_0.split(':') + kwargs = { + "http.host": ip, + "http.port": port, + "store.prefix": prefix, + 'start_http_server': start_http_server, + 'http_server_d': http_server_d, + } + else: + dfs_path = os.getenv("PADDLE_GLOO_FS_PATH", "") + kwargs = { + "dfs.path": dfs_path, + "store.prefix": prefix, + } + + if rendezvous_type == Gloo.RENDEZVOUS.HDFS: + type = "HDFS" + elif rendezvous_type == Gloo.RENDEZVOUS.HTTP: + type = "HTTP" + else: + type = "FILE" + print("Gloo init with {}: need_init_all: {}, args: {}".format( + type, need_init_all, kwargs)) + + self._gloo.init(rendezvous=rendezvous_type, + role=self._role, + role_id=self._role_id(), + worker_num=self._worker_num(), + server_num=self._server_num(), + need_init_all=need_init_all, + kwargs=kwargs) + + if rendezvous_type == Gloo.RENDEZVOUS.HTTP: + http_server_d['running'] = False + + def _generate_role(self): + """ + generate role for role maker + """ + if not self._role_is_generated: + if not self._is_collective: + self._ps_env() + else: + self._collective_env() + self._role_is_generated = True + if not paddle.fluid.framework._non_static_mode(): + self._gloo_init() + + +class UserDefinedRoleMaker(PaddleCloudRoleMaker): + + def __init__(self, is_collective=False, init_gloo=False, **kwargs): + super(UserDefinedRoleMaker, self).__init__(is_collective=is_collective, + init_gloo=init_gloo, + **kwargs) + self._init_gloo = init_gloo + + def _user_defined_ps_env(self): + self._server_endpoints = self._kwargs.get("server_endpoints") + self._worker_endpoints = self._kwargs.get("worker_endpoints", []) + self._trainers_num = self._kwargs.get("worker_num", 0) + + if self._trainers_num == 0: + assert (len(self._worker_endpoints) > 0) + self._trainers_num = len(self._worker_endpoints) + + self._role = self._kwargs.get("role") + self._current_id = self._kwargs.get("current_id") + + if self._role == Role.WORKER and len( + self._worker_endpoints) > self._current_id: + self._cur_endpoint = self._worker_endpoints[self._current_id] + elif self._role == Role.SERVER: + self._cur_endpoint = self._server_endpoints[self._current_id] + self._nodes_num = len( + set([x.split(':')[0] for x in self._worker_endpoints])) + + def _user_defined_collective_env(self): + self._worker_endpoints = self._kwargs.get("worker_endpoints") + self._current_id = self._kwargs.get("current_id") + self._trainers_num = len(self._worker_endpoints) + self._training_role = Role.WORKER + self._nodes_num = len( + set([x.split(':')[0] for x in self._worker_endpoints])) + + def _generate_role(self): + """ + generate role for role maker + """ + if not self._role_is_generated: + if not self._is_collective: + self._user_defined_ps_env() + else: + self._user_defined_collective_env() + self._role_is_generated = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/runtime_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/runtime_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..79dac6716cb26b7e840ea05ce70b8e46d804effc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/runtime_factory.py @@ -0,0 +1,37 @@ +# 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. +from ..runtime.collective_runtime import CollectiveRuntime +from ..runtime.parameter_server_runtime import ParameterServerRuntime +from ...ps.the_one_ps import TheOnePSRuntime + +__all__ = [] + + +class RuntimeFactory(object): + + def __init__(self): + pass + + def _create_runtime(self, context): + if context["role_maker"]._is_collective: + collective_runtime = CollectiveRuntime() + collective_runtime._set_basic_info(context) + return collective_runtime + + k_steps = context["valid_strategy"].a_sync_configs["k_steps"] + + if not context["role_maker"]._is_collective and k_steps >= 0: + ps_runtime = TheOnePSRuntime() + ps_runtime._set_basic_info(context) + return ps_runtime diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/strategy_compiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/strategy_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..823061f903543699474925d0f6d7fb7078b44ba8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/strategy_compiler.py @@ -0,0 +1,213 @@ +# 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. + +__all__ = [] + + +def create_graph(optimizer_list): + nsize = len(optimizer_list) + + edge = [[0] * nsize for _ in range(nsize)] # adjacency matrix + indegree = [0] * nsize + for i, opt in enumerate(optimizer_list): + for j, opt_inner in enumerate(optimizer_list): + if opt._can_update(opt_inner): + edge[i][j] = 1 # weight + indegree[j] += 1 + + return edge, indegree + + +def topo_sort(edge, indegree): + nsize = len(indegree) + + topo = [-1] * nsize + for i in range(nsize): + j = 0 + while j < nsize and indegree[j] != 0: + j += 1 + assert j < nsize, 'The combination of meta optimizers contains ring' + + topo[i] = j + indegree[j] = -1 + for k in range(nsize): + if edge[j][k] != 0: + indegree[k] -= 1 + + return topo + + +def floyd(edge): + nsize = len(edge) + max_len = -1 + max_edge = [-1, -1] + + max_path = [[[] for _ in range(nsize)] for _ in range(nsize)] + for i in range(nsize): + for j in range(nsize): + if edge[i][j] > 0: + max_path[i][j] = [j] + + if edge[i][j] > max_len: + max_len = edge[i][j] + max_edge = [i, j] + + # use floyd algorithm to find max_path + for k in range(nsize): + for i in range(nsize): + for j in range(nsize): + # if a-->b-->c, but a-/->c, can only apply a-->b or b-->c, + # however if a-->b-->c, and a-->c, can apply a->b->c + if edge[i][j] == 0: + continue + + if edge[i][k] == 0 or edge[k][j] == 0: + continue + + if edge[i][j] < edge[i][k] + edge[k][j]: + edge[i][j] = edge[i][k] + edge[k][j] + max_path[i][j] = max_path[i][k] + max_path[k][j] + + max_len = edge[i][j] + max_edge = [i, j] + + if max_len == -1: + return [0] + + return [max_edge[0]] + max_path[max_edge[0]][max_edge[1]] + + +def maximum_path_len_algo(optimizer_list): + if len(optimizer_list) == 0: + return None + + edge, indegree = create_graph(optimizer_list) + topo_sort(edge, indegree) + max_path = floyd(edge) + + candidate = [] + for idx in max_path: + candidate.append(optimizer_list[idx]) + + for idx, opt in enumerate(candidate[:-1]): + opt._update_inner_optimizer(candidate[idx + 1]) + + return candidate + + +class StrategyCompilerBase(object): + + def __init__(self): + pass + + +class StrategyCompiler(StrategyCompilerBase): + """ + StrategyCompiler is responsible for meta optimizers combination + Generally, a user can define serveral distributed strategies that + can generate serveral meta optimizer. The combination of these + meta optimizers should have the right order to apply the optimizers' + minimize function. + This class is responsible for the executable distributed optimizer + generation. + """ + + def __init__(self): + super(StrategyCompiler, self).__init__() + self._meta_optimizers = [] + self._graph_optimizers = [] + self._valid_optimizer_list = None + self._user_defined_strategy = None + self._meta_optimizer_candidates = [] + self._graph_optimizer_candidates = [] + + def _get_applied_meta_optimizer(self): + return self._meta_optimizers + + def _get_applied_meta_list(self): + return [type(opt).__name__ for opt in self._meta_optimizers] + + def _get_applied_graph_list(self): + return [type(opt).__name__ for opt in self._graph_optimizers] + + def _get_valid_strategy(self, dist_strategy, can_not_apply_optimizer_list): + import copy + valid_strategy = copy.deepcopy(dist_strategy) + invalid_optimizers = [] + for candidate in self._meta_optimizer_candidates: + is_valid = False + for valid in self._meta_optimizers: + if candidate.__class__.__name__ == valid.__class__.__name__: + is_valid = True + break + if not is_valid: + invalid_optimizers.append(candidate) + for opt in invalid_optimizers: + opt._disable_strategy(valid_strategy) + for opt in can_not_apply_optimizer_list: + opt._disable_strategy(valid_strategy) + return valid_strategy + + """ + Meta Optimizer Type A: rewrite forward, backward. e.g. recompute, async, sync, pipeline. + results will be splitted in async, sync, pipeline + Meta Optimizer Type B: rewrite forward, + e.g. AMP and the corresponding backward is generated by rewritten forward + Meta Opitmizer Type B: rewrite backward. e.g. gradient fusion + Meta Optimizer Type D: rewrite optimize. e.g. lars, lamb, localsgd, gradient merge, dgc + Meta Optimizer Type E: only transpile to Graph structure for runtime, + currently, grad fusion and kernel fusion, sync batch-norm included. + we will remove grad fusion and sync batch-norm + """ + + def generate_optimizer(self, loss, role_maker, optimizer, + user_defined_strategy, meta_optimizer_list, + graph_optimizer_list): + self._user_defined_strategy = user_defined_strategy + self._meta_optimizer_candidates = meta_optimizer_list + self._graph_optimizer_candidates = graph_optimizer_list + + if len(meta_optimizer_list) == 0 and len(graph_optimizer_list) == 0: + return optimizer, None + else: + # currently, we use heuristic algorithm to select + # meta optimizers combinations + meta_optimizers = maximum_path_len_algo(meta_optimizer_list) + graph_optimizers = maximum_path_len_algo(graph_optimizer_list) + # should design a distributed strategy update interface + # when we have finally decided the combination of meta_optimizer + # and graph_optimizer, the corresponding distributed strategy + # should be updated. + + self._meta_optimizers = [] if meta_optimizers is None else meta_optimizers + self._graph_optimizers = [] if graph_optimizers is None else graph_optimizers + + return_meta = None if meta_optimizers == None else meta_optimizers[0] + return_graph = None if graph_optimizers == None else graph_optimizers[ + 0] + + if meta_optimizers == None or graph_optimizers == None: + return return_meta, return_graph + + # do heuristic filter here, if any meta optimizer in graph optimizers is in + # any meta optimizers' black list, set return_graph to None + need_graph_opt = True + for graph_opt in graph_optimizers: + for program_opt in meta_optimizers: + if graph_opt.__class__.__name__ in program_opt.meta_optimizers_black_list: + need_graph_opt = False + if not need_graph_opt: + return_graph = None + + return return_meta, return_graph diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/topology.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/topology.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad6ce3bd0033b5148884aa06a5ec9566bc7cc19 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/topology.py @@ -0,0 +1,444 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function +import sys +import paddle +import collections +import numpy as np +from itertools import product +from functools import reduce +from ..utils.log_util import logger + +__all__ = ['CommunicateTopology', 'HybridCommunicateGroup'] + +_HYBRID_PARALLEL_GROUP = None + + +class ParallelMode(object): + """ + + There are all the parallel modes currently supported: + + - DATA_PARALLEL: Distribute input data to different devices. + - TENSOR_PARALLEL: Shards tensors in the network to different devices. + - PIPELINE_PARALLEL: Place different layers of the network on different devices. + - SHARDING_PARALLEL: Segment the model parameters, parameter gradients and optimizer states corresponding to the parameters to each device. + + Examples: + .. code-block:: python + + import paddle + parallel_mode = paddle.distributed.ParallelMode + print(parallel_mode.DATA_PARALLEL) # 0 + + """ + + DATA_PARALLEL = 0 + TENSOR_PARALLEL = 1 + PIPELINE_PARALLEL = 2 + SHARDING_PARALLEL = 3 + + +class CommunicateTopology(object): + def __init__( + self, + hybrid_group_names=["data", "pipe", "sharding", "model"], + dims=[1, 1, 1, 1], + ): + self._parallel_names = hybrid_group_names + self._dims = dims + self.coordinate = collections.namedtuple( + 'Coordinate', self._parallel_names + ) + self._world_size = reduce(lambda x, y: x * y, self._dims) + + ranges = [range(d) for d in self._dims] + all_coordinate = [self.coordinate(*x) for x in product(*ranges)] + + self._coord2rank = dict(zip(all_coordinate, range(len(all_coordinate)))) + self._rank2coord = dict( + zip(self._coord2rank.values(), self._coord2rank.keys()) + ) + + def get_hybrid_group_names(self): + return self._parallel_names + + def get_dim(self, axis_name): + return self._dims[self._parallel_names.index(axis_name)] + + def world_size(self): + return self._world_size + + def get_rank(self, **args): + assert len(args) == len(self._dims) + key = self.coordinate(**args) + assert key in self._coord2rank.keys() + return self._coord2rank[key] + + def get_coord(self, rank): + assert rank < self._world_size + assert rank in self._rank2coord.keys() + return self._rank2coord[rank] + + def get_axis_list(self, axis_name, index): + axis = self._parallel_names.index(axis_name) + ranks = [ + self._coord2rank[coord] + for coord in self._coord2rank.keys() + if coord[axis] == index + ] + ranks.sort() + return ranks + + def get_dim_size(self, axis_name): + assert axis_name in self._parallel_names + return self._dims[self._parallel_names.index(axis_name)] + + def get_comm_list(self, axis_name): + assert axis_name in self._parallel_names + other_axis_names = [ + name for name in self._parallel_names if name != axis_name + ] + + ranges = [] + for name in other_axis_names: + dim_num = self.get_dim_size(name) + ranges.append(range(dim_num)) + + all_result = [] + for x in product(*ranges): + key_coord = {} + for other_name in other_axis_names: + key_coord[other_name] = x[other_axis_names.index(other_name)] + + result = [] + for i in range(0, self.get_dim_size(axis_name)): + key_coord[axis_name] = i + result.append(self._coord2rank[self.coordinate(**key_coord)]) + all_result.append(result) + + return all_result + + def get_rank_from_stage(self, global_rank, **kwargs): + coord = self.get_coord(global_rank) + tf = coord._replace(**kwargs)._asdict() + return self.get_rank(**tf) + + +class HybridCommunicateGroup(object): + def __init__(self, topology): + self.nranks = paddle.distributed.get_world_size() + self.global_rank = paddle.distributed.get_rank() + self._topo = topology + + self._dp_degree = self._topo.get_dim('data') + self._mp_degree = self._topo.get_dim('model') + self._pp_degree = self._topo.get_dim('pipe') + self._sharding_degree = self._topo.get_dim('sharding') + + self._data_parallel_id = self._get_data_parallel_id() + self._model_parallel_id = self._get_model_parallel_id() + self._sharding_parallel_id = self._get_sharding_parallel_id() + self.stage_id = self._get_pipe_parallel_id() + + assert self._check_vaild_topo(), ( + "Here is an unreasonable topogy setting. world_size: {}, but" + "mp_num: {}, sharding_num: {}, pp_num: {}, dp_num: {}".format( + self.nranks, + self._mp_degree, + self._sharding_degree, + self._pp_degree, + self._dp_degree, + ) + ) + + # create comm group for data parallel + self._dp_group, self._dp_comm_group = self._set_comm_group("data") + + # create comm group for model parallel + self._mp_group, self._mp_comm_group = self._set_comm_group("model") + + # create comm group for pipe parallel + self._pp_group, self._pp_comm_group = self._set_comm_group("pipe") + + # create comm group for sharding parallel + self._sharding_group, self._sharding_comm_group = self._set_comm_group( + "sharding" + ) + + # create global group for check inf_nan / clip global norm + self._check_group, self._check_comm_group = self._set_check_group( + "data" + ) + + # create p2p group + self.is_first_stage = self.stage_id == 0 + self.is_last_stage = self.stage_id == (self._pp_degree - 1) + + # create p2p_groups + if self._pp_degree > 1: + self._set_p2p_group() + + debug_str = ( + "HybridParallelInfo: rank_id: %d, mp_degree: %d, " + "sharding_degree: %d, pp_degree: %d, dp_degree: %d" + % ( + self.global_rank, + self._mp_degree, + self._sharding_degree, + self._pp_degree, + self._dp_degree, + ) + ) + debug_str += ( + ", mp_group: %s, sharding_group: %s, pp_group: %s, dp_group: %s, check/clip group: %s" + % ( + self._mp_group, + self._sharding_group, + self._pp_group, + self._dp_group, + self._check_group, + ) + ) + logger.info(debug_str) + + global _HYBRID_PARALLEL_GROUP + _HYBRID_PARALLEL_GROUP = self + + def get_parallel_mode(self): + # there are four modes : DataParallel / TensorParallel / PipelineParallel / ShardingParallel + # NOTE when sharding conjugates with other parallel, sharding should act like a optimizer and + # adding its parallel logic within that parallelism + # when use sharding alone, it should have its own parallelism for its parallel logic + # TODO modify 3 others parallel to support sharding + if ( + self._mp_degree == 1 + and self._pp_degree == 1 + and self._dp_degree == 1 + and self._sharding_degree > 1 + ): + return ParallelMode.SHARDING_PARALLEL + elif self._mp_degree == 1 and self._pp_degree == 1: + return ParallelMode.DATA_PARALLEL + elif self._mp_degree > 1 and self._pp_degree == 1: + # initialize the seed + return ParallelMode.TENSOR_PARALLEL + elif self._pp_degree > 1: + return ParallelMode.PIPELINE_PARALLEL + + def _check_vaild_topo(self): + return ( + self._dp_degree + * self._mp_degree + * self._pp_degree + * self._sharding_degree + == self.nranks + ) + + def _set_comm_group(self, parallel_method="data"): + parallel_group = [] + parallel_comm_group = None + parallel_groups = self._topo.get_comm_list(parallel_method) + + for group in parallel_groups: + comm_group = paddle.distributed.new_group(ranks=group) + if self.global_rank in group: + parallel_group = group + parallel_comm_group = comm_group + + assert len(parallel_group) > 0 + assert parallel_comm_group is not None + + return parallel_group, parallel_comm_group + + def _set_check_group(self, parallel_method="data"): + parallel_group = [] + parallel_comm_group = None + parallel_size = self._topo.get_dim(parallel_method) + for idx in range(parallel_size): + parallel_groups = self._topo.get_axis_list(parallel_method, idx) + comm_group = paddle.distributed.new_group(ranks=parallel_groups) + if self.global_rank in parallel_groups: + parallel_group = parallel_groups + parallel_comm_group = comm_group + + assert len(parallel_group) > 0 + assert parallel_comm_group is not None + + return parallel_group, parallel_comm_group + + def _get_p2p_next_rank(self): + assert hasattr(self, 'next_rank'), "next_rank has not been inited" + return self.next_rank + + def _get_p2p_prev_rank(self): + assert hasattr(self, 'prev_rank'), "prev_rank has not been inited" + return self.prev_rank + + def _set_p2p_group(self): + comm_lists = self._topo.get_comm_list('pipe') + + self.send_next_group = None + self.send_prev_group = None + self.recv_next_group = None + self.recv_prev_group = None + + for comm_ranks in comm_lists: + assert len(comm_ranks) == self._pp_degree + for idx, rank in enumerate(comm_ranks): + curr_rank = rank + next_rank = comm_ranks[(idx + 1) % self._pp_degree] + prev_rank = comm_ranks[(idx - 1) % self._pp_degree] + + if self.global_rank == curr_rank: + self.next_rank = next_rank + self.prev_rank = prev_rank + + next_group = paddle.distributed.new_group( + ranks=[curr_rank, next_rank] + ) + if self.global_rank == curr_rank: + self.send_next_group = next_group + elif self.global_rank == next_rank: + self.recv_prev_group = next_group + + prev_group = paddle.distributed.new_group( + ranks=[prev_rank, curr_rank] + ) + + if self.global_rank == curr_rank: + self.send_prev_group = prev_group + elif self.global_rank == prev_rank: + self.recv_next_group = prev_group + + assert self.send_next_group is not None + assert self.send_prev_group is not None + assert self.recv_next_group is not None + assert self.recv_prev_group is not None + + def topology(self): + return self._topo + + def get_global_rank(self): + return self.global_rank + + # data parallel message: + def _get_data_parallel_id(self): + return self._topo.get_coord(self.global_rank).data + + def get_data_parallel_rank(self): + return self._data_parallel_id + + def get_data_parallel_world_size(self): + return self._dp_degree + + def get_data_parallel_group(self): + return self._dp_comm_group + + def get_data_parallel_group_src_rank(self): + return self._dp_comm_group.ranks[0] + + # model parallel message: + def _get_model_parallel_id(self): + return self._topo.get_coord(self.global_rank).model + + def get_model_parallel_rank(self): + return self._model_parallel_id + + def get_model_parallel_world_size(self): + return self._mp_degree + + def get_model_parallel_group(self): + return self._mp_comm_group + + def get_model_parallel_group_src_rank(self): + return self._mp_comm_group.ranks[0] + + # pipeline parallel message + def _get_pipe_parallel_id(self): + return self._topo.get_coord(self.global_rank).pipe + + def get_stage_id(self): + return self.stage_id + + def get_pipe_parallel_world_size(self): + return self._pp_degree + + def get_pipe_parallel_group(self): + return self._pp_comm_group + + def get_p2p_groups(self): + return ( + self.send_next_group, + self.send_prev_group, + self.recv_next_group, + self.recv_prev_group, + ) + + # sharding parallel message: + def _get_sharding_parallel_id(self): + return self._topo.get_coord(self.global_rank).sharding + + def get_sharding_parallel_rank(self): + return self._sharding_parallel_id + + def get_sharding_parallel_world_size(self): + return self._sharding_degree + + def get_sharding_parallel_group(self): + return self._sharding_comm_group + + def get_sharding_parallel_group_src_rank(self): + # TODO should the src rank related to the shard rank for each parameter ? + return self._sharding_comm_group.ranks[0] + + # check parallel group + def get_check_parallel_group(self): + return self._check_comm_group + + def get_rank_from_stage(self, stage_id, **kwargs): + return self._topo.get_rank_from_stage( + self.global_rank, pipe=stage_id, **kwargs + ) + + +class _CommunicateGroup(object): + """tmp for static""" + + def __init__(self): + global _HYBRID_PARALLEL_GROUP + _HYBRID_PARALLEL_GROUP = self + self.groups = dict() + + def set_comm_group( + self, group_name, group_rank, group_size, ring_id, group_ranks + ): + group = paddle.distributed.collective.Group( + group_rank, ring_id, group_ranks + ) + self.groups[group_name] = group + + def get_group(self, group_name): + assert group_name in self.groups + return self.groups[group_name] + + def get_model_parallel_group(self): + return self.get_group('model') + + def get_model_parallel_world_size(self): + return self.get_group('model').nranks + + def get_model_parallel_rank(self): + return self.get_group('model').rank diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/util_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/util_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..6705eb36bf34874ea6cb728879468cac4e50d325 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/base/util_factory.py @@ -0,0 +1,610 @@ +# 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. +"""Fleet Utils.""" +"""distributed operations""" +"""basic collective operations in python""" +"""remote file system""" + +from ..utils.fs import FS, LocalFS, HDFSClient +from paddle.fluid.proto import framework_pb2 +from paddle.fluid.framework import Program +from paddle.fluid import debugger +from google.protobuf import text_format +import paddle.fluid as fluid +from collections import OrderedDict +from paddle.fluid import core +import subprocess +import os +import numpy as np + +__all__ = [] + + +class UtilFactory(object): + + def _create_util(self, context=None): + util = UtilBase() + if context is not None and "valid_strategy" in context: + util._set_strategy(context["valid_strategy"]) + if context is not None and "role_maker" in context: + util._set_role_maker(context["role_maker"]) + return util + + +class UtilBase(object): + + def __init__(self): + self.role_maker = None + self.dist_strategy = None + + def _set_strategy(self, dist_strategy): + self.dist_strategy = dist_strategy + + def _set_role_maker(self, role_maker): + self.role_maker = role_maker + + def _set_file_system(self, fs_client): + assert isinstance( + fs_client, FS + ), "fs_client must be the instance of paddle.distributed.fleet.utils.FS" + self.fs_client = fs_client + + def all_reduce(self, input, mode="sum", comm_world="worker"): + """ + All reduce `input` between specified collection. This is a distributed API. + + Args: + input (list|numpy.array): The input variable to do all_reduce between specified collection. + mode (str): "sum" or "min" or "max". + comm_world (str, optional): Collection used to execute all_reduce operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` . + + Returns: + output(Numpy.array|None): A numpy array with the same shape as the `input` . + + Examples: + .. code-block:: python + + # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` . + import paddle.distributed.fleet as fleet + from paddle.distributed.fleet import PaddleCloudRoleMaker + import sys + import numpy as np + import os + + os.environ["PADDLE_WITH_GLOO"] = "2" + + def train(): + role = PaddleCloudRoleMaker( + is_collective=False, + init_gloo=True, + path="./tmp_gloo") + fleet.init(role) + + if fleet.is_server(): + input = [1, 2] + output = fleet.util.all_reduce(input, "sum", "server") + print(output) + # [2, 4] + elif fleet.is_worker(): + input = np.array([3, 4]) + output = fleet.util.all_reduce(input, "sum", "worker") + print(output) + # [6, 8] + output = fleet.util.all_reduce(input, "sum", "all") + print(output) + # [8, 12] + if __name__ == "__main__": + train() + """ + return self.role_maker._all_reduce(input, mode, comm_world) + + def barrier(self, comm_world="worker"): + """ + Barrier between specified collection. + + Args: + comm_world (str, optional): Collection used to execute barrier operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` . + + Examples: + + .. code-block:: python + + # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` . + + import paddle.distributed.fleet as fleet + from paddle.distributed.fleet import PaddleCloudRoleMaker + import sys + import os + + os.environ["PADDLE_WITH_GLOO"] = "2" + + def train(): + role = PaddleCloudRoleMaker( + is_collective=False, + init_gloo=True, + path="./tmp_gloo") + fleet.init(role) + + if fleet.is_server(): + fleet.util.barrier("server") + print("all server arrive here") + elif fleet.is_worker(): + fleet.util.barrier("worker") + print("all server arrive here") + fleet.util.barrier("all") + print("all servers and workers arrive here") + + if __name__ == "__main__": + train() + """ + self.role_maker._barrier(comm_world) + + def all_gather(self, input, comm_world="worker"): + """ + All gather `input` between specified collection. + + Args: + input (Int|Float): The input variable to do all_gather between specified collection. + comm_world (str, optional): Collection used to execute all_reduce operation. Supported collections incude `worker` , `server` and `all` . The default is `worker` . + + Returns: + output (List): A list of gathered values. + + Examples: + + .. code-block:: python + + # Save the following code in `train.py` , and then execute the command `fleetrun --server_num 2 --worker_num 2 train.py` . + import paddle.distributed.fleet as fleet + from paddle.distributed.fleet import PaddleCloudRoleMaker + import sys + import os + + os.environ["PADDLE_WITH_GLOO"] = "2" + + def train(): + role = PaddleCloudRoleMaker( + is_collective=False, + init_gloo=True, + path="./tmp_gloo") + fleet.init(role) + + if fleet.is_server(): + input = fleet.server_index() + output = fleet.util.all_gather(input, "server") + print(output) + # output = [0, 1] + elif fleet.is_worker(): + input = fleet.worker_index() + output = fleet.util.all_gather(input, "worker") + # output = [0, 1] + print(output) + output = fleet.util.all_gather(input, "all") + print(output) + # output = [0, 1, 0, 1] + + if __name__ == "__main__": + train() + """ + + return self.role_maker._all_gather(input, comm_world) + + def _broadcast(self): + pass + + def _scatter(self): + pass + + def get_heter_file_shard(self, files): + if not isinstance(files, list): + raise TypeError("files should be a list of file need to be read.") + trainers = self.role_maker._worker_num() + trainer_id = self.role_maker._worker_index() - trainers + remainder = len(files) % trainers + blocksize = int(len(files) / trainers) + + blocks = [blocksize] * trainers + for i in range(remainder): + blocks[i] += 1 + + trainer_files = [[]] * trainers + begin = 0 + for i in range(trainers): + trainer_files[i] = files[begin:begin + blocks[i]] + begin += blocks[i] + + return trainer_files[trainer_id] + + def get_file_shard(self, files): + """ + Split files before distributed training, and return filelist assigned to the current trainer. + + .. code-block:: text + + example 1: files is [a, b, c ,d, e] and trainer_num = 2, then trainer + 0 gets [a, b, c] and trainer 1 gets [d, e]. + example 2: files is [a, b], and trainer_num = 3, then trainer 0 gets + [a], trainer 1 gets [b], trainer 2 gets [] + + Args: + files(list): File list need to be read. + + Returns: + List: Files belong to this worker. + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + from paddle.distributed.fleet import UserDefinedRoleMaker + + role = UserDefinedRoleMaker( + is_collective=False, + init_gloo=False, + current_id=0, + role=fleet.Role.WORKER, + worker_endpoints=["127.0.0.1:6003", "127.0.0.1:6004"], + server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"]) + fleet.init(role) + + files = fleet.util.get_file_shard(["file1", "file2", "file3"]) + print(files) + # files = ["file1", "file2"] + """ + if not isinstance(files, list): + raise TypeError("files should be a list of file need to be read.") + + trainer_id = self.role_maker._worker_index() + trainers = self.role_maker._worker_num() + + remainder = len(files) % trainers + blocksize = int(len(files) / trainers) + + blocks = [blocksize] * trainers + for i in range(remainder): + blocks[i] += 1 + + trainer_files = [[]] * trainers + begin = 0 + for i in range(trainers): + trainer_files[i] = files[begin:begin + blocks[i]] + begin += blocks[i] + + return trainer_files[trainer_id] + + def print_on_rank(self, message, rank_id): + """ + Woker of rank `rank_id` print some message. + + Args: + message(str): Log to be printed. + rank_id(int): trainer id. + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + from paddle.distributed.fleet import UserDefinedRoleMaker + + role = UserDefinedRoleMaker( + is_collective=False, + init_gloo=False, + current_id=0, + role=fleet.Role.WORKER, + worker_endpoints=["127.0.0.1:6003", "127.0.0.1:6004"], + server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"]) + fleet.init(role) + + fleet.util.print_on_rank("I'm worker 0", 0) + """ + if self.role_maker._worker_index() != rank_id: + return + print(message) + + def _save_program(self, program, model_filename='__model__', is_text=False): + if is_text: + with open(model_filename, "w") as f: + f.write(str(program)) + else: + with open(model_filename, "wb") as f: + f.write(program.desc.serialize_to_string()) + + def _load_program(self, path, is_text): + + def load_program_binary(path): + """load program from binary string file""" + with open(path, "rb") as f: + program_desc_str = f.read() + return Program.parse_from_string(program_desc_str) + + def load_program_text(path): + """load program from human-readable text file""" + with open(path, "r") as f: + program_desc_text = f.read() + + prog_desc = framework_pb2.ProgramDesc() + text_format.Merge(program_desc_text, prog_desc) + return Program.parse_from_string(prog_desc.SerializeToString()) + + if is_text: + return load_program_text(path) + else: + return load_program_binary(path) + + def _program_type_trans(self, prog_dir, prog_fn, is_text): + prog = self._load_program(os.path.join(prog_dir, prog_fn), is_text) + prog_out_fn = prog_fn + ".bin" if is_text else prog_fn + ".pbtxt" + self._save_program(prog, os.path.join(prog_dir, prog_out_fn), + 1 - is_text) + return prog_out_fn + + def _visualize_graphviz(self, program, output_dir, output_filename): + block = program.global_block() + dot_path = os.path.join(output_dir, output_filename + '.dot') + pdf_path = os.path.join(output_dir, output_filename + '.pdf') + debugger.draw_block_graphviz(block, path=dot_path) + cmd = ["dot", "-Tpdf", dot_path, "-o", pdf_path] + p = subprocess.Popen(cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + p.wait() + + def _proto_check(self, config): + train_prog = self._load_program(config.train_prog_path, + config.is_text_train_program) + pruned_prog = self._load_program(config.pruned_prog_path, + config.is_text_pruned_program) + + is_match = True + + pruned_vars = [(v.name, v) for v in pruned_prog.list_vars() + if fluid.io.is_persistable(v)] + pruned_vars = OrderedDict(pruned_vars) + pruned_vars_name = [name for name in pruned_vars] + print("persistable vars in pruned program: {}".format(pruned_vars_name)) + + # feed and fetch op is added in pruned program when pruning, not need to be found in train program + feed_fetch_type_list = [ + core.VarDesc.VarType.FEED_MINIBATCH, core.VarDesc.VarType.FETCH_LIST + ] + + for var_name in pruned_vars: + var = pruned_vars[var_name] + # feed and fetch op is added in pruned program when pruning, not need to be found in train program + if var.type in feed_fetch_type_list: + break + try: + train_prog_var = train_prog.global_block().var(var_name) + except ValueError as e: + print( + "Not find variable '%s' in train program. please check pruning." + % var_name) + is_match = False + continue + if var.shape != train_prog_var.shape or var.dtype != train_prog_var.dtype: + print( + "variable: {} not match. in pruned program shape: {} dtype:{}, in train program shape: {} dtype: {}" + .format(var_name, var.shape, var.dtype, + train_prog_var.shape, train_prog_var.dtype)) + is_match = False + return is_match + + def _params_check(self, config): + + def feed_gen(batch_size, feeded_vars_dims, feeded_vars_filelist): + + def reader(batch_size, fn, dim): + data = [] + if isinstance(dim, list) or isinstance(dim, tuple): + shape = list(dim) + _temp = 1 + for x in dim: + _temp = _temp * x + dim = _temp + else: + shape = [dim] + + shape = [batch_size] + shape + dim = dim * batch_size + + for line in open(fn, 'r'): + fields = line.strip().split(' ') + fields = [float(d) for d in fields] + while len(fields) >= dim: + tmp = fields[:dim] + fields = fields[dim:] + data.append(np.array(tmp).reshape(shape)) + return data + + batch_feed = [] + for i, fn in enumerate(feeded_vars_filelist): + batch_feed.append(reader(batch_size, fn, feeded_vars_dims[i])) + return batch_feed + + prog = self._load_program( + os.path.join(config.dump_model_dir, config.dump_program_filename), + config.is_text_dump_program) + if config.is_text_dump_program: + model_filename = self._program_type_trans( + config.dump_model_dir, config.dump_program_filename, + config.is_text_dump_program) + + saved_params = [ + v for v in prog.list_vars() if fluid.io.is_persistable(v) + ] + print("persistable vars in dump program: {}".format( + [v.name for v in saved_params])) + + def check_not_expected_ops(prog, not_expected_op_types): + op_types_set = set() + for op in prog.global_block().ops: + if op.type in not_expected_op_types and op.type not in op_types_set: + op_types_set.add(op.type) + return op_types_set + + not_expected_op_types = check_not_expected_ops(prog, ["lookup_table"]) + if len(not_expected_op_types) > 0: + print( + "find op type '{}' in program, please check if your program is pruned correctly !" + .format(list(not_expected_op_types))) + return False + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + scope = fluid.core.Scope() + with fluid.scope_guard(scope): + inference_program, feed_target_names, fetch_targets = \ + fluid.io.load_inference_model(config.dump_model_dir, exe, model_filename=model_filename, + params_filename=config.save_params_filename) + + # check program vars and saved vars shape + orig_para_shape = { + each_var.name: tuple(each_var.desc.shape()) + for each_var in saved_params + } + for each_var in saved_params: + var_temp = fluid.global_scope().find_var(each_var.name) + assert var_temp != None, "can't not find var: " + each_var.name + new_shape = (np.array(var_temp.get_tensor())).shape + assert each_var.name in orig_para_shape, each_var.name + "MUST in var list" + orig_shape = orig_para_shape.get(each_var.name) + if new_shape != orig_shape: + raise RuntimeError( + "Shape not matching: the Program requires a parameter with a shape of ({}), " + "while the loaded parameter (namely [ {} ]) has a shape of ({})." + .format(orig_shape, each_var.name, new_shape)) + + # check feed/fetch vars in program and config + feed_config = config.feed_config + fetch_config = config.fetch_config + fetch_targets_names = [v.name for v in fetch_targets] + if not feed_target_names: + print("warning! no feed targets in program.") + if not fetch_targets_names: + print("warning! no fetch targets in program.") + fetch_list = fetch_targets + feed_name_list = feed_target_names + if feed_config.feeded_vars_names is not None and feed_target_names != feed_config.feeded_vars_names: + print( + "warning! feed vars in program and config are diff: feed in program: {}. feed in config {}." + .format(feed_target_names, feed_config.feeded_vars_names)) + feed_name_list = feed_config.feeded_vars_names + # remove feed op in inference_program. new feed op will be added in exe.run + global_block = inference_program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "feed": # only remove feed op here + need_to_remove_op_index.append(i) + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + if fetch_config.fetch_vars_names is not None and fetch_targets_names != fetch_config.fetch_vars_names: + print( + "warning! fetch vars in program and config are diff: fetch in program: {}. fetch in config {}." + .format(fetch_targets_names, fetch_config.fetch_vars_names)) + fetch_list = [ + inference_program.global_block().var(i) + for i in fetch_config.fetch_vars_names + ] + # remove fetch op in inference_program. new fetch op will be added in exe.run + global_block = inference_program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "fetch": # only remove fetch op here + need_to_remove_op_index.append(i) + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + + # if fetch_list have lod tensor + return_numpy = all([v.lod_level == 0 for v in fetch_list]) + + # try dump fetch_targets + feed_tensors = [] + assert len(feed_config.feeded_vars_names) == len( + feed_config.feeded_vars_dims) == len( + feed_config.feeded_vars_types) + # check program vars and feed tensor shape in config + for i in range(len(feed_config.feeded_vars_names)): + var = inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + if not isinstance(feed_config.feeded_vars_dims[i], + (list, tuple)): + tensor_shape = (feed_config.feeded_vars_dims[i], ) + else: + tensor_shape = tuple(feed_config.feeded_vars_dims[i]) + feed_config.feeded_vars_dims[i] = tensor_shape + var_shape = var.shape[1:] + if tensor_shape != var_shape: + raise RuntimeError( + "feed variable '{}' shape not match. infer program shape: {}. feed tensor shape: {}" + .format(feed_config.feeded_vars_names[i], var_shape, + tensor_shape)) + + if not feed_config.feeded_vars_filelist: + print("generate random feed vars.") + for i in range(len(feed_config.feeded_vars_names)): + var = inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + # create fake feed tensor. if lod_level > 1, should create_lod_tensor() + if var.lod_level == 0: + feed_tensors.append( + np.array(np.random.random( + tuple([config.batch_size] + + list(feed_config.feeded_vars_dims[i]))), + dtype=feed_config.feeded_vars_types[i])) + elif var.lod_level == 1: + t = np.array(np.random.random( + tuple([config.batch_size] + + list(feed_config.feeded_vars_dims[i]))), + dtype=feed_config.feeded_vars_types[i]) + feed_tensors.append( + fluid.create_lod_tensor(t, + [[1] * config.batch_size], + place)) + else: + raise RuntimeError( + "vars with lod_level >= 2 is not supported now in this infer program check tool." + ) + results = exe.run(inference_program, + feed={ + name: feed_tensors[i] + for i, name in enumerate(feed_name_list) + }, + fetch_list=fetch_list, + return_numpy=return_numpy) + else: + print("load feed vars from files: {}.".format( + feed_config.feeded_vars_filelist)) + feed_vars = [ + inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + for i in range(len(feed_config.feeded_vars_names)) + ] + feeder = fluid.DataFeeder(feed_list=feed_vars, place=place) + batch_feed = feed_gen(config.batch_size, + feed_config.feeded_vars_dims, + feed_config.feeded_vars_filelist) + slots = [batch_feed] + results = exe.run(inference_program, + feed=feeder.feed(slots), + fetch_list=fetch_list, + return_numpy=return_numpy) + for i, v in enumerate(fetch_list): + print("fetch_targets name: %s" % v.name) + print("fetch_targets: {}".format(results[i])) + return results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/cloud_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/cloud_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3097bfaa4f0ee2e68fa11cf4551d5f91b844cf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/cloud_utils.py @@ -0,0 +1,110 @@ +# 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. + +import os +import paddle +from paddle.distributed.fleet.launch_utils import get_cluster, logger + +__all__ = [] + + +def get_cloud_cluster(args_node_ips, + device_mode, + devices_per_proc, + args_port=6170): + """ + args_node_ips:string, device_mode:DeviceMode(Int), device_per_proc:list, args_port: int + """ + #you can automatically get ip info while using paddlecloud multi nodes mode. + node_ips = os.getenv("PADDLE_TRAINERS") + assert node_ips is not None, "PADDLE_TRAINERS should not be None" + + node_ip = os.getenv("POD_IP") + assert node_ip is not None, "POD_IP should not be None" + + node_rank = os.getenv("PADDLE_TRAINER_ID") + assert node_rank is not None, "PADDLE_TRAINER_ID should not be None" + + paddle_ports_num = int(os.getenv("TRAINER_PORTS_NUM")) + assert paddle_ports_num is not None, "TRAINER_PORTS_NUM should not be None" + + node_ips = node_ips.split(",") + num_nodes = len(node_ips) + node_rank = int(node_rank) + + if args_node_ips != "127.0.0.1" and args_node_ips != ",".join(node_ips): + logger.warning( + "Please NOTE: When using paddlecloud, cluster_node_ips is \ +automatically got from PADDLE_TRAINERS(multi nodes) or POD_IP(single node).\ +Your input cluster_node_ips: {} doesn't equals to IPs: {} from \ +paddlecloud environment.".format(args_node_ips, node_ips)) + + # DISTRIBUTED_TRAINER_ENDPOINTS: new environment since paddlecloud 1.8.4 + # e.g: DISTRIBUTED_TRAINER_ENDPOINTS="ip1:port1,ip1:port2,ip1:port3,ip1:port4,ip2:port5,ip2:port6,ip2:port7,ip2:port8" + trainer_endpoints = os.getenv("DISTRIBUTED_TRAINER_ENDPOINTS") + if trainer_endpoints is None: + started_port = args_port + if num_nodes > 1: + try: + paddle_port = int(os.getenv("PADDLE_PORT", "")) + + if paddle_ports_num >= len( + devices_per_proc) and paddle_port != args_port: + logger.warning( + "Use Cloud specified port:{}.".format(paddle_port)) + started_port = paddle_port + + except Exception as e: + print(e) + pass + + if started_port is None: + started_port = 6170 + ports = [ + x for x in range(started_port, started_port + len(devices_per_proc)) + ] + trainer_endpoints = [] + for ip in node_ips: + trainer_endpoints.append(["%s:%d" % (ip, port) for port in ports]) + else: + trainer_endpoints_ori = trainer_endpoints.split(",") + trainer_endpoints = [] + assert num_nodes * paddle_ports_num == len(trainer_endpoints_ori) + for i in range(num_nodes): + trainer_endpoints.append( + trainer_endpoints_ori[i * paddle_ports_num:(i + 1) * + paddle_ports_num]) + + logger.debug("parsed from args: node_ips:{} \ + node_ip:{} node_rank:{} trainer_endpoints:{}".format( + node_ips, node_ip, node_rank, trainer_endpoints)) + + cluster, pod = get_cluster(node_ips, node_ip, trainer_endpoints, + device_mode, devices_per_proc) + return cluster, cluster.pods[node_rank] + + +def use_paddlecloud(): + node_ips = os.getenv("PADDLE_TRAINERS") + node_ip = os.getenv("POD_IP") + node_rank = os.getenv("PADDLE_TRAINER_ID") + paddle_ports_num = os.getenv("TRAINER_PORTS_NUM") + if node_ips is None or node_ip is None or node_rank is None or paddle_ports_num is None: + return False + else: + return True + + +def get_trainers_num(): + return int(os.getenv("PADDLE_TRAINERS_NUM", "1")) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2288aca43f75149ce84742d9a5d954e28ce5f3b9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/__init__.py @@ -0,0 +1,16 @@ +# 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 + +from .data_generator import DataGenerator, MultiSlotDataGenerator # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/data_generator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/data_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..47d9e4cc8ef0d34ebb003c6d09ec99e5c7856ba3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/data_generator/data_generator.py @@ -0,0 +1,382 @@ +# 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. + +import os +import sys + +__all__ = [] + + +class DataGenerator(object): + """ + DataGenerator is a general Base class for user to inherit + A user who wants to define his/her own python processing logic + with paddle.distributed.InMemoryDataset/QueueDataset should + inherit this class. + """ + + def __init__(self): + self._proto_info = None + self.batch_size_ = 32 + + def set_batch(self, batch_size): + ''' + Set batch size of current DataGenerator + This is necessary only if a user wants to define generator_batch + + Example: + + .. code-block:: python + + import paddle.distributed.fleet.data_generator as dg + class MyData(dg.DataGenerator): + + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", int_words) + return local_iter + + def generate_batch(self, samples): + def local_iter(): + for s in samples: + yield ("words", s[1].extend([s[1][0]])) + mydata = MyData() + mydata.set_batch(128) + + ''' + self.batch_size_ = batch_size + + def run_from_memory(self): + ''' + This function generator data from memory, it is usually used for + debug and benchmarking + + Example: + .. code-block:: python + + import paddle.distributed.fleet.data_generator as dg + class MyData(dg.DataGenerator): + + def generate_sample(self, line): + def local_iter(): + yield ("words", [1, 2, 3, 4]) + return local_iter + + mydata = MyData() + mydata.run_from_memory() + ''' + batch_samples = [] + line_iter = self.generate_sample(None) + for user_parsed_line in line_iter(): + if user_parsed_line == None: + continue + batch_samples.append(user_parsed_line) + if len(batch_samples) == self.batch_size_: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + batch_samples = [] + if len(batch_samples) > 0: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + + def run_from_stdin(self): + ''' + This function reads the data row from stdin, parses it with the + process function, and further parses the return value of the + process function with the _gen_str function. The parsed data will + be wrote to stdout and the corresponding protofile will be + generated. + + Example: + + .. code-block:: python + + import paddle.distributed.fleet.data_generator as dg + class MyData(dg.DataGenerator): + + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", [int_words]) + return local_iter + + mydata = MyData() + mydata.run_from_stdin() + + ''' + batch_samples = [] + for line in sys.stdin: + line_iter = self.generate_sample(line) + for user_parsed_line in line_iter(): + if user_parsed_line == None: + continue + batch_samples.append(user_parsed_line) + if len(batch_samples) == self.batch_size_: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + batch_samples = [] + if len(batch_samples) > 0: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the datafeed,and + updating proto_info information. + + Args: + line(str): the output of the process() function rewritten by user. + + Returns: + Return a string data that can be read directly by the datafeed. + ''' + raise NotImplementedError( + "pls use MultiSlotDataGenerator or PairWiseDataGenerator") + + def generate_sample(self, line): + ''' + This function needs to be overridden by the user to process the + original data row into a list or tuple. + + Args: + line(str): the original data row + + Returns: + Returns the data processed by the user. + The data format is list or tuple: + [(name, [feasign, ...]), ...] + or ((name, [feasign, ...]), ...) + + For example: + [("words", [1926, 08, 17]), ("label", [1])] + or (("words", [1926, 08, 17]), ("label", [1])) + + Note: + The type of feasigns must be in int or float. Once the float + element appears in the feasign, the type of that slot will be + processed into a float. + + Example: + + .. code-block:: python + + import paddle.distributed.fleet.data_generator as dg + class MyData(dg.DataGenerator): + + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", [int_words]) + return local_iter + + ''' + raise NotImplementedError( + "Please rewrite this function to return a list or tuple: " + + "[(name, [feasign, ...]), ...] or ((name, [feasign, ...]), ...)") + + def generate_batch(self, samples): + ''' + This function needs to be overridden by the user to process the + generated samples from generate_sample(self, str) function + It is usually used as batch processing when a user wants to + do preprocessing on a batch of samples, e.g. padding according to + the max length of a sample in the batch + + Args: + samples(list tuple): generated sample from generate_sample + + Returns: + a python generator, the same format as return value of generate_sample + + Example: + + .. code-block:: python + + import paddle.distributed.fleet.data_generator as dg + class MyData(dg.DataGenerator): + + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", int_words) + return local_iter + + def generate_batch(self, samples): + def local_iter(): + for s in samples: + yield ("words", s[1].extend([s[1][0]])) + mydata = MyData() + mydata.set_batch(128) + ''' + + def local_iter(): + for sample in samples: + yield sample + + return local_iter + + +# TODO: guru4elephant +# add more generalized DataGenerator that can adapt user-defined slot +# for example, [(name, float_list), (name, str_list), (name, int_list)] +class MultiSlotStringDataGenerator(DataGenerator): + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the MultiSlotDataFeed, + and updating proto_info information. + + The input line will be in this format: + >>> [(name, [str(feasign), ...]), ...] + >>> or ((name, [str(feasign), ...]), ...) + The output will be in this format: + >>> [ids_num id1 id2 ...] ... + + For example, if the input is like this: + >>> [("words", ["1926", "08", "17"]), ("label", ["1"])] + >>> or (("words", ["1926", "08", "17"]), ("label", ["1"])) + the output will be: + >>> 3 1234 2345 3456 1 1 + + Args: + line(str): the output of the process() function rewritten by user. + + Returns: + Return a string data that can be read directly by the MultiSlotDataFeed. + ''' + if sys.version > '3' and isinstance(line, zip): + line = list(line) + + if not isinstance(line, list) and not isinstance(line, tuple): + raise ValueError( + "the output of process() must be in list or tuple type" + "Examples: [('words', ['1926', '08', '17']), ('label', ['1'])]") + output = "" + for index, item in enumerate(line): + name, elements = item + if output: + output += " " + out_str = [] + out_str.append(str(len(elements))) + out_str.extend(elements) + output += " ".join(out_str) + return output + "\n" + + +class MultiSlotDataGenerator(DataGenerator): + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the MultiSlotDataFeed, + and updating proto_info information. + + The input line will be in this format: + >>> [(name, [feasign, ...]), ...] + >>> or ((name, [feasign, ...]), ...) + The output will be in this format: + >>> [ids_num id1 id2 ...] ... + The proto_info will be in this format: + >>> [(name, type), ...] + + For example, if the input is like this: + >>> [("words", [1926, 08, 17]), ("label", [1])] + >>> or (("words", [1926, 08, 17]), ("label", [1])) + the output will be: + >>> 3 1234 2345 3456 1 1 + the proto_info will be: + >>> [("words", "uint64"), ("label", "uint64")] + + Args: + line(str): the output of the process() function rewritten by user. + + Returns: + Return a string data that can be read directly by the MultiSlotDataFeed. + ''' + if sys.version > '3' and isinstance(line, zip): + line = list(line) + + if not isinstance(line, list) and not isinstance(line, tuple): + raise ValueError( + "the output of process() must be in list or tuple type" + "Example: [('words', [1926, 08, 17]), ('label', [1])]") + output = "" + + if self._proto_info is None: + self._proto_info = [] + for item in line: + name, elements = item + if not isinstance(name, str): + raise ValueError("name%s must be in str type" % type(name)) + if not isinstance(elements, list): + raise ValueError("elements%s must be in list type" % + type(elements)) + if not elements: + raise ValueError( + "the elements of each field can not be empty, you need padding it in process()." + ) + self._proto_info.append((name, "uint64")) + if output: + output += " " + output += str(len(elements)) + for elem in elements: + if isinstance(elem, float): + self._proto_info[-1] = (name, "float") + elif not isinstance(elem, int) and not isinstance( + elem, long): + raise ValueError( + "the type of element%s must be in int or float" % + type(elem)) + output += " " + str(elem) + else: + if len(line) != len(self._proto_info): + raise ValueError( + "the complete field set of two given line are inconsistent." + ) + for index, item in enumerate(line): + name, elements = item + if not isinstance(name, str): + raise ValueError("name%s must be in str type" % type(name)) + if not isinstance(elements, list): + raise ValueError("elements%s must be in list type" % + type(elements)) + if not elements: + raise ValueError( + "the elements of each field can not be empty, you need padding it in process()." + ) + if name != self._proto_info[index][0]: + raise ValueError( + "the field name of two given line are not match: require<%s>, get<%s>." + % (self._proto_info[index][0], name)) + if output: + output += " " + output += str(len(elements)) + for elem in elements: + if self._proto_info[index][1] != "float": + if isinstance(elem, float): + self._proto_info[index] = (name, "float") + elif not isinstance(elem, int) and not isinstance( + elem, long): + raise ValueError( + "the type of element%s must be in int or float" + % type(elem)) + output += " " + str(elem) + return output + "\n" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..55b944abccd51ca3427060ec610299f41e01e82c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/__init__.py @@ -0,0 +1,21 @@ +# 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 + +from .dataset import DatasetBase # noqa: F401 +from .dataset import InMemoryDataset # noqa: F401 +from .dataset import QueueDataset # noqa: F401 +from .dataset import FileInstantDataset # noqa: F401 +from .dataset import BoxPSDataset # noqa: F401 +from .index_dataset import TreeIndex # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..56bc6eb268a779204bccee94fec85ef1d87c54a2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/dataset.py @@ -0,0 +1,1621 @@ +# Copyright (c) 2018 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. +"""This is definition of dataset class, which is high performance IO.""" + +import paddle +from paddle.fluid.proto import data_feed_pb2 +from google.protobuf import text_format +import paddle.fluid.core as core + +__all__ = [] + + +class DatasetBase(object): + """ Base dataset class. """ + + def __init__(self): + """ Init. """ + # define class name here + # to decide whether we need create in memory instance + self.proto_desc = data_feed_pb2.DataFeedDesc() + self.proto_desc.pipe_command = "cat" + self.dataset = core.Dataset("MultiSlotDataset") + self.thread_num = 1 + self.filelist = [] + self.use_ps_gpu = False + self.psgpu = None + + def init(self, + batch_size=1, + thread_num=1, + use_var=[], + pipe_command="cat", + input_type=0, + fs_name="", + fs_ugi="", + download_cmd="cat"): + """ + should be called only once in user's python scripts to initialize setings of dataset instance. + Normally, it is called by InMemoryDataset or QueueDataset. + + Args: + batch_size(int): batch size. It will be effective during training. default is 1. + thread_num(int): thread num, it is the num of readers. default is 1. + use_var(list): list of variables. Variables which you will use. default is []. + pipe_command(str): pipe command of current dataset. A pipe command is a UNIX pipeline command that can be used only. default is "cat" + input_type(int): the input type of generated input. 0 is for one sample, 1 is for one batch. default is 0. + fs_name(str): fs name. default is "". + fs_ugi(str): fs ugi. default is "". + download_cmd(str): customized download command. default is "cat" + + + """ + self._set_batch_size(batch_size) + self._set_thread(thread_num) + self._set_use_var(use_var) + self._set_pipe_command(pipe_command) + self._set_input_type(input_type) + self._set_hdfs_config(fs_name, fs_ugi) + self._set_download_cmd(download_cmd) + + def _set_pipe_command(self, pipe_command): + """ + Set pipe command of current dataset + A pipe command is a UNIX pipeline command that can be used only + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.dataset.DatasetBase() + dataset._set_pipe_command("python my_script.py") + + Args: + pipe_command(str): pipe command + + """ + self.proto_desc.pipe_command = pipe_command + + def _set_batch_size(self, batch_size): + """ + Set batch size. Will be effective during training + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_batch_size(128) + + Args: + batch_size(int): batch size + + """ + self.proto_desc.batch_size = batch_size + + def _set_thread(self, thread_num): + """ + Set thread num, it is the num of readers. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_thread(12) + + Args: + thread_num(int): thread num + """ + self.dataset.set_thread_num(thread_num) + self.thread_num = thread_num + + def set_filelist(self, filelist): + """ + Set file list in current worker. The filelist is indicated by a list of file names (string). + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset.set_filelist(['a.txt', 'b.txt']) + + Args: + filelist(list[str]): list of file names of inputs. + """ + self.dataset.set_filelist(filelist) + self.filelist = filelist + + def _set_input_type(self, input_type): + self.proto_desc.input_type = input_type + + def _set_uid_slot(self, uid_slot): + """ + Set user slot name. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_uid_slot('6048') + + Args: + set_uid_slot(string): user slot name + """ + multi_slot = self.proto_desc.multi_slot_desc + multi_slot.uid_slot = uid_slot + + def _set_use_var(self, var_list): + """ + Set Variables which you will use. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_use_var([data, label]) + + Args: + var_list(list): variable list + """ + multi_slot = self.proto_desc.multi_slot_desc + for var in var_list: + slot_var = multi_slot.slots.add() + slot_var.is_used = True + slot_var.name = var.name + if var.lod_level == 0: + slot_var.is_dense = True + slot_var.shape.extend(var.shape) + if var.dtype == core.VarDesc.VarType.FP32: + slot_var.type = "float" + elif var.dtype == core.VarDesc.VarType.INT64: + slot_var.type = "uint64" + else: + raise ValueError( + "Currently, paddle.distributed.fleet.dataset only supports dtype=float32 and dtype=int64" + ) + + def _set_hdfs_config(self, fs_name, fs_ugi): + """ + Set hdfs config: fs name ad ugi + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_hdfs_config("my_fs_name", "my_fs_ugi") + + Args: + fs_name(str): fs name + fs_ugi(str): fs ugi + """ + self.dataset.set_hdfs_config(fs_name, fs_ugi) + + def _set_download_cmd(self, download_cmd): + """ + Set customized download cmd: download_cmd + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + dataset._set_download_cmd("./read_from_afs") + + Args: + download_cmd(str): customized download command + """ + self.dataset.set_download_cmd(download_cmd) + + def _prepare_to_run(self): + """ + Set data_feed_desc before load or shuffle, + user no need to call this function. + """ + if self.thread_num > len(self.filelist): + self.thread_num = len(self.filelist) + self.dataset.set_thread_num(self.thread_num) + self.dataset.set_data_feed_desc(self._desc()) + self.dataset.create_readers() + + def _set_use_ps_gpu(self, use_ps_gpu): + """ + set use_ps_gpu flag + + Args: + use_ps_gpu: bool + """ + self.use_ps_gpu = use_ps_gpu + # if not defined heterps with paddle, users will not use psgpu + if not core._is_compiled_with_heterps(): + self.use_ps_gpu = 0 + elif self.use_ps_gpu: + self.psgpu = core.PSGPU() + + def _finish_to_run(self): + self.dataset.destroy_readers() + + def _desc(self): + """ + Returns a protobuf message for this DataFeedDesc + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.DatasetBase() + print(dataset._desc()) + + Returns: + A string message + """ + return text_format.MessageToString(self.proto_desc) + + def _dynamic_adjust_before_train(self, thread_num): + pass + + def _dynamic_adjust_after_train(self): + pass + + def _check_use_var_with_data_generator(self, var_list, data_generator_class, + test_file): + """ + Var consistency insepection of use_var_list and data_generator data. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle + from dataset_generator import CTRDataset + dataset = paddle.distributed.fleet.DatasetBase() + generator_class = CTRDataset() + dataset._check_use_var_with_data_generator([data, label], generator_class, "data/part-00000") + + Args: + var_list(list): variable list + data_generator_class(class): data_generator class + test_file(str): local test file path + """ + + f = open(test_file, "r") + var_len = len(var_list) + + while True: + line = f.readline() + if line: + line_iter = data_generator_class.generate_sample(line) + for user_parsed_line in line_iter(): + data_gen_len = len(user_parsed_line) + if var_len != data_gen_len: + raise ValueError( + "var length mismatch error: var_list = %s vs data_generator = %s" + % (var_len, data_gen_len)) + + for i, ele in enumerate(user_parsed_line): + if len(ele[1]) == 0: + raise ValueError( + "var length error: var %s's length in data_generator is 0" + % ele[0]) + + if var_list[ + i].dtype == core.VarDesc.VarType.FP32 and not all( + isinstance(ele, float) for ele in ele[1]): + raise TypeError( + "var dtype mismatch error: var name = %s, var type in var_list = %s, while var in data_generator contains non-float value, which is %s \n" + "Please check if order of var_list and data_generator are aligned. \n" + "Please check if var's type in data_generator is correct." + % (ele[0], "float", ele[1])) + + if (var_list[i].dtype == core.VarDesc.VarType.INT64 + or var_list[i].dtype + == core.VarDesc.VarType.INT32) and not all( + isinstance(ele, int) for ele in ele[1]): + raise TypeError( + "var dtype mismatch error: var name = %s, var type in var_list = %s, while var in data_generator contains non-int value, which is %s \n" + "Please check if order of var_list and data_generator are aligned. \n" + "Please check if var's type in data_generator is correct." + % (ele[0], "int", ele[1])) + + else: + break + + f.close() + + +class InMemoryDataset(DatasetBase): + """ + :api_attr: Static Graph + + It will load data into memory and shuffle data before training. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + + """ + + def __init__(self): + """ Init. """ + super(InMemoryDataset, self).__init__() + self.proto_desc.name = "MultiSlotInMemoryDataFeed" + self.fleet_send_batch_size = None + self.is_user_set_queue_num = False + self.queue_num = None + self.parse_ins_id = False + self.parse_content = False + self.parse_logkey = False + self.merge_by_sid = True + self.enable_pv_merge = False + self.merge_by_lineid = False + self.fleet_send_sleep_seconds = None + + def _init_distributed_settings(self, **kwargs): + """ + :api_attr: Static Graph + + should be called only once in user's python scripts to initialize distributed-related setings of dataset instance + Args: + kwargs: Keyword arguments. Currently, we support following keys in **kwargs: + + merge_size(int): ins size to merge, if merge_size > 0, set merge by line id, + instances of same line id will be merged after shuffle, + you should parse line id in data generator. default is -1. + parse_ins_id(bool): Set if Dataset need to parse ins_id. default is False. + parse_content(bool): Set if Dataset need to parse content. default is False. + fleet_send_batch_size(int): Set fleet send batch size in one rpc, default is 1024 + fleet_send_sleep_seconds(int): Set fleet send sleep time, default is 0 + fea_eval(bool): Set if Dataset need to do feature importance evaluation using slots shuffle. + default is False. + candidate_size(int): if fea_eval is set True, set the candidate size used in slots shuffle. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=[]) + dataset._init_distributed_settings( + parse_ins_id=True, + parse_content=True, + fea_eval=True, + candidate_size=10000) + + """ + merge_size = kwargs.get("merge_size", -1) + if merge_size > 0: + self._set_merge_by_lineid(merge_size) + + parse_ins_id = kwargs.get("parse_ins_id", False) + self._set_parse_ins_id(parse_ins_id) + + parse_content = kwargs.get("parse_content", False) + self._set_parse_content(parse_content) + + fleet_send_batch_size = kwargs.get("fleet_send_batch_size", None) + if fleet_send_batch_size: + self._set_fleet_send_batch_size(fleet_send_batch_size) + + fleet_send_sleep_seconds = kwargs.get("fleet_send_sleep_seconds", None) + if fleet_send_sleep_seconds: + self._set_fleet_send_sleep_seconds(fleet_send_sleep_seconds) + + fea_eval = kwargs.get("fea_eval", False) + if fea_eval: + candidate_size = kwargs.get("candidate_size", 10000) + self._set_fea_eval(candidate_size, True) + + def update_settings(self, **kwargs): + """ + :api_attr: Static Graph + + should be called in user's python scripts to update setings of dataset instance. + + Args: + kwargs: Keyword arguments. Currently, we support following keys in **kwargs, + including single node settings and advanced distributed related settings: + batch_size(int): batch size. It will be effective during training. default is 1. + thread_num(int): thread num, it is the num of readers. default is 1. + use_var(list): list of variables. Variables which you will use. default is []. + input_type(int): the input type of generated input. 0 is for one sample, 1 is for one batch. default is 0. + fs_name(str): fs name. default is "". + fs_ugi(str): fs ugi. default is "". + pipe_command(str): pipe command of current dataset. A pipe command is a UNIX pipeline command that can be used only. default is "cat" + download_cmd(str): customized download command. default is "cat" + data_feed_type(str): data feed type used in c++ code. default is "MultiSlotInMemoryDataFeed". + queue_num(int): Dataset output queue num, training threads get data from queues. default is-1, which is set same as thread number in c++. + + merge_size(int): ins size to merge, if merge_size > 0, set merge by line id, + instances of same line id will be merged after shuffle, + you should parse line id in data generator. default is -1. + parse_ins_id(bool): Set if Dataset need to parse ins_id. default is False. + parse_content(bool): Set if Dataset need to parse content. default is False. + fleet_send_batch_size(int): Set fleet send batch size in one rpc, default is 1024 + fleet_send_sleep_seconds(int): Set fleet send sleep time, default is 0 + fea_eval(bool): Set if Dataset need to do feature importance evaluation using slots shuffle. + default is False. + candidate_size(int): if fea_eval is set True, set the candidate size used in slots shuffle. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=[]) + dataset._init_distributed_settings( + parse_ins_id=True, + parse_content=True, + fea_eval=True, + candidate_size=10000) + dataset.update_settings(batch_size=2) + + """ + for key in kwargs: + if key == "pipe_command": + self._set_pipe_command(kwargs[key]) + elif key == "batch_size": + self._set_batch_size(kwargs[key]) + elif key == "thread_num": + self._set_thread(kwargs[key]) + elif key == "use_var": + self._set_use_var(kwargs[key]) + elif key == "input_type": + self._set_input_type(kwargs[key]) + elif key == "fs_name" and "fs_ugi" in kwargs: + self._set_hdfs_config(kwargs[key], kwargs["fs_ugi"]) + elif key == "download_cmd": + self._set_download_cmd(kwargs[key]) + elif key == "merge_size" and kwargs.get("merge_size", -1) > 0: + self._set_merge_by_lineid(kwargs[key]) + elif key == "parse_ins_id": + self._set_parse_ins_id(kwargs[key]) + elif key == "parse_content": + self._set_parse_content(kwargs[key]) + elif key == "fleet_send_batch_size": + self._set_fleet_send_batch_size(kwargs[key]) + elif key == "fleet_send_sleep_seconds": + self._set_fleet_send_sleep_seconds(kwargs[key]) + elif key == "fea_eval" and kwargs[key] == True: + candidate_size = kwargs.get("candidate_size", 10000) + self._set_fea_eval(candidate_size, True) + + def init(self, **kwargs): + """ + :api_attr: Static Graph + + should be called only once in user's python scripts to initialize setings of dataset instance + + Args: + kwargs: Keyword arguments. Currently, we support following keys in **kwargs: + + batch_size(int): batch size. It will be effective during training. default is 1. + thread_num(int): thread num, it is the num of readers. default is 1. + use_var(list): list of variables. Variables which you will use. default is []. + input_type(int): the input type of generated input. 0 is for one sample, 1 is for one batch. default is 0. + fs_name(str): fs name. default is "". + fs_ugi(str): fs ugi. default is "". + pipe_command(str): pipe command of current dataset. A pipe command is a UNIX pipeline command that can be used only. default is "cat" + download_cmd(str): customized download command. default is "cat" + data_feed_type(str): data feed type used in c++ code. default is "MultiSlotInMemoryDataFeed". + queue_num(int): Dataset output queue num, training threads get data from queues. default is -1, which is set same as thread number in c++. + + Examples: + .. code-block:: python + + import paddle + import os + paddle.enable_static() + + with open("test_queue_dataset_run_a.txt", "w") as f: + data = "2 1 2 2 5 4 2 2 7 2 1 3" + f.write(data) + with open("test_queue_dataset_run_b.txt", "w") as f: + data = "2 1 2 2 5 4 2 2 7 2 1 3" + f.write(data) + + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + + dataset = paddle.distributed.InMemoryDataset() + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + dataset.set_filelist( + ["test_queue_dataset_run_a.txt", "test_queue_dataset_run_b.txt"]) + dataset.load_into_memory() + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + startup_program = paddle.static.Program() + main_program = paddle.static.Program() + exe.run(startup_program) + + exe.train_from_dataset(main_program, dataset) + + os.remove("./test_queue_dataset_run_a.txt") + os.remove("./test_queue_dataset_run_b.txt") + + """ + batch_size = kwargs.get("batch_size", 1) + thread_num = kwargs.get("thread_num", 1) + use_var = kwargs.get("use_var", []) + input_type = kwargs.get("input_type", 0) + fs_name = kwargs.get("fs_name", "") + fs_ugi = kwargs.get("fs_ugi", "") + pipe_command = kwargs.get("pipe_command", "cat") + download_cmd = kwargs.get("download_cmd", "cat") + + if self.use_ps_gpu: + data_feed_type = "SlotRecordInMemoryDataFeed" + else: + data_feed_type = "MultiSlotInMemoryDataFeed" + self._set_feed_type(data_feed_type) + + super(InMemoryDataset, self).init(batch_size=batch_size, + thread_num=thread_num, + use_var=use_var, + pipe_command=pipe_command, + input_type=input_type, + fs_name=fs_name, + fs_ugi=fs_ugi, + download_cmd=download_cmd) + + if kwargs.get("queue_num", -1) > 0: + queue_num = kwargs.get("queue_num", -1) + self._set_queue_num(queue_num) + + def _set_feed_type(self, data_feed_type): + """ + Set data_feed_desc + """ + self.proto_desc.name = data_feed_type + if (self.proto_desc.name == "SlotRecordInMemoryDataFeed"): + self.dataset = core.Dataset("SlotRecordDataset") + + def _prepare_to_run(self): + """ + Set data_feed_desc before load or shuffle, + user no need to call this function. + """ + if self.thread_num <= 0: + self.thread_num = 1 + self.dataset.set_thread_num(self.thread_num) + if self.queue_num is None: + self.queue_num = self.thread_num + self.dataset.set_queue_num(self.queue_num) + self.dataset.set_parse_ins_id(self.parse_ins_id) + self.dataset.set_parse_content(self.parse_content) + self.dataset.set_parse_logkey(self.parse_logkey) + self.dataset.set_merge_by_sid(self.merge_by_sid) + self.dataset.set_enable_pv_merge(self.enable_pv_merge) + self.dataset.set_data_feed_desc(self._desc()) + self.dataset.create_channel() + self.dataset.create_readers() + + def _dynamic_adjust_before_train(self, thread_num): + if not self.is_user_set_queue_num: + if self.use_ps_gpu: + self.dataset.dynamic_adjust_channel_num(thread_num, True) + else: + self.dataset.dynamic_adjust_channel_num(thread_num, False) + self.dataset.dynamic_adjust_readers_num(thread_num) + + def _dynamic_adjust_after_train(self): + if not self.is_user_set_queue_num: + if self.use_ps_gpu: + self.dataset.dynamic_adjust_channel_num(self.thread_num, True) + else: + self.dataset.dynamic_adjust_channel_num(self.thread_num, False) + self.dataset.dynamic_adjust_readers_num(self.thread_num) + + def _set_queue_num(self, queue_num): + """ + Set Dataset output queue num, training threads get data from queues + + Args: + queue_num(int): dataset output queue num + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_queue_num(12) + + """ + self.is_user_set_queue_num = True + self.queue_num = queue_num + + def _set_parse_ins_id(self, parse_ins_id): + """ + Set if Dataset need to parse insid + + Args: + parse_ins_id(bool): if parse ins_id or not + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_parse_ins_id(True) + + """ + self.parse_ins_id = parse_ins_id + + def _set_parse_content(self, parse_content): + """ + Set if Dataset need to parse content + + Args: + parse_content(bool): if parse content or not + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_parse_content(True) + + """ + self.parse_content = parse_content + + def _set_fleet_send_batch_size(self, fleet_send_batch_size=1024): + """ + Set fleet send batch size, default is 1024 + + Args: + fleet_send_batch_size(int): fleet send batch size + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_fleet_send_batch_size(800) + + """ + self.fleet_send_batch_size = fleet_send_batch_size + + def _set_fleet_send_sleep_seconds(self, fleet_send_sleep_seconds=0): + """ + Set fleet send sleep time, default is 0 + + Args: + fleet_send_sleep_seconds(int): fleet send sleep time + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_fleet_send_sleep_seconds(2) + + """ + self.fleet_send_sleep_seconds = fleet_send_sleep_seconds + + def _set_merge_by_lineid(self, merge_size=2): + """ + Set merge by line id, instances of same line id will be merged after + shuffle, you should parse line id in data generator. + + Args: + merge_size(int): ins size to merge. default is 2. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_merge_by_lineid() + + """ + self.dataset.set_merge_by_lineid(merge_size) + self.merge_by_lineid = True + self.parse_ins_id = True + + def _set_shuffle_by_uid(self, enable_shuffle_uid): + """ + Set if Dataset need to shuffle by uid. + + Args: + set_shuffle_by_uid(bool): if shuffle according to uid or not + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_shuffle_by_uid(True) + """ + self.dataset.set_shuffle_by_uid(enable_shuffle_uid) + + def _set_generate_unique_feasigns(self, generate_uni_feasigns, shard_num): + self.dataset.set_generate_unique_feasigns(generate_uni_feasigns) + self.gen_uni_feasigns = generate_uni_feasigns + self.local_shard_num = shard_num + + def _generate_local_tables_unlock(self, table_id, fea_dim, read_thread_num, + consume_thread_num, shard_num): + self.dataset.generate_local_tables_unlock(table_id, fea_dim, + read_thread_num, + consume_thread_num, shard_num) + + def set_date(self, date): + """ + :api_attr: Static Graph + + Set training date for pull sparse parameters, saving and loading model. Only used in psgpu + + Args: + date(str): training date(format : YYMMDD). eg.20211111 + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + dataset.set_date("20211111") + """ + year = int(date[:4]) + month = int(date[4:6]) + day = int(date[6:]) + if self.use_ps_gpu and core._is_compiled_with_heterps(): + self.psgpu.set_date(year, month, day) + + def tdm_sample(self, tree_name, tree_path, tdm_layer_counts, + start_sample_layer, with_hierachy, seed, id_slot): + self.dataset.tdm_sample(tree_name, tree_path, tdm_layer_counts, + start_sample_layer, with_hierachy, seed, + id_slot) + + def load_into_memory(self, is_shuffle=False): + """ + :api_attr: Static Graph + + Load data into memory + + Args: + is_shuffle(bool): whether to use local shuffle, default is False + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + """ + self._prepare_to_run() + if not self.use_ps_gpu: + self.dataset.load_into_memory() + elif core._is_compiled_with_heterps(): + self.psgpu.set_dataset(self.dataset) + self.psgpu.load_into_memory(is_shuffle) + + def preload_into_memory(self, thread_num=None): + """ + :api_attr: Static Graph + + Load data into memory in async mode + + Args: + thread_num(int): preload thread num + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self._prepare_to_run() + if thread_num is None: + thread_num = self.thread_num + self.dataset.set_preload_thread_num(thread_num) + self.dataset.create_preload_readers() + self.dataset.preload_into_memory() + + def wait_preload_done(self): + """ + :api_attr: Static Graph + + Wait preload_into_memory done + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self.dataset.wait_preload_done() + self.dataset.destroy_preload_readers() + + def local_shuffle(self): + """ + :api_attr: Static Graph + + Local shuffle + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.local_shuffle() + """ + self.dataset.local_shuffle() + + def global_shuffle(self, fleet=None, thread_num=12): + """ + :api_attr: Static Graph + + Global shuffle. + Global shuffle can be used only in distributed mode. i.e. multiple + processes on single machine or multiple machines training together. + If you run in distributed mode, you should pass fleet instead of None. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle() + + Args: + fleet(Fleet): fleet singleton. Default None. + thread_num(int): shuffle thread num. Default is 12. + + """ + trainer_num = 1 + if fleet is not None: + fleet._role_maker.barrier_worker() + trainer_num = fleet.worker_num() + if self.fleet_send_batch_size is None: + self.fleet_send_batch_size = 1024 + if self.fleet_send_sleep_seconds is None: + self.fleet_send_sleep_seconds = 0 + self.dataset.register_client2client_msg_handler() + self.dataset.set_trainer_num(trainer_num) + self.dataset.set_fleet_send_batch_size(self.fleet_send_batch_size) + self.dataset.set_fleet_send_sleep_seconds(self.fleet_send_sleep_seconds) + if fleet is not None: + fleet._role_maker.barrier_worker() + self.dataset.global_shuffle(thread_num) + if fleet is not None: + fleet._role_maker.barrier_worker() + if self.merge_by_lineid: + self.dataset.merge_by_lineid() + if fleet is not None: + fleet._role_maker.barrier_worker() + + def release_memory(self): + """ + :api_attr: Static Graph + + Release InMemoryDataset memory data, when data will not be used again. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle() + exe = paddle.static.Executor(paddle.CPUPlace()) + startup_program = paddle.static.Program() + main_program = paddle.static.Program() + exe.run(startup_program) + exe.train_from_dataset(main_program, dataset) + dataset.release_memory() + + """ + self.dataset.release_memory() + + def get_memory_data_size(self, fleet=None): + """ + :api_attr: Static Graph + + Get memory data size, user can call this function to know the num + of ins in all workers after load into memory. + + Note: + This function may cause bad performance, because it has barrier + + Args: + fleet(Fleet): Fleet Object. + + Returns: + The size of memory data. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + print dataset.get_memory_data_size() + + """ + import numpy as np + local_data_size = self.dataset.get_memory_data_size() + local_data_size = np.array([local_data_size]) + if fleet is not None: + global_data_size = local_data_size * 0 + fleet._role_maker.all_reduce_worker(local_data_size, + global_data_size) + return global_data_size[0] + return local_data_size[0] + + def get_shuffle_data_size(self, fleet=None): + """ + :api_attr: Static Graph + + Get shuffle data size, user can call this function to know the num + of ins in all workers after local/global shuffle. + + Note: + This function may cause bad performance to local shuffle, + because it has barrier. It does not affect global shuffle. + + Args: + fleet(Fleet): Fleet Object. + + Returns: + The size of shuffle data. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + dataset = paddle.distributed.InMemoryDataset() + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle() + print dataset.get_shuffle_data_size() + + """ + import numpy as np + local_data_size = self.dataset.get_shuffle_data_size() + local_data_size = np.array([local_data_size]) + if fleet is not None: + global_data_size = local_data_size * 0 + fleet._role_maker.all_reduce_worker(local_data_size, + global_data_size) + return global_data_size[0] + return local_data_size[0] + + def _set_fea_eval(self, record_candidate_size, fea_eval=True): + """ + set fea eval mode for slots shuffle to debug the importance level of + slots(features), fea_eval need to be set True for slots shuffle. + + Args: + record_candidate_size(int): size of instances candidate to shuffle + one slot + fea_eval(bool): whether enable fea eval mode to enable slots shuffle. + default is True. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + dataset = paddle.distributed.InMemoryDataset() + dataset._set_fea_eval(1000000, True) + + """ + if fea_eval: + self.dataset.set_fea_eval(fea_eval, record_candidate_size) + self.fea_eval = fea_eval + + def slots_shuffle(self, slots): + """ + Slots Shuffle + Slots Shuffle is a shuffle method in slots level, which is usually used + in sparse feature with large scale of instances. To compare the metric, i.e. + auc while doing slots shuffle on one or several slots with baseline to + evaluate the importance level of slots(features). + + Args: + slots(list[string]): the set of slots(string) to do slots shuffle. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + dataset = paddle.distributed.InMemoryDataset() + dataset._init_distributed_settings(fea_eval=True) + slots = ["slot1", "slot2", "slot3", "slot4"] + slots_vars = [] + for slot in slots: + var = paddle.static.data( + name=slot, shape=[None, 1], dtype="int64", lod_level=1) + slots_vars.append(var) + dataset.init( + batch_size=1, + thread_num=2, + input_type=1, + pipe_command="cat", + use_var=slots_vars) + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.slots_shuffle(['slot1']) + """ + if self.fea_eval: + slots_set = set(slots) + self.dataset.slots_shuffle(slots_set) + + +class QueueDataset(DatasetBase): + """ + :api_attr: Static Graph + + QueueDataset, it will process data streamly. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.QueueDataset() + + """ + + def __init__(self): + """ + Initialize QueueDataset + """ + super(QueueDataset, self).__init__() + self.proto_desc.name = "MultiSlotDataFeed" + + def init(self, **kwargs): + """ + :api_attr: Static Graph + + should be called only once in user's python scripts to initialize setings of dataset instance + """ + super(QueueDataset, self).init(**kwargs) + + def _prepare_to_run(self): + """ + Set data_feed_desc/thread num/filelist before run, + user no need to call this function. + """ + if self.thread_num > len(self.filelist): + self.thread_num = len(self.filelist) + if self.thread_num == 0: + self.thread_num = 1 + self.dataset.set_thread_num(self.thread_num) + self.dataset.set_filelist(self.filelist) + self.dataset.set_data_feed_desc(self._desc()) + self.dataset.create_readers() + + +class FileInstantDataset(DatasetBase): + """ + FileInstantDataset, it will process data streamly. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.FileInstantDataset() + """ + + def __init__(self): + """ + Initialize FileInstantDataset + """ + super(FileInstantDataset, self).__init__() + self.proto_desc.name = "MultiSlotFileInstantDataFeed" + + def init(self, **kwargs): + """ + should be called only once in user's python scripts to initialize setings of dataset instance + """ + super(FileInstantDataset, self).init(**kwargs) + + +class BoxPSDataset(InMemoryDataset): + """ + BoxPSDataset: derived from InMemoryDataset. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + """ + + def __init__(self): + """ + Initialize BoxPSDataset + """ + super(BoxPSDataset, self).__init__() + self.boxps = core.BoxPS(self.dataset) + self.proto_desc.name = "PaddleBoxDataFeed" + + def init(self, **kwargs): + """ + should be called only once in user's python scripts to initialize setings of dataset instance + """ + super(BoxPSDataset, self).init(**kwargs) + + rank_offset = kwargs.get("rank_offset", "") + self._set_rank_offset(rank_offset) + pv_batch_size = kwargs.get("pv_batch_size", 1) + self._set_pv_batch_size(pv_batch_size) + parse_logkey = kwargs.get("parse_logkey", False) + self._set_parse_logkey(parse_logkey) + merge_by_sid = kwargs.get("merge_by_sid", False) + self._set_merge_by_sid(merge_by_sid) + enable_pv_merge = kwargs.get("enable_pv_merge", False) + self._set_enable_pv_merge(enable_pv_merge) + + def _set_rank_offset(self, rank_offset): + """ + Set rank_offset for merge_pv. It set the message of Pv. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset._set_rank_offset("rank_offset") + + Args: + rank_offset(str): rank_offset's name + + """ + self.proto_desc.rank_offset = rank_offset + + def _set_pv_batch_size(self, pv_batch_size): + """ + Set pv batch size. It will be effective during enable_pv_merge + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset._set_pv_batch_size(128) + Args: + pv_batch_size(int): pv batch size + + """ + self.proto_desc.pv_batch_size = pv_batch_size + + def _set_parse_logkey(self, parse_logkey): + """ + Set if Dataset need to parse logkey + + Args: + parse_content(bool): if parse logkey or not + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset._set_parse_logkey(True) + + """ + self.parse_logkey = parse_logkey + + def _set_merge_by_sid(self, merge_by_sid): + """ + Set if Dataset need to merge sid. If not, one ins means one Pv. + + Args: + merge_by_sid(bool): if merge sid or not + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset._set_merge_by_sid(True) + + """ + self.merge_by_sid = merge_by_sid + + def _set_enable_pv_merge(self, enable_pv_merge): + """ + Set if Dataset need to merge pv. + + Args: + enable_pv_merge(bool): if enable_pv_merge or not + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset._set_enable_pv_merge(True) + + """ + self.enable_pv_merge = enable_pv_merge + + def set_date(self, date): + """ + Workaround for date + """ + year = int(date[:4]) + month = int(date[4:6]) + day = int(date[6:]) + self.boxps.set_date(year, month, day) + + def begin_pass(self): + """ + Begin Pass + Notify BoxPS to load sparse parameters of next pass to GPU Memory + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset.begin_pass() + """ + self.boxps.begin_pass() + + def end_pass(self, need_save_delta): + """ + End Pass + Notify BoxPS that current pass ended + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset.end_pass(True) + """ + self.boxps.end_pass(need_save_delta) + + def wait_preload_done(self): + """ + Wait async preload done + Wait Until Feed Pass Done + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self.boxps.wait_feed_pass_done() + + def load_into_memory(self): + """ + Load next pass into memory and notify boxps to fetch its emb from SSD + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + """ + self._prepare_to_run() + self.boxps.load_into_memory() + + def preload_into_memory(self): + """ + Begin async preload next pass while current pass may be training + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + """ + self._prepare_to_run() + self.boxps.preload_into_memory() + + def _dynamic_adjust_before_train(self, thread_num): + if not self.is_user_set_queue_num: + self.dataset.dynamic_adjust_channel_num(thread_num, True) + self.dataset.dynamic_adjust_readers_num(thread_num) + + def _dynamic_adjust_after_train(self): + pass + + def slots_shuffle(self, slots): + """ + Slots Shuffle + Slots Shuffle is a shuffle method in slots level, which is usually used + in sparse feature with large scale of instances. To compare the metric, i.e. + auc while doing slots shuffle on one or several slots with baseline to + evaluate the importance level of slots(features). + + Args: + slots(list[string]): the set of slots(string) to do slots shuffle. + + Examples: + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + dataset.set_merge_by_lineid() + #suppose there is a slot 0 + dataset.slots_shuffle(['0']) + """ + slots_set = set(slots) + self.boxps.slots_shuffle(slots_set) + + def set_current_phase(self, current_phase): + """ + Set current phase in train. It is useful for untest. + current_phase : 1 for join, 0 for update. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.set_current_phase(1) + + """ + self.dataset.set_current_phase(current_phase) + + def get_pv_data_size(self): + """ + Get memory data size of Pv, user can call this function to know the pv num + of ins in all workers after load into memory. + + Note: + This function may cause bad performance, because it has barrier + + Returns: + The size of memory pv data. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + print dataset.get_pv_data_size() + + """ + return self.dataset.get_pv_data_size() + + def preprocess_instance(self): + """ + Merge pv instance and convey it from input_channel to input_pv_channel. + It will be effective when enable_pv_merge_ is True. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.preprocess_instance() + + """ + self.dataset.preprocess_instance() + + def postprocess_instance(self): + """ + Divide pv instance and convey it to input_channel. + + Examples: + .. code-block:: python + + import paddle + dataset = paddle.distributed.fleet.BoxPSDataset() + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.preprocess_instance() + exe.train_from_dataset(dataset) + dataset.postprocess_instance() + + """ + self.dataset.postprocess_instance() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/index_dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/index_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8b5a9c5a45bf6ce218960f58e10489f8e703e9ca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/dataset/index_dataset.py @@ -0,0 +1,92 @@ +# Copyright (c) 2021 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. +from paddle.fluid import core + +__all__ = [] + + +class Index(object): + + def __init__(self, name): + self._name = name + + +class TreeIndex(Index): + + def __init__(self, name, path): + super(TreeIndex, self).__init__(name) + self._wrapper = core.IndexWrapper() + self._wrapper.insert_tree_index(name, path) + self._tree = self._wrapper.get_tree_index(name) + self._height = self._tree.height() + self._branch = self._tree.branch() + self._total_node_nums = self._tree.total_node_nums() + self._emb_size = self._tree.emb_size() + self._layerwise_sampler = None + + def height(self): + return self._height + + def branch(self): + return self._branch + + def total_node_nums(self): + return self._total_node_nums + + def emb_size(self): + return self._emb_size + + def get_all_leafs(self): + return self._tree.get_all_leafs() + + def get_nodes(self, codes): + return self._tree.get_nodes(codes) + + def get_layer_codes(self, level): + return self._tree.get_layer_codes(level) + + def get_travel_codes(self, id, start_level=0): + return self._tree.get_travel_codes(id, start_level) + + def get_ancestor_codes(self, ids, level): + return self._tree.get_ancestor_codes(ids, level) + + def get_children_codes(self, ancestor, level): + return self._tree.get_children_codes(ancestor, level) + + def get_travel_path(self, child, ancestor): + res = [] + while (child > ancestor): + res.append(child) + child = int((child - 1) / self._branch) + return res + + def get_pi_relation(self, ids, level): + codes = self.get_ancestor_codes(ids, level) + return dict(zip(ids, codes)) + + def init_layerwise_sampler(self, + layer_sample_counts, + start_sample_layer=1, + seed=0): + assert self._layerwise_sampler is None + self._layerwise_sampler = core.IndexSampler("by_layerwise", self._name) + self._layerwise_sampler.init_layerwise_conf(layer_sample_counts, + start_sample_layer, seed) + + def layerwise_sample(self, user_input, index_input, with_hierarchy=False): + if self._layerwise_sampler is None: + raise ValueError("please init layerwise_sampler first.") + return self._layerwise_sampler.sample(user_input, index_input, + with_hierarchy) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b80a66c6f01d06a467999112e43a6be5c2c8ec51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/__init__.py @@ -0,0 +1,87 @@ +# Copyright (c) 2021 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. + +import signal +import os, sys + +from .manager import ElasticManager +from .manager import ElasticStatus +from .manager import ELASTIC_EXIT_CODE +from .manager import ElasticLevel +from .collective import CollectiveLauncher + +from paddle.distributed.fleet.launch_utils import DistributeMode + + +def enable_elastic(args, distribute_mode): + #elastic_level = os.getenv('PADDLE_ELASTIC_FAULT_TOLERANC_LEVEL') + #if not elastic_level and (elastic_level != ElasticLevel.FAULT_TOLERANCE and + # elastic_level != ElasticLevel.ELASTIC): + # return False + + #if distribute_mode != DistributeMode.COLLECTIVE: + # return False + + if not args.elastic_server and not os.getenv('PADDLE_ELASTIC_SERVER'): + return False + + if not args.job_id and not os.getenv('PADDLE_ELASTIC_JOB_ID'): + return False + + if not args.np and not os.getenv('PADDLE_ELASTIC_NP'): + return False + + return True + + +def launch_elastic(args, distribute_mode): + + server = args.elastic_server or os.getenv('PADDLE_ELASTIC_SERVER') + srv, port = server.split(':') + import etcd3 + etcd_client = etcd3.client(host=srv, port=port) + elastic = ElasticManager(args, etcd_client) + + signal.signal(signal.SIGTERM, elastic.signal_handler) + signal.signal(signal.SIGABRT, elastic.signal_handler) + signal.signal(signal.SIGINT, elastic.signal_handler) + + while True: + + # wait for all nodes ready to run + elastic.wait() + + # execute pre hook action, eg: run shell + elastic.pre_hook() + + # run self with specified launcher + elastic.run(CollectiveLauncher) + + # keep wathing the health status of self and being notified for other's failure + ret = elastic.watch() + if ret == ElasticStatus.COMPLETED: + break + if ret == ElasticStatus.HOLD: + continue + if ret == ElasticStatus.EXIT: + break + if ret == ElasticStatus.ERROR: + sys.exit(3) + if ret == ElasticStatus.RESTART: + sys.exit(ELASTIC_EXIT_CODE) + + if int(elastic.sigint) > 0: + sys.exit(128 + int(elastic.sigint)) + else: + sys.exit(0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/collective.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..f27987571d8d2491f9d9df5efe46129f3df98488 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/collective.py @@ -0,0 +1,63 @@ +# Copyright (c) 2021 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. + +import tempfile +from paddle.distributed.fleet import launch_utils +from paddle.distributed.fleet import cloud_utils +from paddle.distributed.fleet import ascend_utils + +from paddle.distributed.fleet.launch_utils import * + +from paddle.distributed.fleet.elastic.manager import LauncherInterface + + +class CollectiveLauncher(LauncherInterface): + + def __init__(self, args): + self.args = args + self.procs = [] + + def launch(self): + logger.info("collective lauchner launch ...") + args = self.args + self.tmp_dir = tempfile.mkdtemp() + cluster, pod = paddle.distributed.fleet.launch.get_cluster_info(args) + global_envs = paddle.distributed.fleet.launch.get_global_envs( + args, self.tmp_dir) + + self.procs = start_local_trainers( + cluster, + pod, + training_script=args.training_script, + training_script_args=args.training_script_args, + log_dir=args.log_dir, + envs=global_envs) + + for idx, proc in enumerate(self.procs): + logger.info("launch proc_id:{} idx:{}".format(proc.proc.pid, idx)) + + def stop(self): + logger.info("collective lauchner stop ...") + if not self._terminate_procs(): + logger.error("kill process failed") + if os.path.exists(self.tmp_dir): + shutil.rmtree(self.tmp_dir) + + def watch(self): + logger.debug("collective lauchner watch ...") + for p in self.procs: + if p.log_fn and p.local_rank == 0: + pull_worker_log(p) + ret = self._check_procs() + return ret diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/manager.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..451ed76741cb9374e67c315e4863304b860bcc4a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/elastic/manager.py @@ -0,0 +1,614 @@ +# Copyright (c) 2021 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. + +import time +import socket +import os +import six +import copy +import logging +import signal +import random +import threading +import traceback +import subprocess +from paddle.distributed.fleet import cloud_utils +from paddle.distributed.fleet import launch_utils + +from paddle.distributed.utils.log_utils import get_logger + +logger = get_logger("INFO", "ELASTIC") + +ELASTIC_EXIT_CODE = 101 +ELASTIC_AUTO_PARALLEL_EXIT_CODE = 102 + +# wait for timeout, unit: seconds +ELASTIC_TIMEOUT = 2 * 60 + +# keepalived ttl, unit: seconds +ELASTIC_TTL = 60 + + +# 1: Fault tolerance, 2: Elastic +class ElasticLevel: + FAULT_TOLERANCE = 1 + ELASTIC = 2 + + +class ElasticStatus: + COMPLETED = "completed" + ERROR = "error" + HOLD = "hold" + RESTART = "restart" + EXIT = "exit" + + +class LauncherInterface(object): + + def __init__(self, args): + self.args = args + self.procs = [] + + def _terminate_procs(self): + # try to terminate process by group, this happend in multiprocess senario in user process + if os.name != 'nt': + for p in self.procs: + if p.proc.poll() is None: + os.killpg(os.getpgid(p.proc.pid), signal.SIGTERM) + if p.log_fn: + p.log_fn.close() + logger.info("terminate process group gid:{}".format( + p.proc.pid)) + + time.sleep(1) + for p in self.procs: + if p.proc.poll() is None: + p.proc.terminate() + if p.log_fn: + p.log_fn.close() + logger.info("terminate process id:{}".format(p.proc.pid)) + + for step in range(0, 50): + alive = False + for p in self.procs: + if p.proc.poll() is None: # not termniate + os.kill(p.proc.pid, signal.SIGKILL) + alive = True + + if not alive: + logger.info("terminated all the procs") + return True + + time.sleep(1) + return False + + def _check_procs(self): + alive = False + result = None + for p in self.procs: + ret = p.proc.poll() + if ret is None: + alive = True + elif ret != 0: + if ret == ELASTIC_AUTO_PARALLEL_EXIT_CODE: + logger.info("return form elastic auto parallel re-launch") + return ret + logger.error("ABORT!!! ABORT!!! ABORT!!!") + logger.error( + "ERROR rank {} error with exit code {}, check log for detail." + .format(p.rank, ret)) + result = ret + if not alive and result is None: + return 0 + else: + return result + + def launch(self): + raise NotImplementedError + + def stop(self): + raise NotImplementedError + + def watch(self): + raise NotImplementedError + + +class ElasticManager(object): + + def __init__(self, args, etcd_client): + + self.args = args + server = args.elastic_server or os.getenv('PADDLE_ELASTIC_SERVER') + name = args.job_id or os.getenv('PADDLE_ELASTIC_JOB_ID') + self.min_np, self.max_np = self._parse_np(args.np) + host = args.host or os.getenv('POD_IP') + scale = args.scale or int(os.getenv('PADDLE_ELASTIC_SCALE', 0)) + force = args.force or os.getenv('PADDLE_ELASTIC_FORCE') + + self.host = host if host else self._get_host() + + (self.device_mode, + self.devices_per_proc) = launch_utils.get_device_proc_info(args) + + self.elastic_timeout = int( + os.getenv('PADDLE_ELASTIC_TIMEOUT', ELASTIC_TIMEOUT)) + elastic_ttl = int(os.getenv('PADDLE_ELASTIC_TTL', ELASTIC_TTL)) + + self.start_port = None + if cloud_utils.use_paddlecloud(): + self.trainers = os.getenv('PADDLE_TRAINERS', '') + self.np = len(self.trainers.split(",")) + self.start_port = int(os.getenv("PADDLE_PORT", "6170")) + self.dist_endpoints = os.getenv('DISTRIBUTED_TRAINER_ENDPOINTS', '') + trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS', '') + self.trainer_endpoints_list = trainer_endpoints.split(",") + else: + self.trainers = args.ips or os.getenv('PADDLE_TRAINERS', '') + node_ips = self.trainers.split(",") + self.np = len(node_ips) + self.start_port = int(os.getenv("FLAGS_START_PORT", "6170")) + self.dist_endpoints = self._host_to_endpoints( + node_ips, self.devices_per_proc, self.start_port) + self.trainer_endpoints_list = [ + "%s:%d" % (ip, self.start_port) for ip in node_ips + ] + + self.curr_host = "%s:%d" % (self.host, self.start_port) + logger.info(f'start job with np={self.np}') + logger.info( + f"trainers={self.trainers}, trainer_endpoints_list={self.trainer_endpoints_list}" + ) + + # auto correct the value of elastic_level + # 1: Fault tolerant, 2: Elastic + self.elastic_level = int( + os.getenv('PADDLE_ELASTIC_FAULT_TOLERANC_LEVEL', + ElasticLevel.FAULT_TOLERANCE)) + if self.min_np == self.max_np or \ + (self.min_np > 0 and self.max_np == 0): + self.elastic_level = ElasticLevel.FAULT_TOLERANCE + logger.info(f'start job with ElasticLevel.FAULT_TOLERANCE') + if self.min_np > 0 and self.max_np > self.min_np: + self.elastic_level = ElasticLevel.ELASTIC + logger.info(f'start job with ElasticLevel.ELASTIC') + + # compatible with kuberntes service discovery + if not server and os.getenv( + 'PADDLE_ELASTIC_ETCD_SERVICE_HOST') and os.getenv( + 'PADDLE_ELASTIC_ETCD_SERVICE_PORT'): + server = '{}:{}'.format( + os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_HOST'), + os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_PORT')) + + logger.debug('init with server {} host {}'.format(server, host)) + + self.hosts = [] + self.stopped = False + + self.sigint = 0 + self.need_sync = False + + self.elastic_startup_time = None + + if not server or ':' not in server or not name or not self.np: + logger.info( + 'Elastic is not enabled with server {} name {} and np {}'. + format(server, name, self.np)) + self.enable = False + return + else: + self.enable = True + + self.etcd = etcd_client + + # etcd data + self.prefix = "/paddle/" + name + self.node_prefix = self.prefix + '/nodes' + self.np_path = self.prefix + '/np' + self.endpoints_path = self.prefix + '/endpoints' + + node_tag = ''.join( + random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(6)) + self.host_path = '{}/{}{}'.format(self.node_prefix, node_tag, + time.time()) + ''' + 0 group mode, be aware of healthy status of other workers + 1 decouple mode, check own status only + ''' + self.etcd.put(self.prefix, b'0') + + # register callback + def host_call_back(event): + self.hosts = [ + six.ensure_str(i[0]) + for i in self.etcd.get_prefix(self.node_prefix) + ] + self.hosts = list(set(self.hosts)) if self.hosts else self.hosts + logger.info( + f"host_call_back curr_host={self.curr_host}, hosts:{self.hosts}" + ) + self.need_sync = True + self.elastic_startup_time = None + + host_watch = self.etcd.add_watch_prefix_callback( + self.node_prefix, host_call_back) + host_lease = self.etcd.lease(elastic_ttl) + + # register etcd lease heartbeat + def lease_heartbeat(): + while True: + try: + host_lease.refresh() + + hosts = [ + six.ensure_str(i[0]) + for i in self.etcd.get_prefix(self.node_prefix) + ] + hosts = list(set(hosts)) if hosts else hosts + logger.info( + f"[lease_heartbeat] curr_host={self.curr_host}, hosts={hosts}" + ) + if self.curr_host not in hosts: + logger.info( + f"[lease_heartbeat] register host={self.curr_host}") + self.etcd.put(self.host_path, + six.b(self.curr_host), + lease=host_lease) + except Exception as e: + logger.error( + "[lease_heartbeat] internal error:{} {}".format( + e, traceback.format_exc())) + break + time.sleep(elastic_ttl / 3) + + keepalived_thread = threading.Thread(name='lease_heartbeat', + target=lease_heartbeat, + daemon=True) + keepalived_thread.start() + + self.etcd.put(self.host_path, six.b(self.curr_host), lease=host_lease) + + # endpoints handle DISTRIBUTED_TRAINER_ENDPOINTS and PADDLE_TRAINERS + self.etcd.put(self.endpoints_path, + six.b('{}|{}'.format(self.dist_endpoints, self.trainers))) + + def endpoints_call_back(event): + if not self.dist_endpoints: + return + edps = six.ensure_str(self.etcd.get(self.endpoints_path)[0] or '') + self.dist_endpoints, self.trainers = edps.split('|') + logger.info("set DISTRIBUTED_TRAINER_ENDPOINTS {} ".format( + self.dist_endpoints)) + logger.info("set PADDLE_TRAINERS {} ".format(self.trainers)) + + endpoints_watch = self.etcd.add_watch_callback(self.endpoints_path, + endpoints_call_back) + + self.watches = [host_watch, endpoints_watch] + self.launcher = None + + def _host_to_endpoints(self, + ip_port_list: list, + devices_per_proc: list, + start_port: int = 6170) -> str: + endpoint_list = [] + for ip_port in ip_port_list: + endpoints = ip_port.split(":") + if len(endpoints) == 2: + ip = endpoints[0] + port = int(endpoints[1]) + else: + ip = endpoints + port = start_port + + ports = [x for x in range(port, port + len(devices_per_proc))] + endpoint_list.extend(["%s:%d" % (ip, port) for port in ports]) + + dist_endpoints = ','.join(endpoint_list) + return dist_endpoints + + def exit(self, completed=False): + logger.info('manager exist completed {}'.format(completed)) + + if self.launcher: + self.launcher.stop() + + if not self.enable: + return + + if completed: + self.etcd.put(self.prefix, b'1') + + for watch in self.watches: + self.etcd.cancel_watch(watch) + self.etcd.delete(self.host_path) + + hosts = [i for i in self.etcd.get_prefix(self.node_prefix)] + if len(hosts) == 0: + self.etcd.delete_prefix(self.prefix) + + def pre_hook(self): + if not self.args.elastic_pre_hook: + logger.info("skip pre_hook") + return + logger.info("execute pre_hook...") + current_env = copy.copy(os.environ.copy()) + out, err = subprocess.Popen(self.args.elastic_pre_hook, + env=current_env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=True).communicate() + if err: + logger.warning("pre_hook exec failed") + else: + logger.info(f"pre_hook exec result: {out.decode('utf-8').strip()}") + + def _parse_np(self, np: str): + """ + np format is "MIN" or "MIN:MAX" + """ + np_str = np or os.getenv('PADDLE_ELASTIC_NP', "0") + np_dict = np_str.split(":") + min_np = max_np = 0 + if len(np_dict) == 1: + # Fault tolerant + min_np = int(np_dict[0]) + min_np = 1 if min_np <= 0 else min_np + max_np = 1 + elif len(np_dict) == 2: + # Elastic + min_np = int(np_dict[0]) + max_np = int(np_dict[1]) + min_np = 1 if min_np <= 0 else min_np + max_np = min_np if min_np > max_np else max_np + else: + raise ValueError( + f'the np={np} needs to be in "MIN" or "MIN:MAX" format') + + return min_np, max_np + + def _get_host(self): + try: + return socket.gethostbyname(socket.getfqdn(socket.gethostname())) + except: + return '127.0.0.1' + + def _completed(self): + if not self.enable: + return True + + return int(self.etcd.get(self.prefix)[0]) == 1 + + def _match(self, host_list: list = None): + if host_list: + self.hosts = host_list + else: + self.hosts = [ + six.ensure_str(i[0]) + for i in self.etcd.get_prefix(self.node_prefix) + ] + self.hosts = list(set(self.hosts)) if self.hosts else self.hosts + + if self.elastic_level == ElasticLevel.FAULT_TOLERANCE: + if len(self.hosts) == self.np: + return True + else: + return False + + if self.elastic_level == ElasticLevel.ELASTIC: + hosts_num = len(self.hosts) + if hosts_num == self.np: + return True + + if not self.elastic_startup_time: + self.elastic_startup_time = time.time() + if hosts_num == self.max_np: + self.elastic_startup_time = None + return True + elif hosts_num >= self.min_np and hosts_num < self.max_np: + interval_time = time.time() - self.elastic_startup_time + if interval_time <= self.elastic_timeout: + logger.info( + f"wait for timeout, you can set value by PADDLE_ELASTIC_TIMEOUT, \ + hosts_num={hosts_num}, min_np={self.min_np}, \ + interval_time={interval_time}, elastic_timeout={self.elastic_timeout}" + ) + return False + return True + else: + self.elastic_startup_time = None + return False + + return False + + def _update_endpoint(self, endpoints, hosts): + self.etcd.put(self.endpoints_path, + six.b('{}|{}'.format(endpoints, hosts))) + + def _update_fault_tolrance(self): + rank = int(os.getenv('PADDLE_TRAINER_ID', -1)) + logger.debug( + f"self.curr_host={self.curr_host}, self.dist_endpoints={self.dist_endpoints}" + ) + if self.curr_host in self.dist_endpoints: + os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = self.dist_endpoints + os.environ['PADDLE_TRAINERS'] = self.trainers + logger.info("update env DISTRIBUTED_TRAINER_ENDPOINTS {} ".format( + self.dist_endpoints)) + logger.info("update env PADDLE_TRAINERS {} ".format(self.trainers)) + return + + # fault tolerance + idx = self.hosts.index(self.curr_host) + + # swap if self.host not in the right position + if rank >= 0: + self.hosts[idx] = self.hosts[rank] + self.hosts[rank] = self.curr_host + else: + os.environ['PADDLE_TRAINER_ID'] = '{}'.format(idx) + hosts = ','.join([host_port.split(":")[0] for host_port in self.hosts]) + self.args.ips = hosts + os.environ['PADDLE_TRAINERS'] = hosts + + def _update_elastic_scale_out(self): + host_endpoints = copy.deepcopy(self.trainer_endpoints_list) + logger.info( + f"elastic scale out, from {len(self.hosts)} to {self.np}, hosts={self.hosts}, host_endpoints={host_endpoints}" + ) + + for curr_host_port in self.hosts: + if curr_host_port not in host_endpoints: + host_endpoints.append(curr_host_port) + + os.environ['PADDLE_TRAINER_ID'] = '{}'.format( + host_endpoints.index(self.curr_host)) + hosts = ','.join( + [host_port.split(":")[0] for host_port in host_endpoints]) + self.args.ips = hosts + os.environ['PADDLE_TRAINERS'] = hosts + self.np = len(host_endpoints) + os.environ['PADDLE_TRAINER_ENDPOINTS'] = ','.join(host_endpoints) + os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = self.dist_endpoints + self.trainer_endpoints_list = host_endpoints + + def _update_elastic_scale_in(self): + host_endpoints = copy.deepcopy(self.trainer_endpoints_list) + logger.info( + f"elastic scale in, from {self.np} to {len(self.hosts)}, hosts={self.hosts}, host_endpoints={host_endpoints}" + ) + + # If scale in node from the first of the rank list, you need to minimize the movement of the rank + # eg: + # the source trainers is:10.10.10.0,10.10.10.1,10.10.10.2,10.10.10.3 + # 10.10.10.0 is removed + # the new trainers is:10.10.10.3,10.10.10.1,10.10.10.2 + # In this case, the rank of 10.10.10.1 and 10.10.10.2 remains unchanged, while the rank of 10.10.10.3 is set to rank0 + endpoints_dict = dict() + unsorted_endpoints = [] + for id, host_port in enumerate(self.hosts): + idx = host_endpoints.index(host_port) + if idx <= len(self.hosts) - 1 and not endpoints_dict.get(idx): + endpoints_dict[idx] = host_port + else: + unsorted_endpoints.append(host_port) + + idle_index = 0 + sorted_endpoints = [] + for idx in range(len(self.hosts)): + if not endpoints_dict.get(idx) and len(unsorted_endpoints) > 0: + endpoints_dict[idx] = unsorted_endpoints[idle_index] + idle_index += 1 + + sorted_endpoints.append(endpoints_dict.get(idx)) + + logger.info(f"elastic scale in, sorted_endpoints={sorted_endpoints}") + self.trainer_endpoints_list = sorted_endpoints + + ip_list = [ip_port.split(":")[0] for ip_port in sorted_endpoints] + hosts = ','.join(ip_list) + new_endpoints = self._host_to_endpoints(sorted_endpoints, + self.devices_per_proc) + + self.args.ips = hosts + os.environ['PADDLE_TRAINER_ID'] = '{}'.format( + sorted_endpoints.index(self.curr_host)) + os.environ['PADDLE_TRAINERS'] = hosts + self.np = len(sorted_endpoints) + os.environ['PADDLE_TRAINER_ENDPOINTS'] = ','.join(sorted_endpoints) + os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = new_endpoints + self._update_endpoint(new_endpoints, hosts) + + def _update_hosts(self): + assert len(self.hosts) != 0, 'hosts empty' + if self.elastic_level == ElasticLevel.FAULT_TOLERANCE: + self._update_fault_tolrance() + else: + # elastic + if len(self.hosts) == self.np: + logger.info(f"elastic startup, hosts={self.hosts}") + self._update_fault_tolrance() + + elif len(self.hosts) > self.np: + # scale out + self._update_elastic_scale_out() + else: + # scale in + self._update_elastic_scale_in() + + def wait(self): + if not self.enable: + return + + idx = 1 + while not self.stopped: + if self._match(): + logger.info('ready with hosts {}'.format(self.hosts)) + self._update_hosts() + return + logger.info('not ready for np {} with hosts {}'.format( + self.np, self.hosts)) + idx += 1 + time.sleep(2) + return + + def run(self, launcher): + if self.stopped: + return + + self.launcher = launcher(self.args) + self.launcher.launch() + + def watch(self): + + if self.need_sync: + self.need_sync = False + + while not self.stopped: + ret = self.launcher.watch() + logger.debug(f"launcher.watch():{ret}") + + if ret is not None: # self terminated + logger.info('job exit with code {}'.format(ret)) + if ret == ELASTIC_AUTO_PARALLEL_EXIT_CODE: + logger.info('job re-launch for auto parallel') + self.launcher.stop() + return ElasticStatus.HOLD + + # process is completed if ret >= 0 or error else + completed = True if ret == 0 else False + self.exit(completed=completed) + if completed: + return ElasticStatus.COMPLETED + if self.elastic_level == ElasticLevel.FAULT_TOLERANCE: + return ElasticStatus.RESTART + else: + return ElasticStatus.ERROR + + if not self._completed() and (not self._match() or self.need_sync): + self.launcher.stop() + return ElasticStatus.HOLD + + time.sleep(2) + + if self.launcher: + self.launcher.stop() + + return ElasticStatus.EXIT + + def signal_handler(self, sigint, frame): + if self.enable: + self.exit() + self.sigint = sigint + self.stopped = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet.py new file mode 100644 index 0000000000000000000000000000000000000000..f624b7bdb075b77779028f0e56c955adbf3b0735 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet.py @@ -0,0 +1,1573 @@ +# Copyright (c) 2022 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. + +import copy +import paddle +import os +from types import MethodType +import numpy as np +from paddle.fluid.framework import _global_flags +from paddle.fluid import compiler +from .base.role_maker import ( + UserDefinedRoleMaker, + PaddleCloudRoleMaker, + RoleMakerBase, +) +from .base.strategy_compiler import StrategyCompiler +from .base.distributed_strategy import DistributedStrategy +from .base.meta_optimizer_factory import MetaOptimizerFactory +from .base.runtime_factory import RuntimeFactory +from paddle.fluid.wrapped_decorator import wrap_decorator +from paddle.fluid.dygraph import parallel_helper +from paddle.fluid.ir import apply_build_strategy +from .base import topology as tp +from .meta_parallel import model_parallel_random_seed +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from .utils.log_util import logger, set_log_level +import logging + +__all__ = [] + + +def apply_ir_passes(main_program, startup_program, config): + build_strategy = config._user_defined_strategy.build_strategy._copy() + if not _global_flags()['FLAGS_apply_pass_to_program']: + return build_strategy + + pipeline_opt = getattr(main_program, "_pipeline_opt", {}) + if pipeline_opt: + main_program = pipeline_opt["section_program"] + startup_program = startup_program._pipeline_opt["startup_program"] + + pass_attrs = {"use_cuda": config._is_collective} + fuse_all_reduce = config._user_defined_strategy.fuse_all_reduce_ops + if fuse_all_reduce and build_strategy.fuse_all_optimizer_ops: + # FIXME(zjl): currently, fuse_all_optimizer_ops + # have conflict with fuse_all_reduce_ops because + # RawProgramOptimizer also inserts coalesce_tensor + # into program. These two procedures may conflict + # in which vars are to be fused. + logger.warning( + 'Currently, the fuse_all_optimizer_ops pass has conflict with fuse_all_reduce_ops pass. Disable the fuse_all_optimizer_ops pass temporarily.' + ) + build_strategy.fuse_all_optimizer_ops = False + + return apply_build_strategy( + main_program, startup_program, build_strategy, pass_attrs + ) + + +def _inited_runtime_handler_(func): + def __impl__(*args, **kwargs): + cls = args[0] + + if cls._runtime_handle is None: + raise ValueError("Fleet can not find suitable runtime handler") + + return func(*args, **kwargs) + + return __impl__ + + +def _is_non_distributed_check_(func): + def __impl__(*args, **kwargs): + cls = args[0] + + if ( + cls._role_maker is not None + and cls._role_maker._is_non_distributed() is True + ): + logger.warning( + "%s() function doesn't work when use non_distributed fleet." + % (func.__name__) + ) + return + + return func(*args, **kwargs) + + return __impl__ + + +inited_runtime_handler = wrap_decorator(_inited_runtime_handler_) +is_non_distributed_check = wrap_decorator(_is_non_distributed_check_) + + +class Fleet(object): + """ + Unified API for distributed training of PaddlePaddle + Please reference the https://github.com/PaddlePaddle/PaddleFleetX for details + + + Returns: + Fleet: A Fleet instance + + Example for collective training: + + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + fleet.init(is_collective=True) + + strategy = fleet.DistributedStrategy() + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) + + # do distributed training + + + Example for parameter server training: + + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + fleet.init(strategy=strategy) + + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer = fleet.distributed_optimizer(optimizer) + + if fleet.is_first_worker(): + print("this is first worker") + + print("current node index: {}".format(fleet.worker_index())) + print("total number of worker num: {}".format(fleet.worker_num())) + + if fleet.is_worker(): + print("this is worker") + print("worker endpoints: {}".format(fleet.worker_endpoints(to_string=True))) + + print("server num: {}".format(fleet.server_num())) + print("server endpoints: {}".format(fleet.server_endpoints(to_string=True))) + + if fleet.is_server(): + print("this is server") + fleet.stop_worker() + + + """ + + def __init__(self): + self._role_maker = None + self.strategy_compiler = None + self._is_collective = False + self._runtime_handle = None + self._util = None + self._context = {} + self.user_defined_optimizer = paddle.optimizer.Optimizer(0.0) + + def init( + self, + role_maker=None, + is_collective=False, + strategy=None, + log_level="INFO", + ): + """ + Initialize role_maker in Fleet. + + This function is responsible for the distributed architecture + what you want to run your code behind. + + Args: + role_maker (RoleMakerBase, optional): A ``RoleMakerBase`` containing the configuration + of environment variables related to distributed training.If you did not initialize + the rolemaker by yourself, it will be automatically initialized to PaddleRoleMaker. + The default value is None. + is_collective (Boolean, optional): A ``Boolean`` variable determines whether the program + runs on the CPU or GPU. False means set distributed training using CPU, and True means + GPU.The default value is False.The default value is False. + strategy (DistributedStrategy): Extra properties for distributed training. + For details, please refer to paddle.distributed.fleet.DistributedStrategy. Default: None. + log_level (Integer, String, optional): A ``Integer`` or ``String`` Variable determining how hight + the logging level is. Default is "INFO". + + + Returns: + None + + Examples1: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + Examples2: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init(is_collective=True) + + Examples3: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + role = fleet.PaddleCloudRoleMaker() + fleet.init(role) + + Examples4: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + fleet.init(strategy=strategy) + + Examples5: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + strategy = fleet.DistributedStrategy() + fleet.init(log_level = "DEBUG") + + """ + + set_log_level(log_level) + + if strategy is None: + strategy = DistributedStrategy() + self._user_defined_strategy = copy.deepcopy(strategy) + + if role_maker is None: + if isinstance(is_collective, bool): + self._is_collective = is_collective + self._role_maker = PaddleCloudRoleMaker( + is_collective=self._is_collective + ) + else: + raise ValueError( + "`is_collective` should be instance of `bool`, but got {}".format( + type(is_collective) + ) + ) + else: + if isinstance(role_maker, RoleMakerBase): + self._role_maker = role_maker + self._is_collective = role_maker._is_collective + else: + raise ValueError( + "`role_maker` should be subclass of `RoleMakerBase`, but got {}".format( + type(role_maker) + ) + ) + self._role_maker._generate_role() + + import paddle.distributed.fleet as fleet + + fleet.util._set_role_maker(self._role_maker) + + self.strategy_compiler = StrategyCompiler() + + if self._role_maker._is_non_distributed() and self._is_collective: + if paddle.fluid.core.is_compiled_with_cuda(): + gpus_num = paddle.fluid.core.get_cuda_device_count() + if gpus_num != 1: + raise ValueError( + "CUDA_VISIBLE_DEVICES shoule be set only 1 card if you use `python` to launch fleet program." + ) + + if paddle.fluid.framework._non_static_mode(): + if self.worker_num() == 1: + # if worker_num is 1, should construct default topology & hcg + self._topology = tp.CommunicateTopology() + self._hcg = tp.HybridCommunicateGroup(self._topology) + return + if parallel_helper._is_parallel_ctx_initialized(): + logger.warning( + "The dygraph parallel environment has been initialized." + ) + else: + # FLAGS_nccl_nrings is used for dynamic graph multi-stream communication + if "FLAGS_nccl_nrings" in os.environ: + logger.warning( + "You have set the environment variable FLAGS_nccl_nrings " + "outside the program, so the nccl_comm_num in " + "DistributedStrategy will not take effect here." + ) + else: + os.environ["FLAGS_nccl_nrings"] = str( + self._user_defined_strategy.nccl_comm_num + ) + paddle.distributed.init_parallel_env() + + # hybrid parallel not support for npu/xpu + if self._user_defined_strategy.heter_ccl_mode == False: + # init hybrid parallel environment in dygraph + if tp._HYBRID_PARALLEL_GROUP is None: + self._init_hybrid_parallel_env() + else: + logger.warning( + "The dygraph hybrid parallel environment has been initialized." + ) + elif self._is_collective: + use_sharding = self._user_defined_strategy.sharding + + # global group + global_rank = self.worker_index() + global_world_size = self.worker_num() + # NOTE(wangxi): see sharding_optimizer + global_ring_id = 3 if use_sharding else 0 + global_ranks = list(range(global_world_size)) + + if tp._HYBRID_PARALLEL_GROUP is None: + tp._CommunicateGroup() + cg = tp._HYBRID_PARALLEL_GROUP + self._hcg = cg + cg.set_comm_group( + 'global', + global_rank, + global_world_size, + global_ring_id, + global_ranks, + ) + + use_tensor_parallel = self._user_defined_strategy.tensor_parallel + use_mp = use_sharding or use_tensor_parallel + + # hybrid group + if use_mp is False: + return + + mp_degree_sharding = 1 + mp_degree_tensor_parallel = 1 + if use_sharding: + sharding_configs = self._user_defined_strategy.sharding_configs + mp_degree_sharding = int(sharding_configs['mp_degree']) + + if use_tensor_parallel: + tensor_parallel_configs = ( + self._user_defined_strategy.tensor_parallel_configs + ) + mp_degree_tensor_parallel = int( + tensor_parallel_configs['tensor_parallel_degree'] + ) + + if use_sharding and use_tensor_parallel: + assert mp_degree_sharding == mp_degree_tensor_parallel + + mp_degree = ( + mp_degree_sharding + if use_sharding + else mp_degree_tensor_parallel + ) + + if mp_degree > 1: + assert global_world_size % mp_degree == 0 + # NOTE(wangxi): mp_ring_id sync with sharding_optimizer.py _build_groups + mp_ring_id = 0 + mp_rank = global_rank % mp_degree + mp_group_id = global_rank // mp_degree + mp_group_ranks = [ + idx + for idx in global_ranks + if idx // mp_degree == mp_group_id + ] + cg.set_comm_group( + 'model', mp_rank, mp_degree, mp_ring_id, mp_group_ranks + ) + return self + + def _init_hybrid_parallel_env(self): + """initialize the hybrid environment""" + self.hybrid_configs = self._user_defined_strategy.hybrid_configs + self.dp_degree = self.hybrid_configs["dp_degree"] + self.mp_degree = self.hybrid_configs["mp_degree"] + self.pp_degree = self.hybrid_configs["pp_degree"] + self.sharding_degree = self.hybrid_configs["sharding_degree"] + + assert self.mp_degree >= 0, "mp_degree should be greater or equal to 0" + assert self.pp_degree >= 0, "pp_degree should be greater or equal to 0" + assert ( + self.sharding_degree >= 0 + ), "sharding_degree should be greater or equal to 0" + + self.mp_degree = max(self.mp_degree, 1) + self.pp_degree = max(self.pp_degree, 1) + + if self.dp_degree < 0: + nranks = paddle.distributed.get_world_size() + self.dp_degree = nranks // (self.mp_degree * self.pp_degree) + + self.dp_degree = max(self.dp_degree, 1) + + self._topology = tp.CommunicateTopology( + hybrid_group_names=["data", "pipe", "sharding", "model"], + dims=[ + self.dp_degree, + self.pp_degree, + self.sharding_degree, + self.mp_degree, + ], + ) + + self._hcg = tp.HybridCommunicateGroup(self._topology) + + if self.mp_degree > 1: + tensor_parallel_configs = ( + self._user_defined_strategy.tensor_parallel_configs + ) + tensor_init_seed = tensor_parallel_configs["tensor_init_seed"] + if tensor_init_seed == -1: + model_parallel_random_seed() + else: + model_parallel_random_seed(tensor_init_seed) + + def get_hybrid_communicate_group(self): + assert self._hcg is not None + return self._hcg + + def get_hybrid_parallel_topology(self): + assert self._topology is not None + return self._topology + + def is_first_worker(self): + """ + Check whether the node is the first instance of worker. + + Returns: + bool: True if this is the first node of worker, + False if not. + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.is_first_worker() + + """ + return self._role_maker._is_first_worker() + + def worker_index(self): + """ + Get current worker index. + + Returns: + int: node id + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.worker_index() + + """ + return self._role_maker._worker_index() + + def worker_num(self): + """ + Get current total worker number. + + Returns: + int: worker numbers + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.worker_num() + + """ + return self._role_maker._worker_num() + + def node_num(self): + return self._role_maker._get_node_num() + + def local_rank(self): + return self._role_maker._get_local_rank() + + def local_device_ids(self): + return self._role_maker._get_local_device_ids() + + def world_device_ids(self): + return self._role_maker._get_world_device_ids() + + def is_worker(self): + """ + Check whether the node is an instance of worker. + + Returns: + bool: True if this is a node of worker, + False if not. + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.is_worker() + + """ + return self._role_maker._is_worker() + + def is_coordinator(self): + return self._role_maker._is_coordinator() + + def worker_endpoints(self, to_string=False): + """ + Get current worker endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. + + Returns: + list/string: server endpoints + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.worker_endpoints() + + """ + if to_string: + return ",".join(self._role_maker._get_trainer_endpoints()) + else: + return self._role_maker._get_trainer_endpoints() + + def server_num(self): + """ + Get current total worker number. + + Returns: + int: server number + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.server_num() + """ + return len(self._role_maker._get_pserver_endpoints()) + + def server_index(self): + """ + Get current server index. + + Returns: + int: node id + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.server_index() + + """ + return self._role_maker._server_index() + + def server_endpoints(self, to_string=False): + """ + Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. + + Returns: + list/string: server endpoints + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.server_endpoints() + + """ + + if to_string: + return ",".join(self._role_maker._get_pserver_endpoints()) + else: + return self._role_maker._get_pserver_endpoints() + + def is_server(self): + """ + Check whether the node is an instance of server. + + Returns: + bool: True if this is a node of server, + False if not. + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + fleet.is_server() + + """ + return self._role_maker._is_server() + + def barrier_worker(self): + """ + barrier all workers + + Returns: + None + """ + self._role_maker._barrier("worker") + + @is_non_distributed_check + @inited_runtime_handler + def init_worker(self, scopes=None): + """ + initialize `Communicator` for parameter server training. + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.init_worker() + + """ + self._runtime_handle._init_worker(scopes) + + @is_non_distributed_check + @inited_runtime_handler + def init_coordinator(self, scopes=None): + """ + initialize coordinator node + """ + self._runtime_handle._init_coordinator(scopes) + + def make_fl_strategy(self): + self._runtime_handle._make_fl_strategy() + + @is_non_distributed_check + @inited_runtime_handler + def get_fl_client(self): + """ + get worker(training node) ptr + """ + return self._runtime_handle._worker + + @is_non_distributed_check + @inited_runtime_handler + def init_server(self, *args, **kwargs): + """ + init_server executor to initialize startup program, + if the `args` is not empty, it will run load_persistables for increment training. + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.init_server() + + """ + self._runtime_handle._init_server(*args, **kwargs) + + @is_non_distributed_check + @inited_runtime_handler + def load_model(self, path, mode): + """ + load fleet model from path + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.load_model("path", mode=0) + + """ + self._runtime_handle._load_persistables(path, mode) + + @is_non_distributed_check + @inited_runtime_handler + def load_one_table(self, table_id, path, mode): + """ + load fleet one table from path + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.load_one_table(0, "path", mode=0) + + """ + self._runtime_handle._load_one_table(table_id, path, mode) + + @is_non_distributed_check + @inited_runtime_handler + def load_inference_model(self, path, mode): + """ + load fleet inference model from path + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.load_inference_model("path", mode=1) + + """ + self._runtime_handle._load_inference_model(path, mode) + + @is_non_distributed_check + @inited_runtime_handler + def run_server(self): + """ + run server will run pserver main program with executor. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + if fleet.is_server(): + fleet.init_server() + + """ + self._runtime_handle._run_server() + + @is_non_distributed_check + @inited_runtime_handler + def stop_worker(self): + """ + stop `Communicator` and give training complete notice to parameter server. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.init_server() + + """ + self._runtime_handle._stop_worker() + + @is_non_distributed_check + @inited_runtime_handler + def save(self, dirname, feed=[], fetch=[], **configs): + inference = True + + if not feed and not fetch: + inference = False + + place = paddle.CPUPlace() + executor = paddle.static.Executor(place) + + if inference: + feeded_var_names = [] + fetch_var_names = [] + + for var in feed: + if isinstance(var, str): + feeded_var_names.append(var) + elif isinstance(var, paddle.static.Variable): + feeded_var_names.append(var.name) + else: + raise ValueError("feed must be [str|Variable]") + + for var in fetch: + if isinstance(var, str): + fetch_var_names.append(var) + elif isinstance(var, paddle.static.Variable): + fetch_var_names.append(var.name) + else: + raise ValueError("feed must be [str|Variable]") + + fetch_vars = [ + paddle.static.default_main_program().global_block().var(name) + for name in fetch_var_names + ] + + self._runtime_handle._save_inference_model( + executor, dirname, feeded_var_names, fetch_vars, None, True, 0 + ) + else: + increment_mode = 0 + if "mode" in configs: + increment_mode = int(configs["mode"]) + self._runtime_handle._save_persistables( + executor, dirname, main_program=None, mode=increment_mode + ) + + @is_non_distributed_check + @inited_runtime_handler + def save_inference_model( + self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True, + mode=0, + ): + """ + save inference model for inference. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.init_server() + + """ + + self._runtime_handle._save_inference_model( + executor, + dirname, + feeded_var_names, + target_vars, + main_program, + export_for_deployment, + mode, + ) + + @is_non_distributed_check + @inited_runtime_handler + def save_persistables(self, executor, dirname, main_program=None, mode=0): + """ + + saves all persistable tensors from :code:`main_program` to + the folder :code:`dirname`. You can refer to + + The :code:`dirname` is used to specify the folder where persistable tensors + are going to be saved. If you would like to save tensors in separate + files, set :code:`filename` None. + + Args: + executor(Executor): The executor to run for saving persistable tensors. + You can refer to :ref:`api_guide_executor_en` for + more details. + + dirname(str, optional): The saving directory path. + When you need to save the parameter to the memory, set it to None. + main_program(Program, optional): The program whose persistbale tensors will + be saved. Default: None. + + + Returns: + None + + Examples: + + .. code-block:: text + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + exe = paddle.static.Executor(paddle.CPUPlace()) + fleet.save_persistables(exe, "dirname", paddle.static.default_main_program()) + + """ + self._runtime_handle._save_persistables( + executor, dirname, main_program, mode + ) + + @is_non_distributed_check + @inited_runtime_handler + def save_cache_model(self, dirname, **configs): + return self._runtime_handle._save_cache_model(dirname, **configs) + + @is_non_distributed_check + @inited_runtime_handler + def check_save_pre_patch_done(self): + return self._runtime_handle._check_save_pre_patch_done() + + @is_non_distributed_check + @inited_runtime_handler + def save_one_table(self, table_id, path, mode): + """ + save fleet one table from path + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + + # build net + # fleet.distributed_optimizer(...) + + fleet.save_one_table(0, "path", mode=0) + + """ + self._runtime_handle._save_one_table(table_id, path, mode) + + @is_non_distributed_check + @inited_runtime_handler + def save_dense_params( + self, executor, dirname, scope, program, var_names=None + ): + """ + save fleet one table from path + + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.distributed.fleet as fleet + fleet.init() + import paddle + place = paddle.fluid.CPUPlace() + exe = paddle.fluid.Executor(place) + + # build net + # fleet.distributed_optimizer(...) + + fleet.save_dense_params(exe, "path", scope=paddle.static.global_scope(), program=paddle.static.default_main_program()) + + """ + self._runtime_handle._save_dense_params( + executor, dirname, scope, program, var_names + ) + + def shrink(self, threshold=None): + self._runtime_handle._shrink(threshold) + + def distributed_optimizer(self, optimizer, strategy=None): + """ + Optimizer for distributed training. + + For the distributed training, this method would rebuild a new instance of DistributedOptimizer. + Which has basic Optimizer function and special features for distributed training. + + Args: + optimizer(Optimizer): The executor to run for init server. + strategy(DistributedStrategy): Extra properties for distributed optimizer. + It is recommended to use DistributedStrategy in fleet.init(). The strategy + here is for compatibility. If the strategy in fleet.distributed_optimizer() + is not None, then it will overwrite the DistributedStrategy in fleet.init(), + which will take effect in distributed training. + + Returns: + Fleet: instance of fleet. + + Examples: + + .. code-block:: python + + import paddle + import paddle.distributed.fleet as fleet + fleet.init(is_collective=True) + strategy = fleet.DistributedStrategy() + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) + + """ + self.user_defined_optimizer = optimizer + + if strategy is not None: + if self._is_collective: + logger.warning( + "It is recommended to use DistributedStrategy " + "in fleet.init(). The strategy here is only for compatibility. " + "If the strategy in fleet.distributed_optimizer() is " + "not None, then it will overwrite the DistributedStrategy in fleet.init(), " + "which will take effect in distributed training." + ) + self._user_defined_strategy = copy.deepcopy(strategy) + + self._context = {} + + return self + + def _get_amp_optimizer(self): + # imitate target optimizer retrieval + amp_optimizer = None + for optimizer in self.strategy_compiler._get_applied_meta_optimizer(): + if hasattr(optimizer, 'amp_init'): + amp_optimizer = optimizer + break + + if amp_optimizer is None: + if hasattr(self.user_defined_optimizer, 'amp_init'): + amp_optimizer = self.user_defined_optimizer + + assert ( + amp_optimizer is not None + ), "amp_init can only be used when the amp(auto mixed precision) strategy is turned on." + return amp_optimizer + + def get_loss_scaling(self): + """Return the real-time loss scaling factor.""" + amp_optimizer = self._get_amp_optimizer() + return amp_optimizer.get_loss_scaling() + + def amp_init( + self, place, scope=None, test_program=None, use_fp16_test=False + ): + """ + Init the amp training, such as cast fp32 parameters to fp16 type. + + Args: + place(CUDAPlace): place is used to initialize + fp16 parameters with fp32 values. + scope(Scope): The scope is used to find fp32 parameters. + test_program(Program): The program is used for testing. + use_fp16_test(bool): Whether to use fp16 testing. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + paddle.enable_static() + + def run_example_code(): + place = paddle.CUDAPlace(0) + exe = paddle.static.Executor(place) + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + # 1) Use fp16_guard to control the range of fp16 kernels used. + with paddle.static.amp.fp16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + # 2) Create the optimizer and set `multi_precision` to True. + # Setting `multi_precision` to True can avoid the poor accuracy + # or the slow convergence in a way. + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True) + # 3) These ops in `custom_black_list` will keep in the float32 computation type. + amp_list = paddle.static.amp.CustomOpLists( + custom_black_list=['pool2d']) + # 4) The entry of Paddle AMP. + # Enable pure fp16 training by setting `use_pure_fp16` to True. + optimizer = paddle.static.amp.decorate( + optimizer, + amp_list, + init_loss_scaling=128.0, + use_dynamic_loss_scaling=True, + use_pure_fp16=True) + # If you don't use the default_startup_program(), you sholud pass + # your defined `startup_program` into `minimize`. + optimizer.minimize(loss) + exe.run(paddle.static.default_startup_program()) + # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`). + # If you want to perform the testing process, you should pass `test_program` into `amp_init`. + optimizer.amp_init(place, scope=paddle.static.global_scope()) + + if paddle.is_compiled_with_cuda() and len(paddle.static.cuda_places()) > 0: + run_example_code() + """ + amp_optimizer = self._get_amp_optimizer() + return amp_optimizer.amp_init(place, scope, test_program, use_fp16_test) + + def _final_strategy(self): + if "valid_strategy" not in self._context: + print( + "WARNING: You may need to call minimize function before this function is called" + ) + return {} + else: + return self._context["valid_strategy"] + + def _get_applied_meta_list(self): + if "applied_meta_list" not in self._context: + print( + "WARNING: You may need to call minimize function before _get_applied_meta_list called" + ) + return [] + else: + return self._context["applied_meta_list"] + + def _get_applied_graph_list(self): + if "applied_graph_list" not in self._context: + print( + "WARNING: You may need to call minimize function before _get_applied_graph_list called" + ) + return [] + else: + return self._context["applied_graph_list"] + + def minimize( + self, loss, startup_program=None, parameter_list=None, no_grad_set=None + ): + """ + Add distributed operations to minimize ``loss`` by updating ``parameter_list``. + + Args: + loss (Tensor): A ``Tensor`` containing the value to minimize. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameter_list``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameter_list (Iterable, optional): Iterable of ``Tensor`` or ``Tensor.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't need + to be updated. The default value is None. + + Returns: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by minimize and a list of (param, grad) tensor pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + The returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.distributed.fleet as fleet + import paddle.nn.functional as F + + hid_dim = 10 + label_dim = 2 + input_x = paddle.static.data(name='x', shape=[None, 13], dtype='float32') + input_y = paddle.static.data(name='y', shape=[None, 1], dtype='int64') + fc_1 = paddle.static.nn.fc(x=input_x, size=hid_dim, activation='tanh') + fc_2 = paddle.static.nn.fc(x=fc_1, size=hid_dim, activation='tanh') + prediction = paddle.static.nn.fc(x=[fc_2], size=label_dim, activation='softmax') + cost = F.cross_entropy(input=prediction, label=input_y) + avg_cost = paddle.mean(x=cost) + + fleet.init(is_collective=True) + strategy = fleet.DistributedStrategy() + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) + optimizer.minimize(avg_cost) + + # for more examples, please reference https://github.com/PaddlePaddle/PaddleFleetX + + """ + if not isinstance(loss, list): + return self._minimize_impl( + loss, startup_program, parameter_list, no_grad_set + ) + else: + if ( + paddle.fluid.framework._non_static_mode() + or self._role_maker._is_non_distributed() + or self._is_collective + ): + raise ValueError("loss can be list only in PS mode") + return self._minimize_losses_impl( + loss, startup_program, parameter_list, no_grad_set + ) + + def _minimize_impl( + self, loss, startup_program=None, parameter_list=None, no_grad_set=None + ): + context = {} + context["user_defined_strategy"] = copy.deepcopy( + self._user_defined_strategy + ) + if paddle.fluid.framework._non_static_mode(): + # imitate target optimizer retrieval + target_opt = self.user_defined_optimizer + self._context = context + return target_opt.minimize(loss) + + # cache original feed forward program + self.origin_main_program = loss.block.program + # add distributed attr + if not hasattr(self.origin_main_program, "distributed_info_"): + setattr(self.origin_main_program, "distributed_info_", dict()) + self.origin_main_program.distributed_info_[ + "dp_degree" + ] = self._user_defined_strategy.sharding_configs["dp_degree"] + self.origin_main_program.distributed_info_[ + "mp_degree" + ] = self._user_defined_strategy.sharding_configs["mp_degree"] + self.origin_main_program.distributed_info_[ + "pp_degree" + ] = self._user_defined_strategy.sharding_configs["pp_degree"] + self.origin_main_program.distributed_info_[ + "sharding_degree" + ] = self._user_defined_strategy.sharding_configs["sharding_degree"] + + context["origin_main_program"] = self.origin_main_program + context["origin_main_programs"] = [self.origin_main_program] + context["loss"] = loss + if startup_program == None: + self.origin_startup_program = ( + paddle.static.default_startup_program().clone(for_test=False) + ) + startup_program = paddle.static.default_startup_program() + else: + self.origin_startup_program = startup_program.clone(for_test=False) + + context["origin_startup_program"] = startup_program + context["origin_startup_programs"] = [startup_program] + context["role_maker"] = self._role_maker + + # Use the auto-parallel's routines instead + if ( + self._user_defined_strategy.semi_auto + or self._user_defined_strategy.auto_search + ): + from ..auto_parallel.parallelizer import AutoParallelizer + + auto_parallelizer = AutoParallelizer(self) + ( + optimize_ops, + params_grads, + dist_startup_prog, + dist_main_prog, + ) = auto_parallelizer.parallelize( + loss, startup_program, parameter_list, no_grad_set + ) + + return optimize_ops, params_grads, dist_startup_prog, dist_main_prog + + # compile time + distributed_optimizer_list = ( + MetaOptimizerFactory()._get_valid_meta_optimizers( + self.user_defined_optimizer + ) + ) + + context["user_defined_strategy"] = copy.deepcopy( + self._user_defined_strategy + ) + copy_user_defined_strategy = copy.deepcopy(self._user_defined_strategy) + + # trigger the auto-parallel in very strict condition + # strategy = DistributedStrategy() + # strategy.auto = True + # optimizer = paddle.optimizer.SGD(learning_rate=0.1) + # optimizer = fleet.distributed_optimizer(optimizer, strategy) + if copy_user_defined_strategy._is_strict_auto(): + # turn on all the strategy for each optimizer + for opt in distributed_optimizer_list: + opt._enable_strategy(copy_user_defined_strategy, context) + + valid_optimizer_list = [] + valid_graph_optimizer_list = [] + can_not_apply_optimizer_list = [] + # recall meta optimizers for ranking + for opt in distributed_optimizer_list: + opt._set_basic_info( + loss, + self._role_maker, + self.user_defined_optimizer, + copy_user_defined_strategy, + ) + if opt._can_apply() and not opt._is_graph_out(): + valid_optimizer_list.append(opt) + elif opt._can_apply() and opt._is_graph_out(): + valid_graph_optimizer_list.append(opt) + else: + can_not_apply_optimizer_list.append(opt) + # combine recalled meta optimizers to be a valid meta optimizer + ( + meta_optimizer, + graph_optimizer, + ) = self.strategy_compiler.generate_optimizer( + loss, + self._role_maker, + self.user_defined_optimizer, + copy_user_defined_strategy, + valid_optimizer_list, + valid_graph_optimizer_list, + ) + + valid_strategy = self.strategy_compiler._get_valid_strategy( + copy_user_defined_strategy, can_not_apply_optimizer_list + ) + + context["valid_strategy"] = copy.deepcopy(valid_strategy) + logger.debug("valid_strategy: " + str(context["valid_strategy"])) + logger.debug( + "user_defined_strategy: " + str(context["user_defined_strategy"]) + ) + + applied_meta_list = self.strategy_compiler._get_applied_meta_list() + applied_graph_list = self.strategy_compiler._get_applied_graph_list() + + context['applied_meta_list'] = applied_meta_list + context['applied_graph_list'] = applied_graph_list + + self._context = context + + self.valid_strategy = valid_strategy + self.valid_strategy._enable_env() + + optimize_ops = [] + params_grads = [] + + if self._role_maker._is_non_distributed() and not self._is_collective: + if self._runtime_handle is None: + self._runtime_handle = RuntimeFactory()._create_runtime(context) + + compiled_program = compiler.CompiledProgram( + self.origin_main_program + ).with_data_parallel(loss_name=loss.name, share_vars_from=None) + loss.block.program._graph = compiled_program + return self.user_defined_optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set + ) + + if meta_optimizer: + logger.debug( + "before minimize program id: " + str(id(loss.block.program)) + ) + optimize_ops, params_grads = meta_optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set + ) + logger.debug( + "after minimize program id: " + str(id(loss.block.program)) + ) + default_program = paddle.static.default_main_program() + logger.debug("default program id: " + str(id(default_program))) + + if id(default_program) != id(loss.block.program): + paddle.fluid.framework.switch_main_program(loss.block.program) + logger.debug( + "default program id after switch: " + str(id(default_program)) + ) + + else: + optimize_ops, params_grads = self.user_defined_optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set + ) + + context["program_optimize_ops"] = optimize_ops + context["program_params_grads"] = params_grads + + if graph_optimizer: + logger.debug( + "before graph minimize program id: " + + str(id(loss.block.program)) + ) + optimize_ops, params_grads = graph_optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set + ) + # since we do not encourage users to use graph operations + # if a graph optimizer takes effect, mostly + # optimizers_ops and params_grads are None + # i.e. users can not modify current computation graph anymore + context["graph_optimize_ops"] = optimize_ops + context["graph_optimize_grads"] = params_grads + else: + apply_ir_passes(loss.block.program, startup_program, self) + + if not self._role_maker._is_heter_parameter_server_mode: + program = paddle.static.default_main_program() + opt_info = {} if program._fleet_opt is None else program._fleet_opt + opt_info["mpi_size"] = self.worker_num() + opt_info["mpi_rank"] = self.worker_index() + for ( + k, + v, + ) in self._user_defined_strategy.trainer_desc_configs.items(): + if v or k not in opt_info: + opt_info[k] = v + program._fleet_opt = opt_info + + if self._runtime_handle is None: + self._runtime_handle = RuntimeFactory()._create_runtime(context) + + import paddle.distributed.fleet as fleet + + fleet.util._set_strategy(context["valid_strategy"]) + + return optimize_ops, params_grads + + def _minimize_losses_impl( + self, + losses, + startup_programs=None, + parameter_list=None, + no_grad_set=None, + ): + context = {} + + # cache original feed forward program + self.origin_main_program = losses[0].block.program + context["origin_main_program"] = self.origin_main_program + context["origin_main_programs"] = [] + for loss in losses: + context["origin_main_programs"].append(loss.block.program) + context["loss"] = losses + + if startup_programs is None: + if len(losses) == 1: + startup_programs = [paddle.static.default_startup_program()] + else: + raise ValueError( + "startup_program can't be None when loss is list." + ) + self.origin_startup_program = startup_programs[0].clone(for_test=False) + context["origin_startup_program"] = startup_programs[0] + context["origin_startup_programs"] = [] + for program in startup_programs: + context["origin_startup_programs"].append(program) + + context["role_maker"] = self._role_maker + + context["user_defined_strategy"] = copy.deepcopy( + self._user_defined_strategy + ) + + context["valid_strategy"] = copy.deepcopy(self._user_defined_strategy) + + self._context = context + + self.valid_strategy = context["valid_strategy"] + self.valid_strategy._enable_env() + + optimize_ops = [] + params_grads = [] + + from .meta_optimizers import ParameterServerOptimizer + + ps_optimizer = ParameterServerOptimizer(self.user_defined_optimizer) + ps_optimizer._set_basic_info( + losses, + self._role_maker, + self.user_defined_optimizer, + self._user_defined_strategy, + ) + optimize_ops, params_grads = ps_optimizer.minimize_losses_impl( + losses, startup_programs, parameter_list, no_grad_set=no_grad_set + ) + + # default_program = paddle.static.default_main_program() + + # if id(default_program) != id(losses[0].block.program): + # paddle.fluid.framework.switch_main_program(losses[0].block.program) + + context["program_optimize_ops"] = optimize_ops + context["program_params_grads"] = params_grads + + for loss in losses: + program = loss.block.program + opt_info = {} if program._fleet_opt is None else program._fleet_opt + opt_info["mpi_size"] = self.worker_num() + opt_info["mpi_rank"] = self.worker_index() + for ( + k, + v, + ) in self._user_defined_strategy.trainer_desc_configs.items(): + if v or k not in opt_info: + opt_info[k] = v + program._fleet_opt = opt_info + logger.debug( + "fleet base opt info: " + + str(id(program)) + + str(program._fleet_opt) + ) + + if self._runtime_handle is None: + self._runtime_handle = RuntimeFactory()._create_runtime(context) + + import paddle.distributed.fleet as fleet + + fleet.util._set_strategy(context["valid_strategy"]) + + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet_executor_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet_executor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a1d8b18148daed761dd14bfe7b882872ed852b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/fleet_executor_utils.py @@ -0,0 +1,423 @@ +# Copyright (c) 2021 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. + +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY +from paddle.fluid import core +from paddle.static import Program + + +class TaskNode: + """ + Python side TaskNode, connection to the c++ side TaskNode + """ + + def __init__(self, + rank, + max_run_times, + max_slot_times, + role=None, + node_type=None, + task_id=0, + ops=None, + program=None, + lazy_initialize=False): + """ + :param rank (int): Current rank of the task node. + :param max_run_times (int): The max run times of the task node. + :param max_slot_times (int): The mas slot times of the task node. + :param role (int): The role of the task node. (Will be removed in the future) + :param node_type (str): The type of the task node. + :param task_id (int): The id of task node. + :param ops (list): A list of op.desc to init the task node. (Will be removed in the future) + :param program (Program): An instance of Program to init the task node. + :param lazy_initialize (bool): In user-defined task, the program may change adding feed/fetch op. As efficient consideration, the task node will have the C++ object later. + """ + assert ((ops is not None) ^ (program is not None)), \ + "Should provide only one of ops or program to task node." + assert (not ((ops is not None) and lazy_initialize)), \ + "Lazy initialization doesn't support with ops list" + self.id = int(task_id) + self.rank = rank + self.max_run_times = max_run_times + self.max_slot_times = max_slot_times + self.node_type = node_type + self.program = program + self.lazy_initialize = lazy_initialize + self.run_pre_steps = None + self.run_at_offset = None + self.node = None + self.upstreams = [] + self.downstreams = [] + if not lazy_initialize: + if ops is not None: + assert role is not None and task_id is not None, \ + "If init task node with ops, should provide `role` and `task_id`." + self.node = core.TaskNode(role, ops, rank, task_id, + max_run_times, max_slot_times) + else: + self.node = core.TaskNode(program.desc, rank, self.id, + max_run_times, max_slot_times) + if self.node_type: + self.node.set_type(self.node_type) + + def task_node(self): + if self.lazy_initialize: + self.node = core.TaskNode(self.program.desc, self.rank, self.id, + self.max_run_times, self.max_slot_times) + if self.node_type: + self.node.set_type(self.node_type) + if self.run_pre_steps: + self.node.set_run_pre_steps(self.run_pre_steps) + if self.run_at_offset: + self.node.set_run_at_offset(self.run_at_offset) + for up in self.upstreams: + self.node.add_upstream_task(up[0], up[1]) + for down in self.downstreams: + self.node.add_downstream_task(down[0], down[1]) + self.lazy_initialize = False + return self.node + + def set_program(self, program): + assert self.lazy_initialize, \ + "Inside program is unchangable for immediate initialized task node. Set the lazy_initialize to be true if the inside program need to be update. Remember to do all your change before eval node.task_node()." + self.program = program + + def get_program(self): + assert self.program is not None, "The task node is not initialized using program" + return self.program + + def set_run_pre_steps(self, steps): + if self.lazy_initialize: + self.run_pre_steps = steps + else: + self.node.set_run_pre_steps(steps) + + def set_run_at_offset(self, offset): + if self.lazy_initialize: + self.run_at_offset = offset + else: + self.node.set_run_at_offset(offset) + + def add_upstream_task(self, upstream, buffer_size=2): + if self.lazy_initialize: + self.upstreams.append((upstream, buffer_size)) + else: + self.node.add_upstream_task(upstream, buffer_size) + + def add_downstream_task(self, downstream, buffer_size=2): + if self.lazy_initialize: + self.downstreams.append((downstream, buffer_size)) + else: + self.node.add_downstream_task(downstream, buffer_size) + + def task_id(self): + return self.id + + +class CoordSys: + """ + This class is used to mapping rank to (mp rank, sharding rank, pp rank, dp rank). + """ + + def __init__(self, dist_opt): + self.dp_degree = dist_opt.get('dp_degree', 1) + self.pp_degree = dist_opt.get('pp_degree', 1) + self.sharding_degree = dist_opt.get('sharding_degree', 1) + self.mp_degree = dist_opt.get('mp_degree', 1) + + def _invalide_coord(self, coord): + """ + Test the input coord is valid or not. + :param coord: The coord to be tested + :return: False if valid, True if invalid. + """ + return coord['mp_idx'] < 0 or coord['mp_idx'] >= self.mp_degree or \ + coord['sharding_idx'] < 0 or coord['sharding_idx'] >= self.sharding_degree or \ + coord['pp_idx'] < 0 or coord['pp_idx'] >= self.pp_degree or \ + coord['dp_idx'] < 0 or coord['dp_idx'] >= self.dp_degree + + def coord_to_rank(self, coord): + """ + Map the input coord to it's corresponding rank. + :param coord: The coord to be converted + :return: The rank corresponding with the coord + """ + if self._invalide_coord(coord): + return -1 + return int(coord['dp_idx'] * self.pp_degree * self.sharding_degree * self.mp_degree + \ + coord['pp_idx'] * self.sharding_degree * self.mp_degree + \ + coord['sharding_idx'] * self.mp_degree + coord['mp_idx']) + + def rank_to_coord(self, rank): + """ + Map the input rank to it's corresponding coord + :param rank: The rank to be converted + :return: The coord corresponding with the rank + """ + mp_idx = rank % self.mp_degree + rank //= self.mp_degree + sharding_idx = rank % self.sharding_degree + rank //= self.sharding_degree + pp_idx = rank % self.pp_degree + rank //= self.pp_degree + dp_idx = rank % self.dp_degree + return { + 'mp_idx': int(mp_idx), + 'sharding_idx': int(sharding_idx), + 'pp_idx': int(pp_idx), + 'dp_idx': int(dp_idx) + } + + +class FleetExecutorUtils: + + def __init__(self, + dist_strategy=None, + rank=None, + nrank=None, + max_run_times=None): + self.dist_strategy = dist_strategy + self.rank = rank + self.nrank = nrank + self.max_run_times = max_run_times + self.is_auto_parallel = True if dist_strategy is None else False + self.num_of_functionality = 4 + self.coord_sys = None + self.coord = None + if dist_strategy: + self.coord_sys = CoordSys(dist_strategy) + self.coord = self.coord_sys.rank_to_coord(rank) + + def is_optimizer_op(self, op_role): + return op_role == int(OpRole.Optimize) + + def is_lr_sched_op(self, op_role): + return op_role == int(OpRole.Optimize.LRSched) + + def is_forward_op(self, op_role): + return (op_role == int(OpRole.Forward)) or \ + (op_role == (int(OpRole.Forward) | int(OpRole.Loss))) + + def is_backward_op(self, op_role): + return (op_role == int(OpRole.Backward)) or \ + (op_role == (int(OpRole.Backward) | int(OpRole.Loss))) + + def split_program_to_op_list(self, program): + op_list_map = {"lr": [], "fwd": [], "bwd": [], "opt": []} + for op in program.block(0).ops: + # split the program based on the op_role + op_role = int(op.all_attrs()[OP_ROLE_KEY]) + if self.is_lr_sched_op(op_role): + op_list_map["lr"].append(op) + elif self.is_forward_op(op_role): + op_list_map["fwd"].append(op) + elif self.is_backward_op(op_role): + op_list_map["bwd"].append(op) + elif self.is_optimizer_op(op_role): + op_list_map["opt"].append(op) + else: + raise "The op role: " + str( + op_role + ) + " isn't one of LRSched, Forward, Backward or Optimizer." + return op_list_map + + def convert_op_list_to_program(self, op_list, complete_program): + #TODO(liyurui): Complete this convert logic + program_map = { + "lr": Program(), + "fwd": Program(), + "bwd": Program(), + "opt": Program() + } + return program_map + + def build_1f1b_dependency(self, task_node_map): + assert not self.is_auto_parallel, "Handly add dependency should not be invoked in auto parallel mode" + # Generated the dependency based on this graph: + # lr(1:m) -> forward -> backward -> (m:1)optimize + # ↑ ↓ + # lr(1:m) -> forward -> backward -> (m:1)optimize + # ↑ ↓ + # lr(1:m) -> forward -> backward -> (m:1)optimize + + # add dependency intra stage + cur_start_id = self.rank * self.num_of_functionality + pp_buff_size = int(self.dist_strategy['pp_degree'] - + self.coord['pp_idx']) + task_node_map["lr"].add_downstream_task(cur_start_id + 1) + task_node_map["fwd"].add_upstream_task(cur_start_id) + task_node_map["fwd"].add_downstream_task(cur_start_id + 2, pp_buff_size) + task_node_map["bwd"].add_upstream_task(cur_start_id + 1, pp_buff_size) + task_node_map["bwd"].add_downstream_task(cur_start_id + 3) + task_node_map["opt"].add_upstream_task(cur_start_id + 2) + # add dependency inter stage + upstream_coord, downstream_coord = self.coord.copy(), self.coord.copy() + upstream_coord['pp_idx'] = upstream_coord['pp_idx'] - 1 + downstream_coord['pp_idx'] = downstream_coord['pp_idx'] + 1 + pp_upstream = self.coord_sys.coord_to_rank(upstream_coord) + pp_downstream = self.coord_sys.coord_to_rank(downstream_coord) + first_stage = (pp_upstream == -1) + last_stage = (pp_downstream == -1) + prev_pp_start_id = pp_upstream * self.num_of_functionality + next_pp_start_id = pp_downstream * self.num_of_functionality + if not first_stage: + task_node_map["fwd"].add_upstream_task(prev_pp_start_id + 1) + task_node_map["bwd"].add_downstream_task(prev_pp_start_id + 2) + if not last_stage: + task_node_map["fwd"].add_downstream_task(next_pp_start_id + 1) + task_node_map["bwd"].add_upstream_task(next_pp_start_id + 2) + return task_node_map + + def construct_task_nodes_1f1b(self, program_map): + max_slot_times = int(self.max_run_times - self.coord['pp_idx']) + cur_start_id = int(self.rank * self.num_of_functionality) + lr_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + program=program_map["lr"], + task_id=cur_start_id) + fwd_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + program=program_map["fwd"], + task_id=cur_start_id + 1) + bwd_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + program=program_map["bwd"], + task_id=cur_start_id + 2) + opt_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + program=program_map["opt"], + task_id=cur_start_id + 3) + return { + "lr": lr_task_node, + "fwd": fwd_task_node, + "bwd": bwd_task_node, + "opt": opt_task_node + } + + def task_id_to_rank(self): + task_id_to_rank = {} + for i in range(self.nrank): + for j in range(self.num_of_functionality): + task_id_to_rank[int(i * self.num_of_functionality + j)] = i + return task_id_to_rank + + def construct_task_nodes_1f1b_op_list(self, op_list_map): + max_slot_times = int(self.max_run_times - self.coord['pp_idx']) + cur_start_id = int(self.rank * self.num_of_functionality) + lr_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + role=int(OpRole.Optimize.LRSched), + ops=op_list_map["lr"], + task_id=cur_start_id, + node_type="Amplifier") + lr_task_node.set_run_pre_steps(self.max_run_times) + fwd_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + role=int(OpRole.Forward), + ops=op_list_map["fwd"], + task_id=cur_start_id + 1, + node_type="Compute") + bwd_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + role=int(OpRole.Backward), + ops=op_list_map["bwd"], + task_id=cur_start_id + 2, + node_type="Compute") + opt_task_node = TaskNode(rank=self.rank, + max_run_times=self.max_run_times, + max_slot_times=max_slot_times, + role=int(OpRole.Optimize), + ops=op_list_map["opt"], + task_id=cur_start_id + 3, + node_type="Amplifier") + opt_task_node.set_run_pre_steps(self.max_run_times) + opt_task_node.set_run_at_offset(self.max_run_times - 1) + return { + "lr": lr_task_node, + "fwd": fwd_task_node, + "bwd": bwd_task_node, + "opt": opt_task_node + } + + +def run1f1b(program, + rank, + max_run_times, + dist_opt, + nrank, + with_standalone_executor=False): + """ + Split the program to support 1f1b pipeline scheduler. + This funct will split the program based on the op_role. + The program will be split into four parts: lr_sched, fwd, bwd, opt. + And will create task nodes based on the four parts of the program. + :param program: The origin program. + :param rank: Current rank (can be got from fleet.worker_index()). + :param max_run_times: Max run times for a micro batch. AKA number of micro steps. + :param dist_opt: The fleet_opt configured by user. + :param nrank: Number of workers (can be got from fleet.worker_num()). + :param with_standalone_executor: Experiment feature, use fleet executor with standalone executor. + :return: + task_nodes (list): four task nodes for current rank + task_id_to_rank (dict): task nodes' ids to it's corresponding rank + """ + print("fleet executor will use python side 1f1b scheduler.") + fleet_executor_utils = FleetExecutorUtils(dist_strategy=dist_opt, + rank=rank, + nrank=nrank, + max_run_times=max_run_times) + op_list_map = fleet_executor_utils.split_program_to_op_list(program) + task_node_map = None + if with_standalone_executor: + program_map = fleet_executor_utils.convert_op_list_to_program( + op_list_map, program) + task_node_map = fleet_executor_utils.construct_task_nodes_1f1b( + program_map) + else: + op_desc_list_map = {"lr": [], "fwd": [], "bwd": [], "opt": []} + for key in op_list_map: + for op in op_list_map[key]: + op_desc_list_map[key].append(op.desc) + task_node_map = fleet_executor_utils.construct_task_nodes_1f1b_op_list( + op_desc_list_map) + task_node_map = fleet_executor_utils.build_1f1b_dependency(task_node_map) + task_id_to_rank = fleet_executor_utils.task_id_to_rank() + task_node_list = [task_node_map[key].task_node() for key in task_node_map] + return task_node_list, task_id_to_rank + + +def origin(program, rank): + """ + Origin scheduler for fleet executor, supports non-pp mode + :param program: The origin program. + :param rank: Current rank (can be got from fleet.worker_index()). + :return: + task_nodes (list): four task nodes for current rank + task_id_to_rank (dict): a fake dict, since there is no upstream or downstream, this dict won't be used + """ + print("fleet executor will use python side origin scheduler.") + task_node = TaskNode(program=program, + rank=rank, + node_type="Compute", + max_run_times=1, + max_slot_times=1) + task_id_to_rank = {task_node.task_id(): rank} + return [task_node.task_node()], task_id_to_rank diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..158938b76d034822bb762ab97c875042a717629b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch.py @@ -0,0 +1,749 @@ +# 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. +r""" +fleetrun is a module that spawns multiple distributed +process on each training node for gpu training and cpu training. +Usage: + In both of single node training or multiple node training, this module +launch a process on each of the given gpu card or cpu machine. + GPU training: + 1. for single node training with all visible gpu cards: + fleetrun your_training_py (arg1 arg2 and all others) + 2. for single node training with [0,4) cards + fleetrun --gpus="0,1,2,3" your_training_py (arg1 arg2 and all others) + 3. for multiple node training such as two node:192.168.0.16, 192.168.0.17 + on 192.168.0.16: + fleetrun --ips="192.168.0.16,192.168.0.17" \ + your_training_py (arg1 arg2 and all others) + on 192.168.0.17: + fleetrun --ips="192.168.0.16,192.168.0.17" \ + your_training_py (arg1 arg2 and all others) + CPU training: + 1. for single node training with multi servers and workers: + fleetrun --server_num=2 --worker_num=2 your_training_py (arg1 arg2 and all others) + 2. for multiple node training such as two node:192.168.0.16, 192.168.0.17 \ + with 2 servers and 4 workers. + on 192.168.0.16: + fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \ + --workers="192.168.0.16,192.168.0.17,192.168.0.16,192.168.0.17" \ + your_training_py (arg1 arg2 and all others) + on 192.168.0.17: + fleetrun --servers="192.168.0.16:6170,192.168.0.17:6171" \ + --workers="192.168.0.16,192.168.0.17,192.168.0.16,192.168.0.17" \ + your_training_py (arg1 arg2 and all others) + 3. use gloo backend for multiple node training such as two node:192.168.0.16, 192.168.0.17 \ + with 2 servers and 4 workers. (workers should set port) + on 192.168.0.16: + fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \ + --workers="192.168.0.16:6171,192.168.0.17:6171,192.168.0.16:6172,192.168.0.17:6172" \ + your_training_py (arg1 arg2 and all others) + on 192.168.0.17: + fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \ + --workers="192.168.0.16:6171,192.168.0.17:6171,192.168.0.16:6172,192.168.0.17:6172" \ + your_training_py (arg1 arg2 and all others) +""" + +from __future__ import print_function + +import shutil +import sys +import tempfile +from sys import version +import subprocess +import os +import time +import six +import copy +import pathlib +import argparse +from argparse import ArgumentParser, REMAINDER +import paddle +import paddle.fluid as fluid +from paddle.distributed.fleet import launch_utils + +# TODO(danleifeng): Don't import * from a module +from paddle.distributed.fleet.launch_utils import * +from paddle.distributed.fleet import cloud_utils +from paddle.distributed.fleet import ascend_utils + +from paddle.distributed.fleet.elastic import enable_elastic, launch_elastic + +__all__ = [] + + +def _print_arguments(args): + print("----------- Configuration Arguments -----------") + for arg, value in sorted(six.iteritems(vars(args))): + print("%s: %s" % (arg, value)) + print("------------------------------------------------") + + +def _parse_args(): + """ + Helper function parsing the command line options + @retval ArgumentParser + """ + parser = ArgumentParser( + description='''start paddle training using multi-process mode. +see: http://www.paddlepaddle.org/documentation/docs/zh/1.6/user_guides/howto/training/cluster_howto.html#permalink-8--nccl2- +''') + base_group = parser.add_argument_group("Base Parameters") + + base_group.add_argument( + "--log_dir", + type=str, + default="log", + help="The path for each process's log. Default --log_dir=log/") + base_group.add_argument( + "--backend", + type=str, + default=os.environ.get('PADDLE_DISTRI_BACKEND', 'auto'), + help="Specifize the backend, can be gloo|nccl|bkcl|auto|hccl|heter. " + "Default value is auto which perfers nccl or bkcl.") + base_group.add_argument( + "--nproc_per_node", + type=int, + default=None, + help="The number of processes to launch on a node." + "In gpu training, it should be less or equal to the gpus number of you system(or you set by --gpus). And so each process can" + " bound to one or average number of gpus.") + + base_group.add_argument( + "--run_mode", + type=str, + default=None, + help="run mode of job, can be:collective/ps/ps-heter") + + if fluid.core.is_compiled_with_cuda(): + base_group.add_argument( + "--gpus", + type=str, + default=None, + help="It's for gpu training." + "For example:" + "--gpus=\"0,1,2,3\" will launch four training processes each bound to one gpu." + ) + base_group.add_argument("--selected_gpus", dest="gpus") + + if fluid.core.is_compiled_with_xpu(): + base_group.add_argument( + "--xpus", + type=str, + default=None, + help="It's for xpu training. For example: " + "--xpus=\"0,1,2,3\" will launch four training processes each bound to one xpu." + ) + base_group.add_argument("--selected_xpus", dest="xpus") + + if fluid.core.is_compiled_with_npu(): + base_group.add_argument( + "--npus", + type=str, + default=None, + help="It's for xpu training. For example: " + "--npus=\"0,1,2,3\" will launch four training processes each bound to one npu." + ) + base_group.add_argument("--selected_npus", dest="npus") + + if fluid.core.is_compiled_with_mlu(): + base_group.add_argument( + "--mlus", + type=str, + default=None, + help="It's for mlu training. For example: " + "--mlus=\"0,1,2,3\" will launch four training processes each bound to one mlu." + ) + base_group.add_argument("--selected_mlus", dest="mlus") + + base_group.add_argument("training_script", + type=str, + help="The full path to the single GPU training " + "program/script to be launched in parallel, " + "followed by all the arguments for the " + "training script") + + base_group.add_argument('training_script_args', nargs=REMAINDER) + + # Optional arguments for the launch helper + # for collective + collective_group = parser.add_argument_group("Collective Parameters") + collective_group.add_argument( + "--ips", + type=str, + default="127.0.0.1", + help="Paddle cluster nodes ips, such as 192.168.0.16,192.168.0.17..") + collective_group.add_argument( + "--cluster_topo_path", + type=str, + default=None, + help="A json format file will be stored in this path which is used" + "to represent the cluster topology information for auto parallel.") + collective_group.add_argument( + "--rank_mapping_path", + type=str, + default=None, + help="A json format file will be stored in this path which is used" + "to map processes to machines for auto parallel.") + collective_group.add_argument( + "--enable_auto_mapping", + type=bool, + default=False, + help="Set true to enable the lazy launch for auto-parallel scenario.") + + ps_group = parser.add_argument_group("Parameter-Server Parameters") + # for parameter server + ps_group.add_argument("--servers", + type=str, + default="", + help="User defined servers ip:port") + ps_group.add_argument("--workers", + type=str, + default="", + help="User defined workers ip:port") + ps_group.add_argument("--coordinators", + type=str, + default="", + help="User defined coordinators ip:port") + ps_group.add_argument( + "--heter_workers", + type=str, + default="", + help="User defined heter workers in each stage ip1:port1;ip2:port2") + ps_group.add_argument( + "--heter_devices", + type=str, + default="", + help="User defined heter devices in each stage cpu;gpu;cpu") + + ps_group.add_argument("--worker_num", type=int, help="number of workers") + ps_group.add_argument("--coordinator_num", + type=int, + help="number of coordinators") + ps_group.add_argument("--server_num", type=int, help="number of servers") + ps_group.add_argument("--heter_worker_num", + type=str, + help="number of heter_workers in each stage 1;2;3") + ps_group.add_argument("--http_port", type=int, help="Gloo http Port") + + # parameter elastic mode + elastic_group = parser.add_argument_group("Elastic Parameters") + elastic_group.add_argument("--elastic_server", + type=str, + help="etcd server host:port") + elastic_group.add_argument("--elastic_pre_hook", + type=str, + help="elastic pre_hook shell cmd") + + elastic_group.add_argument("--job_id", type=str, help="job unique id") + elastic_group.add_argument("--np", type=int, help="job pod/node number") + elastic_group.add_argument("--scale", type=int, default=0, help="scale np") + elastic_group.add_argument("--host", + type=str, + help="bind host, default to POD_IP env") + elastic_group.add_argument("--force", + type=bool, + default=False, + help="update np force") + + known_args, _ = parser.parse_known_args() + return known_args + + +def get_cluster_from_args(args, device_mode, devices_per_proc): + node_ips = [x.strip() for x in args.ips.split(',')] + if len(node_ips) == 1: + node_ip = node_ips[0] + else: + if args.host: + node_ip = args.host + else: + _, node_ip = get_host_name_ip() + + assert node_ip in node_ips, "Can't find your local ip {%s} in node_ips: {%s}" \ + % (node_ip, node_ips) + node_rank = node_ips.index(node_ip) + + logger.debug("parsed from args: node_ips:{} node_ip:{} node_rank:{}".format( + node_ips, node_ip, node_rank)) + + free_ports = None + if not cloud_utils.use_paddlecloud() and len( + node_ips) <= 1 and os.environ.get('FLAGS_START_PORT') is None: + free_ports = find_free_ports(len(devices_per_proc)) + if free_ports is not None: + free_ports = list(free_ports) + logger.info("find free ports:{}".format(free_ports)) + else: + start_port = 6070 + if os.environ.get('FLAGS_START_PORT') is not None: + start_port = int(os.environ.get('FLAGS_START_PORT')) + + free_ports = [ + x for x in range(start_port, start_port + len(devices_per_proc)) + ] + + trainer_endpoints = [] + for ip in node_ips: + trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports]) + return get_cluster(node_ips, node_ip, trainer_endpoints, device_mode, + devices_per_proc) + + +def cpuonly_check(args): + if args.ips and len(args.ips.split(',')) > 1: + raise RuntimeError( + "CPUONLY launch only support single trainer, that is len(ips)=1, but got %s." + % args.ips) + if args.run_mode: + assert args.run_mode == 'cpuonly', "CPUONLY launch only support run mode is CPUONLY" + if args.servers: + raise RuntimeError("CPUONLY launch can't have --servers as arguments.") + return True + + +def get_cluster_info(args): + # parse arguments, used for cloud-single-machine and local + if args.backend == 'gloo': cpuonly_check(args) + if args.enable_auto_mapping: + (device_mode, devices_per_proc) = (DeviceMode.GPU, []) + else: + (device_mode, + devices_per_proc) = launch_utils.get_device_proc_info(args) + trainers_num = cloud_utils.get_trainers_num() + logger.debug("parsed from args trainerss_num:{} mode:{} devices:{}".format( + trainers_num, device_mode, devices_per_proc)) + + cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + + cluster = None + pod = None + + start_port = 6170 + if os.environ.get('FLAGS_START_PORT') is not None: + start_port = os.environ.get('FLAGS_START_PORT') + # auto mapping between processes and devices for auto-parallel + if args.enable_auto_mapping == True: + assert args.cluster_topo_path is not None, \ + "The cluster topology must be provied when enabling auto mapping." + rank_mapping_path = args.rank_mapping_path or os.getenv( + "PADDLE_RANK_MAPPING_PATH") + if not rank_mapping_path: + os.environ["PADDLE_NEED_RANK_MAPPING"] = str(True) + os.environ["PADDLE_ENABLE_ELASTIC"] = str( + enable_elastic(args, device_mode)) + cwd = pathlib.Path().resolve() + rank_mapping_path = os.path.join(cwd, + "auto_parallel_rank_mapping.json") + os.environ["PADDLE_RANK_MAPPING_PATH"] = str(rank_mapping_path) + + original_args = sys.argv[1:] + os.environ["PADDLE_ORIGINAL_CMD_ARGS"] = " ".join(original_args) + os.environ["PADDLE_CLUSTER_TOPO_PATH"] = str(args.cluster_topo_path) + os.environ["PADDLE_ENABLE_AUTO_MAPPING"] = str( + args.enable_auto_mapping) + cluster, pod = launch_utils.get_mapped_cluster_from_args_without_rank_mapping( + args, device_mode) + else: + os.environ["PADDLE_NEED_RANK_MAPPING"] = str(False) + os.environ["PADDLE_ENABLE_ELASTIC"] = str( + enable_elastic(args, device_mode)) + + os.environ["PADDLE_CLUSTER_TOPO_PATH"] = str(args.cluster_topo_path) + os.environ["PADDLE_RANK_MAPPING_PATH"] = str(rank_mapping_path) + os.environ["PADDLE_ENABLE_AUTO_MAPPING"] = str( + args.enable_auto_mapping) + cluster, pod = launch_utils.get_mapped_cluster_from_args_with_rank_mapping( + args, device_mode) + elif cloud_utils.use_paddlecloud() and trainers_num != 1: + cluster, pod = cloud_utils.get_cloud_cluster(args.ips, device_mode, + devices_per_proc, + start_port) + logger.debug("get cluster from cloud:{}".format(cluster)) + elif device_mode == DeviceMode.ASCEND_NPU: + # for ascend + cluster, pod = ascend_utils.get_cloud_cluster(rank_table_file=os.getenv( + "RANK_TABLE_FILE", None), + device_mode=device_mode, + start_port=start_port) + else: + # trainers_num = 1 or not use paddlecloud ips="a,b" + cluster, pod = get_cluster_from_args(args, device_mode, + devices_per_proc) + logger.debug("get cluster from args:{}".format(cluster)) + return cluster, pod + + +def get_global_envs(args, tmp_dir): + global_envs = copy.copy(os.environ.copy()) + # add gloo env + global_envs["PADDLE_WITH_GLOO"] = str(os.getenv("PADDLE_WITH_GLOO", "0")) + global_envs["PADDLE_GLOO_RENDEZVOUS"] = "3" + global_envs["PADDLE_GLOO_FS_PATH"] = tmp_dir + global_envs["PADDLE_DISTRI_BACKEND"] = args.backend + return global_envs + + +def launch_collective(args): + tmp_dir = tempfile.mkdtemp() + cluster, pod = get_cluster_info(args) + global_envs = get_global_envs(args, tmp_dir) + + procs = start_local_trainers(cluster, + pod, + training_script=args.training_script, + training_script_args=args.training_script_args, + log_dir=args.log_dir, + envs=global_envs) + + for idx, proc in enumerate(procs): + print("launch proc_id:{} idx:{}".format(proc.proc.pid, idx)) + + while True: + try: + alive = watch_local_trainers(procs, cluster.trainers_nranks()) + + if not alive: + logger.info("Local processes completed.") + logger.debug("POD info:{}".format(pod)) + break + + time.sleep(3) + + except: + logger.warning("Terminating... exit") + terminate_local_procs(procs) + exit(1) + + if os.path.exists(tmp_dir): + shutil.rmtree(tmp_dir) + + +def launch_ps(args, distribute_mode): + cloud_flag = cloud_utils.use_paddlecloud() + + # for ps-cpu on paddlecloud + if cloud_flag and distribute_mode == DistributeMode.PS: + direct_start(args) + return + #elif cloud_flag and distribute_mode == DistributeMode.PS_HETER: + # cloud_ps_heter_env_set(args) + # args.workers = os.getenv("PADDLE_TRAINER_ENDPOINTS") + # args.servers = os.getenv("PADDLE_PSERVERS_IP_PORT_LIST") + # args.heter_workers = os.getenv("PADDLE_HETER_TRAINER_IP_PORT_LIST") + + ps_launcher = ParameterServerLauncher(args, distribute_mode) + ps_launcher.start_ps() + return + + +def infer_backend(args): + if args.backend != "auto": return + if fluid.core.is_compiled_with_cuda(): + args.backend = 'nccl' + elif fluid.core.is_compiled_with_npu(): + args.backend = 'unknown' + elif fluid.core.is_compiled_with_xpu(): + args.backend = 'bkcl' + elif fluid.core.is_compiled_with_mlu(): + args.backend = 'cncl' + else: + args.backend = 'gloo' + + +def which_distributed_mode(args): + infer_backend(args) # modify the args.backend + if args.run_mode is not None: + assert args.run_mode in ["collective", "ps", "ps-heter"] + + if args.run_mode == "collective": + return DistributeMode.COLLECTIVE + elif args.run_mode == "ps": + return DistributeMode.PS + elif args.run_mode == "ps-heter": + return DistributeMode.PS_HETER + + ps_args = [ + '--worker_num', '--server_num', '--heter_worker_num', '--servers', + '--workers', '--heter_workers', '--heter_devices', '--http_port' + ] + collective_args = ['--ips'] + + ps_heter_args = ["--heter_worker_num", "--heter_workers", "--heter_devices"] + + coordinator_args = ["--coordinator_num", "--coordinators"] + + has_ps_args = [ + ps_arg for ps_arg in ps_args if ps_arg in " ".join(sys.argv[1:-1]) + ] + has_collective_args = [ + co_arg for co_arg in collective_args + if co_arg in " ".join(sys.argv[1:-1]) + ] + + if len(has_ps_args) > 1 and len(has_collective_args) > 1: + raise ValueError( + "Only one mode(Collective or Parameter-Server) can be selected at the same time, but more than one configuration was received." + ) + + if fluid.core.is_compiled_with_cuda(): + accelerators = fluid.core.get_cuda_device_count() + elif fluid.core.is_compiled_with_npu(): + accelerators = fluid.core.get_npu_device_count() + elif fluid.core.is_compiled_with_xpu(): + accelerators = fluid.core.get_xpu_device_count() + elif fluid.core.is_compiled_with_mlu(): + accelerators = fluid.core.get_mlu_device_count() + else: + accelerators = 0 + + if len(has_ps_args) > 0: + logger.info( + "Run parameter-sever mode. pserver arguments:{}, accelerators count:{}" + .format(has_ps_args, accelerators)) + has_ps_heter_args = list(set(has_ps_args) & set(ps_heter_args)) + has_coordinator_args = list(set(has_ps_args) & set(coordinator_args)) + if len(has_ps_heter_args) > 0: + return DistributeMode.PS_HETER + else: + return DistributeMode.PS + elif len(has_collective_args) > 0: + logger.info( + "Run collective mode. gpu arguments:{}, cuda count:{}".format( + has_collective_args, accelerators)) + return DistributeMode.COLLECTIVE + else: + if not fluid.core.is_compiled_with_cuda( + ) and not fluid.core.is_compiled_with_xpu( + ) and not fluid.core.is_compiled_with_mlu(): + if args.servers: + logger.warning( + "Not found distinct arguments and not compiled with cuda or xpu or npu or mlu. " + "But found args.servers not empty, default use ps mode") + return DistributeMode.PS + else: + return DistributeMode.COLLECTIVE + else: + logger.warning( + "Not found distinct arguments and compiled with cuda or xpu or npu or mlu. " + "Default use collective mode") + return DistributeMode.COLLECTIVE + + +def launch(): + """ + Paddle distribution training entry ``python -m paddle.distributed.launch``. + + Usage: + .. code-block:: bash + :name: code-block-bash1 + + python -m paddle.distributed.launch [-h] [--log_dir LOG_DIR] [--nproc_per_node NPROC_PER_NODE] [--run_mode RUN_MODE] [--gpus GPUS] + [--selected_gpus GPUS] [--ips IPS] [--servers SERVERS] [--workers WORKERS] [--heter_workers HETER_WORKERS] + [--worker_num WORKER_NUM] [--server_num SERVER_NUM] [--heter_worker_num HETER_WORKER_NUM] + [--http_port HTTP_PORT] [--elastic_server ELASTIC_SERVER] [--job_id JOB_ID] [--np NP] [--scale SCALE] + [--host HOST] [--force FORCE] + training_script ... + + + Base Parameters: + - ``--log_dir``: The path for each process's log. e.g., ``--log_dir=output_dir``. Default ``--log_dir=log``. + + - ``--nproc_per_node``: The number of processes to launch on a node. In gpu training, it should be less or equal to the gpus number of you system(or you set by --gpus). e.g., ``--nproc_per_node=8`` + + - ``--run_mode``: run mode of job, can be:collective/ps/ps-heter. e.g., ``--run_mode=ps``. Default ``--run_mode=collective``. + + - ``--gpus``: It's for gpu training. e.g., ``--gpus=0,1,2,3`` will launch four training processes each bound to one gpu. + + - ``--selected_gpus``: gpus aliases, recommend to use ``--gpus``. + + - ``--xpus``: It's for xpu training if xpu is available. e.g., ``--xpus=0,1,2,3``. + + - ``--selected_xpus``: xpus aliases, recommend to use ``--xpus``. + + - ``--mlus``: It's for mlu training. e.g., ``--mlus=0,1,2,3`` will launch four training processes each bound to one mlu. + + - ``--selected_mlus``: mlus aliases, recommend to use ``--mlus``. + + - ``training_script``: The full path to the single GPU training program/script to be launched in parallel, followed by all the arguments for the training script. e.g., ``training.py`` + + - ``training_script_args``: The args of training_script. e.g., ``--lr=0.1`` + + Collective Parameters: + - ``--ips``: Paddle cluster nodes ips, e.g., ``--ips=192.168.0.16,192.168.0.17``. Default ``--ips=127.0.0.1``. + + Parameter-Server Parameters: + - ``--servers``: User defined servers ip:port, e.g., ``--servers="192.168.0.16:6170,192.168.0.17:6170"`` + + - ``--workers``: User defined workers ip:port, e.g., ``--workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172"`` + + - ``--heter_workers``: User defined heter workers ip1:port1;ip2:port2, e.g., ``--heter_workers="192.168.0.16:6172;192.168.0.17:6172"`` + + - ``--worker_num``: Number of workers (It recommend to set when in the emulated distributed environment using single node) + + - ``--server_num``: Number of servers (It recommend to set when in the emulated distributed environment using single node) + + - ``--heter_worker_num``: Number of heter_workers in each stage (It recommend to set when in the emulated distributed environment using single node) + + - ``--heter_devices``: Type of heter_device in each stage + + - ``--http_port``: Gloo http Port + + Elastic Parameters: + - ``--elastic_server``: etcd server host:port, e.g., ``--elastic_server=127.0.0.1:2379`` + + - ``--job_id``: job unique id, e.g., ``--job_id=job1`` + + - ``--np``: job pod/node number, e.g., ``--np=2`` + + - ``--host``: bind host, default to POD_IP env. + + + Returns: + ``None`` + + Examples 1 (collective, single node): + .. code-block:: bash + :name: code-block-example-bash1 + + # For training on single node using 4 gpus. + + python -m paddle.distributed.launch --gpus=0,1,2,3 train.py --lr=0.01 + + Examples 2 (collective, multi node): + .. code-block:: bash + :name: code-block-example-bash2 + + # The parameters of --gpus and --ips must be consistent in each node. + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 + + # On 192.168.0.16: + + python -m paddle.distributed.launch --gpus=0,1,2,3 --ips=192.168.0.16,192.168.0.17 train.py --lr=0.01 + + # On 192.168.0.17: + python -m paddle.distributed.launch --gpus=0,1,2,3 --ips=192.168.0.16,192.168.0.17 train.py --lr=0.01 + + Examples 3 (ps, cpu, single node): + .. code-block:: bash + :name: code-block-example-bash3 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers. + + python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01 + + Examples 4 (ps, cpu, multi node): + .. code-block:: bash + :name: code-block-example-bash4 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers. + + # On 192.168.0.16: + + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + Examples 5 (ps, gpu, single node): + .. code-block:: bash + :name: code-block-example-bash5 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, each worker use single gpu. + + export CUDA_VISIBLE_DEVICES=0,1,2,3 + python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01 + + Examples 6 (ps, gpu, multi node): + .. code-block:: bash + :name: code-block-example-bash6 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers. + + # On 192.168.0.16: + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + Examples 7 (ps-heter, cpu + gpu, single node): + .. code-block:: bash + :name: code-block-example-bash7 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, two workers use gpu, two workers use cpu. + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --server_num=2 --worker_num=2 --heter_worker_num=2 train.py --lr=0.01 + + Examples 8 (ps-heter, cpu + gpu, multi node): + .. code-block:: bash + :name: code-block-example-bash8 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server, 1 gpu worker, 1 cpu worker. + + # On 192.168.0.16: + + export CUDA_VISIBLE_DEVICES=0 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + export CUDA_VISIBLE_DEVICES=0 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01 + + Examples 9 (elastic): + .. code-block:: bash + :name: code-block-example-bash9 + + python -m paddle.distributed.launch --elastic_server=127.0.0.1:2379 --np=2 --job_id=job1 --gpus=0,1,2,3 train.py + + """ + + args = _parse_args() + logger = get_logger() + _print_arguments(args) + + if args.backend == 'auto': + distribute_mode = which_distributed_mode( + args) # which_distributed_mode must modify args.backend + else: + assert args.run_mode == 'collective' or args.run_mode == None, "When backend is not 'auto', run mode must be collective" + check_backend(args.backend) + distribute_mode = DistributeMode.COLLECTIVE + + #assert args.backend in ['gloo', 'nccl', 'bkcl', 'cncl', 'heter', 'unknown'] + + if args.backend == 'gloo': + logger.warning("launch start with CPUONLY mode") + + block_windows_and_macos( + args.backend) # raise error when using gloo on windows or macos + + if enable_elastic(args, distribute_mode): + launch_elastic(args, distribute_mode) + return + + if distribute_mode == DistributeMode.COLLECTIVE: + launch_collective(args) + else: + launch_ps(args, distribute_mode) + + +if __name__ == "__main__": + launch() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..633a65386c485265a35cec89b5ef5bbcd5a9870b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/launch_utils.py @@ -0,0 +1,2027 @@ +# 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. + +import logging +import time +import os +import signal +import copy +import sys +import subprocess +import tempfile +import shutil +from contextlib import closing +import multiprocessing +import socket +import warnings +import six +import struct +import json + +import paddle +import paddle.fluid as fluid +from distutils.util import strtobool +import paddle.utils.cpp_extension.extension_utils as utils + +logger = logging.getLogger("root") +logger.propagate = False + + +class DistributeMode(): + """ + There are various mode for fleetrun, each of them is designed for different model. + """ + COLLECTIVE = 0 + PS = 1 + PS_HETER = 2 + + +class DeviceMode(): + """ + Training devices type + """ + UNKNOWN = -1 + CPU = 0 + GPU = 1 + KUNLUN = 2 + XPU = 2 + ASCEND_NPU = 3 + UNKNOWN = 3 + MLU = 4 + + +class Cluster(object): + + def __init__(self, hdfs): + self.job_server = None + self.pods = [] + self.hdfs = None + self.job_stage_flag = None + + def __str__(self): + return "job_server:{} pods:{} job_stage_flag:{} hdfs:{}".format( + self.job_server, [str(pod) for pod in self.pods], + self.job_stage_flag, self.hdfs) + + def __eq__(self, cluster): + if len(self.pods) != len(cluster.pods): + return False + + for a, b in zip(self.pods, cluster.pods): + if a != b: + return False + + if self.job_stage_flag != cluster.job_stage_flag: + return False + + return True + + def __ne__(self, cluster): + return not self.__eq__(cluster) + + def update_pods(self, cluster): + self.pods = copy.copy(cluster.pods) + + def trainers_nranks(self): + return len(self.trainers_endpoints()) + + def pods_nranks(self): + return len(self.pods) + + def trainers_endpoints(self): + r = [] + for pod in self.pods: + for t in pod.trainers: + r.append(t.endpoint) + return r + + def world_device_ids(self): + r = [] + for pod in self.pods: + for t in pod.trainers: + str_accelerators = [str(acc) for acc in t.accelerators] + r.append(str_accelerators) + return r + + def pods_endpoints(self): + r = [] + for pod in self.pods: + ep = "{}:{}".format(pod.addr, pod.port) + assert pod.port != None and pod.addr != None, "{} not a valid endpoint".format( + ep) + r.append(ep) + return r + + def get_pod_by_id(self, pod_id): + for pod in self.pods: + if str(pod_id) == str(pod.id): + return pod + + return None + + +class JobServer(object): + + def __init__(self): + self.endpoint = None + + def __str__(self): + return "{}".format(self.endpoint) + + def __eq__(self, j): + return self.endpint == j.endpoint + + def __ne__(self, j): + return not self == j + + +class Trainer(object): + + def __init__(self): + self.accelerators = [] + self.endpoint = None + self.rank = None + self.stage = None + + def __str__(self): + return "accelerator:{} endpoint:{} rank:{}".format( + self.accelerators, self.endpoint, self.rank) + + def __eq__(self, t): + if len(self.accelerators) != len(t.accelerators): + return False + + if self.endpoint != t.endpoint or \ + self.rank != t.rank: + return False + + for a, b in zip(self.accelerators, t.accelerators): + if a != b: + return False + + return True + + def __ne__(self, t): + return not self == t + + def rank(self): + return self.rank + + +class Pod(object): + + def __init__(self): + self.rank = None + self.id = None + self.addr = None + self.port = None + self.trainers = [] + self.servers = [] + self.workers = [] + self.coordinators = [] + self.heter_workers = [] + self.accelerators = [] + self.device_mode = None + + def __str__(self): + return "rank:{} id:{} addr:{} port:{} visible_accelerator:{} trainers:{} servers:{} \ + workers:{} heter_workers:{} coordinators:{}".format( + self.rank, self.id, self.addr, self.port, self.accelerators, + [str(t) for t in self.trainers], [str(s) for s in self.servers], + [str(w) + for w in self.workers], [str(h) for h in self.heter_workers], + [str(c) for c in self.coordinators]) + + def __eq__(self, pod): + if self.rank != pod.rank or \ + self.id != pod.id or \ + self.addr != pod.addr or \ + self.port != pod.port: + logger.debug("pod {} != {}".format(self, pod)) + return False + + if len(self.trainers) != len(pod.trainers): + logger.debug("trainers {} != {}".format(self.trainers, + pod.trainers)) + return False + + for i in range(len(self.trainers)): + if self.trainers[i] != pod.trainers[i]: + logger.debug("trainer {} != {}".format(self.trainers[i], + pod.trainers[i])) + return False + + if len(self.servers) != len(pod.servers): + logger.debug("servers {} != {}".format(self.servers, pod.servers)) + return False + + for i in range(len(self.servers)): + if self.servers[i] != pod.servers[i]: + logger.debug("servers {} != {}".format(self.servers[i], + pod.servers[i])) + return False + + if len(self.workers) != len(pod.workers): + logger.debug("workers {} != {}".format(self.workers, pod.workers)) + return False + + for i in range(len(self.workers)): + if self.workers[i] != pod.workers[i]: + logger.debug("workers {} != {}".format(self.workers[i], + pod.workers[i])) + return False + + return True + + def __ne__(self, pod): + return not self == pod + + def parse_response(self, res_pods): + pass + + def rank(self): + return self.rank + + def get_visible_accelerators(self): + r = "" + for g in self.accelerators: + r += "{},".format(g) + + assert r != "", "this pod {} can't see any accelerators".format(self) + + r = r[:-1] + return r + + +def get_logger(log_level=20, name="root"): + logger = logging.getLogger(name) + logger.setLevel(log_level) + + log_handler = logging.StreamHandler() + log_format = logging.Formatter( + '%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s') + log_handler.setFormatter(log_format) + logger.addHandler(log_handler) + + return logger + + +def get_cluster(node_ips, node_ip, trainer_endpoints, device_mode, + devices_per_proc): + assert type(trainer_endpoints) is list, "trainer_endpoints must be list" + cluster = Cluster(hdfs=None) + trainer_rank = 0 + for node_rank, ip in enumerate(node_ips): + pod = Pod() + pod.rank = node_rank + pod.addr = ip + pod.device_mode = device_mode + + cur_node_endpoints = trainer_endpoints[node_rank] + # when use paddlecloud, endpoints may > devices_per_proc(user_defined) + assert len(cur_node_endpoints) >= len( + devices_per_proc + ), "current trainer_endpoints size should be greater equal than acclerators size." + for i in range(len(devices_per_proc)): + trainer = Trainer() + if device_mode == DeviceMode.GPU or device_mode == DeviceMode.ASCEND_NPU or device_mode == DeviceMode.MLU: + if isinstance(devices_per_proc[i], (list, tuple)): + trainer.accelerators.extend(devices_per_proc[i]) + pod.accelerators.extend(devices_per_proc[i]) + else: + trainer.accelerators.append(devices_per_proc[i]) + pod.accelerators.append(devices_per_proc[i]) + elif device_mode == DeviceMode.XPU: + if isinstance(devices_per_proc[i], (list, tuple)): + trainer.accelerators.extend(devices_per_proc[i]) + else: + trainer.accelerators.append(devices_per_proc[i]) + trainer.endpoint = "%s" % (cur_node_endpoints[i]) + trainer.rank = trainer_rank + trainer_rank += 1 + + pod.trainers.append(trainer) + cluster.pods.append(pod) + + pod_rank = node_ips.index(node_ip) + return cluster, cluster.pods[pod_rank] + + +def terminate_local_procs(procs): + # try to terminate process by group, this happend in multiprocess senario in user process + if os.name != 'nt': + for p in procs: + if p.proc.poll() is None: + os.killpg(os.getpgid(p.proc.pid), signal.SIGTERM) + if p.log_fn: + p.log_fn.close() + logger.info("terminate process group gid:{}".format(p.proc.pid)) + + time.sleep(1) + + for p in procs: + if p.proc.poll() is None: + p.proc.terminate() + if p.log_fn: + p.log_fn.close() + logger.debug("terminate process id:{}".format(p.proc.pid)) + + # wait all process terminiated + time.sleep(3) + for step in range(0, 50): + alive = False + for p in procs: + if p.proc.poll() is None: # not termniate + os.kill(p.proc.pid, signal.SIGKILL) + alive = True + + if not alive: + logger.info("terminate all the procs") + return + + time.sleep(3) + + logger.fatal("can't kill all process and exit") + exit(1) + + +def get_host_name_ip(): + try: + host_name = socket.gethostname() + host_ip = socket.gethostbyname(host_name) + return host_name, host_ip + except: + return None + + +def add_arguments(argname, type, default, help, argparser, **kwargs): + """Add argparse's argument. + Usage: + .. code-block:: python + parser = argparse.ArgumentParser() + add_argument("name", str, "Jonh", "User name.", parser) + args = parser.parse_args() + """ + type = strtobool if type == bool else type + argparser.add_argument("--" + argname, + default=default, + type=type, + help=help + ' Default: %(default)s.', + **kwargs) + + +def find_free_ports(num): + + def __free_port(): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + # Note(wangxi): Close the connection with a TCP RST instead + # of a TCP FIN, to avoid time_wait state. + s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, + struct.pack('ii', 1, 0)) + s.bind(('', 0)) + return s.getsockname()[1] + + port_set = set() + step = 0 + while True: + port = __free_port() + if port not in port_set: + port_set.add(port) + + if len(port_set) >= num: + return port_set + + step += 1 + if step > 400: + print( + "can't find avilable port and use the specified static port now!" + ) + return None + + return None + + +def get_ports(num, offset): + if os.environ.get('FLAGS_START_PORT') is None: + ports = find_free_ports(num) + if ports is not None: + ports = list(ports) + else: + start_port = int(os.environ.get('FLAGS_START_PORT')) + ports = range(start_port + offset, start_port + offset + num, 1) + return ports + + +def pretty_print_envs(envs, header=None): + spacing = 2 + max_k = 40 + max_v = 45 + + for k, v in envs.items(): + max_k = max(max_k, len(k)) + + h_format = " " + "|{{:>{}s}}{}{{:^{}s}}|\n".format( + max_k, " " * spacing, max_v) + l_format = " " + "|{{:>{}s}}{{}}{{:^{}s}}|\n".format(max_k, max_v) + length = max_k + max_v + spacing + + border = " +" + "".join(["="] * length) + "+" + line = " +" + "".join(["-"] * length) + "+" + + draws = "" + draws += border + "\n" + + if header: + draws += h_format.format(header[0], header[1]) + else: + draws += h_format.format("fleetrun Distributed Envs", "Value") + + draws += line + "\n" + + for k, v in envs.items(): + if isinstance(v, str) and len(v) >= max_v: + str_v = "... " + v[-41:] + else: + str_v = v + + draws += l_format.format(k, " " * spacing, str(str_v)) + + draws += border + + _str = "\n{}\n".format(draws) + return _str + + +class TrainerProc(object): + + def __init__(self): + self.proc = None + self.log_fn = None + self.log_offset = None + self.rank = None + self.local_rank = None + self.cmd = None + + +_run_with_coverage = False + + +def run_with_coverage(*args): + global _run_with_coverage + assert len(args) <= 1, "len(args) {} should <= 1".format(len(args)) + if len(args) == 1: + assert isinstance(args[0], bool) + _run_with_coverage = args[0] + return _run_with_coverage + + +def start_local_trainers(cluster, + pod, + training_script, + training_script_args, + log_dir=None, + envs=None): + + if envs is None: + current_env = copy.copy(os.environ.copy()) + else: + current_env = copy.copy(envs) + + # paddle broadcast ncclUniqueId use socket, and + # proxy maybe make trainers unreachable, so delete them. + # if we set them to "", grpc will log error message "bad uri" + # so just delete them. + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + + ids = cluster.world_device_ids() + res = [':'.join(ele) for ele in ids] + procs = [] + for idx, t in enumerate(pod.trainers): + proc_env = { + "PADDLE_TRAINER_ID": + "%d" % t.rank, + "PADDLE_CURRENT_ENDPOINT": + "%s" % t.endpoint, + "PADDLE_TRAINERS_NUM": + "%d" % cluster.trainers_nranks(), + "PADDLE_TRAINER_ENDPOINTS": + ",".join(cluster.trainers_endpoints()), + "PADDLE_RANK_IN_NODE": + str(idx), + "PADDLE_LOCAL_DEVICE_IDS": + ",".join([str(acc) for acc in t.accelerators]), + "PADDLE_WORLD_DEVICE_IDS": + ",".join(res), + } + + # The following three environnement variables are used for auto mapping + if current_env.get("PADDLE_CLUSTER_TOPO_PATH", None) is not None: + proc_env["PADDLE_CLUSTER_TOPO_PATH"] = current_env[ + "PADDLE_CLUSTER_TOPO_PATH"] + if current_env.get("PADDLE_RANK_MAPPING_PATH", None) is not None: + proc_env["PADDLE_RANK_MAPPING_PATH"] = current_env[ + "PADDLE_RANK_MAPPING_PATH"] + if current_env.get("PADDLE_ENABLE_AUTO_MAPPING", None) is not None: + proc_env["PADDLE_ENABLE_AUTO_MAPPING"] = current_env[ + "PADDLE_ENABLE_AUTO_MAPPING"] + + if len(t.accelerators) > 0 and pod.device_mode == DeviceMode.GPU: + proc_env["FLAGS_selected_gpus"] = "%s" % ",".join( + [str(g) for g in t.accelerators]) + + elif len(t.accelerators + ) > 0 and pod.device_mode == DeviceMode.ASCEND_NPU: + proc_env["FLAGS_selected_npus"] = "%s" % ",".join( + [str(g) for g in t.accelerators]) + elif len(t.accelerators) > 0 and pod.device_mode == DeviceMode.MLU: + proc_env["FLAGS_selected_mlus"] = "%s" % ",".join( + [str(g) for g in t.accelerators]) + + if len(t.accelerators) > 0: + proc_env["FLAGS_selected_accelerators"] = "%s" % ",".join( + [str(g) for g in t.accelerators]) + # to do: same code style in future + if fluid.core.is_compiled_with_xpu() and len(t.accelerators) > 0: + proc_env["FLAGS_selected_xpus"] = "%s" % ",".join( + [str(g) for g in t.accelerators]) + + current_env.update(proc_env) + + coverage_args = [] + if run_with_coverage() or os.environ.get("WITH_COVERAGE", + "OFF") == "ON": + coverage_args = ["-m", "coverage", "run", "--branch", "-p"] + cmd = [sys.executable, "-u"] + coverage_args + [training_script + ] + training_script_args + + logger.debug("start trainer proc{} env:{}".format(cmd, current_env)) + + if idx == 0: + logger.info("Local start {} processes. First process distributed " + "environment info (Only For Debug): {}".format( + len(pod.trainers), + pretty_print_envs(proc_env, + ("Distributed Envs", "Value")))) + logger.info( + "details about PADDLE_TRAINER_ENDPOINTS can be found in " + "{}/endpoints.log, and detail running logs maybe found in " + "{}/workerlog.0".format(log_dir, log_dir)) + fn = None + pre_fn = None if os.name == 'nt' else os.setsid + if log_dir is not None: + os.system("mkdir -p {}".format(log_dir)) + if os.path.exists("%s/endpoints.log" % log_dir): + os.system("rm -f {}/endpoints.log".format(log_dir)) + with open("%s/endpoints.log" % log_dir, "w") as f: + f.write("PADDLE_TRAINER_ENDPOINTS: \n") + f.write("\n".join(cluster.trainers_endpoints())) + if current_env.get("PADDLE_ENABLE_AUTO_MAPPING") is not None \ + and current_env.get("PADDLE_NEED_RANK_MAPPING").lower() == "true": + fn = open("%s/prelaunchlog.%d" % (log_dir, idx), "a") + else: + fn = open("%s/workerlog.%d" % (log_dir, idx), "a") + proc = subprocess.Popen(cmd, + env=current_env, + stdout=fn, + stderr=fn, + preexec_fn=pre_fn) + else: + proc = subprocess.Popen(cmd, env=current_env, preexec_fn=pre_fn) + + tp = TrainerProc() + tp.proc = proc + tp.rank = t.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + procs.append(tp) + + return procs + + +def pull_worker_log(tp): + if tp.log_fn: + with open(tp.log_fn.name, 'r') as fin: + fin.seek(tp.log_offset, 0) + for line in fin: + try: + sys.stdout.write(line) + except UnicodeEncodeError: + sys.stdout.write( + 'UnicodeEncodeError occurs at this line. ' + 'Please refer to the original log file "%s"\n' % + tp.log_fn.name) + tp.log_offset = fin.tell() + + +def watch_local_trainers(procs, nranks): + try: + error = False + error_rank = [] + # wait all process finish or one error + alive = False + for p in procs: + if p.log_fn and p.local_rank == 0: + pull_worker_log(p) + + ret = p.proc.poll() + if ret is None: + alive = True + elif ret != 0: + error = True + error_rank.append(p.rank) + + if error: + terminate_local_procs(procs) + exit(1) + + except KeyboardInterrupt: + logger.warning("KeyboardInterrupt, exit") + terminate_local_procs(procs) + return + except SystemExit: + logger.error( + "ABORT!!! Out of all {} trainers, the trainer process with rank={} was aborted. Please check its log." + .format(nranks, error_rank)) + terminate_local_procs(procs) + raise + except: + logger.error( + "ABORT!!! Out of all {} trainers, the trainer process with rank={} was aborted. Please check its log." + .format(nranks, error_rank)) + terminate_local_procs(procs) + return + + return alive + + +def get_gpus(gpus): + if gpus is None: + gpus_num = fluid.core.get_cuda_device_count() + res_gpus = [str(x) for x in range(0, gpus_num)] + else: + cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + if cuda_visible_devices is None or cuda_visible_devices == "": + res_gpus = [x.strip() for x in gpus.split(',')] + else: + # change gpus into relative values + # e.g. CUDA_VISIBLE_DEVICES=4,5,6,7; args.gpus=4,5,6,7; + # therefore gpus=0,1,2,3 + cuda_visible_devices_list = cuda_visible_devices.split(',') + for x in gpus.split(','): + assert x in cuda_visible_devices_list, "Can't find "\ + "your gpus %s in CUDA_VISIBLE_DEVICES[%s]."\ + % (x, cuda_visible_devices) + res_gpus = [ + cuda_visible_devices_list.index(x.strip()) + for x in gpus.split(',') + ] + logger.info("Change selected_gpus into reletive values. --ips:{} " + "will change into relative_ips:{} according to your " + "CUDA_VISIBLE_DEVICES:{}".format( + gpus, res_gpus, cuda_visible_devices_list)) + + return res_gpus + + +def get_xpus(xpus): + if xpus is None: + xpus_num = fluid.core.get_xpu_device_count() + res_xpus = [str(x) for x in range(0, xpus_num)] + else: + xpu_visible_devices = os.getenv("XPU_VISIBLE_DEVICES") + if xpu_visible_devices is None or xpu_visible_devices == "": + res_xpus = [x.strip() for x in xpus.split(',')] + else: + # change xpus into relative values + # e.g. XPU_VISIBLE_DEVICES=4,5,6,7; args.xpus=4,5,6,7; + # therefore xpus=0,1,2,3 + xpu_visible_devices_list = xpu_visible_devices.split(',') + for x in xpus.split(','): + assert x in xpu_visible_devices_list, "Can't find "\ + "your xpus %s in XPU_VISIBLE_DEVICES[%s]."\ + % (x, xpu_visible_devices) + res_xpus = [ + xpu_visible_devices_list.index(x.strip()) + for x in xpus.split(',') + ] + logger.info("Change selected_xpus into reletive values. --ips:{} " + "will change into relative_ips:{} according to your " + "XPU_VISIBLE_DEVICES:{}".format( + xpus, res_xpus, xpu_visible_devices_list)) + + return res_xpus + + +def get_npus(npus): + if npus is None: + npus_num = fluid.core.get_npu_device_count() + res_npus = [str(x) for x in range(0, npus_num)] + else: + npu_visible_devices = os.getenv("ASCEND_VISIBLE_DEVICES") + if npu_visible_devices is None or npu_visible_devices == "": + res_npus = [x.strip() for x in npus.split(',')] + else: + # change npus into relative values + # e.g. ASCEND_VISIBLE_DEVICES=4,5,6,7; args.npus=4,5,6,7; + # therefore npus=0,1,2,3 + npu_visible_devices_list = npu_visible_devices.split(',') + for x in npus.split(','): + assert x in npu_visible_devices_list, "Can't find "\ + "your npus %s in ASCEND_VISIBLE_DEVICES[%s]."\ + % (x, npu_visible_devices) + res_npus = [ + npu_visible_devices_list.index(x.strip()) + for x in npus.split(',') + ] + logger.info("Change selected_npus into reletive values. --ips:{} " + "will change into relative_ips:{} according to your " + "ASCEND_VISIBLE_DEVICES:{}".format( + npus, res_npus, npu_visible_devices_list)) + + return res_npus + + +def get_mlus(mlus): + if mlus is None: + mlus_num = fluid.core.get_mlu_device_count() + res_mlus = [str(x) for x in range(0, mlus_num)] + else: + mlu_visible_devices = os.getenv("MLU_VISIBLE_DEVICES") + if mlu_visible_devices is None or mlu_visible_devices == "": + res_mlus = [x.strip() for x in mlus.split(',')] + else: + # change mlus into relative values + # e.g. MLU_VISIBLE_DEVICES=4,5,6,7; args.mlus=4,5,6,7; + # therefore mlus=0,1,2,3 + mlu_visible_devices_list = mlu_visible_devices.split(',') + for x in mlus.split(','): + assert x in mlu_visible_devices_list, "Can't find "\ + "your mlus %s in MLU_VISIBLE_DEVICES[%s]."\ + % (x, mlu_visible_devices) + res_mlus = [ + mlu_visible_devices_list.index(x.strip()) + for x in mlus.split(',') + ] + logger.info("Change selected_mlus into reletive values. --ips:{} " + "will change into relative_ips:{} according to your " + "MLU_VISIBLE_DEVICES:{}".format( + mlus, res_mlus, mlu_visible_devices_list)) + + return res_mlus + + +def get_device_mode(backend): + if backend == 'heter': + if fluid.core.is_compiled_with_cuda() and \ + fluid.core.get_cuda_device_count() > 0: + print("launch train in heter mode with GPU device.") + return DeviceMode.GPU + if fluid.core.is_compiled_with_xpu() and \ + fluid.core.get_xpu_device_count() > 0: + print("launch train in heter mode with XPU device.") + return DeviceMode.XPU + if fluid.core.is_compiled_with_npu() and \ + fluid.core.get_npu_device_count() > 0: + print("launch train in heter mode with NPU device.") + return DeviceMode.ASCEND_NPU + + if backend == 'hccl' and fluid.core.get_npu_device_count() > 0: + print("launch train in ascend npu mode!") + return DeviceMode.ASCEND_NPU + + if backend == 'nccl' and \ + fluid.core.get_cuda_device_count() > 0: + print("launch train in GPU mode!") + return DeviceMode.GPU + + if backend == 'bkcl' and fluid.core.get_xpu_device_count() > 0: + print("launch train in XPU mode") + return DeviceMode.XPU + + if backend == 'cncl' and fluid.core.get_mlu_device_count() > 0: + print("launch train in MLU mode") + return DeviceMode.MLU + + if backend == 'gloo': + print("launch train in CPU mode") + return DeviceMode.CPU + + raise RuntimeError("Don't supported devices") + + +def get_device_proc_info(args): + # device_mode + device_mode = get_device_mode(args.backend) + + # devices + devices_per_proc = [] + if device_mode == DeviceMode.GPU: + gpus = get_gpus(args.gpus) + if args.nproc_per_node is not None: + assert (len(gpus) % int(args.nproc_per_node)) ==0, \ + "gpus' number:{} mod args.nproc_per_node:{} must == 0".format(len(gpus), args.nproc_per_node) + + n = int(len(gpus) / int(args.nproc_per_node)) + devices_per_proc = [ + gpus[i:i + n] for i in six.moves.range(0, len(gpus), n) + ] + else: + devices_per_proc = gpus + elif device_mode == DeviceMode.ASCEND_NPU: + npus = get_npus(args.npus) + if args.nproc_per_node is not None: + assert (len(npus) % int(args.nproc_per_node)) ==0, \ + "npus' number:{} mod args.nproc_per_node:{} must == 0".format(len(npus), args.nproc_per_node) + + n = int(len(npus) / int(args.nproc_per_node)) + devices_per_proc = [ + npus[i:i + n] for i in six.moves.range(0, len(npus), n) + ] + else: + devices_per_proc = npus + elif device_mode == DeviceMode.XPU: + xpus = get_xpus(args.xpus) + if args.nproc_per_node is not None: + assert (len(xpus) % int(args.nproc_per_node)) == 0, \ + "xpus' number:{} mod args.nproc_per_node:{} must == 0".format(len(xpus), args.nproc_per_node) + + n = int(len(xpus) / int(args.nproc_per_node)) + devices_per_proc = [ + xpus[i:i + n] for i in six.moves.range(0, len(xpus), n) + ] + else: + devices_per_proc = xpus + elif device_mode == DeviceMode.MLU: + mlus = get_mlus(args.mlus) + if args.nproc_per_node is not None: + assert (len(mlus) % int(args.nproc_per_node)) ==0, \ + "mlus' number:{} mod args.nproc_per_node:{} must == 0".format(len(mlus), args.nproc_per_node) + + n = int(len(mlus) / int(args.nproc_per_node)) + devices_per_proc = [ + mlus[i:i + n] for i in six.moves.range(0, len(mlus), n) + ] + else: + devices_per_proc = mlus + elif device_mode == DeviceMode.CPU: + if hasattr(args, "paddle_cpuonly") and args.nproc_per_node is None: + #NOTE (xiongkun03) set it to cpu core number + args.nproc_per_node = multiprocessing.cpu_count() + if args.nproc_per_node is None: + devices_per_proc = [0] + else: + devices_per_proc = [x for x in range(0, args.nproc_per_node)] + else: + assert False, "Can't support device_mode:{}, support only cpu|gpu|xpu now.".format( + device_mode) + + return (device_mode, devices_per_proc) + + +def direct_start(args): + # run ps-cpu mode on paddlecloud, using given envs + cmd = [sys.executable, "-u", args.training_script] + \ + args.training_script_args + proc = subprocess.Popen(cmd) + proc.wait() + return + + +def get_custom_endpoints(origin_endpoints, offset=0): + """ + origin_endpoint: ip:port + user_define_endpoint: ip:(port+offset) + """ + assert origin_endpoints != None + paddle_user_define_endpoints_list = [] + for ip_port in origin_endpoints.split(","): + ip = ip_port.split(":")[0] + port = ip_port.split(":")[1] + new_port = int(port) + offset + paddle_user_define_endpoints_list.append(":".join((ip, str(new_port)))) + paddle_user_define_endpoints = ",".join(paddle_user_define_endpoints_list) + return paddle_user_define_endpoints + + +#def cloud_ps_heter_env_set(args): +# environs = {} +# +# paddle_trainer_endpoints = os.getenv("TRAINER_IP_PORT_LIST", "") +# assert paddle_trainer_endpoints != None +# +# paddle_pserver_endpoints = os.getenv("PSERVER_IP_PORT_LIST", "") +# assert paddle_pserver_endpoints != None +# +# # hard code for paddlecloud custom-framework +# avilable_ports = os.getenv("TRAINER_PORTS", "").split(",") +# assert len( +# avilable_ports +# ) >= 2, "set paddle_ports_num >= 2 in config.ini for paddlecloud job submit" +# +# # hard code for paddlecloud custom-framework +# trainers_num = len(paddle_pserver_endpoints.split(",")) +# assert trainers_num != 0 +# environs["PADDLE_TRAINERS_NUM"] = trainers_num +# environs["TRAINERS_NUM"] = trainers_num +# +# # hard code for paddlecloud custom-framework +# environs["PADDLE_HETER_TRAINER_IP_PORT_LIST"] = paddle_trainer_endpoints +# environs["PADDLE_PSERVERS_IP_PORT_LIST"] = paddle_pserver_endpoints +# environs["PADDLE_TRAINER_ENDPOINTS"] = get_custom_endpoints( +# paddle_pserver_endpoints, 1) +# heter_worker_num = len(paddle_trainer_endpoints.split(",")) +# if (args.heter_worker_num != None) and ( +# heter_worker_num != args.heter_worker_num): +# warnings.warn( +# "Your fleetrun setting: heter_worker_num is {}, but we find {} device can be used, this setting has been changed.". +# format(args.heter_worker_num, heter_worker_num)) +# args.heter_worker_num = heter_worker_num +# +# for k, v in environs.items(): +# os.environ[k] = str(v) +# logger.info("Set heter parameter server env: {}".format( +# pretty_print_envs(environs))) + + +def get_mapped_cluster_without_rank_mapping(node_ips, node_ip, + trainer_endpoints, device_mode, + node_ranks): + assert type(trainer_endpoints) is list, "trainer_endpoints must be list" + assert device_mode == DeviceMode.GPU, \ + "Only support get mapped cluster for gpu now." + cluster = Cluster(hdfs=None) + for node_rank, ip in enumerate(node_ips): + pod = Pod() + pod.rank = node_rank + pod.addr = ip + pod.device_mode = device_mode + cur_node_endpoints = trainer_endpoints[node_rank] + + # choose rank from global mapped ranks and set it to the trainer. + ranks_per_node = node_ranks[node_rank] + assert len(ranks_per_node) == 1 + for i in range(len(ranks_per_node)): + trainer = Trainer() + trainer.endpoint = "%s" % (cur_node_endpoints[i]) + trainer.rank = ranks_per_node[i] + pod.trainers.append(trainer) + cluster.pods.append(pod) + + pod_rank = node_ips.index(node_ip) + return cluster, cluster.pods[pod_rank] + + +def get_mapped_cluster_from_args_without_rank_mapping(args, device_mode): + assert device_mode == DeviceMode.GPU, \ + "Only support get mapped cluster for gpu now." + gpus_num = fluid.core.get_cuda_device_count() + + # parse ip-ranks json file + cluster_topo = None + with open(args.cluster_topo_path, "r") as json_file: + cluster_topo = json.load(json_file) + + node_ips = [] + node_ranks = [] + for idx, cur_cluster_topo in enumerate(cluster_topo["machines"]): + node_ips.append(cur_cluster_topo['addr']) + node_ranks.append([idx]) + + if len(node_ips) == 1: + node_ip = node_ips[0] + else: + if args.host: + node_ip = args.host + else: + _, node_ip = get_host_name_ip() + + assert node_ip in node_ips, \ + "Can't find your local ip {%s} in node_ips: {%s}" % (node_ip, node_ips) + node_rank = node_ips.index(node_ip) + + assert len(node_ranks) == len(node_ips), \ + "ranks length should be equal to ips length." + + logger.debug("parsed from args: node_ips:{} node_ip:{} " + "node_rank:{} node_ranks:{}".format(node_ips, node_ip, + node_rank, + node_ranks[node_rank])) + + # NOTE: there are different number of global mapped ranks on each node. + free_ports = [] + trainer_endpoints = [] + for ip in node_ips: + node_rank = node_ips.index(ip) + if os.environ.get('PADDLE_PORT') is not None: + start_port = int(os.getenv("PADDLE_PORT", "")) + free_ports = [ + x for x in range(start_port, start_port + + len(node_ranks[node_rank])) + ] + elif os.environ.get('FLAGS_START_PORT') is not None: + start_port = int(os.environ.get('FLAGS_START_PORT')) + free_ports = [ + x for x in range(start_port, start_port + + len(node_ranks[node_rank])) + ] + else: + free_ports = find_free_ports(len(node_ranks[node_rank])) + trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports]) + + return get_mapped_cluster_without_rank_mapping(node_ips, node_ip, + trainer_endpoints, + device_mode, node_ranks) + + +def get_mapped_cluster_with_rank_mapping(node_ips, node_ip, trainer_endpoints, + device_mode, node_ranks, + node_rank_mappings): + assert type(trainer_endpoints) is list, "trainer_endpoints must be list" + assert device_mode == DeviceMode.GPU, \ + "Only support get mapped cluster for gpu now." + + def get_relative_gpu_id(gpu_id): + cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + if cuda_visible_devices is None or cuda_visible_devices == "": + return gpu_id + else: + cuda_visible_devices_list = cuda_visible_devices.split(',') + relative_id = cuda_visible_devices_list.index(str(gpu_id)) + logger.info( + "Change gpu id from {} to {} based on CUDA_VISIBLE_DEVICES {}". + format(gpu_id, relative_id, cuda_visible_devices_list)) + return relative_id + + cluster = Cluster(hdfs=None) + for node_rank, ip in enumerate(node_ips): + pod = Pod() + pod.rank = node_rank + pod.addr = ip + pod.device_mode = device_mode + cur_node_endpoints = trainer_endpoints[node_rank] + + # choose rank from global mapped ranks and set it to the trainer. + ranks_per_node = node_ranks[node_rank] + cur_node_rank_mapping = node_rank_mappings[node_rank] + for i in range(len(ranks_per_node)): + trainer = Trainer() + local_device_ids = cur_node_rank_mapping["ranks"][str( + ranks_per_node[i])] + assert len(local_device_ids) == 1, \ + "Only support one process to one device mapping" + trainer.accelerators.append(get_relative_gpu_id( + local_device_ids[0])) + trainer.endpoint = "%s" % (cur_node_endpoints[i]) + trainer.rank = ranks_per_node[i] + pod.trainers.append(trainer) + cluster.pods.append(pod) + + pod_rank = node_ips.index(node_ip) + return cluster, cluster.pods[pod_rank] + + +def get_mapped_cluster_from_args_with_rank_mapping(args, device_mode): + assert device_mode == DeviceMode.GPU, \ + "Only support get mapped cluster for gpu now." + gpus_num = fluid.core.get_cuda_device_count() + + # parse ip-ranks json file + rank_mapping_path = args.rank_mapping_path or os.getenv( + "PADDLE_RANK_MAPPING_PATH") + rank_mapping = None + with open(rank_mapping_path, "r") as json_file: + rank_mapping = json.load(json_file) + # reset PADDLE_RANK_MAPPING_PATH env + os.environ["PADDLE_RANK_MAPPING_PATH"] = "" + + node_ips = [] + node_ranks = [] + node_rank_mappings = [] + for cur_rank_mapping in rank_mapping: + node_ips.append(cur_rank_mapping['addr']) + cur_node_rank_list = [ + int(i) for i in list(cur_rank_mapping['ranks'].keys()) + ] + cur_node_rank_list.sort() + node_ranks.append(cur_node_rank_list) + node_rank_mappings.append(cur_rank_mapping) + + if len(node_ips) == 1: + node_ip = node_ips[0] + else: + if args.host: + node_ip = args.host + else: + _, node_ip = get_host_name_ip() + + assert node_ip in node_ips, \ + "Can't find your local ip {%s} in node_ips: {%s}" % (node_ip, node_ips) + node_rank = node_ips.index(node_ip) + + assert len(node_ranks[node_rank]) <= gpus_num, \ + "number of ranks mapped to one node should not exceed the avaiable ones." + assert len(node_ranks) == len(node_ips), \ + "ranks length should be equal to ips length." + + logger.debug("parsed from args: node_ips:{} node_ip:{} " + "node_rank:{} node_ranks:{}".format(node_ips, node_ip, + node_rank, + node_ranks[node_rank])) + + # NOTE: there are different number of global mapped ranks on each node. + free_ports = [] + trainer_endpoints = [] + for ip in node_ips: + node_rank = node_ips.index(ip) + if os.environ.get('PADDLE_PORT') is not None: + start_port = int(os.getenv("PADDLE_PORT", "")) + free_ports = [ + x for x in range(start_port, start_port + + len(node_ranks[node_rank])) + ] + elif os.environ.get('FLAGS_START_PORT') is not None: + start_port = int(os.environ.get('FLAGS_START_PORT')) + free_ports = [ + x for x in range(start_port, start_port + + len(node_ranks[node_rank])) + ] + else: + free_ports = find_free_ports(len(node_ranks[node_rank])) + trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports]) + + return get_mapped_cluster_with_rank_mapping(node_ips, node_ip, + trainer_endpoints, device_mode, + node_ranks, node_rank_mappings) + + +class ParameterServerLauncher(object): + + def __init__(self, args, distribute_mode): + self.args = args + self.distribute_mode = distribute_mode + self.with_coordinator = False + self.server_num = 0 + self.worker_num = 0 + self.heter_worker_num = 0 + self.coordinator_num = 0 + + self.server_endpoints = "" + self.server_endpoints_ips = [] + self.server_endpoints_port = [] + + self.worker_endpoints = "" + self.worker_endpoints_ips = [] + self.worker_endpoints_port = [] + + self.heter_worker_endpoints = "" + self.heter_worker_endpoints_ips = [] + self.heter_worker_endpoints_port = [] + + self.coordinator_endpoints = "" + self.coordinator_endpoints_ips = [] + self.coordinator_endpoints_port = [] + + self.is_local = True + self.current_node_ip = "" + + self.stage_trainer_num = [] + self.stage_heter_map = {} + self.stage_list = [] + self.stage_device_map = {} + self.stage_num = 0 + + self.get_role_endpoints(args) + + def get_role_endpoints(self, args): + if args.server_num: + self.server_num = args.server_num + if args.servers: + assert len( + args.servers.split(",") + ) == self.server_num, "The server_num and servers doesn't match. Expect servers endpoints num epual to server_num, but received servers enpoint num: {} and server_num {}".format( + len(args.servers.split(",")), self.server_num) + self.server_endpoints = args.servers + else: + ports = get_ports(self.server_num, 0) + self.server_endpoints = ",".join( + ["127.0.0.1:" + str(x) for x in ports]) + else: + assert args.servers != "", "The setting of Parameter-Server must has server_num or servers." + self.server_endpoints = args.servers + self.server_num = len(self.server_endpoints.split(",")) + + # get worker envs + if args.worker_num: + self.worker_num = args.worker_num + if args.workers: + assert len( + args.workers.split(",") + ) == self.worker_num, "The worker_num and workers doesn't match. Expect workers endpoints num epual to worker_num, but received workers enpoint num: {} and worker_num {}".format( + len(args.workers.split(",")), self.worker_num) + + self.worker_endpoints = args.workers + else: + ports = get_ports(self.worker_num, self.server_num) + self.worker_endpoints = ",".join( + ["127.0.0.1:" + str(x) for x in ports]) + else: + assert args.workers != "", "The setting of Parameter-Server must has worker_num or workers." + worker_endpoints_ips = [ + x.strip().split(":")[0] for x in args.workers.split(",") + ] + self.worker_num = len(worker_endpoints_ips) + worker_endpoints_len = [ + len(x.strip().split(":")) for x in args.workers.split(",") + ] + + if 1 in worker_endpoints_len: + # if no port value in worker_endpoints, will set default port values. + start_port = 6170 + worker_endpoints_port = range( + start_port + self.server_num, + start_port + self.server_num + self.worker_num, 1) + # create endpoints str + worker_endpoints = [] + for i in range(self.worker_num): + worker_endpoints.append(":".join( + (worker_endpoints_ips[i], + str(worker_endpoints_port[i])))) + self.worker_endpoints = ",".join(worker_endpoints) + else: + self.worker_endpoints = args.workers + + # get coordinator envs + if args.coordinator_num: + self.with_coordinator = True + self.coordinator_num = args.coordinator_num + if args.coordinators: + assert len( + args.coordinators.split(",") + ) == self.coordinator_num, "The coordinator_num and coordinators doesn't match. Expect coordinators endpoints num epual to coordinator_num, but received coordinator enpoint num: {} and coordinator_num {}".format( + len(args.coordinators.split(",")), self.coordinator_num) + + self.coordinator_endpoints = args.coordinators + else: + ports = get_ports(self.coordinator_num, 1) + self.coordinator_endpoints = ",".join( + ["127.0.0.1:" + str(x) for x in ports]) + print(">>> use default coordinator addr(only one process)") + + # get heter worker envs + if self.distribute_mode == DistributeMode.PS_HETER: + assert args.heter_devices != "", "The setting of Parameter-Server heter mode must has heter_devices." + self.stage_device_map[1] = "cpu" # for cpu trainer + heter_devices_list = args.heter_devices.split(";") + for i in range(len(heter_devices_list)): + self.stage_device_map[i + 2] = heter_devices_list[i] + + self.stage_heter_map[1] = self.worker_endpoints + if args.heter_worker_num: + self.stage_heter_trainer_num = args.heter_worker_num.split(";") + self.stage_heter_trainer_num = [ + int(trainer_num) + for trainer_num in self.stage_heter_trainer_num + ] + + if args.heter_workers: + assert len(args.heter_workers.split(";")) == len( + self.stage_heter_trainer_num + ), "The stage_num and heter_workers doesn't match. Expect heter_workers endpoints stage num epual to heter_worker_num stage, but received heter_workers enpoint stage num: {} and heter_worker_num stage {}".format( + len(args.heter_workers.split(";")), + len(self.stage_heter_trainer_num)) + heter_worker_endpoints_list = args.heter_workers.split(";") + self.heter_worker_endpoints = "" + for i in range(len(self.stage_heter_trainer_num)): + if self.heter_worker_endpoints != "": + self.heter_worker_endpoints += "," + heter_worker_endpoints = heter_worker_endpoints_list[ + i].split(",") + assert len( + heter_worker_endpoints + ) == self.stage_heter_trainer_num[ + i], "The heter trainer num in stage {} is not equal in args.heter_worker_num and args.heter_workers".format( + i) + + heter_worker_endpoints_ips = [ + x.strip().split(":")[0] + for x in heter_worker_endpoints + ] + heter_worker_endpoints_len = [ + len(x.strip().split(":")) + for x in heter_worker_endpoints + ] + + if 1 in heter_worker_endpoints_len: + # if no port value in heter_worker_endpoint, will set default port values. + heter_worker_endpoints_port = get_ports( + len(heter_worker_endpoints_ips), + self.worker_num + self.server_num + + self.heter_worker_num) + new_heter_worker_endpoints = [] + for j in range(len(heter_worker_endpoints_ips)): + new_heter_worker_endpoints.append(":".join( + (heter_worker_endpoints_ips[j], + str(heter_worker_endpoints_port[j])))) + ip_port_list = ",".join(new_heter_worker_endpoints) + else: + ip_port_list = ",".join(heter_worker_endpoints) + + self.stage_heter_map[i + 2] = ip_port_list + self.stage_list.extend([i + 2] * + len(ip_port_list.split(','))) + + self.heter_worker_num += self.stage_heter_trainer_num[i] + self.heter_worker_endpoints += ip_port_list + else: + for i in range(len(self.stage_heter_trainer_num)): + heter_trainer_num = self.stage_heter_trainer_num[i] + ports = get_ports( + heter_trainer_num, self.server_num + + self.worker_num + self.heter_worker_num) + ip_port_list = ",".join( + ["127.0.0.1:" + str(x) for x in ports]) + self.stage_heter_map[i + 2] = ip_port_list + self.stage_list.extend([i + 2] * + len(ip_port_list.split(','))) + self.heter_worker_num += heter_trainer_num + if self.heter_worker_endpoints != "": + self.heter_worker_endpoints += "," + self.heter_worker_endpoints += ip_port_list + else: + assert args.heter_workers != "", "The setting of Parameter-Server heter mode must has heter_worker_num or heter_workers." + self.stage_heter_trainer_num = [] + heter_worker_endpoints_list = args.heter_workers.split(";") + self.heter_worker_endpoints = "" + for i in range(len(heter_worker_endpoints_list)): + heter_worker_endpoints = heter_worker_endpoints_list[ + i].split(",") + self.stage_heter_trainer_num.append( + len(heter_worker_endpoints)) + heter_worker_endpoints_ips = [ + x.strip().split(":")[0] for x in heter_worker_endpoints + ] + heter_worker_endpoints_len = [ + len(x.strip().split(":")) + for x in heter_worker_endpoints + ] + if 1 in heter_worker_endpoints_len: + # if no port value in heter_worker_endpoint, will set default port values. + heter_worker_endpoints_port = get_ports( + len(heter_worker_endpoints_ips), self.worker_num + + self.server_num + self.heter_worker_num) + + new_heter_worker_endpoints = [] + for j in range(len(heter_worker_endpoints_ips)): + new_heter_worker_endpoints.append(":".join( + (heter_worker_endpoints_ips[j], + str(heter_worker_endpoints_port[j])))) + ip_port_list = ",".join(new_heter_worker_endpoints) + else: + ip_port_list = ",".join(heter_worker_endpoints) + + self.stage_heter_map[i + 2] = ip_port_list + self.stage_list.extend([i + 2] * + len(ip_port_list.split(','))) + + self.heter_worker_num += self.stage_heter_trainer_num[-1] + if self.heter_worker_endpoints != "": + self.heter_worker_endpoints += "," + self.heter_worker_endpoints += ip_port_list + + self.stage_trainer_num = [self.worker_num + ] + self.stage_heter_trainer_num + self.stage_num = len(self.stage_trainer_num) + + # get http_port + if args.http_port: + http_port = [args.http_port] + else: + http_port = get_ports( + 1, self.server_num + self.worker_num + self.heter_worker_num) + http_ip = self.server_endpoints.split(",")[0].split(":")[0] + self.http_port = http_ip + ":" + str(http_port[0]) + + # check local or user define + self.server_endpoints_ips = [ + x.strip().split(":")[0] for x in self.server_endpoints.split(",") + ] + self.worker_endpoints_ips = [ + x.strip().split(":")[0] for x in self.worker_endpoints.split(",") + ] + + if self.with_coordinator == True: + self.coordinator_endpoints_ips = [ + x.strip().split(":")[0] + for x in self.coordinator_endpoints.split(",") + ] + self.coordinator_endpoints_port = [ + x.strip().split(":")[1] + for x in self.coordinator_endpoints.split(",") + ] + + self.server_endpoints_port = [ + x.strip().split(":")[1] for x in self.server_endpoints.split(",") + ] + self.worker_endpoints_port = [ + x.strip().split(":")[1] for x in self.worker_endpoints.split(",") + ] + self.node_ips = [] + for ip in self.server_endpoints_ips: + if ip not in self.node_ips: + self.node_ips.append(ip) + for ip in self.worker_endpoints_ips: + if ip not in self.node_ips: + self.node_ips.append(ip) + + if self.distribute_mode == DistributeMode.PS_HETER: + self.heter_worker_endpoints_ips = [ + x.strip().split(":")[0] + for x in self.heter_worker_endpoints.split(",") + ] + self.heter_worker_endpoints_port = [ + x.strip().split(":")[1] + for x in self.heter_worker_endpoints.split(",") + ] + for ip in self.heter_worker_endpoints_ips: + if ip not in self.node_ips: + self.node_ips.append(ip) + + if len(set(self.node_ips)) == 1: + self.is_local = True + self.current_node_ip = self.node_ips[0] + else: + self.is_local = False + pod_ip = os.getenv("POD_IP", None) + if pod_ip == None: + _, self.current_node_ip = get_host_name_ip() + else: + self.current_node_ip = pod_ip + if not self.distribute_mode == DistributeMode.PS_HETER: + assert self.current_node_ip in self.node_ips, "Can't find your local ip {%s} in args.servers and args.workers ips: {%s}" \ + % (self.current_node_ip, self.node_ips) + if self.current_node_ip in self.node_ips: + self.node_rank = self.node_ips.index(self.current_node_ip) + logger.debug( + "parsed from args: node_ips:{} current_node_ip:{} node_rank:{}". + format(self.node_ips, self.current_node_ip, self.node_rank)) + + def start_ps(self): + if not self.current_node_ip in self.node_ips: + return + cluster = Cluster(hdfs=None) + server_rank = 0 + worker_rank = 0 + heter_worker_rank = 0 + coordinator_rank = 0 + for node_rank, ip in enumerate(self.node_ips): + pod = Pod() + pod.rank = node_rank + pod.addr = ip + for i in range(len(self.server_endpoints_ips)): + if ip == self.server_endpoints_ips[i]: + server = Trainer() + server.endpoint = "%s:%s" % (ip, + self.server_endpoints_port[i]) + server.rank = server_rank + server_rank += 1 + pod.servers.append(server) + for j in range(len(self.worker_endpoints_ips)): + if ip == self.worker_endpoints_ips[j]: + worker = Trainer() + worker.endpoint = "%s:%s" % (ip, + self.worker_endpoints_port[j]) + worker.rank = worker_rank + worker.stage = 1 + worker_rank += 1 + pod.workers.append(worker) + for m in range(len(self.coordinator_endpoints_ips)): + if ip == self.coordinator_endpoints_ips[m]: + coordinator = Trainer() + coordinator.endpoint = "%s:%s" % ( + ip, self.coordinator_endpoints_port[m]) + coordinator.rank = coordinator_rank + coordinator.stage = 1 + coordinator_rank += 1 + pod.coordinators.append(coordinator) + + for k in range(len(self.heter_worker_endpoints_ips)): + if ip == self.heter_worker_endpoints_ips[k]: + heter_worker = Trainer() + heter_worker.endpoint = "%s:%s" % ( + ip, self.heter_worker_endpoints_port[k]) + heter_worker.rank = heter_worker_rank + heter_worker.stage = self.stage_list[k] + heter_worker_rank += 1 + pod.heter_workers.append(heter_worker) + + cluster.pods.append(pod) + + pod = cluster.pods[self.node_rank] + self.gloo_rendezvous_dir = tempfile.mkdtemp() + + # 3. subproces start + self.procs = { + "worker": [], + "coordinator": [], + "server": [], + "heter_worker": [] + } + self.cmds = { + "worker": [], + "coordinator": [], + "server": [], + "heter_worker": [] + } + self.log_fns = { + "worker": [], + "coordinator": [], + "server": [], + "heter_worker": [] + } + + self.start_pod_server(self.args, pod) + self.start_pod_worker(self.args, pod) + if self.with_coordinator: + self.start_pod_coordinator(self.args, pod) + if self.distribute_mode == DistributeMode.PS_HETER: + self.start_pod_heter_worker(self.args, pod) + + logger.info( + "Please check servers, workers, coordinator and heter_worker logs in {}/workerlog.*, {}/serverlog.* , {}/coordinatorlog.*, and {}/heterlog.*" + .format(self.args.log_dir, self.args.log_dir, self.args.log_dir, + self.args.log_dir)) + + # 4. wait for finish training + if len(self.procs["worker"]) > 0: + # if node has worker procs + # only wait worker to finish here + for i, proc in enumerate(self.procs["worker"]): + self.procs["worker"][i].proc.wait() + if len(self.log_fns["worker"]) > 0: + self.log_fns["worker"][i].close() + logger.info( + "all workers exit, going to finish parameter server and heter_worker." + ) + if len(self.procs["heter_worker"]) > 0: + for i, proc in enumerate(self.procs["heter_worker"]): + self.log_fns["heter_worker"][i].close() + self.procs["heter_worker"][i].proc.terminate() + logger.info("all heter_worker are killed") + + if len(self.procs["server"]) > 0: + for i, proc in enumerate(self.procs["server"]): + self.log_fns["server"][i].close() + self.procs["server"][i].proc.terminate() + logger.info("all parameter server are killed") + + if len(self.procs["coordinator"]) > 0: + for i, proc in enumerate(self.procs["coordinator"]): + self.log_fns["coordinator"][i].close() + self.procs["coordinator"][i].proc.terminate() + logger.info("all coordinators are killed") + + else: + # if node has not worker procs + # blocking training process + if len(self.procs["server"]) > 0: + for i, proc in enumerate(self.procs["server"]): + self.procs["server"][i].proc.wait() + + if len(self.procs["heter_worker"]) > 0: + for i, proc in enumerate(self.procs["heter_worker"]): + self.procs["heter_worker"][i].proc.wait() + + if os.path.exists(self.gloo_rendezvous_dir): + shutil.rmtree(self.gloo_rendezvous_dir) + + def start_pod_server(self, args, pod): + default_env = os.environ.copy() + current_env = copy.copy(default_env) + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + for idx, cur_server in enumerate(pod.servers): + if self.distribute_mode == DistributeMode.PS_HETER: + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": self.worker_endpoints, + "PADDLE_COORDINATOR_ENDPOINTS": self.coordinator_endpoints, + "PADDLE_ALL_HETER_TRAINER_IP_PORT_LIST": + self.heter_worker_endpoints, + "PADDLE_PORT": cur_server.endpoint.split(":")[1], + "TRAINING_ROLE": "PSERVER", + "PADDLE_TRAINERS_NUM": str(self.worker_num), + "POD_IP": cur_server.endpoint.split(":")[0], + "PADDLE_WITH_GLOO": str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": self.gloo_rendezvous_dir, + "PADDLE_GLOO_HTTP_ENDPOINT": self.http_port + } + else: + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": self.worker_endpoints, + "PADDLE_COORDINATOR_ENDPOINTS": self.coordinator_endpoints, + "PADDLE_PORT": cur_server.endpoint.split(":")[1], + "TRAINING_ROLE": "PSERVER", + "PADDLE_TRAINERS_NUM": str(self.worker_num), + "POD_IP": cur_server.endpoint.split(":")[0], + "PADDLE_WITH_GLOO": str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": self.gloo_rendezvous_dir, + "PADDLE_GLOO_HTTP_ENDPOINT": self.http_port + } + current_env.update(proc_env) + + cmd = [sys.executable, "-u", args.training_script + ] + args.training_script_args + self.cmds["server"].append(cmd) + + if idx == 0: + logger.info( + "Local server start {} processes. First process distributed " + "environment info (Only For Debug): {}".format( + len(pod.servers), + pretty_print_envs(proc_env, + ("Distributed Envs", "Value")))) + + if args.log_dir is not None: + os.system("mkdir -p {}".format(args.log_dir)) + fn = open("%s/serverlog.%d" % (args.log_dir, idx), "w") + self.log_fns["server"].append(fn) + proc = subprocess.Popen(cmd, + env=current_env, + stdout=fn, + stderr=fn) + else: + proc = subprocess.Popen(cmd, env=current_env) + + tp = TrainerProc() + tp.proc = proc + tp.rank = cur_server.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + self.procs["server"].append(tp) + + def start_pod_worker(self, args, pod): + default_env = os.environ.copy() + current_env = copy.copy(default_env) + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + + heter_device_num = 0 + device_list = [] + if fluid.core.is_compiled_with_cuda(): + device_list = get_gpus(args.gpus) + heter_device_num = len(device_list) + elif fluid.core.is_compiled_with_xpu(): + heter_device_num = fluid.core.get_xpu_device_count() + device_list = [str(x) for x in range(0, heter_device_num)] + + for idx, cur_worker in enumerate(pod.workers): + device_id = "0" if heter_device_num == 0 else str( + device_list[(idx) % heter_device_num]) + if self.distribute_mode == DistributeMode.PS_HETER: + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": + self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": + self.worker_endpoints, + "PADDLE_TRAINERS_NUM": + str(self.worker_num), + "PADDLE_COORDINATOR_ENDPOINTS": + self.coordinator_endpoints, + "PADDLE_STAGE_TRAINERS_NUM": + str(self.stage_trainer_num), + "STAGE_ID": + "1", + "STAGE_NUM": + str(self.stage_num), + "PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST": + "", + "PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST": + self.stage_heter_map[2], + "PADDLE_ALL_HETER_TRAINER_IP_PORT_LIST": + self.heter_worker_endpoints, + "HETER_DEVICE_TYPE": + self.stage_device_map[1], + "TRAINING_ROLE": + "TRAINER", + "POD_IP": + cur_worker.endpoint.split(":")[0], + "PADDLE_PORT": + cur_worker.endpoint.split(":")[1], + "PADDLE_TRAINER_ID": + str(cur_worker.rank), + "PADDLE_WITH_GLOO": + str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": + "3", + "PADDLE_GLOO_FS_PATH": + self.gloo_rendezvous_dir, + "FLAGS_selected_gpus": + "0", + "FLAGS_selected_xpus": + "0", + "CUDA_VISIBLE_DEVICES": + device_id, + "XPU_VISIBLE_DEVICES": + device_id, + "PADDLE_GLOO_HTTP_ENDPOINT": + self.http_port + } + else: + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": self.worker_endpoints, + "PADDLE_TRAINERS_NUM": str(self.worker_num), + "TRAINING_ROLE": "TRAINER", + "PADDLE_COORDINATOR_ENDPOINTS": self.coordinator_endpoints, + "POD_IP": cur_worker.endpoint.split(":")[0], + "PADDLE_PORT": cur_worker.endpoint.split(":")[1], + "PADDLE_TRAINER_ID": str(cur_worker.rank), + "PADDLE_WITH_GLOO": str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": self.gloo_rendezvous_dir, + "FLAGS_selected_gpus": "0", + "FLAGS_selected_xpus": "0", + "CUDA_VISIBLE_DEVICES": device_id, + "XPU_VISIBLE_DEVICES": device_id, + "PADDLE_GLOO_HTTP_ENDPOINT": self.http_port + } + + current_env.update(proc_env) + cmd = [sys.executable, "-u", args.training_script + ] + args.training_script_args + self.cmds["worker"].append(cmd) + + if idx == 0: + logger.info( + "Local worker start {} processes. First process distributed " + "environment info (Only For Debug): {}".format( + len(pod.workers), + pretty_print_envs(proc_env, + ("Distributed Envs", "Value")))) + + if args.log_dir is not None: + os.system("mkdir -p {}".format(args.log_dir)) + fn = open("%s/workerlog.%d" % (args.log_dir, idx), "w") + self.log_fns["worker"].append(fn) + proc = subprocess.Popen(cmd, + env=current_env, + stdout=fn, + stderr=fn) + else: + proc = subprocess.Popen(cmd, env=current_env) + + tp = TrainerProc() + tp.proc = proc + tp.rank = cur_worker.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + self.procs["worker"].append(tp) + + def start_pod_coordinator(self, args, pod): + print(">>> entering start_pod_coordinator") + default_env = os.environ.copy() + current_env = copy.copy(default_env) + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + + for idx, cur_coordinator in enumerate(pod.coordinators): + device_id = "0" + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": self.worker_endpoints, + "PADDLE_TRAINERS_NUM": str(self.worker_num), + "PADDLE_COORDINATOR_ENDPOINTS": self.coordinator_endpoints, + "PADDLE_COORDINATOR_NUM": str(self.coordinator_num), + "TRAINING_ROLE": "COORDINATOR", + "POD_IP": cur_coordinator.endpoint.split(":")[0], + "PADDLE_PORT": cur_coordinator.endpoint.split(":")[1], + "PADDLE_TRAINER_ID": str(cur_coordinator.rank), + "PADDLE_WITH_GLOO": str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": self.gloo_rendezvous_dir, + "FLAGS_selected_gpus": "0", + "FLAGS_selected_xpus": "0", + "CUDA_VISIBLE_DEVICES": device_id, + "XPU_VISIBLE_DEVICES": device_id, + "PADDLE_GLOO_HTTP_ENDPOINT": self.http_port + } + + current_env.update(proc_env) + cmd = [sys.executable, "-u", args.training_script + ] + args.training_script_args + self.cmds["coordinator"].append(cmd) + + if idx == 0: + logger.info( + "Local coordinator start {} processes. First process distributed " + "environment info (Only For Debug): {}".format( + len(pod.coordinators), + pretty_print_envs(proc_env, + ("Distributed Envs", "Value")))) + + if args.log_dir is not None: + os.system("mkdir -p {}".format(args.log_dir)) + fn = open("%s/coordinator.%d" % (args.log_dir, idx), "w") + self.log_fns["coordinator"].append(fn) + proc = subprocess.Popen(cmd, + env=current_env, + stdout=fn, + stderr=fn) + else: + proc = subprocess.Popen(cmd, env=current_env) + + tp = TrainerProc() + tp.proc = proc + tp.rank = cur_coordinator.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + self.procs["coordinator"].append(tp) + + def start_pod_heter_worker(self, args, pod): + default_env = os.environ.copy() + current_env = copy.copy(default_env) + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + + heter_device_num = 0 + device_list = [] + if fluid.core.is_compiled_with_cuda(): + device_list = get_gpus(args.gpus) + heter_device_num = len(device_list) + elif fluid.core.is_compiled_with_xpu(): + heter_device_num = fluid.core.get_xpu_device_count() + device_list = [str(x) for x in range(0, heter_device_num)] + + for idx, cur_heter_worker in enumerate(pod.heter_workers): + device_id = "0" if heter_device_num == 0 else str( + device_list[(idx) % heter_device_num]) + stage_id = cur_heter_worker.stage + proc_env = { + "PADDLE_PSERVERS_IP_PORT_LIST": + self.server_endpoints, + "PADDLE_TRAINER_ENDPOINTS": + self.worker_endpoints, + "PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST": + self.stage_heter_map[stage_id + 1] + if stage_id <= self.stage_num - 1 else "", + "PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST": + self.stage_heter_map[stage_id - 1], + "PADDLE_ALL_HETER_TRAINER_IP_PORT_LIST": + self.heter_worker_endpoints, + "HETER_DEVICE_TYPE": + self.stage_device_map[stage_id], + "STAGE_ID": + str(stage_id), + "STAGE_NUM": + str(self.stage_num), + "PADDLE_PORT": + cur_heter_worker.endpoint.split(":")[1], + "TRAINING_ROLE": + "HETER_TRAINER", + "PADDLE_TRAINERS_NUM": + str(self.worker_num), + "PADDLE_STAGE_TRAINERS_NUM": + str(self.stage_trainer_num), + "POD_IP": + cur_heter_worker.endpoint.split(":")[0], + "PADDLE_WITH_GLOO": + str(os.getenv("PADDLE_WITH_GLOO", "0")), + "PADDLE_GLOO_RENDEZVOUS": + "3", + "PADDLE_GLOO_FS_PATH": + self.gloo_rendezvous_dir, + "FLAGS_selected_gpus": + "0", + "FLAGS_selected_xpus": + "0", + "CUDA_VISIBLE_DEVICES": + device_id, + "XPU_VISIBLE_DEVICES": + device_id, + "PADDLE_GLOO_HTTP_ENDPOINT": + self.http_port + } + current_env.update(proc_env) + + cmd = [sys.executable, "-u", args.training_script + ] + args.training_script_args + self.cmds["heter_worker"].append(cmd) + + if idx == 0: + logger.info( + "Local heter_worker start {} processes. First process distributed " + "environment info (Only For Debug): {}".format( + len(pod.heter_workers), + pretty_print_envs(proc_env, + ("Distributed Envs", "Value")))) + + if args.log_dir is not None: + os.system("mkdir -p {}".format(args.log_dir)) + fn = open("%s/heterlog.%d" % (args.log_dir, idx), "w") + self.log_fns["heter_worker"].append(fn) + proc = subprocess.Popen(cmd, + env=current_env, + stdout=fn, + stderr=fn) + else: + proc = subprocess.Popen(cmd, env=current_env) + + tp = TrainerProc() + tp.proc = proc + tp.rank = cur_heter_worker.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + self.procs["heter_worker"].append(tp) + + +def check_backend(backend): + if backend not in [ + 'nccl', 'gloo', 'bkcl', 'cncl', 'auto', 'hccl', 'heter', 'xccl' + ]: + raise ValueError( + "paddle.distributed initialize error, " + "backend argument can only be one of " + "'nccl', 'gloo', 'bkcl', 'auto', 'hccl', 'heter', 'xccl' " + "but got %s" % backend) + + if backend == 'nccl' and not fluid.core.is_compiled_with_cuda(): + raise ValueError( + "paddle.distributed initialize error, " + "your paddle is not compiled with cuda but you assign 'nccl' as backend." + ) + + if backend == 'bkcl' and not fluid.core.is_compiled_with_xpu(): + raise ValueError( + "paddle.distributed initialize error, " + "your paddle is not compiled with xpu but you assign 'bkcl' as backend." + ) + + if backend == 'hccl' and not fluid.core.is_compiled_with_npu(): + raise ValueError( + "paddle.distributed initialize error, " + "your paddle is not compiled with npu but you assign 'hccl' as backend." + ) + + if backend == 'cncl' and not fluid.core.is_compiled_with_mlu(): + raise ValueError( + "paddle.distributed initialize error, " + "your paddle is not compiled with mlu but you assign 'cncl' as backend." + ) + + +def block_windows_and_macos(backend): + if backend != 'gloo': return + if utils.OS_NAME.startswith('darwin'): # MACOS , block + raise ValueError( + "You are going to using gloo on macos, but currently is not supported" + ) + if utils.IS_WINDOWS: # MACOS , block + raise ValueError( + "You are going to using gloo on windows, but currently is not supported" + ) + + +def get_backend_by_compile_flag(): + if fluid.core.is_compiled_with_cuda(): + return 'nccl' + + if fluid.core.is_compiled_with_xpu(): + return 'bkcl' + + if fluid.core.is_compiled_with_npu(): + return 'hccl' + + if fluid.core.is_compiled_with_mlu(): + return 'cncl' + + return 'gloo' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11b6970265003fd2136bc8e5e764ae1f59098d65 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/__init__.py @@ -0,0 +1,24 @@ +# Copyright (c) 2022 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. + +from .mp_layers import VocabParallelEmbedding +from .mp_layers import ColumnParallelLinear +from .mp_layers import RowParallelLinear +from .mp_layers import ParallelCrossEntropy + +from .random import RNGStatesTracker +from .random import get_rng_state_tracker +from .random import model_parallel_random_seed +from .random import determinate_seed +from .random import dropout diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba9ce9ed76a9b32c627626c547a0993217d2d7c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_layers.py @@ -0,0 +1,466 @@ +# Copyright (c) 2021 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. + +import paddle +from . import mp_ops +from paddle.fluid import core +from paddle.fluid.dygraph.layers import Layer +from .random import get_rng_state_tracker +from paddle.nn import functional as F +from paddle import framework +from paddle.autograd import PyLayer +from ...base import topology as tp + +__all__ = [] + +# Follow this paper to achieve the file: +# Shoeybi M, Patwary M, Puri R, et al. Megatron-lm: Training multi-billion parameter +# language models using model parallelism[J]. arXiv preprint arXiv:1909.08053, 2019. (https://arxiv.org/abs/1909.08053) + + +def is_fused_matmul_bias_supported(): + if paddle.is_compiled_with_cuda() and not paddle.is_compiled_with_rocm(): + return hasattr(core.ops, 'fused_gemm_epilogue') + else: + return False + + +class VocabParallelEmbedding(Layer): + """Embedding mp parallelized in the vocabulary dimension. + this class is used for splitting embedding in mp group. + + Args: + num_embeddings(int): One element which indicate the size of the dictionary of embeddings. + embedding_dim(int): One element which indicate the size of each embedding vector respectively. + weight_attr(ParamAttr|None): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_ParamAttr` . In addition, + user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. + The local word vector needs to be transformed into numpy format, and the shape of local word + vector should be consistent with :attr:`num_embeddings` . Then :ref:`api_initializer_NumpyArrayInitializer` + is used to load custom or pre-trained word vectors. See code example for details. + mp_group(Group): The tensor parallel group. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Examples: + .. code-block:: python + import paddle + from paddle.distributed import fleet + + class SimpleMPNet(paddle.nn.Layer): + def __init__(self, vocab_size, hidden_size, inner_size, output_size): + super(SimpleMPNet, self).__init__() + self.linear1 = fleet.meta_parallel.ColumnParallelLinear( + hidden_size, + inner_size, + gather_output=False, + has_bias=True) + + self.linear2 = fleet.meta_parallel.RowParallelLinear( + inner_size, + hidden_size, + input_is_parallel=True, + has_bias=True) + + self.linear3 = paddle.nn.Linear(hidden_size, output_size) + + self.embedding = fleet.meta_parallel.VocabParallelEmbedding( + vocab_size, + hidden_size) + + def forward(self, x): + x = self.embedding(x) + x = self.linear1(x) + x = self.linear2(x) + x = self.linear3(x) + return x + """ + + def __init__(self, + num_embeddings, + embedding_dim, + weight_attr=None, + mp_group=None, + name=None): + super(VocabParallelEmbedding, self).__init__() + + self.model_parallel_group = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_group( + ) if mp_group is None else mp_group + self.world_size = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_world_size( + ) if mp_group is None else mp_group.nranks + self.rank = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_rank( + ) if mp_group is None else mp_group.rank + + self.origin_num_embeddings = num_embeddings + self.is_mp = (self.world_size > 1) + + assert num_embeddings % self.world_size == 0, ( + "The length of the vocabulary must be divisible by the parallelism degree of MP" + ) + + per_part_size = num_embeddings // self.world_size + + self.vocab_start_index = self.rank * per_part_size + self._dtype = self._helper.get_default_dtype() + self._size = [per_part_size, embedding_dim] + self._weight_attr = weight_attr + self._name = name + + if self.is_mp and paddle.in_dynamic_mode(): + with get_rng_state_tracker().rng_state(): + self.weight = self.create_parameter(attr=self._weight_attr, + shape=self._size, + dtype=self._dtype, + is_bias=False) + else: + self.weight = self.create_parameter(attr=self._weight_attr, + shape=self._size, + dtype=self._dtype, + is_bias=False) + + self.weight.is_distributed = True if self.is_mp else False + + def forward(self, x): + if self.is_mp: + output_parallel = mp_ops._c_lookup_table( + self.weight, + x, + start_index=self.vocab_start_index, + name=self._name) + output = mp_ops._mp_allreduce(output_parallel, + group=self.model_parallel_group, + use_calc_stream=True, + use_model_parallel=True) + else: + output = F.embedding(x, + weight=self.weight, + padding_idx=None, + sparse=False, + name=self._name) + return output + + +class ColumnParallelLinear(Layer): + """Linear layer with mp parallelized(column). + this class is used for splitting Linear Layer in mp group, column split the weight of the Linear layer. + + Args: + in_features(int): The number of input units. + out_features(int): The number of output units. + weight_attr(ParamAttr|None): The attribute for the learnable weight of this layer. The default value is None + and the weight will be initialized to zero. For detailed information, please refer to paddle.ParamAttr. + has_bias(bool): whether to add bias. + gather_output(bool): whether to do allgahter for the output of each rank. + fuse_matmul_bias(bool): whether to fuse matmul and bias. + mp_group(Group): The tensor parallel group. + name(str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + import paddle + from paddle.distributed import fleet + + class SimpleMPNet(paddle.nn.Layer): + def __init__(self, vocab_size, hidden_size, inner_size, output_size): + super(SimpleMPNet, self).__init__() + self.linear1 = fleet.meta_parallel.ColumnParallelLinear( + hidden_size, + inner_size, + gather_output=False, + has_bias=True) + + self.linear2 = fleet.meta_parallel.RowParallelLinear( + inner_size, + hidden_size, + input_is_parallel=True, + has_bias=True) + + self.linear3 = paddle.nn.Linear(hidden_size, output_size) + + self.embedding = fleet.meta_parallel.VocabParallelEmbedding( + vocab_size, + hidden_size) + + def forward(self, x): + x = self.embedding(x) + x = self.linear1(x) + x = self.linear2(x) + x = self.linear3(x) + return x + """ + + def __init__(self, + in_features, + out_features, + weight_attr=None, + has_bias=None, + gather_output=True, + fuse_matmul_bias=False, + mp_group=None, + name=None): + super(ColumnParallelLinear, self).__init__() + + self.model_parallel_group = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_group( + ) if mp_group is None else mp_group + self.world_size = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_world_size( + ) if mp_group is None else mp_group.nranks + self._name = name + self.is_mp = (self.world_size > 1) + + self.gather_output = gather_output + assert out_features % self.world_size == 0, ( + "Number of column of the weight for linear ({}) must be" + " divisible by model parallel size ({})".format( + out_features, self.world_size)) + self.output_size_per_partition = out_features // self.world_size + + self._weight_attr = weight_attr + self._dtype = self._helper.get_default_dtype() + + if self.is_mp and paddle.in_dynamic_mode(): + with get_rng_state_tracker().rng_state(): + self.weight = self.create_parameter( + shape=[in_features, self.output_size_per_partition], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False) + else: + self.weight = self.create_parameter( + shape=[in_features, self.output_size_per_partition], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False) + + self.weight.is_distributed = True if self.is_mp else False + + if has_bias: + # initialize bias to zero like Megatron + self.bias = self.create_parameter( + shape=[self.output_size_per_partition], + attr=paddle.nn.initializer.Constant(value=0.0), + dtype=self._dtype, + is_bias=True) + self.bias.is_distributed = True if self.is_mp else False + else: + self.bias = None + + self.linear = F.linear + + if fuse_matmul_bias: + if not is_fused_matmul_bias_supported(): + raise NotImplementedError( + "You set fuse_matmul_bias=True in ColumnParallelLinear, " + "however, the paddle you are using not support this operation. " + "Please set fuse_matmul_bias=False or use paddle compiled " + "with cuda 11.6 or higher.") + from paddle.incubate.nn.functional import fused_linear + self.linear = fused_linear + + def forward(self, x): + # use inner api to process identity + if self.is_mp: + input_parallel = mp_ops._c_identity(x, + group=self.model_parallel_group) + else: + input_parallel = x + + output_parallel = self.linear(input_parallel, + self.weight, + self.bias, + name=self._name) + + if self.gather_output and self.is_mp: + output = mp_ops._c_concat(output_parallel, + group=self.model_parallel_group) + else: + output = output_parallel + return output + + +class RowParallelLinear(Layer): + """Linear layer with mp parallelized(row). + this class is used for splitting Linear Layer in mp group, row split the weight of the Linear layer. + + Args: + in_features(int): The number of input units. + out_features(int): The number of output units. + weight_attr(ParamAttr|None): The attribute for the learnable weight of this layer. The default value is None + and the weight will be initialized to zero. For detailed information, please refer to paddle.ParamAttr. + has_bias(bool): whether to add bias. + input_is_parallel(bool): whether the input has alreadly been splitted across the mp group. + fuse_matmul_bias(bool): whether to fuse matmul and bias. + mp_group(Group): The tensor parallel group. + name(str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + import paddle + from paddle.distributed import fleet + + class SimpleMPNet(paddle.nn.Layer): + def __init__(self, vocab_size, hidden_size, inner_size, output_size): + super(SimpleMPNet, self).__init__() + self.linear1 = fleet.meta_parallel.ColumnParallelLinear( + hidden_size, + inner_size, + gather_output=False, + has_bias=True) + + self.linear2 = fleet.meta_parallel.RowParallelLinear( + inner_size, + hidden_size, + input_is_parallel=True, + has_bias=True) + + self.linear3 = paddle.nn.Linear(hidden_size, output_size) + + self.embedding = fleet.meta_parallel.VocabParallelEmbedding( + vocab_size, + hidden_size) + + def forward(self, x): + x = self.embedding(x) + x = self.linear1(x) + x = self.linear2(x) + x = self.linear3(x) + return x + """ + + def __init__(self, + in_features, + out_features, + weight_attr=None, + has_bias=True, + input_is_parallel=False, + fuse_matmul_bias=False, + mp_group=None, + name=None): + super(RowParallelLinear, self).__init__() + + self.in_features = in_features + self.out_features = out_features + self.input_is_parallel = input_is_parallel + self._weight_attr = weight_attr + self._dtype = self._helper.get_default_dtype() + self._name = name + + self.model_parallel_group = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_group( + ) if mp_group is None else mp_group + self.world_size = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_world_size( + ) if mp_group is None else mp_group.nranks + self.rank = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_rank( + ) if mp_group is None else mp_group.rank + + self.is_mp = (self.world_size > 1) + assert in_features % self.world_size == 0, ( + "Number of row of the weight for linear ({}) must be" + " divisible by model parallel size ({})".format( + in_features, self.world_size)) + + self.input_size_per_partition = in_features // self.world_size + + if self.is_mp and paddle.in_dynamic_mode(): + with get_rng_state_tracker().rng_state(): + self.weight = self.create_parameter( + shape=[self.input_size_per_partition, self.out_features], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False) + else: + self.weight = self.create_parameter( + shape=[self.input_size_per_partition, self.out_features], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False) + + self.weight.is_distributed = True if self.is_mp else False + + if has_bias: + self.bias = self.create_parameter( + shape=[self.out_features], + attr=paddle.nn.initializer.Constant(value=0.0), + dtype=self._dtype, + is_bias=True) + else: + self.bias = None + + self.linear = F.linear + + if fuse_matmul_bias: + if not is_fused_matmul_bias_supported(): + raise NotImplementedError( + "You set fuse_matmul_bias=True in RowParallelLinear, " + "however, the paddle you are using not support this operation. " + "Please set fuse_matmul_bias=False or use paddle compiled " + "with cuda 11.6 or higher.") + from paddle.incubate.nn.functional import fused_linear + self.linear = fused_linear + + def forward(self, x): + if self.input_is_parallel or (not self.is_mp): + input_parallel = x + else: + # split last dim + input_parallel = mp_ops._c_split(x, group=self.model_parallel_group) + + if self.is_mp: + output_parallel = self.linear(input_parallel, + self.weight, + name=self._name) + output_ = mp_ops._mp_allreduce(output_parallel, + group=self.model_parallel_group, + use_calc_stream=True, + use_model_parallel=True) + output = output_ + self.bias if self.bias is not None else output_ + else: + output = self.linear(input_parallel, + self.weight, + self.bias, + name=self._name) + + return output + + +class ParallelCrossEntropy(Layer): + """CrossEntropy with mp parallelized. + this class is used for splitting softmax cross entropy in mp group. + + Args: + mp_group(Group): The tensor parallel group. + name(str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + loss_func = ParallelCrossEntropy() + loss = loss_func(img, lable) + """ + + def __init__(self, mp_group=None, name=None): + super(ParallelCrossEntropy, self).__init__() + self.name = name + self.model_parallel_group = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_group( + ) if mp_group is None else mp_group + self.world_size = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_world_size( + ) if mp_group is None else mp_group.nranks + self.rank = tp._HYBRID_PARALLEL_GROUP.get_model_parallel_rank( + ) if mp_group is None else mp_group.rank + + def forward(self, input, label): + loss = mp_ops._c_softmax_with_cross_entropy( + input, label, group=self.model_parallel_group) + return loss diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..18e7b6617783e295070886852c75390e0eb4d339 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/mp_ops.py @@ -0,0 +1,791 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.framework import _in_legacy_dygraph +from paddle.fluid.framework import in_dygraph_mode +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid.dygraph import layers +from paddle.distributed import collective +from ....communication.reduce import ReduceOp +from paddle.fluid.data_feeder import check_dtype +import paddle.fluid.dygraph_utils as dygraph_utils + + +def _c_identity(tensor, group=None): + """ + Return a copy of the tensor, mainly used with model parallel. + + Args: + tensor (Tensor): The input Tensor. Its data type + should be float16, float32, float64, int32 or int64. + group (int): The id of the process group to work on. + + Returns: + Tensor. + """ + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + if in_dygraph_mode(): + from paddle.autograd import PyLayer + + class c_identity_eager(PyLayer): + + @staticmethod + def forward(ctx, tensor): + return _legacy_C_ops.c_identity(tensor, 'use_calc_stream', True, + 'ring_id', group.id, + 'use_model_parallel', True) + + @staticmethod + def backward(ctx, dy): + op_type = collective._get_reduce_op(ReduceOp.SUM, "_c_identity") + group.process_group.allreduce_on_calc_stream(dy, op_type) + return dy + + return c_identity_eager.apply(tensor) + + elif _in_legacy_dygraph(): + return _legacy_C_ops.c_identity(tensor, 'use_calc_stream', True, + 'ring_id', ring_id, + 'use_model_parallel', True) + op_type = 'c_identity' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=tensor.dtype) + + check_variable_and_dtype( + tensor, 'tensor', ['float16', 'float32', 'float64', 'int32', 'int64'], + '_c_identity') + + helper.append_op(type=op_type, + inputs={'X': tensor}, + outputs={'Out': out}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + 'use_model_parallel': True, + }) + return out + + +def _c_concat(tensor, group=None): + """ + Return allgather of the tensor, mainly used with model parallel. + + Args: + tensor (Tensor): The input Tensor. Its data type + should be float16, float32, float64, int32 or int64. + group (int): The id of the process group to work on. + + Returns: + Tensor. + """ + if group is not None and not group.is_member(): + return + group = collective._get_default_group() if group is None else group + ring_id = group.id + + global_rank = collective._get_global_env().rank + rank = group.rank + nranks = group.nranks + + if _non_static_mode(): + return _legacy_C_ops.c_concat(tensor, 'ring_id', ring_id, + 'use_calc_stream', True, 'rank', rank, + 'nranks', nranks, 'use_model_parallel', + True) + + op_type = 'c_concat' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=tensor.dtype) + + check_variable_and_dtype( + tensor, 'tensor', ['float16', 'float32', 'float64', 'int32', 'int64'], + '_c_concat') + + helper.append_op(type=op_type, + inputs={'X': tensor}, + outputs={'Out': out}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + 'use_model_parallel': True, + 'nranks': nranks, + 'rank': rank + }) + return out + + +def _c_split(tensor, group=None): + """ + Split tensor evenly among all members, mainly used with model parallel. + + Args: + tensor (Tensor): The input Tensor. Its data type + should be float16, float32, float64, int32 or int64. + rank (int): The rank of the current process. + group (int): The id of the process group to work on. + + Returns: + Tensor. + """ + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + global_rank = collective._get_global_env().rank + rank = global_rank if group is None else group.get_group_rank(global_rank) + nranks = collective._get_global_env( + ).world_size if group is None else group.nranks + + if _non_static_mode(): + return _legacy_C_ops.c_split(tensor, 'use_calc_stream', True, 'ring_id', + ring_id, 'rank', rank, 'nranks', nranks, + 'use_model_parallel', True) + + op_type = 'c_split' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=tensor.dtype) + + check_variable_and_dtype( + tensor, 'tensor', ['float16', 'float32', 'float64', 'int32', 'int64'], + '_c_split') + + helper.append_op(type=op_type, + inputs={'X': tensor}, + outputs={'Out': out}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + 'rank': rank, + 'nranks': nranks, + 'use_model_parallel': True, + }) + return out + + +def _mp_allreduce(tensor, + op=ReduceOp.SUM, + group=None, + use_calc_stream=True, + use_model_parallel=True): + """[it is same as allreduce above, but it supports model parallel. And it support inplace startegy] + """ + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = collective._get_default_group() if group is None else group + assert op == ReduceOp.SUM, "Unknown parameter: {}.".format(op) + + from paddle.autograd import PyLayer + + class mp_allreduce_eager(PyLayer): + + @staticmethod + def forward(ctx, tensor, group, use_calc_stream, + use_model_parallel): + ctx.ring_id = group.id + + if use_calc_stream: + op_type = collective._get_reduce_op(op, "_mp_allreduce") + group.process_group.allreduce_on_calc_stream( + tensor, op_type) + return tensor + else: + return _legacy_C_ops.c_allreduce_sum_( + tensor, 'use_calc_stream', use_calc_stream, 'ring_id', + ring_id, "use_model_parallel", use_model_parallel) + + @staticmethod + def backward(ctx, dy): + return _legacy_C_ops.c_identity(dy, 'use_calc_stream', True, + 'ring_id', ctx.ring_id, + 'use_model_parallel', True) + + return mp_allreduce_eager.apply(tensor, group, use_calc_stream, + use_model_parallel) + + ring_id = 0 if group is None else group.id + if _in_legacy_dygraph(): + if op == ReduceOp.SUM: + return _legacy_C_ops.c_allreduce_sum_(tensor, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id, "use_model_parallel", + use_model_parallel) + else: + raise ValueError("Unknown parameter: {}.".format(op)) + + op_type = 'c_allreduce_sum' + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=tensor.dtype) + + check_variable_and_dtype( + tensor, 'tensor', ['float16', 'float32', 'float64', 'int32', 'int64'], + op_type) + + helper.append_op(type=op_type, + inputs={'X': tensor}, + outputs={'Out': out}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream, + 'use_model_parallel': use_model_parallel, + }) + return out + + +def _c_lookup_table(table, index, start_index=0, name=None): + """ + Lookup table according to index. + + Args: + table (Tensor): The input Tensor. Its data type + should be float16, float32, float64. + index (Tensor): The index to lookup table. + start_index (int): The initial index for table range. + name (string): The name of the api + + Returns: + Tensor. + """ + if _non_static_mode(): + return _legacy_C_ops.c_embedding(table, index, "start_index", + start_index) + + op_type = 'c_embedding' + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='table') + check_variable_and_dtype(index, 'input', ['int32', 'int64'], op_type) + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='c_embedding', + inputs={ + 'Ids': index, + 'W': table + }, + outputs={'Out': tmp}, + attrs={"start_index": start_index}) + return tmp + + +class _Linear(layers.Layer): + """ + Linear + """ + + def __init__(self, + in_features, + out_features, + weight_attr=None, + bias_attr=None, + name=None): + super(_Linear, self).__init__() + self._dtype = self._helper.get_default_dtype() + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self.weight = self.create_parameter(shape=[in_features, out_features], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False) + self.bias = self.create_parameter(shape=[out_features], + attr=self._bias_attr, + dtype=self._dtype, + is_bias=True) + self.name = name + + def forward(self, input): + out = _linear(x=input, + weight=self.weight, + bias=self.bias, + name=self.name) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'in_features={}, out_features={}, dtype={}{}'.format( + self.weight.shape[0], self.weight.shape[1], self._dtype, name_str) + + +def _c_softmax_with_cross_entropy(logits, + label, + group=None, + return_softmax=False): + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + global_rank = collective._get_global_env().rank + rank = global_rank if group is None else group.get_group_rank(global_rank) + nranks = collective._get_global_env( + ).world_size if group is None else group.nranks + + input_dims = len(list(logits.shape)) + label_dims = len(list(label.shape)) + if input_dims - 1 != label_dims and input_dims != label_dims: + raise ValueError( + 'Expected nput_dims - 1 = label_dims or input_dims == label_dims\ + (got nput_dims{}, label_dims{})'.format(input_dims, label_dims)) + if input_dims - 1 == label_dims: + label = paddle.unsqueeze(label, axis=-1) + + if _non_static_mode(): + softmax, loss = _legacy_C_ops.c_softmax_with_cross_entropy( + logits, label, 'ring_id', ring_id, 'rank', rank, 'nranks', nranks) + if not return_softmax: + return loss + else: + return loss, softmax + + attrs = { + 'ring_id': ring_id, + 'rank': rank, + 'nranks': nranks, + } + helper = LayerHelper('c_softmax_with_cross_entropy', **locals()) + softmax = helper.create_variable_for_type_inference(dtype=logits.dtype) + loss = helper.create_variable_for_type_inference(dtype=logits.dtype) + helper.append_op(type='c_softmax_with_cross_entropy', + inputs={ + 'Logits': logits, + 'Label': label + }, + outputs={ + 'Softmax': softmax, + 'Loss': loss + }, + attrs=attrs) + + if return_softmax: + return loss, softmax + + return loss + + +def _linear(x, weight, bias=None, name=None): + """ + Fuction Linear + """ + if _non_static_mode(): + pre_bias = _varbase_creator(dtype=x.dtype) + _legacy_C_ops.matmul(x, weight, pre_bias, 'transpose_X', False, + 'transpose_Y', False, "alpha", 1) + return dygraph_utils._append_bias_in_dygraph(pre_bias, + bias, + axis=len(x.shape) - 1) + else: + helper = LayerHelper('linear', **locals()) + dtype = x.dtype + assert len( + x.shape) < 4, "X latitude is not supported greater than 3 now." + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + 'linear') + check_dtype(dtype, 'dtype', ['float16', 'float32', 'float64'], 'linear') + + inputs = {'X': [x], 'Y': [weight]} + attrs = { + 'transpose_X': False, + 'transpose_Y': False, + 'alpha': 1, + } + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='matmul_v2', + inputs=inputs, + outputs={'Out': tmp}, + attrs=attrs) + if bias is not None: + res = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='elementwise_add', + inputs={ + 'X': [tmp], + 'Y': [bias] + }, + outputs={'Out': [res]}, + attrs={'axis': len(x.shape) - 1}) + else: + res = tmp + return res + + +def _set_var_distributed(var): + if var is None: + return + + var.is_distributed = True + + # NOTE: use current_block and find_var_recursive to support while_loop + startup_block = paddle.static.default_startup_program().current_block() + main_block = paddle.static.default_main_program().current_block() + startup_block._find_var_recursive(var.name).is_distributed = True + main_block._find_var_recursive(var.name).is_distributed = True + + +def _parallel_linear(x, + num_rows, + num_cols, + axis, + param_attr, + bias_attr, + gather_out, + inner_rank, + nranks, + split_tensor, + name, + group=None): + """ + Parallel Linear + + axis the dimension of the parameter of linear layer. + axis = 0: the row dimension + axis = 1: the col dimension + + """ + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + if axis == 0: + if split_tensor: + x = _c_split(x, group=group) + else: + x = _c_identity(x, group=group) + + linear = paddle.nn.Linear(num_rows, + num_cols, + weight_attr=param_attr, + bias_attr=bias_attr, + name=name) + + # NOTE: npu linear function use matmul_v2 but linear use matmul + linear_function = _linear if core.is_compiled_with_npu()\ + else paddle.nn.functional.linear + linear_out = linear_function( + x, + linear.weight, + # NOTE(wangxi): row split, bias need add after allreduce + None if axis == 0 else linear.bias, + linear.name) + + _set_var_distributed(linear.weight) + # set is_distributed for splited bias + # if a linear layer is splited by row, each rank would hold a complete bias and they should be the same in each rank. + # if a linear layer is splited by col, the bias would also be split into each rank as its weight + if axis == 1 and linear._bias_attr != False: + _set_var_distributed(linear.bias) + + if not gather_out: return linear_out + + out_shape = list(linear_out.shape) + out_shape[0] *= 1 if axis == 0 else nranks + main_block = paddle.static.default_main_program().current_block() + out = main_block.create_var( + shape=out_shape, + dtype=linear_out.dtype, + type=linear_out.type, + lod_level=linear_out.lod_level, + persistable=False, + is_data=False, + need_check_feed=linear_out.desc.need_check_feed()) + if axis == 0: + main_block.append_op(type='c_allreduce_sum', + inputs={'X': linear_out}, + outputs={'Out': out}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + 'use_model_parallel': True + }) + if linear.bias is not None: + out = out + linear.bias + else: + main_block.append_op(type='c_concat', + inputs={'X': linear_out}, + outputs={'Out': out}, + attrs={ + 'rank': inner_rank, + 'ring_id': ring_id, + 'nranks': nranks, + 'use_calc_stream': True, + 'use_model_parallel': True + }) + return out + + +def _parallel_embedding(x, + per_part_embeddings, + origin_size, + param_attr, + inner_rank, + num_partitions, + name, + group=None): + """ + Parallel Embedding + """ + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + helper = LayerHelper("_parallel_embedding", **locals()) + + per_part_size = per_part_embeddings + rank = inner_rank + + vocab_start_index = rank * per_part_size + dtype = helper.get_default_dtype() + size = [per_part_size, origin_size[1]] + + weight = helper.create_parameter(attr=param_attr, + shape=size, + dtype=dtype, + is_bias=False) + + if num_partitions == 1: + return paddle.nn.functional.embedding(x, + weight=weight, + padding_idx=None, + sparse=False, + name=name) + + startup_block = paddle.static.default_startup_program().global_block() + main_block = paddle.static.default_main_program().global_block() + startup_block.vars[weight.name].is_distributed = True + main_block.vars[weight.name].is_distributed = True + + output_parallel = _c_lookup_table(weight, + x, + start_index=vocab_start_index, + name=name) + out = _mp_allreduce(output_parallel, + group=group, + use_calc_stream=True, + use_model_parallel=True) + return out + + +def split(x, + size, + operation, + axis=0, + num_partitions=1, + gather_out=True, + weight_attr=None, + bias_attr=None, + name=None): + """ + + Split the weight of the specified operation into multiple devices + and do the computation in parallel. + + Now the following three cases are supported. + + Case 1: Parallel Embedding + The weight of the embedding operation is a NxM matrix with N rows and M columns. + With parallel embedding, the weight is split into num_partitions partitions, each + of which is a matrix with (N/num_partitions + 1) rows and M column where the last + row as the padding idx. + + Suppose we split the NxM weight into two partitons on device_0 and device_1 + respectively. Then, one each device, the final weight has (N/2 + 1) rows with the + index range from 0 to N/2. On device_0, all values in the input within [0, N/2 -1] + keep unchanged and all other values are changed to N/2 which is the padding index and + are mapped to all zeros after embedding. In the same way, on device_1, the value V in the + input within [N/2, N-1] will be changed to (V - N/2), and all other values are changed + to N/2 and are mapped to all zeros after embedding. Finally, the results on the two + devices are sum-reduced. + + The Embedding put on single card is as shown below: + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_embedding_single.png + :width: 800 + :height: 350 + :alt: single_embedding + :align: center + + Parallel Embedding is shown as below: + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_embedding_split.png + :width: 800 + :alt: split_embedding + :align: center + + Case 2: Row Parallel Linear + The weight of the linear operation is a NxM matrix with N rows and M columns. + With row parallel linear, the weight is split into num_partitions partitions, each + of which is a matrix with N/num_partitions rows and M column. + + The linear layer put on single card is shown as below, the input variable is represented by X, + the weight matrix is represented by W and the output vaiable is O. The linear layer on single card is + simple matrix multiplication operation, O = X * W. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_single.png + :width: 800 + :alt: single_linear + :align: center + + Row Parallel Linear is shown as below. As the name suggests, Row Parallel Linear splits the weight matrix W into + [[W_row1], [W_row2]] along the row. And accordingly the input is splitted along the column into [X_col1, X_col2] and multiply their + respective weight matrices. Finally apply AllReduce on the output from each card to get the final output. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_row.png + :width: 800 + :alt: split_row + :align: center + + Case 3: Column Parallel Linear + The weight of the linear operation is a NxM matrix with N rows and M columns. + With column parallel linear, the weight is split into num_paratitions partitions, each + of which is a matrix with N rows and M/num_partitions column. + + The linear layer put on single card has been illustrated on case 2 and Column Parallel Linear + is shown as below. The Column Parallel Linear splits the weight matrix W into [W_col1, W_col2] along the column and + these splitted matrices respectively multiply the input. Finally apply AllGather on the output from each card to get the final output. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_col.png + :width: 800 + :alt: split_col + :align: center + + As observed, the column parallel linear and row parallel linear can be combined to skip one ALLGATHER communication + operator. Furthermore the Attention and MLP can be combined to imporve the performance as shown below. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/split_col_row.png + :width: 800 + :alt: split_col_row + :align: center + + Args: + x (Tensor): Input tensor. It's data type should be float16, float32, float64, int32 or int64. + size (list|tuple): A list or tuple with two elements indicating the shape of the weight. + operation (str): The name of the operation. The supported operations are 'linear' and 'embedding'. + axis (int, Optional): Indicate along which axis to split the weight. Default: 0. + num_partitions (int, Optional): How many parts the weight is partitioned. Default: 1. + gather_out (bool, Optional): Whether to gather the output after computation. By default, the output + on each partitions will be gathered after computation. Default: True. + weight_attr (ParamAttr, Optional): The parameter attribute for the learnable + weights(Parameter) of the specified operation. Default: None. + bias_attr (ParamAttr, Optional): The parameter attribute for the bias + of the specified operation. Default: None. + name (str, Optional): The default value is None. Normally there is no need for user to set this + property. Default: None. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.distributed.fleet as fleet + + paddle.enable_static() + paddle.set_device('gpu:%d'%paddle.distributed.ParallelEnv().dev_id) + fleet.init(is_collective=True) + data = paddle.randint(0, 8, shape=[10,4]) + emb_out = paddle.distributed.split( + data, + (8, 8), + operation="embedding", + num_partitions=2) + + """ + assert isinstance( + size, + (list, tuple)), ("The type of size for " + "paddle.distributed.split must be list or tuple.") + assert len(size) == 2, ("Number of elements in size of " + "paddle.distributed.split must be two.") + assert isinstance(operation, str), ("The type of operation for " + "paddle.distributed.split must be str.") + supported_operations = [ + 'linear', + 'embedding', + ] + assert operation in supported_operations, ( + "The operation for " + "paddle.distributed.split must be one of {}.".format( + supported_operations)) + if _non_static_mode(): + raise ValueError( + "paddle.distributed.split cannot be used in dynamic " + "graph mode, plese use ParallelEmbedding, ParallelRowLinear, " + "ParallelColumnLinear instead.") + else: + from paddle.distributed.fleet import fleet + assert fleet._role_maker, ("To use paddle.distributed.split, " + "you must call fleet.init() firstly.") + rank = fleet.worker_index() + nranks = fleet.worker_num() + + # rank within a model parallel group + inner_rank = rank % num_partitions + + if operation == "embedding": + assert axis == 0, ("We only support to split the weight of embedding " + "along the first axis now.") + assert size[0] % num_partitions == 0, \ + "The length of the vocabulary must be divisible by num_partitions " \ + "but received vocabulary={} num_partitions={}".format(size[0], num_partitions) + + per_part_size = size[0] // num_partitions + emb_out = _parallel_embedding(x, + per_part_size, + size, + weight_attr, + inner_rank, + num_partitions, + name, + group=None) + return emb_out + else: + should_split = False + if axis == 0: + assert size[0] % num_partitions == 0, ( + "Number of rows of the weight for linear ({}) must be" + " divisible by num_partitions ({})".format( + size[0], num_partitions)) + per_part_size = size[0] // num_partitions + linear_size = (per_part_size, size[1]) + if x.shape[-1] == size[0]: should_split = True + + elif axis == 1: + assert size[1] % num_partitions == 0, ( + "Number of column of the weight for linear ({}) must be" + " divisible by num_partitions ({})".format( + size[1], num_partitions)) + per_part_size = size[1] // num_partitions + linear_size = (size[0], per_part_size) + else: + raise ValueError("The value of axis must be 0 or 1, but the value " + "given is {}.".format(axis)) + + linear_out = _parallel_linear(x, + linear_size[0], + linear_size[1], + axis, + weight_attr, + bias_attr, + gather_out, + inner_rank, + num_partitions, + should_split, + name=name, + group=None) + return linear_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/random.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/random.py new file mode 100644 index 0000000000000000000000000000000000000000..7577be6253cbfadac529c2b3b0b699643c9822e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/layers/mpu/random.py @@ -0,0 +1,243 @@ +# Copyright (c) 2022 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. + +import paddle +import numpy as np +import contextlib +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid.framework import _non_static_mode, default_main_program, Variable +from paddle.fluid.layer_helper import LayerHelper + +__all__ = [] + +MODEL_PARALLEL_RNG = 'model_parallel_rng' + +# This file is inspired by Megatron to control random states for MP: +# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/mpu/random.py + + +class RNGStatesTracker: + """ + Tracker the RNG states. + """ + + def __init__(self): + # Map from name to the rng state. + self.states_ = {} + self.seeds_ = set() + + def reset(self): + self.states_ = {} + self.seeds_ = set() + + def add(self, name, seed): + if seed in self.seeds_: + raise ValueError('seed {} already exists'.format(seed)) + self.seeds_.add(seed) + if name in self.states_: + raise ValueError('state {} already exists'.format(name)) + orig_rng_state = paddle.get_cuda_rng_state() + paddle.seed(seed) + self.states_[name] = paddle.get_cuda_rng_state() + paddle.set_cuda_rng_state(orig_rng_state) + + def get_states_tracker(self): + states = {} + for name in self.states_: + states[name] = self.states_[name] + return states + + def set_states_tracker(self, states): + self.states_ = states + + @contextlib.contextmanager + def rng_state(self, name=MODEL_PARALLEL_RNG): + if name not in self.states_: + raise ValueError('state {} does not exist'.format(name)) + orig_cuda_rng_state = paddle.get_cuda_rng_state() + paddle.set_cuda_rng_state(self.states_[name]) + try: + yield + finally: + self.states_[name] = paddle.get_cuda_rng_state() + paddle.set_cuda_rng_state(orig_cuda_rng_state) + + +RNG_STATE_TRACKER = RNGStatesTracker() + + +def get_rng_state_tracker(): + return RNG_STATE_TRACKER + + +def model_parallel_random_seed(seed=None): + import paddle.distributed.fleet as fleet + hcg = fleet.get_hybrid_communicate_group() + rank = hcg.get_model_parallel_rank() + + if seed: + global_seed = seed + local_seed = seed * 1024 + rank * 100 + else: + global_seed = np.random.randint(0, 655350) + local_seed = np.random.randint(rank * 10000, (rank + 1) * 10000 - 1) + + RNG_STATE_TRACKER.reset() + RNG_STATE_TRACKER.add(MODEL_PARALLEL_RNG, local_seed) + paddle.seed(global_seed) + + +def determinate_seed(rng_name): + assert rng_name is not None and rng_name != "" + helper = LayerHelper('seed', **locals()) + out = helper.create_variable_for_type_inference(dtype=paddle.int32) + # set force_cpu to reduce sync copy from CPU->GPU->CPU, and reduce pipeline hang + helper.append_op(type='seed', + outputs={'Out': out}, + attrs={ + 'deterministic': True, + 'rng_name': rng_name, + 'force_cpu': True + }) + return out + + +def dropout(x, + p=0.5, + axis=None, + rng_name=None, + training=True, + mode="upscale_in_train", + name=None): + """ + Dropout is a regularization technique for reducing overfitting by preventing + neuron co-adaption during training. The dropout operator randomly sets the + outputs of some units to zero, while upscale others according to the given + dropout probability. + + Args: + x (Tensor): The input tensor. The data type is float32 or float64. + p (float|int): Probability of setting units to zero. Default 0.5. + axis (int|list|tuple): The axis along which the dropout is performed. Default None. + rng_name (str): The random seed generator name, which used to obtain deterministic results. + training (bool): A flag indicating whether it is in train phrase or not. Default True. + mode(str): ['upscale_in_train'(default) | 'downscale_in_infer']. + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - dropout_prob ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - dropout_prob) + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor representing the dropout, has same shape and data type as `x` . + + + Examples: + We use ``p=0.5`` in the following description for simplicity. + + 1. When ``axis=None`` , this is commonly used dropout, which dropout each element of x randomly. + + .. code-block:: text + + Let's see a simple case when x is a 2d tensor with shape 2*3: + [[1 2 3] + [4 5 6]] + we generate mask with the same shape as x, which is 2*3. The value of mask is + sampled from a Bernoulli distribution randomly. For example, we may get such mask: + [[0 1 0] + [1 0 1]] + So the output is obtained from elementwise multiply of x and mask: + [[0 2 0] + [4 0 6]] + Using default setting, i.e. ``mode='upscale_in_train'`` , + if in training phase, the final upscale output is: + [[0 4 0 ] + [8 0 12]] + if in test phase, the output is the same as input: + [[1 2 3] + [4 5 6]] + we can also set ``mode='downscale_in_infer'`` , then + if in training phase, the final output is: + [[0 2 0] + [4 0 6]] + if in test phase, the scale output is: + [[0.5 1. 1.5] + [2. 2.5 3. ]] + + """ + if rng_name is None: + return paddle.nn.functional.dropout(x, p, axis, training, mode, name) + + if not isinstance(p, (float, int, Variable)): + raise TypeError("p argument should be a number(int|float) or Variable") + + # fast return for p == 0 + if isinstance(p, (int, float)) and p == 0: return x + + assert 0 <= p <= 1, ValueError("p argument should between 0 and 1") + assert mode in ('downscale_in_infer', 'upscale_in_train'), \ + ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'") + + assert axis is None, \ + TypeError("unsupport axis when using random seed generator") + + mode = 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode #semantic transfer + + # dygraph using tracker, doesn't need determinate seed + if _non_static_mode(): + out, mask = _legacy_C_ops.dropout(x, 'dropout_prob', p, 'is_test', + not training, 'fix_seed', False, + 'seed', 0, 'dropout_implementation', + mode) + return out + + seed = determinate_seed(rng_name) + + if isinstance(p, Variable) and not p.shape != [1]: + raise TypeError( + "Required p.shape == [1] if type(p) is Variable, but received p.shape = {}" + .format(p.shape)) + + helper = LayerHelper('dropout', **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + 'dropout') + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + mask = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) + + helper.append_op(type='dropout', + inputs={ + 'X': [x], + 'Seed': seed + }, + outputs={ + 'Out': [out], + 'Mask': [mask] + }, + attrs={ + 'dropout_prob': p, + 'is_test': not training, + 'dropout_implementation': mode, + }) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1eae4be579aa783cefc0837b6483c255fd2a7f96 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/__init__.py @@ -0,0 +1,34 @@ +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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 + +from .amp_optimizer import AMPOptimizer +from .asp_optimizer import ASPOptimizer +from .recompute_optimizer import RecomputeOptimizer +from .gradient_merge_optimizer import GradientMergeOptimizer +from .graph_execution_optimizer import GraphExecutionOptimizer +from .ps_optimizer import ParameterServerOptimizer +from .pipeline_optimizer import PipelineOptimizer +from .localsgd_optimizer import LocalSGDOptimizer +from .localsgd_optimizer import AdaptiveLocalSGDOptimizer +from .lars_optimizer import LarsOptimizer +from .parameter_server_graph_optimizer import ParameterServerGraphOptimizer +from .dgc_optimizer import DGCOptimizer +from .lamb_optimizer import LambOptimizer +from .fp16_allreduce_optimizer import FP16AllReduceOptimizer +from .sharding_optimizer import ShardingOptimizer +from .dygraph_optimizer import HybridParallelOptimizer +from .dygraph_optimizer import HeterParallelOptimizer +from .dygraph_optimizer import HybridParallelGradScaler +from .tensor_parallel_optimizer import TensorParallelOptimizer +from .raw_program_optimizer import RawProgramOptimizer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/amp_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/amp_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..78a53ccdba55e62a70661b714f553ba6869ff42a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/amp_optimizer.py @@ -0,0 +1,132 @@ +# 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 + +import paddle.fluid.contrib.mixed_precision as mixed_precision +from .meta_optimizer_base import MetaOptimizerBase + +__all__ = [] + + +class AMPOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(AMPOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.wrapped_opt = None + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [ + "LarsOptimizer", + "LambOptimizer", + "RecomputeOptimizer", + "GraphExecutionOptimizer", + ] + self.meta_optimizers_black_list = ["DGCOptimizer"] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(AMPOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _init_wrapped_opt(self): + if self.wrapped_opt is not None: + return + + config = self.user_defined_strategy.amp_configs + + custom_white_list = set(config['custom_white_list']) + custom_black_list = set(config['custom_black_list']) + custom_black_varnames = set(config['custom_black_varnames']) + amp_lists = mixed_precision.AutoMixedPrecisionLists( + custom_white_list, custom_black_list, custom_black_varnames) + + self.wrapped_opt = mixed_precision.decorate( + self.inner_opt, amp_lists, config['init_loss_scaling'], + config['incr_every_n_steps'], config['decr_every_n_nan_or_inf'], + config['incr_ratio'], config['decr_ratio'], + config['use_dynamic_loss_scaling'], config['use_pure_fp16'], + config['use_fp16_guard']) + + # if worker_num > 1, all cards will communication with each other, + # add is_distributed to optimize amp, overlap communication and + # computation by split the check_finite_and_unscale op. + is_distributed = self.role_maker._worker_num() > 1 + if self.user_defined_strategy.sharding: + # FIXME(wangxi). sharding failed when split check_finite_and_unscale + # FIXME(JZ-LIANG). To support Sharding-Megatron-AMP, Megatron should follow Sharding's behavior that to disable is_distributed. + is_distributed = False + self.wrapped_opt._set_distributed(is_distributed) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.amp: + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.amp = False + dist_strategy.amp_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.amp = True + dist_strategy.amp_configs = { + "init_loss_scaling": 32768.0, + "incr_every_n_steps": 1000, + "decr_every_n_nan_or_inf": 2, + "incr_ratio": 2.0, + "decr_ratio": 0.8, + "use_dynamic_loss_scaling": True + } + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + # maybe inner_opt of other meta optimizer + self._init_wrapped_opt() + return self.wrapped_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_gradients(self, params_grads): + return self.wrapped_opt.apply_gradients(params_grads=params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + return self.wrapped_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self._init_wrapped_opt() + optimize_ops, params_grads = \ + self.wrapped_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads + + def amp_init(self, + place, + scope=None, + test_program=None, + use_fp16_test=False): + return self.wrapped_opt.amp_init(place, scope, test_program, + use_fp16_test) + + def get_loss_scaling(self): + return self.wrapped_opt.get_loss_scaling() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..185a92b8d94d3426d616c0624f0f2ee04339349e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2021 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..96d83ff4d39f09b20b77ca9118d6087acd8b55e3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_optimizer.py @@ -0,0 +1,273 @@ +# Copyright (c) 2021 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. + +import os +import paddle.fluid.framework as framework +from paddle.fluid.optimizer import Optimizer +import paddle.fluid.core as core +import numpy as np +from . import ascend_parser +from paddle.distributed import fleet +import hccl.manage.api as hccl +from collections import namedtuple + +HcomGroupConfig = namedtuple('HcomGroupConfig', ['name', 'nranks', 'rank_ids']) + +__all__ = [] + + +class AscendIRParser(object): + + def __init__(self, auto_dp=False, world_rank_size=1): + self.graph_idx = 0 + self.hcom_endpoints = {} + self.groups_to_create = [] + self._auto_dp = auto_dp + self._world_rank_size = world_rank_size + + def _construct_input_map(self, input_varlist): + ret_map = {} + ge_in_operator = [] + for id, var in enumerate(input_varlist): + if var.is_data: # input data + ge_input = core.GEOperatorFactory.create_operator( + var.name, "Data").set_attr_int32("index", id) + ret_map[var.name] = ge_input + ge_in_operator.append(ge_input) + else: # param, learning ... + ge_input = core.GEOperatorFactory.create_operator( + var.name, "Variable") + ge_input.update_output_desc( + "y", + core.GETensorDesc(core.GEShape(var.shape), + core.GEFormat.FORMAT_ND, + core.GEDataType.DT_FLOAT)) + ret_map[var.name] = ge_input + return ge_in_operator, ret_map + + def _endpoint_to_world_rank_id(self, endpoint): + world_endpoints = fleet.worker_endpoints() + assert endpoint in world_endpoints, "endpoint (%s) not in worker_endpoints (%s) " % ( + endpoint, fleet.world_device_ids()) + return world_endpoints.index(endpoint) + + def parse_op(self, op): + if op.type == 'c_gen_nccl_id': + endpoint = op.attr("endpoint") + other_endpoints = op.attr("other_endpoints") + rank = op.attr("rank") + + nccl_id = op.output_arg_names[0] + + # c_gen_nccl_id operator splits endpoints into local endpoint and other_endpoints + # we should combine these together to produce world_rank_ids + self.hcom_endpoints[nccl_id] = other_endpoints[:] + self.hcom_endpoints[nccl_id].insert(rank, endpoint) + + print("nccl_id (%s) registered endpoints %s" % + (nccl_id, self.hcom_endpoints[nccl_id])) + elif op.type == 'c_comm_init': + nccl_id = op.input_arg_names[0] + nranks = op.attr("nranks") + assert nranks == len(self.hcom_endpoints[nccl_id] + ), "nranks doesn't match endpoint count" + rank = op.attr("rank") + ring_id = op.attr("ring_id") + + group_name = "hcom_group_" + str(ring_id) + global_rank_ids = [ + self._endpoint_to_world_rank_id(endpoint) + for endpoint in self.hcom_endpoints[nccl_id] + ] + self.groups_to_create.append( + HcomGroupConfig(name=group_name, + nranks=nranks, + rank_ids=global_rank_ids)) + print("append to create group: %s, with rank_ids: %s" % + (group_name, global_rank_ids)) + elif op.type in ascend_parser.registerd_op: + op_parser = self.parser_factory.create_parse( + ascend_parser.registerd_op[op.type]) + op_parser.apply(op) + else: + assert False, "Op[%s] has not been registered, so we have to skip it" % ( + op.type) + + def _parse_program(self, + graph_name, + program, + input_varlist=[], + fetch_list=[]): + begin_graph_idx = self.graph_idx + ge_in_operator = [] + ge_out_operator = [] + self.var2geop = {} + + block = program.global_block() + if len(block.ops) == 0: + print("There is no ops in program %s" % (graph_name)) + return [] + + graph = core.GEGraph(graph_name) + + ge_in_operator, self.var2geop = self._construct_input_map(input_varlist) + + self.parser_factory = ascend_parser.AscendParserFactory( + graph, self.var2geop) + for i, curop in list(enumerate(block.ops)): + self.parse_op(curop) + + # Set fetch_var for GE + for e in fetch_list: + name = e + if not isinstance(e, str): + name = e.name + ge_out_operator.append(self.var2geop[name]) + + # (Debug) If you want to print back prop vars, append/assign the varname in ge_out_operator here, such as: + # if graph_name == "main": + # ge_out_operator.append(self.var2geop["reduce_sum_0.tmp_0@GRAD"]) + + # Add ops that may be input of a graph, such as const. + for varname, geop in self.var2geop.items(): + if varname.startswith("geinput"): + ge_in_operator.append(geop) + + graph.set_inputs(ge_in_operator).set_outputs(ge_out_operator) + + # Remove ops of origin program + op_num = len(block.ops) + for i in range(op_num - 1, -1, -1): + block._remove_op(i) + + input_varlist = [var for var in input_varlist if var.is_data] + + block.append_op(type="ascend_trigger", + inputs={"FeedList": input_varlist}, + outputs={"FetchList": fetch_list}, + attrs={'graph_idx': self.graph_idx}) + self.graph_idx += 1 + return graph + + def parse_program(self, startup_program, main_program, input_varlist, + fetch_list): + startup_graph = self._parse_program("startup", startup_program) + main_graph = self._parse_program("main", main_program, input_varlist, + fetch_list) + if self._auto_dp and self._world_rank_size > 1: + assert len(self.groups_to_create + ) == 0, "can't parse program under auto_dp mode" + + from paddle.distributed import fleet + self.groups_to_create.append( + HcomGroupConfig(name="hcom_group_0", + nranks=fleet.world_size(), + rank_ids=[x + for x in range(fleet.world_size())])) + + return startup_graph, main_graph + + +# AscendOptimizer is a wrapper for basic optimizer now +# We will make it part of fleet meta_optimizer in the future +class AscendOptimizer(Optimizer): + + def __init__(self, optimizer, fetch_list=[]): + self.inner_opt = optimizer + self.fetch_list = fetch_list + self.ascend_instance = None + + def __del__(self): + print("begin AscendOptimizer del") + if self.ascend_instance is not None: + self.ascend_instance.destroy_global_resources() + core.ge_finalize() + print("end AscendOptimizer del") + + def _can_apply(self): + if not self.user_defined_strategy.ascend: + return False + # TODO(hutuxian): other check here + return True + + def _disable_strategy(self, dist_strategy): + dist_strategy.ascend = False + dist_strategy.ascend_configs = {} + + def _get_input_varlist(self, program): + ret_list = [] + for var in program.list_vars(): + if var.is_data or var.persistable: + ret_list.append(var) + return ret_list + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + auto_dp=False, + rank_table_file=None, + precision_mode="must_keep_origin_dtype"): + minimized = None + if self.inner_opt: + minimized = self.inner_opt.minimize(loss, + startup_program=startup_program) + + self.ascend_instance = core.AscendInstance() + + from paddle.distributed import fleet + if auto_dp and fleet.world_size() > 1: + from paddle.fluid.transpiler import ascend_transpiler + t = ascend_transpiler.AscendTranspiler(startup_program, + loss.block.program) + t.transpile() + #print(loss.block.program) + + # Config about Graph Engine can be found in https://support.huaweicloud.com/ + config = { + "ge.exec.deviceId": str(fleet.local_device_ids()), + "ge.graphRunMode": "1", + "ge.exec.precision_mode": precision_mode, + } + # if multi trainers + if rank_table_file and fleet.world_size() > 1: + config["ge.exec.rankTableFile"] = rank_table_file + config["ge.exec.rankId"] = str(fleet.worker_index()) + config["ge.exec.isUseHcom"] = "1" + config["ge.exec.deployMode"] = "0" + print("ge_initialize config:", config) + core.ge_initialize(config) + + # Init Session + self.ascend_instance.init_global_resources() + + main_block = loss.block + self.parser = AscendIRParser(auto_dp=auto_dp, + world_rank_size=fleet.world_size()) + + input_varlist = self._get_input_varlist(main_block.program) + + startup_graph, main_graph = self.parser.parse_program( + startup_program, main_block.program, input_varlist, self.fetch_list) + + for cfg in self.parser.groups_to_create: + print("create group (%s), nranks: %d, rank_ids: %s" % + (cfg.name, cfg.nranks, cfg.rank_ids)) + hccl.create_group(cfg.name, cfg.nranks, cfg.rank_ids) + + self.ascend_instance.add_ascend_subgraph(0, startup_graph) + self.ascend_instance.add_ascend_subgraph(1, main_graph) + + return minimized diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..99c5100b70e1a5697c3e80e3f54124ce42416ba0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ascend/ascend_parser.py @@ -0,0 +1,2306 @@ +# Copyright (c) 2021 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. +import paddle.fluid.framework as framework +from paddle.fluid.optimizer import Optimizer +import paddle.fluid.core as core +import numpy as np +from paddle.distributed import fleet +from functools import reduce + +__all__ = [] + +registerd_op = { ## forwards + "elementwise_add": "AddParser", + "matmul": "MatMulParser", + "mul": "MulParser", + "relu": "ReluParser", + "softmax_with_cross_entropy": "SoftmaxWithCrossEntropyParser", + "shape": "ShapeParser", + "fill_constant": "FillConstantParser", + "reduce_sum": "ReduceSumParser", + "elementwise_mul": "DotMulParser", + "elementwise_div": "DotDivParser", + "elementwise_pow": "DotPowParser", + "elementwise_max": "MaxParser", + "elementwise_min": "MinParser", + "elementwise_sub": "DotSubParser", + "pow": "PowParser", + "gelu": "GeluParser", + "sqrt": "SqrtParser", + "log": "LogParser", + "sum": "SumParser", + "logical_not": "LogicalNotParser", + "gather": "GatherParser", + "scatter": "ScatterParser", + "cast": "CastParser", + "tanh": "TanhParser", + "stack": "StackParser", + "square": "SquareParser", + "unsqueeze2": "UnSqueezeParser", + "assign": "AssignParser", + "softmax": "SoftMaxParser", + "reshape2": "ReshapeParser", + "transpose2": "TransposeParser", + "layer_norm": "LayerNormParser", + "less_than": "LessParser", + "mean": "MeanParser", + "scale": "ScaleParser", + "slice": "SliceParser", + "top_k": "TopkParser", + "accuracy": "AccuracyParser", + #"increment": "IncrementParser", + "lookup_table": "LookupTableParser", + "truncated_gaussian_random": "TruncatedNormalParser", + "c_allgather": "AllGatherParser", + "c_allreduce_sum": "AllReduceSumParser", + "c_allreduce_max": "AllReduceMaxParser", + "c_broadcast": "BroadcastParser", + "c_reduce_scatter": "ReduceScatterParser", + "c_send": "SendParser", + "c_receive": "ReceiveParser", + "uniform_random": "UniformRandomParser", + "range": "RangeParser", + "equal": "EqualParser", + "expand": "ExpandParser", + "squeeze2": "SqueezeParser", + + ## backwords + "matmul_grad": "MatMulGradParser", + "mul_grad": "MulGradParser", + "relu_grad": "ReluGradParser", + "reduce_sum_grad": "ReduceSumGradParser", + "softmax_with_cross_entropy_grad": "SoftmaxWithCrossEntropyGradParser", + "tanh_grad": "TanhGradParser", + "log_grad": "LogGradParser", + "pow_grad": "PowGradParser", + "sqrt_grad": "SqrtGradParser", + "gelu_grad": "GeluGradParser", + "mean_grad": "MeanGradParser", + 'lookup_table_grad': "LookUpTableGradParser", + "elementwise_mul_grad": "DotMulGradParser", + "elementwise_add_grad": "DotAddGradParser", + "elementwise_div_grad": "DotDivGradParser", + "softmax_grad": "SoftmaxGradParser", + "slice_grad": "SliceGradParser", + "reshape2_grad": "ReshapeGradParser", + "gather_grad": "GatherGradParser", + "transpose2_grad": "TransposeGradParser", + "layer_norm_grad": "LayerNormGradParser", + + ## opt + "sgd": "SGDParser", + #"adam": "AdamParser", +} +global_cnt = -1 +global_input_cnt = -1 + + +class AscendHelper(object): + + def __init__(self): + self.dtype2ge_map = { + 0: core.GEDataType.DT_BOOL, + 1: core.GEDataType.DT_INT16, + 2: core.GEDataType.DT_INT32, + 3: core.GEDataType.DT_INT64, + 4: core.GEDataType.DT_FLOAT16, + 5: core.GEDataType.DT_FLOAT, + 6: core.GEDataType.DT_DOUBLE + } + self.dtype2np_map = { + 0: "bool", + 1: "int16", + 2: "int32", + 3: "int64", + 4: "float16", + 5: "float32", + 6: "float64" + } + self.dtype2paddle_inv_map = {"VarType.FP32": 0, "VarType.FP16": 1} + + def dtype2ge(self, dtype): + assert dtype in self.dtype2ge_map, "dtype[%d] is not supported %d" % ( + dtype) + return self.dtype2ge_map[dtype] + + def dtype2np(self, index): + assert index in self.dtype2np_map, "index[%d] is not supported %d" % ( + index) + return self.dtype2np_map[index] + + +class AscendParserFactory(object): + + def __init__(self, graph, var2geop): + self.graph = graph + self.var2geop = var2geop + + def create_parse(self, parser_class): + try: + parser = globals()[parser_class](self.graph, self.var2geop) + return parser + except: + raise ValueError("parser class %s does not exist" % parser_class) + + +class AscendParserBase(object): + + def __init__(self, graph, var2geop): + self.graph = graph + self.var2geop = var2geop + self.op = None + self.ascend_helper = AscendHelper() + + def _get_ge_input(self, input_var_name): + assert input_var_name in self.var2geop, "var %s not created before" % ( + input_var_name) + return self.var2geop[input_var_name] + + def update_output(self, geop_list, index_list): + output_num = len(self.op.output_names) + assert output_num == len( + index_list + ), "Parser[%s]'s output number[%d] is not equal to parameters number[%d]" % ( + self.parser_name, len(index_list), output_num) + for output_id in range(output_num): + arguments = self.op.output(self.op.output_names[output_id]) + if len(arguments) > 0: + assert len(arguments) == len( + index_list[output_id] + ), "Parser[%s]'s %dth argument number[%d] is not equal to paddle's number[%d]" % ( + self.parser_name, output_id, len( + index_list[output_id]), len(arguments)) + for i in range(len(arguments)): + self.var2geop[arguments[i]] = geop_list[ + index_list[output_id][i]] + + for geop in geop_list: + self.graph.add_op(geop) + + def apply(self, op): + self.op = op + assert self.op.type == self.parser_name, "op [%s] != parser_name[%s]" % ( + self.op.type, self.parser_name) + #print("begin to parse op %s" % (self.parser_name)) + geop_list, index_list = self._apply() + self.update_output(geop_list, index_list) + + def _mark_as_input(self, ge_tensor): + global global_input_cnt + global_input_cnt += 1 + self.var2geop["geinput." + str(global_input_cnt)] = ge_tensor + + def _accumulated_op_id(self): + global global_cnt + global_cnt += 1 + name = "." + str(global_cnt) + return name + + def _create_ge_tensor(self, shape, dtype, value): + tensor_desc = core.GETensorDesc(core.GEShape(shape), + core.GEFormat.FORMAT_ND, + self.ascend_helper.dtype2ge(dtype)) + tensor = core.GETensor(tensor_desc) + + data = (value * np.ones( + (shape))).reshape(shape).astype(self.ascend_helper.dtype2np(dtype)) + buf = data.tobytes() + data_8 = np.frombuffer(buf, dtype=np.uint8) + tensor.set_data(data_8) + return tensor + + def _get_ge_tensor(self, shape, dtype, value_list): + tensor_desc = core.GETensorDesc(core.GEShape(shape), + core.GEFormat.FORMAT_ND, + self.ascend_helper.dtype2ge(dtype)) + tensor = core.GETensor(tensor_desc) + + data = np.array(value_list).reshape(shape).astype( + self.ascend_helper.dtype2np(dtype)) + buf = data.tobytes() + data_8 = np.frombuffer(buf, dtype=np.uint8) + tensor.set_data(data_8) + + tensor_const = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + + return tensor_const + + def _get_variable(self, shape, dtype, tensor): + if dtype == "int32": + type = core.GEDataType.DT_INT32 + elif dtype == "float32": + type = core.GEDataType.DT_FLOAT + + var = core.GEOperatorFactory.create_operator( + "variable" + self._accumulated_op_id(), "Variable") + var.update_output_desc( + "y", + core.GETensorDesc(core.GEShape(shape), core.GEFormat.FORMAT_ND, + type)) + assign = core.GEOperatorFactory.create_operator( + "assign" + self._accumulated_op_id(), + "Assign").set_input("value", tensor).set_input("ref", var) + + return assign + + def _create_shape_tensor(self): + tensor_desc = core.GETensorDesc(core.GEShape([2]), + core.GEFormat.FORMAT_ND, + core.GEDataType.DT_INT32) + tensor = core.GETensor(tensor_desc) + + data = np.ones((2)).astype("int32").reshape([2]) + data[0] = 64 + buf = data.tobytes() + data_8 = np.frombuffer(buf, dtype=np.uint8) + tensor.set_data(data_8) + return tensor + + def _get_GEtensor_shape(self, tensor): + tensor_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Shape").set_input("x", tensor) + tensor_shape = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", tensor_shape).set_attr_int32("dst_type", 0) + return tensor_shape + + +class AddParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(AddParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_add" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + add = core.GEOperatorFactory.create_operator( + "add" + self._accumulated_op_id(), + "Add").set_input("x1", x).set_input("x2", y) + return [add], [[0]] + + +class DotSubParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotSubParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_sub" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + sub = core.GEOperatorFactory.create_operator( + "sub" + self._accumulated_op_id(), + "Sub").set_input("x1", x).set_input("x2", y) + return [sub], [[0]] + + +class DotMulParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotMulParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_mul" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + mul = core.GEOperatorFactory.create_operator( + "dotmul" + self._accumulated_op_id(), + "Mul").set_input("x1", x).set_input("x2", y) + return [mul], [[0]] + + +class DotDivParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotDivParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_div" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + div = core.GEOperatorFactory.create_operator( + "dotdiv" + self._accumulated_op_id(), + "Div").set_input("x1", x).set_input("x2", y) + return [div], [[0]] + + +class DotPowParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotPowParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_pow" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + pow = core.GEOperatorFactory.create_operator( + "dotpow" + self._accumulated_op_id(), + "Pow").set_input("x1", x).set_input("x2", y) + return [pow], [[0]] + + +class LessParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LessParser, self).__init__(graph, var2geop) + self.parser_name = "less_than" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + less_than = core.GEOperatorFactory.create_operator( + "less_than" + self._accumulated_op_id(), + "Less").set_input("x1", x).set_input("x2", y) + return [less_than], [[0]] + + +class MaxParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MaxParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_max" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + max_out = core.GEOperatorFactory.create_operator( + "max" + self._accumulated_op_id(), + "Maximum").set_input("x1", x).set_input("x2", y) + return [max_out], [[0]] + + +class MinParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MinParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_min" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + min_out = core.GEOperatorFactory.create_operator( + "min" + self._accumulated_op_id(), + "Minimum").set_input("x1", x).set_input("x2", y) + return [min_out], [[0]] + + +## cal +class LogParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LogParser, self).__init__(graph, var2geop) + self.parser_name = "log" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + log = core.GEOperatorFactory.create_operator( + "log" + self._accumulated_op_id(), "Log").set_input("x", x) + return [log], [[0]] + + +class SqrtParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SqrtParser, self).__init__(graph, var2geop) + self.parser_name = "sqrt" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + sqrt = core.GEOperatorFactory.create_operator( + "sqrt" + self._accumulated_op_id(), "Sqrt").set_input("x", x) + return [sqrt], [[0]] + + +class PowParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(PowParser, self).__init__(graph, var2geop) + self.parser_name = "pow" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + factor = self.op.attr("factor") + pow_value = core.GEOperatorFactory.create_operator( + "pow" + self._accumulated_op_id(), + "Power").set_input("x", x).set_attr_float( + "power", + factor).set_attr_float("scale", + 1.0).set_attr_float("shift", 0.0) + return [pow_value], [[0]] + + +class SquareParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SquareParser, self).__init__(graph, var2geop) + self.parser_name = "square" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + square = core.GEOperatorFactory.create_operator( + "square" + self._accumulated_op_id(), "Square").set_input("x", x) + return [square], [[0]] + + +class SumParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SumParser, self).__init__(graph, var2geop) + self.parser_name = "sum" + + def _apply(self): + len_list = len(self.op.input_arg_names) + if len_list < 2: + assert False, "the size of input list must large or equal 2" + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + sum = core.GEOperatorFactory.create_operator( + "sum" + self._accumulated_op_id(), + "Add").set_input("x1", x).set_input("x2", y) + for i in range(2, len_list): + y = self._get_ge_input(self.op.input_arg_names[i]) + sum = core.GEOperatorFactory.create_operator( + "sum" + self._accumulated_op_id(), + "Add").set_input("x1", sum).set_input("x2", y) + return [sum], [[0]] + + +class LogicalNotParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LogicalNotParser, self).__init__(graph, var2geop) + self.parser_name = "logical_not" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + logical_not = core.GEOperatorFactory.create_operator( + "logical_not" + self._accumulated_op_id(), + "LogicalNot").set_input("x", x) + return [logical_not], [[0]] + + +class MeanParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MeanParser, self).__init__(graph, var2geop) + self.parser_name = "mean" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + mean = core.GEOperatorFactory.create_operator( + "mean" + self._accumulated_op_id(), "ReduceMeanD").set_input( + "x", x).set_attr_bool("keep_dims", + False).set_attr_vec_int32("axes", []) + return [mean], [[0]] + + +class ReduceSumParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReduceSumParser, self).__init__(graph, var2geop) + self.parser_name = "reduce_sum" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + axes = self.op.attr("dim") + keep_dims = self.op.attr("keep_dim") + reduce_all = self.op.attr("reduce_all") + x_shape = self.op.block.var(self.op.input_arg_names[0]).shape + if reduce_all: + axes = list(range(len(x_shape))) + reduce_sum = core.GEOperatorFactory.create_operator( + "reduce_sum" + self._accumulated_op_id(), + "ReduceSumD").set_input("x", x, 0).set_attr_vec_int32( + "axes", axes).set_attr_bool("keep_dims", keep_dims) + return [reduce_sum], [[0]] + + +#class IncrementParser(AscendParserBase): +# def __init__(self, graph, var2geop): +# super(IncrementParser, self).__init__(graph, var2geop) +# self.parser_name = "increment" +# +# def _apply(self): +# x = self._get_ge_input(self.op.input_arg_names[0]) +# step = self.op.attr("step") #self._get_ge_input(self.op.input_arg_names[1]) +# print("step: ", step) +# +# increment = core.GEOperatorFactory.create_operator("adds" + self._accumulated_op_id(), "Adds").set_input("x", x).set_attr_float("value", step) #set_input("x2", bias) +# +# return [increment] + + +## matrix cal +class MatMulParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MatMulParser, self).__init__(graph, var2geop) + self.parser_name = "matmul" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + transpose_x = self.op.attr("transpose_X") + transpose_y = self.op.attr("transpose_Y") + + x1_shape = self.op.block.var(self.op.input_arg_names[0]).shape + x2_shape = self.op.block.var(self.op.input_arg_names[1]).shape + + if len(x1_shape) > 2: + matmul = core.GEOperatorFactory.create_operator( + "matmul" + self._accumulated_op_id(), "BatchMatMul").set_input( + "x1", x).set_input("x2", y).set_attr_bool( + "adj_x1", + transpose_x).set_attr_bool("adj_x2", transpose_y) + elif len(x1_shape) == 2: + matmul = core.GEOperatorFactory.create_operator( + "matmul" + self._accumulated_op_id(), + "MatMul").set_input("x1", x).set_input("x2", y).set_attr_bool( + "transpose_x1", + transpose_x).set_attr_bool("transpose_x2", transpose_y) + else: + assert False, "not support" + return [matmul], [[0]] + + +class MulParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MulParser, self).__init__(graph, var2geop) + self.parser_name = "mul" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + y = self._get_ge_input(self.op.input_arg_names[1]) + x_num_col_dims = self.op.attr("x_num_col_dims") + y_num_col_dims = self.op.attr("y_num_col_dims") + shape_x1 = self.op.block.var(self.op.input_arg_names[0]).shape + shape_x2 = self.op.block.var(self.op.input_arg_names[1]).shape + + if x_num_col_dims == 1 and y_num_col_dims == 1: + if len(shape_x1) == 2 and len(shape_x2) == 2: + matmul = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "MatMul").set_input("x1", x).set_input("x2", y) + elif len(shape_x1) == 3 and len(shape_x2) == 2: + flatten_x1 = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), + "Flatten").set_input("x", x) + matmul = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "MatMul").set_input("x1", flatten_x1, + 0).set_input("x2", y, 0) + else: + assert False, "not support" + else: + if len(shape_x1) == 3 and len(shape_x2) == 2: + assert x_num_col_dims == 2, "only support 2" + flatten_x1 = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), + "FlattenV2").set_input("x", x).set_attr_int32( + "axis", 0).set_attr_int32("end_axis", 1) + matmul_m = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "MatMul").set_input("x1", flatten_x1, + 0).set_input("x2", y, 0) + matmul_transpose = core.GEOperatorFactory.create_operator( + "transpose" + self._accumulated_op_id(), + "TransposeD").set_input("x", matmul_m).set_attr_vec_int32( + "perm", [1, 0]) + tensor = self._create_ge_tensor( + [3], 2, [shape_x2[1], shape_x1[0], shape_x1[1]]) + const_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + reshape_matmul = core.GEOperatorFactory.create_operator( + "reshape" + self._accumulated_op_id(), + "Reshape").set_input("x", matmul_transpose).set_input( + "shape", const_shape).set_attr_int32("axis", 0) + matmul = core.GEOperatorFactory.create_operator( + "transpose" + self._accumulated_op_id(), + "TransposeD").set_input("x", + reshape_matmul).set_attr_vec_int32( + "perm", [1, 2, 0]) + else: + assert False, "not support" + + return [matmul], [[0]] + + +class LayerNormParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LayerNormParser, self).__init__(graph, var2geop) + self.parser_name = "layer_norm" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[2]) + scale = self._get_ge_input(self.op.input_arg_names[1]) + bias = self._get_ge_input(self.op.input_arg_names[0]) + epsilon = self.op.attr("epsilon") + begin_norm_axis = self.op.attr("begin_norm_axis") + x_dtype = self.op.block.var(self.op.input_arg_names[2]).dtype + + shape_tensor = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) + scale_expand = core.GEOperatorFactory.create_operator( + "broadcast_to_d" + self._accumulated_op_id(), + "BroadcastTo").set_input("x", + scale).set_input("shape", shape_tensor) + bias_expand = core.GEOperatorFactory.create_operator( + "broadcast_to_d" + self._accumulated_op_id(), + "BroadcastTo").set_input("x", + bias).set_input("shape", shape_tensor) + layer_norm = core.GEOperatorFactory.create_operator( + "layer_norm" + self._accumulated_op_id(), + "LayerNorm").set_input("x", x).set_input( + "gamma", + scale_expand).set_input("beta", bias_expand).set_attr_int32( + "begin_norm_axis", begin_norm_axis).set_attr_int32( + "begin_params_axis", + begin_norm_axis).set_attr_float("epsilon", epsilon) + + cast_dtype = 0 if self.ascend_helper.dtype2paddle_inv_map[str( + x_dtype)] == 0 else 1 + y = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", layer_norm, + 0).set_attr_int32("dst_type", cast_dtype) + mean = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", layer_norm, + 1).set_attr_int32("dst_type", cast_dtype) + variance = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", layer_norm, + 2).set_attr_int32("dst_type", cast_dtype) + return [y, mean, variance], [[1], [2], [0]] + + +## activate function +class ReluParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReluParser, self).__init__(graph, var2geop) + self.parser_name = "relu" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + relu = core.GEOperatorFactory.create_operator( + "relu" + self._accumulated_op_id(), "Relu").set_input("x", x) + return [relu], [[0]] + + +class GeluParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(GeluParser, self).__init__(graph, var2geop) + self.parser_name = "gelu" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + gelu = core.GEOperatorFactory.create_operator( + "gelu" + self._accumulated_op_id(), "Gelu").set_input("x", x) + return [gelu], [[0]] + + +class TanhParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TanhParser, self).__init__(graph, var2geop) + self.parser_name = "tanh" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + tanh = core.GEOperatorFactory.create_operator( + "tanh" + self._accumulated_op_id(), "Tanh").set_input("x", x) + return [tanh], [[0]] + + +## loss function +class SoftmaxWithCrossEntropyParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SoftmaxWithCrossEntropyParser, self).__init__(graph, var2geop) + self.parser_name = "softmax_with_cross_entropy" + + def _apply(self): + label = self._get_ge_input(self.op.input_arg_names[0]) + logits = self._get_ge_input(self.op.input_arg_names[1]) + cls_num = self.op.block.var(self.op.input_arg_names[1]).shape[1] + + softmax = core.GEOperatorFactory.create_operator( + "softmax" + self._accumulated_op_id(), + "SoftmaxV2").set_input("x", logits) + label = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", label).set_attr_int32("dst_type", 3) + + tensoron = self._create_ge_tensor([1], 5, 1) + on = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensoron) + tensoroff = self._create_ge_tensor([1], 5, 0) + off = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensoroff) + self._mark_as_input(on) + self._mark_as_input(off) + onehot = core.GEOperatorFactory.create_operator( + "onehot" + self._accumulated_op_id(), + "OneHotD").set_input("x", + label).set_input("on_value", on).set_input( + "off_value", + off).set_attr_int32("depth", cls_num) + squeeze = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "Squeeze").set_input("x", onehot) + + loss_all = core.GEOperatorFactory.create_operator( + "loss" + self._accumulated_op_id(), + "SoftmaxCrossEntropyWithLogits").set_input("features", + logits).set_input( + "labels", squeeze) + loss = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", loss_all, 0).set_attr_int32("dst_type", 0) + loss_expand = core.GEOperatorFactory.create_operator( + "unsqueeze" + self._accumulated_op_id(), + "Unsqueeze").set_input("x", loss).set_attr_vec_int32("axes", [1]) + return [label, softmax, loss_expand], [[2], [1]] + + +class SoftMaxParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SoftMaxParser, self).__init__(graph, var2geop) + self.parser_name = "softmax" + + def _apply(self): + logits = self._get_ge_input(self.op.input_arg_names[0]) + axes = self.op.attr("axis") + + softmax = core.GEOperatorFactory.create_operator( + "softmax" + self._accumulated_op_id(), + "SoftmaxV2").set_input("x", + logits).set_attr_vec_int32("axes", [axes]) + return [softmax], [[0]] + + +## general +class ShapeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ShapeParser, self).__init__(graph, var2geop) + self.parser_name = "shape" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) + return [shape], [[0]] + + +class FillConstantParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(FillConstantParser, self).__init__(graph, var2geop) + self.parser_name = "fill_constant" + + def _apply(self): + shape = self.op.attr("shape") + dtype = self.op.attr("dtype") + value = self.op.attr("value") + + tensor = self._create_ge_tensor(shape, dtype, value) + const = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + self._mark_as_input(const) + if self.op.block.var(self.op.output('Out')[0]).persistable: + #print("%s is Persistable in fill_constant" % + # (self.op.output('Out')[0])) + var = core.GEOperatorFactory.create_operator( + self.op.output('Out')[0], "Variable") + var.update_output_desc( + "y", + core.GETensorDesc(core.GEShape(shape), core.GEFormat.FORMAT_ND, + core.GEDataType.DT_FLOAT)) + assign = core.GEOperatorFactory.create_operator( + "assign" + self._accumulated_op_id(), + "Assign").set_input("value", const).set_input("ref", var) + return [const], [[0]] + return [const], [[0]] + + +class TruncatedNormalParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TruncatedNormalParser, self).__init__(graph, var2geop) + self.parser_name = "truncated_gaussian_random" + + def _apply(self): + shape = self.op.attr("shape") + dtype = self.op.attr("dtype") + mean = self.op.attr("mean") + std = self.op.attr("std") + seed = self.op.attr("seed") + + tensor1 = self._create_ge_tensor([len(shape)], 2, shape) + shape_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor1) + tensor2 = self._create_ge_tensor([1], dtype, mean) + mean_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor2) + tensor3 = self._create_ge_tensor([1], dtype, std) + std_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor3) + tensor4 = self._create_ge_tensor([1], dtype, mean - 2 * std) + min_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor4) + tensor5 = self._create_ge_tensor([1], dtype, mean + 2 * std) + max_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor5) + + self._mark_as_input(shape_tensor) + self._mark_as_input(mean_tensor) + self._mark_as_input(std_tensor) + self._mark_as_input(min_tensor) + self._mark_as_input(max_tensor) + + truncated_normal = core.GEOperatorFactory.create_operator( + "truncated_normal" + self._accumulated_op_id(), + "ParameterizedTruncatedNormal").set_input( + "shape", + shape_tensor).set_input("means", mean_tensor).set_input( + "stdevs", + std_tensor).set_input("min", min_tensor).set_input( + "max", max_tensor).set_attr_int32("seed", 0) + + ## wirte the output of truncatedNormal from startup_program to main_program + if self.op.block.var(self.op.output('Out')[0]).persistable: + #print("%s is Persistable in truncated_normal" % + # (self.op.output('Out')[0])) + var = core.GEOperatorFactory.create_operator( + self.op.output('Out')[0], "Variable") + var.update_output_desc( + "y", + core.GETensorDesc(core.GEShape(shape), core.GEFormat.FORMAT_ND, + core.GEDataType.DT_FLOAT)) + assign = core.GEOperatorFactory.create_operator( + "assign" + self._accumulated_op_id(), + "Assign").set_input("value", + truncated_normal).set_input("ref", var) + return [ + shape_tensor, mean_tensor, std_tensor, min_tensor, max_tensor, + truncated_normal + ], [[-1]] + #else: + # print( + # "self.op.output('Out')[0] is not persistable in truncated_noraml" + # ) + return [truncated_normal], [[0]] + + +class GatherParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(GatherParser, self).__init__(graph, var2geop) + self.parser_name = "gather" + + def _apply(self): + index = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + clo = self.op.block.var(self.op.input_arg_names[1]).shape[-1] + + gather = core.GEOperatorFactory.create_operator( + "gather" + self._accumulated_op_id(), + "Gather").set_input("x", x).set_input("indices", + index).set_attr_bool( + "validate_indices", True) + return [gather], [[0]] + + +class ScatterParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ScatterParser, self).__init__(graph, var2geop) + self.parser_name = "scatter" + + def _apply(self): + index = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + updates = self._get_ge_input(self.op.input_arg_names[2]) + overwrite = self.op.attr("overwrite") + index_shape = self.op.block.var(self.op.input_arg_names[0]).shape + + if len(index_shape) == 1: + index = core.GEOperatorFactory.create_operator( + "unsqueeze" + self.getid(), + "Unsqueeze").set_input("x", + index).set_attr_vec_int32("axes", [1]) + if not overwrite: + scatter_value = core.GEOperatorFactory.create_operator( + "scatter" + self._accumulated_op_id(), + "TensorScatterAdd").set_input("x", x).set_input( + "indices", index).set_input("updates", updates) + else: + scatter_value = core.GEOperatorFactory.create_operator( + "scatter" + self._accumulated_op_id(), + "TensorScatterUpdate").set_input("x", x).set_input( + "indices", index).set_input("updates", updates) + return [x, index, updates, scatter_value], [[-1]] + + +class CastParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(CastParser, self).__init__(graph, var2geop) + self.parser_name = "cast" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + dtype = self.op.attr("out_dtype") + cast = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x).set_attr_int32("dst_type", dtype) + return [cast], [[0]] + + +class AssignParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(AssignParser, self).__init__(graph, var2geop) + self.parser_name = "assign" + + def _apply(self): + const = self._get_ge_input(self.op.input_arg_names[0]) + var = self._get_ge_input(self.op.input_arg_names[1]) + assign = core.GEOperatorFactory.create_operator( + "assign" + self._accumulated_op_id(), + "Assign").set_input("value", const).set_input("ref", var) + return [assign], [[0]] + + +class ScaleParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ScaleParser, self).__init__(graph, var2geop) + self.parser_name = "scale" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + scale = self.op.attr("scale") + bias = self.op.attr("bias") + bias_after_scale = self.op.attr("bias_after_scale") + + if bias_after_scale: + scale_value = core.GEOperatorFactory.create_operator( + "scale" + self._accumulated_op_id(), + "Power").set_input("x", x).set_attr_float( + "power", + 1.0).set_attr_float("scale", + scale).set_attr_float("shift", bias) + else: + x_add_bias = core.GEOperatorFactory.create_operator( + "adds" + self._accumulated_op_id(), + "Adds").set_input("x", x).set_attr_float("value", bias) + scale_value = core.GEOperatorFactory.create_operator( + "scale" + self._accumulated_op_id(), + "Power").set_input("x", x_add_bias).set_attr_float( + "power", + 1.0).set_attr_float("scale", + scale).set_attr_float("shift", 0.0) + return [scale_value], [[0]] + + +class SliceParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SliceParser, self).__init__(graph, var2geop) + self.parser_name = "slice" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + axes = self.op.attr("axes") + starts = self.op.attr("starts") + ends = self.op.attr("ends") + + x_shape = self.op.block.var(self.op.input_arg_names[0]).shape + len_shape = len(x_shape) + axes_cor = list(range(len_shape)) + starts_cor, ends_cor = [], [] + cnt = 0 + for i in range(len_shape): + starts_cor.append(starts[cnt] if i in axes else 0) + if i in axes and ends[cnt] <= x_shape[i]: + ends_cor.append(ends[cnt]) + else: + ends_cor.append(x_shape[i]) + if i in axes: + cnt += 1 + size = [ends_cor[i] - starts_cor[i] for i in range(len(axes_cor))] + + assert len(axes_cor) == len(starts_cor) == len( + ends_cor), "the three fields must have same size" + slice_value = core.GEOperatorFactory.create_operator( + "slice" + self._accumulated_op_id(), + "SliceD").set_input("x", x).set_attr_vec_int32( + "offsets", starts_cor).set_attr_vec_int32("size", size) + + return [slice_value], [[0]] + + +class ReshapeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReshapeParser, self).__init__(graph, var2geop) + self.parser_name = "reshape2" + + def _apply(self): + org_shape = self.op.block.var(self.op.input_arg_names[0]).shape + assert org_shape.count(-1) == 0, "do not allow the dim is -1" + shape = self.op.attr("shape") + for cnt in range(len(shape)): + if shape[cnt] == 0: + shape[cnt] = org_shape[cnt] + + if -1 in shape: + assert shape.count(-1) == 1, "only allow one dim is -1" + mul_res_org = reduce(lambda x, y: x * y, org_shape) + mul_res_refine = reduce(lambda x, y: x * y, shape) * -1 + idx = shape.index(-1) + shape[idx] = mul_res_org // mul_res_refine + + x = self._get_ge_input(self.op.input_arg_names[0]) + tensor = self._create_ge_tensor([len(shape)], 2, shape) + const_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + reshape = core.GEOperatorFactory.create_operator( + "reshape" + self._accumulated_op_id(), + "Reshape").set_input("x", x).set_input("shape", + const_shape).set_attr_int32( + "axis", 0) + x_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) + + return [x_shape, reshape], [[1], [0]] + + +class TransposeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TransposeParser, self).__init__(graph, var2geop) + self.parser_name = "transpose2" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + perm = self.op.attr("axis") + transpose = core.GEOperatorFactory.create_operator( + "transpose" + self._accumulated_op_id(), + "TransposeD").set_input("x", x).set_attr_vec_int32("perm", perm) + x_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) + + return [x_shape, transpose], [[1], [0]] + + +class AccuracyParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(AccuracyParser, self).__init__(graph, var2geop) + self.parser_name = "accuracy" + + def _apply(self): + pred = self._get_ge_input(self.op.input_arg_names[0]) + label = self._get_ge_input(self.op.input_arg_names[1]) + logits = self._get_ge_input(self.op.input_arg_names[2]) + + pred = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", pred).set_attr_int32("dst_type", 3) + label = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", label).set_attr_int32("dst_type", 3) + equal = core.GEOperatorFactory.create_operator( + "equal" + self._accumulated_op_id(), + "Equal").set_input("x1", pred).set_input("x2", label) + cast = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", equal).set_attr_int32("dst_type", 0) + acc = core.GEOperatorFactory.create_operator( + "mean" + self._accumulated_op_id(), "ReduceMeanD").set_input( + "x", cast).set_attr_bool("keep_dims", + False).set_attr_vec_int32("axes", []) + correct = core.GEOperatorFactory.create_operator( + "sum" + self._accumulated_op_id(), "ReduceSumD").set_input( + "x", cast).set_attr_bool("keep_dims", + False).set_attr_vec_int32("axes", []) + ones_tensor = core.GEOperatorFactory.create_operator( + "oneslike" + self._accumulated_op_id(), + "OnesLike").set_input("x", label) + ones_tensor = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", ones_tensor).set_attr_int32("dst_type", 0) + total = core.GEOperatorFactory.create_operator( + "sum" + self._accumulated_op_id(), + "ReduceSumD").set_input("x", ones_tensor).set_attr_bool( + "keep_dims", False).set_attr_vec_int32("axes", []) + + return [acc, correct, total], [[0], [1], [2]] + + +class TopkParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TopkParser, self).__init__(graph, var2geop) + self.parser_name = "top_k" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + k = self.op.attr("k") + + tensor = self._create_ge_tensor([1], 2, k) + const_k = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + cast_x = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x).set_attr_int32("dst_type", 1) + topk = core.GEOperatorFactory.create_operator( + "topk" + self._accumulated_op_id(), + "TopK").set_input("x", cast_x).set_input("k", const_k) + value = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", topk, 0).set_attr_int32("dst_type", 0) + index = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", topk, 1).set_attr_int32("dst_type", 0) + return [value, index], [[1], [0]] + + +class LookupTableParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LookupTableParser, self).__init__(graph, var2geop) + self.parser_name = "lookup_table" + + def _apply(self): + ids = self._get_ge_input(self.op.input_arg_names[0]) + w = self._get_ge_input(self.op.input_arg_names[1]) + + ids_squeeze = core.GEOperatorFactory.create_operator( + "squeeze" + self._accumulated_op_id(), + "Squeeze").set_input("x", ids).set_attr_vec_int32("axes", [-1]) + out = core.GEOperatorFactory.create_operator( + "lookup" + self._accumulated_op_id(), + "Gather").set_input("x", w).set_input("indices", ids_squeeze) + return [out], [[0]] + + +class StackParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(StackParser, self).__init__(graph, var2geop) + self.parser_name = "stack" + + def _apply(self): + tiles = len(self.op.input_arg_names) + data_x_lst = [] + for index in range(tiles): + data_x_lst.append(self._get_ge_input( + self.op.input_arg_names[index])) + axis = self.op.attr("axis") + + data_x = data_x_lst[0] + tensor = self._create_ge_tensor([1], 2, axis) + tensor_axis = core.GEOperatorFactory.create_operator( + "axis" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + expand = core.GEOperatorFactory.create_operator( + "expand" + self._accumulated_op_id(), + "ExpandDims").set_input("x", data_x).set_input("axis", tensor_axis) + + stack = core.GEOperatorFactory.create_operator( + "stack" + self._accumulated_op_id(), "TileWithAxis").set_input( + "x", + expand).set_attr_int32("axis", + axis).set_attr_int32("tiles", tiles) + + return [stack], [[0]] + + +class UnSqueezeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(UnSqueezeParser, self).__init__(graph, var2geop) + self.parser_name = "unsqueeze2" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + axes = self.op.attr('axes') + + output = core.GEOperatorFactory.create_operator( + "unsqueeze" + self._accumulated_op_id(), + "Unsqueeze").set_input("x", x).set_attr_vec_int32("axes", axes) + shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Shape").set_input("x", output) + return [shape, output], [[1], [0]] + + +## parallel +class AllGatherParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(AllGatherParser, self).__init__(graph, var2geop) + self.parser_name = "c_allgather" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + rank_size = self.op.attr("rank_size") + group = self.op.attr("group") + + allgather = core.GEOperatorFactory.create_operator( + "allgather" + self._accumulated_op_id(), + "HcomAllGather").set_input("x", x).set_attr_int32( + "rank_size", rank_size).set_attr_string("group", group) + return [allgather], [[0]] + + +class AllReduceParser(AscendParserBase): + + def __init__(self, graph, var2geop, reduction): + super(AllReduceParser, self).__init__(graph, var2geop) + self.parser_name = "c_allreduce_" + reduction + self.reduction = reduction + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + reduction = self.reduction + ring_id = self.op.attr("ring_id") + group = "hcom_group_" + str(ring_id) + fusion = None #self.op.attr("fusion") + fusion_id = None #self.op.attr("fusion_id") + + allreduce = core.GEOperatorFactory.create_operator( + "allreduce" + self._accumulated_op_id(), + "HcomAllReduce").set_input("x", x).set_attr_string( + "reduction", reduction).set_attr_string("group", group) + if fusion is not None: + allreduce.set_attr_int32("fusion", fusion) + + if fusion_id is not None: + allreduce.set_attr_int32("fusion_id", fusion_id) + return [allreduce], [[0]] + + +class AllReduceSumParser(AllReduceParser): + + def __init__(self, graph, var2geop): + super(AllReduceSumParser, self).__init__(graph, var2geop, 'sum') + + +class AllReduceMaxParser(AllReduceParser): + + def __init__(self, graph, var2geop): + super(AllReduceMaxParser, self).__init__(graph, var2geop, 'max') + + +class BroadcastParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(BroadcastParser, self).__init__(graph, var2geop) + self.parser_name = "c_broadcast" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + root_rank = self.op.attr("root_rank") + group = self.op.attr("group") + + broadcast = core.GEOperatorFactory.create_operator( + "broadcast" + self._accumulated_op_id(), + "HcomBroadcast").set_input("x", x).set_attr_int32( + "root_rank", root_rank).set_attr_string("group", group) + return [broadcast], [[0]] + + +class ReduceScatterParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReduceScatterParser, self).__init__(graph, var2geop) + self.parser_name = "c_reduce_scatter" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + reduction = self.op.attr("reduction") + group = self.op.attr("group") + rank_size = self.op.attr("rank_size") + + reduce_scatter = core.GEOperatorFactory.create_operator( + "reducescatter" + self._accumulated_op_id(), + "HcomReduceScatter").set_input("x", x).set_attr_string( + "reduction", + reduction).set_attr_string("group", group).set_attr_int32( + "rank_size", rank_size) + return [reduce_scatter], [[0]] + + +class SendParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SendParser, self).__init__(graph, var2geop) + self.parser_name = "c_send" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + sr_tag = self.op.attr("sr_tag") + dest_rank = self.op.attr("dest_rank") + group = self.op.attr("group") + + send = core.GEOperatorFactory.create_operator( + "send" + self._accumulated_op_id(), "HcomSend").set_input( + "x", x).set_attr_int32("sr_tag", sr_tag).set_attr_int32( + "dest_rank", dest_rank).set_attr_string("group", group) + return [send], [[0]] + + +class ReceiveParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReceiveParser, self).__init__(graph, var2geop) + self.parser_name = "c_receive" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + sr_tag = self.op.attr("sr_tag") + src_rank = self.op.attr("src_rank") + group = self.op.attr("group") + shape = self.op.attr("shape") + dtype = self.op.attr("dtype") + + receive = core.GEOperatorFactory.create_operator( + "receive" + self._accumulated_op_id(), + "HcomReceive").set_input("x", x).set_attr_int32( + "sr_tag", + sr_tag).set_attr_int32("src_rank", src_rank).set_attr_string( + "group", group).set_attr_vec_int32("shape", + shape).set_attr_int32( + "dtype", dtype) + return [receive], [[0]] + + +class RangeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(RangeParser, self).__init__(graph, var2geop) + self.parser_name = "range" + + def _apply(self): + # TODO not support range type yet + start = self._get_ge_input(self.op.input_arg_names[0]) + end = self._get_ge_input(self.op.input_arg_names[1]) + delta = self._get_ge_input(self.op.input_arg_names[2]) + + ge_range = core.GEOperatorFactory.create_operator( + "range" + self._accumulated_op_id(), "Range")\ + .set_input("start", end)\ + .set_input("limit", start) \ + .set_input("delta", delta) + + return [ge_range], [[0]] + + +class UniformRandomParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(UniformRandomParser, self).__init__(graph, var2geop) + self.parser_name = "uniform_random" + + def _apply(self): + shape = self.op.attr("shape") + + min_v = self.op.attr("min") + max_v = self.op.attr("max") + seed = self.op.attr("seed") + dtype = self.op.attr("dtype") + assert max_v > min_v, "assert max_v > min_v, but received " + \ + "as max_v={}, min_v={} ".format(max_v, min_v) + + tensor1 = self._create_ge_tensor([len(shape)], 2, shape) + shape_tensor = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor1) + + ge_ur = core.GEOperatorFactory.create_operator( + "uniform_random" + self._accumulated_op_id(), "RandomUniform")\ + .set_input("shape", shape_tensor)\ + .set_attr_dtype("dtype", self.ascend_helper.dtype2ge(dtype)) \ + .set_attr_int32("seed", seed)\ + .set_attr_int32("seed2", seed) + + scale = max_v - min_v + + scale_value = core.GEOperatorFactory.create_operator( + "scale" + self._accumulated_op_id(), + "Power").set_input("x", ge_ur).set_attr_float( + "power", + 1.0).set_attr_float("scale", + scale).set_attr_float("shift", min_v) + + return [scale_value], [[0]] + + +class EqualParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(EqualParser, self).__init__(graph, var2geop) + self.parser_name = "equal" + + def _apply(self): + data_x1 = self._get_ge_input(self.op.input_arg_names[0]) + data_x2 = self._get_ge_input(self.op.input_arg_names[1]) + equal = core.GEOperatorFactory.create_operator("equal" \ + + self._accumulated_op_id(), "Equal")\ + .set_input("x1", data_x1)\ + .set_input("x2", data_x2) + return [equal], [[0]] + + +class ExpandParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ExpandParser, self).__init__(graph, var2geop) + self.parser_name = "expand" + + def _apply(self): + data_x1_shape = self._get_ge_input(self.op.input_arg_names[0]) + expand_times = self.op.attr('expand_times') + + tensor = self._create_ge_tensor([len(expand_times)], 2, expand_times) + expand_tensor = core.GEOperatorFactory.\ + create_operator("const" + self._accumulated_op_id(), "Const")\ + .set_attr_tensor("value", tensor) + + assign = core.GEOperatorFactory\ + .create_operator("tile" + self._accumulated_op_id(), "Tile")\ + .set_input("x", data_x1_shape)\ + .set_input("multiples", expand_tensor) + return [assign], [[0]] + + +class SqueezeParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SqueezeParser, self).__init__(graph, var2geop) + self.parser_name = "squeeze2" + + def _apply(self): + tensor = self._get_ge_input(self.op.input_arg_names[0]) + axes = self.op.attr("axes") + + data_squeezed = core.GEOperatorFactory\ + .create_operator("squeeze" + self._accumulated_op_id(), "Squeeze")\ + .set_input("x", tensor)\ + .set_attr_vec_int32("axes", axes) + shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Shape").set_input("x", data_squeezed) + return [shape, data_squeezed], [[1], [0]] + + +#****************************************************************# +#*************************** *************************# +#*************************** *************************# +#*************************** GradParser *************************# +#*************************** *************************# +#*************************** *************************# +#****************************************************************# +## grad +class ReduceSumGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReduceSumGradParser, self).__init__(graph, var2geop) + self.parser_name = "reduce_sum_grad" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + input = self._get_ge_input(self.op.input_arg_names[1]) + + shape_tensor = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Shape").set_input("x", input, 0) + tensoron = self._create_ge_tensor([1], 2, -1) + const = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensoron) + self._mark_as_input(const) + + reduce_sum = core.GEOperatorFactory.create_operator( + "broadcast_to_d" + self._accumulated_op_id(), + "BroadcastTo").set_input("x", x).set_input("shape", shape_tensor) + #reduce_sum = core.GEOperatorFactory.create_operator("expand" + self._accumulated_op_id(), "ExpandDims").set_input("x", reduce_sum).set_input("axis", const) + + return [reduce_sum], [[0]] + + +class MatMulGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MatMulGradParser, self).__init__(graph, var2geop) + self.parser_name = "matmul_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + y = self._get_ge_input(self.op.input_arg_names[2]) + transpose_x = self.op.attr("transpose_X") + transpose_y = self.op.attr("transpose_Y") + + out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape + x_shape = self.op.block.var(self.op.input_arg_names[1]).shape + y_shape = self.op.block.var(self.op.input_arg_names[2]).shape + + if len(x_shape) > 2: + if transpose_y: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "BatchMatMul").set_input("x1", out_grad).set_input( + "x2", + y).set_attr_bool("adj_x1", + False).set_attr_bool("adj_x2", False) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "BatchMatMul").set_input("x1", out_grad).set_input( + "x2", + x).set_attr_bool("adj_x1", + True).set_attr_bool("adj_x2", False) + else: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "BatchMatMul").set_input("x1", out_grad).set_input( + "x2", + y).set_attr_bool("adj_x1", + False).set_attr_bool("adj_x2", True) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "BatchMatMul").set_input( + "x1", x).set_input("x2", out_grad).set_attr_bool( + "adj_x1", True).set_attr_bool("adj_x2", False) + else: + if transpose_y: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", out_grad).set_input( + "x2", y).set_attr_bool("transpose_x1", + False).set_attr_bool( + "transpose_x2", False) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", out_grad).set_input( + "x2", x).set_attr_bool("transpose_x1", + True).set_attr_bool( + "transpose_x2", False) + else: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", out_grad).set_input( + "x2", y).set_attr_bool("transpose_x1", + False).set_attr_bool( + "transpose_x2", True) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", x).set_input( + "x2", out_grad).set_attr_bool("transpose_x1", + True).set_attr_bool( + "transpose_x2", False) + + return [x_grad, y_grad], [[0], [1]] + + +class MulGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MulGradParser, self).__init__(graph, var2geop) + self.parser_name = "mul_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + y = self._get_ge_input(self.op.input_arg_names[2]) + x_num_col_dims = self.op.attr("x_num_col_dims") + y_num_col_dims = self.op.attr("y_num_col_dims") + + shape_out_grad = self.op.block.var(self.op.input_arg_names[0]).shape + shape_x = self.op.block.var(self.op.input_arg_names[1]).shape + shape_y = self.op.block.var(self.op.input_arg_names[2]).shape + + if x_num_col_dims == 1 and y_num_col_dims == 1: + if len(shape_x) == 2 and len(shape_y) == 2: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", out_grad).set_input( + "x2", y).set_attr_bool("transpose_x1", + False).set_attr_bool( + "transpose_x2", True) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", x).set_input( + "x2", out_grad).set_attr_bool("transpose_x1", + True).set_attr_bool( + "transpose_x2", False) + elif len(shape_x) == 3 and len(shape_y) == 2: + flatten_x = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), + "Flatten").set_input("x", x) + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", out_grad).set_input( + "x2", y).set_attr_bool("transpose_x1", + False).set_attr_bool( + "transpose_x2", True) + if len(shape_out_grad) == 2: + x_grad = core.GEOperatorFactory.create_operator( + "unsqueeze" + self._accumulated_op_id(), + "Unsqueeze").set_input("x", x_grad).set_attr_vec_int32( + "axes", [1]) + + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", flatten_x).set_input( + "x2", out_grad).set_attr_bool("transpose_x1", + True).set_attr_bool( + "transpose_x2", False) + else: + if len(shape_x) == 3 and len(shape_y) == 2: + assert x_num_col_dims == 2, "only support 2" + flatten_x = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), + "FlattenV2").set_input("x", x).set_attr_int32( + "axis", 0).set_attr_int32("end_axis", 1) + flatten_out_grad = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), + "FlattenV2").set_input("x", out_grad).set_attr_int32( + "axis", 0).set_attr_int32("end_axis", 1) + + y_unsqueeze = core.GEOperatorFactory.create_operator( + "unsqueeze" + self._accumulated_op_id(), + "Unsqueeze").set_input("x", + y).set_attr_vec_int32("axes", [0]) + y_stack = core.GEOperatorFactory.create_operator( + "stack" + self._accumulated_op_id(), + "TileWithAxis").set_input("x", y_unsqueeze).set_attr_int32( + "axis", 0).set_attr_int32("tiles", shape_out_grad[0]) + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "BatchMatMul").set_input("x1", out_grad).set_input( + "x2", y_stack).set_attr_bool("adj_x1", + False).set_attr_bool( + "adj_x2", True) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "MatMul").set_input("x1", flatten_x).set_input( + "x2", flatten_out_grad).set_attr_bool( + "transpose_x1", + True).set_attr_bool("transpose_x2", False) + + return [x_grad, y_grad], [[0], [1]] + + +class ReluGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReluGradParser, self).__init__(graph, var2geop) + self.parser_name = "relu_grad" + + def _apply(self): + out = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + relu_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "ReluGrad").set_input("gradients", + out_grad).set_input("features", out) + return [relu_grad], [[0]] + + +class SoftmaxWithCrossEntropyGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SoftmaxWithCrossEntropyGradParser, self).__init__(graph, var2geop) + self.parser_name = "softmax_with_cross_entropy_grad" + + def _apply(self): + label = self._get_ge_input(self.op.input_arg_names[0]) + loss_grad = self._get_ge_input(self.op.input_arg_names[1]) + softmax = self._get_ge_input(self.op.input_arg_names[2]) + cls_num = self.op.block.var(self.op.input_arg_names[2]).shape[1] + + label_shape = self.op.block.var(self.op.input_arg_names[0]).shape + loss_grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape + softmax_shape = self.op.block.var(self.op.input_arg_names[2]).shape + + tensoron = self._create_ge_tensor([1], 5, 1) + on = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensoron) + tensoroff = self._create_ge_tensor([1], 5, 0) + off = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensoroff) + self._mark_as_input(on) + self._mark_as_input(off) + + label = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", label).set_attr_int32("dst_type", 3) + onehot = core.GEOperatorFactory.create_operator( + "onehot" + self._accumulated_op_id(), + "OneHotD").set_input("x", + label).set_input("on_value", on).set_input( + "off_value", + off).set_attr_int32("depth", cls_num) + squeeze = core.GEOperatorFactory.create_operator( + "suqeeze" + self._accumulated_op_id(), + "Squeeze").set_input("x", onehot) + sub = core.GEOperatorFactory.create_operator( + "sub" + self._accumulated_op_id(), + "Sub").set_input("x1", softmax).set_input("x2", squeeze) + grad = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "Mul").set_input("x1", loss_grad).set_input("x2", sub) + + return [on, off, label, onehot, grad], [[-1]] + + +class DotMulGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotMulGradParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_mul_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + out_1 = self._get_ge_input(self.op.input_arg_names[1]) + out_2 = self._get_ge_input(self.op.input_arg_names[2]) + + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "Mul").set_input("x1", out_grad).set_input("x2", out_2) + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "Mul").set_input("x1", out_1).set_input("x2", out_grad) + + return [x_grad, y_grad], [[0], [1]] + + +class DotAddGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotAddGradParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_add_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + out_1 = self._get_ge_input(self.op.input_arg_names[1]) + out_2 = self._get_ge_input(self.op.input_arg_names[2]) + out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape + out_1_shape = self.op.block.var(self.op.input_arg_names[1]).shape + out_2_shape = self.op.block.var(self.op.input_arg_names[2]).shape + + x_grad = out_grad + cur_time_x = len(out_grad_shape) - len(out_1_shape) + for i in range(cur_time_x): + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "ReduceSumD").set_input("x", x_grad).set_attr_vec_int32( + "axes", [0]).set_attr_bool("keep_dims", False) + for axis, size in enumerate(out_1_shape): + if size == 1: + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "ReduceSumD").set_input("x", x_grad).set_attr_vec_int32( + "axes", [axis]).set_attr_bool("keep_dims", True) + + y_grad = out_grad + cur_time_y = len(out_grad_shape) - len(out_2_shape) + for i in range(cur_time_y): + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "ReduceSumD").set_input("x", y_grad).set_attr_vec_int32( + "axes", [0]).set_attr_bool("keep_dims", False) + for axis, size in enumerate(out_2_shape): + if size == 1: + y_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "ReduceSumD").set_input("x", y_grad).set_attr_vec_int32( + "axes", [axis]).set_attr_bool("keep_dims", True) + + return [x_grad, y_grad], [[0], [1]] + + +class DotDivGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(DotDivGradParser, self).__init__(graph, var2geop) + self.parser_name = "elementwise_div_grad" + + def _apply(self): + out = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + x = self._get_ge_input(self.op.input_arg_names[2]) + y = self._get_ge_input(self.op.input_arg_names[3]) + + y_power = core.GEOperatorFactory.create_operator( + "power" + self._accumulated_op_id(), + "Power").set_input("x", y).set_attr_float("power", -1) + + tensor_zeros = core.GEOperatorFactory.create_operator( + "zeroslike" + self._accumulated_op_id(), + "ZerosLike").set_input("x", x) + x_zero = core.GEOperatorFactory.create_operator( + "equal" + self._accumulated_op_id(), + "Equal").set_input("x1", x).set_input("x2", tensor_zeros) + x_nozero = core.GEOperatorFactory.create_operator( + "logical_not" + self._accumulated_op_id(), + "LogicalNot").set_input("x", x_zero) + x_nozero_f = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x_nozero).set_attr_int32("dst_type", 0) + x_grad_w = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "Mul").set_input("x1", x_nozero_f).set_input("x2", y_power) + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "Mul").set_input("x1", x_grad_w).set_input("x2", out_grad) + + y_grad_w = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "Mul").set_input("x1", out).set_input("x2", y_power) + y_grad = core.GEOperatorFactory.create_operator( + "mul" + self._accumulated_op_id(), + "Mul").set_input("x1", y_grad_w).set_input("x2", out_grad) + + return [x_grad, y_grad], [[0], [1]] + + +class SoftmaxGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SoftmaxGradParser, self).__init__(graph, var2geop) + self.parser_name = "softmax_grad" + + def _apply(self): + out = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "SoftmaxGrad").set_input("softmax", + out).set_input("grad_softmax", out_grad) + return [x_grad], [[0]] + + +class ReshapeGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(ReshapeGradParser, self).__init__(graph, var2geop) + self.parser_name = "reshape2_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + x_shape = self._get_ge_input(self.op.input_arg_names[1]) + x_shape_list = self.op.block.var(self.op.input_arg_names[1]).shape + + if x_shape_list[0] == 0: + x_shape_delzero = x_shape_list[1:] + tensor = self._create_ge_tensor([len(x_shape_delzero)], 2, + x_shape_delzero) + const_shape = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", tensor) + x_grad = core.GEOperatorFactory.create_operator( + "reshape" + self._accumulated_op_id(), + "Reshape").set_input("x", out_grad).set_input("shape", const_shape) + + return [x_grad], [[0]] + + +class GatherGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(GatherGradParser, self).__init__(graph, var2geop) + self.parser_name = "gather_grad" + + def _apply(self): + index = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + x = self._get_ge_input(self.op.input_arg_names[2]) + + index_shape = self.op.block.var(self.op.input_arg_names[0]).shape + out_grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape + x_shape = self.op.block.var(self.op.input_arg_names[2]).shape + + if len(index_shape) == 1: + index = core.GEOperatorFactory.create_operator( + "unsqueeze" + self._accumulated_op_id(), + "Unsqueeze").set_input("x", + index).set_attr_vec_int32("axes", [1]) + + tensor_zeros = core.GEOperatorFactory.create_operator( + "zeroslike" + self._accumulated_op_id(), + "ZerosLike").set_input("x", x) + x_grad = core.GEOperatorFactory.create_operator( + "scatter" + self._accumulated_op_id(), + "TensorScatterUpdate").set_input("x", tensor_zeros).set_input( + "indices", index).set_input("updates", out_grad) + + return [tensor_zeros, x_grad], [[-1]] + + +class TransposeGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TransposeGradParser, self).__init__(graph, var2geop) + self.parser_name = "transpose2_grad" + + def _apply(self): + out_grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + perm = self.op.attr("axis") + + x_shape = self.op.block.var(self.op.input_arg_names[1]).shape[1:] + out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape + assert list(map(lambda x: out_grad_shape[x], perm)) == list(x_shape) + + x_grad = core.GEOperatorFactory.create_operator( + "transpose" + self._accumulated_op_id(), + "TransposeD").set_input("x", + out_grad).set_attr_vec_int32("perm", perm) + + return [x_grad], [[0]] + + +class LayerNormGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LayerNormGradParser, self).__init__(graph, var2geop) + self.parser_name = "layer_norm_grad" + + def _apply(self): + bias = self._get_ge_input(self.op.input_arg_names[0]) + mean = self._get_ge_input(self.op.input_arg_names[1]) + scale = self._get_ge_input(self.op.input_arg_names[2]) + variance = self._get_ge_input(self.op.input_arg_names[3]) + x = self._get_ge_input(self.op.input_arg_names[4]) + out_grad = self._get_ge_input(self.op.input_arg_names[5]) + x_dtype = self.op.block.var(self.op.input_arg_names[4]).dtype + + x_grad = core.GEOperatorFactory.create_operator( + self.parser_name + self._accumulated_op_id(), + "LayerNormGrad").set_input("dy", out_grad).set_input( + "x", x).set_input("variance", + variance).set_input("mean", mean).set_input( + "gamma", scale) + + cast_dtype = 0 if self.ascend_helper.dtype2paddle_inv_map[str( + x_dtype)] == 0 else 1 + out_x_grad = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x_grad, + 0).set_attr_int32("dst_type", cast_dtype) + out_scale_grad = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x_grad, + 1).set_attr_int32("dst_type", cast_dtype) + out_bias_grad = core.GEOperatorFactory.create_operator( + "cast" + self._accumulated_op_id(), + "Cast").set_input("x", x_grad, + 2).set_attr_int32("dst_type", cast_dtype) + + return [out_x_grad, out_scale_grad, out_bias_grad], [[2], [1], [0]] + + +class TanhGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(TanhGradParser, self).__init__(graph, var2geop) + self.parser_name = 'tanh_grad' + + def _apply(self): + y = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + tanh_grad = core.GEOperatorFactory.create_operator( + "tanh_grad" + self._accumulated_op_id(), + "TanhGrad").set_input("y", y).set_input("dy", out_grad) + + return [tanh_grad], [[0]] + + +class LogGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LogGradParser, self).__init__(graph, var2geop) + self.parser_name = 'log_grad' + + def _apply(self): + grad = self._get_ge_input(self.op.input_arg_names[0]) + input = self._get_ge_input(self.op.input_arg_names[1]) + log_grad = core.GEOperatorFactory.create_operator( + "log_grad" + self._accumulated_op_id(), + "DivNoNan").set_input("x1", grad).set_input("x2", input) + return [log_grad], [[0]] + + +class SqrtGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SqrtGradParser, self).__init__(graph, var2geop) + self.parser_name = "sqrt_grad" + + def _apply(self): + y = self._get_ge_input(self.op.input_arg_names[0]) + out_grad = self._get_ge_input(self.op.input_arg_names[1]) + sqrt_grad = core.GEOperatorFactory.create_operator( + "sqrt_grad" + self._accumulated_op_id(), + "SqrtGrad").set_input("y", y).set_input("dy", out_grad) + return [sqrt_grad] + + +class PowGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(PowGradParser, self).__init__(graph, var2geop) + self.parser_name = "pow_grad" + + def _apply(self): + grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + factor = self.op.attr("factor") + + shape_tensor = self._create_shape_tensor() + shape_tensor = core.GEOperatorFactory.create_operator( + "shape" + self._accumulated_op_id(), "Shape").set_input("x", x) + factor_scale = self._create_ge_tensor([1], 5, factor) + factor_scale = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", factor_scale) + factor_tensor = core.GEOperatorFactory.create_operator( + "broadcast_to_d" + self._accumulated_op_id(), + "BroadcastTo").set_input("x", factor_scale).set_input( + "shape", shape_tensor) + + x_power = core.GEOperatorFactory.create_operator( + "x_power" + self._accumulated_op_id(), + "Power").set_input("x", x).set_attr_float("power", factor - 1) + x_power_mul_factor = core.GEOperatorFactory.create_operator( + "x_power_mul_factor" + self._accumulated_op_id(), + "Mul").set_input("x1", x).set_input("x2", factor_tensor) + x_power_mul_factor_grad = core.GEOperatorFactory.create_operator( + "x_power_mul_factor_grad" + self._accumulated_op_id(), + "Mul").set_input("x1", x_power_mul_factor).set_input("x2", grad) + + return [x_power_mul_factor_grad], [[0]] + + +class GeluGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(GeluGradParser, self).__init__(graph, var2geop) + self.parser_name = "gelu_grad" + + def _apply(self): + grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + + y = core.GEOperatorFactory.create_operator( + "gelu" + self._accumulated_op_id(), "Gelu").set_input("x", x) + gelu_grad = core.GEOperatorFactory.create_operator( + "gelu_grad" + self._accumulated_op_id(), + "GeluGrad").set_input("x", x).set_input("dy", + grad).set_input("y", y) + + return [gelu_grad], [[0]] + + +class MeanGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(MeanGradParser, self).__init__(graph, var2geop) + self.parser_name = "mean_grad" + + def _apply(self): + grad = self._get_ge_input(self.op.input_arg_names[0]) + x = self._get_ge_input(self.op.input_arg_names[1]) + + ones_tensor = core.GEOperatorFactory.create_operator( + "one_tensor" + self._accumulated_op_id(), + "OnesLike").set_input("x", x) + sum = core.GEOperatorFactory.create_operator( + "mean" + self._accumulated_op_id(), + "ReduceSumD").set_input("x", ones_tensor).set_attr_bool( + "keep_dims", False).set_attr_vec_int32("axes", []) + mean = core.GEOperatorFactory.create_operator( + "x_power" + self._accumulated_op_id(), + "Power").set_input("x", sum).set_attr_float("power", -1) + + mean_grad = core.GEOperatorFactory.create_operator( + "mean_grad" + self._accumulated_op_id(), + "Mul").set_input("x1", mean).set_input("x2", grad) + + return [mean_grad], [[0]] + + +class SliceGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SliceGradParser, self).__init__(graph, var2geop) + self.parser_name = "slice_grad" + + def _apply(self): + x = self._get_ge_input(self.op.input_arg_names[0]) + grad = self._get_ge_input(self.op.input_arg_names[1]) + axes = self.op.attr("axes") + starts = self.op.attr("starts") + ends = self.op.attr("ends") + + x_shape = self.op.block.var(self.op.input_arg_names[0]).shape + grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape + + len_shape = len(x_shape) + axes_cor = list(range(len_shape)) + starts_cor, ends_cor = [], [] + cnt = 0 + for i in range(len_shape): + starts_cor.append(starts[cnt] if i in axes else 0) + if i in axes and ends[cnt] <= x_shape[i]: + ends_cor.append(x_shape[i] - ends[cnt]) + else: + ends_cor.append(0) + if i in axes: + cnt += 1 + + starts_cor[0] = 0 + ends_cor[0] = 0 + paddings = [[s, e] for (s, e) in zip(starts_cor, ends_cor)] + slice_value = core.GEOperatorFactory.create_operator( + "slice_grad" + self._accumulated_op_id(), "PadD").set_input( + "x", grad).set_attr_vec_vec_int64("paddings", paddings) + + return [slice_value], [[0]] + + +class LookUpTableGradParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(LookUpTableGradParser, self).__init__(graph, var2geop) + self.parser_name = "lookup_table_grad" + + def _apply(self): + ids = self._get_ge_input(self.op.input_arg_names[0]) + grad = self._get_ge_input(self.op.input_arg_names[1]) + embedding = self._get_ge_input(self.op.input_arg_names[2]) + + shape_ids = self.op.block.var(self.op.input_arg_names[0]).shape + shape_grad = self.op.block.var(self.op.input_arg_names[1]).shape + shape_embedding = self.op.block.var(self.op.input_arg_names[2]).shape + + ids_flatten = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), "FlattenV2").set_input( + "x", ids).set_attr_int32("axis", + 0).set_attr_int32("end_axis", 1) + grad_flatten = core.GEOperatorFactory.create_operator( + "flatten" + self._accumulated_op_id(), "FlattenV2").set_input( + "x", grad).set_attr_int32("axis", + 0).set_attr_int32("end_axis", 1) + + tensor_zeros = core.GEOperatorFactory.create_operator( + "zeroslike" + self._accumulated_op_id(), + "ZerosLike").set_input("x", embedding) + embedding_grad = core.GEOperatorFactory.create_operator( + "scatteradd" + self._accumulated_op_id(), + "TensorScatterAdd").set_input("x", tensor_zeros).set_input( + "indices", ids_flatten).set_input("updates", grad_flatten) + + return [embedding_grad], [[0]] + + +class SGDParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(SGDParser, self).__init__(graph, var2geop) + self.parser_name = "sgd" + + def _apply(self): + grad = self._get_ge_input(self.op.input_arg_names[0]) + lr = self._get_ge_input(self.op.input_arg_names[1]) + param = self._get_ge_input(self.op.input_arg_names[2]) + sgd = core.GEOperatorFactory.create_operator( + "momentum" + self._accumulated_op_id(), + "ApplyGradientDescent").set_input("var", param).set_input( + "alpha", lr).set_input("delta", grad) + return [sgd], [[0]] + + +class AdamParser(AscendParserBase): + + def __init__(self, graph, var2geop): + super(AdamParser, self).__init__(graph, var2geop) + self.parser_name = "adam" + + def _apply(self): + beta1_power = self._get_ge_input(self.op.input_arg_names[0]) + beta2_power = self._get_ge_input(self.op.input_arg_names[1]) + grad = self._get_ge_input(self.op.input_arg_names[2]) + lr = self._get_ge_input(self.op.input_arg_names[3]) + moment1 = self._get_ge_input(self.op.input_arg_names[4]) + moment2 = self._get_ge_input(self.op.input_arg_names[5]) + param = self._get_ge_input(self.op.input_arg_names[6]) + beta1 = self.op.attr('beta1') + beta2 = self.op.attr('beta2') + epsilon = self.op.attr('epsilon') + + beta1 = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", + self._create_ge_tensor([1], 5, beta1)) + beta2 = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", + self._create_ge_tensor([1], 5, beta2)) + epsilon = core.GEOperatorFactory.create_operator( + "const" + self._accumulated_op_id(), + "Const").set_attr_tensor("value", + self._create_ge_tensor([1], 5, epsilon)) + + adam = core.GEOperatorFactory.create_operator( + "adam" + self._accumulated_op_id(), + "ApplyAdam").set_input("var", param).set_input( + "m", moment1).set_input("v", moment2).set_input( + "beta1_power", beta1_power).set_input( + "beta2_power", + beta2_power).set_input("lr", lr).set_input( + "beta1", beta1).set_input("beta2", beta2).set_input( + "epsilon", epsilon).set_input("grad", grad) + + return [adam], [[0]] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/asp_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/asp_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2047c3172c26092ea9e214670861741806eee789 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/asp_optimizer.py @@ -0,0 +1,68 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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 + +from paddle.fluid.contrib.sparsity.asp import ASPHelper +from .meta_optimizer_base import MetaOptimizerBase + +__all__ = [] + + +class ASPOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(ASPOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [ + "AMPOptimizer", "LarsOptimizer", "LambOptimizer", + "GraphExecutionOptimizer", "RecomputeOptimizer", + "GradientMergeOptimizer" + ] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(ASPOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.asp: + return True + + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.asp = False + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.asp = True + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + + optimize_ops, params_grads = ASPHelper._minimize( + self.inner_opt, + loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0cc901025871986ec521ead7bba74262e784fd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/common.py @@ -0,0 +1,228 @@ +# 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. + +from __future__ import print_function +import os + +import paddle.fluid as fluid +from paddle.fluid import core, unique_name +from ..base.private_helper_function import wait_server_ready + +__all__ = [] + +OpRole = core.op_proto_and_checker_maker.OpRole + +OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() +OP_ROLE_VAR_KEY = core.op_proto_and_checker_maker.kOpRoleVarAttrName() + + +def is_update_op(op): + return 'Param' in op.input_names and 'Grad' in op.input_names and \ + "LearningRate" in op.input_names + + +def is_loss_grad_op(op): + if OP_ROLE_KEY not in op.attr_names: + return False + op_role = int(op.all_attrs()[OP_ROLE_KEY]) + return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss) + + +def is_backward_op(op): + return OP_ROLE_KEY in op.attr_names and \ + int(op.all_attrs()[OP_ROLE_KEY]) & int(OpRole.Backward) + + +def is_optimizer_op(op): + return OP_ROLE_KEY in op.attr_names and \ + int(op.all_attrs()[OP_ROLE_KEY]) & int(OpRole.Optimize) + + +class CollectiveHelper(object): + + def __init__(self, role_maker, nrings=1, wait_port=True): + self.nrings = nrings + self.wait_port = wait_port + self.role_maker = role_maker + + def update_startup_program(self, startup_program=None): + self.startup_program = startup_program + if startup_program is None: + self.startup_program = fluid.default_startup_program() + + endpoints = self.role_maker._get_trainer_endpoints() + current_endpoint = endpoints[self.role_maker._worker_index()] + for ring_id in range(self.nrings): + self._init_communicator(self.startup_program, + current_endpoint, endpoints, + self.role_maker._worker_index(), ring_id, + self.wait_port) + self._broadcast_params() + + def _init_communicator(self, + program, + current_endpoint, + endpoints, + rank, + ring_id, + wait_port, + global_ring_id=None, + sync=True): + # if current_endpoint is None, it means just for sync, + # no group is created. + if current_endpoint: + nranks = len(endpoints) + other_endpoints = endpoints[:] + other_endpoints.remove(current_endpoint) + + if rank == 0 and wait_port: + wait_server_ready(other_endpoints) + + def _add_sync_by_allreduce(block): + sync_var = block.create_var(name=unique_name.generate('sync_var'), + dtype=core.VarDesc.VarType.INT32, + persistable=False, + stop_gradient=True) + block.append_op(type='fill_constant', + inputs={}, + outputs={'Out': [sync_var]}, + attrs={ + 'shape': [1], + 'dtype': sync_var.dtype, + 'value': 1, + 'force_cpu': False, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_allreduce_sum', + inputs={'X': [sync_var]}, + outputs={'Out': [sync_var]}, + attrs={ + 'ring_id': global_ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_sync_calc_stream', + inputs={'X': sync_var}, + outputs={'Out': sync_var}, + attrs={OP_ROLE_KEY: OpRole.Forward}) + + block = program.global_block() + if current_endpoint is None: + assert endpoints is None + assert sync + _add_sync_by_allreduce(block) + return + + comm_id_var = block.create_var(name=unique_name.generate('comm_id'), + persistable=True, + type=core.VarDesc.VarType.RAW) + if core.is_compiled_with_cuda(): + block.append_op(type='c_gen_nccl_id', + inputs={}, + outputs={'Out': comm_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_comm_init', + inputs={'X': comm_id_var}, + outputs={}, + attrs={ + 'nranks': nranks, + 'rank': rank, + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + elif core.is_compiled_with_xpu(): + block.append_op(type='c_gen_bkcl_id', + inputs={}, + outputs={'Out': comm_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_comm_init', + inputs={'X': comm_id_var}, + outputs={}, + attrs={ + 'nranks': nranks, + 'rank': rank, + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + elif core.is_compiled_with_npu(): + block.append_op(type='c_gen_hccl_id', + inputs={}, + outputs={'Out': comm_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_comm_init_hccl', + inputs={'X': comm_id_var}, + outputs={}, + attrs={ + 'rank': rank, + 'ring_id': ring_id, + 'device_id': + int(os.getenv("FLAGS_selected_npus")), + 'rank_ids': nranks, + OP_ROLE_KEY: OpRole.Forward + }) + else: + raise ValueError( + "comm_id must be generated in paddlepaddle-xpu or paddlepaddle-xpu." + ) + if sync: _add_sync_by_allreduce(block) + + def _wait(self, current_endpoint, endpoints): + assert (self.wait_port) + other_endpoints = endpoints[:] + other_endpoints.remove(current_endpoint) + wait_server_ready(other_endpoints) + + def _broadcast_params(self): + block = self.startup_program.global_block() + ring_id = -1 + for param in block.iter_parameters(): + if param.is_distributed: + continue + + ring_id = (ring_id + 1) % self.nrings + block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': 0, + OP_ROLE_KEY: OpRole.Forward + }) + + for ring_id in range(self.nrings): + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dgc_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dgc_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d25cf9680236f2ba6272f9ee3d3bbbad2978fef1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dgc_optimizer.py @@ -0,0 +1,120 @@ +# 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 + +from paddle.fluid.optimizer import Momentum, DGCMomentumOptimizer +from .meta_optimizer_base import MetaOptimizerBase +import logging + +__all__ = [] + + +class DGCOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(DGCOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.dgc_opt = None + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(DGCOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _init_dgc_opt(self): + if self.dgc_opt is not None: + return + + opt = self.inner_opt + + if not self.role_maker._is_collective: + return + + if not isinstance(opt, Momentum): + return + + configs = self.user_defined_strategy.dgc_configs + if len(configs['sparsity']) == 0: + # default is [0.999] + configs['sparsity'] = [0.999] + + self.dgc_opt = DGCMomentumOptimizer( + learning_rate=opt._learning_rate, + momentum=opt._momentum, + rampup_begin_step=configs['rampup_begin_step'], + rampup_step=configs['rampup_step'], + sparsity=configs['sparsity'], + parameter_list=opt._parameter_list, + use_nesterov=opt._use_nesterov, + num_trainers=self.role_maker._worker_num(), + regularization=opt.regularization, + grad_clip=opt._grad_clip, + name=opt._name) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.dgc: + if not isinstance(self.inner_opt, Momentum): + logging.warn("dgc only works on Momentum optimizer") + return False + if self.role_maker._worker_num() <= 1: + logging.warn("dgc only works on multi cards") + return False + + return True + + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.dgc = False + dist_strategy.dgc_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.dgc = True + dist_strategy.dgc_configs = {"rampup_begin_step": 0, "rampup_step": 1} + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + self._init_dgc_opt() + return self.dgc_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_gradients(self, params_grads): + self._init_dgc_opt() + return self.dgc_opt.apply_gradients(params_grads=params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + self._init_dgc_opt() + return self.dgc_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self._init_dgc_opt() + optimize_ops, params_grads = \ + self.dgc_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3beb8635ba41a765a1dd567ba7950d73d7829cfa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2021 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 +from .hybrid_parallel_optimizer import HybridParallelOptimizer +from .hybrid_parallel_gradscaler import HybridParallelGradScaler +from .dygraph_sharding_optimizer import DygraphShardingOptimizer +from .heter_parallel_optimizer import HeterParallelOptimizer + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/dygraph_sharding_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/dygraph_sharding_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d34f1cad2703322fe10e17591545641aa3708115 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/dygraph_sharding_optimizer.py @@ -0,0 +1,194 @@ +# Copyright (c) 2021 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. + +###### + +from functools import reduce + +import paddle +from paddle import framework +from ...utils.log_util import logger + + +def _is_trainable(param): + return not param.stop_gradient + + +class DygraphShardingOptimizer(object): + """ + A wrapper for Sharding Optimizer in Dygraph. + + .. warning: DygraphShardingOptimizer is experimental and subject to change. + + .. ZeRO: https://arxiv.org/abs/1910.02054 + + """ + + # TODO (JZ-LIANG) + # TO support following featrues in future: + # 1. fused update parameter sync + # 2. parameters_groups + # 3. dynamic trainable params, which is the case bewteen pretraining and finetuning + # 4. option to choose fuse comm (more GPU MEM need) or un-fuse comm + + def __init__(self, hcg, user_defined_strategy, params, + inner_optimizer_class, **inner_optimizer_kargs): + + if not isinstance(params, list): + raise TypeError( + "`parameters` argument given to the DygraphShardingOptimizer should be " + "an iterable of paddle Tensors, but got argument type is `{}`.". + format(type(params))) + self._parameter_list = params + self._reference_is_trainable_params = list( + map(_is_trainable, self._parameter_list)) + + self._inner_optimizer_class = inner_optimizer_class + self._inner_optimizer_kargs = inner_optimizer_kargs + + # sharding parallel information + # TODO better way to get the hcg & user_defined_strategy + self._hcg = hcg + self._user_defined_strategy = user_defined_strategy + self._sharding_world_size = self._hcg.get_sharding_parallel_world_size() + self._sharding_rank = self._hcg.get_sharding_parallel_rank() + + # logic partitioning + self._build_sharding_mapping() + + # actually create opt ops + self._buid_inner_optimizer() + + def clear_grad(self): + """ + should clear grad for all parameters in model + """ + for p in self._parameter_list: + if not p.stop_gradient: + p.clear_gradient() + + def _build_sharding_mapping(self): + + self._rank2params = self._partition_parameters() + self._param2rank = self._map_param_to_rank() + + def _partition_parameters(self): + """ + Partitions parameters among sharding ranks. + + Return: + Dict[int, List] + """ + # TODO(JZ-LIANG) support multiple partition methods + # method1: greedy even but unorder + # method2: roughly even with oreder + + mapping = {} + for rank_ in range(self._sharding_world_size): + mapping[rank_] = [] + sizes = [0] * self._sharding_world_size + for param in self._parameter_list: + rank = sizes.index(min(sizes)) + mapping[rank].append(param) + numel = reduce(lambda x, y: x * y, param.shape) + assert numel > 0, "param [{}] should larger than 0, but it is [{}]".format( + param.name, numel) + sizes[rank] += numel + + return mapping + + def _map_param_to_rank(self): + """ + mapping parameters to the shard which holds it. + + Return: + Dict[str, int] + """ + mapping = {} + for rank, params in self._rank2params.items(): + for param in params: + mapping[param.name] = rank + return mapping + + def _buid_inner_optimizer(self): + # we rely on the inner opt to determine whether a parameter is stop_gradient or not: + # create moment + # update related ops: clip, regular, opt + self._inner_optimizer = self._inner_optimizer_class( + parameters=self._rank2params[self._sharding_rank], + **self._inner_optimizer_kargs) + + def _sharding_sync_parameters(self): + """ + sync parameter across sharding group + """ + # TODO speed up this functional + + logger.debug("sharding start sync parameters") + with framework.no_grad(): + # TODO detach not need (?) + for rank, params in self._rank2params.items(): + for param in params: + paddle.distributed.broadcast( + param, + # the collective API need src rank to be the global rank id + # instead of the relative logic rank id within group + src=self._hcg.get_sharding_parallel_group().ranks[rank], + group=self._hcg.get_sharding_parallel_group(), + sync_op=True) + + def _update_trainable(self): + """ + allow user to update trainable parameters list during training + """ + raise NotImplementedError + + def minimize(self, + loss, + startup_program=None, + parameters=None, + no_grad_set=None): + + # NOTE in dygraph mode, the only different between step and minimize is that minimize + # allow user to customize the parameters for updating on each step + + input_param_names = set([param.name for param in parameters]) + parameters = list( + filter(lambda x: x.name in input_param_names, + self._rank2params[self._sharding_rank])) + result = self._inner_optimizer.minimize(loss, startup_program, + parameters, no_grad_set) + + # sync parameters across sharding ranks + self._sharding_sync_parameters() + + return result + + def step(self): + # TODO Check whether the model trainable param changed and update state accordingly + + # actually updating + self._inner_optimizer.step() + + # sync parameters across sharding ranks + self._sharding_sync_parameters() + + # TODO is it a good way to make _grad_clip a property + @property + def _grad_clip(self): + assert self._inner_optimizer is not None, "inner opt of sharding is not initiliazed." + return self._inner_optimizer._grad_clip + + def __getattr__(self, item): + return getattr(self._inner_optimizer, item) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/heter_parallel_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/heter_parallel_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..9218024be17203e0082d840d818170c94cad22e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/heter_parallel_optimizer.py @@ -0,0 +1,66 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid import framework + +__all__ = [] + + +def _obtain_optimizer_parameters_list(optimizer): + if getattr(optimizer, '_param_groups', None) and isinstance( + optimizer._param_groups[0], dict): + parameters_list = [] + for group in optimizer._param_groups: + for param in group['params']: + parameters_list.append(param) + else: + parameters_list = [param for param in optimizer._parameter_list] + + return parameters_list + + +class HeterParallelOptimizer: + # adapter wrapper for optimizer + def __init__(self, optimizer, strategy): + self._inner_opt = optimizer + self._strategy = strategy + + # NOTE(liubo48): In pure DataParallel mode, + # the gradient synchronization is achieved through reducer. + + @imperative_base.no_grad + @framework.dygraph_only + def step(self): + parameters_list = _obtain_optimizer_parameters_list(self._inner_opt) + self._inner_opt.step() + + @imperative_base.no_grad + def minimize(self, + loss, + startup_program=None, + parameters=None, + no_grad_set=None): + + # minimize does not support parameters in the form of param_group, + # so no need use _obtain_optimizer_parameters_list + parameter_list = parameters if parameters \ + else self._inner_opt._parameter_list + + return self._inner_opt.minimize(loss, startup_program, parameter_list, + no_grad_set) + + def __getattr__(self, item): + return getattr(self._inner_opt, item) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_gradscaler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_gradscaler.py new file mode 100644 index 0000000000000000000000000000000000000000..5e11760d913d092d34709bc64946558effd3375b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_gradscaler.py @@ -0,0 +1,83 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function +import sys +from paddle.optimizer import Optimizer +from ...base.topology import ParallelMode +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid import framework +from paddle.fluid.framework import Variable +import types +from paddle.fluid import core +import paddle +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +class HybridParallelGradScaler: + + def __init__(self, scaler, hcg): + self._scaler = scaler + self._hcg = hcg + self._use_dp_mode = ( + self._hcg.get_parallel_mode() == ParallelMode.DATA_PARALLEL) + + def scale(self, var): + return self._scaler.scale(var) + + def minimize(self, optimizer, *args, **kwargs): + if not self._enable: + return optimizer.minimize(*args, **kwargs) + + # unscale the grad + self._unscale(optimizer) + + optimize_ops, params_grads = (None, None) + + if self._found_inf: + self._cache_founf_inf = True + else: + optimize_ops, params_grads = optimizer.minimize(*args, **kwargs) + self._cache_founf_inf = False + + if self._use_dynamic_loss_scaling: + self._update() + + return optimize_ops, params_grads + + @imperative_base.no_grad + def _unscale(self, optimizer): + if not self._enable: + return + param_grads = [ + param._grad_ivar() for param in optimizer._parameter_list + if param._grad_ivar() is not None + ] + _legacy_C_ops.check_finite_and_unscale(param_grads, self._scale, + param_grads, self._found_inf) + # allreduce_max found_inf in check_group + if not self._use_dp_mode: + self._found_inf = paddle.cast(self._found_inf, dtype="int32") + # TODO(shenliang03) Since the minimize call in the optimizer is + # after the gradscaler, check_finite needs to synchronize global + # information. In the future, we should use check_group + paddle.distributed.all_reduce(self._found_inf, + op=paddle.distributed.ReduceOp.MAX, + group=None) + self._found_inf = paddle.cast(self._found_inf, dtype="bool") + + def __getattr__(self, item): + return getattr(self._scaler, item) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..14daba5ee330ef5fb54d5a69dbb571ea6af8773b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/hybrid_parallel_optimizer.py @@ -0,0 +1,245 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function +import sys +import paddle +from paddle.optimizer import Optimizer +from paddle.fluid.clip import ClipGradByGlobalNorm +from ...utils.hybrid_parallel_util import fused_allreduce_gradients, sharding_reduce_gradients +from ...base.topology import ParallelMode +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid import framework +from paddle.fluid.framework import Variable +from ...utils.log_util import logger +from paddle.fluid import core +from paddle.fluid import layers + +__all__ = [] + + +def _obtain_optimizer_parameters_list(optimizer): + if getattr(optimizer, '_param_groups', None) and isinstance( + optimizer._param_groups[0], dict): + parameters_list = [] + for group in optimizer._param_groups: + for param in group['params']: + parameters_list.append(param) + else: + parameters_list = [param for param in optimizer._parameter_list] + + return parameters_list + + +class HybridParallelClipGrad: + + def __init__(self, clip, hcg): + self._clip = clip + self._hcg = hcg + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + sum_square_dist_fp16 = [] + sum_square_dist_fp32 = [] + sum_square_not_dist_fp16 = [] + sum_square_not_dist_fp32 = [] + + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + continue + merge_grad = g + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.merge_selected_rows(g) + merge_grad = layers.get_tensor_from_selected_rows(merge_grad) + square = layers.square(merge_grad) + sum_square = layers.reduce_sum(square) + + not_shared_enable = (not hasattr(p, 'is_firstly_shared')) or ( + hasattr(p, 'is_firstly_shared') + and getattr(p, 'is_firstly_shared', True)) + + if not_shared_enable: + if p.is_distributed: + if p.dtype == paddle.float16: + sum_square_dist_fp16.append(sum_square) + elif p.dtype == paddle.float32: + sum_square_dist_fp32.append(sum_square) + else: + if p.dtype == paddle.float16: + sum_square_not_dist_fp16.append(sum_square) + elif p.dtype == paddle.float32: + sum_square_not_dist_fp32.append(sum_square) + + # global norm of distributed FP16 params_and_grads + if len(sum_square_dist_fp16) == 0: + global_norm_dist_fp16 = paddle.to_tensor([0.], dtype=paddle.float32) + else: + global_norm_dist_fp16 = layers.concat(sum_square_dist_fp16) + global_norm_dist_fp16 = layers.reduce_sum(global_norm_dist_fp16) + global_norm_dist_fp16 = paddle.cast(global_norm_dist_fp16, + dtype=paddle.float32) + + # global norm of non-distributed FP16 params_and_grads + if len(sum_square_not_dist_fp16) == 0: + global_norm_not_dist_fp16 = paddle.to_tensor([0.], + dtype=paddle.float32) + else: + global_norm_not_dist_fp16 = layers.concat(sum_square_not_dist_fp16) + global_norm_not_dist_fp16 = layers.reduce_sum( + global_norm_not_dist_fp16) + global_norm_not_dist_fp16 = paddle.cast(global_norm_not_dist_fp16, + dtype=paddle.float32) + + # global norm of distributed FP32 params_and_grads + global_norm_dist_fp32 = layers.concat(sum_square_dist_fp32) if len( + sum_square_dist_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_norm_dist_fp32 = layers.reduce_sum(global_norm_dist_fp32) + + # global norm of non-distributed FP32 params_and_grads + global_norm_not_dist_fp32 = layers.concat( + sum_square_not_dist_fp32 + ) if len(sum_square_not_dist_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_norm_not_dist_fp32 = layers.reduce_sum(global_norm_not_dist_fp32) + + global_norm_var_dist = global_norm_dist_fp16 + global_norm_dist_fp32 + global_norm_var_not_dist = global_norm_not_dist_fp16 + global_norm_not_dist_fp32 + + # add all reduce to get global norm of distributed params_and_grads + if self._hcg.get_model_parallel_world_size() > 1: + paddle.distributed.all_reduce( + global_norm_var_dist, + group=self._hcg.get_check_parallel_group()) + + # add all reduce to get global norm of non-distributed params_and_grads in groups of pp + if self._hcg.get_pipe_parallel_world_size() > 1: + paddle.distributed.all_reduce( + global_norm_var_not_dist, + group=self._hcg.get_pipe_parallel_group()) + + # In Sharding mode, param and grad is mapping different rank in optimizer. + # ClipGradByGlobalNorm need allreduce to get globol norm + if self._hcg.get_sharding_parallel_world_size() > 1: + paddle.distributed.all_reduce( + global_norm_var_not_dist, + group=self._hcg.get_sharding_parallel_group()) + + global_norm_var_fp32 = layers.sqrt(global_norm_var_dist + + global_norm_var_not_dist) + + max_global_norm = layers.fill_constant(shape=[1], + dtype=global_norm_var_fp32.dtype, + value=self.clip_norm) + clip_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=global_norm_var_fp32, + y=max_global_norm)) + clip_var_fp16 = paddle.cast(clip_var, paddle.float16) + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + continue + if p.dtype == paddle.float16: + g.scale_(clip_var_fp16) + else: + g.scale_(clip_var) + p._reset_grad_inplace_version(True) + + return params_grads + + def __getattr__(self, item): + return getattr(self._clip, item) + + def __call__(self, params_grads): + return self._dygraph_clip(params_grads) + + +class HybridParallelOptimizer: + # adapter wrapper for optimizer + def __init__(self, optimizer, hcg, strategy): + self._inner_opt = optimizer + self._strategy = strategy + self._hcg = hcg + + self._use_dp_mode = ( + self._hcg.get_parallel_mode() == ParallelMode.DATA_PARALLEL) + + self._need_dp = (self._hcg.get_data_parallel_world_size() > 1) + + # NOTE(shenliang03): Because of the pure DataParallel mode, the gradient synchronization + # is achieved through reducer, so there is no need to call fuse_allreduce in optimizer. + self._dp_enable = not self._use_dp_mode and self._need_dp + + self._sharding_enable = (self._hcg.get_sharding_parallel_world_size() > + 1) + + if isinstance(self._inner_opt._grad_clip, + ClipGradByGlobalNorm) and not self._use_dp_mode: + logger.warning("While using ClipGradByGlobalNorm in TensorParallel, PipelineParallel " \ + "or Sharding, the grad clip of original optimizer will be changed.") + + if self._sharding_enable: + # change sharding inner_optimizer's _grad_clip + self._inner_opt._inner_optimizer._grad_clip = HybridParallelClipGrad( + self._inner_opt._grad_clip, hcg) + else: + self._inner_opt._grad_clip = HybridParallelClipGrad( + self._inner_opt._grad_clip, hcg) + if self._inner_opt._parameter_list and isinstance( + self._inner_opt._parameter_list[0], dict): + for item in self._inner_opt._param_groups: + if "grad_clip" in item.keys(): + item["grad_clip"] = HybridParallelClipGrad( + self._inner_opt._grad_clip, hcg) + + @imperative_base.no_grad + @framework.dygraph_only + def step(self): + parameters_list = _obtain_optimizer_parameters_list(self._inner_opt) + if self._sharding_enable: + sharding_reduce_gradients(list(parameters_list), self._hcg) + + if self._dp_enable: + fused_allreduce_gradients(list(parameters_list), self._hcg) + + self._inner_opt.step() + + @imperative_base.no_grad + def minimize(self, + loss, + startup_program=None, + parameters=None, + no_grad_set=None): + + # minimize does not support parameters in the form of param_group, + # so no need use _obtain_optimizer_parameters_list + parameter_list = parameters if parameters \ + else self._inner_opt._parameter_list + + # Here sharding should use global parameter list + if self._sharding_enable: + sharding_reduce_gradients(list(parameter_list), self._hcg) + + if self._dp_enable: + fused_allreduce_gradients(list(parameter_list), self._hcg) + + return self._inner_opt.minimize(loss, startup_program, parameter_list, + no_grad_set) + + def __getattr__(self, item): + return getattr(self._inner_opt, item) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/sharding_optimizer_stage2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/sharding_optimizer_stage2.py new file mode 100644 index 0000000000000000000000000000000000000000..ad5cbf83ecb862b264ba1f3e7b410de898d6e839 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/dygraph_optimizer/sharding_optimizer_stage2.py @@ -0,0 +1,423 @@ +# Copyright (c) 2021 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/optim/oss.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import copy +import logging +import numpy as np +from itertools import chain +from functools import reduce +from collections import OrderedDict + +import paddle +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.optimizer import Optimizer +from paddle.fluid.clip import ClipGradByGlobalNorm +from paddle.distributed.collective import _get_global_group, new_group, broadcast, wait + +from ...utils.internal_storage import ParamStorage, GradStorage +from ...meta_parallel.sharding.sharding_utils import Type, device_guard, ShardingClipGrad + +# CUDA alignment 256 bytes, cpu alignment 4096 bytes +alignment = {"gpu": 256, "cpu": 4096} +align = { + Type.fp16.value: 2, + Type.fp32.value: 4, +} + + +class ShardingOptimizerStage2(Optimizer): + """ + A wrapper for Sharding Stage2 Optimizer in Dygraph. + + .. warning: ShardingOptimizer encapsulates the optimization strategy and integrates it into the optimizer. + + .. ZeRO: 1.https://arxiv.org/pdf/1910.02054.pdf 2.https://arxiv.org/pdf/1910.02054.pdf. + + """ + + # TODO (Baibaifan) + # Feature Notes: + # 1. Unified memory for parameters and parameters.grad to InternalStorage. + # 2. Support the segmentation of optimizer parameters and partial updating of parameters. + # 3. Dynamically adjust training parameters and models. + # 4. Support offload function. + # 5. Support the establishment of independent communication groups. + # 6. Broadcast_fp16 is not supported now. + def __init__(self, + params, + optim, + group=None, + offload=False, + device="gpu", + pertrain_sync_models=True, + **kw): + + super().__init__(optim._learning_rate, params, kw) + + # Segmentation information + self._dtype_rank_params = OrderedDict( + ) # {dtype:[param1,param2]} device, rank, params + self._param2rank = {} + self.__segment_params = [] + self._rank_buffer_size = {} # {dtype: {rank: numel+alignment}} + self._param2align = {} # {param.name: align} + + # Default information + self._optim_defaults = kw + self._optim = optim + + assert hasattr(self._optim, "_master_weights" + ), "Must use optimizer with _master_weights attribute" + self._local_params = params + self._default_device = device + self._pfp16 = len( + list( + filter(lambda x: x.trainable and x.dtype == Type.fp16.value, + self._local_params))) > 0 + + self.group = new_group( + _get_global_group().ranks) if group is None else group + + self.world_size = self.group.nranks + self.rank = self.group.rank + self._global_root_rank = self.group.ranks[0] + + # Synchronous all ranks models + if pertrain_sync_models: + self._sync_params_and_buffers() + + self.param_storages = {} # {dtype: {rank: InternalStorage}} + + if isinstance(self._optim._grad_clip, ClipGradByGlobalNorm): + logging.warning( + "While using ClipGradByGlobalNorm in ShardingOptimizer, the grad clip of original optimizer will be changed." + ) + self._optim._grad_clip = ShardingClipGrad(self._optim._grad_clip, + paddle.get_device(), + self.group) + if self._optim._parameter_list and isinstance( + self._optim._parameter_list[0], dict): + for item in self._optim._param_groups: + if "grad_clip" in item.keys(): + item["grad_clip"] = ShardingClipGrad( + self._optim._grad_clip, paddle.get_device(), + self.group) + + if offload: + assert self._pfp16, "Only support offload strategy while using \'Adam\', \'AdamW\' and \'Momentum\' optimizer with AMP/Pure FP16" + + self.offload = offload # Using for offload + self.offload_device = "cpu" + self.offload_buffer_size = 0 + self.offload_param2align = {} + self.offload_params = None + self.offload_grads = None + + self._master_params = {} + + # Update optimizer parameters and adjust parameter storage and use according to rank. + self._update_opt_status() + + @paddle.autograd.no_grad() + def _sync_params_and_buffers(self): + """ + Sync all model states for all ranks + """ + + for p in self._local_params: + broadcast(p, + src=self._global_root_rank, + group=self.group, + sync_op=True) + + # Multi stream operation will be supported later + wait(tensor=p, group=self.group, use_calc_stream=True) + + def _generate_master_params(self, trainable_params): + if self.offload: + for param in trainable_params: + if param.name not in self._master_params.keys(): + self._master_params[param.name] = core.VarBase( + name=param.name, + value=param.cast(dtype=Type.fp32.value).numpy(), + place=core.CPUPlace(), + stop_gradient=param.stop_gradient) + else: + for param in trainable_params: + if param.dtype == Type.fp16.value: + self._optim._master_weights[param.name] = paddle.cast( + param, Type.fp32.value) + + def _update_opt_status(self): + """Update optimizer status and parameter storage information, and special functions to be developed. + """ + # func 1 + self._integration_params() + + # fun 2 TODO + + # Segement helpers + + def _segment_params(self): + """ + Divide all optimizer parameters equally into rank. + """ + if len(self.__segment_params) == 0: + self.__segment_params, param_lists = [ + [] for _ in range(self.world_size) + ], [[] for _ in range(self.world_size)] + sizes = [0] * self.world_size + for param in self._local_params: + # Add this param to rank with smallest size. + rank = sizes.index(min(sizes)) + param_lists[rank].append(param) + + # Statistical real numels + sizes[rank] += np.prod(param.shape) if param.trainable else 0 + + for rank, params in enumerate(param_lists): + self.__segment_params[rank].extend(params) + return self.__segment_params + + @property + def local_params(self): + return self._local_params + + @property + def param2rank(self): + """Map the params to the rank which owns them""" + if len(self._param2rank) == 0: + for rank, params in enumerate(self._segment_params()): + for param in params: + self._param2rank[param.name] = rank + return self._param2rank + + @property + def dtype_rank_params(self): + """ + Divide the parameters into groups according to rank and dtype. + """ + if len(self._dtype_rank_params) == 0: + # Assign the parameters of each rank according to the type + for param in self._local_params: + if param.dtype not in self._dtype_rank_params.keys(): + self._dtype_rank_params[param.dtype] = [ + [] for _ in range(self.world_size) + ] + self._dtype_rank_params[param.dtype][self.param2rank[ + param.name]].append(param) + + # Sort per rank params by size + for dtype in self._dtype_rank_params.keys(): + for rank_params in self._dtype_rank_params[dtype]: + rank_params.sort(key=lambda x: np.prod(x.shape)) + + return self._dtype_rank_params + + @property + def rank_buffer_size(self): + """ + Count the memory size of the parameters corresponding to rank under the corresponding dtype. + """ + # CUDA alignment 256 bytes + if len(self._rank_buffer_size) == 0: + for dtype in self.dtype_rank_params.keys(): + if dtype not in self._rank_buffer_size.keys(): + self._rank_buffer_size[dtype] = {} + for dst_rank, per_rank_params in enumerate( + self.dtype_rank_params[dtype]): + if dst_rank not in self._rank_buffer_size[dtype].keys(): + self._rank_buffer_size[dtype][dst_rank] = 0 + for param in per_rank_params: + if not param.trainable: + continue + size = np.prod(param.shape) * align[dtype] + remaining = size % alignment[self._default_device] + ali = 0 if remaining == 0 else alignment[ + self._default_device] - remaining + align_ = ali // align[dtype] + self._rank_buffer_size[dtype][dst_rank] += np.prod( + param.shape) + align_ + self._param2align[param.name] = align_ + + return self._rank_buffer_size + + def _integration_params(self): + """ + Integrate the parameters into a continuous memory according to rank, and support the update of training parameters. + """ + + for dtype, per_rank_params in self.dtype_rank_params.items(): + if dtype not in self.param_storages.keys(): + self.param_storages[dtype] = {} + + for dst_rank, params in enumerate(per_rank_params): + if len(params) > 0: + + # Merge all the trainable params in a single InternalStorage + trainable_params = list( + filter(lambda x: x.trainable, params)) + if self._pfp16 and dst_rank == self.rank: + self._generate_master_params(trainable_params) + if trainable_params: + param_storage = ParamStorage( + size=self.rank_buffer_size[dtype][dst_rank], + dtype=dtype, + device=self._default_device) + + param_storage.add_rank_params(trainable_params, + self._param2align) + self.param_storages[dtype][dst_rank] = param_storage + + # Clear the InternalStorage keys which are not in use anymore + dtype_in_use = list(self.dtype_rank_params.keys()) + dtype_to_pop = list( + filter(lambda x: x not in dtype_in_use, self.param_storages.keys())) + for d in dtype_to_pop: + self.param_storages.pop(d) + + if self.offload: + self._optim._master_weights = self._master_params + cpu_master_params = [p for p in self._master_params.values()] + for param in cpu_master_params: + size = np.prod(param.shape) * align[Type.fp32.value] + remaining = size % alignment[self.offload_device] + ali = 0 if remaining == 0 else alignment[ + self.offload_device] - remaining + align_ = ali // align[Type.fp32.value] + self.offload_buffer_size += np.prod(param.shape) + align_ + self.offload_param2align[param.name] = align_ + + if cpu_master_params: + with device_guard(self.rank, self.offload_device): + self.offload_params = ParamStorage( + size=self.offload_buffer_size, + dtype=Type.fp32.value, + device=self.offload_device) + self.offload_params.add_rank_params( + cpu_master_params, self.offload_param2align, False) + self.offload_params.buffer.stop_gradient = False + + self.offload_grads = GradStorage( + size=self.offload_buffer_size, + dtype=Type.fp32.value, + device=self.offload_device, + destination=self.rank, + parm2align=self.offload_param2align, + convert_cpu=True) + for p in cpu_master_params: + self.offload_grads.add_grad( + p, self.offload_param2align[p.name]) + + self._optim._master_weights[ + self.offload_params.buffer. + name] = self.offload_params.buffer + + def _offload_acc_grad(self, param_name, grad_fp32_cpu): + """accumulate grads with offload strategy""" + with device_guard(self.rank, self.offload_device): + if param_name in self._master_params.keys(): + if self._master_params[param_name].grad is None: + self._master_params[param_name]._copy_gradient_from( + grad_fp32_cpu) + else: + self._master_params[param_name].grad.add_(grad_fp32_cpu) + + self.offload_params.buffer._copy_gradient_from( + self.offload_grads.buffer) + + def _offload_scale_grad(self, scale_size): + """scale grads with offload strategy""" + with device_guard(self.rank, self.offload_device): + self.offload_grads.buffer.scale_(scale=scale_size) + + def _offload_clear_grad(self): + """clear grads with offload strategy""" + with device_guard(self.rank, self.offload_device): + self.offload_grads.buffer.zero_() + + def step(self): + """ + A wrapper for Optimizer's step function to finish the update operation of the optimizer. + """ + + if self.offload: + params_list = [self.offload_params.buffer] + + #TODO(Baibaifan): Offload will support param_groups later + if not isinstance(self._optim._param_groups[0], dict): + self._optim._parameter_list = params_list + self._optim._param_groups = params_list + + # Run the optimizer of the current rank step + if self.offload: + with device_guard(device=self.offload_device): + self._optim.step() + + dev_id = int(paddle.get_device().split(":")[1]) + for param in self._local_params: + if param.name in self._master_params.keys(): + param.set_value( + self._master_params[param.name].cuda(dev_id).cast( + dtype=param.dtype)) + else: + self._optim.step() + + # Synchronize all the updated shards in between the ranks + self._broadcast_params() + + def minimize(self): + raise RuntimeError( + "optimizer.minimize() not support now, please use optimizer.step()") + + def set_state_dict(self, state_dict): + self._optim.set_state_dict(state_dict) + + def state_dict(self): + return self._optim.state_dict() + + def _clear_cache(self): + self.__segment_params.clear() + self._dtype_rank_params.clear() + self._param2rank.clear() + + @paddle.autograd.no_grad() + def _broadcast_params(self): + """Broadcast the parameters of the current rank to each rank""" + + assert self._default_device == "gpu", "Only supported gpu" + + # Exchange all the shards with the other ranks + for dtype_per_rank in self.param_storages.values(): + for dst_rank, internal_storage in dtype_per_rank.items(): + broadcast(tensor=internal_storage.buffer, + src=self.group.ranks[dst_rank], + group=self.group, + sync_op=True) + + # Multi stream operation will be supported later + wait(tensor=internal_storage.buffer, + group=self.group, + use_calc_stream=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/fp16_allreduce_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/fp16_allreduce_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..93857461b26d26133abe67008ed086129e7a8571 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/fp16_allreduce_optimizer.py @@ -0,0 +1,151 @@ +# 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 + +from paddle.fluid import core, framework, unique_name +from .meta_optimizer_base import MetaOptimizerBase + +__all__ = [] + + +class FP16AllReduceOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(FP16AllReduceOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [ + "LarsOptimizer", + "LambOptimizer", + "RecomputeOptimizer", + "LocalSGDOptimizer", + "GradientMergeOptimizer", + "GraphExecutionOptimizer", + "AdaptiveLocalSGDOptimizer", + ] + self.meta_optimizers_black_list = ["DGCOptimizer"] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(FP16AllReduceOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.fp16_allreduce: + return True + + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.fp16_allreduce = False + + def _enable_strategy(self, dist_strategy, context=None): + dist_strategy.fp16_allreduce = True + + @staticmethod + def fp16_compression(param_and_grads): + """ + Compress fp32 gradients to fp16 during allreduce. + """ + op_maker = core.op_proto_and_checker_maker + + new_param_and_grads = [] # param, grad, is_cast + # cast grad from fp32->fp16 before allreduce, + for param, grad in param_and_grads: + if grad is None or grad.dtype != core.VarDesc.VarType.FP32: + new_param_and_grads.append((param, grad, False)) + continue + + op = grad.op + block = grad.block + var_attr = op.all_attrs()[op_maker.kOpRoleVarAttrName()] + if param.name not in var_attr: + new_param_and_grads.append((param, grad, False)) + continue + + # remove (param, grad) from op_role_var + var_attr.remove(param.name) + var_attr.remove(grad.name) + if len(var_attr) > 1: + op._set_attr(op_maker.kOpRoleVarAttrName(), var_attr) + else: + op._remove_attr(op_maker.kOpRoleVarAttrName()) + + new_grad = block.create_var(name=unique_name.generate(grad.name + + ".cast_fp16"), + dtype=core.VarDesc.VarType.FP16, + persistable=False, + stop_gradient=True) + + with block.program._backward_role_guard(): + cast_op = block.append_op(type="cast", + inputs={"X": grad}, + outputs={"Out": new_grad}, + attrs={ + "in_dtype": + core.VarDesc.VarType.FP32, + "out_dtype": + core.VarDesc.VarType.FP16 + }, + stop_gradient=True) + + backward = op_maker.OpRole.Backward + cast_op._set_attr(op_maker.kOpRoleAttrName(), backward) + cast_op._set_attr(op_maker.kOpRoleVarAttrName(), + [param.name, new_grad.name]) + new_grad.op = cast_op + + new_param_and_grads.append((param, new_grad, True)) + + ret_param_and_grads = [] + # cast grad from fp16->fp32 after allreduce. + # NOTE. Now we split fp16 compression into two for loops, + # if we do not separate them, fuse allreduce will wrong. + # This must be the problem of fuse allreduce pass, need + # fixed in future. + for param, grad, cast in new_param_and_grads: + if not cast: + ret_param_and_grads.append((param, grad)) + continue + + block = grad.block + new_grad = block.create_var(name=unique_name.generate(grad.name + + ".cast_fp32"), + dtype=core.VarDesc.VarType.FP32, + persistable=False, + stop_gradient=True) + + with block.program._optimized_guard( + [param, grad]), framework.name_scope('fp16_allreduce'): + cast_op = block.append_op(type="cast", + inputs={"X": grad}, + outputs={"Out": new_grad}, + attrs={ + "in_dtype": + core.VarDesc.VarType.FP16, + "out_dtype": + core.VarDesc.VarType.FP32 + }, + stop_gradient=True) + ret_param_and_grads.append((param, new_grad)) + + return ret_param_and_grads + + def apply_optimize(self, loss, startup_program, params_grads): + new_params_grads = self.fp16_compression(params_grads) + return self.inner_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=new_params_grads) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/gradient_merge_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/gradient_merge_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..10175f8936a70baad1c588e164e7d0e174b48b0b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/gradient_merge_optimizer.py @@ -0,0 +1,74 @@ +# 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 + +from paddle.fluid.optimizer import GradientMergeOptimizer as GM +from .meta_optimizer_base import MetaOptimizerBase + +__all__ = [] + + +class GradientMergeOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(GradientMergeOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.wrapped_opt = None + self.meta_optimizers_white_list = [ + "AMPOptimizer", + "LarsOptimizer", + "LambOptimizer", + "GraphExecutionOptimizer", + "RecomputeOptimizer", + ] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(GradientMergeOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _init_wrapped_opt(self): + config = self.user_defined_strategy.gradient_merge_configs + self.wrapped_opt = GM(self.inner_opt) + self.wrapped_opt._set_k_steps( + self.user_defined_strategy.gradient_merge_configs["k_steps"]) + self.wrapped_opt._set_avg( + self.user_defined_strategy.gradient_merge_configs["avg"]) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + can_apply = (self.user_defined_strategy.gradient_merge == True) and \ + self.user_defined_strategy.gradient_merge_configs["k_steps"] > 1 + return can_apply + + def _disable_strategy(self, dist_strategy): + dist_strategy.gradient_merge = False + dist_strategy.gradient_merge_configs = {} + + def _enable_strategy(self, dist_strategy, context): + # we currently do not support auto-enable GradientMerge + return + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self._init_wrapped_opt() + optimize_ops, params_grads = \ + self.wrapped_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/graph_execution_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/graph_execution_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b0856a66ff4c0892abcc303b6d30af8c9bef8c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/graph_execution_optimizer.py @@ -0,0 +1,264 @@ +# 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 + +import copy +import paddle +from paddle.fluid.framework import core +from paddle.fluid import compiler +from .meta_optimizer_base import MetaOptimizerBase +from ..base.private_helper_function import wait_server_ready +import logging +from paddle.static import BuildStrategy + +__all__ = [] + + +class GraphExecutionOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(GraphExecutionOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [] + self.meta_optimizers_black_list = [] + + def _is_graph_out(self): + return True + + def _can_apply(self): + """ + Basically, this is PE, and almost all programs can be executed here + """ + if not self.role_maker._is_collective: + # update me. currently, if parameter server is used + # graph execution optimizer can not be applied + return False + return not self.user_defined_strategy.without_graph_optimization + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + pass + + # should fix the variable + def _setup_nccl_op(self, startup_program, main_program, build_strategy): + trainer_endpoints = self.role_maker._get_trainer_endpoints() + other_trainers = copy.copy(trainer_endpoints) + + trainer_id = self.role_maker._worker_index() + current_endpoint = self.role_maker._get_trainer_endpoints()[trainer_id] + other_trainers.remove(current_endpoint) + + trainer_endpoints_env = ",".join(trainer_endpoints) + trainers_num = self.role_maker._worker_num() + + # NOTE(wangxi): npu don't need to wait server ready + if trainer_id == 0 and not paddle.is_compiled_with_npu(): + wait_server_ready(other_trainers) + + if build_strategy.reduce_strategy == BuildStrategy.ReduceStrategy._NoReduce: + return + + if core.is_compiled_with_cuda(): + comm_id_var = startup_program.global_block().create_var( + name="NCCLID", persistable=True, type=core.VarDesc.VarType.RAW) + + for i in range(1, build_strategy.nccl_comm_num): + startup_program.global_block().create_var( + name="NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + + if build_strategy.use_hierarchical_allreduce: + for i in range(0, build_strategy.nccl_comm_num): + startup_program.global_block().create_var( + name="Hierarchical_inter_NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + startup_program.global_block().create_var( + name="Hierarchical_exter_NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + + startup_program.global_block().append_op( + type="gen_nccl_id", + inputs={}, + outputs={"NCCLID": comm_id_var}, + attrs={ + "trainers": + trainer_endpoints, + "trainer_id": + trainer_id, + "nccl_comm_num": + build_strategy.nccl_comm_num, + "use_hierarchical_allreduce": + build_strategy.use_hierarchical_allreduce, + "hierarchical_allreduce_inter_ranks": + build_strategy.hierarchical_allreduce_inter_nranks + }) + elif core.is_compiled_with_xpu(): + comm_id_var = startup_program.global_block().create_var( + name="BKCLID", persistable=True, type=core.VarDesc.VarType.RAW) + + #NOTE(liuyuhui) Baidu Kunlun Communication Library(BKCL) currently do not support multi machines. + assert build_strategy.bkcl_comm_num == 1, \ + "Baidu Kunlun Communication Library(BKCL) currently do not support multi machines." + for i in range(1, build_strategy.bkcl_comm_num): + startup_program.global_block().create_var( + name="BKCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + + startup_program.global_block().append_op( + type="gen_bkcl_id", + inputs={}, + outputs={"BKCLID": comm_id_var}, + attrs={ + "trainers": + trainer_endpoints, + "trainer_id": + trainer_id, + "nccl_comm_num": + build_strategy.nccl_comm_num, + "use_hierarchical_allreduce": + build_strategy.use_hierarchical_allreduce, + "hierarchical_allreduce_inter_ranks": + build_strategy.hierarchical_allreduce_inter_nranks + }) + else: + raise ValueError( + "comm_id must be generated in paddlepaddle-xpu or paddlepaddle-gpu." + ) + + def _try_to_compile(self, startup_program, main_program, loss): + dist_strategy = self.user_defined_strategy + local_build_strategy = dist_strategy.build_strategy + + local_build_strategy.use_hierarchical_allreduce = \ + dist_strategy.use_hierarchical_allreduce + local_build_strategy.hierarchical_allreduce_inter_nranks = \ + dist_strategy.hierarchical_allreduce_inter_nranks + local_build_strategy.sync_batch_norm = \ + dist_strategy.sync_batch_norm + local_build_strategy.fuse_all_reduce_ops = \ + dist_strategy.fuse_all_reduce_ops + local_build_strategy.nccl_comm_num = \ + dist_strategy.nccl_comm_num + + gradient_scale_configs = self.user_defined_strategy.gradient_scale_configs + scale_strategys = { + 'avg': BuildStrategy.GradientScaleStrategy.CoeffNumDevice, + 'sum': BuildStrategy.GradientScaleStrategy.One, + 'customized': BuildStrategy.GradientScaleStrategy.Customized, + } + assert gradient_scale_configs['scale_strategy'] in scale_strategys, \ + "gradient_scale_configs.scale_strategy must be 'avg', 'sum' or 'customized'" + local_build_strategy.gradient_scale_strategy = \ + scale_strategys[gradient_scale_configs['scale_strategy']] + + if self.user_defined_strategy.recompute == True: + logging.warn( + "set enable_sequential_execution=True since you have enable the recompute strategy" + ) + local_build_strategy.enable_sequential_execution = True + + exe_strategy = self.user_defined_strategy.execution_strategy + worker_num = self.role_maker._worker_num() + node_num = self.role_maker._node_num() + + if self.role_maker._is_collective: + assert worker_num >= 1, "nccl2 worker_num must >= 1, now:{}" % worker_num + + if worker_num <= 1: + # local mode + if local_build_strategy.nccl_comm_num > 1: + logging.warn("set nccl_comm_num=1 since you only have 1 node.") + local_build_strategy.nccl_comm_num = 1 + + if node_num <= 1: + if local_build_strategy.use_hierarchical_allreduce: + logging.warn( + "set hierachical_allreduce=False since you only have 1 node." + ) + local_build_strategy.use_hierarchical_allreduce = False + + sync_allreduce = dist_strategy.sync_nccl_allreduce + if sync_allreduce: + exe_strategy.num_threads = max( + local_build_strategy.nccl_comm_num + 1, + exe_strategy.num_threads) + if local_build_strategy.nccl_comm_num > 1: + logging.warn( + "nccl_comm_num > 1, you may need to set sync_nccl_allreduce=False to ensure that different nccl comms can overlap" + ) + + sync_batch_norm = local_build_strategy.sync_batch_norm + if sync_batch_norm: + local_build_strategy.nccl_comm_num = 1 + local_build_strategy.use_hierarchical_allreduce = False + exe_strategy.num_threads = 1 + logging.warn( + "use sync_batch_norm will hang when set num_threads > 1, so " + "set num_threads=1, nccl_comm_num=1, hierachical_allreduce=False." + ) + + # NOTE. compatible with compiler, otherwise these values will be overwritten by compiler + main_program._nccl_comm_num = local_build_strategy.nccl_comm_num + main_program._use_hierarchical_allreduce = local_build_strategy.use_hierarchical_allreduce + main_program._hierarchical_allreduce_inter_nranks = local_build_strategy.hierarchical_allreduce_inter_nranks + + # TODO(guru4elephant): should be an independent optimizer + if worker_num > 1: + self._setup_nccl_op(startup_program, main_program, + local_build_strategy) + + local_build_strategy.num_trainers = self.role_maker._worker_num() + local_build_strategy.trainer_id = self.role_maker._worker_index() + local_build_strategy.trainers_endpoints = self.role_maker._get_trainer_endpoints( + ) + local_build_strategy.enable_backward_optimizer_op_deps = True + + self._compiled_program = compiler.CompiledProgram(main_program) + + self._compiled_program.with_data_parallel( + loss_name=loss.name, + build_strategy=local_build_strategy, + exec_strategy=exe_strategy, + share_vars_from=None) + + return self._compiled_program + + def _disable_strategy(self, dist_strategy): + # TODO(guru4elephant): should close all PE related flags here + return + + def _enable_strategy(self, dist_strategy, context): + # by default, graph execution strategy is enabled + return + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + if startup_program == None: + startup_program = paddle.static.default_startup_program() + compiled_program = self._try_to_compile(startup_program, + loss.block.program, loss) + loss.block.program._graph = compiled_program + + # just return self.optimizer_ops and self.param_grads + return None, None diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lamb_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lamb_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc5bed03aeac8fbf70419476e6844352e79a478 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lamb_optimizer.py @@ -0,0 +1,118 @@ +# 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 + +from paddle.fluid.optimizer import AdamOptimizer +from paddle.fluid.optimizer import LambOptimizer as LAMB +from .meta_optimizer_base import MetaOptimizerBase +import logging + +__all__ = [] + + +class LambOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(LambOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.lamb_opt = None + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = ["GraphExecutionOptimizer"] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(LambOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + opt = self.inner_opt + if not isinstance(opt, AdamOptimizer): + return + + configs = self.user_defined_strategy.lamb_configs + if len(configs['exclude_from_weight_decay']) == 0: + _exclude_from_weight_decay_fn = None + else: + + def exclude_fn(param): + exclude_list = configs['exclude_from_weight_decay'] + for name in exclude_list: + if param.name.endswith(name): + return True + return False + + _exclude_from_weight_decay_fn = exclude_fn + + self.lamb_opt = LAMB( + learning_rate=opt._learning_rate, + lamb_weight_decay=configs['lamb_weight_decay'], + beta1=opt._beta1, + beta2=opt._beta2, + epsilon=opt._epsilon, + parameter_list=opt._parameter_list, + regularization=opt.regularization, + grad_clip=opt._grad_clip, + exclude_from_weight_decay_fn=_exclude_from_weight_decay_fn, + name=opt._name) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.lamb: + if not isinstance(self.inner_opt, AdamOptimizer): + logging.warn( + "lamb need the inner optimizer to be AdamOptimizer optimizer but got {}." + .format(self.inner_opt.type)) + return False + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.lamb = False + dist_strategy.lamb_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.lamb = True + dist_strategy.lamb_configs = { + "lamb_weight_decay": 0.01, + "exclude_from_weight_decay": [] + } + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + return self.lamb_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + # the following function will be used by AMP if both LARS and AMP are turn on together. + def apply_gradients(self, params_grads): + return self.lamb_opt.apply_gradients(params_grads=params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + return self.lamb_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + optimize_ops, params_grads = \ + self.lamb_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lars_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lars_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..44f8fe473e2f982d04ace6b2cc22cc41b47c4e1a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/lars_optimizer.py @@ -0,0 +1,105 @@ +# 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 + +from paddle.fluid.optimizer import Momentum, LarsMomentumOptimizer +from .meta_optimizer_base import MetaOptimizerBase +import logging + +__all__ = [] + + +class LarsOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(LarsOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.lars_opt = None + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = ["GraphExecutionOptimizer"] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(LarsOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + opt = self.inner_opt + if not isinstance(opt, Momentum): + return + + configs = self.user_defined_strategy.lars_configs + + self.lars_opt = LarsMomentumOptimizer( + learning_rate=opt._learning_rate, + momentum=opt._momentum, + lars_coeff=configs['lars_coeff'], + lars_weight_decay=configs['lars_weight_decay'], + parameter_list=opt._parameter_list, + regularization=opt.regularization, + grad_clip=opt._grad_clip, + name=opt._name, + exclude_from_weight_decay=configs['exclude_from_weight_decay'], + epsilon=configs['epsilon']) + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.lars: + if not isinstance(self.inner_opt, Momentum): + logging.warn( + "lars need the inner optimizer to be Momentum optimizer but got {}." + .format(self.inner_opt.type)) + return False + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.lars = False + dist_strategy.lars_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.lars = True + dist_strategy.lars_configs = { + "lars_coeff": 0.01, + "lars_weight_decay": 0.0005, + } + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + return self.lars_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + # the following function will be used by AMP if both LARS and AMP are turn on together. + def apply_gradients(self, params_grads): + return self.lars_opt.apply_gradients(params_grads=params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + return self.lars_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + optimize_ops, params_grads = \ + self.lars_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/localsgd_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/localsgd_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eb170dedb0b72bfd12cd82b66c870c868698cdb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/localsgd_optimizer.py @@ -0,0 +1,431 @@ +# 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. + +from __future__ import print_function + +import paddle +from paddle.fluid import program_guard, layers, default_main_program +from paddle.fluid import default_startup_program +from .meta_optimizer_base import MetaOptimizerBase +from .common import OpRole, OP_ROLE_KEY, CollectiveHelper, is_update_op + +__all__ = [] + + +class LocalSGDOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(LocalSGDOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = ['AMPOptimizer'] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", + "AdaptiveLocalSGDOptimizer", + ] + self.snapshot_key = '@SNAPSHOT' + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if not self.user_defined_strategy.localsgd: + return False + + if self.role_maker._worker_num() <= 1: + return False + + return isinstance(self.inner_opt, paddle.optimizer.momentum.Momentum) \ + or isinstance(self.inner_opt, paddle.fluid.optimizer.Momentum) \ + or isinstance(self.inner_opt, paddle.optimizer.sgd.SGD) \ + or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD) + + def _disable_strategy(self, dist_strategy): + dist_strategy.localsgd = False + dist_strategy.localsgd_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.localsgd = True + dist_strategy.localsgd_configs = {"k_steps": 1, "begin_step": 1} + + def snapshot_name(self, param_name): + return param_name + self.snapshot_key + + def create_snapshot_vars(self, program): + block = program.global_block() + + non_dist_params = [] + for param in block.iter_parameters(): + if not param.is_distributed: + non_dist_params.append(param) + + p2s = [] + for param in non_dist_params: + snapshot = block.create_var(name=self.snapshot_name(param.name), + shape=param.shape, + persistable=True, + stop_gradient=True, + dtype=param.dtype) + p2s.append([param, snapshot]) + return p2s + + def init_snapshot_vars(self, startup_program, param2snapshot): + with program_guard(startup_program): + for param, snapshot in param2snapshot: + layers.assign(param, snapshot) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + minimized = self.inner_opt.minimize(loss, + startup_program=startup_program) + + k_steps_value = self.user_defined_strategy.localsgd_configs['k_steps'] + begin_step_value = self.user_defined_strategy.localsgd_configs[ + 'begin_step'] + + if startup_program is None: + startup_program = default_startup_program() + main_block = loss.block + + self.nrings = 2 + collective_helper = CollectiveHelper(self.role_maker, self.nrings) + collective_helper.update_startup_program(startup_program) + p2s = self.create_snapshot_vars(startup_program) + self.init_snapshot_vars(startup_program, p2s) + + p2s = self.create_snapshot_vars(main_block.program) + with program_guard(main_block.program, startup_program): + step = layers.autoincreased_step_counter(begin=1) + k_steps = layers.create_global_var(name="k_steps", + shape=[1], + value=k_steps_value, + dtype='int64', + persistable=True) + + begin_step = layers.create_global_var(name="begin_step", + shape=[1], + value=begin_step_value, + dtype='int64', + persistable=True) + + last_step = layers.create_global_var(name="last_step", + shape=[1], + value=begin_step_value, + dtype='int64', + persistable=True) + + def communicate(): + sub_block = default_main_program().current_block() + ring_id = -1 + for param, snapshot in p2s: + sub_block.append_op(type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + sub_block.append_op(type='c_sync_calc_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + ring_id = (ring_id + 1) % self.nrings + sub_block.append_op(type='c_allreduce_sum', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Optimize + }) + + for ring_id in range(self.nrings): + sub_block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Optimize + }) + + for param, snapshot in p2s: + sub_block.append_op(type='scale', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'scale': + 1.0 / self.role_maker._worker_num(), + OP_ROLE_KEY: + OpRole.Optimize + }) + sub_block.append_op(type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + sub_block.append_op(type='assign', + inputs={'X': [param]}, + outputs={'Out': [snapshot]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + layers.assign(step, last_step) + + def begin_localsgd(): + layers.cond(step - last_step == k_steps, communicate) + + layers.cond(step > begin_step, begin_localsgd, communicate) + return minimized + + +class AdaptiveLocalSGDOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(AdaptiveLocalSGDOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = ['AMPOptimizer'] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", "LocalSGDOptimizer" + ] + self.snapshot_key = '@SNAPSHOT' + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if not self.user_defined_strategy.adaptive_localsgd: + return False + + if self.role_maker._worker_num() <= 1: + return False + + return isinstance(self.inner_opt, paddle.optimizer.momentum.Momentum) \ + or isinstance(self.inner_opt, paddle.fluid.optimizer.Momentum) \ + or isinstance(self.inner_opt, paddle.optimizer.sgd.SGD) \ + or isinstance(self.inner_opt, paddle.fluid.optimizer.SGD) + + def _disable_strategy(self, dist_strategy): + dist_strategy.adaptive_localsgd = False + dist_strategy.adaptive_localsgd_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.adaptive_localsgd = True + dist_strategy.adaptive_localsgd_configs = { + "init_k_steps": 1, + "begin_step": 1 + } + + def snapshot_name(self, param_name): + return param_name + self.snapshot_key + + def create_snapshot_vars(self, program): + block = program.global_block() + + non_dist_params = [] + for param in block.iter_parameters(): + if not param.is_distributed: + non_dist_params.append(param) + + p2s = [] + for param in non_dist_params: + snapshot = block.create_var(name=self.snapshot_name(param.name), + shape=param.shape, + persistable=True, + stop_gradient=True, + dtype=param.dtype) + p2s.append([param, snapshot]) + return p2s + + def init_snapshot_vars(self, startup_program, param2snapshot): + with program_guard(startup_program): + for param, snapshot in param2snapshot: + layers.assign(param, snapshot) + + def _generate_avg_loss(self, program_block, loss, avg_loss): + program_block.append_op(type='c_allreduce_sum', + inputs={'X': [loss]}, + outputs={'Out': [avg_loss]}, + attrs={ + 'ring_id': 0, + OP_ROLE_KEY: OpRole.Optimize, + 'use_calc_stream': True + }) + program_block.append_op(type='c_sync_calc_stream', + inputs={'X': [avg_loss]}, + outputs={'Out': [avg_loss]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + + program_block.append_op(type='scale', + inputs={'X': [avg_loss]}, + outputs={'Out': [avg_loss]}, + attrs={ + 'scale': + 1.0 / self.role_maker._worker_num(), + OP_ROLE_KEY: OpRole.Optimize + }) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + minimized = self.inner_opt.minimize(loss, + startup_program=startup_program) + + init_k_steps = self.user_defined_strategy.adaptive_localsgd_configs[ + 'init_k_steps'] + begin_step_value = self.user_defined_strategy.adaptive_localsgd_configs[ + 'begin_step'] + + if startup_program is None: + startup_program = default_startup_program() + main_block = loss.block + + self.nrings = 2 + collective_helper = CollectiveHelper(self.role_maker, self.nrings) + collective_helper.update_startup_program(startup_program) + p2s = self.create_snapshot_vars(startup_program) + self.init_snapshot_vars(startup_program, p2s) + + p2s = self.create_snapshot_vars(main_block.program) + with program_guard(main_block.program, startup_program): + step = layers.autoincreased_step_counter(begin=1) + + k_steps = layers.create_global_var(name="k_steps", + shape=[1], + value=int(init_k_steps), + dtype='int64', + persistable=True) + + begin_step = layers.create_global_var(name="begin_step", + shape=[1], + value=int(begin_step_value), + dtype='int64', + persistable=True) + + last_step = layers.create_global_var(name="last_step", + shape=[1], + value=int(0), + dtype='int64', + persistable=True) + + avg_loss = layers.create_global_var(name="avg_loss", + shape=[1], + value=float(0), + dtype=loss.dtype, + persistable=True) + + lr_0 = layers.create_global_var(name="lr_0", + shape=[1], + value=float(0), + dtype='float32', + persistable=True) + + loss_0 = layers.create_global_var(name="loss_0", + shape=[1], + value=float(0), + dtype='float32', + persistable=True) + + global_lr = self.inner_opt._global_learning_rate() + + def initialize(): + self._generate_avg_loss(main_block, loss, avg_loss) + layers.assign(avg_loss, loss_0) + layers.assign(global_lr, lr_0) + + layers.cond(step == 1, initialize) + + def communicate(): + sub_block = default_main_program().current_block() + ring_id = -1 + for param, snapshot in p2s: + sub_block.append_op(type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + sub_block.append_op(type='c_sync_calc_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + ring_id = (ring_id + 1) % self.nrings + sub_block.append_op(type='c_allreduce_sum', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Optimize + }) + + for ring_id in range(self.nrings): + sub_block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Optimize + }) + + for param, snapshot in p2s: + sub_block.append_op(type='scale', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'scale': + 1.0 / self.role_maker._worker_num(), + OP_ROLE_KEY: + OpRole.Optimize + }) + sub_block.append_op(type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + sub_block.append_op(type='assign', + inputs={'X': [param]}, + outputs={'Out': [snapshot]}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + layers.assign(step, last_step) + + def communicate_avg_loss(): + communicate() + self._generate_avg_loss(main_block, loss, avg_loss) + next_local_steps = layers.cast(layers.ceil( + layers.sqrt(lr_0 * avg_loss / (global_lr * loss_0) * + float(init_k_steps))), + dtype='int64') + max_local_steps = layers.fill_constant(shape=[1], + dtype='int64', + value=16) + min_local_steps = layers.fill_constant(shape=[1], + dtype='int64', + value=1) + next_local_steps = layers.elementwise_min( + next_local_steps, max_local_steps) + next_local_steps = layers.elementwise_max( + next_local_steps, min_local_steps) + layers.assign(next_local_steps, k_steps) + + def begin_localsgd(): + layers.cond(step - last_step == k_steps, communicate_avg_loss) + + layers.cond(step > begin_step, begin_localsgd, communicate) + + return minimized diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/meta_optimizer_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/meta_optimizer_base.py new file mode 100644 index 0000000000000000000000000000000000000000..35e11221b6f638b3e2d78ec79d7b9f71477534f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/meta_optimizer_base.py @@ -0,0 +1,101 @@ +# 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. + +from paddle.fluid.optimizer import Optimizer + +__all__ = [] + + +class MetaOptimizerBase(Optimizer): + + def __init__(self, optimizer): + self.inner_opt = optimizer + self._learning_rate = self.inner_opt._learning_rate + self._learning_rate_map = self.inner_opt._learning_rate_map + self.meta_optimizers_white_list = [] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + self.loss = loss + self.role_maker = role_maker + self.user_defined_optimizer = user_defined_optimizer + self.user_defined_strategy = user_defined_strategy + + def _update_inner_optimizer(self, optimizer): + self.inner_opt = optimizer + + def _can_apply(self): + return False + + def _is_graph_out(self): + return False + + def _can_update(self, optimizer): + if str(optimizer.__class__.__name__) in self.meta_optimizers_white_list: + return True + return False + + def _disable_strategy(self, dist_strategy): + raise NotImplementedError( + "you should implement disable strategy in {}".format( + type(self).__name__)) + + def _enable_strategy(self, dist_strategy, context=None): + raise NotImplementedError( + "you should implement enable strategy in {}".format( + type(self).__name__)) + + def apply_gradients(self, params_grads): + return self.inner_opt.apply_gradients(params_grads=params_grads) + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + return self.inner_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_optimize(self, loss, startup_program, params_grads): + return self.inner_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + return optimize_ops, params_grads + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + optimize_ops, params_grads = self.minimize_impl(loss, startup_program, + parameter_list, + no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_graph_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_graph_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..41a5da0d31505e0130a6e3570348948a1144b2cc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_graph_optimizer.py @@ -0,0 +1,79 @@ +# 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 + +from paddle import fluid +from paddle.fluid import compiler +from .parameter_server_optimizer import ParameterServerOptimizer + +__all__ = [] + + +class ParameterServerGraphOptimizer(ParameterServerOptimizer): + + def __init__(self, optimizer): + super(ParameterServerGraphOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [] + + def _can_apply(self): + if self.role_maker._is_collective: + return False + + k_steps = self.user_defined_strategy.a_sync_configs["k_steps"] + if k_steps < 0: + return False + + if self.role_maker._is_server(): + return False + + if self.role_maker._is_heter_parameter_server_mode: + return False + + return True + + def _disable_strategy(self, dist_strategy): + return + + def _enable_strategy(self, dist_strategy, context): + # only open up the async mode for auto-parallel + return + + def _is_graph_out(self): + return True + + def _try_to_compile(self, main_program, loss): + dist_strategy = self._get_distributed_strategy() + + build_strategy = dist_strategy.get_build_strategy() + exec_strategy = dist_strategy.get_execute_strategy() + + self._compiled_program = compiler.CompiledProgram(main_program) + + self._compiled_program.with_data_parallel(loss_name=loss.name, + build_strategy=build_strategy, + exec_strategy=exec_strategy, + share_vars_from=None) + + return self._compiled_program + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + program = loss.block.program + compiled_program = self._try_to_compile(program, loss) + program._graph = compiled_program + # just return self.optimizer_ops and self.param_grads + return None, None diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c04215d45656c98444f7e8d4a3f2a01ca6a4e169 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/parameter_server_optimizer.py @@ -0,0 +1,397 @@ +# 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 + +from paddle import fluid +from .meta_optimizer_base import MetaOptimizerBase +from paddle.fluid import core +import subprocess +import re +import os +import platform +from ..base.private_helper_function import wait_server_ready + +__all__ = [] + + +class ParameterServerOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(ParameterServerOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(ParameterServerOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + #self.micro_batch_size = user_defined_strategy.pipeline_configs[ + # 'micro_batch_size'] + self.num_microbatches = user_defined_strategy.pipeline_configs[ + 'accumulate_steps'] + + def _is_graph_out(self): + return False + + def _can_apply(self): + if self.role_maker._is_collective: + return False + + k_steps = self.user_defined_strategy.a_sync_configs["k_steps"] + return True if k_steps >= 0 else False + + def get_dist_env(self): + trainer_id = int(os.getenv('PADDLE_TRAINER_ID', '0')) + trainer_endpoints = '' + current_endpoint = '' + num_trainers = 0 + if os.getenv('PADDLE_TRAINER_ENDPOINTS'): + trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS') + current_endpoint = trainer_endpoints.split(',')[trainer_id] + num_trainers = len(trainer_endpoints.split(',')) + + return { + 'trainer_id': trainer_id, + 'num_trainers': num_trainers, + 'current_endpoint': current_endpoint, + 'trainer_endpoints': trainer_endpoints + } + + def _get_distributed_strategy(self): + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import StrategyFactory + + k_steps = self.user_defined_strategy.a_sync_configs["k_steps"] + strategy = None + + if not self.user_defined_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_sync_strategy() + + if self.user_defined_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_async_strategy() + + if self.user_defined_strategy.a_sync and k_steps > 0: + strategy = StrategyFactory.create_geo_strategy(k_steps) + + if not strategy: + raise ValueError("k_steps must be invalid value, please check") + + return strategy + + def _build_trainer_programs(self, compiled_config): + from paddle.fluid.incubate.fleet.parameter_server.ir import trainer_pass as worker + + _main = compiled_config.origin_main_program.clone() + _startup = compiled_config.origin_startup_program.clone() + + use_ps_gpu = self.user_defined_strategy.a_sync_configs["use_ps_gpu"] + + if not compiled_config.is_geo_mode(): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _add_lr_decay_table_pass + _add_lr_decay_table_pass( + _main, compiled_config, + self.user_defined_strategy.a_sync_configs["lr_decay_steps"]) + + # for main program + _main = worker.distributed_ops_pass(_main, compiled_config, + use_ps_gpu) + if not use_ps_gpu: + _main = worker.delete_optimizer_pass(_main, compiled_config) + _main = worker.append_send_ops_pass(_main, compiled_config) + _startup = worker.delete_extra_optimizes_pass( + _startup, compiled_config) + + # for startup program + _startup = worker.fake_init_ops_pass(_startup, compiled_config) + if use_ps_gpu: + _main = worker.ps_gpu_pass(_main) + from paddle.fluid.transpiler.collective import SingleProcessMultiThread + t = SingleProcessMultiThread() + env = self.get_dist_env() + t.transpile(startup_program=_startup, + main_program=_main, + rank=env["trainer_id"], + endpoints=env["trainer_endpoints"], + current_endpoint=env['current_endpoint'], + wait_port=False) + + compiled_config.set_origin_ps_main_program(_main) + compiled_config.set_origin_ps_startup_program(_startup) + # for heter program + if self.role_maker._is_heter_parameter_server_mode: + from paddle.fluid.incubate.fleet.parameter_server.ir import heter_trainer_pass as heter_worker + if self.role_maker._is_heter_worker(): + # for heter worker + stage_id = self.role_maker._get_stage_id() + device = self.role_maker._heter_device_type().lower() + _main = heter_worker.split_heter_worker_ops_pass( + _main, compiled_config, stage_id, device) + else: + # for default worker + _main = heter_worker.split_trainer_ops_pass( + _main, compiled_config) + else: + _main = worker.append_send_ops_pass(_main, compiled_config) + _startup = _startup + compiled_config.set_origin_ps_main_program(_main) + compiled_config.set_origin_ps_startup_program(_startup) + + launch_barrier = self.user_defined_strategy.a_sync_configs[ + "launch_barrier"] + launch_barrier_flag = int(os.getenv("FLAGS_LAUNCH_BARRIER", "1")) + if launch_barrier and launch_barrier_flag: + # for trainer wait server ready + wait_server_ready(self.role_maker._get_pserver_endpoints()) + + # for ps-heter mode, wait heter worker ready + # if self.role_maker._is_heter_parameter_server_mode and self.role_maker._is_worker( + # ): + # wait_server_ready(self.role_maker._get_heter_worker_endpoints()) + + return _main, _startup + + def _build_pserver_programs(self, compiled_config): + _main = fluid.Program() + _startup = fluid.Program() + + from paddle.fluid.incubate.fleet.parameter_server.ir import pserver_pass as server + + if not compiled_config.is_geo_mode(): + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_optimize_ops + is_sgd_adam = False + + main_program = compiled_config.get_origin_main_program() + ops = _get_optimize_ops(main_program) + + if len(ops) == 0: + return _main, _startup + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _add_lr_decay_table_pass + lr_decay_steps = self.user_defined_strategy.a_sync_configs[ + "lr_decay_steps"] + _add_lr_decay_table_pass(main_program, compiled_config, + lr_decay_steps) + + for op in ops: + if op.type in ["sgd", "adam"]: + is_sgd_adam = True + break + + if is_sgd_adam: + return _main, _startup + + _main = server.add_listen_and_serv_pass(_main, compiled_config) + _main = server.add_rpc_global_flags_pass(_main, compiled_config) + _main = server.add_optimizer_pass(_main, compiled_config) + _main = server.large_scale_sparse_pass(_main, _main, + compiled_config, False) + _startup = server.build_pserver_startup_program_pass( + _startup, _main, compiled_config) + _startup = server.large_scale_sparse_pass(_startup, _main, + compiled_config, True) + + if not compiled_config.is_sync_mode(): + _main = server.delete_unused_in_main_pass( + _main, compiled_config) + + _startup = server.delete_unused_in_startup_pass( + _startup, _main, compiled_config) + else: + _main = server.add_listen_and_serv_pass(_main, compiled_config) + _main = server.add_rpc_global_flags_pass(_main, compiled_config) + _main = server.add_geo_optimizer_pass(_main, compiled_config) + _startup = server.build_pserver_startup_program_pass( + _startup, _main, compiled_config) + _startup = server.delete_unused_in_startup_pass( + _startup, _main, compiled_config) + + return _main, _startup + + def _can_apply_geo(self, dist_strategy, program): + + def get_sys_free_mem(): + plat = platform.system() + if platform.system() == "Darwin": + vm = subprocess.Popen(['vm_stat'], + stdout=subprocess.PIPE).communicate()[0] + # Process vm_stat + vmLines = vm.split('\n') + sep = re.compile(r':[\s]+') + vmStats = {} + for row in range(1, len(vmLines) - 2): + rowText = vmLines[row].strip() + rowElements = sep.split(rowText) + vmStats[(rowElements[0])] = int( + rowElements[1].strip(r'\.')) * 4096 + return vmStats["Pages free"] + elif platform.system() == "Linux": + mems = {} + with open('/proc/meminfo', 'rb') as f: + for line in f: + fields = line.split() + mems[fields[0]] = int(fields[1]) * 1024 + free = mems[b'MemFree:'] + return free + else: + raise ValueError( + "%s platform is unsupported is parameter server optimizer" % + (platform.system())) + + if not isinstance(self.inner_opt, fluid.optimizer.SGDOptimizer): + return False + + free = get_sys_free_mem() + + from paddle.fluid.incubate.fleet.parameter_server.ir import vars_metatools + + processed_var_names = set(["@EMPTY@"]) + param_memory_size = 0 + for varname in program.global_block().vars: + var = program.global_block().vars[varname] + if not var.persistable or var.desc.type( + ) != core.VarDesc.VarType.LOD_TENSOR: + continue + param = vars_metatools.create_var_struct(var) + param_memory_size += param.m_size + processed_var_names.add(varname) + + upper_mem_use = param_memory_size * 5.0 + + program_tmp_vars = dict() + eval_batch_size = 1024 + for op in program.global_block().ops: + for var_name in op.output_arg_names: + if var_name in processed_var_names: + continue + processed_var_names.add(var_name) + var = program.global_block().vars[var_name] + + if var.desc.type() != core.VarDesc.VarType.LOD_TENSOR: + continue + + data_count = 1 + neg_dim_count = 0 + for x in var.shape: + if x < 0: + if neg_dim_count >= 1: + raise ValueError( + "Var %s has more than one negative dim." % + (var_name)) + neg_dim_count += 1 + data_count *= (-x) + else: + data_count *= x + program_tmp_vars[var_name] = ( + data_count, neg_dim_count, + vars_metatools.dtype_to_size[var.dtype]) + + for varname in program_tmp_vars: + data_count, neg_dim_count, type_size = program_tmp_vars[varname] + if neg_dim_count == 1: + data_count *= eval_batch_size + var_memory = data_count * type_size + upper_mem_use += var_memory + + if upper_mem_use < free: + return True + else: + return False + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self.inner_opt.minimize(loss, startup_program, parameter_list, + no_grad_set) + strategy = self._get_distributed_strategy() + + _origin_main_program = loss.block.program + _origin_startup_program = startup_program + from paddle.fluid.incubate.fleet.parameter_server.ir import public as public + + compiled_config = public.CompileTimeStrategy(_origin_main_program, + _origin_startup_program, + strategy, self.role_maker) + compiled_config.strategy = strategy + + if self.role_maker._is_worker() or self.role_maker._is_heter_worker(): + main_program, startup_program = self._build_trainer_programs( + compiled_config) + if self.role_maker._is_heter_parameter_server_mode: + _origin_startup_program._heter_pipeline_opt = { + "startup_program": startup_program, + "pipeline_stage": int(self.role_maker._get_stage_id()) - 1, + "heter_place": self.role_maker._heter_device(), + } + + loss.block.program._heter_pipeline_opt = { + "trainer": "HeterPipelineTrainer", + "device_worker": "HeterSection", + "trainers": self.role_maker._get_stage_trainers( + ), ## trainer num in each stage + "trainer_id": int(self.role_maker._role_id()), + "pipeline_stage": int(self.role_maker._get_stage_id()) - 1, + "num_pipeline_stages": + int(self.role_maker._get_num_stage()), + "section_program": main_program, + "num_microbatches": self.num_microbatches, + "heter_place": self.role_maker._heter_device(), + } + else: + loss.block.program = main_program + fluid.framework.switch_startup_program(startup_program) + + elif self.role_maker._is_server(): + main_program, startup_program = self._build_pserver_programs( + compiled_config) + loss.block.program = main_program + fluid.framework.switch_startup_program(startup_program) + return None, None + + def _disable_strategy(self, dist_strategy): + #if self.role_maker._is_heter_parameter_server_mode: + # dist_strategy.pipeline = False + # dist_strategy.pipeline_configs = { + # "micro_batch_size": 1, + # "accumulate_steps": 1, + # } + dist_strategy.a_sync = False + a_sync_configs = dist_strategy.a_sync_configs + a_sync_configs["k_steps"] = -1 + dist_strategy.a_sync_configs = a_sync_configs + + def _enable_strategy(self, dist_strategy, context): + #if self.role_maker._is_heter_parameter_server_mode: + # dist_strategy.pipeline = True + # dist_strategy.pipeline_configs = { + # "micro_batch_size": 1, + # "accumulate_steps": 1, + # } + a_sync_configs = dist_strategy.a_sync_configs + if a_sync_configs["k_steps"] >= 0: + return + + dist_strategy.a_sync = True + a_sync_configs = dist_strategy.a_sync_configs + + is_geo = self._can_apply_geo(dist_strategy, + context["origin_main_program"]) + + if is_geo: + a_sync_configs["k_steps"] = 800 + else: + a_sync_configs["k_steps"] = 0 + dist_strategy.a_sync_configs = a_sync_configs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/pipeline_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/pipeline_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f461850b8a13fca9e13076eae4d6359892eac3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/pipeline_optimizer.py @@ -0,0 +1,274 @@ +# 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 + +from __future__ import print_function +from __future__ import division +import os + +import paddle.fluid as fluid +from paddle.fluid import core, unique_name +from ..base.private_helper_function import wait_server_ready +from paddle.fluid.optimizer import PipelineOptimizer as PO +from .meta_optimizer_base import MetaOptimizerBase +from .common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY, CollectiveHelper, is_loss_grad_op, is_backward_op, is_optimizer_op + +__all__ = [] + + +class PipelineOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(PipelineOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = [ + "RecomputeOptimizer", + "AMPOptimizer", + ] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", + ] + self.global_ring_id = 1 + self.dp_ring_id = 2 + self.start_pipeline_ring_id = 20 # Just a magic number + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(PipelineOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + self.micro_batch_size = user_defined_strategy.pipeline_configs[ + 'micro_batch_size'] + self.num_microbatches = user_defined_strategy.pipeline_configs[ + 'accumulate_steps'] + self.schedule_mode = user_defined_strategy.pipeline_configs[ + 'schedule_mode'] + self.use_sharding = user_defined_strategy.sharding + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + # FIXME revise for hybrid parallelism + if self.use_sharding: + return False + + if self.user_defined_strategy.pipeline == True: + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.pipeline = False + dist_strategy.pipeline_configs = { + "micro_batch_size": 1, + "accumulate_steps": 1, + "schedule_mode": "1F1B", + } + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.pipeline = True + dist_strategy.pipeline_configs = { + "micro_batch_size": 1, + "accumulate_steps": 1, + "schedule_mode": "1F1B", + } + + def _broadcast_params(self, ring_id): + block = self.startup_program.global_block() + param = None + for param in block.iter_parameters(): + if param.is_distributed: + continue + + block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': 0, + OP_ROLE_KEY: OpRole.Forward + }) + + if not param: return # no parameter on this device + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + + def _get_process_group_info(self): + # global ring info + self.global_endpoints = self.endpoints + self.global_rank = self.rank + self.global_nranks = self.nranks + + # data parallel ring info + if self.pipeline_num > 1: + self.dp_rank = self.rank // self.inner_parallelism + self.dp_nranks = self.nranks // self.inner_parallelism + start_index = self.rank % self.inner_parallelism + self.dp_endpoints = [ + self.endpoints[start_index + i * self.inner_parallelism] + for i in range(self.pipeline_num) + ] + + def _init_process_group(self, pipeline_pair, pipeline_ring_map): + self._get_process_group_info() + collective_helper = CollectiveHelper(self.role_maker, wait_port=False) + # Create global ring for all gpus (ring_id = 0) + collective_helper._init_communicator(self.startup_program, + self.current_endpoint, + self.global_endpoints, + self.global_rank, + self.global_ring_id, True, + self.global_ring_id, True) + # Create pipeline rings + if self.inner_parallelism > 1: + pipeline_id = self.rank // self.inner_parallelism + start_index = pipeline_id * self.inner_parallelism + for pair in pipeline_pair: + pair_key = pair[0] * 1000 + pair[1] + ring_id = pipeline_ring_map[pair_key] + assert ring_id >= self.start_pipeline_ring_id + first_node = pair[0] + start_index + second_node = pair[1] + start_index + if self.rank != first_node and self.rank != second_node: + collective_helper._init_communicator( + self.startup_program, None, None, None, None, False, + self.global_ring_id, True) + continue + pipeline_endpoints = [ + self.endpoints[first_node], self.endpoints[second_node] + ] + pipeline_rank = 0 if self.rank == first_node else 1 + pipeline_nranks = 2 + collective_helper._init_communicator(self.startup_program, + self.current_endpoint, + pipeline_endpoints, + pipeline_rank, ring_id, + False, self.global_ring_id, + True) + + # Create dp rings + if self.pipeline_num > 1: + collective_helper._init_communicator( + self.startup_program, self.current_endpoint, self.dp_endpoints, + self.dp_rank, self.dp_ring_id, True, self.global_ring_id, True) + self._broadcast_params(self.dp_ring_id) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self.endpoints = self.role_maker._get_trainer_endpoints() + self.current_endpoint = self.endpoints[self.role_maker._worker_index()] + self.rank = self.role_maker._worker_index() + self.nranks = self.role_maker._worker_num() + + self.wrapped_opt = PO(self.inner_opt, + num_microbatches=self.num_microbatches) + orig_startup_program = startup_program if startup_program else fluid.default_startup_program( + ) + block = loss.block + program = block.program + + program._pipeline_opt = dict() + program._pipeline_opt['local_rank'] = self.rank + program._pipeline_opt['global_ring_id'] = self.global_ring_id + program._pipeline_opt['ring_id'] = self.start_pipeline_ring_id + program._pipeline_opt['micro_batch_size'] = self.micro_batch_size + program._pipeline_opt['schedule_mode'] = self.schedule_mode + program._pipeline_opt['use_sharding'] = False + program._pipeline_opt['mp_degree'] = 1 + program._pipeline_opt['mp_rank'] = 0 + optimize_ops, params_grads, prog_list, pp_pair, ring_map = self.wrapped_opt.minimize( + loss, startup_program, parameter_list, no_grad_set) + self.startup_program = orig_startup_program._pipeline_opt[ + 'startup_program'] + self.inner_parallelism = program._pipeline_opt['inner_parallelism'] + assert self.nranks % self.inner_parallelism == 0 + assert prog_list + self.pipeline_num = len(self.endpoints) // self.inner_parallelism + + self._init_process_group(pp_pair, ring_map) + + self.main_program_list = prog_list + self.main_program = program + if self.pipeline_num > 1: + self._transpile_main_program(loss) + return optimize_ops, params_grads + + def _transpile_main_program(self, loss): + self._insert_loss_grad_ops(loss, self.pipeline_num) + self._insert_allreduce_ops(self.dp_ring_id) + + def _insert_loss_grad_ops(self, loss, pipeline_num): + """ + In order to keep the learning rate consistent in different numbers of + training workers, we scale the loss grad by the number of workers + """ + block = self.main_program_list[-1].global_block() + for idx, op in reversed(list(enumerate(block.ops))): + if is_loss_grad_op(op): + loss_grad_var = block.vars[op.output_arg_names[0]] + block._insert_op(idx + 1, + type='scale', + inputs={'X': loss_grad_var}, + outputs={'Out': loss_grad_var}, + attrs={ + 'scale': 1.0 / pipeline_num, + OP_ROLE_KEY: OpRole.Backward + }) + + def _insert_allreduce_ops(self, ring_id): + block = self.main_program._pipeline_opt['section_program'].global_block( + ) + origin_block = self.main_program.global_block() + grad = None + processed_param_name = set() + first_optimize_op_idx = None + for idx, op in reversed(list(enumerate(block.ops))): + if is_backward_op(op) and not first_optimize_op_idx: + first_optimize_op_idx = idx + 1 + # no optimize phase + if first_optimize_op_idx == len(block.ops): return + if is_backward_op(op) and \ + OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.all_attrs()[OP_ROLE_VAR_KEY] + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + offset = 0 + for i in range(0, len(op_role_var), 2): + param_name = op_role_var[i] + param = block.vars[op_role_var[i]] + if param_name in processed_param_name: continue + processed_param_name.add(param_name) + grad_name = op_role_var[i + 1] + if not 'MERGED' in grad_name: grad_name += '@MERGED' + grad = block.vars[grad_name] + origin_param = origin_block.vars[op_role_var[i]] + if origin_param.is_distributed: + continue + + block._insert_op(first_optimize_op_idx + offset, + type='c_allreduce_sum', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize + }) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ps_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ps_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..f274743d5d807cfc226c87d4cef4a6b163f998ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/ps_optimizer.py @@ -0,0 +1,258 @@ +# Copyright (c) 2022 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 + +from paddle import fluid +import paddle.distributed.passes +from .meta_optimizer_base import MetaOptimizerBase +from paddle.fluid import core +import subprocess +import re +import os +import platform +from paddle.distributed.ps.utils.public import * +from paddle.distributed.passes import PassContext +from ..base.private_helper_function import wait_server_ready +from paddle.distributed.ps.utils.ps_factory import PsProgramBuilderFactory + + +class ParameterServerOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(ParameterServerOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(ParameterServerOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _set_origin_programs(self, losses): + self.origin_main_programs = [] + for loss in losses: + self.origin_main_programs.append(loss.block.program) + + def _init_ps_pass_context(self, loss, startup_program): + self.pass_ctx = PassContext() + attrs = {} + # trainer + attrs["env"] = get_dist_env() + + attrs['loss'] = loss + attrs['min_block_size'] = 81920 + attrs['origin_main_program'] = loss.block.program + attrs['origin_startup_program'] = startup_program + + attrs['origin_main_programs'] = self.origin_main_programs + + attrs['cloned_main'] = attrs['origin_main_program'].clone() + attrs['cloned_startup'] = attrs['origin_startup_program'].clone() + + attrs['user_defined_strategy'] = self.user_defined_strategy + attrs['valid_strategy'] = self.user_defined_strategy + attrs['trainer'] = TrainerRuntimeConfig(self.user_defined_strategy) + attrs['ps_mode'] = attrs['trainer'].mode + logger.info("ps_mode: {}".format(attrs['ps_mode'])) + attrs['role_maker'] = self.role_maker + attrs[ + 'is_heter_ps_mode'] = self.role_maker._is_heter_parameter_server_mode + attrs['is_worker'] = self.role_maker._is_worker() + attrs['is_server'] = self.role_maker._is_server() + attrs['is_heter_worker'] = self.role_maker._is_heter_worker() + logger.info("this process is heter? {}".format( + attrs['is_heter_worker'])) + attrs['use_ps_gpu'] = self.user_defined_strategy.a_sync_configs[ + "use_ps_gpu"] + attrs['lr_decay_steps'] = self.user_defined_strategy.a_sync_configs[ + "lr_decay_steps"] + # FL + attrs['local_sparse'] = attrs[ + "user_defined_strategy"].trainer_desc_configs["local_sparse"] + attrs['remote_sparse'] = attrs[ + "user_defined_strategy"].trainer_desc_configs["remote_sparse"] + attrs['is_fl_ps_mode'] = self.user_defined_strategy.is_fl_ps_mode + attrs[ + 'with_coordinator'] = self.user_defined_strategy.is_with_coordinator + + attrs['k_steps'] = self.user_defined_strategy.a_sync_configs["k_steps"] + attrs['launch_barrier'] = self.user_defined_strategy.a_sync_configs[ + "launch_barrier"] + + attrs['launch_barrier_flag'] = int( + os.getenv("FLAGS_LAUNCH_BARRIER", "1")) + + build_var_distributed(attrs) + + # server + attrs['_main_server'] = fluid.Program() + attrs['_startup_server'] = fluid.Program() + attrs['tensor_table'] = {} + + self.pass_ctx._attrs = attrs + + def _is_graph_out(self): + return False + + def _can_apply(self): + if self.role_maker._is_collective: + return False + + k_steps = self.user_defined_strategy.a_sync_configs["k_steps"] + return True if k_steps >= 0 else False + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self.inner_opt.minimize(loss, startup_program, parameter_list, + no_grad_set) + if startup_program == None: + startup_program = paddle.static.default_startup_program() + + +# print("program after inner optimizer minimize:", +# str(loss.block.program)) + self._set_origin_programs([loss]) + self._init_ps_pass_context(loss, startup_program) + ps_builder = PsProgramBuilderFactory()._create_ps_program_builder( + self.pass_ctx) + ps_builder._build_programs() + return None, None + + def minimize_losses_impl(self, + losses, + startup_program=None, + parameter_list=None, + no_grad_set=None): + if parameter_list is None: + parameter_list = [None] * len(losses) + for idx, loss in enumerate(losses): + startup_prog = startup_program[idx] + parameters = parameter_list[idx] + self.inner_opt.minimize(loss, startup_prog, parameters, no_grad_set) + self._set_origin_programs(losses) + for idx, loss in enumerate(losses): + print("ps_optimizer idx loss:", idx, loss) + startup_prog = startup_program[idx] + self._init_ps_pass_context(loss, startup_prog) + ps_builder = PsProgramBuilderFactory()._create_ps_program_builder( + self.pass_ctx) + ps_builder._build_programs() + startup_program[idx] = self.pass_ctx._attrs['cloned_startup'] + return None, None + + def _can_apply_geo(self, program): + + def get_sys_free_mem(): + plat = platform.system() + if platform.system() == "Darwin": + vm = subprocess.Popen(['vm_stat'], + stdout=subprocess.PIPE).communicate()[0] + # Process vm_stat + vmLines = vm.split('\n') + sep = re.compile(r':[\s]+') + vmStats = {} + for row in range(1, len(vmLines) - 2): + rowText = vmLines[row].strip() + rowElements = sep.split(rowText) + vmStats[(rowElements[0])] = int( + rowElements[1].strip(r'\.')) * 4096 + return vmStats["Pages free"] + elif platform.system() == "Linux": + mems = {} + with open('/proc/meminfo', 'rb') as f: + for line in f: + fields = line.split() + mems[fields[0]] = int(fields[1]) * 1024 + free = mems[b'MemFree:'] + return free + else: + raise ValueError( + "%s platform is unsupported is parameter server optimizer" % + (platform.system())) + + if not isinstance(self.inner_opt, fluid.optimizer.SGDOptimizer): + return False + + free = get_sys_free_mem() + processed_var_names = set(["@EMPTY@"]) + param_memory_size = 0 + for varname in program.global_block().vars: + var = program.global_block().vars[varname] + if not var.persistable or var.desc.type( + ) != core.VarDesc.VarType.LOD_TENSOR: + continue + param_memory_size += get_var_mem_size(var) + processed_var_names.add(varname) + + upper_mem_use = param_memory_size * 5.0 + + program_tmp_vars = dict() + eval_batch_size = 1024 + for op in program.global_block().ops: + for var_name in op.output_arg_names: + if var_name in processed_var_names: + continue + processed_var_names.add(var_name) + var = program.global_block().vars[var_name] + + if var.desc.type() != core.VarDesc.VarType.LOD_TENSOR: + continue + + data_count = 1 + neg_dim_count = 0 + for x in var.shape: + if x < 0: + if neg_dim_count >= 1: + raise ValueError( + "Var %s has more than one negative dim." % + (var_name)) + neg_dim_count += 1 + data_count *= (-x) + else: + data_count *= x + program_tmp_vars[var_name] = (data_count, neg_dim_count, + dtype_to_size[var.dtype]) + + for varname in program_tmp_vars: + data_count, neg_dim_count, type_size = program_tmp_vars[varname] + if neg_dim_count == 1: + data_count *= eval_batch_size + var_memory = data_count * type_size + upper_mem_use += var_memory + + if upper_mem_use < free: + return True + else: + return False + + def _enable_strategy(self, dist_strategy, context): + a_sync_configs = dist_strategy.a_sync_configs + if dist_strategy.a_sync_configs["k_steps"] >= 0: + return + dist_strategy.a_sync = True + a_sync_configs = dist_strategy.a_sync_configs + + is_geo = self._can_apply_geo(context["origin_main_program"]) + + a_sync_configs["k_steps"] = 800 if is_geo else 0 + dist_strategy.a_sync_configs = a_sync_configs + + def _disable_strategy(self, dist_strategy): + dist_strategy.a_sync = False + a_sync_configs = dist_strategy.a_sync_configs + dist_strategy.a_sync_configs["k_steps"] = -1 + dist_strategy.a_sync_configs = a_sync_configs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/raw_program_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/raw_program_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2c7b1e45ebd1b21d961e1af47346260379f3df22 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/raw_program_optimizer.py @@ -0,0 +1,478 @@ +# Copyright (c) 2021 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 + +from __future__ import print_function +from __future__ import division +import os +import collections +import numpy as np + +import paddle.fluid as fluid +from paddle.fluid import core, unique_name +from paddle.fluid.dygraph import Layer, LayerList +from ..base.private_helper_function import wait_server_ready +from .meta_optimizer_base import MetaOptimizerBase +from .common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY, CollectiveHelper, is_loss_grad_op, is_backward_op, is_optimizer_op + + +class RawProgramOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(RawProgramOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = [ + "RecomputeOptimizer", + "AMPOptimizer", + "GradientMergeOptimizer", + "LambOptimizer", + "LarsOptimizer", + "DGCOptimizer", + "LocalSGDOptimizer", + ] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", + ] + self.global_ring_id = 0 + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(RawProgramOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + self.without_graph_optimization = user_defined_strategy.without_graph_optimization + self.fuse_all_reduce_ops = user_defined_strategy.fuse_all_reduce_ops + if self.fuse_all_reduce_ops: + self.fuse_grad_size_in_num = user_defined_strategy.fuse_grad_size_in_num + self.calc_comm_same_stream = user_defined_strategy._calc_comm_same_stream + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.without_graph_optimization == True: + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.without_graph_optimization = False + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.without_graph_optimization = True + + def _broadcast_params(self, ring_id): + block = self.startup_program.global_block() + param = None + for param in block.iter_parameters(): + if param.is_distributed: + continue + + block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': 0, + OP_ROLE_KEY: OpRole.Forward + }) + + if not param: return # no parameter on this device + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + + def _get_process_group_info(self): + # global ring info + self.global_endpoints = self.endpoints + self.global_rank = self.rank + self.global_nranks = self.nranks + + def _init_process_group(self): + self._get_process_group_info() + collective_helper = CollectiveHelper(self.role_maker, wait_port=False) + # Create global ring for all gpus (ring_id = 0) + collective_helper._init_communicator(self.startup_program, + self.current_endpoint, + self.global_endpoints, + self.global_rank, + self.global_ring_id, True, + self.global_ring_id, True) + self._broadcast_params(self.global_ring_id) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self.endpoints = self.role_maker._get_trainer_endpoints() + self.current_endpoint = self.endpoints[self.role_maker._worker_index()] + self.rank = self.role_maker._worker_index() + self.nranks = self.role_maker._worker_num() + if startup_program is None: + startup_program = fluid.default_startup_program() + self.startup_program = startup_program + + block = loss.block + program = block.program + self.main_program = program + + optimize_ops, params_grads = self.inner_opt.minimize( + loss, startup_program, parameter_list, no_grad_set) + if self.nranks == 1: + return optimize_ops, params_grads + self._init_process_group() + + self.main_program = program + if self.nranks > 1: + self._transpile_main_program(loss) + return optimize_ops, params_grads + + def _find_gradient_merge_block(self): + GRAD_MERGE_COND_NAME = "grad_merge_cond_name" + gm_cond_var_name = None + for op in self.main_program.global_block().ops: + if GRAD_MERGE_COND_NAME not in op.attr_names: + continue + if gm_cond_var_name is None: + gm_cond_var_name = op.attr(GRAD_MERGE_COND_NAME) + else: + assert gm_cond_var_name == op.attr( + GRAD_MERGE_COND_NAME + ), "multiple gradient merge condition found" + if gm_cond_var_name is None: + return None + + cond_op = None # false_fn of gm is None, so we should only find one block + for op in self.main_program.global_block().ops: + if op.type != 'conditional_block' or 'Cond' not in op.input_names: + continue + cond_vars = op.input('Cond') + if not cond_vars or cond_vars[0] != gm_cond_var_name: + continue + assert cond_op is None, "multiple gradient merge block found" + cond_op = op + assert cond_op is not None, "cannot find gradient merge block" + return cond_op._block_attr("sub_block") + + def _insert_allreduce_ops_for_gm(self, gm_block): + block = self.main_program.global_block() + + first_optimize_op_idx = None + for i, op in reversed(list(enumerate(gm_block.ops))): + if is_backward_op(op) and first_optimize_op_idx is None: + first_optimize_op_idx = i + 1 + break + if first_optimize_op_idx is None: + first_optimize_op_idx = 0 + + param_vars = [] + grad_vars = [] + for op in block.ops: + if is_backward_op(op) and \ + OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.attr(OP_ROLE_VAR_KEY) + assert len(op_role_var) % 2 == 0 + for i in range(0, len(op_role_var), 2): + param = block.var(op_role_var[i]) + grad = block.var(op_role_var[i + 1]) + if param.is_distributed: + continue + param_vars.append(param) + grad_vars.append(grad) + + if not grad_vars: + return + + gm_block._insert_op(first_optimize_op_idx, + type="c_sync_calc_stream", + inputs={'X': grad_vars[0]}, + outputs={'Out': grad_vars[0]}, + attrs={OP_ROLE_KEY: OpRole.Backward}) + + insert_op_num = 1 + ring_id = self.global_ring_id + + # NOTE: can perform fuse allreduce inside the loop in the future + for i, (p, g) in enumerate(zip(param_vars, grad_vars)): + gm_block._insert_op(first_optimize_op_idx + insert_op_num, + type="c_allreduce_sum", + inputs={'X': g}, + outputs={'Out': g}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward, + }) + insert_op_num += 1 + + gm_block._insert_op(first_optimize_op_idx + insert_op_num, + type="c_sync_comm_stream", + inputs={'X': grad_vars}, + outputs={'Out': grad_vars}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward, + }) + + def _transpile_main_program(self, loss): + self._insert_loss_grad_ops(loss) + gm_block = self._find_gradient_merge_block() + if gm_block is not None: + # TODO(zjl): support fuse allreduce + self._insert_allreduce_ops_for_gm(gm_block) + return + + if self.fuse_all_reduce_ops and self.fuse_grad_size_in_num > 1: + self._allreduce_fusion_program() + else: + self._insert_allreduce_ops() + + def _insert_loss_grad_ops(self, loss): + """ + In order to keep the learning rate consistent in different numbers of + training workers, we scale the loss grad by the number of workers + """ + block = self.main_program.global_block() + for idx, op in reversed(list(enumerate(block.ops))): + if is_loss_grad_op(op): + loss_grad_var = block.vars[op.output_arg_names[0]] + block._insert_op(idx + 1, + type='scale', + inputs={'X': loss_grad_var}, + outputs={'Out': loss_grad_var}, + attrs={ + 'scale': 1.0 / self.nranks, + OP_ROLE_KEY: OpRole.Backward + }) + + def _insert_allreduce_ops(self): + block = self.main_program.global_block() + ring_id = self.global_ring_id + grad = None + grad_vars = [] + for idx, op in reversed(list(enumerate(block.ops))): + if is_backward_op(op) and \ + OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.attr(OP_ROLE_VAR_KEY) + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + offset = 1 + for i in range(0, len(op_role_var), 2): + param_name = op_role_var[i] + param = block.var(param_name) + grad_name = op_role_var[i + 1] + grad = block.var(grad_name) + if param.is_distributed: + continue + + grad_vars.append(grad) + block._insert_op(idx + offset, + type='c_sync_calc_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + OP_ROLE_KEY: OpRole.Backward, + }) + offset += 1 + block._insert_op(idx + offset, + type='c_allreduce_sum', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward + }) + + if grad is None: + return + + for idx, op in enumerate(block.ops): + if is_optimizer_op(op): + block._insert_op(idx, + type='c_sync_comm_stream', + inputs={'X': grad_vars}, + outputs={'Out': grad_vars}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward + }) + break + + # This function helps reduce the number of allreduce by integrating op, which can save communication time. + # to use allreduce fuse, follow these codes: + # strategy = paddle.distributed.fleet.DistributedStrategy() + # strategy.without_graph_optimization = True + # strategy.fuse_all_reduce_ops = True + # strategy.calc_comm_same_stream = False + # strategy.fuse_grad_size_in_num = 8 + def _allreduce_fusion_program(self): + block = self.main_program.global_block() + ring_id = self.global_ring_id + param_grads = [] + first_backward_idx = -1 + + # find all grad params + for idx, op in enumerate(block.ops): + if first_backward_idx == -1 and \ + is_backward_op(op): + first_backward_idx = idx + if is_backward_op(op) and \ + OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.attr(OP_ROLE_VAR_KEY) + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0, "vars need to be one param var followed by one grad var, " \ + "but got odd number of vars" + for i in range(0, len(op_role_var), 2): + param_name = op_role_var[i] + param = block.var(param_name) + grad_name = op_role_var[i + 1] + grad = block.var(grad_name) + if param.is_distributed: + continue + param_grads.append((param, grad)) + + outputs_name_to_idx = self.__get_ouputs_name_to_idx( + first_backward_idx, block) + + # structure of grad_param_segments is + # [([grad0, grad1], [param0, param1]), ([grad2, grad3], [param2, param3])] + # each entry of the list is a tuple stores the grads segment list and + # the corresponding params segment list + grad_param_segments = [] + last_dtype = None + # split the grad based on dtype and fused size + for param, grad in param_grads: + if len(grad_param_segments) == 0 \ + or len(grad_param_segments[-1][0]) == self.fuse_grad_size_in_num \ + or grad.dtype != last_dtype: + grad_param_segments.append(([grad], [param])) + last_dtype = grad.dtype + else: + grad_param_segments[-1][0].append(grad) + grad_param_segments[-1][1].append(param) + + if len(grad_param_segments) == 0: + return + + fused_vars = [None] * len(grad_param_segments) + for i in range(len(grad_param_segments) - 1, -1, -1): + # travers the grad_param_segments in backward + # not to use reversed since needs the absolute index value + grad_segment, param_segment = grad_param_segments[i] + # insert coalesce tensor + fused_var = block.create_var(name=unique_name.generate( + 'FusedOutput_{}'.format(grad_segment[0].name)), + dtype=grad_segment[0].dtype, + persistable=False, + stop_gradient=True) + fused_vars[i] = fused_var + after_idx = outputs_name_to_idx[grad_segment[-1]][1] + block._insert_op_without_sync(after_idx + 1, + type='c_allreduce_sum', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': + self.calc_comm_same_stream, + OP_ROLE_KEY: OpRole.Backward + }) + if not self.calc_comm_same_stream: + block._insert_op_without_sync( + after_idx + 1, + type='c_sync_calc_stream', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={OP_ROLE_KEY: OpRole.Backward}) + + # update the outputs_name_to_idx after insertion of sync/allreduce ops + outputs_name_to_idx = self.__get_ouputs_name_to_idx( + first_backward_idx, block) + # the before_idx is not guaranteed sorted, therefore we have to find the + # topology to insert the coalesce ops + pos_for_coalesce = {} + for i in range(len(grad_param_segments) - 1, -1, -1): + # We separate the insertion of coalesce op and the insertion of sync/allreduce op, + # since that the coalesce op's insertion may invalidate the outputs_name_to_idx + grad_segment, param_segment = grad_param_segments[i] + before_idx = len(block.ops) + for grad in outputs_name_to_idx: + before_idx = min(before_idx, outputs_name_to_idx[grad][0]) + pos_for_coalesce[i] = before_idx + + # insert the coalesce op based on the sorted before_idx + pos_for_coalesce = sorted(pos_for_coalesce.items(), + key=lambda kv: (kv[1], kv[0]), + reverse=True) + for i, before_idx in pos_for_coalesce: + grad_segment, param_segment = grad_param_segments[i] + fused_var = fused_vars[i] + block._insert_op_without_sync(before_idx, + type="coalesce_tensor", + inputs={"Input": param_segment}, + outputs={ + "Output": grad_segment, + "FusedOutput": fused_var + }, + attrs={ + "copy_data": False, + "use_align": True, + "dtype": grad_segment[0].dtype, + OP_ROLE_KEY: OpRole.Backward + }) + + if self.calc_comm_same_stream: + block._sync_with_cpp() + return + + # insert the sync comm op + for idx, op in enumerate(block.ops): + if is_optimizer_op(op): + block._insert_op_without_sync(idx, + type='c_sync_comm_stream', + inputs={'X': fused_vars}, + outputs={'Out': fused_vars}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward + }) + break + block._sync_with_cpp() + + def __get_ouputs_name_to_idx(self, first_backward_idx, block): + # Each item of outputs_name_to_idx is a pair of idx. + # The first entry of this pair is the idx of the first op generates the grad, + # which is used to indicate the position to insert coalesce op. + # The second entry of this pair is the idx of the last op generates the grad, + # which is used to indicate the position to insert sync and allreduce op. + outputs_name_to_idx = {} + for idx in range(first_backward_idx, len(block.ops)): + op = block.ops[idx] + if is_optimizer_op(op): + break + for name in op.output_arg_names: + if name == core.kEmptyVarName(): + continue + var = block.var(name) + if not outputs_name_to_idx.get(var): + # if the grad only be generated by one op + # the first idx and the last ids are identical + outputs_name_to_idx[var] = (idx, idx) + else: + outputs_name_to_idx[var] = (outputs_name_to_idx[var][0], + idx) + return outputs_name_to_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/recompute_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/recompute_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c9054c793f491c5b11331b6efcca905a22ad14a5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/recompute_optimizer.py @@ -0,0 +1,101 @@ +# 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 + +from paddle.fluid.optimizer import RecomputeOptimizer as RO +from .meta_optimizer_base import MetaOptimizerBase + +__all__ = [] + + +class RecomputeOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(RecomputeOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.wrapped_opt = None + # we do not allow meta optimizer to be inner optimizer currently + self.meta_optimizers_white_list = [ + "LarsOptimizer", + "LambOptimizer", + "GraphExecutionOptimizer", + "DGCOptimizer", + ] + self.meta_optimizers_black_list = [] + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(RecomputeOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + + def _init_wrapped_opt(self): + if self.wrapped_opt is not None: + return + + configs = self.user_defined_strategy.recompute_configs + self.wrapped_opt = RO(self.inner_opt) + self.wrapped_opt._set_checkpoints(list(configs["checkpoints"])) + if configs["enable_offload"]: + self.wrapped_opt._enable_offload() + # TODO(JZ-LIANG) might found a way to infer the checkpoint shape automatically + checkpoint_shapes = list(configs["checkpoint_shape"]) + self.wrapped_opt.checkpoint_shape = checkpoint_shapes + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.recompute == True: + if len(self.user_defined_strategy.recompute_configs["checkpoints"] + ) == 0: + return False + else: + return True + + def _disable_strategy(self, dist_strategy): + dist_strategy.recompute = False + dist_strategy.recompute_configs = {} + + def _enable_strategy(self, dist_strategy, context): + # we do not support automatically recompute checkpoints currently + return + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + # maybe inner_opt of other meta optimizer + self._init_wrapped_opt() + return self.wrapped_opt.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_gradients(self, params_grads): + return self.wrapped_opt.apply_gradients(params_grads=params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + return self.wrapped_opt.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self._init_wrapped_opt() + optimize_ops, params_grads = \ + self.wrapped_opt.minimize(loss, startup_program, + parameter_list, no_grad_set) + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abf198b97e6e818e1fbe59006f98492640bcee54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/fp16_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/fp16_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3537a3ced2dcdce2389ad2ab8d9c15f6e8426f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/fp16_helper.py @@ -0,0 +1,239 @@ +# 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. + +from paddle.distributed.fleet.meta_optimizers.common import is_optimizer_op, OP_ROLE_KEY, OpRole +from paddle.distributed.fleet.meta_optimizers.sharding.utils import * + +from paddle.fluid import core + +__all__ = [] + + +class FP16Utils(object): + + def __init__(self): + pass + + @staticmethod + def is_fp16_cast_op(block, op, params): + if op.type != "cast": + return False + if is_optimizer_op(op): + return False + assert (len(op.desc.input_arg_names()) == 1) + assert (len(op.desc.output_arg_names()) == 1) + input_name, output_name = op.desc.input_arg_names( + )[0], op.desc.output_arg_names()[0] + if input_name not in params: + return False + input_var = block.var(input_name) + output_var = block.var(output_name) + if input_var.dtype != core.VarDesc.VarType.FP32 or \ + output_var.dtype != core.VarDesc.VarType.FP16: + return False + return True + + @staticmethod + def is_fp32_cast_op(block, op): + if op.type != "cast": + return False + if not is_optimizer_op(op): + return False + assert (len(op.desc.input_arg_names()) == 1) + assert (len(op.desc.output_arg_names()) == 1) + input_name, output_name = op.desc.input_arg_names( + )[0], op.desc.output_arg_names()[0] + input_var = block.var(input_name) + output_var = block.var(output_name) + if input_var.dtype != core.VarDesc.VarType.FP16 or \ + output_var.dtype != core.VarDesc.VarType.FP32: + return False + return True + + @staticmethod + def remove_cast_op(block, params, segment, offset): + inserted_op_num = 0 + for op_idx in reversed( + range(offset + segment._start_idx, offset + segment._end_idx)): + op = block.ops[op_idx] + if FP16Utils.is_fp16_cast_op(block, op, params): + block._remove_op(op_idx, sync=False) + inserted_op_num -= 1 + block._sync_with_cpp() + return inserted_op_num + + @staticmethod + def prune_fp16(block, shard, reduced_grads_to_param, ring_ids): + """ + 1. prune all cast_fp16_to_fp32 ops if the param not belongs to this shard + 2. revise amp inifine grad checking for sharding + """ + # remove cast + for idx, op in reversed(list(enumerate(block.ops))): + if not FP16Utils.is_fp32_cast_op(block, op): + continue + output_name = op.desc.output_arg_names()[0] + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + param_name = output_name.strip( + "@GRAD@MERGED" + ) if "@MERGED" in output_name else output_name.strip("@GRAD") + if param_name not in shard.global_params: + raise ValueError( + "Output 'X' of cast_op must be a grad of" + "model param, but {} is not a grad".format(output_name)) + if output_name in reduced_grads_to_param: + continue + if shard.has_param(param_name): + continue + block._remove_op(idx, sync=False) + block._remove_var(output_name, sync=False) + + block._sync_with_cpp() + update_loss_scaling_op_idx = -1 + inf_var_name = '' + for idx, op in reversed(list(enumerate(block.ops))): + if op.type == "update_loss_scaling": + update_loss_scaling_op_idx = idx + inf_var_name = op.desc.input('FoundInfinite')[0] + if op.type in ["check_finite_and_unscale", "update_loss_scaling"]: + reversed_x = [] + reversed_x_paramname = [] + for input_name in op.desc.input('X'): + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + if "@MERGED" in input_name: + param_name = input_name.strip("@GRAD@MERGED") + else: + param_name = input_name.strip("@GRAD") + if param_name not in shard.global_params: + raise ValueError( + "Input 'X' of check_finite_and_unscale must" + "be grads, but {} is not a grad".format(input_name)) + if shard.has_param(param_name): + reversed_x.append(input_name) + reversed_x_paramname.append(param_name) + op.desc.set_input('X', reversed_x) + op.desc.set_output('Out', reversed_x) + + # the grad checking should take the all and only param in the current shard + to_check_param = set(reversed_x_paramname) + should_check_param = set(shard.global_params).intersection( + set([param for param, worker_idx in shard.global_param2device.items() \ + if worker_idx == shard.worker_idx])) + assert to_check_param == should_check_param, "amp \ + check_finite_and_unscale checking miss [{}] and got unexpected [{}]".format( + should_check_param - to_check_param, + to_check_param - should_check_param) + + if update_loss_scaling_op_idx == -1: + return + inf_var = block.var(inf_var_name) + inf_var_int32 = block.create_var(name=inf_var_name + "@cast_int32", + shape=inf_var.shape, + dtype=core.VarDesc.VarType.INT32) + + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='cast', + inputs={'X': inf_var}, + outputs={'Out': inf_var_int32}, + attrs={ + "in_dtype": inf_var.dtype, + "out_dtype": inf_var_int32.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + + # allreduce(mp)->allreduce(sharding)->allreduce(pp) + for ring_id in ring_ids: + if ring_id == -1: continue + # this allreduce communication should not overlap with calc + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='c_allreduce_max', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var_int32}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='cast', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var}, + attrs={ + "in_dtype": inf_var_int32.dtype, + "out_dtype": inf_var.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + block._sync_with_cpp() + + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + @staticmethod + def sync_amp_check_nan_inf(block, ring_ids): + update_loss_scaling_op_idx = -1 + + for idx, op in reversed(list(enumerate(block.ops))): + if op.type == "update_loss_scaling": + update_loss_scaling_op_idx = idx + inf_var_name = op.desc.input('FoundInfinite')[0] + break + + # not use amp + if update_loss_scaling_op_idx == -1: + return + # 0. inf_var_int32 = cast(inf_var) + # 1. inf_var_int32 = allreduce_max(inf_var_int32) + # 3. inf_var = cast(inf_var_int32) + inf_var = block.var(inf_var_name) + inf_var_int32 = block.create_var(name=inf_var_name + "@cast_int32", + shape=inf_var.shape, + dtype=core.VarDesc.VarType.INT32) + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='cast', + inputs={'X': inf_var}, + outputs={'Out': inf_var_int32}, + attrs={ + "in_dtype": inf_var.dtype, + "out_dtype": inf_var_int32.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + + # allreduce(mp)->allreduce(pp) + for ring_id in ring_ids: + if ring_id == -1: continue + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='c_allreduce_max', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var_int32}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + + block._insert_op_without_sync(update_loss_scaling_op_idx, + type='cast', + inputs={'X': inf_var_int32}, + outputs={'Out': inf_var}, + attrs={ + "in_dtype": inf_var_int32.dtype, + "out_dtype": inf_var.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + update_loss_scaling_op_idx += 1 + block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/gradient_clip_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/gradient_clip_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..03d955842f5fc5e38b49e4aa7639cdb9c49954b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/gradient_clip_helper.py @@ -0,0 +1,248 @@ +# 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. + +from paddle.distributed.fleet.meta_optimizers.common import OP_ROLE_KEY, OpRole + +__all__ = [] + + +class GradientClipHelper(object): + + def __init__(self, mp_ring_id): + self.mp_ring_id = mp_ring_id + + def _is_gradient_clip_op(self, op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/gradient_clip") + + def prune_gradient_clip(self, block, shard, ring_ids): + """ + prune gradient_clip related ops for params that not belong to cur shard + prune: square, reduce_sum, elementwise_mul + keep: sum, sqrt, elementwise_max, elementwise_div + """ + deperated_vars = set() + deperate_op_idx = set() + reversed_x_paramname = [] + global_norm_sum_op_idx = -1 + for idx, op in enumerate(block.ops): + if not self._is_gradient_clip_op(op): + continue + if op.type == "sum": + global_norm_sum_op_idx = idx + continue + deperate_op = False + for input_name in op.desc.input_arg_names(): + if input_name in deperated_vars: + deperate_op = True + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + if "@MERGED" in input_name: + param_name = input_name.strip("@GRAD@MERGED") + else: + param_name = input_name.strip("@GRAD") + if shard.is_param(param_name) and \ + not shard.has_param(param_name): + deperate_op = True + elif shard.is_param(param_name): + reversed_x_paramname.append(param_name) + + if deperate_op: + deperate_op_idx.add(idx) + for output_name in op.desc.output_arg_names(): + if output_name not in op.desc.input_arg_names(): + deperated_vars.add(output_name) + + # NOTE(wangxi): If only have 2 sharding, and 1 param. + # sharding 0 will not deperated_vars, will return, only + # sharding 1 will insert allreduce, then hang. + if not deperated_vars and global_norm_sum_op_idx == -1: + # got no gradient_clip op + return + + for idx, op in reversed(list(enumerate(block.ops))): + if not self._is_gradient_clip_op(op): + continue + if idx in deperate_op_idx: + block._remove_op(idx, sync=False) + continue + if op.type == "sum": + reversed_inputs = [] + global_norm_sum_op_idx = idx + for input_name in op.desc.input_arg_names(): + if input_name not in deperated_vars: + reversed_inputs.append(input_name) + + op.desc.set_input("X", reversed_inputs) + assert (len(op.desc.output_arg_names()) == 1) + sum_res = op.desc.output_arg_names()[0] + + # NOTE(wangxi): If we have 2 param, but sharding is 4, + # then the sum op in some cards will not have input. + # So we use fill_constant_op to set `sum_var` to zero, + # which does not affect correctness. + if len(reversed_inputs) == 0: + sum_var = block.var(sum_res) + namescope = op.attr("op_namescope") + + block._remove_op(idx, sync=False) + op = block._insert_op_without_sync(idx, + type='fill_constant', + inputs={}, + outputs={'Out': sum_res}, + attrs={ + 'shape': + sum_var.shape, + 'dtype': + sum_var.dtype, + 'value': + 0.0, + OP_ROLE_KEY: + OpRole.Optimize + }) + op._set_attr('op_namescope', namescope) + + # allreduce(mp)->allreduce(sharding)->allreduce(pp) + idx_offset = 1 + for ring_id in ring_ids: + if ring_id == -1: continue + # this allreduce should not overlap with calc and should be scheduled in calc stream + block._insert_op_without_sync( + idx + idx_offset, + type='c_allreduce_sum', + inputs={'X': sum_res}, + outputs={'Out': sum_res}, + attrs={ + 'ring_id': ring_id, + 'op_namescope': "/gradient_clip_model_parallelism", + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize, + }) + idx_offset += 1 + + # the grad sum here should take the all and only param in the current shard + to_check_param = set(reversed_x_paramname) + should_check_param = set(shard.global_params).intersection(set( + [param for param, worker_idx in shard.global_param2device.items() \ + if worker_idx == shard.worker_idx])) + assert to_check_param == should_check_param, "amp check_finite_and_unscale \ + checking miss [{}] and got unexpected [{}]".format( + should_check_param - to_check_param, + to_check_param - should_check_param) + + for var_name in deperated_vars: + block._remove_var(var_name, sync=False) + block._sync_with_cpp() + return + + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + def sync_global_norm(self, block, ring_ids, mp_rank): + """ + prune gradient_clip related ops for params that not belong to cur shard + prune: square, reduce_sum, elementwise_mul + keep: sum, sqrt, elementwise_max, elementwise_div + """ + is_clip_grad_by_global_norm = False + for idx, op in list(enumerate(block.ops)): + if not self._is_gradient_clip_op(op): + continue + if op.type == 'sum': + is_clip_grad_by_global_norm = True + break + if not is_clip_grad_by_global_norm: + # TODO(Yuang Liu): need some extra handles when clip_grad_norm for mp + return + + removed_op_idx = set() + removed_tmp_var = set() + for idx, op in list(enumerate(block.ops)): + if not self._is_gradient_clip_op(op): + continue + if op.type == 'sum': + break + for input_name in op.input_arg_names: + input_var = block.var(input_name) + # NOTE: when mp_degree > 1, some vars will be split into each mp rank. + # However, there still some vars such as Scale, Bias are not split. + # Those not be split vars should only be counted once during grad clip + # by global norm. Those vars either doesn't have is_distributed attr + # or the is_distributed attr has been set as False. + # Therefore, we prune those duplicated vars for grad clip. + if mp_rank >= 1 and (not (hasattr(input_var, 'is_distributed') + and input_var.is_distributed)): + removed_op_idx.add(idx) + for output_name in op.output_arg_names: + removed_tmp_var.add(output_name) + + for idx, op in reversed(list(enumerate(block.ops))): + if not self._is_gradient_clip_op(op): + continue + if idx in removed_op_idx: + block._remove_op(idx, sync=False) + + for var_name in removed_tmp_var: + block._remove_var(var_name, sync=False) + + for idx, op in list(enumerate(block.ops)): + if not self._is_gradient_clip_op(op): + continue + if op.type == 'sum': + # If mp_rank == 0, no extra handles, just allreduce + # If mp_rank >= 1, some extra handles is needed + sum_rst_var = block.var(op.output_arg_names[0]) + if mp_rank >= 1: + reserved_vars = [] + for input_name in op.input_arg_names: + if input_name not in removed_tmp_var: + reserved_vars.append(input_name) + + if len(reserved_vars) > 0: + op.desc.set_input("X", reserved_vars) + else: + # If all input of sum op should be removed, then remove the sum op. + # And set the output's value of sum to 0. + namescope = op.attr("op_namescope") + block._remove_op(idx, sync=False) + fill_constant_op = block._insert_op_without_sync( + idx, + type='fill_constant', + inputs={}, + outputs={'Out': sum_rst_var}, + attrs={ + 'shape': sum_rst_var.shape, + 'dtype': sum_rst_var.dtype, + 'value': 0.0, + OP_ROLE_KEY: OpRole.Optimize + }) + fill_constant_op._set_attr('op_namescope', namescope) + self._insert_allreduce(block, ring_ids, idx, sum_rst_var) + break + + @staticmethod + def _insert_allreduce(block, ring_ids, idx, var): + for ring_id in ring_ids: + if ring_id == -1: + continue + + idx = idx + 1 + block._insert_op_without_sync( + idx, + type='c_allreduce_sum', + inputs={'X': var}, + outputs={'Out': var}, + attrs={ + 'ring_id': ring_id, + 'op_namescope': "/gradient_clip_model_parallelism", + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize, + }) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/offload_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/offload_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..9479dc5fceee24f53e2e46f017754d1f5f50b335 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/offload_helper.py @@ -0,0 +1,537 @@ +# 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. + +import copy +from ..common import is_optimizer_op, OP_ROLE_KEY, OpRole, is_update_op +from paddle.fluid import core, unique_name +from .shard import Shard + +__all__ = [] + + +class PlaceType: + # sync with memcpy op, maybe not a good design + CPU = 0 + CUDA = 1 + CUDA_PINNED = 2 + XPU = 3 # unsupport for now + NPU = 4 + NPU_PINNED = 5 + + @staticmethod + def default_device(): + if core.is_compiled_with_cuda(): + return PlaceType.CUDA + elif core.is_compiled_with_npu(): + return PlaceType.NPU + return PlaceType.CPU + + @staticmethod + def default_pinned(): + if core.is_compiled_with_cuda(): + return PlaceType.CUDA_PINNED + elif core.is_compiled_with_npu(): + return PlaceType.NPU_PINNED + return PlaceType.CPU + + +class OffloadHelper(object): + cpu_place_type = 0 + cuda_place_type = PlaceType.default_device() + cuda_pinned_place_type = PlaceType.default_pinned() + + def __init__(self, mp_ring_id=None, dp_ring_id=None): + self.mp_ring_id = mp_ring_id + self.dp_ring_id = dp_ring_id + + def _insert_cast_op(self, block, idx, src_name, dst_name): + src_var = block.var(src_name) + if not block.has_var(dst_name): + block.create_var(name=dst_name, + shape=src_var.shape, + dtype=core.VarDesc.VarType.FP16, + persistable=True) + dst_var = block.var(dst_name) + assert dst_var.dtype == core.VarDesc.VarType.FP16 + block._insert_op_without_sync(idx, + type='cast', + inputs={'X': src_var}, + outputs={'Out': dst_var}, + attrs={ + 'in_dtype': src_var.dtype, + 'out_dtype': dst_var.dtype, + OP_ROLE_KEY: OpRole.Optimize + }) + + def _insert_broadcast_op(self, block, idx, param_name): + rings = [] + + if self.dp_ring_id is not None: + rings.append(self.dp_ring_id) + + # need sync non distributed param in mp group + if self.mp_ring_id is not None: + param = block.var(param_name) + if not hasattr(param, 'is_distributed') or not param.is_distributed: + rings.append(self.mp_ring_id) + + # the insert op order is: mp, dp + for ring in rings: + block._insert_op_without_sync(idx, + type="c_broadcast", + inputs={'X': param_name}, + outputs={'Out': param_name}, + attrs={ + 'ring_id': ring, + 'root': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward, + }) + + def _insert_memcpy_op(self, block, idx, src_name, dst_name, dst_place_type): + src_var = block.var(src_name) + dst_var = block.var(dst_name) + block._insert_op_without_sync(idx, + type='memcpy', + inputs={'X': src_var}, + outputs={'Out': dst_var}, + attrs={ + 'dst_place_type': dst_place_type, + OP_ROLE_KEY: OpRole.Optimize, + }) + + def _insert_fetch_op(self, block, idx, src_name, dst_name): + self._insert_memcpy_op(block, idx, src_name, dst_name, + OffloadHelper.cuda_place_type) + + def _insert_offload_op(self, block, idx, src_name, dst_name): + self._insert_memcpy_op(block, idx, src_name, dst_name, + OffloadHelper.cuda_pinned_place_type) + + def _get_offload_var_name(self, name): + return unique_name.generate(name + '@offload') + + def _create_offload_var(self, var_name, offload_var_name, blocks): + for block in blocks: + var = block.var(var_name) + var.persistable = False + offload_var = block.create_var(name=offload_var_name, + shape=var.shape, + dtype=var.dtype, + persistable=True) + + def offload_fp32param(self, block, startup_block, offload=True): + """ + (p_fp16) = cast(p) + (p_fp16_recompute) = cast(p) + (pout,) = adam(p) + ===========================> + rename(p_fp16_recompute, p_fp16) + + (p,) = prefetch(p@offload) + (pout,) = adam(p) + (p_fp16) = cast(p) + (p@offload) = memcpy(p) + """ + param_to_idx = dict() + param_to_fp16 = dict() + # recompute_var which need rename to fp16_param + fp16_param_to_recompute = dict() + recompute_to_fp16 = dict() + + def remove_param(input_name): + param_to_idx.pop(input_name) + if input_name in param_to_fp16: + fp16_param = param_to_fp16.pop(input_name) + if fp16_param in fp16_param_to_recompute: + recompute = fp16_param_to_recompute.pop(fp16_param) + recompute_to_fp16.pop(recompute) + + # step1: record param + for idx, op in reversed(list(enumerate(block.ops))): + if is_update_op(op): + param = op.desc.input("Param")[0] + param_to_idx[param] = idx + + # step2: remove param which can't offload and + # record param->fp16param, fp16param->recompute_var + for idx, op in enumerate(block.ops): + if is_optimizer_op(op): + break + # TODO (Yuang Liu): tmp solution for fuse_grad_merge + optimize_cast + if not offload and op.type == 'coalesce_tensor': + continue + for input_name in op.desc.input_arg_names(): + if input_name not in param_to_idx: + continue + + # param which will be used by fp32 op + if op.type != 'cast': + remove_param(input_name) + continue + + # param is only used by cast op, + # which to cast fp32_param to fp16_param + output_name = op.output_arg_names[0] + if 'cast_fp16' not in output_name: + remove_param(input_name) + continue + + if 'subprog' not in output_name: + assert output_name == input_name + '.cast_fp16' + assert input_name not in param_to_fp16, \ + "There must be only one cast op from fp32 param to fp16 param." + param_to_fp16[input_name] = output_name + else: + # fp16-->recompute_var + assert input_name in param_to_fp16, \ + "param must first be cast to fp16" + fp16_param = param_to_fp16[input_name] + fp16_param_to_recompute[fp16_param] = output_name + recompute_to_fp16[output_name] = fp16_param + + param_name_to_offload_name = dict() + # step3: main_block add offload, cast op + # change recompute to fp16, remove cast(param) to fp16 + for idx, op in reversed(list(enumerate(block.ops))): + if is_update_op(op): + param = op.desc.input("Param")[0] + if param not in param_to_idx: continue + # step3.1: create offload_var + offload_var_name = self._get_offload_var_name(param) + param_name_to_offload_name[param] = offload_var_name + if offload: + self._create_offload_var(param, offload_var_name, + [block, startup_block]) + + # step3.2: insert cast op and offload op + self._insert_offload_op(block, idx + 1, param, + offload_var_name) + + assert param in param_to_fp16 + fp16_param_name = param_to_fp16[param] + fp16_param_var = block.var(fp16_param_name) + fp16_param_var.persistable = True + self._insert_cast_op(block, idx + 1, param, + param_to_fp16[param]) + + if offload: + # step3.3: insert fetch op + self._insert_fetch_op(block, idx, offload_var_name, param) + continue + + # step3.4: remove cast op + if op.type == 'cast': + input_name = op.desc.input_arg_names()[0] + if input_name in param_to_idx: + block._remove_op(idx, sync=False) + continue + + # step3.5: change recompute_param to fp16_param + for input_name in op.desc.input_arg_names(): + if input_name in recompute_to_fp16: + op._rename_input(input_name, recompute_to_fp16[input_name]) + for output_name in op.desc.output_arg_names(): + if output_name in recompute_to_fp16: + op._rename_output(output_name, + recompute_to_fp16[output_name]) + + # step4: remove recompute_param + for name in recompute_to_fp16.keys(): + block._remove_var(name, sync=False) + + # step5: startup_block add offload + visited_vars = set() + # FIXME(wangxi): should insert in idx, need move comm init to the head. + insert_idx = len(startup_block.ops) + for idx, op in reversed(list(enumerate(startup_block.ops))): + for out_name in op.output_arg_names: + if out_name in visited_vars: + continue + + if out_name in param_name_to_offload_name: + var_name = out_name + if offload: + offload_var_name = param_name_to_offload_name[var_name] + self._insert_offload_op(startup_block, insert_idx, + var_name, offload_var_name) + self._insert_cast_op(startup_block, insert_idx, var_name, + param_to_fp16[var_name]) + # NOTE(wangxi): cast and offload should insert after broadcast param. + # the insert op order is: {mp, dp}broadcast, cast, offload + self._insert_broadcast_op(startup_block, insert_idx, + var_name) + + visited_vars.add(out_name) + + block._sync_with_cpp() + startup_block._sync_with_cpp() + + def cast_fp32param_in_optimize(self, block, startup_block): + """ + (p_fp16) = cast(p) + (p_fp16_recompute) = cast(p) + (pout,) = adam(p) + ===========================> + rename(p_fp16_recompute, p_fp16) + + (pout,) = adam(p) + (p_fp16) = cast(p) + """ + self.offload_fp32param(block, startup_block, offload=False) + + def offload(self, block, startup_block): + """ + (m1, m2) = prefetch(m1@offload, m2@offload) + (m1out, m2out, pout) = adam(m1, m2, p) + (m1@offload, m2@offload) = memcpy(m1, m2) + """ + vars_name_to_offload_name = dict() + + # main_block add offload + for idx, op in reversed(list(enumerate(block.ops))): + if not is_optimizer_op(op): + break + + vars_name = [] + if op.type == "adam" or op.type == "adamw": + # {Moment1Out = [''], Moment2Out = [''], ParamOut = ['']} = + # adam(inputs={Moment1 = [''], Moment2 = [''], Param = ['']}) + vars_name.append(op.desc.input("Moment1")[0]) + vars_name.append(op.desc.input("Moment2")[0]) + elif op.type == 'momentum': + pass + elif op.type == 'lars': + pass + elif op.type == 'lamb': + pass + + # step1: create and init offload_var + for var_name in vars_name: + assert var_name not in vars_name_to_offload_name + + offload_var_name = self._get_offload_var_name(var_name) + vars_name_to_offload_name[var_name] = offload_var_name + + self._create_offload_var(var_name, offload_var_name, + [block, startup_block]) + + # step2: insert offload op + for var_name in vars_name: + offload_var_name = vars_name_to_offload_name[var_name] + self._insert_offload_op(block, idx + 1, var_name, + offload_var_name) + + # step3: insert fetch op + for var_name in vars_name: + offload_var_name = vars_name_to_offload_name[var_name] + self._insert_fetch_op(block, idx, offload_var_name, var_name) + + # startup_block add offload + visited_vars = set() + for idx, op in reversed(list(enumerate(startup_block.ops))): + for out_name in op.output_arg_names: + if out_name in visited_vars: + continue + + if out_name in vars_name_to_offload_name: + var_name = out_name + offload_var_name = vars_name_to_offload_name[var_name] + # insert offload op after var is generated + self._insert_offload_op(startup_block, idx + 1, var_name, + offload_var_name) + visited_vars.add(out_name) + + block._sync_with_cpp() + startup_block._sync_with_cpp() + + def opt_sharding_cast_fp32param(self, + block, + startup_block, + params, + offload=False): + """ + (p_fp16) = cast(p) + (p_fp16_recompute) = cast(p) + (pout,) = adam(p) + ===========================> + rename(p_fp16_recompute, p_fp16) + + (pout,) = adam(p) + (p_fp16) = cast(p) + broadcast(p_fp16) + """ + global_params = set() + local_params = set() + param_to_fp16 = dict() + # recompute_var which need rename to fp16_param + fp16_param_to_recompute = dict() + recompute_to_fp16 = dict() + + def remove_param(input_name): + global_params.remove(input_name) + if input_name in local_params: + local_params.remove(input_name) + if input_name in param_to_fp16: + fp16_param = param_to_fp16.pop(input_name) + if fp16_param in fp16_param_to_recompute: + recompute = fp16_param_to_recompute.pop(fp16_param) + recompute_to_fp16.pop(recompute) + + # step1: record param + global_params = set(params) + for idx, op in reversed(list(enumerate(block.ops))): + if is_update_op(op): + param = op.desc.input("Param")[0] + local_params.add(param) + + # step2: remove param which can't offload and + # record param->fp16param, fp16param->recompute_var + for idx, op in enumerate(block.ops): + if is_optimizer_op(op): + break + # TODO (Yuang Liu): tmp solution for fuse_grad_merge + optimize_cast + if op.type == 'coalesce_tensor': + continue + for input_name in op.desc.input_arg_names(): + if input_name not in global_params: + continue + + # param which will be used by fp32 op + if op.type != 'cast': + remove_param(input_name) + continue + + # param is only used by cast op, + # which to cast fp32_param to fp16_param + output_name = op.output_arg_names[0] + if 'cast_fp16' not in output_name: + remove_param(input_name) + continue + + if 'subprog' not in output_name: + assert output_name == input_name + '.cast_fp16' + assert input_name not in param_to_fp16, \ + "There must be only one cast op from fp32 param to fp16 param." + param_to_fp16[input_name] = output_name + else: + # fp16-->recompute_var + assert input_name in param_to_fp16, \ + "param must first be cast to fp16" + fp16_param = param_to_fp16[input_name] + fp16_param_to_recompute[fp16_param] = output_name + recompute_to_fp16[output_name] = fp16_param + + param_name_to_offload_name = dict() + # step3: main_block add offload, cast op + # change recompute to fp16, remove cast(param) to fp16 + for idx, op in reversed(list(enumerate(block.ops))): + if is_update_op(op): + param = op.desc.input("Param")[0] + if param not in global_params: + continue + # step3.1: create offload_var + offload_var_name = self._get_offload_var_name(param) + param_name_to_offload_name[param] = offload_var_name + if offload: + self._create_offload_var(param, offload_var_name, + [block, startup_block]) + + # step3.2: insert cast op and offload op + self._insert_offload_op(block, idx + 1, param, + offload_var_name) + + assert param in param_to_fp16 + fp16_param_name = param_to_fp16[param] + fp16_param_var = block.var(fp16_param_name) + fp16_param_var.persistable = True + self._insert_cast_op(block, idx + 1, param, + param_to_fp16[param]) + + if offload: + # step3.3: insert fetch op + self._insert_fetch_op(block, idx, offload_var_name, param) + + continue + + # step3.4: remove cast op + if op.type == 'cast': + input_name = op.desc.input_arg_names()[0] + if input_name in global_params: + block._remove_op(idx, sync=False) + continue + + # step3.5: change recompute_param to fp16_param + for input_name in op.desc.input_arg_names(): + if input_name in recompute_to_fp16: + op._rename_input(input_name, recompute_to_fp16[input_name]) + for output_name in op.desc.output_arg_names(): + if output_name in recompute_to_fp16: + op._rename_output(output_name, + recompute_to_fp16[output_name]) + + # step4: remove recompute_param + for name in recompute_to_fp16.keys(): + block._remove_var(name, sync=False) + + # step5: remove fp32 param which not need + for idx, op in enumerate(block.ops): + if op.type not in ['coalesce_tensor', 'c_broadcast']: + continue + for input_name in op.desc.input_arg_names(): + if input_name in param_to_fp16: + op._rename_input(input_name, param_to_fp16[input_name]) + for output_name in op.desc.output_arg_names(): + if output_name in param_to_fp16: + op._rename_output(output_name, param_to_fp16[output_name]) + + for param in global_params: + assert param in param_to_fp16 + fp16_param_name = param_to_fp16[param] + fp16_param_var = block.var(fp16_param_name) + fp16_param_var.persistable = True + + if param not in local_params: + block._remove_var(param, sync=False) + + # step6: startup_block add offload + visited_vars = set() + insert_idx = len(startup_block.ops) + for idx, op in reversed(list(enumerate(startup_block.ops))): + for out_name in op.output_arg_names: + if out_name in visited_vars: continue + + if out_name in param_to_fp16: + var_name = out_name + if offload: + self._insert_offload_op( + startup_block, idx + 1, var_name, + param_name_to_offload_name[var_name]) + + self._insert_cast_op(startup_block, insert_idx, var_name, + param_to_fp16[var_name]) + + # NOTE(wangxi): cast and offload should insert after broadcast param. + # the insert op order is: {mp, dp}broadcast, cast, offload + self._insert_broadcast_op(startup_block, insert_idx, + var_name) + + if var_name not in local_params: + param = startup_block.var(out_name) + param.persistable = False + + visited_vars.add(out_name) + + block._sync_with_cpp() + startup_block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/prune.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/prune.py new file mode 100644 index 0000000000000000000000000000000000000000..adbc00f25deb68b43dcc64558d72fef4019bccbb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/prune.py @@ -0,0 +1,146 @@ +# 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. + +__all__ = [] + + +class ProgramDeps(object): + + def __init__(self, block, start_vars, end_vars): + self._block = block + # vars where to start to build the deps + self._start_vars = start_vars + # vars where to stop to build the deps + self._end_vars = end_vars + # var name -> op idxs which depends on this var + self._var_to_use_op = {} + # sub block deps which is a subset of this topo + self._sub_block_deps = {} + # var name -> op idxs which generate var + self._var_to_generate_op = {} + self._should_removed_var = set() + self._father_block_deps = None + self._build_deps() + + def get_sub_block_deps(self, idx): + if idx in self._sub_block_deps: + return self._sub_block_deps[idx] + else: + return None + + def get_var_deps(self, var_name): + if var_name in self._var_to_use_op: + return self._var_to_use_op[var_name] + else: + return None + + def _build_deps(self, ): + + for var_name in self._start_vars: + self._var_to_use_op[var_name] = [] + self._var_to_generate_op[var_name] = [] + + for idx, op in enumerate(self._block.ops): + if op.type in [ + "c_allreduce_sum", "c_sync_comm_stream", + "c_calc_comm_stream" + ]: + continue + input_vars = op.desc.input_arg_names() + output_vars = op.desc.output_arg_names() + deps_reduce = False + for input_name in input_vars: + if input_name in self._var_to_use_op: + deps_reduce = True + if not deps_reduce: + continue + for input_name in input_vars: + if input_name in self._var_to_use_op: + self._var_to_use_op[input_name].append(idx) + for output_name in output_vars: + if output_name not in self._var_to_use_op: + self._var_to_use_op[output_name] = [] + if output_name not in self._var_to_generate_op: + self._var_to_generate_op[output_name] = [idx] + else: + self._var_to_generate_op[output_name].append(idx) + if op.type == "conditional_block": + # subblock + assert (op.desc.has_attr("sub_block")) + subblock_idx = op.desc.attr("sub_block").id + subblock_deps = ProgramDeps( + self._block.program.block(subblock_idx), + op.desc.input_arg_names(), op.desc.output_arg_names()) + self._sub_block_deps[subblock_idx] = subblock_deps + subblock_deps._father_block_deps = self + + def crop_input_var_from_op(self, op_idx, var_name): + if var_name in self._var_to_use_op: + # update var -> dep_var_op + if self._var_to_use_op[var_name] != []: + if op_idx not in self._var_to_use_op[var_name]: + raise ValueError( + "op_idx: {} is not in self._var_to_use_op[{}], " + "self._var_to_use_op[{}] is {}".format( + op_idx, var_name, var_name, + self._var_to_use_op[var_name])) + self._var_to_use_op[var_name].remove(op_idx) + # update _should_removed_var + if var_name in self._start_vars: + self._should_removed_var.discard(var_name) + elif self._var_to_use_op[ + var_name] == []: # no more deps of this var + self._should_removed_var.add(var_name) + elif self._var_to_generate_op[var_name][-1] >= self._var_to_use_op[ + var_name][-1]: + # there are circle in the graph + self._should_removed_var.add(var_name) + else: # input_name should not be deleted + self._should_removed_var.discard(var_name) + + def crop_output_var_from_op(self, op_idx, var_name): + if var_name in self._var_to_generate_op: + assert (op_idx in self._var_to_generate_op[var_name]) + self._var_to_generate_op[var_name].remove(op_idx) + if self._block.has_var(var_name): + if var_name not in self._var_to_generate_op or self._var_to_generate_op[ + var_name] == []: + self._block._remove_var(var_name, sync=False) + + def remove_op(self, op_idx, reserved_vars=None): + # update deps + op = self._block.ops[op_idx] + for input_name in op.desc.input_arg_names(): + if reserved_vars is not None and input_name in reserved_vars: + continue + self.crop_input_var_from_op(op_idx, input_name) + for output_name in op.desc.output_arg_names(): + if reserved_vars is not None and output_name in reserved_vars: + continue + self.crop_output_var_from_op(op_idx, output_name) + self._block._remove_op(op_idx, sync=False) + + def should_remove_op(self, op_idx): + op = self._block.ops[op_idx] + + # NOTE: At present, it is found that the OP without output is + # only send_v2 and partial_send op, which will be used in + # all device + if len(op.desc.output_arg_names()) == 0: + return False + + for output_name in op.desc.output_arg_names(): + if output_name not in self._should_removed_var: + return False + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/shard.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/shard.py new file mode 100644 index 0000000000000000000000000000000000000000..7002dfa2be51487caeaea52767ca17a588341891 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/shard.py @@ -0,0 +1,158 @@ +# 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. + +from paddle.distributed.fleet.meta_optimizers.common import is_optimizer_op +from paddle.distributed.fleet.meta_optimizers.sharding.utils import * +from paddle.distributed.fleet.meta_optimizers.sharding.fp16_helper import FP16Utils + +__all__ = [] + + +class Shard(object): + + def __init__(self, ): + self.global_params = set([]) + self.worker_idx = -1 + self.worker_num = -1 + self.global_param2device = dict() + self.device2global_params = dict() + + def setup(self, params_grads, worker_idx, worker_num): + # param names of all devices + self.global_params = set([x[0].name for x in params_grads]) + # _param(str) -> device_id(int) + self.worker_idx = worker_idx + self.worker_num = worker_num + # global_param2device contains fp32 params and fp16 params + # device2global_params only contains fp32 params + self.global_param2device, self.device2global_params \ + = self._split_params(params_grads, worker_idx, worker_num) + + def has_param(self, var_name): + return var_name in self.global_param2device and \ + self._var_device_id(var_name) == self.worker_idx + + def has_opt_var(self, var_name): + return self._var_device_id(var_name) == self.worker_idx + + def has_var(self, var_name): + return self._var_device_id(var_name) == -1 or \ + self._var_device_id(var_name) == self.worker_idx + + def _split_params(self, params_grads, worker_idx, worker_num): + param2device = {} + total_param_mem = 0.0 + param2mem = [] + for param in [x[0] for x in params_grads]: + mem = get_var_size(param) + total_param_mem += mem + param2mem.append((param.name, mem)) + device2params = {x: [] for x in range(worker_num)} + device_idx = 0 + mem_accu = 0.0 + for param_name, mem in param2mem: + if mem_accu > total_param_mem * 1.0 * (device_idx + 1) / worker_num: + device_idx += 1 + device2params[device_idx].append(param_name) + param2device[param_name] = device_idx + mem_accu += mem + return param2device, device2params + + def _var_device_id(self, var_name): + if var_name in self.global_param2device: + return self.global_param2device[var_name] + for suffix in [ + "_moment1_0", "_moment2_0", "_beta1_pow_acc_0", + "_beta2_pow_acc_0", "_velocity_0" + ]: + base_name = re.sub(suffix, '', var_name) + if base_name in self.global_param2device: + return self.global_param2device[base_name] + return -1 + + def find_broadcast_params(self, block): + broadcast_vars = set([]) + fp16_params = set([]) + fp16_to_fp32 = {} + + param_usage = {x: 0 for x in self.global_params} + for op in block.ops: + if is_optimizer_op(op): + continue + for input_name in op.desc.input_arg_names(): + if input_name in self.global_params: + param_usage[input_name] += 1 + + for op in block.ops: + if not FP16Utils.is_fp16_cast_op(block, op, self.global_params): + continue + input_name = op.input_arg_names[0] + output_name = op.output_arg_names[0] + broadcast_vars.add(output_name) + fp16_params.add(output_name) + fp16_to_fp32[output_name] = input_name + param_usage[input_name] -= 1 + self.global_param2device[output_name] = self.global_param2device[ + input_name] + + for param, usage in param_usage.items(): + if usage > 0: + broadcast_vars.add(param) + return broadcast_vars + + def device(self, var_name): + return self._var_device_id(var_name) + + def is_param(self, var_name): + return var_name in self.global_params + + def is_opti_var(self, var_name): + if var_name in self.global_params: + return True + for suffix in [ + "_moment1_0", "_moment2_0", "_beta1_pow_acc_0", + "_beta2_pow_acc_0", "_velocity_0" + ]: + base_name = re.sub(suffix, '', var_name) + if base_name in self.global_params: + return True + return False + + def filter_grads(self, grads): + grads_in_shard = [] + for grad in grads: + param = grad.split("@")[0] + if self.has_param(param): + grads_in_shard.append(grad) + return grads_in_shard + + +class ProgramSegment(object): + + def __init__(self, block): + self._block = block + self._allreduce_vars = [] + # sub program start idx + self._start_idx = -1 + # sub program end idx + self._end_idx = -1 + # param name to broadcast name + self._param2broadcast = {} + self._broadcast_vars = [] + # cast op pairs, fp16 name (str) -> fp32 name (str) + self._cast_ops = {} + # fill constant vars + self._fill_constant_vars = [] + # parameter mems + self._param_mem = 0.0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..39f71be0cde764fee56536f437043ef39570dea8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/utils.py @@ -0,0 +1,965 @@ +# 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. +import paddle +from paddle.fluid import core, unique_name +from functools import reduce +from paddle.distributed.fleet.meta_optimizers.common import is_loss_grad_op, is_backward_op, is_optimizer_op +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY + +import re +import os + + +def check_broadcast(block): + """ + if a var is broadcasted, it should have a sync_comm before + this var is used, if not, raise error. + if the broadcasted var has a fill_constant op, the fill_constant + op should stay forward before the broadcast op, and before a + sync_calc op. Otherwise, raise error. + + should ignore and skip broadcast_op of inner_parallelism (e.g. Megatron) + """ + broadcast_vars = {} + for idx, op in enumerate(block.ops): + if op.type == "c_broadcast": + if op.all_attrs()["use_calc_stream"] == False: + var_name = op.desc.input_arg_names()[0] + if "@BroadCast" in var_name: + if var_name in broadcast_vars: + raise ValueError( + "var_name areadly exist: {}" + "the old pos is {}, the new pos is {}".format( + var_name, + broadcast_vars[var_name]["broadcast_pos"], idx)) + broadcast_vars[var_name] = { + "fill_constant_pos": -1, + "broadcast_pos": idx, + } + + for idx, op in enumerate(block.ops): + if op.type == "fill_constant": + var_name = op.desc.output_arg_names()[0] + if var_name in broadcast_vars: + broadcast_vars[var_name]["fill_constant_pos"] = idx + continue + + last_sync_comm_op_idx = -1 + last_sync_calc_op_idx = -1 + for idx, op in enumerate(block.ops): + if op.type == "c_sync_comm_stream": + last_sync_comm_op_idx = idx + continue + if op.type == "c_sync_calc_stream": + last_sync_calc_op_idx = idx + continue + if op.type == "c_broadcast": + if op.all_attrs()["use_calc_stream"] == False: + var_name = op.desc.input_arg_names()[0] + if "@BroadCast" in var_name: + if broadcast_vars[var_name]["fill_constant_pos"] != -1: + assert (last_sync_calc_op_idx != -1) + assert (broadcast_vars[var_name]["fill_constant_pos"] < + last_sync_calc_op_idx) + assert (last_sync_calc_op_idx < idx) + continue + for input_name in op.desc.input_arg_names(): + if input_name in broadcast_vars: + assert (broadcast_vars[input_name]["broadcast_pos"] != -1) + assert (broadcast_vars[input_name]["broadcast_pos"] < + last_sync_comm_op_idx) + assert (last_sync_comm_op_idx < idx) + return + + +def check_allreduce_sum(block, shard, sharding_ring_id, dp_ring_id=-1): + """ + the op order should be: + grad: + - 0: op that generate Var + - 1: sync_calc + - 2: reduce_sum_sharding (allreduce --> reduce) + - 3: sync_comm + - 4: allreuce_sum_dp (dp_grads) + - 5: sync_comm (dp_grads) + - 6: op that use Var (dp_grads & sum) + + should ignore and skip allreduce_op of inner_parallelism (e.g. Megatron) + """ + vars_status = {} + dp_grads_status = {} + idx_last_grad_allreduce = -1 + idx_amp_allreduce = -1 + idx_gradient_clip_allreduce = -1 + + for idx, op in enumerate(block.ops): + # sharding use both allreduce and reduce to sync grad + if op.type == "c_allreduce_sum" or op.type == "c_reduce_sum": + if op.all_attrs()["use_calc_stream"] == False: + ring_id = op.desc.attr("ring_id") + var_name = op.desc.input_arg_names()[0] + param = var_name.split("@")[0] + + assert 'sum' in var_name or ("@GRAD" in var_name) + if 'sum' in var_name or (not shard.has_param(param)): + vars_status[var_name] = -1 + else: + dp_grads_status[var_name] = -1 + + if ring_id != sharding_ring_id: + assert shard.has_param(param) + assert ring_id == dp_ring_id + + if "sum" in var_name: + idx_amp_allreduce = idx + elif "@GRAD": + idx_last_grad_allreduce = idx + + if op.type == "c_allreduce_max": + idx_gradient_clip_allreduce = idx + + for op in block.ops: + if op.type == "c_sync_calc_stream": + for var_name in vars_status: + if var_name in vars_status and vars_status[var_name] == 0: + vars_status[var_name] = 1 + for var_name in dp_grads_status: + if var_name in dp_grads_status and dp_grads_status[ + var_name] == 0: + dp_grads_status[var_name] = 1 + # check sharding allreduce and reduce but skip megatron allreduce + elif op.type == "c_allreduce_sum" or op.type == "c_reduce_sum": + if op.all_attrs()["use_calc_stream"] == False: + var_name = op.desc.input_arg_names()[0] + ring_id = op.desc.attr("ring_id") + if ring_id == sharding_ring_id: + assert op.type == "c_reduce_sum", "Grad in Sharding group should be reduce rather than allreduce" + if var_name in vars_status: + _status = vars_status[var_name] + else: + _status = dp_grads_status[var_name] + if _status == -1: + raise ValueError( + "{} is not generated, but you are" + "trying to all-reduce it".format(var_name)) + if _status == 0: + raise ValueError("There should be a sync_calc op " + "after generate Var: {} and before the" + "c_allreduce_sum op".format(var_name)) + assert (_status == 1) + if var_name in vars_status: + vars_status[var_name] = 2 + else: + dp_grads_status[var_name] = 2 + else: + assert ring_id == dp_ring_id + param = var_name.split("@")[0] + assert shard.has_param(param) + assert dp_grads_status[var_name] == 3 + dp_grads_status[var_name] = 4 + + elif op.type == "c_sync_comm_stream": + var_name = op.desc.input_arg_names()[0] + ring_id = op.desc.attr("ring_id") + if ring_id == sharding_ring_id: + for var_name in op.desc.input_arg_names(): + if var_name in vars_status: + assert vars_status[var_name] == 2 + vars_status[var_name] = 3 + elif var_name in dp_grads_status: + assert dp_grads_status[var_name] == 2 + dp_grads_status[var_name] = 3 + else: + for var_name in op.desc.input_arg_names(): + param = var_name.split("@")[0] + assert ring_id == dp_ring_id + assert shard.has_param(param) + assert dp_grads_status[var_name] == 4 + dp_grads_status[var_name] = 5 + else: + for input_name in op.desc.input_arg_names(): + if input_name in vars_status: + if vars_status[input_name] != 3: + raise ValueError( + "There should be a sync_comm op " + "after allreduce the Var: {}".format(input_name)) + raise ValueError( + "The reduce output grad [{}] should NOT be be used in Non-root rank." + .format(input_name)) + if input_name in dp_grads_status: + if dp_ring_id == -1: + if dp_grads_status[input_name] != 3: + raise ValueError( + "There should be a sync_comm op " + "after allreduce the Var: {}".format( + input_name)) + else: + if dp_grads_status[input_name] != 5: + raise ValueError( + "The grad in shard should be allreduce and sync" + "twice before usage {}".format(input_name)) + + for output_name in op.desc.output_arg_names(): + if output_name in vars_status and \ + vars_status[output_name] == -1: + vars_status[output_name] = 0 + if output_name in dp_grads_status and \ + dp_grads_status[output_name] == -1: + dp_grads_status[output_name] = 0 + + # check sharding with amp + if idx_amp_allreduce != -1: + assert idx_amp_allreduce > idx_last_grad_allreduce + + # check sharding with gradient_clip_by_global_norm + if idx_gradient_clip_allreduce != -1: + assert idx_gradient_clip_allreduce > idx_last_grad_allreduce + + return + + +def get_valid_op_role(block, insert_idx): + """ + return OpRole.Forward or OpRole.Backward + """ + op_role = block.ops[insert_idx].attr('op_role') + if (insert_idx >= len(block.ops)) or (op_role in [ + int(OpRole.Backward), int(OpRole.Optimize) + ]): + return OpRole.Backward + if op_role in [int(OpRole.Forward), int(OpRole.Loss)]: + return OpRole.Forward + + return get_valid_op_role(block, insert_idx + 1) + + +def insert_sync_calc_op(block, insert_idx, calc_dep_vars): + """ + _insert_sync_calc_op + """ + op_role = get_valid_op_role(block, insert_idx) + block._insert_op_without_sync(insert_idx, + type='c_sync_calc_stream', + inputs={'X': calc_dep_vars}, + outputs={'Out': calc_dep_vars}, + attrs={OP_ROLE_KEY: op_role}) + return + + +def insert_sync_comm_op(block, insert_idx, ring_id, comm_dep_vars): + """ + insert sync_comm_op for single var + """ + op_role = get_valid_op_role(block, insert_idx) + block._insert_op_without_sync(insert_idx, + type='c_sync_comm_stream', + inputs={'X': comm_dep_vars}, + outputs={'Out': comm_dep_vars}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: op_role + }) + return 1 + + +def insert_sync_comm_ops(block, insert_idx, ring_id, comm_dep_vars): + """ + insert sync_comm_op for vars + """ + # NOTE (JZ-LIANG) to be check, may result undefined case + if len(comm_dep_vars) == 0: + return 0 + + op_role = get_valid_op_role(block, insert_idx) + block._insert_op_without_sync(insert_idx, + type='c_sync_comm_stream', + inputs={'X': comm_dep_vars}, + outputs={'Out': comm_dep_vars}, + attrs={ + 'ring_id': int(ring_id), + OP_ROLE_KEY: op_role + }) + return 1 + + +def insert_fill_constant_ops(block, insert_idx, fill_constant_vars): + """ + _add_fill_constant_ops + """ + op_role = get_valid_op_role(block, insert_idx) + for broadcast_name in fill_constant_vars: + broadcast_var = block.var(broadcast_name) + block._insert_op_without_sync(insert_idx, + type="fill_constant", + outputs={"Out": broadcast_var.name}, + attrs={ + "shape": broadcast_var.shape, + "dtype": broadcast_var.dtype, + "value": 0.0, + OP_ROLE_KEY: op_role + }) + return + + +def insert_cast_ops(block, insert_idx, cast_ops): + """ + _add_cast_ops + """ + op_role = get_valid_op_role(block, insert_idx) + for fp16_name, fp32_name in cast_ops.items(): + block._insert_op_without_sync(insert_idx, + type="cast", + inputs={"X": fp32_name}, + outputs={"Out": fp16_name}, + attrs={ + "in_dtype": core.VarDesc.VarType.FP32, + "out_dtype": + core.VarDesc.VarType.FP16, + OP_ROLE_KEY: op_role + }) + return + + +def insert_allreduce_ops(block, + insert_idx, + ring_id, + allreduce_vars, + op_role=OpRole.Backward, + use_calc_stream=False, + user_defined_strategy=None): + """ + _add_allreduce_ops + """ + if len(allreduce_vars) == 0: + return + + if user_defined_strategy and \ + user_defined_strategy.fuse_all_reduce_ops and \ + not user_defined_strategy.fuse_grad_merge: + # If fuse_grad_merge is enable, the grad vars have already been fused during + # gradient merge pass, therefore, those vars are not need to be fused here + insert_fused_allreduce_ops(block, insert_idx, ring_id, allreduce_vars, + op_role, use_calc_stream, + user_defined_strategy.fuse_grad_size_in_MB) + else: + for var in allreduce_vars: + block._insert_op_without_sync(insert_idx, + type='c_allreduce_sum', + inputs={'X': var}, + outputs={'Out': var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': + use_calc_stream, + OP_ROLE_KEY: op_role + }) + + return + + +class FuseHelper(object): + + @staticmethod + def sort_vars_by_dtype(block, vars_name): + fp32_vars = [] + fp16_vars = [] + other_vars = [] + for var in vars_name: + dtype = block.var(var).dtype + if dtype == paddle.float32: + fp32_vars.append(var) + elif dtype == paddle.float16: + fp16_vars.append(var) + else: + other_vars.append(var) + assert len(other_vars) == 0, "only support fp32/fp16 vars for fuse" + + fp32_vars.extend(fp16_vars) + return fp32_vars + + @staticmethod + def get_fused_groups(block, vars_name, fuse_size=32.): + """ coalesce tensor, get fused group """ + groups = [] + cur_size = 0. + last_dtype = None + for var_name in vars_name: + real_var = block.var(var_name) + var_size = get_var_size(real_var) + if cur_size + var_size > fuse_size \ + or len(groups) == 0 \ + or real_var.dtype != last_dtype: + groups.append([real_var]) + cur_size = var_size + last_dtype = real_var.dtype + else: + groups[-1].append(real_var) + cur_size += var_size + return groups + + @staticmethod + def insert_coalesce_tensor(block, + index, + groups, + op_role=OpRole.Backward, + prefix="Output"): + fused_vars = [] + insert_num = 0 + for group in groups: + assert len(group) >= 1 + if len(group) == 1: + # no need fuse + fused_vars.append(group[0]) + continue + + fused_var = block.create_var(name=unique_name.generate( + 'Fused{}_{}'.format(prefix, group[0].name)), + dtype=group[0].dtype, + persistable=False, + stop_gradient=True) + fused_vars.append(fused_var) + block._insert_op_without_sync(index, + type="coalesce_tensor", + inputs={"Input": group}, + outputs={ + "Output": group, + "FusedOutput": fused_var + }, + attrs={ + "copy_data": True, + "use_align": True, + "dtype": group[0].dtype, + OP_ROLE_KEY: op_role + }) + insert_num += 1 + return fused_vars, insert_num + + +def insert_fused_allreduce_ops(block, + insert_idx, + ring_id, + allreduce_vars, + op_role=OpRole.Backward, + use_calc_stream=False, + fuse_grad_size_in_MB=32): + groups = FuseHelper.get_fused_groups(block, allreduce_vars, + fuse_grad_size_in_MB) + + fused_vars, insert_num = FuseHelper.insert_coalesce_tensor(block, + insert_idx, + groups, + op_role, + prefix="Grad") + + for fused_var in fused_vars: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_allreduce_sum', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream, + OP_ROLE_KEY: op_role + }) + if not use_calc_stream: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_sync_calc_stream', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={OP_ROLE_KEY: op_role}) + + +def insert_fused_reduce_ops(block, + insert_idx, + ring_id, + reduce_vars, + shard, + op_role=OpRole.Backward, + use_calc_stream=False, + rank=None, + fuse_grad_size=32): + nranks = shard.worker_num + device_to_vars = [[] for _ in range(nranks)] + + for var in reduce_vars: + root_id = get_grad_device(var, shard) + assert 0 <= root_id < nranks, "root_id should >=0 and < nranks, " \ + "but now nranks={}, the root_id of var={} is {}"\ + .format(nranks, var, root_id) + device_to_vars[root_id].append(var) + + for root_id, vars_name in enumerate(device_to_vars): + groups = FuseHelper.get_fused_groups(block, vars_name, fuse_grad_size) + + fused_vars, insert_num = FuseHelper.insert_coalesce_tensor( + block, insert_idx, groups, op_role, prefix="Grad") + + for fused_var in fused_vars: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_reduce_sum', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'root_id': root_id, + 'use_calc_stream': + use_calc_stream, + OP_ROLE_KEY: op_role + }) + if not use_calc_stream: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_sync_calc_stream', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={OP_ROLE_KEY: op_role}) + + return [] if rank is None else device_to_vars[rank] + + +def insert_reduce_ops(block, + insert_idx, + ring_id, + reduce_vars, + shard, + op_role=OpRole.Backward, + use_calc_stream=False, + rank=None, + strategy=None): + """ + _add_reduce_ops + """ + if strategy and strategy.fuse_all_reduce_ops and \ + not strategy.fuse_grad_merge: + return insert_fused_reduce_ops(block, insert_idx, ring_id, reduce_vars, + shard, op_role, use_calc_stream, rank, + strategy.fuse_grad_size_in_MB) + + grad_in_this_device = [] + for var in reduce_vars: + grad_var = var + if strategy and strategy.fuse_all_reduce_ops and \ + strategy.fuse_grad_merge: + # TODO(wangxi): if support fp16_allreduce, need be + # 'FusedMergedGrad.cast_fp16._' + grad_var = var.replace('FusedMergedGrad_', '') + root_id = get_grad_device(grad_var, shard) + assert root_id >= 0, "root id should be a positive int, but now root id is {}".format( + root_id) + if rank is not None and rank == root_id: + grad_in_this_device.append(var) + block._insert_op_without_sync(insert_idx, + type='c_reduce_sum', + inputs={'X': var}, + outputs={'Out': var}, + attrs={ + 'ring_id': ring_id, + 'root_id': root_id, + 'use_calc_stream': use_calc_stream, + OP_ROLE_KEY: op_role + }) + + return grad_in_this_device + + +def insert_fused_broadcast_param_ops(block, + insert_idx, + ring_id, + params, + shard, + op_role=OpRole.Optimize, + use_calc_stream=False, + rank=None, + fuse_size=32): + nranks = shard.worker_num + device_to_vars = [[] for _ in range(nranks)] + + for var in params: + root_id = shard.device(var) + assert 0 <= root_id < nranks, "root_id should >=0 and < nranks, " \ + "but now nranks={}, the root_id of var={} is {}"\ + .format(nranks, var, root_id) + device_to_vars[root_id].append(var) + + for root_id, vars_name in enumerate(device_to_vars): + groups = FuseHelper.get_fused_groups(block, vars_name, fuse_size) + + fused_vars, insert_num = FuseHelper.insert_coalesce_tensor( + block, insert_idx, groups, op_role, prefix="Param") + + for fused_var in fused_vars: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_broadcast', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'root': root_id, + 'use_calc_stream': + use_calc_stream, + OP_ROLE_KEY: op_role + }) + if not use_calc_stream: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_sync_calc_stream', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={OP_ROLE_KEY: op_role}) + + return [] if rank is None else device_to_vars[rank] + + +def insert_broadcast_param_ops(block, + insert_idx, + ring_id, + params, + shard, + op_role=OpRole.Optimize, + use_calc_stream=False, + rank=None, + strategy=None): + """ + add broadcast param ops + """ + if strategy and strategy.fuse_all_reduce_ops: + # TODO(wangxi): put fused var in startup_program, only need exec once + return insert_fused_broadcast_param_ops(block, insert_idx, ring_id, + params, shard, op_role, + use_calc_stream, rank, + strategy.fuse_grad_size_in_MB) + + param_in_this_device = [] + for param in params: + root_id = shard.device(param) + assert root_id >= 0, "root id should be a positive int, but now root id is {}".format( + root_id) + if rank is not None and rank == root_id: + param_in_this_device.append(param) + block._insert_op_without_sync(insert_idx, + type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': root_id, + 'use_calc_stream': use_calc_stream, + OP_ROLE_KEY: op_role + }) + + return param_in_this_device + + +def fuse_opt_broadcast_param_ops(block, + ring_id, + shard, + op_role=OpRole.Optimize, + strategy=None): + """ + fuse optimizer sharding broadcast param ops + """ + if strategy is None or not strategy.fuse_all_reduce_ops: + return + + fuse_size = strategy.fuse_grad_size_in_MB + + nranks = shard.worker_num + device_to_vars = [[] for _ in range(nranks)] + + for idx, op in reversed(list(enumerate(block.ops))): + if not is_optimizer_op(op) or op.type != 'c_broadcast': + break + var = op.input_arg_names[0] + root_id = op.attr('root') + device_to_vars[root_id].insert(0, var) + block._remove_op(idx, sync=False) + + insert_idx = idx + 1 + for root_id, vars_name in enumerate(device_to_vars): + vars_name = FuseHelper.sort_vars_by_dtype(block, vars_name) + groups = FuseHelper.get_fused_groups(block, vars_name, fuse_size) + + fused_vars, insert_num = FuseHelper.insert_coalesce_tensor( + block, insert_idx, groups, op_role, prefix="Param") + + for fused_var in fused_vars: + block._insert_op_without_sync(insert_idx + insert_num, + type='c_broadcast', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'root': root_id, + 'use_calc_stream': True, + OP_ROLE_KEY: op_role + }) + + block._sync_with_cpp() + + +def get_grad_device(grad_name, shard): + assert "@GRAD" in grad_name, "[{}] should be a grad variable.".format( + grad_name) + base_name = None + # NOTE: mind the traversal order + possible_suffixes = [ + # sharding gm + '.cast_fp16@GRAD@MERGED', + '.cast_fp16@GRAD', + # pipeline + '@GRAD@MERGED@FP16', + '@GRAD@MERGED', + '@GRAD', + ] + for suffix in possible_suffixes: + if suffix in grad_name: + base_name = re.sub(suffix, '', grad_name) + break + + assert base_name in shard.global_param2device, "[{}] should be a param variable.".format( + base_name) + + return shard.global_param2device[base_name] + + +def get_first_check_finite_and_unscale_op_idx(block, raise_error=True): + + for idx, op in enumerate(block.ops): + if op.type == "check_finite_and_unscale": + return idx + + if raise_error: + raise ValueError( + "amp is turned on but check_finite_and_unscale op does not exist in main block" + ) + + return -1 + + +def get_first_optimize_op_idx(block): + first_opt_op_idx = None + for index, op in reversed(tuple(enumerate(block.ops))): + if is_backward_op(op) and first_opt_op_idx is None: + first_opt_op_idx = index + 1 + break + return first_opt_op_idx + + +def insert_broadcast_ops(block, insert_idx, ring_id, broadcast2root): + """ + _add_broadcast_ops + """ + op_role = get_valid_op_role(block, insert_idx) + for broadcast_name, root_device in broadcast2root: + block._insert_op_without_sync(insert_idx, + type='c_broadcast', + inputs={'X': broadcast_name}, + outputs={'Out': broadcast_name}, + attrs={ + 'ring_id': ring_id, + 'root': root_device, + OP_ROLE_KEY: op_role + }) + + return + + +DtypeToSize = { + core.VarDesc.VarType.FP16: 2, + core.VarDesc.VarType.FP32: 4, + core.VarDesc.VarType.FP64: 8, + core.VarDesc.VarType.INT16: 2, + core.VarDesc.VarType.INT32: 4, + core.VarDesc.VarType.INT64: 8, + core.VarDesc.VarType.BOOL: 1, + core.VarDesc.VarType.UINT8: 1, +} + + +def get_var_size(param): + """ + input: + - param: var + return: + var size in MB + """ + assert -1 not in param.shape + return reduce(lambda x, y: x * y, + param.shape) * DtypeToSize[param.dtype] / 1024.0 / 1024.0 + + +def insert_scale_loss_grad_ops(block, scale=1.0): + ''' + In order to keep the learning rate consistent in different numbers of + training workers, we scale the loss grad by the number of workers + ''' + for idx, op in reversed(list(enumerate(block.ops))): + if is_loss_grad_op(op): + assert op.type == 'fill_constant', \ + "loss_grad_op must be fill_constant op, " \ + "but this op is {}".format(op.type) + assert op.has_attr('value') + loss_scale = float(op.attr('value')) + loss_scale = loss_scale / scale + op._set_attr('value', loss_scale) + break + + +def comm_analyse(main_program): + """ + Analyse the parameter size that need to be broadcast/allreduce during sharding training + """ + reduce_vars = {} + broadcast_vars = {} + block = main_program.global_block() + for op in block.ops: + if op.type == "c_broadcast": + var_name = op.desc.input_arg_names()[0] + # convert MB to KB + broadcast_vars[var_name] = get_var_size( + block.var(var_name)) * 1024.0 + elif op.type == "c_allreduce_sum": + var_name = op.desc.input_arg_names()[0] + reduce_vars[var_name] = get_var_size(block.var(var_name)) * 1024.0 + + varsize_count = {} + gap = 1 + + for k, v in broadcast_vars.items(): + print("broadcast: {}: {} KB".format(k, v)) + if (int(v / gap) in varsize_count): + varsize_count[int(v / gap)] += 1 + else: + varsize_count[int(v / gap)] = 1 + + for k, v in reduce_vars.items(): + print("allreduce: {}: {} KB".format(k, v)) + if (int(v / gap) in varsize_count): + varsize_count[int(v / gap)] += 1 + else: + varsize_count[int(v / gap)] = 1 + + with open("nccl_size.txt", 'w') as f: + sorted_varsize = sorted(varsize_count.items(), key=lambda x: x[0]) + for varsize, count in sorted_varsize: + print("NCCL size {}~{} KB: {}".format(varsize, varsize + 1, count)) + f.write("NCCL size {}~{} KB: {}\n".format(varsize, varsize + 1, + count)) + + +def add_sync_comm(program, sharding_ring_id): + """ + When clone a test prog by clone from the sharding main prog, + part of the sync_comm op maybe be pruned by mistake, this function + add the sync_comm op for the test prog. + + """ + #NOTE (liangjianzhong): only support one comm stream by now, use more than one + # comm streams will cause error. should be revise in future. + + assert sharding_ring_id >= 0, "sharding_ring_id should larger than zero" + block = program.global_block() + not_sync_vars = set([]) + for op in block.ops: + if op.type in ["c_broadcast", "c_allreduce"]: + for input_name in op.desc.input_arg_names(): + not_sync_vars.add(input_name) + if op.type == "c_sync_comm_stream": + for input_name in op.desc.input_arg_names(): + not_sync_vars.remove(input_name) + if not_sync_vars: + block.append_op(type='c_sync_comm_stream', + inputs={'X': list(not_sync_vars)}, + outputs={'Out': list(not_sync_vars)}, + attrs={ + 'ring_id': + sharding_ring_id, + 'op_role': + core.op_proto_and_checker_maker.OpRole.Forward + }) + return + + +def save_persistables(exe, dirname, main_program, filename=None): + """ + When use sharding, part of persistable vars are unique and are partitioned in different ranks, + and part of persistable vars are duplicated and exist in all the ranks with different values. + This function handles the model saving for sharding training. + """ + # TODO (JZ-LIANG) revise this for uniform mixed parallelism + if main_program._pipeline_opt: + main_program = main_program._pipeline_opt['section_program'] + + def is_opt_vars(var): + # NOTE(JZ-LIANG): The checks should be updated when add new compatible optimizer + # now only Momentum and adam are compatible with sharding, + # support EMA optimizer with '_ema_0', + # support offload with '@offload_0' and '.cast_fp16' + checks = [ + "_moment1_0", "_moment2_0", "_beta1_pow_acc_0", "_beta2_pow_acc_0", + "_velocity_0", "_ema_0", "@offload_0", ".cast_fp16" + ] + for check in checks: + if var.name.endswith(check) and var.persistable: + return True + return False + + def is_gradient_merge_vars(var): + # NOTE(JZ-LIANG): to revise save/load logic in framework instead of write this naive rule + + return var.name.endswith("@GradiantMerge") + + def is_trainable(var): + return isinstance(var, + paddle.fluid.framework.Parameter) and var.trainable + + def sharding_predicate(var): + return is_trainable(var) or is_opt_vars(var) or is_gradient_merge_vars( + var) + + if int(os.environ.get('PADDLE_TRAINER_ID', 0)) == 0: + paddle.fluid.io.save_persistables(exe, + dirname, + main_program=main_program, + filename=None) + else: + paddle.fluid.io.save_vars(exe, + dirname, + main_program=main_program, + predicate=sharding_predicate, + filename=None) + + return + + +def append_naive_sync(block, sync_var, ring_id): + # NOTE (JZ-LIANG) update this to use barrier sync for more elegent logic + # sync within global + block.append_op(type="fill_constant", + outputs={"Out": sync_var}, + attrs={ + "shape": sync_var.shape, + "dtype": sync_var.dtype, + "value": int(1), + }) + block.append_op(type='c_allreduce_sum', + inputs={'X': sync_var}, + outputs={'Out': sync_var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + block.append_op(type='c_sync_calc_stream', + inputs={'X': [sync_var]}, + outputs={'Out': [sync_var]}, + attrs={OP_ROLE_KEY: OpRole.Forward}) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/weight_decay_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/weight_decay_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..42c52af44311c50b63e8341224e961cff481b646 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding/weight_decay_helper.py @@ -0,0 +1,40 @@ +# 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. + +from paddle.distributed.fleet.meta_optimizers.common import OP_ROLE_VAR_KEY + +__all__ = [] + + +class WeightDecayHelper(object): + + def __init__(self): + pass + + def _is_weight_decay_op(self, op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/regularization") + + def prune_weight_decay(self, block, shard): + for idx, op in reversed(list(enumerate(block.ops))): + if not self._is_weight_decay_op(op): + continue + if OP_ROLE_VAR_KEY not in op.attr_names: + raise ValueError( + "The Weight Dacay op should hold op_role_var attribute" + "but the {} op does not hold op_role_var".format(op.type)) + op_role_var = op.all_attrs()[OP_ROLE_VAR_KEY] + if not shard.has_param(op_role_var[0]): + block._remove_op(idx, sync=False) + block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ccac803e72130eaa1432539c41095b0e728bd0e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/sharding_optimizer.py @@ -0,0 +1,1839 @@ +# 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. + +import paddle +from paddle.fluid import unique_name, core +import paddle.fluid as fluid +from paddle.static import default_startup_program, device_guard +from paddle.fluid import layers + +from .common import OpRole, OP_ROLE_VAR_KEY, CollectiveHelper, OP_ROLE_KEY +from .common import is_backward_op, is_optimizer_op, is_update_op +from .meta_optimizer_base import MetaOptimizerBase +from .sharding.shard import Shard, ProgramSegment +from .sharding.fp16_helper import FP16Utils +from .sharding.weight_decay_helper import WeightDecayHelper +from .sharding.gradient_clip_helper import GradientClipHelper +from .sharding.offload_helper import OffloadHelper +from .sharding.prune import ProgramDeps +from .sharding import utils +# FIXME: import * +from .sharding.utils import * +import logging +from ..utils.log_util import logger + +__all__ = [] + + +class ShardingOptimizer(MetaOptimizerBase): + """Sharding Optimizer.""" + + def __init__(self, optimizer): + super(ShardingOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = [ + "RecomputeOptimizer", + "AMPOptimizer", + "LarsOptimizer", + "LambOptimizer", + "ASPOptimizer", + # "ModelParallelOptimizer", + # "PipelineOptimizer", + ] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", + ] + self._main_program = None + self._startup_program = None + self._segments = [] + # params and fp16 params is for broadcast + self._params = set([]) + self._broadcast_vars = set([]) + # reduced grads to param name + self._reduced_grads_to_param = {} + self._shard = Shard() + self._verbose = False + + # use sharding as outer parallelism (e.g. inner:Megatron & outer sharding) + self.mp_degree = 1 + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + if self.role_maker._worker_num() <= 1: + return False + return self.user_defined_strategy.sharding + + def _disable_strategy(self, dist_strategy): + dist_strategy.sharding = False + dist_strategy.sharding_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.sharding = True + dist_strategy.sharding_configs = {"segment_broadcast_MB": 32} + + def _get_sharding_segment_strategy(self): + """ get + self._sharding_segment_strategy + 1. if by_size: self._broadcast_MB + 2. if by_anchors: self._sharding_segment_anchors + self._backward_remain_anchors + self._forward_remain_anchors + """ + strategy = self.user_defined_strategy + sharding_configs = strategy.sharding_configs + segment_strategy = str(sharding_configs["sharding_segment_strategy"]) + + if segment_strategy == "segment_broadcast_MB": + self._broadcast_MB = sharding_configs["segment_broadcast_MB"] + assert self._broadcast_MB > 0, "segment size should larger than zero !" + elif segment_strategy == "segment_anchors": + self._sharding_segment_anchors = sharding_configs["segment_anchors"] + assert len(self._sharding_segment_anchors + ) > 0, "you should set the sharding segment anchors !" + self._backward_remain_anchors = self._sharding_segment_anchors[:] + self._forward_remain_anchors = [] + else: + raise NotImplementedError( + "the sharding segment strategy [{}] is not implemented".format( + str(segment_strategy))) + self._sharding_segment_strategy = segment_strategy + + def _get_hybrid_degree(self): + """ get + self.hybrid_dp + self.sharding_degree + self.mp_degree + self.pp_degree + self.dp_degree + """ + strategy = self.user_defined_strategy + sharding_configs = strategy.sharding_configs + + # parallelism + sharding_degree = int(sharding_configs["sharding_degree"]) + mp_degree = int(sharding_configs["mp_degree"]) + pp_degree = int(sharding_configs["pp_degree"]) + dp_degree = int(sharding_configs['dp_degree']) + global_world_size = self.role_maker._worker_num() + + assert sharding_degree > 0, "sharding degree must be larger than zero" + # pipeline setting + # TODO (JZ-LIANG) should revise here for support mix parallelism with pipeline + if pp_degree > 1: + assert strategy.pipeline is True + + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None): + assert pp_degree == 2, ("For manually set pipeline, only " + "pp_degree = 2 is supported.") + assert global_world_size == mp_degree * sharding_degree * dp_degree, \ + "global work size [{}], mp_degree [{}], sharding_degree [{}], dp_degree [{}].".format( + global_world_size, mp_degree, sharding_degree, dp_degree) + else: + assert global_world_size == mp_degree * sharding_degree * pp_degree * dp_degree, \ + "global work size [{}], mp_degree [{}], sharding_degree [{}], pp_degree [{}], dp_degree [{}].".format( + global_world_size, mp_degree, sharding_degree, pp_degree, dp_degree) + + # FIXME (JZ-LIANG) deprecated hybrid_dp + if sharding_configs["hybrid_dp"]: + logger.warning( + "[hybrid_dp] API setting is deprecated. Now when " + "dp_degree >= 2, its will be in hybrid dp mode automatically") + assert dp_degree >= 1 + + self.hybrid_dp = True if dp_degree > 1 else False + self.sharding_degree = sharding_degree + self.mp_degree = mp_degree + self.pp_degree = pp_degree + self.dp_degree = dp_degree + + def _get_hybrid_dp_mode(self): + """ get + self.hybrid_dp_mode = 'pp_hybrid_dp' or 'sharding_hybrid_dp' + self.gradient_merge_mode = 'pp_gm' or 'sharding_gm' + self._gradient_merge_acc_step + self.pp_allreduce_in_optimize + self._optimizer_sharding + """ + strategy = self.user_defined_strategy + sharding_configs = strategy.sharding_configs + + # NOTE (JZ-LIANG) + # There 2 kind of modes for gradient-merge and hybrid-dp in mixed parallelism [sharding] and [pipeline]. + # We distinguish this two modes since the gm/hybrid-dp related allreduce should be insert in different place + # according different mode to have best performance: + # sharding: communication within node, and therefore should insert within backward segment + # to overlap with bw calc, conduct every micro step. + # pipeline: communication across nodes, and therefore should insert in update segment, + # conduct just once per global step. + dp_mode = None + # dp here is the pure dp as the outest parallelism + if self.hybrid_dp: + if self.pp_degree > 1: + dp_mode = "pp_hybrid_dp" + else: + assert self.sharding_degree > 1, \ + "by now we only support five kind of hybrid dp: sharding_hybrid_dp, " \ + "mp_sharding_hybrid_dp, pp_hybrid_dp, mp_sharding_pp_hybrid_dp, sharding_pp_hybrid_dp." + dp_mode = "sharding_hybrid_dp" + + # gradient merge + gm_mode = None + gm_acc_step = int(sharding_configs["gradient_merge_acc_step"]) + if self.pp_degree <= 1: + gm_mode = "sharding_gm" + self._grad2merged_grad = dict() + else: + gm_mode = "pp_gm" + gm_acc_step = strategy.pipeline_configs['accumulate_steps'] + gradient_scale_configs = strategy.gradient_scale_configs + assert gradient_scale_configs['scale_strategy'] == 'avg', \ + 'For pipeline mode, the ' 'gradient scale mode should ' \ + 'be "avg", but got {}'.format(gradient_scale_configs['scale_strategy']) + # Note (Yuang Liu): this avg_loss flag determines where to do the average op for grad merge. + # If True, will do sum firstly for gradient merge, then do scale by gm_acc_step. + # If False, will scale loss by gm_acc_step first, then do sum for gradient merge. + self.scale_gradient = gradient_scale_configs['scale_gradient'] + if gm_acc_step > 1: + logger.info("Gradient merge in [{}], acc step = [{}]".format( + gm_mode, gm_acc_step)) + + optimizer_sharding = False + # TODO(wangxi): need support dp_as_opt_sharding with sharding + # need support without pp in future + if self.sharding_degree == 1 and self.dp_degree > 1 \ + and sharding_configs['_dp_as_optimizer_sharding'] \ + and self.pp_degree > 1: + optimizer_sharding = True + + self.hybrid_dp_mode = dp_mode + self.gradient_merge_mode = gm_mode + self._gradient_merge_acc_step = gm_acc_step + self._optimizer_sharding = optimizer_sharding + + # this feature is design for ascend, and should NOT be used in GPU training + self.pp_allreduce_in_optimize = sharding_configs[ + "pp_allreduce_in_optimize"] + + def _inner_opt_minimize(self, loss, startup_program, parameter_list, + no_grad_set): + pipeline_configs = self.user_defined_strategy.pipeline_configs + + if self.inner_opt is None: + raise ValueError( + "self.inner_opt of ShardingOptimizer should not be None.") + + if self.pp_degree > 1: + pp_optimizer = fluid.optimizer.PipelineOptimizer( + self.inner_opt, self._gradient_merge_acc_step) + self._pp_optimizer = pp_optimizer + + global_rank = self.role_maker._worker_index() + schedule_mode = pipeline_configs['schedule_mode'] + + pipeline_opt = { + 'schedule_mode': schedule_mode, + 'micro_batch_size': pipeline_configs['micro_batch_size'], + 'local_rank': self.pp_rank, + 'global_rank': global_rank, + 'use_sharding': True, + # TODO (JZ-LIANG) should revise here for support mix parallelism with pipeline + 'ring_id': 20, + 'global_ring_id': 3, + 'mp_degree': self.mp_degree, + 'mp_rank': global_rank % self.mp_degree, + 'scale_gradient': self.scale_gradient + } + main_program = loss.block.program + main_program._pipeline_opt = pipeline_opt + + optimize_ops, params_grads, program_list, self.pipeline_pair, self.pp_ring_map = pp_optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set) + assert self.pp_degree == len(program_list) + else: + optimize_ops, params_grads = self.inner_opt.minimize( + loss, startup_program, parameter_list, no_grad_set) + + if startup_program is None: + startup_program = default_startup_program() + + if self.pp_degree > 1: + startup_program = startup_program._pipeline_opt['startup_program'] + print("pp_rank:", self.pp_rank) + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None): + main_program = program_list[int( + os.getenv("PADDLE_MANUAL_PIPELINE_STAGE"))] + else: + main_program = program_list[self.pp_rank] + with open("main_%d" % self.role_maker._worker_index(), 'w') as f: + f.writelines(str(main_program)) + main_block = main_program.global_block() + new_params_grads = [] + for param, grad in params_grads: + if main_block.has_var(param.name): + new_params_grads.append((param, grad)) + params_grads = new_params_grads + else: + main_block = loss.block + + startup_block = startup_program.global_block() + self._main_program = main_block.program + self._startup_program = startup_program + + if self.pp_degree > 1: + pp_optimizer._rename_gradient_var_name(main_block) + with open("main_%d" % self.role_maker._worker_index(), 'w') as f: + f.writelines(str(main_program)) + + return optimize_ops, params_grads + + def _apply_sharding_pass(self, params_grads): + if self.sharding_degree == 1: return + + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + # step1: build shard + self._build_shard(params_grads, self.sharding_rank, + self.sharding_degree) + + # step2: split_program + self._split_program(main_block) + + # step3: add broadcast and reduce ops + self._add_broadcast_allreduce(main_block) + main_block._sync_with_cpp() + startup_block._sync_with_cpp() + + # step4: remove unneeded ops and vars from block + self._prune_main_program( + main_block, self._shard, + [self.mp_ring_id, self.sharding_ring_id, self.pp_ring_id]) + self._prune_startup_program(startup_block, self._shard) + + def _apply_opt_sharding_pass(self, params_grads): + """ outer dp as optimizer sharding """ + if self._optimizer_sharding is False: return + + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + # step1: build shard + self._build_shard(params_grads, self.dp_rank, self.dp_degree) + + # NOTE(wangxi): prune_main_program will prune cast if not add this + for param, grad in params_grads: + self._reduced_grads_to_param[grad.name] = param.name + + # step4: remove unneeded ops and vars from block + self._prune_main_program( + main_block, self._shard, + [self.mp_ring_id, self.pp_ring_id, self.dp_ring_id]) + self._prune_startup_program(startup_block, self._shard) + + def _insert_allreduce_for_pp(self, params_grads): + if self.pp_degree == 1: return + + strategy = self.user_defined_strategy + sharding_configs = strategy.sharding_configs + + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + # sharding-pp related logic + # pp_optimizer._rename_gradient_var_name(main_block) + # crop ops + if self.sharding_degree > 1: + for idx, op in reversed(list(enumerate(main_block.ops))): + if is_update_op(op): + op_role_var = op.attr('op_role_var') + param_name = op_role_var[0] + if not self._shard.has_param(param_name): + main_block._remove_op(idx) + + for idx, op in reversed(list(enumerate(main_block.ops))): + if op.type != 'cast': continue + in_name = op.input_arg_names[0] + if in_name not in self._params: continue + #if self._shard.has_param(param_name): continue + if in_name not in main_block.vars: + main_block._remove_op(idx) + + if self._optimizer_sharding: + # TODO(wangxi): support fp16_allreduce with optimizer sharding + strategy.fp16_allreduce = False + + shard = self._shard if self._optimizer_sharding else None + accumulated_grad_names = self._pp_optimizer._accumulate_gradients( + main_block, strategy=strategy, shard=shard) + + len_of_ops = len(main_block.ops) + if self.scale_gradient: + self._avg_grad_merge_after_sum(main_block, accumulated_grad_names) + first_optimize_op_index = get_first_optimize_op_idx(main_block) + + if self.pp_allreduce_in_optimize: + logger.info("Pipeline Persistable grad is {}".format( + accumulated_grad_names)) + # FIXME(wangxi): accumulated_grad get from pipeline is not + # include sharding's param@BroadCast grad when + # pp_allreduce_in_optimize + accumulated_grad_names = insert_reduce_ops( + main_block, + first_optimize_op_index, + self.sharding_ring_id, + accumulated_grad_names, + self._shard, + core.op_proto_and_checker_maker.OpRole.Optimize, + use_calc_stream=True, + rank=self.sharding_rank) + + logger.info("PP-Sharding grad is {}".format(accumulated_grad_names)) + first_optimize_op_index += (len(main_block.ops) - len_of_ops) + len_of_ops = len(main_block.ops) + + if self._optimizer_sharding: + accumulated_grad_names = utils.insert_reduce_ops( + main_block, + first_optimize_op_index, + self.dp_ring_id, + accumulated_grad_names, + self._shard, + OpRole.Optimize, + use_calc_stream=True, + rank=self.dp_rank, + strategy=strategy) + logger.info( + "Optimizer grad in this rank {}".format(accumulated_grad_names)) + first_optimize_op_index += (len(main_block.ops) - len_of_ops) + len_of_ops = len(main_block.ops) + + # NOTE(wangxi): we fused after optimize_cast + optimize_cast = sharding_configs['optimize_cast'] + optimizer_param = utils.insert_broadcast_param_ops( + main_block, + len_of_ops, + self.dp_ring_id, [x[0].name for x in params_grads], + self._shard, + OpRole.Optimize, + use_calc_stream=True, + rank=self.dp_rank, + strategy=None if optimize_cast else strategy) + logger.info( + "Optimizer param in this rank {}".format(optimizer_param)) + if not strategy.fuse_grad_merge and not optimize_cast: + assert len(accumulated_grad_names) == len(optimizer_param) + elif self.hybrid_dp and self.hybrid_dp_mode == "pp_hybrid_dp": + insert_allreduce_ops( + main_block, + first_optimize_op_index, + self.dp_ring_id, + accumulated_grad_names, + core.op_proto_and_checker_maker.OpRole.Optimize, + use_calc_stream=True, + user_defined_strategy=strategy) + first_optimize_op_index += (len(main_block.ops) - len_of_ops) + len_of_ops = len(main_block.ops) + + # FIXME(wangxi): if fp16_allreduce, put cast fp16->fp32 to there? + + def _avg_grad_merge_after_sum(self, main_block, accumulated_grad_names): + if self.user_defined_strategy.amp and \ + self.user_defined_strategy.amp_configs['use_dynamic_loss_scaling']: + # For AMP, if using dynamic loss scaling the avg + # operation can be simple done by modify the LossScaling op. + for idx, op in enumerate(main_block.ops): + if op.type == 'check_finite_and_unscale': + loss_scale_name = op.input('Scale')[0] + loss_scaling_var = main_block.var(loss_scale_name) + loss_scale_tmp_var_name = loss_scale_name + '@TMP' + loss_scale_tmp_var = main_block.create_var( + name=loss_scale_tmp_var_name, + shape=loss_scaling_var.shape, + dtype=loss_scaling_var.dtype) + main_block._insert_op_without_sync( + idx, + type='scale', + inputs={'X': loss_scaling_var}, + outputs={'Out': loss_scale_tmp_var}, + attrs={ + 'scale': self._gradient_merge_acc_step, + 'bias': 0.0, + 'bias_after_scale': False, + OP_ROLE_KEY: OpRole.Optimize + }) + op._rename_input(loss_scale_name, loss_scale_tmp_var_name) + break + else: + # For pp, do the avg operation for gradient merge after merging + # the gradient to meet the logic for gradient merge under pure dp. + tmp_first_opt_idx = None + for idx, op in enumerate(main_block.ops): + if is_optimizer_op(op) and op.type != 'c_sync_comm_stream': + tmp_first_opt_idx = idx + break + assert tmp_first_opt_idx is not None, 'Occurs some errors, no optimize ops' + for grad in accumulated_grad_names: + main_block._insert_op_without_sync( + tmp_first_opt_idx, + type='scale', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'scale': 1.0 / self._gradient_merge_acc_step, + 'bias': 0.0, + 'bias_after_scale': False, + OP_ROLE_KEY: OpRole.Optimize + }) + + def _adapt_amp_clip_without_sharding(self): + # if not use sharding, adapt amp/clip, for remain parallelism. + # cast --> amp --> clip --> opt + if self.sharding_degree > 1: return + if self._optimizer_sharding: return + + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + # amp inf_var & clip global_norm_var + + rings = [self.mp_ring_id, self.pp_ring_id] + # FIXME(wangxi): some problem with NPU found_finite, need sync with DP + if core.is_compiled_with_npu(): + rings += [self.dp_ring_id] + FP16Utils.sync_amp_check_nan_inf(main_block, rings) + + gradientclip_helper = GradientClipHelper(None) + gradientclip_helper.sync_global_norm(main_block, + [self.mp_ring_id, self.pp_ring_id], + self.mp_rank) + + def _insert_loss_grad_scale_op(self): + main_block = self._main_program.global_block() + + # step6: loss div dp_degree + global_dp_degree = self.sharding_degree * self.dp_degree + assert int(global_dp_degree) == global_dp_degree + if global_dp_degree > 1: + insert_scale_loss_grad_ops(main_block, scale=global_dp_degree) + + main_block._sync_with_cpp() + + def _apply_optimize_offload_pass(self, params_grads): + strategy = self.user_defined_strategy + sharding_configs = strategy.sharding_configs + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + mp_ring_id = self.mp_ring_id if self.mp_degree > 1 else None + dp_ring_id = self.dp_ring_id if self.dp_degree > 1 else None + offload_helper = OffloadHelper(mp_ring_id=mp_ring_id, + dp_ring_id=dp_ring_id) + + # optimize offload should be enable while gradient merge is enable and + # acc_step is quite large (e.g. >> 100). Since its memcpy could not be + # overlap with calc, otherwise it will slower down training severely. + if sharding_configs["optimize_offload"]: + logger.info("Sharding with optimize offload !") + offload_helper.offload(main_block, startup_block) + # The optimize_cast is already included in offload_fp32param + offload_helper.offload_fp32param(main_block, startup_block) + elif sharding_configs['optimize_cast']: + logger.info("Sharding with optimize cast !") + # NOTE(wangxi): optimize_cast will persist fp16 param, it + # will take more memory, but will be faster. Trade space for time. + if self._optimizer_sharding: + offload_helper.opt_sharding_cast_fp32param( + main_block, startup_block, + [x[0].name for x in params_grads]) + # NOTE(wangxi): fused after optimize_cast + utils.fuse_opt_broadcast_param_ops(main_block, + dp_ring_id, + self._shard, + strategy=strategy) + else: + offload_helper.cast_fp32param_in_optimize( + main_block, startup_block) + + def _dump_program_for_debug(self): + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + with open("start_sharding_%d" % self.role_maker._worker_index(), + 'w') as f: + f.writelines(str(startup_block.program)) + with open("main_sharding_%d" % self.role_maker._worker_index(), + 'w') as f: + f.writelines(str(main_block.program)) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + # TODO: (JZ-LIANG) support multiple comm in future + # self._nrings = self.user_defined_strategy.nccl_comm_num + self._nrings_sharding = 1 + self._nrings_dp = 1 + + self._get_sharding_segment_strategy() + self._get_hybrid_degree() + self._get_hybrid_dp_mode() + + # config sharding & dp groups + self._build_groups() + + # inner optimize minimize + optimize_ops, params_grads = self._inner_opt_minimize( + loss, startup_program, parameter_list, no_grad_set) + + self._init_comm() + + self._apply_sharding_pass(params_grads) + + self._apply_opt_sharding_pass(params_grads) + + self._insert_allreduce_for_pp(params_grads) + + self._adapt_amp_clip_without_sharding() + + # loss div dp_degree + self._insert_loss_grad_scale_op() + + # apply optimize offload or optimize cast + self._apply_optimize_offload_pass(params_grads) + + # step6: (optional) sharding gradient merge + self._sharding_gradient_merge() + + # # check op dependecy + # FIXME (JZ-LIANG) enable checking in future. + # check_broadcast(main_block) + # check_allreduce_sum(main_block, self._shard, self.sharding_ring_id, + # self.dp_ring_id) + + # NOTE(JZ-LIANG) ensure in both sharding_hybrid_dp & pp_hybrid_dp + # init param broadcast should be called after startup pruning + self._initialization_broadcast() + + # NOTE(wangxi): if param is not persistable, program.clone will + # failed, so we remove no persistable param, recreate param as a var + self._recreate_not_persist_param_as_var() + + self._dump_program_for_debug() + + # GPU need to wait server ready, GPU and NPU is Layered connection + if not core.is_compiled_with_npu(): + self._wait() + return optimize_ops, params_grads + + def _init_pair_comm(self, pair, ring_id): + pp_group_endpoints = [ + self.pp_group_endpoints[pair[0]], + self.pp_group_endpoints[pair[1]], + ] + pp_rank = 0 if self.pp_rank == pair[0] else 1 + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None) is None: + self._collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + pp_group_endpoints, + pp_rank, + ring_id, + False, + sync=False) + + def _init_npu_pipeline_comm(self, startup_block): + # NOTE(wangxi): some bug with hccl, must set pp_degree be even number + assert (self.pp_degree % 2) == 0 + + max_ring_id = -1 + my_pair = [] + for pair in self.pipeline_pair: + pair_key = pair[0] * 1000 + pair[1] + ring_id = self.pp_ring_map[pair_key] + max_ring_id = max(max_ring_id, ring_id) + logger.info("pp pair:{}, ring_id: {}".format(pair, ring_id)) + + if self.pp_rank in pair: + my_pair.append(pair) + + # for example: self.pp_rank=2, self.pp_degree=4 + send_to_next_pair = (self.pp_rank, (self.pp_rank + 1) % self.pp_degree + ) # 2->3 + recv_from_next_pair = ( + (self.pp_rank + 1) % self.pp_degree, self.pp_rank) # 3->2 + recv_from_prev_pair = ( + (self.pp_rank - 1 + self.pp_degree) % self.pp_degree, self.pp_rank + ) # 1->2 + send_to_prev_pair = (self.pp_rank, (self.pp_rank - 1 + self.pp_degree) % + self.pp_degree) # 2->1 + + even = (self.pp_rank % 2) == 0 + + # 1. even send to next, odd recv from prev, 0->1, 2->3 + pair = send_to_next_pair if even else recv_from_prev_pair + ring_id = self.pp_ring_map[pair[0] * 1000 + pair[1]] + self._init_pair_comm(pair, ring_id) + my_pair.remove(pair) + logger.info("pair0(even->odd): pp pair:{}, ring_id: {}".format( + pair, ring_id)) + + # 2. even recv from next, odd send to prev, 1->0, 3->2 + pair = recv_from_next_pair if even else send_to_prev_pair + ring_id = self.pp_ring_map[pair[0] * 1000 + pair[1]] + self._init_pair_comm(pair, ring_id) + my_pair.remove(pair) + logger.info("pair1(even<-odd): pp pair:{}, ring_id: {}".format( + pair, ring_id)) + + # if pp_degree is 2, only need pair(0->1, 1->0) + if self.pp_degree > 2: + # 3. odd send to next, even recv from prev, 1->2, 3->0 + pair = send_to_next_pair if not even else recv_from_prev_pair + ring_id = self.pp_ring_map.get(pair[0] * 1000 + pair[1], + max_ring_id + + 1) # 3->0 not in pp_ring_map + self._init_pair_comm(pair, ring_id) + if self.pp_rank != 0 and self.pp_rank != self.pp_degree - 1: + my_pair.remove(pair) + logger.info("pair2(odd->even): pp pair:{}, ring_id: {}".format( + pair, ring_id)) + + # 4. odd recv from next, even send to prev, 2->1, 0->3 + pair = recv_from_next_pair if not even else send_to_prev_pair + ring_id = self.pp_ring_map.get(pair[0] * 1000 + pair[1], + max_ring_id + + 2) # 0->3 not in pp_ring_map + self._init_pair_comm(pair, ring_id) + if self.pp_rank != 0 and self.pp_rank != self.pp_degree - 1: + my_pair.remove(pair) + logger.info("pair3(odd<-even): pp pair:{}, ring_id: {}".format( + pair, ring_id)) + + assert len(my_pair) == 0, "Current pipeline does not support cross stage communication, " \ + "please check unexpected pair {}".format(my_pair) + + def _init_pipeline_comm(self, startup_block): + # TODO (JZ-LIANG) to unify pp_rank_ and pp_rank + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None) is None: + self._collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + self.pp_group_endpoints, + self.pp_rank, + self.pp_ring_id, + False, + sync=False) + + if core.is_compiled_with_npu(): + self._init_npu_pipeline_comm(startup_block) + return + + # GPU + for pair in self.pipeline_pair: + pair_key = pair[0] * 1000 + pair[1] + ring_id = self.pp_ring_map[pair_key] + logger.info("pp pair:{}, ring_id: {}".format(pair, ring_id)) + if self.pp_rank in pair: + self._init_pair_comm(pair, ring_id) + + def _init_comm(self): + # sync var + startup_block = self._startup_program.global_block() + + # mp ring + if self.mp_degree > 1: + self._collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + self.mp_group_endpoints, + self.mp_rank, + self.mp_ring_id, + False, + sync=False) + + # sharding ring + if self.sharding_degree > 1: + self._collective_helper._init_communicator( + self._startup_program, + self.current_endpoint, + self.sharding_group_endpoints, + self.sharding_rank, + self.sharding_ring_id, + False, + sync=False) + + # pp ring + if self.pp_degree > 1: + self._init_pipeline_comm(startup_block) + + # pure dp ring + if self.dp_degree > 1: + self._collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + self.dp_group_endpoints, + self.dp_rank, + self.dp_ring_id, + False, + sync=False) + + startup_block._sync_with_cpp() + + def _build_shard(self, params_grads, shard_rank, shard_size): + # step 2: split params + self._params = set([x[0].name for x in params_grads]) + self._shard.setup(params_grads, shard_rank, shard_size) + + # step 3: get broadcast vars + self._broadcast_vars = self._shard.find_broadcast_params( + self._main_program.global_block()) + + def _wait(self, ): + endpoints = self.global_endpoints[:] + current_endpoint = endpoints[self.global_rank] + if self.global_rank == 0: + self._collective_helper._wait(current_endpoint, endpoints) + + def collect_segment(self, segment, op_idx, block): + segment._start_idx = op_idx + 1 + self._segments.insert(0, segment) + new_segment = ProgramSegment(block) + new_segment._end_idx = op_idx + 1 + + return new_segment + + def _split_program(self, block): + for op_idx, op in reversed(list(enumerate(block.ops))): + if int(op.attr('op_role')) != int(OpRole.Optimize): + last_backward_op_idx = op_idx + 1 + break + + var2broadcast_time = dict() + segment = ProgramSegment(block) + segment._end_idx = last_backward_op_idx + for op_idx in reversed(range(last_backward_op_idx)): + op = block.ops[op_idx] + assert (int(op.attr('op_role')) != int(OpRole.Optimize)) + if self._sharding_segment_strategy == "segment_broadcast_MB": + if segment._param_mem >= self._broadcast_MB: + segment = self.collect_segment(segment, op_idx, block) + + elif self._sharding_segment_strategy == "segment_anchors": + if int(op.attr('op_role')) == int(OpRole.Backward): + for input_name in op.desc.input_arg_names(): + + # NOTE (JZ-LIANG) naive rule to support amp, if amp change, should modify here accordingly + if self.user_defined_strategy.amp: + if ".cast_fp16@GRAD" not in input_name: + continue + else: + input_name = input_name[:input_name. + find(".cast_fp16@GRAD")] + + if input_name in self._backward_remain_anchors: + segment = self.collect_segment( + segment, op_idx, block) + assert input_name not in self._forward_remain_anchors, "segment anchor [{}] met twice !".format( + input_name) + self._backward_remain_anchors.remove(input_name) + self._forward_remain_anchors.append(input_name) + elif int(op.attr('op_role')) == int(OpRole.Forward): + for output_name in op.desc.output_arg_names(): + if output_name in self._forward_remain_anchors: + segment = self.collect_segment( + segment, op_idx, block) + self._forward_remain_anchors.remove(output_name) + + # find broadcast vars + for input_name in op.desc.input_arg_names(): + if input_name not in self._broadcast_vars: + continue + if input_name in segment._param2broadcast: + # skip broadcast because it reuse the old broadcast var + broadcast_name = segment._param2broadcast[input_name] + if input_name != broadcast_name: + op._rename_input(input_name, broadcast_name) + continue + if self._shard.has_param(input_name): + broadcast_var_name = input_name + else: + broadcast_var_name = unique_name.generate(input_name + + "@BroadCast") + segment._fill_constant_vars.append(broadcast_var_name) + + # (JZ-LIANG) should use Param base name ? + broadcast_var_base_name = input_name + if "subprog" in broadcast_var_base_name: + # remove suffix + broadcast_var_base_name = broadcast_var_base_name[: + broadcast_var_base_name + .find( + ".subprog" + )] + + var2broadcast_time[ + broadcast_var_base_name] = var2broadcast_time.get( + broadcast_var_base_name, 0) + 1 + + segment._param2broadcast[input_name] = broadcast_var_name + segment._broadcast_vars.append( + (broadcast_var_name, self._shard.device(input_name))) + segment._param_mem += get_var_size( + self._main_program.global_block().var(input_name)) + + # find reduce vars + if self.pp_degree > 1 and self.pp_allreduce_in_optimize: + # place pipeline gradient allreduce in optimize + pass + else: + if is_backward_op(op) and \ + OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.all_attrs()[OP_ROLE_VAR_KEY] + if len(op_role_var) != 0: + assert len(op_role_var) % 2 == 0 + for i in range(0, len(op_role_var), 2): + param, reduced_grad = op_role_var[i], op_role_var[i + + + 1] + segment._allreduce_vars.append(reduced_grad) + assert (reduced_grad + not in self._reduced_grads_to_param) + self._reduced_grads_to_param[reduced_grad] = param + + # find cast op + if FP16Utils.is_fp16_cast_op(block, op, self._params): + fp32_param = op.desc.input_arg_names()[0] + fp16_param = op.desc.output_arg_names()[0] + if self._shard.has_param(fp32_param): + segment._cast_ops[fp16_param] = fp32_param + + if segment._param_mem > 0: + segment._start_idx = 0 + self._segments.insert(0, segment) + + if self._sharding_segment_strategy == "segment_anchors": + assert len( + self._forward_remain_anchors) == 0, "remain anchors {}".format( + self._forward_remain_anchors) + assert len( + self._backward_remain_anchors) == 0, "remain anchors {}".format( + self._backward_remain_anchors) + + if self._verbose: + for varname in sorted(var2broadcast_time, + key=var2broadcast_time.get, + reverse=True): + logger.info("Sharding broadcast: [{}] times [{}]".format( + var2broadcast_time[varname], varname)) + for idx_ in range(len(self._segments)): + logger.info("segment [{}] :".format(idx_)) + logger.info("start op: [{}] [{}]".format( + block.ops[self._segments[idx_]._start_idx].desc.type(), + block.ops[self._segments[idx_]. + _start_idx].desc.input_arg_names())) + logger.info("end op: [{}] [{}]".format( + block.ops[self._segments[idx_]._end_idx].desc.type(), + block.ops[ + self._segments[idx_]._end_idx].desc.input_arg_names())) + return + + def _prune_main_program(self, block, shard, rings): + """ + calculate deps from allredce op to optimize op, + remove ops and vars not needed in this worker + + 1. prune regularization (weight decay) + 2. prune cast_fp32_to_fp16; update amp_infine_checking + 3. prune gradient_clip related; update global_norm_sum + 4. prune optimizer op + param + gradient + + """ + weightdecay_helper = WeightDecayHelper() + weightdecay_helper.prune_weight_decay(block, shard) + + # FIXME(wangxi): mp should prune duplicated param_grads + # NOTE (JZ-LIANG) the sync of FoundInfinite should among one entire Model Parallelism + # group. and each Data Parallelism group should have its own sync of FoundInfinite + # amp could use global group for sync + FP16Utils.prune_fp16(block, shard, self._reduced_grads_to_param, rings) + + # clipbyglobalnorm should only use the Model paramllelism group (mp-sharding-pp) + gradientclip_helper = GradientClipHelper(None) + gradientclip_helper.prune_gradient_clip(block, shard, rings) + + # build prog deps + reduced_grads = [] + for idx, op in enumerate(block.ops): + input_names = op.desc.input_arg_names() + output_names = op.desc.output_arg_names() + # FIXME(wangxi): need use grads, pipeline grad is @GRAD@MERGE + if op.type == "c_allreduce_sum" and \ + op.attr('use_model_parallel') is False: + assert (len(output_names) == 1) + output_name = output_names[0] + reduced_grads.append(output_name) + + # prune optimizer state and param + pruned_opti_vars = [] + for var_name in list(block.vars.keys()): + if shard.is_opti_var(var_name) and \ + not shard.has_opt_var(var_name): + pruned_opti_vars.append(var_name) + program_deps = ProgramDeps(block, reduced_grads, pruned_opti_vars) + + # Init + for var_name in program_deps._end_vars: + program_deps._should_removed_var.add(var_name) + + # Prune + for idx, op in reversed(list(enumerate(block.ops))): + if op.type in [ + "c_allreduce_sum", + "c_sync_comm_stream", + "c_calc_comm_stream", + "c_gen_nccl_id", + "c_comm_init", + 'send_v2', + 'recv_v2', + ]: + pass + elif op.type == "conditional_block": + assert (op.desc.has_attr("sub_block")) + subblock_idx = op.desc.attr("sub_block").id + subblock_deps = program_deps.get_sub_block_deps(subblock_idx) + # only prune amp subblock + if subblock_deps is None or not self._is_amp_subblock(op): + continue + # init + reversed_output_vars = [] + for output_name in op.desc.output("Out"): + if output_name in program_deps._should_removed_var: + subblock_deps._should_removed_var.add(output_name) + program_deps.crop_output_var_from_op(idx, output_name) + else: + reversed_output_vars.append(output_name) + # prune + for sub_op_idx, _ in reversed( + list(enumerate(subblock_deps._block.ops))): + if subblock_deps.should_remove_op(sub_op_idx): + subblock_deps.remove_op(sub_op_idx) + reversed_input_vars = [] + for input_name in op.desc.input('Input'): + if input_name not in subblock_deps._should_removed_var: + reversed_input_vars.append(input_name) + else: + program_deps.crop_input_var_from_op(idx, input_name) + op.desc.set_input('Input', reversed_input_vars) + op.desc.set_output('Out', reversed_output_vars) + else: + # if all outputs of this op are in _should_removed_var + # _should_removed_var: opt state not cur shard + if program_deps.should_remove_op(idx): + # NOTE(wangxi): need reserve all param in optimizer_sharding + reserved_vars = self._params if self._optimizer_sharding else None + program_deps.remove_op(idx, reserved_vars) + + # NOTE (JZ-LIANG) revise and unify logic here + # sharding support fp16_allreduce logic + block._sync_with_cpp() + for idx, op in reversed(list(enumerate(block.ops))): + if op.type == 'concat' and is_optimizer_op(op): + # remove inputs that not on this card + reserved_x = [] + for var_name in op.desc.input("X"): + if block.has_var(var_name): reserved_x.append(var_name) + op.desc.set_input('X', reserved_x) + block._sync_with_cpp() + return + + def _add_broadcast_allreduce(self, block): + """ + add broadcast allreduce op + if enable gradient_merge, insert related ops + + if combined with pipeline(grad accumulate), + the grad allreduce should be done in optimize role + """ + if len(self._segments) < 1: + return + # sharding + if self.pp_degree > 1 and self.pp_allreduce_in_optimize: + for idx in range(len(self._segments)): + assert len(self._segments[idx]._allreduce_vars) == 0 + + # NOTE (JZ-LIANG) revise and unify logic here + # fix the _end_idx for segments[-1] if pp is used. + new_end_idx = self._segments[-1]._end_idx + for idx in range(self._segments[-1]._end_idx - 1, + self._segments[-1]._start_idx - 1, -1): + op = block.ops[idx] + if op.type == "fill_constant" or op.type == "sum": + if "MERGED" in op.output_arg_names[0]: new_end_idx = idx + 1 + elif op.type == "cast": + if "@TMP" in op.output_arg_names[0]: new_end_idx = idx + 1 + self._segments[-1]._end_idx = new_end_idx + + if self._segments[-1]._allreduce_vars: + shard_allredue_vars = self._shard.filter_grads( + self._segments[-1]._allreduce_vars) + if self.gradient_merge_mode != "sharding_gm" or self._gradient_merge_acc_step <= 1: + if self.hybrid_dp and self.hybrid_dp_mode == "sharding_hybrid_dp" and len( + shard_allredue_vars) >= 1: + insert_sync_comm_ops(block, self._segments[-1]._end_idx, + self.dp_ring_id, shard_allredue_vars) + insert_allreduce_ops( + block, + self._segments[-1]._end_idx, + self.dp_ring_id, + shard_allredue_vars, + user_defined_strategy=self.user_defined_strategy) + # gradient merge + elif self.gradient_merge_mode == "sharding_gm" and self._gradient_merge_acc_step > 1: + self.create_persistable_gradients_and_insert_merge_ops( + block, self._startup_program.global_block(), + self._segments[-1]._end_idx, shard_allredue_vars, + self._shard) + + insert_sync_comm_ops(block, self._segments[-1]._end_idx, + self.sharding_ring_id, + self._segments[-1]._allreduce_vars) + # allreduce --> reduce + insert_reduce_ops(block, + self._segments[-1]._end_idx, + self.sharding_ring_id, + self._segments[-1]._allreduce_vars, + self._shard, + op_role=OpRole.Backward, + use_calc_stream=False) + + for idx, segment in reversed(list(enumerate(self._segments))): + allreduce_vars = self._segments[ + idx - 1]._allreduce_vars if idx > 0 else [] + broadcast_vars = self._segments[ + idx + + 1]._broadcast_vars if idx < len(self._segments) - 1 else [] + fill_constant_vars = self._segments[ + idx + + 2]._fill_constant_vars if idx < len(self._segments) - 2 else [] + cast_ops = self._segments[ + idx + 2]._cast_ops if idx < len(self._segments) - 2 else {} + + for op_idx in reversed(range(segment._start_idx, segment._end_idx)): + op = block.ops[op_idx] + for input_name in op.desc.input_arg_names(): + if input_name in segment._param2broadcast and \ + input_name != segment._param2broadcast[input_name]: + op._rename_input(input_name, + segment._param2broadcast[input_name]) + + for param_name, broadcast_name in segment._param2broadcast.items(): + if param_name != broadcast_name: + block.create_var( + name=broadcast_name, + shape=self._main_program.global_block().var( + param_name).shape, + dtype=self._main_program.global_block().var( + param_name).dtype, + persistable=False) + + # step1: remove cast ops + block._sync_with_cpp() + segment._end_idx += FP16Utils.remove_cast_op( + block, self._params, segment, 0) + + # step2: add Sync ops + shard_allredue_vars = self._shard.filter_grads(allreduce_vars) + + if self.gradient_merge_mode != "sharding_gm" or self._gradient_merge_acc_step <= 1: + if self.hybrid_dp and self.hybrid_dp_mode == "sharding_hybrid_dp" and len( + shard_allredue_vars) >= 1: + insert_sync_comm_ops(block, segment._end_idx, + self.dp_ring_id, shard_allredue_vars) + + broad_cast_vars = [x[0] for x in broadcast_vars] + if len(broad_cast_vars) > 0: + insert_sync_comm_ops(block, segment._end_idx, + self.sharding_ring_id, + broad_cast_vars) + else: + comm_dep_vars = allreduce_vars + [ + x[0] for x in broadcast_vars + ] + if len(comm_dep_vars) > 0: + insert_sync_comm_ops(block, segment._end_idx, + self.sharding_ring_id, + comm_dep_vars) + # gradient merge + elif self.gradient_merge_mode == "sharding_gm" and self._gradient_merge_acc_step > 1: + broad_cast_vars = [x[0] for x in broadcast_vars] + if len(broad_cast_vars) > 0: + insert_sync_comm_ops(block, segment._end_idx, + self.sharding_ring_id, broad_cast_vars) + + calc_dep_vars = fill_constant_vars + [ + k for k, v in cast_ops.items() + ] + self._segments[idx]._allreduce_vars + + if len(calc_dep_vars) > 0: + insert_sync_calc_op(block, segment._end_idx, + [calc_dep_vars[-1]]) + + # step3: insert `fill_constant` ops + insert_fill_constant_ops(block, segment._end_idx, + fill_constant_vars) + + # step4: add `cast` ops + insert_cast_ops(block, segment._end_idx, cast_ops) + + # step5: add broadcast ops + # gradient merge + if self.gradient_merge_mode == "sharding_gm" and self._gradient_merge_acc_step > 1: + self.create_persistable_gradients_and_insert_merge_ops( + block, self._startup_program.global_block(), + segment._start_idx, shard_allredue_vars, self._shard) + + insert_broadcast_ops(block, segment._start_idx, + self.sharding_ring_id, broadcast_vars) + + # step6: add all_reduce ops + # dp + if self.gradient_merge_mode != "sharding_gm" or self._gradient_merge_acc_step <= 1: + if self.hybrid_dp and self.hybrid_dp_mode == "sharding_hybrid_dp" and len( + shard_allredue_vars) >= 1: + insert_allreduce_ops( + block, + segment._start_idx, + self.dp_ring_id, + shard_allredue_vars, + user_defined_strategy=self.user_defined_strategy) + insert_sync_comm_ops(block, segment._start_idx, + self.sharding_ring_id, allreduce_vars) + # gradient merge + elif self.gradient_merge_mode == "sharding_gm" and self._gradient_merge_acc_step > 1: + insert_sync_comm_ops(block, segment._start_idx, + self.sharding_ring_id, allreduce_vars) + # sharding + # allreduce --> reduce + # TODO temp change + if len(allreduce_vars) > 0: + insert_reduce_ops(block, + segment._start_idx, + self.sharding_ring_id, + allreduce_vars, + self._shard, + op_role=OpRole.Backward, + use_calc_stream=False) + + block._sync_with_cpp() + + if self._segments[0]._broadcast_vars: + broadcast_vars = [x[0] for x in self._segments[0]._broadcast_vars] + insert_sync_comm_ops(block, self._segments[0]._start_idx, + self.sharding_ring_id, broadcast_vars) + insert_broadcast_ops(block, self._segments[0]._start_idx, + self.sharding_ring_id, + self._segments[0]._broadcast_vars) + + fill_constant_vars = [] + for x in self._segments[:2]: + fill_constant_vars += x._fill_constant_vars + + # Join + cast_ops = {} + for x in self._segments[:2]: + for k, v in x._cast_ops.items(): + cast_ops[k] = v + + calc_deps_vars = fill_constant_vars + [k for k, v in cast_ops.items()] + if fill_constant_vars or cast_ops: + insert_sync_calc_op(block, self._segments[0]._start_idx, + [calc_deps_vars[-1]]) + + if fill_constant_vars: + insert_fill_constant_ops(block, self._segments[0]._start_idx, + fill_constant_vars) + + if cast_ops: + insert_cast_ops(block, self._segments[0]._start_idx, cast_ops) + + return + + def _prune_startup_program(self, block, shard): + for idx, op in reversed(list(enumerate(block.ops))): + for output_name in op.desc.output_arg_names(): + if shard.has_var(output_name): + continue + if self._optimizer_sharding and shard.is_param(output_name): + continue + #TODO why do we remove op, when only one var is removed + block._remove_op(idx, sync=False) + break + + for var_name in list(block.vars.keys()): + if shard.has_var(var_name): + continue + if self._optimizer_sharding and shard.is_param(var_name): + continue + block._remove_var(var_name, sync=False) + block._sync_with_cpp() + + def _build_groups(self): + """ + pre-assign ring ids + mp: 0 + sharding: 1 + pure-dp: 2 + global: 3 + pp: 4 + pp-pair: >= 20 + if one parallelism is not enable: -1 + and only support parallelism hierarchy: mp --> sharding --> pp --> dp + """ + # step 1: initialize nccl + self.global_word_size = self.role_maker._worker_num() + self.global_rank = self.role_maker._worker_index() + self.global_endpoints = self.role_maker._get_trainer_endpoints() + self.current_endpoint = self.global_endpoints[self.global_rank] + self._collective_helper = CollectiveHelper(self.role_maker, + nrings=self._nrings_sharding) + assert self.global_word_size % self.mp_degree == 0, \ + "global_word_size: {} should be divisible to the mp_degree: {}".format(self.global_word_size, self.mp_degree) + assert self.global_word_size % self.sharding_degree == 0, \ + "global_word_size: {} should be divisible to the sharding_degree: {}".format(self.global_word_size, self.sharding_degree) + assert self.global_word_size % self.pp_degree == 0, \ + "global_word_size: {} should be divisible to the pp_degree: {}".format(self.global_word_size, self.pp_degree) + assert self.global_word_size % self.dp_degree == 0, \ + "global_word_size: {} should be divisible to the dp_degree: {}".format(self.global_word_size, self.dp_degree) + + # mp group + if self.mp_degree > 1: + self.mp_ring_id = 0 + self.mp_rank = self.global_rank % self.mp_degree + self.mp_group_id = self.global_rank // self.mp_degree + self.mp_group_endpoints = [ + ep for idx, ep in enumerate(self.global_endpoints) + if idx // self.mp_degree == self.mp_group_id + ] + assert self.current_endpoint in self.mp_group_endpoints + assert len( + self.mp_group_endpoints + ) == self.mp_degree, "num of mp worker in group is [{}], but mp group size is [{}]".format( + len(self.mp_group_endpoints), self.mp_degree) + else: + self.mp_degree = 1 + self.mp_ring_id = -1 + self.mp_rank = -1 + self.mp_group_id = -1 + self.mp_group_endpoints = [] + + # sharding + if self.sharding_degree > 1: + self.sharding_ring_id = 1 + self.sharding_rank = (self.global_rank // + self.mp_degree) % self.sharding_degree + self.sharding_group_id = self.global_rank // (self.mp_degree * + self.sharding_degree) + # mp + sharding + ... + if self.mp_degree > 1: + self.sharding_group_endpoints = [ + ep for idx, ep in enumerate(self.global_endpoints) + if (idx // (self.mp_degree * self.sharding_degree)) == self. + sharding_group_id and idx % self.mp_degree == self.mp_rank + ] + # sharding + ... + else: + self.sharding_group_endpoints = [ + ep for idx, ep in enumerate(self.global_endpoints) + if (idx // (self.mp_degree * self.sharding_degree) + ) == self.sharding_group_id + ] + assert self.current_endpoint in self.sharding_group_endpoints + else: + self.sharding_degree = 1 + self.sharding_ring_id = -1 + self.sharding_rank = -1 + self.sharding_group_id = -1 + self.sharding_group_endpoints = [] + + # pp + if self.pp_degree > 1: + self.pp_pair_ring_id = 20 + # pipeline global ring_id set to 4 for sharding0, mp1, dp2, global3 + self.pp_ring_id = 4 + self.pp_rank = self.global_rank // (self.sharding_degree * + self.mp_degree) % self.pp_degree + # (NOTE): Already adjust for (outter-pure) dp + self.pp_group_id = self.global_rank // ( + self.mp_degree * self.sharding_degree * self.pp_degree) + pp_first_stage_idx = self.global_rank % ( + self.sharding_degree * self.mp_degree) + self.pp_group_id * ( + self.mp_degree * self.sharding_degree * self.pp_degree) + pp_stage_offset = self.sharding_degree * self.mp_degree + self.pp_group_endpoints = [] + for i in range(self.pp_degree): + self.pp_group_endpoints.append( + self.global_endpoints[pp_first_stage_idx + + pp_stage_offset * i]) + assert self.current_endpoint in self.pp_group_endpoints + else: + self.pp_ring_id = -1 + self.pp_degree = 1 + self.pp_pair_ring_id = -1 + self.pp_rank = -1 + self.pp_group_id = -1 + self.pp_group_endpoints = [] + + # outter-pure-dp group + # NOTE (JZ-LIANG) support outter-pure-dp to scale the throughput in 3D parallelism + # e.g. mp-sharding-pp-dp + # sharding-hybrid-dp as one senario of outter-pure-dp + local_pp_degree = self.pp_degree + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None): + assert self.pp_degree == 2, ("For manually set pipeline, only " + "pp_degree = 2 is supported.") + assert self.global_word_size == self.mp_degree * self.sharding_degree * self.dp_degree, \ + "global work size [{}], mp_degree [{}], sharding_degree [{}], dp_degree [{}].".format( + self.global_word_size, self.mp_degree, self.sharding_degree, self.dp_degree) + local_pp_degree = 1 + else: + assert self.global_word_size == self.mp_degree * self.sharding_degree * self.pp_degree * self.dp_degree, "mp_degree: [{}], sharding_degree: [{}], pp_degree: [{}], dp_degree: [{}]; BUT global nrank: [{}]".format( + self.mp_degree, self.sharding_degree, self.pp_degree, + self.dp_degree, self.global_word_size) + + if self.dp_degree > 1: + self.dp_ring_id = 2 + self.dp_rank = self.global_rank // ( + self.sharding_degree * self.mp_degree * local_pp_degree) + dp_first_rank_idx = self.global_rank % ( + self.sharding_degree * self.mp_degree * local_pp_degree) + dp_offset = (self.sharding_degree * self.mp_degree * + local_pp_degree) + self.dp_group_endpoints = [] + for i in range(self.dp_degree): + self.dp_group_endpoints.append( + self.global_endpoints[dp_first_rank_idx + dp_offset * i]) + assert self.current_endpoint in self.dp_group_endpoints + logger.info("Hybrid DP mode turn on !") + else: + self.dp_ring_id = -1 + self.dp_rank = -1 + self.dp_group_endpoints = [] + + # global group + # use for gen_nccl_comm_sync, amp check nan inf, clip by global norm + # NOTE (JZ-LIANG) when use global ring for calc global norm and dp_degree > 1, the allreduce result should be devided by dp_degree + self.global_ring_id = 3 + + logger.info("global word size: {}".format(self.global_word_size)) + logger.info("global rank: {}".format(self.global_rank)) + logger.info("global endpoints: {}".format(self.global_endpoints)) + logger.info("global ring id: {}".format(self.global_ring_id)) + logger.info("#####" * 6) + + logger.info("mp group size: {}".format(self.mp_degree)) + logger.info("mp rank: {}".format(self.mp_rank)) + logger.info("mp group id: {}".format(self.mp_group_id)) + logger.info("mp group endpoints: {}".format(self.mp_group_endpoints)) + logger.info("mp ring id: {}".format(self.mp_ring_id)) + logger.info("#####" * 6) + + logger.info("sharding group size: {}".format(self.sharding_degree)) + logger.info("sharding rank: {}".format(self.sharding_rank)) + logger.info("sharding group id: {}".format(self.sharding_group_id)) + logger.info("sharding group endpoints: {}".format( + self.sharding_group_endpoints)) + logger.info("sharding ring id: {}".format(self.sharding_ring_id)) + logger.info("#####" * 6) + + logger.info("pp group size: {}".format(self.pp_degree)) + logger.info("pp rank: {}".format(self.pp_rank)) + logger.info("pp group id: {}".format(self.pp_group_id)) + logger.info("pp group endpoints: {}".format(self.pp_group_endpoints)) + logger.info("pp ring id: {}".format(self.pp_ring_id)) + logger.info("#####" * 6) + + logger.info("pure dp group size: {}".format(self.dp_degree)) + logger.info("pure dp rank: {}".format(self.dp_rank)) + logger.info("pure dp group endpoints: {}".format( + self.dp_group_endpoints)) + logger.info("pure dp ring id: {}".format(self.dp_ring_id)) + logger.info("#####" * 6) + + return + + def _recreate_not_persist_param_as_var(self): + + def recreate_not_persist_param_as_var(program): + block = program.global_block() + params = block.all_parameters() + for param in params: + if param.persistable: + continue + + name = param.name + shape = param.shape + dtype = param.dtype + type = param.type + lod_level = param.lod_level + stop_gradient = param.stop_gradient + trainable = param.trainable + optimize_attr = param.optimize_attr + regularizer = param.regularizer + have_dist_attr = False + is_distributed = False + if hasattr(param, 'is_distributed'): + have_dist_attr = True + is_distributed = param.is_distributed + + block._remove_var(name, sync=False) + var = block.create_var(name=name, + shape=shape, + dtype=dtype, + type=type, + lod_level=lod_level, + stop_gradient=stop_gradient, + trainable=trainable, + persistable=False) + if have_dist_attr: + var.is_distributed = is_distributed + + block._sync_with_cpp() + + recreate_not_persist_param_as_var(self._startup_program) + recreate_not_persist_param_as_var(self._main_program) + + def _initialization_broadcast(self): + """ + this funtion is to ensure the initialization between dp group to be + identical when hybrid-dp is used, and the initialization of + not distributed param between mp group to be identical. + """ + if self.dp_degree <= 1 and self.mp_degree <= 1: + return + + startup_block = self._startup_program.global_block() + + params = startup_block.all_parameters() + params_name = [] + not_dist_param_name = set() + + for param in params: + params_name.append(param.name) + if not hasattr(param, 'is_distributed') or not param.is_distributed: + not_dist_param_name.add(param.name) + + # offload and optimize_cast will insert broadcast op + broadcast_params = set() + for op in startup_block.ops: + if op.type == 'c_broadcast': + broadcast_params.add(op.desc.output_arg_names()[0]) + + for param in params_name: + if param in broadcast_params: continue + + rings = [] + # need sync not distributed param in mp group + if self.mp_degree > 1 and param in not_dist_param_name: + rings.append(self.mp_ring_id) + if self.dp_degree > 1: + rings.append(self.dp_ring_id) + + for ring in rings: + startup_block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring, + 'root': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Forward + }) + + startup_block._sync_with_cpp() + + # sharding gradient merge + def create_persistable_gradients_and_insert_merge_ops( + self, main_block, startup_block, insert_idx, grad_names, shard): + + for grad_name in grad_names: + assert get_grad_device( + grad_name, shard + ) == shard.worker_idx, "try to merge gradient not belong to current shard: [{}]".format( + grad_name) + persistable_grad_name = grad_name + '@GradiantMerge' + assert grad_name not in self._grad2merged_grad, "grad [{}] already in grad2merged_grad, maybe you meet sharing weight case !".format( + grad_name) + self._grad2merged_grad[grad_name] = persistable_grad_name + grad_var = main_block.var(grad_name) + # create var + gradient_merge_var = main_block.create_var( + name=persistable_grad_name, + shape=grad_var.shape, + dtype=grad_var.dtype, + persistable=True) + startup_gradient_merge_var = startup_block.create_var( + name=persistable_grad_name, + shape=grad_var.shape, + dtype=grad_var.dtype, + persistable=True) + + # merge gradient + main_block._insert_op_without_sync( + insert_idx, + type="elementwise_add", + inputs={ + 'X': grad_name, + 'Y': gradient_merge_var + }, + outputs={'Out': gradient_merge_var}, + attrs={ + 'axis': -1, + 'use_mkldnn': False, + OP_ROLE_KEY: OpRole.Backward + }) + + # startup initialization + startup_block.append_op(type="fill_constant", + outputs={"Out": startup_gradient_merge_var}, + attrs={ + "shape": grad_var.shape, + "dtype": grad_var.dtype, + "value": float(0), + }) + + main_block._sync_with_cpp() + startup_block._sync_with_cpp() + + def _create_gm_cond(self, main_block): + # Add const var + acc_step_var = layers.create_global_var( + name="gradient_merge_acc_step", + shape=[1], + value=int(self._gradient_merge_acc_step), + dtype='int32', + persistable=True, + force_cpu=True) + + zero_var = layers.create_global_var(name="gradient_merge_zero", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + + # Add step var & cond var + current_step_var = layers.create_global_var( + name="gradient_merge_current_step", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + + cond_var = main_block.create_var(name="gradient_merge_cond", + shape=[1], + dtype='bool') + + with device_guard("cpu"): + # step_var = (step_var + 1) % k_step + main_block.append_op(type='increment', + inputs={'X': [current_step_var]}, + outputs={'Out': [current_step_var]}, + attrs={ + 'step': float(1), + OP_ROLE_KEY: OpRole.Optimize + }) + + main_block.append_op(type='elementwise_mod', + inputs={ + 'X': current_step_var, + 'Y': acc_step_var + }, + outputs={'Out': current_step_var}, + attrs={ + 'axis': -1, + OP_ROLE_KEY: OpRole.Optimize, + 'use_mkldnn': False + }) + + # cond_var = (step_var == 0) + main_block.append_op(type='equal', + inputs={ + 'X': current_step_var, + 'Y': zero_var + }, + outputs={'Out': cond_var}, + attrs={OP_ROLE_KEY: OpRole.Optimize}) + # paddle.static.Print(current_step_var, message="in FWBW last conditional") + return cond_var + + def _true_apply_gradient(self): + """ + allreduce grad@gradientmerge in dp group + grad@gradientmerge / acc_step + re-create all optimize ops of origin main block and rename them + cast(backward) + amp + clip + opt + # fill constant grad@gradientmerge + + """ + # current conditional block + main_block = self._main_program.global_block() + cur_block_idx = self._main_program.current_block_idx + cur_block = self._main_program.current_block() + self.cond_block = self._main_program.current_block() + + # cur_block's forward_block & backward_block is itself + cur_block._set_forward_block_idx(cur_block_idx) + + # allreduce grad@gradientmerge + if self.hybrid_dp: + assert self.dp_ring_id >= 0, "dp_ring_id should larger than 0 when in sharding&DP mode" + for grad, merged_grad in self._grad2merged_grad.items(): + merged_grad_var = main_block.var(merged_grad) + cur_block.append_op(type='c_allreduce_sum', + inputs={'X': merged_grad_var}, + outputs={'Out': merged_grad_var}, + attrs={ + 'ring_id': self.dp_ring_id, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize + }) + + # grad@gradientmerge / acc_step + for grad, merged_grad in self._grad2merged_grad.items(): + # grad /= k_steps + merged_grad_var = main_block.var(merged_grad) + cur_block.append_op(type='scale', + inputs={'X': merged_grad_var}, + outputs={'Out': merged_grad_var}, + attrs={ + 'scale': + 1.0 / float(self._gradient_merge_acc_step), + 'bias': + 0.0, + 'bias_after_scale': + False, + OP_ROLE_KEY: + OpRole.Optimize + }) + + # re-create optimize ops + already_moved_var_names = [] + for op_desc in self.original_optimize_ops_desc: + new_op_desc = cur_block.desc.append_op() + new_op_desc.copy_from(op_desc) + + for input_name in new_op_desc.input_arg_names(): + if input_name in self._grad2merged_grad: + new_op_desc._rename_input( + input_name, self._grad2merged_grad[input_name]) + + for output_name in new_op_desc.output_arg_names(): + if output_name in self._grad2merged_grad: + new_op_desc._rename_output( + output_name, self._grad2merged_grad[output_name]) + + # move non temp optimize vars from block0 to cond block + if output_name not in already_moved_var_names and output_name not in self._grad2merged_grad.keys( + ): + var_ = self._main_program.global_block().var(output_name) + if not var_.persistable: + # move + name_ = var_.name + shape_ = var_.shape + type_ = var_.dtype + self._main_program.global_block()._remove_var( + var_.name, sync=False) + self.cond_block.create_var(name=name_, + shape=shape_, + dtype=type_, + persistable=False) + already_moved_var_names.append(name_) + + self._main_program.global_block()._sync_with_cpp() + cur_block._sync_with_cpp() + + # fill zero to grad@gradientmerge + for grad, merged_grad in self._grad2merged_grad.items(): + merged_grad_var = main_block.var(merged_grad) + cur_block.append_op(type='fill_constant', + outputs={'Out': merged_grad_var}, + attrs={ + "shape": merged_grad_var.shape, + "dtype": merged_grad_var.dtype, + "value": float(0), + OP_ROLE_KEY: OpRole.Optimize + }) + + # lr_var = main_block.var("gradient_merge_current_step") + # paddle.static.Print(lr_var, message="in OPTIMIZE last conditional") + + def _sharding_gradient_merge(self): + """ + copy all optimize ops in origin main block + remove all optimize ops in origin main block + create cond block + + """ + if self.gradient_merge_mode != "sharding_gm" or self._gradient_merge_acc_step <= 1: + return + + main_block = self._main_program.global_block() + # copy original optimize ops to temp ops desc list + # remove them from block 0 + tmp_copy_block = self._main_program._create_block() + + self.original_optimize_ops_desc = [] + for op_idx, op in reversed(list(enumerate(main_block.ops))): + if int(op.attr('op_role')) != int(OpRole.Optimize): + continue + else: + tmp_op_desc = tmp_copy_block.desc.append_op() + tmp_op_desc.copy_from(op.desc) + self.original_optimize_ops_desc.append(tmp_op_desc) + main_block._remove_op(op_idx, sync=False) + tmp_copy_block._sync_with_cpp() + self.original_optimize_ops_desc = list( + reversed(self.original_optimize_ops_desc)) + + # back to block 0 + self._main_program._rollback() + + # create cond vars and ops at the end of block 0 + cond = self._create_gm_cond(main_block) + + # create cond block + cond_block = self._main_program._create_block() + self._true_apply_gradient() + + # back to block 0 + self._main_program._rollback() + + # cond op + step_scope = self._main_program.global_block().create_var( + type=core.VarDesc.VarType.STEP_SCOPES) + conditional_block_op = self._main_program.global_block().append_op( + type='conditional_block', + inputs={ + 'Cond': cond, + 'Input': [], + }, + outputs={ + 'Out': [], + 'Scope': [step_scope] + }, + attrs={ + 'sub_block': cond_block, + 'is_scalar_condition': True, + }) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/tensor_parallel_optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/tensor_parallel_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c628964db35dbdfb09288ba6352437b44c9a6b64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_optimizers/tensor_parallel_optimizer.py @@ -0,0 +1,241 @@ +# Copyright (c) 2021 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 + +from __future__ import print_function +from __future__ import division + +import paddle.fluid as fluid +from paddle.fluid import core, unique_name +from .meta_optimizer_base import MetaOptimizerBase +from .common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY, CollectiveHelper, is_update_op, is_loss_grad_op, is_backward_op, is_optimizer_op + +__all__ = [] + + +class TensorParallelOptimizer(MetaOptimizerBase): + + def __init__(self, optimizer): + super(TensorParallelOptimizer, self).__init__(optimizer) + self.inner_opt = optimizer + self.meta_optimizers_white_list = [ + "RecomputeOptimizer", + "AMPOptimizer", + "LarsOptimizer", + "LambOptimizer", + ] + self.meta_optimizers_black_list = [ + "GraphExecutionOptimizer", + ] + self.mp_ring_id = 0 + self.global_ring_id = 1 + self.dp_ring_id = 2 + + def _set_basic_info(self, loss, role_maker, user_defined_optimizer, + user_defined_strategy): + super(TensorParallelOptimizer, + self)._set_basic_info(loss, role_maker, user_defined_optimizer, + user_defined_strategy) + self.mp_degree = user_defined_strategy.tensor_parallel_configs[ + 'tensor_parallel_degree'] + + def _can_apply(self): + if not self.role_maker._is_collective: + return False + + if self.user_defined_strategy.tensor_parallel == True: + return True + return False + + def _disable_strategy(self, dist_strategy): + dist_strategy.tensor_parallel = False + dist_strategy.tensor_parallel_configs = {} + + def _enable_strategy(self, dist_strategy, context): + dist_strategy.tensor_parallel = True + dist_strategy.tensor_parallel_configs = { + "tensor_parallel_degree": 1, + } + + def _broadcast_params(self, ring_id, mp_mode): + block = self.startup_program.global_block() + param = None + for param in block.iter_parameters(): + if param.is_distributed and mp_mode: + continue + + block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': 0, + OP_ROLE_KEY: OpRole.Forward + }) + + if not param: return # no parameter on this device + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Forward + }) + + def _get_process_group_info(self): + # global ring info + self.global_endpoints = self.endpoints + self.global_rank = self.rank + self.global_nranks = self.nranks + + # model parallel ring info + self.mp_rank = self.rank % self.mp_degree + self.mp_nranks = self.mp_degree + mp_group = self.rank // self.mp_degree + self.mp_endpoints = [ + self.endpoints[i] for i in range(self.global_nranks) + if i // self.mp_degree == mp_group + ] + + # data parallel ring info + if self.nranks > self.mp_degree: + self.dp_rank = self.rank // self.mp_degree + self.dp_nranks = self.nranks // self.mp_degree + start_index = self.rank % self.mp_degree + self.dp_endpoints = [ + self.endpoints[start_index + i * self.mp_degree] + for i in range(self.dp_nranks) + ] + + def _init_process_group(self): + self._get_process_group_info() + collective_helper = CollectiveHelper(self.role_maker, wait_port=False) + + # Create global ring for all gpus + collective_helper._init_communicator(self.startup_program, + self.current_endpoint, + self.global_endpoints, + self.global_rank, + self.global_ring_id, True, + self.global_ring_id, True) + + # Create model parallel ring for all gpus + collective_helper._init_communicator(self.startup_program, + self.current_endpoint, + self.mp_endpoints, self.mp_rank, + self.mp_ring_id, True, + self.global_ring_id, True) + self._broadcast_params(self.mp_ring_id, mp_mode=True) + + # Create dp rings + if self.nranks > self.mp_degree: + collective_helper._init_communicator( + self.startup_program, self.current_endpoint, self.dp_endpoints, + self.dp_rank, self.dp_ring_id, True, self.global_ring_id, True) + self._broadcast_params(self.dp_ring_id, mp_mode=False) + + def minimize_impl(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + self.endpoints = self.role_maker._get_trainer_endpoints() + self.current_endpoint = self.endpoints[self.role_maker._worker_index()] + self.startup_program = startup_program + if startup_program is None: + self.startup_program = fluid.default_startup_program() + + optimize_ops, params_grads = self.inner_opt.minimize( + loss, self.startup_program, parameter_list, no_grad_set) + + self.main_program = loss.block.program + self.nranks = len(self.endpoints) + self.rank = self.role_maker._worker_index() + + self._init_process_group() + + assert self.nranks % self.mp_degree == 0 + + if self.nranks > self.mp_degree: + # data parallelism + dp_degree = self.nranks // self.mp_degree + self._transpile_main_program(loss, dp_degree) + return optimize_ops, params_grads + + def _transpile_main_program(self, loss, dp_degree): + self._insert_loss_grad_ops(loss, dp_degree) + self._insert_allreduce_ops(loss, self.dp_ring_id) + + def _insert_loss_grad_ops(self, loss, dp_degree): + """ + In order to keep the learning rate consistent in different numbers of + training workers, we scale the loss grad by the number of workers + """ + block = loss.block + for idx, op in reversed(list(enumerate(block.ops))): + if is_loss_grad_op(op): + loss_grad_var = block.vars[op.output_arg_names[0]] + block._insert_op(idx + 1, + type='scale', + inputs={'X': loss_grad_var}, + outputs={'Out': loss_grad_var}, + attrs={ + 'scale': 1.0 / dp_degree, + OP_ROLE_KEY: OpRole.Backward + }) + break + + def _insert_allreduce_ops(self, loss, ring_id): + block = loss.block + grad = None + for idx, op in reversed(list(enumerate(block.ops))): + if is_backward_op(op) and OP_ROLE_VAR_KEY in op.attr_names: + op_role_var = op.attr(OP_ROLE_VAR_KEY) + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + offset = idx + for i in range(0, len(op_role_var), 2): + param = block.vars[op_role_var[i]] + grad = block.vars[op_role_var[i + 1]] + if offset == idx: + offset += 1 + block._insert_op(offset, + type='c_sync_calc_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={OP_ROLE_KEY: OpRole.Backward}) + offset += 1 + + block._insert_op(offset, + type='c_allreduce_sum', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward + }) + + if grad is None: + return + + for idx, op in list(enumerate(block.ops)): + if is_optimizer_op(op): + block._insert_op(idx, + type='c_sync_comm_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + OP_ROLE_KEY: OpRole.Backward + }) + break diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f507e2f636884b3b6ea7fabcef0c328631ca4bbc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/__init__.py @@ -0,0 +1,30 @@ +# Copyright (c) 2021 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. + +from .parallel_layers import VocabParallelEmbedding # noqa: F401 +from .parallel_layers import ColumnParallelLinear # noqa: F401 +from .parallel_layers import RowParallelLinear # noqa: F401 +from .parallel_layers import ParallelCrossEntropy # noqa: F401 +from .parallel_layers import LayerDesc # noqa: F401 +from .parallel_layers import SharedLayerDesc # noqa: F401 +from .parallel_layers import PipelineLayer # noqa: F401 +from .parallel_layers import RNGStatesTracker # noqa: F401 +from .parallel_layers import model_parallel_random_seed # noqa: F401 +from .parallel_layers import get_rng_state_tracker # noqa: F401 +from .tensor_parallel import TensorParallel # noqa: F401 +from .pipeline_parallel import PipelineParallel # noqa: F401 +from .pipeline_parallel import PipelineParallelWithInterleave # noqa: F401 +from .sharding_parallel import ShardingParallel # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/meta_parallel_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/meta_parallel_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b8660bd88d40ac35a46f4341dfecb211d2f0ad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/meta_parallel_base.py @@ -0,0 +1,46 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.dygraph.layers import Layer + +__all__ = [] + + +class MetaParallelBase(Layer): + + def __init__(self, layers, hcg, strategy): + super(MetaParallelBase, + self).__init__(layers.full_name() + "_meta_parallel_base") + self._layers = layers + self._hcg = hcg + self._strategy = strategy + self._prepare_for_model() + + def _prepare_for_model(self): + pass + + def _pre_forward(self, *inputs, **kwargs): + pass + + def forward(self, *inputs, **kwargs): + self._pre_forward(*inputs, **kwargs) + + output = self._layers(*inputs, **kwargs) + + self._post_forward(output) + + return output + + def _post_forward(self, output): + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9778574907373d16512c0a12452dbb828402db --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/__init__.py @@ -0,0 +1,26 @@ +# Copyright (c) 2021 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. + +from .mp_layers import VocabParallelEmbedding # noqa: F401 +from .mp_layers import ColumnParallelLinear # noqa: F401 +from .mp_layers import RowParallelLinear # noqa: F401 +from .mp_layers import ParallelCrossEntropy # noqa: F401 +from .pp_layers import LayerDesc # noqa: F401 +from .pp_layers import SharedLayerDesc # noqa: F401 +from .pp_layers import PipelineLayer # noqa: F401 +from .random import RNGStatesTracker # noqa: F401 +from .random import model_parallel_random_seed # noqa: F401 +from .random import get_rng_state_tracker # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/mp_layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/mp_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..66a1c87756220eda7e724a2f4018e77bba12e589 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/mp_layers.py @@ -0,0 +1,20 @@ +# Copyright (c) 2022 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. + +from ...layers.mpu.mp_layers import VocabParallelEmbedding # noqa: F401 +from ...layers.mpu.mp_layers import ColumnParallelLinear # noqa: F401 +from ...layers.mpu.mp_layers import RowParallelLinear # noqa: F401 +from ...layers.mpu.mp_layers import ParallelCrossEntropy # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/pp_layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/pp_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..0e14d141238cafc4a1d678c4f8702dbc9e3c1bea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/pp_layers.py @@ -0,0 +1,836 @@ +# Copyright (c) 2021 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. + +# The file has been adapted from the file: +# https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/runtime/pipe/module.py +# Git commit hash: fafc827d643b3eed611e282d909025f16be36601 +# We retain the following license from the original files: +# MIT License + +# Copyright (c) Microsoft Corporation. + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE + +import math +import re +import glob +import os +import numpy as np +import random +from functools import partial + +import paddle +from paddle.fluid.dygraph.layers import Layer +from ...utils.log_util import logger, layer_to_str +from paddle.distributed import fleet +from paddle.fluid.framework import in_dygraph_mode +from paddle.incubate.distributed.fleet import recompute_hybrid + +__all__ = [] + + +class LayerDesc(object): + def __init__(self, layer_func, *inputs, **kwargs): + self.layer_func = layer_func + self.inputs = inputs + self.kwargs = kwargs + + if not issubclass(layer_func, Layer): + raise TypeError( + "The input(layer_func) should be a derived class of Layer." + ) + + def build_layer(self): + return self.layer_func(*self.inputs, **self.kwargs) + + def __repr__(self): + return layer_to_str( + self.layer_func.__name__, *self.inputs, **self.kwargs + ) + + +class SharedLayerDesc(LayerDesc): + def __init__( + self, + key, + layer_func, + forward_func=None, + shared_weight_attr='weight', + *inputs, + **kwargs + ): + super(SharedLayerDesc, self).__init__(layer_func, *inputs, **kwargs) + self.layer_name = key + self.forward_func = forward_func + self.shared_weight_attr = shared_weight_attr + + +class SegmentLayers(object): + def __init__( + self, + layers_desc, + num_parts, + method="uniform", + num_virtual_pipeline_stage=None, + ): + self._layers_desc = layers_desc + self.method = method + self.num_parts = num_parts + self.num_items = len(layers_desc) + self.num_virtual_pipeline_stage = num_virtual_pipeline_stage + if self.num_virtual_pipeline_stage is not None: + self.total_parts = num_parts * self.num_virtual_pipeline_stage + assert ( + self.num_items >= self.num_parts + ), "layer number should be greater than number of segments" + + def do_segment(self): + if self.method == "uniform": + return self.uniform(self.num_items, self.num_parts) + + elif self.method.startswith('layer:'): + # Divide equally according to the specified layer + layername = self.method.split(':')[1] + weights = [0] * len(self._layers_desc) + weight_idxs = self._gen_layer_weight(layername) + for idx in weight_idxs: + weights[idx] = 1 + + actual_num_parts = ( + self.num_parts + if self.num_virtual_pipeline_stage is None + else self.total_parts + ) + + assert ( + sum(weights) % actual_num_parts == 0 + ), "number of layers ({}) should be divided by part number({})".format( + sum(weights), actual_num_parts + ) + part_size = sum(weights) // actual_num_parts + result = [0 for _ in range(actual_num_parts + 1)] + + memory_counter = 0 + result_idx = 1 + for idx, weight in enumerate(weights): + memory_counter += weight + if memory_counter == part_size: + result[result_idx] = idx + 1 + result_idx += 1 + memory_counter = 0 + result[actual_num_parts] = len(weights) + return result + + def _gen_layer_weight(self, layername): + weight_idxs = [] + regex = re.compile(layername, re.IGNORECASE) + for idx, layer in enumerate(self._layers_desc): + name = None + if isinstance(layer, Layer): + name = layer.__class__.__name__ + elif isinstance(layer, LayerDesc): + name = layer.layer_func.__name__ + else: + try: + name = layer.__name__ + except AttributeError: + # it is not error + continue + if regex.search(name): + weight_idxs.append(idx) + + assert ( + len(weight_idxs) > 0 + ), "weight_idxs' length should be greater than 0" + return weight_idxs + + def uniform(self, num_items, num_parts): + result = [0 for _ in range(num_parts + 1)] + part_size = math.floor(num_items / num_parts) + extra_layers = num_items % num_parts + for i in range(1, num_parts): + offset = 1 if i > (num_parts - extra_layers) else 0 + result[i] = int(min(result[i - 1] + part_size + offset, num_items)) + result[num_parts] = num_items + return result + + +class PipelineLayerChunk(Layer): + def __init__(self): + super(PipelineLayerChunk, self).__init__() + self.run_function = [] + + def append(self, sublayer): + # This method is used to unify codes in _build_layer_impl. + # For 1f1b scheduler, it will call append method of a List. + # For interleave scheduler, it will call append method of this class. + if isinstance(sublayer, Layer): + self.add_sublayer(str(len(self.run_function)), sublayer) + self.run_function.append(sublayer) + + def get_run_function(self): + return self.run_function + + def forward(self, *args, **kwargs): + # Users shouldn't call PipelineLayerChunk directly, since all logics relating with recompute + # are in the forward function of PipelineLayer. Any directly call will bring unexpected + # behavior under recompute circumstance. + raise PermissionError( + "The forward function of PipelineLayerChunk cannot be called directly. " + "Please call forward function of PipelineLayer." + ) + + +class PipelineLayer(Layer): + """PipelineLayer + Args: + layers(Iterable): A sequence of layers description to define the structure for pipeline. + num_stages(int, optional): pp degree, if not specified, 'topology' parameter must be given. + topology(CommunicateTopology, optional): topo of hybrid parallel, if it is None, 'num_stages' parameters must be given. + loss_fn(callable, optional): Loss function. + seg_method(str, optional): the method of splitting pp layer, default 'uniform', or use specific layer to split, method's name must be start with 'layer:'. + recompute_interval(int, optional): the number of layers to be used recompute, the value of 0 represents no recompute. default 0. + recompute_ctx(dict,optional): the context of recompute, when 'recompute_interval' > 0, the context must be given. + num_virtual_pipeline_stages(int, optional): the num of virtual pipeline stages for interleave pp. + Examples: + .. code-block:: python + import paddle.nn as nn + from paddle.distributed import fleet + from paddle.fluid.dygraph.layers import Layer + import paddle.nn.functional as F + from paddle.distributed.fleet.meta_parallel import LayerDesc, PipelineLayer + + pipeline_parallel_size = 2 + strategy = fleet.DistributedStrategy() + strategy.hybrid_configs = { + "dp_degree": 1, + "mp_degree": 1, + "pp_degree": pipeline_parallel_size + } + strategy.pipeline_configs = { + "accumulate_steps": 4, + "micro_batch_size": 2 + } + + fleet.init(is_collective=True, strategy=strategy) + + hcg = fleet.get_hybrid_communicate_group() + + class ReshapeHelp(Layer): + def __init__(self, shape): + super(ReshapeHelp, self).__init__() + self.shape = shape + + def forward(self, x): + return x.reshape(shape=self.shape) + + class AlexNetPipeDesc(PipelineLayer): + def __init__(self, num_classes=10, **kwargs): + self.num_classes = num_classes + decs = [ + LayerDesc( + nn.Conv2D, 1, 64, kernel_size=11, stride=4, padding=5), + LayerDesc(nn.ReLU), + LayerDesc( + nn.MaxPool2D, kernel_size=2, stride=2), + LayerDesc( + nn.Conv2D, 64, 192, kernel_size=5, padding=2), + F.relu, + LayerDesc( + nn.MaxPool2D, kernel_size=2, stride=2), + LayerDesc( + nn.Conv2D, 192, 384, kernel_size=3, padding=1), + F.relu, + LayerDesc( + nn.Conv2D, 384, 256, kernel_size=3, padding=1), + F.relu, + LayerDesc( + nn.Conv2D, 256, 256, kernel_size=3, padding=1), + F.relu, + LayerDesc( + nn.MaxPool2D, kernel_size=2, stride=2), + LayerDesc( + ReshapeHelp, shape=[-1, 256]), + LayerDesc(nn.Linear, 256, self.num_classes), # classifier + ] + super(AlexNetPipeDesc, self).__init__( + layers=decs, loss_fn=nn.CrossEntropyLoss(), **kwargs) + + model = AlexNetPipeDesc(num_stages=pipeline_parallel_size, topology=hcg._topo) + + """ + + def __init__( + self, + layers, + num_stages=None, + topology=None, + loss_fn=None, + seg_method="uniform", + recompute_interval=0, + recompute_ctx=None, + num_virtual_pipeline_stages=None, + ): + super(PipelineLayer, self).__init__() + if num_stages is None and topology is None: + raise ValueError("should provide num_stages or topology") + + if num_virtual_pipeline_stages: + assert isinstance( + num_virtual_pipeline_stages, int + ), "virtual_pipeline_stage should be None or an int" + if num_virtual_pipeline_stages > 1: + logger.info( + "set num_virtual_pipeline_stages > 1 means using interleave scheduler instead of 1f1b scheduler" + ) + assert isinstance( + seg_method, str + ), "seg_method should be a str for interleave scheduler" + assert seg_method.startswith( + 'layer:' + ), "seg_method shoud be start with layer: for interleave scheduler" + + self._num_virtual_pipeline_stages = ( + 1 + if num_virtual_pipeline_stages is None + else num_virtual_pipeline_stages + ) + + # lazy import + import paddle.distributed as dist + from paddle.distributed import fleet + + self.device_id = dist.ParallelEnv().device_id + self.layers = layers + self._loss_fn = loss_fn + self._topo = topology + self._recompute_interval = recompute_interval + self.recompute_ctx = recompute_ctx + + if recompute_interval > 0: + assert ( + recompute_ctx is not None + ), "recompute_ctx must be not None for recompute." + + offload = recompute_ctx.get('offload', False) + partition = recompute_ctx.get('partition', False) + logger.info( + "Start Recompute for PipeLineParallel. recompute_offload: {}, recompute_partition: {}".format( + offload, partition + ) + ) + + world_size = dist.get_world_size() + self.global_rank = dist.get_rank() + + if self._topo: + self._stage_id = self._topo.get_coord(self.global_rank).pipe + self._num_stages = self._topo.get_dim_size("pipe") + if num_stages: + assert ( + self._num_stages == num_stages + ), "num_stages should be equal to be %d" % (self._num_stages) + else: + # construct default topology + if world_size % num_stages != 0: + raise ValueError( + "should provide correct num_stages({}) " + "which can be divided by world_size({})".format( + num_stages, world_size + ) + ) + dp_num = world_size // num_stages + self._topo = fleet.CommunicateTopology( + ["data", "pipe", "model"], [dp_num, num_stages, 1] + ) + self._stage_id = self._topo.get_coord(self.global_rank).pipe + self._num_stages = self._topo.get_dim_size("pipe") + + self._total_stages_with_virtual_stages = ( + self._num_stages * self._num_virtual_pipeline_stages + ) + + # initialize segment + self._layers_desc = list(self.layers) + self._num_layers = len(self._layers_desc) + self.shared_layers = paddle.nn.LayerDict() + self.shared_weight_attrs = {} + + if self._num_virtual_pipeline_stages > 1: + # interleaving pipeline segmentation + self._start_poss = [] + self._end_poss = [] + self._segment_network_for_interleave(seg_method) + # The _model_chunks is a list of PipelineLayerChunk, + # while PipelineLayerChunk is a list of Layers relating with one model chunk. + # Therefore, the _model_chunks is something like 'list of a list of layers'. + self._model_chunks = [] + self._build_layer_with_interleave() + else: + # 1f1b pipeline segmentation + self._start_pos = 0 + self._end_pos = self._num_layers - 1 + self._segment_network(seg_method) + # construct layer + self.run_function = [] + self._build_layer() + + self.shared_comm = self._construct_shared_comm() + self._synchronize_shared_weights() + + def get_stage_from_index(self, layer_idx): + assert 0 <= layer_idx < self._num_layers, "layer_idx is out of bound" + for virtual_pp_rank in range(self._num_virtual_pipeline_stages): + # Mapping the virtual pipeline stage to the real pipeline stage. + # start_idx marks the start of a new virtual pp stage. + start_idx = virtual_pp_rank * self._num_stages + for stage in range(self._num_stages): + # stage mark the real pp stage + if ( + self.segment_parts[start_idx + stage] + <= layer_idx + < self.segment_parts[start_idx + stage + 1] + ): + return stage + + def get_num_virtual_stages(self): + return self._num_virtual_pipeline_stages + + def get_model_chunks(self): + return ( + None + if self._num_virtual_pipeline_stages == 1 + else self._model_chunks + ) + + def _construct_shared_comm(self): + shared_comm = {} + if self._topo.get_dim("pipe") == 1: + return + + layers_desc = self._layers_desc + shared_layer_names = set( + s.layer_name for s in layers_desc if isinstance(s, SharedLayerDesc) + ) + for key in shared_layer_names: + shared_layers = [] + for idx, layer in enumerate(layers_desc): + if ( + isinstance(layer, SharedLayerDesc) + and layer.layer_name == key + ): + shared_layers.append(idx) + + shared_stages = set( + self.get_stage_from_index(idx) for idx in shared_layers + ) + self._dp_degree = self._topo.get_dim('data') + self._mp_degree = self._topo.get_dim('model') + self._sharding_degree = self._topo.get_dim('sharding') + + shared_ranks = [] + for dp in range(self._dp_degree): + for sharding in range(self._sharding_degree): + for mp in range(self._mp_degree): + shared_ranks = [] + for s in sorted(shared_stages): + shared_ranks.append( + self._topo.get_rank_from_stage( + self.global_rank, + pipe=s, + data=dp, + sharding=sharding, + model=mp, + ) + ) + + group = paddle.distributed.new_group(ranks=shared_ranks) + if self.global_rank in shared_ranks: + assert key in self.shared_layers + if key in self.shared_layers: + shared_comm[key] = { + 'ranks': shared_ranks, + 'group': group, + 'weight_attr': self.shared_weight_attrs[ + key + ], + 'layer': self.shared_layers[key], + } + return shared_comm + + def _synchronize_shared_weights(self): + for key, comm in self.shared_comm.items(): + with paddle.framework.no_grad(): + paddle.distributed.broadcast( + getattr(comm['layer'], comm['weight_attr']), + src=min(comm['ranks']), + group=comm['group'], + ) + + for param in comm['layer'].parameters(): + if self.global_rank != min(comm['ranks']): + setattr(param, 'is_firstly_shared', False) + + def allreduce_shared_weight_gradients(self): + for key, comm in self.shared_comm.items(): + param = getattr(self.shared_layers[key], comm['weight_attr']) + # need use trace_op to allreduce weight + if in_dygraph_mode(): + with paddle.framework.no_grad(): + paddle.distributed.all_reduce( + param.grad, group=comm['group'] + ) + else: + with paddle.framework.no_grad(): + paddle.fluid.framework._dygraph_tracer().trace_op( + type="c_allreduce_sum", + inputs={'X': param._grad_ivar()}, + outputs={'Out': param._grad_ivar()}, + attrs={ + 'ring_id': comm['group'].id, + 'use_calc_stream': True, + }, + ) + + def _segment_network_for_interleave(self, seg_method): + logger.info("start segment network for interleave scheduler") + seg = SegmentLayers( + self._layers_desc, + num_parts=self._num_stages, + method=seg_method, + num_virtual_pipeline_stage=self._num_virtual_pipeline_stages, + ) + self.segment_parts = seg.do_segment() + + logger.info( + "segment result:" + + ", ".join(str(arg) for arg in self.segment_parts) + ) + + for i in range( + self._stage_id, + self._total_stages_with_virtual_stages, + self._num_stages, + ): + # If there are 2 real pp stages and 2 virtual pp stages, and the model has 8 layers. + # Layers [0, 1], [4, 5] will be assigned to the first real pp stage. + # Layers [2, 3], [6, 7] will be assigned to the second real pp stage. + # Layers [0, 1] and [2, 3] are the first virtual pp stage in each real pp stage. + # Layers [4, 5] and [6, 7] are the second virtual pp stage in each real pp stage. + assert self.segment_parts[i] <= self.segment_parts[i + 1] + self._start_poss.append(self.segment_parts[i]) + self._end_poss.append(self.segment_parts[i + 1]) + + assert len(self._start_poss) == len(self._end_poss) + + self._print_segmentation_for_debug() + + def _segment_network(self, seg_method): + logger.info("start segment network..") + seg = SegmentLayers( + self._layers_desc, num_parts=self._num_stages, method=seg_method + ) + self.segment_parts = seg.do_segment() + + logger.info( + "segment result:" + + ", ".join(str(arg) for arg in self.segment_parts) + ) + + self._start_pos = self.segment_parts[self._stage_id] + self._end_pos = self.segment_parts[self._stage_id + 1] + self._print_segmentation_for_debug() + + def _print_segmentation_for_debug(self): + # print information for debug + for stage in range( + self._num_stages * self._num_virtual_pipeline_stages + ): + start = self.segment_parts[stage] + end = self.segment_parts[stage + 1] + logger.info( + "stage={}, global_rank={} ,layer_number={}".format( + stage, self.global_rank, end - start + ) + ) + + for index, layer in enumerate(self._layers_desc[start:end]): + logger.info("{}: {}".format(index + start, str(layer))) + + if self._num_virtual_pipeline_stages > 1: + for stage in range(self._num_stages): + stage_to_virtual_stage_info = ( + "stage {} contains virtual stages: ".format(stage) + ) + for i in range( + stage, + self._total_stages_with_virtual_stages, + self._num_stages, + ): + stage_to_virtual_stage_info += " {},".format(i) + logger.info(stage_to_virtual_stage_info) + + if self._loss_fn: + try: + logger.info("loss: {}".format(self._loss_fn.__name__)) + except AttributeError: + logger.info("loss: {}".format(self._loss_fn.__class__.__name__)) + + def _build_layer_with_interleave(self): + for i in range(len(self._start_poss)): + start = self._start_poss[i] + end = self._end_poss[i] + # Get a model chunk + chunk = self._build_layer_impl(start, end) + assert isinstance(chunk, PipelineLayerChunk) + # Add the chunk to all chunks and add this chunk to the sublayer + self._model_chunks.append(chunk) + self.add_sublayer(str(start), chunk) + + def _build_layer(self): + start = self._start_pos + end = self._end_pos + self.run_function = self._build_layer_impl(start, end) + + def _build_layer_impl(self, start, end): + if self._num_virtual_pipeline_stages > 1: + # For interleave scheduler, all layers relating with one model chunk will be saved in PipelineLayerChunk + run_function = PipelineLayerChunk() + else: + # For 1f1b scheduler, just use run_function list + run_function = self.run_function + + for index, layer in enumerate(self._layers_desc[start:end]): + layer_index = start + index + if isinstance(layer, Layer): + run_function.append(layer) + if self._num_virtual_pipeline_stages == 1: + # Only add sublayer for 1f1b scheduler, + # for interleave, PipelineLayerChunk will do this + self.add_sublayer(str(layer_index), layer) + elif isinstance(layer, SharedLayerDesc): + if layer.layer_name not in self.shared_layers: + self.shared_layers[layer.layer_name] = layer.build_layer() + self.shared_weight_attrs[ + layer.layer_name + ] = layer.shared_weight_attr + for param in self.shared_layers[ + layer.layer_name + ].parameters(): + setattr(param, "is_firstly_shared", True) + + if layer.forward_func is None: + run_function.append(self.shared_layers[layer.layer_name]) + + else: + run_function.append( + partial( + layer.forward_func, + self.shared_layers[layer.layer_name], + ) + ) + + elif isinstance(layer, LayerDesc): + model = layer.build_layer() + run_function.append(model) + if self._num_virtual_pipeline_stages == 1: + # Only add sublayer for 1f1b scheduler, + # for interleave, PipelineLayerChunk will do this + self.add_sublayer(str(layer_index), model) + else: + run_function.append(layer) + + return run_function + + def forward_function(self, start, end): + run_function = self.run_function + + def execute_func(*x): + if len(x) == 1: + x = x[0] + for idx, layer in enumerate(run_function[start:end]): + x = layer(x) + return x + + return execute_func + + def forward(self, input, chunk_id=None): + if chunk_id is not None: + assert isinstance(chunk_id, int), "chunk_id should be an int" + assert ( + self._num_virtual_pipeline_stages > 1 + ), "chunk_id is only valid when using virtual pipeline stage" + assert chunk_id < len(self._model_chunks), ( + "The virtual pipeline only has {} chunks, " + "but received chunk_id {}.".format( + len(self._model_chunks), chunk_id + ) + ) + # Get the target model chunk. + model_chunk = self._model_chunks[chunk_id] + # Update the self.run_function to the target run functions. + # Runs for 1f1b and interleave are similar, just handle all functions in self.run_function. + # The only different is that, for 1f1b, self.run_function has already been inited during build_layer. + # But for interleave, self.run_function will keep updating to the target functions at every run. + self.run_function = model_chunk.get_run_function() + + if self._recompute_interval == 0: + input = self.forward_function(0, len(self.run_function))(input) + else: + num_layers = len(self.run_function) + for start_idx in range(0, num_layers, self._recompute_interval): + end_idx = min(start_idx + self._recompute_interval, num_layers) + funcs = self.run_function[start_idx:end_idx] + + if not isinstance(input, tuple): + input = (input,) + + if self._need_recompute(funcs, input): + input = recompute_hybrid( + self.recompute_ctx, + self.forward_function(start_idx, end_idx), + *input + ) + else: + input = self.forward_function(start_idx, end_idx)(*input) + + return input + + def _need_recompute(self, funcs, inputs): + if not any( + input_.stop_gradient == False + for input_ in inputs + if isinstance(input_, paddle.Tensor) + ): + return False + + params = [f.parameters() for f in funcs if isinstance(f, Layer)] + return any(len(list(p)) > 0 for p in params) + + def save_state_dict(self, path): + if self._topo.get_coord(self.global_rank).data != 0: + return + + def _offset_dirname(ckpt_dir, local_layer_idx, local_chunk_id=None): + if self._num_virtual_pipeline_stages == 1: + pos_offset = self._start_pos + else: + assert hasattr(self, '_start_poss') + assert local_chunk_id < len(self._start_poss) + pos_offset = self._start_poss[local_chunk_id] + idx = local_layer_idx + pos_offset + model_rank = self._topo.get_coord(self.global_rank).model + rank_message = "-tensor_" + "{:0>2d}".format(model_rank) + virtual_pipeline_stage_message = "" + if self._num_virtual_pipeline_stages > 1: + # add virtual pipeline info to the save path + assert local_chunk_id is not None + virtual_pipeline_stage_message = ( + "-virtual_pp_stage_{:0>2d}".format(local_chunk_id) + ) + layer_save_path = os.path.join( + ckpt_dir, 'layer_{:0>2d}'.format(idx) + ) + layer_save_path = ( + layer_save_path + + virtual_pipeline_stage_message + + rank_message + + '-model_states.pdparams' + ) + return layer_save_path + + def _save_model(run_functions, local_chunk_id=None): + for idx, layer in enumerate(run_functions): + model_save_path = _offset_dirname(path, idx, local_chunk_id) + if not hasattr(layer, 'state_dict'): + continue + paddle.save(layer.state_dict(), model_save_path) + + os.makedirs(path, exist_ok=True) + if self._num_virtual_pipeline_stages > 1: + logger.info("save model state for virtual pipeline stage...") + for chunk_id in range(len(self._model_chunks)): + run_function = self._model_chunks[chunk_id].get_run_function() + _save_model(run_function, chunk_id) + else: + _save_model(self.run_function) + + logger.info("save model state successfully...") + + def set_state_dir(self, path): + assert os.path.exists( + path + ), "{} not found, please check the path".format(path) + + def _load_model(run_functions, local_chunk_id=None): + for idx, layer in enumerate(run_functions): + if not hasattr(layer, 'set_state_dict'): + continue + if self._num_virtual_pipeline_stages == 1: + pos_offset = self._start_pos + else: + assert hasattr(self, '_start_poss') + assert local_chunk_id < len(self._start_poss) + pos_offset = self._start_poss[local_chunk_id] + layer_idx = idx + pos_offset + layer_save_path = os.path.join( + path, 'layer_{0:0>2d}'.format(layer_idx) + ) + if self._num_virtual_pipeline_stages > 1: + # add virtual pipeline info to the path + assert local_chunk_id is not None + layer_save_path = ( + layer_save_path + + "-virtual_pp_stage_{:0>2d}".format(local_chunk_id) + ) + model_files = glob.glob( + layer_save_path + "*model_states.pdparams" + ) + model_files.sort() + mp_rank = self._topo.get_coord(self.global_rank).model + mp_world_size = self._topo.get_dim('model') + num_files = len(model_files) + + load_param_path = model_files[ + mp_rank * num_files // mp_world_size + ] + model_state_dict = paddle.load(load_param_path) + layer.set_state_dict(model_state_dict) + + if self._num_virtual_pipeline_stages > 1: + logger.info("load model state for virtual pipeline stage...") + for chunk_id in range(len(self._model_chunks)): + run_function = self._model_chunks[chunk_id].get_run_function() + _load_model(run_function, chunk_id) + else: + _load_model(self.run_function) + + self._synchronize_shared_weights() + logger.info("load model state successfully...") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/random.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/random.py new file mode 100644 index 0000000000000000000000000000000000000000..9deed30db66f5c0886ac3712a10ef9785a152b6a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/parallel_layers/random.py @@ -0,0 +1,21 @@ +# Copyright (c) 2022 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. + +from ...layers.mpu.random import RNGStatesTracker # noqa: F401 +from ...layers.mpu.random import get_rng_state_tracker # noqa: F401 +from ...layers.mpu.random import model_parallel_random_seed # noqa: F401 +from ...layers.mpu.random import determinate_seed # noqa: F401 +from ...layers.mpu.random import dropout # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pipeline_parallel.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pipeline_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..77570407335167a1b95caa882c8aa4f400fcbba9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pipeline_parallel.py @@ -0,0 +1,784 @@ +# Copyright (c) 2021 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 + +import paddle +import paddle.fluid as fluid +from .meta_parallel_base import MetaParallelBase +from .parallel_layers.pp_layers import PipelineLayer + +from ..utils.hybrid_parallel_util import broadcast_mp_parameters +from ..utils.hybrid_parallel_util import broadcast_dp_parameters +from ..utils.hybrid_parallel_util import broadcast_sharding_parameters +from ..utils.log_util import logger +from ..meta_optimizers.dygraph_optimizer import ( + HybridParallelOptimizer, + HybridParallelGradScaler, +) +import paddle.fluid.framework as framework +from .pp_utils import p2p_communication as p2p +import paddle.fluid.core as core + +__all__ = [] + + +class PipelineParallel(MetaParallelBase): + def __init__(self, layers, hcg, strategy): + if not isinstance(layers, PipelineLayer): + raise TypeError( + "The Layer should be a derived class of PipelineLayer." + ) + super(PipelineParallel, self).__init__(layers, hcg, strategy) + self.use_data_parallel = self._hcg.get_data_parallel_world_size() > 1 + self.use_model_parallel = self._hcg.get_model_parallel_world_size() > 1 + self.use_sharding_parallel = ( + self._hcg.get_sharding_parallel_world_size() > 1 + ) + + self.total_loss = None + + self.micro_batch_size = self._strategy.pipeline_configs[ + 'micro_batch_size' + ] + self.accumulate_steps = self._strategy.pipeline_configs[ + 'accumulate_steps' + ] + # If sent tensor are not the same from different hosts, + # they shouldn't been sent partially and then concated as a whole tensor. + self._enable_partial_send_recv = self._strategy.pipeline_configs[ + 'enable_partial_send_recv' + ] + self._using_cache = self._strategy.pipeline_configs['p2p_cache_shape'] + + self.num_stages = self._hcg.get_pipe_parallel_world_size() + self.stage_id = self._hcg.get_stage_id() + self.pp_group = self._hcg.get_pipe_parallel_group() + + self._virtual_pp_world_size = None + self._virtual_pp_rank = None + self._real_pp_world_size = self.num_stages + self._real_pp_rank = self.stage_id + + p2p.initialize_p2p_groups( + hcg, self._using_cache, self._enable_partial_send_recv + ) + + self.global_rank = self._hcg.get_global_rank() + self.micro_batch_id = 0 + + self._compute_loss = True + + logger.info( + "Pipeline Info -- num_stages: {}, stage_id: {}".format( + self.num_stages, self.stage_id + ) + ) + + if self.use_model_parallel: + logger.info("start broadcast mp parameters") + broadcast_mp_parameters(self._layers, self._hcg) + + if self.use_sharding_parallel: + logger.info("start broadcast sharding parameters") + broadcast_sharding_parameters(self._layers, self._hcg) + + if self.use_data_parallel: + logger.info("start broadcast dp parameters") + broadcast_dp_parameters(self._layers, self._hcg) + + def is_pipeline_first_stage(self, ignore_virtual=False): + if not ignore_virtual: + if self._virtual_pp_world_size is not None: + assert self._virtual_pp_rank is not None + if self._virtual_pp_rank != 0: + return False + assert self._real_pp_rank is not None + return self._real_pp_rank == 0 + + def is_pipeline_last_stage(self, ignore_virtual=False): + if not ignore_virtual: + if self._virtual_pp_world_size is not None: + assert self._virtual_pp_rank is not None + if self._virtual_pp_rank != (self._virtual_pp_world_size - 1): + return False + assert self._real_pp_rank is not None + assert self._real_pp_world_size is not None + return self._real_pp_rank == (self._real_pp_world_size - 1) + + def set_virtual_pipeline_rank(self, rank): + self._virtual_pp_rank = rank + + def forward_backward_pipeline(self, data, scaler=None): + # use the 1f1b scheduling strategy. + # this strategy is inspired by: + # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/schedules.py + + self.scaler = scaler + + # store data for train + self.data = data + + # store total loss of entire batch + self.total_loss = None + + # store data id for micro_batch + self.micro_batch_id = 0 + + startup_steps = self.num_stages - self.stage_id - 1 + startup_steps = min(startup_steps, self.accumulate_steps) + steady_steps = self.accumulate_steps - startup_steps + + input_buffers = [] + output_buffers = [] + + for step_id in range(startup_steps): + input_tensor = p2p.recv_forward(self.is_pipeline_first_stage()) + + output_tensor = self._forward_step(input_tensor) + p2p.send_forward(output_tensor, self.is_pipeline_last_stage()) + + input_buffers.append(input_tensor) + output_buffers.append(output_tensor) + + if steady_steps > 0: + input_tensor = p2p.recv_forward(self.is_pipeline_first_stage()) + + for i in range(steady_steps): + last_iter = i == (steady_steps - 1) + + output_tensor = self._forward_step(input_tensor) + + output_tensor_grad = p2p.send_forward_recv_backward( + output_tensor, self.is_pipeline_last_stage() + ) + + input_buffers.append(input_tensor) + output_buffers.append(output_tensor) + + input_tensor, output_tensor = input_buffers.pop( + 0 + ), output_buffers.pop(0) + + input_tensor_grad = self._backward_step( + input_tensor, output_tensor, output_tensor_grad + ) + + if last_iter: + input_tensor = None + p2p.send_backward( + input_tensor_grad, self.is_pipeline_first_stage() + ) + else: + input_tensor = p2p.send_backward_recv_forward( + input_tensor_grad, self.is_pipeline_first_stage() + ) + + for i in range(startup_steps): + input_tensor = input_buffers.pop(0) + output_tensor = output_buffers.pop(0) + + output_tensor_grad = p2p.recv_backward( + self.is_pipeline_last_stage() + ) + + input_tensor_grad = self._backward_step( + input_tensor, output_tensor, output_tensor_grad + ) + p2p.send_backward(input_tensor_grad, self.is_pipeline_first_stage()) + + self._layers.allreduce_shared_weight_gradients() + with paddle.amp.auto_cast(enable=False): + train_loss = self._broadcast_final_loss() + return train_loss + + def _prepare_training(self, data, optimizer, lr_scheduler): + # reset the virtual pp rank for each run + self.set_virtual_pipeline_rank(0) + + assert isinstance( + optimizer, HybridParallelOptimizer + ), 'optimizer should be HybridParallelOptimizer subclass.' + + assert ( + fluid.framework._dygraph_tracer()._has_grad + ), 'Please enable the generation of gradients.' + + if self.is_pipeline_first_stage( + ignore_virtual=True + ) or self.is_pipeline_last_stage(ignore_virtual=True): + assert ( + data is not None + ), "For the first and the last stage, the data must be set." + else: + data = None + + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + + self._layers.train() + + return data + + def train_batch(self, data, optimizer, lr_scheduler=None, scaler=None): + data = self._prepare_training(data, optimizer, lr_scheduler) + # 1f1b scheduler for pipeline parallel + train_loss = self.forward_backward_pipeline(data, scaler) + + # optimizer + with paddle.amp.auto_cast(enable=False): + self._optimizer_step() + + return train_loss + + def eval_batch(self, data, compute_loss=False): + # reset the virtual pp rank for each run + self.set_virtual_pipeline_rank(0) + + self._layers.eval() + self._compute_loss = compute_loss + + # save data for eval + self.data = data + # store data id for micro_batch + self.micro_batch_id = 0 + + # store total loss of entire batch + self.total_loss = None + + startup_steps = self.num_stages - self.stage_id - 1 + startup_steps = min(startup_steps, self.accumulate_steps) + steady_steps = self.accumulate_steps - startup_steps + + input_buffers = [] + output_buffers = [] + + for step_id in range(startup_steps): + input_tensor = p2p.recv_forward(self.is_pipeline_first_stage()) + + output_tensor = self._forward_step(input_tensor) + p2p.send_forward(output_tensor, self.is_pipeline_last_stage()) + + input_buffers.append(input_tensor) + output_buffers.append(output_tensor) + + if steady_steps > 0: + input_tensor = p2p.recv_forward(self.is_pipeline_first_stage()) + + for i in range(steady_steps): + last_iter = i == (steady_steps - 1) + + output_tensor = self._forward_step(input_tensor) + p2p.send_forward(output_tensor, self.is_pipeline_last_stage()) + + input_buffers.append(input_tensor) + output_buffers.append(output_tensor) + + if not last_iter: + input_tensor = p2p.recv_forward(self.is_pipeline_first_stage()) + + if self._compute_loss: + self.train_loss = self._broadcast_final_loss() + else: + self.train_loss = output_buffers + + return self.train_loss + + def _forward_step(self, input_tensor, chunk_id=None): + if self.is_pipeline_first_stage(): + input_tensor = self._load_micro_batch(self.micro_batch_id) + + assert chunk_id is None or isinstance(chunk_id, int) + + output_tensor = self._layers.forward(input_tensor, chunk_id=chunk_id) + + if self.is_pipeline_last_stage(): + # train calculate loss for train + if self._compute_loss: + assert ( + self._layers._loss_fn is not None + ), "loss function should exist to compute loss" + labels = self._load_micro_batch(self.micro_batch_id) + output_tensor = self._layers._loss_fn(output_tensor, labels) + assert isinstance( + output_tensor, (paddle.Tensor, core.eager.Tensor) + ), "Currently, loss_fn should obtain Paddle.Tensor dtype" + + with paddle.amp.auto_cast(enable=False): + if self.accumulate_steps > 1: + output_tensor = output_tensor / self.accumulate_steps + + if self.total_loss is None: + self.total_loss = paddle.zeros_like(output_tensor) + self.total_loss += output_tensor.detach() + + if self.is_pipeline_first_stage() or self.is_pipeline_last_stage(): + # Only increase micro batch id at virtual first/last pp stage. + # The micro batch id is used to load data, therefore, only increase it when load data. + self.micro_batch_id += 1 + return output_tensor + + def _backward_step(self, input_tensor, output_tensor, output_tensor_grad): + with paddle.amp.auto_cast(enable=False): + if self.is_pipeline_last_stage(): + assert output_tensor_grad is None + if self.scaler: + paddle.autograd.backward(self.scaler.scale(output_tensor)) + else: + paddle.autograd.backward(output_tensor) + else: + if isinstance(output_tensor, tuple): + outputs = [t for t in output_tensor if not t.stop_gradient] + assert len(outputs) == len(output_tensor_grad) + paddle.autograd.backward( + tensors=outputs, + grad_tensors=[t for t in output_tensor_grad], + ) + else: + paddle.autograd.backward( + tensors=[output_tensor], + grad_tensors=[output_tensor_grad], + ) + + input_tensor_grad = None + if input_tensor is not None: + if isinstance(input_tensor, tuple): + input_tensor_grad = tuple( + [t.grad for t in input_tensor if not t.stop_gradient] + ) + else: + input_tensor_grad = input_tensor.grad + return input_tensor_grad + + def _check_data_vaild(self, data): + batch_size = data.shape[0] + assert self.micro_batch_size * self.accumulate_steps == batch_size, ( + "batch_size needs to be divisible by micro_batch_size. Currently, " + "batch_size = %d, micro_batch_size = %d, accumulate_steps = %d." + % (batch_size, self.micro_batch_size, self.accumulate_steps) + ) + + def _load_micro_batch_impl(self, inputs, cache_id): + begin = cache_id * self.micro_batch_size + end = begin + self.micro_batch_size + + if isinstance(inputs, tuple): + output = [] + for data in inputs: + if isinstance(data, list): + assert ( + len(data) == self.accumulate_steps + ), "length of data should be %d, but it is %d" % ( + self.accumulate_steps, + len(data), + ) + output.append(data[cache_id].detach()) + else: + self._check_data_vaild(data) + output.append(data[begin:end, :].detach()) + return tuple(output) + + elif isinstance(inputs, list): + assert ( + len(inputs) == self.accumulate_steps + ), "length of data should be %d, but it is %d" % ( + self.accumulate_steps, + len(inputs), + ) + return inputs[cache_id].detach() + else: + self._check_data_vaild(inputs) + return inputs[begin:end, :].detach() + + def _load_micro_batch(self, cache_id): + inputs = self.data + if self.is_pipeline_first_stage(): + assert len(inputs) == 2, "length of input should be 2" + return self._load_micro_batch_impl(inputs[0], cache_id) + elif self.is_pipeline_last_stage(): + assert len(inputs) == 2, "length of input should be 2" + return self._load_micro_batch_impl(inputs[1], cache_id) + else: + inputs = None + + def _broadcast_final_loss(self): + # Since the last backward run in interleave will set the virtual rank to 0, + # here we need to check last stage ignoring virtual stage. + if self.is_pipeline_last_stage(ignore_virtual=True): + assert ( + self.total_loss is not None + ), "train_batch() in last stage should obtain vaild loss" + loss = self.total_loss.detach() + is_fp32 = ( + paddle.to_tensor(1) + if loss.dtype == paddle.float32 + else paddle.to_tensor(0) + ) + paddle.distributed.broadcast( + is_fp32, src=self.global_rank, sync_op=True, group=self.pp_group + ) + paddle.distributed.broadcast( + loss, src=self.global_rank, sync_op=True, group=self.pp_group + ) + else: + is_fp32 = paddle.to_tensor(1) + paddle.distributed.broadcast( + is_fp32, + src=self._hcg.get_rank_from_stage(self.num_stages - 1), + sync_op=True, + group=self.pp_group, + ) + loss = ( + paddle.zeros(shape=[1], dtype="float32") + if is_fp32.numpy()[0] + else paddle.zeros(shape=[1], dtype="float16") + ) + paddle.distributed.broadcast( + loss, + src=self._hcg.get_rank_from_stage(self.num_stages - 1), + sync_op=True, + group=self.pp_group, + ) + return loss + + def _optimizer_step(self): + if self.scaler: + self.scaler.step(self.optimizer) + self.scaler.update() + else: + self.optimizer.step() + + self.optimizer.clear_grad() + if self.lr_scheduler: + self.lr_scheduler.step() + + +class PipelineParallelWithInterleave(PipelineParallel): + # pipeline parallel with interleave scheduler + + def __init__(self, layers, hcg, strategy): + super(PipelineParallelWithInterleave, self).__init__( + layers=layers, hcg=hcg, strategy=strategy + ) + assert layers.get_num_virtual_stages() > 1 + assert ( + framework.in_dygraph_mode() + ), "virtual pipeline stage with interleave only support eager dygraph mode" + # setup for interleave scheduler + self.num_model_chunks = layers.get_num_virtual_stages() + self.model_chunks = layers.get_model_chunks() + assert self.model_chunks is not None + assert len(self.model_chunks) == self.num_model_chunks + self._virtual_pp_world_size = self.num_model_chunks + self._virtual_pp_rank = 0 + + def _get_virtual_pp_rank(self, micro_step, forward): + virtual_pp_stage = micro_step % ( + self.num_stages * self.num_model_chunks + ) + virtual_pp_stage = virtual_pp_stage // self.num_stages + if not forward: + virtual_pp_stage = self.num_model_chunks - virtual_pp_stage - 1 + return virtual_pp_stage + + def _forward_step_helper(self, micro_step): + virtual_pp_rank = self._get_virtual_pp_rank(micro_step, forward=True) + self.set_virtual_pipeline_rank(virtual_pp_rank) + + # some checkers + assert hasattr(self, 'input_tensors') + assert hasattr(self, 'output_tensors') + if not self._forward_only: + assert hasattr(self, 'output_tensor_grads') + + if self.is_pipeline_first_stage(): + if len(self.input_tensors[virtual_pp_rank]) == len( + self.output_tensors[virtual_pp_rank] + ): + self.input_tensors[virtual_pp_rank].append(None) + input_tensor = self.input_tensors[virtual_pp_rank][-1] + output_tensor = self._forward_step(input_tensor, virtual_pp_rank) + self.output_tensors[virtual_pp_rank].append(output_tensor) + + if self._forward_only: + # no need to store tensor for backward + self.input_tensors[virtual_pp_rank].pop() + self.output_tensors[virtual_pp_rank].pop() + + return output_tensor + + def _backward_step_helper(self, micro_step): + virtual_pp_rank = self._get_virtual_pp_rank(micro_step, forward=False) + self.set_virtual_pipeline_rank(virtual_pp_rank) + + # some checkers + assert hasattr(self, 'input_tensors') + assert hasattr(self, 'output_tensors') + assert hasattr(self, 'output_tensor_grads') + + if self.is_pipeline_last_stage(): + if len(self.output_tensor_grads[virtual_pp_rank]) == 0: + self.output_tensor_grads[virtual_pp_rank].append(None) + + input_tensor = self.input_tensors[virtual_pp_rank].pop(0) + output_tensor = self.output_tensors[virtual_pp_rank].pop(0) + output_tensor_grad = self.output_tensor_grads[virtual_pp_rank].pop(0) + input_tensor_grad = self._backward_step( + input_tensor, output_tensor, output_tensor_grad + ) + + return input_tensor_grad + + def forward_backward_pipeline( + self, data, scaler, forward_only=False, compute_loss=True + ): + # use interleave scheduling strategy. + # this strategy is inspired by: + # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/schedules.py + if not compute_loss: + assert ( + not forward_only + ), "compute_loss can only be set to False when forward_only is set to True" + + # init some attributes for this batch run + self.scaler = scaler + self.data = data + self.total_loss = None + self.micro_batch_id = 0 + self._forward_only = forward_only + + # init some data buffers for interleave scheduler + self.input_tensors = [[] for _ in range(self.num_model_chunks)] + self.output_tensors = [[] for _ in range(self.num_model_chunks)] + self.output_tensor_grads = [[] for _ in range(self.num_model_chunks)] + + num_steps = self.accumulate_steps * self.num_model_chunks + all_startup_steps = False + if forward_only: + # If only forward, since there is no backward during running, all steps are startup steps + startup_steps = num_steps + else: + if self.accumulate_steps == self.num_stages: + startup_steps = num_steps + all_startup_steps = True + else: + startup_steps = (self.num_stages - self.stage_id - 1) * 2 + startup_steps += (self.num_model_chunks - 1) * self.num_stages + startup_steps = min(startup_steps, num_steps) + + steady_steps = num_steps - startup_steps + + self.set_virtual_pipeline_rank(0) + self.input_tensors[0].append( + p2p.recv_forward(self.is_pipeline_first_stage(), sync_recv=False) + ) + + # run startup steps + for micro_step in range(startup_steps): + output_tensor = self._forward_step_helper(micro_step) + + # determine whether recv forward tensor or not + next_virtual_pp_rank = self._get_virtual_pp_rank( + micro_step + 1, forward=True + ) + recv_prev = True + if self.is_pipeline_first_stage(ignore_virtual=True): + if next_virtual_pp_rank == 0: + # next chunk is the first chunk, not need to pre recv an input tensor + recv_prev = False + # last micro step, no next run + if micro_step == (num_steps - 1): + recv_prev = False + + # last stage shouldn't send tensor to downstream + if self.is_pipeline_last_stage(): + output_tensor = None + + if ( + micro_step == (startup_steps - 1) + and not forward_only + and not all_startup_steps + ): + input_tensor_grad = None + recv_next = True + if self.is_pipeline_last_stage(ignore_virtual=True): + recv_next = False + + # the last startup step needs on four direction comm to set up for steady 1f1b + ( + input_tensor, + output_tensor_grad, + ) = p2p.send_forward_backward_recv_forward_backward( + output_tensor, + input_tensor_grad, + recv_prev=recv_prev, + recv_next=recv_next, + ) + self.output_tensor_grads[self.num_model_chunks - 1].append( + output_tensor_grad + ) + else: + input_tensor = p2p.send_forward_recv_forward( + output_tensor, recv_prev=recv_prev + ) + self.input_tensors[next_virtual_pp_rank].append(input_tensor) + + # run 1f1b steady steps + for micro_step in range(steady_steps): + # forward + forward_micro_step_id = micro_step + startup_steps + output_tensor = self._forward_step_helper(forward_micro_step_id) + + # backward + backward_micro_step_id = micro_step + input_tensor_grad = self._backward_step_helper( + backward_micro_step_id + ) + + # four directions comm + # send output tensor to downstream + # send input tensor grad to upstream + # recv input tensor from upstream + # recv output tensor grad from downstream + + # last stage doesn't send rst to downstream + forward_virtual_pp_rank = self._get_virtual_pp_rank( + forward_micro_step_id, forward=True + ) + self.set_virtual_pipeline_rank(forward_virtual_pp_rank) + if self.is_pipeline_last_stage(): + output_tensor = None + + # first stage doesn't send grad to upstream + backward_virtual_pp_rank = self._get_virtual_pp_rank( + backward_micro_step_id, forward=False + ) + self.set_virtual_pipeline_rank(backward_virtual_pp_rank) + if self.is_pipeline_first_stage(): + input_tensor_grad = None + + # determine whether to recv input tensor from upstream + recv_prev = True + if self.is_pipeline_first_stage(ignore_virtual=True): + next_forward_virtual_pp_rank = self._get_virtual_pp_rank( + forward_micro_step_id - (self.num_stages - 1), forward=True + ) + if next_forward_virtual_pp_rank == (self.num_model_chunks - 1): + # first pp stage and first virtual stage + recv_prev = False + next_forward_virtual_pp_rank += 1 + else: + next_forward_virtual_pp_rank = self._get_virtual_pp_rank( + forward_micro_step_id + 1, forward=True + ) + + # last iteration doesn't need recv from upstream + if micro_step == (steady_steps - 1): + recv_prev = False + + # determine whether to recv grad from downstream + recv_next = True + if self.is_pipeline_last_stage(ignore_virtual=True): + next_backward_virtual_pp_rank = self._get_virtual_pp_rank( + backward_micro_step_id - (self.num_stages - 1), + forward=False, + ) + if next_backward_virtual_pp_rank == 0: + # last pp stage and last virtual stage + recv_next = False + next_backward_virtual_pp_rank -= 1 + else: + next_backward_virtual_pp_rank = self._get_virtual_pp_rank( + backward_micro_step_id + 1, forward=False + ) + + ( + input_tensor, + output_tensor_grad, + ) = p2p.send_forward_backward_recv_forward_backward( + output_tensor, + input_tensor_grad, + recv_prev=recv_prev, + recv_next=recv_next, + ) + + if recv_prev: + self.input_tensors[next_forward_virtual_pp_rank].append( + input_tensor + ) + if recv_next: + self.output_tensor_grads[next_backward_virtual_pp_rank].append( + output_tensor_grad + ) + + # remaining backward steps + if not forward_only: + if all_startup_steps: + self.output_tensor_grads[self.num_model_chunks - 1].append( + p2p.recv_backward( + self.is_pipeline_last_stage(), sync_recv=False + ) + ) + + for micro_step in range(steady_steps, num_steps): + # cooldown loop + input_tensor_grad = self._backward_step_helper(micro_step) + next_backward_virtual_pp_rank = self._get_virtual_pp_rank( + micro_step + 1, forward=False + ) + + recv_next = True + if self.is_pipeline_last_stage(ignore_virtual=True): + if next_backward_virtual_pp_rank == ( + self.num_model_chunks - 1 + ): + recv_next = False + + if micro_step == (num_steps - 1): + recv_next = False + + self.output_tensor_grads[next_backward_virtual_pp_rank].append( + p2p.send_backward_recv_backward( + input_tensor_grad, recv_next=recv_next + ) + ) + + self._layers.allreduce_shared_weight_gradients() + + if compute_loss: + # return loss if compute loss + with paddle.amp.auto_cast(enable=False): + train_loss = self._broadcast_final_loss() + else: + # else just return all intermediate output tensor for all micro steps + train_loss = self.output_tensors + + return train_loss + + def train_batch(self, data, optimizer, lr_scheduler=None, scaler=None): + data = self._prepare_training(data, optimizer, lr_scheduler) + # interleave scheduler for pipeline parallel + train_loss = self.forward_backward_pipeline(data, scaler) + + # optimizer + with paddle.amp.auto_cast(enable=False): + self._optimizer_step() + + return train_loss + + def eval_batch(self, data, compute_loss=False): + # reset the virtual pp rank for each run + self.set_virtual_pipeline_rank(0) + + self._layers.eval() + self._compute_loss = compute_loss + + return self.forward_backward_pipeline(data, None, forward_only=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04575bfb231946e87150ec121ad0be8cd3ea599f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2021 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. + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py new file mode 100644 index 0000000000000000000000000000000000000000..a84c49d74aa06309423986d13ec5017e18ef2277 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/p2p_communication.py @@ -0,0 +1,703 @@ +# Copyright (c) 2021 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. + +import paddle +from ...utils.log_util import logger +import numpy as np +from paddle import _C_ops, _legacy_C_ops +import paddle.fluid.core as core +from paddle.fluid.framework import ( + _in_legacy_dygraph, + _non_static_mode, + in_dygraph_mode, +) +from .utils import paddle_2_number, paddle_2_number, number_2_dtype + +_hcg = None +_use_cache = False +_enable_partial_send_recv = True + + +def initialize_p2p_groups(hcg, use_cache=True, enable_partial_send_recv=True): + global _hcg, _use_cache, _enable_partial_send_recv + _hcg = hcg + _use_cache = use_cache + _enable_partial_send_recv = enable_partial_send_recv + ( + send_next_group, + send_prev_group, + recv_next_group, + recv_prev_group, + ) = _hcg.get_p2p_groups() + + debug_str = ( + "P2pInfo: send_next_group: %s, send_prev_group: %s, " + "recv_next_group: %s, recv_prev_group: %s" + % ( + repr(send_next_group), + repr(send_prev_group), + repr(recv_next_group), + repr(recv_prev_group), + ) + ) + logger.info(debug_str) + + +class SendRecvMeta: + """Mainly used to help p2p communication context information""" + + def __init__(self): + self.send_shape_message = None + self.send_dtype_message = None + + self.recv_shape_message = None + self.recv_dtype_message = None + self.recv_stop_gradient = None + + self.has_send_meta = False + self.has_recv_meta = False + + def _recv_shape_dtype(self, group): + # recv len(shape) + dims = paddle.to_tensor([0]) + src_rank = _hcg._get_p2p_prev_rank() + + paddle.distributed.recv(dims, src=src_rank, group=group) + dims = dims.item() + + # recv shape + shape = paddle.to_tensor([0] * dims) + paddle.distributed.recv(shape, src=src_rank, group=group) + + # recv dtype + dtype = paddle.to_tensor([0]) + paddle.distributed.recv(dtype, src=src_rank, group=group) + + # recv stop_gradient + stop_grad = paddle.to_tensor([0]) + paddle.distributed.recv(stop_grad, src=src_rank, group=group) + return shape.numpy().tolist(), dtype.item(), stop_grad.item() + + def recv_meta(self, group): + tensor_type = paddle.to_tensor([0]) + src_rank = _hcg._get_p2p_prev_rank() + + paddle.distributed.recv(tensor_type, src=src_rank, group=group) + tensor_type = tensor_type.item() + + if tensor_type == 0: + shape, dtype, stop_grad = self._recv_shape_dtype(group) + self.recv_shape_message = shape + self.recv_dtype_message = dtype + self.recv_stop_gradient = bool(stop_grad) + + elif tensor_type == 1: + num = paddle.to_tensor([0]) + paddle.distributed.recv(num, src=src_rank, group=group) + num = num.item() + shapes = [] + dtypes = [] + stop_grads = [] + for i in range(num): + shape, dtype, stop_grad = self._recv_shape_dtype(group) + shapes.append(shape) + dtypes.append(dtype) + stop_grads.append(bool(stop_grad)) + + self.recv_shape_message = tuple(shapes) + self.recv_dtype_message = tuple(dtypes) + self.recv_stop_gradient = tuple(stop_grads) + + def _send_dims_shape_dtype(self, tensor, group): + # send len(shape) + dims = paddle.to_tensor(len(tensor.shape)) + dst_rank = _hcg._get_p2p_next_rank() + + paddle.distributed.send(dims, dst=dst_rank, group=group) + + # send shape + shape = paddle.to_tensor(tensor.shape) + paddle.distributed.send(shape, dst=dst_rank, group=group) + + # send dtype + dtype = paddle.to_tensor(paddle_2_number(tensor.dtype)) + paddle.distributed.send(dtype, dst=dst_rank, group=group) + + # send trainable + stop_grad = paddle.to_tensor(int(tensor.stop_gradient)) + paddle.distributed.send(stop_grad, dst=dst_rank, group=group) + + def send_meta(self, tensor, group): + dst_rank = _hcg._get_p2p_next_rank() + + if isinstance(tensor, (paddle.Tensor, core.eager.Tensor)): + tensor_type = paddle.to_tensor([0]) + # send tensor type + paddle.distributed.send(tensor_type, dst=dst_rank, group=group) + + self._send_dims_shape_dtype(tensor, group) + elif isinstance(tensor, tuple): + tensor_type = paddle.to_tensor([1]) + # send tensor type + paddle.distributed.send(tensor_type, dst=dst_rank, group=group) + + nums = paddle.to_tensor(len(tensor)) + paddle.distributed.send(nums, dst=dst_rank, group=group) + + for d in tensor: + assert isinstance(d, (paddle.Tensor, core.eager.Tensor)) + self._send_dims_shape_dtype(d, group=group) + + def set_send_message(self, tensor): + if isinstance(tensor, (paddle.Tensor, core.eager.Tensor)): + self.send_shape_message = tensor.shape + self.send_dtype_message = paddle_2_number(tensor.dtype) + elif isinstance(tensor, tuple): + self.send_shape_message = tuple( + [d.shape for d in tensor if not d.stop_gradient] + ) + self.send_dtype_message = tuple( + [ + paddle_2_number(d.dtype) + for d in tensor + if not d.stop_gradient + ] + ) + + +_send_recv_meta = SendRecvMeta() + + +def _is_valid_send_recv_partial(tensor, mp_degree): + if not _enable_partial_send_recv: + return False + tensor_numel = np.prod(tensor.shape) + assert tensor_numel != 0, "can't send/recv zero element" + return mp_degree > 1 and tensor_numel % mp_degree == 0 + + +def _partial_send_op( + tensor, group, use_calc_stream, ring_id, dst, nranks, rank_id +): + dst_rank_in_group = dst if group is None else group.get_group_rank(dst) + if _in_legacy_dygraph(): + return _legacy_C_ops.partial_send( + tensor.detach(), + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'peer', + dst_rank_in_group, + 'num', + nranks, + 'id', + rank_id, + ) + elif in_dygraph_mode(): + group = ( + paddle.distributed.collective._get_default_group() + if group is None + else group + ) + comm_op = ( + group.process_group.send_partial_on_calc_stream + if use_calc_stream + else group.process_group.send_partial + ) + return comm_op(tensor, dst_rank_in_group, nranks, rank_id) + + +def send_partial( + tensor, dst=0, nranks=1, rank_id=0, group=None, use_calc_stream=True +): + # dst: local rank in group + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + dst_rank = ( + _hcg._get_p2p_next_rank() if dst == 1 else _hcg._get_p2p_prev_rank() + ) + + if _is_valid_send_recv_partial(tensor, nranks): + return _partial_send_op( + tensor, group, use_calc_stream, ring_id, dst_rank, nranks, rank_id + ) + else: + if _in_legacy_dygraph(): + send_op = lambda x, dst, group: paddle.distributed.send( + x, dst, group, use_calc_stream + ) + elif in_dygraph_mode(): + send_op = paddle.distributed.isend + return send_op(tensor.detach(), dst=dst_rank, group=group) + + +def _partial_recv_op( + tensor, group, use_calc_stream, ring_id, src, nranks, rank_id +): + src_rank_in_group = src if group is None else group.get_group_rank(src) + if _in_legacy_dygraph(): + assert use_calc_stream + return _legacy_C_ops.partial_recv( + tensor.detach(), + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'peer', + src_rank_in_group, + 'num', + nranks, + 'id', + rank_id, + 'dtype', + tensor.dtype, + 'out_shape', + tensor.shape, + ) + elif in_dygraph_mode(): + group = ( + paddle.distributed.collective._get_default_group() + if group is None + else group + ) + comm_op = ( + group.process_group.recv_partial_on_calc_stream + if use_calc_stream + else group.process_group.recv_partial + ) + return comm_op(tensor, src_rank_in_group, nranks, rank_id) + + +def recv_partial( + tensor, src=0, nranks=1, rank_id=0, group=None, use_calc_stream=True +): + # src: local rank in group + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + src_rank = ( + _hcg._get_p2p_prev_rank() if src == 0 else _hcg._get_p2p_next_rank() + ) + + if _is_valid_send_recv_partial(tensor, nranks): + return _partial_recv_op( + tensor, group, use_calc_stream, ring_id, src_rank, nranks, rank_id + ) + else: + if _in_legacy_dygraph() or use_calc_stream: + recv_op = paddle.distributed.recv + elif in_dygraph_mode(): + recv_op = paddle.distributed.irecv + return recv_op(tensor.detach(), src=src_rank, group=group) + + +def _partial_allgather_op( + tensor, group, use_calc_stream, ring_id, nranks, rank_id +): + if _in_legacy_dygraph(): + return _legacy_C_ops.partial_allgather_( + tensor.detach(), + 'use_calc_stream', + use_calc_stream, + 'ring_id', + ring_id, + 'nranks', + nranks, + 'rank', + rank_id, + ) + elif in_dygraph_mode(): + group = ( + paddle.distributed.collective._get_default_group() + if group is None + else group + ) + comm_op = ( + group.process_group.all_gather_partial_on_calc_stream + if use_calc_stream + else group.process_group.all_gather_partial + ) + return comm_op(tensor, tensor, nranks, rank_id) + + +def allgather_partial( + tensor, nranks=1, rank_id=0, group=None, use_calc_stream=True +): + if not _is_valid_send_recv_partial(tensor, nranks): + return tensor + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + + return _partial_allgather_op( + tensor, group, use_calc_stream, ring_id, nranks, rank_id + ) + + +def _p2p_helper( + tensor_send_next, tensor_send_prev, recv_prev, recv_next, sync_recv=True +): + global _hcg + + tensor_recv_prev = None + tensor_recv_next = None + + # send / recv message + recv_shape_msg = _send_recv_meta.recv_shape_message + recv_dtype_msg = _send_recv_meta.recv_dtype_message + recv_stop_gradient = _send_recv_meta.recv_stop_gradient + + send_shape_msg = _send_recv_meta.send_shape_message + send_dtype_msg = _send_recv_meta.send_dtype_message + + # model parallel message + mp_group = _hcg.get_model_parallel_group() + mp_degree = _hcg.get_model_parallel_world_size() + mp_rank = _hcg.get_model_parallel_rank() + + if recv_prev: + if isinstance(recv_shape_msg, tuple): + tensor_recv_prev = [] + for idx, shape in enumerate(recv_shape_msg): + tmp = paddle.empty( + shape=shape, dtype=number_2_dtype(recv_dtype_msg[idx]) + ) + tmp.stop_gradient = recv_stop_gradient[idx] + tensor_recv_prev.append(tmp) + tensor_recv_prev = tuple(tensor_recv_prev) + else: + + tensor_recv_prev = paddle.empty( + shape=recv_shape_msg, dtype=number_2_dtype(recv_dtype_msg) + ) + tensor_recv_prev.stop_gradient = recv_stop_gradient + + if recv_next: + if isinstance(send_shape_msg, tuple): + tensor_recv_next = [] + for idx, shape in enumerate(send_shape_msg): + tensor_recv_next.append( + paddle.empty( + shape=shape, dtype=number_2_dtype(send_dtype_msg[idx]) + ) + ) + tensor_recv_next = tuple(tensor_recv_next) + else: + tensor_recv_next = paddle.empty( + shape=send_shape_msg, dtype=number_2_dtype(send_dtype_msg) + ) + + # TODO(Yuang Liu): use batch_isend_irecv replace all these comm ops + tasks = [] + # start to p2p communicate + if tensor_send_prev is not None: + if isinstance(tensor_send_prev, tuple): + for d in tensor_send_prev: + paddle.distributed.wait(d, use_calc_stream=True) + send_partial( + d, + dst=0, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.send_prev_group, + use_calc_stream=False, + ) + else: + paddle.distributed.wait(tensor_send_prev, use_calc_stream=True) + send_partial( + tensor_send_prev, + dst=0, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.send_prev_group, + use_calc_stream=False, + ) + + if tensor_recv_prev is not None: + if isinstance(tensor_recv_prev, tuple): + for d in tensor_recv_prev: + task = recv_partial( + d, + src=0, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.recv_prev_group, + use_calc_stream=sync_recv, + ) + if sync_recv: + allgather_partial( + d, + nranks=mp_degree, + rank_id=mp_rank, + group=mp_group, + use_calc_stream=True, + ) + else: + tasks.append(task) + else: + task = recv_partial( + tensor_recv_prev, + src=0, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.recv_prev_group, + use_calc_stream=sync_recv, + ) + if sync_recv: + allgather_partial( + tensor_recv_prev, + nranks=mp_degree, + rank_id=mp_rank, + group=mp_group, + use_calc_stream=True, + ) + else: + tasks.append(task) + + if tensor_send_next is not None: + if isinstance(tensor_send_next, tuple): + for d in tensor_send_next: + paddle.distributed.wait(d, use_calc_stream=True) + send_partial( + d, + dst=1, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.send_next_group, + use_calc_stream=False, + ) + else: + paddle.distributed.wait(tensor_send_next, use_calc_stream=True) + send_partial( + tensor_send_next, + dst=1, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.send_next_group, + use_calc_stream=False, + ) + + if tensor_recv_next is not None: + if isinstance(tensor_recv_next, tuple): + for d in tensor_recv_next: + task = recv_partial( + d, + src=1, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.recv_next_group, + use_calc_stream=sync_recv, + ) + if sync_recv: + allgather_partial( + d, + nranks=mp_degree, + rank_id=mp_rank, + group=mp_group, + use_calc_stream=True, + ) + else: + tasks.append(task) + + else: + task = recv_partial( + tensor_recv_next, + src=1, + nranks=mp_degree, + rank_id=mp_rank, + group=_hcg.recv_next_group, + use_calc_stream=sync_recv, + ) + if sync_recv: + allgather_partial( + tensor_recv_next, + nranks=mp_degree, + rank_id=mp_rank, + group=mp_group, + use_calc_stream=True, + ) + else: + tasks.append(task) + + if not sync_recv: + if in_dygraph_mode(): + # wait irecv tasks in eager dygraph mode with new comm library + for task in tasks: + assert task is not None + task.wait() + + tensors_for_all_gather = [] + if tensor_recv_prev is not None: + if isinstance(tensor_recv_prev, tuple): + for d in tensor_recv_prev: + tensors_for_all_gather.append(d) + else: + tensors_for_all_gather.append(tensor_recv_prev) + if tensor_recv_next is not None: + if isinstance(tensor_recv_next, tuple): + for d in tensor_recv_next: + tensors_for_all_gather.append(d) + else: + tensors_for_all_gather.append(tensor_recv_next) + + for tensor in tensors_for_all_gather: + allgather_partial( + tensor, + nranks=mp_degree, + rank_id=mp_rank, + group=mp_group, + use_calc_stream=True, + ) + + return tensor_recv_prev, tensor_recv_next + + +def recv_forward(pp_first_stage, sync_recv=True): + if pp_first_stage: + input_tensor = None + else: + if not _send_recv_meta.has_recv_meta: + _send_recv_meta.recv_meta(_hcg.recv_prev_group) + _send_recv_meta.has_recv_meta = _use_cache + + input_tensor, _ = _p2p_helper( + tensor_send_next=None, + tensor_send_prev=None, + recv_prev=True, + recv_next=False, + sync_recv=sync_recv, + ) + return input_tensor + + +def recv_backward(pp_last_stage, sync_recv=True): + if pp_last_stage: + output_tensor_grad = None + else: + _, output_tensor_grad = _p2p_helper( + tensor_send_next=None, + tensor_send_prev=None, + recv_prev=False, + recv_next=True, + sync_recv=sync_recv, + ) + return output_tensor_grad + + +def send_forward(output_tensor, pp_last_stage): + if not pp_last_stage: + if not _send_recv_meta.has_send_meta: + _send_recv_meta.set_send_message(output_tensor) + _send_recv_meta.send_meta(output_tensor, _hcg.send_next_group) + _send_recv_meta.has_send_meta = _use_cache + + _p2p_helper( + tensor_send_next=output_tensor, + tensor_send_prev=None, + recv_prev=False, + recv_next=False, + ) + + +def send_backward(input_tensor_grad, pp_first_stage): + if not pp_first_stage: + _p2p_helper( + tensor_send_next=None, + tensor_send_prev=input_tensor_grad, + recv_prev=False, + recv_next=False, + ) + + +def send_forward_recv_backward(output_tensor, pp_last_stage): + if pp_last_stage: + output_tensor_grad = None + else: + _, output_tensor_grad = _p2p_helper( + tensor_send_next=output_tensor, + tensor_send_prev=None, + recv_prev=False, + recv_next=True, + ) + return output_tensor_grad + + +def send_backward_recv_forward(input_tensor_grad, pp_first_stage): + if pp_first_stage: + input_tensor = None + else: + input_tensor, _ = _p2p_helper( + tensor_send_next=None, + tensor_send_prev=input_tensor_grad, + recv_prev=True, + recv_next=False, + ) + return input_tensor + + +def send_forward_backward_recv_forward_backward( + output_tensor, input_tensor_grad, recv_prev, recv_next +): + # always have to send dytpe info to downstream + if not _send_recv_meta.has_send_meta: + _send_recv_meta.set_send_message(output_tensor) + _send_recv_meta.send_meta(output_tensor, _hcg.send_next_group) + _send_recv_meta.has_send_meta = _use_cache + if recv_prev and not _send_recv_meta.has_recv_meta: + _send_recv_meta.recv_meta(_hcg.recv_prev_group) + _send_recv_meta.has_recv_meta = _use_cache + input_tensor, output_tensor_grad = _p2p_helper( + tensor_send_next=output_tensor, + tensor_send_prev=input_tensor_grad, + recv_prev=recv_prev, + recv_next=recv_next, + sync_recv=False, + ) + return input_tensor, output_tensor_grad + + +def send_forward_recv_forward(output_tensor, recv_prev): + # always have to send dytpe info to downstream + if not _send_recv_meta.has_send_meta: + _send_recv_meta.set_send_message(output_tensor) + _send_recv_meta.send_meta(output_tensor, _hcg.send_next_group) + _send_recv_meta.has_send_meta = _use_cache + if recv_prev and not _send_recv_meta.has_recv_meta: + _send_recv_meta.recv_meta(_hcg.recv_prev_group) + _send_recv_meta.has_recv_meta = _use_cache + + input_tensor, _ = _p2p_helper( + tensor_send_next=output_tensor, + tensor_send_prev=None, + recv_prev=recv_prev, + recv_next=False, + sync_recv=False, + ) + + return input_tensor + + +def send_backward_recv_backward(input_tensor_grad, recv_next): + _, output_tensor_grad = _p2p_helper( + tensor_send_next=None, + tensor_send_prev=input_tensor_grad, + recv_prev=False, + recv_next=recv_next, + sync_recv=False, + ) + return output_tensor_grad diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c2008abb71c5371acfa55479e7cfb033380656a7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/pp_utils/utils.py @@ -0,0 +1,95 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + +FLOAT_TYPE_DICT = { + paddle.float16: "float16", + paddle.float32: "float32", + paddle.float64: "float64", +} + +PADDLE_TO_NUMBER = { + paddle.float16: 0, + paddle.float32: 1, + paddle.float64: 2, + paddle.int32: 3, + paddle.int64: 4 +} + +NUMBER_TO_DTYPE = { + 0: "float16", + 1: "float32", + 2: "float64", + 3: "int32", + 4: "int64" +} + + +def is_float_tensor(tensor): + """Is a float tensor""" + return tensor.dtype in FLOAT_TYPE_DICT.keys() + + +def get_tensor_dtype(dtype): + assert dtype in FLOAT_TYPE_DICT.keys() + return FLOAT_TYPE_DICT[dtype] + + +def paddle_2_number(dtype): + assert dtype in PADDLE_TO_NUMBER.keys() + return PADDLE_TO_NUMBER[dtype] + + +def number_2_dtype(number): + assert number in NUMBER_TO_DTYPE.keys() + return NUMBER_TO_DTYPE[number] + + +def get_tensor_bytes(tensor): + """Get the bytes a tensor occupied.""" + elem_size = None + if tensor.dtype == paddle.float32: + elem_size = 4 + elif tensor.dtype == paddle.float64: + elem_size = 8 + elif tensor.dtype == paddle.int64: + elem_size = 8 + elif tensor.dtype == paddle.int32: + elem_size = 4 + elif tensor.dtype == paddle.float16: + elem_size = 2 + elif tensor.dtype == paddle.int8: + elem_size = 1 + else: + raise ValueError("unknown data type: {}".format(tensor.dtype)) + return tensor.numel() * elem_size + + +def _all_gather(tensor, group=None, use_calc_stream=True): + """ + The main difference with paddle.distributed.all_gather: + no need to pass in tensor_list, the returned tensor is spliced + """ + if group is not None and not group.is_member(): + return + ring_id = 0 if group is None else group.id + nranks = paddle.distributed.collective._get_global_group( + ).nranks if group is None else group.nranks + return _legacy_C_ops.c_allgather(tensor, 'use_calc_stream', use_calc_stream, + 'ring_id', ring_id, 'nranks', nranks) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6bd8e1ee4e063b21cc5c1fab24d021db8f6f43 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2021 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. + +from .sharding_utils import Type, device_guard diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_optimizer_stage2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_optimizer_stage2.py new file mode 100644 index 0000000000000000000000000000000000000000..beda2401b7573e00659e4d01105e3c0e40fed82a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_optimizer_stage2.py @@ -0,0 +1,541 @@ +# Copyright (c) 2022 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/optim/oss.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import copy +import logging +import warnings + +import numpy as np +from collections import OrderedDict + +import paddle +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.optimizer import Optimizer +from paddle.fluid.clip import ClipGradByGlobalNorm +from paddle.distributed.collective import _get_global_group, new_group, broadcast, wait + +from .group_sharded_storage import ParamStorage, GradStorage +from .group_sharded_utils import Type, device_guard, GroupShardedClipGrad + +# CUDA alignment 256 bytes, cpu alignment 4096 bytes +alignment = {"gpu": 256, "cpu": 4096} +align = { + Type.fp16.value: 2, + Type.bf16.value: 2, + Type.fp32.value: 4, +} + + +class GroupShardedOptimizerStage2(Optimizer): + """ + A wrapper for Sharding Stage2 Optimizer in Dygraph. + + .. warning: ShardingOptimizer encapsulates the optimization strategy and integrates it into the optimizer. + + .. ZeRO: 1.https://arxiv.org/pdf/1910.02054.pdf 2.https://arxiv.org/pdf/1910.02054.pdf. + + """ + + # TODO (Baibaifan) + # Feature Notes: + # 1. Unified memory for parameters and parameters.grad to InternalStorage. + # 2. Support the segmentation of optimizer parameters and partial updating of parameters. + # 3. Dynamically adjust training parameters and models. + # 4. Support offload function. + # 5. Support the establishment of independent communication groups. + # 6. Broadcast_fp16 is not supported now. + def __init__(self, + params, + optim, + group=None, + offload=False, + device="gpu", + pertrain_sync_models=True, + **kw): + + super().__init__(learning_rate=optim._learning_rate, parameters=params) + assert core.is_compiled_with_cuda(), "Only GPU is supported now" + + # Segmentation information + self._dtype_rank_params = OrderedDict( + ) # {dtype:[param1,param2]} device, rank, params + self._param2rank = {} + self.__segment_params = [] + self._rank_buffer_size = {} # {dtype: {rank: numel+alignment}} + self._param2align = {} # {param.name: align} + + # Default information + self._optim = optim + + # sharing stage 2 comm overlap flag + self._reduce_overlap = False + # record the last task used for comm overlap for sharding stage 2 + self._comm_task = None + + assert hasattr(self._optim, "_master_weights" + ), "Must use optimizer with _master_weights attribute" + + # Support parameter group and parameter list + self._local_params = [] + if isinstance(params[0], dict): + for param_group in params: + self._local_params.extend(list(param_group["params"])) + else: + self._local_params.extend(list(params)) + + self._default_device = device + self._pfp16 = len( + list( + filter(lambda x: x.trainable and x.dtype == Type.fp16.value, + self._local_params))) > 0 + + self._broadcast_overlap = False + self._forward_pre_hook_remove_helper = [] + try: + # The fp32 params such as layer_norm_0.w_0 will be at the end of param_list. + # Have to sort the params to make sure all params are in the forward using order. + self._broadcast_order_params = sorted( + self.local_params, + key=lambda x: int(x.name.split('.')[0].split('_')[-1])) + except ValueError: + self._broadcast_order_params = None + + self._group = new_group( + _get_global_group().ranks) if group is None else group + + self.world_size = self._group.nranks + self._rank = self._group.rank + self._global_root_rank = self._group.ranks[0] + + # Synchronous all ranks models + if pertrain_sync_models: + self._sync_params_and_buffers() + + self.param_storages = {} # {dtype: {rank: InternalStorage}} + + if isinstance(self._optim._grad_clip, ClipGradByGlobalNorm): + logging.warning( + "While using ClipGradByGlobalNorm in GroupShardedOptimizerStage2, the grad clip of original optimizer will be changed." + ) + + self._optim._grad_clip = GroupShardedClipGrad( + self._optim._grad_clip, paddle.get_device(), self._group) + if self._optim._parameter_list and isinstance( + self._optim._parameter_list[0], dict): + for item in self._optim._param_groups: + if "grad_clip" in item.keys(): + item["grad_clip"] = self._optim._grad_clip + + if offload: + assert self._pfp16, "Only support offload strategy while using \'Adam\', \'AdamW\' and \'Momentum\' optimizer with AMP/Pure FP16" + + self.offload = offload # Using for offload + self.offload_device = "cpu" + self.offload_buffer_size = 0 + self.offload_param2align = {} + self.offload_params = None + self.offload_grads = None + self.dev_id = int(paddle.get_device().split(":")[1]) + + self._master_params = {} + + # Update optimizer parameters and adjust parameter storage and use according to rank. + self._update_opt_status() + + @paddle.autograd.no_grad() + def _sync_params_and_buffers(self): + """ + Sync all model states for all ranks + """ + + for p in self._local_params: + broadcast(p, + src=self._global_root_rank, + group=self._group, + sync_op=True) + + def _update_task(self, task): + if self._reduce_overlap: + assert task is not None + # Only track of the last reduce task. + # Since all tasks are on the same stream, only need to wait the last one. + # After waiting for the last reduce task, all reduce tasks before have already finished. + self._comm_task = task + + def _set_reduce_overlap(self, reduce_overlap): + # Enable gradients' reduces overlap with backward calculation. + self._reduce_overlap = reduce_overlap + + def _set_broadcast_overlap(self, + broadcast_overlap, + layers=None, + num_groups=None): + # Enable post optimizer broadcasts overlap with the forward calculation of next batch. + self._broadcast_overlap = broadcast_overlap + if self._broadcast_overlap: + assert layers is not None, \ + "To enable broadcast overlap forward, please pass the module to the function." + self._layers = layers + warnings.warn( + "Setting overlap broadcast means the `paddle.device.cuda.synchronize()` " + "must be called manually before calling `paddle.save()` and before and inference." + ) + if self._broadcast_order_params is None: + # Params' names should be like column_linear_32.w_0 patter to get the best performance. + warnings.warn( + "The param name passed to the optimizer doesn't follow .+_[0-9]+\..+ patter, " + "overlap broadcast may harm the performance.") + self._broadcast_order_params = self._local_params + + if num_groups is None or num_groups > len(self._broadcast_order_params): + warnings.warn( + "The num_groups for broadcast is larger than the number of params to be broadcast. " + "It will set to default value: 1 (use the default sharding group)." + ) + num_groups = 1 + + assert isinstance( + num_groups, + int) and num_groups > 0, "num_groups should be a positive integer" + + self._number_of_broadcast_groups = num_groups + self._broadcast_groups = [ + None for _ in range(self._number_of_broadcast_groups) + ] + self._broadcast_groups[0] = self._group + + ranks = self._group.ranks + for i in range(1, self._number_of_broadcast_groups): + self._broadcast_groups[i] = new_group(ranks) + + def _generate_master_params(self, trainable_params): + if self.offload: + for param in trainable_params: + if param.name not in self._master_params.keys(): + self._master_params[param.name] = core.eager.Tensor( + name=param.name, + value=param.cast(dtype=Type.fp32.value).numpy(), + place=core.CPUPlace(), + stop_gradient=param.stop_gradient) + else: + for param in trainable_params: + if param.dtype == Type.fp16.value: + master_tensor = paddle.cast(param, Type.fp32.value) + master_tensor.name = param.name + self._optim._master_weights[param.name] = master_tensor + + def _update_opt_status(self): + """Update optimizer status and parameter storage information, and special functions to be developed. + """ + # func 1 + self._integration_params() + + # Segement helpers + + def _segment_params(self): + """ + Divide all optimizer parameters equally into rank. + """ + if len(self.__segment_params) == 0: + self.__segment_params, param_lists = [ + [] for _ in range(self.world_size) + ], [[] for _ in range(self.world_size)] + sizes = [0] * self.world_size + for param in self._local_params: + # Add this param to rank with smallest size. + rank = sizes.index(min(sizes)) + param_lists[rank].append(param) + + # Statistical real numels + sizes[rank] += param._numel() if param.trainable else 0 + + for rank, params in enumerate(param_lists): + self.__segment_params[rank].extend(params) + return self.__segment_params + + @property + def local_params(self): + return self._local_params + + @property + def param2rank(self): + """Map the params to the rank which owns them""" + if len(self._param2rank) == 0: + for rank, params in enumerate(self._segment_params()): + for param in params: + self._param2rank[param.name] = rank + return self._param2rank + + @property + def dtype_rank_params(self): + """ + Divide the parameters into groups according to rank and dtype. + """ + if len(self._dtype_rank_params) == 0: + # Assign the parameters of each rank according to the type + trainable_params = list( + filter(lambda x: x.trainable, self._local_params)) + for param in trainable_params: + if param.dtype not in self._dtype_rank_params.keys(): + self._dtype_rank_params[param.dtype] = [ + [] for _ in range(self.world_size) + ] + self._dtype_rank_params[param.dtype][self.param2rank[ + param.name]].append(param) + + # Sort per rank params by size + for dtype in self._dtype_rank_params.keys(): + for rank_params in self._dtype_rank_params[dtype]: + rank_params.sort(key=lambda x: x._numel()) + + return self._dtype_rank_params + + @property + def rank_buffer_size(self): + """ + Count the memory size of the parameters corresponding to rank under the corresponding dtype. + """ + # CUDA alignment 256 bytes + if len(self._rank_buffer_size) == 0: + for dtype in self.dtype_rank_params.keys(): + if dtype not in self._rank_buffer_size.keys(): + self._rank_buffer_size[dtype] = {} + for dst_rank, per_rank_params in enumerate( + self.dtype_rank_params[dtype]): + if dst_rank not in self._rank_buffer_size[dtype].keys(): + self._rank_buffer_size[dtype][dst_rank] = 0 + for param in per_rank_params: + if not param.trainable: + continue + size = param._numel() * align[dtype] + remaining = size % alignment[self._default_device] + ali = 0 if remaining == 0 else alignment[ + self._default_device] - remaining + align_ = ali // align[dtype] + self._rank_buffer_size[dtype][dst_rank] += param._numel( + ) + align_ + self._param2align[param.name] = align_ + + return self._rank_buffer_size + + def _integration_params(self): + """ + Integrate the parameters into a continuous memory according to rank, and support the update of training parameters. + """ + + for dtype, per_rank_params in self.dtype_rank_params.items(): + if dtype not in self.param_storages.keys(): + self.param_storages[dtype] = {} + + for dst_rank, params in enumerate(per_rank_params): + if len(params) > 0: + + # Merge all the trainable params in a single InternalStorage + trainable_params = list( + filter(lambda x: x.trainable, params)) + if self._pfp16 and dst_rank == self._rank: + self._generate_master_params(trainable_params) + if trainable_params: + param_storage = ParamStorage( + size=self.rank_buffer_size[dtype][dst_rank], + dtype=dtype, + device=self._default_device) + + param_storage.add_rank_params(trainable_params, + self._param2align) + self.param_storages[dtype][dst_rank] = param_storage + + # Clear the InternalStorage keys which are not in use anymore + dtype_in_use = list(self.dtype_rank_params.keys()) + dtype_to_pop = list( + filter(lambda x: x not in dtype_in_use, self.param_storages.keys())) + for d in dtype_to_pop: + self.param_storages.pop(d) + + if self.offload: + self._optim._master_weights = self._master_params + cpu_master_params = [p for p in self._master_params.values()] + for param in cpu_master_params: + size = param._numel() * align[Type.fp32.value] + remaining = size % alignment[self.offload_device] + ali = 0 if remaining == 0 else alignment[ + self.offload_device] - remaining + align_ = ali // align[Type.fp32.value] + self.offload_buffer_size += param._numel() + align_ + self.offload_param2align[param.name] = align_ + + if cpu_master_params: + with device_guard(self._rank, self.offload_device): + self.offload_params = ParamStorage( + size=self.offload_buffer_size, + dtype=Type.fp32.value, + device=self.offload_device) + self.offload_params.buffer.name = "offload_buffer" + self.offload_params.add_rank_params( + cpu_master_params, self.offload_param2align, False) + self.offload_params.buffer.stop_gradient = False + + self.offload_grads = GradStorage( + size=self.offload_buffer_size, + dtype=Type.fp32.value, + device=self.offload_device, + destination=self._rank, + parm2align=self.offload_param2align, + convert_cpu=True) + for p in cpu_master_params: + self.offload_grads.add_grad( + p, self.offload_param2align[p.name]) + + self._optim._master_weights[ + self.offload_params.buffer. + name] = self.offload_params.buffer + + def _offload_acc_grad(self, param_name, grad_fp32_cpu): + """accumulate grads with offload strategy""" + with device_guard(self._rank, self.offload_device): + if param_name in self._master_params.keys(): + if self._master_params[param_name].grad is None: + self._master_params[param_name]._copy_gradient_from( + grad_fp32_cpu) + else: + self._master_params[param_name].grad.add_(grad_fp32_cpu) + + self.offload_params.buffer._copy_gradient_from( + self.offload_grads.buffer) + + def _offload_scale_grad(self, scale_size): + """scale grads with offload strategy""" + with device_guard(self._rank, self.offload_device): + self.offload_grads.buffer.scale_(scale=scale_size) + + def _offload_clear_grad(self): + """clear grads with offload strategy""" + with device_guard(self._rank, self.offload_device): + self.offload_grads.buffer.zero_() + + def step(self): + """ + A wrapper for Optimizer's step function to finish the update operation of the optimizer. + """ + # This method won't be called directly by opt.step()! + # The _redefine_opt_step() in class GroupShardedStage2 will wrap this function. + if self._broadcast_overlap: + # Clear the pre forward hook in the optimizer step. + for hook_remove in self._forward_pre_hook_remove_helper: + hook_remove.remove() + self._forward_pre_hook_remove_helper = [] + + if self.offload: + params_list = [self.offload_params.buffer] + + #TODO(Baibaifan): Offload will support param_groups later + if not isinstance(self._optim._param_groups[0], dict): + self._optim._parameter_list = params_list + self._optim._param_groups = params_list + + # Run the optimizer of the current rank step + if self.offload: + with device_guard(device=self.offload_device): + self._optim.step() + + for param in self._local_params: + if param.name in self._master_params.keys(): + param.set_value(self._master_params[param.name].cuda( + self.dev_id).cast(dtype=param.dtype)) + else: + self._optim.step() + + # Synchronize all the updated shards in between the ranks + self._broadcast_params() + + def minimize(self): + raise RuntimeError( + "optimizer.minimize() not support now, please use optimizer.step()") + + def set_state_dict(self, state_dict): + self._optim.set_state_dict(state_dict) + + def state_dict(self): + return self._optim.state_dict() + + def _clear_cache(self): + self.__segment_params.clear() + self._dtype_rank_params.clear() + self._param2rank.clear() + + @paddle.autograd.no_grad() + def _broadcast_params(self): + """Broadcast the parameters of the current rank to each rank""" + + # Exchange all the shards with the other ranks + if self._broadcast_overlap: + self._broadcast_params_overlap_forward() + else: + for dtype_per_rank in self.param_storages.values(): + for dst_rank, internal_storage in dtype_per_rank.items(): + broadcast(tensor=internal_storage.buffer, + src=self._group.ranks[dst_rank], + group=self._group, + sync_op=True) + + def _forward_pre_hook_function(self, tasks): + # Since the layers will call pre hook by `forward_pre_hook(self, inputs)`, + # the helper functions needs the x and y to take those params. + def __impl__(x, y): + for task in tasks: + # Wait for broadcast task before using the result of the broadcast. + task.wait() + + return __impl__ + + @paddle.autograd.no_grad() + def _broadcast_params_overlap_forward(self): + # Exchange all the shards with the other ranks, + # but overlap the broadcast with next batch's calculation. + group_idx = 0 + + param2task = {} + for x in self._broadcast_order_params: + if x.trainable: + group = self._broadcast_groups[group_idx] + group_idx = (group_idx + 1) % self._number_of_broadcast_groups + task = broadcast(tensor=x, + src=group.ranks[self._param2rank[x.name]], + group=group, + sync_op=False) + assert x.name not in param2task + param2task[x.name] = task + + for layer in self._layers.sublayers(): + if len(layer.sublayers()) == 0: + # Register forward pre hood for leaf layers. This will get the best performance. + tasks = [] + for param in layer.parameters(): + if param.trainable: + if param.name in param2task: + tasks.append(param2task[param.name]) + self._forward_pre_hook_remove_helper.append( + layer.register_forward_pre_hook( + self._forward_pre_hook_function(tasks))) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage2.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3ab817e91461d26fad680767d62352e4b10c6c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage2.py @@ -0,0 +1,571 @@ +# Copyright (c) 2022 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/data_parallel/sharded_ddp.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import time +import functools +import numpy as np +from functools import reduce +from collections import deque +from types import MethodType + +import paddle +from paddle import nn +from paddle.distributed import collective +from paddle.distributed.utils.log_utils import get_logger + +from .group_sharded_storage import GradStorage +from .group_sharded_optimizer_stage2 import GroupShardedOptimizerStage2 +from .group_sharded_utils import Taskflow, Type, device_guard + +logger_ = get_logger(logging.WARNING) + + +def _trainable(param): + return param.trainable + + +class GroupShardedStage2(nn.Layer): + """ + A wrapper for Sharding Stage2 Layer in Dygraph. + .. warning: GroupShardedStage2 encapsulates the layer strategy and integrates it into the nn.Layer. + .. ZeRO: https://arxiv.org/pdf/1910.02054.pdf. + """ + + # TODO (Baibaifan) + # Feature Notes:: + # 1. Unified memory for param and param.grad to InternalStorage. + # 2. Divide param.grad according to rank to centrally apply for and release GPU memory. + # 3. Dynamically adjust training parameters and models. + # 4. Support offload function. + # 5. Support the establishment of independent communication groups. + + def __init__( + self, + layer, + sharding_optimizer, + group=None, + sync_buffers=False, + buffer_max_size=2**23, #8MB + auto_refresh_trainable=True, + device="gpu"): + super().__init__() + + # training options + self._layer = layer + self._sharding_optimizers = [ + sharding_optimizer + ] if not isinstance(sharding_optimizer, list) else sharding_optimizer + assert all( + list( + map(lambda opt: isinstance(opt, GroupShardedOptimizerStage2), + self._sharding_optimizers)) + ), "Please use GroupShardedOptimizerStage2 optimizer" + self._sync_buffers = sync_buffers + self._auto_refresh_trainable = auto_refresh_trainable + + # Communication related attributes + self._group = collective.new_group( + collective._get_global_group().ranks) if group is None else group + self._world_size_scaling = 1.0 / self._group.nranks + assert self._group.nranks > 1, "Training must be distributed, ranks must be greater than 1" + self._rank = self._group.rank + self._global_root_rank = self._group.ranks[ + 0] # picking ranks index 0 as the reference + self._default_device = device + + # Global statistical parameters + self._all_params = [] + for optim in self._sharding_optimizers: + self._all_params.extend(list(optim.local_params)) + + # sharing stage 2 comm overlap flag + self._reduce_overlap = False + + self._grad_reduced = [] + self._trainable_param2rank = {} + self._trainable_param2align = {} + self._trainable_params = list( + filter(lambda x: x.trainable, self._all_params)) + self._trainable_mask = list(map(_trainable, self._trainable_params)) + self._param_grads = [] + + # Set grad storage size & Display param sizes and model sizes + model_size = sum([p._numel() for p in self._layer.parameters()]) + assert buffer_max_size >= 0, "buffer_max_size must be GE than 0." + self._buffer_max_size = self._rank_buffer_size(buffer_max_size, + model_size) + self._use_grad_storage = buffer_max_size > 0 + self._grad_storages = {} # {dtype: {rank: GradStorage}} + self._has_grad_storage = [] + self._grad_storage_list = [] + + # Offload + # TODO(haohongxiang): Now it's not be supported for multi-optimizers using Offload strategy + self._offload_optims = list( + filter(lambda optim: optim.offload, self._sharding_optimizers)) + if len(self._offload_optims) > 0: + assert len( + self._sharding_optimizers + ) == 1, "Only support offload strategy for single optimizer" + + self._offload = len(self._offload_optims) > 0 + self._offload_device = "cpu" + + # Set backward pass hooks + self._bw_hooks = [] + + # TODO (Baibaifan) Set tasks flow support asynchronous communicate + # self._tasks_flow = deque() + + # Define optimizer step and clear_grad + self._redefine_opt_step() + self._redefine_opt_clear() + + def forward(self, *inputs, **kwargs): + """ + A wrapper for Sharding Stage2 layer. + - Fresh trainable params or rebuild grad storage + - Sync layer's buffer params + - Clear all flags states + - Forward for origin layers + """ + + # Whether to need to reset trainable parameters + needs_fresh = len(self._bw_hooks) == 0 and self.training + + if self._auto_refresh_trainable: + needs_fresh |= self._detect_train_change() + + # Front hook + self._init_internal_storage(needs_fresh) + + # Sync layer's buffers state + if self._sync_buffers: + self.__sync_buffers() + + # Normal FW on the base model + fw = self._layer(*inputs, **kwargs) + + return fw + + def set_state_dict(self, state_dict, use_structured_name=True): + self._layer.set_state_dict(state_dict, + use_structured_name=use_structured_name) + + def state_dict(self, + destination=None, + include_sublayers=True, + structured_name_prefix=""): + return self._layer.state_dict( + destination=destination, + include_sublayers=include_sublayers, + structured_name_prefix=structured_name_prefix) + + def _clear_gradients(self): + """ + Set zero to the gradient of the optimizer's current rank trainable parameters. + """ + # Release grad storages + for dtype in self._grad_storages.keys(): + if not self._offload and self._rank in self._grad_storages[ + dtype].keys(): + self._grad_storages[dtype][self._rank].buffer.zero_() + + # Release grads of params + for param in self._trainable_params: + if param.name in self._param_grads and param.grad is not None: + param._zero_grads() + + # Release grads of master params with offload strategy + if self._offload: + self._sharding_optimizers[0]._offload_clear_grad() + + def _grad_scale(self): + """ + Before the gradient accumulation, scale the gradient. + """ + # Scale grad storages + for dtype in self._grad_storages.keys(): + if not self._offload and self._rank in self._grad_storages[ + dtype].keys(): + self._grad_storages[dtype][self._rank].buffer.scale_( + scale=self._world_size_scaling) + + # Scale grads of params + with paddle.no_grad(): + for param in self._trainable_params: + if param.name in self._param_grads and param.grad is not None: + param.grad.scale_(scale=self._world_size_scaling) + # param._reset_grad_inplace_version(True) + + # Scale grads of master params with offload strategy + if self._offload: + self._sharding_optimizers[0]._offload_scale_grad( + self._world_size_scaling) + + def _init_internal_storage(self, needs_fresh): + """ + Judge Fresh trainable params or rebuild grad storage. + """ + if needs_fresh: + self._fresh_trainable() + else: + self._build_grad_storages() + + # Clear all flags state + self._clear_counters() + + def to(self, device=None, dtype=None, blocking=True): + """ + Synchronously or asynchronously convert the data type of the layer, the device is not supported now. + """ + assert isinstance(device, str), "Device must be type str" + assert device == self._default_device, "New devices are not supported, because of the optimizer state is not sync" + + self._layer.to(device=device, dtype=dtype, blocking=blocking) + + # Re-build the buckets, hooks, etc.. + self._fresh_trainable() + + def _fresh_trainable(self): + """ Whether to update training parameters. """ + + # Make sure that this is not done while gradients are waiting to be reduced (if no_sync context for instance) + if reduce(lambda x, y: x or y, self._grad_reduced, False): + logging.warning("Grads waiting to be reduced.") + + self._trainable_params = list( + filter(lambda x: x.trainable, self._all_params)) + self._trainable_params.sort(key=lambda x: x._numel()) + + self._trainable_param2rank = {} + for optim in self._sharding_optimizers: + # Need to be wrappered for Sharding Stage2 Optimizer + if len(optim.param_storages.keys()) == 0: + optim._update_opt_status() + + # Get the parameters split by the optimizer according to rank + for per_rank_params in optim.dtype_rank_params.values( + ): # all the params from all ranks + for params in per_rank_params: + for param in filter(lambda x: x.trainable, params): + self._trainable_param2rank[ + param.name] = optim.param2rank[param.name] + self._trainable_param2align[ + param.name] = optim._param2align[param.name] + + # Create grad_storage + self._setup_use_grad_storage() + # setup backward hooks + self._setup_backward_hooks() + + @paddle.autograd.no_grad() + def __sync_buffers(self): + """ + Sync all the param buffers from all ranks (exp: batch norm statistics). + """ + + for buffer in self._layer.buffers(include_sublayers=True): + collective.broadcast(buffer, + self._global_root_rank, + self._group, + sync_op=True) + + def __getattr__(self, name): + """Forward missing attributes to wrapped layer.""" + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._layer, name) + + @paddle.autograd.no_grad() + def _clear_counters(self): + """Reset all the grad reduce and call counters.""" + if self.training: + self._grad_reduced = [True for _ in self._trainable_params] + + if self._use_grad_storage: + for grad_storage in self._grad_storage_list: + grad_storage.reset_checked_in() + + def _set_reduce_overlap(self, reduce_overlap): + # Hacky way to not add an extra parameter to the `group_sharded_parallel` funct. + # User should use this like: + # model, optimizer, scaler = group_sharded_parallel(...) + # model._set_reduce_overlap(True) + self._reduce_overlap = reduce_overlap + if self._reduce_overlap: + assert len( + self._sharding_optimizers + ) == 1, "Only support comm overlap strategy for single optimizer" + self._sharding_optimizers[0]._set_reduce_overlap(reduce_overlap) + + def _get_reduce_fn(self, index, param, dst_rank): + """ + There are two ways to reduce gradient. + - 1. Do not use self._use_grad_storage or exceeded buffer_max_size will be reduced separately. + - 2. Use grad_storage Reduce the storage to get the full gradient from different ranks. + """ + + if not self._use_grad_storage or not self._has_grad_storage[index]: + # Direct reduction + @paddle.autograd.no_grad() + def reduce(*_): + # Skip gradient reduction, do not change status information + if self._grad_reduced[index]: + assert param.grad is not None, "Parameter gradient cannot be None" + + # Change reduce information + self._grad_reduced[index] = False + + # Clear the gradient that does not belong to the current rank through the callback function + def cleanup(): + if dst_rank != self._rank: + param.clear_gradient(False) + elif self._offload: + tmp_grad = param.grad.cast( + dtype=Type.fp32.value).cpu() + + self._sharding_optimizers[0]._offload_acc_grad( + param.name, tmp_grad) + del tmp_grad + param.clear_gradient(False) + + # Synchronize the reduce parameter gradient asynchronize + self._sharding_optimizers[0]._update_task( + collective.reduce(tensor=param.grad, + dst=self._group.ranks[dst_rank], + group=self._group, + sync_op=not self._reduce_overlap)) + + # Clear the task flow and trigger callback to clear the redundant gradient + # self._clear_task_flow() + + cleanup() + + else: + # Buffer reduction + @paddle.autograd.no_grad() + def reduce(*_): + # Skip gradient reduction, do not change status information + if self._grad_reduced[index]: + assert param.grad is not None, "Parameter gradient cannot be None" + + # Change reduce information + self._grad_reduced[index] = False + grad_storage = self._grad_storages[param.dtype][dst_rank] + grad_storage.params_checked_in += 1 + + if grad_storage.all_checked_in: + assert grad_storage.buffer is not None + + # Clearing up the grad_storage buffer + def cleanup(): + if dst_rank != self._rank: + for p in grad_storage._params: + p.clear_gradient(False) + + grad_storage.buffer._clear_data() + elif self._offload: + grad_storage.to(device=self._offload_device) + for p in grad_storage._params: + with device_guard(): + tmp_grad = p.grad.cast( + dtype=Type.fp32.value) + self._sharding_optimizers[ + 0]._offload_acc_grad(p.name, tmp_grad) + p.clear_gradient(False) + grad_storage._device = self._default_device + grad_storage.buffer._clear_data() + + # Reduce the bucket + grad_storage.sent = True + # Synchronize the reduce parameter gradient asynchronize + self._sharding_optimizers[0]._update_task( + collective.reduce( + tensor=grad_storage.buffer, + dst=self._group.ranks[grad_storage.destination], + group=self._group, + sync_op=not self._reduce_overlap)) + + cleanup() + + # Clear the task flow and trigger callback to clear the redundant gradient + # self._clear_task_flow() + + return reduce + + def _setup_backward_hooks(self): + """ + Set the backward hook to synchronize the gradients of all rank by reduce group ranks. + """ + + # Remove previous backward hooks + while len(self._bw_hooks) > 0: + self._bw_hooks.pop().remove() + + # Go through the parameters, attach the hook + if not self.training: + return + + for index, param in enumerate(self._trainable_params): + dst_rank = self._trainable_param2rank[param.name] + + reduce_function = self._get_reduce_fn(index, param, dst_rank) + + self._bw_hooks.append( + param._register_backward_hook(reduce_function)) + + def _setup_use_grad_storage(self): + """ + Integrate the parameters gradient into a continuous memory according to rank, and support the update of training parameters. + """ + + # According to parameters's numel sort, allocate memory of parameter gradient to continuous memory according to rank + self._grad_storages = {} + self._has_grad_storage = [False for _ in self._trainable_params] + + for index, param in enumerate(self._trainable_params): + dst_rank = self._trainable_param2rank[param.name] + + if param.dtype not in self._grad_storages.keys(): + self._grad_storages[param.dtype] = {} + + if dst_rank not in self._grad_storages[param.dtype].keys(): + self._grad_storages[param.dtype][dst_rank] = GradStorage( + self._buffer_max_size[param.dtype], + dtype=param.dtype, + device=self._default_device, + destination=dst_rank, + parm2align=self._trainable_param2align) + + # Criteria to decide whether this parameter is to be put in GradStorage + if self._grad_storages[param.dtype][dst_rank].can_add_grad_view( + param, self._trainable_param2align[param.name]): + self._grad_storages[param.dtype][dst_rank].add_grad( + param, self._trainable_param2align[param.name]) + self._has_grad_storage[index] = True + else: + self._param_grads.append(param.name) + print( + "Can not add param: {}, param's shape: {}, param align: {}, grad_storages fill: {}, " + .format(param.name, param.shape, + self._trainable_param2align[param.name], + self._grad_storages[param.dtype][dst_rank]._fill)) + + for dtype in self._grad_storages.keys(): + self._grad_storage_list.extend( + list(self._grad_storages[dtype].values())) + + # def _clear_task_flow(self): + # """Try to consume the previous tasks.""" + # while len(self._tasks_flow) > 0: + # task = self._tasks_flow.popleft() + # task.wait() + # if task.callback is not None: + # task.callback() + + def _detect_train_change(self): + # Current trainable parameters + trainable_mask = list(map(_trainable, self._trainable_params)) + + # Whether parameters trainability changed + trainability_changed = trainable_mask != self._trainable_mask + + if trainability_changed: + logging.warning( + "Trainable params changed, because of eval/train mode or parameter freezing/unfreeze." + ) + self._trainable_mask = trainable_mask + + return trainability_changed + + def _build_grad_storages(self): + """ + Rebuild grad storages. + """ + # Rebuild fp16/fp32 grad storages + for dtype in self._grad_storages.keys(): + for dst_rank, grad_storage in self._grad_storages[dtype].items(): + if self._offload or dst_rank != self._rank: + grad_storage.manumal_relase() + grad_storage.rebuild() + + def _rank_buffer_size(self, buffer_max_size, model_size): + """ + Generate the minimum buffer size for each rank & Display param sizes and model sizes. + """ + + # Initialize buffer size + rank_buffer_size = {} + for shard_opt in self._sharding_optimizers: + if shard_opt.rank_buffer_size: + for dtype in shard_opt.rank_buffer_size.keys(): + sizes = max(shard_opt.rank_buffer_size[dtype].values()) + rank_buffer_size[dtype] = min(sizes, buffer_max_size) + + if Type.fp16.value in rank_buffer_size.keys(): + # FP16 GradStorage and model size + logger_.info( + "====== FP16 GradStorage size: {:.2f}M parameters, Model size {:.2f}M parameters ======" + .format(rank_buffer_size[Type.fp16.value] / 2**19, + model_size / 2**19)) + if Type.bf16.value in rank_buffer_size.keys(): + # FP16 GradStorage and model size + logger_.info( + "====== BF16 GradStorage size: {:.2f}M parameters, Model size {:.2f}M parameters ======" + .format(rank_buffer_size[Type.bf16.value] / 2**19, + model_size / 2**19)) + if Type.fp32.value in rank_buffer_size.keys(): + # FP32 GradStorage and model size + logger_.info( + "====== FP32 GradStorage size: {:.2f}M parameters, Model size {:.2f}M parameters ======" + .format(rank_buffer_size[Type.fp32.value] / 2**18, + model_size / 2**18)) + return rank_buffer_size + + def _redefine_opt_step(self): + grad_func = self._grad_scale + for opt in self._sharding_optimizers: + opt_step = opt.step + + def _opt_step(self): + if self._reduce_overlap: + # Wait for the last reduce task. This wait must before grad scale function. + assert self._comm_task is not None + self._comm_task.wait() + grad_func() + opt_step() + + opt.step = MethodType(_opt_step, opt) + + def _redefine_opt_clear(self): + clear_func = self._clear_gradients + + def _opt_clear(self): + clear_func() + + for opt in self._sharding_optimizers: + opt.clear_grad = MethodType(_opt_clear, opt) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage3.py new file mode 100644 index 0000000000000000000000000000000000000000..b628378140f785f678f8939171f4ea1370ab2cf2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_stage3.py @@ -0,0 +1,920 @@ +# Copyright (c) 2022 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. + +import time +import logging +import numpy as np +from types import MethodType +from collections import OrderedDict + +import paddle +from paddle import nn +from paddle.autograd import PyLayer +import paddle.fluid.core as core +import paddle.fluid.framework as framework +from paddle.fluid.framework import EagerParamBase +from paddle.fluid.clip import ClipGradByGlobalNorm +from paddle.distributed import collective + +from .group_sharded_storage import GradStorage +from .group_sharded_utils import Type, GroupShardedClipGrad, device_guard + + +def _all_gather(tensor, buffer_size, group): + """ + The main difference with paddle.distributed.all_gather: + no need to pass in tensor_list, the returned tensor is spliced + """ + + assert group is not None + if framework.in_dygraph_mode(): + out = paddle.zeros([buffer_size], dtype=tensor.dtype) + task = group.process_group.all_gather(tensor, out) + return out, task + + +# CUDA alignment 256 bytes +alignment = { + "gpu": 256, +} +align = { + Type.fp16.value: 2, + Type.fp32.value: 4, +} + +global CHECK_LAYER +CHECK_LAYER = dict() # Help to check layer's id -> layer's name + + +class GroupShardedStage3(nn.Layer): + """ + A wrapper for Sharding Stage3 Layer in Dygraph. + + .. warning: GroupShardedStage3 encapsulates the layer strategy and integrates it into the nn.Layer. + + .. ZeRO: https://arxiv.org/pdf/1910.02054.pdf. + """ + + # TODO (Baibaifan) + # Feature Notes:: + # 1. The model supports the segmentation of parameters by global ranks in layers. + # 2. Support communication flow and computing flow. + # 3. Support offload function. + # 4. Support the establishment of independent communication groups. + + def __init__(self, + layer, + optimizer, + group=None, + sync_buffers=False, + device="gpu", + segment_size=2**20, + pertrain_sync_models=True, + offload=False, + sync_comm=False): + super().__init__() + + # Default configs + assert core.is_compiled_with_cuda(), "Only support CUDA." + self._layer = layer + self._default_device = device + self.__sync_buffers = sync_buffers + self._offload = offload + self._sync_comm = sync_comm + # segmentation size + assert segment_size >= 0, "segment_size must be GE than 0." + self._segment_size = segment_size + + global DEV + DEV = "cpu" if paddle.get_device() == "cpu" else paddle.get_device( + ).split(":")[0] + global DEV_ID + DEV_ID = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + global param2dtype + param2dtype = dict() + + # Communication group establishment + self._group = collective.new_group( + collective._get_global_group().ranks) if group is None else group + self._world_size_scaling = 1.0 / self._group.nranks + assert self._group.nranks > 1, "Training must be distributed, ranks must be greater than 1." + self._rank = self._group.rank + self._global_root_rank = self._group.ranks[ + 0] # picking ranks index 0 as the reference + + # Parameter segmentation for global ranks + # After flatten -> self._param2buffer_size, self._param2buffer, self._trainable_params + self._param2buffer_size = dict() # {param.name: size} + self._param2buffer = dict( + ) # {param.name: [(start0, end0),(start1, end1), ...]} + self._trainable_params = dict() # {id(layer): [trainable_params]} + self._unslice_params = set() # param's numel <= segment_size + self._unslice_params2align = dict() # {param.name: param's align} + self._grad_storages = dict() # {param.dtype: GradStorage} + + assert not isinstance( + optimizer, list), "Multiple optimizers are not supported now." + self._optim = _OptimizerWrapper(optimizer, self._offload, self._group, + self._update_params_slice) + self._ori_parameter_list = self._optim._parameter_list + self._ori_param_groups = self._optim._param_groups + + # Replace optimizer's _grad_clip + if isinstance(self._optim._grad_clip, ClipGradByGlobalNorm): + logging.warning( + "While using ClipGradByGlobalNorm in GroupShardedStage3, the grad clip of original optimizer will be changed." + ) + self._optim._grad_clip = GroupShardedClipGrad( + self._optim._grad_clip, paddle.get_device(), self._group) + if self._optim._parameter_list and isinstance( + self._optim._parameter_list[0], dict): + for item in self._optim._param_groups: + if "grad_clip" in item.keys(): + item["grad_clip"] = self._optim._grad_clip + + # Synchronous all ranks models + if pertrain_sync_models: + self._sync_params_and_buffers() + + self._segment_rank_params(self._layer) + + # Add unslice params to master_weight in fp16 + self._handle_unslice_params() + + # In the first step, record the execution order of the layer + self._order_tracer = OrderedDict() + self._order_tracer["order"] = 0 + self._order_tracer["layer"] = list() + + # Register task flow + self._task_flow = TaskFlow() + + # Register forward hooks + self._register_forward_hooks(self._layer) + + # Register backward parameter hooks + self._register_backward_hooks() + + # Redefine optimizer step and clear function + self._redefine_opt_step() + self._redefine_opt_clear() + + @paddle.autograd.no_grad() + def _sync_params_and_buffers(self): + """ + Sync all model states for all ranks + """ + + for p in self._layer.parameters(): + collective.broadcast(p, + src=self._global_root_rank, + group=self._group, + sync_op=True) + + def _clear_gradients(self): + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + # 1.Handle param's slice + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + for param in trainable_params: + assert hasattr(param, "fw_storage" + ), "Find {} don't have fw_storage attribute.".format( + param.name) + + param.fw_storage.clear_gradient(False) + param.bw_storage._clear() + param.bw_storage = None + # 2.Handle unslice param + if not self._offload: + for grad_storage in self._grad_storages.values(): + grad_storage.buffer.zero_() + else: + for param in list(self._unslice_params): + param.clear_gradient(False) + tmp_var = param.cuda(DEV_ID) + + if tmp_var.dtype == Type.fp32.value and param2dtype[ + param.name] == Type.fp16.value: + tmp_var = paddle.cast(tmp_var, Type.fp16.value) + tmp_var._share_buffer_to(param) + del tmp_var + for grad_storage in self._grad_storages.values(): + grad_storage.manumal_relase() + grad_storage.rebuild() + + # Update param memery slice + def _update_params_slice(self): + update_list = self._update_params() + + if not isinstance(self._optim._param_groups[0], dict): + slice_params = [param.fw_storage for param in update_list] + self._optim._parameter_list = slice_params + list( + self._unslice_params) + self._optim._param_groups = slice_params + list( + self._unslice_params) + else: + for param_group in self._optim._param_groups: + p_group = [] + for p in param_group['params']: + if hasattr(p, "fw_storage"): + p_group.append(p.fw_storage) + else: + p_group.append(p) + + param_group['params'] = p_group + + def forward(self, *inputs, **kwargs): + """ + A wrapper for Sharding Stage3 layer. + """ + # 1.Sync layer's buffers state + if self.__sync_buffers: + self._sync_buffers() + + # 2.Normal FW on the base model + fw = self._layer(*inputs, **kwargs) + + return fw + + def set_state_dict(self, state_dict, use_structured_name=True): + self._layer.set_state_dict(state_dict, + use_structured_name=use_structured_name) + + def state_dict(self, + destination=None, + include_sublayers=True, + structured_name_prefix=""): + return self._layer.state_dict( + destination=destination, + include_sublayers=include_sublayers, + structured_name_prefix=structured_name_prefix) + + def _handle_unslice_params(self): + buffer_size = dict() + buffer_size[Type.fp32.value] = 0 + buffer_size[Type.fp16.value] = 0 + for param in self._unslice_params: + # Updata optimizer master weights + if param.dtype == Type.fp16.value and not self._offload: + master_tensor = paddle.cast(param, Type.fp32.value) + master_tensor.name = param.name + self._optim._master_weights[param.name] = master_tensor + if self._offload: + param.master_weight = paddle.cast(param, Type.fp32.value).cpu() + param2dtype[param.name] = param.dtype + p_align = self._param2align(param) + self._unslice_params2align[param.name] = p_align + buffer_size[param.dtype] += param._numel() + p_align + + # Create unslice_params'grad + for param in sorted(list(self._unslice_params), key=lambda p: p.name): + if param.dtype not in self._grad_storages.keys(): + self._grad_storages[param.dtype] = GradStorage( + buffer_size[param.dtype], + dtype=param.dtype, + device=self._default_device, + destination=self._rank, + parm2align=self._unslice_params2align) + self._grad_storages[param.dtype].add_grad( + param, self._unslice_params2align[param.name]) + + def _segment_rank_params(self, layer, name="last_layer"): + """ + Flatten parameters according to layer. + """ + current_layer_params = _current_layer_params(layer) + if current_layer_params: + CHECK_LAYER[id(layer)] = name + self._flatten_layer_params(layer, current_layer_params) + + for name, sub_layer in layer.named_children(): + self._segment_rank_params(sub_layer, name) + + def _flatten_layer_params(self, layer, current_layer_params): + """ + Parameter segmentation and memory integration. + """ + + def _add_manage_info(trainable_param): + return _PartitionParam(trainable_param) + + current_params = list() + for p in current_layer_params: + if p.trainable and p._numel() > self._segment_size: + current_params.append(_add_manage_info(p)) + elif p.trainable: + self._unslice_params.add(_UnsliceParam(p)) + + assert id(layer) not in self._trainable_params.keys() + self._trainable_params[id(layer)] = current_params + + for param in self._trainable_params[id(layer)]: + if param.name in self._param2buffer.keys(): + continue + self._param2buffer[param.name] = [] + # 1.Params alignment + align_ = self._param2align(param) + + offset = align_ + param._numel() + buffer_size = offset if offset % self._group.nranks == 0 else offset + self._group.nranks - ( + offset % self._group.nranks) + self._param2buffer_size[param.name] = buffer_size + + # 2.Combination param buffer + assert buffer_size % self._group.nranks == 0 + pre_buffer = buffer_size // self._group.nranks + + for rank_ in range(self._group.nranks): + self._param2buffer[param.name].append( + (rank_ * pre_buffer, (rank_ + 1) * pre_buffer)) + + # Record param's dtype + param2dtype[param.name] = param.dtype + # 3.Flatten layer params and release other rank buffer + self._param_storage(param, buffer_size) + + def _param_storage(self, param, buffer_size): + """ + This is a function to simplify the handling of parameter InternalStorages. + """ + assert isinstance(buffer_size, int) + value = np.zeros( + buffer_size, + dtype=np.float16) if Type.fp16.value == param.dtype else np.zeros( + buffer_size, dtype=np.float32) + buffer = core.eager.Tensor(value=value, place=core.CPUPlace()) + + param_shape = param.shape + origin_state = param.stop_gradient + param.stop_gradient = True + param.flatten_() + param.stop_gradient = origin_state + start, end = self._param2buffer[param.name][self._rank] + + # Copy the current param value + with device_guard(): + tmp_var = buffer._slice(0, param._numel()) + param_cpu = param.cpu() + tmp_var.get_tensor().set(param_cpu.get_tensor(), core.CPUPlace()) + del tmp_var + param.get_tensor()._set_dims(param_shape) + + # Current rank param_storage + if self._offload: + with device_guard(): + tmp_tensor = buffer._slice(start, end) + param.fw_storage = core.eager.Tensor(value=tmp_tensor, + place=core.CPUPlace(), + name="slice@" + param.name) + with device_guard(): + param.master_weight = paddle.cast(param.fw_storage, + Type.fp32.value) + else: + param.fw_storage = core.eager.Tensor(value=buffer._slice( + start, end), + name="slice@" + param.name) + param.status = "part" + + # Updata optimizer master weights + if param.dtype == Type.fp16.value and not self._offload: + master_tensor = paddle.cast(param.fw_storage, Type.fp32.value) + master_tensor.name = param.name + self._optim._master_weights[param.fw_storage.name] = master_tensor + param._clear_data() + + def _register_forward_hooks(self, layer): + """ + Register PyLayer to manage memory slices. + There are four stages: + FW + 1. Before the forward layers, synchronize the full parameters. + 2. After the forward layers, release the full parameter and keep the parameter slice. + BW + 3. Before the backward layers, synchronize the full parameters and create param's grad. + 4. After the gradient accumulation, release the full parameter and keep the parameter slice. + """ + current_layer_params = _current_layer_params(layer) + if current_layer_params: + self._register_forward_all_hooks(layer, self._task_flow) + + for _, sub_layer in layer.named_children(): + self._register_forward_hooks(sub_layer) + + def _register_forward_all_hooks(self, sub_layer, task_flow): + + def _forward_pre_hook(layer, inputs): + return ForwardPreHooks(layer, self._order_tracer, + self._trainable_params, + self._param2buffer_size, self._group, + self._sync_comm, self._offload, task_flow) + + def _forward_post_hook(layer, inputs, outputs): + return ForwardPostHooks.apply(outputs, layer, self._order_tracer, + self._trainable_params, + self._param2buffer, + self._param2buffer_size, self._rank, + self._group, self._sync_comm, + self._offload, task_flow) + + # register previous forward hooks + sub_layer.register_forward_pre_hook(_forward_pre_hook) + + # register post forward hooks + sub_layer.register_forward_post_hook(_forward_post_hook) + + @paddle.autograd.no_grad() + def _sync_buffers(self): + """ + Sync all the param buffers from all ranks (exp: batch norm statistics). + """ + + for buffer in self._layer.buffers(include_sublayers=True): + collective.broadcast(buffer, + self._global_root_rank, + self._group, + sync_op=True) + + def __getattr__(self, name): + """Forward missing attributes to wrapped layer.""" + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._layer, name) + + def _update_params(self): + """ + Update parameters to optimizer memory slice. + """ + update_list = [] + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + # 1.Handle param's slice + for param in trainable_params: + assert hasattr( + param, + "fw_storage"), "Find {} don't have fw_storage attribute".format( + param.name) + # Gradient average + if self._offload: + with device_guard(): + param.bw_storage.scale_(scale=self._world_size_scaling) + else: + param.bw_storage.scale_(scale=self._world_size_scaling) + param.fw_storage = _VarBaseWrapper(param) + assert param.fw_storage.grad is None + param.fw_storage._copy_gradient_from(param.bw_storage) + update_list.append(param) + + # 2.Handle unslice param + for grad_storage in self._grad_storages.values(): + grad_storage.buffer.scale_(scale=self._world_size_scaling) + collective.all_reduce(tensor=grad_storage.buffer, group=self._group) + if self._offload: + for param in list(self._unslice_params): + param._clear_data() + param.master_weight._share_buffer_to(param) + + for grad_storage in self._grad_storages.values(): + for p in grad_storage._params: + tmp_g = _device2cpu(p.grad, convert_dtype=True) + p.clear_gradient(False) + p._copy_gradient_from(tmp_g) + del tmp_g + grad_storage.buffer._clear() + + return update_list + + def get_all_parameters(self, convert2cpu=False): + """ + Get the full parameters and return the corresponding task flows. + """ + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + t_flow = _allgather_buffer(trainable_params, + self._group, + param2buffer_size=self._param2buffer_size, + use_calc_stream=True, + task_flow=TaskFlow(), + sync_wait=True, + offload=self._offload, + convert2cpu=convert2cpu) + if convert2cpu: + for param in trainable_params: + t_flow.full_param[param.name][0]._share_buffer_to(param) + + self._optim._parameter_list = self._ori_parameter_list + self._optim._param_groups = self._ori_param_groups + + def _register_backward_hooks(self): + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + + for param in trainable_params: + allreduce_function = self._get_allreduce_fn(param) + param._register_backward_hook(allreduce_function) + + def _get_allreduce_fn(self, param): + + @paddle.autograd.no_grad() + def allreduce_(*_): + if param.name in self._task_flow.full_grad.keys(): + full_grad = self._task_flow.full_grad[param.name] + # Only support sync allreduce current rank's layer now + collective.all_reduce(tensor=full_grad, group=self._group) + + start, end = self._param2buffer[param.name][self._rank] + if param.bw_storage is None: + param.bw_storage = full_grad._slice(start, + end).detach().clone() + if self._offload: + param.bw_storage = _device2cpu(param.bw_storage, True) + else: + if self._offload: + cpu_grad = _device2cpu( + full_grad._slice(start, end).detach().clone(), True) + with device_guard(): + param.bw_storage = paddle.add( + param.bw_storage, cpu_grad) + else: + param.bw_storage = paddle.add( + param.bw_storage, + full_grad._slice(start, end).detach().clone()) + param.clear_gradient(False) + del self._task_flow.full_grad[param.name] + + if param.name in self._task_flow.full_param.keys(): + if param.status == "all": + param.use_count = 0 + param._clear_data() + start, end = self._param2buffer[param.name][self._rank] + param.fw_storage = self._task_flow.full_param[ + param.name][0]._slice(start, end).detach().clone() + param.status = "part" + del self._task_flow.full_param[param.name] + + if self._offload: + param.fw_storage._clear_data() + param.master_weight._share_buffer_to(param.fw_storage) + + return allreduce_ + + def _param2align(self, param): + # CUDA alignment 256 bytes + size = param._numel() * align[param.dtype] + remaining = size % alignment[self._default_device] + ali = 0 if remaining == 0 else alignment[ + self._default_device] - remaining + align_ = ali // align[param.dtype] + return align_ + + def _redefine_opt_step(self): + params_slice_func = self._update_params_slice + opt_step = self._optim.step + + def _opt_step(self): + if not self.update_scaler: + params_slice_func() + if self.offload: + with device_guard(): + opt_step() + else: + opt_step() + + def _opt_minimize(self): + raise RuntimeError( + "optimizer.minimize() not support now, please use optimizer.step()" + ) + + self._optim.step = MethodType(_opt_step, self._optim) + self._optim.minimize = MethodType(_opt_minimize, self._optim) + + def _redefine_opt_clear(self): + clear_func = self._clear_gradients + + def _opt_clear(self): + clear_func() + + self._optim.clear_grad = MethodType(_opt_clear, self._optim) + + +def ForwardPreHooks(layer, order_tracer, trainable_params, param2buffer_size, + group, sync_comm, offload, task_flow): + + # Record layer's id + layer_id = id(layer) + use_calc, sync_wait = False, False + + if layer_id not in order_tracer.keys() or sync_comm: + use_calc, sync_wait = True, True + + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + else: + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + # wait current layer params + _wait_layer(trainable_params[layer_id], task_flow, group, + param2buffer_size, use_calc, offload) + + if layer_id == order_tracer["layer"][-1]: return + order_ = order_tracer[layer_id] + layer_id = order_tracer["layer"][order_ + 1] + + _allgather_buffer(trainable_params[layer_id], + group, + param2buffer_size=param2buffer_size, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + + return + + +class ForwardPostHooks(PyLayer): + + @staticmethod + def forward(ctx, inputs, layer, order_tracer, trainable_params, + param2buffer, param2buffer_size, rank, group, sync_comm, + offload, task_flow): + + layer_id = id(layer) + # release current layer full params + _release_param(trainable_params[layer_id], param2buffer, rank, + task_flow, offload) + + if layer_id not in order_tracer.keys(): + order_ = order_tracer["order"] + order_tracer[layer_id] = order_ + order_tracer["order"] += 1 + order_tracer["layer"].append(layer_id) + + #Record fw info + ctx.order_tracer = order_tracer + ctx.task_flow = task_flow + ctx.group = group + ctx.layer_id = layer_id + ctx.sync_comm = sync_comm + ctx.trainable_params = trainable_params + ctx.param2buffer_size = param2buffer_size + ctx.offload = offload + + return inputs + + @staticmethod + def backward(ctx, *args): + # Load context value + order_tracer = ctx.order_tracer + task_flow = ctx.task_flow + group = ctx.group + layer_id = ctx.layer_id + trainable_params = ctx.trainable_params + param2buffer_size = ctx.param2buffer_size + sync_comm = ctx.sync_comm + offload = ctx.offload + use_calc, sync_wait = False, False + + # Allgather params synchronization + if sync_comm: + use_calc, sync_wait = True, True + _allgather_buffer(trainable_params[layer_id], + group, + param2buffer_size=param2buffer_size, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + else: + _wait_layer(trainable_params[layer_id], task_flow, group, + param2buffer_size, use_calc, offload) + + # Create params's grad + _create_params_grad(trainable_params[layer_id], param2buffer_size, + task_flow) + + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + if layer_id != order_tracer["layer"][0] and not sync_comm: + layer_next_id = order_tracer["layer"][order_tracer[layer_id] - 1] + _allgather_buffer(trainable_params[layer_next_id], + group, + param2buffer_size=param2buffer_size, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + + return args + + +class TaskFlow: + """ + Task flows, one way linked list for task acquisition. + """ + + def __init__(self, + full_param=dict(), + full_grad=dict(), + use_calc=dict(), + callback=None): + self.full_param = full_param + self.full_grad = full_grad + self.use_calc = use_calc + self.callback = callback + + +def _release_param(trainable_params, + param2buffer, + rank, + task_flow, + offload=False): + for param in trainable_params: + # async communicate share weight not clear + param.use_count -= 1 + if param.use_count == 0: + param._clear_data() + if param.name in task_flow.full_param.keys(): + start, end = param2buffer[param.name][rank] + with paddle.amp.auto_cast(enable=False): + param.fw_storage = task_flow.full_param[ + param.name][0]._slice(start, end).detach().clone() + param.status = "part" + del task_flow.full_param[param.name] + + if offload: + param.fw_storage = _device2cpu(param.fw_storage) + return + + +def _wait_layer(trainable_params, + task_flow, + group, + param2buffer_size, + use_calc_stream, + offload=False): + + for param in trainable_params: + if param.status == "all": + param.use_count += 1 + continue + if param.name in task_flow.full_param.keys(): + full_param, task = task_flow.full_param[param.name] + task.wait() + full_param._slice(0, param._numel())._share_buffer_to(param) + param.fw_storage._clear() + param.fw_storage = None + param.status = "all" + param.use_count += 1 + else: + _allgather_buffer(trainable_params, + group, + param2buffer_size=param2buffer_size, + use_calc_stream=True, + task_flow=task_flow, + sync_wait=True, + offload=offload) + break + return task_flow + + +def _allgather_buffer(trainable_params, + group, + param2buffer_size, + use_calc_stream, + task_flow, + sync_wait=False, + offload=False, + convert2cpu=False): + + for param in trainable_params: + if param.status == "all": + param.use_count += 1 + continue + + if offload: + param.fw_storage = _cpu2device(param) + + buffer_size = param2buffer_size[param.name] + with paddle.amp.auto_cast(enable=False): + full_param, task = _all_gather(param.fw_storage, buffer_size, group) + + # Allgather current layer in the 1st step synchronously + if sync_wait: + with paddle.amp.auto_cast(enable=False): + task.wait() + full_param._slice(0, param._numel())._share_buffer_to(param) + param.fw_storage._clear() + param.fw_storage = None + param.status = "all" + param.use_count += 1 + task_flow.full_param[param.name] = (full_param, task) + + # parameter converts to cpu + if convert2cpu: + p_name = param.name + param = _device2cpu(param) + del task_flow.full_param[p_name] + task_flow.full_param[p_name] = (param, None) + + return task_flow + + +@paddle.autograd.no_grad() +def _create_params_grad(trainable_params, param2buffer_size, task_flow): + for param in trainable_params: + if param.name in task_flow.full_grad.keys(): + continue + assert isinstance(param2buffer_size[param.name], int) + temp_grad = paddle.zeros([param2buffer_size[param.name]], + dtype=param.dtype) + temp_tensor = temp_grad._slice(0, param._numel()) + temp_tensor.get_tensor()._set_dims(param.shape) + param._copy_gradient_from(temp_tensor) + del temp_tensor + task_flow.full_grad[param.name] = temp_grad + return task_flow + + +def _PartitionParam(param): + if not hasattr(param, "fw_storage"): + setattr(param, "fw_storage", None) + setattr(param, "bw_storage", None) + setattr(param, "master_weight", None) + setattr(param, "status", "all") + setattr(param, "use_count", 0) + return param + + +def _UnsliceParam(param): + if not hasattr(param, "unslice"): + setattr(param, "unslice", True) + setattr(param, "master_weight", None) + return param + + +def _VarBaseWrapper(param): + varbase = param.fw_storage + tmp_param = EagerParamBase(shape=varbase.shape, + dtype=varbase.dtype, + name="slice@" + param.name) + varbase._share_buffer_to(tmp_param) + tmp_param.regularizer = param.regularizer + tmp_param.optimize_attr['learning_rate'] = param.optimize_attr[ + 'learning_rate'] + varbase._clear() + return tmp_param + + +def _OptimizerWrapper(optimizer, offload, group, update_params_slice): + if not hasattr(optimizer, "_optim"): + setattr(optimizer, "_optim", optimizer) + setattr(optimizer, "offload", offload) + setattr(optimizer, "_group", group) + setattr(optimizer, "update_scaler", None) + setattr(optimizer, "update_slice", update_params_slice) + return optimizer + + +def _device2cpu(trans_param, convert_dtype=False): + if convert_dtype: + trans_param = paddle.cast(trans_param, Type.fp32.value) + tmp_p = trans_param.cpu() + trans_param._clear_data() + return tmp_p + + +def _cpu2device(param): + tmp_p = param.fw_storage.cuda(DEV_ID) + if tmp_p.dtype == Type.fp32.value and param2dtype[ + param.name] == Type.fp16.value: + tmp_p = paddle.cast(tmp_p, Type.fp16.value) + return tmp_p + + +def _current_layer_params(layer): + return layer.parameters( + include_sublayers=False) + list(layer.extra_parameters) if hasattr( + layer, "extra_parameters") else layer.parameters( + include_sublayers=False) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_storage.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..5b9ab7343f08ca244217160c2f15299d8a72511c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_storage.py @@ -0,0 +1,322 @@ +# Copyright (c) 2022 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/misc/param_bucket.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import os +import time +import numpy as np + +import paddle +from paddle.fluid import core +from .group_sharded_utils import Type, device_guard + + +class InternalStorage: + """ + This is a basic class, which is responsible for consolidating the basic storage tensor. + + """ + + # Support integration parameter tensor + def __init__(self, size, dtype, device, convert_cpu=False): + self._params = [] + self._param_ids = [] + self._fill = 0 + self._device = device + self._dtype = dtype + + # The flatten tensor + size = [size] if isinstance(size, int) else size + if convert_cpu: + value = np.zeros( + size, + dtype=np.float16) if Type.fp16.value == dtype else np.zeros( + size, dtype=np.float32) + self.buffer = core.eager.Tensor(value=value, place=core.CPUPlace()) + if dtype == Type.bf16.value: + self.buffer = paddle.cast(self.buffer, dtype=paddle.bfloat16) + else: + self.buffer = paddle.zeros(size, dtype=dtype) + + self.dev_id = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + assert self.buffer is not None, "Cannot move a collapsed bucket, please rebuild it" + assert (dtype == Type.fp32.value + or Type.fp16.value), "Conversion type is not supported now" + + if self._device != device: + tmp_buffer = self.buffer.cuda( + self.dev_id) if device == "gpu" else self.buffer.cpu() + for param in self._params: + param.clear_gradient(False) + + del self.buffer + self.buffer = tmp_buffer + self._device = device + + if dtype is not None: + self.buffer = self.buffer.cast(dtype=dtype) + self._dtype = dtype + + +class ParamStorage(InternalStorage): + """ + This is a basic class to simplify the handling of parameter InternalStorages. + """ + + def __init__(self, size, dtype, device): + super().__init__(size, dtype, device, convert_cpu=True) + self.param2align = None + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + + super().to(device, dtype) + + if keep_alignment: + self._array_params() + + @paddle.autograd.no_grad() + def add_rank_params(self, trainable_params, param2align, convert_gpu=True): + """ + Add new parameters to the InternalStorage. Params becomes a view of this InternalStorage buffer. + """ + + assert all([ + id(param) not in self._param_ids for param in trainable_params + ]), "The same param cannot be checked in twice" + assert self.buffer is not None + + self.param2align = param2align + + cpu_param_shape = list() + for param in trainable_params: + p_shape = self._add_param_as_view(param, param2align[param.name], + convert_gpu) + cpu_param_shape.append(p_shape) + + if convert_gpu: + # buffer convert from cpu to cuda + self.buffer = self.buffer.cuda(self.dev_id) + + self._fill = 0 + + for idx, param in enumerate(trainable_params): + self._convert_buffer(param, cpu_param_shape[idx], + param2align[param.name]) + self._params.append(param) + self._param_ids.append(id(param)) + + @paddle.autograd.no_grad() + def _add_param_as_view(self, param, align, convert_gpu=True): + + assert ( + param.dtype == self.buffer.dtype + ), "Different types for the InternalStorage and the param, cannot proceed: {} - {}".format( + param.dtype, self.buffer.dtype) + + var_end = self._fill + param._numel() + offset = var_end + align + assert offset <= self.buffer._numel() + + p_shape = param.shape + + origin_state = param.stop_gradient + param.stop_gradient = True + param.flatten_() + param.stop_gradient = origin_state + + # Copy the current param value + + with device_guard(self.dev_id, "cpu"): + tmp_var = self.buffer._slice(self._fill, var_end) + if convert_gpu: + param_cpu = param.cpu() + param._clear_data() + tmp_var.set_value(param_cpu) + else: + tmp_var.set_value(param) + del tmp_var + + self._fill = offset + return p_shape + + @paddle.autograd.no_grad() + def _convert_buffer(self, param, p_shape, align): + + var_end = self._fill + np.prod(p_shape).tolist() + offset = var_end + align + assert offset <= self.buffer._numel() + + # Convert the param value + with device_guard(self.dev_id, self._device): + tmp_tensor = self.buffer._slice(self._fill, var_end) + tmp_tensor._share_buffer_to(param) + param.get_tensor()._set_dims(p_shape) + + self._fill = offset + + @paddle.autograd.no_grad() + def _array_params(self): + """ + Given the parameters which have been registered previously, rebuild the whole InternalStorage. + """ + assert len(self._params) > 0 + assert self.param2align is not None + + self._fill = 0 + for p in self._params: + self._convert_buffer(p, p.shape, self.param2align[p.name]) # modify + + +class GradStorage(InternalStorage): + """ + This is a basic class to simplify the handling of gradient InternalStorages + """ + + def __init__(self, + size, + dtype, + device, + destination, + parm2align, + convert_cpu=False): + if isinstance(size, np.int64): + size = size.tolist() + super().__init__(size, dtype, device, convert_cpu) + + self._max_size = size + self._release = False + + self.params_checked_in = 0 + self.destination = destination + self._parm2align = parm2align + self.sent = False + + def reset_checked_in(self): + """ Reset the counter of the parameter grads which have been checked in + """ + self.params_checked_in = 0 + self.sent = False + + @property + def all_checked_in(self): + """ Judge all the expected gradient check-in happened """ + return len(self._params) == self.params_checked_in + + def can_add_grad_view(self, param, align): + """ Is there enough InternalStorage to add this parameter gradient, and whether this param have already checked in. + """ + return self._fill + param._numel() + align <= self._max_size and id( + param) not in self._param_ids + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + if self._release: + self.rebuild() + + super().to(device, dtype) + + if keep_alignment: + self._array_grads() + + @paddle.autograd.no_grad() + def add_grad(self, param, align): + """ + Add a new parameter gradient to the InternalStorage. Param.grad becomes a view of this InternalStorage buffer. + """ + + assert id( + param + ) not in self._param_ids, "The same gradients cannot be checked in twice" + + self._add_grad_as_view(param, align) + self._params.append(param) + self._param_ids.append(id(param)) + + @paddle.autograd.no_grad() + def manumal_relase(self): + """ + Release the buffer from InternalStorage. The InternalStorage will need to be rebuilt before use. + """ + if not self._release: + for p in self._params: + if p.grad is not None: + p.clear_gradient(False) + + self.buffer = None + self._fill = 0 + self.params_checked_in = 0 + self._release = True + + @paddle.autograd.no_grad() + def rebuild(self): + """ + Given the parameter gradients which have been registered previously, rebuild the whole InternalStorage. + """ + + if self._release: + self.buffer = paddle.zeros([self._max_size], dtype=self._dtype) + + for p in self._params: + self._add_grad_as_view(p, self._parm2align[p.name]) + + self._release = False + + @paddle.autograd.no_grad() + def _array_grads(self): + """ + Given the parameters gradients which have been registered previously, rebuild the whole InternalStorage. + """ + if len(self._params) > 0: + self._fill = 0 + for p in self._params: + self._add_grad_as_view(p, self._parm2align[p.name]) + + @paddle.autograd.no_grad() + def _add_grad_as_view(self, param, align): + assert param._numel( + ) > 0, "Cannot add a gradient to a released InternalStorage, please rebuild" + assert param.dtype == self.buffer.dtype + + grad_end = self._fill + param._numel() + offset = grad_end + align + assert offset <= self.buffer._numel() + + # Copy the current grad value to InternalStorage + with device_guard(self.dev_id, self._device): + tmp_var = self.buffer._slice(self._fill, grad_end) + tmp_var.get_tensor()._set_dims(param.shape) + param._copy_gradient_from(tmp_var) + del tmp_var + + self._fill = offset diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb7b1e8784aa9e912a6963abf29fa287486b9f0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/group_sharded_utils.py @@ -0,0 +1,232 @@ +# Copyright (c) 2022 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. + +import os +import contextlib +from enum import Enum +import numpy as np +from types import MethodType + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid import layers +from paddle.fluid.dygraph import to_variable +from paddle.fluid.framework import dygraph_only + + +class Taskflow: + """ + Task flows, one way linked list for task acquisition. + """ + + def __init__(self, task, callback): + self.task = task + self.callback = callback + + +class Type(Enum): + """ + Type of trainable parameters + """ + fp16 = paddle.float16 + bf16 = paddle.bfloat16 + fp32 = paddle.float32 + + +class GroupShardedClipGrad: + + def __init__(self, clip, device, group): + self._clip = clip + self._device = device + self._group = group + + @paddle.autograd.no_grad() + def _dygraph_clip(self, params_grads): + sum_square_fp32, sum_square_fp16 = [], [] + unslice_params_fp32, unslice_params_fp16 = [], [] + + for p, g in params_grads: + p_slice = True # using for slice parameter in sharding stage3 + if g is None or getattr(p, 'need_clip', True) is False: + continue + if hasattr(p, "unslice"): + p_slice = False + + merge_grad = g + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.get_tensor_from_selected_rows( + layers.merge_selected_rows(g)) + square = layers.square(merge_grad) + sum_square = layers.reduce_sum(square) + + if p.dtype == paddle.float16: + if p_slice: sum_square_fp16.append(sum_square) + else: unslice_params_fp16.append(sum_square) + elif p.dtype == paddle.float32: + if p_slice: sum_square_fp32.append(sum_square) + else: unslice_params_fp32.append(sum_square) + + # global norm of non-distributed FP16 params_and_grads + if len(sum_square_fp16) == 0: + global_norm_fp16 = paddle.to_tensor([0.], dtype=paddle.float32) + else: + global_norm_fp16 = layers.concat(sum_square_fp16) + global_norm_fp16 = layers.reduce_sum(global_norm_fp16) + global_norm_fp16 = paddle.cast(global_norm_fp16, + dtype=paddle.float32) + + # global norm of non-distributed FP16 params_and_grads for unslice parameters + if len(unslice_params_fp16) == 0: + global_unslice_fp16 = paddle.to_tensor([0.], dtype=paddle.float32) + else: + global_unslice_fp16 = layers.concat(unslice_params_fp16) + global_unslice_fp16 = layers.reduce_sum(global_unslice_fp16) + global_unslice_fp16 = paddle.cast(global_unslice_fp16, + dtype=paddle.float32) + + # global norm of non-distributed FP32 params_and_grads + global_norm_fp32 = layers.concat( + sum_square_fp32) if len(sum_square_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_norm_fp32 = layers.reduce_sum(global_norm_fp32) + + # global norm of non-distributed FP32 params_and_grads for unslice parameters + global_unslice_fp32 = layers.concat(unslice_params_fp32) if len( + unslice_params_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_unslice_fp32 = layers.reduce_sum(global_unslice_fp32) + global_unslice_var = global_unslice_fp16 + global_unslice_fp32 + + global_norm_var = global_norm_fp16 + global_norm_fp32 + 1.0 / self._group.nranks * global_unslice_var + + # add all reduce to get global norm of distributed params_and_grads + dev_id = int(self._device.split(":")[1]) + if paddle.device.get_device() == "cpu": + global_norm_var = global_norm_var.cuda(dev_id) + + with device_guard(dev_id, "gpu"): + paddle.distributed.all_reduce(global_norm_var, group=self._group) + + global_norm_var = layers.sqrt(global_norm_var) + max_global_norm = layers.fill_constant(shape=[1], + dtype=global_norm_var.dtype, + value=self.clip_norm) + + clip_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=global_norm_var, + y=max_global_norm)) + clip_var_fp16 = paddle.cast(clip_var, paddle.float16) + + for p, g in params_grads: + if getattr(p, 'need_clip', True) is False or g is None: + continue + origin_state = g.stop_gradient + g.stop_gradient = True + if p.dtype == paddle.float16: + g.scale_(clip_var_fp16.item()) + else: + g.scale_(clip_var.item()) + g.stop_gradient = origin_state + # p._reset_grad_inplace_version(True) + + return params_grads + + def __getattr__(self, item): + return getattr(self._clip, item) + + def __call__(self, params_grads): + return self._dygraph_clip(params_grads) + + +@contextlib.contextmanager +def device_guard(dev_id=0, device="cpu"): + origin_device = paddle.device.get_device() + if device == "cpu": + paddle.set_device(device) + elif device == "gpu": + paddle.set_device("gpu:{}".format(dev_id)) + try: + yield + finally: + paddle.set_device(origin_device) + + +@dygraph_only +def GroupShardedScaler(scaler): + + def unscale_method(self, optimizer): + if not self._enable: + return + param_grads = [] + param_grads_fp16 = [] + param_grads_fp32 = [] + if hasattr(optimizer, "update_slice"): + optimizer.update_slice() + optimizer.update_scaler = True + + if getattr(optimizer._optim, '_param_groups', None) and isinstance( + optimizer._optim._param_groups[0], dict): + + for group in optimizer._optim._param_groups: + for param in group['params']: + if param.grad is not None: + param_grads.append(param.grad) + if param.grad.dtype in [ + core.VarDesc.VarType.FP16, paddle.float16 + ]: + param_grads_fp16.append(param.grad) + else: + param_grads_fp32.append(param.grad) + else: + for param in optimizer._optim._parameter_list: + if param.grad is not None: + param_grads.append(param.grad) + if param.grad.dtype in [ + core.VarDesc.VarType.FP16, paddle.float16 + ]: + param_grads_fp16.append(param.grad) + else: + param_grads_fp32.append(param.grad) + + temp_found_inf_fp16 = to_variable(np.array([0]).astype(np.bool_)) + temp_found_inf_fp32 = to_variable(np.array([0]).astype(np.bool_)) + + device = "cpu" if optimizer.offload else "gpu" + dev_id = 0 if device == "cpu" else int( + paddle.get_device().split(":")[1]) + + with device_guard(dev_id, device): + if len(param_grads_fp16): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp16, + self._scale, + param_grads_fp16, + temp_found_inf_fp16) + if len(param_grads_fp32): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp32, + self._scale, + param_grads_fp32, + temp_found_inf_fp32) + + self._found_inf = 1 if temp_found_inf_fp16 or temp_found_inf_fp32 else 0 + is_found_inf = paddle.to_tensor([self._found_inf], dtype="int32") + + paddle.distributed.all_reduce(is_found_inf, + op=paddle.distributed.ReduceOp.MAX, + group=optimizer._group) + self._found_inf = is_found_inf.numpy()[0] + + scaler._unscale = MethodType(unscale_method, scaler) + return scaler diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py new file mode 100644 index 0000000000000000000000000000000000000000..a08e67456e5e6f77e3dd1358d004927b47f75f40 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py @@ -0,0 +1,554 @@ +# Copyright (c) 2021 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/data_parallel/sharded_ddp.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import os +import contextlib +import logging +import time +import functools +import numpy as np +from itertools import chain +from functools import reduce +from collections import deque +from types import MethodType + +import paddle +from paddle import nn +from paddle.distributed import collective as dist +from paddle.distributed.collective import _get_global_group + +from ...utils.internal_storage import GradStorage +from ...meta_optimizers.dygraph_optimizer.sharding_optimizer_stage2 import ShardingOptimizerStage2 +from .sharding_utils import Taskflow, Type + + +def _trainable(param): + return param.trainable + + +class ShardingStage2(nn.Layer): + """ + A wrapper for Sharding Stage2 Layer in Dygraph. + .. warning: ShardingStage2 encapsulates the layer strategy and integrates it into the nn.Layer. + .. ZeRO: https://arxiv.org/pdf/1910.02054.pdf. + """ + + # TODO (Baibaifan) + # Feature Notes:: + # 1. Unified memory for param and param.grad to InternalStorage. + # 2. Divide param.grad according to rank to centrally apply for and release GPU memory. + # 3. Dynamically adjust training parameters and models. + # 4. Support offload function. + # 5. Support the establishment of independent communication groups. + + def __init__( + self, + layer, + sharding_optimizer, + group=None, + sync_buffers=False, + buffer_max_size=2**23, #8MB + auto_refresh_trainable=True, + device="gpu"): + super().__init__() + + # training options + self._layer = layer + self._sharding_optimizers = [ + sharding_optimizer + ] if not isinstance(sharding_optimizer, list) else sharding_optimizer + assert all( + list( + map(lambda opt: isinstance(opt, ShardingOptimizerStage2), + self._sharding_optimizers)) + ), "Please use ShardingOptimizerStage2 optimizer" + self._sync_buffers = sync_buffers + self._auto_refresh_trainable = auto_refresh_trainable + + # Communication related attributes + self._group = dist.new_group( + _get_global_group().ranks) if group is None else group + self._world_size_scaling = 1.0 / self._group.nranks + assert self._group.nranks > 1, "Training must be distributed, ranks must be greater than 1" + self._rank = self._group.rank + self._global_root_rank = self._group.ranks[ + 0] # picking rank 0 as the reference + self._default_device = device + + # Global statistical parameters + self._all_params = list( + chain(*[optim.local_params for optim in self._sharding_optimizers])) + self._trainable_params = [] + self._grad_reduced = [] + self._trainable_param2rank = {} + self._trainable_param2align = {} + self._trainable_mask = list(map(_trainable, self._all_params)) + self._param_grads = [] + + # Set grad storage size & Display param sizes and model sizes + model_size = sum([np.prod(p.shape) + for p in self._layer.parameters()]).item() + assert buffer_max_size >= 0, "buffer_max_size must be GE than 0." + self._buffer_max_size = self._rank_buffer_size(buffer_max_size, + model_size) + self._use_grad_storage = buffer_max_size > 0 + self._grad_storages = {} # {dtype: {rank: GradStorage}} + self._has_grad_storage = [] + self._grad_storage_list = [] + + # Offload + # TODO(haohongxiang): Now it's not be supported for multi-optimizers using Offload strategy + self._offload_optims = list( + filter(lambda optim: optim.offload, self._sharding_optimizers)) + if len(self._offload_optims) > 0: + assert len( + self._sharding_optimizers + ) == 1, "Only support offload strategy for single optimizer" + + self._offload = self._sharding_optimizers[0].offload + self._offload_device = "cpu" + + # Set backward pass hooks + self._bw_hooks = [] + + # Set tasks flow + self._tasks_flow = deque() + + # Define optimizer step and clear_grad + self._redefine_opt_step() + self._redefine_opt_clear() + + def forward(self, *inputs, **kwargs): + """ + A wrapper for Sharding Stage2 layer. + - Fresh trainable params or rebuild grad storage + - Sync layer's buffer params + - Clear all flags states + - Forward for origin layers + """ + + # Whether to need to reset trainable parameters + needs_fresh = len(self._bw_hooks) == 0 and self.training + + if self._auto_refresh_trainable: + needs_fresh |= self._detect_train_change() + + # Front hook + self._init_internal_storage(needs_fresh) + + # Sync layer's buffers state + if self._sync_buffers: + self.__sync_buffers() + + # Normal FW on the base model + fw = self._layer(*inputs, **kwargs) + + return fw + + def set_state_dict(self, state_dict, use_structured_name=True): + self._layer.set_state_dict(state_dict, + use_structured_name=use_structured_name) + + def state_dict(self, + destination=None, + include_sublayers=True, + structured_name_prefix=""): + return self._layer.state_dict(destination=None, + include_sublayers=True, + structured_name_prefix="") + + def _clear_gradients(self): + """ + Set zero to the gradient of the optimizer's current rank trainable parameters. + """ + # Release grad storages + for dtype in self._grad_storages.keys(): + if not self._offload and self._rank in self._grad_storages[ + dtype].keys(): + self._grad_storages[dtype][self._rank].buffer.zero_() + + # Release grads of params + for param in self._trainable_params: + if param.name in self._param_grads and param.grad is not None: + param.clear_gradient() + + # Release grads of master params with offload strategy + if self._offload: + self._sharding_optimizers[0]._offload_clear_grad() + + def _grad_scale(self): + """ + Before the gradient accumulation, scale the gradient. + """ + # Scale grad storages + for dtype in self._grad_storages.keys(): + if not self._offload and self._rank in self._grad_storages[ + dtype].keys(): + self._grad_storages[dtype][self._rank].buffer.scale_( + scale=self._world_size_scaling) + + # Scale grads of params + for param in self._trainable_params: + if param.name in self._param_grads and param.grad is not None: + param.grad.scale_(scale=self._world_size_scaling) + param._reset_grad_inplace_version(True) + + # Scale grads of master params with offload strategy + if self._offload: + self._sharding_optimizers[0]._offload_scale_grad( + self._world_size_scaling) + + def _init_internal_storage(self, needs_fresh): + """ + Judge Fresh trainable params or rebuild grad storage. + """ + if needs_fresh: + self._fresh_trainable() + else: + self._build_grad_storages() + + # Clear all flags state + self._clear_counters() + + def to(self, device=None, dtype=None, blocking=True): + """ + Synchronously or asynchronously convert the data type of the layer, the device is not supported now. + """ + assert isinstance(device, str), "Device must be type str" + assert device == self._default_device, "New devices are not supported, because of the optimizer state is not sync" + + self._layer.to(device=device, dtype=dtype, blocking=blocking) + + # Re-build the buckets, hooks, etc.. + self._fresh_trainable() + + def _fresh_trainable(self): + """ Whether to update training parameters. """ + + # Make sure that this is not done while gradients are waiting to be reduced (if no_sync context for instance) + if reduce(lambda x, y: x or y, self._grad_reduced, False): + logging.warning("Grads waiting to be reduced.") + + self._trainable_params = list( + filter(lambda x: x.trainable, self._all_params)) + self._trainable_params.sort(key=lambda x: np.prod(x.shape)) + + self._trainable_param2rank = {} + for optim in self._sharding_optimizers: + # Need to be wrappered for Sharding Stage2 Optimizer + if len(optim.param_storages.keys()) == 0: + optim.update_opt_status() + + # Get the parameters split by the optimizer according to rank + for per_rank_params in optim.dtype_rank_params.values( + ): # all the params from all ranks + for params in per_rank_params: + for param in filter(lambda x: x.trainable, params): + self._trainable_param2rank[ + param.name] = optim.param2rank[param.name] + self._trainable_param2align[ + param.name] = optim._param2align[param.name] + + self._setup_use_grad_storage() + + # wait next func hook support + self._setup_backward_hooks() + + @paddle.autograd.no_grad() + def __sync_buffers(self): + """ + Sync all the param buffers from all ranks (exp: batch norm statistics). + """ + + for buffer in self._layer.buffers(include_sublayers=True): + dist.broadcast(buffer, + self._global_root_rank, + self._group, + sync_op=True) + # Multi stream operation will be supported later + dist.wait(tensor=buffer, group=self._group, use_calc_stream=True) + + def __getattr__(self, name): + """Forward missing attributes to wrapped layer.""" + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._layer, name) + + @paddle.autograd.no_grad() + def _clear_counters(self): + """Reset all the grad reduce and call counters.""" + if self.training: + self._grad_reduced = [True for _ in self._trainable_params] + + if self._use_grad_storage: + for grad_storage in self._grad_storage_list: + grad_storage.reset_checked_in() + + def _get_reduce_fn(self, index, param, dst_rank): + """ + There are two ways to reduce gradient. + - 1. Do not use self._use_grad_storage or exceeded buffer_max_size will be reduced separately. + - 2. Use grad_storage Reduce the storage to get the full gradient from different ranks. + """ + + if not self._use_grad_storage or not self._has_grad_storage[index]: + # Direct reduction + @paddle.autograd.no_grad() + def reduce(*_): + # Skip gradient reduction, do not change status information + if self._grad_reduced[index]: + assert param.grad is not None, "Parameter gradient cannot be None" + + # Change reduce information + self._grad_reduced[index] = False + + # Clear the gradient that does not belong to the current rank through the callback function + def cleanup(): + if dst_rank != self._rank: + param.clear_gradient(False) + elif self._offload: + self._sharding_optimizers[0]._offload_acc_grad( + param.name, + param.grad.cast(dtype=Type.fp32.value).cpu()) + param.clear_gradient(False) + + # Synchronize the reduce parameter gradient + self._tasks_flow.append( + Taskflow(task=dist.reduce( + tensor=param.grad, + dst=self._group.ranks[dst_rank], + group=self._group, + sync_op=True), + callback=cleanup)) + + # Multi stream operation will be supported later + dist.wait(tensor=param.grad, + group=self._group, + use_calc_stream=True) + + # Clear the task flow and trigger callback to clear the redundant gradient + self._clear_task_flow() + + else: + # Buffer reduction + @paddle.autograd.no_grad() + def reduce(*_): + # Skip gradient reduction, do not change status information + if self._grad_reduced[index]: + assert param.grad is not None, "Parameter gradient cannot be None" + + # Change reduce information + self._grad_reduced[index] = False + grad_storage = self._grad_storages[param.dtype][dst_rank] + grad_storage.params_checked_in += 1 + + if grad_storage.all_checked_in: + assert grad_storage.buffer is not None + + # Clearing up the grad_storage buffer + def cleanup(): + if dst_rank != self._rank: + for p in grad_storage._params: + p.clear_gradient(False) + p._gradient_set_empty(False) + + grad_storage.buffer.value().get_tensor()._clear( + ) + elif self._offload: + grad_storage.to(device=self._offload_device) + for p in grad_storage._params: + self._sharding_optimizers[ + 0]._offload_acc_grad( + p.name, + p.grad.cast(dtype=Type.fp32.value)) + p.clear_gradient(False) + p._gradient_set_empty(False) + grad_storage._device = self._default_device + grad_storage.buffer.value().get_tensor()._clear( + ) + + # Reduce the bucket + grad_storage.sent = True + self._tasks_flow.append( + Taskflow(task=dist.reduce( + tensor=grad_storage.buffer, + dst=self._group.ranks[grad_storage.destination], + group=self._group, + sync_op=True), + callback=cleanup)) + + # Multi stream operation will be supported later + dist.wait(tensor=grad_storage.buffer, + group=self._group, + use_calc_stream=True) + + # Clear the task flow and trigger callback to clear the redundant gradient + self._clear_task_flow() + + return reduce + + def _setup_backward_hooks(self): + """ + Set the backward hook to synchronize the gradients of all rank by reduce group ranks. + """ + + # Remove previous backward hooks + while len(self._bw_hooks) > 0: + self._bw_hooks.pop().remove() + + # Go through the parameters, attach the hook + if not self.training: + return + + for index, param in enumerate(self._trainable_params): + dst_rank = self._trainable_param2rank[param.name] + + reduce_function = self._get_reduce_fn(index, param, dst_rank) + + self._bw_hooks.append( + param._register_backward_hook(reduce_function)) + + def _setup_use_grad_storage(self): + """ + Integrate the parameters gradient into a continuous memory according to rank, and support the update of training parameters. + """ + + # According to parameters's numel sort, allocate memory of parameter gradient to continuous memory according to rank + self._grad_storages = {} + self._has_grad_storage = [False for _ in self._trainable_params] + + for index, param in enumerate(self._trainable_params): + dst_rank = self._trainable_param2rank[param.name] + + if param.dtype not in self._grad_storages.keys(): + self._grad_storages[param.dtype] = {} + + if dst_rank not in self._grad_storages[param.dtype].keys(): + self._grad_storages[param.dtype][dst_rank] = GradStorage( + self._buffer_max_size[param.dtype], + dtype=param.dtype, + device=self._default_device, + destination=dst_rank, + parm2align=self._trainable_param2align) + + # Criteria to decide whether this parameter is to be put in GradStorage + if self._grad_storages[param.dtype][dst_rank].can_add_grad_view( + param, self._trainable_param2align[param.name]): + self._grad_storages[param.dtype][dst_rank].add_grad( + param, self._trainable_param2align[param.name]) + self._has_grad_storage[index] = True + else: + self._param_grads.append(param.name) + print( + "Can not add param: {}, param's shape: {}, param align: {}, grad_storages fill: {}, " + .format(param.name, param.shape, + self._trainable_param2align[param.name], + self._grad_storages[param.dtype][dst_rank]._fill)) + + self._grad_storage_list = list( + chain(*[ + self._grad_storages[dtype].values() + for dtype in self._grad_storages.keys() + ])) + + def _clear_task_flow(self): + """Try to consume the previous tasks.""" + while len(self._tasks_flow) > 0: + task = self._tasks_flow.popleft() + if task.callback is not None: + task.callback() + + def _detect_train_change(self): + # Current trainable parameters + trainable_mask = list(map(_trainable, self._all_params)) + + # Whether parameters trainability changed + trainability_changed = trainable_mask != self._trainable_mask + + if trainability_changed: + logging.warning( + "Trainable params changed, because of eval/train mode or parameter freezing/unfreeze." + ) + self._trainable_mask = trainable_mask + + return trainability_changed + + def _build_grad_storages(self): + """ + Rebuild grad storages. + """ + # Rebuild fp16/fp32 grad storages + for dtype in self._grad_storages.keys(): + for dst_rank, grad_storage in self._grad_storages[dtype].items(): + if self._offload or dst_rank != self._rank: + grad_storage.manumal_relase() + grad_storage.rebuild() + + def _rank_buffer_size(self, buffer_max_size, model_size): + """ + Generate the minimum buffer size for each rank & Display param sizes and model sizes. + """ + + # Initialize buffer size + rank_buffer_size = {} + for shard_opt in self._sharding_optimizers: + if shard_opt.rank_buffer_size: + for dtype in shard_opt.rank_buffer_size.keys(): + sizes = max(shard_opt.rank_buffer_size[dtype].values()) + rank_buffer_size[dtype] = min(sizes, buffer_max_size) + + if Type.fp16.value in rank_buffer_size.keys(): + # FP16 GradStorage and model size + print( + "====== FP16 GradStorage size: {:.2f}M parameters, Model size {:.2f}M parameters ======" + .format(rank_buffer_size[Type.fp16.value] / 2**19, + model_size / 2**19)) + if Type.fp32.value in rank_buffer_size.keys(): + # FP32 GradStorage and model size + print( + "====== FP32 GradStorage size: {:.2f}M parameters, Model size {:.2f}M parameters ======" + .format(rank_buffer_size[Type.fp32.value] / 2**18, + model_size / 2**18)) + return rank_buffer_size + + def _redefine_opt_step(self): + grad_func = self._grad_scale + for opt in self._sharding_optimizers: + opt_step = opt.step + + def _opt_step(self): + grad_func() + opt_step() + + opt.step = MethodType(_opt_step, opt) + + def _redefine_opt_clear(self): + clear_func = self._clear_gradients + + def _opt_clear(self): + clear_func() + + for opt in self._sharding_optimizers: + opt.clear_grad = MethodType(_opt_clear, opt) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage3.py new file mode 100644 index 0000000000000000000000000000000000000000..5e0c3743dd3f88ff5ada250cb5697da8cc14f8dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage3.py @@ -0,0 +1,932 @@ +# Copyright (c) 2021 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. + +import os +import copy +import time +import contextlib +import logging +import functools +import numpy as np +from itertools import chain +from types import MethodType +from collections import deque, OrderedDict + +import paddle +from paddle import nn +from paddle.autograd import PyLayer +import paddle.fluid.core as core +from paddle.fluid.framework import ParamBase +from paddle.fluid.clip import ClipGradByGlobalNorm +from paddle.distributed import collective as dist +from paddle.distributed.collective import _get_global_group + +from .sharding_utils import Type, ShardingClipGrad, device_guard +from ..pp_utils.utils import _all_gather +from ...utils.internal_storage import GradStorage + +# CUDA alignment 256 bytes +alignment = { + "gpu": 256, +} +align = { + Type.fp16.value: 2, + Type.fp32.value: 4, +} + +global CHECK_LAYER +CHECK_LAYER = dict() # Help to check layer's id -> layer's name + + +class ShardingStage3(nn.Layer): + """ + A wrapper for Sharding Stage3 Layer in Dygraph. + + .. warning: ShardingStage3 encapsulates the layer strategy and integrates it into the nn.Layer. + + .. ZeRO: https://arxiv.org/pdf/1910.02054.pdf. + """ + + # TODO (Baibaifan) + # Feature Notes:: + # 1. The model supports the segmentation of parameters by global ranks in layers. + # 2. Support communication flow and computing flow. + # 3. Support offload function. + # 4. Support the establishment of independent communication groups. + + def __init__(self, + layer, + optimizer, + group=None, + sync_buffers=False, + device="gpu", + segment_size=2**15, + pertrain_sync_models=True, + offload=False, + sync_comm=False): + super().__init__() + + # Default configs + assert core.is_compiled_with_cuda(), "Only support CUDA." + self._layer = layer + self._default_device = device + self.__sync_buffers = sync_buffers + self._offload = offload + self._sync_comm = sync_comm + # segmentation size + assert segment_size >= 0, "segment_size must be GE than 0." + self._segment_size = segment_size + + global DEV + DEV = "cpu" if paddle.get_device() == "cpu" else paddle.get_device( + ).split(":")[0] + global DEV_ID + DEV_ID = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + global param2dtype + param2dtype = dict() + + # Communication group establishment + self._group = dist.new_group( + _get_global_group().ranks) if group is None else group + self._world_size_scaling = 1.0 / self._group.nranks + assert self._group.nranks > 1, "Training must be distributed, ranks must be greater than 1." + self._rank = self._group.rank + self._global_root_rank = self._group.ranks[ + 0] # picking rank 0 as the reference + self._global_ranks = self._group.ranks + + # Parameter segmentation for global ranks + # After flatten -> self._param2buffer_size, self._param2buffer, self._trainable_params + self._param2buffer_size = dict() # {param.name: size} + self._param2buffer = dict( + ) # {param.name: [(start0, end0),(start1, end1), ...]} + self._trainable_params = dict() # {id(layer): [trainable_params]} + self._unslice_params = set() # param's numel <= segment_size + self._unslice_params2align = dict() # {param.name: param's align} + self._grad_storages = dict() # {param.dtype: GradStorage} + + assert not isinstance( + optimizer, list), "Multiple optimizers are not supported now." + self._optim = _OptimizerWrapper(optimizer, self._offload, self._group, + self._update_params_slice) + self._ori_parameter_list = self._optim._parameter_list + self._ori_param_groups = self._optim._param_groups + + # Replace optimizer's _grad_clip + if isinstance(self._optim._grad_clip, ClipGradByGlobalNorm): + logging.warning( + "While using ClipGradByGlobalNorm in ShardingStage3, the grad clip of original optimizer will be changed." + ) + self._optim._grad_clip = ShardingClipGrad(self._optim._grad_clip, + paddle.get_device(), + self._group) + + # Synchronous all ranks models + if pertrain_sync_models: + self._sync_params_and_buffers() + + self._segment_rank_params(self._layer) + + # Add unslice params to master_weight in fp16 + self._handle_unslice_params() + + # In the first step, record the execution order of the layer + self._order_tracer = OrderedDict() + self._order_tracer["order"] = 0 + self._order_tracer["layer"] = list() + + # Register task flow + self._task_flow = TaskFlow() + + # Register forward hooks + self._register_forward_hooks(self._layer) + + # Register backward parameter hooks + self._register_backward_hooks() + + # Redefine optimizer step and clear function + self._redefine_opt_step() + self._redefine_opt_clear() + + @paddle.autograd.no_grad() + def _sync_params_and_buffers(self): + """ + Sync all model states for all ranks + """ + + for p in self._layer.parameters(): + dist.broadcast(p, + src=self._global_root_rank, + group=self._group, + sync_op=True) + + # Multi stream operation will be supported later + dist.wait(tensor=p, group=self._group, use_calc_stream=True) + + def _clear_gradients(self): + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + # 1.Handle param's slice + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + for param in trainable_params: + assert hasattr(param, "fw_storage" + ), "Find {} don't have fw_storage attribute.".format( + param.name) + + param.fw_storage.clear_gradient(False) + param.fw_storage._gradient_set_empty(False) + param.bw_storage._clear() + param.bw_storage = None + # 2.Handle unslice param + if not self._offload: + for grad_storage in self._grad_storages.values(): + grad_storage.buffer.zero_() + else: + for param in list(self._unslice_params): + param.clear_gradient(False) + param._gradient_set_empty(False) + tmp_var = param.cuda(DEV_ID) + + if tmp_var.dtype == Type.fp32.value and param2dtype[ + param.name] == Type.fp16.value: + tmp_var = paddle.cast(tmp_var, Type.fp16.value) + tmp_var._share_buffer_to(param) + tmp_var._clear() + for grad_storage in self._grad_storages.values(): + grad_storage.manumal_relase() + grad_storage.rebuild() + + # Update param memery slice + def _update_params_slice(self): + update_list = self._update_params() + + if not isinstance(self._optim._param_groups[0], dict): + slice_params = [param.fw_storage for param in update_list] + self._optim._parameter_list = slice_params + list( + self._unslice_params) + self._optim._param_groups = slice_params + list( + self._unslice_params) + else: + for param_group in self._optim._param_groups: + p_group = [] + for p in param_group['params']: + if hasattr(p, "fw_storage"): + p_group.append(p.fw_storage) + else: + p_group.append(p) + + param_group['params'] = p_group + + def forward(self, *inputs, **kwargs): + """ + A wrapper for Sharding Stage3 layer. + """ + # 1.Sync layer's buffers state + if self.__sync_buffers: + self._sync_buffers() + + # 2.Normal FW on the base model + fw = self._layer(*inputs, **kwargs) + + return fw + + def set_state_dict(self, state_dict, use_structured_name=True): + self._layer.set_state_dict(state_dict, + use_structured_name=use_structured_name) + + def state_dict(self, + destination=None, + include_sublayers=True, + structured_name_prefix=""): + return self._layer.state_dict(destination=None, + include_sublayers=True, + structured_name_prefix="") + + def _handle_unslice_params(self): + buffer_size = dict() + buffer_size[Type.fp32.value] = 0 + buffer_size[Type.fp16.value] = 0 + for param in self._unslice_params: + # Updata optimizer master weights + if param.dtype == Type.fp16.value and not self._offload: + self._optim._master_weights[param.name] = paddle.cast( + param, Type.fp32.value) + if self._offload: + param.master_weight = paddle.cast(param, Type.fp32.value).cpu() + param2dtype[param.name] = param.dtype + p_align = self._param2align(param) + self._unslice_params2align[param.name] = p_align + buffer_size[param.dtype] += param._numel() + p_align + + # Create unslice_params'grad + for param in sorted(list(self._unslice_params), key=lambda p: p.name): + if param.dtype not in self._grad_storages.keys(): + self._grad_storages[param.dtype] = GradStorage( + buffer_size[param.dtype], + dtype=param.dtype, + device=self._default_device, + destination=self._rank, + parm2align=self._unslice_params2align) + self._grad_storages[param.dtype].add_grad( + param, self._unslice_params2align[param.name]) + + def _segment_rank_params(self, layer, name="last_layer"): + """ + Flatten parameters according to layer. + """ + current_layer_params = _current_layer_params(layer) + if current_layer_params: + CHECK_LAYER[id(layer)] = name + self._flatten_layer_params(layer, current_layer_params) + + for name, sub_layer in layer.named_children(): + self._segment_rank_params(sub_layer, name) + + def _flatten_layer_params(self, layer, current_layer_params): + """ + Parameter segmentation and memory integration. + """ + + def _add_manage_info(trainable_param): + return _PartitionParam(trainable_param) + + current_params = list() + for p in current_layer_params: + if p.trainable and p._numel() > self._segment_size: + current_params.append(_add_manage_info(p)) + elif p.trainable: + self._unslice_params.add(_UnsliceParam(p)) + + assert id(layer) not in self._trainable_params.keys() + self._trainable_params[id(layer)] = current_params + + for param in self._trainable_params[id(layer)]: + if param.name in self._param2buffer.keys(): + continue + self._param2buffer[param.name] = [] + # 1.Params alignment + align_ = self._param2align(param) + + offset = align_ + param._numel() + buffer_size = offset if offset % self._group.nranks == 0 else offset + self._group.nranks - ( + offset % self._group.nranks) + self._param2buffer_size[param.name] = buffer_size + + # 2.Combination param buffer + assert buffer_size % self._group.nranks == 0 + pre_buffer = buffer_size // self._group.nranks + + for rank_ in range(self._group.nranks): + self._param2buffer[param.name].append( + (rank_ * pre_buffer, (rank_ + 1) * pre_buffer)) + + # Record param's dtype + param2dtype[param.name] = param.dtype + + # 3.Flatten layer params and release other rank buffer + self._param_storage(param, buffer_size) + + def _param_storage(self, param, buffer_size): + """ + This is a function to simplify the handling of parameter InternalStorages. + """ + assert isinstance(buffer_size, int) + value = np.zeros( + buffer_size, + dtype=np.float16) if Type.fp16.value == param.dtype else np.zeros( + buffer_size, dtype=np.float32) + buffer = core.VarBase(value=value, place=core.CPUPlace()) + + param_shape = param.shape + origin_state = param.stop_gradient + param.stop_gradient = True + param.flatten_() + param.stop_gradient = origin_state + start, end = self._param2buffer[param.name][self._rank] + + # Copy the current param value + tmp_var = core.VarBase(tensor=buffer._slice(0, param._numel()), + place=core.CPUPlace()) + param_cpu = param.cpu() + tmp_var.value().get_tensor().set(param_cpu.value().get_tensor(), + core.CPUPlace()) + param.value().get_tensor()._set_dims(param_shape) + + # Current rank param_storage + if self._offload: + param.fw_storage = core.VarBase(buffer._slice(start, end), + core.CPUPlace(), + "slice@" + param.name) + with device_guard(device="cpu"): + param.master_weight = paddle.cast(param.fw_storage, + Type.fp32.value) + else: + param.fw_storage = core.VarBase(buffer._slice(start, end), + "slice@" + param.name) + param.status = "part" + + # Updata optimizer master weights + if param.dtype == Type.fp16.value and not self._offload: + self._optim._master_weights[param.fw_storage.name] = paddle.cast( + param.fw_storage, Type.fp32.value) + param._clear() + + def _register_forward_hooks(self, layer): + """ + Register pylayer to manage memory slices. + There are four stages: + FW + 1. Before the forward layers, synchronize the full parameters. + 2. After the forward layers, release the full parameter and keep the parameter slice. + BW + 3. Before the backward layers, synchronize the full parameters and create param's grad. + 4. After the gradient accumulation, release the full parameter and keep the parameter slice. + """ + current_layer_params = _current_layer_params(layer) + if current_layer_params: + self._register_forward_all_hooks(layer, self._task_flow) + + for _, sub_layer in layer.named_children(): + self._register_forward_hooks(sub_layer) + + def _register_forward_all_hooks(self, sub_layer, task_flow): + + def _forward_pre_hook(layer, inputs): + return ForwardPreHooks(layer, self._order_tracer, + self._trainable_params, self._param2buffer, + self._rank, self._group, self._sync_comm, + self._offload, task_flow) + + def _forward_post_hook(layer, inputs, outputs): + return ForwardPostHooks.apply(outputs, layer, self._order_tracer, + self._trainable_params, + self._param2buffer, + self._param2buffer_size, self._rank, + self._group, self._sync_comm, + self._offload, task_flow) + + # register previous forward hooks + sub_layer.register_forward_pre_hook(_forward_pre_hook) + + # register post forward hooks + sub_layer.register_forward_post_hook(_forward_post_hook) + + @paddle.autograd.no_grad() + def _sync_buffers(self): + """ + Sync all the param buffers from all ranks (exp: batch norm statistics). + """ + + for buffer in self._layer.buffers(include_sublayers=True): + dist.broadcast(buffer, + self._global_root_rank, + self._group, + sync_op=True) + # Multi stream operation will be supported later + dist.wait(tensor=buffer, group=self._group, use_calc_stream=True) + + def __getattr__(self, name): + """Forward missing attributes to wrapped layer.""" + try: + return super().__getattr__(name) + except AttributeError: + return getattr(self._layer, name) + + def _update_params(self): + """ + Update parameters to optimizer memory slice. + """ + update_list = [] + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + # 1.Handle param's slice + for param in trainable_params: + assert hasattr( + param, + "fw_storage"), "Find {} don't have fw_storage attribute".format( + param.name) + # Gradient average + if self._offload: + with device_guard(device="cpu"): + param.bw_storage.scale_(scale=self._world_size_scaling) + else: + param.bw_storage.scale_(scale=self._world_size_scaling) + param.fw_storage = _VarBaseWrapper(param) + assert param.fw_storage.grad is None + param.fw_storage._copy_gradient_from(param.bw_storage) + update_list.append(param) + + # 2.Handle unslice param + for grad_storage in self._grad_storages.values(): + grad_storage.buffer.scale_(scale=self._world_size_scaling) + dist.all_reduce(tensor=grad_storage.buffer, + group=self._group, + sync_op=True) + dist.wait(tensor=grad_storage.buffer, + group=self._group, + use_calc_stream=True) + + if self._offload: + for param in list(self._unslice_params): + param._clear() + param.master_weight._share_buffer_to(param) + + for grad_storage in self._grad_storages.values(): + for p in grad_storage._params: + tmp_g = _device2cpu(p.grad, convert_dtype=True) + p.clear_gradient(False) + p._gradient_set_empty(False) + p._copy_gradient_from(tmp_g) + tmp_g._clear() + grad_storage.buffer._clear() + + return update_list + + def get_all_parameters(self, convert2cpu=False): + """ + Get the full parameters and return the corresponding task flows. + """ + assert len(self._trainable_params.keys()) > 0 + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + t_flow = _allgather_buffer(trainable_params, + self._group, + use_calc_stream=True, + task_flow=TaskFlow(), + sync_wait=True, + offload=self._offload, + convert2cpu=convert2cpu) + if convert2cpu: + for param in trainable_params: + t_flow.full_param[param.name]._share_buffer_to(param) + + self._optim._parameter_list = self._ori_parameter_list + self._optim._param_groups = self._ori_param_groups + + def _register_backward_hooks(self): + current_layer_params = self._layer.parameters(include_sublayers=True) + trainable_params = list( + filter(lambda p: p.trainable and p not in self._unslice_params, + current_layer_params)) + + for param in trainable_params: + allreduce_function = self._get_allreduce_fn(param) + param._register_backward_hook(allreduce_function) + + def _get_allreduce_fn(self, param): + + @paddle.autograd.no_grad() + def allreduce_(*_): + if param.name in self._task_flow.full_grad.keys(): + full_grad = self._task_flow.full_grad[param.name] + # Only support sync allreduce current rank's layer now + dist.all_reduce(tensor=full_grad, + group=self._group, + sync_op=True) + dist.wait(tensor=full_grad, + group=self._group, + use_calc_stream=True) + + start, end = self._param2buffer[param.name][self._rank] + if param.bw_storage is None: + param.bw_storage = core.VarBase(full_grad._slice( + start, end)).detach().clone() + if self._offload: + param.bw_storage = _device2cpu(param.bw_storage, True) + else: + if self._offload: + cpu_grad = _device2cpu( + core.VarBase(full_grad._slice( + start, end)).detach().clone(), True) + with device_guard(device="cpu"): + param.bw_storage = paddle.add( + param.bw_storage, cpu_grad) + else: + # param.bw_storage.add_( + # core.VarBase(full_grad._slice(start, end)) + # .detach().clone()) + param.bw_storage = paddle.add( + param.bw_storage, + core.VarBase(full_grad._slice( + start, end)).detach().clone()) + param.clear_gradient(False) + param._gradient_set_empty(False) + tmp_var = self._task_flow.full_grad.pop(param.name) + tmp_var._clear() + + if param.name in self._task_flow.full_param.keys(): + if param.status == "all": + param.use_count = 0 + param._clear() + start, end = self._param2buffer[param.name][self._rank] + param.fw_storage = core.VarBase( + self._task_flow.full_param[param.name]._slice( + start, end), + param.name + "@slice").detach().clone() + param.status = "part" + tmp_var = self._task_flow.full_param.pop(param.name) + tmp_var._clear() + + if self._offload: + param.fw_storage._clear() + param.master_weight._share_buffer_to(param.fw_storage) + + return allreduce_ + + def _param2align(self, param): + # CUDA alignment 256 bytes + size = param._numel() * align[param.dtype] + remaining = size % alignment[self._default_device] + ali = 0 if remaining == 0 else alignment[ + self._default_device] - remaining + align_ = ali // align[param.dtype] + return align_ + + def _redefine_opt_step(self): + params_slice_func = self._update_params_slice + opt_step = self._optim.step + + def _opt_step(self): + if not self.update_scaler: + params_slice_func() + if self.offload: + with device_guard(device="cpu"): + opt_step() + else: + opt_step() + + def _opt_minimize(self): + raise RuntimeError( + "optimizer.minimize() not support now, please use optimizer.step()" + ) + + self._optim.step = MethodType(_opt_step, self._optim) + self._optim.minimize = MethodType(_opt_minimize, self._optim) + + def _redefine_opt_clear(self): + clear_func = self._clear_gradients + + def _opt_clear(self): + clear_func() + + self._optim.clear_grad = MethodType(_opt_clear, self._optim) + + +def ForwardPreHooks(layer, order_tracer, trainable_params, param2buffer, rank, + group, sync_comm, offload, task_flow): + + # Record layer's id + layer_id = id(layer) + use_calc, sync_wait = False, False + + if layer_id not in order_tracer.keys() or sync_comm: + use_calc, sync_wait = True, True + + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + else: + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + # wait current layer params + _wait_layer(trainable_params[layer_id], task_flow, group, use_calc, + offload) + + if layer_id == order_tracer["layer"][-1]: return + order_ = order_tracer[layer_id] + layer_id = order_tracer["layer"][order_ + 1] + + _allgather_buffer(trainable_params[layer_id], + group, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + + return + + +class ForwardPostHooks(PyLayer): + + @staticmethod + def forward(ctx, inputs, layer, order_tracer, trainable_params, + param2buffer, param2buffer_size, rank, group, sync_comm, + offload, task_flow): + + layer_id = id(layer) + # release current layer full params + _release_param(trainable_params[layer_id], param2buffer, rank, + task_flow, offload) + + if layer_id not in order_tracer.keys(): + order_ = order_tracer["order"] + order_tracer[layer_id] = order_ + order_tracer["order"] += 1 + order_tracer["layer"].append(layer_id) + + #Record bw info + ctx.order_tracer = order_tracer + ctx.task_flow = task_flow + ctx.group = group + ctx.layer = layer + ctx.sync_comm = sync_comm + ctx.trainable_params = trainable_params + ctx.param2buffer_size = param2buffer_size + ctx.offload = offload + + return inputs + + @staticmethod + def backward(ctx, *args): + # Load context value + order_tracer = ctx.order_tracer + task_flow = ctx.task_flow + group = ctx.group + layer = ctx.layer + trainable_params = ctx.trainable_params + param2buffer_size = ctx.param2buffer_size + sync_comm = ctx.sync_comm + offload = ctx.offload + layer_id = id(layer) + use_calc, sync_wait = False, False + + # Allgather params synchronization + if sync_comm: + use_calc, sync_wait = True, True + _allgather_buffer(trainable_params[layer_id], + group, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + else: + _wait_layer(trainable_params[layer_id], task_flow, group, use_calc, + offload) + + # Create params's grad + _create_params_grad(trainable_params[layer_id], param2buffer_size, + task_flow) + + # Whether to use calc stream + task_flow.use_calc[layer_id] = use_calc + if layer_id != order_tracer["layer"][0] and not sync_comm: + layer_next_id = order_tracer["layer"][order_tracer[layer_id] - 1] + _allgather_buffer(trainable_params[layer_next_id], + group, + use_calc_stream=use_calc, + task_flow=task_flow, + sync_wait=sync_wait, + offload=offload) + + return args + + +class TaskFlow: + """ + Task flows, one way linked list for task acquisition. + """ + + def __init__(self, + full_param=dict(), + full_grad=dict(), + use_calc=dict(), + callback=None): + self.full_param = full_param + self.full_grad = full_grad + self.use_calc = use_calc + self.callback = callback + + +def _release_param(trainable_params, + param2buffer, + rank, + task_flow, + offload=False): + for param in trainable_params: + # async communicate share weight not clear + param.use_count -= 1 + if param.use_count == 0: + param._clear() + if param.name in task_flow.full_param.keys(): + start, end = param2buffer[param.name][rank] + with paddle.amp.auto_cast(enable=False): + param.fw_storage = core.VarBase( + task_flow.full_param[param.name]._slice(start, end), + param.name + "@slice").detach().clone() + param.status = "part" + tmp_var = task_flow.full_param.pop(param.name) + tmp_var._clear() + + if offload: + param.fw_storage = _device2cpu(param.fw_storage) + return + + +def _wait_layer(trainable_params, + task_flow, + group, + use_calc_stream, + offload=False): + paddle.device.cuda.synchronize() + for param in trainable_params: + if param.status == "all": + param.use_count += 1 + continue + if param.name in task_flow.full_param.keys(): + full_param = task_flow.full_param[param.name] + core.VarBase(full_param._slice( + 0, param._numel()))._share_buffer_to(param) + param.fw_storage._clear() + param.fw_storage = None + param.status = "all" + param.use_count += 1 + else: + _allgather_buffer(trainable_params, + group, + use_calc_stream=True, + task_flow=task_flow, + sync_wait=True, + offload=offload) + break + return task_flow + + +def _allgather_buffer(trainable_params, + group, + use_calc_stream, + task_flow, + sync_wait=False, + offload=False, + convert2cpu=False): + + for param in trainable_params: + if param.status == "all": + param.use_count += 1 + continue + + if offload: + param.fw_storage = _cpu2device(param) + + with paddle.amp.auto_cast(enable=False): + full_param = _all_gather(param.fw_storage, + group, + use_calc_stream=use_calc_stream) + + # Allgather current layer in the 1st step synchronously + if sync_wait: + with paddle.amp.auto_cast(enable=False): + dist.wait(tensor=full_param, + group=group, + use_calc_stream=use_calc_stream) + core.VarBase(full_param._slice( + 0, param._numel()))._share_buffer_to(param) + param.fw_storage._clear() + param.fw_storage = None + param.status = "all" + param.use_count += 1 + task_flow.full_param[param.name] = full_param + + # parameter converts to cpu + if convert2cpu: + p_name = param.name + param = _device2cpu(param) + tmp_var = task_flow.full_param.pop(p_name) + tmp_var._clear() + task_flow.full_param[p_name] = param + + return task_flow + + +@paddle.autograd.no_grad() +def _create_params_grad(trainable_params, param2buffer_size, task_flow): + for param in trainable_params: + if param.name in task_flow.full_grad.keys(): + continue + assert isinstance(param2buffer_size[param.name], int) + temp_grad = paddle.zeros([param2buffer_size[param.name]], + dtype=param.dtype) + param._copy_gradient_from( + core.VarBase(temp_grad._slice(0, param._numel()))) + task_flow.full_grad[param.name] = temp_grad + return task_flow + + +def _PartitionParam(param): + if not hasattr(param, "fw_storage"): + setattr(param, "fw_storage", None) + setattr(param, "bw_storage", None) + setattr(param, "master_weight", None) + setattr(param, "status", "all") + setattr(param, "use_count", 0) + return param + + +def _UnsliceParam(param): + if not hasattr(param, "unslice"): + setattr(param, "unslice", True) + setattr(param, "master_weight", None) + return param + + +def _VarBaseWrapper(param): + varbase = param.fw_storage + tmp_param = ParamBase(shape=varbase.shape, + dtype=varbase.dtype, + name="slice@" + param.name) + varbase._share_buffer_to(tmp_param) + tmp_param.regularizer = param.regularizer + tmp_param.optimize_attr['learning_rate'] = param.optimize_attr[ + 'learning_rate'] + varbase._clear() + return tmp_param + + +def _OptimizerWrapper(optimizer, offload, group, update_params_slice): + if not hasattr(optimizer, "_optim"): + setattr(optimizer, "_optim", optimizer) + setattr(optimizer, "offload", offload) + setattr(optimizer, "group", group) + setattr(optimizer, "update_scaler", None) + setattr(optimizer, "update_slice", update_params_slice) + return optimizer + + +def _device2cpu(trans_param, convert_dtype=False): + if convert_dtype: + trans_param = paddle.cast(trans_param, Type.fp32.value) + tmp_p = trans_param.cpu() + trans_param._clear() + return tmp_p + + +def _cpu2device(param): + tmp_p = param.fw_storage.cuda(DEV_ID) + if tmp_p.dtype == Type.fp32.value and param2dtype[ + param.name] == Type.fp16.value: + tmp_p = paddle.cast(tmp_p, Type.fp16.value) + return tmp_p + + +def _current_layer_params(layer): + return layer.parameters( + include_sublayers=False) + list(layer.extra_parameters) if hasattr( + layer, "extra_parameters") else layer.parameters( + include_sublayers=False) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..42f43ce5377484412bbc69b50d4848fd5f6a9f58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding/sharding_utils.py @@ -0,0 +1,233 @@ +# Copyright (c) 2021 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. + +import os +import contextlib +from collections import abc +from enum import Enum +from math import inf +import numpy as np +from types import MethodType + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid import layers +from paddle.fluid.dygraph import to_variable +from paddle.fluid.framework import dygraph_only +from paddle.fluid.dygraph import base as imperative_base +from paddle.distributed.collective import _get_global_group + + +class Taskflow: + """ + Task flows, one way linked list for task acquisition. + """ + + def __init__(self, task, callback): + self.task = task + self.callback = callback + + +class Type(Enum): + """ + Type of trainable parameters + """ + fp16 = paddle.float16 + bf16 = paddle.bfloat16 + fp32 = paddle.float32 + + +class ShardingClipGrad: + + def __init__(self, clip, device, group): + self._clip = clip + self._device = device + self._group = group + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + sum_square_fp32, sum_square_fp16 = [], [] + unslice_params_fp32, unslice_params_fp16 = [], [] + + for p, g in params_grads: + p_slice = True # using for slice parameter in sharding stage3 + if g is None or getattr(p, 'need_clip', True) is False: + continue + if hasattr(p, "unslice"): + p_slice = False + + merge_grad = g + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.get_tensor_from_selected_rows( + layers.merge_selected_rows(g)) + square = layers.square(merge_grad) + sum_square = layers.reduce_sum(square) + + if p.dtype == paddle.float16: + if p_slice: sum_square_fp16.append(sum_square) + else: unslice_params_fp16.append(sum_square) + elif p.dtype == paddle.float32: + if p_slice: sum_square_fp32.append(sum_square) + else: unslice_params_fp32.append(sum_square) + + # global norm of non-distributed FP16 params_and_grads + if len(sum_square_fp16) == 0: + global_norm_fp16 = paddle.to_tensor([0.], dtype=paddle.float32) + else: + global_norm_fp16 = layers.concat(sum_square_fp16) + global_norm_fp16 = layers.reduce_sum(global_norm_fp16) + global_norm_fp16 = paddle.cast(global_norm_fp16, + dtype=paddle.float32) + + # global norm of non-distributed FP16 params_and_grads for unslice parameter + if len(unslice_params_fp16) == 0: + global_unslice_fp16 = paddle.to_tensor([0.], dtype=paddle.float32) + else: + global_unslice_fp16 = layers.concat(unslice_params_fp16) + global_unslice_fp16 = layers.reduce_sum(global_unslice_fp16) + global_unslice_fp16 = paddle.cast(global_unslice_fp16, + dtype=paddle.float32) + + # global norm of non-distributed FP32 params_and_grads + global_norm_fp32 = layers.concat( + sum_square_fp32) if len(sum_square_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_norm_fp32 = layers.reduce_sum(global_norm_fp32) + + # global norm of non-distributed FP32 params_and_grads for unslice parameter + global_unslice_fp32 = layers.concat(unslice_params_fp32) if len( + unslice_params_fp32) != 0 else paddle.to_tensor( + [0.], dtype=paddle.float32) + global_unslice_fp32 = layers.reduce_sum(global_unslice_fp32) + global_unslice_var = global_unslice_fp16 + global_unslice_fp32 + + global_norm_var = global_norm_fp16 + global_norm_fp32 + 1.0 / self._group.nranks * global_unslice_var + + # add all reduce to get global norm of distributed params_and_grads + dev_id = int(self._device.split(":")[1]) + with device_guard(dev_id, "gpu"): + paddle.distributed.all_reduce(global_norm_var, group=self._group) + + global_norm_var = layers.sqrt(global_norm_var) + max_global_norm = layers.fill_constant(shape=[1], + dtype=global_norm_var.dtype, + value=self.clip_norm) + + clip_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=global_norm_var, + y=max_global_norm)) + clip_var_fp16 = paddle.cast(clip_var, paddle.float16) + + for p, g in params_grads: + if getattr(p, 'need_clip', True) is False or g is None: + continue + origin_state = g.stop_gradient + g.stop_gradient = True + if p.dtype == paddle.float16: + g.scale_(clip_var_fp16) + else: + g.scale_(clip_var) + g.stop_gradient = origin_state + p._reset_grad_inplace_version(True) + + return params_grads + + def __getattr__(self, item): + return getattr(self._clip, item) + + def __call__(self, params_grads): + return self._dygraph_clip(params_grads) + + +@contextlib.contextmanager +def device_guard(dev_id=0, device="cpu"): + origin_device = paddle.device.get_device() + if device == "cpu": + paddle.set_device(device) + elif device == "gpu": + paddle.set_device("gpu:{}".format(dev_id)) + try: + yield + finally: + paddle.set_device(origin_device) + + +@dygraph_only +def ShardingScaler(scaler): + + def unscale_method(self, optimizer): + if not self._enable: + return + param_grads = [] + param_grads_fp16 = [] + param_grads_fp32 = [] + if hasattr(optimizer, "update_slice"): + optimizer.update_slice() + optimizer.update_scaler = True + + if getattr(optimizer._optim, '_param_groups', None) and isinstance( + optimizer._optim._param_groups[0], dict): + + for group in optimizer._optim._param_groups: + for param in group['params']: + if param._grad_ivar() is not None: + param_grads.append(param._grad_ivar()) + if param._grad_ivar().dtype in [ + core.VarDesc.VarType.FP16, paddle.float16 + ]: + param_grads_fp16.append(param._grad_ivar()) + else: + param_grads_fp32.append(param._grad_ivar()) + else: + for param in optimizer._optim._parameter_list: + if param.grad is not None: + param_grads.append(param.grad) + if param.grad.dtype in [ + core.VarDesc.VarType.FP16, paddle.float16 + ]: + param_grads_fp16.append(param.grad) + else: + param_grads_fp32.append(param.grad) + + temp_found_inf_fp16 = to_variable(np.array([0]).astype(np.bool_)) + temp_found_inf_fp32 = to_variable(np.array([0]).astype(np.bool_)) + + device = "cpu" if optimizer.offload else "gpu" + dev_id = 0 if device == "cpu" else int( + paddle.get_device().split(":")[1]) + + with device_guard(dev_id, device): + if len(param_grads_fp16): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp16, + self._scale, + param_grads_fp16, + temp_found_inf_fp16) + if len(param_grads_fp32): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp32, + self._scale, + param_grads_fp32, + temp_found_inf_fp32) + + self._found_inf = 1 if temp_found_inf_fp16 or temp_found_inf_fp32 else 0 + is_found_inf = paddle.to_tensor([self._found_inf], dtype="int32") + + paddle.distributed.all_reduce(is_found_inf, + op=paddle.distributed.ReduceOp.MAX, + group=optimizer.group) + self._found_inf = is_found_inf.numpy()[0] + + scaler._unscale = MethodType(unscale_method, scaler) + return scaler diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding_parallel.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc76570f17a3ce233a21fbe45ed12b6ad4ce700 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/sharding_parallel.py @@ -0,0 +1,34 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.dygraph.layers import Layer +from .meta_parallel_base import MetaParallelBase +from ..utils.hybrid_parallel_util import broadcast_sharding_parameters +from ..utils.log_util import logger + +__all__ = [] + + +class ShardingParallel(MetaParallelBase): + + def __init__(self, layers, hcg, **kwargs): + super(ShardingParallel, self).__init__(layers, hcg, **kwargs) + + def _prepare_for_model(self): + logger.info("start broadcast sharding parameters") + broadcast_sharding_parameters(self._layers, self._hcg) + + # TODO (JZ-LIANG) to support Sharding-DP + + logger.info("sharding's parameters is ready") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/tensor_parallel.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/tensor_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..5814ed898fafbb67009be837435a5a4929c9e656 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/meta_parallel/tensor_parallel.py @@ -0,0 +1,45 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.dygraph.layers import Layer +from .meta_parallel_base import MetaParallelBase +from ..utils.hybrid_parallel_util import broadcast_dp_parameters +from ..utils.hybrid_parallel_util import broadcast_input_data +from ..utils.hybrid_parallel_util import broadcast_mp_parameters, broadcast_sharding_parameters +from ..utils.log_util import logger + +__all__ = [] + + +class TensorParallel(MetaParallelBase): + + def __init__(self, layers, hcg, **kwargs): + super(TensorParallel, self).__init__(layers, hcg, **kwargs) + + def _prepare_for_model(self): + logger.info("start broadcast mp parameters") + broadcast_mp_parameters(self._layers, self._hcg) + + if self._hcg.get_sharding_parallel_world_size() > 1: + logger.info("start broadcast sharding parameters") + broadcast_sharding_parameters(self._layers, self._hcg) + + logger.info("start broadcast dp parameters") + broadcast_dp_parameters(self._layers, self._hcg) + + logger.info("mp's parameters is ready") + + def _pre_forward(self, *inputs, **kwargs): + logger.debug("mp start broadcast input data") + return broadcast_input_data(self._hcg, *inputs, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abcb90afb23c43d5cd2ec00cadb14a296973b84d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/__init__.py @@ -0,0 +1,24 @@ +# 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. + +from .metric import acc # noqa: F401 +from .metric import auc # noqa: F401 +from .metric import mae # noqa: F401 +from .metric import max # noqa: F401 +from .metric import min # noqa: F401 +from .metric import mse # noqa: F401 +from .metric import rmse # noqa: F401 +from .metric import sum # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/metric.py new file mode 100644 index 0000000000000000000000000000000000000000..d2050585df754b11f80eaecf7445caacfef47471 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/metrics/metric.py @@ -0,0 +1,426 @@ +# 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. +"""Fleet Metrics""" + +import math +import numpy as np +from paddle.static import Variable +import paddle + +__all__ = [] + + +def sum(input, scope=None, util=None): + """ + distributed sum in fleet + + Args: + input(numpy.array|Variable|string): output of a layer + scope(Scope): specific scope + + Returns: + global_metric(numpy.array): sum array + + Example: + .. code-block:: python + + # in model.py + input = fluid.layers.cast(some_input, dtype='float32') + cnt = fluid.layers.reduce_sum(input) + global_cnt = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0) + tmp = fluid.layers.elementwise_add(cnt, global_cnt) + fluid.layers.assign(tmp, global_cnt) + + # in train.py, after train or infer + res = np.array(scope.find_var(global_cnt.name).get_tensor()) + print("sum array: ", paddle.distributed.fleet.sum(res)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + if isinstance(input, Variable): + input = np.array(scope.find_var(input.name).get_tensor()) + elif isinstance(input, str): + input = np.array(scope.find_var(input).get_tensor()) + old_shape = np.array(input.shape) + output = np.copy(input) * 0 + output = util.all_reduce(input, "sum") + output = output.reshape(old_shape) + return output + + +def max(input, scope=None, util=None): + """ + distributed max in fleet + + Args: + input(numpy.array|Variable|string): output of a layer + scope(Scope): specific scope + + Returns: + global_metric(numpy.array): max array + + Example: + .. code-block:: python + + # in model.py + input = fluid.layers.cast(some_input, dtype='float32') + cnt = fluid.layers.reduce_sum(input) + global_cnt = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0) + tmp = fluid.layers.elementwise_max(cnt, global_cnt) + fluid.layers.assign(tmp, global_cnt) + + # in train.py, after train or infer + res = np.array(scope.find_var(global_cnt.name).get_tensor()) + print("max array: ", paddle.distributed.fleet.max(res)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + if isinstance(input, Variable): + input = np.array(scope.find_var(input.name).get_tensor()) + elif isinstance(input, str): + input = np.array(scope.find_var(input).get_tensor()) + old_shape = np.array(input.shape) + output = np.copy(input) * 0 + output = util.all_reduce(input, "max") + output = output.reshape(old_shape) + return output + + +def min(input, scope=None, util=None): + """ + distributed min in fleet + + Args: + input(numpy.array|Variable|string): output of a layer + scope(Scope): specific scope + + Returns: + global_metric(numpy.array): min array + + Example: + .. code-block:: python + + # in model.py + input = fluid.layers.cast(some_input, dtype='float32') + cnt = fluid.layers.reduce_sum(input) + global_cnt = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0) + tmp = fluid.layers.elementwise_min(cnt, global_cnt) + fluid.layers.assign(tmp, global_cnt) + + # in train.py, after train or infer + res = np.array(scope.find_var(global_cnt.name).get_tensor()) + print("min array: ", paddle.distributed.fleet.min(res)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + if isinstance(input, Variable): + input = np.array(scope.find_var(input.name).get_tensor()) + elif isinstance(input, str): + input = np.array(scope.find_var(input).get_tensor()) + old_shape = np.array(input.shape) + output = np.copy(input) * 0 + output = util.all_reduce(input, "min") + output = output.reshape(old_shape) + return output + + +def auc(stat_pos, stat_neg, scope=None, util=None): + """ + distributed auc in fleet + + Args: + stat_pos(numpy.array|Variable|string): stat_pos in output of fluid.layers.auc + stat_neg(numpy.array|Variable|string): stat_neg in output of fluid.layers.auc + scope(Scope): specific scope + + Returns: + auc_value(float): auc value + + Example: + .. code-block:: python + + # in model.py + similarity_norm = fluid.layers.sigmoid(fluid.layers.clip(output, min=-15.0, max=15.0)) + binary_predict = fluid.layers.concat( + input=[fluid.layers.elementwise_sub(fluid.layers.ceil(similarity_norm), similarity_norm), similarity_norm], axis=1) + self.auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, stat_neg] = + fluid.layers.auc(input=binary_predict, label=label, curve='ROC', num_thresholds=4096) + + # in train.py, after train or infer + pos = np.array(scope.find_var(stat_pos.name).get_tensor()) + neg = np.array(scope.find_var(stat_neg.name).get_tensor()) + print("auc: ", paddle.distributed.fleet.auc(pos, neg)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + + if isinstance(stat_pos, Variable): + stat_pos = np.array(scope.find_var(stat_pos.name).get_tensor()) + elif isinstance(stat_pos, str): + stat_pos = np.array(scope.find_var(stat_pos).get_tensor()) + if isinstance(stat_neg, Variable): + stat_neg = np.array(scope.find_var(stat_neg.name).get_tensor()) + elif isinstance(stat_neg, str): + stat_neg = np.array(scope.find_var(stat_neg).get_tensor()) + # auc pos bucket shape + old_pos_shape = np.array(stat_pos.shape) + # reshape to one dim + stat_pos = stat_pos.reshape(-1) + global_pos = np.copy(stat_pos) * 0 + # mpi allreduce + global_pos = util.all_reduce(stat_pos, "sum") + global_pos = global_pos.reshape(old_pos_shape) + + # auc neg bucket + old_neg_shape = np.array(stat_neg.shape) + stat_neg = stat_neg.reshape(-1) + global_neg = np.copy(stat_neg) * 0 + global_neg = util.all_reduce(stat_neg, "sum") + global_neg = global_neg.reshape(old_neg_shape) + + # calculate auc + num_bucket = len(global_pos[0]) + area = 0.0 + pos = 0.0 + neg = 0.0 + new_pos = 0.0 + new_neg = 0.0 + total_ins_num = 0 + for i in range(num_bucket): + index = num_bucket - 1 - i + new_pos = pos + global_pos[0][index] + total_ins_num += global_pos[0][index] + new_neg = neg + global_neg[0][index] + total_ins_num += global_neg[0][index] + area += (new_neg - neg) * (pos + new_pos) / 2 + pos = new_pos + neg = new_neg + + auc_value = None + if pos * neg == 0 or total_ins_num == 0: + auc_value = 0.5 + else: + auc_value = area / (pos * neg) + + return auc_value + + +def mae(abserr, total_ins_num, scope=None, util=None): + """ + distributed mae in fleet + + Args: + abserr(numpy.array|Variable|string): abserr in output of fluid.contrib.layers.ctr_metric_bundle + total_ins_num(numpy.array|Variable|string): total variable + scope(Scope): specific scope + + Returns: + mae(float): mae value + + Example: + .. code-block:: python + + # in model.py + sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32')) + + # in train.py, after train or infer + res = np.array(scope.find_var(abserr.name).get_tensor()) + print("mae: ", paddle.distributed.fleet.mae(res, total_ins_num)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + + if isinstance(abserr, Variable): + abserr = np.array(scope.find_var(abserr.name).get_tensor()) + elif isinstance(abserr, str): + abserr = np.array(scope.find_var(abserr).get_tensor()) + if isinstance(total_ins_num, Variable): + total_ins_num = np.array( + scope.find_var(total_ins_num.name).get_tensor()) + elif isinstance(total_ins_num, str): + total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor()) + + old_metric_shape = np.array(abserr.shape) + abserr = abserr.reshape(-1) + global_metric = np.copy(abserr) * 0 + + global_metric = util.all_reduce(abserr, "sum") + global_metric = global_metric.reshape(old_metric_shape) + global_total_num = util.all_reduce(total_ins_num, "sum") + + mae_value = float(global_metric[0]) / float(global_total_num[0]) + return mae_value + + +def rmse(sqrerr, total_ins_num, scope=None, util=None): + """ + distributed rmse in fleet + + Args: + sqrerr(numpy.array|Variable|string): sqrerr in output of fluid.contrib.layers.ctr_metric_bundle + total_ins_num(numpy.array|Variable|string): total variable + scope(Scope): specific scope + + Returns: + rmse(float): rmse value + + Example: + .. code-block:: python + + # in model.py + sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32')) + + # in train.py, after train or infer + res = np.array(scope.find_var(sqrerr.name).get_tensor()) + print("rmse: ", paddle.distributed.fleet.rmse(res, total_ins_num)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + + if isinstance(sqrerr, Variable): + sqrerr = np.array(scope.find_var(sqrerr.name).get_tensor()) + elif isinstance(sqrerr, str): + sqrerr = np.array(scope.find_var(sqrerr).get_tensor()) + if isinstance(total_ins_num, Variable): + total_ins_num = np.array( + scope.find_var(total_ins_num.name).get_tensor()) + elif isinstance(total_ins_num, str): + total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor()) + old_metric_shape = np.array(sqrerr.shape) + sqrerr = sqrerr.reshape(-1) + global_metric = np.copy(sqrerr) * 0 + + global_metric = util.all_reduce(sqrerr, "sum") + global_metric = global_metric.reshape(old_metric_shape) + global_total_num = util.all_reduce(total_ins_num, "sum") + + rmse_value = math.sqrt(float(global_metric[0]) / float(global_total_num[0])) + + return rmse_value + + +def mse(sqrerr, total_ins_num, scope=None, util=None): + """ + distributed mse in fleet + + Args: + sqrerr(numpy.array|Variable|string): sqrerr in output of fluid.contrib.layers.ctr_metric_bundle + total_ins_num(numpy.array|Variable|string): total variable + scope(Scope): specific scope + + Returns: + mse(float): mse value + + Example: + .. code-block:: python + + # in model.py + sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32')) + + # in train.py, after train or infer + metric = np.array(scope.find_var(sqrerr.name).get_tensor()) + print("mse: ", paddle.distributed.fleet.mse(metric, total_ins_num)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + + if isinstance(sqrerr, Variable): + sqrerr = np.array(scope.find_var(sqrerr.name).get_tensor()) + elif isinstance(sqrerr, str): + sqrerr = np.array(scope.find_var(sqrerr).get_tensor()) + if isinstance(total_ins_num, Variable): + total_ins_num = np.array( + scope.find_var(total_ins_num.name).get_tensor()) + elif isinstance(total_ins_num, str): + total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor()) + old_metric_shape = np.array(sqrerr.shape) + sqrerr = sqrerr.reshape(-1) + global_metric = np.copy(sqrerr) * 0 + + global_metric = util.all_reduce(sqrerr, "sum") + global_metric = global_metric.reshape(old_metric_shape) + global_total_num = util.all_reduce(total_ins_num, "sum") + + mse_value = float(global_metric[0]) / float(global_total_num[0]) + return mse_value + + +def acc(correct, total, scope=None, util=None): + """ + distributed accuracy in fleet + + Args: + correct(numpy.array|Variable|string): correct Variable + total(numpy.array|Variable): total Variable + scope(Scope): specific scope + + Returns: + acc(float): accuracy value + + Example: + .. code-block:: python + + # in model.py + correct = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0) + total = fluid.layers.create_global_var(dtype='float32', shape=[1], value=0) + acc = fluid.layers.acc(predict, label, k=1, correct=correct, total=total) + + global_correct = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0) + tmp1 = fluid.layers.elementwise_min(correct, global_correct) + fluid.layers.assign(tmp1, global_correct) + + global_total = fluid.layers.create_global_var(persistable=True, dtype='float32', shape=[1], value=0) + tmp2 = fluid.layers.elementwise_min(total, global_total) + fluid.layers.assign(tmp2, global_total) + + # in train.py, after train or infer + correct_num = np.array(scope.find_var(correct.name).get_tensor()) + total_num = np.array(scope.find_var(total.name).get_tensor()) + print("accuracy: ", paddle.distributed.fleet.acc(correct_num, total_num)) + """ + if scope is None: + scope = paddle.static.global_scope() + if util is None: + util = paddle.distributed.fleet.util + + if isinstance(correct, Variable): + correct = np.array(scope.find_var(correct.name).get_tensor()) + elif isinstance(correct, str): + correct = np.array(scope.find_var(correct).get_tensor()) + if isinstance(total, Variable): + total = np.array(scope.find_var(total.name).get_tensor()) + elif isinstance(total, str): + total = np.array(scope.find_var(total).get_tensor()) + + global_correct_num = np.copy(correct) * 0 + global_total_num = np.copy(total) * 0 + + global_correct_num = util.all_reduce(correct, "sum") + global_total_num = util.all_reduce(total, "sum") + + return float(global_correct_num[0]) / float(global_total_num[0]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/model.py new file mode 100644 index 0000000000000000000000000000000000000000..40633788f12d45be4bc30f25044e700656034d93 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/model.py @@ -0,0 +1,158 @@ +# Copyright (c) 2022 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. + +import paddle +import os +import numpy as np +from .base import topology as tp +from .base.topology import ParallelMode +from .meta_parallel import TensorParallel, model_parallel_random_seed +from .meta_parallel import PipelineParallel, ShardingParallel, PipelineParallelWithInterleave, PipelineLayer +from paddle.fluid import core +from paddle.fluid.dygraph.varbase_patch_methods import _grad_scalar +from paddle.distributed import fleet + +_grad_scalar = None + + +def distributed_model(model): + """ + Return distributed data parallel model (Only work in dygraph mode) + + Args: + model (Layer): the user-defind model which inherits Layer. + + Returns: + distributed data parallel model which inherits Layer. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.distributed import fleet + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear1 = nn.Linear(10, 10) + self._linear2 = nn.Linear(10, 1) + + def forward(self, x): + return self._linear2(self._linear1(x)) + + # 1. initialize fleet environment + fleet.init(is_collective=True) + + # 2. create layer & optimizer + layer = LinearNet() + loss_fn = nn.MSELoss() + adam = paddle.optimizer.Adam( + learning_rate=0.001, parameters=layer.parameters()) + + # 3. get data_parallel model using fleet + adam = fleet.distributed_optimizer(adam) + dp_layer = fleet.distributed_model(layer) + + # 4. run layer + inputs = paddle.randn([10, 10], 'float32') + outputs = dp_layer(inputs) + labels = paddle.randn([10, 1], 'float32') + loss = loss_fn(outputs, labels) + + print("loss:", loss.numpy()) + + loss.backward() + + adam.step() + adam.clear_grad() + + + """ + fleet_env = fleet.fleet + + assert model is not None, "model should not be None" + if fleet_env.worker_num() <= 1: + return model + + amp_enable = False + strategy = fleet_env._user_defined_strategy + if strategy.amp == True: + amp_enable = True + amp_level = "O2" if strategy.amp_configs['use_pure_fp16'] else "O1" + if amp_level.upper() == "O2": + model = paddle.amp.decorate(models=model, + optimizers=None, + level="O2", + master_weight=None, + save_dtype=None) + init_loss_scaling = strategy.amp_configs['init_loss_scaling'] + incr_ratio = strategy.amp_configs['incr_ratio'] + decr_ratio = strategy.amp_configs['decr_ratio'] + incr_every_n_steps = strategy.amp_configs['incr_every_n_steps'] + decr_every_n_nan_or_inf = strategy.amp_configs[ + 'decr_every_n_nan_or_inf'] + use_dynamic_loss_scaling = strategy.amp_configs[ + 'use_dynamic_loss_scaling'] + + global _grad_scalar + _grad_scalar = paddle.amp.GradScaler( + init_loss_scaling=init_loss_scaling, + incr_ratio=incr_ratio, + decr_ratio=decr_ratio, + incr_every_n_steps=incr_every_n_steps, + decr_every_n_nan_or_inf=decr_every_n_nan_or_inf, + use_dynamic_loss_scaling=use_dynamic_loss_scaling) + + if strategy.heter_ccl_mode == True: + distributed_model = paddle.DataParallel( + model, + comm_buffer_size=strategy.fuse_grad_size_in_MB, + last_comm_buffer_size=strategy.last_comm_group_size_MB, + find_unused_parameters=strategy.find_unused_parameters) + return distributed_model + + if fleet_env._hcg.get_parallel_mode() == ParallelMode.SHARDING_PARALLEL: + model = ShardingParallel(model, fleet_env._hcg, strategy=strategy) + elif fleet_env._hcg.get_parallel_mode() == ParallelMode.DATA_PARALLEL: + + # NOTE (JZ-LIANG) init parameters broadcast within sharding group + # normally it should be done inside DataParallel + if fleet_env.sharding_degree > 1: + from paddle.distributed.fleet.utils.hybrid_parallel_util import broadcast_mp_parameters, broadcast_sharding_parameters + assert fleet_env.sharding_degree == fleet_env._hcg.get_sharding_parallel_world_size( + ) + broadcast_sharding_parameters(model, fleet_env._hcg) + model = paddle.DataParallel( + model, + comm_buffer_size=strategy.fuse_grad_size_in_MB, + last_comm_buffer_size=strategy.last_comm_group_size_MB, + find_unused_parameters=strategy.find_unused_parameters) + elif fleet_env._hcg.get_parallel_mode() == ParallelMode.TENSOR_PARALLEL: + model = TensorParallel(model, fleet_env._hcg, strategy=strategy) + elif fleet_env._hcg.get_parallel_mode() == ParallelMode.PIPELINE_PARALLEL: + assert isinstance( + model, PipelineLayer + ), "For pipeline parallel, the model should an instance of PipelineLayer" + if model.get_num_virtual_stages() == 1: + # 1f1b pipeline + model = PipelineParallel(model, fleet_env._hcg, strategy=strategy) + else: + # interleave pipeline + model = PipelineParallelWithInterleave(model, + fleet_env._hcg, + strategy=strategy) + + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ddad6511a0a645f88b4760f2281262beecc41124 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/optimizer.py @@ -0,0 +1,80 @@ +# Copyright (c) 2022 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. + +import copy +import paddle +import os +import numpy as np +from paddle.fluid.framework import dygraph_only, _global_flags +from .base.distributed_strategy import DistributedStrategy +from .meta_optimizers import HybridParallelOptimizer, HeterParallelOptimizer +from paddle.fluid import core +from paddle.distributed import fleet +from .utils.log_util import logger + + +def _dygraph_distributed_optimizer(optimizer, strategy=None): + """ + Optimizer for distributed training. + For the distributed training, this method would rebuild a new instance of DistributedOptimizer. + Which has basic Optimizer function and special features for distributed training. + Args: + optimizer(Optimizer): The executor to run for init server. + strategy(DistributedStrategy): Extra properties for distributed optimizer. + It is recommended to use DistributedStrategy in fleet.init(). The strategy + here is for compatibility. If the strategy in fleet.distributed_optimizer() + is not None, then it will overwrite the DistributedStrategy in fleet.init(), + which will take effect in distributed training. + Returns: + Fleet: instance of fleet. + Examples: + .. code-block:: python + import paddle + import paddle.distributed.fleet as fleet + fleet.init(is_collective=True) + strategy = fleet.DistributedStrategy() + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy) + """ + fleet_env = fleet.fleet + fleet_env.user_defined_optimizer = optimizer + + if strategy is not None: + if fleet_env._is_collective: + logger.warning( + "It is recommended to use DistributedStrategy " + "in fleet_env.init(). The strategy here is only for compatibility. " + "If the strategy in fleet_env.distributed_optimizer() is " + "not None, then it will overwrite the DistributedStrategy in fleet_env.init(), " + "which will take effect in distributed training.") + fleet_env._user_defined_strategy = copy.deepcopy(strategy) + + fleet_env._context = {} + + if fleet_env.worker_num() > 1: + if fleet_env._user_defined_strategy.heter_ccl_mode == False: + return HybridParallelOptimizer(optimizer, fleet_env._hcg, + fleet_env._user_defined_strategy) + else: + return HeterParallelOptimizer(optimizer, + fleet_env._user_defined_strategy) + else: + return optimizer + + +def distributed_optimizer(*args, **kwargs): + if paddle.fluid.framework._non_static_mode(): + return _dygraph_distributed_optimizer(*args, **kwargs) + else: + return fleet.fleet.distributed_optimizer(*args, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/distributed_strategy_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/distributed_strategy_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba70f2c82f3ec10ab6786b89887f3fb2bed2bd7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/distributed_strategy_pb2.py @@ -0,0 +1,2716 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: distributed_strategy.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='distributed_strategy.proto', + package='paddle.fleet', + syntax='proto2', + serialized_pb=_b('\n\x1a\x64istributed_strategy.proto\x12\x0cpaddle.fleet\"}\n\x0fRecomputeConfig\x12\x13\n\x0b\x63heckpoints\x18\x01 \x03(\t\x12\x1d\n\x0e\x65nable_offload\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x18\n\x10\x63heckpoint_shape\x18\x03 \x03(\x05\x12\x1c\n\renable_tuning\x18\x04 \x01(\x08:\x05\x66\x61lse\"\xe2\x03\n\x0eShardingConfig\x12\x37\n\x19sharding_segment_strategy\x18\x01 \x01(\t:\x14segment_broadcast_MB\x12 \n\x14segment_broadcast_MB\x18\x02 \x01(\x02:\x02\x33\x32\x12\x17\n\x0fsegment_anchors\x18\x03 \x03(\t\x12\x1a\n\x0fsharding_degree\x18\x04 \x01(\x05:\x01\x38\x12\x14\n\tmp_degree\x18\x05 \x01(\x05:\x01\x31\x12\x14\n\tdp_degree\x18\x06 \x01(\x05:\x01\x31\x12\x18\n\thybrid_dp\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\"\n\x17gradient_merge_acc_step\x18\x08 \x01(\x05:\x01\x31\x12\x1f\n\x10optimize_offload\x18\t \x01(\x08:\x05\x66\x61lse\x12\'\n\x18pp_allreduce_in_optimize\x18\n \x01(\x08:\x05\x66\x61lse\x12\x14\n\tpp_degree\x18\x0b \x01(\x05:\x01\x31\x12\x1c\n\roptimize_cast\x18\x0c \x01(\x08:\x05\x66\x61lse\x12(\n\x19_dp_as_optimizer_sharding\x18\r \x01(\x08:\x05\x66\x61lse\x12\x10\n\x05stage\x18\x0e \x01(\x05:\x01\x31\x12\x1c\n\renable_tuning\x18\x0f \x01(\x08:\x05\x66\x61lse\"m\n\x0cHybridConfig\x12\x15\n\tdp_degree\x18\x01 \x01(\x05:\x02-1\x12\x14\n\tmp_degree\x18\x02 \x01(\x05:\x01\x31\x12\x14\n\tpp_degree\x18\x03 \x01(\x05:\x01\x31\x12\x1a\n\x0fsharding_degree\x18\x04 \x01(\x05:\x01\x31\"\xff\x02\n\tAMPConfig\x12 \n\x11init_loss_scaling\x18\x01 \x01(\x02:\x05\x33\x32\x37\x36\x38\x12 \n\x12incr_every_n_steps\x18\x02 \x01(\x05:\x04\x31\x30\x30\x30\x12\"\n\x17\x64\x65\x63r_every_n_nan_or_inf\x18\x03 \x01(\x05:\x01\x32\x12\x15\n\nincr_ratio\x18\x04 \x01(\x02:\x01\x32\x12\x17\n\ndecr_ratio\x18\x05 \x01(\x02:\x03\x30.8\x12&\n\x18use_dynamic_loss_scaling\x18\x06 \x01(\x08:\x04true\x12\x19\n\x11\x63ustom_white_list\x18\x07 \x03(\t\x12\x19\n\x11\x63ustom_black_list\x18\x08 \x03(\t\x12\x1d\n\x15\x63ustom_black_varnames\x18\t \x03(\t\x12\x1c\n\ruse_pure_fp16\x18\n \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x0euse_fp16_guard\x18\x0b \x01(\x08:\x04true\x12!\n\x12use_optimizer_fp16\x18\x0c \x01(\x08:\x05\x66\x61lse\";\n\x0eLocalSGDConfig\x12\x12\n\x07k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x15\n\nbegin_step\x18\x02 \x01(\x05:\x01\x31\"H\n\x16\x41\x64\x61ptiveLocalSGDConfig\x12\x17\n\x0cinit_k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x15\n\nbegin_step\x18\x02 \x01(\x05:\x01\x31\"<\n\x13GradientMergeConfig\x12\x12\n\x07k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x11\n\x03\x61vg\x18\x02 \x01(\x08:\x04true\"S\n\tDGCConfig\x12\x1c\n\x11rampup_begin_step\x18\x01 \x01(\x05:\x01\x30\x12\x16\n\x0brampup_step\x18\x02 \x01(\x05:\x01\x31\x12\x10\n\x08sparsity\x18\x03 \x03(\x02\"\x81\x01\n\nLarsConfig\x12\x19\n\nlars_coeff\x18\x01 \x01(\x02:\x05\x30.001\x12!\n\x11lars_weight_decay\x18\x02 \x01(\x02:\x06\x30.0005\x12\x12\n\x07\x65psilon\x18\x03 \x01(\x02:\x01\x30\x12!\n\x19\x65xclude_from_weight_decay\x18\x04 \x03(\t\"P\n\nLambConfig\x12\x1f\n\x11lamb_weight_decay\x18\x01 \x01(\x02:\x04\x30.01\x12!\n\x19\x65xclude_from_weight_decay\x18\x02 \x03(\t\"\xf6\x04\n\rBuildStrategy\x12*\n\x1b\x65nable_sequential_execution\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x66use_elewise_add_act_ops\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0f\x66use_bn_act_ops\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x66use_relu_depthwise_conv\x18\x04 \x01(\x08:\x05\x66\x61lse\x12!\n\x12\x66use_broadcast_ops\x18\x05 \x01(\x08:\x05\x66\x61lse\x12%\n\x16\x66use_all_optimizer_ops\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0e\x65nable_inplace\x18\x07 \x01(\x08:\x05\x66\x61lse\x12/\n!enable_backward_optimizer_op_deps\x18\x08 \x01(\x08:\x04true\x12$\n\x15\x63\x61\x63he_runtime_context\x18\t \x01(\x08:\x05\x66\x61lse\x12!\n\x13\x66use_bn_add_act_ops\x18\n \x01(\x08:\x04true\x12!\n\x12\x65nable_auto_fusion\x18\x0b \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0c\x65nable_addto\x18\x0c \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10\x66ix_op_run_order\x18\r \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x61llow_cuda_graph_capture\x18\x0e \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0freduce_strategy\x18\x0f \x01(\x05:\x01\x30\x12!\n\x12\x66use_gemm_epilogue\x18\x10 \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x13\x64\x65\x62ug_graphviz_path\x18\x11 \x01(\t\"\x9a\x01\n\x11\x45xecutionStrategy\x12\x16\n\x0bnum_threads\x18\x01 \x01(\x05:\x01\x31\x12(\n\x1cnum_iteration_per_drop_scope\x18\x02 \x01(\x05:\x02\x31\x30\x12 \n\x15num_iteration_per_run\x18\x03 \x01(\x05:\x01\x31\x12!\n\x12use_thread_barrier\x18\x04 \x01(\x08:\x05\x66\x61lse\"Q\n\x13GradientScaleConfig\x12\x1b\n\x0escale_strategy\x18\x01 \x01(\t:\x03\x61vg\x12\x1d\n\x0escale_gradient\x18\x02 \x01(\x08:\x05\x66\x61lse\"\x89\x03\n\x0b\x41syncConfig\x12\x13\n\x07k_steps\x18\x01 \x01(\x05:\x02-1\x12\x1c\n\x11max_merge_var_num\x18\x02 \x01(\x05:\x01\x31\x12\x1b\n\x0fsend_queue_size\x18\x03 \x01(\x05:\x02\x31\x36\x12&\n\x17independent_recv_thread\x18\x04 \x01(\x08:\x05\x66\x61lse\x12(\n\x1dmin_send_grad_num_before_recv\x18\x05 \x01(\x05:\x01\x31\x12\x1b\n\x10thread_pool_size\x18\x06 \x01(\x05:\x01\x31\x12\x1a\n\x0fsend_wait_times\x18\x07 \x01(\x05:\x01\x31\x12&\n\x17runtime_split_send_recv\x18\x08 \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x0elaunch_barrier\x18\t \x01(\x08:\x04true\x12&\n\x19heter_worker_device_guard\x18\n \x01(\t:\x03\x63pu\x12\x1a\n\x0elr_decay_steps\x18\x0b \x01(\x05:\x02\x31\x30\x12\x15\n\nuse_ps_gpu\x18\x0c \x01(\x05:\x01\x30\"\xc3\x01\n\x11TrainerDescConfig\x12\x18\n\x10\x64ump_fields_path\x18\x01 \x01(\t\x12\x13\n\x0b\x64ump_fields\x18\x02 \x03(\t\x12\x12\n\ndump_param\x18\x03 \x03(\t\x12\x16\n\x0estat_var_names\x18\x04 \x03(\t\x12\x0f\n\x07trainer\x18\x05 \x01(\t\x12\x15\n\rdevice_worker\x18\x06 \x01(\t\x12\x14\n\x0clocal_sparse\x18\x07 \x03(\t\x12\x15\n\rremote_sparse\x18\x08 \x03(\t\"\xae\x01\n\x0ePipelineConfig\x12\x1b\n\x10micro_batch_size\x18\x01 \x01(\x05:\x01\x31\x12\x1b\n\x10\x61\x63\x63umulate_steps\x18\x02 \x01(\x05:\x01\x31\x12\x1b\n\rschedule_mode\x18\x03 \x01(\t:\x04\x31\x46\x31\x42\x12\x1d\n\x0fp2p_cache_shape\x18\x04 \x01(\x08:\x04true\x12&\n\x18\x65nable_partial_send_recv\x18\x05 \x01(\x08:\x04true\"W\n\x14TensorParallelConfig\x12!\n\x16tensor_parallel_degree\x18\x01 \x01(\x05:\x01\x31\x12\x1c\n\x10tensor_init_seed\x18\x02 \x01(\x05:\x02-1\"\x8c\x01\n\tQatConfig\x12\"\n\x14\x63hannel_wise_abs_max\x18\x01 \x01(\x08:\x04true\x12\x16\n\x0bweight_bits\x18\x02 \x01(\x05:\x01\x38\x12\x1a\n\x0f\x61\x63tivation_bits\x18\x03 \x01(\x05:\x01\x38\x12\x19\n\x11not_quant_pattern\x18\x04 \x03(\t\x12\x0c\n\x04\x61lgo\x18\x05 \x01(\t\"\x9b\x03\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x12\n\ntable_name\x18\x02 \x01(\t\x12\x13\n\x0btable_class\x18\x03 \x01(\t\x12\x17\n\tshard_num\x18\x04 \x01(\x04:\x04\x31\x30\x30\x30\x12%\n\x04type\x18\x05 \x01(\x0e\x32\x17.paddle.fleet.TableType\x12\x36\n\x08\x61\x63\x63\x65ssor\x18\x06 \x01(\x0b\x32$.paddle.fleet.TableAccessorParameter\x12\x1f\n\x10\x63ompress_in_save\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\'\n\x19\x65nable_sparse_table_cache\x18\n \x01(\x08:\x04true\x12(\n\x17sparse_table_cache_rate\x18\x0b \x01(\x01:\x07\x30.00055\x12\'\n\x1bsparse_table_cache_file_num\x18\x0c \x01(\r:\x02\x31\x36\x12\x1c\n\renable_revert\x18\r \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x10shard_merge_rate\x18\x0e \x01(\x02:\x01\x31\"\xac\x03\n\x16TableAccessorParameter\x12\x16\n\x0e\x61\x63\x63\x65ssor_class\x18\x01 \x01(\t\x12\x13\n\x07\x66\x65\x61_dim\x18\x04 \x01(\r:\x02\x31\x31\x12\x15\n\nembedx_dim\x18\x05 \x01(\r:\x01\x38\x12\x1c\n\x10\x65mbedx_threshold\x18\x06 \x01(\r:\x02\x31\x30\x12>\n\x12\x63tr_accessor_param\x18\x07 \x01(\x0b\x32\".paddle.fleet.CtrAccessorParameter\x12K\n\x19table_accessor_save_param\x18\x08 \x03(\x0b\x32(.paddle.fleet.TableAccessorSaveParameter\x12\x33\n\x0f\x65mbed_sgd_param\x18\n \x01(\x0b\x32\x1a.paddle.fleet.SGDParameter\x12\x34\n\x10\x65mbedx_sgd_param\x18\x0b \x01(\x0b\x32\x1a.paddle.fleet.SGDParameter\x12\x38\n\x0fgraph_sgd_param\x18\x0c \x01(\x0b\x32\x1f.paddle.fleet.GraphSGDParameter\"S\n\x11GraphSGDParameter\x12\x19\n\x0bnodeid_slot\x18\x01 \x01(\r:\x04\x39\x30\x30\x38\x12#\n\x15\x66\x65\x61ture_learning_rate\x18\x02 \x01(\x02:\x04\x30.05\"\xc8\x01\n\x0cSGDParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05naive\x18\x02 \x01(\x0b\x32).paddle.fleet.SparseNaiveSGDRuleParameter\x12<\n\x07\x61\x64\x61grad\x18\x03 \x01(\x0b\x32+.paddle.fleet.SparseAdagradSGDRuleParameter\x12\x32\n\x04\x61\x64\x61m\x18\x04 \x01(\x0b\x32$.paddle.fleet.SparseAdamSGDParameter\"p\n\x1bSparseNaiveSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x03 \x03(\x02\"\x8c\x01\n\x1dSparseAdagradSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x18\n\rinitial_g2sum\x18\x02 \x01(\x01:\x01\x33\x12\x1d\n\rinitial_range\x18\x03 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xc8\x01\n\x16SparseAdamSGDParameter\x12\x1c\n\rlearning_rate\x18\x01 \x01(\x01:\x05\x30.001\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x1d\n\x10\x62\x65ta1_decay_rate\x18\x03 \x01(\x01:\x03\x30.9\x12\x1f\n\x10\x62\x65ta2_decay_rate\x18\x04 \x01(\x01:\x05\x30.999\x12\x1a\n\x0b\x61\x64\x61_epsilon\x18\x05 \x01(\x01:\x05\x31\x65-08\x12\x15\n\rweight_bounds\x18\x06 \x03(\x02\"\xca\x02\n\x14\x43trAccessorParameter\x12\x19\n\x0cnonclk_coeff\x18\x01 \x01(\x02:\x03\x30.1\x12\x16\n\x0b\x63lick_coeff\x18\x02 \x01(\x02:\x01\x31\x12\x1b\n\x0e\x62\x61se_threshold\x18\x03 \x01(\x02:\x03\x31.5\x12\x1d\n\x0f\x64\x65lta_threshold\x18\x04 \x01(\x02:\x04\x30.25\x12\x1b\n\x0f\x64\x65lta_keep_days\x18\x05 \x01(\x02:\x02\x31\x36\x12#\n\x15show_click_decay_rate\x18\x06 \x01(\x02:\x04\x30.98\x12\x1d\n\x10\x64\x65lete_threshold\x18\x07 \x01(\x02:\x03\x30.8\x12$\n\x18\x64\x65lete_after_unseen_days\x18\x08 \x01(\x02:\x02\x33\x30\x12\"\n\x17ssd_unseenday_threshold\x18\t \x01(\x05:\x01\x31\x12\x18\n\nshow_scale\x18\n \x01(\x08:\x04true\"S\n\x1aTableAccessorSaveParameter\x12\r\n\x05param\x18\x01 \x01(\r\x12\x11\n\tconverter\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65\x63onverter\x18\x03 \x01(\t\"R\n\x11\x46sClientParameter\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x0c\n\x04user\x18\x02 \x01(\t\x12\x0e\n\x06passwd\x18\x03 \x01(\t\x12\x12\n\nhadoop_bin\x18\x04 \x01(\t\"\xa3\x13\n\x13\x44istributedStrategy\x12,\n\x04mode\x18\x01 \x01(\x0e\x32\x12.paddle.fleet.Mode:\nCOLLECTIVE\x12\x12\n\x03\x61mp\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x18\n\trecompute\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08localsgd\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03\x64gc\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0egradient_merge\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04lars\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04lamb\x18\x08 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08pipeline\x18\t \x01(\x08:\x05\x66\x61lse\x12\x16\n\x07\x65lastic\x18\n \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04\x61uto\x18\x0b \x01(\x08:\x05\x66\x61lse\x12\x14\n\x06\x61_sync\x18\x0c \x01(\x08:\x04true\x12!\n\x13sync_nccl_allreduce\x18\r \x01(\x08:\x04true\x12\x18\n\rnccl_comm_num\x18\x0e \x01(\x05:\x01\x31\x12)\n\x1ause_hierarchical_allreduce\x18\x0f \x01(\x08:\x05\x66\x61lse\x12.\n#hierarchical_allreduce_inter_nranks\x18\x10 \x01(\x05:\x01\x31\x12\x1e\n\x0fsync_batch_norm\x18\x11 \x01(\x08:\x05\x66\x61lse\x12!\n\x13\x66use_all_reduce_ops\x18\x12 \x01(\x08:\x04true\x12 \n\x14\x66use_grad_size_in_MB\x18\x13 \x01(\x05:\x02\x33\x32\x12$\n\x18\x66use_grad_size_in_TFLOPS\x18\x14 \x01(\x02:\x02\x35\x30\x12&\n\x17\x63udnn_exhaustive_search\x18\x15 \x01(\x08:\x05\x66\x61lse\x12&\n\x19\x63onv_workspace_size_limit\x18\x16 \x01(\x05:\x03\x35\x31\x32\x12\x31\n\"cudnn_batchnorm_spatial_persistent\x18\x17 \x01(\x08:\x05\x66\x61lse\x12 \n\x11\x61\x64\x61ptive_localsgd\x18\x18 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0e\x66p16_allreduce\x18\x19 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08sharding\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\"\n\x17last_comm_group_size_MB\x18\x1b \x01(\x02:\x01\x31\x12%\n\x16\x66ind_unused_parameters\x18\x1c \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0ftensor_parallel\x18\x1d \x01(\x08:\x05\x66\x61lse\x12)\n\x1awithout_graph_optimization\x18\x1e \x01(\x08:\x05\x66\x61lse\x12 \n\x15\x66use_grad_size_in_num\x18\x1f \x01(\x05:\x01\x38\x12$\n\x15\x63\x61lc_comm_same_stream\x18 \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03\x61sp\x18! \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0f\x66use_grad_merge\x18\" \x01(\x08:\x05\x66\x61lse\x12\x18\n\tsemi_auto\x18# \x01(\x08:\x05\x66\x61lse\x12\x19\n\nadam_d2sum\x18$ \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0b\x61uto_search\x18% \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0eheter_ccl_mode\x18& \x01(\x08:\x05\x66\x61lse\x12\x1c\n\ris_fl_ps_mode\x18\' \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10with_coordinator\x18( \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03qat\x18) \x01(\x08:\x05\x66\x61lse\x12\x18\n\nsplit_data\x18* \x01(\x08:\x04true\x12\x38\n\x11recompute_configs\x18\x65 \x01(\x0b\x32\x1d.paddle.fleet.RecomputeConfig\x12,\n\x0b\x61mp_configs\x18\x66 \x01(\x0b\x32\x17.paddle.fleet.AMPConfig\x12\x36\n\x10localsgd_configs\x18g \x01(\x0b\x32\x1c.paddle.fleet.LocalSGDConfig\x12\x41\n\x16gradient_merge_configs\x18h \x01(\x0b\x32!.paddle.fleet.GradientMergeConfig\x12,\n\x0b\x64gc_configs\x18i \x01(\x0b\x32\x17.paddle.fleet.DGCConfig\x12\x36\n\x10pipeline_configs\x18j \x01(\x0b\x32\x1c.paddle.fleet.PipelineConfig\x12\x31\n\x0e\x61_sync_configs\x18k \x01(\x0b\x32\x19.paddle.fleet.AsyncConfig\x12.\n\x0clars_configs\x18l \x01(\x0b\x32\x18.paddle.fleet.LarsConfig\x12.\n\x0clamb_configs\x18m \x01(\x0b\x32\x18.paddle.fleet.LambConfig\x12G\n\x19\x61\x64\x61ptive_localsgd_configs\x18n \x01(\x0b\x32$.paddle.fleet.AdaptiveLocalSGDConfig\x12\x36\n\x10sharding_configs\x18o \x01(\x0b\x32\x1c.paddle.fleet.ShardingConfig\x12\x32\n\x0ehybrid_configs\x18p \x01(\x0b\x32\x1a.paddle.fleet.HybridConfig\x12\x43\n\x17tensor_parallel_configs\x18q \x01(\x0b\x32\".paddle.fleet.TensorParallelConfig\x12=\n\x14trainer_desc_configs\x18r \x01(\x0b\x32\x1f.paddle.fleet.TrainerDescConfig\x12:\n\x14\x64ownpour_table_param\x18s \x03(\x0b\x32\x1c.paddle.fleet.TableParameter\x12\x38\n\x0f\x66s_client_param\x18t \x01(\x0b\x32\x1f.paddle.fleet.FsClientParameter\x12,\n\x0bqat_configs\x18u \x01(\x0b\x32\x17.paddle.fleet.QatConfig\x12\x34\n\x0e\x62uild_strategy\x18\xc9\x01 \x01(\x0b\x32\x1b.paddle.fleet.BuildStrategy\x12<\n\x12\x65xecution_strategy\x18\xca\x01 \x01(\x0b\x32\x1f.paddle.fleet.ExecutionStrategy\x12\x42\n\x16gradient_scale_configs\x18\xcb\x01 \x01(\x0b\x32!.paddle.fleet.GradientScaleConfig\"\xfe\x01\n\x12\x44istributedJobInfo\x12\x12\n\nworker_num\x18\x01 \x01(\x05\x12\x12\n\nserver_num\x18\x02 \x01(\x05\x12\x12\n\nworker_ips\x18\x03 \x03(\t\x12\x18\n\x10server_endpoints\x18\x04 \x03(\t\x12\x16\n\x0eorigin_startup\x18\x05 \x01(\t\x12\x13\n\x0borigin_main\x18\x06 \x01(\t\x12\x18\n\x10\x64istributed_main\x18\x07 \x01(\t\x12\x16\n\x0eoptimizer_name\x18\x08 \x01(\t\x12\x33\n\x08strategy\x18\x65 \x01(\x0b\x32!.paddle.fleet.DistributedStrategy*7\n\x04Mode\x12\x0e\n\nCOLLECTIVE\x10\x01\x12\x06\n\x02PS\x10\x02\x12\x0c\n\x08PIPELINE\x10\x03\x12\t\n\x05HETER\x10\x04*4\n\tTableType\x12\x13\n\x0fPS_SPARSE_TABLE\x10\x00\x12\x12\n\x0ePS_DENSE_TABLE\x10\x01') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_MODE = _descriptor.EnumDescriptor( + name='Mode', + full_name='paddle.fleet.Mode', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='COLLECTIVE', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PIPELINE', index=2, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='HETER', index=3, number=4, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=8347, + serialized_end=8402, +) +_sym_db.RegisterEnumDescriptor(_MODE) + +Mode = enum_type_wrapper.EnumTypeWrapper(_MODE) +_TABLETYPE = _descriptor.EnumDescriptor( + name='TableType', + full_name='paddle.fleet.TableType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='PS_SPARSE_TABLE', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_DENSE_TABLE', index=1, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=8404, + serialized_end=8456, +) +_sym_db.RegisterEnumDescriptor(_TABLETYPE) + +TableType = enum_type_wrapper.EnumTypeWrapper(_TABLETYPE) +COLLECTIVE = 1 +PS = 2 +PIPELINE = 3 +HETER = 4 +PS_SPARSE_TABLE = 0 +PS_DENSE_TABLE = 1 + + + +_RECOMPUTECONFIG = _descriptor.Descriptor( + name='RecomputeConfig', + full_name='paddle.fleet.RecomputeConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='checkpoints', full_name='paddle.fleet.RecomputeConfig.checkpoints', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_offload', full_name='paddle.fleet.RecomputeConfig.enable_offload', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='checkpoint_shape', full_name='paddle.fleet.RecomputeConfig.checkpoint_shape', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_tuning', full_name='paddle.fleet.RecomputeConfig.enable_tuning', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=44, + serialized_end=169, +) + + +_SHARDINGCONFIG = _descriptor.Descriptor( + name='ShardingConfig', + full_name='paddle.fleet.ShardingConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sharding_segment_strategy', full_name='paddle.fleet.ShardingConfig.sharding_segment_strategy', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("segment_broadcast_MB").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='segment_broadcast_MB', full_name='paddle.fleet.ShardingConfig.segment_broadcast_MB', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(32), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='segment_anchors', full_name='paddle.fleet.ShardingConfig.segment_anchors', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_degree', full_name='paddle.fleet.ShardingConfig.sharding_degree', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mp_degree', full_name='paddle.fleet.ShardingConfig.mp_degree', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dp_degree', full_name='paddle.fleet.ShardingConfig.dp_degree', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hybrid_dp', full_name='paddle.fleet.ShardingConfig.hybrid_dp', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge_acc_step', full_name='paddle.fleet.ShardingConfig.gradient_merge_acc_step', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimize_offload', full_name='paddle.fleet.ShardingConfig.optimize_offload', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_allreduce_in_optimize', full_name='paddle.fleet.ShardingConfig.pp_allreduce_in_optimize', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_degree', full_name='paddle.fleet.ShardingConfig.pp_degree', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimize_cast', full_name='paddle.fleet.ShardingConfig.optimize_cast', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='_dp_as_optimizer_sharding', full_name='paddle.fleet.ShardingConfig._dp_as_optimizer_sharding', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stage', full_name='paddle.fleet.ShardingConfig.stage', index=13, + number=14, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_tuning', full_name='paddle.fleet.ShardingConfig.enable_tuning', index=14, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=172, + serialized_end=654, +) + + +_HYBRIDCONFIG = _descriptor.Descriptor( + name='HybridConfig', + full_name='paddle.fleet.HybridConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dp_degree', full_name='paddle.fleet.HybridConfig.dp_degree', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mp_degree', full_name='paddle.fleet.HybridConfig.mp_degree', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_degree', full_name='paddle.fleet.HybridConfig.pp_degree', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_degree', full_name='paddle.fleet.HybridConfig.sharding_degree', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=656, + serialized_end=765, +) + + +_AMPCONFIG = _descriptor.Descriptor( + name='AMPConfig', + full_name='paddle.fleet.AMPConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='init_loss_scaling', full_name='paddle.fleet.AMPConfig.init_loss_scaling', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(32768), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='incr_every_n_steps', full_name='paddle.fleet.AMPConfig.incr_every_n_steps', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='decr_every_n_nan_or_inf', full_name='paddle.fleet.AMPConfig.decr_every_n_nan_or_inf', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=2, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='incr_ratio', full_name='paddle.fleet.AMPConfig.incr_ratio', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(2), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='decr_ratio', full_name='paddle.fleet.AMPConfig.decr_ratio', index=4, + number=5, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.8), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_dynamic_loss_scaling', full_name='paddle.fleet.AMPConfig.use_dynamic_loss_scaling', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_white_list', full_name='paddle.fleet.AMPConfig.custom_white_list', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_black_list', full_name='paddle.fleet.AMPConfig.custom_black_list', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_black_varnames', full_name='paddle.fleet.AMPConfig.custom_black_varnames', index=8, + number=9, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_pure_fp16', full_name='paddle.fleet.AMPConfig.use_pure_fp16', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_fp16_guard', full_name='paddle.fleet.AMPConfig.use_fp16_guard', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_optimizer_fp16', full_name='paddle.fleet.AMPConfig.use_optimizer_fp16', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=768, + serialized_end=1151, +) + + +_LOCALSGDCONFIG = _descriptor.Descriptor( + name='LocalSGDConfig', + full_name='paddle.fleet.LocalSGDConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.LocalSGDConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='begin_step', full_name='paddle.fleet.LocalSGDConfig.begin_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1153, + serialized_end=1212, +) + + +_ADAPTIVELOCALSGDCONFIG = _descriptor.Descriptor( + name='AdaptiveLocalSGDConfig', + full_name='paddle.fleet.AdaptiveLocalSGDConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='init_k_steps', full_name='paddle.fleet.AdaptiveLocalSGDConfig.init_k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='begin_step', full_name='paddle.fleet.AdaptiveLocalSGDConfig.begin_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1214, + serialized_end=1286, +) + + +_GRADIENTMERGECONFIG = _descriptor.Descriptor( + name='GradientMergeConfig', + full_name='paddle.fleet.GradientMergeConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.GradientMergeConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg', full_name='paddle.fleet.GradientMergeConfig.avg', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1288, + serialized_end=1348, +) + + +_DGCCONFIG = _descriptor.Descriptor( + name='DGCConfig', + full_name='paddle.fleet.DGCConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='rampup_begin_step', full_name='paddle.fleet.DGCConfig.rampup_begin_step', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='rampup_step', full_name='paddle.fleet.DGCConfig.rampup_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparsity', full_name='paddle.fleet.DGCConfig.sparsity', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1350, + serialized_end=1433, +) + + +_LARSCONFIG = _descriptor.Descriptor( + name='LarsConfig', + full_name='paddle.fleet.LarsConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='lars_coeff', full_name='paddle.fleet.LarsConfig.lars_coeff', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars_weight_decay', full_name='paddle.fleet.LarsConfig.lars_weight_decay', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.0005), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='epsilon', full_name='paddle.fleet.LarsConfig.epsilon', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='exclude_from_weight_decay', full_name='paddle.fleet.LarsConfig.exclude_from_weight_decay', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1436, + serialized_end=1565, +) + + +_LAMBCONFIG = _descriptor.Descriptor( + name='LambConfig', + full_name='paddle.fleet.LambConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='lamb_weight_decay', full_name='paddle.fleet.LambConfig.lamb_weight_decay', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.01), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='exclude_from_weight_decay', full_name='paddle.fleet.LambConfig.exclude_from_weight_decay', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1567, + serialized_end=1647, +) + + +_BUILDSTRATEGY = _descriptor.Descriptor( + name='BuildStrategy', + full_name='paddle.fleet.BuildStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='enable_sequential_execution', full_name='paddle.fleet.BuildStrategy.enable_sequential_execution', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_elewise_add_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_elewise_add_act_ops', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_bn_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_bn_act_ops', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_relu_depthwise_conv', full_name='paddle.fleet.BuildStrategy.fuse_relu_depthwise_conv', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_broadcast_ops', full_name='paddle.fleet.BuildStrategy.fuse_broadcast_ops', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_all_optimizer_ops', full_name='paddle.fleet.BuildStrategy.fuse_all_optimizer_ops', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_inplace', full_name='paddle.fleet.BuildStrategy.enable_inplace', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_backward_optimizer_op_deps', full_name='paddle.fleet.BuildStrategy.enable_backward_optimizer_op_deps', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cache_runtime_context', full_name='paddle.fleet.BuildStrategy.cache_runtime_context', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_bn_add_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_bn_add_act_ops', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_auto_fusion', full_name='paddle.fleet.BuildStrategy.enable_auto_fusion', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_addto', full_name='paddle.fleet.BuildStrategy.enable_addto', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fix_op_run_order', full_name='paddle.fleet.BuildStrategy.fix_op_run_order', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='allow_cuda_graph_capture', full_name='paddle.fleet.BuildStrategy.allow_cuda_graph_capture', index=13, + number=14, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='reduce_strategy', full_name='paddle.fleet.BuildStrategy.reduce_strategy', index=14, + number=15, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_gemm_epilogue', full_name='paddle.fleet.BuildStrategy.fuse_gemm_epilogue', index=15, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='debug_graphviz_path', full_name='paddle.fleet.BuildStrategy.debug_graphviz_path', index=16, + number=17, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1650, + serialized_end=2280, +) + + +_EXECUTIONSTRATEGY = _descriptor.Descriptor( + name='ExecutionStrategy', + full_name='paddle.fleet.ExecutionStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='num_threads', full_name='paddle.fleet.ExecutionStrategy.num_threads', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_iteration_per_drop_scope', full_name='paddle.fleet.ExecutionStrategy.num_iteration_per_drop_scope', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_iteration_per_run', full_name='paddle.fleet.ExecutionStrategy.num_iteration_per_run', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_thread_barrier', full_name='paddle.fleet.ExecutionStrategy.use_thread_barrier', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2283, + serialized_end=2437, +) + + +_GRADIENTSCALECONFIG = _descriptor.Descriptor( + name='GradientScaleConfig', + full_name='paddle.fleet.GradientScaleConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='scale_strategy', full_name='paddle.fleet.GradientScaleConfig.scale_strategy', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("avg").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='scale_gradient', full_name='paddle.fleet.GradientScaleConfig.scale_gradient', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2439, + serialized_end=2520, +) + + +_ASYNCCONFIG = _descriptor.Descriptor( + name='AsyncConfig', + full_name='paddle.fleet.AsyncConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.AsyncConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='max_merge_var_num', full_name='paddle.fleet.AsyncConfig.max_merge_var_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='send_queue_size', full_name='paddle.fleet.AsyncConfig.send_queue_size', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='independent_recv_thread', full_name='paddle.fleet.AsyncConfig.independent_recv_thread', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='min_send_grad_num_before_recv', full_name='paddle.fleet.AsyncConfig.min_send_grad_num_before_recv', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_pool_size', full_name='paddle.fleet.AsyncConfig.thread_pool_size', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='send_wait_times', full_name='paddle.fleet.AsyncConfig.send_wait_times', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='runtime_split_send_recv', full_name='paddle.fleet.AsyncConfig.runtime_split_send_recv', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='launch_barrier', full_name='paddle.fleet.AsyncConfig.launch_barrier', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='heter_worker_device_guard', full_name='paddle.fleet.AsyncConfig.heter_worker_device_guard', index=9, + number=10, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("cpu").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lr_decay_steps', full_name='paddle.fleet.AsyncConfig.lr_decay_steps', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_ps_gpu', full_name='paddle.fleet.AsyncConfig.use_ps_gpu', index=11, + number=12, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2523, + serialized_end=2916, +) + + +_TRAINERDESCCONFIG = _descriptor.Descriptor( + name='TrainerDescConfig', + full_name='paddle.fleet.TrainerDescConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dump_fields_path', full_name='paddle.fleet.TrainerDescConfig.dump_fields_path', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_fields', full_name='paddle.fleet.TrainerDescConfig.dump_fields', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_param', full_name='paddle.fleet.TrainerDescConfig.dump_param', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stat_var_names', full_name='paddle.fleet.TrainerDescConfig.stat_var_names', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer', full_name='paddle.fleet.TrainerDescConfig.trainer', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_worker', full_name='paddle.fleet.TrainerDescConfig.device_worker', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='local_sparse', full_name='paddle.fleet.TrainerDescConfig.local_sparse', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='remote_sparse', full_name='paddle.fleet.TrainerDescConfig.remote_sparse', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2919, + serialized_end=3114, +) + + +_PIPELINECONFIG = _descriptor.Descriptor( + name='PipelineConfig', + full_name='paddle.fleet.PipelineConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='micro_batch_size', full_name='paddle.fleet.PipelineConfig.micro_batch_size', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='accumulate_steps', full_name='paddle.fleet.PipelineConfig.accumulate_steps', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='schedule_mode', full_name='paddle.fleet.PipelineConfig.schedule_mode', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("1F1B").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='p2p_cache_shape', full_name='paddle.fleet.PipelineConfig.p2p_cache_shape', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_partial_send_recv', full_name='paddle.fleet.PipelineConfig.enable_partial_send_recv', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3117, + serialized_end=3291, +) + + +_TENSORPARALLELCONFIG = _descriptor.Descriptor( + name='TensorParallelConfig', + full_name='paddle.fleet.TensorParallelConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='tensor_parallel_degree', full_name='paddle.fleet.TensorParallelConfig.tensor_parallel_degree', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_init_seed', full_name='paddle.fleet.TensorParallelConfig.tensor_init_seed', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3293, + serialized_end=3380, +) + + +_QATCONFIG = _descriptor.Descriptor( + name='QatConfig', + full_name='paddle.fleet.QatConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='channel_wise_abs_max', full_name='paddle.fleet.QatConfig.channel_wise_abs_max', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bits', full_name='paddle.fleet.QatConfig.weight_bits', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='activation_bits', full_name='paddle.fleet.QatConfig.activation_bits', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='not_quant_pattern', full_name='paddle.fleet.QatConfig.not_quant_pattern', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='algo', full_name='paddle.fleet.QatConfig.algo', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3383, + serialized_end=3523, +) + + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.fleet.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.fleet.TableParameter.table_id', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_name', full_name='paddle.fleet.TableParameter.table_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_class', full_name='paddle.fleet.TableParameter.table_class', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_num', full_name='paddle.fleet.TableParameter.shard_num', index=3, + number=4, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=1000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.fleet.TableParameter.type', index=4, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='accessor', full_name='paddle.fleet.TableParameter.accessor', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compress_in_save', full_name='paddle.fleet.TableParameter.compress_in_save', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_sparse_table_cache', full_name='paddle.fleet.TableParameter.enable_sparse_table_cache', index=7, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_rate', full_name='paddle.fleet.TableParameter.sparse_table_cache_rate', index=8, + number=11, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.00055), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_file_num', full_name='paddle.fleet.TableParameter.sparse_table_cache_file_num', index=9, + number=12, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_revert', full_name='paddle.fleet.TableParameter.enable_revert', index=10, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_merge_rate', full_name='paddle.fleet.TableParameter.shard_merge_rate', index=11, + number=14, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3526, + serialized_end=3937, +) + + +_TABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='TableAccessorParameter', + full_name='paddle.fleet.TableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='accessor_class', full_name='paddle.fleet.TableAccessorParameter.accessor_class', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', full_name='paddle.fleet.TableAccessorParameter.fea_dim', index=1, + number=4, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=11, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_dim', full_name='paddle.fleet.TableAccessorParameter.embedx_dim', index=2, + number=5, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_threshold', full_name='paddle.fleet.TableAccessorParameter.embedx_threshold', index=3, + number=6, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ctr_accessor_param', full_name='paddle.fleet.TableAccessorParameter.ctr_accessor_param', index=4, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_accessor_save_param', full_name='paddle.fleet.TableAccessorParameter.table_accessor_save_param', index=5, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embed_sgd_param', full_name='paddle.fleet.TableAccessorParameter.embed_sgd_param', index=6, + number=10, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_sgd_param', full_name='paddle.fleet.TableAccessorParameter.embedx_sgd_param', index=7, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_sgd_param', full_name='paddle.fleet.TableAccessorParameter.graph_sgd_param', index=8, + number=12, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3940, + serialized_end=4368, +) + + +_GRAPHSGDPARAMETER = _descriptor.Descriptor( + name='GraphSGDParameter', + full_name='paddle.fleet.GraphSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nodeid_slot', full_name='paddle.fleet.GraphSGDParameter.nodeid_slot', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=9008, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_learning_rate', full_name='paddle.fleet.GraphSGDParameter.feature_learning_rate', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4370, + serialized_end=4453, +) + + +_SGDPARAMETER = _descriptor.Descriptor( + name='SGDParameter', + full_name='paddle.fleet.SGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.fleet.SGDParameter.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', full_name='paddle.fleet.SGDParameter.naive', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adagrad', full_name='paddle.fleet.SGDParameter.adagrad', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', full_name='paddle.fleet.SGDParameter.adam', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4456, + serialized_end=4656, +) + + +_SPARSENAIVESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseNaiveSGDRuleParameter', + full_name='paddle.fleet.SparseNaiveSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.weight_bounds', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4658, + serialized_end=4770, +) + + +_SPARSEADAGRADSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseAdagradSGDRuleParameter', + full_name='paddle.fleet.SparseAdagradSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.initial_g2sum', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(3), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.initial_range', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.weight_bounds', index=3, + number=4, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4773, + serialized_end=4913, +) + + +_SPARSEADAMSGDPARAMETER = _descriptor.Descriptor( + name='SparseAdamSGDParameter', + full_name='paddle.fleet.SparseAdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseAdamSGDParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseAdamSGDParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta1_decay_rate', full_name='paddle.fleet.SparseAdamSGDParameter.beta1_decay_rate', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.9), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta2_decay_rate', full_name='paddle.fleet.SparseAdamSGDParameter.beta2_decay_rate', index=3, + number=4, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.999), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', full_name='paddle.fleet.SparseAdamSGDParameter.ada_epsilon', index=4, + number=5, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(1e-08), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseAdamSGDParameter.weight_bounds', index=5, + number=6, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4916, + serialized_end=5116, +) + + +_CTRACCESSORPARAMETER = _descriptor.Descriptor( + name='CtrAccessorParameter', + full_name='paddle.fleet.CtrAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nonclk_coeff', full_name='paddle.fleet.CtrAccessorParameter.nonclk_coeff', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='click_coeff', full_name='paddle.fleet.CtrAccessorParameter.click_coeff', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='base_threshold', full_name='paddle.fleet.CtrAccessorParameter.base_threshold', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1.5), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_threshold', full_name='paddle.fleet.CtrAccessorParameter.delta_threshold', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.25), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_keep_days', full_name='paddle.fleet.CtrAccessorParameter.delta_keep_days', index=4, + number=5, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(16), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_click_decay_rate', full_name='paddle.fleet.CtrAccessorParameter.show_click_decay_rate', index=5, + number=6, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.98), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_threshold', full_name='paddle.fleet.CtrAccessorParameter.delete_threshold', index=6, + number=7, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.8), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_after_unseen_days', full_name='paddle.fleet.CtrAccessorParameter.delete_after_unseen_days', index=7, + number=8, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(30), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ssd_unseenday_threshold', full_name='paddle.fleet.CtrAccessorParameter.ssd_unseenday_threshold', index=8, + number=9, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_scale', full_name='paddle.fleet.CtrAccessorParameter.show_scale', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5119, + serialized_end=5449, +) + + +_TABLEACCESSORSAVEPARAMETER = _descriptor.Descriptor( + name='TableAccessorSaveParameter', + full_name='paddle.fleet.TableAccessorSaveParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='param', full_name='paddle.fleet.TableAccessorSaveParameter.param', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='converter', full_name='paddle.fleet.TableAccessorSaveParameter.converter', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deconverter', full_name='paddle.fleet.TableAccessorSaveParameter.deconverter', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5451, + serialized_end=5534, +) + + +_FSCLIENTPARAMETER = _descriptor.Descriptor( + name='FsClientParameter', + full_name='paddle.fleet.FsClientParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='uri', full_name='paddle.fleet.FsClientParameter.uri', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='user', full_name='paddle.fleet.FsClientParameter.user', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='passwd', full_name='paddle.fleet.FsClientParameter.passwd', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hadoop_bin', full_name='paddle.fleet.FsClientParameter.hadoop_bin', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5536, + serialized_end=5618, +) + + +_DISTRIBUTEDSTRATEGY = _descriptor.Descriptor( + name='DistributedStrategy', + full_name='paddle.fleet.DistributedStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='mode', full_name='paddle.fleet.DistributedStrategy.mode', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='amp', full_name='paddle.fleet.DistributedStrategy.amp', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='recompute', full_name='paddle.fleet.DistributedStrategy.recompute', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='localsgd', full_name='paddle.fleet.DistributedStrategy.localsgd', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dgc', full_name='paddle.fleet.DistributedStrategy.dgc', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge', full_name='paddle.fleet.DistributedStrategy.gradient_merge', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars', full_name='paddle.fleet.DistributedStrategy.lars', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lamb', full_name='paddle.fleet.DistributedStrategy.lamb', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline', full_name='paddle.fleet.DistributedStrategy.pipeline', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='elastic', full_name='paddle.fleet.DistributedStrategy.elastic', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='auto', full_name='paddle.fleet.DistributedStrategy.auto', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='a_sync', full_name='paddle.fleet.DistributedStrategy.a_sync', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_nccl_allreduce', full_name='paddle.fleet.DistributedStrategy.sync_nccl_allreduce', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nccl_comm_num', full_name='paddle.fleet.DistributedStrategy.nccl_comm_num', index=13, + number=14, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_hierarchical_allreduce', full_name='paddle.fleet.DistributedStrategy.use_hierarchical_allreduce', index=14, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hierarchical_allreduce_inter_nranks', full_name='paddle.fleet.DistributedStrategy.hierarchical_allreduce_inter_nranks', index=15, + number=16, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_batch_norm', full_name='paddle.fleet.DistributedStrategy.sync_batch_norm', index=16, + number=17, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_all_reduce_ops', full_name='paddle.fleet.DistributedStrategy.fuse_all_reduce_ops', index=17, + number=18, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_MB', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_MB', index=18, + number=19, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=32, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_TFLOPS', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_TFLOPS', index=19, + number=20, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(50), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cudnn_exhaustive_search', full_name='paddle.fleet.DistributedStrategy.cudnn_exhaustive_search', index=20, + number=21, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='conv_workspace_size_limit', full_name='paddle.fleet.DistributedStrategy.conv_workspace_size_limit', index=21, + number=22, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=512, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cudnn_batchnorm_spatial_persistent', full_name='paddle.fleet.DistributedStrategy.cudnn_batchnorm_spatial_persistent', index=22, + number=23, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adaptive_localsgd', full_name='paddle.fleet.DistributedStrategy.adaptive_localsgd', index=23, + number=24, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fp16_allreduce', full_name='paddle.fleet.DistributedStrategy.fp16_allreduce', index=24, + number=25, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding', full_name='paddle.fleet.DistributedStrategy.sharding', index=25, + number=26, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='last_comm_group_size_MB', full_name='paddle.fleet.DistributedStrategy.last_comm_group_size_MB', index=26, + number=27, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='find_unused_parameters', full_name='paddle.fleet.DistributedStrategy.find_unused_parameters', index=27, + number=28, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_parallel', full_name='paddle.fleet.DistributedStrategy.tensor_parallel', index=28, + number=29, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='without_graph_optimization', full_name='paddle.fleet.DistributedStrategy.without_graph_optimization', index=29, + number=30, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_num', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_num', index=30, + number=31, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='calc_comm_same_stream', full_name='paddle.fleet.DistributedStrategy.calc_comm_same_stream', index=31, + number=32, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='asp', full_name='paddle.fleet.DistributedStrategy.asp', index=32, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_merge', full_name='paddle.fleet.DistributedStrategy.fuse_grad_merge', index=33, + number=34, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='semi_auto', full_name='paddle.fleet.DistributedStrategy.semi_auto', index=34, + number=35, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam_d2sum', full_name='paddle.fleet.DistributedStrategy.adam_d2sum', index=35, + number=36, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='auto_search', full_name='paddle.fleet.DistributedStrategy.auto_search', index=36, + number=37, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='heter_ccl_mode', full_name='paddle.fleet.DistributedStrategy.heter_ccl_mode', index=37, + number=38, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_fl_ps_mode', full_name='paddle.fleet.DistributedStrategy.is_fl_ps_mode', index=38, + number=39, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='with_coordinator', full_name='paddle.fleet.DistributedStrategy.with_coordinator', index=39, + number=40, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='qat', full_name='paddle.fleet.DistributedStrategy.qat', index=40, + number=41, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='split_data', full_name='paddle.fleet.DistributedStrategy.split_data', index=41, + number=42, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='recompute_configs', full_name='paddle.fleet.DistributedStrategy.recompute_configs', index=42, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='amp_configs', full_name='paddle.fleet.DistributedStrategy.amp_configs', index=43, + number=102, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='localsgd_configs', full_name='paddle.fleet.DistributedStrategy.localsgd_configs', index=44, + number=103, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge_configs', full_name='paddle.fleet.DistributedStrategy.gradient_merge_configs', index=45, + number=104, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dgc_configs', full_name='paddle.fleet.DistributedStrategy.dgc_configs', index=46, + number=105, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline_configs', full_name='paddle.fleet.DistributedStrategy.pipeline_configs', index=47, + number=106, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='a_sync_configs', full_name='paddle.fleet.DistributedStrategy.a_sync_configs', index=48, + number=107, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars_configs', full_name='paddle.fleet.DistributedStrategy.lars_configs', index=49, + number=108, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lamb_configs', full_name='paddle.fleet.DistributedStrategy.lamb_configs', index=50, + number=109, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adaptive_localsgd_configs', full_name='paddle.fleet.DistributedStrategy.adaptive_localsgd_configs', index=51, + number=110, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_configs', full_name='paddle.fleet.DistributedStrategy.sharding_configs', index=52, + number=111, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hybrid_configs', full_name='paddle.fleet.DistributedStrategy.hybrid_configs', index=53, + number=112, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_parallel_configs', full_name='paddle.fleet.DistributedStrategy.tensor_parallel_configs', index=54, + number=113, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_desc_configs', full_name='paddle.fleet.DistributedStrategy.trainer_desc_configs', index=55, + number=114, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='downpour_table_param', full_name='paddle.fleet.DistributedStrategy.downpour_table_param', index=56, + number=115, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fs_client_param', full_name='paddle.fleet.DistributedStrategy.fs_client_param', index=57, + number=116, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='qat_configs', full_name='paddle.fleet.DistributedStrategy.qat_configs', index=58, + number=117, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='build_strategy', full_name='paddle.fleet.DistributedStrategy.build_strategy', index=59, + number=201, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='execution_strategy', full_name='paddle.fleet.DistributedStrategy.execution_strategy', index=60, + number=202, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_scale_configs', full_name='paddle.fleet.DistributedStrategy.gradient_scale_configs', index=61, + number=203, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5621, + serialized_end=8088, +) + + +_DISTRIBUTEDJOBINFO = _descriptor.Descriptor( + name='DistributedJobInfo', + full_name='paddle.fleet.DistributedJobInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='worker_num', full_name='paddle.fleet.DistributedJobInfo.worker_num', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_num', full_name='paddle.fleet.DistributedJobInfo.server_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='worker_ips', full_name='paddle.fleet.DistributedJobInfo.worker_ips', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_endpoints', full_name='paddle.fleet.DistributedJobInfo.server_endpoints', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='origin_startup', full_name='paddle.fleet.DistributedJobInfo.origin_startup', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='origin_main', full_name='paddle.fleet.DistributedJobInfo.origin_main', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='distributed_main', full_name='paddle.fleet.DistributedJobInfo.distributed_main', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimizer_name', full_name='paddle.fleet.DistributedJobInfo.optimizer_name', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='strategy', full_name='paddle.fleet.DistributedJobInfo.strategy', index=8, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=8091, + serialized_end=8345, +) + +_TABLEPARAMETER.fields_by_name['type'].enum_type = _TABLETYPE +_TABLEPARAMETER.fields_by_name['accessor'].message_type = _TABLEACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['ctr_accessor_param'].message_type = _CTRACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['table_accessor_save_param'].message_type = _TABLEACCESSORSAVEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embed_sgd_param'].message_type = _SGDPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embedx_sgd_param'].message_type = _SGDPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['graph_sgd_param'].message_type = _GRAPHSGDPARAMETER +_SGDPARAMETER.fields_by_name['naive'].message_type = _SPARSENAIVESGDRULEPARAMETER +_SGDPARAMETER.fields_by_name['adagrad'].message_type = _SPARSEADAGRADSGDRULEPARAMETER +_SGDPARAMETER.fields_by_name['adam'].message_type = _SPARSEADAMSGDPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['mode'].enum_type = _MODE +_DISTRIBUTEDSTRATEGY.fields_by_name['recompute_configs'].message_type = _RECOMPUTECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['amp_configs'].message_type = _AMPCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['localsgd_configs'].message_type = _LOCALSGDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['gradient_merge_configs'].message_type = _GRADIENTMERGECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['dgc_configs'].message_type = _DGCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['pipeline_configs'].message_type = _PIPELINECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['a_sync_configs'].message_type = _ASYNCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['lars_configs'].message_type = _LARSCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['lamb_configs'].message_type = _LAMBCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['adaptive_localsgd_configs'].message_type = _ADAPTIVELOCALSGDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['sharding_configs'].message_type = _SHARDINGCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['hybrid_configs'].message_type = _HYBRIDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['tensor_parallel_configs'].message_type = _TENSORPARALLELCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['trainer_desc_configs'].message_type = _TRAINERDESCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['downpour_table_param'].message_type = _TABLEPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['fs_client_param'].message_type = _FSCLIENTPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['qat_configs'].message_type = _QATCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['build_strategy'].message_type = _BUILDSTRATEGY +_DISTRIBUTEDSTRATEGY.fields_by_name['execution_strategy'].message_type = _EXECUTIONSTRATEGY +_DISTRIBUTEDSTRATEGY.fields_by_name['gradient_scale_configs'].message_type = _GRADIENTSCALECONFIG +_DISTRIBUTEDJOBINFO.fields_by_name['strategy'].message_type = _DISTRIBUTEDSTRATEGY +DESCRIPTOR.message_types_by_name['RecomputeConfig'] = _RECOMPUTECONFIG +DESCRIPTOR.message_types_by_name['ShardingConfig'] = _SHARDINGCONFIG +DESCRIPTOR.message_types_by_name['HybridConfig'] = _HYBRIDCONFIG +DESCRIPTOR.message_types_by_name['AMPConfig'] = _AMPCONFIG +DESCRIPTOR.message_types_by_name['LocalSGDConfig'] = _LOCALSGDCONFIG +DESCRIPTOR.message_types_by_name['AdaptiveLocalSGDConfig'] = _ADAPTIVELOCALSGDCONFIG +DESCRIPTOR.message_types_by_name['GradientMergeConfig'] = _GRADIENTMERGECONFIG +DESCRIPTOR.message_types_by_name['DGCConfig'] = _DGCCONFIG +DESCRIPTOR.message_types_by_name['LarsConfig'] = _LARSCONFIG +DESCRIPTOR.message_types_by_name['LambConfig'] = _LAMBCONFIG +DESCRIPTOR.message_types_by_name['BuildStrategy'] = _BUILDSTRATEGY +DESCRIPTOR.message_types_by_name['ExecutionStrategy'] = _EXECUTIONSTRATEGY +DESCRIPTOR.message_types_by_name['GradientScaleConfig'] = _GRADIENTSCALECONFIG +DESCRIPTOR.message_types_by_name['AsyncConfig'] = _ASYNCCONFIG +DESCRIPTOR.message_types_by_name['TrainerDescConfig'] = _TRAINERDESCCONFIG +DESCRIPTOR.message_types_by_name['PipelineConfig'] = _PIPELINECONFIG +DESCRIPTOR.message_types_by_name['TensorParallelConfig'] = _TENSORPARALLELCONFIG +DESCRIPTOR.message_types_by_name['QatConfig'] = _QATCONFIG +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorParameter'] = _TABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['GraphSGDParameter'] = _GRAPHSGDPARAMETER +DESCRIPTOR.message_types_by_name['SGDParameter'] = _SGDPARAMETER +DESCRIPTOR.message_types_by_name['SparseNaiveSGDRuleParameter'] = _SPARSENAIVESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdagradSGDRuleParameter'] = _SPARSEADAGRADSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdamSGDParameter'] = _SPARSEADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name['CtrAccessorParameter'] = _CTRACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorSaveParameter'] = _TABLEACCESSORSAVEPARAMETER +DESCRIPTOR.message_types_by_name['FsClientParameter'] = _FSCLIENTPARAMETER +DESCRIPTOR.message_types_by_name['DistributedStrategy'] = _DISTRIBUTEDSTRATEGY +DESCRIPTOR.message_types_by_name['DistributedJobInfo'] = _DISTRIBUTEDJOBINFO +DESCRIPTOR.enum_types_by_name['Mode'] = _MODE +DESCRIPTOR.enum_types_by_name['TableType'] = _TABLETYPE + +RecomputeConfig = _reflection.GeneratedProtocolMessageType('RecomputeConfig', (_message.Message,), dict( + DESCRIPTOR = _RECOMPUTECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.RecomputeConfig) + )) +_sym_db.RegisterMessage(RecomputeConfig) + +ShardingConfig = _reflection.GeneratedProtocolMessageType('ShardingConfig', (_message.Message,), dict( + DESCRIPTOR = _SHARDINGCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.ShardingConfig) + )) +_sym_db.RegisterMessage(ShardingConfig) + +HybridConfig = _reflection.GeneratedProtocolMessageType('HybridConfig', (_message.Message,), dict( + DESCRIPTOR = _HYBRIDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.HybridConfig) + )) +_sym_db.RegisterMessage(HybridConfig) + +AMPConfig = _reflection.GeneratedProtocolMessageType('AMPConfig', (_message.Message,), dict( + DESCRIPTOR = _AMPCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AMPConfig) + )) +_sym_db.RegisterMessage(AMPConfig) + +LocalSGDConfig = _reflection.GeneratedProtocolMessageType('LocalSGDConfig', (_message.Message,), dict( + DESCRIPTOR = _LOCALSGDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LocalSGDConfig) + )) +_sym_db.RegisterMessage(LocalSGDConfig) + +AdaptiveLocalSGDConfig = _reflection.GeneratedProtocolMessageType('AdaptiveLocalSGDConfig', (_message.Message,), dict( + DESCRIPTOR = _ADAPTIVELOCALSGDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AdaptiveLocalSGDConfig) + )) +_sym_db.RegisterMessage(AdaptiveLocalSGDConfig) + +GradientMergeConfig = _reflection.GeneratedProtocolMessageType('GradientMergeConfig', (_message.Message,), dict( + DESCRIPTOR = _GRADIENTMERGECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GradientMergeConfig) + )) +_sym_db.RegisterMessage(GradientMergeConfig) + +DGCConfig = _reflection.GeneratedProtocolMessageType('DGCConfig', (_message.Message,), dict( + DESCRIPTOR = _DGCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DGCConfig) + )) +_sym_db.RegisterMessage(DGCConfig) + +LarsConfig = _reflection.GeneratedProtocolMessageType('LarsConfig', (_message.Message,), dict( + DESCRIPTOR = _LARSCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LarsConfig) + )) +_sym_db.RegisterMessage(LarsConfig) + +LambConfig = _reflection.GeneratedProtocolMessageType('LambConfig', (_message.Message,), dict( + DESCRIPTOR = _LAMBCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LambConfig) + )) +_sym_db.RegisterMessage(LambConfig) + +BuildStrategy = _reflection.GeneratedProtocolMessageType('BuildStrategy', (_message.Message,), dict( + DESCRIPTOR = _BUILDSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.BuildStrategy) + )) +_sym_db.RegisterMessage(BuildStrategy) + +ExecutionStrategy = _reflection.GeneratedProtocolMessageType('ExecutionStrategy', (_message.Message,), dict( + DESCRIPTOR = _EXECUTIONSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.ExecutionStrategy) + )) +_sym_db.RegisterMessage(ExecutionStrategy) + +GradientScaleConfig = _reflection.GeneratedProtocolMessageType('GradientScaleConfig', (_message.Message,), dict( + DESCRIPTOR = _GRADIENTSCALECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GradientScaleConfig) + )) +_sym_db.RegisterMessage(GradientScaleConfig) + +AsyncConfig = _reflection.GeneratedProtocolMessageType('AsyncConfig', (_message.Message,), dict( + DESCRIPTOR = _ASYNCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AsyncConfig) + )) +_sym_db.RegisterMessage(AsyncConfig) + +TrainerDescConfig = _reflection.GeneratedProtocolMessageType('TrainerDescConfig', (_message.Message,), dict( + DESCRIPTOR = _TRAINERDESCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TrainerDescConfig) + )) +_sym_db.RegisterMessage(TrainerDescConfig) + +PipelineConfig = _reflection.GeneratedProtocolMessageType('PipelineConfig', (_message.Message,), dict( + DESCRIPTOR = _PIPELINECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.PipelineConfig) + )) +_sym_db.RegisterMessage(PipelineConfig) + +TensorParallelConfig = _reflection.GeneratedProtocolMessageType('TensorParallelConfig', (_message.Message,), dict( + DESCRIPTOR = _TENSORPARALLELCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TensorParallelConfig) + )) +_sym_db.RegisterMessage(TensorParallelConfig) + +QatConfig = _reflection.GeneratedProtocolMessageType('QatConfig', (_message.Message,), dict( + DESCRIPTOR = _QATCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.QatConfig) + )) +_sym_db.RegisterMessage(QatConfig) + +TableParameter = _reflection.GeneratedProtocolMessageType('TableParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + +TableAccessorParameter = _reflection.GeneratedProtocolMessageType('TableAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableAccessorParameter) + )) +_sym_db.RegisterMessage(TableAccessorParameter) + +GraphSGDParameter = _reflection.GeneratedProtocolMessageType('GraphSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _GRAPHSGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GraphSGDParameter) + )) +_sym_db.RegisterMessage(GraphSGDParameter) + +SGDParameter = _reflection.GeneratedProtocolMessageType('SGDParameter', (_message.Message,), dict( + DESCRIPTOR = _SGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SGDParameter) + )) +_sym_db.RegisterMessage(SGDParameter) + +SparseNaiveSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseNaiveSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSENAIVESGDRULEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseNaiveSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseNaiveSGDRuleParameter) + +SparseAdagradSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseAdagradSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAGRADSGDRULEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseAdagradSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseAdagradSGDRuleParameter) + +SparseAdamSGDParameter = _reflection.GeneratedProtocolMessageType('SparseAdamSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAMSGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseAdamSGDParameter) + )) +_sym_db.RegisterMessage(SparseAdamSGDParameter) + +CtrAccessorParameter = _reflection.GeneratedProtocolMessageType('CtrAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _CTRACCESSORPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.CtrAccessorParameter) + )) +_sym_db.RegisterMessage(CtrAccessorParameter) + +TableAccessorSaveParameter = _reflection.GeneratedProtocolMessageType('TableAccessorSaveParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORSAVEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableAccessorSaveParameter) + )) +_sym_db.RegisterMessage(TableAccessorSaveParameter) + +FsClientParameter = _reflection.GeneratedProtocolMessageType('FsClientParameter', (_message.Message,), dict( + DESCRIPTOR = _FSCLIENTPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.FsClientParameter) + )) +_sym_db.RegisterMessage(FsClientParameter) + +DistributedStrategy = _reflection.GeneratedProtocolMessageType('DistributedStrategy', (_message.Message,), dict( + DESCRIPTOR = _DISTRIBUTEDSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DistributedStrategy) + )) +_sym_db.RegisterMessage(DistributedStrategy) + +DistributedJobInfo = _reflection.GeneratedProtocolMessageType('DistributedJobInfo', (_message.Message,), dict( + DESCRIPTOR = _DISTRIBUTEDJOBINFO, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DistributedJobInfo) + )) +_sym_db.RegisterMessage(DistributedJobInfo) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/fleet_executor_desc_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/fleet_executor_desc_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2391126e1076d665d6255a52180f32f2b4f130c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/fleet_executor_desc_pb2.py @@ -0,0 +1,123 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: fleet_executor_desc.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='fleet_executor_desc.proto', + package='paddle.distributed', + syntax='proto2', + serialized_pb=_b('\n\x19\x66leet_executor_desc.proto\x12\x12paddle.distributed\")\n\x08RankInfo\x12\x0c\n\x04rank\x18\x01 \x02(\x03\x12\x0f\n\x07ip_port\x18\x02 \x02(\t\"\\\n\x11\x46leetExecutorDesc\x12\x13\n\x08\x63ur_rank\x18\x01 \x01(\x03:\x01\x30\x12\x32\n\x0c\x63luster_info\x18\x02 \x03(\x0b\x32\x1c.paddle.distributed.RankInfo') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_RANKINFO = _descriptor.Descriptor( + name='RankInfo', + full_name='paddle.distributed.RankInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='rank', full_name='paddle.distributed.RankInfo.rank', index=0, + number=1, type=3, cpp_type=2, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ip_port', full_name='paddle.distributed.RankInfo.ip_port', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=49, + serialized_end=90, +) + + +_FLEETEXECUTORDESC = _descriptor.Descriptor( + name='FleetExecutorDesc', + full_name='paddle.distributed.FleetExecutorDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='cur_rank', full_name='paddle.distributed.FleetExecutorDesc.cur_rank', index=0, + number=1, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cluster_info', full_name='paddle.distributed.FleetExecutorDesc.cluster_info', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=92, + serialized_end=184, +) + +_FLEETEXECUTORDESC.fields_by_name['cluster_info'].message_type = _RANKINFO +DESCRIPTOR.message_types_by_name['RankInfo'] = _RANKINFO +DESCRIPTOR.message_types_by_name['FleetExecutorDesc'] = _FLEETEXECUTORDESC + +RankInfo = _reflection.GeneratedProtocolMessageType('RankInfo', (_message.Message,), dict( + DESCRIPTOR = _RANKINFO, + __module__ = 'fleet_executor_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.RankInfo) + )) +_sym_db.RegisterMessage(RankInfo) + +FleetExecutorDesc = _reflection.GeneratedProtocolMessageType('FleetExecutorDesc', (_message.Message,), dict( + DESCRIPTOR = _FLEETEXECUTORDESC, + __module__ = 'fleet_executor_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.FleetExecutorDesc) + )) +_sym_db.RegisterMessage(FleetExecutorDesc) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/index_dataset_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/index_dataset_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..b446c5584e7145c4b14d599785c8d990cad7dd6f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/index_dataset_pb2.py @@ -0,0 +1,182 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: index_dataset.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='index_dataset.proto', + package='paddle.distributed', + syntax='proto2', + serialized_pb=_b('\n\x13index_dataset.proto\x12\x12paddle.distributed\"P\n\tIndexNode\x12\n\n\x02id\x18\x01 \x02(\x04\x12\x0f\n\x07is_leaf\x18\x02 \x02(\x08\x12\x13\n\x0bprobability\x18\x03 \x02(\x02\x12\x11\n\titem_name\x18\x04 \x01(\t\"*\n\x08TreeMeta\x12\x0e\n\x06height\x18\x01 \x02(\x05\x12\x0e\n\x06\x62ranch\x18\x02 \x02(\x05\"$\n\x06KVItem\x12\x0b\n\x03key\x18\x01 \x02(\x0c\x12\r\n\x05value\x18\x02 \x02(\x0c') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_INDEXNODE = _descriptor.Descriptor( + name='IndexNode', + full_name='paddle.distributed.IndexNode', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='id', full_name='paddle.distributed.IndexNode.id', index=0, + number=1, type=4, cpp_type=4, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_leaf', full_name='paddle.distributed.IndexNode.is_leaf', index=1, + number=2, type=8, cpp_type=7, label=2, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='probability', full_name='paddle.distributed.IndexNode.probability', index=2, + number=3, type=2, cpp_type=6, label=2, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='item_name', full_name='paddle.distributed.IndexNode.item_name', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=43, + serialized_end=123, +) + + +_TREEMETA = _descriptor.Descriptor( + name='TreeMeta', + full_name='paddle.distributed.TreeMeta', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='height', full_name='paddle.distributed.TreeMeta.height', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='branch', full_name='paddle.distributed.TreeMeta.branch', index=1, + number=2, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=125, + serialized_end=167, +) + + +_KVITEM = _descriptor.Descriptor( + name='KVItem', + full_name='paddle.distributed.KVItem', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='paddle.distributed.KVItem.key', index=0, + number=1, type=12, cpp_type=9, label=2, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='paddle.distributed.KVItem.value', index=1, + number=2, type=12, cpp_type=9, label=2, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=169, + serialized_end=205, +) + +DESCRIPTOR.message_types_by_name['IndexNode'] = _INDEXNODE +DESCRIPTOR.message_types_by_name['TreeMeta'] = _TREEMETA +DESCRIPTOR.message_types_by_name['KVItem'] = _KVITEM + +IndexNode = _reflection.GeneratedProtocolMessageType('IndexNode', (_message.Message,), dict( + DESCRIPTOR = _INDEXNODE, + __module__ = 'index_dataset_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.IndexNode) + )) +_sym_db.RegisterMessage(IndexNode) + +TreeMeta = _reflection.GeneratedProtocolMessageType('TreeMeta', (_message.Message,), dict( + DESCRIPTOR = _TREEMETA, + __module__ = 'index_dataset_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.TreeMeta) + )) +_sym_db.RegisterMessage(TreeMeta) + +KVItem = _reflection.GeneratedProtocolMessageType('KVItem', (_message.Message,), dict( + DESCRIPTOR = _KVITEM, + __module__ = 'index_dataset_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.KVItem) + )) +_sym_db.RegisterMessage(KVItem) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/the_one_ps_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/the_one_ps_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..17023bb422d59f0ad1e560d7cfd864d54eeb07cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/proto/the_one_ps_pb2.py @@ -0,0 +1,2043 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: the_one_ps.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='the_one_ps.proto', + package='paddle.distributed', + syntax='proto2', + serialized_pb=_b('\n\x10the_one_ps.proto\x12\x12paddle.distributed\"\xe1\x01\n\x11\x46sClientParameter\x12\x46\n\x07\x66s_type\x18\x01 \x01(\x0e\x32/.paddle.distributed.FsClientParameter.FsApiType:\x04HDFS\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\x0c\n\x04user\x18\x03 \x01(\t\x12\x0e\n\x06passwd\x18\x04 \x01(\t\x12\x13\n\x0b\x62uffer_size\x18\x05 \x01(\x05\x12\x12\n\nhadoop_bin\x18\x33 \x01(\t\x12\x10\n\x08\x61\x66s_conf\x18\x65 \x01(\t\"\x1e\n\tFsApiType\x12\x08\n\x04HDFS\x10\x00\x12\x07\n\x03\x41\x46S\x10\x01\"\xe5\x02\n\x0bPSParameter\x12\x14\n\x0cworker_class\x18\x01 \x01(\t\x12\x14\n\x0cserver_class\x18\x02 \x01(\t\x12\x16\n\x0einstance_class\x18\x03 \x01(\t\x12\x15\n\x0binit_gflags\x18\x04 \x01(\t:\x00\x12\x39\n\x0cworker_param\x18\x65 \x01(\x0b\x32#.paddle.distributed.WorkerParameter\x12\x39\n\x0cserver_param\x18\x66 \x01(\x0b\x32#.paddle.distributed.ServerParameter\x12\x44\n\rtrainer_param\x18\xad\x02 \x03(\x0b\x32,.paddle.distributed.DownpourTrainerParameter\x12?\n\x0f\x66s_client_param\x18\xf5\x03 \x01(\x0b\x32%.paddle.distributed.FsClientParameter\"]\n\x0fWorkerParameter\x12J\n\x15\x64ownpour_worker_param\x18\x01 \x01(\x0b\x32+.paddle.distributed.DownpourWorkerParameter\"[\n\x17\x44ownpourWorkerParameter\x12@\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\".paddle.distributed.TableParameter\"\x9e\x01\n\x17\x44ownpourServerParameter\x12@\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\".paddle.distributed.TableParameter\x12\x41\n\rservice_param\x18\x02 \x01(\x0b\x32*.paddle.distributed.ServerServiceParameter\"]\n\x0fServerParameter\x12J\n\x15\x64ownpour_server_param\x18\x01 \x01(\x0b\x32+.paddle.distributed.DownpourServerParameter\"\xa1\x02\n\x18\x44ownpourTrainerParameter\x12<\n\x0b\x64\x65nse_table\x18\x01 \x03(\x0b\x32\'.paddle.distributed.DenseTableParameter\x12>\n\x0csparse_table\x18\x02 \x03(\x0b\x32(.paddle.distributed.SparseTableParameter\x12\x1d\n\x15push_sparse_per_batch\x18\x03 \x01(\x05\x12\x1c\n\x14push_dense_per_batch\x18\x04 \x01(\x05\x12\x0f\n\x07skip_op\x18\x05 \x03(\t\x12\x39\n\x0eprogram_config\x18\x06 \x03(\x0b\x32!.paddle.distributed.ProgramConfig\"{\n\x13\x44\x65nseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x1b\n\x13\x64\x65nse_variable_name\x18\x02 \x03(\t\x12$\n\x1c\x64\x65nse_gradient_variable_name\x18\x03 \x03(\t\x12\x0f\n\x07\x66\x65\x61_dim\x18\x04 \x01(\x05\"z\n\x14SparseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x13\n\x0b\x66\x65\x61ture_dim\x18\x02 \x01(\x05\x12\x10\n\x08slot_key\x18\x03 \x03(\t\x12\x12\n\nslot_value\x18\x04 \x03(\t\x12\x15\n\rslot_gradient\x18\x05 \x03(\t\"\xc3\x01\n\x16ServerServiceParameter\x12\"\n\x0cserver_class\x18\x01 \x01(\t:\x0c\x42rpcPsServer\x12\"\n\x0c\x63lient_class\x18\x02 \x01(\t:\x0c\x42rpcPsClient\x12$\n\rservice_class\x18\x03 \x01(\t:\rBrpcPsService\x12\x1c\n\x11start_server_port\x18\x04 \x01(\r:\x01\x30\x12\x1d\n\x11server_thread_num\x18\x05 \x01(\r:\x02\x31\x32\"\x99\x01\n\rProgramConfig\x12\x12\n\nprogram_id\x18\x01 \x02(\t\x12\x1c\n\x14push_sparse_table_id\x18\x02 \x03(\x05\x12\x1b\n\x13push_dense_table_id\x18\x03 \x03(\x05\x12\x1c\n\x14pull_sparse_table_id\x18\x04 \x03(\x05\x12\x1b\n\x13pull_dense_table_id\x18\x05 \x03(\x05\"\xc9\x04\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x13\n\x0btable_class\x18\x02 \x01(\t\x12\x17\n\tshard_num\x18\x03 \x01(\x04:\x04\x31\x30\x30\x30\x12<\n\x08\x61\x63\x63\x65ssor\x18\x04 \x01(\x0b\x32*.paddle.distributed.TableAccessorParameter\x12;\n\x06tensor\x18\x05 \x01(\x0b\x32+.paddle.distributed.TensorAccessorParameter\x12;\n\x06\x63ommon\x18\x06 \x01(\x0b\x32+.paddle.distributed.CommonAccessorParameter\x12+\n\x04type\x18\x07 \x01(\x0e\x32\x1d.paddle.distributed.TableType\x12\x1e\n\x10\x63ompress_in_save\x18\x08 \x01(\x08:\x04true\x12;\n\x0fgraph_parameter\x18\t \x01(\x0b\x32\".paddle.distributed.GraphParameter\x12\'\n\x19\x65nable_sparse_table_cache\x18\n \x01(\x08:\x04true\x12(\n\x17sparse_table_cache_rate\x18\x0b \x01(\x01:\x07\x30.00055\x12\'\n\x1bsparse_table_cache_file_num\x18\x0c \x01(\r:\x02\x31\x36\x12\x1c\n\renable_revert\x18\r \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x10shard_merge_rate\x18\x0e \x01(\x02:\x01\x31\"\xea\x03\n\x16TableAccessorParameter\x12\x16\n\x0e\x61\x63\x63\x65ssor_class\x18\x01 \x01(\t\x12\x13\n\x07\x66\x65\x61_dim\x18\x04 \x01(\r:\x02\x31\x31\x12\x15\n\nembedx_dim\x18\x05 \x01(\r:\x01\x38\x12\x1c\n\x10\x65mbedx_threshold\x18\x06 \x01(\r:\x02\x31\x30\x12\x44\n\x12\x63tr_accessor_param\x18\x07 \x01(\x0b\x32(.paddle.distributed.CtrAccessorParameter\x12Q\n\x19table_accessor_save_param\x18\x08 \x03(\x0b\x32..paddle.distributed.TableAccessorSaveParameter\x12I\n\x0f\x65mbed_sgd_param\x18\n \x01(\x0b\x32\x30.paddle.distributed.SparseCommonSGDRuleParameter\x12J\n\x10\x65mbedx_sgd_param\x18\x0b \x01(\x0b\x32\x30.paddle.distributed.SparseCommonSGDRuleParameter\x12>\n\x0fgraph_sgd_param\x18\x0c \x01(\x0b\x32%.paddle.distributed.GraphSGDParameter\"S\n\x11GraphSGDParameter\x12\x19\n\x0bnodeid_slot\x18\x01 \x01(\r:\x04\x39\x30\x30\x38\x12#\n\x15\x66\x65\x61ture_learning_rate\x18\x02 \x01(\x02:\x04\x30.05\"\xe3\x02\n\x14\x43trAccessorParameter\x12\x19\n\x0cnonclk_coeff\x18\x01 \x01(\x02:\x03\x30.1\x12\x16\n\x0b\x63lick_coeff\x18\x02 \x01(\x02:\x01\x31\x12\x1b\n\x0e\x62\x61se_threshold\x18\x03 \x01(\x02:\x03\x31.5\x12\x1d\n\x0f\x64\x65lta_threshold\x18\x04 \x01(\x02:\x04\x30.25\x12\x1b\n\x0f\x64\x65lta_keep_days\x18\x05 \x01(\x02:\x02\x31\x36\x12#\n\x15show_click_decay_rate\x18\x06 \x01(\x02:\x04\x30.98\x12\x1d\n\x10\x64\x65lete_threshold\x18\x07 \x01(\x02:\x03\x30.8\x12$\n\x18\x64\x65lete_after_unseen_days\x18\x08 \x01(\x02:\x02\x33\x30\x12\"\n\x17ssd_unseenday_threshold\x18\t \x01(\x05:\x01\x31\x12\x18\n\nshow_scale\x18\n \x01(\x08:\x04true\x12\x17\n\tzero_init\x18\x0b \x01(\x08:\x04true\"\x99\x01\n\x17TensorAccessorParameter\x12\x15\n\rfeed_var_name\x18\x01 \x01(\t\x12\x16\n\x0e\x66\x65tch_var_name\x18\x02 \x01(\t\x12\x1a\n\x12startup_program_id\x18\x03 \x01(\x03\x12\x17\n\x0fmain_program_id\x18\x04 \x01(\x03\x12\x1a\n\x12tensor_table_class\x18\x06 \x01(\t\"\xe9\x01\n\x17\x43ommonAccessorParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ntable_name\x18\x02 \x01(\t\x12\x12\n\nattributes\x18\x03 \x03(\t\x12\x0e\n\x06params\x18\x04 \x03(\t\x12\x0c\n\x04\x64ims\x18\x05 \x03(\r\x12\x14\n\x0cinitializers\x18\x06 \x03(\t\x12\r\n\x05\x65ntry\x18\x07 \x01(\t\x12\x13\n\x0btrainer_num\x18\x08 \x01(\x05\x12\x0c\n\x04sync\x18\t \x01(\x08\x12\x11\n\ttable_num\x18\n \x01(\r\x12\x11\n\ttable_dim\x18\x0b \x01(\r\x12\x0c\n\x04\x61ttr\x18\x0c \x01(\t\"S\n\x1aTableAccessorSaveParameter\x12\r\n\x05param\x18\x01 \x01(\r\x12\x11\n\tconverter\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65\x63onverter\x18\x03 \x01(\t\"\xea\x01\n\x1cSparseCommonSGDRuleParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12>\n\x05naive\x18\x02 \x01(\x0b\x32/.paddle.distributed.SparseNaiveSGDRuleParameter\x12\x42\n\x07\x61\x64\x61grad\x18\x03 \x01(\x0b\x32\x31.paddle.distributed.SparseAdagradSGDRuleParameter\x12\x38\n\x04\x61\x64\x61m\x18\x04 \x01(\x0b\x32*.paddle.distributed.SparseAdamSGDParameter\"p\n\x1bSparseNaiveSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x03 \x03(\x02\"\x8c\x01\n\x1dSparseAdagradSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x18\n\rinitial_g2sum\x18\x02 \x01(\x01:\x01\x33\x12\x1d\n\rinitial_range\x18\x03 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xc8\x01\n\x16SparseAdamSGDParameter\x12\x1c\n\rlearning_rate\x18\x01 \x01(\x01:\x05\x30.001\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x1d\n\x10\x62\x65ta1_decay_rate\x18\x03 \x01(\x01:\x03\x30.9\x12\x1f\n\x10\x62\x65ta2_decay_rate\x18\x04 \x01(\x01:\x05\x30.999\x12\x1a\n\x0b\x61\x64\x61_epsilon\x18\x05 \x01(\x01:\x05\x31\x65-08\x12\x15\n\rweight_bounds\x18\x06 \x03(\x02\"\xe0\x02\n\x0eGraphParameter\x12\x1a\n\x0etask_pool_size\x18\x01 \x01(\x05:\x02\x32\x34\x12\x12\n\nedge_types\x18\x02 \x03(\t\x12\x12\n\nnode_types\x18\x03 \x03(\t\x12\x18\n\tuse_cache\x18\x04 \x01(\x08:\x05\x66\x61lse\x12 \n\x10\x63\x61\x63he_size_limit\x18\x05 \x01(\x05:\x06\x31\x30\x30\x30\x30\x30\x12\x14\n\tcache_ttl\x18\x06 \x01(\x05:\x01\x35\x12\x37\n\rgraph_feature\x18\x07 \x03(\x0b\x32 .paddle.distributed.GraphFeature\x12\x14\n\ntable_name\x18\x08 \x01(\t:\x00\x12\x14\n\ntable_type\x18\t \x01(\t:\x00\x12\x16\n\tshard_num\x18\n \x01(\x05:\x03\x31\x32\x37\x12\x17\n\x0csearch_level\x18\x0b \x01(\x05:\x01\x31\x12\"\n\x14\x62uild_sampler_on_cpu\x18\x0c \x01(\x08:\x04true\":\n\x0cGraphFeature\x12\x0c\n\x04name\x18\x01 \x03(\t\x12\r\n\x05\x64type\x18\x02 \x03(\t\x12\r\n\x05shape\x18\x03 \x03(\x05\"y\n\x0b\x46LParameter\x12\x33\n\x0b\x66l_strategy\x18\x01 \x01(\x0b\x32\x1e.paddle.distributed.FLStrategy\x12\x35\n\x0b\x63lient_info\x18\x02 \x01(\x0b\x32 .paddle.distributed.FLClientInfo\"g\n\nFLStrategy\x12\x15\n\riteration_num\x18\x01 \x01(\x04\x12\x11\n\tclient_id\x18\x02 \x01(\x04\x12\x18\n\nnext_state\x18\x03 \x01(\t:\x04JOIN\x12\x15\n\x0binit_gflags\x18\x04 \x01(\t:\x00\"\xc2\x01\n\x0c\x46LClientInfo\x12\x11\n\tclient_id\x18\x01 \x01(\r\x12\x13\n\x0b\x64\x65vice_type\x18\x02 \x01(\t\x12\x18\n\x10\x63ompute_capacity\x18\x03 \x01(\x05\x12\x11\n\tbandwidth\x18\x04 \x01(\x05\x12\x46\n\x15local_training_result\x18\x05 \x01(\x0b\x32\'.paddle.distributed.LocalTrainingResult\x12\x15\n\x0binit_gflags\x18\x06 \x01(\t:\x00\"0\n\x13LocalTrainingResult\x12\x0b\n\x03\x61\x63\x63\x18\x01 \x01(\x01\x12\x0c\n\x04loss\x18\x02 \x01(\x01*H\n\tTableType\x12\x13\n\x0fPS_SPARSE_TABLE\x10\x00\x12\x12\n\x0ePS_DENSE_TABLE\x10\x01\x12\x12\n\x0ePS_OTHER_TABLE\x10\x02\x42\x06\x80\x01\x01\xf8\x01\x01') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_TABLETYPE = _descriptor.EnumDescriptor( + name='TableType', + full_name='paddle.distributed.TableType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='PS_SPARSE_TABLE', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_DENSE_TABLE', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_OTHER_TABLE', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=5555, + serialized_end=5627, +) +_sym_db.RegisterEnumDescriptor(_TABLETYPE) + +TableType = enum_type_wrapper.EnumTypeWrapper(_TABLETYPE) +PS_SPARSE_TABLE = 0 +PS_DENSE_TABLE = 1 +PS_OTHER_TABLE = 2 + + +_FSCLIENTPARAMETER_FSAPITYPE = _descriptor.EnumDescriptor( + name='FsApiType', + full_name='paddle.distributed.FsClientParameter.FsApiType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='HDFS', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='AFS', index=1, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=236, + serialized_end=266, +) +_sym_db.RegisterEnumDescriptor(_FSCLIENTPARAMETER_FSAPITYPE) + + +_FSCLIENTPARAMETER = _descriptor.Descriptor( + name='FsClientParameter', + full_name='paddle.distributed.FsClientParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fs_type', full_name='paddle.distributed.FsClientParameter.fs_type', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uri', full_name='paddle.distributed.FsClientParameter.uri', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='user', full_name='paddle.distributed.FsClientParameter.user', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='passwd', full_name='paddle.distributed.FsClientParameter.passwd', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='buffer_size', full_name='paddle.distributed.FsClientParameter.buffer_size', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hadoop_bin', full_name='paddle.distributed.FsClientParameter.hadoop_bin', index=5, + number=51, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='afs_conf', full_name='paddle.distributed.FsClientParameter.afs_conf', index=6, + number=101, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FSCLIENTPARAMETER_FSAPITYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=41, + serialized_end=266, +) + + +_PSPARAMETER = _descriptor.Descriptor( + name='PSParameter', + full_name='paddle.distributed.PSParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='worker_class', full_name='paddle.distributed.PSParameter.worker_class', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_class', full_name='paddle.distributed.PSParameter.server_class', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='instance_class', full_name='paddle.distributed.PSParameter.instance_class', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='init_gflags', full_name='paddle.distributed.PSParameter.init_gflags', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='worker_param', full_name='paddle.distributed.PSParameter.worker_param', index=4, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_param', full_name='paddle.distributed.PSParameter.server_param', index=5, + number=102, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_param', full_name='paddle.distributed.PSParameter.trainer_param', index=6, + number=301, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fs_client_param', full_name='paddle.distributed.PSParameter.fs_client_param', index=7, + number=501, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=269, + serialized_end=626, +) + + +_WORKERPARAMETER = _descriptor.Descriptor( + name='WorkerParameter', + full_name='paddle.distributed.WorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_worker_param', full_name='paddle.distributed.WorkerParameter.downpour_worker_param', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=628, + serialized_end=721, +) + + +_DOWNPOURWORKERPARAMETER = _descriptor.Descriptor( + name='DownpourWorkerParameter', + full_name='paddle.distributed.DownpourWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', full_name='paddle.distributed.DownpourWorkerParameter.downpour_table_param', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=723, + serialized_end=814, +) + + +_DOWNPOURSERVERPARAMETER = _descriptor.Descriptor( + name='DownpourServerParameter', + full_name='paddle.distributed.DownpourServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', full_name='paddle.distributed.DownpourServerParameter.downpour_table_param', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_param', full_name='paddle.distributed.DownpourServerParameter.service_param', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=817, + serialized_end=975, +) + + +_SERVERPARAMETER = _descriptor.Descriptor( + name='ServerParameter', + full_name='paddle.distributed.ServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_server_param', full_name='paddle.distributed.ServerParameter.downpour_server_param', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=977, + serialized_end=1070, +) + + +_DOWNPOURTRAINERPARAMETER = _descriptor.Descriptor( + name='DownpourTrainerParameter', + full_name='paddle.distributed.DownpourTrainerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dense_table', full_name='paddle.distributed.DownpourTrainerParameter.dense_table', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table', full_name='paddle.distributed.DownpourTrainerParameter.sparse_table', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_per_batch', full_name='paddle.distributed.DownpourTrainerParameter.push_sparse_per_batch', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_per_batch', full_name='paddle.distributed.DownpourTrainerParameter.push_dense_per_batch', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='skip_op', full_name='paddle.distributed.DownpourTrainerParameter.skip_op', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='program_config', full_name='paddle.distributed.DownpourTrainerParameter.program_config', index=5, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1073, + serialized_end=1362, +) + + +_DENSETABLEPARAMETER = _descriptor.Descriptor( + name='DenseTableParameter', + full_name='paddle.distributed.DenseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.distributed.DenseTableParameter.table_id', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_variable_name', full_name='paddle.distributed.DenseTableParameter.dense_variable_name', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_gradient_variable_name', full_name='paddle.distributed.DenseTableParameter.dense_gradient_variable_name', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', full_name='paddle.distributed.DenseTableParameter.fea_dim', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1364, + serialized_end=1487, +) + + +_SPARSETABLEPARAMETER = _descriptor.Descriptor( + name='SparseTableParameter', + full_name='paddle.distributed.SparseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.distributed.SparseTableParameter.table_id', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_dim', full_name='paddle.distributed.SparseTableParameter.feature_dim', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_key', full_name='paddle.distributed.SparseTableParameter.slot_key', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_value', full_name='paddle.distributed.SparseTableParameter.slot_value', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_gradient', full_name='paddle.distributed.SparseTableParameter.slot_gradient', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1489, + serialized_end=1611, +) + + +_SERVERSERVICEPARAMETER = _descriptor.Descriptor( + name='ServerServiceParameter', + full_name='paddle.distributed.ServerServiceParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='server_class', full_name='paddle.distributed.ServerServiceParameter.server_class', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("BrpcPsServer").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_class', full_name='paddle.distributed.ServerServiceParameter.client_class', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("BrpcPsClient").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_class', full_name='paddle.distributed.ServerServiceParameter.service_class', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("BrpcPsService").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_server_port', full_name='paddle.distributed.ServerServiceParameter.start_server_port', index=3, + number=4, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_thread_num', full_name='paddle.distributed.ServerServiceParameter.server_thread_num', index=4, + number=5, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=12, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1614, + serialized_end=1809, +) + + +_PROGRAMCONFIG = _descriptor.Descriptor( + name='ProgramConfig', + full_name='paddle.distributed.ProgramConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='program_id', full_name='paddle.distributed.ProgramConfig.program_id', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_table_id', full_name='paddle.distributed.ProgramConfig.push_sparse_table_id', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_table_id', full_name='paddle.distributed.ProgramConfig.push_dense_table_id', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_sparse_table_id', full_name='paddle.distributed.ProgramConfig.pull_sparse_table_id', index=3, + number=4, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_dense_table_id', full_name='paddle.distributed.ProgramConfig.pull_dense_table_id', index=4, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1812, + serialized_end=1965, +) + + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.distributed.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.distributed.TableParameter.table_id', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_class', full_name='paddle.distributed.TableParameter.table_class', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_num', full_name='paddle.distributed.TableParameter.shard_num', index=2, + number=3, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=1000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='accessor', full_name='paddle.distributed.TableParameter.accessor', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor', full_name='paddle.distributed.TableParameter.tensor', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='common', full_name='paddle.distributed.TableParameter.common', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.distributed.TableParameter.type', index=6, + number=7, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compress_in_save', full_name='paddle.distributed.TableParameter.compress_in_save', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_parameter', full_name='paddle.distributed.TableParameter.graph_parameter', index=8, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_sparse_table_cache', full_name='paddle.distributed.TableParameter.enable_sparse_table_cache', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_rate', full_name='paddle.distributed.TableParameter.sparse_table_cache_rate', index=10, + number=11, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.00055), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_file_num', full_name='paddle.distributed.TableParameter.sparse_table_cache_file_num', index=11, + number=12, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_revert', full_name='paddle.distributed.TableParameter.enable_revert', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_merge_rate', full_name='paddle.distributed.TableParameter.shard_merge_rate', index=13, + number=14, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1968, + serialized_end=2553, +) + + +_TABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='TableAccessorParameter', + full_name='paddle.distributed.TableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='accessor_class', full_name='paddle.distributed.TableAccessorParameter.accessor_class', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', full_name='paddle.distributed.TableAccessorParameter.fea_dim', index=1, + number=4, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=11, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_dim', full_name='paddle.distributed.TableAccessorParameter.embedx_dim', index=2, + number=5, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_threshold', full_name='paddle.distributed.TableAccessorParameter.embedx_threshold', index=3, + number=6, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ctr_accessor_param', full_name='paddle.distributed.TableAccessorParameter.ctr_accessor_param', index=4, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_accessor_save_param', full_name='paddle.distributed.TableAccessorParameter.table_accessor_save_param', index=5, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embed_sgd_param', full_name='paddle.distributed.TableAccessorParameter.embed_sgd_param', index=6, + number=10, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_sgd_param', full_name='paddle.distributed.TableAccessorParameter.embedx_sgd_param', index=7, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_sgd_param', full_name='paddle.distributed.TableAccessorParameter.graph_sgd_param', index=8, + number=12, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2556, + serialized_end=3046, +) + + +_GRAPHSGDPARAMETER = _descriptor.Descriptor( + name='GraphSGDParameter', + full_name='paddle.distributed.GraphSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nodeid_slot', full_name='paddle.distributed.GraphSGDParameter.nodeid_slot', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=9008, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_learning_rate', full_name='paddle.distributed.GraphSGDParameter.feature_learning_rate', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3048, + serialized_end=3131, +) + + +_CTRACCESSORPARAMETER = _descriptor.Descriptor( + name='CtrAccessorParameter', + full_name='paddle.distributed.CtrAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nonclk_coeff', full_name='paddle.distributed.CtrAccessorParameter.nonclk_coeff', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='click_coeff', full_name='paddle.distributed.CtrAccessorParameter.click_coeff', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='base_threshold', full_name='paddle.distributed.CtrAccessorParameter.base_threshold', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1.5), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_threshold', full_name='paddle.distributed.CtrAccessorParameter.delta_threshold', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.25), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_keep_days', full_name='paddle.distributed.CtrAccessorParameter.delta_keep_days', index=4, + number=5, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(16), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_click_decay_rate', full_name='paddle.distributed.CtrAccessorParameter.show_click_decay_rate', index=5, + number=6, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.98), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_threshold', full_name='paddle.distributed.CtrAccessorParameter.delete_threshold', index=6, + number=7, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.8), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_after_unseen_days', full_name='paddle.distributed.CtrAccessorParameter.delete_after_unseen_days', index=7, + number=8, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(30), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ssd_unseenday_threshold', full_name='paddle.distributed.CtrAccessorParameter.ssd_unseenday_threshold', index=8, + number=9, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_scale', full_name='paddle.distributed.CtrAccessorParameter.show_scale', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='zero_init', full_name='paddle.distributed.CtrAccessorParameter.zero_init', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3134, + serialized_end=3489, +) + + +_TENSORACCESSORPARAMETER = _descriptor.Descriptor( + name='TensorAccessorParameter', + full_name='paddle.distributed.TensorAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='feed_var_name', full_name='paddle.distributed.TensorAccessorParameter.feed_var_name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fetch_var_name', full_name='paddle.distributed.TensorAccessorParameter.fetch_var_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='startup_program_id', full_name='paddle.distributed.TensorAccessorParameter.startup_program_id', index=2, + number=3, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='main_program_id', full_name='paddle.distributed.TensorAccessorParameter.main_program_id', index=3, + number=4, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_table_class', full_name='paddle.distributed.TensorAccessorParameter.tensor_table_class', index=4, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3492, + serialized_end=3645, +) + + +_COMMONACCESSORPARAMETER = _descriptor.Descriptor( + name='CommonAccessorParameter', + full_name='paddle.distributed.CommonAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.distributed.CommonAccessorParameter.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_name', full_name='paddle.distributed.CommonAccessorParameter.table_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attributes', full_name='paddle.distributed.CommonAccessorParameter.attributes', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='params', full_name='paddle.distributed.CommonAccessorParameter.params', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dims', full_name='paddle.distributed.CommonAccessorParameter.dims', index=4, + number=5, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initializers', full_name='paddle.distributed.CommonAccessorParameter.initializers', index=5, + number=6, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='entry', full_name='paddle.distributed.CommonAccessorParameter.entry', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_num', full_name='paddle.distributed.CommonAccessorParameter.trainer_num', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync', full_name='paddle.distributed.CommonAccessorParameter.sync', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_num', full_name='paddle.distributed.CommonAccessorParameter.table_num', index=9, + number=10, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_dim', full_name='paddle.distributed.CommonAccessorParameter.table_dim', index=10, + number=11, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attr', full_name='paddle.distributed.CommonAccessorParameter.attr', index=11, + number=12, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3648, + serialized_end=3881, +) + + +_TABLEACCESSORSAVEPARAMETER = _descriptor.Descriptor( + name='TableAccessorSaveParameter', + full_name='paddle.distributed.TableAccessorSaveParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='param', full_name='paddle.distributed.TableAccessorSaveParameter.param', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='converter', full_name='paddle.distributed.TableAccessorSaveParameter.converter', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deconverter', full_name='paddle.distributed.TableAccessorSaveParameter.deconverter', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3883, + serialized_end=3966, +) + + +_SPARSECOMMONSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseCommonSGDRuleParameter', + full_name='paddle.distributed.SparseCommonSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.distributed.SparseCommonSGDRuleParameter.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', full_name='paddle.distributed.SparseCommonSGDRuleParameter.naive', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adagrad', full_name='paddle.distributed.SparseCommonSGDRuleParameter.adagrad', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', full_name='paddle.distributed.SparseCommonSGDRuleParameter.adam', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3969, + serialized_end=4203, +) + + +_SPARSENAIVESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseNaiveSGDRuleParameter', + full_name='paddle.distributed.SparseNaiveSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.distributed.SparseNaiveSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.distributed.SparseNaiveSGDRuleParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.distributed.SparseNaiveSGDRuleParameter.weight_bounds', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4205, + serialized_end=4317, +) + + +_SPARSEADAGRADSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseAdagradSGDRuleParameter', + full_name='paddle.distributed.SparseAdagradSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.distributed.SparseAdagradSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', full_name='paddle.distributed.SparseAdagradSGDRuleParameter.initial_g2sum', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(3), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.distributed.SparseAdagradSGDRuleParameter.initial_range', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.distributed.SparseAdagradSGDRuleParameter.weight_bounds', index=3, + number=4, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4320, + serialized_end=4460, +) + + +_SPARSEADAMSGDPARAMETER = _descriptor.Descriptor( + name='SparseAdamSGDParameter', + full_name='paddle.distributed.SparseAdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.distributed.SparseAdamSGDParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.distributed.SparseAdamSGDParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta1_decay_rate', full_name='paddle.distributed.SparseAdamSGDParameter.beta1_decay_rate', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.9), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta2_decay_rate', full_name='paddle.distributed.SparseAdamSGDParameter.beta2_decay_rate', index=3, + number=4, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.999), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', full_name='paddle.distributed.SparseAdamSGDParameter.ada_epsilon', index=4, + number=5, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(1e-08), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.distributed.SparseAdamSGDParameter.weight_bounds', index=5, + number=6, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4463, + serialized_end=4663, +) + + +_GRAPHPARAMETER = _descriptor.Descriptor( + name='GraphParameter', + full_name='paddle.distributed.GraphParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='task_pool_size', full_name='paddle.distributed.GraphParameter.task_pool_size', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=24, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='edge_types', full_name='paddle.distributed.GraphParameter.edge_types', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='node_types', full_name='paddle.distributed.GraphParameter.node_types', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_cache', full_name='paddle.distributed.GraphParameter.use_cache', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cache_size_limit', full_name='paddle.distributed.GraphParameter.cache_size_limit', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=100000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cache_ttl', full_name='paddle.distributed.GraphParameter.cache_ttl', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_feature', full_name='paddle.distributed.GraphParameter.graph_feature', index=6, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_name', full_name='paddle.distributed.GraphParameter.table_name', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_type', full_name='paddle.distributed.GraphParameter.table_type', index=8, + number=9, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_num', full_name='paddle.distributed.GraphParameter.shard_num', index=9, + number=10, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=127, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='search_level', full_name='paddle.distributed.GraphParameter.search_level', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='build_sampler_on_cpu', full_name='paddle.distributed.GraphParameter.build_sampler_on_cpu', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4666, + serialized_end=5018, +) + + +_GRAPHFEATURE = _descriptor.Descriptor( + name='GraphFeature', + full_name='paddle.distributed.GraphFeature', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.distributed.GraphFeature.name', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dtype', full_name='paddle.distributed.GraphFeature.dtype', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shape', full_name='paddle.distributed.GraphFeature.shape', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5020, + serialized_end=5078, +) + + +_FLPARAMETER = _descriptor.Descriptor( + name='FLParameter', + full_name='paddle.distributed.FLParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fl_strategy', full_name='paddle.distributed.FLParameter.fl_strategy', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_info', full_name='paddle.distributed.FLParameter.client_info', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5080, + serialized_end=5201, +) + + +_FLSTRATEGY = _descriptor.Descriptor( + name='FLStrategy', + full_name='paddle.distributed.FLStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='iteration_num', full_name='paddle.distributed.FLStrategy.iteration_num', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_id', full_name='paddle.distributed.FLStrategy.client_id', index=1, + number=2, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='next_state', full_name='paddle.distributed.FLStrategy.next_state', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("JOIN").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='init_gflags', full_name='paddle.distributed.FLStrategy.init_gflags', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5203, + serialized_end=5306, +) + + +_FLCLIENTINFO = _descriptor.Descriptor( + name='FLClientInfo', + full_name='paddle.distributed.FLClientInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='client_id', full_name='paddle.distributed.FLClientInfo.client_id', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_type', full_name='paddle.distributed.FLClientInfo.device_type', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compute_capacity', full_name='paddle.distributed.FLClientInfo.compute_capacity', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bandwidth', full_name='paddle.distributed.FLClientInfo.bandwidth', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='local_training_result', full_name='paddle.distributed.FLClientInfo.local_training_result', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='init_gflags', full_name='paddle.distributed.FLClientInfo.init_gflags', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5309, + serialized_end=5503, +) + + +_LOCALTRAININGRESULT = _descriptor.Descriptor( + name='LocalTrainingResult', + full_name='paddle.distributed.LocalTrainingResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='acc', full_name='paddle.distributed.LocalTrainingResult.acc', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='loss', full_name='paddle.distributed.LocalTrainingResult.loss', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5505, + serialized_end=5553, +) + +_FSCLIENTPARAMETER.fields_by_name['fs_type'].enum_type = _FSCLIENTPARAMETER_FSAPITYPE +_FSCLIENTPARAMETER_FSAPITYPE.containing_type = _FSCLIENTPARAMETER +_PSPARAMETER.fields_by_name['worker_param'].message_type = _WORKERPARAMETER +_PSPARAMETER.fields_by_name['server_param'].message_type = _SERVERPARAMETER +_PSPARAMETER.fields_by_name['trainer_param'].message_type = _DOWNPOURTRAINERPARAMETER +_PSPARAMETER.fields_by_name['fs_client_param'].message_type = _FSCLIENTPARAMETER +_WORKERPARAMETER.fields_by_name['downpour_worker_param'].message_type = _DOWNPOURWORKERPARAMETER +_DOWNPOURWORKERPARAMETER.fields_by_name['downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURSERVERPARAMETER.fields_by_name['downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURSERVERPARAMETER.fields_by_name['service_param'].message_type = _SERVERSERVICEPARAMETER +_SERVERPARAMETER.fields_by_name['downpour_server_param'].message_type = _DOWNPOURSERVERPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name['dense_table'].message_type = _DENSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name['sparse_table'].message_type = _SPARSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name['program_config'].message_type = _PROGRAMCONFIG +_TABLEPARAMETER.fields_by_name['accessor'].message_type = _TABLEACCESSORPARAMETER +_TABLEPARAMETER.fields_by_name['tensor'].message_type = _TENSORACCESSORPARAMETER +_TABLEPARAMETER.fields_by_name['common'].message_type = _COMMONACCESSORPARAMETER +_TABLEPARAMETER.fields_by_name['type'].enum_type = _TABLETYPE +_TABLEPARAMETER.fields_by_name['graph_parameter'].message_type = _GRAPHPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['ctr_accessor_param'].message_type = _CTRACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['table_accessor_save_param'].message_type = _TABLEACCESSORSAVEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embed_sgd_param'].message_type = _SPARSECOMMONSGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embedx_sgd_param'].message_type = _SPARSECOMMONSGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['graph_sgd_param'].message_type = _GRAPHSGDPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name['naive'].message_type = _SPARSENAIVESGDRULEPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name['adagrad'].message_type = _SPARSEADAGRADSGDRULEPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name['adam'].message_type = _SPARSEADAMSGDPARAMETER +_GRAPHPARAMETER.fields_by_name['graph_feature'].message_type = _GRAPHFEATURE +_FLPARAMETER.fields_by_name['fl_strategy'].message_type = _FLSTRATEGY +_FLPARAMETER.fields_by_name['client_info'].message_type = _FLCLIENTINFO +_FLCLIENTINFO.fields_by_name['local_training_result'].message_type = _LOCALTRAININGRESULT +DESCRIPTOR.message_types_by_name['FsClientParameter'] = _FSCLIENTPARAMETER +DESCRIPTOR.message_types_by_name['PSParameter'] = _PSPARAMETER +DESCRIPTOR.message_types_by_name['WorkerParameter'] = _WORKERPARAMETER +DESCRIPTOR.message_types_by_name['DownpourWorkerParameter'] = _DOWNPOURWORKERPARAMETER +DESCRIPTOR.message_types_by_name['DownpourServerParameter'] = _DOWNPOURSERVERPARAMETER +DESCRIPTOR.message_types_by_name['ServerParameter'] = _SERVERPARAMETER +DESCRIPTOR.message_types_by_name['DownpourTrainerParameter'] = _DOWNPOURTRAINERPARAMETER +DESCRIPTOR.message_types_by_name['DenseTableParameter'] = _DENSETABLEPARAMETER +DESCRIPTOR.message_types_by_name['SparseTableParameter'] = _SPARSETABLEPARAMETER +DESCRIPTOR.message_types_by_name['ServerServiceParameter'] = _SERVERSERVICEPARAMETER +DESCRIPTOR.message_types_by_name['ProgramConfig'] = _PROGRAMCONFIG +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorParameter'] = _TABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['GraphSGDParameter'] = _GRAPHSGDPARAMETER +DESCRIPTOR.message_types_by_name['CtrAccessorParameter'] = _CTRACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['TensorAccessorParameter'] = _TENSORACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['CommonAccessorParameter'] = _COMMONACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorSaveParameter'] = _TABLEACCESSORSAVEPARAMETER +DESCRIPTOR.message_types_by_name['SparseCommonSGDRuleParameter'] = _SPARSECOMMONSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseNaiveSGDRuleParameter'] = _SPARSENAIVESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdagradSGDRuleParameter'] = _SPARSEADAGRADSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdamSGDParameter'] = _SPARSEADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name['GraphParameter'] = _GRAPHPARAMETER +DESCRIPTOR.message_types_by_name['GraphFeature'] = _GRAPHFEATURE +DESCRIPTOR.message_types_by_name['FLParameter'] = _FLPARAMETER +DESCRIPTOR.message_types_by_name['FLStrategy'] = _FLSTRATEGY +DESCRIPTOR.message_types_by_name['FLClientInfo'] = _FLCLIENTINFO +DESCRIPTOR.message_types_by_name['LocalTrainingResult'] = _LOCALTRAININGRESULT +DESCRIPTOR.enum_types_by_name['TableType'] = _TABLETYPE + +FsClientParameter = _reflection.GeneratedProtocolMessageType('FsClientParameter', (_message.Message,), dict( + DESCRIPTOR = _FSCLIENTPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.FsClientParameter) + )) +_sym_db.RegisterMessage(FsClientParameter) + +PSParameter = _reflection.GeneratedProtocolMessageType('PSParameter', (_message.Message,), dict( + DESCRIPTOR = _PSPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.PSParameter) + )) +_sym_db.RegisterMessage(PSParameter) + +WorkerParameter = _reflection.GeneratedProtocolMessageType('WorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _WORKERPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.WorkerParameter) + )) +_sym_db.RegisterMessage(WorkerParameter) + +DownpourWorkerParameter = _reflection.GeneratedProtocolMessageType('DownpourWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _DOWNPOURWORKERPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.DownpourWorkerParameter) + )) +_sym_db.RegisterMessage(DownpourWorkerParameter) + +DownpourServerParameter = _reflection.GeneratedProtocolMessageType('DownpourServerParameter', (_message.Message,), dict( + DESCRIPTOR = _DOWNPOURSERVERPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.DownpourServerParameter) + )) +_sym_db.RegisterMessage(DownpourServerParameter) + +ServerParameter = _reflection.GeneratedProtocolMessageType('ServerParameter', (_message.Message,), dict( + DESCRIPTOR = _SERVERPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.ServerParameter) + )) +_sym_db.RegisterMessage(ServerParameter) + +DownpourTrainerParameter = _reflection.GeneratedProtocolMessageType('DownpourTrainerParameter', (_message.Message,), dict( + DESCRIPTOR = _DOWNPOURTRAINERPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.DownpourTrainerParameter) + )) +_sym_db.RegisterMessage(DownpourTrainerParameter) + +DenseTableParameter = _reflection.GeneratedProtocolMessageType('DenseTableParameter', (_message.Message,), dict( + DESCRIPTOR = _DENSETABLEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.DenseTableParameter) + )) +_sym_db.RegisterMessage(DenseTableParameter) + +SparseTableParameter = _reflection.GeneratedProtocolMessageType('SparseTableParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSETABLEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.SparseTableParameter) + )) +_sym_db.RegisterMessage(SparseTableParameter) + +ServerServiceParameter = _reflection.GeneratedProtocolMessageType('ServerServiceParameter', (_message.Message,), dict( + DESCRIPTOR = _SERVERSERVICEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.ServerServiceParameter) + )) +_sym_db.RegisterMessage(ServerServiceParameter) + +ProgramConfig = _reflection.GeneratedProtocolMessageType('ProgramConfig', (_message.Message,), dict( + DESCRIPTOR = _PROGRAMCONFIG, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.ProgramConfig) + )) +_sym_db.RegisterMessage(ProgramConfig) + +TableParameter = _reflection.GeneratedProtocolMessageType('TableParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + +TableAccessorParameter = _reflection.GeneratedProtocolMessageType('TableAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.TableAccessorParameter) + )) +_sym_db.RegisterMessage(TableAccessorParameter) + +GraphSGDParameter = _reflection.GeneratedProtocolMessageType('GraphSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _GRAPHSGDPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.GraphSGDParameter) + )) +_sym_db.RegisterMessage(GraphSGDParameter) + +CtrAccessorParameter = _reflection.GeneratedProtocolMessageType('CtrAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _CTRACCESSORPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.CtrAccessorParameter) + )) +_sym_db.RegisterMessage(CtrAccessorParameter) + +TensorAccessorParameter = _reflection.GeneratedProtocolMessageType('TensorAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _TENSORACCESSORPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.TensorAccessorParameter) + )) +_sym_db.RegisterMessage(TensorAccessorParameter) + +CommonAccessorParameter = _reflection.GeneratedProtocolMessageType('CommonAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _COMMONACCESSORPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.CommonAccessorParameter) + )) +_sym_db.RegisterMessage(CommonAccessorParameter) + +TableAccessorSaveParameter = _reflection.GeneratedProtocolMessageType('TableAccessorSaveParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORSAVEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.TableAccessorSaveParameter) + )) +_sym_db.RegisterMessage(TableAccessorSaveParameter) + +SparseCommonSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseCommonSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSECOMMONSGDRULEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.SparseCommonSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseCommonSGDRuleParameter) + +SparseNaiveSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseNaiveSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSENAIVESGDRULEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.SparseNaiveSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseNaiveSGDRuleParameter) + +SparseAdagradSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseAdagradSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAGRADSGDRULEPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.SparseAdagradSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseAdagradSGDRuleParameter) + +SparseAdamSGDParameter = _reflection.GeneratedProtocolMessageType('SparseAdamSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAMSGDPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.SparseAdamSGDParameter) + )) +_sym_db.RegisterMessage(SparseAdamSGDParameter) + +GraphParameter = _reflection.GeneratedProtocolMessageType('GraphParameter', (_message.Message,), dict( + DESCRIPTOR = _GRAPHPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.GraphParameter) + )) +_sym_db.RegisterMessage(GraphParameter) + +GraphFeature = _reflection.GeneratedProtocolMessageType('GraphFeature', (_message.Message,), dict( + DESCRIPTOR = _GRAPHFEATURE, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.GraphFeature) + )) +_sym_db.RegisterMessage(GraphFeature) + +FLParameter = _reflection.GeneratedProtocolMessageType('FLParameter', (_message.Message,), dict( + DESCRIPTOR = _FLPARAMETER, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.FLParameter) + )) +_sym_db.RegisterMessage(FLParameter) + +FLStrategy = _reflection.GeneratedProtocolMessageType('FLStrategy', (_message.Message,), dict( + DESCRIPTOR = _FLSTRATEGY, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.FLStrategy) + )) +_sym_db.RegisterMessage(FLStrategy) + +FLClientInfo = _reflection.GeneratedProtocolMessageType('FLClientInfo', (_message.Message,), dict( + DESCRIPTOR = _FLCLIENTINFO, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.FLClientInfo) + )) +_sym_db.RegisterMessage(FLClientInfo) + +LocalTrainingResult = _reflection.GeneratedProtocolMessageType('LocalTrainingResult', (_message.Message,), dict( + DESCRIPTOR = _LOCALTRAININGRESULT, + __module__ = 'the_one_ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.distributed.LocalTrainingResult) + )) +_sym_db.RegisterMessage(LocalTrainingResult) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\200\001\001\370\001\001')) +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5bcdb1db277661551bdde6e2c1a37e8d2bf906 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2022 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. + +from .recompute import recompute, recompute_sequential +from .recompute_hybrid import recompute_hybrid + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d2db328d179634c9e71b19b1e378ac2e578c3a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute.py @@ -0,0 +1,555 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.fluid import core +from paddle.autograd import PyLayer +from paddle.autograd.py_layer import LegacyPyLayer + +from paddle.fluid import framework +import contextlib +from paddle.fluid.framework import in_dygraph_mode + +import logging +from ..utils.log_util import logger + +__all__ = [] + + +def detach_variable(inputs): + out = [] + for inp in inputs: + if not isinstance(inp, (core.eager.Tensor, core.VarBase)): + out.append(inp) + continue + + x = inp.detach() + x.stop_gradient = inp.stop_gradient + out.append(x) + return tuple(out) + + +def check_recompute_necessary(inputs): + if not any( + input_.stop_gradient == False + for input_ in inputs + if isinstance(input_, (core.eager.Tensor, paddle.Tensor)) + ): + logger.warning( + "[Recompute]: None of the inputs to current recompute block need grad, " + "therefore there is NO need to recompute this block in backward !" + ) + + +@contextlib.contextmanager +def swith_rng_state_tracker(rng_state, tracker): + from paddle.distributed.fleet.meta_parallel.parallel_layers.random import ( + get_rng_state_tracker, + ) + + orig_cuda_rng_state = paddle.get_cuda_rng_state() + orig_cuda_rng_tracker = get_rng_state_tracker().get_states_tracker() + + paddle.set_cuda_rng_state(rng_state) + get_rng_state_tracker().set_states_tracker(tracker) + try: + yield + finally: + paddle.set_cuda_rng_state(orig_cuda_rng_state) + get_rng_state_tracker().set_states_tracker(orig_cuda_rng_tracker) + + +class LegacyRecomputeFunction(LegacyPyLayer): + @staticmethod + def forward(ctx, run_function, preserve_rng_state, *args): + from paddle.distributed.fleet.meta_parallel.parallel_layers.random import ( + get_rng_state_tracker, + ) + + # store for recomputing + ctx.run_function = run_function + ctx.preserve_rng_state = preserve_rng_state + + # NOTE the number of outputs of backward() should be equal to the number of tensors in forward()'s input + # the order of tensors in backward()'s output should be the same as tensors in forward()'s input + # None tensor inputs will be filtered in backward inputs. + + # save input for backward + ctx.inputs = [] + ctx.tensor_indices = [] + tensor_inputs = [] + for i, arg in enumerate(args): + if paddle.is_tensor(arg): + tensor_inputs.append(arg) + ctx.tensor_indices.append(i) + ctx.inputs.append(None) + else: + ctx.inputs.append(arg) + ctx.save_for_backward(*tensor_inputs) + + # NOTE recompute with restore RNG only support one senario where one process for one cuda gpu. + # one process with multiple gpu and mix-gpu-cpu senarios are not support + if ctx.preserve_rng_state: + cur_device = paddle.get_device() + if 'gpu:' not in cur_device: + raise RuntimeError( + "Recompute with RNG perserve is not support current device: {}.".format( + cur_device + ) + ) + ctx.fw_cuda_rng_state = paddle.get_cuda_rng_state() + ctx.fwd_cuda_rng_state_tracker = ( + get_rng_state_tracker().get_states_tracker() + ) + + # TODO support AMP + tracer = framework._dygraph_tracer() + ctx.is_fw_autocast = ( + False if tracer._amp_level == core.AmpLevel.O0 else True + ) + if tracer._amp_level == core.AmpLevel.O2: + ctx.amp_level = 'O2' + elif tracer._amp_level in (core.AmpLevel.O1, core.AmpLevel.O0): + ctx.amp_level = 'O1' + else: + raise ValueError( + "unsupported amp level: {}".format(tracer._amp_level) + ) + + if tracer._amp_dtype == 'float16': + ctx.amp_dtype = 'float16' + elif tracer._amp_dtype in ('bfloat16', 'float32'): + ctx.amp_dtype = 'bfloat16' + else: + raise ValueError( + "unsupported amp dtype: {}".format(tracer._amp_dtype) + ) + + ctx.amp_white_list, ctx.amp_black_list = tracer._get_amp_op_list() + + with paddle.no_grad(): + outputs = run_function(*args) + return outputs + + @staticmethod + def backward(ctx, *args): + from paddle.distributed.fleet.meta_parallel.parallel_layers.random import ( + get_rng_state_tracker, + ) + + with paddle.fluid.dygraph.guard(): + # TODO need to check the recompute calling is vaild or not + + # Restore inputs + inputs = list(ctx.inputs) + tensor_indices = ctx.tensor_indices + tensors = ctx.saved_tensor() + for i, idx in enumerate(tensor_indices): + inputs[idx] = tensors[i] + + # paddle.enable_grad() + tracer = framework._dygraph_tracer() + tracer._has_grad = True + + # NOTE support AMP + # need restore auto_cast state as well as w/b list + if ctx.preserve_rng_state: + with swith_rng_state_tracker( + ctx.fw_cuda_rng_state, ctx.fwd_cuda_rng_state_tracker + ): + with paddle.amp.auto_cast( + enable=ctx.is_fw_autocast, + custom_white_list=ctx.amp_white_list, + custom_black_list=ctx.amp_black_list, + level=ctx.amp_level, + dtype=ctx.amp_dtype, + ): + detached_inputs = detach_variable(tuple(inputs)) + outputs = ctx.run_function(*detached_inputs) + else: + with paddle.amp.auto_cast( + enable=ctx.is_fw_autocast, + custom_white_list=ctx.amp_white_list, + custom_black_list=ctx.amp_black_list, + level=ctx.amp_level, + dtype=ctx.amp_dtype, + ): + detached_inputs = detach_variable(tuple(inputs)) + outputs = ctx.run_function(*detached_inputs) + + if isinstance(outputs, core.VarBase): + outputs = (outputs,) + assert len(outputs) == len(args) + + # run backward() with only tensor that requires grad + forward_outputs_with_grad = [] + # NOTE In Transformer-like network, if user put the attention mask into the recompute segment output, + # pylayer will force the stop_gradient of attention mask to be False, which will make the number of + # tensor that need grad does not match. + # the following backward_inputs_with_grad is used to avoid this case. + backward_inputs_with_grad = [] + for i in range(len(outputs)): + if ( + isinstance(outputs[i], core.VarBase) + and not outputs[i].stop_gradient + ): + forward_outputs_with_grad.append(outputs[i]) + backward_inputs_with_grad.append(args[i]) + + if len(forward_outputs_with_grad) == 0: + raise RuntimeError( + "none of output has requires_grad=True, this recompute() is not necessary" + ) + + # actually backward + with paddle.amp.auto_cast(enable=False): + paddle.autograd.backward( + forward_outputs_with_grad, backward_inputs_with_grad + ) + + grads = list( + inp._grad_ivar() + for inp in detached_inputs + if isinstance(inp, core.VarBase) + ) + return grads + + +class RecomputeFunction(PyLayer): + @staticmethod + def forward(ctx, run_function, preserve_rng_state, *args, **kwargs): + from paddle.distributed.fleet.meta_parallel.parallel_layers.random import ( + get_rng_state_tracker, + ) + + # store for recomputing + ctx.run_function = run_function + ctx.preserve_rng_state = preserve_rng_state + ctx.kwargs = kwargs + + # NOTE the number of outputs of backward() should be equal to the number of tensors in forward()'s input + # the order of tensors in backward()'s output should be the same as tensors in forward()'s input + # None tensor inputs will be filtered in backward inputs. + + # save input for backward + ctx.inputs = [] + ctx.tensor_indices = [] + tensor_inputs = [] + for i, arg in enumerate(args): + if paddle.is_tensor(arg): + tensor_inputs.append(arg) + ctx.tensor_indices.append(i) + ctx.inputs.append(None) + else: + ctx.inputs.append(arg) + ctx.save_for_backward(*tensor_inputs) + + # NOTE recompute with restore RNG only support one senario where one process for one cuda gpu. + # one process with multiple gpu and mix-gpu-cpu senarios are not support + if ctx.preserve_rng_state: + cur_device = paddle.get_device() + if 'gpu:' not in cur_device: + raise RuntimeError( + "Recompute with RNG perserve is not support current device: {}.".format( + cur_device + ) + ) + ctx.fw_cuda_rng_state = paddle.get_cuda_rng_state() + ctx.fwd_cuda_rng_state_tracker = ( + get_rng_state_tracker().get_states_tracker() + ) + + # TODO support AMP + tracer = framework._dygraph_tracer() + ctx.is_fw_autocast = ( + False if tracer._amp_level == core.AmpLevel.O0 else True + ) + if tracer._amp_level == core.AmpLevel.O2: + ctx.amp_level = 'O2' + elif tracer._amp_level in (core.AmpLevel.O1, core.AmpLevel.O0): + ctx.amp_level = 'O1' + else: + raise ValueError( + "unsupported amp level: {}".format(tracer._amp_level) + ) + + if tracer._amp_dtype == 'float16': + ctx.amp_dtype = 'float16' + elif tracer._amp_dtype in ('bfloat16', 'float32'): + ctx.amp_dtype = 'bfloat16' + else: + raise ValueError( + "unsupported amp dtype: {}".format(tracer._amp_dtype) + ) + + ctx.amp_white_list, ctx.amp_black_list = tracer._get_amp_op_list() + + with paddle.no_grad(): + outputs = run_function(*args, **kwargs) + return outputs + + @staticmethod + def backward(ctx, *args): + from paddle.distributed.fleet.meta_parallel.parallel_layers.random import ( + get_rng_state_tracker, + ) + + with paddle.fluid.dygraph.guard(): + # TODO need to check the recompute calling is vaild or not + + # Restore inputs + inputs = list(ctx.inputs) + tensor_indices = ctx.tensor_indices + tensors = ctx.saved_tensor() + for i, idx in enumerate(tensor_indices): + inputs[idx] = tensors[i] + + # paddle.enable_grad() + tracer = framework._dygraph_tracer() + tracer._has_grad = True + + # NOTE support AMP + # need restore auto_cast state as well as w/b list + if ctx.preserve_rng_state: + with swith_rng_state_tracker( + ctx.fw_cuda_rng_state, ctx.fwd_cuda_rng_state_tracker + ): + with paddle.amp.auto_cast( + enable=ctx.is_fw_autocast, + custom_white_list=ctx.amp_white_list, + custom_black_list=ctx.amp_black_list, + level=ctx.amp_level, + dtype=ctx.amp_dtype, + ): + detached_inputs = detach_variable(tuple(inputs)) + outputs = ctx.run_function( + *detached_inputs, **ctx.kwargs + ) + else: + with paddle.amp.auto_cast( + enable=ctx.is_fw_autocast, + custom_white_list=ctx.amp_white_list, + custom_black_list=ctx.amp_black_list, + level=ctx.amp_level, + dtype=ctx.amp_dtype, + ): + detached_inputs = detach_variable(tuple(inputs)) + outputs = ctx.run_function(*detached_inputs, **ctx.kwargs) + + if isinstance(outputs, (core.VarBase, core.eager.Tensor)): + outputs = (outputs,) + assert len(outputs) == len(args) + + # run backward() with only tensor that requires grad + forward_outputs_with_grad = [] + # NOTE In Transformer-like network, if user put the attention mask into the recompute segment output, + # pylayer will force the stop_gradient of attention mask to be False, which will make the number of + # tensor that need grad does not match. + # the following backward_inputs_with_grad is used to avoid this case. + backward_inputs_with_grad = [] + for i in range(len(outputs)): + if ( + isinstance(outputs[i], (core.VarBase, core.eager.Tensor)) + and not outputs[i].stop_gradient + ): + forward_outputs_with_grad.append(outputs[i]) + backward_inputs_with_grad.append(args[i]) + + if len(forward_outputs_with_grad) == 0: + raise RuntimeError( + "none of output has requires_grad=True, this recompute() is not necessary" + ) + + # actually backward + with paddle.amp.auto_cast(enable=False): + paddle.autograd.backward( + forward_outputs_with_grad, backward_inputs_with_grad + ) + + if in_dygraph_mode(): + grads = tuple( + inp._grad_ivar() + for inp in detached_inputs + if isinstance(inp, (core.VarBase, core.eager.Tensor)) + ) + else: + grads = list( + inp._grad_ivar() + for inp in detached_inputs + if isinstance(inp, (core.VarBase, core.eager.Tensor)) + ) + return grads + + +def recompute(function, *args, **kwargs): + """ + recompute intermediate activations to save then memory. + + Parameters: + function(paddle.nn.Layer): layer of sequence of layers that describes part of forward pass of the model + whose intermediate activations will be released to save memory in forward stage and will be recomputed + in backward stage for gradient calculation. + *args(Tensor): inputs to the function. + **kwargs(Dict): Kwargs should only contain the key-value pair of preserve_rng_state, which is used to + indicate whether to save the forward rng. If it is True, then the last forward rng value will be + restored when the forward recalculation of backpropagation is performed. The default + preserve_rng_state is True. + + Returns: + Output of function on args. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed.fleet.utils import recompute + import random + # required: gpu + def get_fc_block(block_idx, input_size, is_last=False): + block_name = "block_" + str(block_idx) + block = paddle.nn.Sequential( + (block_name + "_fc_0", paddle.nn.Linear(input_size, input_size, bias_attr=False)), + (block_name + "_dropout", paddle.nn.Dropout(p=0.5)), + (block_name + "_relu_1", paddle.nn.ReLU()), + (block_name + "_fc_1", paddle.nn.Linear(input_size, input_size, bias_attr=False)), + (block_name + "_relu_2", paddle.nn.ReLU()), + ) + if is_last: + block.add_sublayer( + block_name + "_fc_2", + paddle.nn.Linear( + input_size, 1, bias_attr=False + ) + ) + else: + block.add_sublayer( + block_name + "_fc_2", + paddle.nn.Linear(input_size, input_size, bias_attr=False) + ) + return block + class Naive_fc_net(paddle.nn.Layer): + def __init__(self, input_size=10, + recompute_blocks=[1, 3], + recompute_kwargs={}): + super(Naive_fc_net, self).__init__() + self.recompute_blocks = recompute_blocks + self.recompute_kwargs = recompute_kwargs + self.runfunc0 = get_fc_block(0, input_size, is_last=False) + self.runfunc1 = get_fc_block(1, input_size, is_last=False) + self.runfunc2 = get_fc_block(2, input_size, is_last=False) + self.runfunc3 = get_fc_block(3, input_size, is_last=False) + self.runfunc4 = get_fc_block(4, input_size, is_last=True) + self.total_func = [self.runfunc0, self.runfunc1, self.runfunc2, self.runfunc3, self.runfunc4] + def forward(self, inputs): + nums = len(self.total_func) + for i in range(nums): + if i in self.recompute_blocks: + inputs = recompute(self.total_func[i], inputs, **{"preserve_rng_state": True}) + else: + inputs = self.total_func[i](inputs) + return inputs + def run_model(cuda_state, recompute_block=[], recompute_kwargs={}): + gen = paddle.seed(10) + gen.manual_seed(10) + random.seed(10) + if cuda_state: + paddle.set_cuda_rng_state(cuda_state) + batch_size, input_size = 1, 10 + model = Naive_fc_net( + input_size, + recompute_blocks=recompute_block, + recompute_kwargs=recompute_kwargs) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + loss_ = [] + param_ = [] + grad_ = [] + for _ in range(5): + x = paddle.rand(shape=[batch_size, input_size], dtype="float32") + y_pred = model(x) + loss = y_pred.mean() + loss_.append(loss.item()) + loss.backward() + optimizer.step() + param_.append(model.parameters()[9]) + grad_.append(model.parameters()[3]._grad_ivar()) + optimizer.clear_grad() + return loss_, param_, grad_ + cuda_state = paddle.get_cuda_rng_state() + # without recompute + loss_ref, param_ref, grad_ref = run_model( + cuda_state, recompute_block=[] + ) + loss, param, grad = run_model(cuda_state, recompute_block=[1, 2]) + print("normal_loss: {}, recompute_loss: {}".format(loss_ref, loss)) + # The result of the recompute_loss should be the same as the normal_loss. + """ + # Hack to mix *args with **kwargs in a python 2.7-compliant way + preserve = kwargs.pop('preserve_rng_state', True) + + if framework._dygraph_tracer()._has_grad: + check_recompute_necessary(args) + + return RecomputeFunction.apply(function, preserve, *args, **kwargs) + + +def recompute_sequential(ctx, functions, *args, **kwargs): + """ + recompute intermediate activations to save then memory for 'Sequential' models. + + Parameters: + ctx(dict): include 'segments' and 'preserve_rng_state' keys, the key 'segments' (int, default 1), represents the number of chunks to create in the model, + the key 'preserve_rng_state' (bool, optional, default=True) indicate whether to save the forward rng. If it is True, then the last forward rng value will be + restored when the forward recalculation of backpropagation is performed. and some keys such as 'mp_group', 'offload' and 'partition' are invalid here, + they are useful in 'recompute_hybrid' API. + functions(paddle.nn.Sequential): layer of sequence of layers that describes part of forward pass of the model + whose intermediate activations will be released to save memory in forward stage and will be recomputed + in backward stage for gradient calculation. + *args(Tensor): inputs(tuple) to the function. + **kwargs(Dict): inputs(dict) to the function. + + Returns: + Output of function on args and kwargs. + + Examples: + .. code-block:: python + + model = paddle.nn.Sequential(...) + input = recompute_sequential({'segments' : 1}, model, input) + """ + segments = ctx.get('segments', 1) + preserve_rng_state = ctx.get('preserve_rng_state', True) + + def _run_func(begin, end, funcs): + def do_run(input): + for i in range(begin, end + 1): + input = funcs[i](input) + return input + + return do_run + + if isinstance(functions, paddle.nn.Sequential): + functions = list(functions.children()) + + segment_size = len(functions) // segments + + end = -1 + for begin in range(0, segment_size * (segments - 1), segment_size): + end = begin + segment_size - 1 + args = recompute( + _run_func(begin, end, functions), + *args, + preserve_rng_state=preserve_rng_state, + **kwargs + ) + return _run_func(end + 1, len(functions) - 1, functions)(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute_hybrid.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute_hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..4883cad2511bb83a77ab81635e7bb7096c0e6298 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/recompute/recompute_hybrid.py @@ -0,0 +1,250 @@ +# Copyright (c) 2021 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. + +import contextlib + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.autograd import PyLayer +from paddle.fluid import framework +from ..meta_parallel.parallel_layers.random import get_rng_state_tracker +from paddle.fluid.framework import in_dygraph_mode +from paddle.distributed import fleet +from .recompute import check_recompute_necessary, detach_variable, swith_rng_state_tracker +from ..meta_parallel.pp_utils import utils + +__all__ = [] + + +def _split_activation(tensor, mp_group): + + mp_degree = mp_group.nranks + mp_rank = mp_group.rank + if mp_degree < 2: + return tensor + + tensor_numel = paddle.numel(tensor) + assert tensor_numel != 0, "can't recompute zero element" + assert tensor_numel % mp_degree == 0, "The capacity of the activation ({}) cannot be divisible by mp_degree({})".format( + tensor_numel, mp_degree) + + # use inplace operation to save memory + data = tensor.flatten_() + + part_size = tensor_numel // mp_degree + start = part_size * mp_rank + end = start + part_size + return data[start:end] + + +def _merge_activation(tensor, mp_group): + mp_degree = mp_group.nranks + mp_rank = mp_group.rank + if mp_degree < 2: + return tensor + + # adapt to new dygraph + tensor_shape = list(tensor.shape) + tensor_shape[0] *= mp_group.nranks + out = paddle.empty(tensor_shape, tensor.dtype) + task = mp_group.process_group.all_gather(tensor.cuda(), out) + task.wait() + return out + + +class _HPRecomputeFunction(PyLayer): + """ + Compared with paddle.distributed.fleet.utils.recompute, there are the following differences: + 1. In order to support PipeLineParallel, the input of recompute is modified to ensure that the input can be tuple type. + 2. Offload support for activation + 3. Support MP segmentation of activation to further reduce cuda memory + 4. Adapt to the random state of MP + """ + + @staticmethod + def forward(ctx, run_function, all_outputs, mp_group, offload, partition, + *args, **kwargs): + check_recompute_necessary(args) + + # store for recomputing + ctx.run_function = run_function + + ctx.kwargs = kwargs + + # store the rng states + ctx.fwd_cuda_rng_state = paddle.get_cuda_rng_state() + ctx.fwd_cuda_rng_state_tracker = get_rng_state_tracker( + ).get_states_tracker() + + # save config info + ctx.mp_group = mp_group + ctx.offload = offload + ctx.partition = partition + + # save input for backward + ctx.inputs = [] + ctx.tensor_indices = [] + ctx.tensor_shapes = [] + tensor_inputs = [] + + cur_device = paddle.get_device() + assert 'gpu:' in paddle.get_device( + ), "Recompute with RNG is not support current device: {}.".format( + cur_device) + + # TODO support AMP + tracer = framework._dygraph_tracer() + ctx.is_fw_autocast = False if tracer._amp_level == core.AmpLevel.O0 else True + if tracer._amp_level == core.AmpLevel.O2: + ctx.amp_level = 'O2' + elif tracer._amp_level in (core.AmpLevel.O1, core.AmpLevel.O0): + ctx.amp_level = 'O1' + else: + raise ValueError("unsupported amp level: {}".format( + tracer._amp_level)) + ctx.amp_white_list, ctx.amp_black_list = tracer._get_amp_op_list() + + with paddle.no_grad(): + outputs = run_function(*args, **kwargs) + + for i, arg in enumerate(args): + if paddle.is_tensor(arg): + state = arg.stop_gradient + if partition: + ctx.tensor_shapes.append(arg.shape) + partition = _split_activation(arg.detach(), + mp_group).clone() + # TODO(shenliang03) not use calculate stream to D2H to speed + arg = partition.cpu() if offload else partition + else: + arg = arg.cpu() if offload else arg + arg.stop_gradient = state + tensor_inputs.append(arg) + ctx.tensor_indices.append(i) + ctx.inputs.append(None) + else: + ctx.inputs.append(arg) + + ctx.save_for_backward(*tensor_inputs) + + if paddle.is_tensor(outputs): + all_outputs += [outputs] + return outputs + else: + all_outputs += outputs + return tuple(outputs) + + @staticmethod + def backward(ctx, *args): + with paddle.fluid.dygraph.guard(): + # Restore inputs + inputs = list(ctx.inputs) + tensor_indices = ctx.tensor_indices + tensor_shapes = ctx.tensor_shapes + tensors = list(ctx.saved_tensor()) + + device_id = paddle.distributed.ParallelEnv().device_id + for i, idx in enumerate(tensor_indices): + if ctx.partition: + state = tensors[i].stop_gradient + tensors[i] = _merge_activation( + tensors[i], + ctx.mp_group).detach().reshape_(tensor_shapes[i]) + tensors[i].stop_gradient = state + inputs[idx] = tensors[i].cuda( + device_id) if ctx.offload else tensors[i] + + tracer = framework._dygraph_tracer() + tracer._has_grad = True + + # need restore auto_cast state as well as w/b list + with swith_rng_state_tracker(ctx.fwd_cuda_rng_state, + ctx.fwd_cuda_rng_state_tracker): + with paddle.amp.auto_cast(enable=ctx.is_fw_autocast, + custom_white_list=ctx.amp_white_list, + custom_black_list=ctx.amp_black_list, + level=ctx.amp_level): + detached_inputs = detach_variable(tuple(inputs)) + outputs = ctx.run_function(*detached_inputs, **ctx.kwargs) + + if isinstance(outputs, (core.VarBase, core.eager.Tensor)): + outputs = (outputs, ) + assert len(outputs) == len(args) + + forward_outputs_with_grad = [] + backward_inputs = [] + + for i in range(len(outputs)): + if isinstance( + outputs[i], + (core.VarBase, + core.eager.Tensor)) and not outputs[i].stop_gradient: + forward_outputs_with_grad.append(outputs[i]) + backward_inputs.append(args[i]) + + if len(forward_outputs_with_grad) == 0: + raise RuntimeError( + "none of output has stop_gradient=False, this recompute() is not necessary" + ) + + # actually backward + paddle.autograd.backward(forward_outputs_with_grad, backward_inputs) + grads = tuple(inp._grad_ivar() for inp in detached_inputs + if isinstance(inp, (core.VarBase, core.eager.Tensor))) + return grads + + +def recompute_hybrid(ctx, function, *args, **kwargs): + """ + # NODTE(shenliang03)The current hybrid parallel recompute has limitations. + # It cannot handle the following situations: + # 1. The calculation output of recompute, there are tensors that do not require gradients. + # 2. The forward output tensor has no gradient. This problem can be solved temporarily by detach(). + # 3. Here, we only use float dtype to distinguish whether a gradient is needed in output tensor + + Parameters: + ctx(dict): include 'mp_group', 'offload', and 'partition' keys. the key 'mp_group' (Group), represents the avtivations are splitted + in which group. the key 'offload' (bool, optional, default=False), represents whether to offload to cpu. the key 'partition' (bool, optional, default=False), + represents whether to split activations in the mp_group. and some keys such as 'segments' and 'preserve_rng_state' are invalid here, they are useful in + 'recompute_sequential' API. + function(paddle.nn.Layer): layer of sequence of layers that describes part of forward pass of the model + whose intermediate activations will be released to save memory in forward stage and will be recomputed + in backward stage for gradient calculation. + *args(Tensor): inputs(tuple) to the function. + + **kwargs(Dict): inputs(dict) to the function. + + Returns: + Output of function on args and kwargs. + + """ + mp_group = ctx.get('mp_group', None) + assert mp_group is not None, "ctx must contains mp_group and mp_group can not be None." + + offload = ctx.get('offload', False) + partition = ctx.get('partition', False) + + all_outputs = [] + _HPRecomputeFunction.apply(function, all_outputs, mp_group, offload, + partition, *args, **kwargs) + + if len(all_outputs) == 1: + return all_outputs[0] + else: + for output in all_outputs: + if paddle.is_tensor(output) and not utils.is_float_tensor(output): + output.stop_gradient = True + + return tuple(all_outputs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c30b2f3c5aaadeb5d1dad2799a08931fc70b17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/__init__.py @@ -0,0 +1,19 @@ +# 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. + +from .collective_runtime import CollectiveRuntime +from .parameter_server_runtime import ParameterServerRuntime +from .the_one_ps import TheOnePSRuntime + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/collective_runtime.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/collective_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..183fa9e7c156eb862131272003953460c5d032a2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/collective_runtime.py @@ -0,0 +1,51 @@ +# 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. + +from .runtime_base import RuntimeBase +import logging + +__all__ = [] + + +class CollectiveRuntime(RuntimeBase): + + def __init__(self): + super(CollectiveRuntime, self).__init__() + + def _init_worker(self): + logging.warn( + "You should not call 'init_worker' method for collective mode.") + pass + + def _run_worker(self): + logging.warn( + "You should not call 'run_worker' method for collective mode.") + pass + + def _init_server(self, *args, **kwargs): + logging.warn( + "You should not call 'init_server' method for collective mode.") + pass + + def _run_server(self): + logging.warn( + "You should not call 'run_server' method for collective mode.") + pass + + def _stop_worker(self): + logging.warn( + "You should not call 'stop_worker' method for collective mode.") + pass + + # save inference model should be added here diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/parameter_server_runtime.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/parameter_server_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..6e30ff7969e1d4dc4e37e44f81d41b25f57e320f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/parameter_server_runtime.py @@ -0,0 +1,693 @@ +# 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. + +import os +import warnings + +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.framework import Program +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.executor import Executor +from paddle.fluid.parallel_executor import ParallelExecutor +from paddle.fluid.framework import Variable, Parameter + +from .runtime_base import RuntimeBase +from ..base.private_helper_function import wait_server_ready + +__all__ = [] + + +class ParameterServerRuntime(RuntimeBase): + + def __init__(self): + super(ParameterServerRuntime, self).__init__() + self._communicator = None + + def _set_basic_info(self, context): + self.context = context + self.role_maker = context["role_maker"] + self.origin_main_program = context["origin_main_program"] + self.origin_startup_program = context["origin_startup_program"] + self.async_strategy = self._get_distributed_strategy() + self.compiled_strategy = self.build_compiled_startegy() + + def _get_distributed_strategy(self): + strategy = None + + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import StrategyFactory + + dist_strategy = self.context["valid_strategy"] + k_steps = dist_strategy.a_sync_configs["k_steps"] + + if not dist_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_sync_strategy() + + if dist_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_async_strategy() + + if dist_strategy.a_sync and k_steps > 0: + strategy = StrategyFactory.create_geo_strategy(k_steps) + + if not strategy: + raise ValueError("k_steps must be invalid value, please check") + + return strategy + + def build_compiled_startegy(self): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import CompileTimeStrategy + + compiled_config = CompileTimeStrategy(self.origin_main_program, + self.origin_main_program, + self.async_strategy, + self.role_maker) + return compiled_config + + def _load_sparse_params(self, + executor, + dirname, + varnames, + main_program=None): + assert vars != None + check_vars = [] + load_prog = Program() + load_block = load_prog.global_block() + + def _in_varnames(var): + return var.name in varnames + + load_vars = list( + filter(_in_varnames, + fluid.default_main_program().list_vars())) + if main_program is None: + main_program = self.origin_main_program + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_varname_parts + for each_var in load_vars: + assert isinstance(each_var, Variable) + + origin_varname, _, _ = _get_varname_parts(each_var.name) + + new_var = fluid.io._clone_var_in_block_(load_block, each_var) + var_path = os.path.join(dirname, origin_varname) + if not os.path.exists(var_path): + raise ValueError( + "SelectedRows var {} can not find at {}".format( + new_var.name, var_path)) + + if os.path.isfile(var_path): + load_block.append_op(type='sparse_tensor_load', + inputs={}, + outputs={'Out': [new_var]}, + attrs={ + 'file_path': + os.path.join(dirname, origin_varname), + 'node_index': + self.role_maker._server_index(), + 'node_num': + self.role_maker._server_num(), + 'shape': + each_var.shape + }) + check_vars.append(each_var) + + executor.run(load_prog) + + def _load_distributed_params(self, dirname, varnames): + from paddle.fluid.communicator import LargeScaleKV + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_varname_parts + + scale_kv = LargeScaleKV() + for varname in varnames: + origin_varname, _, _ = _get_varname_parts(varname) + sparse_dir = os.path.join(dirname, origin_varname, varname) + scale_kv.load(varname, sparse_dir) + + @staticmethod + def __exclude_vars(exclude_var_names=[]): + + def is_valid(var): + if var.name in exclude_var_names: + return False + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_varname_parts + + origin_varname, _, _ = _get_varname_parts(var.name) + if origin_varname.endswith("@GRAD"): + return False + + if origin_varname == "learning_rate_0": + return False + + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + return is_valid + + def _init_worker(self): + + def sync_strategy_envs(): + kwargs = {} + kwargs[ + "pserver_endpoints"] = self.role_maker._get_pserver_endpoints() + kwargs["trainer_id"] = self.role_maker._worker_index() + return kwargs + + def geo_strategy_envs(): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames + + def get_sparse_attrs(): + opt_init_map = {} + opt_init_map["gaussian_random"] = ["seed", "mean", "std"] + opt_init_map["fill_constant"] = ["value"] + opt_init_map["uniform_random"] = ["seed", "min", "max"] + opt_init_map["truncated_gaussian_random"] = [ + "seed", "mean", "std" + ] + + dist_varnames = get_sparse_tablenames(self.origin_main_program, + True) + sparse_varnames = get_sparse_tablenames( + self.origin_main_program, False) + + if len(dist_varnames) != 0: + raise ValueError( + "GeoStrategy can not support large scale embeding now, please use fluid.layers.embedding" + ) + + init_attrs = [] + for value_name in sparse_varnames: + value_var = self.origin_main_program.global_block( + ).vars[value_name] + value_attr = [ + value_name, + ",".join([str(dim) for dim in value_var.shape]) + ] + for op in self.origin_startup_program.global_block().ops: + if op.type in opt_init_map.keys( + ) and value_name == op.output("Out")[0]: + init_attr = [op.type] + for attr in opt_init_map[op.type]: + init_attr.append(str(op.attr(attr))) + value_attr.append("&".join(init_attr)) + init_attrs.append(":".join(value_attr)) + break + return "#".join(init_attrs) + + kwargs = {} + kwargs["trainers"] = self.role_maker._worker_num() + kwargs["sparse_attrs"] = get_sparse_attrs() + return kwargs + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_lr_ops, _has_global_step + + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import \ + SyncStrategy, GeoStrategy + + trainer_config = self.async_strategy.get_trainer_runtime_config() + print(trainer_config) + + dist_strategy = self.context["valid_strategy"] + launch_barrier = dist_strategy.a_sync_configs["launch_barrier"] + if launch_barrier: + # for trainer wait server ready + wait_server_ready(self.role_maker._get_pserver_endpoints()) + + # for ps-heter mode, wait heter worker ready + if self.role_maker._is_heter_parameter_server_mode and self.role_maker._is_worker( + ): + wait_server_ready(self.role_maker._get_heter_worker_endpoints()) + + lrs = _has_global_step(_get_lr_ops(self.origin_main_program)) + + if lrs: + kwargs = {"need_global_step": "1"} + else: + kwargs = {"need_global_step": "0"} + + if isinstance(self.async_strategy, GeoStrategy): + geo_kwargs = geo_strategy_envs() + kwargs.update(geo_kwargs) + if isinstance(self.async_strategy, SyncStrategy): + sync_kwargs = sync_strategy_envs() + kwargs.update(sync_kwargs) + + kwargs = kwargs if kwargs else None + + send_ctx = self.compiled_strategy.get_communicator_send_context() + + if self.compiled_strategy.is_geo_mode(): + recv_ctx = self.compiled_strategy.get_communicator_recv_context( + recv_type=4) + else: + recv_ctx = self.compiled_strategy.get_communicator_recv_context( + recv_type=1) + + from paddle.fluid.communicator import Communicator + self._communicator = Communicator( + trainer_config.mode, kwargs, + trainer_config.get_communicator_flags()) + self._communicator.init_with_ctx(send_ctx, recv_ctx) + + if not self._communicator.is_running(): + self._communicator.start() + else: + warnings.warn("communicator has been initialized, skip") + + def _get_executor(self): + executor = fluid.Executor(fluid.CPUPlace()) + if self.role_maker._is_heter_parameter_server_mode: + heter_worker_device_guard = self.context[ + "valid_strategy"].a_sync_configs[ + "heter_worker_device_guard"].upper() + if heter_worker_device_guard not in ["GPU", "XPU", "CPU"]: + raise ValueError("Heter Worker Not Support Device {}".format( + heter_worker_device_guard)) + if self.role_maker._is_heter_worker(): + if heter_worker_device_guard == "GPU": + executor = Executor( + fluid.CUDAPlace( + int(os.getenv("FLAGS_selected_gpus", "0")))) + elif heter_worker_device_guard == "XPU": + executor = Executor( + fluid.XPUPlace( + int(os.getenv("FLAGS_selected_xpus", "0")))) + return executor + + def _init_server(self, *args, **kwargs): + if len(args) > 1: + raise ValueError("init server can only accept 1 args: `dirname`") + elif len(args) == 1: + model_dirname = args[0] + else: + model_dirname = None + + executor = self._get_executor() + if self.role_maker._is_heter_worker( + ) and self.context["valid_strategy"].a_sync_configs["launch_barrier"]: + # for heter trainer wait server ready + wait_server_ready(self.role_maker._get_pserver_endpoints()) + executor.run(fluid.default_startup_program()) + + if self.role_maker._is_heter_worker(): + self._init_worker() + return + + sparse_varnames = self.compiled_strategy.get_sparse_varname_on_ps(False) + sparse_related_optimize_varnames = [] + for var_name in sparse_varnames: + sparse_related_optimize_varnames += self.compiled_strategy.get_optimize_varname_on_ps( + var_name) + sparse_related_optimize_varnames = list( + set(sparse_related_optimize_varnames)) + distribtued_varnames = self.compiled_strategy.get_sparse_varname_on_ps( + True) + distributed_related_optimize_varnames = [] + for var_name in distribtued_varnames: + distributed_related_optimize_varnames += self.compiled_strategy.get_optimize_varname_on_ps( + var_name) + distributed_related_optimize_varnames = list( + set(distributed_related_optimize_varnames)) + + remaining_vars = list( + filter( + ParameterServerRuntime.__exclude_vars( + sparse_varnames + distribtued_varnames + + sparse_related_optimize_varnames + + distributed_related_optimize_varnames), + fluid.default_main_program().list_vars())) + + if not model_dirname: + return + + if not os.path.isdir(model_dirname): + raise ValueError("There is no directory named '%s'", model_dirname) + + # load dense + fluid.io.load_vars(executor, + main_program=fluid.default_main_program(), + dirname=model_dirname, + vars=remaining_vars) + + # load sparse + self._load_sparse_params(executor=executor, + dirname=model_dirname, + varnames=sparse_varnames + + sparse_related_optimize_varnames) + + # load large scale + self._load_distributed_params(dirname=model_dirname, + varnames=distribtued_varnames + + distributed_related_optimize_varnames) + + def _run_server(self): + executor = self._get_executor() + executor.run(fluid.default_main_program()) + + def _stop_worker(self): + self._communicator.stop() + executor = self._get_executor() + executor.close() + + def _get_optimizer_status(self, op, param_name): + supported_opts = [ + "sgd", "adam", "adagrad", "adamax", "momentum", "lars_momentum", + "rmsprop", "decayed_adagrad", "ftrl" + ] + + reshaped_val_map = {} + reshaped_val_map["sgd"] = [] + reshaped_val_map["adam"] = ["moment1_0", "moment2_0"] + reshaped_val_map["adagrad"] = ["moment_0"] + reshaped_val_map["adamax"] = ["moment_0", "inf_norm_0"] + reshaped_val_map["momentum"] = ["velocity_0"] + reshaped_val_map["lars_momentum"] = ["velocity_0"] + reshaped_val_map["rmsprop"] = [ + "momentum_0", "mean_square_0", "mean_grad_0" + ] + reshaped_val_map["decayed_adagrad"] = ["moment_0"] + reshaped_val_map["ftrl"] = ["squared_0", "linear_0"] + + orishaped_val_map = {} + orishaped_val_map["adam"] = ["beta1_pow_acc_0", "beta2_pow_acc_0"] + orishaped_val_map["adamax"] = ["beta1_pow_acc_0"] + + if op not in supported_opts: + raise ValueError( + "fleet can not support optimizer: {}, only this can be supported: {}" + .format(op, supported_opts)) + + reshaped_names = [ + param_name + "_" + val for val in reshaped_val_map[op] + ] + + if op not in orishaped_val_map: + origin_names = [] + else: + origin_names = [ + param_name + "_" + val for val in orishaped_val_map[op] + ] + return reshaped_names, origin_names + + def _get_optimizer_op(self, param_name): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_optimize_ops + + opts = _get_optimize_ops(self.origin_main_program) + for op in opts: + if "Param" in op.input_names and \ + "LearningRate" in op.input_names and op.input("Param")[0] == param_name: + return op + + def _save_dense_params(self, executor, dirname, context, main_program): + self._communicator.recv() + + prog = Program() + block = prog.global_block() + local_vars = [] + + for name, var_ctx in context.items(): + if len(var_ctx.origin_varnames()) != 1: + raise ValueError("Dense can not support split now.") + + varname = var_ctx.origin_varnames()[0] + local_vars.append(varname) + + optimizer = self._get_optimizer_op(varname) + reshaped_varnames, origin_varnames = self._get_optimizer_status( + optimizer.type, varname) + + for var_name in [varname] + reshaped_varnames + origin_varnames: + var = self.origin_main_program.global_block().vars[var_name] + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self.role_maker._worker_index(), + "shape": + var.shape, + "slice_shapes": + [",".join([str(i) for i in var.shape])], + "slice_varnames": [var.name], + "remote_varnames": [var.name], + "is_sparse": + False, + "endpoints": + var_ctx.split_endpoints(), + "file_path": + os.path.join(dirname, var.name) + }) + + executor.run(prog) + return local_vars + + def _save_sparse_params(self, executor, dirname, context, main_program): + prog = Program() + block = prog.global_block() + local_vars = [] + + for name, var_ctx in context.items(): + if len(var_ctx.origin_varnames()) != 1: + raise ValueError("Dense can not support split now.") + + varname = var_ctx.origin_varnames()[0] + local_vars.append(varname) + + optimizer = self._get_optimizer_op(varname) + reshaped_varnames, origin_varnames = self._get_optimizer_status( + optimizer.type, varname) + + var = self.origin_main_program.global_block().vars[varname] + slice_shapes = [] + dims1 = ",".join([str(i) for i in var.shape[1:]]) + + for section in var_ctx.sections(): + slice_shapes.append(str(section) + dims1) + + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self.role_maker._worker_index(), + "shape": + var.shape, + "slice_shapes": + slice_shapes, + "slice_varnames": + var_ctx.split_varnames(), + "remote_varnames": + var_ctx.split_varnames(), + "is_sparse": + True, + "endpoints": + var_ctx.split_endpoints(), + "pserver_num": + len(self.role_maker._get_pserver_endpoints()), + "file_path": + os.path.join(dirname, var.name) + }) + + for reshaped_varname in reshaped_varnames: + var = self.origin_main_program.global_block( + ).vars[reshaped_varname] + + slice_varnames = [] + remote_varnames = [] + for i in range(len(var_ctx.split_varnames())): + slice_varnames.append("{}.block{}".format( + reshaped_varname, i)) + remote_varnames.append(reshaped_varname) + + block.append_op( + type='recv_save', + attrs={ + "trainer_id": self.role_maker._worker_index(), + "shape": var.shape, + "slice_shapes": slice_shapes, + "slice_varnames": slice_varnames, + "remote_varnames": remote_varnames, + "is_sparse": True, + "endpoints": var_ctx.split_endpoints(), + "pserver_num": + len(self.role_maker._get_pserver_endpoints()), + "file_path": os.path.join(dirname, var.name) + }) + + for origin_varname in origin_varnames: + var = self.origin_main_program.global_block( + ).vars[origin_varname] + + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self.role_maker._worker_index(), + "shape": + var.shape, + "slice_shapes": + [",".join([str(i) for i in var.shape])], + "slice_varnames": [origin_varname], + "remote_varnames": [origin_varname], + "is_sparse": + False, + "endpoints": + var_ctx.split_endpoints()[:1], + "file_path": + os.path.join(dirname, var.name) + }) + executor.run(prog) + return context.keys() + + def _save_distributed_params(self, executor, dirname, context, mode): + prog = Program() + block = prog.global_block() + + for name, var_ctx in context.items(): + block.append_op(type='checkpoint_notify', + attrs={ + "varname": name, + "mode": mode, + "slice_varnames": var_ctx.split_varnames(), + "remote_varnames": var_ctx.split_varnames(), + "endpoints": var_ctx.split_endpoints(), + "dirname": dirname + }) + + executor.run(prog) + return context.keys() + + def _save_distributed_persistables(self, executor, dirname, main_program, + mode): + dense_ctx = self.compiled_strategy.get_communicator_recv_context( + recv_type=1, use_origin_program=True) + + sparse_ctx = self.compiled_strategy.get_communicator_recv_context( + recv_type=2, use_origin_program=True) + + distributed_ctx = self.compiled_strategy.get_communicator_recv_context( + recv_type=3, use_origin_program=True) + + recv_dense_varnames = self._save_dense_params(executor, dirname, + dense_ctx, main_program) + + recv_sparse_varnames = self._save_sparse_params(executor, dirname, + sparse_ctx, + main_program) + + recv_distributed_varnames = self._save_distributed_params( + executor, dirname, distributed_ctx, mode) + + saved_varnames = recv_dense_varnames + list( + recv_sparse_varnames) + list(recv_distributed_varnames) + + remaining_vars = list( + filter(ParameterServerRuntime.__exclude_vars(saved_varnames), + main_program.list_vars())) + + fluid.io.save_vars(executor, + main_program=main_program, + dirname=dirname, + vars=remaining_vars) + + def _ps_inference_save_persistables(self, + executor, + dirname, + main_program=None, + mode=0, + **kwargs): + """ + This function filters out all variables with `persistable==True` from the + give `main_program` and then saves these variables to the folder `dirname` + or file `filename`. + + The `dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set `filename` None; if you would like to save all variables in a + single file, use `filename` to specify the file name. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save_persistables() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save_persistables() function, executor must be as Executor type" + ) + + if main_program is None: + main_program = self.compiled_strategy.get_origin_ps_main_program() + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save_persistables() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + self._save_distributed_persistables(executor, dirname, main_program, + mode) + + def _ps_inference_save_inference_model(self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True): + """ + Prune the given `main_program` to build a new program especially for inference, + and then save it and all related parameters to given `dirname` by the `executor`. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save_inference_model() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save_inference_model() function, executor must be as Executor type" + ) + + if main_program is not None: + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save_inference_model() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + fluid.io.save_inference_model(dirname, feeded_var_names, + target_vars, executor, main_program, + None, None, export_for_deployment) + else: + fluid.io.save_inference_model(dirname, feeded_var_names, + target_vars, executor, + self.origin_main_program, None, None, + export_for_deployment, True) + + model_basename = "__model__" + model_filename = os.path.join(dirname, model_basename) + + with open(model_filename, "rb") as f: + program_desc_str = f.read() + + program = Program.parse_from_string(program_desc_str) + program._copy_dist_param_info_from(fluid.default_main_program()) + self._ps_inference_save_persistables(executor, + dirname, + program, + mode=0) + + def _save_inference_model(self, *args, **kwargs): + self._ps_inference_save_inference_model(*args, **kwargs) + + def _save_persistables(self, *args, **kwargs): + self._ps_inference_save_persistables(*args, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/runtime_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/runtime_base.py new file mode 100644 index 0000000000000000000000000000000000000000..38bb31ce3fc1d66e66e0200c2c4c6488592cb935 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/runtime_base.py @@ -0,0 +1,42 @@ +# 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. + +__all__ = [] + + +class RuntimeBase(object): + + def __init__(self): + pass + + def _set_basic_info(self, context): + self.context = context + + def _run_worker(self): + pass + + def _init_server(self, *args, **kwargs): + pass + + def _run_server(self): + pass + + def _stop_worker(self): + pass + + def _save_inference_model(self, *args, **kwargs): + pass + + def _save_persistables(self, *args, **kwargs): + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/the_one_ps.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/the_one_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..82cef558b1f442724b227802027f01ee6cc90776 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/runtime/the_one_ps.py @@ -0,0 +1,1435 @@ +# 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. + +import warnings + +import os +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.framework import Program +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.executor import Executor +from paddle.fluid.parallel_executor import ParallelExecutor +from paddle.fluid.framework import Variable, Parameter +from .runtime_base import RuntimeBase +from ..base.private_helper_function import wait_server_ready + +__all__ = [] + + +def conv_indent(indent): + return "".join([" "] * indent) + + +PSERVER_SAVE_SUFFIX = ".shard" + + +def parse_table_class(varname, o_main_program): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_distributed_sparse_op + from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_sparse_op + + for op in o_main_program.global_block().ops: + if not is_distributed_sparse_op(op) and not is_sparse_op(op): + continue + + param_name = op.input("W")[0] + + if param_name == varname and op.type == "lookup_table" or op.type == "lookup_table_v2": + if op.has_attr('table_class') and op.attr("table_class") != "none": + return op.attr('table_class') + else: + return "MemorySparseTable" + + +def get_default_accessor_proto(accessor, varname, o_main_program): + embedding_dim = 0 + for var in o_main_program.list_vars(): + if var.name == varname: + embedding_dim = var.shape[1] + break + + if not accessor.HasField("accessor_class"): + accessor.accessor_class = "CtrCommonAccessor" + if not accessor.HasField("fea_dim"): + accessor.fea_dim = embedding_dim + if not accessor.HasField("embedx_dim"): + accessor.embedx_dim = embedding_dim - 3 + if not accessor.HasField("embedx_threshold"): + accessor.embedx_threshold = 0 + + ctr_accessor_param = accessor.ctr_accessor_param + if not ctr_accessor_param.HasField("nonclk_coeff"): + ctr_accessor_param.nonclk_coeff = 0.1 + if not ctr_accessor_param.HasField("click_coeff"): + ctr_accessor_param.click_coeff = 1.0 + if not ctr_accessor_param.HasField("base_threshold"): + ctr_accessor_param.base_threshold = 0 + if not ctr_accessor_param.HasField("delta_threshold"): + ctr_accessor_param.delta_threshold = 0 + if not ctr_accessor_param.HasField("delta_keep_days"): + ctr_accessor_param.delta_keep_days = 16 + if not ctr_accessor_param.HasField("show_click_decay_rate"): + ctr_accessor_param.show_click_decay_rate = 1 + if not ctr_accessor_param.HasField("delete_threshold"): + ctr_accessor_param.delete_threshold = 0 + if not ctr_accessor_param.HasField("delete_after_unseen_days"): + ctr_accessor_param.delete_after_unseen_days = 30 + if not ctr_accessor_param.HasField("ssd_unseenday_threshold"): + ctr_accessor_param.ssd_unseenday_threshold = 1 + + for sgd_param in [accessor.embed_sgd_param, accessor.embedx_sgd_param]: + if not sgd_param.HasField("name"): + sgd_param.name = "SparseAdaGradSGDRule" + if sgd_param.name == "SparseAdaGradSGDRule" or sgd_param.name == "StdAdaGradSGDRule": + if not sgd_param.adagrad.HasField("learning_rate"): + sgd_param.adagrad.learning_rate = 0.05 + if not sgd_param.adagrad.HasField("initial_g2sum"): + sgd_param.adagrad.initial_g2sum = 3.0 + if not sgd_param.adagrad.HasField("initial_range"): + sgd_param.adagrad.initial_range = 0.0001 + if len(sgd_param.adagrad.weight_bounds) == 0: + sgd_param.adagrad.weight_bounds.extend([-10.0, 10.0]) + if sgd_param.name == "SparseNaiveSGDRule": + if not sgd_param.naive.HasField("learning_rate"): + sgd_param.naive.learning_rate = 0.05 + if not sgd_param.naive.HasField("initial_range"): + sgd_param.naive.initial_range = 0.0001 + if len(sgd_param.naive.weight_bounds) == 0: + sgd_param.naive.weight_bounds.extend([-10.0, 10.0]) + if sgd_param.name == "SparseAdamSGDRule": + if not sgd_param.adam.HasField("learning_rate"): + sgd_param.adam.learning_rate = 0.001 + if not sgd_param.adam.HasField("initial_range"): + sgd_param.adam.initial_range = 0.0001 + if not sgd_param.adam.HasField("beta1_decay_rate"): + sgd_param.adam.beta1_decay_rate = 0.9 + if not sgd_param.adam.HasField("beta2_decay_rate"): + sgd_param.adam.beta2_decay_rate = 0.999 + if not sgd_param.adam.HasField("ada_epsilon"): + sgd_param.adam.ada_epsilon = 1e-08 + if len(sgd_param.adam.weight_bounds) == 0: + sgd_param.adam.weight_bounds.extend([-10.0, 10.0]) + + +def check_embedding_dim(accessor, varname, o_main_program): + embedding_dim = 0 + for var in o_main_program.list_vars(): + if var.name == varname: + embedding_dim = var.shape[1] + break + fea_dim = accessor.fea_dim + if fea_dim != embedding_dim: + raise ValueError( + "The fea_dim is wrong, it will be sparse_embedding_dim: {}, but got {}" + .format(embedding_dim, fea_dim)) + embedx_dim = accessor.embedx_dim + if embedx_dim != embedding_dim - 3: + raise ValueError( + "The embedx_dim is wrong, it will be sparse_embedding_dim - 3: {}, but got {}" + .format(embedding_dim - 3, embedx_dim)) + + +class Accessor: + + def __init__(self): + self.accessor_class = "" + self.optimizer = None + self.feature_dim = -1 + self.embedding_dim = -1 + self.optimizer = None + + def to_string(self, indent): + accessor_str = "{}accessor {{{}\n{}}}" + attrs = "" + attrs += "accessor_class: \"{}\" ".format(self.accessor_class) + attrs += "fea_dim: {} ".format(self.feature_dim) + attrs += "embedx_dim: {} ".format(self.embedding_dim) + attrs += "\n" + if self.optimizer is not None: + attrs += self.optimizer.to_string(indent) + return accessor_str.format(conv_indent(indent), attrs, + conv_indent(indent)) + + +class CommonAccessor: + + def __init__(self): + self.accessor_class = "" + self.table_name = None + self.entry = None + self.attrs = [] + self.params = [] + self.dims = [] + self.trainer_num = 0 + self.sync = "false" + self.table_num = None + self.table_dim = None + self.initializers = [] + self.opt_input_map = {} + self.opt_attr_map = {} + self.opt_init_map = {} + self.define_optimize_map() + + def define_optimize_map(self): + opt_input_map = {} + opt_input_map["sgd"] = [("Param", None), ("LearningRate", 1)] + opt_input_map["adam"] = [("Param", None), ("Moment1", None), + ("Moment2", None), ("Beta1Pow", 1), + ("Beta2Pow", 1), ("LearningRate", 1)] + opt_input_map["adam_d2sum"] = [("Param", None), ("D2Sum", None), + ("G2Sum", None), ("Moment", None), + ("MomentDecayRate", 1), + ("AdaDecayRate", 1), ("AdaEpsilon", 1), + ("LearningRate", 1)] + opt_input_map["sum"] = [("Param", None)] + opt_input_map["naive_adagrad"] = [("Param", None), ("G2Sum", 1), + ("LearningRate", 1)] + + opt_attr_map = {} + opt_attr_map["sgd"] = [] + opt_attr_map["sum"] = [] + opt_attr_map["naive_adagrad"] = [] + opt_attr_map["adam"] = [("beta1", "f"), ("beta2", "f"), + ("epsilon", "f")] + opt_attr_map["adam_d2sum"] = [("beta1", "f"), ("beta2", "f"), + ("epsilon", "f")] + + opt_init_map = {} + opt_init_map["gaussian_random"] = ["seed", "mean", "std"] + opt_init_map["fill_constant"] = ["value"] + opt_init_map["uniform_random"] = ["seed", "min", "max"] + opt_init_map["truncated_gaussian_random"] = ["seed", "mean", "std"] + + self.opt_attr_map = opt_attr_map + self.opt_input_map = opt_input_map + self.opt_init_map = opt_init_map + + def parse_entry(self, varname, o_main_program): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_distributed_sparse_op + from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_sparse_op + + for op in o_main_program.global_block().ops: + if not is_distributed_sparse_op(op) and not is_sparse_op(op): + continue + + param_name = op.input("W")[0] + + if param_name == varname and op.type == "lookup_table": + self.entry = op.attr('entry') + break + + if param_name == varname and op.type == "lookup_table_v2": + self.entry = "none" + break + + def get_shard(self, total_dim, shard_num, pserver_id): + # remainder = total_dim % shard_num + blocksize = int(total_dim / shard_num + 1) + + if blocksize * (pserver_id + 1) <= total_dim: + return blocksize + else: + if blocksize * pserver_id < total_dim: + return total_dim - blocksize * pserver_id + else: + return 0 + + def get_initializer_attr(self, value_name, o_startup_program): + l_in = "&" + attr_str = "" + + origin_var_name = value_name + for op in o_startup_program.global_block().ops: + if op.type in self.opt_init_map.keys( + ) and origin_var_name == op.output("Out")[0]: + init_attr = [op.type] + for attr in self.opt_init_map[op.type]: + init_attr.append(str(op.attr(attr))) + attr_str = l_in.join(init_attr) + break + return attr_str + + def parse_by_optimizer(self, grad_name, is_sparse, size, single_dim, + compiled_strategy, adam_d2sum): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_optimize_ops + param_name = compiled_strategy.grad_name_to_param_name[grad_name] + main_program, startup_program = compiled_strategy.get_origin_programs() + pserver_id = compiled_strategy.get_role_id() + pserver_num = len(compiled_strategy.get_ps_endpoints()) + optimizer_ops = _get_optimize_ops(main_program) + oop = None + + for op in optimizer_ops: + if ("Param" in op.input_names) and (op.input("Param")[0] + == param_name): + oop = op + break + + if oop is None: + raise ValueError("can not find optimizer for {}".format(grad_name)) + + params = [] + dims = [] + attrs = [] + initializers = [] + + self.trainer_num = compiled_strategy.get_trainers() + self.table_num = size + self.table_dim = single_dim + + if oop.type != 'adam' and adam_d2sum == True: + print('optimization algorithm is not adam, set adam_d2sum False') + adam_d2sum = False + print("adam_d2sum:", adam_d2sum) + if compiled_strategy.is_geo_mode(): + param_varnames = self.opt_input_map["sum"] + attr_varnames = self.opt_attr_map["sum"] + self.accessor_class = "sum" + elif compiled_strategy.use_ps_gpu and is_sparse: + param_varnames = self.opt_input_map["naive_adagrad"] + attr_varnames = self.opt_attr_map["naive_adagrad"] + self.accessor_class = "sgd" + elif adam_d2sum and not is_sparse: + param_varnames = self.opt_input_map["adam_d2sum"] + attr_varnames = self.opt_attr_map["adam_d2sum"] + self.accessor_class = "adam_d2sum" + else: + param_varnames = self.opt_input_map[oop.type] + attr_varnames = self.opt_attr_map[oop.type] + self.accessor_class = oop.type + + for (formal_name, shape) in param_varnames: + params.append(formal_name) + if self.accessor_class == "adam_d2sum": + #for dims + if shape is None: + if is_sparse: + shape = single_dim + else: + shape = self.get_shard(size, pserver_num, pserver_id) + dims.append(shape) + + #for initializers + if formal_name == "Param" or formal_name == "LearningRate": + param = main_program.global_block().vars[oop.input( + formal_name)[0]] + #TODO: for dense learning_rate, can be different from sparse lr + if formal_name == "LearningRate" and param.name != "learning_rate_0": + warnings.warn("will support decay soon") + param = main_program.global_block( + ).vars["learning_rate_0"] + + initializer = self.get_initializer_attr( + param.name, startup_program) + elif formal_name == "MomentDecayRate": + initializer = "fill_constant&0.99" + elif formal_name == "AdaDecayRate": + initializer = "fill_constant&0.9999" + elif formal_name == "AdaEpsilon": + initializer = "fill_constant&1.0e-8" + else: + initializer = "fill_constant&0" + initializers.append(initializer) + else: + if formal_name == "G2Sum": + dims.append(1) + initializer = "fill_constant&0" + initializers.append(initializer) + else: + param = main_program.global_block().vars[oop.input( + formal_name)[0]] + if formal_name == "LearningRate" and param.name != "learning_rate_0": + warnings.warn("will support decay soon") + param = main_program.global_block( + ).vars["learning_rate_0"] + + if shape is None: + if is_sparse: + shape = single_dim + else: + shape = self.get_shard(size, pserver_num, + pserver_id) + dims.append(shape) + + initializer = self.get_initializer_attr( + param.name, startup_program) + initializers.append(initializer) + + for (attr_varname, type_) in attr_varnames: + value = oop.attr(attr_varname) + attrs.append("&".join([attr_varname, type_, str(value)])) + + self.params = params + self.dims = dims + self.initializers = initializers + self.attrs = attrs + + def to_string(self, indent): + accessor_str = "{}common {{{}\n{}}}" + attrs = "" + attrs += "name: \"{}\" ".format(self.accessor_class) + + if self.table_name: + attrs += "table_name: \"{}\" ".format(self.table_name) + + if self.entry: + attrs += "entry: \"{}\" ".format(self.entry) + attrs += "trainer_num: {} ".format(self.trainer_num) + attrs += "sync: {} ".format(self.sync) + if self.table_num: + attrs += "table_num: {} ".format(self.table_num) + if self.table_dim: + attrs += "table_dim: {} ".format(self.table_dim) + + for param in self.params: + attrs += "params: \"{}\" ".format(param) + + for dim in self.dims: + attrs += "dims: {} ".format(dim) + + for initializer in self.initializers: + attrs += "initializers: \"{}\" ".format(initializer) + + attrs += "\n" + return accessor_str.format(conv_indent(indent), attrs, + conv_indent(indent)) + + +class Tensor: + + def __init__(self): + self.main_program_id = None + self.startup_program_id = None + self.feed_var_name = None + self.fetch_var_name = None + self.tensor_table_class = False + + def to_string(self, indent): + program_str = "{}tensor {{{}\n{}}}" + attrs = "" + attrs += "feed_var_name: \"{}\" ".format(str(self.feed_var_name)) + attrs += "fetch_var_name: \"{}\" ".format(str(self.fetch_var_name)) + attrs += "startup_program_id: {} ".format(str(self.startup_program_id)) + attrs += "main_program_id: {} ".format(str(self.main_program_id)) + attrs += "tensor_table_class: \"{}\" ".format( + str(self.tensor_table_class)) + attrs += "\n" + return program_str.format(conv_indent(indent), attrs, + conv_indent(indent)) + + +class Table: + + def __init__(self): + self.id = -1 + self.table_class = None + self.shard_num = -1 + self.type = None + self.accessor = None + self.common = None + self.tensor = None + self.accessor_proto = None + + def to_string(self, indent): + # if self.id == 1: + # proto_txt = '' + # with open('./sparse_table.prototxt') as f: + # proto_txt = f.read() + # return proto_txt + table_str = "{}downpour_table_param {{{}\n{}}}" + + attrs = "" + attrs += "table_id: {} ".format(self.id) + attrs += "table_class: \"{}\" ".format(self.table_class) + attrs += "shard_num: {} ".format(self.shard_num) + attrs += "type: {}".format(self.type) + attrs += "\n" + indent += 2 + + if self.accessor_proto is not None: + accessor_str = "{}accessor {{{}\n{}}}" + accessor_str = accessor_str.format(conv_indent(indent), + self.accessor_proto, + conv_indent(indent)) + attrs += accessor_str + "\n" + elif self.accessor is not None: + attrs += self.accessor.to_string(indent) + attrs += "\n" + + if self.tensor is not None: + attrs += self.tensor.to_string(indent) + attrs += "\n" + + if self.common is not None: + attrs += self.common.to_string(indent) + attrs += "\n" + + return table_str.format(conv_indent(indent), attrs, conv_indent(indent)) + + +class Service: + + def __init__(self): + self.server_class = "BrpcPsServer" + self.client_class = "BrpcPsClient" + self.service_class = "BrpcPsService" + self.start_server_port = 0 + self.server_thread_num = 12 + + def to_string(self, indent): + service_str = "{}service_param {{{}\n{}}}" + + attrs = "" + attrs += "server_class: \"{}\" ".format(self.server_class) + attrs += "client_class: \"{}\" ".format(self.client_class) + attrs += "service_class: \"{}\" ".format(self.service_class) + attrs += "start_server_port: {} ".format(self.start_server_port) + attrs += "server_thread_num: {} ".format(self.server_thread_num) + + return service_str.format(conv_indent(indent), attrs, + conv_indent(indent)) + + +class DownpourServer: + + def __init__(self): + self.service = None + self.tables = [] + + def set_service_param(self, service): + self.service = service + + def append_tables(self, table): + if not isinstance(table, Table): + raise ValueError("only support instance Table") + self.tables.append(table) + + def to_string(self, indent): + server_str = "{}downpour_server_param {{{}\n{}}}" + + table_strs = "" + indent += 2 + + table_strs += "\n" + table_strs += self.service.to_string(indent) + + for table in self.tables: + table_strs += "\n" + table_strs += table.to_string(indent) + return server_str.format(conv_indent(indent), table_strs, + conv_indent(indent)) + + +class Server: + + def __init__(self): + self.servers = [] + + def add_server(self, server): + if not isinstance(server, DownpourServer): + raise ValueError("only support instance DownpourServer") + self.servers.append(server) + + def __str__(self): + server_str = "server_param {{{}\n}}" + indent = 2 + servers_str = "" + for server in self.servers: + servers_str += "\n" + servers_str += server.to_string(indent) + + return server_str.format(servers_str) + + +class DownpourWorker: + + def __init__(self): + self.tables = [] + + def append_tables(self, table): + if not isinstance(table, Table): + raise ValueError("only support instance Table") + self.tables.append(table) + + def to_string(self, indent): + worker_str = "{}downpour_worker_param {{{}\n{}}}" + table_strs = "" + indent += 2 + for table in self.tables: + table_strs += "\n" + table_strs += table.to_string(indent) + + return worker_str.format(conv_indent(indent), table_strs, + conv_indent(indent)) + + +class Worker: + + def __init__(self): + self.workers = [] + + def add_worker(self, worker): + if not isinstance(worker, DownpourWorker): + raise ValueError("only support instance DownpourWorker") + self.workers.append(worker) + + def __str__(self): + worker_str = "worker_param {{{}\n}}" + indent = 2 + workers_str = "" + for worker in self.workers: + workers_str += "\n" + workers_str += worker.to_string(indent) + + return worker_str.format(workers_str) + + +class fsClient: + + def __init__(self, proto): + self.proto = proto + self.uri = proto.uri + self.user = proto.user + self.passwd = proto.passwd + self.hadoop_bin = proto.hadoop_bin + + def to_string(self): + from google.protobuf import text_format + proto_txt = text_format.MessageToString(self.proto) + if proto_txt: + fs_str = "fs_client_param {{\n{}}}" + return fs_str.format(proto_txt) + else: + return "" + + +class TheOnePSRuntime(RuntimeBase): + + def __init__(self): + super(TheOnePSRuntime, self).__init__() + self._communicator = None + self._server = None + self._worker = fluid.core.DistFleetWrapper() + self._server_sub_program = [] + self._heter_client = None + + def _set_basic_info(self, context): + self.context = context + self.role_maker = context["role_maker"] + self.origin_main_program = context["origin_main_program"] + self.origin_startup_program = context["origin_startup_program"] + self.async_strategy = self._get_distributed_strategy() + self.compiled_strategy = self.build_compiled_startegy() + + def _get_distributed_strategy(self): + strategy = None + + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import \ + StrategyFactory + + dist_strategy = self.context["valid_strategy"] + k_steps = dist_strategy.a_sync_configs["k_steps"] + + if not dist_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_sync_strategy() + + if dist_strategy.a_sync and k_steps == 0: + strategy = StrategyFactory.create_async_strategy() + + if dist_strategy.a_sync and k_steps > 0: + strategy = StrategyFactory.create_geo_strategy(k_steps) + + if not strategy: + raise ValueError("k_steps must be invalid value, please check") + + if dist_strategy.a_sync_configs["use_ps_gpu"]: + strategy.use_ps_gpu = True + return strategy + + def build_compiled_startegy(self): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import CompileTimeStrategy + + compiled_config = CompileTimeStrategy(self.origin_main_program, + self.origin_main_program, + self.async_strategy, + self.role_maker) + if self.async_strategy.use_ps_gpu: + compiled_config.use_ps_gpu = True + return compiled_config + + def _init_worker(self): + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import \ + SyncStrategy, GeoStrategy + + is_sync = self.compiled_strategy.is_sync_mode() + worker = self._get_fleet_proto(is_server=False, is_sync=is_sync) + server = self._get_fleet_proto(is_server=True, is_sync=is_sync) + + dist_strategy = self.context["valid_strategy"] + use_ps_gpu = dist_strategy.a_sync_configs["use_ps_gpu"] + if use_ps_gpu: + main_program = self.context['loss'].block.program + if not main_program._fleet_opt: + main_program._fleet_opt = {} + main_program._fleet_opt["use_ps_gpu"] = True + gpus_env = os.getenv("FLAGS_selected_gpus") + main_program._fleet_opt["worker_places"] = [ + int(s) for s in gpus_env.split(",") + ] + + def sync_strategy_envs(): + kwargs = {} + kwargs[ + "pserver_endpoints"] = self.role_maker._get_pserver_endpoints() + kwargs["trainer_id"] = self.role_maker._worker_index() + return kwargs + + proto_txt = str(worker) + "\n" + str(server) + with open('proto_txt', 'w') as f: + f.write(proto_txt) + + debug = bool(int(os.getenv("PSERVER_DEBUG", "0"))) + + if debug: + print("worker: \n{}".format(proto_txt)) + + endpoints = self.compiled_strategy.get_ps_endpoints() + + string_hosts = [] + for idx, ep in enumerate(endpoints): + host, port = ep.split(":") + pshost = fluid.core.PSHost(host, int(port), idx) + string_hosts.append(pshost.serialize_to_string()) + + dense_map = self.compiled_strategy.get_the_one_recv_context( + split_dense_table=self.role_maker._is_heter_parameter_server_mode) + send_ctx = self.compiled_strategy.get_the_one_send_context( + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=self.role_maker._is_heter_parameter_server_mode, + ep_list=endpoints) + trainer_config = self.async_strategy.get_trainer_runtime_config() + + debug = bool(int(os.getenv("PSERVER_DEBUG", "0"))) + if debug: + print("worker: \n{}".format(proto_txt)) + print("communicator send_ctx:") + for key in send_ctx: + print("{}: {}".format(key, send_ctx[key])) + for key in dense_map: + print("{}: {}".format(key, dense_map[key])) + + kwargs = {} + kwargs['need_global_step'] = "0" + kwargs["trainer_id"] = self.role_maker._role_id() + kwargs["trainers"] = self.role_maker._worker_num() + #if self.role_maker._is_heter_worker(): + # kwargs["trainer_id"] += kwargs["trainers"] + + for table in server.servers[0].tables: + if table.table_class == "BarrierTable": + kwargs["barrier_table_id"] = table.id + break + + if isinstance(self.async_strategy, SyncStrategy): + sync_kwargs = sync_strategy_envs() + kwargs.update(sync_kwargs) + + from paddle.fluid.communicator import Communicator, HeterClient + self._communicator = Communicator( + trainer_config.mode, kwargs, + trainer_config.get_communicator_flags()) + self._communicator.init_with_ctx(send_ctx, dense_map, proto_txt, + string_hosts, fluid.global_scope()) + + import paddle.distributed.fleet as fleet + fleet.util.barrier() + info = self._communicator.get_client_info() + if isinstance(info, list) and len(info) > 0: + all_info = self.role_maker._all_gather(info[0]) + # for unittest + if not isinstance(all_info, list): + warnings.warn("gloo may not initialize correctly") + all_info = [all_info] + self._communicator.set_clients(all_info) + # create_c2c_connection default param: + # pserver_timeout_ms=500000 + # pserver_connect_timeout_ms=10000 + # max_retry=3 + self._communicator.create_client_to_client_connection() + print('create c2c connection done') + else: + print('cannot create c2c connection') + + dist_strategy = self.context["valid_strategy"] + + is_test = bool(int(os.getenv("TEST_MODE", "0"))) + + if self.role_maker._is_first_worker( + ) and self.role_maker._is_heter_parameter_server_mode: + # for ps-heter mode load all parameters on first_worker + init_params = self.compiled_strategy.get_the_one_recv_context( + split_dense_table=True, use_origin_program=True) + else: + init_params = dense_map + + if not is_test: + self._communicator.init_params(init_params) + fleet.util.barrier() + self._communicator.pull_dense(init_params) + fleet.util.barrier() + + if not self._communicator.is_running(): + self._communicator.start() + else: + warnings.warn("communicator has been initialized, skip") + + launch_barrier = dist_strategy.a_sync_configs["launch_barrier"] + launch_barrier_flag = int(os.getenv("FLAGS_LAUNCH_BARRIER", "1")) + if launch_barrier and launch_barrier_flag: + # for trainer wait server ready + wait_server_ready(self.role_maker._get_pserver_endpoints()) + if self.role_maker._is_heter_parameter_server_mode and self.role_maker._get_next_trainers( + ) != []: + wait_server_ready(self.role_maker._get_next_trainers()) + if self.role_maker._is_heter_parameter_server_mode: + previous_trainers = [] + if self.role_maker._get_previous_trainers() != []: + previous_trainers = self.role_maker._get_previous_trainers() + next_trainers = [] + if self.role_maker._get_next_trainers() != []: + next_trainers = self.role_maker._get_next_trainers() + self._heter_client = HeterClient(next_trainers, + previous_trainers, + self.role_maker._role_id()) + + def _push_sparse_param(self, + var_name, + table_id=-1, + scope=fluid.global_scope()): + self._communicator.push_sparse_param(var_name, table_id, scope) + + def _get_executor(self): + executor = fluid.Executor(fluid.CPUPlace()) + if self.role_maker._is_heter_parameter_server_mode: + if self.role_maker._is_heter_worker(): + heter_device_type = self.role_maker._heter_device_type().upper() + if heter_device_type not in ["GPU", "XPU", "CPU"]: + raise ValueError( + "Heter Worker Not Support Device {}".format( + device_type)) + if heter_device_type == "GPU": + executor = Executor( + fluid.CUDAPlace( + int(os.getenv("FLAGS_selected_gpus", "0")))) + elif heter_device_type == "XPU": + executor = Executor( + fluid.XPUPlace( + int(os.getenv("FLAGS_selected_xpus", "0")))) + return executor + + def _get_fleet_proto(self, is_server, is_sync, **kwargs): + + def _build_merge_accessor(ctx): + accessor = Accessor() + accessor.accessor_class = "CommMergeAccessor" + accessor.optimizer = None + + if ctx.is_sparse(): + accessor.feature_dim = ctx.sections()[0] + accessor.embedding_dim = ctx.sections()[1] + else: + accessor.feature_dim = ctx.sections()[0] + accessor.embedding_dim = 1 + + return accessor + + def _build_barrier_table(idx): + table = Table() + table.id = idx + table.type = "PS_OTHER_TABLE" + table.table_class = "BarrierTable" + table.shard_num = 256 + + accessor = Accessor() + accessor.accessor_class = "CommMergeAccessor" + accessor.optimizer = None + accessor.feature_dim = 0 + accessor.embedding_dim = 0 + table.accessor = accessor + + common = CommonAccessor() + common.table_name = "barrier_table" + trainer_num = self.compiled_strategy.get_trainers() + if self.role_maker._is_heter_parameter_server_mode: + trainer_num += len( + self.role_maker._get_heter_worker_endpoints()) + common.trainer_num = trainer_num + common.attrs = "" + common.dims = [] + common.params = [] + table.common = common + return table + + def _build_tensor_table(idx, tensor_dict): + table = Table() + table.id = idx + table.type = "PS_OTHER_TABLE" + table.table_class = tensor_dict["tensor_table_class"] + table.shard_num = 256 + + accessor = Accessor() + accessor.accessor_class = "CommMergeAccessor" + accessor.optimizer = None + accessor.feature_dim = 0 + accessor.embedding_dim = 0 + table.accessor = accessor + + common = CommonAccessor() + common.table_name = tensor_dict["feed_var_name"] + common.trainer_num = self.compiled_strategy.get_trainers() + common.attrs = "" + common.dims = [] + common.params = [] + table.common = common + + tensor = Tensor() + tensor.main_program_id = tensor_dict["main_program_id"] + tensor.startup_program_id = tensor_dict["startup_program_id"] + tensor.feed_var_name = tensor_dict["feed_var_name"] + tensor.fetch_var_name = tensor_dict["fetch_var_name"] + tensor.tensor_table_class = tensor_dict["tensor_table_class"] + table.tensor = tensor + + return table + + def _add_tensor_table(tables): + tensor_table_dict = self.compiled_strategy.get_tensor_table_dict() + program_idx = 0 + for table_name in tensor_table_dict: + if tensor_table_dict[table_name]["startup_program"] != None: + tensor_table_dict[table_name][ + "startup_program_id"] = program_idx + self._server_sub_program.append( + tensor_table_dict[table_name]["startup_program"].desc) + program_idx += 1 + if tensor_table_dict[table_name]["main_program"] != None: + tensor_table_dict[table_name][ + "main_program_id"] = program_idx + self._server_sub_program.append( + tensor_table_dict[table_name]["main_program"].desc) + program_idx += 1 + # Todo: Hard code for lr_decay table apply table id + new_table = _build_tensor_table(len(tables), + tensor_table_dict[table_name]) + tables.append(new_table) + return tables + + def _get_tables(): + send_ctx = self.compiled_strategy.get_the_one_send_context( + use_origin_program=True, + split_dense_table=self.role_maker. + _is_heter_parameter_server_mode) + + tables = [] + for idx, (name, ctx) in enumerate(send_ctx.items()): + if ctx.is_tensor_table() or len(ctx.origin_varnames()) < 1: + continue + + table = Table() + table.id = ctx.table_id() + common = CommonAccessor() + + if ctx.is_sparse(): + table.type = "PS_SPARSE_TABLE" + table.shard_num = 256 + + common.table_name = self.compiled_strategy.grad_name_to_param_name[ + ctx.origin_varnames()[0]] + + if self.compiled_strategy.is_geo_mode(): + table.table_class = "MemorySparseGeoTable" + else: + all_table_proto = self.context[ + "user_defined_strategy"].sparse_table_configs + table_proto = all_table_proto.add() + for proto in all_table_proto: + if proto.table_name == common.table_name: + table_proto = proto + break + if table_proto.HasField("table_class"): + table.table_class = table_proto.table_class + else: + table.table_class = parse_table_class( + common.table_name, self.origin_main_program) + if table.table_class != 'MemorySparseTable': + table.table_class = 'MemorySparseTable' + warnings.warn( + "The PS mode must use MemorySparseTable.") + + if table_proto.HasField("shard_num"): + table.shard_num = table_proto.shard_num + else: + table.shard_num = 1000 + warnings.warn( + "The shard_num of sparse table is not set, use default value 1000." + ) + + if table_proto.accessor.ByteSize() == 0: + warnings.warn( + "The accessor of sparse table is not set, use default value." + ) + get_default_accessor_proto(table_proto.accessor, + common.table_name, + self.origin_main_program) + check_embedding_dim(table_proto.accessor, + common.table_name, + self.origin_main_program) + from google.protobuf import text_format + table.accessor_proto = text_format.MessageToString( + table_proto.accessor) + else: + table.type = "PS_DENSE_TABLE" + table.table_class = "MemoryDenseTable" + table.shard_num = 256 + common.table_name = "MergedDense" + + adam_d2sum = self.context["user_defined_strategy"].adam_d2sum + common.parse_by_optimizer( + ctx.origin_varnames()[0], ctx.is_sparse(), + ctx.sections()[0], + ctx.sections()[1] if ctx.is_sparse() else 1, + self.compiled_strategy, adam_d2sum) + + if ctx.is_sparse(): + common.parse_entry(common.table_name, + self.origin_main_program) + + if is_sync: + common.sync = "true" + else: + common.sync = "false" + table.common = common + + if table.table_class != 'MemorySparseTable': + accessor = _build_merge_accessor(ctx) + table.accessor = accessor + tables.append(table) + + tensor_table_dict = self.compiled_strategy.get_tensor_table_dict() + if len(tensor_table_dict) > 0: + tables = _add_tensor_table(tables) + else: + empty_porgram = Program() + self._server_sub_program.append(empty_porgram.desc) + + barrier_table = _build_barrier_table(len(tables)) + tables.append(barrier_table) + return tables + + if is_server: + server = Server() + downpour_server = DownpourServer() + + service = Service() + dist_strategy = self.context["valid_strategy"] + use_ps_gpu = dist_strategy.a_sync_configs["use_ps_gpu"] + if use_ps_gpu: + service.server_class = "PsLocalServer" + service.client_class = "PsLocalClient" + downpour_server.set_service_param(service) + + tables = _get_tables() + downpour_server.tables = tables + server.add_server(downpour_server) + return server + else: + worker = Worker() + downpour_worker = DownpourWorker() + + tables = _get_tables() + downpour_worker.tables = tables + worker.add_worker(downpour_worker) + return worker + + def _init_server(self, dirname=None, var_names=None, **kwargs): + role_id = self.compiled_strategy.get_role_id() + endpoints = self.compiled_strategy.get_ps_endpoints() + is_sync = self.compiled_strategy.is_sync_mode() + trainers = self.compiled_strategy.get_trainers() + if self.role_maker._is_heter_parameter_server_mode: + trainers += len(self.role_maker._get_heter_worker_endpoints()) + server = self._get_fleet_proto(is_server=True, is_sync=is_sync) + proto_txt = str(server) + fs_client = fsClient( + self.context["user_defined_strategy"].fs_client_param) + proto_txt = proto_txt + "\n" + fs_client.to_string() + + debug = bool(int(os.getenv("PSERVER_DEBUG", "0"))) + if debug: + print("server: \n{}".format(proto_txt)) + + string_hosts = [] + for idx, ep in enumerate(endpoints): + host, port = ep.split(":") + pshost = fluid.core.PSHost(host, int(port), idx) + string_hosts.append(pshost.serialize_to_string()) + + self._server = fluid.core.DistFleetWrapper() + self._server.init_server(proto_txt, string_hosts, role_id, trainers, + self._server_sub_program) + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames + + dist_varnames = get_sparse_tablenames(self.origin_main_program, True) + sparse_varnames = get_sparse_tablenames(self.origin_main_program, False) + + distributed_varnames = dist_varnames + sparse_varnames + + if var_names is None: + load_varnames = distributed_varnames + else: + for var_name in var_names: + if var_name not in distributed_varnames: + raise ValueError( + "fleet.init server can only load sparse variables in {}" + .format(distributed_varnames)) + load_varnames = var_names + + if dirname is None or not load_varnames: + return + + sparse_table_maps = {} + for table in server.servers[0].tables: + if table.type == "PS_SPARSE_TABLE" and table.common is not None: + sparse_table_maps[table.common.table_name] = table.id + + dirname = os.path.normpath(dirname) + pserver_id = self.role_maker._role_id() + + for var_name in load_varnames: + table_id = sparse_table_maps[var_name] + # path = os.path.join(dirname, var_name + PSERVER_SAVE_SUFFIX, + # "{}.block{}.txt".format(var_name, pserver_id)) + # meta = os.path.join(dirname, var_name + PSERVER_SAVE_SUFFIX, + # "{}.block{}.meta".format(var_name, pserver_id)) + self._server.load_sparse(dirname, "0", table_id) + + def _run_server(self): + ep = self.compiled_strategy.get_ps_endpoint() + host, port = ep.split(":") + self._server.run_server(host, int(port)) + + def _stop_worker(self): + self._communicator.stop() + if self.role_maker._is_heter_parameter_server_mode: + assert self._heter_client != None, "heter client should not be None in heterps mode" + self._heter_client.stop() + #executor = self._get_executor() + #executor.close() + + @staticmethod + def __exclude_vars(exclude_var_names=[]): + + def is_valid(var): + if var.name in exclude_var_names: + return False + + from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_varname_parts + + origin_varname, _, _ = _get_varname_parts(var.name) + if origin_varname.endswith("@GRAD"): + return False + + if origin_varname == "learning_rate_0": + return False + + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + return is_valid + + def _get_inference_model_path(self, dirname): + if dirname.startswith("afs:") or dirname.startswith("hdfs:"): + model_path = "./dnn_plugin" + else: + model_path = os.path.join(dirname, "dnn_plugin") + return model_path + + def _save_sparse_params(self, executor, dirname, context, main_program, + mode): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames + distributed_varnames = get_sparse_tablenames( + self.compiled_strategy.origin_main_program, True) + values = [] + model_path = self._get_inference_model_path(dirname) + for id, names in context.items(): + if names[0] not in distributed_varnames: + # only save sparse param to local + try: + self._worker.recv_and_save_model(id, model_path) + except: + pass + # save sparse & distributed param on server + self._worker.save_one_model(id, dirname, mode) + values.extend(names) + # self._worker.save_all_model(dirname, mode) + return values + + def _save_distributed_persistables(self, + executor, + dirname, + main_program, + mode=0): + + denses = self.compiled_strategy.get_the_one_recv_context( + is_dense=True, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + sparses = self.compiled_strategy.get_the_one_recv_context( + is_dense=False, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + + sparse_varnames = self._save_sparse_params(executor, dirname, sparses, + main_program, mode) + + recv_dense_varnames = [] + for id, names in denses.items(): + recv_dense_varnames.extend(names) + self._communicator.pull_dense(denses) + + saved_varnames = sparse_varnames + + remaining_vars = list( + filter(TheOnePSRuntime.__exclude_vars(saved_varnames), + main_program.list_vars())) + + import paddle + for var in remaining_vars: + # if var.name not in recv_dense_varnames: + # continue + tensor = var.get_value() + paddle.save(tensor, + os.path.join(dirname, var.name), + use_binary_format=True) + + def _ps_inference_save_persistables(self, + executor, + dirname, + main_program=None, + mode=0, + **kwargs): + """ + This function filters out all variables with `persistable==True` from the + give `main_program` and then saves these variables to the folder `dirname` + or file `filename`. + + The `dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set `filename` None; if you would like to save all variables in a + single file, use `filename` to specify the file name. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type") + + if main_program is None: + main_program = self.compiled_strategy.get_origin_ps_main_program() + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + # Todo(MrChengmo): Save optimizer status + # self._save_distributed_persistables(executor, dirname, main_program, + # mode) + self._worker.save_all_model(dirname, mode) + + def _ps_inference_save_inference_model(self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True, + mode=0): + """ + Prune the given `main_program` to build a new program especially for inference, + and then save it and all related parameters to given `dirname` by the `executor`. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type") + + import paddle + program = self.origin_main_program if main_program is None else main_program + + if isinstance(program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + feed_vars = [ + program.global_block().var(name) for name in feeded_var_names + ] + + infer_program = paddle.static.normalize_program(program, feed_vars, + target_vars) + + infer_program._copy_dist_param_info_from(program) + + model_path = self._get_inference_model_path(dirname) + model_basename = "__model__" + model_basename = os.path.join(model_path, model_basename) + paddle.save(infer_program, model_basename) + + sparses = self.compiled_strategy.get_the_one_recv_context( + is_dense=False, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + sparse_names = self._save_sparse_params(executor, dirname, sparses, + main_program, mode) + + denses = self.compiled_strategy.get_the_one_recv_context( + is_dense=True, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + # TODO(zhaocaibei123): for GEO: should call GeoCommunicator::RecvDense + self._communicator.pull_dense(denses) + + generate_vars = self.context[ + "user_defined_strategy"].trainer_desc_configs["stat_var_names"] + generate_vars = [var for var in generate_vars] + remaining_vars = list( + filter(TheOnePSRuntime.__exclude_vars(sparse_names), + infer_program.list_vars())) + + for var in remaining_vars: + tensor = var.get_value() + paddle.save(tensor, + os.path.join(model_path, var.name), + use_binary_format=True) + + def _save_inference_model(self, *args, **kwargs): + self._ps_inference_save_inference_model(*args, **kwargs) + + def _save_persistables(self, *args, **kwargs): + self._ps_inference_save_persistables(*args, **kwargs) + + def _load_sparse_params(self, dirname, context, main_program, mode): + from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames + distributed_varnames = get_sparse_tablenames( + self.compiled_strategy.origin_main_program, True) + values = [] + for id, names in context.items(): + if names[0] not in distributed_varnames: + # TODO: only load sparse param from local + warnings.warn("varname is not in distributed_varnames, pass") + # load sparse & distributed param on server + self._worker.load_one_table(id, dirname, mode) + values.extend(names) + return values + + def _ps_inference_load_inference_model(self, + dirname, + mode=0, + main_program=None): + if main_program is None: + main_program = self.compiled_strategy.get_origin_ps_main_program() + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + denses = self.compiled_strategy.get_the_one_recv_context( + is_dense=True, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + sparses = self.compiled_strategy.get_the_one_recv_context( + is_dense=False, + split_dense_table=self.role_maker._is_heter_parameter_server_mode, + use_origin_program=True) + + sparse_varnames = self._load_sparse_params(dirname, sparses, + main_program, mode) + + recv_dense_varnames = [] + for id, names in denses.items(): + recv_dense_varnames.extend(names) + + loaded_varnames = sparse_varnames + + remaining_vars = list( + filter(TheOnePSRuntime.__exclude_vars(loaded_varnames), + main_program.list_vars())) + + if dirname.startswith("afs:") or dirname.startswith("hdfs:"): + model_path = "./dnn_plugin" + else: + model_path = os.path.join(dirname, "dnn_plugin") + import paddle + for var in remaining_vars: + if var.name not in recv_dense_varnames: + continue + tensor = paddle.load(os.path.join(model_path, var.name)) + var.set_value(tensor) + + self._communicator.init_params(denses) + + def _load_distributed_persistables(self, path, mode): + self._worker.load_model(path, mode) + + def load_model(self, path, mode): + if mode == 0 or mode == 3: + self._load_distributed_persistables(path, mode) + else: + self._ps_inference_load_inference_model(path, mode) + # self._load_distributed_persistables(path, mode=mode) + + def _shrink(self, threshold=None): + if threshold is not None: + warnings.warn( + "The param threshold is not used in MemorySparseTable, if you need to shrink, please set the config of accessor" + ) + else: + threshold = 0 + import paddle.distributed.fleet as fleet + fleet.util.barrier() + if self.role_maker._is_first_worker(): + sparses = self.compiled_strategy.get_the_one_recv_context( + is_dense=False, + split_dense_table=self.role_maker. + _is_heter_parameter_server_mode, + use_origin_program=True) + + for id, names in sparses.items(): + self._worker.shrink_sparse_table(id, threshold) + fleet.util.barrier() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/scaler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcbaac34a56cd687dd9b690ff293c86493d26ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/scaler.py @@ -0,0 +1,89 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.framework import dygraph_only +from .base.topology import ParallelMode +from paddle.distributed import fleet +from types import MethodType +from paddle.fluid import core +from paddle.fluid.dygraph import to_variable +import numpy as np +from paddle import _C_ops, _legacy_C_ops + + +def distributed_scaler(scaler): + + def unscale_method(self, optimizer): + if not self._enable: + return + if getattr(optimizer, '_param_groups', None) and isinstance( + optimizer._param_groups[0], dict): + param_grads = [] + param_grads_fp16 = [] + param_grads_fp32 = [] + for group in optimizer._param_groups: + for param in group['params']: + if param._grad_ivar() is not None: + param_grads.append(param._grad_ivar()) + if param._grad_ivar( + ).dtype == core.VarDesc.VarType.FP16: + param_grads_fp16.append(param._grad_ivar()) + else: + param_grads_fp32.append(param._grad_ivar()) + else: + param_grads = [ + param._grad_ivar() for param in optimizer._parameter_list + if param._grad_ivar() is not None + ] + param_grads_fp16 = [ + param._grad_ivar() for param in optimizer._parameter_list + if (param._grad_ivar() is not None) and ( + param._grad_ivar().dtype == core.VarDesc.VarType.FP16) + ] + param_grads_fp32 = [ + param._grad_ivar() for param in optimizer._parameter_list + if (param._grad_ivar() is not None) and ( + param._grad_ivar().dtype == core.VarDesc.VarType.FP32) + ] + temp_found_inf_fp16 = to_variable(np.array([0]).astype(np.bool_)) + temp_found_inf_fp32 = to_variable(np.array([0]).astype(np.bool_)) + if len(param_grads_fp16): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp16, + self._scale, + param_grads_fp16, + temp_found_inf_fp16) + if len(param_grads_fp32): + _legacy_C_ops.check_finite_and_unscale(param_grads_fp32, + self._scale, + param_grads_fp32, + temp_found_inf_fp32) + + self._found_inf = 1 if temp_found_inf_fp16 or temp_found_inf_fp32 else 0 + is_found_inf = paddle.to_tensor([self._found_inf], dtype="int32") + + # TODO(shenliang03) Since dp allreduce in the optimizer is + # after the gradscaler, check_finite needs to synchronize global + # information. In the future, we should use check_group to speed. + paddle.distributed.all_reduce(is_found_inf, + op=paddle.distributed.ReduceOp.MAX, + group=None) + self._found_inf = is_found_inf.numpy()[0] + + # Only data_parallel doesn't need to modify scaler + fleet_env = fleet.fleet + if fleet_env._hcg.get_parallel_mode() is not ParallelMode.DATA_PARALLEL: + scaler._unscale = MethodType(unscale_method, scaler) + + return scaler diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..30afae2b432e561bc1e5d8b2cf1461e1a6edaa51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/__init__.py @@ -0,0 +1,129 @@ +# 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. + +from .fs import LocalFS # noqa: F401 +from .fs import HDFSClient # noqa: F401 +from .ps_util import DistributedInfer # noqa: F401 +import paddle.utils.deprecated as deprecated +from paddle.distributed import fleet + +import paddle +from . import log_util # noqa: F401 +from . import hybrid_parallel_util # noqa: F401 + +__all__ = ["LocalFS", "recompute", "DistributedInfer", "HDFSClient"] # noqa + + +def recompute(function, *args, **kwargs): + """ + recompute intermediate activations to save then memory. + Parameters: + function(paddle.nn.Layer): layer of sequence of layers that describes part of forward pass of the model + whose intermediate activations will be released to save memory in forward stage and will be recomputed + in backward stage for gradient calculation. + *args(Tensor): inputs to the function. + **kwargs(Dict): Kwargs should only contain the key-value pair of preserve_rng_state, which is used to + indicate whether to save the forward rng. If it is True, then the last forward rng value will be + restored when the forward recalculation of backpropagation is performed. The default + preserve_rng_state is True. + Returns: + Output of function on args. + + Examples: + .. code-block:: python + + import paddle + from paddle.distributed.fleet.utils import recompute + import random + # required: gpu + def get_fc_block(block_idx, input_size, is_last=False): + block_name = "block_" + str(block_idx) + block = paddle.nn.Sequential( + (block_name + "_fc_0", paddle.nn.Linear(input_size, input_size, bias_attr=False)), + (block_name + "_dropout", paddle.nn.Dropout(p=0.5)), + (block_name + "_relu_1", paddle.nn.ReLU()), + (block_name + "_fc_1", paddle.nn.Linear(input_size, input_size, bias_attr=False)), + (block_name + "_relu_2", paddle.nn.ReLU()), + ) + if is_last: + block.add_sublayer( + block_name + "_fc_2", + paddle.nn.Linear( + input_size, 1, bias_attr=False + ) + ) + else: + block.add_sublayer( + block_name + "_fc_2", + paddle.nn.Linear(input_size, input_size, bias_attr=False) + ) + return block + class Naive_fc_net(paddle.nn.Layer): + def __init__(self, input_size=10, + recompute_blocks=[1, 3], + recompute_kwargs={}): + super(Naive_fc_net, self).__init__() + self.recompute_blocks = recompute_blocks + self.recompute_kwargs = recompute_kwargs + self.runfunc0 = get_fc_block(0, input_size, is_last=False) + self.runfunc1 = get_fc_block(1, input_size, is_last=False) + self.runfunc2 = get_fc_block(2, input_size, is_last=False) + self.runfunc3 = get_fc_block(3, input_size, is_last=False) + self.runfunc4 = get_fc_block(4, input_size, is_last=True) + self.total_func = [self.runfunc0, self.runfunc1, self.runfunc2, self.runfunc3, self.runfunc4] + def forward(self, inputs): + nums = len(self.total_func) + for i in range(nums): + if i in self.recompute_blocks: + inputs = recompute(self.total_func[i], inputs, **{"preserve_rng_state": True}) + else: + inputs = self.total_func[i](inputs) + return inputs + def run_model(cuda_state, recompute_block=[], recompute_kwargs={}): + gen = paddle.seed(10) + gen.manual_seed(10) + random.seed(10) + if cuda_state: + paddle.set_cuda_rng_state(cuda_state) + batch_size, input_size = 1, 10 + model = Naive_fc_net( + input_size, + recompute_blocks=recompute_block, + recompute_kwargs=recompute_kwargs) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + loss_ = [] + param_ = [] + grad_ = [] + for _ in range(5): + x = paddle.rand(shape=[batch_size, input_size], dtype="float32") + y_pred = model(x) + loss = y_pred.mean() + loss_.append(loss.item()) + loss.backward() + optimizer.step() + param_.append(model.parameters()[9]) + grad_.append(model.parameters()[3]._grad_ivar()) + optimizer.clear_grad() + return loss_, param_, grad_ + cuda_state = paddle.get_cuda_rng_state() + # without recompute + loss_ref, param_ref, grad_ref = run_model( + cuda_state, recompute_block=[] + ) + loss, param, grad = run_model(cuda_state, recompute_block=[1, 2]) + print("normal_loss: {}, recompute_loss: {}".format(loss_ref, loss)) + # The result of the recompute_loss should be the same as the normal_loss. + """ + + return fleet.recompute.recompute(function, *args, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/fs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/fs.py new file mode 100644 index 0000000000000000000000000000000000000000..95635154c33aaca9c30b24160629044bb9157a24 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/fs.py @@ -0,0 +1,1566 @@ +# 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. + +import os +import sys +import subprocess +import multiprocessing +from datetime import datetime + +import re +import copy +import errno +import time +import logging +import six +import abc +import paddle.fluid as fluid +from paddle.fluid import core +import functools + +import shutil + +__all__ = [] + + +class ExecuteError(Exception): + pass + + +class FSFileExistsError(Exception): + pass + + +class FSFileNotExistsError(Exception): + pass + + +class FSTimeOut(Exception): + pass + + +class FSShellCmdAborted(ExecuteError): + pass + + +class FS(object): + + @abc.abstractmethod + def ls_dir(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def is_file(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def is_dir(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def is_exist(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def upload(self, local_path, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def download(self, fs_path, local_path): + raise NotImplementedError + + @abc.abstractmethod + def mkdirs(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def delete(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def need_upload_download(self): + raise NotImplementedError + + @abc.abstractmethod + def rename(self, fs_src_path, fs_dst_path): + raise NotImplementedError + + @abc.abstractmethod + def mv(self, fs_src_path, fs_dst_path, overwrite=False, test_exists=False): + raise NotImplementedError + + @abc.abstractmethod + def upload_dir(self, local_dir, dest_dir): + raise NotImplementedError + + @abc.abstractmethod + def list_dirs(self, fs_path): + raise NotImplementedError + + @abc.abstractmethod + def touch(self, fs_path, exist_ok=True): + raise NotImplementedError + + @abc.abstractmethod + def cat(self, fs_path=None): + raise NotImplementedError + + +class LocalFS(FS): + """ + A tool of local file system. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + subdirs, files = client.ls_dir("./") + """ + + def ls_dir(self, fs_path): + """ + List directorys and files under `fs_path` . + + Args: + fs_path(str): The local file path. + + Returns: + Tuple: Return a 2-tuple, the first is a list of all its subdirectories, + and the second is a list of all its subfiles, e.g. ([subdirname1, subdirname1, ...], [filename1, filename2, ...]). + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + subdirs, files = client.ls_dir("./") + """ + if not self.is_exist(fs_path): + return [], [] + + dirs = [] + files = [] + for f in os.listdir(fs_path): + if os.path.isdir(fs_path + "/" + f): + dirs.append(f) + else: + files.append(f) + + return dirs, files + + def mkdirs(self, fs_path): + """ + Create a local directory. + + Args: + fs_path(str): The local directory path. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.mkdirs("test_mkdirs") + client.delete("test_mkdirs") + """ + assert not os.path.isfile(fs_path), "{} is already a file".format( + fs_path) + os.system("mkdir -p {}".format(fs_path)) + + def rename(self, fs_src_path, fs_dst_path): + """ + Rename the file. + + Args: + fs_src_path(str): The actual name of the file or directory + fs_dst_path(str): The new name of the file or directory. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.touch("test_rename_src") + print(client.is_exists("test_rename_src")) # True + client.rename("test_rename_src", "test_rename_dst") + print(client.is_exists("test_rename_src")) # False + print(client.is_exists("test_rename_dst")) # True + client.delete("test_rename_dst") + """ + os.rename(fs_src_path, fs_dst_path) + + def _rmr(self, fs_path): + shutil.rmtree(fs_path) + + def _rm(self, fs_path): + os.remove(fs_path) + + def delete(self, fs_path): + """ + Delete the local file path, whether it's a file or directory. + + Args: + fs_path(str): The local file path. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.mkdirs("test_localFS_mkdirs") + client.delete("test_localFS_mkdirs") + """ + if not self.is_exist(fs_path): + return + + if os.path.isfile(fs_path): + return self._rm(fs_path) + + return self._rmr(fs_path) + + def need_upload_download(self): + return False + + def is_file(self, fs_path): + """ + Whether the local file path is a file. + + Args: + fs_path(str): The local file path. + + Returns: + Bool: Return true if the path exists and it's a file, otherwise return false. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.touch("test_is_file") + print(client.is_file("test_is_file")) # True + client.delete("test_is_file") + """ + return os.path.isfile(fs_path) + + def is_dir(self, fs_path): + """ + Whether the local file path is a directory. + + Args: + fs_path(str): The local file path. + + Returns: + Bool: Return true if the path exists and it's a directory, otherwise return false. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.mkdirs("test_is_dir") + print(client.is_dir("test_is_file")) # True + client.delete("test_is_dir") + """ + return os.path.isdir(fs_path) + + def is_exist(self, fs_path): + """ + Whether the local file path exists. + + Args: + fs_path(str): The local file path. + + Returns: + Bool: Wheter it's a file or directory, return true if the path exists, + otherwise return false. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + ret = local_fs.is_exist("test_is_exist") + """ + return os.path.exists(fs_path) + + def touch(self, fs_path, exist_ok=True): + """ + Create a local file. + + Args: + fs_path(str): The local file path. + exist_ok(bool): When `fs_path` exists, if `exist_ok` is set false, + program will throw an Exception. Default is true. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.touch("test_touch") + client.delete("test_touch") + """ + if self.is_exist(fs_path): + if exist_ok: + return + raise FSFileExistsError + + os.system("touch {}".format(fs_path)) + + def mv(self, src_path, dst_path, overwrite=False, test_exists=False): + """ + Move a local file or directory from `src_path` to `dst_path` . + + Args: + src_path(str): Name of the file or directory, that's needed to be moved. + dst_path(str): Name of the file or directory to which to move to. + overwrite(bool): Whether to re-write `dst_path` if that exists. Default is False. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + client.touch("test_mv_src") + client.mv("test_mv_src", "test_mv_dst") + client.delete("test_mv_dst") + """ + if not self.is_exist(src_path): + raise FSFileNotExistsError + + if overwrite and self.is_exist(dst_path): + self.delete(dst_path) + + if self.is_exist(dst_path): + raise FSFileExistsError + + return self.rename(src_path, dst_path) + + def list_dirs(self, fs_path): + """ + Only list directorys under `fs_path` . + + Args: + fs_path(str): The local file path. + + Returns: + List: A list of all its subdirectories, e.g. [subdirname1, subdirname1, ...]. + + Examples: + .. code-block:: python + + from paddle.distributed.fleet.utils import LocalFS + + client = LocalFS() + subdirs = client.list_dirs("./") + """ + if not self.is_exist(fs_path): + return [] + + dirs = [ + f for f in os.listdir(fs_path) if os.path.isdir(fs_path + "/" + f) + ] + + return dirs + + +def _handle_errors(max_time_out=None): + + def decorator(f): + + @functools.wraps(f) + def handler(*args, **kwargs): + o = args[0] + time_out = max_time_out + if time_out is None: + time_out = float(o._time_out) / 1000.0 + else: + time_out /= 1000.0 + inter = float(o._sleep_inter) / 1000.0 + + start = time.time() + last_print_time = start + while True: + try: + return f(*args, **kwargs) + # important: only ExecuteError need to retry + except ExecuteError as e: + if time.time() - start >= time_out: + raise FSTimeOut("args:{} timeout:{}".format( + args, + time.time() - start)) + + time.sleep(inter) + + if time.time() - last_print_time > 30: + print("hadoop operator timeout:args:{} timeout:{}".format( + args, + time.time() - start)) + last_print_time = time.time() + + return handler + + return decorator + + +class HDFSClient(FS): + """ + A tool of HDFS. + + Args: + hadoop_home(str): Hadoop home. + configs(dict): Hadoop config. It is a dictionary and needs to contain the + keys: "fs.default.name" and "hadoop.job.ugi". + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + hadoop_home = "/home/client/hadoop-client/hadoop/" + + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.ls_dir("hdfs:/test_hdfs_client") + """ + + def __init__( + self, + hadoop_home, + configs, + time_out=5 * 60 * 1000, # ms + sleep_inter=1000): # ms + self.pre_commands = [] + hadoop_bin = '%s/bin/hadoop' % hadoop_home + self.pre_commands.append(hadoop_bin) + dfs = 'fs' + self.pre_commands.append(dfs) + + if configs: + for k, v in six.iteritems(configs): + config_command = '-D%s=%s' % (k, v) + self.pre_commands.append(config_command) + + self._time_out = time_out + self._sleep_inter = sleep_inter + self._base_cmd = " ".join(self.pre_commands) + self._bd_err_re = re.compile( + r'\s?responseErrorMsg\s?\:.*, errorCode\:\s?[0-9]+, path\:') + + def _run_cmd(self, cmd, redirect_stderr=False, retry_times=5): + exe_cmd = "{} -{}".format(self._base_cmd, cmd) + ret = 0 + output = None + retry_sleep_second = 3 + for x in range(retry_times + 1): + ret, output = core.shell_execute_cmd(exe_cmd, 0, 0, redirect_stderr) + ret = int(ret) + if ret == 0: + break + time.sleep(retry_sleep_second) + if ret == 134: + raise FSShellCmdAborted(cmd) + + return ret, output.splitlines() + + @_handle_errors() + def list_dirs(self, fs_path): + """ + Only list directorys under `fs_path` . + + Args: + fs_path(str): The HDFS file path. + + Returns: + List: A list of all its subdirectories, e.g. [subdirname1, subdirname1, ...]. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + subdirs = client.list_dirs("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return [] + + dirs, files = self._ls_dir(fs_path) + return dirs + + @_handle_errors() + def ls_dir(self, fs_path): + """ + List directorys and files under `fs_path` . + + Args: + fs_path(str): The HDFS file path. + + Returns: + Tuple: Return a 2-tuple, the first element is the list of all its subdirectories, + and the second one is the list of all its subfiles, e.g. ([subdirname1, subdirname1, ...], [filename1, filename2, ...]). + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + subdirs, files = client.ls_dir("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return [], [] + + return self._ls_dir(fs_path) + + def _ls_dir(self, fs_path): + cmd = "ls {}".format(fs_path) + ret, lines = self._run_cmd(cmd) + + if ret != 0: + raise ExecuteError(cmd) + + dirs = [] + files = [] + for line in lines: + arr = line.split() + if len(arr) != 8: + continue + + p = os.path.basename(arr[7]) + if arr[0][0] == 'd': + dirs.append(p) + else: + files.append(p) + + return dirs, files + + def _test_match(self, lines): + for l in lines: + m = self._bd_err_re.match(l) + if m != None: + return m + + return None + + @_handle_errors() + def is_dir(self, fs_path): + """ + Whether the remote HDFS path is a directory. + + Args: + fs_path(str): The HDFS file path. + + Returns: + Bool: Return true if the path exists and it's a directory, otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + ret = client.is_file("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return False + + return self._is_dir(fs_path) + + def _is_dir(self, fs_path): + cmd = "test -d {}".format(fs_path, redirect_stderr=True) + ret, lines = self._run_cmd(cmd, retry_times=1) + if ret: + # other error + if self._test_match(lines): + print('raise exception: ') + print('\n'.join(lines)) + raise ExecuteError(cmd) + + return False + + return True + + def is_file(self, fs_path): + """ + Whether the remote HDFS path is a file. + + Args: + fs_path(str): The HDFS file path. + + Returns: + Bool: Return true if the path exists and it's a file, otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + ret = client.is_file("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return False + + return not self._is_dir(fs_path) + + @_handle_errors() + def is_exist(self, fs_path): + """ + Whether the remote HDFS path exists. + + Args: + fs_path(str): The hdfs file path. + + Returns: + Bool: Whether it's is file or directory, return true if the path exists, + otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + ret = client.is_exist("hdfs:/test_hdfs_client") + """ + cmd = "test -e {} ".format(fs_path) + ret, out = self._run_cmd(cmd, redirect_stderr=True, retry_times=1) + if ret != 0: + return False + + return True + + def upload_dir(self, local_dir, dest_dir, overwrite=False): + """ + upload dir to hdfs + Args: + local_dir(str): local dir + dest_dir(str): hdfs dest dir + overwrite(bool): is overwrite + Returns: + return code + """ + local_dir = local_dir.rstrip("/") + dest_dir = dest_dir.rstrip("/") + local_basename = os.path.basename(local_dir) + if self.is_exist(dest_dir + "/" + local_basename) and overwrite: + self.delete(dest_dir + "/" + local_basename) + if not self.is_exist(dest_dir): + self.mkdirs(dest_dir) + self._try_upload(local_dir, dest_dir) + + # can't retry + def upload(self, local_path, fs_path, multi_processes=5, overwrite=False): + """ + Upload the local path to remote HDFS. + + Args: + local_path(str): The local path. + fs_path(str): The HDFS path. + multi_processes(int|1): the upload data process at the same time, default=5 + overwrite(bool|False): will overwrite file on HDFS or not + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.upload("test_hdfs_client", "hdfs:/test_hdfs_client") + """ + + def __subprocess_upload(hdfs_path_single, datas): + for data in datas: + self._try_upload(data, hdfs_path_single) + + def get_local_files(path): + """ + get local files + Args: + path(str): local path + Returns: + list of local files + """ + rlist = [] + + if not os.path.exists(path): + return rlist + + if os.path.isdir(path): + for file in os.listdir(path): + t = os.path.join(path, file) + rlist.append(t) + else: + rlist.append(path) + return rlist + + local = LocalFS() + if not local.is_exist(local_path): + raise FSFileNotExistsError("{} not exists".format(local_path)) + + all_files = get_local_files(local_path) + if not all_files: + print("there are nothing need to upload, function exit") + return + + if self.is_exist(fs_path) and overwrite: + self.delete(fs_path) + self.mkdirs(fs_path) + + procs = [] + for i in range(multi_processes): + process_datas = self._split_files(all_files, i, multi_processes) + p = multiprocessing.Process(target=__subprocess_upload, + args=(fs_path, process_datas)) + procs.append(p) + p.start() + + # complete the processes + for proc in procs: + proc.join() + + @_handle_errors() + def _try_upload(self, local_path, fs_path): + cmd = "put {} {}".format(local_path, fs_path) + ret = 0 + try: + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + self.delete(fs_path) + raise e + + # can't retry + def download(self, fs_path, local_path, multi_processes=5, overwrite=False): + """ + Download remote HDFS path to the local. + + Args: + fs_path(str): The HDFS path. + local_path(str): The local path. + multi_processes(int|1): the download data process at the same time, default=1 + overwrite(bool): is overwrite + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.download("hdfs:/test_hdfs_client", "./") + """ + + def __subprocess_download(local_path, datas): + """ + download file from HDFS + Args: + local_path(str): the local file path + datas(str): the hdfs file path list + """ + for data in datas: + self._try_download(data, local_path) + + if not self.is_exist(fs_path): + raise FSFileNotExistsError("{} not exits".format(fs_path)) + # download file + if self.is_file(fs_path): + return self._try_download(fs_path, local_path) + # download dir + dirs, all_filenames = self.ls_dir(fs_path) + all_files = [fs_path + "/" + i for i in all_filenames] + all_files.extend([fs_path + "/" + i for i in dirs]) + procs = [] + for i in range(multi_processes): + process_datas = self._split_files(all_files, i, multi_processes) + p = multiprocessing.Process(target=__subprocess_download, + args=(local_path, process_datas)) + procs.append(p) + p.start() + + # complete the processes + for proc in procs: + proc.join() + + @_handle_errors() + def _try_download(self, fs_path, local_path): + cmd = "get {} {}".format(fs_path, local_path) + ret = 0 + try: + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + local_fs = LocalFS() + local_fs.delete(local_path) + raise e + + @_handle_errors() + def mkdirs(self, fs_path): + """ + Create a remote HDFS directory. + + Args: + fs_path(str): The HDFS directory path. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.mkdirs("hdfs:/test_hdfs_client") + """ + if self.is_exist(fs_path): + return + + out_hdfs = False + + cmd = "mkdir {} ".format(fs_path) + ret, out = self._run_cmd(cmd, redirect_stderr=True) + if ret != 0: + for l in out: + if "No such file or directory" in l: + out_hdfs = True + break + if not out_hdfs: + raise ExecuteError(cmd) + + if out_hdfs and not self.is_exist(fs_path): + cmd = "mkdir -p {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + def mv(self, fs_src_path, fs_dst_path, overwrite=False, test_exists=True): + """ + Move a remote HDFS file or directory from `fs_src_path` to `fs_dst_path` . + + Args: + fs_src_path(str): Name of the file or directory, that's needed to be moved. + fs_dst_path(str): Name of the file or directory to which to move to. + overwrite(bool): Whether to re-write `fs_dst_path` if that exists. Default is False. + test_exists(bool): Check the existence of `fs_src_path` and `fs_dst_path` . When `test_exists` is set true, if `fs_src_path` doesn't exist or `fs_dst_path` exists, program will throw an Excetption. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.mv("hdfs:/test_hdfs_client", "hdfs:/test_hdfs_client2") + """ + if overwrite and self.is_exist(fs_dst_path): + self.delete(fs_dst_path) + + if test_exists: + if not self.is_exist(fs_src_path): + raise FSFileNotExistsError( + "{} is not exists".format(fs_src_path)) + + if self.is_exist(fs_dst_path): + raise FSFileExistsError("{} exists already".format(fs_dst_path)) + + return self._try_mv(fs_src_path, fs_dst_path) + + @_handle_errors() + def _try_mv(self, fs_src_path, fs_dst_path): + cmd = "mv {} {}".format(fs_src_path, fs_dst_path) + ret = 0 + try: + ret, _ = self._run_cmd(cmd, retry_times=1) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + if not self.is_exist(fs_src_path) and \ + self.is_exist(fs_dst_path): + return + raise e + + def _rmr(self, fs_path): + cmd = "rmr {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + def _rm(self, fs_path): + cmd = "rm {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + @_handle_errors() + def delete(self, fs_path): + """ + Delete a remote HDFS path, whether it's a file or directory. + + Args: + fs_path(str): The HDFS file path. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.delete("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return + + is_dir = self._is_dir(fs_path) + if is_dir: + return self._rmr(fs_path) + + return self._rm(fs_path) + + def touch(self, fs_path, exist_ok=True): + """ + Create a remote HDFS file. + + Args: + fs_path(str): The HDFS file path. + exist_ok(bool): When `fs_path` exists, if `exist_ok` is set false, + program will throw an Exception. Default is true. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.touch("hdfs:/test_hdfs_client") + """ + if self.is_exist(fs_path): + if exist_ok: + return + raise FSFileExistsError + + return self._touchz(fs_path) + + @_handle_errors() + def _touchz(self, fs_path): + cmd = "touchz {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + def need_upload_download(self): + return True + + def cat(self, fs_path=None): + """ + Cat a remote HDFS file. + + Args: + fs_path(str): The HDFS file path. + + Returns: + file content + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + hadoop_home = "/home/client/hadoop-client/hadoop/" + configs = { + "fs.default.name": "hdfs://xxx.hadoop.com:54310", + "hadoop.job.ugi": "hello,hello123" + } + + client = HDFSClient(hadoop_home, configs) + client.cat("hdfs:/test_hdfs_client") + """ + if self.is_file(fs_path): + output = self._try_cat(fs_path) + return "\n".join(output) + else: + return "" + + @_handle_errors() + def _try_cat(self, fs_path): + cmd = "cat {}".format(fs_path) + ret, output = self._run_cmd(cmd, retry_times=1) + if ret != 0: + raise ExecuteError(cmd) + return output + + def _split_files(self, files, trainer_id, trainers): + """ + split file list + Args: + files(list): file list + trainer_id(int): trainer mpi rank id + trainers(int): all trainers num + Returns: + fileist(list): file list of current trainer + """ + remainder = len(files) % trainers + blocksize = len(files) // trainers + + blocks = [blocksize] * trainers + for i in range(remainder): + blocks[i] += 1 + + trainer_files = [[]] * trainers + begin = 0 + for i in range(trainers): + trainer_files[i] = files[begin:begin + blocks[i]] + begin += blocks[i] + + return trainer_files[trainer_id] + + def list_files_info(self, path_list): + """ + list_files return file path and size + Args: + path_list(list): file list + Returns: + fileist(list): file list with file path and size + """ + if len(path_list) <= 0: + return [] + + file_list = [] + + #concat filelist can speed up 'hadoop ls' + str_concat = "" + for path in path_list: + str_concat += path + " " + cmd = "ls " + str_concat + " | awk '{if ($8 != \"\") {print $5\" \"$8 }}'" + ret, lines = self._run_cmd(cmd) + if (len(lines) == 0): + logger.warning("list_files empty, path[%s]" % path_list) + return [] + for line in lines: + arr = line.split(' ') + if len(arr) < 2: + continue + file_path = arr[1] + file_size = int(arr[0]) + file_list.append({'path': file_path, 'size': file_size}) + + return file_list + + +class AFSClient(FS): + """ + A tool of AFS. Use AfsWrapper. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.ls_dir("hdfs:/test_hdfs_client") + """ + + def __init__( + self, + time_out=5 * 60 * 1000, # ms + sleep_inter=1000): # ms + self._fs = core.AfsWrapper() + self._time_out = time_out + + def init(self, fs_name, fs_user, fs_passwd, fs_conf): + self._fs.init(fs_name, fs_user, fs_passwd, fs_conf) + + def list_dirs(self, fs_path): + """ + Only list directorys under `fs_path` . + + Args: + fs_path(str): The HDFS file path. + + Returns: + List: A list of all its subdirectories, e.g. [subdirname1, subdirname1, ...]. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + subdirs = client.list_dirs("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return [] + # TODO:fengdanlei + dirs, files = self._ls_dir(fs_path) + return dirs + + def ls_dir(self, fs_path): + """ + List directorys and files under `fs_path` . + + Args: + fs_path(str): The HDFS file path. + + Returns: + Tuple: Return a 2-tuple, the first element is the list of all its subdirectories, + and the second one is the list of all its subfiles, e.g. ([subdirname1, subdirname1, ...], [filename1, filename2, ...]). + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + subdirs, files = client.ls_dir("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return [], [] + + return self._ls_dir(fs_path) + + def _ls_dir(self, fs_path): + + files = self._fs.list(fs_path) + dirs = [fs_path] + return dirs, files + + def is_dir(self, fs_path): + """ + Whether the remote HDFS path is a directory. + + Args: + fs_path(str): The HDFS file path. + + Returns: + Bool: Return true if the path exists and it's a directory, otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + ret = client.is_file("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return False + + return self._is_dir(fs_path) + + def _is_dir(self, fs_path): + list_path = self._fs.list(fs_path) + if (len(list_path)) > 0: + return True + else: + return False + + def is_file(self, fs_path): + """ + Whether the remote HDFS path is a file. + + Args: + fs_path(str): The HDFS file path. + + Returns: + Bool: Return true if the path exists and it's a file, otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + ret = client.is_file("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return False + + return not self._is_dir(fs_path) + + def is_exist(self, fs_path): + """ + Whether the remote HDFS path exists. + + Args: + fs_path(str): The hdfs file path. + + Returns: + Bool: Whether it's is file or directory, return true if the path exists, + otherwise return false. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + ret = client.is_exist("hdfs:/test_hdfs_client") + """ + return self._fs.exist(fs_path) + + def upload_dir(self, local_dir, dest_dir, overwrite=False): + """ + upload dir to hdfs + Args: + local_dir(str): local dir + dest_dir(str): hdfs dest dir + overwrite(bool): is overwrite + Returns: + return code + """ + local_dir = local_dir.rstrip("/") + dest_dir = dest_dir.rstrip("/") + local_basename = os.path.basename(local_dir) + if self.is_exist(dest_dir + "/" + local_basename) and overwrite: + self.delete(dest_dir + "/" + local_basename) + if not self.is_exist(dest_dir): + self.mkdirs(dest_dir) + self._fs.upload(local_dir, dest_dir) + + # can't retry + def upload(self, local_path, fs_path, multi_processes=1, overwrite=False): + """ + Upload the local path to remote HDFS. + + Args: + local_path(str): The local path. + fs_path(str): The HDFS path. + multi_processes(int|1): the upload data process at the same time, default=5 + overwrite(bool|False): will overwrite file on HDFS or not + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.upload("test_hdfs_client", "hdfs:/test_hdfs_client") + """ + + local = LocalFS() + if not local.is_exist(local_path): + raise FSFileNotExistsError("{} not exists".format(local_path)) + + self._fs.upload(local_path, fs_path) + + def download(self, fs_path, local_path, multi_processes=1, overwrite=False): + """ + Download remote HDFS path to the local. + + Args: + fs_path(str): The HDFS path. + local_path(str): The local path. + multi_processes(int|1): the download data process at the same time, default=1 + overwrite(bool): is overwrite + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.download("hdfs:/test_hdfs_client", "./") + """ + + def __subprocess_download(local_path, datas): + """ + download file from HDFS + Args: + local_path(str): the local file path + datas(str): the hdfs file path list + """ + for data in datas: + self._fs.download(local_path, data) + + if not self.is_exist(fs_path): + raise FSFileNotExistsError("{} not exits".format(fs_path)) + # download file + if self.is_file(fs_path): + return self._fs.download(local_path, fs_path) + # download dir + _, all_filenames = self.ls_dir(fs_path) + all_files = [fs_path + i for i in all_filenames] + procs = [] + for i in range(multi_processes): + process_datas = self._split_files(all_files, i, multi_processes) + p = multiprocessing.Process(target=__subprocess_download, + args=(local_path, process_datas)) + procs.append(p) + p.start() + + # complete the processes + for proc in procs: + proc.join() + + def mkdirs(self, fs_path): + """ + Create a remote HDFS directory. + + Args: + fs_path(str): The HDFS directory path. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.mkdirs("hdfs:/test_hdfs_client") + """ + if self.is_exist(fs_path): + return + self._fs.mkdir(fs_path) + + def mv(self, fs_src_path, fs_dst_path, overwrite=False, test_exists=True): + """ + Move a remote HDFS file or directory from `fs_src_path` to `fs_dst_path` . + + Args: + fs_src_path(str): Name of the file or directory, that's needed to be moved. + fs_dst_path(str): Name of the file or directory to which to move to. + overwrite(bool): Whether to re-write `fs_dst_path` if that exists. Default is False. + test_exists(bool): Check the existence of `fs_src_path` and `fs_dst_path` . When `test_exists` is set true, if `fs_src_path` doesn't exist or `fs_dst_path` exists, program will throw an Excetption. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.mv("hdfs:/test_hdfs_client", "hdfs:/test_hdfs_client2") + """ + if overwrite and self.is_exist(fs_dst_path): + self.delete(fs_dst_path) + + if test_exists: + if not self.is_exist(fs_src_path): + raise FSFileNotExistsError( + "{} is not exists".format(fs_src_path)) + + if self.is_exist(fs_dst_path): + raise FSFileExistsError("{} exists already".format(fs_dst_path)) + + self._fs.mv(fs_src_path, fs_dst_path) + + def delete(self, fs_path): + """ + Delete a remote HDFS path, whether it's a file or directory. + + Args: + fs_path(str): The HDFS file path. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import HDFSClient + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.delete("hdfs:/test_hdfs_client") + """ + if not self.is_exist(fs_path): + return + self._fs.remove(fs_path) + + def touch(self, fs_path, exist_ok=True): + """ + Create a remote HDFS file. + + Args: + fs_path(str): The HDFS file path. + exist_ok(bool): When `fs_path` exists, if `exist_ok` is set false, + program will throw an Exception. Default is true. + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.touch("hdfs:/test_hdfs_client") + """ + if self.is_exist(fs_path): + if exist_ok: + return + raise FSFileExistsError + + return self._fs.touchz(fs_path) + + def need_upload_download(self): + return True + + def cat(self, fs_path=None): + """ + Cat a remote HDFS file. + + Args: + fs_path(str): The HDFS file path. + + Returns: + file content + + Examples: + + .. code-block:: text + + from paddle.distributed.fleet.utils import AFSClient + + client = AFSClient() + client.init("hdfs://xxx.hadoop.com:54310", "hello", "hello123", "./fs_conf") + client.cat("hdfs:/test_hdfs_client") + """ + if self.is_file(fs_path): + return self._fs.cat(fs_path) + else: + return "" + + def _split_files(self, files, trainer_id, trainers): + """ + split file list + Args: + files(list): file list + trainer_id(int): trainer mpi rank id + trainers(int): all trainers num + Returns: + fileist(list): file list of current trainer + """ + remainder = len(files) % trainers + blocksize = len(files) // trainers + + blocks = [blocksize] * trainers + for i in range(remainder): + blocks[i] += 1 + + trainer_files = [[]] * trainers + begin = 0 + for i in range(trainers): + trainer_files[i] = files[begin:begin + blocks[i]] + begin += blocks[i] + + return trainer_files[trainer_id] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/http_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/http_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4653b22f96e07dcf4cf157fdefb5f47880db73bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/http_server.py @@ -0,0 +1,195 @@ +# 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. +"""Http Server.""" + +import logging + +import six +# NOTE: HTTPServer has a different name in python2 and python3 +from http.server import HTTPServer +import http.server as SimpleHTTPServer + +import time +import threading +import socket + +__all__ = [] + + +def get_logger(name, level, fmt): + logger = logging.getLogger(name) + logger.setLevel(level) + handler = logging.FileHandler('http.log', mode='w') + formatter = logging.Formatter(fmt=fmt) + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.propagate = False + return logger + + +_http_server_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +class KVHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): + """ + kv handler class for kv http server, + it defines the way to get/set kv in server. + """ + + def do_GET(self): + """ + get method for kv handler, get value according to key. + """ + log_str = "GET " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + with self.server.kv_lock: + value = self.server.kv.get(scope, {}).get(key) + if value is None: + log_str += ' , key not found: ' + key + self.send_status_code(404) + else: + log_str += ' , key found: ' + key + self.send_response(200) + self.send_header("Content-Length", str(len(value))) + self.end_headers() + self.wfile.write(value) + _http_server_logger.info(log_str) + + def do_PUT(self): + """ + put method for kv handler, set value according to key. + """ + log_str = "PUT " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + content_length = int(self.headers['Content-Length']) + try: + value = self.rfile.read(content_length) + except: + print("receive error invalid request") + self.send_status_code(404) + return + with self.server.kv_lock: + if self.server.kv.get(scope) is None: + self.server.kv[scope] = {} + self.server.kv[scope][key] = value + self.send_status_code(200) + _http_server_logger.info(log_str) + + def do_DELETE(self): + """ + delete method for kv handler, set value according to key. + """ + log_str = "DELETE " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + with self.server.delete_kv_lock: + if self.server.delete_kv.get(scope) is None: + self.server.delete_kv[scope] = set() + self.server.delete_kv[scope].add(key) + self.send_status_code(200) + _http_server_logger.info(log_str) + + def log_message(self, format, *args): + """ + ignore all logging messages in kv handler. + """ + pass + + def send_status_code(self, code): + """ + send status code back to client. + """ + self.send_response(code) + self.send_header("Content-Length", 0) + self.end_headers() + + +class KVHTTPServer(HTTPServer, object): + """ + it is a http server storing kv pairs. + """ + + def __init__(self, port, handler): + """Init.""" + super(KVHTTPServer, self).__init__(('', port), handler) + self.delete_kv_lock = threading.Lock() + self.delete_kv = {} + self.kv_lock = threading.Lock() + self.kv = {} + + def get_deleted_size(self, key): + """ + get deleted size in key. + """ + ret = 0 + with self.delete_kv_lock: + ret = len(self.delete_kv.get(key, set())) + return ret + + +class KVServer: + """ + it is a server storing kv pairs, has a http server inside. + """ + + def __init__(self, port, size={}): + """Init.""" + self.http_server = KVHTTPServer(port, KVHandler) + self.listen_thread = None + self.size = size + + def start(self): + """ + start server until user calls stop to let it quit. + """ + self.listen_thread = threading.Thread( + target=lambda: self.http_server.serve_forever()) + self.listen_thread.start() + + def stop(self): + """ + stop server and clear its resources. + """ + self.http_server.shutdown() + self.listen_thread.join() + self.http_server.server_close() + + def should_stop(self): + """ + return whether the server should stop. + + Returns: + ret(bool): whether the server should stop + """ + for key in self.size: + s = self.http_server.get_deleted_size(key) + if s != self.size.get(key, 0): + return False + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_inference.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b581464fa4dd05fb65735d20ddf948cfa28a51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_inference.py @@ -0,0 +1,786 @@ +# Copyright (c) 2021 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. + +from collections import defaultdict +from paddle.fluid.framework import Program, Block, Operator +from paddle.fluid.framework import _non_static_mode +import paddle.fluid.core as core +import paddle.distributed.fleet as fleet +import numpy as np + + +class HybridParallelInferenceHelper(object): + """ + A helper class to split program for inference with hybrid parallelism. + + Args: + startup_program (Program): the startup program. + main_program (Program): the main program. + num_mp (int): number of model parallel degree. Default ``1``. + num_pp (int): number of pipeline parallel degree. Default ``1``. + micro_batch_size (int): number of micro batch size. Default ``1``. + beam_size (int): number of beam search size. Default ``1``. + init_comm (bool): wheter if initilize comminication group. Default ``True``. + role_maker (RoleMakerBase or subclass): user custom define RoleMakerBase. + If ``role_maker==None``, then use PaddleCloudRoleMaker. Default ``None``. + + Returns: + None. + + Write Paradigm: + + .. code-block:: bash + :name: bash-example1 + + # while op pattern + with paddle.fluid.device_guard(f'{device}:all'): + # init global cond + max_len = layers.fill_constant(shape=[1], dtype="int64", value=10, force_cpu=False) + step_idx = layers.fill_constant(shape=[1], dtype="int64", value=0, force_cpu=False) + cond_int = layers.fill_constant(shape=[1], dtype="int64", value=0, force_cpu=False, name="cond_int") + cond = layers.cast(step_idx < max_len, dtype="bool") + while_op = layers.While(cond, is_test=True) + + # init global lod_tensor_array for generation task + arr = layers.array_write(data, step_idx) + + with while_op.block(): + with paddle.fluid.device_guard(f'{device}:all'): + # read data from global lod_tensor_array + element_in_arr = layers.array_read(array=arr, i=step_idx) + # write placehold data to global lod_tensor_array, + # it need for send_v2 of lod_tensor_array + layers.increment(x=step_idx, value=1.0, in_place=True) + layers.array_write(element_in_arr, i=step_idx, array=arr) + + with paddle.fluid.device_guard(f'{device}:0'): + ... some code + + with paddle.fluid.device_guard(f'{device}:1'): + ... some code + + with paddle.fluid.device_guard(f'{device}:{num_pp-1}'): + # generate some data in while block and write to global lod_tensor_array + # that they are read in next while step. + # we will using send_v2 to send global lod_tensor_array to other pipeline and sync + layers.array_write(other_var, i=step_idx, array=arr) + + # update cond and assign to cond_int, we will sync cond_int + layers.assign(layers.cast(cond, dtype="int32"), cond_int) + + with paddle.fluid.device_guard(f'{model._device}:all'): + # the code below must at end of while block and exists in device:all + layers.assign(layers.cast(cond_int, dtype='bool'), cond) + + with paddle.fluid.device_guard(f'{model._device}:all'): + # use a empty lod_tensor_array to clear lod_tensor_array + layers.assign(layers.create_array(data.dtype), arr) + + + Examples: + + .. code-block:: python + :name: code-example1 + + # required: distributed + import os + import numpy as np + import paddle + import paddle.fluid.layers as layers + import paddle.distributed.fleet as fleet + paddle.enable_static() + + nranks = int(os.getenv("PADDLE_TRAINERS_NUM", 1)) + rank = int(os.getenv("PADDLE_TRAINER_ID", 0)) + dev_id = int(os.getenv("FLAGS_selected_gpus", 0)) + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + if nranks > 1: + dist_strategy = fleet.DistributedStrategy() + dist_strategy.without_graph_optimization = True + fleet.init(is_collective=True, strategy=dist_strategy) + + device = "gpu" + + with paddle.static.program_guard(main_program, startup_program): + with paddle.fluid.device_guard(f'{device}:0'): + X = paddle.static.data(name='X', shape=[None, 2], dtype='float32') + + with paddle.fluid.device_guard(f'{device}:all'): + max_len = layers.fill_constant( + shape=[1], dtype="int64", value=5, force_cpu=False, name="n") + step_idx = layers.fill_constant( + shape=[1], dtype="int64", value=0, force_cpu=False, name="i") + + data = layers.array_write(X, step_idx) + + cond_int = layers.fill_constant(shape=[1], dtype="int64", value=0, force_cpu=False, name="cond_int") + cond = layers.less_than(x=step_idx, y=max_len) + while_op = layers.While(cond, is_test=True) + + with while_op.block(): + with paddle.fluid.device_guard(f'{device}:all'): + input = layers.array_read(array=data, i=step_idx) + layers.increment(x=step_idx, value=1.0, in_place=True) + layers.array_write(input, i=step_idx, array=data) + + with paddle.fluid.device_guard(f'{device}:0'): + param_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(1.0)) + weight1 = paddle.static.create_parameter( + shape=[2, 5], dtype='float32', attr=param_attr, is_bias=False) + hidden1 = paddle.matmul(input, weight1) + + with paddle.fluid.device_guard(f'{device}:1'): + param_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(2.0)) + weight2 = paddle.static.create_parameter( + shape=[5, 2], dtype='float32', attr=param_attr, is_bias=False) + hidden2 = paddle.matmul(hidden1, weight2) + + layers.array_write(hidden2, i=step_idx, array=data) + + # update cond and assign to cond_int, we will sync cond_int + layers.less_than(x=step_idx, y=max_len, cond=cond) + layers.assign(layers.cast(cond, dtype="int32"), cond_int) + + with paddle.fluid.device_guard(f'{device}:all'): + # the code below must at end of while block and exists in device:all + layers.assign(layers.cast(cond_int, dtype='bool'), cond) + + with paddle.fluid.device_guard(f'{device}:all'): + out = layers.create_array(data.dtype) + layers.assign(data, out) + + with paddle.fluid.device_guard(f'{device}:all'): + # use a empty lod_tensor_array to clear lod_tensor_array + layers.assign(layers.create_array(data.dtype), data) + + helper = fleet.HybridParallelInferenceHelper(startup_program, main_program, micro_batch_size=2, num_pp=2, init_comm=nranks>1) + helper.gen_infer_program(['array_write_0.out'], ['cond_int.tmp_0']) + + exe = paddle.static.Executor(paddle.CUDAPlace(dev_id)) + exe.run(startup_program) + + np.random.seed(2333) + for step in range(5): + init_data = np.random.uniform(low=0.0, high=1.0, size=[2, 2]).astype('float32') + [res] = exe.run(main_program, feed={"X": init_data}, fetch_list=[out]) + print('-------- step', step, ' --------') + print(res) + """ + + def __init__(self, + startup_program, + main_program, + num_mp=1, + num_pp=1, + micro_batch_size=1, + beam_size=1, + init_comm=True, + role_maker=None): + + assert isinstance(startup_program, Program) + assert isinstance(main_program, Program) + + self._device = None + if core.is_compiled_with_npu(): + self._device = "npu" + elif core.is_compiled_with_cuda(): + self._device = "gpu" + assert self._device, "Only gpu and npu are supported." + assert not _non_static_mode(), "Only static mode is supported." + + op_maker = core.op_proto_and_checker_maker + self._op_role = op_maker.OpRole + self._op_role_key = op_maker.kOpRoleAttrName() + self._op_device_key = op_maker.kOpDeviceAttrName() + + self._param_device_map = dict() + + self._pipeline_pair = [] + self._pipeline_pair_in_while = [] + self._pp_ring_map = dict() + self.ring_id = 20 # Just a magic number + + self.micro_batch_size = micro_batch_size + self.beam_size = beam_size + self.init_comm = init_comm + + self._output_var_to_op = None + self._input_var_to_op = None + self._main_program = main_program + self._startup_program = startup_program + + if role_maker is None: + self.role_maker = fleet.base.role_maker.PaddleCloudRoleMaker( + is_collective=True) + else: + if isinstance(role_maker, fleet.base.role_maker.RoleMakerBase): + assert role_maker._is_collective == True + self.role_maker = role_maker + + # communication_group info + self.mp_ring_id = 0 + self.global_ring_id = 1 + + self.endpoints = self.role_maker._get_trainer_endpoints() + self.current_endpoint = self.endpoints[self.role_maker._worker_index()] + self.rank = self.role_maker._worker_index() + self.nranks = self.role_maker._worker_num() + assert num_mp * num_pp == self.nranks + self.num_pp = num_pp + self.num_mp = num_mp + + # global ring info + self.global_endpoints = self.endpoints + self.global_rank = self.rank + self.global_nranks = self.nranks + + arr = np.arange(0, self.num_pp * self.num_mp).reshape( + [self.num_pp, self.num_mp]) + ipp, imp = np.where(arr == self.rank) + ipp = ipp[0] + imp = imp[0] + self.mp_group = arr[ipp, :] + self.pp_group = arr[:, imp] + + self._stage = ipp + + def _init_communication_group(self): + dev_ids = [] + for pair in self._pipeline_pair: + prev_id, cur_id = pair + if prev_id not in dev_ids: + dev_ids.append(prev_id) + if cur_id not in dev_ids: + dev_ids.append(cur_id) + num_pp = len(dev_ids) + num_pp = max(1, num_pp) + assert num_pp == self.num_pp, 'num_pp: {}, self.num_pp: {}'.format( + num_pp, self.num_pp) + + collective_helper = fleet.meta_optimizers.common.CollectiveHelper( + self.role_maker, wait_port=False) + + # Create global rings + collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + self.global_endpoints, + self.global_rank, + self.global_ring_id, True, + self.global_ring_id, True) + + # Create mp rings + if self.num_mp > 1: + mp_endpoints = [self.endpoints[mp_idx] for mp_idx in self.mp_group] + mp_rank = [ + idx for idx, mp_idx in enumerate(self.mp_group) + if mp_idx == self.rank + ][0] + collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + mp_endpoints, mp_rank, + self.mp_ring_id, True, + self.global_ring_id, True) + + # Create pipeline rings + if self.num_pp > 1: + for pair in self._pipeline_pair: + pair_key = pair[0] * 1000 + pair[1] + ring_id = self._pp_ring_map[pair_key] + + first_node = self.pp_group[pair[0]] + second_node = self.pp_group[pair[1]] + if self.rank != first_node and self.rank != second_node: + collective_helper._init_communicator( + self._startup_program, None, None, None, None, False, + self.global_ring_id, True) + continue + + pipeline_endpoints = [ + self.endpoints[first_node], self.endpoints[second_node] + ] + pipeline_rank = 0 if self.rank == first_node else 1 + collective_helper._init_communicator(self._startup_program, + self.current_endpoint, + pipeline_endpoints, + pipeline_rank, ring_id, + False, self.global_ring_id, + True) + + def _get_input_output_info(self, block): + ''' + Get info of op input and output. + ''' + # A map from output var to op which generate it. + output_var_to_op = defaultdict(list) + # A map from var to op which takes it as input. + input_var_to_op = defaultdict(list) + + for index, op in enumerate(block.ops): + for var_name in op.input_arg_names: + input_var_to_op[var_name].append([op, index]) + for var_name in op.output_arg_names: + output_var_to_op[var_name].append([op, index]) + + return output_var_to_op, input_var_to_op + + def _update_param_device_map(self): + """ + Get the device info for parameters. + """ + params = [param.name for param in self._main_program.all_parameters()] + for each_block in self._main_program.blocks: + for op in each_block.ops: + for var_name in op.input_arg_names: + if not var_name in params or var_name in self._param_device_map: + continue + device = op.attr(self._op_device_key) + + self._param_device_map[var_name] = device + + def _split_program(self, program, stage, block_idx): + """ + Split a program and get the one with the given pipeline stage. + + Args: + stage (int): pipeline stage + block_idx (int): block index + + Returns: + used_var_names (set): used var names in block_idx block + """ + + used_var_names = set() + block = program.block(block_idx) + op_idx = 0 + for op in list(block.ops): + op_stage = op.attr(self._op_device_key).split(':')[1] + # Copy ops whose op_device set to "gpu:all" to all sections. + if op_stage == "all" or int(op_stage) == stage: + op_idx += 1 + if op.type == "while": + sub_block_id = int(op.attr('sub_block').id) + sub_used_var_names = self._split_program( + program, stage, sub_block_id) + + used_var_names.update(sub_used_var_names) + + input_idxs = [] + input_arg_names = op.input("X") + for i, name in enumerate(input_arg_names): + if name not in sub_used_var_names: + input_idxs.append(i) + if len(input_idxs) > 0: + for i in reversed(input_idxs): + input_arg_names.pop(i) + op.desc.set_input("X", input_arg_names) + + output_idxs = [] + output_arg_names = op.output("Out") + for i, name in enumerate(output_arg_names): + if name not in sub_used_var_names: + output_idxs.append(i) + if len(output_idxs) > 0: + for i in reversed(output_idxs): + output_arg_names.pop(i) + op.desc.set_output("Out", output_arg_names) + + for var_name in op.input_arg_names + op.output_arg_names: + used_var_names.add(var_name) + else: + block._remove_op(op_idx) + + for var_name in list(block.vars.keys()): + if not var_name in used_var_names: + block._remove_var(var_name) + + return used_var_names + + +# def _find_post_op(self, index, var_name): +# """ +# Find the post op that has variable named var_name as input. +# """ +# # bugfix for uniform hybrid parallelism +# if '.cast_fp32' in var_name: +# var_name = var_name.replace('.cast_fp32', '') +# if '.cast_fp16' in var_name: +# var_name = var_name.replace('.cast_fp16', '') + +# post_ops = self._input_var_to_op[var_name] +# if post_ops == None: return None +# result_op = None +# for post_op, post_idx in reversed(post_ops): +# if post_idx > index: +# result_op = post_op +# break +# return result_op + + def _find_prev_op(self, index, var_name): + """ + Find the previous op of op with index that outputs + variable named var_name. + """ + prev_ops = self._output_var_to_op[var_name] + if prev_ops == None: return None + result_op = None + for prev_op, prev_idx in reversed(prev_ops): + if prev_idx < index: + result_op = prev_op + break + return result_op + + def _add_op_device_attr(self, block): + """ + Add op_device attrribute for ops in block that have + not that attribute set. + + Args: + block (Block): the block to process. + """ + assert isinstance(block, Block) + + # Ops should be copied to all pipeline stages. + device_all_ops = [ + "create_py_reader", + "read", + "create_double_buffer_reader", + "while", + ] + + for op in block.ops: + if op.type in device_all_ops: + # We use "gpu:all" to represent an op should be put on all + # pipeline stages, such as read ops. Note that: "gpu:all" + # is only used by pipeline as an indicator. + op._set_attr(self._op_device_key, self._device + ":all") + if op.type == "while": + sub_block_id = op.attr('sub_block').id + sub_block = block.program.block(sub_block_id) + self._add_op_device_attr(sub_block) + + def _check_validation(self, block): + """ + Check whether ops in a block have both the op_device and the + op_role attributes set. + """ + assert isinstance(block, Block) + + pre_stage_id = None + for op in block.ops: + assert op.has_attr(self._op_role_key), ("{} has no {} set .".format( + op.type, self._op_role_key)) + op_role = op.attr(self._op_role_key) + assert op_role == int(self._op_role.Forward), ( + "Only forward is supported for inference.") + if not op._has_kernel(op.type): + assert op.type in [ + "while", "conditional_block" + ], ("The only supported op without kernel is while.") + sub_block_id = op.attr('sub_block').id + sub_block = block.program.block(sub_block_id) + self._check_validation(sub_block) + assert op.has_attr( + self._op_device_key), ("{} has no {} set.".format( + op.type, self._op_device_key)) + + device = op.attr(self._op_device_key) + assert device, ("{} has no {} set.".format(op.type, + self._op_device_key)) + if device.split(':')[1] == "all": continue + + dev_type = device.split(':')[0] + assert dev_type == self._device + stage_id = int(device.split(':')[1]) + pre_stage_id = stage_id + + def _insert_sendrecv_ops_for_boundaries(self, block, is_while_block): + """ + Insert a pair of send and recv ops for every two + consecutive ops on different devices. + """ + # A map from var to device where op takes it as input, + # avoiding multiple send and recv ops. + input_var_to_device = dict() + + extra_index_info = { + 'index': 0, + } + + for index, op in enumerate(list(block.ops)): + cur_device = op.attr(self._op_device_key) + if cur_device.split(':')[-1] == "all": continue + for var_name in op.input_arg_names: + if not block.has_var(var_name) and block._find_var_recursive( + var_name): + continue + var = block.var(var_name) + # skip data var + if var.is_data: continue + prev_device = None + generate_ops = self._output_var_to_op.get(var_name) + if generate_ops is None: + if var_name not in self._param_device_map: + continue + prev_device = self._param_device_map[var_name] + + prev_op = self._find_prev_op(index, var_name) + + if not prev_device: + prev_device = prev_op.attr(self._op_device_key) \ + if prev_op else None + + if prev_device is None or prev_device.split(":")[-1] == "all": + continue + + if prev_device == cur_device: continue + + if var_name not in input_var_to_device: + input_var_to_device[var_name] = [] + if (cur_device, prev_device) in input_var_to_device[var_name]: + continue + + assert self._device == cur_device.split( + ':')[0], "More than one device type found." + device_type = cur_device.split(':')[0] + ':' + + def _insert_send_recv(cur_id, prev_id): + assert cur_id > prev_id + cur_dev = device_type + str(cur_id) + prev_dev = device_type + str(prev_id) + if (cur_dev, prev_dev) in input_var_to_device[var_name]: + return + + if cur_id - prev_id > 1: + _insert_send_recv(cur_id - 1, prev_id) + _insert_send_recv(cur_id, cur_id - 1) + input_var_to_device[var_name].append( + (cur_dev, prev_dev)) + return + + assert cur_id - prev_id == 1 + input_var_to_device[var_name].append((cur_dev, prev_dev)) + + op_role = op.attr(self._op_role_key) + var = block.vars[var_name] + pair = (prev_id, cur_id) + if is_while_block and pair not in self._pipeline_pair_in_while: + self._pipeline_pair_in_while.append(pair) + + # 1000 is just a magic number + pair_key = prev_id * 1000 + cur_id + if pair not in self._pipeline_pair: + self._pipeline_pair.append(pair) + self._pp_ring_map[pair_key] = self.ring_id + ring_id = self.ring_id + self.ring_id += 1 + else: + ring_id = self._pp_ring_map[pair_key] + + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='send_v2', + inputs={'X': var}, + attrs={ + self._op_device_key: prev_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'peer': 1, + 'ring_id': ring_id + }) + extra_index_info['index'] += 1 + var_shape = list(var.shape) + if var_shape[0] < 0: + if is_while_block: + var_shape[ + 0] = self.micro_batch_size * self.beam_size + else: + var_shape[0] = self.micro_batch_size + + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='recv_v2', + outputs={'Out': [var]}, + attrs={ + 'out_shape': var_shape, + 'dtype': var.dtype, + self._op_device_key: cur_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'peer': 0, + 'ring_id': ring_id + }) + extra_index_info['index'] += 1 + + _insert_send_recv(int(cur_device.split(':')[1]), + int(prev_device.split(':')[1])) + block._sync_with_cpp() + + def _insert_sendrecv_ops_in_while_block( + self, block, sync_in_while_lastpp2firstpp_var_names, + sync_in_while_var_names, stage): + dev_ids = [] + for pair in self._pipeline_pair_in_while: + prev_id, cur_id = pair + if prev_id not in dev_ids: + dev_ids.append(prev_id) + if cur_id not in dev_ids: + dev_ids.append(cur_id) + + if len(dev_ids) == 0: + return + + first_id = min(dev_ids) + last_id = max(dev_ids) + + assert len(block.ops) > 2, "It must have more than 2 ops in while sub block, " \ + "layers.assign(layers.cast(cond_int, dtype='bool'), cond) must at end of while block, " \ + "because nccl cannot send bool dtype var" + index = len(block.ops) - 2 + + for prev_id in dev_ids: + if prev_id == cur_id: continue + assert cur_id > prev_id + + pair = (prev_id, cur_id) + # 1000 is just a magic number + pair_key = prev_id * 1000 + cur_id + if pair not in self._pipeline_pair: + self._pipeline_pair.append(pair) + self._pp_ring_map[pair_key] = self.ring_id + ring_id = self.ring_id + self.ring_id += 1 + else: + ring_id = self._pp_ring_map[pair_key] + + if cur_id == last_id and prev_id == first_id: + var_names = sync_in_while_lastpp2firstpp_var_names + sync_in_while_var_names + else: + var_names = sync_in_while_var_names + + for var_name in var_names: + var = block._var_recursive(var_name) + if stage == cur_id: + block._insert_op_without_sync( + index=index, + type='send_v2', + inputs={'X': var}, + attrs={ + self._op_device_key: + self._device + ':' + str(cur_id), + self._op_role_key: int(self._op_role.Forward), + 'use_calc_stream': True, + 'peer': 0, + 'ring_id': ring_id + }) + else: + var_shape = list(var.shape) + var_shape[0] = self.micro_batch_size if var_shape[ + 0] < 0 else var_shape[0] + block._insert_op_without_sync( + index=index, + type='recv_v2', + outputs={'Out': [var]}, + attrs={ + 'out_shape': var_shape, + 'dtype': var.dtype, + self._op_device_key: + self._device + ':' + str(prev_id), + self._op_role_key: int(self._op_role.Forward), + 'use_calc_stream': True, + 'peer': 1, + 'ring_id': ring_id + }) + index += 1 + block._sync_with_cpp() + + def _get_while_block(self): + """ + Get the while sub-block. + """ + main_block = self._main_program.global_block() + num_while = 0 + sub_block_id = None + for op in main_block.ops: + assert num_while < 2, "More than one while op found." + if op.type == 'while': + sub_block_id = op.attr('sub_block').id + num_while += 1 + if sub_block_id: return op, self._main_program.block(sub_block_id) + return None, None + + def gen_infer_program(self, + sync_in_while_lastpp2firstpp_var_names=None, + sync_in_while_var_names=None, + debug=False): + """ + Generate inference program. + Params: + sync_in_while_lastpp2firstpp_var_names (list(str)): the vars in the last pipeline + that need to send var to first pipeline and exclude bool dtype var + sync_in_while_var_names (list(str)): the vars sync among all pipeline in while block + e.g cond. Note that cond cannot be bool dtype. + debug (bool): the flag indicate debug + """ + main_block = self._main_program.global_block() + startup_block = self._startup_program.global_block() + + if debug: + with open(f'main_program.txt', 'w') as f: + f.write(str(self._main_program)) + with open(f'startup_program.txt', 'w') as f: + f.write(str(self._startup_program)) + + # step1: add op_device attribute for all ops + self._add_op_device_attr(startup_block) + self._check_validation(startup_block) + self._add_op_device_attr(main_block) + self._check_validation(main_block) + + # step2: add send/recv ops + self._update_param_device_map() + # step2.1: add send/recv for main_block + out_var_to_op, in_var_to_op = self._get_input_output_info(main_block) + self._output_var_to_op = out_var_to_op + self._input_var_to_op = in_var_to_op + self._insert_sendrecv_ops_for_boundaries(main_block, False) + + # step2.2: add send/recv for while_block + while_op, while_block = self._get_while_block() + if while_block: + out_var_to_op, in_var_to_op = self._get_input_output_info( + while_block) + self._output_var_to_op = out_var_to_op + self._input_var_to_op = in_var_to_op + + self._insert_sendrecv_ops_for_boundaries(while_block, True) + + self._insert_sendrecv_ops_in_while_block( + while_block, sync_in_while_lastpp2firstpp_var_names, + sync_in_while_var_names, self._stage) + + # step3: split programs + self._split_program(self._startup_program, self._stage, 0) + self._split_program(self._main_program, self._stage, 0) + + if debug: + with open(f'main_program.txt.{self.rank}', 'w') as f: + f.write(str(self._main_program)) + with open(f'startup_program.txt.{self.rank}', 'w') as f: + f.write(str(self._startup_program)) + + if self.init_comm: + self._init_communication_group() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7e527eced3f0419f5601efa2138b0f51917194c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/hybrid_parallel_util.py @@ -0,0 +1,260 @@ +# Copyright (c) 2021 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. +import os +import six +import numpy as np + +from paddle import framework +import paddle +from paddle.fluid import core +from paddle.fluid.dygraph.parallel import ( + _split_tensors, + sync_params_buffers, + build_groups, +) +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph +from collections import OrderedDict +from .log_util import logger + +__all__ = [] + + +def _apply_collective_grads(parameters, comm_group, bucket_size, scale=None): + grad_var_set = set() + grad_vars = [] + sparse_grad_vars = [] + + for param in parameters: + if param.trainable and (param._grad_ivar() is not None): + g_var = param._grad_ivar() + assert ( + not g_var._is_sparse() + ), "Now, it doesn't support sparse parameters" + grad_vars.append(g_var) + assert g_var not in grad_var_set + grad_var_set.add(g_var) + + coalesced_grads_and_vars = build_groups(grad_vars, bucket_size) + + nranks = ( + paddle.distributed.get_world_size() + if comm_group is None + else comm_group.nranks + ) + + scale = nranks if scale is None else 1.0 / scale + scale = None if scale == 1.0 else scale + + for coalesced_grad, _, _ in coalesced_grads_and_vars: + # need to div nranks + if scale is not None: + div_factor = paddle.to_tensor(scale, dtype=coalesced_grad.dtype) + paddle.fluid.framework._dygraph_tracer().trace_op( + type="elementwise_div", + inputs={'X': coalesced_grad, 'Y': div_factor}, + outputs={'Out': coalesced_grad}, + attrs={'axis': -1}, + ) + paddle.distributed.all_reduce(coalesced_grad, group=comm_group) + + _split_tensors(coalesced_grads_and_vars) + + +def _apply_collective_grads_eager( + parameters, comm_group, bucket_size, scale=None +): + grad_var_set = set() + grad_vars = [] + + for param in parameters: + if param.trainable and (param._grad_ivar() is not None): + g_var = param._grad_ivar() + assert ( + not g_var.is_sparse() + ), "Now, it doesn't support sparse parameters" + grad_vars.append(g_var) + assert g_var not in grad_var_set + grad_var_set.add(g_var) + + coalesced_grads_and_vars = build_groups(grad_vars, bucket_size) + + nranks = ( + paddle.distributed.get_world_size() + if comm_group is None + else comm_group.nranks + ) + + scale = 1.0 / nranks if scale is None else scale + scale = None if scale == 1.0 else scale + + for coalesced_grad, _, _ in coalesced_grads_and_vars: + # need to div nranks + if scale is not None: + coalesced_grad.scale_(scale) + paddle.distributed.all_reduce(coalesced_grad, group=comm_group) + + _split_tensors(coalesced_grads_and_vars) + + +def _broadcast_data_help(data, shape, dtype, hcg): + model_parallel_group = hcg.get_model_parallel_group() + src_rank = hcg.get_model_parallel_group_src_rank() + mp_rank = hcg.get_model_parallel_rank() + + shape_gpu = paddle.to_tensor(shape, dtype="int32") + paddle.distributed.broadcast( + shape_gpu, src=src_rank, group=model_parallel_group, sync_op=True + ) + + if mp_rank != 0: + input_data = paddle.zeros(shape_gpu, dtype=dtype) + else: + input_data = data + + paddle.distributed.broadcast( + input_data, src=src_rank, group=model_parallel_group, sync_op=True + ) + + if mp_rank != 0: + if in_dygraph_mode(): + data._clear_data() + input_data._share_buffer_to(data) + else: + data.value().get_tensor()._clear() + data.value().get_tensor()._share_data_with( + input_data.value().get_tensor() + ) + + +def broadcast_input_data(hcg, *inputs, **kwargs): + cur_device = paddle.get_device() + for v in inputs: + if isinstance(v, (core.VarBase, core.eager.Tensor)): + with framework.no_grad(): + if ( + "gpu" in cur_device + and in_dygraph_mode() + and not v.place.is_gpu_place() + ): + v_gpu = v.cuda(int(cur_device.split(":")[1])) + v._clear_data() + v_gpu._share_buffer_to(v) + _broadcast_data_help(v, v.shape, v.dtype, hcg) + else: + logger.error("it doesn't support data type {}".format(type(v))) + + for k, v in kwargs.items(): + if isinstance(v, (core.VarBase, core.eager.Tensor)): + with framework.no_grad(): + if ( + "gpu" in cur_device + and in_dygraph_mode() + and not v.place.is_gpu_place() + ): + v_gpu = v.cuda(int(cur_device.split(":")[1])) + v._clear_data() + v_gpu._share_buffer_to(v) + _broadcast_data_help(v, v.shape, v.dtype, hcg) + kwargs[k] = v + else: + logger.error("it doesn't support data type {}".format(type(v))) + return inputs, kwargs + + +def broadcast_mp_parameters(model, hcg): + model_parallel_group = hcg.get_model_parallel_group() + src_rank = hcg.get_model_parallel_group_src_rank() + sync_params_buffers( + model, model_parallel_group, src_rank, is_model_parallel=True + ) + + +def broadcast_dp_parameters(model, hcg): + data_parallel_group = hcg.get_data_parallel_group() + src_rank = hcg.get_data_parallel_group_src_rank() + sync_params_buffers( + model, data_parallel_group, src_rank, is_model_parallel=False + ) + + +def fused_allreduce_gradients_with_group( + parameter_list, group, bucket_size=128 * 1024 * 1024, scale=None +): + apply_func = ( + _apply_collective_grads_eager + if in_dygraph_mode() + else _apply_collective_grads + ) + with framework.no_grad(): + apply_func(parameter_list, group, bucket_size, scale) + + +def fused_allreduce_gradients(parameter_list, hcg): + data_parallel_group = None if hcg is None else hcg.get_data_parallel_group() + logger.debug("dp start fuse allreduce gradients") + fused_allreduce_gradients_with_group(parameter_list, data_parallel_group) + + +def sharding_reduce_gradients(parameter_list, hcg): + # TODO allreduce --> reduce + # TODO merge grad / nrank with dp + logger.debug("sharding start gradients sync") + with framework.no_grad(): + + sharding_nrank = hcg.get_sharding_parallel_group().nranks + for param in parameter_list: + if param.trainable and (param._grad_ivar() is not None): + if in_dygraph_mode(): + param.grad.scale_(1.0 / sharding_nrank) + paddle.distributed.all_reduce( + param.grad, + group=hcg.get_sharding_parallel_group(), + sync_op=True, + ) + + elif _in_legacy_dygraph(): + g_var = param._grad_ivar() + # need use trace_op to allreduce + # paddle.distributed.all_reduce( + # g_var, group=hcg.get_sharding_parallel_group(), use_calc_stream=True) + paddle.fluid.framework._dygraph_tracer().trace_op( + type="c_allreduce_sum", + inputs={'X': g_var}, + outputs={'Out': g_var}, + attrs={ + 'ring_id': hcg.get_sharding_parallel_group().id, + 'use_calc_stream': True, + }, + ) + + # grad / sharding_rank + div_factor = paddle.to_tensor( + sharding_nrank, dtype=g_var.dtype + ) + paddle.fluid.framework._dygraph_tracer().trace_op( + type="elementwise_div", + inputs={'X': g_var, 'Y': div_factor}, + outputs={'Out': g_var}, + attrs={'axis': -1}, + ) + + +def broadcast_sharding_parameters(model, hcg): + # TODO TO save memory, use un-fused broadcast to avoid potentional OOM + logger.debug("sharding start init parameters sync") + sharding_parallel_group = hcg.get_sharding_parallel_group() + src_rank = hcg.get_sharding_parallel_group_src_rank() + sync_params_buffers( + model, sharding_parallel_group, src_rank, is_model_parallel=False + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/internal_storage.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/internal_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..421111d5b88944c699a3130d273a9c2e2c95d882 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/internal_storage.py @@ -0,0 +1,332 @@ +# Copyright (c) 2021 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. + +# The file has been adapted from fairscale file: +# https://github.com/facebookresearch/fairscale/blob/main/fairscale/nn/misc/param_bucket.py +# Git commit hash: 8acbec718f3c70a6b9785470bb9e05cd84fc3f8e +# We retain the following license from the original files: + +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import os +import time +import numpy as np + +import paddle +import paddle.fluid as fluid +from paddle.fluid import core +from ..meta_parallel.sharding.sharding_utils import Type, device_guard + + +class InternalStorage: + """ + This is a basic class, which is responsible for consolidating the basic storage tensor. + + """ + + # Support integration parameter tensor + def __init__(self, size, dtype, device, convert_cpu=False): + self._params = [] + self._param_ids = [] + self._fill = 0 + self._device = device + self._dtype = dtype + + # The actual flat tensor + size = [size] if isinstance(size, int) else size + if convert_cpu: + value = np.zeros( + size, + dtype=np.float16) if Type.fp16.value == dtype else np.zeros( + size, dtype=np.float32) + self.buffer = core.VarBase(value=value, place=core.CPUPlace()) + else: + self.buffer = paddle.zeros(size, dtype=dtype) + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + assert self.buffer is not None, "Cannot move a collapsed bucket, please rebuild it" + assert (dtype == Type.fp32.value + or Type.fp16.value), "Conversion type is not supported now" + + dev_id = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + + if self._device != device: + tmp_buffer = self.buffer.cuda( + dev_id) if device == "gpu" else self.buffer.cpu() + for param in self._params: + param.clear_gradient(False) + param._gradient_set_empty(False) + self.buffer.value().get_tensor()._clear() + self.buffer = tmp_buffer + self._device = device + + if dtype is not None: + self.buffer = self.buffer.cast(dtype=dtype) + self._dtype = dtype + + +class ParamStorage(InternalStorage): + """ + This is a basic class to simplify the handling of parameter InternalStorages. + """ + + def __init__(self, size, dtype, device): + super().__init__(size, dtype, device, convert_cpu=True) + self.param2align = None + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + + super().to(device, dtype) + + if keep_alignment: + self._array_params() + + @fluid.dygraph.no_grad + def add_rank_params(self, trainable_params, param2align, convert_gpu=True): + """ + Add new parameters to the InternalStorage. Params becomes a view of this InternalStorage buffer. + """ + + assert all([ + id(param) not in self._param_ids for param in trainable_params + ]), "The same param cannot be checked in twice" + assert self.buffer is not None + + self.param2align = param2align + + cpu_param_shape = list() + for param in trainable_params: + p_shape = self._add_param_as_view(param, param2align[param.name], + convert_gpu) + cpu_param_shape.append(p_shape) + + if convert_gpu: + # buffer convert from cpu to cuda + dev_id = int(paddle.get_device().split(":")[1]) + self.buffer = self.buffer.cuda(dev_id) + + self._fill = 0 + + for idx, param in enumerate(trainable_params): + self._convert_buffer(param, cpu_param_shape[idx], + param2align[param.name]) + self._params.append(param) + self._param_ids.append(id(param)) + + @fluid.dygraph.no_grad + def _add_param_as_view(self, param, align, convert_gpu=True): + + assert ( + param.dtype == self.buffer.dtype + ), "Different types for the InternalStorage and the param, cannot proceed: {} - {}".format( + param.dtype, self.buffer.dtype) + + var_end = self._fill + np.prod(param.shape) + offset = var_end + align + assert offset <= np.prod(self.buffer.shape) + + p_shape = param.shape + + origin_state = param.stop_gradient + param.stop_gradient = True + param.flatten_() + param.stop_gradient = origin_state + + # Copy the current param value + dev_id = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + with device_guard(dev_id, "cpu"): + tmp_var = core.VarBase( + tensor=self.buffer._slice(self._fill, var_end)) + if convert_gpu: + param_cpu = param.cpu() + param.value().get_tensor()._clear() + tmp_var.set_value(param_cpu) + else: + tmp_var.set_value(param) + + self._fill = offset + return p_shape + + @fluid.dygraph.no_grad + def _convert_buffer(self, param, p_shape, align): + + var_end = self._fill + np.prod(p_shape) + offset = var_end + align + assert offset <= np.prod(self.buffer.shape) + + # Convert the param value + tmp_tensor = self.buffer._slice(self._fill, var_end) + param.value().get_tensor()._share_data_with(tmp_tensor) + param.value().get_tensor()._set_dims(p_shape) + + self._fill = offset + + @fluid.dygraph.no_grad + def _array_params(self): + """ + Given the parameters which have been registered previously, rebuild the whole InternalStorage. + """ + assert len(self._params) > 0 + assert self.param2align is not None + + self._fill = 0 + for p in self._params: + self._convert_buffer(p, p.shape, self.param2align[p.name]) # modify + + +class GradStorage(InternalStorage): + """ + This is a basic class to simplify the handling of gradient InternalStorages + """ + + def __init__(self, + size, + dtype, + device, + destination, + parm2align, + convert_cpu=False): + if isinstance(size, np.int64): + size = size.tolist() + super().__init__(size, dtype, device, convert_cpu) + + self._max_size = size + self._release = False + + self.params_checked_in = 0 + self.destination = destination + self._parm2align = parm2align + self.sent = False + + def reset_checked_in(self): + """ Reset the counter of the parameter grads which have been checked in + """ + self.params_checked_in = 0 + self.sent = False + + @property + def all_checked_in(self): + """ Judge all the expected gradient check-in happened """ + return len(self._params) == self.params_checked_in + + def can_add_grad_view(self, param, align): + """ Is there enough InternalStorage to add this parameter gradient, and whether this param have already checked in. + """ + return self._fill + np.prod( + param.shape) + align <= self._max_size and id( + param) not in self._param_ids + + def to(self, device, dtype=None, keep_alignment=True): + """ + Move the underlying buffer + """ + if self._release: + self.rebuild() + + super().to(device, dtype) + + if keep_alignment: + self._array_grads() + + @fluid.dygraph.no_grad + def add_grad(self, param, align): + """ + Add a new parameter gradient to the InternalStorage. Param.grad becomes a view of this InternalStorage buffer. + """ + + assert id( + param + ) not in self._param_ids, "The same gradients cannot be checked in twice" + + self._add_grad_as_view(param, align) + self._params.append(param) + self._param_ids.append(id(param)) + + @fluid.dygraph.no_grad + def manumal_relase(self): + """ + Release the buffer from InternalStorage. The InternalStorage will need to be rebuilt before use. + """ + if not self._release: + for p in self._params: + if p.grad is not None: + p.clear_gradient(False) + p._gradient_set_empty(False) + + self.buffer = None + self._fill = 0 + self.params_checked_in = 0 + self._release = True + + @fluid.dygraph.no_grad + def rebuild(self): + """ + Given the parameter gradients which have been registered previously, rebuild the whole InternalStorage. + """ + + if self._release: + self.buffer = paddle.zeros([self._max_size], dtype=self._dtype) + + for p in self._params: + self._add_grad_as_view(p, self._parm2align[p.name]) + + self._release = False + + @fluid.dygraph.no_grad + def _array_grads(self): + """ + Given the parameters gradients which have been registered previously, rebuild the whole InternalStorage. + """ + if len(self._params) > 0: + self._fill = 0 + for p in self._params: + self._add_grad_as_view(p, self._parm2align[p.name]) + + @fluid.dygraph.no_grad + def _add_grad_as_view(self, param, align): + assert np.prod( + self.buffer.shape + ) > 0, "Cannot add a gradient to a released InternalStorage, please rebuild" + assert param.dtype == self.buffer.dtype + + grad_end = self._fill + np.prod(param.shape) + offset = grad_end + align + assert offset <= np.prod(self.buffer.shape) + + # Copy the current grad value to InternalStorage + dev_id = 0 if paddle.get_device() == "cpu" else int( + paddle.get_device().split(":")[1]) + if self._device == "cpu": + with device_guard(dev_id, self._device): + tmp_var = core.VarBase(self.buffer._slice(self._fill, grad_end)) + param._copy_gradient_from(tmp_var) + tmp_var.value().get_tensor()._clear() + + elif self._device == "gpu": + tmp_var = core.VarBase(self.buffer._slice(self._fill, grad_end)) + param._copy_gradient_from(tmp_var) + tmp_var.value().get_tensor()._clear() + + self._fill = offset diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/log_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/log_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6118d0264478b1d21a084334267b2bd31b08e3e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/log_util.py @@ -0,0 +1,74 @@ +# Copyright (c) 2021 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. + +import logging +import sys + +from paddle.distributed.utils.log_utils import get_logger + +logger = get_logger("INFO", __name__) + + +def set_log_level(level): + """ + Set log level + + Args: + level (str|int): a specified level + + Example 1: + import paddle + import paddle.distributed.fleet as fleet + fleet.init() + fleet.setLogLevel("DEBUG") + + Example 2: + import paddle + import paddle.distributed.fleet as fleet + fleet.init() + fleet.setLogLevel(1) + + """ + assert isinstance(level, (str, int)), "level's type must be str or int" + if isinstance(level, int): + logger.setLevel(level) + else: + logger.setLevel(level.upper()) + + +def get_log_level_code(): + """ + Return current log level code + """ + return logger.getEffectiveLevel() + + +def get_log_level_name(): + """ + Return current log level name + """ + return logging.getLevelName(get_log_level_code()) + + +def layer_to_str(base, *args, **kwargs): + name = base + "(" + if args: + name += ", ".join(str(arg) for arg in args) + if kwargs: + name += ", " + if kwargs: + name += ", ".join("{}={}".format(key, str(value)) + for key, value in kwargs.items()) + name += ")" + return name diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/ps_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/ps_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0e141d66c1a1797269edc8c94be080c0fa4ba63e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/fleet/utils/ps_util.py @@ -0,0 +1,318 @@ +# 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. +"""Parameter Server utils""" + +import numpy as np +import os +import paddle +import warnings + +__all__ = [] + + +class DistributedInfer: + """ + Utility class for distributed infer of PaddlePaddle. + """ + + def __init__(self, main_program=None, startup_program=None): + if main_program: + self.origin_main_program = main_program.clone() + else: + self.origin_main_program = paddle.static.default_main_program( + ).clone() + + if startup_program: + self.origin_startup_program = startup_program + else: + self.origin_startup_program = paddle.static.default_startup_program( + ) + self.sparse_table_maps = None + + def init_distributed_infer_env(self, + exe, + loss, + role_maker=None, + dirname=None): + import paddle.distributed.fleet as fleet + + if fleet.fleet._runtime_handle is None: + fleet.init(role_maker=role_maker) + + fake_optimizer = paddle.optimizer.SGD() + strategy = fleet.DistributedStrategy() + strategy.a_sync = True + optimizer = fleet.distributed_optimizer(fake_optimizer, + strategy=strategy) + optimizer.minimize(loss, + startup_program=self.origin_startup_program) + + if fleet.is_server(): + fleet.init_server(dirname=dirname) + fleet.run_server() + else: + exe.run(paddle.static.default_startup_program()) + fleet.init_worker() + self._init_dense_params(exe, dirname) + global_startup_program = paddle.static.default_startup_program() + global_startup_program = self.origin_startup_program + global_main_program = paddle.static.default_main_program() + global_main_program = self.origin_main_program + + def _get_sparse_table_map(self): + import paddle.distributed.fleet as fleet + + if self.sparse_table_maps is None: + self.sparse_table_maps = {} + send_ctx = fleet.fleet._runtime_handle._send_ctx + for gradname, ctx in send_ctx.items(): + if ctx.is_sparse: + param = gradname.strip("@GRAD") + self.sparse_table_maps[param] = ctx.table_id() + else: + continue + return self.sparse_table_maps + + def _init_dense_params(self, exe=None, dirname=None): + import paddle.distributed.fleet as fleet + + sparse_table_maps = self._get_sparse_table_map() + + if dirname is not None and exe is not None: + all_persist_vars = [ + v for v in self.origin_main_program.list_vars() + if paddle.static.io.is_persistable(v) + ] + dense_persist_vars = [(v.name, v) for v in all_persist_vars + if v.name not in sparse_table_maps] + need_load_vars = [ + v[1] for v in dense_persist_vars + if os.path.isfile(os.path.join(dirname, v[0])) + ] + paddle.static.load_vars(exe, + dirname, + main_program=self.origin_main_program, + vars=need_load_vars) + + def get_dist_infer_program(self): + varname2tables = self._get_sparse_table_map() + convert_program = self._convert_program(self.origin_main_program, + varname2tables) + return convert_program + + def _convert_program(self, main_program, varname2tables): + + def distributed_ops_pass(program): + SPARSE_OP_TYPE_DICT = {"lookup_table": "W", "lookup_table_v2": "W"} + + def _get_pull_sparse_ops(_program): + pull_sparse_ops = {} + for op in _program.global_block().ops: + if op.type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0] + ops = pull_sparse_ops.get(param_name, []) + ops.append(op) + pull_sparse_ops[param_name] = ops + return pull_sparse_ops + + def _pull_sparse_fuse(_program, pull_sparse_ops): + + def dag_check_up_and_reorder(program, inputs, outputs): + global_block = program.global_block() + min_output_index = len(global_block.ops) + max_input_index = -1 + input_indexes = [0] * len(global_block.ops) + output_indexes = [0] * len(global_block.ops) + for idx, op in enumerate(global_block.ops): + for i in range(0, len(op.output_names)): + if input_indexes[idx] == 1: + break + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + input_indexes[idx] = 1 + max_input_index = max(max_input_index, idx) + break + + for i in range(0, len(op.input_names)): + if output_indexes[idx] == 1: + break + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + output_indexes[idx] = 1 + min_output_index = min( + min_output_index, idx) + + for i in range(len(global_block.ops)): + if input_indexes[i] == 1 and output_indexes[i] == 1: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops because a op both needs embedding table's output as input and produces ids as the same embedding table's input" + ) + return + + if min_output_index < max_input_index: + move_ops = [] + for i in range(min_output_index + 1, + len(input_indexes)): + if input_indexes[i] == 1: + move_ops.append((global_block.ops[i], i)) + for i, op in enumerate(move_ops): + queue = list() + visited = set() + queue.append(op[1]) + visited.add(op[0]) + start = 0 + while start < len(queue): + pos = queue[start] + op = global_block.ops[pos] + op_inputs = [] + for k in range(0, len(op.input_names)): + ins = op.input(op.input_names[k]) + op_inputs.append(ins) + for j in range(pos - 1, min_output_index - 1, + -1): + op1 = global_block.ops[j] + if op1 in visited: + continue + found = False + for k in range(0, len(op1.output_names)): + outs = op1.output(op1.output_names[k]) + for t in range(len(op_inputs)): + for y in op_inputs[t]: + if y in outs: + found = True + break + if found: + break + if found: + break + if found: + if output_indexes[j] == True: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops" + ) + return + queue.append(j) + visited.add(global_block.ops[j]) + start = start + 1 + + queue.sort() + for index in queue: + desc = global_block.desc._insert_op( + min_output_index) + desc.copy_from(global_block.ops[index].desc) + global_block.desc._remove_op( + index + 1, index + 2) + global_block.ops[index].desc = desc + insert_op = global_block.ops.pop(index) + input_state = input_indexes.pop(index) + output_state = output_indexes.pop(index) + global_block.ops.insert(min_output_index, + insert_op) + input_indexes.insert(min_output_index, + input_state) + output_indexes.insert(min_output_index, + output_state) + min_output_index = min_output_index + 1 + + assert global_block.desc.op_size() == len( + global_block.ops) + for i in range(len(global_block.ops)): + assert global_block.desc.op( + i) == global_block.ops[i].desc + + for param, ops in pull_sparse_ops.items(): + all_ops = program.global_block().ops + + inputs = [ + program.global_block().vars[op.input("Ids")[0]] + for op in ops + ] + + w = program.global_block().vars[ops[0].input("W")[0]] + + if w.name not in varname2tables.keys(): + raise ValueError( + "can not find variable {}, please check your configuration" + .format(w.name)) + + table_id = varname2tables[w.name] + + padding_idx = ops[0].attr("padding_idx") + is_distributed = ops[0].attr("is_distributed") + op_type = ops[0].type + + outputs = [ + program.global_block().vars[op.output("Out")[0]] + for op in ops + ] + + dag_check_up_and_reorder(program, inputs, outputs) + op_idxs = [all_ops.index(op) for op in ops] + + for idx in op_idxs[::-1]: + program.global_block()._remove_op(idx) + + inputs_idxs = [-1] * len(inputs) + outputs_idxs = [len(program.global_block().ops) + 1 + ] * len(outputs) + + for idx, op in enumerate(program.global_block().ops): + for i in range(0, len(op.output_names)): + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + inputs_idxs[in_id] = max( + idx, inputs_idxs[in_id]) + for i in range(0, len(op.input_names)): + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + outputs_idxs[out_id] = min( + idx, outputs_idxs[out_id]) + + if min(outputs_idxs) - max(inputs_idxs) >= 1: + distributed_idx = max(inputs_idxs) + 1 + + program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": inputs, + 'W': w + }, + outputs={"Outputs": outputs}, + attrs={ + "is_distributed": is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "is_test": True, + "lookup_table_version": op_type + }) + else: + raise ValueError( + "something wrong with Fleet, submit a issue is recommended" + ) + + pull_sparse_ops = _get_pull_sparse_ops(program) + warnings.warn( + "lookup_table will be forced to test mode when use DistributedInfer" + ) + _pull_sparse_fuse(program, pull_sparse_ops) + return program + + covert_program = distributed_ops_pass(main_program) + return covert_program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce89fa36b06b25cfc7409c093ea227393ae3111 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2022 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. + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__main__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..52b0ed3a012cca31d4bb342684f2cdaf0d8f698f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/__main__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022 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. + +from .main import launch + +launch() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b067973d3749d726bc11929a8f4453bbca70c9fa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/__init__.py @@ -0,0 +1,97 @@ +# Copyright (c) 2022 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. + +from paddle.distributed.launch import plugins + +from .node import Node +from .status import Status +from .args_envs import parse_args, fetch_envs, env_args_mapping +import six + +import logging + + +class Context(object): + + def __init__(self, enable_plugin=True): + self.args, self.unknown_args = parse_args() + self.envs = fetch_envs() + + self.set_env_in_args() + + self.node = Node() + self.status = Status() + + self.logger = self.get_logger() + + # design for event queue, later + self.events = [] + + if enable_plugin: + self._enable_plugin() + + def print(self): + self.logger.info("----------- Configuration ----------------------") + for arg, value in sorted(six.iteritems(vars(self.args))): + self.logger.info("%s: %s" % (arg, value)) + self.logger.info("--------------------------------------------------") + + def is_legacy_mode(self): + if self.args.legacy: + return True + + if self.args.master: + return False + + if len(self.unknown_args) > 0: + self.logger.warning("Compatible mode enable with args {}".format( + self.unknown_args)) + return True + + return False + + def get_envs(self): + return self.envs.copy() + + def set_envs(self, env={}): + env = {k: v for k, v in env.items() if isinstance(v, str)} + self.envs.update(env) + + def _enable_plugin(self): + for pl in plugins.enabled_plugins: + pl(self) + + def get_logger(self, level=logging.INFO): + logger = logging.getLogger("LAUNCH") + logger.setLevel(self.args.log_level.upper() or level) + formatter = logging.Formatter( + fmt='%(name)s %(levelname)s %(asctime)s %(message)s') + ch = logging.StreamHandler() + ch.setFormatter(formatter) + logger.addHandler(ch) + return logger + + def continous_log(self) -> bool: + if self.args.log_level.upper() in ['DEBUG', 'ERROR']: + return True + else: + return False + + def set_env_in_args(self): + for k, v in env_args_mapping.items(): + if k in self.envs: + print( + f"LAUNCH WARNNING args {v} is override by env {self.envs[k]}" + ) + setattr(self.args, v, self.envs[k]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/args_envs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/args_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..104ad1b789f54b2959b34acfe5bef5be91f52944 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/args_envs.py @@ -0,0 +1,177 @@ +# Copyright (c) 2022 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. + +import os +from argparse import ArgumentParser, REMAINDER + +env_args_mapping = { + 'POD_IP': 'host', + 'PADDLE_MASTER': 'master', + 'PADDLE_DEVICES': 'devices', + 'PADDLE_NNODES': 'nnodes', + 'PADDLE_RUN_MODE': 'run_mode', + 'PADDLE_LOG_LEVEL': 'log_level', + 'PADDLE_NPROC_PER_NODE': 'nproc_per_node', + 'PADDLE_JOB_ID': 'job_id', + 'PADDLE_RANK': 'rank', + 'PADDLE_LOG_DIR': 'log_dir', + 'PADDLE_MAX_RESTART': 'max_restart', + 'PADDLE_ELASTIC_LEVEL': 'elastic_level', + 'PADDLE_ELASTIC_TIMEOUT': 'elastic_timeout', + 'PADDLE_SERVER_NUM': 'server_num', + 'PADDLE_TRAINER_NUM': 'trainer_num', + 'PADDLE_SERVERS_ENDPOINTS': 'servers', + 'PADDLE_TRAINERS_ENDPOINTS': 'trainers', + 'PADDLE_GLOO_PORT': 'gloo_port', + 'PADDLE_WITH_GLOO': 'with_gloo', + 'PADDLE_START_PORT': 'start_port', + 'PADDLE_IPS': 'ips', +} + + +def fetch_envs(): + os.environ.pop('http_proxy', None) + os.environ.pop('https_proxy', None) + + return os.environ.copy() + + +def parse_args(): + parser = ArgumentParser() + + base_group = parser.add_argument_group("Base Parameters") + + base_group.add_argument("--master", + type=str, + default=None, + help="the master/rendezvous server, ip:port") + + base_group.add_argument("--legacy", + type=bool, + default=False, + help="use legacy launch") + + base_group.add_argument("--rank", + type=int, + default=-1, + help="the node rank") + + base_group.add_argument("--log_level", + type=str, + default="INFO", + help="log level. Default INFO") + + base_group.add_argument("--nnodes", + type=str, + default="1", + help="the number of nodes, i.e. pod/node number") + + base_group.add_argument("--nproc_per_node", + type=int, + default=None, + help="the number of processes in a pod") + + base_group.add_argument( + "--log_dir", + type=str, + default="log", + help="the path for each process's log. Default ./log") + base_group.add_argument("--run_mode", + type=str, + default=None, + help="run mode of the job, collective/ps/ps-heter") + + base_group.add_argument("--job_id", + type=str, + default="default", + help="unique id of the job. Default default") + + base_group.add_argument("--devices", + "--gpus", + "--npus", + "--xpus", + type=str, + default=None, + help="accelerate devices. as --gpus,npus,xpus") + + base_group.add_argument("--host", type=str, default=None, help="host ip") + + base_group.add_argument("--ips", + type=str, + default=None, + help="nodes ips, e.g. 10.10.1.1,10.10.1.2") + + base_group.add_argument("--start_port", + type=int, + default=6070, + help="fix port start with") + + base_group.add_argument("training_script", + type=str, + help="the full path of py script," + "followed by arguments for the " + "training script") + + base_group.add_argument('training_script_args', nargs=REMAINDER) + + ps_group = parser.add_argument_group("Parameter-Server Parameters") + # for parameter server + ps_group.add_argument("--servers", + type=str, + default='', + help="servers endpoints full list") + ps_group.add_argument("--trainers", + type=str, + default='', + help="trainers endpoints full list") + + ps_group.add_argument("--trainer_num", + type=int, + default=None, + help="number of trainers") + ps_group.add_argument("--server_num", + type=int, + default=None, + help="number of servers") + ps_group.add_argument("--gloo_port", + type=int, + default=6767, + help="gloo http port") + ps_group.add_argument("--with_gloo", + type=str, + default="1", + help="use gloo or not") + + # parameter elastic mode + elastic_group = parser.add_argument_group("Elastic Parameters") + elastic_group.add_argument("--max_restart", + type=int, + default=3, + help="the times can restart. Default 3") + + elastic_group.add_argument( + "--elastic_level", + type=int, + default=-1, + help= + "elastic level: -1 disable, 0 failed exit, peers hold, 1 internal restart" + ) + + elastic_group.add_argument( + "--elastic_timeout", + type=int, + default=30, + help="seconds to wait before elastic job begin to train") + + return parser.parse_known_args() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/device.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/device.py new file mode 100644 index 0000000000000000000000000000000000000000..14997df24590f80d920f2eb0f85fcd89558e05b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/device.py @@ -0,0 +1,185 @@ +# Copyright (c) 2022 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. + +import os +import paddle.fluid as fluid +from paddle.device import get_available_custom_device + + +class DeviceType: + CPU = 'cpu' + GPU = 'gpu' + XPU = 'xpu' + NPU = 'npu' + MLU = 'mlu' + IPU = 'ipu' + CUSTOM_DEVICE = 'custom_device' + + +class Device(object): + + def __init__(self, dtype=None, memory="", labels=""): + self._dtype = dtype + self._memory = memory + self._labels = labels + + def __str__(self): + return ",".join(self._labels) + + @property + def dtype(self): + return self._dtype + + @property + def count(self): + return len(self._labels) or 1 + + @property + def memory(self): + return self._memory + + @property + def labels(self): + return self._labels + + @labels.setter + def labels(self, lbs): + if isinstance(lbs, str): + self._labels = lbs.split(',') + elif isinstance(lbs, list): + self._labels = lbs + else: + self._labels = [] + + def get_selected_device_key(self): + if self._dtype == DeviceType.CPU: + return 'FLAGS_selected_cpus' + if self._dtype == DeviceType.GPU: + return 'FLAGS_selected_gpus' + if self._dtype == DeviceType.NPU: + return 'FLAGS_selected_npus' + if self._dtype == DeviceType.XPU: + return 'FLAGS_selected_xpus' + if self._dtype == DeviceType.MLU: + return 'FLAGS_selected_mlus' + if self._dtype == DeviceType.IPU: + return 'FLAGS_selected_ipus' + if self._dtype == DeviceType.CUSTOM_DEVICE: + return 'FLAGS_selected_{}s'.format(os.getenv('PADDLE_XCCL_BACKEND')) + return 'FLAGS_selected_devices' + + def get_selected_devices(self, devices=''): + ''' + return the device label/id relative to the visible devices + ''' + if not devices: + return [str(x) for x in range(0, len(self._labels))] + else: + devs = [x.strip() for x in devices.split(',')] + return [str(self._labels.index(d)) for d in devs] + + def get_custom_device_envs(self): + return { + 'PADDLE_DISTRI_BACKEND': 'xccl', + 'PADDLE_XCCL_BACKEND': os.getenv('PADDLE_XCCL_BACKEND'), + } + + @classmethod + def parse_device(self): + dev = Device() + visible_devices = None + if 'PADDLE_XCCL_BACKEND' in os.environ: + dev._dtype = DeviceType.CUSTOM_DEVICE + visible_devices_str = '{}_VISIBLE_DEVICES'.format( + os.getenv('PADDLE_XCCL_BACKEND').upper()) + if visible_devices_str in os.environ: + visible_devices = os.getenv(visible_devices_str) + elif 'CUDA_VISIBLE_DEVICES' in os.environ: + dev._dtype = DeviceType.GPU + visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + elif 'XPU_VISIBLE_DEVICES' in os.environ: + dev._dtype = DeviceType.XPU + visible_devices = os.getenv("XPU_VISIBLE_DEVICES") + elif 'ASCEND_VISIBLE_DEVICES' in os.environ: + dev._dtype = DeviceType.NPU + visible_devices = os.getenv("ASCEND_VISIBLE_DEVICES") + elif 'MLU_VISIBLE_DEVICES' in os.environ: + dev._dtype = DeviceType.MLU + visible_devices = os.getenv("MLU_VISIBLE_DEVICES") + + if visible_devices is not None and visible_devices != 'all': + dev._labels = visible_devices.split(',') + else: + return self.detect_device() + + return dev + + @classmethod + def detect_device(self): + + def get_custom_devices_count(device_type): + all_custom_devices = get_available_custom_device() + all_custom_devices = [ + device.split(':')[0] for device in all_custom_devices + ] + custom_devices_count = all_custom_devices.count(device_type) + return custom_devices_count + + dev = Device() + num = 0 + visible_devices = None + if 'PADDLE_XCCL_BACKEND' in os.environ: + custom_device_type = os.getenv('PADDLE_XCCL_BACKEND') + dev._dtype = DeviceType.CUSTOM_DEVICE + num = get_custom_devices_count(custom_device_type) + visible_devices_str = '{}_VISIBLE_DEVICES'.format( + custom_device_type.upper()) + if visible_devices_str in os.environ: + visible_devices = os.getenv(visible_devices_str) + elif fluid.core.is_compiled_with_cuda(): + dev._dtype = DeviceType.GPU + num = fluid.core.get_cuda_device_count() + visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + elif fluid.core.is_compiled_with_xpu(): + dev._dtype = DeviceType.XPU + num = fluid.core.get_xpu_device_count() + visible_devices = os.getenv("XPU_VISIBLE_DEVICES") + elif fluid.core.is_compiled_with_npu(): + dev._dtype = DeviceType.NPU + num = fluid.core.get_npu_device_count() + visible_devices = os.getenv("ASCEND_VISIBLE_DEVICES") + elif fluid.core.is_compiled_with_mlu(): + dev._dtype = DeviceType.MLU + num = fluid.core.get_mlu_device_count() + visible_devices = os.getenv("MLU_VISIBLE_DEVICES") + elif fluid.core.is_compiled_with_ipu(): + dev._dtype = DeviceType.IPU + num = fluid.core.get_ipu_device_count() + # For IPUs, 'labels' is a list which contains the available numbers of IPU devices. + dev._labels = [str(x) for x in range(0, num + 1)] + return dev + + if num == 0: + dev._dtype = DeviceType.CPU + elif visible_devices is None or visible_devices == "all": + dev._labels = [str(x) for x in range(0, num)] + else: + dev._labels = visible_devices.split(',') + + return dev + + +if __name__ == '__main__': + d = Device.parse_device() + print(d.get_selected_devices()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/event.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/event.py new file mode 100644 index 0000000000000000000000000000000000000000..cb39e1529fc82e18e12d2c58dd1dfee035da6b4d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/event.py @@ -0,0 +1,21 @@ +# Copyright (c) 2022 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. + + +class Event(object): + + def __init__(self, kind="status", message="", fatal=False): + self.kind = kind + self.message = message + self.fatal = fatal diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/node.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/node.py new file mode 100644 index 0000000000000000000000000000000000000000..e81c91e1bca9f1ff5f5a1e808b71f1d1b355fa99 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/node.py @@ -0,0 +1,92 @@ +# Copyright (c) 2022 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. + +from .device import Device + +import os +import random +import socket +import struct +from contextlib import closing + + +class Node(object): + + def __init__(self): + # self.device = Device.detect_device() + self.device = Device.parse_device() + self.ip = self.get_host_ip() + self.free_ports = [] + self._allocated_ports = [] + + port_range = os.getenv('PORT_RANGE', '35100:64000') + port_range = port_range.split(':') + self._port_start = int(port_range[0]) + self._port_end = int(port_range[1]) + self._port_cur = random.randint(self._port_start, self._port_end) + + def get_host_ip(self): + try: + self.hostname = socket.gethostname() + self.ip = socket.gethostbyname(socket.getfqdn(self.hostname)) + return self.ip + except: + return '127.0.0.1' + + def get_free_ports(self, n=1): + free_ports = [self.get_free_port() for i in range(n)] + self.free_ports += free_ports + return free_ports + + def get_ports_occupied(self): + return self.free_ports + + def _get_free_port(self, port=0): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, + struct.pack('ii', 1, 0)) + try: + s.bind(('', port)) + return s.getsockname()[1] + except: + return -1 + + def _update_port_cur(self): + self._port_cur += 1 + if self._port_cur > self._port_end: + self._port_cur = self._port_start + + def get_free_port(self): + for _ in range(100): + ret = self._get_free_port(self._port_cur) + if ret > 0: + self._update_port_cur() + return ret + else: + self._update_port_cur() + + return self._port_cur + + @classmethod + def is_server_ready(self, ip, port): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: + #sock.settimeout(0.01) + #sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + result = sock.connect_ex((ip, int(port))) + if result == 0: + return True + else: + return False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/resource.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..d523c3c5cdfe8cd4377d7c50aec75d2bd83856ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/resource.py @@ -0,0 +1,19 @@ +# Copyright (c) 2022 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. + + +class Resource(object): + + def __init__(self): + self.devices = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/status.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/status.py new file mode 100644 index 0000000000000000000000000000000000000000..b87b7b3fb82d8ea76e63d27ad83a7edbe4a611b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/context/status.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022 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. + + +class Status(object): + UNINIT = "uninit" + READY = "ready" + RUNNING = "running" + FAILED = "failed" + TERMINATING = "terminating" + RESTARTING = "restarting" + UNKNOWN = "unknown" + COMPLETED = "completed" + DONE = "done" # should exit whatever status + + def __init__(self): + self._current_status = None + + def current(self): + return self._current_status + + def is_running(self): + return self._current_status == self.RUNNING + + def is_restarting(self): + return self._current_status == self.RESTARTING + + def is_done(self): + if self._current_status in [self.DONE, self.COMPLETED, self.FAILED]: + return True + else: + return False + + def run(self): + self._current_status = self.RUNNING + + def fail(self): + self._current_status = self.FAILED + + def complete(self): + self._current_status = self.COMPLETED + + def restart(self): + self._current_status = self.RESTARTING + + def done(self): + self._current_status = self.DONE diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c686164dbd8847c0650c064b257ef60eb95aeec5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/__init__.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022 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. + +__all__ = [] + +from .collective import CollectiveController +from .collective import CollectiveElasticController +from .ps import PSController +from .ipu_controller import IPUController + +# the order is extremely important +_controllers = [ + IPUController, + CollectiveElasticController, + PSController, + CollectiveController, +] + + +def init(ctx): + for c in _controllers: + if c.enable(ctx): + ctx.print() + return c(ctx) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/collective.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..06612bd7c823d508d8baeeb26efafa453a950686 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/collective.py @@ -0,0 +1,227 @@ +# Copyright (c) 2022 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. + +from .controller import Controller, ControleMode +from ..context.device import DeviceType + +import json +import os +import six +import time + + +class CollectiveController(Controller): + + @classmethod + def enable(cls, ctx): + # collective is the default mode + if ctx: + ctx.logger.debug("{} enabled".format(cls.__name__)) + ctx.args.run_mode = ControleMode.COLLECTIVE + return True + else: + return False + + def build_pod(self): + if self.ctx.args.master is None and self.ctx.args.start_port and self.ctx.args.ips: + self._build_pod_with_args() + else: + self._build_pod_with_master() + + def _build_pod_with_args(self): + self.pod.replicas = self.pod_replicas() + + start_port = int(self.ctx.args.start_port) + ips = self.ctx.args.ips.split(',') + + job_endpoints = [ + f"{h}:{p+start_port}" for h in ips for p in range(self.pod.replicas) + ] + + self.ctx.logger.debug("job endpoints: {}".format(job_endpoints)) + + rank_offset = ips.index( + self.ctx.node.ip + ) * self.pod.replicas if self.ctx.node.ip in ips else 0 + + self.save_pod_log(job_endpoints) + + selected_dev_key = self.ctx.node.device.get_selected_device_key() + selected_dev_list = self.ctx.node.device.get_selected_devices( + self.ctx.args.devices) + + for i in range(self.pod.replicas): + e = { + "PADDLE_GLOBAL_SIZE": "{}".format(len(job_endpoints)), + "PADDLE_LOCAL_SIZE": "{}".format(self.pod.replicas), + "PADDLE_GLOBAL_RANK": "{}".format(i + rank_offset), + "PADDLE_LOCAL_RANK": "{}".format(i), + "PADDLE_NNODES": "{}".format(len(ips)), + ## compatible env + "PADDLE_TRAINER_ENDPOINTS": ",".join(job_endpoints), + "PADDLE_CURRENT_ENDPOINT": job_endpoints[i + rank_offset], + "PADDLE_TRAINER_ID": "{}".format(i + rank_offset), + "PADDLE_TRAINERS_NUM": "{}".format(len(job_endpoints)), + "PADDLE_RANK_IN_NODE": str(i), + } + if len(selected_dev_list) > 0: + if self.ctx.node.device.dtype == DeviceType.CUSTOM_DEVICE: + e.update(self.ctx.node.device.get_custom_device_envs()) + if self.pod.replicas == 1: + e.update({selected_dev_key: ",".join(selected_dev_list)}) + else: + e.update({selected_dev_key: selected_dev_list[i]}) + else: + e.update({'PADDLE_DISTRI_BACKEND': 'gloo'}) + + log_file = f"workerlog.{i}" + self.add_container(envs=e, log_file=log_file) + + return True + + def _build_pod_with_master(self): + self.pod.replicas = self.pod_replicas() + + # rank will be reset when restart + self.pod.rank = int(self.ctx.args.rank) + + port = self.ctx.node.get_free_port() + + # compatible + endpoints = [ + "{}:{}".format(self.ctx.node.ip, p) + for p in self.ctx.node.get_free_ports(self.pod.replicas) + ] + + data = json.dumps({ + 'name': self.pod.name, + 'rank': self.pod.rank, + 'replicas': self.pod.replicas, + 'dtype': self.ctx.node.device.dtype, + 'candidate': '{}:{}'.format(self.ctx.node.ip, port), + 'endpoints': ",".join(endpoints), + }) + + peer_list, rank = self.master.sync_peers('/{}/info'.format(self.job.id), + self.pod.name, data, + self.job.replicas, + self.pod.rank) + self.pod.rank = rank + + if len(peer_list) < 1: + return False + + peer_list = [json.loads(i) for i in peer_list] + + self.ctx.logger.debug("sync peers done {}".format(peer_list)) + self.save_pod_log(peer_list) + + global_size = sum([i['replicas'] for i in peer_list]) + rank_offset = sum([i['replicas'] for i in peer_list[:rank]]) + ''' + The new designed collective need nothing but a master endpoint + ''' + collective_master = peer_list[0]['candidate'] + + job_endpoints = [i['endpoints'] for i in peer_list] + + self.pod.reset() + selected_dev_key = self.ctx.node.device.get_selected_device_key() + selected_dev_list = self.ctx.node.device.get_selected_devices( + self.ctx.args.devices) + for i in range(self.pod.replicas): + e = { + "PADDLE_MASTER": collective_master, + "PADDLE_GLOBAL_SIZE": "{}".format(global_size), + "PADDLE_LOCAL_SIZE": "{}".format(self.pod.replicas), + "PADDLE_GLOBAL_RANK": "{}".format(i + rank_offset), + "PADDLE_LOCAL_RANK": "{}".format(i), + "PADDLE_NNODES": "{}".format(self.job.replicas), + ## compatible env + "PADDLE_TRAINER_ENDPOINTS": ",".join(job_endpoints), + "PADDLE_CURRENT_ENDPOINT": endpoints[i], + "PADDLE_TRAINER_ID": "{}".format(i + rank_offset), + "PADDLE_TRAINERS_NUM": "{}".format(global_size), + "PADDLE_RANK_IN_NODE": str(i), + } + if len(selected_dev_list) > 0: + if self.ctx.node.device.dtype == DeviceType.CUSTOM_DEVICE: + e.update(self.ctx.node.device.get_custom_device_envs()) + if self.pod.replicas == 1: + e.update({selected_dev_key: ",".join(selected_dev_list)}) + else: + e.update({selected_dev_key: selected_dev_list[i]}) + else: + e.update({'PADDLE_DISTRI_BACKEND': 'gloo'}) + + # log_file = "{}.{}.{}.log".format(self.job.id, self.pod.name, i) + log_file = f"workerlog.{i}" + self.add_container(envs=e, log_file=log_file) + + return True + + +class CollectiveElasticController(CollectiveController): + + @classmethod + def enable(cls, ctx): + if ctx.args.master and ctx.args.master.startswith("etcd://"): + ctx.logger.debug("{} enabled".format(cls.__name__)) + ctx.args.run_mode = ControleMode.COLLECTIVE + return True + else: + return False + + def register(self): + if self.job.id == 'default': + self.ctx.logger.warning( + 'Using default job name may cause conflict, add --job_id in args' + ) + + self.master.register_heartbeat(self.job.id, self.pod.name) + + def run(self): + + timeout = int(self.ctx.args.elastic_timeout) + timeout = timeout if self.job.elastic else timeout * 10 + self.register() + + while self.pod.restart <= self.ctx.args.max_restart: + + self.build_job() + + self.ctx.logger.info("Waiting peer ready...") + + ok, replicas = self.master.wait_peer_ready(self.job.replicas_min, + self.job.replicas_max, + timeout) + if ok: + self.job.replicas = replicas + else: + self.ctx.logger.warning("peer not ready {}".format(self.job)) + break + + self.ctx.logger.debug("Run {}".format(self.job)) + + if not self.build_pod(): + continue + + self.master.set_status(self.ctx.status.RUNNING) + + self.deploy_pod() + + if self.watch(): + break + + self.ctx.logger.debug("Job done {}".format(self.job)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/controller.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..56499cb64713454e83f45f90dbe07df54f524d59 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/controller.py @@ -0,0 +1,252 @@ +# Copyright (c) 2022 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. + +import sys +import os +import signal + +from paddle.distributed.launch.job.job import Job +from paddle.distributed.launch.job.pod import Pod +from paddle.distributed.launch.job.container import Container + +from .master import Master +from .watcher import Watcher + +import time + + +class ControleMode: + COLLECTIVE = "collective" + PS = "ps" + IPU = "ipu" + + +class ControllerBase(object): + + def __init__(self, ctx): + signal.signal(signal.SIGTERM, self.signal_handler) + signal.signal(signal.SIGABRT, self.signal_handler) + signal.signal(signal.SIGINT, self.signal_handler) + + self.ctx = ctx + self.master = Master.factory(self.ctx) + + self.watcher = Watcher(self.ctx) + + self.job = Job(nnodes=self.ctx.args.nnodes, + mode=self.ctx.args.run_mode, + jid=self.ctx.args.job_id) + self.pod = Pod() + + self.ctx.set_envs({"POD_NAME": self.pod.name}) + + self.join_server = None + + def deploy_pod(self): + + assert len(self.pod.containers) > 0, "No container in the pod" + + self.ctx.logger.info("Run {}".format(self.pod)) + self.ctx.logger.debug(self.pod.containers[0]) + + self.ctx.status.run() + self.pod.deploy() + + def run(self): + self.build_job() + self.build_pod() + + self.deploy_pod() + + self.watch() + + def watch(self) -> bool: + ''' + watch self and peer status, return true to exit + ''' + #TODO(kuizhiqing) unify ctx.status and master status + + self.ctx.logger.info("Watching {}".format(self.pod)) + + while not self.ctx.status.is_done(): + status = self.pod.watch(timeout=2) + + #if self.ctx.continous_log(): + # default to print log + self.pod.logs() + + # completed + if status == self.ctx.status.COMPLETED: + self.ctx.status.complete() + + self.master.set_status(status) + + while self.pod.logs(): + pass + + self.ctx.logger.info("Pod {}".format(status)) + return True + + # self failure + elif status == self.ctx.status.FAILED: + self.ctx.status.fail() + + self.master.set_status(status) + self.master.restart_peer() + + fc = self.pod.failed_container() + self.ctx.logger.info("Pod {}".format(status)) + self.ctx.logger.error("Container failed !!!\n{}".format(fc[0])) + self.ctx.logger.info( + "------------------------- ERROR LOG DETAIL -------------------------" + ) + fc[0].tail() + + if self.ctx.args.elastic_level <= 0: + self.pod.stop(timeout=3) + return True + else: + self.pod.stop(timeout=30) + return False + + # peer failure + if self.ctx.status.is_restarting( + ) and self.master.get_status() != self.ctx.status.COMPLETED: + self.pod.stop(timeout=30) + return False + + def stop(self, sigint=None): + self.ctx.logger.debug("Controller stop") + + self.watcher.stop() + + self.master.stop() + self.pod.stop(timeout=30) + + def finalize(self): + self.pod.join() + self.master.stop() + + self.ctx.logger.info("Exit code {}".format(self.pod.exit_code)) + sys.exit(self.pod.exit_code) + + def signal_handler(self, sigint, frame): + if hasattr(self, 'sigint'): + self.ctx.logger.info("Force quit in 10 seconds...") + self.pod.stop(timeout=10) + sys.exit(sigint) + + self.ctx.logger.info("Terminating with signal {}".format(sigint)) + + self.sigint = sigint + self.ctx.status.done() + self.stop(sigint=sigint) + self.ctx.logger.info("Exit with signal {}".format(sigint)) + sys.exit(sigint) + + +class Controller(ControllerBase): + ''' + Controller API for customization + ''' + + def build_job(self): + ''' + build job fill the job info. + ''' + self.ctx.logger.info(self.job) + + def build_pod(self) -> bool: + ''' + build pod includes creating containers etc. + + Return True if succeed + ''' + raise NotImplementedError + + def _get_entrypoint(self): + if self.ctx.args.training_script.endswith('.py'): + entrypoint = [sys.executable, "-u", self.ctx.args.training_script] + else: + entrypoint = [self.ctx.args.training_script] + + entrypoint.extend(self.ctx.args.training_script_args) + return entrypoint + + def _get_out_err_file(self, out=None, err=None): + if out and self.ctx.args.log_dir != "": + out = os.path.join(self.ctx.args.log_dir, out) + if err and self.ctx.args.log_dir != "": + err = os.path.join(self.ctx.args.log_dir, err) + return out, (err or out) + + def new_container(self, + entrypoint=None, + envs={}, + use_ctx_env=True, + out=None, + err=None): + c = Container( + entrypoint=(entrypoint or self._get_entrypoint()), + env=(self.ctx.get_envs() if use_ctx_env else {}), + ) + c.outfile, c.errfile = self._get_out_err_file(out, err) + c.update_env(envs) + return c + + def add_container(self, + container=None, + entrypoint=None, + envs={}, + log_file=None, + is_init=False): + + if not container: + container = self.new_container(entrypoint=entrypoint, + envs=envs, + out=log_file, + err=log_file) + + if is_init: + self.pod.add_init_container(container) + else: + self.pod.add_container(container) + + def pod_replicas(self): + ''' + how many process/container should be run in pod + ''' + + if self.ctx.args.nproc_per_node: + return int(self.ctx.args.nproc_per_node) + elif self.ctx.args.devices: + return len(self.ctx.args.devices.split(',')) + else: + return self.ctx.node.device.count + + def save_pod_log(self, info): + ''' + save_pod_log append *info* to the log file of pod.name + ''' + if not self.ctx.args.log_dir: + return + + f = os.path.join(self.ctx.args.log_dir, + '{}.{}.log'.format(self.job.id, self.pod.name)) + try: + os.makedirs(os.path.dirname(f), exist_ok=True) + with open(f, 'a+') as fd: + fd.write(str(info)) + except Exception as e: + self.ctx.logger.error("save log failed because {}".format(e)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ipu_controller.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ipu_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..92dc2960ab6240aa1c690f8d0de0b85c04aec952 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ipu_controller.py @@ -0,0 +1,170 @@ +# Copyright (c) 2022 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. + +import os +import sys +import argparse + +from .collective import CollectiveController, ControleMode +from paddle.distributed.launch.job.container import Container + + +class IPUController(CollectiveController): + + @classmethod + def enable(cls, ctx): + if ctx.args.training_script == "ipu": + ctx.logger.debug("{} enabled".format(cls.__name__)) + ctx.args.run_mode = ControleMode.IPU + return True + else: + return False + + def parse_ipu_args(self, args_list): + parser = argparse.ArgumentParser() + parser.add_argument("--hosts", + type=str, + help="The hosts for IPU distributd training.") + parser.add_argument("--nproc_per_host", + type=int, + help="The number of processes launched per host.") + parser.add_argument("--ipus_per_replica", + type=int, + help="The number of IPUs requested per replica.") + parser.add_argument("--ipu_partition", + type=str, + help="The partition name of IPU devices.") + parser.add_argument("--vipu_server", + type=str, + help="The ip of the IPU device manager.") + parser.add_argument( + "training_script", + type=str, + help= + "The full path to the IPU distributed training program/script to be launched in parallel. e.g., ``training.py``." + ) + parser.add_argument('training_script_args', nargs=argparse.REMAINDER) + return parser.parse_args(args_list) + + def replace_training_script(self): + # IPU distributed computing is based on PopRun which is a wrapper of MPI. + self.ctx.args.training_script = "poprun" + poprun_args = self.parse_ipu_args(self.ctx.args.training_script_args) + + num_ipus = int(self.ctx.args.devices) + # The number of replicas for data parallel + assert (num_ipus % poprun_args.ipus_per_replica) == 0, \ + "The number of IPUs:{} mod the number of IPUs per replica:{} must == 0".format(num_ipus, poprun_args.ipus_per_replica) + num_replicas = num_ipus // poprun_args.ipus_per_replica + self.ctx.logger.info( + "The number of total replicas is {}.".format(num_replicas)) + + # The number of processes + num_nodes = len(poprun_args.hosts.split(',')) + num_procs = num_nodes * poprun_args.nproc_per_host + self.ctx.logger.info( + "The number of total processes is {}.".format(num_procs)) + assert (num_replicas % num_procs) == 0, \ + "The number of replicas:{} mod the number of processes:{} must == 0".format(num_replicas, num_procs) + + # hosts and endpoints + hosts = poprun_args.hosts.replace(' ', '').split(',') + endpoints = [x + ":8090" for x in hosts] + + # args for poprun + poprun_command = [] + + poprun_command.append('--num-instances={}'.format(num_procs)) + poprun_command.append('--num-replicas={}'.format(num_replicas)) + poprun_command.append('--ipus-per-replica={}'.format( + poprun_args.ipus_per_replica)) + poprun_command.append('--host={}'.format(','.join(hosts))) + poprun_command.append('--vipu-partition={}'.format( + poprun_args.ipu_partition)) + poprun_command.append('--vipu-server-host={}'.format( + poprun_args.vipu_server)) + + poprun_command.extend([ + '--update-partition=no', '--vipu-server-timeout=120', + '--print-topology=yes', '--numa-aware=yes' + ]) + + # global envs + global_envs = '--mpi-local-args=\'' + log_level = os.getenv('POPART_LOG_LEVEL', None) + if log_level: + global_envs += '-x POPART_LOG_LEVEL={} '.format(log_level) + global_envs += '-x PADDLE_TRAINERS_NUM={} -x PADDLE_TRAINER_ENDPOINTS={}'.format( + num_procs, ','.join(endpoints)) + global_envs += '\'' + poprun_command.append(global_envs) + + # local envs + for idx in range(num_procs): + cur_endpoint = endpoints[idx // poprun_args.nproc_per_host] + rank_in_node = idx % poprun_args.nproc_per_host + poprun_command.append( + '--instance-mpi-local-args={}:\"-x PADDLE_TRAINER_ID={} -x PADDLE_CURRENT_ENDPOINT={} -x PADDLE_RANK_IN_NODE={}\"' + .format(idx, idx, cur_endpoint, rank_in_node)) + + # executor + poprun_command.append(sys.executable) + + # script and script args + poprun_command.append(poprun_args.training_script) + poprun_command.extend(poprun_args.training_script_args) + + # for debug + print("----------- PopRun Command -----------") + print("poprun \\") + for i in range(len(poprun_command) - 1): + print("%s \\" % (poprun_command[i])) + print("%s" % (poprun_command[len(poprun_command) - 1])) + print("---------------------------------------") + + # replace training_script_args + self.ctx.args.training_script_args = poprun_command + + def _get_entrypoint(self): + entrypoint = [self.ctx.args.training_script] + entrypoint.extend(self.ctx.args.training_script_args) + entrypoint = [" ".join(entrypoint)] + return entrypoint + + def new_container(self, + entrypoint=None, + envs={}, + use_ctx_env=True, + out=None, + err=None): + c = Container( + entrypoint=(entrypoint or self._get_entrypoint()), + env=(self.ctx.get_envs() if use_ctx_env else {}), + ) + c.outfile, c.errfile = self._get_out_err_file(out, err) + c.update_env(envs) + # Need subprocess.Popen(shell=True) for PopRun command + c.shell = True + return c + + def run(self): + # Replace the training script with the PopRun command + self.replace_training_script() + + self.build_job() + self.build_pod() + + self.deploy_pod() + + self.watch() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/master.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/master.py new file mode 100644 index 0000000000000000000000000000000000000000..c71d0890f196a0394f2edd78d61415b841f2562f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/master.py @@ -0,0 +1,320 @@ +# Copyright (c) 2022 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. + +from paddle.distributed.launch.utils.kv_client import KVClient +from paddle.distributed.launch.utils.kv_server import KVServer + +import time +import sys +import six +import threading +import copy +import random + +ETCD_PROTOCAL = 'etcd://' + + +class Master(object): + ''' + Master is a distributed store design to exchange info among nodes + ''' + + MAIN = "main" + STANDBY = "standby" + PATICIPANT = "participant" + + def __init__(self, ctx): + self.ctx = ctx + self.server = None + self.initialized = False + self.endpoint = None + + def stop(self): + raise NotImplementedError + + def set_status(self, status): + pass + + def get_status(self): + return None + + def restart_peer(self): + pass + + def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int): + raise NotImplementedError + + @classmethod + def factory(cls, ctx): + if ctx.args.master and ctx.args.master.startswith(ETCD_PROTOCAL): + return ETCDMaster(ctx) + else: + return HTTPMaster(ctx) + + +class HTTPMaster(Master): + + def lazy_init(self): + if self.initialized: + return + + self.role = Master.PATICIPANT + + if self.ctx.args.master: + self.endpoint = self.ctx.args.master + ip, port = self.endpoint.split(':') + if ip in ['127.0.0.1', self.ctx.node.ip]: + time.sleep(2 * random.random()) + while not self.ctx.node.is_server_ready(ip, int(port)): + try: + self.server = KVServer(int(port)) + self.role = Master.MAIN + break + except Exception as e: + self.ctx.logger.warning( + "start master failed {}".format(e)) + time.sleep(0.1) + continue + else: + port = self.ctx.node.get_free_port() + self.endpoint = "{}:{}".format(self.ctx.node.ip, port) + self.server = KVServer(port) + self.role = Master.MAIN + + print("Copy the following command to other nodes to run.") + cmd = [ + sys.executable.split('/')[-1], "-m", "paddle.distributed.launch" + ] + cmd.extend(["--master", self.endpoint]) + cmd.extend(sys.argv[1:]) + print("-" * 80) + print(" ".join(cmd)) + print("-" * 80) + + if int(self.ctx.args.rank) >= 0: + self.ctx.logger.warning( + "--rank set in the command may not compatible in auto mode") + + if '127.0.0.1' in self.endpoint: + self.endpoint = self.endpoint.replace('127.0.0.1', self.ctx.node.ip) + self.client = KVClient(self.endpoint) + + self.initialized = True + + self._start_server() + + def _start_server(self): + if self.server and not self.server.started: + self.server.start() + self.ctx.logger.debug("KV server start at {}".format(self.endpoint)) + + def _stop_server(self): + if self.server and not self.server.stopped: + self.server.stop() + self.ctx.logger.debug("KV server stopped") + + def stop(self): + self._stop_server() + + def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int): + + if size < 2: + return [value], 0 + + self.ctx.logger.info("Waiting peer start...") + + self.lazy_init() + + while not self.ctx.status.is_done(): + if self.client.wait_server_ready(timeout=5): + break + else: + self.ctx.logger.warning("master not ready") + time.sleep(0.1) + + # 'aaaaaa' make sure main pod (master server) as rank 0 + ky = 'aaaaaa' if rank < 0 and self.role == Master.MAIN else key + k = "{}/{}/{}".format(prefix, ky, rank) + + while not self.ctx.status.is_done(): + if not self.client.put(k, value): + self.ctx.logger.warning("put value failed") + time.sleep(0.1) + continue + + rjson = self.client.get_prefix(prefix) + self.ctx.logger.debug("sync peers {}".format(rjson)) + if rjson and len(rjson) == size: + if rank < 0: + keys = list(rjson.keys()) + keys.sort() + ret = [rjson[k] for k in keys] + idx = ret.index(value) + return ret, idx + else: + ret = [None] * size + for k, v in rjson.items(): + ret[int(k.split('/')[-1])] = v + return ret, rank + else: + time.sleep(0.5) + return [], 0 + + +class ETCDMaster(Master): + + def __init__(self, ctx): + super().__init__(ctx) + + if self.ctx.args.master: + # etcd://localhost:2379 + self.endpoint = self.ctx.args.master.strip("etcd://") + + import etcd3 + + host, port = self.endpoint.split(':') + self.client = etcd3.client(host=host, port=port) + + def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int): + ''' + sync_peers gather all value for key under scope prefix + result always be sorted either by rank or alphabet of pod.name + ''' + + if size < 2: + return [value], 0 + + self.ctx.logger.info("Waiting peer start...") + + path = "{}/{}/{}".format(prefix, key, rank) + + self.client.delete_prefix(prefix) + + self.ctx.logger.debug("sync path {} value {}".format(path, value)) + + while not self.ctx.status.is_done(): + self.client.put(path, six.b(value)) + + result = [i for i in self.client.get_prefix(prefix)] + result = copy.deepcopy(result) + self.ctx.logger.debug("sync peers {}".format(result)) + + if len(result) == size: + if rank < 0: + keys = [six.ensure_str(i[1].key) for i in result] + sorted_keys = [six.ensure_str(i[1].key) for i in result] + sorted_keys.sort() + values = [six.ensure_str(i[0]) for i in result] + ret = [values[keys.index(k)] for k in sorted_keys] + idx = ret.index(value) + return ret, idx + else: + ret = [None] * size + for v, k in result: + ii = int(six.ensure_str(k.key).split('/')[-1]) + if ii < 0: + self.ctx.logger.error( + "rank {} error in sync".format(ii)) + ret[ii] = six.ensure_str(v) + return ret, rank + else: + time.sleep(0.5) + + def register_heartbeat(self, job_id, pod_id, ttl=10): + if hasattr(self, 'heartbeat_prefix'): + self.ctx.logger.warning("Heartbeat already done") + return + + self.job_prefix = '/paddle/{}'.format(job_id) + self.heartbeat_prefix = '{}/heartbeat'.format(self.job_prefix) + + lease = self.client.lease(ttl) + + #self.client.delete_prefix(self.job_prefix) + + beat_path = "{}/{}".format(self.heartbeat_prefix, pod_id) + self.client.put(beat_path, six.b(pod_id), lease=lease) + + def _beat_watch(event): + self.ctx.status.restart() + + beat_watch = self.client.add_watch_prefix_callback( + self.heartbeat_prefix, _beat_watch) + + def _heartbeat(): + while not self.ctx.status.is_done(): + try: + lease.refresh() + if pod_id not in self.fetch_peer_alive(): + self.client.put(beat_path, six.b(pod_id), lease=lease) + self.ctx.logger.debug("Heartbeat register again") + except Exception as e: + self.ctx.logger.error("Heartbeat error {}".format(e)) + time.sleep(ttl / 2) + self.ctx.logger.debug("Heartbeat done") + self.client.cancel_watch(beat_watch) + + self.beat_thread = threading.Thread(name='heartbeat', + target=_heartbeat, + daemon=True) + self.beat_thread.start() + + def fetch_peer_alive(self): + peer_alive = [ + six.ensure_str(i[0]) + for i in self.client.get_prefix(self.heartbeat_prefix) + ] + self.ctx.logger.debug("peer alive {}".format(peer_alive)) + return peer_alive + + def wait_peer_ready(self, replicas_min, replicas_max, timeout): + timeout = timeout if timeout > 1 else 3 + + end = time.time() + timeout + np_pre = len(self.fetch_peer_alive()) + while not self.ctx.status.is_done() and time.time() < end: + np = len(self.fetch_peer_alive()) + if np == replicas_max: + # maximum replicas reached, return immediately + return (True, replicas_max) + elif np != np_pre: + # replicas are changing, reset timeout + end = time.time() + timeout + np_pre = np + time.sleep(0.2) + else: + time.sleep(0.5) + + np = len(self.fetch_peer_alive()) + if np >= replicas_min and np <= replicas_max: + return (True, np) + else: + return (False, np) + + def restart_peer(self): + self.client.delete_prefix(self.heartbeat_prefix) + + def set_status(self, status): + assert self.client.put( + self.job_prefix, six.b(status), + lease=self.client.lease(600)), "set status failed {}".format(status) + + def get_status(self): + return six.ensure_str(self.client.get(self.job_prefix)[0] or '') + + def stop(self): + if hasattr(self, 'beat_thread'): + self.ctx.status.done() + # daemon thread + #self.beat_thread.join() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ps.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ps.py new file mode 100644 index 0000000000000000000000000000000000000000..f785311a525402c49008658f73a39e69502a1e30 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/ps.py @@ -0,0 +1,241 @@ +# Copyright (c) 2022 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. + +from .controller import Controller, ControleMode + +import json +import os, shutil + + +class PSController(Controller): + + @classmethod + def enable(cls, ctx): + if ctx.args.run_mode == ControleMode.PS or ctx.args.server_num or len( + ctx.args.servers) > 0 or ctx.args.trainer_num or len( + ctx.args.trainers) > 0: + ctx.logger.debug("{} enabled".format(cls.__name__)) + ctx.args.run_mode = ControleMode.PS + return True + else: + return False + + def build_pod(self): + if self.ctx.args.servers and self.ctx.args.trainers: + self._build_pod_with_args() + else: + self._build_pod_with_master() + + def _build_pod_with_args(self): + if '127.0.0.1' in self.ctx.args.servers: + host = '127.0.0.1' + else: + host = self.ctx.node.ip + + server_endpoints = [s for s in self.ctx.args.servers.split(",")] + trainer_endpoints = [s for s in self.ctx.args.trainers.split(",")] + servers = [ + s for s in self.ctx.args.servers.split(",") if s.startswith(host) + ] + trainers = [ + s for s in self.ctx.args.trainers.split(",") if s.startswith(host) + ] + server_num = len(servers) + trainer_num = len(trainers) + + self.pod.replicas = server_num + trainer_num + + self.save_pod_log([server_endpoints, trainer_endpoints]) + + import tempfile + gloo_rendezvous_dir = tempfile.mkdtemp() + if os.path.exists(gloo_rendezvous_dir): + shutil.rmtree(gloo_rendezvous_dir) + + gloo_port = self.ctx.args.gloo_port + gloo_http = "{}:{}".format(server_endpoints[0].split(":")[0], gloo_port) + + _gloo_envs = { + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": gloo_rendezvous_dir, + "PADDLE_GLOO_HTTP_ENDPOINT": gloo_http, + "PADDLE_WITH_GLOO": self.ctx.args.with_gloo + } + + for i in range(server_num): + e = { + "PADDLE_PSERVERS_IP_PORT_LIST": self.ctx.args.servers, + "PADDLE_TRAINER_ENDPOINTS": self.ctx.args.trainers, + "PADDLE_PORT": servers[i].split(":")[1], + "PADDLE_ROLE": "PSERVER", + "TRAINING_ROLE": "PSERVER", + "PADDLE_TRAINERS_NUM": "{}".format(len(trainer_endpoints)), + "POD_IP": self.ctx.node.ip, + } + e.update(_gloo_envs) + log_file = "serverlog.{}".format(i) + self.add_container(envs=e, log_file=log_file) + + trainer_rank_offset = 0 + for s in trainer_endpoints: + if s.startswith(host): + break + else: + trainer_rank_offset += 1 + + for i in range(trainer_num): + e = { + "PADDLE_PSERVERS_IP_PORT_LIST": ",".join(server_endpoints), + "PADDLE_TRAINER_ENDPOINTS": ",".join(trainer_endpoints), + "PADDLE_PORT": trainers[i].split(":")[1], + "PADDLE_ROLE": "TRAINER", + "TRAINING_ROLE": "TRAINER", + "PADDLE_TRAINER_ID": "{}".format(i + trainer_rank_offset), + "PADDLE_TRAINERS_NUM": "{}".format(len(trainer_endpoints)), + "POD_IP": self.ctx.node.ip, + } + e.update(_gloo_envs) + log_file = "workerlog.{}".format(i) + self.add_container(envs=e, log_file=log_file) + + def _build_pod_with_master(self): + + self.pod.rank = int(self.ctx.args.rank) + + server_num = self.ctx.args.server_num or 1 + servers = [ + "{}:{}".format(self.ctx.node.ip, p) + for p in self.ctx.node.get_free_ports(server_num) + ] + trainer_num = self.ctx.args.trainer_num or 1 + trainers = [ + "{}:{}".format(self.ctx.node.ip, p) + for p in self.ctx.node.get_free_ports(trainer_num) + ] + + data = json.dumps({ + 'name': self.pod.name, + 'rank': self.pod.rank, + 'servers': servers, + 'trainers': trainers, + 'dtype': self.ctx.node.device.dtype, + 'gloo_port': self.ctx.node.get_free_port(), + }) + + peer_list, rank = self.master.sync_peers('/{}/info'.format(self.job.id), + self.pod.name, data, + self.job.replicas, + self.pod.rank) + + self.ctx.logger.debug("sync peers done {}".format(peer_list)) + + peer_list = [json.loads(i) for i in peer_list] + + self.save_pod_log(peer_list) + + server_endpoints = [j for i in peer_list for j in i['servers']] + trainer_endpoints = [j for i in peer_list for j in i['trainers']] + #rank_offset = sum([i['replicas'] for i in peer_list[:rank]]) + + server_rank_offset = sum([len(i['servers']) for i in peer_list[:rank]]) + trainer_rank_offset = sum( + [len(i['trainers']) for i in peer_list[:rank]]) + + self.pod.rank = rank + + self.pod.replicas = server_num + trainer_num + + import tempfile + gloo_rendezvous_dir = tempfile.mkdtemp() + if os.path.exists(gloo_rendezvous_dir): + shutil.rmtree(gloo_rendezvous_dir) + + gloo_port = peer_list[0]['gloo_port'] + gloo_http = "{}:{}".format(server_endpoints[0].split(":")[0], gloo_port) + + _gloo_envs = { + "PADDLE_GLOO_RENDEZVOUS": "3", + "PADDLE_GLOO_FS_PATH": gloo_rendezvous_dir, + "PADDLE_GLOO_HTTP_ENDPOINT": gloo_http, + "PADDLE_WITH_GLOO": self.ctx.args.with_gloo + } + + for i in range(server_num): + e = { + "PADDLE_NNODES": + "{}".format(self.job.replicas), + "PADDLE_PSERVERS_IP_PORT_LIST": + ",".join(server_endpoints), + "PADDLE_TRAINER_ENDPOINTS": + ",".join(trainer_endpoints), + "PADDLE_PORT": + server_endpoints[i + server_rank_offset].split(":")[1], + "PADDLE_ROLE": + "PSERVER", + "TRAINING_ROLE": + "PSERVER", + "PADDLE_TRAINERS_NUM": + "{}".format(len(trainer_endpoints)), + "POD_IP": + self.ctx.node.ip, + } + e.update(_gloo_envs) + log_file = "serverlog.{}".format(i) + self.add_container(envs=e, log_file=log_file) + + for i in range(trainer_num): + e = { + "PADDLE_NNODES": + "{}".format(self.job.replicas), + "PADDLE_PSERVERS_IP_PORT_LIST": + ",".join(server_endpoints), + "PADDLE_TRAINER_ENDPOINTS": + ",".join(trainer_endpoints), + "PADDLE_PORT": + trainer_endpoints[i + trainer_rank_offset].split(":")[1], + "PADDLE_ROLE": + "TRAINER", + "TRAINING_ROLE": + "TRAINER", + "PADDLE_TRAINER_ID": + "{}".format(i + trainer_rank_offset), + "PADDLE_TRAINERS_NUM": + "{}".format(len(trainer_endpoints)), + "POD_IP": + self.ctx.node.ip, + } + e.update(_gloo_envs) + log_file = "workerlog.{}".format(i) + self.add_container(envs=e, log_file=log_file) + ''' NEW VERSION + for i in range(server_num): + e = { + "PADDLE_PSERVER_ENDPOINTS": ",".join(server_endpoints), + "PADDLE_TRAINER_ENDPOINTS": ",".join(trainer_endpoints), + "PADDLE_ROLE": "PSERVER", + "PADDLE_RANK": "{}".format(i + server_rank_offset), + } + log_tag = "ps.{}".format(i) + self.add_container(envs=e, log_tag=log_tag) + + for i in range(trainer_num): + e = { + "PADDLE_PSERVER_ENDPOINTS": ",".join(server_endpoints), + "PADDLE_TRAINER_ENDPOINTS": ",".join(trainer_endpoints), + "PADDLE_ROLE": "TRAINER_CPU", + "PADDLE_RANK": "{}".format(i + trainer_rank_offset), + } + log_tag = "trainer.{}".format(i) + self.add_container(envs=e, log_tag=log_tag) + ''' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/watcher.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8e346e7908fc9ece77c72a3cba1608369b6be7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/controllers/watcher.py @@ -0,0 +1,98 @@ +# Copyright (c) 2022 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. + +from ..utils.nvsmi import get_gpu_process, get_gpu_util, get_gpu_info +import time +import os + +from threading import Thread + + +class Watcher(object): + + def __init__(self, ctx): + self.ctx = ctx + + self.interval = 30 + + self.gpu_util = [] + + # gpu log file + self.gpus = self.ctx.args.devices or self.ctx.node.device.labels + if len(self.gpus) > 0: + fn = os.path.join(self.ctx.args.log_dir, + "{}.gpu.log".format(self.ctx.args.job_id)) + os.makedirs(os.path.dirname(fn), exist_ok=True) + self.gpu_fd = open(fn, 'w') + else: + return + + # start + self.proc = Thread(target=self.watch) + self.proc.daemon = True + self.proc.start() + + def watch(self): + if not len(self.gpus) > 0: + return + + self._print_gpu_info() + + util_key = "index,utilization_gpu,memory_total,memory_used,memory_free,timestamp" + self.gpu_fd.write(util_key) + self.gpu_fd.write('\n') + + while not self.ctx.status.is_done(): + self._save_gpu_log(util_key) + time.sleep(self.interval) + + if hasattr(self, "gpu_fd"): + self.gpu_fd.close() + + def _print_gpu_info(self): + try: + info_key = "index,uuid,driver_version,name,gpu_serial,display_active,display_mode" + self.gpu_fd.write(info_key) + self.gpu_fd.write('\n') + for line in get_gpu_info(self.gpus): + self.gpu_fd.write(line.str(info_key)) + self.gpu_fd.write('\n') + self.gpu_fd.write('\n') + + process_key = "pid,process_name,gpu_uuid,gpu_name,used_memory" + self.gpu_fd.write(process_key) + self.gpu_fd.write('\n') + for line in get_gpu_process(self.gpus): + self.gpu_fd.write(line.str(process_key)) + self.gpu_fd.write('\n') + self.gpu_fd.write('\n') + + self.gpu_fd.flush() + except: + self.ctx.logger.warning("save gpu info failed") + + def _save_gpu_log(self, util_key): + try: + for line in get_gpu_util(self.gpus): + self.gpu_fd.write(line.str(util_key)) + self.gpu_fd.write('\n') + self.gpu_fd.flush() + except: + self.ctx.logger.warning("save gpu log failed") + + def stop(self): + if hasattr(self, "proc"): + # daemon without join + # self.proc.join() + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/container.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/container.py new file mode 100644 index 0000000000000000000000000000000000000000..8da5363915ced6ac8ece264af919112e2e042f53 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/container.py @@ -0,0 +1,206 @@ +# Copyright (c) 2022 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. + +from collections import OrderedDict +from paddle.distributed.launch.utils.process_context import ProcessContext + +from .status import Status + +import os, copy, sys + + +class Container(object): + ''' + TODO(kuizhiqing) A container can be run by process/thread or just a callable function + ''' + + def __init__(self, entrypoint=[], rank=-1, env={}): + self._entrypoint = entrypoint + self._rank = rank + self._out = None + self._err = None + self._env = env + self._proc = None + + self._retry: int = 3 + self._grace_period = 10 + + self._log_handler = None + self._shell = False + + @property + def entrypoint(self): + return self._entrypoint + + @entrypoint.setter + def entrypoint(self, entry): + self._entrypoint = entry + + @property + def rank(self): + return self._rank + + @rank.setter + def rank(self, r): + self._rank = r + + @property + def outfile(self): + return self._out + + @outfile.setter + def outfile(self, out): + self._out = out + + @property + def errfile(self): + return self._err + + @errfile.setter + def errfile(self, err): + self._err = err + + @property + def shell(self): + return self._shell + + @shell.setter + def shell(self, shell): + self._shell = shell + + def update_env(self, env={}, **kwargs): + env = {k: v for k, v in env.items() if isinstance(v, str)} + self._env.update(env) + + kwargs = {k: v for k, v in kwargs.items() if isinstance(v, str)} + self._env.update(kwargs) + + def _valide_env(self): + for k, v in self._env.items(): + assert isinstance(k, str) and isinstance( + v, str), 'env {}:{} must be str'.format(k, v) + + def _get_fd(self, pth): + if not pth: + return None + + try: + d = os.path.dirname(pth) + if not os.path.isdir(d): + os.makedirs(d, exist_ok=True) + return open(pth, 'a') + except: + return None + + def start(self): + if self._proc and self._proc.alive(): + return True + + self._valide_env() + + self._stdout = self._get_fd(self._out) or sys.stdout + if self._out == self._err: + self._stderr = self._stdout + elif self._err: + self._stderr = self._get_fd(self._err) or sys.stderr + + if not self._log_handler: + self._log_handler = open(self._out) + self._log_handler.seek(0, 2) + self._log_start_offset = self._log_handler.tell() + + self._proc = ProcessContext(self._entrypoint, + env=self._env, + out=self._stdout, + err=self._stderr, + shell=self._shell) + + self._proc.start() + + def terminate(self, force=False): + if self._log_handler: + self._log_handler.close() + self._log_handler = None + + if self._proc and self._proc.alive(): + return self._proc.terminate(force) + + def wait(self, timeout=None): + try: + self._proc.wait(timeout) + return True + except Exception: + return False + + @property + def exit_code(self): + return self._proc.exit_code() if self._proc else -1 + + @property + def status(self): + if not self._proc: + return Status.UNINIT + if self._proc.alive(): + return Status.RUNNING + elif self._proc.exit_code() == 0: + return Status.COMPLETED + else: + return Status.FAILED + + def __str__(self): + return 'Container rank {} status {} cmd {} code {} log {} \nenv {}'.format( + self._rank, + self.status, + self._entrypoint, + self.exit_code, + self.errfile, + self._env, + ) + + def logs(self, fn=None, offset=0, whence=1, limit=1000): + if not self._log_handler: + self._log_handler = open(self._out) + + if fn is None: + fn = sys.stdout + + try: + if offset != 0 or whence != 1: + if whence == 0 and offset < self._log_start_offset: + offset = self._log_start_offset + self._log_handler.seek(offset, whence) + + for _ in range(limit): + line = self._log_handler.readline() + if not line: + return False + fn.write(line) + return True + except: + return + + def tail(self, length=3000): + if not self._log_handler: + self._log_handler = open(self._out) + + try: + self._log_handler.seek(0, 2) + ed = self._log_handler.tell() + except: + pass + + if ed > length: + self.logs(offset=ed - length, whence=0) + else: + self.logs(offset=0, whence=0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/job.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/job.py new file mode 100644 index 0000000000000000000000000000000000000000..4bad1209c1859e8ab53b1bb77facb989e9536bd3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/job.py @@ -0,0 +1,81 @@ +# Copyright (c) 2022 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. + + +class JobMode: + COLLECTIVE = 'collective' + PS = 'ps' + HETER = 'heter' + + +class Job(object): + + def __init__(self, jid='default', mode=JobMode.COLLECTIVE, nnodes="1"): + self._mode = mode + self._id = jid + + self._replicas = 0 + self._replicas_min = self._replicas + self._replicas_max = self._replicas + self._elastic = False + + self.set_replicas(str(nnodes)) + + def __str__(self): + return "Job: {}, mode {}, replicas {}[{}:{}], elastic {}".format( + self.id, self.mode, self._replicas, self._replicas_min, + self._replicas_max, self.elastic) + + @property + def mode(self): + return self._mode + + @property + def id(self): + return self._id + + @property + def elastic(self): + return self._elastic + + @property + def replicas(self): + return self._replicas + + @property + def replicas_min(self): + return self._replicas_min + + @property + def replicas_max(self): + return self._replicas_max + + @replicas.setter + def replicas(self, replicas): + self._replicas = replicas + + def set_replicas(self, nnodes: str): + np = str(nnodes) if nnodes else '1' + + if ':' in np: + nps = np.split(':') + self._replicas_min, self._replicas_max = int(nps[0]), int(nps[1]) + self._replicas = self._replicas_max # default to max + + self._elastic = True + else: + self._replicas = int(np) + self._replicas_min, self._replicas_max = self._replicas, self._replicas + + self._elastic = False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/pod.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/pod.py new file mode 100644 index 0000000000000000000000000000000000000000..c99b2db547a268465458cff5bca3903b54f20ef1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/pod.py @@ -0,0 +1,206 @@ +# Copyright (c) 2022 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. + +from collections import OrderedDict +from .container import Container + +from .status import Status + +import random +import time + + +class PodSepc(object): + + def __init__(self): + self._name = ''.join( + random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(6)) + + # by controller + self._init_containers: List[Container] = [] + self._containers: List[Container] = [] + + #self.resource: Resource = None + #self.status: Status = None + + self._rank = -1 + self._init_timeout = None + self._restart = -1 + self._replicas = 0 # number of containers + self._exit_code = 0 + + +class Pod(PodSepc): + + def __init__(self): + super().__init__() + + def __str__(self): + return "Pod: {}, replicas {}, status {}".format(self.name, + self.replicas, + self.status) + + def failed_container(self): + cs = [] + for c in self._containers: + if c.status == Status.FAILED: + cs.append(c) + return cs + + @property + def name(self): + return self._name + + @property + def replicas(self): + return self._replicas + + @replicas.setter + def replicas(self, r): + self._replicas = max(r, 1) + + @property + def rank(self): + return self._rank + + @rank.setter + def rank(self, r): + self._rank = r + + @property + def restart(self): + return self._restart + + @property + def containers(self): + return self._containers + + def add_container(self, c): + c.rank = len(self._containers) + self._containers.append(c) + + @property + def init_containers(self): + return self._init_containers + + def add_init_container(self, c): + c.rank = len(self._init_containers) + self._init_containers.append(c) + + @property + def exit_code(self): + for c in self._containers: + if c.exit_code != 0: + return c.exit_code + return 0 + + def deploy(self): + # init container should stop before run containers + for i in self._init_containers: + i.start() + i.wait(self._init_timeout) + + for c in self._containers: + c.start() + + self._restart += 1 + + def stop(self, sigint=15, timeout=None): + for c in self._containers: + if isinstance(sigint, int) and timeout is None: + c.send_signal(sigint) + else: + c.terminate() + + if isinstance(timeout, int): + if not self.join(timeout): + for c in self._containers: + c.terminate(force=True) + return False + else: + return True + + def join(self, timeout=None): + for c in self._containers: + if not c.wait(timeout): + return False + return True + + @property + def status(self): + if self.is_failed(): + return Status.FAILED + + if self.is_completed(): + return Status.COMPLETED + + if self.is_running(): + return Status.RUNNING + + return Status.READY + + def reset(self): + self._init_containers = [] + self._containers = [] + + def is_failed(self): + for c in self._containers: + if c.status == Status.FAILED: + return True + return False + + def is_completed(self): + for c in self._containers: + if c.status != Status.COMPLETED: + return False + return True + + def is_running(self): + for c in self._containers: + if c.status != Status.RUNNING: + return False + return True + + def logs(self, idx=None): + if idx is None: + self._containers[0].logs() + else: + self._containers[idx].logs() + + def tail(self, idx=None): + if idx is None: + self._containers[0].tail() + else: + self._containers[idx].tail() + + def watch(self, + all_list=[Status.COMPLETED], + any_list=[Status.FAILED], + interval=1, + timeout=-1): + ''' + watch return if any container status in any_list + or all container status in all_list + ''' + end = time.time() + timeout + while timeout < 0 or time.time() < end: + for c in self._containers: + if c.status in any_list: + return c.status + + s = [c.status for c in self._containers] + if len(set(s)) == 1 and s[0] in all_list: + return s[0] + + time.sleep(interval) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/status.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/status.py new file mode 100644 index 0000000000000000000000000000000000000000..88fd09bbf2267a8f6aa69857d982ba25d787259b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/job/status.py @@ -0,0 +1,24 @@ +# Copyright (c) 2022 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. + + +class Status(object): + UNINIT = "uninit" + READY = "ready" + RUNNING = "running" + FAILED = "failed" + TERMINATING = "terminating" + RESTARTING = "restarting" + UNKNOWN = "unknown" + COMPLETED = "completed" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/main.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/main.py new file mode 100644 index 0000000000000000000000000000000000000000..fccb352c2a3cde863e49995373db8d291a99a3e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/main.py @@ -0,0 +1,289 @@ +# Copyright (c) 2022 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. + +from .context import Context + + +def launch(): + """ + Paddle distribution training entry ``python -m paddle.distributed.launch``. + + Usage: + .. code-block:: bash + :name: code-block-bash1 + + python -m paddle.distributed.launch [-h] [--master MASTER] [--rank RANK] + [--log_level LOG_LEVEL] [--nnodes NNODES] + [--nproc_per_node NPROC_PER_NODE] [--log_dir LOG_DIR] + [--run_mode RUN_MODE] [--job_id JOB_ID] [--devices DEVICES] + [--host HOST] [--servers SERVERS] [--trainers TRAINERS] + [--trainer_num TRAINER_NUM] [--server_num SERVER_NUM] + [--gloo_port GLOO_PORT] [--with_gloo WITH_GLOO] + [--max_restart MAX_RESTART] [--elastic_level ELASTIC_LEVEL] + [--elastic_timeout ELASTIC_TIMEOUT] + training_script ... + + + Base Parameters: + - ``--master``: The master/rendezvous server, support http:// and etcd://, default with http://. e.g., ``--master=127.0.0.1:8080``. Default ``--master=None``. + + - ``--rank``: The rank of the node, can be auto assigned by master. Default ``--rank=-1``. + + - ``--log_level``: The log level to set for logging.setLevel which can be CRITICAL/ERROR/WARNING/INFO/DEBUG/NOTSET, case insensitive. Default ``--log_level=INFO``. + + - ``--nnodes``: The number of nodes for a distributed job, it can be a range in elastic mode, e.g., ``--nnodes=2:3``. Default ``--nnodes=1``. + + - ``--nproc_per_node``: The number of processes to launch on a node. In gpu training, it should be less or equal to the gpus number of you system. e.g., ``--nproc_per_node=8`` + + - ``--log_dir``: The path for each process's log. e.g., ``--log_dir=output_dir``. Default ``--log_dir=log``. + + - ``--run_mode``: The run mode of job, can be:collective/ps/ps-heter. e.g., ``--run_mode=ps``. Default ``--run_mode=collective``. + + - ``--job_id``: The job unique id, it affects the log files' name. e.g., ``--job_id=job1``. Default ``--job_id=default``. + + - ``--devices``: The selected accelerate devices on nodes, can be gpu/xpu/npu/mlu etc.. e.g., ``--devices=0,1,2,3`` will launch four training processes each bound to one device. + + - ``training_script``: The full path to the single GPU training program/script to be launched in parallel, followed by all the arguments for the training script. e.g., ``training.py`` + + - ``training_script_args``: The args of training_script. e.g., ``--lr=0.1`` + + Collective Parameters: + - ``--ips``: [DEPRECATED] Paddle cluster nodes ips, e.g., ``--ips=192.168.0.16,192.168.0.17``. Default ``--ips=127.0.0.1``. + + Parameter-Server Parameters: + - ``--servers``: User defined servers ip:port, e.g., ``--servers="192.168.0.16:6170,192.168.0.17:6170"`` + + - ``--trainers``: User defined trainers ip:port, e.g., ``--trainers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172"`` + + - ``--workers``: [DEPRECATED] The same as trainers. + + - ``--trainer_num``: Number of trainers on each node, can be 0. + + - ``--worker_num``: [DEPRECATED] The same as trainer_num. + + - ``--server_num``: Number of servers on each node, can be 0. + + - ``--heter_workers``: User defined heter workers ip1:port1;ip2:port2, e.g., ``--heter_workers="192.168.0.16:6172;192.168.0.17:6172"`` + + - ``--heter_worker_num``: Number of heter_workers in each stage (It recommend to set when in the emulated distributed environment using single node) + + - ``--heter_devices``: Type of heter_device in each stage + + - ``--gloo_port``: Gloo http Port. Default ``--gloo_port=6767``. + + - ``--with_gloo``: Using gloo or not. Default ``--with_gloo=0``. + + Elastic Parameters: + - ``--max_restart``: The maximum restart times for an elastic job. Default ``--max_restart=3``. + + - ``--elastic_level``: The elastic level: -1: disable, 0: failed exit, peers hold, 1: internal restart. Default ``--elastic_level=-1``. + + - ``--elastic_timeout``: Seconds to wait before elastic job begin to train. Default ``--elastic_timeout=30``. + + IPU Parameters: + IPU distributed launch only requires and allowes three arguments ``--devices``, ``training_script`` and ``training_script_args``. + The ``--devices`` is the number of IPU devices. e.g., ``--devices=4`` will launch the training program with four IPU devices. + The ``training_script`` is only allowed to set as ``ipu``. + The ``training_script_args`` includes arguments required by IPU distributed launch and illustrated as below. + ``Examples 10`` has provided a example of paddle.distributed.launch with IPUs. + + - ``--hosts``: The hosts for IPU distributd training. Each host is able to include multiple processes. + + - ``--nproc_per_host``: The number of processes launched per host. Each process is able to include multiple replicas. + + - ``--ipus_per_replica``: The number of IPUs requested per replica. Each replica is able to include multiple IPUs. + + - ``--ipu_partition``: The partition name of IPU devices. + + - ``--vipu_server``: The ip of the IPU device manager. + + - ``training_script``: The full path to the IPU distributed training program/script to be launched in parallel. e.g., ``training.py``. + + - ``training_script_args``: The args of the IPU distributed training program/script. e.g., ``--lr=0.1``. + + Returns: + - ``None`` + + Examples 0 (master, ip/port auto detection): + .. code-block:: bash + :name: code-block-example-bash0 + + # For training on multi node, run the following command in one of the nodes + + python -m paddle.distributed.launch --nnodes 2 train.py + + # Then the following info will be print + + # Copy the following command to other nodes to run. + # -------------------------------------------------------------------------------- + # python -m paddle.distributed.launch --master 10.0.0.1:38714 --nnodes 2 train.py + # -------------------------------------------------------------------------------- + + # Follow the instruction above and paste the command in other nodes can launch a multi nodes training job. + + # There are two ways to launch a job with the same command for multi nodes training + # 1) using the following command in every nodes, make sure the ip is one of the training node and the port is available on that node + # python -m paddle.distributed.launch --master 10.0.0.1:38714 --nnodes 2 train.py + # 2) using the following command in every nodes with a independent etcd service + # python -m paddle.distributed.launch --master etcd://10.0.0.1:2379 --nnodes 2 train.py + + # This functionality works will for both collective and ps mode and even with other arguments. + + + Examples 1 (collective, single node): + .. code-block:: bash + :name: code-block-example-bash1 + + # For training on single node using 4 gpus. + + python -m paddle.distributed.launch --devices=0,1,2,3 train.py --lr=0.01 + + Examples 2 (collective, multi node): + .. code-block:: bash + :name: code-block-example-bash2 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 + + # On 192.168.0.16: + + python -m paddle.distributed.launch --devices=0,1,2,3 --master=192.168.0.16:8090 train.py --lr=0.01 + + # On 192.168.0.17: + python -m paddle.distributed.launch --devices=0,1,2,3 --master=192.168.0.16:8090 train.py --lr=0.01 + + Examples 3 (ps, cpu, single node): + .. code-block:: bash + :name: code-block-example-bash3 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers. + + python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01 + + Examples 4 (ps, cpu, multi node): + .. code-block:: bash + :name: code-block-example-bash4 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers. + + # On 192.168.0.16: + + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + # Or with master, the following command run 2 server and 2 trainer on each node. + + python -m paddle.distributed.launch --master 192.168.0.16:9090 --server_num=2 --trainer_num=2 --nnodes 2 train.py + + + Examples 5 (ps, gpu, single node): + .. code-block:: bash + :name: code-block-example-bash5 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, each worker use single gpu. + + export CUDA_VISIBLE_DEVICES=0,1,2,3 + python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01 + + Examples 6 (ps, gpu, multi node): + .. code-block:: bash + :name: code-block-example-bash6 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers. + + # On 192.168.0.16: + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01 + + Examples 7 (ps-heter, cpu + gpu, single node): + .. code-block:: bash + :name: code-block-example-bash7 + + # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, two workers use gpu, two workers use cpu. + + export CUDA_VISIBLE_DEVICES=0,1 + python -m paddle.distributed.launch --server_num=2 --worker_num=2 --heter_worker_num=2 train.py --lr=0.01 + + Examples 8 (ps-heter, cpu + gpu, multi node): + .. code-block:: bash + :name: code-block-example-bash8 + + # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server, 1 gpu worker, 1 cpu worker. + + # On 192.168.0.16: + + export CUDA_VISIBLE_DEVICES=0 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01 + + # On 192.168.0.17: + + export CUDA_VISIBLE_DEVICES=0 + python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01 + + Examples 9 (elastic): + .. code-block:: bash + :name: code-block-example-bash9 + + # With the following command, the job will begin to run immediately if 4 nodes are ready, + # or it will run after elastic_timeout if only 2 or 3 nodes ready + python -m paddle.distributed.launch --master etcd://10.0.0.1:2379 --nnodes 2:4 train.py + + # once the number of nodes changes between 2:4 during training, the strategy holds + + Examples 10 (ipu): + .. code-block:: bash + :name: code-block-example-bash10 + + # With the following command, the job will begin to run the distributhed program with IPUs + # Require `devices` as the number of IPUs + # Require `training_script` to be set as `ipu` + # Require `training_script_args` as the arguments of IPU distributed training instead of the arguments of the training program/script + # Please Check the `IPU Parameters` for details + python -m paddle.distributed.launch --devices 4 ipu --hosts=localhost --nproc_per_host=2 --ipus_per_replica=1 --ipu_partition=pod16 --vipu_server=127.0.0.1 train.py + + """ + + # initialize the context to run + ctx = Context() + + if ctx.is_legacy_mode(): + + # legacy mode + from paddle.distributed.fleet import launch + launch.launch() + + else: + + from . import controllers + + # initialize the selected controller + c = controllers.init(ctx) + + # run the pods + c.run() + + # manager or just wait pod + c.finalize() + + +if __name__ == "__main__": + launch() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c82fa55de430a7849ae5408a10758af7f579ad52 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/__init__.py @@ -0,0 +1,81 @@ +# Copyright (c) 2022 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. + +import six +import os + +__all__ = [] + + +# print configuration after args are well filled in controller init +def log(ctx): + ctx.logger.info("----------- Configuration ----------------------") + for arg, value in sorted(six.iteritems(vars(ctx.args))): + ctx.logger.info("%s: %s" % (arg, value)) + ctx.logger.info("--------------------------------------------------") + + +def process_args(ctx): + # reset device by args + #argdev = ctx.args.gpus or ctx.args.xpus or ctx.args.npus + argdev = ctx.args.devices + if argdev: + for d in argdev.split(','): + if d not in ctx.node.device.labels: + ctx.logger.error( + f'Device not found {d} from {argdev} for setting {ctx.node.device.labels}' + ) + + if ctx.args.ips: + ips = ctx.args.ips.split(',') + if '127.0.0.1' in ips and len(ips) != 1: + raise "127.0.0.1 in ips is not allowed in multi-nodes." + + +def collective_compatible(ctx): + if 'PADDLE_TRAINER_ENDPOINTS' in ctx.envs: + eps = ctx.envs['PADDLE_TRAINER_ENDPOINTS'].split(',') + hosts = set([h.split(':')[0] for h in eps]) + ctx.args.master = eps[0] if ':' in eps[0] else '{}:6768'.format(eps[0]) + ctx.args.nnodes = len(hosts) + ctx.logger.info( + 'args reset by env PADDLE_TRAINER_ENDPOINTS\n{}'.format(eps)) + + if 'DISTRIBUTED_TRAINER_ENDPOINTS' in ctx.envs: + eps = ctx.envs['DISTRIBUTED_TRAINER_ENDPOINTS'].split(',') + hosts = set([h.split(':')[0] for h in eps]) + ctx.args.master = eps[0] + ctx.args.nnodes = len(hosts) + ctx.logger.info( + 'args reset by env DISTRIBUTED_TRAINER_ENDPOINTS\n{}'.format(eps)) + + +def rewrite_host_ip(ctx): + if ctx.args.host is not None and "." in ctx.args.host: + ctx.logger.warning('Host ip reset to {}'.format(ctx.args.host)) + ctx.node.ip = ctx.args.host + + +def test_mode(ctx): + if ctx.args.training_script == 'run_check': + ctx.logger.info('Paddle Distributed Test begin...') + if int(ctx.args.nnodes) < 2: + ctx.args.nnodes = 2 + ctx.args.training_script = '{}/test.py'.format( + os.path.dirname(__file__)) + + +enabled_plugins = [ + test_mode, collective_compatible, rewrite_host_ip, process_args +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/test.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/test.py new file mode 100644 index 0000000000000000000000000000000000000000..c51ff513efb57e30e80d208552fa9ce83e3ba843 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/plugins/test.py @@ -0,0 +1,100 @@ +# Copyright (c) 2022 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. + +import numpy as np +import paddle +from paddle.distributed import fleet +from paddle.vision.models import ResNet +from paddle.vision.models.resnet import BottleneckBlock +from paddle.io import Dataset, BatchSampler, DataLoader + +base_lr = 0.1 +momentum_rate = 0.9 +l2_decay = 1e-4 + +epoch = 3 +batch_num = 1 +batch_size = 1 +class_dim = 102 + + +# define a random dataset +class RandomDataset(Dataset): + + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([3, 224, 224]).astype('float32') + label = np.random.randint(0, class_dim - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + +def optimizer_setting(parameter_list=None): + optimizer = paddle.optimizer.Momentum( + learning_rate=base_lr, + momentum=momentum_rate, + weight_decay=paddle.regularizer.L2Decay(l2_decay), + parameters=parameter_list) + return optimizer + + +def train_resnet(): + fleet.init(is_collective=True) + + resnet = ResNet(BottleneckBlock, 18, num_classes=class_dim) + optimizer = optimizer_setting(parameter_list=resnet.parameters()) + optimizer = fleet.distributed_optimizer(optimizer) + resnet = fleet.distributed_model(resnet) + + dataset = RandomDataset(batch_num * batch_size) + train_loader = DataLoader(dataset, + batch_size=batch_size, + shuffle=True, + drop_last=True, + num_workers=2) + + print("Distributed training start...") + for eop in range(epoch): + resnet.train() + + for batch_id, data in enumerate(train_loader()): + img, label = data + label.stop_gradient = True + + out = resnet(img) + loss = paddle.nn.functional.cross_entropy(input=out, label=label) + avg_loss = paddle.mean(x=loss) + acc_top1 = paddle.metric.accuracy(input=out, label=label, k=1) + acc_top5 = paddle.metric.accuracy(input=out, label=label, k=5) + + avg_loss.backward() + optimizer.step() + resnet.clear_gradients() + + print("[Epoch %d, batch %d] loss: %.5f, acc1: %.5f, acc5: %.5f" % + (eop, batch_id, avg_loss, acc_top1, acc_top5)) + + print("Distributed training completed") + + +if __name__ == '__main__': + import os + nnodes = os.getenv('PADDLE_NNODES') + cn = os.getenv('PADDLE_LOCAL_SIZE') + print(f"Prepare distributed training with {nnodes} nodes {cn} cards") + train_resnet() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_client.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a66ca800c58c22a289d0a36c0076a50ec433f66d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_client.py @@ -0,0 +1,95 @@ +# Copyright (c) 2022 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. + +import requests +import time + + +class KVClient(object): + + def __init__(self, endpoint='localhost:2379'): + self.endpoint = endpoint if endpoint.startswith( + "http://") else "http://{}".format(endpoint) + + def put(self, key, value): + key = key if key.startswith('/') else "/{}".format(key) + u = "{}{}".format(self.endpoint, key) + try: + r = requests.post(u, data=value, timeout=3) + if r.status_code == 200: + return True + else: + return False + except: + return False + + def get(self, key): + key = key if key.startswith('/') else "/{}".format(key) + u = "{}{}".format(self.endpoint, key) + try: + r = requests.get(u, timeout=3) + if r.status_code == 200: + ret = r.json() + return ret.get(key, '') + else: + return "error" + except: + return "" + + def get_prefix(self, key): + key = key if key.startswith('/') else "/{}".format(key) + u = "{}{}".format(self.endpoint, key) + try: + r = requests.get(u, timeout=3) + if r.status_code == 200: + return r.json() + except: + return "" + + def delete(self, key): + key = key if key.startswith('/') else "/{}".format(key) + u = "{}{}".format(self.endpoint, key) + try: + r = requests.delete(u, timeout=3) + if r.status_code == 200: + return True + else: + return False + except: + return False + + def wait_server_ready(self, timeout=3): + end = time.time() + timeout + while time.time() < end: + if self.get("/healthy") == "ok": + return True + + +if __name__ == '__main__': + cli = PKVClient("http://localhost:8090") + data = {"/workers/1": "rank1", "/workers/2": "rank2"} + for k, v in data.items(): + cli.put(k, v) + x = cli.get_prefix("/workers") + print(x) + for k, v in data.items(): + assert x[k] == v + + cli.put("key", "value") + print(cli.get("key")) + assert cli.get("key") == "value" + cli.delete("key") + print(cli.get("/key")) + print(cli.get("/healthy")) + assert cli.get("/healthy") == "ok" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf5685c988b7de9541899183b1b1cce161e88eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/kv_server.py @@ -0,0 +1,124 @@ +# Copyright (c) 2022 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. + +from http.server import HTTPServer +import http.server as SimpleHTTPServer + +from multiprocessing import Process + +import threading +import json + + +class KVHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): + + def do_GET(self): + with self.server.kv_lock: + ret = {} + for k, v in self.server.kv.items(): + if k.startswith(self.path): + ret[k] = v.decode(encoding="utf-8") + if ret: + self.output(200, json.dumps(ret).encode("utf-8")) + else: + self.output(404) + + def do_PUT(self): + self.do_POST() + + def do_POST(self): + content_length = int(self.headers['Content-Length'] or 0) + try: + value = self.rfile.read(content_length) + with self.server.kv_lock: + self.server.kv[self.path] = value + self.output(200) + return + except: + self.output(500) + + def do_DELETE(self): + with self.server.kv_lock: + if self.path in self.server.kv: + del self.server.kv[self.path] + self.output(200) + else: + self.output(404) + + def output(self, code, value=''): + self.send_response(code) + self.send_header("Content-Length", len(value)) + self.send_header("Content-Type", "application/json; charset=utf8") + self.end_headers() + if value: + self.wfile.write(value) + + def log_message(self, format, *args): + return + + +class KVServer(HTTPServer, object): + + def __init__(self, port): + super(KVServer, self).__init__(('', port), KVHandler) + self.kv_lock = threading.Lock() + self.kv = {'/healthy': b'ok'} + self.port = port + self.stopped = False + self.started = False + + def start(self): + self.listen_thread = threading.Thread(target=self.serve_forever) + self.listen_thread.start() + self.started = True + + def stop(self): + self.shutdown() + self.listen_thread.join() + self.server_close() + self.stopped = True + + +class PKVServer(): + + def __init__(self, port): + self._server = KVServer(port) + + def start(self): + self.proc = Process(target=self._server.start) + self.proc.daemon = True + self.proc.start() + + def stop(self): + self._server.stop() + self.proc.join() + + @property + def started(self): + return self._server.started + + @property + def stopped(self): + return self._server.stopped + + +if __name__ == '__main__': + #kv = PKVServer(8090) + kv = KVServer(8090) + kv.start() + import time + + #print("serve at 8090 for 600 s") + + time.sleep(600) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/nvsmi.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/nvsmi.py new file mode 100644 index 0000000000000000000000000000000000000000..dc07fbc1d21cb1b3e30baeb8db6441de044ced39 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/nvsmi.py @@ -0,0 +1,118 @@ +# Copyright (c) 2022 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. + +import subprocess +import shlex +import os +import json +import shutil + + +class Info(object): + + def __repr__(self): + return str(self.__dict__) + + def json(self): + return json.dumps(self.__dict__) + + def dict(self): + return self.__dict__ + + def str(self, keys=None): + if keys is None: + keys = self.__dict__.keys() + + if isinstance(keys, str): + keys = keys.split(',') + + values = [str(self.__dict__.get(k, '')) for k in keys] + return ",".join(values) + + +def query_smi(query=None, query_type="gpu", index=None, dtype=None): + """ + query_type: gpu/compute + """ + + if not has_nvidia_smi(): + return [] + + cmd = ["nvidia-smi", "--format=csv,noheader,nounits"] + if isinstance(query, list) and query_type == "gpu": + cmd.extend(["--query-gpu={}".format(",".join(query))]) + elif isinstance(query, list) and query_type.startswith("compute"): + cmd.extend(["--query-compute-apps={}".format(",".join(query))]) + else: + return + + if isinstance(index, list) and len(index) > 0: + cmd.extend(["--id={}".format(",".join(index))]) + if not isinstance(dtype, list) or len(dtype) != len(query): + dtype = [str] * len(query) + + output = subprocess.check_output(cmd, timeout=3) + lines = output.decode("utf-8").split(os.linesep) + ret = [] + for line in lines: + if not line: + continue + info = Info() + for k, v, d in zip(query, line.split(", "), dtype): + setattr(info, k.replace(".", "_"), d(v)) + ret.append(info) + return ret + + +def get_gpu_info(index=None): + q = "index,uuid,driver_version,name,gpu_serial,display_active,display_mode".split( + ",") + d = [int, str, str, str, str, str, str] + index = index if index is None or isinstance( + index, list) else str(index).split(",") + + return query_smi(q, index=index, dtype=d) + + +def get_gpu_util(index=None): + q = "index,utilization.gpu,memory.total,memory.used,memory.free,timestamp".split( + ",") + d = [int, int, int, int, int, str] + index = index if index is None or isinstance( + index, list) else str(index).split(",") + + return query_smi(q, index=index, dtype=d) + + +def get_gpu_process(index=None): + q = "pid,process_name,gpu_uuid,gpu_name,used_memory".split(",") + d = [int, str, str, str, int] + index = index if index is None or isinstance( + index, list) else str(index).split(",") + + return query_smi(q, index=index, query_type="compute", dtype=d) + + +def has_nvidia_smi(): + return shutil.which("nvidia-smi") + + +if __name__ == '__main__': + print(get_gpu_info(0)) + print(get_gpu_util(0)) + print(get_gpu_process(0)) + + u = get_gpu_util() + for i in u: + print(i.str()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/process_context.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/process_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5d8505aa66eb38fc326892d1e23bc9f212fd40c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/launch/utils/process_context.py @@ -0,0 +1,86 @@ +# Copyright (c) 2022 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. + +import subprocess +import os, sys, signal, time + + +class ProcessContext(object): + + def __init__(self, + cmd, + env=os.environ, + out=sys.stdout, + err=sys.stderr, + group=True, + preexec_fn=None, + shell=False): + self._cmd = cmd + self._env = env + self._preexec_fn = preexec_fn + self._stdout = out + self._stderr = err + self._group = group if os.name != 'nt' else False + self._proc = None + self._code = None + self._shell = shell + + def _start(self): + pre_fn = os.setsid if self._group else None + self._proc = subprocess.Popen(self._cmd, + env=self._env, + stdout=self._stdout, + stderr=self._stderr, + preexec_fn=self._preexec_fn or pre_fn, + shell=self._shell) + + def _close_std(self): + try: + if not self._stdout.isatty(): + self._stdout.close() + + if not self._stderr.isatty(): + self._stderr.close() + except: + pass + + def alive(self): + return self._proc and self._proc.poll() is None + + def exit_code(self): + return self._proc.poll() if self._proc else None + + def start(self): + self._start() + + def terminate(self, force=False, max_retry=3): + for i in range(max_retry): + if self.alive(): + if self._group: + os.killpg(os.getpgid(self._proc.pid), signal.SIGTERM) + else: + self._proc.terminate() + time.sleep(0.2) + else: + break + + if force and self.alive(): + self._proc.kill() + + self._close_std() + + return self.alive() + + def wait(self, timeout=None): + self._proc.wait(timeout) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f87fe885824b801ed632d2fb3b021cbb3b7101b5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/__init__.py @@ -0,0 +1,16 @@ +# 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. + +from .metrics import init_metric # noqa: F401 +from .metrics import print_auc # noqa: F401 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/metrics.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4029734545f9d43a6c5d941133d73516cd6ac626 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/metric/metrics.py @@ -0,0 +1,142 @@ +# 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. + +import sys +import yaml +import paddle.fluid as fluid +import logging +from paddle.distributed.utils.log_utils import get_logger + +__all__ = [] +logger = get_logger(logging.INFO, name="metrics") + + +# read metric config from yaml and init MetricMsg in fleet_wrapper +def init_metric(metric_ptr, + metric_yaml_path, + cmatch_rank_var="", + mask_var="", + uid_var="", + phase=-1, + cmatch_rank_group="", + ignore_rank=False, + bucket_size=1000000): + yaml_fobj = open(metric_yaml_path) + if sys.version.startswith('2.7.13'): + content = yaml.load(yaml_fobj) + else: + content = yaml.load(yaml_fobj, Loader=yaml.FullLoader) + + print("yaml metric config: \n") + print(content) + + metric_runner_list = content['monitors'] + if not metric_runner_list: + metric_runner_list = [] + + for metric_runner in metric_runner_list: + is_join = metric_runner['phase'] == 'JOINING' + phase = 1 if is_join else 0 + + if metric_runner['method'] == 'AucCalculator': + metric_ptr.init_metric(metric_runner['method'], + metric_runner['name'], + metric_runner['label'], + metric_runner['target'], cmatch_rank_var, + mask_var, uid_var, phase, cmatch_rank_group, + ignore_rank, bucket_size) + elif metric_runner['method'] == 'MultiTaskAucCalculator': + metric_ptr.init_metric( + metric_runner['method'], metric_runner['name'], + metric_runner['label'], metric_runner['target'], + metric_runner['cmatch_var'], mask_var, uid_var, phase, + metric_runner['cmatch_group'], ignore_rank, bucket_size) + elif metric_runner['method'] == 'CmatchRankAucCalculator': + metric_ptr.init_metric( + metric_runner['method'], metric_runner['name'], + metric_runner['label'], metric_runner['target'], + metric_runner['cmatch_var'], mask_var, uid_var, phase, + metric_runner['cmatch_group'], metric_runner['ignore_rank'], + bucket_size) + elif metric_runner['method'] == 'MaskAucCalculator': + metric_ptr.init_metric(metric_runner['method'], + metric_runner['name'], + metric_runner['label'], + metric_runner['target'], cmatch_rank_var, + metric_runner['mask'], uid_var, phase, + cmatch_rank_group, ignore_rank, bucket_size) + elif metric_runner['method'] == 'CmatchRankMaskAucCalculator': + metric_ptr.init_metric( + metric_runner['method'], metric_runner['name'], + metric_runner['label'], metric_runner['target'], + metric_runner['cmatch_var'], metric_runner['mask'], uid_var, + phase, metric_runner['cmatch_group'], + metric_runner['ignore_rank'], bucket_size) + elif metric_runner['method'] == 'WuAucCalculator': + metric_ptr.init_metric(metric_runner['method'], + metric_runner['name'], + metric_runner['label'], + metric_runner['target'], cmatch_rank_var, + mask_var, metric_runner['uid'], phase, + cmatch_rank_group, ignore_rank, bucket_size) + else: + metric_ptr.init_metric(metric_runner['method'], + metric_runner['name'], + metric_runner['label'], + metric_runner['target'], cmatch_rank_var, + mask_var, phase, cmatch_rank_group, + ignore_rank, bucket_size) + + +def print_metric(metric_ptr, name): + """ + print the metric value. Print directly in back-end + """ + if name.find("wuauc") != -1: + metric = metric_ptr.get_wuauc_metric_msg(name) + monitor_msg = "%s: User Count=%.0f INS Count=%.0f UAUC=%.6f WUAUC=%.6f "\ + % (name, metric[0], metric[1], metric[4], metric[5]) + else: + metric = metric_ptr.get_metric_msg(name) + monitor_msg = "%s: AUC=%.6f BUCKET_ERROR=%.6f MAE=%.6f RMSE=%.6f "\ + "Actual CTR=%.6f Predicted CTR=%.6f COPC=%.6f INS Count=%.0f"\ + % (name, metric[0], metric[1], metric[2], metric[3], metric[4], + metric[5], metric[6], metric[7]) + # logger.info(monitor_msg) + return monitor_msg + + +def print_auc(metric_ptr, is_day, phase="all"): + """ + print metric according to stage and phase + """ + if is_day is True: + stage = "day" + stage_num = -1 + else: + stage = "pass" + stage_num = 1 if phase == "join" else 0 + metric_results = [] + + name_list = metric_ptr.get_metric_name_list(stage_num) + if phase == "all": + for name in name_list: + if name.find(stage) != -1: + metric_results.append(print_metric(metric_ptr, name=name)) + else: + for name in name_list: + if name.find(stage) != -1 and name.find(phase) != -1: + metric_results.append(print_metric(metric_ptr, name=name)) + + return metric_results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cde6a8a97f0eb1e75675ae73ba4883895e1022ce --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/models/moe/utils.py @@ -0,0 +1,231 @@ +# Copyright (c) 2022 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. + +from paddle.fluid import core +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode, _in_legacy_dygraph, in_dygraph_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops + + +def _number_count(numbers, upper_range): + """ + calculate the expert count according to the gate index. + Args: + numbers (Tensor): Tensor. The input gate index whose data type should be int32 or int64. + upper_range (int): The number of the experts. + Returns: + out (Tensor): The output expert count. + Examples: + .. code-block:: python + # required: distributed + import paddle + + numbers = [ + [0, 2], + [0, 2] + ] + upper_range = 6 + numbers = paddle.to_tensor(numbers, dtype="int32") + number_count = paddle.distributed.utils.number_count(numbers, upper_range) + print(number_count) # the result: [2, 0, 2, 0, 0, 0] + """ + if in_dygraph_mode(): + return _legacy_C_ops.number_count(numbers, 'upper_range', upper_range) + elif _in_legacy_dygraph(): + return core.ops.number_count(numbers, 'upper_range', upper_range) + else: + op_type = 'number_count' + + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=numbers.dtype) + + helper.append_op(type=op_type, + inputs={'numbers': numbers}, + outputs={'Out': out}, + attrs={'upper_range': upper_range}) + return out + + +def _assign_pos(x, cum_count): + """ + Assign pos decides which tokens should be fetched belong to + specially expert orderingly. + + Args: + x (Tensor): Tensor. Every element in the list must be a Tensor whose data type + should be float16, float32, float64, int32 or int64. + cum_count (Tensor): The cumulative sum tokens of counters. Every element in the list must be a Tensor whose + data type should be int64. + + Returns: + out (Tensor): Assemble numbers in the order of counters. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + number_count = [2, 0, 2, 0] + numbers = [ + [0, 2], + [0, 2] + ] + number_count = paddle.to_tensor(number_count) + numbers = paddle.to_tensor(numbers, dtype="int32") + num_cum = paddle.cumsum(number_count) + pos = paddle.distributed.utils.assign_pos(x=numbers, cum_count=num_cum) + print(pos) # the result: (2, 0, 3, 1) + """ + if in_dygraph_mode(): + return _legacy_C_ops.assign_pos(x, cum_count, cum_count[-1]) + elif _in_legacy_dygraph(): + return core.ops.assign_pos(x, cum_count, cum_count[-1]) + else: + op_type = 'assign_pos' + + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=cum_count.dtype) + + helper.append_op(type=op_type, + inputs={ + 'X': [x], + 'cum_count': [cum_count], + "eff_num_len": [cum_count[-1]] + }, + outputs={'Out': [out]}) + return out + + +def _random_routing(topk_idx, topk_value, prob, topk=2): + r""" + random routing topk gate idx + ``` + out = topk_idx + for i in len(topk_idx): + if topk * value[i][topk-1] < prob[i]: + out[i][topk-1] = -1 + ``` + Args: + topk_idx: gate idx, shape=(N, topk) + topk_value: values, shape = topk_idx.shape + prob: random prob, shape=(topk_idx.shape[0],) + """ + if topk == 2: + if in_dygraph_mode(): + return _legacy_C_ops.random_routing(prob, topk_value, topk_idx) + elif _in_legacy_dygraph(): + return core.ops.random_routing(prob, topk_value, topk_idx) + else: + raise RuntimeError("Not supporting static mode now") + else: + raise RuntimeError("only topk=2 is supported now") + + +def _limit_by_capacity(expert_count, capacity, n_worker): + """ + limit the expert count by capacity. + Args: + expert_count (Tensor): Tensor. The input expert count whose data type should be int32 or int64. + capacity (Tensor): Tensor. The input capacity whose data type should be int32 or int64 and the elements of capacity should be the same with expert_count.numel()/n_work. + n_work (int): The number of the works. + Returns: + out (Tensor): The output expert count limit by capacity. + Examples: + .. code-block:: python + # required: distributed + import paddle + expert_count = [1, 2, 2, 8, 3, 6] + capacity = [5, 5, 5] + n_work = 2 + expert_count = paddle.to_tensor(expert_count, dtype="int32") + capacity = paddle.to_tensor(capacity, dtype="int32") + out = paddle.distributed.utils.limit_by_capacity(expert_count, capacity, n_work) + print(out) # the result: [1, 2, 2, 4, 3, 3] + """ + if in_dygraph_mode(): + return _legacy_C_ops.limit_by_capacity(expert_count, capacity, + 'n_worker', n_worker) + elif _in_legacy_dygraph(): + return core.ops.limit_by_capacity(expert_count, capacity, 'n_worker', + n_worker) + else: + op_type = 'limit_by_capacity' + + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference( + dtype=expert_count.dtype) + + helper.append_op(type=op_type, + inputs={ + 'expert_count': expert_count, + 'capacity': capacity + }, + outputs={'Out': out}, + attrs={'n_worker': n_worker}) + return out + + +def _prune_gate_by_capacity(gate_idx, expert_count, n_expert, n_worker): + """ + prune gate by capacity(only support CUDA) + + Args: + gate_idx (Tensor): Represents the gate_id sequence corresponding to the input data with type int32, int64. + expert_count (Tensor): The quantity value counted on the gate_id sequence of the input data with type int32, int64. + n_worker(int,optional): The number of workers on the trainer with type int64. + + Returns: + new_gate_idx (Tensor): The gate_id sequence corresponding to the new input data after passing through prune. + + Examples: + .. code-block:: python + + import paddle + gate_idx = paddle.to_tensor([1, 3, 3, 3, 3, 2, 1, 1], dtype='int32') + expert_count = paddle.to_tensor([0, 3, 1, 3, 0, 0, 0, 0], dtype='int32') + n_worker = 1 + new_gate_id = paddle.distributed.utils.prune_gate_by_capacity(gate_idx, expert_count, n_expert, n_worker) + print(new_gate_id) + # Tensor(shape=[8], dtype=int32, place=CUDAPlace(0), stop_gradient=True, + [1, 3, 3, 3, -1, 2, 1, 1]) + """ + if in_dygraph_mode(): + return _legacy_C_ops.prune_gate_by_capacity(gate_idx, expert_count, + "n_expert", n_expert, + "n_worker", n_worker) + elif _in_legacy_dygraph(): + return core.ops.prune_gate_by_capacity(gate_idx, expert_count, + "n_expert", n_expert, "n_worker", + n_worker) + check_variable_and_dtype(gate_idx, 'GateIdx', ['int32', 'int64'], + 'paddle.distributed.utils.prune_gate_by_capacity') + check_variable_and_dtype(expert_count, 'ExpertCount', ['int32', 'int64'], + 'paddle.distributed.utils.prune_gate_by_capacity') + + helper = LayerHelper('prune_gate_by_capacity', **locals()) + new_gate_idx = helper.create_variable_for_type_inference( + dtype=gate_idx.dtype) + helper.append_op(type='prune_gate_by_capacity', + inputs={ + 'GateIdx': gate_idx, + "ExpertCount": expert_count + }, + outputs={'NewGateIdx': new_gate_idx}, + attrs={ + "n_expert": n_expert, + "n_worker": n_worker + }) + + return new_gate_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7187236d47c36e2ba5aebc25febf7f4841b997 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel.py @@ -0,0 +1,456 @@ +# 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 jin 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. + +import os +import six +import warnings +from multiprocessing import Process # noqa: F401 +from multiprocessing import Manager # noqa: F401 +import time +import sys +import paddle + +from paddle import compat as cpt + +# deprecated module import +from paddle.fluid import core +from paddle.fluid.framework import in_dygraph_mode +from paddle.fluid.framework import _set_expected_place +from paddle.fluid.dygraph import parallel_helper +from paddle.distributed.fleet.launch_utils import check_backend +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.distributed.fleet.base.private_helper_function import ( + wait_server_ready, +) # noqa: F401 +from paddle.distributed import collective +from paddle.distributed.collective import _set_group_map +from paddle.distributed.collective import _set_group_map_by_name +from paddle.distributed.collective import _get_group_map_by_name +from paddle.distributed.collective import _group_map_by_name +from paddle.distributed.collective import _default_group_name +from paddle.distributed.collective import _valid_backend_list +from paddle.distributed.collective import _set_default_backend +from paddle.distributed.collective import _set_default_store +from paddle.distributed.collective import _new_process_group_impl +from paddle.distributed.collective import Group +from paddle.distributed.collective import _set_group_map_backend +from paddle.distributed.communication.group import _add_new_group + +__all__ = [] + +ParallelStrategy = core.ParallelStrategy + +# NOTE(chenweihang): Maintain a global parallel env to avoid +# initializing ParallelEnv every time and improve performance +_global_parallel_env = None + + +def _get_global_parallel_env(): + global _global_parallel_env + if _global_parallel_env is None: + _global_parallel_env = ParallelEnv() + return _global_parallel_env + + +def _start_kv_server(port, http_server_d, size): + from paddle.distributed.fleet.utils.http_server import KVServer + + http_server = KVServer(int(port), size=size) + http_server.start() + wait_seconds = 3 + while http_server_d.get("running", False) or not http_server.should_stop(): + time.sleep(wait_seconds) + http_server.stop() + + +def _is_cpuonly(backend): + check_backend(backend) + if ( + backend in ['auto', 'nccl', 'bkcl', 'hccl', 'heter', 'cncl'] + and ( + core.is_compiled_with_cuda() + or core.is_compiled_with_xpu() + or core.is_compiled_with_npu() + or core.is_compiled_with_mlu() + ) + ) or backend is 'xccl': + + # passes 'auto' and can use cuda or xpu, use the default logics. so return False + return False + else: + return True + + +def _check_var_exists(var_name): + var = os.environ.get(var_name, None) + if var is None: + raise ValueError( + "paddle.distributed initialize error, " + "environment variable %s is needed, but not set." % var_name + ) + + +def init_parallel_env(): + """ + + Initialize parallel training environment in dynamic graph mode. + + Note: + Now initialize both `NCCL` and `GLOO` contexts for communication. + + Args: + backend (string): A string represents the backend used by DataParallel, + should be one of 'gloo'(for cpu), 'nccl'(for cuda), 'bkcl'(for xpu), 'auto'(auto detect). + The auto detection prefer 'nccl', 'bkcl' than 'gloo'. + + Returns: + None + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + import paddle.distributed as dist + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear1 = nn.Linear(10, 10) + self._linear2 = nn.Linear(10, 1) + + def forward(self, x): + return self._linear2(self._linear1(x)) + + def train(): + # 1. initialize parallel environment + dist.init_parallel_env() + + # 2. create data parallel layer & optimizer + layer = LinearNet() + dp_layer = paddle.DataParallel(layer) + + loss_fn = nn.MSELoss() + adam = opt.Adam( + learning_rate=0.001, parameters=dp_layer.parameters()) + + # 3. run layer + inputs = paddle.randn([10, 10], 'float32') + outputs = dp_layer(inputs) + labels = paddle.randn([10, 1], 'float32') + loss = loss_fn(outputs, labels) + + loss.backward() + + adam.step() + adam.clear_grad() + + if __name__ == '__main__': + dist.spawn(train) + + """ + + # 0. get env & check world size + global _global_parallel_env + # when call init_parallel_env, need update `_global_parallel_env` + _global_parallel_env = ParallelEnv() + parallel_env = _global_parallel_env + # if not parallel, `init_parallel_env` do nothing + if parallel_env.world_size < 2: + warnings.warn( + "Currently not a parallel execution environment, `paddle.distributed.init_parallel_env` will not do anything." + ) + return + # NOTE(xiongkun): support cpu gloo only, add this environment variable to + # enable cpu only gloo prarllel training) + backend = os.environ.get('PADDLE_DISTRI_BACKEND', 'auto') + is_cpu_only = _is_cpuonly(backend) + # 1. gpu xpu check, must be gpu or xpu, + if not ( + is_cpu_only + or core.is_compiled_with_cuda() + or core.is_compiled_with_xpu() + or core.is_compiled_with_npu() + or core.is_compiled_with_mlu() + ): + raise NotImplementedError( + "If you want to use CPU-only version, please use 'gloo' as backend" + ) + + if backend == "xccl": + FLAGS_selected_custom_devices = 'FLAGS_selected_{}s'.format( + parallel_env.device_type + ) + _check_var_exists(FLAGS_selected_custom_devices) + else: + if not is_cpu_only and core.is_compiled_with_cuda(): + _check_var_exists("FLAGS_selected_gpus") + backend = "nccl" if backend == "auto" else backend + elif not is_cpu_only and core.is_compiled_with_xpu(): + _check_var_exists('FLAGS_selected_xpus') + backend = "bkcl" if backend == "auto" else backend + elif not is_cpu_only and core.is_compiled_with_npu(): + _check_var_exists('FLAGS_selected_npus') + backend = "hccl" if backend == "auto" else backend + elif not is_cpu_only and core.is_compiled_with_mlu(): + _check_var_exists('FLAGS_selected_mlus') + backend = "cncl" if backend == "auto" else backend + + _check_var_exists("PADDLE_TRAINER_ID") + _check_var_exists("PADDLE_CURRENT_ENDPOINT") + _check_var_exists("PADDLE_TRAINERS_NUM") + _check_var_exists("PADDLE_TRAINER_ENDPOINTS") + + # NOTE(chenweihang): [ why config global place here? ] + # the dygraph mode will be set to default mode, + # users will not call `dygraph.guard` or `enable_dygraph` + # directly, if they want to switch default place, + # they need to call a function to change default place, + # here just set correctly place to users + if backend == "xccl": + place = core.CustomPlace( + parallel_env.device_type, parallel_env.device_id + ) + elif is_cpu_only: + place = core.CPUPlace() + elif core.is_compiled_with_cuda(): + place = core.CUDAPlace(parallel_env.device_id) + elif core.is_compiled_with_xpu(): + place = core.XPUPlace(parallel_env.device_id) + elif core.is_compiled_with_npu(): + place = core.NPUPlace(parallel_env.device_id) + elif core.is_compiled_with_mlu(): + place = core.MLUPlace(parallel_env.device_id) + + _set_expected_place(place) + + group = None + if backend in _valid_backend_list and in_dygraph_mode(): + if _default_group_name in _get_group_map_by_name(): + return _get_group_map_by_name()[_default_group_name] + _set_default_backend(backend) + rank = int(os.getenv("PADDLE_TRAINER_ID")) + world_size = int(os.getenv("PADDLE_TRAINERS_NUM")) + assert rank >= 0 and world_size > rank and world_size > 1, ( + "rank must be non-negative and world_size must be the " + "maximum rank plus one. Moreover, at least two processes are " + "required to create a process group." + ) + master_addr = os.getenv("MASTER_ADDR", None) + master_port = os.getenv("MASTER_PORT", None) + endpoints = ( + ":".join([master_addr, master_port]) + if master_addr and master_port + else None + ) + if endpoints is None: + endpoints = os.getenv("PADDLE_MASTER", None) + if endpoints is None: + endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS").split(',')[0] + assert endpoints, ( + "The environment variable 'MASTER_ADDR' and 'MASTER_PORT' " + "must be specified, for example 'export MASTER_ADDR=127.0.0.1' " + "and 'export MASTER_ADDR=54612'. Or you can start your training" + "with paddle.distributed.run module." + ) + master_addr, master_port = endpoints.split(":") + master_port = int(master_port) + is_master = rank == 0 + stop_check_timeout = int(os.getenv("FLAGS_stop_check_timeout", "900")) + default_store = core.TCPStore( + master_addr, + master_port, + is_master, + world_size, + timeout=stop_check_timeout, + ) + _set_default_store(default_store) + pg = _new_process_group_impl( + backend, + default_store, + rank, + world_size, + _default_group_name, + pg_options=None, + ) + ranks = list(range(world_size)) + group = Group(rank, 0, ranks, pg=pg, name=_default_group_name) + _set_group_map_by_name(_default_group_name, group) + _set_group_map(0, group) + _set_group_map_backend(group, backend) + _add_new_group(group) + parallel_helper._set_parallel_ctx(True) + + paddle.distributed.barrier(group=group) + return group + + node_num = set([i.split(":")[0] for i in parallel_env.trainer_endpoints]) + # 3: init gloo context (step 1: httpsever start) + init_gloo = int(os.getenv("PADDLE_WITH_GLOO", "0")) + if is_cpu_only or init_gloo or backend == "heter": + ep_rank_0 = parallel_env.trainer_endpoints[0].split(":") + manager = Manager() + # glboal dict to store status + http_server_d = manager.dict() + http_server_d["running"] = False + if parallel_env.rank == 0: + # The scope for worker used by http server is '_worker' + size = {'_worker': parallel_env.world_size} + if backend == "heter": + size = {'_worker': len(node_num)} + http_server = Process( + target=_start_kv_server, + args=(int(ep_rank_0[1]), http_server_d, size), + ) + http_server.daemon = True + http_server_d["running"] = True + http_server.start() + + # 4. init NCCL ParallelStrategy + strategy = ParallelStrategy() + if parallel_helper._is_parallel_ctx_initialized(): + warnings.warn("The parallel environment has been initialized.") + strategy.nranks = parallel_env.world_size + strategy.local_rank = parallel_env.rank + strategy.trainer_endpoints = parallel_env.trainer_endpoints + strategy.current_endpoint = parallel_env.current_endpoint + strategy.nrings = parallel_env.nrings + + # init nccl or hccl or bkcl or heter context + if is_cpu_only: + parallel_helper._set_parallel_ctx( + core.GLOOParallelContext(strategy, place) + ) + elif backend == "heter": + parallel_helper._set_parallel_ctx( + core.HeterParallelContext(strategy, parallel_env.device_id) + ) + elif core.is_compiled_with_cuda(): + parallel_helper._set_parallel_ctx( + core.NCCLParallelContext(strategy, place) + ) + elif core.is_compiled_with_xpu(): + parallel_helper._set_parallel_ctx( + core.BKCLParallelContext(strategy, place) + ) + elif core.is_compiled_with_npu(): + parallel_helper._set_parallel_ctx( + core.HCCLParallelContext(strategy, place) + ) + elif core.is_compiled_with_mlu(): + parallel_helper._set_parallel_ctx( + core.CNCLParallelContext(strategy, place) + ) + + if backend != "heter": + other_endpoints = strategy.trainer_endpoints[:] + other_endpoints.remove(strategy.current_endpoint) + if not is_cpu_only and strategy.local_rank == 0: + wait_server_ready(other_endpoints) + + parallel_helper._init_parallel_ctx() + + # 5: init gloo context (step 2: gloo init) + # dividing init_gloo into two part beacause nccl and gloo + # are separately looking for free ports which sometimes + # leads to port-conflict. + if (is_cpu_only or backend == "heter") and parallel_env.rank == 0: + # compare to init_gloo, we don't need to + # init gloo, because we do this in _init_parallel_ctx; + http_server_d["running"] = False + http_server.join() + + elif init_gloo: + wait_server_ready([parallel_env.trainer_endpoints[0]]) + gloo_strategy = core.GlooParallelStrategy() + gloo_strategy.rank = parallel_env.rank + gloo_strategy.rank_num = parallel_env.world_size + gloo_strategy.ip_address = ep_rank_0[0] + gloo_strategy.ip_port = int(ep_rank_0[1]) + default_init_timeout_seconds = 3600 + default_run_timeout_seconds = 9999999 + gloo_strategy.init_seconds = default_init_timeout_seconds + gloo_strategy.run_seconds = default_run_timeout_seconds + gloo = core.GlooParallelContext(gloo_strategy) + gloo.init() + if parallel_env.rank == 0: + http_server_d["running"] = False + http_server.join() + return group + + +def get_rank(group=None): + """ + Returns the rank of current trainer in the given group, ranks are consecutive integers in [0, ``world_size``). + If none of the group is given, the global group will be used as default. + + Args: + group (Group, optional): The communication group you want to get rank of current trainer, use global group as default if group is None. + + Returns: + (int) The rank of current trainer in the given group. Return -1 if the process is not part of the given group. + + Warning: + Argument ``group`` only supports in dygraph mode. + + Examples: + .. code-block:: python + + # Execute this script using distributed launch with one card configs. + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + print("The rank is %d" % dist.get_rank()) + # The rank is 0 + """ + if in_dygraph_mode() and group: + return group.rank + + assert group is None, "Only support group argument in eager mode." + return _get_global_parallel_env().rank + + +def get_world_size(group=None): + """ + Returns the number of trainers (number of processes participating in current job) in the given group. + If none of the group is given, the global group will be used as default. + + Args: + group (Group, optional): The communication group you want to check world size, use global group as default if group is None. + + Returns: + (int) The number of trainers in the given group. Return -1 if the process if not part of the given group. + + Warning: + Argument ``group`` only supports in dygraph mode. + + Examples: + .. code-block:: python + + # Execute this script using distributed launch with one card configs. + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + print("The world_size is %d" % dist.get_world_size()) + # The world_size is 1 + """ + if in_dygraph_mode() and group: + return group.world_size + + assert group is None, "Only support group argument in eager mode." + return _get_global_parallel_env().world_size diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel_with_gloo.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel_with_gloo.py new file mode 100644 index 0000000000000000000000000000000000000000..363de6a5505bdfcdfc8d4f50bf32b7d7543f04d2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/parallel_with_gloo.py @@ -0,0 +1,249 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except jin 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. + +import os +import sys +import time +import warnings +from multiprocessing import Process, Manager + +# deprecated module import +from paddle.fluid import core +from paddle.distributed.fleet.base.private_helper_function import wait_server_ready + +__all__ = [] + +_global_gloo_ctx = None + + +def _start_kv_server(port, http_server_d, size): + from paddle.distributed.fleet.utils.http_server import KVServer + http_server = KVServer(int(port), size=size) + http_server.start() + wait_seconds = 3 + while http_server_d.get("running", False) or not http_server.should_stop(): + time.sleep(wait_seconds) + http_server.stop() + + +def gloo_init_parallel_env(rank_id, rank_num, server_endpoint): + """ + Initialize parallel environment with gloo for cpu only. + + Args: + - rank_id(int, required) - the index of current rank; + - rank_num (int, required) - the number of ranks in this parallel env; + - server_endpoint (str, required) - endpoint of server to init gloo context in ip:port format; + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import multiprocessing + from contextlib import closing + import socket + + port_set = set() + + def find_free_port(): + def _free_port(): + with closing(socket.socket(socket.AF_INET, + socket.SOCK_STREAM)) as s: + s.bind(('', 0)) + return s.getsockname()[1] + while True: + port = _free_port() + if port not in port_set: + port_set.add(port) + return port + + def test_gloo_init(id, rank_num, server_endpoint): + paddle.distributed.gloo_init_parallel_env( + id, rank_num, server_endpoint) + + def test_gloo_init_with_multiprocess(num_of_ranks): + jobs = [] + server_endpoint = "127.0.0.1:%s" % (find_free_port()) + for id in range(num_of_ranks): + p = multiprocessing.Process( + target=test_gloo_init, + args=(id, num_of_ranks, server_endpoint)) + jobs.append(p) + p.start() + for proc in jobs: + proc.join() + + if __name__ == '__main__': + # Arg: number of ranks (processes) + test_gloo_init_with_multiprocess(2) + """ + + assert (rank_num < 2) is False, \ + "rank_num should greater than or equal to 2 for parallel environment initialzation." + + # init gloo context + manager = Manager() + # global dict to store status + http_server_status = manager.dict() + http_server_status["running"] = False + if rank_id == 0: + # The scope for worker used by http server is '_worker' + size = {'_worker': rank_num} + http_server_proc = Process(target=_start_kv_server, + args=(int(server_endpoint.split(":")[1]), + http_server_status, size)) + http_server_proc.daemon = True + http_server_status["running"] = True + http_server_proc.start() + + # all processes in this parallel environment should wait until server is ready + wait_server_ready([server_endpoint]) + + gloo_strategy = core.GlooParallelStrategy() + gloo_strategy.rank = rank_id + gloo_strategy.rank_num = rank_num + gloo_strategy.ip_address = server_endpoint.split(":")[0] + gloo_strategy.ip_port = int(server_endpoint.split(":")[1]) + # default_init_timeout_seconds + gloo_strategy.init_seconds = 3600 + # default_run_timeout_seconds + gloo_strategy.run_seconds = 9999999 + + global _global_gloo_ctx + _global_gloo_ctx = core.GlooParallelContext(gloo_strategy) + _global_gloo_ctx.init() + + if rank_id == 0: + http_server_status["running"] = False + http_server_proc.join() + + +def gloo_barrier(): + """ + Call barrier function with initialized gloo context. + + Args: + None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import multiprocessing + from contextlib import closing + import socket + + port_set = set() + + def find_free_port(): + def _free_port(): + with closing(socket.socket(socket.AF_INET, + socket.SOCK_STREAM)) as s: + s.bind(('', 0)) + return s.getsockname()[1] + while True: + port = _free_port() + if port not in port_set: + port_set.add(port) + return port + + def test_gloo_barrier(id, rank_num, server_endpoint): + paddle.distributed.gloo_init_parallel_env( + id, rank_num, server_endpoint) + paddle.distributed.gloo_barrier() + + def test_gloo_barrier_with_multiprocess(num_of_ranks): + jobs = [] + server_endpoint = "127.0.0.1:%s" % (find_free_port()) + for id in range(num_of_ranks): + p = multiprocessing.Process( + target=test_gloo_barrier, + args=(id, num_of_ranks, server_endpoint)) + jobs.append(p) + p.start() + for proc in jobs: + proc.join() + + if __name__ == '__main__': + # Arg: number of ranks (processes) + test_gloo_barrier_with_multiprocess(2) + """ + + assert _global_gloo_ctx is not None, "gloo context is not initialzed." + _global_gloo_ctx.barrier() + + +def gloo_release(): + """ + Release the parallel environment initialized by gloo + + Args: + None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import multiprocessing + from contextlib import closing + import socket + + port_set = set() + + def find_free_port(): + def _free_port(): + with closing(socket.socket(socket.AF_INET, + socket.SOCK_STREAM)) as s: + s.bind(('', 0)) + return s.getsockname()[1] + while True: + port = _free_port() + if port not in port_set: + port_set.add(port) + return port + + def test_gloo_release(id, rank_num, server_endpoint): + paddle.distributed.gloo_init_parallel_env( + id, rank_num, server_endpoint) + paddle.distributed.gloo_barrier() + paddle.distributed.gloo_release() + + def test_gloo_release_with_multiprocess(num_of_ranks): + jobs = [] + server_endpoint = "127.0.0.1:%s" % (find_free_port()) + for id in range(num_of_ranks): + p = multiprocessing.Process( + target=test_gloo_release, + args=(id, num_of_ranks, server_endpoint)) + jobs.append(p) + p.start() + for proc in jobs: + proc.join() + + if __name__ == '__main__': + # Arg: number of ranks (processes) + test_gloo_release_with_multiprocess(2) + """ + + if _global_gloo_ctx is not None: + _global_gloo_ctx.release() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f721a1df50df6711f547854f0b6a6789d9df33f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/__init__.py @@ -0,0 +1,34 @@ +# Copyright (c) 2021 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. + +from .pass_base import new_pass, PassManager, PassContext +from .fuse_all_reduce import * +from .auto_parallel_gradient_merge import * +from .auto_parallel_sharding import * +from .auto_parallel_amp import * +from .auto_parallel_fp16 import * +from .auto_parallel_recompute import * +from .auto_parallel_quantization import * +from .auto_parallel_data_parallel_optimization import * +from .auto_parallel_grad_clip import * +from .cpp_pass import * +import os +from .ps_trainer_pass import * +from .ps_server_pass import * + +__all__ = [ + 'new_pass', + 'PassManager', + 'PassContext', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_amp.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_amp.py new file mode 100644 index 0000000000000000000000000000000000000000..9e0aaa644855482f926ab77f226bf13b3a81e3d1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_amp.py @@ -0,0 +1,786 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.framework import core +from paddle.fluid import unique_name +from .pass_base import PassBase, register_pass +from paddle.distributed.fleet.meta_optimizers.common import OpRole +from paddle.fluid.data_feeder import check_variable_and_dtype, check_type +from paddle.distributed.auto_parallel.utils import get_loss_op, set_var_dist_attr +from paddle.distributed.auto_parallel.utils import naive_set_dist_op_attr_for_program_by_mesh_and_mapping +from paddle.distributed.auto_parallel.process_group import get_world_process_group +from paddle.fluid.contrib.mixed_precision.fp16_utils import AutoMixedPrecisionLists +from paddle.fluid.contrib.mixed_precision.fp16_utils import _keep_fp32_input, _keep_fp32_output, find_op_index +from paddle.fluid.contrib.mixed_precision.fp16_utils import _valid_types, find_true_post_op, find_true_prev_op +from paddle.fluid.contrib.mixed_precision.fp16_utils import _is_in_black_varnames, _dtype_to_str, _rename_arg +from paddle.distributed.auto_parallel.dist_attribute import OperatorDistributedAttribute +from ..auto_parallel.utils import is_forward_op, is_backward_op, is_loss_op + +world_process_group = get_world_process_group() + + +class AMPState(object): + + def __init__(self, block): + self._block = block + self._op_fp16_dict = { + } # op_id --> True/False. 'True' means that the current op is in fp16 mode. + self._var_name_dict = {} # fwd_op_id --> {old_name: cast_name} + self.is_train = False + + def _is_fp16_op(self, op_id): + return self._op_fp16_dict.get(op_id, None) + + def _build_state(self, amp_lists, dist_context): + ops = self._block.ops + dist_op_context = dist_context.dist_op_context + for op in ops: + if int(op.attr('op_role')) == 257: + self.is_train = True + + if int(op.attr('op_role')) == int(OpRole.Forward): + self._mark_black_white_ops(amp_lists) + elif int(op.attr('op_role')) == int(OpRole.Backward): + if op.desc.original_id() in dist_op_context.grad_op_id_to_op_id: + fwd_op_id = dist_op_context.grad_op_id_to_op_id[ + op.desc.original_id()] + if self._is_fp16_op(fwd_op_id) == True: + self._op_fp16_dict[op.desc.original_id()] = True + elif self._is_fp16_op(fwd_op_id) == False: + self._op_fp16_dict[op.desc.original_id()] = False + elif int(op.attr('op_role')) == int(OpRole.Optimize): + break + + return self.is_train + + def _mark_black_white_ops(self, amp_lists): + """ + this function is modified from paddle.fluid.contrib.mixed_precision + """ + self._block._sync_with_cpp() + ops = self._block.ops + + for op in ops: + if int(op.attr('op_role')) == int(OpRole.Backward): + break + if op.type == 'create_py_reader' or op.type == 'read': + continue + if amp_lists.black_varnames is not None and _is_in_black_varnames( + op, amp_lists): + self._op_fp16_dict[op.desc.original_id()] = False + continue + if op.type in amp_lists.black_list: + self._op_fp16_dict[op.desc.original_id()] = False + elif op.type in amp_lists.white_list: + self._op_fp16_dict[op.desc.original_id()] = True + elif op.type in amp_lists.gray_list: + is_black_op = False + is_white_op = False + for in_name in op.input_names: + # if this op has inputs + if in_name: + for in_var_name in op.input(in_name): + in_var = self._block.var(in_var_name) + # this in_var isn't the output of other op + if in_var.op is None: + continue + elif in_var.op is op: + prev_op = find_true_prev_op( + ops, op, in_var_name) + if prev_op is None: + continue + else: + prev_op = in_var.op + # if it's one of inputs + if self._is_fp16_op(prev_op.desc.original_id()) == False or \ + prev_op.type in amp_lists.black_list: + is_black_op = True + elif self._is_fp16_op(prev_op.desc.original_id()) == True or \ + prev_op.type in amp_lists.white_list: + is_white_op = True + if is_black_op: + self._op_fp16_dict[op.desc.original_id()] = False + elif is_white_op: + self._op_fp16_dict[op.desc.original_id()] = True + else: + pass + else: + # For numerical safe, we apply fp32 computation on ops that + # are not determined which list they should stay. + self._op_fp16_dict[op.desc.original_id()] = False + + def cast_forward_program(self, dist_context): + ops = self._block.ops + idx = 0 + while idx < len(ops): + op = ops[idx] + num_cast_ops = 0 + if int(op.attr('op_role')) == int(OpRole.Backward): + break + if self._is_fp16_op(op.desc.original_id()) == False: + num_cast_ops = self._insert_cast_op_forward( + op, idx, core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32, dist_context) + elif self._is_fp16_op(op.desc.original_id()) == True: + num_cast_ops = self._insert_cast_op_forward( + op, idx, core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16, dist_context) + else: + pass + idx += num_cast_ops + 1 + self._block._sync_with_cpp() + + def _insert_cast_op_forward(self, op, idx, src_dtype, dst_dtype, + dist_context): + """ + only for forward cast + modified from paddle.fluid.contrib.mixed_precision + """ + num_cast_ops = 0 + var_name_dict = {} + for in_name in op.input_names: + if src_dtype == core.VarDesc.VarType.FP32 and _keep_fp32_input( + op, in_name): + continue + for in_var_name in op.input(in_name): + in_var = self._block._find_var_recursive(in_var_name) + if in_var.type not in _valid_types or in_var.dtype == dst_dtype: + continue + if in_var.dtype == src_dtype: + cast_name = in_var.name + '.cast_' + _dtype_to_str( + dst_dtype) + out_var = self._block.vars.get(cast_name) + var_name_dict[in_var.name] = cast_name + consume_op_attr = dist_context.get_op_dist_attr_for_program( + op) + assert consume_op_attr is not None + if out_var is None or out_var.dtype != dst_dtype: + # NOTE we make the cast op and var's dist attr as the op that consume the + # cast var instead of the op which generates the var + in_var_dist_attr = consume_op_attr.get_input_dist_attr( + in_var.name) + assert in_var_dist_attr is not None + ref_mesh = in_var_dist_attr.process_mesh + ref_mapping = in_var_dist_attr.dims_mapping + consume_op_attr.set_input_dist_attr( + cast_name, in_var_dist_attr) + + out_var = self._block.create_var( + name=cast_name, + dtype=dst_dtype, + persistable=False, + stop_gradient=in_var.stop_gradient) + set_var_dist_attr(dist_context, out_var, ref_mapping, + ref_mesh) + + cast_op = self._block._insert_op_without_sync( + idx, + type="cast", + inputs={"X": in_var}, + outputs={"Out": out_var}, + attrs={ + "in_dtype": in_var.dtype, + "out_dtype": out_var.dtype, + }) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + cast_op, ref_mesh, ref_mapping, dist_context) + num_cast_ops += 1 + else: + in_var_dist_attr = consume_op_attr.get_input_dist_attr( + in_var.name) + consume_op_attr.set_input_dist_attr( + cast_name, in_var_dist_attr) + _rename_arg(op, in_var.name, cast_name) + else: + if op.has_attr('in_dtype'): + op._set_attr('in_dtype', dst_dtype) + self._var_name_dict[op.desc.original_id()] = var_name_dict + + if src_dtype == core.VarDesc.VarType.FP32 and dst_dtype == core.VarDesc.VarType.FP16: + for out_name in op.output_names: + if _keep_fp32_output(op, out_name): + continue + for out_var_name in op.output(out_name): + out_var = self._block.var(out_var_name) + if out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.FP16) + if op.has_attr('out_dtype'): + op._set_attr('out_dtype', core.VarDesc.VarType.FP16) + return num_cast_ops + + def cast_backward_program(self, params_grads, dist_context): + self._block._sync_with_cpp() + ops = self._block.ops + + loss_op = get_loss_op(self._block) + loss_op_index = find_op_index(self._block.desc, loss_op.desc) + + appended_grad_times = 0 + idx = loss_op_index + 1 + while idx < len(ops): + num_cast_ops = 0 + grad_op = ops[idx] + + # NOTE: the map in `grad_var_to_var` may be changed when the var is casted, + # which will affect the dist_op to insert allreduce_sum op. + op_dist_attr = dist_context.get_op_dist_attr_for_program(grad_op) + if is_backward_op(grad_op) and (is_forward_op(ops[idx - 1]) + or is_loss_op(ops[idx - 1])): + if not op_dist_attr.is_recompute: + appended_grad_times += 1 + + grad_op_orig_id = grad_op.desc.original_id() + dist_op_context = dist_context.dist_op_context + if grad_op_orig_id in dist_op_context.grad_op_id_to_op_id: + if self._is_fp16_op(grad_op_orig_id) == False: # fp32 + num_cast_ops = self._insert_cast_op_backward( + grad_op, idx, core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32, dist_context, + appended_grad_times) + elif self._is_fp16_op(grad_op_orig_id) == True: # fp16 + num_cast_ops = self._insert_cast_op_backward( + grad_op, idx, core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16, dist_context, + appended_grad_times) + elif grad_op.type == "sum": + in_var_name = grad_op.desc.input_arg_names()[0] + src_dtype = self._block.var(in_var_name).dtype + for in_var_name in grad_op.desc.input_arg_names(): + assert src_dtype == self._block.var(in_var_name).dtype + out_var_name = grad_op.desc.output_arg_names()[0] + out_var = self._block.var(out_var_name) + if out_var.dtype != src_dtype: + out_var.desc.set_dtype(src_dtype) + elif int(grad_op.attr('op_role')) == 257: + pass + else: + raise ValueError( + "'{}' op is not supported in the complete amp pass.".format( + grad_op.type)) + idx += num_cast_ops + 1 + + self._block._sync_with_cpp() + _update_backward_cast_ops(params_grads, dist_context) + + def _insert_cast_op_backward(self, grad_op, idx, src_dtype, dst_dtype, + dist_context, appended_grad_times): + """ only for backward cast """ + + def _keep_fp32_input(op, in_name): + op_type = op.type + if op_type in ['layer_norm_grad']: + return in_name not in {'X', 'Y@GRAD'} + return False + + def _keep_fp32_output(op, out_name): + op_type = op.type + if op_type in ['layer_norm_grad']: + return out_name != 'X@GRAD' + return False + + num_cast_ops = 0 + original_id = grad_op.desc.original_id() + dist_op_context = dist_context.dist_op_context + fwd_op_id = dist_op_context.grad_op_id_to_op_id[original_id] + + for in_name in grad_op.input_names: + if src_dtype == core.VarDesc.VarType.FP32 and _keep_fp32_input( + grad_op, in_name): + for in_var_name in grad_op.input(in_name): + in_var = self._block._find_var_recursive(in_var_name) + assert in_var.dtype == core.VarDesc.VarType.FP32 + continue + + for in_var_name in grad_op.input(in_name): + in_var = self._block._find_var_recursive(in_var_name) + if in_var.dtype == src_dtype: + consume_op_attr = dist_context.get_op_dist_attr_for_program( + grad_op) + if in_var_name in self._var_name_dict[fwd_op_id]: + # NOTE: if in_var of consume grad_op has been casted before, + # it should be renamed and reset dist_attr. + cast_name = self._var_name_dict[fwd_op_id][in_var_name] + grad_op.desc._rename_input(in_var_name, cast_name) + in_var_dist_attr = consume_op_attr.get_input_dist_attr( + in_var_name) + consume_op_attr.set_input_dist_attr( + cast_name, in_var_dist_attr) + else: + assert in_var.dtype == dst_dtype, "op [{}] expect input [{}] to be dtype [{}] BUT got [{}]. {}".format( + grad_op.type, in_name, dst_dtype, in_var.dtype, + str(grad_op)) + + for out_name in grad_op.output_names: + if src_dtype == core.VarDesc.VarType.FP32 and _keep_fp32_output( + grad_op, out_name): + for out_var_name in grad_op.output(out_name): + out_var = self._block._find_var_recursive(out_var_name) + assert out_var.dtype == core.VarDesc.VarType.FP32 + continue + + for out_var_name in grad_op.output(out_name): + out_var = self._block._find_var_recursive(out_var_name) + out_var_name_prefix = out_var_name[:out_var_name.find("@")] + fwd_var = self._block._find_var_recursive(out_var_name_prefix) + # NOTE: the out_var's dtype of consume grad_op should equal to the fwd_var's dtype + if out_var.dtype != fwd_var.dtype: + out_var.desc.set_dtype(fwd_var.dtype) + + if out_var.dtype == src_dtype: + if out_var_name_prefix in self._var_name_dict[fwd_op_id]: + # NOTE: if out_var of consume grad_op has been casted before, + # it should be renamed and reset dist_attr, then we insert cast op to + # convert the cast_var to original dtype + consume_op_attr = dist_context.get_op_dist_attr_for_program( + grad_op) + fwd_cast_name = self._var_name_dict[fwd_op_id][ + out_var_name_prefix] + suffix = "" + if "@RENAME" in out_var_name: + suffix = out_var_name[out_var_name.find("@RENAME"):] + cast_name = fwd_cast_name + "@GRAD" + suffix + cast_var = self._block.vars.get(cast_name) + if cast_var is None or cast_var.dtype != dst_dtype: + grad_op.desc._rename_output(out_var_name, cast_name) + out_var_dist_attr = consume_op_attr.get_output_dist_attr( + out_var_name) + ref_mesh = out_var_dist_attr.process_mesh + ref_mapping = out_var_dist_attr.dims_mapping + consume_op_attr.set_output_dist_attr( + cast_name, out_var_dist_attr) + assert ref_mapping is not None + cast_var = self._block.create_var( + name=cast_name, + shape=out_var.shape, + dtype=dst_dtype, + persistable=False, + stop_gradient=out_var.stop_gradient) + set_var_dist_attr(dist_context, cast_var, + ref_mapping, ref_mesh) + dist_op_context.grad_var_to_var[ + appended_grad_times][cast_name] = fwd_cast_name + + cast_op = self._block._insert_op( + idx + 1, + type="cast", + inputs={"X": cast_var}, + outputs={"Out": out_var}, + attrs={ + "in_dtype": cast_var.dtype, + "out_dtype": out_var.dtype, + "op_role": OpRole.Backward + }) + cast_op._remove_attr("op_role_var") + cast_op._remove_attr("op_namescope") + cast_op._remove_attr("with_quant_attr") + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + cast_op, ref_mesh, ref_mapping, dist_context) + num_cast_ops += 1 + else: + assert out_var.dtype == dst_dtype + + return num_cast_ops + + +def _update_backward_cast_ops(params_grads, dist_context): + """ + move param grad cast to the end of backward segment + in order to enabel fp16 allreduce + """ + # TODO filter optimize ops in future + + main_block = paddle.static.default_main_program().global_block() + main_block._sync_with_cpp() + + for p, g in params_grads: + op = g.op + if g.dtype == core.VarDesc.VarType.FP32 and op.type == 'cast': + if int(op.attr('op_role')) == int( + OpRole.Backward) and op.has_attr('op_role_var'): + op._remove_attr("op_role_var") + + post_ops = find_true_post_op(main_block.ops, op, g.name) + if post_ops: + raise ValueError("The cast op {0}'s output should not be" + "used by a non-optimize op, however, it" + "is used by {1}".format(op, post_ops[0])) + + if op == main_block.ops[-1]: + continue + + # add new op in the python and cpp at the same time + new_op_desc = main_block.desc.append_op() + new_op_desc.copy_from(op.desc) + new_op = paddle.fluid.framework.Operator(block=main_block, + desc=new_op_desc, + type=None, + inputs=None, + outputs=None, + attrs=None) + main_block.ops.append(new_op) + + # dist attr + param_dist_attr = dist_context.get_tensor_dist_attr_for_program(p) + output_dist_attr = dist_context.get_tensor_dist_attr_for_program( + main_block.var(op.output_arg_names[0])) + assert param_dist_attr is not None + assert output_dist_attr is not None + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, param_dist_attr.process_mesh, + param_dist_attr.dims_mapping, dist_context) + + output_dist_attr.process_mesh = param_dist_attr.process_mesh + output_dist_attr.dims_mapping = param_dist_attr.dims_mapping + + op_idx = find_op_index(main_block.desc, op.desc) + if op_idx == -1: + raise ValueError("The op {0} is not in program".format(op)) + main_block._remove_op(op_idx, sync=False) + + main_block._sync_with_cpp() + + +def _check_and_update_gradient(params_grads, loss_scaling, dist_context): + + main_block = paddle.static.default_main_program().global_block() + main_block._sync_with_cpp() + + grads = [g for _, g in params_grads] + check_type(grads, 'x', (tuple, list), 'check_finite_and_unscale') + for e in grads: + check_variable_and_dtype(e, "x", ['float16', 'float32', 'float64'], + 'check_finite_and_unscale') + + found_inf = main_block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + ['find_infinite_scale', 'tmp'])), + shape=[1], + dtype='bool', + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + set_var_dist_attr(dist_context, found_inf, [-1], world_process_group.ranks) + + inputs = {'X': grads, 'Scale': loss_scaling} + outputs = {'Out': grads, 'FoundInfinite': found_inf} + attrs = {'op_role': OpRole.Optimize} + new_op = main_block.append_op(type='check_finite_and_unscale', + inputs=inputs, + outputs=outputs, + attrs=attrs) + + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = world_process_group.ranks + new_op_dist_attr.impl_idx = 0 + if len(world_process_group.ranks) > 1: + new_op_dist_attr.impl_type = "check_finite_and_unscale" + for g in grads: + g_dist_attr = dist_context.get_tensor_dist_attr_for_program(g) + assert g_dist_attr is not None + new_op_dist_attr.set_input_dims_mapping(g.name, + g_dist_attr.dims_mapping) + new_op_dist_attr.set_output_dims_mapping(g.name, + g_dist_attr.dims_mapping) + dist_context.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + return grads, found_inf + + +@register_pass("auto_parallel_amp") +class AMPPass(PassBase): + + def __init__(self): + super(AMPPass, self).__init__() + self.set_attr("loss", None) + self.set_attr("dist_context", None) + self.set_attr("custom_white_list", None) + self.set_attr("custom_black_list", None) + self.set_attr("custom_black_varnames", None) + self.set_attr("init_loss_scaling", 32768.0) + self.set_attr("incr_every_n_steps", 1000) + self.set_attr("decr_every_n_nan_or_inf", 2) + self.set_attr("incr_ratio", 2.0) + self.set_attr("decr_ratio", 0.8) + self.set_attr("use_dynamic_loss_scaling", False) + self.set_attr("input_data", []) + self.set_attr("params_grads", []) + self._loss = None + self._loss_scaling = None + self._num_good_steps = None + self._num_bad_steps = None + self._loss = None + + def _check_self(self): + if self.get_attr("init_loss_scaling") < 0: + return False + if self.get_attr("incr_every_n_steps") < 0: + return False + if self.get_attr("decr_every_n_nan_or_inf") < 0: + return False + if self.get_attr("incr_ratio") < 0: + return False + if self.get_attr("decr_ratio") < 0: + return False + if self.get_attr("dist_context") is None: + return False + return True + + def _check_conflict(self, other_pass): + + return True + + # NOTE: why AMPBackwardPass can override apply_single_impl instead of + # apply_impl? AMP is an optimization pass for serial program, + # in distributed scenario, all ranks should have the same modification. + def _apply_single_impl(self, main_program, startup_program, context): + self.dist_context = self.get_attr("dist_context") + params_grads = self.get_attr("params_grads") + + amp_lists = AutoMixedPrecisionLists( + set(self.get_attr("custom_white_list")), + set(self.get_attr("custom_black_list")), + set(self.get_attr("custom_black_varnames"))) + + with paddle.static.program_guard(main_program, startup_program): + amp_state = AMPState(main_program.global_block()) + is_train = amp_state._build_state(amp_lists, self.dist_context) + + amp_state.cast_forward_program(self.dist_context) + + if is_train: + with paddle.static.program_guard(main_program, startup_program): + amp_state.cast_backward_program(params_grads, self.dist_context) + self._init_amp_var() + self._scale_loss() + + if self.get_attr("use_dynamic_loss_scaling" + ) or self.get_attr("init_loss_scaling") != 1.0: + grads, found_inf = _check_and_update_gradient( + params_grads, self._loss_scaling, self.dist_context) + + if self.get_attr("use_dynamic_loss_scaling"): + self._update_loss_scaling(grads, found_inf) + + def _init_amp_var(self): + self._loss_scaling = paddle.static.create_global_var( + name=unique_name.generate("loss_scaling"), + shape=[1], + value=self.get_attr("init_loss_scaling"), + dtype='float32', + persistable=True) + set_var_dist_attr(self.dist_context, self._loss_scaling, [-1], + world_process_group.ranks) + + if self.get_attr("use_dynamic_loss_scaling"): + self._num_good_steps = paddle.static.create_global_var( + name=unique_name.generate("num_good_steps"), + shape=[1], + value=0, + dtype='int32', + persistable=True) + set_var_dist_attr(self.dist_context, self._num_good_steps, [-1], + world_process_group.ranks) + + self._num_bad_steps = paddle.static.create_global_var( + name=unique_name.generate("num_bad_steps"), + shape=[1], + value=0, + dtype='int32', + persistable=True) + set_var_dist_attr(self.dist_context, self._num_bad_steps, [-1], + world_process_group.ranks) + + def _scale_loss(self): + + main_block = paddle.static.default_main_program().global_block() + main_block._sync_with_cpp() + OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() + + loss = self.get_attr("loss") + assert loss is not None + loss_op = loss.op + loss_op_dist_attr = self.dist_context.get_op_dist_attr_for_program( + loss_op) + + if loss.dtype != core.VarDesc.VarType.FP32: + # cast loss here will change the effective loss tensor for the computation graph + # and therefore will effect all following passes whose logic is based on the loss tensor(Recompute & Gradient Merge), + # so we it is not allowed by now. fixed it in future. + raise NotImplementedError( + "Loss's generator op is not support in FP16 in Auto Parallel by now, please put that op into your black-list." + ) + + tmp_name = unique_name.generate(loss.name + ".cast_fp32") + cast_loss = main_block.create_var(name=tmp_name, dtype=dtype) + loss_dist_attr = self.dist_context.get_tensor_dist_attr_for_program( + loss) + ref_mesh = loss_op_dist_attr.process_mesh + self.dist_context.set_tensor_dist_attr_for_program( + cast_loss, loss_dist_attr) + + loss_op_idx = find_op_index(main_block.desc, loss_op.desc) + cast_op = main_block._insert_op( + loss_op_idx + 1, + type='cast', + inputs={'X': [loss]}, + outputs={'Out': [cast_loss]}, + attrs={ + "in_dtype": loss.dtype, + "out_dtype": core.VarDesc.VarType.FP32, + 'op_role': loss_op.all_attrs()[OP_ROLE_KEY], + }) + + loss_op._set_attr(OP_ROLE_KEY, + core.op_proto_and_checker_maker.OpRole.Forward) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + cast_op, ref_mesh, [-1], self.dist_context) + loss = loss.astype('float32') + + if self.get_attr("use_dynamic_loss_scaling" + ) or self.get_attr("init_loss_scaling") != 1.0: + + loss_op_idx = find_op_index(main_block.desc, loss_op.desc) + + # forward + ref_mesh = loss_op_dist_attr.process_mesh + self._scaled_loss = main_block.create_var( + name=unique_name.generate("scaled_loss"), + shape=loss.shape, + dtype=loss.dtype, + persistable=loss.persistable) + set_var_dist_attr(self.dist_context, self._scaled_loss, [-1], + ref_mesh) + + elementwise_mul_op = main_block._insert_op( + loss_op_idx + 1, + type='elementwise_mul', + inputs={ + 'X': [loss], + 'Y': [self._loss_scaling] + }, + outputs={'Out': [self._scaled_loss]}, + attrs={ + 'op_role': loss_op.all_attrs()[OP_ROLE_KEY], + }) + loss_op._set_attr(OP_ROLE_KEY, + core.op_proto_and_checker_maker.OpRole.Forward) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + elementwise_mul_op, ref_mesh, [-1], self.dist_context) + + # backward + first_backward_op = main_block.ops[loss_op_idx + 2] + assert first_backward_op.type == "fill_constant" and int( + first_backward_op.all_attrs()[OP_ROLE_KEY]) == 257 + self._scaled_loss_grad = main_block.create_var( + name=unique_name.generate("scaled_loss") + "@GRAD", + shape=loss.shape, + dtype=loss.dtype, + persistable=loss.persistable) + set_var_dist_attr(self.dist_context, self._scaled_loss_grad, [-1], + ref_mesh) + pre_grad_name = first_backward_op.output_arg_names[0] + first_backward_op._rename_output(pre_grad_name, + self._scaled_loss_grad.name) + # FIXME(JZ-LIANG) a trick to insert backward op + main_block._sync_with_cpp() + elementwise_mul_grad_op_desc = main_block.desc._insert_op( + loss_op_idx + 3) + elementwise_mul_grad_op_desc.set_type("elementwise_mul_grad") + elementwise_mul_grad_op_desc.set_input( + 'Out@GRAD', [self._scaled_loss_grad.name]) + elementwise_mul_grad_op_desc.set_input('X', [loss.name]) + elementwise_mul_grad_op_desc.set_input('Y', + [self._loss_scaling.name]) + elementwise_mul_grad_op_desc.set_output('X@GRAD', [pre_grad_name]) + elementwise_mul_grad_op_desc.set_output('Y@GRAD', []) + elementwise_mul_grad_op_desc._set_attr( + OP_ROLE_KEY, core.op_proto_and_checker_maker.OpRole.Backward) + elementwise_mul_grad_op_desc._set_attr('axis', -1) + elementwise_mul_grad_op = paddle.fluid.framework.Operator( + main_block, elementwise_mul_grad_op_desc) + main_block.ops.insert(loss_op_idx + 3, elementwise_mul_grad_op) + main_block._sync_with_cpp() + elementwise_mul_grad_op = main_block.ops[loss_op_idx + 3] + assert elementwise_mul_grad_op.type == "elementwise_mul_grad" + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + elementwise_mul_grad_op, ref_mesh, [-1], self.dist_context) + + else: + self._scaled_loss = loss + + main_block._sync_with_cpp() + + def _update_loss_scaling(self, grads, found_inf): + + main_block = paddle.static.default_main_program().global_block() + main_block._sync_with_cpp() + + check_variable_and_dtype(self._loss_scaling, "prev_loss_scaling", + ['float32', 'float64'], "update_loss_scaling") + check_type(grads, 'x', (tuple, list), 'update_loss_scaling') + for e in grads: + check_variable_and_dtype(e, "x", ['float16', 'float32', 'float64'], + 'update_loss_scaling') + if e.dtype == core.VarDesc.VarType.FP16: + assert self._loss_scaling.dtype == core.VarDesc.VarType.FP32, \ + "The dtype of prev_loss_scaling should be float32 when the dtype of x is float16." + else: + assert self._loss_scaling.dtype == e.dtype, "The dtype of prev_loss_scaling should be equal to the dtype of x." + + inputs = { + 'X': grads, + 'FoundInfinite': found_inf, + 'PrevLossScaling': self._loss_scaling, + 'InGoodSteps': self._num_good_steps, + 'InBadSteps': self._num_bad_steps + } + + outputs = { + 'Out': grads, + 'LossScaling': self._loss_scaling, + 'OutGoodSteps': self._num_good_steps, + 'OutBadSteps': self._num_bad_steps + } + + attrs = { + 'incr_every_n_steps': self.get_attr("incr_every_n_steps"), + 'decr_every_n_nan_or_inf': self.get_attr("decr_every_n_nan_or_inf"), + 'incr_ratio': self.get_attr("incr_ratio"), + 'decr_ratio': self.get_attr("decr_ratio"), + 'stop_update': self.get_attr("stop_update"), + 'op_role': OpRole.Optimize + } + + new_op = main_block.append_op(type='update_loss_scaling', + inputs=inputs, + outputs=outputs, + attrs=attrs) + + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = world_process_group.ranks + new_op_dist_attr.impl_idx = 0 + if len(world_process_group.ranks) > 1: + new_op_dist_attr.impl_type = "update_loss_scaling" + for g in grads: + g_dist_attr = self.dist_context.get_tensor_dist_attr_for_program(g) + assert g_dist_attr is not None + new_op_dist_attr.set_input_dims_mapping(g.name, + g_dist_attr.dims_mapping) + new_op_dist_attr.set_output_dims_mapping(g.name, + g_dist_attr.dims_mapping) + self.dist_context.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + + main_block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_data_parallel_optimization.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_data_parallel_optimization.py new file mode 100644 index 0000000000000000000000000000000000000000..70592e8b38037d3fcb8f83a111c0250324e7f211 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_data_parallel_optimization.py @@ -0,0 +1,587 @@ +# Copyright (c) 2022 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. + +from collections import OrderedDict +import numpy as np + +import paddle +from paddle.fluid import core, unique_name +from paddle.fluid.framework import default_main_program +from paddle.distributed.fleet.meta_optimizers.common import OpRole, OP_ROLE_KEY, OP_ROLE_VAR_KEY +from paddle.distributed.auto_parallel.operators.common import is_data_parallel_scale_op, is_data_parallel_reduce_op +from paddle.distributed.auto_parallel.utils import is_loss_grad_op, is_optimize_op, is_backward_op, ring_id_to_process_group, find_higher_order_backward_op +from .pass_base import PassBase, PassType, register_pass + +# add new optimizers supporting rescale_grad here +__rescale_grad_supported_opts__ = [ + 'lars_momentum', 'sparse_momentum', 'dgc_momentum', 'momentum', + 'merge_momentum' +] + +# a heuristic number +__max_stream_num_allow__ = 16 + + +def numel(var): + return np.prod(list(var.shape)) + + +@register_pass("auto_parallel_data_parallel_optimization") +class DataParallelOptimizationPass(PassBase): + """ + Apply Optimizations that specialized for data parallelism in Auto Parallel. + 1. prune grad scaling + 2. overlap comm and calc + 3. fuse allreduce + """ + + def __init__(self): + super(DataParallelOptimizationPass, self).__init__() + # NOTE not use depence on loss and param_grads + self.set_attr("dist_context", None) + self.set_attr("global_rank", -1) + self.set_attr("use_sharding", False) + # {grad1: group1, grad2: group1, grad3: group2} + # record the order for fuse grad data memory + self._grad_name_to_group_map = OrderedDict() + # {group1:[grad1, grad2] , group2:[grad3]} + self._group_to_grad_name_map = OrderedDict() + self._support_rescale_grad = False + + def _check_self(self): + if self.get_attr("dist_context") is None: + return False + if (not isinstance(self.get_attr("global_rank"), + int)) or self.get_attr("global_rank") < 0: + return False + + return True + + def _check_conflict(self, other_pass): + return True + + def _type(self): + return PassType.COMM_OPT + + def _apply_single_impl(self, main_program, startup_program, context): + + self.dist_context = self.get_attr("dist_context") + self.global_rank = int(self.get_attr("global_rank")) + self.use_sharding = self.get_attr("use_sharding") + + with paddle.static.program_guard(main_program, startup_program): + self._analyze_program() + + if self.is_data_parallel_applied(): + self._prune_grad_scaling() + self._calc_comm_overlap() + grad_group = self._fuse_allreduce() + + # self.summary(grad_group) + + def _prune_grad_scaling(self): + + if not self._could_be_prune(): + return + + if self._all_dp_groups_same_degree(): + self._scale_backward_initial_grad() + else: + self._update_opt_rescale_grad() + + self._remove_grad_scaling() + + def _calc_comm_overlap(self): + if not self._could_be_overlap(): + return + self._comms_overlap_calc() + self._calc_wait_comms() + + def _fuse_allreduce(self): + + if not self._could_be_fuse(): + return [] + + grad_group = self._group_grads() + self._update_program(grad_group) + + return grad_group + + def _analyze_program(self): + """ + build two maps + {param_grad_name: data_parallel_group} + {pdata_parallel_group: aram_grad_name} + """ + + block = default_main_program().global_block() + ops = block.ops + scaled_grads = [] + + for op in ops: + + if is_data_parallel_reduce_op(op): + grad_name = op.output_arg_names[0] + if grad_name in self._grad_name_to_group_map: + continue + assert op.has_attr( + "ring_id" + ), "Unexception: comm op [{}] has NOT ring id.".format(str(op)) + group = ring_id_to_process_group(op.attr("ring_id")) + + assert group is not None, "Unexception: data parallel group of [{}] from op [{}] is None".format( + grad_name, str(op)) + + self._grad_name_to_group_map[grad_name] = group + + if group not in self._group_to_grad_name_map: + self._group_to_grad_name_map[group] = [grad_name] + else: + self._group_to_grad_name_map[group].append(grad_name) + + elif is_data_parallel_scale_op(op): + grad_name = op.output_arg_names[0] + scaled_grads.append(grad_name) + + # TODO support multiple optimizers in on network in future. + # here we assume that the optimizer is unique in network. + elif is_optimize_op( + op) and op.type in __rescale_grad_supported_opts__: + self._support_rescale_grad = True + + not_synchronized_grads = [] + for grad_name in scaled_grads: + if grad_name not in self._grad_name_to_group_map: + not_synchronized_grads.append(grad_name) + assert len( + not_synchronized_grads + ) == 0, "Unexception: gradients [{}] is scaled BUT NOT synchronized.".format( + not_synchronized_grads) + + def is_data_parallel_applied(self): + return len(self._group_to_grad_name_map) > 0 + + def _could_be_prune(self): + + return self.dist_context.gradient_scale and ( + self._support_rescale_grad or self._all_dp_groups_same_degree()) + + def _all_dp_groups_same_degree(self): + return len( + set([ + len(group.ranks) + for group in self._group_to_grad_name_map.keys() + ])) == 1 + + def _scale_backward_initial_grad(self): + + block = default_main_program().global_block() + dp_degree = len(list(self._group_to_grad_name_map.keys())[0].ranks) + + for idx, op in reversed(list(enumerate(block.ops))): + if is_loss_grad_op(op): + assert op.type == 'fill_constant', \ + "loss_grad_op must be fill_constant op, " \ + "but this op is {}".format(op.type) + assert op.has_attr('value') + loss_scale = float(op.attr('value')) + loss_scale = loss_scale / dp_degree + op._set_attr('value', loss_scale) + break + + def _remove_grad_scaling(self): + block = default_main_program().global_block() + + for op_idx, op in reversed(list(enumerate(block.ops))): + if is_data_parallel_scale_op(op): + block._remove_op(op_idx, False) + + block._sync_with_cpp() + + def _update_opt_rescale_grad(self): + + block = default_main_program().global_block() + scaled_grads = set() + + for idx, op in reversed(list(enumerate(block.ops))): + if is_optimize_op( + op) and op.type in __rescale_grad_supported_opts__: + assert op.has_attr( + 'rescale_grad' + ), "Unexception: op [{}] is supported to have [rescale_grad] attribute.".format( + str(op)) + assert len( + op.input("Grad") + ) == 1, "Unexception: op [{}] is supported to have only one input grad var.".format( + str(op)) + + grad_name = op.input("Grad")[0] + dp_degree = len( + list(self._grad_name_to_group_map[grad_name].ranks)) + scaled_grads.add(grad_name) + + rescale_grad = float(op.attr('rescale_grad')) / dp_degree + op._set_attr('rescale_grad', rescale_grad) + + assert scaled_grads == set(self._grad_name_to_group_map.keys( + )), "Unexception: gradients [{}] are unscaled.".format( + set(self._grad_name_to_group_map.keys()) - scaled_grads) + + def _could_be_overlap(self): + # NOTE current different nccl comm will use different cuda stream + # so if there too many dp group there will be too many stream need to be + # created and sync. + # revise here when framework support custom stream in static mode. + num_dp_comm_stream = len(set(self._group_to_grad_name_map.keys())) + if num_dp_comm_stream > __max_stream_num_allow__: + return False + if self.use_sharding: + return False + return True + + def _comms_overlap_calc(self): + # TODO support InterpreterCore executor for overlap. + # InterpreterCore has a different logic for overlapping + # which is different from use_calc_stream + block = default_main_program().global_block() + ops = block.ops + + # comm wait calc to finish + for idx, op in reversed(list(enumerate(block.ops))): + if is_data_parallel_reduce_op(op): + assert op.has_attr('use_calc_stream') + assert op.has_attr('ring_id') + + op._set_attr('use_calc_stream', False) + ring_id = op.attr("ring_id") + + block._insert_op_without_sync(idx, + type='c_wait_compute', + inputs={'X': []}, + outputs={'Out': []}, + attrs={ + 'op_role': OpRole.Backward, + 'ring_id': ring_id + }) + + block._sync_with_cpp() + + def _calc_wait_comms(self): + + block = default_main_program().global_block() + ops = block.ops + + # NOTE the naive overlap implement in static hybird parallel only sync comm stream + # at the end of Backward phase, based on a strong constraint that + # all communicating gradient would NOT be used after communication in Backward phase. + # BUT this constraint will fail for scenario like Weight-Sharing and Higher-Order Differentiation, + # where gradient will be involved in other calculation between data-parallel allreduce kernel submmited + # into comm streams and the synchronization of comm stream at the end of Backward phase. + # synchronization of comm stream should add according to the usage of communicating gradients + # to support Overlapping for Weight-Sharing and Higher-Order Differentiation. + + ring_id_to_un_sync_grad_map = {} + op_idx_to_sync_ring_id_map = {} + for group in self._group_to_grad_name_map.keys(): + ring_id_to_un_sync_grad_map[group.id] = [] + + # analyze the where need to sync + for i, op in enumerate(ops): + if is_data_parallel_reduce_op(op): + ring_id = op.attr("ring_id") + grad_name = op.output_arg_names[0] + ring_id_to_un_sync_grad_map[ring_id].append(grad_name) + elif is_data_parallel_scale_op(op): + continue + # other ops that might use communicating grad + else: + for input_var_name in op.input_arg_names: + for ring_id, unsync_grad_names in ring_id_to_un_sync_grad_map.items( + ): + if input_var_name in unsync_grad_names: + # need to sync before op_i + if i in op_idx_to_sync_ring_id_map: + op_idx_to_sync_ring_id_map[i].append(ring_id) + else: + op_idx_to_sync_ring_id_map[i] = [ring_id] + # all grads in this comm stream are synced + ring_id_to_un_sync_grad_map[ring_id] = [] + + # insert synchronization + indices = list(op_idx_to_sync_ring_id_map.keys()) + # TODO the synchronization could be optimized + # we should record the event of a gradient is communicating and + # only wait for that event to be completed. + # BUT paddle static currently not support op api for event record only, so + # here we try to wait for all kernel in that comm stream to be finish which is not that optimized. + for i in sorted(indices, reverse=True): + for ring_id in op_idx_to_sync_ring_id_map[i]: + + block._insert_op_without_sync(i, + type='c_wait_comm', + inputs={'X': []}, + outputs={'Out': []}, + attrs={ + 'op_role': OpRole.Backward, + 'ring_id': ring_id + }) + + def _could_be_fuse(self): + # TODO support gradient fuse higher order gradient. + # should analyse the dependencies of gradient in backward. + if find_higher_order_backward_op(default_main_program()): + return False + if self.use_sharding: + return False + return True + + def _group_grads(self): + """ + conditions for gradients to be grouped: + 1. group size < max_fuse_numel + 2. same dp group + 3. same dtype + 4. dependency: grad would NOT be used by other ops within group segment + + gradients inside same group would be fuse into one coalesce tensor + """ + + block = default_main_program().global_block() + ops = block.ops + + # group individual grad vars + # TODO consider fuse gradient for sharding reduce + # TODO let user to set fuse_grad_size + # emb = 50000 * h, ffn = 8 * h * h, mha = 4 * h * h + h = 2048 + ffn_numel = 2 * (4 * h) * h + mha_numel = 3 * h * h + h * h + max_fuse_numel = ffn_numel + mha_numel + grad_groups = [] + cur_group = GradientsGroup(ops, max_fuse_numel) + grouped_grad_names = set() + + def collect_group(cur_group, grad_var, ring_id, i): + if len(cur_group.gradients) == 0: + cur_group = None + elif len(cur_group.gradients) == 1: + grouped_grad_names.remove(cur_group.gradients[0].name) + else: + cur_group.finalize() + grad_groups.append(cur_group) + + new_group = GradientsGroup(ops, max_fuse_numel) + if grad_var: + new_group.add(grad_var, ring_id, i) + grouped_grad_names.add(grad_var.name) + return new_group + + def op_depend_on_group(op, group): + vars_ = set(op.input_arg_names + op.output_arg_names) + grad_names = set([grad.name for grad in group.gradients]) + return len(vars_.intersection(grad_names)) > 0 + + for i, op in enumerate(ops): + if is_data_parallel_reduce_op(op): + ring_id = op.attr("ring_id") + grad_name = op.output_arg_names[0] + grad_var = block.var(grad_name) + grad_numel = numel(grad_var) + + if cur_group.acceptable(grad_var, ring_id): + assert grad_name not in grouped_grad_names + grouped_grad_names.add(grad_name) + cur_group.add(grad_var, ring_id, i) + else: + cur_group = collect_group(cur_group, grad_var, ring_id, i) + else: + if op_depend_on_group(op, cur_group): + cur_group = collect_group(cur_group, None, None, None) + + # collect last group + collect_group(cur_group, None, None, None) + + return grad_groups + + def _update_program(self, grad_groups): + + block = default_main_program().global_block() + + remove_op_types = ['scale', 'c_allreduce_sum', 'c_wait_compute'] + + for i, group in enumerate(grad_groups[::-1]): + + # create coalecse tensor + group.coalesce_var = block.create_var(name=unique_name.generate( + 'coalecse_grad_{}'.format(i)), + dtype=group.dtype, + persistable=False, + stop_gradient=True) + + # update allreduce & scale op + if group.scale_op_idx != -1: + scale_op = block.ops[group.scale_op_idx] + assert scale_op.type == 'scale', "should found scale op but found {}".format( + str(scale_op)) + scale_op._rename_input(scale_op.input_arg_names[0], + group.coalesce_var.name) + scale_op._rename_output(scale_op.output_arg_names[0], + group.coalesce_var.name) + + allreduce_op = block.ops[group.allreduce_op_idx] + assert allreduce_op.type == 'c_allreduce_sum', "should found c_allreduce_sum op but found {}".format( + str(allreduce_op)) + allreduce_op._rename_input(allreduce_op.input_arg_names[0], + group.coalesce_var.name) + allreduce_op._rename_output(allreduce_op.output_arg_names[0], + group.coalesce_var.name) + + # remvoe un-used op + remove_op_indices = group.remove_wait_op_indices + group.remove_allreduce_op_indices + group.remove_scale_op_indices + for idx in sorted(remove_op_indices, reverse=True): + assert block.ops[ + idx].type in remove_op_types, "Unexception: try to remove op {}".format( + str(op)) + block._remove_op(idx) + + # insert coalecse op + concated_shapes = [] + concated_ranks = [] + for grad_ in group.gradients: + shape = grad_.shape + concated_shapes.extend(shape) + concated_ranks.append(len(shape)) + + grad_names = [grad.name for grad in group.gradients] + block._insert_op_without_sync(group.coalesce_op_idx, + type="coalesce_tensor", + inputs={"Input": grad_names}, + outputs={ + "Output": grad_names, + "FusedOutput": group.coalesce_var + }, + attrs={ + "copy_data": False, + "use_align": True, + "dtype": group.dtype, + "concated_shapes": + concated_shapes, + "concated_ranks": concated_ranks, + OP_ROLE_KEY: OpRole.Backward + }) + + block._sync_with_cpp() + # TODO update dist attr + + def summary(self, grad_groups=[]): + # TODO: add logger module + import logging + self._logger = logging.getLogger() + self._logger.propagate = False + if not self._logger.handlers: + self._logger.setLevel(logging.INFO) + log_handler = logging.StreamHandler() + log_format = logging.Formatter( + '[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s' + ) + log_handler.setFormatter(log_format) + self._logger.addHandler(log_handler) + + if len(grad_groups) > 0: + self._logger.info( + "origin {} allreduce ops are fused into {} coalecse allreduce ops." + .format(len(self._grad_name_to_group_map.keys()), + len(grad_groups))) + self._logger.info("gradient fusing group are following: ") + fused_grads = set() + for i, group in enumerate(grad_groups): + self._logger.info( + "coalecse gradient [{}] is composed by: {}".format( + i, [grad.name for grad in group.gradients])) + fused_grads.update([grad.name for grad in group.gradients]) + individual_grads = set( + self._grad_name_to_group_map.keys()) - set(fused_grads) + self._logger.info( + "the following [{}] gradients are not fused: ".format( + len(individual_grads))) + self._logger.info("individual gradient {}".format(individual_grads)) + + +class GradientsGroup(object): + + def __init__(self, ops, max_group_size): + self.max_group_size = max_group_size + self.ops = ops + + self.gradients = [] + self.numel = 0 + self.dtype = None + self.ring_id = None + self.coalesce_var = None + self.coalesce_op_idx = -1 + self.allreduce_op_idx = -1 + self.scale_op_idx = -1 + self.remove_wait_op_indices = [] + self.remove_allreduce_op_indices = [] + self.remove_scale_op_indices = [] + + def acceptable(self, grad_var, ring_id): + if len(self.gradients) == 0: + return True + if ring_id != self.ring_id: + return False + if numel(grad_var) + self.numel > self.max_group_size: + return False + if grad_var.dtype != self.dtype: + return False + + return True + + def add(self, grad_var, ring_id, i): + self.gradients.append(grad_var) + self.ring_id = ring_id + self.dtype = grad_var.dtype + self.numel += numel(grad_var) + + # remove auxiliary ops in non-fuse dp allreduce + self.remove_allreduce_op_indices.append(i) + + # NOTE this pass rely on the original synchronization add in previous passes + # (same stream or calc_wait_comm & comm_wait_calc) + # to guarantee the correctness of comm_calc execution order. + # so the calc_wait_comm should be keep. + grad_op_idx = i - 1 + if i > 0 and self.ops[i - 1].type == 'c_wait_compute': + self.remove_wait_op_indices.append(i - 1) + grad_op_idx -= 1 + if i + 1 < len(self.ops) and is_data_parallel_scale_op(self.ops[i - 1]): + self.remove_scale_op_indices.append(i + 1) + + if len(self.gradients) == 1: + # TODO Remove this is a temporary hack for Tensor Parallel. the logic + # for find grad_op should be more general. + if self.ops[grad_op_idx].type == "c_allreduce_sum": + grad_op_idx -= 1 + + grad_op = self.ops[grad_op_idx] + assert grad_var.name in grad_op.output_arg_names, "grad [{}] should be output of {}".format( + grad_var.name, str(grad_op)) + self.coalesce_op_idx = grad_op_idx + + def finalize(self): + self.allreduce_op_idx = self.remove_allreduce_op_indices.pop() + if len(self.remove_wait_op_indices) > 1: + self.remove_wait_op_indices.pop() + if len(self.remove_scale_op_indices) > 1: + self.scale_op_idx = self.remove_scale_op_indices.pop() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_fp16.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_fp16.py new file mode 100644 index 0000000000000000000000000000000000000000..34684c6ca41800b45b99aa48ef8e716df0a6fd5e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_fp16.py @@ -0,0 +1,818 @@ +# Copyright (c) 2021 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. + +from collections import defaultdict + +import paddle +from paddle.framework import core +from paddle.fluid.framework import default_main_program, default_startup_program +from paddle.fluid import unique_name +from .pass_base import register_pass +from paddle.fluid.data_feeder import check_variable_and_dtype, check_type +from paddle.distributed.auto_parallel.utils import ( + set_var_dist_attr, + naive_set_dist_op_attr_for_program_by_mesh_and_mapping, +) +from paddle.distributed.auto_parallel.process_group import ( + get_world_process_group, +) +from paddle.fluid.contrib.mixed_precision.fp16_utils import ( + AutoMixedPrecisionLists, +) +from paddle.fluid.contrib.mixed_precision.fp16_utils import ( + _keep_layer_norm_scale_bias_to_fp32, + _need_keep_fp32, + _valid_types, + _dtype_to_str, +) +from paddle.distributed.auto_parallel.dist_attribute import ( + OperatorDistributedAttribute, +) +from paddle.distributed.auto_parallel.utils import ( + is_forward_op, + is_backward_op, + OP_ROLE_KEY, + OpRole, +) +from .auto_parallel_amp import AMPPass + +world_process_group = get_world_process_group() +# if user use python "+, -, * /" for network, there might be cast in vanilla program +__amp_skip_ops__ = [ + 'create_py_reader', + 'create_double_buffer_reader', + 'while', + 'cast', +] + + +def set_op_dtype_to_fp16(op): + if ( + op.has_attr('in_dtype') + and op.attr('in_dtype') == core.VarDesc.VarType.FP32 + ): + op._set_attr('in_dtype', core.VarDesc.VarType.FP16) + if ( + op.has_attr('out_dtype') + and op.attr('out_dtype') == core.VarDesc.VarType.FP32 + ): + op._set_attr('out_dtype', core.VarDesc.VarType.FP16) + if op.has_attr('dtype') and op.attr('dtype') == core.VarDesc.VarType.FP32: + op._set_attr('dtype', core.VarDesc.VarType.FP16) + + +# adapot for backward op +def _keep_fp32_input(op, in_name): + op_type = op.type + if op_type == 'batch_norm': + # Scale, Bias, Mean, Variance should be float32. + return in_name != 'X' + if op_type == 'layer_norm' and _keep_layer_norm_scale_bias_to_fp32(): + return in_name != 'X' + if op_type == 'fused_bn_add_activation': + return in_name not in {'X', 'Z'} + if op_type == 'resnet_unit': + return in_name not in {'X', 'FilterX', 'Z', 'FilterZ'} + if op_type in ['fused_attention', 'fused_feedforward']: + return in_name in { + 'LnScale', + 'LnBias', + 'Ln2Scale', + 'Ln2Bias', + "Ln1Scale", + "Ln1Bias", + } + # backward + if op_type in ['batch_norm_grad']: + return in_name not in {'X', 'Y@GRAD'} + if op_type in ['layer_norm_grad']: + return in_name not in {'X', 'Y@GRAD'} + return False + + +def _keep_fp32_output(op, out_name): + op_type = op.type + if op_type in ['batch_norm', 'fused_bn_add_activation']: + return out_name != 'Y' + if op_type == 'layer_norm' and _keep_layer_norm_scale_bias_to_fp32(): + return out_name != 'Y' + if op_type == 'resnet_unit': + return out_name not in {'Y', 'ConvX', 'ConvZ'} + if op_type in ['fused_attention', 'fused_feedforward']: + return out_name in { + 'LnMean', + 'LnVariance', + 'Ln2Mean', + 'Ln2Variance', + 'Ln1Mean', + 'Ln1Variance', + } + # backward + if op_type in ['layer_norm_grad']: + return out_name != 'X@GRAD' + if op_type in ['batch_norm_grad']: + return out_name != 'X@GRAD' + return False + + +class FP16State(object): + def __init__( + self, + program, + amp_list, + dist_context, + use_fp16_guard, + input_data_var_names=None, + ): + self.program = program + self.amp_list = amp_list + self.use_fp16_guard = use_fp16_guard + self.dist_context = dist_context + self.grad_op_to_op_map = ( + self.dist_context.dist_op_context.grad_op_id_to_op_id + ) + if input_data_var_names: + self.input_data_var_names = input_data_var_names + else: + self.input_data_var_names = [] + self._op_fp16_dict = ( + {} + ) # op_id --> True/False. 'True' means that the op is should run in fp16 mode. + # a trick to determine leaf tensor node in program {varname: generator_op_id} + self.forward_non_leaf_tensors = {} + # record the cast ops that are inserted for a forward + self.forward_input_cast_ops = defaultdict( + list + ) # {forward_op_id: [(output_name, input_name, out_dtype, in_dtype, slot_name), ]} + self.is_train = False + + def _is_fp16_op(self, op_id): + return self._op_fp16_dict.get(op_id, None) + + def _build_state(self): + """ + mark the execution mode (fp16 or fp32) for ops in all blocks + include forward ops & backward ops + """ + # mark op dtype + # assume all backward block are behind forward blocks + for block in self.program.blocks: + for op in block.ops: + self._mark_op(op) + + # set forward tensor dtype + for block in self.program.blocks: + self.resolute_tensor_dtype(block) + + # insert cast ops + for block in self.program.blocks: + self.cast_block(block) + + return self.is_train + + def _mark_op(self, op): + + if op.type in __amp_skip_ops__: + return + + if is_forward_op(op): + + # ernie inference trick + if op.type == "assign" and "array_" in op.input_arg_names[0]: + self._op_fp16_dict[op.desc.original_id()] = False + return + if _need_keep_fp32( + op, self.amp_list.unsupported_list, self.use_fp16_guard + ): + self._op_fp16_dict[op.desc.original_id()] = False + else: + self._op_fp16_dict[op.desc.original_id()] = True + for var_name in op.output_arg_names: + # assert var_name not in self.forward_non_leaf_tensors, "{}".format(var_name) + self.forward_non_leaf_tensors[var_name] = op.desc.id() + + elif is_backward_op(op) == int(OpRole.Backward): + + if op.desc.original_id() in self.grad_op_to_op_map: + fwd_op_id = self.grad_op_to_op_map[op.desc.original_id()] + assert fwd_op_id in self._op_fp16_dict, "{}".format(str(op)) + self._op_fp16_dict[op.desc.original_id()] = self._op_fp16_dict[ + fwd_op_id + ] + + if int(op.attr('op_role')) == 257: + self.is_train = True + + def set_var_to_fp16(self, var_name, block): + var = None + try: + var = block.var(var_name) + except ValueError as e: + var = block._var_recursive(var_name) + # var = self.program.global_block().var(var_name) + + # NOTE(JZ-LIANG) "array_" is a hack to adopt for ernie3.0 inference, since there is + # a trick which make the LOD_TENSOR_ARRAY to the float32 in while block to reset the LOD_TENSOR_ARRAY + if var is None or var.type not in _valid_types or "array_" in var_name: + return + + if var.dtype == core.VarDesc.VarType.FP32: + var.desc.set_dtype(core.VarDesc.VarType.FP16) + + def resolute_tensor_dtype(self, block): + + for op in block.ops: + if is_forward_op(op): + # NOTE (JZ-LIANG) un-expected cast op when user call "+, -, *, /" in python + if ( + self._is_fp16_op(op.desc.original_id()) == True + or op.type == "cast" + ): + for in_name in op.input_names: + if _keep_fp32_input(op, in_name): + continue + for in_var_name in op.input(in_name): + if ( + in_var_name not in self.forward_non_leaf_tensors + and in_var_name not in self.input_data_var_names + ): + self.set_var_to_fp16(in_var_name, block) + for out_name in op.output_names: + if _keep_fp32_output(op, out_name): + continue + for out_var_name in op.output(out_name): + self.set_var_to_fp16(out_var_name, block) + set_op_dtype_to_fp16(op) + # NOTE (JZ-LIANG) un-expected cast op when user call "+, -, *, /" in python + elif self._is_fp16_op(op.desc.original_id()) == False: + for out_var_name in op.output_arg_names: + out_var = block.vars.get(out_var_name) + if out_var is None or out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP16: + out_var.desc.set_dtype(core.VarDesc.VarType.FP32) + elif is_backward_op(op): + if self._is_fp16_op(op.desc.original_id()) == True: + for out_name in op.output_names: + if _keep_fp32_output(op, out_name): + continue + for out_var_name in op.output(out_name): + self.set_var_to_fp16(out_var_name, block) + set_op_dtype_to_fp16(op) + # NOTE (JZ-LIANG) un-expected cast op when user call "+, -, *, /" in python + elif self._is_fp16_op(op.desc.original_id()) == False: + for out_var_name in op.output_arg_names: + out_var = block.vars.get(out_var_name) + if out_var is None or out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP16: + out_var.desc.set_dtype(core.VarDesc.VarType.FP32) + + def cast_block(self, block): + dist_op_context = self.dist_context.dist_op_context + idx = 0 + while idx < len(block.ops): + op = block.ops[idx] + num_cast_ops = 0 + + if op.type in __amp_skip_ops__: + idx += 1 + continue + elif is_forward_op(op): + if self._is_fp16_op(op.desc.original_id()) == False: + num_cast_ops = self._insert_forward_cast_ops( + op, + idx, + block, + core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32, + self.dist_context, + ) + elif self._is_fp16_op(op.desc.original_id()) == True: + num_cast_ops = self._insert_forward_cast_ops( + op, + idx, + block, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16, + self.dist_context, + ) + elif is_backward_op(op): + if op.desc.original_id() in dist_op_context.grad_op_id_to_op_id: + if self._is_fp16_op(op.desc.original_id()) == False: + num_cast_ops = self._insert_backward_cast_ops( + op, + idx, + block, + core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32, + self.dist_context, + ) + elif self._is_fp16_op(op.desc.original_id()) == True: + num_cast_ops = self._insert_backward_cast_ops( + op, + idx, + block, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16, + self.dist_context, + ) + elif op.type == "sum": + # all inputs dtype of sum should be equal and output dtype should follow input + out_var_name = op.output_arg_names[0] + in_var_name = op.input_arg_names[0] + out_var = block.var(out_var_name) + in_var = block._find_var_recursive(in_var_name) + for in_var_name in op.input_arg_names: + assert ( + in_var.dtype == block.var(in_var_name).dtype + ), "{}, {}, {}".format( + in_var, block.var(in_var_name), str(op) + ) + out_var.desc.set_dtype(in_var.dtype) + + idx += num_cast_ops + 1 + block._sync_with_cpp() + + def _insert_forward_cast_ops( + self, op, idx, block, src_dtype, dst_dtype, dist_context + ): + + num_cast_ops = 0 + + for in_name in op.input_names: + if src_dtype == core.VarDesc.VarType.FP32 and _keep_fp32_input( + op, in_name + ): + continue + + consume_op_attr = dist_context.get_op_dist_attr_for_program(op) + assert consume_op_attr is not None + for in_var_name in op.input(in_name): + in_var = block._find_var_recursive(in_var_name) + if ( + in_var is None + or in_var.type not in _valid_types + or in_var.dtype == dst_dtype + ): + continue + + if in_var.dtype == src_dtype: + cast_name = ( + in_var.name + '.cast_' + _dtype_to_str(dst_dtype) + ) + cast_var = block.vars.get(cast_name) + self.forward_input_cast_ops[op.desc.original_id()] += [ + (cast_name, in_var.name, dst_dtype, src_dtype, in_name) + ] + + in_var_dist_attr = consume_op_attr.get_input_dist_attr( + in_var.name + ) + assert in_var_dist_attr is not None + # truly insert cast op + if cast_var is None or cast_var.dtype != dst_dtype: + # NOTE we make the cast op and var's dist attr as the op that consume the + # cast var instead of the op which generates the var + # refine op's dist_attr + ref_mesh = in_var_dist_attr.process_mesh + ref_mapping = in_var_dist_attr.dims_mapping + + cast_var = block.create_var( + name=cast_name, + dtype=dst_dtype, + persistable=False, + stop_gradient=in_var.stop_gradient, + ) + set_var_dist_attr( + dist_context, cast_var, ref_mapping, ref_mesh + ) + + cast_op = block._insert_op_without_sync( + idx, + type="cast", + inputs={"X": in_var}, + outputs={"Out": cast_var}, + attrs={ + "in_dtype": in_var.dtype, + "out_dtype": cast_var.dtype, + OP_ROLE_KEY: OpRole.Forward, + }, + ) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + cast_op, ref_mesh, ref_mapping, dist_context + ) + num_cast_ops += 1 + + op._rename_input(in_var.name, cast_name) + consume_op_attr.set_input_dist_attr( + cast_name, in_var_dist_attr + ) + + if op.has_attr('out_dtype') and op.attr('out_dtype') != -1: + assert op.attr('out_dtype') == dst_dtype + + return num_cast_ops + + def _insert_backward_cast_ops( + self, op, idx, block, src_dtype, dst_dtype, dist_context + ): + + num_cast_ops = 0 + op_id = op.desc.id() + original_id = op.desc.original_id() + dist_op_context = dist_context.dist_op_context + forward_op_id = dist_op_context.grad_op_id_to_op_id[original_id] + + grad_op_attr = dist_context.get_op_dist_attr_for_program(op) + assert grad_op_attr is not None + + for out_var_name in op.output_arg_names: + out_var = block.var(out_var_name) + if _keep_fp32_output(op, out_var.name): + continue + assert out_var.dtype == dst_dtype, "{}, {}".format( + str(out_var), dst_dtype + ) + + for ( + cast_name, + src_name, + dst_dtype, + src_dtype, + slot_name, + ) in self.forward_input_cast_ops[forward_op_id]: + + # rename input + assert src_name in op.input( + slot_name + ), "var: {} not in op's {}. {}".format(src_name, slot_name, str(op)) + src_var_dist_attr = grad_op_attr.get_input_dist_attr(src_name) + assert src_var_dist_attr is not None + op._rename_input(src_name, cast_name) + grad_op_attr.set_input_dist_attr(cast_name, src_var_dist_attr) + + # create cast grad + grad_slot_name = slot_name + "@GRAD" + assert grad_slot_name in op.output_names + if len(op.output(grad_slot_name)) == 0: + var = block.var(src_name) + assert var.stop_gradient is True + continue + assert len(op.output(grad_slot_name)) == 1 + grad_name = op.output(grad_slot_name)[0] + grad = block.var(grad_name) + grad_dist_attr = grad_op_attr.get_output_dist_attr(grad_name) + assert grad_dist_attr is not None, "{}".format(grad_name) + ref_mesh = grad_dist_attr.process_mesh + ref_mapping = grad_dist_attr.dims_mapping + + cast_grad = block.create_var( + name=unique_name.generate_with_ignorable_key( + "".join([cast_name, '@GRAD']) + ), + dtype=dst_dtype, + shape=grad.shape, + type=grad.type, + persistable=grad.persistable, + stop_gradient=grad.stop_gradient, + ) + dist_context.set_tensor_dist_attr_for_program( + cast_grad, grad_dist_attr + ) + op._rename_output(grad_name, cast_grad.name) + grad_op_attr.set_output_dist_attr(cast_grad.name, grad_dist_attr) + + # add cast + cast_op = block._insert_op_without_sync( + idx + 1, + type="cast", + inputs={"X": [cast_grad.name]}, + outputs={"Out": [grad.name]}, + attrs={ + "in_dtype": dst_dtype, + "out_dtype": src_dtype, + OP_ROLE_KEY: OpRole.Backward, + }, + ) + grad.desc.set_dtype(src_dtype) + + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + cast_op, ref_mesh, ref_mapping, dist_context + ) + num_cast_ops += 1 + + return num_cast_ops + + +def _check_and_update_gradient(grads, loss_scaling, name, dist_context): + + main_block = paddle.static.default_main_program().global_block() + main_block._sync_with_cpp() + + check_type(grads, 'x', (tuple, list), 'check_finite_and_unscale') + for e in grads: + check_variable_and_dtype( + e, + "x", + ['float16', 'float32', 'float64'], + 'check_finite_and_unscale', + ) + + found_inf = main_block.create_var( + name=unique_name.generate_with_ignorable_key( + ".".join(['find_infinite_scale', name]) + ), + shape=[1], + dtype='bool', + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False, + ) + set_var_dist_attr(dist_context, found_inf, [-1], world_process_group.ranks) + + inputs = {'X': grads, 'Scale': loss_scaling} + outputs = {'Out': grads, 'FoundInfinite': found_inf} + attrs = {'op_role': OpRole.Optimize} + new_op = main_block.append_op( + type='check_finite_and_unscale', + inputs=inputs, + outputs=outputs, + attrs=attrs, + ) + + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = world_process_group.ranks + new_op_dist_attr.impl_idx = 0 + if len(world_process_group.ranks) > 1: + new_op_dist_attr.impl_type = "check_finite_and_unscale" + for g in grads: + g_dist_attr = dist_context.get_tensor_dist_attr_for_program(g) + assert g_dist_attr is not None + new_op_dist_attr.set_input_dims_mapping( + g.name, g_dist_attr.dims_mapping + ) + new_op_dist_attr.set_output_dims_mapping( + g.name, g_dist_attr.dims_mapping + ) + dist_context.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + return grads, found_inf + + +def _split_grads(params_grads): + grads = [g for _, g in params_grads] + fp32_grads = [g for g in grads if g.dtype == core.VarDesc.VarType.FP32] + fp16_grads = [g for g in grads if g.dtype == core.VarDesc.VarType.FP16] + assert len(fp32_grads) + len(fp16_grads) == len( + grads + ), "Data types of all grads must be either fp16 or fp32." + return grads, fp32_grads, fp16_grads + + +def _set_op_dist_attr_with_ranks(new_op, ranks, block, dist_context): + new_op_dist_attr = OperatorDistributedAttribute() + new_op_dist_attr.process_mesh = ranks + new_op_dist_attr.impl_idx = 0 + for var_name in new_op.input_arg_names: + var = block.var(var_name) + var_dist_attr = dist_context.get_tensor_dist_attr_for_program(var) + assert var_dist_attr is not None + new_op_dist_attr.set_input_dims_mapping( + var_name, var_dist_attr.dims_mapping + ) + for var_name in new_op.output_arg_names: + var = block.var(var_name) + var_dist_attr = dist_context.get_tensor_dist_attr_for_program(var) + assert var_dist_attr is not None + new_op_dist_attr.set_output_dims_mapping( + var_name, var_dist_attr.dims_mapping + ) + dist_context.set_op_dist_attr_for_program(new_op, new_op_dist_attr) + + +def _get_memcopy_idx(block, found_inf_var): + # use reduce_any op for check_nan_inf as the anchor for now + for idx, op in enumerate(block.ops): + if ( + op.type == 'reduce_any' + and op.output_arg_names[0] == found_inf_var.name + ): + return idx + 1 + + raise RuntimeError( + "not found the correct location for memcopy for found_inf_var." + ) + + +def _insert_memcopy(block, idx, src_var, dist_context, direction="D2H"): + src_name = src_var.name + output_var = block.create_var( + name=unique_name.generate_with_ignorable_key( + src_name.join(['memcopy_']) + ), + dtype=src_var.dtype, + shape=src_var.shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=src_var.stop_gradient, + ) + + set_var_dist_attr(dist_context, output_var, [-1], world_process_group.ranks) + + # TODO to support CUDAPinned/NPU/XPU Places + if direction == "D2H": + dst_place_type = 0 + elif direction == "D2H": + dst_place_type = 1 + else: + raise NotImplementedError( + "direction [{}] is not supported yet.".format(direction) + ) + + attrs = {'dst_place_type': dst_place_type} + new_op = block._insert_op_without_sync( + index=idx, + type='memcpy', + inputs={'X': [src_var]}, + outputs={'Out': [output_var]}, + attrs=attrs, + ) + _set_op_dist_attr_with_ranks( + new_op, world_process_group.ranks, block, dist_context + ) + block._sync_with_cpp() + return output_var + + +def cast_startup_program(): + main_program = default_main_program() + startup_program = default_startup_program() + + param_to_dtype = {} + for block in main_program.blocks: + for p in block.all_parameters(): + param_to_dtype[p.name] = p.dtype + + def is_initialization_op(op): + comm_op_prefix = "c_" + op_type = op.type + if op_type.startswith(comm_op_prefix): + return False + + if len(op.output_arg_names) != 1 and len(op.input_arg_names) != 0: + return False + + return True + + for op in startup_program.global_block().ops: + if is_initialization_op(op): + output_name = op.output_arg_names[0] + if ( + param_to_dtype.get(output_name, None) + == core.VarDesc.VarType.FP16 + ): + assert op.has_attr( + 'dtype' + ), "initialization op is supported to has dtype attribute but got {}.".format( + str(op) + ) + if op.attr('dtype') == core.VarDesc.VarType.FP32: + op._set_attr('dtype', core.VarDesc.VarType.FP16) + + +@register_pass("auto_parallel_fp16") +class FP16Pass(AMPPass): + def __init__(self): + super(FP16Pass, self).__init__() + + # NOTE: why FP16Pass can override apply_single_impl instead of + # apply_impl? AMP is an optimization pass for serial program, + # in distributed scenario, all ranks should have the same modification. + def _apply_single_impl(self, main_program, startup_program, context): + self.dist_context = self.get_attr("dist_context") + params_grads = self.get_attr("params_grads") + + amp_list = AutoMixedPrecisionLists( + set(self.get_attr("custom_white_list")), + set(self.get_attr("custom_black_list")), + None, + ) + + # NOTE don't not change input data dtype, since it is controled by dataloader + # and which is out of control of FP16 Pass + input_data_var_names = [var.name for var in self.get_attr("input_data")] + + with paddle.static.program_guard(main_program, startup_program): + fp16_state = FP16State( + main_program, + amp_list, + self.dist_context, + self.get_attr("use_fp16_guard"), + input_data_var_names, + ) + is_train = fp16_state._build_state() + + cast_startup_program() + + if is_train: + with paddle.static.program_guard(main_program, startup_program): + # TODO (JZ-LIANG)support cast forward program only when inference + self._init_amp_var() + self._scale_loss() + + grads, fp32_grads, fp16_grads = _split_grads(params_grads) + + if ( + self.get_attr("use_dynamic_loss_scaling") + or self.get_attr("init_loss_scaling") != 1.0 + ): + found_infs = [] + if fp32_grads: + with main_program._optimized_guard([]): + _, found_inf_fp32 = _check_and_update_gradient( + fp32_grads, + self._loss_scaling, + "@fp32", + self.dist_context, + ) + found_infs.append(found_inf_fp32) + if fp16_grads: + with main_program._optimized_guard([]): + _, found_inf_fp16 = _check_and_update_gradient( + fp16_grads, + self._loss_scaling, + "@fp16", + self.dist_context, + ) + found_infs.append(found_inf_fp16) + with main_program._optimized_guard([]): + block = main_program.global_block() + + all_infs = paddle.fluid.layers.concat(found_infs) + set_var_dist_attr( + self.dist_context, + all_infs, + [-1], + world_process_group.ranks, + ) + new_op = block.ops[-1] + assert new_op.type == "concat" + _set_op_dist_attr_with_ranks( + new_op, + world_process_group.ranks, + block, + self.dist_context, + ) + + found_inf = paddle.fluid.layers.reduce_any(all_infs) + set_var_dist_attr( + self.dist_context, + found_inf, + [-1], + world_process_group.ranks, + ) + new_op = block.ops[-1] + assert new_op.type == "reduce_any" + _set_op_dist_attr_with_ranks( + new_op, + world_process_group.ranks, + block, + self.dist_context, + ) + + if self.get_attr("use_dynamic_loss_scaling"): + with main_program._optimized_guard([]): + if fp32_grads: + self._update_loss_scaling(fp32_grads, found_inf) + if fp16_grads: + self._update_loss_scaling(fp16_grads, found_inf) + + # modify optimizer + base_opt = self.get_attr("base_opt") + base_opt._multi_precision = True + if self.get_attr("use_optimizer_fp16"): + base_opt._multi_precision = False + if isinstance( + base_opt, (paddle.fluid.optimizer.Adam, paddle.optimizer.AdamW) + ): + with main_program._optimized_guard([]): + # found_inf = paddle.tensor.creation._memcpy( + # found_inf, paddle.CPUPlace()) + insert_idx = _get_memcopy_idx(block, found_inf) + found_inf = _insert_memcopy( + block, insert_idx, found_inf, self.dist_context + ) + base_opt._set_auxiliary_var('found_inf', found_inf.name) + elif hasattr(base_opt, "_set_auxiliary_var"): + base_opt._set_auxiliary_var('found_inf', found_inf.name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_grad_clip.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_grad_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..34c0b7d56a03814bba6eccb1bd545e631337ed90 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_grad_clip.py @@ -0,0 +1,348 @@ +# Copyright (c) 2022 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. + +import numpy as np +from functools import reduce + +import paddle + +from paddle.fluid import core +from .pass_base import PassBase, register_pass +from ..auto_parallel.reshard import Resharder +from ..auto_parallel.process_group import get_world_process_group +from ..auto_parallel.utils import is_gradient_clip_op, is_optimize_op, OP_ROLE_KEY, OpRole, _get_comm_group +from ..auto_parallel.dist_attribute import TensorDistributedAttribute, OperatorDistributedAttribute + + +def _get_params_grads(block): + params_grads = [] + for op in reversed(block.ops): + if not is_optimize_op(op): + break + if "Param" in op.input_names and "Grad" in op.input_names: + param_name = op.input("Param")[0] + grad_name = op.input("Grad")[0] + param = block.var(param_name) + grad = block.var(grad_name) + params_grads.append((param, grad)) + return params_grads + + +def _get_dpmp_topology(origin_topology, sharding_group): + """ + Get dpmp topology from origin_topology + + Example: + the parallel strategy: dp4-mp2-sharding2 + the complete process_mesh: + topology: [4, 2] + processes: [0, 1, 2, 3, 4, 5, 6, 7] + the dpmp topology: [2, 2] + the sharding axis: 1 + """ + sharding_axis = 1 + dp_sharding_topology = [ + origin_topology[0] // sharding_group.nranks, sharding_group.nranks + ] + if dp_sharding_topology[0] == 1: + sharding_axis = 0 + dp_sharding_topology = dp_sharding_topology[1:] + + product_dp_sharding = reduce(lambda x, y: x * y, dp_sharding_topology) + product_topology = reduce(lambda x, y: x * y, origin_topology) + + if product_topology == product_dp_sharding: + dpmp_topology = dp_sharding_topology + else: + assert product_topology % product_dp_sharding == 0 + mp_degree = product_topology // product_dp_sharding + dpmp_topology = dp_sharding_topology + [mp_degree] + + return dpmp_topology, sharding_axis + + +def _get_dpmp_process_mesh(rank_id, topology, processes, sharding_group): + """ + Get dpmp process_mesh from the complete process_mesh which apply sharding. + + Example: + the parallel strategy: dp4-mp2-sharding2 + the complete process_mesh: + topology: [4, 2] + processes: [0, 1, 2, 3, 4, 5, 6, 7] + the dpmp process_mesh is: + 1) topology: [2, 2], processes: [0, 1, 4, 5] + 2) topology: [2, 2], processes: [2, 3, 6, 7] + """ + if sharding_group is None: + return topology, processes + + # get dpmp_topology + dpmp_topology, sharding_axis = _get_dpmp_topology(topology, sharding_group) + + # get all sharding_groups of ranks + sharding_groups = [] + for rank in processes: + group = _get_comm_group(processes, dpmp_topology, sharding_axis, rank) + if group not in sharding_groups: + sharding_groups.append(group) + + # get dpmp_processes + sharding_groups = np.array(sharding_groups) + dpmp_processes_in_sharding = None + for i in range(sharding_groups.shape[-1]): + if rank_id in sharding_groups[:, i]: + dpmp_processes_in_sharding = sharding_groups[:, i] + + assert dpmp_processes_in_sharding is not None + return dpmp_topology, list(dpmp_processes_in_sharding) + + +def _is_about_global_norm(rank_id, tensor_shape, topology, processes, + dims_mapping, sharding_group): + # get current process_mesh where the parameter exist. + dpmp_topology, dpmp_processes = _get_dpmp_process_mesh( + rank_id, topology, processes, sharding_group) + + complete_shape = Resharder.compute_complete_shape(tensor_shape, + dpmp_topology, + dims_mapping) + + complete_partitions = [] + complete_param_ranks = [] + for process in dpmp_processes: + partition_index = Resharder.compute_partition_index( + process, complete_shape, dims_mapping, dpmp_topology, + dpmp_processes) + if partition_index not in complete_partitions: + complete_partitions.append(partition_index) + complete_param_ranks.append(process) + + return rank_id in complete_param_ranks + + +class ClipHelper(object): + + def __init__(self, params_grads, rank_id, block, dist_context): + params, _ = zip(*params_grads) + self.params = list(params) + self.params_name = [p.name for p in self.params] + self.rank_id = rank_id + self.block = block + self.dist_context = dist_context + self.sharding_group = None + self.world_ranks = get_world_process_group().ranks + if hasattr(dist_context, '_sharding_group'): + self.sharding_group = dist_context._sharding_group + + def _is_calcuate_norm(self, name): + if not self._is_local_param(name): + return False, [] + + param = self.params[self.params_name.index(name)] + dist_attr = self._get_dist_attr(name) + topology = dist_attr.process_mesh.topology + processes = dist_attr.process_mesh.processes + dims_mapping = dist_attr.dims_mapping + return _is_about_global_norm(self.rank_id, param.shape, topology, + processes, dims_mapping, + self.sharding_group) + + def _get_dist_attr(self, name): + var = self.block.vars[name] + return self.dist_context.get_tensor_dist_attr_for_program(var) + + def _is_local_param(self, name): + if name not in self.params_name: + return False + return True + + def _is_local_var(self, name): + dist_attr = self._get_dist_attr(name) + assert dist_attr is not None + return self.rank_id in dist_attr.process_mesh.processes + + def _init_dist_attr(self, op): + op_dist_attr = OperatorDistributedAttribute() + op_dist_attr.process_mesh = self.world_ranks + for in_name in op.input_arg_names: + in_var = self.block.vars[in_name] + in_dist_attr = TensorDistributedAttribute() + in_dist_attr.process_mesh = self.world_ranks + in_dist_attr.dims_mapping = [-1] + self.dist_context.set_tensor_dist_attr_for_program( + in_var, in_dist_attr) + op_dist_attr.set_input_dist_attr(in_name, in_dist_attr) + for out_name in op.output_arg_names: + out_var = self.block.vars[out_name] + out_dist_attr = TensorDistributedAttribute() + out_dist_attr.process_mesh = self.world_ranks + out_dist_attr.dims_mapping = [-1] + self.dist_context.set_tensor_dist_attr_for_program( + out_var, out_dist_attr) + op_dist_attr.set_output_dist_attr(out_name, out_dist_attr) + self.dist_context.set_op_dist_attr_for_program(op, op_dist_attr) + + +@register_pass("auto_parallel_grad_clip") +class ClipGradByGloblNormPass(PassBase): + """ + 1. Remove norm-compute op and grad-scale op when the grad is not in current rank + or is independent of the calculation of norm. + 2. Each rank computes its own norm value, then gets global_norm by allreduce_sum only once. + """ + + def __init__(self): + super(ClipGradByGloblNormPass, self).__init__() + self.set_attr("rank_id", None) + self.set_attr("dist_context", None) + self.set_attr("params_grads", None) + + def _check_self(self): + if self.get_attr("dist_context") is None: + return False + dist_context = self.get_attr("dist_context") + if dist_context._serial_optimizer._grad_clip is None: + return False + if self.get_attr("params_grads") is None: + return False + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, context): + dist_context = self.get_attr("dist_context", None) + rank_id = self.get_attr("rank_id", None) + block = main_program.global_block() + dist_params_grads = self.get_attr("params_grads", None) + # dist_params_grads = _get_params_grads(block) + + self.clip_helper = ClipHelper(dist_params_grads, rank_id, block, + dist_context) + self._remove_no_need_ops_vars(block) + + def _remove_no_need_ops_vars(self, block): + + removed_op_out_type = [ + 'clip_by_norm', 'squared_l2_norm', 'square', 'reduce_sum' + ] + + removed_op_idx = set() + removed_tmp_var = set() + for idx, op in enumerate(block.ops): + if not is_gradient_clip_op(op): + continue + + if op.type in removed_op_out_type: + input_name = op.input("X")[0] + if input_name.find("@GRAD") != -1: + #'clip_by_norm', 'squared_l2_norm', 'square' + param_name = input_name[:input_name.find("@GRAD")] + is_local = self.clip_helper._is_local_param(param_name) + is_calculate = self.clip_helper._is_calcuate_norm( + param_name) + if not is_local or (not is_calculate + and op.type != 'clip_by_norm'): + removed_op_idx.add(idx) + removed_tmp_var.update(set(op.output_arg_names)) + else: + # 'reduce_sum' + if idx - 1 in removed_op_idx: + removed_op_idx.add(idx) + removed_tmp_var.update(set(op.output_arg_names)) + + elif op.type == 'elementwise_mul': + input_name = op.input("X")[0] + if input_name.find("@GRAD") != -1: + param_name = input_name[:input_name.find("@GRAD")] + is_local = self.clip_helper._is_local_param(param_name) + if not is_local: + removed_op_idx.add(idx) + if block.ops[idx - 1].type == 'cast': + removed_op_idx.add(idx - 1) + removed_tmp_var.update( + set(block.ops[idx - 1].output_arg_names)) + + elif op.type == 'sum': + reserved_vars = [] + for input_name in op.input_arg_names: + if input_name not in removed_tmp_var and \ + self.clip_helper._is_local_var(input_name): + reserved_vars.append(input_name) + if not reserved_vars: + removed_op_idx.add(idx) + removed_tmp_var.update(set(op.output_arg_names)) + if block.ops[idx + 1].type == 'cast': + removed_op_idx.add(idx + 1) + removed_tmp_var.update( + set(block.ops[idx + 1].output_arg_names)) + else: + op.desc.set_input("X", reserved_vars) + + for idx, op in reversed(list(enumerate(block.ops))): + if not is_optimize_op(op): + break + if not is_gradient_clip_op(op): + continue + if idx in removed_op_idx: + block._remove_op(idx, sync=False) + + for idx, op in reversed(list(enumerate(block.ops))): + if not is_optimize_op(op): + break + if not is_gradient_clip_op(op): + continue + if op.type == 'sqrt': + input_name = op.input("X")[0] + input_var = block.vars[input_name] + if paddle.distributed.get_world_size() > 1: + offset = 0 + if input_name in removed_tmp_var: + removed_tmp_var.remove(input_name) + fill_constant_op = block._insert_op( + idx, + type='fill_constant', + inputs={}, + outputs={'Out': [input_var]}, + attrs={ + 'shape': [1], + 'dtype': input_var.dtype, + 'value': 0, + 'force_cpu': False, + OP_ROLE_KEY: OpRole.Optimize + }) + fill_constant_op._set_attr('op_namescope', + "/gradient_clip_pass") + offset += 1 + self.clip_helper._init_dist_attr(fill_constant_op) + + allreduce_op = block._insert_op( + idx + offset, + type='c_allreduce_sum', + inputs={'X': [input_var]}, + outputs={'Out': [input_var]}, + attrs={ + 'ring_id': 0, + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize, + }) + allreduce_op._set_attr('op_namescope', + "/gradient_clip_pass") + self.clip_helper._init_dist_attr(allreduce_op) + + for varname in removed_tmp_var: + block._remove_var(varname, sync=False) + + block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_gradient_merge.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_gradient_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..c61d944400d665fe38b19ea09664c3fc4c300a80 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_gradient_merge.py @@ -0,0 +1,315 @@ +# Copyright (c) 2021 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. + +import numpy as np +from collections import OrderedDict +from typing import List, Tuple, Dict, Any + +import paddle +from paddle.framework import core +from paddle.fluid import layers +from paddle.fluid.framework import program_guard, device_guard +from .pass_base import PassBase, PassType, register_pass +from paddle.distributed.auto_parallel.utils import set_var_dist_attr, is_optimize_op, OpRole, OP_ROLE_KEY +from paddle.distributed.auto_parallel.utils import naive_set_dist_op_attr_for_program_by_mesh_and_mapping +from paddle.distributed.auto_parallel.process_group import get_world_process_group + +world_process_group = get_world_process_group() + + +def _remove_and_get_optimizer_op(main_program, dist_context): + # 1 create tmp block + # 2 mv optimizer op from global program to tmp block + # 3 del the op from dist_context + main_block = main_program.global_block() + temp_block = main_program._create_block() + removed_op_idx = [] + optimize_ops_desc = [] + for idx, op in enumerate(main_block.ops): + if is_optimize_op(op): + # append optimizer op to tmp block + new_op_desc = temp_block.desc.append_op() + new_op_desc.copy_from(op.desc) + optimize_ops_desc.append(new_op_desc) + removed_op_idx.append(idx) + + # del op from dist_context + if dist_context: + dist_context.del_dist_op_for_program(op) + + for idx in removed_op_idx[::-1]: + main_block._remove_op(idx, sync=False) + main_block._sync_with_cpp() + + return optimize_ops_desc + + +def _get_gm_cond_var(main_program, k_steps, dist_context): + main_block = main_program.global_block() + # Add const var + k_step_var = layers.create_global_var(name="gradient_merge_k", + shape=[1], + value=int(k_steps), + dtype='int32', + persistable=True, + force_cpu=True) + set_var_dist_attr(dist_context, k_step_var, [-1], world_process_group.ranks) + + zero_var = layers.create_global_var(name="gradient_merge_zero", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + set_var_dist_attr(dist_context, zero_var, [-1], world_process_group.ranks) + + # Add step var & cond var + step_var = layers.create_global_var(name="gradient_merge_step", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + set_var_dist_attr(dist_context, step_var, [-1], world_process_group.ranks) + + cond_var = main_block.create_var(name="gradient_merge_cond", + shape=[1], + dtype='bool') + set_var_dist_attr(dist_context, cond_var, [-1], world_process_group.ranks) + + with device_guard("cpu"): + # step_var += 1 + increment_op = main_block.append_op(type='increment', + inputs={'X': [step_var]}, + outputs={'Out': [step_var]}, + attrs={ + 'step': float(1.0), + OP_ROLE_KEY: OpRole.Backward + }) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + increment_op, world_process_group.ranks, [-1], dist_context) + # step_var %= k_step + elementwise_mod_op = main_block.append_op(type='elementwise_mod', + inputs={ + 'X': step_var, + 'Y': k_step_var + }, + outputs={'Out': step_var}, + attrs={ + 'axis': -1, + 'use_mkldnn': False, + OP_ROLE_KEY: + OpRole.Backward + }) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + elementwise_mod_op, world_process_group.ranks, [-1], dist_context) + # cond_var = (step_var == 0) + equal_op = main_block.append_op(type='equal', + inputs={ + 'X': step_var, + 'Y': zero_var + }, + outputs={'Out': cond_var}, + attrs={OP_ROLE_KEY: OpRole.Backward}) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + equal_op, world_process_group.ranks, [-1], dist_context) + + return cond_var + + +def _append_gradient_merge_backward_op( + main_program, startup_program, params_grads: List[Tuple[Any, Any]], + dist_context) -> Tuple[List[Tuple[Any, Any]], Dict[str, Any]]: + main_block = main_program.global_block() + startup_block = startup_program.global_block() + + # step1: remove grad.op's op_role_var + for param, grad in params_grads: + assert ( + param.type != core.VarDesc.VarType.SELECTED_ROWS + ), "SELECTED_ROWS is not supported in GradientMergeOptimizer for now" + + # {grad.name: gradient_merge_var.name} to rename opt inputs + grad_to_gradient_merge = {} + # {param: gradient_merge_var} to insert scale op and fill_constant op + new_params_to_grads = [] + # step2: create gradient_merge var and init with 0 + for param, grad in params_grads: + param_name = param.name + param_var = main_block.var(param_name) + assert (param_var is not None) + ref_dist_attr = dist_context.get_tensor_dist_attr_for_program(param_var) + assert ref_dist_attr is not None + gradient_merge_var = main_block.create_var(name=param_name + + "@GRAD@GradientMerge", + shape=param_var.shape, + dtype=param_var.dtype, + persistable=True) + ref_process_mesh = ref_dist_attr.process_mesh + ref_dims_mapping = ref_dist_attr.dims_mapping + + set_var_dist_attr(dist_context, gradient_merge_var, ref_dims_mapping, + ref_process_mesh) + + startup_gradient_merge_var = startup_block.create_var( + name=param_name + "@GRAD@GradientMerge", + shape=param_var.shape, + dtype=param_var.dtype, + persistable=True) + startup_block.append_op(type="fill_constant", + outputs={"Out": startup_gradient_merge_var}, + attrs={ + "shape": param_var.shape, + "dtype": param_var.dtype, + "value": float(0), + }) + + # grad_merge += grad + new_grad_op = main_block.append_op(type="elementwise_add", + inputs={ + 'X': grad, + 'Y': gradient_merge_var + }, + outputs={'Out': gradient_merge_var}, + attrs={ + 'axis': -1, + 'use_mkldnn': False, + OP_ROLE_KEY: OpRole.Backward + }) + new_params_to_grads.append([param, gradient_merge_var]) + grad_to_gradient_merge[grad.name] = gradient_merge_var.name + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_grad_op, ref_process_mesh, ref_dims_mapping, dist_context) + return new_params_to_grads, grad_to_gradient_merge + + +def _create_cond_block_and_update_optimizer( + main_program, cond_var, new_params_to_grads: List[Tuple[Any, Any]], + grad_to_gradient_merge: Dict[str, str], optimize_ops_desc: List[Any], + k_steps, avg): + + def true_apply_gradient(): + cur_block_idx = main_program.current_block_idx + cur_block = main_program.current_block() + + # cur_block's forward_block & backward_block is itself + cur_block._set_forward_block_idx(cur_block_idx) + op_maker = core.op_proto_and_checker_maker + if avg: + for param, new_grad in new_params_to_grads: + # grad /= k_steps + cur_block.append_op(type='scale', + inputs={'X': new_grad}, + outputs={'Out': new_grad}, + attrs={ + 'scale': 1.0 / k_steps, + 'bias': 0.0, + 'bias_after_scale': False + }) + new_grad.op._set_attr(OP_ROLE_KEY, OpRole.Optimize) + + # append optimizer ops + for op_desc in optimize_ops_desc: + new_op_desc = cur_block.desc.append_op() + new_op_desc.copy_from(op_desc) + + #update input/output + for input_name in new_op_desc.input_arg_names(): + if input_name in grad_to_gradient_merge: + new_op_desc._rename_input( + input_name, grad_to_gradient_merge[input_name]) + + for output_name in new_op_desc.output_arg_names(): + if output_name in grad_to_gradient_merge: + new_op_desc._rename_output( + output_name, grad_to_gradient_merge[output_name]) + + # remove op_role_var + if new_op_desc.has_attr(op_maker.kOpRoleVarAttrName()): + new_op_desc.remove_attr(op_maker.kOpRoleVarAttrName()) + + # op's update Grad + if core.grad_var_suffix() in new_op_desc.input_arg_names(): + grad_value = new_op_desc.input("Grad")[0] + # TODO FIXME(xym) support fp16 + grad_merge_value = grad_value + '@GradientMerge' + new_op_desc.set_input("Grad", [grad_merge_value]) + + main_program.global_block()._sync_with_cpp() + cur_block._sync_with_cpp() + + # clear gradient_merge_vars + for param, new_grad in new_params_to_grads: + layers.fill_constant(shape=new_grad.shape, + dtype=new_grad.dtype, + value=0.0, + out=new_grad) + new_grad.op._set_attr(OP_ROLE_KEY, op_maker.OpRole.Optimize) + + layers.cond(cond_var, true_fn=true_apply_gradient, false_fn=None) + cond_op = main_program.global_block().ops[-1] + cond_op._set_attr(OP_ROLE_KEY, OpRole.Optimize) + + +def parse_program(main_program, startup_program, params_grads, k_steps, avg, + dist_context): + # 1 remove optimizer_op from main_program + optimize_ops_desc = _remove_and_get_optimizer_op(main_program, dist_context) + + # back to block 0 + main_program._rollback() + + # 2 append gradient merge backward op to main_program + new_params_to_grads, grad_to_gradient_merge = _append_gradient_merge_backward_op( + main_program, startup_program, params_grads, dist_context) + + # 3 create gradient_merge_cond + cond_var = _get_gm_cond_var(main_program, k_steps, dist_context) + + # 4 create ConditionalBlock and append gradient merge optimizer ops + _create_cond_block_and_update_optimizer(main_program, cond_var, + new_params_to_grads, + grad_to_gradient_merge, + optimize_ops_desc, k_steps, avg) + + +@register_pass("auto_parallel_gradient_merge_pass") +class GradientMergePass(PassBase): + + def __init__(self): + super(GradientMergePass, self).__init__() + self.set_attr("k_steps", -1) + self.set_attr("avg", True) + + def _check_self(self): + if self.get_attr("k_steps") < 1: + return False + return True + + def _check_conflict(self, other_pass): + return True + + def _type(self): + return PassType.COMM_OPT + + def _apply_single_impl(self, main_program, startup_program, context): + k_steps = self.get_attr("k_steps", -1) + avg = self.get_attr("avg", False) + dist_context = self.get_attr("dist_context") + params_grads = self.get_attr("params_grads") + with paddle.static.program_guard(main_program, startup_program): + parse_program(main_program, startup_program, params_grads, k_steps, + avg, dist_context) + + main_program._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_quantization.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ac93d83939dedd99f1a6720771367e175d0947 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_quantization.py @@ -0,0 +1,258 @@ +# Copyright (c) 2022 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. + +import paddle + +from paddle.fluid import core, framework +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.fluid.contrib.slim.quantization import utils +from paddle.fluid.contrib.slim.quantization import QuantizationTransformPassV2 +from paddle.fluid.contrib.slim.quantization import AddQuantDequantPassV2 +from paddle.fluid.contrib.slim.quantization import OutScaleForTrainingPass +from paddle.distributed.auto_parallel.dist_attribute import OperatorDistributedAttribute, TensorDistributedAttribute + +from .pass_base import PassBase, register_pass + +TRANSFORM_PASS_OP_TYPES = utils._weight_supported_quantizable_op_type +QUANT_DEQUANT_PASS_OP_TYPES = utils._act_supported_quantizable_op_type + + +def _node_id(node): + return (node.node.graph_id(), node.node.id()) + + +@register_pass("auto_parallel_quantization") +class QuantizationPass(PassBase): + + def __init__(self): + super(QuantizationPass, self).__init__() + self.set_attr("dist_context", None) + self.set_attr("params_grads", None) + + def _check_self(self): + if self.get_attr("dist_context") is None: + return False + if self.get_attr("params_grads") is None: + return False + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, context): + + dist_context = self.get_attr("dist_context") + params_grads = self.get_attr("params_grads") + + # TODO: scope and place will be removed, + # cause params should be initialized by engine module. + scope = paddle.static.global_scope() + place = paddle.fluid.CUDAPlace(ParallelEnv().dev_id) + + # 1. Program convert to Graph, and this pass is only for train mode + main_graph = framework.IrGraph(core.Graph(main_program.desc), + for_test=False) + + # 2. Prepare inputs + transform_pass_ops = [] + quant_dequant_ops = [] + quantize_op_types = [ + 'conv2d', 'depthwise_conv2d', 'mul', 'matmul', 'matmul_v2' + ] + for op_type in quantize_op_types: + if op_type in TRANSFORM_PASS_OP_TYPES: + transform_pass_ops.append(op_type) + elif op_type in QUANT_DEQUANT_PASS_OP_TYPES: + quant_dequant_ops.append(op_type) + + weight_quantize_type = "channel_wise_abs_max" if self.get_attr( + 'channel_wise_abs_max') else "abs_max" + + # 3. Add quant op for ops which have parameters + transform_pass = QuantizationTransformPassV2( + scope=scope, + place=place, + weight_bits=self.get_attr('weight_bits'), + activation_bits=self.get_attr('activation_bits'), + skip_pattern=self.get_attr('not_quant_pattern'), + activation_quantize_type="moving_average_abs_max", + quantizable_op_type=transform_pass_ops, + weight_quantize_type=weight_quantize_type, + weight_quantize_func=None, + act_quantize_func=None, + weight_preprocess_func=None, + act_preprocess_func=None, + optimizer_func=None, + executor=None) + transform_pass.apply(main_graph) + + # 4. Add quant op for ops which don't have parameter + quant_dequant_pass = AddQuantDequantPassV2( + scope=scope, + place=place, + quant_bits=self.get_attr('activation_bits'), + skip_pattern=self.get_attr('not_quant_pattern'), + quantizable_op_type=quant_dequant_ops) + quant_dequant_pass.apply(main_graph) + + # 5. Gather quantitative information for the output + out_scale_training_pass = OutScaleForTrainingPass(scope=scope, + place=place) + out_scale_training_pass.apply(main_graph) + + # 6. Convert Graph back to Program + quant_program = main_graph.to_program() + + # 7. get new prams_grads from quant_program + new_params_grads = [] + for param, grad in params_grads: + if param.name not in quant_program.global_block().vars: + continue + + new_param = quant_program.global_block().vars[param.name] + new_grad = quant_program.global_block().vars[grad.name] + new_params_grads.append((new_param, new_grad)) + + # 8. complete distributed attribution + # NOTE: hack implement, upgrading soon + for ib, block in enumerate(quant_program.blocks): + # recover origin ops' dist_attr and set quant ops' dist_attr + qat_offset = 0 + for ip, quant_op in enumerate(block.ops): + quant_op_dist_attr = OperatorDistributedAttribute() + + if "quantize" in quant_op.type or \ + quant_op.type == "moving_average_abs_max_scale": + + input_name = quant_op.desc.input('X')[0] + if "quantize" in input_name: + input_name = input_name[:input_name.index(".quantized")] + + if quant_op.type == "moving_average_abs_max_scale": + consume_op = main_program.blocks[ib].vars[input_name].op + else: + consume_op = main_program.blocks[ib].ops[ip - + qat_offset] + consume_op_dist_attr = dist_context.get_dist_op_for_program( + consume_op).dist_attr + ref_process_mesh = consume_op_dist_attr.process_mesh + + if input_name in consume_op_dist_attr.outputs_dist_attrs: + consume_input_dist_attr = consume_op_dist_attr.outputs_dist_attrs[ + input_name] + else: + consume_input_dist_attr = consume_op_dist_attr.inputs_dist_attrs[ + input_name] + + quant_op_dist_attr.impl_idx = 0 + quant_op_dist_attr.impl_type = "default" + quant_op_dist_attr.process_mesh = ref_process_mesh + quant_op_dist_attr.set_input_dist_attr( + quant_op.desc.input('X')[0], consume_input_dist_attr) + + for slot_name in quant_op.desc.input_names(): + if slot_name == "X": + continue + for in_name in quant_op.desc.input(slot_name): + input_var = block.vars[in_name] + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = ref_process_mesh + tensor_dist_attr.dims_mapping = [-1] + dist_context.set_tensor_dist_attr_for_program( + input_var, tensor_dist_attr) + quant_op_dist_attr.set_input_dist_attr( + in_name, tensor_dist_attr) + + for slot_name in quant_op.desc.output_names(): + output_name = quant_op.desc.output(slot_name)[0] + output_var = block.vars[output_name] + if slot_name == "Y": + dist_context.set_tensor_dist_attr_for_program( + output_var, consume_input_dist_attr) + quant_op_dist_attr.set_output_dist_attr( + output_name, consume_input_dist_attr) + else: + tensor_dist_attr = TensorDistributedAttribute() + tensor_dist_attr.process_mesh = ref_process_mesh + tensor_dist_attr.dims_mapping = [-1] + dist_context.set_tensor_dist_attr_for_program( + output_var, tensor_dist_attr) + quant_op_dist_attr.set_output_dist_attr( + output_name, tensor_dist_attr) + + quant_op._set_attr("op_device", "") + qat_offset += 1 + + else: + + origin_op = main_program.blocks[ib].ops[ip - qat_offset] + quant_op.desc.set_original_id(origin_op.desc.original_id()) + dist_origin_op = dist_context.get_dist_op_for_program( + origin_op) + assert dist_origin_op is not None, "origin op must have dist attr." + + origin_op_dist_attr = dist_origin_op.dist_attr + quant_op_dist_attr.impl_idx = origin_op_dist_attr.impl_idx + quant_op_dist_attr.impl_type = origin_op_dist_attr.impl_type + quant_op_dist_attr.process_mesh = origin_op_dist_attr.process_mesh + for idx, input_name in enumerate(quant_op.input_arg_names): + origin_input_name = origin_op.input_arg_names[idx] + origin_input_dist_attr = origin_op_dist_attr.inputs_dist_attrs[ + origin_input_name] + quant_op_dist_attr.set_input_dist_attr( + input_name, origin_input_dist_attr) + + if input_name not in main_program.blocks[ib].vars: + origin_input_var = main_program.blocks[ib].vars[ + origin_input_name] + origin_in_tensor_dist_attr = dist_context.get_dist_tensor_for_program( + origin_input_var).dist_attr + quant_input_var = block.vars[input_name] + dist_context.set_tensor_dist_attr_for_program( + quant_input_var, origin_in_tensor_dist_attr) + + for idx, output_name in enumerate( + quant_op.output_arg_names): + origin_output_name = origin_op.output_arg_names[idx] + origin_output_dist_attr = origin_op_dist_attr.outputs_dist_attrs[ + origin_output_name] + quant_op_dist_attr.set_output_dist_attr( + output_name, origin_output_dist_attr) + + if output_name not in main_program.blocks[ib].vars: + origin_output_var = main_program.blocks[ib].vars[ + origin_output_name] + origin_out_tensor_dist_attr = dist_context.get_dist_tensor_for_program( + origin_output_var).dist_attr + quant_output_var = block.vars[output_name] + dist_context.set_tensor_dist_attr_for_program( + quant_output_var, origin_out_tensor_dist_attr) + + dist_context.set_op_dist_attr_for_program( + quant_op, quant_op_dist_attr) + + # recover vars' dist_attr + for name, dst_var in block.vars.items(): + if name in main_program.blocks[ib].vars: + src_var = main_program.blocks[ib].vars[name] + dist_tensor = dist_context.get_dist_tensor_for_program( + src_var) + if not dist_tensor: + continue + dist_context.set_tensor_dist_attr_for_program( + dst_var, dist_tensor.dist_attr) + + context.set_attr("main_program", quant_program) + context.set_attr("startup_program", startup_program) + context.set_attr("params_grads", new_params_grads) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_recompute.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_recompute.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c83a98c19fcb3283011603d7fc65101e79022a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_recompute.py @@ -0,0 +1,415 @@ +# Copyright (c) 2021 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. + +import copy +import logging + +from .pass_base import PassBase, register_pass +from paddle.fluid import core, unique_name +from paddle.fluid import framework as framework +from paddle.fluid.framework import Variable, Operator +from paddle.fluid.backward import _append_grad_suffix_, _get_no_grad_set_name +from paddle.fluid.backward import ProgramStats, _rename_arg_, _find_op_path_ +from paddle.distributed.auto_parallel.process_mesh import ProcessMesh +from paddle.distributed.auto_parallel.dist_attribute import OperatorDistributedAttribute +from paddle.distributed.auto_parallel.utils import get_loss_op, set_var_dist_attr, set_dist_op_desc_original_id +from paddle.distributed.auto_parallel.utils import naive_set_dist_op_attr_for_program_by_mesh_and_mapping + + +class RecomputeState(ProgramStats): + + def __init__(self, block, ops): + super(RecomputeState, self).__init__(block=block, ops=ops) + self._block = block + self._ops = ops + self.var_op_deps = {} + + def build_stats(self): + for i, op in enumerate(self._ops): + for name in op.desc.input_arg_names(): + if name in self.var_op_deps: + self.var_op_deps[name]["var_as_input_ops"].extend([i]) + else: + self.var_op_deps[name] = {} + self.var_op_deps[name]["var_as_input_ops"] = [i] + self.var_op_deps[name]["var_as_output_ops"] = [] + + for name in op.desc.output_arg_names(): + if name in self.var_op_deps: + self.var_op_deps[name]["var_as_output_ops"].extend([i]) + else: + self.var_op_deps[name] = {} + self.var_op_deps[name]["var_as_input_ops"] = [] + self.var_op_deps[name]["var_as_output_ops"] = [i] + + def get_recompute_segments(self, checkpoints): + """ get recompute segments from checkpoints """ + segments = [] + start_idx = -1 + pre_segment_end_idx = -1 + while start_idx + 1 < len(checkpoints): + if start_idx == -1: + ckpt_name = checkpoints[start_idx + 1] + if ckpt_name not in self.var_op_deps: + start_idx += 1 + continue + op_idx_list = self.var_op_deps[ckpt_name]["var_as_output_ops"] + if op_idx_list: + segments.append([0, max(op_idx_list) + 1]) + else: + flag, min_idx, max_idx = self.is_subgraph( + [checkpoints[start_idx]], [checkpoints[start_idx + 1]]) + if flag: + min_idx = self._update_segment_start( + min_idx, pre_segment_end_idx) + segments.append([min_idx, max_idx + 1]) + else: + logging.info( + "Could not recompute op range [{}] - [{}] ".format( + min_idx, max_idx + 1)) + start_idx += 1 + + for i, (idx1, idx2) in enumerate(segments): + logging.info("recompute segment[{}]".format(i)) + logging.info("segment start op: [{}]: [{}] [{}]".format( + self._ops[idx1].desc.type(), + self._ops[idx1].desc.input_arg_names(), + self._ops[idx1].desc.output_arg_names())) + logging.info("segment end op: [{}]: [{}] [{}]".format( + self._ops[idx2 - 1].desc.type(), + self._ops[idx2 - 1].desc.input_arg_names(), + self._ops[idx2 - 1].desc.output_arg_names())) + + return segments + + def modify_forward_desc_for_recompute(self, dist_context): + """ + If program's foward part has 'dropout' op, this function will insert + a seed op before it to guarantee that two dropout op have the same outputs. + """ + op_types = [op.desc.type() for op in self._ops] + if "dropout" not in op_types: + return + + op_idx = 0 + while op_idx < len(self._ops): + cur_op = self._ops[op_idx] + if "grad" in cur_op.type: + break + if cur_op.type != "dropout": + op_idx += 1 + continue + if cur_op.input("Seed") is not None and len(cur_op.input("Seed")): + op_idx += 1 + continue + + cur_op_dist_attr = dist_context.get_op_dist_attr_for_program(cur_op) + # insert seed op to guarantee that two dropout op have the same outputs + op_unique_name = unique_name.generate("seed") + var_unique_name = unique_name.generate_with_ignorable_key(".".join( + [op_unique_name, 'tmp'])) + seed_var = self._block.create_var( + name=var_unique_name, + dtype='int32', + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + + # set new seed_var's dist_attr + ref_dims_mapping = [-1] + ref_process_mesh = cur_op_dist_attr.process_mesh + seed_var_dist_attr = set_var_dist_attr(dist_context, seed_var, + ref_dims_mapping, + ref_process_mesh) + + seed = 0 if cur_op.attr("fix_seed") is False else int( + cur_op.attr("seed")) + seed_op = self._block._insert_op_without_sync( + index=cur_op.idx, + type="seed", + inputs={}, + outputs={"Out": seed_var}, + attrs={ + "seed": seed, + "force_cpu": True + }) + # set new seed op's dist_attr + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + seed_op, ref_process_mesh, ref_dims_mapping, dist_context) + + # modify dropout op's desc + self._ops.insert(op_idx, seed_op) + cur_op.desc.set_input("Seed", [var_unique_name]) + cur_op._remove_attr("fix_seed") + cur_op._remove_attr("seed") + cur_op_dist_attr.set_input_dist_attr(seed_var.name, + seed_var_dist_attr) + op_idx += 2 + + self._block._sync_with_cpp() + + +def _find_op_index(block, cur_op): + for idx in range(block.desc.op_size()): + if cur_op.desc == block.desc.op(idx): + return idx + return -1 + + +def _get_stop_gradients(program, no_grad_set): + """ get no grad var """ + if no_grad_set is None: + no_grad_set = set() + else: + no_grad_set = _get_no_grad_set_name(no_grad_set) + + no_grad_set_name = set() + for var in program.list_vars(): + assert isinstance(var, Variable) + if "@GRAD" in var.name: + break + if var.stop_gradient: + no_grad_set_name.add(_append_grad_suffix_(var.name)) + no_grad_set_name.update(list(map(_append_grad_suffix_, no_grad_set))) + return no_grad_set_name + + +def _add_needed_descs_to_block(descs, block, main_block, in_memory_vars, + dist_context): + """ + Get the recomputed ops which will insert the backward part + """ + if len(descs) == 0: + return [] + result_descs = [] + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + for desc in descs: + if isinstance(desc, framework.Operator): + desc = desc.desc + if isinstance(desc, tuple): + desc = desc[0] + is_needed = False + for name in desc.output_arg_names(): + if main_block.has_var(name) and main_block.var(name).persistable: + continue + if name not in in_memory_vars: + is_needed = True + if is_needed: + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(desc) + set_dist_op_desc_original_id(new_op_desc, desc, dist_context) + new_op_desc._set_attr(op_role_attr_name, backward) + result_descs.append(new_op_desc) + return result_descs + + +@register_pass("auto_parallel_recompute") +class RecomputePass(PassBase): + + def __init__(self): + super(RecomputePass, self).__init__() + self.set_attr("checkpoints", None) + self.set_attr("loss", None) + self.set_attr("dist_context", None) + self.set_attr("no_grad_set", None) + + def _check_self(self): + if self.get_attr("dist_context") is None: + return False + if self.get_attr("loss") is None: + return False + if self.get_attr("checkpoints") is None: + return False + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, context): + checkpoints = self.get_attr("checkpoints") + loss = self.get_attr("loss") + no_grad_set = self.get_attr("no_grad_set") + self._dist_context = self.get_attr("dist_context") + + main_block = main_program.global_block() + no_grad_set_name = _get_stop_gradients(main_program, no_grad_set) + # get op_path which is related to loss + op_path = _find_op_path_(main_block, [loss], [], no_grad_set_name) + + # step 1: build recompute state + rc_state = RecomputeState(main_block, op_path) + rc_state.modify_forward_desc_for_recompute(self._dist_context) + rc_state.build_stats() + checkpoints = rc_state.sort_checkpoints(checkpoints) + segments = rc_state.get_recompute_segments(checkpoints) + if segments == []: + return + + # step 2: get vars_should_be_hold + vars_should_be_hold = [] + for segment in segments: + vars_should_be_hold.extend( + rc_state.get_out_of_subgraph_vars(segment[0], segment[1])) + cross_vars = set(vars_should_be_hold) - set(checkpoints) + logging.info( + "found [{}] vars which cross recompute segment: [{}]," + "better checkpoints might be set to reduce those vars".format( + len(cross_vars), cross_vars)) + vars_should_be_hold.extend(rc_state.get_reserved_vars()) + vars_should_be_hold.extend(rc_state.get_input_nodes()) + vars_should_be_hold = list(set(vars_should_be_hold)) + vars_in_memory = vars_should_be_hold + checkpoints + + # step 3: get recomputed fwd ops desc + var_name_dict = {} + ckpt_ops_dict = {} + buffer_block = main_block.program._create_block() + for i, segment in enumerate(segments[::-1]): + fwd_ops = op_path[segment[0]:segment[1]] + var_suffix = ".subprog_%d" % i + for op in fwd_ops: + input_and_output_names = [] + input_and_output_names.extend(op.desc.input_arg_names()) + input_and_output_names.extend(op.desc.output_arg_names()) + cur_op_dist_attr = self._dist_context.get_op_dist_attr_for_program( + op) + assert cur_op_dist_attr is not None + for name in input_and_output_names: + if main_block.var(name).persistable or name in checkpoints: + continue + if name in vars_should_be_hold: + continue + if name not in var_name_dict: + ref_process_mesh = cur_op_dist_attr.process_mesh + if name in op.desc.input_arg_names(): + ref_dims_mapping = cur_op_dist_attr.get_input_dims_mapping( + name) + else: + ref_dims_mapping = cur_op_dist_attr.get_output_dims_mapping( + name) + # record recomputed var's old_name and new_name (old_name.subprog_XXX) + # create new var with new name + var_name_dict[name] = name + var_suffix + ref_var = main_block.var(name) + rc_var = main_block.create_var( + name=var_name_dict[name], + shape=ref_var.shape, + dtype=ref_var.dtype, + type=ref_var.type, + persistable=ref_var.persistable, + stop_gradient=ref_var.stop_gradient) + # set new recomputed var's dist attr + set_var_dist_attr(self._dist_context, rc_var, + ref_dims_mapping, ref_process_mesh) + # get recomputed segment's descs + segment_descs = _add_needed_descs_to_block(fwd_ops, buffer_block, + main_block, + vars_in_memory, + self._dist_context) + # rename recomputed ops' input and output var name + for key in var_name_dict: + _rename_arg_(segment_descs, key, var_name_dict[key]) + + # NOTE: one forward op could be correspond to multiple xxx_grad op. + # When traversing all grad_ops in reverse, need to set a flag to indicate + # whether the ckpt and its segment_descs can be used. + ckpt_op = op_path[segment[1] - 1] + ckpt_ops_dict[ckpt_op.desc.original_id()] = [True, segment_descs] + + # step 4: insert recomputed fwd ops + ops = main_block.ops + loss_op = get_loss_op(main_block) + loss_op_idx = _find_op_index(main_block, loss_op) + dist_op_context = self._dist_context.dist_op_context + assert loss_op_idx != -1 + # Traversing all grad_ops in reverse, and if the fwd op corresponding to reverse op is checkpoints, + # segments ops should be inserted. + for i in range(len(ops) - 1, loss_op_idx, -1): + grad_op = ops[i] + # remove some attrs of dropout_grad op's desc + if grad_op.type == "dropout_grad": + grad_op._remove_attr("fix_seed") + grad_op._remove_attr("seed") + + # rename grad op's var_name which is not in 'vars_in_memory' + for key in var_name_dict: + if key not in grad_op.input_arg_names + grad_op.output_arg_names: + continue + self.reset_op_dist_attr(grad_op, var_name_dict) + _rename_arg_([grad_op.desc], key, var_name_dict[key]) + + # insert recomputed ops + original_id = grad_op.desc.original_id() + if original_id in dist_op_context.grad_op_id_to_op_id: + fwd_op_id = dist_op_context.grad_op_id_to_op_id[original_id] + if fwd_op_id in ckpt_ops_dict and ckpt_ops_dict[fwd_op_id][0]: + idx = grad_op.idx + while idx - 1 >= 0 and ops[idx - 1].type == "sum": + idx -= 1 + segment_descs = ckpt_ops_dict[fwd_op_id][1] + for _, op_desc in reversed(list(enumerate(segment_descs))): + rc_op = main_block._insert_op_without_sync(idx, + type='nop') + rc_desc = rc_op.desc + rc_desc.copy_from(op_desc) + rc_desc.set_original_id(rc_desc.id()) + # set recomputed ops' dist attr + fwd_op_dist_attr = self._dist_context.get_op_dist_attr_for_program_with_id( + op_desc.original_id()) + assert fwd_op_dist_attr is not None + self.set_op_dist_attr(rc_op, fwd_op_dist_attr, + var_name_dict) + + ckpt_ops_dict[fwd_op_id][0] = False + + main_program._sync_with_cpp() + + def reset_op_dist_attr(self, op, var_name_dict): + op_dist_attr = self._dist_context.get_op_dist_attr_for_program(op) + assert op_dist_attr is not None + for input in op.desc.input_arg_names(): + if input in var_name_dict.keys(): + in_dist_attr = op_dist_attr.get_input_dist_attr(input) + op_dist_attr.set_input_dist_attr(var_name_dict[input], + in_dist_attr) + for output in op.desc.output_arg_names(): + if output in var_name_dict.keys(): + out_dist_attr = op_dist_attr.get_output_dist_attr(output) + op_dist_attr.set_output_dist_attr(var_name_dict[output], + out_dist_attr) + + def set_op_dist_attr(self, op, old_dist_attr, var_name_dict): + new_dist_attr = OperatorDistributedAttribute() + new_dist_attr.is_recompute = True + new_dist_attr.impl_idx = old_dist_attr.impl_idx + new_dist_attr.impl_type = old_dist_attr.impl_type + new_dist_attr.process_mesh = old_dist_attr.process_mesh + for input in old_dist_attr.inputs_dist_attrs.keys(): + if input in var_name_dict.keys(): + in_dist_attr = old_dist_attr.inputs_dist_attrs[input] + new_dist_attr.set_input_dist_attr(var_name_dict[input], + in_dist_attr) + else: + in_dist_attr = old_dist_attr.inputs_dist_attrs[input] + new_dist_attr.set_input_dist_attr(input, in_dist_attr) + for output in old_dist_attr.outputs_dist_attrs.keys(): + if output in var_name_dict.keys(): + out_dist_attr = old_dist_attr.outputs_dist_attrs[output] + new_dist_attr.set_output_dist_attr(var_name_dict[output], + out_dist_attr) + else: + out_dist_attr = old_dist_attr.outputs_dist_attrs[output] + new_dist_attr.set_output_dist_attr(output, out_dist_attr) + self._dist_context.set_op_dist_attr_for_program(op, new_dist_attr) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_sharding.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..636b3218c8a0b5635e9a7abc85afcd95fc976955 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/auto_parallel_sharding.py @@ -0,0 +1,805 @@ +# Copyright (c) 2021 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. + +from functools import reduce +from collections import OrderedDict +import numpy as np + +import paddle +from paddle.framework import core +from paddle.fluid import unique_name +from .pass_base import PassBase, register_pass +from paddle.distributed.fleet.meta_optimizers.common import is_backward_op, is_optimizer_op +from paddle.distributed.auto_parallel.process_group import new_process_group +from paddle.distributed.auto_parallel.operators.common import is_parameter_related, is_data_parallel_reduce_op +from paddle.distributed.auto_parallel.utils import _get_comm_group, naive_set_dist_op_attr_for_program_by_mesh_and_mapping, set_var_dist_attr + +OpRole = core.op_proto_and_checker_maker.OpRole +OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() +_skip_ops = [ + 'create_py_reader', 'create_double_buffer_reader', 'read', 'slice', 'split', + 'assign', "send_v2" +] +# update here to support new optimizers +_supported_optimizer_type = [ + "adam", "adamax", "adamw", "decayed_adagrad", "momentum", "dgc_momentum", + "lars_momentum", "merged_momentum", "lamb", "sgd" +] + + +def _is_reshard_op(op): + return op.desc.has_attr("op_namescope") and \ + "/auto_parallel/reshard" in op.desc.attr('op_namescope') + + +# NOTE we add the "auto_parallel" prefix to the pass in order to +# indicate that this pass should obey some constrains by auto_parallel +# for example all ops and vars should has dist attr before and after pass +# should use dist op instead of custom comm op +@register_pass("auto_parallel_sharding") +class ShardingPass(PassBase): + + def __init__(self): + super(ShardingPass, self).__init__() + self.set_attr("dist_context", None) + self.set_attr("stage", None) + self.set_attr("sharding_degree", None) # for parallelizer + self.set_attr("degree", None) # for parallelizer_v2 + self.set_attr("params_grads", []) + self.set_attr("global_rank", -1) + self.dp_groups = set() + self.sharding_infos = [] + self.varname_to_sharding_info = {} + self.partial_sharding = False + self.outer_dp_group = None + self.shared_params_grads = [] + + def _check_self(self): + if self.get_attr("dist_context") is None: + return False + + if self.get_attr("stage") not in [1, 2, 3]: + return False + if self.get_attr("sharding_degree") is not None: + if (not isinstance(self.get_attr("sharding_degree"), int)) \ + or self.get_attr("sharding_degree") <= 1: + return False + elif self.get_attr("degree") is not None: + if (not isinstance(self.get_attr("degree"), int)) \ + or self.get_attr("degree") <= 1: + return False + else: + return False + if len(self.get_attr("params_grads")) <= 0: + return False + if (not isinstance(self.get_attr("global_rank"), + int)) or self.get_attr("global_rank") < 0: + return False + + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, context): + self._dist_context = self.get_attr("dist_context") + self.sharding_world_size = int( + self.get_attr("sharding_degree") or self.get_attr("degree")) + self.stage = int(self.get_attr("stage")) + self.global_rank = int(self.get_attr("global_rank")) + params_grads = self.get_attr("params_grads") + main_block, startup_block = main_program.global_block( + ), startup_program.global_block() + + self._build_sharding_groups(main_block, params_grads) + self._shard_optimizer(main_block, startup_block, params_grads, context) + self._shard_gradient_synchronization(main_block) + self._shard_parameter(main_block, startup_block) + + context.set_attr("params_grads", self.shared_params_grads) + + def _build_sharding_groups(self, main_block, params_grads): + self._collective_data_parallel_groups(main_block) + self._build_sharding_infos(params_grads) + + def _collective_data_parallel_groups(self, main_block): + for op in main_block.ops: + if not _is_forward_op(op) or op.type in _skip_ops: + continue + # NOTE: there aren't dist_attr in the ops which reshard insert, + # and should be skip in sharding. + if _is_reshard_op(op): + continue + group = _inference_data_parallel_group_for_operator( + self.global_rank, op, self._dist_context) + if group is not None: + self.dp_groups.add(group) + + # TODO(JZ-LIANG) allow more than one dp groups in network, support more general distribution + # genetated by auto search + if len(self.dp_groups) != 1: + raise NotImplementedError( + "So far Only and Exactly one data parallel group in network are supported, but got [{}] different data parallel groups" + .format(len(self.dp_groups))) + + def _build_sharding_infos(self, params_grads): + + for dp_group in self.dp_groups: + + assert dp_group.nranks >= self.sharding_world_size, "sharding world size [{}] should not larger than dp world size [{}]".format( + self.sharding_world_size, dp_group.nranks) + assert dp_group.nranks % self.sharding_world_size == 0, "sharding world size [{}] should be divisible by dp world size [{}]".format( + self.sharding_world_size, dp_group.nranks) + assert self.global_rank in dp_group.ranks, "current ranks [{}] does NOT belong to the data parallel group [{}]".format( + self.global_rank, dp_group.ranks) + assert len( + params_grads + ) >= self.sharding_world_size, "number of parameters [{}] is not enough to be shard among [{}] ranks".format( + len(params_grads), self.sharding_world_size) + + # sharding hybrid data parallel: partial sharding param within + if dp_group.nranks > self.sharding_world_size: + self.partial_sharding = True + assert len( + self.dp_groups + ) == 1, "hybrid sharding and data parallelism are supported only when there is excatly one data parallel group in the network" + outer_dp_group, sharding_group = _get_dp_and_sharding_groups( + dp_group.ranks, self.sharding_world_size, self.global_rank) + sharding_group = new_process_group(sharding_group) + self.outer_dp_group = new_process_group(outer_dp_group) + else: + sharding_group = dp_group + + self._dist_context._sharding_group = sharding_group + # TODO(JZ-LIANG) when support multiple dp groups in future, should group param and bind them to corresponding dp group + sharding_info = ShardingInfo(sharding_group, self.global_rank, + params_grads) + self.sharding_infos.append(sharding_info) + for param in sharding_info.params: + self.varname_to_sharding_info[param.name] = sharding_info + + def _shard_optimizer(self, main_block, startup_block, params_grads, + pass_context): + """ + sharding all optimizer related ops and vars, include: + gradient clip ops & vars + weight decay ops & vars + optimizer ops and states + """ + self._shard_amp_related_op_and_vars(main_block, pass_context) + self._shard_weight_decay(main_block) + # self._shard_gradient_clip(main_block) + self._shard_optimizer_ops_and_states(main_block, startup_block) + self._insert_optimizer_broadcasts(main_block, startup_block) + + def _shard_amp_related_op_and_vars(self, main_block, pass_context): + + if self.stage < 2: + return + + for idx, op in reversed(list(enumerate(main_block.ops))): + # shard amp related param_grad cast + if _is_param_grad_fp32_cast_op(main_block, op): + output_name = op.output_arg_names[0] + param_name = output_name[:output_name.find("@")] + if not self._is_parameter_in_local_shard(param_name): + main_block._remove_op(idx, sync=False) + main_block._remove_var(output_name, sync=False) + + # shard check nan inf + elif op.type in ["check_finite_and_unscale", "update_loss_scaling"]: + reversed_x = [] + for input_name in op.desc.input('X'): + param_name = input_name[:input_name.find("@")] + + if self._is_parameter_in_local_shard(param_name): + reversed_x.append(input_name) + + # NOTE: When `reversed_x` is [], check_finite_and_unscale will be replaced by `fill_constant` op. + # The output of check_finite_and_unscale is be set False + if reversed_x: + op.desc.set_input('X', reversed_x) + op.desc.set_output('Out', reversed_x) + else: + if op.type == "check_finite_and_unscale": + op_role = op.attr('op_role') + out_name = op.output_arg_names[0] + out_var = main_block.vars[out_name] + main_block._remove_op(idx, sync=False) + main_block._insert_op_without_sync( + idx, + type="fill_constant", + outputs={"Out": out_var}, + attrs={ + "shape": out_var.shape, + "dtype": out_var.dtype, + "value": 0, + OP_ROLE_KEY: op_role, + }) + else: + main_block._remove_op(idx, sync=False) + + main_block._sync_with_cpp() + + def _shard_gradient_clip(self, main_block): + + if self.stage < 2: + return + + # TODO (JZ-LIANG) support calculate global norm with tensor parallelism + removed_op_type = ['elementwise_mul', 'squared_l2_norm', 'clip_by_norm'] + removed_op_idx = set() + removed_tmp_var = set() + + for idx, op in list(enumerate(main_block.ops)): + if not _is_gradient_clip_op(op): + continue + + if op.type in removed_op_type: + input_name = op.input("X")[0] + param_name = input_name[:input_name.find("@GRAD")] + if not self._is_parameter_in_local_shard(param_name): + removed_op_idx.add(idx) + if op.type in ['squared_l2_norm', 'clip_by_norm']: + for output_name in op.output_arg_names: + removed_tmp_var.add(output_name) + + for idx, op in reversed(list(enumerate(main_block.ops))): + if not _is_gradient_clip_op(op): + continue + if idx in removed_op_idx: + main_block._remove_op(idx, sync=False) + + for varname in removed_tmp_var: + main_block._remove_var(varname, sync=False) + + for idx, op in list(enumerate(main_block.ops)): + if not _is_gradient_clip_op(op): + continue + if op.type == 'sum': + reserved_vars = [] + for input_name in op.input_arg_names: + if input_name not in removed_tmp_var: + reserved_vars.append(input_name) + op.desc.set_input("X", reserved_vars) + + sum_op_output = op.desc.output_arg_names()[0] + for i, sharding_info in enumerate(self.sharding_infos): + new_op = main_block._insert_op( + idx + i + 1, + type='c_allreduce_sum', + inputs={'X': [sum_op_output]}, + outputs={'Out': [sum_op_output]}, + attrs={ + 'ring_id': sharding_info.group.id, + 'op_namescope': "/gradient_clip_model_parallelism", + 'use_calc_stream': True, + OP_ROLE_KEY: OpRole.Optimize, + }) + dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + main_block.var(sum_op_output)) + # assert dist_attr is not None + # naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + # new_op, dist_attr.process_mesh, dist_attr.dims_mapping, + # self._dist_context) + break + + main_block._sync_with_cpp() + + def _shard_weight_decay(self, main_block): + + if self.stage < 2: + return + + for idx, op in reversed(list(enumerate(main_block.ops))): + if not _is_weight_decay_op(op): + continue + else: + raise NotImplementedError( + "weight decay is NOT supported by now") + main_block._sync_with_cpp() + + def _shard_optimizer_ops_and_states(self, main_block, startup_block): + + should_removed_optimizer_states = [] + for idx, op in reversed(list(enumerate(main_block.ops))): + if not is_optimizer_op(op): + break + + if op.type in _supported_optimizer_type: + assert "Param" in op.input_names + assert len(op.input("Param")) == 1 + param_name = op.input("Param")[0] + if not self._is_parameter_in_local_shard(param_name): + should_removed_optimizer_states.extend([ + varname for varname in op.output_arg_names + if varname != param_name + ]) + main_block._remove_op(idx, sync=False) + else: + self.shared_params_grads.append( + self._get_param_grad(param_name)) + + for idx, op in reversed(list(enumerate(startup_block.ops))): + if len(op.output_arg_names) == 1 and op.output_arg_names[ + 0] in should_removed_optimizer_states: + startup_block._remove_op(idx, sync=False) + + for varname in should_removed_optimizer_states: + if main_block.has_var(varname): + main_block._remove_var(varname, sync=False) + if startup_block.has_var(varname): + startup_block._remove_var(varname, sync=False) + + main_block._sync_with_cpp() + startup_block._sync_with_cpp() + + def _insert_optimizer_broadcasts(self, main_block, startup_block): + + if self.stage > 2: + return + + for sharding_info in self.sharding_infos: + for param in sharding_info.params: + assert main_block.has_var(param.name) + assert startup_block.has_var(param.name) + + new_op = main_block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': + sharding_info.group.id, + 'root': + sharding_info.get_var_rank( + param.name), + 'use_calc_stream': + True, + OP_ROLE_KEY: + OpRole.Optimize + }) + param_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + param) + assert param_dist_attr is not None + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, param_dist_attr.process_mesh, + param_dist_attr.dims_mapping, self._dist_context) + main_block._sync_with_cpp() + + def _is_parameter_in_local_shard(self, param_name): + assert param_name in self.varname_to_sharding_info + sharding_info = self.varname_to_sharding_info[param_name] + return sharding_info.is_in_local_shard(param_name) + + def _get_param_grad(self, param_name): + assert param_name in self.varname_to_sharding_info + sharding_info = self.varname_to_sharding_info[param_name] + p_g = sharding_info.get_param_grad(param_name) + assert p_g is not None + return p_g + + def _shard_gradient_synchronization(self, main_block): + + if self.stage < 2: + return + + dp_ring_ids = [group.id for group in self.dp_groups] + for idx, op in reversed(list(enumerate(main_block.ops))): + if _is_param_grad_allreduce_op(op, main_block): + input_name = op.input_arg_names[0] + base_name = _get_base_name_from_grad_name(input_name) + sharding_info = self.varname_to_sharding_info[base_name] + _insert_reduce_op(main_block, idx, input_name, + sharding_info.group.id, + sharding_info.get_var_rank(base_name), + self._dist_context) + if not self.partial_sharding or not sharding_info.is_in_local_shard( + base_name): + main_block._remove_op(idx + 1, sync=False) + else: + op._set_attr("ring_id", self.outer_dp_group.id) + + # NOTE: + # var@GRAD = sum(var@GRAD@RENAME@0, var@GRAD@RENAME@1) + # If the var is not in local rank and it is output of many ops, or the var is renamed in another words, + # the sum op should be removed. + if _is_param_grad_sum_op(op, main_block): + out_name = op.output_arg_names[0] + base_name = _get_base_name_from_grad_name(out_name) + sharding_info = self.varname_to_sharding_info[base_name] + if not sharding_info.is_in_local_shard(base_name): + main_block._remove_op(idx, sync=False) + + main_block._sync_with_cpp() + + def _shard_parameter(self, main_block, startup_block): + + if self.stage < 3: + return + + dp_ring_ids = [group.id for group in self.dp_groups] + for sharding_info in self.sharding_infos: + need_broadcast_vars, param_usage = sharding_info.get_broadcast_vars_and_param_usage( + main_block) + not_used_param_nane = [] + for param_name in param_usage: + if param_usage[param_name] == 0 and sharding_info.get_var_rank( + param_name) != sharding_info.local_rank: + not_used_param_nane.append(param_name) + + for idx, op in reversed(list(enumerate(main_block.ops))): + if is_optimizer_op(op): + continue + + for input_name in op.desc.input_arg_names(): + # NOTE hack for embedding op when AMP 02-3 + # paddle amp force embedding (lookup table) to be run on fp32 + if _is_param_fp16_cast_op(main_block, op, + sharding_info.param_names): + continue + if input_name not in need_broadcast_vars: + continue + root_rank = sharding_info.get_var_rank(input_name) + if root_rank == sharding_info.local_rank: + broadcast_varname = input_name + else: + broadcast_varname = unique_name.generate(input_name + + "@BroadCast") + input_var = main_block.var(input_name) + new_var = main_block.create_var(name=broadcast_varname, + shape=input_var.shape, + dtype=input_var.dtype, + persistable=False) + ref_dist_attr = self._dist_context.get_tensor_dist_attr_for_program( + input_var) + out_var_dist_attr = set_var_dist_attr( + self._dist_context, new_var, + ref_dist_attr.dims_mapping, + ref_dist_attr.process_mesh) + op._rename_input(input_name, broadcast_varname) + + _insert_init_and_broadcast_op(main_block, idx, + broadcast_varname, + sharding_info.local_rank, + root_rank, + sharding_info.group.id, + op.attr('op_role'), + self._dist_context) + + for idx, op in reversed(list(enumerate(main_block.ops))): + if op.type != "cast": + continue + input_name = op.input_arg_names[0] + output_name = op.output_arg_names[0] + if input_name in not_used_param_nane: + main_block._remove_op(idx, sync=False) + main_block._remove_var(output_name, sync=False) + + for idx, op in reversed(list(enumerate(startup_block.ops))): + assert len(op.output_arg_names) == 1 + output_name = op.output_arg_names[0] + + if op.type == "c_broadcast" and op.attr( + "ring_id") in dp_ring_ids: + if self.outer_dp_group and sharding_info.get_var_rank( + output_name) == sharding_info.local_rank: + op._set_attr("ring_id", self.outer_dp_group.id) + else: + startup_block._remove_op(idx, sync=False) + continue + + if op.type != "c_broadcast" and output_name in param_usage and sharding_info.get_var_rank( + output_name) != sharding_info.local_rank: + startup_block._remove_op(idx, sync=False) + + for param_name in param_usage: + if sharding_info.get_var_rank( + param_name) != sharding_info.local_rank: + main_block._remove_var(param_name, sync=False) + startup_block._remove_var(param_name, sync=False) + + main_block._sync_with_cpp() + startup_block._sync_with_cpp() + + +def _insert_init_and_broadcast_op(block, insert_idx, varname, local_rank, + root_rank, ring_id, op_role, dist_context): + """ + empty op for initialization + """ + broadcast_var = block.var(varname) + broadcast_var_dist_attr = dist_context.get_tensor_dist_attr_for_program( + broadcast_var) + + new_op = block._insert_op_without_sync(insert_idx, + type='c_broadcast', + inputs={'X': varname}, + outputs={'Out': varname}, + attrs={ + 'ring_id': ring_id, + 'root': root_rank, + 'use_calc_stream': True, + OP_ROLE_KEY: op_role + }) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, broadcast_var_dist_attr.process_mesh, + broadcast_var_dist_attr.dims_mapping, dist_context) + if local_rank != root_rank: + + new_op = block._insert_op_without_sync( + insert_idx, + type="empty", + outputs={"Out": broadcast_var.name}, + attrs={ + "shape": broadcast_var.shape, + "dtype": broadcast_var.dtype, + OP_ROLE_KEY: op_role + }) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, broadcast_var_dist_attr.process_mesh, + broadcast_var_dist_attr.dims_mapping, dist_context) + return + + +def _insert_reduce_op(block, + insert_idx, + reduce_var, + ring_id, + root_id, + dist_context, + op_role=OpRole.Backward, + use_calc_stream=True): + assert root_id >= 0, "root id should be a positive int, but now root id is {}".format( + root_id) + new_op = block._insert_op_without_sync(insert_idx, + type='c_reduce_sum', + inputs={'X': [reduce_var]}, + outputs={'Out': [reduce_var]}, + attrs={ + 'ring_id': ring_id, + 'root_id': root_id, + 'use_calc_stream': + use_calc_stream, + OP_ROLE_KEY: op_role + }) + + dist_attr = dist_context.get_tensor_dist_attr_for_program( + block.var(reduce_var)) + naive_set_dist_op_attr_for_program_by_mesh_and_mapping( + new_op, dist_attr.process_mesh, dist_attr.dims_mapping, dist_context) + + +def _get_dp_and_sharding_groups(origin_group, sharding_group_size, rank): + dp_axis = 0 + sharding_axis = 1 + shape = [len(origin_group) // sharding_group_size, sharding_group_size] + + dp_group = _get_comm_group(origin_group, shape, dp_axis, rank) + sharding_group = _get_comm_group(origin_group, shape, sharding_axis, rank) + + return dp_group, sharding_group + + +def _is_gradient_clip_op(op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/gradient_clip") + + +def _is_weight_decay_op(op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/regularization") + + +def _is_param_grad_fp32_cast_op(block, op): + if not is_backward_op(op): + return False + if not _is_desired_cast_op(block, op, core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32): + return False + output_name = op.desc.output_arg_names()[0] + base_name = output_name[:output_name.find("@")] + if not block.has_var(base_name): + return False + return block.var(base_name).is_parameter + + +def _is_param_fp16_cast_op(block, op, params): + + if is_optimizer_op(op): + return False + if not _is_desired_cast_op(block, op): + return False + input_name = op.desc.input_arg_names()[0] + if input_name not in params: + return False + return True + + +def _is_desired_cast_op(block, + op, + src_var_type=core.VarDesc.VarType.FP32, + dst_var_type=core.VarDesc.VarType.FP16): + if op.type != "cast": + return False + assert (len(op.desc.input_arg_names()) == 1) + assert (len(op.desc.output_arg_names()) == 1) + input_var = block.var(op.desc.input_arg_names()[0]) + output_var = block.var(op.desc.output_arg_names()[0]) + + if input_var.dtype != src_var_type or \ + output_var.dtype != dst_var_type: + return False + + return True + + +def _get_base_name_from_grad_name(grad_name): + base_name = None + if ".cast_fp16@GRAD" in grad_name: + base_name = grad_name[:grad_name.find(".cast_fp16@GRAD")] + elif "@GRAD" in grad_name: + base_name = grad_name[:grad_name.find("@GRAD")] + return base_name + + +def _is_param_grad_allreduce_op(op, block): + + if not is_data_parallel_reduce_op(op): + return False + + output_name = op.output_arg_names[0] + base_name = _get_base_name_from_grad_name(output_name) + + if not block.has_var(base_name): + return False + + return block.var(base_name).is_parameter + + +def _is_param_grad_sum_op(op, block): + + if not is_backward_op(op): + return False + if op.type != "sum": + return False + + output_name = op.output_arg_names[0] + base_name = _get_base_name_from_grad_name(output_name) + + if not block.has_var(base_name): + return False + + return block.var(base_name).is_parameter + + +def _is_forward_op(op): + return op.attr("op_role") == 0 + + +def _inference_data_parallel_group_for_operator(rank_id, op, dist_context): + + dp_group = None + for input_name in op.input_arg_names: + if not is_parameter_related(input_name, op.block): + dist_attr = dist_context.get_op_dist_attr_for_program(op) + process_mesh = dist_attr.process_mesh + input_dim_mapping = dist_attr.get_input_dims_mapping(input_name) + mesh_shape = process_mesh.topology + # TODO(JZ-LIANG) replace with specific batch size dimension + batch_size_axis = input_dim_mapping[0] + if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1: + group_ranks = _get_comm_group(process_mesh.processes, + process_mesh.topology, + batch_size_axis, rank_id) + dp_group = new_process_group(group_ranks) + break + + return dp_group + + +def shard_parameters(params, group_size): + # TODO(JZ-LIANG) support multiple partition methods + # method1: greedy even but unorder + # method2: roughly even with oreder + mapping = {} + for rank_ in range(group_size): + mapping[rank_] = [] + sizes = [0] * group_size + for param in params: + rank = sizes.index(min(sizes)) + mapping[rank].append(param) + numel = reduce(lambda x, y: x * y, param.shape) + assert numel > 0, "param [{}] should larger than 0, but it is [{}]".format( + param.name, numel) + sizes[rank] += numel + + return mapping + + +class ShardingInfo(object): + + def __init__(self, group, rank, params_grads): + self.group = group + self.params_grads = dict([(p.name, (p, g)) for p, g in params_grads]) + assert len(self.params_grads) == len(set( + self.params_grads)), "found duplicated param in params_grads" + + self.params = [p for p, _ in params_grads] + self.param_names = [p.name for p in self.params] + self.group_size = group.nranks + self.global_rank = rank + self.local_rank = group.ranks.index(self.global_rank) + # rank in below mapping are local rank in this sharding group + self.rank_to_params = shard_parameters(self.params, self.group_size) + # include fp32 and fp16 param + self.param_to_rank = dict() + self._map_param_to_rank() + + def _map_param_to_rank(self): + """ + mapping parameters to the rank which holds it. + """ + for rank, params in self.rank_to_params.items(): + for param in params: + self.param_to_rank[param.name] = rank + + def get_var_rank(self, varname): + if varname in self.param_to_rank: + return self.param_to_rank[varname] + return -1 + + # determine fp32 and fp16 (cast) param + def is_in_local_shard(self, param_name): + return self.get_var_rank(param_name) == self.local_rank + + # NOTE the follwo logic is designed for supporting AMP O1 when + # the param would be cast to fp16 before used for caculation. + # and sharding should only broadcast the casted fp16 param + # instead of the origin fp32 version param. + def get_broadcast_vars_and_param_usage(self, block): + broadcast_vars = set([]) + fp16_params = set([]) + fp16_to_fp32 = {} + + param_usage = {x: 0 for x in self.param_names} + for op in block.ops: + if is_optimizer_op(op): + continue + for input_name in op.desc.input_arg_names(): + if input_name in self.param_names: + param_usage[input_name] += 1 + + for op in block.ops: + if not _is_param_fp16_cast_op(block, op, self.param_names): + continue + input_name = op.input_arg_names[0] + output_name = op.output_arg_names[0] + broadcast_vars.add(output_name) + fp16_params.add(output_name) + fp16_to_fp32[output_name] = input_name + param_usage[input_name] -= 1 + self.param_to_rank[output_name] = self.param_to_rank[input_name] + + for param, usage in param_usage.items(): + if usage > 0: + broadcast_vars.add(param) + return broadcast_vars, param_usage + + def get_param_grad(self, param_name): + if not self.is_in_local_shard(param_name): + raise ValueError( + "param[{}] not in current rank.".format(param_name)) + if param_name not in self.params_grads: + raise ValueError('param[{}] not in params_grads'.format(param_name)) + return self.params_grads.get(param_name, None) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/cpp_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/cpp_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..c729a919c1a33719855af19ba11d0563bea28226 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/cpp_pass.py @@ -0,0 +1,166 @@ +# Copyright (c) 2021 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. + +from paddle.static import Executor +from .pass_base import PassType, CPPPassWrapper, register_pass +from paddle.fluid.framework import core, _apply_pass as _apply_cpp_pass + + +@register_pass("fuse_elewise_add_act") +class FuseElementwiseAddActPass(CPPPassWrapper): + + def __init__(self): + super(FuseElementwiseAddActPass, self).__init__() + + @property + def cpp_name(self): + return "fuse_elewise_add_act_pass" + + def _type(self): + return PassType.FUSION_OPT + + +@register_pass("fuse_bn_act") +class FuseBatchNormActPass(CPPPassWrapper): + + def __init__(self): + super(FuseBatchNormActPass, self).__init__() + + @property + def cpp_name(self): + return "fuse_bn_act_pass" + + def _type(self): + return PassType.FUSION_OPT + + +@register_pass("fuse_bn_add_act") +class FuseBatchNormAddActPass(CPPPassWrapper): + + def __init__(self): + super(FuseBatchNormAddActPass, self).__init__() + + @property + def cpp_name(self): + return "fuse_bn_add_act_pass" + + def _type(self): + return PassType.FUSION_OPT + + +@register_pass("fuse_relu_depthwise_conv") +class FuseReluDepthwiseConvPass(CPPPassWrapper): + + def __init__(self): + super(FuseReluDepthwiseConvPass, self).__init__() + + @property + def cpp_name(self): + return "fuse_relu_depthwise_conv_pass" + + def _type(self): + return PassType.FUSION_OPT + + +@register_pass("fuse_optimizer") +class FuseOptimizerPass(CPPPassWrapper): + + def __init__(self): + super(FuseOptimizerPass, self).__init__() + + @property + def cpp_name(self): + return [ + "fuse_adam_op_pass", "fuse_sgd_op_pass", "fuse_momentum_op_pass" + ] + + def _type(self): + return PassType.FUSION_OPT + + +@register_pass("inplace_addto_op") +class InplaceAddtoOpPass(CPPPassWrapper): + + def __init__(self): + super(InplaceAddtoOpPass, self).__init__() + + @property + def cpp_name(self): + return "inplace_addto_op_pass" + + def _type(self): + return PassType.CALC_OPT + + +def _set_cinn_op_flag(flag_name, extra_ops): + values = core.globals()[flag_name] + values = [v.strip() for v in values.split(";") if v.strip()] + values.extend(extra_ops) + core.globals()[flag_name] = ";".join(values) + + +@register_pass("build_cinn") +class BuildCINNPass(CPPPassWrapper): + + def __init__(self): + super(BuildCINNPass, self).__init__() + self.set_attr("allow_ops", []) + self.set_attr("deny_ops", []) + + @property + def cpp_name(self): + return "build_cinn_pass" + + def _type(self): + return PassType.CALC_OPT + + def _apply_single_impl(self, main_program, startup_program, context): + + assert 'FLAGS_allow_cinn_ops' in core.globals( + ), "PaddlePaddle is not compiled with CINN support" + old_allow_ops = core.globals()['FLAGS_allow_cinn_ops'] + old_deny_ops = core.globals()['FLAGS_deny_cinn_ops'] + try: + _set_cinn_op_flag('FLAGS_allow_cinn_ops', + self.get_attr("allow_ops")) + _set_cinn_op_flag('FLAGS_deny_cinn_ops', self.get_attr("deny_ops")) + + feed = self.get_attr('feed', []) + fetch_list = self.get_attr('fetch_list', []) + prune_program = self.get_attr('prune_program', True) + + if prune_program: + tmp_main_program = Executor._prune_program( + main_program, feed, fetch_list, []) + + tmp_main_program = Executor._add_fetch_ops( + tmp_main_program, fetch_list, 'fetch') + + else: + + tmp_main_program = Executor._add_fetch_ops( + main_program, fetch_list, 'fetch') + + _apply_cpp_pass(tmp_main_program, startup_program, self.cpp_name, + {}, self.cpp_attr_types) + + tmp_main_program = Executor._remove_fetch_ops(tmp_main_program) + + tmp_main_program = core.ProgramDesc(tmp_main_program.desc) + + main_program._rebuild_from_desc(tmp_main_program) + + finally: + core.globals()['FLAGS_allow_cinn_ops'] = old_allow_ops + core.globals()['FLAGS_deny_cinn_ops'] = old_deny_ops diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/fuse_all_reduce.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/fuse_all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..33a58a67c9d16459fe62b2c9e1c65540e18ff87d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/fuse_all_reduce.py @@ -0,0 +1,365 @@ +# Copyright (c) 2021 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. + +from paddle.framework import core +from paddle.fluid import unique_name +from .pass_base import PassBase, PassType, register_pass +from collections import OrderedDict +import numpy as np + + +def find_adjacent_match_sequences(iterable, + filter_func, + adjacent_filter_func=None): + n = len(iterable) + match_sequences = [] + if adjacent_filter_func is None: + adjacent_filter_func = lambda ref_op, new_op: True + i = 0 + while True: + while i < n and not filter_func(iterable[i]): + i += 1 + j = i + 1 + while j < n and filter_func(iterable[j]) and adjacent_filter_func( + iterable[i], iterable[j]): + j += 1 + if i < n and j <= n: + match_sequences.append((i, j)) + i = j + 1 + if i >= n: + break + return match_sequences + + +def insert_fuse_all_reduce_ops(block, reversed_op_indices, input_var_names, + output_var_names, dtype, attrs): + fused_var = block.create_var(name=unique_name.generate( + "FusedOutput_{}".format(input_var_names[0])), + dtype=dtype) + + # FIXME(zengjinle): here we assume that we use + # c_sync_calc_stream/c_sync_comm_stream to do sync. + # But someone may use c_wait_compute/c_wait_comm instead. + if not attrs["use_calc_stream"]: + ring_id = attrs["ring_id"] + new_op_indices = list(reversed_op_indices) + + for i, op_idx in enumerate(reversed_op_indices): + prev_op_idx = op_idx - 1 + while prev_op_idx >= 0 and block.ops[ + prev_op_idx].type == "c_sync_calc_stream": + new_op_indices.append(prev_op_idx) + prev_op_idx -= 1 + + if i > 0: + next_op_idx = op_idx + 1 + n = len(block.ops) + while next_op_idx < n and block.ops[ + next_op_idx].type == "c_sync_comm_stream": + assert block.ops[next_op_idx].attr("ring_id") == ring_id + new_op_indices.append(next_op_idx) + + new_op_indices = list(set(new_op_indices)) + new_op_indices.sort(reverse=True) + reversed_op_indices = new_op_indices + + insert_idx = reversed_op_indices[0] + 1 + op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName() + + concated_shapes = [] + concated_ranks = [] + for var_name in output_var_names: + shape = block._find_var_recursive(var_name).shape + concated_shapes.extend(shape) + concated_ranks.append(len(shape)) + + coalesce_tensor_op_kwargs = { + "type": "coalesce_tensor", + "inputs": { + "Input": input_var_names, + }, + "outputs": { + "Output": output_var_names, + "FusedOutput": fused_var, + }, + "attrs": { + "use_align": True, + "dtype": dtype, + "concated_shapes": concated_shapes, + "concated_ranks": concated_ranks, + op_role_key: attrs[op_role_key], + }, + } + + if not attrs["use_calc_stream"]: + block._insert_op_without_sync(insert_idx, + type="c_sync_calc_stream", + inputs={"X": fused_var}, + outputs={ + "Out": fused_var, + op_role_key: attrs[op_role_key] + }) + insert_idx += 1 + + # c_allreduce_sum should insert + block._insert_op_without_sync(insert_idx, + type="c_allreduce_sum", + inputs={"X": fused_var}, + outputs={"Out": fused_var}, + attrs=attrs) + + for op_idx in reversed_op_indices: + block._remove_op(op_idx) + + return coalesce_tensor_op_kwargs + + +def has_same_attrs(op1, op2, attr_names): + for attr_name in attr_names: + if op1.attr(attr_name) != op2.attr(attr_name): + return False + return True + + +def filter_all_collective_op_indices(block): + # NOTE: should add more collective ops + all_collective_ops = { + "c_allreduce_sum", + "c_allreduce_prod", + "c_allreduce_max", + "c_allreduce_min", + "c_allgather", + "c_broadcast", + } + + match_op_indices = [] + for i, op in enumerate(block.ops): + if op.type in all_collective_ops: + match_op_indices.append(i) + return match_op_indices + + +def find_all_fuse_all_reduce_groups(block): + collective_op_indices = filter_all_collective_op_indices(block) + collective_ops = [block.ops[i] for i in collective_op_indices] + + def is_valid_allreduce_op(op): + if op.type != "c_allreduce_sum" or op.attr("use_model_parallel"): + return False + in_var_name = op.input("X")[0] + out_var_name = op.output("Out")[0] + if in_var_name != out_var_name: + return False + in_var = block._find_var_recursive(in_var_name) + assert in_var is not None + if in_var.type != core.VarDesc.VarType.LOD_TENSOR: + return False + shape = in_var.shape + if any([s <= 0 for s in shape]): + return False + return True + + same_attr_names = [ + "ring_id", + "use_calc_stream", + core.op_proto_and_checker_maker.kOpRoleAttrName(), + core.op_proto_and_checker_maker.kOpDeviceAttrName(), + ] + + def is_same_adjacent_op(ref_op, new_op): + if not has_same_attrs(ref_op, new_op, same_attr_names): + return False + ref_op_in_var = block._find_var_recursive(ref_op.input("X")[0]) + new_op_in_var = block._find_var_recursive(new_op.input("X")[0]) + if ref_op_in_var.dtype != new_op_in_var.dtype: + return False + return True + + match_seqs = find_adjacent_match_sequences(collective_ops, + is_valid_allreduce_op, + is_same_adjacent_op) + new_match_seqs = [] + for i, j in match_seqs: + new_match_seqs.append([collective_op_indices[k] for k in range(i, j)]) + return new_match_seqs + + +def split_fuse_all_reduce_groups_by_deps(block, groups, op_deps): + new_groups = [] + + def insert_new_group(op_indices, start_idx, end_idx): + if end_idx - start_idx > 1: + new_groups.append(op_indices[start_idx:end_idx]) + + for op_indices in groups: + n = len(op_indices) + assert n > 0 + if n == 1: + continue + + start_idx = 0 + k = start_idx + 1 + while k < n: + found_group = False + for prev_idx in range(start_idx, k): + dep = op_deps[op_indices[prev_idx]][op_indices[k]] + if dep == core.Node.Dep.NoDep: + continue + # [start_idx, k) is valid groups + insert_new_group(op_indices, start_idx, k) + start_idx = k + break + k += 1 + + insert_new_group(op_indices, start_idx, k) + + return new_groups + + +def insert_coalesce_tensor_ops(block, coalesce_ops_kwargs): + if not coalesce_ops_kwargs: + return + + var_infos = {} + for idx, op in enumerate(block.ops): + for var in op.input_arg_names: + if var not in var_infos: + var_infos[var] = [idx, True] + + for var in op.output_arg_names: + if var not in var_infos: + var_infos[var] = [idx, False] + + n = len(block.ops) + insert_idx_and_kwargs = [] + for group_idx, kwargs in enumerate(coalesce_ops_kwargs): + all_vars = kwargs["inputs"]["Input"] + kwargs["outputs"]["Output"] + min_op_idx = n + copy_data = False + for var in all_vars: + if var not in var_infos: + copy_data = True + min_idx = 0 + break + op_idx, is_input = var_infos[var] + if is_input: + copy_data = True + min_op_idx = min(min_op_idx, op_idx) + kwargs["attrs"]["copy_data"] = copy_data + insert_idx_and_kwargs.append((min_op_idx, kwargs)) + + insert_idx_and_kwargs.sort(key=lambda element: element[0], reverse=True) + for idx, kwargs in insert_idx_and_kwargs: + block._insert_op_without_sync(idx, **kwargs) + + +def insert_fuse_all_reduce_by_memory_size(block, groups, max_memory_size): + op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName() + op_role_var_key = core.op_proto_and_checker_maker.kOpRoleVarAttrName() + op_device_key = core.op_proto_and_checker_maker.kOpDeviceAttrName() + coalesce_ops_kwargs = [] + for group in reversed(groups): + first_op = block.ops[group[0]] + ring_id = first_op.attr("ring_id") + use_calc_stream = first_op.attr("use_calc_stream") + use_model_parallel = first_op.attr("use_model_parallel") + op_role = first_op.attr(op_role_key) + op_device = first_op.attr(op_device_key) + + attrs = { + "ring_id": ring_id, + "use_calc_stream": use_calc_stream, + "use_model_parallel": use_model_parallel, + op_role_key: op_role, + op_device_key: op_device, + } + dtype = block._find_var_recursive(first_op.input("X")[0]).dtype + sizeof = core.size_of_dtype(dtype) + + cur_mem_size = 0 + op_role_vars = [] + recorded_op_indices = [] + in_var_names = [] + out_var_names = [] + for op_idx in reversed(group): + op = block.ops[op_idx] + in_var_name = op.input("X")[0] + out_var_name = op.output("Out")[0] + in_var = block._find_var_recursive(in_var_name) + mem_size = int(np.prod(in_var.shape)) * sizeof + if cur_mem_size + mem_size > max_memory_size: + if len(recorded_op_indices) > 1: + attrs[op_role_var_key] = op_role_vars + coalesce_op_kwargs = insert_fuse_all_reduce_ops( + block, recorded_op_indices, in_var_names, out_var_names, + dtype, attrs) + coalesce_ops_kwargs.append(coalesce_op_kwargs) + + cur_mem_size = 0 + op_role_vars = [] + recorded_op_indices = [] + in_var_names = [] + out_var_names = [] + + cur_mem_size += mem_size + recorded_op_indices.append(op_idx) + in_var_names.append(in_var_name) + out_var_names.append(out_var_name) + if op.has_attr(op_role_var_key): + op_role_vars.extend(op.attr(op_role_var_key)) + + if len(recorded_op_indices) > 1: + attrs[op_role_var_key] = op_role_vars + coalesce_op_kwargs = insert_fuse_all_reduce_ops( + block, recorded_op_indices, in_var_names, out_var_names, dtype, + attrs) + coalesce_ops_kwargs.append(coalesce_op_kwargs) + block._sync_with_cpp() + insert_coalesce_tensor_ops(block, coalesce_ops_kwargs) + + +@register_pass("fuse_all_reduce") +class FuseAllReducePass(PassBase): + + def __init__(self): + super(FuseAllReducePass, self).__init__() + self.set_attr("max_memory_size", -1) + + def _check_self(self): + max_memory_size = self.get_attr("max_memory_size") + return max_memory_size > 0 + + def _check_conflict(self, other_pass): + return True + + def _type(self): + return PassType.COMM_OPT + + # NOTE: why FuseAllReducePass can override apply_single_impl instead of + # apply_impl? AllReduce is a collective operation, so the program of each + # rank inside the same communication group should have the same + # c_allreduce_sum operations. Therefore, FuseAllReducePass can override + # apply_single_impl directly. + def _apply_single_impl(self, main_program, startup_program, context): + max_memory_size = self.get_attr("max_memory_size") + op_deps = main_program.desc.get_op_deps() + num_blocks = main_program.num_blocks + for i in range(num_blocks): + block = main_program.block(i) + groups = find_all_fuse_all_reduce_groups(block) + groups = split_fuse_all_reduce_groups_by_deps( + block, groups, op_deps[i]) + insert_fuse_all_reduce_by_memory_size(block, groups, + max_memory_size) + main_program._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b733f8866937579a1eb0da654557b6d45fe45c2d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_base.py @@ -0,0 +1,327 @@ +# Copyright (c) 2021 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. + +import six +import sys +from abc import ABC, abstractmethod +from paddle.fluid.framework import program_guard, _apply_pass as _apply_cpp_pass + + +class PassContext: + + def __init__(self): + self._applied_passes = [] + self._attrs = {} + + def set_attr(self, key, value): + self._attrs[key] = value + + def get_attr(self, key, default=None): + return self._attrs.get(key, default) + + @property + def passes(self): + return self._applied_passes + + def _add_pass(self, pass_obj): + self._applied_passes.append(pass_obj) + + def _pop_pass(self): + del self._applied_passes[-1] + + +class PassType: + UNKNOWN = 0 + COMM_OPT = 1 + CALC_OPT = 2 + PARALLEL_OPT = 3 + FUSION_OPT = 4 + + +class PassBase(ABC): + _REGISTERED_PASSES = {} + _COMMON_RULES = [] + + _BEFORE_WHITE_LISTS_DICT = {} + _AFTER_WHITE_LISTS_DICT = {} + + name = None + + @staticmethod + def _register(pass_name, pass_class): + assert issubclass(pass_class, PassBase) + PassBase._REGISTERED_PASSES[pass_name] = pass_class + + def __init__(self): + self._attrs = {} + + def set_attr(self, key, value): + self._attrs[key] = value + return self + + def get_attr(self, key, default=None): + return self._attrs.get(key, default) + + @abstractmethod + def _check_self(self): + pass + + @abstractmethod + def _check_conflict(self, other_pass): + pass + + def _type(self): + return PassType.UNKNOWN + + def _check_conflict_including_common_rules(self, other_pass): + return self._check_conflict(other_pass) and all( + [r(other_pass, self) for r in PassBase._COMMON_RULES]) + + def apply(self, main_programs, startup_programs, context=None): + if context is None: + context = PassContext() + + if not self._check_self(): + return context + + if not all([ + self._check_conflict_including_common_rules(p) + for p in context.passes + ]): + return context + + assert isinstance(main_programs, list) + assert isinstance(startup_programs, list) + assert len(main_programs) == len(startup_programs) + self._apply_impl(main_programs, startup_programs, context) + context._add_pass(self) + return context + + def _apply_impl(self, main_programs, startup_programs, context): + for main_program, startup_program in zip(main_programs, + startup_programs): + self._apply_single_impl(main_program, startup_program, context) + + @abstractmethod + def _apply_single_impl(self, main_program, startup_program, context): + pass + + +def register_pass(name): + + def impl(cls): + PassBase._register(name, cls) + cls.name = name + return cls + + return impl + + +def new_pass(name, pass_attrs={}): + pass_class = PassBase._REGISTERED_PASSES.get(name) + assert pass_class is not None, "Pass {} is not registered".format(name) + pass_obj = pass_class() + for k, v in pass_attrs.items(): + pass_obj.set_attr(k, v) + return pass_obj + + +class CPPPassWrapper(PassBase): + + def __init__(self): + super(CPPPassWrapper, self).__init__() + + @property + def cpp_name(self): + raise NotImplementedError() + + @property + def cpp_attr_types(self): + return {} + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, context): + _apply_cpp_pass(main_program, startup_program, self.cpp_name, + self._attrs, self.cpp_attr_types) + + +def _fusion_opt_last_rule(pass_before, pass_after): + if pass_before._type( + ) == PassType.FUSION_OPT and pass_after._type() != PassType.FUSION_OPT: + return False + else: + return True + + +def _make_rule_from_white_lists_dict(before_white_lists_dict, + after_white_lists_dict): + + def collect_pass_names(white_lists_dict, result): + for k, v in white_lists_dict.items(): + result.add(k) + assert isinstance(v, (list, tuple)) + for pass_name in v: + assert isinstance(pass_name, (bytes, str)) + result.add(pass_name) + + all_pass_names = set() + collect_pass_names(before_white_lists_dict, all_pass_names) + collect_pass_names(after_white_lists_dict, all_pass_names) + + compatible_pass_dict = {} + for pass_name in all_pass_names: + compatible_pass_dict[pass_name] = set() + + for k, v in before_white_lists_dict.items(): + for pass_name in v: + compatible_pass_dict[k].add(pass_name) + + for k, v in after_white_lists_dict.items(): + for pass_name in v: + compatible_pass_dict[pass_name].add(k) + + def rule(pass_before, pass_after): + all_passes_after = compatible_pass_dict.get(pass_before.name) + if all_passes_after is None or pass_after.name not in compatible_pass_dict: + return True + else: + return pass_after.name in all_passes_after + + return rule + + +# The key-value pair (k, [v1, v2, ..., vn]) means the pass k can be +# applied before any of pass [v1, v2, ..., vn] is applied +PassBase._BEFORE_WHITE_LISTS_DICT = { + "fuse_gradient_merge": ["fuse_all_reduce"], + # Add more white lists here +} + +# The key-value pair (k, [v1, v2, ..., vn]) means the pass k can be +# applied after any of pass [v1, v2, ..., vn] is applied +PassBase._AFTER_WHITE_LISTS_DICT = { + # Add more white lists here +} + +PassBase._COMMON_RULES = [ + _fusion_opt_last_rule, + lambda pass_before, pass_after: type(pass_before) != type(pass_after), + _make_rule_from_white_lists_dict(PassBase._BEFORE_WHITE_LISTS_DICT, + PassBase._AFTER_WHITE_LISTS_DICT), + # Add more common rules here +] + + +def _find_longest_path(edges): + n = len(edges) + paths = [None] * n + dists = [None] * n + + min_path = [] + min_dist = 0 + for i in range(n): + paths[i] = [None] * n + dists[i] = [None] * n + for j in range(n): + assert isinstance(edges[i][j], bool) + if not edges[i][j]: + dists[i][j] = n # inf + paths[i][j] = [] + else: + assert edges[i][j] is True + dists[i][j] = -1 + paths[i][j] = [i, j] + if dists[i][j] < min_dist: + min_dist = -1 + min_path = paths[i][j] + + for k in range(n): + for i in range(n): + for j in range(n): + if dists[i][j] > dists[i][k] + dists[k][j]: + dists[i][j] = dists[i][k] + dists[k][j] + paths[i][j] = paths[i][k] + paths[k][j] + if dists[i][j] < min_dist: + min_dist = dists[i][j] + min_path = paths[i][j] + + return min_path if min_path else [0] + + +def _solve_pass_conflict(passes, context): + passes = [p for p in passes if p._check_self()] + if not passes: + return [] + + old_passes = passes + passes = [] + for p in old_passes: + if all([ + p._check_conflict_including_common_rules(applied_p) + for applied_p in context.passes + ]): + passes.append(p) + + if not passes: + return [] + + n = len(passes) + adjacent_matrix = [] + for _ in range(n): + adjacent_matrix.append([None] * n) + + for i in range(n): + for j in range(n): + adjacent_matrix[i][j] = passes[ + j]._check_conflict_including_common_rules(passes[i]) + + longest_path = _find_longest_path(adjacent_matrix) + return [passes[idx] for idx in longest_path] + + +class PassManager: + + def __init__(self, passes, context=None, auto_solve_conflict=True): + if context is None: + context = PassContext() + self._context = context + + if auto_solve_conflict: + self._passes = _solve_pass_conflict(passes, context) + else: + self._passes = list(passes) + + def apply(self, main_programs, startup_programs): + context = self._context + for p in self._passes: + context = p.apply(main_programs, startup_programs, context) + self._context = context + return context + + @property + def context(self): + return self._context + + @property + def names(self): + return [p.name for p in self.passes] + + @property + def passes(self): + return tuple(self._passes) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6e43930d2e176f914478b595f77194eb9ee65ec0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/pass_utils.py @@ -0,0 +1,134 @@ +# Copyright (c) 2021 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. + +from collections import OrderedDict + + +def list_to_ordered_dict(list_obj, ordered_dict=None): + if ordered_dict is None: + ordered_dict = OrderedDict() + else: + assert isinstance(ordered_dict, OrderedDict) + for obj in list_obj: + if obj not in ordered_dict: + ordered_dict[obj] = True + return ordered_dict + + +# The inputs of a program are the variables +# that first occur as the input of the op. +def get_inputs_of_program(program): + visited_vars = set() + input_vars = [] + for op in program.global_block().ops: + for in_var_name in op.input_arg_names: + if in_var_name not in visited_vars: + input_vars.append(in_var_name) + visited_vars.add(in_var_name) + + for out_var_name in op.output_arg_names: + visited_vars.add(out_var_name) + return input_vars + + +def get_outputs_of_program(program): + output_vars = OrderedDict() + for op in program.global_block().ops: + list_to_ordered_dict(op.output_arg_names, output_vars) + return list(output_vars.keys()) + + +def prune_program(program, start_op_idx, end_op_idx): + op_num = len(program.global_block().ops) + if start_op_idx < 0: + start_op_idx += op_num + assert start_op_idx >= 0 and start_op_idx < op_num + if end_op_idx < 0: + end_op_idx += op_num + assert end_op_idx >= 0 and end_op_idx <= op_num, end_op_idx + assert start_op_idx < end_op_idx + + program = program.clone() + for idx in range(op_num - 1, end_op_idx - 1, -1): + program.global_block()._remove_op(idx, sync=False) + for idx in range(start_op_idx - 1, -1, -1): + program.global_block()._remove_op(idx, sync=False) + program._sync_with_cpp() + + valid_vars = set() + for op in program.global_block().ops: + for in_var_name in op.input_arg_names: + valid_vars.add(in_var_name) + for out_var_name in op.output_arg_names: + valid_vars.add(out_var_name) + + vars_to_remove = [] + for var in program.global_block().vars: + if var not in valid_vars: + vars_to_remove.append(var) + + for var in vars_to_remove: + program.global_block()._remove_var(var, sync=False) + program._sync_with_cpp() + return program + + +def split_program(program, op_indices): + """ + Split the program by op_indices. + + For examples, a program has 100 ops, and op_indices = [25, 60]. + Then the program is splitted into 3 parts, containing 25, 35 and 40 + ops respectively. + + The return values are a tuple with 3 elements: the splitted program + list, the input var names of each splitted program, and the output + var names of each splitted program. + """ + assert op_indices, "op_indices cannot be empty" + op_num = len(program.global_block().ops) + assert op_num > 0, "program cannot be empty" + + op_indices = [idx if idx >= 0 else idx + op_num for idx in op_indices] + + if op_indices[0] != 0: + op_indices = [0] + op_indices + if op_indices[-1] != op_num: + op_indices.append(op_num) + + for idx in range(len(op_indices) - 1): + assert op_indices[idx] < op_indices[ + idx + 1], "op_indices must be strictly sorted" + + splitted_programs = [] + for idx in range(len(op_indices) - 1): + new_split = prune_program(program, op_indices[idx], op_indices[idx + 1]) + splitted_programs.append(new_split) + + num_split = len(splitted_programs) + input_vars = [get_inputs_of_program(p) for p in splitted_programs] + output_vars = [ + list_to_ordered_dict(get_outputs_of_program(p)) + for p in splitted_programs + ] + valid_output_vars = [OrderedDict() for _ in range(num_split)] + valid_output_vars[-1] = output_vars[-1] + for i in range(1, num_split): + for in_var_name in input_vars[i]: + for j in reversed(range(i)): + if in_var_name in output_vars[j]: + valid_output_vars[j][in_var_name] = True + break + valid_output_vars = [list(item.keys()) for item in valid_output_vars] + return splitted_programs, input_vars, valid_output_vars diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_server_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_server_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..0b77468338784389c9be56ab49010b2f30d50baf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_server_pass.py @@ -0,0 +1,240 @@ +# Copyright (c) 2022 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. + +import paddle +from ..ps.utils.public import * +from paddle.framework import core +from .pass_base import PassBase, register_pass +from paddle.optimizer.lr import LRScheduler +from paddle.optimizer.lr import ExponentialDecay, NoamDecay, PiecewiseDecay, NaturalExpDecay, InverseTimeDecay +from paddle.fluid.layers.learning_rate_scheduler import exponential_decay, noam_decay, piecewise_decay, natural_exp_decay, inverse_time_decay + + +@register_pass("add_lr_decay_table_pass") +class AddLrDecayTablePass(PassBase): + + def __init__(self): + super(AddLrDecayTablePass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _add_tensor_table(self, + attrs, + feed_var_name, + fetch_var_name="", + startup_program=None, + main_program=None, + tensor_table_class=""): + tensor_table_dict = {} + tensor_table_dict[feed_var_name] = {} + tensor_table_dict[feed_var_name]["feed_var_name"] = feed_var_name + tensor_table_dict[feed_var_name]["fetch_var_name"] = fetch_var_name + tensor_table_dict[feed_var_name]["startup_program"] = startup_program + tensor_table_dict[feed_var_name]["main_program"] = main_program + tensor_table_dict[feed_var_name][ + "tensor_table_class"] = tensor_table_class + attrs['tensor_table'] = tensor_table_dict + + def _get_lr_sheduler_program(self, lr_sheduler, lr_decay_steps): + schedler_decay = [ + 'NoamDecay', 'NaturalExpDecay', 'InverseTimeDecay', + 'ExponentialDecay' + ] + + decay_main_program = fluid.framework.Program() + decay_startup_program = fluid.framework.Program() + lr_name = "" + + if isinstance(lr_sheduler, ExponentialDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = exponential_decay(1.0, lr_decay_steps, lr_sheduler.gamma, + True) + lr_name = lr.name + logging.warn( + "ExponentialDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + elif isinstance(lr_sheduler, NoamDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = noam_decay(lr_sheduler.d_model, lr_sheduler.warmup_steps, + 1.0) + lr_name = lr.name + logging.warn("NoamDecay is set, warmup steps is [ %d ]" % + lr_sheduler.warmup_steps) + elif isinstance(lr_sheduler, NaturalExpDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = natural_exp_decay(1.0, lr_decay_steps, lr_sheduler.gamma, + True) + lr_name = lr.name + logging.warn( + "NaturalExpDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + elif isinstance(lr_sheduler, InverseTimeDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = inverse_time_decay(1.0, lr_decay_steps, lr_sheduler.gamma, + True) + lr_name = lr.name + logging.warn( + "InverseTimeDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + else: + raise ValueError( + "Not supported current LearningRate strategy, please use follow decay strategy: {}" + .format(schedler_decay)) + + return decay_main_program, decay_startup_program, lr_name + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + if hasattr(attrs['origin_main_program'], 'lr_sheduler') == False: + return + + assert isinstance(attrs['origin_main_program'].lr_sheduler, + LRScheduler), "must be LRScheduler" + + ops = get_optimize_ops(attrs['origin_main_program']) + lr_decay_main_program, lr_decay_startup_program, lr_name = self._get_lr_sheduler_program( + attrs['origin_main_program'].lr_sheduler, attrs['lr_decay_steps']) + self._add_tensor_table(attrs, "@LR_DECAY_COUNTER@", lr_name, + lr_decay_startup_program, lr_decay_main_program, + "GlobalStepTable") + return + + +@register_pass("add_listen_and_serv_pass") +class AddListenAndServPass(PassBase): + + def __init__(self): + super(AddListenAndServPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + opt = { + "grad_to_block_id": None, + "sparse_grad_to_param": None, + "lr_decay_block_id": None, + "dense_optimize_blocks": None, + "sparse_optimize_blocks": None, + + # runtime attribute + "endpoint": get_ps_endpoint(attrs['role_maker']), + "pserver_id": get_role_id(attrs['role_maker']), + "Fanin": get_trainers(attrs['role_maker']), + "distributed_mode": attrs['ps_mode'], + "rpc_get_thread_num": -1, + "rpc_send_thread_num": -1, + "rpc_prefetch_thread_num": -1 + } + main_program.global_block().append_op(type="listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=opt) + + +@register_pass("add_rpc_global_flags_pass") +class AddRpcGlobalFlagsPass(PassBase): + + def __init__(self): + super(AddRpcGlobalFlagsPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + pass + + +@register_pass("add_optimizer_pass") +class AddOptimizerPass(PassBase): + + def __init__(self): + super(AddOptimizerPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + pass + + +@register_pass("add_geo_optimizer_pass") +class AddGeoOptimizerPass(PassBase): + + def __init__(self): + super(AddGeoOptimizerPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + pass + + +@register_pass("build_pserver_startup_program_pass") +class BuildPserverStartupProgramPass(PassBase): + + def __init__(self): + super(BuildPserverStartupProgramPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + pass + + +@register_pass("delete_unused_in_startup_pass") +class DeleteUnusedInStartupPass(PassBase): + + def __init__(self): + super(DeleteUnusedInStartupPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_trainer_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_trainer_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..466730ae1a56f633f24cfe8fb374a17e88db1af8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/passes/ps_trainer_pass.py @@ -0,0 +1,1504 @@ +# Copyright (c) 2022 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. + +import os +import paddle +import paddle.compat as cpt +from ..ps.utils.public import * +from paddle.framework import core +from paddle.distributed.passes.pass_base import PassBase, register_pass +from paddle.fluid.transpiler.details.program_utils import delete_ops +from paddle.fluid.transpiler.collective import SingleProcessMultiThread +from _collections import deque, defaultdict +from paddle.fluid.framework import Program, Parameter + + +@register_pass("append_send_ops_pass") +class AppendSendOpsPass(PassBase): # 该 pass 被多种模式复用 + + def __init__(self): + super(AppendSendOpsPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _append_send_op(self, program, union_vars, queue, is_sparse, table_id, + ps_mode): + if queue == STEP_COUNTER: + send_input_vars = [] + else: + send_input_vars = [ + program.global_block().vars[union_var] + for union_var in union_vars + ] + + dummy_output = [] + if ps_mode in [DistributedMode.SYNC, DistributedMode.HALF_ASYNC]: + dummy_output = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + program.global_block().append_op(type="send", + inputs={"X": send_input_vars}, + outputs={"Out": dummy_output}, + attrs={ + "send_varnames": [queue], + "is_sparse": + is_sparse, + "table_id": + table_id, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + return dummy_output + + def _append_barrier_op(self, program, dummys, trainer_id): + program.global_block().append_op(type="send_barrier", + inputs={"X": dummys}, + outputs={"Out": []}, + attrs={ + "trainer_id": + trainer_id, + "half_async": + True, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + ps_mode = attrs['ps_mode'] + #if ps_mode == DistributedMode.GEO: + # send_ctx = get_geo_trainer_send_context(attrs) # geo 模式, 没必要 + send_ctx = get_the_one_send_context( + attrs, + split_dense_table=attrs['is_heter_ps_mode']) # async、sync 等各种模式 + + dummys = [] + for merged_name, send in send_ctx.items(): # embedding_0.w_0@GRAD + if send.is_sparse() and ps_mode != DistributedMode.GEO: + continue + if (not send.is_sparse()) and ps_mode == DistributedMode.GEO: + continue + if send.program_id() != id(attrs['loss'].block.program): + continue + if len(send.remote_sparse_ids()) > 0: + continue + is_sparse = 1 if send.is_sparse() else 0 + is_sparse = 2 if send.is_distributed() else is_sparse + dummys.append( + self._append_send_op(main_program, send.origin_varnames(), + merged_name, is_sparse, send.table_id(), + ps_mode)) + if ps_mode in [DistributedMode.SYNC, DistributedMode.HALF_ASYNC]: + trainer_id = get_role_id(attrs['role_maker']) + self._append_barrier_op(main_program, dummys, trainer_id) + + +@register_pass("distributed_ops_pass") +class DistributedOpsPass(PassBase): + + def __init__(self): + super(DistributedOpsPass, self).__init__() + self.w_2_table_id = {} + self.emb_size = {} + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _push_sparse_fuse(self, _program, push_sparse_ops, attrs, use_cvm_op): + if attrs['use_ps_gpu']: + return + if len(push_sparse_ops) == 0: + return + show = None + clk = None + use_entry = False + for param, ops in push_sparse_ops.items(): + op_first = ops[0] + break + if op_first.has_attr("entry"): + entry = op_first.attr("entry") + entry = entry.split(':') + if len(entry) == 3 and entry[0] == 'show_click_entry': + show_var_name = entry[1] + click_var_name = entry[2] + if show_var_name in _program.global_block( + ).vars and click_var_name in _program.global_block().vars: + show = _program.global_block().vars[show_var_name] + clk = _program.global_block().vars[click_var_name] + use_entry = True + else: + warnings.warn( + 'ShowClickEntry configured, but cannot find show/click var, will not use' + ) + + if not use_entry: + print('ShowClickEntry not configured, will not use') + show = _program.global_block().create_var( + name="show", + dtype=core.VarDesc.VarType.FP32, + persistable=False, + stop_gradient=True) + _program.global_block()._insert_op(index=0, + type='fill_constant', + inputs={}, + outputs={'Out': show}, + attrs={ + 'shape': [1], + 'dtype': show.dtype, + 'value': 1, + }) + + clk = _program.global_block().create_var( + name="clk", + dtype=core.VarDesc.VarType.FP32, + persistable=False, + stop_gradient=True) + _program.global_block()._insert_op(index=0, + type='fill_constant', + inputs={}, + outputs={'Out': clk}, + attrs={ + 'shape': [1], + 'dtype': clk.dtype, + 'value': 0, + }) + + for param, ops in push_sparse_ops.items(): + all_ops = _program.global_block().ops + op_idxs = [all_ops.index(op) for op in ops] + inputs = [ + _program.global_block().vars[op.input("Ids")[0]] for op in ops + ] + w = _program.global_block().vars[ops[0].output("W@GRAD")[0]] + table_id = self.w_2_table_id[param] + + padding_idx = ops[0].attr("padding_idx") + is_distributed = ops[0].attr("is_distributed") + op_type = ops[0].type + + slots = [op.attr("slot") for op in ops] + print('debug zcb slots: ', slots) + outputs = [ + _program.global_block().vars[op.input("Out@GRAD")[0]] + for op in ops + ] + + for idx in op_idxs[::-1]: + _program.global_block()._remove_op(idx) + + _program.global_block().append_op(type="distributed_push_sparse", + inputs={ + "Ids": inputs, + 'W': w, + "Outputs": outputs, + "Shows": show, + "Clicks": clk, + }, + outputs={"Outputs": outputs}, + attrs={ + "is_distributed": + is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "size": self.emb_size[param], + "use_cvm_op": use_cvm_op, + "slots": slots + }) + + def _pull_sparse_fuse(self, _program, pull_sparse_ops, attrs, send_ctx): + + def dag_check_up_and_reorder(program, inputs, outputs): + global_block = program.global_block() + min_output_index = len(global_block.ops) + max_input_index = -1 + input_indexes = [0] * len(global_block.ops) + output_indexes = [0] * len(global_block.ops) + for idx, op in enumerate(global_block.ops): + for i in range(0, len(op.output_names)): + if input_indexes[idx] == 1: + break + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + input_indexes[idx] = 1 + max_input_index = max(max_input_index, idx) + break + + for i in range(0, len(op.input_names)): + if output_indexes[idx] == 1: + break + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + output_indexes[idx] = 1 + min_output_index = min(min_output_index, idx) + + for i in range(len(global_block.ops)): + if input_indexes[i] == 1 and output_indexes[i] == 1: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops because a op both needs embedding table's output as input and produces ids as the same embedding table's input" + ) + return + + if min_output_index < max_input_index: + move_ops = [] + for i in range(min_output_index + 1, len(input_indexes)): + if input_indexes[i] == 1: + move_ops.append((global_block.ops[i], i)) + for i, op in enumerate(move_ops): + queue = list() + visited = set() + queue.append(op[1]) + visited.add(op[0]) + start = 0 + while start < len(queue): + pos = queue[start] + op = global_block.ops[pos] + op_inputs = [] + for k in range(0, len(op.input_names)): + ins = op.input(op.input_names[k]) + op_inputs.append(ins) + for j in range(pos - 1, min_output_index - 1, -1): + op1 = global_block.ops[j] + if op1 in visited: + continue + found = False + for k in range(0, len(op1.output_names)): + outs = op1.output(op1.output_names[k]) + for t in range(len(op_inputs)): + for y in op_inputs[t]: + if y in outs: + found = True + break + if found: + break + if found: + break + if found: + if output_indexes[j] == True: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops" + ) + return + queue.append(j) + visited.add(global_block.ops[j]) + start = start + 1 + + queue.sort() + for index in queue: + desc = global_block.desc._insert_op(min_output_index) + desc.copy_from(global_block.ops[index].desc) + global_block.desc._remove_op(index + 1, index + 2) + global_block.ops[index].desc = desc + insert_op = global_block.ops.pop(index) + input_state = input_indexes.pop(index) + output_state = output_indexes.pop(index) + global_block.ops.insert(min_output_index, insert_op) + input_indexes.insert(min_output_index, input_state) + output_indexes.insert(min_output_index, output_state) + min_output_index = min_output_index + 1 + + assert global_block.desc.op_size() == len(global_block.ops) + for i in range(len(global_block.ops)): + assert global_block.desc.op(i) == global_block.ops[i].desc + + if attrs['use_ps_gpu']: + gpups_inputs_idxs = list() + gpups_outputs_idxs = list() + gpups_inputs = list() + gpups_outputs = list() + gpups_w_size = list() + gpups_min_distributed_idx = len(_program.global_block().ops) + 1 + + for param, ops in pull_sparse_ops.items(): + all_ops = _program.global_block().ops + op_device = "" + if attrs['is_heter_ps_mode']: + op_device = ops[0].attr("op_device") + inputs = [ + _program.global_block().vars[op.input("Ids")[0]] for op in ops + ] + w = _program.global_block().vars[ops[0].input("W")[0]] + self.emb_size[param] = w.shape[1] + + grad_name = attrs['param_name_to_grad_name'][w.name] + + table_id = -1 + + for name, ctx in send_ctx.items(): + if grad_name in ctx.origin_varnames(): + table_id = ctx.table_id() + + if table_id == -1: + raise ValueError( + "can not find suitable sparse table, please check") + + self.w_2_table_id[param] = table_id + padding_idx = ops[0].attr("padding_idx") + is_distributed = ops[0].attr("is_distributed") + op_type = ops[0].type + + outputs = [ + _program.global_block().vars[op.output("Out")[0]] for op in ops + ] + + dag_check_up_and_reorder(_program, inputs, outputs) + + op_idxs = [all_ops.index(op) for op in ops] + + for idx in op_idxs[::-1]: + _program.global_block()._remove_op(idx) + + inputs_idxs = [-1] * len(inputs) + outputs_idxs = [len(_program.global_block().ops) + 1] * len(outputs) + + for idx, op in enumerate(_program.global_block().ops): + for i in range(0, len(op.output_names)): + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + inputs_idxs[in_id] = max(idx, inputs_idxs[in_id]) + for i in range(0, len(op.input_names)): + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + outputs_idxs[out_id] = min(idx, + outputs_idxs[out_id]) + + if attrs['use_ps_gpu']: + gpups_inputs_idxs.extend(inputs_idxs) + gpups_outputs_idxs.extend(outputs_idxs) + gpups_inputs.extend(inputs) + gpups_outputs.extend(outputs) + gpups_w_size.extend([w.shape[1]] * len(inputs)) + gpups_min_distributed_idx = min(min(op_idxs), + gpups_min_distributed_idx) + continue + + if min(outputs_idxs) - max(inputs_idxs) >= 1: + if max(inputs_idxs) == -1: + distributed_idx = min(op_idxs) + else: + distributed_idx = max(inputs_idxs) + 1 + + _program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": inputs, + 'W': w + }, + outputs={"Outputs": outputs}, + attrs={ + "is_distributed": is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "lookup_table_version": op_type, + "op_device": op_device + }) + else: + for i in range(len(inputs_idxs)): + distributed_idx = op_idxs[i] + + _program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": [inputs[i]], + 'W': w + }, + outputs={"Outputs": [outputs[i]]}, + attrs={ + "is_distributed": is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "lookup_table_version": op_type, + "op_device": op_device + }) + + if attrs['use_ps_gpu'] and len(gpups_inputs) > 0: + if max(gpups_inputs_idxs) > 0: + raise ValueError("There can't be ops before embedding in gpups") + + _program.global_block()._insert_op(index=gpups_min_distributed_idx, + type="pull_gpups_sparse", + inputs={ + "Ids": gpups_inputs, + }, + outputs={"Out": gpups_outputs}, + attrs={ + "size": gpups_w_size, + "is_distributed": True, + "is_sparse": True + }) + PSGPU = paddle.fluid.core.PSGPU() + try: + gpu_slot = [int(var.name) for var in gpups_inputs] + except (ValueError): + raise ValueError( + "The slot name in gpups Should be able to convert to integer." + ) + PSGPU.set_slot_vector(gpu_slot) + gpu_mf_sizes = [x - 3 for x in gpups_w_size] + PSGPU.set_slot_dim_vector(gpu_mf_sizes) + + def _get_pull_sparse_ops(self, _program, attrs): + pull_sparse_ops = {} + pull_sparse_ids = {} + push_sparse_ops = {} + ops = {} + use_cvm_op = False + for op in _program.global_block().ops: + if op.type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0] + if attrs['is_heter_ps_mode'] and not attrs['is_fl_ps_mode']: + # TODO: trick for matchnet, need to modify for heter_ps + param_name += op.input("Ids")[0][0] + if param_name in attrs['local_sparse']: # for recall/ncf model + continue + ops = pull_sparse_ops.get(param_name, []) + ops.append(op) + pull_sparse_ops[param_name] = ops + ids = pull_sparse_ids.get(param_name, []) + ids.append(op.input("Ids")[0]) + pull_sparse_ids[param_name] = ids + if op.type == 'cvm': + use_cvm_op = True + + for op in _program.global_block().ops: + if op.type in SPARSE_GRAD_OP_TYPE_DICT.keys(): + param_name = op.input(SPARSE_GRAD_OP_TYPE_DICT[op.type])[0] + if param_name in pull_sparse_ids and op.input( + "Ids")[0] in pull_sparse_ids[param_name]: + ops = push_sparse_ops.get(param_name, []) + ops.append(op) + push_sparse_ops[param_name] = ops + + return pull_sparse_ops, push_sparse_ops, use_cvm_op + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + pull_sparse_ops, push_sparse_ops, use_cvm_op = self._get_pull_sparse_ops( + main_program, attrs) + print("is_heter_ps_mode in distributed_ops_pass {}?".format( + attrs['is_heter_ps_mode'])) + send_ctx = get_the_one_send_context( + attrs, split_dense_table=attrs['is_heter_ps_mode']) + self._pull_sparse_fuse(main_program, pull_sparse_ops, attrs, send_ctx) + self._push_sparse_fuse(main_program, push_sparse_ops, attrs, use_cvm_op) + + +@register_pass("delete_optimizer_pass") +class DeleteOptimizesPass(PassBase): + + def __init__(self): + super(DeleteOptimizesPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _delete_optimizer_op_and_vars(self, _program, remote_optimize_ops, + local_optimize_ops): + local_optimize_vars = [] + remote_optimize_vars = [] + remote_optimize_op_role_vars = [] + optimize_need_delete_vars = [] + + for op in local_optimize_ops: + local_optimize_vars.extend(op.input_arg_names) + + for op in remote_optimize_ops: + remote_optimize_vars.extend(op.input_arg_names) + remote_optimize_op_role_vars.extend(op.attr("op_role_var")) + + remote_optimize_vars = list( + set(remote_optimize_vars + )) # param + grad + optimizer_state + learning_rate + remote_optimize_op_role_vars = list( + set(remote_optimize_op_role_vars)) # param + grad + print( + "remote_optimize_vars: {}, remote_optimize_op_role_vars: {}, local_optimize_vars: {}" + .format(remote_optimize_vars, remote_optimize_op_role_vars, + local_optimize_vars)) + for var in remote_optimize_vars: + if var in local_optimize_vars: + continue + if var not in remote_optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + delete_ops(_program.global_block(), remote_optimize_ops) + for var in need_delete_optimize_vars: + if _program.global_block().has_var(var): + _program.global_block()._remove_var(var) + + def _add_lr_var(self, main_program, attrs): + # Todo: hard code for pe + lr_var = attrs['origin_main_program'].global_block( + ).vars["learning_rate_0"] + main_program.global_block().create_var(name=lr_var.name, + shape=lr_var.shape, + dtype=lr_var.dtype, + type=lr_var.type, + lod_level=lr_var.lod_level, + persistable=True) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + all_optimize_ops = get_optimize_ops(main_program) + remote_optimize_ops = get_optimize_ops(main_program, + attrs['remote_sparse']) + lr_ops = get_lr_ops(main_program) + remote_optimize_ops.extend(lr_ops) + local_optimize_ops = list( + set(all_optimize_ops) - set(remote_optimize_ops)) + self._delete_optimizer_op_and_vars(main_program, remote_optimize_ops, + local_optimize_ops) + + if hasattr(attrs['origin_main_program'], 'lr_sheduler'): + self._add_lr_var(main_program, attrs) + + +@register_pass("delete_extra_optimizer_pass") +class DeleteExtraOptimizerPass(PassBase): + + def __init__(self): + super(DeleteExtraOptimizerPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + remote_optimize_vars = [] + remote_optimize_op_role_vars = [] + optimize_need_delete_vars = [] + all_optimize_ops = get_optimize_ops(main_program) + remote_optimize_ops = get_optimize_ops(main_program, + attrs['remote_sparse']) + local_optimize_ops = list( + set(all_optimize_ops) - set(remote_optimize_ops)) + + local_optimize_vars = [] + for op in local_optimize_ops: + local_optimize_vars.extend(op.input_arg_names) + + for op in remote_optimize_ops: + remote_optimize_vars.extend(op.input_arg_names) + remote_optimize_op_role_vars.extend(op.attr("op_role_var")) + + remote_optimize_vars = list(set(remote_optimize_vars)) + remote_optimize_op_role_vars = list(set(remote_optimize_op_role_vars)) + for var in remote_optimize_vars: + if var in local_optimize_vars: + continue + if 'learning_rate_0' == var: + continue + if var not in remote_optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + init_ops = [] + for var in need_delete_optimize_vars: + param_init_op = [] + for op in startup_program.global_block().ops: + if var in op.output_arg_names: + param_init_op.append(op) + init_ops.extend(param_init_op) + delete_ops(startup_program.global_block(), init_ops) + + for var in need_delete_optimize_vars: + if startup_program.global_block().has_var(var): + startup_program.global_block()._remove_var(var) + + +@register_pass("fake_init_ops_pass") +class FakeInitOpsPass(PassBase): + + def __init__(self): + super(FakeInitOpsPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _get_sparse_table_names(self, attrs): + dist_varnames = get_sparse_tablenames(attrs['origin_main_programs'], + True) + sparse_varnames = get_sparse_tablenames(attrs['origin_main_programs'], + False) + return list(set(dist_varnames + sparse_varnames)) + + def _fake_init_sparsetable(self, startup_program, sparse_table_names, + attrs): + # delete table init op + for table_name in sparse_table_names: + table_var = startup_program.global_block().vars[table_name] + if str(table_var).split( + ":")[0].strip().split()[-1] in attrs['local_sparse']: + continue + table_param_init_op = [] + for op in startup_program.global_block().ops: + if table_name in op.output_arg_names: + table_param_init_op.append(op) + init_op_num = len(table_param_init_op) + if init_op_num != 1: + raise ValueError("table init op num should be 1, now is " + + str(init_op_num)) + table_init_op = table_param_init_op[0] + startup_program.global_block().append_op( + type="fake_init", + inputs={}, + outputs={"Out": table_var}, + attrs={"shape": table_init_op.attr('shape')}) + delete_ops(startup_program.global_block(), table_param_init_op) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + sparse_tables = self._get_sparse_table_names(attrs) + self._fake_init_sparsetable(startup_program, sparse_tables, attrs) + + +@register_pass("ps_gpu_pass") +class PsGpuPass(PassBase): + + def __init__(self): + super(PsGpuPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _add_push_box_sparse_op(self, program): + insert_index = -1 + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "lookup_table_grad": + insert_index = idx + for op in program.global_block().ops: + if op.type != "pull_box_sparse" and op.type != "pull_gpups_sparse": + continue + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op.desc, cpt.to_text(set()), []) + for op_desc in grad_op_desc: + new_op_desc = program.global_block().desc._insert_op( + insert_index + 1) + new_op_desc.copy_from(op_desc) + new_op_desc._set_attr(op_role_attr_name, backward) + new_op = paddle.fluid.framework.Operator( + program.global_block(), new_op_desc) + program.global_block().ops.insert(insert_index + 1, new_op) + program.global_block()._sync_with_cpp() + + def _remove_optimizer_var(self, program): + embedding_w = {} + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "lookup_table_grad": + for name in op.input("W"): + embedding_w[name] = 1 + + optimize_vars = [] + optimize_op_role_vars = [] + optimize_need_delete_vars = [] + for op in get_optimize_ops(program): + for name in op.input("Param"): + if name in embedding_w: + optimize_op_role_vars.extend(op.attr("op_role_var")) + for key_name in op.input_names: + if key_name == "LearningRate": + continue + for var in op.input(key_name): + optimize_vars.append(var) + + optimize_vars = list(set(optimize_vars)) + optimize_op_role_vars = list(set(optimize_op_role_vars)) + + for var in optimize_vars: + if var not in optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + for name in need_delete_optimize_vars: + if program.global_block().has_var(name): + program.global_block()._remove_var(name) + + def _remove_lookup_table_grad_op_and_var(self, program): + lookup_table_grad_var = {} + remove_op_index = [] + remove_var = [] + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "lookup_table_grad": + for name in op.output("W@GRAD"): + lookup_table_grad_var[name] = 1 + remove_op_index.append(idx) + remove_var.append(name) + for name in op.input("W"): + lookup_table_grad_var[name] = 1 + + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "pull_box_sparse" or op.type == "pull_gpups_sparse": + continue + for key_name in op.input_names: + for var in op.input(key_name): + if var in lookup_table_grad_var: + remove_op_index.append(idx) + break + + remove_op_index = list(set(remove_op_index)) + remove_op_index.sort(reverse=True) + for idx in remove_op_index: + program.global_block()._remove_op(idx) + for name in remove_var: + program.global_block()._remove_var(name) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + self._add_push_box_sparse_op(main_program) + self._remove_optimizer_var(main_program) + self._remove_lookup_table_grad_op_and_var(main_program) + + +@register_pass("ps_transpile_pass") +class PsTranspilePass(PassBase): + + def __init__(self): + super(PsTranspilePass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + t = SingleProcessMultiThread() + env = get_dist_env() + t.transpile(startup_program=startup_program, + main_program=main_program, + rank=env["trainer_id"], + endpoints=env["trainer_endpoints"], + current_endpoint=env['current_endpoint'], + wait_port=False) + + +@register_pass("split_heter_worker_ops_pass") +class SplitHeterWorkerOpsPass(PassBase): + + def __init__(self): + super(SplitHeterWorkerOpsPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _create_heter_program(self, program, attrs, heter_program, + program_block_ops_list, heter_ops, + block_var_detail): + # This function mainly includes the following contents: + # 1. For every heter block: + # a) copy heter device op from origin program + # b) create variables which belong to heter op: + # -> if variable is persistable, clone it in global_scope + # -> if variable is temp, create it in heter block + # c) create communicate related op as follow: + # joint_var.0_1 -> slice -> reshape -> origin_var + # origin_var -> origin_program + # reshape -> concat -> joint_var.1_2 + # d) copy send op from origin program for var@grad which loacted in current heter block + # e) re-check every op in current blcok if its device is not current heter devie + # 2. Create send op for step counter in last heter-block + # 3. Create Listen&Serv OP and Send&Recv OP for distributed training + # 4. update CompileTimeStrategy for heter_program + + optimizer_block = [] + grad_to_block_id = [] + send_grad_var_list = [] + + pre_block_idx = heter_program.num_blocks - 1 + role_maker = attrs['role_maker'] + current_device = role_maker._heter_device_type().lower() + stage_id = int(role_maker._get_stage_id()) + + heter_block_ops_forward = program_block_ops_list[stage_id - + 1]["forward"] + heter_block_ops_backward = program_block_ops_list[stage_id - + 1]["backward"] + + heter_block = heter_program._create_block(pre_block_idx) + optimizer_block.append(heter_block) + for _, op in enumerate(heter_block_ops_forward): + block_append_op(heter_program, program, heter_block, op) + + entrance_vars = block_var_detail[stage_id - 1]["forward"]["entrance"] + add_vars_by_var_list(entrance_vars, program, heter_program, heter_block) + exit_vars = block_var_detail[stage_id - 1]["forward"]["exit"] + add_vars_by_var_list(exit_vars, program, heter_program, heter_block) + + first_op_index_fp = len(heter_block.ops) + + if stage_id < len(program_block_ops_list): + + heter_block_bp = heter_program._create_block(pre_block_idx) + optimizer_block.append(heter_block_bp) + + for _, op in enumerate(heter_block_ops_backward): + block_append_op(heter_program, program, heter_block_bp, op) + + bp_entrance_vars = block_var_detail[stage_id - + 1]["backward"]["entrance"] + add_vars_by_var_list(bp_entrance_vars, program, heter_program, + heter_block_bp) + bp_exit_vars = block_var_detail[stage_id - 1]["backward"]["exit"] + add_vars_by_var_list(bp_exit_vars, program, heter_program, + heter_block_bp) + backward_comm_info = get_communicate_var_info(program, + stage_id, + bp_entrance_vars, + type="backward") + + grad_to_block_id.append(backward_comm_info["block_input_var_name"] + + ":" + str(heter_block_bp.idx)) + + else: + for _, op in enumerate(heter_block_ops_backward): + block_append_op(heter_program, program, heter_block, op) + + bp_entrance_vars = block_var_detail[stage_id - + 1]["backward"]["entrance"] + add_vars_by_var_list(bp_entrance_vars, program, heter_program, + heter_block) + bp_exit_vars = block_var_detail[stage_id - 1]["backward"]["exit"] + add_vars_by_var_list(bp_exit_vars, program, heter_program, + heter_block) + + heter_block_bp = heter_block + + forward_comm_info = get_communicate_var_info(program, + stage_id, + entrance_vars, + type="forward") + + grad_to_block_id.append(forward_comm_info["block_input_var_name"] + + ":" + str(heter_block.idx)) + + first_op_index_bp = len(heter_block_bp.ops) + + if stage_id <= len(block_var_detail) - 1: + static_var = insert_communicate_op(program, role_maker, heter_block, + stage_id, first_op_index_fp, + block_var_detail, current_device) + static_var_bp = insert_communicate_op(program, role_maker, + heter_block_bp, stage_id, + first_op_index_bp, + block_var_detail, current_device, + False) + + # add send op + send_grad_var_list = add_send_op( + program, heter_block_bp, + block_var_detail[stage_id - 1]["backward"]["persistables"]) + + # add step conter + send_input_vars = [] + dummy_output = [] + pserver_endpoints = get_ps_endpoints(role_maker) + attrs = { + "message_to_block_id": grad_to_block_id, + "optimize_blocks": optimizer_block, + # runtime attribute + "endpoint": get_heter_worker_endpoint(role_maker), + "fanin": len(get_previous_stage_trainers(role_maker)), + "pserver_id": get_role_id(role_maker), + "distributed_mode": attrs['ps_mode'], + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + # append the listen_and_serv op + heter_program.global_block().append_op(type="heter_listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + # TODO check heter program + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + """ + split heter worker program from origin-program + 1. find heter op (located on different device) + 2. find input&output of every heter-block + 3. create heter worker program, add listen&serv op + """ + attrs = pass_ctx._attrs + default_deveice = "cpu" + program, heter_ops, _, program_block_ops = find_heter_ops( + main_program, default_deveice) + if len(heter_ops) == 0: + warnings.warn( + "Currently running in Heter Parameter Server mode, but no OP running on heterogeneous devices, Please check your code." + ) + main_program = program + return + + program_block_ops = union_forward_gradient_op(program_block_ops) + block_vars_detail = find_block_joints(program, program_block_ops, + heter_ops) + heter_program = framework.Program() + self._create_heter_program(program, attrs, heter_program, + program_block_ops, heter_ops, + block_vars_detail) + main_program = heter_program + + +@register_pass("split_trainer_ops_pass") +class SplitTrainerOpsPass(PassBase): + + def __init__(self): + super(SplitTrainerOpsPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _replace_ops_by_communicate_op(self, program, attrs, heter_block_index, + ops_list, block_var_detail): + all_op = program.global_block().ops + start_op = ops_list[0] + first_op_idx = -1 + for op in all_op: + if str(op) == str(start_op): + first_op_idx = all_op.index(op) + break + assert first_op_idx != -1 + delete_same_ops(program.global_block(), ops_list) + + entrance_var = [] + role_maker = attrs['role_maker'] + if heter_block_index == 1: + next_heter_worker_endpoints = get_next_stage_trainers(role_maker) + + entrance_var = block_var_detail[heter_block_index]["forward"][ + "entrance"] + + comm_info = get_communicate_var_info(program, heter_block_index + 1, + entrance_var) + program.global_block()._insert_op( + index=first_op_idx, + type="send_and_recv", + inputs={"X": program.global_block().vars[entrance_var[0]]}, + outputs={"Out": []}, + attrs={ + "mode": "forward", + "send_var_name": entrance_var + ["microbatch_id"], + "recv_var_name": [], + "message_name": comm_info["block_input_var_name"], + "next_endpoints": next_heter_worker_endpoints, + "previous_endpoints": [], + "trainer_id": get_role_id(role_maker), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return entrance_var + + def _remove_var_pair_by_grad(self, var_name, attrs): + for index, pair in enumerate(attrs['merged_variables_pairs']): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del attrs['merged_variables_pairs'][index] + + for index, pair in enumerate(attrs['merged_dense_pairs']): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del attrs['merged_dense_pairs'][index] + return + + for index, pair in enumerate(attrs['merged_sparse_pairs']): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del attrs['merged_sparse_pairs'][index] + return + + def _remove_trainer_send_op(self, program, attrs, heter_block_index, + block_var_detail): + # if trainer do FF->BP->SEND, it has follow vars: var, var@GRAD + # if trainer only do SEND, it has one var: var@GRAD + # Delete Send op ,if trainer doesn't has pair var (var<->var@GRAD) + persistables = block_var_detail[heter_block_index]["forward"]["persistables"] + \ + block_var_detail[heter_block_index]["backward"]["persistables"] + need_remove_send_op = [] + need_remove_grad_var = [] + for op in find_send_op(program): + input_list, _ = find_op_input_output(program, + program.global_block(), op) + for var_name in input_list: + origin_var_name = var_name.split("@GRAD")[0] + if origin_var_name in persistables: + need_remove_send_op.append(op) + need_remove_grad_var.append(var_name) + need_remove_send_op = list(set(need_remove_send_op)) + delete_ops(program.global_block(), need_remove_send_op) + for grad_var_name in need_remove_grad_var: + self._remove_var_pair_by_grad(grad_var_name, attrs) + + def _create_trainer_program(self, program, origin_program, attrs, + program_block_ops_list, block_var_detail): + # This function mainly includes the following contents: + # 1. For every heter block in origin program + # a) delete heter op and related variables + # b) add send&recv op + # c) add communicate ops as follows: + # origin_var -> reshape -> concat -> joint_var.0_1 + # send&recv op(send joint_var.0_1; recv joint_var.1_2) + # joint_var.1_2 -> slice -> reshape -> origin_var + # d) remove send op which related var@grad is not in trainer program + # 2. check every op's device + static_var = [] + for heter_block_index in range(1, len(program_block_ops_list)): + ops_list = program_block_ops_list[heter_block_index][ + "forward"] + program_block_ops_list[heter_block_index][ + "backward"] + static_var += self._replace_ops_by_communicate_op( + program, attrs, heter_block_index, ops_list, block_var_detail) + self._remove_trainer_send_op(program, attrs, heter_block_index, + block_var_detail) + + optimizer_block = [] + grad_to_block_id = [] + + bp_ops_list = program_block_ops_list[0]["backward"] + delete_same_ops(program.global_block(), bp_ops_list) + delete_trainer_useless_var(program, static_var) + backward_block = create_backward_block(program, origin_program, + bp_ops_list, block_var_detail) + + bp_entrance_vars = block_var_detail[0]["backward"]["entrance"] + backward_comm_info = get_communicate_var_info(origin_program, + 1, + bp_entrance_vars, + type="backward") + + grad_to_block_id.append(backward_comm_info["block_input_var_name"] + + ":" + str(backward_block.idx)) + optimizer_block.append(backward_block) + role_maker = attrs['role_maker'] + attrs = { + "message_to_block_id": grad_to_block_id, + "optimize_blocks": optimizer_block, + # runtime attribute + "endpoint": + get_trainer_endpoint(role_maker), ## get trainer endpoint + "fanin": 0, ## get heter worker + "pserver_id": get_role_id(role_maker), + "distributed_mode": attrs['ps_mode'], + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + # append the listen_and_serv op + program.global_block()._insert_op(index=0, + type="heter_listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + + ## TODO add check for bp block + #check_op_device(program.global_block(), DEFAULT_DEVICE) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + """ + split cpu-trainer program from origin-program + 1. find heter op (located on different device) + 2. find input&output of every heter-block + 3. create cpu-trainer program, add send&recv op + """ + attrs = pass_ctx._attrs + default_device_ = 'cpu' + program, heter_ops, default_ops, program_block_ops = find_heter_ops( + main_program, default_device_) + program_block_ops = union_forward_gradient_op(program_block_ops) + + block_vars_detail = find_block_joints(program, program_block_ops, + heter_ops) + trainer_program = program.clone() + self._create_trainer_program(trainer_program, program, attrs, + program_block_ops, block_vars_detail) + main_program = trainer_program + + +@register_pass("set_heter_pipeline_opt_pass") +class SetHeterPipelineOptPass(PassBase): + + def __init__(self): + super(SetHeterPipelineOptPass, self).__init__() + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + role_maker = attrs['role_maker'] + num_microbatches = attrs['user_defined_strategy'].pipeline_configs[ + 'accumulate_steps'] + + startup_program._heter_pipeline_opt = { + "startup_program": startup_program, + "pipeline_stage": int(role_maker._get_stage_id()) - 1, + "heter_place": role_maker._heter_device(), + "is_fl_mode": 1 + } + main_program._heter_pipeline_opt = { + "trainer": "HeterPipelineTrainer", + "device_worker": "HeterSection", + "trainers": + role_maker._get_stage_trainers(), ## trainer num in each stage + "trainer_id": int(role_maker._role_id()), + "pipeline_stage": int(role_maker._get_stage_id()) - 1, + "num_pipeline_stages": int(role_maker._get_num_stage()), + "section_program": main_program, + "num_microbatches": num_microbatches, + "heter_place": role_maker._heter_device(), + "is_fl_mode": 1 + } + + +@register_pass("split_fl_ops_pass") +class SplitFlOpsPass(PassBase): + + def __init__(self): + super(SplitFlOpsPass, self).__init__() + self.PART_A_DEVICE_FlAG = 'gpu:0' + self.PART_A_JOINT_OP_DEVICE_FlAG = 'gpu:2' + self.PART_B_DEVICE_FlAG = 'gpu:1' + self.PART_B_JOINT_OP_DEVICE_FlAG = 'gpu:3' + + def _check_self(self): + return True + + def _check_conflict(self, other_pass): + return True + + def _insert_encrypt_op(self): + pass + + def _insert_decrypt_op(self): + pass + + def _clear_op_device_flag(self, program): + for block in program.blocks: + for op in block.ops: + device = op.attr(OP_DEVICE_KEY) + op._set_attr(OP_DEVICE_KEY, '') if device != '' else None + + def _split_fl_program(self): + self.partA_ops = [] + self.partB_ops = [] + party_program_map = defaultdict(Program) + block = self.ori_main_program.block(0) + for op in block.ops: + device = op.attr(OP_DEVICE_KEY) + if device == self.PART_A_DEVICE_FlAG or device == '' or device == self.PART_A_JOINT_OP_DEVICE_FlAG: + program = party_program_map['a'] + self.partA_ops.append(op) + elif device == self.PART_B_DEVICE_FlAG or device == self.PART_B_JOINT_OP_DEVICE_FlAG: + program = party_program_map['b'] + self.partB_ops.append(op) + op_desc = op.desc + ap_op = program.global_block().desc.append_op() + ap_op.copy_from(op_desc) + ap_op._set_attr(OP_DEVICE_KEY, device) + + for key in ['a', 'b']: + program = party_program_map[key] + program._sync_with_cpp() + + return party_program_map + + def _insert_partA_communicate_op(self, block, idx): + comm_info = "forward_joint_{}_{}@fl_ps".format(1, 2) + block._insert_op( + idx, + type='send_and_recv', + inputs={'X': self.partA_to_partB_tensor}, + outputs={'Out': []}, + attrs={ + 'mode': 'forward', # mode 直接关联前向和反向 channel 选择 + 'send_var_name': + self.partA_to_partB_tensor_name + ["microbatch_id"], + 'recv_var_name': [], + 'message_name': comm_info, + 'next_endpoints': + get_next_stage_trainers(self.role_maker), # partB_endpoints + 'previous_endpoints': + get_previous_stage_trainers(self.role_maker), + 'trainer_id': get_role_id(self.role_maker), # global id + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + return + + def _insert_partB_communicate_op(self, block, idx): + comm_info = ("backward_joint_{}_{}@fl_ps".format(2, 1)) + block._insert_op( + idx, + type='send_and_recv', + inputs={'X': self.partB_to_partA_grad}, + outputs={'Out': []}, + attrs={ + 'mode': 'backward', + 'send_var_name': + self.partB_to_partA_grad_name + ["microbatch_id"], + 'recv_var_name': [], + 'message_name': comm_info, + 'next_endpoints': + get_next_stage_trainers(self.role_maker), # partA_endpoints + 'previous_endpoints': + get_previous_stage_trainers(self.role_maker), + 'trainer_id': get_role_id(self.role_maker), # global id + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + return + + def _create_var_for_block(self, vars, block): + for var in vars: + if block._find_var_recursive(str(var)): + continue + source_var = self.ori_main_block._var_recursive(str(var)) + if isinstance(var, Parameter): + dest_var = block.create_parameter( + name=source_var.name, + shape=source_var.shape, + dtype=source_var.dtype, + type=source_var.type, + lod_level=source_var.lod_level, + stop_gradient=source_var.stop_gradient, + trainable=source_var.trainable, + optimize_attr=source_var.optimize_attr, + regularizer=source_var.regularizer, + error_clip=source_var.error_clip) + else: + dest_var = block._clone_variable(source_var, False) + dest_var.stop_gradient = source_var.stop_gradient + if hasattr(source_var, 'is_distributed'): + dest_var.is_distributed = source_var.is_distributed + + def _get_block_by_idx(self, op_list, program, block_idx): + if block_idx < len(program.blocks): + new_block = program.block(block_idx) + else: + new_block = program._create_block() + for _, op in enumerate(op_list): + ap_op = new_block.desc.append_op() + ap_op.copy_from(op.desc) + ap_op._set_attr(OP_DEVICE_KEY, op.attr(OP_DEVICE_KEY)) + vars = op.desc.input_arg_names() + op.desc.output_arg_names() + self._create_var_for_block(vars, new_block) + new_block._sync_with_cpp() + return new_block + + def _find_joint_forward_op(self, block, flag): + op_idx = 0 + for op in block.ops: + if is_forward_op(op) and op.attr(OP_DEVICE_KEY) == flag: + return op_idx + else: + op_idx += 1 + return op_idx + + def _find_joint_backward_op(self, block, flag): + op_idx = 0 + for op in block.ops: + if is_backward_op(op) and op.attr(OP_DEVICE_KEY) == flag: + return op_idx + else: + op_idx += 1 + return op_idx + + def _get_partB_to_partA_grad(self, block, flag): + op_idx = self._find_joint_backward_op(block, flag) + op = block.ops[op_idx] + vars1 = op.desc.input_arg_names() + op_idx = self._find_joint_forward_op(block, flag) + op = block.ops[op_idx] + vars2 = op.desc.output_arg_names() + self.partB_to_partA_grad_name = list(set(vars1) - set(vars2)) + self.partB_to_partA_grad = [] + for var_name in self.partB_to_partA_grad_name: + self.partB_to_partA_grad.append(self.ori_main_block.var(var_name)) + + def _find_dense_grad_vars(self, bp_op_list): + program = self.ori_main_program + bp_op_input, bp_op_output = find_ops_list_input_output( + program, bp_op_list) + return (screen_persistables(program, bp_op_input) + + screen_persistables(program, bp_op_output)) + + def _get_partA_program(self, block): + # 1. create block 0 + # 1.1 insert send op + op_idx = self._find_joint_forward_op(block, + self.PART_A_JOINT_OP_DEVICE_FlAG) + op_list = [] + for i in range(len(block.ops)): + op = block.ops[i] + op_list.append(op) + if i == op_idx: + out_name = op.desc.output_arg_names()[0] + self.partA_to_partB_tensor_name = op.desc.output_arg_names() + self.partA_to_partB_tensor = self.ori_main_block.var(out_name) + break + first_block = self._get_block_by_idx(op_list, self.partA_program, 0) + self._insert_partA_communicate_op(first_block, op_idx + 1) + # logger.info('partA-first_block:{}'.format(first_block)) + + # 2. create block 1 + bp_op_list = get_bp_op_list(block) + push_sparse_op_list = get_distributed_push_sparse_op_list(block) + # logger.info('bp_op_list: {}'.format(bp_op_list)) + second_block = self._get_block_by_idx(bp_op_list + push_sparse_op_list, + self.partA_program, 1) + # 2.1. insert partA recv op + block_input_flag = "backward_joint_{}_{}@fl_ps".format(2, 1) + grad_to_block_id = block_input_flag + ":" + str(second_block.idx) + attrs = { + "message_to_block_id": [grad_to_block_id], + "optimize_blocks": [second_block], + "endpoint": get_trainer_endpoint(self.role_maker), ## + "fanin": 0, + "pserver_id": get_role_id(self.role_maker), + "distributed_mode": self.ps_mode, + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + second_block._insert_op(index=0, + type='heter_listen_and_serv', + inputs={'X': []}, + outputs={}, + attrs=attrs) + # 2.2 insert push dense grad op + send_ops = find_send_op(self.ori_main_program) # push dense + delete_same_ops(block, send_ops) + dense_grad_vars = self._find_dense_grad_vars(bp_op_list) + add_send_op(self.ori_main_program, second_block, dense_grad_vars) + # logger.info('partA-second_block:{}'.format(second_block)) + + def _get_partB_program(self, block): + op_idx1 = self._find_joint_forward_op( + block, self.PART_B_JOINT_OP_DEVICE_FlAG) # elementwise_add op + op_idx2 = self._find_joint_backward_op(block, + self.PART_B_JOINT_OP_DEVICE_FlAG) + op_cnt = 0 + op_list1 = [] + op_list2 = [] + op_list3 = [] + for op in block.ops: + if op_cnt < op_idx1: + op_list1.append(op) + elif op_cnt <= op_idx2: + op_list2.append(op) + else: + op_list3.append(op) + op_cnt += 1 + + # 1. create block 0 + first_block = self._get_block_by_idx(op_list1, self.partB_program, 0) + + # 2. create block 1 + second_block = self._get_block_by_idx(op_list2, self.partB_program, 1) + # 2.1 insert send op + self._insert_partB_communicate_op(second_block, len(op_list2)) + # 2.2 insert remain ops + second_block = self._get_block_by_idx(op_list3, self.partB_program, 1) + # 2.3 insert push dense grad op + bp_op_list = get_bp_op_list(second_block) + dense_grad_vars = self._find_dense_grad_vars(bp_op_list) + add_send_op(self.ori_main_program, second_block, dense_grad_vars) + + # 3. insert partB recv op + block_input_flag = "forward_joint_{}_{}@fl_ps".format(1, 2) + grad_to_block_id = block_input_flag + ":" + str(second_block.idx) + attrs = { + "message_to_block_id": [grad_to_block_id], + "optimize_blocks": [second_block], ## what to do? + "endpoint": get_heter_worker_endpoint(self.role_maker), + "fanin": len(get_previous_stage_trainers(self.role_maker)), + "pserver_id": 1, # TODO + "distributed_mode": self.ps_mode, + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + first_block._insert_op(index=len(op_list1), + type="heter_listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + + #logger.info('partB-first_block:{}'.format(first_block)) + #logger.info('partB-second_block:{}'.format(second_block)) + + def _apply_single_impl(self, main_program, startup_program, pass_ctx): + attrs = pass_ctx._attrs + self.role_maker = attrs['role_maker'] + self.ps_mode = attrs['ps_mode'] + self.is_part_b = attrs['is_heter_worker'] # TODO + self.ori_main_program = main_program + self.ori_main_block = main_program.block(0) + + party_program_map = self._split_fl_program() + + prog_a = party_program_map['a'] + _main_file = ps_log_root_dir + '6_fl_A_main_program.prototxt' + debug_program(_main_file, prog_a) + self._get_partB_to_partA_grad(prog_a.global_block(), + self.PART_A_JOINT_OP_DEVICE_FlAG) + + prog_b = party_program_map['b'] + _main_file = ps_log_root_dir + '6_fl_B_main_program.prototxt' + debug_program(_main_file, prog_b) + + if not self.is_part_b: + self.partA_program = framework.Program() + self._get_partA_program(prog_a.global_block()) + pass_ctx._attrs['part_a_main_program'] = self.partA_program + self._clear_op_device_flag(self.partA_program) + check_program(self.partA_program) + else: + self.partB_program = framework.Program() + self._get_partB_program(prog_b.global_block()) + pass_ctx._attrs['part_b_main_program'] = self.partB_program + self._clear_op_device_flag(self.partB_program) + check_program(self.partB_program) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/coordinator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..a012f338a514fb0e30d37ce5d9201996de584888 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/coordinator.py @@ -0,0 +1,354 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.communicator import FLCommunicator +from paddle.distributed.fleet.proto import the_one_ps_pb2 +from google.protobuf import text_format +from paddle.distributed.ps.utils.public import is_distributed_env +from paddle.distributed import fleet +import time +import abc +import os +import logging + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +formatter = logging.Formatter( + fmt='%(asctime)s %(levelname)-2s [%(filename)s:%(lineno)d] %(message)s') +ch = logging.StreamHandler() +ch.setFormatter(formatter) +logger.addHandler(ch) + + +class ClientInfoAttr: + CLIENT_ID = 0 + DEVICE_TYPE = 1 + COMPUTE_CAPACITY = 2 + BANDWIDTH = 3 + + +class FLStrategy: + JOIN = 0 + WAIT = 1 + FINISH = 2 + + +class ClientSelectorBase(abc.ABC): + + def __init__(self, fl_clients_info_mp): + self.fl_clients_info_mp = fl_clients_info_mp + self.clients_info = {} + self.fl_strategy = {} + + def parse_from_string(self): + if not self.fl_clients_info_mp: + logger.warning("fl-ps > fl_clients_info_mp is null!") + + for client_id, info in self.fl_clients_info_mp.items(): + self.fl_client_info_desc = the_one_ps_pb2.FLClientInfo() + text_format.Parse(bytes(info, encoding="utf8"), + self.fl_client_info_desc) + self.clients_info[client_id] = {} + self.clients_info[client_id][ + ClientInfoAttr. + DEVICE_TYPE] = self.fl_client_info_desc.device_type + self.clients_info[client_id][ + ClientInfoAttr. + COMPUTE_CAPACITY] = self.fl_client_info_desc.compute_capacity + self.clients_info[client_id][ + ClientInfoAttr.BANDWIDTH] = self.fl_client_info_desc.bandwidth + + @abc.abstractmethod + def select(self): + pass + + +class ClientSelector(ClientSelectorBase): + + def __init__(self, fl_clients_info_mp): + super().__init__(fl_clients_info_mp) + self.__fl_strategy = {} + + def select(self): + self.parse_from_string() + for client_id in self.clients_info: + logger.info("fl-ps > client {} info : {}".format( + client_id, self.clients_info[client_id])) + # ......... to implement ...... # + fl_strategy_desc = the_one_ps_pb2.FLStrategy() + fl_strategy_desc.iteration_num = 99 + fl_strategy_desc.client_id = 0 + fl_strategy_desc.next_state = "JOIN" + str_msg = text_format.MessageToString(fl_strategy_desc) + self.__fl_strategy[client_id] = str_msg + return self.__fl_strategy + + +class FLClientBase(abc.ABC): + + def __init__(self): + pass + + def set_basic_config(self, role_maker, config, metrics): + self.role_maker = role_maker + self.config = config + self.total_train_epoch = int(self.config.get("runner.epochs")) + self.train_statical_info = dict() + self.train_statical_info['speed'] = [] + self.epoch_idx = 0 + self.worker_index = fleet.worker_index() + self.main_program = paddle.static.default_main_program() + self.startup_program = paddle.static.default_startup_program() + self._client_ptr = fleet.get_fl_client() + self._coordinators = self.role_maker._get_coordinator_endpoints() + logger.info("fl-ps > coordinator enpoints: {}".format( + self._coordinators)) + self.strategy_handlers = dict() + self.exe = None + self.use_cuda = int(self.config.get("runner.use_gpu")) + self.place = paddle.CUDAPlace(0) if self.use_cuda else paddle.CPUPlace() + self.print_step = int(self.config.get("runner.print_interval")) + self.debug = self.config.get("runner.dataset_debug", False) + self.reader_type = self.config.get("runner.reader_type", "QueueDataset") + self.set_executor() + self.make_save_model_path() + self.set_metrics(metrics) + + def set_train_dataset_info(self, train_dataset, train_file_list): + self.train_dataset = train_dataset + self.train_file_list = train_file_list + logger.info("fl-ps > {}, data_feed_desc:\n {}".format( + type(self.train_dataset), self.train_dataset._desc())) + + def set_test_dataset_info(self, test_dataset, test_file_list): + self.test_dataset = test_dataset + self.test_file_list = test_file_list + + def set_train_example_num(self, num): + self.train_example_nums = num + + def load_dataset(self): + if self.reader_type == "InmemoryDataset": + self.train_dataset.load_into_memory() + + def release_dataset(self): + if self.reader_type == "InmemoryDataset": + self.train_dataset.release_memory() + + def set_executor(self): + self.exe = paddle.static.Executor(self.place) + + def make_save_model_path(self): + self.save_model_path = self.config.get("runner.model_save_path") + if self.save_model_path and (not os.path.exists(self.save_model_path)): + os.makedirs(self.save_model_path) + + def set_dump_fields(self): + # DumpField + # TrainerDesc -> SetDumpParamVector -> DumpParam -> DumpWork + if self.config.get("runner.need_dump"): + self.debug = True + dump_fields_path = "{}/epoch_{}".format( + self.config.get("runner.dump_fields_path"), self.epoch_idx) + dump_fields = self.config.get("runner.dump_fields", []) + dump_param = self.config.get("runner.dump_param", []) + persist_vars_list = self.main_program.all_parameters() + persist_vars_name = [ + str(param).split(":")[0].strip().split()[-1] + for param in persist_vars_list + ] + logger.info( + "fl-ps > persist_vars_list: {}".format(persist_vars_name)) + + if dump_fields_path is not None: + self.main_program._fleet_opt[ + 'dump_fields_path'] = dump_fields_path + if dump_fields is not None: + self.main_program._fleet_opt["dump_fields"] = dump_fields + if dump_param is not None: + self.main_program._fleet_opt["dump_param"] = dump_param + + def set_metrics(self, metrics): + self.metrics = metrics + self.fetch_vars = [var for _, var in self.metrics.items()] + + +class FLClient(FLClientBase): + + def __init__(self): + super(FLClient, self).__init__() + + def __build_fl_client_info_desc(self, state_info): + # ......... to implement ...... # + state_info = { + ClientInfoAttr.DEVICE_TYPE: "Andorid", + ClientInfoAttr.COMPUTE_CAPACITY: 10, + ClientInfoAttr.BANDWIDTH: 100 + } + client_info = the_one_ps_pb2.FLClientInfo() + client_info.device_type = state_info[ClientInfoAttr.DEVICE_TYPE] + client_info.compute_capacity = state_info[ + ClientInfoAttr.COMPUTE_CAPACITY] + client_info.bandwidth = state_info[ClientInfoAttr.BANDWIDTH] + str_msg = text_format.MessageToString(client_info) + return str_msg + + def run(self): + self.register_default_handlers() + self.print_program() + self.strategy_handlers['initialize_model_params']() + self.strategy_handlers['init_worker']() + self.load_dataset() + self.train_loop() + self.release_dataset() + self.strategy_handlers['finish']() + + def train_loop(self): + while self.epoch_idx < self.total_train_epoch: + logger.info("fl-ps > curr epoch idx: {}".format(self.epoch_idx)) + self.strategy_handlers['train']() + self.strategy_handlers['save_model']() + self.barrier() + state_info = { + "client id": self.worker_index, + "auc": 0.9, + "epoch": self.epoch_idx + } + self.push_fl_client_info_sync(state_info) + strategy_dict = self.pull_fl_strategy() + logger.info("fl-ps > recved fl strategy: {}".format(strategy_dict)) + # ......... to implement ...... # + if strategy_dict['next_state'] == "JOIN": + self.strategy_handlers['infer']() + elif strategy_dict['next_state'] == "FINISH": + self.strategy_handlers['finish']() + + def push_fl_client_info_sync(self, state_info): + str_msg = self.__build_fl_client_info_desc(state_info) + self._client_ptr.push_fl_client_info_sync(str_msg) + return + + def pull_fl_strategy(self): + strategy_dict = {} + fl_strategy_str = self._client_ptr.pull_fl_strategy( + ) # block: wait for coordinator's strategy arrived + logger.info("fl-ps > fl client recved fl_strategy(str):\n{}".format( + fl_strategy_str)) + fl_strategy_desc = the_one_ps_pb2.FLStrategy() + text_format.Parse(bytes(fl_strategy_str, encoding="utf8"), + fl_strategy_desc) + strategy_dict["next_state"] = fl_strategy_desc.next_state + return strategy_dict + + def barrier(self): + fleet.barrier_worker() + + def register_handlers(self, strategy_type, callback_func): + self.strategy_handlers[strategy_type] = callback_func + + def register_default_handlers(self): + self.register_handlers('train', self.callback_train) + self.register_handlers('infer', self.callback_infer) + self.register_handlers('finish', self.callback_finish) + self.register_handlers('initialize_model_params', + self.callback_initialize_model_params) + self.register_handlers('init_worker', self.callback_init_worker) + self.register_handlers('save_model', self.callback_save_model) + + def callback_init_worker(self): + fleet.init_worker() + + def callback_initialize_model_params(self): + if self.exe == None or self.main_program == None: + raise AssertionError("exe or main_program not set") + self.exe.run(self.startup_program) + + def callback_train(self): + epoch_start_time = time.time() + self.set_dump_fields() + fetch_info = [ + "Epoch {} Var {}".format(self.epoch_idx, var_name) + for var_name in self.metrics + ] + self.exe.train_from_dataset(program=self.main_program, + dataset=self.train_dataset, + fetch_list=self.fetch_vars, + fetch_info=fetch_info, + print_period=self.print_step, + debug=self.debug) + self.epoch_idx += 1 + epoch_time = time.time() - epoch_start_time + epoch_speed = self.train_example_nums / epoch_time + self.train_statical_info["speed"].append(epoch_speed) + logger.info("fl-ps > callback_train finished") + + def callback_infer(self): + fetch_info = [ + "Epoch {} Var {}".format(self.epoch_idx, var_name) + for var_name in self.metrics + ] + self.exe.infer_from_dataset(program=self.main_program, + dataset=self.test_dataset, + fetch_list=self.fetch_vars, + fetch_info=fetch_info, + print_period=self.print_step, + debug=self.debug) + + def callback_save_model(self): + model_dir = "{}/{}".format(self.save_model_path, self.epoch_idx) + if fleet.is_first_worker() and self.save_model_path: + if is_distributed_env(): + fleet.save_persistables(self.exe, model_dir) # save all params + else: + raise ValueError("it is not distributed env") + + def callback_finish(self): + fleet.stop_worker() + + def print_program(self): + with open("./{}_worker_main_program.prototxt".format(self.worker_index), + 'w+') as f: + f.write(str(self.main_program)) + with open( + "./{}_worker_startup_program.prototxt".format( + self.worker_index), 'w+') as f: + f.write(str(self.startup_program)) + + def print_train_statical_info(self): + with open("./train_statical_info.txt", 'w+') as f: + f.write(str(self.train_statical_info)) + + +class Coordinator(object): + + def __init__(self, ps_hosts): + self._communicator = FLCommunicator(ps_hosts) + self._client_selector = None + + def start_coordinator(self, self_endpoint, trainer_endpoints): + self._communicator.start_coordinator(self_endpoint, trainer_endpoints) + + def make_fl_strategy(self): + logger.info("fl-ps > running make_fl_strategy(loop) in coordinator\n") + while True: + # 1. get all fl clients reported info + str_map = self._communicator.query_fl_clients_info( + ) # block: wait for all fl clients info reported + # 2. generate fl strategy + self._client_selector = ClientSelector(str_map) + fl_strategy = self._client_selector.select() + # 3. save fl strategy from python to c++ + self._communicator.save_fl_strategy(fl_strategy) + time.sleep(5) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/the_one_ps.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/the_one_ps.py new file mode 100644 index 0000000000000000000000000000000000000000..0ce5e70788e72b9987fc6d445e72526b40b5f8fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/the_one_ps.py @@ -0,0 +1,1595 @@ +# Copyright (c) 2022 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. + +import warnings + +import os +import paddle.fluid as fluid +from paddle.distributed import fleet +from paddle.fluid import core +from paddle.distributed.ps.utils.public import * +from paddle.fluid.framework import Program +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.executor import Executor +from paddle.fluid.parallel_executor import ParallelExecutor +from paddle.fluid.framework import Variable, Parameter +from paddle.distributed.fleet.runtime.runtime_base import RuntimeBase +from paddle.distributed.fleet.base.private_helper_function import wait_server_ready +from paddle.distributed.fleet.proto import the_one_ps_pb2 +from paddle.fluid.communicator import Communicator, HeterClient +from google.protobuf import text_format +from paddle.distributed.ps.coordinator import Coordinator + +__all__ = [ + 'Table', 'SparseTable', 'GeoSparseTable', 'BarrierTable', 'TensorTable', + 'DenseTable' +] + + +def get_program_by_id(context, program_id): + programs = context["origin_main_programs"] + for i, program in enumerate(programs): + if id(program) == program_id: + return program, context["origin_startup_programs"][i], i + return None, None, None + + +def parse_table_class(varname, program_id, context): + main_program, startup_program, idx = get_program_by_id(context, program_id) + for op in main_program.global_block().ops: + if not is_distributed_sparse_op(op) and not is_sparse_op(op): + continue + + param_name = op.input("W")[0] + + if param_name == varname and op.type == "lookup_table" or op.type == "lookup_table_v2": + if op.has_attr('table_class') and op.attr("table_class") != "none": + return op.attr('table_class') + else: + return "MemorySparseTable" + + +def check_embedding_dim(accessor_proto, varname, program_id, context): + main_program, startup_program, idx = get_program_by_id(context, program_id) + embedding_dim = 0 + for var in main_program.list_vars(): + if var.name == varname: + embedding_dim = var.shape[1] + print('new var: {}, {}, {}'.format(var, embedding_dim, + accessor_proto.fea_dim)) + break + + fea_dim = accessor_proto.fea_dim + if accessor_proto.accessor_class == "SparseAccessor": + if fea_dim != embedding_dim + 2: + raise ValueError( + "The fea_dim is wrong, it will be sparse_embedding_dim + 2: {}, but got {}" + .format(embedding_dim + 2, fea_dim)) + else: + if fea_dim != embedding_dim: + raise ValueError( + "The fea_dim is wrong, it will be sparse_embedding_dim: {}, but got {}" + .format(embedding_dim, fea_dim)) + + embedx_dim = accessor_proto.embedx_dim + if accessor_proto.accessor_class == "SparseAccessor": + if embedx_dim != embedding_dim - 1: + raise ValueError( + "The embedx_dim is wrong, it will be sparse_embedding_dim - 1: {}, but got {}" + .format(embedding_dim - 1, embedx_dim)) + else: + if embedx_dim != embedding_dim - 3: + raise ValueError( + "The embedx_dim is wrong, it will be sparse_embedding_dim - 3: {}, but got {}" + .format(embedding_dim - 3, embedx_dim)) + + +class Service: + + def __init__(self): + pass + + def _set(self, service_proto): + service_proto.server_class = "BrpcPsServer" + service_proto.client_class = "BrpcPsClient" + service_proto.service_class = "BrpcPsService" + service_proto.start_server_port = 0 + service_proto.server_thread_num = 12 + + +class GpuService(Service): + + def __init__(self): + super(GpuService, self).__init__() + + def _set(self, service_proto): + service_proto.server_class = 'PsLocalServer' + service_proto.client_class = 'PsLocalClient' + + +class Accessor: + + def __init__(self): + self.accessor_class = "" + self.optimizer = None + self.feature_dim = 0 + self.embedding_dim = 0 + + # TableAccessorParameter accessor + def _set(self, accessor_proto, varname, program_id, context, + common_accessor): + main_program, startup_program, idx = get_program_by_id( + context, program_id) + embedding_dim = 0 + for var in main_program.list_vars(): + if var.name == varname: + embedding_dim = var.shape[1] + break + + if not accessor_proto.HasField("accessor_class"): + # DownpourSparseValueAccessor + if context['use_ps_gpu']: + accessor_proto.accessor_class = "CtrDymfAccessor" + else: + accessor_proto.accessor_class = "SparseAccessor" + if not accessor_proto.HasField("fea_dim"): + if accessor_proto.accessor_class == "SparseAccessor": + accessor_proto.fea_dim = embedding_dim + 2 + else: + accessor_proto.fea_dim = embedding_dim + if not accessor_proto.HasField("embedx_dim"): + if accessor_proto.accessor_class == "SparseAccessor": + accessor_proto.embedx_dim = embedding_dim - 1 + else: + accessor_proto.embedx_dim = embedding_dim - 3 + if not accessor_proto.HasField("embedx_threshold"): + accessor_proto.embedx_threshold = 0 + + graph_sgd_param = accessor_proto.graph_sgd_param + if not graph_sgd_param.HasField("nodeid_slot"): + graph_sgd_param.nodeid_slot = 9008 + if not graph_sgd_param.HasField("feature_learning_rate"): + graph_sgd_param.feature_learning_rate = 0.05 + + ctr_accessor_param = accessor_proto.ctr_accessor_param + if accessor_proto.embedx_dim == 0: + ctr_accessor_param.zero_init = False + if not ctr_accessor_param.HasField("nonclk_coeff"): + ctr_accessor_param.nonclk_coeff = 0.1 + if not ctr_accessor_param.HasField("click_coeff"): + ctr_accessor_param.click_coeff = 1.0 + if not ctr_accessor_param.HasField("base_threshold"): + ctr_accessor_param.base_threshold = 0 + if not ctr_accessor_param.HasField("delta_threshold"): + ctr_accessor_param.delta_threshold = 0 + if not ctr_accessor_param.HasField("delta_keep_days"): + ctr_accessor_param.delta_keep_days = 16 + if not ctr_accessor_param.HasField("show_click_decay_rate"): + ctr_accessor_param.show_click_decay_rate = 1 + if not ctr_accessor_param.HasField("delete_threshold"): + ctr_accessor_param.delete_threshold = 0 + if not ctr_accessor_param.HasField("delete_after_unseen_days"): + ctr_accessor_param.delete_after_unseen_days = 30 + if not ctr_accessor_param.HasField("ssd_unseenday_threshold"): + ctr_accessor_param.ssd_unseenday_threshold = 1 + + for sgd_param in [ + accessor_proto.embed_sgd_param, accessor_proto.embedx_sgd_param + ]: + if not sgd_param.HasField("name"): + if common_accessor.accessor_class == "sgd": + sgd_param.name = "SparseNaiveSGDRule" + if common_accessor.accessor_class == "adam": + sgd_param.name = "SparseAdamSGDRule" + else: # for fl-ps, because geo accessor is 'sum' + sgd_param.name = "SparseAdamSGDRule" + + if sgd_param.name == "SparseAdaGradSGDRule" or sgd_param.name == "StdAdaGradSGDRule": + if not sgd_param.adagrad.HasField("learning_rate"): + sgd_param.adagrad.learning_rate = 0.05 + if not sgd_param.adagrad.HasField("initial_g2sum"): + sgd_param.adagrad.initial_g2sum = 3.0 + if not sgd_param.adagrad.HasField("initial_range"): + sgd_param.adagrad.initial_range = 0.0001 + if len(sgd_param.adagrad.weight_bounds) == 0: + sgd_param.adagrad.weight_bounds.extend([-10.0, 10.0]) + + if sgd_param.name == "SparseNaiveSGDRule": + if not sgd_param.naive.HasField("learning_rate"): + learning_rate = common_accessor.initializers[-1].split( + "&")[1] + sgd_param.naive.learning_rate = float(learning_rate) + if not sgd_param.naive.HasField("initial_range"): + initial_range = common_accessor.initializers[0].split( + "&")[-1] + sgd_param.naive.initial_range = float(initial_range) + if len(sgd_param.naive.weight_bounds) == 0: + sgd_param.naive.weight_bounds.extend([-10.0, 10.0]) + + if sgd_param.name == "SparseAdamSGDRule" or sgd_param.name == "SparseSharedAdamSGDRule": + if not sgd_param.adam.HasField("learning_rate"): + learning_rate = common_accessor.initializers[-1].split( + "&")[1] + sgd_param.adam.learning_rate = float(learning_rate) + if not sgd_param.adam.HasField("initial_range"): + initial_range = common_accessor.initializers[0].split( + "&")[-1] + sgd_param.adam.initial_range = float(initial_range) + + attr_list = [x.split("&") for x in common_accessor.attrs] + if not sgd_param.adam.HasField( + "beta1_decay_rate" + ) and common_accessor.accessor_class == "adam": + sgd_param.adam.beta1_decay_rate = float(attr_list[0][1]) + else: + sgd_param.adam.beta1_decay_rate = 0.9 + if not sgd_param.adam.HasField( + "beta2_decay_rate" + ) and common_accessor.accessor_class == "adam": + sgd_param.adam.beta2_decay_rate = float(attr_list[1][1]) + else: + sgd_param.adam.beta2_decay_rate = 0.999 + if not sgd_param.adam.HasField( + "ada_epsilon" + ) and common_accessor.accessor_class == "adam": + sgd_param.adam.ada_epsilon = float(attr_list[2][1]) + else: + sgd_param.adam.ada_epsilon = 1e-08 + if len(sgd_param.adam.weight_bounds) == 0: + sgd_param.adam.weight_bounds.extend([-10.0, 10.0]) + + +class CommonAccessor(Accessor): + + def __init__(self): + super(CommonAccessor, self).__init__() + self.table_name = '' + self.entry = 'none' + self.attrs = [] + self.params = [] + self.dims = [] + self.trainer_num = 0 + self.sync = False + self.initializers = [] + self.opt_input_map = {} + self.opt_attr_map = {} + self.opt_init_map = {} + self.define_optimize_map() + + def define_optimize_map(self): + opt_input_map = {} + opt_input_map["sgd"] = [("Param", None), ("LearningRate", 1)] + opt_input_map["adam"] = [("Param", None), ("Moment1", None), + ("Moment2", None), ("Beta1Pow", 1), + ("Beta2Pow", 1), ("LearningRate", 1)] + opt_input_map["adam_d2sum"] = [("Param", None), ("D2Sum", None), + ("G2Sum", None), ("Moment", None), + ("MomentDecayRate", 1), + ("AdaDecayRate", 1), ("AdaEpsilon", 1), + ("LearningRate", 1)] + opt_input_map["sum"] = [("Param", None)] + opt_input_map["naive_adagrad"] = [("Param", None), ("G2Sum", 1), + ("LearningRate", 1)] + opt_input_map["summary"] = [("Param", None), ("SummaryDecayRate", 1)] + + opt_attr_map = {} + opt_attr_map["sgd"] = [] + opt_attr_map["sum"] = [] + opt_attr_map["naive_adagrad"] = [] + opt_attr_map["adam"] = [("beta1", "f"), ("beta2", "f"), + ("epsilon", "f")] + opt_attr_map["adam_d2sum"] = [("beta1", "f"), ("beta2", "f"), + ("epsilon", "f")] + opt_attr_map["summary"] = [("summary_decay_rate", "f")] + + opt_init_map = {} + opt_init_map["gaussian_random"] = ["seed", "mean", "std"] + opt_init_map["fill_constant"] = ["value"] + opt_init_map["uniform_random"] = ["seed", "min", "max"] + opt_init_map["truncated_gaussian_random"] = ["seed", "mean", "std"] + + self.opt_attr_map = opt_attr_map + self.opt_input_map = opt_input_map + self.opt_init_map = opt_init_map + + def parse_entry(self, varname, program_id, context): + main_program, startup_program, idx = get_program_by_id( + context, program_id) + for op in main_program.global_block().ops: + if not is_distributed_sparse_op(op) and not is_sparse_op(op): + continue + + param_name = op.input("W")[0] + + if param_name == varname and op.type == "lookup_table": + self.entry = op.attr('entry') + break + + if param_name == varname and op.type == "lookup_table_v2": + self.entry = "none" + break + + def get_shard(self, total_dim, shard_num, pserver_id): + blocksize = int(total_dim / shard_num + 1) + + if blocksize * (pserver_id + 1) <= total_dim: + return blocksize + else: + if blocksize * pserver_id < total_dim: + return total_dim - blocksize * pserver_id + else: + return 0 + + def get_initializer_attr(self, value_name, o_startup_program): + l_in = "&" + attr_str = "" + + origin_var_name = value_name + # print("get_initializer_attr param name:", value_name) + for op in o_startup_program.global_block().ops: + if op.type in self.opt_init_map.keys( + ) and origin_var_name == op.output("Out")[0]: + init_attr = [op.type] + # print("get_initializer_attr op type:", op.type) + for attr in self.opt_init_map[op.type]: + # print("get_initializer_attr opt_init_map attr:", attr) + init_attr.append(str(op.attr(attr))) + # print("get_initializer_attr op attr:", str(op.attr(attr))) + attr_str = l_in.join(init_attr) + break + return attr_str + + def parse_by_optimizer(self, ctx, context): + grad_name = ctx.origin_varnames()[0] + is_sparse = ctx.is_sparse() + size = ctx.sections()[0] + single_dim = ctx.sections()[1] if ctx.is_sparse() else 1 + adam_d2sum = context["user_defined_strategy"].adam_d2sum + # print("parse_by_optimizer table_id:{} is_datanorm:{}".format( + # ctx.table_id(), ctx.is_datanorm_table())) + + main_program, startup_program, idx = get_program_by_id( + context, ctx.program_id()) + pserver_id = get_role_id(context['role_maker']) + pserver_num = len(get_ps_endpoints(context['role_maker'])) + optimizer_ops = get_optimize_ops(main_program) + # print("the one ps optimizer_ops:", optimizer_ops) + # print("the one ps parse_by_optimizer grad_name:", grad_name) + oop = None + + for op in optimizer_ops: + if ("Param" in op.input_names) and ( + op.input("Param")[0] + == context['grad_name_to_param_name'][grad_name]): + oop = op + break + + if oop is None: + raise ValueError("can not find optimizer for {}".format(grad_name)) + + params = [] + dims = [] + attrs = [] + initializers = [] + + self.trainer_num = get_trainers(context['role_maker']) + self.table_num = size + self.table_dim = single_dim + + if oop.type != 'adam' and adam_d2sum == True: + print('optimization algorithm is not adam, set adam_d2sum False') + adam_d2sum = False + print("adam_d2sum:", adam_d2sum) + if context['ps_mode'] == DistributedMode.GEO: + param_varnames = self.opt_input_map["sum"] + attr_varnames = self.opt_attr_map["sum"] + self.accessor_class = "sum" + elif context['use_ps_gpu'] and is_sparse: + param_varnames = self.opt_input_map["naive_adagrad"] + attr_varnames = self.opt_attr_map["naive_adagrad"] + self.accessor_class = "sgd" + elif ctx.is_datanorm_table(): + param_varnames = self.opt_input_map["summary"] + attr_varnames = self.opt_attr_map["summary"] + self.accessor_class = "summary" + elif adam_d2sum and not is_sparse: + param_varnames = self.opt_input_map["adam_d2sum"] + attr_varnames = self.opt_attr_map["adam_d2sum"] + self.accessor_class = "adam_d2sum" + else: + if oop.type != 'sgd' and oop.type != 'adam': + raise ValueError( + "The dense optimizer in PS is only supported SGD or Adam!") + param_varnames = self.opt_input_map[oop.type] + attr_varnames = self.opt_attr_map[oop.type] + self.accessor_class = oop.type + + for (formal_name, shape) in param_varnames: + params.append(formal_name) + if self.accessor_class == "adam_d2sum": + #for dims + if shape is None: + if is_sparse: + shape = single_dim + else: + shape = self.get_shard(size, pserver_num, pserver_id) + dims.append(shape) + + #for initializers + if formal_name == "Param" or formal_name == "LearningRate": + param = main_program.global_block().vars[oop.input( + formal_name)[0]] + #TODO: for dense learning_rate, can be different from sparse lr + if formal_name == "LearningRate" and param.name != "learning_rate_" + str( + idx): + warnings.warn("will support decay soon") + param = main_program.global_block().vars[ + "learning_rate_" + str(idx)] + + initializer = self.get_initializer_attr( + param.name, startup_program) + elif formal_name == "MomentDecayRate": + initializer = "fill_constant&0.99" + elif formal_name == "AdaDecayRate": + initializer = "fill_constant&0.9999" + elif formal_name == "AdaEpsilon": + initializer = "fill_constant&1.0e-8" + else: + initializer = "fill_constant&0" + initializers.append(initializer) + elif self.accessor_class == "summary": + #for dims + if shape is None: + if is_sparse: + shape = single_dim + else: + shape = self.get_shard(size, pserver_num, pserver_id) + dims.append(shape) + + #for initializers + if formal_name == "Param": + param = main_program.global_block().vars[oop.input( + formal_name)[0]] + + initializer = self.get_initializer_attr( + param.name, startup_program) + elif formal_name == "SummaryDecayRate": + initializer = "fill_constant&0.999999" + else: + initializer = "fill_constant&0" + initializers.append(initializer) + else: + if formal_name == "G2Sum": + dims.append(1) + initializer = "fill_constant&0" + initializers.append(initializer) + else: + param = main_program.global_block().vars[oop.input( + formal_name)[0]] + if formal_name == "LearningRate" and param.name != "learning_rate_" + str( + idx): + warnings.warn("will support decay soon") + param = main_program.global_block().vars[ + "learning_rate_" + str(idx)] + + if shape is None: + if is_sparse: + shape = single_dim + else: + shape = self.get_shard(size, pserver_num, + pserver_id) + dims.append(shape) + + initializer = self.get_initializer_attr( + param.name, startup_program) + initializers.append(initializer) + + if self.accessor_class == 'summary': + datanorm_ops = get_datanorm_ops(main_program) + for op in datanorm_ops: + if ("BatchSize" in op.input_names) and ( + op.input("BatchSize")[0] + == context['grad_name_to_param_name'][grad_name]): + oop = op + break + + for (attr_varname, type_) in attr_varnames: + value = oop.attr(attr_varname) + attrs.append("&".join([attr_varname, str(value)])) + + self.params = params + self.dims = dims + self.initializers = initializers + self.attrs = attrs + + # CommonAccessorParameter common + def _set(self, proto): + proto.name = self.accessor_class + proto.table_name = self.table_name + proto.params.extend(self.params) + proto.dims.extend(self.dims) + proto.initializers.extend(self.initializers) + proto.entry = self.entry + proto.trainer_num = self.trainer_num + proto.sync = self.sync + proto.table_num = self.table_num + proto.table_dim = self.table_dim + proto.attr = "#".join(self.attrs) + + +class Tensor: + + def __init__(self, tesnor_dcit): + self.tensor_dict = tesnor_dcit + + def _set(self, tensor_proto): + tensor_proto.main_program_id = self.tensor_dict.get( + "main_program_id", 0) + tensor_proto.startup_program_id = self.tensor_dict.get( + "startup_program_id", 0) + tensor_proto.feed_var_name = self.tensor_dict.get("feed_var_name", '') + tensor_proto.fetch_var_name = self.tensor_dict.get("fetch_var_name", '') + tensor_proto.tensor_table_class = self.tensor_dict.get( + "tensor_table_class", '') + + +class Table: + + def __init__(self): + self.table_class = None + self.shard_num = -1 + self.type = None + self.accessor = Accessor() + self.shard_num = 256 + self.common = CommonAccessor() + self.tensor = None + + def _set(self, table_proto): + pass + + +class BarrierTable(Table): + + def __init__(self, context, idx): + super(BarrierTable, self).__init__() + self.type = None + self.shard_num = 256 + self.accessor.accessor_class = 'CommMergeAccessor' + self.common.attrs = "" + self.common.dims = [] + self.common.params = [] + self.is_heter_ps_mode = context['is_heter_ps_mode'] + self.role_maker = context['role_maker'] + self.idx = idx + self.is_sync = context['is_sync'] + + def _set(self, table_proto): + table_proto.table_id = self.idx + table_proto.table_class = 'BarrierTable' + table_proto.shard_num = 256 + table_proto.type = the_one_ps_pb2.PS_OTHER_TABLE + + table_proto.accessor.accessor_class = "CommMergeAccessor" + table_proto.accessor.fea_dim = 0 + table_proto.accessor.embedx_dim = 0 + + table_proto.common.name = "" + table_proto.common.table_name = "barrier_table" + table_proto.common.sync = self.is_sync + table_proto.common.entry = 'none' + + trainer_num = get_trainers(self.role_maker) + if self.is_heter_ps_mode: + trainer_num += len(self.role_maker._get_heter_worker_endpoints()) + table_proto.common.trainer_num = trainer_num + + +class TensorTable(Table): + + def __init__(self, idx, tensor_dict, role_maker): + super(TensorTable, self).__init__() + self.idx = idx + self.tensor_dict = tensor_dict + self.role_maker = role_maker + + def _set(self, table_proto): + table_proto.table_id = self.idx + table_proto.type = the_one_ps_pb2.PS_OTHER_TABLE + table_proto.table_class = self.tensor_dict.get("tensor_table_class", '') + + table_proto.accessor.accessor_class = "CommMergeAccessor" + + table_proto.common.table_name = self.tensor_dict.get( + "feed_var_name", '') + table_proto.common.trainer_num = get_trainers(self.role_maker) + + tensor = Tensor(self.tensor_dict) + tensor._set(table_proto.tensor) + + +class SparseTable(Table): + + def __init__(self, context, send_ctx): + super(SparseTable, self).__init__() + self.context = context + self.ctx = send_ctx + self.type = None + self.table_class = 'MemorySparseTable' + self.accessor = Accessor() + + def _set(self, table_proto): + ctx = self.ctx + if ctx.is_tensor_table() or len( + ctx.origin_varnames()) < 1 or (ctx.is_sparse() == False): + return + table_proto.table_id = ctx.table_id() + table_proto.table_class = self.table_class + table_proto.type = the_one_ps_pb2.PS_SPARSE_TABLE + table_proto.shard_num = self.shard_num + if table_proto.sparse_table_cache_file_num > len( + get_ps_endpoints(self.context['role_maker'])): + table_proto.sparse_table_cache_file_num = len( + get_ps_endpoints(self.context['role_maker'])) + + self.common.table_name = self.context['grad_name_to_param_name'][ + ctx.origin_varnames()[0]] + + self.common.parse_by_optimizer(ctx, self.context) + self.common.parse_entry(self.common.table_name, ctx.program_id(), + self.context) + self.common.sync = True if self.context['is_sync'] else False + + self.common._set(table_proto.common) + + print('new table_name: {}'.format(self.common.table_name)) + all_table_proto = self.context[ + "user_defined_strategy"].sparse_table_configs + usr_table_proto = all_table_proto.add() + for proto in all_table_proto: + if proto.table_name == self.common.table_name: + usr_table_proto = proto + break + if usr_table_proto.HasField("table_class"): + table_proto.table_class = usr_table_proto.table_class + else: + table_proto.table_class = 'MemorySparseTable' + warnings.warn("The PS mode must use MemorySparseTable.") + if usr_table_proto.HasField("shard_num"): + table_proto.shard_num = usr_table_proto.shard_num + else: + if self.context['use_ps_gpu']: + table_proto.shard_num = 37 + warnings.warn( + "The shard_num of sparse table is not set, use default value 37 in gpups." + ) + else: + table_proto.shard_num = 1000 + warnings.warn( + "The shard_num of sparse table is not set, use default value 1000 in cpups." + ) + + if usr_table_proto.HasField("enable_sparse_table_cache"): + table_proto.enable_sparse_table_cache = usr_table_proto.enable_sparse_table_cache + if usr_table_proto.HasField("sparse_table_cache_rate"): + table_proto.sparse_table_cache_rate = usr_table_proto.sparse_table_cache_rate + if usr_table_proto.HasField("sparse_table_cache_file_num"): + table_proto.sparse_table_cache_file_num = usr_table_proto.sparse_table_cache_file_num + if usr_table_proto.HasField("enable_revert"): + table_proto.enable_revert = usr_table_proto.enable_revert + if usr_table_proto.HasField("shard_merge_rate"): + table_proto.shard_merge_rate = usr_table_proto.shard_merge_rate + + if usr_table_proto.accessor.ByteSize() == 0: + warnings.warn( + "The accessor of sparse table is not set, use default value.") + + table_proto.accessor.ParseFromString( + usr_table_proto.accessor.SerializeToString()) + self.accessor._set(table_proto.accessor, self.common.table_name, + ctx.program_id(), self.context, self.common) + + check_embedding_dim(table_proto.accessor, self.common.table_name, + ctx.program_id(), self.context) + + +class GeoSparseTable(SparseTable): + + def __init__(self, context, send_ctx): + super(GeoSparseTable, self).__init__(context, send_ctx) + self.table_class = "MemorySparseGeoTable" + if self.context['ps_mode'] != DistributedMode.GEO: + raise ValueError("not geo sparse table!") + + def _set(self, table_proto): + ctx = self.ctx + if ctx.is_tensor_table() or len( + ctx.origin_varnames()) < 1 or (ctx.is_sparse() == False): + return + table_proto.table_id = ctx.table_id() + table_proto.table_class = self.table_class + table_proto.type = the_one_ps_pb2.PS_SPARSE_TABLE + table_proto.shard_num = self.shard_num + + table_proto.accessor.accessor_class = 'CommMergeAccessor' + table_proto.accessor.fea_dim = ctx.sections()[0] + table_proto.accessor.embedx_dim = ctx.sections()[1] + + self.common.table_name = self.context['grad_name_to_param_name'][ + ctx.origin_varnames()[0]] + self.common.parse_by_optimizer(ctx, self.context) + self.common.parse_entry(self.common.table_name, ctx.program_id(), + self.context) + self.common.sync = False + self.common._set(table_proto.common) + + +class DenseTable(Table): + + def __init__(self, context, send_ctx): + super(DenseTable, self).__init__() + self.context = context + self.ctx = send_ctx + self.accessor = Accessor() + + def _set(self, table_proto): + ctx = self.ctx + if ctx.is_tensor_table() or len( + ctx.origin_varnames()) < 1 or (ctx.is_sparse() == True): + return + + table_proto.table_id = ctx.table_id() + + table_proto.type = the_one_ps_pb2.PS_DENSE_TABLE + table_proto.table_class = "MemoryDenseTable" + table_proto.shard_num = 256 + + table_proto.accessor.accessor_class = 'CommMergeAccessor' + table_proto.accessor.fea_dim = ctx.sections()[0] + table_proto.accessor.embedx_dim = 1 + + self.common.table_name = "MergedDense" + self.common.parse_by_optimizer(ctx, self.context) + self.common.parse_entry(self.common.table_name, ctx.program_id(), + self.context) + self.common.sync = True if self.context['is_sync'] else False + + self.common._set(table_proto.common) + + +class Server: + + def __init__(self): + pass + + def _set(self): + pass + + +class DownpourServer(Server): + + def __init__(self): + super(DownpourServer, self).__init__() + + def _set(self): + pass + + +class Worker: + + def __init__(self): + pass + + def _set(self): + pass + + +class DownpourWorker(Worker): + + def __init__(self): + super(DownpourWorker, self).__init__() + + def _set(self): + pass + + +class fsClient: + + def __init__(self, fs_client_param): + self.fs_client_param = fs_client_param + + def _set(self, proto): + if not text_format.MessageToString(self.fs_client_param): + return + proto.uri = self.fs_client_param.uri + proto.user = self.fs_client_param.user + proto.passwd = self.fs_client_param.passwd + proto.hadoop_bin = self.fs_client_param.hadoop_bin + + +class PsDescBuilder(object): + + def __init__(self, context): + self.context = context + self.is_sync = context['is_sync'] + self.ps_mode = context['ps_mode'] + self.is_heter_ps_mode = context['is_heter_ps_mode'] + self.use_ps_gpu = context['use_ps_gpu'] + self.barrier_table_id = None + + self.send_ctx = get_the_one_send_context( + self.context, split_dense_table=self.is_heter_ps_mode) + + self.tensor_table_dict = {} # TODO + self._server_sub_program = [] + + self.tables = self._get_tables() + + self.service = self._get_service() + self.fs_client = self._get_fs_client() + + self.ps_desc = the_one_ps_pb2.PSParameter() + self.fl_desc = the_one_ps_pb2.FLParameter() + + def _get_tensor_tables(self): + program_idx = 0 + if not self.tensor_table_dict: + self._server_sub_program.append(Program().desc) + tables = [] + for table_name in self.tensor_table_dict: + tables.append(globals()['TensorTable'](len(tables), tensor_dict, + self.context['role_maker'])) + program_idx += 1 + return tables + + def _get_tables(self): + tables = [] + for idx, (name, ctx) in enumerate(self.send_ctx.items()): + print("idx, name, ctx:", idx, name, ctx) + if ctx.is_sparse(): + if self.ps_mode == DistributedMode.GEO: + if (self.context['local_sparse'] + and name[:-5] in self.context['local_sparse']) or ( + not self.context['local_sparse']): + tables.append(globals()['GeoSparseTable'](self.context, + ctx)) + else: + tables.append(globals()['SparseTable'](self.context, + ctx)) + else: + tables.append(globals()['SparseTable'](self.context, ctx)) + else: + tables.append(globals()['DenseTable'](self.context, ctx)) + self.tensor_tables = self._get_tensor_tables() + tables.extend(self.tensor_tables) + tables.append(globals()['BarrierTable'](self.context, len(tables))) + return tables + + def _get_service(self): + if self.use_ps_gpu: + return GpuService() + else: + return Service() + + def _get_fs_client(self): + return fsClient(self.context["user_defined_strategy"].fs_client_param) + + def build_fl_client_desc(self, client_info): + pass + + def build_worker_desc(self): + for table in self.tables: + table_proto = self.ps_desc.worker_param.downpour_worker_param.downpour_table_param.add( + ) + table._set(table_proto) + table_proto = self.ps_desc.server_param.downpour_server_param.downpour_table_param.add( + ) + table._set(table_proto) + if type(table) == BarrierTable and self.barrier_table_id is None: + self.barrier_table_id = table.idx + self.service._set( + self.ps_desc.server_param.downpour_server_param.service_param) + self.fs_client._set(self.ps_desc.fs_client_param) + return text_format.MessageToString(self.ps_desc) + + def build_server_desc(self): + self.sparse_table_maps = {} + for table in self.tables: + table_proto = self.ps_desc.server_param.downpour_server_param.downpour_table_param.add( + ) + table._set(table_proto) + if table_proto.type == the_one_ps_pb2.PS_SPARSE_TABLE and table_proto.common is not None: + self.sparse_table_maps[ + table_proto.common.table_name] = table_proto.table_id + + self.service._set( + self.ps_desc.server_param.downpour_server_param.service_param) + self.fs_client._set(self.ps_desc.fs_client_param) + return text_format.MessageToString(self.ps_desc) + + +class TheOnePSRuntime(RuntimeBase): + + def __init__(self): + super(TheOnePSRuntime, self).__init__() + self._communicator = None + self._server = None + self._worker = fluid.core.DistFleetWrapper() + self._coordinator = None + self._server_sub_program = [] + self._heter_client = None + self._send_ctx = None + + def _set_basic_info(self, context): + self.context = context + self.role_maker = context["role_maker"] + self.role_id = get_role_id(self.role_maker) + self.debug = bool(int(os.getenv("PSERVER_DEBUG", "0"))) + + self.origin_main_program = context["origin_main_program"] + self.origin_main_programs = context.get("origin_main_programs", + [self.origin_main_program]) + self.context["origin_main_programs"] = self.origin_main_programs + self.context["origin_startup_programs"] = context.get( + 'origin_startup_programs', [context['origin_startup_program']]) + self.context[ + 'is_heter_ps_mode'] = self.role_maker._is_heter_parameter_server_mode + self.is_heter_ps_mode = self.context['is_heter_ps_mode'] + self.context['trainer'] = TrainerRuntimeConfig( + context['valid_strategy']) + self.context['ps_mode'] = self.context['trainer'].mode + self.context['use_ps_gpu'] = context['valid_strategy'].a_sync_configs[ + 'use_ps_gpu'] + self.context['is_sync'] = True if self.context[ + 'ps_mode'] == DistributedMode.SYNC else False + self.context['grad_name_to_param_name'] = {} + self.context['tensor_table'] = {} + # FL + self.context['local_sparse'] = context[ + "user_defined_strategy"].trainer_desc_configs["local_sparse"] + self.context['remote_sparse'] = context[ + "user_defined_strategy"].trainer_desc_configs["remote_sparse"] + print("fl-ps > local_sparse: {}, remote_sparse: {}".format( + self.context['local_sparse'], self.context['remote_sparse'])) + + build_var_distributed(self.context) + + self.trainer_endpoints = get_trainer_endpoints(self.role_maker) + + self.endpoints = get_ps_endpoints(self.role_maker) + self.string_hosts = [] + for idx, ep in enumerate(self.endpoints): + host, port = ep.split(":") + pshost = fluid.core.PSHost(host, int(port), idx) + self.string_hosts.append(pshost.serialize_to_string()) + + self.with_coordinator = self.role_maker._with_coordinator + self.coordinator_hosts = [] + if self.with_coordinator: + print("fl-ps > all ps addrs: {}".format(self.string_hosts)) + coordinator_endpoints = self.role_maker._get_coordinator_endpoints() + for idx, ep in enumerate(coordinator_endpoints): + ip, port = ep.split(":") + pshost = fluid.core.PSHost(ip, int(port), idx) + self.coordinator_hosts.append(pshost.serialize_to_string()) + + self.ps_desc_builder = PsDescBuilder(self.context) + + def _init_all_params(self, scopes, send_ctx, recv_map): + all_var_names = [] + for name, ctx in send_ctx.items(): + if ctx.is_sparse(): + continue + _, _, idx = get_program_by_id(self.context, ctx.program_id()) + scope = scopes[idx] + table_id = ctx.table_id() + var_names = recv_map[table_id] + #print("init params:", idx, table_id, var_names) + self._worker.push_dense_params(scope, table_id, var_names) + all_var_names.extend(var_names) + return all_var_names + + def _pull_all_dense(self, scopes, send_ctx, recv_map): + all_var_names = [] + for name, ctx in send_ctx.items(): + if ctx.is_sparse(): + continue + _, _, idx = get_program_by_id(self.context, ctx.program_id()) + scope = scopes[idx] + table_id = ctx.table_id() + var_names = recv_map[table_id] + #print("pull all dense:", idx, table_id, var_names) + self._worker.pull_dense_params(scope, table_id, var_names) + all_var_names.extend(var_names) + return all_var_names + + def _init_params(self, program, scope, send_ctx, recv_map): + all_var_names = [] + for name, ctx in send_ctx.items(): + if ctx.is_sparse(): + continue + if ctx.program_id() != id(program): + continue + table_id = ctx.table_id() + var_names = recv_map[table_id] + # print("init params:", table_id, var_names) + self._worker.push_dense_params(scope, table_id, var_names) + all_var_names.extend(var_names) + return all_var_names + + def _pull_dense(self, program, scope, send_ctx, recv_map): + all_var_names = [] + for name, ctx in send_ctx.items(): + if ctx.is_sparse(): + continue + if ctx.program_id() != id(program): + continue + table_id = ctx.table_id() + var_names = recv_map[table_id] + # print("pull dense:", table_id, var_names) + self._worker.pull_dense_params(scope, table_id, var_names) + all_var_names.extend(var_names) + return all_var_names + + def _init_worker(self, scopes=None): + worker_desc = self.ps_desc_builder.build_worker_desc() + if self.context['use_ps_gpu']: + main_program = self.context['loss'].block.program + if not main_program._fleet_opt: + main_program._fleet_opt = {} + main_program._fleet_opt["use_ps_gpu"] = True + gpus_env = os.getenv("FLAGS_selected_gpus") + gpus_env = [int(s) for s in gpus_env.split(",")] + main_program._fleet_opt["worker_places"] = gpus_env + PSGPU = fluid.core.PSGPU() + PSGPU.init_gpu_ps(gpus_env) + + def sync_strategy_envs(): + kwargs = {} + kwargs[ + "pserver_endpoints"] = self.role_maker._get_pserver_endpoints() + kwargs["trainer_id"] = self.role_maker._worker_index() + return kwargs + + dense_map = get_the_one_recv_context( + self.context, split_dense_table=self.is_heter_ps_mode) + send_ctx = get_the_one_send_context( + self.context, + split_dense_table=self.is_heter_ps_mode, + ep_list=self.endpoints) + self._send_ctx = send_ctx + trainer_config = self.context['trainer'] + + if self.debug: + print("worker_desc: \n{}".format(worker_desc)) + print("communicator send_ctx:") + for key in send_ctx: + print("{}: {}".format(key, send_ctx[key])) + for key in dense_map: + print("{}: {}".format(key, dense_map[key])) + + kwargs = {} + kwargs['need_global_step'] = "0" + kwargs["trainer_id"] = self.role_maker._role_id() + kwargs["trainers"] = self.role_maker._worker_num() + + kwargs["barrier_table_id"] = self.ps_desc_builder.barrier_table_id + + if self.context['ps_mode'] == DistributedMode.SYNC: + sync_kwargs = sync_strategy_envs() + kwargs.update(sync_kwargs) + + print("communicator config:", trainer_config.get_communicator_flags()) + + self._worker.init_worker(worker_desc, self.string_hosts, self.role_id) + if not self.is_heter_ps_mode: + self.trainer_endpoint = get_trainer_endpoint(self.role_maker) + print("fl-ps > trainer_endpoint: {}".format(self.trainer_endpoint)) + print("fl-ps > with_coordinator? {}".format(self.with_coordinator)) + print("fl-ps > coordinator addr: {}".format(self.coordinator_hosts)) + if self.with_coordinator: + self._worker.init_fl_worker(self.coordinator_hosts, self.role_id, + self.trainer_endpoint) + + if self.context[ + 'ps_mode'] == DistributedMode.GEO or self.is_heter_ps_mode: + self._communicator = Communicator( + trainer_config.mode, kwargs, + trainer_config.get_communicator_flags()) + self._communicator.init_with_ctx(send_ctx, dense_map, worker_desc, + self.string_hosts, + fluid.global_scope()) + fleet.util.barrier() + + # info = self._communicator.get_client_info() + info = self._worker.get_client_info() + if isinstance(info, list) and len(info) > 0: + all_info = self.role_maker._all_gather( + info[0]) # 收集其他 client 的 service 地址 + # for unittest + if not isinstance(all_info, list): + warnings.warn("gloo may not initialize correctly") + all_info = [all_info] + + # self._communicator.set_clients(all_info) + # self._communicator.create_client_to_client_connection() + self._worker.set_clients(all_info) + self._worker.create_client2client_connection() + print('create c2c connection done') + else: + print('cannot create c2c connection') + + dist_strategy = self.context["valid_strategy"] + + is_test = bool(int(os.getenv("TEST_MODE", "0"))) + + if scopes is None: + if len(self.origin_main_programs) > 1: + raise ValueError( + "You must set the scope list when you have Multiple programs" + ) + scopes = [fluid.global_scope()] + if len(self.origin_main_programs) != len(scopes): + raise VauleError("len(programs) != len(scopes)") + + self.scopes = scopes + if not is_test: + if self.context[ + 'ps_mode'] == DistributedMode.GEO or self.is_heter_ps_mode == True: + self._communicator.init_params(dense_map) + else: + if not self.context['use_ps_gpu']: + if self.role_id == 0: + print("entering self._init_all_params()") + self._init_all_params(scopes, send_ctx, dense_map) + + fleet.util.barrier() # 保证 0 号 worker 参数 push_dense_param over + + if not self.context['use_ps_gpu']: + self._pull_all_dense(scopes, send_ctx, dense_map) + fleet.util.barrier() + + if self.context[ + 'ps_mode'] == DistributedMode.GEO or self.is_heter_ps_mode == True: + if not self._communicator.is_running(): + self._communicator.start() + else: + warnings.warn("communicator has been initialized, skip") + + launch_barrier = dist_strategy.a_sync_configs["launch_barrier"] + launch_barrier_flag = int(os.getenv("FLAGS_LAUNCH_BARRIER", "1")) + if launch_barrier and launch_barrier_flag: + wait_server_ready(self.role_maker._get_pserver_endpoints()) + if self.is_heter_ps_mode and self.role_maker._get_next_trainers( + ) != []: + wait_server_ready(self.role_maker._get_next_trainers()) + if self.is_heter_ps_mode: + previous_trainers = [] + if self.role_maker._get_previous_trainers() != []: + previous_trainers = self.role_maker._get_previous_trainers() + next_trainers = [] + if self.role_maker._get_next_trainers() != []: + next_trainers = self.role_maker._get_next_trainers() + self._heter_client = HeterClient( + next_trainers, previous_trainers, + self.role_maker._role_id()) # --> HeterClient::GetInstance + + def _init_coordinator(self, scopes=None): + if self._coordinator == None: + self._coordinator = Coordinator(self.string_hosts) + + print(">>> curr node ip: {}".format(self.coordinator_hosts[0])) + print(">>> all trainer endpoints: {}".format(self.trainer_endpoints)) + self._coordinator.start_coordinator(self.coordinator_hosts[0], + self.trainer_endpoints) + + def _make_fl_strategy(self): + if self._coordinator == None: + assert ("Coordinator py object is null!") + else: + self._coordinator.make_fl_strategy() + + def _init_server(self, dirname=None, var_names=None, **kwargs): + server_desc = self.ps_desc_builder.build_server_desc() + trainers = get_trainers(self.role_maker) + if self.is_heter_ps_mode: + trainers += len(self.role_maker._get_heter_worker_endpoints()) + + if self.debug: + print("server_desc: \n{}".format(server_desc)) + + self._server = fluid.core.DistFleetWrapper() + self._server.init_server(server_desc, self.string_hosts, self.role_id, + trainers, self._server_sub_program) + + dist_varnames = get_sparse_tablenames(self.origin_main_programs, True) + sparse_varnames = get_sparse_tablenames(self.origin_main_programs, + False) + + distributed_varnames = dist_varnames + sparse_varnames + + if var_names is None: + load_varnames = distributed_varnames + else: + for var_name in var_names: + if var_name not in distributed_varnames: + raise ValueError( + "fleet.init server can only load sparse variables in {}" + .format(distributed_varnames)) + load_varnames = var_names + + if dirname is None or not load_varnames: + return + + sparse_table_maps = self.ps_desc_builder.sparse_table_maps + + dirname = os.path.normpath(dirname) + pserver_id = self.role_maker._role_id() + + for var_name in load_varnames: + table_id = sparse_table_maps[var_name] + self._server.load_sparse(dirname, "0", table_id) + + def _run_server(self): + ep = get_ps_endpoint(self.role_maker) + host, port = ep.split(":") + self._server.run_server(host, int(port)) + + def _stop_worker(self): + if self.context['ps_mode'] == DistributedMode.GEO: + self._communicator.stop() + self._worker.stop_worker() + if self.is_heter_ps_mode: + assert self._heter_client != None, "heter client should not be None in heterps mode" + self._heter_client.stop() + + @staticmethod + def __exclude_vars(exclude_var_names=[]): + + def is_valid(var): + if var.name in exclude_var_names: + return False + + from .utils.public import _get_varname_parts + origin_varname, _, _ = _get_varname_parts(var.name) + if origin_varname.endswith("@GRAD"): + return False + + if origin_varname.startswith("learning_rate_"): + return False + + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + return is_valid + + def _get_inference_model_path(self, dirname): + if dirname.startswith("afs:") or dirname.startswith("hdfs:"): + model_path = "./dnn_plugin" + else: + model_path = os.path.join(dirname, "dnn_plugin") + return model_path + + def _ps_save_dense_params(self, + executor, + dirname, + scope, + program, + var_names=None): + dense_map = get_the_one_recv_context( + self.context, split_dense_table=self.is_heter_ps_mode) + send_ctx = get_the_one_send_context( + self.context, + split_dense_table=self.is_heter_ps_mode, + ep_list=self.endpoints) + if program is None or len(self.origin_main_programs) == 1: + program = self.origin_main_programs[0] + dense_var_names = self._pull_dense(program, scope, send_ctx, dense_map) + save_var_names = dense_var_names if var_names is None else var_names + vars = [program.global_block().var(i) for i in save_var_names] + import paddle + with paddle.static.scope_guard(scope): + paddle.static.save_vars(executor, + "./", + program, + vars=vars, + filename=dirname) + + def _save_sparse_params(self, executor, dirname, context, main_program, + mode): + distributed_varnames = get_sparse_tablenames(self.origin_main_programs, + True) + values = [] + model_path = self._get_inference_model_path(dirname) + for id, names in context.items(): + if names[0] not in distributed_varnames: + # only save sparse param to local + try: + self._worker.recv_and_save_model(id, model_path) + except: + pass + # save sparse & distributed param on server + self._worker.save_one_model(id, dirname, mode) + values.extend(names) + # self._worker.save_all_model(dirname, mode) + return values + + def _save_distributed_persistables(self, + executor, + dirname, + main_program=None, + mode=0, + **kwargs): + """ + This function filters out all variables with `persistable==True` from the + give `main_program` and then saves these variables to the folder `dirname` + or file `filename`. + + The `dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set `filename` None; if you would like to save all variables in a + single file, use `filename` to specify the file name. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type") + + if main_program is None: + main_program = self.context['origin_main_program'] + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + self._worker.save_all_model(dirname, mode) + + def _ps_inference_save_inference_model(self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True, + mode=0): + """ + Prune the given `main_program` to build a new program especially for inference, + and then save it and all related parameters to given `dirname` by the `executor`. + """ + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save() function, executor must be as Executor type") + + import paddle + program = self.origin_main_programs[ + 0] if main_program is None else main_program + _, _, idx = get_program_by_id(self.context, id(program)) + scope = self.scopes[idx] + print("save inference model scope idx:", idx) + + if isinstance(program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + feed_vars = [ + program.global_block().var(name) for name in feeded_var_names + ] + + infer_program = paddle.static.normalize_program(program, feed_vars, + target_vars) + + infer_program._copy_dist_param_info_from(program) + + model_path = self._get_inference_model_path(dirname) + model_basename = "__model__" + model_basename = os.path.join(model_path, model_basename) + paddle.save(infer_program, model_basename) + + sparses = get_the_one_recv_context( + self.context, + is_dense=False, + split_dense_table=self.is_heter_ps_mode) + sparse_names = self._save_sparse_params(executor, dirname, sparses, + main_program, mode) + + dense_map = get_the_one_recv_context( + self.context, split_dense_table=self.is_heter_ps_mode) + send_ctx = get_the_one_send_context( + self.context, + split_dense_table=self.is_heter_ps_mode, + ep_list=self.endpoints) + self._pull_dense(program, scope, send_ctx, dense_map) + + generate_vars = self.context[ + "user_defined_strategy"].trainer_desc_configs["stat_var_names"] + generate_vars = [var for var in generate_vars] + remaining_vars = list( + filter(TheOnePSRuntime.__exclude_vars(sparse_names), + infer_program.list_vars())) + + for var in remaining_vars: + tensor = var.get_value(scope) + paddle.save(tensor, + os.path.join(model_path, var.name), + use_binary_format=True) + + def _save_cache_model(self, dirname, **kwargs): + mode = kwargs.get("mode", 1) + table_id = kwargs.get("table_id", 0) + self._worker.client_flush() + fleet.util.barrier() + cache_threshold = 0.0 + + if self.role_maker._is_first_worker(): + cache_threshold = self._worker.get_cache_threshold(table_id) + #check cache threshold right or not + fleet.util.barrier() + + if self.role_maker._is_first_worker(): + self._worker.cache_shuffle(table_id, dirname, mode, cache_threshold) + + fleet.util.barrier() + + feasign_num = -1 + if self.role_maker._is_first_worker(): + feasign_num = self._worker.save_cache(table_id, dirname, mode) + + fleet.util.barrier() + return feasign_num + + def _check_save_pre_patch_done(self): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._worker.check_save_pre_patch_done() + fleet.util.barrier() + + def _load_sparse_params(self, dirname, context, main_program, mode): + distributed_varnames = get_sparse_tablenames(self.origin_main_programs, + True) + values = [] + for id, names in context.items(): + if names[0] not in distributed_varnames: + # TODO: only load sparse param from local + warnings.warn("varname is not in distributed_varnames, pass") + # load sparse & distributed param on server + self._worker.load_one_table(id, dirname, mode) + values.extend(names) + return values + + def _ps_inference_load_inference_model(self, + dirname, + mode=0, + main_program=None): + main_program = self.origin_main_programs[ + 0] if main_program is None else main_program + _, _, idx = get_program_by_id(self.context, id(main_program)) + scope = self.scopes[idx] + print("load inference model scope idx:", idx) + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + sparses = get_the_one_recv_context( + self.context, + is_dense=False, + split_dense_table=self.is_heter_ps_mode) + + sparse_varnames = self._load_sparse_params(dirname, sparses, + main_program, mode) + + dense_map = get_the_one_recv_context( + self.context, split_dense_table=self.is_heter_ps_mode) + send_ctx = get_the_one_send_context( + self.context, + split_dense_table=self.is_heter_ps_mode, + ep_list=self.endpoints) + + recv_dense_varnames = [] + for _, names in dense_map.items(): + recv_dense_varnames.extend(names) + + loaded_varnames = sparse_varnames + + remaining_vars = list( + filter(TheOnePSRuntime.__exclude_vars(loaded_varnames), + main_program.list_vars())) + + model_path = self._get_inference_model_path(dirname) + import paddle + for var in remaining_vars: + if var.name not in recv_dense_varnames: + continue + tensor = paddle.load(os.path.join(model_path, var.name)) + var.set_value(tensor, scope) + + self._init_params(main_program, scope, send_ctx, dense_map) + + def _save_one_table(self, table_id, path, mode): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._worker.save_one_model(table_id, path, mode) + fleet.util.barrier() + + def _save_dense_params(self, *args, **kwargs): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._ps_save_dense_params(*args, **kwargs) + fleet.util.barrier() + + def _save_persistables(self, *args, **kwargs): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._save_distributed_persistables(*args, **kwargs) + fleet.util.barrier() + + def _save_inference_model(self, *args, **kwargs): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._ps_inference_save_inference_model(*args, **kwargs) + fleet.util.barrier() + + def _load_one_table(self, table_id, path, mode): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._worker.load_one_table(table_id, path, mode) + fleet.util.barrier() + + def _load_persistables(self, path, mode): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._worker.load_model(path, mode) + fleet.util.barrier() + + def _load_inference_model(self, path, mode): + fleet.util.barrier() + if self.role_maker._is_first_worker(): + self._ps_inference_load_inference_model(path, mode) + fleet.util.barrier() + + def _shrink(self, threshold=None): + if threshold is not None: + warnings.warn( + "The param threshold is not used in MemorySparseTable, if you need to shrink, please set the config of accessor" + ) + else: + threshold = 0 + + fleet.util.barrier() + if self.role_maker._is_first_worker(): + sparses = get_the_one_recv_context( + self.context, + is_dense=False, + split_dense_table=self.role_maker. + _is_heter_parameter_server_mode) + + for id, names in sparses.items(): + self._worker.shrink_sparse_table(id, threshold) + fleet.util.barrier() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf5c1e3ec0315397d52c93cfb4eb2b01c3ccb4e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_factory.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022 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. + +import paddle +from .ps_program_builder import * +from .public import * + +__all__ = [ + 'PsProgramBuilder', 'GeoPsProgramBuilder', 'CpuSyncPsProgramBuilder', + 'CpuAsyncPsProgramBuilder', 'GpuPsProgramBuilder', + 'HeterAsyncPsProgramBuilder', 'FlPsProgramBuilder', 'NuPsProgramBuilder' +] + + +class PsProgramBuilderFactory(object): + + def __init__(self): + pass + + def _create_ps_program_builder(self, pass_ctx): + attrs = pass_ctx._attrs + if attrs['ps_mode'] == DistributedMode.GEO: + if len(attrs['local_sparse']) != 0: + return globals()['NuPsProgramBuilder'](pass_ctx) + else: + return globals()['GeoPsProgramBuilder'](pass_ctx) + elif attrs['use_ps_gpu']: + return globals()['GpuPsProgramBuilder'](pass_ctx) + elif attrs['is_heter_ps_mode'] and not attrs['is_fl_ps_mode']: + return globals()['HeterAsyncPsProgramBuilder'](pass_ctx) + elif 'is_fl_ps_mode' in attrs and attrs['is_fl_ps_mode']: + return globals()['FlPsProgramBuilder'](pass_ctx) + elif attrs['ps_mode'] == DistributedMode.SYNC: + return globals()['CpuSyncPsProgramBuilder'](pass_ctx) + else: + return globals()['CpuAsyncPsProgramBuilder'](pass_ctx) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_infer_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_infer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..97043fd7ba6885aac81cad5a49924c23c67d4d47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_infer_utils.py @@ -0,0 +1,13 @@ +# Copyright (c) 2022 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_program_builder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_program_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd870ffee5d947bc57b60f5812712047a2bc35c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/ps_program_builder.py @@ -0,0 +1,431 @@ +# Copyright (c) 2022 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. + +import paddle +from .public import * +from paddle.distributed.fleet.base.private_helper_function import wait_server_ready +from paddle.distributed.passes import new_pass, PassContext + + +class PsProgramBuilder(object): + + def __init__(self, pass_ctx): + self.pass_ctx = pass_ctx + self.attrs = self.pass_ctx._attrs + self.loss = self.attrs['loss'] + self.origin_startup_program = self.attrs['origin_startup_program'] + self.main_program = self.attrs['origin_main_programs'] + + self.cloned_main = self.attrs['cloned_main'] + self.cloned_startup = self.attrs['cloned_startup'] + + self.use_ps_gpu = self.attrs['use_ps_gpu'] + self.use_heter_ps = self.attrs['is_heter_ps_mode'] + self.is_worker = self.attrs['is_worker'] + self.is_heter_worker = self.attrs['is_heter_worker'] + self.is_server = self.attrs['is_server'] + self.ps_mode = self.attrs['ps_mode'] + + self.launch_barrier = self.attrs['launch_barrier'] + self.launch_barrier_flag = self.attrs['launch_barrier_flag'] + self.server_endpoints = self.attrs['role_maker']._get_pserver_endpoints( + ) + + def _build_trainer_desc(self): + opt_info = self.loss.block.program._fleet_opt + opt_info = {} if opt_info is None else opt_info + opt_info["trainer"] = opt_info.get("trainer", "MultiTrainer") + opt_info["device_worker"] = opt_info.get("device_worker", "Hogwild") + self.cloned_main._fleet_opt = opt_info + + def _optimize_programs(self): + pass + + def _build_trainer_programs(self): + raise NotImplementedError + + def _build_pserver_programs(self): + is_sgd_adam = False + ops = get_optimize_ops(self.attrs['origin_main_program']) + if len(ops) == 0: + return + add_lr_decay_table_pass = new_pass('add_lr_decay_table_pass', + self.attrs) + add_lr_decay_table_pass.apply([], [], self.pass_ctx) + for op in ops: + if op.type in ["sgd", "adam"]: + is_sgd_adam = True + break + if is_sgd_adam: + return + + def _build_programs(self): + if self.attrs['is_worker']: + self._build_trainer_programs() + fluid.framework.switch_startup_program(self.cloned_startup) + print("fluid.default_startup_program: {}".format( + fluid.default_startup_program)) + # print("ps_program_build before =", id(self.loss.block.program)) + self._build_trainer_desc() + self.loss.block.program = self.cloned_main + # print("ps_program_build after =", id(self.loss.block.program)) + # print("ps_program_build clone after =", id(self.cloned_main)) + # print("ps_program_build after trainer_desc", + # id(self.loss.block.program)) + # print("ps_program build trainer desc", + # self.loss.block.program._fleet_opt) + + elif self.attrs['is_server']: + self._build_pserver_programs() + self.loss.block.program = self.attrs['_main_server'] + fluid.framework.switch_startup_program( + self.attrs['_startup_server']) + + +class GeoPsProgramBuilder(PsProgramBuilder): # 仅 CPU 模式 + + def __init__(self, pass_ctx): + super(GeoPsProgramBuilder, self).__init__(pass_ctx) + if self.ps_mode != DistributedMode.GEO: + raise ValueError("ps mode: {} not matched {}", + format(self.ps_mode, "GeoPsProgramBuilder")) + + def _build_trainer_programs(self): + append_send_ops_pass = new_pass("append_send_ops_pass", self.attrs) + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + self.attrs['origin_main_program'] = self.cloned_main + + if self.launch_barrier and self.launch_barrier_flag: + wait_server_ready(self.server_endpoints) + + def _build_pserver_programs(self): + add_listen_and_serv_pass = new_pass('add_listen_and_serv_pass', + self.attrs) + add_listen_and_serv_pass.apply([self.attrs['_main_server']], [None], + self.pass_ctx) + return + + +class NuPsProgramBuilder(PsProgramBuilder): + + def __init__(self, pass_ctx): + super(NuPsProgramBuilder, self).__init__(pass_ctx) + if not self.attrs['local_sparse']: + raise ValueError("No local sparse params") + + def _build_trainer_programs(self): + add_lr_decay_table_pass = new_pass("add_lr_decay_table_pass", + self.attrs) + add_lr_decay_table_pass.apply([], [], self.pass_ctx) + + distributed_ops_pass = new_pass("distributed_ops_pass", self.attrs) + distributed_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_optimizer_pass = new_pass("delete_optimizer_pass", self.attrs) + delete_optimizer_pass.apply([self.cloned_main], [None], self.pass_ctx) + + append_send_ops_pass = new_pass("append_send_ops_pass", + self.attrs) # fleet->PushDenseVarsAsync + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_extra_optimizer_pass = new_pass("delete_extra_optimizer_pass", + self.attrs) + delete_extra_optimizer_pass.apply([self.attrs['origin_main_program']], + [self.cloned_startup], self.pass_ctx) + + fake_init_ops_pass = new_pass("fake_init_ops_pass", self.attrs) + fake_init_ops_pass.apply([None], [self.cloned_startup], self.pass_ctx) + + append_send_ops_pass = new_pass("append_send_ops_pass", + self.attrs) # communicator->Send + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + self.attrs['origin_main_program'] = self.cloned_main + self.attrs['origin_startup_program'] = self.cloned_startup + + if self.launch_barrier and self.launch_barrier_flag: + wait_server_ready(self.server_endpoints) + + return + + +class CpuSyncPsProgramBuilder(PsProgramBuilder): + + def __init__(self, pass_ctx): + super(CpuSyncPsProgramBuilder, self).__init__(pass_ctx) + if self.ps_mode != DistributedMode.SYNC and self.ps_mode != DistributedMode.ASYNC: + raise ValueError("ps mode: {} not matched {}", + format(self.ps_mode, "PsProgramBuilder")) + + def _build_trainer_programs(self): + # print("build trainer program entry") + # print("before ps program builder program:", self.cloned_main) + add_lr_decay_table_pass = new_pass("add_lr_decay_table_pass", + self.attrs) + add_lr_decay_table_pass.apply([], [], self.pass_ctx) + + # print("before distributed op pass") + distributed_ops_pass = new_pass("distributed_ops_pass", self.attrs) + distributed_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_optimizer_pass = new_pass("delete_optimizer_pass", self.attrs) + delete_optimizer_pass.apply([self.cloned_main], [None], self.pass_ctx) + + append_send_ops_pass = new_pass("append_send_ops_pass", self.attrs) + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_extra_optimizer_pass = new_pass("delete_extra_optimizer_pass", + self.attrs) + delete_extra_optimizer_pass.apply([self.attrs['origin_main_program']], + [self.cloned_startup], self.pass_ctx) + + fake_init_ops_pass = new_pass("fake_init_ops_pass", self.attrs) + fake_init_ops_pass.apply([None], [self.cloned_startup], self.pass_ctx) + + self.attrs['origin_main_program'] = self.cloned_main + self.attrs['origin_startup_program'] = self.cloned_startup + # print("after ps program builder program:", self.cloned_main) + + if self.launch_barrier and self.launch_barrier_flag: + wait_server_ready(self.server_endpoints) + + return + + +class CpuAsyncPsProgramBuilder(CpuSyncPsProgramBuilder): + + def __init__(self, pass_ctx): + super(CpuAsyncPsProgramBuilder, self).__init__(pass_ctx) + + def _build_trainer_desc(self): + opt_info = self.loss.block.program._fleet_opt + opt_info = {} if opt_info is None else opt_info + opt_info["trainer"] = opt_info.get("trainer", "DistMultiTrainer") + opt_info["device_worker"] = opt_info.get("device_worker", + "DownpourLite") + pid = str(id(self.cloned_main)) + program_configs = { + pid: { + 'pull_dense': [], + 'push_dense': [], + 'pull_sparse': [], + 'push_sparse': [] + } + } + dense_table_config = {} + send_ctx = get_the_one_send_context(self.attrs) + recv_ctx = get_the_one_recv_context(self.attrs) + for name, ctx in send_ctx.items(): + if ctx.program_id() != id(self.loss.block.program): + continue + if ctx.is_sparse(): + continue + if not ctx.is_tensor_table(): + program_configs[pid]['pull_dense'].append(ctx.table_id()) + program_configs[pid]['push_dense'].append(ctx.table_id()) + dense_table_config[ctx.table_id()] = recv_ctx[ctx.table_id()] + opt_info['program_configs'] = program_configs + opt_info['dense_table_config'] = dense_table_config + self.cloned_main._fleet_opt = opt_info + + +class GpuPsProgramBuilder(PsProgramBuilder): + + def __init__(self, pass_ctx): + super(GpuPsProgramBuilder, self).__init__(pass_ctx) + + def _build_trainer_programs(self): + + add_lr_decay_table_pass = new_pass("add_lr_decay_table_pass", + self.attrs) + add_lr_decay_table_pass.apply([], [], self.pass_ctx) + + distributed_ops_pass = new_pass("distributed_ops_pass", self.attrs) + distributed_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + fake_init_ops_pass = new_pass("fake_init_ops_pass", self.attrs) + fake_init_ops_pass.apply([None], [self.cloned_startup], self.pass_ctx) + + ps_gpu_pass = new_pass("ps_gpu_pass", self.attrs) + ps_gpu_pass.apply([self.cloned_main], [None], self.pass_ctx) + + ps_transpile_pass = new_pass("ps_transpile_pass", self.attrs) + ps_transpile_pass.apply([self.cloned_main], [self.cloned_startup], + self.pass_ctx) + + self.attrs['origin_main_program'] = self.cloned_main + self.attrs['origin_startup_program'] = self.cloned_startup + + if self.launch_barrier and self.launch_barrier_flag: + wait_server_ready(self.server_endpoints) + + return + + +class HeterAsyncPsProgramBuilder(PsProgramBuilder): + + def __init__(self, pass_ctx): + super(HeterAsyncPsProgramBuilder, self).__init__(pass_ctx) + + def _build_trainer_programs(self): + add_lr_decay_table_pass = new_pass("add_lr_decay_table_pass", + self.attrs) + add_lr_decay_table_pass.apply([], [], self.pass_ctx) + + distributed_ops_pass = new_pass("distributed_ops_pass", self.attrs) + distributed_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_optimizer_pass = new_pass("delete_optimizer_pass", self.attrs) + delete_optimizer_pass.apply([self.cloned_main], [None], self.pass_ctx) + + append_send_ops_pass = new_pass("append_send_ops_pass", self.attrs) + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + delete_extra_optimizer_pass = new_pass("delete_extra_optimizer_pass", + self.attrs) + delete_extra_optimizer_pass.apply([self.attrs['origin_main_program']], + [self.cloned_startup], self.pass_ctx) + + fake_init_ops_pass = new_pass("fake_init_ops_pass", self.attrs) + fake_init_ops_pass.apply([None], [self.cloned_startup], self.pass_ctx) + + if self.is_heter_worker: + split_heter_worker_ops_pass = new_pass( + "split_heter_worker_ops_pass", self.attrs) + split_heter_worker_ops_pass.apply([self.cloned_main], [None], + self.pass_ctx) + else: + split_trainer_ops_pass = new_pass("split_trainer_ops_pass", + self.attrs) + split_trainer_ops_pass.apply([self.cloned_main], [None], + self.pass_ctx) + + set_heter_pipeline_opt_pass = new_pass('set_heter_pipeline_opt_pass', + self.attrs) + set_heter_pipeline_opt_pass.apply([self.cloned_main], + [self.cloned_startup], self.pass_ctx) + + if self.launch_barrier and self.launch_barrier_flag: + wait_server_ready(self.server_endpoints) + + return + + def _build_programs(self): + if self.attrs['is_worker'] or self.attrs['is_heter_worker']: + self._build_trainer_programs() + ps_set_heter_pipeline_opt_pass = new_pass( + "set_heter_pipeline_opt_pass", self.attrs) + ps_set_heter_pipeline_opt_pass.apply([self.cloned_main], + [self.cloned_startup], + self.pass_ctx) + + elif self.attrs['is_server']: + self._build_pserver_programs() + self.loss.block.program = self.attrs['_main_server'] + fluid.framework.switch_startup_program( + self.attrs['_startup_server']) + + +class FlPsProgramBuilder(HeterAsyncPsProgramBuilder): + + def __init__(self, pass_ctx): + super(FlPsProgramBuilder, self).__init__(pass_ctx) + + def _build_trainer_programs(self): + _main_file = ps_log_root_dir + '0_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + distributed_ops_pass = new_pass("distributed_ops_pass", self.attrs) + distributed_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + _main_file = ps_log_root_dir + '1_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + delete_optimizer_pass = new_pass("delete_optimizer_pass", self.attrs) + delete_optimizer_pass.apply([self.cloned_main], [None], self.pass_ctx) + + _main_file = ps_log_root_dir + '2_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + append_send_ops_pass = new_pass("append_send_ops_pass", self.attrs) + append_send_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + _main_file = ps_log_root_dir + '3_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + delete_extra_optimizer_pass = new_pass("delete_extra_optimizer_pass", + self.attrs) + delete_extra_optimizer_pass.apply([self.attrs['origin_main_program']], + [self.cloned_startup], self.pass_ctx) + + _main_file = ps_log_root_dir + '4_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + #fake_init_ops_pass = new_pass("fake_init_ops_pass", self.attrs) + #fake_init_ops_pass.apply([None], [self.cloned_startup], self.pass_ctx) + + _main_file = ps_log_root_dir + '5_fl_worker_main_program.prototxt' + #debug_program(_main_file, self.cloned_main) + + split_trainer_ops_pass = new_pass("split_fl_ops_pass", self.attrs) + split_trainer_ops_pass.apply([self.cloned_main], [None], self.pass_ctx) + + if not self.is_heter_worker: + self.part_a_program = self.pass_ctx._attrs['part_a_main_program'] + self.cloned_main = self.part_a_program + _main_file = ps_log_root_dir + '8_fl_A_main_program.prototxt' + debug_program(_main_file, self.cloned_main) + else: + self.part_b_program = self.pass_ctx._attrs['part_b_main_program'] + self.cloned_main = self.part_b_program + _main_file = ps_log_root_dir + '8_fl_B_main_program.prototxt' + debug_program(_main_file, self.cloned_main) + + set_heter_pipeline_opt_pass = new_pass('set_heter_pipeline_opt_pass', + self.attrs) + set_heter_pipeline_opt_pass.apply([self.cloned_main], + [self.cloned_startup], self.pass_ctx) + + self.attrs['origin_startup_program'] = self.cloned_startup + self.attrs['origin_main_program'] = self.cloned_main + + if not self.is_heter_worker: + _main_file = ps_log_root_dir + 'final_fl_A_main_program.prototxt' + debug_program( + _main_file, self.attrs['origin_main_program']. + _heter_pipeline_opt['section_program']) + else: + _main_file = ps_log_root_dir + 'final_fl_B_main_program.prototxt' + debug_program( + _main_file, self.attrs['origin_main_program']. + _heter_pipeline_opt['section_program']) + + return + + def _build_pserver_programs(self): + self.loss.block.program = self.attrs['_main_server'] + + def _build_programs(self): + if not self.is_server: + self._build_trainer_programs() + fluid.framework.switch_startup_program(self.cloned_startup) + fluid.framework.switch_main_program(self.cloned_main) + print("fluid.default_startup_program: {}".format( + fluid.default_startup_program()._heter_pipeline_opt)) + else: + self._build_pserver_programs() + fluid.framework.switch_startup_program( + self.attrs['_startup_server']) + fluid.framework.switch_main_program(self.attrs['_main_server']) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/public.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/public.py new file mode 100644 index 0000000000000000000000000000000000000000..3b2310f1143af80a654f5012d7ce9c64fefba648 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/ps/utils/public.py @@ -0,0 +1,1618 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function +from functools import reduce + +import collections +import math +import os +import warnings +import logging +import six +import paddle.fluid as fluid +from paddle.fluid import core +import paddle.fluid.framework as framework + +#logging.basicConfig( +# format='%(levelname)s - %(asctime)s - %(pathname)s: %(lineno)s - %(message)s', level=logging.INFO) +#logger = logging.getLogger(__name__) + +OP_NAME_SCOPE = "op_namescope" +CLIP_OP_NAME_SCOPE = "gradient_clip" +STEP_COUNTER = "@PS_STEP_COUNTER@" +LEARNING_RATE_DECAY_COUNTER = "@LR_DECAY_COUNTER@" + +OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName() +RPC_OP_ROLE_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleAttrName() +RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC +op_role = core.op_proto_and_checker_maker.OpRole +op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() +LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched +OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize +backward = core.op_proto_and_checker_maker.OpRole.Backward +OP_DEVICE_KEY = core.op_proto_and_checker_maker.kOpDeviceAttrName() + +DEVICE_LIST = ["cpu", "gpu", "xpu"] +COMMUNICATE_OPS_TYPE = ["send", "recv", "fetch_barrier", "send_barrier"] +SPARSE_OP_LIST = ["lookup_table", "lookup_table_v2"] +SPARSE_OP_TYPE_DICT = {"lookup_table": "W", "lookup_table_v2": "W"} +SPARSE_GRAD_OP_TYPE_DICT = { + "lookup_table_grad": "W", + "lookup_table_v2_grad": "W" +} +DEFAULT_DEVICE = 'cpu' + +DATA_NORM_NAME = [".batch_size", ".batch_sum", ".batch_square_sum"] +DATA_NORM_GRAD_NAME = [x + "@GRAD" for x in DATA_NORM_NAME] + + +def logger_config(log_path, logging_name): + logger = logging.getLogger(logging_name) + logger.setLevel(level=logging.WARNING) + handler = logging.FileHandler(log_path, + mode='a', + encoding='UTF-8', + delay=True) + handler.setLevel(logging.INFO) + formatter = logging.Formatter( + '%(levelname)s - %(asctime)s - %(pathname)s: %(lineno)s - %(message)s') + handler.setFormatter(formatter) + console = logging.StreamHandler() + console.setLevel(logging.DEBUG) + logger.addHandler(handler) + logger.addHandler(console) + return logger + + +ps_log_root_dir = './ps_log/' +logger = logger_config(log_path='./ps_usr_print_log', + logging_name='ps_usr_print_log') + + +class DistributedMode: + SYNC = 0 + ASYNC = 1 + HALF_ASYNC = 2 + GEO = 3 + FL = 4 + NU = 5 + + +class TrainerRuntimeConfig(object): + + def __init__(self, valid_strategy): + self.mode = None + num_threads = os.getenv("CPU_NUM", "1") + send_queue_size = num_threads + k_steps = valid_strategy.a_sync_configs["k_steps"] + + if not valid_strategy.a_sync and k_steps == 0: + self.mode = DistributedMode.SYNC + + if valid_strategy.a_sync and k_steps == 0: + self.mode = DistributedMode.ASYNC + + if valid_strategy.a_sync and k_steps > 0: + self.mode = DistributedMode.GEO + send_queue_size = k_steps + + self.runtime_configs = {} + self.runtime_configs['communicator_max_merge_var_num'] = os.getenv( + "FLAGS_communicator_max_merge_var_num", send_queue_size) + self.runtime_configs['communicator_send_queue_size'] = os.getenv( + "FLAGS_communicator_send_queue_size", send_queue_size) + self.runtime_configs[ + 'communicator_independent_recv_thread'] = os.getenv( + "FLAGS_communicator_independent_recv_thread", "1") + self.runtime_configs[ + 'communicator_min_send_grad_num_before_recv'] = os.getenv( + "FLAGS_communicator_min_send_grad_num_before_recv", num_threads) + self.runtime_configs['communicator_thread_pool_size'] = os.getenv( + "FLAGS_communicator_thread_pool_size", "5") + self.runtime_configs['communicator_send_wait_times'] = os.getenv( + "FLAGS_communicator_send_wait_times", "5") + self.runtime_configs['communicator_is_sgd_optimizer'] = os.getenv( + "FLAGS_communicator_is_sgd_optimizer", "1") + + def get_communicator_flags(self): + need_keys = [] + num_threads = os.getenv("CPU_NUM", "1") + mode_str = "" + if self.mode is None or self.mode == DistributedMode.ASYNC: + need_keys = self.runtime_configs.keys() + mode_str = "async" + elif self.mode == DistributedMode.SYNC or self.mode == DistributedMode.HALF_ASYNC: + mode_str = "sync or half_async" + need_keys = [ + 'communicator_max_merge_var_num', + 'communicator_send_wait_times', 'communicator_thread_pool_size', + 'communicator_send_queue_size' + ] + elif self.mode == DistributedMode.GEO: + mode_str = "GEO" + need_keys = [ + 'communicator_thread_pool_size', 'communicator_send_wait_times', + 'communicator_max_merge_var_num', 'communicator_send_queue_size' + ] + else: + raise ValueError("Unsupported Mode") + + if self.mode == DistributedMode.SYNC or self.mode == DistributedMode.HALF_ASYNC: + max_merge_var_num = self.runtime_configs[ + 'communicator_max_merge_var_num'] + send_queue_size = self.runtime_configs[ + 'communicator_send_queue_size'] + if max_merge_var_num != num_threads: + print( + 'WARNING: In {} mode, communicator_max_merge_var_num ' + 'must be equal to CPU_NUM. But received, ' + 'communicator_max_merge_var_num = {}, CPU_NUM = ' + '{}. communicator_max_merge_var_num will be forced to {}.'. + format(mode_str, max_merge_var_num, num_threads, + num_threads)) + self.runtime_configs[ + 'communicator_max_merge_var_num'] = num_threads + if send_queue_size != num_threads: + print('WARNING: In {} mode, communicator_send_queue_size ' + 'must be equal to CPU_NUM. But received, ' + 'communicator_send_queue_size = {}, CPU_NUM = ' + '{}. communicator_send_queue_size will be forced to {}.'. + format(mode_str, send_queue_size, num_threads, + num_threads)) + self.runtime_configs[ + 'communicator_send_queue_size'] = num_threads + + return dict((key, str(self.runtime_configs[key])) for key in need_keys) + + +def get_lr_ops(program): + lr_ops = [] + for index, op in enumerate(program.global_block().ops): + role_id = int(op.attr(RPC_OP_ROLE_ATTR_NAME)) + if role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) or \ + role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) | \ + int(OPT_OP_ROLE_ATTR_VALUE): + lr_ops.append(op) + return lr_ops + + +def get_optimize_ops(_program, remote_sparse=[]): + block = _program.global_block() + opt_ops = [] + for op in block.ops: + if _is_opt_role_op(op): + if len(remote_sparse) > 0 and op.input( + "Param" + )[0] not in remote_sparse: # for fl: only delete remote sparse optimize + continue + # delete clip op from opt_ops when run in Parameter Server mode + if OP_NAME_SCOPE in op.all_attrs() \ + and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE): + op._set_attr( + "op_role", + int(core.op_proto_and_checker_maker.OpRole.Backward)) + continue + opt_ops.append(op) + return opt_ops + + +def get_datanorm_ops(_program): + block = _program.global_block() + opt_ops = [] + for op in block.ops: + if op.type == 'data_norm': + opt_ops.append(op) + return opt_ops + + +def get_dist_env(): + trainer_id = int(os.getenv('PADDLE_TRAINER_ID', '0')) + trainer_endpoints = '' + current_endpoint = '' + num_trainers = 0 + if os.getenv('PADDLE_TRAINER_ENDPOINTS'): + trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS') + current_endpoint = trainer_endpoints.split(',')[trainer_id] + num_trainers = len(trainer_endpoints.split(',')) + + return { + 'trainer_id': trainer_id, + 'num_trainers': num_trainers, + 'current_endpoint': current_endpoint, + 'trainer_endpoints': trainer_endpoints + } + + +def get_role_id(role_maker): + try: + return role_maker._role_id() + except Exception: + return role_maker.role_id() + + +def get_ps_endpoint(role_maker): + try: + return role_maker._get_pserver_endpoints()[get_role_id(role_maker)] + except Exception: + return role_maker.get_pserver_endpoints()[get_role_id(role_maker)] + + +def get_ps_endpoints(role_maker): + try: + return role_maker._get_pserver_endpoints() + except Exception: + return role_maker.get_pserver_endpoints() + + +def get_heter_worker_endpoint(role_maker): + return role_maker._get_heter_worker_endpoint() + + +def get_trainer_endpoint(role_maker): + return role_maker._get_trainer_endpoint() + + +def get_trainer_endpoints(role_maker): + return role_maker._get_trainer_endpoints() + + +def get_previous_stage_trainers(role_maker): + try: + return role_maker._get_previous_trainers() + except Exception: + return role_maker.get_previous_trainers() + + +def is_distributed_sparse_op(op): + if op.type in SPARSE_OP_LIST and op.attr('is_distributed') is True: + return True + + if op.type == "distributed_lookup_table" and op.attr( + 'is_distributed') is True: + return True + + return False + + +def get_sparse_tablename(op): + return op.input("W")[0] + + +def is_sparse_op(op): + if op.type in SPARSE_OP_LIST and op.attr('is_sparse') is True and op.attr( + 'is_distributed') is False: + return True + + if op.type == "distributed_lookup_table" and op.attr( + 'is_distributed') is False: + return True + + return False + + +def get_sparse_tablenames(programs, is_distributed): + tablenames = set() + for program in programs: + if is_distributed: + for op in program.global_block().ops: + if is_distributed_sparse_op(op): + tablenames.add(get_sparse_tablename(op)) + else: + for op in program.global_block().ops: + if is_sparse_op(op): + tablenames.add(get_sparse_tablename(op)) + return list(tablenames) + + +def get_trainers(role_maker): + try: + return role_maker._worker_num() + except Exception: + return role_maker.worker_num() + + +def get_dense_send_context(program, + send_ctx, + idx, + merged_dense_pairs, + trainer_id, + split_dense_table=False): + if len(merged_dense_pairs) < 1: + return idx + if not split_dense_table: + dense_pairs = [] + data_norm_pairs = [] + for merged in merged_dense_pairs: + is_data_norm = False + grad = merged[1] + varname = grad.merged_var.name + for name in DATA_NORM_GRAD_NAME: + if varname.endswith(name): + is_data_norm = True + if is_data_norm: + data_norm_pairs.append(merged) + else: + dense_pairs.append(merged) + + # simple dense table + origin_varnames = [] + var_numel = 0 + for merged in dense_pairs: + grad = merged[1] + origin_varnames.append(grad.merged_var.name) + var = program.global_block().vars[grad.merged_var.name] + var_numel += reduce(lambda x, y: x * y, var.shape) + grad_name = "Dense@GRAD_" + str(idx) + aggregate = True + # print("public get_dense_send_context dense_table:", grad_name, + # var_numel, origin_varnames) + from paddle.fluid.core import CommContext + dense_ctx = CommContext(grad_name, [grad_name], ["127.0.0.1:6071"], + [var_numel], origin_varnames, trainer_id, + aggregate, False, False, idx, False, False, + id(program), []) + send_ctx[grad_name] = dense_ctx + idx += 1 + + if len(data_norm_pairs) <= 0: + return idx + + # data norm table + origin_varnames = [] + var_numel = 0 + for merged in data_norm_pairs: + grad = merged[1] + origin_varnames.append(grad.merged_var.name) + var = program.global_block().vars[grad.merged_var.name] + var_numel += reduce(lambda x, y: x * y, var.shape) + grad_name = "DataNorm@GRAD_" + str(idx) + aggregate = True + # print("public get_dense_send_context data_norm table:", grad_name, + # var_numel, origin_varnames) + from paddle.fluid.core import CommContext + data_norm_ctx = CommContext(grad_name, [grad_name], ["127.0.0.1:6071"], + [var_numel], origin_varnames, trainer_id, + aggregate, False, False, idx, False, True, + id(program), []) + send_ctx[grad_name] = data_norm_ctx + idx += 1 + else: + for merged in merged_dense_pairs: + grad = merged[1] + origin_varname = grad.merged_var.name + var = program.global_block().vars[origin_varname] + var_numel = reduce(lambda x, y: x * y, var.shape) + grad_name = origin_varname + aggregate = True + from paddle.fluid.core import CommContext + dense_ctx = CommContext(grad_name, [grad_name], ["127.0.0.1:6071"], + [var_numel], [origin_varname], trainer_id, + aggregate, False, False, idx, False, False, + id(program), []) + send_ctx[grad_name] = dense_ctx + idx += 1 + return idx + + +def get_geo_trainer_send_context(attrs): + if attrs['ps_mode'] != DistributedMode.GEO: + raise ValueError("ps mode: {} not matched {}", + format(ps_mode, "get_geo_trainer_send_context")) + send_ctx = {} + trainer_id = get_role_id(attrs['role_maker']) + origin_programs = attrs['origin_main_programs'] + idx = 0 # table idx + + distibuted_varnames = get_sparse_tablenames(origin_programs, True) + for i, program in enumerate(origin_programs): + merged_sparse_pairs = attrs['merged_sparse_pairs'][i] + for merged in merged_sparse_pairs: + param, grad = merged + grad_name = grad.merged_var.name + param_name = param.merged_var.name + if param_name in attrs['remote_sparse']: # for recall/ncf model + continue + + is_distributed = True if param_name in distibuted_varnames else False + var = program.global_block().vars[grad.merged_var.name] + var_numel = reduce(lambda x, y: x * y, var.shape[1:]) + from paddle.fluid.core import CommContext + print("public get_the_geo_send_context sparse: ", grad_name, + var_numel) + sparse_ctx = CommContext(grad_name, [grad_name], ["127.0.0.1:6071"], + [var_numel], [grad_name], trainer_id, True, + True, is_distributed, idx, False, False, + id(program), []) + idx += 1 + send_ctx[sparse_ctx.var_name()] = sparse_ctx + + if len(send_ctx) == 0: + raise ValueError("GeoSGD require sparse parameters in your net.") + + if len(attrs['tensor_table']) > 0 and attrs['is_worker']: + name, ctx = _step_ctx(idx, attrs['role_maker']) + send_ctx[name] = ctx + + return send_ctx + + +def _step_ctx(idx, role_maker): + name = STEP_COUNTER + trainer_id = get_role_id(role_maker) + endpoints = get_ps_endpoints(role_maker) + sections = [1] * len(endpoints) + names = [name] * len(endpoints) + from paddle.fluid.core import CommContext + ctx = CommContext(name, names, endpoints, sections, [name], trainer_id, + True, False, False, idx, True, False, -1, []) + return name, ctx + + +def get_the_one_send_context(attrs, split_dense_table=False, ep_list=None): + if ep_list is None: + ep_list = ["127.0.0.1:6071"] + send_ctx = {} + trainer_id = get_role_id(attrs['role_maker']) + origin_programs = attrs['origin_main_programs'] + print("is_heter_ps_mode? {}".format(split_dense_table)) + + idx = 0 + distibuted_varnames = get_sparse_tablenames(origin_programs, True) + # print("public distibuted_varnames:", distibuted_varnames) + for i, program in enumerate(origin_programs): + merged_sparse_pairs = attrs['merged_sparse_pairs'][i] + for merged in merged_sparse_pairs: + param, grad = merged + grad_name = grad.merged_var.name + param_name = param.merged_var.name + + remote_sparse_ids = [] + if param_name in attrs['remote_sparse']: # for recall/ncf model + remote_sparse_ids.append(idx) + + splited_varname = [] + for i in range(len(ep_list)): + splited_varname.append("{}.block{}".format(param_name, i)) + + is_distributed = True if param_name in distibuted_varnames else False + + var = program.global_block().vars[grad.merged_var.name] + + shape = list(var.shape) + shape[0] = 0 if is_distributed else shape[0] + + if grad_name in send_ctx: + continue + from paddle.fluid.core import CommContext + print("public get_the_one_send_context sparse: ", grad_name, + splited_varname, shape) + sparse_ctx = CommContext(grad_name, splited_varname, ep_list, shape, + [grad_name], trainer_id, True, True, + is_distributed, idx, False, False, + id(program), remote_sparse_ids) + + idx += 1 + send_ctx[sparse_ctx.var_name()] = sparse_ctx + + for i, program in enumerate(origin_programs): + merged_dense_pairs = attrs['merged_dense_pairs'][i] + idx = get_dense_send_context(program, send_ctx, idx, merged_dense_pairs, + trainer_id, split_dense_table) + + if len(attrs['tensor_table']) > 0 and attrs['is_worker']: + name, ctx = _step_ctx(idx, attrs['role_maker']) + send_ctx[name] = ctx + + return send_ctx + + +def find_heter_ops(program, default_device="cpu"): + if default_device not in DEVICE_LIST: + raise ValueError("Given device {} is not in device list {}".format( + default_device, DEVICE_LIST)) + + def _is_heter_op(op, current_heter_device, default_device="cpu"): + heter_devices = list(DEVICE_LIST) + heter_devices.remove(default_device) + op_device = op.attr("op_device") + op_type = op.type + if op_device in heter_devices: + return True + elif op_type in COMMUNICATE_OPS_TYPE and current_heter_device != default_device: + # for distributed communciate ops: send & recv & barrier etc. + # Todo: need update this method + #op._set_attr('op_device', current_heter_device) + return True + elif op_device == None or op_device == default_device: + op._set_attr('op_device', default_device) + return False + return False + + def _is_same_device(op, pre_device, default_device="cpu"): + op_device = op.attr("op_device") + if op_device == pre_device: + return True + if pre_device == default_device: + return True + return False + + def _append_heter_op(op, current_heter_block_ops, heter_ops): + op_device = op.attr("op_device") + if op_device not in heter_ops: + heter_ops[op_device] = {} + current_heter_block_ops.append(op) + + origin_porgram = program.clone() + block = program.global_block() + ''' + re-place sum op to fix bug for union forward backward op + ''' + var2idx = {} + op_list = list(block.ops) + op_size = len(op_list) + + for i in range(op_size - 1, -1, -1): + op_list = list(block.ops) + op = op_list[i] + if "_grad" in op.type: + forward_op_type = op.type.split("_grad")[0] + if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[forward_op_type])[0] + if param_name in var2idx: + ## insert sum op & remove sum op from var2idx and origin place + op_list = list(block.ops) + sum_op = op_list[var2idx[param_name]] + sum_op_inputs = { + sum_op.input_names[0]: + [block.vars[input] for input in sum_op.input_arg_names] + } + sum_op_outputs = { + sum_op.output_names[0]: [ + block.vars[output] + for output in sum_op.output_arg_names + ] + } + block._insert_op(index=i + 1, + type=sum_op.type, + inputs=sum_op_inputs, + outputs=sum_op_outputs, + attrs=sum_op.all_attrs()) + block._remove_op(var2idx[param_name] + 1) + var2idx.pop(param_name) + for var_ in var2idx: + var2idx[var_] += 1 + elif forward_op_type == "elementwise_mul": + """ + get output varname of pre op + + """ + output_vars_no_grad = [] + for key in op.output_names: + for varname in op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + output_vars_no_grad.append(varname.split("@GRAD")[0]) + for no_grad_var in output_vars_no_grad: + if no_grad_var in var2idx: + """ + insert sum op & remove sum op from var2idx and origin place + + """ + op_list = list(block.ops) + sum_op = op_list[var2idx[no_grad_var]] + sum_op_inputs = { + sum_op.input_names[0]: [ + block.vars[input] + for input in sum_op.input_arg_names + ] + } + sum_op_outputs = { + sum_op.output_names[0]: [ + block.vars[output] + for output in sum_op.output_arg_names + ] + } + block._insert_op(index=i + 1, + type=sum_op.type, + inputs=sum_op_inputs, + outputs=sum_op_outputs, + attrs=sum_op.all_attrs()) + block._remove_op(var2idx[no_grad_var] + 1) + var2idx.pop(no_grad_var) + for var_ in var2idx: + var2idx[var_] += 1 + else: + if op.type == "sum": + var = op.output("Out")[0] + if "@GRAD" in var: + origin_var = var.split("@GRAD")[0] + pre_op = op_list[i - 1] + if "_grad" in pre_op.type: + forward_op_type = pre_op.type.split("_grad")[0] + if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ + and pre_op.attr('remote_prefetch') is True: + param_name = pre_op.input( + SPARSE_OP_TYPE_DICT[forward_op_type])[0] + if param_name == origin_var and op.attr( + "op_device") == pre_op.attr("op_device"): + continue + else: + var2idx[origin_var] = i + elif forward_op_type == "elementwise_mul": + output_vars = [] + for key in pre_op.output_names: + for varname in pre_op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + output_vars.append(varname) + input_vars = [] + for key in op.input_names: + for varname in op.input(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + input_vars.append(varname) + is_match = False + for varname in output_vars: + if varname in input_vars: + is_match = True + break + if is_match: + continue + else: + var2idx[origin_var] = i + else: + var2idx[origin_var] = i + + origin_porgram = program.clone() + block = program.global_block() + + program_block_ops = [] + default_ops = {default_device: {}} + heter_ops = {} + block_index = 0 + + current_heter_block_ops = [] + current_default_block_ops = [] + current_heter_device = default_device + is_heter = False + for op in block.ops: + if _is_heter_op(op, current_heter_device, default_device): + # for gpu/xpu-op + is_heter = True + + # for cpu-op block append + if len(current_default_block_ops) > 1: + default_ops[default_device][ + block_index] = current_default_block_ops + program_block_ops.append(current_default_block_ops) + current_default_block_ops = [] + block_index += 1 + + if _is_same_device(op, current_heter_device, default_device): + # for gpu-op, gpu-op -> gpu-op,... + current_heter_device = op.attr("op_device") + _append_heter_op(op, current_heter_block_ops, heter_ops) + else: + # for gpu-op -> xpu-op, ... + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + block_index += 1 + current_heter_block_ops = [] + current_heter_device = op.attr("op_device") + _append_heter_op(op, current_heter_block_ops, heter_ops) + + elif is_heter: + # for gpu/xpu-op -> cpu-op + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + block_index += 1 + current_heter_block_ops = [] + current_heter_device = default_device + is_heter = False + current_default_block_ops.append(op) + else: + # for cpu-op + current_default_block_ops.append(op) + + if current_default_block_ops != []: + default_ops[default_device][block_index] = current_default_block_ops + program_block_ops.append(current_default_block_ops) + + if current_heter_block_ops != []: + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + + if len(heter_ops) == 0: + warnings.warn( + "No heterogeneous OP was found in your program , " + " please using fluid.device_guard() to run OPs on different device." + ) + + total_heter_ops = 0 + heter_blocks = 0 + for device in heter_ops.keys(): + heter_block_dict = heter_ops[device] + heter_blocks += len(heter_block_dict) + for _, heter_block in heter_block_dict.items(): + total_heter_ops += len(heter_block) + print( + "There are {} OPs in your main_program, and contains {} heter-OPs which is made up of {} heter-blocks." + .format(len(block.ops), total_heter_ops, heter_blocks)) + + return origin_porgram, heter_ops, default_ops, program_block_ops + + +def union_forward_gradient_op(program_block_ops_list): + """ + before analyzing the input & output of each block in program_block_list, we should + union the forward op and corresponding gradient op to elimincate the unnecessary variable + transmit + """ + """ + fix for 2emb model, re-place sum op + + """ + block_length = len(program_block_ops_list) + union_program_block_ops_list = [] + assert block_length % 2 != 0, "the length of program_block_ops_list should be odd" + for i in range(0, block_length // 2): + block_op_list = {"forward": program_block_ops_list[i]} + block_op_list.update( + {"backward": program_block_ops_list[block_length - 1 - i]}) + union_program_block_ops_list.append(block_op_list) + + block_op_list = {"forward": [], "backward": []} + for op in program_block_ops_list[block_length // 2]: + if not "_grad" in op.type and not (op.type == "sum"): + block_op_list["forward"].append(op) + else: + block_op_list["backward"].append(op) + union_program_block_ops_list.append(block_op_list) + return union_program_block_ops_list + + +def find_block_joints(program, program_block_ops_list, heter_ops): + block_var_detail = find_entrance_exit_private(program, + program_block_ops_list) + block_var_detail = entrance_exit_check(program, program_block_ops_list, + block_var_detail, heter_ops) + block_var_detail = delete_block_useless_exit(program, + program_block_ops_list, + block_var_detail) + + return block_var_detail + + +def find_ops_list_input_output(program, ops_list): + input_var_list = [] + output_var_list = [] + for op in ops_list: + inputs = _get_input_map_from_op(program.global_block().vars, op) + input_var_list += get_varlist_from_op_map(inputs) + outputs = _get_output_map_from_op(program.global_block().vars, op) + output_var_list += get_varlist_from_op_map(outputs) + + input_var_list = list(set(input_var_list)) + output_var_list = list(set(output_var_list)) + return input_var_list, output_var_list + + +def find_entrance_exit_private(program, program_block_ops_list): + block_var_detail = [] + persistables = [] + for index, block_op_list in enumerate(program_block_ops_list): + ## forward + block_input, block_output = find_ops_list_input_output( + program, block_op_list["forward"]) + persistables = screen_persistables( + program, block_input) + screen_persistables(program, block_output) + # find entrance & exit + block_private_vars = list(set(block_input) & set(block_output)) + block_entrance = list(set(block_input) - set(block_private_vars)) + block_exit = list(set(block_output) - set(block_private_vars)) + detail = { + "forward": { + "entrance": block_entrance, + "exit": block_exit, + "private": block_private_vars, + "persistables": persistables + } + } + + ## backward + bp_block_input, bp_block_output = find_ops_list_input_output( + program, block_op_list["backward"]) + bp_persistables = screen_persistables( + program, bp_block_input) + screen_persistables( + program, bp_block_output) + # find entrance & exit + bp_block_private_vars = list(set(bp_block_input) & set(bp_block_output)) + bp_block_entrance = list( + set(bp_block_input) - set(bp_block_private_vars)) + bp_block_exit = list(set(bp_block_output) - set(bp_block_private_vars)) + detail.update({ + "backward": { + "entrance": bp_block_entrance, + "exit": bp_block_exit, + "private": bp_block_private_vars, + "persistables": bp_persistables + } + }) + block_var_detail.append(detail) + return block_var_detail + + +def entrance_exit_check(program, program_block_ops_list, block_var_detail, + heter_ops): + for index in range(len(block_var_detail) - 1, -1, -1): + if index - 1 < 0: + break + previous_block_exit = block_var_detail[index - 1]["forward"]["exit"] + previous_block_exit.sort() + current_block_entrance = block_var_detail[index]["forward"]["entrance"] + + backward_entrance = block_var_detail[index]["backward"]["entrance"] + + forward_all = block_var_detail[index]["forward"][ + "entrance"] + block_var_detail[index]["forward"][ + "private"] + block_var_detail[index]["forward"]["exit"] + + for var in backward_entrance: + if not ("@GRAD" in var) and not (var in forward_all): + current_block_entrance.append(var) + + current_block_entrance.sort() + + if previous_block_exit == current_block_entrance: + continue + exist_vars = list( + set(previous_block_exit) & set(current_block_entrance)) + need_add_vars = list(set(current_block_entrance) - set(exist_vars)) + # var in different stage should not be ignored, since they are not placed in the same program & device + #need_add_vars = find_need_var_from_previous_block( + # need_add_vars, block_var_detail, index, heter_ops) + + previous_block_private = block_var_detail[index - + 1]["forward"]["private"] + previous_block_entrance = block_var_detail[index - + 1]["forward"]["entrance"] + for var in need_add_vars: + if var not in previous_block_private and var not in previous_block_entrance: + previous_block_entrance.append(var) + previous_block_exit.append(var) + if not var in current_block_entrance: + current_block_entrance.append(var) + + for index in range(0, len(block_var_detail) - 1, 1): + previous_block_exit = block_var_detail[index + 1]["backward"]["exit"] + previous_block_exit.sort() + current_block_entrance = block_var_detail[index]["backward"]["entrance"] + + current_block_entrance.sort() + + if previous_block_exit == current_block_entrance: + continue + exist_vars = list( + set(previous_block_exit) & set(current_block_entrance)) + need_add_vars = list(set(current_block_entrance) - set(exist_vars)) + need_ignore_vars = [] + for var in need_add_vars: + if not "@GRAD" in var: + need_ignore_vars.append(var) + need_add_vars = list( + set(need_add_vars).difference(set(need_ignore_vars))) + previous_block_private = block_var_detail[index + + 1]["backward"]["private"] + previous_block_entrance = block_var_detail[index + + 1]["backward"]["entrance"] + for var in need_add_vars: + if var not in previous_block_private and var not in previous_block_entrance: + previous_block_entrance.append(var) + previous_block_exit.append(var) + return block_var_detail + + +def delete_block_useless_exit(program, program_block_ops_list, + block_var_detail): + ## forward + for index in range(len(block_var_detail)): + if index == len(block_var_detail) - 1: + break + current_block_exit = block_var_detail[index]["forward"]["exit"] + next_block_entrance = block_var_detail[index + 1]["forward"]["entrance"] + need_delete_var = [] + for var in current_block_exit: + if var not in next_block_entrance: + need_delete_var.append(var) + + for var in need_delete_var: + current_block_exit.remove(var) + ## backward + for index in range(len(block_var_detail) - 1, -1, -1): + if index - 1 < 0: + break + current_block_exit = block_var_detail[index]["backward"]["exit"] + next_block_entrance = block_var_detail[index - + 1]["backward"]["entrance"] + need_delete_var = [] + for var in current_block_exit: + if var not in next_block_entrance: + need_delete_var.append(var) + for var in need_delete_var: + current_block_exit.remove(var) + + return block_var_detail + + +def get_communicate_var_info(program, + block_index, + entrance_var_list, + type="forward"): + input_var_reshape_dim = [] + input_var_reshape_name = [] + + if type == "forward": + block_input_var_name = "forward_joint_{}_{}@Heter".format( + block_index - 1, block_index) + else: + block_input_var_name = "backward_joint_{}_{}@Heter".format( + block_index + 1, block_index) + + entrance_var_list.sort() + # input + # Heter_SERVER_BLOCK_index@JOINT_VAR -> slice -> var@Heter_SERVER_BLOCK@INPUT_RESHAPE_VAR -> reshape -> var + for name in entrance_var_list: + var = program.global_block().vars[name] + shape = var.shape + recv_var_dim = -1 * reduce(lambda x, y: x * y, shape) + input_var_reshape_dim.append(recv_var_dim) + input_var_reshape_name.append("{}.input_reshape@Heter".format(name)) + + info = { + "input_var_reshape_dim": input_var_reshape_dim, + "input_var_reshape_name": input_var_reshape_name, + "block_input_var_name": block_input_var_name, + } + + return info + + +def add_vars_by_var_list(var_name_list, origin_program, program, block): + for var_name in var_name_list: + if var_name not in program.global_block( + ).vars and var_name not in block.vars: + var = origin_program.global_block().vars[var_name] + if var.persistable: + program.global_block()._clone_variable(var, + force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + +def _get_output_map_from_op(varmap, op): + """Returns a dict from op output name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.output_names: + vars = [] + for varname in op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def get_varlist_from_op_map(var_map): + var_list = [] + for key, varlist in six.iteritems(var_map): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + var_list.append(var.name) + return var_list + + +def _get_input_map_from_op(varmap, op): + """Returns a dict from op input name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.input_names: + vars = [] + for varname in op.input(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def screen_persistables(program, var_list): + need_remove = [] + for var_name in var_list: + if "@GRAD" in var_name: + if "GRAD" != var_name.split("@")[-1]: + continue + origin_var_name = var_name.split("@GRAD")[0] + var = program.global_block().vars[origin_var_name] + else: + var = program.global_block().vars[var_name] + + if fluid.io.is_persistable(var): + need_remove.append(var_name) + + for var_name in need_remove: + var_list.remove(var_name) + return need_remove + + +def block_append_op(program, origin_program, block, op): + merge_ordereddict = origin_program.global_block().vars.copy() + merge_ordereddict.update(block.vars) + inputs = _get_input_map_from_op(merge_ordereddict, op) + for key, varlist in six.iteritems(inputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var.name not in program.global_block( + ).vars and var.name not in block.vars: + if var.persistable: + program.global_block()._clone_variable( + var, force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + outputs = _get_output_map_from_op(origin_program.global_block().vars, op) + for key, varlist in six.iteritems(outputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var.name not in program.global_block( + ).vars and var.name not in block.vars: + if var.persistable: + program.global_block()._clone_variable( + var, force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + if "_grad" not in op.type: + # for forward op + return block.append_op(type=op.type, + inputs=inputs, + outputs=outputs, + attrs=op.all_attrs()) + else: + # for grad op + op_desc = op.desc + backward = core.op_proto_and_checker_maker.OpRole.Backward + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + + # append grad op + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(op_desc) + new_op_desc._set_attr(RPC_OP_ROLE_ATTR_NAME, backward) + + # set device gard + if op.desc.has_attr(device_attr_name): + op_device = op_desc.attr(device_attr_name) + new_op_desc._set_attr(device_attr_name, op_device) + block._sync_with_cpp() + + +def get_next_stage_trainers(role_maker): + try: + return role_maker._get_next_trainers() + except Exception: + return role_maker.get_next_trainers() + + +def insert_communicate_op(orign_program, + role_maker, + heter_block, + stage_id, + first_op_index, + block_var_detail, + device, + is_forward=True): + + if is_forward: + next_heter_worker_endpoints = get_next_stage_trainers(role_maker) + previous_heter_worker_endpoints = get_previous_stage_trainers( + role_maker) + entrance_var = block_var_detail[stage_id]["forward"]["entrance"] + comm_info = get_communicate_var_info(orign_program, stage_id + 1, + entrance_var) + + else: + next_heter_worker_endpoints = get_next_stage_trainers(role_maker) + previous_heter_worker_endpoints = get_previous_stage_trainers( + role_maker) + entrance_var = block_var_detail[stage_id - 1]["backward"]["exit"] + comm_info = get_communicate_var_info(orign_program, stage_id - 1, + entrance_var, "backward") + + heter_block._insert_op(index=first_op_index, + type="send_and_recv", + inputs={"X": heter_block.vars[entrance_var[0]]}, + outputs={"Out": []}, + attrs={ + "mode": "forward" if is_forward else "backward", + "send_var_name": + entrance_var + ["microbatch_id"], + "recv_var_name": [], + "message_name": + comm_info["block_input_var_name"], + "next_endpoints": next_heter_worker_endpoints, + "previous_endpoints": + previous_heter_worker_endpoints, + "trainer_id": get_role_id(role_maker), + "op_device": device, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return entrance_var + + +def get_the_one_recv_context(context, is_dense=True, split_dense_table=False): + recv_id_maps = {} + grad_name_to_param_name = {} + if is_dense: + send_ctx = get_the_one_send_context(context, + split_dense_table=split_dense_table) + for idx, (name, ctx) in enumerate(send_ctx.items()): + if ctx.is_sparse(): + continue + if ctx.is_tensor_table(): + continue + + origin_grad_varnames = ctx.origin_varnames() + + param_names = [] + for grad_varname in origin_grad_varnames: + param_name = context["grad_name_to_param_name"][grad_varname] + param_names.append(param_name) + recv_id_maps[ctx.table_id()] = param_names + else: + send_ctx = get_the_one_send_context(context, + split_dense_table=False, + ep_list=None) + for idx, (name, ctx) in enumerate(send_ctx.items()): + if not ctx.is_sparse(): + continue + + origin_grad_varnames = ctx.origin_varnames() + + param_names = [] + for grad_varname in origin_grad_varnames: + param_name = context["grad_name_to_param_name"][grad_varname] + param_names.append(param_name) + recv_id_maps[ctx.table_id()] = param_names + return recv_id_maps + + +def _get_varname_parts(varname): + # returns origin, blockid, trainerid + orig_var_name = "" + trainer_part = "" + block_part = "" + trainer_idx = varname.find(".trainer_") + if trainer_idx >= 0: + trainer_part = varname[trainer_idx + 1:] + else: + trainer_idx = len(varname) + block_index = varname.find(".block") + if block_index >= 0: + block_part = varname[block_index + 1:trainer_idx] + else: + block_index = len(varname) + orig_var_name = varname[0:min(block_index, trainer_idx)] + return orig_var_name, block_part, trainer_part + + +dtype_to_size = { + core.VarDesc.VarType.FP16: 2, + core.VarDesc.VarType.FP32: 4, + core.VarDesc.VarType.FP64: 8, + core.VarDesc.VarType.INT16: 2, + core.VarDesc.VarType.INT32: 4, + core.VarDesc.VarType.INT64: 8, + core.VarDesc.VarType.BOOL: 1, + core.VarDesc.VarType.UINT8: 1, +} + + +def get_var_mem_size(var): + m_size = reduce(lambda x, y: x * y, var.shape) + m_size *= dtype_to_size[var.dtype] + return m_size + + +class MergedVariable: + + def __init__(self, merged, ordered, offsets): + self.merged_var = merged + self.ordered_vars = ordered + self.offsets = offsets + + +def build_var_distributed(context): + origin_programs = context['origin_main_programs'] + + param_name_to_grad_name = {} + grad_name_to_param_name = {} + context["origin_sparse_pairs"] = [] + context["origin_dense_pairs"] = [] + context["merged_sparse_pairs"] = [] + context['merged_dense_pairs'] = [] + context["merged_variables_pairs"] = [] + context["merged_variable_map"] = {} + for origin_program in origin_programs: + sparse_pairs, dense_pairs = get_param_grads(origin_program) + #print("public build_var_distributed sparse_pairs:", sparse_pairs) + #print("public build_var_distributed dense_pairs:", dense_pairs) + origin_for_sparse = [] + origin_for_dense = [] + merged_sparse_pairs = [] + merged_dense_pairs = [] + merged_variables_pairs = [] + + for param, grad in sparse_pairs: + origin_for_sparse.append((param, grad)) + + for param, grad in dense_pairs: + origin_for_dense.append((param, grad)) + + for dense_pair in origin_for_dense: + param, grad = dense_pair + + m_param = MergedVariable(param, [param], [0]) + m_grad = MergedVariable(grad, [grad], [0]) + merged_variables_pairs.append((m_param, m_grad)) + merged_dense_pairs.append((m_param, m_grad)) + #print("public build_var_distributed merged_dense_pairs:", + # merged_dense_pairs) + + for sparse_pair in origin_for_sparse: + param, grad = sparse_pair + + m_param = MergedVariable(param, [param], [0]) + m_grad = MergedVariable(grad, [grad], [0]) + merged_variables_pairs.append((m_param, m_grad)) + merged_sparse_pairs.append((m_param, m_grad)) + #print("public build_var_distributed merged_sparse_pairs:", + # merged_sparse_pairs) + + for merged in merged_variables_pairs: + m_param, m_grad = merged + context["merged_variable_map"][ + m_param.merged_var.name] = m_param.merged_var + context["merged_variable_map"][ + m_grad.merged_var.name] = m_grad.merged_var + + param_merges = [] + param_merges.extend(origin_for_sparse) + param_merges.extend(origin_for_dense) + + for param, grad in param_merges: + param_name_to_grad_name[param.name] = grad.name + grad_name_to_param_name[grad.name] = param.name + + context["origin_sparse_pairs"].append(origin_for_sparse) + context["origin_dense_pairs"].append(origin_for_dense) + context["merged_sparse_pairs"].append(merged_sparse_pairs) + context['merged_dense_pairs'].append(merged_dense_pairs) + + context["param_name_to_grad_name"] = param_name_to_grad_name + context["grad_name_to_param_name"] = grad_name_to_param_name + ''' + print("public build_var_distributed origin_sparse_pairs:", + context["origin_sparse_pairs"]) + print("public build_var_distributed origin_for_dense:", + context["origin_dense_pairs"]) + print("public build_var_distributed merged_sparse_pairs:", + context["merged_sparse_pairs"]) + print("public build_var_distributed merged_dense_pairs:", + context['merged_dense_pairs']) + print("public build_var_distributed param_name_to_grad_name:", + param_name_to_grad_name) + print("public build_var_distributed grad_name_to_param_name:", + grad_name_to_param_name) + ''' + + +def _is_opt_role_op(op): + # NOTE : depend on oprole to find out whether this op is for + # optimize + op_maker = core.op_proto_and_checker_maker + optimize_role = core.op_proto_and_checker_maker.OpRole.Optimize + if op_maker.kOpRoleAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(optimize_role): + return True + return False + + +def get_param_grads(origin_program): + + def _get_params_grads(sparse_varnames): + block = origin_program.global_block() + + dense_param_grads = [] + sparse_param_grads = [] + + optimize_params = set() + origin_var_dict = origin_program.global_block().vars + role_id = int(core.op_proto_and_checker_maker.OpRole.Backward) + for op in block.ops: + if _is_opt_role_op(op): + # delete clip op from opt_ops when run in Parameter Server mode + if OP_NAME_SCOPE in op.all_attrs() \ + and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE): + op._set_attr("op_role", role_id) + continue + if op.attr(OP_ROLE_VAR_ATTR_NAME): + param_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[0] + grad_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[1] + if param_name not in optimize_params: + optimize_params.add(param_name) + param_grad = (origin_var_dict[param_name], + origin_var_dict[grad_name]) + + if param_name in sparse_varnames: + sparse_param_grads.append(param_grad) + else: + dense_param_grads.append(param_grad) + return sparse_param_grads, dense_param_grads + + def _get_sparse_varnames(): + varnames = [] + for op in origin_program.global_block().ops: + if op.type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0] + varnames.append(param_name) + + return list(set(varnames)) + + sparse_varnames = _get_sparse_varnames() + sparse_param_grads, dense_param_grads = _get_params_grads(sparse_varnames) + + return sparse_param_grads, dense_param_grads + + +def delete_ops(block, ops): + for op in ops: + try: + idx = list(block.ops).index(op) + block._remove_op(idx) + except Exception as e: + print(e) + + +def find_send_op(program): + send_op_list = [] + for op in program.global_block().ops: + if op.type == "send": + send_op_list.append(op) + return send_op_list + + +def find_op_input_output(program, block, op): + input_var_list = [] + output_var_list = [] + inputs = _get_input_map_from_op(block.vars, op) + input_var_list += get_varlist_from_op_map(inputs) + outputs = _get_output_map_from_op(block.vars, op) + output_var_list += get_varlist_from_op_map(outputs) + input_var_list = list(set(input_var_list)) + output_var_list = list(set(output_var_list)) + return input_var_list, output_var_list + + +def add_send_op(program, block, _vars): + + def _get_send_op_dict(): + send_op_dict = {} + send_op_list = find_send_op(program) + for op in send_op_list: + input_list, _ = find_op_input_output(program, + program.global_block(), op) + for var in input_list: + send_op_dict[var] = op + return send_op_dict + + send_grad_var_list = [] + send_op_dict = _get_send_op_dict() + table_dict = {} + for persistable_var in _vars: + if "@GRAD" not in persistable_var: + continue + if "GRAD" != persistable_var.split("@")[-1]: + continue + if persistable_var not in send_op_dict: + continue + send_op = send_op_dict[persistable_var] + is_sparse = send_op.attr('is_sparse') + table_id = send_op.attr('table_id') + send_varnames = send_op.attr('send_varnames') + send_grad_var_list.append(persistable_var) + if table_id not in table_dict: + table_dict[table_id] = {} + table_dict[table_id]['var_list'] = [] + table_dict[table_id]['is_sparse'] = is_sparse + table_dict[table_id]['send_varnames'] = send_varnames + table_dict[table_id]['var_list'].append(persistable_var) + + for table_id in table_dict: + dummy_output = block.create_var( + name=framework.generate_control_dev_var_name()) + send_input_vars = [ + block.vars[union_var] + for union_var in table_dict[table_id]['var_list'] + ] + block.append_op(type="send", + inputs={"X": send_input_vars}, + outputs={"Out": dummy_output}, + attrs={ + "send_varnames": + table_dict[table_id]['send_varnames'], + "is_sparse": is_sparse, + "table_id": table_id, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return send_grad_var_list + + +def get_vars_name_in_block(block): + vars_list = block.vars.keys() + vars_name_list = [var_name for var_name in vars_list] + return vars_name_list + + +# reserve static_var +def delete_trainer_useless_var(program, static_var): + static_var = list(set(static_var)) + program_useful_var_list = [] + for op in program.global_block().ops: + input_var_list, output_var_list = find_op_input_output( + program, program.global_block(), op) + op_var_list = list(set(input_var_list).union(set(output_var_list))) + program_useful_var_list = list( + set(program_useful_var_list).union(set(op_var_list))) + program_useful_var_list += static_var + program_useless_var_list = list( + set(get_vars_name_in_block(program.global_block())).difference( + set(program_useful_var_list))) + for var in program_useless_var_list: + program.global_block()._remove_var(var) + return program_useless_var_list + + +def create_backward_block(program, origin_program, bp_ops_list, + block_var_detail): + pre_block_idx = program.num_blocks - 1 + heter_block = program._create_block(pre_block_idx) + + for _, op in enumerate(bp_ops_list): + if op.type == "send": + send_varnames = op.attr('send_varnames') + is_skip = False + for varname in send_varnames: + if varname not in program.global_block( + ).vars and varname not in heter_block.vars: + is_skip = True + break + if is_skip == True: + continue + block_append_op(program, origin_program, heter_block, op) + + entrance_vars = block_var_detail[0]["backward"]["entrance"] + add_vars_by_var_list(entrance_vars, origin_program, program, heter_block) + exit_vars = block_var_detail[0]["backward"]["exit"] + add_vars_by_var_list(exit_vars, origin_program, program, heter_block) + return heter_block + + +def is_backward_op(op): + return op_role_attr_name in op.attr_names and ( + int(op.attr(op_role_attr_name)) & int(op_role.Backward)) + + +def is_forward_op(op): + return op_role_attr_name in op.attr_names and (int( + op.attr(op_role_attr_name)) == int(op_role.Forward)) + + +def is_push_sparse_op(op): + return op.type == 'distributed_push_sparse' + + +def get_distributed_push_sparse_op_list(block): + push_sparse_op_list = [] + for op_idx in range(block.desc.op_size()): + op = block.ops[op_idx] + if is_push_sparse_op(op): + push_sparse_op_list.append(op) + return push_sparse_op_list + + +def get_bp_op_list(block): + bp_op_list = [] + for op_idx in range(block.desc.op_size()): + op = block.ops[op_idx] + if is_backward_op(op): + bp_op_list.append(op) + return bp_op_list + + +def delete_same_ops(block, ops): + for op in ops: + try: + for origin_op in block.ops: + if str(origin_op) == str(op): + idx = list(block.ops).index(origin_op) + block._remove_op(idx) + break + except Exception as e: + print(e) + + +def check_program(program): + block_idx = 0 + for block in program.blocks: + for op in block.ops: + input_var_names = op.desc.input_arg_names() + output_var_names = op.desc.output_arg_names() + for var_name in (input_var_names + output_var_names): + if not block._find_var_recursive(str(var_name)): + raise ValueError( + 'var: {} needed by op is not found in block: {}'.format( + str(var_name), block_idx)) + block_idx += 1 + print('program checked valid') + + +def debug_program(file, program): + # py >= 3.2 + os.makedirs(os.path.dirname(file), exist_ok=True) + with open(file, 'w+') as f: + f.write(str(program)) + + +def is_distributed_env(): + node_role = os.getenv("TRAINING_ROLE") + if node_role is None: + return False + else: + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e938c12d5af0ea34af2311e8a3d6ad6c0ff09543 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022 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. + +from .group_sharded import group_sharded_parallel, save_group_sharded_model # noqa: F401 + +__all__ = ['group_sharded_parallel', 'save_group_sharded_model'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/group_sharded.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/group_sharded.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a5bb69f962a45a3f848dcb29c7acfeff675572 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/sharding/group_sharded.py @@ -0,0 +1,280 @@ +# Copyright (c) 2022 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. + +import os +import logging +from enum import Enum + +import paddle + +from paddle.optimizer import Optimizer +from paddle.distributed.utils.log_utils import get_logger +from paddle.fluid.framework import in_dygraph_mode + +# Old version +from paddle.distributed.fleet.meta_optimizers.dygraph_optimizer.sharding_optimizer_stage2 import ( + ShardingOptimizerStage2, +) +from paddle.distributed.fleet.meta_parallel.sharding.sharding_stage2 import ( + ShardingStage2, +) +from paddle.distributed.fleet.meta_parallel.sharding.sharding_stage3 import ( + ShardingStage3, +) +from paddle.distributed.fleet.meta_parallel.sharding.sharding_utils import ( + ShardingScaler, +) + +# New version +from paddle.distributed.fleet.meta_parallel.sharding.group_sharded_optimizer_stage2 import ( + GroupShardedOptimizerStage2, +) +from paddle.distributed.fleet.meta_parallel.sharding.group_sharded_stage2 import ( + GroupShardedStage2, +) +from paddle.distributed.fleet.meta_parallel.sharding.group_sharded_stage3 import ( + GroupShardedStage3, +) +from paddle.distributed.fleet.meta_parallel.sharding.group_sharded_utils import ( + GroupShardedScaler, +) + +logger_ = get_logger(logging.WARNING) + + +def group_sharded_parallel( + model, + optimizer, + level, + scaler=None, + group=None, + offload=False, + sync_buffers=False, + buffer_max_size=2**23, + segment_size=2**20, + sync_comm=False, +): + """ + Use group_sharded_parallel can perform group shared configuration on the model, optimizer and GradScaler. Level has three string options, 'os', 'os_g' and 'p_g_os' corresponds to three different usage scenarios: optimizer state segmentation, optimizer state + gradient segmentation, and parameter + gradient + optimizer state segmentation. + Usually, optimizer state + gradient segmentation is actually a re optimization of optimizer state segmentation, so optimizer state + gradient segmentation can be used to realize optimizer state segmentation. + + Args: + model (Layer): The layer to be wrapped with group_sharded_parallel. + optimizer (Optimizer): The optimizer to be wrapped with group_sharded_parallel. + level (str): The different level of the group sharded. Such as `os`, `os_g`, `p_g_os`. + scaler (GradScaler, optional): If AMP is used, you need to pass GradScaler. Defaults to None, indicating that GradScaler is not used. + group (Group, optional): The group instance. Defaults to None, indicating that the default environment group is used. + offload (bool, optional): Whether to use the offload function. Defaults to False, which means that the offload function is not used. + sync_buffers (bool, optional): Whether to broadcast model buffers. It is generally used when there are registered model buffers. Defaults to False, indicating that model buffers are not used. + buffer_max_size (int, optional): The max size of the buffer used to integrate gradient in `os_g`. The larger the size, the more GPU memory will be used. Defaults to 2**23, which means that the dimension of the buffer is 2**23. + segment_size (int, optional): The smallest size of parameter to be sharded in `p_g_os`. Defaults to 2**20, indicating that the dimension of the minimum segmented parameter is 2**20. + sync_comm (bool, optional): Whether to use synchronous communication, only in `p_g_os` used. Defaults to False, indicating that asynchronous communication is used. + + Returns: + model: A wrapper for group sharded given model. + optimizer: A wrapper for group sharded given optimizer. + scaler: A wrapper for group sharded given scaler. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + from paddle.fluid.dygraph.nn import Linear + from paddle.distributed import fleet + from paddle.distributed.sharding import group_sharded_parallel + + fleet.init(is_collective=True) + group = paddle.distributed.new_group([0, 1]) + model = Linear(1000, 1000) + + clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0) + optimizer = paddle.optimizer.AdamW(learning_rate=0.001, parameters=model.parameters(), weight_decay=0.00001, grad_clip=clip) + + # wrap sharding model, optimizer and scaler + model, optimizer, scaler = group_sharded_parallel(model, optimizer, "p_g", scaler=scaler) + + img, label = data + label.stop_gradient = True + img.stop_gradient = True + + out = model(img) + loss = paddle.nn.functional.cross_entropy(input=out, label=label) + + loss.backward() + optimizer.step() + optimizer.clear_grad() + """ + # check optition type + assert isinstance( + model, paddle.nn.Layer + ), "The model must be the instance of paddle.nn.Layer." + assert isinstance( + optimizer, Optimizer + ), "The optimizer must be the instance of paddle.optimizer.Optimizer." + assert level in [ + 'os', + 'os_g', + 'p_g_os', + ], "The level must be os, os_g or p_g_os." + + def check_dtype(param): + return param.dtype == paddle.float16 + + params_fp16 = list(filter(check_dtype, model.parameters())) + if scaler is None and len(params_fp16) > 0: + raise ValueError("Please enter the correct scaler.") + # convert model/optimizer/scaler + if level in ['os', 'os_g']: + logger_.info("*" * 30) + logger_.info("Sharded level os uses sharded level os_g achieved now.") + logger_.info("*" * 30) + if in_dygraph_mode(): + optimizer = GroupShardedOptimizerStage2( + params=optimizer._parameter_list, + optim=optimizer, + group=group, + offload=offload, + ) + model = GroupShardedStage2( + model, + optimizer, + group=group, + sync_buffers=sync_buffers, + buffer_max_size=buffer_max_size, + ) + else: + optimizer = ShardingOptimizerStage2( + params=model.parameters(), + optim=optimizer, + group=group, + offload=offload, + ) + model = ShardingStage2( + model, + optimizer, + group=group, + sync_buffers=sync_buffers, + buffer_max_size=buffer_max_size, + ) + elif level == 'p_g_os': + if in_dygraph_mode(): + model = GroupShardedStage3( + model, + optimizer=optimizer, + group=group, + sync_buffers=sync_buffers, + segment_size=segment_size, + offload=offload, + sync_comm=sync_comm, + ) + else: + model = ShardingStage3( + model, + optimizer=optimizer, + group=group, + sync_buffers=sync_buffers, + segment_size=segment_size, + offload=offload, + sync_comm=sync_comm, + ) + else: + raise ValueError("Please enter the correct level.") + if isinstance(scaler, paddle.amp.GradScaler): + if in_dygraph_mode(): + scaler = GroupShardedScaler(scaler) + else: + scaler = ShardingScaler(scaler) + logger_.info("*" * 30) + logger_.info( + "If there is a communication hang using group sharded, please check whether the communication operations of each process are unified." + ) + logger_.info("*" * 30) + + return model, optimizer, scaler + + +def save_group_sharded_model(model, output, optimizer=None): + """ + Group sharded encapsulated model and optimizer state saving module. + + Note: + If using save_group_sharded_model saves the model. When loading again, you need to set the model or optimizer state before using group_sharded_parallel. + + Args: + model (Layer): A wrapper for group sharded given model. + output (str): Save directory. + optimizer (Optimizer, optional): Group sharded encapsulated optimizer. Defaults to None, indicating that the optimizer state is not saved. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + from paddle.fluid.dygraph.nn import Linear + from paddle.distributed import fleet + from paddle.distributed.sharding import group_sharded_parallel, save_group_sharded_model + + fleet.init(is_collective=True) + group = paddle.distributed.new_group([0, 1]) + model = Linear(1000, 1000) + + clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0) + optimizer = paddle.optimizer.AdamW(learning_rate=0.001, parameters=model.parameters(), weight_decay=0.00001, grad_clip=clip) + + # wrap sharding model, optimizer and scaler + model, optimizer, scaler = group_sharded_parallel(model, optimizer, "p_g", scaler=scaler) + + img, label = data + label.stop_gradient = True + img.stop_gradient = True + + out = model(img) + loss = paddle.nn.functional.cross_entropy(input=out, label=label) + + loss.backward() + optimizer.step() + optimizer.clear_grad() + + # save model and optimizer state_dict + save_group_sharded_model(model, optimizer, output=output_dir) + """ + logger_.info( + "==========Begin to save group sharded model and optimizer==========" + ) + assert not os.path.isfile( + output + ), "Saving directory ({}) should be a directory, not a file".format(output) + os.makedirs(output, exist_ok=True) + output_model = os.path.join(output, "model.pdmodel") + if isinstance(model, (ShardingStage2, GroupShardedStage2)): + paddle.save(model._layer.state_dict(), output_model) + elif isinstance(model, (ShardingStage3, GroupShardedStage3)): + convert2cpu = True if model._offload else False + model.get_all_parameters(convert2cpu=convert2cpu) + paddle.save(model._layer.state_dict(), output_model) + else: + raise ValueError( + "Please use the layer which is wrapped with group_sharded_parallel." + ) + + if optimizer is not None: + assert hasattr( + optimizer, "_optim" + ), "Please use the optimizer which is wrapped with group_sharded_parallel." + output_opt = os.path.join(output, "model.pdopt") + paddle.save(optimizer._optim.state_dict(), output_opt) + logger_.info( + "==========End to save group sharded model and optimizer==========" + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/spawn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..b7908213c9b51ea98ec9d006ae00bccfb0eddfbd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/spawn.py @@ -0,0 +1,610 @@ +# 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. + +from __future__ import print_function, division + +import multiprocessing +import os +import signal +import six +import sys +import warnings + +from paddle.distributed.utils.launch_utils import _print_arguments, _prepare_trainer_env, get_host_name_ip +from paddle.distributed.cloud_utils import get_cluster_and_pod, _get_trainers_num +from paddle.distributed.fleet.launch import get_cluster_from_args +from paddle.distributed.fleet.cloud_utils import use_paddlecloud +from paddle.distributed.fleet.launch_utils import DeviceMode, check_backend, block_windows_and_macos +from paddle.device import get_device + +# deprecated module import +from paddle.fluid import core +from paddle.fluid.framework import _cpu_num, set_flags + +__all__ = [] + + +class ParallelEnvArgs(object): + + def __init__(self): + # Paddle cluster nodes ips, such as 192.168.0.16,192.168.0.17.. + self.cluster_node_ips = None + + # The current node ip. + self.node_ip = None + + # whether to use paddlecloud platform to run your multi-process job. + # If false, no need to set this argument. + self.use_paddlecloud = None + + # The trainer's started port on a single node + self.started_port = None + + # Print the config or not + self.print_config = True + + # It's for gpu training and the training process will run + # on the selected_devices, each process is bound to a single GPU. + # And if it's not set, this module will use all the gpu cards + # for training. + self.selected_devices = None + + +def _py_supported_check(): + if not sys.version_info >= (3, 4): + raise RuntimeError( + "Use `paddle.distributed.spawn` to start parallel training " + "requires python version greater than 3.4, if your python " + "is lower than this version, please use " + "`paddle.distributed.launch` instead.") + + +def _options_valid_check(options): + # `print_config` keeped as a debug options, not show to users + supported_options = [ + 'start_method', 'ips', 'gpus', 'xpus', 'mlus', 'print_config', 'backend' + ] + deprecated_options = [ + 'selected_devices', 'started_port', 'cluster_node_ips', 'node_ip', + 'use_paddlecloud' + ] + for key in options: + if key not in supported_options: + if key in deprecated_options: + warnings.warn( + "The config option (%s) of `paddle.distributed.spawn` is deprecated. " + "Please use the latest config options stated in the `spawn` API documentation." + % key, DeprecationWarning) + else: + raise ValueError( + "The config option (%s) of `paddle.distributed.spawn` is not supported." + % key) + + +def _get_default_nprocs(): + device = get_device() + if 'gpu' in device: + return core.get_cuda_device_count() + elif 'xpu' in device: + return core.get_xpu_device_count() + elif 'mlu' in device: + return core.get_mlu_device_count() + elif 'cpu' in device: + return multiprocessing.cpu_count() + else: + raise RuntimeError( + "`paddle.distributed.spawn` does not support parallel training on device `{}` now." + .format(device)) + + +def _get_default_backend(): + device = get_device() + if 'gpu' in device: + return 'nccl' + elif 'xpu' in device: + return 'bkcl' + elif 'mlu' in device: + return 'cncl' + elif 'cpu' in device: + return 'gloo' + else: + raise RuntimeError( + "`paddle.distributed.spawn` does not support parallel training on device `{}` now." + .format(device)) + + +def _get_node_ip(ips): + node_ip = None + node_ips = [x.strip() for x in ips.split(',')] + if len(node_ips) == 1: + node_ip = node_ips[0] + else: + _, node_ip = get_host_name_ip() + return node_ip + + +def _get_subprocess_env_list(nprocs, options): + # NOTE (xiongkun03) Why put backend deduction here ? + # Becase _get_subprocess_env_list is used by many testcases. + # So for campability, we put backend deduction here + + # logic for handle backend option + if 'backend' not in options or options['backend'] == 'auto': + options['backend'] = _get_default_backend() + check_backend(options['backend']) + block_windows_and_macos(options['backend']) + + # contruct processes env list + processes_env_list = [] + + # get args from kwargs + args = ParallelEnvArgs() + + # deal with `ips` + args.cluster_node_ips = options.get('ips', None) + if args.cluster_node_ips is None: + args.cluster_node_ips = options.get('cluster_node_ips', None) + if args.cluster_node_ips is None: + args.cluster_node_ips = "127.0.0.1" + + # deal with `gpus` or `xpus` + # set default selected devices(gpus or xpus) + # e.g. if the nprocs is 4, the selected gpus is "0,1,2,3" + # NOTE(chenweihang): [ why not use FLAGS_selected_gpus or FLAGS_selected_xpus directly? ] + # because the FLAGS_selected_gpus or FLAGS_selected_xpus may be used in other place, + # if we set FLAGS_selected_gpus or FLAGS_selected_xpus to be `0,1,2,3`, it may cause error + # when using `ParallelEnv` + # NOTE(chenweihang): use absolute gpu or xpu card id + if options['backend'] == 'nccl': + args.selected_devices = options.get('gpus', None) + if args.selected_devices is None: + args.selected_devices = options.get('selected_devices', None) + env_devices = os.getenv("CUDA_VISIBLE_DEVICES", None) + if env_devices is None or env_devices == "": + env_devices_list = [ + str(x) for x in six.moves.range(core.get_cuda_device_count()) + ] + else: + env_devices_list = env_devices.split(',') + if args.selected_devices is None: + if len(env_devices_list) < nprocs: + raise RuntimeError( + "the number of visible devices(%d) is less than the number " + "of spawn processes(%d), please ensure that the correct " + "`nprocs` argument is passed or the environment variable " + "`CUDA_VISIBLE_DEVICES` is correctly configured." % + (len(env_devices_list), nprocs)) + args.selected_devices = ",".join( + [str(env_devices_list[x]) for x in range(0, nprocs)]) + else: + selected_device_list = args.selected_devices.split(',') + if len(selected_device_list) != nprocs: + raise ValueError( + "The number of selected devices(%s) is not equal to " + "the number of spawn processes(%d), please ensure that the " + "correct `nprocs` and `gpus` arguments are passed." % + (len(selected_device_list), nprocs)) + for card_id in selected_device_list: + if card_id not in env_devices_list: + raise ValueError("The selected gpu card %s cannot found in " + "CUDA_VISIBLE_DEVICES (%s)." % + (card_id, ",".join(env_devices_list))) + + elif options['backend'] == 'bkcl': + args.selected_devices = options.get('xpus', None) + if args.selected_devices is None: + args.selected_devices = options.get('selected_devices', None) + env_devices = os.getenv("XPU_VISIBLE_DEVICES", None) + if env_devices is None or env_devices == "": + env_devices_list = [ + str(x) for x in six.moves.range(core.get_xpu_device_count()) + ] + else: + env_devices_list = env_devices.split(',') + if args.selected_devices is None: + if len(env_devices_list) < nprocs: + raise RuntimeError( + "the number of visible devices(%d) is less than the number " + "of spawn processes(%d), please ensure that the correct " + "`nprocs` argument is passed or the environment variable " + "`XPU_VISIBLE_DEVICES` is correctly configured." % + (len(env_devices_list), nprocs)) + args.selected_devices = ",".join( + [str(env_devices_list[x]) for x in range(0, nprocs)]) + else: + selected_device_list = args.selected_devices.split(',') + if len(selected_device_list) != nprocs: + raise ValueError( + "The number of selected devices(%s) is not equal to " + "the number of spawn processes(%d), please ensure that the " + "correct `nprocs` and `xpus` arguments are passed." % + (len(selected_device_list), nprocs)) + for card_id in selected_device_list: + if card_id not in env_devices_list: + raise ValueError("The selected xpu card %s cannot found in " + "XPU_VISIBLE_DEVICES (%s)." % + (card_id, ",".join(env_devices_list))) + elif options['backend'] == 'cncl': + args.selected_devices = options.get('mlus', None) + if args.selected_devices is None: + args.selected_devices = options.get('selected_devices', None) + env_devices = os.getenv("MLU_VISIBLE_DEVICES", None) + if env_devices is None or env_devices == "": + env_devices_list = [ + str(x) for x in six.moves.range(core.get_mlu_device_count()) + ] + else: + env_devices_list = env_devices.split(',') + if args.selected_devices is None: + if len(env_devices_list) < nprocs: + raise RuntimeError( + "the number of visible devices(%d) is less than the number " + "of spawn processes(%d), please ensure that the correct " + "`nprocs` argument is passed or the environment variable " + "`MLU_VISIBLE_DEVICES` is correctly configured." % + (len(env_devices_list), nprocs)) + args.selected_devices = ",".join( + [str(env_devices_list[x]) for x in range(0, nprocs)]) + else: + selected_device_list = args.selected_devices.split(',') + if len(selected_device_list) != nprocs: + raise ValueError( + "The number of selected devices(%s) is not equal to " + "the number of spawn processes(%d), please ensure that the " + "correct `nprocs` and `mlus` arguments are passed." % + (len(selected_device_list), nprocs)) + for card_id in selected_device_list: + if card_id not in env_devices_list: + raise ValueError("The selected mlu card %s cannot found in " + "MLU_VISIBLE_DEVICES (%s)." % + (card_id, ",".join(env_devices_list))) + elif options['backend'] == 'gloo': + # TODO check gpu / xpu flag must not exist + warnings.warn( + "Your model will be trained under CPUONLY mode by using GLOO," + "because CPUPlace is specified manually or your installed PaddlePaddle only support CPU Device." + ) + args.paddle_cpuonly = True + args.selected_devices = None + args.ips = args.cluster_node_ips + assert options.get( + 'use_paddlecloud', + None) is None, "CPUONLY spawn doesn't support use paddle cloud" + assert len( + args.cluster_node_ips.split(',') + ) <= 1, "CPUONLY spawn only support single trainer, that is len(ips)=1, but got %s." + assert _get_trainers_num( + ) == 1, "CPUONLY spawn doesn't support multi-trainer" + + # set other inner args + args.node_ip = options.get('node_ip', None) + if args.node_ip is None: + args.node_ip = _get_node_ip(args.cluster_node_ips) + + args.started_port = options.get('started_port', None) + + args.use_paddlecloud = options.get('use_paddlecloud', None) + if args.use_paddlecloud is None: + args.use_paddlecloud = use_paddlecloud() + + # get cluster and pod config + if options['backend'] == 'gloo': + devices_per_proc = [x for x in range(0, nprocs)] + cluster, pod = get_cluster_from_args(args, DeviceMode.CPU, + devices_per_proc) + else: + cluster, pod = get_cluster_and_pod(args) + + # prepare subprocess env list + for trainer in pod.trainers: + processes_env_list.append( + _prepare_trainer_env(cluster, trainer, options['backend'])) + + # [Debug] print config + args.print_config = options.get('print_config', False) + if args.print_config: + _print_arguments(args) + + return processes_env_list + + +def _remove_risky_env(): + # remove useless env vars + # no copy, each process will hold env vars itself + os.environ.pop("http_proxy", None) + os.environ.pop("https_proxy", None) + + +def _set_trainer_env(env_dict, backend): + # NOTE(chenweihang): [ Why need set FLAGS_selected_gpus or FLAGS_selected_xpus here? ] + # When the child process starts, it will inherit the configuration of the + # main process and set the FLAGS once, but the environment variable has + # not been set at this time, which leads to the FLAGS_selected_gpus or FLAGS_selected_xpus + # is keep same with mainprocess(usually empty), so manually update the flags here + + # NOTE(xiongkun): why put backend here? because if gloo, we shouldn't set FLAGS_selectedXXX + # + + if backend == 'nccl': + set_flags({'FLAGS_selected_gpus': env_dict['FLAGS_selected_gpus']}) + elif backend == 'bkcl': + set_flags({'FLAGS_selected_xpus': env_dict['FLAGS_selected_xpus']}) + elif backend == 'cncl': + set_flags({'FLAGS_selected_mlus': env_dict['FLAGS_selected_mlus']}) + else: + #NOTE(xiongkun) why not raise Error ? + # So far, we added support for CPU parallel, and will be applied when paddle is not + # compiled with cuda or xp. just do nothing. + pass + + for var_name in env_dict: + os.environ[var_name] = env_dict[var_name] + + +def _func_wrapper(func, args, error_queue, return_queue, env_dict, backend): + try: + # config subprocess environment variables + _remove_risky_env() + _set_trainer_env(env_dict, backend) + # execute function + result = func(*args) + # record function return value + return_queue.put(result) + except KeyboardInterrupt: + pass + except Exception: + import traceback + error_queue.put(traceback.format_exc()) + sys.exit(1) + + +class MultiprocessContext(object): + + def __init__(self, processes, error_queues, return_queues): + _py_supported_check() + self.error_queues = error_queues + # NOTE(chenweihang): The `spawn` method is mainly used + # to wrap the outermost execution function of the program for + # parallel execution. Generally, the return value is not concerned, + # but if the user needs to obtain the return value, users can get + # the return result of each process from context.return_queues + self.return_queues = return_queues + self.processes = processes + self.sentinels = { + process.sentinel: index + for index, process in enumerate(processes) + } + + def join(self, timeout=None): + if len(self.sentinels) == 0: + return True + + ready = multiprocessing.connection.wait(self.sentinels.keys(), + timeout=timeout) + + error_index = None + for sentinel in ready: + index = self.sentinels.pop(sentinel) + process = self.processes[index] + process.join() + if process.exitcode != 0: + error_index = index + break + + if error_index is None: + return len(self.sentinels) == 0 + + for process in self.processes: + if process.is_alive(): + process.terminate() + process.join() + + self._throw_exception(error_index) + + def _throw_exception(self, error_index): + if self.error_queues[error_index].empty(): + exitcode = self.processes[error_index].exitcode + if exitcode < 0: + name = signal.Signals(-exitcode).name + raise Exception("Process %d terminated with signal %s." % + (error_index, name)) + else: + raise Exception("Process %d terminated with exit code %d." % + (error_index, exitcode)) + + original_trace = self.error_queues[error_index].get() + msg = "\n\n----------------------------------------------\n" \ + "Process %d terminated with the following error:\n" \ + "----------------------------------------------\n\n" % error_index + msg += original_trace + raise Exception(msg) + + +def spawn(func, args=(), nprocs=-1, join=True, daemon=False, **options): + """ + Start multiple processes with ``spawn`` method for parallel training. + + .. note:: + ``spawn`` now only supports GPU or XPU or MLU collective mode. The collective mode + of GPU and XPU and MLU cannot be started at the same time, so the option `gpus` and + `xpus` and 'mlus' cannot be configured at the same time. + + Args: + func (function): The target function is called by spawned process. + This function need to be able to pickled, so it must be defined + at the top level of a module. + args (list|tuple, optional): Arguments passed to ``func``. + nprocs (int, optional): Number of processed to start. Default: -1. + when nprocs is -1, the available device will be obtained from + the environment variable when the model is executed: If use GPU, + the currently available device ID is obtained from the environment + variable CUDA_VISIBLE_DEVICES; If use XPU, the currently available + device ID is obtained from the environment variable XPU_VISIBLE_DEVICES. + join (bool, optional): Perform a blocking join on all spawned processes. + Default: True. + daemon (bool, optional): The spawned processes' daemon flag. Default: False. + **options(dict, optional): Other initial parallel execution environment + configuration options. The following options are currently supported: + (1) start_method (string): the way to start a process. + The start method can be ``spawn`` , ``fork`` , ``forkserver`` . + Because the CUDA runtime does not support the ``fork`` start method, + when use CUDA in subprocesses, we should start process by ``spawn`` + or ``forkserver`` method. Default: "spawn" ; + (2) gpus (string): The training process will run on the + selected gpus, such as "0,1,2,3". Default: None; + (3) xpus (string): The training process will run on the + selected xpus, such as "0,1,2,3". Default: None; + (4) mlus (string): The training process will run on the + selected mlus, such as "0,1,2,3". Default: None; + (5) ips (string): Paddle cluster nodes ips, such as + "192.168.0.16,192.168.0.17". Default: "127.0.0.1" . + + Returns: + ``MultiprocessContext`` object, it hold the spawned processes. + + Examples: + .. code-block:: python + + from __future__ import print_function + + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + import paddle.distributed as dist + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear1 = nn.Linear(10, 10) + self._linear2 = nn.Linear(10, 1) + + def forward(self, x): + return self._linear2(self._linear1(x)) + + def train(print_result=False): + # 1. initialize parallel environment + group = dist.init_parallel_env() + process_group = group.process_group if group else None + + # 2. create data parallel layer & optimizer + layer = LinearNet() + dp_layer = paddle.DataParallel(layer, group = process_group) + + loss_fn = nn.MSELoss() + adam = opt.Adam( + learning_rate=0.001, parameters=dp_layer.parameters()) + + # 3. run layer + inputs = paddle.randn([10, 10], 'float32') + outputs = dp_layer(inputs) + labels = paddle.randn([10, 1], 'float32') + loss = loss_fn(outputs, labels) + + if print_result is True: + print("loss:", loss.numpy()) + + loss.backward() + + adam.step() + adam.clear_grad() + + # Usage 1: only pass function. + # If your training method no need any argument, and + # use all visible devices for parallel training. + if __name__ == '__main__': + dist.spawn(train) + + # Usage 2: pass function and arguments. + # If your training method need some arguments, and + # use all visible devices for parallel training. + if __name__ == '__main__': + dist.spawn(train, args=(True,)) + + # Usage 3: pass function, arguments and nprocs. + # If your training method need some arguments, and + # only use part of visible devices for parallel training. + # If your machine hold 8 cards {0,1,2,3,4,5,6,7}, + # this case will use cards {0,1}; If you set + # CUDA_VISIBLE_DEVICES=4,5,6,7, this case will use + # cards {4,5} + if __name__ == '__main__': + dist.spawn(train, args=(True,), nprocs=2) + + # Usage 4: pass function, arguments, nprocs and gpus. + # If your training method need some arguments, and + # only use part of visible devices for parallel training, + # but you can't set your machine's environment variable + # CUDA_VISIBLE_DEVICES, such as it is None or all cards + # {0,1,2,3,4,5,6,7}, you can pass `gpus` to + # select the GPU cards you want to use. For example, + # this case will use cards {4,5} if your machine hold 8 cards. + if __name__ == '__main__': + dist.spawn(train, args=(True,), nprocs=2, gpus='4,5') + """ + # NOTE(chenweihang): [ why only supports python3.4+ ? ] + # Python supported setting the child process startup method + # since 3.4. The previous version can only use the default startup + # method, while the default startup method of Unix is fork, which + # cannot support CUDA runtime multi-process + _py_supported_check() + + # Give an error hint when the users enter a configuration option + # that does not exist + _options_valid_check(options) + + # get default nprocs + if nprocs == -1: + nprocs = _get_default_nprocs() + + # NOTE(chenweihang): [ why need get cluster info before run? ] + # when using `paddle.distributed.spawn` start parallel training, + # we should get cluster info before starting subprocess, and pass + # correct info to each subprocess + procs_env_list = _get_subprocess_env_list(nprocs, options) + + # start processes + # NOTE(chenweihang): [ why default start method is spawn? ] + # The CUDA runtime does not support the fork start method, + # either the spawn or forkserver start method are required + # to use CUDA in subprocesses. + start_method = options.get('start_method', None) + if start_method is None: + start_method = 'spawn' + mp = multiprocessing.get_context(start_method) + + error_queues = [] + return_queues = [] + processes = [] + for i in range(nprocs): + error_queue = mp.SimpleQueue() + return_queue = mp.SimpleQueue() + process = mp.Process(target=_func_wrapper, + args=(func, args, error_queue, return_queue, + procs_env_list[i], options['backend'])) + process.daemon = daemon + process.start() + error_queues.append(error_queue) + return_queues.append(return_queue) + processes.append(process) + + context = MultiprocessContext(processes, error_queues, return_queues) + if not join: + return context + + # loop until all process end + while not context.join(): + pass + + # finally return context + return context diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce89fa36b06b25cfc7409c093ea227393ae3111 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2022 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. + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/launch_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/launch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3282b5f58bc1a63ab4337147e31cd4b5b90405c0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/launch_utils.py @@ -0,0 +1,548 @@ +# Copyright (c) 2022 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. + +import time +import os +import signal +import copy +import sys +import subprocess +from contextlib import closing +import socket +from paddle.fluid import core +from distutils.util import strtobool +import six + +from paddle.distributed.fleet.launch_utils import get_backend_by_compile_flag +from ..utils.log_utils import get_logger + +logger = get_logger("INFO", "root") + + +def get_cluster_from_args(args, selected_gpus): + node_ips = [x.strip() for x in args.cluster_node_ips.split(',')] + node_ip = args.node_ip + node_rank = node_ips.index(node_ip) + + logger.debug("parsed from args:node_ips:{} node_ip:{} node_rank:{}".format( + node_ips, node_ip, node_rank)) + + free_ports = None + if not args.use_paddlecloud and len( + node_ips) <= 1 and args.started_port is None: + free_ports = find_free_ports(len(selected_gpus)) + if free_ports is not None: + free_ports = list(free_ports) + else: + started_port = 6070 + if args.started_port is not None: + started_port = args.started_port + + free_ports = [ + x for x in range(started_port, started_port + len(selected_gpus)) + ] + + trainer_endpoints = [] + for ip in node_ips: + trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports]) + return get_cluster(node_ips, node_ip, trainer_endpoints, selected_gpus) + + +def get_gpus(selected_gpus): + if selected_gpus is None: + from paddle.fluid import core + gpus_num = core.get_cuda_device_count() + gpus = [str(x) for x in range(0, gpus_num)] + else: + cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + if cuda_visible_devices is None or cuda_visible_devices == "": + gpus = [x.strip() for x in selected_gpus.split(',')] + else: + # change selected_gpus into relative values + # e.g. CUDA_VISIBLE_DEVICES=4,5,6,7; args.selected_gpus=4,5,6,7; + # therefore selected_gpus=0,1,2,3 + cuda_visible_devices_list = cuda_visible_devices.split(',') + for x in selected_gpus.split(','): + assert x in cuda_visible_devices_list, "Can't find "\ + "your selected_gpus %s in CUDA_VISIBLE_DEVICES[%s]."\ + % (x, cuda_visible_devices) + gpus = [ + cuda_visible_devices_list.index(x.strip()) + for x in selected_gpus.split(',') + ] + logger.info("Change selected_gpus into reletive values. --ips:{} " + "will change into relative_ips:{} according to your " + "CUDA_VISIBLE_DEVICES:{}".format( + selected_gpus, gpus, cuda_visible_devices_list)) + + return gpus + + +class Hdfs(object): + + def __init__(self): + self.hdfs_ugi = None + self.hdfs_name = None + self.hdfs_path = None + + def is_valid(self): + return self.hdfs_ugi is not None and \ + self.hdfs_name is not None and \ + self.hdfs_path is not None + + def __str__(self): + return "hdfs_ugi:{} hdfs_name:{} hdfs_path{}".format( + self.hdfs_ugi, self.hdfs_name, self.hdfs_path) + + def __eq__(self, n): + return self.hdfs_ugi == n.hdfs_ugi and \ + self.hdfs_name == n.hdfs_name and \ + self.hdfs_path == n.hdfs_path + + def __ne__(self, n): + return not self == n + + +class Cluster(object): + + def __init__(self, hdfs): + self.job_server = None + self.pods = [] + self.hdfs = None + self.job_stage_flag = None + + def __str__(self): + return "job_server:{} pods:{} job_stage_flag:{} hdfs:{}".format( + self.job_server, [str(pod) for pod in self.pods], + self.job_stage_flag, self.hdfs) + + def __eq__(self, cluster): + if len(self.pods) != len(cluster.pods): + return False + + for a, b in zip(self.pods, cluster.pods): + if a != b: + return False + + if self.job_stage_flag != cluster.job_stage_flag: + return False + + return True + + def __ne__(self, cluster): + return not self.__eq__(cluster) + + def update_pods(self, cluster): + self.pods = copy.copy(cluster.pods) + + def trainers_nranks(self): + return len(self.trainers_endpoints()) + + def pods_nranks(self): + return len(self.pods) + + def trainers_endpoints(self): + r = [] + for pod in self.pods: + for t in pod.trainers: + r.append(t.endpoint) + return r + + def pods_endpoints(self): + r = [] + for pod in self.pods: + ep = "{}:{}".format(pod.addr, pod.port) + assert pod.port != None and pod.addr != None, "{} not a valid endpoint".format( + ep) + r.append(ep) + + return r + + def get_pod_by_id(self, pod_id): + for pod in self.pods: + if str(pod_id) == str(pod.id): + return pod + + return None + + +class JobServer(object): + + def __init__(self): + self.endpoint = None + + def __str__(self): + return "{}".format(self.endpoint) + + def __eq__(self, j): + return self.endpint == j.endpoint + + def __ne__(self, j): + return not self == j + + +class Trainer(object): + + def __init__(self): + self.gpus = [] + self.endpoint = None + self.rank = None + + def __str__(self): + return "gpu:{} endpoint:{} rank:{}".format(self.gpus, self.endpoint, + self.rank) + + def __eq__(self, t): + if len(self.gpus) != len(t.gpus): + return False + + if self.endpoint != t.endpoint or \ + self.rank != t.rank: + return False + + for a, b in zip(self.gpus, t.gpus): + if a != b: + return False + + return True + + def __ne__(self, t): + return not self == t + + def get_rank(self): + return self.rank + + +class Pod(object): + + def __init__(self): + self.rank = None + self.id = None + self.addr = None + self.port = None + self.trainers = [] + self.gpus = [] + + def __str__(self): + return "rank:{} id:{} addr:{} port:{} visible_gpu:{} trainers:{}".format( + self.rank, self.id, self.addr, self.port, self.gpus, + [str(t) for t in self.trainers]) + + def __eq__(self, pod): + if self.rank != pod.rank or \ + self.id != pod.id or \ + self.addr != pod.addr or \ + self.port != pod.port: + logger.debug("pod {} != {}".format(self, pod)) + return False + + if len(self.trainers) != len(pod.trainers): + logger.debug("trainers {} != {}".format(self.trainers, + pod.trainers)) + return False + + for i in range(len(self.trainers)): + if self.trainers[i] != pod.trainers[i]: + logger.debug("trainer {} != {}".format(self.trainers[i], + pod.trainers[i])) + return False + + return True + + def __ne__(self, pod): + return not self == pod + + def parse_response(self, res_pods): + pass + + def get_visible_gpus(self): + r = "" + for g in self.gpus: + r += "{},".format(g) + + assert r != "", "this pod {} can't see any gpus".format(self) + + r = r[:-1] + return r + + +def get_cluster(node_ips, node_ip, trainer_endpoints, selected_gpus): + assert type(trainer_endpoints) is list, "trainer_endpoints must be list" + cluster = Cluster(hdfs=None) + trainer_rank = 0 + for node_rank, ip in enumerate(node_ips): + pod = Pod() + pod.rank = node_rank + pod.addr = ip + cur_node_endpoints = trainer_endpoints[node_rank] + # when use paddlecloud, endpoints may > selected_gpus(user_defined) + assert len(cur_node_endpoints) >= len( + selected_gpus + ), "current trainer_endpoints size should be greater equal than selected_gpus size." + for i in range(len(selected_gpus)): + trainer = Trainer() + trainer.gpus.append(selected_gpus[i]) + trainer.endpoint = "%s" % (cur_node_endpoints[i]) + trainer.rank = trainer_rank + trainer_rank += 1 + + pod.trainers.append(trainer) + cluster.pods.append(pod) + + pod_rank = node_ips.index(node_ip) + return cluster, cluster.pods[pod_rank] + + +def terminate_local_procs(procs): + for p in procs: + if p.proc.poll() is None: + p.proc.terminate() + if p.log_fn: + p.log_fn.close() + logger.debug("terminate process id:{}".format(p.proc.pid)) + + #wait all process terminiated + time.sleep(3) + for step in range(0, 50): + alive = False + for p in procs: + if p.proc.poll() is None: # not termniate + os.kill(p.proc.pid, signal.SIGKILL) + alive = True + + if not alive: + logger.info("terminate all the procs") + return + + time.sleep(3) + + logger.fatal("can't kill all process and exit") + exit(1) + + +def get_host_name_ip(): + try: + host_name = socket.gethostname() + host_ip = socket.gethostbyname(host_name) + return host_name, host_ip + except: + return None + + +def add_arguments(argname, type, default, help, argparser, **kwargs): + """Add argparse's argument. + Usage: + .. code-block:: python + parser = argparse.ArgumentParser() + add_argument("name", str, "Jonh", "User name.", parser) + args = parser.parse_args() + """ + type = strtobool if type == bool else type + argparser.add_argument("--" + argname, + default=default, + type=type, + help=help + ' Default: %(default)s.', + **kwargs) + + +def find_free_ports(num): + + def __free_port(): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + s.bind(('', 0)) + return s.getsockname()[1] + + port_set = set() + step = 0 + while True: + port = __free_port() + if port not in port_set: + port_set.add(port) + + if len(port_set) >= num: + return port_set + + step += 1 + if step > 100: + print( + "can't find avilable port and use the specified static port now!" + ) + return None + + return None + + +def _prepare_trainer_env(cluster, trainer, backend=None): + if backend is None: + backend = get_backend_by_compile_flag() # for compatibility + if backend == 'bkcl': + proc_env = { + "FLAGS_selected_xpus": + "%s" % ",".join([str(g) for g in trainer.gpus]), + "PADDLE_TRAINER_ID": "%d" % trainer.rank, + "PADDLE_CURRENT_ENDPOINT": "%s" % trainer.endpoint, + "PADDLE_TRAINERS_NUM": "%d" % cluster.trainers_nranks(), + "PADDLE_TRAINER_ENDPOINTS": ",".join(cluster.trainers_endpoints()) + } + elif backend == 'nccl': + proc_env = { + "FLAGS_selected_gpus": + "%s" % ",".join([str(g) for g in trainer.gpus]), + "PADDLE_TRAINER_ID": "%d" % trainer.rank, + "PADDLE_CURRENT_ENDPOINT": "%s" % trainer.endpoint, + "PADDLE_TRAINERS_NUM": "%d" % cluster.trainers_nranks(), + "PADDLE_TRAINER_ENDPOINTS": ",".join(cluster.trainers_endpoints()) + } + elif backend == 'cncl': + proc_env = { + "FLAGS_selected_mlus": + "%s" % ",".join([str(g) for g in trainer.gpus]), + "PADDLE_TRAINER_ID": "%d" % trainer.rank, + "PADDLE_CURRENT_ENDPOINT": "%s" % trainer.endpoint, + "PADDLE_TRAINERS_NUM": "%d" % cluster.trainers_nranks(), + "PADDLE_TRAINER_ENDPOINTS": ",".join(cluster.trainers_endpoints()) + } + elif backend == 'gloo': + # NOTE (xiongkun) default fall back into cpu only + proc_env = { + "PADDLE_TRAINER_ID": "%d" % trainer.rank, + "PADDLE_CURRENT_ENDPOINT": "%s" % trainer.endpoint, + "PADDLE_TRAINERS_NUM": "%d" % cluster.trainers_nranks(), + "PADDLE_TRAINER_ENDPOINTS": ",".join(cluster.trainers_endpoints()), + "PADDLE_DISTRI_BACKEND": + backend, # only add here, other will be auto + } + else: + raise ValueError("backend must be one of 'gloo, nccl, bkcl'") + + return proc_env + + +class TrainerProc(object): + + def __init__(self): + self.proc = None + self.log_fn = None + self.log_offset = None + self.rank = None + self.local_rank = None + self.cmd = None + + +def start_local_trainers(cluster, + pod, + training_script, + training_script_args, + log_dir=None): + current_env = copy.copy(os.environ.copy()) + #paddle broadcast ncclUniqueId use socket, and + #proxy maybe make trainers unreachable, so delete them. + #if we set them to "", grpc will log error message "bad uri" + #so just delete them. + current_env.pop("http_proxy", None) + current_env.pop("https_proxy", None) + + procs = [] + for idx, t in enumerate(pod.trainers): + proc_env = _prepare_trainer_env(cluster, t) + current_env.update(proc_env) + + logger.debug("trainer proc env:{}".format(current_env)) + + cmd = [sys.executable, "-u", training_script] + training_script_args + + logger.info("start trainer proc:{} env:{}".format(cmd, proc_env)) + + fn = None + if log_dir is not None: + os.system("mkdir -p {}".format(log_dir)) + fn = open("%s/workerlog.%d" % (log_dir, idx), "a") + proc = subprocess.Popen(cmd, env=current_env, stdout=fn, stderr=fn) + else: + proc = subprocess.Popen(cmd, env=current_env) + + tp = TrainerProc() + tp.proc = proc + tp.rank = t.rank + tp.local_rank = idx + tp.log_fn = fn + tp.log_offset = fn.tell() if fn else None + tp.cmd = cmd + + procs.append(tp) + + return procs + + +def pull_worker_log(tp): + if tp.log_fn: + with open(tp.log_fn.name, 'r') as fin: + fin.seek(tp.log_offset, 0) + for line in fin: + try: + sys.stdout.write(line) + except UnicodeEncodeError: + sys.stdout.write( + 'UnicodeEncodeError occurs at this line. ' + 'Please refer to the original log file "%s"\n' % + tp.log_fn.name) + tp.log_offset = fin.tell() + + +def watch_local_trainers(procs, nranks): + try: + error = False + error_rank = [] + # wait all process finish or one error + alive = False + for p in procs: + if p.log_fn and p.local_rank == 0: + pull_worker_log(p) + + ret = p.proc.poll() + if ret is None: + alive = True + elif ret != 0: + error = True + error_rank.append(p.rank) + + if error: + terminate_local_procs(procs) + exit(1) + + except KeyboardInterrupt: + logger.warning("KeyboardInterrupt, exit") + terminate_local_procs(procs) + raise + except SystemExit: + logger.error( + "ABORT!!! Out of all {} trainers, the trainer process with rank={} was aborted. Please check its log." + .format(nranks, error_rank)) + terminate_local_procs(procs) + raise + except: + logger.error( + "ABORT!!! Out of all {} trainers, the trainer process with rank={} was aborted. Please check its log." + .format(nranks, error_rank)) + terminate_local_procs(procs) + raise + + return alive + + +def _print_arguments(args): + print("----------- Configuration Arguments -----------") + for arg, value in sorted(six.iteritems(vars(args))): + print("%s: %s" % (arg, value)) + print("------------------------------------------------") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/log_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/log_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c00ce9b82786f500f4054e2eb215b4b7df151cde --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/log_utils.py @@ -0,0 +1,35 @@ +# Copyright (c) 2022 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. + +import logging + + +def get_logger(log_level, name="root"): + + logger = logging.getLogger(name) + + # Avoid printing multiple logs + logger.propagate = False + + if not logger.handlers: + log_handler = logging.StreamHandler() + logger.setLevel(log_level) + log_format = logging.Formatter( + '[%(asctime)-15s] [%(levelname)8s] %(filename)s:%(lineno)s - %(message)s' + ) + log_handler.setFormatter(log_format) + logger.addHandler(log_handler) + else: + logger.setLevel(log_level) + return logger diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/moe_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/moe_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d6dbfdfab58c0205882077de68a056ed509930ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distributed/utils/moe_utils.py @@ -0,0 +1,255 @@ +# Copyright (c) 2022 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. + +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle import _legacy_C_ops + + +def global_scatter(x, + local_count, + global_count, + group=None, + use_calc_stream=True): + """ + The global_scatter operator distributes the data of x to n_expert * world_size experts according to local_count, + and then receives data according to global_count. The expert refers to a user-defined expert network, + n_expert refers to the number of expert networks owned by each card, and world_size refers to the number of graphics cards running the network. + + As shown below, the value of the world size is 2, n_expert 2, the batch size of the x 4 and local_count is [2, 0, 2, 0]. + The global_count of the rank 0 is [2, 0, , ], rank 1 is [2, 0, ,](Due to the limited space, only the data calculated on rank 0 is shown here). + In the global_scatter operator, local_count[i] represents sending local_count[i] data to the (i % n_expert)th expert of the (i // n_expert)th card, + global_count[i] represents receiving global_count[i] data from the (i // n_expert)th card to the (i % n_expert)th expert of this card. The rank in the + figure respresent the rank of the current card in all cards. + + The process of global_scatter sending data is as follows: + + local_count[0] represents taking out 2 batches from x and sending 2 batches to the 0th expert of the 0th card; + + local_count[1] represents taking out 0 batches from x and sending 0 batches to the 1th expert of the 0th card; + + local_count[2] represents taking out 2 batches from x and sending 2 batches to the 0th expert of the 1th card; + + local_count[3] represents taking out 0 batches from x and sending 0 batches to the 1th expert of the 1th card; + + Therefore, the global_count[0] of the 0th card is equal to 2, which means that 2 batches of data are received from the 0th card to the 0th expert; + + the global_count[1] of the 0th card is equal to 0, which means that 0 batches of data are received from the 0th card to the 1th expert; + + the global_count[0] of the 1th card is equal to 2, which means that 2 batches of data are received from the 0th card to the 0th expert; + + the global_count[1] of the 1th card is equal to 0, which means that 0 batches of data are received from the 0th card to the 1th expert. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/global_scatter_gather.png + :width: 800 + :alt: global_scatter_gather + :align: center + + Args: + x (Tensor): Tensor. The tensor data type should be float16, float32, float64, int32 or int64. + local_count (Tensor): Tensor which have n_expert * world_size elements that indicates + how many data needed to be sent. The tensor data type should be int64. + global_count (Tensor): Tensor which have n_expert * world_size elements that indicates + how many data needed to be received. The tensor data type should be int64. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + use_calc_stream (bool, optional): Wether to use calculation stream (True) or communication stream. Default: True. + + Returns: + out (Tensor): The data received from all experts. + + Examples: + .. code-block:: python + + # required: distributed + import numpy as np + import paddle + from paddle.distributed import init_parallel_env + init_parallel_env() + n_expert = 2 + world_size = 2 + d_model = 2 + in_feat = d_model + local_input_buf = np.array([[1, 2],[3, 4],[5, 6],[7, 8],[9, 10]], \ + dtype=np.float32) + if paddle.distributed.ParallelEnv().local_rank == 0: + local_count = np.array([2, 1, 1, 1]) + global_count = np.array([2, 1, 1, 1]) + else: + local_count = np.array([1, 1, 2, 1]) + global_count = np.array([1, 1, 2, 1]) + local_input_buf = paddle.to_tensor(local_input_buf, dtype="float32", stop_gradient=False) + local_count = paddle.to_tensor(local_count, dtype="int64") + global_count = paddle.to_tensor(global_count, dtype="int64") + a = paddle.distributed.utils.global_scatter(local_input_buf, \ + local_count, global_count) + a.stop_gradient = False + print(a) + # out for rank 0: [[1, 2], [3, 4], [1, 2], [5, 6], [3, 4]] + # out for rank 1: [[7, 8], [5, 6], [7, 8], [9, 10], [9, 10]] + # backward test + c = a * a + c.backward() + print("local_input_buf.grad: ", local_input_buf.grad) + # out for rank 0: [[2, 4], [6, 8], [10, 12], [14, 16], [18, 20]] + # out for rank 1: [[2, 4], [6, 8], [10, 12], [14, 16], [18, 20]] + """ + if group is not None and not group.is_member(): + return + + ring_id = 0 if group is None else group.id + if _non_static_mode(): + return _legacy_C_ops.global_scatter(x, local_count, \ + global_count, \ + 'use_calc_stream', use_calc_stream, \ + 'ring_id', ring_id) + else: + op_type = 'global_scatter' + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], + 'global_scatter') + check_variable_and_dtype(local_count, 'local_count', ['int64'], + 'global_scatter') + check_variable_and_dtype(global_count, 'global_count', ['int64'], + 'global_scatter') + + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=op_type, + inputs={ + 'X': [x], + 'local_count': [local_count], + 'global_count': [global_count], + }, + outputs={'Out': [out]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream + }) + return out + + +def global_gather(x, + local_count, + global_count, + group=None, + use_calc_stream=True): + """ + The global_gather operator gathers the data of x into n_expert * world_size experts according to global_count, and then receives data according to local_count. + The expert refers to a user-defined expert network, n_expert refers to the number of expert networks owned by each card, and world_size refers to the number of graphics cards running the network. + + As shown below, the value of the world size is 2, n_expert 2, the batch size of the x 4 and local_count is [2, 0, 2, 0]. + The global_count of the rank 0 is [2, 0, , ], rank 1 is [2, 0, ,](Due to the limited space, only the data calculated on rank 0 is shown here). + In the global_gather operator, the meaning of the global_count and local_count is opposed to global_scatter, global_count[i] represents sending global_count[i] data to the (i % n_expert)th expert of the (i // n_expert)th card, + local_count[i] represents receiving local_count[i] data from the (i // n_expert)th card to the (i % n_expert)th expert of this card. The data sent will be arranged according to the experts of each card. + The rank in the figure respresent the rank of the current card in all cards. + + The process of global_gather sending data is as follows: + + The global_count[0] of the 0th card represents sending 2 data to the 0th expert of the 0th card; + + The global_count[1] of the 0th card represents sending 0 data to the 1th expert of the 0th card; + + The global_count[0] of the 1th card represents sending 2 data to the 0th expert of the 0th card; + + The global_count[1] of the 1th card represents sending 0 data to the 1th expert of the 0th card. + + .. image:: https://githubraw.cdn.bcebos.com/PaddlePaddle/docs/develop/docs/api/paddle/distributed/img/global_scatter_gather.png + :width: 800 + :alt: global_scatter_gather + :align: center + + + Args: + x (Tensor): Tensor. Tensor whose data type should be float16, float32, float64, int32 or int64. + local_count (Tensor): Tensor which have n_expert * world_size elements that indicates + how many data needed to be received. Tensor data type should be int64. + global_count (Tensor): Tensor which have n_expert * world_size elements that indicates + how many data needed to be sent. Tensor data type should be int64. + group (Group, optional): The group instance return by new_group or None for global default group. Default: None. + use_calc_stream (bool, optional): Wether to use calculation stream (True) or communication stream. Default: True. + + Returns: + out (Tensor): The data received from all experts. + + Examples: + .. code-block:: python + + # required: distributed + import numpy as np + import paddle + from paddle.distributed import init_parallel_env + init_parallel_env() + n_expert = 2 + world_size = 2 + d_model = 2 + in_feat = d_model + local_input_buf = np.array([[1, 2],[3, 4],[5, 6],[7, 8],[9, 10]],\ + dtype=np.float32) + if paddle.distributed.ParallelEnv().local_rank == 0: + local_count = np.array([2, 1, 1, 1]) + global_count = np.array([2, 1, 1, 1]) + else: + local_count = np.array([1, 1, 2, 1]) + global_count = np.array([1, 1, 2, 1]) + local_input_buf = paddle.to_tensor(local_input_buf, dtype="float32", stop_gradient=False) + local_count = paddle.to_tensor(local_count, dtype="int64") + global_count = paddle.to_tensor(global_count, dtype="int64") + a = paddle.distributed.utils.global_gather(local_input_buf, local_count, global_count) + print(a) + # out for rank 0: [[1, 2], [3, 4], [7, 8], [1, 2], [7, 8]] + # out for rank 1: [[5, 6], [9, 10], [3, 4], [5, 6], [9, 10]] + a.stop_gradient = False + c = a * a + c.backward() + print("local_input_buf.grad", local_input_buf.grad) + # out for rank 0: [[2, 4], [6, 8], [10, 12], [14, 16], [18, 20]] + # out for rank 1: [[2, 4], [6, 8], [10, 12], [14, 16], [18, 20]] + """ + if group is not None and not group.is_member(): + return + + ring_id = 0 if group is None else group.id + if _non_static_mode(): + return _legacy_C_ops.global_gather(x, local_count, \ + global_count, \ + 'use_calc_stream', use_calc_stream, \ + 'ring_id', ring_id) + else: + op_type = 'global_gather' + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], + 'global_gather') + + check_variable_and_dtype(local_count, 'local_count', ['int64'], + 'global_gather') + + check_variable_and_dtype(global_count, 'global_count', ['int64'], + 'global_gather') + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=op_type, + inputs={ + 'X': [x], + 'local_count': [local_count], + 'global_count': [global_count] + }, + outputs={'Out': [out]}, + attrs={ + 'ring_id': group, + 'use_calc_stream': use_calc_stream, + }) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64d59b04864baa077e74806d6bf6a931442ee5ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/__init__.py @@ -0,0 +1,36 @@ +# Copyright (c) 2021 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. + +from paddle.distribution import transform +from paddle.distribution.beta import Beta +from paddle.distribution.categorical import Categorical +from paddle.distribution.dirichlet import Dirichlet +from paddle.distribution.distribution import Distribution +from paddle.distribution.exponential_family import ExponentialFamily +from paddle.distribution.independent import Independent +from paddle.distribution.kl import kl_divergence, register_kl +from paddle.distribution.multinomial import Multinomial +from paddle.distribution.normal import Normal +from paddle.distribution.transform import * # noqa: F403 +from paddle.distribution.transformed_distribution import \ + TransformedDistribution +from paddle.distribution.uniform import Uniform + +__all__ = [ # noqa + 'Beta', 'Categorical', 'Dirichlet', 'Distribution', 'ExponentialFamily', + 'Multinomial', 'Normal', 'Uniform', 'kl_divergence', 'register_kl', + 'Independent', 'TransformedDistribution' +] + +__all__.extend(transform.__all__) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/beta.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/beta.py new file mode 100644 index 0000000000000000000000000000000000000000..e371b56eb66b891a2f866d3238f68bb800c385be --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/beta.py @@ -0,0 +1,159 @@ +# Copyright (c) 2021 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. +import numbers + +import paddle +from paddle.distribution import dirichlet, exponential_family + + +class Beta(exponential_family.ExponentialFamily): + r""" + Beta distribution parameterized by alpha and beta. + + In probability theory and statistics, the beta distribution is a family of + continuous probability distributions defined on the interval [0, 1] + parameterized by two positive shape parameters, denoted by alpha and beta, + that appear as exponents of the random variable and control the shape of + the distribution. The generalization to multiple variables is called a + Dirichlet distribution. + + The probability density function (pdf) is + + .. math:: + + f(x; \alpha, \beta) = \frac{1}{B(\alpha, \beta)}x^{\alpha-1}(1-x)^{\beta-1} + + where the normalization, B, is the beta function, + + .. math:: + + B(\alpha, \beta) = \int_{0}^{1} t^{\alpha - 1} (1-t)^{\beta - 1}\mathrm{d}t + + + Args: + alpha (float|Tensor): Alpha parameter. It supports broadcast semantics. + The value of alpha must be positive. When the parameter is a tensor, + it represents multiple independent distribution with + a batch_shape(refer to ``Distribution`` ). + beta (float|Tensor): Beta parameter. It supports broadcast semantics. + The value of beta must be positive(>0). When the parameter is tensor, + it represent multiple independent distribution with + a batch_shape(refer to ``Distribution`` ). + + Examples: + + .. code-block:: python + + import paddle + + # scale input + beta = paddle.distribution.Beta(alpha=0.5, beta=0.5) + print(beta.mean) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.50000000]) + print(beta.variance) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.12500000]) + print(beta.entropy()) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.12500000]) + + # tensor input with broadcast + beta = paddle.distribution.Beta(alpha=paddle.to_tensor([0.2, 0.4]), beta=0.6) + print(beta.mean) + # Tensor(shape=[2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.25000000, 0.40000001]) + print(beta.variance) + # Tensor(shape=[2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.10416666, 0.12000000]) + print(beta.entropy()) + # Tensor(shape=[2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [-1.91923141, -0.38095069]) + """ + + def __init__(self, alpha, beta): + if isinstance(alpha, numbers.Real): + alpha = paddle.full(shape=[1], fill_value=alpha) + + if isinstance(beta, numbers.Real): + beta = paddle.full(shape=[1], fill_value=beta) + + self.alpha, self.beta = paddle.broadcast_tensors([alpha, beta]) + + self._dirichlet = dirichlet.Dirichlet( + paddle.stack([self.alpha, self.beta], -1)) + + super(Beta, self).__init__(self._dirichlet._batch_shape) + + @property + def mean(self): + """Mean of beta distribution. + """ + return self.alpha / (self.alpha + self.beta) + + @property + def variance(self): + """Variance of beat distribution + """ + sum = self.alpha + self.beta + return self.alpha * self.beta / (sum.pow(2) * (sum + 1)) + + def prob(self, value): + """Probability density funciotn evaluated at value + + Args: + value (Tensor): Value to be evaluated. + + Returns: + Tensor: Probability. + """ + return paddle.exp(self.log_prob(value)) + + def log_prob(self, value): + """Log probability density funciton evaluated at value + + Args: + value (Tensor): Value to be evaluated + + Returns: + Tensor: Log probability. + """ + return self._dirichlet.log_prob(paddle.stack([value, 1.0 - value], -1)) + + def sample(self, shape=()): + """Sample from beta distribution with sample shape. + + Args: + shape (Sequence[int], optional): Sample shape. + + Returns: + Sampled data with shape `sample_shape` + `batch_shape` + `event_shape`. + """ + shape = shape if isinstance(shape, tuple) else tuple(shape) + return paddle.squeeze(self._dirichlet.sample(shape)[..., 0], axis=-1) + + def entropy(self): + """Entropy of dirichlet distribution + + Returns: + Tensor: Entropy. + """ + return self._dirichlet.entropy() + + @property + def _natural_parameters(self): + return (self.alpha, self.beta) + + def _log_normalizer(self, x, y): + return paddle.lgamma(x) + paddle.lgamma(y) - paddle.lgamma(x + y) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/categorical.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..cd44277f3e8a7037ea09c5fff8921046b739ef9f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/categorical.py @@ -0,0 +1,348 @@ +# Copyright (c) 2021 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. + +import math +import warnings + +import numpy as np +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.distribution import distribution +from paddle.fluid import core +from paddle.fluid.data_feeder import (check_dtype, check_type, + check_variable_and_dtype, convert_dtype) +from paddle.fluid.framework import _non_static_mode, in_dygraph_mode +from paddle.fluid.layers import (control_flow, elementwise_add, elementwise_div, + elementwise_mul, elementwise_sub, nn, ops, + tensor) +from paddle.tensor import arange, concat, gather_nd, multinomial + + +class Categorical(distribution.Distribution): + r""" + Categorical distribution is a discrete probability distribution that + describes the possible results of a random variable that can take on + one of K possible categories, with the probability of each category + separately specified. + + The probability mass function (pmf) is: + + .. math:: + + pmf(k; p_i) = \prod_{i=1}^{k} p_i^{[x=i]} + + In the above equation: + + * :math:`[x=i]` : it evaluates to 1 if :math:`x==i` , 0 otherwise. + + Args: + logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64. + name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + paddle.seed(200) # on CPU device + y = paddle.rand([6]) + print(y) + # [0.77663314 0.90824795 0.15685187 + # 0.04279523 0.34468332 0.7955718 ] + + cat = Categorical(x) + cat2 = Categorical(y) + + paddle.seed(1000) # on CPU device + cat.sample([2,3]) + # [[0, 0, 5], + # [3, 4, 5]] + + cat.entropy() + # [1.77528] + + cat.kl_divergence(cat2) + # [0.071952] + + value = paddle.to_tensor([2,1,3]) + cat.probs(value) + # [0.00608027 0.108298 0.269656] + + cat.log_prob(value) + # [-5.10271 -2.22287 -1.31061] + + """ + + def __init__(self, logits, name=None): + """ + Args: + logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64. + name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + """ + if not _non_static_mode(): + check_type(logits, 'logits', + (np.ndarray, tensor.Variable, list, tuple), + 'Categorical') + + self.name = name if name is not None else 'Categorical' + self.dtype = 'float32' + + if self._validate_args(logits): + self.logits = logits + self.dtype = convert_dtype(logits.dtype) + else: + if isinstance(logits, np.ndarray) and str( + logits.dtype) in ['float32', 'float64']: + self.dtype = logits.dtype + self.logits = self._to_tensor(logits)[0] + if self.dtype != convert_dtype(self.logits.dtype): + self.logits = tensor.cast(self.logits, dtype=self.dtype) + dist_sum = paddle.sum(self.logits, axis=-1, keepdim=True) + self._prob = self.logits / dist_sum + + def sample(self, shape): + """Generate samples of the specified shape. + + Args: + shape (list): Shape of the generated samples. + + Returns: + Tensor: A tensor with prepended dimensions shape. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + cat = Categorical(x) + + paddle.seed(1000) # on CPU device + cat.sample([2,3]) + # [[0, 0, 5], + # [3, 4, 5]] + + """ + name = self.name + '_sample' + if not _non_static_mode(): + check_type(shape, 'shape', (list), 'sample') + + num_samples = np.prod(np.array(shape)) + + logits_shape = list(self.logits.shape) + if len(logits_shape) > 1: + sample_shape = shape + logits_shape[:-1] + logits = paddle.reshape( + self.logits, [np.prod(logits_shape[:-1]), logits_shape[-1]]) + else: + sample_shape = shape + logits = self.logits + + sample_index = multinomial(self._logits_to_probs(logits), num_samples, + True) + + # multinomial sample shape is (logits.shape[:-1], num_samples), need to + # tanspose to (num_samples, logits.shape[:-1]) + permute = list(range(sample_index.dim())) + permute.insert(0, permute.pop(-1)) + sample_index = sample_index.transpose(permute) + + return paddle.reshape(sample_index, sample_shape, name=name) + + def kl_divergence(self, other): + """The KL-divergence between two Categorical distributions. + + Args: + other (Categorical): instance of Categorical. The data type is float32. + + Returns: + Tensor: kl-divergence between two Categorical distributions. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + paddle.seed(200) # on CPU device + y = paddle.rand([6]) + print(y) + # [0.77663314 0.90824795 0.15685187 + # 0.04279523 0.34468332 0.7955718 ] + + cat = Categorical(x) + cat2 = Categorical(y) + + cat.kl_divergence(cat2) + # [0.071952] + + """ + name = self.name + '_kl_divergence' + if not _non_static_mode(): + check_type(other, 'other', Categorical, 'kl_divergence') + + logits = self.logits - \ + paddle.max(self.logits, axis=-1, keepdim=True) + other_logits = other.logits - paddle.max( + other.logits, axis=-1, keepdim=True) + e_logits = ops.exp(logits) + other_e_logits = ops.exp(other_logits) + z = paddle.sum(e_logits, axis=-1, keepdim=True) + other_z = paddle.sum(other_e_logits, axis=-1, keepdim=True) + prob = e_logits / z + kl = paddle.sum( + prob * + (logits - paddle.log(z) - other_logits + paddle.log(other_z)), + axis=-1, + keepdim=True, + name=name) + + return kl + + def entropy(self): + """Shannon entropy in nats. + + Returns: + Tensor: Shannon entropy of Categorical distribution. The data type is float32. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + cat = Categorical(x) + + cat.entropy() + # [1.77528] + + """ + name = self.name + '_entropy' + logits = self.logits - \ + paddle.max(self.logits, axis=-1, keepdim=True) + e_logits = ops.exp(logits) + z = paddle.sum(e_logits, axis=-1, keepdim=True) + prob = e_logits / z + + neg_entropy = paddle.sum(prob * (logits - paddle.log(z)), axis=-1) + entropy = paddle.scale(neg_entropy, scale=-1.0, name=name) + return entropy + + def probs(self, value): + """Probabilities of the given category (``value``). + + If ``logits`` is 2-D or higher dimension, the last dimension will be regarded as + category, and the others represents the different distributions. + At the same time, if ``vlaue`` is 1-D Tensor, ``value`` will be broadcast to the + same number of distributions as ``logits``. + If ``value`` is not 1-D Tensor, ``value`` should have the same number distributions + with ``logits. That is, ``value[:-1] = logits[:-1]``. + + Args: + value (Tensor): The input tensor represents the selected category index. + + Returns: + Tensor: probability according to the category index. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + cat = Categorical(x) + + value = paddle.to_tensor([2,1,3]) + cat.probs(value) + # [0.00608027 0.108298 0.269656] + + """ + name = self.name + '_probs' + if len(self._prob.shape) == 1: # batch_shape is empty + return paddle.gather(self._prob, + value.reshape([-1], name=name), + name=name).reshape(value.shape, name=name) + else: + if len(value.shape) == 1: + return paddle.take_along_axis( + self._prob, + paddle.reshape(value, + (len(self._prob.shape) - 1) * [1] + [-1], + name=name), + axis=-1) + else: + return paddle.take_along_axis(self._prob, value, axis=-1) + + def log_prob(self, value): + """Log probabilities of the given category. Refer to ``probs`` method. + + Args: + value (Tensor): The input tensor represents the selected category index. + + Returns: + Tensor: Log probability. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Categorical + + paddle.seed(100) # on CPU device + x = paddle.rand([6]) + print(x) + # [0.5535528 0.20714243 0.01162981 + # 0.51577556 0.36369765 0.2609165 ] + + cat = Categorical(x) + + value = paddle.to_tensor([2,1,3]) + cat.log_prob(value) + # [-5.10271 -2.22287 -1.31061] + + """ + name = self.name + '_log_prob' + + return paddle.log(self.probs(value), name=name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/constraint.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..4cde3d30a565ca5838f2275fc81763a0ec84abda --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/constraint.py @@ -0,0 +1,57 @@ +# Copyright (c) 2022 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. +import paddle + + +class Constraint(object): + """Constraint condition for random variable. + """ + + def __call__(self, value): + raise NotImplementedError + + +class Real(Constraint): + + def __call__(self, value): + return value == value + + +class Range(Constraint): + + def __init__(self, lower, upper): + self._lower = lower + self._upper = upper + super(Range, self).__init__() + + def __call__(self, value): + return self._lower <= value <= self._upper + + +class Positive(Constraint): + + def __call__(self, value): + return value >= 0. + + +class Simplex(Constraint): + + def __call__(self, value): + return paddle.all(value >= 0, + axis=-1) and ((value.sum(-1) - 1).abs() < 1e-6) + + +real = Real() +positive = Positive() +simplex = Simplex() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/dirichlet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/dirichlet.py new file mode 100644 index 0000000000000000000000000000000000000000..6862bf30e06fb335c6773c76c3326b5678119b8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/dirichlet.py @@ -0,0 +1,172 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.distribution import exponential_family +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph +from paddle.fluid.layer_helper import LayerHelper + + +class Dirichlet(exponential_family.ExponentialFamily): + r""" + Dirichlet distribution with parameter "concentration". + + The Dirichlet distribution is defined over the `(k-1)-simplex` using a + positive, lenght-k vector concentration(`k > 1`). + The Dirichlet is identically the Beta distribution when `k = 2`. + + For independent and identically distributed continuous random variable + :math:`\boldsymbol X \in R_k` , and support + :math:`\boldsymbol X \in (0,1), ||\boldsymbol X|| = 1` , + The probability density function (pdf) is + + .. math:: + + f(\boldsymbol X; \boldsymbol \alpha) = \frac{1}{B(\boldsymbol \alpha)} \prod_{i=1}^{k}x_i^{\alpha_i-1} + + where :math:`\boldsymbol \alpha = {\alpha_1,...,\alpha_k}, k \ge 2` is + parameter, the normalizing constant is the multivariate beta function. + + .. math:: + + B(\boldsymbol \alpha) = \frac{\prod_{i=1}^{k} \Gamma(\alpha_i)}{\Gamma(\alpha_0)} + + :math:`\alpha_0=\sum_{i=1}^{k} \alpha_i` is the sum of parameters, + :math:`\Gamma(\alpha)` is gamma function. + + Args: + concentration (Tensor): "Concentration" parameter of dirichlet + distribution, also called :math:`\alpha`. When it's over one + dimension, the last axis denotes the parameter of distribution, + ``event_shape=concentration.shape[-1:]`` , axes other than last are + condsider batch dimensions with ``batch_shape=concentration.shape[:-1]`` . + + Examples: + + .. code-block:: python + + import paddle + + dirichlet = paddle.distribution.Dirichlet(paddle.to_tensor([1., 2., 3.])) + + print(dirichlet.entropy()) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [-1.24434423]) + print(dirichlet.prob(paddle.to_tensor([.3, .5, .6]))) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [10.80000114]) + + """ + + def __init__(self, concentration): + if concentration.dim() < 1: + raise ValueError( + "`concentration` parameter must be at least one dimensional") + + self.concentration = concentration + super(Dirichlet, self).__init__(concentration.shape[:-1], + concentration.shape[-1:]) + + @property + def mean(self): + """Mean of Dirichelt distribution. + + Returns: + Mean value of distribution. + """ + return self.concentration / self.concentration.sum(-1, keepdim=True) + + @property + def variance(self): + """Variance of Dirichlet distribution. + + Returns: + Variance value of distribution. + """ + concentration0 = self.concentration.sum(-1, keepdim=True) + return (self.concentration * (concentration0 - self.concentration)) / ( + concentration0.pow(2) * (concentration0 + 1)) + + def sample(self, shape=()): + """Sample from dirichlet distribution. + + Args: + shape (Sequence[int], optional): Sample shape. Defaults to empty tuple. + """ + shape = shape if isinstance(shape, tuple) else tuple(shape) + return _dirichlet(self.concentration.expand(self._extend_shape(shape))) + + def prob(self, value): + """Probability density function(PDF) evaluated at value. + + Args: + value (Tensor): Value to be evaluated. + + Returns: + PDF evaluated at value. + """ + return paddle.exp(self.log_prob(value)) + + def log_prob(self, value): + """Log of probability densitiy function. + + Args: + value (Tensor): Value to be evaluated. + """ + return ((paddle.log(value) * (self.concentration - 1.0)).sum(-1) + + paddle.lgamma(self.concentration.sum(-1)) - + paddle.lgamma(self.concentration).sum(-1)) + + def entropy(self): + """Entropy of Dirichlet distribution. + + Returns: + Entropy of distribution. + """ + concentration0 = self.concentration.sum(-1) + k = self.concentration.shape[-1] + return (paddle.lgamma(self.concentration).sum(-1) - + paddle.lgamma(concentration0) - + (k - concentration0) * paddle.digamma(concentration0) - + ((self.concentration - 1.0) * + paddle.digamma(self.concentration)).sum(-1)) + + @property + def _natural_parameters(self): + return (self.concentration, ) + + def _log_normalizer(self, x): + return x.lgamma().sum(-1) - paddle.lgamma(x.sum(-1)) + + +def _dirichlet(concentration, name=None): + op_type = 'dirichlet' + + check_variable_and_dtype(concentration, 'concentration', + ['float32', 'float64'], op_type) + + if in_dygraph_mode(): + return paddle._C_ops.dirichlet(concentration) + elif _in_legacy_dygraph(): + return paddle._legacy_C_ops.dirichlet(concentration) + else: + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference( + dtype=concentration.dtype) + helper.append_op(type=op_type, + inputs={"Alpha": concentration}, + outputs={'Out': out}, + attrs={}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/distribution.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..75934052da98ff2feaa18979cb3f26f151beb089 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/distribution.py @@ -0,0 +1,291 @@ +# 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. + +# TODO: define the distribution functions +# __all__ = ['Categorical', +# 'MultivariateNormalDiag', +# 'Normal', +# 'sampling_id', +# 'Uniform'] + +from __future__ import print_function + +import math +import warnings + +import numpy as np +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid.data_feeder import ( + check_dtype, + check_type, + check_variable_and_dtype, + convert_dtype, +) +from paddle.fluid.framework import ( + _non_static_mode, + in_dygraph_mode, + _in_legacy_dygraph, +) +from paddle.fluid.layers import ( + control_flow, + elementwise_add, + elementwise_div, + elementwise_mul, + elementwise_sub, + nn, + ops, + tensor, +) +from paddle.tensor import arange, concat, gather_nd, multinomial + + +class Distribution(object): + """ + The abstract base class for probability distributions. Functions are + implemented in specific distributions. + + Args: + batch_shape(Sequence[int], optional): independent, not identically + distributed draws, aka a "collection" or "bunch" of distributions. + event_shape(Sequence[int], optional): the shape of a single + draw from the distribution; it may be dependent across dimensions. + For scalar distributions, the event shape is []. For n-dimension + multivariate distribution, the event shape is [n]. + """ + + def __init__(self, batch_shape=(), event_shape=()): + + self._batch_shape = ( + batch_shape + if isinstance(batch_shape, tuple) + else tuple(batch_shape) + ) + self._event_shape = ( + event_shape + if isinstance(event_shape, tuple) + else tuple(event_shape) + ) + + super(Distribution, self).__init__() + + @property + def batch_shape(self): + """Returns batch shape of distribution + + Returns: + Sequence[int]: batch shape + """ + return self._batch_shape + + @property + def event_shape(self): + """Returns event shape of distribution + + Returns: + Sequence[int]: event shape + """ + return self._event_shape + + @property + def mean(self): + """Mean of distribution""" + raise NotImplementedError + + @property + def variance(self): + """Variance of distribution""" + raise NotImplementedError + + def sample(self, shape=()): + """Sampling from the distribution.""" + raise NotImplementedError + + def rsample(self, shape=()): + """reparameterized sample""" + raise NotImplementedError + + def entropy(self): + """The entropy of the distribution.""" + raise NotImplementedError + + def kl_divergence(self, other): + """The KL-divergence between self distributions and other.""" + raise NotImplementedError + + def prob(self, value): + """Probability density/mass function evaluated at value. + + Args: + value (Tensor): value which will be evaluated + """ + return self.log_prob(value).exp() + + def log_prob(self, value): + """Log probability density/mass function.""" + raise NotImplementedError + + def probs(self, value): + """Probability density/mass function. + + Note: + + This method will be deprecated in the future, please use `prob` + instead. + """ + raise NotImplementedError + + def _extend_shape(self, sample_shape): + """compute shape of the sample + + Args: + sample_shape (Tensor): sample shape + + Returns: + Tensor: generated sample data shape + """ + return sample_shape + self._batch_shape + self._event_shape + + def _validate_args(self, *args): + """ + Argument validation for distribution args + Args: + value (float, list, numpy.ndarray, Tensor) + Raises + ValueError: if one argument is Tensor, all arguments should be Tensor + """ + is_variable = False + is_number = False + for arg in args: + if isinstance(arg, tensor.Variable): + is_variable = True + else: + is_number = True + + if is_variable and is_number: + raise ValueError( + 'if one argument is Tensor, all arguments should be Tensor' + ) + + return is_variable + + def _to_tensor(self, *args): + """ + Argument convert args to Tensor + + Args: + value (float, list, numpy.ndarray, Tensor) + Returns: + Tensor of args. + """ + numpy_args = [] + variable_args = [] + tmp = 0.0 + + for arg in args: + if isinstance(arg, float): + arg = [arg] + if not isinstance(arg, (list, tuple, np.ndarray, tensor.Variable)): + raise TypeError( + "Type of input args must be float, list, numpy.ndarray or Tensor, but received type {}".format( + type(arg) + ) + ) + + arg_np = np.array(arg) + arg_dtype = arg_np.dtype + if str(arg_dtype) != 'float32': + if str(arg_dtype) != 'float64': + # "assign" op doesn't support float64. if dtype is float64, float32 variable will be generated + # and converted to float64 later using "cast". + warnings.warn( + "data type of argument only support float32 and float64, your argument will be convert to float32." + ) + arg_np = arg_np.astype('float32') + # tmp is used to support broadcast, it summarizes shapes of all the args and get the mixed shape. + tmp = tmp + arg_np + numpy_args.append(arg_np) + + dtype = tmp.dtype + for arg in numpy_args: + arg_broadcasted, _ = np.broadcast_arrays(arg, tmp) + arg_variable = tensor.create_tensor(dtype=dtype) + tensor.assign(arg_broadcasted, arg_variable) + variable_args.append(arg_variable) + + return tuple(variable_args) + + def _check_values_dtype_in_probs(self, param, value): + """ + Log_prob and probs methods have input ``value``, if value's dtype is different from param, + convert value's dtype to be consistent with param's dtype. + + Args: + param (Tensor): low and high in Uniform class, loc and scale in Normal class. + value (Tensor): The input tensor. + + Returns: + value (Tensor): Change value's dtype if value's dtype is different from param. + """ + if _non_static_mode(): + if value.dtype != param.dtype and convert_dtype(value.dtype) in [ + 'float32', + 'float64', + ]: + warnings.warn( + "dtype of input 'value' needs to be the same as parameters of distribution class. dtype of 'value' will be converted." + ) + if in_dygraph_mode(): + return _C_ops.cast(value, param.dtype) + if _in_legacy_dygraph(): + return _legacy_C_ops.cast( + value, 'in_dtype', value.dtype, 'out_dtype', param.dtype + ) + return value + + check_variable_and_dtype( + value, 'value', ['float32', 'float64'], 'log_prob' + ) + if value.dtype != param.dtype: + warnings.warn( + "dtype of input 'value' needs to be the same as parameters of distribution class. dtype of 'value' will be converted." + ) + return tensor.cast(value, dtype=param.dtype) + return value + + def _probs_to_logits(self, probs, is_binary=False): + r""" + Converts probabilities into logits. For the binary, probs denotes the + probability of occurrence of the event indexed by `1`. For the + multi-dimensional, values of last axis denote the probabilities of + occurrence of each of the events. + """ + return ( + (paddle.log(probs) - paddle.log1p(-probs)) + if is_binary + else paddle.log(probs) + ) + + def _logits_to_probs(self, logits, is_binary=False): + r""" + Converts logits into probabilities. For the binary, each value denotes + log odds, whereas for the multi-dimensional case, the values along the + last dimension denote the log probabilities of the events. + """ + return ( + paddle.nn.functional.sigmoid(logits) + if is_binary + else paddle.nn.functional.softmax(logits, axis=-1) + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/exponential_family.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/exponential_family.py new file mode 100644 index 0000000000000000000000000000000000000000..b78e77497043b2ad47509978570d8557898835f2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/exponential_family.py @@ -0,0 +1,75 @@ +# Copyright (c) 2021 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. + +import paddle +from paddle.distribution import distribution +from paddle.fluid.framework import _non_static_mode, in_dygraph_mode + + +class ExponentialFamily(distribution.Distribution): + r""" + ExponentialFamily is the base class for probability distributions belonging + to exponential family, whose probability mass/density function has the + form is defined below + + ExponentialFamily is derived from `paddle.distribution.Distribution`. + + .. math:: + + f_{F}(x; \theta) = \exp(\langle t(x), \theta\rangle - F(\theta) + k(x)) + + where :math:`\theta` denotes the natural parameters, :math:`t(x)` denotes + the sufficient statistic, :math:`F(\theta)` is the log normalizer function + for a given family and :math:`k(x)` is the carrier measure. + + Distribution belongs to exponential family referring to https://en.wikipedia.org/wiki/Exponential_family + """ + + @property + def _natural_parameters(self): + raise NotImplementedError + + def _log_normalizer(self): + raise NotImplementedError + + @property + def _mean_carrier_measure(self): + raise NotImplementedError + + def entropy(self): + """caculate entropy use `bregman divergence` + https://www.lix.polytechnique.fr/~nielsen/EntropyEF-ICIP2010.pdf + """ + entropy_value = -self._mean_carrier_measure + + natural_parameters = [] + for parameter in self._natural_parameters: + parameter = parameter.detach() + parameter.stop_gradient = False + natural_parameters.append(parameter) + + log_norm = self._log_normalizer(*natural_parameters) + + if _non_static_mode(): + grads = paddle.grad(log_norm.sum(), + natural_parameters, + create_graph=True) + else: + grads = paddle.static.gradients(log_norm.sum(), natural_parameters) + + entropy_value += log_norm + for p, g in zip(natural_parameters, grads): + entropy_value -= p * g + + return entropy_value diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/independent.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/independent.py new file mode 100644 index 0000000000000000000000000000000000000000..884c34b4b6adb2a930bb9b19f17ad3ee42b544e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/independent.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022 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. + +from paddle.distribution import distribution + + +class Independent(distribution.Distribution): + r""" + Reinterprets some of the batch dimensions of a distribution as event dimensions. + + This is mainly useful for changing the shape of the result of + :meth:`log_prob`. + + Args: + base (Distribution): The base distribution. + reinterpreted_batch_rank (int): The number of batch dimensions to + reinterpret as event dimensions. + + Examples: + + .. code-block:: python + + import paddle + from paddle.distribution import independent + + beta = paddle.distribution.Beta(paddle.to_tensor([0.5, 0.5]), paddle.to_tensor([0.5, 0.5])) + print(beta.batch_shape, beta.event_shape) + # (2,) () + print(beta.log_prob(paddle.to_tensor(0.2))) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.22843921, -0.22843921]) + reinterpreted_beta = independent.Independent(beta, 1) + print(reinterpreted_beta.batch_shape, reinterpreted_beta.event_shape) + # () (2,) + print(reinterpreted_beta.log_prob(paddle.to_tensor([0.2, 0.2]))) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.45687842]) + """ + + def __init__(self, base, reinterpreted_batch_rank): + if not isinstance(base, distribution.Distribution): + raise TypeError( + f"Expected type of 'base' is Distribution, but got {type(base)}" + ) + if not (0 < reinterpreted_batch_rank <= len(base.batch_shape)): + raise ValueError( + f"Expected 0 < reinterpreted_batch_rank <= {len(base.batch_shape)}, but got {reinterpreted_batch_rank}" + ) + self._base = base + self._reinterpreted_batch_rank = reinterpreted_batch_rank + + shape = base.batch_shape + base.event_shape + super(Independent, + self).__init__(batch_shape=shape[:len(base.batch_shape) - + reinterpreted_batch_rank], + event_shape=shape[len(base.batch_shape) - + reinterpreted_batch_rank:]) + + @property + def mean(self): + return self._base.mean + + @property + def variance(self): + return self._base.variance + + def sample(self, shape=()): + return self._base.sample(shape) + + def log_prob(self, value): + return self._sum_rightmost(self._base.log_prob(value), + self._reinterpreted_batch_rank) + + def prob(self, value): + return self.log_prob(value).exp() + + def entropy(self): + return self._sum_rightmost(self._base.entropy(), + self._reinterpreted_batch_rank) + + def _sum_rightmost(self, value, n): + return value.sum(list(range(-n, 0))) if n > 0 else value diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/kl.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/kl.py new file mode 100644 index 0000000000000000000000000000000000000000..34b18dd06b00b1d2e8c555267f9e9be500a23fd3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/kl.py @@ -0,0 +1,231 @@ +# Copyright (c) 2021 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. +import functools +import warnings + +import paddle +from paddle.distribution.beta import Beta +from paddle.distribution.categorical import Categorical +from paddle.distribution.dirichlet import Dirichlet +from paddle.distribution.distribution import Distribution +from paddle.distribution.exponential_family import ExponentialFamily +from paddle.distribution.normal import Normal +from paddle.distribution.uniform import Uniform +from paddle.fluid.framework import _non_static_mode, in_dygraph_mode + +__all__ = ["register_kl", "kl_divergence"] + +_REGISTER_TABLE = {} + + +def kl_divergence(p, q): + r""" + Kullback-Leibler divergence between distribution p and q. + + .. math:: + + KL(p||q) = \int p(x)log\frac{p(x)}{q(x)} \mathrm{d}x + + Args: + p (Distribution): ``Distribution`` object. Inherits from the Distribution Base class. + q (Distribution): ``Distribution`` object. Inherits from the Distribution Base class. + + Returns: + Tensor, Batchwise KL-divergence between distribution p and q. + + Examples: + + .. code-block:: python + + import paddle + + p = paddle.distribution.Beta(alpha=0.5, beta=0.5) + q = paddle.distribution.Beta(alpha=0.3, beta=0.7) + + print(paddle.distribution.kl_divergence(p, q)) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0.21193528]) + + """ + return _dispatch(type(p), type(q))(p, q) + + +def register_kl(cls_p, cls_q): + """Decorator for register a KL divergence implemention function. + + The ``kl_divergence(p, q)`` function will search concrete implemention + functions registered by ``register_kl``, according to multi-dispatch pattern. + If an implemention function is found, it will return the result, otherwise, + it will raise ``NotImplementError`` exception. Users can register + implemention funciton by the decorator. + + Args: + cls_p (Distribution): The Distribution type of Instance p. Subclass derived from ``Distribution``. + cls_q (Distribution): The Distribution type of Instance q. Subclass derived from ``Distribution``. + + Examples: + .. code-block:: python + + import paddle + + @paddle.distribution.register_kl(paddle.distribution.Beta, paddle.distribution.Beta) + def kl_beta_beta(): + pass # insert implementation here + """ + if not issubclass(cls_p, Distribution) or not issubclass( + cls_q, Distribution + ): + raise TypeError('cls_p and cls_q must be subclass of Distribution') + + def decorator(f): + _REGISTER_TABLE[cls_p, cls_q] = f + return f + + return decorator + + +def _dispatch(cls_p, cls_q): + """Multiple dispatch into concrete implement function""" + + # find all matched super class pair of p and q + matchs = [ + (super_p, super_q) + for super_p, super_q in _REGISTER_TABLE + if issubclass(cls_p, super_p) and issubclass(cls_q, super_q) + ] + if not matchs: + raise NotImplementedError + + left_p, left_q = min(_Compare(*m) for m in matchs).classes + right_p, right_q = min(_Compare(*reversed(m)) for m in matchs).classes + + if _REGISTER_TABLE[left_p, left_q] is not _REGISTER_TABLE[right_p, right_q]: + warnings.warn( + 'Ambiguous kl_divergence({}, {}). Please register_kl({}, {})'.format( + cls_p.__name__, + cls_q.__name__, + left_p.__name__, + right_q.__name__, + ), + RuntimeWarning, + ) + + return _REGISTER_TABLE[left_p, left_q] + + +@functools.total_ordering +class _Compare(object): + def __init__(self, *classes): + self.classes = classes + + def __eq__(self, other): + return self.classes == other.classes + + def __le__(self, other): + for cls_x, cls_y in zip(self.classes, other.classes): + if not issubclass(cls_x, cls_y): + return False + if cls_x is not cls_y: + break + return True + + +@register_kl(Beta, Beta) +def _kl_beta_beta(p, q): + return ( + (q.alpha.lgamma() + q.beta.lgamma() + (p.alpha + p.beta).lgamma()) + - (p.alpha.lgamma() + p.beta.lgamma() + (q.alpha + q.beta).lgamma()) + + ((p.alpha - q.alpha) * p.alpha.digamma()) + + ((p.beta - q.beta) * p.beta.digamma()) + + ( + ((q.alpha + q.beta) - (p.alpha + p.beta)) + * (p.alpha + p.beta).digamma() + ) + ) + + +@register_kl(Dirichlet, Dirichlet) +def _kl_dirichlet_dirichlet(p, q): + return ( + (p.concentration.sum(-1).lgamma() - q.concentration.sum(-1).lgamma()) + - ((p.concentration.lgamma() - q.concentration.lgamma()).sum(-1)) + + ( + ( + (p.concentration - q.concentration) + * ( + p.concentration.digamma() + - p.concentration.sum(-1).digamma().unsqueeze(-1) + ) + ).sum(-1) + ) + ) + + +@register_kl(Categorical, Categorical) +def _kl_categorical_categorical(p, q): + return p.kl_divergence(q) + + +@register_kl(Normal, Normal) +def _kl_normal_normal(p, q): + return p.kl_divergence(q) + + +@register_kl(Uniform, Uniform) +def _kl_uniform_uniform(p, q): + return p.kl_divergence(q) + + +@register_kl(ExponentialFamily, ExponentialFamily) +def _kl_expfamily_expfamily(p, q): + """Compute kl-divergence using `Bregman divergences `_""" + if not type(p) == type(q): + raise NotImplementedError + + p_natural_params = [] + for param in p._natural_parameters: + param = param.detach() + param.stop_gradient = False + p_natural_params.append(param) + + q_natural_params = q._natural_parameters + + p_log_norm = p._log_normalizer(*p_natural_params) + + try: + if _non_static_mode(): + p_grads = paddle.grad( + p_log_norm, p_natural_params, create_graph=True + ) + else: + p_grads = paddle.static.gradients(p_log_norm, p_natural_params) + except RuntimeError as e: + raise TypeError( + "Cann't compute kl_divergence({cls_p}, {cls_q}) use bregman divergence. Please register_kl({cls_p}, {cls_q}).".format( + cls_p=type(p).__name__, cls_q=type(q).__name__ + ) + ) from e + + kl = q._log_normalizer(*q_natural_params) - p_log_norm + for p_param, q_param, p_grad in zip( + p_natural_params, q_natural_params, p_grads + ): + term = (q_param - p_param) * p_grad + kl -= _sum_rightmost(term, len(q.event_shape)) + + return kl + + +def _sum_rightmost(value, n): + return value.sum(list(range(-n, 0))) if n > 0 else value diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/multinomial.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..424ec4b120d1b49c137730f1adab9717cd8d130d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/multinomial.py @@ -0,0 +1,193 @@ +# Copyright (c) 2022 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. + +import collections + +import paddle +from paddle.distribution import categorical, distribution +try: + from collections.abc import Iterable +except: + from collections import Iterable + + +class Multinomial(distribution.Distribution): + r""" + Multinomial distribution parameterized by :attr:`total_count` and + :attr:`probs`. + + In probability theory, the multinomial distribution is a generalization of + the binomial distribution, it models the probability of counts for each side + of a k-sided die rolled n times. When k is 2 and n is 1, the multinomial is + the bernoulli distribution, when k is 2 and n is grater than 1, it is the + binomial distribution, when k is grater than 2 and n is 1, it is the + categorical distribution. + + The probability mass function (PMF) for multinomial is + + .. math:: + + f(x_1, ..., x_k; n, p_1,...,p_k) = \frac{n!}{x_1!...x_k!}p_1^{x_1}...p_k^{x_k} + + where, :math:`n` is number of trials, k is the number of categories, + :math:`p_i` denote probability of a trial falling into each category, + :math:`{\textstyle \sum_{i=1}^{k}p_i=1}, p_i \ge 0`, and :math:`x_i` denote + count of each category. + + Args: + total_count (int): Number of trials. + probs (Tensor): Probability of a trial falling into each category. Last + axis of probs indexes over categories, other axes index over batches. + Probs value should between [0, 1], and sum to 1 along last axis. If + the value over 1, it will be normalized to sum to 1 along the last + axis. + + Examples: + + .. code-block:: python + + import paddle + + multinomial = paddle.distribution.Multinomial(10, paddle.to_tensor([0.2, 0.3, 0.5])) + print(multinomial.sample((2, 3))) + # Tensor(shape=[2, 3, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[1., 4., 5.], + # [0., 2., 8.], + # [2., 4., 4.]], + + # [[1., 6., 3.], + # [3., 3., 4.], + # [3., 4., 3.]]]) + """ + + def __init__(self, total_count, probs): + if not isinstance(total_count, int) or total_count < 1: + raise ValueError( + 'input parameter total_count must be int type and grater than zero.' + ) + + if probs.dim() < 1: + raise ValueError( + 'probs parameter shoule not be none and over one dimension') + + self.probs = probs / probs.sum(-1, keepdim=True) + self.total_count = total_count + self._categorical = categorical.Categorical( + logits=self._probs_to_logits(probs)) + + super(Multinomial, self).__init__(probs.shape[:-1], probs.shape[-1:]) + + @property + def mean(self): + """mean of multinomial distribuion. + + Returns: + Tensor: mean value. + """ + return self.probs * self.total_count + + @property + def variance(self): + """variance of multinomial distribution. + + Returns: + Tensor: variance value. + """ + return self.total_count * self.probs * (1 - self.probs) + + def prob(self, value): + """probability mass function evaluated at value. + + Args: + value (Tensor): value to be evaluated. + + Returns: + Tensor: probability of value. + """ + return paddle.exp(self.log_prob(value)) + + def log_prob(self, value): + """probability mass function evaluated at value + + Args: + value (Tensor): value to be evaluated. + + Returns: + Tensor: probability of value. + """ + if paddle.is_integer(value): + value = paddle.cast(value, self.probs.dtype) + + logits, value = paddle.broadcast_tensors( + [paddle.log(self.probs), value]) + logits[(value == 0) & (paddle.isinf(logits))] = 0 + + return (paddle.lgamma(value.sum(-1) + 1) - + paddle.lgamma(value + 1).sum(-1) + (value * logits).sum(-1)) + + def sample(self, shape=()): + """draw sample data from multinomial distribution + + Args: + sample_shape (tuple, optional): [description]. Defaults to (). + """ + if not isinstance(shape, Iterable): + raise TypeError('sample shape must be Iterable object.') + + samples = self._categorical.sample([ + self.total_count, + ] + list(shape)) + return paddle.nn.functional.one_hot(samples, self.probs.shape[-1]).cast( + self.probs.dtype).sum(0) + + def entropy(self): + """entropy of multinomial distribution + + Returns: + Tensor: entropy value + """ + n = paddle.full(shape=[1], + fill_value=self.total_count, + dtype=self.probs.dtype) + support = paddle.arange( + self.total_count + 1, + dtype=self.probs.dtype).reshape((-1, ) + + (1, ) * len(self.probs.shape))[1:] + + binomial_pmf = paddle.exp(self._binomial_logpmf(n, support)) + + return ((n * self._categorical.entropy() - paddle.lgamma(n + 1)) + + ((binomial_pmf * paddle.lgamma(support + 1)).sum([0, -1]))) + + def _binomial_logpmf(self, count, value): + logits = self._probs_to_logits(self.probs, is_binary=True) + + factor_n = paddle.lgamma(count + 1) + factor_k = paddle.lgamma(value + 1) + factor_nmk = paddle.lgamma(count - value + 1) + + norm = (count * _clip_by_zero(logits) + + count * paddle.log1p(paddle.exp(-paddle.abs(logits))) - + factor_n) + + return value * logits - factor_k - factor_nmk - norm + + +def _binomial_support(count, dtype): + return paddle.arange(count + 1, dtype=dtype) + + +def _clip_by_zero(x): + # like clip(x, min=0) but grad at 0 is 0.5 + return (x.clip(min=0) + x - x.clip(max=0)) / 2 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/normal.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/normal.py new file mode 100644 index 0000000000000000000000000000000000000000..91c795f334904169bfc06aa66b0d10f12999c634 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/normal.py @@ -0,0 +1,308 @@ +# Copyright (c) 2021 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. + +import math +import warnings + +import numpy as np +from paddle import _C_ops, _legacy_C_ops +from paddle.distribution import distribution +from paddle.fluid import core +from paddle.fluid.data_feeder import ( + check_dtype, + check_type, + check_variable_and_dtype, + convert_dtype, +) +from paddle.fluid.framework import _non_static_mode, in_dygraph_mode +from paddle.fluid.layers import ( + control_flow, + elementwise_add, + elementwise_div, + elementwise_mul, + elementwise_sub, + nn, + ops, + tensor, +) + + +class Normal(distribution.Distribution): + r"""The Normal distribution with location `loc` and `scale` parameters. + + Mathematical details + + The probability density function (pdf) is + + .. math:: + + pdf(x; \mu, \sigma) = \frac{1}{Z}e^{\frac {-0.5 (x - \mu)^2} {\sigma^2} } + + .. math:: + + Z = (2 \pi \sigma^2)^{0.5} + + In the above equation: + + * :math:`loc = \mu`: is the mean. + * :math:`scale = \sigma`: is the std. + * :math:`Z`: is the normalization constant. + + Args: + loc(int|float|list|tuple|numpy.ndarray|Tensor): The mean of normal distribution.The data type is float32 and float64. + scale(int|float|list|tuple|numpy.ndarray|Tensor): The std of normal distribution.The data type is float32 and float64. + name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Examples: + .. code-block:: python + + import paddle + from paddle.distribution import Normal + + # Define a single scalar Normal distribution. + dist = Normal(loc=0., scale=3.) + # Define a batch of two scalar valued Normals. + # The first has mean 1 and standard deviation 11, the second 2 and 22. + dist = Normal(loc=[1., 2.], scale=[11., 22.]) + # Get 3 samples, returning a 3 x 2 tensor. + dist.sample([3]) + + # Define a batch of two scalar valued Normals. + # Both have mean 1, but different standard deviations. + dist = Normal(loc=1., scale=[11., 22.]) + + # Complete example + value_tensor = paddle.to_tensor([0.8], dtype="float32") + + normal_a = Normal([0.], [1.]) + normal_b = Normal([0.5], [2.]) + sample = normal_a.sample([2]) + # a random tensor created by normal distribution with shape: [2, 1] + entropy = normal_a.entropy() + # [1.4189385] with shape: [1] + lp = normal_a.log_prob(value_tensor) + # [-1.2389386] with shape: [1] + p = normal_a.probs(value_tensor) + # [0.28969154] with shape: [1] + kl = normal_a.kl_divergence(normal_b) + # [0.34939718] with shape: [1] + """ + + def __init__(self, loc, scale, name=None): + if not _non_static_mode(): + check_type( + loc, + 'loc', + (int, float, np.ndarray, tensor.Variable, list, tuple), + 'Normal', + ) + check_type( + scale, + 'scale', + (int, float, np.ndarray, tensor.Variable, list, tuple), + 'Normal', + ) + + self.batch_size_unknown = False + self.all_arg_is_float = False + self.name = name if name is not None else 'Normal' + self.dtype = 'float32' + + if isinstance(loc, int): + loc = float(loc) + if isinstance(scale, int): + scale = float(scale) + + if self._validate_args(loc, scale): + self.batch_size_unknown = True + self.loc = loc + self.scale = scale + self.dtype = convert_dtype(loc.dtype) + else: + if isinstance(loc, float) and isinstance(scale, float): + self.all_arg_is_float = True + if isinstance(loc, np.ndarray) and str(loc.dtype) in [ + 'float32', + 'float64', + ]: + self.dtype = loc.dtype + elif isinstance(scale, np.ndarray) and str(scale.dtype) in [ + 'float32', + 'float64', + ]: + self.dtype = scale.dtype + # pylint: disable=unbalanced-tuple-unpacking + self.loc, self.scale = self._to_tensor(loc, scale) + if self.dtype != convert_dtype(self.loc.dtype): + self.loc = tensor.cast(self.loc, dtype=self.dtype) + self.scale = tensor.cast(self.scale, dtype=self.dtype) + super(Normal, self).__init__(self.loc.shape) + + def sample(self, shape, seed=0): + """Generate samples of the specified shape. + + Args: + shape (list): 1D `int32`. Shape of the generated samples. + seed (int): Python integer number. + + Returns: + Tensor, A tensor with prepended dimensions shape.The data type is float32. + + """ + if not _non_static_mode(): + check_type(shape, 'shape', (list), 'sample') + check_type(seed, 'seed', (int), 'sample') + + batch_shape = list((self.loc + self.scale).shape) + name = self.name + '_sample' + + if self.batch_size_unknown: + output_shape = shape + batch_shape + zero_tmp = tensor.fill_constant_batch_size_like( + self.loc + self.scale, batch_shape + shape, self.dtype, 0.0 + ) + zero_tmp_reshape = nn.reshape(zero_tmp, output_shape) + zero_tmp_shape = nn.shape(zero_tmp_reshape) + normal_random_tmp = nn.gaussian_random( + zero_tmp_shape, mean=0.0, std=1.0, seed=seed, dtype=self.dtype + ) + output = normal_random_tmp * (zero_tmp_reshape + self.scale) + output = elementwise_add(output, self.loc, name=name) + return output + else: + output_shape = shape + batch_shape + output = nn.gaussian_random( + output_shape, mean=0.0, std=1.0, seed=seed, dtype=self.dtype + ) * (tensor.zeros(output_shape, dtype=self.dtype) + self.scale) + output = elementwise_add(output, self.loc, name=name) + if self.all_arg_is_float: + return nn.reshape(output, shape, name=name) + else: + return output + + def entropy(self): + r"""Shannon entropy in nats. + + The entropy is + + .. math:: + + entropy(\sigma) = 0.5 \log (2 \pi e \sigma^2) + + In the above equation: + + * :math:`scale = \sigma`: is the std. + + Returns: + Tensor, Shannon entropy of normal distribution.The data type is float32. + + """ + name = self.name + '_entropy' + batch_shape = list((self.loc + self.scale).shape) + zero_tmp = tensor.fill_constant_batch_size_like( + self.loc + self.scale, batch_shape, self.dtype, 0.0 + ) + return elementwise_add( + 0.5 + zero_tmp, + 0.5 * math.log(2 * math.pi) + nn.log((self.scale + zero_tmp)), + name=name, + ) + + def log_prob(self, value): + """Log probability density/mass function. + + Args: + value (Tensor): The input tensor. + + Returns: + Tensor: log probability.The data type is same with value. + + """ + name = self.name + '_log_prob' + value = self._check_values_dtype_in_probs(self.loc, value) + + var = self.scale * self.scale + log_scale = nn.log(self.scale) + return elementwise_sub( + -1.0 * ((value - self.loc) * (value - self.loc)) / (2.0 * var), + log_scale + math.log(math.sqrt(2.0 * math.pi)), + name=name, + ) + + def probs(self, value): + """Probability density/mass function. + + Args: + value (Tensor): The input tensor. + + Returns: + Tensor, probability. The data type is same with value. + + """ + name = self.name + '_probs' + value = self._check_values_dtype_in_probs(self.loc, value) + + var = self.scale * self.scale + return elementwise_div( + ops.exp( + -1.0 * ((value - self.loc) * (value - self.loc)) / (2.0 * var) + ), + (math.sqrt(2 * math.pi) * self.scale), + name=name, + ) + + def kl_divergence(self, other): + r"""The KL-divergence between two normal distributions. + + The probability density function (pdf) is + + .. math:: + + KL\_divergence(\mu_0, \sigma_0; \mu_1, \sigma_1) = 0.5 (ratio^2 + (\frac{diff}{\sigma_1})^2 - 1 - 2 \ln {ratio}) + + .. math:: + + ratio = \frac{\sigma_0}{\sigma_1} + + .. math:: + + diff = \mu_1 - \mu_0 + + In the above equation: + + * :math:`loc = \mu_0`: is the mean of current Normal distribution. + * :math:`scale = \sigma_0`: is the std of current Normal distribution. + * :math:`loc = \mu_1`: is the mean of other Normal distribution. + * :math:`scale = \sigma_1`: is the std of other Normal distribution. + * :math:`ratio`: is the ratio of scales. + * :math:`diff`: is the difference between means. + + Args: + other (Normal): instance of Normal. + + Returns: + Tensor, kl-divergence between two normal distributions.The data type is float32. + + """ + if not _non_static_mode(): + check_type(other, 'other', Normal, 'kl_divergence') + + name = self.name + '_kl_divergence' + var_ratio = self.scale / other.scale + var_ratio = var_ratio * var_ratio + t1 = (self.loc - other.loc) / other.scale + t1 = t1 * t1 + return elementwise_add( + 0.5 * var_ratio, 0.5 * (t1 - 1.0 - nn.log(var_ratio)), name=name + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transform.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..986416e3c59555aaa7804972ed29b4ce9c4a0ff0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transform.py @@ -0,0 +1,1286 @@ +# Copyright (c) 2022 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. + +import enum +import functools +import math +import numbers +import operator +import typing + +import paddle +import paddle.nn.functional as F +from paddle.distribution import ( + constraint, + distribution, + transformed_distribution, + variable, +) + +__all__ = [ # noqa + 'Transform', + 'AbsTransform', + 'AffineTransform', + 'ChainTransform', + 'ExpTransform', + 'IndependentTransform', + 'PowerTransform', + 'ReshapeTransform', + 'SigmoidTransform', + 'SoftmaxTransform', + 'StackTransform', + 'StickBreakingTransform', + 'TanhTransform', +] + + +class Type(enum.Enum): + """Mapping type of a transformation.""" + + BIJECTION = 'bijection' # bijective(injective and surjective) + INJECTION = 'injection' # injective-only + SURJECTION = 'surjection' # surjective-only + OTHER = 'other' # general, neither injective nor surjective + + @classmethod + def is_injective(cls, _type): + """Both bijection and injection are injective mapping.""" + return _type in (cls.BIJECTION, cls.INJECTION) + + +class Transform(object): + r"""Base class for the transformations of random variables. + + ``Transform`` can be used to represent any differentiable and injective + function from the subset of :math:`R^n` to subset of :math:`R^m`, generally + used for transforming a random sample generated by ``Distribution`` + instance. + + Suppose :math:`X` is a K-dimensional random variable with probability + density function :math:`p_X(x)`. A new random variable :math:`Y = f(X)` may + be defined by transforming :math:`X` with a suitably well-behaved funciton + :math:`f`. It suffices for what follows to note that if `f` is one-to-one and + its inverse :math:`f^{-1}` have a well-defined Jacobian, then the density of + :math:`Y` is + + .. math:: + + p_Y(y) = p_X(f^{-1}(y)) |det J_{f^{-1}}(y)| + + where det is the matrix determinant operation and :math:`J_{f^{-1}}(y)` is + the Jacobian matrix of :math:`f^{-1}` evaluated at :math:`y`. + Taking :math:`x = f^{-1}(y)`, the Jacobian matrix is defined by + + .. math:: + + J(y) = \begin{bmatrix} + {\frac{\partial x_1}{\partial y_1}} &{\frac{\partial x_1}{\partial y_2}} + &{\cdots} &{\frac{\partial x_1}{\partial y_K}} \\ + {\frac{\partial x_2}{\partial y_1}} &{\frac{\partial x_2} + {\partial y_2}}&{\cdots} &{\frac{\partial x_2}{\partial y_K}} \\ + {\vdots} &{\vdots} &{\ddots} &{\vdots}\\ + {\frac{\partial x_K}{\partial y_1}} &{\frac{\partial x_K}{\partial y_2}} + &{\cdots} &{\frac{\partial x_K}{\partial y_K}} + \end{bmatrix} + + A ``Transform`` can be characterized by three operations: + + #. forward + Forward implements :math:`x \rightarrow f(x)`, and is used to convert + one random outcome into another. + #. inverse + Undoes the transformation :math:`y \rightarrow f^{-1}(y)`. + #. log_det_jacobian + The log of the absolute value of the determinant of the matrix of all + first-order partial derivatives of the inverse function. + + Subclass typically implement follow methods: + + * _forward + * _inverse + * _forward_log_det_jacobian + * _inverse_log_det_jacobian (optional) + + If the transform changes the shape of the input, you must also implemented: + + * _forward_shape + * _inverse_shape + + """ + _type = Type.INJECTION + + def __init__(self): + super(Transform, self).__init__() + + @classmethod + def _is_injective(cls): + """Is the transformation type one-to-one or not. + + Returns: + bool: ``True`` denotes injective. ``False`` denotes non-injective. + """ + return Type.is_injective(cls._type) + + def __call__(self, input): + """Make this instance as a callable object. The return value is + depening on the input type. + + * If the input is a ``Tensor`` instance, return + ``self.forward(input)`` . + * If the input is a ``Distribution`` instance, return + ``TransformedDistribution(base=input, transforms=[self])`` . + * If the input is a ``Transform`` instance, return + ``ChainTransform([self, input])`` . + + Args: + input (Tensor|Distribution|Transform): The input value. + + Returns: + [Tensor|TransformedDistribution|ChainTransform]: The return value. + """ + if isinstance(input, distribution.Distribution): + return transformed_distribution.TransformedDistribution( + input, [self] + ) + if isinstance(input, Transform): + return ChainTransform([self, input]) + return self.forward(x) + + def forward(self, x): + """Forward transformation with mapping :math:`y = f(x)`. + + Useful for turning one random outcome into another. + + Args: + x (Tensos): Input parameter, generally is a sample generated + from ``Distribution``. + + Returns: + Tensor: Outcome of forward transformation. + """ + if not isinstance(x, paddle.fluid.framework.Variable): + raise TypeError( + f"Expected 'x' is a Tensor or Real, but got {type(x)}." + ) + if x.dim() < self._domain.event_rank: + raise ValueError( + f'The dimensions of x({x.dim()}) should be ' + f'grater than or equal to {self._domain.event_rank}' + ) + return self._forward(x) + + def inverse(self, y): + """Inverse transformation :math:`x = f^{-1}(y)`. It's useful for "reversing" + a transformation to compute one probability in terms of another. + + Args: + y (Tensor): Input parameter for inverse transformation. + + Returns: + Tensor: Outcome of inverse transform. + """ + if not isinstance(y, paddle.fluid.framework.Variable): + raise TypeError( + f"Expected 'y' is a Tensor or Real, but got {type(y)}." + ) + if y.dim() < self._codomain.event_rank: + raise ValueError( + f'The dimensions of y({y.dim()}) should be ' + f'grater than or equal to {self._codomain.event_rank}' + ) + return self._inverse(y) + + def forward_log_det_jacobian(self, x): + """The log of the absolute value of the determinant of the matrix of all + first-order partial derivatives of the inverse function. + + Args: + x (Tensor): Input tensor, generally is a sample generated from + ``Distribution`` + + Returns: + Tensor: The log of the absolute value of Jacobian determinant. + """ + if not isinstance(x, paddle.fluid.framework.Variable): + raise TypeError( + f"Expected 'y' is a Tensor or Real, but got {type(x)}." + ) + if ( + isinstance(x, paddle.fluid.framework.Variable) + and x.dim() < self._domain.event_rank + ): + raise ValueError( + f'The dimensions of x({x.dim()}) should be ' + f'grater than or equal to {self._domain.event_rank}' + ) + if not self._is_injective(): + raise NotImplementedError( + "forward_log_det_jacobian can't be implemented for non-injective" + "transforms." + ) + + return self._call_forward_log_det_jacobian(x) + + def inverse_log_det_jacobian(self, y): + """Compute :math:`log|det J_{f^{-1}}(y)|`. + Note that ``forward_log_det_jacobian`` is the negative of this function, + evaluated at :math:`f^{-1}(y)`. + + Args: + y (Tensor): The input to the ``inverse`` Jacobian determinant + evaluation. + + Returns: + Tensor: The value of :math:`log|det J_{f^{-1}}(y)|`. + """ + if not isinstance(y, paddle.fluid.framework.Variable): + raise TypeError(f"Expected 'y' is a Tensor, but got {type(y)}.") + if y.dim() < self._codomain.event_rank: + raise ValueError( + f'The dimensions of y({y.dim()}) should be ' + f'grater than or equal to {self._codomain.event_rank}' + ) + return self._call_inverse_log_det_jacobian(y) + + def forward_shape(self, shape): + """Infer the shape of forward transformation. + + Args: + shape (Sequence[int]): The input shape. + + Returns: + Sequence[int]: The output shape. + """ + if not isinstance(shape, typing.Sequence): + raise TypeError( + f"Expected shape is Sequence[int] type, but got {type(shape)}." + ) + return self._forward_shape(shape) + + def inverse_shape(self, shape): + """Infer the shape of inverse transformation. + + Args: + shape (Sequence[int]): The input shape of inverse transformation. + + Returns: + Sequence[int]: The output shape of inverse transformation. + """ + if not isinstance(shape, typing.Sequence): + raise TypeError( + f"Expected shape is Sequence[int] type, but got {type(shape)}." + ) + return self._inverse_shape(shape) + + @property + def _domain(self): + """The domain of this transformation""" + return variable.real + + @property + def _codomain(self): + """The codomain of this transformation""" + return variable.real + + def _forward(self, x): + """Inner method for publid API ``forward``, subclass should + overwrite this method for supporting forward transformation. + """ + raise NotImplementedError('Forward not implemented') + + def _inverse(self, y): + """Inner method of public API ``inverse``, subclass should + overwrite this method for supporting inverse transformation. + """ + raise NotImplementedError('Inverse not implemented') + + def _call_forward_log_det_jacobian(self, x): + """Inner method called by ``forward_log_det_jacobian``.""" + if hasattr(self, '_forward_log_det_jacobian'): + return self._forward_log_det_jacobian(x) + if hasattr(self, '_inverse_log_det_jacobian'): + return -self._inverse_log_det_jacobian(self.forward(y)) + raise NotImplementedError( + 'Neither _forward_log_det_jacobian nor _inverse_log_det_jacobian' + 'is implemented. One of them is required.' + ) + + def _call_inverse_log_det_jacobian(self, y): + """Inner method called by ``inverse_log_det_jacobian``""" + if hasattr(self, '_inverse_log_det_jacobian'): + return self._inverse_log_det_jacobian(y) + if hasattr(self, '_forward_log_det_jacobian'): + return -self._forward_log_det_jacobian(self._inverse(y)) + raise NotImplementedError( + 'Neither _forward_log_det_jacobian nor _inverse_log_det_jacobian ' + 'is implemented. One of them is required' + ) + + def _forward_shape(self, shape): + """Inner method called by ``forward_shape``, which is used to infer the + forward shape. Subclass should overwrite this method for supporting + ``forward_shape``. + """ + return shape + + def _inverse_shape(self, shape): + """Inner method called by ``inverse_shape``, whic is used to infer the + invese shape. Subclass should overwrite this method for supporting + ``inverse_shape``. + """ + return shape + + +class AbsTransform(Transform): + r"""Absolute transformation with formula :math:`y = f(x) = abs(x)`, + element-wise. + + This non-injective transformation allows for transformations of scalar + distributions with the absolute value function, which maps ``(-inf, inf)`` + to ``[0, inf)`` . + + * For ``y`` in ``(0, inf)`` , ``AbsTransform.inverse(y)`` returns the set invese + ``{x in (-inf, inf) : |x| = y}`` as a tuple, ``-y, y`` . + * For ``y`` equal ``0`` , ``AbsTransform.inverse(0)`` returns ``0, 0``, which is not + the set inverse (the set inverse is the singleton {0}), but "works" in + conjunction with ``TransformedDistribution`` to produce a left + semi-continuous pdf. + * For ``y`` in ``(-inf, 0)`` , ``AbsTransform.inverse(y)`` returns the + wrong thing ``-y, y``. This is done for efficiency. + + Examples: + + .. code-block:: python + + import paddle + + abs = paddle.distribution.AbsTransform() + + print(abs.forward(paddle.to_tensor([-1., 0., 1.]))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 0., 1.]) + + print(abs.inverse(paddle.to_tensor(1.))) + # (Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-1.]), Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.])) + + # The |dX/dY| is constant 1. So Log|dX/dY| == 0 + print(abs.inverse_log_det_jacobian(paddle.to_tensor(1.))) + # (Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # 0.), Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # 0.)) + + #Special case handling of 0. + print(abs.inverse(paddle.to_tensor(0.))) + # (Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.]), Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.])) + print(abs.inverse_log_det_jacobian(paddle.to_tensor(0.))) + # (Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # 0.), Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # 0.)) + + """ + _type = Type.SURJECTION + + def _forward(self, x): + return x.abs() + + def _inverse(self, y): + return -y, y + + def _inverse_log_det_jacobian(self, y): + zero = paddle.zeros([1], dtype=y.dtype) + return zero, zero + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.positive + + +class AffineTransform(Transform): + r"""Affine transformation with mapping + :math:`y = \text{loc} + \text{scale} \times x`. + + Args: + loc (Tensor): The location parameter. + scale (Tensor): The scale parameter. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1., 2.]) + affine = paddle.distribution.AffineTransform(paddle.to_tensor(0.), paddle.to_tensor(1.)) + + print(affine.forward(x)) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 2.]) + print(affine.inverse(affine.forward(x))) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 2.]) + print(affine.forward_log_det_jacobian(x)) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.]) + """ + _type = Type.BIJECTION + + def __init__(self, loc, scale): + if not isinstance(loc, paddle.fluid.framework.Variable): + raise TypeError(f"Expected 'loc' is a Tensor, but got {type(loc)}") + if not isinstance(scale, paddle.fluid.framework.Variable): + raise TypeError( + f"Expected scale is a Tensor, but got {type(scale)}" + ) + self._loc = loc + self._scale = scale + super(AffineTransform, self).__init__() + + @property + def loc(self): + return self._loc + + @property + def scale(self): + return self._scale + + def _forward(self, x): + return self._loc + self._scale * x + + def _inverse(self, y): + return (y - self._loc) / self._scale + + def _forward_log_det_jacobian(self, x): + return paddle.abs(self._scale).log() + + def _forward_shape(self, shape): + return tuple( + paddle.broadcast_shape( + paddle.broadcast_shape(shape, self._loc.shape), + self._scale.shape, + ) + ) + + def _inverse_shape(self, shape): + return tuple( + paddle.broadcast_shape( + paddle.broadcast_shape(shape, self._loc.shape), + self._scale.shape, + ) + ) + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.real + + +class ChainTransform(Transform): + r"""Composes multiple transforms in a chain. + + Args: + transforms (Sequence[Transform]): A sequence of transformations. + + Examples: + + .. code-block:: python + + import paddle + + + x = paddle.to_tensor([0., 1., 2., 3.]) + + chain = paddle.distribution.ChainTransform(( + paddle.distribution.AffineTransform( + paddle.to_tensor(0.), paddle.to_tensor(1.)), + paddle.distribution.ExpTransform() + )) + print(chain.forward(x)) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1. , 2.71828175 , 7.38905621 , 20.08553696]) + print(chain.inverse(chain.forward(x))) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0., 1., 2., 3.]) + print(chain.forward_log_det_jacobian(x)) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0., 1., 2., 3.]) + print(chain.inverse_log_det_jacobian(chain.forward(x))) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [ 0., -1., -2., -3.]) + """ + + def __init__(self, transforms): + if not isinstance(transforms, typing.Sequence): + raise TypeError( + f"Expected type of 'transforms' is Sequence, but got {type(transforms)}" + ) + if not all(isinstance(t, Transform) for t in transforms): + raise TypeError( + "All elements of transforms should be Transform type." + ) + + self.transforms = transforms + super(ChainTransform, self).__init__() + + def _is_injective(self): + return all(t._is_injective() for t in self.transforms) + + def _forward(self, x): + for transform in self.transforms: + x = transform.forward(x) + return x + + def _inverse(self, y): + for transform in reversed(self.transforms): + y = transform.inverse(y) + return y + + def _forward_log_det_jacobian(self, x): + value = 0.0 + event_rank = self._domain.event_rank + for t in self.transforms: + value += self._sum_rightmost( + t.forward_log_det_jacobian(x), event_rank - t._domain.event_rank + ) + x = t.forward(x) + event_rank += t._codomain.event_rank - t._domain.event_rank + return value + + def _forward_shape(self, shape): + for transform in self.transforms: + shape = transform.forward_shape(shape) + return shape + + def _inverse_shape(self, shape): + for transform in self.transforms: + shape = transform.inverse_shape(shape) + return shape + + def _sum_rightmost(self, value, n): + """sum value along rightmost n dim""" + return value.sum(list(range(-n, 0))) if n > 0 else value + + @property + def _domain(self): + domain = self.transforms[0]._domain + + # Compute the lower bound of input dimensions for chain transform. + # + # Suppose the dimensions of input tensor is N, and chain [t0,...ti,...tm], + # ti(in) denotes ti.domain.event_rank, ti(out) denotes ti.codomain.event_rank, + # delta(ti) denotes (ti(out) - ti(in)). + # For transform ti, N shoud satisfy the constraint: + # N + delta(t0) + delta(t1)...delta(t(i-1)) >= ti(in) + # So, for all transform in chain, N shoud satisfy follow constraints: + # t0: N >= t0(in) + # t1: N >= t1(in) - delta(t0) + # ... + # tm: N >= tm(in) - ... - delta(ti) - ... - delta(t0) + # + # Above problem can be solved more effectively use dynamic programming. + # Let N(i) denotes lower bound of transform ti, than the state + # transition equation is: + # N(i) = max{N(i+1)-delta(ti), ti(in)} + event_rank = self.transforms[-1]._codomain.event_rank + for t in reversed(self.transforms): + event_rank -= t._codomain.event_rank - t._domain.event_rank + event_rank = max(event_rank, t._domain.event_rank) + + return variable.Independent(domain, event_rank - domain.event_rank) + + @property + def _codomain(self): + codomain = self.transforms[-1]._codomain + + event_rank = self.transforms[0]._domain.event_rank + for t in self.transforms: + event_rank += t._codomain.event_rank - t._domain.event_rank + event_rank = max(event_rank, t._codomain.event_rank) + + return variable.Independent(codomain, event_rank - codomain.event_rank) + + +class ExpTransform(Transform): + r"""Exponent transformation with mapping :math:`y = \exp(x)`. + + Examples: + + .. code-block:: python + + import paddle + + exp = paddle.distribution.ExpTransform() + print(exp.forward(paddle.to_tensor([1., 2., 3.]))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2.71828175 , 7.38905621 , 20.08553696]) + + print(exp.inverse(paddle.to_tensor([1., 2., 3.]))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0. , 0.69314718, 1.09861231]) + + print(exp.forward_log_det_jacobian(paddle.to_tensor([1., 2., 3.]))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 2., 3.]) + + print(exp.inverse_log_det_jacobian(paddle.to_tensor([1., 2., 3.]))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [ 0. , -0.69314718, -1.09861231]) + """ + _type = Type.BIJECTION + + def __init__(self): + super(ExpTransform, self).__init__() + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.positive + + def _forward(self, x): + return x.exp() + + def _inverse(self, y): + return y.log() + + def _forward_log_det_jacobian(self, x): + return x + + +class IndependentTransform(Transform): + r""" + ``IndependentTransform`` wraps a base transformation, reinterprets + some of the rightmost batch axes as event axes. + + Generally, it is used to expand the event axes. This has no effect on the + forward or inverse transformaion, but does sum out the + ``reinterpretd_bach_rank`` rightmost dimensions in computing the determinant + of Jacobian matrix. + + To see this, consider the ``ExpTransform`` applied to a Tensor which has + sample, batch, and event ``(S,B,E)`` shape semantics. Suppose the Tensor's + paritioned-shape is ``(S=[4], B=[2, 2], E=[3])`` , reinterpreted_batch_rank + is 1. Then the reinterpreted Tensor's shape is ``(S=[4], B=[2], E=[2, 3])`` . + The shape returned by ``forward`` and ``inverse`` is unchanged, ie, + ``[4,2,2,3]`` . However the shape returned by ``inverse_log_det_jacobian`` + is ``[4,2]``, because the Jacobian determinant is a reduction over the + event dimensions. + + Args: + base (Transform): The base transformation. + reinterpreted_batch_rank (int): The num of rightmost batch rank that + will be reinterpreted as event rank. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1., 2., 3.], [4., 5., 6.]]) + + # Exponential transform with event_rank = 1 + multi_exp = paddle.distribution.IndependentTransform( + paddle.distribution.ExpTransform(), 1) + print(multi_exp.forward(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[2.71828175 , 7.38905621 , 20.08553696 ], + # [54.59814835 , 148.41316223, 403.42880249]]) + print(multi_exp.forward_log_det_jacobian(x)) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [6. , 15.]) + """ + + def __init__(self, base, reinterpreted_batch_rank): + if not isinstance(base, Transform): + raise TypeError( + f"Expected 'base' is Transform type, but get {type(base)}" + ) + if reinterpreted_batch_rank <= 0: + raise ValueError( + f"Expected 'reinterpreted_batch_rank' is grater than zero, but got {reinterpreted_batch_rank}" + ) + + self._base = base + self._reinterpreted_batch_rank = reinterpreted_batch_rank + super(IndependentTransform, self).__init__() + + def _is_injective(self): + return self._base._is_injective() + + def _forward(self, x): + if x.dim() < self._domain.event_rank: + raise ValueError("Input dimensions is less than event dimensions.") + return self._base.forward(x) + + def _inverse(self, y): + if y.dim() < self._codomain.event_rank: + raise ValueError("Input dimensions is less than event dimensions.") + return self._base.inverse(y) + + def _forward_log_det_jacobian(self, x): + return self._base.forward_log_det_jacobian(x).sum( + list(range(-self._reinterpreted_batch_rank, 0)) + ) + + def _forward_shape(self, shape): + return self._base.forward_shape(shape) + + def _inverse_shape(self, shape): + return self._base.inverse_shape(shape) + + @property + def _domain(self): + return variable.Independent( + self._base._domain, self._reinterpreted_batch_rank + ) + + @property + def _codomain(self): + return variable.Independent( + self._base._codomain, self._reinterpreted_batch_rank + ) + + +class PowerTransform(Transform): + r""" + Power transformation with mapping :math:`y = x^{\text{power}}`. + + Args: + power (Tensor): The power parameter. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1., 2.]) + power = paddle.distribution.PowerTransform(paddle.to_tensor(2.)) + + print(power.forward(x)) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 4.]) + print(power.inverse(power.forward(x))) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1., 2.]) + print(power.forward_log_det_jacobian(x)) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.69314718, 1.38629436]) + """ + _type = Type.BIJECTION + + def __init__(self, power): + if not isinstance(power, paddle.fluid.framework.Variable): + raise TypeError( + f"Expected 'power' is a tensor, but got {type(power)}" + ) + self._power = power + super(PowerTransform, self).__init__() + + @property + def power(self): + return self._power + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.positive + + def _forward(self, x): + return x.pow(self._power) + + def _inverse(self, y): + return y.pow(1 / self._power) + + def _forward_log_det_jacobian(self, x): + return (self._power * x.pow(self._power - 1)).abs().log() + + def _forward_shape(self, shape): + return tuple(paddle.broadcast_shape(shape, self._power.shape)) + + def _inverse_shape(self, shape): + return tuple(paddle.broadcast_shape(shape, self._power.shape)) + + +class ReshapeTransform(Transform): + r"""Reshape the event shape of a tensor. + + Note that ``in_event_shape`` and ``out_event_shape`` must have the same + number of elements. + + Args: + in_event_shape(Sequence[int]): The input event shape. + out_event_shape(Sequence[int]): The output event shape. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.ones((1,2,3)) + reshape_transform = paddle.distribution.ReshapeTransform((2, 3), (3, 2)) + print(reshape_transform.forward_shape((1,2,3))) + # (5, 2, 6) + print(reshape_transform.forward(x)) + # Tensor(shape=[1, 3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[1., 1.], + # [1., 1.], + # [1., 1.]]]) + print(reshape_transform.inverse(reshape_transform.forward(x))) + # Tensor(shape=[1, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[1., 1., 1.], + # [1., 1., 1.]]]) + print(reshape_transform.forward_log_det_jacobian(x)) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.]) + """ + _type = Type.BIJECTION + + def __init__(self, in_event_shape, out_event_shape): + if not isinstance(in_event_shape, typing.Sequence) or not isinstance( + out_event_shape, typing.Sequence + ): + raise TypeError( + f"Expected type of 'in_event_shape' and 'out_event_shape' is " + f"Squence[int], but got 'in_event_shape': {in_event_shape}, " + f"'out_event_shape': {out_event_shape}" + ) + if functools.reduce(operator.mul, in_event_shape) != functools.reduce( + operator.mul, out_event_shape + ): + raise ValueError( + f"The numel of 'in_event_shape' should be 'out_event_shape', " + f"but got {functools.reduce(operator.mul, in_event_shape)}!={functools.reduce(operator.mul, out_event_shape)}" + ) + + self._in_event_shape = tuple(in_event_shape) + self._out_event_shape = tuple(out_event_shape) + super(ReshapeTransform, self).__init__() + + @property + def in_event_shape(self): + return self._in_event_shape + + @property + def out_event_shape(self): + return self._out_event_shape + + @property + def _domain(self): + return variable.Independent(variable.real, len(self._in_event_shape)) + + @property + def _codomain(self): + return variable.Independent(variable.real, len(self._out_event_shape)) + + def _forward(self, x): + return x.reshape( + tuple(x.shape)[: x.dim() - len(self._in_event_shape)] + + self._out_event_shape + ) + + def _inverse(self, y): + return y.reshape( + tuple(y.shape)[: y.dim() - len(self._out_event_shape)] + + self._in_event_shape + ) + + def _forward_shape(self, shape): + if len(shape) < len(self._in_event_shape): + raise ValueError( + f"Expected length of 'shape' is not less than {len(self._in_event_shape)}, but got {len(shape)}" + ) + if shape[-len(self._in_event_shape) :] != self._in_event_shape: + raise ValueError( + f"Event shape mismatch, expected: {self._in_event_shape}, but got {shape[-len(self._in_event_shape):]}" + ) + return ( + tuple(shape[: -len(self._in_event_shape)]) + self._out_event_shape + ) + + def _inverse_shape(self, shape): + if len(shape) < len(self._out_event_shape): + raise ValueError( + f"Expected 'shape' length is not less than {len(self._out_event_shape)}, but got {len(shape)}" + ) + if shape[-len(self._out_event_shape) :] != self._out_event_shape: + raise ValueError( + f"Event shape mismatch, expected: {self._out_event_shape}, but got {shape[-len(self._out_event_shape):]}" + ) + return ( + tuple(shape[: -len(self._out_event_shape)]) + self._in_event_shape + ) + + def _forward_log_det_jacobian(self, x): + # paddle.zeros not support zero dimension Tensor. + shape = x.shape[: x.dim() - len(self._in_event_shape)] or [1] + return paddle.zeros(shape, dtype=x.dtype) + + +class SigmoidTransform(Transform): + r"""Sigmoid transformation with mapping :math:`y = \frac{1}{1 + \exp(-x)}` and :math:`x = \text{logit}(y)`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.ones((2,3)) + t = paddle.distribution.SigmoidTransform() + print(t.forward(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0.73105860, 0.73105860, 0.73105860], + # [0.73105860, 0.73105860, 0.73105860]]) + print(t.inverse(t.forward(x))) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1.00000012, 1.00000012, 1.00000012], + # [1.00000012, 1.00000012, 1.00000012]]) + print(t.forward_log_det_jacobian(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[-1.62652326, -1.62652326, -1.62652326], + # [-1.62652326, -1.62652326, -1.62652326]]) + """ + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.Variable(False, 0, constraint.Range(0.0, 1.0)) + + def _forward(self, x): + return F.sigmoid(x) + + def _inverse(self, y): + return y.log() - (-y).log1p() + + def _forward_log_det_jacobian(self, x): + return -F.softplus(-x) - F.softplus(x) + + +class SoftmaxTransform(Transform): + r"""Softmax transformation with mapping :math:`y=\exp(x)` then normalizing. + + It's generally used to convert unconstrained space to simplex. This mapping + is not injective, so ``forward_log_det_jacobian`` and + ``inverse_log_det_jacobian`` are not implemented. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.ones((2,3)) + t = paddle.distribution.SoftmaxTransform() + print(t.forward(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0.33333334, 0.33333334, 0.33333334], + # [0.33333334, 0.33333334, 0.33333334]]) + print(t.inverse(t.forward(x))) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[-1.09861231, -1.09861231, -1.09861231], + # [-1.09861231, -1.09861231, -1.09861231]]) + """ + _type = Type.OTHER + + @property + def _domain(self): + return variable.Independent(variable.real, 1) + + @property + def _codomain(self): + return variable.Variable(False, 1, constraint.simplex) + + def _forward(self, x): + x = (x - x.max(-1, keepdim=True)[0]).exp() + return x / x.sum(-1, keepdim=True) + + def _inverse(self, y): + return y.log() + + def _forward_shape(self, shape): + if len(shape) < 1: + raise ValueError( + f"Expected length of shape is grater than 1, but got {len(shape)}" + ) + return shape + + def _inverse_shape(self, shape): + if len(shape) < 1: + raise ValueError( + f"Expected length of shape is grater than 1, but got {len(shape)}" + ) + return shape + + +class StackTransform(Transform): + r"""``StackTransform`` applies a sequence of transformations along the + specific axis. + + Args: + transforms (Sequence[Transform]): The sequence of transformations. + axis (int, optional): The axis along which will be transformed. default + value is 0. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.stack( + (paddle.to_tensor([1., 2., 3.]), paddle.to_tensor([1, 2., 3.])), 1) + t = paddle.distribution.StackTransform( + (paddle.distribution.ExpTransform(), + paddle.distribution.PowerTransform(paddle.to_tensor(2.))), + 1 + ) + print(t.forward(x)) + # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[2.71828175 , 1. ], + # [7.38905621 , 4. ], + # [20.08553696, 9. ]]) + + print(t.inverse(t.forward(x))) + # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1., 1.], + # [2., 2.], + # [3., 3.]]) + + print(t.forward_log_det_jacobian(x)) + # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1. , 0.69314718], + # [2. , 1.38629436], + # [3. , 1.79175949]]) + """ + + def __init__(self, transforms, axis=0): + if not transforms or not isinstance(transforms, typing.Sequence): + raise TypeError( + f"Expected 'transforms' is Sequence[Transform], but got {type(transforms)}." + ) + if not all(isinstance(t, Transform) for t in transforms): + raise TypeError( + 'Expected all element in transforms is Transform Type.' + ) + if not isinstance(axis, int): + raise TypeError(f"Expected 'axis' is int, but got{type(axis)}.") + + self._transforms = transforms + self._axis = axis + + def _is_injective(self): + return all(t._is_injective() for t in self._transforms) + + @property + def transforms(self): + return self._transforms + + @property + def axis(self): + return self._axis + + def _forward(self, x): + self._check_size(x) + return paddle.stack( + [ + t.forward(v) + for v, t in zip(paddle.unstack(x, self._axis), self._transforms) + ], + self._axis, + ) + + def _inverse(self, y): + self._check_size(y) + return paddle.stack( + [ + t.inverse(v) + for v, t in zip(paddle.unstack(y, self._axis), self._transforms) + ], + self._axis, + ) + + def _forward_log_det_jacobian(self, x): + self._check_size(x) + return paddle.stack( + [ + t.forward_log_det_jacobian(v) + for v, t in zip(paddle.unstack(x, self._axis), self._transforms) + ], + self._axis, + ) + + def _check_size(self, v): + if not (-v.dim() <= self._axis < v.dim()): + raise ValueError( + f'Input dimensions {v.dim()} should be grater than stack ' + f'transform axis {self._axis}.' + ) + if v.shape[self._axis] != len(self._transforms): + raise ValueError( + f'Input size along {self._axis} should be equal to the ' + f'length of transforms.' + ) + + @property + def _domain(self): + return variable.Stack([t._domain for t in self._transforms], self._axis) + + @property + def _codomain(self): + return variable.Stack( + [t._codomain for t in self._transforms], self._axis + ) + + +class StickBreakingTransform(Transform): + r"""Convert an unconstrained vector to the simplex with one additional + dimension by the stick-breaking construction. + + Examples: + + .. code-block:: python + + import paddle + + + x = paddle.to_tensor([1.,2.,3.]) + t = paddle.distribution.StickBreakingTransform() + print(t.forward(x)) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.47536686, 0.41287899, 0.10645414, 0.00530004]) + print(t.inverse(t.forward(x))) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.99999988, 2. , 2.99999881]) + print(t.forward_log_det_jacobian(x)) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-9.10835075]) + """ + + _type = Type.BIJECTION + + def _forward(self, x): + offset = x.shape[-1] + 1 - paddle.ones([x.shape[-1]]).cumsum(-1) + z = F.sigmoid(x - offset.log()) + z_cumprod = (1 - z).cumprod(-1) + return F.pad(z, [0] * 2 * (len(x.shape) - 1) + [0, 1], value=1) * F.pad( + z_cumprod, [0] * 2 * (len(x.shape) - 1) + [1, 0], value=1 + ) + + def _inverse(self, y): + y_crop = y[..., :-1] + offset = y.shape[-1] - paddle.ones([y_crop.shape[-1]]).cumsum(-1) + sf = 1 - y_crop.cumsum(-1) + x = y_crop.log() - sf.log() + offset.log() + return x + + def _forward_log_det_jacobian(self, x): + y = self.forward(x) + offset = x.shape[-1] + 1 - paddle.ones([x.shape[-1]]).cumsum(-1) + x = x - offset.log() + return (-x + F.log_sigmoid(x) + y[..., :-1].log()).sum(-1) + + def _forward_shape(self, shape): + if not shape: + raise ValueError(f"Expected 'shape' is not empty, but got {shape}") + return shape[:-1] + (shape[-1] + 1,) + + def _inverse_shape(self, shape): + if not shape: + raise ValueError(f"Expected 'shape' is not empty, but got {shape}") + return shape[:-1] + (shape[-1] - 1,) + + @property + def _domain(self): + return variable.Independent(variable.real, 1) + + @property + def _codomain(self): + return variable.Variable(False, 1, constraint.simplex) + + +class TanhTransform(Transform): + r"""Tanh transformation with mapping :math:`y = \tanh(x)`. + + Examples: + + .. code-block:: python + + import paddle + + tanh = paddle.distribution.TanhTransform() + + x = paddle.to_tensor([[1., 2., 3.], [4., 5., 6.]]) + + print(tanh.forward(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0.76159418, 0.96402758, 0.99505478], + # [0.99932933, 0.99990922, 0.99998772]]) + print(tanh.inverse(tanh.forward(x))) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1.00000012, 2. , 3.00000286], + # [4.00002146, 5.00009823, 6.00039864]]) + print(tanh.forward_log_det_jacobian(x)) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[-0.86756170 , -2.65000558 , -4.61865711 ], + # [-6.61437654 , -8.61379623 , -10.61371803]]) + print(tanh.inverse_log_det_jacobian(tanh.forward(x))) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0.86756176 , 2.65000558 , 4.61866283 ], + # [6.61441946 , 8.61399269 , 10.61451530]]) + """ + _type = Type.BIJECTION + + @property + def _domain(self): + return variable.real + + @property + def _codomain(self): + return variable.Variable(False, 0, constraint.Range(-1.0, 1.0)) + + def _forward(self, x): + return x.tanh() + + def _inverse(self, y): + return y.atanh() + + def _forward_log_det_jacobian(self, x): + """We implicitly rely on _forward_log_det_jacobian rather than + explicitly implement ``_inverse_log_det_jacobian`` since directly using + ``-tf.math.log1p(-tf.square(y))`` has lower numerical precision. + + See details: https://github.com/tensorflow/probability/blob/master/tensorflow_probability/python/bijectors/tanh.py#L69-L80 + """ + return 2.0 * (math.log(2.0) - x - F.softplus(-2.0 * x)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transformed_distribution.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transformed_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..160af5e4870af48992afd0eeb785f5c8a69d93f3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/transformed_distribution.py @@ -0,0 +1,121 @@ +# Copyright (c) 2022 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. + +import typing + +from paddle.distribution import distribution +from paddle.distribution import transform +from paddle.distribution import independent + + +class TransformedDistribution(distribution.Distribution): + r""" + Applies a sequence of Transforms to a base distribution. + + Args: + base (Distribution): The base distribution. + transforms (Sequence[Transform]): A sequence of ``Transform`` . + + Examples: + + .. code-block:: python + + import paddle + from paddle.distribution import transformed_distribution + + d = transformed_distribution.TransformedDistribution( + paddle.distribution.Normal(0., 1.), + [paddle.distribution.AffineTransform(paddle.to_tensor(1.), paddle.to_tensor(2.))] + ) + + print(d.sample([10])) + # Tensor(shape=[10], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.10697651, 3.33609009, -0.86234951, 5.07457638, 0.75925219, + # -4.17087793, 2.22579336, -0.93845034, 0.66054249, 1.50957513]) + print(d.log_prob(paddle.to_tensor(0.5))) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-1.64333570]) + """ + + def __init__(self, base, transforms): + if not isinstance(base, distribution.Distribution): + raise TypeError( + f"Expected type of 'base' is Distribution, but got {type(base)}." + ) + if not isinstance(transforms, typing.Sequence): + raise TypeError( + f"Expected type of 'transforms' is Sequence[Transform] or Chain, but got {type(transforms)}." + ) + if not all(isinstance(t, transform.Transform) for t in transforms): + raise TypeError("All element of transforms must be Transform type.") + + chain = transform.ChainTransform(transforms) + if len(base.batch_shape + base.event_shape) < chain._domain.event_rank: + raise ValueError( + f"'base' needs to have shape with size at least {chain._domain.event_rank}, bug got {len(base_shape)}." + ) + if chain._domain.event_rank > len(base.event_shape): + base = independent.Independent( + (base, chain._domain.event_rank - len(base.event_shape))) + self._base = base + self._transforms = transforms + + transformed_shape = chain.forward_shape(base.batch_shape + + base.event_shape) + transformed_event_rank = chain._codomain.event_rank + \ + max(len(base.event_shape)-chain._domain.event_rank, 0) + super(TransformedDistribution, self).__init__( + transformed_shape[:len(transformed_shape) - transformed_event_rank], + transformed_shape[len(transformed_shape) - transformed_event_rank:]) + + def sample(self, shape=()): + """Sample from ``TransformedDistribution``. + + Args: + shape (tuple, optional): The sample shape. Defaults to (). + + Returns: + [Tensor]: The sample result. + """ + x = self._base.sample(shape) + for t in self._transforms: + x = t.forward(x) + return x + + def log_prob(self, value): + """The log probability evaluated at value. + + Args: + value (Tensor): The value to be evaluated. + + Returns: + Tensor: The log probability. + """ + log_prob = 0.0 + y = value + event_rank = len(self.event_shape) + for t in reversed(self._transforms): + x = t.inverse(y) + event_rank += t._domain.event_rank - t._codomain.event_rank + log_prob = log_prob - \ + _sum_rightmost(t.forward_log_det_jacobian( + x), event_rank-t._domain.event_rank) + y = x + log_prob += _sum_rightmost(self._base.log_prob(y), + event_rank - len(self._base.event_shape)) + return log_prob + + +def _sum_rightmost(value, n): + return value.sum(list(range(-n, 0))) if n > 0 else value diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/uniform.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/uniform.py new file mode 100644 index 0000000000000000000000000000000000000000..aca3608ba6283d8da1f7e70072fb13761eaa6fa2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/distribution/uniform.py @@ -0,0 +1,300 @@ +# Copyright (c) 2021 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. + +import math +import warnings + +import numpy as np +from paddle import _C_ops, _legacy_C_ops +from paddle.distribution import distribution +from paddle.fluid import core +from paddle.fluid.data_feeder import ( + check_dtype, + check_type, + check_variable_and_dtype, + convert_dtype, +) +from paddle.fluid.framework import ( + _non_static_mode, + in_dygraph_mode, + _in_legacy_dygraph, +) +from paddle.fluid.layers import ( + control_flow, + elementwise_add, + elementwise_div, + elementwise_mul, + elementwise_sub, + nn, + ops, + tensor, +) +from paddle.tensor import arange, concat, gather_nd, multinomial + + +class Uniform(distribution.Distribution): + r"""Uniform distribution with `low` and `high` parameters. + + Mathematical Details + + The probability density function (pdf) is + + .. math:: + + pdf(x; a, b) = \frac{1}{Z}, \ a <=x ndim: + raise ValueError( + "Length of FFT argument s should not be larger than the rank of input. " + "Received s: {}, rank of x: {}".format(s, ndim) + ) + for size in s: + if not isinstance(size, int) or size <= 0: + raise ValueError( + "FFT sizes {} contains invalid value ({})".format(s, size) + ) + + +def _check_fft_axis(x, axis): + ndim = x.ndim + if not isinstance(axis, int): + raise ValueError( + "Invalid FFT axis ({}), it shoule be an integer.".format(axis) + ) + if axis < -ndim or axis >= ndim: + raise ValueError( + "Invalid FFT axis ({}), it should be in range [-{}, {})".format( + axis, ndim, ndim + ) + ) + + +def _check_fft_axes(x, axes): + ndim = x.ndim + if not isinstance(axes, Sequence): + raise ValueError( + "Invalid FFT axes ({}), it should be a sequence of integers.".format( + axes + ) + ) + if len(axes) > ndim: + raise ValueError( + "Length of fft axes should not be larger than the rank of input. " + "Received, len of axes: {}, rank of x: {}".format(len(axes), ndim) + ) + for axis in axes: + if not isinstance(axis, int) or axis < -ndim or axis >= ndim: + raise ValueError( + "FFT axes {} contains invalid value ({}), it should be in range [-{}, {})".format( + axes, axis, ndim, ndim + ) + ) + + +def _resize_fft_input(x, s, axes): + if len(s) != len(axes): + raise ValueError("length of `s` should equals length of `axes`.") + shape = x.shape + ndim = x.ndim + + axes_to_pad = [] + paddings = [] + axes_to_slice = [] + slices = [] + for i, axis in enumerate(axes): + if shape[axis] < s[i]: + axes_to_pad.append(axis) + paddings.append(s[i] - shape[axis]) + elif shape[axis] > s[i]: + axes_to_slice.append(axis) + slices.append((0, s[i])) + + if axes_to_slice: + x = paddle.slice( + x, + axes_to_slice, + starts=[item[0] for item in slices], + ends=[item[1] for item in slices], + ) + if axes_to_pad: + padding_widths = [0] * (2 * ndim) + for axis, pad in zip(axes_to_pad, paddings): + padding_widths[2 * axis + 1] = pad + x = paddle.nn.functional.pad(x, padding_widths) + return x + + +def _normalize_axes(x, axes): + ndim = x.ndim + return [item if item >= 0 else (item + ndim) for item in axes] + + +def _check_at_least_ndim(x, rank): + if x.ndim < rank: + raise ValueError( + "The rank of the input ({}) should >= {}".format(x.ndim, rank) + ) + + +# public APIs 1d +def fft(x, n=None, axis=-1, norm="backward", name=None): + """ + Calculate one-dimensional discrete Fourier transform. + + This function uses the efficient fast Fourier transform (FFT) algorithm [1] to + calculate the 1-D * n * point discrete Fourier transform (DFT). + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + n (int, optional): The length of the output transform axis. If `n` is less than + the length input, the input will be cropped. If larger, the input is filled + with zeros. If `n` is not given, the input length along the axis specified + by `axis` is used. + axis (int, optional): Axis used to calculate FFT. If not specified, the last axis + is used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on + the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies + the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are + scaled by ``1/sqrt(n)``. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + complex tensor. The truncated or zero-padded input, transformed along the axis indicated + by `axis`, or the last one if `axis` is not specified. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.exp(3j * np.pi * np.arange(7) / 7) + xp = paddle.to_tensor(x) + fft_xp = paddle.fft.fft(xp).numpy() + print(fft_xp) + # [1.+1.25396034e+00j 1.+4.38128627e+00j 1.-4.38128627e+00j + # 1.-1.25396034e+00j 1.-4.81574619e-01j 1.+8.88178420e-16j + # 1.+4.81574619e-01j] + + + """ + if is_integer(x) or is_floating_point(x): + return fft_r2c( + x, n, axis, norm, forward=True, onesided=False, name=name + ) + else: + return fft_c2c(x, n, axis, norm, forward=True, name=name) + + +def ifft(x, n=None, axis=-1, norm="backward", name=None): + """ + Compute the 1-D inverse discrete Fourier Transform. + + This function computes the inverse of the 1-D *n*-point discrete Fourier transform + computed by `fft`. In other words, ``ifft(fft(x)) == x`` to within numerical accuracy. + + The input should be ordered in the same way as is returned by `fft`, + i.e., + + * ``x[0]`` should contain the zero frequency term, + * ``x[1:n//2]`` should contain the positive-frequency terms, + * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in + increasing order starting from the most negative frequency. + + For an even number of input points, ``x[n//2]`` represents the sum of + the values at the positive and negative Nyquist frequencies, as the two + are aliased together. + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + n (int, optional): The length of the output transform axis. If `n` is less than + the length input, the input will be cropped. If larger, the input is filled + with zeros. If `n` is not given, the input length along the axis specified + by `axis` is used. + axis (int, optional): Axis used to calculate FFT. If not specified, the last axis + is used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on + the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies + the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are + scaled by ``1/sqrt(n)``. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + complex tensor. The truncated or zero-padded input, transformed along the axis indicated + by `axis`, or the last one if `axis` is not specified. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.exp(3j * np.pi * np.arange(7) / 7) + xp = paddle.to_tensor(x) + ifft_xp = paddle.fft.ifft(xp).numpy() + print(ifft_xp) + # [0.14285714+1.79137191e-01j 0.14285714+6.87963741e-02j + # 0.14285714+1.26882631e-16j 0.14285714-6.87963741e-02j + # 0.14285714-1.79137191e-01j 0.14285714-6.25898038e-01j + # 0.14285714+6.25898038e-01j] + + """ + if is_integer(x) or is_floating_point(x): + return fft_r2c( + x, n, axis, norm, forward=False, onesided=False, name=name + ) + else: + return fft_c2c(x, n, axis, norm, forward=False, name=name) + + +def rfft(x, n=None, axis=-1, norm="backward", name=None): + """ + The one dimensional FFT for real input. + + This function computes the one dimensional *n*-point discrete Fourier + Transform (DFT) of a real-valued tensor by means of an efficient algorithm + called the Fast Fourier Transform (FFT). + + When the DFT is computed for purely real input, the output is + Hermitian-symmetric. This function does not compute the negative frequency + terms, and the length of the transformed axis of the output is therefore + ``n//2 + 1``. + + Args: + x(Tensor) : Real-valued input tensor + n(int, optional): Number of points along transformation axis in the + input to use. If `n` is smaller than the length of the input, the + input is cropped. If it is larger, the input is padded with zeros. + If `n` is not given, the length of the input along the axis + specified by `axis` is used. + axis(int, optional): Axis over which to compute the FFT. Default value + is last axis. + norm(str, optional) : Normalization mode, indicates which direction of + the forward/backward pair of transforms is scaled and with what + normalization factor. Include {"backward", "ortho", "forward"}, + default value is "backward". + + - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively; + - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively; + - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``. + + Where ``n`` is the multiplication of each element in ``s`` . + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor) : complex tensor + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.0, 1.0, 0.0, 0.0]) + print(paddle.fft.rfft(x)) + # Tensor(shape=[3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [ (1+0j), -1j , (-1+0j)]) + """ + return fft_r2c(x, n, axis, norm, forward=True, onesided=True, name=name) + + +def irfft(x, n=None, axis=-1, norm="backward", name=None): + """ + Computes the inverse of `rfft`. + + This function calculates the inverse of the one-dimensional *n* point discrete + Fourier transform of the actual input calculated by "rfft". In other words, + ``irfft(rfft(a),len(a)) == a`` is within the numerical accuracy range. + + The input shall be in the form of "rfft", i.e. the actual zero frequency term, + followed by the complex positive frequency term, in the order of increasing frequency. + Because the discrete Fourier transform of the actual input is Hermite symmetric, + the negative frequency term is regarded as the complex conjugate term of the corresponding + positive frequency term. + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + n (int, optional): The length of the output transform axis. For `n` output + points, ``n//2 + 1``input points are necessary. If the length of the input tensor is greater + than `n`, it will be cropped, if it is shorter than this, fill in zero. If `n` is not given, + it is considered to be ``2 * (k-1)``, where ``k`` is the length of the input axis specified + along the ` axis'. + axis (int, optional): Axis used to calculate FFT. If not specified, the last axis + is used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Real tensor. Truncated or zero fill input for the transformation along the axis indicated by + `axis`, or the last input if `axis` is not specified. The length of the conversion axis + is `n`, or ``2 * k-2``, if `k` is None, where `k` is the length of the input conversion axis. + If the output is an odd number, you need to specify the value of 'n', such as ``2 * k-1`` + in some cases. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, -1j, -1]) + irfft_x = paddle.fft.irfft(x) + print(irfft_x) + # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [0., 1., 0., 0.]) + """ + return fft_c2r(x, n, axis, norm, forward=False, name=name) + + +def hfft(x, n=None, axis=-1, norm="backward", name=None): + """ + Compute the FFT of a signal that has Hermitian symmetry, a real + spectrum. + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + n (int, optional): The length of the output transform axis. For `n` output + points, ``n//2 + 1`` input points are necessary. If the length of the input tensor is greater + than `n`, it will be cropped, if it is shorter than this, fill in zero. If `n` is not given, + it is considered to be ``2 * (k-1)``, where ``k`` is the length of the input axis specified + along the ` axis'. + axis (int,optional): Axis used to calculate FFT. If not specified, the last axis + is used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Real tensor. Truncated or zero fill input for the transformation along the axis indicated by + `axis`, or the last input if `axis` is not specified. The length of the conversion axis + is `n`, or ``2 * k-2``, if `k` is None, where `k` is the length of the input conversion axis. + If the output is an odd number, you need to specify the value of 'n', such as ``2 * k-1`` in + some cases. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, -1j, -1]) + hfft_x = paddle.fft.hfft(x) + print(hfft_x) + # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [0., 0., 0., 4.]) + """ + + return fft_c2r(x, n, axis, norm, forward=True, name=name) + + +def ihfft(x, n=None, axis=-1, norm="backward", name=None): + """ + The inverse FFT of a signal that has Hermitian symmetry. + + This function computes the one dimensional *n*-point inverse FFT of a signal + that has Hermitian symmetry by means of an efficient algorithm called + the Fast Fourier Transform (FFT). + + When the DFT is computed for purely real input, the output is + Hermitian-symmetric. This function does not compute the negative frequency + terms, and the length of the transformed axis of the output is therefore + ``n//2 + 1``. + + Args: + x(Tensor): Input tensor. + n(int, optional): The number of points along transformation axis in the + input to use. If `n` is smaller than the length of the input, the + input is cropped. If it is larger, the input is padded with zeros. + If `n` is not given, the length of the input along the axis + specified by `axis` is used. + axis(int, optional) : Axis over which to compute the inverse FFT. If not + given, the last axis is used. + norm(str, optional) : Normalization mode, indicates which direction of + the forward/backward pair of transforms is scaled and with what + normalization factor. Include {"backward", "ortho", "forward"}, + default value is "backward". + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor) : complex tensor. + + Examples: + + .. code-block:: python + + import paddle + + spectrum = paddle.to_tensor([10.0, -5.0, 0.0, -1.0, 0.0, -5.0]) + print(paddle.fft.ifft(spectrum)) + # Tensor(shape=[6], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [(-0.1666666716337204+0j), (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j), (3.5+0j), (2.3333334922790527+1.9868215517249155e-08j), (1+1.9868215517249155e-08j)]) + print(paddle.fft.ihfft(spectrum)) + # Tensor(shape = [4], dtype = complex64, place = CUDAPlace(0), stop_gradient = True, + # [(-0.1666666716337204+0j), (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j), (3.5+0j)]) + + """ + return fft_r2c(x, n, axis, norm, forward=False, onesided=True, name=name) + + +# public APIs nd +def fftn(x, s=None, axes=None, norm="backward", name=None): + """ + Compute the N-D discrete Fourier Transform. + + This function calculates the n-D discrete Fourier transform on any number of axes + in the M-D array by fast Fourier transform (FFT). + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + s (sequence of ints, optional): Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on + the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies + the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are + scaled by ``1/sqrt(n)``. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + complex tensor. The truncated or zero-padded input, transformed along the axes indicated by + `axes`, or by a combination of `s` and `x`, as explained in the parameters section above. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.mgrid[:4, :4, :4][1] + xp = paddle.to_tensor(x) + fftn_xp = paddle.fft.fftn(xp, axes=(1, 2)).numpy() + print(fftn_xp) + # [[[24.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+8.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]] + # [[24.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+8.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]] + # [[24.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+8.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]] + # [[24.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+8.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.+0.j 0.+0.j 0.+0.j 0.-0.j] + # [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]] + """ + if is_integer(x) or is_floating_point(x): + return fftn_r2c( + x, s, axes, norm, forward=True, onesided=False, name=name + ) + else: + return fftn_c2c(x, s, axes, norm, forward=True, name=name) + + +def ifftn(x, s=None, axes=None, norm="backward", name=None): + """ + Compute the N-D inverse discrete Fourier Transform. + + This function computes the inverse of the N-D discrete + Fourier Transform over any number of axes in an M-D array by + means of the Fast Fourier Transform (FFT). In other words, + ``ifftn(fftn(x)) == x`` to within numerical accuracy. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fftn`, i.e., it should have the term for zero frequency + in all axes in the low-order corner, the positive frequency terms in the + first half of all axes, the term for the Nyquist frequency in the middle + of all axes and the negative frequency terms in the second half of all + axes, in order of decreasingly negative frequency. + + Args: + x (Tensor): The input data. It's a Tensor type. It's a complex. + s (sequence of ints, optional): Shape (length of each transformed axis) of the output + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + This corresponds to ``n`` for ``fft(x, n)``. + Along any axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. + axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on + the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies + the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are + scaled by ``1/sqrt(n)``. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + complex tensor. The truncated or zero-padded input, transformed along the axes indicated by + `axes`, or by a combination of `s` and `x`, as explained in the parameters section above. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.eye(3) + ifftn_x = paddle.fft.ifftn(x, axes=(1,)) + print(ifftn_x) + # Tensor(shape=[3, 3], dtype=complex64, place=Place(cpu), stop_gradient=True, + # [[ (0.3333333432674408+0j) , + # (0.3333333432674408-0j) , + # (0.3333333432674408+0j) ], + # [ (0.3333333432674408+0j) , + # (-0.1666666716337204+0.28867512941360474j), + # (-0.1666666716337204-0.28867512941360474j)], + # [ (0.3333333432674408+0j) , + # (-0.1666666716337204-0.28867512941360474j), + # (-0.1666666716337204+0.28867512941360474j)]]) + """ + if is_integer(x) or is_floating_point(x): + return fftn_r2c( + x, s, axes, norm, forward=False, onesided=False, name=name + ) + else: + return fftn_c2c(x, s, axes, norm, forward=False, name=name) + + +def rfftn(x, s=None, axes=None, norm="backward", name=None): + """ + + The N dimensional FFT for real input. + + This function computes the N-dimensional discrete Fourier Transform over + any number of axes in an M-dimensional real array by means of the Fast + Fourier Transform (FFT). By default, all axes are transformed, with the + real transform performed over the last axis, while the remaining + transforms are complex. + + The transform for real input is performed over the last transformation + axis, as by `rfft`, then the transform over the remaining axes is + performed as by `fftn`. The order of the output is as for `rfft` for the + final transformation axis, and as for `fftn` for the remaining + transformation axes. + + Args: + x(Tensor) : Input tensor, taken to be real. + s(Sequence[int], optional) : Shape to use from the exec fft. The final element of + `s` corresponds to `n` for ``rfft(x, n)``, while for the remaining + axes, it corresponds to `n` for ``fft(x, n)``. Along any axis, if + the given shape is smaller than that of the input, the input is + cropped. If it is larger, the input is padded with zeros. if `s` is + not given, the shape of the input along the axes specified by `axes` + is used. + axes(Sequence[int], optional) : Axes over which to compute the FFT. If not given, + the last ``len(s)`` axes are used, or all axes if `s` is also not + specified. + norm(str, optional) : Normalization mode, indicates which direction of + the forward/backward pair of transforms is scaled and with what + normalization factor. Include {"backward", "ortho", "forward"}, + default value is "backward". The details of + three operations are shown below: + + - "backward": The factor of forward direction and backward direction are ``1`` + and ``1/n`` respectively; + - "forward": The factor of forward direction and backward direction are ``1/n`` + and ``1`` respectively; + - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``. + + Where ``n`` is the multiplication of each element in ``s`` . + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor), complex tensor + + Examples: + .. code-block:: python + + import paddle + + # default, all axis will be used to exec fft + x = paddle.ones((2, 3, 4)) + print(paddle.fft.rfftn(x)) + # Tensor(shape=[2, 3, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[[(24+0j), 0j , 0j ], + # [0j , 0j , 0j ], + # [0j , 0j , 0j ]], + # + # [[0j , 0j , 0j ], + # [0j , 0j , 0j ], + # [0j , 0j , 0j ]]]) + + # use axes(2, 0) + print(paddle.fft.rfftn(x, axes=(2, 0))) + # Tensor(shape=[2, 3, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[[(8+0j), 0j , 0j ], + # [(8+0j), 0j , 0j ], + # [(8+0j), 0j , 0j ]], + # + # [[0j , 0j , 0j ], + # [0j , 0j , 0j ], + # [0j , 0j , 0j ]]]) + + """ + return fftn_r2c(x, s, axes, norm, forward=True, onesided=True, name=name) + + +def irfftn(x, s=None, axes=None, norm="backward", name=None): + """ + Computes the inverse of `rfftn`. + + This function computes the inverse of the N-D discrete + Fourier Transform for real input over any number of axes in an + M-D array by means of the Fast Fourier Transform (FFT). In + other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical + accuracy. (The ``x.shape`` is necessary like ``len(x)`` is for `irfft`, + and for the same reason.) + + The input should be ordered in the same way as is returned by `rfftn`, + i.e., as for `irfft` for the final transformation axis, and as for `ifftn` + along all the other axes. + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): The length of the output transform axis. + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). + + - `s` is also the number of input points used along this axis, except for the last axis, where ``s[-1]//2+1`` points of the input are used. + - Along any axis, if the shape indicated by `s` is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. + - If `s` is not given, the shape of the input along the axes specified by axes is used. Except for the last axis which is taken to be ``2*(k-1)`` + + where ``k`` is the length of the input along that axis. + + axes (sequence of ints, optional): Axes over which to compute the inverse FFT. If not given, the last + `len(s)` axes are used, or all axes if `s` is also not specified. + norm (str): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". The details of + three operations are shown below: + + - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively; + - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively; + - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``. + + Where ``n`` is the multiplication of each element in ``s`` . + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Real tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`, + or by a combination of `s` or `x`, as explained in the parameters section above. The length of + each transformed axis is as given by the corresponding element of `s`, or the length of the input + in every axis except for the last one if `s` is not given. In the final transformed axis the length + of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the length of the final + transformed axis of the input. To get an odd number of output points in the final axis, + `s` must be specified. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2.+2.j, 2.+2.j, 3.+3.j]).astype(paddle.complex128) + print(x) + irfftn_x = paddle.fft.irfftn(x) + print(irfftn_x) + + # Tensor(shape=[3], dtype=complex128, place=Place(cpu), stop_gradient=True, + # [(2+2j), (2+2j), (3+3j)]) + # Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=True, + # [ 2.25000000, -1.25000000, 0.25000000, 0.75000000]) + + """ + return fftn_c2r(x, s, axes, norm, forward=False, name=name) + + +def hfftn(x, s=None, axes=None, norm="backward", name=None): + """ + Compute the N-D FFT of Hermitian symmetric complex input, i.e., a + signal with a real spectrum. + + This function calculates the n-D discrete Fourier transform of Hermite symmetric + complex input on any axis in M-D array by fast Fourier transform (FFT). + In other words, ``ihfftn(hfftn(x, s)) == x is within the numerical accuracy range. + (``s`` here are ``x.shape`` and ``s[-1] = x.shape[- 1] * 2 - 1``. This is necessary + for the same reason that ``irfft` requires ``x.shape``.) + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): The length of the output transform axis. + (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the + number of input points used along this axis, except for the last axis, + where ``s[-1]//2+1`` points of the input are used. Along any axis, if + the shape indicated by `s` is smaller than that of the input, the input + is cropped. If it is larger, the input is padded with zeros. + If `s` is not given, the shape of the input along the axes specified by axes + is used. Except for the last axis which is taken to be ``2*(k-1)`` where + ``k`` is the length of the input along that axis. + axes (sequence of ints, optional): Axes over which to compute the inverse FFT. If not given, the last + `len(s)` axes are used, or all axes if `s` is also not specified. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Real tensor. Truncate or zero fill input, transforming along the axis indicated by axis or + a combination of `s` or `X`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([(2+2j), (2+2j), (3+3j)]) + hfftn_x = paddle.fft.hfftn(x) + print(hfftn_x) + # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [ 9., 3., 1., -5.]) + """ + return fftn_c2r(x, s, axes, norm, forward=True, name=name) + + +def ihfftn(x, s=None, axes=None, norm="backward", name=None): + """ + The n dimensional inverse FFT of a signal that has Hermitian symmetry. + + This function computes the n dimensional inverse FFT over any number of axes + in an M-dimensional of a signal that has Hermitian symmetry by means of an + efficient algorithm called the Fast Fourier Transform (FFT). + + Args: + x(Tensor): Input tensor. + s(Sequence[int], optional) : Shape (length along each transformed axis) + to use from the input. (``s[0]`` refers to axis 0, ``s[1]`` to axis + 1, etc.). Along any axis, if the given shape is smaller than that + of the input, the input is cropped. If it is larger, the input is + padded with zeros. if `s` is not given, the shape of the input + along the axes specified by `axes` is used. + axes(Sequence[int], optional) : Axis over which to compute the inverse FFT. If not + given, the last axis is used. + norm(str, optional) : Normalization mode, indicates which direction of + the forward/backward pair of transforms is scaled and with what + normalization factor. Include {"backward", "ortho", "forward"}, + default value is "backward". + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor) : complex tensor. + + Examples: + + .. code-block:: python + + import paddle + + spectrum = paddle.to_tensor([10.0, -5.0, 0.0, -1.0, 0.0, -5.0]) + print(paddle.fft.ifft(spectrum)) + # Tensor(shape=[6], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [(-0.1666666716337204+0j), (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j), (3.5+0j), (2.3333334922790527+1.9868215517249155e-08j), (1+1.9868215517249155e-08j)]) + print(paddle.fft.ihfft(spectrum)) + # Tensor(shape = [4], dtype = complex64, place = CUDAPlace(0), stop_gradient = True, + # [(-0.1666666716337204+0j), (1-1.9868215517249155e-08j), (2.3333334922790527-1.9868215517249155e-08j), (3.5+0j)]) + """ + return fftn_r2c(x, s, axes, norm, forward=False, onesided=True, name=name) + + +# public APIs 2d +def fft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + Compute the 2-D discrete Fourier Transform + + This function computes the N-D discrete Fourier Transform + over any axes in an M-D array by means of the + Fast Fourier Transform (FFT). By default, the transform is computed over + the last two axes of the input array, i.e., a 2-dimensional FFT. + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): Shape (length of each transformed axis) of the output. + It should be a sequence of 2 integers. This corresponds to ``n`` for ``fft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. Default is None. + axes (sequence of ints, optional): Axes over which to compute the FFT. It should be a + sequence of 2 integers. If not specified, the last two axes are used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Complex tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`, + or the last two axes if `axes` is not given. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.mgrid[:2, :2][1] + xp = paddle.to_tensor(x) + fft2_xp = paddle.fft.fft2(xp).numpy() + print(fft2_xp) + # [[ 2.+0.j -2.+0.j] + # [ 0.+0.j 0.+0.j]] + + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return fftn(x, s, axes, norm, name) + + +def ifft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + Compute the 2-D inverse discrete Fourier Transform. + + This function computes the inverse of the 2-D discrete Fourier + Transform over any number of axes in an M-D array by means of + the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x`` + to within numerical accuracy. By default, the inverse transform is + computed over the last two axes of the input array. + + The input, analogously to `ifft`, should be ordered in the same way as is + returned by `fft2`, i.e., it should have the term for zero frequency + in the low-order corner of the two axes, the positive frequency terms in + the first half of these axes, the term for the Nyquist frequency in the + middle of the axes and the negative frequency terms in the second half of + both axes, in order of decreasingly negative frequency. + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): Shape (length of each transformed axis) of the output. + It should be a sequence of 2 integers. This corresponds to ``n`` for ``fft(x, n)``. + Along each axis, if the given shape is smaller than that of the input, + the input is cropped. If it is larger, the input is padded with zeros. + if `s` is not given, the shape of the input along the axes specified + by `axes` is used. Default is None. + axes (sequence of ints, optional): Axes over which to compute the FFT. It should be a + sequence of 2 integers. If not specified, the last two axes are used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Complex tensor. The truncated or zero-padded input, transformed along the axes indicated by `axes`, + or the last two axes if `axes` is not given. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.mgrid[:2, :2][1] + xp = paddle.to_tensor(x) + ifft2_xp = paddle.fft.ifft2(xp).numpy() + print(ifft2_xp) + # [[ 0.5+0.j -0.5+0.j] + # [ 0. +0.j 0. +0.j]] + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return ifftn(x, s, axes, norm, name) + + +def rfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + The two dimensional FFT with real tensor input. + + This is really just `rfftn` with different default behavior. + For more details see `rfftn`. + + Args: + x(Tensor): Input tensor, taken to be real. + s(Sequence[int], optional) : Shape of the FFT. + axes(Sequence[int], optional): Axes over which to compute the FFT. + norm(str, optional) : {"backward", "ortho", "forward"}, + default is "backward". Indicates which direction of the + forward/backward pair of transforms is scaled and with what + normalization factor. The details of + three operations are shown below: + + - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively; + - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively; + - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``. + + Where ``n`` is the multiplication of each element in ``s`` . + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor): The result of the real 2-D FFT. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + x = paddle.to_tensor(np.mgrid[:5, :5][0].astype(np.float32)) + print(paddle.fft.rfft2(x)) + # Tensor(shape=[5, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[ (50+0j) , (1.1920928955078125e-07+0j) , 0j ], + # [(-12.5+17.204774856567383j) , (-9.644234211236835e-08+7.006946134424652e-08j) , 0j ], + # [(-12.500000953674316+4.061495304107666j) , (3.6837697336977726e-08-1.1337477445749755e-07j), 0j ], + # [(-12.500000953674316-4.061495304107666j) , (3.6837697336977726e-08+1.1337477445749755e-07j), 0j ], + # [(-12.5-17.204774856567383j) , (-9.644234211236835e-08-7.006946134424652e-08j) , 0j ]]) + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return rfftn(x, s, axes, norm, name) + + +def irfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + Computes the inverse of `rfft2`. + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): Shape of the real output to the inverse FFT. Default is None. + axes (sequence of ints, optional): The axes over which to compute the inverse FFT. Axes + must be two-dimensional. If not specified, the last two axes are used by default. + norm (str, optional): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". The details of + three operations are shown below: + + - "backward": The factor of forward direction and backward direction are ``1`` and ``1/n`` respectively; + - "forward": The factor of forward direction and backward direction are ``1/n`` and ``1`` respectively; + - "ortho": The factor of forward direction and backword direction are both ``1/sqrt(n)``. + + Where ``n`` is the multiplication of each element in ``s`` . + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Real tensor. The result of the inverse real 2-D FFT. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[3.+3.j, 2.+2.j, 3.+3.j], [2.+2.j, 2.+2.j, 3.+3.j]]) + irfft2_x = paddle.fft.irfft2(x) + print(irfft2_x) + # Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[ 2.37500000, -1.12500000, 0.37500000, 0.87500000], + # [ 0.12500000, 0.12500000, 0.12500000, 0.12500000]]) + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return irfftn(x, s, axes, norm, name) + + +def hfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + Compute the 2-D FFT of a Hermitian complex array. + + Args: + x (Tensor): The input data. It's a Tensor type. + s (sequence of ints, optional): Shape of the real output. Default is None. + axes (sequence of ints, optional): Axes over which to compute the FFT. Axes must be + two-dimensional. If not specified, the last two axes are used by default. + norm (str): Indicates which direction to scale the `forward` or `backward` transform + pair and what normalization factor to use. The parameter value must be one + of "forward" or "backward" or "ortho". Default is "backward". + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Real tensor. The real result of the 2-D Hermitian complex real FFT. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[3.+3.j, 2.+2.j, 3.+3.j], [2.+2.j, 2.+2.j, 3.+3.j]]) + hfft2_x = paddle.fft.hfft2(x) + print(hfft2_x) + # Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[19., 7., 3., -9.], + # [ 1., 1., 1., 1.]]) + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return hfftn(x, s, axes, norm, name) + + +def ihfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): + """ + Compute the two dimensional inverse FFT of a real spectrum. + + This is really `ihfftn` with different defaults. + For more details see `ihfftn`. + + Args: + x(Tensor): Input tensor. + s(Sequence[int], optional): Shape of the real input to the inverse FFT. + axes(Sequance[int], optional): The axes over which to compute the + inverse fft. Default is the last two axes. + norm(str, optional): {"backward", "ortho", "forward"}. Default is + "backward". + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + out(Tensor) : The result of the inverse hermitian 2-D FFT. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.mgrid[:5, :5][0].astype(np.float64) + xp = paddle.to_tensor(x) + ihfft2_xp = paddle.fft.ihfft2(xp).numpy() + print(ihfft2_xp) + # [[ 2. +0.j 0. +0.j 0. +0.j ] + # [-0.5-0.68819096j 0. +0.j 0. +0.j ] + # [-0.5-0.16245985j 0. +0.j 0. +0.j ] + # [-0.5+0.16245985j 0. +0.j 0. +0.j ] + # [-0.5+0.68819096j 0. +0.j 0. +0.j ]] + """ + _check_at_least_ndim(x, 2) + if s is not None: + if not isinstance(s, Sequence) or len(s) != 2: + raise ValueError( + "Invalid FFT argument s ({}), it should be a sequence of 2 integers.".format( + s + ) + ) + if axes is not None: + if not isinstance(axes, Sequence) or len(axes) != 2: + raise ValueError( + "Invalid FFT argument axes ({}), it should be a sequence of 2 integers.".format( + axes + ) + ) + return ihfftn(x, s, axes, norm, name) + + +# public APIs utilities +def fftfreq(n, d=1.0, dtype=None, name=None): + """ + Return the Discrete Fourier Transform sample frequencies. + + The returned float array `f` contains the frequency bin centers in cycles + per unit of the sample spacing (with zero at the start). For instance, if + the sample spacing is in seconds, then the frequency unit is cycles/second. + + Given input length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd + + Args: + n (int): Dimension inputed. + d (scalar, optional): Sample spacing (inverse of the sampling rate). Defaults is 1. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. A tensor of length 'n' containing the sampling frequency. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([3, 1, 2, 2, 3], dtype=float) + scalar_temp = 0.5 + n = x.size + fftfreq_xp = paddle.fft.fftfreq(n, d=scalar_temp) + print(fftfreq_xp) + + # Tensor(shape=[5], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [ 0. , 0.40000001, 0.80000001, -0.80000001, -0.40000001]) + """ + + dtype = paddle.framework.get_default_dtype() + val = 1.0 / (n * d) + pos_max = (n + 1) // 2 + neg_max = n // 2 + indices = paddle.arange(-neg_max, pos_max, dtype=dtype, name=name) + indices = paddle.roll(indices, -neg_max, name=name) + return indices * val + + +def rfftfreq(n, d=1.0, dtype=None, name=None): + """ + Return the Discrete Fourier Transform sample frequencies. + + The returned floating-point array "F" contains the center of the frequency unit, + and the unit is the number of cycles of the sampling interval (the starting point is zero). + + Given input length `n` and a sample spacing `d`:: + + f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd + + the Nyquist frequency component is considered to be positive. + + Args: + n (int): Dimension inputed. + d (scalar, optional): Sample spacing (inverse of the sampling rate). Defaults is 1. + dtype (str, optional): The data type of returns. Defaults is the data type of returns + of ``paddle.get_default_dtype()``. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. A tensor of length ``n//2 + 1`` containing the sample frequencies. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([3, 1, 2, 2, 3], dtype=float) + scalar_temp = 0.3 + n = x.size + rfftfreq_xp = paddle.fft.rfftfreq(n, d=scalar_temp) + print(rfftfreq_xp) + + # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [0. , 0.66666669, 1.33333337]) + + """ + + dtype = paddle.framework.get_default_dtype() + val = 1.0 / (n * d) + pos_max = 1 + n // 2 + indices = paddle.arange(0, pos_max, dtype=dtype, name=name) + return indices * val + + +def fftshift(x, axes=None, name=None): + """ + Shift the zero-frequency component to the center of the spectrum. + + This function swaps half spaces for all the axes listed (all by default). + Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. + + Args: + n (int): Dimension inputed. + axes (int|tuple, optional): The axis on which to move. The default is none, which moves all axes. + Default is None. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. The shifted tensor. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([3, 1, 2, 2, 3], dtype=float) + n = x.size + fftfreq_xp = paddle.fft.fftfreq(n, d=0.3) + res = paddle.fft.fftshift(fftfreq_xp).numpy() + print(res) + # [-1.3333334 -0.6666667 0. 0.6666667 1.3333334] + + """ + shape = paddle.shape(x) + if axes is None: + # shift all axes + rank = len(x.shape) + axes = list(range(0, rank)) + shifts = shape // 2 + elif isinstance(axes, int): + shifts = shape[axes] // 2 + else: + shifts = paddle.concat([shape[ax] // 2 for ax in axes]) + return paddle.roll(x, shifts, axes, name=name) + + +def ifftshift(x, axes=None, name=None): + """ + The inverse of `fftshift`. Although the even length 'x' is the same, the function of the + odd length 'x' is different. An example. + + Args: + n (int): Dimension inputed. + axes (int|tuple, optional): The axis on which to move. The default is none, which moves all axes. + Default is None. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. The shifted tensor. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([3, 1, 2, 2, 3], dtype=float) + n = x.size + fftfreq_xp = paddle.fft.fftfreq(n, d=0.3) + res = paddle.fft.ifftshift(fftfreq_xp).numpy() + print(res) + # [ 1.3333334 -1.3333334 -0.6666667 0. 0.6666667] + + """ + shape = paddle.shape(x) + if axes is None: + # shift all axes + rank = len(x.shape) + axes = list(range(0, rank)) + shifts = -shape // 2 + elif isinstance(axes, int): + shifts = -shape[axes] // 2 + else: + shifts = paddle.concat([-shape[ax] // 2 for ax in axes]) + return paddle.roll(x, shifts, axes, name=name) + + +# internal functions +def fft_c2c(x, n, axis, norm, forward, name): + if is_integer(x): + x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype())) + elif is_floating_point(x): + x = paddle.cast(x, _real_to_complex_dtype(x.dtype)) + _check_normalization(norm) + + axis = axis if axis is not None else -1 + _check_fft_axis(x, axis) + axes = [axis] + axes = _normalize_axes(x, axes) + if n is not None: + _check_fft_n(n) + s = [n] + x = _resize_fft_input(x, s, axes) + op_type = 'fft_c2c' + + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type) + if in_dygraph_mode(): + out = _C_ops.fft_c2c(x, axes, norm, forward) + elif _in_legacy_dygraph(): + attrs = ('axes', axes, 'normalization', norm, 'forward', forward) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = {'axes': axes, 'normalization': norm, 'forward': forward} + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +def fft_r2c(x, n, axis, norm, forward, onesided, name): + if is_integer(x): + x = paddle.cast(x, paddle.get_default_dtype()) + _check_normalization(norm) + axis = axis if axis is not None else -1 + _check_fft_axis(x, axis) + axes = [axis] + axes = _normalize_axes(x, axes) + if n is not None: + _check_fft_n(n) + s = [n] + x = _resize_fft_input(x, s, axes) + op_type = 'fft_r2c' + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], op_type) + + if in_dygraph_mode(): + out = _C_ops.fft_r2c(x, axes, norm, forward, onesided) + elif _in_legacy_dygraph(): + attrs = ( + 'axes', + axes, + 'normalization', + norm, + 'forward', + forward, + 'onesided', + onesided, + ) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = { + 'axes': axes, + 'normalization': norm, + 'forward': forward, + 'onesided': onesided, + } + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference( + _real_to_complex_dtype(dtype) + ) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +def fft_c2r(x, n, axis, norm, forward, name): + if is_integer(x): + x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype())) + elif is_floating_point(x): + x = paddle.cast(x, _real_to_complex_dtype(x.dtype)) + _check_normalization(norm) + axis = axis if axis is not None else -1 + _check_fft_axis(x, axis) + axes = [axis] + axes = _normalize_axes(x, axes) + if n is not None: + _check_fft_n(n) + s = [n // 2 + 1] + x = _resize_fft_input(x, s, axes) + op_type = 'fft_c2r' + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type) + + if in_dygraph_mode(): + if n is not None: + out = _C_ops.fft_c2r(x, axes, norm, forward, n) + else: + out = _C_ops.fft_c2r(x, axes, norm, forward, 0) + elif _in_legacy_dygraph(): + if n is not None: + attrs = ( + 'axes', + axes, + 'normalization', + norm, + 'forward', + forward, + 'last_dim_size', + n, + ) + else: + attrs = ('axes', axes, 'normalization', norm, 'forward', forward) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = {'axes': axes, 'normalization': norm, 'forward': forward} + if n is not None: + attrs['last_dim_size'] = n + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference( + _complex_to_real_dtype(dtype) + ) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +def fftn_c2c(x, s, axes, norm, forward, name): + if is_integer(x): + x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype())) + elif is_floating_point(x): + x = paddle.cast(x, _real_to_complex_dtype(x.dtype)) + _check_normalization(norm) + if s is not None: + _check_fft_shape(x, s) + + rank = x.ndim + if axes is None: + if s is None: + axes = list(range(rank)) + else: + fft_ndims = len(s) + axes = list(range(rank - fft_ndims, rank)) + else: + _check_fft_axes(x, axes) + axes = _normalize_axes(x, axes) + axes_argsoft = np.argsort(axes).tolist() + axes = [axes[i] for i in axes_argsoft] + if s is not None: + if len(s) != len(axes): + raise ValueError( + "Length of s ({}) and length of axes ({}) does not match.".format( + len(s), len(axes) + ) + ) + s = [s[i] for i in axes_argsoft] + + if s is not None: + x = _resize_fft_input(x, s, axes) + op_type = 'fft_c2c' + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type) + + if in_dygraph_mode(): + out = _C_ops.fft_c2c(x, axes, norm, forward) + elif _in_legacy_dygraph(): + attrs = ('axes', axes, 'normalization', norm, 'forward', forward) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = {'axes': axes, 'normalization': norm, 'forward': forward} + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +def fftn_r2c(x, s, axes, norm, forward, onesided, name): + if is_integer(x): + x = paddle.cast(x, paddle.get_default_dtype()) + _check_normalization(norm) + if s is not None: + _check_fft_shape(x, s) + + rank = x.ndim + if axes is None: + if s is None: + axes = list(range(rank)) + else: + fft_ndims = len(s) + axes = list(range(rank - fft_ndims, rank)) + else: + _check_fft_axes(x, axes) + axes = _normalize_axes(x, axes) + axes_argsoft = np.argsort(axes[:-1]).tolist() + axes = [axes[i] for i in axes_argsoft] + [axes[-1]] + if s is not None: + if len(s) != len(axes): + raise ValueError( + "Length of s ({}) and length of axes ({}) does not match.".format( + len(s), len(axes) + ) + ) + s = [s[i] for i in axes_argsoft] + [s[-1]] + + if s is not None: + x = _resize_fft_input(x, s, axes) + + op_type = 'fft_r2c' + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], op_type) + + if in_dygraph_mode(): + out = _C_ops.fft_r2c(x, axes, norm, forward, onesided) + elif _in_legacy_dygraph(): + attrs = ( + 'axes', + axes, + 'normalization', + norm, + 'forward', + forward, + 'onesided', + onesided, + ) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = { + 'axes': axes, + 'normalization': norm, + 'forward': forward, + 'onesided': onesided, + } + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference( + _real_to_complex_dtype(dtype) + ) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + + return out + + +def fftn_c2r(x, s, axes, norm, forward, name): + if is_integer(x): + x = paddle.cast(x, _real_to_complex_dtype(paddle.get_default_dtype())) + elif is_floating_point(x): + x = paddle.cast(x, _real_to_complex_dtype(x.dtype)) + _check_normalization(norm) + if s is not None: + _check_fft_shape(x, s) + + rank = x.ndim + if axes is None: + if s is None: + axes = list(range(rank)) + else: + fft_ndims = len(s) + axes = list(range(rank - fft_ndims, rank)) + else: + _check_fft_axes(x, axes) + axes = _normalize_axes(x, axes) + axes_argsoft = np.argsort(axes[:-1]).tolist() + axes = [axes[i] for i in axes_argsoft] + [axes[-1]] + if s is not None: + if len(s) != len(axes): + raise ValueError( + "Length of s ({}) and length of axes ({}) does not match.".format( + len(s), len(axes) + ) + ) + s = [s[i] for i in axes_argsoft] + [s[-1]] + + if s is not None: + fft_input_shape = list(s) + fft_input_shape[-1] = fft_input_shape[-1] // 2 + 1 + x = _resize_fft_input(x, fft_input_shape, axes) + + op_type = 'fft_c2r' + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], op_type) + + if in_dygraph_mode(): + if s is not None: + out = _C_ops.fft_c2r(x, axes, norm, forward, s[-1]) + else: + out = _C_ops.fft_c2r(x, axes, norm, forward, 0) + elif _in_legacy_dygraph(): + if s: + attrs = ( + 'axes', + axes, + 'normalization', + norm, + 'forward', + forward, + 'last_dim_size', + s[-1], + ) + else: + attrs = ('axes', axes, 'normalization', norm, 'forward', forward) + out = getattr(_legacy_C_ops, op_type)(x, *attrs) + else: + inputs = { + 'X': [x], + } + attrs = {'axes': axes, 'normalization': norm, 'forward': forward} + if s: + attrs["last_dim_size"] = s[-1] + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference( + _complex_to_real_dtype(dtype) + ) + outputs = {"Out": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa07124ad49813256d4b8da7730bac5fac67c2d1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/__init__.py @@ -0,0 +1,234 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import os +import sys +import atexit + +# The legacy core need to be removed before "import core", +# in case of users installing paddlepadde without -U option +core_suffix = 'so' +if os.name == 'nt': + core_suffix = 'pyd' + +legacy_core = os.path.abspath( + os.path.dirname(__file__)) + os.sep + 'core.' + core_suffix +if os.path.exists(legacy_core): + sys.stderr.write('Deleting legacy file ' + legacy_core + '\n') + try: + os.remove(legacy_core) + except Exception as e: + raise e + +# import all class inside framework into fluid module +from . import framework +from .framework import * +# import all class inside executor into fluid module +from . import executor +from .executor import * + +from . import data_feed_desc +from .data_feed_desc import * + +from . import dataset +from .dataset import * + +from .data import * + +from . import trainer_desc + +from . import io +from . import evaluator +from . import initializer +from .initializer import set_global_initializer +from . import layers +from . import dygraph +from . import contrib +from . import nets +from . import optimizer +from . import backward +from .backward import gradients +from . import regularizer +from . import average +from . import metrics +from . import transpiler +from . import incubate +from .input import embedding, one_hot +from . import distribute_lookup_table +from .param_attr import ParamAttr, WeightNormParamAttr +from .data_feeder import DataFeeder + +from .core import LoDTensor, LoDTensorArray, Scope, _Scope +from .core import CPUPlace, XPUPlace, CUDAPlace, CUDAPinnedPlace, NPUPlace, IPUPlace, MLUPlace, CustomPlace +from .incubate import fleet +from .transpiler import DistributeTranspiler, \ + memory_optimize, release_memory, DistributeTranspilerConfig +from .lod_tensor import create_lod_tensor, create_random_int_lodtensor +from . import clip +from . import profiler +from . import unique_name +from . import parallel_executor +from .parallel_executor import * +from . import compiler +from .compiler import * +from paddle.fluid.layers.math_op_patch import monkey_patch_variable +from . import install_check +from .dygraph.nn import * +from .dygraph.layers import * +from .dygraph.base import enable_dygraph, disable_dygraph +from .io import save, load, load_program_state, set_program_state +from .dygraph.checkpoint import save_dygraph, load_dygraph +from .dygraph.varbase_patch_methods import monkey_patch_varbase +from . import generator +from .core import _cuda_synchronize +from .generator import Generator +from .trainer_desc import TrainerDesc, DistMultiTrainer, PipelineTrainer, HeterPipelineTrainer, MultiTrainer, HeterXpuTrainer +from .transpiler import HashName, RoundRobin +from .backward import append_backward + +Tensor = LoDTensor +enable_imperative = enable_dygraph +disable_imperative = disable_dygraph + +__all__ = framework.__all__ + executor.__all__ + \ + trainer_desc.__all__ + transpiler.__all__ + \ + parallel_executor.__all__ + lod_tensor.__all__ + \ + data_feed_desc.__all__ + compiler.__all__ + backward.__all__ + generator.__all__ + [ + 'io', + 'initializer', + 'embedding', + 'one_hot', + 'layers', + 'contrib', + 'data', + 'dygraph', + 'enable_dygraph', + 'disable_dygraph', + 'enable_imperative', + 'disable_imperative', + 'transpiler', + 'nets', + 'optimizer', + 'backward', + 'regularizer', + 'LoDTensor', + 'LoDTensorArray', + 'CPUPlace', + 'XPUPlace', + 'CUDAPlace', + 'CUDAPinnedPlace', + 'NPUPlace', + 'IPUPlace', + 'MLUPlace', + 'Tensor', + 'ParamAttr', + 'WeightNormParamAttr', + 'DataFeeder', + 'clip', + 'profiler', + 'unique_name', + 'Scope', + 'install_check', + 'save', + 'load', + '_cuda_synchronize' + ] + + +def __bootstrap__(): + """ + Enable reading gflags from environment variables. + + Returns: + None + """ + import sys + import os + import platform + from . import core + + # NOTE(zhiqiu): When (1)numpy < 1.19; (2) python < 3.7, + # unittest is always imported in numpy (maybe some versions not). + # so is_test is True and p2p is not inited. + in_test = 'unittest' in sys.modules + + try: + num_threads = int(os.getenv('OMP_NUM_THREADS', '1')) + except ValueError: + num_threads = 1 + + if num_threads > 1: + print('WARNING: OMP_NUM_THREADS set to {0}, not 1. The computation ' + 'speed will not be optimized if you use data parallel. It will ' + 'fail if this PaddlePaddle binary is compiled with OpenBlas since' + ' OpenBlas does not support multi-threads.'.format(num_threads), + file=sys.stderr) + print('PLEASE USE OMP_NUM_THREADS WISELY.', file=sys.stderr) + + os.environ['OMP_NUM_THREADS'] = str(num_threads) + + flag_prefix = "FLAGS_" + read_env_flags = [ + key[len(flag_prefix):] for key in core.globals().keys() + if key.startswith(flag_prefix) + ] + + def remove_flag_if_exists(name): + if name in read_env_flags: + read_env_flags.remove(name) + + sysstr = platform.system() + if 'Darwin' in sysstr: + remove_flag_if_exists('use_pinned_memory') + + if os.name == 'nt': + remove_flag_if_exists('cpu_deterministic') + + if core.is_compiled_with_ipu(): + # Currently we request all ipu available for training and testing + # finer control of pod of IPUs will be added later + read_env_flags += [] + + core.init_gflags(["--tryfromenv=" + ",".join(read_env_flags)]) + # Note(zhouwei25): sys may not have argv in some cases, + # Such as: use Python/C API to call Python from C++ + try: + core.init_glog(sys.argv[0]) + except Exception: + sys.argv = [""] + core.init_glog(sys.argv[0]) + # don't init_p2p when in unittest to save time. + core.init_devices() + core.init_default_kernel_signatures() + + +# TODO(panyx0718): Avoid doing complex initialization logic in __init__.py. +# Consider paddle.init(args) or paddle.main(args) +monkey_patch_variable() +__bootstrap__() +monkey_patch_varbase() + +# NOTE(zhiqiu): register npu_finalize on the exit of Python, +# do some clean up manually. +if core.is_compiled_with_npu(): + atexit.register(core.npu_finalize) +# NOTE(Aurelius84): clean up ExecutorCacheInfo in advance manually. +atexit.register(core.clear_executor_cache) + +# NOTE(Aganlengzi): clean up KernelFactory in advance manually. +# NOTE(wangran16): clean up DeviceManger in advance manually. +# Keep clear_kernel_factory running before clear_device_manager +atexit.register(core.clear_device_manager) +atexit.register(core.clear_kernel_factory) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/average.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/average.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5f4cb84f665cdaa0a9cf204988fc49b4832052 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/average.py @@ -0,0 +1,90 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import numpy as np +import warnings +""" + Class of all kinds of Average. + + All Averages are accomplished via Python totally. + They do not change Paddle's Program, nor do anything to + modify NN model's configuration. They are completely + wrappers of Python functions. +""" + +__all__ = ["WeightedAverage"] + + +def _is_number_(var): + return isinstance(var, int) or isinstance( + var, float) or (isinstance(var, np.ndarray) and var.shape == (1, )) + + +def _is_number_or_matrix_(var): + return _is_number_(var) or isinstance(var, np.ndarray) + + +class WeightedAverage(object): + """ + Calculate weighted average. + + The average calculating is accomplished via Python totally. + They do not change Paddle's Program, nor do anything to + modify NN model's configuration. They are completely + wrappers of Python functions. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + avg = fluid.average.WeightedAverage() + avg.add(value=2.0, weight=1) + avg.add(value=4.0, weight=2) + avg.eval() + + # The result is 3.333333333. + # For (2.0 * 1 + 4.0 * 2) / (1 + 2) = 3.333333333 + """ + + def __init__(self): + warnings.warn( + "The %s is deprecated, please use fluid.metrics.Accuracy instead." % + (self.__class__.__name__), Warning) + self.reset() + + def reset(self): + self.numerator = None + self.denominator = None + + def add(self, value, weight): + if not _is_number_or_matrix_(value): + raise ValueError( + "The 'value' must be a number(int, float) or a numpy ndarray.") + if not _is_number_(weight): + raise ValueError("The 'weight' must be a number(int, float).") + + if self.numerator is None or self.denominator is None: + self.numerator = value * weight + self.denominator = weight + else: + self.numerator += value * weight + self.denominator += weight + + def eval(self): + if self.numerator is None or self.denominator is None: + raise ValueError( + "There is no data to be averaged in WeightedAverage.") + return self.numerator / self.denominator diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/backward.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/backward.py new file mode 100644 index 0000000000000000000000000000000000000000..93d6d798dc4ebd794b469cea567b5aecd79f11ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/backward.py @@ -0,0 +1,2301 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +from .proto import framework_pb2 + +from paddle.fluid import framework as framework +from paddle.fluid import program_guard +from . import core +import collections +import copy +import six +import logging +from .. import compat as cpt +from . import unique_name +from . import log_helper +import paddle.fluid +from .data_feeder import check_type +import warnings +try: + from collections.abc import Sequence +except: + from collections import Sequence + +__all__ = [ + 'append_backward', + 'gradients', +] + +_logger = log_helper.get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +class ProgramStats(object): + + def __init__(self, block, ops): + self.block = block + self.ops = ops + self.op_deps = {} # op-> in_ops, out_ops + self.var_op_deps = {} # var as input op, var as output op + + def get_input_nodes(self): + input_names = [] + for name in self.var_op_deps: + if len(self.var_op_deps[name]["var_as_output_ops"]) == 0 and \ + len(self.var_op_deps[name]["var_as_input_ops"]) > 0: + if self.block.var(name).persistable: + continue + input_names.append(name) + for op in self.ops: + if op.desc.type() == "read": + input_names.extend(op.desc.output_arg_names()) + return input_names + + def get_reserved_vars(self): + var_name = [] + for op in self.ops: + if op.desc.type() == "seed": + var_name.extend(op.desc.output_arg_names()) + return var_name + + def get_out_of_subgraph_vars(self, begin_op_idx, end_op_idx): + var_name = [] + for i in range(begin_op_idx, end_op_idx, 1): + for name in self.ops[i].desc.output_arg_names(): + if name in self.var_op_deps: + for idx in self.var_op_deps[name]["var_as_input_ops"]: + if idx >= end_op_idx: + var_name.append(name) + for name in self.ops[i].desc.input_arg_names(): + if name in self.var_op_deps: + for idx in self.var_op_deps[name]["var_as_output_ops"]: + if idx < begin_op_idx: + var_name.append(name) + return var_name + + def is_subgraph(self, var_group1, var_group2): + # should traverse from var_group1 to var_group2 + # max op idx in var_group2 + # min op idx in var_group1 + min_op_idx = len(self.ops) + max_op_idx = -1 + for name in var_group1: + if name not in self.var_op_deps: + return False, min_op_idx, max_op_idx + for name in var_group2: + if name not in self.var_op_deps: + return False, min_op_idx, max_op_idx + for name in var_group1: + op_idx = self.var_op_deps[name]["var_as_input_ops"] + for idx in op_idx: + min_op_idx = min(min_op_idx, idx) + for name in var_group2: + op_idx = self.var_op_deps[name]["var_as_output_ops"] + for idx in op_idx: + max_op_idx = max(max_op_idx, idx) + if min_op_idx >= max_op_idx: + return False, min_op_idx, max_op_idx + + return True, min_op_idx, max_op_idx + + def _update_segment_start(self, min_idx, pre_segment_end_idx): + """ + persist vars of amp-related cast should be included in recompute segment + """ + + def is_amp_cast(op): + return op.desc.type() == 'cast' and self.block.var( + op.desc.input_arg_names()[0]).persistable + + idx_ = min_idx - 1 + updated_min_idx = min_idx + while idx_ > pre_segment_end_idx: + if is_amp_cast(self.ops[idx_]): + _logger.info("found amp-cast op: {}, : {}".format( + self.ops[idx_].desc.type(), + self.ops[idx_].desc.input_arg_names()[0])) + updated_min_idx = idx_ + idx_ -= 1 + else: + break + + return updated_min_idx + + def build_stats(self): + for i, op in enumerate(self.ops): + self.op_deps[i] = {"in_ops": [], "out_ops": []} + for j, name in enumerate(op.desc.input_arg_names()): + if name in self.var_op_deps: + self.op_deps[i]["in_ops"].extend( + self.var_op_deps[name]["var_as_output_ops"]) + for j, name in enumerate(op.desc.input_arg_names()): + if name in self.var_op_deps: + self.var_op_deps[name]["var_as_input_ops"].extend([i]) + else: + self.var_op_deps[name] = {} + self.var_op_deps[name]["var_as_input_ops"] = [i] + self.var_op_deps[name]["var_as_output_ops"] = [] + + for j, name in enumerate(op.desc.output_arg_names()): + if name in self.var_op_deps: + self.var_op_deps[name]["var_as_output_ops"].extend([i]) + else: + self.var_op_deps[name] = {} + self.var_op_deps[name]["var_as_input_ops"] = [] + self.var_op_deps[name]["var_as_output_ops"] = [i] + + for op_idx in self.op_deps[i]["in_ops"]: + self.op_deps[op_idx]["out_ops"].extend([i]) + + def sort_checkpoints(self, checkpoints_name): + sorted_checkpoints = [] + for name in checkpoints_name: + if name not in self.var_op_deps: + _logger.info( + "Recompute Optimizer: deleted %s from checkpoints, because it is not used in paddle program." + % name) + elif self.var_op_deps[name]["var_as_output_ops"] == []: + # input nodes + sorted_checkpoints.append((name, -1)) + else: + sorted_checkpoints.append( + (name, max(self.var_op_deps[name]["var_as_output_ops"]))) + sorted_checkpoints = sorted(sorted_checkpoints, key=lambda x: x[1]) + return [x[0] for x in sorted_checkpoints] + + def modify_forward_desc_for_recompute(self): + op_types = [op.desc.type() for op in self.ops] + if "dropout" not in op_types: + return + + op_idx = 0 + while op_idx < len(self.ops): + op = self.ops[op_idx] + if op.desc.type() != "dropout": + op_idx += 1 + continue + # already insert seed op before dropout + if op.input('Seed') is not None and len(op.input('Seed')) == 1: + op_idx += 1 + continue + # add a seed op so that the two dropout op can generate same output + op_unique_name = unique_name.generate("seed") + var_unique_name = unique_name.generate_with_ignorable_key(".".join( + [op_unique_name, 'tmp'])) + added_var = self.block.create_var( + name=var_unique_name, + dtype='int32', + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + seed = 0 if op.attr("fix_seed") is False else int(op.attr("seed")) + + op_device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName( + ) + op_device = "" + if op.desc.has_attr(op_device_attr_name): + op_device = op.desc.attr(op_device_attr_name) + + # Setting the force_cpu of seed to true will make the output of seed in cpu memory, + # reduce the synchronous copy from GPU to CPU in dropout, and reduce the communication hang + added_op = self.block._insert_op(index=op.idx, + type='seed', + inputs={}, + outputs={'Out': [added_var]}, + attrs={ + 'seed': seed, + 'op_device': op_device, + 'force_cpu': True + }) + self.ops.insert(op_idx, added_op) + # modify dropout op desc so that it accept a seed var as input + op.desc.set_input("Seed", [var_unique_name]) + op.desc.remove_attr("fix_seed") + op.desc.remove_attr("seed") + self.block._sync_with_cpp() + op_idx += 2 + + +def _pretty_op_desc_(op_desc, prefix): + out_s = "%s\tname:[%s]\n%s \tinputs:[%s]\n%s \toutputs:[%s]" % \ + (prefix + "_op", str(op_desc.type()), prefix + "_input", " ".join(op_desc.input_arg_names()), + prefix + "_output", " ".join(op_desc.output_arg_names())) + return out_s + + +def _add_needed_descs_to_block(descs, + block, + main_block, + in_memory_vars, + grad_op_id_to_fwd_op=None): + if len(descs) == 0: + return [] + result_descs = [] + op_role_attr_name = \ + core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + for desc in descs: + origin_desc = desc + origin_is_operator = False + if isinstance(desc, framework.Operator): + desc = desc.desc + origin_is_operator = True + if isinstance(desc, tuple): + desc = desc[0] + is_needed = False + for name in desc.output_arg_names(): + if main_block.has_var(name) and main_block.var(name).persistable: + continue + if name not in in_memory_vars: + is_needed = True + if is_needed: + if origin_is_operator and grad_op_id_to_fwd_op is not None: + grad_op_id_to_fwd_op[desc.original_id()] = origin_desc + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(desc) + new_op_desc._set_attr(op_role_attr_name, backward) + if desc.has_attr('op_device'): + new_op_desc._set_attr('op_device', desc.attr('op_device')) + result_descs.append(new_op_desc) + return result_descs + + +def _add_descs_to_block(descs, block, grad_op_id_to_fwd_op=None): + if len(descs) == 0: + return [] + result_descs = [] + op_role_attr_name = \ + core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + for desc in descs: + if isinstance(desc, framework.Operator): + # for recompute, should record recompute ops + if grad_op_id_to_fwd_op is not None: + grad_op_id_to_fwd_op[desc.desc.original_id()] = desc + desc = desc.desc + if isinstance(desc, tuple): + desc = desc[0] + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(desc) + new_op_desc._set_attr(op_role_attr_name, backward) + if desc.has_attr('op_device'): + new_op_desc._set_attr('op_device', desc.attr('op_device')) + result_descs.append(new_op_desc) + return result_descs + + +def _find_loss_op_(loss): + for op in reversed(loss.block.ops): + assert isinstance(op, framework.Operator) + if len(op.output_arg_names + ) == 1 and op.output_arg_names[0] == loss.name: + loss.op = op + break + if loss.op is None: + raise ValueError("loss.op is None. Should not happend") + + +def _rename_arg_(op_descs, old_name, new_name, begin_idx=None, end_idx=None): + """ + Traverse all ops in op_descs[begin_idx : end_idx], + if any op has inputs/outputs named "old_name", rename it as 'new_name' + """ + if begin_idx is None: + begin_idx = 0 + if end_idx is None: + end_idx = len(op_descs) + if isinstance(op_descs, (list, tuple)): + for i in range(begin_idx, end_idx): + op_desc = op_descs[i] + if isinstance(op_desc, tuple): + op_desc = op_desc[0] + op_desc._rename_input(old_name, new_name) + op_desc._rename_output(old_name, new_name) + if isinstance(op_descs, collections.OrderedDict): + for key, value in op_descs.items(): + if isinstance(value, (list, tuple)): + for op_desc in value: + op_desc._rename_input(old_name, new_name) + op_desc._rename_output(old_name, new_name) + + +def _create_op_desc_(op_type, inputs, outputs, attrs): + """ + Create a C++ OpDesc object with specified inputs, outputs and attributes. + """ + op_desc = core.OpDesc() + op_desc.set_type(op_type) + for para, args in six.iteritems(inputs): + op_desc.set_input( + para, + list( + map( + lambda arg: arg.decode() + if isinstance(arg, six.binary_type) else arg, args))) + for para, args in six.iteritems(outputs): + op_desc.set_output( + para, + list( + map( + lambda arg: arg.decode() + if isinstance(arg, six.binary_type) else arg, args))) + + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + op_device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + + if op_role_attr_name not in attrs: + attrs[ + op_role_attr_name] = core.op_proto_and_checker_maker.OpRole.Backward + if op_device_attr_name not in attrs: + attrs[op_device_attr_name] = "" + for name, val in six.iteritems(attrs): + if isinstance(val, framework.Block): + op_desc.set_block_attr(name, val.desc) + else: + op_desc._set_attr(name, val) + return op_desc + + +def _create_loss_op_desc_(loss): + op_desc = _create_op_desc_( + "fill_constant", {}, {"Out": [_append_grad_suffix_(loss.name)]}, { + "shape": [1], + "value": + 1.0, + "dtype": + loss.dtype, + "force_cpu": + False, + core.op_proto_and_checker_maker.kOpRoleAttrName(): + int(core.op_proto_and_checker_maker.OpRole.Backward) + | int(core.op_proto_and_checker_maker.OpRole.Loss), + core.op_proto_and_checker_maker.kOpDeviceAttrName(): + loss.op.attr(core.op_proto_and_checker_maker.kOpDeviceAttrName()) + }) + return op_desc + + +def _infer_var_data_type_shape_(grad_var_name, block): + """ + Infer the data type and shape of given grad variable + """ + grad_var = block.desc.find_var(cpt.to_bytes(grad_var_name)) + fwd_name = _strip_grad_suffix_(grad_var_name) + if block.desc.has_var_recursive(cpt.to_bytes(fwd_name)): + fwd_var = block.desc.find_var_recursive(cpt.to_bytes(fwd_name)) + grad_var.set_dtype(fwd_var.dtype()) + grad_var.set_shape(fwd_var.shape()) + else: + # TODO(jiabin): Maybe we should not to this to cause some unexpected error on dtype + warnings.warn( + "Set grad var: {} dtype to default FP32, since we can't find its related forward var" + .format(grad_var_name)) + grad_var.set_dtype(core.VarDesc.VarType.FP32) + + +def _all_in_set_(cands, s): + """ + Test if all elements of 'cands' are in set 's' + """ + if len(cands) == 0: + return False + for c in cands: + if not c in s: + return False + return True + + +def _some_in_set_(cands, s): + """ + Test if some elements of 'cands' are in set 's' + """ + if len(cands) == 0: + return False + literal_set = cpt.to_text(s) + literal_cands = cpt.to_text(cands) + for c in literal_cands: + if c in literal_set: + return True + return False + + +def _strip_grad_suffix_(name): + """ + Strip the grad suffix from the given variable name + e.g. x@GRAD ==> x + y@GRAD@RENAME@1 ==> y + """ + name = cpt.to_text(name) + pos = name.find(core.grad_var_suffix()) + new_name = name[:pos] if pos != -1 else name + new_pos = name.rfind('grad/') + return new_name[new_pos + 5:] if new_pos != -1 else new_name + + +def _append_grad_suffix_(name): + """ + Append grad suffix to the given variable name + e.g. x ==> x@GRAD + """ + return cpt.to_text(name) + core.grad_var_suffix() + + +def _accumulate_gradients_by_sum_op_(var_name, + renamed_vars, + pending_sum_ops, + op_idx, + op_device=""): + """ + Use sum op to accumulate_gradients, the gradients are stored in renamed_vars. + """ + if op_idx not in pending_sum_ops.keys(): + pending_sum_ops[op_idx] = [] + pending_sum_ops[op_idx].append( + _create_op_desc_("sum", {"X": renamed_vars[var_name]}, + {"Out": [var_name]}, { + "use_mkldnn": False, + "op_device": op_device + })) + renamed_vars[var_name] = [var_name] + + +def _accumulate_gradients_by_add_ops_(var_name, + renamed_vars, + pending_sum_ops, + op_idx, + op_device=""): + """ + Use several inplace add op to accumulate_gradients, the gradients are stored in renamed_vars. + """ + if op_idx not in pending_sum_ops.keys(): + pending_sum_ops[op_idx] = [] + out_name = renamed_vars[var_name][0] + for i in range(1, len(renamed_vars[var_name])): + x_name = out_name + y_name = renamed_vars[var_name][i] + if i != len(renamed_vars[var_name]) - 1: + out_name = var_name + '@ADD@' + str(i) + else: + out_name = var_name + pending_sum_ops[op_idx].append( + _create_op_desc_("grad_add", { + "X": [x_name], + "Y": [y_name] + }, {"Out": [out_name]}, { + "use_mkldnn": False, + "op_device": op_device + })) + renamed_vars[var_name] = [var_name] + + +def _addup_repetitive_outputs_(op_descs, + block_idx, + grad_var_to_var=None, + grad_op_id_to_fwd_op=None): + """ + In backward part, an variable may be the output of more than one ops. + And one op may yield its multiple outputs to the same variable. + In these cases, the variable should be the accumulation of all the outputs. + `sum_op`s are added to implement the accumulate. + + Args: + grad_var_to_var(dict): used to build the mapping between grad var name and forward var name. + Only for auto parallel. + """ + + _MAX_ADD_NUM_ = framework._global_flags()['FLAGS_max_inplace_grad_add'] + #pending_sum_ops = [] + pending_sum_ops = collections.OrderedDict() + var_rename_count = collections.defaultdict(int) + renamed_vars = collections.defaultdict(list) + renamed_var_start_idx = collections.defaultdict(list) + var_device = collections.defaultdict(str) + for idx, op_desc in enumerate(op_descs): + op_device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName( + ) + op_device = "" + if op_desc.has_attr(op_device_attr_name): + op_device = op_desc.attr(op_device_attr_name) + for var_name in op_desc.input_arg_names(): + if "@GRAD" not in var_name: + continue + if len(renamed_vars[var_name]) > 1: + if len(renamed_vars[var_name]) > _MAX_ADD_NUM_: + _accumulate_gradients_by_sum_op_(var_name, renamed_vars, + pending_sum_ops, idx, + var_device[var_name]) + else: + _accumulate_gradients_by_add_ops_(var_name, renamed_vars, + pending_sum_ops, idx, + var_device[var_name]) + + for param_idx, param_name in enumerate(op_desc.output_names()): + arg_names = op_desc.output(param_name) + for arg_idx, var_name in enumerate(arg_names): + if "@GRAD" not in var_name: + continue + # if "@RENAME@" in var_name: + # continue + if var_name == core.empty_var_name( + ) or var_name in op_desc.input_arg_names(): + # empty variable or inplace op + continue + if len(renamed_vars[var_name]) == 0: + # it's the first time we get the variable + renamed_vars[var_name] = [var_name] + renamed_var_start_idx[var_name] = idx + else: + if len(renamed_vars[var_name]) == 1: + new_name = var_name + "@RENAME@block" + str(block_idx) + "@" + \ + str(var_rename_count[var_name]) + var_rename_count[var_name] += 1 + # Build the mapping between the new_name and var_name (Only for auto parallel) + if grad_var_to_var is not None: + if var_name in grad_var_to_var: + grad_var_to_var[new_name] = grad_var_to_var[ + var_name] + else: + grad_var_to_var[new_name] = var_name + # rename original var_name + renamed_vars[var_name][0] = new_name + # before change: _rename_arg_(op_descs, var_name, + # new_name, 0, idx) + # rename arg from idx of the first appearance + # in backward, not always from 0 + _rename_arg_(op_descs, var_name, new_name, + renamed_var_start_idx[var_name], idx) + _rename_arg_(pending_sum_ops, var_name, new_name) + + for p in op_desc.output_names()[:param_idx]: + p_arg_names = op_desc.output(p) + if var_name in p_arg_names: + op_desc.set_output(p, [ + new_name if x == var_name else x + for x in p_arg_names + ]) + + arg_names = [ + new_name if x == var_name else x + for x in arg_names[:arg_idx] + ] + arg_names[arg_idx:] + + new_name = var_name + "@RENAME@block" + str(block_idx) + "@" + \ + str(var_rename_count[var_name]) + var_rename_count[var_name] += 1 + # Build the mapping between the new_name and var_name (Only for auto parallel) + if grad_var_to_var is not None: + if var_name in grad_var_to_var: + grad_var_to_var[new_name] = grad_var_to_var[ + var_name] + else: + grad_var_to_var[new_name] = var_name + arg_names[arg_idx] = new_name + op_desc.set_output(param_name, arg_names) + renamed_vars[var_name].append(new_name) + # record the latest device + var_device[var_name] = op_device + + for var_name, inputs in six.iteritems(renamed_vars): + if len(renamed_vars[var_name]) > 1: + if len(renamed_vars[var_name]) > _MAX_ADD_NUM_: + _accumulate_gradients_by_sum_op_(var_name, renamed_vars, + pending_sum_ops, len(op_descs), + var_device[var_name]) + else: + _accumulate_gradients_by_add_ops_(var_name, + renamed_vars, pending_sum_ops, + len(op_descs), + var_device[var_name]) + + op_descs_len = len(op_descs) + # sum_op descs are sorted according to their insert position + for key, value in collections.OrderedDict( + reversed(list(pending_sum_ops.items()))).items(): + + # NOTE(zhiqiu): Since reversed, the idx of op_descs to be inserted will remains correct. + # For example, [0, 1, 2], and we want to insert 'a' at idx 1, 'b' at idx 2, and the expected result is [0, 1, 'a', 2, 'b']. + # If reversed, we first insert 'b' at idx 2, it becomes [0, 1, 2, 'b'], and then insert 'a' at idx 1, it becomes [0, 1, 'a', 2, 'b']. + # If not reverse, we first insert 'a' at idx 1, it becomes [0, 1, 'a', 2], and then insert 'b' at idx 2, it becomes [0, 1, 'a', 'b', 2]. + idx = key + for i, op in enumerate(value): + # update the mapping between fwd and bwd + target_idx = idx - 1 if idx == op_descs_len else idx + i + if grad_op_id_to_fwd_op is not None and grad_op_id_to_fwd_op.get( + op_descs[target_idx].original_id(), None) is not None: + grad_op_id_to_fwd_op[op.original_id()] = grad_op_id_to_fwd_op[ + op_descs[target_idx].original_id()] + op_descs.insert(idx + i, op) + + return op_descs + + +def _remove_no_grad_branch_(op_descs, + no_grad_set, + grad_op_id_to_fwd_op=None, + target_vars=[]): + """ + Remove unnecessary grad ops + A grad op can be removed in two cases: + 1. all outputs of the grad op are in 'no_grad_set' + 2. all grad inputs of the grad op are in 'no_grad_set' + NOTE: we will skip target_vars's grad name. + """ + + def _op_can_be_removed_(op_desc, no_grad_set): + out_arg_names = op_desc.output_arg_names() + if len(out_arg_names) == 0 or _all_in_set_(out_arg_names, no_grad_set): + return True + if _all_in_set_([ + name for name in op_desc.input_arg_names() + if name.find(core.grad_var_suffix()) != -1 + ], no_grad_set): + no_grad_set.update(set(out_arg_names) - target_grad_var_names) + return True + return False + + # Remove ops whose outputs are all in no_grad_dict + target_grad_var_names = set( + [var.name + core.grad_var_suffix() for var in target_vars]) + op_descs = [ + op_desc for op_desc in op_descs + if not _op_can_be_removed_(op_desc, no_grad_set) + ] + # Insert fill_any_like_op with value 0 + to_insert = [] + for idx, op_desc in enumerate(op_descs): + for arg in op_desc.input_arg_names(): + # arg is a gradient var name and arg should not have gradient + if core.grad_var_suffix() in arg and arg in no_grad_set: + x_in = _strip_grad_suffix_(arg) + # the reason should be: arg can be input of another grad op + # and the op is a not-to-remove op + new_op_desc = _create_op_desc_("fill_any_like", {"X": [x_in]}, + {"Out": [arg]}, { + 'value': 0, + 'dtype': -1 + }) + # update the mapping between fwd and bwd + if grad_op_id_to_fwd_op is not None and grad_op_id_to_fwd_op.get( + op_desc.original_id(), None) is not None: + grad_op_id_to_fwd_op[new_op_desc.original_id( + )] = grad_op_id_to_fwd_op[op_desc.original_id()] + to_insert.append((new_op_desc, idx)) + + list([op_descs.insert(p[1], p[0]) for p in reversed(to_insert)]) + + return op_descs + + +def _find_not_need_ops(grad_op_descs, forward_ops, input_grad_names_set): + """ + Pruning Program with Structural Analysis Method of Computational Graph. + The nodes of the computational graph composed of backward OPS should be + interconnected. If there are unconnected sub-graphs in the computational graph, + these sub-graphs should be cut off. + + Args: + grad_op_descs(list[core.OpDesc]): The candidate backward OpDescs. + forward_ops(list[Operator]): The forward ops. + input_grad_names_set(set): this set is used to store the gradients' name + which is generated by backward ops, and input_grad_names_set can help + to prune the unnecessary backward ops. + + Return: + (set[core.OpDesc]): A set of OpDescs which should be pruned. + """ + + class Var(object): + + def __init__(self, var_name): + self.var_name = var_name + self.gen_op = None + self.pendding_ops = [] + + def set_gen_op(self, gen_op): + assert isinstance(gen_op, Op) + assert self.gen_op is None + self.gen_op = gen_op + + def add_pending_op(self, op): + assert isinstance(op, Op) + self.pendding_ops.append(op) + + class Op(object): + + def __init__(self, op_desc): + self.op_desc = op_desc + self.inputs = [] + self.outputs = [] + + def insert_input(self, var): + assert isinstance(var, Var) + self.inputs.append(var) + + def insert_output(self, var): + assert isinstance(var, Var) + self.outputs.append(var) + + var_versions = dict() + + def _create_node(name): + if name not in var_versions.keys(): + var_versions[name] = [Var(name)] + else: + var_versions[name].append(Var(name)) + return var_versions[name][-1] + + def _create_or_get_last_version_node(name): + if name not in var_versions.keys(): + var_versions[name] = [Var(name)] + return var_versions[name][-1] + + def _create_op_node(op_desc): + op_node = Op(op_desc) + for input in op_desc.input_arg_names(): + var = _create_or_get_last_version_node(name=input) + var.add_pending_op(op_node) + op_node.insert_input(var) + for output in op_desc.output_arg_names(): + var = _create_node(name=output) + var.set_gen_op(op_node) + op_node.insert_output(var) + return op_node + + # Record the forward vars + forward_vars_set = set() if input_grad_names_set is None else set( + input_grad_names_set) + for op in forward_ops: + forward_vars_set.update(op.desc.input_arg_names()) + forward_vars_set.update(op.desc.output_arg_names()) + + # Record the vars which are created during backward and is not generated by op. + backward_vars_set = set() + # special_op_nodes is the candidate sub-graph head node. + special_op_nodes = set() + for op_desc in grad_op_descs: + input_set = set(op_desc.input_arg_names()) + # The new_vars are created during backward and is not generated by op. + new_vars = input_set - forward_vars_set - backward_vars_set + backward_vars_set.update(op_desc.output_arg_names()) + + op_node = _create_op_node(op_desc) + if len(new_vars) == len(input_set): + special_op_nodes.add(op_node) + + not_need_op_descs = [] + # Start traversing all candidate sub-graph headers to check whether + # they are connected to backward computational graphs, and if they are + # not, list them in not_need_op_descs + for special_op_node in special_op_nodes: + op_list = [special_op_node] + ready_vars = set(special_op_node.inputs) + remove_ops = True + candidate_ops = [special_op_node] + while len(candidate_ops) > 0: + op_node = candidate_ops.pop(0) + if _all_in_set_(op_node.inputs, ready_vars): + for out_var in op_node.outputs: + candidate_ops.extend(out_var.pendding_ops) + op_list.extend(out_var.pendding_ops) + ready_vars.update(op_node.outputs) + else: + remove_ops = False + break + if remove_ops: + not_need_op_descs.extend([node.op_desc for node in op_list]) + not_need_op_descs_set = set(not_need_op_descs) + grad_op_descs_set = set(grad_op_descs) + # If a backward computational graph is simply one sub-graph header, the + # not_need_op_descs will be whole graph, this IF clause avoids it. + if grad_op_descs_set == not_need_op_descs_set: + return set() + return not_need_op_descs_set + + +def serialize_op_decs(op_desc): + protostr = op_desc.serialize_to_string() + proto = framework_pb2.OpDesc.FromString(six.binary_type(protostr)) + return proto.__str__() + + +def _append_backward_ops_with_checkpoints_(block, + ops, + target_vars, + target_block, + no_grad_dict, + grad_to_var, + checkpoints, + grad_op_id_to_fwd_op=None): + """ + Create grad ops with forward ops, and insert them into given block + + Args: + block(Block): the block where forward ops are + ops(Op): the forward operators whose forward recomputation backward ops need to be added + target_vars(list[Tensor]): the loss vars we want to calculate gradient. + target_block(Block): the block which is going to hold new generated grad ops + no_grad_dict(dict): + key(int) block index + val(str): corresponding forward variable name + checkpoints: variables that a user defined as checkpoint for forward recomputation + + Algorithms: + 0) deal with forward recomputing program descs + 1) find ops between checkpoints, i.e. recompute_segments + 2) go through all forward ops and induct all variables that will be hold in memory + a. variables that are used across segments will be held in memory + b. output of dropout op will be held in memory + c. input variables will be held in memory + 3) go through each recompute_segments, add backward ops with forward recomputation + a. add ops in current recompute_segment as forward recomputation ops + b. rename all non-checkpoint variables in recomputation ops + c. add backward ops of current recomputation ops + d. add sum op for repetitive_outputs + 4) remove no grad branch as it is in _remove_no_grad_branch_ + 5) Note1: all appended ops' OpRole are Backward + 6) Note2: all variables with new name should be returned so that _append_backward_vars_ can be called + 7) Note3: current forward recomputation backpropagation does not handle programs with subblock + """ + + checkpoints_name = [x.name for x in checkpoints] + checkpoints_name = list(set(checkpoints_name)) + local_block = block.program._create_block() + buffer_block = block.program._create_block() + # 0) deal with forward recomputing program descs + program_stat = ProgramStats(block, ops) + program_stat.modify_forward_desc_for_recompute() + program_stat.build_stats() + + # 1) find ops between checkpoints, i.e. recompute_segments + checkpoints_name = program_stat.sort_checkpoints(checkpoints_name) + segments = [] + + if len(checkpoints_name) == 1: + # only one checkpoint + max_op_idx = -1 + var_group = [checkpoints_name[0]] + for name in var_group: + if name not in program_stat.var_op_deps: + break + op_idx = program_stat.var_op_deps[name]["var_as_output_ops"] + # only count the last generate op + for idx in op_idx: + max_op_idx = max(max_op_idx, idx) + if max_op_idx > 0: + segments.append([0, max_op_idx + 1]) + else: + start_idx = 0 + pre_segment_end_idx = -1 + while True: + if start_idx >= len(checkpoints_name) - 1: + break + # min_idx: checkpoint_1' s input op + # max_idx: checkpoint_2' s output op + flag, min_idx, max_idx = program_stat.is_subgraph( + [checkpoints_name[start_idx]], + [checkpoints_name[start_idx + 1]]) + if flag: + # max_idx + 1 since the exact and used segment end idx is max_idx + min_idx = program_stat._update_segment_start( + min_idx, pre_segment_end_idx) + segments.append([min_idx, max_idx + 1]) + else: + _logger.info("Could not recompute op range [{}] - [{}] ".format( + min_idx, max_idx + 1)) + + start_idx += 1 + + if segments != [] and segments[0][0] != 0: + recompute_segments = [[0, segments[0][0]]] + segments + else: + recompute_segments = segments + + for i, (idx1, idx2) in enumerate(recompute_segments): + _logger.info("recompute segment[{}]".format(i)) + _logger.info("segment start op: [{}]: [{}]".format( + ops[idx1].desc.type(), ops[idx1].desc.input_arg_names())) + _logger.info("segment end op: [{}]: [{}]".format( + ops[idx2 - 1].desc.type(), ops[idx2 - 1].desc.input_arg_names())) + _logger.info("recompute segment[{}]".format(i)) + _logger.info("segment start op: [{}]: [{}]".format( + ops[idx1].desc.type(), ops[idx1].desc.input_arg_names())) + _logger.info("segment end op: [{}]: [{}]".format( + ops[idx2 - 1].desc.type(), ops[idx2 - 1].desc.input_arg_names())) + + # 2) go through all forward ops and induct all variables that will be hold in memory + vars_should_be_hold = [] + # a. variables that are used across segments will be held in memory + for segment in recompute_segments: + vars_should_be_hold.extend( + program_stat.get_out_of_subgraph_vars(segment[0], segment[1])) + + cross_vars = set(vars_should_be_hold) - set(checkpoints_name) + _logger.info("found [{}] vars which cross recompute segment: [{}], better checkpoints might be set to reduce those vars".format( \ + len(cross_vars), cross_vars)) + + # b. output of seed op should be kept in memory + vars_should_be_hold.extend(program_stat.get_reserved_vars()) + # c. input variables are checkpoints + vars_should_be_hold.extend(program_stat.get_input_nodes()) + vars_should_be_hold = list(set(vars_should_be_hold)) + + # 3) go through each recompute_segments, add backward ops with forward recomputation + grad_op_descs = [] + var_name_dict = {} + + vars_in_memory = vars_should_be_hold + checkpoints_name + + max_calculated_op_position = len(ops) + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + if recompute_segments == []: + gap_ops = ops[0:max_calculated_op_position] + for op in reversed(gap_ops): + if op.has_attr("sub_block"): + raise Exception("Recompute don't support ops with sub_block" + "invoke op: %s" % + _pretty_op_desc_(op.desc, "with_sub_block")) + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op.desc, cpt.to_text(no_grad_dict[block.idx]), []) + + # record the mapping between fwd and bwd + if grad_op_id_to_fwd_op is not None: + for op_desc in grad_op_desc: + grad_op_id_to_fwd_op[op_desc.original_id()] = op + + # Set device for grad_op according to forward Op + if op.desc.has_attr(device_attr_name): + op_device = op.desc.attr(device_attr_name) + for op_desc in grad_op_desc: + op_desc._set_attr(device_attr_name, op_device) + added_descs = _add_descs_to_block(grad_op_desc, local_block, + grad_op_id_to_fwd_op) + grad_op_descs.extend(added_descs) + grad_to_var.update(op_grad_to_var) + + for i, segment in enumerate(recompute_segments[::-1]): + gap_ops = ops[segment[1]:max_calculated_op_position] + max_calculated_op_position = segment[0] + for op in reversed(gap_ops): + if op.has_attr("sub_block"): + raise Exception("Recompute don't support ops with sub_block" + "invoke op: %s" % + _pretty_op_desc_(op.desc, "with_sub_block")) + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op.desc, cpt.to_text(no_grad_dict[block.idx]), []) + + # record the mapping between fwd and bwd + if grad_op_id_to_fwd_op is not None: + for op_desc in grad_op_desc: + grad_op_id_to_fwd_op[op_desc.original_id()] = op + + # Set device for grad_op according to forward Op + if op.desc.has_attr(device_attr_name): + op_device = op.desc.attr(device_attr_name) + for op_desc in grad_op_desc: + op_desc._set_attr(device_attr_name, op_device) + added_descs = _add_descs_to_block(grad_op_desc, local_block, + grad_op_id_to_fwd_op) + grad_op_descs.extend(added_descs) + grad_to_var.update(op_grad_to_var) + + ff_ops = ops[segment[0]:segment[1]] + var_suffix = ".subprog_%d" % i + + for op in ff_ops: + if op.has_attr("sub_block"): + raise Exception("Recompute don't support ops with sub_block" + "invoke op: %s" % + _pretty_op_desc_(op.desc, "with_sub_block")) + input_and_output_names = [] + input_and_output_names.extend(op.desc.input_arg_names()) + input_and_output_names.extend(op.desc.output_arg_names()) + for name in input_and_output_names: + if block.var(name).persistable or name in checkpoints_name: + continue + if name in vars_should_be_hold: + continue + if name not in var_name_dict: + var_name_dict[name] = name + var_suffix + + # we should create the rename var in subprog, otherwise its VarType will be BOOL + ref_var = block.program.global_block().var(name) + block.create_var(name=var_name_dict[name], + shape=ref_var.shape, + dtype=ref_var.dtype, + type=ref_var.type, + persistable=ref_var.persistable, + stop_gradient=ref_var.stop_gradient) + + # 3.a. add ops in current recompute_segment as forward recomputation ops + buffer_descs = _add_needed_descs_to_block(ff_ops, buffer_block, block, + vars_in_memory, + grad_op_id_to_fwd_op) + added_descs = _add_descs_to_block(ff_ops, local_block, + grad_op_id_to_fwd_op) + + # 3.b. rename all non-checkpoint variables in recomputation ops + for key in var_name_dict: + _rename_arg_(buffer_descs, key, var_name_dict[key]) + + # added_descs should be in grad_op_descs because it is backward op desc + grad_op_descs.extend(buffer_descs) + + # 3.c. add backward ops for all ops in current segment + for op_desc in reversed(added_descs): + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op_desc, cpt.to_text(no_grad_dict[block.idx]), []) + + # record the mapping between fwd and bwd + if grad_op_id_to_fwd_op is not None: + for g_op_desc in grad_op_desc: + grad_op_id_to_fwd_op[g_op_desc.original_id( + )] = grad_op_id_to_fwd_op[op_desc.original_id()] + + # Set device for grad_op according to forward Op + if op_desc.has_attr(device_attr_name): + op_device = op_desc.attr(device_attr_name) + for g_op_desc in grad_op_desc: + g_op_desc._set_attr(device_attr_name, op_device) + + for key in var_name_dict: + _rename_arg_(grad_op_desc, key, var_name_dict[key]) + grad_op_descs.extend(grad_op_desc) + grad_to_var.update(op_grad_to_var) + + # 3.d. add sum op for repetitive_outputs + grad_op_descs = _addup_repetitive_outputs_( + grad_op_descs, block.idx, grad_op_id_to_fwd_op=grad_op_id_to_fwd_op) + # 4) remove no grad branch as it is in _remove_no_grad_branch_ + grad_op_descs = _remove_no_grad_branch_(grad_op_descs, + no_grad_dict[block.idx], + grad_op_id_to_fwd_op, target_vars) + added_descs = _add_descs_to_block(grad_op_descs, target_block, + grad_op_id_to_fwd_op) + return program_stat, checkpoints_name, vars_should_be_hold, recompute_segments + + +def _get_sub_block_path(sub_block, + sub_block_op_desc, + no_grad_set, + op_path_dict, + sub_block_target_names=None): + """ + Get output vars in subblock which will be assigned to parent block. + It is used to find the grad path in subblock. + + Args: + sub_block(Block): The sub-block in which to get op path. + sub_block_op_desc: The op desc of the sub-block op such as 'while', 'conditional_block' and 'recurrent'. + no_grad_set(set): The set of no grad var name. no_grad_set will be changed. + op_path_dict(dict): op_path_dict will be changed. + key(int) block index + val(list) the op path of block(index) + sub_block_target_names(set): Target var names of sub-block. + Return: + The forward op path of sub-block corresponding to backward op. + """ + + assert sub_block_op_desc.has_attr( + "sub_block") and sub_block.idx == sub_block_op_desc._block_attr_id( + "sub_block") + assert isinstance(sub_block_target_names, (set, type(None))) + + if sub_block_target_names is None: + sub_block_target_names = sub_block_op_desc.output_arg_names + + # TODO(huihuangzheng): add support for recurrent op. + if sub_block_op_desc.type in ["conditional_block", "while"]: + # Step1: get the output vars in sub-block + sub_outputs = [ + sub_block._var_recursive(var) for var in sub_block_target_names + ] + for var in sub_block_target_names: + for op_desc in sub_block.ops: + if var in op_desc.output_arg_names: + for name in op_desc.input_arg_names: + sub_outputs.append(sub_block._var_recursive(name)) + + # Step2: find op path of sub-block + is_while = sub_block_op_desc.type in ["while"] + sub_block_op_path = _find_op_path_(sub_block, sub_outputs, [], + no_grad_set, op_path_dict, is_while) + return sub_block_op_path + return sub_block.ops + + +def _is_grad_op_(op): + op_maker = core.op_proto_and_checker_maker + backward = core.op_proto_and_checker_maker.OpRole.Backward + if op_maker.kOpRoleVarAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(backward): + return True + return False + + +def _rename_grad_name_(name, grad_order): + return 'grad/' * grad_order + name + + +def _append_backward_ops_(block, + ops, + target_vars, + target_block, + no_grad_dict, + grad_to_var, + callbacks=None, + input_grad_names_set=None, + op_path_dict=None, + distop_context=None, + rename_var_map=None, + grad_op_id_to_fwd_op=None): + """ + Create all grad ops, and insert them into given block + + Args: + block(Block): the block where forward ops are + ops(Op): the forward operators whose backward ops need to be added + target_vars(list[Tensor]): the loss vars we want to calculate gradient. + target_block(Block): the block which is going to hold new generated grad ops + no_grad_dict(dict): + key(int) block index + val(set) a set of variable names. These variables have no gradient + grad_to_var(dict)(output argument): + key(str): grad variable name + val(str): corresponding forward variable name + callbacks(callable object): a callable object used to decorate new generated grad ops + input_grad_names_set(set): this set is used to store the gradients' name which is + generated by backward ops, and input_grad_names_set can help to prune the unnecessary + backward ops. + op_path_dict(dict): op_path_dict will be changed. + key(int) block index + val(list) the op path of block(index) + rename_var_map(dict): used to associate target_grad var name with first grad_op input name. + Only used in for high order gradient. + """ + + # Build the mapping between the forward op and backward op (Only for auto parallel) + def update_distop_context(distop_context, op_grad_to_var, + appending_grad_times): + distop_context.grad_var_to_var[appending_grad_times].update( + op_grad_to_var) + for op_desc in grad_op_desc: + assert op_desc.original_id( + ) not in distop_context.grad_op_id_to_op_id + distop_context.grad_op_id_to_op_id[ + op_desc.original_id()] = op.desc.original_id() + + if callbacks is not None: + assert (isinstance(callbacks, (list, tuple))) + for cb in callbacks: + if not hasattr(cb, '__call__'): + raise ValueError("'callback' must be a callable object.") + + # grad_op_descs holds created grad_op, and will be appended to target_block + grad_op_descs = [] + program = block.program + + if rename_var_map is None: + rename_var_map = {} + assert isinstance(rename_var_map, dict) + + # add grad_op_desc by reversed ops + for op in reversed(ops): + grad_sub_block_list = [] + # If the op has its own sub-block, deal with the sub-block first + if op.has_attr("sub_block"): + sub_block = program.block(op._block_attr_id("sub_block")) + grad_sub_block = program._create_block() + grad_sub_block._set_forward_block_idx(sub_block.idx) + # see follwing comments for why set None here. + pre_input_grad_names_set = copy.copy(input_grad_names_set) + input_grad_names_set = None + sub_block_path = op_path_dict[op._block_attr_id("sub_block")] + _append_backward_ops_(sub_block, + sub_block_path, + target_vars, + grad_sub_block, + no_grad_dict, + grad_to_var, + callbacks, + input_grad_names_set, + op_path_dict, + grad_op_id_to_fwd_op=grad_op_id_to_fwd_op) + input_grad_names_set = pre_input_grad_names_set + + program._rollback() + grad_sub_block_list.append(grad_sub_block.desc) + + # Getting op's corresponding grad_op + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op.desc, cpt.to_text(no_grad_dict[block.idx]), grad_sub_block_list) + + # record the mapping between fwd and bwd + if grad_op_id_to_fwd_op is not None: + for op_desc in grad_op_desc: + grad_op_id_to_fwd_op[op_desc.original_id()] = op + + # Build the mapping between the forward op and backward op (Only for auto parallel) + if distop_context is not None: + update_distop_context(distop_context, op_grad_to_var, + program._appending_grad_times) + else: + default_ctx = getattr(paddle.distributed.auto_parallel.dist_context, + '_g_default_distributed_context', None) + if default_ctx is not None: + distop_context = default_ctx.dist_op_context + update_distop_context(distop_context, op_grad_to_var, + program._appending_grad_times) + + # Set device for grad_op according to forward Op + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + if op.desc.has_attr(device_attr_name): + op_device = op.desc.attr(device_attr_name) + for op_desc in grad_op_desc: + op_desc._set_attr(device_attr_name, op_device) + + # Rename internal gradient variables in multiple backward + # so that they have different names with previous backward. + # For example: + # y = x * x, grad = fluid.gradients(fluid.gradients(y, x) + y * y, x) + # In second-time backward, gradient variable names of partial + # forward network (y * y) may be have same names with first-time + # fluid.gradients(y, x). + # So rename here before _addup_repetitive_outputs_. + if program._appending_grad_times > 1: + for op_desc in grad_op_desc: + forward_op_inputs = op.desc.input_arg_names() + for name in op_desc.input_arg_names(): + if name in rename_var_map and name not in forward_op_inputs: + op_desc._rename_input(name, rename_var_map[name]) + for name in op_desc.output_arg_names(): + if "@GRAD" not in name: + continue + if block.desc.find_var(name.encode("ascii")): + new_name = _rename_grad_name_( + name, program._appending_grad_times) + op_desc._rename_output(name, new_name) + rename_var_map[name] = new_name + + if name in op_grad_to_var: + # Build the mapping between the grad var name and var name (Only for auto parallel) + if distop_context is not None: + distop_context.grad_var_to_var[ + program._appending_grad_times][ + new_name] = op_grad_to_var[name] + op_grad_to_var[new_name] = op_grad_to_var[name] + op_grad_to_var.pop(name) + + # If input_grad_names_set is not None, extend grad_op_descs only when + # any input grad in outputs of previous grad ops. + # But this strategy is not suited for while op for some control flow, + # for example, for while op, the grads maybe generated in next loop. + if input_grad_names_set is not None: + is_grad_name = lambda name: name.find(core.grad_var_suffix( + )) != -1 or name in input_grad_names_set + is_append_grad = False + for op_desc in grad_op_desc: + input_grad_names = [ + name for name in op_desc.input_arg_names() + if is_grad_name(name) + ] + # some code of gradient ops, like increment, are not very + # standard, there is no @GRAD in these ops' inputs. + if len(input_grad_names) == 0: + is_append_grad = True + break + + if _some_in_set_(input_grad_names, input_grad_names_set): + grad_op_descs.append(op_desc) + is_append_grad = True + for name in op_desc.output_arg_names(): + input_grad_names_set.add(name) + if is_append_grad: + grad_to_var.update(op_grad_to_var) + else: + grad_op_descs.extend(grad_op_desc) + grad_to_var.update(op_grad_to_var) + + # record mapping bewteen grad var name and var name (Only for auto parallel) + grad_var_to_var = None + if distop_context is not None: + grad_var_to_var = distop_context.grad_var_to_var[ + program._appending_grad_times] + # sum parameter's gradients' var given multiple var gradient + grad_op_descs = _addup_repetitive_outputs_( + grad_op_descs, + block.idx, + grad_var_to_var, + grad_op_id_to_fwd_op=grad_op_id_to_fwd_op) + + # if all outputs of the grad op are in no_grad_set, then just remove and fill zero + # if all inputs of the grad op are in no_grad_set, just remove this op + grad_op_descs = _remove_no_grad_branch_(grad_op_descs, + no_grad_dict[block.idx], + grad_op_id_to_fwd_op, target_vars) + + # remove some backward ops + not_need_ops = _find_not_need_ops(grad_op_descs, ops, input_grad_names_set) + + grad_op_descs = [ + op_desc for op_desc in grad_op_descs if op_desc not in not_need_ops + ] + + # append op_desc in grad_op_descs to target_block + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + for op_desc in grad_op_descs: + new_op_desc = target_block.desc.append_op() + new_op_desc.copy_from(op_desc) + new_op_desc._set_attr(op_role_attr_name, backward) + grad_to_var["__current_op_desc__"] = new_op_desc + if callbacks is not None: + assert (isinstance(callbacks, (list, tuple))) + for cb in callbacks: + cb(block=target_block, context=grad_to_var) + + +def _is_grad_var_(var_name): + return core.grad_var_suffix() in var_name + + +# Find the op who holds the sub_block as its "sub_block" attr +def _find_parent_op_(sub_block): + sub_block_id = sub_block.idx + + if sub_block_id == 0: + return None + + program = sub_block.program + for block_id in six.moves.range(program.num_blocks): + block_desc = program.block(block_id).desc + for op_idx in six.moves.range(block_desc.op_size()): + op = block_desc.op(op_idx) + if op.has_attr("sub_block") and op._block_attr_id( + "sub_block") == sub_block_id: + return op + + # NOTE(paddle-dev): When optimizer is added in conditional block, + # sub_block may not be found. + return None + + +def _append_backward_vars_(block, start_op_idx, grad_to_var, grad_info_map): + """ + Create new variables required by backward pass. + + Args: + block(Block): the block where new variables will be created + start_op_idx(int): Only variables required by ops in block.ops[start_op_idx : ] will be created + grad_to_var(dict): + key(str): grad variable name + val(str): corresponding forward variable name + In most cases, this dict is generated by _append_backward_ops_() + grad_info_map(dict)(output argument): + key(str): forward variable name + val(tuple): a tuple of (str, Block), str is the corresponding grad name, Block is the block containing grad variable + """ + ops_to_remove = [] + ''' + NOTE(paddle-dev): while_grad op may hold some inputs which are not found + in the parent/forward block, and they are also the outputs of while_grad + op. These kinds of inputs are the recursive outputs inside while_grad op. + They should be considered as "already created" when scanning the inner + ops of while_grad ops. + ''' + parent_op = _find_parent_op_(block) + parent_op_vars = [] + if parent_op is not None: + input_args = parent_op.input_arg_names() + output_args = parent_op.output_arg_names() + for in_arg in input_args: + if in_arg in output_args: + parent_op_vars.append(in_arg) + + for op_idx in range(start_op_idx, block.desc.op_size()): + op_desc = block.desc.op(op_idx) + if op_desc.has_attr("sub_block"): + sub_block = block.program.block(op_desc._block_attr_id("sub_block")) + _append_backward_vars_(sub_block, 0, grad_to_var, grad_info_map) + + grad_var_ins = [ + var for var in op_desc.input_arg_names() if _is_grad_var_(var) + ] + grad_var_outs = [ + var for var in op_desc.output_arg_names() if _is_grad_var_(var) + ] + + inputs = [ + var for var in op_desc.input_arg_names() + if var != core.empty_var_name() + ] + outputs = [ + var for var in op_desc.output_arg_names() + if var != core.empty_var_name() + ] + + # If the outputs of grad op is empty, just remove it + if not outputs: + ops_to_remove.append(op_idx) + continue + else: + ''' + If the output is not empty and there is any grad input, find + whether there is any existing input. If not, just remove it. + ''' + if grad_var_ins: + existing_grad_var_ins = [ + var for var in grad_var_ins + if block.desc.has_var_recursive(cpt.to_bytes(var)) + or var in parent_op_vars + ] + if not existing_grad_var_ins: + ''' + FIXME(paddle-dev, zengjinle): rnn_memory_helper_grad is used + in recurrent op. The input of this op does not even exist in + the program! Therefore, any dependency analysis would not + work to this op! If I do not add the following code, this op + would be pruned, and the calculation result would be wrong. + Maybe we should re-design this op later... + ''' + if op_desc.type() not in ['rnn_memory_helper_grad']: + ops_to_remove.append(op_idx) + continue + + new_vars = set() + # create new gradient variables + for grad_var_name in op_desc.output_arg_names(): + if block.desc.has_var_recursive(cpt.to_bytes( + grad_var_name)) or grad_var_name == core.empty_var_name(): + continue + block.desc.var(cpt.to_bytes(grad_var_name)) + new_vars.add(grad_var_name) + if grad_var_name not in grad_to_var: + continue + grad_info_map[grad_to_var[grad_var_name]] = (grad_var_name, block) + # infer_shape and infer_type + op_desc.check_attrs() + op_desc.infer_var_type(block.desc) + op_desc.infer_shape(block.desc) + + for arg in op_desc.output_arg_names(): + if arg in new_vars: + _infer_var_data_type_shape_(arg, block) + + for op_idx in reversed(ops_to_remove): + block.desc._remove_op(op_idx, op_idx + 1) + + +def _rename_grad_(block, start_op_idx, grad_to_var, target_grad_map): + var_map = copy.copy(target_grad_map) + for op_idx in range(start_op_idx, block.desc.op_size()): + op_desc = block.desc.op(op_idx) + for name in op_desc.input_arg_names(): + if name in var_map: + op_desc._rename_input(name, var_map[name]) + + for name in op_desc.output_arg_names(): + if "@GRAD" not in name: + continue + if block.desc.find_var(name.encode("ascii")): + new_name = unique_name.generate(name) + op_desc._rename_output(name, new_name) + var_map[name] = new_name + + for g, ng in six.iteritems(var_map): + if g in grad_to_var: + grad_to_var[ng] = grad_to_var[g] + grad_to_var.pop(g) + + +def _get_stop_gradients_(program): + no_grad_dict = dict() + assert isinstance(program, framework.Program) + for block in program.blocks: + assert isinstance(block, framework.Block) + block_no_grad_set = set() + for var in list(block.vars.values()): + assert isinstance(var, framework.Variable) + if var.stop_gradient: + block_no_grad_set.add(_append_grad_suffix_(var.name)) + no_grad_dict[block.idx] = block_no_grad_set + return no_grad_dict + + +def _get_son_parent_block_idx_dict(program, current_block_idx): + + son_parent_block_idx_dict = collections.OrderedDict() + while current_block_idx >= 0: + parent_block_idx = program.block(current_block_idx).parent_idx + son_parent_block_idx_dict[current_block_idx] = parent_block_idx + current_block_idx = parent_block_idx + + return son_parent_block_idx_dict + + +def _get_no_grad_set_name(no_grad_set): + no_grad_set_name = set() + if no_grad_set is not None: + if isinstance(no_grad_set, (set, list, tuple)): + for i, no_grad_var in enumerate(no_grad_set): + if isinstance(no_grad_var, framework.Variable): + no_grad_set_name.add(no_grad_var.name) + elif isinstance(no_grad_var, six.string_types): + no_grad_set_name.add(no_grad_var) + else: + raise TypeError( + "The type of no_grad_set's member must be paddle.fluid.Variable or str, but received %s." + % (type(no_grad_var))) + else: + raise TypeError( + "The type of no_grad_set should be set or list or tuple, but received {}" + .format(type(no_grad_set))) + return no_grad_set_name + + +@framework.static_only +def append_backward(loss, + parameter_list=None, + no_grad_set=None, + callbacks=None, + checkpoints=None, + distop_context=None): + """ + :api_attr: Static Graph + + This function appends backward part to main_program. + + A complete neural network training is made up of forward and backward + propagation. However, when we configure a network, we only need to + specify its forward part. This function uses the chain rule to automatically + generate the backward part according to the forward part. + + In most cases, users do not need to invoke this function manually. + It will be automatically invoked by the optimizer's `minimize` function. + + Parameters: + loss(Tensor): The loss Tensor of the network. + parameter_list(list[Tensor|str]|tuple[Tensor|str], optional): List/Tuple of Parameters or Parameter.names + that need to be updated by optimizers. + If it is None, all parameters + will be updated. + Default: None. + no_grad_set(set[Tensor|str], optional): Set of Tensors or Tensor.names in the :ref:`api_guide_Block_en` 0 whose gradients + should be ignored. All Tensors with + `stop_gradient=True` from all blocks will + be automatically added into this set. + If this parameter is not None, the Tensors or Tensor.names in this set will be added to the default set. + Default: None. + callbacks(list[callable object]|tuple[callable object], optional): List/Tuple of callback functions. + The callbacks are used for + doing some custom jobs during + backward part building. All + callable objects in it will + be invoked once each time a + new gradient operator is added + into the program. The callable + object must have two input + parameters: ``block`` and ``context`` . + The ``block`` is the :ref:`api_guide_Block_en` which + the new gradient operator will + be added to. The ``context`` is a + map, whose keys are gradient + Tensor names and values are + corresponding original :ref:`api_guide_tensor_en` . + In addition to this, the ``context`` + has another special key-value pair: + the key is string ``__current_op_desc__`` + and the value is the op_desc of the + gradient operator who has just + triggered the callable object. + Default: None. + + Returns: + list of tuple ( :ref:`api_guide_tensor_en` , :ref:`api_guide_tensor_en` ): Pairs of parameter and its corresponding gradients. + The key is the parameter and the value is gradient Tensor. + + Raises: + AssertionError: If ``loss`` is not an instance of Tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 13], dtype='int64') + y = paddle.static.data(name='y', shape=[None, 1], dtype='float32') + x_emb = paddle.static.nn.embedding(x, size=[100, 256]) + y_predict = paddle.static.nn.fc(x=x_emb, size=1, activation=None, name='my_fc') + loss = F.square_error_cost(input=y_predict, label=y) + avg_loss = paddle.mean(loss) + + # Get all weights in main_program, not include bias. + all_weights = [param for param in paddle.static.default_main_program().block(0).all_parameters() if 'w_' in param.name] + all_weights_name = [w.name for w in all_weights] + + # return all param_grads needed to be updated if parameter_list set default None. + p_g_list1 = paddle.static.append_backward(loss=avg_loss) + # output: [(embedding_0.w_0, embedding_0.w_0@GRAD), (my_fc.w_0, my_fc.w_0@GRAD), (my_fc.b_0, my_fc.b_0@GRAD)] + + # return the param_grads corresponding to parameter_list that can be list of param (Tensor). + p_g_list2 = paddle.static.append_backward(loss=avg_loss, parameter_list=all_weights) + # output: [(embedding_0.w_0, embedding_0.w_0@GRAD), (my_fc.w_0, my_fc.w_0@GRAD)] + + # parameter_list can be list of param.name (str). + p_g_list3 = paddle.static.append_backward(loss=avg_loss, parameter_list=all_weights_name) + # output: [(embedding_0.w_0, embedding_0.w_0@GRAD), (my_fc.w_0, my_fc.w_0@GRAD)] + + # no_grad_set can be set of Tensors that means grad will be cut off from these Tensors. + p_g_list4 = paddle.static.append_backward(loss=avg_loss, no_grad_set=set([x_emb])) + # output: [(my_fc.w_0, my_fc.w_0@GRAD), (my_fc.b_0, my_fc.b_0@GRAD)] + + # no_grad_set can be set of Tensor.name when the Tensor is created inside layers and can't be specified explicitly. + p_g_list5 = paddle.static.append_backward(loss=avg_loss, no_grad_set=set(['my_fc.b_0'])) + # output: [(embedding_0.w_0, embedding_0.w_0@GRAD), (my_fc.w_0, my_fc.w_0@GRAD)] + + # return [] because all param_grads are filtered by no_grad_set. + p_g_list6 = paddle.static.append_backward(loss=avg_loss, parameter_list=all_weights, no_grad_set=set(all_weights)) + + """ + grad_op_id_to_fwd_op = { + } # for cuda graph usage, recording the mapping between grad op original id to fwd op + + check_type(loss, 'loss', framework.Variable, + 'paddle.static.append_backward') + + if loss.op is None: + # the loss is from a cloned program. Find loss op manually. + _find_loss_op_(loss) + + loss.op._set_attr( + core.op_proto_and_checker_maker.kOpRoleAttrName(), + int(core.op_proto_and_checker_maker.OpRole.Forward) + | int(core.op_proto_and_checker_maker.OpRole.Loss)) + + if callbacks is not None: + check_type(callbacks, 'callbacks', (list, tuple), + 'paddle.static.append_backward') + + program = loss.block.program + root_block = program.block(0) + current_block_idx = program.current_block_idx + current_block = program.block(current_block_idx) + + is_in_control_flow = current_block_idx != 0 + + # Double grad is not supported in sub-block (control flow) + if not is_in_control_flow: + # _appending_grad_times used for double grad + program._appending_grad_times += 1 + + if no_grad_set is None: + no_grad_set = set() + else: + no_grad_set = _get_no_grad_set_name(copy.copy(no_grad_set)) + no_grad_dict = _get_stop_gradients_(program) + # no_grad_set only contains vars in block 0 + # Todo(liym27): support vars in sub block + no_grad_dict[0].update(list(map(_append_grad_suffix_, no_grad_set))) + + # Currently it is only to support the optimizer.minimize + # in a switch branch, which can append_backward in a sub_block. + # Note: while_loop is in control flow, but it makes no sense to call optimizer in while. + # Todo: report error when it is in while_loop + if is_in_control_flow: + # create grad block if in switch control flow. + target_grad_block = program._create_block( + parent_idx=current_block.parent_idx) + target_grad_block._set_forward_block_idx(current_block_idx) + # after _create_block, program.current_block changes + else: + target_grad_block = root_block + + son_parent_block_idx_dict = _get_son_parent_block_idx_dict( + program, current_block_idx) + + block_fwd_op_num_dict = {} # block_id: fwd_op_num + for idx in son_parent_block_idx_dict: + block_fwd_op_num_dict[idx] = program.block(idx).desc.op_size() + + grad_to_var = dict() + + # pass the cuda_graph_attr to the fill_constant which generates the loss_grad + op_desc = _create_loss_op_desc_(loss) + grad_op_id_to_fwd_op[op_desc.original_id()] = loss.op + target_grad_block.desc.append_op().copy_from(op_desc) + + for block_idx in son_parent_block_idx_dict: + block = program.block(block_idx) + + block_no_grad_set = set( + map(_strip_grad_suffix_, no_grad_dict[block_idx])) + + op_path_dict = dict() + op_path = _find_op_path_(block, [loss], [], block_no_grad_set, + op_path_dict) + + no_grad_vars = _find_no_grad_vars(block, op_path, [loss], + block_no_grad_set) + + block_no_grad_set.update(no_grad_vars) + no_grad_dict[block_idx].update( + list(map(_append_grad_suffix_, block_no_grad_set))) + + input_grad_names_set = None + # For double backward, input_grad_names is used for filtering + # some non-used gradients op(s). + + # TODO(liym27): need a better design. + # not support double grad in control flow sub-block now. + if not is_in_control_flow: + if program._appending_grad_times > 1: + input_grad_names_set = set([_append_grad_suffix_(loss.name)]) + + # TODO: support _append_backward_ops_with_checkpoints_ in + # sub-block (control flow) + is_recompute = False + if checkpoints != None and \ + isinstance(checkpoints, list) and \ + len(checkpoints) > 0: + is_recompute = True + program_stat, checkpoint_names, \ + vars_should_be_hold, \ + recompute_segments = \ + _append_backward_ops_with_checkpoints_( + root_block, + op_path, + [loss], + root_block, + no_grad_dict, + grad_to_var, + checkpoints, + grad_op_id_to_fwd_op) + else: + _append_backward_ops_( + block, # the block where forward ops are in + op_path, + [loss], + target_grad_block, + no_grad_dict, + grad_to_var, + callbacks, + input_grad_names_set=input_grad_names_set, + op_path_dict=op_path_dict, + distop_context=distop_context, + grad_op_id_to_fwd_op=grad_op_id_to_fwd_op) + + grad_info_map = dict() + + # if in control flow, target_grad_block is a created new block which only contains grad ops, + # so fwd_op_num is set to 0. + fwd_op_num = block_fwd_op_num_dict[ + current_block_idx] if not is_in_control_flow else 0 + + # Because append_backward may be called multiple times, + # we need rename the internal gradient variables so that they have + # different names. + _rename_grad_(target_grad_block, fwd_op_num, grad_to_var, {}) + + _append_backward_vars_(target_grad_block, fwd_op_num, grad_to_var, + grad_info_map) + + program.current_block_idx = current_block_idx + program._sync_with_cpp() + + # for cuda graph, copy the cuda graph attr from forward op to backward op + for op in target_grad_block.ops: + if grad_op_id_to_fwd_op.get(op.desc.original_id(), None) is not None: + fwd_op = grad_op_id_to_fwd_op[op.desc.original_id()] + op._cuda_graph_attr = fwd_op._cuda_graph_attr + + if parameter_list is not None: + check_type(parameter_list, 'parameter_list', (list, tuple, set), + 'fluid.backward.append_backward') + parameters = [] + for i, param in enumerate(parameter_list): + check_type(param, 'parameter_list[%s]' % i, + (framework.Variable, six.string_types), + 'fluid.backward.append_backward') + if isinstance(param, framework.Variable): + parameters.append(param.name) + elif isinstance(param, six.string_types): + parameters.append(param) + else: + params = program.global_block().all_parameters() + parameters = [param.name for param in params if param.trainable] + + params_and_grads = [] + op_role_var_attr_name = core.op_proto_and_checker_maker.kOpRoleVarAttrName() + for param in parameters: + if cpt.to_text(param) not in grad_info_map: + continue + grad_info = grad_info_map[param] + grad_block = grad_info[1] + if not grad_block.has_var(grad_info[0]): + raise ValueError("grad block[{0}] did not have grad var {1}".format( + grad_info[1], grad_info[0])) + # Get the param var from the global block + param_var = program.global_block().var(param) + grad_var = grad_block.var(grad_info[0]) + if not is_in_control_flow: + if loss.block.has_var(grad_info[0]): + params_and_grads.append((param_var, grad_var)) + else: + params_and_grads.append((param_var, None)) + else: + params_and_grads.append((param_var, grad_var)) + + for p, g in params_and_grads: + if g is None: + continue + ops = grad_block.ops if is_in_control_flow else program.global_block( + ).ops + for op in reversed(ops): + assert isinstance(op, framework.Operator) + if g.name in op.output_arg_names: + g.op = op + break + + if g.op is None: + raise ValueError("Unexpected branch") + attr_val = [p.name, g.name] + if g.op.has_attr(op_role_var_attr_name): + attr_val.extend(g.op.attr(op_role_var_attr_name)) + g.op._set_attr(op_role_var_attr_name, attr_val) + + if is_recompute: + return params_and_grads, checkpoint_names + else: + return params_and_grads + + +def _as_list(x): + if x is None: + return [] + return list(x) if isinstance(x, Sequence) else [x] + + +def _is_ancestor_block(ancestor_block, block): + prog = block.program + ancestor_idx = ancestor_block.idx + parent_idx = block.parent_idx + + while parent_idx != -1: + if parent_idx == ancestor_idx: + return True + parent_idx = prog.block(parent_idx).parent_idx + + return False + + +def _get_output_names(cur_block, targets): + """ + In `cur_block`, get output names those linked to targets. + NOTE: + 1. `targets` can be in `cur_block`; + Usually, `targets` is in `cur_block`. However, considering control flow, + 2. `targets` may be in sub-block but `cur_block` is an ancestor of `targets[0].block`; + 3. `targets` may be in the block which is ancestor of `cur_block`. + """ + + block = targets[0].block if targets else cur_block + current_output_names = set([out.name for out in targets]) + + # 1. If `targets` in cur_block or the ancestral block of `cur_block` + if block.idx == cur_block.idx or _is_ancestor_block(block, cur_block): + return current_output_names + + # 2. If `cur_block` is an ancestor of `targets[0].block`, run while loop + prog = cur_block.program + while block.idx != cur_block.idx: + assert block.parent_idx != -1 + parent_block = prog.block(block.parent_idx) + + parent_block_output_names = set() + for op in reversed(block.ops): + if _some_in_set_(op.desc.output_arg_names(), current_output_names): + for name in op.desc.input_arg_names(): + current_output_names.add(name) + if not block.desc.find_var(cpt.to_bytes(name)) \ + and parent_block.desc.find_var(cpt.to_bytes(name)): + parent_block_output_names.add(name) + + block = parent_block + current_output_names = parent_block_output_names + + return current_output_names + + +def _find_no_grad_vars(block, op_path, targets, no_grad_set): + """ + Find the vars which is not used in the program, and + those vars belong to no_grad_var. + """ + output_names = _get_output_names(block, targets) + no_grad_var = [] + for i, op in reversed(list(enumerate(op_path))): + # If the op has sub_block, it is too complicated to find the correct no_grad_var. + if not op.has_attr("sub_block"): + for out_var in op.desc.output_arg_names(): + if out_var not in output_names and out_var not in op.desc.input_arg_names( + ) and not block.vars[out_var].stop_gradient: + no_grad_var.append(out_var) + for name in op.desc.input_arg_names(): + if name not in no_grad_set: + output_names.add(name) + return set(no_grad_var) + + +def _find_op_path_(block, + targets, + inputs, + no_grad_set, + op_path_dict=None, + is_while=False): + """ + It is used to find the grad path in `block`. + + Args: + block(Block): The block in which to get op path. + targets(list[Variable]): The target variables. + inputs(list[Variable]): The input variables. + no_grad_set(set): The set of no grad var name. no_grad_set will be changed. + op_path_dict(dict): op_path_dict will be changed. op_path_dict will be changed. + key(int) block index + val(list) the op path of block(index) + is_while(bool): Whether or not `block` is while block + Return: + The forward op path of block corresponding to backward op. + """ + + input_names = set([inp.name for inp in inputs]) + output_names = _get_output_names(block, targets) + if op_path_dict is None: + op_path_dict = dict() + + relevant_op_flags = [True] * len(block.ops) + + # All the inputs of the block are used if inputs is empty, + if inputs: + for i, op in enumerate(block.ops): + if _some_in_set_(op.desc.input_arg_names(), + input_names) and core.has_non_empty_grad_op_maker( + op.type): + for name in op.desc.output_arg_names(): + if name not in no_grad_set: + input_names.add(name) + else: + relevant_op_flags[i] = False + + for i, op in reversed(list(enumerate(block.ops))): + if op.has_attr("sub_block"): + sub_block_id = op._block_attr_id("sub_block") + sub_block = block.program.block(sub_block_id) + sub_block_target_names = output_names & set(op.output_arg_names) + sub_block_path = _get_sub_block_path(sub_block, op, set(), + op_path_dict, + sub_block_target_names) + op_path_dict[sub_block_id] = sub_block_path + + if _some_in_set_(op.desc.output_arg_names(), + output_names) and core.has_non_empty_grad_op_maker( + op.type): + for name in op.desc.input_arg_names(): + if name not in no_grad_set: + output_names.add(name) + else: + relevant_op_flags[i] = False + + if is_while: + # If block is while block, dealing with op specifically again. + # TODO(liym27): Consider special types of ops. + for i, op in reversed(list(enumerate(block.ops))): + if relevant_op_flags[i] == False \ + and _some_in_set_(op.desc.output_arg_names(), output_names): + relevant_op_flags[i] = True + + op_path = [ + block.ops[i] for i in range(len(block.ops)) if relevant_op_flags[i] + ] + + if inputs: + for op in op_path: + for name in op.desc.input_arg_names(): + if name not in input_names and block.vars[name].stop_gradient: + no_grad_set.add(name) + + return op_path + + +def calc_gradient(targets, inputs, target_gradients=None, no_grad_set=None): + """ + Backpropagate the gradients of targets to inputs. + + Args: + targets(Tensor|list[Tensor]|tuple[Tensor]): The target Tensors + inputs(Tensor|list[Tensor]|tuple[Tensor]): The input Tensors + target_gradients (Tensor|list[Tensor]|tuple[Tensor], optional): The gradient Tensors + of targets which has the same shape with targets, If None, ones will + be created for them. + no_grad_set(set[Tensor|str], optional): Set of Tensors or Tensor.names in the :ref:`api_guide_Block_en` 0 whose gradients + should be ignored. All Tensors with + `stop_gradient=True` from all blocks will + be automatically added into this set. + If this parameter is not None, the Tensors or Tensor.names in this set will be added to the default set. + Default: None. + + Return: + (list[Tensor]): A list of gradients for inputs + If an input does not affect targets, the corresponding gradient Tensor + will be None + """ + targets = _as_list(targets) + inputs = _as_list(inputs) + target_gradients = _as_list(target_gradients) + + block = targets[0].block + prog = block.program + # increase appending gradients times + prog._appending_grad_times += 1 + block_idx = block.idx + + if not target_gradients: + target_gradients = [None] * len(targets) + + if len(targets) != len(target_gradients): + raise ValueError( + "Should have the same number of target_gradients as targets") + + if no_grad_set is None: + no_grad_set = set() + else: + no_grad_set = _get_no_grad_set_name(copy.copy(no_grad_set)) + no_grad_dict = _get_stop_gradients_(prog) + no_grad_dict[0].update(list(map(_append_grad_suffix_, no_grad_set))) + + fwd_op_num = block.desc.op_size() + + input_grad_names_set = set() + + target_grad_map = {} + rename_var_map = {} + for i, grad in enumerate(target_gradients): + target = targets[i] + grad_name = _append_grad_suffix_(target.name) + if grad is None: + target_shape = target.name + '_shape' + block.desc.append_op().copy_from( + _create_op_desc_("shape", {'Input': [target.name]}, + {"Out": [target_shape]}, {})) + input_grad_names_set.add(target_shape) + op_desc = _create_op_desc_("fill_constant", + {"ShapeTensor": [target_shape]}, + {"Out": [grad_name]}, { + "shape": target.shape, + "value": 1.0, + "dtype": target.dtype, + }) + + block.desc.append_op().copy_from(op_desc) + input_grad_names_set.add(grad_name) + else: + if target.block.idx != block_idx or target.block.program != prog: + raise ValueError("all targets must be in the same block") + if target.shape != grad.shape: + raise ValueError( + "The shapes of target and grad are different: %s %s" % + (target.name, grad.name)) + target_grad_map[_append_grad_suffix_(target.name)] = grad.name + input_grad_names_set.add(grad.name) + rename_var_map[grad_name] = grad.name + + # For double backward, input_grad_names is used for filter + # some non-used gradients op. rename_var_map is used to + # associate target_grad var name with first grad_op input name. + if prog._appending_grad_times == 1: + input_grad_names_set = None + rename_var_map = {} + + for input in inputs: + if input.block.program != prog: + raise "input must be in the same program as targets" + + block_no_grad_set = set(map(_strip_grad_suffix_, no_grad_dict[0])) + + op_path_dict = dict() + op_path = _find_op_path_(block, targets, inputs, block_no_grad_set, + op_path_dict) + + # find no grad var by op_path + no_grad_vars = _find_no_grad_vars(block, op_path, targets, + block_no_grad_set) + block_no_grad_set.update(no_grad_vars) + + no_grad_dict[0].update(list(map(_append_grad_suffix_, block_no_grad_set))) + grad_to_var = dict() + grad_info_map = dict() + _append_backward_ops_(block, + op_path, + targets, + block, + no_grad_dict, + grad_to_var, + input_grad_names_set=input_grad_names_set, + op_path_dict=op_path_dict, + rename_var_map=rename_var_map) + + # Because calc_gradient may be called multiple times, + # we need rename the internal gradient variables so that they have + # different names. + _rename_grad_(block, fwd_op_num, grad_to_var, target_grad_map) + + _append_backward_vars_(block, fwd_op_num, grad_to_var, grad_info_map) + prog._sync_with_cpp() + + grad_vars = [] + for input_var in inputs: + if input_var.name not in grad_info_map: + grad_vars.append(None) + else: + grad_info = grad_info_map[input_var.name] + grad_block = grad_info[1] + grad_var = grad_block.var(grad_info[0]) + grad_vars.append(grad_var) + + if len(grad_vars) == 1: + return grad_vars[0] + else: + return grad_vars + + +@framework.static_only +def gradients(targets, inputs, target_gradients=None, no_grad_set=None): + """ + + Backpropagate the gradients of targets to inputs. + + Args: + targets (Tensor|list[Tensor]|tuple[Tensor]): The target Tensors. + inputs (Tensor|list[Tensor]|tuple[Tensor]): The input Tensors. + target_gradients (Tensor|list[Tensor]|tuple[Tensor], optional): The gradient Tensor + of targets which has the same shape with targets, If None, ones will + be created for them. + no_grad_set (set[Tensor|str], optional): Set of Tensors or Tensor.names in the :ref:`api_guide_Block_en` 0 whose gradients + should be ignored. All Tensors with ``stop_gradient=True`` from all blocks will + be automatically added into this set. If this parameter is not None, the Tensors or Tensor.names + in this set will be added to the default set. Default: None. + + Return: + (list[Tensor]): A list of gradients for inputs + If an input does not affect targets, the corresponding gradient Tensor + will be None. + + Examples: + + .. code-block:: python + :name: code-example + import paddle + import paddle.nn.functional as F + + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 2, 8, 8], dtype='float32') + x.stop_gradient=False + y = paddle.static.nn.conv2d(x, 4, 1, bias_attr=False) + y = F.relu(y) + z = paddle.static.gradients([y], x) + print(z) # [var x@GRAD : LOD_TENSOR.shape(-1, 2, 8, 8).dtype(float32).stop_gradient(False)] + """ + check_type(targets, 'targets', (framework.Variable, list, tuple), + 'paddle.static.gradients') + check_type(inputs, 'inputs', (framework.Variable, list, tuple), + 'paddle.static.gradients') + check_type(target_gradients, 'target_gradients', + (framework.Variable, list, tuple, type(None)), + 'paddle.static.gradients') + outs = calc_gradient(targets, inputs, target_gradients, no_grad_set) + return _as_list(outs) + + +@framework.static_only +def gradients_with_optimizer(program, optimizer, inputs=None, outputs=None): + """ + :api_attr: Static Graph + + Backpropagate the gradients of the program and apply the gradients with the given optimizer. + + Args: + program (Program): The input program. + optimizer (Optimizer): The optimizer to apply the gradients. + inputs (Tensor|list[Tensor]|tuple[Tensor], optional): The input Tensors. + If None, the inputs will be created from the input variables in the given program. Default:None. + outputs (Tensor|list[Tensor]|tuple[Tensor], optional): The output Tensors. + If None, the outputs will be created from the output variables in the given program. Default: None. + + Return: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by gradients_with_optimizer and a list of (param, grad) variable pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + The returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + img = static.data(name='image', shape=[None, 784]) + pred = static.nn.fc(x=img, size=10, activation='relu') + loss = paddle.mean(pred) + opt_ops, pram_grads = paddle.fluid.backward.gradients_with_optimizer(static.default_main_program(), opt) + print(opt_ops) + + """ + check_type(program, 'program', paddle.fluid.Program, + 'paddle.static.gradients_with_optimizer') + check_type(optimizer, 'optimizer', paddle.optimizer.Optimizer, + 'paddle.static.gradients_with_optimizer') + + if inputs is None or outputs is None: + in_set = set() + out_set = set() + for block in program.blocks: + for op in block.ops: + for name in op.input_arg_names: + in_set.add(block.vars[name]) + for name in op.output_arg_names: + out_set.add(block.vars[name]) + if inputs is None: + inputs = list(in_set.difference(out_set)) + if outputs is None: + outputs = list(out_set.difference(in_set)) + + grads = gradients(outputs, inputs) + + with program_guard(program, None): + pram_grads = [(pram, grad) for pram, grad in zip(inputs, grads) + if isinstance(pram, paddle.fluid.framework.Parameter) + and grad is not None] + + optimize_ops = optimizer.apply_gradients(pram_grads) + + return optimize_ops, pram_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/clip.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd94d840c4d7f44bcc0ce4b09dfb59f10e6259b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/clip.py @@ -0,0 +1,904 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import copy +import six +import warnings + +import functools +import paddle +from . import layers +from . import framework +from . import core +from . import name_scope +from .dygraph import base as imperative_base +from .data_feeder import check_variable_and_dtype +from .framework import _non_static_mode, in_dygraph_mode, _in_legacy_dygraph +from .layer_helper import LayerHelper +from .framework import default_main_program +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'set_gradient_clip', 'ErrorClipByValue', 'ClipGradByValue', + 'ClipGradByNorm', 'ClipGradByGlobalNorm' +] + +_clip_by_global_norm_using_mp_type_flag = False + + +def _clip_by_global_norm_using_mp_type(*args): + global _clip_by_global_norm_using_mp_type_flag + assert len(args) <= 1 + if len(args) == 1: + assert isinstance(args[0], bool) + old_value = _clip_by_global_norm_using_mp_type_flag + _clip_by_global_norm_using_mp_type_flag = args[0] + return old_value + else: + return _clip_by_global_norm_using_mp_type_flag + + +def _cast_to_mp_type_if_enabled(x): + if (x.dtype == core.VarDesc.VarType.FP16 + or x.dtype == core.VarDesc.VarType.BF16 + ) and _clip_by_global_norm_using_mp_type(): + return x.astype(core.VarDesc.VarType.FP32) + else: + return x + + +def _squared_l2_norm(x): + r""" + This OP returns the squared L2 norm of a tensor. + """ + + x = _cast_to_mp_type_if_enabled(x) + if core.is_compiled_with_xpu( + ) or x.dtype == core.VarDesc.VarType.FP16 or x.dtype == core.VarDesc.VarType.BF16: + square = layers.square(x) + sum_square = layers.reduce_sum(square) + return sum_square + + if in_dygraph_mode(): + return _C_ops.squared_l2_norm(x) + elif _in_legacy_dygraph(): + return _legacy_C_ops.squared_l2_norm(x) + + op_type = 'squared_l2_norm' + check_variable_and_dtype(x, 'x', ['float32', 'float64'], op_type) + helper = LayerHelper(op_type, **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + + inputs = {"X": x} + outputs = {'Out': out} + helper.append_op(type=op_type, inputs=inputs, outputs=outputs) + return out + + +class BaseErrorClipAttr(object): + + def __str__(self): + raise NotImplementedError() + + def _append_clip_op(self, block, grad_name): + raise NotImplementedError() + + +class ErrorClipByValue(BaseErrorClipAttr): + r""" + Clips tensor values to the range [min, max]. + + Given a tensor ``t`` (see Examples below), this operation clips its value \ + to ``min`` and ``max`` inplace. + + - Any values less than min are set to min. + - Any values greater than max are set to max. + + Args: + max (float): The maximum value to clip by. + min (float, optional): The minimum value to clip by. if not set by user, \ + will be set to ``-max`` by framework. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + BATCH_SIZE = 128 + CLIP_MAX = 2e-6 + CLIP_MIN = -1e-6 + prog = fluid.framework.Program() + with fluid.program_guard(main_program=prog): + image = fluid.layers.data( + name='x', shape=[784], dtype='float32') + hidden1 = fluid.layers.fc(input=image, size=128, act='relu') + hidden2 = fluid.layers.fc(input=hidden1, size=64, act='relu') + predict = fluid.layers.fc( + input=hidden2, size=10, act='softmax') + label = fluid.layers.data(name='y', shape=[1], dtype='int64') + cost = fluid.layers.cross_entropy(input=predict, label=label) + avg_cost = fluid.layers.mean(cost) + prog_clip = prog.clone() + prog_clip.block(0).var(hidden1.name)._set_error_clip( + fluid.clip.ErrorClipByValue( + max=CLIP_MAX, min=CLIP_MIN) + """ + + def __init__(self, max, min=None): + max = float(max) + if min is None: + min = -max + else: + min = float(min) + self.max = max + self.min = min + + def __str__(self): + return "ByValue, min=%f, max=%f" % (self.min, self.max) + + def _append_clip_op(self, block, grad_name): + clip_op_desc = block.desc.append_op() + clip_op_desc.set_type("clip") + clip_op_desc.set_input("X", [grad_name]) + clip_op_desc.set_output("Out", [grad_name]) + clip_op_desc._set_attr("min", self.min) + clip_op_desc._set_attr("max", self.max) + + +def error_clip_callback(block, context): + # the context is a grad_to_var map + grad_to_var = context + op_desc = block.desc.op(block.desc.op_size() - 1) + for grad_n in [n for n in op_desc.output_arg_names() if n in grad_to_var]: + fwd_var = block._var_recursive(grad_to_var[grad_n]) + error_clip = getattr(fwd_var, "error_clip", None) + if not (error_clip is None + or isinstance(error_clip, BaseErrorClipAttr)): + raise TypeError( + "Variable's error_clip should be an instance of BaseErrorClipAttr or None." + ) + if error_clip is not None: + error_clip._append_clip_op(block, grad_n) + + +class ClipGradBase(object): + + def __init__(self): + super(ClipGradBase, self).__init__() + + def __str__(self): + raise NotImplementedError() + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + raise NotImplementedError + + def _static_clip(self, params_grads): + raise NotImplementedError + + def __call__(self, params_grads): + if framework._non_static_mode(): + return self._dygraph_clip(params_grads) + else: + for p, g in params_grads: + if getattr(p, 'gradient_clip_attr', None) is not None: + warnings.warn( + "'set_gradient_clip' will be ineffective, because you have " + "set 'need_clip' in 'ParamAttr'. So, 'set_gradient_clip' " + "is redundant and you can remove it.") + break + return self._static_clip(params_grads) + + def _process_context(self, context, param, grad): + raise NotImplementedError() + + def _create_operators(self, param, grad): + raise NotImplementedError() + + +class ClipGradByValue(ClipGradBase): + """ + Limit the value of multi-dimensional Tensor :math:`X` to the range [min, max]. + + - Any values less than min are set to ``min``. + + - Any values greater than max are set to ``max``. + + The multi-dimensional Tensor :math:`X` is not passed from this class, but the gradients of all parameters set in ``optimizer``. + If ``need_clip`` of specific param is ``False`` in its ``ParamAttr``, then the gradients of this param will not be clipped. + + Gradient clip will takes effect after being set in ``optimizer`` , see the document ``optimizer`` + (for example: :ref:`api_paddle_optimizer_SGD`). + + Note: + ``need_clip`` of ``ClipGradByValue`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + + Args: + max (float): The maximum value to clip by. + min (float, optional): The minimum value to clip by. if not set by user, it will be set to ``-max`` + automatically. In this case, ``max`` must be greater than 0. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.uniform([10, 10], min=-1.0, max=1.0, dtype='float32') + linear = paddle.nn.Linear(in_features=10, out_features=10, + weight_attr=paddle.ParamAttr(need_clip=True), + bias_attr=paddle.ParamAttr(need_clip=False)) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + + clip = paddle.nn.ClipGradByValue(min=-1, max=1) + sdg = paddle.optimizer.SGD(learning_rate=0.1, parameters=linear.parameters(), grad_clip=clip) + sdg.step() + """ + + def __init__(self, max, min=None): + super(ClipGradByValue, self).__init__() + if min is None: + assert (max > 0.0) + min = -max + self.max = float(max) + self.min = float(min) + + def __str__(self): + return "Clip Gradient By Value, min = %f, max=%f" % (self.min, self.max) + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + params_and_grads = [] + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + new_grad = paddle.clip(x=g, min=self.min, max=self.max) + params_and_grads.append((p, new_grad)) + return params_and_grads + + def _static_clip(self, params_grads): + params_and_grads = [] + param_new_grad_name_dict = dict() + with framework.name_scope('gradient_clip'): + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + + with p.block.program._optimized_guard([p, g]): + new_grad = layers.clip(x=g, min=self.min, max=self.max) + params_and_grads.append((p, new_grad)) + param_new_grad_name_dict[p.name] = new_grad.name + _correct_clip_op_role_var(params_and_grads, param_new_grad_name_dict) + return params_and_grads + + def _process_context(self, context, param, grad): + pass + + def _create_operators(self, param, grad): + new_grad = layers.clip(x=grad, min=self.min, max=self.max) + return param, new_grad + + +class ClipGradByNorm(ClipGradBase): + r""" + Limit the l2 norm of multi-dimensional Tensor :math:`X` to ``clip_norm`` . + + - If the l2 norm of :math:`X` is greater than ``clip_norm`` , :math:`X` will be compressed by a ratio. + + - If the l2 norm of :math:`X` is less than or equal to ``clip_norm`` , nothing will be done. + + The multidimensional Tensor :math:`X` is not passed from this class, but the gradients of all parameters set in ``optimizer``. + If ``need_clip`` of specific param is ``False`` in its ``ParamAttr``, then the gradients of this param will not be clipped. + + Gradient clip will takes effect after being set in ``optimizer`` , see the document ``optimizer`` + (for example: :ref:`api_paddle_optimizer_SGD`). + + The clipping formula is: + + .. math:: + Out = + \left\{ + \begin{array}{ccl} + X & & if (norm(X) \leq clip\_norm) \\ + \frac{clip\_norm*X}{norm(X)} & & if (norm(X) > clip\_norm) \\ + \end{array} + \right. + + + where :math:`norm(X)` represents the L2 norm of :math:`X`. + + .. math:: + norm(X) = ( \sum_{i=1}^{n}|x\_i|^2)^{ \frac{1}{2}} + + Note: + ``need_clip`` of ``ClipGradByNorm`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + + Args: + clip_norm(float): The maximum norm value. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.uniform([10, 10], min=-1.0, max=1.0, dtype='float32') + linear = paddle.nn.Linear(in_features=10, out_features=10, + weight_attr=paddle.ParamAttr(need_clip=True), + bias_attr=paddle.ParamAttr(need_clip=False)) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + + clip = paddle.nn.ClipGradByNorm(clip_norm=1.0) + sdg = paddle.optimizer.SGD(learning_rate=0.1, parameters=linear.parameters(), grad_clip=clip) + sdg.step() + """ + + def __init__(self, clip_norm): + super(ClipGradByNorm, self).__init__() + self.clip_norm = float(clip_norm) + + def __str__(self): + return "Gradient Clip By Norm, clip_norm=%f" % self.clip_norm + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + params_and_grads = [] + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + new_grad = layers.clip_by_norm(x=g, max_norm=self.clip_norm) + params_and_grads.append((p, new_grad)) + return params_and_grads + + def _static_clip(self, params_grads): + params_and_grads = [] + with framework.name_scope('gradient_clip'): + param_new_grad_name_dict = dict() + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + + with p.block.program._optimized_guard([p, g]): + new_grad = layers.clip_by_norm(x=g, max_norm=self.clip_norm) + param_new_grad_name_dict[p.name] = new_grad.name + params_and_grads.append((p, new_grad)) + _correct_clip_op_role_var(params_and_grads, param_new_grad_name_dict) + return params_and_grads + + def _process_context(self, context, param, grad): + pass + + def _create_operators(self, param, grad): + new_grad = layers.clip_by_norm(x=grad, max_norm=self.clip_norm) + return param, new_grad + + +_allow_pure_fp16_global_norm_clip_flag = False + + +def _allow_pure_fp16_global_norm_clip(*args): + global _allow_pure_fp16_global_norm_clip_flag + if len(args) == 0: + return _allow_pure_fp16_global_norm_clip_flag + else: + assert len(args) == 1 and isinstance(args[0], bool) + old_value = _allow_pure_fp16_global_norm_clip_flag + _allow_pure_fp16_global_norm_clip_flag = args[0] + return old_value + + +class ClipGradByGlobalNorm(ClipGradBase): + r""" + Given a list of Tensor :math:`t\_list` , calculate the global norm for the elements of all tensors in + :math:`t\_list` , and limit it to ``clip_norm`` . + + - If the global norm is greater than ``clip_norm`` , all elements of :math:`t\_list` will be compressed by a ratio. + + - If the global norm is less than or equal to ``clip_norm`` , nothing will be done. + + The list of Tensor :math:`t\_list` is not passed from this class, but the gradients of all parameters set in ``optimizer``. + If ``need_clip`` of specific param is ``False`` in its ``ParamAttr``, then the gradients of this param will not be clipped. + + Gradient clip will takes effect after being set in ``optimizer`` , see the document ``optimizer`` + (for example: :ref:`api_paddle_optimizer_SGD`). + + The clipping formula is: + + .. math:: + + t\_list[i] = t\_list[i] * \frac{clip\_norm}{\max(global\_norm, clip\_norm)} + + where: + + .. math:: + + global\_norm = \sqrt{\sum_{i=0}^{N-1}(l2norm(t\_list[i]))^2} + + Note: + ``need_clip`` of ``ClipGradyGlobalNorm`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + + Args: + clip_norm (float): The maximum norm value. + group_name (str, optional): The group name for this clip. Default value is ``default_group``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.uniform([10, 10], min=-1.0, max=1.0, dtype='float32') + linear = paddle.nn.Linear(in_features=10, out_features=10, + weight_attr=paddle.ParamAttr(need_clip=True), + bias_attr=paddle.ParamAttr(need_clip=False)) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + + clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0) + sdg = paddle.optimizer.SGD(learning_rate=0.1, parameters=linear.parameters(), grad_clip=clip) + sdg.step() + """ + + def __init__(self, + clip_norm, + group_name="default_group", + auto_skip_clip=False): + super(ClipGradByGlobalNorm, self).__init__() + self.clip_norm = float(clip_norm) + self.group_name = group_name + assert isinstance(auto_skip_clip, bool) + self.auto_skip_clip = auto_skip_clip + + def __str__(self): + return "Gradient Clip By GlobalNorm, global_norm=%f" % (self.clip_norm) + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + params_and_grads = [] + sum_square_list = [] + sum_square_list_fp16 = [] + sum_square_list_fp32 = [] + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + continue + merge_grad = g + + if in_dygraph_mode() and g.is_selected_rows(): + merge_grad = layers.merge_selected_rows(g) + merge_grad = merge_grad._get_tensor_from_selected_rows() + + elif g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.merge_selected_rows(g) + merge_grad = layers.get_tensor_from_selected_rows(merge_grad) + + sum_square = _squared_l2_norm(merge_grad) + if sum_square.dtype == core.VarDesc.VarType.FP16 or sum_square.dtype == core.VarDesc.VarType.BF16: + sum_square_list_fp16.append(sum_square) + elif sum_square.dtype == core.VarDesc.VarType.FP32: + sum_square_list_fp32.append(sum_square) + else: + sum_square_list.append(sum_square) + + # all parameters have been filterd out + if len(sum_square_list) + len(sum_square_list_fp16) + len( + sum_square_list_fp32) == 0: + return params_grads + + sum_dtype = 'float64' if len(sum_square_list) > 0 else "float32" + global_norm_var = [] + if len(sum_square_list_fp16) > 0: + global_norm_var_fp16 = paddle.add_n(sum_square_list_fp16) + global_norm_var.append(global_norm_var_fp16.astype(sum_dtype)) + if len(sum_square_list_fp32) > 0: + global_norm_var_fp32 = paddle.add_n(sum_square_list_fp32) + if sum_dtype == 'float32': + global_norm_var.append(global_norm_var_fp32) + else: + global_norm_var.append(global_norm_var_fp32.astype(sum_dtype)) + if len(sum_square_list) > 0: + global_norm_var_fp64 = paddle.add_n(sum_square_list) + global_norm_var.append(global_norm_var_fp64) + global_norm_var = paddle.add_n(global_norm_var) + global_norm_var = layers.sqrt(global_norm_var) + max_global_norm = layers.fill_constant(shape=[1], + dtype=global_norm_var.dtype, + value=self.clip_norm) + + need_clip = False + if not self.auto_skip_clip: # always apply clip + need_clip = True + clip_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=global_norm_var, + y=max_global_norm)) + elif global_norm_var > max_global_norm: + # only when global_norm_var > max_global_norm, grad need clip + need_clip = True + clip_var = layers.elementwise_div(x=max_global_norm, + y=global_norm_var) + + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + # TODO(wangxi): use inplace elementwise_mul + if need_clip: + clip_input = (clip_var.astype(g.dtype) + if clip_var.dtype != g.dtype else clip_var) + new_grad = layers.elementwise_mul(g, clip_input) + params_and_grads.append((p, new_grad)) + else: + params_and_grads.append((p, g)) + + return params_and_grads + + def _static_clip(self, params_grads): + params_and_grads = [] + sum_square_list = [] + sum_square_list_fp16 = [] + sum_square_list_fp32 = [] + with framework.name_scope('gradient_clip'): + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + continue + merge_grad = g + with p.block.program._optimized_guard([p, g]): + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.merge_selected_rows(g) + merge_grad = layers.get_tensor_from_selected_rows( + merge_grad) + sum_square = _squared_l2_norm(merge_grad) + if sum_square.dtype == core.VarDesc.VarType.FP16: + sum_square_list_fp16.append(sum_square) + elif sum_square.dtype == core.VarDesc.VarType.FP32: + sum_square_list_fp32.append(sum_square) + else: + sum_square_list.append(sum_square) + + # all parameters have been filterd out + if len(sum_square_list) + len(sum_square_list_fp16) + len( + sum_square_list_fp32) == 0: + return params_grads + + with p.block.program._optimized_guard([p, g]): + sum_dtype = 'float64' if len(sum_square_list) > 0 else "float32" + + global_norm_var = [] + if len(sum_square_list_fp16) > 0: + global_norm_var_fp16 = layers.sums(sum_square_list_fp16) + if sum_square_list_fp32 or sum_square_list or not _allow_pure_fp16_global_norm_clip( + ): + global_norm_var.append( + global_norm_var_fp16.astype(sum_dtype)) + else: + global_norm_var.append(global_norm_var_fp16) + if len(sum_square_list_fp32) > 0: + global_norm_var_fp32 = layers.sums(sum_square_list_fp32) + if sum_dtype == 'float32': + global_norm_var.append(global_norm_var_fp32) + else: + global_norm_var.append( + global_norm_var_fp32.astype(sum_dtype)) + if len(sum_square_list) > 0: + # fp64 + global_norm_var_other_dtype = layers.sums(sum_square_list) + global_norm_var.append(global_norm_var_other_dtype) + + global_norm_var = layers.sums(global_norm_var) if len( + global_norm_var) > 1 else global_norm_var[0] + global_norm_var = layers.sqrt(x=global_norm_var) + max_global_norm = layers.fill_constant( + shape=[1], + dtype=global_norm_var.dtype, + value=self.clip_norm) + scale_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=max_global_norm, + y=global_norm_var)) + param_new_grad_name_dict = dict() + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + + with p.block.program._optimized_guard([p, g]): + new_g = _cast_to_mp_type_if_enabled(g) + # inplace + scale_input = (scale_var.astype('float16') if + new_g.dtype == core.VarDesc.VarType.FP16 and + scale_var.dtype != core.VarDesc.VarType.FP16 + else scale_var) + # NOTE(Yuang Liu): For pure dp with gradient merge, the p and g + # will be in different blocks with the gradient clip related ops. + # We need to handle the correct block, otherwise will encounter + # a 'NotFoundError' during compile time. + block = default_main_program().current_block() + block.append_op(type='elementwise_mul', + inputs={ + 'X': new_g, + 'Y': scale_input + }, + outputs={'Out': new_g}) + if new_g is not g: + block.append_op(type='cast', + inputs={'X': new_g}, + outputs={'Out': g}, + attrs={ + 'in_dtype': new_g.dtype, + 'out_dtype': g.dtype + }) + + param_new_grad_name_dict[p.name] = g.name + params_and_grads.append((p, g)) + + _correct_clip_op_role_var(params_and_grads, param_new_grad_name_dict) + return params_and_grads + + def _process_context(self, context, param, grad): + if self.group_name not in context: + context[self.group_name] = [] + context[self.group_name + "_clip_value"] = self.clip_norm + context[self.group_name + "_clip"] = layers.fill_constant( + shape=[1], dtype=grad.dtype, value=self.clip_norm) + else: + if not self.clip_norm == context[self.group_name + "_clip_value"]: + raise ValueError( + "All parameters' 'clip_norm' of a same group should be the same" + ) + + merge_grad = grad + if grad.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.merge_selected_rows(grad) + merge_grad = layers.get_tensor_from_selected_rows(merge_grad) + + local_norm_var = _squared_l2_norm(merge_grad) + context[self.group_name].append(local_norm_var) + + self.context = context + + def _create_operators(self, param, grad): + group_scale_name = self.group_name + "_scale" + if group_scale_name not in self.context: + group_norm_var = layers.sums(input=self.context[self.group_name]) + group_norm_var = layers.sqrt(x=group_norm_var) + clip_var = self.context[self.group_name + "_clip"] + group_scale_var = layers.elementwise_div(x=clip_var, + y=layers.elementwise_max( + x=clip_var, + y=group_norm_var)) + assert group_scale_var.shape == (1, ) + self.context[group_scale_name] = group_scale_var + + # inplace + param.block.append_op(type='elementwise_mul', + inputs={ + 'X': grad, + 'Y': self.context[group_scale_name] + }, + outputs={'Out': grad}) + + return param, grad + + +@framework.dygraph_not_support +def set_gradient_clip(clip, param_list=None, program=None): + """ + :api_attr: Static Graph + + Warning: + + This API must be used after building network, and before ``minimize`` , + and it may be removed in future releases, so it is not recommended. + It is recommended to set ``grad_clip`` when initializing the ``optimizer`` , + this is a better method to clip gradient. There are three clipping strategies: + :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` . + + To specify parameters that require gradient clip. + + Args: + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default value: None, and there is no + gradient clipping. + param_list (list(Variable), optional): Parameters that require gradient clip. + It can be a list of parameter or a list of parameter's name. + Default None, meaning that all parameters in the program will be included. + program (Program, optional): The program where parameters are located. + Default None, meaning that using :ref:`api_fluid_default_main_program` . + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + def network(): + image = fluid.data(name='image', shape=[ + None, 28], dtype='float32') + param_attr1 = fluid.ParamAttr("fc1_param") + fc1 = fluid.layers.fc(image, size=10, param_attr=param_attr1) + param_attr2 = fluid.ParamAttr("fc2_param") + fc2 = fluid.layers.fc(fc1, size=10, param_attr=param_attr2) + loss = fluid.layers.reduce_mean(fc2) + return loss + + + # network 1: clip all parameter gradient + with fluid.program_guard(fluid.Program(), fluid.Program()): + loss = network() + fluid.clip.set_gradient_clip( + fluid.clip.GradientClipByGlobalNorm(clip_norm=2.0)) + sgd = fluid.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(loss) + + # network 2: clip parameter gradient by name + with fluid.program_guard(fluid.Program(), fluid.Program()): + loss = network() + fluid.clip.set_gradient_clip( + fluid.clip.GradientClipByValue(min=-1.0, max=1.0), + param_list=["fc1_param", "fc2_param"]) + sgd = fluid.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(loss) + + # network 3: clip parameter gradient by value + with fluid.program_guard(fluid.Program(), fluid.Program()): + loss = network() + param_var1 = fluid.default_main_program().global_block().var("fc1_param") + param_var2 = fluid.default_main_program().global_block().var("fc2_param") + fluid.clip.set_gradient_clip( + fluid.clip.GradientClipByValue(min=-1.0, max=1.0), + param_list=[param_var1, param_var2]) + sgd = fluid.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(loss) + + # network 4: use 'set_gradient_clip' and 'optimize(grad_clip=clip)' together + with fluid.program_guard(fluid.Program(), fluid.Program()): + loss = network() + clip1 = fluid.clip.GradientClipByValue(min=-1.0, max=1.0) + clip2 = fluid.clip.GradientClipByNorm(clip_norm=1.0) + # Set the gradient clipping strategy: clip1 + fluid.clip.set_gradient_clip(clip1) + # Set the gradient clipping strategy: clip2 + sgd = fluid.optimizer.SGD(learning_rate=1e-3, grad_clip=clip2) + sgd.minimize(loss) + # 'set_gradient_clip' will not take effect when setting has a conflict, + # and the gradient clipping strategy will be 'clip2' + + + """ + warnings.warn("Caution! 'set_gradient_clip' is not recommended " + "and may be deprecated in future! " + "We recommend a new strategy: set 'grad_clip' " + "when initializing the 'optimizer'. " + "This method can reduce the mistakes, please " + "refer to documention of 'optimizer'.") + + if not isinstance(clip, ClipGradBase): + raise TypeError( + "'clip' should be an instance of ClipGradBase's derived class") + if program is None: + program = framework.default_main_program() + + for op in program.block(0).ops: + if 'op_namescope' in op.all_attrs() and "optimizer" in op.attr( + "op_namescope"): + warnings.warn( + "'minimize' has been invoked before, this will make 'set_gradient_clip' " + "be ineffective! Please invoke 'set_gradient_clip' before 'minimize'." + ) + break + + if param_list is None: + param_list = program.block(0).all_parameters() + if all(isinstance(elem, six.string_types) for elem in param_list): + param_list = [program.block(0).var(elem) for elem in param_list] + if not all(isinstance(elem, framework.Parameter) for elem in param_list): + raise TypeError( + "'param_list' should be a list of Parameter or basestring(parameter's name)." + ) + + for param in param_list: + param.gradient_clip_attr = copy.deepcopy(clip) + + +def append_gradient_clip_ops(param_grads): + context = dict() + for p, g in param_grads: + if g is None: + continue + with p.block.program._optimized_guard( + [p, g]), framework.name_scope('gradient_clip'): + clip_attr = getattr(p, 'gradient_clip_attr', None) + if clip_attr is None: + return param_grads + if not isinstance(clip_attr, ClipGradBase): + raise TypeError( + "clip attribute should be an instance of GradientClipBase") + + clip_attr._process_context(context=context, param=p, grad=g) + + res = [] + param_new_grad_name_dict = dict() + for p, g in param_grads: + if g is None: + continue + with p.block.program._optimized_guard( + [p, g]), framework.name_scope('gradient_clip'): + param, new_grad = clip_attr._create_operators(param=p, grad=g) + param_new_grad_name_dict[param.name] = new_grad.name + res.append([param, new_grad]) + + _correct_clip_op_role_var(res, param_new_grad_name_dict) + return res + + +# change wrong mapping relation between param & grad in clip op +# Note: This function is sensitive to the time cost of the network with gradient clipping +# and should not be changed easily. If you must change, please test the time cost. +def _correct_clip_op_role_var(params_grads, param_new_grad_name_dict): + block_id_list = [] + if len(param_new_grad_name_dict) == 0: + return + for param, grad in params_grads: + if grad is None: + continue + block_id = param.block.idx + if block_id in block_id_list: + continue + block_id_list.append(block_id) + for op in param.block.program.global_block().ops: + if op.has_attr("op_namescope") and "gradient_clip" in op.attr( + "op_namescope") and op.attr('op_role_var'): + param_name = op.attr('op_role_var')[0] + if param_name in param_new_grad_name_dict: + correct_p_g = [ + param_name, param_new_grad_name_dict[param_name] + ] + op._set_attr('op_role_var', correct_p_g) + + +GradientClipBase = ClipGradBase +GradientClipByValue = ClipGradByValue +GradientClipByNorm = ClipGradByNorm +GradientClipByGlobalNorm = ClipGradByGlobalNorm diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/communicator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/communicator.py new file mode 100644 index 0000000000000000000000000000000000000000..4704628f2aee8a719ea4409346bd106087a11c74 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/communicator.py @@ -0,0 +1,264 @@ +# 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. + +# 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. + +from .executor import global_scope +""" +Communicator is used for async distribute training in distribute_transpiler mode. +It's a wrapper of a cpp class Communicator and should be used inside fleet API. +""" +from . import core +from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode + +__all__ = ['Communicator', 'FLCommunicator', 'LargeScaleKV'] + + +class Communicator(object): + + def __init__(self, mode, kwargs=None, envs=None): + """ + Communicator is used for async distribute training in distribute_transpiler mode. + It's a wrapper of a cpp class Communicator and should be used inside fleet API. + + Args: + program(Program): the trainers program after transpile of distribute_transpiler. + It's used by communicator to extract the information to do communication. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + prog = fluid.Program() + comm = fluid.communicator.Communicator(prog) + comm.start() + comm.stop() + """ + # set all recv op to not_run mode + + if kwargs == None: + if envs == None: + envs = {} + else: + if mode == DistributedMode.SYNC: + envs["pserver_endpoints"] = ','.join( + kwargs["pserver_endpoints"]) + + envs["trainers"] = str(kwargs["trainers"]) + envs["trainer_id"] = str(kwargs["trainer_id"]) + envs["need_global_step"] = str(kwargs["need_global_step"]) + envs["barrier_table_id"] = str(kwargs["barrier_table_id"]) + + mode_str = None + + if mode == DistributedMode.SYNC: + mode_str = "SYNC" + elif mode == DistributedMode.ASYNC: + mode_str = "ASYNC" + elif mode == DistributedMode.HALF_ASYNC: + mode_str = "HALF_ASYNC" + elif mode == DistributedMode.GEO: + mode_str = "GEO" + + self.mode = mode_str + self.envs = envs + self.communicator_ = None + self.send_ctx_ = None + self.recv_ctx_ = None + + def init_with_ctx(self, + send_ctx, + recv_ctx, + proto_txt, + unit64_hosts, + scope=None): + if scope == None: + scope = global_scope() + self.communicator_ = core.DistCommunicator(self.mode, proto_txt, + unit64_hosts, send_ctx, + recv_ctx, scope, self.envs) + self.send_ctx_ = send_ctx + self.recv_ctx_ = recv_ctx + + def create_client_to_client_connection(self, + pserver_timeout_ms=500000, + pserver_connect_timeout_ms=10000, + max_retry=3): + self.communicator_.create_client_to_client_connection( + pserver_timeout_ms, pserver_connect_timeout_ms, max_retry) + + def get_client_info(self): + return self.communicator_.get_client_info() + + def set_clients(self, host_list): + self.communicator_.set_clients(host_list) + + def start(self): + """ + Start communicator. Should call before training process. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + prog = fluid.Program() + comm = fluid.communicator.Communicator(prog) + comm.start() + comm.stop() + """ + if self.communicator_ == None: + print('you must call init_with_ctx first to init comm before start') + return + self.communicator_.start() + + def stop(self): + """ + Stop communicator. Should call after training process. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + prog = fluid.Program() + comm = fluid.communicator.Communicator(prog) + comm.start() + comm.stop() + """ + if self.communicator_ == None: + print('you must call init_with_ctx first to init comm before stop') + return + self.communicator_.stop() + + def is_running(self): + """ + Get communicator is running or stop. + + Returns: + bool + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + prog = fluid.Program() + comm = fluid.communicator.Communicator(prog) + comm.is_running() + """ + if self.communicator_ == None: + print('you must call init_with_ctx first to init comm before stop') + return + self.communicator_.is_running() + + def recv(self): + self.communicator_.recv() + + def init_params(self, context): + self.communicator_.init_params(context) + + def pull_dense(self, context): + self.communicator_.pull_dense(context) + + def push_sparse_param(self, var_name, table_id=-1, scope=None): + if scope == None: + scope = global_scope() + if not self.is_running(): + raise ValueError( + "Communicator should init first. Using fleet.init_worker() before push_sparse_param()" + ) + assert isinstance(var_name, str) + assert isinstance(table_id, int) + if table_id == -1: + table_id = self.send_ctx_[var_name].table_id() + self.communicator_.push_sparse_param(var_name, table_id, scope) + + +class FLCommunicator(Communicator): ## only for coordinator + + def __init__(self, ps_hosts, kwargs=None): + mode = None + super(FLCommunicator, self).__init__(mode, kwargs) + send_ctx = {} + dense_map = {} + prototxt = "" + self.mode = "WITH_COORDINATOR" + self.init_with_ctx(send_ctx, dense_map, prototxt, ps_hosts) + + def start_coordinator(self, self_endpoint, trainer_endpoints): + if self.communicator_ != None: + self.communicator_.start_coordinator(self_endpoint, + trainer_endpoints) + return + + def save_fl_strategy(self, mp): + if self.communicator_ != None: + self.communicator_.save_fl_strategy(mp) + else: + raise ValueError("self.communicator_ is null") + return + + def query_fl_clients_info(self): + info_mp = {} + if self.communicator_ != None: + info_mp = self.communicator_.query_fl_clients_info() + return info_mp + + +class LargeScaleKV(object): + + def __init__(self): + self.scale_kv = core.LargeScaleKV() + + def save(self, varname, dirname): + self.scale_kv.save(varname, dirname) + + def load(self, varname, dirname): + self.scale_kv.load(varname, dirname) + + def size(self, varname): + return self.scale_kv.size(varname) + + +class HeterClient(object): + + def __init__(self, endpoint, previous_endpoint, trainer_id): + self.heter_client_ = core.HeterClient(endpoint, previous_endpoint, + trainer_id) + + def stop(self): + self.heter_client_.stop() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/compiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..1f81afbed64d79421feba58b45d252a64272a3af --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/compiler.py @@ -0,0 +1,1356 @@ +# Copyright (c) 2018 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. + +import multiprocessing +import os +import six +import sys +import warnings +from .. import compat as cpt +from . import framework +from .framework import _get_paddle_place, _get_paddle_place_list +from .framework import cuda_places, cpu_places, xpu_places +from . import core + +__all__ = [ + 'CompiledProgram', 'ExecutionStrategy', 'BuildStrategy', + 'IpuCompiledProgram', 'IpuStrategy' +] + +ExecutionStrategy = core.ParallelExecutor.ExecutionStrategy +BuildStrategy = core.ParallelExecutor.BuildStrategy +InferNativeConfig = core.NativeConfig +InferAnalysisConfig = core.AnalysisConfig +DeviceType = core.DeviceType + + +def _place_obj(place): + p = core.Place() + p.set_place(place) + return p + + +def _is_pserver_mode(main_program): + main = main_program if main_program \ + else framework.default_main_program() + for op in main.global_block().ops: + if op.type in ["send", "recv"]: + return True + return False + + +def _has_backward_op(graph): + for node in graph.nodes(): + if node.is_op() and node.op() is not None and \ + node.op().type().endswith("_grad"): + return True + return False + + +def _prune_feed_ops(program): + # prune the feed ops in the program. + pop_idx = [] + for i, op in enumerate(program.global_block().ops): + if op.type == "feed": pop_idx.append(i) + for index in pop_idx[::-1]: + program.global_block()._remove_op(index) + + +def _has_optimize_op(block): + for op in block.ops: + op_maker = core.op_proto_and_checker_maker + optimize = core.op_proto_and_checker_maker.OpRole.Optimize + if op_maker.kOpRoleVarAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(optimize): + return True + return False + + +def _has_optimizer_in_control_flow(program): + if not program: + program = framework.default_main_program() + for op in program.global_block().ops: + if op.type == "conditional_block_grad": + sub_block = program.block(op._block_attr_id("sub_block")) + if _has_optimize_op(sub_block): + return True + + return False + + +def _should_broadcast_or_not_exists(program, var_name): + block = program.global_block() + var = block.vars.get(var_name, None) + if var is None: + return True + is_distributed = getattr(var, '_is_distributed', False) or getattr( + var, 'is_distributed', False) + return not is_distributed + + +class CompiledProgram(object): + """ + :api_attr: Static Graph + + The CompiledProgram is used to transform a program or graph for + various optimizations according to the configuration of build_strategy, + for example, the operators' fusion in the computation graph, memory + optimization during the execution of the computation graph, etc. + For more information about build_strategy, please refer to + :code:`paddle.static.BuildStrategy`. + + Args: + program_or_graph (Graph|Program): This argument is the Program or Graph + being executed. + build_strategy(BuildStrategy): This argument is used to compile the + program or graph with the specified options, such as operators' fusion + in the computational graph and memory optimization during the execution + of the computational graph. For more information about build_strategy, + please refer to :code:`paddle.static.BuildStrategy`. The default is None. + + Returns: + CompiledProgram + + Example: + .. code-block:: python + + import numpy + import paddle + import paddle.static as static + + paddle.enable_static() + + place = paddle.CUDAPlace(0) # paddle.CPUPlace() + exe = static.Executor(place) + + data = static.data(name='X', shape=[None, 1], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + loss = paddle.mean(hidden) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + exe.run(static.default_startup_program()) + compiled_prog = static.CompiledProgram( + static.default_main_program()) + + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = exe.run(compiled_prog, + feed={"X": x}, + fetch_list=[loss.name]) + """ + + def __init__(self, program_or_graph, build_strategy=None): + if isinstance(program_or_graph, core.Graph): + self._graph = program_or_graph + # don't not create a new program here. + self._program = None + elif isinstance(program_or_graph, framework.Program): + _prune_feed_ops(program_or_graph) + self._graph = core.Graph(program_or_graph.desc) + self._program = program_or_graph + else: + raise TypeError( + "The type of program_to_graph parameter is wrong, expected Graph or Program, but received %s" + % type(program_or_graph)) + + self._scope = None + self._place = None + self._executor = None + self._compiled = False + self._is_data_parallel = False + self._is_inference = False + self._loss_name = None + self._share_vars_from = None + self._places = None + self._build_strategy = build_strategy + self._exec_strategy = None + + def with_data_parallel(self, + loss_name=None, + build_strategy=None, + exec_strategy=None, + share_vars_from=None, + places=None): + """ + This interface is used to transform the input Program or Graph to a multi-graph + to run the model in data parallel mode. Users can use the build_strategy and + exec_strategy to set some optimizations that can be applied during the construction + and computation of the Graph, such as reducing the number of AllReduce operations, + specifying the size of the thread pool used in the computation Graph running the model, + and so on. + + .. note:: + If build_strategy is specified when building CompiledProgram and calling + with_data_parallel, build_strategy in CompiledProgram will be overwritten, therefore, + if it is data parallel training, it is recommended to set build_strategy when calling + with_data_parallel interface. + + Args: + loss_name (str): This parameter is the name of the loss Tensor of the model. + **Note: If it is model training, you must set loss_name, otherwise the + result may be problematic**. The default is None. + build_strategy(BuildStrategy): This parameter is used to compile the + program or graph with the specified options, such as operators' fusion + in the computational graph and memory optimization during the execution + of the computational graph. For more information about build_strategy, + please refer to :code:`fluid.BuildStrategy`. The default is None. + exec_strategy(ExecutionStrategy): exec_strategy specifies the options that can + be changed when running the current model, such as the thread pool size. + For more information about exec_strategy, please refer to :code:`fluid.ExecutionStrategy`. + The default is None. + share_vars_from(CompiledProgram): If share_vars_from is set, the current + CompiledProgram will share the parameter value with the CompiledProgram + specified by share_vars_from. This parameter needs to be set when model testing + is required during model training, and the data parallel mode is used for + training and testing. Since CompiledProgram will only distribute parameter + Tensors to other devices when it is first executed, the CompiledProgram + specified by share_vars_from must be run before the current CompiledProgram. + The default is None. + places(list(CUDAPlace)|list(CPUPlace)|list(str)|None): This parameter specifies the device + on which the model is running. If you want to run on GPU0 and GPU1, places are + [fluid.CUDAPlace(0), fluid.CUDAPlace(1)]; if you want to run with 2 CPUs, places are + [fluid.CPUPlace()] * 2. If the parameter is not set, i.e. the parameter is None, + the available device will be obtained from the environment variable when the model + is executed: If the GPU is used, the currently available device ID is obtained + from the environment variable FLAGS_selected_gpus or CUDA_VISIBLE_DEVICES when + the model is executed; CPU, when the model is executed, the currently available + CPU number is obtained from the environment variable CPU_NUM. For example, + export CPU_NUM=4, if the environment variable is not set, the executor will + add the variable to the environment variable and set its value to 1. + The default is None. If ``places`` is the list of string, the string in the list + can be ``cpu``, ``gpu:x``, where ``x`` is the index of the GPUs. + + Returns: + CompiledProgram + + Example: + .. code-block:: python + + import numpy + import os + import paddle + import paddle.static as static + + paddle.enable_static() + + use_cuda = True + place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() + parallel_places = [paddle.CUDAPlace(0), paddle.CUDAPlace(1)] if use_cuda else [paddle.CPUPlace()] * 2 + + # NOTE: If you use CPU to run the program, you need + # to specify the CPU_NUM, otherwise, paddle will use + # all the number of the logic core as the CPU_NUM, + # in that case, the batch size of the input should be + # greater than CPU_NUM, if not, the process will be + # failed by an exception. + if not use_cuda: + os.environ['CPU_NUM'] = str(2) + + exe = static.Executor(place) + + data = static.data(name='X', shape=[None, 1], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + loss = paddle.mean(hidden) + + test_program = static.default_main_program().clone(for_test=True) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + exe.run(static.default_startup_program()) + compiled_train_prog = static.CompiledProgram( + static.default_main_program()).with_data_parallel( + loss_name=loss.name, places=parallel_places) + # NOTE: if not set share_vars_from=compiled_train_prog, + # the parameters used in test process are different with + # the parameters used by train process + compiled_test_prog = static.CompiledProgram( + test_program).with_data_parallel( + share_vars_from=compiled_train_prog, + places=parallel_places) + + train_data = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = exe.run(compiled_train_prog, + feed={"X": train_data}, + fetch_list=[loss.name]) + test_data = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = exe.run(compiled_test_prog, + feed={"X": test_data}, + fetch_list=[loss.name]) + """ + assert not self._is_data_parallel, "Already compiled with parallel, cannot be recompiled." + assert not self._is_inference, "Cannot compile with both data parallel and inference." + self._is_data_parallel = True + # FIXME(zcd): Currently, the build_strategy can be set during creating + # CompiledProgram or calling with_data_parallel, and it may be confusing, + # but in the long run, we should set up build_strategy only when creating + # CompiledProgram, and exec_strategy should be deprecated. + if build_strategy is not None: self._build_strategy = build_strategy + self._exec_strategy = exec_strategy + self._loss_name = loss_name + self._share_vars_from = share_vars_from + if isinstance(places, (list, tuple)): + self._places = _get_paddle_place_list(places) + else: + self._places = _get_paddle_place(places) + + if _has_backward_op(self._graph): + assert self._loss_name is not None, "The loss name of CompiledProgram is None. The loss name should be set if CompiledProgram contains backward part." + + if self._places is not None: + if not isinstance(self._places, (list, tuple)): + self._places = [self._places] + + return self + + def _with_inference_optimize(self, config): + """ Add inference optimize + + Args: + config: instance of `NativeConfig` or `AnalysisConfig` to create predictor + Returns: + self + """ + assert not self._is_data_parallel, "Cannot compile with both data parallel and inference" + assert not self._is_inference, "Already compiled with inference, cannot be recompiled." + + assert any([ + isinstance(config, InferNativeConfig), + isinstance(config, InferAnalysisConfig) + ]) + self._is_inference = True + self._infer_config = config + return self + + def _with_distributed(self): + raise NotImplementedError( + "Subclass of CompiledProgram should implement _with_distributed method." + ) + + def _compile_data_parallel(self, places, use_device, scope=None): + if self._share_vars_from: + if scope: + sys.stderr.write("share_vars_from is set, scope is ignored.\n") + if not self._share_vars_from._is_data_parallel: + raise ValueError( + "The shared Program is not data parallel, cannot " + "share variables from it.") + if self._share_vars_from._executor is None: + raise ValueError( + "The shared Program is not compiled and executed, so there is no " + "variables to share.") + self._local_scopes = self._share_vars_from._executor.local_scopes() + else: + assert scope is not None, "" + self._local_scopes = [] + + assert isinstance(places, tuple) or isinstance(places, list), \ + "Currently , The places type can only be list or tuple, but the input type is {}.".format(type(places)) + + if self._build_strategy is None: + self._build_strategy = BuildStrategy() + self._build_strategy.is_distribution = _is_pserver_mode(self._program) + + if self._exec_strategy is None: + self._exec_strategy = ExecutionStrategy() + self._exec_strategy._use_device = use_device + + if self._exec_strategy.num_threads == 0: + if self._exec_strategy._use_device == DeviceType.CUDA: + # Experiments on se-resnext shows that too many threads hurt + # performance. Worth tunning for other models in the future. + self._exec_strategy.num_threads = len(places) * 4 + elif self._exec_strategy._use_device == DeviceType.XPU: + # Currently only single thread is supported in Kunlun XPU. + self._exec_strategy.num_threads = 1 + else: + self._exec_strategy.num_threads = len(places) * 2 + + if "FLAGS_use_cinn" in core.globals() and core.globals( + )["FLAGS_use_cinn"] and self._exec_strategy.num_threads != 1: + warnings.warn("At present, when CINN is turned on, each process can " \ + "only contain one thread, so reset the number of threads to 1 here.") + self._exec_strategy.num_threads = 1 + + if self._build_strategy.num_trainers > 1: + assert self._is_data_parallel, \ + "If you use multi-trainer to train the model, you should use "\ + "the data parallel model, i.e. calling with_data_parallel function." + + # TODO(wuyi): trainer endpoings should be passed in through + # build_strategy, not program.xxx. + # TODO(gongwb): let user to set them once. + if self._program and self._build_strategy.num_trainers > 1 and \ + self._program._trainers_endpoints: + tps = self._program._trainers_endpoints + + assert self._build_strategy.num_trainers == len( + tps), "The trainer numbers is not equal to endpoint numbers." + self._build_strategy.trainers_endpoints = tps + + if self._program: + self._build_strategy.nccl_comm_num = self._program._nccl_comm_num + self._build_strategy.use_hierarchical_allreduce = self._program._use_hierarchical_allreduce + self._build_strategy.hierarchical_allreduce_inter_nranks = self._program._hierarchical_allreduce_inter_nranks + + if self._build_strategy.sync_batch_norm: + self._build_strategy.enable_sequential_execution = True + + if self._program is not None and self._program._enable_dgc: + assert self._exec_strategy._use_device == DeviceType.CUDA, "DGC only used under CUDA environment." + assert self._build_strategy.num_trainers * len( + places) > 1, "DGC is not avaliable for single card training." + assert self._build_strategy.reduce_strategy == BuildStrategy.ReduceStrategy.AllReduce, "DGC \ + only can be used for AllReduce BuildStrategy." + + # DGC doesn't support fuse for now, close fuse. + self._build_strategy.fuse_all_reduce_ops = False + + self._persistable_vars = [] + for node in self._graph.nodes(): + if node.is_var() and node.var() is not None and node.var().persistable() and \ + node.var().type() != core.VarDesc.VarType.RAW: + name = cpt.to_text(node.name()) + if self._program is not None and _should_broadcast_or_not_exists( + self._program, name): + self._persistable_vars.append(cpt.to_text(node.name())) + + places = list(map(_place_obj, places)) + + # ParallelExecutor would broadcast all the parameters during initializing. + # The parameters of each process should be in the same ordered for the data-parallelism + # distributed training to keep the broadcast correct. + self._persistable_vars = list(set(self._persistable_vars)) + self._persistable_vars.sort() + + return core.ParallelExecutor( + places, self._persistable_vars, + cpt.to_text(self._loss_name) if self._loss_name else six.u(''), + self._scope, self._local_scopes, self._exec_strategy, + self._build_strategy, self._graph) + + def _compile_inference(self): + return core.create_paddle_predictor(self._infer_config) + + def _compile(self, scope, place): + """Compile the program based on the configs. + + Args: + scope: The variables (resources) that are associated with + this compiled program. + place: The location that the compiled program will be run on. + + Returns: + self + """ + if self._compiled: + if scope and self._scope != scope: + raise ValueError("Cannot compile program with different scope.") + if place and not self._place._equals(place): + raise ValueError("Cannot compile program with different place.") + return self + self._compiled = True + + self._scope = scope + self._place = place + + if self._is_inference: + self._executor = self._compile_inference() + else: + if self._is_data_parallel: + self._places = self._get_places(self._place, self._places) + else: + self._places = [self._place] + + # Todo(liym27):If optimizer is used in control flow, + # training on multi-places is not supported now, will + # be supported later. + if len(self._places) > 1 and \ + _has_optimizer_in_control_flow(self._program): + raise NotImplementedError( + "If optimizer is used in control flow, " + "training on multi-places is not supported now.") + if isinstance(self._place, core.CUDAPlace): + use_device = DeviceType.CUDA + elif isinstance(self._place, core.XPUPlace): + use_device = DeviceType.XPU + else: + use_device = DeviceType.CPU + self._executor = self._compile_data_parallel(use_device=use_device, + scope=self._scope, + places=self._places) + return self + + def _get_places(self, place, place_list): + has_set_place = (place_list is not None) + if has_set_place: + for p in place_list: + assert p._type() == place._type(), \ + "Place type not match. You may set wrong type of places." + else: + if isinstance(place, core.CUDAPlace): + place_list = cuda_places() + elif isinstance(place, core.XPUPlace): + place_list = xpu_places() + else: + place_list = cpu_places() + assert place_list, "No places for execution." + return place_list + + +class IpuDynamicPatcher(object): + """ + Patcher for IPU dynamic2static support. + """ + + patcher_cache = [] + + def __init__(self): + pass + + @staticmethod + def convert_concrete_program(ipu_strategy, + concrete_program, + class_instance=None): + """ + Convert the ConcreteProgram to IPUConcreteProgram. + """ + from ..fluid.dygraph.base import switch_to_static_graph + from ..fluid import backward + from ..fluid.initializer import Constant + from ..fluid.framework import device_guard + import paddle + + inputs = concrete_program.inputs + outputs = concrete_program.outputs + startup_program = concrete_program.startup_program + + scope = paddle.static.global_scope() + + @switch_to_static_graph + def append_backward_desc(): + program = concrete_program.main_program + + # backward with optimizer to add backward graph to program + backward.gradients_with_optimizer(program, ipu_strategy._optimizer) + + # initialize backward parameters + exe = paddle.static.Executor(paddle.CPUPlace()) + startup_program = paddle.static.default_startup_program() + exe.run(startup_program) + + return program + + if ipu_strategy.enable_fp16: + class_instance.to(dtype="float16") + + # copy the bias and filters + for param_or_buffer in concrete_program.parameters: + param_or_buffer_tensor = scope.var( + param_or_buffer.name).get_tensor() + src_tensor = param_or_buffer.value().get_tensor() + param_or_buffer_tensor._share_data_with(src_tensor) + + # TODO(czr): feed and fetch list needs to consider more type + if class_instance: + feed_list = [elem.name for elem in inputs[1:] if elem is not None] + else: + feed_list = [elem.name for elem in inputs if elem is not None] + fetch_list = [elem.name for elem in outputs] + + if ipu_strategy.is_training: + concrete_program.main_program = append_backward_desc() + # copy optimizer parameters + optimizer = ipu_strategy._optimizer + for k, v in optimizer._accumulators.items(): + for param_name, var_tmp in v.items(): + var = optimizer.helper.create_global_variable( + name=var_tmp.name, + persistable=True, + dtype=var_tmp.dtype, + type=var_tmp.type, + shape=var_tmp.shape, + belong_to_optimizer=True) + device = optimizer._get_device_for_param(param_name) + with device_guard(device): + optimizer.helper.set_variable_initializer( + var, initializer=Constant(value=0.0)) + param_or_lr_tensor = scope.find_var( + var_tmp.name).get_tensor() + optim_tensor = var.value().get_tensor() + param_or_lr_tensor._share_data_with(optim_tensor) + optimizer._accumulators[k][param_name] = var + + @switch_to_static_graph + def func_compile(): + if ipu_strategy.enable_fp16: + amp_list = paddle.static.amp.CustomOpLists() + amp_list.unsupported_list = {"cumsum"} + to_fp16_var_names = paddle.static.amp.cast_model_to_fp16( + concrete_program.main_program, + amp_list, + use_fp16_guard=False) + paddle.static.amp.cast_parameters_to_fp16( + paddle.CPUPlace(), + concrete_program.main_program, + to_fp16_var_names=to_fp16_var_names) + + program = IpuCompiledProgram(concrete_program.main_program, + ipu_strategy=ipu_strategy, + scope=scope).compile( + feed_list, fetch_list) + return program + + main_program = func_compile() + concrete_program.main_program = main_program + return concrete_program + + @staticmethod + def patch_program_cache(ipu_strategy): + """ Monkey patch ProgramCache discriptor to support dynamic2static in IPU. + + Args: + ipu_strategy: The ipu_strategy used in dynamic graph. + + Returns: + None + """ + from ..fluid.dygraph.dygraph_to_static.program_translator import ProgramCache + from ..fluid.dygraph.dygraph_to_static.program_translator import CacheKey + from ..fluid.dygraph.dygraph_to_static import logging_utils + from ..fluid.dygraph.dygraph_to_static.program_translator import MAX_TRACED_PROGRAM_COUNT + from ..fluid.dygraph.dygraph_to_static.partial_program import partial_program_from + + old_getter = ProgramCache.__getitem__ + + def patch_getter(self, item): + if not isinstance(item, CacheKey): + raise ValueError( + 'type(item) should be CacheKey, but received %s' % + type(item).__name__) + item_id = hash(item) + self._recent_key = item_id + if item_id not in self._caches or ipu_strategy.need_compile: + if item_id in self._caches: + logging_utils.warn( + "ipu_strategy chances detected. Please sync weights.") + if self._caches and not ipu_strategy.need_compile: + logging_utils.warn( + "dynamic2static on IPU doesn't support mutiple caches. Please make sure" + "dynamic inputs is not used.") + concrete_program, _ = self._build_once(item) + concrete_program = IpuDynamicPatcher.convert_concrete_program( + ipu_strategy, concrete_program, item.class_instance) + + self._caches[item_id] = (concrete_program, + partial_program_from(concrete_program)) + # Note: raise warnings if number of traced program is more than `max_tracing_count` + current_tracing_count = len(self._caches) + if current_tracing_count > MAX_TRACED_PROGRAM_COUNT: + logging_utils.warn( + "Current traced program number: {} > `max_tracing_count`:{}. Too much cached programs will bring expensive overhead. " + "The reason may be: (1) passing tensors with different shapes, (2) passing python objects instead of tensors." + .format(current_tracing_count, + MAX_TRACED_PROGRAM_COUNT)) + + return self._caches[item_id] + + setattr(ProgramCache, '__getitem__', patch_getter) + IpuDynamicPatcher.patcher_cache.append( + [ProgramCache, '__getitem__', old_getter]) + + @staticmethod + def patch_lr_scheduler(ipu_strategy): + from paddle.optimizer.lr import LRScheduler + # For IPU dynamic graph usage, lr_var is not synced in executor as static mode do. + # Manually set lr to ipu_strategy to update the lr. + old_step = LRScheduler.step + + def patch_step(self, epoch=None): + old_step(self, epoch) + ipu_strategy.set_options({"lr": self.last_lr}) + + setattr(LRScheduler, 'step', patch_step) + IpuDynamicPatcher.patcher_cache.append([LRScheduler, 'step', old_step]) + + @staticmethod + def register_patch(ipu_strategy): + IpuDynamicPatcher.patch_program_cache(ipu_strategy) + IpuDynamicPatcher.patch_lr_scheduler(ipu_strategy) + + @staticmethod + def release_patch(): + for module, key, attr in IpuDynamicPatcher.patcher_cache: + setattr(module, key, attr) + + +class IpuStrategy(object): + """ + Help users precisely control the graph building in :code:`paddle.static.IpuCompiledProgram` . + + Returns: + The IpuStrategy instance. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + """ + + def __init__(self): + if core.is_compiled_with_ipu(): + self._ipu_strategy = core.IpuStrategy() + default_options = { + 'location_optimizer': { + 'on_chip': 0, + 'use_replicated_tensor_sharding': 1, + }, # set optimizer location + 'accumulation_and_replication_reduction_type': + 1, # popart::ReductionType::Mean + 'mean_accumulation_and_replication_reduction_strategy': + 1, # popart::MeanReductionStrategy::Post + } + self._ipu_strategy.set_options(default_options) + self.has_custom_ops = False + self.custom_op_names = [] + self.need_compile = True + else: + raise RuntimeError( + "Can not use IpuStrategy in non IPU compiled environment, please re-compile with WITH_IPU=ON." + ) + from paddle import in_dynamic_mode + if in_dynamic_mode(): + self.register_patch() + + def register_patch(self): + """ + Register patchs function to support dynamic to static on IPU. This operation would break the dy2static functionality on CPU. + Use `release_patch` to release the patch. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + ipu_strategy = static.IpuStrategy() + + ipu_strategy.register_patch() + """ + IpuDynamicPatcher.register_patch(self) + + def release_patch(self): + """ + Release the registered IPU functions. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + ipu_strategy = static.IpuStrategy() + + ipu_strategy.release_patch() + """ + IpuDynamicPatcher.release_patch() + + def set_optimizer(self, optimizer): + """ + Set optimizer to ipu_strategy in dynamic mode. + + Args: + optimizer (Optimizer): Optimizer to be used in training. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + linear = paddle.nn.Linear(10, 10) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, + parameters=linear.parameters()) + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_optimizer(optimizer) + """ + from paddle import in_dynamic_mode + if in_dynamic_mode(): + self._optimizer = optimizer + optimizer_attrs = self.parse_optimizer(optimizer) + self._ipu_strategy.set_options(optimizer_attrs) + else: + raise RuntimeError("Only needs to set optimizer in dynamic mode.") + + def parse_optimizer(self, optimizer): + """ + Parse optimizer attributes for IPU dynamic to static support. Currently only support parse lr. + + Args: + optimizer (Optimizer): Optimizer to be parsed. + + Returns: + Dict. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + linear = paddle.nn.Linear(10, 10) + optimizer = paddle.optimizer.SGD(learning_rate=0.01, + parameters=linear.parameters()) + ipu_strategy = static.IpuStrategy() + attrs = ipu_strategy.parse_optimizer(optimizer) + """ + + def get_lr(): + from paddle.optimizer.lr import LRScheduler + if isinstance(optimizer._learning_rate, float): + return {"lr": optimizer._learning_rate} + elif isinstance(optimizer._learning_rate, LRScheduler): + return {"lr": optimizer._learning_rate()} + + attr_fn = [get_lr] + optimizer_attrs = {"is_dynamic": True} + for fn in attr_fn: + optimizer_attrs.update(fn()) + return optimizer_attrs + + def set_graph_config(self, + num_ipus=1, + is_training=True, + micro_batch_size=1, + enable_manual_shard=False): + """ + Set graph configuration to the IpuStrategy instance. + + Args: + num_ipus (int, optional): Number of IPU devices. Default 1, which means only use 1 IPU. + is_training (bool, optional): True is training graph, False is inference graph. Default True, which means is training mode. + batch_size (int, optional): The batch-size in the graph. Used to make the graph batch-size fixed, + if the batch-size in the graph is dynamic. Default 1, which means the batch-size would be set 1, if the batch-size is dynamice. + enable_manual_shard (bool, optional): Enable graph sharding or not. Only if num_ipus > 1, enable_manual_shard is able to be set True. + Default False, which means disabled. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_graph_config(num_ipus=1, + is_training=True, + micro_batch_size=1, + enable_manual_shard=False) + """ + if num_ipus == 1 and enable_manual_shard: + raise RuntimeError( + "Only if num_ipus > 1, enable_manual_shard is able to be set True." + ) + options = { + 'num_ipus': num_ipus, + 'is_training': is_training, + 'micro_batch_size': micro_batch_size, + 'enable_manual_shard': enable_manual_shard, + } + self.set_options(options) + + def set_pipelining_config(self, + enable_pipelining=False, + batches_per_step=1, + enable_gradient_accumulation=False, + accumulation_factor=1): + """ + Set pipelining configuration to the IpuStrategy instance. Used to optimize the throughput performance. + + Args: + enable_pipelining (bool, optional): Enable data pipelining between subgraphs. Only if enable_manual_shard=True, enable_pipelining is able to be set True. + Default False, which means disabled. + batches_per_step (int, optional): Set the batches per run in data pipelining mode. Only if enable_pipelining=True, batches_per_step is able to be set > 1. + Default 1, which means no data pipelining. + enable_gradient_accumulation (bool, optional): Enable to accumulate gradients before updating the weights in training mode. Only if enable_pipelining=True, + enable_gradient_accumulation is able to be set True. Default False, which means no gradient accumulation. + accumulation_factor (int, optional): Specify the number of micro-batches to accumulate + before applying the varUpdate. Default 1, which means disable the accumulation. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_pipelining_config(enable_pipelining=False, + batches_per_step=1, + enable_gradient_accumulation=False, + accumulation_factor=1) + """ + enable_manual_shard = self.get_option('enable_manual_shard') + if not enable_manual_shard and enable_pipelining: + raise RuntimeError( + "Only if enable_manual_shard=True, enable_pipelining is able to be set True." + ) + options = { + 'enable_pipelining': enable_pipelining, + 'batches_per_step': batches_per_step, + 'enable_gradient_accumulation': enable_gradient_accumulation, + 'accumulation_factor': accumulation_factor, + } + self.set_options(options) + + def set_precision_config(self, enable_fp16=False): + """ + Set half computation configuration to the IpuStrategy instance. Used to optimize the performance. + + Args: + enable_fp16 (bool, optional): Enable FLOAT16 mode and transform FLOAT32 to FLOAT16. Default False, which means disable FLOAT16 mode. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_precision_config(enable_fp16=False) + """ + options = { + 'enable_fp16': enable_fp16, + } + self.set_options(options) + + def add_custom_op(self, + paddle_op, + popart_op=None, + domain='custom.ops', + version=1): + """ + Add a mapping to use popart custom ops running on the IPU. + + Args: + paddle_op(str): the name of custom op in paddle. + + popart_op(str): the name of custom op in popart. + + domain(str): domain name of custom op in popart. + + version(int): version of custom op in popart. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.add_custom_op('paddle_relu', 'popart_relu') + """ + if popart_op is None: + popart_op = paddle_op + custom_op = { + 'paddle_op': paddle_op, + 'popart_op': popart_op, + 'domain': domain, + 'version': version, + } + self.set_options({'custom_op': custom_op}) + self.custom_op_names.append(paddle_op) + if not self.has_custom_ops: + self.has_custom_ops = True + + def set_options(self, options): + """ + Set options from dict. + + Args: + options(dict): dict of options. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + options = {'num_ipus':1, 'enable_fp16': True} + ipu_strategy.set_options(options) + """ + self._ipu_strategy.set_options(options) + # check whether to recompile program with updated ipu options. + recompile_white_list = {'lr'} + if options.keys() - recompile_white_list: + self.need_compile = True + + def get_option(self, option): + """ + Get option. + + Args: + option(str): name of option. + + Returns: + option value. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + num_ipus = ipu_strategy.get_option('num_ipus') + """ + return self._ipu_strategy.get_option(option)['value'] + + def enable_pattern(self, pattern): + """ + Enable PopART pattern to optimize the graph. + + Args: + pattern(string): the name of the pattern. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.enable_pattern("ViewSimplifyPattern") + """ + self._ipu_strategy.enable_pattern(pattern) + + def disable_pattern(self, pattern): + """ + Disable PopART pattern. + + Args: + pattern(string): the name of the pattern. + + Returns: + None. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.disable_pattern("ViewSimplifyPattern") + """ + self._ipu_strategy.disable_pattern(pattern) + + @property + def num_ipus(self): + """ + Get the number of IPU devices from IpuStrategy instance. + """ + return self.get_option('num_ipus') + + @property + def is_training(self): + """ + Get the boolean of training or inference from IpuStrategy instance. + """ + return self.get_option('is_training') + + @property + def enable_pipelining(self): + """ + Get the boolean of enable pipelining or not from IpuStrategy instance. + """ + return self.get_option('enable_pipelining') + + @property + def enable_fp16(self): + """ + Get the boolean of float16 mode or not from IpuStrategy instance. + """ + return self.get_option('enable_fp16') + + +class IpuCompiledProgram(object): + """ + The IpuCompiledProgram is used to transform a program to a ipu-target program, + such as forward graph extraction, computing graph transformation, useless scale Ops clean, etc. + + Args: + program(Program, optional): This parameter represents the :code:`Program` + to be executed. Default is None, which means the program will be set to + the default program :code:`paddle.static.default_main_program()` . + scope(Scope, optional): The scope used to run this program, you can switch + it to different scope. Default is None, which means use the global + scope :code:`paddle.static.global_scope()` . + ipu_strategy(IpuStrategy, optional): This argument is used to build the program with the + specified options, such as half computation, training or inference session, the number of IPUs, etc. + Default is None, which means build the program based on the default `ipu_strategy`. + + Returns: + IpuCompiledProgram + + Example: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + a = static.data(name='data', shape=[None, 1], dtype='int32') + b = a + 1 + main_prog = static.default_main_program() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_graph_config(num_ipus=1, is_training=True, micro_batch_size=1) + ipu_strategy.set_pipelining_config(enable_pipelining=False, batches_per_step=1, enable_gradient_accumulation=False, accumulation_factor=1) + ipu_strategy.set_precision_config(enable_fp16=False) + + ipu_compiled_program = static.IpuCompiledProgram( + main_prog, + ipu_strategy=ipu_strategy) + """ + + def __init__(self, program=None, scope=None, ipu_strategy=None): + if not core.is_compiled_with_ipu(): + raise ValueError( + "Can not use this function since PaddlePaddle is not compiled with IPU" + ) + + if program is None: + program = framework.default_main_program() + + if not isinstance(program, framework.Program): + raise TypeError( + "The type of program is wrong, expected Program, but got %s" % + type(program)) + + self._program = program + self._compiled = False + + if scope is not None: + self._scope = scope + else: + # import here to avoiding confused + import paddle + self._scope = paddle.static.global_scope() + + if ipu_strategy is not None: + self._ipu_strategy = ipu_strategy + else: + self._ipu_strategy = IpuStrategy() + + if ipu_strategy.has_custom_ops: + self._custom_op_names = set(ipu_strategy.custom_op_names) + else: + self._custom_op_names = () + + self._backend = core.IpuBackend.get_instance() + + def compile(self, feed_list, fetch_list): + """ + This interface is used to compile the input Program to a program + to run the model on the ipu. + + Args: + feed_list(list): This parameter represents the input Tensors of the model. + + fetch_list(list): This parameter represents the Tensors that need to be returned + after the model. + + Returns: + Program + + Example: + .. code-block:: python + + # required: ipu + + import paddle + import paddle.static as static + + paddle.enable_static() + + a = static.data(name='data', shape=[None, 1], dtype='int32') + b = a + 1 + main_prog = static.default_main_program() + + ipu_strategy = static.IpuStrategy() + ipu_strategy.set_graph_config(num_ipus=1, is_training=True, micro_batch_size=1) + ipu_strategy.set_pipelining_config(enable_pipelining=False, batches_per_step=1, enable_gradient_accumulation=False, accumulation_factor=1) + ipu_strategy.set_precision_config(enable_fp16=False) + + program = static.IpuCompiledProgram( + main_prog, + ipu_strategy=ipu_strategy).compile([a.name], [b.name]) + """ + self._backend.set_scope(self._scope) + self._backend.set_ipu_strategy(self._ipu_strategy._ipu_strategy) + + # feed and fetch doesn't have corresponding popart op, so we rm both here + global_block = self._program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == 'feed' or op.type == 'fetch': + need_to_remove_op_index.append(i) + + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + + for var in ['feed', 'fetch']: + if global_block.has_var(var): + global_block._remove_var(var) + + self._program.desc.flush() + self._graph = core.Graph(self._program.desc) + + if self._ipu_strategy.is_training: + passes = [ + 'optimizer_extract_pass', + 'optimizer_state_align_pass', + ] + for pass_name in passes: + a_pass = core.get_pass(pass_name) + a_pass.apply(self._graph) + + passes = [ + 'forward_graph_extract_pass', + 'infer_shape_pass', + 'avg_shard_pass', + 'delete_scale_op_pass', + ] + for pass_name in passes: + a_pass = core.get_pass(pass_name) + if pass_name == 'infer_shape_pass': + a_pass.set('feed_list', feed_list) + a_pass.apply(self._graph) + + a_pass = core.get_pass('popart_canonicalization_pass') + if self._custom_op_names: + a_pass.set('custom_ops', self._custom_op_names) + a_pass.apply(self._graph) + + passes = [ + 'ipu_inplace_pass', + 'ipu_graph_builder_pass', + 'ipu_runtime_replacer_pass', + ] + for pass_name in passes: + a_pass = core.get_pass(pass_name) + a_pass.set('feed_list', feed_list) + a_pass.set('fetch_list', fetch_list) + a_pass.apply(self._graph) + + convert_pass = core.get_pass('graph_to_program_pass') + desc = core.ProgramDesc() + convert_pass.set_not_owned('program', desc) + convert_pass.apply(self._graph) + program = framework.Program._construct_from_desc(desc) + + if hasattr(self._program, 'lr_sheduler'): + # how to share var between two different block ? + lr_var_name = self._program.lr_sheduler._var_name + + program.lr_sheduler = self._program.lr_sheduler + # Program.clone will clone lr_sheduler, so i set lr_var as + # lr_sheduler attribute + global_block = self._program.global_block() + program.lr_sheduler.lr_var = global_block.vars[lr_var_name] + + # with popart, we need to support batches_per_step, what means + # the shape of feed_var and feed_tensor(maybe numpy array) will + # mismatch, so we set need_check_feed to False. Thus we can avoid + # modify logic of run. + program_global_block = program.global_block() + for feed_name in feed_list: + feed_var = program_global_block.var(feed_name) + feed_var.desc.set_need_check_feed(False) + + if not hasattr(program, 'org_program'): + program.org_program = self._program + + self._ipu_strategy.need_compile = False + + return program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64e7eb395b71238f70928c2c4d513224288b5013 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/__init__.py @@ -0,0 +1,49 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from __future__ import print_function + +from . import decoder +from .decoder import * +from . import memory_usage_calc +from .memory_usage_calc import * +from . import op_frequence +from .op_frequence import * +from . import quantize +from .quantize import * +from . import slim +from . import extend_optimizer +from .extend_optimizer import * +from . import model_stat +from .model_stat import * +from . import mixed_precision +from .mixed_precision import * +from . import layers +from .layers import * +from . import optimizer +from .optimizer import * +from . import sparsity +from .sparsity import * + +__all__ = [] +__all__ += decoder.__all__ +__all__ += memory_usage_calc.__all__ +__all__ += op_frequence.__all__ +__all__ += quantize.__all__ +__all__ += extend_optimizer.__all__ +__all__ += ['mixed_precision'] +__all__ += layers.__all__ +__all__ += optimizer.__all__ +__all__ += sparsity.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f973fd3c9af60a0c9a2ba5225a616671545436b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function + +from . import beam_search_decoder +from .beam_search_decoder import * + +__all__ = beam_search_decoder.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/beam_search_decoder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/beam_search_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..6032238910ec63034508555579413881fef232cc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/decoder/beam_search_decoder.py @@ -0,0 +1,855 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This module provides a general beam search decoder API for RNN based decoders. +The purpose of this API is to allow users to highly customize the behavior +within their RNN decoder(vanilla RNN, LSTM, attention + LSTM, future etc.), +without using the low level API such as while ops. + +This API is still under active development and may change drastically. +""" + +from __future__ import print_function + +from ...wrapped_decorator import signature_safe_contextmanager +import numpy as np +import six + +from ... import layers +from ...framework import Variable +from ... import core +from ... import framework, unique_name +from ...layer_helper import LayerHelper + +__all__ = ['InitState', 'StateCell', 'TrainingDecoder', 'BeamSearchDecoder'] + + +class _DecoderType: + TRAINING = 1 + BEAM_SEARCH = 2 + + +class InitState(object): + """ + The initial hidden state object. The state objects holds a variable, and may + use it to initialize the hidden state cell of RNN. Usually used as input to + `StateCell` class. + + Args: + init (Variable): The initial variable of the hidden state. If set None, + the variable will be created as a tensor with constant value based + on `shape` and `value` param. + shape (tuple|list): If `init` is None, new Variable's shape. Default + None. + value (float): If `init` is None, new Variable's value. Default None. + init_boot (Variable): If provided, the initial variable will be created + with the same shape as this variable. + need_reorder (bool): If set true, the init will be sorted by its lod + rank within its batches. This should be used if `batch_size > 1`. + dtype (np.dtype|core.VarDesc.VarType|str): Data type of the initial + variable. + + Returns: + An initialized state object. + + Examples: + See `StateCell`. + """ + + def __init__(self, + init=None, + shape=None, + value=0.0, + init_boot=None, + need_reorder=False, + dtype='float32'): + if init is not None: + self._init = init + elif init_boot is None: + raise ValueError( + 'init_boot must be provided to infer the shape of InitState .\n' + ) + else: + self._init = layers.fill_constant_batch_size_like(input=init_boot, + value=value, + shape=shape, + dtype=dtype) + + self._shape = shape + self._value = value + self._need_reorder = need_reorder + self._dtype = dtype + + @property + def value(self): + return self._init + + @property + def need_reorder(self): + return self._need_reorder + + +class _MemoryState(object): + + def __init__(self, state_name, rnn_obj, init_state): + self._state_name = state_name # each is a rnn.memory + self._rnn_obj = rnn_obj + self._state_mem = self._rnn_obj.memory( + init=init_state.value, need_reorder=init_state.need_reorder) + + def get_state(self): + return self._state_mem + + def update_state(self, state): + self._rnn_obj.update_memory(self._state_mem, state) + + +class _ArrayState(object): + + def __init__(self, state_name, block, init_state): + self._state_name = state_name + self._block = block + + self._state_array = self._block.create_var( + name=unique_name.generate('array_state_array'), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=init_state.value.dtype) + + self._counter = self._block.create_var( + name=unique_name.generate('array_state_counter'), + type=core.VarDesc.VarType.LOD_TENSOR, + dtype='int64') + + # initialize counter + self._block.append_op(type='fill_constant', + inputs={}, + outputs={'Out': [self._counter]}, + attrs={ + 'shape': [1], + 'dtype': self._counter.dtype, + 'value': float(0.0), + 'force_cpu': True + }) + + self._counter.stop_gradient = True + + # write initial state + block.append_op(type='write_to_array', + inputs={ + 'X': init_state.value, + 'I': self._counter + }, + outputs={'Out': self._state_array}) + + def get_state(self): + state = layers.array_read(array=self._state_array, i=self._counter) + return state + + def update_state(self, state): + layers.increment(x=self._counter, value=1, in_place=True) + layers.array_write(state, array=self._state_array, i=self._counter) + + +class StateCell(object): + """ + The state cell class stores the hidden state of the RNN cell. A typical RNN + cell has one or more hidden states, and one or more step inputs. This class + allows you to defines the name of hidden states as well as step inputs, and + their associated variables. + + Args: + inputs (dict): A feeding dict of {name(str) : Variable}. It specifies + the names of step inputs for RNN cell, and the associated variables. + The variable could initially be None and set manually during each + RNN step. + states (dict): A feeding dict of {name(str) : InitState object}. It + specifies the names of hidden states and their initialized state. + out_state (str): A string that specifies the name of hidden state that + will be used to compute the score in beam search process. + name (str): The name of the RNN cell. Default None. + + Raises: + `ValueError`: If the initial state is not an instance of InitState, or + the out_state is not in the dict of states. + + Returns: + StateCell: The initialized StateCell object. + + Examples: + .. code-block:: python + hidden_state = InitState(init=encoder_out, need_reorder=True) + state_cell = StateCell( + inputs={'current_word': None}, + states={'h': hidden_state}, + out_state='h') + """ + + def __init__(self, inputs, states, out_state, name=None): + self._helper = LayerHelper('state_cell', name=name) + self._cur_states = {} + self._state_names = [] + for state_name, state in six.iteritems(states): + if not isinstance(state, InitState): + raise ValueError('state must be an InitState object.') + self._cur_states[state_name] = state + self._state_names.append(state_name) + self._inputs = inputs # inputs is place holder here + self._cur_decoder_obj = None + self._in_decoder = False + self._states_holder = {} + self._switched_decoder = False + self._state_updater = None + self._out_state = out_state + if self._out_state not in self._cur_states: + raise ValueError('out_state must be one state in states') + + def _enter_decoder(self, decoder_obj): + if self._in_decoder == True or self._cur_decoder_obj is not None: + raise ValueError('StateCell has already entered a decoder.') + self._in_decoder = True + self._cur_decoder_obj = decoder_obj + self._switched_decoder = False + + def _leave_decoder(self, decoder_obj): + if not self._in_decoder: + raise ValueError('StateCell not in decoder, ' + 'invalid leaving operation.') + + if self._cur_decoder_obj != decoder_obj: + raise ValueError('Inconsistent decoder object in StateCell.') + + self._in_decoder = False + self._cur_decoder_obj = None + self._switched_decoder = False + + def _switch_decoder(self): # lazy switch + if not self._in_decoder: + raise ValueError('StateCell must be enter a decoder.') + + if self._switched_decoder: + raise ValueError('StateCell already done switching.') + + for state_name in self._state_names: + if state_name not in self._states_holder: + state = self._cur_states[state_name] + + if not isinstance(state, InitState): + raise ValueError('Current type of state is %s, should be ' + 'an InitState object.' % type(state)) + + self._states_holder[state_name] = {} + + if self._cur_decoder_obj.type == _DecoderType.TRAINING: + self._states_holder[state_name][id(self._cur_decoder_obj)] \ + = _MemoryState(state_name, + self._cur_decoder_obj.dynamic_rnn, + state) + elif self._cur_decoder_obj.type == _DecoderType.BEAM_SEARCH: + self._states_holder[state_name][id(self._cur_decoder_obj)] \ + = _ArrayState(state_name, + self._cur_decoder_obj._parent_block(), + state) + else: + raise ValueError('Unknown decoder type, only support ' + '[TRAINING, BEAM_SEARCH]') + + # Read back, since current state should be LoDTensor + self._cur_states[state_name] = \ + self._states_holder[state_name][ + id(self._cur_decoder_obj)].get_state() + + self._switched_decoder = True + + def get_state(self, state_name): + """ + The getter of state object. Find the state variable by its name. + + Args: + state_name (str): A string of the state's name. + + Returns: + The associated state object. + """ + if self._in_decoder and not self._switched_decoder: + self._switch_decoder() + + if state_name not in self._cur_states: + raise ValueError( + 'Unknown state %s. Please make sure _switch_decoder() ' + 'invoked.' % state_name) + + return self._cur_states[state_name] + + def get_input(self, input_name): + """ + The getter of input variable. Find the input variable by its name. + + Args: + input_name (str): The string of the input's name. + + Returns: + The associated input variable. + """ + if input_name not in self._inputs or self._inputs[input_name] is None: + raise ValueError('Invalid input %s.' % input_name) + return self._inputs[input_name] + + def set_state(self, state_name, state_value): + """ + The setter of the state variable. Change the variable of the given + `state_name`. + + Args: + state_name (str): The name of the state to change. + state_value (Var): The variable of the new state. + """ + self._cur_states[state_name] = state_value + + def state_updater(self, updater): + """ + Set up the updater to update the hidden state every RNN step. The + behavior of updater could be customized by users. The updater should be + a function that takes a `StateCell` object as input and update the + hidden state within it. The hidden state could be accessed through + `get_state` method. + + Args: + updater (func): the updater to update the state cell. + """ + self._state_updater = updater + + def _decorator(state_cell): + if state_cell == self: + raise TypeError('Updater should only accept a StateCell object ' + 'as argument.') + updater(state_cell) + + return _decorator + + def compute_state(self, inputs): + """ + Provide the step input of RNN cell, and compute the new hidden state + with updater and give step input. + + Args: + inputs (dict): A feed dict, {name(str): Variable}. name should be + the names of step inputs for this RNN cell, and Variable should be + the associated variables. + + Examples: + .. code-block:: python + state_cell.compute_state(inputs={'x': current_word}) + """ + if self._in_decoder and not self._switched_decoder: + self._switch_decoder() + + for input_name, input_value in six.iteritems(inputs): + if input_name not in self._inputs: + raise ValueError('Unknown input %s. ' + 'Please make sure %s in input ' + 'place holder.' % (input_name, input_name)) + self._inputs[input_name] = input_value + self._state_updater(self) + + def update_states(self): + """ + Update and record state information after each RNN step. + """ + if self._in_decoder and not self._switched_decoder: + self._switched_decoder() + + for state_name, decoder_state in six.iteritems(self._states_holder): + if id(self._cur_decoder_obj) not in decoder_state: + raise ValueError('Unknown decoder object, please make sure ' + 'switch_decoder been invoked.') + decoder_state[id(self._cur_decoder_obj)].update_state( + self._cur_states[state_name]) + + def out_state(self): + """ + Get the output state variable. This must be called after update_states. + + Returns: + The output variable of the RNN cell. + """ + return self._cur_states[self._out_state] + + +class TrainingDecoder(object): + """ + A decoder that can only be used for training. The decoder could be + initialized with a `StateCell` object. The computation within the RNN cell + could be defined with decoder's block. + + Args: + state_cell (StateCell): A StateCell object that handles the input and + state variables. + name (str): The name of this decoder. Default None. + + Returns: + TrainingDecoder: The initialized TrainingDecoder object. + + Examples: + .. code-block:: python + decoder = TrainingDecoder(state_cell) + with decoder.block(): + current_word = decoder.step_input(trg_embedding) + decoder.state_cell.compute_state(inputs={'x': current_word}) + current_score = layers.fc(input=decoder.state_cell.get_state('h'), + size=32, + act='softmax') + decoder.state_cell.update_states() + decoder.output(current_score) + """ + BEFORE_DECODER = 0 + IN_DECODER = 1 + AFTER_DECODER = 2 + + def __init__(self, state_cell, name=None): + self._helper = LayerHelper('training_decoder', name=name) + self._status = TrainingDecoder.BEFORE_DECODER + self._dynamic_rnn = layers.DynamicRNN() + self._type = _DecoderType.TRAINING + self._state_cell = state_cell + self._state_cell._enter_decoder(self) + + @signature_safe_contextmanager + def block(self): + """ + Define the behavior of the decoder for each RNN time step. + """ + if self._status != TrainingDecoder.BEFORE_DECODER: + raise ValueError('decoder.block() can only be invoked once') + self._status = TrainingDecoder.IN_DECODER + + with self._dynamic_rnn.block(): + yield + + self._status = TrainingDecoder.AFTER_DECODER + self._state_cell._leave_decoder(self) + + @property + def state_cell(self): + self._assert_in_decoder_block('state_cell') + return self._state_cell + + @property + def dynamic_rnn(self): + return self._dynamic_rnn + + @property + def type(self): + return self._type + + def step_input(self, x): + """ + Set the input variable as a step input to the RNN cell. For example, + in machine translation, each time step we read one word from the target + sentences, then the target sentence is a step input to the RNN cell. + + Args: + x (Variable): the variable to be used as step input. + + Returns: + Variable: The variable as input of current step. + + Examples: + .. code-block:: python + current_word = decoder.step_input(trg_embedding) + """ + self._assert_in_decoder_block('step_input') + return self._dynamic_rnn.step_input(x) + + def static_input(self, x): + """ + Set the input variable as a static input of RNN cell. In contrast to + step input, this variable will be used as a whole within the RNN decode + loop and will not be scattered into time steps. + + Args: + x (Variable): the variable to be used as static input. + + Returns: + Variable: The variable as input of current step. + + Examples: + .. code-block:: python + encoder_vec = decoder.static_input(encoded_vector) + """ + self._assert_in_decoder_block('static_input') + return self._dynamic_rnn.static_input(x) + + def __call__(self, *args, **kwargs): + """ + Get the output of RNN. This API should only be invoked after RNN.block() + + Returns: + Variable: The specified output of the RNN cell. + """ + if self._status != TrainingDecoder.AFTER_DECODER: + raise ValueError('Output of training decoder can only be visited ' + 'outside the block.') + return self._dynamic_rnn(*args, **kwargs) + + def output(self, *outputs): + """ + Set the output variable of the RNN cell. + + Args: + *outputs (Variables): a series of variables that treated as output + of the RNN cell. + + Examples: + .. code-block:: python + out = fluid.layers.fc(input=h, + size=32, + bias_attr=True, + act='softmax') + decoder.output(out) + """ + self._assert_in_decoder_block('output') + self._dynamic_rnn.output(*outputs) + + def _assert_in_decoder_block(self, method): + if self._status != TrainingDecoder.IN_DECODER: + raise ValueError('%s should be invoked inside block of ' + 'TrainingDecoder object.' % method) + + +class BeamSearchDecoder(object): + """ + A beam search decoder that can be used for inference. The decoder should be + initialized with a `StateCell` object. The decode process can be defined + within its block. + + Args: + state_cell (StateCell): A StateCell object that handles the input and + state variables. + init_ids (Variable): The init beam search token ids. + init_scores (Variable): The associated score of each id. + target_dict_dim (int): Size of dictionary. + word_dim (int): Word embedding dimension. + input_var_dict (dict): A feeding dict to feed the required input + variables to the state cell. It will be used by state_cell 's + compute method. Default empty. + topk_size (int): The topk size used for beam search. Default 50. + max_len (int): The maximum allowed length of the generated sentence. + Default 100. + beam_size (int): The beam width of beam search decode. Default 1. + end_id (int): The id of end token within beam search. + name (str): The name of this decoder. Default None. + + Returns: + BeamSearchDecoder: A initialized BeamSearchDecoder object. + + Examples: + .. code-block:: python + decoder = BeamSearchDecoder( + state_cell=state_cell, + init_ids=init_ids, + init_scores=init_scores, + target_dict_dim=target_dict_dim, + word_dim=word_dim, + init_var_dict={}, + topk_size=topk_size, + sparse_emb=IS_SPARSE, + max_len=max_length, + beam_size=beam_size, + end_id=1, + name=None + ) + decoder.decode() + translation_ids, translation_scores = decoder() + """ + BEFORE_BEAM_SEARCH_DECODER = 0 + IN_BEAM_SEARCH_DECODER = 1 + AFTER_BEAM_SEARCH_DECODER = 2 + + def __init__(self, + state_cell, + init_ids, + init_scores, + target_dict_dim, + word_dim, + input_var_dict={}, + topk_size=50, + sparse_emb=True, + max_len=100, + beam_size=1, + end_id=1, + name=None): + self._helper = LayerHelper('beam_search_decoder', name=name) + self._counter = layers.zeros(shape=[1], dtype='int64') + self._counter.stop_gradient = True + self._type = _DecoderType.BEAM_SEARCH + self._max_len = layers.fill_constant(shape=[1], + dtype='int64', + value=max_len) + self._cond = layers.less_than(x=self._counter, + y=layers.fill_constant(shape=[1], + dtype='int64', + value=max_len)) + self._while_op = layers.While(self._cond) + self._state_cell = state_cell + self._state_cell._enter_decoder(self) + self._status = BeamSearchDecoder.BEFORE_BEAM_SEARCH_DECODER + self._zero_idx = layers.fill_constant(shape=[1], + value=0, + dtype='int64', + force_cpu=True) + self._array_dict = {} + self._array_link = [] + self._ids_array = None + self._scores_array = None + self._beam_size = beam_size + self._end_id = end_id + + self._init_ids = init_ids + self._init_scores = init_scores + self._target_dict_dim = target_dict_dim + self._topk_size = topk_size + self._sparse_emb = sparse_emb + self._word_dim = word_dim + self._input_var_dict = input_var_dict + + @signature_safe_contextmanager + def block(self): + """ + Define the behavior of the decoder for each RNN time step. + """ + if self._status != BeamSearchDecoder.BEFORE_BEAM_SEARCH_DECODER: + raise ValueError('block() can only be invoke once.') + + self._status = BeamSearchDecoder.IN_BEAM_SEARCH_DECODER + + with self._while_op.block(): + yield + with layers.Switch() as switch: + with switch.case(self._cond): + layers.increment(x=self._counter, value=1.0, in_place=True) + + for value, array in self._array_link: + layers.array_write(x=value, + i=self._counter, + array=array) + + layers.less_than(x=self._counter, + y=self._max_len, + cond=self._cond) + + self._status = BeamSearchDecoder.AFTER_BEAM_SEARCH_DECODER + self._state_cell._leave_decoder(self) + + @property + def type(self): + return self._type + + def early_stop(self): + """ + Stop the generation process in advance. Could be used as "break". + """ + layers.fill_constant(shape=[1], + value=0, + dtype='bool', + force_cpu=True, + out=self._cond) + + def decode(self): + """ + Set up the computation within the decoder. Then you could call the + decoder to get the result of beam search decode. If you want to define + a more specific decoder, you could override this function. + + Examples: + .. code-block:: python + decoder.decode() + translation_ids, translation_scores = decoder() + """ + with self.block(): + prev_ids = self.read_array(init=self._init_ids, is_ids=True) + prev_scores = self.read_array(init=self._init_scores, + is_scores=True) + prev_ids_embedding = layers.embedding( + input=prev_ids, + size=[self._target_dict_dim, self._word_dim], + dtype='float32', + is_sparse=self._sparse_emb) + + feed_dict = {} + update_dict = {} + + for init_var_name, init_var in six.iteritems(self._input_var_dict): + if init_var_name not in self.state_cell._inputs: + raise ValueError('Variable ' + init_var_name + + ' not found in StateCell!\n') + + read_var = self.read_array(init=init_var) + update_dict[init_var_name] = read_var + feed_var_expanded = layers.sequence_expand( + read_var, prev_scores) + feed_dict[init_var_name] = feed_var_expanded + + for state_str in self._state_cell._state_names: + prev_state = self.state_cell.get_state(state_str) + prev_state_expanded = layers.sequence_expand( + prev_state, prev_scores) + self.state_cell.set_state(state_str, prev_state_expanded) + + for i, input_name in enumerate(self._state_cell._inputs): + if input_name not in feed_dict: + feed_dict[input_name] = prev_ids_embedding + + self.state_cell.compute_state(inputs=feed_dict) + current_state = self.state_cell.out_state() + current_state_with_lod = layers.lod_reset(x=current_state, + y=prev_scores) + scores = layers.fc(input=current_state_with_lod, + size=self._target_dict_dim, + act='softmax') + topk_scores, topk_indices = layers.topk(scores, k=self._topk_size) + accu_scores = layers.elementwise_add(x=layers.log(x=topk_scores), + y=layers.reshape(prev_scores, + shape=[-1]), + axis=0) + selected_ids, selected_scores = layers.beam_search(prev_ids, + prev_scores, + topk_indices, + accu_scores, + self._beam_size, + end_id=1, + level=0) + + with layers.Switch() as switch: + with switch.case(layers.is_empty(selected_ids)): + self.early_stop() + with switch.default(): + self.state_cell.update_states() + self.update_array(prev_ids, selected_ids) + self.update_array(prev_scores, selected_scores) + for update_name, var_to_update in six.iteritems( + update_dict): + self.update_array(var_to_update, feed_dict[update_name]) + + def read_array(self, init, is_ids=False, is_scores=False): + """ + Read an array to get the decoded ids and scores generated by previous + RNN step. At the first step of RNN, the init variable mut be used to + initialize the array. + + Args: + init (Variable): The initial variable for first step usage. init + must be provided. + is_ids (bool): Specify whether the variable is an id. + is_scores (bool): Specify whether the variable is a score. + + Returns: + The associated variable generated during previous RNN steps. + + Examples: + .. code-block:: python + prev_ids = decoder.read_array(init=init_ids, is_ids=True) + prev_scores = decoder.read_array(init=init_scores, is_scores=True) + """ + self._assert_in_decoder_block('read_array') + + if is_ids and is_scores: + raise ValueError('Shouldn\'t mark current array be ids array and' + 'scores array at the same time.') + + if not isinstance(init, Variable): + raise TypeError('The input argument `init` must be a Variable.') + + parent_block = self._parent_block() + array = parent_block.create_var( + name=unique_name.generate('beam_search_decoder_array'), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=init.dtype) + parent_block.append_op(type='write_to_array', + inputs={ + 'X': init, + 'I': self._zero_idx + }, + outputs={'Out': array}) + + if is_ids: + self._ids_array = array + elif is_scores: + self._scores_array = array + + read_value = layers.array_read(array=array, i=self._counter) + self._array_dict[read_value.name] = array + return read_value + + def update_array(self, array, value): + """ + Store the value generated in current step in an array for each RNN step. + This array could be accessed by read_array method. + + Args: + array (Variable): The array to append the new variable to. + value (Variable): The newly generated value to be stored. + """ + self._assert_in_decoder_block('update_array') + + if not isinstance(array, Variable): + raise TypeError( + 'The input argument `array` of must be a Variable.') + if not isinstance(value, Variable): + raise TypeError('The input argument `value` of must be a Variable.') + + array = self._array_dict.get(array.name, None) + if array is None: + raise ValueError('Please invoke read_array before update_array.') + self._array_link.append((value, array)) + + def __call__(self): + """ + Run the decode process and return the final decode result. + + Returns: + A tuple of decoded (id, score) pairs. id is a Variable that holds + the generated tokens, and score is a Variable with the same shape + as id, holds the score for each generated token. + """ + if self._status != BeamSearchDecoder.AFTER_BEAM_SEARCH_DECODER: + raise ValueError('Output of BeamSearchDecoder object can ' + 'only be visited outside the block.') + return layers.beam_search_decode(ids=self._ids_array, + scores=self._scores_array, + beam_size=self._beam_size, + end_id=self._end_id) + + @property + def state_cell(self): + self._assert_in_decoder_block('state_cell') + return self._state_cell + + def _parent_block(self): + """ + Getter of parent block. + + Returns: + The parent block of decoder. + """ + program = self._helper.main_program + parent_block_idx = program.current_block().parent_idx + if parent_block_idx < 0: + raise ValueError('Invalid block with index %d.' % parent_block_idx) + parent_block = program.block(parent_block_idx) + return parent_block + + def _assert_in_decoder_block(self, method): + if self._status != BeamSearchDecoder.IN_BEAM_SEARCH_DECODER: + raise ValueError('%s should be invoked inside block of ' + 'BeamSearchDecoder object.' % method) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..697ea0f05ae725cbda66e2568cf212bd69cb8787 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function +from . import extend_optimizer_with_weight_decay +from .extend_optimizer_with_weight_decay import * + +__all__ = [] +__all__ += extend_optimizer_with_weight_decay.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/extend_optimizer_with_weight_decay.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/extend_optimizer_with_weight_decay.py new file mode 100644 index 0000000000000000000000000000000000000000..6a87bb54d3f8b92b68f252c74371c2bce2bb998f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/extend_optimizer/extend_optimizer_with_weight_decay.py @@ -0,0 +1,151 @@ +# 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. +import paddle.fluid +from paddle.fluid import framework as framework + +__all__ = ["extend_with_decoupled_weight_decay"] + + +class DecoupledWeightDecay(object): + + def __init__(self, coeff=0.0, apply_decay_param_fun=None, **kwargs): + if not isinstance(coeff, float) and \ + not isinstance(coeff, framework.Variable): + raise TypeError("coeff should be float or Variable.") + self._params_name = set() + self._apply_decay_param_fun = apply_decay_param_fun + self._coeff = coeff + super(DecoupledWeightDecay, self).__init__(**kwargs) + + def _scale_parameters(self, params_and_grads): + """ + Adds weight decay ops. + scaled_parameter = parameter * coeff + + Args: + params_and_grads: A list of (parameters, gradients) pairs, + the parameters need to decay. + Raises: + Exception: The type of coeff and parameter is not consistent. + """ + if isinstance(self._coeff, float) and self._coeff == 0.0: + return + + scaled_params = [] + for param, grad in params_and_grads: + # If no gradient then we don't need to do anything + if grad is None: + continue + if self._apply_decay_param_fun is not None \ + and not self._apply_decay_param_fun(param.name): + continue + + if isinstance(self._coeff, float): + assert param.dtype is not paddle.fluid.core.VarDesc.VarType.FP32, \ + "the type of coeff(float) and parameter(%s) is not consistent."%(self._coeff.dtype) + else: + assert self._coeff.dtype == param.dtype, \ + "the type of coeff(%s) and parameter(%s) is not consistent."%(self._coeff.dtype, param.dtype) + + with param.block.program._optimized_guard( + [param, grad]), framework.name_scope('weight decay'): + assert param.name not in self._params_name + scaled_params.append((param, grad, param * self._coeff)) + self._params_name.add(param.name) + return scaled_params + + def backward(self, **kargs): + return super(DecoupledWeightDecay, self).backward(**kargs) + + def apply_optimize(self, **kargs): + return super(DecoupledWeightDecay, self).apply_optimize(**kargs) + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + params_grads = self.backward(loss=loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + scaled_params = self._scale_parameters(params_grads) + for p_grad_sgrad in scaled_params: + param, grad, scaled_param = p_grad_sgrad + with param.block.program._optimized_guard( + [param, grad]), framework.name_scope('weight decay'): + updated_param = paddle.fluid.layers.elementwise_sub( + x=param, y=scaled_param) + paddle.fluid.layers.assign(input=updated_param, output=param) + + optimize_ops = self.apply_optimize(loss=loss, + params_grads=params_grads, + startup_program=startup_program) + return optimize_ops, params_grads + + def __str__(self): + return " ".join(["Weight Decay, params:", ",".join(self._params_name)]) + + +def extend_with_decoupled_weight_decay(base_optimizer): + """ + extend_with_decoupled_weight_decay is a decorator function, it returns an + optimizer class with decoupled weight decay. The returned optimizer will + apply weight decay on the optimized parameters with the parameters before + optimization, i.e: new_parameter = optimized_parameter - parameter * coeff. + The details of decoupled weight decay yplease refer to this + `DECOUPLED WEIGHT DECAY REGULARIZATION `_. + + Args: + base_optimizer (Optimizer): The base_optimizer should be a derived class of Optimizer. + + Returns: + OptimizerWithDecoupledWeightDecay: the optimizer with decouple weight decay. + + Examples: + + .. code-block:: python + + AdamW = fluid.contrib.extend_with_decoupled_weight_decay( + fluid.optimizer.Adam) + optimizer = AdamW(learning_rate=0.1, + weight_decay=0.01) + + optimizer.minimize(cost) + """ + if not issubclass(base_optimizer, paddle.fluid.optimizer.Optimizer): + raise TypeError( + "The input(base_optimizer) should be a derived class of Optimizer.") + + class OptimizerWithDecoupledWeightDecay(DecoupledWeightDecay, + base_optimizer): + """ + OptimizerWithDecoupledWeightDecay is used to update the optimized parameters + with the parameters before optimization. For more information, please refer: + https://arxiv.org/pdf/1711.05101.pdf. + + Args: + weight_decay (float|Variable): The weight decay coefficient, it can be + float or Variable. + apply_decay_param_fun (function|None): If it is not None, + only variables that makes apply_decay_param_fun(variable)==True + will be updated. It only works when we want to specify variables. + Default: None. + """ + + def __init__(self, weight_decay, apply_decay_param_fun=None, **kwargs): + super(OptimizerWithDecoupledWeightDecay, + self).__init__(weight_decay, apply_decay_param_fun, **kwargs) + + return OptimizerWithDecoupledWeightDecay diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94889a65b3620f730dcd39c911599f50acbfe614 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/__init__.py @@ -0,0 +1,27 @@ +# 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. + +from __future__ import print_function + +from . import nn +from .nn import * + +from .rnn_impl import * +from . import metric_op +from .metric_op import * + +__all__ = [] +__all__ += nn.__all__ +__all__ += rnn_impl.__all__ +__all__ += metric_op.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/metric_op.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/metric_op.py new file mode 100644 index 0000000000000000000000000000000000000000..6f72086410a514f7e7732d1c9bb6d09a975597dc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/metric_op.py @@ -0,0 +1,250 @@ +# 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. +""" +Contrib layers just related to metric. +""" + +from __future__ import print_function + +import warnings +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.initializer import Normal, Constant +from paddle.fluid.framework import Variable +from paddle.fluid.param_attr import ParamAttr +from paddle.fluid.layers import tensor + +__all__ = ['ctr_metric_bundle'] + + +def ctr_metric_bundle(input, label, ins_tag_weight=None): + """ + ctr related metric layer + + This function help compute the ctr related metrics: RMSE, MAE, predicted_ctr, q_value. + To compute the final values of these metrics, we should do following computations using + total instance number: + MAE = local_abserr / instance number + RMSE = sqrt(local_sqrerr / instance number) + predicted_ctr = local_prob / instance number + q = local_q / instance number + Note that if you are doing distribute job, you should all reduce these metrics and instance + number first + + Args: + input(Tensor): A floating-point 2D Tensor, values are in the range + [0, 1]. Each row is sorted in descending order. This + input should be the output of topk. Typically, this + Tensor indicates the probability of each label. + label(Tensor): A 2D int Tensor indicating the label of the training + data. The height is batch size and width is always 1. + ins_tag_weight(Tensor): A 2D int Tensor indicating the ins_tag_weight of the training + data. 1 means real data, 0 means fake data. + A LoDTensor or Tensor with type float32,float64. + + Returns: + local_sqrerr(Tensor): Local sum of squared error + local_abserr(Tensor): Local sum of abs error + local_prob(Tensor): Local sum of predicted ctr + local_q(Tensor): Local sum of q value + + Examples 1: + .. code-block:: python + + import paddle + paddle.enable_static() + data = paddle.static.data(name="data", shape=[32, 32], dtype="float32") + label = paddle.static.data(name="label", shape=[-1, 1], dtype="int32") + predict = paddle.nn.functional.sigmoid(paddle.static.nn.fc(input=data, size=1)) + auc_out = paddle.static.ctr_metric_bundle(input=predict, label=label) + Examples 2: + .. code-block:: python + + import paddle + paddle.enable_static() + data = paddle.static.data(name="data", shape=[32, 32], dtype="float32") + label = paddle.static.data(name="label", shape=[-1, 1], dtype="int32") + predict = paddle.nn.functional.sigmoid(paddle.static.nn.fc(input=data, size=1)) + ins_tag_weight = paddle.static.data(name='ins_tag', shape=[-1,16], lod_level=0, dtype='int64') + auc_out = paddle.static.ctr_metric_bundle(input=predict, label=label, ins_tag_weight=ins_tag_weight) + + """ + if ins_tag_weight is None: + ins_tag_weight = tensor.fill_constant(shape=[1, 1], + dtype="float32", + value=1.0) + + assert input.shape == label.shape + helper = LayerHelper("ctr_metric_bundle", **locals()) + + local_abserr = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + local_sqrerr = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + local_prob = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + local_q = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + local_pos_num = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + local_ins_num = helper.create_global_variable(persistable=True, + dtype='float32', + shape=[1]) + + tmp_res_elesub = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[-1]) + tmp_res_sigmoid = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[-1]) + tmp_ones = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[-1]) + + batch_prob = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + batch_abserr = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + batch_sqrerr = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + batch_q = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + batch_pos_num = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + batch_ins_num = helper.create_global_variable(persistable=False, + dtype='float32', + shape=[1]) + for var in [ + local_abserr, batch_abserr, local_sqrerr, batch_sqrerr, local_prob, + batch_prob, local_q, batch_q, batch_pos_num, batch_ins_num, + local_pos_num, local_ins_num + ]: + helper.set_variable_initializer(var, Constant(value=0.0, + force_cpu=True)) + + helper.append_op(type="elementwise_sub", + inputs={ + "X": [input], + "Y": [label] + }, + outputs={"Out": [tmp_res_elesub]}) + + helper.append_op(type="squared_l2_norm", + inputs={"X": [tmp_res_elesub]}, + outputs={"Out": [batch_sqrerr]}) + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_sqrerr], + "Y": [local_sqrerr] + }, + outputs={"Out": [local_sqrerr]}) + + helper.append_op(type="l1_norm", + inputs={"X": [tmp_res_elesub]}, + outputs={"Out": [batch_abserr]}) + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_abserr], + "Y": [local_abserr] + }, + outputs={"Out": [local_abserr]}) + + helper.append_op(type="reduce_sum", + inputs={"X": [input]}, + outputs={"Out": [batch_prob]}) + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_prob], + "Y": [local_prob] + }, + outputs={"Out": [local_prob]}) + helper.append_op(type="sigmoid", + inputs={"X": [input]}, + outputs={"Out": [tmp_res_sigmoid]}) + helper.append_op(type="reduce_sum", + inputs={"X": [tmp_res_sigmoid]}, + outputs={"Out": [batch_q]}) + + helper.append_op(type="reduce_sum", + inputs={"X": [label]}, + outputs={"Out": [batch_pos_num]}) + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_pos_num], + "Y": [local_pos_num] + }, + outputs={"Out": [local_pos_num]}) + + helper.append_op(type='fill_constant_batch_size_like', + inputs={"Input": label}, + outputs={'Out': [tmp_ones]}, + attrs={ + 'shape': [-1, 1], + 'dtype': tmp_ones.dtype, + 'value': float(1.0), + }) + helper.append_op(type="reduce_sum", + inputs={"X": [tmp_ones]}, + outputs={"Out": [batch_ins_num]}) + + #if data is fake, return 0 + inputs_slice = {'Input': ins_tag_weight} + attrs = {'axes': [0]} + attrs['starts'] = [0] + attrs['ends'] = [1] + helper.append_op(type="slice", + inputs=inputs_slice, + attrs=attrs, + outputs={"Out": ins_tag_weight}) + + axis = helper.kwargs.get('axis', 0) + helper.append_op(type="elementwise_mul", + inputs={ + "X": [batch_ins_num], + "Y": [ins_tag_weight] + }, + outputs={"Out": [batch_ins_num]}, + attrs={'axis': axis}) + + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_ins_num], + "Y": [local_ins_num] + }, + outputs={"Out": [local_ins_num]}) + + helper.append_op(type="elementwise_mul", + inputs={ + "X": [batch_q], + "Y": [ins_tag_weight] + }, + outputs={"Out": [batch_q]}, + attrs={'axis': axis}) + helper.append_op(type="elementwise_add", + inputs={ + "X": [batch_q], + "Y": [local_q] + }, + outputs={"Out": [local_q]}) + + return local_sqrerr, local_abserr, local_prob, local_q, local_pos_num, local_ins_num diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/nn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..90bf501ed5c17aac07b5eb1bdeb54a80fa7f60b9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/nn.py @@ -0,0 +1,2101 @@ +# Copyright (c) 2022 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. +""" +Contrib layers just related to the neural network. +""" + +from __future__ import print_function + +import os +import six +import warnings +import inspect + +import numpy as np +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.layers import utils +from ... import unique_name +from paddle.fluid.initializer import Normal, Constant, NumpyArrayInitializer +from paddle.fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype, convert_dtype + +from paddle.fluid import core +from paddle.fluid.param_attr import ParamAttr + +from paddle.fluid.framework import Variable, convert_np_dtype_to_dtype_ +from paddle.fluid.layers import slice, reshape +import warnings +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'fused_elemwise_activation', 'sequence_topk_avg_pooling', 'var_conv_2d', + 'match_matrix_tensor', 'tree_conv', 'fused_embedding_seq_pool', + 'multiclass_nms2', 'search_pyramid_hash', 'shuffle_batch', 'partial_concat', + 'sparse_embedding', 'partial_sum', 'tdm_child', 'rank_attention', + 'tdm_sampler', 'batch_fc', '_pull_box_extended_sparse', 'bilateral_slice', + 'correlation', 'fused_bn_add_act', 'fused_seqpool_cvm' +] + + +def fused_elemwise_activation(x, + y, + functor_list, + axis=-1, + scale=0.0, + save_intermediate_out=True): + """ + **Fused elementwise_add/mul and activation layers** + + This function computes an elementwise_add/mul cooperated with an activation. + + .. math:: + + out = Unary(Binary(x, y)) + + or + + .. math:: + + out = Binary(x, Unary(y)) + + Unary operators can be: `scale`, `relu`, `tanh`. Binary operators can be: + `elementwise_add`, `elementwise_mul`. + + Args: + x (Variable): left operation of the binary operator. + y (Variable): right operator of the binary operator. + functor_list (list of str): types of operator which will be executed + by this layer. For example, ['elementwise_add', 'relu'] + (out = elementwise_add(x, relu(y))), + or ['relu', 'elemmentwise_add'] (out = relu(elementwise_add(x, y))). + axis (int32, default -1): axis of elementwise op. + scale (float32, default 0): parameter of scale op. + save_intermediate_out (bool, default True): whether to save the + intermediate result, Unary(y) or Binary(x, y). + + Returns: + Variable: The computation result. + """ + if isinstance(functor_list, str): + functor_list = functor_list.split(',') + + if not isinstance(functor_list, list) or len(functor_list) != 2: + raise ValueError( + 'functor_list should be a list of str, and the length should be 2.') + + helper = LayerHelper('fused_elemwise_activation', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + intermediate_out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='fused_elemwise_activation', + inputs={ + 'X': x, + 'Y': y + }, + outputs={ + 'Out': out, + 'IntermediateOut': intermediate_out + }, + attrs={ + 'axis': axis, + 'scale': scale, + 'save_intermediate_out': save_intermediate_out, + 'functor_list': functor_list + }) + return out + + +def var_conv_2d(input, + row, + col, + input_channel, + output_channel, + filter_size, + stride=1, + param_attr=None, + act=None, + dtype='float32', + name=None): + r""" + The var_conv_2d layer calculates the output base on the :attr:`input` with variable length, + row, col, input channel, filter size and strides. Both :attr:`input`, :attr:`row`, + and :attr:`col` are 1-level LodTensor. The convolution operation is same as conv2d layer with + padding. Besides, input.dims[1] should be 1. + + .. code-block:: text + + If input_channel is 2 and given row lodTensor and col lodTensor as follows: + row.lod = [[5, 4]] + col.lod = [[6, 7]] + input is a lodTensor: + input.lod = [[60, 56]] # where 60 = input_channel * 5 * 6 + input.dims = [116, 1] # where 116 = 60 + 56 + + If set output_channel is 3, filter_size is [3, 3], stride is [1, 1]: + # where 90 = output_channel * [(5-1)/stride + 1] * [(6-1)/stride + 1] + output.lod = [[90, 84]] + output.dims = [174, 1] # where 174 = 90 + 84 + + Args: + input (Variable): The input should be 1-level LodTensor with dims[1] equals 1. + row (Variable): The row should be 1-level LodTensor to provide height information. + col (Variable): The col should be 1-level LodTensor to provide width information. + input_channel (int): The number of input channel. + output_channel (int): The number of output channel. + filter_size (int|tuple|None): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + stride (int|tuple): The stride size. If stride is a tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: stride = 1. + param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights + of var_conv2d. If it is set to None or one attribute of ParamAttr, var_conv2d + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with :math:`Normal(0.0, std)`, + and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{ + 0.5}`. Default: None. + act (str): Activation type, if it is set to None, activation is not appended. + Default: None + dtype ('float32'): The data type of parameter and output. + name (str|None): A name for this layer(optional). If set None, the layer + will be named automatically. Default: None + + Returns: + Variable: Output variable with LoD specified by this layer. + + Examples: + .. code-block:: python + + import numpy as np + from paddle.fluid import layers + from paddle.fluid import contrib + + x_lod_tensor = layers.data(name='x', shape=[1], lod_level=1) + row_lod_tensor = layers.data(name='row', shape=[6], lod_level=1) + col_lod_tensor = layers.data(name='col', shape=[6], lod_level=1) + out = contrib.var_conv_2d(input=x_lod_tensor, + row=row_lod_tensor, + col=col_lod_tensor, + input_channel=3, + output_channel=5, + filter_size=[3, 3], + stride=1) + """ + helper = LayerHelper('var_conv_2d', **locals()) + x_shape = list(input.shape) + assert len(x_shape) == 2 + + filter_size = utils.convert_to_list(filter_size, 2, 'filter_size') + stride = utils.convert_to_list(stride, 2, 'stride') + + filter_shape = [ + int(output_channel), + int(input_channel) * filter_size[0] * filter_size[1] + ] + filter_param = helper.create_parameter( + attr=helper.param_attr, + shape=filter_shape, + dtype=dtype, + ) + + conv_res = helper.create_variable_for_type_inference(dtype) + tmp_res = helper.create_variable_for_type_inference(dtype, + stop_gradient=True) + + helper.append_op(type='var_conv_2d', + inputs={ + 'X': input, + 'ROW': row, + 'COLUMN': col, + 'W': filter_param, + }, + outputs={ + "Out": conv_res, + "Col": tmp_res + }, + attrs={ + 'InputChannel': input_channel, + 'OutputChannel': output_channel, + 'StrideH': stride[0], + 'StrideW': stride[1], + 'KernelH': filter_size[0], + 'KernelW': filter_size[1], + }) + + return helper.append_activation(conv_res) + + +def match_matrix_tensor(x, + y, + channel_num, + act=None, + param_attr=None, + dtype='float32', + name=None): + """ + Calculate the semantic matching matrix of two word sequences with variable length. + Given a query A of length `n` and a title B of length `m`, the input shape are respectively + [n, h] and [m, h], which h is hidden_size. If :attr:`channel_num` is set to 3, + it will generate a learnable parameter matrix W with shape [h, 3, h]. + Then the semantic matching matrix of query A and title B is calculated by + A * W * B.T = [n, h]*[h, 3, h]*[h, m] = [n, 3, m]. The learnable parameter matrix `W` + is equivalent to a fully connected layer in the calculation process. If :attr:`act` is provided, + the corresponding activation function will be applied to output matrix. + The :attr:`x` and :attr:`y` should be LodTensor and only one level LoD is supported. + + .. code-block:: text + + Given a 1-level LoDTensor x: + x.lod = [ + [2, 3, ]] + x.data = [[0.3, 0.1], [0.2, 0.3], [ + 0.5, 0.6], [0.7, 0.1], [0.3, 0.4]] + x.dims = [5, 2] + y is a Tensor: + y.lod = [[3, 1, ]] + y.data = [[0.1, 0.2], [0.3, 0.7], [0.9, 0.2], [0.4, 0.1]] + y.dims = [4, 2] + set channel_num 2, then we get a 1-level LoDTensor: + # where 12 = channel_num * x.lod[0][0] * y.lod[0][0] + out.lod = [[12, 6]] + out.dims = [18, 1] # where 18 = 12 + 6 + + Args: + x (Variable): Input variable x which should be 1-level LodTensor. + y (Variable): Input variable y which should be 1-level LodTensor. + channel_num (int): The channel number of learnable parameter W. + act (str, default None): Activation to be applied to the output of this layer. + param_attr (ParamAttr|list of ParamAttr, default None): The parameter attribute for learnable + parameters/weights of this layer. + dtype ('float32'): The data type of w data. + name (str|None): A name for this layer(optional). If set None, the layer will be named automatically. Default: None + + Returns: + Variable: output with LoD specified by this layer. + + Examples: + .. code-block:: python + + import numpy as np + from paddle.fluid import layers + from paddle.fluid import contrib + + x_lod_tensor = layers.data(name='x', shape=[10], lod_level=1) + y_lod_tensor = layers.data(name='y', shape=[10], lod_level=1) + out, out_tmp = contrib.match_matrix_tensor( + x=x_lod_tensor, y=y_lod_tensor, channel_num=3) + """ + helper = LayerHelper('match_matrix_tensor', **locals()) + + x_shape = list(x.shape) + y_shape = list(y.shape) + assert len(x_shape) == 2 and len( + y_shape) == 2 and x_shape[-1] == y_shape[-1] + + weight_shape = [x_shape[-1], channel_num, y_shape[-1]] + w = helper.create_parameter(attr=helper.param_attr, + shape=weight_shape, + dtype=dtype, + is_bias=False) + mm_res = helper.create_variable_for_type_inference(dtype) + tmp_res = helper.create_variable_for_type_inference(dtype, + stop_gradient=True) + helper.append_op(type='match_matrix_tensor', + inputs={ + 'X': x, + 'Y': y, + 'W': w, + }, + outputs={ + "Out": mm_res, + "Tmp": tmp_res + }, + attrs={'dim_t': channel_num}) + + return helper.append_activation(mm_res), tmp_res + + +def sequence_topk_avg_pooling(input, row, col, topks, channel_num): + """ + The :attr:`topks` is a list with incremental values in this function. For each topk, + it will average the topk features as an output feature for each channel of every + input sequence. Both :attr:`row` and :attr:`col` are LodTensor, which provide height + and width information for :attr:`input` tensor. If feature size of input sequence is less + than topk, it will padding 0 at the back. + + .. code-block:: text + + If channel_num is 2 and given row LoDTensor and col LoDTensor as follows: + row.lod = [[5, 4]] + col.lod = [[6, 7]] + + input is a LoDTensor with input.lod[0][i] = channel_num * row.lod[0][i] * col.lod[0][i] + input.lod = [[60, 56]] # where 60 = channel_num * 5 * 6 + input.dims = [116, 1] # where 116 = 60 + 56 + + If topks is [1, 3, 5], then we get a 1-level LoDTensor: + out.lod = [[5, 4]] # share Lod info with row LodTensor + out.dims = [9, 6] # where 6 = len(topks) * channel_num + + Args: + input (Variable): The input should be 2D LodTensor with dims[1] equals 1. + row (Variable): The row should be 1-level LodTensor to provide the height information + of the input tensor data. + col (Variable): The col should be 1-level LodTensor to provide the width information + of the input tensor data. + topks (list): A list of incremental value to average the topk feature. + channel_num (int): The number of input channel. + + Returns: + Variable: output LodTensor specified by this layer. + + Examples: + + .. code-block:: python + + import numpy as np + from paddle.fluid import layers + from paddle.fluid import contrib + + x_lod_tensor = layers.data(name='x', shape=[1], lod_level=1) + row_lod_tensor = layers.data(name='row', shape=[6], lod_level=1) + col_lod_tensor = layers.data(name='col', shape=[6], lod_level=1) + out = contrib.sequence_topk_avg_pooling(input=x_lod_tensor, + row=row_lod_tensor, + col=col_lod_tensor, + topks=[1, 3, 5], + channel_num=5) + """ + helper = LayerHelper('sequence_topk_avg_pooling', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + pos = helper.create_variable_for_type_inference(dtype=helper.input_dtype(), + stop_gradient=True) + helper.append_op(type='sequence_topk_avg_pooling', + inputs={ + 'X': input, + 'ROW': row, + 'COLUMN': col + }, + outputs={ + 'Out': out, + 'pos': pos + }, + attrs={ + 'topks': topks, + 'channel_num': channel_num + }) + + return out + + +def tree_conv(nodes_vector, + edge_set, + output_size, + num_filters=1, + max_depth=2, + act='tanh', + param_attr=None, + bias_attr=None, + name=None): + """ + ${comment} +Args : nodes_vector(${nodes_vector_type}) : $ { nodes_vector_comment } +edge_set(${edge_set_type}) : $ { edge_set_comment } + output_size(int): output feature width + num_filters(int): number of filters, Default 1 + max_depth(int): max depth of filters, Default 2 + act(str): activation function, Default tanh + param_attr(ParamAttr): the parameter attribute for the filters, Default None + bias_attr(ParamAttr): the parameter attribute for the bias of this layer, Default None + name(str): a name of this layer(optional). If set None, the layer will be named automatically, Default None + + Returns: + out(${out_type}): ${ + out_comment + } + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + # 10 for max_node_size of dataset, 5 for vector width + nodes_vector = fluid.layers.data( + name='vectors', shape=[10, 5], dtype='float32') + # 10 for max_node_size of dataset, 2 for every edge has two nodes + # edges must be directional + edge_set = fluid.layers.data(name='edge_set', shape=[ + 10, 2], dtype='float32') + # the shape of output will be [10, 6, 1], + # 10 for max_node_size of dataset, 6 for output size, 1 for 1 filter + out_vector = fluid.layers.tree_conv(nodes_vector, edge_set, 6, 1, 2) +#After reshape, output tensor could be nodes_vector for next tree convolution + out_vector = fluid.layers.reshape(out_vector, shape=[-1, 10, 6]) + out_vector_2 = fluid.layers.tree_conv(out_vector, edge_set, 3, 4, 2) +#also output tensor could be pooling(the pooling in paper called global pooling) + pooled = fluid.layers.reduce_max(out_vector, dim=2) # global pooling + """ + check_type(nodes_vector, 'nodes_vector', (Variable), 'tree_conv') + check_type(edge_set, 'edge_set', (Variable), 'tree_conv') + + helper = LayerHelper("tree_conv", **locals()) + dtype = helper.input_dtype('nodes_vector') + feature_size = nodes_vector.shape[2] + W_shape = [feature_size, 3, output_size, num_filters] + W = helper.create_parameter(attr=param_attr, + shape=W_shape, + dtype=dtype, + is_bias=False) + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op(type='tree_conv', + inputs={ + 'NodesVector': nodes_vector, + 'EdgeSet': edge_set, + 'Filter': W + }, + outputs={ + 'Out': out, + }, + attrs={'max_depth': max_depth}) + if helper.bias_attr: + pre_activation = helper.append_bias_op(out) + else: + pre_activation = out + return helper.append_activation(pre_activation) + + +def fused_embedding_seq_pool(input, + size, + is_sparse=False, + padding_idx=None, + combiner='sum', + param_attr=None, + dtype='float32'): + r""" + **Embedding Sequence pool** + + This layer is the fusion of lookup table and sequence_pool. + + Args: + input (Variable): Input is a Tensor Variable, which contains the IDs' information. + The value of the input IDs should satisfy :math:`0<= id < size[0]`. + size (tuple|list): The shape of the lookup_table parameter. It should + have two elements which indicate the size of the dictionary of + embedding and the size of each embedding vector respectively. + is_sparse (bool): The flag indicating whether to use sparse update. + Default: False. + padding_idx (int|long|None): It will output all-zero padding data whenever + lookup encounters :math:`padding\_idx` in Ids. If set :attr:`None`, it makes + no effect to output. If :math:`padding\_idx < 0`, the :math:`padding\_idx` + will automatically be converted to :math:`size[0] + padding\_idx` to use. + Default: None. + combiner (str): The pooling type of sequence_pool, and only support `sum`. + Default: sum. + param_attr (ParamAttr): Parameters for this layer. + dtype (np.dtype|core.VarDesc.VarType|str): The dtype refers to the data type of output + tensor. It can be float32, float_16, int etc. + Returns: + The sequence pooling variable which is a Tensor. + Examples: + .. code-block:: python + import numpy as np + import paddle.fluid as fluid + + dict_size = 20 + data_t = fluid.layers.data( + name='word', shape=[1], dtype='int64', lod_level=1) + padding_idx = np.random.randint(1, 10) + out = fluid.contrib.fused_embedding_seq_pool( + input=data_t, + size=[dict_size, 32], + param_attr='w', + padding_idx=padding_idx, + is_sparse=False) + """ + helper = LayerHelper('fused_embedding_seq_pool', **locals()) + w = helper.create_parameter(attr=helper.param_attr, + shape=size, + dtype=dtype, + is_bias=False) + out = helper.create_variable_for_type_inference(dtype) + padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( + size[0] + padding_idx) + helper.append_op(type='fused_embedding_seq_pool', + inputs={ + 'Ids': input, + 'W': w + }, + outputs={'Out': out}, + attrs={ + 'is_sparse': is_sparse, + 'combiner': combiner, + 'padding_idx': padding_idx + }) + return out + + +def fused_seqpool_cvm(input, + pool_type, + cvm, + pad_value=0.0, + use_cvm=True, + cvm_offset=2): + """ + :api_attr: Static Graph + + This OP is the fusion of sequence_pool and continuous_value_model op. + + **Note:** The Op only receives List of LoDTensor as input, only support SUM pooling now. + + Args: + input(Variable|list of Variable): Input is List of LoDTensor. + pool_type(str): pooling type, only support SUM pooling now. + cvm(Variable): cvm Variable. + pad_value(float, optional): padding value of sequence pool. Default: 0.0. + use_cvm(bool, optional): use cvm or not. Default: True. + cvm_offset(int, optional): cvm offset. Default: 2, which means cvm contains show, click. + + Returns: + Variable|list of Variable: The tensor variable storing sequence pool and cvm + of input. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + data = paddle.static.data(name='x', shape=[-1, 1], dtype='int64', lod_level=1) + data2 = paddle.static.data(name='y', shape=[-1, 1], dtype='int64', lod_level=1) + inputs = [data, data2] + embs = fluid.layers.nn._pull_box_sparse(input=inputs, size=11, is_distributed=True, is_sparse=True) + + label = paddle.static.data(name="label", shape=[-1, 1], dtype="int64", lod_level=1) + ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype="int64", value=1) + show_clk = paddle.cast(paddle.concat([ones, label], axis=1), dtype='float32') + show_clk.stop_gradient = True + + cvms = fluid.contrib.layers.fused_seqpool_cvm(embs, 'sum', show_clk) + + + """ + helper = LayerHelper('fused_seqpool_cvm', **locals()) + + if pool_type.upper() != 'SUM': + raise ValueError( + "fused_seqpool_cvm only support SUM pooling now, and your type is: " + + pool_type) + + check_type(input, 'input', list, 'fused_seqpool_cvm') + if isinstance(input, list): + for _input in input: + check_variable_and_dtype(_input, 'input', ['float32'], + 'fused_seqpool_cvm') + + dtype = helper.input_dtype() + inputs = helper.multiple_input() + outs = [ + helper.create_variable_for_type_inference(dtype) + for i in range(len(inputs)) + ] + + helper.append_op(type="fused_seqpool_cvm", + inputs={ + "X": inputs, + "CVM": cvm + }, + outputs={"Out": outs}, + attrs={ + "pooltype": pool_type.upper(), + "pad_value": pad_value, + "use_cvm": use_cvm, + "cvm_offset": cvm_offset, + }) + + return outs + + +def multiclass_nms2(bboxes, + scores, + score_threshold, + nms_top_k, + keep_top_k, + nms_threshold=0.3, + normalized=True, + nms_eta=1., + background_label=0, + return_index=False, + name=None): + """ + **Multiclass NMS2** + + This operator is to do multi-class non maximum suppression (NMS) on + boxes and scores. + In the NMS step, this operator greedily selects a subset of detection bounding + boxes that have high scores larger than score_threshold, if providing this + threshold, then selects the largest nms_top_k confidences scores if nms_top_k + is larger than -1. Then this operator pruns away boxes that have high IOU + (intersection over union) overlap with already selected boxes by adaptive + threshold NMS based on parameters of nms_threshold and nms_eta. + Aftern NMS step, at most keep_top_k number of total bboxes are to be kept + per image if keep_top_k is larger than -1. + + Args: + bboxes (Variable): Two types of bboxes are supported: + 1. (Tensor) A 3-D Tensor with shape + [N, M, 4 or 8 16 24 32] represents the + predicted locations of M bounding bboxes, + N is the batch size. Each bounding box has four + coordinate values and the layout is + [xmin, ymin, xmax, ymax], when box size equals to 4. + 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4] + M is the number of bounding boxes, C is the + class number + scores (Variable): Two types of scores are supported: + 1. (Tensor) A 3-D Tensor with shape [N, C, M] + represents the predicted confidence predictions. + N is the batch size, C is the class number, M is + number of bounding boxes. For each category there + are total M scores which corresponding M bounding + boxes. Please note, M is equal to the 2nd dimension + of BBoxes. + 2. (LoDTensor) A 2-D LoDTensor with shape [M, C]. + M is the number of bbox, C is the class number. + In this case, input BBoxes should be the second + case with shape [M, C, 4]. + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all + categories will be considered. Default: 0 + score_threshold (float): Threshold to filter out bounding boxes with + low confidence score. If not provided, + consider all boxes. + nms_top_k (int): Maximum number of detections to be kept according to + the confidences after the filtering detections based + on score_threshold. + nms_threshold (float): The threshold to be used in NMS. Default: 0.3 + nms_eta (float): The threshold to be used in NMS. Default: 1.0 + keep_top_k (int): Number of total bboxes to be kept per image after NMS + step. -1 means keeping all bboxes after NMS step. + normalized (bool): Whether detections are normalized. Default: True + return_index(bool): Whether return selected index. Default: False + name(str): Name of the multiclass nms op. Default: None. + + Returns: + A tuple with two Variables: (Out, Index) if return_index is True, + otherwise, a tuple with one Variable(Out) is returned. + Out: A 2-D LoDTensor with shape [No, 6] represents the detections. + Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax] + or A 2-D LoDTensor with shape [No, 10] represents the detections. + Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3, + x4, y4]. No is the total number of detections. + If all images have not detected results, all elements in LoD will be + 0, and output tensor is empty (None). + Index: Only return when return_index is True. A 2-D LoDTensor with + shape [No, 1] represents the selected index which type is Integer. + The index is the absolute value cross batches. No is the same number + as Out. If the index is used to gather other attribute such as age, + one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where + N is the batch size and M is the number of boxes. + + + Examples: + .. code-block:: python + + + import paddle.fluid as fluid + boxes = fluid.layers.data(name='bboxes', shape=[81, 4], + dtype='float32', lod_level=1) + scores = fluid.layers.data(name='scores', shape=[81], + dtype='float32', lod_level=1) + out, index = fluid.layers.multiclass_nms2(bboxes=boxes, + scores=scores, + background_label=0, + score_threshold=0.5, + nms_top_k=400, + nms_threshold=0.3, + keep_top_k=200, + normalized=False, + return_index=True) + """ + helper = LayerHelper('multiclass_nms2', **locals()) + + output = helper.create_variable_for_type_inference(dtype=bboxes.dtype) + index = helper.create_variable_for_type_inference(dtype='int') + helper.append_op(type="multiclass_nms2", + inputs={ + 'BBoxes': bboxes, + 'Scores': scores + }, + attrs={ + 'background_label': background_label, + 'score_threshold': score_threshold, + 'nms_top_k': nms_top_k, + 'nms_threshold': nms_threshold, + 'keep_top_k': keep_top_k, + 'nms_eta': nms_eta, + 'normalized': normalized + }, + outputs={ + 'Out': output, + 'Index': index + }) + output.stop_gradient = True + index.stop_gradient = True + + if return_index: + return output, index + return output + + +def search_pyramid_hash(input, + num_emb, + space_len, + pyramid_layer, + rand_len, + drop_out_percent, + is_training, + use_filter, + white_list_len, + black_list_len, + seed, + lr, + param_attr=None, + param_attr_wl=None, + param_attr_bl=None, + name=None, + distribute_update_vars=None, + dtype='float32'): + """ + **Pyramid hash embedding** + + Args: + input (Variable): LoDTensor Variable contained the IDs' information. + num_emb (int): The embedding size of output. + space_len (int): The length of pyramid hash embedding space. + pyramid_layer (int): The number of pyramid layers. It should be greater than 2. + rand_len (int): The minimum length of pyramid hash cell. + drop_out_percent (float): The probability of dropping out the input token randomly. + It should satisfy: [0., 1.] + is_training (bool): Whether in training or testing phrase. + use_filter(bool): If set True, the white filter and black filter should be given by + :attr:`param_attr_wl` and :attr:`param_attr_bl` . + white_list_len(int): If set :math:`white_list_len>0` , white filter with shape [white_list_len, 1] + should be provided by param_attr_wl. + black_list_len(int): If set :math:`black_list_len>0` , black filter with shape [black_list_len, 1] + should be provided by param_attr_bl. + seed(int): The number of random seed. + lr(float): The learning rate of weight created by :attr:`param_attr` with shape [space_len+rand_len, 1] + in this layer. + param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . + param_attr_wl(ParamAttr): Specified parameters of white filter. + param_attr_bl(ParamAttr): Specified parameters of black filter. + distribute_update_vars(list[ParamAttr.name]): Decided which params should be updated in distribute training. + Used in Distribute Transpiler to create a trainer/server program. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + dtype(str): The data type of output variable, float32. + Returns: + Variable: LoDTensor of pyramid hash embedding. + """ + helper = LayerHelper('search_pyramid_hash', **locals()) + + w_shape = [space_len + rand_len, 1] + w = helper.create_parameter(attr=param_attr, + shape=w_shape, + dtype=dtype, + is_bias=False) + w.stop_gradient = True + + input_vars = {'X': input, 'W': w} + if white_list_len > 0: + wl_shape = [white_list_len, 1] + white_list = helper.create_parameter(attr=param_attr_wl, + shape=wl_shape, + dtype=dtype, + is_bias=False) + white_list.stop_gradient = True + input_vars['WhiteList'] = white_list + + if black_list_len >= 0: + bl_shape = [black_list_len, 1] + black_list = helper.create_parameter(attr=param_attr_bl, + shape=bl_shape, + dtype=dtype, + is_bias=False) + black_list.stop_gradient = True + input_vars['BlackList'] = black_list + + distribute_update_vars_str = "" + if distribute_update_vars: + assert isinstance(distribute_update_vars, list) + special_name_list = [] + if param_attr: + special_name_list.append(param_attr.name) + if param_attr_wl: + special_name_list.append(param_attr_wl.name) + if param_attr_bl: + special_name_list.append(param_attr_bl.name) + for param in distribute_update_vars: + if param not in special_name_list: + raise ValueError( + "Pyramid Hash layer didn't have parameter {}".format(param)) + distribute_update_vars_str = ",".join(distribute_update_vars) + + res = helper.create_variable_for_type_inference(dtype) + drop_pos = helper.create_variable_for_type_inference(dtype) + x_temp_out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='pyramid_hash', + inputs=input_vars, + outputs={ + "Out": res, + "X_Temp_Out": x_temp_out, + 'DropPos': drop_pos + }, + attrs={ + 'num_emb': num_emb, + 'space_len': space_len, + 'pyramid_layer': pyramid_layer, + 'rand_len': rand_len, + 'drop_out_percent': drop_out_percent, + 'is_training': is_training, + 'use_filter': use_filter, + 'white_list_len': white_list_len, + 'black_list_len': black_list_len, + 'seed': seed, + 'lr': lr, + 'distribute_update_vars': distribute_update_vars_str + }) + + return res + + +def shuffle_batch(x, seed=None): + """ + This layer shuffle input tensor :attr:`x` . Normally, :attr:`x` is 2-D LoDTensor. + + :attr:`x` is a LoDTensor to be shuffled with shape :math:`[N_1, N_2, ..., N_k, D]` . Note that the last dim of input will not be shuffled. + :math:`N_1 * N_2 * ... * N_k` numbers of elements with length :math:`D` will be shuffled randomly. + + For Example: + + .. code-block:: text + + Input: + x.data = [[1, 2], [3, 4], [5, 6], [7, 8]] + x.dims = [4, 2] + + Attrs: + seed = 2019 + + Output: + Out.data =[[7, 8], [1, 2], [3, 4], [5, 6]] + Out.dims = [4, 2] + + Args: + x (Variable): The input variable. The input variable is a N-D LoDTensor with type int, float32 or float64. + seed (None|int|Variable): The start up seed. If set, seed will be set as the start up seed of shuffle engine. + If not set(Default), start up seed of shuffle engine will be generated randomly. + + Returns: + Variables: The shuffled LoDTensor with the same shape and lod as input. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name="x", shape=[-1, 4]) + out = fluid.contrib.layers.shuffle_batch(x) + """ + helper = LayerHelper('shuffle_batch', **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + shuffle_idx = helper.create_variable_for_type_inference(dtype=np.int64) + if seed is None and helper.main_program.random_seed != 0: + seed = helper.main_program.random_seed + if seed is None: + seed = np.random.randint(-65536, 65535) + op_attrs = {} + if isinstance(seed, int): + op_attrs["startup_seed"] = seed + seed = helper.create_variable( + name=unique_name.generate("shuffle_batch_seed"), + dtype="int64", + persistable=False) + helper.append_op(type='shuffle_batch', + inputs={ + 'X': x, + 'Seed': seed + }, + outputs={ + 'Out': out, + 'ShuffleIdx': shuffle_idx, + 'SeedOut': seed + }, + attrs=op_attrs) + return out + + +def partial_concat(input, start_index=0, length=-1): + """ + **Partial Concat** + This OP concatenates the inputs according to the start index and length. This + OP exists in contrib, which means that it is not shown to the public. + Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be + performed along the second dimension. + + .. code-block:: text + + Given: + x = [[0, 1, 2], + [3, 4, 5]] + y = [[6, 7 ,8], + [9, 10, 11]] + output = partial_concat([x, y], start_index=0, length=2) + + we get: + + output = [[0, 1, 6, 7], + [3, 4, 9, 10]] + + Args: + input(list): List of input Tensors with data type float32, float64, int32, + int64. + start_index(int32): The start index of each instance for partial concatenation. + Default is 0. + length(int32): The length of each instance for partial concatenation. Default is -1. + Negative values for all elements after start_index. + Returns: + Variable: A Tensor with the same data type as input's. + Examples: + .. code-block:: python + import paddle.fluid as fluid + x = fluid.data(name="x", shape=[None,3], dtype="float32") + y = fluid.data(name="y", shape=[None,3], dtype="float32") + concat = fluid.contrib.layers.partial_concat( + [x, y], start_index=0, length=2) + """ + if not isinstance(input, list): + warnings.warn( + "The type of input in partial_concat should be list, but received %s." + % (type(input))) + input = [input] + for id, x in enumerate(input): + check_variable_and_dtype( + x, 'input[' + str(id) + ']', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'partial_concat') + check_type(start_index, 'start_index', (int), 'partial_concat') + check_type(length, 'length', (int), 'partial_concat') + inputs = {'X': input} + attrs = {'start_index': start_index, 'length': length} + helper = LayerHelper('partial_concat', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op(type='partial_concat', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + return out + + +def partial_sum(input, start_index=0, length=-1): + """ + **PartialSum** + This Op can sum the vars by specifying the initial position(start_index) and length(length). + This Op exists in contrib, which means that it is not shown to the public. + Only 2-D Tensor or LodTensor input is supported. Slice and concat can only be + performed along the second dimension. + .. code-block:: text + + Given: + x = [[0, 1, 2], + [3, 4, 5]] + y = [[6, 7 ,8], + [9, 10, 11]] + output = partial_sum([x, y], start_index=0, length=2) + we get: + + output = [[6, 8], + [12, 14]] + Args: + input(list): List of input Tensors with data type float32, float64, int32, + int64. + Returns: + Variable: A Tensor with the same data type as input's. + Examples: + .. code-block:: python + import paddle.fluid.layers as layers + import paddle.fluid as fluid + import numpy as np + x = fluid.data(name="x", shape=[None, 3], dtype="float32") + y = fluid.data(name="y", shape=[None, 3], dtype="float32") + sum = layers.partial_sum([x,y], start_index=0, length=2) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + xx = np.array([1,2,3,4,5,6]).reshape((2,3)).astype("float32") + yy = np.array([6,5,4,4,5,6]).reshape((2,3)).astype("float32") + out = exe.run(feed={"x":xx, "y":yy}, fetch_list=[sum]) + """ + for id, x in enumerate(input): + check_variable_and_dtype(x, 'input[' + str(id) + ']', + ['float32', 'float64', 'int32', 'int64'], + 'partial_sum') + + inputs = {'X': input} + attrs = {} + attrs['start_index'] = start_index + attrs['length'] = length + helper = LayerHelper('partial_sum', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op(type='partial_sum', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + return out + + +def sparse_embedding(input, + size, + padding_idx=None, + is_test=False, + entry=None, + table_class="MemorySparseTable", + param_attr=None, + dtype='float32', + slot=None): + r""" + :api_attr: Static Graph + + The OP is used as the operator of the Embedding Lookup layer in the large-scale + sparse training of the parameter server mode, instead of using the paddle.nn.functional.embedding. + + The operator is used to lookup embeddings vector of ids provided by :attr:`input` . + It automatically constructs a 2D embedding matrix based on the input :attr:`size` + (vocab_size, emb_size) and :attr:`dtype` . + + The shape of output Tensor is generated by appending an emb_size dimension to the + last dimension of the input Tensor shape. + + **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , otherwise + the program will throw an exception and exit. + + .. code-block:: text + + Case 1: + + input is a Tensor. padding_idx = -1 + input.data = [[1, 3], [2, 4], [4, 127]] + input.shape = [3, 2] + Given size = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when ids is 127. + + Case 2: + + input is a LoDTensor with 1-level LoD. padding_idx = 0 + input.lod = [[2, 3]] + input.data = [[1], [3], [2], [4], [0]] + input.shape = [5, 1] + Given size = [128, 16] + output is a LoDTensor: + out.lod = [[2, 3]] + out.shape = [5, 1, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452]], + [[0.345421456, 0.524563927, ..., 0.144534654]], + [[0.345249859, 0.124939536, ..., 0.194353745]], + [[0.945345345, 0.435394634, ..., 0.435345365]], + [[0.0, 0.0, ..., 0.0 ]]] # padding data + It will pad all-zero data when ids is 0. + + Args: + input(Variable): A Tensor or LoDTensor with type int64, which contains the id + information. The value of the input id should satisfy :math:`0<= id < size[0]` . + size(tuple|list): The shape of lookup table parameter (vocab_size, emb_size). It + should have two elements which indicates the size of the dictionary of embeddings + and the size of each embedding vector respectively. The initial parameter size + is 0 in the large-scale sparse scenario, which will gradually expand with the + training. So if vocab_size is temporarily useless, its value can be any integer. + The emb_size is the dimensional configuration of the word embedding weight parameter. + padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-vocab_size, vocab_size). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever + lookup encounters :math:`padding\_idx` in id. And the padding data will not be updated + while training. If set None, it makes no efe mfect to output. Default: None. + is_test(bool, optional): Training or prediction mode. In prediction mode (is_test=False), + the output is not initialized and created, and it is filled with 0 and returned. Default: False. + entry(str, optional): Entry config with parameter server whose value is ProbabilityEntry, + CountFilterEntry or None. Default: None. + table_class(str, optional): The type of the sparse table. The value can be CommonSparseTable + or SSDSparseTable. The default is CommonSparseTable. + param_attr(ParamAttr, optional): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. In addition, user-defined or pre-trained word + vectors can be loaded with the :attr:`param_attr` parameter. The local word vector needs + to be transformed into numpy format, and the shape of local word vector should be consistent + with :attr:`size` . + dtype(str): It refers to the data type of output Tensor. It must be float32 or + float64. Default: float32. + + Returns: + Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` . + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + sparse_feature_dim = 1024 + embedding_size = 64 + + # Only when the feature appear more than 10 times or more will be participated in the training. + entry = paddle.distributed.CountFilterEntry(10) + + input = paddle.static.data(name='ins', shape=[1], dtype='int64') + + emb = paddle.static.nn.sparse_embedding( + input=input, + size=[sparse_feature_dim, embedding_size], + is_test=False, + entry=entry, + param_attr=paddle.ParamAttr(name="SparseFeatFactors", + initializer=paddle.nn.initializer.Uniform())) + + """ + + helper = LayerHelper('sparse_embedding', **locals()) + + check_variable_and_dtype(input, 'input', ['int64'], + 'fluid.contrib.layers.sparse_embedding') + + check_dtype(dtype, 'dtype', ['float32', 'float64'], + 'paddle.static.nn.sparse_embedding') + + w = helper.create_parameter(attr=helper.param_attr, + shape=size, + type=core.VarDesc.VarType.SELECTED_ROWS, + dtype=dtype, + is_bias=False) + + tmp = helper.create_variable_for_type_inference(dtype) + + padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( + size[0] + padding_idx) + + if table_class not in [ + "CommonSparseTable", "SSDSparseTable", "MemorySparseTable" + ]: + raise ValueError( + "table_class must be in [CommonSparseTable, SSDSparseTable, MemorySparseTable]" + ) + + entry_str = "none" + + if entry is not None: + if entry.__class__.__name__ not in [ + "ProbabilityEntry", "CountFilterEntry", "ShowClickEntry" + ]: + raise ValueError( + "entry must be instance in [paddle.distributed.ProbabilityEntry, paddle.distributed.CountFilterEntry, paddle.distributed.ShowClickEntry]" + ) + entry_str = entry._to_attr() + + if slot == None: + slot = 0 + + helper.append_op(type='lookup_table', + inputs={ + 'Ids': input, + 'W': w + }, + outputs={'Out': tmp}, + attrs={ + 'padding_idx': padding_idx, + 'is_sparse': True, + 'is_distributed': True, + 'remote_prefetch': True, + 'is_test': is_test, + 'entry': entry_str, + 'table_class': table_class, + 'slot': slot + }) + return tmp + + +def tdm_child(x, node_nums, child_nums, param_attr=None, dtype='int32'): + """ + **Tdm Child** + According to the input node_id on the given tree, return the corresponding child node_id and + whether child is a leaf node by leaf_mask value. + .. code-block:: text + + Given: + tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes + x = [[2], [3]] + node_nums = 7 + child_nums = 2 + + we get: + child = [[5, 6], + [0, 0]] + leaf_mask = [[1, 1], + [0, 0]] + Args: + x(Variable): Variable contained the node_id information, dtype support int32/int64. + node_nums(int): Number of total nodes. + child_nums(int): Maximum number of child nodes per node. + param_attr(ParamAttr): To specify the tdm-tree-info parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in: ref: `api_fluid_ParamAttr`, should + has shape(node_nums, 3 + child_nums), dtype support int32/int64. + The dimension[1] of tdm-tree-info contains the following: + 1. Item_id(int, shape(1)), if node is a leaf node, give its item_id corresponding to node_id, else give 0. + 2. Layer_id(int, shape(1)), indicates which layer the node is on. + 3. Parent_id(int, shape(1)), node's parent node. + 4. Child_id(int, shape(child_nums)), all child node's node_id of this node should be given. + If the number of child nodes is insufficient, padding 0 until child nums equal to child_nums + dtype(str): The data type of output child and leaf_mask, support int32/int64. + + Returns: + tuple: A tuple including input node's child(Variable) and leaf_mask(Variable). + If child is a leaf node, leaf_mask equal ot 1, otherwise equal to 0. + + Examples: + .. code-block:: python + import paddle.fluid as fluid + import numpy as np + x = fluid.data(name="x", shape=[None, 1], dtype="int32", lod_level=1) + tree_info = [[0,0,0,1,2], + [0,1,0,3,4],[0,1,0,5,6], + [0,2,1,0,0],[1,2,1,0,0],[2,2,2,0,0],[3,2,2,0,0]] + tree_info_np = np.array(tree_info) + tree_info_np = np.reshape(tree_info_np, (7,5)) + node_nums = 7 + child_nums = 2 + child, leaf_mask = fluid.contrib.layers.tdm_child(x, node_nums, child_nums, + param_attr=fluid.ParamAttr( + initializer=fluid.initializer.NumpyArrayInitializer( + tree_info_np))) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + xx = np.array([[2],[3]]).reshape((2,1)).astype("int32") + child_res, leaf_mask_res = exe.run(feed={"x":xx}, fetch_list=[child, leaf_mask]) + """ + helper = LayerHelper("tdm_child", **locals()) + check_dtype(dtype, 'dtype', ['int32', 'int64'], + 'fluid.contrib.layers.tdm_child') + c_dtype = convert_np_dtype_to_dtype_(dtype) + tree_info = helper.create_parameter(attr=helper.param_attr, + shape=[node_nums, 3 + child_nums], + dtype=dtype, + default_initializer=Constant(0)) + tree_info.stop_gradient = True + + child = helper.create_variable_for_type_inference(dtype=dtype) + leaf_mask = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op(type='tdm_child', + inputs={ + 'X': x, + 'TreeInfo': tree_info + }, + outputs={ + 'Child': child, + 'LeafMask': leaf_mask + }, + attrs={ + 'child_nums': child_nums, + 'dtype': c_dtype + }, + stop_gradient=True) + return (child, leaf_mask) + + +def tdm_sampler(x, + neg_samples_num_list, + layer_node_num_list, + leaf_node_num, + tree_travel_attr=None, + tree_layer_attr=None, + output_positive=True, + output_list=True, + seed=0, + tree_dtype='int32', + dtype='int32'): + """ + **Tdm Sampler** + According to the input positive samples at leaf node(x), do negative sampling layer by layer on the given tree. + .. code-block:: text + + Given: + tree[[0], [1, 2], [3, 4], [5, 6]] # A binary tree with seven nodes + travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path (exclude root node) + layer_list = [[1, 2], [3, 4, 5, 6]] # two layer (exclude root node) + + x = [[0], [1], [2], [3]] # Corresponding to leaf node [[3], [4], [5], [6]] + neg_samples_num_list = [0, 0] # negative sample nums = 0 + layer_node_num_list = [2, 4] + leaf_node_num = 4 + output_list = False + + we get: + out = [[1, 3], [1, 4], [2, 5], [2, 6]] + labels = [[1, 1], [1, 1], [1, 1], [1, 1]] + mask = [[1, 1], [1, 1], [1, 1], [1, 1]] + + Args: + x (Variable): Variable contained the item_id(corresponding to leaf node) information, dtype support int32/int64. + neg_samples_num_list (list(int)): Number of negative samples per layer. + layer_node_num_list (list(int)): Number of nodes per layer, must has same shape with neg_samples_num_list. + leaf_node_num (int): Number of leaf nodes. + tree_travel_attr (ParamAttr): To specify the tdm-travel parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr`, should + has shape (leaf_node_num, len(layer_node_num_list)), dtype support int32/int64. + tree_layer_attr (ParamAttr): To specify the tdm-layer parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr`, should + has shape (node_num, 1), dtype support int32/int64. + output_positive (bool): Whether to output positive samples (includ label and mask )at the same time. + output_list (bool): Whether to divide the output into layers and organize it into list format. + seed (int): The number of random seed. + tree_dtype(np.dtype|core.VarDesc.VarType|str): The dtype of tdm-travel and tdm-layer, support int32/int64 + dtype(np.dtype|core.VarDesc.VarType|str): The dtype of output(sampling results, labels and masks) + + Returns: + tuple: A tuple including sampling results, corresponding labels and masks. if output_positive = True, sampling + result will include both positive and negative samples. If sampling reseult is a positive sample, the label is 1, + and if it is a negative sample, it is 0. If the tree is unbalanced, in order to ensure the consistency of the + sampling result shape, the padding sample's mask = 0, the real sample's mask value = 1. + If output_list = True, the result will organize into list format specified by layer information. + Output variable have same type with tdm-travel and tdm-layer parameter(tree_dtype). + + Examples: + .. code-block:: python + import paddle.fluid as fluid + import numpy as np + x = fluid.data(name="x", shape=[None, 1], dtype="int32", lod_level=1) + travel_list = [[1, 3], [1, 4], [2, 5], [2, 6]] # leaf node's travel path, shape(leaf_node_num, layer_num) + layer_list_flat = [[1], [2], [3], [4], [5], [6]] # shape(node_nums, 1) + + neg_samples_num_list = [0, 0] # negative sample nums = 0 + layer_node_num_list = [2, 4] #two layer (exclude root node) + leaf_node_num = 4 + + travel_array = np.array(travel_list) + layer_array = np.array(layer_list_flat) + + sample, label, mask = fluid.contrib.layers.tdm_sampler( + x, + neg_samples_num_list, + layer_node_num_list, + leaf_node_num, + tree_travel_attr=fluid.ParamAttr( + initializer=fluid.initializer.NumpyArrayInitializer( + travel_array)), + tree_layer_attr=fluid.ParamAttr( + initializer=fluid.initializer.NumpyArrayInitializer( + layer_array)), + output_positive=True, + output_list=True, + seed=0, + tree_dtype='int32') + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + xx = np.array([[0],[1]]).reshape((2,1)).astype("int32") + + exe.run(feed={"x":xx}) + + """ + helper = LayerHelper("tdm_sampler", **locals()) + check_dtype(tree_dtype, 'tree_dtype', ['int32', 'int64'], + 'fluid.contrib.layers.tdm_sampler') + check_dtype(dtype, 'dtype', ['int32', 'int64'], + 'fluid.contrib.layers.tdm_sampler') + c_dtype = convert_np_dtype_to_dtype_(dtype) + + if len(neg_samples_num_list) != len(layer_node_num_list): + raise ValueError( + "The shape of negative samples list must match the shape of layers. " + "But received len of neg_samples_num_list: {}," + "and len of layer_node_num_list: {}, please check your input.". + format(len(neg_samples_num_list), len(layer_node_num_list))) + assert leaf_node_num is not None, "leaf_node_num should not be None here." + + layer_nums = 0 + node_nums = 0 + tree_layer_offset_lod = [0] + for layer_idx, layer_node_num in enumerate(layer_node_num_list): + layer_nums += 1 + node_nums += layer_node_num + tree_layer_offset_lod.append(node_nums) + if neg_samples_num_list[layer_idx] >= layer_node_num_list[layer_idx]: + raise ValueError( + "The number of negative samples must be less than the number of nodes " + "in the layer {}, But received negative nums {}, and num of node at layer {} " + "is {}, please check your input.".format( + layer_idx, neg_samples_num_list[layer_idx], layer_idx, + layer_node_num_list[layer_idx])) + assert leaf_node_num < node_nums, "leaf_node_num must be less than total node nums." + + travel_shape = [leaf_node_num, layer_nums] + travel = helper.create_parameter(attr=tree_travel_attr, + shape=travel_shape, + dtype=tree_dtype, + default_initializer=Constant(0)) + + layer_shape = [node_nums, 1] + layer = helper.create_parameter(attr=tree_layer_attr, + shape=layer_shape, + dtype=tree_dtype, + default_initializer=Constant(0)) + + out = helper.create_variable_for_type_inference(dtype=dtype) + out.stop_gradient = True + + labels = helper.create_variable_for_type_inference(dtype=dtype) + labels.stop_gradient = True + + mask = helper.create_variable_for_type_inference(dtype=dtype) + mask.stop_gradient = True + + helper.append_op(type='tdm_sampler', + inputs={ + "X": x, + "Travel": travel, + "Layer": layer + }, + outputs={ + 'Out': out, + 'Labels': labels, + 'Mask': mask + }, + attrs={ + 'neg_samples_num_list': neg_samples_num_list, + 'output_positive': output_positive, + 'layer_offset_lod': tree_layer_offset_lod, + 'seed': seed, + 'dtype': c_dtype + }) + + if output_list: + output_list = [] + labels_list = [] + mask_list = [] + start_offset = 0 + positive_flag = 1 + if not output_positive: + positive_flag = 0 + + for layer_sample_num in neg_samples_num_list: + end_offset = start_offset + \ + layer_sample_num + positive_flag + layer_samples = slice(out, + axes=[1], + starts=[start_offset], + ends=[end_offset]) + layer_labels = slice(labels, + axes=[1], + starts=[start_offset], + ends=[end_offset]) + layer_mask = slice(mask, + axes=[1], + starts=[start_offset], + ends=[end_offset]) + + layer_samples = reshape(layer_samples, + [-1, layer_sample_num + positive_flag, 1]) + layer_samples.stop_gradient = True + + layer_labels = reshape(layer_labels, + [-1, layer_sample_num + positive_flag, 1]) + layer_labels.stop_gradient = True + + layer_mask = reshape(layer_mask, + [-1, layer_sample_num + positive_flag, 1]) + layer_mask.stop_gradient = True + + output_list.append(layer_samples) + labels_list.append(layer_labels) + mask_list.append(layer_mask) + start_offset = end_offset + + out = output_list + labels = labels_list + mask = mask_list + + return (out, labels, mask) + + +def rank_attention(input, + rank_offset, + rank_param_shape, + rank_param_attr, + max_rank=3, + max_size=0): + """ + **Rank Attention layer** + This Op can calculate rank attention between input and rank_param, and + rank_param gives the organization of data. Notice: It currently supports + GPU device. + This Op exists in contrib, which means that it is not shown to the public. + Args: + input: Tensor with data type float32, float64. + rank_offset: Tensor with data type int32. + rank_para_shape: The shape of rank_param. + rank_param_attr: Attribute initializer of rank_param. + max_rank: The max rank of input's ranks. + Returns: + Variable: A Tensor with the same data type as input's. + Examples: + .. code-block:: python + import paddle.fluid as fluid + import numpy as np + + input = fluid.data(name="input", shape=[None, 2], dtype="float32") + rank_offset = fluid.data(name="rank_offset", shape=[None, 7], dtype="int32") + out = fluid.contrib.layers.rank_attention(input=input, + rank_offset=rank_offset, + rank_param_shape=[18,3], + rank_param_attr= + fluid.ParamAttr(learning_rate=1.0, + name="ubm_rank_param.w_0", + initializer= + fluid.initializer.Xavier(uniform=False)), + max_rank=3, + max_size=0) + """ + helper = LayerHelper('rank_attention', **locals()) + dtype = helper.input_dtype(input_param_name='input') + input_shape = input.shape + assert input_shape[1] * max_rank * max_rank == rank_param_shape[0] + + rank_param = helper.create_parameter(attr=rank_param_attr, + shape=rank_param_shape, + dtype=dtype) + rank_param.stop_gradient = False + + output = helper.create_variable_for_type_inference(dtype) + input_help = helper.create_variable_for_type_inference(dtype=dtype, + stop_gradient=True) + ins_rank = helper.create_variable_for_type_inference(dtype=dtype, + stop_gradient=True) + + helper.append_op(type="rank_attention", + inputs={ + "X": input, + "RankOffset": rank_offset, + "RankParam": rank_param + }, + outputs={ + "Out": output, + "InputHelp": input_help, + "InsRank": ins_rank + }, + attrs={ + "MaxRank": max_rank, + "MaxSize": max_size + }) + return output + + +def batch_fc(input, param_size, param_attr, bias_size, bias_attr, act=None): + """ + **Batch FC layer** + This Op can calculate BatchFC. This is similar to matmul op, + except that the bias and relu activation layers are added. + Notice: It currently supports GPU device. + This Op exists in contrib, which means that it is not shown to the public. + Args: + input: Tensor with data type float32, float64. + param_size: The size of w. + param_attr: Attribute initializer of w. + bias_size: The size of bias. + bias_attr: Attribute initializer of bias. + act: Activation to be applied to the output of this layer. + + Returns: + Variable: A Tensor with the same data type as input's. + Examples: + .. code-block:: python + import paddle.fluid as fluid + + input = fluid.data(name="input", shape=[16, 2, 3], dtype="float32") + out = fluid.contrib.layers.batch_fc(input=input, + param_size=[16, 3, 10], + param_attr= + fluid.ParamAttr(learning_rate=1.0, + name="w_0", + initializer= + fluid.initializer.Xavier(uniform=False)), + bias_size=[16, 10], + bias_attr= + fluid.ParamAttr(learning_rate=1.0, + name="b_0", + initializer= + fluid.initializer.Xavier(uniform=False)), + act="relu") + """ + + helper = LayerHelper("batch_fc", **locals()) + check_type(input, 'input', (Variable), 'batch_fc') + input_shape = input.shape + assert input_shape[0] == param_size[0] + assert input_shape[2] == param_size[1] + assert param_size[2] == bias_size[1] + assert input_shape[0] == bias_size[0] + + dtype = helper.input_dtype() + check_dtype(dtype, 'input', ['float32', 'float64'], 'batch_fc') + + w = helper.create_parameter(attr=param_attr, + shape=param_size, + dtype=dtype, + is_bias=False) + b = helper.create_parameter(attr=bias_attr, + shape=bias_size, + dtype=dtype, + is_bias=False) + pre_act = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="batch_fc", + inputs={ + "Input": input, + "W": w, + "Bias": b + }, + outputs={"Out": pre_act}) + return helper.append_activation(pre_act) + + +def _pull_box_extended_sparse(input, size, extend_size=64, dtype='float32'): + r""" + **Pull Box Extended Sparse Layer** + This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in + BoxPS lookup table. The result of this lookup is the embedding of each ID in the + :attr:`input`. + Args: + input(Variable|list of Variable): Input is a Tensor Variable, which + contains the IDs information. + size(int): The embedding size parameter, which indicates the size of + each embedding vector respectively. + extend_size(int): The embedding size parameter in extended dim, + which indicates the size of each embedding vector respectively. + dtype(str): The dtype refers to the data type of output tensor. Only supports + float32 now. + Returns: + Variable|list of Variable: The tensor variable storing the embeddings of the \ + supplied inputs. + Examples: + .. code-block:: python + import paddle.fluid as fluid + data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + emb, emb_ex = fluid.contrib.layers._pull_box_extended_sparse(input=data, size=8, extend_size=128) + """ + helper = LayerHelper('pull_box_extended_sparse', **locals()) + helper.input_dtype() + inputs = helper.multiple_input() + outs = [ + helper.create_variable_for_type_inference(dtype) + for i in range(len(inputs)) + ] + outs_extend = [ + helper.create_variable_for_type_inference(dtype) + for i in range(len(inputs)) + ] + helper.append_op(type='pull_box_extended_sparse', + inputs={'Ids': inputs}, + outputs={ + 'Out': outs, + 'OutExtend': outs_extend + }, + attrs={ + 'emb_size': size, + 'emb_extended_size': extend_size + }) + if len(outs) == 1: + return outs[0], outs_extend[0] + return outs, outs_extend + + +def bilateral_slice(x, guide, grid, has_offset, name=None): + """ + :alias_main: paddle.nn.functional.bilateral_slice + :alias: paddle.nn.functional.bilateral_slice,paddle.nn.functional.vision.bilateral_slice + :old_api: paddle.fluid.layers.bilateral_slice + + This operation implements bilateral slicing on the input according to the guide map. + For more information of bilateral slicing, please refer to Deep Bilateral Learning for Real-Time Image Enhancement _ + + Args: + x(Variable): The input tensor, which is a 4-D tensor with shape + [N, C, H, W], N is the batch size, C is the channel + number, H and W is the feature height and width. + The data type is float32 and float64. + guide(Variable): Input grid tensor of shape [N, H, W]. The + data type is float32 and float64. + grid(Variable): Input grid tensor of shape [N, C, D, H, W]. The + data type is float32 and float64. + has_offset(bool): Whether to slice with affine offset. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: Output of shape [N, C, H, W]. The data type is same as input tensor. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data(name='x', shape=[None, 3, 101, 60], dtype='float32') + guide = fluid.data(name='guide', shape=[None, 101, 60], dtype='float32') + grid = fluid.data(name='grid', shape=[None, 12, 8, 10, 6], dtype='float32') + + # without offset + output = fluid.contrib.bilateral_slice(x, guide, grid, has_offset=False) + + # has offset + output = fluid.contrib.bilateral_slice(x, guide, grid, has_offset=True) + + """ + if paddle.fluid._non_static_mode(): + attrs = ('has_offset', has_offset) + return getattr(_legacy_C_ops, "bilateral_slice")(x, grid, guide, *attrs) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'bilateral_slice') + check_variable_and_dtype(guide, 'guide', ['float32', 'float64'], + 'bilateral_slice') + check_variable_and_dtype(grid, 'grid', ['float32', 'float64'], + 'bilateral_slice') + helper = LayerHelper("bilateral_slice", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + inputs = {'X': x, 'Guide': guide, 'Grid': grid} + helper.append_op(type='bilateral_slice', + inputs=inputs, + attrs={'has_offset': has_offset}, + outputs={'Out': out}) + return out + + +def correlation(x, + y, + pad_size, + kernel_size, + max_displacement, + stride1, + stride2, + corr_type_multiply=1): + """ + + This operation compute correlation of two tensor. + For more information of correlation, please refer to PWC-Net: + CNNs for Optical Flow Using Pyramid, Warping, and Cost Volume + _ + + Args: + x(Tensor): The input x is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64. + y(Tensor): The input y is 4-D Tensor with shape [N, C, H, W]. The data type is float32 and float64. + pad_size(int): Pad size. The data type is int. + max_displacement(int): Max displacement. The data type is int. + stride1(int): stride size of x. The data type is int. + stride2(int): stride size of y. The data type is int. + corr_type_multiply(int, optional): The type of multiply. The data type is int. Default: 1. + + Returns: + Tensor: The data type is same as input tensor. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + x1 = fluid.layers.data(name='x1', + shape=x_shape, + dtype=x_type, + append_batch_size=False) + x2 = fluid.layers.data(name='x2', + shape=x_shape, + dtype=x_type, + append_batch_size=False) + + + out = fluid.contrib.correlation( + x1, + x2, + pad_size=4, + kernel_size=1, + max_displacement=4, + stride1=1, + stride2=1) + + """ + + if paddle.fluid._non_static_mode(): + attrs = ("pad_size", pad_size, "kernel_size", kernel_size, + "max_displacement", max_displacement, "stride1", stride1, + "stride2", stride2, "corr_type_multiply", corr_type_multiply) + output = getattr(_legacy_C_ops, "correlation")(x, y, *attrs) + else: + helper = LayerHelper("correlation", **locals()) + output = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type="correlation", + inputs={ + "Input1": x, + "Input2": y + }, + attrs={ + "pad_size": pad_size, + "kernel_size": kernel_size, + "max_displacement": max_displacement, + "stride1": stride1, + "stride2": stride2, + "corr_type_multiply": corr_type_multiply + }, + outputs={"Output": output}) + return output + + +def fused_bn_add_act(x, + y, + momentum=0.9, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + moving_mean_name=None, + moving_variance_name=None, + act=None, + name=None): + r""" + This Op performs batch norm on input x, and adds the result to input y. Then + it performs activation on the sum. The data format of inputs must be NHWC + `[batch, in_height, in_width, in_channels]`. + + Args: + x(Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type + is float16. + y(Tensor): The rank of input tensor can be 2, 3, 4, 5. The data type + is float16. + momentum(float|Tensor, optional): The value used for the moving_mean and + moving_var computation. This should be a float number or a tensor with + shape [1] and data type as float32. The updated formula is: + :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` + :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` + Default is 0.9. + epsilon(float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + param_attr(ParamAttr, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. + If the Initializer of the param_attr is not set, the parameter is initialized + with Xavier. Default: None. + bias_attr(ParamAttr, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + Default: None. + moving_mean_name(str, optional): The name of moving_mean which store the global Mean. If it + is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm + will save global mean with the string. + moving_variance_name(str, optional): The name of the moving_variance which store the global Variance. + If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm + will save global variance with the string. + act(string, optional): Activation type, linear|relu|prelu|... + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + def build_program(main_program, startup_program): + with fluid.program_guard(main_program, startup_program): + x = fluid.layers.data(name='x', shape=[1, 28, 28], dtype='float32') + y = fluid.layers.data(name="y", shape=[1], dtype='int64') + conv1_1 = fluid.layers.conv2d( + input=x, + filter_size=3, + num_filters=32, + stride=1, + padding=1, + act=None, + bias_attr=False, + data_format='NHWC') + conv1_2 = fluid.layers.conv2d( + input=x, + filter_size=3, + num_filters=32, + stride=1, + padding=1, + act=None, + bias_attr=False, + data_format='NHWC') + bn = fluid.layers.batch_norm( + input=conv1_1, + act=None, + data_layout='NHWC') + fused_bn_add_act = fluid.contrib.layers.fused_bn_add_act(conv1_2, bn) + prediction = fluid.layers.fc(input=fused_bn_add_act, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=prediction, label=y) + loss = fluid.layers.mean(loss) + sgd = fluid.optimizer.SGD(learning_rate=0.001) + sgd = fluid.contrib.mixed_precision.decorate( + sgd, use_dynamic_loss_scaling=True, init_loss_scaling=128.0) + sgd.minimize(loss) + + return x, y, loss + + iters = 5 + batch_size = 16 + support_gpu = fluid.is_compiled_with_cuda() + if support_gpu: + main_program = fluid.Program() + startup_program = fluid.Program() + place = fluid.CUDAPlace(0) + x, y, loss = build_program(main_program, startup_program) + + feeder = fluid.DataFeeder(feed_list=[x, y], place=place) + train_reader = paddle.batch( + paddle.dataset.mnist.train(), batch_size=batch_size) + exe = fluid.Executor(place) + scope = fluid.Scope() + with fluid.scope_guard(scope): + exe.run(startup_program) + for _ in range(iters): + data = next(train_reader()) + loss_v = exe.run(main_program, feed=feeder.feed(data), fetch_list=[loss]) + """ + helper = LayerHelper('fused_bn_add_act', **locals()) + + check_variable_and_dtype(x, 'input', ['float16', 'float32', 'float64'], + 'fused_bn_add_act') + check_variable_and_dtype(y, 'input', ['float16', 'float32', 'float64'], + 'fused_bn_add_act') + bn_param_dtype = core.VarDesc.VarType.FP32 + + x_shape = x.shape + channel_num = x_shape[-1] + param_shape = [channel_num] + + # create parameter + scale = helper.create_parameter(attr=helper.param_attr, + shape=param_shape, + dtype=bn_param_dtype, + default_initializer=Constant(1.0)) + bias = helper.create_parameter(attr=helper.bias_attr, + shape=param_shape, + dtype=bn_param_dtype, + is_bias=True) + mean = helper.create_parameter(attr=ParamAttr(name=moving_mean_name, + initializer=Constant(0.0), + trainable=False), + shape=param_shape, + dtype=bn_param_dtype) + mean.stop_gradient = True + variance = helper.create_parameter(attr=ParamAttr(name=moving_variance_name, + initializer=Constant(1.0), + trainable=False), + shape=param_shape, + dtype=bn_param_dtype) + variance.stop_gradient = True + + # create output + # mean and mean_out share the same memory + mean_out = mean + # variance and variance out share the same memory + variance_out = variance + saved_mean = helper.create_variable_for_type_inference(dtype=bn_param_dtype, + stop_gradient=True) + saved_variance = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) + reserve_space = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.FP16, stop_gradient=True) + batch_norm_out = helper.create_variable_for_type_inference( + core.VarDesc.VarType.FP16) + + inputs = { + "X": x, + "Z": y, + "Scale": scale, + "Bias": bias, + } + attrs = {"epsilon": epsilon, 'momentum': momentum} + + outputs = { + "Y": batch_norm_out, + "MeanOut": mean_out, + "VarianceOut": variance_out, + "SavedMean": saved_mean, + "SavedVariance": saved_variance, + "ReserveSpace": reserve_space + } + + helper.append_op(type="fused_bn_add_activation", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return batch_norm_out + + +def pow2_decay_with_linear_warmup(warmup_steps, + total_steps, + base_lr, + end_lr, + dtype='float32', + name=None): + if paddle.fluid._non_static_mode(): + raise NotImplementedError( + "pow2_decay_with_linear_warmup does not support dygraph mode yet.") + + helper = LayerHelper("pow2_decay_with_linear_warmup", **locals()) + lr = helper.create_global_variable(persistable=True, dtype=dtype, shape=[1]) + helper.set_variable_initializer( + lr, Constant(value=float(base_lr) / warmup_steps)) + + step = helper.create_global_variable(persistable=True, + dtype='int64', + shape=[1]) + helper.set_variable_initializer(step, Constant(value=0)) + assert warmup_steps <= total_steps, "warmup_steps cannot be larger than total_steps" + + helper.append_op(type="pow2_decay_with_linear_warmup", + inputs={ + "LearningRate": lr, + "Step": step + }, + outputs={ + "LearningRateOut": lr, + "StepOut": step + }, + attrs={ + "warmup_steps": warmup_steps, + "total_steps": total_steps, + "base_lr": base_lr, + "end_lr": end_lr, + }) + return lr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/rnn_impl.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/rnn_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..0b14948bff9849533e66e73001a32a08a2264af9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/layers/rnn_impl.py @@ -0,0 +1,826 @@ +# 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. + +import copy + +from paddle.fluid import layers, unique_name +from paddle.fluid.dygraph import Layer +from paddle.fluid.dygraph.layer_object_helper import LayerObjectHelper +from paddle.fluid.layers.control_flow import StaticRNN + +__all__ = ['BasicGRUUnit', 'basic_gru', 'BasicLSTMUnit', 'basic_lstm'] + + +class BasicGRUUnit(Layer): + """ + **** + BasicGRUUnit class, using basic operators to build GRU + The algorithm can be described as the equations below. + + .. math:: + u_t & = actGate(W_ux xu_{t} + W_uh h_{t-1} + b_u) + + r_t & = actGate(W_rx xr_{t} + W_rh h_{t-1} + b_r) + + m_t & = actNode(W_cx xm_t + W_ch dot(r_t, h_{t-1}) + b_m) + + h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t) + + Args: + name_scope(string) : The name scope used to identify parameters and biases + hidden_size (integer): The hidden size used in the Unit. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, gru_unit will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of GRU unit. + If it is set to None or one attribute of ParamAttr, gru_unit will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cell (actNode). + Default: 'fluid.layers.tanh' + dtype(string): data type used in this unit + + Examples: + + .. code-block:: python + + import paddle.fluid.layers as layers + from paddle.fluid.contrib.layers import BasicGRUUnit + + input_size = 128 + hidden_size = 256 + input = layers.data( name = "input", shape = [-1, input_size], dtype='float32') + pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32') + + gru_unit = BasicGRUUnit( "gru_unit", hidden_size ) + + new_hidden = gru_unit( input, pre_hidden ) + + """ + + def __init__(self, + name_scope, + hidden_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + dtype='float32'): + super(BasicGRUUnit, self).__init__(name_scope, dtype) + # reserve old school _full_name and _helper for static graph save load + self._full_name = unique_name.generate(name_scope + "/" + + self.__class__.__name__) + self._helper = LayerObjectHelper(self._full_name) + + self._name = name_scope + self._hiden_size = hidden_size + self._param_attr = param_attr + self._bias_attr = bias_attr + self._gate_activation = gate_activation or layers.sigmoid + self._activation = activation or layers.tanh + self._dtype = dtype + + def _build_once(self, input, pre_hidden): + self._input_size = input.shape[-1] + assert (self._input_size > 0) + + if self._param_attr is not None and self._param_attr.name is not None: + gate_param_attr = copy.deepcopy(self._param_attr) + candidate_param_attr = copy.deepcopy(self._param_attr) + gate_param_attr.name += "_gate" + candidate_param_attr.name += "_candidate" + else: + gate_param_attr = self._param_attr + candidate_param_attr = self._param_attr + + self._gate_weight = self.create_parameter( + attr=gate_param_attr, + shape=[self._input_size + self._hiden_size, 2 * self._hiden_size], + dtype=self._dtype) + + self._candidate_weight = self.create_parameter( + attr=candidate_param_attr, + shape=[self._input_size + self._hiden_size, self._hiden_size], + dtype=self._dtype) + + if self._bias_attr is not None and self._bias_attr.name is not None: + gate_bias_attr = copy.deepcopy(self._bias_attr) + candidate_bias_attr = copy.deepcopy(self._bias_attr) + gate_bias_attr.name += "_gate" + candidate_bias_attr.name += "_candidate" + else: + gate_bias_attr = self._bias_attr + candidate_bias_attr = self._bias_attr + + self._gate_bias = self.create_parameter(attr=gate_bias_attr, + shape=[2 * self._hiden_size], + dtype=self._dtype, + is_bias=True) + self._candidate_bias = self.create_parameter(attr=candidate_bias_attr, + shape=[self._hiden_size], + dtype=self._dtype, + is_bias=True) + + def forward(self, input, pre_hidden): + concat_input_hidden = layers.concat([input, pre_hidden], 1) + + gate_input = layers.matmul(x=concat_input_hidden, y=self._gate_weight) + + gate_input = layers.elementwise_add(gate_input, self._gate_bias) + + gate_input = self._gate_activation(gate_input) + r, u = layers.split(gate_input, num_or_sections=2, dim=1) + + r_hidden = r * pre_hidden + + candidate = layers.matmul(layers.concat([input, r_hidden], 1), + self._candidate_weight) + candidate = layers.elementwise_add(candidate, self._candidate_bias) + + c = self._activation(candidate) + new_hidden = u * pre_hidden + (1 - u) * c + + return new_hidden + + +def basic_gru(input, + init_hidden, + hidden_size, + num_layers=1, + sequence_length=None, + dropout_prob=0.0, + bidirectional=False, + batch_first=True, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + dtype='float32', + name='basic_gru'): + r""" + GRU implementation using basic operator, supports multiple layers and bidirectional gru. + + .. math:: + u_t & = actGate(W_ux xu_{t} + W_uh h_{t-1} + b_u) + + r_t & = actGate(W_rx xr_{t} + W_rh h_{t-1} + b_r) + + m_t & = actNode(W_cx xm_t + W_ch dot(r_t, h_{t-1}) + b_m) + + h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t) + + Args: + input (Variable): GRU input tensor, + if batch_first = False, shape should be ( seq_len x batch_size x input_size ) + if batch_first = True, shape should be ( batch_size x seq_len x hidden_size ) + init_hidden(Variable|None): The initial hidden state of the GRU + This is a tensor with shape ( num_layers x batch_size x hidden_size) + if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size) + and can be reshaped to tensor with ( num_layers x 2 x batch_size x hidden_size) to use. + If it's None, it will be set to all 0. + hidden_size (int): Hidden size of the GRU + num_layers (int): The total number of layers of the GRU + sequence_length (Variabe|None): A Tensor (shape [batch_size]) stores each real length of each instance, + This tensor will be convert to a mask to mask the padding ids + If it's None means NO padding ids + dropout_prob(float|0.0): Dropout prob, dropout ONLY works after rnn output of each layers, + NOT between time steps + bidirectional (bool|False): If it is bidirectional + batch_first (bool|True): The shape format of the input and output tensors. If true, + the shape format should be :attr:`[batch_size, seq_len, hidden_size]`. If false, + the shape format should be :attr:`[seq_len, batch_size, hidden_size]`. By default + this function accepts input and emits output in batch-major form to be consistent + with most of data format, though a bit less efficient because of extra transposes. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, gru_unit will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of GRU unit. + If it is set to None or one attribute of ParamAttr, gru_unit will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cell (actNode). + Default: 'fluid.layers.tanh' + dtype(string): data type used in this unit + name(string): name used to identify parameters and biases + + Returns: + rnn_out(Tensor),last_hidden(Tensor) + - rnn_out is result of GRU hidden, with shape (seq_len x batch_size x hidden_size) \ + if is_bidirec set to True, shape will be ( seq_len x batch_sze x hidden_size*2) + - last_hidden is the hidden state of the last step of GRU \ + shape is ( num_layers x batch_size x hidden_size ) \ + if is_bidirec set to True, shape will be ( num_layers*2 x batch_size x hidden_size), + can be reshaped to a tensor with shape( num_layers x 2 x batch_size x hidden_size) + + Examples: + .. code-block:: python + + import paddle.fluid.layers as layers + from paddle.fluid.contrib.layers import basic_gru + + batch_size = 20 + input_size = 128 + hidden_size = 256 + num_layers = 2 + dropout = 0.5 + bidirectional = True + batch_first = False + + input = layers.data( name = "input", shape = [-1, batch_size, input_size], dtype='float32') + pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32') + sequence_length = layers.data( name="sequence_length", shape=[-1], dtype='int32') + + + rnn_out, last_hidden = basic_gru( input, pre_hidden, hidden_size, num_layers = num_layers, \ + sequence_length = sequence_length, dropout_prob=dropout, bidirectional = bidirectional, \ + batch_first = batch_first) + + """ + + fw_unit_list = [] + + for i in range(num_layers): + new_name = name + "_layers_" + str(i) + if param_attr is not None and param_attr.name is not None: + layer_param_attr = copy.deepcopy(param_attr) + layer_param_attr.name += "_fw_w_" + str(i) + else: + layer_param_attr = param_attr + if bias_attr is not None and bias_attr.name is not None: + layer_bias_attr = copy.deepcopy(bias_attr) + layer_bias_attr.name += "_fw_b_" + str(i) + else: + layer_bias_attr = bias_attr + fw_unit_list.append( + BasicGRUUnit(new_name, hidden_size, layer_param_attr, + layer_bias_attr, gate_activation, activation, dtype)) + if bidirectional: + bw_unit_list = [] + + for i in range(num_layers): + new_name = name + "_reverse_layers_" + str(i) + if param_attr is not None and param_attr.name is not None: + layer_param_attr = copy.deepcopy(param_attr) + layer_param_attr.name += "_bw_w_" + str(i) + else: + layer_param_attr = param_attr + if bias_attr is not None and bias_attr.name is not None: + layer_bias_attr = copy.deepcopy(bias_attr) + layer_bias_attr.name += "_bw_b_" + str(i) + else: + layer_bias_attr = bias_attr + + bw_unit_list.append( + BasicGRUUnit(new_name, hidden_size, layer_param_attr, + layer_bias_attr, gate_activation, activation, + dtype)) + + if batch_first: + input = layers.transpose(input, [1, 0, 2]) + + mask = None + if sequence_length: + max_seq_len = layers.shape(input)[0] + mask = layers.sequence_mask(sequence_length, + maxlen=max_seq_len, + dtype='float32') + mask = layers.transpose(mask, [1, 0]) + + direc_num = 1 + if bidirectional: + direc_num = 2 + if init_hidden: + init_hidden = layers.reshape( + init_hidden, shape=[num_layers, direc_num, -1, hidden_size]) + + def get_single_direction_output(rnn_input, + unit_list, + mask=None, + direc_index=0): + rnn = StaticRNN() + with rnn.step(): + step_input = rnn.step_input(rnn_input) + + if mask: + step_mask = rnn.step_input(mask) + + for i in range(num_layers): + if init_hidden: + pre_hidden = rnn.memory(init=init_hidden[i, direc_index]) + else: + pre_hidden = rnn.memory(batch_ref=rnn_input, + shape=[-1, hidden_size], + ref_batch_dim_idx=1) + + new_hidden = unit_list[i](step_input, pre_hidden) + + if mask: + new_hidden = layers.elementwise_mul( + new_hidden, step_mask, axis=0) - layers.elementwise_mul( + pre_hidden, (step_mask - 1), axis=0) + rnn.update_memory(pre_hidden, new_hidden) + + rnn.step_output(new_hidden) + + step_input = new_hidden + if dropout_prob != None and dropout_prob > 0.0: + step_input = layers.dropout( + step_input, + dropout_prob=dropout_prob, + ) + + rnn.step_output(step_input) + + rnn_out = rnn() + + last_hidden_array = [] + rnn_output = rnn_out[-1] + for i in range(num_layers): + last_hidden = rnn_out[i] + last_hidden = last_hidden[-1] + last_hidden_array.append(last_hidden) + + last_hidden_output = layers.concat(last_hidden_array, axis=0) + last_hidden_output = layers.reshape(last_hidden_output, + shape=[num_layers, -1, hidden_size]) + + return rnn_output, last_hidden_output + # seq_len, batch_size, hidden_size + + fw_rnn_out, fw_last_hidden = get_single_direction_output(input, + fw_unit_list, + mask, + direc_index=0) + + if bidirectional: + bw_input = layers.reverse(input, axis=[0]) + bw_mask = None + if mask: + bw_mask = layers.reverse(mask, axis=[0]) + bw_rnn_out, bw_last_hidden = get_single_direction_output(bw_input, + bw_unit_list, + bw_mask, + direc_index=1) + + bw_rnn_out = layers.reverse(bw_rnn_out, axis=[0]) + + rnn_out = layers.concat([fw_rnn_out, bw_rnn_out], axis=2) + last_hidden = layers.concat([fw_last_hidden, bw_last_hidden], axis=1) + + last_hidden = layers.reshape( + last_hidden, shape=[num_layers * direc_num, -1, hidden_size]) + + if batch_first: + rnn_out = layers.transpose(rnn_out, [1, 0, 2]) + return rnn_out, last_hidden + else: + + rnn_out = fw_rnn_out + last_hidden = fw_last_hidden + + if batch_first: + rnn_out = layers.transpose(rnn_out, [1, 0, 2]) + + return rnn_out, last_hidden + + +def basic_lstm(input, + init_hidden, + init_cell, + hidden_size, + num_layers=1, + sequence_length=None, + dropout_prob=0.0, + bidirectional=False, + batch_first=True, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + forget_bias=1.0, + dtype='float32', + name='basic_lstm'): + r""" + LSTM implementation using basic operators, supports multiple layers and bidirectional LSTM. + + .. math:: + i_t &= \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_i) + + f_t &= \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_f + forget_bias ) + + o_t &= \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_o) + + \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + b_c) + + c_t &= f_t \odot c_{t-1} + i_t \odot \\tilde{c_t} + + h_t &= o_t \odot tanh(c_t) + + Args: + input (Variable): lstm input tensor, + if batch_first = False, shape should be ( seq_len x batch_size x input_size ) + if batch_first = True, shape should be ( batch_size x seq_len x hidden_size ) + init_hidden(Variable|None): The initial hidden state of the LSTM + This is a tensor with shape ( num_layers x batch_size x hidden_size) + if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size) + and can be reshaped to a tensor with shape ( num_layers x 2 x batch_size x hidden_size) to use. + If it's None, it will be set to all 0. + init_cell(Variable|None): The initial hidden state of the LSTM + This is a tensor with shape ( num_layers x batch_size x hidden_size) + if is_bidirec = True, shape should be ( num_layers*2 x batch_size x hidden_size) + and can be reshaped to a tensor with shape ( num_layers x 2 x batch_size x hidden_size) to use. + If it's None, it will be set to all 0. + hidden_size (int): Hidden size of the LSTM + num_layers (int): The total number of layers of the LSTM + sequence_length (Variabe|None): A tensor (shape [batch_size]) stores each real length of each instance, + This tensor will be convert to a mask to mask the padding ids + If it's None means NO padding ids + dropout_prob(float|0.0): Dropout prob, dropout ONLY work after rnn output of each layers, + NOT between time steps + bidirectional (bool|False): If it is bidirectional + batch_first (bool|True): The shape format of the input and output tensors. If true, + the shape format should be :attr:`[batch_size, seq_len, hidden_size]`. If false, + the shape format should be :attr:`[seq_len, batch_size, hidden_size]`. By default + this function accepts input and emits output in batch-major form to be consistent + with most of data format, though a bit less efficient because of extra transposes. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, lstm_unit will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of LSTM unit. + If it is set to None or one attribute of ParamAttr, lstm_unit will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cell (actNode). + Default: 'fluid.layers.tanh' + forget_bias (float|1.0) : Forget bias used to compute the forget gate + dtype(string): Data type used in this unit + name(string): Name used to identify parameters and biases + + Returns: + rnn_out(Tensor), last_hidden(Tensor), last_cell(Tensor) + - rnn_out is the result of LSTM hidden, shape is (seq_len x batch_size x hidden_size) \ + if is_bidirec set to True, it's shape will be ( seq_len x batch_sze x hidden_size*2) + - last_hidden is the hidden state of the last step of LSTM \ + with shape ( num_layers x batch_size x hidden_size ) \ + if is_bidirec set to True, it's shape will be ( num_layers*2 x batch_size x hidden_size), + and can be reshaped to a tensor ( num_layers x 2 x batch_size x hidden_size) to use. + - last_cell is the hidden state of the last step of LSTM \ + with shape ( num_layers x batch_size x hidden_size ) \ + if is_bidirec set to True, it's shape will be ( num_layers*2 x batch_size x hidden_size), + and can be reshaped to a tensor ( num_layers x 2 x batch_size x hidden_size) to use. + + Examples: + .. code-block:: python + + import paddle.fluid.layers as layers + from paddle.fluid.contrib.layers import basic_lstm + + batch_size = 20 + input_size = 128 + hidden_size = 256 + num_layers = 2 + dropout = 0.5 + bidirectional = True + batch_first = False + + input = layers.data( name = "input", shape = [-1, batch_size, input_size], dtype='float32') + pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32') + pre_cell = layers.data( name = "pre_cell", shape=[-1, hidden_size], dtype='float32') + sequence_length = layers.data( name="sequence_length", shape=[-1], dtype='int32') + + rnn_out, last_hidden, last_cell = basic_lstm( input, pre_hidden, pre_cell, \ + hidden_size, num_layers = num_layers, \ + sequence_length = sequence_length, dropout_prob=dropout, bidirectional = bidirectional, \ + batch_first = batch_first) + + """ + fw_unit_list = [] + + for i in range(num_layers): + new_name = name + "_layers_" + str(i) + if param_attr is not None and param_attr.name is not None: + layer_param_attr = copy.deepcopy(param_attr) + layer_param_attr.name += "_fw_w_" + str(i) + else: + layer_param_attr = param_attr + if bias_attr is not None and bias_attr.name is not None: + layer_bias_attr = copy.deepcopy(bias_attr) + layer_bias_attr.name += "_fw_b_" + str(i) + else: + layer_bias_attr = bias_attr + fw_unit_list.append( + BasicLSTMUnit(new_name, + hidden_size, + param_attr=layer_param_attr, + bias_attr=layer_bias_attr, + gate_activation=gate_activation, + activation=activation, + forget_bias=forget_bias, + dtype=dtype)) + if bidirectional: + bw_unit_list = [] + + for i in range(num_layers): + new_name = name + "_reverse_layers_" + str(i) + if param_attr is not None and param_attr.name is not None: + layer_param_attr = copy.deepcopy(param_attr) + layer_param_attr.name += "_bw_w_" + str(i) + else: + layer_param_attr = param_attr + if bias_attr is not None and bias_attr.name is not None: + layer_bias_attr = copy.deepcopy(bias_attr) + layer_bias_attr.name += "_bw_b_" + str(i) + else: + layer_bias_attr = param_attr + bw_unit_list.append( + BasicLSTMUnit(new_name, + hidden_size, + param_attr=layer_param_attr, + bias_attr=layer_bias_attr, + gate_activation=gate_activation, + activation=activation, + forget_bias=forget_bias, + dtype=dtype)) + + if batch_first: + input = layers.transpose(input, [1, 0, 2]) + + mask = None + if sequence_length: + max_seq_len = layers.shape(input)[0] + mask = layers.sequence_mask(sequence_length, + maxlen=max_seq_len, + dtype='float32') + + mask = layers.transpose(mask, [1, 0]) + + direc_num = 1 + if bidirectional: + direc_num = 2 + # convert to [num_layers, 2, batch_size, hidden_size] + if init_hidden: + init_hidden = layers.reshape( + init_hidden, shape=[num_layers, direc_num, -1, hidden_size]) + init_cell = layers.reshape( + init_cell, shape=[num_layers, direc_num, -1, hidden_size]) + + # forward direction + def get_single_direction_output(rnn_input, + unit_list, + mask=None, + direc_index=0): + rnn = StaticRNN() + with rnn.step(): + step_input = rnn.step_input(rnn_input) + + if mask: + step_mask = rnn.step_input(mask) + + for i in range(num_layers): + if init_hidden: + pre_hidden = rnn.memory(init=init_hidden[i, direc_index]) + pre_cell = rnn.memory(init=init_cell[i, direc_index]) + else: + pre_hidden = rnn.memory(batch_ref=rnn_input, + shape=[-1, hidden_size]) + pre_cell = rnn.memory(batch_ref=rnn_input, + shape=[-1, hidden_size]) + + new_hidden, new_cell = unit_list[i](step_input, pre_hidden, + pre_cell) + + if mask: + new_hidden = layers.elementwise_mul( + new_hidden, step_mask, axis=0) - layers.elementwise_mul( + pre_hidden, (step_mask - 1), axis=0) + new_cell = layers.elementwise_mul( + new_cell, step_mask, axis=0) - layers.elementwise_mul( + pre_cell, (step_mask - 1), axis=0) + + rnn.update_memory(pre_hidden, new_hidden) + rnn.update_memory(pre_cell, new_cell) + + rnn.step_output(new_hidden) + rnn.step_output(new_cell) + + step_input = new_hidden + if dropout_prob != None and dropout_prob > 0.0: + step_input = layers.dropout( + step_input, + dropout_prob=dropout_prob, + dropout_implementation='upscale_in_train') + + rnn.step_output(step_input) + + rnn_out = rnn() + + last_hidden_array = [] + last_cell_array = [] + rnn_output = rnn_out[-1] + for i in range(num_layers): + last_hidden = rnn_out[i * 2] + last_hidden = last_hidden[-1] + last_hidden_array.append(last_hidden) + last_cell = rnn_out[i * 2 + 1] + last_cell = last_cell[-1] + last_cell_array.append(last_cell) + + last_hidden_output = layers.concat(last_hidden_array, axis=0) + last_hidden_output = layers.reshape(last_hidden_output, + shape=[num_layers, -1, hidden_size]) + last_cell_output = layers.concat(last_cell_array, axis=0) + last_cell_output = layers.reshape(last_cell_output, + shape=[num_layers, -1, hidden_size]) + + return rnn_output, last_hidden_output, last_cell_output + # seq_len, batch_size, hidden_size + + fw_rnn_out, fw_last_hidden, fw_last_cell = get_single_direction_output( + input, fw_unit_list, mask, direc_index=0) + + if bidirectional: + bw_input = layers.reverse(input, axis=[0]) + bw_mask = None + if mask: + bw_mask = layers.reverse(mask, axis=[0]) + bw_rnn_out, bw_last_hidden, bw_last_cell = get_single_direction_output( + bw_input, bw_unit_list, bw_mask, direc_index=1) + + bw_rnn_out = layers.reverse(bw_rnn_out, axis=[0]) + + rnn_out = layers.concat([fw_rnn_out, bw_rnn_out], axis=2) + last_hidden = layers.concat([fw_last_hidden, bw_last_hidden], axis=1) + last_hidden = layers.reshape( + last_hidden, shape=[num_layers * direc_num, -1, hidden_size]) + + last_cell = layers.concat([fw_last_cell, bw_last_cell], axis=1) + last_cell = layers.reshape( + last_cell, shape=[num_layers * direc_num, -1, hidden_size]) + + if batch_first: + rnn_out = layers.transpose(rnn_out, [1, 0, 2]) + return rnn_out, last_hidden, last_cell + else: + + rnn_out = fw_rnn_out + last_hidden = fw_last_hidden + last_cell = fw_last_cell + + if batch_first: + rnn_out = layers.transpose(rnn_out, [1, 0, 2]) + + return rnn_out, last_hidden, last_cell + + +class BasicLSTMUnit(Layer): + r""" + **** + BasicLSTMUnit class, Using basic operator to build LSTM + The algorithm can be described as the code below. + + .. math:: + + i_t &= \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_i) + + f_t &= \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_f + forget_bias ) + + o_t &= \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_o) + + \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + b_c) + + c_t &= f_t \odot c_{t-1} + i_t \odot \\tilde{c_t} + + h_t &= o_t \odot tanh(c_t) + + - $W$ terms denote weight matrices (e.g. $W_{ix}$ is the matrix + of weights from the input gate to the input) + - The b terms denote bias vectors ($bx_i$ and $bh_i$ are the input gate bias vector). + - sigmoid is the logistic sigmoid function. + - $i, f, o$ and $c$ are the input gate, forget gate, output gate, + and cell activation vectors, respectively, all of which have the same size as + the cell output activation vector $h$. + - The :math:`\odot` is the element-wise product of the vectors. + - :math:`tanh` is the activation functions. + - :math:`\\tilde{c_t}` is also called candidate hidden state, + which is computed based on the current input and the previous hidden state. + + Args: + name_scope(string) : The name scope used to identify parameter and bias name + hidden_size (integer): The hidden size used in the Unit. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, lstm_unit will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of LSTM unit. + If it is set to None or one attribute of ParamAttr, lstm_unit will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized as zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cells (actNode). + Default: 'fluid.layers.tanh' + forget_bias(float|1.0): forget bias used when computing forget gate + dtype(string): data type used in this unit + + Examples: + + .. code-block:: python + + import paddle.fluid.layers as layers + from paddle.fluid.contrib.layers import BasicLSTMUnit + + input_size = 128 + hidden_size = 256 + input = layers.data( name = "input", shape = [-1, input_size], dtype='float32') + pre_hidden = layers.data( name = "pre_hidden", shape=[-1, hidden_size], dtype='float32') + pre_cell = layers.data( name = "pre_cell", shape=[-1, hidden_size], dtype='float32') + + lstm_unit = BasicLSTMUnit( "gru_unit", hidden_size) + + new_hidden, new_cell = lstm_unit( input, pre_hidden, pre_cell ) + + """ + + def __init__(self, + name_scope, + hidden_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + forget_bias=1.0, + dtype='float32'): + super(BasicLSTMUnit, self).__init__(name_scope, dtype) + # reserve old school _full_name and _helper for static graph save load + self._full_name = unique_name.generate(name_scope + "/" + + self.__class__.__name__) + self._helper = LayerObjectHelper(self._full_name) + + self._name = name_scope + self._hiden_size = hidden_size + self._param_attr = param_attr + self._bias_attr = bias_attr + self._gate_activation = gate_activation or layers.sigmoid + self._activation = activation or layers.tanh + self._forget_bias = layers.fill_constant([1], + dtype=dtype, + value=forget_bias) + self._forget_bias.stop_gradient = False + self._dtype = dtype + + def _build_once(self, input, pre_hidden, pre_cell): + self._input_size = input.shape[-1] + assert (self._input_size > 0) + + self._weight = self.create_parameter( + attr=self._param_attr, + shape=[self._input_size + self._hiden_size, 4 * self._hiden_size], + dtype=self._dtype) + + self._bias = self.create_parameter(attr=self._bias_attr, + shape=[4 * self._hiden_size], + dtype=self._dtype, + is_bias=True) + + def forward(self, input, pre_hidden, pre_cell): + concat_input_hidden = layers.concat([input, pre_hidden], 1) + gate_input = layers.matmul(x=concat_input_hidden, y=self._weight) + + gate_input = layers.elementwise_add(gate_input, self._bias) + i, j, f, o = layers.split(gate_input, num_or_sections=4, dim=-1) + new_cell = layers.elementwise_add( + layers.elementwise_mul( + pre_cell, + layers.sigmoid(layers.elementwise_add(f, self._forget_bias))), + layers.elementwise_mul(layers.sigmoid(i), layers.tanh(j))) + new_hidden = layers.tanh(new_cell) * layers.sigmoid(o) + + return new_hidden, new_cell diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/memory_usage_calc.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/memory_usage_calc.py new file mode 100644 index 0000000000000000000000000000000000000000..24e39d7ac61dbad1ece08927535f899adf8b618e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/memory_usage_calc.py @@ -0,0 +1,121 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This module provides a memory usage calculate function for user. +The purpose of this API is to allow users to estimate memory usage of +a program under a special batch size, then user can set appropriate +batch size to fully utilize a GPU. + +This API is still under active development and may change drastically. +""" + +from __future__ import print_function + +import six + +from .. import core +from ..framework import Program, Variable + +__all__ = ['memory_usage'] + +dtype_to_size = { + core.VarDesc.VarType.FP16: 2, + core.VarDesc.VarType.FP32: 4, + core.VarDesc.VarType.FP64: 8, + core.VarDesc.VarType.INT16: 2, + core.VarDesc.VarType.INT32: 4, + core.VarDesc.VarType.INT64: 8, + core.VarDesc.VarType.BOOL: 1, + core.VarDesc.VarType.UINT8: 1, +} + +DEBUG = False + + +def memory_usage(program, batch_size): + r""" + Get the estimate memory usage of program with input batch size. + + Args: + program(Program): The current Program. + batch_size(int): The current input data batch_size. + + Returns: + min_total_memory(float): the estimate memory usage lower bound. + max_total_memory(float): the estimate memory usage upper bound. + unit_str(string): the unit of estimate usage result. + + Examples: + + >>> import paddle.fluid as fluid + >>> lower_usage, upper_usage, unit = fluid.contrib.memory_usage( + fluid.default_main_program(), batch_size=10) + >>> print "memory usage is about %.3f - %.3f %s" % \ + (lower_usage, upper_usage, unit) + + """ + + # Parameters check + if not isinstance(program, Program): + raise TypeError( + "Calculating Memory Usage requires Program as its Parameter." + "But you passed in %s" % (type(program))) + if batch_size <= 0: + raise ValueError("The batch size need to be positive.") + + # Get the var_name list of first block and calculate + total_memory = 0.0 + processed_var_names = set(["@EMPTY@"]) + for op in program.global_block().ops: + for var_name in op.output_arg_names: + if var_name in processed_var_names: + continue + processed_var_names.add(var_name) + var = program.global_block().vars[var_name] + if var.desc.type() != core.VarDesc.VarType.LOD_TENSOR: + continue + + data_count = 1 + neg_dim_count = 0 + for x in var.shape: + if x < 0: + if neg_dim_count >= 1: + raise ValueError( + "Var %s has more than one negative dim." % + (var_name)) + neg_dim_count += 1 + data_count *= batch_size * (-x) + else: + data_count *= x + var_memory = data_count * dtype_to_size[var.dtype] + if DEBUG: + print("%s memory usage: %d" % (var.name, var_memory)) + total_memory += var_memory + if DEBUG: + print("total memory usage: %.2f" % (total_memory)) + + # Convert appropriate unit + unit_str = "B" + if total_memory > 1024: + total_memory /= 1024 + unit_str = "KB" + if total_memory > 1024: + total_memory /= 1024 + unit_str = "MB" + + # Append extra memory consumption (5% - 10%) + min_total_memory = total_memory * 1.05 + max_total_memory = total_memory * 1.1 + + return min_total_memory, max_total_memory, unit_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd5015ec80f2256c595364c22bd969f2ca327b2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/__init__.py @@ -0,0 +1,28 @@ +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function + +from . import decorator +from .decorator import * +from . import fp16_lists +from .fp16_lists import * +from . import fp16_utils +from .fp16_utils import * +from . import bf16 + +__all__ = [] +__all__ += decorator.__all__ +__all__ += fp16_lists.__all__ +__all__ += fp16_utils.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/amp_nn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/amp_nn.py new file mode 100644 index 0000000000000000000000000000000000000000..62b98e75ea1d2eb69cc0b9a6637df2401dc49232 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/amp_nn.py @@ -0,0 +1,145 @@ +# 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. + +from paddle.fluid.data_feeder import check_variable_and_dtype, check_type +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import Variable +from paddle.fluid import core + +__all__ = ['check_finite_and_unscale', 'update_loss_scaling'] + + +def check_finite_and_unscale(x, scale, name=None, float_status=None): + """ + Check if input X contains all finite data, if yes, scale it by input Scale. + + $$Out = X / scale$$ + + If any tensor in X contains Inf or Nan, the Out will generate a indicator. + FoundInfinite will be 1 (True), and Out will not be scaled. In this case, the data of + Out should not be used, and its data may not be deterministic. + Otherwise, FoundInfinite will be 0 (False). + + Args: + x(list|tuple): The input tensors of check_finite_and_unscale operator. + scale: The scale of check_finite_and_unscale operator. + float_status(Tensor): (Only used on NPU) The float status to check overflow. + """ + check_type(x, 'x', (tuple, list), 'check_finite_and_unscale') + for e in x: + check_variable_and_dtype(e, "x", ['float16', 'float32', 'float64'], + 'check_finite_and_unscale') + + helper = LayerHelper("check_finite_and_unscale", **locals()) + found_inf = helper.create_variable_for_type_inference(dtype='bool') + + inputs = {'X': x, 'Scale': scale} + if core.is_compiled_with_npu(): + check_variable_and_dtype(float_status, "float_status", + ['float16', 'float32'], + 'check_finite_and_unscale') + inputs['FloatStatus'] = float_status + outputs = {'Out': x, 'FoundInfinite': found_inf} + helper.append_op(type='check_finite_and_unscale', + inputs=inputs, + outputs=outputs) + + return x, found_inf + + +def update_loss_scaling(x, + found_inf, + prev_loss_scaling, + num_good_steps, + num_bad_steps, + incr_every_n_steps, + decr_every_n_nan_or_inf, + incr_ratio, + decr_ratio, + stop_update=False, + name=None): + """ + Update loss scaling according to overall gradients. If all gradients is + finite after incr_every_n_steps, loss scaling will increase by incr_ratio. + Otherwise, loss scaling will decrease by decr_ratio after + decr_every_n_nan_or_inf steps and each step some gradients are infinite. + + Args: + x(list|tuple): The input tensors of update_loss_scaling operator. + found_inf (Variable): A boolean variable indicates whether + there is any infinite gradient. + prev_loss_scaling (Variable): Previous loss scaling. + num_good_steps (Variable): A variable accumulates good steps in which + all gradients are finite. + num_bad_steps (Variable): A variable accumulates bad steps in which + some gradients are infinite. + incr_every_n_steps (int): A variable represents increasing loss + scaling every n consecutive steps with + finite gradients. + decr_every_n_nan_or_inf (int): A variable represents decreasing + loss scaling every n accumulated + steps with nan or inf gradients. + incr_ratio(float): The multiplier to use when increasing the loss + scaling. + decr_ratio(float): The less-than-one-multiplier to use when decreasing + loss scaling. + """ + + check_variable_and_dtype(prev_loss_scaling, "prev_loss_scaling", + ['float32', 'float64'], "update_loss_scaling") + check_type(x, 'x', (tuple, list), 'update_loss_scaling') + for e in x: + check_variable_and_dtype(e, "x", ['float16', 'float32', 'float64'], + 'update_loss_scaling') + if e.dtype == core.VarDesc.VarType.FP16: + assert prev_loss_scaling.dtype == core.VarDesc.VarType.FP32, \ + "The dtype of prev_loss_scaling should be float32 when the dtype of x is float16." + else: + assert prev_loss_scaling.dtype == e.dtype, "The dtype of prev_loss_scaling should be equal to the dtype of x." + + helper = LayerHelper("update_loss_scaling", **locals()) + + inputs = { + 'X': x, + 'FoundInfinite': found_inf, + 'PrevLossScaling': prev_loss_scaling, + 'InGoodSteps': num_good_steps, + 'InBadSteps': num_bad_steps + } + + outputs = { + 'Out': x, + 'LossScaling': prev_loss_scaling, + 'OutGoodSteps': num_good_steps, + 'OutBadSteps': num_bad_steps + } + + attrs = { + 'incr_every_n_steps': incr_every_n_steps, + 'decr_every_n_nan_or_inf': decr_every_n_nan_or_inf, + 'incr_ratio': incr_ratio, + 'decr_ratio': decr_ratio, + } + + if isinstance(stop_update, Variable): + inputs['StopUpdate'] = stop_update + else: + attrs['stop_update'] = stop_update + + helper.append_op(type='update_loss_scaling', + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0920176f772352fe954cc10f538f6fb897da2ac4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function + +from . import amp_lists +from .amp_lists import * +from . import amp_utils +from .amp_utils import * +from . import decorator +from .decorator import * + +__all__ = [] +__all__ += decorator.__all__ +__all__ += amp_lists.__all__ +__all__ += amp_utils.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_lists.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_lists.py new file mode 100644 index 0000000000000000000000000000000000000000..3f799809af9772167eea7097a465ac2e3e2e0668 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_lists.py @@ -0,0 +1,111 @@ +# Copyright (c) 2021 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. + +import copy +from paddle.fluid import core + +from ..fp16_lists import white_list as white_list_fp16, black_list as black_list_fp16,\ + gray_list as gray_list_fp16 + +__all__ = ["AutoMixedPrecisionListsBF16"] + + +class AutoMixedPrecisionListsBF16(object): + """ + AutoMixedPrecisionListsBF16 is a class for fp32/bf16 op types list. The lists are used for an + algorithm which determines op's execution mode (fp32 or bf16).It can update pre-defined + fp32 list and bf16 list according to users' custom fp32 bf16 lists. + + Args: + custom_bf16_list (set): Users' custom bf16 list. + custom_fp32_list (set): Users' custom fp32 list. + custom_fp32_varnames (set): Users' custom fp32 variables' names. + + Examples: + .. code-block:: python + import paddle + paddle.enable_static() + with paddle.static.amp.bf16_guard(): + paddle.static.amp.AutoMixedPrecisionListsBF16(custom_fp32_list={'lstm'}) + """ + + def __init__(self, + custom_bf16_list=None, + custom_fp32_list=None, + custom_fp32_varnames=None): + self._custom_bf16_list = custom_bf16_list + self._custom_fp32_list = custom_fp32_list + self.bf16_list = copy.copy(bf16_list) + self.fp32_list = copy.copy(fp32_list) + self.gray_list = copy.copy(gray_list) + self.bf16_initializer_list = copy.copy(bf16_initializer_list) + self.unsupported_list = copy.copy(unsupported_list) + self.fp32_varnames = copy.copy(custom_fp32_varnames) + self._update_list() + + def _update_list(self): + """ + Update fp32 and bf16 list according to users' custom list. + """ + if self._custom_bf16_list and self._custom_fp32_list: + for op_name in self._custom_bf16_list: + if op_name in self._custom_fp32_list: + raise ValueError("Custom bf16 list overlap " + "custom fp32 list") + if self._custom_bf16_list: + for op_name in self._custom_bf16_list: + if op_name in self.fp32_list: + self.fp32_list.remove(op_name) + elif op_name in self.gray_list: + self.gray_list.remove(op_name) + self.bf16_list.add(op_name) + if self._custom_fp32_list: + for op_name in self._custom_fp32_list: + if op_name in self.bf16_list: + self.bf16_list.remove(op_name) + elif op_name in self.gray_list: + self.gray_list.remove(op_name) + self.fp32_list.add(op_name) + self.unsupported_list.add(op_name) + + +bf16_initializer_list = {'fill_constant', 'uniform_random'} + +# always bf16 +bf16_list = { + 'conv2d', + 'matmul', + 'matmul_v2', + 'mul', +} + +# depends on the prev_op type +gray_list = { + 'elementwise_add', 'elementwise_sub', 'elementwise_mul', 'elementwise_div', + 'relu', 'layer_norm', 'slice', 'concat', 'uniform_random', 'reshape2', + 'transpose2', 'pool2d', 'sigmoid', 'cast', 'scale', 'fill_constant', 'split' +} + +_, _, _sys_unsupported_bf16_list = core.op_supported_infos( + 'CPU', core.VarDesc.VarType.BF16) +unsupported_list = _sys_unsupported_bf16_list + +fp32_list = black_list_fp16.copy().copy() +fp32_list |= white_list_fp16 +fp32_list |= gray_list_fp16 + +fp32_list -= bf16_list +fp32_list -= gray_list +unsupported_list -= bf16_list +unsupported_list -= gray_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d2528c0e11eda50921ca3e2107e17810f3422610 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/amp_utils.py @@ -0,0 +1,552 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function + +from .... import core +from .... import framework +from .... import global_scope +from ....log_helper import get_logger +from ....wrapped_decorator import signature_safe_contextmanager +from .amp_lists import AutoMixedPrecisionListsBF16 +from ..fp16_utils import find_true_prev_op, find_true_post_op, _rename_arg, \ + find_op_index, _rename_op_input + +import collections +import struct +import logging +import numpy as np + +__all__ = [ + "bf16_guard", "rewrite_program_bf16", "cast_model_to_bf16", + "cast_parameters_to_bf16", "convert_float_to_uint16" +] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + +_valid_types = [ + core.VarDesc.VarType.LOD_TENSOR, core.VarDesc.VarType.SELECTED_ROWS, + core.VarDesc.VarType.LOD_TENSOR_ARRAY +] + +_bf16_guard_pattern = "__use_bf16__" + + +def convert_float_to_uint16(in_list): + in_list = np.asarray(in_list) + out = np.vectorize( + lambda x: struct.unpack('> 16, + otypes=[np.uint16])(in_list.flat) + return np.reshape(out, in_list.shape) + + +def _dtype_to_str(dtype): + """ + Convert specific variable type to its corresponding string. + + Args: + dtype (VarType): Variable type. + """ + if dtype == core.VarDesc.VarType.BF16: + return 'bf16' + else: + return 'fp32' + + +def _insert_cast_op(block, op, idx, src_dtype, dest_dtype): + """ + Insert cast op and rename args of input and output. + + Args: + block (Program): The block in which the operator is. + op (Operator): The operator to insert cast op. + idx (int): The index of current operator. + src_dtype (VarType): The input variable dtype of cast op. + dest_dtype (VarType): The output variable dtype of cast op. + + Returns: + num_cast_op (int): The number of cast ops that have been inserted. + """ + num_cast_ops = 0 + + for in_name in op.input_names: + if src_dtype == core.VarDesc.VarType.FP32 and op.type in [ + 'batch_norm', 'fused_bn_add_activation', 'layer_norm' + ]: + if in_name not in {'X', 'Z'}: + continue + for in_var_name in op.input(in_name): + in_var = block.var(in_var_name) + if in_var.type not in _valid_types or in_var.dtype == dest_dtype: + continue + if in_var.dtype == src_dtype: + cast_name = in_var.name + '.cast_' + _dtype_to_str(dest_dtype) + out_var = block.vars.get(cast_name) + if out_var is None or out_var.dtype != dest_dtype: + out_var = block.create_var( + name=cast_name, + dtype=dest_dtype, + persistable=False, + stop_gradient=in_var.stop_gradient) + + block._insert_op(idx, + type="cast", + inputs={"X": in_var}, + outputs={"Out": out_var}, + attrs={ + "in_dtype": in_var.dtype, + "out_dtype": out_var.dtype + }) + num_cast_ops += 1 + _rename_arg(op, in_var.name, out_var.name) + else: + if op.has_attr('in_dtype'): + op._set_attr('in_dtype', dest_dtype) + if src_dtype == core.VarDesc.VarType.FP32 and dest_dtype == core.VarDesc.VarType.BF16: + for out_name in op.output_names: + if op.type in [ + 'batch_norm', 'fused_bn_add_activation', 'layer_norm' + ] and out_name != 'Y': + continue + for out_var_name in op.output(out_name): + out_var = block.var(out_var_name) + if out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.BF16) + if op.has_attr('out_dtype'): + op._set_attr('out_dtype', core.VarDesc.VarType.BF16) + return num_cast_ops + + +def _insert_cast_post_op(block, op, idx, src_dtype, dest_dtype, target_name, + op_var_rename_map): + num_cast_ops = 0 + target_var = block.var(target_name) + if target_var.type not in _valid_types or target_var.dtype == dest_dtype: + return num_cast_ops + + assert target_var.dtype == src_dtype, \ + "The real dtype({}) is not equal to the src dtype({})".format(_dtype_to_str(target_var.dtype), _dtype_to_str(src_dtype)) + + cast_name = target_var.name + '.cast_' + _dtype_to_str(dest_dtype) + cast_var = block.vars.get(cast_name) + if cast_var is None or cast_var.dtype != dest_dtype: + cast_var = block.create_var(name=cast_name, + dtype=dest_dtype, + persistable=False, + stop_gradient=target_var.stop_gradient) + block._insert_op(idx, + type="cast", + inputs={"X": target_var}, + outputs={"Out": cast_var}, + attrs={ + "in_dtype": target_var.dtype, + "out_dtype": cast_var.dtype + }) + num_cast_ops += 1 + op_var_rename_map[block.idx][target_var.name] = cast_var.name + + return num_cast_ops + + +def _is_in_fp32_varnames(op, amp_lists): + if not amp_lists.fp32_varnames: + return False + + for in_name in op.input_arg_names: + if in_name in amp_lists.fp32_varnames: + return True + + for out_name in op.output_arg_names: + if out_name in amp_lists.fp32_varnames: + return True + + return False + + +def _need_keep_fp32(op, unsupported_op_list, use_bf16_guard): + if op.type in unsupported_op_list: + # the highest priority condition: If ops don't have bf16 computing kernels, + # they must be executed in fp32 calculation pattern. + return True + + # process ops about learning rate + in_out_arg_names = [] + in_out_arg_names.extend(list(op.input_arg_names)) + in_out_arg_names.extend(list(op.output_arg_names)) + for name in in_out_arg_names: + if "learning_rate" in name: + return True + + if use_bf16_guard: + if op.has_attr("op_namescope") and \ + (_bf16_guard_pattern in op.attr("op_namescope")): + # op in bf16 guard + return False + else: + # op not in bf16 guard + return True + else: + return False + + +@signature_safe_contextmanager +def bf16_guard(): + """ + As for the pure bf16 training, if users set `use_bf16_guard` to True, + only those ops created in the context manager `bf16_guard` will be + transformed as float16 type. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn.functional as F + paddle.enable_static() + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + + with paddle.static.amp.bf16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + """ + with framework.name_scope(prefix=_bf16_guard_pattern): + yield + + +def are_post_ops_bf16(post_ops, keep_fp32_ops): + for post_op in post_ops: + for op in post_op: + if op in keep_fp32_ops: + return False + return True + + +def cast_initializers_to_bf16(startup_prog, + amp_lists, + block, + all_ops, + keep_fp32_ops, + to_bf16_var_names=None): + prepend_ops = startup_prog.global_block().ops + for op in prepend_ops: + if str(op.type) in amp_lists.bf16_initializer_list: + change_op = True + op_post_ops = [] + op_out_vars = [] + for out_name in op.output_names: + for out_var_name in op.output(out_name): + out_var = block.var(out_var_name) + post_op = find_true_post_op(all_ops, op, out_var_name, True) + + if out_var is None or out_var.type not in _valid_types: + change_op = False + break + op_post_ops.append(post_op) + op_out_vars.append(out_var) + + if change_op and are_post_ops_bf16(op_post_ops, keep_fp32_ops): + for out_var in op_out_vars: + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.BF16) + if to_bf16_var_names is not None and out_var.name in to_bf16_var_names: + to_bf16_var_names.remove(out_var.name) + if op.has_attr('dtype') and op.attr( + 'dtype') == core.VarDesc.VarType.FP32: + op._set_attr('dtype', core.VarDesc.VarType.BF16) + + +def cast_model_to_bf16(program, + startup_prog=None, + amp_lists=None, + use_bf16_guard=True): + """ + Traverse all ops in the whole model and set their inputs and outputs + to the bf16 data type. This function will do some special processing for + the batch normalization, which will keep the batchnorm's computations in FP32. + Args: + program (Program): The used program. + amp_lists (AutoMixedPrecisionListsBF16): An AutoMixedPrecisionListsBF16 object. + use_bf16_guard(bool): Determine whether to use `bf16_guard` when + constructing the program. Default True. + """ + + if amp_lists is None: + amp_lists = AutoMixedPrecisionListsBF16() + global_block = program.global_block() + keep_fp32_ops = set() + to_bf16_var_names = set() + to_bf16_pre_cast_ops = set() + origin_ops = [] + for block in program.blocks: + origin_ops.extend(block.ops) + + for block in program.blocks: + ops = block.ops + for op in ops: + if op.type == 'create_py_reader' or op.type == 'read': + continue + if _need_keep_fp32(op, amp_lists.unsupported_list, use_bf16_guard): + keep_fp32_ops.add(op) + continue # processed below + for in_name in op.input_names: + if op.type in { + 'batch_norm', 'fused_bn_add_activation', 'layer_norm' + } and in_name not in {'X', 'Z'}: + continue + for in_var_name in op.input(in_name): + in_var = None + try: + in_var = block.var(in_var_name) + except ValueError as e: + _logger.debug( + "-- {}, try to get it in the global block --". + format(e)) + in_var = global_block.var(in_var_name) + if in_var is not None: + _logger.debug( + "-- var {} is got in the global block --". + format(in_var_name)) + + if in_var is None or in_var.type not in _valid_types: + continue + + if in_var.dtype == core.VarDesc.VarType.FP32: + in_var.desc.set_dtype(core.VarDesc.VarType.BF16) + to_bf16_var_names.add(in_var_name) + + _logger.debug( + "-- op type: {}, in var name: {}, in var dtype: {} --". + format(op.type, in_var_name, in_var.dtype)) + + for out_name in op.output_names: + if op.type in { + 'batch_norm', 'fused_bn_add_activation', 'layer_norm' + } and out_name != 'Y': + continue + for out_var_name in op.output(out_name): + out_var = None + try: + out_var = block.var(out_var_name) + except ValueError as e: + _logger.debug( + "-- {}, try to get it in the global block --". + format(e)) + out_var = global_block.var(out_var_name) + if out_var is not None: + _logger.debug( + "-- var {} is got in the global block --". + format(out_var_name)) + + if out_var is None or out_var.type not in _valid_types: + continue + + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.BF16) + + _logger.debug( + "-- op type: {}, out var name: {}, out var dtype: {} --" + .format(op.type, out_var_name, out_var.dtype)) + for attr_name in ['in_dtype', 'out_dtype', 'dtype']: + if op.has_attr(attr_name) and op.attr( + attr_name) == core.VarDesc.VarType.FP32: + op._set_attr(attr_name, core.VarDesc.VarType.BF16) + if op.has_attr('use_mkldnn'): + op._set_attr('use_mkldnn', True) + if op.has_attr('mkldnn_data_type'): + op._set_attr('mkldnn_data_type', 'bfloat16') + + if startup_prog is not None: + cast_initializers_to_bf16(startup_prog, amp_lists, global_block, + ops, keep_fp32_ops, to_bf16_var_names) + + # process ops in keep_fp32_ops + op_var_rename_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + for block in program.blocks: + ops = block.ops + idx = 0 + while idx < len(ops): + op = ops[idx] + num_cast_ops = 0 + if op not in keep_fp32_ops: + if op in to_bf16_pre_cast_ops: + in_var_cast_num = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.BF16) + num_cast_ops += in_var_cast_num + else: + pre_cast_num = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.BF16, + core.VarDesc.VarType.FP32) + num_cast_ops += pre_cast_num + for out_var_name in op.output_arg_names: + out_var = block.vars.get(out_var_name) + if out_var is None or out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.BF16: + out_var.desc.set_dtype(core.VarDesc.VarType.FP32) + post_ops = find_true_post_op(ops, op, out_var_name) + for post_op in post_ops: + if post_op in keep_fp32_ops: + continue + post_cast_num = _insert_cast_post_op( + block, op, idx + pre_cast_num + 1, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.BF16, out_var_name, + op_var_rename_map) + num_cast_ops += post_cast_num + idx += num_cast_ops + 1 + + _rename_op_input(program, op_var_rename_map, origin_ops, keep_fp32_ops) + return to_bf16_var_names + + +def cast_parameters_to_bf16(place, program, scope=None, to_bf16_var_names=None): + """ + Traverse all parameters in the whole model and set them to the BF16 data type. + Whereas, this function will keep parameters of batchnorms in FP32. + Args: + place(fluid.CPUPlace|fluid.CUDAPlace): `place` is used to restore the BF16 weight tensors. + program (Program): The used program. + scope(fluid.Scope, optional): `scope` is used to get the FP32 weight tensor values. + Default is None. + to_bf16_var_names(set|list, optional): The data types of vars in `to_bf16_var_names` + will be set to BF16. Usually, it is the returned + value of `cast_model_to_bf16` API. + """ + all_parameters = [] + for block in program.blocks: + all_parameters.extend(block.all_parameters()) + + bf16_var_names = to_bf16_var_names if to_bf16_var_names else set() + var_scope = scope if scope else global_scope() + for param in all_parameters: + if param.name in bf16_var_names: + _logger.debug("---- cast {} to bf16 dtype ----".format(param.name)) + param_t = var_scope.find_var(param.name).get_tensor() + data = np.array(param_t) + param_t.set(convert_float_to_uint16(data), place) + + +def rewrite_program_bf16(main_prog, amp_lists=None): + """ + Traverse all ops in current block and insert cast op according to + which set current op belongs to. + + 1. When an op belongs to the fp32 list, add it to fp32 set + 2. When an op belongs to the bf16 list, add it to bf16 set + 3. When an op belongs to the gray list. If one + of its inputs is the output of fp32 set op or fp32 list op, + add it to fp32 set. If all of its previous ops are not fp32 + op and one of its inputs is the output of bf16 set op or + bf16 list op, add it to bf16 set. + 4. When an op isn't in the lists, add it to fp32 op set. + 5. Add necessary cast ops to make sure that fp32 set op will be + computed in fp32 mode, while bf16 set op will be computed in + bf16 mode. + + Args: + main_prog (Program): The main program for training. + """ + if amp_lists is None: + amp_lists = AutoMixedPrecisionListsBF16() + block = main_prog.global_block() + ops = block.ops + bf16_op_set = set() + fp32_op_set = set() + for op in ops: + + # NOTE(zhiqiu): 'create_py_reader' and 'read' is used in non-iterable DataLoder, + # we don't need to handle reader op and the input of 'create_py_reader' is not + # in block, which may result in errors. + # See GeneratorLoader._init_non_iterable() for details. + if op.type == 'create_py_reader' or op.type == 'read': + continue + + if amp_lists.fp32_varnames is not None and _is_in_fp32_varnames( + op, amp_lists): + fp32_op_set.add(op) + continue + + if op.type in amp_lists.fp32_list: + fp32_op_set.add(op) + elif op.type in amp_lists.bf16_list: + bf16_op_set.add(op) + elif op.type in amp_lists.gray_list: + is_fp32_op = False + is_bf16_op = False + for in_name in op.input_names: + # if this op has inputs + if in_name: + for in_var_name in op.input(in_name): + in_var = block.var(in_var_name) + # this in_var isn't the output of other op + if in_var.op is None: + continue + elif in_var.op is op: + prev_op = find_true_prev_op(ops, op, in_var_name) + if prev_op is None: + continue + else: + prev_op = in_var.op + # if it's one of inputs + if prev_op in fp32_op_set or \ + prev_op.type in amp_lists.fp32_list: + is_fp32_op = True + elif prev_op in bf16_op_set or \ + prev_op.type in amp_lists.bf16_list: + is_bf16_op = True + if is_fp32_op: + fp32_op_set.add(op) + elif is_bf16_op: + bf16_op_set.add(op) + else: + pass + else: + # For numerical safe, we apply fp32 computation on ops that + # are not determined which list they should stay. + fp32_op_set.add(op) + + idx = 0 + while idx < len(ops): + op = ops[idx] + num_cast_ops = 0 + if op in fp32_op_set: + num_cast_ops = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.BF16, + core.VarDesc.VarType.FP32) + elif op in bf16_op_set: + if op.has_attr('use_mkldnn'): + op._set_attr('use_mkldnn', True) + op._set_attr('mkldnn_data_type', 'bfloat16') + elif op.has_attr('dtype') and op.attr( + 'dtype') == core.VarDesc.VarType.FP32: + op._set_attr('dtype', core.VarDesc.VarType.BF16) + + num_cast_ops = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.BF16) + else: + pass + + idx += num_cast_ops + 1 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/decorator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..41fce89a9e9dacc052c919c00b2ef3b17e5f4624 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/bf16/decorator.py @@ -0,0 +1,322 @@ +# Copyright (c) 2021 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. + +from paddle.fluid import (core, default_main_program, layers, program_guard, + unique_name) +from .amp_utils import (rewrite_program_bf16, cast_model_to_bf16, + cast_parameters_to_bf16) +from .amp_lists import AutoMixedPrecisionListsBF16 +import types +import warnings + +__all__ = ["decorate_bf16"] + + +class OptimizerWithMixedPrecision(object): + """ + Optimizer with mixed-precision (MP) training. This is a wrapper of a common + optimizer, plus the support of mixed-precision pre-training. The object + of this class almost has the same behavior as the common optimizer, with the + methods `minimize()`, `backward()`, `apply_gradients()` implemented. + Additionally, it enables the MP training automatically, i.e, the creation + and maintenance of master parameters, scaling of loss, etc. + + Args: + optimizer (Optimizer): A common Optimizer object. + amp_lists (CustomOpLists): An CustomOpLists object. + use_pure_bf16(bool): Whether to use the pure bf16 training. + use_bf16_guard(bool): Whether to use `bf16_guard` when constructing the program. + + """ + + def __init__(self, optimizer, amp_lists, use_pure_bf16, use_bf16_guard): + self._optimizer = optimizer + if optimizer.type == 'sgd': + optimizer._use_mkldnn = True + self._amp_lists = amp_lists + self._param_grads = None + self._train_program = None + + self._learning_rate = optimizer._learning_rate + self._learning_rate_map = optimizer._learning_rate_map + self._use_pure_bf16 = use_pure_bf16 + self._use_bf16_guard = use_bf16_guard + self._to_bf16_var_names = None + + def _init_amp_var(self): + # Ensure the data type of learning rate vars is float32 (same as the + # master parameter dtype) + if isinstance(self._optimizer._learning_rate, float): + self._optimizer._learning_rate_map[default_main_program()] = \ + layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(self._optimizer._learning_rate), + dtype='float32', + persistable=True) + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + Backward propagation or auto differentiation for gradients' computation. + + Args: + loss (Variable): The loss Variable to minimize. + startup_program (Program|None): The startup Program for initializing + parameters in `parameter_list`. + parameter_list (list|None): A list of Variables to update. + no_grad_set (set|None): A set of Variables should be ignored. + callbacks (list|None): A list of callable objects to run when appending + backward operator for one parameter. + + Returns: + A list of (param, grad), which is a tuple of a parameter and its + gradient respectively, and the scaled loss. + """ + train_program = loss.block.program + self._train_program = train_program + + with program_guard(self._train_program, startup_program): + self._init_amp_var() + + if self._use_pure_bf16: + self._to_bf16_var_names = cast_model_to_bf16( + self._train_program, startup_program, self._amp_lists, + self._use_bf16_guard) + else: + rewrite_program_bf16(self._train_program, self._amp_lists) + + if loss.dtype != core.VarDesc.VarType.FP32: + loss = loss.astype('float32') + + params_grads = self._optimizer.backward(loss, startup_program, + parameter_list, no_grad_set, + callbacks) + return params_grads + + def amp_init(self, + place, + scope=None, + test_program=None, + use_bf16_test=False): + """ + Init the amp training, such as cast fp32 parameters to bf16 type. + + Args: + place(CPUPlace): place is used to initialize + bf16 parameters with fp32 values. + scope(Scope): The scope is used to find fp32 parameters. + test_program(Program): The program is used for testing. + use_bf16_test(bool): Whether to use bf16 testing. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn.functional as F + paddle.enable_static() + + def run_example_code(): + place = paddle.CPUPlace(0) + exe = paddle.static.Executor(place) + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + # 1) Use bf16_guard to control the range of bf16 kernels used. + with paddle.static.amp.bf16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + # 2) Create the optimizer and set `multi_precision` to True. + # Setting `multi_precision` to True can avoid the poor accuracy + # or the slow convergence in a way. + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True) + # 3) These ops in `custom_fp32_list` will keep in the float32 computation type. + amp_list = paddle.static.amp.CustomOpLists( + custom_fp32_list=['pool2d']) + # 4) The entry of Paddle AMP. + # Enable pure bf16 training by setting `use_pure_bf16` to True. + optimizer = paddle.static.amp.bf16.decorate_bf16( + optimizer, + amp_list, + use_pure_bf16=True) + # If you don't use the default_startup_program(), you sholud pass + # your defined `startup_program` into `minimize`. + optimizer.minimize(loss) + exe.run(paddle.static.default_startup_program()) + # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`). + # If you want to perform the testing process, you should pass `test_program` into `amp_init`. + optimizer.amp_init(place, scope=paddle.static.global_scope()) + + """ + assert self._train_program is not None, \ + "Please call the minimize method first." + if self._use_pure_bf16: + cast_parameters_to_bf16(place, self._train_program, scope, + self._to_bf16_var_names) + if test_program is not None: + if self._use_pure_bf16: + cast_model_to_bf16(test_program, + amp_lists=self._amp_lists, + use_bf16_guard=self._use_bf16_guard) + elif use_bf16_test: + rewrite_program_bf16(test_program, amp_lists=self._amp_lists) + + def apply_gradients(self, params_grads): + """ + Apply gradients. + + Args: + params_grads (list): A list of params. + + Returns: + A list of optimize operators. + """ + + return self._optimizer.apply_gradients(params_grads) + + def apply_optimize(self, loss, startup_program, params_grads): + program = loss.block.program + with program_guard(program, startup_program): + optimize_ops = self.apply_gradients(params_grads) + return optimize_ops + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + Perform optimization by minimizing the given loss. + + Args: + loss (Variable): The loss Variable. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + + Returns: + The scaled loss by scaling factor, the list of optimize ops, and a + list of scaled parameters and gradients. + """ + opt_dict = self._optimizer.__class__.__dict__ + if 'minimize' in opt_dict and isinstance(opt_dict['minimize'], + types.FunctionType): + warnings.warn( + "The decorated optimizer has its own `minimize` method, but it will not be executed." + ) + + params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, startup_program, params_grads) + + return optimize_ops, params_grads + + +def decorate_bf16(optimizer, + amp_lists=None, + use_pure_bf16=False, + use_bf16_guard=None): + """ + Decorate the given optimizer to adapt to the mixed-precision training. + + Args: + optimizer(Optimizer): A common Optimizer. + amp_lists (CustomOpLists): An CustomOpLists object. + use_pure_bf16(bool): Whether to use the pure bf16 training. Default False. + use_bf16_guard(bool): Whether to use `bf16_guard` when constructing the program. + Default None, which means that its value equals to `use_pure_bf16`. + + Returns: + An optimizer acting like a normal one but with mixed-precision training + enabled. + + Examples 1: + .. code-block:: python + + # fp32&bf16 list based strategy example + import paddle + import paddle.static as static + + paddle.enable_static() + + data = static.data(name='X', shape=[None, 1], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + loss = paddle.mean(hidden) + optimizer = paddle.optimizer.Adam(learning_rate=0.001) + + mp_optimizer = static.amp.decorate_bf16(optimizer=optimizer) + + ops, param_grads = mp_optimizer.minimize(loss) + + Examples 2: + .. code-block:: python + + # pure bf16 training example + import numpy as np + import paddle + import paddle.nn.functional as F + + def run_example_code(): + place = paddle.CPUPlace(0) + exe = paddle.static.Executor(place) + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + # 1) Use bf16_guard to control the range of bf16 kernels used. + with paddle.static.amp.bf16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + # 2) Create the optimizer and set `multi_precision` to True. + # Setting `multi_precision` to True can avoid the poor accuracy + # or the slow convergence in a way. + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True) + # 3) These ops in `custom_fp32_list` will keep in the float32 computation type. + amp_list = paddle.static.amp.CustomOpLists( + custom_fp32_list=['pool2d']) + # 4) The entry of Paddle AMP. + # Enable pure bf16 training by setting `use_pure_bf16` to True. + optimizer = paddle.static.amp.decorate_bf16( + optimizer, + amp_list, + use_pure_bf16=True) + # If you don't use the default_startup_program(), you sholud pass + # your defined `startup_program` into `minimize`. + optimizer.minimize(loss) + exe.run(paddle.static.default_startup_program()) + # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`). + # If you want to perform the testing process, you should pass `test_program` into `amp_init`. + optimizer.amp_init(place, scope=paddle.static.global_scope()) + + """ + if amp_lists is None: + amp_lists = AutoMixedPrecisionListsBF16() + + if use_bf16_guard is None: + use_bf16_guard = use_pure_bf16 + + mp_optimizer = OptimizerWithMixedPrecision(optimizer, amp_lists, + use_pure_bf16, use_bf16_guard) + + return mp_optimizer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/decorator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..787a4e90a0f4399bfa51bde6e65ee0c8671b7800 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/decorator.py @@ -0,0 +1,642 @@ +# 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. + +from ... import core +from ... import default_main_program +from ... import default_startup_program +from ... import framework +from ... import layers +from ... import program_guard +from ... import unique_name +from . import fp16_utils +from .fp16_utils import rewrite_program +from .fp16_utils import cast_model_to_fp16 +from .fp16_utils import cast_parameters_to_fp16 +from .fp16_utils import update_role_var_grad +from .fp16_lists import AutoMixedPrecisionLists +from .amp_nn import check_finite_and_unscale +from .amp_nn import update_loss_scaling +import types +import warnings +import paddle + +__all__ = ["decorate"] + + +class OptimizerWithMixedPrecision(object): + """ + Optimizer with mixed-precision (MP) training. This is a wrapper of a common + optimizer, plus the support of mixed-precision pre-training. The object + of this class almost has the same behavior as the common optimizer, with the + methods `minimize()`, `backward()`, `apply_gradients()` implemented. + Additionally, it enables the MP training automatically, i.e, the creation + and maintenance of master parameters, scaling of loss, etc. + + Args: + optimizer (Optimizer): A common Optimizer object. + amp_lists (CustomOpLists): An CustomOpLists object. + init_loss_scaling (float): The initial loss scaling factor. + use_dynamic_loss_scaling (bool): Whether to use dynamic loss scaling. + incr_every_n_steps(int): Increases loss scaling every n consecutive + steps with finite gradients. + decr_every_n_nan_or_inf(int): Decreases loss scaling every n + accumulated steps with nan or + inf gradients. + incr_ratio(float): The multiplier to use when increasing the loss + scaling. + decr_ratio(float): The less-than-one-multiplier to use when decreasing + the loss scaling. + use_pure_fp16(bool): Whether to use the pure fp16 training. Default False. + use_fp16_guard(bool): Whether to use `fp16_guard` when constructing the program. + Default None, which means that its value is equal to `use_pure_fp16`. + + """ + + def __init__(self, optimizer, amp_lists, init_loss_scaling, + use_dynamic_loss_scaling, incr_every_n_steps, + decr_every_n_nan_or_inf, incr_ratio, decr_ratio, use_pure_fp16, + use_fp16_guard): + self._optimizer = optimizer + self._amp_lists = amp_lists + self._param_grads = None + self._train_program = None + + self._is_distributed = False + self._scaled_loss = None + self._loss_scaling = None + self._init_loss_scaling = init_loss_scaling + self._use_dynamic_loss_scaling = use_dynamic_loss_scaling + self._learning_rate = optimizer._learning_rate + self._learning_rate_map = optimizer._learning_rate_map + self._use_pure_fp16 = use_pure_fp16 + self._use_fp16_guard = use_fp16_guard + self._to_fp16_var_names = None + if self._use_dynamic_loss_scaling: + self._incr_every_n_steps = incr_every_n_steps + self._decr_every_n_nan_or_inf = decr_every_n_nan_or_inf + self._incr_ratio = incr_ratio + self._decr_ratio = decr_ratio + self._num_good_steps = None + self._num_bad_steps = None + + def _set_distributed(self, flag): + # if distributed, all cards will communication with each other, + # overlap communication and computation by split the + # check_finite_and_unscale op. + self._is_distributed = flag + + def get_loss_scaling(self): + """Return the real-time loss scaling factor. + """ + assert self._loss_scaling is not None, 'Please call minimize() before calling get_loss_scaling().' + return self._loss_scaling + + def get_scaled_loss(self): + """Return the scaled loss. + It's useful when you feed customed loss into executor. + """ + return self._scaled_loss + + def _supports_check_nan_inf(self): + return getattr(self._optimizer, "_supports_check_nan_inf", False) + + def _init_amp_var(self): + self._loss_scaling = layers.create_global_var( + name=unique_name.generate("loss_scaling"), + shape=[1], + value=self._init_loss_scaling, + dtype='float32', + persistable=True) + + if self._use_dynamic_loss_scaling: + self._num_good_steps = layers.create_global_var( + name=unique_name.generate("num_good_steps"), + shape=[1], + value=0, + dtype='int32', + persistable=True) + self._num_bad_steps = layers.create_global_var( + name=unique_name.generate("num_bad_steps"), + shape=[1], + value=0, + dtype='int32', + persistable=True) + + # Ensure the data type of learning rate vars is float32 (same as the + # master parameter dtype) + if isinstance(self._optimizer._learning_rate, float): + self._optimizer._learning_rate_map[default_main_program()] = \ + layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(self._optimizer._learning_rate), + dtype='float32', + persistable=True) + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + Backward propagation or auto differentiation for gradients' computation. + + Args: + loss (Variable): The loss Variable to minimize. + startup_program (Program|None): The startup Program for initializing + parameters in `parameter_list`. + parameter_list (list|None): A list of Variables to update. + no_grad_set (set|None): A set of Variables should be ignored. + callbacks (list|None): A list of callable objects to run when appending + backward operator for one parameter. + + Returns: + A list of (param, grad), which is a tuple of a parameter and its + gradient respectively, and the scaled loss. + """ + train_program = loss.block.program + self._train_program = train_program + + # NOTE(zhiqiu): _float_status is only used for NPU. + if core.is_compiled_with_npu(): + float_status = paddle.static.data(name="float_status", + shape=[8], + dtype='float32') + self._train_program.global_block().append_op( + type="alloc_float_status", + outputs={"FloatStatus": float_status}, + ) + self._train_program.global_block().append_op( + type="clear_float_status", + inputs={"FloatStatus": float_status}, + outputs={"FloatStatusOut": float_status}, + ) + self._float_status = float_status + else: + self._float_status = None + + with program_guard(self._train_program, startup_program): + self._init_amp_var() + + if self._use_pure_fp16: + self._to_fp16_var_names = cast_model_to_fp16( + self._train_program, self._amp_lists, self._use_fp16_guard) + else: + rewrite_program(self._train_program, self._amp_lists) + + if loss.dtype != core.VarDesc.VarType.FP32: + loss = loss.astype('float32') + # When not using dynamic loss scaling and the init loss scaling value is equal to 1.0, + # the model can be optimized. + if self._use_dynamic_loss_scaling or self._init_loss_scaling != 1.0: + self._scaled_loss = loss * self._loss_scaling + else: + self._scaled_loss = loss + + params_grads = self._optimizer.backward(self._scaled_loss, + startup_program, + parameter_list, no_grad_set, + callbacks) + if self._supports_check_nan_inf(): + self._add_cast_ops_to_startup_program(startup_program) + return params_grads + + def _add_cast_ops_to_startup_program(self, startup_program): + names = list(self._to_fp16_var_names) if self._to_fp16_var_names else [] + names.sort() + startup_program = default_startup_program( + ) if startup_program is None else startup_program + block = startup_program.global_block() + param_names = [p.name for p in block.all_parameters()] + for name in names: + if name not in param_names: + continue + + tmp = block.create_var(dtype=core.VarDesc.VarType.FP32) + block.append_op(type='assign', + inputs={'X': [name]}, + outputs={'Out': [tmp]}) + block.append_op(type='cast', + inputs={'X': [tmp]}, + outputs={'Out': [name]}, + attrs={ + 'in_dtype': core.VarDesc.VarType.FP32, + 'out_dtype': core.VarDesc.VarType.FP16, + }) + self._to_fp16_var_names = None + + def amp_init(self, + place, + scope=None, + test_program=None, + use_fp16_test=False): + """ + Init the amp training, such as cast fp32 parameters to fp16 type. + + Args: + place(CUDAPlace): place is used to initialize + fp16 parameters with fp32 values. + scope(Scope): The scope is used to find fp32 parameters. + test_program(Program): The program is used for testing. + use_fp16_test(bool): Whether to use fp16 testing. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn.functional as F + paddle.enable_static() + + def run_example_code(): + place = paddle.CUDAPlace(0) + exe = paddle.static.Executor(place) + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + # 1) Use fp16_guard to control the range of fp16 kernels used. + with paddle.static.amp.fp16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + # 2) Create the optimizer and set `multi_precision` to True. + # Setting `multi_precision` to True can avoid the poor accuracy + # or the slow convergence in a way. + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True) + # 3) These ops in `custom_black_list` will keep in the float32 computation type. + amp_list = paddle.static.amp.CustomOpLists( + custom_black_list=['pool2d']) + # 4) The entry of Paddle AMP. + # Enable pure fp16 training by setting `use_pure_fp16` to True. + optimizer = paddle.static.amp.decorate( + optimizer, + amp_list, + init_loss_scaling=128.0, + use_dynamic_loss_scaling=True, + use_pure_fp16=True) + # If you don't use the default_startup_program(), you sholud pass + # your defined `startup_program` into `minimize`. + optimizer.minimize(loss) + exe.run(paddle.static.default_startup_program()) + # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`). + # If you want to perform the testing process, you should pass `test_program` into `amp_init`. + optimizer.amp_init(place, scope=paddle.static.global_scope()) + + if paddle.is_compiled_with_cuda() and len(paddle.static.cuda_places()) > 0: + run_example_code() + """ + assert self._train_program is not None, \ + "Please call the minimize method first." + if self._use_pure_fp16: + cast_parameters_to_fp16(place, self._train_program, scope, + self._to_fp16_var_names) + if test_program is not None: + if self._use_pure_fp16: + cast_model_to_fp16(test_program, self._amp_lists, + self._use_fp16_guard) + elif use_fp16_test: + rewrite_program(test_program, self._amp_lists) + + def apply_gradients(self, params_grads): + """ + Check scaled gradients to determine whether to update loss scaling and update + parameters by their scaled gradients. + + Args: + params_grads (list): A list of params and scaled grads. + + Returns: + A list of optimize operators. + """ + + # Change the op_role_var attr for some ops, so that gradients + # transferred across GPUs can be FP16. + update_role_var_grad(self._train_program, params_grads) + + # When not using dynamic loss scaling and the init loss scaling value is equal to 1.0, + # the model can be optimized. + if not self._use_dynamic_loss_scaling and self._init_loss_scaling == 1.0: + return self._optimizer.apply_gradients(params_grads) + + if self._supports_check_nan_inf(): + self._optimizer._set_scale(self._loss_scaling) + optimize_ops = self._optimizer.apply_gradients(params_grads) + found_inf = self._optimizer._found_inf + self._add_dynamic_loss_scaling(params_grads, found_inf) + return optimize_ops + + found_inf = self._check_finite_and_unscale(params_grads) + if self._use_dynamic_loss_scaling: + self._add_dynamic_loss_scaling(params_grads, found_inf) + + # Pass found_inf to adam, to skip update for not only param, but also momentum and beta_pow + # With fleet, optimizers are nested and the real optimizer set by user is the inner most one. + real_optimizer = self._optimizer + while hasattr(real_optimizer, "inner_opt"): + real_optimizer = real_optimizer.inner_opt + if isinstance(real_optimizer, + (paddle.fluid.optimizer.Adam, paddle.optimizer.AdamW)): + # NOTE(zhiqiu): Since found_inf needs to be on cpu in adam op, we + # copy it in advance to avoid multiple time copies. + with self._train_program._optimized_guard([]): + found_inf = paddle.tensor.creation._memcpy( + found_inf, paddle.CPUPlace()) + real_optimizer._set_auxiliary_var('found_inf', found_inf) + elif hasattr(real_optimizer, "_set_auxiliary_var"): + real_optimizer._set_auxiliary_var('found_inf', found_inf) + optimize_ops = self._optimizer.apply_gradients(params_grads) + return optimize_ops + + def _split_grads(self, params_grads): + grads = [g for _, g in params_grads] + fp32_grads = [g for g in grads if g.dtype == core.VarDesc.VarType.FP32] + fp16_grads = [g for g in grads if g.dtype == core.VarDesc.VarType.FP16] + assert len(fp32_grads) + len(fp16_grads) == len(grads), \ + "Data types of all grads must be either fp16 or fp32." + return grads, fp32_grads, fp16_grads + + def _check_finite_and_unscale(self, params_grads): + grads, fp32_grads, fp16_grads = self._split_grads(params_grads) + found_infs = [] + + if self._is_distributed: + # if distributed, split check_finite_and_unscale to overlap + # unscale with communication + if core.is_compiled_with_npu(): + with self._train_program._optimized_guard(grads): + _, found_inf = check_finite_and_unscale( + grads, + self._loss_scaling, + name="find_infinite_scale", + float_status=self._float_status) + found_infs.append(found_inf) + else: + for p, g in params_grads: + with self._train_program._optimized_guard([p, g]): + _, found_inf = check_finite_and_unscale( + [ + g, + ], + self._loss_scaling, + name="find_infinite_scale", + float_status=self._float_status) + found_infs.append(found_inf) + elif self._use_pure_fp16: + if fp32_grads: + with self._train_program._optimized_guard(fp32_grads): + _, fp32_found_inf = check_finite_and_unscale( + fp32_grads, + self._loss_scaling, + name="find_infinite_scale_fp32", + float_status=self._float_status) + found_infs.append(fp32_found_inf) + if fp16_grads: + with self._train_program._optimized_guard(fp16_grads): + _, fp16_found_inf = check_finite_and_unscale( + fp16_grads, + self._loss_scaling, + name="find_infinite_scale_fp16", + float_status=self._float_status) + found_infs.append(fp16_found_inf) + else: + with self._train_program._optimized_guard(grads): + _, found_inf = check_finite_and_unscale( + grads, + self._loss_scaling, + name="find_infinite_scale", + float_status=self._float_status) + + if self._is_distributed or self._use_pure_fp16: + with self._train_program._optimized_guard([]): + all_infs = layers.concat(found_infs) + found_inf = layers.reduce_any(all_infs) + + return found_inf + + def _add_dynamic_loss_scaling(self, params_grads, found_inf): + if self._supports_check_nan_inf(): + with self._train_program._optimized_guard([]): + update_loss_scaling( + [], + found_inf, + self._loss_scaling, + self._num_good_steps, + self._num_bad_steps, + self._incr_every_n_steps, + self._decr_every_n_nan_or_inf, + self._incr_ratio, + self._decr_ratio, + stop_update=self._optimizer._get_stop_update_var(), + name="update_loss_scaling") + return + + grads, fp32_grads, fp16_grads = self._split_grads(params_grads) + if self._use_pure_fp16: + stop_update = False + with self._train_program._optimized_guard([]): + if fp32_grads: + update_loss_scaling(fp32_grads, + found_inf, + self._loss_scaling, + self._num_good_steps, + self._num_bad_steps, + self._incr_every_n_steps, + self._decr_every_n_nan_or_inf, + self._incr_ratio, + self._decr_ratio, + stop_update=stop_update, + name="update_loss_scaling_fp32") + stop_update = True + if fp16_grads: + update_loss_scaling(fp16_grads, + found_inf, + self._loss_scaling, + self._num_good_steps, + self._num_bad_steps, + self._incr_every_n_steps, + self._decr_every_n_nan_or_inf, + self._incr_ratio, + self._decr_ratio, + stop_update=stop_update, + name="update_loss_scaling_fp16") + else: + with self._train_program._optimized_guard([]): + update_loss_scaling(grads, + found_inf, + self._loss_scaling, + self._num_good_steps, + self._num_bad_steps, + self._incr_every_n_steps, + self._decr_every_n_nan_or_inf, + self._incr_ratio, + self._decr_ratio, + name="update_loss_scaling") + + def apply_optimize(self, loss, startup_program, params_grads): + program = loss.block.program + with program_guard(program, startup_program): + optimize_ops = self.apply_gradients(params_grads) + return optimize_ops + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + Perform optimization by minimizing the given loss. + + Args: + loss (Variable): The loss Variable. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + + Returns: + The scaled loss by scaling factor, the list of optimize ops, and a + list of scaled parameters and gradients. + """ + + opt_dict = self._optimizer.__class__.__dict__ + if 'minimize' in opt_dict and isinstance(opt_dict['minimize'], + types.FunctionType): + warnings.warn( + "The decorated optimizer has its own `minimize` method, but it will not be executed." + ) + + scaled_params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, startup_program, + scaled_params_grads) + + return optimize_ops, scaled_params_grads + + +def decorate(optimizer, + amp_lists=None, + init_loss_scaling=2**15, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=2, + incr_ratio=2.0, + decr_ratio=0.8, + use_dynamic_loss_scaling=True, + use_pure_fp16=False, + use_fp16_guard=None): + """ + Decorate the given optimizer to adapt to the mixed-precision training. + + Args: + optimizer(Optimizer): A common Optimizer. + amp_lists (CustomOpLists): An CustomOpLists object. + init_loss_scaling(float): The initial loss scaling factor. + incr_every_n_steps(int): Increases loss scaling every n consecutive + steps with finite gradients. + decr_every_n_nan_or_inf(int): Decreases loss scaling every n + accumulated steps with nan or + inf gradients. + incr_ratio(float): The multiplier to use when increasing the loss + scaling. + decr_ratio(float): The less-than-one-multiplier to use when decreasing + the loss scaling. + use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling. + use_pure_fp16(bool): Whether to use the pure fp16 training. Default False. + use_fp16_guard(bool): Whether to use `fp16_guard` when constructing the program. + Default None, which means that its value equals to `use_pure_fp16`. + + Returns: + An optimizer acting like a normal one but with mixed-precision training + enabled. + + Examples 1: + .. code-block:: python + + # black&white list based strategy example + import paddle + import paddle.static as static + + paddle.enable_static() + + data = static.data(name='X', shape=[None, 1], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + loss = paddle.mean(hidden) + optimizer = paddle.optimizer.Adam(learning_rate=0.001) + + mp_optimizer = static.amp.decorate( + optimizer=optimizer, init_loss_scaling=8.0) + + ops, param_grads = mp_optimizer.minimize(loss) + scaled_loss = mp_optimizer.get_scaled_loss() + + Examples 2: + .. code-block:: python + + # pure fp16 training example + import numpy as np + import paddle + import paddle.nn.functional as F + + def run_example_code(): + place = paddle.CUDAPlace(0) + exe = paddle.static.Executor(place) + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + # 1) Use fp16_guard to control the range of fp16 kernels used. + with paddle.static.amp.fp16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + # 2) Create the optimizer and set `multi_precision` to True. + # Setting `multi_precision` to True can avoid the poor accuracy + # or the slow convergence in a way. + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, multi_precision=True) + # 3) These ops in `custom_black_list` will keep in the float32 computation type. + amp_list = paddle.static.amp.CustomOpLists( + custom_black_list=['pool2d']) + # 4) The entry of Paddle AMP. + # Enable pure fp16 training by setting `use_pure_fp16` to True. + optimizer = paddle.static.amp.decorate( + optimizer, + amp_list, + init_loss_scaling=128.0, + use_dynamic_loss_scaling=True, + use_pure_fp16=True) + # If you don't use the default_startup_program(), you sholud pass + # your defined `startup_program` into `minimize`. + optimizer.minimize(loss) + exe.run(paddle.static.default_startup_program()) + # 5) Use `amp_init` after FP32 parameters initialization(such as `exe.run(startup_program)`). + # If you want to perform the testing process, you should pass `test_program` into `amp_init`. + optimizer.amp_init(place, scope=paddle.static.global_scope()) + + if paddle.is_compiled_with_cuda() and len(paddle.static.cuda_places()) > 0: + run_example_code() + """ + if amp_lists is None: + amp_lists = AutoMixedPrecisionLists() + + if use_fp16_guard is None: + use_fp16_guard = use_pure_fp16 + + mp_optimizer = OptimizerWithMixedPrecision( + optimizer, amp_lists, init_loss_scaling, use_dynamic_loss_scaling, + incr_every_n_steps, decr_every_n_nan_or_inf, incr_ratio, decr_ratio, + use_pure_fp16, use_fp16_guard) + + return mp_optimizer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_lists.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_lists.py new file mode 100644 index 0000000000000000000000000000000000000000..b2767b1dd1cbfa7ab4ea209bb8cee3b648e5cb7c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_lists.py @@ -0,0 +1,191 @@ +# 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. + +import copy +from ... import core + +__all__ = ["CustomOpLists", "AutoMixedPrecisionLists"] + +# lookup_table fp16 is slower than fp32, though fp16 is supported. +_extra_unsupported_fp16_list = { + 'lookup_table', 'lookup_table_v2', 'scatter', 'scatter_grad' +} + + +class AutoMixedPrecisionLists(object): + """ + AutoMixedPrecisionLists is a class for black/white list. It can update + pre-defined black list and white list according to users' custom black + white lists. The lists are used for an algorithm which determines op's + execution mode (fp32 or fp16). + + Args: + custom_white_list (set): Users' custom white list. + custom_black_list (set): Users' custom black list. + custom_black_varnames (set): Users' custom black varibles' names. + """ + + def __init__(self, + custom_white_list=None, + custom_black_list=None, + custom_black_varnames=None): + self._custom_white_list = custom_white_list + self._custom_black_list = custom_black_list + self.white_list = copy.copy(white_list) + self.black_list = copy.copy(black_list) + self.gray_list = copy.copy(gray_list) + self.unsupported_list = copy.copy(unsupported_fp16_list) + self.black_varnames = copy.copy(custom_black_varnames) + self._update_list() + + def _update_list(self): + """ + Update black and white list according to users' custom list. + """ + if self._custom_white_list and self._custom_black_list: + for op_name in self._custom_white_list: + if op_name in self._custom_black_list: + raise ValueError("Custom white list overlap " + "custom black list") + if self._custom_white_list: + for op_name in self._custom_white_list: + if op_name in self.black_list: + self.black_list.remove(op_name) + elif op_name in self.gray_list: + self.gray_list.remove(op_name) + self.white_list.add(op_name) + if op_name in _extra_unsupported_fp16_list: + self.unsupported_list.remove(op_name) + if self._custom_black_list: + for op_name in self._custom_black_list: + if op_name in self.white_list: + self.white_list.remove(op_name) + elif op_name in self.gray_list: + self.gray_list.remove(op_name) + self.black_list.add(op_name) + self.unsupported_list.add(op_name) + + +# The three sets listed below are changed dynamiclly. They don't contain all +# paddle ops currently. + +# The set of ops that support fp16 calculation and are considered numerically- +# safe and performance-critical. These ops are always converted to fp16. +white_list = { + 'conv2d', + 'matmul', + 'matmul_v2', + 'mul', +} + +# The set of ops that support fp16 calculation and are considered numerically- +# dangerous and whose effects may also be observed in downstream ops. +black_list = { + 'exp', + 'square', + 'log', + 'mean', + 'sum', + 'cos_sim', + 'softmax', + 'softmax_with_cross_entropy', + 'sigmoid_cross_entropy_with_logits', + 'c_softmax_with_cross_entropy', + 'cross_entropy', + 'cross_entropy2', + # fp16 is slower than fp32, though fp16 is supported. + 'lookup_table', + 'lookup_table_v2', + 'linear_interp_v2', + 'nearest_interp_v2', + 'bilinear_interp_v2', + 'bicubic_interp_v2', + 'trilinear_interp_v2', + # default fp32 can avoid return inf when the sum value large than 65504 + 'reduce_sum', +} + +# This set contains two types of ops. All ops supported fp16 calculation. One +# of two types is considered numerically-safe, but may be made unsafe by an +# upstream blacklist op. Another type do not have numerically-significant +# effects, like stack, flatten2. +gray_list = { + 'elementwise_add', + 'elementwise_sub', + 'elementwise_mul', + 'elementwise_div', + 'elementwise_max', + 'elementwise_min', + 'elementwise_pow', + 'elementwise_mod', + 'elementwise_floordiv', + 'batch_norm', + 'layer_norm', + 'tanh', + 'sigmoid', + 'top_k', + 'pool2d', + 'pool3d', + 'dropout', + 'relu', + 'relu6', + 'leaky_relu', + 'soft_relu', + 'flatten2', + 'stack', + 'unstack', + 'uniform_random', + 'uniform_random_batch_size_like', + 'gaussian_random', + 'gaussian_random_batch_size_like', + 'slice', + 'rank', + 'scale', + 'transpose2', + 'reshape2', + 'gather', + 'fill_constant', + 'get_tensor_from_selected_rows', + 'sign', + 'cast', + 'fused_bn_add_activation', + 'c_identity', + 'c_concat', + 'c_allreduce_sum', + 'concat', + 'split', + 'fused_feedforward', + 'fused_attention', + 'fused_multi_transformer', +} + +# The set of ops that don't support fp16 calculation +# lookup_table fp16 is slower than fp32, though fp16 is supported. +_sys_unsupported_fp16_list = [] +if core.is_compiled_with_xpu(): + _, _, _sys_unsupported_fp16_list = core.op_supported_infos( + 'XPU', core.VarDesc.VarType.FP16) +elif core.is_compiled_with_npu(): + _, _, _sys_unsupported_fp16_list = core.op_supported_infos( + 'NPU', core.VarDesc.VarType.FP16) +elif core.is_compiled_with_mlu(): + _, _, _sys_unsupported_fp16_list = core.op_supported_infos( + 'MLU', core.VarDesc.VarType.FP16) +else: + _, _, _sys_unsupported_fp16_list = core.op_supported_infos( + 'GPU', core.VarDesc.VarType.FP16) + +unsupported_fp16_list = _extra_unsupported_fp16_list | _sys_unsupported_fp16_list + +CustomOpLists = AutoMixedPrecisionLists diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b23c94c7e499495aae14d3c0a11c9867b3029f4d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/mixed_precision/fp16_utils.py @@ -0,0 +1,710 @@ +# 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. + +from __future__ import print_function + +from ... import core +from ... import framework +from ... import layers +from ... import global_scope +from ...log_helper import get_logger +from ...wrapped_decorator import signature_safe_contextmanager +from .fp16_lists import AutoMixedPrecisionLists +import collections +import logging +import numpy as np + +__all__ = ["fp16_guard", "cast_model_to_fp16", "cast_parameters_to_fp16"] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + +_valid_types = [ + core.VarDesc.VarType.LOD_TENSOR, core.VarDesc.VarType.SELECTED_ROWS, + core.VarDesc.VarType.LOD_TENSOR_ARRAY +] + +_fp16_guard_pattern = "__use_fp16__" + + +def _rename_arg(op, old_name, new_name): + """ + If an op has old_name input and output, rename these input + args new_name. + + Args: + op (Operator): Current operator. + old_name (str): The old name of input args. + new_name (str): The new name of input args. + """ + op_desc = op.desc + if isinstance(op_desc, tuple): + op_desc = op_desc[0] + op_desc._rename_input(old_name, new_name) + op_desc._rename_output(old_name, new_name) + + +def _rename_op_input(program, op_var_rename_map, origin_ops, keep_fp32_ops): + for block in program.blocks: + ops = block.ops + block_id = block.idx + for op in ops: + if op not in origin_ops or op in keep_fp32_ops: + continue + for name in op.input_arg_names: + if name in op_var_rename_map[block_id]: + op._rename_input(name, op_var_rename_map[block_id][name]) + + +def _dtype_to_str(dtype): + """ + Convert specific variable type to its corresponding string. + + Args: + dtype (VarType): Variable type. + """ + if dtype == core.VarDesc.VarType.FP16: + return 'fp16' + else: + return 'fp32' + + +_keep_layer_norm_scale_bias_to_fp32_flag = True + + +def _keep_layer_norm_scale_bias_to_fp32(*args): + global _keep_layer_norm_scale_bias_to_fp32_flag + if len(args) == 0: + return _keep_layer_norm_scale_bias_to_fp32_flag + else: + assert len(args) == 1 and isinstance(args[0], bool) + old_value = _keep_layer_norm_scale_bias_to_fp32_flag + _keep_layer_norm_scale_bias_to_fp32_flag = args[0] + return old_value + + +def _keep_fp32_input(op, in_name): + op_type = op.type + if op_type == 'batch_norm': + # Scale, Bias, Mean, Variance should be float32. + return in_name != 'X' + if op_type == 'layer_norm' and _keep_layer_norm_scale_bias_to_fp32(): + return in_name != 'X' + if op_type == 'fused_bn_add_activation': + return in_name not in {'X', 'Z'} + if op_type == 'resnet_unit': + return in_name not in {'X', 'FilterX', 'Z', 'FilterZ'} + if op_type in ['fused_attention', 'fused_feedforward']: + return in_name in { + 'LnScale', 'LnBias', 'Ln2Scale', 'Ln2Bias', "Ln1Scale", "Ln1Bias" + } + if op_type == 'fused_multi_transformer': + return in_name in {'LnScale', 'LnBias', 'FFNLnScale', 'FFNLnBias'} + return False + + +def _keep_fp32_output(op, out_name): + op_type = op.type + if op_type in ['batch_norm', 'fused_bn_add_activation']: + return out_name != 'Y' + if op_type == 'layer_norm' and _keep_layer_norm_scale_bias_to_fp32(): + return out_name != 'Y' + if op_type == 'resnet_unit': + return out_name not in {'Y', 'ConvX', 'ConvZ'} + if op_type in ['fused_attention', 'fused_feedforward']: + return out_name in { + 'LnMean', 'LnVariance', 'Ln2Mean', 'Ln2Variance', 'Ln1Mean', + 'Ln1Variance' + } + return False + + +def _insert_cast_op(block, op, idx, src_dtype, dest_dtype): + """ + Insert cast op and rename args of input and output. + + Args: + block (Program): The block in which the operator is. + op (Operator): The operator to insert cast op. + idx (int): The index of current operator. + src_dtype (VarType): The input variable dtype of cast op. + dest_dtype (VarType): The output variable dtype of cast op. + + Returns: + num_cast_op (int): The number of cast ops that have been inserted. + """ + num_cast_ops = 0 + + for in_name in op.input_names: + if src_dtype == core.VarDesc.VarType.FP32 and _keep_fp32_input( + op, in_name): + continue + for in_var_name in op.input(in_name): + in_var = block._find_var_recursive(in_var_name) + if in_var.type not in _valid_types or in_var.dtype == dest_dtype: + continue + if in_var.dtype == src_dtype: + cast_name = in_var.name + '.cast_' + _dtype_to_str(dest_dtype) + out_var = block.vars.get(cast_name) + if out_var is None or out_var.dtype != dest_dtype: + op_device = op.attr('op_device') + # NOTE(wangxi): optimize for pipeline, reduce one send. + # if in_var is stop_gradient and prev_op device is `all`, + # set cast_op device to `all`, can reduce send cast_var. + # TODO: need remove this after we unified the dynamic + # and static pipeline interface. + if src_dtype == core.VarDesc.VarType.FP32 and in_var.stop_gradient: + prev_op = None + if in_var.op is op: + prev_op = find_true_prev_op(block.ops, op, + in_var_name) + elif in_var.op is not None: + prev_op = in_var.op + + prev_op_device = None + if prev_op is not None: + prev_op_device = prev_op.attr('op_device') + + if prev_op_device is not None and 'all' in prev_op_device: + op_device = prev_op_device + + out_var = block.create_var( + name=cast_name, + dtype=dest_dtype, + persistable=False, + stop_gradient=in_var.stop_gradient) + + block._insert_op_without_sync(idx, + type="cast", + inputs={"X": in_var}, + outputs={"Out": out_var}, + attrs={ + "in_dtype": in_var.dtype, + "out_dtype": + out_var.dtype, + "op_device": op_device, + "op_role": + op.attr("op_role"), + }) + num_cast_ops += 1 + _rename_arg(op, in_var.name, out_var.name) + else: + if op.has_attr('in_dtype'): + op._set_attr('in_dtype', dest_dtype) + if src_dtype == core.VarDesc.VarType.FP32 and dest_dtype == core.VarDesc.VarType.FP16: + for out_name in op.output_names: + if _keep_fp32_output(op, out_name): + continue + for out_var_name in op.output(out_name): + out_var = block.var(out_var_name) + if out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.FP16) + if op.has_attr('out_dtype'): + op._set_attr('out_dtype', core.VarDesc.VarType.FP16) + return num_cast_ops + + +def _insert_cast_post_op(block, op, idx, src_dtype, dest_dtype, target_name, + op_var_rename_map): + num_cast_ops = 0 + + target_var = block.var(target_name) + if target_var.type not in _valid_types or target_var.dtype == dest_dtype: + return num_cast_ops + + assert target_var.dtype == src_dtype, \ + "The real dtype({}) is not equal to the src dtype({})".format( + _dtype_to_str(target_var.dtype), _dtype_to_str(src_dtype)) + + cast_name = target_var.name + '.cast_' + _dtype_to_str(dest_dtype) + cast_var = block.vars.get(cast_name) + if cast_var is None or cast_var.dtype != dest_dtype: + cast_var = block.create_var(name=cast_name, + dtype=dest_dtype, + persistable=False, + stop_gradient=target_var.stop_gradient) + block._insert_op(idx, + type="cast", + inputs={"X": target_var}, + outputs={"Out": cast_var}, + attrs={ + "in_dtype": target_var.dtype, + "out_dtype": cast_var.dtype, + "op_device": op.attr("op_device"), + "op_role": op.attr("op_role"), + }) + num_cast_ops += 1 + op_var_rename_map[block.idx][target_var.name] = cast_var.name + + return num_cast_ops + + +def find_true_prev_op(ops, cur_op, var_name): + """ + Find the true prev op that outputs var_name variable. + + Args: + ops (list): A list of ops. + cur_op (Operator): Current operator which has var_name variable. + var_name (string): Variable name. + """ + prev_op = [] + for op in ops: + if op == cur_op: + break + for out_name in op.output_names: + for out_var_name in op.output(out_name): + if out_var_name == var_name: + prev_op.append(op) + if prev_op: + if not len(prev_op) == 1: + raise ValueError("There must be only one previous op " + "that outputs {0} variable".format(var_name)) + else: + return prev_op[0] + return None + + +def find_true_post_op(ops, cur_op, var_name, search_all=False): + """ + if there are post ops, return them, if there is no post op, + return None instead. + Args: + ops (list): A list of ops. + cur_op (Operator): Current operator which has var_name variable. + var_name (string): Variable name. + search_all (bool): The type of operator search. Use if \"cur_op\" is not in the \"ops\" set. + """ + post_op = [] + if search_all: + """ + \"cur_op\" do not have to be in list of \"ops\". E.g. \"cur_op\" can come + from startup_prog block and \"ops\" list from main_prog block. + By setting idx to -1, we'll start looking for post-ops from the top of the list. + If search_all is False, assume that \"cur_op\" is in \"ops\" list, + so to reduce the time of search we can start iterating from \"cur_op\" idx. + """ + idx = -1 + else: + for idx, op in enumerate(ops): + if op == cur_op: + break + + for i in range(idx + 1, len(ops)): + op = ops[i] + for in_name in op.input_names: + for in_var_name in op.input(in_name): + if in_var_name == var_name: + post_op.append(op) + + return post_op + + +def find_op_index(block_desc, cur_op_desc): + """ + """ + for idx in range(block_desc.op_size()): + if cur_op_desc == block_desc.op(idx): + return idx + return -1 + + +def _is_in_black_varnames(op, amp_lists): + for in_name in op.input_arg_names: + if in_name in amp_lists.black_varnames: + return True + + for out_name in op.output_arg_names: + if out_name in amp_lists.black_varnames: + return True + + return False + + +def _need_keep_fp32(op, unsupported_op_list, use_fp16_guard): + if op.type in unsupported_op_list: + # the highest priority condition: If ops don't have fp16 computing kernels, + # they must be executed in fp32 calculation pattern. + return True + + # process ops about learning rate + in_out_arg_names = [] + in_out_arg_names.extend(list(op.input_arg_names)) + in_out_arg_names.extend(list(op.output_arg_names)) + for name in in_out_arg_names: + if "learning_rate" in name: + return True + + if use_fp16_guard: + if op.has_attr("op_namescope") and \ + (_fp16_guard_pattern in op.attr("op_namescope")): + # op in fp16 guard + return False + else: + # op not in fp16 guard + return True + else: + return False + + +@signature_safe_contextmanager +def fp16_guard(): + """ + As for the pure fp16 training, if users set `use_fp16_guard` to True, + only those ops created in the context manager `fp16_guard` will be + transformed as float16 type. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn.functional as F + paddle.enable_static() + data = paddle.static.data(name='X', shape=[None, 1, 28, 28], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=6, filter_size=3) + + with paddle.static.amp.fp16_guard(): + bn = paddle.static.nn.batch_norm(input=conv2d, act="relu") + pool = F.max_pool2d(bn, kernel_size=2, stride=2) + hidden = paddle.static.nn.fc(pool, size=10) + loss = paddle.mean(hidden) + """ + with framework.name_scope(prefix=_fp16_guard_pattern): + yield + + +def cast_model_to_fp16(program, amp_lists=None, use_fp16_guard=True): + """ + Traverse all ops in the whole model and set their inputs and outputs + to the fp16 data type. This function will do some special process for + the batch normalization, which keeps the computational process of + batchnorms in FP32. + Args: + program (Program): The used program. + amp_lists (AutoMixedPrecisionLists): An AutoMixedPrecisionLists object. + use_fp16_guard(bool): Determine whether to use `fp16_guard` when + constructing the program. Default True. + """ + + if amp_lists is None: + amp_lists = AutoMixedPrecisionLists() + global_block = program.global_block() + keep_fp32_ops = set() + to_fp16_var_names = set() + origin_ops = [] + for block in program.blocks: + origin_ops.extend(block.ops) + + for block in program.blocks: + ops = block.ops + for op in ops: + if op.type == 'create_py_reader' or op.type == 'read': + continue + if _need_keep_fp32(op, amp_lists.unsupported_list, use_fp16_guard): + keep_fp32_ops.add(op) + continue # processed below + for in_name in op.input_names: + # for ipu, all inputs must be converted to fp16 + if not core.is_compiled_with_ipu() and _keep_fp32_input( + op, in_name): + continue + for in_var_name in op.input(in_name): + in_var = None + try: + in_var = block.var(in_var_name) + except ValueError as e: + _logger.debug( + "-- {}, try to get it in the global block --". + format(e)) + in_var = global_block.var(in_var_name) + if in_var is not None: + _logger.debug( + "-- var {} is got in the global block --". + format(in_var_name)) + + if in_var is None or in_var.type not in _valid_types: + continue + + if in_var.dtype == core.VarDesc.VarType.FP32: + in_var.desc.set_dtype(core.VarDesc.VarType.FP16) + to_fp16_var_names.add(in_var_name) + + _logger.debug( + "-- op type: {}, in var name: {}, in var dtype: {} --". + format(op.type, in_var_name, in_var.dtype)) + + for out_name in op.output_names: + # for ipu, all outputs must be converted to fp16 + if not core.is_compiled_with_ipu() and _keep_fp32_output( + op, out_name): + continue + for out_var_name in op.output(out_name): + out_var = None + try: + out_var = block.var(out_var_name) + except ValueError as e: + _logger.debug( + "-- {}, try to get it in the global block --". + format(e)) + out_var = global_block.var(out_var_name) + if out_var is not None: + _logger.debug( + "-- var {} is got in the global block --". + format(out_var_name)) + + if out_var is None or out_var.type not in _valid_types: + continue + + if out_var.dtype == core.VarDesc.VarType.FP32: + out_var.desc.set_dtype(core.VarDesc.VarType.FP16) + + _logger.debug( + "-- op type: {}, out var name: {}, out var dtype: {} --" + .format(op.type, out_var_name, out_var.dtype)) + if op.has_attr('in_dtype') and op.attr( + 'in_dtype') == core.VarDesc.VarType.FP32: + op._set_attr('in_dtype', core.VarDesc.VarType.FP16) + if op.has_attr('out_dtype') and op.attr( + 'out_dtype') == core.VarDesc.VarType.FP32: + op._set_attr('out_dtype', core.VarDesc.VarType.FP16) + if op.has_attr('dtype') and op.attr( + 'dtype') == core.VarDesc.VarType.FP32: + op._set_attr('dtype', core.VarDesc.VarType.FP16) + + # process ops in keep_fp32_ops + op_var_rename_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + for block in program.blocks: + ops = block.ops + idx = 0 + while idx < len(ops): + op = ops[idx] + num_cast_ops = 0 + if op in keep_fp32_ops: + pre_cast_num = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32) + num_cast_ops += pre_cast_num + for out_var_name in op.output_arg_names: + out_var = block.vars.get(out_var_name) + if out_var is None or out_var.type not in _valid_types: + continue + if out_var.dtype == core.VarDesc.VarType.FP16: + out_var.desc.set_dtype(core.VarDesc.VarType.FP32) + post_ops = find_true_post_op(ops, op, out_var_name) + for post_op in post_ops: + if post_op in keep_fp32_ops: + continue + post_cast_num = _insert_cast_post_op( + block, op, idx + pre_cast_num + 1, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16, out_var_name, + op_var_rename_map) + num_cast_ops += post_cast_num + idx += num_cast_ops + 1 + + _rename_op_input(program, op_var_rename_map, origin_ops, keep_fp32_ops) + return to_fp16_var_names + + +def cast_parameters_to_fp16(place, program, scope=None, to_fp16_var_names=None): + """ + Traverse all parameters in the whole model and set them to the FP16 data type. + Whereas, this function will keep parameters of batchnorms in FP32. + Args: + place(fluid.CPUPlace|fluid.CUDAPlace): `place` is used to restore the FP16 weight tensors. + program (Program): The used program. + scope(fluid.Scope, optional): `scope` is used to get the FP32 weight tensor values. + Default is None. + to_fp16_var_names(set|list, optional): The data types of vars in `to_fp16_var_names` + will be set to FP16. Usually, it is the returned + value of `cast_model_to_fp16` API. + """ + all_parameters = [] + for block in program.blocks: + all_parameters.extend(block.all_parameters()) + + fp16_var_names = to_fp16_var_names if to_fp16_var_names else set() + var_scope = scope if scope else global_scope() + for param in all_parameters: + if param.name in fp16_var_names: + _logger.debug("---- cast {} to fp16 dtype ----".format(param.name)) + param_t = var_scope.find_var(param.name).get_tensor() + data = np.array(param_t) + param_t.set(np.float16(data), place) + + +def rewrite_program(main_prog, amp_lists): + """ + Traverse all ops in current block and insert cast op according to + which set current op belongs to. + + 1. When an op belongs to the black list, add it to black set + 2. When an op belongs to the white list, add it to white set + 3. When an op belongs to the gray list. If one + of its inputs is the output of black set op or black list op, + add it to black set. If all of its previous ops are not black + op and one of its inputs is the output of white set op or + white list op, add it to white set. + 4. When an op isn't in the lists, add it to black op set. + 5. Add necessary cast ops to make sure that black set op will be + computed in fp32 mode, while white set op will be computed in + fp16 mode. + + Args: + main_prog (Program): The main program for training. + """ + block = main_prog.global_block() + block._sync_with_cpp() + ops = block.ops + white_op_set = set() + black_op_set = set() + for op in ops: + + # NOTE(zhiqiu): 'create_py_reader' and 'read' is used in non-iterable DataLoder, + # we don't need to handle reader op and the input of 'create_py_reader' is not + # in block, which may result in errors. + # See GeneratorLoader._init_non_iterable() for details. + if op.type == 'create_py_reader' or op.type == 'read': + continue + + if amp_lists.black_varnames is not None and _is_in_black_varnames( + op, amp_lists): + black_op_set.add(op) + continue + + if op.type in amp_lists.black_list: + black_op_set.add(op) + elif op.type in amp_lists.white_list: + white_op_set.add(op) + elif op.type in amp_lists.gray_list: + is_black_op = False + is_white_op = False + for in_name in op.input_names: + # if this op has inputs + if in_name: + for in_var_name in op.input(in_name): + in_var = block.var(in_var_name) + # this in_var isn't the output of other op + if in_var.op is None: + continue + elif in_var.op is op: + prev_op = find_true_prev_op(ops, op, in_var_name) + if prev_op is None: + continue + else: + prev_op = in_var.op + # if it's one of inputs + if prev_op in black_op_set or \ + prev_op.type in amp_lists.black_list: + is_black_op = True + elif prev_op in white_op_set or \ + prev_op.type in amp_lists.white_list: + is_white_op = True + if is_black_op: + black_op_set.add(op) + elif is_white_op: + white_op_set.add(op) + else: + pass + else: + # For numerical safe, we apply fp32 computation on ops that + # are not determined which list they should stay. + black_op_set.add(op) + + idx = 0 + while idx < len(ops): + op = ops[idx] + num_cast_ops = 0 + if op in black_op_set: + num_cast_ops = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32) + elif op in white_op_set: + num_cast_ops = _insert_cast_op(block, op, idx, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP16) + else: + pass + + idx += num_cast_ops + 1 + + +def update_role_var_grad(main_prog, params_grads): + """ + Update op_role_var attr for some ops to make sure the gradients + transferred across GPUs is FP16. + 1. Check whether the op that outputs gradient is cast or not. + 2. If op is cast and gradient is FP32, remove the op_role_var + and find the prev op which outputs FP16 gradient + 3. Update the op_role_var of the prev op. + + Args: + main_prog (Program): The main program for training. + params_grads (list): A list of params and grads. + """ + block = main_prog.global_block() + block._sync_with_cpp() + BACKWARD = core.op_proto_and_checker_maker.OpRole.Backward + OPTIMIZE = core.op_proto_and_checker_maker.OpRole.Optimize + for p, g in params_grads: + op = g.op + if g.dtype == core.VarDesc.VarType.FP32 and op.type == 'cast': + role = op.attr('op_role') + if role & int(BACKWARD) and op.has_attr('op_role_var'): + op._remove_attr("op_role_var") + else: + raise ValueError("The cast op {0} must be in BACKWARD role " + "and have op_role_var attr.".format(op)) + + fp16_grad_name = op.input(op.input_names[0])[0] + op_for_fp16_grad = find_true_prev_op(block.ops, op, fp16_grad_name) + op_role_var_attr_name = \ + core.op_proto_and_checker_maker.kOpRoleVarAttrName() + attr_val = [p.name, fp16_grad_name] + if op_for_fp16_grad.has_attr(op_role_var_attr_name): + attr_val.extend(op_for_fp16_grad.attr(op_role_var_attr_name)) + op_for_fp16_grad._set_attr(op_role_var_attr_name, attr_val) + + # Maximize the all_reduce overlap, and perform the cast + # operation after gradients transfer. + op._set_attr('op_role', OPTIMIZE) + # optimize op should stay behind forward and backward ops + if op == block.ops[-1]: + continue + post_ops = find_true_post_op(block.ops, op, g.name) + if post_ops: + raise ValueError("The cast op {0}'s output should not be" + "used by a non-optimize op, however, it" + "is used by {1}".format(op, post_ops[0])) + # add new op in the python and cpp at the same time + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(op.desc) + new_op = framework.Operator(block=block, + desc=new_op_desc, + type=None, + inputs=None, + outputs=None, + attrs=None) + block.ops.append(new_op) + op_idx = find_op_index(block.desc, op.desc) + if op_idx == -1: + raise ValueError("The op {0} is not in program".format(op)) + block._remove_op(op_idx, sync=False) + block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/model_stat.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/model_stat.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6d82671f24f5de82cea550c91297413dd02d7c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/model_stat.py @@ -0,0 +1,208 @@ +# 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. +''' +Example: + >>from paddle.fluid.contrib.model_stat import summary + >>main_program = ... + >>summary(main_program) + +-----+------------+----------------+----------------+---------+------------+ + | No. | TYPE | INPUT | OUTPUT | PARAMs | FLOPs | + +-----+------------+----------------+----------------+---------+------------+ + | 0 | conv2d | (3, 200, 200) | (64, 100, 100) | 9408 | 188160000 | + | 1 | batch_norm | (64, 100, 100) | (64, 100, 100) | 256 | 640000 | + | 2 | relu | (64, 100, 100) | (64, 100, 100) | 0 | 640000 | + | 3 | pool2d | (64, 100, 100) | (64, 50, 50) | 0 | 1440000 | + ... + | 176 | conv2d | (512, 7, 7) | (512, 7, 7) | 2359296 | 231211008 | + | 177 | relu | (512, 7, 7) | (512, 7, 7) | 0 | 25088 | + | 178 | conv2d | (512, 7, 7) | (2048, 7, 7) | 1048576 | 102760448 | + | 179 | relu | (2048, 7, 7) | (2048, 7, 7) | 0 | 100352 | + | 180 | pool2d | (2048, 7, 7) | (2048, 1, 1) | 0 | 100352 | + +-----+------------+----------------+----------------+---------+------------+ + Total PARAMs: 48017344(0.0480G) + Total FLOPs: 11692747751(11.69G) +''' +from collections import OrderedDict + + +def summary(main_prog): + ''' + It can summary model's PARAMS, FLOPs until now. + It support common operator like conv, fc, pool, relu, sigmoid, bn etc. + Args: + main_prog: main program + Returns: + print summary on terminal + ''' + collected_ops_list = [] + for one_b in main_prog.blocks: + block_vars = one_b.vars + for one_op in one_b.ops: + op_info = OrderedDict() + spf_res = _summary_model(block_vars, one_op) + if spf_res is None: + continue + # TODO: get the operator name + op_info['type'] = one_op.type + op_info['input_shape'] = spf_res[0][1:] + op_info['out_shape'] = spf_res[1][1:] + op_info['PARAMs'] = spf_res[2] + op_info['FLOPs'] = spf_res[3] + collected_ops_list.append(op_info) + + summary_table, total = _format_summary(collected_ops_list) + _print_summary(summary_table, total) + + +def _summary_model(block_vars, one_op): + ''' + Compute operator's params and flops. + Args: + block_vars: all vars of one block + one_op: one operator to count + Returns: + in_data_shape: one operator's input data shape + out_data_shape: one operator's output data shape + params: one operator's PARAMs + flops: : one operator's FLOPs + ''' + if one_op.type in ['conv2d', 'depthwise_conv2d']: + k_arg_shape = block_vars[one_op.input("Filter")[0]].shape + in_data_shape = block_vars[one_op.input("Input")[0]].shape + out_data_shape = block_vars[one_op.output("Output")[0]].shape + c_out, c_in, k_h, k_w = k_arg_shape + _, c_out_, h_out, w_out = out_data_shape + assert c_out == c_out_, 'shape error!' + k_groups = one_op.attr("groups") + kernel_ops = k_h * k_w * (c_in / k_groups) + bias_ops = 0 if one_op.input("Bias") == [] else 1 + params = c_out * (kernel_ops + bias_ops) + flops = h_out * w_out * c_out * (kernel_ops + bias_ops) + # base nvidia paper, include mul and add + flops = 2 * flops + + elif one_op.type == 'pool2d': + in_data_shape = block_vars[one_op.input("X")[0]].shape + out_data_shape = block_vars[one_op.output("Out")[0]].shape + _, c_out, h_out, w_out = out_data_shape + k_size = one_op.attr("ksize") + params = 0 + flops = h_out * w_out * c_out * (k_size[0] * k_size[1]) + + elif one_op.type == 'mul': + k_arg_shape = block_vars[one_op.input("Y")[0]].shape + in_data_shape = block_vars[one_op.input("X")[0]].shape + out_data_shape = block_vars[one_op.output("Out")[0]].shape + # TODO: fc has mul ops + # add attr to mul op, tell us whether it belongs to 'fc' + # this's not the best way + if 'fc' not in one_op.output("Out")[0]: + return None + k_in, k_out = k_arg_shape + # bias in sum op + params = k_in * k_out + 1 + flops = k_in * k_out + + elif one_op.type in ['sigmoid', 'tanh', 'relu', 'leaky_relu', 'prelu']: + in_data_shape = block_vars[one_op.input("X")[0]].shape + out_data_shape = block_vars[one_op.output("Out")[0]].shape + params = 0 + if one_op.type == 'prelu': + params = 1 + flops = 1 + for one_dim in in_data_shape: + flops *= one_dim + + elif one_op.type == 'batch_norm': + in_data_shape = block_vars[one_op.input("X")[0]].shape + out_data_shape = block_vars[one_op.output("Y")[0]].shape + _, c_in, h_out, w_out = in_data_shape + # gamma, beta + params = c_in * 2 + # compute mean and std + flops = h_out * w_out * c_in * 2 + + else: + return None + + return in_data_shape, out_data_shape, params, flops + + +def _format_summary(collected_ops_list): + ''' + Format summary report. + Args: + collected_ops_list: the collected operator with summary + Returns: + summary_table: summary report format + total: sum param and flops + ''' + _verify_dependent_package() + + from prettytable import PrettyTable + summary_table = PrettyTable( + ["No.", "TYPE", "INPUT", "OUTPUT", "PARAMs", "FLOPs"]) + summary_table.align = 'r' + + total = {} + total_params = [] + total_flops = [] + for i, one_op in enumerate(collected_ops_list): + # notice the order + table_row = [ + i, + one_op['type'], + one_op['input_shape'], + one_op['out_shape'], + int(one_op['PARAMs']), + int(one_op['FLOPs']), + ] + summary_table.add_row(table_row) + total_params.append(int(one_op['PARAMs'])) + total_flops.append(int(one_op['FLOPs'])) + + total['params'] = total_params + total['flops'] = total_flops + + return summary_table, total + + +def _verify_dependent_package(): + """ + Verify whether `prettytable` is installed. + """ + try: + from prettytable import PrettyTable + except ImportError: + raise ImportError( + "paddle.summary() requires package `prettytable`, place install it firstly using `pip install prettytable`. " + ) + + +def _print_summary(summary_table, total): + ''' + Print all the summary on terminal. + Args: + summary_table: summary report format + total: sum param and flops + ''' + parmas = total['params'] + flops = total['flops'] + print(summary_table) + print('Total PARAMs: {}({:.4f}M)'.format(sum(parmas), + sum(parmas) / (10**6))) + print('Total FLOPs: {}({:.2f}G)'.format(sum(flops), sum(flops) / 10**9)) + print( + "Notice: \n now supported ops include [Conv, DepthwiseConv, FC(mul), BatchNorm, Pool, Activation(sigmoid, tanh, relu, leaky_relu, prelu)]" + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/op_frequence.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/op_frequence.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9b7b1073d9ededc034f4d6dd2ff823df60a7bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/op_frequence.py @@ -0,0 +1,106 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function +from collections import OrderedDict + +from ..framework import Program + +__all__ = ['op_freq_statistic'] + + +def op_freq_statistic(program): + """ + Statistics of Op frequency. + + Args: + program(Program): The current Program. + + Returns: + uni_op_freq(dict): the single op frequency. + adj_2_op_freq(dict): the two adjacent ops frequency. + + Examples: + + >>> import paddle.fluid as fluid + >>> uni_op_freq, adj_2_op_freq = fluid.contrib.op_freq_statistic( + >>> fluid.default_main_program()) + >>> for op_type, op_num in uni_op_freq: + >>> print("%s \t %d" % (op_type, op_num)) + >>> for op_type, op_num in adj_2_op_freq: + >>> print("%s \t %d" % (op_type, op_num)) + + """ + + if not isinstance(program, Program): + raise TypeError("The input type should be Porgram." + "But you passed in %s" % (type(program))) + + uni_op_freq = OrderedDict() + adj_2_op_freq = OrderedDict() + op_in_ops = OrderedDict() + + parameters = [p.name for p in program.blocks[0].all_parameters()] + + # get uni_op_freq + for op in program.global_block().ops: + had_recorded = False + for var_name in op.output_arg_names: + if var_name in parameters: + continue + if not had_recorded and uni_op_freq.has_key(op.type): + uni_op_freq[op.type] += 1 + had_recorded = True + elif not had_recorded: + uni_op_freq[op.type] = 1 + had_recorded = True + + # get adj_2_op_freq + var_gen_op = {} + for op in program.global_block().ops: + for var_name in op.input_arg_names: + if var_name in parameters: + continue + if var_gen_op.has_key(var_name): + assert len(var_gen_op[var_name]) > 0 + if op_in_ops.has_key(op.type): + op_in_ops[op.type].append(var_gen_op[var_name][-1]) + else: + op_in_ops[op.type] = [var_gen_op[var_name][-1]] + else: + print("Var's generate op is not found,%s, %s" % + (var_name, op.type)) + + for var_name in op.output_arg_names: + if var_gen_op.has_key(var_name): + var_gen_op[var_name].append(op.type) + else: + var_gen_op[var_name] = [op.type] + + for op, in_ops in op_in_ops.iteritems(): + for in_op in in_ops: + op_op = in_op + "->" + op + if adj_2_op_freq.has_key(op_op): + adj_2_op_freq[op_op] += 1 + else: + adj_2_op_freq[op_op] = 1 + + uni_op_freq = sorted(uni_op_freq.items(), + key=lambda item: item[1], + reverse=True) + adj_2_op_freq = sorted(adj_2_op_freq.items(), + key=lambda item: item[1], + reverse=True) + + return uni_op_freq, adj_2_op_freq diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..67e972cf3e2319fff5b6ceed799537d62806376b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/optimizer.py @@ -0,0 +1,249 @@ +# 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. +from paddle.fluid.optimizer import Optimizer +from paddle.fluid.regularizer import L1DecayRegularizer +from paddle.fluid.regularizer import L2DecayRegularizer +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid.framework import program_guard +from paddle.fluid import unique_name +from paddle.fluid import layers +from paddle.fluid.layer_helper import LayerHelper +import warnings +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['Momentum'] + + +class Momentum(Optimizer): + r""" + + Simple Momentum optimizer with velocity state + + This optimizer has a flag for Nestrov Momentum. + + The update equations are as follows: + + .. math:: + + & velocity = mu * velocity + gradient + + & if (use\_nesterov): + + &\quad param = param - (gradient + mu * velocity) * learning\_rate + + & else: + + &\quad param = param - learning\_rate * velocity + + Parameters: + learning_rate (float|Variable): The learning rate used to update parameters. \ + Can be a float value or a Variable with one float value as data element. + momentum (float): Momentum factor + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + use_nesterov (bool, optional): Enables Nesterov momentum, default is false. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false. + rescale_grad (float, optional): Multiply the gradient with `rescale_grad` before updating. \ + Often choose to be ``1.0/batch_size``. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + paddle.enable_static() + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = paddle.static.data(name='x', shape=[1, 13], dtype='float32') + y = paddle.static.data(name='y', shape=[1], dtype='float32') + linear = paddle.nn.Linear(13, 1) + y_predict = linear(x) + cost = paddle.nn.functional.square_error_cost(input=y_predict, label=y) + avg_cost = paddle.mean(cost) + + moment_optimizer = fluid.contrib.optimizer.Momentum(learning_rate=0.001, momentum=0.9) + moment_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(paddle.static.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + """ + _velocity_acc_str = "velocity" + + def __init__(self, + learning_rate, + momentum, + parameter_list=None, + use_nesterov=False, + regularization=None, + grad_clip=None, + multi_precision=False, + rescale_grad=1.0, + name=None): + assert learning_rate is not None + assert momentum is not None + predicate = lambda regular: isinstance(regular, L2DecayRegularizer) + py_regular = None if predicate(regularization) else regularization + super(Momentum, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=py_regular, + grad_clip=grad_clip, + name=name) + self.type = "momentum" + self._momentum = momentum + self._use_nesterov = bool(use_nesterov) + self._regularization_method = "" + self._regularization_coeff = 0 + if (isinstance(regularization, L2DecayRegularizer)): + self._regularization_method = "l2_decay" + self._regularization_coeff = regularization._regularization_coeff + self._multi_precision = multi_precision + self._rescale_grad = rescale_grad + self._master_weights = {} + + def _create_master_weight(self, param): + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + target_param = self._master_weights[ + param.name] if find_master else param + target_name = target_param.name + if (name not in self._accumulators + or target_name not in self._accumulators[name]): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name)) + return self._accumulators[name][target_name] + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_accumulator(self._velocity_acc_str, master_p) + continue + if p.dtype == core.VarDesc.VarType.FP16 and not self._multi_precision: + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Momentum optimizer." + ) + self._add_accumulator(self._velocity_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + velocity_acc = self._get_accumulator(self._velocity_acc_str, + param_and_grad[0]) + lr = self._create_param_lr(param_and_grad) + + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + master_weight = (self._master_weights[param_and_grad[0].name] + if find_master else None) + + if framework._non_static_mode(): + _, _, _ = _legacy_C_ops.momentum( + param_and_grad[0], param_and_grad[1], velocity_acc, lr, + master_weight, param_and_grad[0], velocity_acc, master_weight, + 'mu', self._momentum, 'use_nesterov', self._use_nesterov, + 'regularization_method', self._regularization_method, + 'regularization_coeff', self._regularization_coeff, + 'multi_precision', find_master) + return None + + attrs = { + "mu": self._momentum, + "use_nesterov": self._use_nesterov, + "regularization_method": self._regularization_method, + "regularization_coeff": self._regularization_coeff, + "multi_precision": find_master, + "rescale_grad": self._rescale_grad + } + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "Velocity": [velocity_acc], + "LearningRate": [lr] + } + outputs = { + "ParamOut": [param_and_grad[0]], + "VelocityOut": [velocity_acc] + } + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + # create the momentum optimize op + momentum_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return momentum_op diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14c208d0e7f35ebfbbe1c36d0b11a8d0f0efb4a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import print_function + +from . import quantize_transpiler +from .quantize_transpiler import * + +__all__ = quantize_transpiler.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/quantize_transpiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/quantize_transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..de4c10040862afd2eea4ca92703f31348057b07a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/quantize/quantize_transpiler.py @@ -0,0 +1,556 @@ +# Copyright (c) 2018 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. + +import collections +import numpy as np + +from paddle.fluid.framework import default_main_program, default_startup_program, program_guard +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid import unique_name +from paddle.fluid import core +from paddle.fluid.initializer import Constant +from paddle.fluid.param_attr import ParamAttr +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.layers.nn import autoincreased_step_counter +from paddle.fluid.framework import Variable +from paddle.fluid.executor import global_scope + +__all__ = ['QuantizeTranspiler'] + +_QUANTIZABLE_OP_TYPES = ['conv2d', 'depthwise_conv2d', 'mul'] + + +def _quantized_var_name(var_name): + """ + Return quantized variable name for the input `var_name`. + """ + return "%s.quantized" % (var_name) + + +def _dequantized_var_name(var_name): + """ + Return dequantized variable name for the input `var_name`. + """ + return "%s.dequantized" % (var_name) + + +def _quantized_scale_name(var_name): + """ + Return quantized variable name for the input `var_name`. + """ + return "%s.scale" % (var_name) + + +def _original_var_name(var_name): + """ + Return the original variable name. + """ + if var_name.endswith('.quantized.dequantized'): + return var_name[:-len('.quantized.dequantized')] + if var_name.endswith('.quantized'): + return var_name[:-len('.quantized')] + if var_name.endswith('.dequantized'): + return var_name[:-len('.dequantized')] + if var_name.endswith('.scale'): + return var_name[:-len('.scale')] + else: + return var_name + + +def _is_float(v): + return isinstance(v, float) or isinstance(v, np.float32) + + +def quant(x, scale, num_bits): + y = np.round(x / scale * ((1 << (num_bits - 1)) - 1)) + return y + + +class QuantizeTranspiler(object): + + def __init__(self, + weight_bits=8, + activation_bits=8, + activation_quantize_type='abs_max', + weight_quantize_type='abs_max', + window_size=10000, + moving_rate=0.9): + """ + Convert and rewrite the fluid Program according to weight and + activation quantization type. + + Args: + weight_bits (int): quantization bit number for weights, + the bias is not quantized. + activation_bits (int): quantization bit number for activation. + activation_quantize_type (str): quantization type for activation, + now support 'abs_max', 'range_abs_max'. If use 'abs_max' mode, + the quantization scale will be calculated dynamically each step + in both training and testing period. If use 'range_abs_max', + a static quantization scale will be calculated during training + and used in inference. + weight_quantize_type (str): quantization type for weights, + support 'abs_max'. The 'range_abs_max' usually is not used for + weight, since weights are fixed once the model is well trained. + window_size (int): the window size for 'range_abs_max' quantization. + + Examples: + + .. code-block:: python + + # the original program will be rewrite, if you don't want to + # change it, please clone at first. + # quantize_program = program.clone() + t = fluid.QuantizeTranspiler() + t.transpile(quantize_program) + + """ + self.weight_bits = weight_bits + self.activation_bits = activation_bits + quant_type = ['abs_max', 'range_abs_max', 'moving_average_abs_max'] + if weight_quantize_type not in quant_type: + raise ValueError( + "Unknown weight_quantize_type: '%s'. It can only be ", + "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'.", + str(weight_quantize_type)) + if activation_quantize_type not in quant_type: + raise ValueError( + "Unknown activation_quantize_type : '%s'. It can only be ", + "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'.", + str(activation_quantize_type)) + + self.weight_quantize_type = weight_quantize_type + self.activation_quantize_type = activation_quantize_type + + self.window_size = window_size + self.moving_rate = moving_rate + self.helper = LayerHelper(self.__class__.__name__) + self.fake_quant_op_types = [ + 'fake_quantize_abs_max', 'fake_quantize_range_abs_max', + 'fake_quantize_moving_average_abs_max' + ] + self.fake_dequant_op_types = ['fake_dequantize_max_abs'] + self.is_test = None + self.global_step = None + + def training_transpile(self, program=None, startup_program=None): + """Rewrites a training input program in place for simulated + quantization. Insert fake quantization and de-quantization ops into + program to simulate the error introduced by quantization. And change + the gradient ops' input by using the faked quantization weights and + activation. Since the program is transformed in place, the graph + connection will change. + + Args: + program (Program): the input program to be transpile. + """ + self.is_test = False + program = default_main_program() if program is None else program + startup_program = default_startup_program() if startup_program is \ + None else startup_program + + # marked the variable which has been quantized and dequantized. + dequanted_vars = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + grad_op_types = ['%s_grad' % (type) for type in _QUANTIZABLE_OP_TYPES] + + params = [p.name for p in program.global_block().iter_parameters()] + + def _transpile_forward(block, op): + idx = block.ops.index(op) + block_id = block.idx + # insert quant op and dequant op + for name in op.input_arg_names: + #if share input between ops + if name in dequanted_vars[block_id]: + dequant_var = dequanted_vars[block_id][name] + else: + var = block.var(name) + quant_bits = self.weight_bits if var.name in params \ + else self.activation_bits + quant_type = self.weight_quantize_type if var.name \ + in params else self.activation_quantize_type + + quant_var, scale_var = self._insert_quant_op( + block, idx, var, quant_bits, quant_type) + dequant_var = self._insert_dequant_op( + block, idx + 1, quant_var, scale_var, quant_bits) + dequanted_vars[block_id][name] = dequant_var + # rename the forward op inputs + op._rename_input(name, dequant_var.name) + + def _transpile_backward(block, op): + block_id = block.idx + no_dequanted_input_vars = True + for name in op.input_arg_names: + if name in dequanted_vars[block_id]: + dequant_var = dequanted_vars[block_id][name] + op._rename_input(name, dequant_var.name) + no_dequanted_input_vars = False + if no_dequanted_input_vars: + raise ValueError("There is no dequanted inputs for op %s." % + (op.type)) + + with program_guard(program, startup_program): + self._create_global_step() + for block in program.blocks: + ops = list(block.ops) + block_id = block.idx + for op in ops: + # rewrite the forward ProgramDes + if op.type in _QUANTIZABLE_OP_TYPES: + _transpile_forward(block, op) + # rename the backward op inputs + if op.type in grad_op_types: + _transpile_backward(block, op) + + def _create_global_step(self): + if self.weight_quantize_type == 'range_abs_max' or \ + self.activation_quantize_type == 'range_abs_max': + self.global_step = autoincreased_step_counter() + + def freeze_program(self, program, place, scope=None): + """Freeze input training program for inference. + + Args: + program (Program): the input program to be transpile. + """ + + self.is_test = True + scope = global_scope() if scope is None else scope + program = default_main_program() if program is None else program + + persistable_vars = [ + v.name + for v in filter(lambda var: var.persistable, program.list_vars()) + ] + op_in_rename_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + op_out_rename_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + var_scale_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + + def _remove_fake_quant_and_dequant_op(block, op): + idx = block.ops.index(op) + block_id = block.idx + k = op.output('Out')[0] + v = op.input('X')[0] + if v not in op_in_rename_map[block_id]: + op_in_rename_map[block_id][k] = v + else: + op_in_rename_map[block_id][k] = op_in_rename_map[block_id][v] + block._remove_op(idx) + + def _insert_post_dequant_op(block, op): + idx = block.ops.index(op) + block_id = block.idx + max_range = None + scale_var = None + for name in op.input_arg_names: + #rename input name of the op to the input name of last op which has be removed + if name in op_in_rename_map[block_id]: + op._rename_input(name, op_in_rename_map[block_id][name]) + + scale_v = var_scale_map[block_id][_original_var_name(name)] + if _original_var_name(name) in persistable_vars: + param_range = (1 << (self.weight_bits - 1)) - 1 + act_range = (1 << (self.activation_bits - 1)) - 1 + assert _is_float(scale_v) + max_range = param_range * act_range / scale_v + else: + assert isinstance(scale_v, Variable) + scale_var = scale_v + + if len(op.output_arg_names) != 1: + raise ValueError("Only support one output, but op %s has" + " more than one output." % (op.type)) + out_var = block.var(op.output_arg_names[0]) + dequant_var = block.create_var(name=_dequantized_var_name( + out_var.name), + type=out_var.type, + shape=out_var.shape, + dtype=out_var.dtype) + # insert fake_dequantize_op + dequant_op = block._insert_op(idx + 1, + type="fake_dequantize_max_abs", + attrs={'max_range': float(max_range)}, + inputs={ + "X": out_var, + 'Scale': scale_var + }, + outputs={"Out": dequant_var}) + op_out_rename_map[block_id][out_var.name] = dequant_var.name + return dequant_var + + def _load_var(name): + return np.array(scope.find_var(name).get_tensor()) + + def _restore_var(name, arr): + t = scope.find_var(name).get_tensor() + t.set(arr, place) + + for block in program.blocks: + ops = list(block.ops) + block_id = block.idx + for op in ops: + op_type = op.type + + # insert dequant_op after fc/conv, need to rename + # input of the followed ops(of fc/conv) to the dquant_op + for name in op.input_arg_names: + if name in op_out_rename_map[block_id]: + op._rename_input(name, + op_out_rename_map[block_id][name]) + + if op_type in self.fake_quant_op_types: + in_arg_name = op.input('X')[0] + if in_arg_name in persistable_vars: + if self.weight_quantize_type == 'abs_max': + param = _load_var(in_arg_name) + scale_v = np.max(np.abs(param)) + else: + scale_v = _load_var(op.output('OutScale')[0]) + var_scale_map[block_id][in_arg_name] = scale_v + else: + scale_v = block.var(op.output('OutScale')[0]) + var_scale_map[block_id][in_arg_name] = scale_v + + if in_arg_name in persistable_vars: + _remove_fake_quant_and_dequant_op(block, op) + # quantize weight and restore + param_t = _load_var(in_arg_name) + param_q_t = quant(param_t, scale_v, self.weight_bits) + _restore_var(in_arg_name, param_q_t) + + if op_type in self.fake_dequant_op_types: + _remove_fake_quant_and_dequant_op(block, op) + + if op_type in _QUANTIZABLE_OP_TYPES: + dequant_var = _insert_post_dequant_op(block, op) + + # remove the unused var in ProgramDesc + self._remove_unused_var(program) + #program = program.clone() + + def convert_to_int8(self, program, place, scope=None): + scope = global_scope() if scope is None else scope + program = default_main_program() if program is None else program + + def _load_var(name): + return np.array(scope.find_var(name).get_tensor()) + + global_block = program.global_block() + + def convert_to_int8(var): + int8_var_name = var.name + ".int8" + int8_var = global_block.create_parameter( + name=int8_var_name.encode('ascii'), + type=var.type, + dtype=core.VarDesc.VarType.INT8, + shape=var.shape) + + tensor = _load_var(var.name) + + scope.var(int8_var_name) + int8_tensor = scope.find_var(int8_var_name).get_tensor() + int8_tensor.set(tensor.astype(np.int8), place) + return int8_var + + input_map = {} + for block in program.blocks: + for op in list(block.ops): + if op.type in _QUANTIZABLE_OP_TYPES: + for name in op.input_arg_names: + var = block.var(name) + if var.persistable: + if name not in input_map: + int8_var = convert_to_int8(var) + input_map[name] = int8_var.name + op._rename_input(name, input_map[name]) + self._remove_unused_var(program) + + def _remove_unused_var(self, program): + all_remove_vars = [] + for block in program.blocks: + args = [] + for op in block.ops: + args += op.input_arg_names + args += op.output_arg_names + args = list(set(args)) #vals of all left ops + var_names = block.vars.keys() # all vals + sub_block_remove_vars = [] + for var in var_names: + if var not in args: + sub_block_remove_vars.append(var) + all_remove_vars.append(sub_block_remove_vars) + + remove_vars = [list(set(v)) for v in all_remove_vars] + for i, block in enumerate(program.blocks): + for v in remove_vars[i]: + block._remove_var(v) + + def _insert_quant_abs_max_op(self, block, idx, var, quant_bits): + """Insert fake_quantize_abs_max op. + """ + quant_var = block.create_var(name=_quantized_var_name(var.name), + type=var.type, + shape=var.shape, + dtype=var.dtype) + scale = block.create_var(name=_quantized_scale_name(var.name), + type=var.type, + shape=var.shape, + dtype=var.dtype) + quant_op = block._insert_op(idx, + type='fake_quantize_abs_max', + attrs={'bit_length': quant_bits}, + inputs={'X': var}, + outputs={ + 'Out': quant_var, + 'OutScale': scale + }) + return quant_var, scale + + def _insert_quant_range_abs_max_op(self, block, idx, var, quant_bits): + """Insert fake_quantize_range_abs_max + """ + quant_var = block.create_var(name=_quantized_var_name(var.name), + type=var.type, + shape=var.shape, + dtype=var.dtype) + scale = self.helper.create_parameter(attr=ParamAttr( + name=_quantized_scale_name(var.name), + initializer=Constant(0.001), + trainable=False), + shape=[1], + dtype=var.dtype) + scale.stop_gradient = True + + ins = {'X': var, 'InScale': scale} + outs = {'Out': quant_var, 'OutScale': scale} + if not self.is_test: + # A global step counter variable with type int64 + scales = self.helper.create_global_variable( + name=unique_name.generate('scales'), + persistable=True, + dtype=var.dtype, + shape=[self.window_size]) + self.helper.set_variable_initializer(scales, + initializer=Constant(value=0)) + + ins['Iter'] = self.global_step + outs['OutScales'] = scales + + attrs = { + 'window_size': self.window_size, + 'bit_length': quant_bits, + 'is_test': self.is_test + } + + quant_op = block._insert_op(idx, + type='fake_quantize_range_abs_max', + attrs=attrs, + inputs=ins, + outputs=outs) + + return quant_var, scale + + def _insert_quant_moving_average_abs_max_op(self, block, idx, var, + quant_bits): + """Insert fake_quantize_moving_average_abs_max + """ + quant_var = block.create_var(name=_quantized_var_name(var.name), + type=var.type, + shape=var.shape, + dtype=var.dtype) + state = self.helper.create_global_variable( + name=unique_name.generate('state'), + persistable=True, + dtype=var.dtype, + shape=[1]) + self.helper.set_variable_initializer(state, + initializer=Constant(value=1)) + accum = self.helper.create_global_variable( + name=unique_name.generate('accum'), + persistable=True, + dtype=var.dtype, + shape=[1]) + self.helper.set_variable_initializer(accum, + initializer=Constant(value=1)) + scale = self.helper.create_parameter(attr=ParamAttr( + name=_quantized_scale_name(var.name), + initializer=Constant(0.001), + trainable=False), + shape=[1], + dtype=var.dtype) + scale.stop_gradient = True + + ins = {'X': var, 'InScale': scale} + outs = {'Out': quant_var, 'OutScale': scale} + if not self.is_test: + ins['InState'] = state + ins['InAccum'] = accum + outs['OutState'] = state + outs['OutAccum'] = accum + + attrs = { + 'bit_length': quant_bits, + 'moving_rate': self.moving_rate, + 'is_test': self.is_test + } + + quant_op = block._insert_op(idx, + type='fake_quantize_moving_average_abs_max', + attrs=attrs, + inputs=ins, + outputs=outs) + + return quant_var, scale + + def _insert_quant_op(self, block, idx, var, quant_bits, quant_type): + """ + Insert fake_quantize_op + """ + if quant_type == 'abs_max': + return self._insert_quant_abs_max_op(block, idx, var, quant_bits) + elif quant_type == 'range_abs_max': + return self._insert_quant_range_abs_max_op(block, idx, var, + quant_bits) + elif quant_type == 'moving_average_abs_max': + return self._insert_quant_moving_average_abs_max_op( + block, idx, var, quant_bits) + + def _insert_dequant_op(self, block, idx, var, scale, quant_bits): + """ + Insert fake_quantize_op + """ + dequant_var = block.create_var(name=_dequantized_var_name(var.name), + type=var.type, + shape=var.shape, + dtype=var.dtype) + # insert fake_dequantize_op + max_range = (1 << (quant_bits - 1)) - 1 + dequant_op = block._insert_op(idx, + type="fake_dequantize_max_abs", + attrs={'max_range': float(max_range)}, + inputs={ + "X": var, + 'Scale': scale + }, + outputs={"Out": dequant_var}) + return dequant_var diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b94a21a7e406b833797f8f521c62a2351c2bc30a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5be249b0eb73eec7cc6e22d3c5111fac5fb8e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/__init__.py @@ -0,0 +1,33 @@ +# 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. + +from __future__ import print_function + +from . import quantization_pass +from .quantization_pass import * +from . import quant_int8_mkldnn_pass +from .quant_int8_mkldnn_pass import * +from . import quant2_int8_mkldnn_pass +from .quant2_int8_mkldnn_pass import * +from . import post_training_quantization +from .post_training_quantization import * +from . import imperative +from .imperative import * + +__all__ = [] +__all__ += quantization_pass.__all__ +__all__ += quant_int8_mkldnn_pass.__all__ +__all__ += quant2_int8_mkldnn_pass.__all__ +__all__ += post_training_quantization.__all__ +__all__ += imperative.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/adaround.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/adaround.py new file mode 100644 index 0000000000000000000000000000000000000000..04d894b055dc6e10bededa2c2b9151cfaad55ec1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/adaround.py @@ -0,0 +1,325 @@ +# Copyright (c) 2021 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. + +import numpy as np +import time +import sys +import logging + +import paddle.fluid as fluid + +from ....log_helper import get_logger +from .utils import load_variable_data, set_variable_data, stable_sigmoid, quant_tensor, dequant_tensor, _channelwise_quant_axis1_ops, calculate_quant_cos_error, bias_correction_w + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + +GAMMA = -0.1 +ZETA = 1.1 + + +def compute_soft_rounding(alpha_v): + return fluid.layers.clip(fluid.layers.sigmoid(alpha_v) * (ZETA - GAMMA) + + GAMMA, + min=0, + max=1) + + +def compute_soft_rounding_np(alpha_v): + return np.clip(stable_sigmoid(alpha_v) * (ZETA - GAMMA) + GAMMA, + a_min=0, + a_max=1) + + +class AdaRoundLoss(object): + + def __init__(self, reg_param=0.01, default_beta_range=(20, 2)): + self.default_reg_param = reg_param + self.default_beta_range = default_beta_range + + def compute_recon_loss(self, ada_quantized_output, orig_output): + square_cost = fluid.layers.square_error_cost(ada_quantized_output, + orig_output) + recon_loss = fluid.layers.reduce_mean( + fluid.layers.reduce_sum(square_cost, dim=-1)) + return recon_loss + + def compute_round_loss(self, alpha_v, warm_start, beta): + + def round_loss_fn(): + # compute rectified sigmoid of parameter 'alpha' which maps it between zero and one + h_v = compute_soft_rounding(alpha_v) + + # calculate regularization term - which ensures parameter to converge to exactly zeros and ones + # at the end of optimization + reg_term = fluid.layers.reduce_sum( + -fluid.layers.pow(fluid.layers.abs(2 * h_v - 1), factor=beta) + + 1) + + # calculate the rounding loss + round_loss = self.default_reg_param * reg_term + + return round_loss + + round_loss = fluid.layers.cond( + warm_start, lambda: fluid.layers.fill_constant( + shape=[1], dtype='float32', value=0.0), round_loss_fn) + + return round_loss + + def compute_beta(self, max_iter, cur_iter, warm_start): + + # Start and stop beta for annealing of rounding loss (start_beta, end_beta) + start_beta, end_beta = self.default_beta_range + + # iteration at end of warm start period, which is 20% of max iterations + warm_start_end_iter = warm_start * max_iter + + # compute relative iteration of current iteration + rel_iter = (cur_iter - warm_start_end_iter) / (max_iter - + warm_start_end_iter) + beta = end_beta + 0.5 * (start_beta - + end_beta) * (1 + np.cos(rel_iter * np.pi)) + + return beta + + +class AdaRound(object): + + def __init__(self, + scale, + weight_tensor, + scope=None, + weight_var_name=None, + weight_op_type=None, + is_train=True, + num_iterations=1000): + self.is_train = is_train + self.num_iterations = num_iterations + self.warm_start = 0.1 + self.weight_bits = 8 + self.offset = 0. # zero-point offset + self.adaround_loss = AdaRoundLoss() + self.ori_weight_tensor = weight_tensor + self.scale = scale + self.scope = scope + self.quant_axis = 0 + if weight_op_type in _channelwise_quant_axis1_ops: + self.quant_axis = 1 + self.weight_var_name = weight_var_name + self.alpha_name = weight_var_name + ".alpha" + self.initialize_alpha(weight_tensor.copy(), scale, weight_var_name) + + def initialize_alpha(self, tensor, scale, var_name): + """ + Initializes alpha parameter, same shape as the weight tensor + """ + tensor_scale = quant_tensor(tensor, scale, quant_axis=self.quant_axis) + tensor_floor = np.floor(tensor_scale) + tensor = tensor_scale - tensor_floor + alpha = -np.log((ZETA - GAMMA) / (tensor - GAMMA) - 1) + self.alpha_v = fluid.layers.create_parameter( + shape=alpha.shape, + dtype="float32", + name=var_name + ".alpha", + default_initializer=fluid.initializer.NumpyArrayInitializer(alpha)) + + def _calculate_output_with_adarounded_weights(self, program, place, exe, + data, fp32_fetch_list, + weight_tensor_dequant): + set_variable_data(self.scope, place, self.weight_var_name, + weight_tensor_dequant) + + adaround_out_tensor = exe.run(program=program, + feed=data, + fetch_list=[fp32_fetch_list], + return_numpy=True, + scope=self.scope) + return adaround_out_tensor + + def _calculate_quant_weight(self): + np_alpha = load_variable_data(self.scope, self.alpha_name) + h_alpha = compute_soft_rounding_np(np_alpha) + + # Scale the tensor + tensor_scale = quant_tensor(self.ori_weight_tensor.copy(), + self.scale, + quant_axis=self.quant_axis) + + weight_tensor = np.floor(tensor_scale) + + # Adaround the tensor + weight_tensor_quant = np.add(weight_tensor, h_alpha) + return weight_tensor_quant + + def _calculate_adarounded_weights(self): + weight_tensor_quant = self._calculate_quant_weight() + + # Dequantize the tensor + weight_tensor_dequant = dequant_tensor(weight_tensor_quant + + self.offset, + self.scale, + quant_axis=self.quant_axis) + return weight_tensor_dequant + + def update_final_weights(self): + weight_tensor_quant = self._calculate_quant_weight() + return weight_tensor_quant + + def get_loss(self, beta, warm_start, adaround_out_tensor, orig_out_tensor): + round_loss = self.adaround_loss.compute_round_loss( + self.alpha_v, warm_start, beta) + recon_loss = self.adaround_loss.compute_recon_loss( + adaround_out_tensor, orig_out_tensor) + loss = round_loss + recon_loss + losses = { + 'loss': loss, + 'round_loss': round_loss, + 'recon_loss': recon_loss + } + return losses + + def update_beta_warm(self, cur_iteration): + warm_start = cur_iteration < self.num_iterations * self.warm_start + beta = self.adaround_loss.compute_beta(self.num_iterations, + cur_iteration, self.warm_start) + return beta, warm_start + + +def run_adaround(data_loader, + fp32_program, + fetch_list, + exe, + scope, + place, + quantized_op_pairs, + weight_op_pairs, + scale_dict, + num_iterations=1000, + lr=0.001, + bias_correction=False, + fast_mode=True): + fetch_op_name = fetch_list[0].name + final_weight_tensor_quant_dict = {} + for weight_var_name, quant_op_out_name in quantized_op_pairs.items(): + _logger.info('Start adaround op: {}'.format(weight_var_name)) + weight_op_type = weight_op_pairs[weight_var_name] + # get scale and weight tensor + weight_var_tensor = load_variable_data(scope, weight_var_name) + scale = scale_dict[weight_var_name] + fp32_fetch_list = None + for _op in fp32_program.global_block().ops: + if _op.type == "fetch": + _op._rename_input(fetch_op_name, quant_op_out_name) + fp32_fetch_list = fp32_program.global_block().var( + quant_op_out_name) + fetch_op_name = quant_op_out_name + + # build adaround program + exec_strategy = fluid.ExecutionStrategy() + exec_strategy.num_iteration_per_drop_scope = 1 + startup_program = fluid.Program() + train_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + with fluid.unique_name.guard(): + # initialize adaround + adaround = AdaRound(scale, + weight_var_tensor, + scope=scope, + weight_var_name=weight_var_name, + weight_op_type=weight_op_type, + num_iterations=num_iterations) + orig_out_tensor = fluid.data(name='orig_out_tensor', + shape=fp32_fetch_list.shape, + dtype='float32') + adaround_out_tensor = fluid.data(name='adaround_out_tensor', + shape=fp32_fetch_list.shape, + dtype='float32') + beta_tensor = fluid.data(name='beta', + shape=[1], + dtype='float32') + warm_start_tensor = fluid.data(name='warm_start', + shape=[1], + dtype='bool') + + train_fetches_loss = adaround.get_loss(beta_tensor, + warm_start_tensor, + adaround_out_tensor, + orig_out_tensor) + optimizer = fluid.optimizer.Adam(learning_rate=lr) + loss = train_fetches_loss['loss'] + optimizer.minimize(loss) + exe.run(startup_program) + + start_time = time.time() + prev_start_time = start_time + for i, data in enumerate(data_loader()): + prev_start_time = start_time + start_time = time.time() + # run fp32 model + np_orig_out_tensor = exe.run(program=fp32_program, + feed=data, + fetch_list=[fp32_fetch_list], + return_numpy=True, + scope=scope) + + adaround_weight_tensor_dequant = adaround._calculate_adarounded_weights( + ) + np_adaround_out_tensor = adaround._calculate_output_with_adarounded_weights( + fp32_program, place, exe, data, fp32_fetch_list, + adaround_weight_tensor_dequant) + + # If the cosine distance of the two tensor is small, skip training + cos_error = calculate_quant_cos_error(np_orig_out_tensor[0], + np_adaround_out_tensor[0]) + if fast_mode and cos_error > 0.99: + _logger.info("The cosine error is small, skip training.") + break + beta, warm_start = adaround.update_beta_warm(i) + feed_dict = { + 'orig_out_tensor': np_orig_out_tensor[0], + 'adaround_out_tensor': np_adaround_out_tensor[0], + 'beta': beta, + 'warm_start': warm_start + } + out = exe.run( + train_program, + feed=feed_dict, + fetch_list=[v.name for v in train_fetches_loss.values()], + return_numpy=True) + _logger.info( + "Iter {:d}, lr {:.5f}, loss {:.5f}, loss_round {:.5f}, loss_recon {:.5f}, time {:.5f}s" + .format(i, lr, np.mean(out[0]), np.mean(out[1]), + np.mean(out[2]), start_time - prev_start_time)) + sys.stdout.flush() + if i == num_iterations: + break + final_weight_tensor_quant_dict[ + weight_var_name] = adaround.update_final_weights() + + if bias_correction: + final_weight_tensor_quant_dict[weight_var_name] = bias_correction_w( + weight_var_tensor, + final_weight_tensor_quant_dict[weight_var_name], + scale, + adaround.quant_axis, + weight_bits=adaround.weight_bits) + + del adaround + + # update adarounded calibrated weights + for weight_var_name in quantized_op_pairs.keys(): + set_variable_data(scope, place, weight_var_name, + final_weight_tensor_quant_dict[weight_var_name]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/cal_kl_threshold.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/cal_kl_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..69cd3f64061628a5db015886bc5966df045ec55d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/cal_kl_threshold.py @@ -0,0 +1,135 @@ +# Copyright (c) 2021 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. + +import logging +import math +import numpy as np +from ....log_helper import get_logger + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + +__all__ = ['cal_kl_threshold'] + + +def expand_quantized_bins(quantized_bins, reference_bins): + ''' + Expand hist bins. + ''' + expanded_quantized_bins = [0] * len(reference_bins) + num_merged_bins = int(len(reference_bins) / len(quantized_bins)) + j_start = 0 + j_end = num_merged_bins + for idx in range(len(quantized_bins)): + zero_count = reference_bins[j_start:j_end].count(0) + num_merged_bins = j_end - j_start + if zero_count == num_merged_bins: + avg_bin_ele = 0 + else: + avg_bin_ele = quantized_bins[idx] / (num_merged_bins - zero_count + + 0.0) + for idx1 in range(j_start, j_end): + expanded_quantized_bins[idx1] = (0 if reference_bins[idx1] == 0 else + avg_bin_ele) + j_start += num_merged_bins + j_end += num_merged_bins + if (idx + 1) == len(quantized_bins) - 1: + j_end = len(reference_bins) + return expanded_quantized_bins + + +def safe_entropy(reference_distr_P, P_sum, candidate_distr_Q, Q_sum): + ''' + Calculate the entropy. + ''' + assert len(reference_distr_P) == len(candidate_distr_Q) + tmp_sum1 = 0 + tmp_sum2 = 0 + for idx in range(len(reference_distr_P)): + p_idx = reference_distr_P[idx] + q_idx = candidate_distr_Q[idx] + if p_idx == 0: + tmp_sum1 += 0 + tmp_sum2 += 0 + else: + if q_idx == 0: + _logger.error("Fatal error!, idx = " + str(idx) + + " qindex = 0! p_idx = " + str(p_idx)) + tmp_sum1 += p_idx * (math.log(Q_sum * p_idx)) + tmp_sum2 += p_idx * (math.log(P_sum * q_idx)) + return (tmp_sum1 - tmp_sum2) / P_sum + + +def cal_kl_threshold(hist, bin_width, bits): + ''' + Using the KL-divergenc method to get the more precise threshold. + + Args: + hist(List): The hist of the tensor. + bin_width(float): The bin width for the hist. + bits(int): The quantization bits. + ''' + assert hist.ndim == 1 + hist_bins = hist.shape[0] + starting_iter = int((hist_bins - 1) * 0.5) + quant_range = 2**(bits - 1) - 1 + + P_sum = np.sum(np.array(hist).ravel()) + min_kl_divergence = 0 + min_kl_index = 0 + kl_inited = False + + for i in range(starting_iter, hist_bins): + reference_distr_P = hist[0:i].tolist() + outliers_count = sum(hist[i:]) + if reference_distr_P[i - 1] == 0: + continue + reference_distr_P[i - 1] += outliers_count + reference_distr_bins = reference_distr_P[:] + candidate_distr_Q = hist[0:i].tolist() + num_merged_bins = int(i / quant_range) + candidate_distr_Q_quantized = [0] * quant_range + j_start = 0 + j_end = num_merged_bins + for idx in range(quant_range): + candidate_distr_Q_quantized[idx] = sum( + candidate_distr_Q[j_start:j_end]) + j_start += num_merged_bins + j_end += num_merged_bins + if (idx + 1) == quant_range - 1: + j_end = i + candidate_distr_Q = expand_quantized_bins(candidate_distr_Q_quantized, + reference_distr_bins) + Q_sum = sum(candidate_distr_Q) + kl_divergence = safe_entropy(reference_distr_P, P_sum, + candidate_distr_Q, Q_sum) + if not kl_inited: + min_kl_divergence = kl_divergence + min_kl_index = i + kl_inited = True + elif kl_divergence < min_kl_divergence: + min_kl_divergence = kl_divergence + min_kl_index = i + else: + pass + if min_kl_index == 0: + while starting_iter > 0: + if hist[starting_iter] == 0: + starting_iter -= 1 + continue + else: + break + min_kl_index = starting_iter + return (min_kl_index + 0.5) * bin_width diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7210da93f7bf570945ec462f9f9cacd831ff8ab4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/__init__.py @@ -0,0 +1,37 @@ +# 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. + +from __future__ import print_function + +from . import qat +from .qat import * + +from . import ptq +from .ptq import * + +from . import ptq_config +from .ptq_config import * + +from . import ptq_quantizer +from .ptq_quantizer import * + +from . import ptq_registry +from .ptq_registry import * + +__all__ = [] +__all__ += qat.__all__ +__all__ += ptq.__all__ +__all__ += ptq_config.__all__ +__all__ += ptq_quantizer.__all__ +__all__ += ptq_registry.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae949bf0fe379be8cb6929ad36d2aeedfef869d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py @@ -0,0 +1,199 @@ +# 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. + +import copy +import paddle +import paddle.nn as nn +from . import utils + + +class Identity(nn.Layer): + '''a layer to replace bn or relu layers''' + + def __init__(self, *args, **kwargs): + super(Identity, self).__init__() + + def forward(self, input): + return input + + +def fuse_conv_bn(model): + is_train = False + if model.training: + model.eval() + is_train = True + fuse_list = [] + tmp_pair = [None, None] + for name, layer in model.named_sublayers(): + if isinstance(layer, nn.Conv2D): + tmp_pair[0] = name + if isinstance(layer, nn.BatchNorm2D): + tmp_pair[1] = name + + if tmp_pair[0] and tmp_pair[1] and len(tmp_pair) == 2: + fuse_list.append(tmp_pair) + tmp_pair = [None, None] + model = fuse_layers(model, fuse_list) + if is_train: + model.train() + + +def fuse_layers(model, layers_to_fuse, inplace=False): + ''' + fuse layers in layers_to_fuse + + Args: + model(paddle.nn.Layer): The model to be fused. + layers_to_fuse(list): The layers' names to be fused. For + example,"fuse_list = [["conv1", "bn1"], ["conv2", "bn2"]]". + A TypeError would be raised if "fuse" was set as + True but "fuse_list" was None. + Default: None. + inplace(bool): Whether apply fusing to the input model. + Default: False. + + Return + fused_model(paddle.nn.Layer): The fused model. + ''' + if inplace == False: + model = copy.deepcopy(model) + for layers in layers_to_fuse: + _fuse_layers(model, layers) + return model + + +def _fuse_layers(model, layers_list): + '''fuse all the layers in layers_list''' + layer_list = [] + for layer_name in layers_list: + parent_layer, sub_name = utils.find_parent_layer_and_sub_name( + model, layer_name) + layer_list.append(getattr(parent_layer, sub_name)) + new_layers = _fuse_func(layer_list) + for i, item in enumerate(layers_list): + parent_layer, sub_name = utils.find_parent_layer_and_sub_name( + model, item) + setattr(parent_layer, sub_name, new_layers[i]) + + +def _fuse_func(layer_list): + '''choose the fuser method and fuse layers''' + types = tuple(type(m) for m in layer_list) + fusion_method = types_to_fusion_method.get(types, None) + new_layers = [None] * len(layer_list) + fused_layer = fusion_method(*layer_list) + for handle_id, pre_hook_fn in layer_list[0]._forward_pre_hooks.items(): + fused_layer.register_forward_pre_hook(pre_hook_fn) + del layer_list[0]._forward_pre_hooks[handle_id] + for handle_id, hook_fn in layer_list[-1]._forward_post_hooks.items(): + fused_layer.register_forward_post_hook(hook_fn) + del layer_list[-1]._forward_post_hooks[handle_id] + new_layers[0] = fused_layer + for i in range(1, len(layer_list)): + identity = Identity() + identity.training = layer_list[0].training + new_layers[i] = identity + return new_layers + + +def _fuse_conv_bn(conv, bn): + '''fuse conv and bn for train or eval''' + assert(conv.training == bn.training),\ + "Conv and BN both must be in the same mode (train or eval)." + if conv.training: + assert bn._num_features == conv._out_channels, 'Output channel of Conv2d must match num_features of BatchNorm2d' + raise NotImplementedError + else: + return _fuse_conv_bn_eval(conv, bn) + + +def _fuse_conv_bn_eval(conv, bn): + '''fuse conv and bn for eval''' + assert (not (conv.training or bn.training)), "Fusion only for eval!" + fused_conv = copy.deepcopy(conv) + + fused_weight, fused_bias = _fuse_conv_bn_weights(fused_conv.weight, + fused_conv.bias, bn._mean, + bn._variance, bn._epsilon, + bn.weight, bn.bias) + fused_conv.weight.set_value(fused_weight) + if fused_conv.bias is None: + fused_conv.bias = paddle.create_parameter( + shape=[fused_conv._out_channels], is_bias=True, dtype=bn.bias.dtype) + fused_conv.bias.set_value(fused_bias) + return fused_conv + + +def _fuse_conv_bn_weights(conv_w, conv_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b): + '''fuse weights and bias of conv and bn''' + if conv_b is None: + conv_b = paddle.zeros_like(bn_rm) + if bn_w is None: + bn_w = paddle.ones_like(bn_rm) + if bn_b is None: + bn_b = paddle.zeros_like(bn_rm) + bn_var_rsqrt = paddle.rsqrt(bn_rv + bn_eps) + conv_w = conv_w * \ + (bn_w * bn_var_rsqrt).reshape([-1] + [1] * (len(conv_w.shape) - 1)) + conv_b = (conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b + return conv_w, conv_b + + +def _fuse_linear_bn(linear, bn): + '''fuse linear and bn''' + assert (linear.training == bn.training),\ + "Linear and BN both must be in the same mode (train or eval)." + if linear.training: + assert bn._num_features == linear.weight.shape[ + 1], 'Output channel of Linear must match num_features of BatchNorm' + raise NotImplementedError + else: + return _fuse_linear_bn_eval(linear, bn) + + +def _fuse_linear_bn_eval(linear, bn): + '''fuse linear and bn for eval''' + assert (not (linear.training or bn.training)), "Fusion only for eval!" + fused_linear = copy.deepcopy(linear) + + fused_weight, fused_bias = _fuse_linear_bn_weights(fused_linear.weight, + fused_linear.bias, + bn._mean, bn._variance, + bn._epsilon, bn.weight, + bn.bias) + fused_linear.weight.set_value(fused_weight) + if fused_linear.bias is None: + fused_linear.bias = paddle.create_parameter( + shape=[fused_linear.weight.shape[1]], + is_bias=True, + dtype=bn.bias.dtype) + fused_linear.bias.set_value(fused_bias) + return fused_linear + + +def _fuse_linear_bn_weights(linear_w, linear_b, bn_rm, bn_rv, bn_eps, bn_w, + bn_b): + '''fuse weights and bias of linear and bn''' + if linear_b is None: + linear_b = paddle.zeros_like(bn_rm) + bn_scale = bn_w * paddle.rsqrt(bn_rv + bn_eps) + fused_w = linear_w * bn_scale.unsqueeze(-1) + fused_b = (linear_b - bn_rm) * bn_scale + bn_b + return fused_w, fused_b + + +types_to_fusion_method = { + (nn.Conv2D, nn.BatchNorm2D): _fuse_conv_bn, + (nn.Linear, nn.BatchNorm1D): _fuse_linear_bn, +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq.py new file mode 100644 index 0000000000000000000000000000000000000000..febdacdf43eace93701438f06c8d0236196af7ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq.py @@ -0,0 +1,485 @@ +# Copyright (c) 2021 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. + +import logging +import copy +import os +import numpy as np + +import paddle +import paddle.nn.quant.quant_layers as quant_layers +from paddle.fluid.log_helper import get_logger +from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX + +from . import fuse_utils +from . import utils +from . import ptq_hooks +from . import ptq_config +from . import ptq_quantizer +from .ptq_registry import PTQRegistry + +__all__ = ['ImperativePTQ'] + +_logger = get_logger( + __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s' +) + + +class ImperativePTQ(object): + """ + Static post training quantization. + """ + + def __init__(self, quant_config=ptq_config.default_ptq_config): + """ + Constructor. + + Args: + quant_config(PTQConfig): the config of post training quantization. + The config has weight_quantizer and activation_quantizer. + In default, the weight_quantizer is PerChannelAbsmaxQuantizer + and the activation_quantizer is KLQuantizer. + """ + super(ImperativePTQ, self).__init__() + + assert isinstance(quant_config, ptq_config.PTQConfig) + + self._quant_config = quant_config + + def quantize(self, model, inplace=False, fuse=False, fuse_list=None): + """ + Add quant config and hook to the target layer. + + Args: + model(paddle.nn.Layer): The model to be quantized. + inplace(bool): Whether apply quantization to the input model. + Default: False. + fuse(bool): Whether to fuse layers. + Default: False. + fuse_list(list): The layers' names to be fused. For example, + "fuse_list = [["conv1", "bn1"], ["conv2", "bn2"]]". + A TypeError would be raised if "fuse" was set as + True but "fuse_list" was None. + Default: None. + Return + quantized_model(paddle.nn.Layer): The quantized model. + """ + assert isinstance( + model, paddle.nn.Layer + ), "The model must be the instance of paddle.nn.Layer." + if not inplace: + model = copy.deepcopy(model) + if fuse: + model.eval() + model = fuse_utils.fuse_layers(model, fuse_list) + for name, layer in model.named_sublayers(): + if ( + PTQRegistry.is_supported_layer(layer) + and utils.is_leaf_layer(layer) + and not self._is_skip_layer(layer) + ): + + # Add quant config + quant_config = copy.deepcopy(self._quant_config) + if PTQRegistry.is_simulated_quant_layer(layer): + quant_config.enable_in_act_quantizer = True + layer._quant_config = quant_config + + # register hook + hook = ptq_hooks.quant_forward_post_hook + quant_hook_handle = layer.register_forward_post_hook(hook) + quant_config.quant_hook_handle = quant_hook_handle + layer._forward_post_hooks.move_to_end( + quant_hook_handle._hook_id, last=False + ) + + return model + + def save_quantized_model(self, model, path, input_spec=None, **config): + """ + 1. Convert the quantized model + 2. Call jit.save to save the inference model + 3. Post process the inference model. + + Args: + model (Layer): The model to be saved. + path (str): The path prefix to save model. The format is + ``dirname/file_prefix`` or ``file_prefix``. + input_spec (list[InputSpec|Tensor], optional): Describes the input + of the saved model's forward method, which can be described by + InputSpec or example Tensor. If None, all input variables of + the original Layer's forward method would be the inputs of + the saved model. Default None. + **config (dict, optional): Other save configuration options for + compatibility. We do not recommend using these configurations, + they may be removed in the future. If not necessary, DO NOT use + them. Default None. + The following options are currently supported: + (1) output_spec (list[Tensor]): Selects the output targets of + the saved model. By default, all return variables of original + Layer's forward method are kept as the output of the saved model. + If the provided ``output_spec`` list is not all output variables, + the saved model will be pruned according to the given + ``output_spec`` list. + + Returns: + None + """ + + assert isinstance( + model, paddle.nn.Layer + ), "The model must be the instance of paddle.nn.Layer." + + # Convert and save dygraph quantized model + self._convert(model) + + paddle.jit.save(layer=model, path=path, input_spec=input_spec, **config) + + # Load inference program + is_dynamic_mode = False + if paddle.in_dynamic_mode(): + is_dynamic_mode = True + paddle.enable_static() + + place = paddle.CPUPlace() + scope = paddle.static.global_scope() + exe = paddle.static.Executor(place) + + dirname = os.path.dirname(path) + basename = os.path.basename(path) + model_filename = basename + INFER_MODEL_SUFFIX + params_filename = basename + INFER_PARAMS_SUFFIX + + [ + infer_program, + feed_target_names, + fetch_targets, + ] = paddle.fluid.io.load_inference_model( + dirname=dirname, + executor=exe, + model_filename=model_filename, + params_filename=params_filename, + ) + + # Process inference program + self._clean_up(infer_program) + self._gather_input_thresholds(infer_program, scope) + self._remove_scale_op(infer_program) + + # Save final program + paddle.fluid.io.save_inference_model( + dirname=dirname, + feeded_var_names=feed_target_names, + target_vars=fetch_targets, + executor=exe, + main_program=infer_program.clone(), + model_filename=model_filename, + params_filename=params_filename, + ) + + if is_dynamic_mode: + paddle.disable_static() + + def _convert(self, model): + """ + Convert the quantized model. + + Args: + model(paddle.nn.Layer): The quantized model. + inplace(bool): Whether apply conversion to the input model. + Default: False. + Returns: + None + """ + + for name, sub_layer in model.named_sublayers(): + if self._is_quant_layer(sub_layer): + sub_layer._quant_config.quant_hook_handle.remove() + + self._cal_thresholds(model) + + for name, sub_layer in model.named_sublayers(): + if self._is_quant_layer(sub_layer): + self._save_output_thresholds(sub_layer, sub_layer._quant_config) + + self._wrap_simulated_layers(model) + + def _cal_thresholds(self, model): + """ + Calculate the thresholds of inputs and outputs. + + Args: + model(paddle.nn.Layer): The quantized model. + Returns: + None + """ + assert isinstance( + model, paddle.nn.Layer + ), "The input model must be the instance of paddle.nn.Layer." + + total_num = 0 + cur_num = 0 + for name, sub_layer in model.named_sublayers(): + if self._is_quant_layer(sub_layer): + total_num += 1 + + for name, sub_layer in model.named_sublayers(): + if self._is_quant_layer(sub_layer): + cur_num += 1 + if cur_num % 5 == 0: + _logger.info( + "Process the %s / %s layer" % (cur_num, total_num) + ) + + quant_config = sub_layer._quant_config + + if quant_config.enable_in_act_quantizer: + quant_config.in_act_quantizer.cal_thresholds() + quant_config.out_act_quantizer.cal_thresholds() + + if PTQRegistry.is_simulated_quant_layer(sub_layer): + weights = (sub_layer.weight,) + quant_config.wt_quantizer.sample_data(sub_layer, weights) + quant_config.wt_quantizer.cal_thresholds() + + def _save_output_thresholds(self, sub_layer, quant_config): + """ + Save the output thresholds to the layer. + + Args: + sub_layer(paddle.nn.Layer): The quantized layer. + quant_config(PTQConfig): the quant config for the layer. + Returns: + None + """ + assert isinstance( + sub_layer, paddle.nn.Layer + ), "The input model must be the instance of paddle.nn.Layer." + + layer_info = PTQRegistry.layer_info(sub_layer) + + output_names = layer_info.output_names + output_thresholds = quant_config.out_act_quantizer.thresholds + assert len(output_names) == 1 + if len(output_thresholds) == 1: + save_name = output_names[0] + str(0) + "_threshold" + sub_layer._set_op_attrs({save_name: output_thresholds[0]}) + sub_layer._set_op_attrs({"out_threshold": output_thresholds[0]}) + else: + _logger.warning( + "output_thresholds shape of {} need to be 1, but received {}".format( + output_names[0], len(output_thresholds) + ) + ) + + def _wrap_simulated_layers(self, model): + """ + Replace conv2d and linear with the quantized layers, and save + thresholds into the fake layers. + Args: + model(paddle.nn.Layer): The model to be quantized. + Returns: + None + """ + assert isinstance( + model, paddle.nn.Layer + ), "The input model must be the instance of paddle.nn.Layer." + + for name, sub_layer in model.named_sublayers(): + if self._is_quant_layer( + sub_layer + ) and PTQRegistry.is_simulated_quant_layer(sub_layer): + + quant_config = sub_layer._quant_config + assert quant_config.enable_in_act_quantizer == True + wt_quantizer = quant_config.wt_quantizer + in_act_quantizer = quant_config.in_act_quantizer + + # create layer + quant_layer_name = None + for key, value in utils.layer_name_map.items(): + if isinstance(sub_layer, value): + quant_layer_name = 'Quantized' + key + break + assert quant_layer_name is not None + + if isinstance(wt_quantizer, ptq_quantizer.AbsmaxQuantizer): + weight_quantize_type = "abs_max" + else: + weight_quantize_type = "channel_wise_abs_max" + kwargs = { + "weight_quantize_type": weight_quantize_type, + "activation_quantize_type": "moving_average_abs_max", + "weight_bits": wt_quantizer.quant_bits, + "activation_bits": in_act_quantizer.quant_bits, + } + + quant_layer = quant_layers.__dict__[quant_layer_name]( + sub_layer, **kwargs + ) + + # save the input thresholds + assert hasattr(quant_layer, "_fake_quant_input") + assert hasattr(quant_layer._fake_quant_input, "_scale") + if len(in_act_quantizer.thresholds) == 1: + input_threshold = np.array( + [in_act_quantizer.thresholds[0]], dtype=np.float32 + ) + quant_layer._fake_quant_input._scale.set_value( + input_threshold + ) + + assert hasattr(quant_layer, "_fake_quant_weight") + assert hasattr(quant_layer._fake_quant_weight, "_scale") + assert len(wt_quantizer.thresholds) == 1 + weight_threshold = wt_quantizer.thresholds[0] + if isinstance(weight_threshold, list): + weight_threshold = np.array( + weight_threshold, dtype=np.float32 + ) + else: + weight_threshold = np.array( + [weight_threshold], dtype=np.float32 + ) + quant_layer._fake_quant_weight._scale.set_value( + weight_threshold + ) + + # save the output thresholds + self._save_output_thresholds(quant_layer, quant_config) + + # replace the layer + parent_layer, sub_name = utils.find_parent_layer_and_sub_name( + model, name + ) + setattr(parent_layer, sub_name, quant_layer) + + def _gather_input_thresholds(self, program, scope): + """ + Get and save input thresholds from the front ops. + + Args: + program(Program): the input infer program. + scope(Scope): the corresponding scope for the program. + Returns: + None + """ + for op in utils.program_all_ops(program): + for in_var_name in utils._get_op_input_var_names(op): + previous_op = utils.find_previous_op(op.block, in_var_name) + if previous_op is None: + continue + + if ( + "quantize_dequantize" in previous_op.type + or previous_op.type == "moving_average_abs_max_scale" + ): + attr_name = previous_op.output('OutScale')[0] + in_threshold = utils.load_variable_data(scope, attr_name) + in_threshold = utils.fp_numpy_to_naive(in_threshold) + argname, index = utils._get_input_name_index( + op, in_var_name + ) + op._set_attr( + argname + str(index) + "_threshold", in_threshold + ) + op._set_attr("with_quant_attr", True) + else: + for out_var_name in utils._get_op_output_var_names( + previous_op + ): + if out_var_name != in_var_name: + continue + argname, index = utils._get_output_name_index( + previous_op, out_var_name + ) + attr_name = argname + str(index) + "_threshold" + if not previous_op.has_attr(attr_name): + continue + threshold = previous_op.attr(attr_name) + + argname, index = utils._get_input_name_index( + op, in_var_name + ) + attr_name = argname + str(index) + "_threshold" + op._set_attr(attr_name, threshold) + op._set_attr("with_quant_attr", True) + + def _clean_up(self, program): + """ + Remove useless thresholds which are added in jit.save. + + Args: + program(Program): the input infer program. + Returns: + None + """ + + def _helper(op, next_op, old_attr_name, new_attr_name): + if ( + op.has_attr(old_attr_name) + and next_op.has_attr(old_attr_name) + and op.attr(old_attr_name) == next_op.attr(old_attr_name) + ): + threshold = op.attr(old_attr_name) + op._remove_attr(old_attr_name) + next_op._remove_attr(old_attr_name) + next_op._set_attr(new_attr_name, threshold) + next_op._set_attr("with_quant_attr", True) + + for op in utils.program_all_ops(program): + if "quantize_dequantize" in op.type: + # remove the thresholds in fake ops + for attr_name in op.attr_names: + if "_threshold" in attr_name: + op._remove_attr(attr_name) + elif op.type in ["conv2d", "matmul"]: + # change the thresholds in conv2d/matmul + eleadd + arg_name = "Output" if op.type == "conv2d" else "Out" + out_var_name = op.output(arg_name)[0] + next_ops = utils.find_next_ops(op.block, out_var_name) + if len(next_ops) > 1 or next_ops[0].type != "elementwise_add": + continue + next_op = next_ops[0] + + argname, index = utils._get_output_name_index(op, out_var_name) + old_attr_name = argname + str(index) + "_threshold" + + argname, index = utils._get_output_name_index( + next_op, next_op.output("Out")[0] + ) + new_attr_name = argname + str(index) + "_threshold" + + _helper(op, next_op, old_attr_name, new_attr_name) + _helper(op, next_op, "out_threshold", "out_threshold") + + def _remove_scale_op(self, program): + """ + Remove the moving_average_abs_max_scale op. + """ + for op in utils.program_all_ops(program): + if op.type == "moving_average_abs_max_scale": + in_var_name = op.input("X")[0] + out_var_name = op.output("Out")[0] + next_ops = utils.find_next_ops(op.block, out_var_name) + for next_op in next_ops: + next_op._rename_input(out_var_name, in_var_name) + + @staticmethod + def _is_skip_layer(layer): + return hasattr(layer, "skip_quant") and layer.skip_quant == True + + @staticmethod + def _is_quant_layer(layer): + return hasattr(layer, "_quant_config") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_config.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_config.py new file mode 100644 index 0000000000000000000000000000000000000000..384d2c704fd88e683a077a1154be5ba98feb0806 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_config.py @@ -0,0 +1,56 @@ +# Copyright (c) 2021 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. + +import six +import abc +import copy + +import paddle + +from .ptq_quantizer import * + +__all__ = ['PTQConfig', 'default_ptq_config'] + + +class PTQConfig(object): + """ + The PTQ config shows how to quantize the inputs and outputs. + """ + + def __init__(self, activation_quantizer, weight_quantizer): + """ + Constructor. + + Args: + activation_quantizer(BaseQuantizer): The activation quantizer. + It should be the instance of BaseQuantizer. + weight_quantizer(BaseQuantizer): The weight quantizer. + It should be the instance of BaseQuantizer. + """ + super(PTQConfig, self).__init__() + assert isinstance(activation_quantizer, tuple(SUPPORT_ACT_QUANTIZERS)) + assert isinstance(weight_quantizer, tuple(SUPPORT_WT_QUANTIZERS)) + + self.in_act_quantizer = copy.deepcopy(activation_quantizer) + self.out_act_quantizer = copy.deepcopy(activation_quantizer) + self.wt_quantizer = copy.deepcopy(weight_quantizer) + + self.quant_hook_handle = None + + # In order to wrap simulated layers, use in_act_quantizer + # to calculate the input thresholds for conv2d, linear and etc. + self.enable_in_act_quantizer = False + + +default_ptq_config = PTQConfig(KLQuantizer(), PerChannelAbsmaxQuantizer()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_hooks.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..41c9b07195aefd867c2762476c8c94cb812b7074 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_hooks.py @@ -0,0 +1,32 @@ +# Copyright (c) 2021 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. + +import paddle +import math +import numpy as np +from . import ptq_config +from .ptq_registry import PTQRegistry + + +def quant_forward_post_hook(layer, inputs, outputs): + """ + The forward_post_hook for PTQ. + """ + assert hasattr(layer, '_quant_config'), \ + "The layer should have _quant_config attr" + + qc = layer._quant_config + if qc.enable_in_act_quantizer: + qc.in_act_quantizer.sample_data(layer, inputs) + qc.out_act_quantizer.sample_data(layer, (outputs, )) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_quantizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0988f24a1837f6f8af5e69c3fa69da9b74b7c5ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_quantizer.py @@ -0,0 +1,270 @@ +# Copyright (c) 2021 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. + +import six +import abc +import copy +import math +import numpy as np + +import paddle + +from . import utils +from ..cal_kl_threshold import cal_kl_threshold + +__all__ = [ + 'BaseQuantizer', 'AbsmaxQuantizer', 'PerChannelAbsmaxQuantizer', + 'KLQuantizer', 'HistQuantizer', 'SUPPORT_ACT_QUANTIZERS', + 'SUPPORT_WT_QUANTIZERS' +] + + +def abs_max_value(tensor): + return float(paddle.max(paddle.abs(tensor)).numpy()) + + +def merge_max_value(old, new): + """ + Merge the max element one by one in two lists. + """ + assert isinstance(old, list) and isinstance(new, list) + if old != []: + assert len(old) == len(new) + for i in range(len(old)): + assert type(old[i]) == type(new[i]) + if isinstance(old[i], list): + new[i] = merge_max_value(old[i], new[i]) + else: + new[i] = old[i] if new[i] < old[i] else new[i] + return new + + +def combine_abs_max_and_hist(tensor, origin_max, origin_hist, bins, + upsample_bins): + """ + """ + + new_max = abs_max_value(tensor) + + if new_max == 0.0: + return origin_max, origin_hist + elif origin_max == 0.0: + new_hist, _ = np.histogram(paddle.abs(tensor).numpy(), + range=(0, new_max), + bins=bins) + new_hist = new_hist.astype(np.float32) + return new_max, new_hist + elif new_max <= origin_max: + new_hist, _ = np.histogram(paddle.abs(tensor).numpy(), + range=(0, origin_max), + bins=bins) + new_hist = new_hist.astype(np.float32) + new_hist += origin_hist + return origin_max, new_hist + else: + # bin_width = origin_max / (bins * upsample_bins) + # = new_max / (bins * downsample_bins) + bin_width = origin_max / (bins * upsample_bins) + downsampe_bins = int(math.ceil(new_max / (bins * bin_width))) + new_max = bins * bin_width * downsampe_bins + + upsampled_hist = np.repeat(origin_hist, upsample_bins) + expanded_hist = np.zeros((bins * downsampe_bins), dtype=np.float32) + expanded_hist[0:bins * upsample_bins] = upsampled_hist + cumsumed_hist = np.cumsum( + expanded_hist, dtype=np.float64)[downsampe_bins - 1::downsampe_bins] + shift_cumsumed_hist = np.zeros((bins), dtype=np.float64) + shift_cumsumed_hist[1:] = cumsumed_hist[0:-1] + sampled_hist = (cumsumed_hist - shift_cumsumed_hist) / upsample_bins + sampled_hist = sampled_hist.astype(np.float32) + + new_hist, _ = np.histogram(paddle.abs(tensor).numpy(), + range=(0, new_max), + bins=bins) + new_hist = new_hist.astype(np.float32) + new_hist += sampled_hist + + return new_max, new_hist + + +@six.add_metaclass(abc.ABCMeta) +class BaseQuantizer(object): + """ + Base quantizer for activation and weight. + """ + + def __init__(self, quant_bits=8): + super(BaseQuantizer, self).__init__() + assert isinstance(quant_bits, int) + assert quant_bits > 0 and quant_bits <= 16 + + self.quant_bits = quant_bits + + self.abs_max_vals = [] + self.thresholds = [] + + @abc.abstractmethod + def sample_data(self, layer, tensors): + pass + + @abc.abstractmethod + def cal_thresholds(self): + pass + + +class AbsmaxQuantizer(BaseQuantizer): + """ + Per-tensor abs max quantizer. + """ + + def __init__(self, quant_bits=8): + super(AbsmaxQuantizer, self).__init__(quant_bits) + + def sample_data(self, layer, tensors): + assert isinstance(tensors, tuple) + + abs_max_vals = [abs_max_value(t) for t in tensors] + self.abs_max_vals = merge_max_value(self.abs_max_vals, abs_max_vals) + + def cal_thresholds(self): + self.thresholds = self.abs_max_vals + + +class PerChannelAbsmaxQuantizer(BaseQuantizer): + """ + Per channel abs max quantizer. + """ + + def __init__(self, quant_bits=8): + super(PerChannelAbsmaxQuantizer, self).__init__(quant_bits) + + def sample_data(self, layer, tensors): + assert isinstance(layer, paddle.nn.Layer) + assert isinstance(tensors, tuple) + + abs_max_vals_list = [] + for idx, tensor in enumerate(tensors): + if isinstance(layer, tuple(utils.spec_channel_axis_layers)): + abs_max_vals = [ + abs_max_value(tensor[:, i]) for i in range(tensor.shape[1]) + ] + abs_max_vals_list.append(abs_max_vals) + else: + abs_max_vals = [ + abs_max_value(tensor[i]) for i in range(tensor.shape[0]) + ] + abs_max_vals_list.append(abs_max_vals) + + self.abs_max_vals = merge_max_value(self.abs_max_vals, + abs_max_vals_list) + + def cal_thresholds(self): + self.thresholds = self.abs_max_vals + + +@six.add_metaclass(abc.ABCMeta) +class BaseHistQuantizer(BaseQuantizer): + """ + """ + + def __init__(self, quant_bits=8, bins=1024, upsample_bins=64): + super(BaseHistQuantizer, self).__init__(quant_bits) + self.bins = bins + self.upsample_bins = upsample_bins + + self.hists = [] + + def sample_data(self, layer, tensors): + assert isinstance(tensors, tuple) + + if self.abs_max_vals == []: + abs_max_vals = [abs_max_value(t) for t in tensors] + self.abs_max_vals = abs_max_vals + + for idx, tensor in enumerate(tensors): + if abs_max_vals[idx] == 0.0: + self.hists.append(None) + else: + hist, _ = np.histogram(paddle.abs(tensor).numpy(), + range=(0., abs_max_vals[idx]), + bins=self.bins) + hist = hist.astype(np.float32) + self.hists.append(hist) + else: + assert len(self.abs_max_vals) == len(tensors) + assert len(self.hists) == len(tensors) + + for idx, tensor in enumerate(tensors): + new_abs_max, new_hist = combine_abs_max_and_hist( + tensor, self.abs_max_vals[idx], self.hists[idx], self.bins, + self.upsample_bins) + self.abs_max_vals[idx] = new_abs_max + self.hists[idx] = new_hist + + @abc.abstractmethod + def cal_thresholds(self): + pass + + +class HistQuantizer(BaseHistQuantizer): + """ + """ + + def __init__(self, + quant_bits=8, + bins=1024, + upsample_bins=64, + hist_percent=0.99999): + super(HistQuantizer, self).__init__(quant_bits, bins, upsample_bins) + self.hist_percent = hist_percent + + def cal_thresholds(self): + + def _helper(abs_max, hist, percent): + assert hist.ndim == 1 and percent < 1.0 + hist = hist / np.sum(hist, dtype=np.float64) + cumsumed_hist = np.cumsum(hist) + index = np.argwhere(cumsumed_hist >= percent)[0] + return float((index - 0.5) * (abs_max / hist.shape[0])) + + for idx in range(len(self.hists)): + if self.hists[idx] is None: + self.thresholds.append(self.abs_max_vals[idx]) + else: + threshold = _helper(self.abs_max_vals[idx], self.hists[idx], + self.hist_percent) + self.thresholds.append(threshold) + + +class KLQuantizer(BaseHistQuantizer): + """ + """ + + def __init__(self, quant_bits=8, bins=1024, upsample_bins=64): + super(KLQuantizer, self).__init__(quant_bits, bins, upsample_bins) + + def cal_thresholds(self): + for idx in range(len(self.hists)): + if self.hists[idx] is None: + self.thresholds.append(self.abs_max_vals[idx]) + else: + hist = self.hists[idx] + abs_max_val = self.abs_max_vals[idx] + bin_width = abs_max_val / hist.shape[0] + threshold = cal_kl_threshold(hist, bin_width, self.quant_bits) + self.thresholds.append(threshold) + + +SUPPORT_ACT_QUANTIZERS = [AbsmaxQuantizer, HistQuantizer, KLQuantizer] +SUPPORT_WT_QUANTIZERS = [AbsmaxQuantizer, PerChannelAbsmaxQuantizer] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_registry.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b6a243abece6a85b212886771b7e244002c41f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/ptq_registry.py @@ -0,0 +1,145 @@ +# Copyright (c) 2021 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. + +import paddle + +__all__ = ['PTQRegistry'] + + +class LayerInfo(object): + """ + Store the argnames of the inputs and outputs. + """ + + def __init__(self, layer, input_names, weight_names, output_names): + super(LayerInfo, self).__init__() + self.layer = layer + self.input_names = input_names + self.weight_names = weight_names + self.output_names = output_names + + +PTQ_LAYERS_INFO = [ + LayerInfo(paddle.nn.Conv2D, ['Input'], ['Filter'], ['Output']), + LayerInfo(paddle.nn.Linear, ['X'], ['Y'], ['Out']), + LayerInfo(paddle.nn.BatchNorm2D, ['X'], [], ['Y']), + LayerInfo(paddle.nn.AdaptiveMaxPool2D, ['X'], [], ['Out']), + LayerInfo(paddle.nn.AdaptiveAvgPool2D, ['X'], [], ['Out']), + LayerInfo(paddle.nn.AvgPool2D, ['X'], [], ['Out']), + LayerInfo(paddle.nn.MaxPool2D, ['X'], [], ['Out']), + LayerInfo(paddle.nn.ReLU, ['X'], [], ['Out']), + LayerInfo(paddle.nn.ReLU6, ['X'], [], ['Out']), + LayerInfo(paddle.nn.Hardswish, ['X'], [], ['Out']), + LayerInfo(paddle.nn.Swish, ['X'], [], ['Out']), + LayerInfo(paddle.nn.Sigmoid, ['X'], [], ['Out']), + LayerInfo(paddle.nn.Softmax, ['X'], [], ['Out']), + LayerInfo(paddle.nn.Tanh, ['X'], [], ['Out']), + LayerInfo(paddle.nn.quant.add, ['X', 'Y'], [], ['Out']), +] + +QUANT_LAYERS_INFO = [ + LayerInfo( + paddle.nn.quant.quant_layers.QuantizedConv2D, + ['Input'], + ['Filter'], + ['Output'], + ), + LayerInfo( + paddle.nn.quant.quant_layers.QuantizedLinear, ['X'], ['Y'], ['Out'] + ), +] + +SIMULATED_LAYERS = [paddle.nn.Conv2D, paddle.nn.Linear] + + +class PTQRegistry(object): + """ + Register the supported layers for PTQ and provide layers info. + """ + + supported_layers_map = {} + registered_layers_map = {} + is_inited = False + + def __init__(self): + super(PTQRegistry, self).__init__() + + @classmethod + def _init(cls): + if not cls.is_inited: + for layer_info in PTQ_LAYERS_INFO: + cls.supported_layers_map[layer_info.layer] = layer_info + + all_layers_info = PTQ_LAYERS_INFO + QUANT_LAYERS_INFO + for layer_info in all_layers_info: + cls.registered_layers_map[layer_info.layer] = layer_info + cls.is_inited = True + + @classmethod + def is_supported_layer(cls, layer): + """ + Analyze whether the layer supports quantization. + Args: + layer(Layer): The input layer can be a python class or an instance. + Returns: + flag(bool): Whther the layer is supported. + """ + cls._init() + return layer in cls.supported_layers_map or isinstance( + layer, tuple(cls.supported_layers_map.keys()) + ) + + @classmethod + def is_registered_layer(cls, layer): + """ + Analyze whether the layer is register layer_info. + Args: + layer(Layer): The input layer can be a python class or an instance. + Returns: + flag(bool): Wether the layer is register layer_info. + """ + cls._init() + return layer in cls.registered_layers_map or isinstance( + layer, tuple(cls.registered_layers_map.keys()) + ) + + @classmethod + def is_simulated_quant_layer(cls, layer): + """ + Analyze whether the layer is simulated quant layer. + Args: + layer(Layer): The input layer can be a python class or an instance. + Returns: + flag(bool): Whther the layer is supported. + """ + return layer in SIMULATED_LAYERS or isinstance( + layer, tuple(SIMULATED_LAYERS) + ) + + @classmethod + def layer_info(cls, layer): + """ + Get the infomation for the layer. + Args: + layer(Layer): The input layer can be a python class or an instance. + Returns: + layer_info(LayerInfo): The layer info of the input layer. + """ + assert cls.is_registered_layer( + layer + ), "The input layer is not register." + + for layer_key, layer_info in cls.registered_layers_map.items(): + if layer == layer_key or isinstance(layer, layer_key): + return layer_info diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/qat.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/qat.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4b7721d55ffd82dc1cc13a44aef7b94e740bec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/qat.py @@ -0,0 +1,687 @@ +# 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. + +import collections +import logging +import numpy as np +import sys +import os +import warnings + +import paddle +import paddle.nn as nn +import paddle.nn.quant.quant_layers as quant_layers +from paddle.fluid import dygraph, core, framework, unique_name +from paddle.fluid.framework import IrGraph +from paddle.fluid.executor import Executor, global_scope +from paddle.fluid.param_attr import ParamAttr +from paddle.fluid.initializer import Constant +from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX +from paddle.fluid.io import load_inference_model, save_inference_model +from ..quantization_pass import ReplaceFakeQuantDequantPass, QuantWeightPass +from paddle.fluid.log_helper import get_logger +from .. import quantization_pass +from ..utils import move_persistable_var_to_global_block +from . import utils +from . import fuse_utils + +__all__ = ['ImperativeQuantAware'] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +def lazy_import_fleet(layer_name_map, fake_quant_input_layers): + from paddle.distributed import fleet + layer_name_map[ + 'ColumnParallelLinear'] = fleet.meta_parallel.parallel_layers.mp_layers.ColumnParallelLinear + layer_name_map[ + 'RowParallelLinear'] = fleet.meta_parallel.parallel_layers.mp_layers.RowParallelLinear + fake_quant_input_layers.append(fleet.meta_parallel.RowParallelLinear) + fake_quant_input_layers.append(fleet.meta_parallel.ColumnParallelLinear) + return layer_name_map, fake_quant_input_layers + + +class ImperativeQuantAware(object): + """ + Applying quantization aware training (QAT) to the dgraph model. + """ + + def __init__(self, + quantizable_layer_type=[ + 'Conv2D', 'Linear', 'Conv2DTranspose', + 'ColumnParallelLinear', 'RowParallelLinear' + ], + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max', + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + fuse_conv_bn=False, + weight_preprocess_layer=None, + act_preprocess_layer=None, + weight_quantize_layer=None, + act_quantize_layer=None, + onnx_format=False): + """ + The constructor for ImperativeQuantAware. + + Args: + quantizable_layer_type(list[str | layer]): List the type of + layers that will be quantized. Default is ['Conv2D', 'Linear']. + weight_quantize_type(str): quantization type for weights, + which supports 'abs_max' and 'channel_wise_abs_max'. + activation_quantize_type(str): quantization type for activations, + which supports 'abs_max' and 'moving_average_abs_max' now. + If using 'abs_max' mode, the quantization scale will be + calculated dynamically each step in both training and testing + period. If using 'moving_average_abs_max', the static + quantization scale will be calculated during training and + used in inference. + weight_bits(int): quantization bit number for weights, whereas + the bias is not quantized. + activation_bits(int): quantization bit number for activations. + moving_rate(float): the parameter for 'moving_average_abs_max' + quantization. + fuse_conv_bn(bool): Whether to fuse conv and bn, default is False. + weight_preprocess_layer(paddle.nn.Layer, optional): A paddle + Layer that defines how to preprocess weight before quantization. + Using this can quickly test if user's preprocess method works + or not. The input is non-quantized weight and function returns + processed weight to be quantized. + If None, the weight will be quantized directly. + Default is None. + act_preprocess_layer(paddle.nn.Layer, optional): A paddle Layer + that defines how to preprocess activation before quantization. + Using this can quickly test if user's preprocess method works + or not. The input is non-quantized activation and function returns + processed activation to be quantized. + If None, the activation will be quantized directly. + Default is None. + weight_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that + defines how to quantize weight. + Using this can quickly test if user's quantization method works or not. + In this layer, user should both define quantization method and + dequantization method, that is, the function's input is non-quantized + weight and returns dequantized weight. + If None, will use uantization op defined by 'weight_quantize_type'. + Default is None. + act_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that defines + how to quantize activation. + Using this can quickly test if user's quantization method works or not. + In this layer, user should both define quantization method and + dequantization method, that is, the function's input is non-quantized + activation and returns dequantized activation. + If None, will use quantization op defined by 'activation_quantize_type'. + Default is None. + onnx_format (bool, optional): Whether to export the quantized model + with format of ONNX. Default is False. + + Note: + If user sets attribute 'skip_quant' to a Layer that support dynamic + quantization and sets it to true, the layer would not be quantized + during training. If this attribute is not sets or the attribute is + false, the Layer would be qunatized in training. + + Examples 1: + .. code-block:: python + + import paddle + from paddle.fluid.contrib.slim.quantization \ + import ImperativeQuantAware + from paddle.vision.models \ + import resnet + + model = resnet.resnet50(pretrained=True) + + imperative_qat = ImperativeQuantAware( + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max') + + # Add the fake quant logical. + # The original model will be rewrite. + # The outscale of outputs in supportted layers would be calculated. + imperative_qat.quantize(model) + + # Fine-tune the quantized model + # ... + + # Save quant model for the inference. + imperative_qat.save_quantized_model( + layer=model, + model_path="./resnet50_qat", + input_spec=[ + paddle.static.InputSpec( + shape=[None, 3, 224, 224], dtype='float32')]) + + Examples 2: + .. code-block:: python + + import paddle + from paddle.fluid.contrib.slim.quantization \ + import ImperativeQuantAware + + class ImperativeModel(paddle.nn.Layer): + def __init__(self): + super(ImperativeModel, self).__init__() + # self.linear_0 would skip the quantization. + self.linear_0 = paddle.nn.Linear(784, 400) + self.linear_0.skip_quant = True + + # self.linear_1 would not skip the quantization. + self.linear_1 = paddle.nn.Linear(400, 10) + self.linear_1.skip_quant = False + + def forward(self, inputs): + x = self.linear_0(inputs) + x = self.linear_1(inputs) + return x + + model = ImperativeModel() + imperative_qat = ImperativeQuantAware( + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max') + + # Add the fake quant logical. + # The original model will be rewrite. + # + # There is only one Layer(self.linear1) would be added the + # fake quant logical. + imperative_qat.quantize(model) + + # Fine-tune the quantized model + # ... + + # Save quant model for the inference. + imperative_qat.save_quantized_model( + layer=model, + model_path="./imperative_model_qat") + """ + super(ImperativeQuantAware, self).__init__() + self.fuse_conv_bn = fuse_conv_bn + + kwargs = { + "quantizable_layer_type": quantizable_layer_type, + "weight_quantize_type": weight_quantize_type, + "activation_quantize_type": activation_quantize_type, + "weight_bits": weight_bits, + "activation_bits": activation_bits, + "moving_rate": moving_rate, + "weight_preprocess_layer": weight_preprocess_layer, + "act_preprocess_layer": act_preprocess_layer, + "weight_quantize_layer": weight_quantize_layer, + "act_quantize_layer": act_quantize_layer + } + + self._quantize_inputs = ImperativeQuantizeInputs(**kwargs) + + self._quantize_outputs = ImperativeQuantizeOutputs( + moving_rate, activation_bits, onnx_format) + + def quantize(self, model): + """ + According to weights' and activations' quantization types, + the model will be added some fake quant ops, such as + fake_quantize_dequantize_moving_average_abs_max, + fake_quantize_dequantize_abs_max and so on. At the same time, + the out_scale value of outputs would be calculated. + + Args: + model(paddle.nn.Layer): the model to be quantized. + Returns: + None + + Examples: + .. code-block:: python + + import paddle + from paddle.fluid.contrib.slim.quantization \ + import ImperativeQuantAware + + class ImperativeModel(paddle.nn.Layer): + def __init__(self): + super(ImperativeModel, self).__init__() + # self.linear_0 would skip the quantization. + self.linear_0 = paddle.nn.Linear(784, 400) + self.linear_0.skip_quant = True + + # self.linear_1 would not skip the quantization. + self.linear_1 = paddle.nn.Linear(400, 10) + self.linear_1.skip_quant = False + + def forward(self, inputs): + x = self.linear_0(inputs) + x = self.linear_1(inputs) + return x + + model = ImperativeModel() + imperative_qat = ImperativeQuantAware( + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max') + + # Add the fake quant logical. + # The original model will be rewrite. + # + # There is only one Layer(self.linear1) would be added the + # fake quant logical. + imperative_qat.quantize(model) + """ + assert isinstance(model, dygraph.Layer), \ + "The model must be the instance of dygraph.Layer." + + if self.fuse_conv_bn: + fuse_utils.fuse_conv_bn(model) + + self._quantize_inputs.apply(model) + self._quantize_outputs.apply(model) + return model + + def save_quantized_model(self, layer, path, input_spec=None, **config): + self._quantize_outputs.save_quantized_model(layer, path, input_spec, + **config) + + +class ImperativeQuantizeInputs(object): + """ + Based on the input params, add the quant_dequant computational + logic both for activation inputs and weight inputs. + """ + + def __init__(self, + quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'], + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max', + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_preprocess_layer=None, + act_preprocess_layer=None, + weight_quantize_layer=None, + act_quantize_layer=None): + """ + The constructor for ImperativeQuantizeInputs. + + Please refer to the args of ImperativeQuantAware. + """ + super(ImperativeQuantizeInputs, self).__init__() + self.layer_name_map, self.fake_quant_input_layers = lazy_import_fleet( + utils.layer_name_map, utils.fake_quant_input_layers) + + self._quantizable_layer_type = tuple( + self.layer_name_map[layer] if layer in + self.layer_name_map else layer for layer in quantizable_layer_type) + for layer in self._quantizable_layer_type: + assert not isinstance(layer, str) \ + and layer in self.fake_quant_input_layers, \ + "%s is unspported to be quantized." % layer + + quantize_type = { + 'abs_max', 'moving_average_abs_max', 'channel_wise_abs_max' + } + assert weight_quantize_type != 'moving_average_abs_max' \ + and weight_quantize_type in quantize_type, \ + "Unsupported weight_quantize_type: %s. It can only " \ + "be abs_max or channel_wise_abs_max." % weight_quantize_type + # TODO (jc): activation_quantize_type supports range_abs_max + assert activation_quantize_type == 'moving_average_abs_max', \ + "Unsupported activation_quantize_type: %s. It can " \ + "only be moving_average_abs_max now." \ + % activation_quantize_type + + bits_check = lambda bits: isinstance(bits, int) \ + and bits >= 0 and bits <= 16 + assert bits_check(weight_bits), \ + "weight_bits should be 1, 2,... or 16." + assert bits_check(activation_bits), \ + "activation_bits should be 1, 2,... or 16." + + layer_check = lambda method: method is None or \ + issubclass(method, dygraph.layers.Layer) + assert layer_check(weight_preprocess_layer), \ + "weight_preprocess should be nn.Layer." + assert layer_check(act_preprocess_layer), \ + "act_preprocess should be nn.Layer." + assert layer_check(weight_quantize_layer), \ + "weight_quantize should be nn.Layer." + assert layer_check(act_quantize_layer), \ + "act_quantize should be nn.Layer." + + self._kwargs = { + "weight_quantize_type": weight_quantize_type, + "activation_quantize_type": activation_quantize_type, + "weight_bits": weight_bits, + "activation_bits": activation_bits, + "moving_rate": moving_rate, + "weight_pre_layer": weight_preprocess_layer, + "act_pre_layer": act_preprocess_layer, + "weight_quant_layer": weight_quantize_layer, + "act_quant_layer": act_quantize_layer + } + + def apply(self, model): + """ + Quantize the weights and activations to calculate for specific + layers. + + Args: + model(paddle.nn.Layer): The target model which would + calculate the input quantization scale. + + Returns: + None + """ + + assert isinstance(model, dygraph.Layer), \ + "The model must be the instance of dygraph.Layer." + + for name, cur_layer in model.named_sublayers(): + if not isinstance(cur_layer, self._quantizable_layer_type) \ + or (hasattr(cur_layer, "skip_quant") \ + and cur_layer.skip_quant == True): + continue + + parent_layer, sub_name = \ + utils.find_parent_layer_and_sub_name(model, name) + + cur_quant_layer = self._get_input_quantized_layer(cur_layer) + setattr(parent_layer, sub_name, cur_quant_layer) + + def _get_input_quantized_layer(self, layer): + quant_layer_name = None + + for key, value in self.layer_name_map.items(): + if isinstance(layer, value): + quant_layer_name = 'Quantized' + key + break + assert quant_layer_name is not None, \ + "The layer %s is unsupported to be quantized." \ + % layer.full_name() + + return quant_layers.__dict__[quant_layer_name](layer, **self._kwargs) + + +class ImperativeQuantizeOutputs(object): + """ + Calculate the output scales for target layers. + """ + + def __init__(self, moving_rate=0.9, activation_bits=8, onnx_format=False): + """ + The constructor for ImperativeQuantizeOutputs. + + Args: + moving_rate(float): The decay coefficient of moving average. + The default value is 0.9. + activation_bits(int, optional): quantization bit number for activation. Default is 8. + """ + super(ImperativeQuantizeOutputs, self).__init__() + self._moving_rate = moving_rate + self._activation_bits = activation_bits + self._onnx_format = onnx_format + + def apply(self, model): + """ + Insert the `moving_average_abs_max_scale` layers to calculate the + output scales for specific layers in the dygraph model. + + Args: + model(paddle.nn.Layer): The target model which would be + calculate the output quantization scale. + + Returns: + None + """ + assert isinstance(model, dygraph.Layer), \ + "The model must be the instance of dygraph.Layer." + + for cur_name, cur_layer in model.named_sublayers(): + if '_act_preprocess' in cur_name: + continue + if not self._is_target_layer(cur_layer): + continue + + parent_layer, sub_name = \ + utils.find_parent_layer_and_sub_name(model, cur_name) + + reduce_type = None + + if isinstance(cur_layer, tuple(utils.fake_quant_output_layers)): + cur_quant_layer = quant_layers.FakeQuantMAOutputScaleLayer( + cur_layer, self._moving_rate, reduce_type=reduce_type) + else: + cur_quant_layer = quant_layers.MAOutputScaleLayer( + cur_layer, self._moving_rate, reduce_type=reduce_type) + + setattr(parent_layer, sub_name, cur_quant_layer) + + def save_quantized_model(self, model, path, input_spec=None, **config): + """ + Save the quantized model for the inference. + + Args: + model (Layer): The model to be saved. + path (str): The path prefix to save model. The format is + ``dirname/file_prefix`` or ``file_prefix``. + input_spec (list[InputSpec|Tensor], optional): Describes the input + of the saved model's forward method, which can be described by + InputSpec or example Tensor. If None, all input variables of + the original Layer's forward method would be the inputs of + the saved model. Default None. + **config (dict, optional): Other save configuration options for + compatibility. We do not recommend using these configurations, + they may be removed in the future. If not necessary, DO NOT use + them. Default None. + The following options are currently supported: + (1) output_spec (list[Tensor]): Selects the output targets of + the saved model. By default, all return variables of original + Layer's forward method are kept as the output of the saved model. + If the provided ``output_spec`` list is not all output variables, + the saved model will be pruned according to the given + ``output_spec`` list. + + Returns: + None + """ + assert isinstance(model, dygraph.Layer), \ + "The model must be the instance of dygraph.Layer." + + paddle.jit.save(layer=model, path=path, input_spec=input_spec, **config) + + is_dynamic_mode = False + if paddle.in_dynamic_mode(): + is_dynamic_mode = True + paddle.enable_static() + + place = core.CPUPlace() + scope = global_scope() + exe = Executor(place) + + dirname = os.path.dirname(path) + basename = os.path.basename(path) + model_filename = basename + INFER_MODEL_SUFFIX + params_filename = basename + INFER_PARAMS_SUFFIX + + [infer_program, feed_target_names, fetch_targets + ] = (load_inference_model(dirname=dirname, + executor=exe, + model_filename=model_filename, + params_filename=params_filename)) + + if not self._onnx_format: + self._gather_scales(infer_program, scope, fetch_targets) + + # Remove `moving_average_abs_max_scale` node in sub graphs. + graph = IrGraph(core.Graph(infer_program.desc), for_test=False) + for sub_graph in graph.all_sub_graphs(): + for _op in sub_graph.all_op_nodes(): + if _op.name() == "moving_average_abs_max_scale": + sub_graph.safe_remove_nodes(_op) + sub_graph.resolve_hazard() + infer_program = graph.to_program() + + self._set_skip_quant_attr(infer_program) + + clip_extra = False + else: + graph = IrGraph(core.Graph(infer_program.desc), for_test=False) + transform_pass = ReplaceFakeQuantDequantPass( + scope, place, quant_bits=self._activation_bits) + for sub_graph in graph.all_sub_graphs(): + sub_graph._for_test = True + transform_pass.apply(sub_graph) + + quant_weight_pass = QuantWeightPass(scope, place) + for sub_graph in graph.all_sub_graphs(): + sub_graph._for_test = True + quant_weight_pass.apply(sub_graph) + + infer_program = graph.to_program() + + clip_extra = True + + move_persistable_var_to_global_block(infer_program) + + save_inference_model(dirname=dirname, + feeded_var_names=feed_target_names, + target_vars=fetch_targets, + executor=exe, + main_program=infer_program.clone(), + model_filename=model_filename, + params_filename=params_filename, + clip_extra=clip_extra) + + if is_dynamic_mode: + paddle.disable_static() + + def _is_target_layer(self, layer): + """ + Whether the layer needs to calculate output scales. + """ + # exclude fake_quant ops in quant_layers file + if not isinstance(layer, dygraph.Layer): + return False + + if self._onnx_format: + return True if isinstance(layer, tuple( + utils.fake_quant_wrap_layers)) else False + + flag = False + if utils.is_leaf_layer(layer) and \ + not isinstance(layer, tuple(utils.fake_quant_leaf_layers)): + flag = True + + if isinstance(layer, tuple(utils.fake_quant_wrap_layers)): + flag = True + + if isinstance(layer, paddle.nn.quant.FloatFunctionalLayer): + flag = True + + return flag + + def _gather_scales(self, program, scope, fetch_targets): + """ + Get all scales from fake ops, save them into the corresponding ops + and delete all moving_average_abs_max_scale ops. + """ + + def _gather_input_scale(): + target_ops = [] + skip_ops = utils.fake_quantize_dequantize_op_types + \ + ["moving_average_abs_max_scale"] + for block in program.blocks: + for op in block.ops: + if op.type not in skip_ops: + target_ops.append(op) + + for op in target_ops: + for in_var_name in utils._get_op_input_var_names(op): + previous_op = utils.find_previous_op(op.block, in_var_name) + + if previous_op is not None and \ + ("quantize_dequantize" in previous_op.type or \ + previous_op.type == "moving_average_abs_max_scale"): + scale_name = previous_op.output('OutScale')[0] + in_scale = utils.load_variable_data(scope, scale_name) + in_scale = utils.fp_numpy_to_naive(in_scale) + argname, index = utils._get_input_name_index( + op, in_var_name) + op._set_attr(argname + str(index) + "_threshold", + in_scale) + op._set_attr("with_quant_attr", True) + + def _gather_output_scale(): + target_ops = [] + for block in program.blocks: + for op in block.ops: + if op.type == "moving_average_abs_max_scale": + target_ops.append(op) + + for op in target_ops: + in_var_name = op.input('X')[0] + out_var_name = op.output('Out')[0] + block = op.block + previous_op = utils.find_previous_op(block, in_var_name) + next_ops = utils.find_next_ops(block, out_var_name) + + out_scale_name = op.output('OutScale')[0] + out_scale = utils.load_variable_data(scope, out_scale_name) + out_scale = utils.fp_numpy_to_naive(out_scale) + + if previous_op.type != "feed": + res = utils._get_output_name_index(previous_op, in_var_name) + if res is not None: + argname, index = res + previous_op._set_attr( + argname + str(index) + "_threshold", out_scale) + previous_op._set_attr("out_threshold", out_scale) + previous_op._set_attr("with_quant_attr", True) + + for next_op in next_ops: + next_op._rename_input(out_var_name, in_var_name) + # If next_op is `fetch` and out_var_name in fetch_targets, + # fetch_targets must update to in_var_name when rename input. + for i in range(len(fetch_targets)): + if fetch_targets[i].name == out_var_name: + fetch_targets[i] = block.var(in_var_name) + + _gather_input_scale() + _gather_output_scale() + + def _set_skip_quant_attr(self, program): + """ + Label the skip quantized ops. + """ + for block in program.blocks: + for op in block.ops: + if self._is_skip_quant_op(block, op): + op._set_attr("skip_quant", True) + op._set_attr("with_quant_attr", True) + + def _is_skip_quant_op(self, block, in_op): + """ + The input op should be skipped quantization. + 1. the type of input op should be conv2d, depthwise_conv2d or matmul + 2. the previous ops of the input op are not fake_quantize_dequantize ops + """ + target_op_types = [ + "conv2d", "depthwise_conv2d", "matmul", "conv2d_transpose" + ] + if in_op.type not in target_op_types: + return False + + previous_ops = [utils.find_previous_op(block, arg_name) \ + for arg_name in in_op.input_arg_names] + return any(op is not None and op.type not in \ + utils.fake_quantize_dequantize_op_types for op in previous_ops) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a30d775165e186212961df9ae3d1e85b3728f016 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/imperative/utils.py @@ -0,0 +1,178 @@ +# 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. + +import math +import numpy as np + +import paddle +import paddle.nn.quant.quant_layers as quant_layers + +from ..utils import _get_op_input_var_names, _get_op_output_var_names, _get_output_name_index, _get_input_name_index + +layer_name_map = { + 'Conv2DTranspose': paddle.nn.Conv2DTranspose, + 'Conv2D': paddle.nn.Conv2D, + 'Linear': paddle.nn.Linear, + 'AdaptiveAvgPool2D': paddle.nn.AdaptiveAvgPool2D, + 'AdaptiveMaxPool2D': paddle.nn.AdaptiveMaxPool2D, + 'AvgPool2D': paddle.nn.AvgPool2D, + 'MaxPool2D': paddle.nn.MaxPool2D, + 'Hardswish': paddle.nn.Hardswish, + 'LeakyReLU': paddle.nn.LeakyReLU, + 'PReLU': paddle.nn.PReLU, + 'ReLU': paddle.nn.ReLU, + 'ReLU6': paddle.nn.ReLU6, + 'Sigmoid': paddle.nn.Sigmoid, + 'Softmax': paddle.nn.Softmax, + 'Swish': paddle.nn.Swish, + 'Tanh': paddle.nn.Tanh, + 'Hardswish': paddle.nn.Hardswish, + 'BatchNorm': paddle.nn.BatchNorm, + 'GroupNorm': paddle.nn.GroupNorm, + 'LayerNorm': paddle.nn.LayerNorm, +} + +# Apply fake quant for the inputs of these layers +fake_quant_input_layers = [ + paddle.nn.Conv2D, + paddle.nn.Linear, + paddle.nn.Conv2DTranspose, +] + +# Apply fake quant for the output of these layers +# TODO(jc): fix the problem of adding duplicate fake_quant ops +# paddle.nn.AdaptiveAvgPool2D, paddle.nn.AvgPool2D, paddle.nn.ReLU,paddle.nn.LeakyReLU +fake_quant_output_layers = [ + paddle.nn.quant.add, paddle.nn.quant.subtract, paddle.nn.quant.multiply, + paddle.nn.quant.divide +] + +fake_quant_leaf_layers = [ + quant_layers.FakeQuantAbsMax, + quant_layers.FakeQuantChannelWiseAbsMax, + quant_layers.FakeQuantMovingAverageAbsMax, + quant_layers.MovingAverageAbsMaxScale, +] + +fake_quant_wrap_layers = [ + quant_layers.QuantizedConv2D, quant_layers.QuantizedLinear, + quant_layers.QuantizedConv2DTranspose, + quant_layers.QuantizedColumnParallelLinear, + quant_layers.QuantizedRowParallelLinear +] + +# The weight format of these layers is Cin * Cout * H * W +spec_channel_axis_layers = [paddle.nn.Conv2DTranspose, paddle.nn.Linear] + +weight_op_types = [ + "conv2d", "depthwise_conv2d", "matmul", "conv2d_transpose", + "depthwise_conv2d_transpose" +] + +fake_quantize_dequantize_op_types = [ + "fake_quantize_dequantize_abs_max", + "fake_channel_wise_quantize_dequantize_abs_max", + "fake_quantize_dequantize_moving_average_abs_max" +] + + +def load_variable_data(scope, var_name): + """ + Load variable value from scope + """ + var_node = scope.find_var(var_name) + assert var_node is not None, \ + "Can not find " + var_name + " in the scope." + return np.array(var_node.get_tensor()) + + +def find_previous_op(block, var_name): + """ + Find the previous op for the input variable. + """ + for op in block.ops: + if var_name in op.output_arg_names: + return op + return None + + +def find_next_ops(block, var_name): + """ + Find all followed ops for the input variable. + """ + res_ops = [] + for op in block.ops: + if var_name in op.input_arg_names: + res_ops.append(op) + return res_ops + + +def find_parent_layer_and_sub_name(model, name): + """ + Given the model and the name of a layer, find the parent layer and + the sub_name of the layer. + For example, if name is 'block_1/convbn_1/conv_1', the parent layer is + 'block_1/convbn_1' and the sub_name is `conv_1`. + Args: + model(paddle.nn.Layer): the model to be quantized. + name(string): the name of a layer + + Returns: + parent_layer, subname + """ + assert isinstance(model, paddle.nn.Layer), \ + "The model must be the instance of paddle.nn.Layer." + assert len(name) > 0, "The input (name) should not be empty." + + last_idx = 0 + idx = 0 + parent_layer = model + while idx < len(name): + if name[idx] == '.': + sub_name = name[last_idx:idx] + if hasattr(parent_layer, sub_name): + parent_layer = getattr(parent_layer, sub_name) + last_idx = idx + 1 + idx += 1 + sub_name = name[last_idx:idx] + return parent_layer, sub_name + + +def program_all_ops(program): + """ + Return all ops for the input program. + """ + all_ops = [] + for block in program.blocks: + for op in block.ops: + all_ops.append(op) + return all_ops + + +def is_leaf_layer(layer): + """ + Whether the layer is leaf layer. + """ + return isinstance(layer, paddle.nn.Layer) \ + and len(layer.sublayers()) == 0 + + +def fp_numpy_to_naive(x_np): + """ + Convert numpy to float or list. + """ + if x_np.size == 1: + return float(x_np) + else: + return x_np.tolist() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/post_training_quantization.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/post_training_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..97cb732d5e6cebd0a927caef16058895c45febde --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/post_training_quantization.py @@ -0,0 +1,1643 @@ +# Copyright (c) 2018 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. + +import os +import re +import math +import shutil +import logging +import numpy as np + +try: + from tqdm import tqdm +except: + from .utils import tqdm +from inspect import isgeneratorfunction +from .... import io +from .... import core +from .... import reader +from .... import framework +from .... import unique_name +from ....executor import global_scope, Executor +from ....framework import IrGraph +from ....log_helper import get_logger +from .quantization_pass import QuantizationTransformPass, QuantizationTransformPassV2, QuantizationFreezePass, QuantWeightPass, AddQuantDequantPass, AddQuantDequantPassV2 +from .cal_kl_threshold import cal_kl_threshold +from .adaround import run_adaround +from . import utils + +__all__ = [ + 'PostTrainingQuantization', + 'WeightQuantization', + 'PostTrainingQuantizationProgram', +] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +def _all_persistable_var_names(program): + persistable_var_names = [] + for var in program.list_vars(): + if var.persistable: + persistable_var_names.append(var.name) + return persistable_var_names + + +def _remove_unused_var_nodes(graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) + return graph + + +def _remove_ctrl_vars(graph): + remove_ctr_vars = set() + for node in graph.all_var_nodes(): + if node.is_ctrl_var(): + remove_ctr_vars.add(node) + graph.safe_remove_nodes(remove_ctr_vars) + return graph + + +def _apply_pass(scope, + graph, + pass_name, + attrs=None, + attr_values=None, + debug=False): + ir_pass = core.get_pass(pass_name) + cpp_graph = graph.graph + if not cpp_graph.has('__param_scope__'): + cpp_graph.set_not_owned('__param_scope__', scope) + if attrs: + assert attr_values and len(attrs) == len( + attr_values + ), "Different number of pass attributes and their values." + for attr, value in zip(attrs, attr_values): + ir_pass.set(attr, value) + ir_pass.apply(cpp_graph) + if debug: + graph.draw('.', 'qat_fp32_{}'.format(pass_name), graph.all_op_nodes()) + _remove_unused_var_nodes(graph) + return graph + + +class PostTrainingQuantization(object): + """ + Utilizing post training quantization methon to quantize the FP32 model, + and it uses calibrate data to get the quantization information for all + quantized variables. + """ + + def __init__(self, + executor, + model_dir, + scope=None, + model_filename=None, + params_filename=None, + batch_generator=None, + sample_generator=None, + data_loader=None, + batch_size=10, + batch_nums=None, + algo="KL", + hist_percent=0.99999, + quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"], + round_type='round', + learning_rate=0.001, + is_full_quantize=False, + bias_correction=False, + activation_bits=8, + weight_bits=8, + activation_quantize_type='range_abs_max', + weight_quantize_type='channel_wise_abs_max', + onnx_format=False, + freeze_model=True, + optimize_model=False, + is_use_cache_file=False, + skip_tensor_list=None, + same_scale_tensor_list=None, + cache_dir=None, + scale_dict=None, + return_graph=False): + ''' + Constructor. + + Args: + executor(fluid.Executor): The executor to load, run and save the + quantized model. + scope(fluid.Scope, optional): The scope of the program, use it to load + and save variables. If scope=None, get scope by global_scope(). + model_dir(str): The path of the fp32 model that will be quantized, + and the model and params files are under the path. + model_filename(str, optional): The name of file to load the inference + program. If it is None, the default filename '__model__' will + be used. Default is 'None'. + params_filename(str, optional): The name of file to load all parameters. + When all parameters were saved in a single binary file, set it + as the real filename. If parameters were saved in separate files, + set it as 'None'. Default is 'None'. + batch_generator(Python Generator): The batch generator provides + calibrate data for DataLoader, and it returns a batch every + time. Note that, sample_generator and batch_generator, only one + should be set. Beisdes, batch_generator supports lod tensor. + sample_generator(Python Generator): The sample generator provides + calibrate data for DataLoader, and it only returns a sample every + time. Note that, sample_generator and batch_generator, only one + should be set. Beisdes, sample_generator dose not support lod tensor. + data_loader(Python Generator, Paddle.io.DataLoader, optional): The + Generator or Dataloader provides calibrate data, and it could + return a batch every time. + batch_size(int, optional): The batch size of DataLoader. Default is 10. + batch_nums(int, optional): If batch_nums is not None, the number of + calibrate data is batch_size*batch_nums. If batch_nums is None, use + all data provided by sample_generator as calibrate data. + algo(str, optional): If algo='KL', use KL-divergenc method to + get the KL threshold for quantized activations and get the abs_max + value for quantized weights. If algo='abs_max', get the abs max + value for activations and weights. If algo= 'min_max', get the min + and max value for quantized activations and weights. If algo='avg', + get the average value among the max values for activations. If + algo= 'hist', get the value of 'hist_percent' quantile as the threshold. + If algo='mse', get the value which makes the quantization mse loss + minimal. Default is KL. + hist_percent(float, optional): The threshold of algo 'hist' for activations. + Default is 0.99999. + quantizable_op_type(list[str], optional): List the type of ops + that will be quantized. Default is ["conv2d", "depthwise_conv2d", + "mul"]. + round_type(str, optional): The method of converting the quantized weights + value float->int. Currently supports ['round', 'adaround'] methods. + Default is `round`, which is rounding nearest to the integer. + 'adaround' is refer to https://arxiv.org/abs/2004.10568. + learning_rate(float, optional): The learning rate of adaround method. + is_full_quantized(bool, optional): If set is_full_quantized as True, + apply quantization to all supported quantizable op type. If set + is_full_quantized as False, only apply quantization to the op type + according to the input quantizable_op_type. + bias_correction(bool, optional): If set as True, use the bias correction + method of https://arxiv.org/abs/1810.05723. Default is False. + activation_bits(int): quantization bit number for activation. + weight_bits(int, optional): quantization bit number for weights. + activation_quantize_type(str): quantization type for activation, + now support 'range_abs_max', 'moving_average_abs_max' and 'abs_max'. + This param only specifies the fake ops in saving quantized model. + If it is 'range_abs_max' or 'moving_average_abs_max', we save the scale + obtained by post training quantization in fake ops. Note that, if it + is 'abs_max', the scale will not be saved in fake ops. + weight_quantize_type(str): quantization type for weights, + support 'abs_max' and 'channel_wise_abs_max'. This param only specifies + the fake ops in saving quantized model, and we save the scale obtained + by post training quantization in fake ops. Compared to 'abs_max', + the model accuracy is usually higher when it is 'channel_wise_abs_max'. + onnx_format(bool): Whether to export the quantized model with format of ONNX. + Default is False. + freeze_model(bool): Whether to convert quantized and trained ``program`` to final + quantized ``program``. Default: True. + skip_tensor_list(list): List of skip quant tensor name. Default: None. + same_scale_tensor_list(list(list)): The list of tensor keep same scale in the outermost + list, the final scale about every list is the max of the scale in the list + of tensor. Default: None. + optimize_model(bool, optional): If set optimize_model as True, it applies + some passes to the model before quantization, and it supports + `conv2d/depthwise_conv2d + bn` pass so far. Some targets require the + weights are quantized by tensor-wise method, which means the weights + scale for all channel are the same. However, if fuse + `conv2d/depthwise_conv2d + bn`, the weights scale for all channel will + be different. In address this problem, fuse the pattern before + quantization. Default False. + is_use_cache_file(bool, optional): This param is deprecated. + cache_dir(str, optional): This param is deprecated. + Returns: + None + + Examples: + .. code-block:: python + import paddle.fluid as fluid + from paddle.fluid.contrib.slim.quantization import PostTrainingQuantization + + exe = fluid.Executor(fluid.CPUPlace()) + model_dir = path/to/fp32_model_params + # set model_filename as None when the filename is __model__, + # otherwise set it as the real filename + model_filename = None + # set params_filename as None when all parameters were saved in + # separate files, otherwise set it as the real filename + params_filename = None + save_model_path = path/to/save_model_path + # prepare the sample generator according to the model, and the + # sample generator must return a sample every time. The reference + # document: https://www.paddlepaddle.org.cn/documentation/docs/zh + # /user_guides/howto/prepare_data/use_py_reader.html + sample_generator = your_sample_generator + batch_size = 10 + batch_nums = 10 + algo = "KL" + quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"] + ptq = PostTrainingQuantization( + executor=exe, + sample_generator=sample_generator, + model_dir=model_dir, + model_filename=model_filename, + params_filename=params_filename, + batch_size=batch_size, + batch_nums=batch_nums, + algo=algo, + quantizable_op_type=quantizable_op_type) + ptq.quantize() + ptq.save_quantized_model(save_model_path) + ''' + + self._support_activation_quantize_type = [ + 'range_abs_max', 'moving_average_abs_max', 'abs_max' + ] + self._support_weight_quantize_type = ['abs_max', 'channel_wise_abs_max'] + self._support_algo_type = [ + 'KL', 'hist', 'avg', 'mse', 'emd', 'abs_max', 'min_max', 'ptf' + ] + assert round_type in ['adaround', 'round'] + self._round_type = round_type + self._learning_rate = learning_rate + self._dynamic_quantize_op_type = ['lstm'] + self._support_quantize_op_type = \ + list(set(utils._weight_supported_quantizable_op_type + + utils._act_supported_quantizable_op_type + + self._dynamic_quantize_op_type)) + + # Check inputs + assert executor is not None, "The executor cannot be None." + assert any([gen is not None] for gen in [sample_generator, + batch_generator, data_loader]), "The sample_generator, batch_generator " \ + "and data_loader cannot be None in the same time." + if data_loader is not None: + assert isinstance(data_loader, (io.DataLoader, type(isgeneratorfunction), reader.GeneratorLoader)), \ + "data_loader only accepts `paddle.io.DataLoader` or Generator instance." + assert batch_size > 0, "The batch_size should be greater than 0." + assert algo in self._support_algo_type, \ + "The algo should be KL, hist, mse, avg, abs_max, min_max or ptf." + assert activation_quantize_type in self._support_activation_quantize_type, \ + "The activation_quantize_type ({}) should in ({}).".format( + activation_quantize_type, self._support_activation_quantize_type) + assert weight_quantize_type in self._support_weight_quantize_type, \ + "The weight_quantize_type ({}) shoud in ({}).".format( + weight_quantize_type, self._support_weight_quantize_type) + + # Save input params + self._bias_correction = bias_correction + self._executor = executor + self._scope = global_scope() if scope == None else scope + self._model_dir = model_dir + self._model_filename = model_filename + self._params_filename = params_filename + self._sample_generator = sample_generator + self._batch_generator = batch_generator + self._batch_size = batch_size + self._batch_nums = batch_nums + self._algo = algo + self._hist_percent = hist_percent + self._activation_bits = activation_bits + self._weight_bits = weight_bits + self._activation_quantize_type = activation_quantize_type + self._weight_quantize_type = weight_quantize_type + self._onnx_format = onnx_format + self._clip_extra = True if self._onnx_format else False + self._skip_tensor_list = skip_tensor_list + self._is_full_quantize = is_full_quantize + if is_full_quantize: + self._quantizable_op_type = self._support_quantize_op_type + else: + self._quantizable_op_type = quantizable_op_type + for op_type in self._quantizable_op_type: + assert op_type in self._support_quantize_op_type, \ + op_type + " is not supported for quantization." + self._optimize_model = optimize_model + + # Define variables + self._place = self._executor.place + self._program = None + self._feed_list = None + self._fetch_list = None + self._data_loader = data_loader + + self._out_scale_op_list = utils.QUANT_SUPPORTED_OP_TYPE_LIST + self._quantized_weight_var_name = set() + self._quantized_act_var_name = set() + self._weight_op_pairs = {} + # The vars for alog = KL or hist + self._sampling_act_abs_min_max = {} + self._sampling_act_histogram = {} + self._sampling_data = {} + self._quantized_var_threshold = {} + self._histogram_bins = 2048 + # The vars for algo = min_max + self._quantized_var_min = {} + self._quantized_var_max = {} + # The vars for algo = avg + self._quantized_var_avg = {} + # The best loss of algo = mse + self._best_calibration_loss = {} + # The threshold for algo = abs_max, mse or avg + self._quantized_threshold = {} + self._same_scale_tensor_list = same_scale_tensor_list + self._freeze_model = freeze_model + self._scale_dict = scale_dict + self._return_graph = return_graph + self.FLAG = False + if self._program is not None: + self.FLAG = True + + def quantize(self): + ''' + Load the FP32 model, and use the calibrate data to calculate the forward-stage. + Based on the sample data, we can get the quantization information, and obtain + the final quantized model. + + Args: + None + Returns: + the program of quantized model. + ''' + self._load_model_data() + self._collect_target_varnames() + self._set_activation_persistable() + + if self._algo in ["KL", "hist"]: + batch_id = 0 + with tqdm( + total=self._batch_nums, + bar_format= + 'Preparation stage, Run batch:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for data in self._data_loader(): + self._executor.run(program=self._program, + feed=data, + fetch_list=self._fetch_list, + return_numpy=False, + scope=self._scope) + self._collect_activation_abs_min_max() + batch_id += 1 + t.update() + if self._batch_nums and batch_id >= self._batch_nums: + break + self._init_sampling_act_histogram() + + batch_id = 0 + with tqdm(total=self._batch_nums, + bar_format= + 'Sampling stage, Run batch:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for data in self._data_loader(): + self._executor.run(program=self._program, + feed=data, + fetch_list=self._fetch_list, + return_numpy=False, + scope=self._scope) + self._sampling() + batch_id += 1 + t.update() + if self._batch_nums and batch_id >= self._batch_nums: + break + + if self._algo == 'avg': + for var_name in self._quantized_act_var_name: + self._quantized_threshold[var_name] = \ + np.array(self._quantized_var_avg[var_name]).mean() + if self._algo in ["KL", "hist"]: + self._calculate_kl_hist_threshold() + + if self._round_type == 'adaround': + self._adaround_apply() + + self._reset_activation_persistable() + + if self._algo is 'min_max': + self._save_input_threhold() + else: + self._update_program() + + # save out_threshold for quantized ops. + if not self.FLAG: + self._save_output_threshold() + + if any(op_type in self._quantizable_op_type + for op_type in self._dynamic_quantize_op_type): + self._collect_dynamic_quantize_op_threshold( + self._dynamic_quantize_op_type) + + utils.move_persistable_var_to_global_block(self._program) + + if not self._return_graph: + return self._program + else: + main_graph = IrGraph(core.Graph(self._program.desc), for_test=True) + return main_graph + + def _adaround_apply(self): + assert self._algo != "min_max", "The algo should not be min_max." + if self._algo in ["KL", "hist"]: + scale_dict = self._quantized_var_threshold + else: + scale_dict = self._quantized_threshold + run_adaround(self._data_loader, + self._program, + self._fetch_list, + self._executor, + self._scope, + self._place, + self._quantized_op_pairs, + self._weight_op_pairs, + scale_dict, + num_iterations=self._batch_nums, + bias_correction=self._bias_correction, + lr=self._learning_rate) + + def save_quantized_model(self, + save_model_path, + model_filename=None, + params_filename=None): + ''' + Save the quantized model to the disk. + + Args: + save_model_path(str): The path to save the quantized model. + model_filename(str, optional): If the model_filename is None, + save the model to '__model__'. Otherwise, save the model + to the specified filename. Default: None. + params_filename(str, optional): If the params_filename is None, + save params to separted files. Otherwise, save all params + to the specified filename. + Returns: + None + ''' + io.save_inference_model(dirname=save_model_path, + model_filename=model_filename, + params_filename=params_filename, + feeded_var_names=self._feed_list, + target_vars=self._fetch_list, + executor=self._executor, + main_program=self._program, + clip_extra=self._clip_extra) + _logger.info("The quantized model is saved in " + save_model_path) + + def _load_model_data(self): + ''' + Load model and set data loader. + ''' + if self._program is None: + _logger.info("Load model and set data loader ...") + [self._program, self._feed_list, self._fetch_list] = \ + io.load_inference_model(dirname=self._model_dir, + executor=self._executor, + model_filename=self._model_filename, + params_filename=self._params_filename) + + if self._optimize_model: + self._optimize_fp32_model() + + feed_vars = [framework._get_var(str(var_name), self._program) \ + for var_name in self._feed_list] + + if self._data_loader is not None: + self._batch_nums = self._batch_nums if self._batch_nums else len( + self._data_loader) + return + self._data_loader = io.DataLoader.from_generator(feed_list=feed_vars, + capacity=3 * + self._batch_size, + iterable=True) + if self._sample_generator is not None: + self._data_loader.set_sample_generator(self._sample_generator, + batch_size=self._batch_size, + drop_last=True, + places=self._place) + elif self._batch_generator is not None: + self._data_loader.set_batch_generator(self._batch_generator, + places=self._place) + self._batch_nums = self._batch_nums if self._batch_nums else len( + list(self._data_loader)) + + def _optimize_fp32_model(self): + ''' + Fuse the `conv2d/depthwise_conv2d + bn` in FP32 model. + ''' + _logger.info("Optimize FP32 model ...") + graph = IrGraph(core.Graph(self._program.desc), for_test=True) + graph = _remove_ctrl_vars(graph) + graph = _apply_pass(self._scope, graph, 'conv_bn_fuse_pass') + graph = _apply_pass(self._scope, graph, 'depthwise_conv_bn_fuse_pass') + graph = _apply_pass(self._scope, graph, 'conv_transpose_bn_fuse_pass') + graph = _apply_pass(self._scope, graph, 'conv_eltwiseadd_bn_fuse_pass') + graph = _apply_pass(self._scope, graph, + 'depthwise_conv_eltwiseadd_bn_fuse_pass') + + self._program = graph.to_program() + + def _collect_target_varnames(self): + ''' + Collect the variable names for sampling, and set activation + variables to be persistable. + ''' + # TODO(juncaipeng), consider the name_scope of skip_quant + _logger.info("Collect quantized variable names ...") + self._quantized_op_pairs = {} + + def collect_var_name(var_name_list, persistable_var_names, op_type): + for var_name in var_name_list: + if var_name in persistable_var_names: + self._quantized_weight_var_name.add(var_name) + self._weight_op_pairs[var_name] = op_type + else: + self._quantized_act_var_name.add(var_name) + + persistable_var_names = _all_persistable_var_names(self._program) + for block_id in range(len(self._program.blocks)): + for op in self._program.blocks[block_id].ops: + # skip quant form self._skip_tensor_list + if self._skip_tensor_list is not None: + for inp_name in utils._get_op_input_var_names(op): + if inp_name in self._skip_tensor_list: + op._set_attr("op_namescope", "skip_quant") + + op_type = op.type + if self._is_full_quantize and \ + op_type not in self._quantizable_op_type: + _logger.warning(op_type + + " is not supported for quantization.") + # For quantized ops, sample inputs and outputs + if op_type in self._quantizable_op_type: + collect_var_name(utils._get_op_input_var_names(op), + persistable_var_names, op_type) + collect_var_name(utils._get_op_output_var_names(op), + persistable_var_names, op_type) + # collect quanted op output var name + for out_var_name in utils._get_op_output_var_names(op): + for in_var_name in utils._get_op_input_var_names(op): + if in_var_name in persistable_var_names: + self._quantized_op_pairs[ + in_var_name] = out_var_name + # For other op, only sample output scale + elif op_type in self._out_scale_op_list: + collect_var_name(utils._get_op_output_var_names(op), + persistable_var_names, op_type) + + def _set_activation_persistable(self): + ''' + Set activation variables to be persistable, so can obtain + the tensor data in sample_data + ''' + for var in self._program.list_vars(): + if var.name in self._quantized_act_var_name: + var.persistable = True + + def _reset_activation_persistable(self): + ''' + Reset activations to be not persistable. + ''' + to_erase = [] + for var in self._program.list_vars(): + if var.name in self._quantized_act_var_name: + var.persistable = False + to_erase.append(var.name) + + def _sampling(self): + ''' + Sample the min/max, abs_max or histogram in every iterations. + ''' + if self._algo == "abs_max": + self._sample_abs_max() + elif self._algo == "avg": + self._sample_avg() + elif self._algo == "min_max": + self._sample_min_max() + elif self._algo == "mse": + self._sample_mse() + elif self._algo == "emd": + self._sample_emd() + elif self._algo == "ptf": + self._sample_ptf() + elif self._algo in ["KL", "hist"]: + self._sample_histogram() + + def _sample_mse(self): + if self._quantized_threshold == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + abs_max_value = float(np.max(np.abs(var_tensor))) + elif self._weight_quantize_type == "channel_wise_abs_max": + abs_max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[:, i])))) + else: + for i in range(var_tensor.shape[0]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[i])))) + self._quantized_threshold[var_name] = abs_max_value + _logger.info("MSE searching stage ...") + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + var_tensor = var_tensor.flatten() + abs_max_value = float(np.max(np.abs(var_tensor))) + abs_max_value = 1e-8 if abs_max_value == 0.0 else abs_max_value + s = 0.3 + if var_name not in self._best_calibration_loss: + self._best_calibration_loss[var_name] = float('inf') + while s <= 1.0: + scale = s * abs_max_value + s += 0.02 + bins = 2**(self._activation_bits - 1) - 1 + if self._onnx_format: + quant_var = np.clip(np.round(var_tensor / scale * bins), + -bins - 1, bins) + quant_dequant_var = quant_var / bins * scale + else: + quant_dequant_var = np.round( + np.clip(var_tensor, 0.0, scale) / scale * + bins) / bins * scale + mse_loss = ((var_tensor - quant_dequant_var)**2).mean() + if mse_loss <= self._best_calibration_loss[var_name]: + self._best_calibration_loss[var_name] = mse_loss + self._quantized_threshold[var_name] = scale + + def _sample_emd(self): + if self._quantized_threshold == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + abs_max_value = float(np.max(np.abs(var_tensor))) + elif self._weight_quantize_type == "channel_wise_abs_max": + abs_max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[:, i])))) + else: + for i in range(var_tensor.shape[0]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[i])))) + self._quantized_threshold[var_name] = abs_max_value + _logger.info("EMD searching stage ...") + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + var_tensor = var_tensor.flatten() + abs_max_value = float(np.max(np.abs(var_tensor))) + abs_max_value = 1e-8 if abs_max_value == 0.0 else abs_max_value + s = 0.3 + if var_name not in self._best_calibration_loss: + self._best_calibration_loss[var_name] = float('inf') + while s <= 1.0: + scale = s * abs_max_value + s += 0.02 + bins = 2**(self._activation_bits - 1) - 1 + if self._onnx_format: + quant_var = np.clip(np.round(var_tensor / scale * bins), + -bins - 1, bins) + quant_dequant_var = quant_var / bins * scale + else: + quant_dequant_var = np.round( + np.clip(var_tensor, 0.0, scale) / scale * + bins) / bins * scale + emd_loss = np.abs( + np.mean(var_tensor) - np.mean(quant_dequant_var)) + np.abs( + np.std(var_tensor) - np.std(quant_dequant_var)) + if emd_loss <= self._best_calibration_loss[var_name]: + self._best_calibration_loss[var_name] = emd_loss + self._quantized_threshold[var_name] = scale + + def _sample_avg(self): + if self._quantized_threshold == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + abs_max_value = float(np.max(np.abs(var_tensor))) + elif self._weight_quantize_type == "channel_wise_abs_max": + abs_max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[:, i])))) + else: + for i in range(var_tensor.shape[0]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[i])))) + self._quantized_threshold[var_name] = abs_max_value + + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + abs_max_value = float(np.max(np.abs(var_tensor))) + if (var_name not in self._quantized_var_avg): + self._quantized_var_avg[var_name] = [] + abs_avg_value = float(np.mean(np.max( \ + np.abs(var_tensor.reshape(var_tensor.shape[0], -1)), axis=(1)))) + self._quantized_var_avg[var_name].append(abs_avg_value) + continue + + def _sample_abs_max(self): + if self._quantized_threshold == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + abs_max_value = float(np.max(np.abs(var_tensor))) + elif self._weight_quantize_type == "channel_wise_abs_max": + abs_max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[:, i])))) + else: + for i in range(var_tensor.shape[0]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[i])))) + self._quantized_threshold[var_name] = abs_max_value + + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + abs_max_value = float(np.max(np.abs(var_tensor))) + if (var_name not in self._quantized_threshold) or \ + (abs_max_value > self._quantized_threshold[var_name]): + self._quantized_threshold[var_name] = abs_max_value + + def _sample_min_max(self): + if self._quantized_var_min == {} and self._quantized_var_max == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + min_value = float(np.min(var_tensor)) + max_value = float(np.max(var_tensor)) + elif self._weight_quantize_type == "channel_wise_abs_max": + min_value = [] + max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + min_value.append(float(np.min(var_tensor[:, i]))) + max_value.append(float(np.max(var_tensor[:, i]))) + else: + for i in range(var_tensor.shape[0]): + min_value.append(float(np.min(var_tensor[i]))) + max_value.append(float(np.max(var_tensor[i]))) + self._quantized_var_min[var_name] = min_value + self._quantized_var_max[var_name] = max_value + + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + min_value = float(np.min(var_tensor)) + max_value = float(np.max(var_tensor)) + if (var_name not in self._quantized_var_min) or \ + (min_value < self._quantized_var_min[var_name]): + self._quantized_var_min[var_name] = min_value + if (var_name not in self._quantized_var_max) or \ + (max_value > self._quantized_var_max[var_name]): + self._quantized_var_max[var_name] = max_value + + def _sample_histogram(self): + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + var_tensor_abs = np.abs(var_tensor) + bins = self._sampling_act_histogram[var_name][1] + hist, _ = np.histogram(var_tensor_abs, bins=bins) + self._sampling_act_histogram[var_name][0] += hist + + def _sample_ptf(self): + """ + The following code are modified from: + https://github.com/megvii-research/FQ-ViT/ + """ + if self._quantized_threshold == {}: + for var_name in self._quantized_weight_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + abs_max_value = float(np.max(np.abs(var_tensor))) + elif self._weight_quantize_type == "channel_wise_abs_max": + abs_max_value = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(var_tensor.shape[1]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[:, i])))) + else: + for i in range(var_tensor.shape[0]): + abs_max_value.append( + float(np.max(np.abs(var_tensor[i])))) + self._quantized_threshold[var_name] = abs_max_value + + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + abs_max_value = float(np.max(np.abs(var_tensor))) + q_max = 2**(self._activation_bits - 1) - 1 + scale8 = abs_max_value / q_max + scale4 = scale8 / 2 + scale2 = scale4 / 2 + scale1 = scale2 / 2 + quant_dequant_var_scale1 = np.clip(np.round(var_tensor / scale1), 0, + q_max) * scale1 + quant_dequant_var_scale2 = np.clip(np.round(var_tensor / scale2), 0, + q_max) * scale2 + quant_dequant_var_scale4 = np.clip(np.round(var_tensor / scale4), 0, + q_max) * scale4 + quant_dequant_var_scale8 = np.clip(np.round(var_tensor / scale8), 0, + q_max) * scale8 + score1 = utils.l2_loss(var_tensor, quant_dequant_var_scale1) + score2 = utils.l2_loss(var_tensor, quant_dequant_var_scale2) + score4 = utils.l2_loss(var_tensor, quant_dequant_var_scale4) + score8 = utils.l2_loss(var_tensor, quant_dequant_var_scale8) + score = [score1, score2, score4, score8] + mask = 2**score.index(min(score)) + scale = scale1 * mask + threshold = q_max * scale + self._quantized_threshold[var_name] = threshold + + def _save_input_threhold(self): + ''' + Save input threshold to the quantized op. + ''' + assert self._algo == "min_max", \ + "The algo should be min_max to save input threshold." + for block_id in range(len(self._program.blocks)): + for op in self._program.blocks[block_id].ops: + if op.type in self._quantizable_op_type: + for var_name in utils._get_op_input_var_names(op): + assert var_name in self._quantized_var_min + assert var_name in self._quantized_var_max + op._set_attr(var_name + ".min", + self._quantized_var_min[var_name]) + op._set_attr(var_name + ".max", + self._quantized_var_max[var_name]) + op._set_attr("with_quant_attr", True) + + def _collect_activation_abs_min_max(self): + ''' + Collect the abs_min and abs_max for all activation. When algo = KL, + get the min and max value, and then calculate the threshold. + ''' + for var_name in self._quantized_act_var_name: + var_tensor = utils.load_variable_data(self._scope, var_name) + var_tensor = np.abs(var_tensor) + min_value = float(np.min(var_tensor)) + max_value = float(np.max(var_tensor)) + if var_name not in self._sampling_act_abs_min_max: + self._sampling_act_abs_min_max[var_name] = [ + min_value, max_value + ] + else: + if min_value < self._sampling_act_abs_min_max[var_name][0]: + self._sampling_act_abs_min_max[var_name][0] = min_value + if max_value > self._sampling_act_abs_min_max[var_name][1]: + self._sampling_act_abs_min_max[var_name][1] = max_value + + def _init_sampling_act_histogram(self): + ''' + Based on the min/max value, init the sampling_act_histogram. + ''' + for var_name in self._quantized_act_var_name: + if var_name not in self._sampling_act_histogram: + min_val = self._sampling_act_abs_min_max[var_name][0] + max_val = self._sampling_act_abs_min_max[var_name][1] + hist, hist_edeges = np.histogram([], + bins=self._histogram_bins, + range=(min_val, max_val)) + self._sampling_act_histogram[var_name] = [hist, hist_edeges] + + def _calculate_kl_hist_threshold(self): + ''' + Calculate the KL or hist threshold of quantized variables. + ''' + _logger.info("Calculate {} threshold ...".format(self._algo)) + assert self._algo in ["KL", "hist"], "The algo should be KL or hist." + + # Abs_max threshold for weights + for var_name in self._quantized_weight_var_name: + weight_data = utils.load_variable_data(self._scope, var_name) + if self._weight_quantize_type == "abs_max": + weight_threshold = float(np.max(np.abs(weight_data))) + elif self._weight_quantize_type == "channel_wise_abs_max": + weight_threshold = [] + if self._weight_op_pairs[ + var_name] in utils._channelwise_quant_axis1_ops: + for i in range(weight_data.shape[1]): + weight_threshold.append( + float(np.max(np.abs(weight_data[:, i])))) + else: + for i in range(weight_data.shape[0]): + weight_threshold.append( + float(np.max(np.abs(weight_data[i])))) + self._quantized_var_threshold[var_name] = weight_threshold + + for var_name in self._quantized_act_var_name: + hist, hist_edeges = self._sampling_act_histogram[var_name] + if self._algo == "KL": + bin_width = hist_edeges[1] - hist_edeges[0] + self._quantized_var_threshold[var_name] = \ + cal_kl_threshold(hist, bin_width, self._activation_bits) + elif self._algo == "hist": + self._quantized_var_threshold[var_name] = \ + self._get_hist_scaling_factor(hist, hist_edeges) + + def _update_program(self): + ''' + Use QuantizationTransformPass and AddQuantDequantPass to insert + fake_quantize, fake_dequantize and fake_quant_dequant op. + Besides, save all threshold to the scale var node. + ''' + _logger.info("Update the program ...") + graph = IrGraph(core.Graph(self._program.desc), for_test=True) + + # use QuantizationTransformPass to insert fake_quant/fake_dequantize op + major_quantizable_op_types = [] + for op_type in utils._weight_supported_quantizable_op_type: + if op_type in self._quantizable_op_type: + major_quantizable_op_types.append(op_type) + if not self._onnx_format: + transform_pass = QuantizationTransformPass( + scope=self._scope, + place=self._place, + weight_bits=self._weight_bits, + activation_bits=self._activation_bits, + activation_quantize_type=self._activation_quantize_type, + weight_quantize_type=self._weight_quantize_type, + quantizable_op_type=major_quantizable_op_types) + else: + transform_pass = QuantizationTransformPassV2( + scope=self._scope, + place=self._place, + weight_bits=self._weight_bits, + activation_bits=self._activation_bits, + activation_quantize_type=self._activation_quantize_type, + weight_quantize_type=self._weight_quantize_type, + quantizable_op_type=major_quantizable_op_types) + + for sub_graph in graph.all_sub_graphs(): + # Insert fake_quant/fake_dequantize op must in test graph, so + # set per graph's _for_test is True. + sub_graph._for_test = True + transform_pass.apply(sub_graph) + + # use AddQuantDequantPass to insert fake_quant_dequant op + minor_quantizable_op_types = [] + for op_type in utils._act_supported_quantizable_op_type: + if op_type in self._quantizable_op_type: + minor_quantizable_op_types.append(op_type) + if not self._onnx_format: + add_quant_dequant_pass = AddQuantDequantPass( + scope=self._scope, + place=self._place, + quantizable_op_type=minor_quantizable_op_types) + else: + add_quant_dequant_pass = AddQuantDequantPassV2( + scope=self._scope, + place=self._place, + quantizable_op_type=minor_quantizable_op_types, + is_full_quantized=True) + + for sub_graph in graph.all_sub_graphs(): + sub_graph._for_test = True + add_quant_dequant_pass.apply(sub_graph) + + # save threshold to scale var node + if self._scale_dict is None: + if self._algo in ["KL", "hist"]: + scale_dict = self._quantized_var_threshold + else: + scale_dict = self._quantized_threshold + + if self._same_scale_tensor_list is not None: + for tensor_list in self._same_scale_tensor_list: + max_scale = None + tmp_tensor_list = [] + for tensor_name in tensor_list: + if '#' in tensor_name: + real_tensor_name, opera, scalar = tensor_name.split( + '#') + if real_tensor_name not in scale_dict.keys(): + continue + if opera == '*': + scale_dict[real_tensor_name] = float( + scale_dict[real_tensor_name]) * float( + scalar) + elif opera == '/': + scale_dict[real_tensor_name] = float( + scale_dict[real_tensor_name]) / float( + scalar) + max_scale = scale_dict[ + real_tensor_name] if max_scale is None else max( + max_scale, scale_dict[real_tensor_name]) + else: + if tensor_name not in scale_dict.keys(): + continue + max_scale = scale_dict[ + tensor_name] if max_scale is None else max( + max_scale, scale_dict[tensor_name]) + + for tensor_name in tensor_list: + if '#' in tensor_name: + real_tensor_name, opera, scalar = tensor_name.split( + '#') + if real_tensor_name not in scale_dict.keys(): + continue + if opera == '*': + scale_dict[ + real_tensor_name] = max_scale / float( + scalar) + elif opera == '/': + scale_dict[ + real_tensor_name] = max_scale * float( + scalar) + else: + if tensor_name not in scale_dict.keys(): + continue + scale_dict[tensor_name] = max_scale + self._scale_dict = scale_dict + + for key, val in self._scale_dict.items(): + utils.set_variable_data(self._scope, self._place, key + "@scale", + np.array([val], dtype=np.float32)) + utils.set_variable_data(self._scope, self._place, + key + ".quant_dequant@scale", + np.array([val], dtype=np.float32)) + + if not self._onnx_format: + # apply QuantizationFreezePass, and obtain the final quant model + if self._freeze_model: + freeze_pass = QuantizationFreezePass( + scope=self._scope, + place=self._place, + bias_correction=self._bias_correction, + weight_bits=self._weight_bits, + round_type=self._round_type, + activation_bits=self._activation_bits, + weight_quantize_type=self._weight_quantize_type, + quantizable_op_type=major_quantizable_op_types) + + for sub_graph in graph.all_sub_graphs(): + sub_graph._for_test = True + freeze_pass.apply(sub_graph) + else: + quant_weight_pass = QuantWeightPass(self._scope, self._place) + for sub_graph in graph.all_sub_graphs(): + sub_graph._for_test = True + quant_weight_pass.apply(sub_graph) + + self._program = graph.to_program() + + def _save_output_threshold(self): + ''' + Save output threshold to the quantized op. + ''' + self._calibration_scales = {} + + def save_info(op_node, out_var_name, threshold_map, out_info_name, + quantized_type): + assert out_var_name in threshold_map, \ + "The output ({}) of {} node does not have threshold.".format( + out_var_name, op_node.type) + if self._onnx_format: + # For easy extension, every var_node set a dict to save parameters of quant. + self._calibration_scales[var_name] = {} + self._calibration_scales[var_name]['scale'] = threshold_map[ + var_name] + else: + op_node._set_attr(out_info_name, threshold_map[var_name]) + op_node._set_attr("with_quant_attr", True) + if op_node.type in self._quantizable_op_type: + op._set_attr("quantization_type", quantized_type) + + def analysis_and_save_info(op_node, out_var_name): + argname_index = utils._get_output_name_index(op_node, out_var_name) + assert argname_index is not None, \ + out_var_name + " is not the output of the op" + if self._algo == "KL": + # For compatibility, we save output threshold by two methods. + save_info(op_node, out_var_name, self._quantized_var_threshold, + "out_threshold", "post_kl") + save_info( + op_node, out_var_name, self._quantized_var_threshold, + argname_index[0] + str(argname_index[1]) + "_threshold", + "post_kl") + elif self._algo == "hist": + # For compatibility, we save output threshold by two methods. + save_info(op_node, out_var_name, self._quantized_var_threshold, + "out_threshold", "post_hist") + save_info( + op_node, out_var_name, self._quantized_var_threshold, + argname_index[0] + str(argname_index[1]) + "_threshold", + "post_hist") + + elif self._algo in ["avg", "abs_max", "mse", "emd", "ptf"]: + save_info(op_node, out_var_name, self._quantized_threshold, + "out_threshold", "post_" + str(self._algo)) + save_info( + op_node, out_var_name, self._quantized_threshold, + argname_index[0] + str(argname_index[1]) + "_threshold", + "post_" + str(self._algo)) + elif self._algo == "min_max": + save_info(op_node, out_var_name, self._quantized_var_min, + "out_min", "post_min_max") + save_info(op_node, out_var_name, self._quantized_var_max, + "out_max", "post_min_max") + + for block_id in range(len(self._program.blocks)): + for op in self._program.blocks[block_id].ops: + if op.type in (self._quantizable_op_type + + self._out_scale_op_list): + out_var_names = utils._get_op_output_var_names(op) + for var_name in out_var_names: + analysis_and_save_info(op, var_name) + + def _collect_dynamic_quantize_op_threshold(self, target_ops_type): + """ + Collect and save the weight threshold for dynamic quantize ops, + such as lstm and gru. + Args: + target_ops_type(list): the op type of target ops + Returns: + None + """ + + target_ops = [] + for index in range(self._program.num_blocks): + for op in self._program.block(index).ops: + if op.type in target_ops_type: + target_ops.append(op) + + quantization_type = str("post_" + self._algo).lower() + persistable_var_names = _all_persistable_var_names(self._program) + for op in target_ops: + for var_name in utils._get_op_input_var_names(op): + if var_name in persistable_var_names: + var_data = utils.load_variable_data(self._scope, var_name) + threshold = float(np.max(np.abs(var_data))) + argname, index = utils._get_input_name_index(op, var_name) + op._set_attr(argname + str(index) + "_threshold", threshold) + op._set_attr("quantization_type", quantization_type) + op._set_attr("bit_length", self._weight_bits) + op._set_attr("with_quant_attr", True) + + def _get_hist_scaling_factor(self, hist, hist_edges): + ''' + Using the hist method to get the scaling factor. + ''' + threshold_rate = self._hist_percent + hist = hist / float(sum(hist)) + hist_sum = 0 + hist_index = 0 + for i in range(len(hist)): + hist_sum += hist[i] + if hist_sum >= threshold_rate: + hist_index = i + 1 + break + bin_width = hist_edges[1] - hist_edges[0] + return (hist_index - 0.5) * bin_width + + +class PostTrainingQuantizationProgram(PostTrainingQuantization): + + def __init__(self, + executor, + program, + feed_list=None, + fetch_list=None, + scope=None, + batch_generator=None, + sample_generator=None, + data_loader=None, + batch_size=10, + batch_nums=None, + algo="KL", + hist_percent=0.99999, + quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"], + round_type='round', + learning_rate=0.001, + is_full_quantize=False, + bias_correction=False, + activation_bits=8, + weight_bits=8, + activation_quantize_type='range_abs_max', + weight_quantize_type='channel_wise_abs_max', + onnx_format=False, + freeze_model=True, + optimize_model=False, + is_use_cache_file=False, + skip_tensor_list=None, + same_scale_tensor_list=None, + cache_dir=None, + scale_dict=None, + return_graph=True): + super().__init__(executor, scope, None, None, None, batch_generator, + sample_generator, data_loader, batch_size, batch_nums, + algo, hist_percent, quantizable_op_type, round_type, + learning_rate, is_full_quantize, bias_correction, + activation_bits, weight_bits, activation_quantize_type, + weight_quantize_type, onnx_format, freeze_model, + optimize_model, is_use_cache_file, skip_tensor_list, + same_scale_tensor_list, cache_dir, scale_dict, + return_graph) + self.FLAG = False + self._program = program + if self._program is not None: + self.FLAG = True + assert feed_list is not None, \ + "Feed list should not be None." + assert fetch_list is not None, \ + "Fetch list should not be None." + self._feed_list = feed_list + self._fetch_list = fetch_list + + +class WeightQuantization(object): + _supported_quantizable_op_type = ['conv2d', 'depthwise_conv2d', 'mul'] + _supported_weight_quantize_type = ['channel_wise_abs_max', 'abs_max'] + + def __init__(self, model_dir, model_filename=None, params_filename=None): + ''' + This class quantizes the weight of some ops to reduce the size of model + or improve the perforemace. + + Args: + model_dir(str): The path of the fp32 model that will be quantized, + and the model and params files are under the path. + model_filename(str, optional): The name of file to load the inference + program. If it is None, the default filename '__model__' will + be used. Default is 'None'. + params_filename(str, optional): The name of file to load all parameters. + When all parameters were saved in a single binary file, set it + as the real filename. If parameters were saved in separate files, + set it as 'None'. Default is 'None'. + ''' + self._model_dir = model_dir + self._model_filename = model_filename + self._params_filename = params_filename + + def quantize_weight_to_int(self, + save_model_dir, + save_model_filename=None, + save_params_filename=None, + quantizable_op_type=["conv2d", "mul"], + weight_bits=8, + weight_quantize_type="channel_wise_abs_max", + generate_test_model=False, + threshold_rate=0.0): + ''' + In order to reduce the size of model, this api quantizes the weight + of some ops from float32 to int8/16. In the inference stage, the + quantized weight will be dequantized to float32 again. + + Args: + save_model_dir(str): The path to save the quantized model. + save_model_filename(str, optional): The name of file to + save the inference program. If it is None, the default + filename '__model__' will be used. Default is 'None'. + save_params_filename(str, optional): The name of file to + save all parameters. If it is None, parameters were + saved in separate files. If it is not None, all + parameters were saved in a single binary file. + quantizable_op_type(list[str], optional): The list of ops + that will be quantized, and the quantized ops should be + contained in ["conv2d", "depthwise_conv2d", "mul"]. + Default is ["conv2d","mul"]. + weight_bits(int, optional): The bits for the quantized weight, + and it should be 8 or 16. Default is 8. + weight_quantize_type(str, optional): quantization type for weights, + support 'channel_wise_abs_max' and 'abs_max'. Set it as + 'channel_wise_abs_max', the accuracy performs better. + generate_test_model(bool, optional): If set generate_test_model + as True, it saves a fake quantized model, in which the weights + are quantized and dequantized. We can use PaddlePaddle to load + the fake quantized model and test the accuracy on GPU or CPU. + threshold_rate(float, optional): This api uses abs_max methd to + quantize the weight from float32 to int8/16, and the abs max + value is important for quantization diff. When the abs_max + value is far away from the center of the numerical distribution, + we can set threshold_rate between 1e-6 and 1e-8, so the abs max + value will be optimized. Default is 0.0. + ''' + for op_type in quantizable_op_type: + assert op_type in self._supported_quantizable_op_type, \ + "Input error:" + op_type + \ + " is not supported for weight quantization." + assert weight_bits in [8, 16], \ + "Input error: weight_bits should be 8 or 16." + assert weight_quantize_type in self._supported_weight_quantize_type, \ + "Input error: weight_quantize_type should in {}".format( + self._supported_weight_quantize_type) + + quantized_model_dir = os.path.join(save_model_dir, "quantized_model") + self._quantize_weight_to_int(quantized_model_dir, save_model_filename, + save_params_filename, quantizable_op_type, + weight_bits, weight_quantize_type, False, + threshold_rate) + + if generate_test_model: + test_model_dir = os.path.join(save_model_dir, "test_model") + self._quantize_weight_to_int(test_model_dir, save_model_filename, + save_params_filename, + quantizable_op_type, weight_bits, + weight_quantize_type, True, + threshold_rate) + + def convert_weight_to_fp16(self, save_model_dir): + """ + Convert all presistable vars from fp32 to fp16. + Note that, this api only changes the data type of variables in + __params__ file, and the __model__ file remains unchanged. + + Args: + save_model_dir(str): The path to save the fp16 model. + """ + + # Load model + place = core.CPUPlace() + exe = Executor(place) + scope = global_scope() + [infer_program, feed_list, fetch_list] = \ + io.load_inference_model(dirname=self._model_dir, + executor=exe, + model_filename=self._model_filename, + params_filename=self._params_filename) + + # Clone and save fp16 weights + save_program = framework.Program() + save_block = save_program.global_block() + save_var_map = {} + + for var in infer_program.list_vars(): + if (var.type == core.VarDesc.VarType.RAW) or \ + (not var.persistable) or (var.name in ['feed', 'fetch']) \ + or (var.dtype != core.VarDesc.VarType.FP32): + continue + + #new_var = _clone_var_to_block_(var, save_block) + new_var = save_block._clone_variable(var) + if self._params_filename is not None: + save_var_map[new_var.name] = new_var + else: + save_file_path = os.path.join(os.path.normpath(save_model_dir), + new_var.name) + save_block.append_op(type='save', + inputs={'X': [new_var]}, + outputs={}, + attrs={ + 'file_path': + os.path.normpath(save_file_path), + 'save_as_fp16': + True + }) + + if self._params_filename is not None: + save_var_list = [] + for name in sorted(save_var_map.keys()): + save_var_list.append(save_var_map[name]) + + saved_params_var = save_block.create_var( + type=core.VarDesc.VarType.RAW, + name=unique_name.generate("saved_params")) + saved_params_var.desc.set_persistable(True) + + save_path = os.path.join(os.path.normpath(save_model_dir), + self._params_filename) + save_block.append_op(type='save_combine', + inputs={'X': save_var_list}, + outputs={'Y': saved_params_var}, + attrs={ + 'file_path': save_path, + 'save_as_fp16': True + }) + + save_program._sync_with_cpp() + exe.run(save_program) + + # Copy model + model_filename = "__model__" if self._model_filename is None \ + else self._model_filename + src_model = os.path.join(self._model_dir, model_filename) + dest_model = os.path.join(save_model_dir, model_filename) + shutil.copyfile(src_model, dest_model) + + def _quantize_weight_to_int(self, save_model_dir, save_model_filename, + save_params_filename, quantizable_op_type, + weight_bits, weight_quantize_type, for_test, + threshold_rate): + """ + Generate quantized model or fake quantized model. + """ + # Load model + place = core.CPUPlace() + exe = Executor(place) + scope = global_scope() + [program, feed_list, fetch_list] = \ + io.load_inference_model(dirname=self._model_dir, + executor=exe, + model_filename=self._model_filename, + params_filename=self._params_filename) + + quantized_ops = [] + for index in range(program.num_blocks): + block = program.block(index) + for op in block.ops: + if op.type in quantizable_op_type: + quantized_ops.append(op) + + # Quantize weights + persistable_var_names = _all_persistable_var_names(program) + for op in quantized_ops: + for var_name in op.input_arg_names: + if var_name in persistable_var_names: + if weight_quantize_type == "abs_max": + self._weight_abs_max_quantization( + scope, place, weight_bits, threshold_rate, op, + var_name, for_test) + elif weight_quantize_type == "channel_wise_abs_max": + self._weight_channel_wise_abs_max_quantization( + scope, place, weight_bits, op, var_name, for_test) + + io.save_inference_model(dirname=save_model_dir, + feeded_var_names=feed_list, + target_vars=fetch_list, + executor=exe, + main_program=program, + model_filename=save_model_filename, + params_filename=save_params_filename) + + def _weight_abs_max_quantization(self, scope, place, weight_bits, + threshold_rate, op, var_name, for_test): + ''' + Use abs_max method to quantize weight. + ''' + quantize_range = (1 << (weight_bits - 1)) - 1 + save_weight_dtype = np.int8 if weight_bits == 8 else np.int16 + + # Get quantized scale and weight data + weight_data = utils.load_variable_data(scope, var_name) + if abs(threshold_rate) < 1e-10: + threshold_value = np.max(np.abs(weight_data)) + else: + threshold_value = self._calculate_threshold(\ + weight_data, threshold_rate) + weight_data[weight_data > threshold_value] = threshold_value + weight_data[weight_data < -threshold_value] = -threshold_value + scale = threshold_value / quantize_range + quantized_weight_data = \ + np.around(weight_data / scale).astype(save_weight_dtype) + + # Set weight data + if not for_test: + utils.set_variable_data(scope, place, var_name, + quantized_weight_data) + else: + dequantized_weight_data = \ + (quantized_weight_data * scale).astype(np.float32) + utils.set_variable_data(scope, place, var_name, + dequantized_weight_data) + + # Save info + op._set_attr('quantization_type', 'post_weight_abs_max') + op._set_attr('quantize_weight_bits', weight_bits) + op._set_attr(var_name + "_quant_scale", [scale]) # Save as list + op._set_attr("with_quant_attr", True) + + def _weight_channel_wise_abs_max_quantization(self, scope, place, + weight_bits, op, var_name, + for_test): + ''' + Use channel_wise_abs_max method to quantize weight. + ''' + quantize_range = (1 << (weight_bits - 1)) - 1 + save_weight_dtype = np.int8 if weight_bits == 8 else np.int16 + + # Get quantized scale and weight data + weight_data = utils.load_variable_data(scope, var_name) + if op.type == "mul": + scales, quantized_weight_data = \ + self._mul_channel_wise_quantization(weight_data, + quantize_range, save_weight_dtype) + elif op.type in ["conv2d", "depthwise_conv2d"]: + scales, quantized_weight_data = \ + self._conv_channel_wise_quantization(weight_data, + quantize_range, save_weight_dtype) + else: + _logger.error(op.type + " is not supported by weight quantization") + + # Set weight data + if not for_test: + utils.set_variable_data(scope, place, var_name, + quantized_weight_data) + else: + if op.type == "mul": + dequantized_weight_data = \ + self._mul_channel_wise_dequantization(quantized_weight_data, scales) + elif op.type in ["conv2d", "depthwise_conv2d"]: + dequantized_weight_data = \ + self._conv_channel_wise_dequantization(quantized_weight_data, scales) + else: + _logger.error(op.type + + " is not supported by weight quantization") + utils.set_variable_data(scope, place, var_name, + dequantized_weight_data) + + # Save info + op._set_attr('quantization_type', 'post_weight_channel_wise_abs_max') + op._set_attr('quantize_weight_bits', weight_bits) + op._set_attr(var_name + "_quant_scale", scales) + op._set_attr("with_quant_attr", True) + + def _conv_channel_wise_quantization(self, weight_data, quantize_range, + save_weight_dtype): + ''' + Get channel wise scale for the weights of conv2d and depthwise_conv2d, + and quantize the weights. + ''' + scales = [] + quantized_weight_data = np.zeros_like(weight_data, + dtype=save_weight_dtype) + channel_num = weight_data.shape[0] + for i in range(channel_num): + scale = np.max(np.abs(weight_data[i])) / quantize_range + scales.append(scale) + quantized_weight_data[i] = \ + np.around(weight_data[i] / scale).astype(save_weight_dtype) + return scales, quantized_weight_data + + def _conv_channel_wise_dequantization(self, quantized_weight_data, scales): + ''' + For conv2d and depthwise_conv2d, dequantize the weights to fp32. + ''' + dequantized_weight_data = np.zeros_like(quantized_weight_data, + dtype=np.float32) + for i in range(len(scales)): + dequantized_weight_data[i] = \ + (quantized_weight_data[i] * scales[i]).astype(np.float32) + return dequantized_weight_data + + def _mul_channel_wise_quantization(self, weight_data, quantize_range, + save_weight_dtype): + ''' + Get channel wise scale for the weights of conv2d and depthwise_conv2d, + and quantize the weights. + ''' + scales = [] + quantized_weight_data = np.zeros_like(weight_data, + dtype=save_weight_dtype) + channel_num = weight_data.shape[-1] + for i in range(channel_num): + scale = np.max(np.abs(weight_data[:, i])) / quantize_range + scales.append(scale) + quantized_weight_data[:, i] = \ + np.around(weight_data[:, i] / scale).astype(save_weight_dtype) + return scales, quantized_weight_data + + def _mul_channel_wise_dequantization(self, quantized_weight_data, scales): + ''' + For mul, dequantize the weights to fp32. + ''' + dequantized_weight_data = np.zeros_like(quantized_weight_data, + dtype=np.float32) + for i in range(len(scales)): + dequantized_weight_data[:, i] = \ + (quantized_weight_data[:, i] * scales[i]).astype(np.float32) + return dequantized_weight_data + + def _calculate_threshold(self, input, threshold_rate, histogram_bins=5000): + input_abs = np.abs(input) + hist, hist_edeges = np.histogram(input_abs, + bins=histogram_bins, + range=(0, np.max(input_abs))) + hist = hist / float(sum(hist)) + hist_sum = 0 + hist_index = 0 + for i in range(len(hist)): + hist_sum += hist[i] + if hist_sum >= 1.0 - threshold_rate: + hist_index = i + 1 + break + bin_width = hist_edeges[1] - hist_edeges[0] + return hist_index * bin_width diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant2_int8_mkldnn_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant2_int8_mkldnn_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..6557a0aec010137d4417cfe5329bff41652698d9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant2_int8_mkldnn_pass.py @@ -0,0 +1,664 @@ +# 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. + +import numpy as np +from .... import core +from ....framework import IrGraph +from ....framework import _get_paddle_place + +__all__ = ['Quant2Int8MkldnnPass'] + +OpRole = core.op_proto_and_checker_maker.OpRole + + +class Quant2Int8MkldnnPass(object): + """ + Transform a quant model IrGraph into MKL-DNN supported INT8 IrGraph. + The pass consists of the following transformations: + 1. gather scale values from fake quantize/dequantize operators, + 2. extract FP32 inference model graph from the quant graph, i.e. + a. remove fake quantize/dequantize operators, + b. dequantize conv2d and mul's weights, + 3. optimize the FP32 graph using standard FP32 optimization fuses + (e.g. `conv2d`+`bn` -> `conv2d`), + 4. quantize the optimized FP32 graph using standard INT8v2 quantization + passes (`cpu_quantize_pass`, `cpu_quantize_squash_pass`). + """ + + def __init__(self, + _ops_to_quantize, + _op_ids_to_skip=None, + _scope=None, + _place=None, + _core=None, + _debug=False): + self._scope = _scope + self._place = _get_paddle_place(_place) + self._core = _core + self._debug = _debug + self._fake_quantize_types = [ + 'fake_quantize_moving_average_abs_max', + 'fake_quantize_range_abs_max', + ] + self._fake_dequantize_types = [ + 'fake_dequantize_max_abs', 'fake_channel_wise_dequantize_max_abs' + ] + self._fake_quantize_dequantize_types = [ + 'fake_quantize_dequantize_abs_max', + 'fake_quantize_dequantize_moving_average_abs_max', + 'fake_channel_wise_quantize_dequantize_abs_max' + ] + self._ops_to_quantize = _ops_to_quantize + self._op_ids_to_skip = _op_ids_to_skip if _op_ids_to_skip is not None else set( + [-1]) + self._scale_immutable_ops = [ + 'transpose2', 'reshape2', 'pool2d', 'slice', 'shape', + 'nearest_interp', 'nearest_interp_v2' + ] + self._scale_ops = ['scale'] + self._conv_ops = ['conv2d', 'depthwise_conv2d'] + self._pool_ops = ['pool2d'] + self._mul_ops = ['mul'] + self._fc_ops = ['fc'] + self._relu_ops = ['relu', 'relu6'] + self._matmul_ops = ['matmul', 'matmul_v2'] + self._gru_ops = ['fusion_gru', 'multi_gru'] + self._lstm_ops = ['fusion_lstm'] + self._weight_thresholds = {} + # Collect the Input and Output sclaes from Fake quant models + self._var_quant_scales = {} + self._max_range = {} + self._s8_max = 127 + self._pass_idx = 0 + self._pass_group = 'int8' + + def apply(self, graph): + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + + self._reset_pass_idx_and_group('int8') + graph = self._label_skip_quantized_op(graph) + graph = self._gather_weight_thresholds_from_fake(graph) + graph = self._gather_input_scales_from_fake(graph) + graph = self._gather_output_scales_from_attr(graph) + graph = self._remove_fake_ops(graph) + graph = self._dequantize_weights(graph) + graph = self._optimize_fp32_graph(graph) + graph = self._compute_weight_scales(graph) + # This function causes nondeterministic quantization behavior + # graph = self._update_relu_output_scales(graph) + graph = self._propagate_scales(graph) + graph = self._quantize_fp32_graph(graph) + graph = self._final_optimizations(graph) + graph = self._cleanup(graph) + return graph + + def prepare_and_optimize_fp32(self, graph): + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + + self._reset_pass_idx_and_group('fp32') + graph = self._optimize_fp32_graph(graph) + graph = self._final_optimizations(graph) + graph = self._cleanup(graph) + return graph + + def _reset_pass_idx_and_group(self, group): + self._pass_idx = 0 + self._pass_group = group + + def _convert_scale2tensor(self, scale): + tensor = core.LoDTensor() + tensor.set(scale, core.CPUPlace()) + return tensor + + def _is_quantizing_all_ops(self): + return len(self._ops_to_quantize) == 0 + + def _is_any_of_op_types_in_graph(self, op_types, graph): + return any(op.name() in op_types for op in graph.all_op_nodes()) + + def _is_any_of_op_types_quantized(self, op_types, graph): + return self._is_any_of_op_types_in_graph( + op_types, graph) and (self._is_quantizing_all_ops() + or any(op_type in self._ops_to_quantize + for op_type in op_types)) + + def _is_conv_quantized(self, graph): + return self._is_any_of_op_types_quantized(self._conv_ops, graph) + + def _is_fc_quantized(self, graph): + return self._is_any_of_op_types_quantized(self._fc_ops, graph) + + def _label_skip_quantized_op(self, graph): + """ + For some ops(conv2d, depthwise_conv2d, mul, matml), find and label + the skip quantized ops. cpu_quantize_placement_pass will use the + label to identify it. + For static models, the skip quantized ops have `skip_quant` attr. + Therefore, it only needs to find and label the skip quantized ops for + dygraph models, in which the quantized ops don't have `quantization_type` + attr. + """ + target_ops = self._conv_ops + self._mul_ops + self._matmul_ops + for op_node in graph.all_op_nodes(): + if op_node.name() in target_ops and \ + not op_node.op().has_attr("quantization_type"): + is_quantized_op = True + for var_node in op_node.inputs: + for front_op_node in var_node.inputs: + if "quantize" not in front_op_node.name(): + is_quantized_op = False + if not is_quantized_op: + op_node.op()._set_attr("skip_quant", True) + return graph + + def _add_scale_for_vars(self, var_names, use_unsigned_int, lod_tensor): + """ + Save quantization scales for variables. Do not overwrite. + """ + scales = self._var_quant_scales + for var_name in var_names: + if var_name not in scales: + scales[var_name] = (use_unsigned_int, lod_tensor) + + def _gather_input_scales_from_fake(self, graph): + # fake_quantize_dequantize_abs_max doesn't have scale value + fake_ops = ['fake_quantize_dequantize_moving_average_abs_max'] + fake_ops.extend(self._fake_quantize_types) + + for op in graph.all_op_nodes(): + if op.name() in fake_ops: + bit_length = op.op().attr("bit_length") + assert bit_length == 8, 'Unsupported number quantization bits ({}). Only 8 is supported now.'.format( + bit_length) + + input_name = op.input("X")[0] + scale_name = op.input("InScale")[0] + output_name = op.output("Out")[0] + # Gather new weight scales after folding batchnorm in convolution + scale = np.array( + 1.0 / self._load_param(self._scope, scale_name)[0]).astype( + np.float64) + scale[scale == np.Inf] = 0.0 + lod_tensor = self._convert_scale2tensor(scale) + use_unsigned_int = False + self._add_scale_for_vars([input_name, output_name], + use_unsigned_int, lod_tensor) + + return graph + + def _gather_weight_thresholds_from_fake(self, graph): + for op in graph.all_op_nodes(): + if op.name() in self._fake_dequantize_types: + input_name = op.input("X")[0] + if op.op().has_attr("max_range"): + _max_range = np.array(op.op().attr("max_range")).astype( + np.float64) + self._weight_thresholds[input_name] = np.array( + self._s8_max * self._s8_max / _max_range).astype( + np.float64) + else: + scale_name = op.input("Scales")[0] + self._weight_thresholds[input_name] = np.array( + self._load_param(self._scope, + scale_name)).astype(np.float64) + + return graph + + def _gather_output_scales_from_attr(self, graph): + for op in graph.all_op_nodes(): + if op.op().has_attr("out_threshold"): + attr_scale = op.op().attr("out_threshold") + if attr_scale == 0.0: + continue + scale = np.array(1.0 / attr_scale).astype(np.float64) + scale[scale == np.Inf] = 0.0 + scale_lod_tensor = self._convert_scale2tensor(scale) + use_unsigned_int = False + for output_name in op.op().outputs(): + for out_var_name in op.op().output(output_name): + self._add_scale_for_vars([out_var_name], + use_unsigned_int, + scale_lod_tensor) + + return graph + + def _propagate_scales(self, graph): + + def _update_scale_op_in_scale(op, input, output): + unsigned, tensor = self._var_quant_scales[output] + scale = np.array(tensor) * op.op().attr("scale") + new_tensor = self._convert_scale2tensor(scale.astype(np.float64)) + self._var_quant_scales[input] = (unsigned, new_tensor) + + def _update_scales(graph): + waiting_for_scale = set() + for op in graph.all_op_nodes(): + if op.name() in self._scale_immutable_ops: + if op.name() == 'slice' or op.name() == 'shape': + input_name = op.input("Input")[0] + else: + input_name = op.input("X")[0] + output_name = op.output("Out")[0] + tensor_names = [input_name, output_name] + + if all(name not in self._var_quant_scales + for name in tensor_names): + waiting_for_scale.update(tensor_names) + continue + elif input_name in self._var_quant_scales: + self._var_quant_scales[ + output_name] = self._var_quant_scales[input_name] + elif output_name in self._var_quant_scales: + self._var_quant_scales[ + input_name] = self._var_quant_scales[output_name] + elif op.name() == 'concat': + output_name = op.output("Out")[0] + if output_name in self._var_quant_scales: + input_names = op.input("X") + for input_name in input_names: + self._var_quant_scales[ + input_name] = self._var_quant_scales[ + output_name] + elif op.name() in self._scale_ops: + input_name = op.input("X")[0] + output_name = op.output("Out")[0] + if output_name in self._var_quant_scales: + _update_scale_op_in_scale(op, input_name, output_name) + return waiting_for_scale + + waiting_for_scale = _update_scales(graph) + waiting_for_scale_prev = set() + + while len(waiting_for_scale + ) != 0 and waiting_for_scale != waiting_for_scale_prev: + waiting_for_scale_prev = waiting_for_scale + waiting_for_scale = _update_scales(graph) + + return graph + + def _load_param(self, scope, param_name): + return np.array(scope.find_var(param_name).get_tensor()) + + def _remove_fake_ops(self, graph): + for op in graph.all_op_nodes(): + if op.name() in self._fake_quantize_types: + self._remove_fake_quantize(graph, op) + elif op.name() in self._fake_dequantize_types: + self._remove_fake_dequantize(graph, op) + elif op.name() in self._fake_quantize_dequantize_types: + self._remove_fake_dequantize(graph, op) + + return graph + + def _remove_fake_quantize(self, graph, op): + fake_quant_in = graph._find_node_by_name(op.inputs, op.input("X")[0]) + fake_quant_in_scale = graph._find_node_by_name(op.inputs, + op.input("InScale")[0]) + fake_quant_out = graph._find_node_by_name(op.outputs, + op.output("Out")[0]) + fake_quant_out_scale = graph._find_node_by_name( + op.outputs, + op.output("OutScale")[0]) + + next_ops = fake_quant_out.outputs + for next_op in next_ops: + self._swap_inputs(next_op, fake_quant_out, fake_quant_in) + graph.link_to(fake_quant_in, next_op) + graph.safe_remove_nodes( + {op, fake_quant_in_scale, fake_quant_out, fake_quant_out_scale}) + + return graph + + def _remove_fake_dequantize(self, graph, op): + fake_dequant_in = graph._find_node_by_name(op.inputs, op.input("X")[0]) + fake_dequant_out = graph._find_node_by_name(op.outputs, + op.output("Out")[0]) + + next_ops = fake_dequant_out.outputs + for next_op in next_ops: + self._swap_inputs(next_op, fake_dequant_out, fake_dequant_in) + graph.link_to(fake_dequant_in, next_op) + graph.safe_remove_nodes({op, fake_dequant_out}) + + return graph + + def _swap_inputs(self, op, old_input, new_input): + for input_name in op.op().input_names(): + if old_input.name() in op.input(input_name): + op.op().set_input(input_name, [ + new_input.name() if x == old_input.name() else x + for x in op.input(input_name) + ]) + + def _dequantize_weights(self, graph): + + def _is_int8_weights(op_node, weight_name): + weight_var_name = op_node.input(weight_name)[0] + if self._scope.find_var(weight_var_name) is None: + return False + weight = self._load_param(self._scope, weight_var_name) + return np.all(np.mod(weight, 1) == 0) + + mul_and_matmul_ops = self._mul_ops + self._matmul_ops + for op in graph.all_op_nodes(): + if op.name() in self._conv_ops and _is_int8_weights(op, "Filter"): + self._dequantize_op_weights(graph, op, "Filter", "Output") + elif op.name() in mul_and_matmul_ops and _is_int8_weights(op, "Y"): + self._dequantize_op_weights(graph, op, "Y", "Out") + + return graph + + def _dequantize_op_weights(self, graph, op_node, weight_name, output_name): + weight_var_name = op_node.input(weight_name)[0] + output_var_name = op_node.output(output_name)[0] + # Convert int8 range weights to fp32 range weights + scales = self._weight_thresholds[output_var_name] + weight = self._load_param(self._scope, weight_var_name) + if scales.size == 1 or scales.size == weight.shape[0]: + w_fp32 = np.multiply(np.divide(weight, self._s8_max).T, scales.T).T + elif len(weight.shape) > 1 and scales.size == weight.shape[1]: + w_fp32 = np.multiply(np.divide(weight, self._s8_max), scales) + else: + raise ValueError( + "The size of weight scales vector ({}) does not match the dimensions ({}) of the weights tensor {}." + .format(scales.size, weight.shape, weight_var_name)) + w_fp32 = w_fp32.reshape(weight.shape).astype(np.float32) + self._restore_var(weight_var_name, w_fp32) + + def _restore_var(self, name, array): + tensor = self._scope.find_var(name).get_tensor() + tensor.set(array, self._place) + + def _update_activations(self, graph): + for op in graph.all_op_nodes(): + if op.name( + ) in self._conv_ops and not op.op().has_attr("fuse_activation"): + activation = "" + if op.op().has_attr("fuse_relu") and op.op().attr("fuse_relu"): + activation = "relu" + op.set_attr("fuse_activation", activation) + return graph + + def _remove_ctrl_vars(self, graph): + remove_ctr_vars = set() + for node in graph.all_var_nodes(): + if node.is_ctrl_var(): + remove_ctr_vars.add(node) + graph.safe_remove_nodes(remove_ctr_vars) + return graph + + def _optimize_fp32_graph(self, graph): + graph = self._update_activations(graph) + graph = self._remove_ctrl_vars(graph) + graph = self._apply_pass(graph, 'mkldnn_placement_pass', + ['mkldnn_enabled_op_types'], [set()]) + # remove dropout ops + graph = self._apply_pass(graph, 'simplify_with_basic_ops_pass') + graph = self._apply_pass(graph, 'layer_norm_fuse_pass') + graph = self._apply_pass(graph, 'attention_lstm_fuse_pass') + graph = self._apply_pass(graph, 'seqconv_eltadd_relu_fuse_pass') + graph = self._apply_pass(graph, 'fc_lstm_fuse_pass') + graph = self._apply_pass(graph, 'mul_lstm_fuse_pass') + graph = self._apply_pass(graph, 'fc_gru_fuse_pass') + graph = self._apply_pass(graph, 'mul_gru_fuse_pass') + graph = self._apply_pass(graph, 'multi_gru_fuse_pass') + graph = self._apply_pass(graph, 'multi_gru_seq_fuse_pass') + graph = self._apply_pass(graph, 'seq_concat_fc_fuse_pass') + graph = self._apply_pass(graph, 'gpu_cpu_squeeze2_matmul_fuse_pass') + graph = self._apply_pass(graph, 'gpu_cpu_reshape2_matmul_fuse_pass') + graph = self._apply_pass(graph, 'gpu_cpu_flatten2_matmul_fuse_pass') + graph = self._apply_pass(graph, 'matmul_v2_scale_fuse_pass') + graph = self._apply_pass(graph, 'squared_mat_sub_fuse_pass') + graph = self._apply_pass(graph, 'is_test_pass') + graph = self._apply_pass(graph, 'gpu_cpu_map_matmul_v2_to_mul_pass') + graph = self._apply_pass(graph, 'gpu_cpu_map_matmul_v2_to_matmul_pass') + graph = self._apply_pass(graph, 'matmul_scale_fuse_pass') + graph = self._apply_pass(graph, 'gpu_cpu_map_matmul_to_mul_pass') + graph = self._apply_pass(graph, 'repeated_fc_relu_fuse_pass') + graph = self._apply_pass(graph, 'depthwise_conv_mkldnn_pass') + graph = self._apply_pass(graph, 'conv_bn_fuse_pass') + graph = self._apply_pass(graph, 'conv_eltwiseadd_bn_fuse_pass') + graph = self._apply_pass(graph, 'conv_affine_channel_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'conv_transpose_bn_fuse_pass') + graph = self._apply_pass(graph, + 'conv_transpose_eltwiseadd_bn_fuse_pass') + graph = self._apply_pass(graph, 'conv_bias_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'conv_transpose_bias_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'conv_elementwise_add_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'conv_activation_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'fc_fuse_pass', + ['use_gpu', 'use_fc_padding'], [False, False]) + graph = self._apply_pass(graph, 'repeated_fc_relu_fuse_pass') + if self._is_fc_quantized(graph): + # Disabled due to topology-dependent speed-up + graph = self._apply_pass(graph, 'fc_mkldnn_pass') + graph = self._apply_pass(graph, 'fc_act_mkldnn_fuse_pass') + graph = self._apply_pass(graph, + 'matmul_transpose_reshape_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'batch_norm_act_fuse_pass') + graph = self._apply_pass(graph, 'softplus_activation_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'scale_matmul_fuse_pass') + graph = self._apply_pass(graph, + 'reshape_transpose_matmul_mkldnn_fuse_pass') + graph = self._apply_pass(graph, + 'matmul_elementwise_add_mkldnn_fuse_pass') + # the following pass should be the last one since it will work on all fused ops. + graph = self._apply_pass(graph, 'runtime_context_cache_pass') + return graph + + def _apply_pass(self, graph, pass_name, attrs=None, attr_values=None): + ir_pass = core.get_pass(pass_name) + cpp_graph = graph.graph + if not cpp_graph.has('__param_scope__'): + cpp_graph.set_not_owned('__param_scope__', self._scope) + if attrs: + assert attr_values and len(attrs) == len( + attr_values + ), "Different number of pass attributes and their values." + for attr, value in zip(attrs, attr_values): + ir_pass.set(attr, value) + ir_pass.apply(cpp_graph) + if self._debug: + graph.draw( + '.', '{}_{}_{}'.format(self._pass_group, self._pass_idx, + pass_name), graph.all_op_nodes()) + self._remove_unused_var_nodes(graph) + self._pass_idx += 1 + return graph + + def _final_optimizations(self, graph): + # make some MKL-DNN ops working inplace + graph = self._apply_pass(graph, 'mkldnn_inplace_pass') + return graph + + def _cleanup(self, graph): + graph = self._remove_unused_var_nodes(graph) + graph = self._set_op_role_forward(graph) + return graph + + def _remove_unused_var_nodes(self, graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) + return graph + + def _set_op_role_forward(self, graph): + ops = graph.all_op_nodes() + for op in ops: + op.set_attr("op_role", OpRole.Forward) + return graph + + def _compute_weight_scales(self, graph): + + def _compute_var_scales(ops, w_name, axis): + for op in graph.all_op_nodes(): + if op.op().type() in ops: + weight_var_name = op.input(w_name)[0] + weights = np.array( + self._load_param(self._scope, weight_var_name)) + scales = 1.0 / np.amax(np.abs( + weights.reshape(weights.shape[0], -1)).astype( + np.float64), + axis=axis) + scales[scales == np.Inf] = 0.0 + + lod_tensor = self._convert_scale2tensor(scales) + use_unsigned_int = False + self._var_quant_scales[weight_var_name] = (use_unsigned_int, + lod_tensor) + + def _compute_single_gru_weight_scales(wx_var_name, wh_var_name): + wx = np.array(self._load_param(self._scope, wx_var_name)) + wh = np.array(self._load_param(self._scope, wh_var_name)) + OC = wh.shape[0] + scale_ur = 1.0 / np.max(np.abs( + np.concatenate([ + wx[:, :2 * OC], + wh.flatten()[:2 * OC * OC].reshape(OC, 2 * OC) + ], + axis=0)), + axis=0) + scale_o = 1.0 / np.max(np.abs( + np.concatenate([ + wx[:, 2 * OC:], + wh.flatten()[2 * OC * OC:].reshape(OC, OC) + ], + axis=0)), + axis=0) + + gru_weights_scale = np.concatenate([scale_ur, + scale_o]).astype('float') + + return self._convert_scale2tensor(gru_weights_scale) + + def _compute_gru_weight_scales(wx_name, wh_name): + for op in graph.all_op_nodes(): + if op.op().type() in self._gru_ops: + assert len(op.input(wx_name)) == len( + op.input(wh_name) + ), 'Mismatch in number of weights inputs ({} for WeightX vs. {} for WeightH).'.format( + len(op.input(wx_name)), len(op.input(wh_name))) + for i, wx_var_name in enumerate(op.input(wx_name)): + wh_var_name = op.input(wh_name)[i] + use_unsigned_int = False + lod_tensor = _compute_single_gru_weight_scales( + wx_var_name, wh_var_name) + self._var_quant_scales[wx_var_name] = (use_unsigned_int, + lod_tensor) + + def _compute_single_lstm_weight_scales(wx_var_name, wh_var_name): + wx = np.array(self._load_param(self._scope, wx_var_name)) + wh = np.array(self._load_param(self._scope, wh_var_name)) + + lstm_weights_scale = 1.0 / np.max( + np.abs(np.concatenate([wx[:, :], wh[:, :]], axis=0)), axis=0) + lstm_weights_scale = lstm_weights_scale.astype('float') + + return self._convert_scale2tensor(lstm_weights_scale) + + def _compute_lstm_weight_scales(wx_name, wh_name): + for op in graph.all_op_nodes(): + if op.op().type() in self._lstm_ops: + assert len(op.input(wx_name)) == len( + op.input(wh_name) + ), 'Mismatch in number of weights inputs ({} for WeightX vs. {} for WeightH).'.format( + len(op.input(wx_name)), len(op.input(wh_name))) + for i, wx_var_name in enumerate(op.input(wx_name)): + wh_var_name = op.input(wh_name)[i] + use_unsigned_int = False + lod_tensor = _compute_single_lstm_weight_scales( + wx_var_name, wh_var_name) + self._var_quant_scales[wx_var_name] = (use_unsigned_int, + lod_tensor) + + _compute_var_scales(self._conv_ops, "Filter", axis=1) + _compute_var_scales(self._fc_ops, "W", axis=0) + _compute_var_scales(self._gru_ops, "WeightH", axis=0) + _compute_var_scales(self._lstm_ops, "WeightH", axis=0) + _compute_gru_weight_scales("WeightX", "WeightH") + _compute_lstm_weight_scales("WeightX", "WeightH") + return graph + + def _update_relu_output_scales(self, graph): + + def _set_unsigned_scale(graph, ops, op_out_name, predicate): + ''' + Sets the type of an output scale of a passed op type(s) to 'unsigned int8' if the + predicate applied on op passes. Typically, the predicate checks if op's + activation is set to relu. + ''' + for op in graph.all_op_nodes(): + if op.name() in ops: + out_name = op.output(op_out_name)[0] + if out_name in self._var_quant_scales and predicate( + op.op()): + is_unsigned, tensor = self._var_quant_scales[out_name] + if is_unsigned is False: + # If the variable is signed, it means that the scales for this var + # were computed for signed data, so the scale must be multiplied by 2 + # to fill the entire range of uint8 + scale = np.array(tensor) * 2 + tensor = self._convert_scale2tensor( + scale.astype(np.float64)) + self._var_quant_scales[out_name] = (True, tensor) + return graph + + def conv_predicate(op): + return op.attr("fuse_activation") in self._relu_ops + + graph = _set_unsigned_scale(graph, self._conv_ops, "Output", + conv_predicate) + + def fc_predicate(op): + return op.attr("activation_type") in self._relu_ops + + graph = _set_unsigned_scale(graph, self._fc_ops, "Out", fc_predicate) + + graph = _set_unsigned_scale(graph, self._relu_ops, 'Out', + lambda op: True) + + return graph + + def _get_data_layout(self, graph): + return 'NHWC' if self._is_conv_quantized(graph) else 'NCHW' + + def _quantize_fp32_graph(self, graph): + graph = self._apply_pass(graph, 'scale_matmul_fuse_pass') + graph = self._apply_pass(graph, + 'reshape_transpose_matmul_mkldnn_fuse_pass') + graph = self._apply_pass(graph, 'cpu_quantize_placement_pass', + ['quantize_enabled_op_types'], + [self._ops_to_quantize]) + graph = self._apply_pass( + graph, 'cpu_quantize_pass', ['quant_var_scales', 'data_layout'], + [self._var_quant_scales, + self._get_data_layout(graph)]) + graph = self._apply_pass(graph, 'cpu_quantize_squash_pass') + graph = self._apply_pass(graph, 'int8_scale_calculation_mkldnn_pass') + graph = self._apply_pass(graph, 'params_quantization_mkldnn_pass') + return graph diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant_int8_mkldnn_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant_int8_mkldnn_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..d56aeb79f3f7c93ef23a2888f2f58fc0628e4ef0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quant_int8_mkldnn_pass.py @@ -0,0 +1,281 @@ +# 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. + +import numpy as np +from .... import core +from ....framework import IrGraph +from ....framework import IrNode +from ....framework import _get_paddle_place + +__all__ = ['QuantInt8MkldnnPass'] + + +class QuantInt8MkldnnPass(object): + """ + Convert QuantizationFreezePass generated IrGraph to MKL-DNN supported INT8 + IrGraph. Following transformations did in this pass: + 1. Convert int8 range weights with float32 data type, which are generated by + the QuantizationFreezePass, to float32 range weights with float32 data type + by using the corresponding scales. This conversion is because MKL-DNN INT8 + conv2d kernel and mul kernel now only support float32 weights input, hence + weights quantization will happen inside the conv2d and mul INT8 kernel. + 2. Create the new conv2d or mul op with the converted weights and link its output + to fake_dequantize_abs_max op's output and set conv2d's attribute "force_fp32 + _output" as true + 3. Transform fake_quantize_xx op to quantize op + 4. Remove fake_dequantize_abs_max op + """ + + def __init__(self, _scope=None, _place=None): + r""" + Args: + scope(fluid.Scope): scope is used to initialize the new parameters. + place(fluid.CPUPlace|str): place is used to initialize the new parameters. + When it is string, it can be only 'cpu'. + + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle.fluid as fluid + from paddle.fluid.contrib.slim.quantization \ + import QuantInt8MkldnnPass + from paddle.fluid.framework import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(fluid.Program().desc), for_test=False) + place = fluid.CPUPlace() + mkldnn_pass = QuantInt8MkldnnPass(fluid.global_scope(), + place) + mkldnn_pass.apply(graph) + """ + + self._scope = _scope + self._place = _get_paddle_place(_place) + + self._quantize_type = [ + 'fake_quantize_moving_average_abs_max', + 'fake_quantize_range_abs_max' + ] + self._dequantize_type = ['fake_dequantize_max_abs'] + self._quantize_dequantize_type = [ + 'fake_quantize_dequantize_moving_average_abs_max' + ] + + self._quantizable_ops = ['conv2d', 'depthwise_conv2d', 'mul'] + self._conv_ops = ['conv2d', 'depthwise_conv2d'] + self._pool_ops = ['pool2d'] + + self._in_scale = {} + self._max_range = {} + self._new_output = {} + self._s8_max = 127 + + def apply(self, graph): + """ + Quantize the graph for running MKL-DNN INT8 inference. According + to activation quantization type, the graph will transform fake + quantize ops to quantize ops and remove the fake dequantize ops. + + Args: + graph(IrGraph): the applied graph. + """ + + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + ops = graph.all_op_nodes() + + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + # Collect the _in_scales and _max_range to calculate the new scales for MKL-DNN + # INT8 conv2d and mul + for op_node in ops: + if op_node.name() in self._dequantize_type: + input_name = op_node.input("X")[0] + scale_name = op_node.input("Scale")[0] + self._in_scale[input_name] = self._load_param( + self._scope, scale_name)[0] + self._max_range[input_name] = op_node.op().attr("max_range") + self._new_output[input_name] = op_node.output("Out")[0] + + if op_node.name() in self._quantize_dequantize_type: + inputs = op_node.op().input_names() + attrs = op_node.op().attr_names() + input_name = op_node.input("X")[0] + scale_name = op_node.input("InScale")[0] + self._in_scale[input_name] = self._load_param( + self._scope, scale_name)[0] + # self._max_range[input_name] = op_node.op().attr("max_range") + self._new_output[input_name] = op_node.output("Out")[0] + + for op_node in ops: + if op_node.name() in self._quantizable_ops: + if op_node.name() in self._conv_ops: + self._transform_to_conv_mkldnn(graph, op_node) + elif op_node.name() in self._pool_ops: + self._transform_to_pool_mkldnn(graph, op_node) + else: + self._transform_to_mul_mkldnn(graph, op_node) + elif op_node.name() in self._quantize_type: + self._transform_to_quantize_mkldnn(graph, op_node) + elif op_node.name() in self._dequantize_type: + self._remove_fake_dequantize_op(graph, op_node) + self._remove_unused_var_nodes(graph) + return graph + + def _transform_to_pool_mkldnn(self, graph, op): + output_name = op.output("Out")[0] + input_name = op.input("X")[0] + + def _transform_to_conv_mkldnn(self, graph, op_node): + weight_name = op_node.input("Filter")[0] + output_name = op_node.output("Output")[0] + # Convert int8 range weights to fp32 range weights + weight = self._load_param(self._scope, weight_name) + w_fp32 = np.divide(np.multiply(weight, self._s8_max), + self._max_range[output_name]) + w_fp32 = w_fp32.reshape(weight.shape) + self._restore_var(weight_name, w_fp32) + input_var_node = graph._find_node_by_name(op_node.inputs, + op_node.input("Input")[0]) + weight_var_node = graph._find_node_by_name(op_node.inputs, weight_name) + + # Set fake_dequantize_abs_max's output as new output of conv2d + output_var_node = graph._find_node_by_name( + graph.all_var_nodes(), self._new_output[output_name]) + attrs = { + name: op_node.op().attr(name) + for name in op_node.op().attr_names() + } + + conv_op_node = graph.create_op_node(op_type='conv2d', + attrs=attrs, + inputs={ + 'Input': input_var_node, + 'Filter': weight_var_node + }, + outputs={'Output': output_var_node}) + + # Based on the Quant's scales to calculate the scales of MKL-DNN INT8 conv2d + scale_in = self._s8_max / self._in_scale[output_name] + scale_w = [] + scale_w = [self._max_range[output_name] / self._s8_max] + + conv_op_node.set_attr("Scale_weights", scale_w) + conv_op_node.set_attr("Scale_in", scale_in) + conv_op_node.set_attr("Scale_out", 1.0) + conv_op_node.set_attr("use_mkldnn", 1) + conv_op_node.set_attr("force_fp32_output", 1) + graph.link_to(input_var_node, conv_op_node) + graph.link_to(weight_var_node, conv_op_node) + graph.link_to(conv_op_node, output_var_node) + graph.safe_remove_nodes(op_node) + + def _transform_to_mul_mkldnn(self, graph, op_node): + # For MKL-DNN INT8 mul, input Y should be the weights + weight_name = op_node.input("Y")[0] + output_name = op_node.output("Out")[0] + # Convert int8 range weights to fp32 range weights + weight = self._load_param(self._scope, weight_name) + w_fp32 = np.divide(np.multiply(weight, self._s8_max), + self._max_range[output_name]) + w_fp32 = w_fp32.reshape(weight.shape) + self._restore_var(weight_name, w_fp32) + input_var_node = graph._find_node_by_name(op_node.inputs, + op_node.input("X")[0]) + weight_var_node = graph._find_node_by_name(op_node.inputs, weight_name) + + # Set fake_dequantize_abs_max's output as new output of mul + output_var_node = graph._find_node_by_name( + graph.all_var_nodes(), self._new_output[output_name]) + attrs = { + name: op_node.op().attr(name) + for name in op_node.op().attr_names() + } + + mul_op_node = graph.create_op_node(op_type='mul', + attrs=attrs, + inputs={ + 'X': input_var_node, + 'Y': weight_var_node + }, + outputs={'Out': output_var_node}) + + # Based on the Quant's scales to calculate MKL-DNN INT8 mul's scales + scale_in = self._s8_max / self._in_scale[output_name] + scale_w = [] + scale_w = [self._max_range[output_name] / self._s8_max] + + mul_op_node.set_attr("scale_y", scale_w) + mul_op_node.set_attr("scale_x", scale_in) + mul_op_node.set_attr("scale_out", 1.0) + mul_op_node.set_attr("use_mkldnn", 1) + mul_op_node.set_attr("force_fp32_output", 1) + graph.link_to(input_var_node, mul_op_node) + graph.link_to(weight_var_node, mul_op_node) + graph.link_to(mul_op_node, output_var_node) + graph.safe_remove_nodes(op_node) + + def _transform_to_quantize_mkldnn(self, graph, op_node): + """ + Transform fake_quantize_xx op to quantize mkldnn op in the graph. + """ + input_var_node = graph._find_node_by_name(op_node.inputs, + op_node.input("X")[0]) + output_var_node = graph._find_node_by_name(op_node.outputs, + op_node.output("Out")[0]) + scale_in = self._s8_max / self._load_param( + self._scope, + op_node.input("InScale")[0])[0] + quant_op_node = graph.create_op_node( + op_type='quantize', + attrs={ + 'data_format': 'MKLDNNLAYOUT', + 'use_mkldnn': 1, + 'Scale': scale_in, + 'is_negative_input': 1 + }, + inputs={'Input': input_var_node}, + outputs={'Output': output_var_node}) + graph.link_to(input_var_node, quant_op_node) + graph.link_to(quant_op_node, output_var_node) + graph.safe_remove_nodes(op_node) + + def _remove_fake_dequantize_op(self, graph, op_node): + input_var_node = graph._find_node_by_name(op_node.inputs, + op_node.input("X")[0]) + graph.safe_remove_nodes(op_node) + + def _load_param(self, scope, param_name): + return np.array(scope.find_var(param_name).get_tensor()) + + def _restore_var(self, name, array): + tensor = self._scope.find_var(name).get_tensor() + tensor.set(array, self._place) + + def _remove_unused_var_nodes(self, graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantization_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantization_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..c94117830d79e926fafcd92626d4e80584cace86 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantization_pass.py @@ -0,0 +1,2882 @@ +# Copyright (c) 2018 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. + +import collections +import numpy as np +try: + from tqdm import tqdm +except: + from .utils import tqdm +from ..... import compat as cpt +from .... import core +from ....framework import IrGraph +from ....framework import IrNode +from ....framework import Operator +from .... import unique_name + +from ....framework import Program, program_guard, default_startup_program +from ....data import data +from ....layers import mean +from ....executor import scope_guard +from ....framework import _get_paddle_place +from . import utils + +__all__ = [ + 'QuantizationTransformPass', + 'QuantizationFreezePass', + 'ConvertToInt8Pass', + 'TransformForMobilePass', + 'OutScaleForTrainingPass', + 'OutScaleForInferencePass', + 'AddQuantDequantPass', + 'QuantizationTransformPassV2', + 'AddQuantDequantPassV2', + 'ReplaceFakeQuantDequantPass', + 'QuantWeightPass', + 'AddQuantDequantForInferencePass', +] + +_fake_quant_op_list = [ + 'fake_quantize_abs_max', 'fake_quantize_range_abs_max', + 'fake_quantize_moving_average_abs_max', 'fake_channel_wise_quantize_abs_max' +] + +_fake_dequant_op_list = [ + 'fake_dequantize_max_abs', 'fake_channel_wise_dequantize_max_abs' +] + +_fake_quant_dequant_op_list = [ + 'fake_quantize_dequantize_moving_average_abs_max', + "fake_channel_wise_quantize_dequantize_abs_max", + "fake_quantize_dequantize_abs_max", +] + +_conv_ops = ['conv2d', 'depthwise_conv2d', 'conv2d_transpose'] + +_SCALE_DEFAULT_VALUE = 0.001 + + +def _init_var_node(var_node, value, scope, place): + assert isinstance(value, + np.ndarray), 'The type of value should be numpy array.' + assert scope is not None, \ + 'The scope cannot be set None.' + assert place is not None, \ + 'The place cannot be set None.' + tensor = scope.var(var_node.name()).get_tensor() + tensor.set(value, place) + + +def _is_input_all_not_persistable(graph, op_node): + ''' + Analyse the real inputs of the op node are all not persistable. + ''' + is_input_all_not_persistable = True + for var_name in utils._get_op_input_var_names(op_node): + in_node = graph._find_node_by_name(op_node.inputs, var_name) + is_input_all_not_persistable = (is_input_all_not_persistable and \ + (not in_node.persistable())) + return is_input_all_not_persistable + + +def _check_grandchild_op_node(op_node, grandchild_op_name): + ''' + Check whether the fake_quant node has a grandchild op node named + grandchild_op_name. + ''' + for out1_var_node in op_node.outputs: + for out1_op_node in out1_var_node.outputs: + for out2_var_node in out1_op_node.outputs: + for out2_op_node in out2_var_node.outputs: + if out2_op_node.name() == grandchild_op_name: + return True + return False + + +class QuantizationTransformPass(object): + """ + Quantize the ops that have weights. Add quant and dequant ops for + the quantized ops's inputs. + """ + + def __init__(self, + scope=None, + place=None, + weight_bits=8, + activation_bits=8, + activation_quantize_type='abs_max', + weight_quantize_type='abs_max', + window_size=10000, + moving_rate=0.9, + skip_pattern=['skip_quant'], + quantizable_op_type=['conv2d', 'depthwise_conv2d', 'mul'], + weight_quantize_func=None, + act_quantize_func=None, + weight_preprocess_func=None, + act_preprocess_func=None, + optimizer_func=None, + executor=None, + is_test=None): + r""" + Constructor. + + Args: + scope(fluid.Scope): When activation use 'range_abs_max' as the quantize + type, this pass will create some new parameters. The scope is used to + initialize these new parameters. + place(fluid.CPUPlace|fluid.CUDAPlace|str): place is used to initialize new + parameters described above. If it's string, It can be ``cpu``, and ``gpu:x``, + where ``x`` is the index of the GPUs. + weight_bits(int): quantization bit number for weights, + the bias is not quantized. + activation_bits(int): quantization bit number for activation. + activation_quantize_type(str): quantization type for activation, + now support 'abs_max', 'range_abs_max' and 'moving_average_abs_max'. + If use 'abs_max' mode, the quantization scale will be calculated + dynamically each step in both training and testing period. If use + 'range_abs_max', a static quantization scale will be calculated + during training and used in inference. + weight_quantize_type(str): quantization type for weights, + support 'abs_max' and 'channel_wise_abs_max'. The 'range_abs_max' + usually is not used for weight, since weights are fixed once the + model is well trained. + window_size(int): the window size for 'range_abs_max' quantization. + moving_rate(float): the param for 'moving_average_abs_max' quantization. + skip_pattern(str or str list): The user-defined quantization skip pattern, which + will be presented in the name scope of an op. When the skip pattern is + detected in an op's name scope, the corresponding op will not be quantized. + quantizable_op_type(list[str]): List the type of ops that will be quantized. + Default is ["conv2d", "depthwise_conv2d", "mul"]. The quantizable_op_type in + QuantizationFreezePass and ConvertToInt8Pass must be the same as this. + weight_quantize_func(function): Function that defines how to quantize weight. + Using this can quickly test if user's quantization method works or not. + In this function, user should both define quantization function and + dequantization function, that is, the function's input is non-quantized + weight and function returns dequantized weight. If None, will use + quantization op defined by 'weight_quantize_type'. Default is None. + act_quantize_func(function): Function that defines how to quantize activation. + Using this can quickly test if user's quantization method works or not. + In this function, user should both define quantization and dequantization + process, that is, the function's input is non-quantized activation and + function returns dequantized activation. If None, will use quantization + op defined by 'activation_quantize_type'. Default is None. + weight_preprocess_func(function): Function that defines how to preprocess + weight before quantization. Using this can quickly test if user's preprocess + method works or not. The function's input is non-quantized weight and + function returns processed weight to be quantized. If None, the weight will + be quantized directly. Default is None. + act_preprocess_func(function): Function that defines how to preprocess + activation before quantization. Using this can quickly test if user's + preprocess method works or not. The function's input is non-quantized + activation and function returns processed activation to be quantized. + If None, the activation will be quantized directly. Default is None. + optimizer_func(function): Fuction return a optimizer. When 'is_test' is + False and user want to use self-defined quantization function and + preprocess function, this function must be set. Default is None. + executor(Fluid.Executor): If user want to use self-defined quantization + function and preprocess function, executor must be set for initialization. + Default is None. + + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle.fluid as fluid + from paddle.fluid.contrib.slim.quantization \ + import QuantizationTransformPass + from paddle.fluid.contrib.slim.graph import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(program.desc), for_test=False) + place = fluid.CPUPlace() + transform_pass = QuantizationTransformPass(fluid.global_scope(), + place) + transform_pass.apply(graph) + """ + self._scope = scope + self._place = _get_paddle_place(place) + self._weight_bits = weight_bits + self._activation_bits = activation_bits + self._skip_pattern = skip_pattern + self._weight_quantize_func = weight_quantize_func + self._act_quantize_func = act_quantize_func + self._weight_preprocess_func = weight_preprocess_func + self._act_preprocess_func = act_preprocess_func + self._optimizer = optimizer_func + self._exe = executor + quant_type = [ + 'abs_max', 'channel_wise_abs_max', 'range_abs_max', + 'moving_average_abs_max' + ] + assert activation_quantize_type != 'channel_wise_abs_max', \ + "The activation quantization type does not support 'channel_wise_abs_max'." + if activation_quantize_type not in quant_type: + raise ValueError( + "Unknown activation_quantize_type : '%s'. It can only be " + "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'." % + (str(activation_quantize_type))) + if weight_quantize_type not in quant_type: + raise ValueError( + "Unknown weight_quantize_type: '%s'. It can only be " + "'abs_max' or 'channel_wise_abs_max' or 'range_abs_max' " + "or 'moving_average_abs_max'." % (str(weight_quantize_type))) + + self._activation_quantize_type = activation_quantize_type + self._weight_quantize_type = weight_quantize_type + self._window_size = window_size + self._moving_rate = moving_rate + + self._quantizable_ops = quantizable_op_type + for op in self._quantizable_ops: + assert op in utils._weight_supported_quantizable_op_type, \ + op + " is not supported for quantization." + self._quantizable_grad_ops = [ + '%s_grad' % (op) for op in self._quantizable_ops + ] + self._is_test = is_test + self._global_step = None + + self.create_var_map = {} + self.create_op_map = {} + + def apply(self, graph): + """ + Quantize the graph for training process. According to weight and + activation quantization type, the graph will be added some fake + quantize operators and fake dequantize operators. + + Args: + graph(IrGraph): the applied graph. + Returns: + None + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + if self._is_test is None: + self._is_test = graph.is_test() + # marked the variable which has been dequantized. + dequantized_vars = collections.OrderedDict() + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + processed_vars = [] + + def _quant_preprocess(op_node): + user_skipped = False + if isinstance(self._skip_pattern, list): + user_skipped = op_node.op().has_attr("op_namescope") and \ + any(pattern in op_node.op().attr("op_namescope") \ + for pattern in self._skip_pattern) + elif isinstance(self._skip_pattern, str): + user_skipped = op_node.op().has_attr("op_namescope") and \ + op_node.op().attr("op_namescope").find( + self._skip_pattern) != -1 + + if user_skipped: + op_node.op()._set_attr("skip_quant", True) + op_node.op()._set_attr("with_quant_attr", True) + + def _transform_forward(graph, op): + op.op()._set_attr("quantization_type", "qat_with_weight") + op.op()._set_attr("with_quant_attr", True) + inputs = op.inputs + for var_node in inputs: + if var_node.name() not in op.input_arg_names(): + continue + if var_node.name() in dequantized_vars: + dequant_var_node = dequantized_vars[var_node.name()] + else: + name = var_node.name() + if name in processed_vars: + continue + is_weight = True if var_node.name() in persistable_vars \ + else False + + # if var node is weight and weight_preprocess_func is not None, + # will insert weight preprocess func + # to preorocess weight before quantization + # if var node is activation and act_preprocess_func is not None, + # will insert activation preprocess func + # to preorocess activation before quantization + if is_weight and self._weight_preprocess_func is not None: + var_node = self._insert_func( + graph, self._weight_preprocess_func, var_node, op) + elif not is_weight and self._act_preprocess_func is not None: + var_node = self._insert_func(graph, + self._act_preprocess_func, + var_node, op) + + # if var node is weight and weight_quantize_func is not None, + # will insert weight quantize func to quantize and dequantize weight + # if var node is activation and act_quantize_func is not None, + # will insert act quantize func to quantize and dequantize activation + if is_weight and self._weight_quantize_func is not None: + target_out_node = self._insert_func( + graph, self._weight_quantize_func, var_node, op) + processed_vars.append(name) + continue + elif not is_weight and self._act_quantize_func is not None: + target_out_node = self._insert_func( + graph, self._act_quantize_func, var_node, op) + processed_vars.append(name) + continue + + quant_bits = self._weight_bits if var_node.name() in persistable_vars \ + else self._activation_bits + quant_type = self._weight_quantize_type if is_weight \ + else self._activation_quantize_type + if quant_type == 'channel_wise_abs_max': # Weight quantization + quant_axis = 1 if op.name() in \ + utils._channelwise_quant_axis1_ops else 0 + quant_var_node, scale_var_node = self._insert_channel_quant_op( + graph, var_node, name, quant_bits, quant_axis) + dequant_var_node = self._insert_channel_dequant_op( + graph, quant_var_node, [scale_var_node], + [quant_bits], quant_axis) + else: + quant_var_node, scale_var_node = self._insert_quant_op( + graph, var_node, name, quant_bits, quant_type) + dequant_var_node = self._insert_dequant_op( + graph, quant_var_node, scale_var_node, quant_bits) + dequantized_vars[name] = dequant_var_node + graph.update_input_link(var_node, dequant_var_node, op) + + def _transform_backward(graph, op): + for var_node in op.inputs: + if var_node.name() not in op.input_arg_names(): + continue + if var_node.name() in dequantized_vars: + dequant_var_node = dequantized_vars[var_node.name()] + graph.update_input_link(var_node, dequant_var_node, op) + + def _has_weight(op): + has_weight = False + for var_node in op.inputs: + if var_node.name() not in op.input_arg_names(): + continue + name = var_node.name() + if var_node.name() in persistable_vars: + has_weight = True + return has_weight + + if not self._is_test: + self._create_global_step(graph) + ops = graph.all_op_nodes() + # Do the preproccess of quantization, such as skipping some ops + # for not being quantized. + for op in ops: + if op.name() in self._quantizable_ops or \ + op.name() in self._quantizable_grad_ops: + _quant_preprocess(op) + # Insert mapping table to solve the problem in saving inference model. + graph.out_node_mapping_table = dict() + # The process of _transform_forward and _transform_backward is needed in two for loops. + # The loop for transforming the forward graph: + with tqdm(total=len(ops), + bar_format= + 'Adding quant op with weight:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for op in ops: + if op.name() in self._quantizable_ops: + if not self._is_skip_quant(graph, op) and _has_weight(op): + _transform_forward(graph, op) + t.update() + # The loop for renaming the inputs of backward op. + for op in ops: + if op.name() in self._quantizable_grad_ops and _has_weight(op): + _transform_backward(graph, op) + graph.resolve_hazard() + return graph + + def _create_global_step(self, graph): + if self._weight_quantize_type == 'range_abs_max' or \ + self._activation_quantize_type == 'range_abs_max': + counter_name = cpt.to_text('@STEP_COUNTER@') + for node in graph.all_var_nodes(): + if node.name() == counter_name: + self._global_step = node + if self._global_step is None: + global_step_in = graph.create_persistable_node( + name=counter_name, + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[1], + var_dtype=core.VarDesc.VarType.INT64) + _init_var_node(global_step_in, np.zeros([1], dtype='int64'), + self._scope, self._place) + global_step_out = graph.create_var_node_from_desc( + global_step_in.var()) + # The attribute of `op_role` is needed by ParallelExecutor. + increment_op = graph.create_op_node( + op_type='increment', + attrs={ + 'step': 1.0, + 'op_role': + core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={'X': global_step_in}, + outputs={'Out': global_step_out}) + graph.link_to(global_step_in, increment_op) + graph.link_to(increment_op, global_step_out) + self._global_step = global_step_out + + def _insert_quant_op(self, graph, var_node, name, quant_bits, quant_type): + """ + Insert fake_quantize_op in the graph. + """ + if quant_type == 'abs_max': + return self._insert_quant_abs_max_op(graph, var_node, name, + quant_bits) + elif quant_type == 'range_abs_max': + return self._insert_quant_range_abs_max_op(graph, var_node, name, + quant_bits) + elif quant_type == 'moving_average_abs_max': + return self._insert_quant_moving_average_abs_max_op( + graph, var_node, name, quant_bits) + + def _insert_quant_abs_max_op(self, graph, var_node, name, quant_bits): + """ + Insert fake_quantize_abs_max op in the graph. + """ + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + quant_var_node = graph.create_var_node( + name=self._quantized_var_name(name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + scale_name = self._quantized_scale_name(name) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + try: + scale_value = np.array( + self._scope.find_var(scale_name).get_tensor()) + except: + scale_value = np.zeros([1], dtype=data_type) + scale_var_node = graph.create_persistable_node( + name=scale_name, + var_type=var_node.type(), + shape=[1], + var_dtype=var_node.dtype()) + _init_var_node(scale_var_node, scale_value, self._scope, self._place) + + quant_op_node = graph.create_op_node( + op_type='fake_quantize_abs_max', + attrs={ + 'bit_length': quant_bits, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={'X': var_node}, + outputs={ + 'Out': quant_var_node, + 'OutScale': scale_var_node + }) + graph.link_to(var_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + graph.link_to(quant_op_node, scale_var_node) + return quant_var_node, scale_var_node + + def _insert_quant_range_abs_max_op(self, graph, var_node, name, quant_bits): + """ + Insert fake_quantize_range_abs_max on the graph. + """ + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + quant_var_node = graph.create_var_node( + name=self._quantized_var_name(name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + + scale_name = self._quantized_scale_name(name) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + try: + scale_value = np.array( + self._scope.find_var(scale_name).get_tensor()) + except: + scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type) + scale_in_node = graph.create_persistable_node( + name=scale_name, + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[1], + var_dtype=var_node.dtype()) + _init_var_node(scale_in_node, scale_value, self._scope, self._place) + + scale_out_node = graph.create_var_node_from_desc(scale_in_node.var()) + inputs = {'X': var_node, 'InScale': scale_in_node} + outputs = {'Out': quant_var_node, 'OutScale': scale_out_node} + + if not self._is_test: + # The name of scales_var_node maybe 'scales_0', 'scales_1', etc. + scales_node = graph.create_persistable_node( + name=unique_name.generate('scales'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[self._window_size], + var_dtype=var_node.dtype()) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + _init_var_node(scales_node, + np.zeros([self._window_size], dtype=data_type), + self._scope, self._place) + + inputs['Iter'] = self._global_step + outputs['OutScales'] = scales_node + attrs = { + 'window_size': self._window_size, + 'bit_length': quant_bits, + 'is_test': self._is_test, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + } + quant_op_node = graph.create_op_node( + op_type='fake_quantize_range_abs_max', + attrs=attrs, + inputs=inputs, + outputs=outputs) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_in_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + graph.link_to(quant_op_node, scale_out_node) + + if not self._is_test: + graph.link_to(self._global_step, quant_op_node) + graph.link_to(quant_op_node, scales_node) + + return quant_var_node, scale_out_node + + def _insert_quant_moving_average_abs_max_op(self, graph, var_node, name, + quant_bits): + """Insert fake_quantize_moving_average_abs_max + """ + quant_var_node = graph.create_var_node( + name=self._quantized_var_name(name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + scale_name = self._quantized_scale_name(name) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + try: + scale_value = np.array( + self._scope.find_var(scale_name).get_tensor()) + except: + scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type) + scale_in_node = graph.create_persistable_node( + name=scale_name, + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[1], + var_dtype=var_node.dtype()) + _init_var_node(scale_in_node, scale_value, self._scope, self._place) + + scale_out_node = graph.create_var_node_from_desc(scale_in_node.var()) + ins = {'X': var_node, 'InScale': scale_in_node} + outs = {'Out': quant_var_node, 'OutScale': scale_out_node} + if not self._is_test: + state_in_node = graph.create_persistable_node( + name=unique_name.generate('state'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + _init_var_node(state_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + accum_in_node = graph.create_persistable_node( + name=unique_name.generate('accum'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + _init_var_node(accum_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + state_out_node = graph.create_var_node_from_desc( + state_in_node.var()) + accum_out_node = graph.create_var_node_from_desc( + accum_in_node.var()) + + ins['InState'] = state_in_node + ins['InAccum'] = accum_in_node + outs['OutState'] = state_out_node + outs['OutAccum'] = accum_out_node + + attrs = { + 'bit_length': quant_bits, + 'moving_rate': self._moving_rate, + 'is_test': self._is_test, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + } + + quant_op_node = graph.create_op_node( + op_type='fake_quantize_moving_average_abs_max', + attrs=attrs, + inputs=ins, + outputs=outs) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_in_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + graph.link_to(quant_op_node, scale_out_node) + + if not self._is_test: + graph.link_to(state_in_node, quant_op_node) + graph.link_to(accum_in_node, quant_op_node) + graph.link_to(quant_op_node, state_out_node) + graph.link_to(quant_op_node, accum_out_node) + + return quant_var_node, scale_out_node + + def _insert_channel_quant_op(self, graph, var_node, name, quant_bits, + quant_axis): + """ + Insert fake_channel_wise_quantize_abs_max op in the graph. + """ + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + quant_var_node = graph.create_var_node( + name=self._quantized_var_name(name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + scale_name = self._quantized_scale_name(name) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + try: + scale_value = np.array( + self._scope.find_var(scale_name).get_tensor()) + except: + scale_value = np.zeros([var_node.shape()[quant_axis]], + dtype=data_type) + scale_var_node = graph.create_persistable_node( + name=self._quantized_scale_name(name), + var_type=var_node.type(), + shape=[var_node.shape()[quant_axis]], + var_dtype=var_node.dtype()) + _init_var_node(scale_var_node, scale_value, self._scope, self._place) + quant_op_node = graph.create_op_node( + op_type='fake_channel_wise_quantize_abs_max', + attrs={ + 'bit_length': quant_bits, + 'quant_axis': quant_axis, + 'is_test': self._is_test, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={'X': var_node}, + outputs={ + 'Out': quant_var_node, + 'OutScale': scale_var_node + }) + graph.link_to(var_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + graph.link_to(quant_op_node, scale_var_node) + return quant_var_node, scale_var_node + + def _insert_dequant_op(self, graph, var_node, scale_var_node, quant_bits): + """ + Insert fake_dequantize_op in the graph. + """ + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + dequant_var_node = graph.create_var_node( + name=self._dequantized_var_name(var_node.name()), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + max_range = (1 << (quant_bits - 1)) - 1 + dequant_op_node = graph.create_op_node( + op_type='fake_dequantize_max_abs', + attrs={ + 'max_range': float(max_range), + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={ + 'X': var_node, + 'Scale': scale_var_node + }, + outputs={'Out': dequant_var_node}) + graph.link_to(var_node, dequant_op_node) + graph.link_to(scale_var_node, dequant_op_node) + graph.link_to(dequant_op_node, dequant_var_node) + return dequant_var_node + + def _insert_channel_dequant_op(self, graph, var_node, scale_var_nodes, + quant_bits, quant_axis): + """ + Insert fake_channel_wise_dequantize_max_abs in the graph. + """ + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + dequant_var_node = graph.create_var_node( + name=self._dequantized_var_name(var_node.name()), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + dequant_op_node = graph.create_op_node( + op_type='fake_channel_wise_dequantize_max_abs', + attrs={ + 'quant_bits': quant_bits, + 'quant_axis': quant_axis, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={ + 'X': var_node, + 'Scales': scale_var_nodes + }, + outputs={'Out': dequant_var_node}) + graph.link_to(var_node, dequant_op_node) + for scale_n in scale_var_nodes: + graph.link_to(scale_n, dequant_op_node) + graph.link_to(dequant_op_node, dequant_var_node) + return dequant_var_node + + def _create_new_node(self, graph, in_node): + """ + create a node that same with in_node in graph + Args: + graph(IrGraph): create node in graph. + in_node(IrVarNode): create node that same with in_node. + Returns: + created new node + """ + key = '' + for inp in in_node.inputs: + key = key + inp.name() + key = key + in_node.name() + for inp in in_node.outputs: + key = key + inp.name() + + if key in self.create_var_map.keys(): + new_node = self.create_var_map[key] + elif in_node.is_ctrl_var(): + new_node = graph.create_control_dep_var() + self.create_var_map[key] = new_node + else: + new_node = graph.create_var_node_from_desc(in_node.node.var()) + self.create_var_map[key] = new_node + return new_node + + def _copy_graph(self, graph, source_graph, op_node): + """ + copy op_node in source_graph to graph. And will run recursively + for next ops that link to op_node's outputs. + Args: + graph(IrGraph): target graph to copy. + source_graph(IrGraph): source graph to copy. + op_node(IrOpNode): op node in source_graph. + Returns: + None + + """ + key = '' + for inp in op_node.inputs: + key = key + inp.name() + key = key + op_node.name() + for inp in op_node.outputs: + key = key + inp.name() + has_created = False + if key in self.create_op_map.keys(): + new_op_node = self.create_op_map[key] + has_created = True + else: + new_op_node = graph.create_op_node_from_desc(op_node.node.op()) + self.create_op_map[key] = new_op_node + if has_created: + return + for in_node in op_node.inputs: + new_node = self._create_new_node(graph, in_node) + graph.link_to(new_node, new_op_node) + for in_node in op_node.outputs: + new_node = self._create_new_node(graph, in_node) + graph.link_to(new_op_node, new_node) + for var_node in op_node.outputs: + for next_op_node in var_node.outputs: + self._copy_graph(graph, source_graph, next_op_node) + return + + def _insert_func(self, graph, func, var_node, op): + """ + Insert a tmp program that returned by func between var_node and op. + + Args: + graph(IrGraph): target graph to insert tmp program. + func(Function): function to define a tmp program + var_node(IrVarNode): node in target graph. + op(IrOpNode): op in target graph. + Returns: + op's new input that replaces var_node + """ + tmp_program = Program() + startup_program = Program() + with program_guard(tmp_program, startup_program): + with unique_name.guard(var_node.name() + "_"): + in_node = data(var_node.name() + '_tmp_input', + shape=var_node.shape(), + dtype='float32') + out_node = func(in_node) + graph.out_node_mapping_table[out_node.name] = var_node.name() + # loss shape must be 1 when minimize + loss = mean(out_node) + if not graph._for_test: + assert self._optimizer, "optimizer_func must be set when graph is test graph" + in_node.stop_gradient = False + optimizer = self._optimizer() + optimizer.minimize(loss) + with scope_guard(self._scope): + self._exe.run(startup_program) + + tmp_graph = IrGraph(core.Graph(tmp_program.desc), + for_test=graph._for_test) + in_node = tmp_graph._find_node_by_name(tmp_graph.all_var_nodes(), + in_node.name) + out_node = tmp_graph._find_node_by_name(tmp_graph.all_var_nodes(), + out_node.name) + + in_node_params = [] + in_op_node = [] + # copy tmp graph to graph, after that, we can insert tmp graph's copy to graph. + for node in tmp_graph.all_var_nodes(): + if node.inputs == [] and node.persistable(): + in_node_params.append(node) + for node in tmp_graph.all_op_nodes(): + if node.inputs == []: + in_op_node.append(node) + for node in in_node.outputs: + self._copy_graph(graph, tmp_graph, node) + for node in in_node_params: + for op_node in node.outputs: + self._copy_graph(graph, tmp_graph, op_node) + for node in in_op_node: + self._copy_graph(graph, tmp_graph, node) + + target_in_node = graph._find_node_by_name(graph.all_var_nodes(), + in_node.name()) + target_out_node = graph._find_node_by_name(graph.all_var_nodes(), + out_node.name()) + loss_node = graph._find_node_by_name(graph.all_var_nodes(), loss.name) + outputs = target_in_node.outputs + for node in outputs: + graph.update_input_link(target_in_node, var_node, node) + graph.update_input_link(var_node, target_out_node, op) + + # update grad + if not graph._for_test: + op_out = op.outputs[0] + op_out_grad = graph._find_node_by_name(graph.all_var_nodes(), + op_out.name() + "@GRAD") + # find op's gradient op, such as conv2d_grad + op_grad = op_out_grad.outputs[0] + target_out_grad_node = graph._find_node_by_name( + graph.all_var_nodes(), + target_out_node.name() + "@GRAD") + in_node_grad = graph._find_node_by_name( + graph.all_var_nodes(), + target_in_node.name() + "@GRAD") + in_node_grad_op = in_node_grad.inputs + # update op_grad's input + graph.update_input_link(var_node, target_out_node, op_grad) + + op_grad_out = None + # find var_node's corresponding grad node + for node in op_grad.outputs: + if var_node.name() + "@GRAD" in node.name(): + op_grad_out = node + # update op_grad's output + if op_grad_out is not None: + graph.update_output_link(op_grad_out, target_out_grad_node, + op_grad) + else: + graph.link_to(op_grad, target_out_grad_node) + + for node in in_node_grad_op: + graph.update_input_link(target_in_node, var_node, node) + if op_grad_out: + graph.update_output_link(in_node_grad, op_grad_out, node) + # remove useless nodes + mean_grad = target_out_grad_node.inputs[0] + mean_out_grad = mean_grad.inputs[0] + fill_constant_node = mean_out_grad.inputs[0] + graph.safe_remove_nodes(mean_grad) + graph.safe_remove_nodes(mean_out_grad) + graph.safe_remove_nodes(fill_constant_node) + graph.safe_remove_nodes(in_node_grad) + + graph.safe_remove_nodes(loss_node.inputs[0]) + graph.safe_remove_nodes(loss_node) + graph.safe_remove_nodes(target_in_node) + return target_out_node + + def _quantized_var_name(self, var_name): + """ + Return quantized variable name for the input `var_name`. + """ + return "%s.quantized" % (var_name) + + def _dequantized_var_name(self, var_name): + """ + Return dequantized variable name for the input `var_name`. + """ + return "%s.dequantized" % (var_name) + + def _quantized_scale_name(self, var_name): + """ + Return the scale name of quantized variable for the input `var_name`. + """ + return "%s@scale" % (var_name) + + def _is_skip_quant(self, graph, op_node): + """ + Analyse whether the op node skips quantization. + """ + is_skip = False + if op_node.op().has_attr("skip_quant") and \ + op_node.op().attr("skip_quant"): + is_skip = True + # if the inputs of mul and matmul are not all persistable, use + # AddQuantDequantPass to quantize them. + if op_node.name() in ["mul", "matmul"] and \ + _is_input_all_not_persistable(graph, op_node): + is_skip = True + if op_node.op().has_attr("quantization_type") and \ + op_node.op().attr("quantization_type") == "qat_without_weight": + is_skip = True + return is_skip + + +class QuantizationFreezePass(object): + + def __init__(self, + scope, + place, + bias_correction=False, + weight_bits=8, + activation_bits=8, + round_type='round', + weight_quantize_type='abs_max', + quantizable_op_type=None): + """ + The freeze pass is used to adjust the quantize operator order, for example: + 1) `activation -> quant -> dequant -> conv2d` will be frozen into + `activation -> quant -> conv2d -> dequant` + 2) `weight -> quant -> dequant -> conv2d` will be frozen into `weight -> conv2d`, + and weight will be scaled offline. + + Args: + scope(fluid.Scope): scope is used to get the weight tensor values. + place(fluid.CPUPlace|fluid.CUDAPlace|str): place is used to restore the weight tensors. + If it's string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the index of the GPUs. + bias_correction(bool): whether use bias correction for post-training quantization. + https://arxiv.org/abs/1810.05723. + weight_bits(int): quantization bit number for weights. + activation_bits(int): quantization bit number for activation. + round_type(str, optional): The method of converting the quantized weights + value float->int. Currently supports ['round', 'adaround'] methods. + Default is `round`, which is rounding nearest to the integer. + 'adaround' is refer to https://arxiv.org/abs/2004.10568. + weight_quantize_type(str): quantization type for weights, support 'abs_max' and + 'channel_wise_abs_max'. The 'range_abs_max' usually is not used for weight, + since weights are fixed once the model is well trained. + quantizable_op_type(list[str]): This input param will be removed latter. The pass + will process all quantized op, so it is not necessary to set the input param. + """ + assert scope is not None, \ + 'The scope cannot be set None.' + assert place is not None, \ + 'The place cannot be set None.' + self._scope = scope + self._bias_correction = bias_correction + self._place = _get_paddle_place(place) + self._weight_bits = weight_bits + self._activation_bits = activation_bits + self._round_type = round_type + self._weight_quantize_type = weight_quantize_type + self._fake_quant_op_names = _fake_quant_op_list + self._fake_dequant_op_names = _fake_dequant_op_list + self._op_input_rename_map = collections.OrderedDict() + self._op_output_rename_map = collections.OrderedDict() + self._quant_var_scale_map = collections.OrderedDict() + + def apply(self, graph): + """ + Adjust quantize/dequantize operators order for the inference process. + + Args: + graph(IrGraph): the applied graph. + Returns: + None + """ + # Get input scales in fake quant op and process weights + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + ops = graph.all_op_nodes() + for op_node in ops: + op_name = op_node.name() + if op_name in self._fake_quant_op_names: + input_arg_name = op_node.input('X')[0] + if hasattr(graph, 'out_node_mapping_table'): + if input_arg_name in graph.out_node_mapping_table.keys(): + input_arg_name = graph.out_node_mapping_table[ + input_arg_name] + if input_arg_name not in persistable_vars: + scale_v = graph._find_node_by_name( + op_node.outputs, + op_node.output('OutScale')[0]) + self._quant_var_scale_map[input_arg_name] = scale_v + else: + # Obtain scale from OutScale var node + scale_v = self._load_var(op_node.output('OutScale')[0]) + assert scale_v.ndim in [ + 1, 2 + ], "the dim of scale_v should be 1 or 2" + if scale_v.ndim == 2: + scale_v = scale_v[0] + if scale_v.size == 1 and self._weight_quantize_type == 'abs_max': + scale_v = scale_v[0] + else: + scale_v = scale_v.tolist() + self._quant_var_scale_map[input_arg_name] = scale_v + # Quantize weight and restore + if self._round_type == 'round': + param_v = self._load_var(input_arg_name) + if any( + _check_grandchild_op_node(op_node, op) + for op in utils._channelwise_quant_axis1_ops): + quant_axis = 1 + else: + quant_axis = 0 + quantized_param_v = utils.quant_tensor( + param_v.copy(), scale_v, quant_axis, + self._weight_bits) + quantized_param_v = np.round(quantized_param_v) + # Weight bias correction + if self._bias_correction == True: + quantized_param_v = utils.bias_correction_w( + param_v, + quantized_param_v, + scale_v, + quant_axis, + weight_bits=self._weight_bits) + quantized_param_v = np.round(quantized_param_v) + self._restore_var(input_arg_name, quantized_param_v) + self._remove_fake_quant_and_dequant_op(graph, op_node) + + # Remove all fake dequant op + ops = graph.all_op_nodes() + for op_node in ops: + op_name = op_node.name() + if op_name in self._fake_dequant_op_names: + self._remove_fake_quant_and_dequant_op(graph, op_node) + + # Insert post dequant op + ops = graph.all_op_nodes() + for op_node in ops: + op_node_desc = op_node.op() + if op_node_desc.has_attr("quantization_type") and \ + op_node_desc.attr("quantization_type") == "qat_with_weight": + if self._weight_quantize_type == 'channel_wise_abs_max': + quant_axis = 1 if op_node.name() in \ + utils._channelwise_quant_axis1_ops else 0 + self._insert_post_channel_dequant_op( + graph, op_node, quant_axis) + else: + self._insert_post_dequant_op(graph, op_node) + + # Rename inputs of the followed ops after inserting dequant_op after fc/conv + for op_node in ops: + for var_node in op_node.inputs: + if var_node.node in self._op_output_rename_map: + old_in = var_node + new_in = self._op_output_rename_map[var_node.node] + graph.update_input_link(old_in, new_in, op_node) + + # remove the unused var node in the graph + self._remove_unused_var_nodes(graph) + graph.resolve_hazard() + return graph + + def _remove_fake_quant_and_dequant_op(self, graph, op_node): + k = graph._find_node_by_name(op_node.outputs, op_node.output('Out')[0]) + v = graph._find_node_by_name(op_node.inputs, op_node.input('X')[0]) + if v.node not in self._op_input_rename_map: + self._op_input_rename_map[k.node] = v + else: + self._op_input_rename_map[k.node] = self._op_input_rename_map[ + v.node] + graph.safe_remove_nodes(op_node) + + def _insert_post_channel_dequant_op(self, graph, op_node, quant_axis): + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + for var_node in op_node.inputs: + name = var_node.name() + if name not in op_node.input_arg_names(): + continue + if var_node.node in self._op_input_rename_map: + old_in = var_node + new_in = self._op_input_rename_map[var_node.node] + new_in.clear_outputs() + graph.update_input_link(old_in, new_in, op_node) + original_var_name = self._original_var_name(name) + scale_v = self._quant_var_scale_map[original_var_name] + if original_var_name in persistable_vars: + assert isinstance( + scale_v, + list), 'The scale of parameter %s is not a list.' % ( + original_var_name) + channel_scale = np.array(scale_v) + else: + assert isinstance(scale_v, IrNode) + scale_var_node = self._quant_var_scale_map[original_var_name] + + if len(op_node.output_arg_names()) != 1: + raise ValueError("Only support one output, but op %s has" + " more than one output." % (op_node.name())) + + output_var_node = graph._find_node_by_name( + op_node.outputs, + op_node.output_arg_names()[0]) + weight_scale_node = graph.create_persistable_node( + name=unique_name.generate('channel_scale'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[channel_scale.shape[0]], + var_dtype=output_var_node.dtype()) + data_type = 'float64' if output_var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + _init_var_node(weight_scale_node, channel_scale.astype(data_type), + self._scope, self._place) + dequant_var_node = graph.create_var_node( + name=self._dequantized_var_name(output_var_node.name()), + var_type=output_var_node.type(), + shape=output_var_node.shape(), + var_dtype=output_var_node.dtype()) + x_num_col_dims = 1 + if op_node.name() in ['matmul', 'matmul_v2', 'mul']: + x_num_col_dims = len(op_node.outputs[0].shape()) - 1 + if op_node.op().has_attr("x_num_col_dims"): + x_num_col_dims = op_node.op().attr("x_num_col_dims") + dequant_op_node = graph.create_op_node( + op_type='fake_channel_wise_dequantize_max_abs', + attrs={ + 'quant_bits': [self._weight_bits, self._activation_bits], + 'quant_axis': quant_axis, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward, + 'x_num_col_dims': x_num_col_dims + }, + inputs={ + 'X': output_var_node, + 'Scales': [weight_scale_node, scale_var_node] + }, + outputs={'Out': dequant_var_node}) + graph.link_to(output_var_node, dequant_op_node) + graph.link_to(scale_var_node, dequant_op_node) + graph.link_to(weight_scale_node, dequant_op_node) + graph.link_to(dequant_op_node, dequant_var_node) + self._op_output_rename_map[output_var_node.node] = dequant_var_node + return dequant_var_node + + def _insert_post_dequant_op(self, graph, op_node): + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + max_range = 1 + param_range = (1 << (self._weight_bits - 1)) - 1 + act_range = (1 << (self._activation_bits - 1)) - 1 + for var_node in op_node.inputs: + name = var_node.name() + if name not in op_node.input_arg_names(): + continue + if var_node.node in self._op_input_rename_map: + old_in = var_node + new_in = self._op_input_rename_map[var_node.node] + new_in.clear_outputs() + graph.update_input_link(old_in, new_in, op_node) + original_var_name = self._original_var_name(name) + scale_v = self._quant_var_scale_map[original_var_name] + if original_var_name in persistable_vars: + assert self._is_float( + scale_v), 'The scale of parameter %s is not a float.' % ( + original_var_name) + scale_v = 1e-8 if scale_v == 0.0 else scale_v + max_range *= param_range / scale_v + else: + max_range *= act_range + assert isinstance(scale_v, IrNode) + scale_var_node = self._quant_var_scale_map[original_var_name] + + if len(op_node.output_arg_names()) != 1: + raise ValueError("Only support one output, but op %s has" + " more than one output." % (op_node.name())) + + output_var_node = graph._find_node_by_name( + op_node.outputs, + op_node.output_arg_names()[0]) + dequant_var_node = graph.create_var_node( + name=self._dequantized_var_name(output_var_node.name()), + var_type=output_var_node.type(), + shape=output_var_node.shape(), + var_dtype=output_var_node.dtype()) + dequant_op_node = graph.create_op_node( + op_type='fake_dequantize_max_abs', + attrs={ + 'max_range': float(max_range), + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + }, + inputs={ + 'X': output_var_node, + 'Scale': scale_var_node + }, + outputs={'Out': dequant_var_node}) + graph.link_to(output_var_node, dequant_op_node) + graph.link_to(scale_var_node, dequant_op_node) + graph.link_to(dequant_op_node, dequant_var_node) + self._op_output_rename_map[output_var_node.node] = dequant_var_node + return dequant_var_node + + def _load_var(self, name): + return np.array(self._scope.find_var(name).get_tensor()) + + def _restore_var(self, name, array): + tensor = self._scope.find_var(name).get_tensor() + tensor.set(array, self._place) + + def _remove_unused_var_nodes(self, graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) + + def _original_var_name(self, var_name): + """ + Return the original variable name. + """ + if var_name.endswith('.quantized.dequantized'): + return var_name[:-len('.quantized.dequantized')] + if var_name.endswith('.quantized'): + return var_name[:-len('.quantized')] + if var_name.endswith('.dequantized'): + return var_name[:-len('.dequantized')] + if var_name.endswith('@scale'): + return var_name[:-len('@scale')] + else: + return var_name + + def _dequantized_var_name(self, var_name): + """ + Return dequantized variable name for the input `var_name`. + """ + return "%s.dequantized" % (var_name) + + def _is_float(self, v): + return isinstance(v, float) or isinstance(v, np.float32) \ + or isinstance(v, np.float64) + + +class ConvertToInt8Pass(object): + + def __init__(self, scope, place, quantizable_op_type=None): + """ + Convert the weights into int8_t type. + + Args: + scope(fluid.Scope): scope is used to get the weight tensor values. + place(fluid.CPUPlace|fluid.CUDAPlace|str): place is used to restore the + 8bits weight tensors. If it's string, It can be ``cpu``, and ``gpu:x``, + where ``x`` is the index of the GPUs. + quantizable_op_type(list[str]): This input param will be removed latter. The pass + will process all quantized op, so it is not necessary to set the input param. + """ + assert scope is not None, \ + 'The scope cannot be set None.' + assert place is not None, \ + 'The place cannot be set None.' + self._scope = scope + self._place = _get_paddle_place(place) + + def apply(self, graph): + """ + Convert weights' type of the graph. After that, the data type of the + graph weights is int8_t. + + Args: + graph(IrGraph): the applied graph. + Returns: + None + """ + persistable_vars = [p.name() for p in graph.all_persistable_nodes()] + ops = graph.all_op_nodes() + input_map = {} + for op_node in ops: + if op_node.op().has_attr("quantization_type") and \ + op_node.op().attr("quantization_type") == "qat_with_weight": + for var_node in op_node.inputs: + name = var_node.name() + if name in persistable_vars: + if name not in input_map: + int8_var_node = self._convert_to_int8( + graph, var_node) + input_map[name] = int8_var_node + graph.update_input_link(var_node, input_map[name], + op_node) + + # remove the unused var node in the graph + self._remove_unused_var_nodes(graph) + graph.resolve_hazard() + return graph + + def _convert_to_int8(self, graph, var_node): + int8_var_node_name = var_node.name() + ".int8" + int8_var_node = graph.create_persistable_node( + name=cpt.to_text(int8_var_node_name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=core.VarDesc.VarType.INT8) + array = self._load_var(var_node.name()) + self._scope.var(int8_var_node_name) + self._store_var(int8_var_node_name, array, np.int8) + return int8_var_node + + def _load_var(self, name): + return np.array(self._scope.find_var(name).get_tensor()) + + def _store_var(self, name, array, dtype): + tensor = self._scope.find_var(name).get_tensor() + tensor.set(array.astype(dtype), self._place) + + def _remove_unused_var_nodes(self, graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) + + +class TransformForMobilePass(object): + + def __init__(self): + """ + This pass is used to convert the frozen graph for paddle-mobile execution. + """ + self._fake_quant_op_names = _fake_quant_op_list + self._fake_dequant_op_names = _fake_dequant_op_list + + def apply(self, graph): + """ + Because paddle-mobile use `quantize` an `dequantize` as the names of + quantize operator and dequantize operator, the `apply` function just + realize this logic. + + Args: + graph(IrGraph): the graph will be transformed. + Returns: + None + """ + ops = graph.all_op_nodes() + for op_node in ops: + name = op_node.name() + if name in self._fake_quant_op_names: + op_node.set_type('quantize') + quant_node = graph.create_op_node_from_desc(op_node.op()) + for input_node in op_node.inputs: + graph.link_to(input_node, quant_node) + for output_node in op_node.outputs: + graph.link_to(quant_node, output_node) + graph.safe_remove_nodes(op_node) + if name in self._fake_dequant_op_names: + op_node.set_type('dequantize') + dequant_node = graph.create_op_node_from_desc(op_node.op()) + for input_node in op_node.inputs: + graph.link_to(input_node, dequant_node) + for output_node in op_node.outputs: + graph.link_to(dequant_node, output_node) + graph.safe_remove_nodes(op_node) + graph.resolve_hazard() + return graph + + +class OutScaleForTrainingPass(object): + + def __init__(self, + scope=None, + place=None, + moving_rate=0.9, + is_test=None, + scale_dict=None): + """ + This pass is used for calculating output scales of some operators. + These output scales may be used by tensorRT or some other inference engines. + + Args: + scope(fluid.Scope): The scope is used to initialize these new parameters. + place(fluid.CPUPlace|fluid.CUDAPlace|str): The place is used to initialize new parameters. + If it's string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the + index of the GPUs. + moving_rate(float): The decay coefficient of moving average. The default value is 0.9. + """ + self._scope = scope + self._place = _get_paddle_place(place) + self._moving_rate = moving_rate + self._is_test = is_test + self._teller_set = utils.QUANT_SUPPORTED_OP_TYPE_LIST + self._scale_dict = scale_dict + + def apply(self, graph): + """ + Insert the `moving_average_abs_max_scale` op in order to calculate output scales + of operators in the teller_set. + + Args: + graph(IrGraph): the target graph. + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + if self._is_test is None: + self._is_test = graph.is_test() + target_ops = [] + for op in graph.all_op_nodes(): + if op.name() in self._teller_set: + target_ops.append(op) + with tqdm(total=len(target_ops), + bar_format='Adding OutScale op:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for op in target_ops: + for output_var_name in utils._get_op_output_var_names(op): + in_node = graph._find_node_by_name(op.outputs, + output_var_name) + if in_node.dtype() not in \ + [core.VarDesc.VarType.FP64, core.VarDesc.VarType.FP32]: + continue + + data_type = 'float64' if in_node.dtype() \ + == core.VarDesc.VarType.FP64 else 'float32' + try: + graph._find_node_by_name( + graph.all_var_nodes(), + self._scale_name(in_node.name())) + continue + except: + scale_node = graph.create_persistable_node( + name=self._scale_name(in_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[1], + var_dtype=in_node.dtype()) + if self._scale_dict is not None: + try: + scale_value = np.array( + [self._scale_dict[in_node.name()]]) + except: + scale_value = np.ones([1], dtype=data_type) + else: + scale_value = np.ones([1], dtype=data_type) + _init_var_node(scale_node, scale_value, self._scope, + self._place) + + ins = {'X': in_node} + outs = {'OutScale': scale_node} + if not self._is_test: + state_in_node = graph.create_persistable_node( + name=unique_name.generate('scale_state@'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=in_node.dtype(), + shape=[1]) + _init_var_node(state_in_node, + np.ones([1], dtype=data_type), + self._scope, self._place) + accum_in_node = graph.create_persistable_node( + name=unique_name.generate('scale_accum@'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=in_node.dtype(), + shape=[1]) + _init_var_node(accum_in_node, + np.ones([1], dtype=data_type), + self._scope, self._place) + state_out_node = graph.create_var_node_from_desc( + state_in_node.var()) + accum_out_node = graph.create_var_node_from_desc( + accum_in_node.var()) + + ins['InState'] = state_in_node + ins['InAccum'] = accum_in_node + outs['OutState'] = state_out_node + outs['OutAccum'] = accum_out_node + + attrs = { + 'moving_rate': self._moving_rate, + 'is_test': self._is_test, + 'op_role': + core.op_proto_and_checker_maker.OpRole.Forward + } + scale_op_node = graph.create_op_node( + op_type='moving_average_abs_max_scale', + attrs=attrs, + inputs=ins, + outputs=outs) + graph.link_to(in_node, scale_op_node) + graph.link_to(scale_op_node, scale_node) + if not self._is_test: + graph.link_to(state_in_node, scale_op_node) + graph.link_to(accum_in_node, scale_op_node) + graph.link_to(scale_op_node, state_out_node) + graph.link_to(scale_op_node, accum_out_node) + t.update() + return graph + + def _scale_name(self, var_name): + """ + Return the scale name for the var named `var_name`. + """ + return "%s@scale" % (var_name) + + +class OutScaleForInferencePass(object): + + def __init__(self, scope=None): + """ + This pass is used for setting output scales of some operators. + These output scales may be used by tensorRT or some other inference engines. + + Args: + scope(fluid.Scope): The scope is used to initialize these new parameters. + """ + self._scope = scope + self._teller_set = utils.QUANT_SUPPORTED_OP_TYPE_LIST + + def apply(self, graph): + """ + Get output scales from the scope and set these scales in op_descs + of operators in the teller_set. + + Args: + graph(IrGraph): the target graph. + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + op_nodes = graph.all_op_nodes() + for op_node in op_nodes: + if op_node.name() in self._teller_set: + var_names = utils._get_op_output_var_names(op_node) + for var_name in var_names: + in_node = graph._find_node_by_name(op_node.outputs, + var_name) + if in_node.dtype() not in \ + [core.VarDesc.VarType.FP64, core.VarDesc.VarType.FP32]: + continue + + scale_name = self._scale_name(var_name) + scale_var = self._scope.find_var(scale_name) + assert scale_var is not None, \ + "Can not find {} variable in the scope".format(scale_name) + scale_value = np.array(scale_var.get_tensor())[0] + + # For compatibility, we save output threshold by two methods. + op_node.op()._set_attr("out_threshold", float(scale_value)) + + argname_index = utils._get_output_name_index( + op_node, var_name) + assert argname_index is not None, \ + var_name + " is not the output of the op" + op_node.op()._set_attr(argname_index[0] + str(argname_index[1]) \ + + "_threshold", float(scale_value)) + op_node.op()._set_attr("with_quant_attr", True) + graph.resolve_hazard() + return graph + + def _scale_name(self, var_name): + """ + Return the scale name for the var named `var_name`. + """ + return "%s@scale" % (var_name) + + +class AddQuantDequantPass(object): + """ + Quantize the ops that do not have weights, and add quant_dequant op for the + quantized ops's inputs. + """ + + # To be compatible with PaddleSlim, not remove _activation_type for now + _activation_type = ["relu", "relu6", "leaky_relu", "tanh", "swish"] + + def __init__(self, + scope=None, + place=None, + moving_rate=0.9, + quant_bits=8, + skip_pattern=["skip_quant"], + quantizable_op_type=["elementwise_add", "pool2d"], + is_full_quantized=False, + is_test=None, + scale_dict=None): + """ + Constructor. + + Args: + scope(fluid.Scope): The scope is used to initialize these new parameters. + place(fluid.CPUPlace|fluid.CUDAPlace|str): place is used to initialize new + parameters described above. If ``place`` is string, it can be It can be ``cpu`` + or ``gpu:x``, where ``x`` is the index of the GPUs. + moving_rate(float, optional): the param for 'quant_dequant_moving_average_abs_max' + quantization. Default is 0.9. + quant_bits(int, optional): quantization bit number for activation. Default is 8. + skip_pattern(str, optional): The user-defined quantization skip pattern, which + will be presented in the name scope of an op. When the skip pattern is + detected in an op's name scope, the corresponding op will not be quantized. + Default is 'skip_quant'. + quantizable_op_type(list[str], optional): List the type of ops that will be + quantized. Default is ["elementwise_add", "pool2d"]. + is_full_quantized(bool, optional): If set is_full_quantized as True, apply + quantization to all supported quantizable op type. If set is_full_quantized + as False, only apply quantization to the op type according to the input + quantizable_op_type. + """ + self._scope = scope + self._place = _get_paddle_place(place) + self._moving_rate = moving_rate + self._quant_bits = quant_bits + self._is_test = is_test + self._skip_pattern = skip_pattern + self._scale_dict = scale_dict + + if is_full_quantized: + self._quantizable_op_type = utils._act_supported_quantizable_op_type + else: + self._quantizable_op_type = quantizable_op_type + for op_type in quantizable_op_type: + assert op_type in utils._act_supported_quantizable_op_type, \ + op_type + " is not supported for quantization." + self._quantizable_grad_op_type = [ + '%s_grad' % (op) for op in self._quantizable_op_type + ] + + assert self._scope != None, "scope must not be None." + assert self._place != None, "place must not be None." + + def apply(self, graph): + """ + Add quant_dequant before some ops, such as the 'elementwise_add' and + 'pool2d' op. + + Args: + graph(IrGraph): the target graph. + Returns: + None + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + if self._is_test is None: + self._is_test = graph.is_test() + dequantized_vars_map = collections.OrderedDict() + + # Forward stage, insert quant_dequant op + all_op_nodes = graph.all_op_nodes() + with tqdm(total=len(all_op_nodes), + bar_format= + 'Adding quant activation op:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for op_node in all_op_nodes: + if op_node.name() in self._quantizable_op_type: + is_skip = False + if isinstance(self._skip_pattern, list): + is_skip = op_node.op().has_attr("op_namescope") and \ + any(pattern in op_node.op().attr("op_namescope") for pattern in self._skip_pattern) + elif isinstance(self._skip_pattern, str): + is_skip = op_node.op().has_attr("op_namescope") and \ + op_node.op().attr("op_namescope").find(self._skip_pattern) != -1 + is_quantized = op_node.op().has_attr("quantization_type") and \ + op_node.op().attr("quantization_type") == "qat_with_weight" + if is_skip or is_quantized or \ + (not _is_input_all_not_persistable(graph, op_node)): + continue + + op_node.op()._set_attr("quantization_type", + "qat_without_weight") + op_node.op()._set_attr("activation_bits", self._quant_bits) + op_node.op()._set_attr("with_quant_attr", True) + arg_names = utils._get_op_input_var_names(op_node) + for arg_name in arg_names: + in_node = graph._find_node_by_name( + op_node.inputs, arg_name) + if arg_name in dequantized_vars_map: + quant_var_node = dequantized_vars_map[arg_name] + else: + quant_var_node, _ = \ + self._inser_quant_dequant_moving_average_abs_max_op( + graph, in_node, self._quant_bits) + dequantized_vars_map[arg_name] = quant_var_node + graph.update_input_link(in_node, quant_var_node, + op_node) + t.update() + + # Backward stage, update input link + for op_node in all_op_nodes: + if op_node.name() in self._quantizable_grad_op_type: + for input_name in op_node.input_arg_names(): + if input_name in dequantized_vars_map: + in_node = graph._find_node_by_name( + op_node.inputs, input_name) + dequant_var_node = dequantized_vars_map[input_name] + graph.update_input_link(in_node, dequant_var_node, + op_node) + + graph.resolve_hazard() + return graph + + def _inser_quant_dequant_moving_average_abs_max_op(self, graph, var_node, + quant_bits): + """Insert fake_quantize_dequantize_moving_average_abs_max op. + """ + quant_var_node = graph.create_var_node(name="{}.quant_dequant".format( + var_node.name()), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + scale_name = "{}.quant_dequant@scale".format(var_node.name()) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + try: + if self._scale_dict is not None and var_node.name( + ) in self._scale_dict.keys(): + scale_value = np.array([self._scale_dict[var_node.name()]], + dtype=data_type) + else: + scale_value = np.array( + self._scope.find_var(scale_name).get_tensor(), + dtype=data_type) + except: + scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type) + + scale_in_node = graph.create_persistable_node( + name="{}.quant_dequant@scale".format(var_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=[1], + var_dtype=var_node.dtype()) + + _init_var_node(scale_in_node, scale_value, self._scope, self._place) + scale_out_node = graph.create_var_node_from_desc(scale_in_node.var()) + ins = {'X': var_node, 'InScale': scale_in_node} + outs = {'Out': quant_var_node, 'OutScale': scale_out_node} + if not self._is_test: + state_in_node = graph.create_persistable_node( + name=unique_name.generate('quant_dequant.state'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + _init_var_node(state_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + accum_in_node = graph.create_persistable_node( + name=unique_name.generate('quant_dequant.accum'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + _init_var_node(accum_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + state_out_node = graph.create_var_node_from_desc( + state_in_node.var()) + accum_out_node = graph.create_var_node_from_desc( + accum_in_node.var()) + + ins['InState'] = state_in_node + ins['InAccum'] = accum_in_node + outs['OutState'] = state_out_node + outs['OutAccum'] = accum_out_node + + attrs = { + 'bit_length': quant_bits, + 'moving_rate': self._moving_rate, + 'is_test': self._is_test, + 'op_role': core.op_proto_and_checker_maker.OpRole.Forward + } + + quant_op_node = graph.create_op_node( + op_type='fake_quantize_dequantize_moving_average_abs_max', + attrs=attrs, + inputs=ins, + outputs=outs) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_in_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + graph.link_to(quant_op_node, scale_out_node) + + if not self._is_test: + graph.link_to(state_in_node, quant_op_node) + graph.link_to(accum_in_node, quant_op_node) + graph.link_to(quant_op_node, state_out_node) + graph.link_to(quant_op_node, accum_out_node) + + return quant_var_node, scale_out_node + + +class InsertQuantizeLinear(object): + """ + Insert quantize_linear and dequantize_linear op before ops. + + Args: + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to restore the weight tensors. + If it's string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the index of the GPUs. + scope(paddle.Scope): scope is used to get the weight tensor values. + quant_bits(int, optional): quantization bit number for weight. Default is 8. + quant_axis(int, optional): quantization dimension of channels. When it is greater than or + equal to 0, it will quantization with per channel, else quantization with per layer. + Default is -1. + channel_wise(bool, optional): Whether quantization with per channel or not. Default is False. + moving_rate(float): the rate for 'moving average' method. + is_test(bool, optional): Whether quantization with training or not. Default is True. + scale_dict(dict, optional): calibration ranges of tensors output. + """ + + def __init__(self, + place, + scope, + quant_bits=8, + quant_axis=-1, + channel_wise=False, + moving_rate=0.9, + is_test=True, + scale_dict=None): + self._place = place + self._scope = scope + self.quant_bits = quant_bits + self.quant_axis = quant_axis + self.channel_wise = channel_wise + self._is_test = is_test + self._moving_rate = moving_rate + self._scale_dict = scale_dict + + def insert_quant_op(self, graph, var_node, var_name=None): + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + var_name = var_node.name() if not var_name else var_name + quant_var_node = graph.create_var_node( + name=self._quantized_var_name(var_name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + scale_name = self._quantized_scale_name(var_name) + if self.channel_wise: + scale_var_shape = var_node.shape()[self.quant_axis] + scale_var_type = core.VarDesc.VarType.LOD_TENSOR + init_scale_value = np.ones(scale_var_shape, + dtype=data_type) * _SCALE_DEFAULT_VALUE + else: + scale_var_shape = 1 + scale_var_type = var_node.type() + init_scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type) + + if self._scale_dict is not None and var_node.name( + ) in self._scale_dict.keys(): + init_scale_value = np.array([self._scale_dict[var_node.name()]], + dtype=data_type) + + scale_var_node = graph.create_persistable_node( + name=scale_name, + var_type=scale_var_type, + shape=[scale_var_shape], + var_dtype=var_node.dtype()) + _init_var_node(scale_var_node, init_scale_value, self._scope, + self._place) + + zero_point_node = None + if zero_point_node is None: + zero_point_node = graph.create_persistable_node( + name=self._zero_point_name(quant_var_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=scale_var_node.shape(), + var_dtype=core.VarDesc.VarType.INT32) + _init_var_node(zero_point_node, + np.zeros(scale_var_node.shape(), dtype="int32"), + self._scope, self._place) + + inputs = {"X": var_node, "Scale": scale_var_node} + if zero_point_node is not None: + inputs["ZeroPoint"] = zero_point_node + + attrs = {"quant_axis": self.quant_axis, "bit_length": self.quant_bits} + attrs["op_role"] = core.op_proto_and_checker_maker.OpRole.Forward + outputs = {"Y": quant_var_node} + if not self._is_test: + scale_out_node = graph.create_var_node_from_desc( + scale_var_node.var()) + state_in_node = graph.create_persistable_node( + name=unique_name.generate('state'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + data_type = 'float64' if var_node.dtype( + ) == core.VarDesc.VarType.FP64 else 'float32' + _init_var_node(state_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + accum_in_node = graph.create_persistable_node( + name=unique_name.generate('accum'), + var_type=core.VarDesc.VarType.LOD_TENSOR, + var_dtype=var_node.dtype(), + shape=[1]) + _init_var_node(accum_in_node, np.ones([1], dtype=data_type), + self._scope, self._place) + state_out_node = graph.create_var_node_from_desc( + state_in_node.var()) + accum_out_node = graph.create_var_node_from_desc( + accum_in_node.var()) + + outputs["OutScale"] = scale_out_node + inputs['InState'] = state_in_node + inputs['InAccum'] = accum_in_node + outputs['OutState'] = state_out_node + outputs['OutAccum'] = accum_out_node + attrs["is_test"] = self._is_test + attrs['moving_rate'] = self._moving_rate + + quant_op_node = graph.create_op_node(op_type="quantize_linear", + attrs=attrs, + inputs=inputs, + outputs=outputs) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_var_node, quant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + if not self._is_test: + graph.link_to(state_in_node, quant_op_node) + graph.link_to(accum_in_node, quant_op_node) + graph.link_to(quant_op_node, state_out_node) + graph.link_to(quant_op_node, accum_out_node) + graph.link_to(quant_op_node, scale_out_node) + return quant_var_node, scale_var_node + + def insert_dequant_op(self, graph, var_node, scale_var_node): + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + + dequant_var_node = graph.create_var_node( + name=self._dequantized_var_name(var_node.name()), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + + zero_point_node = None + if zero_point_node is None: + zero_point_node = graph.create_persistable_node( + name=self._zero_point_name(dequant_var_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=scale_var_node.shape(), + var_dtype=core.VarDesc.VarType.INT32) + _init_var_node(zero_point_node, + np.zeros(scale_var_node.shape(), dtype="int32"), + self._scope, self._place) + + inputs = {"X": var_node, "Scale": scale_var_node} + if zero_point_node is not None: + inputs["ZeroPoint"] = zero_point_node + + attrs = {"quant_axis": self.quant_axis, "bit_length": self.quant_bits} + attrs["op_role"] = core.op_proto_and_checker_maker.OpRole.Forward + + quant_op_node = graph.create_op_node(op_type="dequantize_linear", + attrs=attrs, + inputs=inputs, + outputs={"Y": dequant_var_node}) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_var_node, quant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, quant_op_node) + graph.link_to(quant_op_node, dequant_var_node) + return dequant_var_node + + def _quantized_var_name(self, var_name): + """ + Return quantized variable name for the input `var_name`. + """ + return "%s.quantized" % (var_name) + + def _dequantized_var_name(self, var_name): + """ + Return dequantized variable name for the input `var_name`. + """ + return "%s.dequantized" % (var_name) + + def _quantized_scale_name(self, var_name): + """ + Return the scale name of quantized variable for the input `var_name`. + """ + return "%s@scale" % (var_name) + + def _zero_point_name(self, var_name): + """ + Return the scale name for the var named `var_name`. + """ + return "%s@zero_point" % (var_name) + + +class QuantizationTransformPassV2(QuantizationTransformPass): + """ + Quantize the ops that have weights. Add quant and dequant ops for + the quantized ops's inputs. It is used in the new format of quantization. + """ + + def __init__(self, + scope=None, + place=None, + weight_bits=8, + activation_bits=8, + activation_quantize_type='abs_max', + weight_quantize_type='abs_max', + window_size=10000, + moving_rate=0.9, + skip_pattern=['skip_quant'], + quantizable_op_type=['conv2d', 'depthwise_conv2d', 'mul'], + weight_quantize_func=None, + act_quantize_func=None, + weight_preprocess_func=None, + act_preprocess_func=None, + optimizer_func=None, + executor=None, + is_test=None): + r""" + Args: + scope(paddle.Scope): When activation use 'range_abs_max' as the quantize + type, this pass will create some new parameters. The scope is used to + initialize these new parameters. + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to initialize new + parameters described above. If it's string, It can be ``cpu``, and ``gpu:x``, + where ``x`` is the index of the GPUs. + weight_bits(int): quantization bit number for weights, + the bias is not quantized. + activation_bits(int): quantization bit number for activation. + activation_quantize_type(str): quantization type for activation, + now support 'abs_max', 'range_abs_max' and 'moving_average_abs_max'. + If use 'abs_max' mode, the quantization scale will be calculated + dynamically each step in both training and testing period. If use + 'range_abs_max', a static quantization scale will be calculated + during training and used in inference. + weight_quantize_type(str): quantization type for weights, + support 'abs_max' and 'channel_wise_abs_max'. The 'range_abs_max' + usually is not used for weight, since weights are fixed once the + model is well trained. + window_size(int): the window size for 'range_abs_max' quantization. + moving_rate(float): the param for 'moving_average_abs_max' quantization. + skip_pattern(str or str list): The user-defined quantization skip pattern, which + will be presented in the name scope of an op. When the skip pattern is + detected in an op's name scope, the corresponding op will not be quantized. + quantizable_op_type(list[str]): List the type of ops that will be quantized. + Default is ["conv2d", "depthwise_conv2d", "mul"]. The quantizable_op_type in + QuantizationFreezePass and ConvertToInt8Pass must be the same as this. + weight_quantize_func(function): Function that defines how to quantize weight. + Using this can quickly test if user's quantization method works or not. + In this function, user should both define quantization function and + dequantization function, that is, the function's input is non-quantized + weight and function returns dequantized weight. If None, will use + quantization op defined by 'weight_quantize_type'. Default is None. + act_quantize_func(function): Function that defines how to quantize activation. + Using this can quickly test if user's quantization method works or not. + In this function, user should both define quantization and dequantization + process, that is, the function's input is non-quantized activation and + function returns dequantized activation. If None, will use quantization + op defined by 'activation_quantize_type'. Default is None. + weight_preprocess_func(function): Function that defines how to preprocess + weight before quantization. Using this can quickly test if user's preprocess + method works or not. The function's input is non-quantized weight and + function returns processed weight to be quantized. If None, the weight will + be quantized directly. Default is None. + act_preprocess_func(function): Function that defines how to preprocess + activation before quantization. Using this can quickly test if user's + preprocess method works or not. The function's input is non-quantized + activation and function returns processed activation to be quantized. + If None, the activation will be quantized directly. Default is None. + optimizer_func(function): Fuction return a optimizer. When 'is_test' is + False and user want to use self-defined quantization function and + preprocess function, this function must be set. Default is None. + executor(paddle.Executor): If user want to use self-defined quantization + function and preprocess function, executor must be set for initialization. + Default is None. + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle + from paddle.fluid.contrib.slim.quantization \ + import QuantizationTransformPassV2 + from paddle.fluid.contrib.slim.graph import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(program.desc), for_test=False) + place = paddle.CPUPlace() + scope = paddle.static.global_scope() + transform_pass = QuantizationTransformPassV2(scope, place) + transform_pass.apply(graph) + """ + self._scope = scope + self._place = _get_paddle_place(place) + self._weight_bits = weight_bits + self._activation_bits = activation_bits + self._skip_pattern = skip_pattern + self._weight_quantize_func = weight_quantize_func + self._act_quantize_func = act_quantize_func + self._weight_preprocess_func = weight_preprocess_func + self._act_preprocess_func = act_preprocess_func + self._optimizer = optimizer_func + self._exe = executor + quant_type = [ + 'abs_max', 'channel_wise_abs_max', 'range_abs_max', + 'moving_average_abs_max' + ] + assert activation_quantize_type != 'channel_wise_abs_max', \ + "The activation quantization type does not support 'channel_wise_abs_max'." + if activation_quantize_type not in quant_type: + raise ValueError( + "Unknown activation_quantize_type : '%s'. It can only be " + "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'." % + (str(activation_quantize_type))) + if weight_quantize_type not in quant_type: + raise ValueError( + "Unknown weight_quantize_type: '%s'. It can only be " + "'abs_max' or 'channel_wise_abs_max' or 'range_abs_max' " + "or 'moving_average_abs_max'." % (str(weight_quantize_type))) + + self._activation_quantize_type = activation_quantize_type + self._weight_quantize_type = weight_quantize_type + self._window_size = window_size + self._moving_rate = moving_rate + + self._quantizable_ops = quantizable_op_type + for op in self._quantizable_ops: + assert op in utils._weight_supported_quantizable_op_type, \ + op + " is not supported for quantization." + self._quantizable_grad_ops = [ + '%s_grad' % (op) for op in self._quantizable_ops + ] + self._is_test = is_test + self._global_step = None + + self.create_var_map = {} + self.create_op_map = {} + + # marked the variable which has been dequantized. + self.dequantized_vars = collections.OrderedDict() + self.persistable_vars = [] + self.processed_vars = [] + + def _quant_preprocess(self, op_node): + user_skipped = False + if isinstance(self._skip_pattern, list): + user_skipped = op_node.op().has_attr("op_namescope") and \ + any(pattern in op_node.op().attr("op_namescope") \ + for pattern in self._skip_pattern) + elif isinstance(self._skip_pattern, str): + user_skipped = op_node.op().has_attr("op_namescope") and \ + op_node.op().attr("op_namescope").find( + self._skip_pattern) != -1 + + if user_skipped: + op_node.op()._set_attr("skip_quant", True) + op_node.op()._set_attr("with_quant_attr", True) + + def _transform_forward(self, graph, op): + op.op()._set_attr("quantization_type", "qat_with_weight") + inputs = op.inputs + for var_node in inputs: + if var_node.name() not in op.input_arg_names(): + continue + if var_node.name() in self.dequantized_vars: + dequant_var_node = self.dequantized_vars[var_node.name()] + else: + name = var_node.name() + if name in self.processed_vars: + continue + is_weight = True if var_node.name() in self.persistable_vars \ + else False + + # if var node is weight and weight_preprocess_func is not None, + # will insert weight preprocess func + # to preorocess weight before quantization + # if var node is activation and act_preprocess_func is not None, + # will insert activation preprocess func + # to preorocess activation before quantization + if is_weight and self._weight_preprocess_func is not None: + var_node = self._insert_func(graph, + self._weight_preprocess_func, + var_node, op) + elif not is_weight and self._act_preprocess_func is not None: + var_node = self._insert_func(graph, + self._act_preprocess_func, + var_node, op) + + # if var node is weight and weight_quantize_func is not None, + # will insert weight quantize func to quantize and dequantize weight + # if var node is activation and act_quantize_func is not None, + # will insert act quantize func to quantize and dequantize activation + if is_weight and self._weight_quantize_func is not None: + target_out_node = self._insert_func( + graph, self._weight_quantize_func, var_node, op) + self.processed_vars.append(name) + continue + elif not is_weight and self._act_quantize_func is not None: + target_out_node = self._insert_func(graph, + self._act_quantize_func, + var_node, op) + self.processed_vars.append(name) + continue + + quant_bits = self._weight_bits if var_node.name() in self.persistable_vars \ + else self._activation_bits + quant_type = self._weight_quantize_type if is_weight \ + else self._activation_quantize_type + quant_axis = -1 + channel_wise = False + if quant_type == 'channel_wise_abs_max': # Weight quantization + channel_wise = True + quant_axis = 1 if op.name() in \ + utils._channelwise_quant_axis1_ops else 0 + insert_quant_pass = InsertQuantizeLinear( + self._place, + self._scope, + quant_bits=quant_bits, + quant_axis=quant_axis, + channel_wise=channel_wise, + moving_rate=self._moving_rate, + is_test=self._is_test) + quant_var_node, scale_var_node = insert_quant_pass.insert_quant_op( + graph, var_node, var_name=name) + dequant_var_node = insert_quant_pass.insert_dequant_op( + graph, quant_var_node, scale_var_node) + + self.dequantized_vars[name] = dequant_var_node + graph.update_input_link(var_node, dequant_var_node, op) + + def _transform_backward(self, graph, op): + for var_node in op.inputs: + if var_node.name() not in op.input_arg_names(): + continue + if var_node.name() in self.dequantized_vars: + dequant_var_node = self.dequantized_vars[var_node.name()] + graph.update_input_link(var_node, dequant_var_node, op) + + def _has_weight(self, op): + has_weight = False + for var_node in op.inputs: + if var_node.name() not in op.input_arg_names(): + continue + name = var_node.name() + if var_node.name() in self.persistable_vars: + has_weight = True + return has_weight + + def apply(self, graph): + """ + Quantize the graph for training process. According to weight and + activation quantization type, the graph will be added some fake + quantize operators and fake dequantize operators. + + Args: + graph(IrGraph): the applied graph. + Returns: + None + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + if self._is_test is None: + self._is_test = graph.is_test() + + self.persistable_vars = [ + p.name() for p in graph.all_persistable_nodes() + ] + + ops = graph.all_op_nodes() + # Do the preproccess of quantization, such as skipping some ops + # for not being quantized. + for op in ops: + if op.name() in self._quantizable_ops or \ + op.name() in self._quantizable_grad_ops: + self._quant_preprocess(op) + # Insert mapping table to solve the problem in saving inference model. + graph.out_node_mapping_table = dict() + # The process of _transform_forward and _transform_backward is needed in two for loops. + # The loop for transforming the forward graph: + with tqdm(total=len(ops), + bar_format= + 'Adding quant op with weight:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for op in ops: + if op.name() in self._quantizable_ops: + if not self._is_skip_quant(graph, + op) and self._has_weight(op): + self._transform_forward(graph, op) + t.update() + # The loop for renaming the inputs of backward op. + for op in ops: + if op.name() in self._quantizable_grad_ops and self._has_weight(op): + self._transform_backward(graph, op) + return graph + + +class AddQuantDequantPassV2(object): + """ + Quantize the ops that do not have weights, and add quant_linear and dequant_linear + op for the quantized ops's inputs. It is used in the new format of quantization. + """ + + # To be compatible with PaddleSlim, not remove _activation_type for now + _activation_type = ["relu", "relu6", "leaky_relu", "tanh", "swish"] + + def __init__(self, + scope=None, + place=None, + moving_rate=0.9, + quant_bits=8, + skip_pattern=["skip_quant"], + quantizable_op_type=["elementwise_add", "pool2d"], + is_full_quantized=False, + is_test=None, + scale_dict=None): + """ + Args: + scope(paddle.Scope): The scope is used to initialize these new parameters. + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to initialize new + parameters described above. If ``place`` is string, it can be It can be ``cpu`` + or ``gpu:x``, where ``x`` is the index of the GPUs. + moving_rate(float, optional): the param for 'quant_dequant_moving_average_abs_max' + quantization. Default is 0.9. + quant_bits(int, optional): quantization bit number for activation. Default is 8. + skip_pattern(str, optional): The user-defined quantization skip pattern, which + will be presented in the name scope of an op. When the skip pattern is + detected in an op's name scope, the corresponding op will not be quantized. + Default is 'skip_quant'. + quantizable_op_type(list[str], optional): List the type of ops that will be + quantized. Default is ["elementwise_add", "pool2d"]. + is_full_quantized(bool, optional): If set is_full_quantized as True, apply + quantization to all supported quantizable op type. If set is_full_quantized + as False, only apply quantization to the op type according to the input + quantizable_op_type. + scale_dict(dict, optional): calibration ranges of tensors output. + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle + from paddle.fluid.contrib.slim.quantization \ + import AddQuantDequantPassV2 + from paddle.fluid.contrib.slim.graph import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(program.desc), for_test=False) + place = paddle.CPUPlace() + scope = paddle.static.global_scope() + add_quant_dequant_pass = AddQuantDequantPassV2(scope, place) + add_quant_dequant_pass.apply(graph) + """ + self._scope = scope + self._place = _get_paddle_place(place) + self._moving_rate = moving_rate + self._quant_bits = quant_bits + self._is_test = is_test + self._skip_pattern = skip_pattern + self._scale_dict = scale_dict + + if is_full_quantized: + self._quantizable_op_type = utils._act_supported_quantizable_op_type + else: + self._quantizable_op_type = quantizable_op_type + for op_type in quantizable_op_type: + assert op_type in utils._act_supported_quantizable_op_type, \ + op_type + " is not supported for quantization." + self._quantizable_grad_op_type = [ + '%s_grad' % (op) for op in self._quantizable_op_type + ] + + assert self._scope != None, "scope must not be None." + assert self._place != None, "place must not be None." + self.persistable_vars = [] + + def apply(self, graph): + """ + Add quant_dequant before some ops, such as the 'elementwise_add' and + 'pool2d' op. + + Args: + graph(IrGraph): the target graph. + Returns: + None + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + if self._is_test is None: + self._is_test = graph.is_test() + dequantized_vars_map = collections.OrderedDict() + + self.persistable_vars = [ + p.name() for p in graph.all_persistable_nodes() + ] + + # Forward stage, insert quant_dequant op + all_op_nodes = graph.all_op_nodes() + with tqdm(total=len(all_op_nodes), + bar_format= + 'Adding quant activation op:|{bar}| {n_fmt}/{total_fmt}', + ncols=80) as t: + for op_node in all_op_nodes: + if op_node.name() in self._quantizable_op_type: + is_skip = False + if isinstance(self._skip_pattern, list): + is_skip = op_node.op().has_attr("op_namescope") and \ + any(pattern in op_node.op().attr("op_namescope") for pattern in self._skip_pattern) + elif isinstance(self._skip_pattern, str): + is_skip = op_node.op().has_attr("op_namescope") and \ + op_node.op().attr("op_namescope").find(self._skip_pattern) != -1 + is_quantized = op_node.op().has_attr("quantization_type") and \ + op_node.op().attr("quantization_type") == "qat_with_weight" + if is_skip or is_quantized: + continue + + arg_names = utils._get_op_input_var_names(op_node) + for arg_name in arg_names: + in_node = graph._find_node_by_name( + op_node.inputs, arg_name) + if in_node.persistable(): + continue + if arg_name in dequantized_vars_map: + dequant_var_node = dequantized_vars_map[arg_name] + else: + insert_quant_pass = InsertQuantizeLinear( + self._place, + self._scope, + quant_bits=self._quant_bits, + quant_axis=-1, + channel_wise=False, + moving_rate=self._moving_rate, + is_test=self._is_test, + scale_dict=self._scale_dict) + quant_var_node, scale_var_node = insert_quant_pass.insert_quant_op( + graph, in_node) + dequant_var_node = insert_quant_pass.insert_dequant_op( + graph, quant_var_node, scale_var_node) + dequantized_vars_map[arg_name] = dequant_var_node + graph.update_input_link(in_node, dequant_var_node, + op_node) + t.update() + + # Backward stage, update input link + for op_node in all_op_nodes: + if op_node.name() in self._quantizable_grad_op_type: + for input_name in op_node.input_arg_names(): + if input_name in dequantized_vars_map: + in_node = graph._find_node_by_name( + op_node.inputs, input_name) + dequant_var_node = dequantized_vars_map[input_name] + graph.update_input_link(in_node, dequant_var_node, + op_node) + + return graph + + +class ReplaceFakeQuantDequantPass(object): + """ + replace quant-dequant ops with quantize_linear and dequantize_linear ops. + """ + + def __init__(self, scope, place, quant_bits=8): + r""" + Args: + scope(paddle.Scope): The scope is used to initialize these new parameters. + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to initialize new + parameters described above. If ``place`` is string, it can be It can be ``cpu`` + or ``gpu:x``, where ``x`` is the index of the GPUs. + quant_bits(int, optional): quantization bit number for activation. Default is 8. + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle + from paddle.fluid.contrib.slim.quantization \ + import ReplaceFakeQuantDequantPass + from paddle.fluid.contrib.slim.graph import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(program.desc), for_test=False) + place = paddle.CPUPlace() + scope = paddle.static.global_scope() + replace_pass = ReplaceFakeQuantDequantPass(scope, place) + replace_pass.apply(graph) + """ + self._place = _get_paddle_place(place) + self._scope = scope + self._quant_bits = quant_bits + assert self._scope != None, "scope must not be None." + assert self._place != None, "place must not be None." + + def apply(self, graph): + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + fake_quant_dequant_ops = [] + + for op in graph.all_op_nodes(): + if op.name() in _fake_quant_dequant_op_list or op.name( + ) == "moving_average_abs_max_scale": + fake_quant_dequant_ops.append(op) + + for _op in fake_quant_dequant_ops: + self._replace_op(graph, _op) + graph.safe_remove_nodes(_op) + + graph.resolve_hazard() + return graph + + def _replace_op(self, graph, op): + x_node = graph._find_node_by_name(op.inputs, op.input("X")[0]) + out_node = graph._find_node_by_name(op.outputs, op.output("Out")[0]) + scale_node = graph._find_node_by_name(op.outputs, + op.output("OutScale")[0]) + + quant_axis = op.op().attr("quant_axis") if op.op().has_attr( + "quant_axis") else -1 + bit_length = op.op().attr("bit_length") if op.op().has_attr( + "bit_length") else self._quant_bits + + zero_point_node = None + quanted_node = x_node + if zero_point_node is None: + zero_point_node = graph.create_persistable_node( + name=self._zero_point_name(quanted_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=scale_node.shape(), + var_dtype=core.VarDesc.VarType.INT32) + _init_var_node(zero_point_node, + np.zeros(scale_node.shape(), dtype="int32"), + self._scope, self._place) + + quant_var_node = graph.create_var_node(name=self._quantized_var_name( + x_node.name()), + var_type=x_node.type(), + shape=x_node.shape(), + var_dtype=x_node.dtype()) + quant_op_node = graph.create_op_node(op_type="quantize_linear", + attrs={ + "quant_axis": quant_axis, + "bit_length": bit_length + }, + inputs={ + "X": x_node, + "Scale": scale_node, + "ZeroPoint": zero_point_node + }, + outputs={"Y": quant_var_node}) + graph.link_to(x_node, quant_op_node) + graph.link_to(scale_node, quant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + dequant_op_node = graph.create_op_node(op_type="dequantize_linear", + attrs={ + "quant_axis": quant_axis, + "bit_length": bit_length + }, + inputs={ + "X": quant_var_node, + "Scale": scale_node, + "ZeroPoint": zero_point_node + }, + outputs={"Y": out_node}) + graph.link_to(quant_var_node, dequant_op_node) + graph.link_to(scale_node, dequant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, dequant_op_node) + graph.link_to(dequant_op_node, out_node) + + def _quantized_var_name(self, var_name): + """ + Return quantized variable name for the input `var_name`. + """ + return "%s.quantized" % (var_name) + + def _zero_point_name(self, var_name): + """ + Return the scale name for the var named `var_name`. + """ + return "%s@zero_point" % (var_name) + + +class QuantWeightPass(object): + """ + quant weights and remove weights input quantize_linear node. for example: + `weight -> quant -> dequant -> conv2d` will be frozen into `weight -> dequant -> conv2d`, + and weight will be scaled offline. + + Args: + scope(paddle.Scope): scope is used to get the weight tensor values. + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to restore the weight tensors. + If it's string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the index of the GPUs. + bias_correction(bool): whether use bias correction for post-training quantization. + https://arxiv.org/abs/1810.05723. + quant_bits(int, optional): quantization bit number for weight. Default is 8. + save_int_weight(bool, optional): Whether the type saving the weight is int. Default is True. + + Examples: + .. code-block:: python + # The original graph will be rewrite. + import paddle + from paddle.fluid.contrib.slim.quantization \ + import QuantWeightPass + from paddle.fluid.contrib.slim.graph import IrGraph + from paddle.fluid import core + + graph = IrGraph(core.Graph(program.desc), for_test=False) + place = paddle.CPUPlace() + scope = paddle.static.global_scope() + quant_weight_pass = QuantWeightPass(scope, place) + quant_weight_pass.apply(graph) + """ + + def __init__(self, + scope, + place, + bias_correction=False, + quant_bits=8, + save_int_weight=True): + self._place = _get_paddle_place(place) + self._scope = scope + self._bias_correction = bias_correction + self._quant_bits = quant_bits + self._save_int_weight = save_int_weight + assert self._scope != None, "scope must not be None." + assert self._place != None, "place must not be None." + + def apply(self, graph): + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + fake_quant_ops_for_weight = [] + + fake_quant_ops = [ + op for op in graph.all_op_nodes() if op.name() == "quantize_linear" + ] + for _op in fake_quant_ops: + x_node = graph._find_node_by_name(_op.inputs, _op.input("X")[0]) + if x_node.persistable(): + scale_node = graph._find_node_by_name(_op.inputs, + _op.input("Scale")[0]) + zero_point_node = graph._find_node_by_name( + _op.inputs, + _op.input("ZeroPoint")[0]) + out_node = graph._find_node_by_name(_op.outputs, + _op.output("Y")[0]) + + scale_v = self._load_var(scale_node.name()) + assert scale_v.ndim in [1, 2 + ], "the dim of scale_v should be 1 or 2" + if scale_v.ndim == 2: + scale_v = scale_v[0] + if scale_v.size == 1 and _op.name() == 'abs_max': + scale_v = scale_v[0] + else: + scale_v = scale_v.tolist() + param_v = self._load_var(x_node.name()) + quant_axis = _op.op().attr("quant_axis") + bits_length = _op.op().attr("bit_length") + quantized_param_v = utils.quant_tensor(param_v.copy(), + scale_v, + quant_axis, + bits_length, + onnx_format=True) + if self._bias_correction == True: + quantized_param_v = utils.bias_correction_w( + param_v, + quantized_param_v, + scale_v, + quant_axis, + weight_bits=bits_length) + if self._save_int_weight: + # cast weight type to int + if self._quant_bits == 8: + save_weight_dtype = np.int8 + quantized_param_v = quantized_param_v.astype( + save_weight_dtype) + self._restore_var(x_node.name(), quantized_param_v) + + for next_op_node in out_node.outputs: + graph.update_input_link(out_node, x_node, next_op_node) + graph.safe_remove_nodes(out_node) + self._remove_unused_var_nodes(graph) + + def _remove_unused_var_nodes(self, graph): + all_used_vars = set() + ops = graph.all_op_nodes() + for op_node in ops: + for input_node in op_node.inputs: + all_used_vars.add(input_node) + for output_node in op_node.outputs: + all_used_vars.add(output_node) + + all_used_vars = {n.node for n in all_used_vars} + all_unused_vars = { + n + for n in filter(lambda node: node.node not in all_used_vars, + graph.all_var_nodes()) + } + graph.safe_remove_nodes(all_unused_vars) + + def _load_var(self, name): + return np.array(self._scope.find_var(name).get_tensor()) + + def _restore_var(self, name, array): + tensor = self._scope.find_var(name).get_tensor() + tensor.set(array, self._place) + + +class AddQuantDequantForInferencePass(object): + """ + When export quant model, it will traverse to find the output of each op, and then insert the quant/dequant op after it. + """ + + def __init__(self, scope, place, quant_bits=8): + """ + Args: + scope(fluid.Scope): The scope is used to initialize these new parameters. + place(paddle.CPUPlace|paddle.CUDAPlace|str): place is used to restore the weight tensors. + If it's string, it can be ``cpu``, and ``gpu:x``, where ``x`` is the index of the GPUs. + quant_bits(int, optional): quantization bit number for weight. Default is 8. + """ + self._scope = scope + self._place = place + self._quant_bits = quant_bits + self._teller_set = utils.QUANT_SUPPORTED_OP_TYPE_LIST + + def apply(self, graph): + """ + Args: + graph(IrGraph): the target graph. + """ + assert isinstance(graph, + IrGraph), 'graph must be the instance of IrGraph.' + dequant_node_map = {} + dequantized_vars_map = collections.OrderedDict() + for op_node in graph.all_op_nodes(): + if op_node.name() in self._teller_set: + var_names = utils._get_op_output_var_names(op_node) + for var_name in var_names: + out_node = graph._find_node_by_name(op_node.outputs, + var_name) + if out_node.dtype() not in \ + [core.VarDesc.VarType.FP64, core.VarDesc.VarType.FP32]: + continue + if var_name in dequantized_vars_map: + dequant_var_node = dequantized_vars_map[var_name] + else: + dequant_var_node = self._insert_quant_dequant_op( + graph, out_node) + dequantized_vars_map[var_name] = dequant_var_node + dequant_node_map[var_name] = dequant_var_node + + # remove unuse node and link act quant/dequant linear to op node + for op_node in graph.all_op_nodes(): + if op_node.name() == 'moving_average_abs_max_scale': + graph.safe_remove_nodes(op_node) + else: + var_names = utils._get_op_input_var_names(op_node) + for var_name in var_names: + if var_name in dequant_node_map: + in_node = graph._find_node_by_name( + op_node.inputs, var_name) + graph.update_input_link(in_node, + dequant_node_map[var_name], + op_node) + + return graph + + def _scale_name(self, var_name): + """ + Return the scale name for the var named `var_name`. + """ + return "%s@scale" % (var_name) + + def _insert_quant_dequant_op(self, graph, var_node): + assert var_node.is_var(), '{} is not a var'.format(var_node.name()) + var_name = var_node.name() + quant_axis = -1 + quant_var_node = graph.create_var_node( + name="{}.quantized".format(var_name), + var_type=var_node.type(), + shape=var_node.shape(), + var_dtype=var_node.dtype()) + scale_var_node = graph._find_node_by_name(graph.all_persistable_nodes(), + self._scale_name(var_name)) + try: + zero_point_node = graph._find_node_by_name( + graph.all_persistable_nodes(), + "{}@zero_point".format(quant_var_node.name())) + except: + zero_point_node = graph.create_persistable_node( + name="{}@zero_point".format(quant_var_node.name()), + var_type=core.VarDesc.VarType.LOD_TENSOR, + shape=scale_var_node.shape(), + var_dtype=core.VarDesc.VarType.INT32) + _init_var_node(zero_point_node, + np.zeros(scale_var_node.shape(), dtype="int32"), + self._scope, self._place) + + inputs = {"X": var_node, "Scale": scale_var_node} + if zero_point_node is not None: + inputs["ZeroPoint"] = zero_point_node + + attrs = {"quant_axis": quant_axis, "bit_length": self._quant_bits} + attrs["op_role"] = core.op_proto_and_checker_maker.OpRole.Forward + outputs = {"Y": quant_var_node} + + quant_op_node = graph.create_op_node(op_type="quantize_linear", + attrs=attrs, + inputs=inputs, + outputs=outputs) + + graph.link_to(var_node, quant_op_node) + graph.link_to(scale_var_node, quant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, quant_op_node) + graph.link_to(quant_op_node, quant_var_node) + + # add dequant_linear node + dequant_var_node = graph.create_var_node( + name="{}.dequantized".format(quant_var_node.name()), + var_type=quant_var_node.type(), + shape=quant_var_node.shape(), + var_dtype=quant_var_node.dtype()) + + inputs = {"X": quant_var_node, "Scale": scale_var_node} + if zero_point_node is not None: + inputs["ZeroPoint"] = zero_point_node + + attrs = {"quant_axis": -1, "bit_length": self._quant_bits} + attrs["op_role"] = core.op_proto_and_checker_maker.OpRole.Forward + + dequant_op_node = graph.create_op_node(op_type="dequantize_linear", + attrs=attrs, + inputs=inputs, + outputs={"Y": dequant_var_node}) + + graph.link_to(quant_var_node, dequant_op_node) + graph.link_to(scale_var_node, dequant_op_node) + if zero_point_node is not None: + graph.link_to(zero_point_node, dequant_op_node) + graph.link_to(dequant_op_node, dequant_var_node) + return dequant_var_node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantize_transpiler_v2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantize_transpiler_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..892b027de531eed819bec54eec4a231ac00e1a10 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/quantize_transpiler_v2.py @@ -0,0 +1,433 @@ +# 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. + +import collections +import logging +import numpy as np +from .... import core +from ....framework import Program, Operator, Variable, program_guard +from ....executor import global_scope +from .... import unique_name +from ....layer_helper import LayerHelper +from ....param_attr import ParamAttr +from ....initializer import Constant +from ....log_helper import get_logger + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +def find_next_ops(block, var_name): + """ + Find all followed ops for the input variable. + """ + res_ops = [] + for op in block.ops: + if var_name in op.input_arg_names: + res_ops.append(op) + return res_ops + + +def load_variable_data(scope, var_name): + ''' + Load variable value from scope + ''' + var_node = scope.find_var(var_name) + assert var_node is not None, \ + "Cannot find " + var_name + " in scope." + return np.array(var_node.get_tensor()) + + +class QuantizeTranspilerV2(object): + + def __init__(self, + weight_bits=8, + activation_bits=8, + weight_quantize_type='abs_max', + activation_quantize_type='moving_average_abs_max', + quantizable_op_type=[ + 'conv2d', + 'depthwise_conv2d', + 'mul', + ], + skip_pattern=['skip_quant']): + """ + Apply fake quant for the quantized ops. + + Args: + weight_bits(int): the bit of quantized weight. + activation_bits(int): the bit of quantized activation. + weight_quantize_type(str): the quantization type for weight. + Only support to be 'abs_max' and 'channel_wise_abs_max'. + activation_quantize_type(str): the quantization type for activation. + Only support to be 'abs_max' and 'moving_average_abs_max'. + quantizable_op_type(str): set the op type for quantization. + skip_pattern(str|list): The user-defined quantization skip pattern, which + will be presented in the name scope of an op. When the skip pattern is + detected in an op's name scope, the corresponding op will not be quantized. + """ + self._weight_bits = weight_bits + self._activation_bits = activation_bits + + assert activation_quantize_type in \ + ["abs_max", "moving_average_abs_max"], \ + "activation_quantize_type should be abs_max " \ + "or moving_average_abs_max for now." + assert weight_quantize_type in ["abs_max", "channel_wise_abs_max"], \ + "weight_quantize_type should be abs_max or channel_wise_abs_max." + self._activation_quantize_type = activation_quantize_type + self._weight_quantize_type = weight_quantize_type + + for op_type in quantizable_op_type: + assert op_type in ['conv2d', 'depthwise_conv2d', 'mul'], \ + "Quantize op should be ['conv2d', 'depthwise_conv2d', 'mul']" + self._quantizable_ops = quantizable_op_type + self._quantizable_grad_ops = [ + '%s_grad' % (op) for op in self._quantizable_ops + ] + + self._skip_pattern = skip_pattern + self._helper = LayerHelper(self.__class__.__name__) + + self._moving_rate = 0.9 + self._out_ch_axis1_ops = ['conv2d_transpose', 'mul', 'matmul'] + + def apply(self, program, startup_program, is_test=False): + """ + Apply quantization to fluid Program. + + Args: + program(Program): the train or test program to be quantized. + startup_program(Program): the corresponding startup_program. + is_test(bool): Whethe the program is used for test. + Returns: + None + """ + assert isinstance(program, Program), \ + "program must be the instance of Program" + assert isinstance(startup_program, Program), \ + "startup_program must be the instance of Program" + + var_rename_map = [ + collections.OrderedDict() for _ in range(len(program.blocks)) + ] + with program_guard(program, startup_program): + for block in program.blocks: + ops = list(block.ops) + for op in ops: + if op.type in self._quantizable_ops and \ + (not self._is_skip_quant(op)): + self._transform_forward(block, op, var_rename_map, + is_test) + + for block in program.blocks: + ops = list(block.ops) + for op in ops: + if op.type in self._quantizable_grad_ops and \ + (not self._is_skip_quant(op)): + self._transform_backward(block, op, var_rename_map) + + def convert(self, test_program, scope=None): + """ + Convert the test program. + Get the out scale from the moving_average_abs_max_scale op and save the + out scale into the quantized op. + Args: + test_program(Program): the test program to be converted. + scope(fluid.Scope, optional): The scope of the program, use it to load + and save variables. If scope=None, get scope by global_scope(). + """ + scope = global_scope() if scope == None else scope + + for block in test_program.blocks: + for op in block.ops: + if op.has_attr("quantization_type") \ + and op.attr("quantization_type") == "qat_with_weight": + # quant op -> var1 -> fake op -> var2 + assert len(op.output_arg_names) == 1 + var1_name = op.output_arg_names[0] + + fake_ops = find_next_ops(block, var1_name) + assert len(fake_ops) == 1 + fake_op = fake_ops[0] + assert fake_op.type == "moving_average_abs_max_scale" + + out_scale_name = fake_op.output("OutScale") + out_threshold = load_variable_data(scope, out_scale_name[0]) + op._set_attr("out_threshold", float(out_threshold)) + + var2_name = fake_op.output("Out")[0] + op._rename_output(var1_name, var2_name) + fake_op._rename_output(var2_name, var1_name) + + def _transform_forward(self, block, op, var_rename_map, is_test): + """ + Insert fake quant op before the target ops. + """ + op._set_attr("quantization_type", "qat_with_weight") + + # insert fake quant op before the quantized op + for in_name in op.input_arg_names: + block_id = block.idx + idx = block.ops.index(op) + + if in_name in var_rename_map[block_id]: + new_in_name = var_rename_map[block_id][in_name] + else: + in_var = block.var(in_name) + target_dtype = [ + core.VarDesc.VarType.FP32, core.VarDesc.VarType.FP16 + ] + if in_var.dtype not in target_dtype: + continue + + quant_bits = self._weight_bits if in_var.persistable \ + else self._activation_bits + quant_type = self._weight_quantize_type if in_var.persistable \ + else self._activation_quantize_type + + if quant_type == "abs_max": + new_var = self._insert_abs_max_fq_op( + block, idx, in_var, quant_bits) + elif quant_type == "moving_average_abs_max": + new_var = self._insert_ma_abs_max_fq_op( + block, idx, in_var, quant_bits, is_test) + elif quant_type == "channel_wise_abs_max": + ch_axis = 1 if op.type in self._out_ch_axis1_ops else 0 + new_var = self._insert_pc_abs_max_fq_op( + block, idx, in_var, quant_bits, ch_axis) + else: + _logger.error("Don't support the quant_type: %s" % + quant_type) + continue + + new_in_name = new_var.name + var_rename_map[block_id][in_name] = new_in_name + + op._rename_input(in_name, new_in_name) + + # insert out scale op followed the quantized op + for out_name in op.output_arg_names: + next_ops = find_next_ops(block, out_name) + + idx = block.ops.index(op) + out_var = block.var(out_name) + new_out_var = self._insert_ma_abs_max_scale_op( + block, idx + 1, out_var, is_test, True) + + for next_op in next_ops: + if "_grad" not in next_op.type: + next_op._rename_input(out_name, new_out_var.name) + + def _is_skip_quant(self, op): + """ + Analyse whether the op should skip quantization or not. + """ + user_skipped = False + if isinstance(self._skip_pattern, list): + user_skipped = op.has_attr("op_namescope") and \ + any(pattern in op.attr("op_namescope") \ + for pattern in self._skip_pattern) + elif isinstance(self._skip_pattern, str): + user_skipped = op.has_attr("op_namescope") and \ + op.attr("op_namescope").find( + self._skip_pattern) != -1 + return user_skipped + + def _transform_backward(self, block, op, var_rename_map): + """ + Update the backword of the target ops. + Note: for the grad ops, only rename the input, skip rename the output. + """ + block_id = block.idx + no_dequanted_input_vars = True + for name in op.input_arg_names: + if name in var_rename_map[block_id]: + new_var_name = var_rename_map[block_id][name] + op._rename_input(name, new_var_name) + no_dequanted_input_vars = False + if no_dequanted_input_vars: + raise ValueError("There is no dequanted inputs for op %s." % + (op.type)) + + def _insert_abs_max_fq_op(self, block, idx, in_var, quant_bits): + """ + Inset abs max fake quant op. + """ + quant_dequant_var = block.create_var(type=in_var.type, + name="{}.quant_dequant".format( + in_var.name), + shape=in_var.shape, + dtype=in_var.dtype) + scale_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.quant_dequant.scale".format(in_var.name), + initializer=Constant(0.), + trainable=False), + shape=[1], + dtype=in_var.dtype) + scale_var.stop_gradient = True + + inputs = {'X': in_var} + outputs = {'Out': quant_dequant_var, 'OutScale': scale_var} + attrs = {'bit_length': quant_bits} + block._insert_op(idx, + type='fake_quantize_dequantize_abs_max', + attrs=attrs, + inputs=inputs, + outputs=outputs) + return quant_dequant_var + + def _insert_ma_abs_max_fq_op(self, block, idx, in_var, quant_bits, is_test): + """ + Insert moving average abs max fake quant op. + """ + quant_dequant_var = block.create_var(type=in_var.type, + name="{}.quant_dequant".format( + in_var.name), + shape=in_var.shape, + dtype=in_var.dtype) + + scale_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.quant_dequant.scale".format(in_var.name), + initializer=Constant(0.), + trainable=False), + shape=[1], + dtype=in_var.dtype) + scale_var.stop_gradient = True + + if not is_test: + state_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.quant_dequant.state".format(in_var.name), + initializer=Constant(0), + trainable=False), + shape=[1], + dtype=in_var.dtype) + state_var.stop_gradient = True + + accum_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.quant_dequant.accum".format(in_var.name), + initializer=Constant(0), + trainable=False), + shape=[1], + dtype=in_var.dtype) + accum_var.stop_gradient = True + + attrs = { + 'moving_rate': self._moving_rate, + 'bit_length': quant_bits, + 'is_test': is_test + } + inputs = {'X': in_var, 'InScale': scale_var} + outputs = {'Out': quant_dequant_var, 'OutScale': scale_var} + if not is_test: + inputs['InState'] = state_var + inputs['InAccum'] = accum_var + outputs['OutState'] = state_var + outputs['OutAccum'] = accum_var + + block._insert_op(idx, + type='fake_quantize_dequantize_moving_average_abs_max', + attrs=attrs, + inputs=inputs, + outputs=outputs) + return quant_dequant_var + + def _insert_pc_abs_max_fq_op(self, block, idx, in_var, quant_bits, ch_axis): + """ + Insert per channel abs max fake quant op. + """ + quant_dequant_var = block.create_var(type=in_var.type, + name="{}.quant_dequant".format( + in_var.name), + shape=in_var.shape, + dtype=in_var.dtype) + + scale_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.quant_dequant.scale".format(in_var.name), + initializer=Constant(0.), + trainable=False), + shape=[in_var.shape[ch_axis]], + dtype=in_var.dtype) + scale_var.stop_gradient = True + + inputs = {'X': in_var} + outputs = {'Out': quant_dequant_var, 'OutScale': scale_var} + attrs = {'bit_length': quant_bits, 'quant_axis': ch_axis} + block._insert_op(idx, + type='fake_channel_wise_quantize_dequantize_abs_max', + attrs=attrs, + inputs=inputs, + outputs=outputs) + return quant_dequant_var + + def _insert_ma_abs_max_scale_op(self, + block, + idx, + in_var, + is_test, + has_out_var=False): + """ + Insert moving average abs max scale op. + """ + scale_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.outscale.scale".format(in_var.name), + initializer=Constant(0.), + trainable=False), + shape=[1], + dtype=in_var.dtype) + scale_var.stop_gradient = True + + attrs = {'moving_rate': self._moving_rate, 'is_test': is_test} + inputs = {'X': in_var} + outputs = {'OutScale': scale_var} + + if not is_test: + state_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.outscale.state".format(in_var.name), + initializer=Constant(0), + trainable=False), + shape=[1], + dtype=in_var.dtype) + state_var.stop_gradient = True + + accum_var = self._helper.create_parameter(attr=ParamAttr( + name="{}.outscale.accum".format(in_var.name), + initializer=Constant(0), + trainable=False), + shape=[1], + dtype=in_var.dtype) + accum_var.stop_gradient = True + + inputs['InState'] = state_var + inputs['InAccum'] = accum_var + outputs['OutState'] = state_var + outputs['OutAccum'] = accum_var + + if has_out_var: + out_var = block.create_var(type=in_var.type, + name="{}.tmp".format(in_var.name), + shape=in_var.shape, + dtype=in_var.dtype) + + outputs['Out'] = out_var + + block._insert_op(idx, + type='moving_average_abs_max_scale', + attrs=attrs, + inputs=inputs, + outputs=outputs) + + if has_out_var: + return out_var diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4446939a5546ad1b37b54c1fd2d8d5a086ce69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/slim/quantization/utils.py @@ -0,0 +1,479 @@ +# Copyright (c) 2021 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. + +import sys +import numpy as np +from ....framework import IrNode +from ....framework import Operator + +_weight_supported_quantizable_op_type = [ + 'conv2d', 'depthwise_conv2d', 'conv2d_transpose', 'mul', 'matmul', + 'matmul_v2' +] + +_act_supported_quantizable_op_type = [ + "pool2d", + "elementwise_add", + "concat", + "softmax", + "argmax", + "transpose", + "equal", + "gather", + "greater_equal", + "greater_than", + "less_equal", + "less_than", + "mean", + "not_equal", + "reshape", + "reshape2", + "dropout", + "bilinear_interp", + "nearest_interp", + "trilinear_interp", + "slice", + "squeeze", + "elementwise_sub", + "mul", + "matmul", + "relu", + "relu6", + "leaky_relu", + "tanh", + "swish", + "transpose", + "transpose2", + "sigmoid", + "pad2d", + "flatten", + "flatten2", + "batch_norm", + "layer_norm", + "matmul_v2", + "split", + "flatten_contiguous_range", + "squeeze2", + "nearest_interp_v2", + "bilinear_interp", + "bilinear_interp_v2", + "fill_constant_batch_size_like", + "arg_max", + "abs", + "assign", + "cast", + "clip", + "box_coder", + "crop", + "cumsum", + "elementwise_mul", + "elementwise_pow", + "expand_v2", + "fill_any_like", + "fill_constant", + "gelu", + "hard_sigmoid", + "hard_swish", + "instance_norm", + "lookup_table", + "lookup_table_v2", + "norm", + "p_norm", + "pad3d", + "pow", + "prelu", + "reduce_mean", + "unsqueeze", + "unsqueeze2", + "logical_and", + "logical_not", + "meshgrid", + "roi_align", + "strided_slice", + "where", + "grid_sampler", + "tile", + "group_norm", + "reduce_sum", + "square", + "softplus", + "shuffle_channel", + "reduce_max", +] + +QUANT_SUPPORTED_OP_TYPE_LIST = list( + set(_weight_supported_quantizable_op_type + + _act_supported_quantizable_op_type)) + +_out_scale_op_list = QUANT_SUPPORTED_OP_TYPE_LIST + +_channelwise_quant_axis1_ops = [ + 'conv2d_transpose', 'mul', 'matmul', 'matmul_v2' +] + +# list op real input and output names, to avoid processing input such as AxisTensor. +_op_real_in_out_name = { + "conv2d": [["Input", "Filter"], ["Output"]], + "depthwise_conv2d": [["Input", "Filter"], ["Output"]], + "conv2d_transpose": [["Input", "Filter"], ["Output"]], + "mul": [["X", "Y"], ["Out"]], + "matmul": [["X", "Y"], ["Out"]], + "matmul_v2": [["X", "Y"], ["Out"]], + "pool2d": [["X"], ["Out"]], + "elementwise_add": [["X", "Y"], ["Out"]], + "concat": [["X"], ["Out"]], + "softmax": [["X"], ["Out"]], + "argmax": [["X"], ["Out"]], + "transpose": [["X"], ["Out"]], + "equal": [["X", "Y"], ["Out"]], + "gather": [["X"], ["Out"]], + "greater_equal": [["X", "Y"], ["Out"]], + "greater_than": [["X", "Y"], ["Out"]], + "less_equal": [["X", "Y"], ["Out"]], + "less_than": [["X", "Y"], ["Out"]], + "mean": [["X"], ["Out"]], + "not_equal": [["X", "Y"], ["Out"]], + "reshape": [["X"], ["Out"]], + "reshape2": [["X"], ["Out"]], + "transpose2": [["X"], ["Out"]], + "bilinear_interp": [["X"], ["Out"]], + "nearest_interp": [["X"], ["Out"]], + "trilinear_interp": [["X"], ["Out"]], + "slice": [["Input"], ["Out"]], + "squeeze": [["X"], ["Out"]], + "elementwise_sub": [["X", "Y"], ["Out"]], + "relu": [["X"], ["Out"]], + "relu6": [["X"], ["Out"]], + "leaky_relu": [["X"], ["Out"]], + "prelu": [["X", "Alpha"], ["Out"]], + "tanh": [["X"], ["Out"]], + "swish": [["X"], ["Out"]], + "dropout": [["X"], ["Out"]], + "batch_norm": [["X"], ["Y"]], + "layer_norm": [["X"], ["Y"]], + "sigmoid": [["X"], ["Out"]], + "elementwise_mul": [["X", "Y"], ["Out"]], + "elementwise_pow": [["X", "Y"], ["Out"]], + "hard_swish": [["X"], ["Out"]], + "hard_sigmoid": [["X"], ["Out"]], + "gru": [["Input", "Weight"], ["Hidden"]], + "lstm": [["Input", "Weight"], ["Hidden"]], + "pad2d": [["X"], ["Out"]], + "pad3d": [["X"], ["Out"]], + "flatten": [["X"], ["Out"]], + "flatten2": [["X"], ["Out"]], + "unsqueeze2": [["X"], ["Out"]], + "unsqueeze2": [["X"], ["Out"]], + "flatten_contiguous_range": [["X"], ["Out"]], + "split": [["X"], ["Out"]], + "squeeze2": [["X"], ["Out"]], + "nearest_interp_v2": [["X"], ["Out"]], + "bilinear_interp": [["X"], ["Out"]], + "bilinear_interp_v2": [["X"], ["Out"]], + "fill_constant_batch_size_like": [["Input"], ["Out"]], + "arg_max": [["X"], ["Out"]], + "abs": [["X"], ["Out"]], + "assign": [["X"], ["Out"]], + "cast": [["X"], ["Out"]], + "clip": [["X"], ["Out"]], + "box_coder": [["PriorBox"], ["OutputBox"]], + "crop": [["X"], ["Out"]], + "cumsum": [["X"], ["Out"]], + "expand_v2": [["X"], ["Out"]], + "fill_any_like": [["X"], ["Out"]], + "fill_constant": [[], ["Out"]], + "gelu": [["X"], ["Out"]], + "instance_norm": [["X"], ["Out"]], + "lookup_table": [["W", "Ids"], ["Out"]], + "lookup_table_v2": [["W", "Ids"], ["Out"]], + "norm": [["X"], ["Norm"]], + "p_norm": [["X"], ["Out"]], + "pow": [["X"], ["Out"]], + "reduce_mean": [["X"], ["Out"]], + "stack": [["X"], ["Y"]], + "top_k_v2": [["X"], ["Out", "Indices"]], + "logical_and": [["X", "Y"], ["Out"]], + "logical_not": [["X"], ["Out"]], + "meshgrid": [["X"], ["Out"]], + "roi_align": [["X", "ROIs"], ["Out"]], + "strided_slice": [["Input"], ["Out"]], + "where": [["Condition", "X", "Y"], ["Out"]], + "grid_sampler": [["X", "Grid"], ["Output"]], + "tile": [["X"], ["Out"]], + "group_norm": [["X"], ["Y", "Mean", "Variance"]], + "reduce_sum": [["X"], ["Out"]], + "square": [["X"], ["Out"]], + "softplus": [["X"], ["Out"]], + "shuffle_channel": [["X"], ["Out"]], + "reduce_max": [["X"], ["Out"]], +} + + +def _get_op_input_var_names(op): + """ + Get the input var names of the op. + Args: + op(IrNode, Operator): the input op. + Returns: + input_var_names or None. + """ + assert isinstance(op, (IrNode, Operator)), \ + "The input op should be IrNode or Operator." + var_names = [] + op_name = op.name() if isinstance(op, IrNode) \ + else op.type + if op_name not in _op_real_in_out_name: + return [] + + name_list = _op_real_in_out_name[op_name][0] + for name in name_list: + var_name = op.input(name) + if isinstance(var_name, list): + var_names.extend(var_name) + else: + var_names.append(var_name) + return var_names + + +def _get_op_output_var_names(op): + """ """ + assert isinstance(op, (IrNode, Operator)), \ + "The input op should be IrNode or Operator." + var_names = [] + op_name = op.name() if isinstance(op, IrNode) \ + else op.type + if op_name not in _op_real_in_out_name: + return [] + + name_list = _op_real_in_out_name[op_name][1] + for name in name_list: + var_name = op.output(name) + if isinstance(var_name, list): + var_names.extend(var_name) + else: + var_names.append(var_name) + return var_names + + +def _get_input_name_index(op, input_var_name): + """Get the input name and index of the var_name in the op""" + assert isinstance(op, (IrNode, Operator)), \ + "The input op should be IrNode or Operator." + op_name = op.name() if isinstance(op, IrNode) \ + else op.type + if op_name not in _op_real_in_out_name: + return None + + res = None + for argname in _op_real_in_out_name[op_name][0]: + var_names = op.input(argname) + for index, name in enumerate(var_names): + if name == input_var_name: + res = (argname, index) + return res + + +def _get_output_name_index(op, output_var_name): + """Get the output name and index of the var_name in the op""" + assert isinstance(op, (IrNode, Operator)), \ + "The input op should be IrNode or Operator." + op_name = op.name() if isinstance(op, IrNode) \ + else op.type + if op_name not in _op_real_in_out_name: + return None + + name_list = _op_real_in_out_name[op_name][1] + res = None + for name in name_list: + var_name = op.output(name) + for index, val in enumerate(var_name): + if val == output_var_name: + res = (name, index) + return res + + +def load_variable_data(scope, var_name): + ''' + Load variable value from scope + ''' + var_node = scope.find_var(var_name) + assert var_node is not None, \ + "Cannot find " + var_name + " in scope." + return np.array(var_node.get_tensor()) + + +def set_variable_data(scope, place, var_name, np_value): + ''' + Set the value of var node by name, if the node exits, + ''' + assert isinstance(np_value, np.ndarray), \ + 'The type of value should be numpy array.' + var_node = scope.find_var(var_name) + if var_node != None: + tensor = var_node.get_tensor() + tensor.set(np_value, place) + + +def quant_tensor(x, scale, quant_axis=0, weight_bits=8, onnx_format=False): + # symmetry quant + def _clip(x, scale): + x[x > scale] = scale + x[x < -scale] = -scale + return x + + bnt = (1 << (weight_bits - 1)) - 1 + if isinstance(scale, list) and len(scale) == 1: + scale = scale[0] + if isinstance(scale, list): + assert quant_axis in [0, 1], 'quant_axis should be 0 or 1 for now.' + for i, s in enumerate(scale): + if s == 0.0: + s = 1e-8 + if quant_axis == 0: + if onnx_format: + x[i] = np.round(x[i] / s * bnt) + x[i] = np.clip(x[i], -bnt - 1, bnt) + else: + x[i] = _clip(x[i], s) + x[i] = x[i] / s * bnt + else: + if onnx_format: + x[:, i] = np.round(x[:, i] / s * bnt) + x[:, i] = np.clip(x[:, i], -bnt - 1, bnt) + else: + x[:, i] = _clip(x[:, i], s) + x[:, i] = x[:, i] / s * bnt + else: + scale = 1e-8 if scale == 0.0 else scale + if onnx_format: + x = np.round(x / scale * bnt) + x = np.clip(x, -bnt - 1, bnt) + else: + x = _clip(x, scale) + x = x / scale * bnt + return x + + +def dequant_tensor(x, scale, quant_axis=0, weight_bits=8): + assert quant_axis in [0, 1], 'quant_axis should be 0 or 1 for now.' + bnt = (1 << (weight_bits - 1)) - 1 + if isinstance(scale, list): + for i, s in enumerate(scale): + if s == 0.0: + s = 1e-8 + if quant_axis == 0: + x[i] = x[i] * s / bnt + else: + x[:, i] = x[:, i] * s / bnt + else: + scale = 1e-8 if scale == 0.0 else scale + x = x * scale / bnt + return x + + +def bias_correction_w(x, x_quant, scale_v, quant_axis, weight_bits=8): + ''' + Bias correction for weight + ''' + eps = 1e-8 + bnt = (1 << (weight_bits - 1)) - 1 + x_dequant = x_quant.copy() + if isinstance(scale_v, list): + if quant_axis == 0: + for i, s in enumerate(scale_v): + x_dequant[i] = x_dequant[i] * s / bnt + quant_bias = x - x_dequant + mean_bias = quant_bias.reshape(quant_bias.shape[0], -1).mean(-1) + std_orig = x.reshape(x.shape[0], -1).std(-1) + std_quant = x_dequant.reshape(x_dequant.shape[0], -1).std(-1) + std_bias = std_orig / (std_quant + eps) + else: + for i, s in enumerate(scale_v): + x_dequant[:, i] = x_quant[:, i] * s / bnt + quant_bias = x - x_dequant + mean_bias = np.array( + [quant_bias[:, i].mean() for i in range(quant_bias.shape[1])]) + std_orig = np.array([x[:, i].std() for i in range(x.shape[1])]) + std_quant = np.array( + [x_dequant[:, i].std() for i in range(x_dequant.shape[1])]) + std_bias = std_orig / (std_quant + eps) + else: + x_dequant = x_quant * scale_v / bnt + mean_bias = (x - x_dequant).mean() + std_bias = x.std() / (x_dequant.std() + eps) + if mean_bias.ndim == 1: + std_bias = np.resize(std_bias, x.shape) + mean_bias = np.resize(mean_bias, x.shape) + + x_dequant = (mean_bias + x_dequant) * std_bias + quantized_param_v = quant_tensor(x_dequant, scale_v, quant_axis, + weight_bits) + return quantized_param_v + + +def stable_sigmoid(x): + sig = np.where(x < 0, np.exp(x) / (1 + np.exp(x)), 1 / (1 + np.exp(-x))) + return sig + + +def calculate_quant_cos_error(orig_tensor, qdq_tensor): + cos_sim = np.inner(orig_tensor.flatten(), qdq_tensor.flatten()) \ + / (np.linalg.norm(orig_tensor.flatten()) * np.linalg.norm(qdq_tensor.flatten())) + return cos_sim + + +def move_persistable_var_to_global_block(program): + # Move sub blocks persistable var to global block + global_block = program.global_block() + for _op in global_block.ops: + if _op.type == "while": + _block_id = _op.attr("sub_block").id + _block = program.block(_block_id) + persistables = [] + for _name, _var in _block.vars.items(): + if _var.persistable: + global_block._clone_variable(_var) + persistables.append(_name) + for _name in persistables: + _block._remove_var(_name) + persistables.extend(_op.input('X')) + _op.desc.set_input("X", persistables) + + +def l2_loss(gt, pred): + return ((gt - pred)**2).mean() + + +class tqdm(object): + + def __init__(self, total, bar_format='Loading|{bar}', ncols=80): + self.total = total + self.bar_format = bar_format + self.ncols = ncols + self.n = 0 + + def update(self, n=1): + self.n += n + a = "=" * round((self.n / self.total) * self.ncols) + b = " " * (self.ncols - len(a)) + prefix = self.bar_format.split('|')[0] + sys.stderr.write("\r{}|{}=>{}| {}/{}".format(prefix, a, b, self.n, + self.total)) + sys.stderr.flush() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + sys.stderr.write('\n') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08778a707d23a997671019e0ce1ef2b7763d4c6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/__init__.py @@ -0,0 +1,39 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from __future__ import print_function + +from .utils import calculate_density +from .utils import check_mask_1d +from .utils import get_mask_1d +from .utils import check_mask_2d +from .utils import get_mask_2d_greedy +from .utils import get_mask_2d_best +from .utils import create_mask +from .utils import check_sparsity +from .utils import MaskAlgo +from .utils import CheckMethod +from .asp import decorate +from .asp import prune_model +from .asp import set_excluded_layers +from .asp import reset_excluded_layers +from .supported_layer_list import add_supported_layer + +__all__ = [ + 'calculate_density', 'check_mask_1d', 'get_mask_1d', 'check_mask_2d', + 'get_mask_2d_greedy', 'get_mask_2d_best', 'create_mask', 'check_sparsity', + 'MaskAlgo', 'CheckMethod', 'decorate', 'prune_model', 'set_excluded_layers', + 'reset_excluded_layers', 'add_supported_layer' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/asp.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/asp.py new file mode 100644 index 0000000000000000000000000000000000000000..692591d770f5dc74a168326a8a8a97f119501494 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/asp.py @@ -0,0 +1,965 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. +""" +Functions for Auto SParsity (ASP) training and inference. +""" + +import os +import copy +import numpy as np +import paddle +from paddle.fluid.framework import dygraph_only +from paddle.fluid import global_scope, program_guard, layers +from paddle.fluid.initializer import ConstantInitializer +from paddle.fluid.contrib import sparsity +from paddle.fluid import core +from paddle.fluid.contrib.sparsity.supported_layer_list import supported_layers_and_prune_func_map +from paddle.fluid.contrib.sparsity.supported_layer_list import _default_pruning + +OpRole = core.op_proto_and_checker_maker.OpRole +OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() + +__all__ = [ + 'decorate', 'prune_model', 'set_excluded_layers', 'reset_excluded_layers' +] + + +def set_excluded_layers(param_names, main_program=None): + r""" + Set parameter name of layers which would not be pruned as sparse weights. + + Args: + param_names (list of string): A list contains names of parameters. + main_program (Program, optional): Program with model definition and its parameters. + If None is given, then it would be set as `paddle.static.default_main_program(). + Default is None. + Examples: + 1. Usage of Dynamic Graph + + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 100) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + prediction = self.linear1(hidden) + return prediction + + my_layer = MyLayer() + optimizer = paddle.optimizer.SGD( + learning_rate=0.01, parameters=my_layer.parameters()) + + # Need to set excluded layers before calling decorate + paddle.incubate.asp.set_excluded_layers([my_layer.linear1.full_name()]) + + optimizer = paddle.incubate.asp.decorate(optimizer) + + 2. Usage of Static Graph + + .. code-block:: python + + import paddle + + paddle.enable_static() + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 100) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + prediction = self.linear1(hidden) + return prediction + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + input_data = paddle.static.data(name='data', shape=[None, 3, 224, 224]) + label = paddle.static.data(name='label', shape=[None, 100]) + my_layer = MyLayer() + prob = my_layer(input_data) + loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) + + # Setup exluded layers out from ASP workflow. + # Please note, excluded_layers must be set before calling optimizer.minimize(). + paddle.incubate.asp.set_excluded_layers([my_layer.linear1.full_name()], main_program) + + optimizer = paddle.optimizer.SGD(learning_rate=0.1) + optimizer = paddle.static.amp.decorate(optimizer ) + # Calling paddle.incubate.asp.decorate() to wrap minimize() in optimizer, which + # will insert necessary masking operations for ASP workflow. + optimizer = paddle.incubate.asp.decorate(optimizer) + optimizer.minimize(loss, startup_program) + """ + if main_program is None: + main_program = paddle.static.default_main_program() + ASPHelper.set_excluded_layers(param_names=param_names, + main_program=main_program) + + +def reset_excluded_layers(main_program=None): + r""" + Reset exculded layers setting corresponding to :attr:`main_program`. If :attr:`main_program` + is None, then all configurations of excluded_layers would be cleaned. + + Args: + main_program (Program, optional): Program with model definition and its parameters. + If None is given, then this function would reset all excluded_layers. + Default is None. + Examples: + 1. Usage of Dynamic Graph + + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 100) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + prediction = self.linear1(hidden) + return prediction + + my_layer = MyLayer() + optimizer = paddle.optimizer.SGD( + learning_rate=0.01, parameters=my_layer.parameters()) + + # Need to set excluded layers before calling decorate + paddle.incubate.asp.set_excluded_layers([my_layer.linear1.full_name()]) + # Reset excluded_layers, all supported layers would be included into Automatic SParsity's workflow. + # Please note, reset_excluded_layers also must be called before calling sparsity.decorate(). + paddle.incubate.asp.reset_excluded_layers() + + optimizer = paddle.incubate.asp.decorate(optimizer) + + 2. Usage of Static Graph + + .. code-block:: python + + import paddle + + paddle.enable_static() + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 100) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + prediction = self.linear1(hidden) + return prediction + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + input_data = paddle.static.data(name='data', shape=[None, 3, 224, 224]) + label = paddle.static.data(name='label', shape=[None, 100]) + my_layer = MyLayer() + prob = my_layer(input_data) + loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) + + # Setup exluded layers out from ASP workflow. + # Please note, excluded_layers must be set before calling optimizer.minimize(). + paddle.incubate.asp.set_excluded_layers([my_layer.linear1.full_name()], main_program) + # Reset excluded_layers, all supported layers would be included into Automatic SParsity's workflow. + # Please note, reset_excluded_layers also must be called before calling optimizer.minimize(). + paddle.incubate.asp.reset_excluded_layers(main_program) + + optimizer = paddle.optimizer.SGD(learning_rate=0.1) + optimizer = paddle.static.amp.decorate(optimizer ) + # Calling paddle.incubate.asp.decorate() to wrap minimize() in optimizer, which + # will insert necessary masking operations for ASP workflow. + optimizer = paddle.incubate.asp.decorate(optimizer) + optimizer.minimize(loss, startup_program) + """ + ASPHelper.reset_excluded_layers(main_program=main_program) + + +def decorate(optimizer): + r""" + Wrap the given optimizer as a OptimizerWithSparsityGuarantee, + If runnig with dynamic graph mode. ASP would creates mask variables for supported parameters. + Else if in static graph mode, ASP would creates mask variables and inserts necessary ops + when calling minimize() + + Args: + optimizer (Optimizer): A Optimizer used for training. + Returns: + OptimizerWithSparsityGuarantee: A wrapper for ASP to decorate `minimize` function of the given optimizer. + Examples: + 1. Usage of Dynamic Graph + + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 32) + self.linear2 = paddle.nn.Linear(32, 32) + self.linear3 = paddle.nn.Linear(32, 10) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + hidden = self.linear1(hidden) + hidden = self.linear2(hidden) + prediction = self.linear3(hidden) + return prediction + + my_layer = MyLayer() + optimizer = paddle.optimizer.SGD( + learning_rate=0.01, parameters=my_layer.parameters()) + + # Calling paddle.incubate.asp.decorate() to wrap step() in optimizer, which + # will apply necessary masking operations for ASP workflow. + # In dynamic graph mode, ASP would create related mask variables during decoration. + optimizer = paddle.incubate.asp.decorate(optimizer) + + 2. Usage of Static Graph + + .. code-block:: python + + import paddle + + paddle.enable_static() + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 100) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + prediction = self.linear1(hidden) + return prediction + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + input_data = paddle.static.data(name='data', shape=[None, 3, 224, 224]) + label = paddle.static.data(name='label', shape=[None, 100]) + my_layer = MyLayer() + prob = my_layer(input_data) + loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) + + optimizer = paddle.optimizer.SGD(learning_rate=0.1) + # Calling paddle.incubate.asp.decorate() to wrap minimize() in optimizer, which + # will insert necessary masking operations for ASP workflow. + # In static graph mode, ASP creates related mask variables + # during minimize(). + optimizer = paddle.incubate.asp.decorate(optimizer) + optimizer.minimize(loss, startup_program) + """ + return ASPHelper.decorate(optimizer) + + +def prune_model(model, n=2, m=4, mask_algo='mask_1d', with_mask=True): + r""" + Pruning parameters of supported layers in :attr:`model` via + specified mask generation function given by :attr:`mask_algo`. This + function supports both training and inference controlled by :attr:`with_mask`. + If :attr:`with_mask` is True, it would also prune parameter related ASP mask Variables, + else only prunes parameters. + + *Note*: (Static graph mode) If calling this function with :attr:`with_mask`, it should call `OptimizerWithSparsityGuarantee.minimize` + and initialization (`exe.run(startup_program`)) before (For successfully obtain mask Variable). + Typically set `with_mask` as true for training (have called `OptimizerWithSparsityGuarantee.minimize`) and false for + inference only. To obtain OptimizerWithSparsityGuarantee, please see `paddle.incubate.asp.decoreate()`. + + Args: + model (Program|nn.Layer): Program with model definition and its parameters, or a object of `paddle.nn.Layer`. + n (int, optional): n of `n:m` sparse pattern. Default is 2. + m (int, optional): m of `n:m` sparse pattern. Default is 4. + mask_algo (string, optional): The function name to generate spase mask. Default is `mask_1d`. + The vaild inputs should be one of 'mask_1d', 'mask_2d_greedy' and 'mask_2d_best'. + with_mask (bool, optional): To prune mask Variables related to parameters or not. Ture is purning also, False is not. Default is True. + Returns: + dictionary: A dictionary with key: `parameter name` (string) and value: its corresponding mask Variable. + Examples: + 1. Usage of Dynamic Graph + + .. code-block:: python + + import paddle + import numpy as np + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 32) + self.linear2 = paddle.nn.Linear(32, 32) + self.linear3 = paddle.nn.Linear(32, 10) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + hidden = self.linear1(hidden) + hidden = self.linear2(hidden) + prediction = self.linear3(hidden) + return prediction + + my_layer = MyLayer() + loss_fn = paddle.nn.MSELoss(reduction='mean') + + optimizer = paddle.optimizer.SGD( + learning_rate=0.01, parameters=my_layer.parameters()) + + # Calling paddle.incubate.asp.decorate() to wrap step() in optimizer, which + # will apply necessary masking operations for ASP workflow. + # In dynamic graph mode, ASP would create related mask variables during decoration. + optimizer = paddle.incubate.asp.decorate(optimizer) + + # Must call paddle.incubate.asp.decorate() first before calling paddle.incubate.asp.prune_model() + paddle.incubate.asp.prune_model(my_layer, mask_algo='mask_2d_best') + + for i in range(10): + imgs = paddle.to_tensor( + np.random.randn(64, 3, 32, 32), + dtype='float32', stop_gradient=False) + labels = paddle.to_tensor( + np.random.randint(10, size=(64, 1)), + dtype='float32', stop_gradient=False) + output = my_layer(imgs) + loss = loss_fn(output, labels) + loss.backward() + optimizer.step() + optimizer.clear_grad() + + 2. Usage of Static Graph + + .. code-block:: python + + import paddle + import numpy as np + + paddle.enable_static() + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.conv1 = paddle.nn.Conv2D( + in_channels=3, out_channels=4, kernel_size=3, padding=2) + self.linear1 = paddle.nn.Linear(4624, 32) + self.linear2 = paddle.nn.Linear(32, 32) + self.linear3 = paddle.nn.Linear(32, 10) + + def forward(self, img): + hidden = self.conv1(img) + hidden = paddle.flatten(hidden, start_axis=1) + hidden = self.linear1(hidden) + hidden = self.linear2(hidden) + prediction = self.linear3(hidden) + return prediction + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + input_data = paddle.static.data(name='data', shape=[None, 3, 32, 32]) + label = paddle.static.data(name='label', shape=[None, 1]) + my_layer = MyLayer() + prob = my_layer(input_data) + loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label)) + + optimizer = paddle.optimizer.SGD(learning_rate=0.1) + # Calling paddle.incubate.asp.decorate() to wrap minimize() in optimizer, which + # will insert necessary masking operations for ASP workflow. + # In static graph mode, ASP creates related mask variables + # during minimize(). + optimizer = paddle.incubate.asp.decorate(optimizer) + optimizer.minimize(loss, startup_program) + + device = paddle.device.get_device() + place = paddle.set_device(device) + + exe = paddle.static.Executor(place) + exe.run(startup_program) + + # Must call exe.run(startup_program) first before calling paddle.asp.prune_model() + paddle.incubate.asp.prune_model(my_layer, mask_algo='mask_2d_best') + # it also be accepted to call + # paddle.incubate.asp.prune_model(main_program, mask_algo='mask_2d_best') + + for i in range(10): + imgs = np.random.randn(64, 3, 32, 32).astype('float32') + labels = np.random.randint(10, size=(64, 1)).astype('float32') + exe.run(main_program, feed={'data':imgs, 'label':labels}) + """ + device = paddle.device.get_device() + place = paddle.set_device(device) + + MaskAlgo_mapping = { + 'mask_1d': sparsity.MaskAlgo.MASK_1D, + 'mask_2d_greedy': sparsity.MaskAlgo.MASK_2D_GREEDY, + 'mask_2d_best': sparsity.MaskAlgo.MASK_2D_BEST + } + assert (mask_algo in MaskAlgo_mapping), \ + 'The "mask_algo" should be one of ["mask_1d", "mask_2d_greedy", "mask_2d_best"]' + + prune_func = None + if isinstance(model, paddle.nn.Layer): + prune_func = ASPHelper.prune_model_by_layer + elif isinstance(model, paddle.static.Program): + prune_func = ASPHelper.prune_model_by_program + if hasattr(model, "distributed_info_") and \ + model.distributed_info_["sharding_degree"] > 1 and \ + paddle.fluid.is_compiled_with_cuda(): + gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0)) + place = paddle.CUDAPlace(gpu_id) + else: + raise TypeError( + "model should be paddle.nn.Layer or paddle.static.Program, but got {}" + .format(type(model))) + + return prune_func(place, + model, + n=n, + m=m, + mask_algo=MaskAlgo_mapping[mask_algo], + with_mask=with_mask) + + +class ProgramASPInfo(object): + r""" + ProgramASPInfo is a container to keep ASP relevant information of Pragrom. It contains three inner-variables: + 1. __mask_vars (Dictionary): Key is parameter's name and vaule is its corresponding sparse mask Variable object, which is created by `ASPHelper.create_mask_variables`. + 2. __masks (Dictionary): Key is parameter's name and vaule is its corressponding sparse mask Numpy array, which is created by `ASPHelper.prune_model`. + 3. __excluded_layers (List): It stores name of layers which should not involve into ASP workflow. + """ + + def __init__(self): + self.__mask_vars = {} + self.__masks = {} + self.__excluded_layers = [] + + def update_mask_vars(self, param_name, var): + self.__mask_vars[param_name] = var + + def update_masks(self, param_name, var): + self.__masks[param_name] = var + + def update_excluded_layers(self, param_names): + self.__excluded_layers.extend(copy.deepcopy(param_names)) + + def reset_excluded_layers(self): + self.__excluded_layers = [] + + @property + def mask_vars(self): + return self.__mask_vars + + @property + def masks(self): + return self.__masks + + @property + def excluded_layers(self): + return self.__excluded_layers + + +class ASPHelper(object): + r""" + ASPHelper is a collection of Auto SParsity (ASP) functions to enable + + 1. training models with weights in 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 from scratch. + 2. pruning well-trained models into 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 for fine-tuning. + """ + + MASK_APPENDDED_NAME = 'asp_mask' + PADDLE_WEIGHT_SUFFIX = "w_" + + __asp_info = {} + + @classmethod + def set_excluded_layers(cls, param_names, main_program): + r""" + This is the implementation of `sparsity.set_excluded_layers`, for details please see explanation in `sparsity.set_excluded_layers`. + """ + asp_info = cls._get_program_asp_info(main_program) + asp_info.update_excluded_layers(param_names) + + @classmethod + def reset_excluded_layers(cls, main_program=None): + r""" + This is the implementation of `sparsity.reset_excluded_layers`, for details please see explanation in `sparsity.reset_excluded_layers`. + """ + if main_program is None: + for prog in cls.__asp_info: + cls.__asp_info[prog].reset_excluded_layers() + else: + cls._get_program_asp_info(main_program).reset_excluded_layers() + + @staticmethod + def decorate(optimizer): + r""" + This is the implementation of `sparsity.decorate`, for details please see explanation in `sparsity.decorate`. + """ + if paddle.in_dynamic_mode(): + # main_prog and startup_prog would be used with paddle.static.program_guard + # to create ASP masks. Moreover, main_prog is a key to map paddle.static.Program + # to its own ASP informantion, like ASP mask variables. For dynamic graph, we use + # default_main_program as the key. + main_prog = paddle.static.default_main_program() + startup_prog = paddle.static.default_startup_program() + ASPHelper._create_mask_variables(main_prog, startup_prog, + optimizer._parameter_list) + return OptimizerWithSparsityGuarantee(optimizer) + + @classmethod + def prune_model_by_program(cls, + place, + main_program=None, + n=2, + m=4, + mask_algo=sparsity.MaskAlgo.MASK_1D, + with_mask=True): + r""" + This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`. + """ + + if main_program is None: + main_program = paddle.static.default_main_program() + + asp_info = cls._get_program_asp_info(main_program) + for param in main_program.global_block().all_parameters(): + if ASPHelper._is_supported_layer(main_program, param.name): + weight_tensor = global_scope().find_var(param.name).get_tensor() + weight_nparray = np.array(weight_tensor) + + prune_func = ASPHelper._get_prune_func_by_name(param.name) + + weight_pruned_nparray, weight_sparse_mask = \ + prune_func(weight_nparray, m, n, mask_algo, param.name) + weight_pruned_nparray = weight_pruned_nparray.astype( + weight_nparray.dtype) + weight_tensor.set(weight_pruned_nparray, place) + + if with_mask: + weight_mask_param = global_scope().find_var( + ASPHelper._get_mask_name(param.name)) + assert weight_mask_param is not None, \ + 'Cannot find {} variable, please call optimizer.minimize (' \ + 'paddle.sparsity.decorate(optimizer).minimize(loss)' \ + ' and initialization (exe.run(startup_program)) first!'.format(ASPHelper._get_mask_name(param.name)) + weight_mask_tensor = weight_mask_param.get_tensor() + weight_sparse_mask = weight_sparse_mask.astype( + np.array(weight_mask_tensor).dtype) + weight_mask_tensor.set(weight_sparse_mask, place) + asp_info.update_masks(param.name, weight_sparse_mask) + return asp_info.masks.copy() + + @classmethod + def prune_model_by_layer(cls, + place, + layer, + n=2, + m=4, + mask_algo=sparsity.MaskAlgo.MASK_1D, + with_mask=True): + r""" + This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`. + """ + if paddle.in_dynamic_mode(): + main_program = paddle.static.default_main_program() + asp_info = cls._get_program_asp_info(main_program) + + for param in layer.parameters(): + if ASPHelper._is_supported_layer(main_program, param.name): + weight_nparray = param.numpy() + + prune_func = ASPHelper._get_prune_func_by_name(param.name) + + weight_pruned_nparray, weight_sparse_mask = \ + prune_func(weight_nparray, m, n, mask_algo, param.name) + + weight_pruned_nparray = weight_pruned_nparray.astype( + weight_nparray.dtype) + param.set_value(weight_pruned_nparray) + + if with_mask: + weight_mask_param = asp_info.mask_vars.get( + param.name, None) + assert weight_mask_param is not None, \ + 'Cannot find {} variable, please call sparsity.decorate() to' \ + ' decorate your optimizer first!'.format(ASPHelper._get_mask_name(param.name)) + weight_mask_param.set_value(weight_sparse_mask) + + asp_info.update_masks(param.name, weight_sparse_mask) + + return asp_info.masks.copy() + else: + # This for loop is only used to obtain Block and Program from + # first parameters. + target_program = None + for param in layer.parameters(): + target_program = param.block.program + assert target_program is not None, \ + 'Cannot get paddle.static.Program from Paddle.nn.Layer.' + return ASPHelper.prune_model_by_program(place, + target_program, + n=n, + m=m, + mask_algo=mask_algo, + with_mask=with_mask) + + @staticmethod + def _get_mask_name(param_name): + r""" + Return mask name by given parameter name :attr:`param_name`. + + Args: + param_name (string): The name of parameter. + Returns: + string: The mask name of :attr:`param_name`. + """ + return param_name + "." + ASPHelper.MASK_APPENDDED_NAME + + @staticmethod + def _get_not_ASP_relevant_vars(main_program): + r""" + Get all parameters's Variables in :attr:`main_program` but excluded ASP mask Variables. + + Args: + main_program (Program): Program with model definition and its parameters. + Returns: + list: A list of parameter Variables in :attr:`main_program` (excluded ASP mask Variables). + """ + var_list = [] + for param in main_program.global_block().all_parameters(): + param_name_list = param.name.split('.') + + if ASPHelper.MASK_APPENDDED_NAME not in param_name_list: + var_list.append(param) + return var_list + + @classmethod + def _get_program_asp_info(cls, main_program): + if main_program not in cls.__asp_info: + cls.__asp_info[main_program] = ProgramASPInfo() + return cls.__asp_info[main_program] + + @classmethod + def _is_supported_layer(cls, main_program, param_name): + r""" + Verify if given :attr:`param_name` is supported by ASP. + + Args: + param_name (string): The name of parameter. + Returns: + bool: True if it is supported, else False. + Examples: + .. code-block:: python + + from paddle.static.sparsity.asp import ASPHelper + + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + input_data = paddle.static.data(name='data', shape=[None, 128]) + fc = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None) + + for param in main_program.global_block().all_parameters(): + ASPHelper._is_supported_layer(main_program, param.name) + # fc_0.w_0 -> True + # fc_0.b_0 -> False + """ + param_name_list = param_name.split('.') + + if ASPHelper.MASK_APPENDDED_NAME in param_name_list: + return False + + for layer in cls._get_program_asp_info(main_program).excluded_layers: + if layer in param_name: + return False + + if param_name in supported_layers_and_prune_func_map: + return True + + # The parameter's name is neither in *.* format nor added to supported_layers_and_prune_func_map, return False. + if len(param_name_list) == 1: + return False + + param_name_no_weight_suffix = param_name_list[0] + param_type_suffix = param_name_list[1] + layer_name = param_name_no_weight_suffix[:param_name_no_weight_suffix. + rfind('_')] + if ASPHelper.PADDLE_WEIGHT_SUFFIX not in param_type_suffix: + return False + + if param_name_no_weight_suffix in supported_layers_and_prune_func_map or \ + layer_name in supported_layers_and_prune_func_map: + return True + + return False + + @classmethod + def _get_prune_func_by_name(cls, param_name): + func = supported_layers_and_prune_func_map.get(param_name, None) + param_name_no_weight_suffix = param_name.split('.')[0] + if func is None: + func = supported_layers_and_prune_func_map.get( + param_name_no_weight_suffix, None) + if func is None: + layer_name = param_name_no_weight_suffix[: + param_name_no_weight_suffix + .rfind('_')] + func = supported_layers_and_prune_func_map.get( + layer_name, _default_pruning) + return func + + @classmethod + def _minimize(cls, + optimizer, + loss, + main_program=None, + startup_program=None, + parameter_list=None, + no_grad_set=None): + r""" + This function is a decorator of `minimize` function in `Optimizer`. + There are three steps: + + 1. Call :attr:`optimizer`.minimize(:attr:`loss`) + 2. Create sparse mask Tensors according to supported layers in :attr:`main_program`. + 3. Insert masking ops in the end of parameters update. + + *Note*: Please use `ASP.decorate` instead when applying distributed training with `Fleet`. + (Due to there is a invisiable graphs optimization in `Fleet.minimize()` which make training graph + cannot be modified anymore.) + + Args: + optimizer (Optimizer): A Optimizer used for training. + loss (Variable): A Variable containing the value to minimize. + main_program (Program, optional): Program with model definition and its parameters. Default is `loss.block.program`. + startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`. + parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated. + no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None. + Returns: + list: operators from :attr:`optimizer`.minimize(:attr:`loss`). + list: pairs of parameters and their gradients. + """ + if main_program is None: + main_program = loss.block.program + + if startup_program is None: + startup_program = paddle.static.default_startup_program() + + optimizer_ops, params_and_grads = optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set) + + params_only = [pg[0] for pg in params_and_grads] + cls._create_mask_variables(main_program, startup_program, params_only) + cls._insert_sparse_mask_ops(main_program, params_only) + return optimizer_ops, params_and_grads + + @classmethod + @dygraph_only + def _step(cls, optimizer): + r""" + This function is a decorator of `step` function in `Optimizer`. + There are three steps: + + 1. Call :attr:`optimizer`.step() + 2. Mask parameters with sparse masks. + + *Note*: Please use `ASP.decorate` instead when applying distributed training with `Fleet`. + (Due to there is a invisiable graphs optimization in `Fleet.minimize()` which make training graph + cannot be modified anymore.) + + Args: + optimizer (Optimizer): A Optimizer used for training. + """ + optimizer.step() + main_prog = paddle.static.default_main_program() + with paddle.fluid.dygraph.no_grad(): + ASPHelper._insert_sparse_mask_ops(main_prog, + optimizer._parameter_list) + + @classmethod + def _create_mask_variables(cls, main_program, startup_program, params): + r""" + Create sparse mask Tensors according to supported layers in :attr:`main_program`. + This function is called in second step of `ASPHelper._minimize` + + Args: + main_program (Program): Program with model definition and its parameters. + startup_program (Program): Program for initializing parameters. + params (list): Variable parameters. + """ + asp_info = cls._get_program_asp_info(main_program) + with program_guard(main_program, startup_program): + for param in params: + if ASPHelper._is_supported_layer(main_program, param.name): + if param.name not in asp_info.mask_vars: + mask_param = layers.create_parameter( + name=ASPHelper._get_mask_name(param.name), + shape=param.shape, + dtype=param.dtype, + default_initializer=ConstantInitializer(value=1.0)) + mask_param.stop_gradient = True + mask_param.trainable = False + asp_info.update_mask_vars(param.name, mask_param) + + @classmethod + def _insert_sparse_mask_ops(cls, main_program, params): + r""" + Insert masking ops in the end of parameters update. + This function is called in third step of `ASPHelper._minimize` + + Args: + main_program (Program): Program with model definition and its parameters. + params (list): Variable parameters. + """ + block = main_program.global_block() + asp_info = cls._get_program_asp_info(main_program) + for param in params: + if param.name in asp_info.mask_vars: + block.append_op(type='elementwise_mul', + inputs={ + "X": param, + 'Y': asp_info.mask_vars[param.name] + }, + outputs={'Out': param}, + attrs={ + 'axis': -1, + 'use_mkldnn': False, + OP_ROLE_KEY: int(OpRole.Optimize) + }) + + +class OptimizerWithSparsityGuarantee(object): + r""" + OptimizerWithSparsityGuarantee is a wrapper to decorate `minimize` function of given optimizer by `_minimize` of ASPHelper. + The decorated `minimize` function would do three things (exactly same as `ASPHelper._minimize`): + 1. Call `minimize` function of given optimizer. + 2. Call `ASPHelper._create_mask_variables` to create mask Variables. + 3. Call `ASPHelper._insert_sparse_mask_ops` to insert weight masking ops in the end of `loss`'s Program. + """ + + def __init__(self, optimizer): + self._optimizer = optimizer + + def __getattr__(self, item): + return getattr(self._optimizer, item) + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + r""" + This function is to call `ASPHelper.minimize()` and return its return + + Args: + loss (Variable): A Variable containing the value to minimize. + startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`. + parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated. + no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None. + Returns: + list: operators from :attr:`optimizer`.minimize(:attr:`loss`). + list: pairs of parameters and their gradients. + """ + return ASPHelper._minimize(self._optimizer, + loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + @dygraph_only + def step(self): + r""" + This function is a decorator of `step` function in `Optimizer`. + There are three steps: + + 1. Call :attr:`optimizer`.step() + 2. Mask parameters with sparse masks. + + *Note*: Please use `ASP.decorate` instead when applying distributed training with `Fleet`. + (Due to there is a invisiable graphs optimization in `Fleet.minimize()` which make training graph + cannot be modified anymore.) + + Args: + optimizer (Optimizer): A Optimizer used for training. + """ + ASPHelper._step(self._optimizer) + + @dygraph_only + def state_dict(self): + r""" + This function is a decorator of `state_dict` function in `Optimizer`. + + Returns: + state_dict(dict) : dict contains all the Tensor used by optimizer + """ + state_dict = self._optimizer.state_dict() + asp_info = ASPHelper._get_program_asp_info( + paddle.static.default_main_program()) + for param_name, var in asp_info.mask_vars.items(): + state_dict.update({ASPHelper._get_mask_name(param_name): var}) + return state_dict + + @dygraph_only + def set_state_dict(self, state_dict): + r""" + This function is a decorator of `set_state_dict` function in `Optimizer`. + Args: + state_dict(dict) : Dict contains all the Tensor needed by optimizer + Return: + None + """ + asp_info = ASPHelper._get_program_asp_info( + paddle.static.default_main_program()) + for param_name, var in asp_info.mask_vars.items(): + param_mask_name = ASPHelper._get_mask_name(param_name) + assert param_mask_name in state_dict, \ + "The {} is not found.".format(param_mask_name) + var.set_value(state_dict[param_mask_name]) + asp_info.update_masks(param_name, var.numpy()) + return self._optimizer.set_state_dict(state_dict) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/supported_layer_list.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/supported_layer_list.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b64f27eccc1ec5849f43ea1a57d584354e1527 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/supported_layer_list.py @@ -0,0 +1,123 @@ +# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2022 NVIDIA Corporation. 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. + +import numpy as np +import paddle +import copy +from paddle.fluid.contrib import sparsity +import threading +import logging +from ...log_helper import get_logger + +__all__ = ['add_supported_layer'] + +_logger = get_logger( + __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s' +) + + +def _default_pruning(weight_nparray, m, n, func_name, param_name): + + # if the to-be-pruned dimension's size is smaller than m, we don't prune it. This strong assertion is required by the inference from cuSparseLT. + shape = weight_nparray.shape + weight_pruned_nparray = copy.deepcopy(weight_nparray) + weight_sparse_mask = np.ones_like(weight_pruned_nparray) + exlude_cond_shape2 = len(shape) == 2 and shape[0] < m + exlude_cond_shape4 = len(shape) == 4 and shape[1] < m + if exlude_cond_shape2: + _logger.warning( + '{} is not pruned because the first dimension of {} is smaller than {}'.format( + param_name, shape, m + ) + ) + return weight_pruned_nparray, weight_sparse_mask + if exlude_cond_shape4: + _logger.warning( + '{} is not pruned because the second dimension of {} is smaller than {}'.format( + param_name, shape, m + ) + ) + return weight_pruned_nparray, weight_sparse_mask + + checked_func_name = sparsity.CheckMethod.get_checking_method(func_name) + + # The double transpose ops here make sure pruning direction consistent with cuSparseLt. + # SPMMA in cuSparseLt: D = (AxB) + C, where matrix A (mxk) is sparse matrix. + # cuSparseLt would prune matrix A along k dimension. + # In sparse training, layer weight matrices is viewed sparse matrix A, so + # the math fomula should be 'Act(WX + b)'. However, default fomula in PaddlePaddle + # is 'Act(XW + b)'. For enabling SPMMA, weights and inputs should be transposed + # for computing, Act( (W^T X^T)^T + b). Therefore, we have to prune alog k dimension + # of W^T, which is m dimension of W. Moreove, all mask generating functions in + # sparsity/utils is row-major pruning. That is the reason we have to transpose weight + # matrices beforce invoking create_mask. Then we transpose the result mask to make + # sure its shape to be the same as the input weight. + weight_sparse_mask = sparsity.create_mask( + weight_nparray.T, func_name=func_name, n=n, m=m + ).T + weight_pruned_nparray = np.multiply(weight_nparray, weight_sparse_mask) + assert sparsity.check_sparsity( + weight_pruned_nparray.T, n=n, m=m, func_name=checked_func_name + ), 'Pruning {} weight matrix failure!!!'.format(param_name) + return weight_pruned_nparray, weight_sparse_mask + + +# When value of given key in this DICT is None, +# ASP will call default pruning function in pruning stage. +_supported_layers_and_prune_func_map_lock = threading.Lock() +supported_layers_and_prune_func_map = {} + + +def add_supported_layer(layer, pruning_func=None): + r""" + + Add supported layers and its corresponding pruning function. + + Args: + name (string|Layer): The name or type of layer, needed to support. If layer is `Layer` then + it would be turn to string internally. ASP would use this name to match parameter's name and call + its the corresponding pruning function. + pruning_func (function, optional): a function type which receives five argument (weight_nparray, + m, n, func_name, param_name), weight_nparray is a nparray of weight, param_name is the name of weight, + m, n, and func_name, please see `prune_model` for details. + + """ + name = None + if isinstance(layer, str): + name = layer + elif isinstance(layer, paddle.fluid.dygraph.layers.Layer): + name = paddle.fluid.dygraph.layers._convert_camel_to_snake( + type(layer).__name__ + ) + elif issubclass(layer, paddle.fluid.dygraph.layers.Layer): + name = paddle.fluid.dygraph.layers._convert_camel_to_snake( + layer.__name__ + ) + else: + assert ( + "The type of layer should be string of Layer, but got {}!".format( + type(layer) + ) + ) + if pruning_func is None: + pruning_func = _default_pruning + _supported_layers_and_prune_func_map_lock.acquire() + supported_layers_and_prune_func_map.update({name: pruning_func}) + _supported_layers_and_prune_func_map_lock.release() + + +add_supported_layer('fc') +add_supported_layer('linear') +add_supported_layer('conv2d') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d706bd31e8effcad5e5c5a266577ed34b24f9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/contrib/sparsity/utils.py @@ -0,0 +1,618 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. +""" +Utilities of Auto SParsity (ASP). +""" + +from __future__ import print_function + +import sys +import math +import collections +import numpy as np +from enum import Enum +from itertools import permutations +import threading + +__all__ = [ + 'calculate_density', + 'check_mask_1d', + 'get_mask_1d', + 'check_mask_2d', + 'get_mask_2d_greedy', + 'get_mask_2d_best', + 'create_mask', + 'check_sparsity', + 'MaskAlgo', + 'CheckMethod', +] + + +class MaskAlgo(Enum): + r""" + A collection of all mask generating algorithms. + There currently are three algorithms, `MASK_1D`, `MASK_2D_GREEDY` and `MASK_2D_BEST` + """ + MASK_1D = 'get_mask_1d' + MASK_2D_GREEDY = 'get_mask_2d_greedy' + MASK_2D_BEST = 'get_mask_2d_best' + + +class CheckMethod(Enum): + r""" + A collection of all sparsity checking approaches. + There currently are two methods, `CHECK_1D` and `CHECK_2D` + """ + CHECK_1D = 'check_mask_1d' + CHECK_2D = 'check_mask_2d' + + @staticmethod + def get_checking_method(mask_algo): + r""" + Get sparsity checking method by mask generating algorithm. + + Args: + mask_algo (MaskAlgo): The algorithm of mask generating. + Returns: + CheckMethod: The corresponded sparsity checking method. + Examples: + .. code-block:: python + + import numpy as np + from paddle.static.sparsity import MaskAlgo + from paddle.fluid.contrib.sparsity import CheckMethod + + CheckMethod.get_checking_method(MaskAlgo.MASK_1D) + # CheckMethod.CHECK_1D + + CheckMethod.get_checking_method(MaskAlgo.MASK_2D_GREEDY) + # CheckMethod.CHECK_2D + + CheckMethod.get_checking_method(MaskAlgo.MASK_2D_BEST) + # CheckMethod.CHECK_2D + """ + assert isinstance( + mask_algo, MaskAlgo + ), "mask_algo should be MaskAlgo type" + if mask_algo == MaskAlgo.MASK_1D: + return CheckMethod.CHECK_1D + else: + return CheckMethod.CHECK_2D + + +def calculate_density(x): + r""" + + Return the density of the input tensor. + + Args: + x (nparray): The input tensor. + + Returns: + float, The density of :attr:`x`. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + x = np.array([[0, 1, 3, 0], + [1, 1, 0, 1]]) + paddle.incubate.asp.calculate_density(x) # 0.625 + + """ + x_flattened = x.flatten() + return float(np.nonzero(x_flattened)[0].size) / x_flattened.size + + +def _reshape_1d(mat, m): + r""" + Reshape the input 2D matrix to shape (-1, m). + If the second dimension of :attr:`mat` is not a multiples of :attr:`m`, + then this function would pad the remainder with 0 before reshaping. + + .. math:: + + remainder = mat.shape[1] % m + + Args: + mat (nparray): The input 2D matrix. + m (int): The second dimension of reshaped matrix. + Returns: + tuple: A pair of the reshaped and padded matrix and the shape of padded matrix (non-reshaping). + """ + assert len(mat.shape) == 2, "The input mat should be a 2D matrix!" + + remainder = mat.shape[1] % m + if mat.shape[1] % m > 0: + mat_padded = np.zeros((mat.shape[0], mat.shape[1] + (m - remainder))) + mat_padded[:, : mat.shape[1]] = mat + shape = mat_padded.shape + return mat_padded.reshape(-1, m), shape + else: + return mat.reshape(-1, m), mat.shape + + +def check_mask_1d(mat, n, m): + r""" + Check if every row of the input matrix :attr:`mat` is in 1D `n:m` sparse pattern. + This function would pad the second dimension of :attr:`mat` by zero + to be a multiples of :attr:`m` if necessary. + + 1D `n:m` sparse pattern: At least :attr:`n` zeros in every :math:`1 \times m` block. + + Args: + mat (nparray): The input matrix. + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + bool: True if every row of :attr:`mat` is in 1D n:m sparse pattern, else False. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + x = np.array([[0, 1, 3, 0], + [1, 0, 0, 1]]) + sparsity.check_mask_1d(x, 2, 4) # True + + x = np.array([[0, 1, 5, 4], + [1, 0, 0, 1]]) + sparsity.check_mask_1d(x, 2, 4) # False + + # x would be padded to shape (2, 8) + x = np.array([[0, 1, 0, 4, 6], + [1, 0, 0, 1, 7]]) + sparsity.check_mask_1d(x, 2, 4) # True + """ + if len(mat.shape) <= 1: + mat_flattern, shape = _reshape_1d(mat.reshape(1, mat.shape[0]), m) + else: + mat_flattern, shape = _reshape_1d(mat, m) + + for sub_mat in mat_flattern: + if np.nonzero(sub_mat)[0].size > (m - n): + return False + return True + + +def get_mask_1d(mat, n, m): + r""" + Generate 1D `n:m` sparse pattern mask of the input matrix :attr:`mat` + in row-directory. This function would pad the second dimension of :attr:`mat` + by zero to be a multiples of :attr:`m` before mask generation. + + 1D `n:m` sparse pattern: At least :attr:`n` zeros in every :math:`1 \times m` block. + + Args: + mat (nparray): The input matrix. + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + nparray: The 1D `n:m` sparse mask of :attr:`mat`. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + mat = np.array([[0, 1, 5, 4], + [2, 7, 3, 6]]) + mask = sparsity.get_mask_1d(mat, 2, 4) + # nparray([[0, 0, 1, 1], + # [0, 1, 0, 1]]) + sparsity.check_mask_1d(mask, 2, 4) # True + """ + mat_flattern, shape = _reshape_1d(mat, m) + + mask_flattern = np.ones_like(mat_flattern) + mask = np.ones_like(mat) + for i in range(mat_flattern.shape[0]): + sub_mat = mat_flattern[i] + min_order_indices = np.argsort(np.absolute(sub_mat)) + mask_flattern[i, min_order_indices[:n].tolist()] = 0 + mask_flattern = mask_flattern.reshape(shape) + mask[:, :] = mask_flattern[:, : mat.shape[1]] + return mask + + +def _reshape_2d(mat, m): + r""" + Reshape the input 2D matrix to shape (-1, :math:`m \times m`). + In each dimension of :attr:`mat`, if it is not a multiples of :attr:`m`, + then this function would pad the remainder with 0 before reshaping. + + .. math:: + + remainder_0 = mat.shape[0] % m \\ + remainder_1 = mat.shape[1] % m + + Args: + mat (nparray): The input 2D matrix. + m (int): The square root of second dimension of reshaped matrix. + Returns: + tuple: A pair of the reshaped and padded matrix and the shape of padded matrix (non-reshaping). + """ + assert len(mat.shape) == 2, "The input mat should be a 2D matrix!" + + remainder_0 = mat.shape[0] % m + remainder_1 = mat.shape[1] % m + + new_shape = ( + mat.shape[0] if remainder_0 == 0 else mat.shape[0] + (m - remainder_0), + mat.shape[1] if remainder_1 == 0 else mat.shape[1] + (m - remainder_1), + ) + mat_padded = np.zeros(new_shape) + mat_padded[: mat.shape[0], : mat.shape[1]] = mat + + mat_flattern = np.empty(new_shape).reshape(-1, m * m) + curr_idx = 0 + for row_start in range(0, mat_padded.shape[0], m): + row_end = row_start + m + for col_start in range(0, mat_padded.shape[1], m): + col_end = col_start + m + sub_mat = np.squeeze( + mat_padded[row_start:row_end, col_start:col_end].reshape(-1) + ) + mat_flattern[curr_idx] = sub_mat + curr_idx += 1 + return mat_flattern, mat_padded.shape + + +def check_mask_2d(mat, n, m): + r""" + Check if every :math:`m \times m` block of the input matrix :attr:`mat` is in 2D `n:m` sparse pattern. + This function would pad each dimension of :attr:`mat` by zero to be a multiples of + :attr:`m` if necessary. + + 2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block + under the constraint of at least :attr:`n` zeros for each row and column. + + Args: + mat (nparray): The input matrix. + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + bool: True if every :math:`m \times m` block of the input matrix :attr:`mat` is in 2D `n:m` sparse pattern, else False. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + x = np.array([[0, 8, 9, 0], + [9, 0, 0, 10], + [5, 0, 0, 6], + [0, 4, 6, 0]]) + sparsity.check_mask_2d(x, 2, 4) # True + + x = np.array([[0, 8, 0, 9], + [9, 0, 0, 10], + [0, 5, 0, 6], + [0, 4, 6, 0]]) + sparsity.check_mask_2d(x, 2, 4) # False + + # x would be padded to shape (8, 8) + x = np.array([[0, 8, 0, 9], + [9, 0, 7, 0], + [0, 5, 0, 6], + [3, 0, 6, 0], + [1, 1, 0, 1]]) + sparsity.check_mask_2d(x, 2, 4) # True + """ + mat_padded, shape = _reshape_2d(mat, m) + for sub_mat in mat_padded: + sub_mask = np.absolute(np.squeeze(sub_mat.reshape(m, m))) > 0 + if (np.sum(np.sum(sub_mask, axis=1) > (m - n)) != 0) and ( + np.sum(np.sum(sub_mask, axis=0) > (m - n)) != 0 + ): + return False + return True + + +def get_mask_2d_greedy(mat, n, m): + r""" + Greedily generate 2D `n:m` sparse pattern mask of the input matrix :attr:`mat`. + This function would pad each dimension of :attr:`mat` by zero to be a multiples of :attr:`m` before mask generation. + + 2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block + under the constraint of at least :attr:`n` zeros for each row and column. + Greedily generating: For each :math:`m \times m` block, selecting values to keep in descent order. + + Args: + mat (nparray): The input matrix. + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + nparray: The 2D `n:m` sparse mask of :attr:`mat`. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + mat = np.array([[9, 8, 3, 7], + [9, 2, 1, 10], + [5, 1, 3, 6], + [2, 4, 6, 1]]) + mask = sparsity.get_mask_2d_greedy(mat, 2, 4) + # nparray([[1. 1. 0. 0.] + # [1. 0. 0. 1.] + # [0. 0. 1. 1.] + # [0. 1. 1. 0.]]) + sparsity.check_mask_2d(mask, 2, 4) # True + """ + mat_padded, shape = _reshape_2d(mat, m) + mask_padded = np.zeros_like(mat_padded).reshape(-1, m, m) + + for idx in range(len(mat_padded)): + sub_mat = np.absolute(np.squeeze(mat_padded[idx])) + sub_mask = np.squeeze(mask_padded[idx]) + + min_order_1d_indices = np.argsort(sub_mat) + min_order_2d_indices = [ + (int(x / m), x % m) for x in min_order_1d_indices + ] + row_counter = collections.Counter() + col_counter = collections.Counter() + + for i in range(len(min_order_1d_indices) - 1, -1, -1): + matrix_entry = min_order_2d_indices[i] + if (row_counter[matrix_entry[0]] == n) or ( + col_counter[matrix_entry[1]] == n + ): + continue + + sub_mask[matrix_entry[0], matrix_entry[1]] = 1.0 + row_counter[matrix_entry[0]] += 1 + col_counter[matrix_entry[1]] += 1 + + mask = np.empty(shape) + curr_idx = 0 + for row_start in range(0, shape[0], m): + row_end = row_start + m + for col_start in range(0, shape[1], m): + col_end = col_start + m + mask[row_start:row_end, col_start:col_end] = mask_padded[curr_idx] + curr_idx += 1 + return mask[: mat.shape[0], : mat.shape[1]] + + +_valid_2d_patterns_lock = threading.Lock() +_valid_2d_patterns = {} + + +def _compute_valid_2d_patterns(n, m): + r""" + Compute all vaild 2D `n:m` sparse patterns. + + 2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block + under the constraint of at least :attr:`n` zeros for each row and column. + + Args: + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + dictionary: A dictionary with key: *m_n* (string) and value: all vaild 2D `n:m` sparse patterns. + """ + global _valid_2d_patterns_lock + global _valid_2d_patterns + + valid_key = '{}_{}'.format(m, n) + if valid_key in _valid_2d_patterns: + return _valid_2d_patterns[valid_key] + else: + patterns = np.zeros(m) + patterns[:n] = 1 + patterns = list(set(permutations(patterns.tolist()))) + patterns = patterns + patterns + patterns = np.asarray(list(set(permutations(patterns, m)))) + + valid = ( + ((patterns.sum(axis=1) <= n).sum(axis=1) == m) + .nonzero()[0] + .reshape(-1) + ) + valid_patterns = np.empty((valid.shape[0], m, m)) + valid_patterns[:] = patterns[valid[:]] + + _valid_2d_patterns_lock.acquire() + _valid_2d_patterns[valid_key] = valid_patterns + _valid_2d_patterns_lock.release() + + return valid_patterns + + +def get_mask_2d_best(mat, n, m): + r""" + Generate 2D `n:m` sparse pattern mask of the input matrix :attr:`mat` + to form sparse matrix with maximun L1 norm .This function would pad each + dimension of :attr:`mat` by zero to be a multiples of :attr:`m` before mask generation. + + 2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block + under the constraint of at least :attr:`n` zeros for each row and column. + + *Note*: L1 norm of sparse matrix from `Best` API is greater than or equal to the one from `Greedy`. + + Args: + mat (nparray): The input matrix. + n (int): n of `n:m` sparse pattern. + m (int): m of `n:m` sparse pattern. + Returns: + nparray: The 1D `n:m` sparse mask of :attr:`mat`. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + mat = np.array([[2, 8, 9, 9], + [9, 1, 3, 9], + [5, 6, 3, 9], + [2, 4, 6, 9]]) + mask_greedy = sparsity.get_mask_2d_greedy(mat, 2, 4) + mask_best = sparsity.get_mask_2d_best(mat, 2, 4) + print("L1 norm of `greedy` sparse matrix", np.multiply(mat, mask_greedy).sum()) # 56 + print("L1 norm of `best` sparse matrix", np.multiply(mat, mask_best).sum()) # 61 + """ + patterns = _compute_valid_2d_patterns(n, m) + + mat_flattern, shape = _reshape_2d(mat, m) + mask_flattern = np.ones_like(mat_flattern).reshape(-1, m, m) + pmax = np.argmax( + np.matmul(mat_flattern, patterns.reshape(patterns.shape[0], m * m).T), + axis=1, + ) + + mask_flattern[:] = patterns[pmax[:]] + mask = np.empty(shape) + + curr_idx = 0 + for row_start in range(0, shape[0], m): + row_end = row_start + m + for col_start in range(0, shape[1], m): + col_end = col_start + m + mask[row_start:row_end, col_start:col_end] = mask_flattern[curr_idx] + curr_idx += 1 + return mask[: mat.shape[0], : mat.shape[1]] + + +def create_mask(tensor, func_name=MaskAlgo.MASK_1D, n=2, m=4): + r""" + Create `n:m` sparse pattern mask of the input tensor via function given by :attr:`func_name`. + Currently only support tensor with dimension less than or equal to 4. + + Args: + tensor (nparray): The input tensor. + func_name (MaskAlgo, optional): The function name to generate spase mask. Default is `MaskAlgo.MASK_1D`. All options please refer to `MaskAlgo`. + n (int, optional): n of `n:m` sparse pattern. Default is 2. + m (int, optional): m of `n:m` sparse pattern. Default is 4. + Returns: + nparray: The `n:m` sparse mask of :attr:`tensor` generated by :attr:`func_name`. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + tensor = np.array([[2, 8, 9, 9], + [9, 1, 3, 9], + [5, 6, 3, 9], + [2, 4, 6, 9]]) + mask_1d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_1D) + # nparray([[0 0 1 1], + # [1 0 0 1], + # [0 1 0 1], + # [0 0 1 1]]) + mask_2d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_2D_BEST) + # nparray([[0 1 1 0], + # [1 0 0 1], + # [1 1 0 0], + # [0 0 1 1]]) + """ + shape = tensor.shape + dtype = tensor.dtype + t = tensor.astype(float) + + assert isinstance(func_name, MaskAlgo), ( + "func_name argumet of create_mask is only accepted as type MaskAlgo. " + "But got {}".format(type(func_name)) + ) + func = getattr(sys.modules[__name__], func_name.value, None) + if len(shape) == 1: + t = t.reshape(1, shape[0]) + elif len(shape) == 2: + t = t.reshape(shape[0], shape[1]) + elif len(shape) == 3: + t = t.reshape(shape[0] * shape[1], shape[2]) + # 4d-tensor conv (h, w, in, out) -> (h*w*out, in) in GemmConvKernel Op + elif len(shape) == 4: + t = t.transpose([0, 1, 3, 2]).reshape( + shape[0] * shape[1] * shape[3], shape[2] + ) + mask = func(t, n=n, m=m) + return ( + mask.reshape([shape[0], shape[1], shape[3], shape[2]]) + .transpose([0, 1, 3, 2]) + .astype(dtype) + ) + else: + raise ValueError( + "The dimension of input tensor is not supported in create_mask, " + "Only dimension < 4 is supported but got {}".format(len(shape)) + ) + + mask = func(t, n=n, m=m) + return mask.reshape(shape).astype(dtype) + + +def check_sparsity(tensor, func_name=CheckMethod.CHECK_1D, n=2, m=4): + r""" + Check if input tensor is in `n:m` sparse pattern via function given by :attr:`func_name`. + Currently only support tensor with dimension less than or equal to 4. + + Args: + tensor (nparray): The input tensor. + func_name (CheckMethod, optional): The function name to generate spase mask. Default is `CheckMethod.CHECK_1D`. All options please refer to `CheckMethod`. + n (int, optional): n of `n:m` sparse pattern. Default is 2. + m (int, optional): m of `n:m` sparse pattern. Default is 4. + Returns: + bool: True if tensor pass checking of function given by :attr:`func_name`, else False. + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid.contrib.sparsity as sparsity + + tensor = np.array([[2, 8, 9, 9], + [9, 1, 3, 9], + [5, 6, 3, 9], + [2, 4, 6, 9]]) + mask_1d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_1D) + # nparray([[0 0 1 1], + # [1 0 0 1], + # [0 1 0 1], + # [0 0 1 1]]) + sparsity.check_sparsity(mask_1d, func_name=sparsity.CheckMethod.CHECK_1D) # True + sparsity.check_sparsity(mask_1d, func_name=sparsity.CheckMethod.CHECK_2D) # False + """ + shape = tensor.shape + t = tensor.astype(float) + + assert type(func_name) == CheckMethod, ( + "func_name argumet of check_sparsity is only accepted as type CheckMethod. " + "But got {}".format(type(func_name)) + ) + func = getattr(sys.modules[__name__], func_name.value, None) + if len(shape) == 1: + t = t.reshape(1, shape[0]) + elif len(shape) == 2: + t = t.reshape(shape[0], shape[1]) + elif len(shape) == 3: + t = t.reshape(shape[0] * shape[1], shape[2]) + # 4d-tensor conv (h, w, in, out) -> (h*w*out, in) in GemmConvKernel Op + elif len(shape) == 4: + t = t.transpose([0, 1, 3, 2]).reshape( + [shape[0] * shape[1] * shape[3], shape[2]] + ) + else: + raise ValueError( + "The dimension of input tensor is not supported in create_mask, " + "Only dimension < 4 is supported but got {}".format(len(shape)) + ) + + return func(t, n=n, m=m) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/core.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/core.py new file mode 100644 index 0000000000000000000000000000000000000000..6c642dba67a69522dadd84193ac47c7299b05f1b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/core.py @@ -0,0 +1,376 @@ +# 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. + +from __future__ import print_function + +import site +import sys +import os +import warnings +import platform + +has_paddle_dy_lib = False + +dy_lib_name = 'libpaddle' +dy_lib_suffix = 'so' +if os.name == 'nt': + dy_lib_suffix = 'pyd' + +current_path = os.path.abspath(os.path.dirname(__file__)) +if os.path.exists(current_path + os.sep + dy_lib_name + '.' + dy_lib_suffix): + has_paddle_dy_lib = True + +try: + if os.name == 'nt': + third_lib_path = current_path + os.sep + '..' + os.sep + 'libs' + # Will load shared library from 'path' on windows + os.environ['path'] = ( + current_path + ';' + third_lib_path + ';' + os.environ['path'] + ) + sys.path.insert(0, third_lib_path) + # Note: from python3.8, PATH will not take effect + # https://github.com/python/cpython/pull/12302 + # Use add_dll_directory to specify dll resolution path + if sys.version_info[:2] >= (3, 8): + os.add_dll_directory(third_lib_path) + +except ImportError as e: + from .. import compat as cpt + + if os.name == 'nt': + executable_path = os.path.abspath(os.path.dirname(sys.executable)) + raise ImportError( + """NOTE: You may need to run \"set PATH=%s;%%PATH%%\" + if you encounters \"DLL load failed\" errors. If you have python + installed in other directory, replace \"%s\" with your own + directory. The original error is: \n %s""" + % (executable_path, executable_path, cpt.get_exception_message(e)) + ) + else: + raise ImportError( + """NOTE: You may need to run \"export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH\" + if you encounters \"libmkldnn.so not found\" errors. If you have python + installed in other directory, replace \"/usr/local/lib\" with your own + directory. The original error is: \n""" + + cpt.get_exception_message(e) + ) +except Exception as e: + raise e + + +def avx_supported(): + """ + Whether current system(Linux, MacOS, Windows) is supported with AVX. + """ + from .. import compat as cpt + + sysstr = platform.system().lower() + has_avx = False + if sysstr == 'linux': + try: + pipe = os.popen('cat /proc/cpuinfo | grep -i avx') + has_avx = pipe.read() != '' + pipe.close() + except Exception as e: + sys.stderr.write( + 'Can not get the AVX flag from /proc/cpuinfo.\n' + 'The original error is: %s\n' % cpt.get_exception_message(e) + ) + return has_avx + elif sysstr == 'darwin': + try: + pipe = os.popen('sysctl machdep.cpu.features | grep -i avx') + has_avx = pipe.read() != '' + pipe.close() + except Exception as e: + sys.stderr.write( + 'Can not get the AVX flag from machdep.cpu.features.\n' + 'The original error is: %s\n' % cpt.get_exception_message(e) + ) + if not has_avx: + import subprocess + + pipe = subprocess.Popen( + 'sysctl machdep.cpu.leaf7_features | grep -i avx', + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + _ = pipe.communicate() + has_avx = True if pipe.returncode == 0 else False + return has_avx + elif sysstr == 'windows': + import ctypes + + ONE_PAGE = ctypes.c_size_t(0x1000) + + def asm_func(code_str, restype=ctypes.c_uint32, argtypes=()): + # Call the code_str as a function + # Alloc 1 page to ensure the protection + pfnVirtualAlloc = ctypes.windll.kernel32.VirtualAlloc + pfnVirtualAlloc.restype = ctypes.c_void_p + MEM_COMMIT = ctypes.c_ulong(0x1000) + PAGE_READWRITE = ctypes.c_ulong(0x4) + address = pfnVirtualAlloc( + None, ONE_PAGE, MEM_COMMIT, PAGE_READWRITE + ) + if not address: + raise Exception("Failed to VirtualAlloc") + + # Copy the code into the memory segment + memmove = ctypes.CFUNCTYPE( + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_size_t, + )(ctypes._memmove_addr) + if memmove(address, code_str, len(code_str)) < 0: + raise Exception("Failed to memmove") + + # Enable execute permissions + PAGE_EXECUTE = ctypes.c_ulong(0x10) + pfnVirtualProtect = ctypes.windll.kernel32.VirtualProtect + res = pfnVirtualProtect( + ctypes.c_void_p(address), + ONE_PAGE, + PAGE_EXECUTE, + ctypes.byref(ctypes.c_ulong(0)), + ) + if not res: + raise Exception("Failed VirtualProtect") + + # Flush instruction cache + pfnGetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess + pfnGetCurrentProcess.restype = ctypes.c_void_p + prochandle = ctypes.c_void_p(pfnGetCurrentProcess()) + res = ctypes.windll.kernel32.FlushInstructionCache( + prochandle, ctypes.c_void_p(address), ONE_PAGE + ) + if not res: + raise Exception("Failed FlushInstructionCache") + + # Cast the memory to function + functype = ctypes.CFUNCTYPE(restype, *argtypes) + func = functype(address) + return func, address + + # http://en.wikipedia.org/wiki/CPUID#EAX.3D1:_Processor_Info_and_Feature_Bits + # mov eax,0x1; cpuid; mov cx, ax; ret + code_str = b"\xB8\x01\x00\x00\x00\x0f\xa2\x89\xC8\xC3" + avx_bit = 28 + retval = 0 + try: + # Convert the code_str into a function that returns uint + func, address = asm_func(code_str) + retval = func() + ctypes.windll.kernel32.VirtualFree( + ctypes.c_void_p(address), ctypes.c_size_t(0), ONE_PAGE + ) + except Exception as e: + sys.stderr.write( + 'Failed getting the AVX flag on Windows.\n' + 'The original error is: %s\n' % cpt.get_exception_message(e) + ) + return (retval & (1 << avx_bit)) > 0 + else: + sys.stderr.write('Do not get AVX flag on %s\n' % sysstr) + return False + + +def run_shell_command(cmd): + import subprocess + + out, err = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True + ).communicate() + if err: + return None + else: + return out.decode('utf-8').strip() + + +def get_dso_path(core_so, dso_name): + if core_so and dso_name: + return run_shell_command( + "ldd %s|grep %s|awk '{print $3}'" % (core_so, dso_name) + ) + else: + return None + + +def load_dso(dso_absolute_path): + if dso_absolute_path: + try: + from ctypes import cdll + + cdll.LoadLibrary(dso_absolute_path) + except: + warnings.warn("Load {} failed".format(dso_absolute_path)) + + +def pre_load(dso_name): + if has_paddle_dy_lib: + core_so = current_path + os.sep + dy_lib_name + '.' + dy_lib_suffix + else: + core_so = None + dso_path = get_dso_path(core_so, dso_name) + load_dso(dso_path) + + +def get_libc_ver(): + ldd_glibc = run_shell_command("ldd --version | awk '/ldd/{print $NF}'") + if ldd_glibc is not None: + return ("glibc", ldd_glibc) + + ldd_musl = run_shell_command("ldd 2>&1 | awk '/Version/{print $NF}'") + if ldd_musl is not None: + return ("musl", ldd_musl) + return (None, None) + + +def less_than_ver(a, b): + if a is None or b is None: + return False + + import re + import operator + + def to_list(s): + s = re.sub(r'(\.0+)+$', '', s) + return [int(x) for x in s.split('.')] + + return operator.lt(to_list(a), to_list(b)) + + +# NOTE(zhiqiu): An error may occurs when import paddle in linux platform with glibc < 2.22, +# the error message of which is "dlopen: cannot load any more object with static TLS". +# This happens when: +# (1) the number of dynamic shared librarys (DSO) loaded > 14, +# (2) after that, load a dynamic shared library (DSO) with static TLS. +# For paddle, the problem is that 'libgomp' is a DSO with static TLS, and it is loaded after 14 DSOs. +# So, here is a tricky way to solve the problem by pre load 'libgomp' before 'libpaddle.so'. +# The final solution is to upgrade glibc to > 2.22 on the target system. +if platform.system().lower() == 'linux': + libc_type, libc_ver = get_libc_ver() + if libc_type == 'glibc' and less_than_ver(libc_ver, '2.23'): + try: + pre_load('libgomp') + except Exception as e: + # NOTE(zhiqiu): do not abort if failed, since it may success when import libpaddle.so + sys.stderr.write('Error: Can not preload libgomp.so') + +try: + from . import libpaddle + + if avx_supported() and not libpaddle.is_compiled_with_avx(): + sys.stderr.write( + "Hint: Your machine support AVX, but the installed paddlepaddle doesn't have avx core. " + "Hence, no-avx core with worse preformance will be imported.\nIf you like, you could " + "reinstall paddlepaddle by 'python -m pip install --force-reinstall paddlepaddle-gpu[==version]' " + "to get better performance.\n" + ) + + # assign tensor alias + libpaddle.LoDTensor = libpaddle.Tensor + + from .libpaddle import * + from .libpaddle import __doc__, __file__, __name__, __package__ + from .libpaddle import __unittest_throw_exception__ + from .libpaddle import _append_python_callable_object_and_return_id + from .libpaddle import _cleanup, _Scope + from .libpaddle import _get_use_default_grad_op_desc_maker_ops + from .libpaddle import _get_all_register_op_kernels + from .libpaddle import _is_program_version_supported + from .libpaddle import _set_eager_deletion_mode + from .libpaddle import _get_eager_deletion_vars + from .libpaddle import _set_fuse_parameter_group_size + from .libpaddle import _set_fuse_parameter_memory_size + from .libpaddle import _is_dygraph_debug_enabled + from .libpaddle import _dygraph_debug_level + from .libpaddle import _switch_tracer + from .libpaddle import _set_paddle_lib_path + from .libpaddle import _create_loaded_parameter + from .libpaddle import _cuda_synchronize + from .libpaddle import _is_compiled_with_heterps + from .libpaddle import _promote_types_if_complex_exists + from .libpaddle import _set_cached_executor_build_strategy + from .libpaddle import _device_synchronize + from .libpaddle import _get_current_stream + from .libpaddle import _Profiler, _ProfilerResult, _RecordEvent + from .libpaddle import _set_current_stream + from .libpaddle import _get_phi_kernel_name + + if sys.platform != 'win32': + from .libpaddle import _set_process_pids + from .libpaddle import _erase_process_pids + from .libpaddle import _set_process_signal_handler + from .libpaddle import _throw_error_if_process_failed + from .libpaddle import _convert_to_tensor_list + from .libpaddle import _array_to_share_memory_tensor + from .libpaddle import _cleanup_mmap_fds + from .libpaddle import _remove_tensor_list_mmap_fds +except Exception as e: + if has_paddle_dy_lib: + sys.stderr.write( + 'Error: Can not import paddle core while this file exists: ' + + current_path + + os.sep + + 'libpaddle.' + + dy_lib_suffix + + '\n' + ) + if not avx_supported() and libpaddle.is_compiled_with_avx(): + sys.stderr.write( + "Error: Your machine doesn't support AVX, but the installed PaddlePaddle is avx core, " + "you should reinstall paddlepaddle with no-avx core.\n" + ) + raise e + + +def set_paddle_custom_device_lib_path(lib_path): + if os.environ.get('CUSTOM_DEVICE_ROOT', None) is not None: + # use setted environment value + return + if os.path.exists(lib_path): + # set CUSTOM_DEVICE_ROOT default path + os.environ['CUSTOM_DEVICE_ROOT'] = os.path.normpath(lib_path) + else: + os.environ['CUSTOM_DEVICE_ROOT'] = '' + + +# set paddle lib path +def set_paddle_lib_path(): + site_dirs = ( + site.getsitepackages() + if hasattr(site, 'getsitepackages') + else [x for x in sys.path if 'site-packages' in x] + ) + for site_dir in site_dirs: + lib_dir = os.path.sep.join([site_dir, 'paddle', 'libs']) + if os.path.exists(lib_dir): + _set_paddle_lib_path(lib_dir) + set_paddle_custom_device_lib_path( + os.path.sep.join([lib_dir, '..', '..', 'paddle-plugins']) + ) + return + if hasattr(site, 'USER_SITE'): + lib_dir = os.path.sep.join([site.USER_SITE, 'paddle', 'libs']) + if os.path.exists(lib_dir): + _set_paddle_lib_path(lib_dir) + set_paddle_custom_device_lib_path( + os.path.sep.join([lib_dir, '..', '..', 'paddle-plugins']) + ) + + +set_paddle_lib_path() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data.py new file mode 100644 index 0000000000000000000000000000000000000000..4a15b6a8ea272be38d5158a660932dc4ae1d41a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data.py @@ -0,0 +1,125 @@ +# 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. + +import numpy as np +import six + +from paddle.fluid import core +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.data_feeder import check_dtype, check_type +from ..utils import deprecated +from paddle.fluid.framework import static_only + +__all__ = ['data'] + + +@static_only +@deprecated(since="2.0.0", update_to="paddle.static.data") +def data(name, shape, dtype='float32', lod_level=0): + """ + **Data Layer** + + This function creates a variable on the global block. The global variable + can be accessed by all the following operators in the graph. The variable + is a placeholder that could be fed with input, such as Executor can feed + input into the variable. + + Note: + `paddle.fluid.layers.data` is deprecated. It will be removed in a + future version. Please use this `paddle.fluid.data`. + + The `paddle.fluid.layers.data` set shape and dtype at compile time but + does NOT check the shape or the dtype of fed data, this + `paddle.fluid.data` checks the shape and the dtype of data fed by + Executor or ParallelExecutor during run time. + + To feed variable size inputs, users can set None or -1 on the variable + dimension when using :code:`paddle.fluid.data`, or feed variable size + inputs directly to :code:`paddle.fluid.layers.data` and PaddlePaddle + will fit the size accordingly. + + The default :code:`stop_gradient` attribute of the Variable created by + this API is true, which means the gradient won't be passed backward + through the data Variable. Set :code:`var.stop_gradient = False` If + user would like to pass backward gradient. + + Args: + name (str): The name/alias of the variable, see :ref:`api_guide_Name` + for more details. + shape (list|tuple): List|Tuple of integers declaring the shape. You can + set "None" or -1 at a dimension to indicate the dimension can be of any + size. For example, it is useful to set changeable batch size as "None" or -1. + dtype (np.dtype|VarType|str, optional): The type of the data. Supported + dtype: bool, float16, float32, float64, int8, int16, int32, int64, + uint8. Default: float32. + lod_level (int, optional): The LoD level of the LoDTensor. Usually users + don't have to set this value. For more details about when and how to + use LoD level, see :ref:`user_guide_lod_tensor` . Default: 0. + + Returns: + Variable: The global variable that gives access to the data. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + paddle.enable_static() + + # Creates a variable with fixed size [3, 2, 1] + # User can only feed data of the same shape to x + x = fluid.data(name='x', shape=[3, 2, 1], dtype='float32') + + # Creates a variable with changeable batch size -1. + # Users can feed data of any batch size into y, + # but size of each data sample has to be [2, 1] + y = fluid.data(name='y', shape=[-1, 2, 1], dtype='float32') + + z = x + y + + # In this example, we will feed x and y with np-ndarray "1" + # and fetch z, like implementing "1 + 1 = 2" in PaddlePaddle + feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32) + + exe = fluid.Executor(fluid.CPUPlace()) + out = exe.run(fluid.default_main_program(), + feed={ + 'x': feed_data, + 'y': feed_data + }, + fetch_list=[z.name]) + + # np-ndarray of shape=[3, 2, 1], dtype=float32, whose elements are 2 + print(out) + + """ + helper = LayerHelper('data', **locals()) + + check_type(name, 'name', (six.binary_type, six.text_type), 'data') + check_type(shape, 'shape', (list, tuple), 'data') + + shape = list(shape) + for i in six.moves.range(len(shape)): + if shape[i] is None: + shape[i] = -1 + + return helper.create_global_variable(name=name, + shape=shape, + dtype=dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + stop_gradient=True, + lod_level=lod_level, + is_data=True, + need_check_feed=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feed_desc.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feed_desc.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4ce735fca8164d9ff6c7d019197ad432960f74 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feed_desc.py @@ -0,0 +1,257 @@ +# Copyright (c) 2018 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. + +from paddle.fluid.proto import data_feed_pb2 +from google.protobuf import text_format + +__all__ = ['DataFeedDesc'] + + +class DataFeedDesc(object): + """ + :api_attr: Static Graph + + Datafeed descriptor, describing input training data format. This class is + currently only used for AsyncExecutor (See comments for class AsyncExecutor + for a brief introduction) + + DataFeedDesc shall be initialized from a valid protobuf message from disk. + + See :code:`paddle/fluid/framework/data_feed.proto` for message definition. + A typical message might look like: + + .. code-block:: python + + import paddle.fluid as fluid + f = open("data.proto", "w") + print >> f, 'name: "MultiSlotDataFeed"' + print >> f, 'batch_size: 2' + print >> f, 'multi_slot_desc {' + print >> f, ' slots {' + print >> f, ' name: "words"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, ' slots {' + print >> f, ' name: "label"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, '}' + f.close() + data_feed = fluid.DataFeedDesc('data.proto') + + However, users usually shouldn't care about the message format; instead, + they are encouraged to use :code:`Data Generator` as a tool to generate a + valid data description, in the process of converting their raw log files to + training files acceptable to AsyncExecutor. + + DataFeedDesc can also be changed during runtime. Once you got familiar with + what each field mean, you can modify it to better suit your need. E.g.: + + .. code-block:: python + + import paddle.fluid as fluid + data_feed = fluid.DataFeedDesc('data.proto') + data_feed.set_batch_size(128) + data_feed.set_dense_slots('wd') # The slot named 'wd' will be dense + data_feed.set_use_slots('wd') # The slot named 'wd' will be used + + Finally, the content can be dumped out for debugging purpose: + + .. code-block:: python + + print(data_feed.desc()) + + Args: + proto_file(string): Disk file containing a data feed description. + + """ + + def __init__(self, proto_file): + self.proto_desc = data_feed_pb2.DataFeedDesc() + self.proto_desc.pipe_command = "cat" + with open(proto_file, 'r') as f: + text_format.Parse(f.read(), self.proto_desc) + if self.proto_desc.name == "MultiSlotDataFeed": + self.__name_to_index = { + slot.name: i + for i, slot in enumerate(self.proto_desc.multi_slot_desc.slots) + } + + def set_batch_size(self, batch_size): + """ + Set :attr:`batch_size` in :ref:`api_fluid_DataFeedDesc` . :attr:`batch_size` can be changed during training. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + f = open("data.proto", "w") + print >> f, 'name: "MultiSlotDataFeed"' + print >> f, 'batch_size: 2' + print >> f, 'multi_slot_desc {' + print >> f, ' slots {' + print >> f, ' name: "words"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, ' slots {' + print >> f, ' name: "label"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, '}' + f.close() + data_feed = fluid.DataFeedDesc('data.proto') + data_feed.set_batch_size(128) + + Args: + batch_size (int): The number of batch size. + + Returns: + None. + + """ + self.proto_desc.batch_size = batch_size + + def set_dense_slots(self, dense_slots_name): + """ + Set slots in :attr:`dense_slots_name` as dense slots. **Note: In default, all slots are sparse slots.** + + Features for a dense slot will be fed into a Tensor, while those for a + sparse slot will be fed into a LoDTensor. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + f = open("data.proto", "w") + print >> f, 'name: "MultiSlotDataFeed"' + print >> f, 'batch_size: 2' + print >> f, 'multi_slot_desc {' + print >> f, ' slots {' + print >> f, ' name: "words"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, ' slots {' + print >> f, ' name: "label"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, '}' + f.close() + data_feed = fluid.DataFeedDesc('data.proto') + data_feed.set_dense_slots(['words']) + + Args: + dense_slots_name (list(str)): a list of slot names which will be set dense. + + Returns: + None. + + """ + if self.proto_desc.name != "MultiSlotDataFeed": + raise ValueError( + "Only MultiSlotDataFeed needs set_dense_slots, please check your datafeed.proto" + ) + for name in dense_slots_name: + self.proto_desc.multi_slot_desc.slots[ + self.__name_to_index[name]].is_dense = True + + def set_use_slots(self, use_slots_name): + """ + Set if a specific slot will be used for training. A dataset shall + contain a lot of features, through this function one can select which + ones will be used for a specific model. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + f = open("data.proto", "w") + print >> f, 'name: "MultiSlotDataFeed"' + print >> f, 'batch_size: 2' + print >> f, 'multi_slot_desc {' + print >> f, ' slots {' + print >> f, ' name: "words"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, ' slots {' + print >> f, ' name: "label"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, '}' + f.close() + data_feed = fluid.DataFeedDesc('data.proto') + data_feed.set_use_slots(['words']) + + Args: + use_slots_name: a list of slot names which will be used in training + + Note: + Default is not used for all slots + """ + if self.proto_desc.name != "MultiSlotDataFeed": + raise ValueError( + "Only MultiSlotDataFeed needs set_use_slots, please check your datafeed.proto" + ) + for name in use_slots_name: + self.proto_desc.multi_slot_desc.slots[ + self.__name_to_index[name]].is_used = True + + def desc(self): + """ + Returns a protobuf message for this DataFeedDesc + + Example: + .. code-block:: python + + import paddle.fluid as fluid + f = open("data.proto", "w") + print >> f, 'name: "MultiSlotDataFeed"' + print >> f, 'batch_size: 2' + print >> f, 'multi_slot_desc {' + print >> f, ' slots {' + print >> f, ' name: "words"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, ' slots {' + print >> f, ' name: "label"' + print >> f, ' type: "uint64"' + print >> f, ' is_dense: false' + print >> f, ' is_used: true' + print >> f, ' }' + print >> f, '}' + f.close() + data_feed = fluid.DataFeedDesc('data.proto') + print(data_feed.desc()) + + Returns: + A string message + """ + return text_format.MessageToString(self.proto_desc) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feeder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feeder.py new file mode 100644 index 0000000000000000000000000000000000000000..876d4772462f50a60e8bc56a865aae24ffea5db4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/data_feeder.py @@ -0,0 +1,579 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from . import core +import numpy as np +import os +import six +from six.moves import zip, range, xrange +import multiprocessing +import warnings + +from .framework import Variable, default_main_program, _current_expected_place, _non_static_mode, _in_eager_without_dygraph_check +from .framework import _cpu_num, _cuda_ids + +__all__ = ['DataFeeder'] + +_PADDLE_DTYPE_2_NUMPY_DTYPE = { + core.VarDesc.VarType.BOOL: 'bool', + core.VarDesc.VarType.FP16: 'float16', + core.VarDesc.VarType.BF16: 'uint16', + core.VarDesc.VarType.FP32: 'float32', + core.VarDesc.VarType.FP64: 'float64', + core.VarDesc.VarType.INT8: 'int8', + core.VarDesc.VarType.INT16: 'int16', + core.VarDesc.VarType.INT32: 'int32', + core.VarDesc.VarType.INT64: 'int64', + core.VarDesc.VarType.UINT8: 'uint8', + core.VarDesc.VarType.COMPLEX64: 'complex64', + core.VarDesc.VarType.COMPLEX128: 'complex128', +} + + +def convert_dtype(dtype): + if isinstance(dtype, core.VarDesc.VarType): + if dtype in _PADDLE_DTYPE_2_NUMPY_DTYPE: + return _PADDLE_DTYPE_2_NUMPY_DTYPE[dtype] + elif isinstance(dtype, type): + if dtype in [ + bool, np.float16, np.uint16, np.float32, np.float64, np.int8, + np.int16, np.int32, np.int64, np.uint8, np.complex64, + np.complex128 + ]: + return dtype.__name__ + else: + if dtype in [ + 'bool', 'float16', 'uint16', 'float32', 'float64', 'int8', + 'int16', 'int32', 'int64', 'uint8', 'complex64', 'complex128', + u'bool', u'float16', u'uint16', u'float32', u'float64', u'int8', + u'int16', u'int32', u'int64', u'uint8', u'complex64', + u'complex128' + ]: + # this code is a little bit dangerous, since error could happen + # when casting no-ascii code to str in python2. + # but since the set itself is limited, so currently, it is good. + # however, jointly supporting python2 and python3, (as well as python4 maybe) + # may still be a long-lasting problem. + return str(dtype) + # NOTE(zhangbo): Now numpy does not support bfloat, and paddle use uint16 to represent bfloat16, and there binaries are consistent. + if dtype in ['bfloat16']: + return 'uint16' + + raise TypeError( + "dtype must be any of [bool, float16, uint16, float32, float64, int8, int16, " + "int32, int64, uint8, complex64, complex128], but received %s" % dtype) + + +def check_variable_and_dtype(input, + input_name, + expected_dtype, + op_name, + extra_message=''): + check_type(input, input_name, Variable, op_name, extra_message) + check_dtype(input.dtype, input_name, expected_dtype, op_name, extra_message) + + +def check_type(input, input_name, expected_type, op_name, extra_message=''): + # NOTE [ Why skip dynamic graph check ]: + # 1. If the input type / dtype of a layer is wrong, it will be reported + # directly on that line. User can easily print the relevant information + # on which line. It is easier to debug, so there is no need to check + # in dynamic graph mode. + # 2. Performance considerations. Because these checks are executed at + # each step in dynamic graph mode, it will bring a heavy performance burden. + if _non_static_mode(): + return + + # NOTE: `in_declarative_mode` is used to determined whether this op is called under + # @declarative in transformation from dygrah to static layer. We add VarBase in + # expected_type to skip checking because varBase may be created and used in unusual way. + from .dygraph.base import in_declarative_mode + # Need a better design to be fix this. + if in_declarative_mode(): + if not isinstance(expected_type, tuple): + expected_type = (expected_type, ) + expected_type += (core.VarBase, ) + if _in_eager_without_dygraph_check(): + expected_type += (core.eager.Tensor, ) + elif isinstance(input, core.VarBase): + raise TypeError( + "Please use `with fluid.dygraph.guard()` as context or `fluid.enable_dygraph()` to switch to imperative mode firstly. " + "Because received '{}' in {} is a imperative Variable.".format( + input_name, op_name)) + elif hasattr(core, "eager"): + if isinstance(input, core.eager.Tensor): + raise TypeError( + "Please use `with fluid.dygraph.guard()` as context or `fluid.enable_dygraph()` to switch to imperative mode firstly. " + "Because received '{}' in {} is a imperative Variable.".format( + input_name, op_name)) + if not isinstance(input, expected_type): + raise TypeError( + "The type of '%s' in %s must be %s, but received %s. %s" % + (input_name, op_name, expected_type, type(input), extra_message)) + + +def check_dtype(input_dtype, + input_name, + expected_dtype, + op_name, + extra_message=''): + # See NOTE [ Why skip dynamic graph check ] + if _non_static_mode(): + return + if convert_dtype(input_dtype) in ['float16']: + warnings.warn( + "The data type of '%s' in %s only support float16 in GPU now. %s" % + (input_name, op_name, extra_message)) + if convert_dtype(input_dtype) in ['uint16'] and op_name not in [ + 'reshape', 'lookup_table', 'scale' + ]: + warnings.warn( + "The data type of '%s' in %s only support bfloat16 in OneDNN now. %s" + % (input_name, op_name, extra_message)) + if convert_dtype(input_dtype) not in expected_dtype: + raise TypeError( + "The data type of '%s' in %s must be %s, but received %s. %s" % + (input_name, op_name, expected_dtype, convert_dtype(input_dtype), + extra_message)) + + +def check_shape(shape, + op_name, + expected_shape_type=(list, tuple, Variable), + expected_element_type=(int, Variable), + expected_tensor_dtype=('int32', 'int64')): + # See NOTE [ Why skip dynamic graph check ] + if _non_static_mode(): + return + check_type(shape, 'shape', expected_shape_type, op_name) + if expected_element_type is not None and not isinstance(shape, Variable): + for item in shape: + check_type(item, 'element of shape', expected_element_type, op_name) + if expected_tensor_dtype is not None and isinstance(item, Variable): + check_dtype( + item.dtype, 'element of shape', expected_tensor_dtype, + op_name, + 'If element of shape is Tensor, its data type should be {}'. + format(', '.join(expected_tensor_dtype))) + if expected_tensor_dtype is not None and isinstance(shape, Variable): + check_dtype(shape.dtype, 'shape', expected_tensor_dtype, op_name) + + +class DataToLoDTensorConverter(object): + + def __init__(self, place, lod_level, shape, dtype): + self.place = place + self.lod_level = lod_level + self.shape = shape + negtive_count = 0 + for s in self.shape: + if s < 0: + negtive_count += 1 + if negtive_count > 1: + self.shape = None + break + self.dtype = convert_dtype(dtype) + self._reset() + + def _reset(self): + self.data = [] + self.lod = [[] for _ in six.moves.range(self.lod_level)] + + def feed(self, data): + self._feed_impl_(data, self.lod, self.lod_level) + + def _feed_impl_(self, data, lod, lod_level): + if lod_level == 0: + self.data.append(data) + else: + lod[0].append(len(data)) + for each_data in data: + self._feed_impl_(each_data, lod[1:], lod_level - 1) + + def _check_shape(self, shape): + for s1, s2 in zip(self.shape, shape): + if s1 != s2 and s1 >= 0 and s2 >= 0: + raise ValueError( + "Shape not match. What is defined in data layer is {}, but receive {}" + .format(self.shape, shape)) + + def done(self): + arr = np.array(self.data, dtype=self.dtype) + if self.shape: + if len(arr.shape) != len(self.shape): + try: + arr = arr.reshape(self.shape) + except ValueError: + raise ValueError( + "Reshape error. What is defined in data layer is {}, but receive {}" + .format(self.shape, arr.shape)) + t = core.LoDTensor() + t.set(arr, self.place) + if self.lod_level > 0: + t.set_recursive_sequence_lengths(self.lod) + self._reset() + return t + + +class BatchedTensorProvider(object): + + def __init__(self, feed_list, place, batch_size, generator, drop_last): + self.place = place + self.batch_size = batch_size + self.generator = generator + self.converters = [] + self.drop_last = drop_last + + for var in feed_list: + assert var.lod_level == 0, "lod_level must be 0" + self.converters.append( + DataToLoDTensorConverter(place=self.place, + lod_level=0, + shape=var.shape, + dtype=var.dtype)) + + def _done(self): + return [c.done() for c in self.converters] + + def __call__(self): + idx = 0 + for each_sample in self.generator(): + for each_slot, each_converter in six.moves.zip( + each_sample, self.converters): + each_converter.data.append(each_slot) + + idx += 1 + if idx == self.batch_size: + idx = 0 + yield self._done() + + if not self.drop_last and idx > 0: + yield self._done() + else: + [c._reset() for c in self.converters] + + +class DataFeeder(object): + """ + :api_attr: Static Graph + + DataFeeder converts the data that returned by a reader into a data + structure that can feed into Executor. The reader is usually a + python generator that returns a list of mini-batch data entries. + + Parameters: + feed_list (list): Variables or names of Variables that need + to feed. + place (:ref:`api_fluid_CPUPlace` | :ref:`api_fluid_CUDAPlace` ): + place indicates the device (CPU | GPU) the data will be fed into, if + you want to feed data into GPU, please using :code:`fluid.CUDAPlace(i)` + (:code:`i` represents the GPU id), or if you want to feed data into CPU, + please using :code:`fluid.CPUPlace()`. + program (:ref:`api_fluid_Program` , optional): The Program that will + feed data into, if program is None, it will use default_main_program(). + Default None. + + Raises: + :code:`ValueError` - If some Variables are not in this Program. + + Example: + .. code-block:: python + + import numpy as np + import paddle + import paddle.fluid as fluid + + place = fluid.CPUPlace() + def reader(): + for _ in range(4): + yield np.random.random([4]).astype('float32'), np.random.random([3]).astype('float32'), + + main_program = fluid.Program() + startup_program = fluid.Program() + + with fluid.program_guard(main_program, startup_program): + data_1 = fluid.data(name='data_1', shape=[None, 2, 2], dtype='float32') + data_2 = fluid.data(name='data_2', shape=[None, 1, 3], dtype='float32') + out = fluid.layers.fc(input=[data_1, data_2], size=2) + # ... + feeder = fluid.DataFeeder([data_1, data_2], place) + + exe = fluid.Executor(place) + exe.run(startup_program) + + feed_data = feeder.feed(reader()) + + # print feed_data to view feed results + # print(feed_data['data_1']) + # print(feed_data['data_2']) + + outs = exe.run(program=main_program, + feed=feed_data, + fetch_list=[out]) + print(outs) + + """ + + def __init__(self, feed_list, place, program=None): + self.feed_dtypes = [] + self.feed_names = [] + self.feed_shapes = [] + self.feed_lod_level = [] + if program is None: + program = default_main_program() + for each_var in feed_list: + if isinstance(each_var, six.string_types): + each_var = program.block(0).var(each_var) + if not isinstance(each_var, Variable): + raise TypeError("Feed list should contain a list of variable") + self.feed_dtypes.append(each_var.dtype) + self.feed_names.append(each_var.name) + self.feed_lod_level.append(each_var.lod_level) + self.feed_shapes.append(each_var.shape) + + self.place = place + + def feed(self, iterable): + """ + According to :code:`feed_list` of :code:`DataFeeder` and :code:`iterable` , converts + the input into a data structure that can feed into Executor. + + Parameters: + iterable (generator): user defined python generator to read the raw input data + + Returns: + :code:`dict`: a :code:`dict` that contains (variable name - converted tensor) pairs + + Example: + .. code-block:: python + + # In this example, reader - generator will return a list of ndarray of 3 elements + # feed API will convert each ndarray input into a tensor + # the return result is a dict with keys: data_1, data_2, data_3 + # result['data_1'] a LoD-Tensor with shape of [5, 2, 1, 3]. 5 is batch size, and [2, 1, 3] is the real shape of data_1. + # result['data_2'], result['data_3'] are similar. + import numpy as np + import paddle.fluid as fluid + + def reader(limit=5): + for i in range(1, limit + 1): + yield np.ones([6]).astype('float32') * i , np.ones([1]).astype('int64') * i, np.random.random([9]).astype('float32') + + data_1 = fluid.data(name='data_1', shape=[None, 2, 1, 3]) + data_2 = fluid.data(name='data_2', shape=[None, 1], dtype='int64') + data_3 = fluid.data(name='data_3', shape=[None, 3, 3], dtype='float32') + feeder = fluid.DataFeeder(['data_1','data_2', 'data_3'], fluid.CPUPlace()) + + + result = feeder.feed(reader()) + print(result['data_1']) + print(result['data_2']) + print(result['data_3']) + + """ + converter = [] + for lod_level, shape, dtype in six.moves.zip(self.feed_lod_level, + self.feed_shapes, + self.feed_dtypes): + converter.append( + DataToLoDTensorConverter(place=self.place, + lod_level=lod_level, + shape=shape, + dtype=dtype)) + + for each_sample in iterable: + assert len(each_sample) == len(converter), ( + "The number of fields in data (%d) does not match " + + "len(feed_list) (%d)") % (len(each_sample), len(converter)) + for each_converter, each_slot in six.moves.zip( + converter, each_sample): + each_converter.feed(each_slot) + ret_dict = {} + for each_name, each_converter in six.moves.zip(self.feed_names, + converter): + ret_dict[each_name] = each_converter.done() + return ret_dict + + def feed_parallel(self, iterable, num_places=None): + """ + Similar with feed function, feed_parallel is used with multiple devices (CPU|GPU). + Here :code:`iterable` is a list of python generators. The data return by each + generator in the list will be fed into a separate device. + + Parameters: + iterable (list|tuple): list of user-defined python generators. The element + number should match the :code:`num_places`. + num_places (int, optional): the number of devices. If not provided (None), + all available devices on the machine will be used. Default None. + + Returns: + :code:`generator`: a :code:`generator` that generate dict which contains (variable name - converted tensor) pairs, + the total number of dicts will be generated matches with the :code:`num_places` + + .. note:: + The number of devices - :code:`num_places` should equal to the generator (element of :code:`iterable` ) number + + Example: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + def generate_reader(batch_size, base=0, factor=1): + def _reader(): + for i in range(batch_size): + yield np.ones([4]) * factor + base, np.ones([4]) * factor + base + 5 + return _reader() + + x = fluid.data(name='x', shape=[None, 2, 2]) + y = fluid.data(name='y', shape=[None, 2, 2], dtype='float32') + + z = fluid.layers.elementwise_add(x, y) + + feeder = fluid.DataFeeder(['x','y'], fluid.CPUPlace()) + place_num = 2 + places = [fluid.CPUPlace() for x in range(place_num)] + data = [] + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + program = fluid.CompiledProgram(fluid.default_main_program()).with_data_parallel(places=places) + + # print sample feed_parallel r result + # for item in list(feeder.feed_parallel([generate_reader(5, 0, 1), generate_reader(3, 10, 2)], 2)): + # print(item['x']) + # print(item['y']) + + reader_list = [generate_reader(5, 0, 1), generate_reader(3, 10, 2)] + res = exe.run(program=program, feed=list(feeder.feed_parallel(reader_list, 2)), fetch_list=[z]) + print(res) + + """ + if isinstance(self.place, core.CUDAPlace): + places = [ + core.CUDAPlace(i) for i in six.moves.xrange( + self._get_number_of_places_(num_places)) + ] + else: + places = [ + core.CPUPlace() for _ in six.moves.xrange( + self._get_number_of_places_(num_places)) + ] + + if len(iterable) != len(places): + raise ValueError("feed_parallel takes multiple mini-batches. Each " + "mini-batch will be feed on each device. The " + "number of devices and number of mini-batches " + "must be same.") + + place = self.place + for p, batch in six.moves.zip(places, iterable): + self.place = p + yield self.feed(batch) + self.place = place + + def _get_number_of_places_(self, num_places): + if num_places is not None: + return int(num_places) + elif isinstance(self.place, core.CUDAPlace): + return len(_cuda_ids()) + else: + return _cpu_num() + + def decorate_reader(self, + reader, + multi_devices, + num_places=None, + drop_last=True): + """ + Decorate the reader (generator) to fit multiple devices. The reader generate + multiple mini-batches. Each mini-batch will be fed into a single device. + + Parameters: + reader(generator): a user defined python generator used to get :code:`mini-batch` of data. + A :code:`mini-batch` can be regarded as a python generator that returns batches of input + entities, just like the below :code:`_mini_batch` in the code example. + multi_devices(bool): indicate whether to use multiple devices or not. + num_places(int, optional): if :code:`multi_devices` is True, you can specify the number + of devices(CPU|GPU) to use, if multi_devices is None, the function will use all the + devices of the current machine. Default None. + drop_last(bool, optional): whether to drop the last round of data if it is not enough to + feed all devices. Default True. + + Returns: + :code:`generator`: a new :code:`generator` which return converted dicts that can be fed into Executor + + Raises: + :code:`ValueError`: If drop_last is False and the data cannot fit devices perfectly. + + Example: + .. code-block:: python + + import numpy as np + import paddle + import paddle.fluid as fluid + import paddle.fluid.compiler as compiler + + def reader(): + def _mini_batch(batch_size): + for i in range(batch_size): + yield np.random.random([16]).astype('float32'), np.random.randint(10, size=[1]) + + for _ in range(10): + yield _mini_batch(np.random.randint(1, 10)) + + place_num = 3 + places = [fluid.CPUPlace() for _ in range(place_num)] + + # a simple network sample + data = fluid.data(name='data', shape=[None, 4, 4], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + hidden = fluid.layers.fc(input=data, size=10) + + feeder = fluid.DataFeeder(place=places[0], feed_list=[data, label]) + reader = feeder.decorate_reader(reader, multi_devices=True, num_places=3, drop_last=True) + + exe = fluid.Executor(places[0]) + exe.run(fluid.default_startup_program()) + compiled_prog = compiler.CompiledProgram( + fluid.default_main_program()).with_data_parallel(places=places) + + for i,data in enumerate(reader()): + # print data if you like + # print(i, data) + ret = exe.run(compiled_prog, feed=data, fetch_list=[hidden]) + print(ret) + + """ + + def __reader_creator__(): + if not multi_devices: + for item in reader(): + yield self.feed(item) + else: + num = self._get_number_of_places_(num_places) + item = [] + for batch in reader(): + item.append(batch) + if len(item) == num: + yield list(self.feed_parallel(item, num)) + item = [] + if not drop_last and len(item) != 0: + raise ValueError( + "The data batch which cannot fit for devices will be " + "dropped is not implementation. Other strategies are " + "not implemented") + + return __reader_creator__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..597f1f217483ccafe73d0b4fe337cb2b24b4b436 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/__init__.py @@ -0,0 +1,32 @@ +# 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. + +from __future__ import print_function + +from . import dataset +from .dataset import * + +from . import batch_sampler +from .batch_sampler import * + +from . import dataloader_iter +from .dataloader_iter import * + +from . import sampler +from .sampler import * + +__all__ = dataset.__all__ \ + + batch_sampler.__all__ \ + + dataloader_iter.__all__ \ + + sampler.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/batch_sampler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/batch_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..8187faef0086ba323c3c71275ee0e1ff34126963 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/batch_sampler.py @@ -0,0 +1,344 @@ +# 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. + +from __future__ import print_function +from __future__ import division + +import numpy as np +import math + +from .sampler import Sampler, SequenceSampler, RandomSampler +from .dataset import Dataset, IterableDataset + +__all__ = ["BatchSampler", "DistributedBatchSampler"] + + +class BatchSampler(Sampler): + """ + A base implement of batch sampler used by `paddle.io.DataLoader` + which yield mini-batch indices(a list/tuple with length as + mini-batch size and holds sample indices) iterably. + + Batch sampler used by :code:`paddle.io.DataLoader` should be a subclass + of :code:`paddle.io.BatchSampler`, BatchSampler subclasses should + implement following methods: + + :code:`__iter__`: return mini-batch indices iterably. + + :code:`__len__`: get mini-batch number in an epoch. + + + Args: + dataset(Dataset): this could be a :code:`paddle.io.Dataset` + implement or other python object which implemented + :code:`__len__` for BatchSampler to get indices as the + range of :attr:`dataset` length. Default None. + sampler (Sampler): this could be a :code:`paddle.io.Dataset` + instance which implemented :code:`__iter__` to yield + sample indices. :attr:`sampler` and :attr:`dataset` + can not be set in the same time. If :attr:`sampler` + is set, :attr:`shuffle` should not be set. Default None. + shuffle(bool): whether to shuffle indices order before genrating + batch indices. Default False. + batch_size(int): sample indice number in a mini-batch indices. + drop_last(bool): whether drop the last incomplete batch dataset size + is not divisible by the batch size. Default False + + Returns: + BatchSampler: an iterable object for indices iterating + + Examples: + + .. code-block:: python + + from paddle.io import RandomSampler, BatchSampler, Dataset + + # init with dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + bs = BatchSampler(dataset=RandomDataset(100), + shuffle=False, + batch_size=16, + drop_last=False) + + for batch_indices in bs: + print(batch_indices) + + # init with sampler + sampler = RandomSampler(RandomDataset(100)) + bs = BatchSampler(sampler=sampler, + batch_size=8, + drop_last=True) + + for batch_indices in bs: + print(batch_indices) + + + see `paddle.io.DataLoader` + + """ + + def __init__(self, + dataset=None, + sampler=None, + shuffle=False, + batch_size=1, + drop_last=False): + if dataset is None: + assert sampler is not None, \ + "either dataset or sampler should be set" + assert isinstance(sampler, Sampler), \ + "sampler should be a paddle.io.Sampler, but got {}".format(type(sampler)) + assert not shuffle, "shuffle should be False when sampler is set" + self.sampler = sampler + else: + assert not isinstance(dataset, IterableDataset), \ + "dataset should not be a paddle.io.IterableDataset" + assert sampler is None, \ + "should not set both dataset and sampler" + assert isinstance(shuffle, bool), \ + "shuffle should be a boolean value, but got {}".format(type(shuffle)) + if shuffle: + self.sampler = RandomSampler(dataset) + else: + self.sampler = SequenceSampler(dataset) + + assert isinstance(batch_size, int) and batch_size > 0, \ + "batch_size should be a positive integer, but got {}".format(batch_size) + self.batch_size = batch_size + assert isinstance(drop_last, bool), \ + "drop_last should be a boolean value, but got {}".format(type(drop_last)) + self.drop_last = drop_last + + def __iter__(self): + batch_indices = [] + for idx in self.sampler: + batch_indices.append(idx) + if len(batch_indices) == self.batch_size: + yield batch_indices + batch_indices = [] + if not self.drop_last and len(batch_indices) > 0: + yield batch_indices + + def __len__(self): + num_samples = len(self.sampler) + num_samples += int(not self.drop_last) * (self.batch_size - 1) + return num_samples // self.batch_size + + +class _InfiniteIterableSampler(object): + + def __init__(self, dataset, batch_size=1): + assert isinstance( + dataset, IterableDataset + ), "dataset should be an instance of paddle.io.IterableDataset" + self.dataset = dataset + self.batch_size = batch_size + + def __iter__(self): + while True: + yield [None] * self.batch_size + + +class DistributedBatchSampler(BatchSampler): + """Sampler that restricts data loading to a subset of the dataset. + + In such case, each process can pass a DistributedBatchSampler instance + as a DataLoader sampler, and load a subset of the original dataset that + is exclusive to it. + + .. note:: + Dataset is assumed to be of constant size. + + Args: + dataset(paddle.io.Dataset): this could be a `paddle.io.Dataset` implement + or other python object which implemented + `__len__` for BatchSampler to get sample + number of data source. + batch_size(int): sample indice number in a mini-batch indices. + num_replicas(int, optional): porcess number in distributed training. + If :attr:`num_replicas` is None, :attr:`num_replicas` will be + retrieved from :code:`paddle.distributed.ParallenEnv`. + Default None. + rank(int, optional): the rank of the current process among :attr:`num_replicas` + processes. If :attr:`rank` is None, :attr:`rank` is retrieved from + :code:`paddle.distributed.ParallenEnv`. Default None. + shuffle(bool): whther to shuffle indices order before genrating + batch indices. Default False. + drop_last(bool): whether drop the last incomplete batch dataset size + is not divisible by the batch size. Default False + + Examples: + .. code-block:: python + + import numpy as np + + from paddle.io import Dataset, DistributedBatchSampler + + # init with dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + dataset = RandomDataset(100) + sampler = DistributedBatchSampler(dataset, batch_size=64) + + for data in sampler: + # do something + break + """ + + def __init__(self, + dataset, + batch_size, + num_replicas=None, + rank=None, + shuffle=False, + drop_last=False): + self.dataset = dataset + + assert isinstance(batch_size, int) and batch_size > 0, \ + "batch_size should be a positive integer" + self.batch_size = batch_size + assert isinstance(shuffle, bool), \ + "shuffle should be a boolean value" + self.shuffle = shuffle + assert isinstance(drop_last, bool), \ + "drop_last should be a boolean number" + + from paddle.fluid.dygraph.parallel import ParallelEnv + + if num_replicas is not None: + assert isinstance(num_replicas, int) and num_replicas > 0, \ + "num_replicas should be a positive integer" + self.nranks = num_replicas + else: + self.nranks = ParallelEnv().nranks + + if rank is not None: + assert isinstance(rank, int) and rank >= 0, \ + "rank should be a non-negative integer" + self.local_rank = rank + else: + self.local_rank = ParallelEnv().local_rank + + self.drop_last = drop_last + self.epoch = 0 + self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.nranks)) + self.total_size = self.num_samples * self.nranks + + def __iter__(self): + num_samples = len(self.dataset) + indices = np.arange(num_samples).tolist() + indices += indices[:(self.total_size - len(indices))] + assert len(indices) == self.total_size + if self.shuffle: + np.random.RandomState(self.epoch).shuffle(indices) + self.epoch += 1 + + # subsample + def _get_indices_by_batch_size(indices): + subsampled_indices = [] + last_batch_size = self.total_size % (self.batch_size * self.nranks) + assert last_batch_size % self.nranks == 0 + last_local_batch_size = last_batch_size // self.nranks + + for i in range(self.local_rank * self.batch_size, + len(indices) - last_batch_size, + self.batch_size * self.nranks): + subsampled_indices.extend(indices[i:i + self.batch_size]) + + indices = indices[len(indices) - last_batch_size:] + subsampled_indices.extend( + indices[self.local_rank * + last_local_batch_size:(self.local_rank + 1) * + last_local_batch_size]) + return subsampled_indices + + if self.nranks > 1: + indices = _get_indices_by_batch_size(indices) + + assert len(indices) == self.num_samples + _sample_iter = iter(indices) + + batch_indices = [] + for idx in _sample_iter: + batch_indices.append(idx) + if len(batch_indices) == self.batch_size: + yield batch_indices + batch_indices = [] + if not self.drop_last and len(batch_indices) > 0: + yield batch_indices + + def __len__(self): + num_samples = self.num_samples + num_samples += int(not self.drop_last) * (self.batch_size - 1) + return num_samples // self.batch_size + + def set_epoch(self, epoch): + """ + Sets the epoch number. When :attr:`shuffle=True`, this number is used + as seeds of random numbers. By default, users may not set this, all + replicas (workers) use a different random ordering for each epoch. + If set same number at each epoch, this sampler will yield the same + ordering at all epoches. + + Arguments: + epoch (int): Epoch number. + + Examples: + .. code-block:: python + + import numpy as np + + from paddle.io import Dataset, DistributedBatchSampler + + # init with dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + dataset = RandomDataset(100) + sampler = DistributedBatchSampler(dataset, batch_size=64) + + for epoch in range(10): + sampler.set_epoch(epoch) + """ + self.epoch = epoch diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/collate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/collate.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf041007eb38fcc0a374799c0ae6b57a60bdd61 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/collate.py @@ -0,0 +1,111 @@ +# Copyright (c) 2021 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. + +import paddle +import numbers +import numpy as np +from ..framework import _non_static_mode +from .. import core, layers + +try: + from collections.abc import Sequence, Mapping +except: + from collections import Sequence, Mapping + + +def default_collate_fn(batch): + """ + Default batch collating function for :code:`paddle.io.DataLoader`, + get input data as a list of sample datas, each element in list + if the data of a sample, and sample data should composed of list, + dictionary, string, number, numpy array and paddle.Tensor, this + function will parse input data recursively and stack number, + numpy array and paddle.Tensor datas as batch datas. e.g. for + following input data: + + [{'image': np.array(shape=[3, 224, 224]), 'label': 1}, + {'image': np.array(shape=[3, 224, 224]), 'label': 3}, + {'image': np.array(shape=[3, 224, 224]), 'label': 4}, + {'image': np.array(shape=[3, 224, 224]), 'label': 5},] + + + This default collate function zipped each number and numpy array + field together and stack each field as the batch field as follows: + + {'image': np.array(shape=[4, 3, 224, 224]), 'label': np.array([1, 3, 4, 5])} + + + Args: + batch(list of sample data): batch should be a list of sample data. + + Returns: + Batched data: batched each number, numpy array and paddle.Tensor + in input data. + """ + sample = batch[0] + if isinstance(sample, np.ndarray): + batch = np.stack(batch, axis=0) + return batch + elif isinstance(sample, (paddle.Tensor, core.eager.Tensor)): + return layers.stack(batch, axis=0) + elif isinstance(sample, numbers.Number): + batch = np.array(batch) + return batch + elif isinstance(sample, (str, bytes)): + return batch + elif isinstance(sample, Mapping): + return { + key: default_collate_fn([d[key] for d in batch]) + for key in sample + } + elif isinstance(sample, Sequence): + sample_fields_num = len(sample) + if not all(len(sample) == sample_fields_num for sample in iter(batch)): + raise RuntimeError( + "fileds number not same among samples in a batch") + return [default_collate_fn(fields) for fields in zip(*batch)] + + raise TypeError("batch data con only contains: tensor, numpy.ndarray, " + "dict, list, number, but got {}".format(type(sample))) + + +def default_convert_fn(batch): + """ + Default batch converting function for :code:`paddle.io.DataLoader`. + get input data as a list of sample datas, each element in list + if the data of a sample, and sample data should composed of list, + dictionary, string, number, numpy array and paddle.Tensor. + + .. note:: + This function is default :attr:`collate_fn` in **Distable + automatic batching** mode, for **Distable automatic batching** + mode, please ses :attr:`paddle.io.DataLoader` + + Args: + batch(list of sample data): batch should be a list of sample data. + + Returns: + Batched data: batched each number, numpy array and paddle.Tensor + in input data. + """ + if isinstance(batch, (paddle.Tensor, np.ndarray, core.eager.Tensor)): + return batch + elif isinstance(batch, (str, bytes)): + return batch + elif isinstance(batch, Mapping): + return {key: default_convert_fn(batch[key]) for key in batch} + elif isinstance(batch, Sequence): + return [default_convert_fn(d) for d in batch] + else: + return batch diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataloader_iter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataloader_iter.py new file mode 100644 index 0000000000000000000000000000000000000000..92fe3fb91549b948efb2e569c66e884bcc9afcbe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataloader_iter.py @@ -0,0 +1,788 @@ +# 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. + +import os +import six +import sys +import time +import signal +import numbers +import logging +import itertools +import threading +import numpy as np +import multiprocessing +from collections import namedtuple +from paddle.fluid.framework import _set_expected_place, _current_expected_place, set_flags + +# NOTE: queue has a different name in python2 and python3 +import queue + +import paddle +import paddle.profiler as profiler +from paddle.profiler.utils import in_profiler_mode +from .. import core, layers +from ..framework import _non_static_mode, in_dygraph_mode, _in_legacy_dygraph +from ..multiprocess_utils import _set_SIGCHLD_handler, MP_STATUS_CHECK_INTERVAL, CleanupFuncRegistrar +from .fetcher import _IterableDatasetFetcher, _MapDatasetFetcher +from .batch_sampler import _InfiniteIterableSampler +from .collate import default_collate_fn, default_convert_fn +from .worker import ParentWatchDog, get_worker_info, _worker_loop, \ + _DatasetKind, _IterableDatasetStopIteration, _WorkerException, \ + _ResumeIteration +from .flat import _flatten_batch, _restore_batch +from paddle.profiler.timer import benchmark + +__all__ = ['get_worker_info'] + +# NOTE: fix `terminate called without an active exception` +# if for loop break and program exit immediately(with no model +# layers processing) after iterate **the first few data** in +# distributed lauch mode, distributed launch will call +# terminate() to kill main process on each devices, but thread +# is still iterating to fullfill blocking queue caches, which +# may cause thread error `terminate called without an active +# exception` for terminate is a strong singal and `__del__` +# of DataLoader may not be called, so we add a global link to +# the last DataLoader instance to call `__del__` to clean up +# resources +# NOTE: cannot simply as `__del__` to CleanupFuncRegistrar, +# for this will remain a link to each DataLoader instance in +# global, and will precludes GC to auto collect DataLoader +# instance and will cause memory leak +_loader = None + + +def _clear_loader(): + global _loader + if _loader is not None: + try: + _loader.__del__() + del _loader + except: + pass + + +CleanupFuncRegistrar.register(_clear_loader) + + +class _DataLoaderIterBase(object): + """ + Iterator implement of DataLoader, will load and feed mini-batch + data by setting in given dataloader. + + Args: + loader(instance of DataLoader): instance of `fluid.io.DataLoader` + """ + + def __init__(self, loader): + self._dataset = loader.dataset + self._feed_list = loader.feed_list or [] + self._places = loader.places + self._return_list = loader.return_list + self._batch_sampler = loader.batch_sampler + self._drop_last = loader.drop_last + self._auto_collate_batch = loader.auto_collate_batch + self._num_workers = loader.num_workers + self._use_buffer_reader = loader.use_buffer_reader + self._prefetch_factor = loader.prefetch_factor + self._use_shared_memory = loader.use_shared_memory + self._timeout = loader.timeout if loader.timeout > 0 else MP_STATUS_CHECK_INTERVAL + self._worker_init_fn = loader.worker_init_fn + self._dataset_kind = loader.dataset_kind + self._pin_memory = loader.pin_memory + + self._sampler_iter = iter(self._index_sampler) + if self._auto_collate_batch: + self._collate_fn = loader.collate_fn or default_collate_fn + else: + self._collate_fn = loader.collate_fn or default_convert_fn + + # LoDTensorBlockingQueue instance for create_py_reader and a thread + # to put mini-batch data to self._blocking_queue, mini-batch data + # will be get from: + # 1. multi-process mode: get data from workers' result queue + # 2. single-process mode: read mini-batch data in main process + self._blocking_queue = None + self._thread = None + self._thread_done_event = threading.Event() + + @property + def _index_sampler(self): + if self._auto_collate_batch: + return self._batch_sampler + else: + if self._dataset_kind == _DatasetKind.MAP: + return list(range(len(self._dataset))) + else: + return _InfiniteIterableSampler(self._dataset, 1) + + def __iter__(self): + return self + + def __len__(self): + return len(self._batch_sampler) + + def _exit_thread_expectedly(self): + self._thread_done_event.set() + if self._blocking_queue: + self._blocking_queue.close() + + def _exit_thread_unexpectedly(self): + self._thread_done_event.set() + if self._blocking_queue: + self._blocking_queue.kill() + + +class _DataLoaderIterSingleProcess(_DataLoaderIterBase): + """ + Single process implement of DataLoaderIter, loading data from + loader.data in main process + """ + + def __init__(self, loader): + super(_DataLoaderIterSingleProcess, self).__init__(loader) + + self._dataset_fetcher = _DatasetKind.create_fetcher( + self._dataset_kind, self._dataset, self._auto_collate_batch, + self._collate_fn, self._drop_last) + + # NOTE: _structrue_infos used to record the data structure of + # batch to restore batch structure after reading Tensor + # from blocking_queue in single-process mode. Note that + # only single process is used in single-process mode, we + # can record the data structure sequencely in a list without + # recording the send and recv index + self._structure_infos = [] + + # NOTE: len(self._places) batch data compose as an output + # iteration, set blocking_queue can cache "self._prefetch_factor" iteration datas + # at most here + self._blocking_queue_capacity = self._prefetch_factor * len( + self._places) + + self._init_thread() + self._shutdown = False + + global _loader + _loader = self + + def _init_thread(self): + self._var_names = [v.name for v in self._feed_list] + self._shapes = [v.shape for v in self._feed_list] + self._dtypes = [v.dtype for v in self._feed_list] + self._need_check_feed = [ + v.desc.need_check_feed() for v in self._feed_list + ] + # if only 1 place, do not need to keep order + self._blocking_queue = core.init_lod_tensor_blocking_queue( + core.Variable(), self._blocking_queue_capacity, + len(self._places) > 1) + self._reader = core.create_py_reader( + self._blocking_queue, self._var_names, self._shapes, self._dtypes, + self._need_check_feed, self._places, self._use_buffer_reader, True, + self._pin_memory) + + self._thread = threading.Thread(target=self._thread_loop, + args=(_current_expected_place(), )) + self._thread.daemon = True + self._thread.start() + + def _thread_loop(self, legacy_expected_place): + #NOTE(zhiqiu): Set the expected place for new thread as the same as father thread, + # and it will call platform::SetDeviceId() in c++ internally. + # If we do not set cudaDeviceId in new thread, the default cudaDeviceId will be 0, + # Which may cost hundreds of MB of GPU memory on CUDAPlace(0) if calling some cuda + # APIs in this thread. + _set_expected_place(legacy_expected_place) + + while not self._thread_done_event.is_set(): + try: + indices = next(self._sampler_iter) + + # read data from dataset in mini-batch + # with paddle.fluid.dygraph.guard(place=paddle.CPUPlace()): + # read data from dataset in mini-batch + batch = self._dataset_fetcher.fetch(indices, + self._thread_done_event) + except StopIteration: + self._exit_thread_expectedly() + return + + if batch is None or self._thread_done_event.is_set(): break + + # flat batch and record structure infos + batch, structure = _flatten_batch(batch) + self._structure_infos.append(structure) + + if self._thread_done_event.is_set(): break + + try: + # pack as LoDTensorArray + array = core.LoDTensorArray() + for slot in batch: + if isinstance(slot, (paddle.Tensor, core.eager.Tensor)): + slot = slot.value().get_tensor() + elif not isinstance(slot, core.LoDTensor): + tmp = core.LoDTensor() + tmp.set(slot, core.CPUPlace()) + slot = tmp + + array.append(slot) + + if self._thread_done_event.is_set(): break + + try: + self._blocking_queue.push(array) + except: + self._exit_thread_expectedly() + + except: + self._exit_thread_unexpectedly() + six.reraise(*sys.exc_info()) + + self._exit_thread_expectedly() + + def __next__(self): + if in_profiler_mode(): + trace_event = profiler.RecordEvent( + name="_DataLoaderIterSingleProcess", + event_type=profiler.TracerEventType.Dataloader) + trace_event.begin() + try: + benchmark().check_if_need_record(self) + benchmark().before_reader() + if in_dygraph_mode(): + data = core.eager.read_next_tensor_list( + self._reader.read_next_list()[0]) + data = _restore_batch(data, self._structure_infos.pop(0)) + else: + if _in_legacy_dygraph(): + data = self._reader.read_next_var_list() + data = _restore_batch(data, self._structure_infos.pop(0)) + else: # in static mode + if self._return_list: + data = self._reader.read_next_list() + for i in range(len(data)): + data[i] = data[i]._move_to_list() + structs = [ + self._structure_infos.pop(0) + for _ in range(len(self._places)) + ] + data = [_restore_batch(d, s) \ + for d, s in zip(data, structs)] + # static graph organized data on multi-device with list, if + # place number is 1, there is only 1 device, extra the data + # from list for devices to be compatible with dygraph mode + if len(self._places) == 1: + data = data[0] + else: + data = self._reader.read_next() + benchmark().after_reader() + + return data + except StopIteration: + self._reader.shutdown() + self._try_shutdown_all() + six.reraise(*sys.exc_info()) + finally: + if in_profiler_mode(): + trace_event.end() + + def _shutdown_thread(self): + if self._thread: + self._thread_done_event.set() + # NOTE: we wait for _thread exit for 3 seconds, if + # thread not exit normally, force kill it + for _ in range(3): + if self._thread.is_alive(): + time.sleep(1) + else: + break + else: + if self._thread is not threading.current_thread(): + self._thread.join() + + self._thread = None + + # python2 compatibility + def next(self): + return self.__next__() + + def _try_shutdown_all(self): + if not self._shutdown: + try: + # # _blocking_queue in keep order mode holds sub-threads + # # need to release thread resources on unexpected exit + if self._blocking_queue: + self._blocking_queue.close() + self._blocking_queue = None + # NOTE: blocking queue should be closed firstly for + # blocking queue read may hang and _thread_done_event + # cannot be checked + self._shutdown_thread() + finally: + self._shutdown = True + + def __del__(self): + self._try_shutdown_all() + + +class _DataLoaderIterMultiProcess(_DataLoaderIterBase): + + def __init__(self, loader): + super(_DataLoaderIterMultiProcess, self).__init__(loader) + + self._persistent_workers = loader._persistent_workers + self._resume_worker_cnt = 0 + + assert self._num_workers > 0, "Multi-process DataLoader " \ + "invalid num_workers({})".format(self._num_workers) + + # subprocess wrokers' result queue + self._data_queue = None + + # data get from _data_queue will be reordered by _rcvd_idx + # for data order keeping, data index not equal _rcvd_idx + # will be cached in _task_infos + self._send_idx = 0 + self._rcvd_idx = 0 + self._batches_outstanding = 0 + self._task_infos = {} + self._structure_infos = [] + + # indices outstand as _outstanding_capacity at first, and + # blocking_queue capacity is also _outstanding_capacity. + # _outstanding_capacity here to make sure each indices_queue + # has at least "_prefetch_factor" indices, and outstanding batch cached + # output data for at least "_prefetch_factor" iterations(Note that len(_places) + # batches will be composed as an iteration output) + self._outstanding_capacity = self._prefetch_factor * max( + self._num_workers, len(self._places)) + + # see _try_put_indices + self._thread_lock = threading.Lock() + + self._base_seed = np.random.randint(low=0, high=sys.maxsize) + + # init workers and indices queues and put 2 indices in each indices queue + self._init_workers() + for _ in range(self._outstanding_capacity): + self._try_put_indices() + + self._init_thread() + self._shutdown = False + + def _init_workers(self): + # multiprocess worker and indice queue list initial as empty + self._workers = [] + self._worker_status = [] + self._indices_queues = [] + self._workers_idx_cycle = itertools.cycle(range(self._num_workers)) + + # create data_queue for workers + self._data_queue = multiprocessing.Queue() + + # event for workers and thread, thread event is only need + # in multi-processing mode + self._workers_done_event = multiprocessing.Event() + self._thread_done_event = threading.Event() + + for i in range(self._num_workers): + indices_queue = multiprocessing.Queue() + self._indices_queues.append(indices_queue) + worker = multiprocessing.Process( + target=_worker_loop, + args=(self._dataset, self._dataset_kind, indices_queue, + self._data_queue, self._workers_done_event, + self._auto_collate_batch, self._collate_fn, + self._drop_last, self._worker_init_fn, i, + self._num_workers, self._use_shared_memory, + self._base_seed)) + worker.daemon = True + worker.start() + self._workers.append(worker) + self._worker_status.append(True) + + core._set_process_pids(id(self), tuple(w.pid for w in self._workers)) + _set_SIGCHLD_handler() + + def _clear_and_remove_data_queue(self): + if self._data_queue is not None: + while True: + try: + self._data_queue.get_nowait() + except: + self._data_queue.cancel_join_thread() + self._data_queue.close() + break + + def _init_thread(self): + self._var_names = [v.name for v in self._feed_list] + self._shapes = [v.shape for v in self._feed_list] + self._dtypes = [v.dtype for v in self._feed_list] + self._need_check_feed = [ + v.desc.need_check_feed() for v in self._feed_list + ] + # if only 1 place, do not need to keep order + self._blocking_queue = core.init_lod_tensor_blocking_queue( + core.Variable(), self._outstanding_capacity, + len(self._places) > 1) + self._reader = core.create_py_reader( + self._blocking_queue, self._var_names, self._shapes, self._dtypes, + self._need_check_feed, self._places, self._use_buffer_reader, True, + self._pin_memory) + + self._thread_done_event = threading.Event() + # thread event is only need in multi-processing mode + self._thread = threading.Thread(target=self._thread_loop, + args=(_current_expected_place(), )) + self._thread.daemon = True + self._thread.start() + + def _reset(self): + # resume iteration in following steps + # 1. Resume workers, clear worker caches + # put _ResumeIteration to all worker as resume iteration flag + with self._thread_lock: + self._resume_worker_cnt = self._num_workers + for worker_id in range(self._num_workers): + self._indices_queues[worker_id].put(_ResumeIteration()) + self._batches_outstanding += 1 + # all flag will be check in _thread_loop, simply wait here + while self._resume_worker_cnt > 0: + time.sleep(0.5) + + # 2. clear blocking_queue caches + # in order not to restart the thread, we just clear + # the blocking_queue cachees instead of recreating one + while self._blocking_queue.size() >= len(self._places): + if in_dygraph_mode(): + data = core.eager.read_next_tensor_list( + self._reader.read_next_list()[0]) + else: + if _in_legacy_dygraph(): + self._reader.read_next_var_list() + elif self._return_list: + self._reader.read_next_list() + else: + data = self._reader.read_next() + + # 3. reset all states + self._send_idx = 0 + self._rcvd_idx = 0 + self._batches_outstanding = 0 + self._task_infos = {} + self._structure_infos = [] + + # set all worker status available + self._worker_status = [True] * self._num_workers + + # 4. reset _sampler_iter and put prefetch indices to start next epoch + # init workers and indices queues and put 2 indices in each indices queue + self._sampler_iter = iter(self._index_sampler) + for _ in range(self._outstanding_capacity): + self._try_put_indices() + + def _shutdown_worker(self, worker_id, shutdown=False): + if self._worker_status[worker_id] or (self._persistent_workers + and shutdown): + self._indices_queues[worker_id].put(None) + self._worker_status[worker_id] = False + + def _try_shutdown_all(self, timeout=None): + if not self._shutdown: + try: + self._exit_thread_expectedly() + self._clear_and_remove_data_queue() + + # set _workers_done_event should be set before put None + # to indices_queue, workers wll exit on reading None from + # indices_queue + self._workers_done_event.set() + for i in range(self._num_workers): + self._shutdown_worker(i, shutdown=True) + + if not self._shutdown: + for w in self._workers: + w.join(timeout) + for q in self._indices_queues: + q.cancel_join_thread() + q.close() + finally: + core._erase_process_pids(id(self)) + self._shutdown = True + + def _thread_loop(self, legacy_expected_place): + #NOTE(zhiqiu): Set the expected place for new thread as the same as father thread, + # and it will call platform::SetDeviceId() in c++ internally. + # If we do not set cudaDeviceId in new thread, the default cudaDeviceId will be 0, + # Which may cost hundreds of MB of GPU memory on CUDAPlace(0) if calling some cuda + # APIs in this thread. + _set_expected_place(legacy_expected_place) + + while not self._thread_done_event.is_set(): + batch = self._get_data() + if not self._thread_done_event.is_set(): + if batch is None: + self._exit_thread_expectedly() + else: + if isinstance(batch, _ResumeIteration): + assert self._resume_worker_cnt > 0 + self._resume_worker_cnt -= 1 + continue + try: + # pack as LoDTensorArray + array = core.LoDTensorArray() + if self._use_shared_memory: + for tensor in batch: + array.append(tensor) + else: + # LoDTensor not in shared memory is not + # serializable, cannot be create in workers + for slot in batch: + if isinstance( + slot, + (paddle.Tensor, core.eager.Tensor)): + slot = slot.value().get_tensor() + elif not isinstance(slot, core.LoDTensor): + tmp = core.LoDTensor() + tmp.set(slot, core.CPUPlace()) + slot = tmp + array.append(slot) + + if not self._blocking_queue.push(array): + self._blocking_queue.close() + except Exception as e: + self._exit_thread_unexpectedly() + six.reraise(*sys.exc_info()) + finally: + self._rcvd_idx += 1 + + def _get_data(self): + while not self._thread_done_event.is_set(): + # For IterableDataset, batch indices is generated infinitely + # for each worker to raise StopIteration, but a StopIteration + # raising process will discard a batch indices which is count + # in _send_idx but will not increase _rcvd_idx, so we check + # whether the worker is still alive here to skip the discarded + # batch indices and increase _rcvd_idx + if self._dataset_kind == _DatasetKind.ITER: + while self._rcvd_idx < self._send_idx: + info = self._task_infos[self._rcvd_idx] + if len(info) == 3 or self._worker_status[info[0]]: + break + del self._task_infos[self._rcvd_idx] + self._rcvd_idx += 1 + self._batches_outstanding -= 1 + else: + # NOTE: when _rcvd_idx catch up _send_idx, which means + # one of following: + # 1. all 2 * num_workers batches have been loaded + # and stored in _blocking_queue + # 2. all data drained + # we need to let _thread blocking at _data_queue + # get_data to inoccupy CPU, otherwise may occupy + # CPU time for model running + # NOTE: in persistent workers mode, do not check data + # drained here, simply let it go to _data_queue + # reading to get _ResumeIteration + if not self._persistent_workers: + # NOTE: _rcvd_idx and _send_idx only record batches among + # workers, if batches among workers drained, there + # may also be data in blocking queue + if self._batches_outstanding < len(self._places): + return None + + if self._rcvd_idx in self._task_infos and \ + len(self._task_infos[self._rcvd_idx]) == 3: + info = self._task_infos.pop(self._rcvd_idx) + self._structure_infos.append(info[2]) + return info[1] + + try: + # [ avoid hang ]: main process may blocking at _reader.read_next when + # KeyboardInterrupt, we do following tradeoff: + # 1. get data with timeout, MP_STATUS_CHECK_INTERVAL(5s) as timeout + # default, if KeyboardInterrupt blocking, failed workers will be + # checked and raise RuntimeError to quit DataLoader in timeout + # exception handling. + # 2. if get data timeout and check workers all alive, continue to + # get data again + data = self._data_queue.get(timeout=self._timeout) + except Exception as e: + # check if thread done event set when waiting data + if self._thread_done_event.is_set(): + continue + + # check failed workers + failed_workers = [] + for i, w in enumerate(self._workers): + if self._worker_status[i] and not w.is_alive(): + failed_workers.append(w) + self._shutdown_worker(i) + if len(failed_workers) > 0: + self._exit_thread_unexpectedly() + pids = ', '.join(str(w.pid) for w in failed_workers) + raise RuntimeError("DataLoader {} workers exit unexpectedly, " \ + "pids: {}".format(len(failed_workers), pids)) + + # get(timeout) will call _poll(timeout) and may raise IOError + if isinstance(e, queue.Empty) or isinstance(e, IOError): + # continue on timeout to keep getting data from queue + continue + + self._exit_thread_unexpectedly() + logging.error("DataLoader reader thread failed({}) to read data from " \ + "workers' result queue.".format(e)) + six.reraise(*sys.exc_info()) + else: + if self._dataset_kind == _DatasetKind.ITER and isinstance( + data, _IterableDatasetStopIteration): + # if a worker get StopIteraion, we shutdown this worker, + # note that this batch indices to trigger StopIteration + # is discard, outstanding batch number should be decrease + # and another indices should be put for other workers + # may still working. + if self._persistent_workers: + self._worker_status[data.worker_id] = False + else: + self._shutdown_worker(data.worker_id) + self._batches_outstanding -= 1 + self._try_put_indices() + continue + + idx, batch, structure = data + + if isinstance(idx, _ResumeIteration) and batch is None \ + and structure is None: + return idx + + if isinstance(batch, _WorkerException): + self._exit_thread_unexpectedly() + batch.reraise() + + if idx == self._rcvd_idx: + del self._task_infos[idx] + self._structure_infos.append(structure) + return batch + else: + self._task_infos[idx] += (batch, structure) + continue + + def _try_put_indices(self): + assert self._batches_outstanding <= self._outstanding_capacity, \ + "too many indices have been put to queue" + # In multi-process mode for IterableDataset, _try_put_indices will + # be called both in main process(for our implement has blocking queue, + # and blocking queue read is in main process) and thread, which may + # cause error following error + # 1. "ValueError: generator already executing" in next(self._sampler_iter) + # 2. re-enter in increase _send_idx + # add a lock for threading save, for _try_put_indices is only a slight + # function which is not in data reading pipeline, this lock almost no + # influence on performance + with self._thread_lock: + try: + indices = next(self._sampler_iter) + except StopIteration: + return + + for i in range(self._num_workers): + worker_idx = next(self._workers_idx_cycle) + if self._worker_status[worker_idx]: + break + else: + return + + self._indices_queues[worker_idx].put((self._send_idx, indices)) + self._task_infos[self._send_idx] = (worker_idx, ) + self._batches_outstanding += 1 + self._send_idx += 1 + + def __del__(self): + self._try_shutdown_all() + + def _shutdown_on_exit(self): + self._try_shutdown_all(1) + + def __next__(self): + if in_profiler_mode(): + trace_event = profiler.RecordEvent( + name="_DataLoaderIterMultiProcess", + event_type=profiler.TracerEventType.Dataloader) + trace_event.begin() + try: + benchmark().check_if_need_record(self) + benchmark().before_reader() + # _batches_outstanding here record the total batch data number + # in 'from after _try_put_indices to beforeoutput data', this + # value should be _outstanding_capacity if data is not drained, + # if _batches_outstanding is less than _places number, there are + # no enough data to generate next output, close blocking_queue and + # set _thread_done_event here, py_reader will raise StopIteration, + # end workers and indices_queues in StopIteration handling + if self._batches_outstanding < len(self._places): + if self._persistent_workers: + raise StopIteration + else: + self._thread_done_event.set() + self._blocking_queue.close() + + if in_dygraph_mode(): + data = core.eager.read_next_tensor_list( + self._reader.read_next_list()[0]) + data = _restore_batch(data, self._structure_infos.pop(0)) + else: + if _in_legacy_dygraph(): + data = self._reader.read_next_var_list() + data = _restore_batch(data, self._structure_infos.pop(0)) + else: + if self._return_list: + data = self._reader.read_next_list() + for i in range(len(data)): + data[i] = data[i]._move_to_list() + structs = [ + self._structure_infos.pop(0) + for _ in range(len(self._places)) + ] + data = [_restore_batch(d, s) \ + for d, s in zip(data, structs)] + # static graph organized data on multi-device with list, if + # place number is 1, there is only 1 device, extra the data + # from list for devices to be compatible with dygraph mode + if len(self._places) == 1: + data = data[0] + else: + data = self._reader.read_next() + self._on_output_batch() + benchmark().after_reader() + return data + except StopIteration: + if not self._persistent_workers: + self._reader.shutdown() + self._try_shutdown_all() + six.reraise(*sys.exc_info()) + finally: + if in_profiler_mode(): + trace_event.end() + + # python2 compatibility + def next(self): + return self.__next__() + + def _on_output_batch(self): + for _ in range(len(self._places)): + self._batches_outstanding -= 1 + self._try_put_indices() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..bd3bb87a79fdb1e94febda24feaacf84ed61e75a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/dataset.py @@ -0,0 +1,530 @@ +# 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. + +from __future__ import print_function + +import paddle +from .. import framework + +__all__ = [ + "Dataset", "IterableDataset", "TensorDataset", "ComposeDataset", + "ChainDataset", "random_split", "Subset" +] + + +class Dataset(object): + """ + An abstract class to encapsulate methods and behaviors of datasets. + + All datasets in map-style(dataset samples can be get by a given key) + should be a subclass of `paddle.io.Dataset`. All subclasses should + implement following methods: + + :code:`__getitem__`: get sample from dataset with a given index. This + method is required by reading dataset sample in :code:`paddle.io.DataLoader`. + + :code:`__len__`: return dataset sample number. This method is required + by some implements of :code:`paddle.io.BatchSampler` + + see :code:`paddle.io.DataLoader`. + + Examples: + + .. code-block:: python + + import numpy as np + from paddle.io import Dataset + + # define a random dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + dataset = RandomDataset(10) + for i in range(len(dataset)): + print(dataset[i]) + + """ + + def __init__(self): + pass + + def __getitem__(self, idx): + raise NotImplementedError("'{}' not implement in class "\ + "{}".format('__getitem__', self.__class__.__name__)) + + def __len__(self): + raise NotImplementedError("'{}' not implement in class "\ + "{}".format('__len__', self.__class__.__name__)) + + +class IterableDataset(Dataset): + """ + An abstract class to encapsulate methods and behaviors of iterable datasets. + + All datasets in iterable-style (can only get sample one by one sequentially, like + a Python iterator) should be a subclass of `paddle.io.IterableDataset`. All subclasses should + implement following methods: + + :code:`__iter__`: yield sample sequentially. This method is required by reading dataset sample in :code:`paddle.io.DataLoader`. + + .. note:: + do not implement :code:`__getitem__` and :code:`__len__` in IterableDataset, should not be called either. + + see :code:`paddle.io.DataLoader`. + + Examples: + + .. code-block:: python + + import numpy as np + from paddle.io import IterableDataset + + # define a random dataset + class RandomDataset(IterableDataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __iter__(self): + for i in range(self.num_samples): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + yield image, label + + dataset = RandomDataset(10) + for img, lbl in dataset: + print(img, lbl) + + When :attr:`num_workers > 0`, each worker has a different copy of the dataset object and + will yield whole dataset samples, which means samples in dataset will be repeated in + :attr:`num_workers` times. If it is required for each sample to yield only once, there + are two methods to configure different copy in each worker process to avoid duplicate data + among workers as follows. In both the methods, worker information that can be getted in + a worker process by `paddle.io.get_worker_info` will be needed. + + Example 1: splitting data copy in each worker in :code:`__iter__` + + .. code-block:: python + + import math + import paddle + import numpy as np + from paddle.io import IterableDataset, DataLoader, get_worker_info + + class SplitedIterableDataset(IterableDataset): + def __init__(self, start, end): + self.start = start + self.end = end + + def __iter__(self): + worker_info = get_worker_info() + if worker_info is None: + iter_start = self.start + iter_end = self.end + else: + per_worker = int( + math.ceil((self.end - self.start) / float( + worker_info.num_workers))) + worker_id = worker_info.id + iter_start = self.start + worker_id * per_worker + iter_end = min(iter_start + per_worker, self.end) + + for i in range(iter_start, iter_end): + yield np.array([i]) + + dataset = SplitedIterableDataset(start=2, end=9) + dataloader = DataLoader( + dataset, + num_workers=2, + batch_size=1, + drop_last=True) + + for data in dataloader: + print(data) + # outputs: [2, 5, 3, 6, 4, 7] + + Example 2: splitting data copy in each worker by :code:`worker_init_fn` + + .. code-block:: python + + import math + import paddle + import numpy as np + from paddle.io import IterableDataset, DataLoader, get_worker_info + + class RangeIterableDataset(IterableDataset): + def __init__(self, start, end): + self.start = start + self.end = end + + def __iter__(self): + for i in range(self.start, self.end): + yield np.array([i]) + + dataset = RangeIterableDataset(start=2, end=9) + + def worker_init_fn(worker_id): + worker_info = get_worker_info() + + dataset = worker_info.dataset + start = dataset.start + end = dataset.end + num_per_worker = int( + math.ceil((end - start) / float(worker_info.num_workers))) + + worker_id = worker_info.id + dataset.start = start + worker_id * num_per_worker + dataset.end = min(dataset.start + num_per_worker, end) + + dataloader = DataLoader( + dataset, + num_workers=2, + batch_size=1, + drop_last=True, + worker_init_fn=worker_init_fn) + + for data in dataloader: + print(data) + # outputs: [2, 5, 3, 6, 4, 7] + + """ + + def __init__(self): + pass + + def __iter__(self): + raise NotImplementedError("'{}' not implement in class "\ + "{}".format('__iter__', self.__class__.__name__)) + + def __getitem__(self, idx): + raise RuntimeError("'{}' should not be called for IterableDataset" \ + "{}".format('__getitem__', self.__class__.__name__)) + + def __len__(self): + raise RuntimeError("'{}' should not be called for IterableDataset" \ + "{}".format('__len__', self.__class__.__name__)) + + +class TensorDataset(Dataset): + """ + Dataset defined by a list of tensors. + + Each tensor should be in shape of [N, ...], while N is the sample number, + and ecah tensor contains a field of sample, :code:`TensorDataset` retrieve + each sample by indexing tensors in the 1st dimension. + + Args: + tensors(list|tuple): A list/tuple of tensors with same shape in the 1st dimension. + + Returns: + Dataset: a Dataset instance wrapping tensors. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.io import TensorDataset + + + input_np = np.random.random([2, 3, 4]).astype('float32') + input = paddle.to_tensor(input_np) + label_np = np.random.random([2, 1]).astype('int32') + label = paddle.to_tensor(label_np) + + dataset = TensorDataset([input, label]) + + for i in range(len(dataset)): + input, label = dataset[i] + print(input, label) + + """ + + def __init__(self, tensors): + if not framework._non_static_mode(): + raise RuntimeError( + "TensorDataset con only be used in imperative mode") + assert all([tensor.shape[0] == tensors[0].shape[0] for tensor in tensors]), \ + "tensors not have same shape of the 1st dimension" + self.tensors = tensors + + def __getitem__(self, index): + return tuple(tensor[index] for tensor in self.tensors) + + def __len__(self): + return self.tensors[0].shape[0] + + +def to_list(value): + if value is None: + return value + if isinstance(value, (list, tuple)): + return list(value) + return [value] + + +class ComposeDataset(Dataset): + """ + A Dataset which composes fields of multiple datasets. + + This dataset is used for composing fileds of multiple map-style + datasets of same length. + + Args: + datasets(list of Dataset): List of datasets to be composed. + + Returns: + Dataset: A Dataset which composes fields of multiple datasets. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.io import Dataset, ComposeDataset + + + # define a random dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([32]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + dataset = ComposeDataset([RandomDataset(10), RandomDataset(10)]) + for i in range(len(dataset)): + image1, label1, image2, label2 = dataset[i] + print(image1) + print(label1) + print(image2) + print(label2) + + """ + + def __init__(self, datasets): + self.datasets = list(datasets) + assert len(self.datasets) > 0, "input datasets shoule not be empty" + for i, dataset in enumerate(self.datasets): + assert isinstance(dataset, Dataset), \ + "each input dataset should be paddle.io.Dataset" + assert not isinstance(dataset, IterableDataset), \ + "paddle.io.IterableDataset not supported" + if i > 0: + assert len(dataset) == len(self.datasets[i-1]), \ + "lengths of datasets should be same" + + def __len__(self): + return len(self.datasets[0]) + + def __getitem__(self, idx): + sample = [] + for dataset in self.datasets: + sample.extend(to_list(dataset[idx])) + return tuple(sample) + + +class ChainDataset(IterableDataset): + """ + A Dataset which chains multiple iterable-tyle datasets. + + This dataset is used for assembling multiple datasets which should + be :code:`paddle.io.IterableDataset`. + + Args: + datasets(list of Dataset): List of datasets to be chainned. + + Returns: + Dataset: A Dataset which chains fields of multiple datasets. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.io import IterableDataset, ChainDataset + + + # define a random dataset + class RandomDataset(IterableDataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __iter__(self): + for i in range(10): + image = np.random.random([32]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + yield image, label + + dataset = ChainDataset([RandomDataset(10), RandomDataset(10)]) + for image, label in iter(dataset): + print(image, label) + + """ + + def __init__(self, datasets): + self.datasets = list(datasets) + assert len(self.datasets) > 0, "input datasets shoule not be empty" + for i, dataset in enumerate(self.datasets): + assert isinstance(dataset, IterableDataset), \ + "ChainDataset only support paddle.io.IterableDataset" + + def __iter__(self): + for dataset in self.datasets: + for sample in dataset: + yield sample + + +class Subset(Dataset): + """ + Subset of a dataset at specified indices. + + Args: + dataset (Dataset): The whole Dataset. + indices (sequence): Indices in the whole set selected for subset. + + Returns: + List[Dataset]: A Dataset which is the subset of the original dataset. + + Examples: + + .. code-block:: python + + import paddle + from paddle.io import Subset + + # example 1: + a = paddle.io.Subset(dataset=range(1, 4), indices=[0, 2]) + print(list(a)) + # [1, 3] + + # example 2: + b = paddle.io.Subset(dataset=range(1, 4), indices=[1, 1]) + print(list(b)) + # [2, 2] + """ + + def __init__(self, dataset, indices): + self.dataset = dataset + self.indices = indices + + def __getitem__(self, idx): + return self.dataset[self.indices[idx]] + + def __len__(self): + return len(self.indices) + + +def random_split(dataset, lengths, generator=None): + """ + Randomly split a dataset into non-overlapping new datasets of given lengths. + Optionally fix the generator for reproducible results, e.g.: + + Args: + dataset (Dataset): Dataset to be split + lengths (sequence): lengths of splits to be produced + generator (Generator, optional): Generator used for the random permutation. Default is None then the DefaultGenerator is used in manual_seed(). + + Returns: + Datasets: A list of subset Datasets, which are the non-overlapping subsets of the original Dataset. + + Examples: + + .. code-block:: python + + import paddle + from paddle.io import random_split + + a_list = paddle.io.random_split(range(10), [3, 7]) + print(len(a_list)) + # 2 + + for idx, v in enumerate(a_list[0]): + print(idx, v) + + # output of the first subset + # 0 1 + # 1 3 + # 2 9 + + for idx, v in enumerate(a_list[1]): + print(idx, v) + # output of the second subset + # 0 5 + # 1 7 + # 2 8 + # 3 6 + # 4 0 + # 5 2 + # 6 4 + """ + # Cannot verify that dataset is Sized + if sum(lengths) != len(dataset): # type: ignore + raise ValueError( + "Sum of input lengths does not equal the length of the input dataset!" + ) + # TODO(@Joejiong): support Variable or Tensor type with .tolist class member function. + # For example var.item() and var.tolist() + indices = paddle.randperm(sum(lengths)).numpy().tolist() + return [ + Subset(dataset, indices[offset - length:offset]) + for offset, length in zip(_accumulate(lengths), lengths) + ] + + +def _accumulate(iterable, fn=lambda x, y: x + y): + """ + Return running totals + + Args: + iterable: any iterable object for example dataset. + y (x): one element in the iterable object. + fn (x, y): Defaults to lambdax. + + Yields: + yields total from beginning iterator to current iterator. + + Example code: + + .. code-block:: python + + _accumulate([1,2,3,4,5]) --> 1 3 6 10 15 + _accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 + """ + + it = iter(iterable) + try: + total = next(it) + except StopIteration: + return + yield total + for element in it: + total = fn(total, element) + yield total diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/fetcher.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..387032cdfbbd37e03bf9a58af4486a470f8e95d8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/fetcher.py @@ -0,0 +1,139 @@ +# 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. + +import logging +from ..log_helper import get_logger +from collections.abc import Sequence, Mapping + +_WARNING_TO_LOG = True + + +class _DatasetFetcher(object): + + def __init__(self, dataset, auto_collate_batch, collate_fn, drop_last): + self.dataset = dataset + self.auto_collate_batch = auto_collate_batch + self.collate_fn = collate_fn + self.drop_last = drop_last + + # NOTE: fetch function here perform the whole pipeline of dataset + # reading and data trasforms of a batch in each calling, this + # may take a long time inside, if DataLoader is exit outside, + # fetch need to perceive exit situation, so we pass done_event + # here for fetch to check exit status + # NOTE: if DataLoadet exit by `break`, performing GPU tensor operations, + # e.g. to_tensor may cause SIGSEGV in thread, so we pass the + # done_event argument to check DataLoader exit status between + # ecah sample processing in the batch + def fetch(self, batch_indices, done_event=None): + raise NotImplementedError("'fetch' not implement for class {}".format( + self.__class__.__name__)) + + def _log_warning(self): + # only log warning on GPU 0 when distributed launch + from ...distributed import get_world_size, get_rank + if get_world_size() >= 2 and get_rank() != 0: + return + + warn_str = "Detect dataset only contains single fileds, return format " \ + "changed since Paddle 2.1. In Paddle <= 2.0, DataLoader add " \ + "a list surround output data(e.g. return [data]), and in " \ + "Paddle >= 2.1, DataLoader return the single filed directly " \ + "(e.g. return data). For example, in following code: \n\n" + warn_str += \ + "import numpy as np\n" \ + "from paddle.io import DataLoader, Dataset\n\n" \ + "class RandomDataset(Dataset):\n" \ + " def __getitem__(self, idx):\n" \ + " data = np.random.random((2, 3)).astype('float32')\n\n" \ + " return data\n\n" \ + " def __len__(self):\n" \ + " return 10\n\n" \ + "dataset = RandomDataset()\n" \ + "loader = DataLoader(dataset, batch_size=1)\n" \ + "data = next(loader())\n\n" + + warn_str += "In Paddle <= 2.0, data is in format '[Tensor(shape=(1, 2, 3), " \ + "dtype=float32)]', and in Paddle >= 2.1, data is in format" \ + " 'Tensor(shape=(1, 2, 3), dtype=float32)'\n" + + logger = get_logger("DataLoader", + logging.INFO, + fmt='%(levelname)s: %(message)s') + logger.warning(warn_str) + + +class _IterableDatasetFetcher(_DatasetFetcher): + + def __init__(self, dataset, auto_collate_batch, collate_fn, drop_last): + super(_IterableDatasetFetcher, + self).__init__(dataset, auto_collate_batch, collate_fn, drop_last) + self.dataset_iter = iter(dataset) + + def fetch(self, batch_indices, done_event=None): + + if self.auto_collate_batch: + data = [] + for _ in batch_indices: + if done_event is None or not done_event.is_set(): + try: + data.append(next(self.dataset_iter)) + except StopIteration: + break + else: + return None + + if len(data) == 0 or (self.drop_last + and len(data) < len(batch_indices)): + raise StopIteration + + global _WARNING_TO_LOG + if not isinstance(data[0], (Sequence, Mapping)) \ + and _WARNING_TO_LOG: + self._log_warning() + _WARNING_TO_LOG = False + else: + data = next(self.dataset_iter) + + if self.collate_fn: + data = self.collate_fn(data) + return data + + +class _MapDatasetFetcher(_DatasetFetcher): + + def __init__(self, dataset, auto_collate_batch, collate_fn, drop_last): + super(_MapDatasetFetcher, self).__init__(dataset, auto_collate_batch, + collate_fn, drop_last) + + def fetch(self, batch_indices, done_event=None): + if self.auto_collate_batch: + data = [] + for idx in batch_indices: + if done_event is None or not done_event.is_set(): + data.append(self.dataset[idx]) + else: + return None + + global _WARNING_TO_LOG + if not isinstance(data[0], (Sequence, Mapping)) \ + and _WARNING_TO_LOG: + self._log_warning() + _WARNING_TO_LOG = False + else: + data = self.dataset[batch_indices] + + if self.collate_fn: + data = self.collate_fn(data) + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/flat.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/flat.py new file mode 100644 index 0000000000000000000000000000000000000000..5baf4cc853e27596b36ce485228db6e6a9f3f0d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/flat.py @@ -0,0 +1,144 @@ +# Copyright (c) 2021 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. + +import paddle +import numbers +import numpy as np + +try: + from collections.abc import Sequence, Mapping +except: + from collections import Sequence, Mapping + +FIELD_PREFIX = "_paddle_field_" + + +def _flatten_batch(batch): + """ + For lod_blocking_queue only receive tensor array, flatten batch + data, extract numpy.array data out as a list of numpy.array to + send to lod_blocking_queue, and save the batch data structure + such as fields in other types (str, int, etc) or key-value map + of dictionaries + """ + + def _flatten(batch, flat_batch, structure, field_idx): + if isinstance(batch, Sequence): + for field in batch: + if isinstance(field, (np.ndarray, paddle.Tensor, + paddle.fluid.core.eager.Tensor)): + structure.append('{}{}'.format(FIELD_PREFIX, field_idx)) + flat_batch.append(field) + field_idx += 1 + elif isinstance(field, (str, bytes, numbers.Number)): + structure.append(field) + elif isinstance(field, Sequence): + field_struct, field_idx = _flatten(field, flat_batch, [], + field_idx) + structure.append(field_struct) + elif isinstance(field, Mapping): + field_struct, field_idx = _flatten(field, flat_batch, {}, + field_idx) + structure.append(field_struct) + else: + structure.append(field) + elif isinstance(batch, Mapping): + for k, field in batch.items(): + if isinstance(field, (np.ndarray, paddle.Tensor, + paddle.fluid.core.eager.Tensor)): + structure[k] = '{}{}'.format(FIELD_PREFIX, field_idx) + flat_batch.append(field) + field_idx += 1 + elif isinstance(field, (str, bytes, numbers.Number)): + structure[k] = field + elif isinstance(field, Sequence): + field_struct, field_idx = _flatten(field, flat_batch, [], + field_idx) + structure[k] = field_struct + elif isinstance(field, Mapping): + field_struct, field_idx = _flatten(field, flat_batch, {}, + field_idx) + structure[k] = field_struct + else: + structure[k] = field + else: + raise TypeError("wrong flat data type: {}".format(type(batch))) + + return structure, field_idx + + # sample only contains single fields + if not isinstance(batch, Sequence): + flat_batch = [] + structure, _ = _flatten([batch], flat_batch, [], 0) + return flat_batch, structure[0] + flat_batch = [] + structure, _ = _flatten(batch, flat_batch, [], 0) + return flat_batch, structure + + +def _restore_batch(flat_batch, structure): + """ + After reading list of Tensor data from lod_blocking_queue outputs, + use this function to restore the batch data structrue, replace + :attr:`_paddle_field_x` with data from flat_batch + """ + + def _restore(structure, field_idx): + if isinstance(structure, Sequence): + for i, field in enumerate(structure): + if isinstance(field, str) and field.startswith(FIELD_PREFIX): + cur_field_idx = int(field.replace(FIELD_PREFIX, '')) + field_idx = max(field_idx, cur_field_idx) + assert flat_batch[cur_field_idx] is not None, \ + "flat_batch[{}] parsed repeatly" + structure[i] = flat_batch[cur_field_idx] + flat_batch[cur_field_idx] = None + elif isinstance(field, (str, bytes, numbers.Number)): + continue + elif isinstance(field, (Sequence, Mapping)): + field_idx = _restore(structure[i], field_idx) + elif isinstance(structure, Mapping): + for k, field in structure.items(): + if isinstance(field, str) and field.startswith(FIELD_PREFIX): + cur_field_idx = int(field.replace(FIELD_PREFIX, '')) + field_idx = max(field_idx, cur_field_idx) + assert flat_batch[cur_field_idx] is not None, \ + "flat_batch[{}] parsed repeatly" + structure[k] = flat_batch[cur_field_idx] + flat_batch[cur_field_idx] = None + elif isinstance(field, (str, bytes, numbers.Number)): + continue + elif isinstance(field, (Sequence, Mapping)): + field_idx = _restore(structure[k], field_idx) + else: + raise TypeError("wrong flat data type: {}".format(type(structure))) + + return field_idx + + assert isinstance(flat_batch, Sequence), \ + "flat_batch is not a list or tuple" + + # no np.array in dataset, no output tensor from blocking queue + # simply return structure + if len(flat_batch) == 0: + return structure + + # sample only contains single fields + if isinstance(structure, (str, bytes)): + assert structure == '{}{}'.format(FIELD_PREFIX, 0), \ + "invalid structure: {}".format(structure) + return flat_batch[0] + field_idx = _restore(structure, 0) + assert field_idx + 1 == len(flat_batch), "Tensor parse incomplete" + return structure diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/sampler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..25a46f3b5df2df6851dd0273d1fd75f1e24bcf36 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/sampler.py @@ -0,0 +1,323 @@ +# 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. + +from __future__ import print_function +from __future__ import division + +import numpy as np +from .. import core + +__all__ = [ + "Sampler", "SequenceSampler", "RandomSampler", "WeightedRandomSampler" +] + + +class Sampler(object): + """ + An abstract class to encapsulate methods and behaviors of samplers. + + All sampler used by :code:`paddle.io.BatchSampler` should be a subclass + of :code:`paddle.io.Sampler`, BatchSampler subclasses should + implement following methods: + + :code:`__iter__`: return sample index iterably, which iterate over indices + of dataset elements + + :code:`__len__`: the number of sample in :attr:`data_source` + + + Args: + data_source(Dataset, optional): this could be an instance of + :code:`paddle.io.Dataset` other Python object which + implemented :code:`__len__` for Sampler to get indices + as the range of :attr:`dataset` length. Default None. + + Returns: + Sampler: an iterable object for sample indices iterating + + Examples: + + .. code-block:: python + + from paddle.io import Dataset, Sampler + + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class MySampler(Sampler): + def __init__(self, data_source): + self.data_source = data_source + + def __iter__(self): + return iter(range(len(self.data_source))) + + def __len__(self): + return len(self.data_source) + + sampler = MySampler(data_source=RandomDataset(100)) + + for index in sampler: + print(index) + + see `paddle.io.BatchSampler` + see `paddle.io.DataLoader` + + """ + + def __init__(self, data_source=None): + self.data_source = data_source + + def __iter__(self): + raise NotImplementedError + + # Not define __len__ method in this base class here for __len__ + # is not needed in same sence, e.g. paddle.io.IterableDataset + + +class SequenceSampler(Sampler): + """ + Iterate samples sequentially, yield :code:`0, 1, 2, ..., len(data_source) -1` + generally, + + Args: + data_source(Dataset): dataset to sample, this could be an + instance of :code:`paddle.io.Dataset` other Python + object which implemented :code:`__len__`. + + Returns: + Sampler: a Sampler yield sample index sequentially + + Examples: + + .. code-block:: python + + from paddle.io import Dataset, SequenceSampler + + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + sampler = SequenceSampler(data_source=RandomDataset(100)) + + for index in sampler: + print(index) + + see `paddle.io.Sampler` + """ + + def __init__(self, data_source): + self.data_source = data_source + + def __iter__(self): + return iter(range(len(self.data_source))) + + def __len__(self): + return len(self.data_source) + + +class RandomSampler(Sampler): + """ + Iterate samples randomly, yield shuffled indices, if :attr:`replacement=False`, + yield shuffled indices of the whole data souce, if :attr:`replacement=True`, + :attr:`num_samples` can set to specify the sample number to draw. + + Args: + data_source(Dataset): dataset to sample, this could be an + instance of :code:`paddle.io.Dataset` other Python + object which implemented :code:`__len__`. + replacement(bool): If False, sample the whole dataset, If False, + set :attr:`num_samples` for how many sample to draw. Default False. + num_samples(int): set sample number to draw if :attr:`replacement` + is True. Default None. + generator(Generator): specify a generator to sample the data source. Default None + + Returns: + Sampler: a Sampler yield sample index randomly + + Examples: + + .. code-block:: python + + from paddle.io import Dataset, RandomSampler + + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([784]).astype('float32') + label = np.random.randint(0, 9, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + sampler = RandomSampler(data_source=RandomDataset(100)) + + for index in sampler: + print(index) + + see `paddle.io.Sampler` + """ + + def __init__(self, + data_source, + replacement=False, + num_samples=None, + generator=None): + self.data_source = data_source + self.replacement = replacement + self._num_samples = num_samples + self.generator = generator + + if not isinstance(self.replacement, bool): + raise TypeError("expect boolean value for replacement, but got " + "replacement={}".format(self.replacement)) + + if self._num_samples is not None and not replacement: + raise ValueError( + "num_samples should not be specified while replacement is False" + ) + + if not isinstance(self.num_samples, int) or self.num_samples <= 0: + raise ValueError("num_samples should be a positive integer, " + "but got num_samples={}".format(self.num_samples)) + + @property + def num_samples(self): + if self._num_samples is None: + return len(self.data_source) + return self._num_samples + + def __iter__(self): + n = len(self.data_source) + if self.generator: + for i in range(self.num_samples): + try: + index = next(self.generator) + except StopIteration: + return + yield index + else: + if self.replacement: + for index in np.random.choice(np.arange(n), + self.num_samples, + replace=True).tolist(): + yield index + else: + for index in np.random.choice(np.arange(n), n, + replace=False).tolist(): + yield index + + def __len__(self): + return self.num_samples + + +def _weighted_sample(weights, num_samples, replacement=True): + if isinstance(weights, core.LoDTensor): + weights = weights.numpy() + if isinstance(weights, (list, tuple)): + weights = np.array(weights) + assert isinstance(weights, np.ndarray), \ + "weights should be paddle.Tensor, numpy.ndarray, list or tuple" + assert len(weights.shape) <= 2, \ + "weights should be a 1-D or 2-D array" + weights = weights.reshape((-1, weights.shape[-1])) + assert np.all(weights >= 0.), \ + "weights should be positive value" + assert not np.any(weights == np.inf), \ + "weights shoule not be INF" + assert not np.any(weights == np.nan), \ + "weights shoule not be NaN" + + non_zeros = np.sum(weights > 0., axis=1) + assert np.all(non_zeros > 0), \ + "weights should have positive values" + if not replacement: + assert np.all(non_zeros >= num_samples), \ + "weights positive value number should not " \ + "less than num_samples when replacement=False" + + weights = weights / weights.sum(axis=1) + rets = [] + for i in range(weights.shape[0]): + ret = np.random.choice(weights.shape[1], num_samples, replacement, + weights[i]) + rets.append(ret) + return np.array(rets) + + +class WeightedRandomSampler(Sampler): + """ + Random sample with given weights (probabilities), sampe index will be in range + [0, len(weights) - 1], if :attr:`replacement` is True, index can be sampled + multiple times. + + Args: + weights(numpy.ndarray|paddle.Tensor|list|tuple): sequence of weights, + should be numpy array, paddle.Tensor, list or tuple + num_samples(int): set sample number to draw from sampler. + replacement(bool): Whether to draw sample with replacements, default True + + Returns: + Sampler: a Sampler yield sample index randomly by given weights + + Examples: + + .. code-block:: python + + from paddle.io import WeightedRandomSampler + + sampler = WeightedRandomSampler(weights=[0.1, 0.3, 0.5, 0.7, 0.2], + num_samples=5, + replacement=True) + + for index in sampler: + print(index) + """ + + def __init__(self, weights, num_samples, replacement=True): + if not isinstance(num_samples, int) or num_samples <= 0: + raise ValueError("num_samples should be a positive integer") + if not isinstance(replacement, bool): + raise ValueError("replacement should be a boolean value") + self.weights = weights + self.num_samples = num_samples + self.replacement = replacement + + def __iter__(self): + idxs = _weighted_sample(self.weights, self.num_samples, + self.replacement) + return iter(idxs.reshape((-1)).tolist()) + + def __len__(self): + mul = np.prod(self.weights.shape) // self.weights.shape[-1] + return self.num_samples * mul diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/worker.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..06ea7ef9d72a37b10756c34cda3b66975df4def5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataloader/worker.py @@ -0,0 +1,374 @@ +# Copyright (c) 2021 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. + +import os +import six +import sys +import paddle +import numpy as np +import traceback +from collections import namedtuple +from .. import core +from .fetcher import _IterableDatasetFetcher, _MapDatasetFetcher +from ..multiprocess_utils import _cleanup_mmap, CleanupFuncRegistrar, MP_STATUS_CHECK_INTERVAL +from ..framework import _non_static_mode, _in_eager_without_dygraph_check +from .flat import _flatten_batch + +# NOTE: queue has a different name in python2 and python3 +import queue + +__all__ = ['get_worker_info'] + + +class _IterableDatasetStopIteration(object): + + def __init__(self, worker_id): + self.worker_id = worker_id + + +class _ResumeIteration(object): + pass + + +class _DatasetKind(object): + MAP = 0 + ITER = 1 + + @staticmethod + def create_fetcher(kind, dataset, auto_collate_batch, collate_fn, + drop_last): + if kind == _DatasetKind.MAP: + return _MapDatasetFetcher(dataset, auto_collate_batch, collate_fn, + drop_last) + elif kind == _DatasetKind.ITER: + return _IterableDatasetFetcher(dataset, auto_collate_batch, + collate_fn, drop_last) + else: + raise NotImplementedError("unknown Dataset kind {}".format(kind)) + + +class ParentWatchDog(object): + + def __init__(self): + self._parent_pid = os.getppid() + self._parent_alive = True + + def is_alive(self): + if self._parent_alive: + self._parent_alive = os.getppid() == self._parent_pid + return self._parent_alive + + +# worker information for each workers, used for splitting data copy +# for IteratorDataset in worker processes. +_worker_info = None + + +def get_worker_info(): + """ + Get DataLoader worker process information function, this function is + used to split data copy in worker process for IterableDataset + (see :code:`paddle.io.IterableDataset`), worker information contains + following fields: + + :attr:`num_workers`: total worker process number, see `paddle.io.DataLoader` + + :attr:`id`: the worker processs id, count from 0 to :attr:`num_workers - 1` + + :attr:`dataset`: the dataset object in this worker process + + Returns: + WorkerInfo: an instance of WorkerInfo which contains fields above. + + .. note:: + For more usage and examples, please see :code:`paddle.io.IterableDataset` + + Example: + + .. code-block:: python + + import math + import paddle + import numpy as np + from paddle.io import IterableDataset, DataLoader, get_worker_info + + class SplitedIterableDataset(IterableDataset): + def __init__(self, start, end): + self.start = start + self.end = end + + def __iter__(self): + worker_info = get_worker_info() + if worker_info is None: + iter_start = self.start + iter_end = self.end + else: + per_worker = int( + math.ceil((self.end - self.start) / float( + worker_info.num_workers))) + worker_id = worker_info.id + iter_start = self.start + worker_id * per_worker + iter_end = min(iter_start + per_worker, self.end) + + for i in range(iter_start, iter_end): + yield np.array([i]) + + place = paddle.CPUPlace() + dataset = SplitedIterableDataset(start=2, end=9) + dataloader = DataLoader( + dataset, + places=place, + num_workers=2, + batch_size=1, + drop_last=True) + + for data in dataloader: + print(data) + # outputs: [2, 5, 3, 6, 4, 7] + + """ + return _worker_info + + +class WorkerInfo(object): + __initialized = False + + def __init__(self, **kwargs): + for k, v in kwargs.items(): + setattr(self, k, v) + self.__initialized = True + + def __setattr__(self, key, val): + if self.__initialized: + raise RuntimeError("Cannot assign attributes to {} objects".format( + self.__class__.__name__)) + return super(WorkerInfo, self).__setattr__(key, val) + + +class _WorkerException(object): + + def __init__(self, worker_id, exc_info=None): + self.worker_id = worker_id + exc_info = exc_info or sys.exc_info() + self.exc_type = exc_info[0] + self.exc_msg = "".join(traceback.format_exception(*exc_info)) + + def reraise(self): + msg = "DataLoader worker({}) caught {} with message:\n{}".format( + self.worker_id, self.exc_type.__name__, self.exc_msg) + if getattr(self.exc_type, "message", None): + raise self.exc_type(message=msg) + raise self.exc_type(msg) + + +# The function `_generate_states` is adapted from `numpy.random.SeedSequence` +# from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx +# Here is the copyright: + +# SeedSequence is derived from Melissa E. O'Neill's C++11 `std::seed_seq` +# implementation, as it has a lot of nice properties that we want. +# https://gist.github.com/imneme/540829265469e673d045 +# http://www.pcg-random.org/posts/developing-a-seed_seq-alternative.html + +# The MIT License (MIT) + +# Copyright (c) 2015 Melissa E. O'Neill +# Copyright (c) 2019 NumPy Developers +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +INIT_A = 0x43b0d7e5 +MULT_A = 0x931e8875 +INIT_B = 0x8b51f9dd +MULT_B = 0x58f38ded +MIX_MULT_L = 0xca01f9dd +MIX_MULT_R = 0x4973f715 +XSHIFT = np.dtype(np.uint32).itemsize * 8 // 2 +MASK32 = 0xFFFFFFFF + + +def _generate_states(base_seed=0, worker_id=0): + # init hash constant + hash_const_A = INIT_A + hash_const_B = INIT_B + + def hash(value): + nonlocal hash_const_A + value = (value ^ hash_const_A) & MASK32 + hash_const_A = (hash_const_A * MULT_A) & MASK32 + value = (value * hash_const_A) & MASK32 + value = (value ^ (value >> XSHIFT)) & MASK32 + return value + + def mix(x, y): + result_x = (MIX_MULT_L * x) & MASK32 + result_y = (MIX_MULT_R * y) & MASK32 + result = (result_x - result_y) & MASK32 + result = (result ^ (result >> XSHIFT)) & MASK32 + return result + + # init entropys with based_seed and worker_id and calculate pool + entropys = [worker_id, base_seed & MASK32, base_seed >> 32, 0] + pool = [hash(entropy) for entropy in entropys] + + # mix all bits together + for i in range(len(pool)): + for j in range(len(pool)): + if i != j: + pool[j] = mix(pool[j], hash(pool[i])) + + states = [] + for p in pool: + state = (p ^ hash_const_B) & MASK32 + hash_const_B = (hash_const_B * MULT_B) & MASK32 + state = (state * hash_const_B) & MASK32 + state = (state ^ (state >> XSHIFT)) & MASK32 + states.append(state) + + return states + + +def _worker_loop(dataset, dataset_kind, indices_queue, out_queue, done_event, + auto_collate_batch, collate_fn, drop_last, init_fn, worker_id, + num_workers, use_shared_memory, base_seed): + try: + # NOTE: [ mmap files clear ] When the child process exits unexpectedly, + # some shared memory objects may have been applied for but have not yet + # been put into the inter-process Queue. This part of the object needs + # to be cleaned up when the process ends. + CleanupFuncRegistrar.register(_cleanup_mmap) + + # set signal handler + core._set_process_signal_handler() + + # set different numpy seed for each worker + try: + import numpy as np + import time + import random + except ImportError: + pass + else: + seed = base_seed + worker_id + random.seed(seed) + paddle.seed(seed) + np.random.seed(_generate_states(base_seed, worker_id)) + + global _worker_info + _worker_info = WorkerInfo(id=worker_id, + num_workers=num_workers, + dataset=dataset, + seed=base_seed) + + init_exception = None + try: + if init_fn is not None: + init_fn(worker_id) + fetcher = _DatasetKind.create_fetcher(dataset_kind, dataset, + auto_collate_batch, + collate_fn, drop_last) + except: + init_exception = _WorkerException(worker_id) + + iterator_drained = False + parent_watch_dog = ParentWatchDog() + + while parent_watch_dog.is_alive(): + try: + data = indices_queue.get(MP_STATUS_CHECK_INTERVAL) + except queue.Empty: + continue + + if isinstance(data, _ResumeIteration): + out_queue.put((data, None, None)) + iterator_drained = False + fetcher = _DatasetKind.create_fetcher(dataset_kind, dataset, + auto_collate_batch, + collate_fn, True) + continue + + # None as poison piil, so worker event should be set + if data is None: + assert done_event.is_set() or iterator_drained, \ + "get None when worker done_event set" + break + # If worker done event is set but get still get data in + # indices_queue, remaining data should be get and skipped. + if done_event.is_set() or iterator_drained: + continue + + idx, indices = data + try: + if init_exception is not None: + batch = init_exception + init_exception = None + else: + # NOTE: GPU tensor operation is not supported in sub-process + # but default device is GPU in paddle-gpu version, which + # may copy CPU tensor to GPU even if users want to use + # CPU tensor operation, so we add CPUPlace guard here + # to make sure tensor will be operated only on CPU + with paddle.fluid.dygraph.guard(place=paddle.CPUPlace()): + batch = fetcher.fetch(indices) + except Exception as e: + if isinstance( + e, StopIteration) and dataset_kind == _DatasetKind.ITER: + out_queue.put(_IterableDatasetStopIteration(worker_id)) + iterator_drained = True + else: + out_queue.put((idx, _WorkerException(worker_id), None)) + else: + if isinstance(batch, _WorkerException): + out_queue.put((idx, batch, None)) + batch, structure = _flatten_batch(batch) + if use_shared_memory: + # NOTE: In eager mode, Tensor._share_memory has no + # effect, fall back to _array_to_share_memory_tensor + def tensor_share_memory(tensor): + if _in_eager_without_dygraph_check(): + return core._array_to_share_memory_tensor(tensor) + return tensor._share_memory() + tensor_list = [ + core._array_to_share_memory_tensor(b) + if isinstance(b, np.ndarray) \ + else tensor_share_memory(b) for b in batch + ] + out_queue.put((idx, tensor_list, structure)) + core._remove_tensor_list_mmap_fds(tensor_list) + else: + out_queue.put((idx, batch, structure)) + except KeyboardInterrupt: + # NOTE: Main process will raise KeyboardInterrupt anyways, ignore it in child process + pass + except: + six.reraise(*sys.exc_info()) + finally: + if use_shared_memory: + _cleanup_mmap() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..9fba7bb70f189e9914792b221f733e3578f81460 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dataset.py @@ -0,0 +1,1338 @@ +# Copyright (c) 2018 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. +"""This is definition of dataset class, which is high performance IO.""" + +from paddle.fluid.proto import data_feed_pb2 +from google.protobuf import text_format +from . import core +from ..utils import deprecated + +__all__ = ['DatasetFactory', 'InMemoryDataset', 'QueueDataset'] + + +class DatasetFactory(object): + """ + DatasetFactory is a factory which create dataset by its name, + you can create "QueueDataset" or "InMemoryDataset", or "FileInstantDataset", + the default is "QueueDataset". + + Example: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + + """ + + def __init__(self): + """ Init. """ + pass + + def create_dataset(self, datafeed_class="QueueDataset"): + """ + Create "QueueDataset" or "InMemoryDataset", or "FileInstantDataset", + the default is "QueueDataset". + + Args: + datafeed_class(str): datafeed class name, QueueDataset or InMemoryDataset. + Default is QueueDataset. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + + """ + try: + dataset = globals()[datafeed_class]() + return dataset + except: + raise ValueError("datafeed class %s does not exist" % + datafeed_class) + + +class DatasetBase(object): + """ Base dataset class. """ + + def __init__(self): + """ Init. """ + # define class name here + # to decide whether we need create in memory instance + self.proto_desc = data_feed_pb2.DataFeedDesc() + self.proto_desc.pipe_command = "cat" + self.dataset = core.Dataset("MultiSlotDataset") + self.thread_num = 1 + self.filelist = [] + self.use_ps_gpu = False + self.psgpu = None + + def set_pipe_command(self, pipe_command): + """ + Set pipe command of current dataset + A pipe command is a UNIX pipeline command that can be used only + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_pipe_command("python my_script.py") + + Args: + pipe_command(str): pipe command + + """ + self.proto_desc.pipe_command = pipe_command + + def set_so_parser_name(self, so_parser_name): + """ + Set so parser name of current dataset + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_so_parser_name("./abc.so") + + Args: + pipe_command(str): pipe command + + """ + self.proto_desc.so_parser_name = so_parser_name + + def set_rank_offset(self, rank_offset): + """ + Set rank_offset for merge_pv. It set the message of Pv. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_rank_offset("rank_offset") + + Args: + rank_offset(str): rank_offset's name + + """ + self.proto_desc.rank_offset = rank_offset + + def set_fea_eval(self, record_candidate_size, fea_eval=True): + """ + set fea eval mode for slots shuffle to debug the importance level of + slots(features), fea_eval need to be set True for slots shuffle. + + Args: + record_candidate_size(int): size of instances candidate to shuffle + one slot + fea_eval(bool): whether enable fea eval mode to enable slots shuffle. + default is True. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_fea_eval(1000000, True) + + """ + if fea_eval: + self.dataset.set_fea_eval(fea_eval, record_candidate_size) + self.fea_eval = fea_eval + + def slots_shuffle(self, slots): + """ + Slots Shuffle + Slots Shuffle is a shuffle method in slots level, which is usually used + in sparse feature with large scale of instances. To compare the metric, i.e. + auc while doing slots shuffle on one or several slots with baseline to + evaluate the importance level of slots(features). + + Args: + slots(list[string]): the set of slots(string) to do slots shuffle. + + Examples: + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_merge_by_lineid() + #suppose there is a slot 0 + dataset.slots_shuffle(['0']) + """ + if self.fea_eval: + slots_set = set(slots) + self.dataset.slots_shuffle(slots_set) + + def set_batch_size(self, batch_size): + """ + Set batch size. Will be effective during training + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_batch_size(128) + + Args: + batch_size(int): batch size + + """ + self.proto_desc.batch_size = batch_size + + def set_pv_batch_size(self, pv_batch_size): + """ + Set pv batch size. It will be effective during enable_pv_merge + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_pv_batch(128) + Args: + pv_batch_size(int): pv batch size + + """ + self.proto_desc.pv_batch_size = pv_batch_size + + def set_thread(self, thread_num): + """ + Set thread num, it is the num of readers. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_thread(12) + + Args: + thread_num(int): thread num + """ + self.dataset.set_thread_num(thread_num) + self.thread_num = thread_num + + def set_filelist(self, filelist): + """ + Set file list in current worker. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_filelist(['a.txt', 'b.txt']) + + Args: + filelist(list): file list + """ + self.dataset.set_filelist(filelist) + self.filelist = filelist + + def set_input_type(self, input_type): + self.proto_desc.input_type = input_type + + def set_use_var(self, var_list): + """ + Set Variables which you will use. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_use_var([data, label]) + + Args: + var_list(list): variable list + """ + multi_slot = self.proto_desc.multi_slot_desc + for var in var_list: + slot_var = multi_slot.slots.add() + slot_var.is_used = True + slot_var.name = var.name + if var.lod_level == 0: + slot_var.is_dense = True + slot_var.shape.extend(var.shape) + if var.dtype == core.VarDesc.VarType.FP32: + slot_var.type = "float" + elif var.dtype == core.VarDesc.VarType.INT64: + slot_var.type = "uint64" + elif var.dtype == core.VarDesc.VarType.INT32: + slot_var.type = "uint32" + else: + raise ValueError( + "Currently, fluid.dataset only supports dtype=float32, dtype=int32 and dtype=int64" + ) + + def set_hdfs_config(self, fs_name, fs_ugi): + """ + Set hdfs config: fs name ad ugi + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_hdfs_config("my_fs_name", "my_fs_ugi") + + Args: + fs_name(str): fs name + fs_ugi(str): fs ugi + """ + self.dataset.set_hdfs_config(fs_name, fs_ugi) + + def set_download_cmd(self, download_cmd): + """ + Set customized download cmd: download_cmd + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + dataset.set_download_cmd("./read_from_afs") + + Args: + download_cmd(str): customized download command + """ + self.dataset.set_download_cmd(download_cmd) + + def _prepare_to_run(self): + """ + Set data_feed_desc before load or shuffle, + user no need to call this function. + """ + if self.thread_num > len(self.filelist): + self.thread_num = len(self.filelist) + self.dataset.set_thread_num(self.thread_num) + self.dataset.set_data_feed_desc(self.desc()) + self.dataset.create_readers() + + def _set_use_ps_gpu(self, psgpu): + """ + set use_ps_gpu flag + + Args: + use_ps_gpu: bool + """ + self.use_ps_gpu = True + # if not defined heterps with paddle, users will not use psgpu + if not core._is_compiled_with_heterps(): + self.use_ps_gpu = False + elif self.use_ps_gpu: + self.psgpu = psgpu + + def _finish_to_run(self): + self.dataset.destroy_readers() + + def desc(self): + """ + Returns a protobuf message for this DataFeedDesc + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset() + print(dataset.desc()) + + Returns: + A string message + """ + return text_format.MessageToString(self.proto_desc) + + def _dynamic_adjust_before_train(self, thread_num): + pass + + def _dynamic_adjust_after_train(self): + pass + + +class InMemoryDataset(DatasetBase): + """ + InMemoryDataset, it will load data into memory + and shuffle data before training. + This class should be created by DatasetFactory + + Example: + dataset = paddle.fluid.DatasetFactory().create_dataset("InMemoryDataset") + """ + + @deprecated(since="2.0.0", update_to="paddle.distributed.InMemoryDataset") + def __init__(self): + """ Init. """ + super(InMemoryDataset, self).__init__() + self.proto_desc.name = "MultiSlotInMemoryDataFeed" + self.fleet_send_batch_size = None + self.is_user_set_queue_num = False + self.queue_num = None + self.parse_ins_id = False + self.parse_content = False + self.parse_logkey = False + self.merge_by_sid = True + self.enable_pv_merge = False + self.merge_by_lineid = False + self.fleet_send_sleep_seconds = None + self.trainer_num = -1 + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_feed_type") + def set_feed_type(self, data_feed_type): + """ + Set data_feed_desc + """ + self.proto_desc.name = data_feed_type + if (self.proto_desc.name == "SlotRecordInMemoryDataFeed"): + self.dataset = core.Dataset("SlotRecordDataset") + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._prepare_to_run") + def _prepare_to_run(self): + """ + Set data_feed_desc before load or shuffle, + user no need to call this function. + """ + if self.thread_num <= 0: + self.thread_num = 1 + self.dataset.set_thread_num(self.thread_num) + if self.queue_num is None: + self.queue_num = self.thread_num + self.dataset.set_queue_num(self.queue_num) + self.dataset.set_parse_ins_id(self.parse_ins_id) + self.dataset.set_parse_content(self.parse_content) + self.dataset.set_parse_logkey(self.parse_logkey) + self.dataset.set_merge_by_sid(self.merge_by_sid) + self.dataset.set_enable_pv_merge(self.enable_pv_merge) + self.dataset.set_data_feed_desc(self.desc()) + self.dataset.create_channel() + self.dataset.create_readers() + + @deprecated( + since="2.0.0", + update_to= + "paddle.distributed.InMemoryDataset._dynamic_adjust_before_train") + def _dynamic_adjust_before_train(self, thread_num): + if not self.is_user_set_queue_num: + if self.use_ps_gpu: + self.dataset.dynamic_adjust_channel_num(thread_num, True) + else: + self.dataset.dynamic_adjust_channel_num(thread_num, False) + self.dataset.dynamic_adjust_readers_num(thread_num) + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._dynamic_adjust_after_train" + ) + def _dynamic_adjust_after_train(self): + if not self.is_user_set_queue_num: + if self.use_ps_gpu: + self.dataset.dynamic_adjust_channel_num(self.thread_num, True) + else: + self.dataset.dynamic_adjust_channel_num(self.thread_num, False) + self.dataset.dynamic_adjust_readers_num(self.thread_num) + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_queue_num") + def set_queue_num(self, queue_num): + """ + Set Dataset output queue num, training threads get data from queues + + Args: + queue_num(int): dataset output queue num + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_queue_num(12) + + """ + self.is_user_set_queue_num = True + self.queue_num = queue_num + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_parse_ins_id" + ) + def set_parse_ins_id(self, parse_ins_id): + """ + Set id Dataset need to parse insid + + Args: + parse_ins_id(bool): if parse ins_id or not + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_parse_ins_id(True) + + """ + self.parse_ins_id = parse_ins_id + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_parse_content") + def set_parse_content(self, parse_content): + """ + Set if Dataset need to parse content + + Args: + parse_content(bool): if parse content or not + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_parse_content(True) + + """ + self.parse_content = parse_content + + def set_parse_logkey(self, parse_logkey): + """ + Set if Dataset need to parse logkey + + Args: + parse_content(bool): if parse logkey or not + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_parse_logkey(True) + + """ + self.parse_logkey = parse_logkey + + def _set_trainer_num(self, trainer_num): + """ + Set trainer num + + Args: + trainer_num(int): trainer num + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset._set_trainer_num(1) + + """ + self.trainer_num = trainer_num + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_merge_by_sid" + ) + def set_merge_by_sid(self, merge_by_sid): + """ + Set if Dataset need to merge sid. If not, one ins means one Pv. + + Args: + merge_by_sid(bool): if merge sid or not + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_merge_by_sid(True) + + """ + self.merge_by_sid = merge_by_sid + + def set_enable_pv_merge(self, enable_pv_merge): + """ + Set if Dataset need to merge pv. + + Args: + enable_pv_merge(bool): if enable_pv_merge or not + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_enable_pv_merge(True) + + """ + self.enable_pv_merge = enable_pv_merge + + def preprocess_instance(self): + """ + Merge pv instance and convey it from input_channel to input_pv_channel. + It will be effective when enable_pv_merge_ is True. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.preprocess_instance() + + """ + self.dataset.preprocess_instance() + + def set_current_phase(self, current_phase): + """ + Set current phase in train. It is useful for untest. + current_phase : 1 for join, 0 for update. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.set_current_phase(1) + + """ + self.dataset.set_current_phase(current_phase) + + def postprocess_instance(self): + """ + Divide pv instance and convey it to input_channel. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.preprocess_instance() + exe.train_from_dataset(dataset) + dataset.postprocess_instance() + + """ + self.dataset.postprocess_instance() + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_fleet_send_batch_size" + ) + def set_fleet_send_batch_size(self, fleet_send_batch_size=1024): + """ + Set fleet send batch size, default is 1024 + + Args: + fleet_send_batch_size(int): fleet send batch size + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_fleet_send_batch_size(800) + + """ + self.fleet_send_batch_size = fleet_send_batch_size + + @deprecated( + since="2.0.0", + update_to= + "paddle.distributed.InMemoryDataset._set_fleet_send_sleep_seconds") + def set_fleet_send_sleep_seconds(self, fleet_send_sleep_seconds=0): + """ + Set fleet send sleep time, default is 0 + + Args: + fleet_send_sleep_seconds(int): fleet send sleep time + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_fleet_send_sleep_seconds(2) + + """ + self.fleet_send_sleep_seconds = fleet_send_sleep_seconds + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset._set_merge_by_lineid") + def set_merge_by_lineid(self, merge_size=2): + """ + Set merge by line id, instances of same line id will be merged after + shuffle, you should parse line id in data generator. + + Args: + merge_size(int): ins size to merge. default is 2. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_merge_by_lineid() + + """ + self.dataset.set_merge_by_lineid(merge_size) + self.merge_by_lineid = True + self.parse_ins_id = True + + @deprecated( + since="2.0.0", + update_to= + "paddle.distributed.InMemoryDataset._set_generate_unique_feasigns") + def set_generate_unique_feasigns(self, generate_uni_feasigns, shard_num): + self.dataset.set_generate_unique_feasigns(generate_uni_feasigns) + self.gen_uni_feasigns = generate_uni_feasigns + self.local_shard_num = shard_num + + @deprecated( + since="2.0.0", + update_to= + "paddle.distributed.InMemoryDataset._generate_local_tables_unlock") + def generate_local_tables_unlock(self, table_id, fea_dim, read_thread_num, + consume_thread_num, shard_num): + self.dataset.generate_local_tables_unlock(table_id, fea_dim, + read_thread_num, + consume_thread_num, shard_num) + + def set_date(self, date): + """ + :api_attr: Static Graph + + Set training date for pull sparse parameters, saving and loading model. Only used in psgpu + + Args: + date(str): training date(format : YYMMDD). eg.20211111 + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_date("20211111") + """ + year = int(date[:4]) + month = int(date[4:6]) + day = int(date[6:]) + if self.use_ps_gpu and core._is_compiled_with_heterps(): + self.psgpu.set_date(year, month, day) + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.load_into_memory") + def load_into_memory(self, is_shuffle=False): + """ + Load data into memory + + Args: + is_shuffle(bool): whether to use local shuffle, default is False + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + """ + self._prepare_to_run() + if not self.use_ps_gpu: + self.dataset.load_into_memory() + elif core._is_compiled_with_heterps(): + self.psgpu.set_dataset(self.dataset) + self.psgpu.load_into_memory(is_shuffle) + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.preload_into_memory") + def preload_into_memory(self, thread_num=None): + """ + Load data into memory in async mode + + Args: + thread_num(int): preload thread num + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self._prepare_to_run() + if thread_num is None: + thread_num = self.thread_num + self.dataset.set_preload_thread_num(thread_num) + self.dataset.create_preload_readers() + self.dataset.preload_into_memory() + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.wait_preload_done" + ) + def wait_preload_done(self): + """ + Wait preload_into_memory done + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self.dataset.wait_preload_done() + self.dataset.destroy_preload_readers() + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.local_shuffle") + def local_shuffle(self): + """ + Local shuffle + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.local_shuffle() + """ + self.dataset.local_shuffle() + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.global_shuffle") + def global_shuffle(self, fleet=None, thread_num=12): + """ + Global shuffle. + Global shuffle can be used only in distributed mode. i.e. multiple + processes on single machine or multiple machines training together. + If you run in distributed mode, you should pass fleet instead of None. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle(fleet) + + Args: + fleet(Fleet): fleet singleton. Default None. + thread_num(int): shuffle thread num. Default is 12. + + """ + if fleet is not None: + if hasattr(fleet, "barrier_worker"): + print("pscore fleet") + fleet.barrier_worker() + else: + fleet._role_maker.barrier_worker() + if self.trainer_num == -1: + self.trainer_num = fleet.worker_num() + if self.fleet_send_batch_size is None: + self.fleet_send_batch_size = 1024 + if self.fleet_send_sleep_seconds is None: + self.fleet_send_sleep_seconds = 0 + self.dataset.register_client2client_msg_handler() + self.dataset.set_trainer_num(self.trainer_num) + self.dataset.set_fleet_send_batch_size(self.fleet_send_batch_size) + self.dataset.set_fleet_send_sleep_seconds(self.fleet_send_sleep_seconds) + if fleet is not None: + if hasattr(fleet, "barrier_worker"): + fleet.barrier_worker() + else: + fleet._role_maker.barrier_worker() + self.dataset.global_shuffle(thread_num) + if fleet is not None: + if hasattr(fleet, "barrier_worker"): + fleet.barrier_worker() + else: + fleet._role_maker.barrier_worker() + if self.merge_by_lineid: + self.dataset.merge_by_lineid() + if fleet is not None: + if hasattr(fleet, "barrier_worker"): + fleet.barrier_worker() + else: + fleet._role_maker.barrier_worker() + + @deprecated(since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.release_memory") + def release_memory(self): + """ + :api_attr: Static Graph + + Release InMemoryDataset memory data, when data will not be used again. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle(fleet) + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + exe.train_from_dataset(fluid.default_main_program(), dataset) + dataset.release_memory() + + """ + self.dataset.release_memory() + + def get_pv_data_size(self): + """ + Get memory data size of Pv, user can call this function to know the pv num + of ins in all workers after load into memory. + + Note: + This function may cause bad performance, because it has barrier + + Returns: + The size of memory pv data. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + print dataset.get_pv_data_size() + + """ + return self.dataset.get_pv_data_size() + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.get_memory_data_size") + def get_memory_data_size(self, fleet=None): + """ + Get memory data size, user can call this function to know the num + of ins in all workers after load into memory. + + Note: + This function may cause bad performance, because it has barrier + + Args: + fleet(Fleet): Fleet Object. + + Returns: + The size of memory data. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + print dataset.get_memory_data_size(fleet) + + """ + import numpy as np + local_data_size = self.dataset.get_memory_data_size() + local_data_size = np.array([local_data_size]) + if fleet is not None: + global_data_size = local_data_size * 0 + fleet._role_maker.all_reduce_worker(local_data_size, + global_data_size) + return global_data_size[0] + return local_data_size[0] + + @deprecated( + since="2.0.0", + update_to="paddle.distributed.InMemoryDataset.get_shuffle_data_size") + def get_shuffle_data_size(self, fleet=None): + """ + Get shuffle data size, user can call this function to know the num + of ins in all workers after local/global shuffle. + + Note: + This function may cause bad performance to local shuffle, + because it has barrier. It does not affect global shuffle. + + Args: + fleet(Fleet): Fleet Object. + + Returns: + The size of shuffle data. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + dataset.global_shuffle(fleet) + print dataset.get_shuffle_data_size(fleet) + + """ + import numpy as np + local_data_size = self.dataset.get_shuffle_data_size() + local_data_size = np.array([local_data_size]) + print('global shuffle local_data_size: ', local_data_size) + if fleet is not None: + global_data_size = local_data_size * 0 + if hasattr(fleet, "util"): + global_data_size = fleet.util.all_reduce(local_data_size) + else: + fleet._role_maker.all_reduce_worker(local_data_size, + global_data_size) + return global_data_size[0] + return local_data_size[0] + + def _set_heter_ps(self, enable_heter_ps=False): + """ + Set heter ps mode + user no need to call this function. + """ + self.dataset.set_heter_ps(enable_heter_ps) + + def set_graph_config(self, config): + """ + Set graph config, user can set graph config in gpu graph mode. + + Args: + config(dict): config dict. + + Returns: + The size of shuffle data. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + graph_config = {"walk_len": 24, + "walk_degree": 10, + "once_sample_startid_len": 80000, + "sample_times_one_chunk": 5, + "window": 3, + "debug_mode": 0, + "batch_size": 800, + "meta_path": "cuid2clk-clk2cuid;cuid2conv-conv2cuid;clk2cuid-cuid2clk;clk2cuid-cuid2conv", + "gpu_graph_training": 1} + dataset.set_graph_config(graph_config) + + """ + self.proto_desc.graph_config.walk_degree = config.get("walk_degree", 1) + self.proto_desc.graph_config.walk_len = config.get("walk_len", 20) + self.proto_desc.graph_config.window = config.get("window", 5) + self.proto_desc.graph_config.once_sample_startid_len = config.get( + "once_sample_startid_len", 8000) + self.proto_desc.graph_config.sample_times_one_chunk = config.get( + "sample_times_one_chunk", 10) + self.proto_desc.graph_config.batch_size = config.get("batch_size", 1) + self.proto_desc.graph_config.debug_mode = config.get("debug_mode", 0) + self.proto_desc.graph_config.first_node_type = config.get( + "first_node_type", "") + self.proto_desc.graph_config.meta_path = config.get("meta_path", "") + self.proto_desc.graph_config.gpu_graph_training = config.get( + "gpu_graph_training", True) + self.dataset.set_gpu_graph_mode(True) + + +class QueueDataset(DatasetBase): + """ + QueueDataset, it will process data streamly. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("QueueDataset") + + """ + + def __init__(self): + """ + Initialize QueueDataset + This class should be created by DatasetFactory + """ + super(QueueDataset, self).__init__() + self.proto_desc.name = "MultiSlotDataFeed" + + @deprecated(since="2.0.0", + update_to="paddle.distributed.QueueDataset._prepare_to_run") + def _prepare_to_run(self): + """ + Set data_feed_desc/thread num/filelist before run, + user no need to call this function. + """ + if self.thread_num > len(self.filelist): + self.thread_num = len(self.filelist) + if self.thread_num == 0: + self.thread_num = 1 + self.dataset.set_thread_num(self.thread_num) + self.dataset.set_filelist(self.filelist) + self.dataset.set_data_feed_desc(self.desc()) + self.dataset.create_readers() + + def local_shuffle(self): + """ + Local shuffle data. + + Local shuffle is not supported in QueueDataset + NotImplementedError will be raised + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("QueueDataset") + dataset.local_shuffle() + + Raises: + NotImplementedError: QueueDataset does not support local shuffle + + """ + raise NotImplementedError( + "QueueDataset does not support local shuffle, " + "please use InMemoryDataset for local_shuffle") + + def global_shuffle(self, fleet=None): + """ + Global shuffle data. + + Global shuffle is not supported in QueueDataset + NotImplementedError will be raised + + Args: + fleet(Fleet): fleet singleton. Default None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + dataset = fluid.DatasetFactory().create_dataset("QueueDataset") + dataset.global_shuffle(fleet) + + Raises: + NotImplementedError: QueueDataset does not support global shuffle + + """ + raise NotImplementedError( + "QueueDataset does not support global shuffle, " + "please use InMemoryDataset for global_shuffle") + + +class FileInstantDataset(DatasetBase): + """ + FileInstantDataset, it will process data streamly. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory.create_dataset("FileInstantDataset") + """ + + def __init__(self): + """ + Initialize FileInstantDataset + This class should be created by DatasetFactory + """ + super(FileInstantDataset, self).__init__() + self.proto_desc.name = "MultiSlotFileInstantDataFeed" + + def local_shuffle(self): + """ + Local shuffle + FileInstantDataset does not support local shuffle + """ + raise NotImplementedError( + "FileInstantDataset does not support local shuffle, " + "please use InMemoryDataset for local_shuffle") + + def global_shuffle(self, fleet=None): + """ + Global shuffle + FileInstantDataset does not support global shuffle + """ + raise NotImplementedError( + "FileInstantDataset does not support global shuffle, " + "please use InMemoryDataset for global_shuffle") + + +class BoxPSDataset(InMemoryDataset): + """ + BoxPSDataset: derived from InMemoryDataset. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + """ + + def __init__(self): + """ + Initialize BoxPSDataset + This class should be created by DatasetFactory + """ + super(BoxPSDataset, self).__init__() + self.boxps = core.BoxPS(self.dataset) + self.proto_desc.name = "PaddleBoxDataFeed" + + def set_date(self, date): + """ + Workaround for date + """ + year = int(date[:4]) + month = int(date[4:6]) + day = int(date[6:]) + self.boxps.set_date(year, month, day) + + def begin_pass(self): + """ + Begin Pass + Notify BoxPS to load sparse parameters of next pass to GPU Memory + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + dataset.begin_pass() + """ + self.boxps.begin_pass() + + def end_pass(self, need_save_delta): + """ + End Pass + Notify BoxPS that current pass ended + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + dataset.end_pass(True) + """ + self.boxps.end_pass(need_save_delta) + + def wait_preload_done(self): + """ + Wait async preload done + Wait Until Feed Pass Done + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + dataset.wait_preload_done() + """ + self.boxps.wait_feed_pass_done() + + def load_into_memory(self): + """ + Load next pass into memory and notify boxps to fetch its emb from SSD + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.load_into_memory() + """ + self._prepare_to_run() + self.boxps.load_into_memory() + + def preload_into_memory(self): + """ + Begin async preload next pass while current pass may be training + Examples: + .. code-block:: python + + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset") + filelist = ["a.txt", "b.txt"] + dataset.set_filelist(filelist) + dataset.preload_into_memory() + """ + self._prepare_to_run() + self.boxps.preload_into_memory() + + def _dynamic_adjust_before_train(self, thread_num): + if not self.is_user_set_queue_num: + self.dataset.dynamic_adjust_channel_num(thread_num, True) + self.dataset.dynamic_adjust_readers_num(thread_num) + + def _dynamic_adjust_after_train(self): + pass + + def slots_shuffle(self, slots): + """ + Slots Shuffle + Slots Shuffle is a shuffle method in slots level, which is usually used + in sparse feature with large scale of instances. To compare the metric, i.e. + auc while doing slots shuffle on one or several slots with baseline to + evaluate the importance level of slots(features). + + Args: + slots(list[string]): the set of slots(string) to do slots shuffle. + + Examples: + import paddle.fluid as fluid + dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset") + dataset.set_merge_by_lineid() + #suppose there is a slot 0 + dataset.slots_shuffle(['0']) + """ + slots_set = set(slots) + self.boxps.slots_shuffle(slots_set) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/debugger.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..76b7c3d7dc1207f2a69cd6e490967fcad03bc02e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/debugger.py @@ -0,0 +1,283 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import sys +import six +import random +import os +import re +from .graphviz import GraphPreviewGenerator +from .proto import framework_pb2 +from google.protobuf import text_format +from . import unique_name +from .framework import Program, default_main_program, Variable +from . import core +from . import io +from .layer_helper import LayerHelper + +_vartype2str_ = [ + "UNK", + "LoDTensor", + "SelectedRows", + "FeedMinibatch", + "FetchList", + "StepScopes", + "LodRankTable", + "LoDTensorArray", + "PlaceList", +] +_dtype2str_ = [ + "bool", + "int16", + "int32", + "int64", + "float16", + "float32", + "float64", +] + + +def repr_data_type(type): + return _dtype2str_[type] + + +def repr_tensor(proto): + return "tensor(type={}, shape={})".format(_dtype2str_[int(proto.data_type)], + str(proto.dims)) + + +reprtpl = "{ttype} {name} ({reprs})" + + +def repr_lodtensor(proto): + if proto.type.type != framework_pb2.VarType.LOD_TENSOR: + return + + level = proto.type.lod_tensor.lod_level + reprs = repr_tensor(proto.type.lod_tensor.tensor) + return reprtpl.format(ttype="LoDTensor" if level > 0 else "Tensor", + name=proto.name, + reprs="level=%d, %s" % + (level, reprs) if level > 0 else reprs) + + +def repr_selected_rows(proto): + if proto.type.type != framework_pb2.VarType.SELECTED_ROWS: + return + + return reprtpl.format(ttype="SelectedRows", + name=proto.name, + reprs=repr_tensor(proto.type.selected_rows)) + + +def repr_tensor_array(proto): + if proto.type.type != framework_pb2.VarType.LOD_TENSOR_ARRAY: + return + + return reprtpl.format(ttype="TensorArray", + name=proto.name, + reprs="level=%d, %s" % + (proto.type.tensor_array.lod_level, + repr_tensor(proto.type.lod_tensor.tensor))) + + +type_handlers = [ + repr_lodtensor, + repr_selected_rows, + repr_tensor_array, +] + + +def repr_var(vardesc): + for handler in type_handlers: + res = handler(vardesc) + if res: + return res + + +def pprint_program_codes(program_desc): + reprs = [] + for block_idx in range(program_desc.desc.num_blocks()): + block_desc = program_desc.block(block_idx) + block_repr = pprint_block_codes(block_desc) + reprs.append(block_repr) + return '\n'.join(reprs) + + +def pprint_block_codes(block_desc, show_backward=False): + + def is_op_backward(op_desc): + if op_desc.type.endswith('_grad'): return True + + def is_var_backward(var): + if "@GRAD" in var.parameter: return True + for arg in var.arguments: + if "@GRAD" in arg: return True + + for var in op_desc.inputs: + if is_var_backward(var): return True + for var in op_desc.outputs: + if is_var_backward(var): return True + return False + + def is_var_backward(var_desc): + return "@GRAD" in var_desc.name + + if type(block_desc) is not framework_pb2.BlockDesc: + block_desc = framework_pb2.BlockDesc.FromString( + block_desc.desc.serialize_to_string()) + var_reprs = [] + op_reprs = [] + for var in block_desc.vars: + if not show_backward and is_var_backward(var): + continue + var_reprs.append(repr_var(var)) + + for op in block_desc.ops: + if not show_backward and is_op_backward(op): continue + op_reprs.append(repr_op(op)) + + tpl = "// block-{idx} parent-{pidx}\n// variables\n{vars}\n\n// operators\n{ops}\n" + return tpl.format( + idx=block_desc.idx, + pidx=block_desc.parent_idx, + vars='\n'.join(var_reprs), + ops='\n'.join(op_reprs), + ) + + +def repr_attr(desc): + tpl = "{key}={value}" + valgetter = [ + lambda attr: attr.i, + lambda attr: attr.f, + lambda attr: attr.s, + lambda attr: attr.ints, + lambda attr: attr.floats, + lambda attr: attr.strings, + lambda attr: attr.b, + lambda attr: attr.bools, + lambda attr: attr.block_idx, + lambda attr: attr.l, + ] + key = desc.name + value = valgetter[desc.type](desc) + if key == "dtype": + value = repr_data_type(value) + return tpl.format(key=key, value=str(value)), (key, value) + + +def _repr_op_fill_constant(optype, inputs, outputs, attrs): + if optype == "fill_constant": + return "{output} = {data} [shape={shape}]".format( + output=','.join(outputs), + data=attrs['value'], + shape=str(attrs['shape'])) + + +op_repr_handlers = [ + _repr_op_fill_constant, +] + + +def repr_op(opdesc): + optype = None + attrs = [] + attr_dict = {} + is_target = None + inputs = [] + outputs = [] + + tpl = "{outputs} = {optype}({inputs}{is_target}) [{attrs}]" + args2value = lambda args: args[0] if len(args) == 1 else str(list(args)) + for var in opdesc.inputs: + key = var.parameter + value = args2value(var.arguments) + inputs.append("%s=%s" % (key, value)) + for var in opdesc.outputs: + value = args2value(var.arguments) + outputs.append(value) + for attr in opdesc.attrs: + attr_repr, attr_pair = repr_attr(attr) + attrs.append(attr_repr) + attr_dict[attr_pair[0]] = attr_pair[1] + + is_target = opdesc.is_target + + for handler in op_repr_handlers: + res = handler(opdesc.type, inputs, outputs, attr_dict) + if res: return res + + return tpl.format(outputs=', '.join(outputs), + optype=opdesc.type, + inputs=', '.join(inputs), + attrs="{%s}" % ','.join(attrs), + is_target=", is_target" if is_target else "") + + +def draw_block_graphviz(block, highlights=None, path="./temp.dot"): + ''' + Generate a debug graph for block. + Args: + block(Block): a block. + ''' + graph = GraphPreviewGenerator("some graph") + # collect parameters and args + protostr = block.desc.serialize_to_string() + desc = framework_pb2.BlockDesc.FromString(six.binary_type(protostr)) + + def need_highlight(name): + if highlights is None: return False + for pattern in highlights: + assert type(pattern) is str + if re.match(pattern, name): + return True + return False + + # draw parameters and args + vars = {} + for var in desc.vars: + # TODO(gongwb): format the var.type + # create var + if var.persistable: + varn = graph.add_param(var.name, + str(var.type).replace("\n", "
", 1), + highlight=need_highlight(var.name)) + else: + varn = graph.add_arg(var.name, highlight=need_highlight(var.name)) + vars[var.name] = varn + + def add_op_link_var(op, var, op2var=False): + for arg in var.arguments: + if arg not in vars: + # add missing variables as argument + vars[arg] = graph.add_arg(arg, highlight=need_highlight(arg)) + varn = vars[arg] + highlight = need_highlight(op.description) or need_highlight( + varn.description) + if op2var: + graph.add_edge(op, varn, highlight=highlight) + else: + graph.add_edge(varn, op, highlight=highlight) + + for op in desc.ops: + opn = graph.add_op(op.type, highlight=need_highlight(op.type)) + for var in op.inputs: + add_op_link_var(opn, var, False) + for var in op.outputs: + add_op_link_var(opn, var, True) + + graph(path, show=False) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/default_scope_funcs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/default_scope_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b2c84dfe6f2650b4a2ee4465f723812e5d4a01 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/default_scope_funcs.py @@ -0,0 +1,103 @@ +# Copyright (c) 2018 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. +""" +Default scope function. + +`Paddle` manages Scope as programming language's scope. It just a +thread-local stack of Scope. Top of that stack is current scope, the bottom +of that stack is all scopes' parent. + +Invoking `var/find_var` can `new/find` variable in current scope. +Invoking `enter_local_scope/leave_local_scope` can create or destroy local +scope. + +A `scoped_function` will take a `function` as input. That function will be +invoked in a new local scope. +""" + +from __future__ import print_function + +import paddle.fluid.core +import threading + +__tl_scope__ = threading.local() + +__all__ = [ + 'get_cur_scope', + 'enter_local_scope', + 'leave_local_scope', + 'var', + 'find_var', + 'scoped_function', +] + + +def get_cur_scope(): + """ + Get current scope. + :rtype: paddle.fluid.core.Scope + """ + cur_scope_stack = getattr(__tl_scope__, 'cur_scope', None) + if cur_scope_stack is None: + __tl_scope__.cur_scope = list() + if len(__tl_scope__.cur_scope) == 0: + __tl_scope__.cur_scope.append(paddle.fluid.core.Scope()) + return __tl_scope__.cur_scope[-1] + + +def enter_local_scope(): + """ + Enter a new local scope + """ + cur_scope = get_cur_scope() + new_scope = cur_scope.new_scope() + __tl_scope__.cur_scope.append(new_scope) + + +def leave_local_scope(): + """ + Leave local scope + """ + __tl_scope__.cur_scope.pop() + get_cur_scope().drop_kids() + + +def var(name): + """ + create variable in current scope. + """ + return get_cur_scope().var(name) + + +def find_var(name): + """ + get variable in current scope. + """ + return get_cur_scope().find_var(name) + + +def scoped_function(func): + """ + invoke `func` in new scope. + + :param func: a callable function that will be run in new scope. + :type func: callable + """ + enter_local_scope() + try: + func() + except: + raise + finally: + leave_local_scope() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/device_worker.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/device_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c094a84f758b1c0f75687254730acc00b8b5b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/device_worker.py @@ -0,0 +1,628 @@ +# 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. +"""Defination of device workers.""" + +from __future__ import print_function + +__all__ = [ + 'DeviceWorker', 'Hogwild', 'DownpourSGD', 'Section', 'DownpourSGDOPT', + 'HeterSection' +] + + +class DeviceWorker(object): + """ + DeviceWorker is an abstract class, which generates worker desc. + This class is an inner class that we do computation logics within + the implementation. For example, execution of a program or a graph. + """ + + def __init__(self): + """Init.""" + self._program = None + self._infer = None + + def _set_infer(self, infer=False): + """ + set inference flag for current device worker + + Args: + infer(bool): whether to do inference + """ + self._infer = infer + + def _set_fleet_desc(self, fleet_desc): + """ + Set fleet desc. + + Args: + fleet_desc(PSParameter): pslib.PSParameter object + """ + self._fleet_desc = fleet_desc + + def _set_program(self, program): + """ + Set program. + + Args: + program(Program): a Program object + """ + self._program = program + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc. + + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + raise NotImplementedError( + "DeviceWorker does not implement gen_worker_desc, " + "please use Hogwild or DownpourSGD, etc.") + + +class Hogwild(DeviceWorker): + """ + Hogwild is a kind of SGD algorithm. + + """ + + def __init__(self): + """Init.""" + super(Hogwild, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is HogwildWorker. + + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + trainer_desc.device_worker_name = "HogwildWorker" + if self._infer: + # just ignore feed op for inference model + trainer_desc.hogwild_param.skip_ops.extend([ + "feed", "push_sparse", "push_sparse_v2", "push_dense", + "distributed_push_sparse", "send" + ]) + + dense_table_set = set() + program_id = str(id(self._program)) + print("device worker program id:", program_id) + if self._program == None: + print("program of current device worker is not configured") + exit(-1) + opt_info = self._program._fleet_opt + # when opt_info is None or empty dict, it should return + if not opt_info: + return + downpour = trainer_desc.downpour_param + hogwild = trainer_desc.hogwild_param + if opt_info["stat_var_names"]: + for i in opt_info["stat_var_names"]: + hogwild.stat_var_names.extend([i]) + downpour.stat_var_names.extend([i]) + + from paddle.fluid.incubate.fleet.parameter_server import version + + if version.is_transpiler( + ) and "fleet_desc" not in opt_info and "program_configs" not in opt_info: + return + + program_configs = opt_info["program_configs"] + print("device worker program_configs:", program_configs) + + for pid in program_configs: + print("device worker", pid, program_id) + if pid == program_id: + pc = downpour.program_config.add() + pc.program_id = program_id + print("device worker pull dense:", + program_configs[program_id]["pull_dense"]) + for i in program_configs[program_id]["push_sparse"]: + pc.push_sparse_table_id.extend([i]) + for i in program_configs[program_id]["push_dense"]: + pc.push_dense_table_id.extend([i]) + dense_table_set.add(i) + for i in program_configs[program_id]["pull_sparse"]: + pc.pull_sparse_table_id.extend([i]) + for i in program_configs[program_id]["pull_dense"]: + pc.pull_dense_table_id.extend([i]) + dense_table_set.add(i) + break + + trainer_desc.device_worker_name = "HogwildWorker" + pull_thread = trainer_desc.pull_dense_param + pull_thread.device_num = trainer_desc.thread_num + if opt_info.get("program_id_to_worker") is None and opt_info.get( + "dense_table_config") is None: + raise ValueError( + "opt_info must have program_id_to_worker or dense_table_config") + if opt_info.get("program_id_to_worker") is not None: + prog_id_to_worker = opt_info["program_id_to_worker"] + if prog_id_to_worker.get(program_id) is None: + raise ValueError("%s not found in program_id_to_worker" % + program_id) + worker = opt_info["program_id_to_worker"][program_id] + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.table_id = \ + i.table_id + sparse_len = len(worker.get_desc().sparse_table) + for i in range(sparse_len): + sparse_table = downpour.sparse_table.add() + sparse_table.table_id = worker.get_desc( + ).sparse_table[i].table_id + sparse_table.sparse_key_name.extend( + worker.get_desc().sparse_table[i].slot_key) + sparse_table.sparse_value_name.extend( + worker.get_desc().sparse_table[i].slot_value) + sparse_table.sparse_grad_name.extend( + worker.get_desc().sparse_table[i].slot_gradient) + sparse_table.fea_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim + # not use emb_dim + sparse_table.emb_dim = -1 + # not use hard code click + sparse_table.label_var_name = "" + + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = downpour.dense_table.add() + dense_table.table_id = i.table_id + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.dense_grad_name.extend( + i.dense_gradient_variable_name) + hogwild.skip_ops.extend(worker.get_desc().skip_op) + else: + dense_table_config = opt_info.get("dense_table_config") + print("device worker dense_table_config:", dense_table_config) + for table_id, varnames in dense_table_config.items(): + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(varnames) + dense_table.table_id = table_id + + if self._infer: + hogwild.skip_ops.extend( + ["push_sparse", "push_sparse_v2", "push_dense"]) + + +class DownpourLite(DeviceWorker): + """ + DownpourLite is a kind of SGD algorithm. + + """ + + def __init__(self): + """Init.""" + super(DownpourLite, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is DownpourLiteWorker. + + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + print("create DownpourLiteWorker") + trainer_desc.device_worker_name = "DownpourLiteWorker" + if self._infer: + # just ignore feed op for inference model + trainer_desc.downpour_param.skip_ops.extend([ + "feed", "push_sparse", "push_sparse_v2", "push_dense", + "distributed_push_sparse", "send" + ]) + + dense_table_set = set() + program_id = str(id(self._program)) + print("device worker program id:", program_id) + if self._program == None: + print("program of current device worker is not configured") + exit(-1) + opt_info = self._program._fleet_opt + # when opt_info is None or empty dict, it should return + if not opt_info: + return + downpour = trainer_desc.downpour_param + if opt_info["stat_var_names"]: + for i in opt_info["stat_var_names"]: + downpour.stat_var_names.extend([i]) + + from paddle.fluid.incubate.fleet.parameter_server import version + + if version.is_transpiler( + ) and "fleet_desc" not in opt_info and "program_configs" not in opt_info: + return + + program_configs = opt_info["program_configs"] + print("device worker program_configs:", program_configs) + + for pid in program_configs: + print("device worker", pid, program_id) + if pid == program_id: + pc = downpour.program_config.add() + pc.program_id = program_id + print("device worker pull dense:", + program_configs[program_id]["pull_dense"]) + for i in program_configs[program_id]["push_sparse"]: + pc.push_sparse_table_id.extend([i]) + for i in program_configs[program_id]["push_dense"]: + pc.push_dense_table_id.extend([i]) + dense_table_set.add(i) + for i in program_configs[program_id]["pull_sparse"]: + pc.pull_sparse_table_id.extend([i]) + for i in program_configs[program_id]["pull_dense"]: + pc.pull_dense_table_id.extend([i]) + dense_table_set.add(i) + break + + pull_thread = trainer_desc.pull_dense_param + pull_thread.device_num = trainer_desc.thread_num + if opt_info.get("program_id_to_worker") is None and opt_info.get( + "dense_table_config") is None: + raise ValueError( + "opt_info must have program_id_to_worker or dense_table_config") + if opt_info.get("program_id_to_worker") is not None: + prog_id_to_worker = opt_info["program_id_to_worker"] + if prog_id_to_worker.get(program_id) is None: + raise ValueError("%s not found in program_id_to_worker" % + program_id) + worker = opt_info["program_id_to_worker"][program_id] + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.table_id = \ + i.table_id + sparse_len = len(worker.get_desc().sparse_table) + for i in range(sparse_len): + sparse_table = downpour.sparse_table.add() + sparse_table.table_id = worker.get_desc( + ).sparse_table[i].table_id + sparse_table.sparse_key_name.extend( + worker.get_desc().sparse_table[i].slot_key) + sparse_table.sparse_value_name.extend( + worker.get_desc().sparse_table[i].slot_value) + sparse_table.sparse_grad_name.extend( + worker.get_desc().sparse_table[i].slot_gradient) + sparse_table.fea_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim + # not use emb_dim + sparse_table.emb_dim = -1 + # not use hard code click + sparse_table.label_var_name = "" + + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = downpour.dense_table.add() + dense_table.table_id = i.table_id + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.dense_grad_name.extend( + i.dense_gradient_variable_name) + downpour.skip_ops.extend(worker.get_desc().skip_op) + else: + dense_table_config = opt_info.get("dense_table_config") + print("device worker dense_table_config:", dense_table_config) + for table_id, varnames in dense_table_config.items(): + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(varnames) + dense_table.table_id = table_id + + if self._infer: + downpour.skip_ops.extend( + ["push_sparse", "push_sparse_v2", "push_dense"]) + + +class DownpourSGD(DeviceWorker): + """ + DownpourSGD is a kind of distributed SGD algorithm. + """ + + def __init__(self): + """ + Init. + initialize downpourSGD device worker + """ + super(DownpourSGD, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is DownpourWorker. + + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + dense_table_set = set() + program_id = str(id(self._program)) + if self._program == None: + print("program of current device worker is not configured") + exit(-1) + opt_info = self._program._fleet_opt + program_configs = opt_info["program_configs"] + downpour = trainer_desc.downpour_param + + for pid in program_configs: + if pid == program_id: + pc = downpour.program_config.add() + pc.program_id = program_id + for i in program_configs[program_id]["push_sparse"]: + pc.push_sparse_table_id.extend([i]) + for i in program_configs[program_id]["push_dense"]: + pc.push_dense_table_id.extend([i]) + dense_table_set.add(i) + for i in program_configs[program_id]["pull_sparse"]: + pc.pull_sparse_table_id.extend([i]) + for i in program_configs[program_id]["pull_dense"]: + pc.pull_dense_table_id.extend([i]) + dense_table_set.add(i) + # code for partial push dense table such as multitask + if "cond2denseid" in program_configs[program_id]: + cond2denseid = program_configs[program_id]["cond2denseid"] + for key, value in cond2denseid.items(): + mc_map = pc.partial_pushdense_condtable_map.add() + mc_map.key = key + mc_map.value = value + break + + trainer_desc.device_worker_name = opt_info.get("worker_class", + "DownpourWorker") + pull_thread = trainer_desc.pull_dense_param + pull_thread.device_num = trainer_desc.thread_num + if opt_info.get("program_id_to_worker") is None: + raise ValueError("opt_info must have program_id_to_worker") + prog_id_to_worker = opt_info["program_id_to_worker"] + if prog_id_to_worker.get(program_id) is None: + raise ValueError("%s not found in program_id_to_worker" % + program_id) + worker = opt_info["program_id_to_worker"][program_id] + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.table_id = \ + i.table_id + sparse_len = len(worker.get_desc().sparse_table) + for i in range(sparse_len): + sparse_table = downpour.sparse_table.add() + sparse_table.table_id = worker.get_desc().sparse_table[i].table_id + sparse_table.sparse_key_name.extend( + worker.get_desc().sparse_table[i].slot_key) + sparse_table.sparse_value_name.extend( + worker.get_desc().sparse_table[i].slot_value) + sparse_table.sparse_grad_name.extend( + worker.get_desc().sparse_table[i].slot_gradient) + if opt_info["use_cvm"] or "no_cvm" in opt_info and opt_info[ + "no_cvm"] == True: + sparse_table.emb_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim + sparse_table.fea_dim = sparse_table.emb_dim + else: + sparse_table.emb_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim - 2 + sparse_table.fea_dim = sparse_table.emb_dim + 2 + # TODO(guru4elephant): hard code here, need to improve + sparse_table.label_var_name = "click" + if opt_info["stat_var_names"]: + for i in opt_info["stat_var_names"]: + downpour.stat_var_names.extend([i]) + + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = downpour.dense_table.add() + dense_table.table_id = i.table_id + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.dense_grad_name.extend( + i.dense_gradient_variable_name) + downpour.skip_ops.extend(worker.get_desc().skip_op) + if self._infer: + downpour.push_dense = False + downpour.push_sparse = False + + +class DownpourSGDOPT(DeviceWorker): + """ + DownpourSGDOPT is a kind of distributed SGD algorithm. + """ + + def __init__(self): + """ + Init. + initialize downpourSGDOPT device worker + """ + super(DownpourSGDOPT, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is DownpourWorker. + + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + dense_table_set = set() + program_id = str(id(self._program)) + if self._program == None: + print("program of current device worker is not configured") + exit(-1) + opt_info = self._program._fleet_opt + program_configs = opt_info["program_configs"] + downpour = trainer_desc.downpour_param + + for pid in program_configs: + if pid == program_id: + pc = downpour.program_config.add() + pc.program_id = program_id + for i in program_configs[program_id]["push_sparse"]: + pc.push_sparse_table_id.extend([i]) + for i in program_configs[program_id]["push_dense"]: + pc.push_dense_table_id.extend([i]) + dense_table_set.add(i) + for i in program_configs[program_id]["pull_sparse"]: + pc.pull_sparse_table_id.extend([i]) + for i in program_configs[program_id]["pull_dense"]: + pc.pull_dense_table_id.extend([i]) + dense_table_set.add(i) + break + + trainer_desc.device_worker_name = "DownpourWorkerOpt" + pull_thread = trainer_desc.pull_dense_param + pull_thread.device_num = trainer_desc.thread_num + if opt_info.get("program_id_to_worker") is None: + raise ValueError("opt_info must have program_id_to_worker") + prog_id_to_worker = opt_info["program_id_to_worker"] + if prog_id_to_worker.get(program_id) is None: + raise ValueError("%s not found in program_id_to_worker" % + program_id) + worker = opt_info["program_id_to_worker"][program_id] + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = pull_thread.dense_table.add() + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.table_id = \ + i.table_id + sparse_len = len(worker.get_desc().sparse_table) + for i in range(sparse_len): + sparse_table = downpour.sparse_table.add() + sparse_table.table_id = worker.get_desc().sparse_table[i].table_id + sparse_table.sparse_key_name.extend( + worker.get_desc().sparse_table[i].slot_key) + sparse_table.sparse_value_name.extend( + worker.get_desc().sparse_table[i].slot_value) + sparse_table.sparse_grad_name.extend( + worker.get_desc().sparse_table[i].slot_gradient) + if opt_info["use_cvm"] or "no_cvm" in opt_info and opt_info[ + "no_cvm"] == True: + sparse_table.emb_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim + sparse_table.fea_dim = sparse_table.emb_dim + else: + sparse_table.emb_dim = \ + self._fleet_desc.server_param.downpour_server_param.downpour_table_param[ + i].accessor.fea_dim - 2 + sparse_table.fea_dim = sparse_table.emb_dim + 2 + # TODO(guru4elephant): hard code here, need to improve + sparse_table.label_var_name = "click" + if "local_tables" in opt_info and sparse_table.table_id in opt_info[ + "local_tables"]: + sparse_table.is_local = True + if "async_tables" in opt_info and sparse_table.table_id in opt_info[ + "async_tables"]: + sparse_table.is_async = True + if opt_info["stat_var_names"]: + for i in opt_info["stat_var_names"]: + downpour.stat_var_names.extend([i]) + + for i in worker.get_desc().dense_table: + if i.table_id in dense_table_set: + dense_table = downpour.dense_table.add() + dense_table.table_id = i.table_id + dense_table.dense_value_name.extend(i.dense_variable_name) + dense_table.dense_grad_name.extend( + i.dense_gradient_variable_name) + downpour.skip_ops.extend(worker.get_desc().skip_op) + if self._infer: + downpour.push_dense = False + downpour.push_sparse = False + + +class Section(DeviceWorker): + """SectionWorker.""" + + def __init__(self): + """Init.""" + super(Section, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is SectionWorker. + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + from google.protobuf import text_format + from . import core + trainer_desc.device_worker_name = "SectionWorker" + pipeline_opt = self._program._pipeline_opt + section_param = trainer_desc.section_param + section_param.num_microbatches = pipeline_opt["num_microbatches"] + section_param.start_cpu_core_id = pipeline_opt["start_cpu_core_id"] + section_param.pipeline_stage = pipeline_opt["pipeline_stage"] + section_param.num_pipeline_stages = pipeline_opt["num_pipeline_stages"] + schedule_mode_str = pipeline_opt["schedule_mode"] + # F-then-B scheduler which runs Forward phase for all microbatches, + # then runs Backward phase for all microbatches. + # 1F1B scheduler, which runs forward phase and backward phase altertively + # after startup phase. + assert schedule_mode_str in [ + "F-then-B", "1F1B" + ], ("The schedule mode " + "for pipeline must be one of F-then-B or 1F1B") + schedule_mode = 0 if schedule_mode_str == "F-then-B" else 1 + section_param.schedule_mode = schedule_mode + cfg = section_param.section_config + program = pipeline_opt["section_program"] + cfg.program_desc.ParseFromString( + program._get_desc().serialize_to_string()) + # TODO: why does not work + # cfg.program_desc.CopyFrom(program.program._get_desc()) + place = pipeline_opt["place"] + place_id = pipeline_opt["place_id"] + if core.is_compiled_with_cuda(): + assert isinstance(place, core.CUDAPlace) + elif core.is_compiled_with_npu(): + assert isinstance(place, core.NPUPlace) + cfg.place = cfg.CUDAPlace + cfg.place_id = place_id + + +class HeterSection(DeviceWorker): + """HeterSectionWorker.""" + + def __init__(self): + """Init.""" + super(HeterSection, self).__init__() + + def _gen_worker_desc(self, trainer_desc): + """ + Generator worker desc, which device worker is HeterSectionWorker. + Args: + trainer_desc(TrainerDesc): a TrainerDesc object + """ + from google.protobuf import text_format + from . import core + trainer_desc.device_worker_name = "HeterSectionWorker" + heter_pipeline_opt = self._program._heter_pipeline_opt + heter_section_param = trainer_desc.heter_section_param + heter_section_param.num_microbatches = heter_pipeline_opt[ + "num_microbatches"] + heter_section_param.pipeline_stage = heter_pipeline_opt[ + "pipeline_stage"] + heter_section_param.num_pipeline_stages = heter_pipeline_opt[ + "num_pipeline_stages"] + cfg = heter_section_param.section_config + program = heter_pipeline_opt["section_program"] + cfg.program_desc.ParseFromString( + program._get_desc().serialize_to_string()) + + +class DeviceWorkerFactory(object): + + def _create_device_worker(self, worker_type): + classname = worker_type.capitalize() + return globals()[classname]() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distribute_lookup_table.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distribute_lookup_table.py new file mode 100644 index 0000000000000000000000000000000000000000..74824f6832442d5090e0cea2962ca2f68b7a0181 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distribute_lookup_table.py @@ -0,0 +1,79 @@ +# Copyright (c) 2018 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. + +LOOKUP_TABLE_TYPE = "lookup_table" + + +def find_distributed_lookup_table_inputs(program, table_name): + """ + Find input variable of distribute lookup table in program. + We only support one distribute table now. + Args: + program(Program): given program, locate distributed lookup table + table_name(str): given table name that is found beforehand + Returns: + inputs + """ + local_vars = program.current_block().vars + inputs = [] + for op in program.global_block().ops: + if op.type == LOOKUP_TABLE_TYPE: + if table_name == op.input("W")[0]: + inputs.extend([local_vars[name] for name in op.input("Ids")]) + return inputs + + +def find_distributed_lookup_table_outputs(program, table_name): + """ + Find output variable of distribute lookup table in program. + We only support one distribute table now. + Args: + program(Program): given program, locate distributed lookup table + table_name(str): given table name that is found beforehand + Returns: + outputs + """ + local_vars = program.current_block().vars + outputs = [] + for op in program.global_block().ops: + if op.type == LOOKUP_TABLE_TYPE: + if table_name == op.input("W")[0]: + outputs.extend([local_vars[name] for name in op.output("Out")]) + return outputs + + +def find_distributed_lookup_table(program): + """ + Find distribute lookup table in program. + We only support one distribute table now. + Args: + program(Program): given program, locate distributed lookup table + Returns: + table_name or None + """ + table_name = None + + for op in program.global_block().ops: + if op.type == LOOKUP_TABLE_TYPE: + if op.attr('is_distributed') is True: + if table_name is None: + table_name = op.input("W")[0] + if table_name != op.input("W")[0]: + raise RuntimeError("all distributed lookup_table_ops" + " should have only one table") + else: + if table_name is not None: + assert op.input("W")[0] != table_name + + return table_name diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd609c504078b907221a689fbb4e910ec8d54270 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) 2018 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 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/downpour.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/downpour.py new file mode 100644 index 0000000000000000000000000000000000000000..4d6cc88ea7e6686e2110ab79a5da846ceacd46c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/downpour.py @@ -0,0 +1,167 @@ +# Copyright (c) 2018 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 + +from .node import DownpourServer +from .node import DownpourWorker +from ..backward import append_backward +import ps_pb2 as pslib +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table_inputs +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table_outputs +from google.protobuf import text_format + + +class DownpourSGD(object): + r""" + Distributed optimizer of downpour stochastic gradient descent + Standard implementation of Google's Downpour SGD + in Large Scale Distributed Deep Networks + + Args: + learning_rate (float): the learning rate used to update parameters. \ + Can be a float value + Examples: + .. code-block:: python + + opt = fluid.DistributedOptimizer(sgd_opt) + opt.minimize() + + downpour_sgd = fluid.distributed.DownpourSGD(learning_rate=0.2) + downpour_sgd.minimize(cost) + """ + + def __init__(self, learning_rate=0.001, window=1): + # todo(guru4elephant): add more optimizers here as argument + # todo(guru4elephant): make learning_rate as a variable + self.learning_rate_ = learning_rate + self.window_ = window + self.type = "downpour" + self.data_norm_name = [ + ".batch_size", ".batch_square_sum", ".batch_sum", + ".batch_size@GRAD", ".batch_square_sum@GRAD", ".batch_sum@GRAD" + ] + + def minimize(self, + losses, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + DownpounSGD is a distributed optimizer so + that user can call minimize to generate backward + operators and optimization operators within minimize function + Args: + loss(Variable): loss variable defined by user + startup_program(Program): startup program that defined by user + parameter_list(str list): parameter names defined by users + no_grad_set(set): a set of variables that is defined by users + so that these variables do not need gradient computation + Returns: + [ps_param, worker_skipped_ops] + ps_param: parameter server protobuf desc + worker_skipped_ops: operator names that need + to be skipped during execution + """ + if not isinstance(losses, list): + raise ValueError('losses is a list, just lick [model.cost]') + table_name = find_distributed_lookup_table(losses[0].block.program) + prefetch_slots = find_distributed_lookup_table_inputs( + losses[0].block.program, table_name) + prefetch_slots_emb = find_distributed_lookup_table_outputs( + losses[0].block.program, table_name) + + ps_param = pslib.PSParameter() + server = DownpourServer() + worker = DownpourWorker(self.window_) + sparse_table_index = 0 + server.add_sparse_table(sparse_table_index, self.learning_rate_, + prefetch_slots, prefetch_slots_emb) + worker.add_sparse_table(sparse_table_index, self.learning_rate_, + prefetch_slots, prefetch_slots_emb) + dense_table_index = 1 + program_configs = [] + param_grads_list = [] + for loss_index in range(len(losses)): + program_config = ps_param.trainer_param.program_config.add() + program_config.program_id = str(id( + losses[loss_index].block.program)) + program_config.pull_sparse_table_id.extend([sparse_table_index]) + program_config.push_sparse_table_id.extend([sparse_table_index]) + params_grads = sorted(append_backward(losses[loss_index], + parameter_list, no_grad_set), + key=lambda x: x[0].name) + param_grads_list.append(params_grads) + params = [] + grads = [] + data_norm_params = [] + data_norm_grads = [] + for i in params_grads: + is_data_norm_data = False + for data_norm_name in self.data_norm_name: + if i[0].name.endswith(data_norm_name): + is_data_norm_data = True + data_norm_params.append(i[0]) + if not is_data_norm_data: + params.append(i[0]) + for i in params_grads: + is_data_norm_data = False + for data_norm_grad in self.data_norm_name: + if i[0].name.endswith(data_norm_grad): + is_data_norm_data = True + data_norm_grads.append(i[1]) + if not is_data_norm_data: + grads.append(i[1]) + server.add_dense_table(dense_table_index, self.learning_rate_, + params, grads) + worker.add_dense_table(dense_table_index, self.learning_rate_, + params, grads) + program_config.pull_dense_table_id.extend([dense_table_index]) + program_config.push_dense_table_id.extend([dense_table_index]) + if len(data_norm_params) != 0 and len(data_norm_grads) != 0: + dense_table_index += 1 + server.add_data_norm_table(dense_table_index, + self.learning_rate_, + data_norm_params, data_norm_grads) + worker.add_dense_table(dense_table_index, self.learning_rate_, + data_norm_params, data_norm_grads) + program_config.pull_dense_table_id.extend([dense_table_index]) + program_config.push_dense_table_id.extend([dense_table_index]) + dense_table_index += 1 + program_configs.append(program_config) + ps_param.server_param.CopyFrom(server.get_desc()) + ps_param.trainer_param.CopyFrom(worker.get_desc()) + for program_config in program_configs: + ps_param.trainer_param.program_config.extend([program_config]) + # Todo(guru4elephant): figure out how to support more sparse parameters + # currently only support lookup_table + worker_skipped_ops = ["lookup_table", "lookup_table_grad"] + ps_param.trainer_param.skip_op.extend(worker_skipped_ops) + + # all fleet operations should be defined in operators in the future + # we want to return an object here containing: + # 1) worker execution strategy + # 2) pserver execution strategy + # 3) fleet configurations + # 4) skipped operators in runtime + # 5) distributed optimization + opt_info = {} + opt_info["trainer"] = "DistMultiTrainer" + opt_info["device_worker"] = "DownpourSGD" + opt_info["optimizer"] = "DownpourSGD" + opt_info["fleet_desc"] = ps_param + opt_info["worker_skipped_ops"] = worker_skipped_ops + + for loss in losses: + loss.block.program._fleet_opt = opt_info + + return None, param_grads_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/fleet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/fleet.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2bcdc213b4b6d94dfa7078660bef4a1c3c647e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/fleet.py @@ -0,0 +1,77 @@ +# 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 +import sys +from .. import core +from . import ps_instance +from google.protobuf import text_format + +__all__ = ['Fleet'] + + +class Fleet(object): + """ + + """ + + def __init__(self): + self.instance_ = ps_instance.PaddlePSInstance() + self.fleet_ = core.FleetWrapper() + + def stop(self): + self.instance_.barrier_worker() + if self.instance.is_first_worker(): + self.fleet_.stop_server() + self.instance_.barrier_worker() + self.instance_.barrier_all() + self.instance.finalize() + + def init_pserver(self, opt_info): + if "fleet_desc" in opt_info: + self.dist_desc_str_ = text_format.MessageToString( + opt_info["fleet_desc"]) + self.dist_desc_ = opt_info["fleet_desc"] + else: + print( + "You should run distributed optimization to get opt_info first") + sys.exit(-1) + self.fleet_.init_server(self.dist_desc_str_) + ip = self.fleet_.start_server() + self.instance_.set_ip(ip) + self.instance.barrier_all() + ips = self.instance.gather_ips() + self.fleet.gather_servers(ips, self.instance_.get_node_cnt()) + self.instance_.barrier_all() + + def init_worker(self, opt_info): + if "fleet_desc" in opt_info: + self.dist_desc_str_ = text_format.MessageToString( + opt_info["fleet_desc"]) + self.dist_desc_ = opt_info["fleet_desc"] + else: + print( + "You should run distributed optimization to get opt_info first") + sys.exit(-1) + self.instance_.barrier_all() + ips = self.instance.gather_ips() + self.fleet_.init_worker(self.dist_desc_str_, ips, + self.instance_.get_node_cnt(), + self.instance._rankid) + self.instance.barrier_worker() + + def init_pserver_model(self): + if self.instance_.is_first_worker(): + self.fleet_.init_model() + self.instance_.barrier_worker() + + def save_pserver_model(self, save_path): + self.fleet_.save_model(save_path) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..20f45b4e7961544d60053306b40325386d36bda3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/helper.py @@ -0,0 +1,85 @@ +# Copyright (c) 2018 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. + + +class FileSystem(object): + """ + A file system that support hadoop client desc. + + Args: + fs_type (string): fs_type, for example is "afs" + user (string): hadoop param + passwd (string): hadoop param + hadoop bin (string): hadoop param + Examples: + fs = FileSystm() + """ + + def __init__(self, + fs_type="afs", + uri="afs://xx", + user=None, + passwd=None, + hadoop_bin=""): + assert user != None + assert passwd != None + assert hadoop_bin != None + import ps_pb2 as pslib + self.fs_client = pslib.FsClientParameter() + self.fs_client.uri = uri + self.fs_client.user = user + self.fs_client.passwd = passwd + #self.fs_client.buffer_size = 0 + self.fs_client.hadoop_bin = hadoop_bin + #self.fs_client.afs_conf = afs_conf if not afs_conf else "" + + def get_desc(self): + """ + get hadoop desc. + """ + return self.fs_client + + +class MPIHelper(object): + """ + MPIHelper is a wrapper of mpi4py, support get_rank get_size etc. + Args: + No params + Examples: + mh = MPIHelper() + mh.get_ip() + """ + + def __init__(self): + from mpi4py import MPI + self.comm = MPI.COMM_WORLD + self.MPI = MPI + + def get_rank(self): + return self.comm.Get_rank() + + def get_size(self): + return self.comm.Get_size() + + def get_ip(self): + import socket + local_ip = socket.gethostbyname(socket.gethostname()) + return local_ip + + def get_hostname(self): + import socket + return socket.gethostname() + + def finalize(self): + self.MPI.Finalize() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/node.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/node.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc1c51e06a0f971e8b9082936f3d8bfb9f007a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/node.py @@ -0,0 +1,180 @@ +# Copyright (c) 2018 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 + +import ps_pb2 as pslib +# NOTE: reduce removed in fuctools in python3 +from functools import reduce + + +class Server(object): + """ + A Server basic class. + """ + + def __init__(self): + pass + + +class Worker(object): + """ + A Worker basic class. + """ + + def __init__(self): + pass + + +class DownpourServer(Server): + """ + DownpourServer class is used to generate server program_desc + Args: + server: it is pslib.ServerParameter() + Examples: + server = DownpourServer() + """ + + def __init__(self): + self.server_ = pslib.ServerParameter() + self.server_.downpour_server_param.service_param.start_server_port = 0 + self.server_.downpour_server_param.service_param.server_class = "DownpourBrpcPsServer" + self.server_.downpour_server_param.service_param.client_class = "DownpourBrpcPsClient" + self.server_.downpour_server_param.service_param.service_class = "DownpourPsService" + self.server_.downpour_server_param.service_param.server_thread_num = 12 + + def add_sparse_table(self, table_id, learning_rate, slot_key_vars, + slot_value_var): + r""" + Args: + table_id(int): id of sparse params table + learning_rate(float): the learning rate used to update parameters. \ + Can be a float value + slot_key_vars(string): slot key id + slot_value_var(string): slot key value after embedding + Returns: + return None + """ + table = self.server_.downpour_server_param.downpour_table_param.add() + table.table_id = table_id + table.table_class = "DownpourSparseTable" + table.type = pslib.PS_SPARSE_TABLE + table.accessor.accessor_class = "DownpourFeatureValueAccessor" + table.accessor.sparse_sgd_param.learning_rate = learning_rate + table.accessor.sparse_sgd_param.initial_g2sum = 3 + table.accessor.sparse_sgd_param.initial_range = 1e-4 + table.accessor.sparse_sgd_param.weight_bounds.extend([-10, 10]) + + table.accessor.embedx_dim = 8 + table.accessor.embedx_threshold = 5 + table.accessor.fea_dim = 11 + table.accessor.downpour_accessor_param.nonclk_coeff = 0.1 + table.accessor.downpour_accessor_param.click_coeff = 2 + table.accessor.downpour_accessor_param.base_threshold = 0.2 + table.accessor.downpour_accessor_param.delta_threshold = 0.15 + table.accessor.downpour_accessor_param.delta_keep_days = 31 + table.accessor.downpour_accessor_param.show_click_decay_rate = 0.999 + table.accessor.downpour_accessor_param.delete_threshold = 0.8 + + def add_dense_table(self, table_id, learning_rate, param_var, grad_var): + r""" + Args: + table_id(int): id of sparse params table + learning_rate(float): the learning rate used to update parameters. \ + Can be a float value + param_var(list): all dense param. it is a list. + grad_var(list): all dense grad parm it is a list. + Returns: + return None + """ + table = self.server_.downpour_server_param.downpour_table_param.add() + table.table_id = table_id + table.table_class = "DownpourDenseTable" + table.type = pslib.PS_DENSE_TABLE + table.accessor.accessor_class = "DownpourDenseValueAccessor" + table.accessor.dense_sgd_param.name = "adam" + table.accessor.dense_sgd_param.adam.learning_rate = learning_rate + table.accessor.dense_sgd_param.adam.avg_decay_rate = 0.999993 + table.accessor.dense_sgd_param.adam.ada_decay_rate = 0.9999 + table.accessor.dense_sgd_param.adam.ada_epsilon = 1e-8 + table.accessor.dense_sgd_param.adam.mom_decay_rate = 0.99 + table.accessor.dense_sgd_param.naive.learning_rate = 0.0002 + fea_dim = 0 + for param in filter(lambda x: x.name.find("embedding") == -1, + param_var): + fea_dim += reduce(lambda x, y: x * y, param.shape, 1) + table.accessor.fea_dim = fea_dim + + def get_desc(self): + """ + Return downpour server program_desc + """ + return self.server_ + + +class DownpourWorker(Worker): + """ + DownpourWorker class is used to generate worker program_desc + Args: + window (int): push params frequency + worker: it is pslib.DownpourTrainerParameter + Examples: + worker = DownpourWorker(1) + """ + + def __init__(self, window): + self.window = window + self.worker_ = pslib.DownpourTrainerParameter() + + def add_sparse_table(self, table_id, learning_rate, slot_key_vars, + slot_value_vars): + r""" + Args: + table_id(int): id of sparse params table + learning_rate(float): the learning rate used to update parameters. \ + Can be a float value + slot_key_vars(string): slot key id + slot_value_var(string): slot key value after embedding + Returns: + return None + """ + table = self.worker_.sparse_table.add() + table.table_id = table_id + table.slot_key.extend([var.name for var in slot_key_vars]) + table.slot_value.extend([var.name for var in slot_value_vars]) + table.slot_gradient.extend( + [var.name + "@GRAD" for var in slot_value_vars]) + + def add_dense_table(self, table_id, learning_rate, param_vars, grad_vars): + r""" + Args: + table_id(int): id of sparse params table + learning_rate(float): the learning rate used to update parameters. \ + Can be a float value + param_var(list): all dense param. it is a list. + grad_var(list): all dense grad parm it is a list. + Returns: + return None + """ + table = self.worker_.dense_table.add() + table.table_id = table_id + table.dense_variable_name.extend( + filter(lambda x: x.find("embedding") == -1, + [p.name for p in param_vars])) + table.dense_gradient_variable_name.extend( + filter(lambda x: x.find("embedding") == -1, + [g.name for g in grad_vars])) + + def get_desc(self): + """ + Return downpour worker program_desc + """ + return self.worker_ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_instance.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..9254a4a136f7753122adf96f00bfd7eff6dcf942 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_instance.py @@ -0,0 +1,160 @@ +# Copyright (c) 2018 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 + +from .helper import MPIHelper + + +class PaddlePSInstance(object): + """ + PaddlePSInstance class is used to generate A instance of server or worker + Args: + server_worker_mode: is a value 0 or 1, default is 1 + proc_per_node: process per node, default is 2 + Examples: + instance = PaddlePSInstance(1, 2) + """ + + def __init__(self, server_worker_mode=1, proc_per_node=2): + self.dh = MPIHelper() + self._rankid = self.dh.get_rank() + self._server_worker_mode = server_worker_mode + self._proc_per_node = proc_per_node + self._nodes = self.dh.get_size() + + self._ip = 0 + self._worker_num = self._nodes * self._proc_per_node / 2 + self._server_num = self._nodes * self._proc_per_node / 2 + self._total_server_worker = self._worker_num + self._server_num + self._node_type = None #IDLE=-1, WORKER=1, SERVER=0 + self._set_nodetype() + self._comm = None + self._split_comm() + + def _set_nodetype(self): + if self._server_worker_mode == 0: + if self._rankid < self._server_num: + self._node_type = 1 + elif self._rankid < self._total_server_worker: + self._node_type = 0 + else: + self._node_type = -1 + elif self._server_worker_mode == 1: + if self._rankid < self._total_server_worker: + if 0 == self._rankid % self._proc_per_node % 2: + self._node_type = 0 + else: + self._node_type = 1 + else: + self._node_type = -1 + else: + self._node_type = -1 + + def _split_comm(self): + if self.is_server(): + self._comm = self.dh.comm.Split(self._node_type) + elif self.is_worker(): + self._comm = self.dh.comm.Split(self._node_type) + pass + + def get_worker_id(self): + """ + Return worker index + """ + if self._server_worker_mode == 0: + return self._rankid == self.server_num + else: + return self._rankid / self._proc_per_node + + def get_server_id(self): + """ + Return server index + """ + if self._server_worker_mode == 0: + return self.rank_id + else: + return self.rank_id / self._proc_per_node + + def is_worker(self): + """ + Return instance is worker or not + """ + return self._node_type == 1 + + def is_server(self): + """ + Return instance is server or not + """ + return self._node_type == 0 + + def is_first_worker(self): + """ + Return instance is first worker or not + """ + return self.is_worker() and 0 == self.get_worker_id() + + def set_ip(self, ip): + """ + set server ip + """ + self._ip = ip + + def gather_ips(self): + """ + Return all servers and workers ip through mpi allgather + """ + self._ips = self.dh.comm.allgather(self._ip) + return self._ips + + def get_node_cnt(self): + """ + Return node cnt + """ + return self._nodes + + def get_worker_num(self): + """ + Return worker num + """ + return self._worker_num + + def get_server_num(self): + """ + Return server num + """ + return self._server_num + + def barrier_all(self): + """ + barrier workers and servers + """ + self.dh.comm.barrier() + + def barrier_worker(self): + """ + barrier workers + """ + if self.is_worker(): + self._comm.barrier() + pass + + def finalize(self): + """ + MPI finalize + """ + self.dh.finalize() + pass + + +if __name__ == "__main__": + instance = PaddlePSInstance(1, 2) + instance.barrier_all() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..f1262ebae12ff4f447857554e183d4d5ba02a001 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/distributed/ps_pb2.py @@ -0,0 +1,2427 @@ +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ps.proto + +import sys + +_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor.FileDescriptor( + name='ps.proto', + package='paddle', + syntax='proto2', + serialized_pb=_b( + '\n\x08ps.proto\x12\x06paddle\"\x9e\x02\n\x0bPSParameter\x12\x14\n\x0cworker_class\x18\x01 \x01(\t\x12\x14\n\x0cserver_class\x18\x02 \x01(\t\x12\x16\n\x0einstance_class\x18\x03 \x01(\t\x12-\n\x0cworker_param\x18\x65 \x01(\x0b\x32\x17.paddle.WorkerParameter\x12-\n\x0cserver_param\x18\x66 \x01(\x0b\x32\x17.paddle.ServerParameter\x12\x38\n\rtrainer_param\x18\xad\x02 \x01(\x0b\x32 .paddle.DownpourTrainerParameter\x12\x33\n\x0f\x66s_client_param\x18\xf5\x03 \x01(\x0b\x32\x19.paddle.FsClientParameter\"Q\n\x0fWorkerParameter\x12>\n\x15\x64ownpour_worker_param\x18\x01 \x01(\x0b\x32\x1f.paddle.DownpourWorkerParameter\"Q\n\x0fServerParameter\x12>\n\x15\x64ownpour_server_param\x18\x01 \x01(\x0b\x32\x1f.paddle.DownpourServerParameter\"O\n\x17\x44ownpourWorkerParameter\x12\x34\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\x16.paddle.TableParameter\"\xfd\x01\n\x18\x44ownpourTrainerParameter\x12\x30\n\x0b\x64\x65nse_table\x18\x01 \x03(\x0b\x32\x1b.paddle.DenseTableParameter\x12\x32\n\x0csparse_table\x18\x02 \x03(\x0b\x32\x1c.paddle.SparseTableParameter\x12\x1d\n\x15push_sparse_per_batch\x18\x03 \x01(\x05\x12\x1c\n\x14push_dense_per_batch\x18\x04 \x01(\x05\x12\x0f\n\x07skip_op\x18\x05 \x03(\t\x12-\n\x0eprogram_config\x18\x06 \x03(\x0b\x32\x15.paddle.ProgramConfig\"\x99\x01\n\rProgramConfig\x12\x12\n\nprogram_id\x18\x01 \x02(\t\x12\x1c\n\x14push_sparse_table_id\x18\x02 \x03(\x05\x12\x1b\n\x13push_dense_table_id\x18\x03 \x03(\x05\x12\x1c\n\x14pull_sparse_table_id\x18\x04 \x03(\x05\x12\x1b\n\x13pull_dense_table_id\x18\x05 \x03(\x05\"{\n\x13\x44\x65nseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x1b\n\x13\x64\x65nse_variable_name\x18\x02 \x03(\t\x12$\n\x1c\x64\x65nse_gradient_variable_name\x18\x03 \x03(\t\x12\x0f\n\x07\x66\x65\x61_dim\x18\x04 \x01(\x05\"z\n\x14SparseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x13\n\x0b\x66\x65\x61ture_dim\x18\x02 \x01(\x05\x12\x10\n\x08slot_key\x18\x03 \x03(\t\x12\x12\n\nslot_value\x18\x04 \x03(\t\x12\x15\n\rslot_gradient\x18\x05 \x03(\t\"\x86\x01\n\x17\x44ownpourServerParameter\x12\x34\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\x16.paddle.TableParameter\x12\x35\n\rservice_param\x18\x02 \x01(\x0b\x32\x1e.paddle.ServerServiceParameter\"\xd7\x01\n\x16ServerServiceParameter\x12*\n\x0cserver_class\x18\x01 \x01(\t:\x14\x44ownpourBrpcPsServer\x12*\n\x0c\x63lient_class\x18\x02 \x01(\t:\x14\x44ownpourBrpcPsClient\x12(\n\rservice_class\x18\x03 \x01(\t:\x11\x44ownpourPsService\x12\x1c\n\x11start_server_port\x18\x04 \x01(\r:\x01\x30\x12\x1d\n\x11server_thread_num\x18\x05 \x01(\r:\x02\x31\x32\"\xbf\x01\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x13\n\x0btable_class\x18\x02 \x01(\t\x12\x12\n\nshared_num\x18\x03 \x01(\x04\x12\x30\n\x08\x61\x63\x63\x65ssor\x18\x04 \x01(\x0b\x32\x1e.paddle.TableAccessorParameter\x12\x1f\n\x04type\x18\x05 \x01(\x0e\x32\x11.paddle.TableType\x12\x1f\n\x10\x63ompress_in_save\x18\x06 \x01(\x08:\x05\x66\x61lse\"\xf1\x02\n\x16TableAccessorParameter\x12\x16\n\x0e\x61\x63\x63\x65ssor_class\x18\x01 \x01(\t\x12\x38\n\x10sparse_sgd_param\x18\x02 \x01(\x0b\x32\x1e.paddle.SparseSGDRuleParameter\x12\x36\n\x0f\x64\x65nse_sgd_param\x18\x03 \x01(\x0b\x32\x1d.paddle.DenseSGDRuleParameter\x12\x0f\n\x07\x66\x65\x61_dim\x18\x04 \x01(\r\x12\x12\n\nembedx_dim\x18\x05 \x01(\r\x12\x18\n\x10\x65mbedx_threshold\x18\x06 \x01(\r\x12G\n\x17\x64ownpour_accessor_param\x18\x07 \x01(\x0b\x32&.paddle.DownpourTableAccessorParameter\x12\x45\n\x19table_accessor_save_param\x18\x08 \x03(\x0b\x32\".paddle.TableAccessorSaveParameter\"\xce\x01\n\x1e\x44ownpourTableAccessorParameter\x12\x14\n\x0cnonclk_coeff\x18\x01 \x01(\x02\x12\x13\n\x0b\x63lick_coeff\x18\x02 \x01(\x02\x12\x16\n\x0e\x62\x61se_threshold\x18\x03 \x01(\x02\x12\x17\n\x0f\x64\x65lta_threshold\x18\x04 \x01(\x02\x12\x17\n\x0f\x64\x65lta_keep_days\x18\x05 \x01(\x02\x12\x1d\n\x15show_click_decay_rate\x18\x06 \x01(\x02\x12\x18\n\x10\x64\x65lete_threshold\x18\x07 \x01(\x02\"S\n\x1aTableAccessorSaveParameter\x12\r\n\x05param\x18\x01 \x01(\r\x12\x11\n\tconverter\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65\x63onverter\x18\x03 \x01(\t\"e\n\x10PsRequestMessage\x12\x0e\n\x06\x63md_id\x18\x01 \x02(\r\x12\x10\n\x08table_id\x18\x02 \x01(\r\x12\x0e\n\x06params\x18\x03 \x03(\x0c\x12\x11\n\tclient_id\x18\x04 \x01(\x05\x12\x0c\n\x04\x64\x61ta\x18\x05 \x01(\x0c\"w\n\x16SparseSGDRuleParameter\x12\x15\n\rlearning_rate\x18\x01 \x01(\x01\x12\x15\n\rinitial_g2sum\x18\x02 \x01(\x01\x12\x18\n\rinitial_range\x18\x03 \x01(\x01:\x01\x30\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xe1\x01\n\x15\x44\x65nseSGDRuleParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\x04\x61\x64\x61m\x18\x02 \x01(\x0b\x32\x18.paddle.AdamSGDParameter\x12(\n\x05naive\x18\x03 \x01(\x0b\x32\x19.paddle.NaiveSGDParameter\x12,\n\x07summary\x18\x04 \x01(\x0b\x32\x1b.paddle.SummarySGDParameter\x12:\n\x0emoving_average\x18\x05 \x01(\x0b\x32\".paddle.MovingAverageRuleParameter\"\x86\x01\n\x10\x41\x64\x61mSGDParameter\x12\x15\n\rlearning_rate\x18\x01 \x01(\x01\x12\x16\n\x0e\x61vg_decay_rate\x18\x02 \x01(\x01\x12\x16\n\x0e\x61\x64\x61_decay_rate\x18\x03 \x01(\x01\x12\x13\n\x0b\x61\x64\x61_epsilon\x18\x04 \x01(\x01\x12\x16\n\x0emom_decay_rate\x18\x05 \x01(\x01\"B\n\x11NaiveSGDParameter\x12\x15\n\rlearning_rate\x18\x01 \x01(\x01\x12\x16\n\x0e\x61vg_decay_rate\x18\x02 \x01(\x01\";\n\x13SummarySGDParameter\x12$\n\x12summary_decay_rate\x18\x01 \x01(\x01:\x08\x30.999999\".\n\x1aMovingAverageRuleParameter\x12\x10\n\x08momentum\x18\x01 \x01(\x01\"I\n\x11PsResponseMessage\x12\x13\n\x08\x65rr_code\x18\x01 \x02(\x05:\x01\x30\x12\x11\n\x07\x65rr_msg\x18\x02 \x02(\t:\x00\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xd5\x01\n\x11\x46sClientParameter\x12:\n\x07\x66s_type\x18\x01 \x01(\x0e\x32#.paddle.FsClientParameter.FsApiType:\x04HDFS\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\x0c\n\x04user\x18\x03 \x01(\t\x12\x0e\n\x06passwd\x18\x04 \x01(\t\x12\x13\n\x0b\x62uffer_size\x18\x05 \x01(\x05\x12\x12\n\nhadoop_bin\x18\x33 \x01(\t\x12\x10\n\x08\x61\x66s_conf\x18\x65 \x01(\t\"\x1e\n\tFsApiType\x12\x08\n\x04HDFS\x10\x00\x12\x07\n\x03\x41\x46S\x10\x01*4\n\tTableType\x12\x13\n\x0fPS_SPARSE_TABLE\x10\x00\x12\x12\n\x0ePS_DENSE_TABLE\x10\x01*\xbd\x02\n\x07PsCmdID\x12\x17\n\x13PS_PULL_DENSE_TABLE\x10\x00\x12\x17\n\x13PS_PUSH_DENSE_TABLE\x10\x01\x12\x18\n\x14PS_PULL_SPARSE_TABLE\x10\x02\x12\x18\n\x14PS_PUSH_SPARSE_TABLE\x10\x03\x12\x13\n\x0fPS_SHRINK_TABLE\x10\x04\x12\x15\n\x11PS_SAVE_ONE_TABLE\x10\x05\x12\x15\n\x11PS_SAVE_ALL_TABLE\x10\x06\x12\x15\n\x11PS_LOAD_ONE_TABLE\x10\x07\x12\x15\n\x11PS_LOAD_ALL_TABLE\x10\x08\x12\x16\n\x12PS_CLEAR_ONE_TABLE\x10\t\x12\x16\n\x12PS_CLEAR_ALL_TABLE\x10\n\x12\x17\n\x13PS_PUSH_DENSE_PARAM\x10\x0b\x12\x12\n\x0ePS_STOP_SERVER\x10\x0c\x32K\n\tPsService\x12>\n\x07service\x12\x18.paddle.PsRequestMessage\x1a\x19.paddle.PsResponseMessageB\x03\x80\x01\x01' + )) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_TABLETYPE = _descriptor.EnumDescriptor( + name='TableType', + full_name='paddle.TableType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='PS_SPARSE_TABLE', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_DENSE_TABLE', + index=1, + number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3489, + serialized_end=3541, +) +_sym_db.RegisterEnumDescriptor(_TABLETYPE) + +TableType = enum_type_wrapper.EnumTypeWrapper(_TABLETYPE) +_PSCMDID = _descriptor.EnumDescriptor( + name='PsCmdID', + full_name='paddle.PsCmdID', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='PS_PULL_DENSE_TABLE', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_DENSE_TABLE', + index=1, + number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PULL_SPARSE_TABLE', + index=2, + number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_SPARSE_TABLE', + index=3, + number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SHRINK_TABLE', + index=4, + number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SAVE_ONE_TABLE', + index=5, + number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SAVE_ALL_TABLE', + index=6, + number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_LOAD_ONE_TABLE', + index=7, + number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_LOAD_ALL_TABLE', + index=8, + number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_CLEAR_ONE_TABLE', + index=9, + number=9, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_CLEAR_ALL_TABLE', + index=10, + number=10, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_DENSE_PARAM', + index=11, + number=11, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_STOP_SERVER', + index=12, + number=12, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3544, + serialized_end=3861, +) +_sym_db.RegisterEnumDescriptor(_PSCMDID) + +PsCmdID = enum_type_wrapper.EnumTypeWrapper(_PSCMDID) +PS_SPARSE_TABLE = 0 +PS_DENSE_TABLE = 1 +PS_PULL_DENSE_TABLE = 0 +PS_PUSH_DENSE_TABLE = 1 +PS_PULL_SPARSE_TABLE = 2 +PS_PUSH_SPARSE_TABLE = 3 +PS_SHRINK_TABLE = 4 +PS_SAVE_ONE_TABLE = 5 +PS_SAVE_ALL_TABLE = 6 +PS_LOAD_ONE_TABLE = 7 +PS_LOAD_ALL_TABLE = 8 +PS_CLEAR_ONE_TABLE = 9 +PS_CLEAR_ALL_TABLE = 10 +PS_PUSH_DENSE_PARAM = 11 +PS_STOP_SERVER = 12 + +_FSCLIENTPARAMETER_FSAPITYPE = _descriptor.EnumDescriptor( + name='FsApiType', + full_name='paddle.FsClientParameter.FsApiType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='HDFS', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='AFS', + index=1, + number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3457, + serialized_end=3487, +) +_sym_db.RegisterEnumDescriptor(_FSCLIENTPARAMETER_FSAPITYPE) + +_PSPARAMETER = _descriptor.Descriptor( + name='PSParameter', + full_name='paddle.PSParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='worker_class', + full_name='paddle.PSParameter.worker_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='server_class', + full_name='paddle.PSParameter.server_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='instance_class', + full_name='paddle.PSParameter.instance_class', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='worker_param', + full_name='paddle.PSParameter.worker_param', + index=3, + number=101, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='server_param', + full_name='paddle.PSParameter.server_param', + index=4, + number=102, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_param', + full_name='paddle.PSParameter.trainer_param', + index=5, + number=301, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fs_client_param', + full_name='paddle.PSParameter.fs_client_param', + index=6, + number=501, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=21, + serialized_end=307, +) + +_WORKERPARAMETER = _descriptor.Descriptor( + name='WorkerParameter', + full_name='paddle.WorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_worker_param', + full_name='paddle.WorkerParameter.downpour_worker_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=309, + serialized_end=390, +) + +_SERVERPARAMETER = _descriptor.Descriptor( + name='ServerParameter', + full_name='paddle.ServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_server_param', + full_name='paddle.ServerParameter.downpour_server_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=392, + serialized_end=473, +) + +_DOWNPOURWORKERPARAMETER = _descriptor.Descriptor( + name='DownpourWorkerParameter', + full_name='paddle.DownpourWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', + full_name='paddle.DownpourWorkerParameter.downpour_table_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=475, + serialized_end=554, +) + +_DOWNPOURTRAINERPARAMETER = _descriptor.Descriptor( + name='DownpourTrainerParameter', + full_name='paddle.DownpourTrainerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dense_table', + full_name='paddle.DownpourTrainerParameter.dense_table', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table', + full_name='paddle.DownpourTrainerParameter.sparse_table', + index=1, + number=2, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_per_batch', + full_name='paddle.DownpourTrainerParameter.push_sparse_per_batch', + index=2, + number=3, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_per_batch', + full_name='paddle.DownpourTrainerParameter.push_dense_per_batch', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='skip_op', + full_name='paddle.DownpourTrainerParameter.skip_op', + index=4, + number=5, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='program_config', + full_name='paddle.DownpourTrainerParameter.program_config', + index=5, + number=6, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=557, + serialized_end=810, +) + +_PROGRAMCONFIG = _descriptor.Descriptor( + name='ProgramConfig', + full_name='paddle.ProgramConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='program_id', + full_name='paddle.ProgramConfig.program_id', + index=0, + number=1, + type=9, + cpp_type=9, + label=2, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_table_id', + full_name='paddle.ProgramConfig.push_sparse_table_id', + index=1, + number=2, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_table_id', + full_name='paddle.ProgramConfig.push_dense_table_id', + index=2, + number=3, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_sparse_table_id', + full_name='paddle.ProgramConfig.pull_sparse_table_id', + index=3, + number=4, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_dense_table_id', + full_name='paddle.ProgramConfig.pull_dense_table_id', + index=4, + number=5, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=813, + serialized_end=966, +) + +_DENSETABLEPARAMETER = _descriptor.Descriptor( + name='DenseTableParameter', + full_name='paddle.DenseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.DenseTableParameter.table_id', + index=0, + number=1, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_variable_name', + full_name='paddle.DenseTableParameter.dense_variable_name', + index=1, + number=2, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_gradient_variable_name', + full_name='paddle.DenseTableParameter.dense_gradient_variable_name', + index=2, + number=3, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', + full_name='paddle.DenseTableParameter.fea_dim', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=968, + serialized_end=1091, +) + +_SPARSETABLEPARAMETER = _descriptor.Descriptor( + name='SparseTableParameter', + full_name='paddle.SparseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.SparseTableParameter.table_id', + index=0, + number=1, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_dim', + full_name='paddle.SparseTableParameter.feature_dim', + index=1, + number=2, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_key', + full_name='paddle.SparseTableParameter.slot_key', + index=2, + number=3, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_value', + full_name='paddle.SparseTableParameter.slot_value', + index=3, + number=4, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_gradient', + full_name='paddle.SparseTableParameter.slot_gradient', + index=4, + number=5, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1093, + serialized_end=1215, +) + +_DOWNPOURSERVERPARAMETER = _descriptor.Descriptor( + name='DownpourServerParameter', + full_name='paddle.DownpourServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', + full_name='paddle.DownpourServerParameter.downpour_table_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_param', + full_name='paddle.DownpourServerParameter.service_param', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1218, + serialized_end=1352, +) + +_SERVERSERVICEPARAMETER = _descriptor.Descriptor( + name='ServerServiceParameter', + full_name='paddle.ServerServiceParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='server_class', + full_name='paddle.ServerServiceParameter.server_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourBrpcPsServer").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_class', + full_name='paddle.ServerServiceParameter.client_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourBrpcPsClient").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_class', + full_name='paddle.ServerServiceParameter.service_class', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourPsService").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_server_port', + full_name='paddle.ServerServiceParameter.start_server_port', + index=3, + number=4, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_thread_num', + full_name='paddle.ServerServiceParameter.server_thread_num', + index=4, + number=5, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=12, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1355, + serialized_end=1570, +) + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='table_id', + full_name='paddle.TableParameter.table_id', + index=0, + number=1, + type=4, + cpp_type=4, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_class', + full_name='paddle.TableParameter.table_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shared_num', + full_name='paddle.TableParameter.shared_num', + index=2, + number=3, + type=4, + cpp_type=4, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='accessor', + full_name='paddle.TableParameter.accessor', + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='type', + full_name='paddle.TableParameter.type', + index=4, + number=5, + type=14, + cpp_type=8, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compress_in_save', + full_name='paddle.TableParameter.compress_in_save', + index=5, + number=6, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1573, + serialized_end=1764, +) + +_TABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='TableAccessorParameter', + full_name='paddle.TableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='accessor_class', + full_name='paddle.TableAccessorParameter.accessor_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_sgd_param', + full_name='paddle.TableAccessorParameter.sparse_sgd_param', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_sgd_param', + full_name='paddle.TableAccessorParameter.dense_sgd_param', + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', + full_name='paddle.TableAccessorParameter.fea_dim', + index=3, + number=4, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_dim', + full_name='paddle.TableAccessorParameter.embedx_dim', + index=4, + number=5, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_threshold', + full_name='paddle.TableAccessorParameter.embedx_threshold', + index=5, + number=6, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='downpour_accessor_param', + full_name='paddle.TableAccessorParameter.downpour_accessor_param', + index=6, + number=7, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_accessor_save_param', + full_name='paddle.TableAccessorParameter.table_accessor_save_param', + index=7, + number=8, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1767, + serialized_end=2136, +) + +_DOWNPOURTABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='DownpourTableAccessorParameter', + full_name='paddle.DownpourTableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nonclk_coeff', + full_name='paddle.DownpourTableAccessorParameter.nonclk_coeff', + index=0, + number=1, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='click_coeff', + full_name='paddle.DownpourTableAccessorParameter.click_coeff', + index=1, + number=2, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='base_threshold', + full_name='paddle.DownpourTableAccessorParameter.base_threshold', + index=2, + number=3, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_threshold', + full_name='paddle.DownpourTableAccessorParameter.delta_threshold', + index=3, + number=4, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_keep_days', + full_name='paddle.DownpourTableAccessorParameter.delta_keep_days', + index=4, + number=5, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_click_decay_rate', + full_name= + 'paddle.DownpourTableAccessorParameter.show_click_decay_rate', + index=5, + number=6, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_threshold', + full_name='paddle.DownpourTableAccessorParameter.delete_threshold', + index=6, + number=7, + type=2, + cpp_type=6, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2139, + serialized_end=2345, +) + +_TABLEACCESSORSAVEPARAMETER = _descriptor.Descriptor( + name='TableAccessorSaveParameter', + full_name='paddle.TableAccessorSaveParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='param', + full_name='paddle.TableAccessorSaveParameter.param', + index=0, + number=1, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='converter', + full_name='paddle.TableAccessorSaveParameter.converter', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deconverter', + full_name='paddle.TableAccessorSaveParameter.deconverter', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2347, + serialized_end=2430, +) + +_PSREQUESTMESSAGE = _descriptor.Descriptor( + name='PsRequestMessage', + full_name='paddle.PsRequestMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='cmd_id', + full_name='paddle.PsRequestMessage.cmd_id', + index=0, + number=1, + type=13, + cpp_type=3, + label=2, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.PsRequestMessage.table_id', + index=1, + number=2, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='params', + full_name='paddle.PsRequestMessage.params', + index=2, + number=3, + type=12, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_id', + full_name='paddle.PsRequestMessage.client_id', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='data', + full_name='paddle.PsRequestMessage.data', + index=4, + number=5, + type=12, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b(""), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2432, + serialized_end=2533, +) + +_SPARSESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseSGDRuleParameter', + full_name='paddle.SparseSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.SparseSGDRuleParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', + full_name='paddle.SparseSGDRuleParameter.initial_g2sum', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', + full_name='paddle.SparseSGDRuleParameter.initial_range', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', + full_name='paddle.SparseSGDRuleParameter.weight_bounds', + index=3, + number=4, + type=2, + cpp_type=6, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2535, + serialized_end=2654, +) + +_DENSESGDRULEPARAMETER = _descriptor.Descriptor( + name='DenseSGDRuleParameter', + full_name='paddle.DenseSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', + full_name='paddle.DenseSGDRuleParameter.name', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', + full_name='paddle.DenseSGDRuleParameter.adam', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', + full_name='paddle.DenseSGDRuleParameter.naive', + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='summary', + full_name='paddle.DenseSGDRuleParameter.summary', + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='moving_average', + full_name='paddle.DenseSGDRuleParameter.moving_average', + index=4, + number=5, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2657, + serialized_end=2882, +) + +_ADAMSGDPARAMETER = _descriptor.Descriptor( + name='AdamSGDParameter', + full_name='paddle.AdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.AdamSGDParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg_decay_rate', + full_name='paddle.AdamSGDParameter.avg_decay_rate', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_decay_rate', + full_name='paddle.AdamSGDParameter.ada_decay_rate', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', + full_name='paddle.AdamSGDParameter.ada_epsilon', + index=3, + number=4, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mom_decay_rate', + full_name='paddle.AdamSGDParameter.mom_decay_rate', + index=4, + number=5, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2885, + serialized_end=3019, +) + +_NAIVESGDPARAMETER = _descriptor.Descriptor( + name='NaiveSGDParameter', + full_name='paddle.NaiveSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.NaiveSGDParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg_decay_rate', + full_name='paddle.NaiveSGDParameter.avg_decay_rate', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3021, + serialized_end=3087, +) + +_SUMMARYSGDPARAMETER = _descriptor.Descriptor( + name='SummarySGDParameter', + full_name='paddle.SummarySGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='summary_decay_rate', + full_name='paddle.SummarySGDParameter.summary_decay_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.999999), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3089, + serialized_end=3148, +) + +_MOVINGAVERAGERULEPARAMETER = _descriptor.Descriptor( + name='MovingAverageRuleParameter', + full_name='paddle.MovingAverageRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='momentum', + full_name='paddle.MovingAverageRuleParameter.momentum', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3150, + serialized_end=3196, +) + +_PSRESPONSEMESSAGE = _descriptor.Descriptor( + name='PsResponseMessage', + full_name='paddle.PsResponseMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='err_code', + full_name='paddle.PsResponseMessage.err_code', + index=0, + number=1, + type=5, + cpp_type=1, + label=2, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='err_msg', + full_name='paddle.PsResponseMessage.err_msg', + index=1, + number=2, + type=9, + cpp_type=9, + label=2, + has_default_value=True, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='data', + full_name='paddle.PsResponseMessage.data', + index=2, + number=3, + type=12, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b(""), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3198, + serialized_end=3271, +) + +_FSCLIENTPARAMETER = _descriptor.Descriptor( + name='FsClientParameter', + full_name='paddle.FsClientParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fs_type', + full_name='paddle.FsClientParameter.fs_type', + index=0, + number=1, + type=14, + cpp_type=8, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='uri', + full_name='paddle.FsClientParameter.uri', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='user', + full_name='paddle.FsClientParameter.user', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='passwd', + full_name='paddle.FsClientParameter.passwd', + index=3, + number=4, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='buffer_size', + full_name='paddle.FsClientParameter.buffer_size', + index=4, + number=5, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hadoop_bin', + full_name='paddle.FsClientParameter.hadoop_bin', + index=5, + number=51, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='afs_conf', + full_name='paddle.FsClientParameter.afs_conf', + index=6, + number=101, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[ + _FSCLIENTPARAMETER_FSAPITYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3274, + serialized_end=3487, +) + +_PSPARAMETER.fields_by_name['worker_param'].message_type = _WORKERPARAMETER +_PSPARAMETER.fields_by_name['server_param'].message_type = _SERVERPARAMETER +_PSPARAMETER.fields_by_name[ + 'trainer_param'].message_type = _DOWNPOURTRAINERPARAMETER +_PSPARAMETER.fields_by_name['fs_client_param'].message_type = _FSCLIENTPARAMETER +_WORKERPARAMETER.fields_by_name[ + 'downpour_worker_param'].message_type = _DOWNPOURWORKERPARAMETER +_SERVERPARAMETER.fields_by_name[ + 'downpour_server_param'].message_type = _DOWNPOURSERVERPARAMETER +_DOWNPOURWORKERPARAMETER.fields_by_name[ + 'downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'dense_table'].message_type = _DENSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'sparse_table'].message_type = _SPARSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'program_config'].message_type = _PROGRAMCONFIG +_DOWNPOURSERVERPARAMETER.fields_by_name[ + 'downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURSERVERPARAMETER.fields_by_name[ + 'service_param'].message_type = _SERVERSERVICEPARAMETER +_TABLEPARAMETER.fields_by_name[ + 'accessor'].message_type = _TABLEACCESSORPARAMETER +_TABLEPARAMETER.fields_by_name['type'].enum_type = _TABLETYPE +_TABLEACCESSORPARAMETER.fields_by_name[ + 'sparse_sgd_param'].message_type = _SPARSESGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'dense_sgd_param'].message_type = _DENSESGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'downpour_accessor_param'].message_type = _DOWNPOURTABLEACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'table_accessor_save_param'].message_type = _TABLEACCESSORSAVEPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name['adam'].message_type = _ADAMSGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name['naive'].message_type = _NAIVESGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name[ + 'summary'].message_type = _SUMMARYSGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name[ + 'moving_average'].message_type = _MOVINGAVERAGERULEPARAMETER +_FSCLIENTPARAMETER.fields_by_name[ + 'fs_type'].enum_type = _FSCLIENTPARAMETER_FSAPITYPE +_FSCLIENTPARAMETER_FSAPITYPE.containing_type = _FSCLIENTPARAMETER +DESCRIPTOR.message_types_by_name['PSParameter'] = _PSPARAMETER +DESCRIPTOR.message_types_by_name['WorkerParameter'] = _WORKERPARAMETER +DESCRIPTOR.message_types_by_name['ServerParameter'] = _SERVERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourWorkerParameter'] = _DOWNPOURWORKERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourTrainerParameter'] = _DOWNPOURTRAINERPARAMETER +DESCRIPTOR.message_types_by_name['ProgramConfig'] = _PROGRAMCONFIG +DESCRIPTOR.message_types_by_name['DenseTableParameter'] = _DENSETABLEPARAMETER +DESCRIPTOR.message_types_by_name['SparseTableParameter'] = _SPARSETABLEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourServerParameter'] = _DOWNPOURSERVERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'ServerServiceParameter'] = _SERVERSERVICEPARAMETER +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'TableAccessorParameter'] = _TABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourTableAccessorParameter'] = _DOWNPOURTABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name[ + 'TableAccessorSaveParameter'] = _TABLEACCESSORSAVEPARAMETER +DESCRIPTOR.message_types_by_name['PsRequestMessage'] = _PSREQUESTMESSAGE +DESCRIPTOR.message_types_by_name[ + 'SparseSGDRuleParameter'] = _SPARSESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DenseSGDRuleParameter'] = _DENSESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['AdamSGDParameter'] = _ADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name['NaiveSGDParameter'] = _NAIVESGDPARAMETER +DESCRIPTOR.message_types_by_name['SummarySGDParameter'] = _SUMMARYSGDPARAMETER +DESCRIPTOR.message_types_by_name[ + 'MovingAverageRuleParameter'] = _MOVINGAVERAGERULEPARAMETER +DESCRIPTOR.message_types_by_name['PsResponseMessage'] = _PSRESPONSEMESSAGE +DESCRIPTOR.message_types_by_name['FsClientParameter'] = _FSCLIENTPARAMETER +DESCRIPTOR.enum_types_by_name['TableType'] = _TABLETYPE +DESCRIPTOR.enum_types_by_name['PsCmdID'] = _PSCMDID + +PSParameter = _reflection.GeneratedProtocolMessageType( + 'PSParameter', + (_message.Message, ), + dict(DESCRIPTOR=_PSPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PSParameter) + )) +_sym_db.RegisterMessage(PSParameter) + +WorkerParameter = _reflection.GeneratedProtocolMessageType( + 'WorkerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_WORKERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.WorkerParameter) + )) +_sym_db.RegisterMessage(WorkerParameter) + +ServerParameter = _reflection.GeneratedProtocolMessageType( + 'ServerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SERVERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ServerParameter) + )) +_sym_db.RegisterMessage(ServerParameter) + +DownpourWorkerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourWorkerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURWORKERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourWorkerParameter) + )) +_sym_db.RegisterMessage(DownpourWorkerParameter) + +DownpourTrainerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourTrainerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURTRAINERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourTrainerParameter) + )) +_sym_db.RegisterMessage(DownpourTrainerParameter) + +ProgramConfig = _reflection.GeneratedProtocolMessageType( + 'ProgramConfig', + (_message.Message, ), + dict(DESCRIPTOR=_PROGRAMCONFIG, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ProgramConfig) + )) +_sym_db.RegisterMessage(ProgramConfig) + +DenseTableParameter = _reflection.GeneratedProtocolMessageType( + 'DenseTableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DENSETABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DenseTableParameter) + )) +_sym_db.RegisterMessage(DenseTableParameter) + +SparseTableParameter = _reflection.GeneratedProtocolMessageType( + 'SparseTableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SPARSETABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseTableParameter) + )) +_sym_db.RegisterMessage(SparseTableParameter) + +DownpourServerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourServerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURSERVERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourServerParameter) + )) +_sym_db.RegisterMessage(DownpourServerParameter) + +ServerServiceParameter = _reflection.GeneratedProtocolMessageType( + 'ServerServiceParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SERVERSERVICEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ServerServiceParameter) + )) +_sym_db.RegisterMessage(ServerServiceParameter) + +TableParameter = _reflection.GeneratedProtocolMessageType( + 'TableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_TABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + +TableAccessorParameter = _reflection.GeneratedProtocolMessageType( + 'TableAccessorParameter', + (_message.Message, ), + dict(DESCRIPTOR=_TABLEACCESSORPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableAccessorParameter) + )) +_sym_db.RegisterMessage(TableAccessorParameter) + +DownpourTableAccessorParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourTableAccessorParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_DOWNPOURTABLEACCESSORPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourTableAccessorParameter) + )) +_sym_db.RegisterMessage(DownpourTableAccessorParameter) + +TableAccessorSaveParameter = _reflection.GeneratedProtocolMessageType( + 'TableAccessorSaveParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_TABLEACCESSORSAVEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableAccessorSaveParameter) + )) +_sym_db.RegisterMessage(TableAccessorSaveParameter) + +PsRequestMessage = _reflection.GeneratedProtocolMessageType( + 'PsRequestMessage', + (_message.Message, ), + dict(DESCRIPTOR=_PSREQUESTMESSAGE, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PsRequestMessage) + )) +_sym_db.RegisterMessage(PsRequestMessage) + +SparseSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'SparseSGDRuleParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SPARSESGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseSGDRuleParameter) + +DenseSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'DenseSGDRuleParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DENSESGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DenseSGDRuleParameter) + )) +_sym_db.RegisterMessage(DenseSGDRuleParameter) + +AdamSGDParameter = _reflection.GeneratedProtocolMessageType( + 'AdamSGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_ADAMSGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.AdamSGDParameter) + )) +_sym_db.RegisterMessage(AdamSGDParameter) + +NaiveSGDParameter = _reflection.GeneratedProtocolMessageType( + 'NaiveSGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_NAIVESGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.NaiveSGDParameter) + )) +_sym_db.RegisterMessage(NaiveSGDParameter) + +SummarySGDParameter = _reflection.GeneratedProtocolMessageType( + 'SummarySGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SUMMARYSGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SummarySGDParameter) + )) +_sym_db.RegisterMessage(SummarySGDParameter) + +MovingAverageRuleParameter = _reflection.GeneratedProtocolMessageType( + 'MovingAverageRuleParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_MOVINGAVERAGERULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.MovingAverageRuleParameter) + )) +_sym_db.RegisterMessage(MovingAverageRuleParameter) + +PsResponseMessage = _reflection.GeneratedProtocolMessageType( + 'PsResponseMessage', + (_message.Message, ), + dict(DESCRIPTOR=_PSRESPONSEMESSAGE, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PsResponseMessage) + )) +_sym_db.RegisterMessage(PsResponseMessage) + +FsClientParameter = _reflection.GeneratedProtocolMessageType( + 'FsClientParameter', + (_message.Message, ), + dict(DESCRIPTOR=_FSCLIENTPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.FsClientParameter) + )) +_sym_db.RegisterMessage(FsClientParameter) + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), + _b('\200\001\001')) +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d66e33097833a53a9fbff06437816d4320be652e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/__init__.py @@ -0,0 +1,75 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from . import base +from .base import * + +from . import layers +from .layers import * + +from . import container +from .container import * + +from . import nn +from .nn import * + +from . import tracer +from .tracer import * + +from . import parallel +from .parallel import * + +from . import checkpoint +from .checkpoint import * + +from . import learning_rate_scheduler +from .learning_rate_scheduler import * + +from . import jit +from .jit import * + +from . import io +from .io import * + +from . import static_runner +from .static_runner import StaticModelRunner + +from . import dygraph_to_static +from .dygraph_to_static import ProgramTranslator + +from . import rnn +from .rnn import * + +from . import amp +from .amp import * + +from .math_op_patch import monkey_patch_math_varbase + +from .inplace_utils import inplace_apis_in_dygraph_only + +__all__ = [] +__all__ += layers.__all__ +__all__ += base.__all__ +__all__ += container.__all__ +__all__ += nn.__all__ +__all__ += parallel.__all__ +__all__ += checkpoint.__all__ +__all__ += learning_rate_scheduler.__all__ +__all__ += jit.__all__ +__all__ += io.__all__ +__all__ += rnn.__all__ +__all__ += ['ProgramTranslator'] +__all__ += amp.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e86c5a20c5a411fda2a0011f63f4b5254e9bd07a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/__init__.py @@ -0,0 +1,23 @@ +# 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. + +from . import auto_cast +from .auto_cast import * + +from . import loss_scaler +from .loss_scaler import * + +__all__ = [] +__all__ += auto_cast.__all__ +__all__ += loss_scaler.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/auto_cast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/auto_cast.py new file mode 100644 index 0000000000000000000000000000000000000000..87df808213656254067fa08117c92db5b1a947fd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/auto_cast.py @@ -0,0 +1,564 @@ +# 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. + +from __future__ import print_function +from paddle.fluid.wrapped_decorator import signature_safe_contextmanager, wrap_decorator +from paddle.fluid import core +import contextlib +from paddle.fluid.framework import Variable, _non_static_mode, OpProtoHolder, Parameter, _dygraph_tracer, dygraph_only, set_flags, get_flags +import warnings +import copy +import functools +import paddle +import operator +import types + +AMP_LEVEL = core.AmpLevel + +__all__ = ['amp_guard', 'amp_decorate'] + +# The set of ops that support fp16 calculation and are considered numerically- +# safe and performance-critical. These ops are always converted to fp16. +WHITE_LIST = { + 'conv2d', + 'matmul', + 'matmul_v2', + 'mul', + 'fake_quantize_dequantize_abs_max', + 'fake_quantize_dequantize_moving_average_abs_max', +} + +# The set of ops that support fp16 calculation and are considered numerically- +# dangerous and whose effects may also be observed in downstream ops. +BLACK_LIST = { + 'exp', + 'square', + 'log', + 'mean', + 'sum', + 'cos_sim', + 'softmax', + 'softmax_with_cross_entropy', + 'sigmoid_cross_entropy_with_logits', + 'c_softmax_with_cross_entropy', + 'cross_entropy', + 'cross_entropy2', + # default fp32 can avoid return inf when the sum value large than 65504 + 'reduce_sum', + # FP16 performance of grad op is worse than that of FP32. Use FP32 by default. + 'linear_interp_v2', + 'nearest_interp_v2', + 'bilinear_interp_v2', + 'bicubic_interp_v2', + 'trilinear_interp_v2', +} + +AMP_RELATED_FLAGS = [ + 'FLAGS_cudnn_exhaustive_search', + 'FLAGS_conv_workspace_size_limit', + 'FLAGS_cudnn_batchnorm_spatial_persistent', +] + +AMP_RELATED_FLAGS_SETTING = { + 'FLAGS_cudnn_exhaustive_search': 1, + 'FLAGS_conv_workspace_size_limit': 1000, + 'FLAGS_cudnn_batchnorm_spatial_persistent': 1, +} + +PURE_FP16_WHITE_LIST = {' '} +PURE_FP16_BLACK_LIST = { + 'lookup_table', + 'lookup_table_v2', + 'scatter', + 'scatter_grad', + # FP16 performance of grad op is worse than that of FP32. Use FP32 by default. + 'linear_interp_v2', + 'nearest_interp_v2', + 'bilinear_interp_v2', + 'bicubic_interp_v2', + 'trilinear_interp_v2', +} + +BF16_WHITE_LIST = {'conv2d', 'matmul_v2'} +BF16_BLACK_LIST = {' '} + +_g_amp_state_ = None + + +def amp_state(): + global _g_amp_state_ + return _g_amp_state_ + + +#NOTE(zhiqiu): similar as paddle.fluid.contrib.mixed_precision.fp16_lists.AutoMixedPrecisionLists._update_list +# The reason why not use AutoMixedPrecisionLists is that custom_black_varnames is not suitable for imperative mode. +def _update_list(custom_white_list, + custom_black_list, + level='O1', + dtype='float16'): + """ + Update black and white list according to users' custom list. + """ + if dtype == 'float16': + if level == 'O1': + _white_list = copy.copy(WHITE_LIST) + _black_list = copy.copy(BLACK_LIST) + else: + _white_list = copy.copy(PURE_FP16_WHITE_LIST) + _black_list = copy.copy(PURE_FP16_BLACK_LIST) + else: + _white_list = copy.copy(BF16_WHITE_LIST) + _black_list = copy.copy(BF16_BLACK_LIST) + if custom_white_list and custom_black_list: + for op_name in custom_white_list: + if op_name in custom_black_list: + raise ValueError("Custom white list overlap " + "custom black list") + if custom_white_list: + for op_name in custom_white_list: + if op_name in _black_list: + _black_list.remove(op_name) + _white_list.add(op_name) + if custom_black_list: + for op_name in custom_black_list: + if op_name in _white_list: + _white_list.remove(op_name) + _black_list.add(op_name) + return _white_list, _black_list + + +def _in_amp_guard(): + """ + Judge whether current code block is in `amp_guard` context. + """ + tracer = _dygraph_tracer() + if tracer: + if tracer._amp_level == core.AmpLevel.O1: + return True + else: + return False + else: + return False + + +def _in_pure_fp16_guard(): + tracer = _dygraph_tracer() + return tracer and tracer._amp_level == core.AmpLevel.O2 + + +def _is_gpu_float16_supported(): + """ + Judge whether current gpu support float16 amp. + """ + prop = paddle.device.cuda.get_device_capability() + return prop[0] >= 7 + + +def _is_gpu_bfloat16_supported(): + """ + Judge whether current gpu support bfloat16 amp. + """ + prop = paddle.device.cuda.get_device_capability() + cuda_version = paddle.version.cuda() + if cuda_version is not None and cuda_version != 'False': + cuda_version_check = int(cuda_version.split('.')[0]) >= 11 + else: + cuda_version_check = False + return prop[0] >= 8 and cuda_version_check + + +@dygraph_only +def pure_fp16_initialize(models): + for idx in range(len(models)): + for layer in models[idx].sublayers(include_self=True): + layer._casted_by_pure_fp16 = True + if (layer._dtype == 'float16') or isinstance( + layer, (paddle.nn.BatchNorm, paddle.nn.BatchNorm1D, + paddle.nn.BatchNorm2D, paddle.nn.BatchNorm3D, + paddle.nn.LayerNorm, paddle.nn.SyncBatchNorm)): + continue + if isinstance(layer, (paddle.incubate.nn.FusedFeedForward, + paddle.incubate.nn.FusedMultiHeadAttention)): + layer._amp_decorate(dtype='float16') + continue + layer._to_impl(dtype='float16', + include_sublayers=False, + floating_only=True) + return models + + +def check_models(models): + for model in models: + if not isinstance(model, paddle.nn.Layer): + raise RuntimeError( + "Current train mode is pure fp16, models should be paddle.nn.Layer, but receive {}." + .format(type(model))) + if isinstance(model, paddle.DataParallel): + raise RuntimeError( + "For distributed AMP training, you should first use paddle.amp.decorate() to decotate origin model, and then call paddle.DataParallel get distributed model." + ) + + +def check_optimizers(optimizers): + for optimizer in optimizers: + if not isinstance( + optimizer, + (paddle.optimizer.Optimizer, paddle.fluid.optimizer.Optimizer)): + raise RuntimeError( + "Current train mode is pure fp16, optimizers should be paddle.optimizer.Optimizer or paddle.fluid.optimizer.Optimizer, but receive {}." + .format(type(optimizer))) + + +@signature_safe_contextmanager +@dygraph_only +def amp_guard(enable=True, + custom_white_list=None, + custom_black_list=None, + level='O1', + dtype='float16'): + """ + :api_attr: imperative + + Create a context which enables auto-mixed-precision(AMP) of operators executed in dynamic graph mode. + If enabled, the input data type (float32 or float16) of each operator is decided + by autocast algorithm for better performance. + + Commonly, it is used together with `GradScaler` to achieve Auto-Mixed-Precision in + imperative mode. It is used together with `decorator` to achieve Pure fp16 in imperative mode. + + Args: + enable(bool, optional): Enable auto-mixed-precision or not. Default is True. + custom_white_list(set|list|tuple, optional): The custom white_list. It's the set of ops that support + fp16 calculation and are considered numerically-safe and performance-critical. These ops + will be converted to fp16. + custom_black_list(set|list|tuple, optional): The custom black_list. The set of ops that support fp16 + calculation and are considered numerically-dangerous and whose effects may also be + observed in downstream ops. These ops will not be converted to fp16. + level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the input data type of each operator will be casted by white_list and black_list; + O2 represent Pure fp16, all operators parameters and input data will be casted to fp16, except operators in black_list, don't support fp16 kernel and batchnorm. Default is O1(amp) + dtype(str, optional): Whether to use 'float16' or 'bfloat16'. Default is 'float16'. + + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32') + with paddle.fluid.dygraph.guard(): + conv2d = paddle.fluid.dygraph.Conv2D(3, 2, 3) + data = paddle.fluid.dygraph.to_variable(data) + with paddle.fluid.dygraph.amp_guard(): + conv = conv2d(data) + print(conv.dtype) # FP16 + with paddle.fluid.dygraph.amp_guard(enable=False): + conv = conv2d(data) + print(conv.dtype) # FP32 + + """ + amp_state = locals() + global _g_amp_state_ + original_state = _g_amp_state_ + _g_amp_state_ = amp_state + + # check amp_level: O0-O2 + level = level.upper() + if not (level in ['O0', 'O1', 'O2']): + raise ValueError( + "level should be O0, O1 or O2. O0 represents fp32 train mode, O1 represents AMP train mode, O2 represents pure fp16/bf16 train mode." + ) + + # check amp_dtype: float16 or bfloat16 + dtype = dtype.lower() + if not (dtype in ['float16', 'bfloat16']): + raise ValueError("dtype should be 'float16' or 'bfloat16'.") + + # check tracer + tracer = _dygraph_tracer() + if not tracer: + raise ValueError( + "current_tracer is None, maybe it is not in imperative mode.") + + # check device_type: + # NOTE: Now, amp only support gpu for float16 and bfloat16, xpu for float16, mlu for float16, npu for float16. + # Maybe we will support cpu for bfloat16. + if enable and not (tracer._expected_place.is_gpu_place() + or tracer._expected_place.is_xpu_place() + or tracer._expected_place.is_mlu_place() + or tracer._expected_place.is_npu_place() + or tracer._expected_place.is_custom_place()): + warnings.warn( + 'amp_guard can only be enabled on CUDAPlace, XPUPlace, MLUPlace, NPUPlace, and CustomPlace, current place is %s, so it makes no effect.' + % tracer._expected_place) + enable = False + # For npu: + if tracer._expected_place.is_npu_place() and (dtype == 'bfloat16'): + warnings.warn('NPUPlace only support float16 amp.') + enable = False + # For xpu: + if tracer._expected_place.is_xpu_place() and (dtype == 'bfloat16'): + warnings.warn('XPUPlace only support float16 amp.') + enable = False + # For mlu: + if tracer._expected_place.is_mlu_place() and (dtype == 'bfloat16'): + warnings.warn('MLUPlace only support float16 amp.') + enable = False + # For custom device: + if tracer._expected_place.is_custom_place() and (dtype == 'bfloat16'): + warnings.warn('CustomPlace only support float16 amp.') + enable = False + # For gpu float16: Compute Capability should >= 7. + # For gpu bfloat16: Compute Capability should >= 8 & CUDA Version should >= 11. + if tracer._expected_place.is_gpu_place(): + if (dtype == 'float16') and not _is_gpu_float16_supported(): + prop = paddle.device.cuda.get_device_capability() + warnings.warn( + "For float16, amp only support NVIDIA GPU with Compute Capability 7.0 or higher, current GPU is: %s, with Compute Capability: %d.%d." + % (paddle.device.cuda.get_device_name(), prop[0], prop[1])) + elif (dtype == 'bfloat16') and not _is_gpu_bfloat16_supported(): + prop = paddle.device.cuda.get_device_capability() + cuda_version = paddle.version.cuda() + warnings.warn( + "For bfloat16, amp only support NVIDIA GPU with Compute Capability 8.0 or higher and CUDA Version 11.0 or higher, current GPU is: %s, with Compute Capability: %d.%d, current CUDA Version is: %s." + % (paddle.device.cuda.get_device_name(), prop[0], prop[1], + cuda_version)) + + amp_dtype = dtype + + if level == 'O1': + amp_level = AMP_LEVEL.O1 + if dtype == 'float16': + _white_list = WHITE_LIST + _black_list = BLACK_LIST + elif dtype == 'bfloat16': + _white_list = BF16_WHITE_LIST + _black_list = BF16_BLACK_LIST + + elif level == 'O2': + amp_level = AMP_LEVEL.O2 + if dtype == 'float16': + _white_list = PURE_FP16_WHITE_LIST + _black_list = PURE_FP16_BLACK_LIST + elif dtype == 'bfloat16': + _white_list = BF16_WHITE_LIST + _black_list = BF16_BLACK_LIST + elif level == 'O0': + amp_level = AMP_LEVEL.O0 + if dtype == 'float16': + _white_list = WHITE_LIST + _black_list = BLACK_LIST + elif dtype == 'bfloat16': + _white_list = BF16_WHITE_LIST + _black_list = BF16_BLACK_LIST + + if custom_white_list or custom_black_list: + _white_list, _black_list = _update_list(custom_white_list, + custom_black_list, level, dtype) + + if not enable: + amp_level = AMP_LEVEL.O0 + amp_dtype = "float32" + + if tracer: + # enable auto_cast + original_amp_level = tracer._amp_level + tracer._amp_level = amp_level + + # set amp op list + original_white_list, original_black_list = tracer._get_amp_op_list() + tracer._set_amp_op_list(_white_list, _black_list) + + # TODO(zhiqiu) set amp related flags automatically in this guard + # Currently, if FLAGS_cudnn_batchnorm_spatial_persistent is set True in amp_guard, + # batch_norm can run in fast mode, but batch_norm_grad can not if backward if not executed insise amp_guard. + # So, users need to set related flags manually. + + # original_flags = get_flags(AMP_RELATED_FLAGS) + # set_flags(AMP_RELATED_FLAGS_SETTING) + + # set amp dtype + original_amp_dtype = tracer._amp_dtype + tracer._amp_dtype = amp_dtype + + # restore status + try: + yield + finally: + if tracer: + _g_amp_state_ = original_state + tracer._amp_level = original_amp_level + tracer._set_amp_op_list(original_white_list, original_black_list) + # set_flags(original_flags) + tracer._amp_dtype = original_amp_dtype + + +class StateDictHook(object): + + def __init__(self, save_dtype): + self._save_dtype = save_dtype + + def __call__(self, state_dict): + for key in state_dict: + param = state_dict[key] + with paddle.fluid.dygraph.guard(): + if paddle.is_floating_point(param): + param_applied = paddle.cast(param, self._save_dtype) + param_applied.name = param.name + state_dict[key] = param_applied + + +@dygraph_only +def amp_decorate(models, + optimizers=None, + level='O1', + master_weight=None, + save_dtype=None): + """ + Decorate models and optimizers for auto-mixed-precision. When level is O1(amp), the decorate will do nothing. + When level is O2(pure fp16), the decorate will cast all parameters of models to FP16, except BatchNorm and LayerNorm. + + Commonly, it is used together with `amp_guard` to achieve Pure fp16 in imperative mode. + + Args: + models(Layer|list of Layer, optional): The defined models by user, models must be either a single model or a list of models. Default is None. + optimizers(Optimizer|list of Optimizer, optional): The defined optimizers by user, optimizers must be either a single optimizer or a list of optimizers. Default is None. + level(str, optional): Auto mixed precision level. Accepted values are "O1" and "O2": O1 represent mixed precision, the decorator will do nothing; + O2 represent Pure fp16, the decorator will cast all parameters of models to FP16, except BatchNorm and LayerNorm. Default is O1(amp) + master_weight(bool, optinal): For level='O2', whether to use multi-precision during weight updating. If master_weight is None, in O2 level optimizer will use multi-precision. Default is None. + save_dtype(float, optional): The save model parameter dtype when use `paddle.save` or `paddle.jit.save`,it should be float16, float32, float64 or None. + The save_dtype will not change model parameters dtype, it just change the state_dict dtype. When save_dtype is None, the save dtype is same as model dtype. Default is None. + + Examples: + + .. code-block:: python + + # required: gpu + # Demo1: single model and optimizer: + import paddle + + model = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer = paddle.optimizer.SGD(parameters=model.parameters()) + + model, optimizer = paddle.fluid.dygraph.amp_decorate(models=model, optimizers=optimizer, level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = model(data) + print(output.dtype) # FP16 + + # required: gpu + # Demo2: multi models and optimizers: + model2 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer2 = paddle.optimizer.Adam(parameters=model2.parameters()) + + models, optimizers = paddle.fluid.dygraph.amp_decorate(models=[model, model2], optimizers=[optimizer, optimizer2], level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = models[0](data) + output2 = models[1](data) + print(output.dtype) # FP16 + print(output2.dtype) # FP16 + + # required: gpu + # Demo3: optimizers is None: + model3 = paddle.nn.Conv2D(3, 2, 3, bias_attr=False) + optimizer3 = paddle.optimizer.Adam(parameters=model2.parameters()) + + model = paddle.fluid.dygraph.amp_decorate(models=model3, level='O2') + + data = paddle.rand([10, 3, 32, 32]) + + with paddle.fluid.dygraph.amp_guard(enable=True, custom_white_list=None, custom_black_list=None, level='O2'): + output = model(data) + print(output.dtype) # FP16 + """ + if not (level in ['O1', 'O2']): + raise ValueError( + "level should be O1 or O2, O1 represent AMP train mode, O2 represent Pure fp16 train mode." + ) + + if level == 'O1': + if optimizers is None: + return models + else: + return models, optimizers + + models_is_list = False + if isinstance(models, paddle.nn.Layer): + models_is_list = False + models = [models] + check_models(models) + elif isinstance(models, list): + check_models(models) + models_is_list = True + else: + raise TypeError( + "models must be either a single model or a list of models.") + + models = pure_fp16_initialize(models=models) + + if optimizers is not None: + # check optimizers + optimizers_is_list = False + if isinstance( + optimizers, + (paddle.optimizer.Optimizer, paddle.fluid.optimizer.Optimizer)): + optimizers_is_list = False + optimizers = [optimizers] + check_optimizers(optimizers) + elif isinstance(optimizers, list): + check_optimizers(optimizers) + optimizers_is_list = True + else: + raise TypeError( + "optimizers must be either a single optimizer or a list of optimizers." + ) + # supprot master_weight + for idx_opt in range(len(optimizers)): + if hasattr(optimizers[idx_opt], '_multi_precision'): + if master_weight is False: + optimizers[idx_opt]._multi_precision = False + else: + optimizers[idx_opt]._multi_precision = True + + if save_dtype is not None: + if not (save_dtype in ['float16', 'float32', 'float64']): + raise ValueError( + "save_dtype can only be float16 float32 or float64, but your input save_dtype is %s." + % save_dtype) + for idx in range(len(models)): + for layer in models[idx].sublayers(include_self=True): + layer.register_state_dict_hook(StateDictHook(save_dtype)) + + if models_is_list: + if optimizers is not None: + if optimizers_is_list: + return models, optimizers + else: + return models, optimizers[0] + else: + return models + else: + if optimizers is not None: + if optimizers_is_list: + return models[0], optimizers + else: + return models[0], optimizers[0] + else: + return models[0] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/loss_scaler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/loss_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb4c730975a6c63152d9fd6dfbbaac4285d6e3a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/amp/loss_scaler.py @@ -0,0 +1,502 @@ +# 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. + +from __future__ import print_function +from paddle.fluid import core +from paddle.fluid.dygraph import to_variable +from paddle.fluid.framework import _varbase_creator, _dygraph_tracer, dygraph_only +from paddle.fluid.data_feeder import check_type +from ...wrapped_decorator import signature_safe_contextmanager, wrap_decorator +import warnings +import numpy as np +from paddle import _C_ops, _legacy_C_ops +from collections import defaultdict +from enum import Enum + +__all__ = ['AmpScaler', 'OptimizerState'] + + +class OptimizerState(Enum): + INIT = 0 + UNSCALED = 1 + STEPPED = 2 + + +def _refresh_optimizer_state(): + return {"state": OptimizerState.INIT} + + +class AmpScaler(object): + """ + :api_attr: imperative + + AmpScaler is used for Auto-Mixed-Precision training/inferring in imperative + mode. It controls the scaling of loss, helps avoiding numerical overflow. + The object of this class has seventeen methods `scale()`, `unscale_()`, `minimize()` and `get`/`set` api of parameters. + + `scale()` is used to multiply the loss by a scale ratio. + `unscale_()` is used to unscale the gradients of parameters, multiplies the gradients of parameters by 1/(scale ratio) + `minimize()` is similar as `optimizer.minimize()`, performs parameters updating, and it will update the loss_scaling. + + Commonly, it is used together with `amp_guard` to achieve Auto-Mixed-Precision in + imperative mode. + + Args: + enable(bool, optional): Enable loss scaling or not. Default is True. + init_loss_scaling (float, optional): The initial loss scaling factor. Default is 2**15. + incr_ratio(float, optional): The multiplier to use when increasing the loss + scaling. Default is 2.0. + decr_ratio(float, optional): The less-than-one-multiplier to use when decreasing + the loss scaling. Default is 0.5. + incr_every_n_steps(int, optional): Increases loss scaling every n consecutive + steps with finite gradients. Default is 1000. + decr_every_n_nan_or_inf(int, optional): Decreases loss scaling every n + accumulated steps with nan or inf gradients. Default is 2. + use_dynamic_loss_scaling(bool, optional): Whether to use dynamic loss scaling. If False, fixed loss_scaling is used. If True, the loss scaling is updated dynamicly. Default is True. + Returns: + An AmpScaler object. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32') + with fluid.dygraph.guard(): + model = fluid.dygraph.Conv2D(3, 2, 3) + optimizer = fluid.optimizer.SGDOptimizer( + learning_rate=0.01, parameter_list=model.parameters()) + scaler = fluid.dygraph.AmpScaler(init_loss_scaling=1024) + data = fluid.dygraph.to_variable(data) + with fluid.dygraph.amp_guard(): + conv = model(data) + loss = fluid.layers.reduce_mean(conv) + scaled = scaler.scale(loss) + scaled.backward() + scaler.minimize(optimizer, scaled) + """ + + @dygraph_only + def __init__(self, + enable=True, + init_loss_scaling=2.**15, + incr_ratio=2.0, + decr_ratio=0.5, + incr_every_n_steps=1000, + decr_every_n_nan_or_inf=1, + use_dynamic_loss_scaling=True): + + tracer = _dygraph_tracer() + if not tracer: + raise ValueError( + "current_tracer is None, maybe it is not in imperative mode.") + + if enable and not (tracer._expected_place.is_gpu_place() + or tracer._expected_place.is_xpu_place() + or tracer._expected_place.is_mlu_place() + or tracer._expected_place.is_npu_place() + or tracer._expected_place.is_custom_place()): + warnings.warn( + 'AmpScaler can only be enabled on CUDAPlace, XPUPlace, MLUPlace, NPUPlace and CustomPlace, current place is %s, so it makes no effect.' + % tracer._expected_place) + enable = False + + self._enable = enable + + if self._enable: + assert incr_ratio > 1.0, "The incr_ratio must be > 1.0." + assert decr_ratio < 1.0, "The decr_ratio must be < 1.0." + + self._init_loss_scaling = init_loss_scaling + self._incr_ratio = incr_ratio + self._decr_ratio = decr_ratio + self._incr_every_n_steps = incr_every_n_steps + self._decr_every_n_nan_or_inf = decr_every_n_nan_or_inf + self._incr_count = 0 + self._decr_count = 0 + self._use_dynamic_loss_scaling = use_dynamic_loss_scaling + + self._found_inf = to_variable(np.array([0]).astype(np.bool_)) + self._temp_found_inf_fp16 = to_variable( + np.array([0]).astype(np.bool_)) + self._temp_found_inf_fp32 = to_variable( + np.array([0]).astype(np.bool_)) + self._scale = to_variable( + np.array([self._init_loss_scaling]).astype(np.float32)) + self._cache_founf_inf = None + self._optimizer_states = defaultdict(_refresh_optimizer_state) + + def scale(self, var): + """ + Multiplies a variable(Tensor) by the scale factor and returns scaled outputs. + If this instance of :class:`AmpScaler` is not enabled, output are returned unmodified. + + Args: + var (Variable): The variable to scale. + Returns: + The scaled variable or original variable. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32') + with fluid.dygraph.guard(): + model = fluid.dygraph.Conv2D(3, 2, 3) + optimizer = fluid.optimizer.SGDOptimizer( + learning_rate=0.01, parameter_list=model.parameters()) + scaler = fluid.dygraph.AmpScaler(init_loss_scaling=1024) + data = fluid.dygraph.to_variable(data) + with fluid.dygraph.amp_guard(): + conv = model(data) + loss = fluid.layers.reduce_mean(conv) + scaled = scaler.scale(loss) + scaled.backward() + scaler.minimize(optimizer, scaled) + """ + check_type(var, "var", core.VarBase, 'AmpScaler.scale()') + + if not self._enable: + return var + + return var * self._scale + + def minimize(self, optimizer, *args, **kwargs): + """ + This function is similar as `Optimizer.minimize()`, which performs parameters updating. + + If the scaled gradients of parameters contains NAN or INF, the parameters updating is skipped. + Otherwise, if `unscale_()` has not been called, it first unscales the scaled gradients of parameters, then updates the parameters. + + Finally, the loss scaling ratio is updated. + + Args: + optimizer(Optimizer): The optimizer used to update parameters. + args: Arguments, which will be forward to `optimizer.minimize()`. + kwargs: Keyword arguments, which will be forward to `Optimizer.minimize()`. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32') + with fluid.dygraph.guard(): + model = fluid.dygraph.Conv2D(3, 2, 3) + optimizer = fluid.optimizer.SGDOptimizer( + learning_rate=0.01, parameter_list=model.parameters()) + scaler = fluid.dygraph.AmpScaler(init_loss_scaling=1024) + data = fluid.dygraph.to_variable(data) + with fluid.dygraph.amp_guard(): + conv = model(data) + loss = fluid.layers.reduce_mean(conv) + scaled = scaler.scale(loss) + scaled.backward() + scaler.minimize(optimizer, scaled) + """ + if not self._enable: + return optimizer.minimize(*args, **kwargs) + + optimizer_state = self._optimizer_states[id(optimizer)] + + # unscale the grad + if optimizer_state["state"] is OptimizerState.INIT: + self._unscale(optimizer) + + optimize_ops, params_grads = (None, None) + + if self._found_inf: + self._cache_founf_inf = True + else: + optimize_ops, params_grads = optimizer.minimize(*args, **kwargs) + self._cache_founf_inf = False + + if self._use_dynamic_loss_scaling: + # uopdate the scale + self._update() + + self._optimizer_states = defaultdict(_refresh_optimizer_state) + + return optimize_ops, params_grads + + def _unscale(self, optimizer): + """ + Unscale the gradients of parameters, multiplies the gradients of parameters by 1/(loss scaling ratio). + If this instance of :class:`GradScaler` is not enabled, output are returned unmodified. + Args: + optimizer(Optimizer): The optimizer used to update parameters. + Returns: + The unscaled parameters or original parameters. + """ + if not self._enable: + return + + optimizer_state = self._optimizer_states[id(optimizer)] + + if optimizer_state["state"] is OptimizerState.UNSCALED: + raise RuntimeError( + "unscale_() has already been called on this optimizer since the last update()." + ) + elif optimizer_state["state"] is OptimizerState.STEPPED: + raise RuntimeError("unscale_() is being called after step().") + + if getattr(optimizer, '_param_groups', None) and isinstance( + optimizer._param_groups[0], dict): + param_grads = [] + param_grads_fp16 = [] + param_grads_fp32 = [] + for group in optimizer._param_groups: + for param in group['params']: + if param._grad_ivar() is not None: + param_grads.append(param._grad_ivar()) + if param._grad_ivar( + ).dtype == core.VarDesc.VarType.FP16: + param_grads_fp16.append(param._grad_ivar()) + else: + param_grads_fp32.append(param._grad_ivar()) + else: + param_grads = [ + param._grad_ivar() for param in optimizer._parameter_list + if param._grad_ivar() is not None + ] + param_grads_fp16 = [ + param for param in param_grads + if param.dtype == core.VarDesc.VarType.FP16 + ] + param_grads_fp32 = [ + param for param in param_grads + if param.dtype == core.VarDesc.VarType.FP32 + ] + if core.is_compiled_with_npu(): + float_status = _legacy_C_ops.alloc_float_status() + _legacy_C_ops.clear_float_status(float_status, float_status) + + if len(param_grads_fp16): + _legacy_C_ops.check_finite_and_unscale( + param_grads_fp16, self._scale, float_status, + param_grads_fp16, self._temp_found_inf_fp16) + if len(param_grads_fp32): + _legacy_C_ops.check_finite_and_unscale( + param_grads_fp32, self._scale, float_status, + param_grads_fp32, self._temp_found_inf_fp32) + else: + if len(param_grads_fp16): + _legacy_C_ops.check_finite_and_unscale( + param_grads_fp16, self._scale, param_grads_fp16, + self._temp_found_inf_fp16) + if len(param_grads_fp32): + _legacy_C_ops.check_finite_and_unscale( + param_grads_fp32, self._scale, param_grads_fp32, + self._temp_found_inf_fp32) + + self._found_inf = self._temp_found_inf_fp16 or self._temp_found_inf_fp32 + + optimizer_state["state"] = OptimizerState.UNSCALED + + def _update(self): + """ + Updates the loss_scaling. + """ + if not self._enable: + return + + if self._cache_founf_inf: + self._incr_count = 0 + self._decr_count = self._decr_count + 1 + if self._decr_count == self._decr_every_n_nan_or_inf: + print( + 'Found inf or nan, current scale is: {}, decrease to: {}*{}' + .format(float(self._scale), float(self._scale), + float(self._decr_ratio))) + self._scale = self._scale * self._decr_ratio + self._decr_count = 0 + else: + self._decr_count = 0 + self._incr_count = self._incr_count + 1 + if self._incr_count == self._incr_every_n_steps: + self._scale = self._scale * self._incr_ratio + self._incr_count = 0 + + return + + def is_enable(self): + """ + Enable loss scaling or not. + + Returns: + bool: enable loss scaling return True else return False. + """ + return self._enable + + def is_use_dynamic_loss_scaling(self): + """ + Whether to use dynamic loss scaling. + + Returns: + bool: if fixed loss_scaling is used return False, if the loss scaling is updated dynamicly return true. + """ + return self._use_dynamic_loss_scaling + + def get_init_loss_scaling(self): + """ + Return the initial loss scaling factor. + + Reurns: + float: the initial loss scaling factor. + """ + return self._init_loss_scaling + + def set_init_loss_scaling(self, new_init_loss_scaling): + """ + Set the initial loss scaling factor by `new_init_loss_scaling`. + + Args: + new_init_loss_scaling(int): The new_init_loss_scaling used to update initial loss scaling factor.s + """ + self._init_loss_scaling = new_init_loss_scaling + self._scale = to_variable( + np.array([self._init_loss_scaling]).astype(np.float32)) + + def get_incr_ratio(self): + """ + Return the multiplier to use when increasing the loss scaling. + + Reurns: + float: the multiplier to use when increasing the loss scaling. + """ + return self._incr_ratio + + def set_incr_ratio(self, new_incr_ratio): + """ + Set the multiplier to use when increasing the loss scaling by `new_incr_ratio`, `new_incr_ratio` should > 1.0. + + Args: + new_incr_ratio(float): The new_incr_ratio used to update the multiplier to use when increasing the loss scaling. + """ + assert new_incr_ratio > 1.0, "The new_incr_ratio must be > 1.0." + self._incr_ratio = new_incr_ratio + + def get_decr_ratio(self): + """ + Get the less-than-one-multiplier to use when decreasing the loss scaling. + + Reurns: + float: the less-than-one-multiplier to use when decreasing the loss scaling. + """ + return self._decr_ratio + + def set_decr_ratio(self, new_decr_ratio): + """ + Set the less-than-one-multiplier to use when decreasing the loss scaling by `new_incr_ratio`, `new_decr_ratio` should < 1.0. + + Args: + new_decr_ratio(float): The new_decr_ratio used to update the less-than-one-multiplier to use when decreasing the loss scaling. + """ + assert new_decr_ratio < 1.0, "The new_decr_ratio must be < 1.0." + self._decr_ratio = new_decr_ratio + + def get_incr_every_n_steps(self): + """ + Return the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Reurns: + int: the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + """ + return self._incr_every_n_steps + + def set_incr_every_n_steps(self, new_incr_every_n_steps): + """ + Set the num `n` by `new_incr_every_n_steps`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + + Args: + new_incr_every_n_steps(int): The new_incr_every_n_steps used to update the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. + """ + self._incr_every_n_steps = new_incr_every_n_steps + + def get_decr_every_n_nan_or_inf(self): + """ + Return the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Reurns: + int: the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + """ + return self._decr_every_n_nan_or_inf + + def set_decr_every_n_nan_or_inf(self, new_decr_every_n_nan_or_inf): + """ + Set the num `n` by `new_decr_every_n_nan_or_inf`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + + Args: + new_decr_every_n_nan_or_inf(int): The new_decr_every_n_nan_or_inf used to update the num `n`, `n` represent decreases loss scaling every `n` accumulated steps with nan or inf gradients. + """ + self._decr_every_n_nan_or_inf = new_decr_every_n_nan_or_inf + + def state_dict(self): + """ + Returns the state of the scaler as a `dict`, If this instance is not enabled, returns an empty dict. + + Reurns: + A dict of scaler includes: + scale (tensor): The loss scaling factor. + incr_ratio(float): The multiplier to use when increasing the loss scaling. + decr_ratio(float): The less-than-one-multiplier to use when decreasing the loss scaling. + incr_every_n_steps(int): Increases loss scaling every n consecutive steps with finite gradients. + decr_every_n_nan_or_inf(int): Decreases loss scaling every n accumulated steps with nan or inf gradients. + incr_count(int): The number of recent consecutive unskipped steps. + decr_count(int): The number of recent consecutive skipped steps. + use_dynamic_loss_scaling(bool): Whether to use dynamic loss scaling. If False, fixed loss_scaling is used. If True, the loss scaling is updated dynamicly. Default is True. + """ + return { + "scale": self._scale.numpy(), + "incr_ratio": self._incr_ratio, + "decr_ratio": self._decr_ratio, + "incr_every_n_steps": self._incr_every_n_steps, + "decr_every_n_nan_or_inf": self._decr_every_n_nan_or_inf, + "incr_count": self._incr_count, + "decr_count": self._decr_count, + "use_dynamic_loss_scaling": self._use_dynamic_loss_scaling + } if self._enable else {} + + def load_state_dict(self, state_dict): + """ + Loads the scaler state. + + Args: + state_dict(dict): scaler state. Should be an object returned from a call to `AmpScaler.state_dict()`. + """ + if not self._enable: + return + + if len(state_dict) == 0: + raise RuntimeError( + "The input state dict is empty, possibly because it was saved " + "from a disabled instance of GradScaler.") + + self._init_loss_scaling = state_dict["scale"][0] + self._scale = to_variable( + np.array([self._init_loss_scaling]).astype(np.float32)) + self._incr_ratio = state_dict["incr_ratio"] + self._decr_ratio = state_dict["decr_ratio"] + self._incr_every_n_steps = state_dict["incr_every_n_steps"] + self._decr_every_n_nan_or_inf = state_dict["decr_every_n_nan_or_inf"] + self._incr_count = state_dict["incr_count"] + self._decr_count = state_dict["decr_count"] + self._use_dynamic_loss_scaling = state_dict["use_dynamic_loss_scaling"] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/base.py new file mode 100644 index 0000000000000000000000000000000000000000..cca6a5fc1c71de0e3ec17c4013a6e92be56ab69a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/base.py @@ -0,0 +1,803 @@ +# Copyright (c) 2018 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. +from ..wrapped_decorator import signature_safe_contextmanager, wrap_decorator +import decorator +import contextlib +import functools +import inspect +import sys +import numpy as np +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid.multiprocess_utils import CleanupFuncRegistrar +from .tracer import Tracer +import logging +from ..data_feeder import convert_dtype +import warnings +from ..framework import _get_paddle_place, _in_legacy_dygraph, _in_eager_without_dygraph_check +import paddle +import warnings + +__all__ = [ + 'no_grad', 'no_grad_', 'grad', 'guard', 'enable_dygraph', 'disable_dygraph', + 'enabled', 'to_variable' +] + +# Flag that indicates whether running code under `@declarative` +_in_declarative_mode_ = False + + +def in_declarative_mode(): + """ + Return a bool value that indicates whether running code under `@declarative` + + """ + return _in_declarative_mode_ + + +def declarative_unsupport_argument_warning(func_name, input_names, inputs, + support_values): + """ + Warning if inputs do not elementwisely equals to support_values. + It's a utility function for dy2static when dygraph interface have + more inputs than static interface such as paddle.grad. + + """ + for name, inp, sup in zip(input_names, inputs, support_values): + if inp != sup: + warnings.warn(f"{func_name} has unsupported parameter in jit: " + + f"{name}, jit will discard it") + + +def _switch_to_static_graph_(func): + + def __impl__(*args, **kwargs): + with framework._dygraph_guard(None): + return func(*args, **kwargs) + + return __impl__ + + +switch_to_static_graph = wrap_decorator(_switch_to_static_graph_) + + +@signature_safe_contextmanager +def _switch_declarative_mode_guard_(is_declarative=True): + + global _in_declarative_mode_ + original_val = _in_declarative_mode_ + _in_declarative_mode_ = is_declarative + yield + _in_declarative_mode_ = original_val + + +@signature_safe_contextmanager +def program_desc_tracing_guard(enable): + tracer = framework._dygraph_tracer() + if tracer: + original_val = tracer._enable_program_desc_tracing + tracer._enable_program_desc_tracing = enable + try: + yield + finally: + if tracer: + tracer._enable_program_desc_tracing = original_val + + +_functional_dygraph_context_manager = None + + +@signature_safe_contextmanager +def param_guard(parameters): + # Note: parameters is a reference of self._parameters or self._buffers + if in_declarative_mode( + ) and not framework._non_static_mode() and parameters: + origin_parameters = parameters.copy() + for name, var_base in parameters.items(): + if isinstance(var_base, list): + new_var = [_convert_into_variable(var) for var in var_base] + else: + new_var = _convert_into_variable(var_base) + parameters[name] = new_var + yield + parameters.update(origin_parameters) + else: + yield + + +def _convert_into_variable(tensor): + """ + Convert Varbase into Variable. + """ + if isinstance(tensor, (core.eager.Tensor, core.VarBase)): + # Check whether has been created before. + new_var = tensor.block._find_var_recursive(tensor.name) + if new_var is not None: + assert isinstance(new_var, framework.Variable) + # Convert ParamBase into Parameter with same attributes in dy2stat. + elif isinstance(tensor, + (framework.EagerParamBase, framework.ParamBase)): + new_var = tensor._to_static_var(to_parameter=True) + else: + # Note(Aurelius84): Convert VarBase in self._buffers into Variable with + # same attributes and set persistable=True to allow saving this var. + # Because users can create a VarBase in `__init__` like a + # `mask` Tensor or `hidden_0` in RNN layers, which is equivalent to a Parameter + # and necessary for inferring. It will be pruned if it's not necessary for inferring. + + # But if its shape is empty while created from `create_variable()`, we consider this buffer + # non-persistable. See case of `drop_state` in lstm api. + is_persistable = len(tensor.shape) > 0 + + new_var = tensor._to_static_var(to_parameter=False, + persistable=is_persistable) + return new_var + else: + return tensor + + +def enabled(): + """ + This function checks whether the program runs in dynamic graph mode or not. + You can enter dynamic graph mode with :ref:`api_fluid_dygraph_guard` api, + or enable and disable dynamic graph mode with :ref:`api_fluid_dygraph_enable_dygraph` + and :ref:`api_fluid_dygraph_disable_dygraph` api . + + **Note**: + ``fluid.dygraph.enabled`` is the alias of ``fluid.in_dygraph_mode``, and + ``fluid.in_dygraph_mode`` is recommended to use for now. + + Returns: + bool: Whether the program is running in dynamic graph mode. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + fluid.enable_dygraph() # Now we are in dygragh mode + print(fluid.dygraph.enabled()) # True + fluid.disable_dygraph() + print(fluid.dygraph.enabled()) # False + """ + # TODO(jiabin): Make this check as in_dygraph_mode when we support default eager mode. + return framework._non_static_mode() + + +def enable_dygraph(place=None): + """ + + .. note:: + Dynamic graph mode is turn ON by default since paddle 2.0.0 + + This API turn OFF static graph mode. You can turn ON static graph mode by `enable_static <./disable_dygraph_en.html>`_ . + + Parameters: + place(paddle.CPUPlace|paddle.CUDAPlace|str, optional): Place to run dynamic graph. Default: None. Which means that the running place will be + determined according to the way of paddle compilation. If ``place`` is string, It can be ``cpu``, and ``gpu:x``, where ``x`` is the + index of the GPUs. + + return: + None + + Examples: + .. code-block:: python + + import paddle + print(paddle.in_dynamic_mode()) # True, dynamic mode is turn ON by default since paddle 2.0.0 + + paddle.enable_static() + print(paddle.in_dynamic_mode()) # False, Now we are in static mode + + paddle.disable_static() + print(paddle.in_dynamic_mode()) # True, Now we are in dynamic mode + + """ + global _functional_dygraph_context_manager + if _functional_dygraph_context_manager is None: + _functional_dygraph_context_manager = guard( + place=_get_paddle_place(place)) + _functional_dygraph_context_manager.__enter__() + + # call disable_dygraph when Python exit + CleanupFuncRegistrar.register(disable_dygraph) + + +def disable_dygraph(): + """ + + .. note:: + Dynamic graph mode is turn ON by default since paddle 2.0.0 + + This API turn ON static graph mode. You can turn ON static graph mode by `disable_static <./enable_dygraph_en.html>`_ . + + return: + None + + Examples: + .. code-block:: python + + import paddle + print(paddle.in_dynamic_mode()) # True, dynamic mode is turn ON by default since paddle 2.0.0 + + paddle.enable_static() + print(paddle.in_dynamic_mode()) # False, Now we are in static mode + + paddle.disable_static() + print(paddle.in_dynamic_mode()) # True, Now we are in dynamic mode + + """ + global _functional_dygraph_context_manager + if _functional_dygraph_context_manager is not None: + _functional_dygraph_context_manager.__exit__(*sys.exc_info()) + _functional_dygraph_context_manager = None + + +@signature_safe_contextmanager +def _switch_tracer_mode_guard_(is_train=True): + tracer = framework._dygraph_tracer() + if tracer: + has_grad = tracer._has_grad + tracer._has_grad = is_train + try: + yield + finally: + tracer._has_grad = has_grad + else: + yield + + +def no_grad(func=None): + """ + :api_attr: imperative + + Create a context which disables dygraph gradient calculation. + In this mode, the result of every computation will have `stop_gradient=True`. + + Also functions as a decorator. (Make sure to instantiate without parenthesis.) + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + # use as generator + + data = np.array([[2, 3], [4, 5]]).astype('float32') + with fluid.dygraph.guard(): + l0 = fluid.Linear(2, 2) # l0.weight.gradient() is None + l1 = fluid.Linear(2, 2) + with fluid.dygraph.no_grad(): + # l1.weight.stop_gradient is False + tmp = l1.weight * 2 # tmp.stop_gradient is True + x = fluid.dygraph.to_variable(data) + y = l0(x) + tmp + o = l1(y) + o.backward() + print(tmp.gradient() is None) # True + print(l0.weight.gradient() is None) # False + + # use as decorator + + @fluid.dygraph.no_grad + def test_layer(): + with fluid.dygraph.guard(): + inp = np.ones([3, 1024], dtype='float32') + t = fluid.dygraph.base.to_variable(inp) + linear1 = fluid.Linear(1024, 4, bias_attr=False) + linear2 = fluid.Linear(4, 4) + ret = linear1(t) + dy_ret = linear2(ret) + + test_layer() + + """ + if in_declarative_mode(): + warnings.warn( + "paddle.no_grad is only supported for inference model, and not supported for training under @to_static." + ) + if func is None: + return _switch_tracer_mode_guard_(is_train=False) + else: + + @decorator.decorator + def __impl__(func, *args, **kwargs): + with _switch_tracer_mode_guard_(is_train=False): + return func(*args, **kwargs) + + return __impl__(func) + + +class no_grad_: + """ + :api_attr: imperative + + Create a context which disables dygraph gradient calculation. + In this mode, the result of every computation will have `stop_gradient` set + to `True`. + + Also functions as a decorator. (Make sure to use an instance.) + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + # use as generator + + data = np.array([[2, 3], [4, 5]]).astype('float32') + l0 = paddle.nn.Linear(2, 2) # l0.weight.gradient() is None + l1 = paddle.nn.Linear(2, 2) + with paddle.no_grad(): + # l1.weight.stop_gradient is False + tmp = l1.weight * 2 # tmp.stop_gradient is True + x = paddle.to_tensor(data) + y = l0(x) + tmp + o = l1(y) + o.backward() + print(tmp.gradient() is None) # True + print(l0.weight.gradient() is None) # False + + # use as decorator + + @paddle.no_grad() + def test_layer(): + inp = np.ones([3, 1024], dtype='float32') + t = paddle.to_tensor(inp) + linear1 = paddle.nn.Linear(1024, 4, bias_attr=False) + linear2 = paddle.nn.Linear(4, 4) + ret = linear1(t) + dy_ret = linear2(ret) + + test_layer() + """ + + def __call__(self, func): + + @decorator.decorator + def _decorate_function(func, *args, **kwargs): + with self: + return func(*args, **kwargs) + + @decorator.decorator + def _decorate_generator(func, *args, **kwargs): + gen = func(*args, **kwargs) + with self: + for x in gen: + yield x + + if inspect.isgeneratorfunction(func): + return _decorate_generator(func) + else: + return _decorate_function(func) + + def __enter__(self): + tracer = framework._dygraph_tracer() + if tracer: + self.orig = tracer._has_grad + tracer._has_grad = False + + def __exit__(self, *args): + tracer = framework._dygraph_tracer() + if tracer: + tracer._has_grad = self.orig + + +@signature_safe_contextmanager +def guard(place=None): + """ + :api_attr: imperative + + This context will create a dygraph context for dygraph to run, using python ``with`` statement. + + Parameters: + place(fluid.CPUPlace| fluid.CUDAPlace|str, optional): Place to execute dygraph. + If None, the running place will be determined according to the way of paddle compilation. + If ``place`` is string, It can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the + index of the GPUs or XPUs. Default: None + + return: + None + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + with fluid.dygraph.guard(): + inp = np.ones([3, 1024], dtype='float32') + t = fluid.dygraph.base.to_variable(inp) + linear1 = fluid.Linear(1024, 4, bias_attr=False) + linear2 = fluid.Linear(4, 4) + ret = linear1(t) + dy_ret = linear2(ret) + + """ + train = framework.Program() + startup = framework.Program() + tracer = Tracer() + VarBase = core.VarBase + + if place is not None: + expected_place = _get_paddle_place(place) + else: + expected_place = framework._current_expected_place() + + with framework.program_guard(train, startup): + with framework.unique_name.guard(): + with framework._dygraph_guard(tracer): + with framework._dygraph_place_guard(expected_place): + yield + + +@framework.non_static_only +def grad(outputs, + inputs, + grad_outputs=None, + retain_graph=None, + create_graph=False, + only_inputs=True, + allow_unused=False, + no_grad_vars=None): + ''' + .. note:: + **This API is ONLY available in imperative mode.** + + This API computes the sum of gradients of `outputs` with respect to each `inputs` . + + Parameters: + outputs (Tensor|list(Tensor)|tuple(Tensor)): the output Tensor or + Tensor list/tuple of the graph to compute gradients. + inputs (Tensor|list(Tensor)|tuple(Tensor)): the input Tensor or + Tensor list/tuple of the graph to compute gradients. The returned + values of this API are the gradients of `inputs` . + grad_outputs (Tensor|list(Tensor|None)|tuple(Tensor|None), optional): + initial gradient values of `outputs` . If `grad_outputs` is None, + the initial gradient values of `outputs` would be Tensors filled with 1; + if `grad_outputs` is not None, it must have the same length as `outputs` , + and in this case, the initial gradient value of the i-th `outputs` would + be: (1) a Tensor filled with 1 when the i-th element of `grad_outputs` + is None; (2) the i-th element of `grad_outputs` when the i-th element of + `grad_outputs` is a Tensor. Default None. + retain_graph (bool, optional): whether to retain the forward graph which + is used to calculate the gradient. When it is True, the graph would + be retained, in which way users can calculate backward twice for the + same graph. When it is False, the graph would be freed. Default None, + which means it is equal to `create_graph` . + create_graph (bool, optional): whether to create the gradient graphs of + the computing process. When it is True, higher order derivatives are + supported to compute; when it is False, the gradient graphs of the + computing process would be discarded. Default False. + only_inputs (bool, optional): whether to only compute the gradients of + `inputs` . If it is False, the gradients of all remaining leaf + Tensors in the graph would be also computed and accumulated. + If it is True, only the gradients of `inputs` would be computed. + Default True. only_inputs=False is under development, and it is + not supported yet. + allow_unused (bool, optional): whether to raise error or return None if some + Tensors of `inputs` are unreachable in the graph. If some Tensors of + `inputs` are unreachable in the graph (i.e., their gradients are None), + error would be raised if allow_unused=False, or None would be returned as + their gradients if allow_unused=True. Default False. + no_grad_vars (Tensor|list(Tensor)|tuple(Tensor)|set(Tensor), optional): + the Tensors whose gradients are not needed to compute. Default None. + + Returns: + list: a list of Tensors, whose length is the same as the Tensor number + inside `inputs`, and the i-th returned Tensor is the sum of gradients of + `outputs` with respect to the i-th `inputs`. + + Examples: + .. code-block:: python + :name: code-example-1 + + import paddle + + def test_dygraph_grad(create_graph): + x = paddle.ones(shape=[1], dtype='float32') + x.stop_gradient = False + y = x * x + + # Since y = x * x, dx = 2 * x + dx = paddle.grad( + outputs=[y], + inputs=[x], + create_graph=create_graph, + retain_graph=True)[0] + + z = y + dx + + # If create_graph = False, the gradient of dx + # would not be backpropagated. Therefore, + # z = x * x + dx, and x.gradient() = 2 * x = 2.0 + + # If create_graph = True, the gradient of dx + # would be backpropagated. Therefore, + # z = x * x + dx = x * x + 2 * x, and + # x.gradient() = 2 * x + 2 = 4.0 + + z.backward() + return x.gradient() + + print(test_dygraph_grad(create_graph=False)) # [2.] + print(test_dygraph_grad(create_graph=True)) # [4.] + + .. code-block:: python + :name: code-example-2 + + import paddle + + def test_dygraph_grad(grad_outputs=None): + x = paddle.to_tensor(2.0) + x.stop_gradient = False + + y1 = x * x + y2 = x * 3 + + # If grad_outputs=None, dy1 = [1], dy2 = [1]. + # If grad_outputs=[g1, g2], then: + # - dy1 = [1] if g1 is None else g1 + # - dy2 = [1] if g2 is None else g2 + + # Since y1 = x * x, dx = 2 * x * dy1. + # Since y2 = x * 3, dx = 3 * dy2. + # Therefore, the final result would be: + # dx = 2 * x * dy1 + 3 * dy2 = 4 * dy1 + 3 * dy2. + + dx = paddle.grad( + outputs=[y1, y2], + inputs=[x], + grad_outputs=grad_outputs)[0] + + return dx.numpy() + + grad_value = paddle.to_tensor(4.0) + # dy1 = [1], dy2 = [1] + print(test_dygraph_grad(None)) # [7.] + + # dy1 = [1], dy2 = [4] + print(test_dygraph_grad([None, grad_value])) # [16.] + + # dy1 = [4], dy2 = [1] + print(test_dygraph_grad([grad_value, None])) # [19.] + + # dy1 = [3], dy2 = [4] + grad_y1 = paddle.to_tensor(3.0) + print(test_dygraph_grad([grad_y1, grad_value])) # [24.] + ''' + if in_declarative_mode(): + # In dy2static context, we call static interface `gradients` + # to calculate grads. + from paddle.static import gradients + declarative_unsupport_argument_warning( + "paddle.grad", + ["retain_graph", "create_grad", "only_inputs", "allow_unused"], + [retain_graph, create_graph, only_inputs, allow_unused], + [None, False, True, False]) + return gradients(outputs, inputs, grad_outputs, no_grad_vars) + + def check_in_out(in_out_list, name): + assert in_out_list is not None, "{} should not be None".format(name) + + if isinstance(in_out_list, (list, tuple)): + assert len(in_out_list) > 0, "{} cannot be empty".format(name) + for each_var in in_out_list: + if _in_eager_without_dygraph_check(): + assert isinstance( + each_var, core.eager.Tensor + ), "Elements of {} must be Tensor".format(name) + else: + assert isinstance( + each_var, + core.VarBase), "Elements of {} must be Variable".format( + name) + return in_out_list + else: + if _in_eager_without_dygraph_check(): + assert isinstance( + in_out_list, core.eager.Tensor + ), "{} must be Tensor or list of Tensor".format(name) + else: + assert isinstance( + in_out_list, core.VarBase + ), "{} must be Variable or list of Variable".format(name) + return [in_out_list] + + outputs = check_in_out(outputs, 'outputs') + inputs = check_in_out(inputs, 'inputs') + + if grad_outputs is not None: + if not isinstance(grad_outputs, (list, tuple)): + grad_outputs = [grad_outputs] + + for each_var in grad_outputs: + if each_var is not None: + if _in_eager_without_dygraph_check(): + assert isinstance( + each_var, core.eager.Tensor + ), "grad_outputs must be None, a Variable or a list containing None or Variables" + else: + assert isinstance( + each_var, core.VarBase + ), "grad_outputs must be None, a Variable or a list containing None or Variables" + else: + grad_outputs = [] + + if len(grad_outputs) > 0: + assert len(grad_outputs) == len( + outputs), "The length of grad_outputs must be equal to outputs" + + if no_grad_vars is None: + no_grad_vars = [] + elif isinstance(no_grad_vars, (core.VarBase, core.eager.Tensor)): + no_grad_vars = [no_grad_vars] + elif isinstance(no_grad_vars, core.eager.Tensor): + no_grad_vars = [no_grad_vars] + elif isinstance(no_grad_vars, (list, tuple, set)): + no_grad_vars = list(no_grad_vars) + for var in no_grad_vars: + if _in_eager_without_dygraph_check(): + assert isinstance( + var, + core.eager.Tensor), "no_grad_vars can only contains Tensor" + else: + assert isinstance( + var, + core.VarBase), "no_grad_vars can only contains Variable" + else: + if _in_eager_without_dygraph_check(): + raise AssertionError( + "no_grad_vars must be None, Tensor or list/tuple/set of Tensors" + ) + else: + raise AssertionError( + "no_grad_vars must be None, Variable or list/tuple/set of Variables" + ) + + assert isinstance(create_graph, bool), "create_graph must be True or False" + + if retain_graph is None: + retain_graph = create_graph + + assert isinstance(retain_graph, + bool), "retain_graph must be None, True or False" + + assert isinstance(allow_unused, bool), "allow_unused must be True or False" + + assert isinstance(only_inputs, bool), "only_inputs must be True or False" + assert only_inputs, "only_inputs=False is not supported yet" + + if _in_eager_without_dygraph_check(): + return core.eager.run_partial_grad(outputs, inputs, grad_outputs, + retain_graph, create_graph, + only_inputs, allow_unused, + no_grad_vars) + else: + place = core.Place() + place.set_place(framework._current_expected_place()) + return core.dygraph_partial_grad(inputs, outputs, grad_outputs, + no_grad_vars, place, create_graph, + retain_graph, allow_unused, + only_inputs) + + +@framework.dygraph_only +def to_variable(value, name=None, zero_copy=None, dtype=None): + r""" + :api_attr: imperative + + The API will create a ``Variable`` object from + tuple, list, numpy\.ndarray or Variable object. + + Parameters: + value(tuple|list|ndarray|Variable|Tensor): Initial data. + Can be a list, tuple, NumPy ndarray, Variable, Tensor. + The shape can be multi-dimensional. The data type is one of + numpy\.{float16, float32, float64, int16, int32, int64, + uint8, uint16, complex64, complex128}. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` . + zero_copy(bool, optional): Whether to share memory with the input numpy + array. This parameter only works with CPUPlace and will be set to + True when it is None. Default: None. (Note: zero_copy is discarded temporally for some reason.) + dtype(str, optional): The desired data type of returned ``Variable`` . + Can be 'bool' , 'float16' , 'float32' , 'float64' , 'int8' , 'int16' , + 'int32' , 'int64' , 'uint8' . Default: None. + + Returns: + Variable : If ``value`` is a tuple/list/numpy\.ndarray object, + return ``Tensor`` created from the corresponding numpy\.ndarray object, which has + same data type and shape with ``value``. + + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + with fluid.dygraph.guard(fluid.CPUPlace()): + x = np.ones([2, 2], np.float32) + y = fluid.dygraph.to_variable(x, zero_copy=False) + x[0][0] = -1 + y[0][0].numpy() # array([1.], dtype=float32) + y = fluid.dygraph.to_variable(x) + x[0][0] = 0 + y[0][0].numpy() # array([0.], dtype=float32) + c = np.array([2+1j, 2]) + z = fluid.dygraph.to_variable(c) + z.numpy() # array([2.+1.j, 2.+0.j]) + z.dtype # 'complex128' + + y = fluid.dygraph.to_variable([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + y.shape # [3L, 2L] + + y = fluid.dygraph.to_variable(((0.1, 1.2), (2.2, 3.1), (4.9, 5.2)), dtype='int32') + y.shape # [3L, 2L] + + """ + support_type = (list, tuple, np.ndarray, core.eager.Tensor, core.VarBase, + framework.Variable, core.Tensor, core.LoDTensor) + if not isinstance(value, support_type): + raise TypeError( + "The type of 'value' in fluid.dygraph.to_variable must be %s, but received %s." + % (support_type, type(value))) + if isinstance(value, (core.eager.Tensor, core.VarBase, framework.Variable)): + return value + elif isinstance(value, (core.Tensor, core.LoDTensor)): + return core.VarBase(value) + else: + if isinstance(framework._current_expected_place(), + framework.core.CPUPlace): + #TODO(zhiqiu): we found two problems when enable zero_copy on CPUPlace. + # (1): eigen requires 16-bytes alignments, but the data of numpy array may not statisfy. + # Details: https://eigen.tuxfamily.org/dox/group__TopicUnalignedArrayAssert.html + # (2): when used in flask framework, it may result in hang. + # Details: https://github.com/PaddlePaddle/Paddle/issues/26635 + # So, we temporally diable the zero_copy strategy. + if zero_copy == True: + warnings.warn( + "Currently, zero_copy is not supported, and it will be discarded." + ) + zero_copy = False + else: + assert not zero_copy, "zero_copy mode can only be used with CPUPlace" + + if not isinstance(value, np.ndarray): + value = np.array(value) + + if dtype is not None: + dtype = convert_dtype(dtype) + if value.dtype != dtype: + value = value.astype(dtype) + + if _in_eager_without_dygraph_check(): + return core.eager.Tensor(value, framework._current_expected_place(), + False, zero_copy, name if name else None, + True) + else: + py_var = core.VarBase(value=value, + place=framework._current_expected_place(), + persistable=False, + zero_copy=zero_copy, + name=name if name else '') + return py_var diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/checkpoint.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe5d236a58e5c9c7f817e48d08d5cf9d833ca39 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/checkpoint.py @@ -0,0 +1,295 @@ +# 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. + +from __future__ import print_function + +import os +import collections +import functools +from ..framework import Variable, default_main_program, _non_static_mode, dygraph_only, Parameter, ParamBase, _varbase_creator, _dygraph_tracer, EagerParamBase +import pickle +from . import learning_rate_scheduler +import warnings +from .. import core +from .base import guard +from paddle.fluid.dygraph.jit import _SaveLoadConfig +from paddle.fluid.dygraph.io import _construct_program_holders, _construct_params_and_buffers + +__all__ = [ + 'save_dygraph', + 'load_dygraph', +] + + +def _parse_load_config(configs): + supported_configs = ['model_filename', 'params_filename', 'keep_name_table'] + + # input check + for key in configs: + if key not in supported_configs: + raise ValueError( + "The additional config (%s) of `paddle.fluid.load_dygraph` is not supported." + % (key)) + + # construct inner config + inner_config = _SaveLoadConfig() + inner_config.model_filename = configs.get('model_filename', None) + inner_config.params_filename = configs.get('params_filename', None) + inner_config.keep_name_table = configs.get('keep_name_table', None) + + return inner_config + + +@dygraph_only +def save_dygraph(state_dict, model_path): + ''' + :api_attr: imperative + + Save Layer's state_dict to disk. This will generate a file with suffix ".pdparams" + + The state_dict is get from Layers.state_dict function + + Args: + state_dict(dict) : The state dict to be saved. + model_path(str) : the file prefix to save the state_dict. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + + state_dict = emb.state_dict() + fluid.save_dygraph( state_dict, "paddle_dy") + + adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000), + parameter_list = emb.parameters() ) + + state_dict = adam.state_dict() + fluid.save_dygraph( state_dict, "paddle_dy") + + ''' + + base_name = os.path.basename(model_path) + assert base_name != "", "The input model_path MUST be format of dirname/filename [dirname\\filename in Windows system], but received filename is empty string." + + suffix = ".pdparams" + assert len(state_dict) > 0, "state_dict is empty, no need to save" + + param_num = 0 + for k, v in state_dict.items(): + if isinstance(v, (ParamBase, EagerParamBase)): + param_num += 1 + + if param_num == 0: + suffix = ".pdopt" + + model_dict = {} + name_table = {} + for k, v in state_dict.items(): + if isinstance(v, (Variable, core.VarBase, core.eager.Tensor)): + model_dict[k] = v.numpy() + name_table[k] = v.name + else: + model_dict[k] = v + model_dict["StructuredToParameterName@@"] = name_table + + file_name = model_path + suffix + dir_name = os.path.dirname(file_name) + if dir_name and not os.path.exists(dir_name): + os.makedirs(dir_name) + + with open(file_name, 'wb') as f: + pickle.dump(model_dict, f, protocol=2) + + +# NOTE(chenweihang): load_dygraph will deprecated in future, we don't +# support new loading features for it +# TODO(qingqing01): remove dygraph_only to support loading static model. +# maybe need to unify the loading interface after 2.0 API is ready. +# @dygraph_only +def load_dygraph(model_path, **configs): + ''' + :api_attr: imperative + + Load parameter state dict from disk. + + .. note:: + Due to some historical reasons, if you load ``state_dict`` from the saved + result of `paddle.static.save_inference_model`, the structured variable name + will cannot be restored. You need to set the argument `use_structured_name=False` + when using `Layer.set_state_dict` later. + + Args: + model_path(str) : The file prefix store the state_dict. + (The path should Not contain suffix '.pdparams') + **configs (dict, optional): Other load configuration options for compatibility. We do not + recommend using these configurations, if not necessary, DO NOT use them. Default None. + The following options are currently supported: + (1) model_filename (str): The inference model file name of the paddle 1.x ``save_inference_model`` + save format. Default file name is :code:`__model__` . + (2) params_filename (str): The persistable variables file name of the paddle 1.x ``save_inference_model`` + save format. No default file name, save variables separately by default. + + Returns: + state_dict(dict) : the dict store the state_dict + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.disable_static() + + emb = paddle.nn.Embedding(10, 10) + + state_dict = emb.state_dict() + fluid.save_dygraph(state_dict, "paddle_dy") + + scheduler = paddle.optimizer.lr.NoamDecay( + d_model=0.01, warmup_steps=100, verbose=True) + adam = paddle.optimizer.Adam( + learning_rate=scheduler, + parameters=emb.parameters()) + state_dict = adam.state_dict() + fluid.save_dygraph(state_dict, "paddle_dy") + + para_state_dict, opti_state_dict = fluid.load_dygraph("paddle_dy") + ''' + # deal with argument `model_path` + model_prefix = model_path + if model_prefix.endswith(".pdparams"): + model_prefix = model_prefix[:-9] + elif model_prefix.endswith(".pdopt"): + model_prefix = model_prefix[:-6] + + para_dict = None + opti_dict = None + params_file_path = model_prefix + ".pdparams" + opti_file_path = model_prefix + ".pdopt" + + # deal with argument `config` + config = _parse_load_config(configs) + + if os.path.exists(params_file_path) or os.path.exists(opti_file_path): + # Load state dict by `save_dygraph` save format + para_dict = {} + if os.path.exists(params_file_path): + with open(params_file_path, 'rb') as f: + para_dict = pickle.load(f, encoding='latin1') + + if not config.keep_name_table and "StructuredToParameterName@@" in para_dict: + del para_dict["StructuredToParameterName@@"] + + if os.path.exists(opti_file_path): + with open(opti_file_path, 'rb') as f: + opti_dict = pickle.load(f, encoding='latin1') + else: + # check model path + if not os.path.isdir(model_prefix): + raise ValueError("Model saved directory '%s' is not exists." % + model_prefix) + + # check whether model file exists + if config.model_filename is None: + model_filename = '__model__' + else: + model_filename = config.model_filename + model_file_path = os.path.join(model_path, model_filename) + + if os.path.exists(model_file_path): + # Load state dict by `jit.save/io.save_inference_model` save format + # NOTE(chenweihang): [ Compatibility of save_inference_model save format ] + # The model saved by `save_inference_model` does not completely correspond to + # the information required by the `state_dict` under the dygraph. + # `save_inference_model` not save structured name, we need to remind + # the user to configure the `use_structured_name` argument when `set_state_dict` + # NOTE(chenweihang): `jit.save` doesn't save optimizer state + + # 1. load program desc & construct _ProgramHolder + programs = _construct_program_holders(model_path, + config.model_filename) + + # 2. load layer parameters & buffers + # NOTE: using fluid.dygraph.guard() here will cause import error in py2 + with guard(): + persistable_var_dict = _construct_params_and_buffers( + model_prefix, + programs, + config.params_filename, + append_suffix=False) + + # 3. construct state_dict + para_dict = dict() + for var_name in persistable_var_dict: + para_dict[var_name] = persistable_var_dict[var_name].numpy() + + # if *.info exists, we can recover structured_name + var_info_filename = str(config.params_filename) + ".info" + var_info_path = os.path.join(model_prefix, var_info_filename) + if os.path.exists(var_info_path): + with open(var_info_path, 'rb') as f: + extra_var_info = pickle.load(f) + structured_para_dict = dict() + for var_name in para_dict: + structured_name = extra_var_info[var_name].get( + 'structured_name', None) + assert structured_name is not None, "Cannot find saved variable (%s)'s structured name in saved model." % var_name + structured_para_dict[structured_name] = para_dict[ + var_name] + para_dict = structured_para_dict + else: + # load state dict by `io.save_params/persistables` save format + # TODO(chenweihang): [ Now only supports loading parameters separately ] + # If users save all parameters as one file, the [ variable.name -> variable ] + # mapping info will lost, so users need to give variable list, but users build + # variable list in dygraph mode is difficult, we recommend users to use + # paddle.static.load_program_state in this case + + # Try to load all the files in the directory in VarBase format, + # the file name is used as the name of VarBase + load_var_list = [] + + # 1. load file names + var_name_list = [] + for root, _, files in os.walk(model_path): + for filename in files: + file_path = os.path.join(root, filename) + tmp_var_name = os.path.relpath(file_path, model_path) + var_name = tmp_var_name.replace("\\", "/") + var_name_list.append(var_name) + + # 2. create and load VarBase + with guard(): + for name in var_name_list: + new_var = _varbase_creator(name=name, persistable=True) + _dygraph_tracer().trace_op( + type='load', + inputs={}, + outputs={'Out': new_var}, + attrs={'file_path': os.path.join(model_path, name)}) + load_var_list.append(new_var) + + # 3. construct state_dict + para_dict = dict() + for var in load_var_list: + para_dict[var.name] = var.numpy() + + return para_dict, opti_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/container.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/container.py new file mode 100644 index 0000000000000000000000000000000000000000..854df39355748ec45c53f3e377e44dfef862ff2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/container.py @@ -0,0 +1,331 @@ +# 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. + +from collections import OrderedDict +from ..framework import Parameter +from .layers import Layer +from .base import param_guard + +__all__ = [ + 'Sequential', + 'ParameterList', + 'LayerList', +] + + +class Sequential(Layer): + """Sequential container. + Sub layers will be added to this container in the order of argument in the constructor. + The argument passed to the constructor can be iterable Layers or iterable name Layer pairs. + + Parameters: + layers(Layer|list|tuple): Layer or list/tuple of iterable name Layer pair. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + data = np.random.uniform(-1, 1, [30, 10]).astype('float32') + data = paddle.to_tensor(data) + # create Sequential with iterable Layers + model1 = paddle.nn.Sequential( + paddle.nn.Linear(10, 1), paddle.nn.Linear(1, 2) + ) + model1[0] # access the first layer + res1 = model1(data) # sequential execution + + # create Sequential with name Layer pairs + model2 = paddle.nn.Sequential( + ('l1', paddle.nn.Linear(10, 2)), + ('l2', paddle.nn.Linear(2, 3)) + ) + model2['l1'] # access l1 layer + model2.add_sublayer('l3', paddle.nn.Linear(3, 3)) # add sublayer + res2 = model2(data) # sequential execution + + """ + + def __init__(self, *layers): + super(Sequential, self).__init__() + if len(layers) > 0 and isinstance(layers[0], (list, tuple)): + for name, layer in layers: + self.add_sublayer(name, layer) + else: + for idx, layer in enumerate(layers): + self.add_sublayer(str(idx), layer) + + def __getitem__(self, name): + if isinstance(name, slice): + return self.__class__(*(list(self._sub_layers.values())[name])) + elif isinstance(name, str): + return self._sub_layers[name] + else: + if name >= len(self._sub_layers): + raise IndexError('index {} is out of range'.format(name)) + elif name < 0 and name >= -len(self._sub_layers): + name += len(self._sub_layers) + elif name < -len(self._sub_layers): + raise IndexError('index {} is out of range'.format(name)) + return list(self._sub_layers.values())[name] + + def __setitem__(self, name, layer): + assert isinstance(layer, Layer) + setattr(self, str(name), layer) + + def __delitem__(self, name): + name = str(name) + assert name in self._sub_layers + del self._sub_layers[name] + + def __len__(self): + return len(self._sub_layers) + + def forward(self, input): + for layer in self._sub_layers.values(): + input = layer(input) + return input + + +class ParameterList(Layer): + """ParameterList Container. + + This container acts like a Python list, but parameters it contains will be properly added. + + Parameters: + parameters (iterable, optional): Iterable Parameters to be added + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + class MyLayer(paddle.nn.Layer): + def __init__(self, num_stacked_param): + super(MyLayer, self).__init__() + # create ParameterList with iterable Parameters + self.params = paddle.nn.ParameterList( + [paddle.create_parameter( + shape=[2, 2], dtype='float32')] * num_stacked_param) + + def forward(self, x): + for i, p in enumerate(self.params): + tmp = self._helper.create_variable_for_type_inference('float32') + self._helper.append_op( + type="mul", + inputs={"X": x, + "Y": p}, + outputs={"Out": tmp}, + attrs={"x_num_col_dims": 1, + "y_num_col_dims": 1}) + x = tmp + return x + + data_np = np.random.uniform(-1, 1, [5, 2]).astype('float32') + x = paddle.to_tensor(data_np) + num_stacked_param = 4 + model = MyLayer(num_stacked_param) + print(len(model.params)) # 4 + res = model(x) + print(res.shape) # [5, 2] + + replaced_param = paddle.create_parameter(shape=[2, 3], dtype='float32') + model.params[num_stacked_param - 1] = replaced_param # replace last param + res = model(x) + print(res.shape) # [5, 3] + model.params.append(paddle.create_parameter(shape=[3, 4], dtype='float32')) # append param + print(len(model.params)) # 5 + res = model(x) + print(res.shape) # [5, 4] + """ + + def __init__(self, parameters=None): + super(ParameterList, self).__init__() + if parameters is not None: + for idx, param in enumerate(parameters): + assert isinstance(param, Parameter) + self.add_parameter(str(idx), param) + + def __getitem__(self, idx): + with param_guard(self._parameters): + return self._parameters[str(idx)] + + def __setitem__(self, idx, param): + assert isinstance(param, Parameter) + setattr(self, str(idx), param) + + def __len__(self): + return len(self._parameters) + + def __iter__(self): + with param_guard(self._parameters): + return iter(self._parameters.values()) + + def append(self, parameter): + """Appends a given parameter at the end of the list. + + Parameters: + parameter (Parameter): parameter to append + """ + idx = len(self._parameters) + self.add_parameter(str(idx), parameter) + return self + + +class LayerList(Layer): + """ + LayerList holds sublayers, and sublayers it contains are properly registered. + Holded sublayers can be indexed like a regular python list. + + Parameters: + sublayers (iterable of Layer, optional): sublayers to hold + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self.linears = paddle.nn.LayerList( + [paddle.nn.Linear(10, 10) for i in range(10)]) + + def forward(self, x): + # LayerList can act as an iterable, or be indexed using ints + for i, l in enumerate(self.linears): + x = self.linears[i // 2](x) + l(x) + return x + """ + + def __init__(self, sublayers=None): + super(LayerList, self).__init__() + if sublayers is not None: + for idx, layer in enumerate(sublayers): + self.add_sublayer(str(idx), layer) + + def _get_abs_idx(self, idx): + if isinstance(idx, int): + if not (-len(self) <= idx < len(self)): + raise IndexError( + 'index {} is out of range, should be an integer in range [{}, {})' + .format(idx, -len(self), len(self))) + if idx < 0: + idx += len(self) + return idx + + def __getitem__(self, idx): + if isinstance(idx, slice): + return self.__class__(list(self._sub_layers.values())[idx]) + else: + idx = self._get_abs_idx(idx) + return self._sub_layers[str(idx)] + + def __setitem__(self, idx, sublayer): + idx = self._get_abs_idx(idx) + return setattr(self, str(idx), sublayer) + + def __delitem__(self, idx): + if isinstance(idx, slice): + for k in range(len(self._sub_layers))[idx]: + delattr(self, str(k)) + else: + idx = self._get_abs_idx(idx) + delattr(self, str(idx)) + str_indices = [str(i) for i in range(len(self._sub_layers))] + self._sub_layers = OrderedDict( + list(zip(str_indices, self._sub_layers.values()))) + + def __len__(self): + return len(self._sub_layers) + + def __iter__(self): + return iter(self._sub_layers.values()) + + def append(self, sublayer): + """ + Appends a sublayer to the end of the list. + + Parameters: + sublayer (Layer): sublayer to append + + Examples: + .. code-block:: python + + import paddle + + linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)]) + another = paddle.nn.Linear(10, 10) + linears.append(another) + print(len(linears)) # 11 + """ + self.add_sublayer(str(len(self)), sublayer) + return self + + def insert(self, index, sublayer): + """ + Insert a sublayer before a given index in the list. + + Parameters: + index (int): index to insert. + sublayer (Layer): sublayer to insert + + Examples: + .. code-block:: python + + import paddle + + linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)]) + another = paddle.nn.Linear(10, 10) + linears.insert(3, another) + print(linears[3] is another) # True + another = paddle.nn.Linear(10, 10) + linears.insert(-1, another) + print(linears[-2] is another) # True + """ + assert isinstance(index, int) and \ + -len(self._sub_layers) <= index < len(self._sub_layers), \ + "index should be an integer in range [{}, {})".format(-len(self), len(self)) + + index = self._get_abs_idx(index) + for i in range(len(self._sub_layers), index, -1): + self._sub_layers[str(i)] = self._sub_layers[str(i - 1)] + self._sub_layers[str(index)] = sublayer + + def extend(self, sublayers): + """ + Appends sublayers to the end of the list. + + Parameters: + sublayers (iterable of Layer): iterable of sublayers to append + + Examples: + .. code-block:: python + + import paddle + + linears = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(10)]) + another_list = paddle.nn.LayerList([paddle.nn.Linear(10, 10) for i in range(5)]) + linears.extend(another_list) + print(len(linears)) # 15 + print(another_list[0] is linears[10]) # True + """ + offset = len(self) + for i, sublayer in enumerate(sublayers): + idx = str(offset + i) + self.add_sublayer(idx, sublayer) + return self diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9608910ee8d6223ea8e7bab06d5db90632cc2be0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/__init__.py @@ -0,0 +1,47 @@ +# 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. + +from __future__ import print_function + +from . import ast_transformer +from .ast_transformer import * + +from . import static_analysis +from .static_analysis import * + +from . import loop_transformer +from .loop_transformer import * + +from . import variable_trans_func +from .variable_trans_func import * + +from . import program_translator +from .program_translator import * + +from . import convert_call_func +from .convert_call_func import * + +from . import convert_operators + +from . import logging_utils +from .logging_utils import * + +__all__ = [] +__all__ += ast_transformer.__all__ +__all__ += loop_transformer.__all__ +__all__ += static_analysis.__all__ +__all__ += variable_trans_func.__all__ +__all__ += program_translator.__all__ +__all__ += convert_call_func.__all__ +__all__ += logging_utils.__all__ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/assert_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/assert_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..57d952fd6bb73d66a85d7d48d4a7070da3103409 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/assert_transformer.py @@ -0,0 +1,44 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class AssertTransformer(BaseTransformer): + """ + A class transforms python assert to convert_assert. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of AssertTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_Assert(self, node): + convert_assert_node = gast.parse('_jst.Assert({test}, {msg})'.format( + test=ast_to_source_code(node.test), + msg=ast_to_source_code(node.msg) if node.msg else "")).body[0].value + + return gast.Expr(value=convert_assert_node) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ast_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ast_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..e946969f1ab8cea0239b8353e544a9bec373add9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ast_transformer.py @@ -0,0 +1,135 @@ +# 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. + +from __future__ import print_function + +# gast is a generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST). +# It provides a compatibility layer between the AST of various Python versions, +# as produced by ast.parse from the standard ast module. +# See details in https://github.com/serge-sans-paille/gast/ + +import os +from paddle.utils import gast +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.early_return_transformer import EarlyReturnTransformer +from paddle.fluid.dygraph.dygraph_to_static.assert_transformer import AssertTransformer +from paddle.fluid.dygraph.dygraph_to_static.basic_api_transformer import BasicApiTransformer +from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import BreakContinueTransformer +from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import BreakTransformOptimizer +from paddle.fluid.dygraph.dygraph_to_static.call_transformer import CallTransformer +from paddle.fluid.dygraph.dygraph_to_static.cast_transformer import CastTransformer +from paddle.fluid.dygraph.dygraph_to_static.grad_transformer import GradTransformer +from paddle.fluid.dygraph.dygraph_to_static.typehint_transformer import TypeHintTransformer +from paddle.fluid.dygraph.dygraph_to_static.ifelse_transformer import IfElseTransformer +from paddle.fluid.dygraph.dygraph_to_static.list_transformer import ListTransformer +from paddle.fluid.dygraph.dygraph_to_static.logical_transformer import LogicalTransformer +from paddle.fluid.dygraph.dygraph_to_static.loop_transformer import LoopTransformer +from paddle.fluid.dygraph.dygraph_to_static.print_transformer import PrintTransformer +from paddle.fluid.dygraph.dygraph_to_static.return_transformer import ReturnTransformer +from paddle.fluid.dygraph.dygraph_to_static.create_variable_transformer import CreateVariableTransformer +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import StaticAnalysisVisitor +from paddle.fluid.dygraph.dygraph_to_static.tensor_shape_transformer import TensorShapeTransformer +from paddle.fluid.dygraph.dygraph_to_static.decorator_transformer import DecoratorTransformer + +from paddle.fluid.dygraph.dygraph_to_static import logging_utils +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name + +__all__ = ['DygraphToStaticAst'] + + +def apply_optimization(transformers): + """ + Judge wheter to apply optimized transformation, such as BreakTransformOptimizer. + And not all optimized transformations are applied by default. It's controlled by + 'export FLAGS_optim_transformation=1' + """ + flag = str( + os.environ.get('FLAGS_optim_transformation')) in ['1', 'True', 'true'] + if flag: + transformers.insert(3, BreakTransformOptimizer) + + +class DygraphToStaticAst(BaseTransformer): + """ + Main class to transform Dygraph to Static Graph + """ + + def __init__(self): + self.translator_logger = logging_utils.TranslatorLogger() + + def get_static_ast(self, root): + # save root for some analysis may need global AST + self.root = root + self.static_analysis_visitor = StaticAnalysisVisitor(root) + self.static_analysis_root = self.static_analysis_visitor.get_node_wrapper_root( + ) + self.decorate_func_name = None + self.transfer_from_node_type(self.static_analysis_root) + return self.static_analysis_root + + def _apply(self, transformer, node_wrapper, log_level): + transformer(node_wrapper).transform() + self.translator_logger.log_transformed_code(log_level, self.root, + transformer.__name__) + + def transfer_from_node_type(self, node_wrapper): + self.translator_logger.log( + 1, "Source code: \n{}".format(ast_to_source_code(self.root))) + # Generic transformation + self.visit(node_wrapper.node) + + transformers = [ + EarlyReturnTransformer, + BasicApiTransformer, # Basic Api + TensorShapeTransformer, # Tensor.shape -> layers.shape(Tensor) + #ListTransformer, # List used in control flow + BreakContinueTransformer, # break/continue in loops + ReturnTransformer, # return in functions + LogicalTransformer, # logical and/or/not + CreateVariableTransformer, # create undefined var for if / while / for + LoopTransformer, # for/while -> while_op + IfElseTransformer, # if/else -> cond_op + AssertTransformer, # assert statement + PrintTransformer, # print statement + CallTransformer, # transform call recursively + CastTransformer, # type casting statement + #GradTransformer, # transform paddle.grad to paddle.gradients + DecoratorTransformer, # transform decorators to function call + TypeHintTransformer, # remove all typehint in gast.Name + ] + + apply_optimization(transformers) + + for index, transformer in enumerate(transformers): + self._apply(transformer, node_wrapper, log_level=index + 1) + + self.translator_logger.log_transformed_code( + logging_utils.LOG_AllTransformer, self.root, "All Transformers") + + def visit_FunctionDef(self, node): + if self.decorate_func_name is None: + self.decorate_func_name = node.name + + self.generic_visit(node) + return node + + def get_module_name(self): + """ + Return the main function name which will be used as module name + in ast_to_func. + """ + # Should consider BaseAPITransformer which add new module name in Yamei's PR. + assert self.decorate_func_name, "decorate_func_name shall not be None." + return self.decorate_func_name diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/base_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/base_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff5b522095244609c3f2a511571d22078d299cc5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/base_transformer.py @@ -0,0 +1,532 @@ +# 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. + +from paddle.utils import gast +from paddle.fluid import unique_name +from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import create_assign_node +from paddle.fluid.dygraph.dygraph_to_static.utils import ORIGI_INFO +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_INDEX_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_TUPLE_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_TUPLE_INDEX_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_VAR_LEN_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_VAR_NAME_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_ZIP_TO_LIST_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_TARGET_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_ITERATOR_PREFIX + + +class BaseTransformer(gast.NodeTransformer): + + def visit(self, node): + if not isinstance(node, gast.AST): + msg = ('Expected "gast.AST", but got "{}".').format(type(node)) + raise ValueError(msg) + origin_info = getattr(node, ORIGI_INFO, None) + + result = super(BaseTransformer, self).visit(node) + + iter_result = result + if iter_result is not node and iter_result is not None: + if not isinstance(iter_result, (list, tuple)): + iter_result = (iter_result, ) + if origin_info is not None: + for n in iter_result: + setattr(n, ORIGI_INFO, origin_info) + + return result + + +class RenameTransformer(BaseTransformer): + + def __init__(self, node): + assert isinstance( + node, gast.AST), "RenameTransformer only accepts gast.AST as input" + self.root = node + self.old_name = "" + self.new_name = "" + + def rename(self, old_name, new_name): + self.old_name = old_name + self.new_name = new_name + self.visit(self.root) + + def visit_Name(self, node): + self.generic_visit(node) + if node.id == self.old_name: + node.id = self.new_name + return node + + def visit_Attribute(self, node): + self.generic_visit(node) + attr_full_name = get_attribute_full_name(node) + if attr_full_name == self.old_name: + new_name_node = gast.parse(self.new_name).body[0].value + return new_name_node + return node + + +class NameNodeReplaceTransformer(BaseTransformer): + """ + This class replaces specified gast.Name node by replace_node. + """ + + def __init__(self, root_node, target_name, replace_node): + assert isinstance(target_name, str) + + # NOTE(liym27): + # Use gast.Name to replace gast.Name, otherwise, errors may occur. + # + # For examples: + # If using a gast.Subscript to replace gast.Name, and the original gast.Name + # is in the arguments of FunctionDef, an exception will be raised. + # + # ``` + # def func(x[i])) # x[i] can not be a argument + # # ... + # ``` + + assert isinstance(replace_node, gast.Name) + self.target_name = target_name + self.replace_node = replace_node + + self.visit(root_node) + + def visit_Name(self, node): + if node.id == self.target_name: + return self.replace_node + return node + + def visit_Nonlocal(self, node): + names = node.names + + def replace(s): + if s == self.target_name: return self.replace_node.id + return s + + node.names = list(map(replace, names)) + return node + + +class ForLoopTuplePreTransformer(BaseTransformer): + """ pre-process of for loop. + >>> for A in B: + >>> C + + will be changed into : + + >>> UUID_iterator = _jst.Indexable(B) # make iterator-only to indexable list. + >>> for UUID_target in UUID_iterator: + >>> A = _jst.Unpack(UUID_target, structure) + >>> C + + make the later loop_transform have unified type: + >>> for target in iter: + >>> body + """ + + def __init__(self, wrapper_root): + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_For(self, node): + self.generic_visit(node) + tuple_target = unique_name.generate(FOR_ITER_TARGET_PREFIX) + tuple_iterator = unique_name.generate(FOR_ITER_ITERATOR_PREFIX) + origin_tuple_node = node.target + assign_iterator_node = gast.parse( + f"{tuple_iterator} = _jst.Indexable({ast_to_source_code(node.iter).strip()})" + ).body[0] + node.target = gast.Name(id=tuple_target, + ctx=gast.Store(), + annotation=None, + type_comment=None) + node.iter = gast.Name(id=tuple_iterator, + ctx=gast.Load(), + annotation=None, + type_comment=None) + node.body[0:0] = self.tuple_to_stmts(origin_tuple_node, tuple_target) + # return a list will insert a list of node replace the original for node. + return [assign_iterator_node, node] + + def tuple_node_to_unpack_structure(self, node): + """ Create a sequence to represents the structure of nest. + For example: `a, (b,c), [d,e,f]` is represented by + `[1, [1,1], [1,1,1]]`. the `1` is just a notation. + + Specially, `a` is represented by `1`. + """ + ret = [] + if not isinstance(node, (gast.Tuple, gast.List)): + return 1 + for element in node.elts: + ret.append(self.tuple_node_to_unpack_structure(element)) + return ret + + def tuple_to_stmts(self, node, tuple_name): + structure_str = str(self.tuple_node_to_unpack_structure(node)) + node_str = ast_to_source_code(node).strip() + assign_node_str = f"{node_str} = _jst.Unpack({tuple_name}, {structure_str})" + assign_node = gast.parse(assign_node_str).body[0] + return [assign_node] + + +class ForNodeVisitor(object): + """ + This class parses python for statement, get transformed 3 statement components of for node + three key statements: + 1). init_stmts: list[node], prepare nodes of for loop, may not only one + 2). cond_stmt: node, condition node to judge whether continue loop + 3). body_stmts: list[node], updated loop body, sometimes we should change + the original statement in body, not just append new statement + + In this process, the semantics of for does not change. + + Now only can parse 3 type statements (Here var is VarBase(Tensor) or python variable): + 1). for x in range(var[*]|var.numpy()[*]) + 2). for x in var|var.numpy() + 3). for i, x enumerate(var|var.numpy()) + """ + + def __init__(self, for_node): + assert isinstance( + for_node, gast.For + ), "Input node for the initialization of ForNodeVisitor is not gast.For node." + # 1. original for node + self.node = for_node + + # 2. gast.For node main parts + self.target = for_node.target + # NOTE: type may be Node or list[Node] + self.iter_args = for_node.iter if self.is_for_iter( + ) else for_node.iter.args + self.body = for_node.body + + # 3. key shared node or names + # - x: + # - for x in range(***) + # - for x in var|var.numpy() + # - for i, x enumerate(var|var.numpy()) + self.iter_var_name = self._get_iter_var_name() + + # - created index var to slice Variable: __for_loop_var_index_0 + # - for x in var|var.numpy() + # - for i, x enumerate(var|var.numpy()) + self.iter_idx_name = unique_name.generate(FOR_ITER_INDEX_PREFIX) + + # - created shape var to build loop condition: __for_loop_var_len_0 + # - for x in var|var.numpy() + # - for i, x enumerate(var|var.numpy()) + # - for x in var + self.iter_var_len_name = unique_name.generate(FOR_ITER_VAR_LEN_PREFIX) + # - created zip to list var : __for_loop_iter_zip_0 + self.iter_zip_to_list_name = unique_name.generate( + FOR_ITER_ZIP_TO_LIST_PREFIX) + + # - var.numpy()/var + # - for x in var|var.numpy() + # - for i, x enumerate(var|var.numpy()) + self.iter_node = self._get_iter_node() + + # - enumeate i: + # - for i, x enumerate(var|var.numpy()) + self.enum_idx_name = self._get_enum_idx_name() + + # - range/enumerate args length + self.args_length = None + + def parse(self): + self._args_check() + if self.is_for_range_iter(): + return self._parse_for_range_stmts() + elif self.is_for_iter(): + return self._parse_for_stmts() + elif self.is_for_enumerate_iter(): + return self._parse_for_enumerate_stmts() + else: + return None + + def is_for_range_iter(self): + return isinstance(self.node.iter, gast.Call) and isinstance( + self.node.iter.func, + gast.Name) and self.node.iter.func.id == "range" + + def is_for_iter(self): + if isinstance(self.node.iter, + (gast.Name, gast.Attribute, gast.List, gast.Tuple)): + return True + elif isinstance(self.node.iter, gast.Call) and isinstance( + self.node.iter.func, + gast.Attribute) and self.node.iter.func.attr == 'numpy': + return True + elif isinstance(self.node.iter, gast.Subscript): + return True + else: + return False + + def is_for_enumerate_iter(self): + return isinstance(self.node.iter, gast.Call) and isinstance( + self.node.iter.func, + gast.Name) and self.node.iter.func.id == "enumerate" + + def _args_check(self): + if self.is_for_range_iter(): + self.args_length = len(self.iter_args) + assert self.args_length >= 1 and self.args_length <= 3, "range() function takes 1 to 3 arguments" + elif self.is_for_enumerate_iter(): + self.args_length = len(self.iter_args) + assert self.args_length >= 1 and self.args_length <= 2, "enumerate() function takes 1 to 2 arguments" + else: + self.args_length = None + + def _parse_for_range_stmts(self): + init_stmts = [] + init_stmts.append(self._build_index_init_node()) + + compare_node = self._build_compare_node() + step_node = self._build_step_node() + cond_stmt = self._build_cond_stmt(step_node, compare_node) + + body_stmts = self.body + body_stmts.append(self._build_index_increase_node(step_node)) + + return init_stmts, cond_stmt, body_stmts + + def _parse_for_stmts(self): + init_stmts = [] + init_stmts.extend(self._build_iter_node()) + init_stmts.append(self._build_index_init_node()) + init_stmts.append(self._build_var_len_assign_node()) + + compare_node = self._build_compare_node() + step_node = self._build_step_node() + cond_stmt = self._build_cond_stmt(step_node, compare_node) + + body_stmts = self.body + + # NOTE(liym27): Here add a gast.Assign, and the target of it is gast.Name. + # In NameNodeReplaceTransformer, using gast.Name to replace gast.Name is safe. + target_node, assign_node = self._build_assign_var_slice_node() + body_stmts[0:0] = [assign_node] + for body_node in body_stmts: + NameNodeReplaceTransformer(body_node, self.iter_var_name, + target_node) + body_stmts.append(self._build_index_increase_node(step_node)) + + return init_stmts, cond_stmt, body_stmts + + def _parse_for_enumerate_stmts(self): + init_stmts = [] + init_stmts.extend(self._build_iter_node()) + init_stmts.append(self._build_index_init_node()) + init_stmts.append(self._build_var_len_assign_node()) + init_stmts.append(self._build_enum_init_node()) + + compare_node = self._build_compare_node() + step_node = self._build_step_node() + cond_stmt = self._build_cond_stmt(step_node, compare_node) + + body_stmts = self.body + + target_node, assign_node = self._build_assign_var_slice_node() + body_stmts[0:0] = [assign_node] + for body_node in body_stmts: + NameNodeReplaceTransformer(body_node, self.iter_var_name, + target_node) + + body_stmts.append(self._build_index_increase_node(step_node)) + body_stmts.append(self._build_enum_increase_node()) + + return init_stmts, cond_stmt, body_stmts + + def _build_index_init_node(self): + if self.is_for_range_iter(): + if self.args_length == 1: + index_init_value_str = '0' + else: + index_init_value_str = ast_to_source_code( + self.iter_args[0]).strip() + + index_init_var_name = self.iter_var_name + else: + index_init_value_str = '0' + index_init_var_name = self.iter_idx_name + + index_init_node_source_str = "{target} = {value}".format( + target=index_init_var_name, value=index_init_value_str) + + index_init_node = gast.parse(index_init_node_source_str).body[0] + + return index_init_node + + def _build_var_len_assign_node(self): + # get the length of iterable variable + if isinstance(self.iter_node, gast.Call) and isinstance( + self.iter_node.func, + gast.Attribute) and self.iter_node.func.attr == 'numpy': + iter_var_name = ast_to_source_code( + self.iter_node.func.value).strip() + else: + iter_var_name = ast_to_source_code(self.iter_node).strip() + + convert_len_node_source_str = '{} = _jst.Len({})'.format( + self.iter_var_len_name, iter_var_name) + + convert_len_node = gast.parse(convert_len_node_source_str).body[0] + + return convert_len_node + + def _build_iter_node(self): + """ + Process special cases for iter_node inclue: + - Case 1 (for zip): + + - for i, val in enumerate(zip(x, y)) # original code: + + - __for_loop_iter_zip_0 = list(zip(x, y)) + - for i, val in enumerate(__for_loop_iter_zip_0) + """ + new_nodes = [] + if isinstance(self.iter_node, gast.Call) and isinstance( + self.iter_node.func, gast.Name): + if self.iter_node.func.id == 'zip': + iter_var_name = ast_to_source_code(self.iter_node).strip() + zip_to_list_str = "{target} = list({value})".format( + target=self.iter_zip_to_list_name, value=iter_var_name) + zip_to_list_node = gast.parse(zip_to_list_str).body[0] + new_nodes.append(zip_to_list_node) + + self.iter_node = gast.Name(id=self.iter_zip_to_list_name, + ctx=gast.Load(), + annotation=None, + type_comment=None) + + return new_nodes + + def _build_enum_init_node(self): + if self.is_for_enumerate_iter() and self.args_length != 1: + init_value_str = ast_to_source_code(self.iter_args[1]).strip() + else: + init_value_str = '0' + + enum_init_node_source_str = "{} = {}".format(self.enum_idx_name, + init_value_str) + enum_init_node = gast.parse(enum_init_node_source_str).body[0] + return enum_init_node + + def _build_compare_node(self): + if self.is_for_range_iter(): + compare_node = self.iter_args[ + 0] if self.args_length == 1 else self.iter_args[1] + else: + compare_node = gast.Name(id=self.iter_var_len_name, + ctx=gast.Load(), + annotation=None, + type_comment=None) + return compare_node + + def _build_step_node(self): + if self.is_for_range_iter(): + step_node = self.iter_args[ + 2] if self.args_length == 3 else gast.Constant(value=1, + kind=None) + else: + step_node = gast.Constant(value=1, kind=None) + return step_node + + def _build_cond_stmt(self, step_node, compare_node): + if not isinstance(step_node, (gast.Constant, gast.UnaryOp)): + raise NotImplementedError( + "Dynamic-to-Static only supports the step value is a constant or negative constant in 'for-range' statements, " + "such as '2', '-3'. But received: '{}'. Please fix code to be compatible with Dynamic-to-Static." + .format(ast_to_source_code(step_node).strip())) + + if isinstance(step_node, gast.UnaryOp) or step_node.value < 0: + # eg: + # range(max, min, -2) + # -> + # i > min + return gast.Compare(left=gast.Name( + id=self.iter_var_name + if self.is_for_range_iter() else self.iter_idx_name, + ctx=gast.Load(), + annotation=None, + type_comment=None), + ops=[gast.Gt()], + comparators=[compare_node]) + else: + # eg: + # range(min, max, 2) + # -> + # i < max + return gast.Compare(left=gast.Name( + id=self.iter_var_name + if self.is_for_range_iter() else self.iter_idx_name, + ctx=gast.Load(), + annotation=None, + type_comment=None), + ops=[gast.Lt()], + comparators=[compare_node]) + + def _build_index_increase_node(self, step_node): + return gast.AugAssign(target=gast.Name( + id=self.iter_var_name + if self.is_for_range_iter() else self.iter_idx_name, + ctx=gast.Store(), + annotation=None, + type_comment=None), + op=gast.Add(), + value=step_node) + + def _build_assign_var_slice_node(self): + var_slice_str = "{}[{}]".format( + ast_to_source_code(self.iter_node).strip(), self.iter_idx_name) + var_slice_node = gast.parse(var_slice_str).body[0].value + new_iter_var_name = unique_name.generate(FOR_ITER_VAR_NAME_PREFIX) + target_node, assign_node = create_assign_node(new_iter_var_name, + var_slice_node) + return target_node, assign_node + + def _build_enum_increase_node(self): + return gast.AugAssign(target=gast.Name(id=self.enum_idx_name, + ctx=gast.Store(), + annotation=None, + type_comment=None), + op=gast.Add(), + value=gast.Constant(value=1, kind=None)) + + def _get_iter_var_name(self): + if self.is_for_range_iter(): + return self.target.id + elif self.is_for_iter(): + return self.target.id + elif self.is_for_enumerate_iter(): + return self.target.elts[1].id + return None + + def _get_iter_node(self): + if self.is_for_iter(): + return self.iter_args + elif self.is_for_enumerate_iter(): + return self.iter_args[0] + return None + + def _get_enum_idx_name(self): + if self.is_for_enumerate_iter(): + return self.target.elts[0].id + return None diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/basic_api_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/basic_api_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..55afb7ae6d6de6bb4eecce60fdfa30792ae5e835 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/basic_api_transformer.py @@ -0,0 +1,195 @@ +# 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. + +import astor +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static import utils +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code + + +class BasicApiTransformer(BaseTransformer): + """ + Class to transform basic API from dygraph to static graph. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of BasicApiTransformer." + + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + self.class_node_dict = {} + + def transform(self): + to_tensor_transformer = ToTensorTransformer(self.root) + to_tensor_transformer.transform() + attribute_transformer = AttributeJstTransformer(self.root) + attribute_transformer.transform() + self.visit(self.root) + + return self.wrapper_root + + def visit_Assign(self, node): + if self._update_class_node_dict(node): + return None + + for child_node in gast.walk(node.value): + if isinstance(child_node, gast.Call): + self._visit_Call(child_node) + return node + + def visit_Expr(self, node): + value_node = node.value + for child_node in gast.walk(value_node): + if isinstance(child_node, gast.Call): + # TODO(liym27): + # Considers that a dygraph api which modifies the input or has a output. + if utils.is_dygraph_api(child_node): + return + else: + self._visit_Call(child_node) + return node + + def _visit_Call(self, node): + assert isinstance(node, gast.Call) + func_name = astor.to_source(gast.gast_to_ast(node.func)) + + if self._is_dygraph_forward(func_name): + class_node = self._get_class_node(func_name) + static_node = utils.to_static_ast(node, class_node) + return static_node + else: + return node + + def _is_dygraph_forward(self, func_id): + return func_id in self.class_node_dict + + def _get_class_node(self, func_id): + return self.class_node_dict[func_id] + + def _update_class_node_dict(self, node): + assert isinstance(node, gast.Assign) + node_value = node.value + if isinstance(node_value, gast.Call): + if is_to_variable(node_value): + return False + + if utils.is_dygraph_api(node_value): + dygraph_api = node_value.func.attr + if not utils.dygraph_class_to_static_api.get(dygraph_api): + return False + + utils.update_args_of_func(node_value, node_value, "__init__") + target_str = astor.to_source(gast.gast_to_ast(node.targets[0])) + self.class_node_dict[target_str] = node_value + return True + # TODO: node.value is not dygraph class + return False + + +class ToTensorTransformer(BaseTransformer): + """ + Class to transform paddle.to_tensor and paddle.to_variable to paddle.assign + """ + + def __init__(self, node): + assert isinstance( + node, gast.AST + ), "Input non-gast.AST node for the initialization of ToTensorTransformer." + self.root = node + + def transform(self): + self.visit(self.root) + return self.root + + def visit_Call(self, node): + assert isinstance(node, gast.Call) + if is_to_variable(node): + node = to_assign_node(node) + self.generic_visit(node) + return node + + +class AttributeJstTransformer(BaseTransformer): + """ + change some special attribute into __jst.XXX(obj, "attr_name") format. + for example: + a.size --> __jst.attr(a, "size") + + because `size` have different behavier when in dygraph / static mode + NOTE: we only deal with ctx=Load() case. + """ + + def __init__(self, node): + assert isinstance( + node, gast.AST + ), "Input non-gast.AST node for the initialization of ToTensorTransformer." + self.interested_name = set([ + 'size', + ]) + self.root = node + + def transform(self): + self.visit(self.root) + return self.root + + def visit_Attribute(self, node): + assert isinstance(node, gast.Attribute) + assert isinstance(node.attr, str) + if isinstance(node.ctx, + gast.Load) and node.attr in self.interested_name: + attr = node.attr + value = node.value + node = gast.parse("_jst.Attr({}, \"{}\")".format( + ast_to_source_code(value).strip(), attr)).body[0].value + self.generic_visit(node) + return node + + +def is_to_variable(node): + assert isinstance(node, gast.Call) + api_name = utils.ast_to_source_code(node.func).strip() + + if utils.is_dygraph_api(node): + return api_name.endswith("to_variable") + + return False + + +def to_assign_node(node): + # Transform dygraph api `fluid.dygraph.to_variable` alias `paddle.to_tensor` to static api `paddle.assign`. + # NOTE: + # 1. Api `to_variable` supports data type {float16, float32, float64, int16, int32, int64, uint8, uint16}, + # but api `assign` only supports {float32, float64, int32, int64, bool}; + # 2. If the input of api `assign` is numpy.ndarray, its size cannot be greater than 1024 * 1024. + + assert isinstance(node, gast.Call) + assign_api = gast.parse('paddle.assign').body[0].value + node.func = assign_api + + if node.args: + node.args = [node.args[0]] + node.keywords = [] + else: + for idx, kw in enumerate(node.keywords): + if kw.arg == 'value' or kw.arg == 'data': + node.keywords[idx].arg = 'x' + node.keywords = [node.keywords[idx]] + node.args = [] + break + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/break_continue_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/break_continue_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..b63fe6eea5af2c54a2cde861bff77f652d8a0d3e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/break_continue_transformer.py @@ -0,0 +1,377 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast + +from paddle.fluid import unique_name +from paddle.fluid.dygraph.dygraph_to_static.utils import index_in_list +from paddle.fluid.dygraph.dygraph_to_static.utils import BaseNodeVisitor +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import create_bool_node +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import ForNodeVisitor + +__all__ = ['BreakContinueTransformer'] + +BREAK_NAME_PREFIX = '__break' +CONTINUE_NAME_PREFIX = '__continue' + + +class ForToWhileTransformer(BaseTransformer): + """ + Transform python for loop into while loop and add condition node in the + loop test + """ + + def __init__(self, parent_node, loop_node, condition_node): + assert isinstance( + loop_node, + gast.For), "loop_node is not gast.For in ForToWhileTransformer" + self.parent_node = parent_node + self.loop_node = loop_node + self.condition_node = condition_node + + def transform(self): + if hasattr(self.parent_node, 'body'): + body_list = self.parent_node.body + i = index_in_list(body_list, self.loop_node) + if i != -1: + new_stmts = self.get_for_stmt_nodes(body_list[i]) + body_list[i:i + 1] = new_stmts + i += len(new_stmts) + return new_stmts + if hasattr(self.parent_node, 'orelse'): + body_list = self.parent_node.orelse + i = index_in_list(body_list, self.loop_node) + if i != -1: + new_stmts = self.get_for_stmt_nodes(body_list[i]) + body_list[i:i + 1] = new_stmts + i += len(new_stmts) + return new_stmts + raise ValueError( + "parent_node doesn't contain the loop_node in ForToWhileTransformer" + ) + + def get_for_stmt_nodes(self, node): + assert isinstance( + node, gast.For), "Input node is NOT gast.For in get_for_stmt_nodes" + + # 1. parse current gast.For node + current_for_node_parser = ForNodeVisitor(node) + stmts_tuple = current_for_node_parser.parse() + if stmts_tuple is None: + return [node] + init_stmts, cond_stmt, body_stmts = stmts_tuple + + # 2. append break statement + new_cond_stmt = gast.BoolOp(op=gast.And(), + values=[cond_stmt, self.condition_node]) + + # 3. construct gast.While node + while_node = gast.While(test=new_cond_stmt, + body=body_stmts, + orelse=node.orelse) + init_stmts.append(while_node) + return init_stmts + + +class BreakContinueTransformer(BaseNodeVisitor): + """ + Rewrite 'break' and 'continue' key words in a if-else python way to make + it equivalent to original control flow + + The main idea of this class is: + + 1. Map the 'break/continue' stmt with an unique boolean variable V. + + 2. Find the first ancestor block containing this 'break/continue', a + block can be a node containing stmt list. We should remove all stmts + after the 'break/continue' and set the V to True here. + + 3. Add 'if V' for stmts in ancestor blocks between the first one + (exclusive) and the ancestor loop (inclusive) + + 4. For 'break' add break into condition of the loop. For 'continue', + set continue to False at the beginning of each loop + + TODO: more details should be summarized as design document + + Note: The class is inherited from BaseNodeVisitor instead of NodeTransformer, + because ancestor nodes will be modified inplace for `Break/Continue` here. + In general, we recommend to inheriting NodeTransformer to modify node! + """ + + def __init__(self, wrapper_root): + super(BreakContinueTransformer, self).__init__() + + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_Break(self, node): + loop_node_index = _find_ancestor_loop_index(node, self.ancestor_nodes) + assert loop_node_index != -1, "SyntaxError: 'break' outside loop" + loop_node = self.ancestor_nodes[loop_node_index] + + # 1. Map the 'break/continue' stmt with an unique boolean variable V. + variable_name = unique_name.generate(BREAK_NAME_PREFIX) + + # 2. Find the first ancestor block containing this 'break/continue', a + # block can be a node containing stmt list. We should remove all stmts + # after the 'break/continue' and set the V to True here. + first_block_index = self._remove_stmts_after_break_continue( + node, variable_name, loop_node_index) + + # 3. Add 'if not V' for stmts in ancestor blocks between the first one + # (exclusive) and the ancestor loop (inclusive) + self._replace_if_stmt(loop_node_index, first_block_index, variable_name) + + # 4. For 'break' add break into condition of the loop. + assign_false_node = create_bool_node(variable_name, False) + self._add_stmt_before_cur_node(loop_node_index, assign_false_node) + + cond_var_node = gast.UnaryOp(op=gast.Not(), + operand=gast.Name(id=variable_name, + ctx=gast.Load(), + annotation=None, + type_comment=None)) + + if isinstance(loop_node, gast.While): + loop_node.test = gast.BoolOp(op=gast.And(), + values=[loop_node.test, cond_var_node]) + elif isinstance(loop_node, gast.For): + parent_node = self.ancestor_nodes[loop_node_index - 1] + for_to_while = ForToWhileTransformer(parent_node, loop_node, + cond_var_node) + for_to_while.transform() + + def visit_Continue(self, node): + loop_node_index = _find_ancestor_loop_index(node, self.ancestor_nodes) + assert loop_node_index != -1, "SyntaxError: 'continue' outside loop" + loop_node = self.ancestor_nodes[loop_node_index] + + # 1. Map the 'break/continue' stmt with an unique boolean variable V. + variable_name = unique_name.generate(CONTINUE_NAME_PREFIX) + + # 2. Find the first ancestor block containing this 'break/continue', a + # block can be a node containing stmt list. We should remove all stmts + # after the 'break/continue' and set the V to True here. + first_block_index = self._remove_stmts_after_break_continue( + node, variable_name, loop_node_index) + + # 3. Add 'if not V' for stmts in ancestor blocks between the first one + # (exclusive) and the ancestor loop (inclusive) + self._replace_if_stmt(loop_node_index, first_block_index, variable_name) + + # 4. For 'continue', set continue to False at the beginning of each loop + assign_false_node = create_bool_node(variable_name, False) + loop_node.body.insert(0, assign_false_node) + + def _remove_stmts_after_break_continue(self, break_continue_node, + break_continue_name, + loop_node_index): + for first_block_index in range( + len(self.ancestor_nodes) - 1, loop_node_index - 1, -1): + first_block = self.ancestor_nodes[first_block_index] + if hasattr(first_block, + "body") and self._replace_break_continue_in_stmt_list( + first_block.body, break_continue_node, + break_continue_name): + return first_block_index + + if hasattr(first_block, + "orelse") and self._replace_break_continue_in_stmt_list( + first_block.orelse, break_continue_node, + break_continue_name): + return first_block_index + + return first_block_index + + def _replace_if_stmt(self, loop_node_index, first_block_index, + break_continue_name): + for i in range(first_block_index - 1, loop_node_index - 1, -1): + cur_node = self.ancestor_nodes[i] + son_node = self.ancestor_nodes[i + 1] + if hasattr(cur_node, + 'body') and self._replace_after_node_to_if_in_stmt_list( + cur_node.body, son_node, break_continue_name): + continue + if hasattr( + cur_node, + 'orelse') and self._replace_after_node_to_if_in_stmt_list( + cur_node.orelse, son_node, break_continue_name): + continue + + def _replace_break_continue_in_stmt_list(self, stmt_list, + break_continue_node, + break_continue_name): + i = index_in_list(stmt_list, break_continue_node) + if i == -1: + return False + assign_true_node = create_bool_node(break_continue_name, True) + stmt_list[i:] = [assign_true_node] + return True + + def _replace_after_node_to_if_in_stmt_list(self, stmt_list, node, + break_continue_name): + i = index_in_list(stmt_list, node) + if i == -1: + return False + + if i == len(stmt_list) - 1: + # No need to add, we consider this as added successfully + return True + + if_stmt = gast.If(test=gast.UnaryOp(op=gast.Not(), + operand=gast.Name( + id=break_continue_name, + ctx=gast.Store(), + annotation=None, + type_comment=None)), + body=stmt_list[i + 1:], + orelse=[]) + stmt_list[i + 1:] = [] + stmt_list.append(if_stmt) + return True + + def _add_stmt_before_cur_node(self, cur_node_index, stmt_node): + cur_node = self.ancestor_nodes[cur_node_index] + parent_node = self.ancestor_nodes[cur_node_index - 1] + if hasattr(parent_node, + "body") and self._add_stmt_into_list_before_node( + parent_node.body, cur_node, stmt_node): + return True + if hasattr(parent_node, + "orelse") and self._add_stmt_into_list_before_node( + parent_node.orelse, cur_node, stmt_node): + return True + return False + + def _add_stmt_into_list_before_node(self, stmt_list, node, stmt_node): + i = index_in_list(stmt_list, node) + if i == -1: + return False + stmt_list.insert(i, stmt_node) + return True + + +def _find_ancestor_loop_index(node, ancestor_nodes): + for i in range(len(ancestor_nodes) - 1, -1, -1): + if isinstance(ancestor_nodes[i], (gast.For, gast.While)): + return i + return -1 + + +class BreakTransformOptimizer(BaseNodeVisitor): + """ + In specific pattern, the transformed code could be optimized by joining the + If.test with while.test. + + Currently supported pattern is: + ``` + while cond1: while cond1 and not cond2: + if cond2: ---> do_something() + break + do_something() + ``` + + See following example: + + >>> def foo(x): + ... i = paddle.to_tensor(1, dtype='int32') + ... while i < 10: + ... if x.mean() > 5: + ... break + ... x += i + ... i += 1 + ... return x + + The generated code after applying optimization will be: + ``` + def foo(x): + i = paddle.to_tensor(1, dtype='int32') + while i < 10 and not x.mean() > 5: + x += i + i += 1 + return x + ``` + It can avoid wrapping all ops after `break` statement into `cond_op` that + usually brings very heavy overhead. + """ + + def __init__(self, wrapper_root): + super(BreakTransformOptimizer, self).__init__() + + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_Break(self, node): + loop_node_index = _find_ancestor_loop_index(node, self.ancestor_nodes) + assert loop_node_index != -1, "SyntaxError: 'break' outside loop" + loop_node = self.ancestor_nodes[loop_node_index] + + if self._is_break_cond_pattern(node, loop_node): + cond_var_node = self._join_with_while_cond(node, loop_node) + + if isinstance(loop_node, gast.While): + loop_node.test = gast.BoolOp( + op=gast.And(), values=[loop_node.test, cond_var_node]) + elif isinstance(loop_node, gast.For): + parent_node = self.ancestor_nodes[loop_node_index - 1] + for_to_while = ForToWhileTransformer(parent_node, loop_node, + cond_var_node) + for_to_while.transform() + + def _is_break_cond_pattern(self, break_node, loop_node): + """ + Judge whether if match the pattern to join `If.test` with `while.test` + """ + # while/for -> if -> break + if len(self.ancestor_nodes) < 3 or self.ancestor_nodes[-3] != loop_node: + return False + + assert self.ancestor_nodes[-1] == break_node + parent_if_node = self.ancestor_nodes[-2] + + is_matched = False + if isinstance(parent_if_node, gast.If): + # gast.If only contains `break` + break_first_in_if = parent_if_node.body[0] == break_node and len( + parent_if_node.orelse) == 0 + # gast.If is first node of loop_node + if_first_in_loop = loop_node.body[0] == parent_if_node + + is_matched = if_first_in_loop and break_first_in_if + + return is_matched + + def _join_with_while_cond(self, break_node, loop_node): + """ + Join the `If.test` with `While.test` together. + """ + parent_if_node = self.ancestor_nodes[-2] + + cond_var_node = gast.UnaryOp(op=gast.Not(), operand=parent_if_node.test) + + # remove the gast.If node that contains the gast.Break. + assert loop_node.body[0] == parent_if_node + loop_node.body.pop(0) + + return cond_var_node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/call_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/call_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..15b909f3d3d8408a30ab810e5cb62442d1473c25 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/call_transformer.py @@ -0,0 +1,84 @@ +# 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. + +from __future__ import print_function +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import is_paddle_api +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + +PDB_SET = "pdb.set_trace" + + +class CallTransformer(BaseTransformer): + """ + This class transforms function calls into Static Graph Ast. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of CallTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def _no_need_convert_call(self, node): + """ + Determines whether a function needs to be transformed by `convert_call`. + It doesn't need to be transformed when a function satisfies the following conditions: + 1. It's a api of paddle + 2. It's a python builtin function not include `len`, `zip`, `range` and `enumerate` + """ + assert isinstance(node, gast.Call) + if is_paddle_api(node): + return True + + func_str = ast_to_source_code(node.func).strip() + try: + from paddle.fluid.dygraph.dygraph_to_static.convert_call_func import is_builtin + need_convert_builtin_func_list = { + 'len', + 'zip', + 'range', + 'enumerate', + } + is_builtin = eval("is_builtin({})".format(func_str)) + need_convert = func_str in need_convert_builtin_func_list + return is_builtin and not need_convert + except Exception: + return False + + def transform(self): + self.visit(self.root) + + def visit_Call(self, node): + self.generic_visit(node) + + if self._no_need_convert_call(node): + return node + + func_str = ast_to_source_code(node.func).strip() + + # NOTE(liym27): Don't convert `pad.set_trace` even if the convertion doesn't work finally, because + # it is clearer to see where it is called from. + if PDB_SET in func_str: + return node + + new_func_str = "_jst.Call({})".format(func_str) + new_func_ast = gast.parse(new_func_str).body[0].value + node.func = new_func_ast + + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/cast_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/cast_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..a297d5cf56ed1d9841843d1b10d36e042a30198d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/cast_transformer.py @@ -0,0 +1,47 @@ +# 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. + +from __future__ import print_function +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class CastTransformer(BaseTransformer): + """ + This class transforms type casting into Static Graph Ast. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of CastTransformer." + self._root = wrapper_root.node + self._castable_type = {'bool', 'int', 'float'} + + def transform(self): + self.visit(self._root) + + def visit_Call(self, node): + self.generic_visit(node) + func_str = ast_to_source_code(node.func).strip() + if func_str in self._castable_type and len(node.args) > 0: + args_str = ast_to_source_code(node.args[0]).strip() + new_func_str = "_jst.AsDtype({}, '{}')".format(args_str, func_str) + new_node = gast.parse(new_func_str).body[0].value + return new_node + + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_call_func.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_call_func.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d96b6fe0ad868ee4e32455fbf539359e14f7c2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_call_func.py @@ -0,0 +1,288 @@ +# 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. + +from __future__ import print_function + +import collections +import copy +import functools +import logging +import inspect +import pdb +import re +import types + +import numpy +import six + +from paddle.fluid.dygraph.container import Sequential +from paddle.fluid.dygraph.dygraph_to_static.convert_operators import convert_len, convert_zip +from paddle.fluid.dygraph.dygraph_to_static.convert_operators import convert_range, convert_enumerate +from paddle.fluid.dygraph.dygraph_to_static.logging_utils import TranslatorLogger +from paddle.fluid.dygraph.dygraph_to_static.program_translator import StaticFunction +from paddle.fluid.dygraph.dygraph_to_static.program_translator import convert_to_static +from paddle.fluid.dygraph.dygraph_to_static.program_translator import unwrap_decorators +from paddle.fluid.dygraph.dygraph_to_static.utils import is_paddle_func, unwrap +from paddle.fluid.dygraph.layers import Layer + +__all__ = ["convert_call"] + +# TODO(liym27): A better way to do this. +BUILTIN_LIKELY_MODULES = [ + collections, pdb, copy, inspect, re, six, numpy, logging +] +# The api(s) should be considered as plain function and convert +# them into static layer code. +PADDLE_NEED_CONVERT_APIS = [Sequential] + +translator_logger = TranslatorLogger() + +CONVERSION_OPTIONS = "An attribute for a function that indicates conversion flags of the function in dynamic-to-static." + + +class ConversionOptions(object): + """ + A container for conversion flags of a function in dynamic-to-static. + + Attributes: + not_convert(bool): An attribute indicates that the function won't be converted in dynamic-to-static. + + NOTE(liym27): More attributes and methods can be added in this class. + """ + + def __init__(self, not_convert=False): + self.not_convert = not_convert + + +def is_builtin(func, name=None): + """ predict whether a function is a builtin function with name={name}. + if name == None, then any builtin function will return True + """ + + def name_judge(): + return name is None or func.__name__ == name + + if isinstance(func, types.BuiltinFunctionType) and name_judge(): + return True + elif func in six.moves.builtins.__dict__.values() and name_judge(): + return True + else: + return False + + +def is_unsupported(func): + """ + Checks whether the func is supported by dygraph to static graph. + """ + + for m in BUILTIN_LIKELY_MODULES: + for v in m.__dict__.values(): + func_in_dict = func == v + if isinstance(func_in_dict, (list, numpy.ndarray)): + func_in_dict = numpy.array(func_in_dict).any() + if func_in_dict: + translator_logger.log( + 2, + "Whitelist: {} is part of built-in module and does not have to be transformed." + .format(func)) + return True + + # NOTE: should be placed before `is_paddle_func` + if type(func) in PADDLE_NEED_CONVERT_APIS: + return False + + if is_paddle_func(func): + translator_logger.log( + 2, + "Whitelist: {} is part of Paddle module and does not have to be transformed." + .format(func)) + return True + + +def convert_call(func): + """ + Converts a function call which needs to be transformed to static function. + + Args: + func (callable): A callable function or method to convert. + + Returns: + Callable: A converted function. + + Examples: + .. code-block:: python + + import paddle + from paddle.jit.dy2static import convert_call + + paddle.enable_static() + def dyfunc(x): + if paddle.mean(x) < 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + new_func = convert_call(dyfunc) + x = paddle.tensor.manipulation.fill_constant(shape=[3, 3], value=0, dtype='float64') + x_v = new_func(x) + + exe = paddle.static.Executor(paddle.CPUPlace()) + out = exe.run(fetch_list=[x_v]) + print(out[0]) + # [[1. 1. 1.] + # [1. 1. 1.] + # [1. 1. 1.]] + + """ + translator_logger.log(1, + "Convert callable object: convert {}.".format(func)) + func_self = None + converted_call = None + + # Function in convert_call may be decorated by another `@to_static`, + # in this case, unwraps it into a raw method or function. + _, func = unwrap_decorators(func) + + options = getattr(func, CONVERSION_OPTIONS, None) + if options is not None and options.not_convert: + translator_logger.log( + 2, + "{} is not converted when it is decorated by 'paddle.jit.not_to_static'." + .format(func)) + return func + + if is_builtin(func, "len"): + return convert_len + + if is_builtin(func, "zip"): + return convert_zip + + if is_builtin(func, "range"): + return convert_range + + if is_builtin(func, "enumerate"): + return convert_enumerate + + if is_builtin(func) or is_unsupported(func): + return func + + if inspect.isgeneratorfunction(func): + # NOTE(xiongkun03): inspect.isfunction() will return True even though func is a generator function. + # If we don't deal generatorfunction here, we will regard it as normal function and get errors in some + # occasion. + number_of_stars = 30 + translator_logger.warn( + "\n\n" + "*" * number_of_stars + + "\nYour function:`{}` doesn't support to transform to static function because it is a generator function, it will be run as-is." + .format(func.__name__) + "\n" + "*" * number_of_stars + "\n\n") + return func + + if inspect.isfunction(func): + # TODO(liym27): If func is a lambda function, special conversion is needed. + if func.__name__ == '': + return func + try: + # Note(Aurelius84): Because `@declarative` returns a class instance instead of + # a function. This will modify the value referring to itself in `__globals__`. + + # For example: + # + # @declarative + # def foo(x): + # return x + # + # `foo` will be converted into a wrapper class, suppose as `StaticFunction`. + # And `foo.__globals__['foo']` will still return this `StaticFunction` instead of + # `foo` function. So `isinstance(fn, StaticFunction)` is added here. + _origfunc = unwrap(func) + global_functions = set() + for fn in _origfunc.__globals__.values(): + if inspect.isfunction(fn): + global_functions.add(fn) + elif isinstance(fn, StaticFunction): + _, fn = unwrap_decorators(fn) + global_functions.add(fn) + elif inspect.isclass(fn): + if isinstance(fn.__dict__.get(func.__name__, None), + staticmethod): + global_functions.add( + func) # Add func to ensure that we will convert + + if func in global_functions: + converted_call = convert_to_static(func) + func_self = getattr(func, '__self__', None) + else: + # NOTE: + # If func is not in __globals__, it does not need to be transformed + # because it has been transformed before. + translator_logger.warn( + "{} doesn't have to be transformed to static function because it has been transformed before, it will be run as-is." + .format(func)) + converted_call = func + except AttributeError: + # NOTE: + # If func is not in __globals__, it does not need to be transformed + # because it has been transformed before. + converted_call = None + except (IOError, OSError): + # NOTE: + # If func has been decorated, its source code can not be get + # so that it can not be transformed to static function. + converted_call = None + elif inspect.ismethod(func): + try: + converted_call = convert_to_static(func) + func_self = getattr(func, '__self__', None) + except (IOError, OSError): + # NOTE: func may have been decorated. + converted_call = None + + elif hasattr(func, '__class__') and hasattr(func.__class__, '__call__'): + if hasattr(func, 'forward') and isinstance(func, Layer): + try: + _, forward_func = unwrap_decorators(func.forward) + func._original_funcs['forward'] = forward_func.__func__ + forward_func = convert_to_static(forward_func) + # Bound mothod will be convert into plain function after `convert_to_static`. + # So descriptor mechanism is used to bound `self` instance on function to + # keep it as bound method. + setattr(func, 'forward', forward_func.__get__(func)) + except (IOError, OSError, TypeError): + # NOTE: func.forward may have been decorated. + func_self = None if func_self else func_self + converted_call = func + else: + try: + call_func = func.__class__.__call__ + converted_call = convert_to_static(call_func) + func_self = func + except (IOError, OSError, TypeError): + # NOTE: + # If `func` is a class which is being initialized, for example `convert_call(Foo)()`, + # it doesn't need to be transformed + func_self = None if func_self else func_self + else: + raise NotImplementedError( + "Callable {} can not be transformed at present.".format(func)) + + if converted_call is None: + translator_logger.warn( + "{} doesn't have to be transformed to static function, and it will be run as-is." + .format(func)) + return func + + if func_self: + converted_call = functools.partial(converted_call, func_self) + return converted_call diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..e22d83d56f3a51da37f043f4fc5ea3cabaa9e02d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py @@ -0,0 +1,757 @@ +# 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. + +import re +import paddle +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import to_static_variable +from paddle.fluid.framework import core, Variable +from paddle.fluid.layers import Assert, Print +from paddle.fluid.layers import range as paddle_range +from paddle.fluid.layers import array_length, array_read, array_write, create_array +from paddle.fluid.layers import assign, fill_constant, slice, reduce_all, reduce_any +from paddle.fluid.layers import cast, control_flow, logical_and, logical_not, logical_or, nn +from paddle.fluid.layers.control_flow import cond, while_loop, less_than, increment +from paddle.fluid.dygraph.dygraph_to_static.return_transformer import RETURN_NO_VALUE_VAR_NAME +from paddle.fluid.dygraph.dygraph_to_static.utils import UndefinedVar, Dygraph2StaticException +from paddle.fluid.dygraph.dygraph_to_static.utils import GetterSetterHelper +from paddle.fluid.layers.utils import copy_mutable_vars + + +def convert_attr(x, attr): + if isinstance(x, Variable) and attr == "size": + return x.size() + else: + return getattr(x, attr) + + +def indexable(x, code=None): + if isinstance(x, Variable): return x + if hasattr(x, '__len__') and hasattr(x, '__getitem__'): return x + if hasattr(x, '__iter__'): + return [i for i in x] + else: + raise RuntimeError("X can't be convert into indexable.") + + +def unpack_by_structure(target, structure): + """ unified unpack interface for paddle and python. + """ + if isinstance(target, Variable): + return _unpack_by_structure_paddle(target, structure) + else: + return _unpack_by_structure_python(target, structure) + + +def _unpack_by_structure_python(target, structure): + """ TODO(xiongkun): analysis the differences between python and paddle unpack. + """ + return _unpack_by_structure_paddle(target, structure) + + +def _unpack_by_structure_paddle(target, structure): + if structure == 1: + return target + ret = [] + for idx, ele in enumerate(structure): + if ele == 1: + ret.append(target[idx]) + continue + if isinstance(ele, list): + ret.append(unpack_by_structure(target[idx], ele)) + continue + assert False, "structure element must be 1 or list" + return ret + + +def convert_while_loop(cond, + body, + getter, + setter, + return_name_ids=None, + push_pop_names=None): + """ + A function representation of a Python ``while`` statement. + + Args: + cond(Callable): A callable object that returns a boolean variable to control whether to execute the loop body. It takes ``loop_vars`` as arguments. + body(Callable): A callable object that returns a tuple or list of variables with the same arguments ``loops_vars`` as ``cond`` . + get_args(callable): Get all arguments that needed in true_fn and false_fn. + set_args(callable): Update arguments that modified in trure_fn and false_fn. + return_name_ids(list[string], optional): the returned names. + push_pop_names(list[string], optional): the names on which called .append() or .pop(). + + Returns: + A list or tuple of variables which returned by ``body``. + """ + + # NOTE: It may be slower if cond is very expensive, but usually cond is just O(1). + # If loop_vars is changed during cond callable, then it causes bug, but current logical_and/logical_not/... doesn't change the loop_vars. + pred = cond() + if isinstance(pred, Variable): + _run_paddle_while(cond, body, getter, setter, return_name_ids, + push_pop_names) + else: + _run_py_while(cond, body, getter, setter) + + +def _convert_tensor_arrray_if_necessary(setterhelper, push_pop_names): + push_pop_vars = setterhelper.get(push_pop_names) + if push_pop_vars is None: + return + + def maybe_to_tensor_array(v): + if isinstance(v, list): + return create_array("float32", initialized_list=v) + else: + return v + + setterhelper.set(push_pop_names, + [maybe_to_tensor_array(v) for v in push_pop_vars]) + + +def _run_paddle_while(cond, body, getter, setter, return_name_ids, + push_pop_names): + # NOTE: loop_vars of Paddle op `control_flow.while_loop` must be Paddle Tensors. + helper = GetterSetterHelper(getter, setter, return_name_ids, push_pop_names) + _convert_tensor_arrray_if_necessary(helper, push_pop_names) + + def new_body_fn(*args): + """ wrap the body() and add return value for `while_loop` + the args may be differ from getter(). + """ + mutable_loop_vars = args + helper.set(return_name_ids, mutable_loop_vars) + body() + return helper.get(return_name_ids) + + def new_cond_fn(*args): + """ cond is a zero-args function, which is not + compatible with `while_loop`. + """ + return cond() + + # UndefinedVar will become data layer not check variable with value=NO_VALUE_MAGIC. + loop_vars = [ + to_static_variable(var) if not isinstance(var, UndefinedVar) else var + for var in helper.get(return_name_ids) + ] + helper.set(return_name_ids, + loop_vars) # change the non-local var to variable + # variable maybe modified to inner var. change it into + loop_vars = control_flow.while_loop(new_cond_fn, new_body_fn, loop_vars) + helper.set(return_name_ids, loop_vars) + return loop_vars + + +def _run_py_while(cond, body, getter, setter): + while True: + pred = cond() + if isinstance(pred, Variable): + raise Dygraph2StaticException( + "python while pred change from bool to variable.") + if not pred: break + body() + + +def convert_logical_and(x_func, y_func): + """ + A function representation of a Python ``and`` statement. + + Args: + x_func(callable): x_func() is the left hand operand of ``and`` operator. x_func() is bool or Tensor. + y_func(callable): y_func() is the right hand operand of ``and`` operator. y_func() is bool or Tensor. + + Returns: + A python bool variable or a bool Tensor. + + NOTE(liym27): + 1) The operands are executed sequentially according to the running logic of Python. So here the arguments + should be callable. + 2) If the left hand operand is False, the right hand operand should be executed. + + For example: + a = x > 1 and y < 1 + Transformed code: + a = paddle.jit.dy2static.convert_logical_and(lambda:x>1, lambda:y<1) + + In `convert_logical_and(lambda:x>1, lambda:y<1)`, `lambda:y<1` must be run after `lambda:x>1`. And + if `x>1` is False, `y<1` should NOT be run. + """ + x_value = x_func() + if not isinstance(x_value, Variable): + return _run_py_logical_and(lambda: x_value, y_func) + + y_value = y_func() + if not isinstance(y_value, Variable): + return _run_py_logical_and(lambda: y_value, lambda: x_value) + + return _run_paddle_logical_and(x_value, y_value) + + +def _run_paddle_logical_and(x, y): + x = cast_bool_if_necessary(x) + y = cast_bool_if_necessary(y) + return logical_and(x, y) + + +def _run_py_logical_and(x_func, y_func): + x_value = x_func() + assert not isinstance(x_value, Variable) + + # NOTE(liym27): + # 1. Returns y_func() if x_value is False; + # 2. If x_value is False, y_func() should not be run. + return x_value and y_func() + + +def convert_logical_or(x_func, y_func): + """ + A function representation of a Python ``or`` statement. + + Args: + x_func(callable): x_func() is the left hand operand of ``or`` operator. x_func() is bool or Tensor. + y_func(callable): y_func() is the right hand operand of ``or`` operator. y_func() is bool or Tensor. + + Returns: + A python bool variable or a bool Tensor. + + NOTE(liym27): + 1) The operands are executed sequentially according to the running logic of Python. So here the arguments + should be callable. + 2) If the left hand operand is True, the right hand operand should be executed. + + For example: + a = x > 1 or y < 1 + Transformed code: + a = paddle.jit.dy2static.convert_logical_or(lambda:x>1, lambda:y<1) + + In `convert_logical_or(lambda:x>1, lambda:y<1)`, `lambda:y<1` must be run after `lambda:x>1`. And + if `x>1` is True, `y<1` should NOT be run. + """ + x_value = x_func() + if not isinstance(x_value, Variable): + return _run_py_logical_or(lambda: x_value, y_func) + + y_value = y_func() + if not isinstance(y_value, Variable): + return _run_py_logical_or(lambda: y_value, lambda: x_value) + + return _run_paddle_logical_or(x_value, y_value) + + +def _run_paddle_logical_or(x, y): + x = cast_bool_if_necessary(x) + y = cast_bool_if_necessary(y) + return logical_or(x, y) + + +def _run_py_logical_or(x_func, y_func): + x_value = x_func() + assert not isinstance(x_value, Variable) + + # NOTE(liym27): + # 1. Returns y_func() if x_value is False; + # 2. If x_value is True, y_func() should not be run. + return x_value or y_func() + + +def convert_logical_not(x): + """ + A function representation of a Python ``not`` statement. + + Args: + x(bool|Tensor): Operand of ``not`` operator. + + Returns: + A python bool variable or a bool Tensor. + """ + + if isinstance(x, Variable): + return _run_paddle_logical_not(x) + else: + return _run_py_logical_not(x) + + +def _run_paddle_logical_not(x): + x = cast_bool_if_necessary(x) + return logical_not(x) + + +def _run_py_logical_not(x): + return not x + + +def convert_ifelse(pred, + true_fn, + false_fn, + get_args, + set_args, + return_name_ids, + push_pop_names=None): + """ + A function representation of a Python ``if/else`` statement. + + Args: + pred(bool|Tensor): A boolean Tensor which determines whether to return the result of ``true_fn`` or ``false_fn`` . + true_fn(callable): A callable to be performed if ``pred`` is true. + false_fn(callable): A callable to be performed if ``pred`` is false. + get_args(callable): Get all arguments that needed in true_fn and false_fn. + set_args(callable): Update arguments that modified in trure_fn and false_fn. + return_name_ids(list[string], optional): the returned names. + push_pop_names(list[string], optional): the names on which called .append() or .pop(). + + Returns: + ``true_fn()`` if the predicate ``pred`` is true else ``false_fn()`` . + + """ + if isinstance(pred, Variable): + out = _run_paddle_cond(pred, true_fn, false_fn, get_args, set_args, + return_name_ids, push_pop_names) + else: + out = _run_py_ifelse(pred, true_fn, false_fn, get_args, set_args, + return_name_ids) + + return out + + +def _run_paddle_cond(pred, true_fn, false_fn, get_args, set_args, + return_name_ids, push_pop_names): + """ + Paddle cond API will evaluate both ture_fn and false_fn codes. + """ + helper = GetterSetterHelper(get_args, set_args, return_name_ids, + push_pop_names) + _convert_tensor_arrray_if_necessary(helper, push_pop_names) + pred = cast_bool_if_necessary(pred) + init_args = helper.get(return_name_ids) + + def new_true_fn(): + #init args may contain mutable python container like [var, 2], we copy then like in while_loop + helper.set(return_name_ids, copy_mutable_vars(init_args)) + ret = true_fn() + # IfExpr will return a non-None return value, so we just return ret. + # We assume normal return has no return value. + if ret is None: return helper.get(return_name_ids) + else: return ret + + def new_false_fn(): + #init args may contain mutable python container like [var, 2], we copy then like in while_loop + helper.set(return_name_ids, copy_mutable_vars(init_args)) + ret = false_fn() + if ret is None: return helper.get(return_name_ids) + else: return ret + + try: + cond_outs = control_flow.cond(pred, new_true_fn, new_false_fn, None, + return_name_ids) + except Exception as e: + if re.search("Unsupported return type of true_fn and false_fn in cond", + str(e)): + raise Dygraph2StaticException( + "Your if/else have different return type. TODO: add link to modifty. {}" + .format(str(e))) + if re.search("Incompatible return values of", str(e)): + raise Dygraph2StaticException( + "Your if/else have different number of return value. TODO: add link to modifty. {}" + .format(str(e))) + raise e + get_args = lambda: helper.get(return_name_ids) + set_args = lambda vs: helper.set(return_name_ids, vs) + return _recover_args_state(cond_outs, get_args, set_args, return_name_ids) + + +def _run_py_ifelse(pred, true_fn, false_fn, get_args, set_args, + return_name_ids): + """ + Evaluate python original branch function if-else. + """ + py_outs = true_fn() if pred else false_fn() + return py_outs + + +def _remove_no_value_return_var(out): + if isinstance(out, tuple) and len(out) > 0: + processed_out = out + align_ret = out[0] + if isinstance(align_ret, tuple): + for index, item in enumerate(align_ret): + if isinstance(item, Variable) and (RETURN_NO_VALUE_VAR_NAME + in item.name): + # return None + if index == 0: + processed_out = (None, ) + out[1:] + elif index == 1: + processed_out = align_ret[:1] + out[1:] + else: + processed_out = (align_ret[:index], ) + out[1:] + break + + for index, item in enumerate(processed_out): + if isinstance(item, Variable) and (RETURN_NO_VALUE_VAR_NAME + in item.name): + processed_out = processed_out[:index] + + if not processed_out: + return None + elif len(processed_out) == 1: + return processed_out[0] + else: + return processed_out + + else: + return out + + +def _check_no_undefined_var(outs, names, branch_name): + if names is None: return + if not isinstance(outs, (list, tuple)): + outs = [outs] + for var, name in zip(list(outs), names): + if isinstance(var, UndefinedVar): + raise ValueError( + "Required '{}' must be initialized both in if-else branch, but found it not initialized in '{}'." + .format(name, branch_name)) + + +def _recover_args_state(outs, get_args, set_args, return_name_ids): + """ + Currently we support variant length of early return statement by padding + _no_return_value. + + # TODO(dev): We shall consider to evaluate whether should support this for Python if-else? + """ + # IfExpr's return_name_ids maybe None + if return_name_ids is None: + return outs + + init_args = get_args() + # recover args state + num_outs = len(return_name_ids) + num_args = len(init_args) + assert num_outs <= num_args + + if num_args == 1: + final_outs = (outs, ) if not isinstance(outs, + (list, tuple)) else tuple(outs) + else: + outs = (outs, ) if num_outs == 1 else tuple(outs) + final_outs = outs + init_args[num_outs:] + + set_args(final_outs) + return final_outs + + +def convert_len(var): + """ + Returns variable(length) from shape ops based on var.type + + Note: In addition to some ast transformations, some block-related + operations are added in `len` transformation, such as appending + `shape_op` in var.block. + """ + if isinstance(var, Variable): + if var.type in [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.SELECTED_ROWS + ]: + # Note: Length of var may be known ahead of time in dygraph, + # but it probably represents batch size which can be variant. + # so we return a variable dynamically inferred from var.shape. + if var.shape[0] > 0 and var.type == core.VarDesc.VarType.LOD_TENSOR: + return var.shape[0] + return nn.shape(var)[0] + elif var.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + return control_flow.array_length(var) + else: + raise TypeError( + 'len(var) only supports LoDTensor/LoDTensorArray/SelectedRows, but received %s.' + % type(var)) + else: + if isinstance(var, VariableTuple): + return var.__len__() + return len(var) + + +def convert_zip(*args): + for i, arg in enumerate(args): + if isinstance(arg, Variable) and arg.shape[0] == -1: + raise RuntimeError( + "Not support zip(tensor, ...) when tensor.shape[0] == -1, " + "but found args[{}].shape[0] == -1 in 'zip'".format(str(i))) + return zip(*args) + + +# TODO(xiongkun): delete when list is ready. +class VariableTuple: + """ + this class will cause enumerate can't be wrapped by other iterator change function. + this will be fixed when list is producted. + VariableTuple can only deal with variables which is fixed. + """ + + def __init__(self, var, start=0): + self.var = var + self.len = convert_len(var) + if isinstance(self.len, Variable): + self.rag = paddle_range(start, start + self.len, 1, paddle.int64) + else: + self.rag = range(start, start + self.len) + + def __getitem__(self, idx): + return self.rag[idx], self.var[idx] + + def __len__(self): + return self.len + + +def convert_enumerate(*args): + has_variable = any(map(lambda x: isinstance(x, Variable), args)) + if has_variable: + return VariableTuple(*args) + return enumerate(*args) + + +def convert_range(*args): + has_variable = any(map(lambda x: isinstance(x, Variable), args)) + if has_variable: + if len(args) == 1: return paddle_range(0, args[0], 1, paddle.int64) + if len(args) == 2: + return paddle_range(args[0], args[1], 1, paddle.int64) + if len(args) == 3: + return paddle_range(args[0], args[1], args[2], paddle.int64) + return range(*args) + + +def convert_shape(x): + """ + A function representation of the shape of variable. + """ + + def has_negative(list_shape): + return any([x < 0 for x in list_shape]) + + # When `x` is Variable: + # (1) if x.shape contains -1, such as [2, -1, 64], returns [2, var, 64], + # where var = paddle.shape(x)[1] + + # (2) if x.shape does not contains -1, return lsit(x.shape) directly + + if isinstance(x, Variable): + values = list(x.shape) + if has_negative(values): + shape_tensor = nn.shape(x) + for i, v in enumerate(values): + if v is None or v < 0: + values[i] = shape_tensor[i] + return values + else: + return x.shape + + +def convert_shape_compare(left, *args): + """ + A function handles comparison difference between Paddle and Python. + For example, if x and y are Tensors, x.shape == y.shape will return single + boolean Value (True/False). However, paddle.shape(x) == paddle.shape(y) is + an element-wise comparison. The difference can cause dy2stat error. So we + create this function to handle the difference. + + Args: + left: variable + *args: compare_op(str), variable, compare_op(str), variable, where + compare_op means "<", ">", "==", "!=", etc. + Returns: + If the variables to compare are NOT Paddle Variables, we will return as + Python like "a op1 b and b op2 c and ... ". + If the variables to compare are Paddle Variables, we will do elementwise + comparsion first and then reduce to a boolean whose numel is 1. + + """ + args_len = len(args) + assert args_len >= 2, "convert_shape_compare needs at least one right compare variable" + assert args_len % 2 == 0, "Illegal input for convert_shape_compare, *args should be op(str), var, op(str), var ..." + num_cmp = args_len // 2 + if isinstance(left, Variable): + + def reduce_compare(x, op_str, y): + element_wise_result = eval("x " + op_str + " y") + if op_str == "!=": + return reduce_any(element_wise_result) + elif op_str == "is" or op_str == "is not" or op_str == "in" or op_str == "not in": + return element_wise_result + else: + return reduce_all(element_wise_result) + + final_result = reduce_compare(left, args[0], args[1]) + for i in range(1, num_cmp): + cmp_left = args[i * 2 - 1] + cmp_op = args[i * 2] + cmp_right = args[i * 2 + 1] + cur_result = reduce_compare(cmp_left, cmp_op, cmp_right) + final_result = convert_logical_and(lambda: final_result, + lambda: cur_result) + return final_result + else: + cmp_left = left + final_result = None + for i in range(num_cmp): + cmp_op = args[i * 2] + cmp_right = args[i * 2 + 1] + cur_result = eval("cmp_left " + cmp_op + " cmp_right") + if final_result is None: + final_result = cur_result + else: + final_result = final_result and cur_result + + if final_result is False: + return False + cmp_left = cmp_right + return final_result + + +def cast_bool_if_necessary(var): + assert isinstance(var, Variable) + if convert_dtype(var.dtype) not in ['bool']: + var = cast(var, dtype="bool") + return var + + +def convert_var_dtype(var, dtype): + if isinstance(var, Variable): + src_dtype = convert_dtype(var.dtype) + assert src_dtype in [ + 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'uint8' + ], "The dtype of var {} is {}, which is not supported in the cast op.".format( + var.name, src_dtype) + assert dtype in [ + 'bool', 'int', 'float' + ], "The casted target dtype is {}, which is not supported in type casting.".format( + dtype) + cast_map = { + 'bool': 'bool', + 'int': 'int32', + 'float': 'float32', + } + return cast(var, dtype=cast_map[dtype]) + else: + return eval('{}(var)'.format(dtype)) + + +def convert_assert(cond, message=""): + """ + A function representation of a Python ``assert`` statement. + """ + if isinstance(cond, Variable): + cond = cast(cond, "bool") + # NOTE: message is not used because Paddle Assert has no corresponding parameter to use. + return Assert(cond) + else: + assert cond, message + + +def convert_print(*args): + """ + A function representing Python ``print`` statement. Note: this is a basic + python function so we haven't handle sep, end, file and flush parameters of + python function. + """ + for var in args: + if isinstance(var, Variable): + var = Print(var) + else: + print(var) + + +def convert_pop(target, *args): + """ + A function representation of a Python pop statement for a list or dict. + + Args: + target(list|dict|Tensor): A variable to pop item from. + *args(tuple): index or default value to parse. + + Returns: + A item poped from target. + """ + + is_variable = isinstance(target, Variable) + if is_variable: + is_tensor_array = target.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY + + if is_variable and is_tensor_array: + return _run_paddle_pop(target, *args) + else: + return _run_python_pop(target, *args) + + +def _run_paddle_pop(array, *args): + if len(args) == 0: + idx = -1 + else: + idx = args[0] + + assert isinstance(idx, int) + + def cond(i, new_array): + return less_than(i, arr_len) + + def body(i, new_array): + item = array_read(array=array, i=i) + array_write(item, array_length(new_array), new_array) + i = increment(i) + return i, new_array + + arr_len = array_length(array) + if idx < 0: + idx = idx + arr_len + else: + idx = fill_constant(shape=[1], dtype="int64", value=idx) + + pop_item = array_read(array, idx) + + new_array = _slice_tensor_array(array, 0, idx) + i = idx + 1 + _, new_array = while_loop(cond, body, [i, new_array]) + assign(input=new_array, output=array) + + return pop_item + + +# TODO(liym27): A better way to slice tensor array. +# Maybe support start == end for slice op. +def _slice_tensor_array(array, start, end): + + def true_fn(): + null_array = create_array("float32") + return null_array + + def false_fn(array, start, end): + new_array = slice(array, starts=[start], ends=[end], axes=[0]) + return new_array + + new_array = cond(start == end, true_fn, lambda: false_fn(array, start, end)) + return new_array + + +def _run_python_pop(target, *args): + # 1. pop for a dict + if len(args) == 2: + idx, default = args + return target.pop(idx, default) + + # 2. pop for a list or dict + else: + idx = args[0] if args else -1 + return target.pop(idx) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/create_variable_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/create_variable_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..bcfa3e3ec1ca926be86935ce0e847b4ed3201676 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/create_variable_transformer.py @@ -0,0 +1,49 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.utils import FunctionNameLivenessAnalysis +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import create_undefined_var +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class CreateVariableTransformer(BaseTransformer): + """ + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Type of input node should be AstNodeWrapper, but received %s ." % type( + wrapper_root) + self.root = wrapper_root.node + FunctionNameLivenessAnalysis(self.root) + + def transform(self): + """ + Main function to transform AST. + """ + self.visit(self.root) + + def visit_FunctionDef(self, node): + #attributes = set(filter(lambda x: '.' in x, node.pd_scope.modified_vars())) + self.generic_visit(node) + bodys = node.body + names = sorted(node.pd_scope.created_vars()) + for name in names: + bodys[0:0] = [create_undefined_var(name)] + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/decorator_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/decorator_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..299b5faa55402af0941baecca17041c1e7d62ccc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/decorator_transformer.py @@ -0,0 +1,140 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.utils import create_funcDef_node, ast_to_source_code, is_paddle_api, Dygraph2StaticException +import warnings + +import re +from paddle.fluid.dygraph.dygraph_to_static.utils import RE_PYNAME, RE_PYMODULE + +IGNORE_NAMES = [ + 'declarative', 'to_static', 'dygraph_to_static_func', 'wraps', + 'staticmethod', 'classmethod', 'decorator' +] + + +class DecoratorTransformer(BaseTransformer): + """ + Transform decorators. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Type of input node should be AstNodeWrapper, but received %s ." % type( + wrapper_root) + self.root = wrapper_root.node + + self.ancestor_nodes = [] + + def transform(self): + """ + Main function to transform AST. + """ + self.visit(self.root) + + def visit_FunctionDef(self, node): + assert isinstance(node, gast.FunctionDef) + self.generic_visit(node) + + deco_list = node.decorator_list + node.decorator_list = [] + + # every decorator will append a node + decofun_nodes = [] + # func to be decoed next time + deco_target = '_orig_' + node.name + # last decoed func + decoed_func = '' + + for deco in reversed(deco_list): + # skip INGNORE_NAMES + deco_full_name = ast_to_source_code(deco).strip() + if isinstance(deco, gast.Call): + # match case like : + # 1: @_jst.Call(a.b.c.d.deco)() + # 2: @q.w.e.r.deco() + re_tmp = re.match( + r'({module})*({name}\(){{0,1}}({module})*({name})(\)){{0,1}}\(.*$' + .format(name=RE_PYNAME, module=RE_PYMODULE), deco_full_name) + deco_name = re_tmp.group(4) + else: + # match case like: + # @a.d.g.deco + re_tmp = re.match( + r'({module})*({name})$'.format(name=RE_PYNAME, + module=RE_PYMODULE), + deco_full_name) + deco_name = re_tmp.group(2) + if deco_name in IGNORE_NAMES: + continue + elif deco_name == 'contextmanager': + warnings.warn( + "Dy2Static : A context manager decorator is used, this may not work correctly after transform." + ) + + decoed_func = '_decoedby_' + deco_name + + # get function after decoration + if isinstance(deco, gast.Call): + if '_jst.Call' in deco_full_name: + # in this case , the deco_full_name will be like: + # '_jst.Call(deco)(5)' + rematch = re.match(r'\_jst\.Call\((.+?)\)\((.*)\)', + deco_full_name) + re_name = rematch.group(1) + re_args = rematch.group(2) + re_args_with_func = deco_target + ', ' + re_args + decofun_str = 'try:\n\t{0} = _jst.Call({1})({2})\nexcept:\n\t{0} = _jst.Call({1})({3})({4})'\ + .format(decoed_func, re_name, re_args_with_func, re_args, deco_target) + else: + # paddle api will not be transformed to '_jst.Call' + rematch = re.match(r'(.+?)\((.*)\)', deco_full_name) + re_name = rematch.group(1) + re_args = rematch.group(2) + re_args_with_func = deco_target + ', ' + re_args + decofun_str = 'try:\n\t{0} = {1}({2})\nexcept:\n\t{0} = {1}({3})({4})'\ + .format(decoed_func, re_name, re_args_with_func, re_args, deco_target) + + else: + decofun_str = '{} = _jst.Call({})({})'.format( + decoed_func, deco_full_name, deco_target) + + decofun_nodes.extend(gast.parse(decofun_str).body) + deco_target = decoed_func + + if not decofun_nodes: + return node + + orig_func_node = gast.FunctionDef(name='_orig_' + node.name, + args=node.args, + body=node.body, + decorator_list=[], + returns=None, + type_comment=None) + + args = [arg.id for arg in node.args.args] + arg_str = ','.join(args) + callfun_str = 'return {}({})'.format(decoed_func, arg_str) + callfun_node = gast.parse(callfun_str).body[0] + + node.body = [orig_func_node] + decofun_nodes + [callfun_node] + + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/early_return_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/early_return_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf82b020994e48e3fbcd58821727c1e1b39f859 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/early_return_transformer.py @@ -0,0 +1,89 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class EarlyReturnTransformer(BaseTransformer): + """ + Transform if/else return statement of Dygraph into Static Graph. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Type of input node should be AstNodeWrapper, but received %s ." % type( + wrapper_root) + self.root = wrapper_root.node + + def transform(self): + """ + Main function to transform AST. + """ + self.visit(self.root) + + def is_define_return_in_if(self, node): + assert isinstance( + node, gast.If + ), "Type of input node should be gast.If, but received %s ." % type( + node) + for child in node.body: + if isinstance(child, gast.Return): + return True + return False + + def visit_block_nodes(self, nodes): + result_nodes = [] + destination_nodes = result_nodes + for node in nodes: + rewritten_node = self.visit(node) + + if isinstance(rewritten_node, (list, tuple)): + destination_nodes.extend(rewritten_node) + else: + destination_nodes.append(rewritten_node) + + # append other nodes to if.orelse even though if.orelse is not empty + if isinstance(node, gast.If) and self.is_define_return_in_if(node): + destination_nodes = node.orelse + # handle stmt like `if/elif/elif` + while len(destination_nodes) > 0 and \ + isinstance(destination_nodes[0], gast.If) and \ + self.is_define_return_in_if(destination_nodes[0]): + destination_nodes = destination_nodes[0].orelse + + return result_nodes + + def visit_If(self, node): + node.body = self.visit_block_nodes(node.body) + node.orelse = self.visit_block_nodes(node.orelse) + return node + + def visit_While(self, node): + node.body = self.visit_block_nodes(node.body) + node.orelse = self.visit_block_nodes(node.orelse) + return node + + def visit_For(self, node): + node.body = self.visit_block_nodes(node.body) + node.orelse = self.visit_block_nodes(node.orelse) + return node + + def visit_FunctionDef(self, node): + node.body = self.visit_block_nodes(node.body) + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/error.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/error.py new file mode 100644 index 0000000000000000000000000000000000000000..93670758dae77e864a93318924162724c53fd9a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/error.py @@ -0,0 +1,352 @@ +# 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. + +import os +import six +import sys +import traceback +import linecache +import re + +from paddle.fluid.dygraph.dygraph_to_static.origin_info import Location, OriginInfo, global_origin_info_map + +ERROR_DATA = "Error data about original source code information and traceback." + +# A flag to set whether to open the dygraph2static error reporting module +SIMPLIFY_ERROR_ENV_NAME = "TRANSLATOR_SIMPLIFY_NEW_ERROR" +DEFAULT_SIMPLIFY_NEW_ERROR = 1 + +# A flag to set whether to display the simplified error stack +DISABLE_ERROR_ENV_NAME = "TRANSLATOR_DISABLE_NEW_ERROR" +DEFAULT_DISABLE_NEW_ERROR = 0 + +SOURCE_CODE_RANGE = 5 +BLANK_COUNT_BEFORE_FILE_STR = 4 + + +def attach_error_data(error, in_runtime=False): + """ + Attachs error data about original source code information and traceback to an error. + + Args: + error(Exception): An native error. + in_runtime(bool): `error` is raised in runtime if in_runtime is True, otherwise in compile time + Returns: + An error attached data about original source code information and traceback. + """ + + e_type, e_value, e_traceback = sys.exc_info() + tb = traceback.extract_tb(e_traceback)[1:] + + error_data = ErrorData(e_type, e_value, tb, global_origin_info_map) + error_data.in_runtime = in_runtime + + setattr(error, ERROR_DATA, error_data) + + return error + + +class TraceBackFrame(OriginInfo): + """ + Traceback frame information. + """ + + def __init__(self, location, function_name, source_code): + self.location = location + self.function_name = function_name + self.source_code = source_code + + def formated_message(self): + # self.source_code may be empty in some functions. + # For example, decorator generated function + return ' ' * BLANK_COUNT_BEFORE_FILE_STR + 'File "{}", line {}, in {}\n\t{}'.format( + self.location.filepath, self.location.lineno, self.function_name, + self.source_code.lstrip() + if isinstance(self.source_code, str) else self.source_code) + + +class TraceBackFrameRange(OriginInfo): + """ + Traceback frame information. + """ + + def __init__(self, location, function_name): + self.location = location + self.function_name = function_name + self.source_code = [] + blank_count = [] + begin_lineno = max(1, self.location.lineno - int(SOURCE_CODE_RANGE / 2)) + + for i in range(begin_lineno, begin_lineno + SOURCE_CODE_RANGE): + line = linecache.getline(self.location.filepath, i).rstrip('\n') + line_lstrip = line.lstrip() + self.source_code.append(line_lstrip) + if not line_lstrip: # empty line from source code + blank_count.append(-1) + else: + blank_count.append(len(line) - len(line_lstrip)) + + if i == self.location.lineno: + hint_msg = '~' * len(self.source_code[-1]) + ' <--- HERE' + self.source_code.append(hint_msg) + blank_count.append(blank_count[-1]) + linecache.clearcache() + # remove top and bottom empty line in source code + while len(self.source_code) > 0 and not self.source_code[0]: + self.source_code.pop(0) + blank_count.pop(0) + while len(self.source_code) > 0 and not self.source_code[-1]: + self.source_code.pop(-1) + blank_count.pop(-1) + + min_black_count = min([i for i in blank_count if i >= 0]) + for i in range(len(self.source_code)): + # if source_code[i] is empty line between two code line, dont add blank + if self.source_code[i]: + self.source_code[i] = ' ' * ( + blank_count[i] - min_black_count + + BLANK_COUNT_BEFORE_FILE_STR * 2) + self.source_code[i] + + def formated_message(self): + msg = ' ' * BLANK_COUNT_BEFORE_FILE_STR + 'File "{}", line {}, in {}\n'.format( + self.location.filepath, self.location.lineno, self.function_name) + # add empty line after range code + return msg + '\n'.join(self.source_code) + + +class SuggestionDict(object): + + def __init__(self): + # {(keywords): (suggestions)} + self.suggestion_dict = { + ('is not initialized.', 'Hint:', 'IsInitialized'): + ("Please ensure all your sublayers are inheritted from nn.Layer.", + "Please ensure there is no tensor created explicitly depended on external data, we suggest to register it as buffer tensor. See https://www.paddlepaddle.org.cn/documentation/docs/zh/guides/04_dygraph_to_static/export_model/principle_cn.html#parameters-buffers for details" + ) + } + + def keys(self): + return self.suggestion_dict.keys() + + def __getitem__(self, key): + return self.suggestion_dict[key] + + +class Dy2StKeyError(Exception): + pass + + +class ErrorData(object): + """ + Error data attached to an exception which is raised in un-transformed code. + """ + + def __init__(self, error_type, error_value, origin_traceback, + origin_info_map): + self.error_type = error_type + self.error_value = error_value + self.origin_traceback = origin_traceback + self.origin_info_map = origin_info_map + self.in_runtime = False + self.suggestion_dict = SuggestionDict() + + def create_exception(self): + message = self.create_message() + if self.error_type is KeyError: + new_exception = Dy2StKeyError(message) + else: + new_exception = self.error_type(message) + setattr(new_exception, ERROR_DATA, self) + return new_exception + + def create_message(self): + """ + Creates a custom error message which includes trace stack with source code information of dygraph from user. + """ + message_lines = [] + + # Step1: Adds header message to prompt users that the following is the original information. + header_message = "In transformed code:" + message_lines.append(header_message) + message_lines.append("") + + # Simplify error value to improve readability if error is raised in runtime + if self.in_runtime: + if int( + os.getenv(SIMPLIFY_ERROR_ENV_NAME, + DEFAULT_SIMPLIFY_NEW_ERROR)): + self._simplify_error_value() + message_lines.append(str(self.error_value)) + return '\n'.join(message_lines) + + # Step2: Optimizes stack information with source code information of dygraph from user. + user_code_traceback_index = [] + for i, (filepath, lineno, funcname, + code) in enumerate(self.origin_traceback): + dygraph_func_info = self.origin_info_map.get((filepath, lineno), + None) + if dygraph_func_info: + user_code_traceback_index.append(i) + + # Add user code traceback + for i in user_code_traceback_index: + filepath, lineno, funcname, code = self.origin_traceback[i] + dygraph_func_info = self.origin_info_map.get((filepath, lineno), + None) + if i == user_code_traceback_index[-1]: + traceback_frame = TraceBackFrameRange( + dygraph_func_info.location, dygraph_func_info.function_name) + else: + traceback_frame = TraceBackFrame( + dygraph_func_info.location, dygraph_func_info.function_name, + dygraph_func_info.source_code) + + message_lines.append(traceback_frame.formated_message()) + message_lines.append("") + + # Add paddle traceback after user code traceback + paddle_traceback_start_index = user_code_traceback_index[ + -1] + 1 if user_code_traceback_index else 0 + for filepath, lineno, funcname, code in self.origin_traceback[ + paddle_traceback_start_index:]: + traceback_frame = TraceBackFrame(Location(filepath, lineno), + funcname, code) + message_lines.append(traceback_frame.formated_message()) + message_lines.append("") + + # Step3: Adds error message like "TypeError: dtype must be int32, but received float32". + # NOTE: `format_exception` is a list, its length is 1 in most cases, but sometimes its length + # is gather than 1, for example, the error_type is IndentationError. + format_exception = traceback.format_exception_only( + self.error_type, self.error_value) + error_message = [ + " " * BLANK_COUNT_BEFORE_FILE_STR + line + for line in format_exception + ] + message_lines.extend(error_message) + + return '\n'.join(message_lines) + + def _create_revise_suggestion(self, bottom_error_message): + revise_suggestions = [ + '', ' ' * BLANK_COUNT_BEFORE_FILE_STR + 'Revise suggestion: ' + ] + for keywords in self.suggestion_dict.keys(): + contain_keywords = [ + True for i in keywords if i in ''.join(bottom_error_message) + ] + if len(contain_keywords) == len( + keywords): # all keywords should be in bottom_error_message + for suggestion in self.suggestion_dict[keywords]: + suggestion_msg = ' ' * BLANK_COUNT_BEFORE_FILE_STR * 2 + '{}. {}'.format( + str(len(revise_suggestions) - 1), suggestion) + revise_suggestions.append(suggestion_msg) + return revise_suggestions if len(revise_suggestions) > 2 else [] + + def _simplify_error_value(self): + """ + Simplifies error value to improve readability if error is raised in runtime. + + NOTE(liym27): The op callstack information about transformed static code has been replaced with original dygraph code. + + TODO(liym27): + 1. Need a more robust way because the code of start_trace may change. + 2. Set the switch to determine whether to simplify error_value + """ + + assert self.in_runtime is True + + error_value_lines = str(self.error_value).split("\n") + error_value_lines_strip = [mes.lstrip(" ") for mes in error_value_lines] + + start_trace = "outputs = static_func(*inputs)" + start_idx = error_value_lines_strip.index(start_trace) + + error_value_lines = error_value_lines[start_idx + 1:] + error_value_lines_strip = error_value_lines_strip[start_idx + 1:] + + # use empty line to locate the bottom_error_message + empty_line_idx = error_value_lines_strip.index('') + bottom_error_message = error_value_lines[empty_line_idx + 1:] + revise_suggestion = self._create_revise_suggestion(bottom_error_message) + + error_traceback = [] + user_code_traceback_index = [] + pattern = 'File "(?P.+)", line (?P.+), in (?P.+)' + + # Distinguish user code and framework code using static_info_map + static_info_map = {} + for k, v in self.origin_info_map.items(): + origin_filepath = v.location.filepath + origin_lineno = v.location.lineno + static_info_map[(origin_filepath, origin_lineno)] = k + + for i in range(0, len(error_value_lines_strip), 2): + if error_value_lines_strip[i].startswith("File "): + re_result = re.search(pattern, error_value_lines_strip[i]) + tmp_filepath, lineno_str, function_name = re_result.groups() + code = error_value_lines_strip[ + i + 1] if i + 1 < len(error_value_lines_strip) else '' + + if static_info_map.get((tmp_filepath, int(lineno_str))): + user_code_traceback_index.append(len(error_traceback)) + + error_traceback.append( + (tmp_filepath, int(lineno_str), function_name, code)) + + error_frame = [] + # Add user code traceback + for i in user_code_traceback_index: + filepath, lineno, funcname, code = error_traceback[i] + if i == user_code_traceback_index[-1]: + traceback_frame = TraceBackFrameRange( + Location(filepath, lineno), funcname) + else: + traceback_frame = TraceBackFrame(Location(filepath, lineno), + funcname, code) + error_frame.append(traceback_frame.formated_message()) + error_frame.append("") + + # Add paddle traceback after user code traceback + paddle_traceback_start_index = user_code_traceback_index[ + -1] + 1 if user_code_traceback_index else 0 + for filepath, lineno, funcname, code in error_traceback[ + paddle_traceback_start_index:]: + traceback_frame = TraceBackFrame(Location(filepath, lineno), + funcname, code) + error_frame.append(traceback_frame.formated_message()) + error_frame.append("") + + error_frame.extend(bottom_error_message) + error_frame.extend(revise_suggestion) + error_value_str = '\n'.join(error_frame) + self.error_value = self.error_type(error_value_str) + + def raise_new_exception(self): + # Raises the origin error if disable dygraph2static error module, + if int(os.getenv(DISABLE_ERROR_ENV_NAME, DEFAULT_DISABLE_NEW_ERROR)): + raise + + new_exception = self.create_exception() + if six.PY3: + # NOTE(liym27): + # 1. Why `raise new_exception from None`? + # In Python 3, by default, an new exception is raised with trace information of the caught exception. + # This only raises new_exception and hides unwanted implementation details from tracebacks of the + # caught exception. + # 2. Use exec to bypass syntax error checking in Python 2. + + six.exec_("raise new_exception from None") + else: + raise new_exception diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/function_spec.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/function_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..e8afef094689827b3b4511b8e37594fc9869c369 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/function_spec.py @@ -0,0 +1,427 @@ +# 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. + +import six +import inspect +import numpy as np +import collections + +import paddle +from paddle.fluid import core +from paddle.fluid.dygraph import layers +from paddle.fluid.layers.utils import flatten +from paddle.fluid.layers.utils import pack_sequence_as +from paddle.fluid.dygraph.base import switch_to_static_graph +from paddle.fluid.dygraph.dygraph_to_static import logging_utils +from paddle.fluid.dygraph.dygraph_to_static.utils import parse_arg_and_kwargs +from paddle.fluid.dygraph.dygraph_to_static.utils import parse_varargs_name +from paddle.fluid.dygraph.dygraph_to_static.utils import type_name +from paddle.fluid.dygraph.dygraph_to_static.utils import func_to_source_code +from paddle.fluid.dygraph.io import TranslatedLayer + + +class FunctionSpec(object): + """ + Wrapper class for a function for class method. + """ + + def __init__(self, function, input_spec=None): + self._dygraph_function = function + if input_spec is None: + self._input_spec = None + self._flat_input_spec = None + else: + self._input_spec = self._verify_input_spec(input_spec) + self._flat_input_spec = flatten(self._input_spec) + + # parse full argument names list. + self._arg_names, self._default_kwargs = parse_arg_and_kwargs(function) + # parse *args + self.varargs_name = parse_varargs_name(function) + if self.varargs_name is not None and isinstance(function.__self__, + TranslatedLayer): + self._arg_names += function.__self__._input_args_names + + def unified_args_and_kwargs(self, args, kwargs): + """ + Moves kwargs with default value into arguments list to keep `args` contain the same length + value as function definition. + + For example: + + Given function definition: `def foo(x, a=1, b=2)`, + when calling it by `foo(23)`, the args is `[23]`, kwargs is `{a=1, b=2}`. + In this function, it will return args with `[23, 1, 2]`, kwargs with `{}` + + Args: + args(tuple): tuple of input arguments value of decorated function. + kwargs(dict): dict of input keyword arguments value of decorated function. + + Return: + New arguments tuple containing default kwargs value. + """ + if len(self._arg_names) < len(args): + error_msg = "The decorated function `{}` requires {} arguments: {}, but received {} with {}.".format( + self._dygraph_function.__name__, len(self._arg_names), + self._arg_names, len(args), args) + if args and inspect.isclass(args[0]): + error_msg += "\n\tMaybe the function has more than one decorator, we don't support this for now." + raise NotImplementedError(error_msg) + else: + raise ValueError(error_msg) + + args = list(args) + + for i in six.moves.range(len(args), len(self._arg_names)): + arg_name = self._arg_names[i] + if arg_name in kwargs: + args.append(kwargs[arg_name]) + del kwargs[arg_name] + else: + if arg_name not in self._default_kwargs: + raise ValueError( + "`{}()` requires `{}` arguments, but not found in input `args`: {} and `kwargs`: {}." + .format(self._dygraph_function.__name__, arg_name, args, + kwargs)) + args.append(self._default_kwargs[arg_name]) + + return tuple(args), kwargs + + def _replace_value_with_input_spec(self, args): + args_with_spec = [] + for idx, input_var in enumerate(flatten(args)): + if isinstance(input_var, np.ndarray): + input_var = paddle.static.InputSpec.from_numpy(input_var) + _set_spec_stop_gradient(input_var, True) + elif isinstance(input_var, (core.VarBase, core.eager.Tensor)): + stop_gradient = input_var.stop_gradient + input_var = paddle.static.InputSpec.from_tensor(input_var) + _set_spec_stop_gradient(input_var, stop_gradient) + + args_with_spec.append(input_var) + + args_with_spec = pack_sequence_as(args, args_with_spec) + return args_with_spec + + def args_to_input_spec(self, args, kwargs): + """ + Converts input arguments into InputSpec. + + 1. If specific input_spec, use them to construct feed layers. + 2. If input_spec is None, consider all Tensor and Numpy.ndarray as feed layers + + Args: + args(tuple): tuple of input arguments value of function containing default kwargs value. + kwargs(dict): kwargs arguments received by **kwargs. + + Return: + Same nest structure with args and kwargs by replacing value with InputSpec. + """ + + args_with_spec = [] + kwargs_with_spec = [] + if self._input_spec is not None: + # Note: Because the value type and length of `kwargs` is uncertain. + # So we don't support to deal this case while specificing `input_spec` currently. + if kwargs: + raise ValueError( + "{} got unexpected keyword arguments: {}. Cannot trace the function when `input_spec` is specificed." + .format(self._dygraph_function.__name__, kwargs)) + + # Note: The length of `input_spec` can be greater than `args`, + # because `args` may contains non-tensor value merged form `kwargs` + # after `unified_args_and_kwargs`. + if len(args) < len(self._input_spec): + raise ValueError( + "Requires len(arguments) >= len(input_spec), but received len(args):{} < len(InputSpec): {}" + .format(len(args), len(self._input_spec))) + + # replace argument with corresponding InputSpec. + args_with_spec = convert_to_input_spec(args, self._input_spec) + else: + args_with_spec = self._replace_value_with_input_spec(args) + kwargs_with_spec = self._replace_value_with_input_spec(kwargs) + + # If without specificing name in input_spec, add default name + # according to argument name from decorated function. + args_with_spec = replace_spec_empty_name(self._arg_names, + args_with_spec) + + return args_with_spec, kwargs_with_spec + + @switch_to_static_graph + def to_static_inputs_with_spec(self, input_with_spec, main_program): + """ + Constructs feed layer by inputs with InputSpec information for main program. + + Args: + input_with_spec(tuple): input arguments by replacing argument with InputSpec. + main_program(Program): main program for inserting feed layer. + """ + flat_input_spec = flatten(input_with_spec) + + inputs = [] + block = main_program.global_block() + for i, var_spec in enumerate(flat_input_spec): + if isinstance(var_spec, paddle.static.InputSpec): + stop_gradient = getattr(var_spec, 'stop_gradient', False) + feed_layer = block.create_var( + # TODO(Aurelius84): consider a more elegant way to name this + name=var_spec.name or "feed_%s" % i, + shape=var_spec.shape, + dtype=var_spec.dtype, + is_data=True, + need_check_feed=False, + stop_gradient=stop_gradient) + else: + feed_layer = var_spec + inputs.append(feed_layer) + + return pack_sequence_as(input_with_spec, inputs) + + def _verify_input_spec(self, input_spec): + """ + Verifies the `input_spec` and its element type is valid. + """ + if not isinstance(input_spec, (tuple, list)): + raise TypeError( + "The type(input_spec) should be one of (tuple, list), but received {}." + .format(type_name(input_spec))) + + return tuple(input_spec) + + def __repr__(self): + return "function: {}({}), input_spec: {}".format( + self._dygraph_function.__name__, ','.join(self._arg_names), + self._input_spec) + + @property + def dygraph_function(self): + return self._dygraph_function + + @property + def args_name(self): + return self._arg_names + + @property + def input_spec(self): + return self._input_spec + + @property + def flat_input_spec(self): + return self._flat_input_spec + + @property + def code(self): + return func_to_source_code(self._dygraph_function) + + +def get_parameters(layer_instance, include_sublayer=True): + """ + Returns parameters of decorated layers. If set `include_sublayer` True, + the parameters created in sub layers will be added. + """ + params = collections.OrderedDict() + if layer_instance is not None: + if isinstance(layer_instance, layers.Layer): + if include_sublayer: + params = layer_instance.parameters() + names = [p.name for p in params] + params = collections.OrderedDict(zip(names, params)) + else: + params = layer_instance._parameters + else: + raise TypeError( + "Type of `layer_instance` should be nn.Layer, but received {}". + format(type_name(layer_instance))) + + return params + + +def get_buffers(layer_instance, include_sublayer=True): + """ + Returns Variable buffers of decorated layers. If set `include_sublayer` True, + the Variable buffers created in sub layers will be added. + """ + buffers = collections.OrderedDict() + if layer_instance is not None: + if isinstance(layer_instance, layers.Layer): + if include_sublayer: + buffers = layer_instance.buffers() + names = [buffer.name for buffer in buffers] + buffers = collections.OrderedDict(zip(names, buffers)) + else: + buffers = layer_instance._buffers + else: + raise TypeError( + "Type of `layer_instance` should be nn.Layer, but received {}". + format(type_name(layer_instance))) + return buffers + + +def convert_to_input_spec(inputs, input_spec): + """ + Replaces tensor in structured `inputs` by InputSpec in `input_spec`. + + Args: + inputs(list|dict): nested structure list or dict. + input_spec(list|dict): same nested structure list or dict as inputs. + + + Return: + Same structure with inputs by replacing the element with specified InputSpec. + """ + + def check_type_and_len(input, spec, check_length=False): + if type(input) is not type(spec): + raise TypeError('type(input) should be {}, but received {}.'.format( + type(spec), type(input))) + if check_length and len(input) < len(spec): + raise ValueError( + 'Requires len(inputs) >= len(input_spec), but received len(inputs):{} < len(input_spec):{}' + .format(len(inputs), len(input_spec))) + + if isinstance(input_spec, (tuple, list)): + input_with_spec = [] + check_type_and_len(inputs, input_spec, True) + + for i, spec in enumerate(input_spec): + out_spec = convert_to_input_spec(inputs[i], spec) + input_with_spec.append(out_spec) + + # Note: If the rest inputs contain tensor or numpy.ndarray + # without specific InputSpec, raise warning. + if len(inputs) > len(input_spec): + for rest_input in inputs[len(input_spec):]: + if isinstance(rest_input, (core.VarBase, np.ndarray)): + logging_utils.warn( + "The inputs constain `{}` without specificing InputSpec, its shape and dtype will be treated immutable. " + "Please specific InputSpec information in `@to_static` if you expect them as mutable inputs." + .format(type_name(rest_input))) + input_with_spec.extend(inputs[len(input_spec):]) + + return input_with_spec + elif isinstance(input_spec, dict): + input_with_spec = {} + check_type_and_len(inputs, input_spec, True) + for name, input in six.iteritems(inputs): + if name in input_spec: + input_with_spec[name] = convert_to_input_spec( + input, input_spec[name]) + else: + input_with_spec[name] = input + return input_with_spec + elif isinstance(input_spec, paddle.static.InputSpec): + return input_spec + else: + # NOTE(Aurelius84): Support non-Tensor type as input spec info + return input_spec + + +def replace_spec_empty_name(args_name, input_with_spec): + """ + Adds default name according to argument name from decorated function + if without specificing InputSpec.name + + The naming rule are as followed: + 1. If InputSpec.name is not None, do nothing. + 2. If each argument `x` corresponds to an InputSpec, using the argument name like `x` + 3. If the arguments `inputs` corresponds to a list(InputSpec), using name like `inputs_0`, `inputs_1` + 4. If the arguments `input_dic` corresponds to a dict(InputSpec), using key as name. + + For example: + + # case 1: foo(x, y) + foo = to_static(foo, input_spec=[InputSpec([None, 10]), InputSpec([None])]) + print([in_var.name for in_var in foo.inputs]) # [x, y] + + # case 2: foo(inputs) where inputs is a list + foo = to_static(foo, input_spec=[[InputSpec([None, 10]), InputSpec([None])]]) + print([in_var.name for in_var in foo.inputs]) # [inputs_0, inputs_1] + + # case 3: foo(inputs) where inputs is a dict + foo = to_static(foo, input_spec=[{'x': InputSpec([None, 10]), 'y': InputSpec([None])}]) + print([in_var.name for in_var in foo.inputs]) # [x, y] + """ + input_with_spec = list(input_with_spec) + candidate_arg_names = args_name[:len(input_with_spec)] + + for i, arg_name in enumerate(candidate_arg_names): + input_spec = input_with_spec[i] + input_with_spec[i] = _replace_spec_name(arg_name, input_spec) + + return input_with_spec + + +def _replace_spec_name(name, input_spec): + """ + Replaces InputSpec.name with given `name` while not specificing it. + """ + if isinstance(input_spec, paddle.static.InputSpec): + if input_spec.name is None: + input_spec.name = name + return input_spec + elif isinstance(input_spec, (list, tuple)): + processed_specs = [] + for i, spec in enumerate(input_spec): + new_name = "{}_{}".format(name, i) + processed_specs.append(_replace_spec_name(new_name, spec)) + return processed_specs + elif isinstance(input_spec, dict): + processed_specs = {} + for key, spec in six.iteritems(input_spec): + processed_specs[key] = _replace_spec_name(key, spec) + return processed_specs + else: + return input_spec + + +def _set_spec_stop_gradient(spec, stop_gradient): + """ + Set new attribute ``stop_gradient`` for InputSpec to avoid generating redundant grad_op + while append_backward. + """ + assert isinstance(spec, paddle.static.InputSpec) + spec.stop_gradient = stop_gradient + + +def _hash_spec_names(args_specs, kwargs_specs): + """ + Generater hash spec with args/kwargs InputSpec names. + Consider the following InputSpecs with same shape/dtype except for name: + 1. [InputSpec([3,3], 'float32', 'x'), InputSpec([3,3], 'float32', 'x')] + 2. [InputSpec([3,3], 'float32', 'x'), InputSpec([3,3], 'float32', 'y')] + Under @to_static, we should generate two different program not just one, because + the former has one input ('x'), but the latter has two input ('x', 'y'). + """ + spec_names = [ + spec.name for spec in flatten(args_specs) + if isinstance(spec, paddle.static.InputSpec) + ] + spec_names += [ + spec.name for spec in flatten(kwargs_specs) + if isinstance(spec, paddle.static.InputSpec) + ] + i, name_ids = 0, {} + + def to_idx(name): + nonlocal i + if name not in name_ids: + name_ids[name] = i + i += 1 + return name_ids[name] + + value = [to_idx(name) for name in spec_names] + + return tuple(value) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/grad_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/grad_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..09125623e16a5478b8857019b2834ef38522786f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/grad_transformer.py @@ -0,0 +1,93 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function + +from paddle.utils import gast +import warnings + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static import utils +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class GradTransformer(BaseTransformer): + """ + A class transforms dygraph paddle.grad to static graph paddle.gradients. The + transformation is applied to support double grad mode. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of GradTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_Call(self, node): + self.generic_visit(node) + if not is_grad_api_node(node): + return node + + dygraph_grad_parameters = [ + "outputs", "inputs", "grad_outputs", "retain_graph", "create_graph", + "only_inputs", "allow_unused", "no_grad_vars" + ] + to_static_grad_param = { + "outputs": "targets", + "inputs": "inputs", + "grad_outputs": "target_gradients", + "no_grad_vars": "no_grad_set" + } + static_keywords = [] + + for kw in node.keywords: + if kw.arg not in dygraph_grad_parameters or kw.arg not in to_static_grad_param: + warnings.warn("paddle.grad has unsupported parameter in jit: " + + kw.arg + ", jit will discard it") + continue + dygraph_grad_parameters.remove(kw.arg) + kw.arg = to_static_grad_param[kw.arg] + static_keywords.append(kw) + + for i in range(len(node.args)): + arg_name = dygraph_grad_parameters[i] + if arg_name not in to_static_grad_param: + warnings.warn("paddle.grad has unsupported parameter in jit: " + + kw.arg + ", jit will discard it") + continue + kw = gast.keyword(arg=to_static_grad_param[arg_name], + value=node.args[i]) + static_keywords.append(kw) + + node.func = gast.parse('paddle.static.gradients').body[0].value + node.keywords = static_keywords + node.args = [] + return node + + +def is_grad_api_node(node): + assert isinstance(node, gast.Call) + api_name = utils.ast_to_source_code(node.func).strip() + if utils.is_paddle_api(node): + if 'no_grad' in api_name: + warnings.warn( + "paddle.no_grad is only supported for inference model, and not supported for training under @to_static." + ) + return False + return api_name.endswith("grad") + return False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ifelse_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ifelse_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c64daa2fdc4f5180639288b628fef2820361ccc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/ifelse_transformer.py @@ -0,0 +1,395 @@ +# 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. + +from __future__ import print_function + +import six +import copy +import textwrap +from collections import defaultdict + +# gast is a generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST). +# It provides a compatibility layer between the AST of various Python versions, +# as produced by ast.parse from the standard ast module. +# See details in https://github.com/serge-sans-paille/gast/ +from paddle.utils import gast +from paddle.fluid import unique_name + +from paddle.fluid.dygraph.dygraph_to_static.utils import create_funcDef_node, ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import create_assign_node, FunctionNameLivenessAnalysis +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import StaticAnalysisVisitor +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import create_undefined_var +from paddle.fluid.dygraph.dygraph_to_static.utils import create_nonlocal_stmt_nodes +from paddle.fluid.dygraph.dygraph_to_static.utils import create_get_args_node, create_set_args_node +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.utils import FOR_ITER_INDEX_PREFIX, FOR_ITER_TUPLE_PREFIX, FOR_ITER_TUPLE_INDEX_PREFIX, FOR_ITER_VAR_LEN_PREFIX, FOR_ITER_VAR_NAME_PREFIX, FOR_ITER_ZIP_TO_LIST_PREFIX, FOR_ITER_TARGET_PREFIX, FOR_ITER_ITERATOR_PREFIX +from paddle.fluid.dygraph.dygraph_to_static.utils import GetterSetterHelper, create_name_str + +TRUE_FUNC_PREFIX = 'true_fn' +FALSE_FUNC_PREFIX = 'false_fn' +GET_ARGS_FUNC_PREFIX = 'get_args' +SET_ARGS_FUNC_PREFIX = 'set_args' +ARGS_NAME = '__args' + + +class IfElseTransformer(BaseTransformer): + """ + Transform if/else statement of Dygraph into Static Graph. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Type of input node should be AstNodeWrapper, but received %s ." % type( + wrapper_root) + self.root = wrapper_root.node + FunctionNameLivenessAnalysis( + self.root) # name analysis of current ast tree. + + def transform(self): + """ + Main function to transform AST. + """ + self.visit(self.root) + + def visit_If(self, node): + self.generic_visit(node) + true_func_node, false_func_node, get_args_node, set_args_node, return_name_ids, push_pop_ids = transform_if_else( + node, self.root) + + new_node = create_convert_ifelse_node(return_name_ids, push_pop_ids, + node.test, true_func_node, + false_func_node, get_args_node, + set_args_node) + + return [get_args_node, set_args_node, true_func_node, false_func_node + ] + [new_node] + + def visit_Call(self, node): + # Remove `numpy()` statement, like `Tensor.numpy()[i]` -> `Tensor[i]` + if isinstance(node.func, gast.Attribute): + attribute = node.func + if attribute.attr == 'numpy': + node = attribute.value + self.generic_visit(node) + return node + + def visit_IfExp(self, node): + """ + Transformation with `true_fn(x) if Tensor > 0 else false_fn(x)` + """ + self.generic_visit(node) + + new_node = create_convert_ifelse_node(None, None, node.test, node.body, + node.orelse, None, None, True) + # Note: A blank line will be added separately if transform gast.Expr + # into source code. Using gast.Expr.value instead to avoid syntax error + # in python. + if isinstance(new_node, gast.Expr): + new_node = new_node.value + + return new_node + + +class NameVisitor(gast.NodeVisitor): + + def __init__(self, after_node=None, end_node=None): + # The start node (exclusive) of the visitor + self.after_node = after_node + # The terminate node of the visitor. + self.end_node = end_node + # Dict to store the names and ctxs of vars. + self.name_ids = defaultdict(list) + # List of current visited nodes + self.ancestor_nodes = [] + # True when in range (after_node, end_node). + self._in_range = after_node is None + self._candidate_ctxs = (gast.Store, gast.Load, gast.Param) + self._def_func_names = set() + + def visit(self, node): + """Visit a node.""" + if self.after_node is not None and node == self.after_node: + self._in_range = True + return + if node == self.end_node: + self._in_range = False + return + + self.ancestor_nodes.append(node) + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + ret = visitor(node) + self.ancestor_nodes.pop() + + return ret + + def visit_If(self, node): + """ + For nested `if/else`, the created vars are not always visible for parent node. + In addition, the vars created in `if.body` are not visible for `if.orelse`. + + Case 1: + x = 1 + if m > 1: + res = new_tensor + res = res + 1 # Error, `res` is not visible here. + + Case 2: + if x_tensor > 0: + res = new_tensor + else: + res = res + 1 # Error, `res` is not visible here. + + In above two cases, we should consider to manage the scope of vars to parsing + the arguments and returned vars correctly. + """ + if not self._in_range or not self.end_node: + self.generic_visit(node) + return + else: + before_if_name_ids = copy.deepcopy(self.name_ids) + body_name_ids = self._visit_child(node.body) + # If traversal process stops early in `if.body`, return the currently seen name_ids. + if not self._in_range: + self._update_name_ids(before_if_name_ids) + else: + else_name_ids = self._visit_child(node.orelse) + # If traversal process stops early in `if.orelse`, return the currently seen name_ids. + if not self._in_range: + self._update_name_ids(before_if_name_ids) + else: + # Blocks the vars in `if.body` and only inserts the vars both created in 'if/else' branch + # into name_ids. + new_name_ids = self._find_new_name_ids( + body_name_ids, else_name_ids) + for new_name_id in new_name_ids: + before_if_name_ids[new_name_id].append(gast.Store()) + + self.name_ids = before_if_name_ids + + def visit_Attribute(self, node): + if not self._in_range or not self._is_call_func_name_node(node): + self.generic_visit(node) + + def visit_Name(self, node): + if not self._in_range: + self.generic_visit(node) + return + blacklist = {'True', 'False', 'None'} + if node.id in blacklist: return + if node.id in self._def_func_names: + return + if not self._is_call_func_name_node(node): + if isinstance(node.ctx, self._candidate_ctxs): + self.name_ids[node.id].append(node.ctx) + + def visit_Assign(self, node): + if not self._in_range: + self.generic_visit(node) + return + # Visit `value` firstly. + node._fields = ('value', 'targets') + self.generic_visit(node) + + def visit_FunctionDef(self, node): + # NOTE: We skip to visit names of get_args and set_args, because they contains + # nonlocal statement such as 'nonlocal x, self' where 'self' should not be + # parsed as returned value in contron flow. + if GET_ARGS_FUNC_PREFIX in node.name or SET_ARGS_FUNC_PREFIX in node.name: + return + + if not self._in_range: + self.generic_visit(node) + return + self._def_func_names.add(node.name) + if not self.end_node: + self.generic_visit(node) + else: + before_name_ids = copy.deepcopy(self.name_ids) + self.name_ids = defaultdict(list) + self.generic_visit(node) + + if not self._in_range: + self._update_name_ids(before_name_ids) + else: + self.name_ids = before_name_ids + + def _visit_child(self, node): + self.name_ids = defaultdict(list) + if isinstance(node, list): + for item in node: + if isinstance(item, gast.AST): + self.visit(item) + elif isinstance(node, gast.AST): + self.visit(node) + + return copy.deepcopy(self.name_ids) + + def _find_new_name_ids(self, body_name_ids, else_name_ids): + + def is_required_ctx(ctxs, required_ctx): + for ctx in ctxs: + if isinstance(ctx, required_ctx): + return True + return False + + candidate_name_ids = set(body_name_ids.keys()) & set( + else_name_ids.keys()) + store_ctx = gast.Store + new_name_ids = set() + for name_id in candidate_name_ids: + if is_required_ctx(body_name_ids[name_id], + store_ctx) and is_required_ctx( + else_name_ids[name_id], store_ctx): + new_name_ids.add(name_id) + + return new_name_ids + + def _is_call_func_name_node(self, node): + white_func_names = set(['append', 'extend']) + if len(self.ancestor_nodes) > 1: + assert self.ancestor_nodes[-1] == node + parent_node = self.ancestor_nodes[-2] + if isinstance(parent_node, gast.Call) and parent_node.func == node: + # e.g: var_list.append(elem), var_list is also a name_id. + should_skip = isinstance( + node, gast.Attribute) and node.attr in white_func_names + if not should_skip: + return True + return False + + def _update_name_ids(self, new_name_ids): + for name_id, ctxs in six.iteritems(new_name_ids): + self.name_ids[name_id] = ctxs + self.name_ids[name_id] + + +def _valid_nonlocal_names(return_name_ids, nonlocal_names): + """ + All var in return_name_ids should be in nonlocal_names. + Moreover, we will always put return_name_ids in front of nonlocal_names. + + For Example: + + return_name_ids: [x, y] + nonlocal_names : [a, y, b, x] + + Return: + nonlocal_names : [x, y, a, b] + """ + assert isinstance(return_name_ids, list) + for name in return_name_ids: + if name not in nonlocal_names: + raise ValueError( + "Required returned var '{}' must be in 'nonlocal' statement '', but not found." + .format(name)) + nonlocal_names.remove(name) + + return return_name_ids + nonlocal_names + + +def transform_if_else(node, root): + """ + Transform ast.If into control flow statement of Paddle static graph. + """ + + # TODO(liym27): Consider variable like `self.a` modified in if/else node. + return_name_ids = sorted(list(node.pd_scope.modified_vars())) + push_pop_ids = sorted(list(node.pd_scope.variadic_length_vars())) + nonlocal_names = list(return_name_ids) + nonlocal_names.sort() + # NOTE: All var in return_name_ids should be in nonlocal_names. + nonlocal_names = _valid_nonlocal_names(return_name_ids, nonlocal_names) + + # TODO(dev): Need a better way to deal this. + # LoopTransformer will create some special vars, which is not visiable by users. so we can sure it's safe to remove them. + filter_names = [ + ARGS_NAME, FOR_ITER_INDEX_PREFIX, FOR_ITER_TUPLE_PREFIX, + FOR_ITER_TARGET_PREFIX, FOR_ITER_ITERATOR_PREFIX, + FOR_ITER_TUPLE_INDEX_PREFIX, FOR_ITER_VAR_LEN_PREFIX, + FOR_ITER_VAR_NAME_PREFIX, FOR_ITER_ZIP_TO_LIST_PREFIX + ] + + def remove_if(x): + for name in filter_names: + if x.startswith(name): return False + return True + + nonlocal_names = list(filter(remove_if, nonlocal_names)) + return_name_ids = nonlocal_names + + nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names) + + empty_arg_node = gast.arguments(args=[], + posonlyargs=[], + vararg=None, + kwonlyargs=[], + kw_defaults=None, + kwarg=None, + defaults=[]) + + true_func_node = create_funcDef_node( + nonlocal_stmt_node + node.body, + name=unique_name.generate(TRUE_FUNC_PREFIX), + input_args=empty_arg_node, + return_name_ids=[]) + false_func_node = create_funcDef_node( + nonlocal_stmt_node + node.orelse, + name=unique_name.generate(FALSE_FUNC_PREFIX), + input_args=empty_arg_node, + return_name_ids=[]) + + helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_ids) + get_args_node = create_get_args_node(helper.union()) + set_args_node = create_set_args_node(helper.union()) + + return true_func_node, false_func_node, get_args_node, set_args_node, return_name_ids, push_pop_ids + + +def create_convert_ifelse_node(return_name_ids, + push_pop_ids, + pred, + true_func, + false_func, + get_args_func, + set_args_func, + is_if_expr=False): + """ + Create `paddle.jit.dy2static.convert_ifelse( + pred, true_fn, false_fn, get_args, set_args, return_name_ids)` + to replace original `python if/else` statement. + """ + if is_if_expr: + true_func_source = "lambda : {}".format(ast_to_source_code(true_func)) + false_func_source = "lambda : {}".format(ast_to_source_code(false_func)) + else: + true_func_source = true_func.name + false_func_source = false_func.name + + convert_ifelse_layer = gast.parse( + '_jst.IfElse(' + '{pred}, {true_fn}, {false_fn}, {get_args}, {set_args}, {return_name_ids}, push_pop_names={push_pop_ids})' + .format( + pred=ast_to_source_code(pred), + true_fn=true_func_source, + false_fn=false_func_source, + get_args=get_args_func.name if not is_if_expr else + 'lambda: None', #TODO: better way to deal with this + set_args=set_args_func.name + if not is_if_expr else 'lambda args: None', + return_name_ids=create_name_str(return_name_ids), + push_pop_ids=create_name_str(push_pop_ids))).body[0] + + return convert_ifelse_layer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/list_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/list_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..33ec9b9be73e5afb81e040df480dae78f28540f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/list_transformer.py @@ -0,0 +1,258 @@ +# 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. + +from __future__ import print_function + +import astor +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper, StaticAnalysisVisitor +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import slice_is_num +from paddle.fluid.dygraph.dygraph_to_static.utils import is_control_flow_to_transform +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class ListTransformer(BaseTransformer): + """ + This class transforms python list used in control flow into Static Graph Ast. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of ListTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + self.list_name_to_updated = dict() + self.list_nodes = set() + + self.static_analysis_visitor = StaticAnalysisVisitor(self.root) + self.node_to_wrapper_map = self.static_analysis_visitor.get_node_to_wrapper_map( + ) + var_env = self.static_analysis_visitor.get_var_env() + var_env.cur_scope = var_env.cur_scope.sub_scopes[0] + self.scope_var_type_dict = var_env.get_scope_var_type() + + def transform(self): + self.visit(self.root) + self.replace_list_with_tensor_array(self.root) + + def visit_Call(self, node): + if isinstance(node.func, gast.Attribute): + func_name = node.func.attr + if func_name == "pop": + node = self._replace_pop(node) + return node + + def visit_Assign(self, node): + if self._update_list_name_to_updated(node): + return node + + if self._need_to_array_write_node(node): + return self._transform_slice_to_tensor_write(node) + + self.generic_visit(node) + return node + + def visit_If(self, node): + self.generic_visit(node) + if is_control_flow_to_transform(node, self.static_analysis_visitor, + self.scope_var_type_dict): + self._transform_list_append_in_control_flow(node) + return node + + def visit_While(self, node): + self.generic_visit(node) + if is_control_flow_to_transform(node, self.static_analysis_visitor, + self.scope_var_type_dict): + self._transform_list_append_in_control_flow(node) + return node + + def visit_For(self, node): + self.generic_visit(node) + if is_control_flow_to_transform(node, self.static_analysis_visitor, + self.scope_var_type_dict): + self._transform_list_append_in_control_flow(node) + return node + + def replace_list_with_tensor_array(self, node): + for child_node in gast.walk(node): + if isinstance(child_node, gast.Assign): + if self._need_to_create_tensor_array(child_node): + child_node.value = self._create_tensor_array( + child_node.value) + + def _transform_list_append_in_control_flow(self, node): + for child_node in gast.walk(node): + if self._need_to_array_write_node(child_node): + child_node.value = \ + self._to_array_write_node(child_node.value) + + def _need_to_array_write_node(self, node): + if isinstance(node, gast.Expr): + if isinstance(node.value, gast.Call): + if self._is_list_append_tensor(node.value): + return True + + if isinstance(node, gast.Assign): + target_node = node.targets[0] + if isinstance(target_node, gast.Subscript): + list_name = ast_to_source_code(target_node.value).strip() + if list_name in self.list_name_to_updated: + if self.list_name_to_updated[list_name] == True: + return True + return False + + def _transform_slice_to_tensor_write(self, node): + assert isinstance(node, gast.Assign) + target_node = node.targets[0] + + target_name = target_node.value.id + slice_node = target_node.slice + + if isinstance(slice_node, gast.Slice): + pass + elif slice_is_num(target_node): + value_code = ast_to_source_code(node.value) + i = "paddle.cast(" \ + "x=_jst.to_static_variable({})," \ + "dtype='int64')".format(ast_to_source_code(slice_node)) + assign_code = "{} = paddle.tensor.array_write(x={}, i={}, array={})" \ + .format(target_name, value_code, i, target_name) + assign_node = gast.parse(assign_code).body[0] + return assign_node + + def _is_list_append_tensor(self, node): + """ + a.append(b): a is list, b is Tensor + self.x.append(b): self.x is list, b is Tensor + """ + assert isinstance(node, gast.Call) + # 1. The func is `append`. + if not isinstance(node.func, gast.Attribute): + return False + if node.func.attr != 'append': + return False + + # 2. It's a `python list` to call append(). + value_name = astor.to_source(gast.gast_to_ast(node.func.value)).strip() + if value_name not in self.list_name_to_updated: + return False + + # 3. The number of arg of append() is one + # Only one argument is supported in Python list.append() + if len(node.args) != 1: + return False + + # TODO(liym27): The arg of append() should be Tensor. But because the type of arg is often wrong with static analysis, + # the arg is not required to be Tensor here. + # 4. The arg of append() is Tensor + # arg = node.args[0] + # if isinstance(arg, gast.Name): + # # TODO: `arg.id` may be not in scope_var_type_dict if `arg.id` is the arg of decorated function + # # Need a better way to confirm whether `arg.id` is a Tensor. + # try: + # var_type_set = self.scope_var_type_dict[arg.id] + # except KeyError: + # return False + # if NodeVarType.NUMPY_NDARRAY in var_type_set: + # return False + # if NodeVarType.TENSOR not in var_type_set and NodeVarType.PADDLE_RETURN_TYPES not in var_type_set: + # return False + # # TODO: Consider that `arg` may be a gast.Call about Paddle Api. eg: list_a.append(paddle.reshape(x)) + # # else: + # # return True + self.list_name_to_updated[value_name.strip()] = True + return True + + def _need_to_create_tensor_array(self, node): + assert isinstance(node, gast.Assign) + target_node = node.targets[0] + try: + target_id = target_node.id + except AttributeError: + return False + if self.list_name_to_updated.get(target_id) and node in self.list_nodes: + return True + return False + + def _create_tensor_array(self, value_node): + # Although `dtype='float32'`, other types such as `int32` can also be supported + init_value = ast_to_source_code(value_node).strip() + func_code = "paddle.tensor.create_array('float32', {})".format( + init_value) + func_node = gast.parse(func_code).body[0].value + return func_node + + def _to_array_write_node(self, node): + assert isinstance(node, gast.Call) + array = astor.to_source(gast.gast_to_ast(node.func.value)) + x = astor.to_source(gast.gast_to_ast(node.args[0])) + i = "paddle.tensor.array_length({})".format(array) + func_code = "paddle.tensor.array_write(x={}, i={}, array={})".format( + x, i, array) + return gast.parse(func_code).body[0].value + + def _update_list_name_to_updated(self, node): + assert isinstance(node, gast.Assign) + target_node = node.targets[0] + # NOTE: Code like `x, y = a, []` has been transformed to `x=a; y=[]` + try: + target_id = target_node.id + except AttributeError: + return False + value_node = node.value + if isinstance(value_node, gast.List): + self.list_name_to_updated[target_id] = False + self.list_nodes.add(node) + return True + elif target_id in self.list_name_to_updated and \ + self.list_name_to_updated[target_id] == False: + del self.list_name_to_updated[target_id] + return False + + def _replace_pop(self, node): + """ + Replace a pop statement for a list or dict. + For example: + + list_a = [0,1,2,3,4] + x = list_a.pop() # --> convert_pop(list_a) + y = list_a.pop(1) # --> convert_pop(list_a, 1) + + dict_a = {"red":0, "blue":1, "yellow":2} + m = dict_a.pop("red") # --> convert_pop(dict_a, "red") + n = dict_a.pop("black", 3) # --> convert_pop(dict_a, "black", 3) + + """ + assert isinstance(node, gast.Call) + assert isinstance(node.func, gast.Attribute) + + target_node = node.func.value + target_str = ast_to_source_code(target_node).strip() + + args_str = [ast_to_source_code(arg).strip() for arg in node.args] + + # NOTE(liym27): + # 1. pop stmt for a list if len(args_str) == 0 + # 2. pop stmt for a list or dict if len(args_str) == 1 + # 3. pop stmt for a dict if len(args_str) == 2 + if len(args_str) <= 2: + new_pop_str = "_jst.Pop({}, {})"\ + .format(target_str, ",".join(args_str)) + new_pop_node = gast.parse(new_pop_str).body[0].value + return new_pop_node + else: + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logging_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae10997c8e7f0c324ddf931f1f40f124c8782e9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logging_utils.py @@ -0,0 +1,276 @@ +# 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. + +import os +import threading + +import six +from paddle.fluid import log_helper +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code + +__all__ = ["TranslatorLogger", "set_verbosity", "set_code_level"] + +VERBOSITY_ENV_NAME = 'TRANSLATOR_VERBOSITY' +CODE_LEVEL_ENV_NAME = 'TRANSLATOR_CODE_LEVEL' +DEFAULT_VERBOSITY = -1 +DEFAULT_CODE_LEVEL = -1 + +LOG_AllTransformer = 100 + + +def synchronized(func): + + def wrapper(*args, **kwargs): + with threading.Lock(): + return func(*args, **kwargs) + + return wrapper + + +class TranslatorLogger(object): + """ + class for Logging and debugging during the tranformation from dygraph to static graph. + The object of this class is a singleton. + """ + + @synchronized + def __new__(cls, *args, **kwargs): + if not hasattr(cls, '_instance'): + cls._instance = object.__new__(cls, *args, **kwargs) + cls._instance._initialized = False + return cls._instance + + def __init__(self): + if self._initialized: + return + + self._initialized = True + self.logger_name = "Dynamic-to-Static" + self._logger = log_helper.get_logger( + self.logger_name, + 1, + fmt='%(asctime)s %(name)s %(levelname)s: %(message)s') + self._verbosity_level = None + self._transformed_code_level = None + self._need_to_echo_log_to_stdout = None + self._need_to_echo_code_to_stdout = None + + @property + def logger(self): + return self._logger + + @property + def verbosity_level(self): + if self._verbosity_level is not None: + return self._verbosity_level + else: + return int(os.getenv(VERBOSITY_ENV_NAME, DEFAULT_VERBOSITY)) + + @verbosity_level.setter + def verbosity_level(self, level): + self.check_level(level) + self._verbosity_level = level + + @property + def transformed_code_level(self): + if self._transformed_code_level is not None: + return self._transformed_code_level + else: + return int(os.getenv(CODE_LEVEL_ENV_NAME, DEFAULT_CODE_LEVEL)) + + @transformed_code_level.setter + def transformed_code_level(self, level): + self.check_level(level) + self._transformed_code_level = level + + @property + def need_to_echo_log_to_stdout(self): + if self._need_to_echo_log_to_stdout is not None: + return self._need_to_echo_log_to_stdout + return False + + @need_to_echo_log_to_stdout.setter + def need_to_echo_log_to_stdout(self, log_to_stdout): + assert isinstance(log_to_stdout, (bool, type(None))) + self._need_to_echo_log_to_stdout = log_to_stdout + + @property + def need_to_echo_code_to_stdout(self): + if self._need_to_echo_code_to_stdout is not None: + return self._need_to_echo_code_to_stdout + return False + + @need_to_echo_code_to_stdout.setter + def need_to_echo_code_to_stdout(self, code_to_stdout): + assert isinstance(code_to_stdout, (bool, type(None))) + self._need_to_echo_code_to_stdout = code_to_stdout + + def check_level(self, level): + if isinstance(level, (six.integer_types, type(None))): + rv = level + else: + raise TypeError("Level is not an integer: {}".format(level)) + return rv + + def has_code_level(self, level): + level = self.check_level(level) + return level == self.transformed_code_level + + def has_verbosity(self, level): + """ + Checks whether the verbosity level set by the user is greater than or equal to the log level. + Args: + level(int): The level of log. + Returns: + True if the verbosity level set by the user is greater than or equal to the log level, otherwise False. + """ + level = self.check_level(level) + return self.verbosity_level >= level + + def error(self, msg, *args, **kwargs): + self.logger.error(msg, *args, **kwargs) + if self.need_to_echo_log_to_stdout: + self._output_to_stdout('ERROR: ' + msg, *args) + + def warn(self, msg, *args, **kwargs): + if self.verbosity_level != -1: + self.logger.warning(msg, *args, **kwargs) + if self.need_to_echo_log_to_stdout: + self._output_to_stdout('WARNING: ' + msg, *args) + + def log(self, level, msg, *args, **kwargs): + if self.has_verbosity(level): + msg_with_level = '(Level {}) {}'.format(level, msg) + self.logger.info(msg_with_level, *args, **kwargs) + if self.need_to_echo_log_to_stdout: + self._output_to_stdout('INFO: ' + msg_with_level, *args) + + def log_transformed_code(self, level, ast_node, transformer_name, *args, + **kwargs): + if self.has_code_level(level): + source_code = ast_to_source_code(ast_node) + if level == LOG_AllTransformer: + header_msg = "After the last level ast transformer: '{}', the transformed code:\n" \ + .format(transformer_name) + else: + header_msg = "After the level {} ast transformer: '{}', the transformed code:\n"\ + .format(level, transformer_name) + + msg = header_msg + source_code + self.logger.info(msg, *args, **kwargs) + + if self.need_to_echo_code_to_stdout: + self._output_to_stdout('INFO: ' + msg, *args) + + def _output_to_stdout(self, msg, *args): + msg = self.logger_name + ' ' + msg + print(msg % args) + + +_TRANSLATOR_LOGGER = TranslatorLogger() + + +def set_verbosity(level=0, also_to_stdout=False): + """ + Sets the verbosity level of log for dygraph to static graph. Logs can be output to stdout by setting `also_to_stdout`. + + There are two means to set the logging verbosity: + + 1. Call function `set_verbosity` + + 2. Set environment variable `TRANSLATOR_VERBOSITY` + + + **Note**: + `set_verbosity` has a higher priority than the environment variable. + + Args: + level(int): The verbosity level. The larger value idicates more verbosity. + The default value is 0, which means no logging. + also_to_stdout(bool): Whether to also output log messages to `sys.stdout`. + + Examples: + .. code-block:: python + + import os + import paddle + + paddle.jit.set_verbosity(1) + # The verbosity level is now 1 + + os.environ['TRANSLATOR_VERBOSITY'] = '3' + # The verbosity level is now 3, but it has no effect because it has a lower priority than `set_verbosity` + """ + _TRANSLATOR_LOGGER.verbosity_level = level + _TRANSLATOR_LOGGER.need_to_echo_log_to_stdout = also_to_stdout + + +def get_verbosity(): + return _TRANSLATOR_LOGGER.verbosity_level + + +def set_code_level(level=LOG_AllTransformer, also_to_stdout=False): + """ + Sets the level to print code from specific level Ast Transformer. Code can be output to stdout by setting `also_to_stdout`. + + There are two means to set the code level: + + 1. Call function `set_code_level` + + 2. Set environment variable `TRANSLATOR_CODE_LEVEL` + + + **Note**: + `set_code_level` has a higher priority than the environment variable. + + Args: + level(int): The level to print code. Default is 100, which means to print the code after all AST Transformers. + also_to_stdout(bool): Whether to also output code to `sys.stdout`. + + Examples: + .. code-block:: python + + import paddle + + paddle.jit.set_code_level(2) + # It will print the transformed code at level 2, which means to print the code after second transformer, + # as the date of August 28, 2020, it is CastTransformer. + + os.environ['TRANSLATOR_CODE_LEVEL'] = '3' + # The code level is now 3, but it has no effect because it has a lower priority than `set_code_level` + + """ + _TRANSLATOR_LOGGER.transformed_code_level = level + _TRANSLATOR_LOGGER.need_to_echo_code_to_stdout = also_to_stdout + + +def get_code_level(): + return _TRANSLATOR_LOGGER.transformed_code_level + + +def error(msg, *args, **kwargs): + _TRANSLATOR_LOGGER.error(msg, *args, **kwargs) + + +def warn(msg, *args, **kwargs): + _TRANSLATOR_LOGGER.warn(msg, *args, **kwargs) + + +def log(level, msg, *args, **kwargs): + _TRANSLATOR_LOGGER.log(level, msg, *args, **kwargs) + + +def log_transformed_code(level, ast_node, transformer_name, *args, **kwargs): + _TRANSLATOR_LOGGER.log_transformed_code(level, ast_node, transformer_name, + *args, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logical_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logical_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3e9a56b0e74dd921b8713a1d70a758caf5355eda --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/logical_transformer.py @@ -0,0 +1,103 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + +cmpop_type_to_str = { + gast.Eq: "==", + gast.NotEq: "!=", + gast.Lt: "<", + gast.LtE: "<=", + gast.Gt: ">", + gast.GtE: ">=", + gast.Is: "is", + gast.IsNot: "is not", + gast.In: "in", + gast.NotIn: "not in" +} + + +def cmpop_node_to_str(node): + return cmpop_type_to_str[type(node)] + + +class LogicalTransformer(BaseTransformer): + """ + Transform python boolean op into Paddle logical op. + + For example: + a = x > 1 and y < 1 + + Transformed code: + a = _jst.And(lambda:x>1, lambda:y<1) + """ + + def __init__(self, wrapper_root): + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + return self.visit(self.root) + + def visit_UnaryOp(self, node): + self.generic_visit(node) + if isinstance(node.op, gast.Not): + arg = ast_to_source_code(node.operand) + new_node_str = "_jst.Not({})".format(arg) + # NOTE: gast.parse returns Module(body=[expr(value=...)]) + new_node = gast.parse(new_node_str).body[0].value + return new_node + return node + + def visit_BoolOp(self, node): + self.generic_visit(node) + if isinstance(node.op, gast.And): + new_node = self._create_bool_op_node(node.values, 'And') + elif isinstance(node.op, gast.Or): + new_node = self._create_bool_op_node(node.values, 'Or') + else: + raise TypeError( + "Only supports and/or syntax in control flow if statement.") + return new_node + + def _create_bool_op_node(self, nodes, api_type): + ''' + NOTE(liym27): + The arguments of function convert_logical_XX should be callable so that they can be run + according to the actual order. In `convert_logical_and(lambda:x>1, lambda:y<1)`, `lambda:y<1` + must be run after `lambda:x>1`, If `x>1` is False, `y<1` should NOT be run. + ''' + assert len( + nodes + ) > 1, "The length of BoolOp should be at least 2, but received {}.".format( + len(nodes)) + if len(nodes) > 2: + # Creates logic_and/logic_or node recursively. + pre_logic_node = self._create_bool_op_node(nodes[:2], api_type) + if len(nodes[2:]) == 1: + post_logic_node = nodes[2] + else: + post_logic_node = self._create_bool_op_node(nodes[2:], api_type) + nodes = [pre_logic_node] + [post_logic_node] + + args = [ast_to_source_code(child) for child in nodes] + new_node_str = "_jst.{}(lambda:{}, lambda:{})".format( + api_type, args[0], args[1]) + # NOTE: gast.parse return Module(body=[expr(...)]) + new_node = gast.parse(new_node_str).body[0].value + return new_node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..3f1914eea8f725d7bc0de81e1c7eef8cd6a2ddcf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/loop_transformer.py @@ -0,0 +1,694 @@ +# 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. + +from __future__ import print_function + +import copy +from paddle.utils import gast + +from collections import defaultdict +from paddle.fluid import unique_name +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import NodeVarType +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import StaticAnalysisVisitor +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import generate_name_node +from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import create_undefined_var +from paddle.fluid.dygraph.dygraph_to_static.utils import create_nonlocal_stmt_nodes, create_get_args_node, create_set_args_node +from paddle.fluid.dygraph.dygraph_to_static.utils import FunctionNameLivenessAnalysis +from paddle.fluid.dygraph.dygraph_to_static.ifelse_transformer import ARGS_NAME +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import RenameTransformer +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import ForLoopTuplePreTransformer +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import ForNodeVisitor +from paddle.fluid.dygraph.dygraph_to_static.utils import GetterSetterHelper, create_name_str + +__all__ = ['LoopTransformer', 'NameVisitor'] + +WHILE_CONDITION_PREFIX = 'while_condition' +WHILE_BODY_PREFIX = 'while_body' + +FOR_CONDITION_PREFIX = 'for_loop_condition' +FOR_BODY_PREFIX = 'for_loop_body' + + +def create_while_nodes(condition_name, body_name, loop_var_names, + push_pop_names, getter_name, setter_name): + """ + Returns a list of gast.Node which represents the calling of Paddle + controlflow while_loop. + + Usually, the list just contain 1 statement such as: + + [a, b, c] = paddle.jit.dy2static.convert_while_loop( + condition_name, body_name, [a, b, c]) + + where a, b, c are in loop_var_names. + + However, if loop_var_names contains property such as foo.x, we cannot + assign the property as output of convert_while_loop because Python + property is a kind of read-only attribute. To handle the case, we replace + the attributes which are output of convert_while_loop with generated + variables, then if we know the attribute is not read-only at runtime, we + assign the attribute. The created statements are like: + + [a, b, __attribute_variable_1] = paddle.jit.dy2static.convert_while_loop( + condition_name, body_name, [a, b, foo.x]) + if not isinstance(getattr(type(foo), x, None), property): foo.x = __attribute_variable_1 + + The number of above statements is not only 1, that's why the return type is + a list of gast.Node. + """ + # NOTE(liym27): + # It's better to parse the source code into an AST node than to customize an AST node + # including child nodes, because it is easy to mistake the ast node type when customizing the node. + # + # For example: loop_var_names = [a, b, foo.x], the type of `a` or `b` is gast.Name, + # but the type of `foo.x` gast.Attribute. + # We have to make loop_var_names and assign_loop_var_names with same order + # set doesn't have order so we convert it to list + loop_var_names = list(loop_var_names) + assign_loop_var_names = [] + for name in (loop_var_names): + assign_loop_var_names.append(name) + + while_func_name = "_jst.While" + while_node_str = "{}({}, {}, {}, {}, return_name_ids={}, push_pop_names={})".format( + while_func_name, condition_name, body_name, getter_name, setter_name, + create_name_str(loop_var_names), create_name_str(push_pop_names)) + while_node = gast.parse(while_node_str).body[0] + + ret = [while_node] + return ret + + +class NameVisitor(gast.NodeVisitor): + ''' + Analysis name liveness for loop transformer + ''' + + def __init__(self, root_node): + # Set of gast.Name or gast.Attribute for variables + self.current_seen_vars = set() + + # List of gast.While/gast.For nodes + self.current_loop = [] + + # List of nodes that have scope of variables. + self.nodes_with_scope = [] + self.blacklist_names = {"False", "True", "None"} + + # Mapping from gast.While/gast.For to variable nodes + self.before_loop_body_vars = defaultdict(set) + # NOTE: Use ordered list as dict value + self.in_loop_vars = defaultdict(list) + + # Mapping from gast.While/gast.For to variable nodes which is condition + # of loop or being modified during the loop + self.write_in_loop = defaultdict(set) + self.condition_vars = defaultdict(set) + self.in_condition = False + + # Some names are types, we shouldn't record them as loop var names. + self.type_vars = set() + + self.static_analysis_visitor = StaticAnalysisVisitor(root_node) + self.node_to_wrapper_map = self.static_analysis_visitor.get_node_to_wrapper_map( + ) + + self.visit(root_node) + + def get_loop_var_names(self, node): + assert isinstance( + node, (gast.While, gast.For)), "Input node is not gast loop node" + loop_var_names = set() + create_var_names = set() + read_context = {type(gast.Load()), type(gast.AugLoad())} + + in_loop_vars_list = self.in_loop_vars[node] + + # get dict `var_name_to_ctxs` + var_name_to_ctxs = defaultdict(list) + for var_node in in_loop_vars_list: + var_name_to_ctxs[self._var_node_to_name(var_node)].append( + var_node.ctx) + + in_loop_vars = set(in_loop_vars_list) + in_loop_vars = self._remove_unnecessary_vars(in_loop_vars, node) + in_loop_name_strs = self._var_nodes_to_names(in_loop_vars) + + before_loop_body_vars = self.before_loop_body_vars[node] + before_loop_body_vars = self._remove_unnecessary_vars( + before_loop_body_vars, node) + before_loop_name_strs = self._var_nodes_to_names(before_loop_body_vars) + + after_loop_vars = self.current_seen_vars - before_loop_body_vars - in_loop_vars + after_loop_vars = self._remove_unnecessary_vars(after_loop_vars, node) + after_loop_name_strs = self._var_nodes_to_names(after_loop_vars, + read_context) + condition_vars = self.condition_vars[node] + condition_names = self._var_nodes_to_names(condition_vars) + + write_vars = self.write_in_loop[node] + write_names = self._var_nodes_to_names(write_vars) + + name_to_type = {} + for var in in_loop_vars: + wrapper = self.node_to_wrapper_map[var] + name_to_type[self._var_node_to_name(var)] = wrapper.node_var_type + for name in in_loop_name_strs: + if name in before_loop_name_strs: + # If a variable is used in loop and created before loop + + # If this var is a basic variable and read-only and not + # condition var, it may not be loop_var else it should + # be in loop_var as input + if (not name in condition_names) and (not name in write_names): + continue + loop_var_names.add(name) + + elif name in after_loop_name_strs: + # If a variable is created in the while loop and read after + # loop, it should be in loop_var and we should create it + + # because name in after_loop_name must be initialized in loop + # So it is write-only, we don't have to filter read-only basic + # vars out + loop_var_names.add(name) + create_var_names.add(name) + else: + # If a variable is used and created in loop, but used before created, + # it should be in loop_var and we should create it. + + # For example, `var_a` should be in loop_var and we should create it. + # + # res = 0 + # for i, x in enumerate(x_array): + # if i > 2: + # x = func1(var_a) + # var_a = func2(x) + # + + is_created = False + for ctx in var_name_to_ctxs[name]: + if isinstance(ctx, gast.Store): + is_created = True + + if isinstance(var_name_to_ctxs[name][0], + gast.Load) and is_created: + loop_var_names.add(name) + create_var_names.add(name) + + return loop_var_names, create_var_names + + def visit_Name(self, node): + if self._is_call_func_name_node(node): + self.generic_visit(node) + return + if node.id in self.blacklist_names: + self.generic_visit(node) + return + + self.current_seen_vars.add(node) + write_context = { + type(gast.Store()), + type(gast.AugStore()), + type(gast.Del()) + } + + for loop_node in self.current_loop: + self.in_loop_vars[loop_node].append(node) + if type(node.ctx) in write_context: + self.write_in_loop[loop_node].add(node) + if self.in_condition: + self.condition_vars[loop_node].add(node) + self.generic_visit(node) + + def visit_FunctionDef(self, node): + self.nodes_with_scope.append(node) + self.blacklist_names.add(node.name) + + # The variables in the function are not visible to the outside scope. + before_func_seen_vars = copy.copy(self.current_seen_vars) + + self.generic_visit(node) + self.nodes_with_scope.pop() + # After exiting the scope of the node, variables in this scope + # should be removed from self.current_seen_vars. + if self.nodes_with_scope: + self.current_seen_vars = before_func_seen_vars + + def visit(self, node): + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + ret = visitor(node) + return ret + + def visit_Attribute(self, node): + if self._is_call_func_name_node(node): + return + attr_full_name = get_attribute_full_name(node) + # Class variables are not allowed to appear in the arguments list + # of defined function under class methods in Python. + """ + def class_func(self): + def while_loop_body(self.x, y) # `self.x` is illegal. + """ + # TODO: If do change the variable with `self.var`, need a better + # way to deal with this case. + if attr_full_name.startswith("self."): + return + self.current_seen_vars.add(node) + + for loop_node in self.current_loop: + self.in_loop_vars[loop_node].append(node) + + # sub-nodes are visited during get_attribute_full_name and we shouldn't + # visit again + + def visit_For(self, node): + self.current_loop.append(node) + self.in_condition = True + self.visit(node.target) + self.visit(node.iter) + self.in_condition = False + self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars) + self.generic_visit(node) + self.current_loop.pop() + + def visit_While(self, node): + self.current_loop.append(node) + self.in_condition = True + self.visit(node.test) + self.in_condition = False + self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars) + self.generic_visit(node) + self.current_loop.pop() + + def visit_Call(self, node): + # Store type var names such as "isinstance(x, some_type_names)" and + # Remove them later + if isinstance(node.func, gast.Name) and node.func.id == 'isinstance': + type_node = node.args[1] + if isinstance(type_node, gast.Tuple): + for element in type_node.elts: + self.type_vars.add(ast_to_source_code(element).strip()) + else: + self.type_vars.add(ast_to_source_code(type_node).strip()) + self.generic_visit(node) + + def _var_nodes_to_names(self, node_set, ctx_filter_set=None): + ret = set() + for node in node_set: + if ctx_filter_set is None or type(node.ctx) in ctx_filter_set: + ret.add(self._var_node_to_name(node)) + return ret + + def _var_node_to_name(self, node): + if isinstance(node, gast.Name): + return node.id + elif isinstance(node, gast.Attribute): + return get_attribute_full_name(node) + + def _node_var_type_is_basic(self, node_var_type): + basic_types = { + NodeVarType.BOOLEAN, NodeVarType.INT, NodeVarType.FLOAT, + NodeVarType.STRING + } + for t in node_var_type: + if t in basic_types: + return True + return False + + def _is_call_func_name_node(self, node): + parent_node = self._get_parent_node(node) + if isinstance(parent_node, gast.Call) and parent_node.func == node: + return True + return False + + def _is_global_or_nonlocal(self, node): + return False + + def _is_ancestor_node(self, ancestor_node, node): + parent_node = self._get_parent_node(node) + + while parent_node is not None: + if parent_node == ancestor_node: + return True + parent_node = self._get_parent_node(parent_node) + return False + + def _get_parent_node(self, node): + wrapper_node = self.node_to_wrapper_map.get(node) + if wrapper_node: + if wrapper_node.parent: + parent_node = wrapper_node.parent.node + return parent_node + return None + + def _remove_unnecessary_vars(self, loop_vars, loop_node): + """ + Remove unnecessary vars from before_loop_vars, after_loop_vars or in_loop_vars about loop_node. + 1. Remove target vars of gast.For from before_loop_vars or after_loop_vars. + 2. Remove vars only in gast.comprehension. + 3. Remove vars that are type names, for example: "isinstance(x, var_type_name)" + :param loop_vars: before_loop_vars, after_loop_vars or in_loop_vars of loop_node. + :param loop_node: Current loop node. + """ + + def filter_name_nodes_from(root_node, target_var_names): + """ + Filter children with gast.Name type from node.(inclusivly) + """ + name_nodes = set() + if isinstance(root_node, gast.Name): + if node.id in target_var_names: + name_nodes.add(root_node) + for child_node in gast.walk(root_node): + if isinstance(child_node, gast.Name): + if child_node.id in target_var_names: + name_nodes.add(child_node) + + return name_nodes + + vars_of_list_generator = set() + target_vars_of_for_node = set() + + for name_node in loop_vars: + if not isinstance(name_node, gast.Name): + continue + + parent_node = self._get_parent_node(name_node) + + # NOTE: gast.For.target or gast.comprehension.target can be gast.Tuple. + # For examples: + # 1) `for i, j in enumerate(x)` has two target vars: i and j + # 2) `[x for x,y in array]` has two target vars: x and y + if isinstance(parent_node, gast.Tuple): + parent_node = self._get_parent_node(parent_node) + + # 1. Get vars only in gast.comprehension. + # For examples: + # 1) [x for x,y in array] -> x, x, y + # 2) [f(x) for x in array] -> x + # 3) [func(x, y) for x in array] -> x, x + if isinstance(parent_node, gast.comprehension): + # 1.1 target vars in list/set comprehensions + target_node = parent_node.target + if isinstance(target_node, gast.Tuple): + target_vars = target_node.elts + else: + target_vars = [target_node] + + vars_of_list_generator = vars_of_list_generator | set( + target_vars) + + # 1.2 vars from target vars used in elt_node + target_var_names = {var.id for var in target_vars} + comp_node = self._get_parent_node(parent_node) + elt_nodes = [] + if isinstance(comp_node, gast.ListComp): + elt_nodes.append(comp_node.elt) + elif isinstance(comp_node, gast.DictComp): + elt_nodes.extend([comp_node.key, comp_node.value]) + + for node in elt_nodes: + vars_of_list_generator |= filter_name_nodes_from( + node, target_var_names) + + # 2. Get target vars or vars from target vars used in for-loop but the for-loop is + # 1) not the "loop_node" itself + # 2) not the ancestor of the "loop_node" + # + # For examples: + # for k in range(x): # if it's this "loop_node", i or j both should be target vars. + # # do something + # + # for i in range(a): # if it's this "loop_node", k or j should be in target vars but i should not. + # for j in range(a): # if it's this "loop_node", k should be in target_vars but i or j should not. + # x = i+j + elif isinstance(parent_node, gast.For): + if parent_node is loop_node: + continue + if self._is_ancestor_node(parent_node, loop_node): + continue + # 2.1 target vars in gast.For node. + target_node = parent_node.target + if isinstance(target_node, gast.Tuple): + target_vars = target_node.elts + else: + target_vars = [target_node] + + target_vars_of_for_node = target_vars_of_for_node | set( + target_vars) + + # 2.2 vars from target vars used in for-loop + target_vars_name_strs = {var.id for var in target_vars_of_for_node} + for var in loop_vars: + if not isinstance(var, gast.Name): + continue + if var.id in target_vars_name_strs and var not in self.condition_vars[ + loop_node]: + target_vars_of_for_node.add(var) + + removed_vars = target_vars_of_for_node | vars_of_list_generator + + # 3. Remove var type names which are stored in self.type_vars + for var in loop_vars: + if ast_to_source_code(var).strip() in self.type_vars: + removed_vars.add(var) + + return loop_vars - removed_vars + + +class LoopTransformer(BaseTransformer): + """ + This class transforms python while/for statement into Static Graph Ast + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of LoopTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + FunctionNameLivenessAnalysis(self.root) + + def transform(self): + ForLoopTuplePreTransformer(self.wrapper_root).transform() + self.visit(self.root) + + def visit_While(self, node): + self.generic_visit(node) + new_stmts = self.get_while_stmt_nodes(node) + return new_stmts + + def visit_For(self, node): + self.generic_visit(node) + new_stmts = self.get_for_stmt_nodes(node) + return new_stmts + + def replace_stmt_list(self, body_list): + if not isinstance(body_list, list): + return + + i = 0 + while i < len(body_list): + if isinstance(body_list[i], gast.While): + new_stmts = self.get_while_stmt_nodes(body_list[i]) + body_list[i:i + 1] = new_stmts + i += len(new_stmts) + elif isinstance(body_list[i], gast.For): + new_stmts = self.get_for_stmt_nodes(body_list[i]) + body_list[i:i + 1] = new_stmts + i += len(new_stmts) + else: + i += 1 + + def get_for_stmt_nodes(self, node): + # TODO: consider for - else in python + + # 1. get key statements for different cases + # NOTE 1: three key statements: + # 1). init_stmts: list[node], prepare nodes of for loop, may not only one + # 2). cond_stmt: node, condition node to judge whether continue loop + # 3). body_stmts: list[node], updated loop body, sometimes we should change + # the original statement in body, not just append new statement + # + # NOTE 2: The following `for` statements will be transformed to `while` statements: + # 1). for x in range(*) + # 2). for x in iter_var + # 3). for i, x in enumerate(*) + + current_for_node_parser = ForNodeVisitor(node) + stmts_tuple = current_for_node_parser.parse() + if stmts_tuple is None: + return [node] + init_stmts, cond_stmt, body_stmts = stmts_tuple + # 2. get original loop vars + loop_var_names, create_var_names = node.pd_scope.modified_vars( + ), node.pd_scope.created_vars() + push_pop_names = list(node.pd_scope.variadic_length_vars()) + # TODO: Remove the bunch of code? We have the unique format `for A in B:` + # NOTE: in 'for x in var' or 'for i, x in enumerate(var)' cases, + # we need append new loop var & remove useless loop var + # 1. for x in var -> x is no need + # 2. for i, x in enumerate(var) -> x is no need + if current_for_node_parser.is_for_iter(): + iter_var_name = current_for_node_parser.iter_var_name + iter_idx_name = current_for_node_parser.iter_idx_name + loop_var_names.add(iter_idx_name) + if current_for_node_parser.enum_idx_name is not None: + loop_var_names.add(current_for_node_parser.enum_idx_name) + + # 3. prepare result statement list + new_stmts = [] + # Python can create variable in loop and use it out of loop, E.g. + # + # for x in range(10): + # y += x + # print(x) # x = 10 + # + # We don't need to create static variable for them, because + # we do this in CreateUndefinedVarTransformer + + # create non-local statement for body and cond. + nonlocal_names = list(loop_var_names | create_var_names) + nonlocal_names.sort() + # TODO(dev): Need a better way to deal this. + if ARGS_NAME in nonlocal_names: + nonlocal_names.remove(ARGS_NAME) + + nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names) + + # 4. append init statements + new_stmts.extend(init_stmts) + + # 5. create & append condition function node + condition_func_node = gast.FunctionDef( + name=unique_name.generate(FOR_CONDITION_PREFIX), + args=gast.arguments(args=[], + posonlyargs=[], + vararg=None, + kwonlyargs=[], + kw_defaults=None, + kwarg=None, + defaults=[]), + body=nonlocal_stmt_node + [gast.Return(value=cond_stmt)], + decorator_list=[], + returns=None, + type_comment=None) + new_stmts.append(condition_func_node) + + # 6. create & append loop body function node + # append return values for loop body + body_func_node = gast.FunctionDef( + name=unique_name.generate(FOR_BODY_PREFIX), + args=gast.arguments(args=[], + posonlyargs=[], + vararg=None, + kwonlyargs=[], + kw_defaults=None, + kwarg=None, + defaults=[]), + body=nonlocal_stmt_node + body_stmts, + decorator_list=[], + returns=None, + type_comment=None) + new_stmts.append(body_func_node) + + helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names) + get_args_node = create_get_args_node(helper.union()) + set_args_node = create_set_args_node(helper.union()) + # 7. create & append while loop node + while_loop_nodes = create_while_nodes(condition_func_node.name, + body_func_node.name, + nonlocal_names, push_pop_names, + get_args_node.name, + set_args_node.name) + new_stmts.extend([get_args_node, set_args_node]) + new_stmts.extend(while_loop_nodes) + + return new_stmts + + def get_while_stmt_nodes(self, node): + loop_var_names, create_var_names = node.pd_scope.modified_vars( + ), node.pd_scope.created_vars() + push_pop_names = list(node.pd_scope.variadic_length_vars()) + new_stmts = [] + + # create non-local statement for body and cond. + nonlocal_names = list(loop_var_names | create_var_names) + nonlocal_names.sort() + # TODO(dev): Need a better way to deal this. + if ARGS_NAME in nonlocal_names: + nonlocal_names.remove(ARGS_NAME) + + nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names) + + # Python can create variable in loop and use it out of loop, E.g. + # + # while x < 10: + # x += 1 + # y = x + # z = y + # + # We don't need to create static variable for those variables, because + # we do this in CreateUndefinedVarTransformer + + condition_func_node = gast.FunctionDef( + name=unique_name.generate(WHILE_CONDITION_PREFIX), + args=gast.arguments(args=[], + posonlyargs=[], + vararg=None, + kwonlyargs=[], + kw_defaults=None, + kwarg=None, + defaults=[]), + body=nonlocal_stmt_node + [gast.Return(value=node.test)], + decorator_list=[], + returns=None, + type_comment=None) + + new_stmts.append(condition_func_node) + + new_body = node.body + body_func_node = gast.FunctionDef( + name=unique_name.generate(WHILE_BODY_PREFIX), + args=gast.arguments(args=[], + posonlyargs=[], + vararg=None, + kwonlyargs=[], + kw_defaults=None, + kwarg=None, + defaults=[]), + body=nonlocal_stmt_node + new_body, + decorator_list=[], + returns=None, + type_comment=None) + new_stmts.append(body_func_node) + + helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names) + get_args_node = create_get_args_node(helper.union()) + set_args_node = create_set_args_node(helper.union()) + + while_loop_nodes = create_while_nodes(condition_func_node.name, + body_func_node.name, + nonlocal_names, push_pop_names, + get_args_node.name, + set_args_node.name) + new_stmts.extend([get_args_node, set_args_node]) + new_stmts.extend(while_loop_nodes) + return new_stmts diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/origin_info.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/origin_info.py new file mode 100644 index 0000000000000000000000000000000000000000..93f089cf8dd9da51b2d0f83fe2cbc41be182bf05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/origin_info.py @@ -0,0 +1,315 @@ +# 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. + +from __future__ import print_function + +import collections +import inspect + +from paddle.utils import gast +from paddle.fluid import core +from paddle.fluid.dygraph.dygraph_to_static.utils import unwrap +from paddle.fluid.dygraph.dygraph_to_static.utils import ORIGI_INFO +from paddle.fluid.framework import Program +try: + from collections.abc import Sequence +except: + from collections import Sequence + + +class Location(object): + """ + Location information of source code. + """ + __slots__ = ( + "filepath", + "lineno", + "col_offset", + ) + + def __init__(self, filepath, lineno, col_offset=None): + self.filepath = filepath + self.lineno = lineno + self.col_offset = col_offset + + def __str__(self): + return "location: {}:{}:{}".format(self.filepath, self.lineno, + self.col_offset) + + @property + def line_location(self): + return (self.filepath, self.lineno) + + +class OriginInfo(object): + """ + Original information of source code. + """ + __slots__ = ( + "location", + "function_name", + "source_code", + ) + + def __init__(self, location, function_name, source_code): + self.location = location + self.function_name = function_name + self.source_code = source_code + + def __str__(self): + return "{} \nsource_code: {} in function {}\n ".format( + self.location, self.source_code, self.function_name) + + def formated_message(self): + flag_for_origin_info = "(* user code *)" + return ' File "{}", line {}, in {} {}\n\t{}'.format( + self.location.filepath, self.location.lineno, self.function_name, + flag_for_origin_info, self.source_code.lstrip()) + + def as_frame(self): + return (self.location.filepath, self.location.lineno, + self.function_name, self.source_code.lstrip()) + + +class OriginInfoAttacher(gast.NodeTransformer): + """ + Attach original source information to AST node according corresponding function. + """ + + def __init__(self, root, func): + self.root = root + self.func = unwrap(func) + self.filepath = inspect.getsourcefile(self.func) + self.source_code = inspect.getsource(self.func) + self.current_func = [] + + def transform(self): + source_lines, begin_lineno = inspect.getsourcelines(self.func) + begin_line = source_lines[0] + self.col_offset = len(begin_line) - len(begin_line.lstrip()) + self.source_lines = [line.strip("\n") for line in source_lines] + self.lineno_offset = begin_lineno - 1 + self.visit(self.root) + + def visit(self, node): + if isinstance(node, gast.FunctionDef): + self.current_func.append(node) + if hasattr(node, "lineno"): + self._attach_origin_info(node) + self.generic_visit(node) + + if isinstance(node, gast.FunctionDef): + self.current_func.pop() + return node + + def _attach_origin_info(self, node): + assert isinstance(node, gast.AST) + assert hasattr(node, "lineno") + + lineno = self._abs_lineno(node) + col_offset = self._abs_col_offset(node) + loc = Location(self.filepath, lineno, col_offset) + func_name = self.current_func[-1].name + code_line = self.source_lines[node.lineno - 1] + + origin_info = OriginInfo(loc, func_name, code_line) + setattr(node, ORIGI_INFO, origin_info) + + def _abs_lineno(self, node): + # NOTE(liym27): + # There are differences in ast_node.lineno between PY3.8+ and PY3.8-. + # If the first gast.FunctionDef has decorator, the lineno of gast.FunctionDef is differs. + # 1. < PY3.8 + # its lineno equals to the lineno of the first decorator node, which is not right. + # 2. >= PY3.8 + # its lineno is the actual lineno, which is right. + + return self.lineno_offset + node.lineno + + def _abs_col_offset(self, node): + return self.col_offset + node.col_offset + + +global_origin_info_map = {} + + +def create_and_update_origin_info_map(transformed_node, + static_func, + is_global=True): + """ + Creates a original information map between transformed static function and original dygraph function. + + Args: + transformed_node(gast.AST): The AST node of transformed dygraph function with attached source information of original dygraph function. + static_func(Callable): The static function transformed by dygraph function corresponding to transformed_node. + + Returns: + The original information map. + """ + + origin_info_map = {} + static_source = inspect.getsource(static_func) + static_node = gast.parse(static_source) + static_node = attach_origin_info(static_node, static_func) + + for t_node, s_node in ast_walk(transformed_node, static_node): + assert type(t_node) == type(s_node), \ + "The node types should be the same, but received type(t_node) is {}, and type(s_node) is {}." \ + .format(type(t_node), type(s_node)) + dygraph_info = getattr(t_node, ORIGI_INFO, None) + static_info = getattr(s_node, ORIGI_INFO, None) + + if dygraph_info is None or static_info is None: + continue + static_loc = static_info.location.line_location + exist_origin_info = origin_info_map.get(static_loc) + + if exist_origin_info is not None: + if exist_origin_info.location.lineno >= dygraph_info.location.lineno: + continue + if exist_origin_info.location.col_offset <= dygraph_info.location.col_offset: + continue + + origin_info_map[static_loc] = dygraph_info + + global_origin_info_map.update(origin_info_map) + if is_global: + return global_origin_info_map + + return origin_info_map + + +def attach_origin_info(ast_node, func): + """ + Attach original source information to AST node according corresponding function. + + Args: + ast_node(gast.AST): The AST node to attach original source information. + func(Callable): The corresponding function of ast_node. Parse the original information from this function. + + Returns: + An AST node attached original source information. + """ + resolver = OriginInfoAttacher(ast_node, func) + resolver.transform() + return ast_node + + +def ast_walk(transformed_node, static_node): + """ + Recursively yield all descendant nodes in the trees starting at transformed_node and static_node (including itself) in parallel. + + NOTE(liym27): + Function ast.walk is not used because it yield all descendant nodes in no specified order. + """ + + def _as_list(x): + if x is None: + return [] + return list(x) if isinstance(x, Sequence) else [x] + + transformed_node_list = _as_list(transformed_node) + static_node_list = _as_list(static_node) + + while transformed_node_list: + assert len(transformed_node_list) == len(static_node_list) + t_node = transformed_node_list.pop() + s_node = static_node_list.pop() + if type(t_node) != type(s_node): + # NOTE(liym27): + # Node types should be strictly required, but there is no strict distinction between gast.Load and gast.Param + # in the ast transformation process. + if isinstance(t_node, (gast.Load, gast.Param)) or isinstance( + s_node, (gast.Load, gast.Param)): + continue + + assert type(t_node) == type(s_node), \ + "The node types should be the same, but received type(t_node) is {}, and type(s_node) is {}."\ + .format(type(t_node), type(s_node)) + + yield t_node, s_node + + for field in t_node._fields: + t_node_child = getattr(t_node, field) + s_node_child = getattr(s_node, field) + + if isinstance(t_node_child, gast.AST): + transformed_node_list.append(t_node_child) + static_node_list.append(s_node_child) + elif isinstance(t_node_child, (list, tuple)): + assert len(t_node_child) == len(s_node_child) + for d_item, s_item in zip(t_node_child, s_node_child): + if isinstance(d_item, gast.AST): + transformed_node_list.append(d_item) + static_node_list.append(s_item) + + +def update_op_callstack_with_origin_info(program): + """ + Replaces op callstack information about transformed static code with original dygraph code. + """ + + assert isinstance(program, Program) + + def get_new_op_callstack(callstack): + """ + An example of callstack: + + File "path1/to/file.py", line 10, in func_1 + y = fluid.layers.fill_constant(x, shape=[1], dtype="int32") + File "path2/to/file.py", line 740, in fill_constant + stop_gradient=True) + File "path3/to/file.py", line 43, in append_op + return self.main_program.current_block().append_op(*args, **kwargs) + File "path4/to/file.py", line 2811, in append_op + attrs=kwargs.get("attrs", None)) + File "path5/to/file.py", line 1919, in __init__ + for frame in traceback.extract_stack(): + """ + + assert len(callstack) % 2 == 0 + for i in range(0, len(callstack), 2): + + file_line = callstack[i].lstrip(" ").split(",") + + filepath = file_line[0][6:-1] + lineno = int(file_line[1][6:]) + funcname = file_line[2][4:] + code = callstack[i + 1].lstrip(" ") + + loc = Location(filepath, lineno) + dygraph_func_info = global_origin_info_map.get(loc.line_location) + if dygraph_func_info: + filepath, lineno, funcname, code = \ + dygraph_func_info.as_frame() + + callstack[i] = ' File "{}", line {}, in {}'.format( + filepath, lineno, funcname) + callstack[i + 1] = ' {}'.format(code) + + return callstack + + op_maker = core.op_proto_and_checker_maker + callstack_var_name = op_maker.kOpCreationCallstackAttrName() + + for block in program.blocks: + for i, op in enumerate(block.ops): + if op.has_attr(callstack_var_name): + callstack = op.attr(callstack_var_name) + + callstack = get_new_op_callstack(callstack) + + op._set_attr(callstack_var_name, callstack) + + return program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/partial_program.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/partial_program.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f82c1ec9b53632882703b09ee9b5d6713a32e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/partial_program.py @@ -0,0 +1,1071 @@ +# 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. + +from __future__ import print_function +import numpy as np +import six + +import paddle +from paddle.fluid import framework, backward, core, program_guard +from paddle.fluid.executor import ( + _is_enable_standalone_executor, + _is_dy2st_enable_standalone_executor, +) +from paddle.fluid.dygraph import layers +from paddle.fluid.dygraph.base import switch_to_static_graph +from paddle.fluid.dygraph.dygraph_to_static import logging_utils +from paddle.fluid.dygraph.dygraph_to_static.return_transformer import ( + RETURN_NO_VALUE_MAGIC_NUM, +) +from paddle.fluid.layers.utils import flatten +from paddle.fluid.layers.utils import pack_sequence_as +from paddle.fluid.layers.utils import _hash_with_id +from paddle.fluid.compiler import BuildStrategy +from paddle.fluid.framework import _apply_pass +from paddle.fluid.contrib.mixed_precision.decorator import ( + AutoMixedPrecisionLists, +) +from paddle.fluid.contrib.mixed_precision.fp16_utils import ( + rewrite_program, + cast_model_to_fp16, +) +from paddle.fluid.dygraph.amp.auto_cast import ( + _in_amp_guard, + _in_pure_fp16_guard, +) +import paddle.compat as cpt +from paddle import _C_ops, _legacy_C_ops + + +class NestSequence(object): + """ + A wrapper class that easily to flatten and restore the nest structure of + given sequence. + """ + + def __init__(self, raw_input, need_check=False): + self.__raw_input = raw_input + self.__input_list = self.tolist() + self.__var_ids = self._get_var_ids() + self._check_non_variable(need_check) + + def tolist(self): + """ + Flattens the nested sequences into single list. + """ + return flatten(self.__raw_input) + + def restore(self, value_list): + """ + Restores the nested sequence from value list. + """ + assert len(self.__input_list) == len(value_list) + return pack_sequence_as(self.__raw_input, value_list) + + def _get_var_ids(self): + var_ids = [] + for idx, var in enumerate(self.__input_list): + if isinstance( + var, (framework.Variable, core.VarBase, core.eager.Tensor) + ): + var_ids.append(idx) + + return var_ids + + def _check_non_variable(self, need_check): + """ + Raises warning if output of traced function contains non-tensor type values. + """ + if need_check: + warning_types = set() + for var in self.__input_list: + if not isinstance( + var, (framework.Variable, core.VarBase, core.eager.Tensor) + ): + warning_types.add(type(var)) + if warning_types: + logging_utils.warn( + "Output of traced function contains non-tensor type values: {}. " + "Currently, We don't support to update them while training and will return " + "what we first saw. Please try to return them as tensor.".format( + list(warning_types) + ) + ) + + @property + def var_ids(self): + return self.__var_ids + + def __getitem__(self, item): + return self.__input_list[item] + + +class LazyInitialized(object): + """ + Descriptor to implement lazy initialization of property. + """ + + def __init__(self, function): + self.function = function + + def __get__(self, instance, cls): + val = self.function(instance) + setattr(instance, self.function.__name__, val) + return val + + +def _change_is_test_status(program, is_test): + # change all `is_test` attributes + for block in program.blocks: + for op in block.ops: + if op.has_attr('is_test'): + op._set_attr('is_test', is_test) + return program + + +class PartialProgramLayer: + """ + PartialProgramLayer wraps all the ops from layers decorated by `@declarative` + and execute them as a static subgraph. + + .. note:: + **1. This is a very low level API. Users should not use this API + directly. Please use `partial_program_from(concrete_program)` + to create it. + **2. LoDTensorArray is not currently supported in the output. + + Args: + main_program(Program): The main program that contains ops need to be executed. + inputs(list[Variable]): The input list of the decorated function by `@declarative`. + outputs(list[Variable]): The output list of the decorated function by `@declarative`. + parameters(list[VarBase]|None): All trainable parameters included in the program. Default None. + + Returns: + Layer: A Layer object that run all ops internally in static mode. + """ + + def __init__( + self, main_program, inputs, outputs, parameters=None, **kwargs + ): + super(PartialProgramLayer, self).__init__() + self._inputs = NestSequence(inputs) + self._outputs = NestSequence(outputs, need_check=True) + self._params = parameters if parameters is not None else [] + + self._build_strategy = kwargs.get('build_strategy', BuildStrategy()) + assert isinstance(self._build_strategy, BuildStrategy) + + self._origin_main_program = self._verify_program(main_program) + self._cuda_graph_vec = self._create_cuda_graph_vec() + self._cuda_graph_capture_mode = "" + self._cuda_graph_pool_id = 0 + # Set default mode to train + self.training = True + + custom_white_list, custom_black_list = None, None + tracer = framework._dygraph_tracer() + if tracer: + custom_white_list, custom_black_list = tracer._get_amp_op_list() + # For AMP training + self._amp_list = AutoMixedPrecisionLists( + custom_white_list=custom_white_list, + custom_black_list=custom_black_list, + ) + + # program_id -> list(scope) + self._scope_cache = {} + + def _get_scope(self, program_id=None, use_scope_cache=False): + if use_scope_cache: + if program_id not in self._scope_cache: + scope = core.Scope() + self._scope_cache[program_id] = [scope] + return scope + else: + for scope in self._scope_cache[program_id]: + if scope._can_reuesd: + return scope + scope = core.Scope() + self._scope_cache[program_id].append(scope) + return scope + else: + return core.Scope() + + @LazyInitialized + def _double_grads(self): + return self._get_double_grads(self._origin_main_program) + + # whole + @switch_to_static_graph + def _create_program(self, is_infer_mode=False): + if is_infer_mode: + return self._origin_main_program.clone(for_test=is_infer_mode) + else: + train_program = self._append_backward_desc( + self._origin_main_program + ) + # Note: Only set grad type once after initializing train program. So we put it here. + self._set_grad_type(self._params, train_program) + return train_program + + @switch_to_static_graph + def _create_amp_program(self, is_infer_mode=False): + amp_program = self._origin_main_program.clone(for_test=is_infer_mode) + with program_guard(amp_program): + rewrite_program(amp_program, self._amp_list) + if is_infer_mode: + return amp_program + else: + train_amp_program = self._append_backward_desc(amp_program) + self._set_grad_type(self._params, train_amp_program) + return train_amp_program + + @switch_to_static_graph + def _create_pure_fp16_program(self, is_infer_mode=False): + pure_fp16_program = self._origin_main_program.clone( + for_test=is_infer_mode + ) + with program_guard(pure_fp16_program): + cast_model_to_fp16( + pure_fp16_program, self._amp_list, use_fp16_guard=False + ) + if is_infer_mode: + return pure_fp16_program + else: + train_pure_fp16_program = self._append_backward_desc( + pure_fp16_program + ) + self._set_grad_type(self._params, train_pure_fp16_program) + return train_pure_fp16_program + + @switch_to_static_graph + def _create_forward_backward_train_program(self): + whole_program = self._create_program() + forward_end_op_index = self._infer_program.desc.block(0).op_size() + return self._get_forward_backward_program_form( + whole_program, forward_end_op_index + ) + + @switch_to_static_graph + def _create_forward_backward_train_amp_program(self): + whole_program = self._create_amp_program() + forward_end_op_index = self._infer_amp_program.desc.block(0).op_size() + return self._get_forward_backward_program_form( + whole_program, forward_end_op_index + ) + + @switch_to_static_graph + def _create_forward_backward_train_pure_fp16_program(self): + whole_program = self._create_pure_fp16_program() + forward_end_op_index = self._infer_pure_fp16_program.desc.block( + 0 + ).op_size() + return self._get_forward_backward_program_form( + whole_program, forward_end_op_index + ) + + @LazyInitialized + def _train_program(self): + return self._create_program() + + @LazyInitialized + def _infer_program(self): + return self._create_program(is_infer_mode=True) + + @LazyInitialized + def _train_amp_program(self): + return self._create_amp_program() + + @LazyInitialized + def _infer_amp_program(self): + return self._create_amp_program(is_infer_mode=True) + + @LazyInitialized + def _train_pure_fp16_program(self): + return self._create_pure_fp16_program() + + @LazyInitialized + def _infer_pure_fp16_program(self): + return self._create_pure_fp16_program(is_infer_mode=True) + + @LazyInitialized + def _train_forward_backward_program(self): + program = self._create_forward_backward_train_program() + return program + + @LazyInitialized + def _train_amp_forward_backward_program(self): + program = self._create_forward_backward_train_amp_program() + return program + + @LazyInitialized + def _train_pure_fp16_forward_backward_program(self): + program = self._create_forward_backward_train_pure_fp16_program() + return program + + @property + def whole_program(self): + if self.training: + if _in_amp_guard(): + return self._train_amp_program + elif _in_pure_fp16_guard(): + return self._train_pure_fp16_program + else: + return self._train_program + else: + if _in_amp_guard(): + return self._infer_amp_program + elif _in_pure_fp16_guard(): + return self._infer_pure_fp16_program + else: + return self._infer_program + + @property + def forward_program(self): + if self.training: + if _in_amp_guard(): + program = self._train_amp_forward_backward_program + return program[0] + elif _in_pure_fp16_guard(): + program = self._train_pure_fp16_forward_backward_program + return program[0] + else: + program = self._train_forward_backward_program + return program[0] + else: + if _in_amp_guard(): + return self._infer_amp_program + elif _in_pure_fp16_guard(): + return self._infer_pure_fp16_program + else: + return self._infer_program + + @property + def backward_program(self): + if self.training: + if _in_amp_guard(): + program = self._train_amp_forward_backward_program + return program[1] + elif _in_pure_fp16_guard(): + program = self._train_pure_fp16_forward_backward_program + return program[1] + else: + program = self._train_forward_backward_program + return program[1] + else: + return paddle.static.Program() + + @LazyInitialized + def _train_program_id(self): + program_id = _hash_with_id(self._train_program, self) + core._set_cached_executor_build_strategy( + program_id, self._build_strategy + ) + return program_id + + @LazyInitialized + def _infer_program_id(self): + return _hash_with_id(self._infer_program, self) + + @LazyInitialized + def _train_amp_program_id(self): + program_id = _hash_with_id(self._train_amp_program, self) + core._set_cached_executor_build_strategy( + program_id, self._build_strategy + ) + return program_id + + @LazyInitialized + def _infer_amp_program_id(self): + return _hash_with_id(self._infer_amp_program, self) + + @LazyInitialized + def _train_pure_fp16_program_id(self): + program_id = _hash_with_id(self._train_pure_fp16_program, self) + core._set_cached_executor_build_strategy( + program_id, self._build_strategy + ) + return program_id + + @LazyInitialized + def _infer_pure_fp16_program_id(self): + return _hash_with_id(self._infer_pure_fp16_program, self) + + @property + def whole_program_id(self): + if self.training: + if _in_amp_guard(): + return self._train_amp_program_id + elif _in_pure_fp16_guard(): + return self._train_pure_fp16_program_id + else: + return self._train_program_id + else: + if _in_amp_guard(): + return self._infer_amp_program_id + elif _in_pure_fp16_guard(): + return self._infer_pure_fp16_program_id + else: + return self._infer_program_id + + def _verify_program(self, main_program): + """ + Verify that the program parameter is initialized, prune some unused params, + and remove redundant op callstack. + """ + # 1. Check all params from main program can be found in self._params + self._check_params_all_inited(main_program) + # 2. Prune the parameters not used anywhere in the program. + self._prune_unused_params(main_program) + + return main_program + + def prepare_gradient_aggregation( + self, start_idx, main_program, target_program + ): + """ + Why we need add gradient aggregation operation ? + In some cases, if non leaf nodes are used as output, gradient overwriting will occur, such as + def forward(self, in): + x = 2 * in # <---- x is a non-leaf node in program. + y = x + 3 + return x, y + + loss = forward(in)[0].sum() + loss.backward() # <----- x@grad will be overwrited by elementwise_add_grad Op + """ + + def _need_aggregation(var): + """ + if exist a op whose inputs is var, then return True + """ + if not isinstance(var, framework.Variable) or var.type not in [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.SELECTED_ROWS, + ]: + return False + if var.dtype not in [paddle.float32, paddle.float64]: + return False + for op in main_program.block(0).ops: + for in_arg in op.input_arg_names: + if in_arg == var.name: + return True + return False + + def _insert_aggregation_ops_for_var(target_program, var): + suffix = "@dy2static" + var_grad_name = var.grad_name + new_grad_name = var.name + suffix + "@GRAD" + finded_ops = list( + filter( + lambda x: x[0] >= start_idx + and any( + [ + out_arg == var_grad_name + for out_arg in x[1].output_arg_names + ] + ), + enumerate(target_program.block(0).ops), + ) + ) + + # len(finded_ops) may equals zero when stop_gradient works. + # len(finded_ops) may > 1, because we may have fill_constant op. + if len(finded_ops) == 0: + return None + # step1: create a new var named var.name@GRAD + target_program.block(0).create_var( + name=new_grad_name, + type=var.type, + dtype=var.dtype, + shape=var.shape, + ) + # step2: rename the var.name@GRAD to var.name@GRAD@dy2static + for idx, op in finded_ops: + op._rename_input(var_grad_name, new_grad_name) + op._rename_output(var_grad_name, new_grad_name) + # step3: insert sum op to aggregate the gradient. + # var.name@GRAD = sum(var.name@dy2static@GRAD, var.name@GRAD) + target_program.block(0)._insert_op( + finded_ops[-1][0] + 1, + type='sum', + inputs={'X': [var_grad_name, new_grad_name]}, + outputs={"Out": var_grad_name}, + ) + return None + + to_processed_vars = list( + filter(_need_aggregation, self._outputs.tolist()) + ) + for _var in to_processed_vars: + _insert_aggregation_ops_for_var(target_program, _var) + + @switch_to_static_graph + def _append_backward_desc(self, main_program): + # make sure all status of is_test are False in train mode. + program = _change_is_test_status(main_program.clone(), is_test=False) + targets = [] + for out in self._outputs.tolist(): + if isinstance(out, framework.Variable): + targets.append(program.global_block().var(out.name)) + + if targets: + backward.gradients(targets=targets, inputs=[]) + + start_idx = len(main_program.block(0).ops) + 2 * len( + self._outputs.tolist() + ) + + self.prepare_gradient_aggregation(start_idx, main_program, program) + + return program + + def _prune_unused_params(self, program): + """ + Prune the parameters not used anywhere in the program. + The `@declarative` may only decorated a sub function which + contains some unused parameters created in `__init__`. + So prune these parameters to avoid unnecessary operations in + `run_program_op`. + """ + required_params = [] + for param in self._params: + found_param = False + for block in program.blocks: + for op in block.ops: + if ( + param.name in op.input_arg_names + or param.name in op.output_arg_names + ): + required_params.append(param) + found_param = True + break + if found_param: + break + + self._params = required_params + + def _get_double_grads(self, program): + double_grads = [] + for block in program.blocks: + for name in block.vars: + if "@GRAD" in name: + var_desc = block.vars[name].desc + var_base = None + if not framework._in_eager_mode_: + var_base = core.VarBase( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + else: + var_base = core.eager.Tensor( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + double_grads.append(var_base) + return self._valid_vars(double_grads) + + def _get_end_op_index(self): + if _in_amp_guard(): + infer_program = self._infer_amp_program + elif _in_pure_fp16_guard(): + infer_program = self._infer_pure_fp16_program + else: + infer_program = self.infer_program + return infer_program.desc.block(0).op_size() + + def __call__(self, inputs): + in_vars, out_vars = self._prepare(inputs) + + self._cast_fp16_if_pure_fp16(in_vars) + + attrs = [ + 'global_block', + self.program.desc.block(0), + 'start_op_index', + 0, + 'end_op_index', + self._get_end_op_index(), + 'is_test', + not self.training, + 'program_id', + self.program_id, + ] + if self._cuda_graph_capture_mode: + attrs.extend( + ( + 'cuda_graph_capture_mode', + self._cuda_graph_capture_mode, + 'cuda_graph_pool_id', + self._cuda_graph_pool_id, + ) + ) + + use_interpretorcore = ( + _is_enable_standalone_executor() + and _is_dy2st_enable_standalone_executor() + ) + attrs.extend(('use_interpretorcore', use_interpretorcore)) + if use_interpretorcore: + attrs.extend( + ( + 'forward_global_block', + self.forward_program.desc.block(0), + 'backward_global_block', + self.backward_program.desc.block(0), + ) + ) + + _legacy_C_ops.run_program( + self._valid_vars(in_vars), + self._valid_vars(self._params), + self._valid_vars(out_vars), + self._create_scope_vec( + program_id=self.program_id, use_scope_cache=True + ), + self._double_grads, + self._cuda_graph_vec, + *attrs + ) + else: + _legacy_C_ops.run_program( + self._valid_vars(in_vars), + self._valid_vars(self._params), + self._valid_vars(out_vars), + self._create_scope_vec(), + self._double_grads, + self._cuda_graph_vec, + *attrs + ) + restored_nest_out = self._restore_out(out_vars) + return self._remove_no_value(restored_nest_out) + + def _cast_fp16_if_pure_fp16(self, in_vars): + if _in_pure_fp16_guard(): + for i, var in enumerate(in_vars): + name = var.name + if ( + self.program.global_block().has_var(name) + and self.program.global_block().var(name).dtype + == paddle.float16 + ): + in_vars[i] = var.astype('float16') + in_vars[i].name = name + + @property + def program(self): + return self.whole_program + + @property + def program_id(self): + return self.whole_program_id + + @property + def train_program(self): + if _in_amp_guard(): + return self._train_amp_program + elif _in_pure_fp16_guard(): + return self._train_pure_fp16_program + else: + return self._train_program + + @property + def infer_program(self): + if _in_amp_guard(): + return self._infer_amp_program + elif _in_pure_fp16_guard(): + return self._infer_pure_fp16_program + else: + return self._infer_program + + @switch_to_static_graph + def _get_forward_backward_program_form( + self, whole_program, forward_end_op_index + ): + forward_builded_program = add_build_strategy_for( + whole_program, 0, forward_end_op_index, self._build_strategy + ) + backward_start_op_index = forward_end_op_index + 2 * len( + self._outputs.var_ids + ) + backward_end_op_index = whole_program.desc.block(0).op_size() + backward_builded_program = add_build_strategy_for( + whole_program, + backward_start_op_index, + backward_end_op_index, + self._build_strategy, + ) + self._apply_inplace_pass( + forward_builded_program, backward_builded_program + ) + return [forward_builded_program, backward_builded_program] + + def _apply_inplace_pass(self, forward_program, backward_program): + attr_types = { + "use_cuda": "bool", + "mem_opt_skip_vars": "list[str]", + "for_partial_block": "bool", + } + empty_startup_program = paddle.static.Program() + use_cuda = True if core.is_compiled_with_cuda() else False + # skip data var + forward_mem_opt_skip_vars = [] + backward_mem_opt_skip_vars = [] + for var_name, var in forward_program.global_block().vars.items(): + if var.is_data: + forward_mem_opt_skip_vars.append(var_name) + for var_name, var in backward_program.global_block().vars.items(): + if var.is_data: + backward_mem_opt_skip_vars.append(var_name) + for var in self._inputs: + if isinstance(var, paddle.fluid.framework.Variable): + forward_mem_opt_skip_vars.append(var.desc.name()) + backward_mem_opt_skip_vars.append(var.desc.name()) + for var in self._outputs: + if isinstance(var, paddle.fluid.framework.Variable): + forward_mem_opt_skip_vars.append(var.desc.name()) + backward_mem_opt_skip_vars.append(var.desc.name()) + for var_name in core.parse_safe_eager_deletion_skip_vars( + backward_program.desc + ): + forward_mem_opt_skip_vars.append(var_name) + attrs = { + "use_cuda": use_cuda, + "mem_opt_skip_vars": forward_mem_opt_skip_vars, + "for_partial_block": True, + } + _apply_pass( + forward_program, + empty_startup_program, + "buffer_shared_inplace_pass", + attrs, + attr_types, + ) + attrs = { + "use_cuda": use_cuda, + "mem_opt_skip_vars": backward_mem_opt_skip_vars, + "for_partial_block": True, + } + _apply_pass( + backward_program, + empty_startup_program, + "buffer_shared_inplace_pass", + attrs, + attr_types, + ) + + def _prepare(self, inputs): + """ + Prepare inputs, outputs, attrs. + """ + assert isinstance(inputs, (tuple, list)) + # Flatten inputs with nested structure into single list. + flatten_inputs = flatten(inputs) + # Convert variable into VarBase and feed in training data. + input_vars = [] + expected_place = framework._current_expected_place() + for i, value in enumerate(flatten_inputs): + if isinstance(value, np.ndarray): + var = None + if not framework._in_eager_mode_: + var = core.VarBase( + value=value, + name=self._inputs[i].desc.name(), + persistable=False, + place=expected_place, + zero_copy=True, + ) + else: + var = core.eager.Tensor( + value=value, + name=self._inputs[i].desc.name(), + persistable=False, + place=expected_place, + zero_copy=True, + ) + elif isinstance(value, (core.VarBase, core.eager.Tensor)): + # NOTE(Aurelius84): If var is on CPUPlace, it will be transformed multi times + # into CUDAPlace when it's as input of multi Ops. so we move it in advance + # to avoid this problem. + if value.stop_gradient and not value.place._equals( + expected_place + ): + var = value._copy_to(expected_place, False) + var.stop_gradient = True + else: + var = value + var.name = self._inputs[i].desc.name() + else: + continue + input_vars.append(var) + + # mapping from name(string) -> VarBase + out_varbase_map = {} + + def create_out(var_id): + var = self._outputs[var_id] + assert isinstance(var, framework.Variable) + var_desc = var.desc + varbase = None + + if var_desc.name() in out_varbase_map: + return out_varbase_map[var_desc.name()] + + if not framework._in_eager_mode_: + var_base = core.VarBase( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + else: + var_base = core.eager.Tensor( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + var_base.stop_gradient = var.stop_gradient + out_varbase_map[var_desc.name()] = var_base + return var_base + + # Create VarBase to receive output data. + out_vars = list(map(create_out, self._outputs.var_ids)) + + return input_vars, out_vars + + def _create_scope_vec(self, program_id=None, use_scope_cache=False): + # Hold forward variables + tmp_scope_vec = None + inner_scope = self._get_scope( + program_id=program_id, use_scope_cache=use_scope_cache + ) + if not framework._in_eager_mode_: + tmp_scope_vec = core.VarBase( + core.VarDesc.VarType.FP32, + [], + "program_out_scope", + core.VarDesc.VarType.STEP_SCOPES, + True, + ) + tmp_scope_vec.value().set_scope(inner_scope) + else: + tmp_scope_vec = [inner_scope] + return tmp_scope_vec + + def _create_cuda_graph_vec(self): + var = core.VarBase( + core.VarDesc.VarType.FP32, + [], + "cuda_graph", + core.VarDesc.VarType.RAW, + True, + ) + var.stop_gradient = True + return var + + def _restore_out(self, out_vars): + """ + Restores same nested outputs by only replacing the Variable with VarBase. + """ + + flatten_outputs = self._outputs.tolist() + for i, idx in enumerate(self._outputs.var_ids): + flatten_outputs[idx] = out_vars[i] + outs = self._outputs.restore(flatten_outputs) + if outs is not None and len(outs) == 1: + outs = outs[0] + + return outs + + @switch_to_static_graph + def _clone_for_test(self, main_program): + return main_program.clone(for_test=True) + + def _is_no_value(self, var): + if isinstance(var, (core.VarBase, core.eager.Tensor)) and var.shape == [ + 1 + ]: + # NOTE: .numpy() will insert MemcpySync operation, it hits performance. + if var.numpy()[0] == RETURN_NO_VALUE_MAGIC_NUM: + return True + return False + + def _remove_no_value(self, out_vars): + """ + Removes invalid value for various-length return statement + """ + if isinstance(out_vars, (core.VarBase, core.eager.Tensor)): + if self._is_no_value(out_vars): + return None + return out_vars + elif isinstance(out_vars, (tuple, list)): + if isinstance(out_vars, tuple): + res = tuple( + var for var in out_vars if not self._is_no_value(var) + ) + else: + # isinstance(out_vars, list) + res = [var for var in out_vars if not self._is_no_value(var)] + + has_removed = len(out_vars) > len(res) + # len(out_vars) > len(res) means we have removed var. This is + # preventing out_vars is empty or just one element at the beginning + if len(res) == 0 and has_removed: + return None + elif len(res) == 1 and has_removed: + return res[0] + return res + + return out_vars + + def _set_grad_type(self, params, train_program): + # NOTE: if user set sparse gradient mode, the param's gradient + # will be SelectedRows, not LoDTensor. But tracer will just + # set param grad VarBase by forward VarBase(LoDTensor) + # If we don't change grad_var type here, RunProgramOp need + # transform SelectedRows to LoDTensor forcibly, it may not + # be user wanted result. + for param in params: + grad_name = param.name + core.grad_var_suffix() + grad_var = train_program.desc.block(0).find_var( + cpt.to_bytes(grad_name) + ) + # NOTE: cannot find var desc maybe no problem, such as in batch_norm + if grad_var is None: + continue + param._set_grad_type(grad_var.type()) + + def _remove_op_call_stack(self, main_program): + """ + Remove op's python call stack with redundant low-level error messages related to + transforamtions to avoid confusing users. + """ + assert isinstance(main_program, framework.Program) + for block in main_program.blocks: + for op in block.ops: + if op.has_attr("op_callstack"): + op._remove_attr("op_callstack") + + return main_program + + def _check_params_all_inited(self, main_program): + """ + Check all params from main program are already initialized, see details as follows: + 1. all parameters in self._params should be type `framework.ParamBase` which are created in dygraph. + 2. all parameters from transformed program can be found in self._params. + Because they share same data with ParamBase of original dygraph. + """ + if not isinstance(self._params, (list, tuple)): + raise TypeError( + "Type of self._params in PartialProgramLayer should be list or tuple, but received %s." + % type(self._params) + ) + + param_and_buffer_names_set = set() + for i, var in enumerate(self._params): + # self._params constains parameters and buffers with persistable=True. + if not isinstance(var, (core.VarBase, core.eager.Tensor)): + raise TypeError( + 'Type of self._params[{}] in PartialProgramLayer should be Parameter or Variable, but received {}.'.format( + i, type(var) + ) + ) + param_and_buffer_names_set.add(var.name) + + for block in main_program.blocks: + for name, var in six.iteritems(block.vars): + if isinstance(var, framework.Parameter): + if name not in param_and_buffer_names_set: + raise ValueError( + "\n\tWe don't support to define layer with parameters in the function decorated by `@to_static`." + "\n\tBut we found parameter(%s) was created in the decorated function." + "\n" + "\n\tRevise suggestion: " + "\n\t\t1. Please ensure all your sublayers are inheritted from nn.Layer." + "\n\t\t2. Please use nn.ParameterList and nn.LayerList as container instead of using a native Python container such as List" + % name + ) + + def _valid_vars(self, vars): + return vars if vars else None + + +def _create_fake_var(): + """ + Create a fake_var (force on CPU) to handle empty input or output + """ + if not framework._in_eager_mode_: + return [ + core.VarBase( + core.VarDesc.VarType.FP32, + [], + "Fake_var", + core.VarDesc.VarType.RAW, + False, + ) + ] + else: + return [ + core.eager.Tensor( + core.VarDesc.VarType.FP32, + [], + "Fake_var", + core.VarDesc.VarType.RAW, + False, + ) + ] + + +def partial_program_from(concrete_program): + inputs = concrete_program.inputs + if inputs and isinstance(inputs[0], layers.Layer): + inputs = inputs[1:] + + return PartialProgramLayer( + concrete_program.main_program, + inputs, + concrete_program.outputs, + concrete_program.parameters, + **concrete_program.kwargs + ) + + +@switch_to_static_graph +def add_build_strategy_for( + program, start_op_index, end_op_index, build_strategy=None +): + if start_op_index < end_op_index: + compiled_program = paddle.static.CompiledProgram( + core.Graph(program.desc, start_op_index, end_op_index), + build_strategy=build_strategy, + ) + compiled_program._compile( + core.Scope(), framework._current_expected_place() + ) + ir_graph = framework.IrGraph(compiled_program._graph) + builded_program = ir_graph.to_program() + if hasattr(compiled_program._program, 'lr_sheduler'): + builded_program.lr_sheduler = compiled_program._program.lr_sheduler + else: + builded_program = program + return builded_program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/print_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/print_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..8615b3596e081ddbf80f9736a72ab183474bc2c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/print_transformer.py @@ -0,0 +1,55 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper, StaticAnalysisVisitor +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class PrintTransformer(BaseTransformer): + """ + This class transforms python print function to fluid.layers.Print. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of PrintTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + self.static_analysis_visitor = StaticAnalysisVisitor(self.root) + self.node_to_wrapper_map = self.static_analysis_visitor.get_node_to_wrapper_map( + ) + + def transform(self): + self.visit(self.root) + + # NOTE: deal with print in PY3 + def visit_Call(self, node): + if isinstance(node.func, gast.Name) and node.func.id == 'print': + node = self._create_print_node(node.args) + return node + + # NOTE: deal with print in PY2 + def visit_Print(self, node): + convert_print_node = self._create_print_node(node.values) + return gast.Expr(value=convert_print_node) + + def _create_print_node(self, print_args): + convert_print_func = gast.parse('_jst.Print').body[0].value + return gast.Call(func=convert_print_func, args=print_args, keywords=[]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/program_translator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/program_translator.py new file mode 100644 index 0000000000000000000000000000000000000000..fbaa4b9f0ef5233651e95214957fd71e39212cd8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/program_translator.py @@ -0,0 +1,1358 @@ +# 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. + +from __future__ import print_function + +import collections +from paddle.utils import gast +import inspect +import six +import textwrap +import threading +import weakref + +from paddle.fluid import framework +from paddle.fluid import _non_static_mode +from paddle.fluid.dygraph import layers +from paddle.fluid.data_feeder import check_type +from paddle.fluid.layers.utils import flatten +from paddle.fluid.dygraph.base import param_guard +from paddle.fluid.dygraph.base import switch_to_static_graph +from paddle.fluid.dygraph.dygraph_to_static import DygraphToStaticAst +from paddle.fluid.dygraph.dygraph_to_static import error +from paddle.fluid.dygraph.dygraph_to_static import logging_utils +from paddle.fluid.dygraph.dygraph_to_static.origin_info import attach_origin_info +from paddle.fluid.dygraph.dygraph_to_static.origin_info import create_and_update_origin_info_map +from paddle.fluid.dygraph.dygraph_to_static.origin_info import update_op_callstack_with_origin_info +from paddle.fluid.dygraph.dygraph_to_static.partial_program import partial_program_from +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_func +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import func_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.utils import input_specs_compatible +from paddle.fluid.dygraph.dygraph_to_static.utils import type_name +from paddle.fluid.dygraph.dygraph_to_static.utils import unwrap +from paddle.fluid.dygraph.dygraph_to_static.utils import make_hashable, ALREADY_D2S +from paddle.fluid.dygraph.dygraph_to_static.function_spec import FunctionSpec, _hash_spec_names +from paddle.fluid.dygraph.dygraph_to_static.function_spec import get_buffers, get_parameters +from paddle.fluid.wrapped_decorator import signature_safe_contextmanager + +__all__ = ['ProgramTranslator', 'convert_to_static'] + +# For each traced function, we set `max_traced_program_count` = 10 to consider caching performance. +# Once exceeding the threshold, we will raise warning to users to make sure the conversion is as expected. +MAX_TRACED_PROGRAM_COUNT = 10 + + +class FunctionCache(object): + """ + Caches the transformed functions to avoid redundant conversions of the same function. + """ + + def __init__(self): + # Caches the converted static functions. {dygraph_func: static_func} + self._converted_static_func_caches = weakref.WeakKeyDictionary() + # Caches the converted ast node for same source code. {source_code: ast_root} + self._code_to_ast_caches = dict() + self._dygraph_to_static = DygraphToStaticAst() + + def convert_with_cache(self, func): + """ + Returns the cached static function or converts it when first encounters the function. + """ + # If hit cache, return it directly. + static_func = self._converted_static_func_caches.get(func, None) + + if static_func is None: + static_func = self._convert(func) + self._converted_static_func_caches[func] = static_func + + return static_func + + def _convert(self, func): + """ + Converts dygraph function into static function. For two functions with same dedent code, + the second function will reuse the transformed ast node of previous one. + + For example: + # A.py + def foo(x, y): + z = x + y + return z + + # B.py + def foo(x, y): + z = x + y + return z + + If the conversion of A.foo happens after B.foo, it will reuse the transformed ast node of B.foo + to speed up the conversion. + """ + # Note: In Python2, it will raise OSError when inspect function + # with decorator directly and function.__wrapped__ holds the actual function. + func = unwrap(func) + source_code = func_to_source_code(func) + + # TODO(liym27): + # Consider this case: source_code in self._code_to_ast_caches, + # but actually they are methods in different classes. + # Maybe use (__class__, source_code) as key + if source_code in self._code_to_ast_caches: + root_wrapper = self._code_to_ast_caches[source_code] + else: + root = gast.parse(source_code) + root = attach_origin_info(root, func) + root_wrapper = self._dygraph_to_static.get_static_ast(root) + self._code_to_ast_caches[source_code] = root_wrapper + + # Get static function from AST + static_func, file_name = ast_to_func(root_wrapper.node, func) + + create_and_update_origin_info_map(root_wrapper.node, static_func) + return static_func + + def exist(self, func): + return func in self._converted_static_func_caches + + +_CACHE_LOCK = threading.Lock() +_FUNCTION_CACHE = FunctionCache() + + +def convert_to_static(function): + """ + Transforms function of dygraph into static function using the cache mechanism. + + Args: + function(callable): The function with dygraph layers that will be converted into static layers. + """ + if getattr(function, ALREADY_D2S, None): + return function + with _CACHE_LOCK: + static_func = _FUNCTION_CACHE.convert_with_cache(function) + setattr(static_func, ALREADY_D2S, True) + return static_func + + +class CacheKey(object): + """ + Cached key for ProgramCache. + """ + __slots__ = [ + 'function_spec', 'input_args_with_spec', 'input_kwargs_with_spec', + 'class_instance', 'kwargs', '_spec_names_id' + ] + + def __init__(self, function_spec, input_args_with_spec, + input_kwargs_with_spec, class_instance, **kwargs): + """ + Initializes a cache key. + + Args: + functions_spec(FunctionSpec): a FunctionSpec instance of decorated function. + input_args_with_spec(list[InputSpec]): actual input args with some arguments replaced by InputSpec. + input_kwargs_with_spec(list[{string:InputSpec}]): actual input kwargs with some arguments replaced by InputSpec. + class_instance(object): a instance of class `Layer`. + **kwargs(dict): manage other arguments used for better scalability + """ + self.function_spec = function_spec + self.input_args_with_spec = input_args_with_spec + self.input_kwargs_with_spec = input_kwargs_with_spec + self.class_instance = class_instance + # NOTE: `kwargs` is usually not considered as basic member for `__hash__` + self.kwargs = kwargs + self._spec_names_id = _hash_spec_names(input_args_with_spec, + input_kwargs_with_spec) + + @classmethod + def from_func_and_args(cls, function_spec, args, kwargs, class_instance): + """ + Generated a CacheKey instance by given inputs. + + Args: + functions_spec(FunctionSpec): a FunctionSpec instance of decorated function. + args(tuple): tuple of actual inputs arguments. + kwargs(dict): dict of actual inputs keyword arguments. + class_instance(object): a instance of class `Layer`. + """ + # 1. filter `self` in args + if args and isinstance(args[0], layers.Layer): + args = args[1:] + # 2. convert tensor and numpy array into InputSpec + _args, _kwargs = function_spec.unified_args_and_kwargs(args, kwargs) + input_args_with_spec, input_kwargs_with_spec = function_spec.args_to_input_spec( + _args, _kwargs) + + # 3. check whether hit the cache or build a new program for the input arguments + return CacheKey(function_spec, input_args_with_spec, + input_kwargs_with_spec, class_instance) + + def __hash__(self): + error_msg = "Arguments to a `@paddle.jit.to_static` must be a hashable Python objects (or nested structures of these types)." + with_hook = self.kwargs.get("with_hook", False) + is_train = self.kwargs.get("is_train", False) + return hash((id(self.function_spec), + make_hashable(self.input_args_with_spec, error_msg), + make_hashable(self.input_kwargs_with_spec, + error_msg), self._spec_names_id, + self.class_instance, with_hook, is_train)) + + def __eq__(self, other): + return (type(self) is type(other)) and hash(self) == hash(other) + + def __neq__(self, other): + return not self == other + + def __repr__(self): + return "id(function_spec): {}, input_args_with_spec: {}, input_kwargs_with_spec: {}, class_instance: {}".format( + id(self.function_spec), self.input_args_with_spec, + self.input_kwargs_with_spec, self.class_instance) + + +def unwrap_decorators(func): + """ + Unwraps a decorated function and returns the decorator list and inner target. + """ + decorators = [] + cur = func + while True: + if isinstance(cur, StaticFunction): + decorators.append(cur) + # Note: if `cur` is a method, keep it as bound method of class. + instance = cur._class_instance + if instance is not None: + cur = cur.dygraph_function.__get__(instance) + else: + cur = cur.dygraph_function + else: + break + return decorators, cur + + +class StaticFunction(object): + """ + Wrapper class to Manage program conversion of decorated function. + + """ + + def __init__(self, function, input_spec=None, **kwargs): + """ + Initializes a `StaticFunction`. + + Args: + function(callable): A function or method that will be converted into static program. + input_spec(list[InputSpec]): list of InputSpec to specify the `shape/dtype/name` information for each input argument, default None. + **kwargs(dict): other arguments like `build_strategy` et.al. + """ + # save the instance `self` while decorating a method of class. + + if inspect.ismethod(function): + self._dygraph_function = getattr(function, '__func__') + self._class_instance = getattr(function, '__self__') + + if not hasattr(self._class_instance, '_original_funcs'): + raise TypeError( + "When using 'to_static' to convert method of a class, " + "please ensure the class inherits from nn.Layer") + self._class_instance._original_funcs[ + function.__name__] = self._dygraph_function + else: + self._dygraph_function = function + self._class_instance = None + + self._input_spec = input_spec + self._function_spec = FunctionSpec(function, input_spec) + self._program_cache = ProgramCache() + self._descriptor_cache = weakref.WeakKeyDictionary() + # Note: Hold a reference to ProgramTranslator for switching `enable_to_static`. + self._program_trans = ProgramTranslator() + self._kwargs = kwargs + self._training = True + self._cuda_graph_capture_mode = "" + self._cuda_graph_pool_id = 0 + + self._property = kwargs.get("property", False) + + @property + def is_property(self): + # whether is class proproty to be exported. + return self._property + + def train(self): + if isinstance(self._class_instance, + layers.Layer) and self._class_instance.training == False: + raise RuntimeError( + "Failed to switch train mode. {} is a Layer's method, " + "please use Layer.train() to switch train mode.".format( + self.dygraph_function)) + self._training = True + + def eval(self): + if isinstance(self._class_instance, + layers.Layer) and self._class_instance.training == True: + raise RuntimeError( + "Failed to switch eval mode. {} is a Layer's method, " + "please use Layer.eval() to switch eval mode.".format( + self.dygraph_function)) + self._training = False + + def __get__(self, instance, owner): + """ + Overrides this method to parse the class instance and call bound method correctly. + + For example: + + ''' + class Net(Layer): + def __init__(self): + pass + + @paddle.jit.to_static + def forward(self, x, y): + return x + y + + net = Net() + out = net(x, y) + ''' + + In above case, `net(x, y)` will call `net.forward(x, y)` firstly that is a bound method + of `Net` instance. After decorated by `@paddle.jit.to_static`, it will firstly to call `__get__` + to parse the class instance correctly instead of the `StaticFunction` instance. + """ + if instance not in self._descriptor_cache: + if instance is None: + return self + # Note(Aurelius84): To construct new instance of StaticFunction when we + # first encouter the bound function of layer and cache it. + new_static_layer = self._clone() + new_static_layer._class_instance = instance + self._descriptor_cache[instance] = new_static_layer + + return self._descriptor_cache[instance] + + def _clone(self): + return self.__class__(self._dygraph_function, self._input_spec, + **self._kwargs) + + def __call__(self, *args, **kwargs): + """ + Supports to call the returned instance with input `args` and `kwargs` directly. + + Args: + *args(tuple): tuple of all input arguments from original decorated function. + **kwargs(dict): dict of all input keyward arguments from original decorated function. + + Return: + Outputs of decorated function. + """ + if self._property: + return self._call_dygraph_function(*args, **kwargs) + + # 1. call dygraph function directly if not enable `declarative` + if not self._program_trans.enable_to_static: + # NOTE(liym27): + # Here calls `warnings.warn` but not `logging_utils.warn` because by default warnings.warn(message) + # will show up **only once**. StaticFunction.__call__ will run many times, it is appropriate to + # display this warning message only once. + logging_utils.warn( + "The decorator '@paddle.jit.to_static' does NOT work when setting ProgramTranslator.enable to False. " + "We will just return dygraph output. If you would like to get static graph output, please call API " + "ProgramTranslator.enable(True)") + return self._call_dygraph_function(*args, **kwargs) + + if not _non_static_mode(): + raise RuntimeError( + "Failed to run the callable object {} decorated by '@paddle.jit.to_static', " + "because it is NOT in dynamic mode. Please disable the static mode to enter dynamic mode with the " + "following API: paddle.disable_static().".format( + self.dygraph_function)) + + # 2. trace ops from dygraph layers and cache the generated program. + args, kwargs = self._function_spec.unified_args_and_kwargs(args, kwargs) + + try: + concrete_program, partial_program_layer = self.get_concrete_program( + *args, **kwargs, is_train=self._is_train_mode()) + # 3. synchronize self.training attribute. + if isinstance(self._class_instance, layers.Layer): + partial_program_layer.training = self._class_instance.training + else: + partial_program_layer.training = self._training + + partial_program_layer._cuda_graph_capture_mode = self._cuda_graph_capture_mode + partial_program_layer._cuda_graph_pool_id = self._cuda_graph_pool_id + + # 4. return outputs. + try: + return partial_program_layer(args) + except Exception as e: + if not hasattr(e, error.ERROR_DATA): + # runtime error + error.attach_error_data(e, in_runtime=True) + raise + except Exception as e: + error_data = getattr(e, error.ERROR_DATA, None) + if error_data: + error_data.raise_new_exception() + else: + logging_utils.warn( + "Please file an issue at 'https://github.com/PaddlePaddle/Paddle/issues'" + " if you can't handle this {} yourself.".format(type(e))) + raise e + + def _is_train_mode(self): + if self._class_instance is not None: + if not hasattr(self._class_instance, 'training'): + raise TypeError( + "When using 'to_static' to convert method of a class, " + "please ensure the class inherits from nn.Layer") + return self._class_instance.training + else: + return self._training + + def _call_dygraph_function(self, *args, **kwargs): + """ + Calls dygraph function directly and returns the outputs. + + Args: + *args(tuple): tuple of all input arguments from original decorated function. + **kwargs(dict): dict of all input keyward arguments from original decorated function. + + Return: + Outputs of dygraph function. + """ + if self._class_instance is not None: + dygraph_function = self._dygraph_function.__get__( + self._class_instance) + else: + dygraph_function = self._dygraph_function + + return dygraph_function(*args, **kwargs) + + def _raise_when_property(self): + """raise RuntimeError when property=True + + Raises: + RuntimeError: can not call this func when property=True + """ + if self.is_property: + raise RuntimeError("Can not call the func when property=True.") + + def get_concrete_program(self, *args, **kwargs): + """ + Returns traced concrete program and inner executable partial layer. + + Args: + *args(tuple): input arguments values or InputSpec + **kwargs(dict) : input kwargs values. + + Returns: + Traced ConcreteProgram and executable translated Layer. + """ + self._raise_when_property() + + with_hook = kwargs.get("with_hook", False) + is_train = kwargs.get("is_train", True) + if "is_train" in kwargs: kwargs.pop("is_train") + if "with_hook" in kwargs: kwargs.pop("with_hook") + # 1. unify args/kwargs and replace Tensor with InputSpec + if len(args) != len(self._function_spec.args_name): + args, kwargs = self._function_spec.unified_args_and_kwargs( + args, kwargs) + input_args_with_spec, input_kwargs_with_spec = self._function_spec.args_to_input_spec( + args, kwargs) + + # 2. generate cache key + cache_key = CacheKey(self._function_spec, + input_args_with_spec, + input_kwargs_with_spec, + self._class_instance, + **self._kwargs, + with_hook=with_hook, + is_train=is_train) + + # 3. check whether hit the cache or build a new program for the input arguments + concrete_program, partial_program_layer = self._program_cache[cache_key] + return concrete_program, partial_program_layer + + def get_traced_count(self): + """ + Returns the number of traced programs for the decorated function. + """ + return len(self._program_cache) + + @property + def code(self): + """ + Returns the source code of transformed static function for debugging. + """ + static_func = convert_to_static(self._dygraph_function) + source_code = func_to_source_code(static_func) + return source_code + + @property + def dygraph_function(self): + """ + Returns the original decorated function. + """ + return self._dygraph_function + + @property + def concrete_program(self): + """ + Returns recent ConcreteProgram instance of decorated function. + + Examples: + .. code-block:: python + + import paddle + from paddle.jit import to_static + from paddle.static import InputSpec + + paddle.disable_static() + + def foo(x, y): + z = x + y + return z + + # usage 1: + decorated_foo = to_static(foo, input_spec=[InputSpec([10], name='x'), InputSpec([10], name='y')]) + print(decorated_foo.concrete_program) + + # usage 2: + decorated_foo = to_static(foo) + out_foo = decorated_foo(paddle.rand([10]), paddle.rand([10])) + print(decorated_foo.concrete_program) + """ + return self.concrete_program_specify_input_spec(input_spec=None) + + def concrete_program_specify_input_spec(self, + input_spec=None, + with_hook=False): + """ + Returns recent ConcreteProgram instance of decorated function while + specifying input_spec. If the self._function_spec already has + input_spec, it will check the compatibility of input input_spec and + the self._function_spec.input_spec. If input input_spec=None, then + this method uses self._function_spec.input_spec + + args: + input_spec (list[InputSpec], optional): Describes the input of + the translate function. + """ + self._raise_when_property() + # if specific the `input_spec`, the length of program_cache will always 1, + # else, return the last one. + cached_program_len = len(self._program_cache) + # If specific `input_spec`, apply convertion from dygraph layers into static Program. + if cached_program_len == 0: + desired_input_spec = input_spec + if self._function_spec.input_spec is not None: + if input_spec is not None and not input_specs_compatible( + flatten(input_spec), + flatten(self._function_spec.input_spec)): + raise ValueError( + "The `input_spec`: {} used to construct concrete_program is conflict with the `input_spec`: {} in `@paddle.jit.to_static`" + .format(input_spec, self._function_spec.input_spec)) + # NOTE(chenweihang): we should always translated program based on the `input_spec` + # decorated on forward if it is valid + desired_input_spec = self._function_spec.input_spec + if input_spec is not None: + logging_utils.warn( + "\n\nYou have specified `input_spec` both in function definition (higher priority) and `paddle.jit.save` (will be ignored.)\n\n\t Using: {}\n\n\t Ignore: {}\n" + .format(desired_input_spec, input_spec)) + + has_input_spec = (desired_input_spec is not None) + if has_input_spec: + concrete_program, _ = self.get_concrete_program( + *desired_input_spec, + with_hook=with_hook, + is_train=self._is_train_mode()) + return concrete_program + else: + raise ValueError( + "No valid transformed program for {}.\n\t Please specific `input_spec` in `@paddle.jit.to_static` or feed input tensor to call the decorated function at once.\n" + .format(self._function_spec)) + elif with_hook: + cache_key = self._program_cache._recent_cache_key + cache_key.kwargs["with_hook"] = True + concrete_program, _ = self._program_cache[cache_key] + return concrete_program + + # If more than one programs have been cached, return the recent converted program by default. + elif cached_program_len > 1: + logging_utils.warn( + "Current {} has more than one cached programs: {}, the last traced progam will be return by default." + .format(self._function_spec, cached_program_len)) + + cache_key, (concrete_program, + partial_layer) = self._program_cache.last() + return concrete_program + + def rollback(self): + """ + Rollback into original dygraph functions for current class instance. + + Returns: + Function or Method + + Example:: + .. code-block:: python + + import paddle + + class Net(paddle.nn.Layer): + def __init__(self): + super(Net, self).__init__() + + def forward(self, x, flag=True): + if flag: + out = x + 1 + else: + out = x - 1 + return out + + x = paddle.randn([10, 1], 'float32') + net = paddle.jit.to_static(Net()) # convert into static mode + out = net(x) + + net.forward.rollback() # rollback into dygraph mode + out = net(x) + """ + + def rollback_impl(class_instance): + for name, func in class_instance._original_funcs.items(): + setattr(class_instance, name, func.__get__(class_instance)) + + for sublayer in class_instance.sublayers(include_self=False): + rollback_impl(sublayer) + + if self._class_instance is None: + return self._dygraph_function + + # only rollback sub-functions on path of top _dygraph_function + func_name = self._dygraph_function.__name__ + assert func_name in self._class_instance._original_funcs, "Not Found function '{}' in class '{}'.".format( + func_name, self._class_instance.__name__) + func = self._class_instance._original_funcs[func_name] + setattr(self._class_instance, func_name, + func.__get__(self._class_instance)) + + for sublayer in self._class_instance.sublayers(include_self=False): + rollback_impl(sublayer) + + return getattr(self._class_instance, func_name) + + def __deepcopy__(self, memo): + """ + Customized behavior for copy.deepcopy, return original decorated function instead + of a new StaticFunction Object. StaticFunction itself is not copyable becuase it's + associated with class_instance. + + We add __deepcopy__ here only for the following usage: + + Example:: + .. code-block:: python + + import copy + import paddle + + class Net(paddle.nn.Layer): + def __init__(self): + super(Net, self).__init__() + + def forward(self, x, flag=True): + if flag: + out = x + 1 + else: + out = x - 1 + return out + + x = paddle.randn([10, 1], 'float32') + net = paddle.jit.to_static(Net()) # convert into static mode + + copy_net = copy.deepcopy(net) # deepcopy a new net without @to_static + + Please attention that original 'net' will unwrap @to_static and rollback into simple Layer. + """ + if self._class_instance is not None: + net_name = type(self._class_instance).__name__ + logging_utils.log( + level=-1, + msg="Not recommend to deepcopy '{}' decorated with @to_static, it has side effect that will" \ + " rollback into original state before @to_static. Please deepcopy '{}' before applying @to_static." + .format(net_name, net_name)) + self.rollback() + return self._dygraph_function.__get__(memo[id( + self._class_instance)]) + else: + return self._dygraph_function + + @property + def inputs(self): + """ + Returns input tensors of recent converted static program. + """ + self._raise_when_property() + concrete_program = self.concrete_program + inputs = [ + var for var in flatten(concrete_program.inputs) + if isinstance(var, framework.Variable) + ] + return inputs + + @property + def outputs(self): + """ + Returns output tensors of recent converted static program. + """ + self._raise_when_property() + concrete_program = self.concrete_program + outputs = [ + var for var in flatten(concrete_program.outputs) + if isinstance(var, framework.Variable) + ] + + return outputs + + @property + def main_program(self): + """ + Returns recent converted static main program. + """ + self._raise_when_property() + concrete_program = self.concrete_program + main_program = concrete_program.main_program + return main_program + + @property + def program_cache(self): + return self._program_cache + + @property + def function_spec(self): + return self._function_spec + + +def _verify_init_in_dynamic_mode(class_instance): + """ + Verifies the instance is initialized in dynamic mode. + """ + if isinstance(class_instance, layers.Layer): + if not class_instance._init_in_dynamic_mode: + raise RuntimeError( + " `paddle.jit.to_static` is only available in dynamic mode. Please call `paddle.disable_static()` before " + "initializing your Layer class `{}` . Because parameters of Layer class should be initialized firstly " + "in dynamic mode while applying transformation.".format( + class_instance)) + + +class HookHelper(object): + """ + Only For converting pre/post hooks operation in outermost layer while jit.save. + Because hooks in sublayer have been processed automatically. + """ + + def __init__(self, func, class_instance, with_hook=False): + self.func = func + self.class_instance = class_instance + self.with_hook = with_hook + self.need_apply_hook = with_hook and isinstance( + self.class_instance, layers.Layer) and getattr( + func, "__name__") == "forward" + + def apply_pre_hooks(self, inputs): + """ + Apply _forward_pre_hooks from outermost layer + """ + if not self.need_apply_hook: return inputs + + inputs = inputs[1:] + for forward_pre_hook in self.class_instance._forward_pre_hooks.values(): + hook_result = forward_pre_hook(self.class_instance, inputs) + if hook_result is not None: + if not isinstance(hook_result, tuple): + hook_result = (hook_result, ) + inputs = hook_result + + return [self.class_instance] + list(inputs) + + def apply_post_hooks(self, inputs, outputs): + """ + Apply _forward_post_hooks from outermost layer + """ + if not self.need_apply_hook: return outputs + + inputs = inputs[1:] + for forward_post_hook in self.class_instance._forward_post_hooks.values( + ): + hook_result = forward_post_hook(self.class_instance, inputs, + outputs) + if hook_result is not None: + outputs = hook_result + + inputs.insert(0, self.class_instance) + return outputs + + +class ConcreteProgram(object): + + __slots__ = [ + 'inputs', 'outputs', 'main_program', "startup_program", "parameters", + "function", 'kwargs' + ] + + def __init__(self, + inputs, + outputs, + parameters, + function, + main_program, + startup_program=None, + **kwargs): + self.inputs = inputs + self.outputs = outputs + self.main_program = main_program + self.startup_program = startup_program + self.parameters = parameters + self.function = function + self.kwargs = kwargs + + @staticmethod + @switch_to_static_graph + def from_func_spec(func_spec, input_spec, input_kwargs_spec, class_instance, + **kwargs): + """ + Builds the main_program with specialized inputs and returns outputs + of program as fetch_list. + + Args: + func_spec(FunctionSpec): A FunctionSpec instance for decorated function. + input_spec(list[InputSpec]): + """ + # verify the instance is initialized in imperative mode. + _verify_init_in_dynamic_mode(class_instance) + + # Transforms dygraph function into static function and caches it. + dygraph_function = func_spec.dygraph_function + static_func = convert_to_static(dygraph_function) + # apply pre\post hook for outermost layer + hook_helper = HookHelper(dygraph_function, class_instance, + kwargs.get("with_hook", False)) + + main_program, startup_program = framework.Program(), framework.Program() + # Note: The random seed should be synchronized into cached program + # if set in `fluid.dygraph_guard` because some ops rely on it, such as + # `fluid.layers.dropout`. + main_program.random_seed = framework.default_main_program().random_seed + startup_program.random_seed = framework.default_startup_program( + ).random_seed + + from paddle.fluid.dygraph.base import _switch_declarative_mode_guard_ + with framework.program_guard(main_program, startup_program): + with _switch_declarative_mode_guard_(is_declarative=True): + # 1. Adds `fluid.data` layers for input if needed + static_inputs = func_spec.to_static_inputs_with_spec( + input_spec, main_program) + _kwargs = func_spec.to_static_inputs_with_spec( + input_kwargs_spec, main_program) + if class_instance: + static_inputs = tuple([class_instance] + + list(static_inputs)) + + # 2. Gets all ParamBases and buffered VarBases in the function + all_parameters_and_buffers = _extract_indeed_params_buffers( + class_instance) + + # 3. Builds program only once and returns the output Variables. + with param_guard(get_parameters( + class_instance, + False)), param_guard(get_buffers(class_instance, + False)): + try: + # only for jit.save, do nothing while train and eval process + inputs = hook_helper.apply_pre_hooks(static_inputs) + if _kwargs: + outputs = static_func(*inputs, **_kwargs) + else: + outputs = static_func(*inputs) + outputs = hook_helper.apply_post_hooks(inputs, outputs) + except BaseException as e: + # NOTE: If e is raised in compile time, e should be attached to ERROR_DATA here. + error.attach_error_data(e) + error_data = getattr(e, error.ERROR_DATA, None) + if error_data: + error_data.raise_new_exception() + raise + + if outputs is not None: + need_wrap_into_list = not isinstance( + outputs, (tuple, list)) or len(outputs) == 1 + if need_wrap_into_list: + outputs = [outputs] + + main_program = update_op_callstack_with_origin_info(main_program) + + return ConcreteProgram(inputs=static_inputs, + outputs=outputs, + parameters=all_parameters_and_buffers, + function=dygraph_function, + main_program=main_program, + startup_program=startup_program, + **kwargs) + + +def _extract_indeed_params_buffers(class_instance): + """ + To filter not initialzed buffers. + """ + params = list(get_parameters(class_instance).values()) + buffers = list(get_buffers(class_instance).values()) + buffers = [buffer for buffer in buffers if len(buffer.shape) != 0] + + return params + buffers + + +class ProgramCache(object): + """ + Wrapper class for the program functions defined by dygraph function. + """ + + def __init__(self): + # {hash_id : (concrete_program, partial_layer)} + self._caches = collections.OrderedDict() + # trace mostly recent used program + self._recent_key = None + self._recent_cache_key = None + + def _build_once(self, cache_key): + concrete_program = ConcreteProgram.from_func_spec( + func_spec=cache_key.function_spec, + input_spec=cache_key.input_args_with_spec, + input_kwargs_spec=cache_key.input_kwargs_with_spec, + class_instance=cache_key.class_instance, + **cache_key.kwargs) + return concrete_program, partial_program_from(concrete_program) + + def __getitem__(self, item): + if not isinstance(item, CacheKey): + raise ValueError('type(item) should be CacheKey, but received %s' % + type_name(item)) + item_id = hash(item) + self._recent_cache_key = item + self._recent_key = item_id + if item_id not in self._caches: + self._caches[item_id] = self._build_once(item) + # Note: raise warnings if number of traced program is more than `max_tracing_count` + current_tracing_count = len(self._caches) + if current_tracing_count > MAX_TRACED_PROGRAM_COUNT: + logging_utils.warn( + "Current traced program number: {} > `max_tracing_count`:{}. Too much cached programs will bring expensive overhead. " + "The reason may be: (1) passing tensors with different shapes, (2) passing python objects instead of tensors." + .format(current_tracing_count, MAX_TRACED_PROGRAM_COUNT)) + + return self._caches[item_id] + + def get_program(self, item): + if not isinstance(item, CacheKey): + raise ValueError( + "Input item's type should be FunctionSpec, but received %s" % + type_name(item)) + item_id = hash(item) + if item_id not in self._caches: + raise RuntimeError( + "Failed to find program for input item, please decorate input function by `@paddle.jit.to_static`." + ) + return self._caches[item_id] + + def last(self): + assert len( + self._caches) >= 1, "No valid cached program in ProgramCache." + assert self._recent_key is not None + return self._recent_key, self._caches[self._recent_key] + + def __len__(self): + return len(self._caches) + + def concrete_programs(self): + return [cp for key, (cp, _) in six.iteritems(self._caches)] + + +def synchronized(func): + func.__lock__ = threading.Lock() + + def lock_func(*args, **kwargs): + with func.__lock__: + return func(*args, **kwargs) + + return lock_func + + +class ProgramTranslator(object): + """ + Class to translate dygraph function into static graph function. The object + of this class is a singleton. + + Args: + None. + + Returns: + ProgramTranslator: the singleton object. + + Examples: + .. code-block:: python + + import paddle + + # Two methods get same object because ProgramTranslator is a singleton + paddle.jit.ProgramTranslator() + paddle.jit.ProgramTranslator.get_instance() + + """ + + _singleton_lock = threading.Lock() + _instance = None + + @synchronized + def __new__(cls, *args, **kwargs): + if cls._instance is None: + cls._instance = object.__new__(cls, *args, **kwargs) + cls._instance._initialized = False + return cls._instance + + @classmethod + def get_instance(cls): + if cls._instance is None: + with cls._singleton_lock: + cls._instance = cls() + return cls._instance + + @classmethod + def reset(cls): + if cls._instance is not None: + cls._instance._initialized = False + cls._instance.__init__() + + def __init__(self): + # To make sure that calls __init__ only once. + if self._initialized: + return + self._initialized = True + self._program_cache = ProgramCache() + self.enable_to_static = True + + def enable(self, enable_to_static): + """ + Enable or disable the converting from imperative to static graph by + ProgramTranslator globally. + + Args: + enable_to_static (bool): True or False to enable or disable converting to static. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + + + @paddle.jit.to_static + def func(x): + if paddle.mean(x) > 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + + prog_trans = paddle.jit.ProgramTranslator() + prog_trans.enable(False) + + x = paddle.ones([1, 2]) + # ProgramTranslator is disabled so the func is run in dygraph + print(func(x)) # [[0. 0.]] + + """ + check_type(enable_to_static, "enable_to_static", bool, + "ProgramTranslator.enable") + self.enable_to_static = enable_to_static + + def get_output(self, dygraph_func, *args, **kwargs): + """ + Returns the output dygraph Tensor for dygraph function. The dygraph + function will be translated into static graph function so the under + beneath numerical result will be calculated by static graph mode. + + Args: + dygraph_func (callable): the dygraph function. + *args (tuple): the input argument of dygraph_func. + **kwargs (dict): the input argument of dygraph_func. + + Returns: + Tensor or tuple of Tensors: the dygraph Tensor containing digital result. + + Examples: + .. code-block:: python + + import paddle + + + def func(x): + if paddle.mean(x) > 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + + prog_trans = paddle.jit.ProgramTranslator() + + x = paddle.ones([1, 2]) + x_v = prog_trans.get_output(func, x) + print(x_v) # [[0. 0.]] + + """ + assert callable( + dygraph_func + ), "Input dygraph_func is not a callable in ProgramTranslator.get_output" + + if not self.enable_to_static: + # Here calls `warnings.warn` but not `logging_utils.warn` because by default warnings.warn(message) + # will show up **only once**. + logging_utils.warn( + "The ProgramTranslator.get_output doesn't work when setting ProgramTranslator.enable to False. " + "We will just return dygraph output. " + "Please call ProgramTranslator.enable(True) if you would like to get static output." + ) + return dygraph_func(*args, **kwargs) + try: + function_spec = FunctionSpec(dygraph_func) + cache_key = CacheKey.from_func_and_args( + function_spec, args, kwargs, + getattr(dygraph_func, '__self__', None)) + _, partial_program_layer = self._program_cache[cache_key] + + if args and isinstance(args[0], layers.Layer): + # Synchronize self.training attribute. + partial_program_layer.training = args[0].training + args = args[1:] + try: + return partial_program_layer(args) + except BaseException as e: + # NOTE: + # 1. If e is raised in compile time, e should have been attached to ERROR_DATA before; + # 2. If e raised in runtime, e should be attached to ERROR_DATA here. + if not hasattr(e, error.ERROR_DATA): + # runtime error + error.attach_error_data(e, in_runtime=True) + raise + except BaseException as e: + error_data = getattr(e, error.ERROR_DATA, None) + if error_data: + error_data.raise_new_exception() + else: + logging_utils.warn( + "Please file an issue at 'https://github.com/PaddlePaddle/Paddle/issues'" + " if you can't handle this {} yourself.".format(type(e))) + raise e + + def get_func(self, dygraph_func): + """ + Returns a callable function which converts imperative dygraph APIs of + the input dygraph_func into declarative net-building APIs, which means + it doesn't return immediate digital result as get_output does. + Users should handle Program and Executor by themselves. + + Args: + dygraph_func (callable): the dygraph function. + + Returns: + callable: converting imperative dygraph APIs into declarative + net-building APIs. + + Examples: + .. code-block:: python + + import paddle + + + def func(x): + if paddle.mean(x) > 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + + prog_trans = paddle.jit.ProgramTranslator() + static_func = prog_trans.get_func(func) + print(callable(static_func)) # True + + """ + assert callable( + dygraph_func + ), "Input dygraph_func is not a callable in ProgramTranslator.get_func" + + if not self.enable_to_static: + logging_utils.warn( + "The ProgramTranslator.get_func doesn't work when setting ProgramTranslator.enable to False. We will " + "just return dygraph output. Please call ProgramTranslator.enable(True) if you would like to get static output." + ) + return dygraph_func + + static_func = convert_to_static(dygraph_func) + return static_func + + def get_program(self, dygraph_func, *args, **kwargs): + """ + Returns the translated static program and input/output Tensors from + dygraph function. The users can use the program to run by executor. + + Args: + dygraph_func (callable): the dygraph function. + *args (tuple): the input argument of dygraph_func. + **kwargs (dict): the input argument of dygraph_func. + + Returns: + tuple of (main_program, startup_program, inputs, outputs) whose + types are (Program, Program, list of Tensors, list of Tensors). + main_program: the converted main program. + startup_program: the converted startup program. + inputs: list of input Tensors which need to be fed. + outputs: list of output Tensors which users can fetch. + + Examples: + .. code-block:: python + + import paddle + + + def func(x): + if paddle.mean(x) > 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + + prog_trans = paddle.jit.ProgramTranslator() + x = paddle.ones([1, 2]) + main_prog, start_prog, inputs, outputs = prog_trans.get_program(func, x) + print([i.name for i in inputs]) + # [u'generated_tensor_0'] the feed input Tensor name representing x + print([o.name for o in outputs]) + # [u'_generated_var_4'] the fetch output Tensor name representing x_v + + """ + assert callable( + dygraph_func + ), "Input dygraph_func is not a callable in ProgramTranslator.get_program" + + if not self.enable_to_static: + logging_utils.warn( + "The ProgramTranslator.get_program doesn't work when setting ProgramTranslator.enable to False." + "We will just return dygraph output. " + "Please call ProgramTranslator.enable(True) if you would like to get static output." + ) + return dygraph_func(*args, **kwargs) + + function_spec = FunctionSpec(dygraph_func) + cache_key = CacheKey.from_func_and_args( + function_spec, args, kwargs, getattr(dygraph_func, '__self__', + None)) + concrete_program, partial_program_layer = self._program_cache[cache_key] + + # Note: concrete_program hold all input/output infos include non-Variable + input_vars = [ + var for var in concrete_program.inputs + if isinstance(var, framework.Variable) + ] + output_vars = [ + var for var in concrete_program.outputs + if isinstance(var, framework.Variable) + ] + + return concrete_program.main_program, \ + concrete_program.startup_program, \ + input_vars, \ + output_vars + + def get_code(self, dygraph_func): + """ + Returns the translated static function string code from dygraph function. + + Args: + dygraph_func (callable): the dygraph function. + + Returns: + str: the string code of translated static function. + + Examples: + .. code-block:: python + + import paddle + + + def func(x): + if paddle.mean(x) > 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + + prog_trans = paddle.jit.ProgramTranslator() + + code = prog_trans.get_code(func) + print(type(code)) # + + """ + assert callable( + dygraph_func + ), "Input dygraph_func is not a callable in ProgramTranslator.get_code" + # Gets AST from dygraph function + + unwrap_func = unwrap(dygraph_func) + raw_code = inspect.getsource(unwrap_func) + code = textwrap.dedent(raw_code) + root = gast.parse(code) + + # Transform AST + dygraph_to_static = DygraphToStaticAst() + root_wrapper = dygraph_to_static.get_static_ast(root) + + # Get source_code + source_code = ast_to_source_code(root_wrapper.node) + return source_code + + def get_program_cache(self): + """ + Returns the ProgramCache instance. This method is used by PaddlePaddle + developers to manage program cache in ProgramTranslator. Normal users + don't have to call this method. + + Returns: + ProgramCache: ProgramCache instance of ProgramTranslator. + + Examples: + .. code-block:: python + + import paddle + + prog_trans = paddle.jit.ProgramTranslator() + prog_cache = prog_trans.get_program_cache() + + """ + return self._program_cache diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/return_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/return_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..17a55fa0b743010a02267407808f34ea98e103da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/return_transformer.py @@ -0,0 +1,372 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast + +from paddle.fluid import unique_name +from paddle.fluid.dygraph.dygraph_to_static.utils import index_in_list +from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import ForToWhileTransformer +from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import create_fill_constant_node +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer +from paddle.fluid.dygraph.dygraph_to_static.utils import Dygraph2StaticException +from paddle.fluid.dygraph.dygraph_to_static.utils import ORIGI_INFO + +__all__ = [ + 'RETURN_NO_VALUE_MAGIC_NUM', 'RETURN_NO_VALUE_VAR_NAME', 'ReturnTransformer' +] + +# Constant for the name of the variable which stores the boolean state that we +# should return +RETURN_PREFIX = '__return' + +# Constant for the name of the variable which stores the final return value +RETURN_VALUE_PREFIX = '__return_value' + +# Constant for the name of variables to initialize the __return_value +RETURN_VALUE_INIT_NAME = '__return_value_init' + +# Constant magic number representing returning no value. This constant amis to +# support returning various lengths of variables. Static graph must have fixed +# size of fetched output while dygraph can have flexible lengths of output, to +# solve it in dy2stat, we put float64 value with this magic number at Static +# graph as a place holder to indicate the returning placeholder means no value +# should return. + +# Assign not support float64, use float32 value as magic number. +RETURN_NO_VALUE_MAGIC_NUM = 1.77113e+27 +RETURN_NO_VALUE_VAR_NAME = "__no_value_return_var" + + +def get_return_size(return_node): + assert isinstance(return_node, gast.Return), "Input is not gast.Return node" + return_length = 0 + if return_node.value is not None: + if isinstance(return_node.value, gast.Tuple): + return_length = len(return_node.value.elts) + else: + return_length = 1 + return return_length + + +class ReplaceReturnNoneTransformer(BaseTransformer): + """ + Replace 'return None' to 'return' because 'None' cannot be a valid input + in control flow. In ReturnTransformer single 'Return' will be appended no + value placeholder + """ + + def __init__(self, root_node): + self.root = root_node + + def transform(self): + self.visit(self.root) + + def visit_Return(self, node): + if isinstance(node.value, gast.Name) and node.value.id == 'None': + node.value = None + return node + if isinstance(node.value, gast.Constant) and node.value.value == None: + node.value = None + return node + return node + + +class ReturnAnalysisVisitor(gast.NodeVisitor): + """ + Visits gast Tree and analyze the information about 'return'. + """ + + def __init__(self, root_node): + self.root = root_node + assert isinstance( + self.root, gast.FunctionDef), "Input is not gast.FunctionDef node" + + # the number of return statements + self.count_return = 0 + + # maximum number of variables + self.max_return_length = 0 + + self.visit(self.root) + + def visit_FunctionDef(self, node): + """ + don't analysis closure, just analyze current func def level. + """ + if node == self.root: + self.generic_visit(node) + + def visit_Return(self, node): + self.count_return += 1 + + return_length = get_return_size(node) + self.max_return_length = max(self.max_return_length, return_length) + + self.generic_visit(node) + + def get_func_return_count(self): + return self.count_return + + def get_func_max_return_length(self): + return self.max_return_length + + +class ReturnTransformer(BaseTransformer): + """ + Transforms return statements into equivalent python statements containing + only one return statement at last. The basics idea is using a return value + variable to store the early return statements and boolean states with + if-else to skip the statements after the return. + + Go through all the function definition and call SingleReturnTransformer for each function. + SingleReturnTransformer don't care the nested function def. + """ + + def __init__(self, wrapper_root): + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + pre_transformer = ReplaceReturnNoneTransformer(self.root) + pre_transformer.transform() + + def transform(self): + self.visit(self.root) + + def visit_FunctionDef(self, node): + node = self.generic_visit(node) + node = SingleReturnTransformer(node).transform() + return node + + +class SingleReturnTransformer(BaseTransformer): + """ + This function only apply to single function. don't care the nested function_def + """ + + def __init__(self, root): + self.root = root + assert isinstance( + self.root, gast.FunctionDef), "Input is not gast.FunctionDef node" + + self.ancestor_nodes = [] + + # The name of return placeholder + self.return_value_name = None + + # Every return stmt corresponds to a bool value variable, and return name is the name of the boolean variable + self.return_name = [] + + self.pre_analysis = None + + def assert_parent_is_not_while(self, parent_node_of_return): + if isinstance(parent_node_of_return, (gast.While, gast.For)): + raise Dygraph2StaticException( + "Found return statement in While or For body and loop " + "is meaningless, please check you code and remove return in while/for." + ) + + def generic_visit(self, node): + # Because we change ancestor nodes during visit_Return, not current + # node, original generic_visit of NodeTransformer will visit node + # which may be deleted. To prevent that node being added into + # transformed AST, We self-write a generic_visit and visit + for field, value in gast.iter_fields(node): + if isinstance(value, list): + for item in value: + if isinstance(item, gast.AST): + self.visit(item) + elif isinstance(value, gast.AST): + self.visit(value) + + def visit(self, node): + """ + Self-defined visit for appending ancestor + """ + self.ancestor_nodes.append(node) + ret = super(SingleReturnTransformer, self).visit(node) + self.ancestor_nodes.pop() + return ret + + def visit_FunctionDef(self, node): + """ + don't analysis closure, just analyze current func def level. + """ + if node == self.root: + self.generic_visit(node) + return node + + def append_assign_to_return_node(self, value, parent_node_of_return, + return_name, assign_nodes): + self.assert_parent_is_not_while(parent_node_of_return) + assert value in [True, False], "value must be True or False." + if isinstance(parent_node_of_return, gast.If): + # Prepend control flow boolean nodes such as '__return@1 = True' + node_str = "{} = _jst.create_bool_as_type({}, {})".format( + return_name, + ast_to_source_code(parent_node_of_return.test).strip(), value) + + assign_node = gast.parse(node_str).body[0] + assign_nodes.append(assign_node) + + def transform(self): + node = self.root + self.pre_analysis = ReturnAnalysisVisitor(node) + max_return_length = self.pre_analysis.get_func_max_return_length() + while self.pre_analysis.get_func_return_count() > 0: + # every visit will decrease the number of returns. + # so we need a while. + self.visit(node) + self.pre_analysis = ReturnAnalysisVisitor(node) + + if max_return_length == 0: + return node + + # Prepend initialization of final return and append final return statement + value_name = self.return_value_name + if value_name is not None: + node.body.append( + gast.Return(value=gast.Name(id=value_name, + ctx=gast.Load(), + annotation=None, + type_comment=None))) + assign_return_value_node = gast.Assign(targets=[ + gast.Name(id=value_name, + ctx=gast.Store(), + annotation=None, + type_comment=None) + ], + value=gast.Constant( + kind=None, value=None)) + node.body.insert(0, assign_return_value_node) + return node + + def visit_Return(self, node): + return_name = unique_name.generate(RETURN_PREFIX) + self.return_name.append(return_name) + max_return_length = self.pre_analysis.get_func_max_return_length() + parent_node_of_return = self.ancestor_nodes[-2] + + for ancestor_index in reversed(range(len(self.ancestor_nodes) - 1)): + ancestor = self.ancestor_nodes[ancestor_index] + cur_node = self.ancestor_nodes[ancestor_index + 1] + + def _deal_branches(branch_name): + if hasattr(ancestor, branch_name): + branch_node = getattr(ancestor, branch_name) + if index_in_list(branch_node, cur_node) != -1: + if cur_node == node: + self._replace_return_in_stmt_list( + branch_node, cur_node, return_name, + max_return_length, parent_node_of_return) + self._replace_after_node_to_if_in_stmt_list( + branch_node, cur_node, return_name, + parent_node_of_return) + + _deal_branches("body") + _deal_branches("orelse") + # If return node in while loop, add `not return_name` in gast.While.test + if isinstance(ancestor, gast.While): + cond_var_node = gast.UnaryOp(op=gast.Not(), + operand=gast.Name( + id=return_name, + ctx=gast.Load(), + annotation=None, + type_comment=None)) + ancestor.test = gast.BoolOp( + op=gast.And(), values=[ancestor.test, cond_var_node]) + continue + + # If return node in for loop, add `not return_name` in gast.While.test + if isinstance(ancestor, gast.For): + cond_var_node = gast.UnaryOp(op=gast.Not(), + operand=gast.Name( + id=return_name, + ctx=gast.Load(), + annotation=None, + type_comment=None)) + parent_node = self.ancestor_nodes[ancestor_index - 1] + for_to_while = ForToWhileTransformer(parent_node, ancestor, + cond_var_node) + new_stmts = for_to_while.transform() + while_node = new_stmts[-1] + self.ancestor_nodes[ancestor_index] = while_node + + if ancestor == self.root: + break + # return_node is replaced so we shouldn't return here + + def _replace_return_in_stmt_list(self, stmt_list, return_node, return_name, + max_return_length, parent_node_of_return): + + assert max_return_length >= 0, "Input illegal max_return_length" + i = index_in_list(stmt_list, return_node) + if i == -1: + return False + + assign_nodes = [] + self.append_assign_to_return_node(True, parent_node_of_return, + return_name, assign_nodes) + + return_length = get_return_size(return_node) + # In this case we should NOT append RETURN_NO_VALUE placeholder + if return_node.value is not None: + if self.return_value_name is None: + self.return_value_name = unique_name.generate( + RETURN_VALUE_PREFIX) + + assign_nodes.append( + gast.Assign(targets=[ + gast.Name(id=self.return_value_name, + ctx=gast.Store(), + annotation=None, + type_comment=None) + ], + value=return_node.value)) + return_origin_info = getattr(return_node, ORIGI_INFO, None) + setattr(assign_nodes[-1], ORIGI_INFO, return_origin_info) + + # If there is a return in the body or else of if, the remaining statements + # will not be executed, so they can be properly replaced. + stmt_list[i:] = assign_nodes + return True + + def _replace_after_node_to_if_in_stmt_list(self, stmt_list, node, + return_name, + parent_node_of_return): + i = index_in_list(stmt_list, node) + if i < 0 or i >= len(stmt_list): + return False + if i == len(stmt_list) - 1: + # No need to add, we consider this as added successfully + return True + + if_stmt = gast.If(test=gast.UnaryOp(op=gast.Not(), + operand=gast.Name( + id=return_name, + ctx=gast.Store(), + annotation=None, + type_comment=None)), + body=stmt_list[i + 1:], + orelse=[]) + + stmt_list[i + 1:] = [if_stmt] + + # Here assume that the parent node of return is gast.If + assign_nodes = [] + self.append_assign_to_return_node(False, parent_node_of_return, + return_name, assign_nodes) + stmt_list[i:i] = assign_nodes + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/static_analysis.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/static_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..82177b343aaf4be8fda7231324cf0a17619423c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/static_analysis.py @@ -0,0 +1,445 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast +from .logging_utils import warn +from .utils import is_paddle_api, is_dygraph_api, is_numpy_api, index_in_list, ast_to_source_code + +__all__ = ['AstNodeWrapper', 'NodeVarType', 'StaticAnalysisVisitor'] + + +class NodeVarType(object): + """ + Enum class of python variable types. We have to know some variable types + during compile time to transfer AST. For example, a string variable and a + tensor variable in if clause may lead to different conversion from dygraph + to static graph. + """ + ERROR = -1 # Returns when static analysis gets error + UNKNOWN = 0 # Reserve for AST nodes have not known the type + STATEMENT = 1 # For nodes representing statement (non-variable type) + CALLABLE = 2 + + # python data types + NONE = 100 + BOOLEAN = 101 + INT = 102 + FLOAT = 103 + STRING = 104 + TENSOR = 105 + NUMPY_NDARRAY = 106 + + # python collections + LIST = 200 + SET = 201 + DICT = 202 + + PADDLE_DYGRAPH_API = 300 + PADDLE_CONTROL_IF = 301 + PADDLE_CONTROL_WHILE = 302 + PADDLE_CONTROL_FOR = 303 + # Paddle API may not be visible to get source code. + # We use this enum value to denote the type return by a Paddle API + PADDLE_RETURN_TYPES = 304 + + # If node.node_var_type in TENSOR_TYPES, it can be considered as tensor-dependent. + TENSOR_TYPES = {TENSOR, PADDLE_RETURN_TYPES} + + Annotation_map = { + "Tensor": TENSOR, + "paddle.Tensor": TENSOR, + "int": INT, + "float": FLOAT, + "bool": BOOLEAN, + "str": STRING + } + + @staticmethod + def binary_op_output_type(in_type1, in_type2): + if in_type1 == in_type2: + return in_type1 + + if in_type1 == NodeVarType.UNKNOWN: + return in_type2 + if in_type2 == NodeVarType.UNKNOWN: + return in_type1 + + supported_types = [ + NodeVarType.BOOLEAN, NodeVarType.INT, NodeVarType.FLOAT, + NodeVarType.NUMPY_NDARRAY, NodeVarType.TENSOR, + NodeVarType.PADDLE_RETURN_TYPES + ] + + if in_type1 not in supported_types: + return NodeVarType.UNKNOWN + if in_type2 not in supported_types: + return NodeVarType.UNKNOWN + + forbidden_types = [NodeVarType.NUMPY_NDARRAY, NodeVarType.TENSOR] + if in_type1 in forbidden_types and in_type2 in forbidden_types: + return NodeVarType.UNKNOWN + return max(in_type1, in_type2) + + @staticmethod + def type_from_annotation(annotation): + annotation_str = ast_to_source_code(annotation).strip() + if annotation_str in NodeVarType.Annotation_map: + return NodeVarType.Annotation_map[annotation_str] + + # raise warning if not found + warn("Currently we don't support annotation: %s" % annotation_str) + return NodeVarType.UNKNOWN + + +class AstNodeWrapper(object): + """ + Wrapper for python gast.node. We need a node wrapper because gast.node + doesn't store all required information when we are transforming AST. + We should collect additional information which the actual transformation + needs. + """ + + def __init__(self, node): + self.node = node + self.parent = None + self.children = [] + self.node_var_type = {NodeVarType.UNKNOWN} + + +class AstVarScope(object): + """ + AstVarScope is a class holding the map from current scope variable to its + type. + """ + SCOPE_TYPE_SCRIPT = 0 + SCOPE_TYPE_FUNCTION = 1 + SCOPE_TYPE_CLASS = 2 + + def __init__(self, + scope_name='', + scope_type=SCOPE_TYPE_SCRIPT, + parent_scope=None): + self.sub_scopes = [] + self.name_to_id = {} + self.id_to_type = {} + self.cur_id = 0 + + self.scope_name = scope_name + self.scope_type = scope_type + self.parent_scope = parent_scope + if parent_scope is not None: + parent_scope.sub_scopes.append(self) + + def add_var_type(self, var_name, node_var_type): + var_type = self.get_var_type(var_name) + if var_type == {NodeVarType.UNKNOWN}: + self.set_var_type(var_name, node_var_type) + else: + if isinstance(node_var_type, set): + var_type.update(node_var_type) + else: + var_type.add(node_var_type) + + def set_var_type(self, var_name, node_var_type): + if var_name in self.name_to_id: + num_id = self.name_to_id[var_name] + else: + num_id = self.cur_id + self.cur_id += 1 + self.name_to_id[var_name] = num_id + self.id_to_type[num_id] = node_var_type if isinstance( + node_var_type, set) else {node_var_type} + + def get_var_type(self, var_name): + if var_name in self.name_to_id: + num_id = self.name_to_id[var_name] + return self.id_to_type[num_id] + if self.parent_scope is None: + return {NodeVarType.UNKNOWN} + return self.parent_scope.get_var_type(var_name) + + +class AstVarEnv(object): + """ + A class maintains scopes and mapping from name strings to type. + """ + + def __init__(self): + self.cur_scope = AstVarScope() + + def enter_scope(self, scope_name, scope_type): + self.cur_scope = AstVarScope(scope_name, + scope_type, + parent_scope=self.cur_scope) + return self.cur_scope + + def exit_scope(self): + assert self.cur_scope.parent_scope is not None, "Call exit_scope in "\ + "AstVarEnv when current scope doesn't have parent scope." + self.cur_scope = self.cur_scope.parent_scope + return self.cur_scope + + def get_parent_scope(self): + assert self.cur_scope.parent_scope is not None, "Call parent_scope in "\ + "AstVarEnv when current scope doesn't have parent scope." + return self.cur_scope.parent_scope + + def add_var_type(self, var_name, node_var_type): + self.cur_scope.add_var_type(var_name, node_var_type) + + def set_var_type(self, var_name, node_var_type): + self.cur_scope.set_var_type(var_name, node_var_type) + + def get_var_type(self, var_name): + return self.cur_scope.get_var_type(var_name) + + def get_scope_var_type(self): + ''' + Returns a dict mapping from variable name to type. Used for debug and + test. + ''' + cur_scope_dict = {} + for name in self.cur_scope.name_to_id: + node_var_type = self.cur_scope.get_var_type(name) + cur_scope_dict[name] = node_var_type + return cur_scope_dict + + +class StaticAnalysisVisitor(object): + """ + A class that does static analysis + """ + + def __init__(self, ast_root=None): + if ast_root is not None: + self.run(ast_root) + + def run(self, ast_root): + self.node_wrapper_root = None + self.ancestor_wrappers = [] + self.node_to_wrapper_map = {} + self.var_env = AstVarEnv() + + self.dfs_visit(ast_root) + + def dfs_visit(self, node): + # AST reuses some gast.nodes, such as Param node of expr_context + if node not in self.node_to_wrapper_map: + cur_wrapper = AstNodeWrapper(node) + self.node_to_wrapper_map[node] = cur_wrapper + else: + cur_wrapper = self.node_to_wrapper_map[node] + + if self.node_wrapper_root is None: + self.node_wrapper_root = cur_wrapper + + if len(self.ancestor_wrappers) != 0: + last_wrapper = self.ancestor_wrappers[-1] + last_wrapper.children.append(cur_wrapper) + cur_wrapper.parent = last_wrapper + + self.ancestor_wrappers.append(cur_wrapper) + for child in gast.iter_child_nodes(node): + if isinstance(child, gast.FunctionDef) or isinstance( + child, gast.AsyncFunctionDef): + # TODO: current version is function name mapping to its type + # consider complex case involving parameters + self.var_env.enter_scope(child.name, + AstVarScope.SCOPE_TYPE_FUNCTION) + func_type = self.dfs_visit(child) + self.var_env.exit_scope() + else: + self.dfs_visit(child) + self.ancestor_wrappers.pop() + + cur_wrapper.node_var_type = self._get_node_var_type(cur_wrapper) + return cur_wrapper.node_var_type + + def get_node_wrapper_root(self): + return self.node_wrapper_root + + def get_node_to_wrapper_map(self): + return self.node_to_wrapper_map + + def get_var_env(self): + return self.var_env + + def is_tensor_node(self, node): + tensor_types = {NodeVarType.TENSOR, NodeVarType.PADDLE_RETURN_TYPES} + node_wrapper = self.node_to_wrapper_map.get(node, None) + if node_wrapper is None: + return False + if node_wrapper.node_var_type & tensor_types: + return True + + def _get_constant_node_type(self, node): + assert isinstance(node, gast.Constant), \ + "Type of input node should be gast.Constant, but received %s" % type(node) + # singleton: None, True or False + if node.value is None: + return {NodeVarType.NONE} + if isinstance(node.value, bool): + return {NodeVarType.BOOLEAN} + if isinstance(node.value, int): + return {NodeVarType.INT} + if isinstance(node.value, float): + return {NodeVarType.FLOAT} + if isinstance(node.value, str): + return {NodeVarType.STRING} + + return {NodeVarType.UNKNOWN} + + def _get_node_var_type(self, cur_wrapper): + node = cur_wrapper.node + if isinstance(node, gast.Constant): + return self._get_constant_node_type(node) + + if isinstance(node, gast.BoolOp): + return {NodeVarType.BOOLEAN} + if isinstance(node, gast.Compare): + return {NodeVarType.BOOLEAN} + + if isinstance(node, gast.Dict): + return {NodeVarType.DICT} + if isinstance(node, gast.Set): + return {NodeVarType.SET} + + if isinstance(node, gast.UnaryOp): + return self.node_to_wrapper_map[node.operand].node_var_type + + if isinstance(node, gast.BinOp): + left_type = self.node_to_wrapper_map[node.left].node_var_type + right_type = self.node_to_wrapper_map[node.right].node_var_type + result_type = set() + for l in left_type: + for r in right_type: + result_type.add(NodeVarType.binary_op_output_type(l, r)) + return result_type + + if isinstance(node, gast.Assign): + ret_type = self.node_to_wrapper_map[node.value].node_var_type + for target in node.targets: + if isinstance(target, gast.Name): + self.node_to_wrapper_map[target].node_var_type = ret_type + self.var_env.set_var_type(target.id, ret_type) + # Handle statements like `a, b = paddle.shape(x)` + elif isinstance(target, gast.Tuple): + for sub_target in target.elts: + if isinstance(sub_target, gast.Name): + self.node_to_wrapper_map[ + sub_target].node_var_type = ret_type + self.var_env.set_var_type(sub_target.id, ret_type) + return ret_type + + if isinstance(node, gast.AnnAssign): + # TODO(0x45f): To determine whether need to support assignment statements + # like `self.x: float = 2.1`. + ret_type = {NodeVarType.type_from_annotation(node.annotation)} + # if annotation and value(Constant) are diffent type, we use value type + if node.value: + node_value_type = self.node_to_wrapper_map[ + node.value].node_var_type + if not (node_value_type + & {NodeVarType.UNKNOWN, NodeVarType.STATEMENT}): + ret_type = node_value_type + if isinstance(node.target, gast.Name): + self.node_to_wrapper_map[node.target].node_var_type = ret_type + self.var_env.set_var_type(node.target.id, ret_type) + return ret_type + + if isinstance(node, gast.Name): + if node.id == "None": + return {NodeVarType.NONE} + if node.id in {"True", "False"}: + return {NodeVarType.BOOLEAN} + # If node is child of functionDef.arguments + parent_node_wrapper = cur_wrapper.parent + if parent_node_wrapper and isinstance(parent_node_wrapper.node, + gast.arguments): + + return self._get_func_argument_type(parent_node_wrapper, node) + + return self.var_env.get_var_type(node.id) + + if isinstance(node, gast.Return): + # If return nothing: + if node.value is None: + return {NodeVarType.NONE} + + return_type = self.node_to_wrapper_map[node.value].node_var_type + assert self.var_env.cur_scope.scope_type == AstVarScope.SCOPE_TYPE_FUNCTION, "Return at non-function scope" + func_name = self.var_env.cur_scope.scope_name + parent_scope = self.var_env.get_parent_scope() + parent_scope.add_var_type(func_name, return_type) + return return_type + + if isinstance(node, gast.Call): + if is_dygraph_api(node): + if isinstance(node.func, gast.Attribute): + if node.func.attr == "to_variable": + return {NodeVarType.TENSOR} + if is_paddle_api(node): + return {NodeVarType.PADDLE_RETURN_TYPES} + if is_numpy_api(node): + # In this simple version we assume numpy api returns nd-array + return {NodeVarType.NUMPY_NDARRAY} + + if isinstance(node.func, gast.Name): + return self.var_env.get_var_type(node.func.id) + if isinstance(node, gast.Subscript): + if self.is_tensor_node(node.value): + return {NodeVarType.TENSOR} + + return {NodeVarType.STATEMENT} + + def _get_func_argument_type(self, parent_node_wrapper, node): + """ + Returns type information by parsing annotation or default values. + + For example: + 1. parse by default values. + foo(x, y=1, z='s') -> x: UNKNOWN, y: INT, z: STR + + 2. parse by Py3 type annotation. + foo(x: Tensor, y: int, z: str) -> x: Tensor, y: INT, z: STR + + 3. parse by type annotation and default values. + foo(x: Tensor, y: int, z: str = 'abc') -> x: Tensor, y: INT, z: STR + + NOTE: Currently, we only support Tensor, int, bool, float, str et.al. + Other complicate types will be supported later. + """ + assert isinstance(node, gast.Name) + + parent_node = parent_node_wrapper.node + var_type = {NodeVarType.UNKNOWN} + if node.annotation is not None: + var_type = {NodeVarType.type_from_annotation(node.annotation)} + self.var_env.set_var_type(node.id, var_type) + + # if annotation and value(Constant) are diffent type, we use value type + if parent_node.defaults: + index = index_in_list(parent_node.args, node) + args_len = len(parent_node.args) + if index != -1 and args_len - index <= len(parent_node.defaults): + defaults_node = parent_node.defaults[index - args_len] + if isinstance(defaults_node, gast.Constant): + var_type = self._get_constant_node_type(defaults_node) + + # Add node with identified type into cur_env. + self.var_env.set_var_type(node.id, var_type) + + return var_type diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/tensor_shape_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/tensor_shape_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..88ece85cd139e90a9f6cfe62239bf6cf5938ca58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/tensor_shape_transformer.py @@ -0,0 +1,50 @@ +# 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. + +from __future__ import print_function + +from paddle.utils import gast + +from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class TensorShapeTransformer(BaseTransformer): + """ + This class transforms variable.shape into Static Graph Ast. + All 'xxx.shape' will be converted int '_jst.Shape(x)'. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of TensorShapeTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_Attribute(self, node): + self.generic_visit(node) + if node.attr == 'shape': + args = ast_to_source_code(node.value).strip() + # NOTE(dev): we can deal with paddle.shape in this case, but it's + # not pretty to modify into 'convert_shape(paddle)(x)[0]'. + if args != 'paddle': + convert_shape_func = "_jst.Shape({})".format(args) + shape_node = gast.parse(convert_shape_func).body[0].value + return shape_node + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/typehint_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/typehint_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..f258b98b50711942f62fac9ad0c874328ce0cdfd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/typehint_transformer.py @@ -0,0 +1,47 @@ +# Copyright (c) 2022 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. + +from paddle.utils import gast +import warnings + +from paddle.fluid.dygraph.dygraph_to_static.static_analysis import AstNodeWrapper +from paddle.fluid.dygraph.dygraph_to_static import utils +from paddle.fluid.dygraph.dygraph_to_static.base_transformer import BaseTransformer + + +class TypeHintTransformer(BaseTransformer): + """ + A class remove all the typehint in gast.Name(annotation). + Please put it behind other transformers because other transformer may relay on typehints. + """ + + def __init__(self, wrapper_root): + assert isinstance( + wrapper_root, AstNodeWrapper + ), "Input non-AstNodeWrapper node for the initialization of TypeHintTransformer." + self.wrapper_root = wrapper_root + self.root = wrapper_root.node + + def transform(self): + self.visit(self.root) + + def visit_FunctionDef(self, node): + node.returns = None + self.generic_visit(node) + return node + + def visit_Name(self, node): + node.annotation = None + self.generic_visit(node) + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d97a81e61697322487cea10dcf99666c4e59f08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/utils.py @@ -0,0 +1,1569 @@ +# 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. + +from __future__ import print_function + +import ast +import astor +import atexit +import copy +import collections +from paddle.utils import gast +import inspect +import os, sys +import shutil +import six +import tempfile +import textwrap +import numpy as np + +import paddle +from paddle.fluid import unique_name +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid import core +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.layers import assign +import collections +from functools import reduce +import warnings + +# Note(Aurelius): Do not forget the dot `.` to distinguish other +# module such as paddlenlp. +PADDLE_MODULE_PREFIX = 'paddle.' +DYGRAPH_MODULE_PREFIX = 'paddle.fluid.dygraph' +DYGRAPH_TO_STATIC_MODULE_PREFIX = 'paddle.fluid.dygraph.dygraph_to_static' +GET_ARGS_FUNC_PREFIX = 'get_args' +SET_ARGS_FUNC_PREFIX = 'set_args' +ALREADY_D2S = '__already_d2s' +ARGS_NAME = '__args' +# NOTE(liym27): Please use `getattr(ast_node, ORIGI_INFO)` instead of . operation to get the original information of ast node. +ORIGI_INFO = "Original information of source code for ast node." + + +class BaseNodeVisitor(gast.NodeVisitor): + """ + Implement customized NodeVisitor inherited from gast.NodeVisitor. + Ancestor nodes are traced to easily support more operations of currently + visited node. + """ + + def __init__(self): + self.ancestor_nodes = [] + + def visit(self, node): + """Visit a node.""" + self.ancestor_nodes.append(node) + + method = 'visit_' + node.__class__.__name__ + visitor = getattr(self, method, self.generic_visit) + ret = visitor(node) + self.ancestor_nodes.pop() + return ret + + +# imp is deprecated in python3 +from importlib.machinery import SourceFileLoader + +dygraph_class_to_static_api = { + "CosineDecay": "cosine_decay", + "ExponentialDecay": "exponential_decay", + "InverseTimeDecay": "inverse_time_decay", + "NaturalExpDecay": "natural_exp_decay", + "NoamDecay": "noam_decay", + "PiecewiseDecay": "piecewise_decay", + "PolynomialDecay": "polynomial_decay", +} + +DEL_TEMP_DIR = True # A flag to avoid atexit.register more than once +FOR_ITER_INDEX_PREFIX = '__for_loop_var_index' +FOR_ITER_TUPLE_PREFIX = '__for_loop_iter_tuple' +FOR_ITER_TARGET_PREFIX = '__for_loop_iter_target' +FOR_ITER_ITERATOR_PREFIX = '__for_loop_iter_iterator' +FOR_ITER_TUPLE_INDEX_PREFIX = '__for_loop_iter_tuple_index' +FOR_ITER_VAR_LEN_PREFIX = '__for_loop_var_len' +FOR_ITER_VAR_NAME_PREFIX = '__for_loop_iter_var' +FOR_ITER_ZIP_TO_LIST_PREFIX = '__for_loop_iter_zip' + +RE_PYNAME = '[a-zA-Z0-9_]+' +RE_PYMODULE = r'[a-zA-Z0-9_]+\.' + +# FullArgSpec is valid from Python3. Defined a Namedtuple to +# to make it available in Python2. +FullArgSpec = collections.namedtuple( + 'FullArgSpec', + [ + 'args', + 'varargs', + 'varkw', + 'defaults', + 'kwonlyargs', + 'kwonlydefaults', + 'annotations', + ], +) + + +def data_layer_not_check(name, shape, dtype='float32', lod_level=0): + """ + This function creates a Tensor on the global block. The created Tensor + doesn't check the dtype and the shape of feed data because dygraph input + data can be various-length. This API is used in translating dygraph into + static graph. + + Note: + The default :code:`stop_gradient` attribute of the Tensor created by + this API is true, which means the gradient won't be passed backward + through the data Tensor. Set :code:`var.stop_gradient = False` If + user would like to pass backward gradient. + + Args: + name (str): The name/alias of the Tensor, see :ref:`api_guide_Name` + for more details. + shape (list|tuple): List|Tuple of integers declaring the shape. You can + set "None" at a dimension to indicate the dimension can be of any + size. For example, it is useful to set changeable batch size as "None" + dtype (np.dtype|VarType|str, optional): The type of the data. Supported + dtype: bool, float16, float32, float64, int8, int16, int32, int64, + uint8. Default: float32 + lod_level (int, optional): The LoD level of the LoDTensor. Usually users + don't have to set this value. For more details about when and how to + use LoD level, see :ref:`user_guide_lod_tensor` . Default: 0 + + Returns: + Tensor: The global Tensor that gives access to the data. + """ + helper = LayerHelper('data', **locals()) + shape = list(shape) + for i in six.moves.range(len(shape)): + if shape[i] is None: + shape[i] = -1 + + return helper.create_global_variable( + name=name, + shape=shape, + dtype=dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + stop_gradient=True, + lod_level=lod_level, + is_data=True, + need_check_feed=False, + ) + + +def create_undefined_variable(): + from paddle.fluid.dygraph.dygraph_to_static.return_transformer import ( + RETURN_NO_VALUE_MAGIC_NUM, + ) + + var = data_layer_not_check( + unique_name.generate("undefined_var"), [1], "float64" + ) + var.stop_gradient = False + # the variable is created in block(0), we append assign in block(0) either. + helper = LayerHelper('create_undefined_variable', **locals()) + saved_block_ids = helper.main_program.current_block_idx + helper.main_program.current_block_idx = 0 + assign(RETURN_NO_VALUE_MAGIC_NUM, var) + helper.main_program.current_block_idx = saved_block_ids + return var + + +class UndefinedVar: + def __init__(self, name): + self.name = name + + def check(self): + raise UnboundLocalError( + "local variable '{}' should be created before using it." + ) + + +class Dygraph2StaticException(Exception): + def __init__(self, message): + super().__init__(message) + + +def saw(x): + if isinstance(x, UndefinedVar): + return x.check() + else: + return x + + +def getfullargspec(target): + if hasattr(inspect, "getfullargspec"): + return inspect.getfullargspec(target) + else: + argspec = inspect.getargspec(target) + return FullArgSpec( + args=argspec.args, + varargs=argspec.varargs, + varkw=argspec.keywords, + defaults=argspec.defaults, + kwonlyargs=[], + kwonlydefaults=None, + annotations={}, + ) + + +def parse_arg_and_kwargs(function): + """ + Returns full argument names as list. e.g ['x', 'y', 'z'] + """ + fullargspec = getfullargspec(function) + arg_names = fullargspec.args + if arg_names and 'self' == arg_names[0]: + arg_names = fullargspec.args[1:] + + # parse default kwargs + default_kwargs = {} + default_values = fullargspec.defaults + if default_values: + assert len(default_values) <= len(arg_names) + default_kwarg_names = arg_names[-len(default_values) :] + default_kwargs = dict(zip(default_kwarg_names, default_values)) + + return arg_names, default_kwargs + + +def parse_varargs_name(function): + """ + Returns varargs name string of function. e.g: 'input' from `foo(x, *input)` + """ + fullargspec = getfullargspec(function) + varargs = fullargspec.varargs + return varargs + + +def type_name(v): + return type(v).__name__ + + +def make_hashable(x, error_msg=None): + """ + Makes input `x` hashable. + + For some unhashable objects, such as `dict/list/set/np.ndarray`,applying hash function by using their values. + """ + if isinstance(x, (tuple, list, set)): + return tuple(map(make_hashable, x)) + + try: + hash(x) + except TypeError: + if isinstance(x, np.ndarray): + # Note: `tostring()` will return the binary data from np.ndarray that + # means different value will lead to different hash code. + return hash(x.tostring()) + elif isinstance(x, dict): + return tuple(map(make_hashable, x.values())) + + error_msg = error_msg or "Requires a hashable object." + raise ValueError(error_msg + " But received type: %s" % type_name(x)) + + return x + + +def _is_api_in_module_helper(obj, module_prefix): + m = inspect.getmodule(obj) + return m is not None and m.__name__.startswith(module_prefix) + + +def is_api_in_module(node, module_prefix): + assert isinstance(node, gast.Call), "Input non-Call node for is_dygraph_api" + + # Python can have gast.Call as function, for example: covert_call(func)(x) + # We only check the most outside function + func_node = node.func + while isinstance(func_node, gast.Call): + func_node = func_node.func + + func_str = astor.to_source(gast.gast_to_ast(func_node)).strip() + try: + # TODO(liym27): + # Consider a better to import modules like: + # source_file = inspect.getfile(dyfunc) + # import_statements = ImportVisitor(source_file).transform() + # import_str = "".join(import_statements) + import paddle + import paddle.fluid as fluid + import paddle.fluid.dygraph as dygraph + import paddle.fluid.layers as layers + import paddle.jit.dy2static as _jst + + from paddle.fluid.dygraph import to_variable + from paddle import to_tensor + + return eval( + "_is_api_in_module_helper({}, '{}')".format(func_str, module_prefix) + ) + except Exception: + return False + + +def is_dygraph_api(node): + + # Note: A api in module dygraph_to_static is not a real dygraph api. + if is_api_in_module(node, DYGRAPH_TO_STATIC_MODULE_PREFIX): + return False + + # TODO(liym27): A better way to determine whether it is a dygraph api. + # Consider the decorator @dygraph_only + return is_api_in_module(node, DYGRAPH_MODULE_PREFIX) + + +def is_paddle_api(node): + return is_api_in_module(node, PADDLE_MODULE_PREFIX) + + +def is_paddle_func(func): + m = inspect.getmodule(func) + return m is not None and m.__name__.startswith(PADDLE_MODULE_PREFIX) + + +# Is numpy_api cannot reuse is_api_in_module because of numpy module problem +def is_numpy_api(node): + assert isinstance(node, gast.Call), "Input non-Call node for is_numpy_api" + func_str = astor.to_source(gast.gast_to_ast(node.func)) + try: + import numpy as np + + module_result = eval( + "_is_api_in_module_helper({}, '{}')".format(func_str, "numpy") + ) + # BUG: np.random.uniform doesn't have module and cannot be analyzed + # TODO: find a better way + if not module_result: + return func_str.startswith("numpy.") or func_str.startswith("np.") + except Exception: + return False + + +def is_control_flow_to_transform( + node, static_analysis_visitor=None, var_name_to_type=None +): + """ + Determines whether the node is a PaddlePaddle control flow statement which needs to + be transformed into a static graph control flow statement. + """ + assert isinstance( + node, gast.AST + ), "The type of input node must be gast.AST, but received %s." % type(node) + visitor = IsControlFlowVisitor( + node, static_analysis_visitor, node_var_type_map=var_name_to_type + ) + need_to_transform = visitor.transform() + return need_to_transform + + +def _delete_keywords_from(node): + assert isinstance(node, gast.Call) + func_src = astor.to_source(gast.gast_to_ast(node.func)) + import paddle.fluid as fluid + + full_args = eval("inspect.getargspec({})".format(func_src)) + full_args_name = full_args[0] + + node.keywords = [k for k in node.keywords if k.arg in full_args_name] + return + + +def to_static_api(dygraph_class): + if dygraph_class in dygraph_class_to_static_api: + return dygraph_class_to_static_api[dygraph_class] + else: + raise NotImplementedError( + "Paddle dygraph API {} cannot be converted " + "to static graph at present.".format(dygraph_class) + ) + + +def _add_keywords_to(node, dygraph_api_name): + assert isinstance(node, gast.Call) + if dygraph_api_name == "Linear": + for ast_keyword in node.keywords: + if ast_keyword.arg == "output_dim": + ast_keyword.arg = "size" + + node.keywords.append( + gast.keyword( + arg="num_flatten_dims", value=gast.Constant(value=-1, kind=None) + ) + ) + + if dygraph_api_name == "BilinearTensorProduct": + for ast_keyword in node.keywords: + if ast_keyword.arg == "output_dim": + ast_keyword.arg = "size" + + if dygraph_api_name == "PRelu": + for ast_keyword in node.keywords: + if ast_keyword.arg == "input": + ast_keyword.arg = "x" + return + + +def to_static_ast(node, class_node): + assert isinstance(node, gast.Call) + assert isinstance(class_node, gast.Call) + static_api = to_static_api(class_node.func.attr) + + node.func = gast.Attribute( + attr=static_api, + ctx=gast.Load(), + value=gast.Attribute( + attr='layers', + ctx=gast.Load(), + value=gast.Name( + ctx=gast.Load(), id='fluid', annotation=None, type_comment=None + ), + ), + ) + + update_args_of_func(node, class_node, 'forward') + + node.args.extend(class_node.args) + node.keywords.extend(class_node.keywords) + _add_keywords_to(node, class_node.func.attr) + _delete_keywords_from(node) + + gast.fix_missing_locations(node) + + return node + + +def update_args_of_func(node, dygraph_node, method_name): + assert isinstance(node, gast.Call) + if method_name not in ["__init__", "forward"]: + raise ValueError( + "The method name of class to update args should be '__init__' or 'forward'" + ) + + class_src = astor.to_source(gast.gast_to_ast(dygraph_node.func)) + import paddle.fluid as fluid + + if method_name == "__init__" or eval( + "issubclass({}, fluid.dygraph.Layer)".format(class_src) + ): + full_args = eval( + "inspect.getargspec({}.{})".format(class_src, method_name) + ) + full_args_name = [ + arg_name for arg_name in full_args[0] if arg_name != "self" + ] + else: + full_args_name = [] + added_keywords = [] + for idx, arg in enumerate(node.args): + added_keywords.append(gast.keyword(arg=full_args_name[idx], value=arg)) + + node.args = [] + node.keywords = added_keywords + node.keywords + + +def create_api_shape_node(tensor_shape_node): + assert isinstance( + tensor_shape_node, (gast.Name, gast.Attribute, gast.Subscript) + ) + + if isinstance(tensor_shape_node, gast.Name): + api_shape_node = gast.Call( + func=gast.parse('paddle.shape').body[0].value, + args=[tensor_shape_node], + keywords=[], + ) + return api_shape_node + + if isinstance(tensor_shape_node, gast.Attribute): + api_shape_node = gast.Call( + func=gast.parse('paddle.shape').body[0].value, + args=[tensor_shape_node.value], + keywords=[], + ) + return api_shape_node + + if isinstance(tensor_shape_node, gast.Subscript): + result_node = copy.deepcopy(tensor_shape_node) + result_node.value = create_api_shape_node(result_node.value) + return result_node + + +def get_constant_variable_node(name, value, shape=[1], dtype='int64'): + return gast.parse( + '%s = paddle.full(%s, "%s", %s)' % (name, str(shape), str(value), dtype) + ) + + +def get_attribute_full_name(node): + assert isinstance( + node, gast.Attribute + ), "Input non-Attribute node to get attribute full name" + return astor.to_source(gast.gast_to_ast(node)).strip() + + +def generate_name_node(name_ids, ctx=gast.Load(), gen_tuple_if_single=False): + """ + If name_ids is list or tuple or set with multiple strings, this function + generates gast.Tuple of gast.Name. + If the name_ids is single string or contains only 1 string, this function + returns gast.Name if gen_tuple_if_single==False else returns gast.Tuple + with only one gast.Name + + This function is used at several gast.Return statements. + """ + if isinstance(name_ids, six.string_types): + name_ids = [name_ids] + if not isinstance(name_ids, (list, tuple, set)): + raise TypeError( + 'name_ids must be list or tuple or set, but received %s' + % type(type(name_ids)) + ) + + def create_node_for_name(name): + if '.' not in name: + return gast.Name( + id=name, ctx=ctx, annotation=None, type_comment=None + ) + return gast.parse(name).body[0].value + + gast_names = [create_node_for_name(name_id) for name_id in name_ids] + if len(gast_names) == 1 and not gen_tuple_if_single: + name_node = gast_names[0] + else: + name_node = gast.Tuple(elts=gast_names, ctx=ctx) + return name_node + + +def create_funcDef_node(nodes, name, input_args, return_name_ids): + """ + Wrapper all statements of nodes into one ast.FunctionDef, which can be + called by ast.Call. + """ + nodes = copy.copy(nodes) + # add return statement + if return_name_ids: + nodes.append(gast.Return(value=generate_name_node(return_name_ids))) + else: + nodes.append(gast.Return(value=None)) + func_def_node = gast.FunctionDef( + name=name, + args=input_args, + body=nodes, + decorator_list=[], + returns=None, + type_comment=None, + ) + return func_def_node + + +def index_in_list(array_list, item): + try: + return array_list.index(item) + except ValueError: + # Item not in array_list + return -1 + + +def create_assign_node(name, node): + """ + Creates a `gast.Assign` node by given name_id as target and node as value. + """ + targets = generate_name_node(name, ctx=gast.Store()) + assign_node = gast.Assign(targets=[targets], value=node) + return targets, assign_node + + +def get_temp_dir(): + """ + Return @to_static temp directory. + """ + dir_name = "paddle/to_static_tmp/{pid}".format(pid=os.getpid()) + temp_dir = os.path.join(os.path.expanduser('~/.cache'), dir_name) + + is_windows = sys.platform.startswith('win') + if is_windows: + temp_dir = os.path.normpath(temp_dir) + + if not os.path.exists(temp_dir): + os.makedirs(temp_dir) + + return temp_dir + + +def ast_to_func(ast_root, dyfunc, delete_on_exit=True): + """ + Transform modified AST of decorated function into python callable object. + TODO: If only decorate one of inner function instead of decorating the main + function, the other inner functions are invisible for the decorated function. + """ + + def remove_if_exit(dir_path): + if os.path.exists(dir_path): + shutil.rmtree(dir_path) + + def func_prefix(func): + pre_fix = func.__name__ + if hasattr(func, '__self__'): + try: + pre_fix = func.__self__.__class__.__name__ + '_' + func.__name__ + except: + pass + return pre_fix + + source = ast_to_source_code(ast_root) + source = _inject_import_statements() + source + temp_dir = get_temp_dir() + f = tempfile.NamedTemporaryFile( + mode='w', + prefix=func_prefix(dyfunc), + suffix='.py', + delete=False, + dir=temp_dir, + encoding='utf-8', + ) + with f: + module_name = os.path.basename(f.name[:-3]) + f.write(source) + + global DEL_TEMP_DIR + if delete_on_exit and DEL_TEMP_DIR: + # Clear temporary files in TEMP_DIR while exitting Python process + atexit.register(remove_if_exit, dir_path=temp_dir) + DEL_TEMP_DIR = False + + func_name = dyfunc.__name__ + module = SourceFileLoader(module_name, f.name).load_module() + # The 'forward' or 'another_forward' of 'TranslatedLayer' cannot be obtained + # through 'func_name'. So set the special function name '__i_m_p_l__'. + if hasattr(module, '__i_m_p_l__'): + callable_func = getattr(module, '__i_m_p_l__') + callable_func.__name__ = func_name + elif hasattr(module, func_name): + callable_func = getattr(module, func_name) + else: + raise ValueError( + 'Function: %s doesn\'t exist in the Module transformed from AST.' + % func_name + ) + # After transform dygraph function into callable_func saved in tmp file, + # it lost the global variables from imported statements or defined in source file. + # Recovers the necessary variables by `__globals__`. + recover_globals_attribute(dyfunc, callable_func) + + return callable_func, f.name + + +def _inject_import_statements(): + import_statements = [ + "import paddle", + "from paddle import Tensor", + "import paddle.fluid as fluid", + "import paddle.jit.dy2static as _jst", + "from typing import *", + "import numpy as np", + "import warnings", + "warnings.filterwarnings('ignore', category=DeprecationWarning)", + ] + return '\n'.join(import_statements) + '\n' + + +def recover_globals_attribute(src_obj, dst_obj): + attr_name = '__globals__' + + src_globals = getattr(src_obj, attr_name, {}) + dst_globals = getattr(dst_obj, attr_name, {}) + + for k, v in six.iteritems(src_globals): + # ignore builtin attribute. + if not (k.startswith('__') and k.endswith('__')): + dst_globals[k] = v + + +def func_to_source_code(function, dedent=True): + """ + Transforms function into raw string of source code. + """ + if not (inspect.isfunction(function) or inspect.ismethod(function)): + raise TypeError( + "The type of 'function' should be a function or method, but received {}.".format( + type(function).__name__ + ) + ) + source_code_list, _ = inspect.getsourcelines(function) + # Replace comments with blank lines so that error messages are not misplaced + source_code_list = [ + line if not line.lstrip().startswith('#') else '\n' + for line in source_code_list + ] + source_code = ''.join(source_code_list) + if dedent: + source_code = textwrap.dedent(source_code) + + return source_code + + +def ast_to_source_code(ast_node): + """ + Transforms ast node into source code. + """ + if not isinstance(ast_node, (gast.AST, ast.AST)): + raise TypeError( + "Type of ast_root should be gast.AST or ast.AST, but received %s." + % type(ast_node) + ) + if isinstance(ast_node, gast.AST): + ast_node = gast.gast_to_ast(ast_node) + + # Do not wrap lines even if they are too long + def pretty_source(source): + return ''.join(source) + + source_code = astor.to_source(ast_node, pretty_source=pretty_source) + return source_code + + +def is_candidate_node(node): + """ + Nodes with specified type will be dependent on tensor. + """ + is_compare_node = isinstance( + node, + ( + gast.Compare, + gast.BoolOp, + gast.UnaryOp, + gast.For, + gast.If, + gast.While, + ), + ) + # TODO(Aurelius84): `.numpy()` may be an customized function, + # and should consider a more elegant way to solve this problem. + has_numpy_attr = ".numpy()" in ast_to_source_code(node) + return is_compare_node or has_numpy_attr + + +def compare_with_none(node): + """ + Whether the comparator of `gast.Compare` node is `None`. + """ + if isinstance(node, gast.Compare): + for child in [node.left, node.comparators]: + # node.comparators is a list. + if isinstance(child, list): + child = child[0] + if (isinstance(child, gast.Constant) and child.value is None) or ( + isinstance(child, gast.Name) and child.id == 'None' + ): + return True + return False + + +class IsControlFlowVisitor(gast.NodeVisitor): + """ + Judge whether the ast_node of control flow from Dygraph code dependent on paddle Tensor. + `ast_node` can be gast.If, gast.For, gast.While, gast.If.test(gast.Compare, gast.BoolOp, gast.UnaryOp). + + If returns True, + gast.If.test must meet at least one of the following requirements: + 1. involves at least one var whose type is Tensor. + 2. the Tensor var calls `.numpy()[]` interface or Tensor.shape is [1]. + 3. involves Tensor.shape[i] and the shape[i] is unknown in compile time. + gast.While must meet at least one of the requirements 1 to 5: + 4. has `break` statement. + 5. has `continue` statement. + gast.For must meet at least one of the requirements 4 to 8: + 6. calls `range` function in `for` statement and the argument of range is Tensor. + 7. calls `enumerate` function in `for` statement and the argument of enumerate is Tensor. + 8. the iterable varaible in `for` statement is Tensor. + TODO: Support non-range case + + The following examples should not be considered as control_flow_if: + 1. `if Tensor_var` or `if Tensor_var is None` + 2. if Tensor.shape[i] is determined with fixed value (not -1 or None) + + Note: pred in ConditionalBlock require variable, which means all vars should be Tensor + or transformed into Tensor, like fill_constant(shape=[1], dtype='int32', value=Tensor.shape[i]). + + TODO: 1. need to deal with `tensor.shape[i]` which need to eval the data of shape[i], + because reshape_op may be called before this statement. + """ + + def __init__( + self, ast_node, static_analysis_visitor=None, node_var_type_map=None + ): + assert isinstance( + ast_node, gast.AST + ), "Type of input node should be gast.AST, but received %s." % type( + ast_node + ) + self.ast_root = ast_node + if static_analysis_visitor is None: + from .static_analysis import StaticAnalysisVisitor + + static_analysis_visitor = StaticAnalysisVisitor(ast_node) + self.static_analysis_visitor = static_analysis_visitor + self.node_to_wrapper_map = ( + self.static_analysis_visitor.get_node_to_wrapper_map() + ) + self.node_var_type_map = node_var_type_map + + self.is_control_flow_num = 0 + self._compare_node_tenor_set = set() + + def transform(self): + node = self.ast_root + if isinstance(node, gast.If): + self._visit_If(node) + elif isinstance(node, gast.For): + self._visit_For(node) + elif isinstance(node, gast.While): + self._visit_While(node) + else: + self.visit(node) + return self.is_control_flow_num > 0 + + def _visit_If(self, node): + assert isinstance(node, gast.If) + self.visit(node.test) + return + + def _visit_For(self, node): + assert isinstance(node, gast.For) + if isinstance(node.iter, gast.Call): + # for in range(var[0]|var.numpy()[0]) or for in enumerate(var|var.numpy()) + if isinstance(node.iter.func, gast.Name): + if ( + node.iter.func.id == "range" + or node.iter.func.id == "enumerate" + ): + for arg in node.iter.args: + self.visit(arg) + else: + return + # for in var.numpy() + elif isinstance(node.iter.func, gast.Attribute): + if node.iter.func.attr == 'numpy': + self._visit_Call(node.iter) + else: + return + else: + return + elif isinstance(node.iter, gast.Name): + # for in var + self.visit(node.iter) + else: + return + + for child_node in gast.walk(node): + if isinstance(child_node, (gast.Continue, gast.Break)): + self._visit_break_continue(child_node) + return + + def _visit_While(self, node): + assert isinstance(node, gast.While) + test = node.test + self.generic_visit(test) + for child_node in gast.walk(node): + if isinstance(child_node, (gast.Continue, gast.Break)): + self._visit_break_continue(child_node) + return + + def _visit_break_continue(self, node): + assert isinstance(node, (gast.Break, gast.Continue)) + wrapper_node = self.node_to_wrapper_map.get(node) + if not wrapper_node: + # Transformed node is not in node_to_wrapper_map + return + + while wrapper_node.parent: + parent_node = wrapper_node.parent.node + if isinstance(parent_node, (gast.For, gast.While)): + if parent_node is self.ast_root: + self.is_control_flow_num += 1 + return + else: + return + + wrapper_node = wrapper_node.parent + + return + + def visit_BoolOp(self, node): + for i, child in enumerate(node.values): + self.visit(child) + return node + + def visit_Compare(self, node): + pre_control_flow_num = self.is_control_flow_num + if not compare_with_none(node): + self.generic_visit(node) + for child in gast.walk(node): + if isinstance(child, gast.Subscript): + self._visit_Subscript(child) + if self.is_control_flow_num > pre_control_flow_num: + self._compare_node_tenor_set.add(node) + return node + + def _visit_Subscript(self, node): + self.generic_visit(node) + if hasattr(node, 'value') and isinstance(node.value, gast.Call): + self._visit_Call(node.value) + return node + + def _visit_Call(self, node): + assert isinstance(node, gast.Call) + if isinstance(node.func, gast.Attribute): + attr_node = node.func + if attr_node.attr == 'numpy': + self.is_control_flow_num += 1 + + def visit_Call(self, node): + self._visit_Call(node) + if is_paddle_api(node): + self.is_control_flow_num += 1 + return node + + def visit_Name(self, node): + if self._is_node_with_tensor(node, node.id): + self.is_control_flow_num += 1 + return node + + def visit_Constant(self, node): + if self._is_node_with_tensor(node, node.value): + self.is_control_flow_num += 1 + return node + + def _is_node_with_tensor(self, node, name_id): + from paddle.fluid.dygraph.dygraph_to_static.static_analysis import ( + NodeVarType, + ) + + # Look up the node_var_type_map by name_id. + if self.node_var_type_map: + if name_id and isinstance(name_id, six.string_types): + var_type = self.node_var_type_map.get(name_id, None) + if var_type and var_type & NodeVarType.TENSOR_TYPES: + return True + # if not found, look up the node_to_wrapper_map by node. + wrapper_node = self.node_to_wrapper_map.get(node, None) + if wrapper_node is not None: + if wrapper_node.node_var_type & NodeVarType.TENSOR_TYPES: + return True + + return False + + def get_compare_nodes_with_tensor(self): + return self._compare_node_tenor_set + + +# NOTE: inspect.unwrap() exits in PY3 but not in PY2. +def unwrap(func): + """ + Returns the object wrapped by decorators. + """ + + def _is_wrapped(f): + return hasattr(f, '__wrapped__') + + unwrapped_f = func + while _is_wrapped(unwrapped_f): + unwrapped_f = unwrapped_f.__wrapped__ + + return unwrapped_f + + +def input_specs_compatible(src_input_specs, desired_input_specs): + """ + Returns True if the two input specs are compatible, otherwise False. + + args: + src_input_spec (list or tuple[InputSpec et.al]): list/tuple of + paddle.static.InputSpec or int/str et.al + desired_input_specs (list or tuple[InputSpec et.al]): list/tuple of + paddle.static.InputSpec or int/str et.al + """ + len_specs = len(src_input_specs) + if len_specs != len(desired_input_specs): + # NOTE(chenweihang): if the input_spec of jit.save is a subset of + # input_spec of to_static, also compatible + for spec in src_input_specs: + if spec not in desired_input_specs: + return False + else: + for (src_spec, desired_spec) in zip( + src_input_specs, desired_input_specs + ): + if isinstance(src_spec, paddle.static.InputSpec) or isinstance( + desired_spec, paddle.static.InputSpec + ): + if not _compatible_tensor_spec(src_spec, desired_spec): + return False + else: + if not _compatible_non_tensor_spec(src_spec, desired_spec): + return False + + return True + + +def _compatible_tensor_spec(src_spec, desired_spec): + """ + Check whether two tensor type spec is compatible. + """ + for spec in [src_spec, desired_spec]: + if not isinstance(spec, paddle.static.InputSpec): + return False + src_shape = src_spec.shape + other_shape = desired_spec.shape + len_shape = len(src_shape) + if len_shape != len(other_shape): + return False + for j in range(len_shape): + if src_shape[j] is None or src_shape[j] < 0: + continue + if other_shape[j] is None or other_shape[j] < 0: + continue + if src_shape[j] != other_shape[j]: + return False + + src_dtype = convert_dtype(src_spec.dtype) + other_dtype = convert_dtype(desired_spec.dtype) + if src_dtype != other_dtype: + return False + + return True + + +def _compatible_non_tensor_spec(src_spec, desired_spec): + """ + Check whether two non-tensor type spec is compatible. + """ + + def hash_value(spec): + try: + hash_val = make_hashable(spec) + except: + hash_val = None + return hash_val + + src_hash_val = hash_value(src_spec) + desired_hash_val = hash_value(desired_spec) + + if src_hash_val != desired_hash_val: + return False + else: + return True + + +def slice_is_num(slice_node): + # A slice_node.slice can be a: + # (1) ast.Index, which is a simple number such as [1], [-2] + # (2) ast.Slice, which is represented by bounds such as [2:-1] + # (3) ast.Tuple, which includes the above two cases such as [2:-1, 1] + # If slice node is case (1), return True, Otherwise, return False. + # + # NOTE: In (1) case, when gast>=0.4.0, gast.Index is not used, which is replaced + # other gast node such as gast.Constant, gast.Name, gast.UnaryOp and so on. + # Considering the compatibility of gast, here use ast note to check whether the + # node is a num. For more details, please visit https://github.com/serge-sans-paille/gast + + assert isinstance(slice_node, gast.Subscript) + slice_node_str = ast_to_source_code(slice_node).strip() + ast_node = ast.parse(slice_node_str).body[0].value + + if isinstance(ast_node.slice, (ast.Tuple, ast.Slice)): + return False + + if isinstance(ast_node.slice, ast.Index): + return True + + return False + + +class NameScope: + def __init__(self): + """ + A NameScope is a object which manager all the variable names. + only FunctionDef and Controlflow node will have a namescope property. + + type can be "function" and "controlflow" + + we don't analyze the read only variable because they don't affect the analysis. + """ + self.globals = set() + self.nonlocals = set() + self.args = set() + self.father = None # point to the nearest function name scope. + self.w_vars = set() # all qualified + normal names been stored + self.created = set() # useful for control flow compatibility + # only valid in control_flow nodes + # may be remove later. + self.push_pop_vars = set() # we call push and pop in the vars + + def set_father(self, father): + self.father = father + + def existed_vars(self): + """vars existing in current scope. + they must not contain qualified names. + """ + local_vars = self.w_vars - self.globals - self.nonlocals - self.args + return set(filter(lambda x: '.' not in x, local_vars)) + + def created_vars(self): + return self.created + + def modified_vars(self): + # may be globals / non-locals / args / qualified names and created_vars + return self.w_vars + + def variadic_length_vars(self): + """ + At present, we do not support global append, such as + + import numpy as np + a = [] + def func(): + a.append() # global names `a`, we will raise a warning. + p.append(a, 1) # global names `np`, we will raise a warning. + """ + non_global_push_pop_names = [] + for var in self.push_pop_vars: + if self._is_simple_name(var) and self.is_global_var(var): + warnings.warn( + f"Find variable `{var}` defined in global scope" + f" and call `{var}.append() or {var}.pop()`" + f", which will be ignored and never be transfered into" + f" tensor array." + ) + else: + non_global_push_pop_names.append(var) + return set(non_global_push_pop_names) + + def control_flow_vars(self): + valid_names = self.w_vars + tmp = (self.father.global_vars & valid_names,) + return {"global": tmp, "nonlocal": self.w_vars - tmp} + + def _is_simple_name(self, name): + if '.' in name or '[' in name: + return False + return True + + def is_global_var(self, name): + """ + Return whether the name is a var created in global scope. + Search from bottom to top. If it is not created or modified, + it means global vars; otherwise, it means local vars. + Only valid after FunctionNameLivenessAnalysis visitor. + """ + assert self._is_simple_name( + name + ), "is_global_var accept a simple name, but get `{name}`." + ancestor = self + while ancestor is not None: + if name in ancestor.globals: + return True + if name in (ancestor.nonlocals | ancestor.w_vars): + return False + ancestor = ancestor.father + return True + + def is_local_var(self, name): + return not self.is_global_var(name) + + def merge_from(self, name_scope): + self.globals |= name_scope.globals + self.nonlocals |= name_scope.nonlocals + self.args |= name_scope.args + self.w_vars |= name_scope.w_vars + self.push_pop_vars |= name_scope.push_pop_vars + + +class FunctionNameLivenessAnalysis(gast.NodeVisitor): + """analyze the liveness of a function. + + every variables stored in this scope will be collected, + in addition with global/nonlocal information and + push_pop information. + + 1. global variable is stored in node.var_globals. + 2. nonlocal variable is stored in node.var_nonlocals. + 3. arguments is stored in node.var_args. + 4. if a variable's push and pop attribute is called, + it will be collected in push_pop_vars. They are + used for transformation to tensor_array. + NOTE: push_pop_vars **may not** in w_vars. + a.push(0) don't modify the variable a, but the content + of a. + + For example: + + def func(*args, **kargs): + a = 12 + global i,j + nonlocal x,y + print(a) + i = k + b = [] + c = [1,2,3] + for m in range(10): + q = 12 + b.push(1) + c.pop() + + After this visitor we have: + # node is the FunctionDef node with name: "func" + node.pd_scope = NameScope( + globals = ['i', 'j'], + nonlocals = ['x', 'y'], + args = ['args', 'kargs'], + wr_vars = ['a', 'i', 'q', 'm', 'c', 'b'] + push_pop_vars = ['b', 'c'] + ) + """ + + def __init__(self, root_node): + self.scope_node_stack = [] # controlflow, functiondef node + self.visit(root_node) + + def _reset_name_scope(self, node): + # always reset the node as empty namescope. + setattr(node, "pd_scope", NameScope()) + + def _get_name_scope(self, node): + if not hasattr(node, "pd_scope"): + setattr(node, "pd_scope", NameScope()) + return node.pd_scope + + def _current_name_scope(self): + return self._get_name_scope(self.scope_node_stack[-1]) + + def _father_name_scope(self): + if len(self.scope_node_stack) == 1: + return None + return self._get_name_scope(self.scope_node_stack[-2]) + + def _nearest_function_scope(self): + if len(self.scope_node_stack) == 1: + return None + for node in self.scope_node_stack[-2::-1]: + if isinstance(node, gast.FunctionDef): + return self._get_name_scope(node) + + def visit_ListComp(self, node): + """[ i for i in range(10) ] + In this case, `i` will not created in FunctionScope. + We don't collect `i` by not calling generic_visit. + """ + pass + + def visit_DictComp(self, node): + """the same as ListComp.""" + pass + + def visit_Name(self, node): + self.generic_visit(node) + write_context = (gast.Store, gast.AugStore, gast.Del) + if isinstance(node.ctx, write_context): + self._current_name_scope().w_vars.add(node.id) + + def visit_FunctionDef(self, node): + def pre_func(): + self._current_name_scope().args |= set( + self._get_argument_names(node) + ) + + def post_func(): + """NOTE: why we need merge w_vars and push_pop_vars here ? + because we do ifelse_transformer after loop_transformer. Loops will changed into functioons. but we know this function will be called in if. so we add w_vars to father function scope. + """ + from paddle.fluid.dygraph.dygraph_to_static.loop_transformer import ( + WHILE_CONDITION_PREFIX, + WHILE_BODY_PREFIX, + FOR_CONDITION_PREFIX, + FOR_BODY_PREFIX, + ) + from paddle.fluid.dygraph.dygraph_to_static.ifelse_transformer import ( + TRUE_FUNC_PREFIX, + FALSE_FUNC_PREFIX, + ) + + control_flow_function_def = [ + WHILE_BODY_PREFIX, + WHILE_BODY_PREFIX, + FOR_CONDITION_PREFIX, + FOR_BODY_PREFIX, + TRUE_FUNC_PREFIX, + FALSE_FUNC_PREFIX, + ] + + def is_control_flow_def_node(): + for prefix in control_flow_function_def: + if node.name.startswith(prefix): + return True + return False + + if self._father_name_scope() and is_control_flow_def_node(): + self._father_name_scope().w_vars |= ( + self._current_name_scope().w_vars + ) + self._father_name_scope().push_pop_vars |= ( + self._current_name_scope().push_pop_vars + ) + + self._visit_scope_node(node, pre_func, post_func) + + def _visit_scope_node(self, node, pre_func, post_func): + """scope node main visit logic. + pre_func and post_func is callbacks + """ + self._reset_name_scope(node) + self.scope_node_stack.append(node) + self._current_name_scope().set_father(self._nearest_function_scope()) + if pre_func: + pre_func() + self.generic_visit(node) + if post_func: + post_func() + self.scope_node_stack.pop() + + def _visit_controlflow_node(self, node): + def post_func(): + self._father_name_scope().merge_from(self._current_name_scope()) + self._nearest_function_scope().merge_from( + self._current_name_scope() + ) + self._current_name_scope().created = ( + self._nearest_function_scope().existed_vars() + - node.before_created + ) + # gather created vars into father and used in CreateUndefinedVarTransform + self._nearest_function_scope().created |= ( + self._current_name_scope().created + ) + + def pre_func(): + setattr( + node, + "before_created", + self._nearest_function_scope().existed_vars(), + ) + + self._visit_scope_node(node, pre_func, post_func) + + def visit_For(self, node): + self._visit_controlflow_node(node) + + def visit_While(self, node): + self._visit_controlflow_node(node) + + def visit_If(self, node): + self._visit_controlflow_node(node) + + def visit_Global(self, node): + self._current_name_scope().globals |= set(node.names) + + def visit_Nonlocal(self, node): + self._current_name_scope().nonlocals |= set(node.names) + + def visit_Attribute(self, node): + self.generic_visit(node) + write_context = (gast.Store, gast.AugStore, gast.Del) + if isinstance(node.ctx, write_context): + name = ast_to_source_code(node).strip() + self._current_name_scope().w_vars.add(name) + + def visit_Call(self, node): + self.generic_visit(node) + if not isinstance(node.func, gast.Attribute): + return + variadic_length_method = ['append', 'pop'] + if node.func.attr not in variadic_length_method: + return + # we don't treat push and pop as a write operator. such as a[i]=10 is not modify a. + name = ast_to_source_code(node.func.value).strip() + self._current_name_scope().push_pop_vars.add(name) + + def _get_argument_names(self, node): + """get all arguments name in the functiondef node. + this node is local to the function and shouldn't + be created. + """ + assert isinstance( + node, gast.FunctionDef + ), "Input node is not function define node" + names = [a for a in node.args.args] + names.append(node.args.vararg) + names.append(node.args.kwarg) + names = [i.id for i in names if i is not None] + return names + + +def create_get_args_node(names): + """ + Create get_args function as follows: + + def get_args_0(): + nonlocal x, y + return x, y + """ + + def empty_node(): + func_def = """ + def {func_name}(): + return + """.format( + func_name=unique_name.generate(GET_ARGS_FUNC_PREFIX) + ) + return gast.parse(textwrap.dedent(func_def)).body[0] + + assert isinstance(names, (list, tuple)) + node = create_nonlocal_stmt_nodes(names) + if not names: + return empty_node() + if node == []: + nonlocal_vars = "\n" + else: + nonlocal_vars = ast_to_source_code(node[0]) + template = """ + def {func_name}(): + {nonlocal_vars} + return {vars}, + """ + func_def = template.format( + func_name=unique_name.generate(GET_ARGS_FUNC_PREFIX), + nonlocal_vars=nonlocal_vars, + vars=",".join(names), + ) + return gast.parse(textwrap.dedent(func_def)).body[0] + + +def create_set_args_node(names): + """ + Create set_args function as follows: + + def set_args_0(__args): + nonlocal x, y + x, y = __args + """ + + def empty_node(): + func_def = """ + def {func_name}({args}): + pass + """.format( + func_name=unique_name.generate(SET_ARGS_FUNC_PREFIX), args=ARGS_NAME + ) + return gast.parse(textwrap.dedent(func_def)).body[0] + + assert isinstance(names, (list, tuple)) + node = create_nonlocal_stmt_nodes(names) + if not names: + return empty_node() + if node == []: + nonlocal_vars = "\n" + else: + nonlocal_vars = ast_to_source_code(node[0]) + template = """ + def {func_name}({args}): + {nonlocal_vars} + {vars}, = {args} + """ + func_def = template.format( + func_name=unique_name.generate(SET_ARGS_FUNC_PREFIX), + args=ARGS_NAME, + nonlocal_vars=nonlocal_vars, + vars=",".join(names), + ) + return gast.parse(textwrap.dedent(func_def)).body[0] + + +def create_nonlocal_stmt_nodes(names): + assert isinstance(names, (list, tuple)) + + mapped = list(filter(lambda n: '.' not in n, names)) + mapped = list(filter(lambda n: '[' not in n, mapped)) + names = sorted( + mapped, key=mapped.index + ) # to keep the order, we can't use set() to unique + if not names: + return [] + func_code = "nonlocal {}".format(','.join(names)) + return [gast.parse(func_code).body[0]] + + +class GetterSetterHelper: + """we have two classes of names in setter and getter function: + w_vars(loop_vars) + push_pop_vars + To simplify the setter logic in convert_while and convert_cond, + we extract the helper class here. + """ + + def __init__(self, getter_func, setter_func, *name_lists): + name_lists = map(lambda x: [] if x is None else x, name_lists) + name_sets = map(lambda x: set(x), name_lists) + self._union = list(reduce(lambda x, y: x | y, name_sets, set())) + self._union.sort() + self.getter = getter_func + self.setter = setter_func + self.name2id = {name: idx for idx, name in enumerate(self._union)} + + def union(self): + return self._union + + def get(self, names): + if names is None: + names = [] + vars = self.getter() + if vars is None: + return tuple() + for n in names: + assert ( + n in self.name2id + ), "the name `{}` not in name union set`{}`.".format( + n, self.name2id.keys() + ) + return tuple(map(lambda n: vars[self.name2id[n]], names)) + + def set(self, names, values): + if names is None: + names = [] + if values is None: + values = [] + vars = self.getter() + if vars is None: + return + for n in names: + assert ( + n in self.name2id + ), "the name `{}` not in name union set`{}`.".format( + n, self.name2id.keys() + ) + vars = list(vars) + indices = list(map(lambda n: self.name2id[n], names)) + for i, v in zip(indices, values): + vars[i] = v + self.setter(vars) + + +def create_name_str(name_ids): + """ + Return "('x', 'y')" for [x, y] + """ + if not name_ids: + return 'None' + + names_str = ["'%s'" % (name.replace("'", "\\'")) for name in name_ids] + return "(%s, )" % ','.join(names_str) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/variable_trans_func.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/variable_trans_func.py new file mode 100644 index 0000000000000000000000000000000000000000..fec231d54852462cf3ef57e5bb7079177cc63411 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/dygraph_to_static/variable_trans_func.py @@ -0,0 +1,92 @@ +# 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. + +from __future__ import print_function + +import six +import paddle +import textwrap +from paddle.utils import gast +from paddle.fluid import unique_name +from paddle.fluid.framework import Variable +from paddle.fluid.dygraph.dygraph_to_static.utils import UndefinedVar, create_undefined_variable +from paddle.fluid.layers.utils import map_structure, is_sequence + +__all__ = [ + 'create_bool_as_type', + 'create_fill_constant_node', + 'to_static_variable', + 'create_undefined_var', +] + + +def create_undefined_var(name): + func_code = "{} = _jst.UndefinedVar('{}')".format(name, name) + return gast.parse(func_code).body[0] + + +def create_fill_constant_node(name, value=0): + func_code = "{} = paddle.full(shape=[1], ".format(name) + if isinstance(value, bool): + func_code += "dtype='bool', fill_value={}, name='{}')".format( + value, name) + return gast.parse(func_code).body[0] + if isinstance(value, float): + func_code += "dtype='float64', fill_value={}, name='{}')".format( + value, name) + return gast.parse(func_code).body[0] + + if isinstance(value, int): + func_code += "dtype='int64', fill_value={}, name='{}')".format( + value, name) + return gast.parse(func_code).body[0] + + +def to_static_variable(x): + ''' + Translate a Python Tensor to PaddlePaddle static graph Tensor + ''' + if isinstance(x, bool): + return paddle.full(shape=[1], dtype='bool', fill_value=x) + if isinstance(x, float): + return paddle.full(shape=[1], dtype='float64', fill_value=x) + if isinstance(x, six.integer_types): + return paddle.full(shape=[1], dtype='int64', fill_value=x) + if isinstance(x, UndefinedVar) or x is None: + """ + for early return case, we need a variable to represent None, current we use data_layer_not_check. + """ + return create_undefined_variable() + if is_sequence(x): + return map_structure(to_static_variable, x) + return x + + +def create_bool_as_type(x, value=True): + ''' + Create a bool variable, which type is the same as x. + ''' + if isinstance(x, Variable): + return paddle.full(shape=[1], fill_value=value, dtype="bool") + else: + return value + + +def create_bool_node(name, value): + ''' + Create a assign stmt for name = value . + ''' + assert isinstance(value, bool) + node = "{} = {}".format(name, value) + return gast.parse(node).body[0] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/inplace_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/inplace_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..968a957b660d3510e0abafdbf39fd6ffe5c4d364 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/inplace_utils.py @@ -0,0 +1,40 @@ +# Copyright (c) 2021 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. + +from ..wrapped_decorator import wrap_decorator +from ..framework import _non_static_mode +import warnings +import paddle +from paddle import _C_ops, _legacy_C_ops + + +# NOTE(pangyoki): The Inplace APIs with underline(`_`) is only valid for the method of calling `_C_ops` +# in dygraph mode. If static mode is used, the inplace mechanism will not be used, and the static method +# of the original API will be called. +def _inplace_apis_in_dygraph_only_(func): + + def __impl__(*args, **kwargs): + if not _non_static_mode(): + origin_api_name = func.__name__[:-1] + warnings.warn( + "In static mode, {}() is the same as {}() and does not perform inplace operation." + .format(func.__name__, origin_api_name)) + origin_func = "{}.{}".format(func.__module__, origin_api_name) + return eval(origin_func)(*args, **kwargs) + return func(*args, **kwargs) + + return __impl__ + + +inplace_apis_in_dygraph_only = wrap_decorator(_inplace_apis_in_dygraph_only_) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/io.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/io.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6f095df99964e1c4a61b6480b306c738705b4a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/io.py @@ -0,0 +1,1680 @@ +# 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. + +from __future__ import print_function + +import os +import six +import pickle +import numpy as np + +import paddle +from paddle import compat as cpt +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid import backward +from paddle.fluid import unique_name +from paddle.fluid.dygraph import layers +from paddle.fluid.layers import nn +from paddle.fluid.layers.utils import _hash_with_id +from paddle.fluid.dygraph.base import switch_to_static_graph +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.executor import ( + _is_enable_standalone_executor, + _is_dy2st_enable_standalone_executor, +) +from paddle.fluid.dygraph.dygraph_to_static.partial_program import ( + add_build_strategy_for, + LazyInitialized, +) +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['TranslatedLayer'] + +INFER_MODEL_SUFFIX = ".pdmodel" +INFER_PARAMS_SUFFIX = ".pdiparams" +INFER_PARAMS_INFO_SUFFIX = ".pdiparams.info" +INFER_PROPERTY_SUFFIX = '.meta' + +LOADED_VAR_SUFFIX = "load" +PARAMETER_NAME_PREFIX = "param" +BUFFER_NAME_PREFIX = "buffer" + + +def _load_program_desc(model_file_path): + # 1. parse program desc + with open(model_file_path, "rb") as f: + program_desc_str = f.read() + + program_desc = core.ProgramDesc(program_desc_str) + if not core._is_program_version_supported(program_desc._version()): + raise ValueError( + "Unsupported program version: %d\n" % program_desc._version() + ) + + return program_desc + + +def _is_persistable(var_desc): + if ( + var_desc.type() == core.VarDesc.VarType.FEED_MINIBATCH + or var_desc.type() == core.VarDesc.VarType.FETCH_LIST + or var_desc.type() == core.VarDesc.VarType.READER + or var_desc.type() == core.VarDesc.VarType.RAW + ): + return False + return var_desc.persistable() + + +def _is_parameter(persistable_var_desc, program_desc): + # 1. firstly, param should be input of op + input_ops = [] # op can be repeated + for block_idx in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(block_idx) + for op_idx in six.moves.range(block.op_size()): + op = block.op(op_idx) + # NOTE: parameter is the input of a certain op + if persistable_var_desc.name() in op.input_arg_names(): + input_ops.append(op) + # 2. secondly, param should not be output of op or be same op's output + for block_idx in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(block_idx) + for op_idx in six.moves.range(block.op_size()): + op = block.op(op_idx) + if persistable_var_desc.name() in op.output_arg_names(): + # such as batch_norm_op + if op in input_ops: + continue + else: + return False + return True + + +def _get_persistable_vars(program_desc): + persistable_vars = [] + for i in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(i) + persistable_vars.extend(list(filter(_is_persistable, block.all_vars()))) + return persistable_vars + + +def _get_persistable_var_names(program_desc): + """ + Get all persistable variable names in ProgramDesc. + """ + var_names = [] + persistable_vars = _get_persistable_vars(program_desc) + for var in persistable_vars: + var_names.append(var.name()) + return var_names + + +def _get_all_var_names(program_desc): + all_var_names = set() + for i in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(i) + for var in block.all_vars(): + all_var_names.add(var.name()) + return all_var_names + + +@switch_to_static_graph +def _append_loaded_suffix(name): + """ + Append loaded suffix to the given variable name + e.g. x ==> x.load_0, x.load_0 ==> x.load_0.load_0 + """ + suffix = LOADED_VAR_SUFFIX + name = cpt.to_text(name) + new_name = unique_name.generate_with_ignorable_key('.'.join((name, suffix))) + return new_name + + +@switch_to_static_graph +def _generate_unique_var_name(prefix): + return unique_name.generate_with_ignorable_key(prefix) + + +def _append_loaded_suffix_to_var(program_desc): + suffix_varname_dict = dict() + persistable_vars = _get_persistable_vars(program_desc) + for var_desc in persistable_vars: + old_name = var_desc.name() + new_name = _append_loaded_suffix(var_desc.name()) + suffix_varname_dict[new_name] = old_name + var_desc.set_name(new_name) + for block_idx in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(block_idx) + block._rename_var(cpt.to_bytes(old_name), cpt.to_bytes(new_name)) + for op_idx in six.moves.range(block.op_size()): + op = block.op(op_idx) + op._rename_input(old_name, new_name) + op._rename_output(old_name, new_name) + return suffix_varname_dict + + +@switch_to_static_graph +def _generate_unique_var_name_sync_with_main_program(prefix): + return unique_name.generate(prefix) + + +def _get_loaded_var_new_old(program_desc, all_new_old_dict_all): + new_old_dict = dict() + persistable_vars = _get_persistable_vars(program_desc) + for var_desc in persistable_vars: + name_new = var_desc.name() + new_old_dict[name_new] = all_new_old_dict_all[name_new] + return new_old_dict + + +def _rename_var_program_desc(program_desc, include=None, exclude=None): + """ + Change the name of the loaded variables.Use 'unique_name.generate' to avoid duplication. + It is used when loading multiple program during inference. + + e.g. linear_0.tmp_3 ==> linear_0.tmp_1, x ==> x_0. For double grad, x@GRAD ==> x_0@GRAD + If 'include' is not `None`,variables in include and the corresponding + double grad variables (if exist) are renamed. + If 'exclude' is not `None`,variables that are in exclude and the + corresponding double grad variables (if exist) are not renamed. + + Args: + program_desc(ProgramDesc):the variables in it will be modified. + include(List):list of names of variables. + exclude(List):list of names of variables. + + Returns: + tuple of (dict_rename_var_new_old, dict_rename_var_old_new) + dict_rename_var_new_old is a dict mapping from new name to old name + dict_rename_var_old_new is a dict mapping from old name to new name + """ + dict_rename_var_old_new = dict() + dict_rename_var_new_old = dict() + old_names = [] + # Store all old names + for b_idx in six.moves.range(program_desc.num_blocks()): + cur_block = program_desc.block(b_idx) + for var in cur_block.all_vars(): + old_names.append(var.name()) + + # Create dict_rename_var_new_old and dict_rename_var_old_new for non double + # grad variables + has_double_grad = False + for b_idx in six.moves.range(program_desc.num_blocks()): + cur_block = program_desc.block(b_idx) + for var_idx, var in enumerate(cur_block.all_vars()): + name_old = var.name() + is_double_grad_var = "@GRAD" in name_old + has_double_grad = has_double_grad or is_double_grad_var + should_rename = ( + (include is None or name_old in include) + and (exclude is None or name_old not in exclude) + and not is_double_grad_var + ) + if should_rename: + temp_name = name_old.split('_') + if len(temp_name) > 1 and temp_name[-1].isnumeric(): + temp_name = "_".join(temp_name[:-1]) + else: + temp_name = name_old + while True: + name_new = _generate_unique_var_name_sync_with_main_program( + temp_name + ) + if ( + name_new + not in old_names[:var_idx] + old_names[var_idx + 1 :] + ): + break + else: + name_new = name_old + if name_old != name_new: + cur_block._rename_var( + cpt.to_bytes(name_old), cpt.to_bytes(name_new) + ) + if not is_double_grad_var: + dict_rename_var_old_new[name_old] = name_new + dict_rename_var_new_old[name_new] = name_old + + # Handle double grad names + if has_double_grad: + double_grad_rename_dict = {} + for name_old in dict_rename_var_old_new: + for b_idx in six.moves.range(program_desc.num_blocks()): + cur_block = program_desc.block(b_idx) + for var_idx, var in enumerate(cur_block.all_vars()): + var_name = var.name() + if "@GRAD" in var_name and name_old in var_name: + new_var_name = var_name.replace( + name_old, dict_rename_var_old_new[name_old] + ) + double_grad_rename_dict[var_name] = new_var_name + for var_name in double_grad_rename_dict: + dict_rename_var_old_new[var_name] = double_grad_rename_dict[ + var_name + ] + dict_rename_var_new_old[ + double_grad_rename_dict[var_name] + ] = var_name + + # Rename on program desc + for b_idx in six.moves.range(program_desc.num_blocks()): + cur_block = program_desc.block(b_idx) + for op_idx in six.moves.range(cur_block.op_size()): + op = cur_block.op(op_idx) + for input_arg_name in op.input_arg_names(): + if input_arg_name in dict_rename_var_old_new: + if ( + input_arg_name + != dict_rename_var_old_new[input_arg_name] + ): + op._rename_input( + input_arg_name, + dict_rename_var_old_new[input_arg_name], + ) + if cur_block.has_var(cpt.to_bytes(input_arg_name)): + cur_block._rename_var( + cpt.to_bytes(input_arg_name), + cpt.to_bytes( + dict_rename_var_old_new[input_arg_name] + ), + ) + for output_arg_name in op.output_arg_names(): + if output_arg_name in dict_rename_var_old_new: + if ( + output_arg_name + != dict_rename_var_old_new[output_arg_name] + ): + op._rename_output( + output_arg_name, + dict_rename_var_old_new[output_arg_name], + ) + if cur_block.has_var(cpt.to_bytes(output_arg_name)): + cur_block._rename_var( + cpt.to_bytes(output_arg_name), + cpt.to_bytes( + dict_rename_var_old_new[output_arg_name] + ), + ) + program_desc.flush() + return dict_rename_var_new_old, dict_rename_var_old_new + + +@switch_to_static_graph +def _build_program_by_desc(program_desc): + prog = framework.Program() + prog.desc = program_desc + prog.blocks = [ + framework.Block(prog, i) + for i in six.moves.range(prog.desc.num_blocks()) + ] + prog._sync_with_cpp() + return prog + + +def _change_is_test_status(program_desc, is_test): + # change all `is_test` attributes + for i in six.moves.range(program_desc.num_blocks()): + block = program_desc.block(i) + for j in six.moves.range(block.op_size()): + op = block.op(j) + if op.has_attr('is_test'): + op._set_attr('is_test', is_test) + + +class _ProgramHolder(object): + """ + Holds the execution information of a Program. + + _ProgramHolder is the execution unit of TranslatedLayer, + if TranslatedLayer contains multiple _ProgramHolder, + it can execute multiple methods + + _ProgramHolder is an internal concept. + """ + + def __init__(self, program_desc): + super(_ProgramHolder, self).__init__() + + # input, output, persistable, double_grads var info + self._input_descs = [] + self._output_descs = [] + self._double_grad_descs = [] + self._persistable_names = [] + + # execution scope + self._inner_scope = core.Scope() + + # append suffix var name dict + self._suffix_varname_dict = None + # forward program + self._infer_program_desc = self._preprocess(program_desc) + # forward + backward program + self._train_program_desc = self._append_backward_desc( + self._infer_program_desc + ) + + # forward: + @switch_to_static_graph + def _create_forward_train_program(self): + whole_program = _build_program_by_desc(self._train_program_desc) + end_op_index = self._infer_program_desc.block(0).op_size() + if end_op_index > 0: + return add_build_strategy_for(whole_program, 0, end_op_index) + else: + return whole_program + + @LazyInitialized + def _forward_program_desc(self): + return self._create_forward_train_program().desc + + # backward + @switch_to_static_graph + def _create_backward_train_program(self): + whole_program = _build_program_by_desc(self._train_program_desc) + start_op_index = self._infer_program_desc.block(0).op_size() + 2 * len( + self._output_descs + ) + end_op_index = whole_program.desc.block(0).op_size() + if start_op_index < end_op_index: + return add_build_strategy_for( + whole_program, start_op_index, end_op_index + ) + else: + return paddle.static.Program() + + @LazyInitialized + def _backward_program_desc(self): + return self._create_backward_train_program().desc + + @property + def infer_program(self): + return self._infer_program_desc + + @property + def train_program(self): + return self._train_program_desc + + @property + def forward_program(self): + return self._forward_program_desc + + @property + def backward_program(self): + return self._backward_program_desc + + @property + def input_descs(self): + return self._input_descs + + @property + def output_descs(self): + return self._output_descs + + @property + def persistable_names(self): + return self._persistable_names + + @property + def double_grad_descs(self): + return self._double_grad_descs + + @property + def scope(self): + return self._inner_scope + + def _preprocess(self, program_desc): + # rename persistable variables of 'program_desc' + list_persistable_var = _get_persistable_var_names(program_desc) + rename_new_old_dict, _ = _rename_var_program_desc( + program_desc, list_persistable_var + ) + # 1. Prune original program + # remove feed, fetch and scale-1 op, remove op_callstack attr + ops_to_remove = [] + root_block = program_desc.block(0) + for i in six.moves.range(root_block.op_size()): + op = root_block.op(i) + if op.type() == 'feed': + ops_to_remove.append(i) + feed_var_name = cpt.to_bytes(op.input('X')[0]) + root_block._remove_var(feed_var_name) + self._input_descs.append( + root_block.find_var(cpt.to_bytes(op.output('Out')[0])) + ) + elif op.type() == 'scale' and op.output('Out')[0].startswith( + 'save_infer_model/scale_' + ): + ops_to_remove.append(i) + out_var_name = cpt.to_bytes(op.output('Out')[0]) + root_block._remove_var(out_var_name) + self._output_descs.append( + root_block.find_var(cpt.to_bytes(op.input('X')[0])) + ) + elif op.type() == 'fetch': + ops_to_remove.append(i) + fetch_var_name = cpt.to_bytes(op.output('Out')[0]) + root_block._remove_var(fetch_var_name) + # NOTE: some old pre-train models have no extra scale_op + if not op.input('X')[0].startswith('save_infer_model/scale_'): + self._output_descs.append( + root_block.find_var(cpt.to_bytes(op.input('X')[0])) + ) + else: + if op.has_attr("op_callstack"): + op.remove_attr("op_callstack") + + for op_idx in reversed(ops_to_remove): + root_block._remove_op(op_idx, op_idx + 1) + + for i in range(program_desc.num_blocks()): + block_desc = program_desc.block(i) + for var_desc in block_desc.all_vars(): + if "@GRAD" in var_desc.name(): + self._double_grad_descs.append(var_desc) + + # 2. Input processing, reverse feed vars + self._input_descs.reverse() + + # 3. Output processing, add scale for outputs + tmp_program = _build_program_by_desc(program_desc) + # NOTE: [why need append scale for outputs] + # When dealing with some more complex pre-training models, there + # will be situations where the pre-training model has multiple + # fetch outputs. In the scenario of multiple fetch outputs, + # there is a special case where multiple outputs of the model + # may be on the same branch. According to the user's subsequent + # use, multiple outputs may be associated with multiple branches. + # These subsequent operations are added in TranslatedLayer is + # agnostic during initialization, which results in subsequent + # gradient accumulation operations that are required on the + # output node in the middle of the branch will not be performed, + # resulting in error, details see pull request: + # [https://github.com/PaddlePaddle/Paddle/pull/24627] + self._append_scale_to_output(tmp_program) + + # 4. Persistable vars processing + # - append loaded suffix to persistable vars + # NOTE: [why need to append suffix to persistable vars] + # Dygraph and static graph mode use the same naming mechanism. + # If users want to load the model fine-tune, it is possible + # to add the existing Layer in the loaded model to enhance + # the network. For example, the original saved model has linear, + # and later after loading, a new linear is added. At this time, + # there will be a problem of duplicate names, so here is unified + # to add the LOADED suffix to the parameters of the model loaded + self._suffix_varname_dict = _get_loaded_var_new_old( + program_desc, rename_new_old_dict + ) + + # - get persistable var + self._persistable_names = _get_persistable_var_names(program_desc) + + return program_desc + + @switch_to_static_graph + def _append_scale_to_output(self, program): + # 1. append scale & save var + scale_output_vars = [] + with framework.program_guard(program): + for i, out in enumerate(self._output_descs): + var = program.global_block().var(out.name()) + var = nn.scale( + var, 1.0, name="translated_layer/scale_{}".format(i) + ) + scale_output_vars.append(var) + # 2. update output names & descs + for i, var in enumerate(scale_output_vars): + self._output_descs[i] = var.desc + + @switch_to_static_graph + def _get_train_forward_program(self, infer_program_desc): + program_desc_copy = core.ProgramDesc(infer_program_desc) + + # 1. set all `is_test` attributes to False + _change_is_test_status(program_desc_copy, False) + + # 2. prepare program and related var + # NOTE: To reuse backward interfaces, build Program firstly. + # Originally, there is no need to build a program, but need to almost + # rewrite a series of methods for append_backward for program_desc. + # Therefore, in order to reuse the method of backward.py, build the program here. + program = _build_program_by_desc(program_desc_copy) + # 3. Add the outputs which is only used for training and not saved in + # inference program. + for block_idx in six.moves.range(program.num_blocks): + block = program.block(block_idx) + for op in block.ops: + if op.type == "batch_norm": + if ( + "ReserveSpace" not in op.output_names + or len(op.output("ReserveSpace")) == 0 + ): + reserve_space = block.create_var( + name=unique_name.generate_with_ignorable_key( + ".".join(["reserve_space", 'tmp']) + ), + dtype=block.var(op.input("X")[0]).dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True, + ) + op.desc.set_output("ReserveSpace", [reserve_space.name]) + return program + + @switch_to_static_graph + def _append_backward_desc(self, infer_program_desc): + program = self._get_train_forward_program(infer_program_desc) + + targets = [] + for out in self._output_descs: + targets.append(program.global_block().var(out.name())) + + # 3. append backward + backward.gradients(targets=targets, inputs=[]) + return program.desc + + +# [ TranslatedLayer : Run program in imperative mode ] +# +# DESIGN IDEA: using an special operator `RunProgram`, execute program inside operator. +# +# Op's Inputs: +# - the input variable of the user feed +# - the necessary parameters of the network +# Op's Outputs: +# - the output variable of fetch +# +# This op receives a complete program desc, internally creates scope +# and executor, executes this program. Key points: +# +# 1. Data Sharing: +# The varBase of the dynamic graph is not in the scope, so before the op +# executes the program internally, create persistent variables with the +# same name as feed, parameters, and fetch in the scope, and share the +# LoDTensor of the op input. +# +# 2. Forward and Backward Separation: +# Because the dynamic graph op performs the forward and backward separately, +# in the forward op RunProgram, we only execute the forward part of whole program, +# and in the backward op RunProgramGrad, we execute the backward part of program. +# We can not separate the program into forward and backward part, which will +# make some control flow execution logic wrong. + + +# NOTE: [compatible] deal with model saved by save_inference_model, +# which need get var info from program desc +def _load_persistable_vars_by_program( + model_path, program_holder, params_filename=None +): + # make sure the path has been checked + persistable_vars = _get_persistable_vars(program_holder.infer_program) + load_var_dict = {} + for each_var in persistable_vars: + orig_each_name = program_holder._suffix_varname_dict[each_var.name()] + if _is_parameter(each_var, program_holder.infer_program): + # create output varbase + if framework._in_eager_without_dygraph_check(): + new_var = framework.EagerParamBase( + shape=each_var.shape(), + dtype=each_var.dtype(), + name=each_var.name(), + type=each_var.type(), + persistable=True, + ) + else: + new_var = framework.ParamBase( + shape=each_var.shape(), + dtype=each_var.dtype(), + name=each_var.name(), + type=each_var.type(), + persistable=True, + ) + else: + new_var = framework._varbase_creator( + type=each_var.type(), + name=each_var.name(), + shape=each_var.shape(), + dtype=each_var.dtype(), + persistable=True, + ) + if params_filename is None: + framework._dygraph_tracer().trace_op( + type='load', + inputs={}, + outputs={'Out': new_var}, + attrs={'file_path': os.path.join(model_path, orig_each_name)}, + ) + new_var.stop_gradient = False + load_var_dict[each_var.name()] = new_var + + if params_filename is not None: + load_var_list = [] + dict_name_old_new = { + v: k for k, v in program_holder._suffix_varname_dict.items() + } + for name in sorted(dict_name_old_new.keys()): + load_var_list.append(load_var_dict[dict_name_old_new[name]]) + + framework._dygraph_tracer().trace_op( + type='load_combine', + inputs={}, + outputs={'Out': load_var_list}, + attrs={'file_path': os.path.join(model_path, params_filename)}, + ) + + for each_var in persistable_vars: + if not _is_parameter(each_var, program_holder.infer_program): + continue + param = load_var_dict[each_var.name()] + param.stop_gradient = False + + # NOTE: [Recovery stop gradient information based on the program] + # After loading the model, the stop_gradient information + # of the original variable is lost, but if a parameter does not + # have a corresponding @GRAD variable in the backward program, + # it can be said that it is also stop_gradient + all_var_names = _get_all_var_names(program_holder.train_program) + for var_name in load_var_dict: + grad_var_name = var_name + core.grad_var_suffix() + if grad_var_name not in all_var_names: + load_var_dict[var_name].stop_gradient = True + + return load_var_dict + + +def _load_persistable_vars( + model_path, var_info_path, program_holder, params_filename +): + # 1. load extra var info + with open(var_info_path, 'rb') as f: + extra_var_info = pickle.load(f) + + # 2. construct var dict + load_var_dict = dict() + load_var_list = [] + inv_suffix_varname_dict = { + value: key for key, value in program_holder._suffix_varname_dict.items() + } + + # NOTE(chenweihang): we need load persistable vars based the program, + # because the program may be pruned when `save_inference_model`, some + # var in `extra_var_info` may have been pruned + for name in sorted(inv_suffix_varname_dict): + if name not in extra_var_info: + raise RuntimeError( + "The model to be loaded is not complete." + "The variable `%s` of program cannot be found in loaded model.", + name, + ) + # get suffix var name, see [why need to append suffix to persistable vars] + new_name = inv_suffix_varname_dict[name] + # create output varbase + if extra_var_info[name].get('trainable', None) is not None: + # use default shape and dtype + if framework._in_eager_without_dygraph_check(): + new_var = framework.EagerParamBase( + shape=[ + 1 + ], # only to pass check, this shape is not meaningful + dtype=core.VarDesc.VarType.FP32, + name=new_name, + persistable=True, + ) + else: + new_var = framework.ParamBase( + shape=[ + 1 + ], # only to pass check, this shape is not meaningful + dtype=core.VarDesc.VarType.FP32, + name=new_name, + persistable=True, + ) + else: + new_var = framework._varbase_creator( + name=new_name, persistable=True + ) + + new_var.stop_gradient = extra_var_info[name]['stop_gradient'] + load_var_dict[new_name] = new_var + load_var_list.append(new_var) + + # 3. load all vars + assert params_filename is not None, "params_filename should not be None." + var_file_path = os.path.join(model_path, params_filename) + if not os.path.exists(var_file_path): + if len(extra_var_info) != 0: + raise ValueError("The model to be loaded is incomplete.") + else: + framework._dygraph_tracer().trace_op( + type='load_combine', + inputs={}, + outputs={'Out': load_var_list}, + attrs={'file_path': var_file_path}, + ) + + return load_var_dict + + +# NOTE(chenweihang): to adapt paddle.load to get state_dict +def _remove_varname_suffix(var_dict, program_holder): + no_suffix_var_dict = dict() + for var_name in var_dict: + no_suffix_name = program_holder._suffix_varname_dict[var_name] + no_suffix_var_dict[no_suffix_name] = var_dict[var_name] + return no_suffix_var_dict + + +def _construct_program_holders(model_path, model_filename=None): + # make sure the path has been checked + program_holder_dict = dict() + + if model_filename is not None: + # [compatible] if assign model_filename, only can load one program as Layer.forward + model_filename = os.path.basename(model_filename) + model_file_path = os.path.join(model_path, model_filename) + model_name = model_filename[: -len(INFER_MODEL_SUFFIX)] + # Load every file that meets the requirements in the directory model_path. + for filename in os.listdir(model_path): + if model_filename == filename: + func_name = 'forward' + model_file_path = os.path.join(model_path, model_filename) + elif filename.endswith(INFER_MODEL_SUFFIX) and filename.startswith( + model_name + ): + parsing_names = filename[ + len(model_name) : -len(INFER_MODEL_SUFFIX) + 1 + ].split('.') + if len(parsing_names) == 3 and len(parsing_names[1]) > 0: + func_name = parsing_names[1] + model_file_path = os.path.join(model_path, filename) + else: + continue + else: + continue + program_holder_dict[func_name] = _ProgramHolder( + _load_program_desc(model_file_path) + ) + else: + for _, _, file_names in os.walk(model_path): + for name in file_names: + if 'model' in name: + model_file_path = os.path.join(model_path, name) + method_name = name.strip('_') + if method_name == 'model': + method_name = 'forward' + else: + method_name.replace('model', '') + program_holder_dict[method_name] = _ProgramHolder( + _load_program_desc(model_file_path) + ) + + return program_holder_dict + + +def _construct_params_and_buffers( + model_path, programs, params_filename=None, append_suffix=True +): + var_info_filename = str(params_filename) + ".info" + var_info_path = os.path.join(model_path, var_info_filename) + params_path = os.path.join(model_path, str(params_filename)) + + if os.path.exists(var_info_path): + var_dict = _load_persistable_vars( + model_path, var_info_path, programs['forward'], params_filename + ) + model_name = params_filename[: -len(INFER_PARAMS_SUFFIX)] + # Load every file that meets the requirements in the directory model_path. + for file_name in os.listdir(model_path): + if file_name.startswith(model_name) and file_name.endswith( + INFER_PARAMS_SUFFIX + ): + parsing_names = file_name[ + len(model_name) : -len(INFER_PARAMS_SUFFIX) + 1 + ].split('.') + if len(parsing_names) == 3 and len(parsing_names[1]) > 0: + func_name = parsing_names[1] + else: + continue + else: + continue + var_info_path = os.path.join(model_path, var_info_filename) + var_dict.update( + _load_persistable_vars( + model_path, var_info_path, programs[func_name], file_name + ) + ) + elif params_filename is not None and not os.path.exists(params_path): + # When saving XX, there is only '*.pdmodel' + return dict() + else: + var_dict = _load_persistable_vars_by_program( + model_path, programs['forward'], params_filename + ) + + if not append_suffix: + var_dict = _remove_varname_suffix(var_dict, programs['forward']) + + return var_dict + + +def _valid_vars(vars): + if vars: + return vars + if framework._in_eager_without_dygraph_check(): + return [ + core.eager.Tensor( + core.VarDesc.VarType.FP32, + [], + "Fake_var", + core.VarDesc.VarType.RAW, + False, + ) + ] + else: + return [ + core.VarBase( + core.VarDesc.VarType.FP32, + [], + "Fake_var", + core.VarDesc.VarType.RAW, + False, + ) + ] + + +def _run_dygraph(instance, input, program_holder): + + # 1. prepare inputs, outputs, attrs + input_vars = [] + for i, value in enumerate(input): + if not isinstance(value, (np.ndarray, core.VarBase, core.eager.Tensor)): + raise TypeError( + "The type of input in TranslatedLayer must be numpy array or Variable(VarBase), but received %s." + % type(value) + ) + # NOTE: In order to unify the API, firstly convert the input to VarBase + if isinstance(value, np.ndarray): + if framework._in_eager_without_dygraph_check(): + var = core.eager.Tensor( + value=value, + name=program_holder.input_descs[i].name(), + persistable=False, + place=framework._current_expected_place(), + zero_copy=True, + ) + else: + var = core.VarBase( + value=value, + name=program_holder.input_descs[i].name(), + persistable=False, + place=framework._current_expected_place(), + zero_copy=True, + ) + else: + var = value + # NOTE: we changed var name here, + # but it may be an important name set by user + var.name = program_holder.input_descs[i].name() + input_vars.append(var) + if instance._input_args_names is None: + instance._input_args_names = [ + ins.name() for ins in program_holder.input_descs + ] + + persistable_vars = [] + for var_name in program_holder.persistable_names: + dy_var_name = instance._persistable_var_name_dict[var_name] + if dy_var_name in instance._parameters: + persistable_vars.append(instance._parameters[dy_var_name]) + elif dy_var_name in instance._buffers: + persistable_vars.append(instance._buffers[dy_var_name]) + else: + raise ValueError( + "The persistable variable %s does not exist in current TranslatedLayer." + % var_name + ) + + output_vars = [] + for var_desc in program_holder.output_descs: + if framework._in_eager_without_dygraph_check(): + var = core.eager.Tensor( + dtype=var_desc.dtype(), + dims=var_desc.shape(), + name=var_desc.name(), + type=var_desc.type(), + persistable=False, + ) + else: + var = core.VarBase( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + output_vars.append(var) + + # hold forward variables + if framework._in_eager_without_dygraph_check(): + tmp_scope_vec = [program_holder.scope] + else: + tmp_scope_vec = core.VarBase( + core.VarDesc.VarType.FP32, + [], + "program_out_scope", + core.VarDesc.VarType.STEP_SCOPES, + True, + ) + tmp_scope_vec.value().set_scope(program_holder.scope) + + double_grad_vars = [] + for var_desc in program_holder.double_grad_descs: + if framework._in_eager_without_dygraph_check(): + var = core.eager.Tensor( + dtype=var_desc.dtype(), + dims=var_desc.shape(), + name=var_desc.name(), + type=var_desc.type(), + persistable=False, + ) + else: + var = core.VarBase( + var_desc.dtype(), + var_desc.shape(), + var_desc.name(), + var_desc.type(), + False, + ) + double_grad_vars.append(var) + + # 2. run program by op + trace_program = ( + program_holder.infer_program + if instance._is_test + else program_holder.train_program + ) + forward_program = ( + program_holder._infer_program_desc + if instance._is_test + else program_holder.forward_program + ) + end_op_index = program_holder.infer_program.block(0).op_size() + + attrs = [ + 'global_block', + trace_program.block(0), + 'start_op_index', + 0, + 'end_op_index', + end_op_index, + 'is_test', + instance._is_test, + 'program_id', + _hash_with_id(trace_program, instance), + ] + + use_interpretorcore = ( + _is_enable_standalone_executor() + and _is_dy2st_enable_standalone_executor() + ) + attrs.extend(('use_interpretorcore', use_interpretorcore)) + if use_interpretorcore: + attrs.extend( + ( + 'forward_global_block', + forward_program.block(0), + 'backward_global_block', + program_holder.backward_program.block(0), + ) + ) + + _legacy_C_ops.run_program( + _valid_vars(input_vars), + _valid_vars(persistable_vars), + _valid_vars(output_vars), + tmp_scope_vec, + _valid_vars(double_grad_vars), + None, + *attrs + ) + + # NOTE: [ why need set param's gradient type here ] + # if user set sparse gradient mode, the param's gradient + # will be SelectedRows, not LoDTensor. But tracer will just + # set param grad VarBase by forward VarBase(LoDTensor) + # If we don't change grad_var type here, RunProgramOp need + # transform SelectedRows to LoDTensor forcibly, it may not + # be user wanted result. + for persistable_var in persistable_vars: + grad_var_name = persistable_var.name + core.grad_var_suffix() + grad_var = trace_program.block(0).find_var(cpt.to_bytes(grad_var_name)) + # NOTE: cannot find var desc maybe not problem, + # such as in batch_norm + if grad_var is None: + continue + persistable_var._set_grad_type(grad_var.type()) + + # 3. prepare output, keep same form with inputs + outs = output_vars + if len(output_vars) == 1: + outs = output_vars[0] + return outs + + +def _run_static_graph(input, program_holder, trace_program): + main_program = framework.default_main_program() + param_var_names = _get_persistable_var_names(trace_program) + _, dict_rename_var_old_new = _rename_var_program_desc( + trace_program, exclude=param_var_names + ) + trace_program.flush() + output_names = [var.name() for var in program_holder.output_descs] + # append blocks from 'trace_program' + _append_block( + main_program, + trace_program, + program_holder, + input, + dict_rename_var_old_new, + ) + main_program._sync_with_cpp() + outs = _get_output_from_program( + main_program, program_holder, dict_rename_var_old_new + ) + if len(outs) == 1: + outs = outs[0] + return outs + + +def _collect_current_and_parent_var(program, block_idx): + ''' + Get variables in current block and its parent block. + + Args: + program(Program): The program containing the current block. + block_idx(int): index of current block. + + Returns: + List: list of variables. + ''' + vars = [] + if block_idx < 0: + return vars + for var in program.block(block_idx).vars: + vars.append(var) + parent_idx = program.block(block_idx).parent_idx + if parent_idx > -1: + vars += _collect_current_and_parent_var(program, parent_idx) + return vars + + +def _append_block( + dest_program, + src_program_desc, + program_holder, + input_variables, + dict_rename_var_old_new=None, +): + ''' + Append Variables and Operators in 'src_program_desc' to dest_program. + + Args: + dest_program(Program): Variables and Operators are appended to it. + src_program_desc(ProgramDesc): Variables in it will be appended to 'dest_program'. + program_holder(_ProgramHolder): program_holder of TranslatedLayer + input_variables(list): list of input variables + dict_rename_var_old_new(None|dict): When using '_rename_var_program_desc', + use it to map the name of the variable before it was modified and the new name. + ''' + + origin_block_idx = dest_program.current_block_idx + param_var_names = _collect_current_and_parent_var( + dest_program, origin_block_idx + ) + append_var_from_block_desc_static( + dest_program.block(origin_block_idx), + src_program_desc.block(0), + exclude=param_var_names, + ) + + name_inp_desc = [inp.name() for inp in program_holder.input_descs] + input_names = [inp.name for inp in input_variables] + if len(name_inp_desc) != len(input_names): + raise ValueError( + "The number of input is invalid, expected {}, but received {}.".format( + len(name_inp_desc), len(input_names) + ) + ) + for i, out_name in enumerate(name_inp_desc): + if dict_rename_var_old_new: + out_name = dict_rename_var_old_new[out_name] + dest_program.block(origin_block_idx).append_op( + type='assign', + inputs={'X': [input_names[i]]}, + outputs={'Out': [out_name]}, + ) + + append_ops = append_op_from_block_desc_static( + dest_program.block(origin_block_idx), src_program_desc.block(0) + ) + dest_program._sync_with_cpp() + + offset_block_idx = dest_program.num_blocks - 1 + + if src_program_desc.num_blocks() > 1: + for src_block_idx in range(1, src_program_desc.num_blocks()): + src_block = src_program_desc.block(src_block_idx) + src_parent_idx = src_block.parent + if src_parent_idx > 0: + parent_idx = offset_block_idx + parent_idx + else: + parent_idx = origin_block_idx + dest_block = dest_program._create_block(parent_idx=parent_idx) + append_var_from_block_desc_static( + dest_block, src_block, exclude=param_var_names + ) + append_ops += append_op_from_block_desc_static( + dest_block, src_block + ) + + dest_program._sync_with_cpp() + for op in append_ops: + if op.has_attr('sub_block'): + sub = op.attr('sub_block') + if isinstance(sub, framework.core.BlockDesc): + origin_id = sub.id + if isinstance(sub, framework.Block): + origin_id = sub.idx + op._set_attr( + 'sub_block', dest_program.block(offset_block_idx + origin_id) + ) + dest_program._sync_with_cpp() + dest_program.current_block_idx = origin_block_idx + + +def _get_output_from_program( + program, program_holder, dict_rename_var_old_new=None +): + """ + Get output name of 'program' according to program_holder + """ + outs = list() + for var in program_holder.output_descs: + for idx in range(program.num_blocks): + vars = program.block(idx).vars + var_name = var.name() + if dict_rename_var_old_new: + var_name = dict_rename_var_old_new[var_name] + if var_name in vars: + out = vars[var_name] + if out not in outs: + outs.append(out) + return outs + + +def append_op_from_block_desc_static(block, src_block_desc): + """ + Append Operators of 'src_block_desc' to current block. + + Args: + block(Block): append OP of 'src_block_desc' to it. + src_block_desc(BlockDesc): append var of 'src_block_desc' + + Returns: + List: list of the OP that are append to current block. + """ + ops = [] + for i in range(src_block_desc.op_size()): + ops.append(append_op_from_desc_static(block, src_block_desc.op(i))) + return ops + + +def append_op_from_desc_static(block, op_desc): + """ + Append Operators to 'block' according to 'op_desc'. + + Args: + block(Block): append OP of 'src_block_desc' to it. + op_desc(OpDesc): create OP according to it. + + Returns: + Operator: OP appended to 'block'. + """ + op_type = op_desc.type() + op_append = block.desc.append_op() + op_append.copy_from(op_desc) + op = framework.Operator( + block=block, + desc=op_append, + type=op_type, + inputs=None, + outputs=None, + attrs=None, + ) + block.ops.append(op) + return op + + +def append_var_from_block_desc_static( + block, src_block_desc, include=None, exclude=None +): + """ + Append Variables of 'src_block_desc' to current block. + If 'include' is not `None`,variables that are not in include are not append. + If 'exclude' is not `None`,variables that are in exclude will are not append. + + Args: + block(Block): append Variables of 'src_block_desc' to it. + src_block_desc(BlockDesc): append var of 'src_block_desc' + include(List):list of names of variables + exclude(List):list of names of variables + + Returns: + List: list of the variables that are append to current block. + """ + vars_append = [] + for var_desc in src_block_desc.all_vars(): + var_desc_name = var_desc.name() + should_append = (include is None or var_desc_name in include) and ( + exclude is None or var_desc_name not in exclude + ) + if not block.has_var(var_desc_name) and should_append: + var_type = var_desc.type() + if var_type in [ + core.VarDesc.VarType.SELECTED_ROWS, + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.LOD_TENSOR_ARRAY, + ]: + data_type = var_desc.dtype() + var_shape = var_desc.shape() + else: + data_type = None + var_shape = None + if var_type in [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.LOD_TENSOR_ARRAY, + ]: + lod_level = var_desc.lod_level() + else: + lod_level = None + + if var_desc.persistable(): + current_block = block.program.global_block() + else: + current_block = block + + vars_append.append( + current_block.create_var( + name=var_desc.name(), + dtype=data_type, + type=var_type, + shape=var_shape, + lod_level=lod_level, + persistable=var_desc.persistable(), + set_need_check_feed=var_desc.need_check_feed(), + ) + ) + return vars_append + + +class TranslatedLayer(layers.Layer): + """ + TranslatedLayer is a ``paddle.nn.Layer`` for holding the model + loaded by :ref:`api_paddle_jit_load` . It can be used like a + general Layer object in eval or train mode. + + .. note: + The TranslatedLayer objects should not be created by constructor, it only can be loaded and constructed by :ref:`api_paddle_jit_load` . + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + opt.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + # 1. train & save model. + + # create network + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters()) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + # train + train(layer, loader, loss_fn, adam) + + # save + model_path = "linear.example.model" + paddle.jit.save(layer, model_path) + + # 2. load model as TranslatedLayer + + # load + translated_layer = paddle.jit.load(model_path) + + # inference + translated_layer.eval() + x = paddle.randn([1, IMAGE_SIZE], 'float32') + pred = translated_layer(x) + + # fine-tune + translated_layer.train() + adam = opt.Adam(learning_rate=0.001, parameters=translated_layer.parameters()) + train(translated_layer, loader, loss_fn, adam) + + """ + + def __init__(self, programs, persistable_vars): + super(TranslatedLayer, self).__init__() + + if not isinstance(programs, dict): + raise TypeError( + "TranslatedLayer need to use _ProgramHolder's dict for initialization." + ) + if not isinstance(persistable_vars, dict): + raise TypeError( + "TranslatedLayer need to use persistable variable dict for initialization." + ) + + self._program_holder_dict = programs + + # NOTE(chenweihang): [ why not use var name directly? ] + # When add parameter or buffer to Layer by follow apis, + # the variable name can't contain `.`, beccause which may cause + # AttributeError when access the newly added parameter or buffer + # in the form of `self.**.**``, but the ParamBase or BarBase + # name contains `.` originally, such as `linear_0.w_0`, so here + # need to generate new var name for each var + self._persistable_var_name_dict = dict() + # the TranslatedLayer object holded var names count started from 0 + with unique_name.guard(): + for name, var in persistable_vars.items(): + if isinstance( + var, (framework.ParamBase, framework.EagerParamBase) + ): + dy_name = _generate_unique_var_name(PARAMETER_NAME_PREFIX) + self._persistable_var_name_dict[name] = dy_name + self.add_parameter(dy_name, var) + elif isinstance(var, (core.VarBase, core.eager.Tensor)): + dy_name = _generate_unique_var_name(BUFFER_NAME_PREFIX) + self._persistable_var_name_dict[name] = dy_name + self.register_buffer(dy_name, var) + else: + raise TypeError( + "Adding persistent variable which to layer is not supported now" + ) + + self._is_test = True + self._input_args_names = None + + @staticmethod + @framework.dygraph_only + def _construct(model_path, configs=None): + # 0. dir and filename check + model_path = os.path.normpath(model_path) + if not os.path.isdir(model_path): + raise ValueError("There is no directory named '%s'" % model_path) + model_filename = None + params_filename = None + if configs is not None: + model_filename = configs.model_filename + params_filename = configs.params_filename + + # 1. load program desc & construct _ProgramHolder + programs = _construct_program_holders(model_path, model_filename) + + # 2. load layer parameters & buffers + persistable_vars = _construct_params_and_buffers( + model_path, programs, params_filename + ) + + # 3. construct TranslatedLayer object + translated_layer = TranslatedLayer(programs, persistable_vars) + + # 4. create TranslatedLayer's execution method + for method_name, program_holder in programs.items(): + if translated_layer._input_args_names is None: + translated_layer._input_args_names = [ + ins.name() for ins in program_holder.input_descs + ] + setattr( + TranslatedLayer, + method_name, + TranslatedLayer._execution_method_creator( + method_name, program_holder + ), + ) + + # 5. set TranslatedLayer's default mode to eval + translated_layer.eval() + + return translated_layer + + @staticmethod + def _execution_method_creator(method_name, program_holder): + def __i_m_p_l__(self, *input): + program_holder = self._program_holder_dict[__i_m_p_l__.__name__] + # When using jit.save, it runs in static graph mode. + # Run in dynamic graph mode when the model is inferring. + if _non_static_mode(): + return _run_dygraph(self, input, program_holder) + else: + # NOTE(weixin): [ why not use 'program_holder.infer_program' directly? ] + # When use '_run_static_graph(input, program_holder, program_holder.infer_program)', + # because '_run_static_graph' modifies 'ProgramDesc', 'OpDesc.op_size()' will return a very large wrong number. + # A Segmentation fault error may occur if used 'p=ProgramDesc(program_holder.infer_program)'. + p = framework.Program._construct_from_desc( + core.ProgramDesc(program_holder.infer_program) + ) + return _run_static_graph(input, program_holder, p.desc) + + __i_m_p_l__.__name__ = method_name + return __i_m_p_l__ + + def train(self): + self._is_test = False + self.training = True + + def eval(self): + self._is_test = True + self.training = False + + def program(self, method_name='forward'): + """ + Gets translated program of specified method. + + Args: + - method_name (string): mehtod name corresponding to the program + to be obtained. Default: 'forward'. + + Returns: + Program + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + opt.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + # create network + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters()) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + # train + train(layer, loader, loss_fn, adam) + + # save + model_path = "linear.example.model" + paddle.jit.save(layer, model_path) + + # load + translated_layer = paddle.jit.load(model_path) + + # get program + program = translated_layer.program() + """ + # 1. get program holder + program_holder = self._get_program_holder(method_name) + + # 2. get inference program desc + program_desc = program_holder.infer_program + + # 3. construct program + program = _build_program_by_desc(program_desc) + return program + + def _get_program_holder(self, method_name='forward'): + program_holder = self._program_holder_dict.get(method_name, None) + if program_holder is None: + raise ValueError( + "The method `%s` does not exist in loaded TranslatedLayer." + % method_name + ) + return program_holder + + def _input_spec(self, method_name='forward'): + # 1. get program holder + program_holder = self._get_program_holder(method_name) + + # 2. build input spec by input desc + input_spec = [] + for var_desc in program_holder.input_descs: + spec = paddle.static.InputSpec( + shape=var_desc.shape(), + dtype=var_desc.dtype(), + name=var_desc.name(), + ) + input_spec.append(spec) + + return input_spec + + def _output_spec(self, method_name='forward'): + # 1. get program holder + program_holder = self._get_program_holder(method_name) + + # 2. build output spec by output desc + output_spec = [] + for var_desc in program_holder.output_descs: + # NOTE(chenweihang): InputSpec describes a tensor, not just input. + # Maybe the name is not good enough. Here we use InputSpec to + # construct the description of Output tensor + spec = paddle.static.InputSpec( + shape=var_desc.shape(), + dtype=var_desc.dtype(), + name=var_desc.name(), + ) + output_spec.append(spec) + + return output_spec diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/jit.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0c7bda0a895b405f58b3053eb05a96c7bef415 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/jit.py @@ -0,0 +1,1693 @@ +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from __future__ import print_function + +import os +import pickle +import warnings +import functools +from collections import OrderedDict +import inspect +import threading +from typing import Text, Tuple, Any, List + +import six +import paddle +from paddle.fluid import core, dygraph +from paddle.fluid.compiler import BuildStrategy, CompiledProgram, ExecutionStrategy +from paddle.fluid.data_feeder import check_type +from paddle.fluid.layers.utils import flatten, pack_sequence_as +from paddle.fluid.dygraph.base import program_desc_tracing_guard, switch_to_static_graph +from paddle.fluid.dygraph.dygraph_to_static import logging_utils +from paddle.fluid.dygraph.dygraph_to_static.convert_call_func import ConversionOptions, CONVERSION_OPTIONS +from paddle.fluid.dygraph.dygraph_to_static.logging_utils import set_code_level, set_verbosity +from paddle.fluid.dygraph.dygraph_to_static.program_translator import ProgramTranslator, StaticFunction, unwrap_decorators +from paddle.fluid.dygraph.io import TranslatedLayer, INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX, INFER_PARAMS_INFO_SUFFIX, INFER_PROPERTY_SUFFIX +from paddle.fluid.dygraph.layers import Layer +from paddle.fluid.executor import Executor, scope_guard +from paddle.fluid.framework import Block, ParamBase, Program, Variable, Parameter, EagerParamBase +from paddle.fluid.framework import _current_expected_place, _dygraph_guard, _dygraph_tracer +from paddle.fluid.framework import dygraph_only, _non_static_mode +from paddle.fluid.wrapped_decorator import wrap_decorator + +__all__ = [ + 'TracedLayer', 'declarative', 'dygraph_to_static_func', 'set_code_level', + 'set_verbosity', 'save', 'load', 'not_to_static' +] + + +def create_program_from_desc(program_desc): + program = Program() + program.desc = program_desc + program.blocks = [Block(program, 0)] + program._sync_with_cpp() + return program + + +def _extract_vars(inputs, result_list, err_tag='inputs'): + if isinstance(inputs, Variable): + result_list.append(inputs) + elif isinstance(inputs, (list, tuple)): + for var in inputs: + _extract_vars(var, result_list, err_tag) + else: + raise TypeError( + "The type of 'each element of {}' in fluid.dygraph.jit.TracedLayer.trace must be fluid.Variable, but received {}." + .format(err_tag, type(inputs))) + + +def extract_vars(inputs, err_tag='inputs'): + result_list = [] + _extract_vars(inputs, result_list, err_tag) + return result_list + + +def _dygraph_to_static_func_(dygraph_func): + """ + Converts imperative dygraph APIs into declarative function APIs. Decorator + @dygraph_to_static_func only converts imperative dygraph APIs into + declarative net-building APIs, which means it doesn't return immediate + digital result as imperative mode. Users should handle Program and Executor + by themselves. + + Note: + This decorator is NOT our recommended way to transform imperative function + to declarative function. We will remove this decorator after we finalize + cleaning up code. + + Args: + dygraph_func (callable): callable imperative function. + + Returns: + Callable: converting imperative dygraph APIs into declarative + net-building APIs. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + from paddle.fluid.dygraph.jit import dygraph_to_static_func + + @dygraph_to_static_func + def func(x): + if paddle.mean(x) < 0: + x_v = x - 1 + else: + x_v = x + 1 + + return x_v + + x = fluid.layers.fill_constant(shape=[3, 3], value=0, dtype='float64') + + x_v = func(x) + exe = fluid.Executor(fluid.CPUPlace()) + out = exe.run(fetch_list=[x_v]) + print(out[0]) + # [[1. 1. 1.] + # [1. 1. 1.] + # [1. 1. 1.]] + + """ + + # TODO: remove this decorator after we finalize training API + def __impl__(*args, **kwargs): + program_translator = ProgramTranslator() + if _non_static_mode() or not program_translator.enable_to_static: + logging_utils.warn( + "The decorator 'dygraph_to_static_func' doesn't work in " + "dygraph mode or set ProgramTranslator.enable to False. " + "We will just return dygraph output.") + return dygraph_func(*args, **kwargs) + static_func = program_translator.get_func(dygraph_func) + return static_func(*args, **kwargs) + + return __impl__ + + +dygraph_to_static_func = wrap_decorator(_dygraph_to_static_func_) + + +def copy_decorator_attrs(original_func, decorated_obj): + """ + Copies some necessary attributes from original function into decorated function. + + Args: + original_func(callable): the original decorated function. + decorated_obj(StaticFunction): the target decorated StaticFunction object. + """ + decorator_name = "declarative" + + decorated_obj.__name__ = original_func.__name__ + decorated_obj._decorator_name = decorator_name + decorated_obj.__wrapped__ = original_func + decorated_obj.__doc__ = original_func.__doc__ + if hasattr(original_func, "__module__"): + decorated_obj.__module__ = original_func.__module__ + + return decorated_obj + + +def declarative(function=None, + input_spec=None, + build_strategy=None, + property=False): + """ + Converts imperative dygraph APIs into declarative function APIs. Decorator + @declarative handles the Program and Executor of static mode and returns + the result as dygraph Tensor(s). Users could use the returned dygraph + Tensor(s) to do imperative training, inference, or other operations. If the + decorated function calls other imperative function, the called one will be + converted into declarative function as well. + + Args: + function (callable): callable imperative function. + input_spec(list[InputSpec]|tuple[InputSpec]): list/tuple of InputSpec to specific the shape/dtype/name + information of each input Tensor. + build_strategy(BuildStrategy|None): This argument is used to compile the + converted program with the specified options, such as operators' fusion + in the computational graph and memory optimization during the execution + of the computational graph. For more information about build_strategy, + please refer to :code:`paddle.static.BuildStrategy`. The default is None. + property(bool, Optional): whether the fucntion is python property. The default is False. + + + Returns: + Tensor(s): containing the numerical result. + + Examples: + .. code-block:: python + + import paddle + from paddle.jit import to_static + + @to_static + def func(x): + if paddle.mean(x) < 0: + x_v = x - 1 + else: + x_v = x + 1 + return x_v + + x = paddle.ones([1, 2], dtype='float32') + x_v = func(x) + print(x_v) # [[2. 2.]] + + """ + + def decorated(python_func): + """ + Decorates a python function into a StaticFunction object. + """ + # Step 1. unwrap the function if it is already decorated. + _, python_func = unwrap_decorators(python_func) + + # Step 2. copy some attributes from original python function. + static_layer = copy_decorator_attrs(original_func=python_func, + decorated_obj=StaticFunction( + function=python_func, + input_spec=input_spec, + build_strategy=build_strategy, + property=property)) + + return static_layer + + build_strategy = build_strategy or BuildStrategy() + if not isinstance(build_strategy, BuildStrategy): + raise TypeError( + "Required type(build_strategy) shall be `paddle.static.BuildStrategy`, but received {}" + .format(type(build_strategy).__name__)) + + # for usage: `declarative(foo, ...)` + if function is not None: + if isinstance(function, Layer): + if isinstance(function.forward, StaticFunction): + class_name = function.__class__.__name__ + logging_utils.warn( + "`{}.forward` has already been decorated somewhere. It will be redecorated to replace previous one." + .format(class_name)) + function.forward = decorated(function.forward) + return function + else: + return decorated(function) + + # for usage: `@declarative` + return decorated + + +def not_to_static(func=None): + """ + A Decorator to suppresses the convertion of a function. + + Args: + func(callable): The function to decorate. + + Returns: + callable: A function which won't be converted in Dynamic-to-Static. + + Examples: + .. code-block:: python + + import paddle + + @paddle.jit.not_to_static + def func_not_to_static(x): + res = x - 1 + return res + + @paddle.jit.to_static + def func(x): + if paddle.mean(x) < 0: + out = func_not_to_static(x) + else: + out = x + 1 + return out + + x = paddle.ones([1, 2], dtype='float32') + out = func(x) + print(out) # [[2. 2.]] + """ + if func is None: + return not_to_static + + options = ConversionOptions(not_convert=True) + setattr(func, CONVERSION_OPTIONS, options) + return func + + +class _SaveLoadConfig(object): + + def __init__(self): + self._output_spec = None + self._model_filename = None + self._params_filename = None + self._separate_params = False + # used for `paddle.load` + self._keep_name_table = False + + # NOTE: Users rarely use following configs, so these configs are not open to users, + # reducing user learning costs, but we retain the configuration capabilities + + # If True, programs are modified to only support direct inference deployment. + # Otherwise,more information will be stored for flexible optimization and re-training. + # Currently, only True is supported + self._export_for_deployment = True + + # If True, It will save inference program only, and do not save params of Program + self._program_only = False + self.with_hook = False + + # if True, multi `StaticFunction` will share params in one file. + self.combine_params = False + + @property + def output_spec(self): + return self._output_spec + + @output_spec.setter + def output_spec(self, spec): + if spec is None: + return + if not isinstance(spec, list): + raise TypeError( + "The config `output_spec` should be 'list', but received input type is %s." + % type(input)) + for var in spec: + if not isinstance(var, core.VarBase): + raise TypeError( + "The element in config `output_spec` list should be 'Variable', but received element's type is %s." + % type(var)) + self._output_spec = spec + + @property + def model_filename(self): + return self._model_filename + + @model_filename.setter + def model_filename(self, filename): + if filename is None: + return + if not isinstance(filename, six.string_types): + raise TypeError( + "The config `model_filename` should be str, but received input's type is %s." + % type(filename)) + if len(filename) == 0: + raise ValueError("The config `model_filename` is empty string.") + self._model_filename = filename + + @property + def params_filename(self): + return self._params_filename + + @params_filename.setter + def params_filename(self, filename): + if filename is None: + return + if not isinstance(filename, six.string_types): + raise TypeError( + "The config `params_filename` should be str, but received input's type is %s." + % type(filename)) + if len(filename) == 0: + raise ValueError("The config `params_filename` is empty string.") + self._params_filename = filename + + @property + def keep_name_table(self): + return self._keep_name_table + + @keep_name_table.setter + def keep_name_table(self, value): + if value is None: + return + if not isinstance(value, bool): + raise TypeError( + "The config `keep_name_table` should be bool value, but received input's type is %s." + % type(value)) + self._keep_name_table = value + + +def _parse_save_configs(configs): + supported_configs = [ + 'output_spec', "with_hook", "combine_params", "clip_extra", + "skip_forward" + ] + + # input check + for key in configs: + if key not in supported_configs: + raise ValueError( + "The additional config (%s) of `paddle.jit.save` is not supported." + % (key)) + + # construct inner config + inner_config = _SaveLoadConfig() + inner_config.output_spec = configs.get('output_spec', None) + inner_config.with_hook = configs.get('with_hook', False) + inner_config.combine_params = configs.get("combine_params", False) + inner_config.clip_extra = configs.get("clip_extra", True) + inner_config.skip_forward = configs.get("skip_forward", False) + + return inner_config + + +def _parse_load_config(configs): + supported_configs = ['model_filename', 'params_filename'] + + # input check + for key in configs: + if key not in supported_configs: + raise ValueError( + "The additional config (%s) of `paddle.jit.load` is not supported." + % (key)) + + # construct inner config + inner_config = _SaveLoadConfig() + inner_config.model_filename = configs.get('model_filename', None) + inner_config.params_filename = configs.get('params_filename', None) + + return inner_config + + +def _get_input_var_names(inputs, input_spec): + name_none_error = "The %s's name is None. " \ + "When using jit.save, please set InputSepc's name in " \ + "to_static(input_spec=[]) and jit.save(input_spec=[]) " \ + "and make sure they are consistent." + name_no_exists_error = "The tensor `%s` does not exists. " \ + "Please make sure the name of InputSpec or example Tensor " \ + "in input_spec is the same as the name of InputSpec in " \ + "`to_static` decorated on the Layer.forward method." + result_list = [] + input_var_names = [ + var.name for var in flatten(inputs) if isinstance(var, Variable) + ] + if input_spec is None: + # no prune + return input_var_names + else: + # fileter out non-tensor type spec infos. + input_spec = [ + spec for spec in input_spec + if isinstance(spec, paddle.static.InputSpec) + ] + + if len(input_spec) == len(input_var_names): + # no prune + result_list = input_var_names + # if input spec name not in input_var_names, only raise warning + for spec in input_spec: + if spec.name is None: + warnings.warn(name_none_error % spec) + elif spec.name not in input_var_names: + warnings.warn(name_no_exists_error % spec.name) + else: + # do nothing + pass + else: + # prune + for spec in input_spec: + if spec.name is None: + # name is None, the input_spec only can be InputSpec + raise ValueError(name_none_error % spec) + elif spec.name not in input_var_names: + # the input_spec can be `InputSpec` or `VarBase` + raise ValueError(name_no_exists_error % spec.name) + else: + result_list.append(spec.name) + + return result_list + + +def _get_output_vars(outputs, output_spec, with_hook=False): + name_no_exists_error = "The tensor `%s` does not exists. " \ + "Please make sure the name of example Tensor " \ + "in configs.output_spec is the output tensor of " \ + "Layer.forward method." + if output_spec and with_hook: + raise RuntimeError( + "Currently not support specify output_spec while founding pre/post hooks in your outermost layer." + ) + result_list = [] + output_vars_dict = OrderedDict() + for var in flatten(outputs): + if isinstance(var, Variable): + output_vars_dict[var.name] = var + if output_spec is None: + result_list = list(output_vars_dict.values()) + elif output_spec is not None and len(output_spec) == len(output_vars_dict): + result_list = list(output_vars_dict.values()) + for var in output_spec: + if var.name not in output_vars_dict: + warnings.warn(name_no_exists_error % var.name) + else: + for var in output_spec: + if var.name not in output_vars_dict: + raise ValueError(name_no_exists_error % var.name) + else: + result_list.append(output_vars_dict[var.name]) + return result_list + + +# NOTE(chenweihang): [ Handling of use cases of API paddle.jit.load ] +# `paddle.jit.load` may be used to load saved results of: +# 1. Expected cases: +# - paddle.jit.save +# - paddle.static.save_inference_model +# - paddle.fluid.io.save_inference_model +# 2. Error cases: +# - paddle.save: no .pdmodel for prefix +# - paddle.static.save: no .pdiparams but .pdparams exists +# - paddle.fluid.io.save_params/save_persistables: no __model__ +# TODO(chenweihang): polish error message in above error cases +def _build_load_path_and_config(path, config): + # NOTE(chenweihang): If both [prefix save format] and [directory save format] exist, + # raise error, avoid confusing behavior + prefix_format_path = path + INFER_MODEL_SUFFIX + prefix_format_exist = os.path.exists(prefix_format_path) + directory_format_exist = os.path.isdir(path) + if prefix_format_exist and directory_format_exist: + raise ValueError( + "The %s.pdmodel and %s directory exist at the same time, " + "don't know which one to load, please make sure that the specified target " + "of ``path`` is unique." % (path, path)) + elif not prefix_format_exist and not directory_format_exist: + raise ValueError("The ``path`` (%s) to load model not exists. " + "Please make sure that *.pdmodel exists or " + "don't using ``skip_forward=True`` to jit.save." % + path) + else: + if prefix_format_exist: + file_prefix = os.path.basename(path) + model_path = os.path.dirname(path) + if config.model_filename is not None: + warnings.warn( + "When loading the result saved with the " + "specified file prefix, the ``model_filename`` config does " + "not take effect.") + config.model_filename = file_prefix + INFER_MODEL_SUFFIX + if config.params_filename is not None: + warnings.warn( + "When loading the result saved with the " + "specified file prefix, the ``params_filename`` config does " + "not take effect.") + config.params_filename = file_prefix + INFER_PARAMS_SUFFIX + else: + # Compatible with the old save_inference_model format + model_path = path + + return model_path, config + + +_save_pre_hooks_lock = threading.Lock() +_save_pre_hooks = [] + + +class HookRemoveHelper(object): + """ A HookRemoveHelper that can be used to remove hook. """ + + def __init__(self, hook): + self._hook = hook + + def remove(self): + _remove_save_pre_hook(self._hook) + + +def _register_save_pre_hook(hook): + """ + Register a save pre-hook for `paddle.jit.save`. + This hook will be executed before `save` function has been invoked. + + hook(layer, input_spec, configs) -> None + - layer (Layer|function): This argument is corresponding to `layer` in `paddle.jit.save`. + - input_spec (list or tuple[InputSpec|Tensor|Python built-in variable]): This argument is corresponding to `input_spec` in `paddle.jit.save`. + - configs (dict): This argument is corresponding to `configs` in `paddle.jit.save`. + + Args: + hook(function): a function registered as a save pre-hook + + Returns: + HookRemoveHelper: a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()`. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + + IMAGE_SIZE = 256 + CLASS_NUM = 10 + + class LinearNet(paddle.nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = paddle.nn.Linear(IMAGE_SIZE, CLASS_NUM) + + def forward(self, x): + return self._linear(x) + + saving_count = 0 + def save_pre_hook(layer, input_spec, configs): + global saving_count + saving_count += 1 + + remove_handler = paddle.jit.register_save_pre_hook(save_pre_hook) + + layer = LinearNet() + paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])]) + # saving_count == 1 + + remove_handler.remove() + paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])]) + # saving_count == 1 + """ + global _save_pre_hooks_lock + global _save_pre_hooks + _save_pre_hooks_lock.acquire() + if hook not in _save_pre_hooks: + _save_pre_hooks.append(hook) + _save_pre_hooks_lock.release() + return HookRemoveHelper(hook) + + +def _clear_save_pre_hooks(): + global _save_pre_hooks_lock + global _save_pre_hooks + _save_pre_hooks_lock.acquire() + _save_pre_hooks.clear() + _save_pre_hooks_lock.release() + + +def _remove_save_pre_hook(hook): + global _save_pre_hooks_lock + global _save_pre_hooks + _save_pre_hooks_lock.acquire() + if hook in _save_pre_hooks: + _save_pre_hooks.remove(hook) + _save_pre_hooks_lock.release() + + +@wrap_decorator +def _run_save_pre_hooks(func): + + def wrapper(layer, path, input_spec=None, **configs): + global _save_pre_hooks + for hook in _save_pre_hooks: + hook(layer, input_spec, configs) + func(layer, path, input_spec, **configs) + + return wrapper + + +def _save_property(filename: Text, property_vals: List[Tuple[Any, Text]]): + """class property serialization. + + Args: + filename (Text): *.meta + property_vals (List[Tuple): class property. + """ + + def set_property(meta, key, val): + if isinstance(val, float): + meta.set_float(key, val) + elif isinstance(val, int): + meta.set_int(key, val) + elif isinstance(val, str): + meta.set_string(key, val) + elif isinstance(val, (tuple, list)): + if isinstance(val[0], float): + meta.set_floats(key, val) + elif isinstance(val[0], int): + meta.set_ints(key, val) + elif isinstance(val[0], str): + meta.set_strings(key, val) + else: + raise ValueError(f"Note support val type: {type(val)}") + return + + with open(filename, 'wb') as f: + meta = paddle.framework.core.Property() + for item in property_vals: + val, key = item[0], item[1] + set_property(meta, key, val) + f.write(meta.serialize_to_string()) + + +@_run_save_pre_hooks +@switch_to_static_graph +def save(layer, path, input_spec=None, **configs): + """ + Saves input Layer or function as ``paddle.jit.TranslatedLayer`` + format model, which can be used for inference or fine-tuning after loading. + + It will save the translated program and all related persistable + variables of input Layer to given ``path`` . + + ``path`` is the prefix of saved objects, and the saved translated program file + suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` , + and here also saved some additional variable description information to a file, + its suffix is ``.pdiparams.info``, these additional information is used in fine-tuning. + + The saved model can be loaded by follow APIs: + - ``paddle.jit.load`` + - ``paddle.static.load_inference_model`` + - Other C++ inference APIs + + .. note:: + When using ``paddle.jit.save`` to save a function, parameters will not be saved. If you have to + save the parameter, please pass the Layer containing function and parameter to ``paddle.jit.save``. + + Args: + layer (Layer|function): The Layer or function to be saved. + path (str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``. + input_spec (list or tuple[InputSpec|Tensor|Python built-in variable], optional): Describes the input of the saved model's forward + method, which can be described by InputSpec or example Tensor. Moreover, we support to specify non-tensor type argument, + such as int, float, string, or list/dict of them.If None, all input variables of + the original Layer's forward method would be the inputs of the saved model. Default None. + **configs (dict, optional): Other save configuration options for compatibility. We do not + recommend using these configurations, they may be removed in the future. If not necessary, + DO NOT use them. Default None. + The following options are currently supported: + (1) output_spec (list[Tensor]): Selects the output targets of the saved model. + By default, all return variables of original Layer's forward method are kept as the + output of the saved model. If the provided ``output_spec`` list is not all output variables, + the saved model will be pruned according to the given ``output_spec`` list. + + Returns: + None + + Examples: + .. code-block:: python + + # example 1: save layer + import numpy as np + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + opt.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + # 1. train & save model. + + # create network + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters()) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + # train + train(layer, loader, loss_fn, adam) + + # save + path = "example_model/linear" + paddle.jit.save(layer, path) + + # example 2: save function + import paddle + from paddle.static import InputSpec + + + def save_function(): + @paddle.jit.to_static + def fun(inputs): + return paddle.tanh(inputs) + + path = 'test_jit_save_load_function_1/func' + inps = paddle.rand([3, 6]) + origin = fun(inps) + + paddle.jit.save(fun, path) + load_func = paddle.jit.load(path) + + load_result = load_func(inps) + print((load_result - origin).abs().max() < 1e-10) + + save_function() + """ + + # 1. input build & check + prog_translator = ProgramTranslator() + if not prog_translator.enable_to_static: + raise RuntimeError( + "The paddle.jit.save doesn't work when setting ProgramTranslator.enable to False." + ) + + if not (isinstance(layer, Layer) or inspect.isfunction(layer) + or isinstance(layer, StaticFunction)): + raise TypeError( + "The input of paddle.jit.save should be 'Layer' or 'Function', but received input type is %s." + % type(layer)) + elif inspect.isfunction(layer) or isinstance(layer, StaticFunction): + warnings.warn( + 'What you save is a function, and `jit.save` will generate the name of the model file according to `path` you specify. When loading these files with `jit.load`, you get a `TranslatedLayer` whose inference result is the same as the inference result of the function you saved.' + ) + + # NOTE(chenweihang): If the input layer be wrapped by DataParallel, + # the args and kwargs of forward method will can't be parsed by + # function_spec, so here we save DataParallel._layers instead + # DataParallel it self + # NOTE(chenweihang): using inner_layer, do not change input layer + if isinstance(layer, paddle.DataParallel): + inner_layer = layer._layers + else: + inner_layer = layer + + # path check + file_prefix = os.path.basename(path) + if file_prefix == "": + raise ValueError( + "The input path MUST be format of dirname/file_prefix " + "[dirname\\file_prefix in Windows system], but received " + "file_prefix is empty string.") + + dirname = os.path.dirname(path) + if dirname and not os.path.exists(dirname): + os.makedirs(dirname) + + # avoid change user given input_spec + inner_input_spec = None + if input_spec is not None: + if isinstance(layer, Layer): + for attr_func in dir(inner_layer): + static_func = getattr(inner_layer, attr_func, None) + if isinstance(static_func, + StaticFunction) and 'forward' != attr_func: + raise ValueError( + "If there are static functions other than 'forward' that need to be saved, the input 'input_spec' should be None, but received the type of 'input_spec' is %s." + % type(input_spec)) + + if not isinstance(input_spec, (list, tuple)): + raise TypeError( + "The input input_spec should be 'list', but received input_spec's type is %s." + % type(input_spec)) + inner_input_spec = [] + for var in flatten(input_spec): + if isinstance(var, paddle.static.InputSpec): + inner_input_spec.append(var) + elif isinstance(var, (core.VarBase, core.eager.Tensor, Variable)): + inner_input_spec.append( + paddle.static.InputSpec.from_tensor(var)) + else: + # NOTE(Aurelius84): Support non-Tensor type in `input_spec`. + inner_input_spec.append(var) + + # parse configs + configs = _parse_save_configs(configs) + # whether outermost layer has pre/post hook, if does, we need also save + # these operators in program. + with_hook = configs.with_hook + combine_params = configs.combine_params + if combine_params: + configs._program_only = True + + scope = core.Scope() + extra_var_info = dict() + if isinstance(layer, Layer): + functions = dir(inner_layer) + if inner_layer._forward_pre_hooks or inner_layer._forward_post_hooks: + with_hook = True + else: + # layer is function + functions = [ + layer, + ] + + combine_vars = {} + property_vals = [] # (value, key) + concrete_program = None + for attr_func in functions: + if isinstance(layer, Layer): + static_func = getattr(inner_layer, attr_func, None) + if isinstance(static_func, StaticFunction): + if static_func.is_property: + # property method to be exported + immediate_val = static_func() + property_vals.append( + (immediate_val, + layer.__class__.__name__ + '.' + attr_func)) + continue + + concrete_program = static_func.concrete_program_specify_input_spec( + inner_input_spec, with_hook=with_hook) + elif 'forward' == attr_func: + if configs.skip_forward: + # do not jit.save forward function + continue + + # transform in jit.save, if input_spec is incomplete, declarative will throw error + # inner_input_spec is list[InputSpec], it should be packed with same structure + # as original input_spec here. + if inner_input_spec: + inner_input_spec = pack_sequence_as(input_spec, + inner_input_spec) + static_forward = declarative(inner_layer.forward, + input_spec=inner_input_spec) + concrete_program = static_forward.concrete_program_specify_input_spec( + with_hook=with_hook) + # the input_spec has been used in declarative, which is equal to + # @declarative with input_spec and jit.save without input_spec, + # avoid needless warning + inner_input_spec = None + else: + continue + else: + # When layer is a function + if isinstance(attr_func, StaticFunction): + if attr_func.is_property: + # property method to be exported + immediate_val = attr_func() + property_vals.append((immediate_val, attr_func)) + continue + + concrete_program = attr_func.concrete_program_specify_input_spec( + inner_input_spec) + else: + if inner_input_spec: + inner_input_spec = pack_sequence_as(input_spec, + inner_input_spec) + static_function = declarative(attr_func, + input_spec=inner_input_spec) + concrete_program = static_function.concrete_program + + if static_function._class_instance is None: + warnings.warn( + '`jit.save` will only save the `Program`, not the parameters. If you have to save the parameters, please make sure that {} is a member function of `paddle.nn.Layer` and the saved parameters are in `state_dict`' + .format(layer)) + + # when save multi `StaticFunction`, all `StaticFunction` share params. + dygraph_state_dict = None + if isinstance(inner_layer, Layer): + dygraph_state_dict = inner_layer.to_static_state_dict() + elif isinstance(attr_func, StaticFunction): + if attr_func._class_instance: + dygraph_state_dict = attr_func._class_instance.to_static_state_dict( + ) + + if dygraph_state_dict: + # NOTE(chenweihang): we maintain the mapping of variable name to + # structured name, the buffer variable (non-persistable) + # saved to inference program may not need by dygraph Layer, + # we only record the state_dict variable's structured name + state_names_dict = dict() + state_var_dict = dict() + for structured_name, var in six.iteritems(dygraph_state_dict): + state_names_dict[var.name] = structured_name + state_var_dict[var.name] = var + + # 3. share parameters from Layer to scope & record var info + with dygraph.guard(): + for param_or_buffer in concrete_program.parameters: + # share to scope + if param_or_buffer.type == core.VarDesc.VarType.VOCAB: + scr_tensor = param_or_buffer.value().get_map_tensor() + tgt_var = scope.var(param_or_buffer.name) + tgt_var.set_vocab(scr_tensor) + else: + param_or_buffer_tensor = scope.var( + param_or_buffer.name).get_tensor() + #src_tensor = param_or_buffer.value().get_tensor() + src_tensor = state_var_dict[ + param_or_buffer.name].value().get_tensor() + param_or_buffer_tensor._share_data_with(src_tensor) + # record var info + if param_or_buffer.name not in extra_var_info: + extra_info_dict = dict() + if param_or_buffer.name in state_names_dict: + extra_info_dict['structured_name'] = state_names_dict[ + param_or_buffer.name] + extra_info_dict[ + 'stop_gradient'] = param_or_buffer.stop_gradient + if isinstance(param_or_buffer, (ParamBase, EagerParamBase)): + extra_info_dict['trainable'] = param_or_buffer.trainable + extra_var_info[param_or_buffer.name] = extra_info_dict + + # 4. build input & output of save_infernece_model + # NOTE(chenweihang): [ Get input variables name ] + # There are two cases, whether to prune the inputs or not + # - not prune inputs (recommend): + # - the len(input_spec) == len((concrete_program.inputs) - 1 + # - here can use concrete_program.inputs directly + # - prune inputs: + # - the input_spec length < len((concrete_program.inputs) - 1 + # - the input_spec's name should be in concrete_program.inputs + input_var_names = _get_input_var_names(concrete_program.inputs, + inner_input_spec) + + # NOTE(chenweihang): [ Get output variables ] + # the rule is like [ Get input variables name ]. For output var, + # we only support VarBase spec, and actually, we only need the + # var name of output, and we don't recommended to use output_spec + # print(concrete_program.main_program) + # print(concrete_program.outputs, configs.output_spec) + output_vars = _get_output_vars(concrete_program.outputs, + configs.output_spec, with_hook) + + # 5. save inference model + from paddle.fluid.io import save_inference_model + + # construct new save_inference_model arguments + model_path = dirname + # NOTE(chenweihang): because prefix contains model and params filename, + # so we don't support set model_filename & params_filename + if 'forward' == attr_func or not isinstance(layer, Layer): + model_filename = file_prefix + INFER_MODEL_SUFFIX + params_filename = file_prefix + INFER_PARAMS_SUFFIX + else: + model_filename = file_prefix + '.' + attr_func + INFER_MODEL_SUFFIX + params_filename = file_prefix + '.' + attr_func + INFER_PARAMS_SUFFIX + + with scope_guard(scope): + save_inference_model( + dirname=model_path, + feeded_var_names=input_var_names, + target_vars=output_vars, + executor=Executor(_current_expected_place()), + main_program=concrete_program.main_program.clone(), + model_filename=model_filename, + params_filename=params_filename, + export_for_deployment=configs._export_for_deployment, + program_only=configs._program_only, + clip_extra=configs.clip_extra) + + if combine_params: + clone_main_program = concrete_program.main_program.clone() + clone_main_program = clone_main_program._prune_with_input( + input_var_names, output_vars) + for block in clone_main_program.blocks: + combine_vars.update(block.vars) + + # save shared params + if combine_params: + # sort vars by name + combine_vars = sorted(combine_vars.items(), key=lambda item: item[0]) + ordered_vars = [] + for name, var in combine_vars: + ordered_vars.append(var) + + params_filename = file_prefix + INFER_PARAMS_SUFFIX + with scope_guard(scope): + paddle.static.save_vars(Executor(_current_expected_place()), + dirname=model_path, + vars=list( + filter(paddle.fluid.io.is_persistable, + ordered_vars)), + filename=params_filename) + # save property + property_save_path = os.path.join(os.path.normpath(model_path), + file_prefix + INFER_PROPERTY_SUFFIX) + _save_property(property_save_path, property_vals) + + # NOTE(chenweihang): [ Save extra variable info ] + # save_inference_model will lose some important variable information, including: + # - Variable name and correspondence (when saved variables as one file) + # - Variable.stop_gradient information + # - Which persistent variable are parameter and which are not + # - Parameter.trainable information + # + # The lost information cannot be recovered when it is loaded again, + # so if we want to perform fine-tune after loading, we may need to + # configure redundant information to proceed. + # + # Due to compatibility issues, we cannot change the original storage structure, + # but we can save these information in `jit.save` without changing the original + # storage to improve user experience. So we save extra information into + # file `***.pdiparams.info` + + # "layer" can only be Layer or function or StaticFunction. + contain_parameter = False + if concrete_program is not None: + for var in concrete_program.main_program.list_vars(): + contain_parameter |= isinstance(var, Parameter) + + if (isinstance(layer, Layer) or contain_parameter) and extra_var_info: + with scope_guard(scope): + extra_var_info_path = path + INFER_PARAMS_INFO_SUFFIX + with open(extra_var_info_path, 'wb') as f: + pickle.dump(extra_var_info, f, protocol=2) + + +@dygraph_only +def load(path, **configs): + """ + :api_attr: imperative + + Load model saved by ``paddle.jit.save`` or ``paddle.static.save_inference_model`` or + paddle 1.x API ``paddle.fluid.io.save_inference_model`` as ``paddle.jit.TranslatedLayer``, + then performing inference or fine-tune training. + + .. note:: + If you load model saved by ``paddle.static.save_inference_model`` , + there will be the following limitations when using it in fine-tuning: + 1. Imperative mode do not support LoDTensor. All original model's feed targets or parametars that depend on LoD are temporarily unavailable. + 2. All saved model's feed targets need to be passed into TranslatedLayer's forward function. + 3. The variable's ``stop_gradient`` information is lost and can not be recovered. + 4. The parameter's ``trainable`` information is lost and can not be recovered. + + Args: + path (str): The path prefix to load model. The format is ``dirname/file_prefix`` or ``file_prefix`` . + **configs (dict, optional): Other load configuration options for compatibility. We do not + recommend using these configurations, they may be removed in the future. If not necessary, + DO NOT use them. Default None. + The following options are currently supported: + (1) model_filename (str): The inference model file name of the paddle 1.x + ``save_inference_model`` save format. Default file name is :code:`__model__` . + (2) params_filename (str): The persistable variables file name of the paddle 1.x + ``save_inference_model`` save format. No default file name, save variables separately + by default. + + + Returns: + TranslatedLayer: A Layer object can run saved translated model. + + Examples: + 1. Load model saved by ``paddle.jit.save`` then performing inference and fine-tune training. + + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + opt.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + # 1. train & save model. + + # create network + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters()) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + # train + train(layer, loader, loss_fn, adam) + + # save + path = "example_model/linear" + paddle.jit.save(layer, path) + + # 2. load model + + # load + loaded_layer = paddle.jit.load(path) + + # inference + loaded_layer.eval() + x = paddle.randn([1, IMAGE_SIZE], 'float32') + pred = loaded_layer(x) + + # fine-tune + loaded_layer.train() + adam = opt.Adam(learning_rate=0.001, parameters=loaded_layer.parameters()) + train(loaded_layer, loader, loss_fn, adam) + + + 2. Load model saved by ``paddle.fluid.io.save_inference_model`` then performing and fine-tune training. + + .. code-block:: python + + import numpy as np + import paddle + import paddle.static as static + import paddle.nn as nn + import paddle.optimizer as opt + import paddle.nn.functional as F + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + paddle.enable_static() + + image = static.data(name='image', shape=[None, 784], dtype='float32') + label = static.data(name='label', shape=[None, 1], dtype='int64') + pred = static.nn.fc(x=image, size=10, activation='softmax') + loss = F.cross_entropy(input=pred, label=label) + avg_loss = paddle.mean(loss) + + optimizer = paddle.optimizer.SGD(learning_rate=0.001) + optimizer.minimize(avg_loss) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + feed_list=[image, label], + places=place, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + return_list=False, + num_workers=2) + + # 1. train and save inference model + for data in loader(): + exe.run( + static.default_main_program(), + feed=data, + fetch_list=[avg_loss]) + + model_path = "fc.example.model" + paddle.fluid.io.save_inference_model( + model_path, ["image"], [pred], exe) + + # 2. load model + + # enable dygraph mode + paddle.disable_static(place) + + # load + fc = paddle.jit.load(model_path) + + # inference + fc.eval() + x = paddle.randn([1, IMAGE_SIZE], 'float32') + pred = fc(x) + + # fine-tune + fc.train() + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=fc.parameters()) + loader = paddle.io.DataLoader(dataset, + places=place, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = fc(image) + loss = loss_fn(out, label) + loss.backward() + adam.step() + adam.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + """ + # 1. construct correct config + config = _parse_load_config(configs) + model_path, config = _build_load_path_and_config(path, config) + + return TranslatedLayer._construct(model_path, config) + + +@dygraph_only +def _trace(layer, + inputs, + feed_prefix='feed_', + fetch_prefix='fetch_', + tmp_prefix='t_'): + assert isinstance(layer, Layer) + + if not isinstance(inputs, (list, tuple)): + inputs = [inputs] + + tracer = _dygraph_tracer()._get_program_desc_tracer() + + var_list = extract_vars(inputs) + + with program_desc_tracing_guard(True): + original_outputs = layer(*inputs) + if not isinstance(original_outputs, (list, tuple)): + outputs = [original_outputs] + else: + outputs = original_outputs + out_vars = extract_vars(outputs, err_tag='outputs') + + program_desc, feed_names, fetch_names, parameters = tracer.create_program_desc( + var_list, feed_prefix, out_vars, fetch_prefix, tmp_prefix) + tracer.reset() + + with _dygraph_guard(None): + program = create_program_from_desc(program_desc) + + return original_outputs, program, feed_names, fetch_names, parameters + + +class TracedLayer(object): + """ + :api_attr: imperative + + TracedLayer is used to convert a forward dygraph model to a static + graph model. This is mainly used to save the dygraph model for online + inference using C++. Besides, users can also do inference in Python + using the converted static graph model, which usually has better + performance than the original dygraph model. + + TracedLayer would run the static graph model using :code:`Executor` + and :code:`CompiledProgram` . The static graph model would share + parameters with the dygraph model. + + All TracedLayer objects should not be created by constructor and should + be created by static method :code:`TracedLayer.trace(layer, inputs)` . + + The TracedLayer can only be used to convert the data-independent dygraph + model into the static graph model, which means the dygraph model should + be independent with the tensor data and shape. + """ + + def __init__(self, program, parameters, feed_names, fetch_names): + self._program = program + self._feed_names = feed_names + self._fetch_names = fetch_names + self._params = parameters + + self._place = _current_expected_place() + + self._scope = core.Scope() + for p in parameters: + src_tensor = p.value().get_tensor() + dst_tensor = self._scope.var(p.name).get_tensor() + dst_tensor._share_data_with(src_tensor) + + self._exe = Executor(self._place) + self._compiled_program = None + self._build_strategy = None + self._exec_strategy = None + + @property + def program(self): + return self._program + + def _switch(self, is_test=True): + for block_id in range(self._program.num_blocks): + block = self._program.block(block_id) + for op in block.ops: + if op.has_attr("is_test"): + op._set_attr("is_test", is_test) + + @staticmethod + @dygraph_only + def trace(layer, inputs): + """ + This method is the only allowed method to create TracedLayer object. + It would call the :code:`layer(*inputs)` method to run the dygraph + model and convert it into a static graph model. + + Args: + layer (paddle.nn.Layer): the layer object to be traced. + inputs (list(Tensor)|tuple(Tensor)|Tensor): the input tensors of + the layer object. + + Returns: + tuple: A tuple of 2 items, whose the first item is the output of + :code:`layer(*inputs)` , and the second item is the created + TracedLayer object. + + Examples: + .. code-block:: python: + + import paddle + + class ExampleLayer(paddle.nn.Layer): + def __init__(self): + super(ExampleLayer, self).__init__() + self._fc = paddle.nn.Linear(3, 10) + + def forward(self, input): + return self._fc(input) + + + layer = ExampleLayer() + in_var = paddle.uniform(shape=[2, 3], dtype='float32') + out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var]) + + # run the static graph model using Executor inside + out_static_graph = static_layer([in_var]) + + print(len(out_static_graph)) # 1 + print(out_static_graph[0].shape) # (2, 10) + + # save the static graph model for inference + static_layer.save_inference_model(dirname='./saved_infer_model') + + """ + assert isinstance( + layer, Layer + ), "The type of 'layer' in fluid.dygraph.jit.TracedLayer.trace must be fluid.dygraph.Layer, but received {}.".format( + type(layer)) + outs, prog, feed, fetch, parameters = _trace(layer, inputs) + traced = TracedLayer(prog, parameters, feed, fetch) + return outs, traced + + def set_strategy(self, build_strategy=None, exec_strategy=None): + """ + Set the strategies when running static graph model. + + Args: + build_strategy (BuildStrategy, optional): build strategy of + :code:`CompiledProgram` inside TracedLayer. Default None. + exec_strategy (ExecutionStrategy, optional): execution strategy of + :code:`CompiledProgram` inside TracedLayer. Default None. + + Returns: + None + + Examples: + .. code-block:: python: + + import paddle + + class ExampleLayer(paddle.nn.Layer): + def __init__(self): + super(ExampleLayer, self).__init__() + self._fc = paddle.nn.Linear(3, 10) + + def forward(self, input): + return self._fc(input) + + layer = ExampleLayer() + in_var = paddle.uniform(shape=[2, 3], dtype='float32') + + out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var]) + + build_strategy = paddle.static.BuildStrategy() + build_strategy.enable_inplace = True + + exec_strategy = paddle.static.ExecutionStrategy() + exec_strategy.num_threads = 2 + + static_layer.set_strategy(build_strategy=build_strategy, exec_strategy=exec_strategy) + out_static_graph = static_layer([in_var]) + + """ + assert self._compiled_program is None, "Cannot set strategy after run" + assert isinstance( + build_strategy, (type(None), BuildStrategy) + ), "The type of 'build_strategy' in fluid.dygraph.jit.TracedLayer.set_strategy must be fluid.BuildStrategy, but received {}.".format( + type(build_strategy)) + assert isinstance( + exec_strategy, (type(None), ExecutionStrategy) + ), "The type of 'exec_strategy' in fluid.dygraph.jit.TracedLayer.set_strategy must be fluid.ExecutionStrategy, but received {}.".format( + type(exec_strategy)) + self._build_strategy = build_strategy + self._exec_strategy = exec_strategy + + @switch_to_static_graph + def _compile(self): + self._compiled_program = CompiledProgram( + self._program).with_data_parallel( + build_strategy=self._build_strategy, + exec_strategy=self._exec_strategy, + places=self._place) + + def _build_feed(self, inputs): + assert isinstance(inputs, (list, tuple)), \ + "Inputs should be a list or tuple of variables" + assert len(inputs) == len(self._feed_names) + feed_dict = {} + if _non_static_mode(): + for x, name in zip(inputs, self._feed_names): + feed_dict[name] = x.value().get_tensor() + else: + for x, name in zip(inputs, self._feed_names): + feed_dict[name] = x + + return feed_dict + + @switch_to_static_graph + def _run(self, feed): + return self._exe.run(self._compiled_program, + feed=feed, + fetch_list=self._fetch_names) + + def __call__(self, inputs): + with scope_guard(self._scope): + if self._compiled_program is None: + self._compile() + + return self._run(self._build_feed(inputs)) + + @switch_to_static_graph + def save_inference_model(self, path, feed=None, fetch=None, **kwargs): + """ + Save the TracedLayer to a model for inference. The saved + inference model can be loaded by C++ inference APIs. + + ``path`` is the prefix of saved objects, and the saved translated program file + suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` . + + Args: + path(str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``. + feed (list[int], optional): the input variable indices of the saved + inference model. If None, all input variables of the + TracedLayer object would be the inputs of the saved inference + model. Default None. + fetch (list[int], optional): the output variable indices of the + saved inference model. If None, all output variables of the + TracedLayer object would be the outputs of the saved inference + model. Default None. + kwargs: Supported keys including 'clip_extra'.set to True if you want to clip extra information for every operator. + + Returns: + None + + Examples: + .. code-block:: python: + + import numpy as np + import paddle + + class ExampleLayer(paddle.nn.Layer): + def __init__(self): + super(ExampleLayer, self).__init__() + self._fc = paddle.nn.Linear(3, 10) + + def forward(self, input): + return self._fc(input) + + save_dirname = './saved_infer_model' + in_np = np.random.random([2, 3]).astype('float32') + in_var = paddle.to_tensor(in_np) + layer = ExampleLayer() + + out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var]) + static_layer.save_inference_model(save_dirname, feed=[0], fetch=[0]) + + paddle.enable_static() + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + program, feed_vars, fetch_vars = paddle.static.load_inference_model(save_dirname, + exe) + + fetch, = exe.run(program, feed={feed_vars[0]: in_np}, fetch_list=fetch_vars) + print(fetch.shape) # (2, 10) + """ + check_type(path, "path", str, + "fluid.dygraph.jit.TracedLayer.save_inference_model") + check_type(feed, "feed", (type(None), list), + "fluid.dygraph.jit.TracedLayer.save_inference_model") + if isinstance(feed, list): + for f in feed: + check_type( + f, "each element of feed", int, + "fluid.dygraph.jit.TracedLayer.save_inference_model") + check_type(fetch, "fetch", (type(None), list), + "fluid.dygraph.jit.TracedLayer.save_inference_model") + if isinstance(fetch, list): + for f in fetch: + check_type( + f, "each element of fetch", int, + "fluid.dygraph.jit.TracedLayer.save_inference_model") + clip_extra = kwargs.get('clip_extra', True) + # path check + file_prefix = os.path.basename(path) + if file_prefix == "": + raise ValueError( + "The input path MUST be format of dirname/file_prefix " + "[dirname\\file_prefix in Windows system], but received " + "file_prefix is empty string.") + + dirname = os.path.dirname(path) + if dirname and not os.path.exists(dirname): + os.makedirs(dirname) + + from paddle.fluid.io import save_inference_model + + def get_feed_fetch(all_vars, partial_vars): + if partial_vars is None: + return all_vars + + return [all_vars[idx] for idx in partial_vars] + + with scope_guard(self._scope): + feeded_var_names = get_feed_fetch(self._feed_names, feed) + target_var_names = get_feed_fetch(self._fetch_names, fetch) + target_vars = [] + for name in target_var_names: + target_var = self._program.global_block().vars.get(name, None) + assert target_var is not None, "{} cannot be found".format(name) + target_vars.append(target_var) + + model_filename = file_prefix + INFER_MODEL_SUFFIX + params_filename = file_prefix + INFER_PARAMS_SUFFIX + + save_inference_model(dirname=dirname, + feeded_var_names=feeded_var_names, + target_vars=target_vars, + executor=self._exe, + main_program=self._program.clone(), + model_filename=model_filename, + params_filename=params_filename, + clip_extra=clip_extra) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_hooks.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..68c3d463e5deb911435df885106009e3510d0e09 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_hooks.py @@ -0,0 +1,74 @@ +# Copyright (c) 2021 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. + +import six +import warnings + +from paddle.fluid.framework import default_main_program, _non_static_mode + + +class LayerOpsRecoder: + """ + Record generated operators information in nn.Layer. + """ + + def __init__(self, start=-1, end=-1, ops=None, is_valid=False, hooks=None): + self.start = start + self.end = end + self.ops = ops + self.is_valid = is_valid + self.hooks = hooks + + +def record_program_ops_pre_hook(layer, inputs): + """ + A pre-hook to mark op numbers before enter layer.forward. + """ + if not _non_static_mode(): + if layer._op_recorder.start < 0: + layer._op_recorder.start = len( + default_main_program().current_block().ops) + layer._op_recorder.is_valid = True + else: + layer._op_recorder.is_valid = False + warnings.warn( + "{} has recorded the op information before. Please check whether you call this layer twice." + .format(layer._full_name)) + + return None + + +def set_op_customized_attrs_post_hook(layer, inputs, outputs): + """ + A post-hook to append customized attributes into all operators generated in current layer. + """ + if not _non_static_mode() and layer._op_recorder.is_valid: + + start = layer._op_recorder.start + end = len(default_main_program().current_block().ops) + assert (start >= 0 and end >= start) + ops = default_main_program().current_block().ops[start:end] + + layer._op_recorder.end = end + layer._op_recorder.ops = ops + + for op in ops: + for attr_name, val in six.iteritems(layer._customized_attrs): + op._set_attr(attr_name, val) + + # remove pre-hook and post-hook + for hook_helper in layer._op_recorder.hooks: + hook_helper.remove() + + return None diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_object_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_object_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..394df321811d83c86e088bf89fbeac7722ba0fcd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layer_object_helper.py @@ -0,0 +1,192 @@ +# 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. + +from __future__ import print_function + +import copy +import six +from ..framework import Parameter, _non_static_mode, _global_flags +from ..param_attr import ParamAttr +from .. import core +from six.moves import zip +from ..layer_helper_base import LayerHelperBase +from ..dygraph_utils import _append_activation_in_dygraph + + +class LayerObjectHelper(LayerHelperBase): + + def __init__(self, name): + super(LayerObjectHelper, self).__init__(name, layer_type=name) + + def append_op(self, + type=None, + inputs=None, + outputs=None, + attrs=None, + stop_gradient=None): + """append an operator for this layer object. + + Args: + type: operator type + inputs: input variable of the operator + dtype: data type of this parameter + is_bias: if this is a bias parameter + default_initializer: set the default initializer for this parameter + + Returns created parameter Variable. + """ + return self.main_program.current_block().append_op( + type=type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=stop_gradient) + + def _multiple_input(self, inputs_in): + inputs = inputs_in + ret = [] + if isinstance(inputs, (list, tuple)): + for inp in inputs: + ret.append(self.to_variable(inp)) + else: + ret.append(self.to_variable(inputs)) + return ret + + # TODO: make it public when we need it + def _input(self, inputs_in): + inputs = self._multiple_input(inputs_in) + if len(inputs) != 1: + raise "{0} layer only takes one input in".format(self.layer_type) + return inputs[0] + + def _multiple_param_attr(self, length, param_attr_in=None): + param_attr = param_attr_in + if isinstance(param_attr, ParamAttr): + param_attr = [param_attr] + + if len(param_attr) != 1 and len(param_attr) != length: + raise ValueError("parameter number mismatch in {}".format( + self.name)) + elif len(param_attr) == 1 and length != 1: + tmp = [None] * length + for i in six.moves.range(length): + tmp[i] = copy.deepcopy(param_attr[0]) + param_attr = tmp + return param_attr + + def iter_inputs_and_params(self, inputs_in, param_attr_in=None): + """Access all inputs and params one by one + + Args: + inputs_in: inputs to be iter + param_attr_in: param_attr to be iter + + Returns input, param_attr + """ + param_attr_in = ParamAttr._to_attr(param_attr_in) + if isinstance(param_attr_in, bool): + raise ValueError('Param_attr should not be False in {}'.format( + self.name)) + inputs = inputs_in if (inputs_in is not None) else [] + inputs = self._multiple_input(inputs) + param_attrs = self._multiple_param_attr(len(inputs), param_attr_in) + for ipt, param_attr in zip(inputs, param_attrs): + yield ipt, param_attr + + def input_dtype(self, inputs_in): + """Get input data type + + Args: + inputs_in: inputs wanted know the data type + + Returns dtype of the input + """ + inputs_in = inputs_in if (inputs_in is not None) else [] + inputs = self._multiple_input(inputs_in) + dtype = None + for each in inputs: + if dtype is None: + dtype = each.dtype + elif dtype != each.dtype: + raise ValueError("Data Type mismatch: %d to %d in %s" % + (dtype, each.dtype, self.name)) + return dtype + + def get_parameter(self, name): + """Get parameter specifically + + Args: + name: parameter's name + + Returns target parameter + """ + param = self.main_program.global_block().var(name) + if not isinstance(param, Parameter): + raise ValueError("no Parameter name %s found in %s" % + (name, self.name)) + return param + + # TODO: this should not be called anymore after all activation func move to Layers + def append_activation(self, input_var, act=None, use_cudnn=None): + """Append activation + + Args: + input_var: the input variable. The len(input_var.shape) is + larger or equal than 2. + act: activation type + use_cudnn: if use cudnn + + Return the Variable of after append activation + """ + act = act + if act is None: + return input_var + if isinstance(act, six.string_types): + act = {'type': act} + else: + raise TypeError( + str(act) + " should be unicode or str in %s ", self.name) + + if (use_cudnn is not None) and use_cudnn: + act['use_cudnn'] = use_cudnn + use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + if (use_mkldnn is not None) and use_mkldnn: + act['use_mkldnn'] = use_mkldnn + act_type = act.pop('type') + if _non_static_mode(): + res = _append_activation_in_dygraph(input_var, act_type, use_cudnn, + use_mkldnn) + return res + else: + tmp = self.create_variable_for_type_inference(dtype=input_var.dtype) + self.append_op(type=act_type, + inputs={"X": [input_var]}, + outputs={"Out": [tmp]}, + attrs=act) + return tmp + + def is_instance(self, param, cls): + """Check if the input parameter is instance of input class + + Args: + param: parameter to be check + cls: class of the parameter + + Return result of the check (True or False) + """ + param = param + if not isinstance(param, cls): + raise TypeError( + "The input {0} parameter of method {1} must be {2}, in layer {3}", + param, self.layer_type, cls.__name__, self.name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..d21db965a54d0fcfb01c75e3ff58d0acb4d0d62c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/layers.py @@ -0,0 +1,1902 @@ +# Copyright (c) 2018 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. + +import collections +import contextlib +import sys +import numpy as np +import six +import re +import copy +import weakref +import warnings +from copy import deepcopy +import inspect + +import paddle +import paddle.profiler as profiler +from paddle.profiler.utils import in_profiler_mode + +from . import parallel_helper +from .. import unique_name +from paddle.fluid import core +from .layer_object_helper import LayerObjectHelper +from .layer_hooks import ( + record_program_ops_pre_hook, + set_op_customized_attrs_post_hook, + LayerOpsRecoder, +) +from .base import ( + program_desc_tracing_guard, + param_guard, + in_declarative_mode, + _convert_into_variable, +) +from paddle.fluid import framework +from ..param_attr import ParamAttr +from paddle.fluid.executor import Executor, global_scope +from paddle.fluid.framework import ( + _non_static_mode, + convert_np_dtype_to_dtype_, + in_dygraph_mode, +) +from paddle.fluid.framework import Program, program_guard +from paddle.fluid.framework import _current_expected_place as _get_device +from paddle.fluid.core import VarDesc +from paddle.fluid.dygraph import no_grad +import paddle.utils.deprecated as deprecated + +__all__ = ['Layer'] + +_first_cap_re = re.compile('(.)([A-Z][a-z]+)') +_all_cap_re = re.compile('([a-z])([A-Z])') + + +def _convert_camel_to_snake(name): + s1 = _first_cap_re.sub(r'\1_\2', name) + return _all_cap_re.sub(r'\1_\2', s1).lower() + + +def _addindent(string, indent): + s1 = string.split('\n') + if len(s1) == 1: + return string + s2 = [] + for idx, line in enumerate(s1): + if idx > 0: + s2.append(str((indent * ' ') + line)) + return s1[0] + '\n' + '\n'.join(s2) + + +class HookRemoveHelper(object): + """A HookRemoveHelper that can be used to remove hook.""" + + next_hook_id = 0 + + def __init__(self, hooks): + self._hooks_ref = weakref.ref(hooks) + self._hook_id = HookRemoveHelper.next_hook_id + HookRemoveHelper.next_hook_id += 1 + + def remove(self): + hooks = self._hooks_ref() + if hooks is not None and self._hook_id in hooks: + del hooks[self._hook_id] + + +class Layer(object): + """ + Dynamic graph Layer based on OOD, includes the parameters of the layer, the structure of the forward graph and so on. + + Parameters: + name_scope (str, optional): prefix name used by the layer to name parameters. + If prefix is "my_layer", parameter name in MyLayer + can be "my_layer_0.w_n", where "w" is the parameter + base name and "n" is an unique suffix auto-generated. + If None, prefix name will be snake cased class name. Default: None. + dtype(str, optional): data type of this parameter. + If set str, it can be "bool", "float16", "float32", "float64", + "int8", "int16", "int32", "int64", "uint8" or "uint16". + Default: "float32" + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + self._dropout = paddle.nn.Dropout(p=0.5) + def forward(self, input): + temp = self._linear(input) + temp = self._dropout(temp) + return temp + x = paddle.randn([10, 1], 'float32') + mylayer = MyLayer() + mylayer.eval() # set mylayer._dropout to eval mode + out = mylayer(x) + mylayer.train() # set mylayer._dropout to train mode + out = mylayer(x) + """ + + def __init__(self, name_scope=None, dtype="float32"): + self.training = True + if name_scope is None: + name_scope = _convert_camel_to_snake(self.__class__.__name__) + self._full_name = unique_name.generate(name_scope) + self._helper = LayerObjectHelper(self._full_name) + self._built = False + self._dtype = dtype + self._init_in_dynamic_mode = framework._non_static_mode() + + self._parameters = collections.OrderedDict() + # Buffers the variable (not parameter) created in layer + self._buffers = collections.OrderedDict() + self._non_persistable_buffer_names_set = set() + self._sub_layers = collections.OrderedDict() + self._loaddict_holder = collections.OrderedDict() + + # Record generated op_descs in this layer + self._op_recorder = LayerOpsRecoder(ops=[], hooks=[]) + self._customized_attrs = {} + + self._forward_pre_hooks = collections.OrderedDict() + self._forward_post_hooks = collections.OrderedDict() + + self._casted_by_pure_fp16 = False + + self._state_dict_hooks = collections.OrderedDict() + # Records orignal functions after @to_static to support to rollback + self._original_funcs = collections.OrderedDict() + + def train(self): + """ + + Sets this Layer and all its sublayers to training mode. + This only effects certain modules like `Dropout` and `BatchNorm`. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + self._dropout = paddle.nn.Dropout(p=0.5) + + def forward(self, input): + temp = self._linear(input) + temp = self._dropout(temp) + return temp + + x = paddle.randn([10, 1], 'float32') + mylayer = MyLayer() + mylayer.eval() # set mylayer._dropout to eval mode + out = mylayer(x) + mylayer.train() # set mylayer._dropout to train mode + out = mylayer(x) + + """ + # global setting in dygraph + # NOTE(chenweihang): nn.Layer also can be used in static mode, + # but _dygraph_tracer() can not be called in static mode + if _non_static_mode(): + framework._dygraph_tracer().train_mode() + # Layer-level setting + self.training = True + for layer in self.sublayers(): + layer.training = True + + def eval(self): + """ + Sets this Layer and all its sublayers to evaluation mode. + This only effects certain modules like `Dropout` and `BatchNorm`. + + Returns: + None + + Example:: + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + self._dropout = paddle.nn.Dropout(p=0.5) + + def forward(self, input): + temp = self._linear(input) + temp = self._dropout(temp) + return temp + + x = paddle.randn([10, 1], 'float32') + mylayer = MyLayer() + mylayer.eval() # set mylayer._dropout to eval mode + out = mylayer(x) + print(out) + + """ + # global setting in dygraph + # NOTE(chenweihang): nn.Layer also can be used in static mode, + # but _dygraph_tracer() can not be called in static mode + if _non_static_mode(): + framework._dygraph_tracer().eval_mode() + # Layer-level setting + self.training = False + for layer in self.sublayers(): + layer.training = False + + def apply(self, fn): + """ + + Applies ``fn`` recursively to every sublayer (as returned by ``.sublayers()``) + as well as self. Typical use includes initializing the parameters of a model. + + Parameters: + fn (function): a function to be applied to each sublayer + + Returns: + Layer, self + + Example:: + .. code-block:: python + + import paddle + import paddle.nn as nn + + net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) + + def init_weights(layer): + if type(layer) == nn.Linear: + print('before init weight:', layer.weight.numpy()) + new_weight = paddle.full(shape=layer.weight.shape, dtype=layer.weight.dtype, fill_value=0.9) + layer.weight.set_value(new_weight) + print('after init weight:', layer.weight.numpy()) + + net.apply(init_weights) + + print(net.state_dict()) + + """ + for layer in self.children(): + layer.apply(fn) + + fn(self) + + return self + + def full_name(self): + """ + + Full name for this layer, composed by name_scope + "/" + MyLayer.__class__.__name__ + + Returns: + str, full name of this layer. + + Example:: + .. code-block:: python + + import paddle + + class LinearNet(paddle.nn.Layer): + def __init__(self): + super(LinearNet, self).__init__(name_scope = "demo_linear_net") + self._linear = paddle.nn.Linear(1, 1) + + def forward(self, x): + return self._linear(x) + + linear_net = LinearNet() + print(linear_net.full_name()) # demo_linear_net_0 + + """ + return self._full_name + + def register_forward_post_hook(self, hook): + """ + + Register a forward post-hook for Layer. The hook will be called after `forward` function has been computed. + + It should have the following form, `input` and `output` of the `hook` is `input` and `output` of the `Layer` respectively. + User can use forward post-hook to change the output of the Layer or perform information statistics tasks on the Layer. + + hook(Layer, input, output) -> None or modified output + + Parameters: + hook(function): a function registered as a forward post-hook + + Returns: + HookRemoveHelper, a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()` . + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # the forward_post_hook change the output of the layer: output = output * 2 + def forward_post_hook(layer, input, output): + # user can use layer, input and output for information statistis tasks + + # change the output + return output * 2 + + linear = paddle.nn.Linear(13, 5) + + # register the hook + forward_post_hook_handle = linear.register_forward_post_hook(forward_post_hook) + + value1 = np.arange(26).reshape(2, 13).astype("float32") + in1 = paddle.to_tensor(value1) + + out0 = linear(in1) + + # remove the hook + forward_post_hook_handle.remove() + + out1 = linear(in1) + + # hook change the linear's output to output * 2, so out0 is equal to out1 * 2. + assert (out0.numpy() == (out1.numpy()) * 2).any() + + """ + hook_remove_helper = HookRemoveHelper(self._forward_post_hooks) + self._forward_post_hooks[hook_remove_helper._hook_id] = hook + return hook_remove_helper + + def register_forward_pre_hook(self, hook): + """ + + Register a forward pre-hook for Layer. The hook will be called before `forward` function has been computed. + + It should have the following form, `input` of the `hook` is `input` of the `Layer`, + hook can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if + a single value is returned(unless that value is already a tuple). + User can use forward pre-hook to change the input of the Layer or perform information statistics tasks on the Layer. + + hook(Layer, input) -> None or modified input + + Parameters: + hook(function): a function registered as a forward pre-hook + + Returns: + HookRemoveHelper, a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()` . + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # the forward_pre_hook change the input of the layer: input = input * 2 + def forward_pre_hook(layer, input): + # user can use layer and input for information statistis tasks + + # change the input + input_return = (input[0] * 2) + return input_return + + linear = paddle.nn.Linear(13, 5) + + # register the hook + forward_pre_hook_handle = linear.register_forward_pre_hook(forward_pre_hook) + + value0 = np.arange(26).reshape(2, 13).astype("float32") + in0 = paddle.to_tensor(value0) + out0 = linear(in0) + + # remove the hook + forward_pre_hook_handle.remove() + + value1 = value0 * 2 + in1 = paddle.to_tensor(value1) + out1 = linear(in1) + + # hook change the linear's input to input * 2, so out0 is equal to out1. + assert (out0.numpy() == out1.numpy()).any() + """ + hook_remove_helper = HookRemoveHelper(self._forward_pre_hooks) + self._forward_pre_hooks[hook_remove_helper._hook_id] = hook + return hook_remove_helper + + def create_parameter( + self, + shape, + attr=None, + dtype=None, + is_bias=False, + default_initializer=None, + ): + """Create parameters for this layer. + + Parameters: + shape(list): Shape of the parameter. + attr(ParamAttr, optional): Parameter attribute of weight. Please refer to :ref:`api_paddle_ParamAttr`. Default: None. + dtype(str, optional): Data type of this parameter. + If set str, it can be "bool", "float16", "float32", "float64", + "int8", "int16", "int32", "int64", "uint8" or "uint16". Default: "float32". + is_bias(bool, optional): if this is a bias parameter. Default: False. + default_initializer(Initializer, optional): the default initializer for this parameter. + If set None, default initializer will be set to paddle.nn.initializer.Xavier and paddle.nn.initializer.Constant + for non-bias and bias parameter, respectively. Default: None. + + Returns: + :Tensor, created parameter. + + Examples: + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + w_tmp = self.create_parameter([1,1]) + self.add_parameter("w_tmp", w_tmp) + + def forward(self, input): + return self._linear(input) + + mylayer = MyLayer() + for name, param in mylayer.named_parameters(): + print(name, param) # will print w_tmp,_linear.weight,_linear.bias + + """ + temp_attr = copy.deepcopy(attr) + if isinstance(temp_attr, six.string_types) and temp_attr == "": + temp_attr = None + return self._helper.create_parameter( + temp_attr, shape, dtype, is_bias, default_initializer + ) + + @deprecated( + since="2.0.0", + update_to="paddle.nn.Layer.create_tensor", + reason="New api in create_tensor, easier to use.", + ) + def create_variable(self, name=None, persistable=None, dtype=None): + """ + + Create Tensor for this layer. + + Parameters: + name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None + + persistable(bool, optional): if set this tensor persistable. Default: False + + dtype(str, optional): data type of this parameter. If set str, it can be "bool", "float16", "float32", "float64","int8", "int16", "int32", "int64", "uint8" or "uint16". If set None, it will be "float32". Default: None + + Returns: + Tensor, created Tensor. + + Examples: + .. code-block:: python + + import paddle + + class MyLinear(paddle.nn.Layer): + def __init__(self, + in_features, + out_features): + super(MyLinear, self).__init__() + self.linear = paddle.nn.Linear( 10, 10) + + self.back_var = self.create_variable(name = "linear_tmp_0", dtype=self._dtype) + + def forward(self, input): + out = self.linear(input) + paddle.assign( out, self.back_var) + + return out + + """ + if name is not None: + var_name = ".".join([self._full_name, name]) + else: + var_name = unique_name.generate( + ".".join([self._full_name, "_generated_var"]) + ) + + return self._helper.main_program.current_block().create_var( + name=var_name, + persistable=persistable, + dtype=dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + ) + + # TODO: Add more parameter list when we need them + def create_tensor(self, name=None, persistable=None, dtype=None): + """ + + Create Tensor for this layer. + + Parameters: + name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None + persistable(bool, optional): if set this tensor persistable. Default: False + dtype(str, optional): data type of this parameter. + If set str, it can be "bool", "float16", "float32", "float64", + "int8", "int16", "int32", "int64", "uint8" or "uint16". + If set None, it will be "float32". Default: None + + Returns: + Tensor, created Tensor. + + Examples: + .. code-block:: python + + import paddle + + class MyLinear(paddle.nn.Layer): + def __init__(self, + in_features, + out_features): + super(MyLinear, self).__init__() + self.linear = paddle.nn.Linear( 10, 10) + + self.back_var = self.create_tensor(name = "linear_tmp_0", dtype=self._dtype) + + def forward(self, input): + out = self.linear(input) + paddle.assign( out, self.back_var) + + return out + + """ + if name is not None: + var_name = ".".join([self._full_name, name]) + else: + var_name = unique_name.generate( + ".".join([self._full_name, "_generated_var"]) + ) + + return self._helper.main_program.current_block().create_var( + name=var_name, + persistable=persistable, + dtype=dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + ) + + def parameters(self, include_sublayers=True): + """ + + Returns a list of all Parameters from current layer and its sub-layers. + + Returns: + list of Tensor, a list of Parameters. + + Examples: + .. code-block:: python + + import paddle + + linear = paddle.nn.Linear(1,1) + print(linear.parameters()) # print linear_0.w_0 and linear_0.b_0 + + """ + ret = [ + param + for _, param in self.named_parameters( + include_sublayers=include_sublayers + ) + ] + return ret + + def children(self): + """ + + Returns an iterator over immediate children layers. + + Yields: + Layer: a child layer + + Examples: + .. code-block:: python + + import paddle + + linear1 = paddle.nn.Linear(10, 3) + linear2 = paddle.nn.Linear(3, 10, bias_attr=False) + model = paddle.nn.Sequential(linear1, linear2) + + layer_list = list(model.children()) + + print(layer_list) # [, ] + + """ + for _, layer in self.named_children(): + yield layer + + def named_children(self): + """Returns an iterator over immediate children layers, yielding both + the name of the layer as well as the layer itself. + + Yields: + (string, Layer): Tuple containing a name and child layer + + Examples: + .. code-block:: python + + import paddle + + linear1 = paddle.nn.Linear(10, 3) + linear2 = paddle.nn.Linear(3, 10, bias_attr=False) + model = paddle.nn.Sequential(linear1, linear2) + for prefix, layer in model.named_children(): + print(prefix, layer) + # ('0', ) + # ('1', ) + + """ + memo = set() + for name, layer in self._sub_layers.items(): + if layer is not None and layer not in memo: + memo.add(layer) + yield name, layer + + def sublayers(self, include_self=False): + """ + + Returns a list of sub layers. + + Parameters: + include_self(bool, optional): Whether return self as sublayers. Default: False + + Returns: + list of Layer, a list of sub layers. + + Examples: + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + self._dropout = paddle.nn.Dropout(p=0.5) + + def forward(self, input): + temp = self._linear(input) + temp = self._dropout(temp) + return temp + + mylayer = MyLayer() + print(mylayer.sublayers()) # [, ] + + """ + ret = [ + layer + for _, layer in self.named_sublayers(include_self=include_self) + ] + return ret + + def named_parameters(self, prefix='', include_sublayers=True): + """ + Returns an iterator over all parameters in the Layer, yielding tuple of name and parameter. + + Parameters: + prefix(str, optional): Prefix to prepend to all parameter names. Default: ''. + include_sublayers(bool, optional): Whether include the parameters of sublayers. + If True, also include the named parameters from sublayers. Default: True. + + Yields: + (string, Parameter): Tuple of name and Parameter + + Examples: + .. code-block:: python + + import paddle + + fc1 = paddle.nn.Linear(10, 3) + fc2 = paddle.nn.Linear(3, 10, bias_attr=False) + model = paddle.nn.Sequential(fc1, fc2) + for name, param in model.named_parameters(): + print(name, param) + + """ + params_set = set() + named_sublayers = ( + self.named_sublayers(prefix=prefix, include_self=True) + if include_sublayers + else zip([prefix], [self]) + ) + for layer_prefix, sublayer in named_sublayers: + params = sublayer._parameters.items() + for key, param in params: + if param is None or param in params_set: + continue + params_set.add(param) + name = layer_prefix + ('.' if layer_prefix else '') + key + yield name, param + + def named_sublayers(self, prefix='', include_self=False, layers_set=None): + """ + Returns an iterator over all sublayers in the Layer, yielding tuple of name and sublayer. + The duplicate sublayer will only be yielded once. + + Parameters: + prefix(str, optional): Prefix to prepend to all parameter names. Default: ''. + include_self(bool, optional): Whether include the Layer itself. Default: False. + layers_set(set, optional): The set to record duplicate sublayers. Default: None. + + Yields: + (string, Layer): Tuple of name and Layer + + Examples: + .. code-block:: python + + import paddle + + fc1 = paddle.nn.Linear(10, 3) + fc2 = paddle.nn.Linear(3, 10, bias_attr=False) + model = paddle.nn.Sequential(fc1, fc2) + for prefix, layer in model.named_sublayers(): + print(prefix, layer) + + """ + if layers_set is None: + layers_set = set() + if include_self and self not in layers_set: + layers_set.add(self) + yield prefix, self + for key, layer in self._sub_layers.items(): + if layer is None: + continue + layer_prefix = prefix + ('.' if prefix else '') + key + for p, l in layer.named_sublayers( + prefix=layer_prefix, include_self=True, layers_set=layers_set + ): + yield p, l + + def register_buffer(self, name, tensor, persistable=True): + """ + Registers a tensor as buffer into the layer. + + `buffer` is a non-trainable tensor and will not be updated by optimizer, + but is necessary for evaluation and inference. For example, the mean and variance in BatchNorm layers. + The registered buffer is persistable by default, and will be saved into + `state_dict` alongside parameters. If set persistable=False, it registers + a non-persistable buffer, so that it will not be a part of `state_dict` . + + Buffers can be accessed as attributes using given names. + + Parameters: + name (string): name of the buffer. The buffer can be accessed + from this layer using the given name + tensor (Tensor): the tensor to be registered as buffer. + persistable (bool): whether the buffer is part of this layer's + state_dict. + + Returns: + None + + Examples: + .. code-block:: python + + import numpy as np + import paddle + + linear = paddle.nn.Linear(10, 3) + value = np.array([0]).astype("float32") + buffer = paddle.to_tensor(value) + linear.register_buffer("buf_name", buffer, persistable=True) + + # get the buffer by attribute. + print(linear.buf_name) + + """ + + if '_buffers' not in self.__dict__: + raise ValueError( + "super(YourLayer, self).__init__() should be called first" + ) + elif not isinstance(name, six.string_types): + raise TypeError( + "The name of buffer should be a string, but received {}.".format( + type(name).__name__ + ) + ) + elif '.' in name: + raise KeyError( + "The name of buffer can not contain `.`, " + "because when you access the newly added buffer in the " + "form of `self.**.**`, it will cause AttributeError." + ) + elif name == '': + raise KeyError("The name of buffer can not be empty.") + elif hasattr(self, name) and name not in self._buffers: + raise KeyError("attribute '{}' already exists.".format(name)) + elif tensor is not None and not ( + type(tensor) == core.VarBase or type(tensor) == core.eager.Tensor + ): + raise TypeError( + "The registered buffer should be a Paddle.Tensor, but received {}.".format( + type(tensor).__name__ + ) + ) + else: + self._buffers[name] = tensor + if persistable: + self._non_persistable_buffer_names_set.discard(name) + else: + self._non_persistable_buffer_names_set.add(name) + + def buffers(self, include_sublayers=True): + """ + + Returns a list of all buffers from current layer and its sub-layers. + + Parameters: + include_sublayers(bool, optional): Whether include the buffers of sublayers. If True, also include the buffers from sublayers. Default: True + + Returns: + list of Tensor, a list of buffers. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + + linear = paddle.nn.Linear(10, 3) + value = np.array([0]).astype("float32") + buffer = paddle.to_tensor(value) + linear.register_buffer("buf_name", buffer, persistable=True) + + print(linear.buffers()) # == print([linear.buf_name]) + + """ + ret = [ + buffer + for _, buffer in self.named_buffers( + include_sublayers=include_sublayers + ) + ] + return ret + + def named_buffers(self, prefix='', include_sublayers=True): + """ + Returns an iterator over all buffers in the Layer, yielding tuple of name and Tensor. + + Parameters: + prefix(str, optional): Prefix to prepend to all buffer names. Default: ''. + include_sublayers(bool, optional): Whether include the buffers of sublayers. + If True, also include the named buffers from sublayers. Default: True. + + Yields: + (string, Tensor): Tuple of name and tensor + + Examples: + .. code-block:: python + + import numpy as np + import paddle + + fc1 = paddle.nn.Linear(10, 3) + buffer1 = paddle.to_tensor(np.array([0]).astype("float32")) + # register a tensor as buffer by specific `persistable` + fc1.register_buffer("buf_name_1", buffer1, persistable=True) + + fc2 = paddle.nn.Linear(3, 10) + buffer2 = paddle.to_tensor(np.array([1]).astype("float32")) + # register a buffer by assigning an attribute with Tensor. + # The `persistable` can only be False by this way. + fc2.buf_name_2 = buffer2 + + model = paddle.nn.Sequential(fc1, fc2) + + # get all named buffers + for name, buffer in model.named_buffers(): + print(name, buffer) + + """ + buffers_set = set() + named_sublayers = ( + self.named_sublayers(prefix=prefix, include_self=True) + if include_sublayers + else zip([prefix], [self]) + ) + for layer_prefix, sublayer in named_sublayers: + buffers = sublayer._buffers.items() + for key, buffer in buffers: + if buffer is None or buffer in buffers_set: + continue + buffers_set.add(buffer) + name = layer_prefix + ('.' if layer_prefix else '') + key + yield name, buffer + + def clear_gradients(self): + """ + Clear the gradients of all parameters for this layer. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + value = np.arange(26).reshape(2, 13).astype("float32") + a = paddle.to_tensor(value) + linear = paddle.nn.Linear(13, 5) + adam = paddle.optimizer.Adam(learning_rate=0.01, + parameters=linear.parameters()) + out = linear(a) + out.backward() + adam.step() + linear.clear_gradients() + + """ + for p in self.parameters(): + if p.trainable: + p.clear_gradient() + + def _build_once(self, *args, **kwargs): + pass + + def _dygraph_call_func(self, *inputs, **kwargs): + for forward_pre_hook in self._forward_pre_hooks.values(): + hook_result = forward_pre_hook(self, inputs) + if hook_result is not None: + if not isinstance(hook_result, tuple): + hook_result = (hook_result,) + inputs = hook_result + + if not self._built: + with program_desc_tracing_guard(False): + self._build_once(*inputs, **kwargs) + + # TODO(liuyuhui) Only xpu broadcast parameters here. + # The other device is to call _sync_params_buffers in DataParallel + # to realize the parameter synchronization among multiply cards. + if ( + parallel_helper._is_data_parallel_mode() + and paddle.is_compiled_with_xpu() + ): + parallel_helper._broadcast_parameters( + self._parameters.values() + ) + + self._built = True + + if in_profiler_mode(): + with profiler.RecordEvent( + self.__class__.__name__, profiler.TracerEventType.Forward + ): + outputs = self.forward(*inputs, **kwargs) + else: + outputs = self.forward(*inputs, **kwargs) + + for forward_post_hook in self._forward_post_hooks.values(): + hook_result = forward_post_hook(self, inputs, outputs) + if hook_result is not None: + outputs = hook_result + + return outputs + + def __call__(self, *inputs, **kwargs): + if ( + (not in_declarative_mode()) + and (not self._forward_pre_hooks) + and (not self._forward_post_hooks) + and (not self._built) + and in_dygraph_mode() + and (not in_profiler_mode()) + ): + self._build_once(*inputs, **kwargs) + return self.forward(*inputs, **kwargs) + else: + return self._dygraph_call_func(*inputs, **kwargs) + + def forward(self, *inputs, **kwargs): + """ + Defines the computation performed at every call. + Should be overridden by all subclasses. + + Parameters: + *inputs(tuple): unpacked tuple arguments + **kwargs(dict): unpacked dict arguments + """ + raise NotImplementedError + + def backward(self, *inputs): + raise ValueError("Layer shouldn't implement backward") + + def add_sublayer(self, name, sublayer): + """ + + Adds a sub Layer instance. + + Added sublayer can be accessed by self.name + + Parameters: + name(str): name of this sublayer. + sublayer(Layer): an instance of Layer. + Returns: + Layer, the sublayer passed in. + + Examples: + .. code-block:: python + + import paddle + + class MySequential(paddle.nn.Layer): + def __init__(self, *layers): + super(MySequential, self).__init__() + if len(layers) > 0 and isinstance(layers[0], tuple): + for name, layer in layers: + self.add_sublayer(name, layer) + else: + for idx, layer in enumerate(layers): + self.add_sublayer(str(idx), layer) + + def forward(self, input): + for layer in self._sub_layers.values(): + input = layer(input) + return input + + fc1 = paddle.nn.Linear(10, 3) + fc2 = paddle.nn.Linear(3, 10, bias_attr=False) + model = MySequential(fc1, fc2) + for prefix, layer in model.named_sublayers(): + print(prefix, layer) + + """ + assert isinstance(sublayer, Layer) or sublayer == None + + self._sub_layers[name] = sublayer + return sublayer + + def add_parameter(self, name, parameter): + """Adds a Parameter instance. + + Added parameter can be accessed by self.name + + Parameters: + name(str): name of this sublayer. + parameter(Parameter): an instance of Parameter. + Returns: + Parameter, the parameter passed in. + Examples: + .. code-block:: python + + import paddle + + class MyLayer(paddle.nn.Layer): + def __init__(self): + super(MyLayer, self).__init__() + self._linear = paddle.nn.Linear(1, 1) + w_tmp = self.create_parameter([1,1]) + self.add_parameter("w_tmp", w_tmp) + + def forward(self, input): + return self._linear(input) + + mylayer = MyLayer() + for name, param in mylayer.named_parameters(): + print(name, param) # will print w_tmp,_linear.weight,_linear.bias + + """ + if '_parameters' not in self.__dict__: + raise RuntimeError( + "super(YourLayer, self).__init__() should be called firstly." + ) + elif not isinstance(name, six.string_types): + raise TypeError( + "The name of parameter should be a string, but received {}.".format( + type(name).__name__ + ) + ) + elif '.' in name: + raise KeyError( + "The name of parameter can not contain `.`, " + "because when you access the newly added parameter in the " + "form of `self.**.**`, it will cause AttributeError." + ) + elif name == '': + raise KeyError("The name of parameter can not be empty.") + elif hasattr(self, name) and name not in self._parameters: + raise KeyError("The parameter '{}' already exists.".format(name)) + elif parameter is not None and not isinstance( + parameter, framework.Parameter + ): + raise TypeError( + "The parameter to be added should be a Parameter, but received {}.".format( + type(parameter).__name__ + ) + ) + else: + if parameter is None: + self._parameters[name] = None + + if len(self._loaddict_holder) > 0: + assert ( + parameter.name in self._loaddict_holder + ), "Parameter not found, Can't not find [ {} ] in state_dict".format( + parameter.name + ) + + parameter.set_value(self._loaddict_holder[parameter.name]) + + self._parameters[name] = parameter + return parameter + + def _set_op_attrs(self, attrs): + """ + Add customized attribute while append_op. In case of quantization, we want to save + some attributes into op_desc while exporting inference model by @to_static. + + Arguments: + attrs(dict): customized attributes that will be added into op_descs. + + NOTE: The interface is only exposed to developers. + """ + + def is_already_registered(is_pre_hook): + layers_hooks = ( + self._forward_pre_hooks + if is_pre_hook + else self._forward_post_hooks + ) + candidate_hook = ( + record_program_ops_pre_hook + if is_pre_hook + else set_op_customized_attrs_post_hook + ) + + already_registed = False + if layers_hooks: + last_key = next(reversed(layers_hooks)) + already_registed = layers_hooks[last_key] == candidate_hook + + return already_registed + + if not isinstance(attrs, dict): + raise TypeError( + "attrs should be type(dict), but received {}".format( + type(attrs).__name__ + ) + ) + + # NOTE: Overwrite behavior for same key. + self._customized_attrs.update(attrs) + + if not is_already_registered(is_pre_hook=True): + pre_hook_helper = self.register_forward_pre_hook( + record_program_ops_pre_hook + ) + assert len(self._op_recorder.hooks) == 0 + self._op_recorder.hooks = [pre_hook_helper] + + # manually register post_hook to ensure it is inserted into the head. + if not is_already_registered(is_pre_hook=False): + post_hook_helper = self.register_forward_post_hook( + set_op_customized_attrs_post_hook + ) + if len(self._forward_post_hooks) > 1: + self._forward_post_hooks.move_to_end( + post_hook_helper._hook_id, last=False + ) + + assert len(self._op_recorder.hooks) == 1 + + # hooks that need to be removed once we finish executing them. + self._op_recorder.hooks.append(post_hook_helper) + + def __getstate__(self): + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __getattr__(self, name): + if '_parameters' in self.__dict__: + _parameters = self.__dict__['_parameters'] + if name in self._parameters: + if in_declarative_mode(): + return _convert_into_variable(self._parameters[name]) + return self._parameters[name] + if '_sub_layers' in self.__dict__: + _sub_layers = self.__dict__['_sub_layers'] + if name in self._sub_layers: + return self._sub_layers[name] + if '_buffers' in self.__dict__: + _buffers = self.__dict__['_buffers'] + if name in _buffers: + if in_declarative_mode(): + return _convert_into_variable(_buffers[name]) + return _buffers[name] + return object.__getattribute__(self, name) + + def __setattr__(self, name, value): + def _remove_if_exist(*dicts): + for d in dicts: + if name in d: + del d[name] + + if isinstance(getattr(type(self), name, None), property): + object.__setattr__(self, name, value) + params = self.__dict__.get('_parameters', None) + if isinstance(value, framework.Parameter): + if params is None: + raise ValueError( + "super(YourLayer, self).__init__() should be called first" + ) + if len(self._loaddict_holder) > 0: + assert ( + value.name in self._loaddict_holder + ), "Parameter not found, Can't not find [ {} ] in state_dict".format( + value.name + ) + + value.set_value(self._loaddict_holder[value.name]) + + _remove_if_exist(self.__dict__, self._buffers, self._sub_layers) + params[name] = value + elif params is not None and name in params: + if value is not None: + raise TypeError( + "assignment to parameter '{}' should be of type Parameter or None, but got '{}'".format( + name, type(value).__name__ + ) + ) + params[name] = None + else: + layers = self.__dict__.get('_sub_layers', None) + if isinstance(value, Layer): + if layers is None: + raise ValueError( + "super(YourLayer, self).__init__() should be called first" + ) + + _remove_if_exist(self.__dict__, self._parameters, self._buffers) + layers[name] = value + elif layers is not None and name in layers: + if value is not None: + raise TypeError( + "assignment to sublayer '{}' should be of type Layer or None, but got '{}'".format( + name, type(value).__name__ + ) + ) + layers[name] = None + else: + _buffers = self.__dict__.get('_buffers', None) + if isinstance(value, (core.VarBase, core.eager.Tensor)): + if _buffers is None: + raise ValueError( + "super(YourLayer, self).__init__() should be called first" + ) + _remove_if_exist( + self.__dict__, self._parameters, self._sub_layers + ) + # Set persistable=False by default. Only `register_buffer` can + # add a persistable buffer. + if name not in self._buffers: + self._non_persistable_buffer_names_set.add(name) + if not value.name: + value.name = unique_name.generate('_buffers_' + name) + _buffers[name] = value + elif _buffers is not None and name in _buffers: + # Note(Aurelius84): In Dy2stat, the value of the Buffer may be modified in + # decorated function, such as `self.buffer = new_tensor`. So we update its + # value via `assign`. + if type(value) == framework.Variable: + from paddle import assign + + # Note(zhhsplendid): the condition below happens in PaddleGan model, + # but should all non-Variable _buffers[name] be re-assign? We + # should consider it in the future. I current wrote this as + # conservative code. + if in_declarative_mode() and _buffers[name] is None: + raise RuntimeError( + 'In Dy2stat, self.{0} is a buffer and self.{0} is ' + 'not allowed to be set to Variable when self.{0} is None.'.format( + name + ) + ) + elif ( + _buffers[name] is None + or type(getattr(self, name)) == core.VarBase + ): + _buffers[name] = assign(value) + else: + assign(value, getattr(self, name)) + elif value is not None: + raise TypeError( + "assignment to buffers '{}' should be of type core.VarBase or None, but got '{}'".format( + name, type(value).__name__ + ) + ) + else: + # Assigning None will remove the buffer, but if re-assign a new varBase to it, + # it will be remarked as a buffer with same `persistable` attribute. + _buffers[name] = None + else: + object.__setattr__(self, name, value) + + def __delattr__(self, name): + if name in self._parameters: + del self._parameters[name] + elif name in self._sub_layers: + del self._sub_layers[name] + elif name in self._buffers: + del self._buffers[name] + self._non_persistable_buffer_names_set.discard(name) + else: + object.__delattr__(self, name) + + def __dir__(self): + """ + Return a list. Get all parameters, buffers(non-parameter tensors), sublayers, method and attr of Layer. + + Examples: + .. code-block:: python + import paddle + import numpy as np + + class Mylayer(paddle.nn.Layer): + def __init__(self): + super(Mylayer, self).__init__() + self.linear1 = paddle.nn.Linear(10, 10) + self.linear2 = paddle.nn.Linear(5, 5) + self.conv2d = paddle.nn.Conv2D(3, 2, 3) + self.embedding = paddle.nn.Embedding(128, 16) + self.h_0 = paddle.to_tensor(np.zeros([10, 10]).astype('float32')) + + mylayer = Mylayer() + print(dir(mylayer)) + # only parts are shown, because of list have too much content + # ['__call__', '__class__', ... , 'conv2d', 'embedding', 'h_0', 'linear1', 'linear2', ... , 'sublayers', 'train'] + + """ + method = dir(self.__class__) + attrs = list(self.__dict__.keys()) + parameters = list(self._parameters.keys()) + sublayers = list(self._sub_layers.keys()) + buffers = list(self._buffers.keys()) + + keys = method + attrs + parameters + sublayers + buffers + + return keys + + def extra_repr(self): + """ + Extra representation of this layer, you can have custom implementation + of your own layer. + """ + return '' + + def __repr__(self): + extra_lines = [] + extra_repr = self.extra_repr() + extra_lines = extra_repr.split('\n') + sublayer_lines = [] + for name, layer in self._sub_layers.items(): + sublayer_str = repr(layer) + sublayer_str = _addindent(sublayer_str, 2) + sublayer_lines.append('(' + name + '): ' + sublayer_str) + + final_str = self.__class__.__name__ + '(' + if extra_lines: + if len(extra_lines) > 1: + final_str += '\n ' + '\n '.join(extra_lines) + '\n' + elif len(extra_lines) == 1: + final_str += extra_lines[0] + if sublayer_lines: + final_str += '\n ' + '\n '.join(sublayer_lines) + '\n' + + final_str += ')' + return final_str + + def register_state_dict_hook(self, hook): + hook_remove_helper = HookRemoveHelper(self._state_dict_hooks) + self._state_dict_hooks[hook_remove_helper._hook_id] = hook + return hook_remove_helper + + def _obtain_parameters_buffers( + self, + destination=None, + include_sublayers=True, + structured_name_prefix="", + ): + """ + The difference from state_dict() is that state_dict_hook will not be called, + but the original types of parameters and buffers will be maintained. + """ + if destination is None: + destination = collections.OrderedDict() + for name, data in self._parameters.items(): + if data is not None: + destination[structured_name_prefix + name] = data + for name, buffer in self._buffers.items(): + if ( + buffer is not None + and name not in self._non_persistable_buffer_names_set + ): + destination[structured_name_prefix + name] = buffer + + if include_sublayers: + for layer_name, layer_item in self._sub_layers.items(): + if layer_item is not None: + destination_temp = destination.copy() + destination_temp.update( + layer_item._obtain_parameters_buffers( + destination_temp, + include_sublayers, + structured_name_prefix + layer_name + ".", + ) + ) + destination = destination_temp + return destination + + def _state_dict_impl( + self, + destination=None, + include_sublayers=True, + structured_name_prefix="", + include_non_persistable_buffer=False, + use_hook=True, + ): + """ + Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict + + Parameters: + destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None + include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True + include_non_persistable_buffer(bool, optional): If true, include non persistable buffers of current layer and its sub-layers, it is used in pure fp16 and jit.save. Default: False + use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True + """ + + if destination is None: + destination = collections.OrderedDict() + for name, data in self._parameters.items(): + if data is not None: + destination[structured_name_prefix + name] = data + for name, buffer in self._buffers.items(): + if not include_non_persistable_buffer: + if ( + buffer is not None + and name not in self._non_persistable_buffer_names_set + ): + destination[structured_name_prefix + name] = buffer + else: + if buffer is not None: + destination[structured_name_prefix + name] = buffer + + if include_sublayers: + for layer_name, layer_item in self._sub_layers.items(): + if layer_item is not None: + destination_temp = destination.copy() + destination_temp.update( + layer_item._state_dict_impl( + destination_temp, + include_sublayers, + structured_name_prefix + layer_name + ".", + include_non_persistable_buffer, + use_hook, + ) + ) + destination = destination_temp + if use_hook: + for state_dict_hook in self._state_dict_hooks.values(): + hook_result = state_dict_hook(destination) + if hook_result is not None: + destination = hook_result + + return destination + + def to_static_state_dict( + self, + destination=None, + include_sublayers=True, + structured_name_prefix="", + use_hook=True, + ): + ''' + + Get all parameters and buffers of current layer and its sub-layers. And set them into a dict + + Parameters: + destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None + include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True + use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True + + Retruns: + dict, a dict contains all the parameters and persistable buffers. + + Examples: + .. code-block:: python + + import paddle + + emb = paddle.nn.Embedding(10, 10) + + state_dict = emb.to_static_state_dict() + paddle.save( state_dict, "paddle_dy.pdparams") + + ''' + return self._state_dict_impl( + destination=destination, + include_sublayers=include_sublayers, + structured_name_prefix=structured_name_prefix, + include_non_persistable_buffer=True, + use_hook=use_hook, + ) + + def state_dict( + self, + destination=None, + include_sublayers=True, + structured_name_prefix="", + use_hook=True, + ): + ''' + Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict + + Parameters: + destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None + include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True + use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True + + Retruns: + dict: a dict contains all the parameters and persistable buffers. + + Examples: + .. code-block:: python + + import paddle + + emb = paddle.nn.Embedding(10, 10) + + state_dict = emb.state_dict() + paddle.save( state_dict, "paddle_dy.pdparams") + + ''' + return self._state_dict_impl( + destination=destination, + include_sublayers=include_sublayers, + structured_name_prefix=structured_name_prefix, + include_non_persistable_buffer=False, + use_hook=use_hook, + ) + + @framework.deprecate_stat_dict + def set_state_dict(self, state_dict, use_structured_name=True): + ''' + Set parameters and persistable buffers from state_dict. All the parameters and buffers will be reset by the tensor in the state_dict + + Parameters: + state_dict(dict) : Dict contains all the parameters and persistable buffers. + use_structured_name(bool, optional) : If true, use structured name as key, otherwise, use parameter or buffer name as key. + Default: True + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + emb = paddle.nn.Embedding(10, 10) + + state_dict = emb.state_dict() + paddle.save(state_dict, "paddle_dy.pdparams") + para_state_dict = paddle.load("paddle_dy.pdparams") + emb.set_state_dict(para_state_dict) + + ''' + + def _check_match(key, param): + state = state_dict.get(key, None) + if state is None: + raise ValueError( + "{} is not found in the provided dict.".format(key) + ) + if isinstance(state, dict) or isinstance(state, list): + if len(state) != len(param): + raise ValueError( + "{} receieves the length of {}, " + "but the expected shape is {}".format( + key, len(state), len(param) + ) + ) + else: + return param, state + else: + state_shape = ( + state.shape() + if inspect.ismethod(state.shape) + else state.shape + ) + + if list(state_shape) != list(param.shape): + raise ValueError( + "{} receives a shape {}, but the expected shape is {}.".format( + key, list(state_shape), list(param.shape) + ) + ) + return param, state + + matched_param_state = [] + for key, param in self.state_dict(use_hook=False).items(): + key_name = key if use_structured_name else param.name + try: + match_res = _check_match(key_name, param) + matched_param_state.append(match_res) + except ValueError as err: + warnings.warn(("Skip loading for {}. ".format(key) + str(err))) + + if _non_static_mode(): + for param, state in matched_param_state: + param.set_value(state) + else: + + def _set_var(var, ndarray): + t = global_scope().find_var(var.name).get_tensor() + p = t._place() + if p.is_cpu_place(): + place = core.CPUPlace() + elif p.is_cuda_pinned_place(): + place = core.CUDAPinnedPlace() + elif p.is_xpu_place(): + p = core.Place() + p.set_place(t._place()) + place = core.XPUPlace(p.xpu_device_id()) + else: + p = core.Place() + p.set_place(t._place()) + place = core.CUDAPlace(p.gpu_device_id()) + t.set(ndarray, place) + + executor = Executor(_get_device())._default_executor + # restore parameter states + core._create_loaded_parameter( + [param for param, state in matched_param_state], + global_scope(), + executor, + ) + for param, state in matched_param_state: + _set_var(param, state) + + def to(self, device=None, dtype=None, blocking=None): + ''' + Cast the parameters and buffers of Layer by the give device, dtype and blocking. + + Parameters: + device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored. + If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the + index of the GPUs or XPUs. Default: None. + + dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None. + + blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be + asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None. + + Returns: + self + + Examples: + .. code-block:: python + + # required: skip + import paddle + + linear=paddle.nn.Linear(2, 2) + linear.weight + #Parameter containing: + #Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [[-0.32770029, 0.38653070], + # [ 0.46030545, 0.08158520]]) + + linear.to(dtype='float64') + linear.weight + #Tenor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=False, + # [[-0.32770029, 0.38653070], + # [ 0.46030545, 0.08158520]]) + + linear.to(device='cpu') + linear.weight + #Tensor(shape=[2, 2], dtype=float64, place=CPUPlace, stop_gradient=False, + # [[-0.32770029, 0.38653070], + # [ 0.46030545, 0.08158520]]) + linear.to(device=paddle.CUDAPinnedPlace(), blocking=False) + linear.weight + #Tensor(shape=[2, 2], dtype=float64, place=CUDAPinnedPlace, stop_gradient=False, + # [[-0.04989364, -0.56889004], + # [ 0.33960250, 0.96878713]]) + + ''' + return self._to_impl( + device=device, + dtype=dtype, + blocking=blocking, + include_sublayers=True, + floating_only=False, + ) + + def _apply(self, func, device, dtype, blocking, include_sublayers=True): + if include_sublayers: + for layer in self.children(): + layer._apply(func, device, dtype, blocking, include_sublayers) + + for key, param in self._parameters.items(): + if param is not None: + with no_grad(): + param_applied = func(param, device, dtype, blocking) + + if param.grad is not None: + with no_grad(): + grad_applied = func( + param._grad_ivar(), device, dtype, blocking + ) + + for key, buf in self._buffers.items(): + if buf is not None: + self._buffers[key] = func(buf, device, dtype, blocking) + + self._dtype = dtype + + def _transform(self, t, device, dtype, blocking): + if device is None: + device = t.place + if dtype is None: + dtype = t.dtype + + if type(dtype) is not VarDesc.VarType: + dtype = convert_np_dtype_to_dtype_(dtype) + + # 1. gpu place need to determine whether the memory is sufficient for allocation: + if t.place.is_gpu_place(): + # for gpu, minimum memory allocation unit is 256 bytes. + size_dtype = core.size_of_dtype(dtype) + # Note(zhangbo): Paddle GPU minimum memory allocation unit is 256 bytes, waiting_alloc_memory will comput ‘t’ occupied memory space. + # Coefficient 1.2 is used to avoid OOM that may occur in this critical state when the memory is just enough. + waiting_alloc_memory = ( + ((np.prod(t.shape) * size_dtype) / 256 + 1) * 256 * 1.2 + ) + gpu_memory_available = core.gpu_memory_available() + if gpu_memory_available < waiting_alloc_memory: + # Copy param / Tensor to cpu + t_used = t._copy_to( + paddle.CPUPlace(), blocking + ) # k-v type will error + # Release mem of t + t.value().get_tensor()._clear() + else: + t_used = t + else: + t_used = t + + # 2. cast param / Tensor to dtype + if dtype is not None and dtype != t_used.dtype: + with paddle.fluid.framework._dygraph_place_guard( + place=t_used.place + ): + t_casted = t_used.cast(dtype=dtype) + else: + t_casted = t_used + + # 3. Copy casted cpu param / Tensor to device + if device is not None and not t_casted.place._equals(device): + new_t = t_casted._copy_to(device, blocking) + else: + new_t = t_casted + + # 4. share Tensor to origin param / Tensor + dst_tensor = t.value().get_tensor() + src_tensor = new_t.value().get_tensor() + dst_tensor._share_data_with(src_tensor) + + return t + + def _to_impl( + self, + device=None, + dtype=None, + blocking=None, + include_sublayers=True, + floating_only=False, + ): + ''' + Cast the parameters and buffers of Layer by the give device, dtype and blocking. + + Parameters: + device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored. + If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the + index of the GPUs or XPUs. Default: None. + + dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None. + + blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be + asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None. + + include_sublayers(bool|True, optional): If True, deal with self and all sublayers parameters and buffers, if not only deal with self parameters and buffers. Default: True. + + floating_only(bool|False, optional): If True, only cast all floating point parameters and buffers of Layer by the give device, dtype and blocking. + + Returns: + self + + ''' + + if device is None and dtype is None and blocking is None: + return self + + if device is not None: + if isinstance(device, str): + device = paddle.device._convert_to_place(device) + elif isinstance( + device, + ( + core.CPUPlace, + core.CUDAPlace, + core.CUDAPinnedPlace, + core.XPUPlace, + ), + ): + pass + else: + raise ValueError( + "device value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace() or paddle.XPUPlace(), but the type of device is " + + type(device).__name__ + ) + + if blocking is None: + blocking = True + else: + assert isinstance( + blocking, bool + ), "blocking value error, must be the True, False or None" + + def transform(t, device, dtype, blocking): + if floating_only and (not paddle.is_floating_point(t)): + return t + return self._transform(t, device, dtype, blocking) + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=UserWarning) + self._apply(transform, device, dtype, blocking, include_sublayers) + + self._dtype = dtype + return self + + def _startup_program(self): + """ + Return starup program containing initialization operations of all parameters. + + NOTE(dev): This is a very low level API and only for inner developer. + """ + startup_program = Program() + for param in self.parameters(): + param._create_init_op(startup_program.global_block()) + + return startup_program + + # [aliases] Compatible with old method names + set_dict = set_state_dict + load_dict = set_state_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/learning_rate_scheduler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/learning_rate_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..18950144bc4d4e353aaec92c0d60c8da653918b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/learning_rate_scheduler.py @@ -0,0 +1,1226 @@ +# 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. + +from __future__ import print_function + +import math +import warnings + +from .. import unique_name +from ..framework import Variable +from ..data_feeder import check_type + +__all__ = [ + 'NoamDecay', 'PiecewiseDecay', 'NaturalExpDecay', 'ExponentialDecay', + 'InverseTimeDecay', 'PolynomialDecay', 'CosineDecay', 'LinearLrWarmup', + 'ReduceLROnPlateau', 'StepDecay', 'MultiStepDecay', 'LambdaDecay' +] + + +class LearningRateDecay(object): + """ + Base class of learning rate decay + + Define the common interface of an LearningRateDecay. + User should not use this class directly, + but need to use one of it's implementation. + """ + + def __init__(self, begin=0, step=1, dtype='float32'): + self.step_num = begin + self.step_size = step + self.dtype = dtype + + def __call__(self): + lr = self.step() + if isinstance(lr, float): + lr = self.create_lr_var(lr) + self.step_num += self.step_size + return lr + + def create_lr_var(self, lr): + """ + convert lr from float to variable + + Args: + lr: learning rate + Returns: + learning rate variable + """ + from .. import layers + lr = layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(lr), + dtype=self.dtype, + persistable=False) + return lr + + # Note: If you want to change what optimizer.state_dict stores, just overwrite this functions, + # "self.step_num" will be stored by default. + def state_dict(self): + """ + Returns the state of the scheduler as a :class:`dict`. + + It is a subset of self.__dict__ . + """ + self._state_keys() + state_dict = {} + for key in self.keys: + if key not in self.__dict__: + continue + value = self.__dict__[key] + if isinstance(value, Variable): + assert value.shape == [ + 1 + ], "shape of Variable in state_dict must be [1] {}".format( + value.shape) + value = value.numpy()[0] + state_dict[key] = value + + return state_dict + + def _state_keys(self): + """ + set the keys in self.__dict__ that are needed to be saved. + """ + self.keys = ['step_num'] + + def set_state_dict(self, state_dict): + """ + Loads the schedulers state. + """ + self._state_keys() + for key in self.keys: + if key in state_dict: + self.__dict__[key] = state_dict[key] + else: + raise RuntimeError( + "Please check whether state_dict is correct for optimizer. Can't find [ {} ] in state_dict" + .format(key)) + if len(state_dict) > len(self.keys): + warnings.warn( + "There are some unused values in state_dict. Maybe the optimizer have different 'LearningRateDecay' when invoking state_dict and set_dict" + ) + + # [aliases] Compatible with old method names + set_dict = set_state_dict + + def step(self): + raise NotImplementedError() + + +class PiecewiseDecay(LearningRateDecay): + """ + :api_attr: imperative + + Piecewise decay scheduler. + + The algorithm can be described as the code below. + + .. code-block:: text + + boundaries = [10000, 20000] + values = [1.0, 0.5, 0.1] + if global_step < 10000: + learning_rate = 1.0 + elif 10000 <= global_step < 20000: + learning_rate = 0.5 + else: + learning_rate = 0.1 + + Parameters: + boundaries(list): A list of steps numbers. The type of element in the list is python int. + values(list): A list of learning rate values that will be picked during + different step boundaries. The type of element in the list is python float. + begin(int): The begin step to initialize the global_step in the description above. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + boundaries = [10000, 20000] + values = [1.0, 0.5, 0.1] + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding( [10, 10] ) + optimizer = fluid.optimizer.SGD( + learning_rate=fluid.dygraph.PiecewiseDecay(boundaries, values, 0), + parameter_list = emb.parameters() ) + """ + + def __init__(self, boundaries, values, begin, step=1, dtype='float32'): + super(PiecewiseDecay, self).__init__(begin, step, dtype) + self.boundaries = boundaries + self.values = values + + self.vars = [] + for value in values: + self.vars.append(value) + + def step(self): + for i in range(len(self.boundaries)): + if self.step_num < self.boundaries[i]: + return self.vars[i] + return self.create_lr_var(self.vars[len(self.values) - 1]) + + +class NaturalExpDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies natural exponential decay to the initial learning rate. + + The algorithm can be described as following. + + .. math:: + + decayed\_learning\_rate = learning\_rate * e^{y} + + If staircase is set to False, then: + + .. math:: + + y = - decay\_rate * \\frac{global\_step}{decay\_steps} + + If staircase is set to True, then: + + .. math:: + + y = - decay\_rate * math.floor(\\frac{global\_step}{decay\_steps}) + + Parameters: + learning_rate(Variable|float): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. + decay_steps(int): The decay step size. It determines the decay cycle. + decay_rate(int): The decay rate. + staircase(bool, optional): If set to True, decay the learning rate at discrete intervals. The + default value is False. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + base_lr = 0.1 + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.dygraph.NaturalExpDecay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True), + parameter_list=emb.parameters()) + + """ + + def __init__(self, + learning_rate, + decay_steps, + decay_rate, + staircase=False, + begin=0, + step=1, + dtype='float32'): + super(NaturalExpDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.decay_steps = decay_steps + self.decay_rate = decay_rate + self.staircase = staircase + + def step(self): + from .. import layers + div_res = self.create_lr_var(self.step_num / self.decay_steps) + if self.staircase: + div_res = layers.floor(div_res) + decayed_lr = self.learning_rate * layers.exp( + -1 * self.decay_rate * div_res) + + return decayed_lr + + +class ExponentialDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies exponential decay to the learning rate. + + The algorithm can be described as following. + + .. math:: + + decayed\_learning\_rate = learning\_rate * decay\_rate ^ y + + If staircase is set to False, then: + + .. math:: + + y = \\frac{global\_step}{decay\_steps} + + If staircase is set to True, then: + + .. math:: + + y = math.floor(\\frac{global\_step}{decay\_steps}) + + + Parameters: + learning_rate(Variable|float): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. + decay_steps(int): The decay step size. It determines the decay cycle. + decay_rate(float): The decay rate. + staircase(bool, optional): If set to True, decay the learning rate at discrete intervals. The + default value is False. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + base_lr = 0.1 + with fluid.dygraph.guard(): + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.dygraph.ExponentialDecay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True)) + + """ + + def __init__(self, + learning_rate, + decay_steps, + decay_rate, + staircase=False, + begin=0, + step=1, + dtype='float32'): + super(ExponentialDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.decay_steps = decay_steps + self.decay_rate = decay_rate + self.staircase = staircase + + def step(self): + from .. import layers + div_res = self.create_lr_var(self.step_num / self.decay_steps) + if self.staircase: + div_res = layers.floor(div_res) + + decayed_lr = self.learning_rate * (self.decay_rate**div_res) + + return decayed_lr + + +class InverseTimeDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies inverse time decay to the initial learning rate. + + The algorithm can be described as following. + If staircase is set to False, then: + + .. math:: + + decayed\_learning\_rate = \\frac{learning\_rate}{1 + decay\_rate * \\frac{global\_step}{decay\_step}} + + If staircase is set to True, then: + + .. math:: + + decayed\_learning\_rate = \\frac{learning\_rate}{1 + decay\_rate * math.floor(\\frac{global\_step}{decay\_step})} + + Parameters: + learning_rate(Variable|float): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. + decay_steps(int): The decay step size. It determines the decay cycle. + decay_rate(float): The decay rate. + staircase(bool, optional): If set to True, decay the learning rate at discrete intervals. The + default value is False. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + base_lr = 0.1 + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.dygraph.InverseTimeDecay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True), + parameter_list = emb.parameters()) + + """ + + def __init__(self, + learning_rate, + decay_steps, + decay_rate, + staircase=False, + begin=0, + step=1, + dtype='float32'): + super(InverseTimeDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.decay_steps = decay_steps + self.decay_rate = decay_rate + self.staircase = staircase + + def step(self): + from .. import layers + div_res = self.create_lr_var(self.step_num / self.decay_steps) + if self.staircase: + div_res = layers.floor(div_res) + + decayed_lr = self.learning_rate / (1 + self.decay_rate * div_res) + + return decayed_lr + + +class PolynomialDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies polynomial decay to the initial learning rate. + + The algorithm can be described as following. + + If cycle is set to True, then: + + .. math:: + + decay\_steps & = decay\_steps * math.ceil(\\frac{global\_step}{decay\_steps}) + + decayed\_learning\_rate & = (learning\_rate-end\_learning\_rate)*(1-\\frac{global\_step}{decay\_steps})^{power}+end\_learning\_rate + + If cycle is set to False, then: + + .. math:: + + global\_step & = min(global\_step, decay\_steps) + + decayed\_learning\_rate & = (learning\_rate-end\_learning\_rate)*(1-\\frac{global\_step}{decay\_steps})^{power}+end\_learning\_rate + + Parameters: + learning_rate(Variable|float): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. + decay_steps(int): The decay step size. It determines the decay cycle. + end_learning_rate(float, optional): The minimum final learning rate. The default value is 0.0001. + power(float, optional): Power of polynomial. The default value is 1.0. + cycle(bool, optional): If set true, decay the learning rate every decay_steps. The default value is False. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + start_lr = 0.01 + total_step = 5000 + end_lr = 0 + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding( [10, 10]) + optimizer = fluid.optimizer.SGD( + learning_rate = fluid.dygraph.PolynomialDecay( + start_lr, total_step, end_lr, power=1.0), + parameter_list = emb.parameters()) + + """ + + def __init__(self, + learning_rate, + decay_steps, + end_learning_rate=0.0001, + power=1.0, + cycle=False, + begin=0, + step=1, + dtype='float32'): + super(PolynomialDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.decay_steps = decay_steps + self.end_learning_rate = end_learning_rate + self.power = power + self.cycle = cycle + + def step(self): + from .. import layers + tmp_step_num = self.step_num + tmp_decay_steps = self.decay_steps + if self.cycle: + div_res = layers.ceil( + self.create_lr_var(tmp_step_num / float(self.decay_steps))) + + if tmp_step_num == 0: + div_res = self.create_lr_var(1.0) + tmp_decay_steps = self.decay_steps * div_res + else: + tmp_step_num = self.create_lr_var( + tmp_step_num if tmp_step_num < self.decay_steps else self. + decay_steps) + + decayed_lr = (self.learning_rate - self.end_learning_rate) * \ + ((1 - tmp_step_num / tmp_decay_steps) ** self.power) + self.end_learning_rate + return decayed_lr + + +class CosineDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies cosine decay to the learning rate. + + The algorithm can be described as following. + + .. math:: + + decayed\_learning\_rate = learning\_rate * 0.5 * (math.cos(global\_step * \\frac{math.pi}{step\_each\_epoch} ) + 1) + + Parameters: + learning_rate(Variable|float): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. + step_each_epoch(int): The number of steps in an epoch. + epochs(int): The number of epochs. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + None. + + Examples: + .. code-block:: python + + base_lr = 0.1 + with fluid.dygraph.guard(): + optimizer = fluid.optimizer.SGD( + learning_rate = fluid.dygraph.CosineDecay( + base_lr, 10000, 120) ) + """ + + def __init__(self, + learning_rate, + step_each_epoch, + epochs, + begin=0, + step=1, + dtype='float32'): + super(CosineDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.step_each_epoch = step_each_epoch + self.epochs = epochs + + def step(self): + from .. import layers + cur_epoch = layers.floor( + self.create_lr_var(self.step_num / self.step_each_epoch)) + decayed_lr = self.learning_rate * 0.5 * ( + layers.cos(cur_epoch * math.pi / self.epochs) + 1) + return decayed_lr + + +class NoamDecay(LearningRateDecay): + r""" + :api_attr: imperative + + Applies Noam decay to the initial learning rate. + + The algorithm can be described as following. + + .. math:: + + decayed\_learning\_rate = learning\_rate * d_{model}^{-0.5} * min(global\_step^{-0.5}, global\_step * warmup\_steps^{-1.5}) + + Please reference `attention is all you need `_ + + Parameters: + d$_{model}$(Variable|int): The dimensionality of input and output feature vector of model. If type is Variable, + it's a tensor with shape [1] and the data type can be int32 or int64. The type can also be python int. + warmup_steps(Variable|int): The number of warmup steps. A super parameter. If type is Variable, + it's a tensor with shape [1] and the data type can be int32 or int64. The type can also be python int. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + learning_rate(Variable|float|int): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. Default 1.0 + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + warmup_steps = 100 + learning_rate = 0.01 + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + optimizer = fluid.optimizer.SGD( + learning_rate = fluid.dygraph.NoamDecay( + 1/(warmup_steps *(learning_rate ** 2)), + warmup_steps), + parameter_list = emb.parameters()) + """ + + def __init__(self, + d_model, + warmup_steps, + begin=1, + step=1, + dtype='float32', + learning_rate=1.0): + super(NoamDecay, self).__init__(begin, step, dtype) + self.learning_rate = learning_rate + self.d_model = d_model + self.warmup_steps = warmup_steps + + def step(self): + from .. import layers + a = self.create_lr_var(self.step_num**-0.5) + b = self.create_lr_var((self.warmup_steps**-1.5) * self.step_num) + lr_value = self.learning_rate * (self.d_model** + -0.5) * layers.elementwise_min(a, b) + return lr_value + + +class LinearLrWarmup(LearningRateDecay): + """ + :api_attr: imperative + + This operator use the linear learning rate warm up strategy to adjust the learning rate preliminarily before the normal learning rate scheduling. + For more information, please refer to `Bag of Tricks for Image Classification with Convolutional Neural Networks `_ + + When global_step < warmup_steps, learning rate is updated as: + + .. code-block:: text + + linear_step = end_lr - start_lr + lr = start_lr + linear_step * (global_step / warmup_steps) + + where start_lr is the initial learning rate, and end_lr is the final learning rate; + + When global_step >= warmup_steps, learning rate is updated as: + + .. code-block:: text + + lr = learning_rate + + where lr is the learning_rate after warm-up. + + Args: + learning_rate (Variable|float): Learning_rate after warm-up, it could be 1D-Tensor or single value with the data type of float32. + warmup_steps (int): Steps for warm up. + start_lr (float): Initial learning rate of warm up. + end_lr (float): Final learning rate of warm up. + begin(int, optional): The begin step. The initial value of global_step described above. The default value is 0. + step(int, optional): The step size used to calculate the new global_step in the description above. + The default value is 1. + dtype(str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Returns: + Variable: Warm-up learning rate with the same data type as learning_rate. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + learning_rate = 0.1 + warmup_steps = 50 + start_lr = 0 + end_lr = 0.1 + + with fluid.dygraph.guard(): + lr_decay = fluid.dygraph.LinearLrWarmup( learning_rate, warmup_steps, start_lr, end_lr) + + + """ + + def __init__(self, + learning_rate, + warmup_steps, + start_lr, + end_lr, + begin=1, + step=1, + dtype='float32'): + super(LinearLrWarmup, self).__init__(begin, step, dtype) + type_check = isinstance(learning_rate, float) or isinstance( + learning_rate, int) or isinstance(learning_rate, LearningRateDecay) + if not type_check: + raise TypeError( + "the type of learning_rate should be [int, float or LearningRateDecay], the current type is {}" + .format(learning_rate)) + self.learning_rate = learning_rate + self.warmup_steps = warmup_steps + self.start_lr = start_lr + assert end_lr > start_lr, "end_lr {} must be greater than start_lr {}".format( + end_lr, start_lr) + self.lr_ratio_before_warmup = (float(end_lr) - + float(start_lr)) / float(warmup_steps) + + def step(self): + base_lr = self.learning_rate + if isinstance(self.learning_rate, LearningRateDecay): + base_lr = base_lr() + + from .. import layers + if self.step_num < self.warmup_steps: + return self.lr_ratio_before_warmup * self.step_num + self.start_lr + else: + return base_lr + + +class ReduceLROnPlateau(LearningRateDecay): + """ + :api_attr: imperative + + Reduce learning rate when ``loss`` has stopped descending. Models often benefit from reducing the learning rate + by 2 to 10 times once model performance has no longer improvement. + + The ``loss`` is the one which has been pass into ``step`` , it must be 1-D Tensor with shape [1]. When ``loss`` + stop descending for a ``patience`` number of epochs, the learning rate will be reduced to ``learning_rate * decay_rate`` . + (Specially, ``mode`` can also be set to ``'max`` , in this case, when ``loss`` stop ascending for a ``patience`` number + of epochs, the learning rate will be reduced.) + + In addition, After each reduction, it will wait a ``cooldown`` number of epochs before resuming normal operation. + + Args: + learning_rate (Variable|float|int): The initial learning rate. It can be set to python float or int number. + If the type is Variable, it should be 1-D Tensor with shape [1], the data type can be 'float32' or 'float64'. + mode (str, optional): ``'min'`` or ``'max'`` can be selected. Normally, it is ``'min'`` , which means that the + learning rate will reduce when ``loss`` stops descending. Specially, if it's set to ``'max'`` , the learning + rate will reduce when ``loss`` stops ascending. Default: ``'min'`` . + decay_rate (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * decay_rate`` . + It should be less than 1.0. Default: 0.1. + patience (int, optional): When ``loss`` doesn't improve for this number of epochs, learing rate will be reduced. + Default: 10. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False``. + threshold (float, optional): ``threshold`` and ``threshold_mode`` will determine the minimum change of ``loss`` . + This make tiny changes of ``loss`` will be ignored. Default: 1e-4. + threshold_mode (str, optional): ``'rel'`` or ``'abs'`` can be selected. In ``'rel'`` mode, the minimum change of ``loss`` + is ``last_loss * threshold`` , where ``last_loss`` is ``loss`` in last epoch. In ``'abs'`` mode, the minimum + change of ``loss`` is ``threshold`` . Default: ``'rel'`` . + cooldown (int, optional): The number of epochs to wait before resuming normal operation. Default: 0. + min_lr (float, optional): The lower bound of the learning rate after reduction. Default: 0. + eps (float, optional): Minimal decay applied to lr. If the difference between new and old lr is smaller than eps, the update is + ignored. Default: 1e-8. + dtype (str, optional): The data type used to create the learning rate variable. The data type can be set as + 'float32', 'float64'. Default: 'float32'. + + Returns: + Reduced learning rate. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + x = np.random.uniform(-1, 1, [10, 10]).astype("float32") + linear = fluid.dygraph.Linear(10, 10) + input = fluid.dygraph.to_variable(x) + + reduce_lr = fluid.dygraph.ReduceLROnPlateau( + learning_rate = 1.0, + decay_rate = 0.5, + patience = 5, + verbose = True, + cooldown = 3) + adam = fluid.optimizer.Adam( + learning_rate = reduce_lr, + parameter_list = linear.parameters()) + + for epoch in range(10): + total_loss = 0 + for bath_id in range(5): + out = linear(input) + loss = fluid.layers.reduce_mean(out) + total_loss += loss + adam.minimize(loss) + + avg_loss = total_loss/5 + + # adjust learning rate according to avg_loss + reduce_lr.step(avg_loss) + lr = adam.current_step_lr() + print("current avg_loss is %s, current lr is %s" % (avg_loss.numpy()[0], lr)) + + """ + + def __init__(self, + learning_rate, + mode='min', + decay_rate=0.1, + patience=10, + verbose=False, + threshold=1e-4, + threshold_mode='rel', + cooldown=0, + min_lr=0, + eps=1e-8, + dtype='float32'): + super(ReduceLROnPlateau, self).__init__(dtype=dtype) + mode = mode.lower() + if mode not in ['min', 'max']: + raise ValueError('mode ' + mode + ' is unknown!') + self.mode = mode + + if decay_rate >= 1.0: + raise ValueError( + 'new_lr = origin_lr * decay_rate and decay_rate should be < 1.0.' + ) + self.decay_rate = self.create_lr_var(decay_rate) + + threshold_mode = threshold_mode.lower() + if threshold_mode not in ['rel', 'abs']: + raise ValueError('threshold mode ' + threshold_mode + + ' is unknown!') + self.threshold_mode = threshold_mode + check_type(learning_rate, 'learning_rate', (float, int, Variable), + 'ReduceLROnPlateau') + if not isinstance(learning_rate, (float, int, Variable)): + raise TypeError( + "The type of 'learning_rate' in 'ReduceLROnPlateau' must be 'float, int, Variable', but received %s." + % type(learning_rate)) + + self.learning_rate = learning_rate + self.verbose = verbose + self.patience = patience + self.threshold = threshold + self.threshold_mode = threshold_mode + self.cooldown = cooldown + self.min_lr = self.create_lr_var(min_lr) + self.eps = eps + + self.cooldown_counter = 0 + self.best_loss = None + self.num_bad_epochs = 0 + self.epoch_num = 0 + + # "cooldown_counter / best_loss / num_bad_epochs / epoch_num / learning_rate" will be stored. + def _state_keys(self): + self.keys = [ + 'cooldown_counter', 'best_loss', 'num_bad_epochs', 'epoch_num', + 'learning_rate' + ] + + def __call__(self): + if not isinstance(self.learning_rate, Variable): + self.learning_rate = self.create_lr_var(self.learning_rate) + return self.learning_rate + + def step(self, loss): + """ + It should be invoked on each epoch. Update the learning rate in optimizer according to ``loss`` . + The new learning rate will take effect on next call to ``optimizer.minimize`` . + + Args: + loss (Variable): A ``Variable`` that will be monitored to determine whether the learning rate will reduce. + If it stop descending for a ``patience`` number of epochs, the learning rate will reduce. It should + be 1-D Tensor with shape [1]. + Specially, if ``mode`` has been set to ``'max'`` , the learning rate will reduce when it stops ascending. + Returns: + None + + Examples: + Please refer to the example of current LearningRateDecay. + """ + + # loss must be 1-D Tensor with shape [1] + check_type(loss, 'loss', Variable, 'ReduceLROnPlateau.step') + assert len(loss.shape) == 1 and loss.shape[0] == 1, "the loss.shape " \ + "should be (1L,), but the current loss.shape is {}. Maybe that " \ + "you should call paddle.mean to process it first.".format(loss.shape) + + self.epoch_num += 1 + if self.cooldown_counter > 0: + self.cooldown_counter -= 1 + else: + if self.best_loss is None or self._is_better(loss, self.best_loss): + self.best_loss = loss + self.num_bad_epochs = 0 + else: + self.num_bad_epochs += 1 + + if self.num_bad_epochs > self.patience: + from .. import layers + self.cooldown_counter = self.cooldown + self.num_bad_epochs = 0 + new_lr = layers.elementwise_max( + self.learning_rate * self.decay_rate, self.min_lr) + if self.learning_rate - new_lr > self.eps: + if self.verbose: + old_lr = self.learning_rate.numpy()[0] if isinstance( + self.learning_rate, + Variable) else self.learning_rate + print('Epoch {}: reducing learning rate from {} to {}.'. + format(self.epoch_num, old_lr, + new_lr.numpy()[0])) + self.learning_rate = new_lr + + def _is_better(self, current, best): + if self.mode == 'min' and self.threshold_mode == 'rel': + return current < best - best * self.threshold + + elif self.mode == 'min' and self.threshold_mode == 'abs': + return current < best - self.threshold + + elif self.mode == 'max' and self.threshold_mode == 'rel': + return current > best + best * self.threshold + + else: + return current > best + self.threshold + + +class _LearningRateEpochDecay(LearningRateDecay): + """ + :api_attr: imperative + + Base class of learning rate decay, which is updated each epoch. + + Define the common interface of an _LearningRateEpochDecay. + User should not use this class directly, + but need to use one of it's implementation. And invoke method: `epoch()` each epoch. + """ + + def __init__(self, learning_rate, dtype=None): + if not isinstance(learning_rate, (float, int)): + raise TypeError( + "The type of 'learning_rate' must be 'float, int', but received %s." + % type(learning_rate)) + if learning_rate < 0: + raise ValueError("Invalid learning rate: {}".format(learning_rate)) + + self.base_lr = float(learning_rate) + + self.epoch_num = -1 + self.dtype = dtype + if dtype is None: + self.dtype = "float32" + self.learning_rate = self.create_lr_var(self.base_lr) + + self.epoch() + + # For those subclass who overload _LearningRateEpochDecay, "self.epoch_num/learning_rate" will be stored by default. + # you can change it for your subclass. + def _state_keys(self): + self.keys = ['epoch_num', 'learning_rate'] + + def __call__(self): + """ + Return last computed learning rate on current epoch. + """ + if not isinstance(self.learning_rate, Variable): + self.learning_rate = self.create_lr_var(self.learning_rate) + return self.learning_rate + + def epoch(self, epoch=None): + """ + compueted learning_rate and update it when invoked. + """ + if epoch is None: + self.epoch_num += 1 + else: + self.epoch_num = epoch + + self.learning_rate = self.get_lr() + + def get_lr(self): + raise NotImplementedError + + +class StepDecay(_LearningRateEpochDecay): + """ + :api_attr: imperative + + Decays the learning rate of ``optimizer`` by ``decay_rate`` every ``step_size`` number of epoch. + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 + step_size = 30 + decay_rate = 0.1 + + learning_rate = 0.5 if epoch < 30 + learning_rate = 0.05 if 30 <= epoch < 60 + learning_rate = 0.005 if 60 <= epoch < 90 + ... + + Parameters: + learning_rate (float|int): The initial learning rate. It can be set to python float or int number. + step_size (int): Period of learning rate decay. + decay_rate (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * decay_rate`` . + It should be less than 1.0. Default: 0.1. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + with fluid.dygraph.guard(): + x = np.random.uniform(-1, 1, [10, 10]).astype("float32") + linear = fluid.dygraph.Linear(10, 10) + input = fluid.dygraph.to_variable(x) + scheduler = fluid.dygraph.StepDecay(0.5, step_size=3) + adam = fluid.optimizer.Adam(learning_rate = scheduler, parameter_list = linear.parameters()) + + for epoch in range(9): + for batch_id in range(5): + out = linear(input) + loss = fluid.layers.reduce_mean(out) + adam.minimize(loss) + scheduler.epoch() + + print("epoch:{}, current lr is {}" .format(epoch, adam.current_step_lr())) + # epoch:0, current lr is 0.5 + # epoch:1, current lr is 0.5 + # epoch:2, current lr is 0.5 + # epoch:3, current lr is 0.05 + # epoch:4, current lr is 0.05 + # epoch:5, current lr is 0.05 + # epoch:6, current lr is 0.005 + # epoch:7, current lr is 0.005 + # epoch:8, current lr is 0.005 + + """ + + def __init__(self, learning_rate, step_size, decay_rate=0.1): + if not isinstance(step_size, int): + raise TypeError( + "The type of 'step_size' must be 'int', but received %s." % + type(step_size)) + if decay_rate >= 1.0: + raise ValueError('decay_rate should be < 1.0.') + + self.step_size = step_size + self.decay_rate = decay_rate + super(StepDecay, self).__init__(learning_rate) + + def get_lr(self): + decay_rate = self.create_lr_var(self.decay_rate) + i = self.epoch_num // self.step_size + return self.base_lr * (decay_rate**i) + + +class MultiStepDecay(_LearningRateEpochDecay): + """ + :api_attr: imperative + + Decays the learning rate of ``optimizer`` by ``decay_rate`` once ``epoch`` reaches one of the milestones. + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 + milestones = [30, 50] + decay_rate = 0.1 + if epoch < 30: + learning_rate = 0.5 + elif epoch < 50: + learning_rate = 0.05 + else: + learning_rate = 0.005 + + Parameters: + learning_rate (float|int): The initial learning rate. It can be set to python float or int number. + milestones (tuple|list): List or tuple of each boundaries. Must be increasing. + decay_rate (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * decay_rate`` . + It should be less than 1.0. Default: 0.1. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + with fluid.dygraph.guard(): + x = np.random.uniform(-1, 1, [10, 10]).astype("float32") + linear = fluid.dygraph.Linear(10, 10) + input = fluid.dygraph.to_variable(x) + scheduler = fluid.dygraph.MultiStepDecay(0.5, milestones=[3, 5]) + adam = fluid.optimizer.Adam(learning_rate = scheduler, parameter_list = linear.parameters()) + + for epoch in range(6): + for batch_id in range(5): + out = linear(input) + loss = fluid.layers.reduce_mean(out) + adam.minimize(loss) + scheduler.epoch() + + print("epoch:{}, current lr is {}" .format(epoch, adam.current_step_lr())) + # epoch:0, current lr is 0.5 + # epoch:1, current lr is 0.5 + # epoch:2, current lr is 0.5 + # epoch:3, current lr is 0.05 + # epoch:4, current lr is 0.05 + # epoch:5, current lr is 0.005 + + """ + + def __init__(self, learning_rate, milestones, decay_rate=0.1): + if not isinstance(milestones, (tuple, list)): + raise TypeError( + "The type of 'milestones' in 'MultiStepDecay' must be 'tuple, list', but received %s." + % type(milestones)) + + if not all([ + milestones[i] < milestones[i + 1] + for i in range(len(milestones) - 1) + ]): + raise ValueError('The elements of milestones must be incremented') + if decay_rate >= 1.0: + raise ValueError('decay_rate should be < 1.0.') + + self.milestones = milestones + self.decay_rate = decay_rate + super(MultiStepDecay, self).__init__(learning_rate) + + def get_lr(self): + decay_rate = self.create_lr_var(self.decay_rate) + for i in range(len(self.milestones)): + if self.epoch_num < self.milestones[i]: + return self.base_lr * (decay_rate**i) + + return self.base_lr * (decay_rate**len(self.milestones)) + + +class LambdaDecay(_LearningRateEpochDecay): + """ + :api_attr: imperative + + Sets the learning rate of ``optimizer`` to the initial lr times a multiplicative factor, and this multiplicative + factor is computed by function ``lr_lambda`` . ``lr_lambda`` is funciton which receives ``epoch`` . + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 # init learning_rate + lr_lambda = lambda epoch: 0.95 ** epoch + + learning_rate = 0.5 # epoch 0 + learning_rate = 0.475 # epoch 1 + learning_rate = 0.45125 # epoch 2 + + Parameters: + learning_rate (float|int): The initial learning rate. It can be set to python float or int number. + lr_lambda (function): A function which computes a multiplicative factor given an integer parameter ``epoch`` , and + then multiply the initial learning rate by this multiplicative factor. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + with fluid.dygraph.guard(): + x = np.random.uniform(-1, 1, [10, 10]).astype("float32") + linear = fluid.dygraph.Linear(10, 10) + input = fluid.dygraph.to_variable(x) + scheduler = fluid.dygraph.LambdaDecay(0.5, lr_lambda=lambda x: 0.95**x) + adam = fluid.optimizer.Adam(learning_rate = scheduler, parameter_list = linear.parameters()) + + for epoch in range(6): + for batch_id in range(5): + out = linear(input) + loss = fluid.layers.reduce_mean(out) + adam.minimize(loss) + scheduler.epoch() + + print("epoch:%d, current lr is %f" .format(epoch, adam.current_step_lr())) + # epoch:0, current lr is 0.5 + # epoch:1, current lr is 0.475 + # epoch:2, current lr is 0.45125 + + """ + + def __init__(self, learning_rate, lr_lambda): + if not callable(lr_lambda): + raise TypeError( + "The type of 'lr_lambda' in 'LambdaDecay' must be 'function', but received %s." + % type(lr_lambda)) + + self.lr_lambda = lr_lambda + super(LambdaDecay, self).__init__(learning_rate) + + def get_lr(self): + base_lr = self.create_lr_var(self.base_lr) + + return self.base_lr * self.lr_lambda(self.epoch_num) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/math_op_patch.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/math_op_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b12c43fa17bdeca4db2516d3ead356306357d54f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/math_op_patch.py @@ -0,0 +1,456 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from .. import core +from ..framework import Variable, convert_np_dtype_to_dtype_, _varbase_creator, _in_legacy_dygraph, in_dygraph_mode +from ..layers.layer_function_generator import OpProtoHolder +from . import no_grad +from .. import framework + +import numpy as np +import warnings +from paddle import _C_ops, _legacy_C_ops + +_supported_int_dtype_ = [ + core.VarDesc.VarType.UINT8, + core.VarDesc.VarType.INT8, + core.VarDesc.VarType.INT16, + core.VarDesc.VarType.INT32, + core.VarDesc.VarType.INT64, + core.VarDesc.VarType.BOOL, +] + +# NOTE(chenweihang): We currently do not fully support the type promotion +# between tensors. Parting support here is because the interoperation of +# real and complex numbers in paddle quantum is very frequent, such as the +# binary operation between `float` and `complex64`, so we must support the +# correct type promotion on the APIs paddle quantum used. +# Now only check in dygraph (paddle quantum based dygraph) +# Full type promotion support will need to be fully verified later. +_supported_promote_complex_types_ = [ + '__add__', + '__radd__', + '__sub__', + '__rsub__', + '__mul__', + '__rmul__', + '__div__', + '__truediv__', + '__rdiv__', + '__rtruediv__', + '__matmul__', +] + +_complex_dtypes = [ + core.VarDesc.VarType.COMPLEX64, + core.VarDesc.VarType.COMPLEX128, +] + +_already_patch_varbase = False +_already_patch_eager_tensor = False + + +def monkey_patch_math_varbase(): + """ + Similar to monkey_patch_variable. + The difference is, in dygraph mode, use auto-generated op functions for better performance. + """ + + @no_grad + def create_tensor(value, dtype, shape): + if framework._in_eager_mode_: + out = _C_ops.full(shape, value, dtype, + framework._current_expected_place()) + else: + out = _varbase_creator(dtype=dtype) + out = _legacy_C_ops.fill_constant(out, 'dtype', dtype, 'shape', + shape, 'value', value, + 'force_cpu', False) + out.stop_gradient = True + return out + + def create_scalar(value, dtype): + return create_tensor(value, dtype, shape=[1]) + + def astype(self, dtype): + """ + + Cast a Tensor to a specified data type. + + Args: + dtype: The target data type. + + Returns: + Tensor: a new Tensor with target dtype + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + original_tensor = paddle.ones([2, 2]) + print("original tensor's dtype is: {}".format(original_tensor.dtype)) + new_tensor = original_tensor.astype('float32') + print("new tensor's dtype is: {}".format(new_tensor.dtype)) + + """ + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if _in_legacy_dygraph(): + return _legacy_C_ops.cast(self, 'in_dtype', self.dtype, 'out_dtype', + dtype) + return _C_ops.cast(self, dtype) + + def _scalar_elementwise_op_(var, scale, bias): + if framework.in_dygraph_mode(): + return _C_ops.scale(var, float(scale), bias, True) + return _legacy_C_ops.scale(var, 'scale', scale, 'bias', bias) + + def _neg_(var): + return _scalar_elementwise_op_(var, -1.0, 0.0) + + def _float_(var): + numel = np.prod(var.shape) + assert numel == 1, "only one element variable can be converted to float." + tensor = var.value().get_tensor() + assert tensor._is_initialized(), "variable's tensor is not initialized" + return float(var.numpy().flatten()[0]) + + def _long_(var): + numel = np.prod(var.shape) + assert numel == 1, "only one element variable can be converted to long." + tensor = var.value().get_tensor() + assert tensor._is_initialized(), "variable's tensor is not initialized" + return int(var.numpy().flatten()[0]) + + def _int_(var): + numel = np.prod(var.shape) + assert numel == 1, "only one element variable can be converted to int." + tensor = var.value().get_tensor() + assert tensor._is_initialized(), "variable's tensor is not initialized" + return int(var.numpy().flatten()[0]) + + def _len_(var): + if var.type == core.VarDesc.VarType.VOCAB: + return len(var.value().get_map_tensor()) + elif var.type == core.VarDesc.VarType.STRINGS: + return len(var.value().get_string_tensor()) + else: + return var.shape[0] + + def _index_(var): + numel = np.prod(var.shape) + assert numel == 1, "only one element variable can be converted to python index." + tensor = var.value().get_tensor() + assert tensor._is_initialized(), "variable's tensor is not initialized" + return int(var.numpy().flatten()[0]) + + @property + def _ndim_(var): + return len(var.shape) + + @property + def _size_(var): + return np.prod(var.shape) + + @property + def _T_(var): + if len(var.shape) == 1: + return var + perm = [] + for i in range(len(var.shape)): + perm.insert(0, i) + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.transpose2(var, 'axis', perm) + else: + out = _C_ops.transpose(var, perm) + return out + + def _scalar_add_(var, value): + return _scalar_elementwise_op_(var, 1.0, value) + + def _scalar_sub_(var, value): + return _scalar_elementwise_op_(var, 1.0, -value) + + def _scalar_rsub_(var, value): + return _scalar_elementwise_op_(var, -1.0, value) + + def _scalar_mul_(var, value): + return _scalar_elementwise_op_(var, value, 0.0) + + def _scalar_div_(var, value): + return _scalar_elementwise_op_(var, 1.0 / value, 0.0) + + # for binary operator such as elementwise, compare + def _binary_creator_(method_name, + op_type, + reverse=False, + scalar_method=None, + call_final_api=False): + + def __impl__(self, other_var): + # 1. scalar exists cases + # we need combine the tensor.dtype and scalar.dtype, cast correct object + if isinstance(other_var, float): + # in all cases(+, -, *, /, **, //, %), we need cast tensor.dtype to float + if self.dtype in _supported_int_dtype_: + self = astype(self, 'float32') + # here use `scale` replace `elementwise` to get better performance + # but only +, -, *, / can use this method + if scalar_method is not None: + return scalar_method(self, other_var) + elif isinstance(other_var, int): + # in all cases(+, -, *, /, **, //, %), we can cast it to float + # because the output tensor.dtype depend on the type of input tensor + other_var = float(other_var) + # division is a special case + # NOTE(chenweihang): because we cast tensor to float32 instead float64, + # the division result can only guarantee the numerical accuracy of 6 digits + # after the decimal point. The result of numpy calculation is of float64 type, + # so the calculation result here and the calculation result of numpy are + # different after 6 decimal point. If necessary, we can also use float64 here. + # torch's behavior here is consistent with ours + if (op_type == "divide" or op_type == "elementwise_div" + ) and self.dtype in _supported_int_dtype_: + self = astype(self, 'float32') + # here use `scale` replace `elementwise` to get better performance + # but only +, -, *, / can use this method + if scalar_method is not None: + return scalar_method(self, other_var) + else: + # do nothing + pass + + # 2. create varbase for scalar + lhs_dtype = self.dtype + if framework._in_eager_mode_: + other_var_should_be = core.eager.Tensor + else: + other_var_should_be = core.VarBase + if not isinstance(other_var, other_var_should_be): + if isinstance(other_var, complex): + import paddle + other_var = paddle.to_tensor(other_var, dtype='complex64') + else: + if reverse: + other_var = create_tensor(other_var, + dtype=lhs_dtype, + shape=self.shape) + else: + # add fill_op + other_var = create_scalar(value=other_var, + dtype=lhs_dtype) + + # 3. promote types or unify right var type to left var + rhs_dtype = other_var.dtype + if lhs_dtype != rhs_dtype: + if method_name in _supported_promote_complex_types_ and ( + lhs_dtype in _complex_dtypes + or rhs_dtype in _complex_dtypes): + # only when lhs_dtype or rhs_dtype is complex type, + # the dtype will promote, in other cases, directly + # use lhs_dtype, this is consistent will original rule + promote_dtype = core._promote_types_if_complex_exists( + lhs_dtype, rhs_dtype) + self = self if lhs_dtype == promote_dtype else astype( + self, promote_dtype) + other_var = other_var if rhs_dtype == promote_dtype else astype( + other_var, promote_dtype) + else: + warnings.warn( + 'The dtype of left and right variables are not the same, left dtype is {}, but right dtype is {}, the right dtype will convert to {}' + .format(lhs_dtype, rhs_dtype, lhs_dtype)) + other_var = astype(other_var, lhs_dtype) + + if reverse: + tmp = self + self = other_var + other_var = tmp + + if (op_type == "divide" or op_type == "elementwise_div" + ) and self.dtype in _supported_int_dtype_: + self = astype(self, 'float32') + other_var = astype(other_var, 'float32') + + # 4. calculation + axis = -1 + if in_dygraph_mode(): + math_op = getattr(_C_ops, op_type) + else: + math_op = getattr(_legacy_C_ops, op_type) + if call_final_api: + if op_type == "matmul": + return math_op(self, other_var, False, False) + if op_type == "pow": + if isinstance(other_var, core.eager.Tensor): + return _C_ops.elementwise_pow(self, other_var) + else: + return _C_ops.elementwise_pow(self, other_var) + return math_op(self, other_var, -1) + return math_op(self, other_var, 'axis', axis) + + if call_final_api: + comment = "" + else: + comment = OpProtoHolder.instance().get_op_proto(op_type).comment + + __impl__.__doc__ = """ + {0} + Args: + other_var(Tensor|float|int): right hand Tensor + + Returns: + Tensor + """.format(comment) + __impl__.__name__ = method_name + return __impl__ + + varbase_methods = [ + ('__neg__', _neg_), + ('__float__', _float_), + ('__long__', _long_), + ('__int__', _int_), + ('__len__', _len_), + ('__index__', _index_), + ('astype', astype), + ('dim', lambda x: len(x.shape)), + ('ndimension', lambda x: len(x.shape)), + ('ndim', _ndim_), + ('size', _size_), + ('T', _T_), + ('__add__', _binary_creator_('__add__', 'add', False, _scalar_add_, + True)) if framework._in_eager_mode_ else + ('__add__', + _binary_creator_('__add__', 'elementwise_add', False, _scalar_add_)), + ## a+b == b+a. Do not need to reverse explicitly + ('__radd__', + _binary_creator_('__radd__', 'add', False, _scalar_add_, True)) + if framework._in_eager_mode_ else + ('__radd__', + _binary_creator_('__radd__', 'elementwise_add', False, _scalar_add_)), + ('__sub__', + _binary_creator_('__sub__', 'subtract', False, _scalar_sub_, True)) + if framework._in_eager_mode_ else + ('__sub__', + _binary_creator_('__sub__', 'elementwise_sub', False, _scalar_sub_)), + ('__rsub__', + _binary_creator_('__rsub__', 'subtract', True, _scalar_rsub_, True)) + if framework._in_eager_mode_ else + ('__rsub__', + _binary_creator_('__rsub__', 'elementwise_sub', True, _scalar_rsub_)), + ('__mul__', + _binary_creator_('__mul__', 'multiply', False, _scalar_mul_, True)) + if framework._in_eager_mode_ else + ('__mul__', + _binary_creator_('__mul__', 'elementwise_mul', False, _scalar_mul_)), + ## a*b == b*a. Do not need to reverse explicitly + ('__rmul__', + _binary_creator_('__rmul__', 'multiply', False, _scalar_mul_, True)) + if framework._in_eager_mode_ else + ('__rmul__', + _binary_creator_('__rmul__', 'elementwise_mul', False, _scalar_mul_)), + ('__div__', + _binary_creator_('__div__', 'divide', False, _scalar_div_, True)) + if framework._in_eager_mode_ else + ('__div__', + _binary_creator_('__div__', 'elementwise_div', False, _scalar_div_)), + ('__truediv__', + _binary_creator_('__truediv__', 'divide', False, _scalar_div_, True)) + if framework._in_eager_mode_ else + ('__truediv__', + _binary_creator_('__truediv__', 'elementwise_div', False, + _scalar_div_)), + ('__rdiv__', _binary_creator_('__rdiv__', 'divide', True, None, True)) + if framework._in_eager_mode_ else + ('__rdiv__', + _binary_creator_('__rdiv__', 'elementwise_div', True, None)), + ('__rtruediv__', + _binary_creator_('rtruediv__', 'divide', True, None, True)) + if framework._in_eager_mode_ else + ('__rtruediv__', + _binary_creator_('rtruediv__', 'elementwise_div', True, None)), + ('__pow__', _binary_creator_('__pow__', 'pow', False, _C_ops.pow, True)) + if framework._in_eager_mode_ else + ('__pow__', + _binary_creator_('__pow__', 'elementwise_pow', False, None)), + ('__rpow__', _binary_creator_('__rpow__', 'elementwise_pow', True, + None)), + ('__floordiv__', + _binary_creator_('__floordiv__', 'floor_divide', False, None, True)) + if framework._in_eager_mode_ else + ('__floordiv__', + _binary_creator_('__floordiv__', 'elementwise_floordiv', False, None)), + ('__mod__', _binary_creator_('__mod__', 'remainder', False, None, True)) + if framework._in_eager_mode_ else + ('__mod__', + _binary_creator_('__mod__', 'elementwise_mod', False, None)), + ('__matmul__', + _binary_creator_('__matmul__', "matmul", False, None, True)) + if framework._in_eager_mode_ else + ('__matmul__', + _binary_creator_('__matmul__', "matmul_v2", False, None)), + ## for logical compare + ('__eq__', _binary_creator_('__eq__', 'equal', False, None, True)) + if framework._in_eager_mode_ else + ('__eq__', _binary_creator_('__eq__', 'equal', False, None)), + ('__ne__', _binary_creator_('__ne__', 'not_equal', False, None, True)) + if framework._in_eager_mode_ else + ('__ne__', _binary_creator_('__ne__', 'not_equal', False, None)), + ('__lt__', _binary_creator_('__lt__', 'less_than', False, None, True)) + if framework._in_eager_mode_ else + ('__lt__', _binary_creator_('__lt__', 'less_than', False, None)), + ('__le__', _binary_creator_('__le__', 'less_equal', False, None, True)) + if framework._in_eager_mode_ else + ('__le__', _binary_creator_('__le__', 'less_equal', False, None)), + ('__gt__', _binary_creator_('__gt__', 'greater_than', False, None, + True)) if framework._in_eager_mode_ else + ('__gt__', _binary_creator_('__gt__', 'greater_than', False, None)), + ('__ge__', _binary_creator_('__ge__', 'greater_equal', False, None, + True)) if framework._in_eager_mode_ else + ('__ge__', _binary_creator_('__ge__', 'greater_equal', False, None)), + ('__array_ufunc__', None) + ] + + global _already_patch_varbase + global _already_patch_eager_tensor + + if framework._in_eager_mode_: + local_already_patch = _already_patch_eager_tensor + _already_patch_eager_tensor = True + local_tensor = core.eager.Tensor + else: + local_already_patch = _already_patch_varbase + _already_patch_varbase = True + local_tensor = core.VarBase + + if not local_already_patch: + for method in varbase_methods: + method_name = method[0] + method_impl = method[1] + setattr(local_tensor, method_name, method_impl) + else: + import paddle.tensor + # Tensor method from module paddle.tensor + for method_name in paddle.tensor.tensor_method_func: + if hasattr(local_tensor, method_name): continue + method_impl = getattr(paddle.tensor, method_name, None) + if method_impl: setattr(local_tensor, method_name, method_impl) + + for magic_method, origin_method in paddle.tensor.magic_method_func: + impl = getattr(paddle.tensor, origin_method, None) + if impl: setattr(local_tensor, magic_method, impl) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/nn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..e0262fb113eba407a2a0537f291c98c35d739cd8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/nn.py @@ -0,0 +1,3362 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import paddle +from six.moves import reduce +from .. import core +from ..layers import utils +from ..layers import nn as F +from .. import dygraph_utils +from . import layers +from ..framework import Variable, _non_static_mode, OpProtoHolder, Parameter, _dygraph_tracer, _varbase_creator, default_main_program, _global_flags, in_dygraph_mode, _in_legacy_dygraph +from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype +from ..param_attr import ParamAttr +from ..initializer import Normal, Constant, NumpyArrayInitializer +from .. import unique_name +from .layer_object_helper import LayerObjectHelper +from ..data_feeder import check_variable_and_dtype, check_type +import numpy as np +import numbers +import logging +import os +import paddle.utils.deprecated as deprecated +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'Conv2D', 'Conv3D', 'Pool2D', 'Linear', 'BatchNorm', 'Dropout', 'Embedding', + 'GRUUnit', 'InstanceNorm', 'LayerNorm', 'NCE', 'PRelu', + 'BilinearTensorProduct', 'Conv2DTranspose', 'Conv3DTranspose', 'GroupNorm', + 'SpectralNorm', 'TreeConv', 'Flatten' +] + + +class Conv2D(layers.Layer): + r""" + This interface is used to construct a callable object of the ``Conv2D`` class. + For more details, refer to code examples. + The convolution2D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input and + Output are in NCHW format, where N is batch size, C is the number of + the feature map, H is the height of the feature map, and W is the width of the feature map. + Filter's shape is [MCHW] , where M is the number of output feature map, + C is the number of input feature map, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input feature map divided by the groups. + Please refer to UFLDL's `convolution + `_ + for more details. + If bias attribution and activation type are provided, bias is added to the + output of the convolution, and the corresponding activation function is + applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \\sigma (W \\ast X + b) + + Where: + + * :math:`X`: Input value, a ``Tensor`` with NCHW format. + * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] . + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D ``Tensor`` with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Parameters: + num_channels(int): The number of channels in the input image. + num_filters(int): The number of filter. It is as same as the output + feature map. + filter_size (int or tuple): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + stride (int or tuple, optional): The stride size. If stride is a tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: 1. + padding (int or tuple, optional): The padding size. If padding is a tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: 0. + dilation (int or tuple, optional): The dilation size. If dilation is a tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: 1. + groups (int, optional): The groups number of the Conv2D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: 1. + param_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter) + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with :math:`Normal(0.0, std)`, + and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv2d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True. + act (str, optional): Activation type, if it is set to None, activation is not appended. + Default: None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of filter of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Returns: + None + + Raises: + ValueError: if ``use_cudnn`` is not a bool value. + + Examples: + .. code-block:: python + + from paddle.fluid.dygraph.base import to_variable + import paddle.fluid as fluid + from paddle.fluid.dygraph import Conv2D + import numpy as np + + data = np.random.uniform(-1, 1, [10, 3, 32, 32]).astype('float32') + with fluid.dygraph.guard(): + conv2d = Conv2D(3, 2, 3) + data = to_variable(data) + conv = conv2d(data) + + """ + + def __init__(self, + num_channels, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + dtype='float32'): + assert param_attr is not False, "param_attr should not be False here." + super(Conv2D, self).__init__() + + if (core.is_compiled_with_cuda() and paddle.fluid.get_flags( + "FLAGS_conv2d_disable_cudnn")["FLAGS_conv2d_disable_cudnn"]): + use_cudnn = False + + self._num_channels = num_channels + self._groups = groups + self._stride = utils.convert_to_list(stride, 2, 'stride') + self._padding = utils.convert_to_list(padding, 2, 'padding') + self._dilation = utils.convert_to_list(dilation, 2, 'dilation') + self._act = act + if not isinstance(use_cudnn, bool): + raise ValueError("use_cudnn should be True or False") + self._use_cudnn = use_cudnn + self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + self._filter_size = filter_size + self._num_filters = num_filters + self._param_attr = param_attr + self._bias_attr = bias_attr + self._dtype = dtype + + if (self._num_channels == self._groups + and num_filters % self._num_channels == 0 + and not self._use_cudnn and not self._use_mkldnn): + self._l_type = 'depthwise_conv2d' + else: + self._l_type = 'conv2d' + + # NPU only supports depthwise_conv2d when "input_channel = output_channel = groups" + if core.is_compiled_with_npu(): + if (self._num_channels == self._groups + and self._num_channels == self._num_filters): + self._l_type = 'depthwise_conv2d' + else: + self._l_type = 'conv2d' + + self._num_channels = num_channels + if self._groups is None: + num_filter_channels = self._num_channels + else: + if self._num_channels % self._groups != 0: + raise ValueError("num_channels must be divisible by groups.") + num_filter_channels = self._num_channels // self._groups + filter_size = utils.convert_to_list(self._filter_size, 2, 'filter_size') + filter_shape = [self._num_filters, num_filter_channels] + filter_size + + def _get_default_param_initializer(): + filter_elem_num = filter_size[0] * filter_size[ + 1] * self._num_channels + std = (2.0 / filter_elem_num)**0.5 + return Normal(0.0, std, 0) + + self.weight = self.create_parameter( + attr=self._param_attr, + shape=filter_shape, + dtype=self._dtype, + default_initializer=_get_default_param_initializer()) + + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + if in_dygraph_mode() and self._l_type == "conv2d": + pre_bias = _C_ops.conv2d(input, self.weight, self._stride, + self._padding, "EXPLICIT", + self._groups if self._groups else 1, + self._dilation, "NCHW", False, -1, False) + if self.bias is not None: + pre_act = F.elementwise_add(pre_bias, self.bias, axis=1) + else: + pre_act = pre_bias + return dygraph_utils._append_activation_in_dygraph( + pre_act, self._act, use_mkldnn=self._use_mkldnn) + + if _non_static_mode() and (self._l_type == 'conv2d' + or self._l_type == 'depthwise_conv2d'): + attrs = ('strides', self._stride, 'paddings', self._padding, + 'dilations', self._dilation, 'groups', + self._groups if self._groups else 1, 'use_cudnn', + self._use_cudnn, 'use_mkldnn', self._use_mkldnn) + out = _legacy_C_ops.conv2d(input, self.weight, *attrs) + pre_bias = out + + pre_act = dygraph_utils._append_bias_in_dygraph( + pre_bias, self.bias, 1, use_mkldnn=self._use_mkldnn) + return dygraph_utils._append_activation_in_dygraph( + pre_act, self._act, use_mkldnn=self._use_mkldnn) + inputs = { + 'Input': [input], + 'Filter': [self.weight], + } + attrs = { + 'strides': self._stride, + 'paddings': self._padding, + 'dilations': self._dilation, + 'groups': self._groups if self._groups else 1, + 'use_cudnn': self._use_cudnn, + 'use_mkldnn': self._use_mkldnn, + } + + check_variable_and_dtype(input, 'input', + ['float16', 'float32', 'float64'], 'Conv2D') + pre_bias = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + + self._helper.append_op(type=self._l_type, + inputs={ + 'Input': input, + 'Filter': self.weight, + }, + outputs={"Output": pre_bias}, + attrs=attrs) + + if self.bias is not None: + pre_act = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [pre_bias], + 'Y': [self.bias] + }, + outputs={'Out': [pre_act]}, + attrs={ + 'axis': 1, + 'use_mkldnn': self._use_mkldnn + }) + else: + pre_act = pre_bias + + # Currently, we don't support inplace in dygraph mode + return self._helper.append_activation(pre_act, act=self._act) + + +class Conv3D(layers.Layer): + r""" + **Convlution3D Layer** + + The convolution3D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional tensors with a shape of + :math:`[N, C, D, H, W]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. Convlution3D is similar with Convlution2D + but adds one dimension(depth). If bias attribution and activation type are + provided, bias is added to the output of the convolution, and the + corresponding activation function is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)` + + - Output: + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D_{out}&= \\frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\\\ + H_{out}&= \\frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1 + + Parameters: + num_channels(int): The number of channels in the input image. + num_filters(int): The number of filter. It is as same as the output image channel. + filter_size (int|tuple, optional): The filter size. If filter_size is a tuple, + it must contain three integers, (filter_size_D, filter_size_H, filter_size_W). + Otherwise, the filter will be a square, filter_size_depth = filter_size_height + = filter_size_width = filter_size. + stride (int|tuple, optional): The stride size. If stride is a tuple, it must + contain three integers, (stride_D, stride_H, stride_W). Otherwise, the + stride_D = stride_H = stride_W = stride. The default value is 1. + padding (int|tuple, optional): The padding size. If padding is a tuple, it must + contain three integers, (padding_D, padding_H, padding_W). Otherwise, the + padding_D = padding_H = padding_W = padding. The default value is 0. + dilation (int|tuple, optional): The dilation size. If dilation is a tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups (int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1. + param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d. If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. The default value is True. + act (str, optional): Activation type, if it is set to None, activation is not appended. + The default value is None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Returns: + None. + + Raises: + ValueError: If the shapes of input, filter_size, stride, padding and + groups mismatch. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + with fluid.dygraph.guard(): + data = numpy.random.random((5, 3, 12, 32, 32)).astype('float32') + conv3d = fluid.dygraph.nn.Conv3D( + num_channels=3, num_filters=2, filter_size=3, act="relu") + ret = conv3d(fluid.dygraph.base.to_variable(data)) + + """ + + def __init__(self, + num_channels, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + dtype='float32'): + assert param_attr is not False, "param_attr should not be False here." + super(Conv3D, self).__init__() + self._num_channels = num_channels + self._groups = groups + self._stride = utils.convert_to_list(stride, 3, 'stride') + self._padding = utils.convert_to_list(padding, 3, 'padding') + self._dilation = utils.convert_to_list(dilation, 3, 'dilation') + self._act = act + self._use_cudnn = use_cudnn + self._filter_size = filter_size + self._num_filters = num_filters + self._param_attr = param_attr + self._bias_attr = bias_attr + self._dtype = dtype + + if self._groups is None: + num_filter_channels = self._num_channels + else: + if self._num_channels % self._groups != 0: + raise ValueError("num_channels must be divisible by groups.") + num_filter_channels = self._num_channels // self._groups + + filter_size = utils.convert_to_list(self._filter_size, 3, 'filter_size') + filter_shape = [self._num_filters, num_filter_channels] + filter_size + + def _get_default_param_initializer(): + filter_elem_num = filter_size[0] * filter_size[1] * filter_size[ + 2] * self._num_channels + std = (2.0 / filter_elem_num)**0.5 + return Normal(0.0, std, 0) + + self.weight = self.create_parameter( + attr=self._param_attr, + shape=filter_shape, + dtype=self._dtype, + default_initializer=_get_default_param_initializer()) + + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + pre_bias = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + + self._helper.append_op(type='conv3d', + inputs={ + 'Input': input, + 'Filter': self.weight, + }, + outputs={"Output": pre_bias}, + attrs={ + 'strides': self._stride, + 'paddings': self._padding, + 'dilations': self._dilation, + 'groups': + self._groups if self._groups else 1, + 'use_cudnn': self._use_cudnn, + 'use_mkldnn': False + }) + + if self.bias is not None: + pre_act = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [pre_bias], + 'Y': [self.bias] + }, + outputs={'Out': [pre_act]}, + attrs={'axis': 1}) + else: + pre_act = pre_bias + + return self._helper.append_activation(pre_act, act=self._act) + + +class Conv3DTranspose(layers.Layer): + r""" + **Convlution3D transpose layer** + + The convolution3D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCDHW format. Where N is batch size, C is the number of channels, + D is the depth of the feature, H is the height of the feature, and W + is the width of the feature. Parameters(dilations, strides, paddings) are + two elements. These two elements represent height and width, respectively. + The details of convolution transpose layer, please refer to the following + explanation and references `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\\\ + H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\\\ + D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\\\ + + **Note**: + + The conv3d_transpose can be seen as the backward of the conv3d. For conv3d, + when stride > 1, conv3d maps multiple input shape to the same output shape, + so for conv3d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \ + H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output + size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`, + the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`, + conv3d_transpose can compute the kernel size automatically. + + + Parameters: + num_channels(int): The number of channels in the input image. + num_filters(int): The number of the filter. It is as same as the output + image channel. + filter_size(int|tuple): The filter size. If filter_size is a tuple, + it must contain three integers, (filter_size_D, filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + padding(int|tuple, optional): The padding size. The padding argument effectively + adds `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a string, + either 'VALID' or 'SAME' supported, which is the padding algorithm. If `padding` + is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `'NCDHW'`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `'NDHWC'`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + The default value is 0. + stride(int|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a tuple, it must contain three integers, (stride_depth, stride_height, + stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. + The default value is 1. + dilation(int|tuple, optional): The dilation size. If dilation is a tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + The default value is 1. + param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. The default value is None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. The default value is True. + act (str, optional): Activation type, if it is set to None, activation is not appended. + The default value is None. + name(str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Attribute: + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Returns: + None. + + Raises: + ValueError: If the shapes of input, filter_size, stride, padding and + groups mismatch. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + with fluid.dygraph.guard(): + data = numpy.random.random((5, 3, 12, 32, 32)).astype('float32') + conv3dTranspose = fluid.dygraph.nn.Conv3DTranspose( + num_channels=3, + num_filters=12, + filter_size=12, + use_cudnn=False) + ret = conv3dTranspose(fluid.dygraph.base.to_variable(data)) + + """ + + def __init__(self, + num_channels, + num_filters, + filter_size, + padding=0, + stride=1, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + dtype='float32'): + super(Conv3DTranspose, self).__init__() + if not isinstance(use_cudnn, bool): + raise ValueError("use_cudnn should be True or False") + assert param_attr is not False, "param_attr should not be False in conv3d_transpose." + self._padding = utils.convert_to_list(padding, 3, 'padding') + self._stride = utils.convert_to_list(stride, 3, 'stride') + self._dilation = utils.convert_to_list(dilation, 3, 'dilation') + self._param_attr = param_attr + self._num_channels = num_channels + self._filter_size = filter_size + self._groups = 1 if groups is None else groups + self._num_filters = num_filters + self._use_cudnn = use_cudnn + self._bias_attr = bias_attr + self._act = act + self._dtype = dtype + + self._filter_size = utils.convert_to_list( + self._filter_size, 3, 'conv3d_transpose.filter_size') + + filter_shape = [self._num_channels, self._num_filters // self._groups + ] + self._filter_size + self.weight = self.create_parameter(dtype=self._dtype, + shape=filter_shape, + attr=self._param_attr) + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + pre_bias = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type="conv3d_transpose", + inputs={ + 'Input': [input], + 'Filter': [self.weight] + }, + outputs={'Output': pre_bias}, + attrs={ + 'strides': self._stride, + 'paddings': self._padding, + 'dilations': self._dilation, + 'groups': + self._groups if self._groups else 1, + 'use_cudnn': self._use_cudnn + }) + + if self._bias_attr: + pre_act = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [pre_bias], + 'Y': [self.bias] + }, + outputs={'Out': [pre_act]}, + attrs={'axis': 1}) + else: + pre_act = pre_bias + + # Currently, we don't support inplace in imperative mode + return self._helper.append_activation(pre_act, act=self._act) + + +class Pool2D(layers.Layer): + r""" + + This interface is used to construct a callable object of the ``Pool2D`` class. + For more details, refer to code examples. + The pooling2d operation calculates the output based on the input, pool_type and pool_size, pool_stride, + pool_padding parameters.Input and output are in NCHW format, where N is batch size, C is the number of feature map, + H is the height of the feature map, and W is the width of the feature map. + Parameters(ksize, strides, paddings) are two elements. These two elements represent height and width, respectively. + The input(X) size and output(Out) size may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C, H_{in}, W_{in})` + + - Output: + + Output shape: :math:`(N, C, H_{out}, W_{out})` + + If ``ceil_mode`` = False: + + .. math:: + + H_{out} = \\frac{(H_{in} - ksize[0] + 2 * paddings[0])}{strides[0]} + 1 \\\\ + W_{out} = \\frac{(W_{in} - ksize[1] + 2 * paddings[1])}{strides[1]} + 1 + + If ``ceil_mode`` = True: + + .. math:: + + H_{out} = \\frac{(H_{in} - ksize[0] + 2 * paddings[0] + strides[0] - 1)}{strides[0]} + 1 \\\\ + W_{out} = \\frac{(W_{in} - ksize[1] + 2 * paddings[1] + strides[1] - 1)}{strides[1]} + 1 + + If ``exclusive`` = False: + + .. math:: + + hstart &= i * strides[0] - paddings[0] \\\\ + hend &= hstart + ksize[0] \\\\ + wstart &= j * strides[1] - paddings[1] \\\\ + wend &= wstart + ksize[1] \\\\ + Output(i ,j) &= \\frac{sum(Input[hstart:hend, wstart:wend])}{ksize[0] * ksize[1]} + + If ``exclusive`` = True: + + .. math:: + + hstart &= max(0, i * strides[0] - paddings[0])\\\\ + hend &= min(H, hstart + ksize[0]) \\\\ + wstart &= max(0, j * strides[1] - paddings[1]) \\\\ + wend & = min(W, wstart + ksize[1]) \\\\ + Output(i ,j) & = \\frac{sum(Input[hstart:hend, wstart:wend])}{(hend - hstart) * (wend - wstart)} + + Parameters: + pool_size (int or list or tuple, optional): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (pool_size_Height, pool_size_Width). + Otherwise, the pool kernel size will be a square of an int. Default: -1. + pool_type(str, optional) : The pooling type, can be "max" for max-pooling and "avg" for average-pooling. + Default: max. + pool_stride (int or list or tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain two integers, (pool_stride_Height, pool_stride_Width). Otherwise, + the pool stride size will be a square of an int. Default: 1. + pool_padding (int or list or tuple, optional): The padding size for pooling operation. + If ``pool_padding`` is a tuple, + it must contain two integers, (pool_padding_on_Height, pool_padding_on_Width). + Otherwise, the padding size for pooling operation will be a square of an int. Default: 0. + global_pooling (bool, optional): Whether to use the global pooling. If global_pooling = true, + kernel size and paddings will be ignored. Default: False. + use_cudnn (bool, optional): Only used in cudnn kernel, need install cudnn. Default: True. + ceil_mode (bool, optional): Whether to use the ceil function to calculate output height and width. + False is the default. If it is set to False, the floor function will be used. Default: False. + exclusive (bool, optional): Whether to exclude padding points in average pooling mode. Default: True. + data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + ``[batch_size, input_channels, input_height, input_width]``. When it is `"NHWC"`, the data is + stored in the order of: ``[batch_size, input_height, input_width, input_channels]`` + + Returns: + None + + Raises: + ValueError: If ``pool_type`` is not "max" nor "avg". + ValueError: If ``global_pooling`` is False and ``pool_size`` is -1. + ValueError: If ``use_cudnn`` is not a bool value. + ValueError: If ``data_format`` is not "NCHW" nor "NHWC". + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + + with fluid.dygraph.guard(): + data = numpy.random.random((3, 32, 32, 5)).astype('float32') + pool2d = fluid.dygraph.Pool2D(pool_size=2, + pool_type='max', + pool_stride=1, + global_pooling=False) + pool2d_res = pool2d(to_variable(data)) + + """ + + def __init__(self, + pool_size=-1, + pool_type="max", + pool_stride=1, + pool_padding=0, + global_pooling=False, + use_cudnn=True, + ceil_mode=False, + exclusive=True, + data_format="NCHW"): + data_format = data_format.upper() # supprt NHWC, nhwc, etc. + pool_type = pool_type.lower() # supprt max, Max, etc. + if pool_type not in ["max", "avg"]: + raise ValueError( + "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.", + str(pool_type)) + + if global_pooling is False and pool_size == -1: + raise ValueError( + "When the global_pooling is False, pool_size must be passed " + "and be a valid value. Received pool_size: " + str(pool_size)) + + if not isinstance(use_cudnn, bool): + raise ValueError("use_cudnn should be True or False") + + self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format)) + + super(Pool2D, self).__init__() + + self._pool_type = pool_type + self._pool_size = utils.convert_to_list(pool_size, 2, 'pool_size') + self._pool_padding = utils.convert_to_list(pool_padding, 2, + 'pool_padding') + self._pool_stride = utils.convert_to_list(pool_stride, 2, 'pool_stride') + self._global_pooling = global_pooling + self._use_cudnn = use_cudnn + self._ceil_mode = ceil_mode + self._exclusive = exclusive + self._data_format = data_format + self._l_type = 'pool2d' + + def forward(self, input): + if _non_static_mode(): + if not self._use_mkldnn and in_dygraph_mode(): + return _C_ops.pool2d(input, self._pool_size, self._pool_stride, + self._pool_padding, self._ceil_mode, + self._exclusive, self._data_format, + self._pool_type, self._global_pooling, + False, "EXPLICIT", self._use_cudnn) + + attrs = ('pooling_type', self._pool_type, 'ksize', self._pool_size, + 'global_pooling', self._global_pooling, 'strides', + self._pool_stride, 'paddings', self._pool_padding, + 'use_cudnn', self._use_cudnn, 'ceil_mode', self._ceil_mode, + 'use_mkldnn', self._use_mkldnn, 'exclusive', + self._exclusive, 'data_format', self._data_format) + return _legacy_C_ops.pool2d(input, *attrs) + + check_variable_and_dtype( + input, 'input', ['int8', 'uint8', 'float16', 'float32', 'float64'], + 'Pool2D') + + attrs = { + "pooling_type": self._pool_type, + "ksize": self._pool_size, + "global_pooling": self._global_pooling, + "strides": self._pool_stride, + "paddings": self._pool_padding, + "use_cudnn": self._use_cudnn, + "ceil_mode": self._ceil_mode, + "use_mkldnn": self._use_mkldnn, + "exclusive": self._exclusive, + "data_format": self._data_format, + } + inputs = {"X": [input]} + + pool_out = self._helper.create_variable_for_type_inference(self._dtype) + + self._helper.append_op(type=self._l_type, + inputs={"X": input}, + outputs={"Out": pool_out}, + attrs=attrs) + return pool_out + + +class Linear(layers.Layer): + """ + + Fully-connected linear transformation layer: + + .. math:: + + Out = Act({XW + b}) + + where :math:`X` is the input Tensor, :math:`W` and :math:`b` are weight and bias respectively. + + Linear layer takes only one ``Tensor`` input. + The Linear layer multiplies input tensor with weight matrix and + produces an output Tensor of shape [N, *, `output_dim`], + where N is batch size and `*` means any number of additional dimensions. + If ``bias_attr`` is not None, a bias variable will be created and added to the output. + Finally, if ``act`` is not None, it will be applied to the output as well. + + Parameters: + input_dim(int): The number of input units in this layer. + output_dim(int): The number of output units in this layer. + param_attr(ParamAttr or list of ParamAttr, optional): The parameter attribute for learnable + weights(Parameter) of this layer. Default: None. + bias_attr(ParamAttr or list of ParamAttr, optional): The attribute for the bias + of this layer. If it is set to False, no bias will be added to the output units. + If it is set to None, the bias is initialized zero. Default: None. + act(str, optional): Activation to be applied to the output of this layer. Default: None. + dtype(str, optional): Dtype used for weight, it can be "float32" or "float64". Default: "float32". + + Attributes: + **weight** (Parameter): the learnable weights of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Returns: + None + + Examples: + .. code-block:: python + + from paddle.fluid.dygraph.base import to_variable + import paddle.fluid as fluid + from paddle.fluid.dygraph import Linear + import numpy as np + + data = np.random.uniform(-1, 1, [30, 10, 32]).astype('float32') + with fluid.dygraph.guard(): + linear = Linear(32, 64) + data = to_variable(data) + res = linear(data) # [30, 10, 64] + """ + + def __init__(self, + input_dim, + output_dim, + param_attr=None, + bias_attr=None, + act=None, + dtype="float32"): + super(Linear, self).__init__() + self._act = act + self._dtype = dtype + self.weight = self.create_parameter(shape=[input_dim, output_dim], + attr=param_attr, + dtype=dtype, + is_bias=False) + self.bias = self.create_parameter(shape=[output_dim], + attr=bias_attr, + dtype=dtype, + is_bias=True) + + self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + + def forward(self, input): + if _non_static_mode(): + pre_bias = _varbase_creator(dtype=input.dtype) + _legacy_C_ops.matmul(input, self.weight, pre_bias, 'transpose_X', + False, 'transpose_Y', False, "alpha", 1, + "use_mkldnn", self._use_mkldnn) + pre_act = dygraph_utils._append_bias_in_dygraph( + pre_bias, + self.bias, + axis=len(input.shape) - 1, + use_mkldnn=self._use_mkldnn) + + return dygraph_utils._append_activation_in_dygraph( + pre_act, self._act, use_mkldnn=self._use_mkldnn) + + check_variable_and_dtype(input, 'input', + ['float16', 'float32', 'float64'], "Linear") + + attrs = { + "transpose_X": False, + "transpose_Y": False, + "alpha": 1, + "use_mkldnn": self._use_mkldnn, + } + inputs = {"X": [input], "Y": [self.weight]} + + tmp = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type="matmul", + inputs=inputs, + outputs={"Out": tmp}, + attrs=attrs) + if self.bias is not None: + pre_activation = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [tmp], + 'Y': [self.bias] + }, + outputs={'Out': [pre_activation]}, + attrs={ + 'axis': len(input.shape) - 1, + 'use_mkldnn': self._use_mkldnn + }) + else: + pre_activation = tmp + return self._helper.append_activation(pre_activation, act=self._act) + + +class InstanceNorm(layers.Layer): + r""" + This interface is used to construct a callable object of the ``InstanceNorm`` class. + For more details, refer to code examples. + + Can be used as a normalizer function for convolution or fully_connected operations. + The required data format for this layer is one of the following: + + DataLayout: NCHW `[batch, in_channels, in_height, in_width]` + + Refer to `Instance Normalization: The Missing Ingredient for Fast Stylization `_ + for more details. + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \\mu_{\\beta} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW} x_i \\qquad &//\\ + \\ mean\ of\ one\ feature\ map\ in\ mini-batch \\\\ + \\sigma_{\\beta}^{2} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW}(x_i - \\ + \\mu_{\\beta})^2 \\qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\\\ + \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ + \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ + y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift + + Note: + `H` means height of feature map, `W` means width of feature map. + + Parameters: + num_channels(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + param_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. + If the Initializer of the param_attr is not set, the parameter is initialized + one. If it is set to False, will not create param_attr. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm. + If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + If it is set to False, will not create bias_attr. Default: None. + dtype(str, optional): Indicate the data type of the input ``Tensor``, + which can be float32 or float64. Default: float32. + + Returns: + None. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + import paddle + + # x's shape is [1, 3, 1, 2] + x = np.array([[[[1.0, 8.0]], [[10.0, 5.0]], [[4.0, 6.0]]]]).astype('float32') + with fluid.dygraph.guard(): + x = to_variable(x) + instanceNorm = paddle.nn.InstanceNorm(3) + ret = instanceNorm(x) + # ret's shape is [1, 3, 1, 2]; value is [-1 1 0.999999 -0.999999 -0.999995 0.999995] + print(ret) + + """ + + def __init__(self, + num_channels, + epsilon=1e-5, + param_attr=None, + bias_attr=None, + dtype='float32'): + super(InstanceNorm, self).__init__() + + if param_attr == False or bias_attr == False: + assert bias_attr == param_attr, "param_attr and bias_attr must be set to Fasle at the same time in InstanceNorm" + self._epsilon = epsilon + self._param_attr = param_attr + self._bias_attr = bias_attr + self._dtype = dtype + + if param_attr != False and bias_attr != False: + self.scale = self.create_parameter( + attr=self._param_attr, + shape=[num_channels], + dtype=self._dtype, + default_initializer=Constant(1.0), + is_bias=False) + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[num_channels], + dtype=self._dtype, + default_initializer=Constant(0.0), + is_bias=True) + else: + self.scale = None + self.bias = None + + def forward(self, input): + if in_dygraph_mode(): + out = _C_ops.instance_norm(input, self.scale, self.bias, + self._epsilon) + return out + if _in_legacy_dygraph(): + out, _, _ = _legacy_C_ops.instance_norm(input, self.scale, + self.bias, 'epsilon', + self._epsilon) + return out + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + "InstanceNorm") + + attrs = {"epsilon": self._epsilon} + + if self.scale and self.bias: + inputs = {"X": [input], "Scale": [self.scale], "Bias": [self.bias]} + else: + inputs = {"X": [input]} + + saved_mean = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + saved_variance = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + instance_norm_out = self._helper.create_variable_for_type_inference( + self._dtype) + + outputs = { + "Y": [instance_norm_out], + "SavedMean": [saved_mean], + "SavedVariance": [saved_variance] + } + + self._helper.append_op(type="instance_norm", + inputs=inputs, + outputs=outputs, + attrs=attrs) + return instance_norm_out + + +class BatchNorm(layers.Layer): + r""" + + This interface is used to construct a callable object of the ``BatchNorm`` class. + For more details, refer to code examples. + It implements the function of the Batch Normalization Layer and can be used + as a normalizer function for conv2d and fully connected operations. + The data is normalized by the mean and variance of the channel based on the current batch data. + Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing + Internal Covariate Shift `_ + for more details. + + When use_global_stats = False, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad & + //\ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \mu_{\beta})^2 \qquad & + //\ mini-batch\ variance \\ + + - :math:`x` : mini-batch data + - :math:`m` : the size of the mini-batch data + + When use_global_stats = True, the :math:`\\mu_{\\beta}` + and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch. + They are global or running statistics (moving_mean and moving_variance). It usually got from the + pre-trained model. Calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global variance \\ + + The normalization function formula is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable proportional parameter + - :math:`\beta` : trainable deviation parameter + + Parameters: + num_channels(int): Indicate the number of channels of the input ``Tensor``. + act(str, optional): Activation to be applied to the output of batch normalization. Default: None. + is_test (bool, optional): A flag indicating whether it is in test phrase or not. + This flag only has effect on static graph mode. For dygraph mode, please use ``eval()``. + Default: False. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + param_attr(ParamAttr, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr(ParamAttr, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + dtype(str, optional): Indicate the data type of the input ``Tensor``, + which can be float32 or float64. Default: float32. + data_layout(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW. + in_place(bool, optional): Make the input and output of batch norm reuse memory. Default: False. + moving_mean_name(str, optional): The name of moving_mean which store the global Mean. Default: None. + moving_variance_name(str, optional): The name of the moving_variance which store the global Variance. Default: None. + do_model_average_for_mean_and_var(bool, optional): Whether parameter mean and variance should do model + average when model average is enabled. Default: True. + use_global_stats(bool, optional): Whether to use global mean and + variance. In inference or test mode, set use_global_stats to true + or is_test to true, and the behavior is equivalent. + In train mode, when setting use_global_stats True, the global mean + and variance are also used during train period. Default: False. + trainable_statistics(bool, optional): Whether to calculate mean and var in eval mode. In eval mode, when + setting trainable_statistics True, mean and variance will be calculated by current batch statistics. + Default: False. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + + x = np.random.random(size=(3, 10, 3, 7)).astype('float32') + with fluid.dygraph.guard(): + x = to_variable(x) + batch_norm = fluid.BatchNorm(10) + hidden1 = batch_norm(x) + """ + + def __init__(self, + num_channels, + act=None, + is_test=False, + momentum=0.9, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + dtype='float32', + data_layout='NCHW', + in_place=False, + moving_mean_name=None, + moving_variance_name=None, + do_model_average_for_mean_and_var=True, + use_global_stats=False, + trainable_statistics=False): + super(BatchNorm, self).__init__() + self._param_attr = param_attr + self._bias_attr = bias_attr + self._act = act + self._use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + + assert bias_attr is not False, "bias_attr should not be False in batch_norm." + + if dtype == "float16": + self._dtype = "float32" + else: + self._dtype = dtype + + param_shape = [num_channels] + + # create parameter + self.weight = self.create_parameter(attr=self._param_attr, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(1.0)) + self.weight.stop_gradient = use_global_stats and self._param_attr.learning_rate == 0. + + self.bias = self.create_parameter(attr=self._bias_attr, + shape=param_shape, + dtype=self._dtype, + is_bias=True) + self.bias.stop_gradient = use_global_stats and self._param_attr.learning_rate == 0. + + self._mean = self.create_parameter(attr=ParamAttr( + name=moving_mean_name, + initializer=Constant(0.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var), + shape=param_shape, + dtype=self._dtype) + self._mean.stop_gradient = True + + self._variance = self.create_parameter(attr=ParamAttr( + name=moving_variance_name, + initializer=Constant(1.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var), + shape=param_shape, + dtype=self._dtype) + self._variance.stop_gradient = True + + self._in_place = in_place + self._data_layout = data_layout + self._momentum = momentum + self._epsilon = epsilon + self._is_test = is_test + self._fuse_with_relu = False + self._use_global_stats = use_global_stats + self._trainable_statistics = trainable_statistics + + def forward(self, input): + # create output + # mean and mean_out share the same memory + mean_out = self._mean + # variance and variance out share the same memory + variance_out = self._variance + + if _non_static_mode(): + if in_dygraph_mode(): + batch_norm_out, t1, t2, t3, t4, _ = _C_ops.batch_norm( + input, self.weight, self.bias, self._mean, self._variance, + self._momentum, self._epsilon, self._data_layout, + not self.training, self._use_global_stats, + self._trainable_statistics, False) + return dygraph_utils._append_activation_in_dygraph( + batch_norm_out, act=self._act, use_mkldnn=self._use_mkldnn) + + elif _in_legacy_dygraph(): + attrs = ("momentum", self._momentum, "epsilon", self._epsilon, + "is_test", not self.training, "data_layout", + self._data_layout, "use_mkldnn", self._use_mkldnn, + "fuse_with_relu", self._fuse_with_relu, + "use_global_stats", self._use_global_stats, + 'trainable_statistics', self._trainable_statistics) + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.batch_norm( + input, self.weight, self.bias, self._mean, self._variance, + None, mean_out, variance_out, *attrs) + + return dygraph_utils._append_activation_in_dygraph( + batch_norm_out, act=self._act, use_mkldnn=self._use_mkldnn) + + check_variable_and_dtype(input, 'input', + ['float16', 'float32', 'float64'], 'BatchNorm') + + attrs = { + "momentum": self._momentum, + "epsilon": self._epsilon, + "is_test": self._is_test, + "data_layout": self._data_layout, + "use_mkldnn": False, + "fuse_with_relu": self._fuse_with_relu, + "use_global_stats": self._use_global_stats, + "trainable_statistics": self._trainable_statistics, + } + + inputs = { + "X": [input], + "Scale": [self.weight], + "Bias": [self.bias], + "Mean": [self._mean], + "Variance": [self._variance] + } + + saved_mean = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + saved_variance = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + reserve_space = self._helper.create_variable_for_type_inference( + dtype=self._helper.input_dtype(input), stop_gradient=True) + + batch_norm_out = input if self._in_place else self._helper.create_variable_for_type_inference( + self._dtype) + + outputs = { + "Y": [batch_norm_out], + "MeanOut": [mean_out], + "VarianceOut": [variance_out], + "SavedMean": [saved_mean], + "SavedVariance": [saved_variance] + } + if reserve_space is not None: + outputs["ReserveSpace"] = [reserve_space] + + self._helper.append_op(type="batch_norm", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + # Currently, we don't support inplace in dygraph mode + return self._helper.append_activation(batch_norm_out, self._act) + + +class Dropout(layers.Layer): + """ + This interface is used to construct a callable object of the ``Dropout`` class. + For more details, refer to code examples. + + Drop or keep each element of input independently. Dropout is a regularization + technique for reducing overfitting by preventing neuron co-adaption during + training. The dropout operator randomly sets (according to the given dropout + probability) the outputs of some units to zero, while others are remain + unchanged. + + Dropout layer can be removed for efficiency concern. + + Parameters: + p (float, optional): Probability of setting units to zero. Default: 0.5 + seed (int, optional): A Python integer used to create random seeds. If this + parameter is set to None, a random seed is used. + NOTE: If an integer seed is given, always the same output + units will be dropped. DO NOT use a fixed seed in training. Default: None. + dropout_implementation(string, optional): ['downgrade_in_infer'(default)|'upscale_in_train'] + + 1. downgrade_in_infer(default), downgrade the outcome at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + + (mask is a tensor same shape with input, value is 0 or 1 + ratio of 0 is dropout_prob) + 2. upscale_in_train, upscale the outcome at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + (mask is a tensor same shape with input, value is 0 or 1 + ratio of 0 is p) + is_test (bool, optional): A flag indicating whether it is in test phrase or not. + This flag only has effect on static graph mode. For dygraph mode, please use ``eval()``. + Default: False. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + + x = np.random.random(size=(3, 10, 3, 7)).astype('float32') + with fluid.dygraph.guard(): + x = to_variable(x) + m = fluid.dygraph.Dropout(p=0.5) + droped_train = m(x) + # switch to eval mode + m.eval() + droped_eval = m(x) + """ + + def __init__(self, + p=0.5, + seed=None, + dropout_implementation="downgrade_in_infer", + is_test=False): + super(Dropout, self).__init__() + assert isinstance(p, (float, int)), "p argument should be a number" + assert 0 <= p <= 1, "p argument should between 0 and 1" + self._dropout_prob = p + assert seed is None or isinstance( + seed, int), "seed argument should be None or a integer" + self._seed = seed + assert dropout_implementation in ( + 'downgrade_in_infer', 'upscale_in_train' + ), "dropout_implementation argument should be 'downgrade_in_infer' or 'upscale_in_train'" + self._dropout_implementation = dropout_implementation + self._is_test = is_test + + def forward(self, input): + # fast return for p == 0 + if self._dropout_prob == 0: + return input + prog = default_main_program() + if (self._seed is None or self._seed == 0) and prog.random_seed != 0: + self._seed = prog.random_seed + attrs = { + 'dropout_prob': self._dropout_prob, + 'is_test': + not self.training if _non_static_mode() else self._is_test, + 'fix_seed': self._seed is not None, + 'seed': self._seed if self._seed is not None else 0, + 'dropout_implementation': self._dropout_implementation, + } + + if _non_static_mode(): + attrs = sum(attrs.items(), ()) + out, mask = _legacy_C_ops.dropout(input, *attrs) + return out + + out = self._helper.create_variable_for_type_inference(dtype=input.dtype) + mask = self._helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) + + self._helper.append_op(type='dropout', + inputs={'X': [input]}, + outputs={ + 'Out': [out], + 'Mask': [mask] + }, + attrs=attrs) + return out + + +class Embedding(layers.Layer): + r""" + :alias_main: paddle.nn.Embedding + :alias: paddle.nn.Embedding,paddle.nn.layer.Embedding,paddle.nn.layer.common.Embedding + :old_api: paddle.fluid.dygraph.Embedding + + **Embedding Layer** + + This interface is used to construct a callable object of the ``Embedding`` class. + For specific usage, refer to code examples. It implements the function of the Embedding Layer. + This layer is used to lookup embeddings vector of ids provided by :attr:`input` . + It automatically constructs a 2D embedding matrix based on the + input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` . + + The shape of output Tensor is generated by appending an emb_size dimension to the + last dimension of the input Tensor shape. + + **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , + otherwise the program will throw an exception and exit. + + .. code-block:: text + + Case 1: + + input is a Tensor. padding_idx = -1 + input.data = [[1, 3], [2, 4], [4, 127] + input.shape = [3, 2] + Given size = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when ids is 127. + + Parameters: + size(tuple|list): The shape of the look up table parameter. It should have two elements which indicate the size + of the dictionary of embeddings and the size of each embedding vector respectively. + is_sparse(bool): The flag indicating whether to use sparse update. This parameter only + affects the performance of the backwards gradient update. It is recommended to set + True because sparse update is faster. But some optimizer does not support sparse update, + such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` , + :ref:`api_fluid_optimizer_DecayedAdagradOptimizer` , :ref:`api_fluid_optimizer_FtrlOptimizer` , + :ref:`api_fluid_optimizer_LambOptimizer` and :ref:`api_fluid_optimizer_LarsMomentumOptimizer` . + In these case, is_sparse must be False. Default: False. + is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used + in multi-machine distributed CPU training. Default: False. + padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup + encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. + If set None, it makes no effect to output. Default: None. + param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . In addition, + user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. + The local word vector needs to be transformed into numpy format, and the shape of local word + vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer` + is used to load custom or pre-trained word vectors. See code example 2 for details. + dtype(np.dtype|core.VarDesc.VarType|str): It refers to the data type of output Tensor. + It must be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + Returns: + Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` . + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.dygraph.base as base + import numpy as np + + # example 1 + inp_word = np.array([[2, 3, 5], [4, 2, 1]]).astype('int64') + inp_word.shape # [2, 3] + dict_size = 20 + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding( + size=[dict_size, 32], + param_attr='emb.w', + is_sparse=False) + static_rlt3 = emb(base.to_variable(inp_word)) + static_rlt3.shape # [2, 3, 32] + + # example 2: load custom or pre-trained word vectors + weight_data = np.random.random(size=(128, 100)) # word vectors with numpy format + w_param_attrs = fluid.ParamAttr( + name="emb_weight", + learning_rate=0.5, + initializer=fluid.initializer.NumpyArrayInitializer(weight_data), + trainable=True) + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding( + size=[128, 100], + param_attr= w_param_attrs, + is_sparse=False) + static_rlt3 = emb(base.to_variable(inp_word)) + """ + + def __init__(self, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32'): + super(Embedding, self).__init__() + self._size = size + self._is_sparse = is_sparse + self._is_distributed = is_distributed + self._padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( + size[0] + padding_idx) + + self._param_attr = param_attr + self._dtype = dtype + self._remote_prefetch = self._is_sparse and (not self._is_distributed) + if self._remote_prefetch: + assert self._is_sparse is True and self._is_distributed is False + + self.weight = self.create_parameter(attr=self._param_attr, + shape=self._size, + dtype=self._dtype, + is_bias=False) + + def forward(self, input): + if _non_static_mode(): + return _legacy_C_ops.lookup_table_v2( + self.weight, input, 'is_sparse', self._is_sparse, + 'is_distributed', self._is_distributed, 'remote_prefetch', + self._remote_prefetch, 'padding_idx', self._padding_idx) + + check_variable_and_dtype(input, 'input', + ['uint8', 'int8', 'int16', 'int32', 'int64'], + 'Embedding') + attrs = { + 'is_sparse': self._is_sparse, + 'is_distributed': self._is_distributed, + 'remote_prefetch': self._remote_prefetch, + 'padding_idx': self._padding_idx + } + + out = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type='lookup_table_v2', + inputs={ + 'Ids': input, + 'W': self.weight + }, + outputs={'Out': out}, + attrs=attrs) + + return out + + +class LayerNorm(layers.Layer): + r""" + :alias_main: paddle.nn.LayerNorm + :alias: paddle.nn.LayerNorm,paddle.nn.layer.LayerNorm,paddle.nn.layer.norm.LayerNorm + :old_api: paddle.fluid.dygraph.LayerNorm + + This interface is used to construct a callable object of the ``LayerNorm`` class. + For more details, refer to code examples. + It implements the function of the Layer Normalization Layer and can be applied to mini-batch input data. + Refer to `Layer Normalization `_ + + The formula is as follows: + + .. math:: + + \\mu & = \\frac{1}{H}\\sum_{i=1}^{H} x_i + + \\sigma & = \\sqrt{\\frac{1}{H}\sum_{i=1}^{H}{(x_i - \\mu)^2} + \\epsilon} + + y & = f(\\frac{g}{\\sigma}(x - \\mu) + b) + + - :math:`x`: the vector representation of the summed inputs to the neurons in that layer. + - :math:`H`: the number of hidden units in a layers + - :math:`\\epsilon`: the small value added to the variance to prevent division by zero. + - :math:`g`: the trainable scale parameter. + - :math:`b`: the trainable bias parameter. + + Parameters: + normalized_shape(int or list or tuple): Input shape from an expected input of + size :math:`[*, normalized_shape[0], normalized_shape[1], ..., normalized_shape[-1]]`. + If it is a single integer, this module will normalize over the last dimension + which is expected to be of that specific size. + scale(bool, optional): Whether to learn the adaptive gain :math:`g` after + normalization. Default: True. + shift(bool, optional): Whether to learn the adaptive bias :math:`b` after + normalization. Default: True. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + gain :math:`g`. If :attr:`scale` is False, :attr:`param_attr` is + omitted. If :attr:`scale` is True and :attr:`param_attr` is None, + a default :code:`ParamAttr` would be added as scale. The + :attr:`param_attr` is initialized as 1 if it is added. Default: None. + bias_attr(ParamAttr, optional): The parameter attribute for the learnable + bias :math:`b`. If :attr:`shift` is False, :attr:`bias_attr` is + omitted. If :attr:`shift` is True and :attr:`param_attr` is None, + a default :code:`ParamAttr` would be added as bias. The + :attr:`bias_attr` is initialized as 0 if it is added. Default: None. + act(str, optional): Activation to be applied to the output of layer normalization. + Default: None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy + + x = numpy.random.random((3, 32, 32)).astype('float32') + with fluid.dygraph.guard(): + x = to_variable(x) + layerNorm = fluid.LayerNorm([32, 32]) + ret = layerNorm(x) + + """ + + def __init__(self, + normalized_shape, + scale=True, + shift=True, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + act=None, + dtype='float32'): + super(LayerNorm, self).__init__() + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = [normalized_shape] + + self._normalized_shape = list(normalized_shape) + self._scale = scale + self._shift = shift + self._epsilon = epsilon + self._param_attr = param_attr + self._bias_attr = bias_attr + self._act = act + self._dtype = dtype + param_shape = [np.prod(self._normalized_shape)] + if self._scale: + self.weight = self.create_parameter( + attr=self._param_attr, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(1.0)) + else: + if self._param_attr: + logging.warn("param_attr are only available with scale is True") + self.weight = None + + if self._shift: + assert self._bias_attr is not False + self.bias = self.create_parameter(attr=self._bias_attr, + shape=param_shape, + dtype=self._dtype, + is_bias=True) + else: + if self._bias_attr: + logging.warn("bias_attr are only available with shift is True") + self.bias = None + + def forward(self, input): + input_shape = list(input.shape) + input_ndim = len(input_shape) + normalized_ndim = len(self._normalized_shape) + self._begin_norm_axis = input_ndim - normalized_ndim + if input_ndim < normalized_ndim or input_shape[ + self._begin_norm_axis:] != self._normalized_shape: + str_normalized_shape = str(self._normalized_shape) + raise ValueError('Given normalized_shape is ' + + str_normalized_shape + + ', expected input with shape [*, ' + + str_normalized_shape[1:] + + ', but got input shape ' + str(input_shape)) + + if _non_static_mode(): + if in_dygraph_mode(): + pre_act, _, _, = _C_ops.layer_norm(input, self.weight, + self.bias, self._epsilon, + self._begin_norm_axis, False) + return dygraph_utils._append_activation_in_dygraph( + pre_act, act=self._act) + else: + pre_act, _, _ = _legacy_C_ops.layer_norm( + input, self.weight, self.bias, 'epsilon', self._epsilon, + 'begin_norm_axis', self._begin_norm_axis) + return dygraph_utils._append_activation_in_dygraph( + pre_act, act=self._act) + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'LayerNorm') + + inputs = dict() + inputs['X'] = [input] + if self._scale: + inputs['Scale'] = [self.weight] + if self._shift: + inputs['Bias'] = [self.bias] + attrs = { + "epsilon": self._epsilon, + "begin_norm_axis": self._begin_norm_axis + } + + # create output + mean_out = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + variance_out = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + layer_norm_out = self._helper.create_variable_for_type_inference( + self._dtype) + + self._helper.append_op(type="layer_norm", + inputs=inputs, + outputs={ + "Y": layer_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={ + "epsilon": self._epsilon, + "begin_norm_axis": self._begin_norm_axis + }) + + return self._helper.append_activation(layer_norm_out, act=self._act) + + +class GRUUnit(layers.Layer): + """ + **GRU unit layer** + + It creates a callable object from GRUUnit class. + If origin_mode is True, then the equation of a gru step is from paper + `Learning Phrase Representations using RNN Encoder-Decoder for Statistical + Machine Translation `_ + + .. math:: + u_t & = actGate(xu_{t} + W_u h_{t-1} + b_u) + + r_t & = actGate(xr_{t} + W_r h_{t-1} + b_r) + + m_t & = actNode(xm_t + W_c dot(r_t, h_{t-1}) + b_m) + + h_t & = dot(u_t, h_{t-1}) + dot((1-u_t), m_t) + + If origin_mode is False, then the equation of a gru step is from paper + `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence + Modeling `_ + + .. math:: + u_t & = actGate(xu_{t} + W_u h_{t-1} + b_u) + + r_t & = actGate(xr_{t} + W_r h_{t-1} + b_r) + + m_t & = actNode(xm_t + W_c dot(r_t, h_{t-1}) + b_m) + + h_t & = dot((1-u_t), h_{t-1}) + dot(u_t, m_t) + + + The inputs of gru unit includes :math:`z_t`, :math:`h_{t-1}`. In terms + of the equation above, the :math:`z_t` is split into 3 parts - + :math:`xu_t`, :math:`xr_t` and :math:`xm_t`. This means that in order to + implement a full GRU unit operator for an input, a fully + connected layer has to be applied, such that :math:`z_t = W_{fc}x_t`. + + The terms :math:`u_t` and :math:`r_t` represent the update and reset gates + of the GRU cell. Unlike LSTM, GRU has one lesser gate. However, there is + an intermediate candidate hidden output, which is denoted by :math:`m_t`. + This layer has three outputs :math:`h_t`, :math:`dot(r_t, h_{t-1})` + and concatenation of :math:`u_t`, :math:`r_t` and :math:`m_t`. + + Parameters: + size (int): The input dimension value. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + hidden-hidden weight matrix. + + **Note**: + + 1. The shape of the weight matrix is :math:`[T, 3*D]`, where D is the hidden size. + 2. All elements in the weight matrix can be divided into two parts. The first + part are weights of the update gate and reset gate with shape :math:`[D, 2*D]`, + and the second part are weights for candidate hidden state with shape :math:`[D, D]`. + + + If it is set to None or one attribute of ParamAttr, gru_unit will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. The default + value is None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias + of GRU.Note that the bias with :math:`[1, 3*D]` concatenates + the bias in the update gate, reset gate and candidate calculations. + If it is set to False, no bias will be applied to the update gate, + reset gate and candidate calculations. If it is set to None or one + attribute of ParamAttr, gru_unit will create ParamAttr as + bias_attr. If the Initializer of the bias_attr is not set, the bias + is initialized zero. The default value is None. + activation (str): The activation type for cell (actNode). + The default value is 'tanh'. + gate_activation (str): The activation type for gates (actGate). + The default value is 'sigmoid'. + dtype(str): The dtype of the layers. The data type can be set as + 'float32', 'float64'. The default value is 'float32'. + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Returns: + tuple: The hidden value, reset-hidden value and gate values. The hidden value + is a 2-D tensor with shape :math:`[T, D]` . The reset-hidden value is a + 2-D tensor with shape :math:`[T, D]` . The gate value is a 2-D tensor with + shape :math:`[T, 3*D]`. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.dygraph.base as base + import numpy + + lod = [[2, 4, 3]] + D = 5 + T = sum(lod[0]) + + input = numpy.random.rand(T, 3 * D).astype('float32') + hidden_input = numpy.random.rand(T, D).astype('float32') + with fluid.dygraph.guard(): + x = numpy.random.random((3, 32, 32)).astype('float32') + gru = fluid.dygraph.GRUUnit(size=D * 3) + dy_ret = gru( + base.to_variable(input), base.to_variable(hidden_input)) + + """ + + def __init__(self, + size, + param_attr=None, + bias_attr=None, + activation='tanh', + gate_activation='sigmoid', + origin_mode=False, + dtype='float32'): + super(GRUUnit, self).__init__() + self._bias_attr = bias_attr + activation_dict = dict( + identity=0, + sigmoid=1, + tanh=2, + relu=3, + ) + self.activation = activation_dict[activation] + self.gate_activation = activation_dict[gate_activation] + + self._dtype = dtype + size = size // 3 + # create weight + self.weight = self.create_parameter(attr=param_attr, + shape=[size, 3 * size], + dtype=dtype) + + # create bias + bias_size = [1, 3 * size] + self._bias_size = bias_size + self.bias = self.create_parameter(attr=bias_attr, + shape=bias_size, + dtype=dtype, + is_bias=True) + + def forward(self, input, hidden): + if _non_static_mode(): + gate, reset_hidden_pre, updated_hidden = _legacy_C_ops.gru_unit( + input, hidden, self.weight, self.bias, 'activation', + self.activation, 'gate_activation', self.gate_activation) + return updated_hidden, reset_hidden_pre, gate + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'GRUUnit') + check_variable_and_dtype(hidden, 'hidden', ['float32', 'float64'], + 'GRUUnit') + inputs = { + 'Input': [input], + 'HiddenPrev': [hidden], + 'Weight': [self.weight] + } + if self.bias is not None: + inputs['Bias'] = [self.bias] + gate = self._helper.create_variable_for_type_inference(self._dtype) + reset_hidden_pre = self._helper.create_variable_for_type_inference( + self._dtype) + updated_hidden = self._helper.create_variable_for_type_inference( + self._dtype) + self._helper.append_op(type='gru_unit', + inputs=inputs, + outputs={ + 'Gate': gate, + 'ResetHiddenPrev': reset_hidden_pre, + 'Hidden': updated_hidden, + }, + attrs={ + 'activation': self.activation, + 'gate_activation': self.gate_activation, + }) + + return updated_hidden, reset_hidden_pre, gate + + +class NCE(layers.Layer): + """ + This interface is used to construct a callable object of the ``NCE`` class. + For more details, refer to code examples. + It implements the function of the ``NCE`` loss function. + By default this function uses a uniform distribution for sampling, and it + compute and return the noise-contrastive estimation training loss. See + `Noise-contrastive estimation: A new estimation principle for unnormalized statistical models `_ . + + Parameters: + num_total_classes (int): Total number of classes in all samples. + dim (int): Dimension of input (possibly embedding dim). + param_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter) + of nce. If it is set to None or one attribute of ParamAttr, nce + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr or bool, optional): The attribute for the bias of nce. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, nce + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + num_neg_samples (int, optional): The number of negative classes. The default value is 10. + sampler (str, optional): The sampler used to sample class from negative classes. + It can be 'uniform', 'log_uniform' or 'custom_dist'. + default: 'uniform'. + custom_dist (float[], optional): A float[] with size=num_total_classes. + It is used when sampler is set to 'custom_dist'. + custom_dist[i] is the probability of i-th class to be sampled. + Default: None. + seed (int, optional): The seed used in sampler. Default: 0. + is_sparse(bool, optional): The flag indicating whether to use sparse update. If is_sparse is True, the weight@GRAD and bias@GRAD will be changed to SelectedRows. Default: False. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Returns: + None + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + window_size = 5 + dict_size = 20 + label_word = int(window_size // 2) + 1 + inp_word = np.array([[1], [2], [3], [4], [5]]).astype('int64') + nid_freq_arr = np.random.dirichlet(np.ones(20) * 1000).astype('float32') + + with fluid.dygraph.guard(): + words = [] + for i in range(window_size): + words.append(fluid.dygraph.base.to_variable(inp_word[i])) + + emb = fluid.Embedding( + size=[dict_size, 32], + param_attr='emb.w', + is_sparse=False) + + embs3 = [] + for i in range(window_size): + if i == label_word: + continue + + emb_rlt = emb(words[i]) + embs3.append(emb_rlt) + + embs3 = fluid.layers.concat(input=embs3, axis=1) + nce = fluid.NCE( + num_total_classes=dict_size, + dim=embs3.shape[1], + num_neg_samples=2, + sampler="custom_dist", + custom_dist=nid_freq_arr.tolist(), + seed=1, + param_attr='nce.w', + bias_attr='nce.b') + + wl = fluid.layers.unsqueeze(words[label_word], axes=[0]) + nce_loss3 = nce(embs3, wl) + + """ + + def __init__(self, + num_total_classes, + dim, + sample_weight=None, + param_attr=None, + bias_attr=None, + num_neg_samples=None, + sampler="uniform", + custom_dist=None, + seed=0, + is_sparse=False, + dtype='float32'): + super(NCE, self).__init__() + self._param_attr = param_attr + self._bias_attr = bias_attr + self._num_total_classes = num_total_classes + self._dtype = dtype + self._inputs = dict() + self._inputs['SampleWeight'] = sample_weight if sample_weight is not None else [] + if sampler == "uniform": + sampler = 0 + elif sampler == "log_uniform": + sampler = 1 + elif sampler == "custom_dist": + assert custom_dist is not None + # assert isinstance(custom_dist, Variable) + + custom_dist_len = len(custom_dist) + alias_probs_ = [0] * custom_dist_len + alias_ = [0] * custom_dist_len + bigs = [] + littles = [] + for i in range(custom_dist_len): + normal_prob = custom_dist[i] * custom_dist_len + if normal_prob - 1.0 > 0: + bigs.append((i, normal_prob)) + elif 1.0 - normal_prob > 0: + littles.append((i, normal_prob)) + else: + alias_probs_[i] = normal_prob + alias_[i] = -1 + + while len(bigs) and len(littles): + big = bigs.pop(0) + little = littles.pop(0) + + big_idx = big[0] + big_prob = big[1] + + alias_probs_[little[0]] = little[1] + alias_[little[0]] = big_idx + big_left = big[1] + little[1] - 1 + if big_left - 1.0 > 0: + bigs.append((big_idx, big_left)) + elif 1.0 - big_left > 0: + littles.append((big_idx, big_left)) + else: + alias_probs_[big_idx] = big_left + alias_[big_idx] = -1 + + if len(bigs): + big = bigs.pop(0) + alias_probs_[big[0]] = 1.0 + alias_[big[0]] = -1 + if len(littles): + little = littles.pop(0) + alias_probs_[little[0]] = 1.0 + alias_[little[0]] = -1 + + def _init_by_numpy_array(numpy_array): + ret = self.create_parameter( + attr=ParamAttr(), + shape=numpy_array.shape, + dtype=numpy_array.dtype, + default_initializer=NumpyArrayInitializer(numpy_array)) + ret.stop_gradient = True + return ret + + self._inputs['CustomDistProbs'] = _init_by_numpy_array( + np.array(custom_dist).astype('float32')) + self._inputs['CustomDistAlias'] = _init_by_numpy_array( + np.array(alias_).astype('int32')) + self._inputs['CustomDistAliasProbs'] = _init_by_numpy_array( + np.array(alias_probs_).astype('float32')) + sampler = 2 + else: + raise Exception("Unsupported sampler type.") + + if num_neg_samples is None: + num_neg_samples = 10 + else: + num_neg_samples = int(num_neg_samples) + self._num_neg_samples = num_neg_samples + remote_prefetch = is_sparse + print( + "With sparse mode, if your models has only small parameter prefetch may cause speed down" + ) + self._attrs = { + 'num_total_classes': int(num_total_classes), + 'num_neg_samples': num_neg_samples, + 'seed': seed, + 'sampler': sampler, + 'is_sparse': is_sparse, + 'remote_prefetch': remote_prefetch + } + + self.weight = self.create_parameter( + attr=self._param_attr, + shape=[self._num_total_classes, dim], + is_bias=False, + dtype=self._dtype) + if self._bias_attr: + self.bias = self.create_parameter( + attr=self._bias_attr, + shape=[self._num_total_classes, 1], + is_bias=True, + dtype=self._dtype) + self._inputs['Bias'] = self.bias + self._inputs['Weight'] = self.weight + + def forward(self, input, label, sample_weight=None): + if _non_static_mode(): + attrs = ('num_total_classes', self._attrs['num_total_classes'], + 'num_neg_samples', self._attrs['num_neg_samples'], 'seed', + self._attrs['seed'], 'sampler', self._attrs['sampler'], + 'is_sparse', self._attrs['is_sparse'], 'remote_prefetch', + self._attrs['remote_prefetch']) + cost, _, _ = _legacy_C_ops.nce(input, label, self.weight, self.bias, + self._inputs['SampleWeight'], + self._inputs['CustomDistProbs'], + self._inputs['CustomDistAlias'], + self._inputs['CustomDistAliasProbs'], + *attrs) + return cost / (self._num_neg_samples + 1) + + check_variable_and_dtype(input, "input", ['float32', 'float64'], "NCE") + check_variable_and_dtype(label, "label", ['int64'], "NCE") + check_type(sample_weight, 'sample_weight', (Variable, type(None)), + 'NCE') + assert isinstance(input, Variable) + assert isinstance(label, Variable) + + self._inputs['Input'] = input + self._inputs['Label'] = label + self._inputs['SampleWeight'] = sample_weight if sample_weight is not None else [] + + cost = self._helper.create_variable_for_type_inference( + dtype=input.dtype) + sample_logits = self._helper.create_variable_for_type_inference( + dtype=input.dtype) + sample_labels = self._helper.create_variable_for_type_inference( + dtype=label.dtype) + + self._helper.append_op(type='nce', + inputs=self._inputs, + outputs={ + 'Cost': cost, + 'SampleLogits': sample_logits, + 'SampleLabels': sample_labels + }, + attrs=self._attrs) + return cost / (self._num_neg_samples + 1) + + +class PRelu(layers.Layer): + r""" + This interface is used to construct a callable object of the ``PRelu`` class. + For more details, refer to code examples. + It implements three activation methods of the ``PRelu`` activation function. + + Equation: + + .. math:: + y = \max(0, x) + \\alpha * \min(0, x) + + Parameters: + mode (str): The mode for weight sharing. It supports all, channel + and element. all: all elements share same weight + channel:elements in a channel share same weight + element:each element has a weight + channel (int, optional): The number of channels. + This argument is required when mode is "channel". + Default: None. + input_shape (list or tuple, optional): The shape of input. + This argument is required when mode is "element". + Default: None. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + weight (alpha). Default: None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + + inp_np = np.ones([5, 200, 100, 100]).astype('float32') + with fluid.dygraph.guard(): + inp_np = to_variable(inp_np) + prelu0 = fluid.PRelu( + mode='all', + param_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(1.0))) + dy_rlt0 = prelu0(inp_np) + prelu1 = fluid.PRelu( + mode='channel', + channel=200, + param_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(1.0))) + dy_rlt1 = prelu1(inp_np) + prelu2 = fluid.PRelu( + mode='element', + input_shape=inp_np.shape, + param_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(1.0))) + dy_rlt2 = prelu2(inp_np) + + """ + + def __init__(self, + mode, + channel=None, + input_shape=None, + param_attr=None, + dtype='float32'): + # need specify name_scope since snake-cased 'PRelu' is 'p_relu' + super(PRelu, self).__init__(name_scope='prelu') + self._mode = mode + self._param_attr = param_attr + self._dtype = dtype + if mode == 'all': + self._alpha_shape = [1] + elif mode == 'channel': + assert isinstance( + channel, + int), "channel argument is required when mode is 'channel'." + #NOTE(zhiqiu): The _alpha_shape should be [1, channel] + [1] * len(input_shape[2:]), not [1, channel, 1, 1]. + # However, the suffix 1 in the list is useless, since the tensor is viewed as one demension array during kernel calculation. + # And, input_shape is not required when mode is 'channel', so it is simplified. + #NOTE(zhiqiu): Revert shape to [1, channel, 1, 1] for compatibility with saved model of old version. + self._alpha_shape = [1, channel, 1, 1] + elif mode == 'element': + assert isinstance( + input_shape, + (list, tuple + )), "input_shape argument is required when mode is 'element'." + self._alpha_shape = [1] + list(input_shape)[1:] + else: + raise ValueError('mode should be one of all, channel, element.') + self.weight = self.create_parameter(attr=self._param_attr, + shape=self._alpha_shape, + dtype='float32', + is_bias=False, + default_initializer=Constant(1.0)) + + def forward(self, input): + if in_dygraph_mode(): + return _C_ops.prelu(input, self.weight, "NCHW", self._mode) + + check_variable_and_dtype(input, 'input', ['float32'], 'PRelu') + out = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type="prelu", + inputs={ + "X": input, + 'Alpha': self.weight + }, + attrs={"mode": self._mode}, + outputs={"Out": out}) + return out + + +class BilinearTensorProduct(layers.Layer): + r""" + + **Add Bilinear Tensor Product Layer** + + This layer performs bilinear tensor product on two inputs. + For example: + + .. math:: + out_{i} = x * W_{i} * {y^\mathrm{T}}, i=0,1,...,size-1 + + In this formula: + - :math:`x`: the first input contains M elements, shape is [batch_size, M]. + - :math:`y`: the second input contains N elements, shape is [batch_size, N]. + - :math:`W_{i}`: the i-th learned weight, shape is [M, N] + - :math:`out_{i}`: the i-th element of out, shape is [batch_size, size]. + - :math:`y^\mathrm{T}`: the transpose of :math:`y`. + + Parameters: + input1_dim (int): The dimension of each first input. + input2_dim (int): The dimension of each second input. + output_dim (int): The dimension of output of this layer. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None. + act (str, optional): Activation to be applied to the output of this layer. The default value is None. + param_attr (ParamAttr, optional): The parameter attribute for the learnable w, parameters/weights of + this layer. The default value is None. + bias_attr (ParamAttr, optional): The parameter attribute for the bias + of this layer. If it is set to False, no bias will be added to the output units. + If it is set to None, the bias is initialized zero. The default value is None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Returns: + Tensor: A 2-D Tensor of shape [batch_size, size]. + + Examples: + .. code-block:: python + + import paddle + import numpy + + layer1 = numpy.random.random((5, 5)).astype('float32') + layer2 = numpy.random.random((5, 4)).astype('float32') + bilinearTensorProduct = paddle.nn.BilinearTensorProduct( + input1_dim=5, input2_dim=4, output_dim=1000) + ret = bilinearTensorProduct(paddle.to_tensor(layer1), + paddle.to_tensor(layer2)) + + """ + + def __init__(self, + input1_dim, + input2_dim, + output_dim, + name=None, + act=None, + param_attr=None, + bias_attr=None, + dtype='float32'): + super(BilinearTensorProduct, self).__init__() + self._param_attr = param_attr + self._bias_attr = bias_attr + self._act = act + self._name = name + self._input1_dim = input1_dim + self._input2_dim = input2_dim + self._output_dim = output_dim + self._inputs = dict() + self._dtype = dtype + + param_shape = [self._output_dim, self._input1_dim, self._input2_dim] + self.weight = self.create_parameter(attr=self._param_attr, + shape=param_shape, + dtype=self._dtype, + is_bias=False) + bias_size = [1, self._output_dim] + self.bias = self.create_parameter(attr=self._bias_attr, + shape=bias_size, + dtype=self._dtype, + is_bias=True) + + @deprecated(since="2.0.0", + update_to="paddle.nn.Bilinear", + reason="New name and new args in Bilinear, easier to use.") + def forward(self, x, y): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], + 'BilinearTensorProduct') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], + 'BilinearTensorProduct') + self._inputs = {"X": x, "Y": y, "Weight": self.weight} + if self.bias is not None: + self._inputs["Bias"] = self.bias + if self._name is not None: + out = self._helper.create_variable(name=".".join( + [self.full_name(), self._name]), + dtype=self._dtype, + persistable=False) + else: + out = self._helper.create_variable(dtype=self._dtype, + persistable=False) + self._helper.append_op(type="bilinear_tensor_product", + inputs=self._inputs, + outputs={"Out": out}) + + # add activation + return self._helper.append_activation(out, act=self._act) + + +class Conv2DTranspose(layers.Layer): + r""" + This interface is used to construct a callable object of the ``Conv2DTranspose`` class. + For more details, refer to code examples. + The convolution2D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input and output + are in NCHW format. Where N is batch size, C is the number of feature map, + H is the height of the feature map, and W is the width of the feature map. + Filter's shape is [MCHW] , where M is the number of input feature map, + C is the number of output feature map, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input feature map divided by the groups. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + The details of convolution transpose layer, please refer to the following explanation and references + `conv2dtranspose `_ . + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + Where: + + * :math:`X`: Input value, a ``Tensor`` with NCHW format. + * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] . + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D ``Tensor`` with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H^\prime_{out} &= (H_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (W_f - 1) + 1 \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ) \\\\ + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ) + + Parameters: + num_channels(int): The number of channels in the input image. + num_filters(int): The number of the filter. It is as same as the output + feature map. + filter_size(int or tuple): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + output_size(int or tuple, optional): The output image size. If output size is a + tuple, it must contain two integers, (image_H, image_W). None if use + filter_size, padding, and stride to calculate output_size. + if output_size and filter_size are specified at the same time, They + should follow the formula above. Default: None. + padding(int or tuple, optional): The padding size. If padding is a tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: 0. + stride(int or tuple, optional): The stride size. If stride is a tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: 1. + dilation(int or tuple, optional): The dilation size. If dilation is a tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: 1. + groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: 1. + param_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter) + of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv2d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True. + act (str, optional): Activation type, if it is set to None, activation is not appended. + Default: None. + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + data = np.random.random((3, 32, 32, 5)).astype('float32') + conv2DTranspose = fluid.dygraph.nn.Conv2DTranspose( + num_channels=32, num_filters=2, filter_size=3) + ret = conv2DTranspose(fluid.dygraph.base.to_variable(data)) + + """ + + def __init__(self, + num_channels, + num_filters, + filter_size, + output_size=None, + padding=0, + stride=1, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + dtype='float32'): + super(Conv2DTranspose, self).__init__() + assert param_attr is not False, "param_attr should not be False in conv2d_transpose." + self._param_attr = param_attr + self._bias_attr = bias_attr + self._act = act + self._groups = groups + self._num_channels = num_channels + self._num_filters = num_filters + self._use_cudnn = use_cudnn + self._padding = padding + self._stride = stride + self._dilation = dilation + self._filter_size = filter_size + self._output_size = output_size + self._dtype = dtype + + if (self._num_channels == self._groups + and self._num_filters == self._num_channels + and not self._use_cudnn): + self._op_type = 'depthwise_conv2d_transpose' + else: + self._op_type = 'conv2d_transpose' + + self._padding = utils.convert_to_list(self._padding, 2, 'padding') + self._stride = utils.convert_to_list(self._stride, 2, 'stride') + self._dilation = utils.convert_to_list(self._dilation, 2, 'dilation') + + self._filter_size = utils.convert_to_list( + self._filter_size, 2, 'conv2d_transpose.filter_size') + + if self._output_size is None: + self._output_size = [] + elif isinstance(self._output_size, list): + if utils._contain_var(self._output_size): + self._output_size = utils._convert_to_tensor_list( + self._output_size) + else: + self._output_size = utils.convert_to_list( + self._output_size, 2, 'output_size') + elif isinstance(self._output_size, int): + self._output_size = utils.convert_to_list(self._output_size, 2, + 'output_size') + elif isinstance(self._output_size, Variable): + check_dtype(self._output_size.dtype, 'output_size', + ['int32', 'int64'], 'Conv2DTranspose') + if len(self._output_size.shape) == 1 and ( + self._output_size.shape[0] == 1 + or self._output_size.shape[0] == 2): + if self._output_size.shape[0] == 1: + self._output_size = [self._output_size, self._output_size] + else: + raise ValueError( + "output_size must contain one or two integers.") + else: + raise ValueError("output_size should be list or int or Tensor") + self._padding = utils.convert_to_list(self._padding, 2, 'padding') + self._groups = 1 if self._groups is None else self._groups + filter_shape = [self._num_channels, self._num_filters // self._groups + ] + self._filter_size + + self.weight = self.create_parameter(dtype=self._dtype, + shape=filter_shape, + attr=self._param_attr) + + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + if _non_static_mode(): + op = getattr(_legacy_C_ops, self._op_type) + out = op(input, self.weight, 'output_size', self._output_size, + 'strides', self._stride, 'paddings', self._padding, + 'dilations', self._dilation, 'groups', self._groups, + 'use_cudnn', self._use_cudnn) + pre_bias = out + pre_act = dygraph_utils._append_bias_in_dygraph( + pre_bias, self.bias, 1) + return dygraph_utils._append_activation_in_dygraph(pre_act, + act=self._act) + + check_variable_and_dtype(input, 'input', + ['float16', 'float32', 'float64'], + "Conv2DTranspose") + + inputs = {'Input': [input], 'Filter': [self.weight]} + attrs = { + 'output_size': self._output_size, + 'strides': self._stride, + 'paddings': self._padding, + 'dilations': self._dilation, + 'groups': self._groups, + 'use_cudnn': self._use_cudnn + } + + pre_bias = self._helper.create_variable_for_type_inference( + dtype=input.dtype) + self._helper.append_op(type=self._op_type, + inputs=inputs, + outputs={'Output': pre_bias}, + attrs=attrs) + + if self.bias is not None: + pre_act = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [pre_bias], + 'Y': [self.bias] + }, + outputs={'Out': [pre_act]}, + attrs={'axis': 1}) + else: + pre_act = pre_bias + + out = self._helper.append_activation(pre_act, act=self._act) + return out + + +class SequenceConv(layers.Layer): + """ + This function creates the op for sequence_conv, using the inputs and + other convolutional configurations for the filters and stride as given + in the input parameters to the function. + + Parameters: + name_scope(str): The name of this class. + num_filters (int): number of filters. + filter_size (int): the filter size (H and W). Default: 3. + filter_stride (int): stride of the filter. Default: 1. + padding (bool|None): if True, add paddings. Default: None + bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of sequence_conv. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, sequence_conv + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights + of sequence_conv. If it is set to None or one attribute of ParamAttr, sequence_conv + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + act (str): Activation type, if it is set to None, activation is not appended. + Default: None. + + Attributes: + weight (Parameter): the learnable weights of filters of this layer. + bias (Parameter|None): the learnable bias of this layer. + + Returns: + Variable: output of sequence_conv + """ + + def __init__(self, + name_scope, + num_filters, + filter_size=3, + filter_stride=1, + padding=None, + bias_attr=None, + param_attr=None, + act=None): + assert not _non_static_mode( + ), "SequenceConv is not supported by dynamic graph mode yet!" + super(SequenceConv, self).__init__(name_scope) + self._num_filters = num_filters + self._filter_size = filter_size + self._filter_stride = filter_stride + self._padding = padding + self._bias_attr = bias_attr + self._param_attr = param_attr + self._act = act + + def _build_once(self, input): + self._dtype = self._helper.input_dtype(input) + filter_shape = [self._filter_size * input.shape[1], self._num_filters] + self.weight = self.create_parameter(attr=self._param_attr, + shape=filter_shape, + dtype=self._dtype) + + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + pre_bias = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type='sequence_conv', + inputs={ + 'X': [input], + 'Filter': [self.weight], + }, + outputs={"Out": pre_bias}, + attrs={ + 'contextStride': self._filter_stride, + 'contextStart': -int(self._filter_size // 2), + 'contextLength': self._filter_size + }) + + if self.bias is not None: + pre_act = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [pre_bias], + 'Y': [self.bias] + }, + outputs={'Out': [pre_act]}, + attrs={'axis': 1}) + else: + pre_act = pre_bias + + return self._helper.append_activation(pre_act, act=self._act) + + +class RowConv(layers.Layer): + """ + ***Row-convolution operator*** + + The row convolution is called lookahead convolution. This operator was introduced in the following paper for DeepSpeech2: + http://www.cs.cmu.edu/~dyogatam/papers/wang+etal.iclrworkshop2016.pdf + + The main motivation is that a bidirectional RNN, useful in DeepSpeech like speech models, learns representation for a sequence by performing a + forward and a backward pass through the entire sequence. However, unlike + unidirectional RNNs, bidirectional RNNs are challenging to deploy in an online + and low-latency setting. The lookahead convolution incorporates information + from future subsequences in a computationally efficient manner to improve + unidirectional recurrent neural networks. The row convolution operator is + different from the 1D sequence convolution, and is computed as follows: + + Given an input sequence X of length t and input dimension D, and a filter (W) of size context * D. + + More details about row_conv please refer to the design document https://github.com/PaddlePaddle/Paddle/issues/2228#issuecomment-303903645 . + + Parameters: + name_scope(str): The name of this class. + future_context_size (int): Future context size. Please note, the shape + of convolution kernel is [future_context_size + 1, D]. + param_attr (ParamAttr): Attributes of parameters, including + name, initializer etc. Default: None. + act (str): Non-linear activation to be applied to output variable. Default: None. + + Attributes: + weight (Parameter): the learnable weights of this layer. + + Returns: + the output(Out) is a LodTensor, which supports variable time-length input sequences. + The underlying tensor in this LodTensor is a matrix with shape T x N, i.e., the same shape as X. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + with fluid.dygraph.guard(): + x = numpy.random.random((16)).astype('float32') + rowConv = fluid.dygraph.nn.RowConv( + 'RowConv', future_context_size=2) + ret = rowConv(fluid.dygraph.base.to_variable(x)) + + """ + + def __init__(self, + name_scope, + future_context_size, + param_attr=None, + act=None): + assert not _non_static_mode( + ), "RowConv is not supported by dynamic graph mode yet!" + super(RowConv, self).__init__(name_scope) + self._act = act + self._param_attr = param_attr + self._future_context_size = future_context_size + + def _build_once(self, input): + self._dtype = self._helper.input_dtype(input) + filter_shape = [self._future_context_size + 1, input.shape[1]] + self.weight = self.create_parameter(attr=self._param_attr, + shape=filter_shape, + dtype=self._dtype, + is_bias=False) + + def forward(self, input): + out = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type='row_conv', + inputs={ + 'X': [input], + 'Filter': [self.weight] + }, + outputs={'Out': [out]}) + return self._helper.append_activation(out, act=self._act) + + +class GroupNorm(layers.Layer): + """ + :alias_main: paddle.nn.GroupNorm + :alias: paddle.nn.GroupNorm,paddle.nn.layer.GroupNorm,paddle.nn.layer.norm.GroupNorm + :old_api: paddle.fluid.dygraph.GroupNorm + + This interface is used to construct a callable object of the ``GroupNorm`` class. + For more details, refer to code examples. + It implements the function of the Group Normalization Layer. + Refer to `Group Normalization `_ . + + Parameters: + channels(int): The number of channels of input. + groups(int): The number of groups that divided from channels. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + scale :math:`g`. If it is set to False, no scale will be added to the output units. + If it is set to None, the bias is initialized one. Default: None. + bias_attr(ParamAttr, optional): The parameter attribute for the learnable + bias :math:`b`. If it is set to False, no bias will be added to the output units. + If it is set to None, the bias is initialized zero. Default: None. + act(str, optional): Activation to be applied to the output of group normalization. Default: None. + data_layout(str, optional): Specify the input data format. Only NCHW is supported. Default: NCHW. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + x = np.random.random((8, 32, 32)).astype('float32') + groupNorm = fluid.dygraph.nn.GroupNorm(channels=32, groups=4) + ret = groupNorm(fluid.dygraph.base.to_variable(x)) + + """ + + def __init__(self, + channels, + groups, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + act=None, + data_layout='NCHW', + dtype='float32'): + super(GroupNorm, self).__init__() + self._param_attr = param_attr + self._bias_attr = bias_attr + self._epsilon = epsilon + self._channels = channels + self._groups = groups + self._act = act + self._dtype = dtype + if data_layout != 'NCHW': + raise ValueError("unsupported data layout:" + data_layout) + + param_shape = [self._channels] + + self.weight = self.create_parameter(attr=self._param_attr or False, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(1.0)) + + self.bias = self.create_parameter(attr=self._bias_attr or False, + shape=param_shape, + dtype=self._dtype, + is_bias=True) + + def forward(self, input): + mean_out = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + variance_out = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True) + if in_dygraph_mode(): + out = _C_ops.group_norm(input, self.weight, self.bias, + self._epsilon, self._groups, "NCHW") + + return dygraph_utils._append_activation_in_dygraph(out, self._act) + + elif _in_legacy_dygraph(): + attrs = ('epsilon', self._epsilon, 'groups', self._groups) + out, _, _ = _legacy_C_ops.group_norm(input, self.weight, self.bias, + mean_out, variance_out, *attrs) + + return dygraph_utils._append_activation_in_dygraph(out, self._act) + else: + inputs = {'X': input} + if self.bias is not None: + inputs['Bias'] = self.bias + if self.weight is not None: + inputs['Scale'] = self.weight + + # create output + group_norm_out = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + + self._helper.append_op(type="group_norm", + inputs=inputs, + outputs={ + "Y": group_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={ + "epsilon": self._epsilon, + "groups": self._groups + }) + + return self._helper.append_activation(group_norm_out, self._act) + + +class SpectralNorm(layers.Layer): + r""" + This interface is used to construct a callable object of the ``SpectralNorm`` class. + For more details, refer to code examples. It implements the function of the Spectral Normalization Layer. + This layer calculates the spectral normalization value of weight parameters of + fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D + Parameters. Calculations are showed as follows. + + Step 1: + Generate vector U in shape of [H], and V in shape of [W]. + While H is the :attr:`dim` th dimension of the input weights, + and W is the product result of remaining dimensions. + + Step 2: + :attr:`power_iters` should be a positive integer, do following + calculations with U and V for :attr:`power_iters` rounds. + + .. math:: + + \mathbf{v} := \frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} + + \mathbf{u} := \frac{\mathbf{W}^{T} \mathbf{v}}{\|\mathbf{W}^{T} \mathbf{v}\|_2} + + Step 3: + Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. + + .. math:: + + \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} + + \mathbf{W} = \frac{\mathbf{W}}{\sigma(\mathbf{W})} + + + Refer to `Spectral Normalization `_ . + + Parameters: + weight_shape(list or tuple): The shape of weight parameter. + dim(int, optional): The index of dimension which should be permuted to the first before reshaping Input(Weight) to matrix, it should be set as 0 if Input(Weight) is the weight of fc layer, and should be set as 1 if Input(Weight) is the weight of conv layer. Default: 0. + power_iters(int, optional): The number of power iterations to calculate spectral norm. Default: 1. + eps(float, optional): The epsilon for numerical stability in calculating norms. Default: 1e-12. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + x = paddle.rand((2,8,32,32)) + + spectral_norm = paddle.nn.SpectralNorm(x.shape, dim=1, power_iters=2) + spectral_norm_out = spectral_norm(x) + + print(spectral_norm_out.shape) # [2, 8, 32, 32] + + """ + + def __init__(self, + weight_shape, + dim=0, + power_iters=1, + eps=1e-12, + dtype='float32'): + super(SpectralNorm, self).__init__() + self._power_iters = power_iters + self._eps = eps + self._dim = dim + self._dtype = dtype + + self._weight_shape = list(weight_shape) + assert np.prod(self._weight_shape) > 0,\ + "Any dimension of `weight_shape` cannot be equal to 0." + assert dim < len(self._weight_shape), \ + ("The input `dim` should be less than the " + "length of `weight_shape`, but received dim=" + "{}".format(dim)) + h = self._weight_shape[self._dim] + w = np.prod(self._weight_shape) // h + + self.weight_u = self.create_parameter(attr=ParamAttr(), + shape=[h], + dtype=self._dtype, + default_initializer=Normal( + 0., 1.)) + self.weight_u.stop_gradient = True + + self.weight_v = self.create_parameter(attr=ParamAttr(), + shape=[w], + dtype=self._dtype, + default_initializer=Normal( + 0., 1.)) + self.weight_v.stop_gradient = True + + def forward(self, weight): + if in_dygraph_mode(): + return _C_ops.spectral_norm(weight, self.weight_u, self.weight_v, + self._dim, self._power_iters, self._eps) + + check_variable_and_dtype(weight, "weight", ['float32', 'float64'], + 'SpectralNorm') + inputs = {'Weight': weight, 'U': self.weight_u, 'V': self.weight_v} + out = self._helper.create_variable_for_type_inference(self._dtype) + self._helper.append_op(type="spectral_norm", + inputs=inputs, + outputs={ + "Out": out, + }, + attrs={ + "dim": self._dim, + "power_iters": self._power_iters, + "eps": self._eps, + }) + + return out + + +class TreeConv(layers.Layer): + """ + This interface is used to construct a callable object of the ``TreeConv`` class. + For more details, refer to code examples. + Tree-Based Convolution is a kind of convolution based on tree structure. + Tree-Based Convolution is a part of Tree-Based Convolution Neural Network(TBCNN), + which is used to classify tree structures, such as Abstract Syntax Tree. + Tree-Based Convolution proposed a kind of data structure called continuous binary tree, + which regards multiway tree as binary tree. + The paper of Tree-Based Convolution Operator is here: `tree-based convolution `_ . + + Parameters: + feature_size(int): last dimension of nodes_vector. + output_size(int): output feature width. + num_filters(int, optional): number of filters, Default: 1. + max_depth(int, optional): max depth of filters, Default: 2. + act(str, optional): activation function, Default: tanh. + param_attr(ParamAttr, optional): the parameter attribute for the filters, Default: None. + bias_attr(ParamAttr, optional): the parameter attribute for the bias of this layer, Default: None. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + dtype (str, optional): Data type, it can be "float32" or "float64". Default: "float32". + + Attribute: + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + with fluid.dygraph.guard(): + nodes_vector = numpy.random.random((1, 10, 5)).astype('float32') + edge_set = numpy.random.random((1, 9, 2)).astype('int32') + treeConv = fluid.dygraph.nn.TreeConv( + feature_size=5, output_size=6, num_filters=1, max_depth=2) + ret = treeConv(fluid.dygraph.base.to_variable(nodes_vector), fluid.dygraph.base.to_variable(edge_set)) + """ + + def __init__(self, + feature_size, + output_size, + num_filters=1, + max_depth=2, + act='tanh', + param_attr=None, + bias_attr=None, + name=None, + dtype='float32'): + super(TreeConv, self).__init__() + self._name = name + self._feature_size = feature_size + self._output_size = output_size + self._act = act + self._max_depth = max_depth + self._num_filters = num_filters + self._bias_attr = bias_attr + self._param_attr = param_attr + self._dtype = dtype + w_shape = [self._feature_size, 3, self._output_size, self._num_filters] + if self._bias_attr: + self.bias = self.create_parameter(attr=self._bias_attr, + shape=[self._num_filters], + dtype=self._dtype, + is_bias=True) + self.weight = self.create_parameter(attr=self._param_attr, + shape=w_shape, + dtype=self._dtype, + is_bias=False) + + def forward(self, nodes_vector, edge_set): + check_type(nodes_vector, 'nodes_vector', (Variable), 'TreeConv') + check_type(edge_set, 'edge_set', (Variable), 'TreeConv') + if self._name: + out = self.create_variable(name=self._name, + dtype=self._dtype, + persistable=False) + else: + out = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='tree_conv', + inputs={ + 'NodesVector': nodes_vector, + 'EdgeSet': edge_set, + 'Filter': self.weight + }, + outputs={ + 'Out': out, + }, + attrs={'max_depth': self._max_depth}) + if self._bias_attr: + pre_activation = self._helper.create_variable_for_type_inference( + dtype=self._dtype) + self._helper.append_op(type='elementwise_add', + inputs={ + 'X': [out], + 'Y': [self.bias] + }, + outputs={'Out': [pre_activation]}, + attrs={'axis': 1}) + else: + pre_activation = out + return self._helper.append_activation(pre_activation, act=self._act) + + +class Flatten(layers.Layer): + """ + This interface is used to construct a callable object of the ``FLatten`` class. + For more details, refer to code examples. + It implements flatten a contiguous range of dims into a tensor. + + Parameters: + start_axis(int): first dim to flatten (default = 1) + stop_axis(int): last dim to flatten (default = -1). + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + inp_np = np.ones([5, 2, 3, 4]).astype('float32') + inp_np = paddle.to_tensor(inp_np) + flatten = paddle.nn.Flatten(start_axis=1, stop_axis=2) + flatten_res = flatten(inp_np) + + """ + + def __init__(self, start_axis=1, stop_axis=-1): + super(Flatten, self).__init__() + self.start_axis = start_axis + self.stop_axis = stop_axis + + def forward(self, input): + out = paddle.tensor.manipulation.flatten(input, + start_axis=self.start_axis, + stop_axis=self.stop_axis) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1ea80d872955d7a207f5f62b1acb810203d38d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel.py @@ -0,0 +1,870 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except jin 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. + +import os +import six +import numpy as np +import warnings +from collections import OrderedDict +import itertools +import warnings +from contextlib import contextmanager + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid import core +from paddle.fluid import framework +from paddle.fluid.dygraph import layers +from paddle.fluid.dygraph import parallel_helper +from paddle.fluid.dygraph import to_variable, no_grad +from paddle.utils import deprecated +from ..layers import collective +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid.framework import ParamBase, _in_legacy_dygraph, _non_static_mode, in_dygraph_mode + +__all__ = ["prepare_context", "ParallelEnv", "DataParallel"] + +ParallelStrategy = core.ParallelStrategy + + +@deprecated(since="2.0.0", update_to="paddle.distributed.init_parallel_env") +def prepare_context(strategy=None): + ''' + :api_attr: imperative + ''' + if strategy is None: + strategy = ParallelStrategy() + strategy.nranks = Env().nranks + strategy.local_rank = Env().local_rank + strategy.trainer_endpoints = Env().trainer_endpoints + strategy.current_endpoint = Env().current_endpoint + if strategy.nranks < 2: + return + assert framework._non_static_mode() is True, \ + "dygraph.prepare_context should be used with dygraph mode." + place = framework._current_expected_place() + assert place is not None, \ + "dygraph.prepare_context should be used in fluid.dygraph.guard(place) guard." + if not parallel_helper._is_parallel_ctx_initialized(): + if isinstance(place, core.CUDAPlace): + parallel_helper._set_parallel_ctx( + core.NCCLParallelContext(strategy, place)) + elif isinstance(place, core.XPUPlace): + parallel_helper._set_parallel_ctx( + core.BKCLParallelContext(strategy, place)) + elif isinstance(place, core.NPUPlace): + parallel_helper._set_parallel_ctx( + core.HCCLParallelContext(strategy, place)) + else: + # TODO(Yancey1989): add Gloo Parallel Context to support CPU parallel computation + assert ("Only support CUDAPlace or XPUPlace or NPUPlace for now.") + parallel_helper._init_parallel_ctx() + return strategy + + +class ParallelEnv(object): + """ + .. note:: + This API is not recommended, if you need to get rank and world_size, + it is recommended to use ``paddle.distributed.get_rank()`` and + ``paddle.distributed.get_world_size()`` . + + This class is used to obtain the environment variables required for + the parallel execution of ``paddle.nn.Layer`` in dynamic mode. + + The parallel execution in dynamic mode needs to be started using ``paddle.distributed.launch`` + or ``paddle.distributed.spawn`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed as dist + + def train(): + # 1. initialize parallel environment + dist.init_parallel_env() + + # 2. get current ParallelEnv + parallel_env = dist.ParallelEnv() + print("rank: ", parallel_env.rank) + print("world_size: ", parallel_env.world_size) + + # print result in process 1: + # rank: 1 + # world_size: 2 + # print result in process 2: + # rank: 2 + # world_size: 2 + + if __name__ == '__main__': + # 1. start by ``paddle.distributed.spawn`` (default) + dist.spawn(train, nprocs=2) + # 2. start by ``paddle.distributed.launch`` + # train() + """ + + def __init__(self): + self._rank = int(os.getenv("PADDLE_TRAINER_ID", "0")) + self._world_size = int(os.getenv("PADDLE_TRAINERS_NUM", "1")) + self._device_type = str(os.getenv("PADDLE_XCCL_BACKEND", "")) + + # imperative only support one gpu or xpu + if self._device_type != "": + FLAGS_selected_custom_devices = 'FLAGS_selected_{}s'.format( + self._device_type) + selected_custom_devices = os.getenv(FLAGS_selected_custom_devices, + "0").split(",") + self._device_id = int(selected_custom_devices[0]) + else: + if core.is_compiled_with_cuda(): + selected_gpus = os.getenv("FLAGS_selected_gpus", "0").split(",") + self._device_id = int(selected_gpus[0]) + elif core.is_compiled_with_xpu(): + selected_xpus = os.getenv("FLAGS_selected_xpus", "0").split(",") + self._device_id = int(selected_xpus[0]) + elif core.is_compiled_with_npu(): + selected_npus = os.getenv("FLAGS_selected_npus", "0").split(",") + self._device_id = int(selected_npus[0]) + elif core.is_compiled_with_mlu(): + selected_mlus = os.getenv("FLAGS_selected_mlus", "0").split(",") + self._device_id = int(selected_mlus[0]) + + self._trainer_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS", + "").split(",") + self._current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT", "") + self._nrings = int(os.getenv("FLAGS_nccl_nrings", "1")) + assert self._nrings > 0, \ + "nccl_nrings must be an integer greater than 0." + assert self._nrings < 9, \ + "nccl_nrings should be less than 9, which is enough in most scenarios." + + @property + def rank(self): + """ + Rank of current trainer. + + Its value is equal to the value of the environment variable ``PADDLE_TRAINER_ID`` . The default value is 0. + + Examples: + .. code-block:: python + + # execute this command in terminal: export PADDLE_TRAINER_ID=0 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The rank is %d" % env.rank) + # The rank is 0 + """ + return self._rank + + @property + def world_size(self): + """ + The number of trainers (number of processes participating in current job). + + Its value is equal to the value of the environment variable ``PADDLE_TRAINERS_NUM`` . The default value is 1. + + Examples: + .. code-block:: python + + # execute this command in terminal: export PADDLE_TRAINERS_NUM=4 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The world_size is %d" % env.world_size) + # The world_size is 4 + """ + return self._world_size + + @property + def device_id(self): + """ + The ID of selected GPU card for parallel training. + + Its value is equal to the value of the environment variable ``FLAGS_selected_gpus`` . The default value is 0. + + Examples: + .. code-block:: python + + # execute this command in terminal: export FLAGS_selected_gpus=1 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The device id are %d" % env.device_id) + # The device id are 1 + """ + return self._device_id + + @property + def device_type(self): + """ + The type of custom device for parallel training. + + Its value is equal to the value of the environment variable ``PADDLE_XCCL_BACKEND`` . The default value is None. + + """ + return self._device_type + + @property + def current_endpoint(self): + """ + The endpoint of current trainer, it is in the form of (node IP + port). + + Its value is equal to the value of the environment variable ``PADDLE_CURRENT_ENDPOINT`` . The default value is "". + + Examples: + .. code-block:: python + + # execute this command in terminal: export PADDLE_CURRENT_ENDPOINT=127.0.0.1:6170 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The current endpoint are %s" % env.current_endpoint) + # The current endpoint are 127.0.0.1:6170 + """ + return self._current_endpoint + + @property + def trainer_endpoints(self): + """ + The endpoints of all trainer nodes in the task, + which are used to broadcast the NCCL ID when NCCL2 is initialized. + + Its value is equal to the value of the environment variable ``PADDLE_TRAINER_ENDPOINTS`` . The default value is "". + + Examples: + .. code-block:: python + + # execute this command in terminal: export PADDLE_TRAINER_ENDPOINTS=127.0.0.1:6170,127.0.0.1:6171 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The trainer endpoints are %s" % env.trainer_endpoints) + # The trainer endpoints are ['127.0.0.1:6170', '127.0.0.1:6171'] + """ + return self._trainer_endpoints + + @property + def nrings(self): + """ + Nrings of current trainer. + + Its value is equal to the value of the environment variable ``FLAGS_nccl_nrings`` . The default value is 1. + + Examples: + .. code-block:: python + + # execute this command in terminal: export FLAGS_nccl_nrings=1 + import paddle.distributed as dist + + env = dist.ParallelEnv() + print("The nrings is %d" % env.nrings) + # the number of ring is 1 + """ + return self._nrings + + # [aliases] Compatible with old method names + local_rank = rank + nranks = world_size + dev_id = device_id + + +# NOTE: [ Compatible ] Originally this class name is `Env`. The semantics of the old class names +# are inaccurate and may confuse users, so replace it with `ParallelEnv`, but to be compatible +# with the old examples, here still need to keep this name. +Env = ParallelEnv + + +def _build_default_parallel_strategy(): + strategy = ParallelStrategy() + strategy.nranks = ParallelEnv().nranks + strategy.local_rank = ParallelEnv().local_rank + strategy.trainer_endpoints = ParallelEnv().trainer_endpoints + strategy.current_endpoint = ParallelEnv().current_endpoint + return strategy + + +def _coalesce_tensors(var_groups): + from ..layers import nn + coalesced_grads_and_grad_vars = [] + for group_id, grad_vars in var_groups.items(): + flattened_vars = [] + g_var_shapes = [] + for g_var in grad_vars: + g_var_shapes.append(g_var.shape) + flattened_vars.append( + nn.reshape(x=g_var, shape=[np.prod(g_var.shape)])) + coalesced_grad = nn.concat(flattened_vars) + coalesced_grads_and_grad_vars.append( + [coalesced_grad, grad_vars, g_var_shapes]) + return coalesced_grads_and_grad_vars + + +@framework.dygraph_only +def _reshape_inplace(x, shape): + x_shape = framework._varbase_creator(dtype=x.dtype) + framework._dygraph_tracer().trace_op(type="reshape2", + inputs={'X': x}, + outputs={ + 'Out': x, + 'XShape': x_shape + }, + attrs={'shape': shape}) + + +@framework.dygraph_only +def _split_tensors(coalesced_grads_and_grad_vars): + if _in_legacy_dygraph(): + for coalesced_grad, origin_grad_vars, grad_shapes in coalesced_grads_and_grad_vars: + grad_var_len = [np.prod(g_shape) for g_shape in grad_shapes] + framework._dygraph_tracer().trace_op( + type='split', + inputs={'X': coalesced_grad}, + outputs={'Out': origin_grad_vars}, + attrs={ + 'sections': grad_var_len, + 'axis': 0 + }) + for g_var, g_shape in zip(origin_grad_vars, grad_shapes): + _reshape_inplace(x=g_var, shape=g_shape) + assert g_var.shape == g_shape + elif in_dygraph_mode(): + for coalesced_grad, origin_grad_vars, grad_shapes in coalesced_grads_and_grad_vars: + grad_var_len = [np.prod(g_shape) for g_shape in grad_shapes] + attrs = () + attrs += ('sections', grad_var_len) + attrs += ('axis', 0) + _legacy_C_ops.split(coalesced_grad, origin_grad_vars, *attrs) + for g_var, g_shape in zip(origin_grad_vars, grad_shapes): + g_var.reshape_(shape=g_shape) + assert g_var.shape == g_shape + + +def scale_loss(loss): + # TODO(liuyuhui) Currently only for xpu. Will be removed in the future. + if not ParallelEnv().world_size > 1: + return loss + + loss_scale = to_variable( + np.array([ParallelEnv().world_size]).astype("float32")) + loss_scale.stop_gradient = True + scaled_loss = loss / loss_scale + return scaled_loss + + +@imperative_base.no_grad +@framework.dygraph_only +def build_groups(vars, group_size): + group_idx = 0 + memory_counter = 0 + var_groups = OrderedDict() + dtype = vars[0].dtype + + for var in vars: + bytes = np.prod(var.shape) * core.size_of_dtype(var.dtype) + if memory_counter < group_size and dtype == var.dtype: + memory_counter += bytes + else: + memory_counter = bytes + dtype = var.dtype + group_idx += 1 + var_groups.setdefault(group_idx, []).append(var) + return _coalesce_tensors(var_groups) + + +@imperative_base.no_grad +@framework.dygraph_only +def sync_params_buffers(model, + comm_group=None, + src_rank=0, + is_model_parallel=False): + model_vars = [] + for _, param in model._obtain_parameters_buffers().items(): + if not isinstance(param, (core.VarBase, core.eager.Tensor)): + raise TypeError( + "The data type of '%s' must be Varbase or eager.Tensor" % + param.name) + + # is_distributed param not need to sync when in mp mode + if isinstance(param, (ParamBase, core.eager.Tensor)): + if is_model_parallel and param.is_distributed: + continue + + # NOTE(shenliang03): Support situations that do not require synchronization parameters, + # such as moe's expert parameters + if getattr(param, "no_sync", False): + continue + if param.type == core.VarDesc.VarType.VOCAB: + continue + + model_vars.append(param.detach()) + if len(model_vars) == 0: + return + + # group size is 128M + coalesced_vars = build_groups(model_vars, 128 * 1024 * 1024) + + for coalesced_var, _, _ in coalesced_vars: + paddle.distributed.broadcast(coalesced_var, + src=src_rank, + group=comm_group, + sync_op=True) + + for coalesced_var, origin_vars, var_shapes in coalesced_vars: + var_len = [np.prod(v_shape) for v_shape in var_shapes] + paddle.fluid.framework._dygraph_tracer().trace_op( + type='split', + inputs={'X': coalesced_var}, + outputs={'Out': origin_vars}, + attrs={ + 'sections': var_len, + 'axis': 0 + }) + + +class DataParallel(layers.Layer): + """ + Run the dygraph module with data parallelism. + + Currently, DataParallel class only supports to run the dynamic graph + with multi-process. + + Now supports two ways to start training: + + 1. start by ``paddle.distributed.spawn`` method, for example: + + ``python demo.py`` (spawn need to be called in ``__main__`` method) + + 2. start by ``paddle.distributed.launch`` module, for example: + + ``python -m paddle.distributed.launch --gpus=0,1 demo.py`` . + + And the content of `demo.py` is the code of examples. + + Args: + layers(Layer): The module that should be executed by data parallel. + strategy(ParallelStrategy, optional): (deprecated) The strategy of data parallelism, + contains environment configuration related to parallel execution. Default: None. + comm_buffer_size(int, optional): It limits the memory size(MB) of one buffer + parameters' gradient which is the input of communication + calling(e.g NCCLAllReduce). Default: 25. + last_comm_buffer_size(float, optional): It limits memory size(MB) of last buffer in communication + calling. Making the last communication buffer size small is useful to + improve performance. Default: 1. + find_unused_parameters(bool, optional): Whether to traverse the entire backward graph from the + all tensors in the return value of the wrapped model's + forward function. For parameters not involved in loss + calculation, their gradients will be marked as ready in + advance to prepare reduce. Please note that all forward + outputs derived from the wrapped model parameters must + participate in the calculation of loss and subsequent + gradient calculations. If not, serious error will occur. + Note that setting the find_unused_parameters to True + will affect computing performance. Therefore, if all parameters + are sure to participate in the loss calculation and the + autograd graph construction, please set it False. Default: False. + + Returns: + Layer: The data paralleled module. + + Examples: + + .. code-block:: python + :name: dp-example + + # required: distributed + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + import paddle.distributed as dist + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear1 = nn.Linear(10, 10) + self._linear2 = nn.Linear(10, 1) + + def forward(self, x): + return self._linear2(self._linear1(x)) + + def train(): + # 1. initialize parallel environment + dist.init_parallel_env() + + # 2. create data parallel layer & optimizer + layer = LinearNet() + dp_layer = paddle.DataParallel(layer) + + loss_fn = nn.MSELoss() + adam = opt.Adam( + learning_rate=0.001, parameters=dp_layer.parameters()) + + # 3. run layer + inputs = paddle.randn([10, 10], 'float32') + outputs = dp_layer(inputs) + labels = paddle.randn([10, 1], 'float32') + loss = loss_fn(outputs, labels) + + loss.backward() + + adam.step() + adam.clear_grad() + + if __name__ == '__main__': + # 1. start by ``paddle.distributed.spawn`` (default) + dist.spawn(train, nprocs=2) + # 2. start by ``paddle.distributed.launch`` + # train() + + + .. note:: + ``PyLayer`` is not supported in DataParallel. To solve problems of this kind, + it's recommended to skip gradient synchronization among multiple cards by 'no_sync', + and manually implement 'all_reduce' before model optimization. There is an example + showing specific implemetation processing. + + Examples: + + .. code-block:: python + :name: dp-pylayer-example + + # required: distributed + import numpy + import paddle + import paddle.distributed as dist + from paddle.autograd import PyLayer + from paddle.distributed.fleet.utils.hybrid_parallel_util import fused_allreduce_gradients + + class cus_tanh(PyLayer): + @staticmethod + def forward(ctx, x): + y = paddle.tanh(x) + ctx.save_for_backward(y) + return y + + @staticmethod + def backward(ctx, dy): + y, = ctx.saved_tensor() + grad = dy * (1 - paddle.square(y)) + return grad + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + self.linear = paddle.nn.Linear(2, 2) + + def forward(self, inputs): + inputs = cus_tanh.apply(inputs) + return self.linear(inputs) + + if __name__ == '__main__': + dist.init_parallel_env() + + model = SimpleNet() + model = paddle.DataParallel(model) + opt = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) + + for step in range(10): + x_data = numpy.random.randn(2, 2).astype(numpy.float32) + x = paddle.to_tensor(x_data) + x.stop_gradient = False + + # step 1 : skip gradient synchronization by 'no_sync' + with model.no_sync(): + y_pred = model(x) + loss = y_pred.mean() + loss.backward() + + # step 2 : fuse + allreduce manually before optimization + fused_allreduce_gradients(list(model.parameters()), None) + + opt.step() + opt.clear_grad() + + """ + + def __init__(self, + layers, + strategy=None, + comm_buffer_size=25, + last_comm_buffer_size=1, + find_unused_parameters=False, + group=None): + super(DataParallel, + self).__init__(layers.full_name() + "_data_parallel") + + assert _non_static_mode(), \ + "It's not supported to construct DataParallel in static mode." + + self._layers = layers + self.find_unused_parameters = find_unused_parameters + self.grad_need_sync = True + self.group = group + self.var_dtype = core.eager.Tensor if in_dygraph_mode( + ) else core.VarBase + + # NOTE(chenweihang): The ParallelStrategy here is not strictly a strategy. + # It just stores some environment variables, which can be constructed by + # ParallelEnv. Here it is set as an optional argument. + # This parameter is not removed because of compatibility with 1.x writing. + if strategy is not None: + self._strategy = strategy + else: + self._strategy = _build_default_parallel_strategy() + + if self._strategy.nranks > 1: + # check the environment + assert parallel_helper.__parallel_ctx__clz__ is not None, \ + "ParallelContext must be initialized before. You should use init_parallel_env() before" \ + "constructing the DataParallel." + + if in_dygraph_mode(): + self.group = paddle.distributed.collective._get_default_group( + ) if self.group is None else self.group + + assert isinstance(self.group, paddle.distributed.collective.Group), \ + "ProcessGroup must be an instance of Group in DataParallel." + + # sync buffer and params + # TODO(liuyuhui) Currently not support xpu. xpu is + # still broadcasting parameters when calling layer + if not paddle.is_compiled_with_xpu(): + sync_params_buffers(self._layers) + + self.comm_buffer_size = int(comm_buffer_size * 1024 * 1024) + # NOTE(shenliang03): We can set environment variables to control + # the size of the group, Default: 1MB. The role of this small group is: + # when the last group allreduce, the overlap cannot work. Making the + # the last group small is useful to improve performance. + self.last_comm_buffer_size = int(last_comm_buffer_size * 1024 * + 1024) + self.init_reducer() + else: + warnings.warn("The program will return to single-card operation. " + "Please check 1, whether you use spawn or fleetrun " + "to start the program. 2, Whether it is a multi-card " + "program. 3, Is the current environment multi-card.") + + def init_reducer(self): + layers_param = [] + params_set = set() + for sublayer in self.sublayers(): + for _, param in sublayer.named_parameters(include_sublayers=False): + if param is None or param in params_set: + continue + params_set.add(param) + if not isinstance(param, self.var_dtype): + raise TypeError("The data type of '%s' must be '%s'" % + (param.name, self.var_dtype)) + if param.trainable: + layers_param.append((sublayer, param)) + + trainable_parameters = [param for _, param in layers_param] + + assert len(trainable_parameters) > 0, \ + "This model does not have any parameters to train, and " \ + "does not need to use DataParallel" + + # NOTE(shenliang03): Here we can only use the attributes to judge whether + # parameter is sparse(or SelectedRows). The reason is that the sparse message + # can't be obtained when bp hasn't happened yet. So if layer supports sparse parameter, + # we should add the layer here like "paddle.nn.layer.common.Embedding". + def check_layer_sparse(sublayer): + if isinstance(sublayer, paddle.nn.layer.common.Embedding): + return sublayer._sparse + # NOTE(shenliang03):This is for compatibility. If paddle.fluid.dygraph.Embedding + # is removed in the future, the check will also be removed here. + if isinstance(sublayer, paddle.fluid.dygraph.Embedding): + return sublayer._is_sparse + return False + + is_sparse_gradient = [ + check_layer_sparse(sublayer) for sublayer, _ in layers_param + ] + + if in_dygraph_mode(): + self.group_indices = core.eager_assign_group_by_size( + trainable_parameters, is_sparse_gradient, + [self.last_comm_buffer_size, self.comm_buffer_size]) + + self._reducer = core.EagerReducer( + trainable_parameters, list(reversed(self.group_indices)), + is_sparse_gradient, self.group.process_group, + [self.last_comm_buffer_size, self.comm_buffer_size], + self.find_unused_parameters) + elif _in_legacy_dygraph(): + self.group_indices = core.assign_group_by_size( + trainable_parameters, is_sparse_gradient, + [self.last_comm_buffer_size, self.comm_buffer_size]) + + self._reducer = core.Reducer( + trainable_parameters, list(reversed(self.group_indices)), + is_sparse_gradient, parallel_helper.__parallel_ctx__clz__, + [self.last_comm_buffer_size, self.comm_buffer_size], + self.find_unused_parameters) + + def _find_varbase(self, obj): + var_type = core.eager.Tensor if in_dygraph_mode() else core.VarBase + if isinstance(obj, var_type): + return [obj] + if isinstance(obj, (list, tuple)): + return itertools.chain(*map(self._find_varbase, obj)) + if isinstance(obj, dict): + return itertools.chain(*map(self._find_varbase, obj.values())) + return [] + + @contextmanager + def no_sync(self): + """ + A context manager to stop gradient synchronization. Within no_sync(), + gradients of parameters will only be accumulated on model and not + synchronized util the first forward-backward out of this context. + + Examples: + .. code-block:: python + + # required: distributed + import paddle + import paddle.nn as nn + import paddle.distributed as dist + + class SimpleNet(nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + self._linear = nn.Linear(10, 1) + + def forward(self, x): + return self._linear(x) + + dist.init_parallel_env() + model = SimpleNet() + dp_model = paddle.DataParallel(model) + + inputs_1 = paddle.randn([10, 10], 'float32') + inputs_2 = paddle.ones([10, 10], 'float32') + + with dp_model.no_sync(): + # gradients will not be synchronized + dp_model(inputs_1).backward() + + # synchronization happens here + dp_model(inputs_2).backward() + + """ + tmp_grad_need_sync = self.grad_need_sync + self.grad_need_sync = False + try: + yield + finally: + self.grad_need_sync = tmp_grad_need_sync + + def forward(self, *inputs, **kwargs): + outputs = self._layers(*inputs, **kwargs) + if self._strategy.nranks > 1 and framework._dygraph_tracer( + )._has_grad and self.grad_need_sync: + self._reducer.prepare_for_backward(list( + self._find_varbase(outputs))) + return outputs + + @deprecated(since="2.0.0", + reason="This method does not need to be called anymore.") + def scale_loss(self, loss): + """ + Deprecated method, now ``scale_loss`` is an empty method, + keep this method just for compatibility. + """ + return loss + + @deprecated(since="2.0.0", + reason="This method does not need to be called anymore.") + def apply_collective_grads(self): + """ + Deprecated method, now ``apply_collective_grads`` is an empty method, + keep this method just for compatibility. + """ + return + + def state_dict(self, + destination=None, + include_sublayers=True, + structured_name_prefix=""): + ''' + Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict + + Parameters: + destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None + include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True + + Retruns: + dict: a dict contains all the parameters and persistable buffers. + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + + emb = fluid.dygraph.Embedding([10, 10]) + emb = fluid.dygraph.DataParallel(emb) + + state_dict = emb.state_dict() + paddle.save(state_dict, "paddle_dy.pdparams") + + ''' + + return self._layers.state_dict( + destination=destination, + include_sublayers=include_sublayers, + structured_name_prefix=structured_name_prefix) + + @framework.deprecate_stat_dict + def set_state_dict(self, state_dict, use_structured_name=True): + ''' + Set parameters and persistable buffers from state_dict. All the parameters and buffers will be reset by the tensor in the state_dict + + Parameters: + state_dict(dict) : Dict contains all the parameters and persistable buffers. + use_structured_name(bool, optional) : If true, use structured name as key, otherwise, use parameter or buffer name as key. + Default: True + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.distributed as dist + + dist.init_parallel_env() + + emb = paddle.nn.Embedding(10, 10) + emb = fluid.dygraph.DataParallel(emb) + + state_dict = emb.state_dict() + paddle.save(state_dict, "paddle_dy.pdparams") + + para_state_dict = paddle.load("paddle_dy.pdparams") + emb.set_state_dict(para_state_dict) + + ''' + + self._layers.set_state_dict(state_dict, + use_structured_name=use_structured_name) + + # [aliases] Compatible with old method names + set_dict = set_state_dict + load_dict = set_state_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0bb4603525ec744ba1c31e352ca091e395fd05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/parallel_helper.py @@ -0,0 +1,53 @@ +# 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 jin 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. +import os +from ..layers import collective +from ..framework import Parameter + +__parallel_ctx__clz__ = None + + +def _is_data_parallel_mode(): + global __parallel_ctx__clz__ + return __parallel_ctx__clz__ is not None and int( + os.getenv("PADDLE_TRAINERS_NUM", "1")) > 1 + + +def _is_parallel_ctx_initialized(): + global __parallel_ctx__clz__ + return __parallel_ctx__clz__ is not None + + +def _set_parallel_ctx(ccl_parallel_context): + global __parallel_ctx__clz__ + assert __parallel_ctx__clz__ is None, \ + "ParallelContext can only be initialized once." + __parallel_ctx__clz__ = ccl_parallel_context + + +def _init_parallel_ctx(): + global __parallel_ctx__clz__ + assert __parallel_ctx__clz__ is not None, \ + "ParallelContext should be initialized." + __parallel_ctx__clz__.init() + + +def _broadcast_parameters(parameters): + for param in parameters: + # In model parallel, some parameters are split into multiple devices, + # so we could not broadcast these parameters. + if param.is_distributed: continue + + if isinstance(param, Parameter) and param.trainable: + collective._broadcast(param, 0, sync_mode=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..04c865500bb5e668373844e2940eaf36d1e9e39c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/profiler.py @@ -0,0 +1,30 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from .. import core + +__all__ = [ + 'start_gperf_profiler', + 'stop_gperf_profiler', +] + + +def start_gperf_profiler(): + core.start_imperative_gperf_profiler() + + +def stop_gperf_profiler(): + core.stop_imperative_gperf_profiler() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/rnn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..837287faa0f48afe9dee03c898f4c4064b9a8ceb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/rnn.py @@ -0,0 +1,460 @@ +# 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. + +from . import Layer +from ..layers import sigmoid, tanh, concat, fill_constant, matmul, elementwise_add, elementwise_mul, split +import copy + +__all__ = ['LSTMCell', 'GRUCell'] + + +class LSTMCell(Layer): + r""" + LSTMCell implementation using basic operators. + There are two LSTMCell version, the default one is compatible with CUDNN LSTM implementation. + The algorithm can be described as the equations below. + + .. math:: + + i_t &= sigmoid(W_{ix}x_{t} + W_{ih}h_{t-1} + bx_i + bh_i) + + f_t &= sigmoid(W_{fx}x_{t} + W_{fh}h_{t-1} + bx_f + bh_f) + + o_t &= sigmoid(W_{ox}x_{t} + W_{oh}h_{t-1} + bx_o + bh_o) + + \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + bx_c + bh_c) + + c_t &= f_t \\odot c_{t-1} + i_t \\odot \\tilde{c_t} + + h_t &= o_t \\odot tanh(c_t) + + The other LSTMCell version is compatible with the BasicLSTMUnit used in static graph. + The algorithm can be described as the equations below. + + .. math:: + + i_t &= sigmoid(W_{ix}x_{t} + W_{ih}h_{t-1} + b_i) + + f_t &= sigmoid(W_{fx}x_{t} + W_{fh}h_{t-1} + b_f + forget_bias ) + + o_t &= sigmoid(W_{ox}x_{t} + W_{oh}h_{t-1} + b_o) + + \\tilde{c_t} &= tanh(W_{cx}x_t + W_{ch}h_{t-1} + b_c) + + c_t &= f_t \\odot c_{t-1} + i_t \\odot \\tilde{c_t} + + h_t &= o_t \\odot tanh(c_t) + + Args: + hidden_size (integer): The hidden size used in the Cell. + input_size (integer): The input size used in the Cell. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, LSTMCell will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of LSTMCell. + If it is set to None or one attribute of ParamAttr, LSTMCell will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized as zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cells (actNode). + Default: 'fluid.layers.tanh' + forget_bias(float|1.0): forget bias used when computing forget gate. This + is not used in default LSTMCell implementation (CUDNN compatiable) + use_cudnn_impl(bool|True): whether to use CUDNN compatible LSTMCell + dtype(string): data type used in this cell + + Returns: + None + + Examples: + + .. code-block:: python + + from paddle import fluid + import paddle.fluid.core as core + from paddle.fluid.dygraph import LSTMCell + import numpy as np + batch_size = 64 + input_size = 128 + hidden_size = 256 + step_input_np = np.random.uniform(-0.1, 0.1, ( + batch_size, input_size)).astype('float64') + pre_hidden_np = np.random.uniform(-0.1, 0.1, ( + batch_size, hidden_size)).astype('float64') + pre_cell_np = np.random.uniform(-0.1, 0.1, ( + batch_size, hidden_size)).astype('float64') + if core.is_compiled_with_cuda(): + place = core.CUDAPlace(0) + else: + place = core.CPUPlace() + with fluid.dygraph.guard(place): + cudnn_lstm = LSTMCell(hidden_size, input_size) + step_input_var = fluid.dygraph.to_variable(step_input_np) + pre_hidden_var = fluid.dygraph.to_variable(pre_hidden_np) + pre_cell_var = fluid.dygraph.to_variable(pre_cell_np) + new_hidden, new_cell = cudnn_lstm(step_input_var, pre_hidden_var, pre_cell_var) + + """ + + def __init__(self, + hidden_size, + input_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + forget_bias=1.0, + use_cudnn_impl=True, + dtype='float64'): + super(LSTMCell, self).__init__(dtype) + + self._hidden_size = hidden_size + self._input_size = input_size + self._param_attr = param_attr + self._bias_attr = bias_attr + self._dtype = dtype + self._gate_activation = gate_activation or sigmoid + self._activation = activation or tanh + self._use_cudnn_impl = use_cudnn_impl + + if self._use_cudnn_impl: + + if self._param_attr is not None and self._param_attr.name is not None: + weight_ih_param_attr = copy.deepcopy(self._param_attr) + weight_hh_param_attr = copy.deepcopy(self._param_attr) + weight_ih_param_attr.name += "_weight_ih" + weight_hh_param_attr.name += "_weight_hh" + else: + weight_ih_param_attr = self._param_attr + weight_hh_param_attr = self._param_attr + + if self._bias_attr is not None and self._bias_attr.name is not None: + bias_ih_param_attr = copy.deepcopy(self._bias_attr) + bias_hh_param_attr = copy.deepcopy(self._bias_attr) + bias_ih_param_attr.name += "_bias_ih" + bias_hh_param_attr.name += "_bias_hh" + else: + bias_ih_param_attr = self._bias_attr + bias_hh_param_attr = self._bias_attr + + self._weight_ih = self.create_parameter( + attr=weight_ih_param_attr, + shape=[4 * self._hidden_size, self._input_size], + dtype=self._dtype) + + self._weight_hh = self.create_parameter( + attr=weight_hh_param_attr, + shape=[4 * self._hidden_size, self._hidden_size], + dtype=self._dtype) + + self._bias_ih = self.create_parameter(attr=bias_ih_param_attr, + shape=[4 * self._hidden_size], + dtype=self._dtype, + is_bias=True) + self._bias_hh = self.create_parameter(attr=bias_hh_param_attr, + shape=[4 * self._hidden_size], + dtype=self._dtype, + is_bias=True) + + else: + + self._forget_bias = fill_constant([1], + dtype=dtype, + value=forget_bias) + self._forget_bias.stop_gradient = False + + self._weight = self.create_parameter( + attr=self._param_attr, + shape=[ + self._input_size + self._hidden_size, 4 * self._hidden_size + ], + dtype=dtype) + + self._bias = self.create_parameter(attr=self._bias_attr, + shape=[4 * self._hidden_size], + dtype=dtype, + is_bias=True) + + def forward(self, input, pre_hidden, pre_cell): + + if self._use_cudnn_impl: + igates = matmul(input, y=self._weight_ih, transpose_y=True) + igates = elementwise_add(igates, self._bias_ih) + hgates = matmul(pre_hidden, self._weight_hh, transpose_y=True) + hgates = elementwise_add(hgates, self._bias_hh) + + chunked_igates = split(igates, num_or_sections=4, dim=1) + chunked_hgates = split(hgates, num_or_sections=4, dim=1) + + ingate = elementwise_add(chunked_igates[0], chunked_hgates[0]) + ingate = self._gate_activation(ingate) + + forgetgate = elementwise_add(chunked_igates[1], chunked_hgates[1]) + forgetgate = self._gate_activation(forgetgate) + + cellgate = elementwise_add(chunked_igates[2], chunked_hgates[2]) + cellgate = self._activation(cellgate) + + outgate = elementwise_add(chunked_igates[3], chunked_hgates[3]) + outgate = self._gate_activation(outgate) + + new_cell = (forgetgate * pre_cell) + (ingate * cellgate) + new_hidden = outgate * self._activation(new_cell) + + else: + + concat_input_hidden = concat([input, pre_hidden], 1) + gate_input = matmul(x=concat_input_hidden, y=self._weight) + + gate_input = elementwise_add(gate_input, self._bias) + i, j, f, o = split(gate_input, num_or_sections=4, dim=-1) + new_cell = elementwise_add( + elementwise_mul( + pre_cell, + self._gate_activation(elementwise_add(f, + self._forget_bias))), + elementwise_mul(sigmoid(i), tanh(j))) + new_hidden = self._activation(new_cell) * self._gate_activation(o) + + return new_hidden, new_cell + + +class GRUCell(Layer): + r""" + GRU implementation using basic operators. + There are two GRUCell version, the default one is compatible with CUDNN GRU implementation. + The algorithm can be described as the equations below. + + .. math:: + + u_t & = sigmoid(W_{ux} x_{t} + b_ux + W_{uh} h_{t-1} + b_uh) + + r_t & = sigmoid(W_{rx} x_{t} + b_rx + W_{rh} h_{t-1} + b_rh) + + \\tilde{h_{t}} & = tanh(W_{cx} x_{t} + b_cx + r_t \\odot (W_{ch} h_{t-1} + b_ch)) + + h_t & = u_t h_{t-1} + (1-u_t) \\tilde{h_{t}} + + The other LSTMCell version is compatible with the BasicGRUUnit used in static graph. + The algorithm can be described as the equations below. + + .. math:: + + u_t & = sigmoid(W_{ux} x_{t} + W_{uh} h_{t-1} + b_u) + + r_t & = sigmoid(W_{rx} x_{t} + W_{rh} h_{t-1} + b_r) + + \\tilde{h_{t}} & = tanh(W_{cx} x_{t} + W_{ch} \\odot(r_t, h_{t-1}) + b_m) + + h_t & = u_t h_{t-1} + (1-u_t) \\tilde{h_{t}} + + Args: + hidden_size (integer): The hidden size used in the Cell. + input_size (integer): The input size used in the Cell. + param_attr(ParamAttr|None): The parameter attribute for the learnable + weight matrix. Note: + If it is set to None or one attribute of ParamAttr, GRUCell will + create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|None): The parameter attribute for the bias + of GRUCell. + If it is set to None or one attribute of ParamAttr, GRUCell will + create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + gate_activation (function|None): The activation function for gates (actGate). + Default: 'fluid.layers.sigmoid' + activation (function|None): The activation function for cell (actNode). + Default: 'fluid.layers.tanh' + use_cudnn_impl(bool|True): whether to use CUDNN compatible LSTMCell + dtype(string): data type used in this cell + + Returns: + None + + Examples: + + .. code-block:: python + + from paddle import fluid + import paddle.fluid.core as core + from paddle.fluid.dygraph import GRUCell + import numpy as np + batch_size = 64 + input_size = 128 + hidden_size = 256 + step_input_np = np.random.uniform(-0.1, 0.1, ( + batch_size, input_size)).astype('float64') + pre_hidden_np = np.random.uniform(-0.1, 0.1, ( + batch_size, hidden_size)).astype('float64') + if core.is_compiled_with_cuda(): + place = core.CUDAPlace(0) + else: + place = core.CPUPlace() + with fluid.dygraph.guard(place): + cudnn_gru = GRUCell(hidden_size, input_size) + step_input_var = fluid.dygraph.to_variable(step_input_np) + pre_hidden_var = fluid.dygraph.to_variable(pre_hidden_np) + + """ + + def __init__(self, + hidden_size, + input_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + use_cudnn_impl=True, + dtype='float64'): + super(GRUCell, self).__init__() + + self._hidden_size = hidden_size + self._input_size = input_size + self._param_attr = param_attr + self._bias_attr = bias_attr + self._dtype = dtype + self._gate_activation = gate_activation or sigmoid + self._activation = activation or tanh + self._use_cudnn_impl = use_cudnn_impl + + if self._use_cudnn_impl: + + if self._param_attr is not None and self._param_attr.name is not None: + weight_ih_param_attr = copy.deepcopy(self._param_attr) + weight_hh_param_attr = copy.deepcopy(self._param_attr) + weight_ih_param_attr.name += "_weight_ih" + weight_hh_param_attr.name += "_weight_hh" + else: + weight_ih_param_attr = self._param_attr + weight_hh_param_attr = self._param_attr + + if self._bias_attr is not None and self._bias_attr.name is not None: + bias_ih_param_attr = copy.deepcopy(self._bias_attr) + bias_hh_param_attr = copy.deepcopy(self._bias_attr) + bias_ih_param_attr.name += "_bias_ih" + bias_hh_param_attr.name += "_bias_hh" + else: + bias_ih_param_attr = self._bias_attr + bias_hh_param_attr = self._bias_attr + + self._weight_ih = self.create_parameter( + attr=weight_ih_param_attr, + shape=[3 * self._hidden_size, self._input_size], + dtype=self._dtype) + + self._weight_hh = self.create_parameter( + attr=weight_hh_param_attr, + shape=[3 * self._hidden_size, self._hidden_size], + dtype=self._dtype) + + self._bias_ih = self.create_parameter(attr=bias_ih_param_attr, + shape=[3 * self._hidden_size], + dtype=self._dtype, + is_bias=True) + self._bias_hh = self.create_parameter(attr=bias_hh_param_attr, + shape=[3 * self._hidden_size], + dtype=self._dtype, + is_bias=True) + + else: + + if self._param_attr is not None and self._param_attr.name is not None: + gate_weight_param_attr = copy.deepcopy(self._param_attr) + candidate_weight_param_attr = copy.deepcopy(self._param_attr) + gate_weight_param_attr.name += "_gate_weight" + candidate_weight_param_attr.name += "_candidate_weight" + else: + gate_weight_param_attr = self._param_attr + candidate_weight_param_attr = self._param_attr + + if self._bias_attr is not None and self._bias_attr.name is not None: + gate_bias_param_attr = copy.deepcopy(self._bias_attr) + candidate_bias_param_attr = copy.deepcopy(self._bias_attr) + gate_bias_param_attr.name += "_gate_bias" + candidate_bias_param_attr.name += "_candidate_bias" + else: + gate_bias_param_attr = self._bias_attr + candidate_bias_param_attr = self._bias_attr + + self._gate_weight = self.create_parameter( + attr=gate_weight_param_attr, + shape=[ + self._input_size + self._hidden_size, 2 * self._hidden_size + ], + dtype=dtype) + + self._candidate_weight = self.create_parameter( + attr=candidate_weight_param_attr, + shape=[self._input_size + self._hidden_size, self._hidden_size], + dtype=dtype) + + self._gate_bias = self.create_parameter( + attr=gate_bias_param_attr, + shape=[2 * self._hidden_size], + dtype=dtype, + is_bias=True) + self._candidate_bias = self.create_parameter( + attr=candidate_bias_param_attr, + shape=[self._hidden_size], + dtype=dtype, + is_bias=True) + + def forward(self, input, pre_hidden): + + if self._use_cudnn_impl: + + igates = matmul(input, y=self._weight_ih, transpose_y=True) + igates = elementwise_add(igates, self._bias_ih) + hgates = matmul(pre_hidden, self._weight_hh, transpose_y=True) + hgates = elementwise_add(hgates, self._bias_hh) + + chunked_igates = split(igates, num_or_sections=3, dim=1) + chunked_hgates = split(hgates, num_or_sections=3, dim=1) + + reset_gate = elementwise_add(chunked_igates[0], chunked_hgates[0]) + reset_gate = self._gate_activation(reset_gate) + + input_gate = elementwise_add(chunked_igates[1], chunked_hgates[1]) + input_gate = self._gate_activation(input_gate) + + _temp = reset_gate * chunked_hgates[2] + new_gate = elementwise_add(chunked_igates[2], _temp) + new_gate = self._activation(new_gate) + + new_hidden = (pre_hidden - new_gate) * input_gate + new_gate + + else: + + concat_input_hidden = concat([input, pre_hidden], 1) + + gate_input = matmul(x=concat_input_hidden, y=self._gate_weight) + + gate_input = elementwise_add(gate_input, self._gate_bias) + gate_input = self._gate_activation(gate_input) + r, u = split(gate_input, num_or_sections=2, dim=1) + + r_hidden = r * pre_hidden + + candidate = matmul(concat([input, r_hidden], 1), + self._candidate_weight) + candidate = elementwise_add(candidate, self._candidate_bias) + + c = self._activation(candidate) + new_hidden = u * pre_hidden + (1 - u) * c + + return new_hidden diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/static_runner.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/static_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..e8738da07e99352f07688dd8ddde83bd31c6e1fa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/static_runner.py @@ -0,0 +1,39 @@ +# 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. + +from __future__ import print_function + +from paddle.fluid.dygraph.jit import _SaveLoadConfig +from paddle.fluid.dygraph.io import TranslatedLayer + + +# NOTE: This class will be deprecated later. +# It is kept here because PaddleHub is already using this API. +class StaticModelRunner(object): + """ + A Dynamic graph Layer for loading inference program and related parameters, + and then performing fine-tune training or inference. + + .. note:: + This is a temporary API, which will be deprecated later, please use + `fluid.dygraph.jit.load` to achieve the same function. + """ + + def __new__(cls, model_dir, model_filename=None, params_filename=None): + configs = _SaveLoadConfig() + if model_filename is not None: + configs.model_filename = model_filename + if params_filename is not None: + configs.params_filename = params_filename + return TranslatedLayer._construct(model_dir, configs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/tracer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..4627d6d11e74c520d41e6569659c414d5fa561b4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/tracer.py @@ -0,0 +1,325 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import six + +from collections import defaultdict +from paddle.fluid import core +from paddle.fluid import framework +from paddle import _C_ops, _legacy_C_ops + +name_mapping = { + "graph_send_recv": { + "final_op_name": "graph_send_recv", + "x": "X", + "src_index": "Src_index", + "dst_index": "Dst_index", + "out": "Out", + "dst_count": "Dst_count" + }, + "matmul_v2": { + "final_op_name": "matmul", + "transpose_x": "trans_x", + "transpose_y": "trans_y", + "x": "X", + "y": "Y", + "out": "Out", + }, + # "elementwise_add": { + # "final_op_name": "add", + # "x": "X", + # "y": "Y", + # }, + "trunc": { + "final_op_name": "trunc", + "x": "X", + "out": "Out", + }, + # "pool2d": { + # "final_op_name": "pool2d", + # "x": "X", + # "kernel_size": "ksize", + # "out": "Out", + # }, + "abs": { + "final_op_name": "abs", + "x": "X", + "out": "Out", + }, + "digamma": { + "final_op_name": "digamma", + "x": "X", + "out": "Out", + }, + "diagonal": { + "final_op_name": "diagonal", + "x": "Input", + "offset": "offset", + "axis1": "axis1", + "axis2": "axis2", + "out": "Out", + }, + "roi_align": { + "final_op_name": "roi_align", + "x": "X", + "boxes": "ROIs", + "boxes_num": "RoisNum", + "pooled_height": "pooled_height", + "pooled_width": "pooled_width", + "spatial_scale": "spatial_scale", + "sampling_ratio": "sampling_ratio", + "aligned": "aligned", + }, + # "one_hot": { + # "final_op_name": "one_hot", + # "x": "X", + # "num_class": "depth", + # "out": "Out", + # } +} + + +class Tracer(core.Tracer): + """ + :api_attr: imperative + + Tracer is used to execute and record the operators executed, to construct the + computation graph in dygraph model. Tracer has two mode, :code:`train_mode` + and :code:`eval_mode`. In :code:`train_mode`, Tracer would add backward network + automatically and perform AutoGrad by method :code:`loss.backward()`. + In :code:`eval_mode`, Tracer would not add backward network. + + This is a low level API, users don't need to use it directly. + """ + + def __init__(self): + super(Tracer, self).__init__() + + self._train_mode = True + + def eager_legacy_trace_op(self, + op_type, + inputs, + outputs, + attrs, + stop_gradient=False, + inplace_map=None): + function_ptr = _legacy_C_ops.__dict__[op_type] + + core_ops_args_info = _legacy_C_ops.get_core_ops_args_info() + core_ops_args_type_info = _legacy_C_ops.get_core_ops_args_type_info() + core_ops_returns_info = _legacy_C_ops.get_core_ops_returns_info() + + op_args = core_ops_args_info[op_type] + op_args_type = core_ops_args_type_info[op_type] + op_returns = core_ops_returns_info[op_type] + + arg_list = [] + for i in range(len(op_args)): + # initialized with None + arg_to_append = None + + arg_name = op_args[i] + arg_type = op_args_type[i] + if arg_name in inputs.keys(): + arg_to_append = inputs[arg_name] + elif arg_name in outputs.keys(): + arg_to_append = outputs[arg_name] + else: + if "Num" in arg_name[-3:]: + # Remove "Num" suffix to get out_name + out_name = arg_name[:-3] + assert out_name in outputs.keys() + num_outs = len(outputs[out_name]) + arg_to_append = num_outs + # NOTE(dev): For MasterParam/MasterParamOut in optimzer op + elif "Var" in arg_name[-3:]: + out_name = arg_name[:-3] + print(out_name) + if out_name in outputs.keys(): + arg_to_append = outputs[out_name] + elif out_name in inputs.keys(): + arg_to_append = inputs[out_name] + + if arg_to_append is None: + arg_list.append(arg_to_append) + elif arg_type == "tensor": + if isinstance(arg_to_append, list): + arg_list.append(arg_to_append[0]) + else: + arg_list.append(arg_to_append) + elif arg_type == "list": + assert isinstance(arg_to_append, list) + arg_list.append(arg_to_append) + else: + assert arg_type == "int" + assert isinstance(arg_to_append, int) + arg_list.append(arg_to_append) + + attrs_list = [] + for k, v in attrs.items(): + attrs_list.append(k) + attrs_list.append(v) + returns = function_ptr(*arg_list, *attrs_list) + + if op_type == 'load_combine': + assert len(outputs.keys()) == 1 + key = list(outputs.keys())[0] + for j in range(len(returns)): + returns[j]._share_underline_tensor_to(outputs[key][j]) + return + + if isinstance(returns, tuple): + for i in range(len(op_returns)): + retname = op_returns[i] + if retname in outputs.keys(): + # Replaced outputs by function returns + if isinstance(returns[i], list): + for j in range(len(returns[i])): + outputs[retname][j].reconstruct_from_( + returns[i][j], False) + else: + if isinstance(outputs[retname], list): + outputs[retname][0].reconstruct_from_( + returns[i], False) + else: + outputs[retname].reconstruct_from_( + returns[i], False) + elif isinstance(returns, list): + assert len(outputs.keys()) == 1 + key = list(outputs.keys())[0] + for j in range(len(returns)): + outputs[key][j].reconstruct_from_(returns[j], False) + else: + assert len(outputs.keys()) == 1 + key = list(outputs.keys())[0] + if isinstance(outputs[key], list): + outputs[key][0].reconstruct_from_(returns, False) + else: + outputs[key].reconstruct_from_(returns, False) + + def eager_trace_op(self, + op_type, + inputs, + outputs, + attrs, + stop_gradient=False, + inplace_map=None): + assert op_type in name_mapping.keys() + + op_type = name_mapping[op_type]["final_op_name"] + function_ptr = _C_ops.__dict__[op_type] + + core_ops_args_info = _C_ops.get_core_ops_args_info() + core_ops_args_type_info = _C_ops.get_core_ops_args_type_info() + core_ops_returns_info = _C_ops.get_core_ops_returns_info() + + op_args = core_ops_args_info[op_type] + op_args_type = core_ops_args_type_info[op_type] + op_returns = core_ops_returns_info[op_type] + + arg_list = [] + for i in range(len(op_args)): + eager_arg_name = op_args[i] + arg_type = op_args_type[i] + + assert eager_arg_name in name_mapping[op_type].keys() + arg_name = name_mapping[op_type][eager_arg_name] + + if arg_name in inputs.keys(): + arg_to_append = inputs[arg_name] + elif arg_name in outputs.keys(): + arg_to_append = outputs[arg_name] + elif arg_name in attrs.keys() and arg_type == "": + arg_to_append = attrs[arg_name] + else: + # dispensable + arg_to_append = None + + if arg_type == "": + # attribute + arg_list.append(arg_to_append) + elif arg_type == "tensor": + if isinstance(arg_to_append, list): + arg_list.append(arg_to_append[0]) + else: + arg_list.append(arg_to_append) + elif arg_type == "list": + assert isinstance(arg_to_append, list) + arg_list.append(arg_to_append) + else: + assert arg_to_append is None + arg_list.append(arg_to_append) + + returns = function_ptr(*arg_list) + + if isinstance(returns, tuple): + for i in range(len(op_returns)): + eager_retname = op_returns[i] + + assert eager_retname in name_mapping[op_type].keys() + retname = name_mapping[op_type][eager_retname] + if retname in outputs.keys(): + # Replaced outputs by function returns + if isinstance(returns[i], list): + for j in range(len(returns[i])): + outputs[retname][j].reconstruct_from_( + returns[i][j], False) + else: + outputs[retname][0].reconstruct_from_(returns[i], False) + elif isinstance(returns, list): + assert len(outputs.keys()) == 1 + key = list(outputs.keys())[0] + for j in range(len(returns)): + outputs[key][j].reconstruct_from_(returns[j], False) + else: + assert len(outputs.keys()) == 1 + key = list(outputs.keys())[0] + if isinstance(outputs[key], list): + outputs[key][0].reconstruct_from_(returns, False) + else: + outputs[key].reconstruct_from_(returns, False) + + def trace_op(self, + type, + inputs, + outputs, + attrs, + stop_gradient=False, + inplace_map=None): + if not framework._in_legacy_dygraph(): + # inputs : {"sum": [tensor], ...} + # outputs : {"sum": [tensor], ...} + if type in name_mapping.keys(): + type = name_mapping[type]["final_op_name"] + + assert type in _legacy_C_ops.__dict__ + self.eager_trace_op(type, inputs, outputs, attrs, stop_gradient, + inplace_map) + else: + self.eager_legacy_trace_op(type, inputs, outputs, attrs, + stop_gradient, inplace_map) + else: + self.trace(type, inputs, outputs, attrs, + framework._current_expected_place(), self._has_grad + and not stop_gradient, + inplace_map if inplace_map else {}) + + def train_mode(self): + self._train_mode = True + + def eval_mode(self): + self._train_mode = False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/varbase_patch_methods.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/varbase_patch_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f89b295c7982c646c103989b5673c32d34e30d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph/varbase_patch_methods.py @@ -0,0 +1,1047 @@ +# 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. + +import inspect +import numpy as np +import warnings +import weakref +import sys + +import paddle +from .. import framework +from ..framework import convert_np_dtype_to_dtype_, _in_legacy_dygraph +from .. import core +from .. import unique_name +from ..framework import Variable, Parameter, ParamBase, _getitem_impl_, _setitem_impl_, EagerParamBase, in_dygraph_mode +from .base import switch_to_static_graph +from .math_op_patch import monkey_patch_math_varbase +from .parallel import scale_loss +from paddle.fluid.data_feeder import convert_dtype, _PADDLE_DTYPE_2_NUMPY_DTYPE +import paddle.utils.deprecated as deprecated +import paddle.profiler as profiler +from paddle.profiler.utils import in_profiler_mode +from paddle import _C_ops, _legacy_C_ops + +_grad_scalar = None + + +class TensorHookRemoveHelper(object): + """ + A helper class that for removing Tensor gradient's hook. + NOTE(wuweilong):the operation weakref.ref(tensor) will cause some unexpected errors in eager mode. + """ + + def __init__(self, tensor, hook_id): + self._tensor = tensor if framework._in_eager_mode_ else weakref.ref( + tensor) + self._hook_id = hook_id + + def remove(self): + """ + Remove reference Tensor's hook. + + Returns: + bool: Return True if removed successfully + """ + tensor = self._tensor if framework._in_eager_mode_ else self._tensor() + if tensor is not None: + res = tensor._remove_grad_hook(self._hook_id) + if res is True: + return True + else: + warnings.warn( + "The backward hook (ID: %d) of Tensor `%s` you want to remove does not exist or has been removed." + % (self._hook_id, tensor.name), RuntimeWarning) + return False + + +_already_patch_repr = False + + +def monkey_patch_varbase(): + + @switch_to_static_graph + def _to_static_var(self, to_parameter=False, **kwargs): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + Transform a VarBase into static Variable with same attributes. It's a low level interface used + in dy2static and shall not be called directly. + + Args: + to_parameter (bool): It takes effect only if the input a VarBase. If set True, + the VarBase will be converted into framework.Parameters. Otherwise, it will + be converted into framework.Variable. Default False. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + import numpy as np + + data = np.ones([3, 1024], dtype='float32') + with fluid.dygraph.guard(): + var_base = to_variable(data) + static_var = var_base._to_static_var() + + """ + + # Note: getattr(self, attr, None) will call x.grad=x.gradient(), but gradient() only available in dygraph. + # It will fail. So, for propery that different between dynamic and static graph, should not getattr(self, attr, None). + attr_not_need_keys = ['grad', 'T', 'place', '_place_str'] + param_keys = ['stop_gradient', 'trainable'] + if isinstance(self, (ParamBase, EagerParamBase)): + attr_kwargs = self.__dict__.copy() + for key in param_keys: + attr_kwargs[key] = getattr(self, key) + else: + attr_names = [] + for name in dir(self): + if name not in attr_not_need_keys: + if not inspect.ismethod(getattr( + self, name)) and not name.startswith('_'): + attr_names.append(name) + attr_kwargs = {name: getattr(self, name) for name in attr_names} + + attr_keys = ['block', 'shape', 'dtype', 'type', 'name', 'persistable'] + for attr in attr_keys: + attr_kwargs[attr] = getattr(self, attr, None) + + # If specify block, use it instead of self.block + if 'block' in kwargs: + attr_kwargs['block'] = kwargs['block'] + + attr_kwargs.update(kwargs) + + if to_parameter or isinstance(self, (ParamBase, EagerParamBase)): + del attr_kwargs['persistable'] + # NOTE(Aurelius84): All parameters should be placed into global block. + attr_kwargs['block'] = attr_kwargs['block'].program.global_block() + static_var = Parameter(**attr_kwargs) + else: + static_var = Variable(**attr_kwargs) + return static_var + + # TODO(jiabin): move this to cplusplus end if we find some performance issue on it + @framework.dygraph_only + def set_value(self, value): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + Set a new value for this Variable. + + Args: + value (Variable|np.ndarray): the new value. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + from paddle.fluid.dygraph import Linear + import numpy as np + + data = np.ones([3, 1024], dtype='float32') + with fluid.dygraph.guard(): + linear = fluid.dygraph.Linear(1024, 4) + t = to_variable(data) + linear(t) # call with default weight + custom_weight = np.random.randn(1024, 4).astype("float32") + linear.weight.set_value(custom_weight) # change existing weight + out = linear(t) # call with different weight + + """ + if framework._in_eager_mode_: + base_tensor = core.eager.Tensor + else: + base_tensor = core.VarBase + assert isinstance(value, (np.ndarray, base_tensor, dict, str)), \ + "Variable set_value function, arguments type only support Variable, numpy, VarBase, dict, string." + + if isinstance(value, (dict, str)): + assert len(self) == len( + value + ), "Variable length not match, Variable [ {} ] need tensor with length {} but load set tensor with length {}".format( + self.name, len(self), len(value)) + if isinstance(value, dict): + self.value().set_vocab(value) + else: + self.value().set_string_list(value) + else: + assert self.shape == list(value.shape), \ + "Variable Shape not match, Variable [ {} ] need tensor with shape {} but load set tensor with shape {}".format( + self.name, self.shape, value.shape) + + if isinstance(value, base_tensor): + dtype = value.dtype + else: + dtype = convert_np_dtype_to_dtype_(value.dtype) + + assert self.dtype == dtype, \ + "Variable dtype not match, Variable [ {} ] need tensor with dtype {} but load tensor with dtype {}".format( + self.name, self.dtype, dtype) + + # NOTE(wuweilong): self could be VarBase or Tensor, the subsequent behavior are defined in different files + # if self is VarBase, method value() return Variable that bindded in imperative.cc, get_tensor() bindded in pybind.cc + # if self is Tensor, method value() return self that defined in this file, get_tensor() defined in eager_method.cc + # this Interface behavior will be unifed in the future. + self.value().get_tensor().set(value, + framework._current_expected_place()) + + @framework.dygraph_only + def backward(self, grad_tensor=None, retain_graph=False): + """ + Run backward of current Graph which starts from current Tensor. + + The new gradient will accumulat on previous gradient. + + You can clear gradient by ``Tensor.clear_grad()`` . + + Args: + grad_tensor(Tensor, optional): initial gradient values of the current Tensor. If `grad_tensor` is None, + the initial gradient values of the current Tensor would be Tensor filled with 1.0; + if `grad_tensor` is not None, it must have the same length as the current Tensor. + Teh default value is None. + + retain_graph(bool, optional): If False, the graph used to compute grads will be freed. If you would + like to add more ops to the built graph after calling this method( :code:`backward` ), set the parameter + :code:`retain_graph` to True, then the grads will be retained. Thus, seting it to False is much more memory-efficient. + Defaults to False. + Returns: + NoneType: None + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor(5., stop_gradient=False) + for i in range(5): + y = paddle.pow(x, 4.0) + y.backward() + print("{}: {}".format(i, x.grad)) + # 0: [500.] + # 1: [1000.] + # 2: [1500.] + # 3: [2000.] + # 4: [2500.] + + x.clear_grad() + print("{}".format(x.grad)) + # 0. + + grad_tensor=paddle.to_tensor(2.) + for i in range(5): + y = paddle.pow(x, 4.0) + y.backward(grad_tensor) + print("{}: {}".format(i, x.grad)) + # 0: [1000.] + # 1: [2000.] + # 2: [3000.] + # 3: [4000.] + # 4: [5000.] + + """ + if framework._non_static_mode(): + if in_profiler_mode(): + record_event = profiler.RecordEvent( + "Gradient Backward", profiler.TracerEventType.Backward) + record_event.begin() + if grad_tensor is not None: + if framework._in_eager_mode_: + assert isinstance( + grad_tensor, core.eager.Tensor + ), "The type of grad_tensor must be paddle.Tensor" + else: + assert isinstance( + grad_tensor, paddle.Tensor + ), "The type of grad_tensor must be paddle.Tensor" + assert grad_tensor.shape == self.shape, \ + "Tensor shape not match, Tensor of grad_tensor [ {} ] with shape {} mismatch Tensor [ {} ] with shape {}".format( + grad_tensor.name, grad_tensor.shape, self.name, self.shape) + + if framework._in_eager_mode_: + if grad_tensor is None: + grad_tensor = [] + else: + grad_tensor = [grad_tensor] + if _grad_scalar: + # When using amp with Fleet DistributedStrategy, we do loss scaling implicitly. + self = _grad_scalar.scale(self) + if paddle.is_compiled_with_xpu() or paddle.is_compiled_with_npu( + ) or paddle.is_compiled_with_mlu(): + # TODO(liuyuhui): Currently only for xpu. Will be removed in the future. + scaled_loss = scale_loss(self) + if framework._in_eager_mode_: + core.eager.run_backward([scaled_loss], grad_tensor, + retain_graph) + else: + core.dygraph_run_backward([scaled_loss], [grad_tensor], + retain_graph, + framework._dygraph_tracer()) + else: + if framework._in_eager_mode_: + core.eager.run_backward([self], grad_tensor, retain_graph) + else: + core.dygraph_run_backward([self], [grad_tensor], + retain_graph, + framework._dygraph_tracer()) + if in_profiler_mode(): + record_event.end() + else: + raise ValueError( + "Variable.backward() is only available in DyGraph mode") + + @framework.dygraph_only + @deprecated( + since="2.1.0", + level=1, + reason= + "Please use tensor.grad, which returns the tensor value of the gradient." + ) + def gradient(self): + """ + .. warning:: + This API will be deprecated in the future, it is recommended to use + :code:`x.grad` which returns the tensor value of the gradient. + + Get the Gradient of Current Tensor. + + Returns: + ndarray: Numpy value of the gradient of current Tensor + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor(5., stop_gradient=False) + y = paddle.pow(x, 4.0) + y.backward() + print("grad of x: {}".format(x.gradient())) + # [500.] + + """ + if framework._in_eager_mode_: + if self.grad is None: + return None + if self.grad.is_selected_rows(): + return (np.array(self.grad.numpy()), np.array(self.grad.rows())) + return self.grad.numpy() + else: + if self._grad_ivar() is None: + return None + + new_ivar = self._grad_ivar()._copy_to(core.CPUPlace(), True) + if self._grad_ivar().type == core.VarDesc.VarType.SELECTED_ROWS: + return (np.array( + new_ivar.value().get_selected_rows().get_tensor()), + np.array(new_ivar.value().get_selected_rows().rows())) + else: + return np.array(new_ivar.value().get_tensor()) + + @framework.dygraph_only + def register_hook(self, hook): + """ + Registers a backward hook for current Tensor. + + The hook will be called every time the gradient Tensor of current Tensor is computed. + + The hook should not modify the input gradient Tensor, but it can optionally return + a new gradient Tensor which will be used in place of current Tensor's gradient. + + The hook should have the following signature: + + hook(grad) -> Tensor or None + + Args: + hook(function): A backward hook to be registered for Tensor.grad + + Returns: + TensorHookRemoveHelper: A helper object that can be used to remove the registered hook by calling `remove()` method. + + Examples: + .. code-block:: python + + import paddle + + # hook function return None + def print_hook_fn(grad): + print(grad) + + # hook function return Tensor + def double_hook_fn(grad): + grad = grad * 2 + return grad + + x = paddle.to_tensor([0., 1., 2., 3.], stop_gradient=False) + y = paddle.to_tensor([4., 5., 6., 7.], stop_gradient=False) + z = paddle.to_tensor([1., 2., 3., 4.]) + + # one Tensor can register multiple hooks + h = x.register_hook(print_hook_fn) + x.register_hook(double_hook_fn) + + w = x + y + # register hook by lambda function + w.register_hook(lambda grad: grad * 2) + + o = z.matmul(w) + o.backward() + # print_hook_fn print content in backward + # Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [2., 4., 6., 8.]) + + print("w.grad:", w.grad) # w.grad: [1. 2. 3. 4.] + print("x.grad:", x.grad) # x.grad: [ 4. 8. 12. 16.] + print("y.grad:", y.grad) # y.grad: [2. 4. 6. 8.] + + # remove hook + h.remove() + """ + if self.stop_gradient is True: + raise RuntimeError( + "Cannot register hook on a tensor that stop gradient.") + + hook_id = self._register_grad_hook(hook) + helper = TensorHookRemoveHelper(self, hook_id) + return helper + + @framework.dygraph_only + def _to(self, device=None, dtype=None, blocking=None): + + if device is None and dtype is None and blocking is None: + return self + + if device is not None: + if isinstance(device, str): + device = paddle.device._convert_to_place(device) + elif isinstance( + device, + (core.CPUPlace, core.CUDAPlace, core.CUDAPinnedPlace, + core.XPUPlace, core.CustomPlace)): + pass + else: + raise ValueError( + "device value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace(), paddle.XPUPlace() or paddle.CustomPlace(), but the type of device is " + + type(device).__name__) + + if blocking is None: + blocking = True + else: + assert isinstance( + blocking, + bool), "blocking value error, must be the True, False or None" + + def transform(t, device, dtype, blocking): + if device is None: + device = t.place + if dtype is None: + dtype = t.dtype + if type(dtype) is str: + dtype = framework.convert_np_dtype_to_dtype_(dtype) + + # 1. gpu place need to determine whether the memory is sufficient for allocation. + if t.place.is_gpu_place(): + size_dtype = core.size_of_dtype(dtype) + # Note(weilong wu): Paddle GPU minimum memory allocation unit is 256 bytes, + # waiting_alloc_memory will compute the memory space occupied by 't'. + # Coefficient 1.2 is used to avoid OOM that may occur in this critical state when the memory is just enough. + waiting_alloc_memory = ( + (t._numel() * size_dtype) / 256 + 1) * 256 * 1.2 + gpu_memory_available = core.gpu_memory_available() + if gpu_memory_available < waiting_alloc_memory: + # Copy Tensor to cpu + t_used = t._copy_to(paddle.CPUPlace(), blocking) + # Release memory of t + t._clear() + else: + # Tensor still in GPU + t_used = t + else: + t_used = t + + # 2. cast Tensor to dtype + if dtype is not None and dtype != t_used.dtype: + with paddle.fluid.framework._dygraph_place_guard( + place=t_used.place): + t_casted = t_used.cast(dtype=dtype) + else: + t_casted = t_used + + # 3. Copy casted Tensor(in CPU or GPU) to device + if device is not None and not t_casted.place._equals(device): + new_t = t_casted._copy_to(device, blocking) + else: + new_t = t_casted + + # 4. Share Tensor to origin Tensor + dst_tensor = t.value().get_tensor() + src_tensor = new_t.value().get_tensor() + dst_tensor._share_data_with(src_tensor) + + return t + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=UserWarning) + return transform(self, device, dtype, blocking) + + @property + def grad(self): + """ + .. warning:: + This API will return the tensor value of the gradient. If you want + to get the numpy value of the gradient, you can use :code:`x.grad.numpy()`. + + Get the Gradient of Current Tensor. + + Returns: + Tensor: the gradient of current Tensor + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor(5., stop_gradient=False) + y = paddle.pow(x, 4.0) + y.backward() + print("grad of x: {}".format(x.grad)) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=False, [500.]) + + """ + msg = 'tensor.grad will return the tensor value of the gradient.' \ + ' This is an incompatible upgrade for tensor.grad API. ' \ + ' It\'s return type changes from numpy.ndarray in version 2.0 to paddle.Tensor in version 2.1.0. ' \ + ' If you want to get the numpy value of the gradient, you can use :code:`x.grad.numpy()`' + warning_msg = "\033[93m\nWarning:\n%s \033[0m" % (msg) + # ensure ANSI escape sequences print correctly in cmd and powershell + if sys.platform.lower() == 'win32': + warning_msg = "\nWarning:\n%s " % (msg) + warnings.warn(warning_msg) + return self._grad_ivar() + + def clear_grad(self): + """ + The alias of clear_gradient(). + """ + self.clear_gradient() + + def item(self, *args): + """ + Convert element at specific position in Tensor into Python scalars. If the position is not specified, the Tensor must be a + single-element Tensor. + + Args: + *args(int): The input coordinates. If it's single int, the data in the corresponding order of flattened Tensor will be returned. + Default: None, and it must be in the case where Tensor has only one element. + + Returns(Python scalar): A Python scalar, whose dtype is corresponds to the dtype of Tensor. + + Raises: + ValueError: If the Tensor has more than one element, there must be coordinates. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor(1) + print(x.item()) #1 + print(type(x.item())) # + + x = paddle.to_tensor(1.0) + print(x.item()) #1.0 + print(type(x.item())) # + + x = paddle.to_tensor(True) + print(x.item()) #True + print(type(x.item())) # + + x = paddle.to_tensor(1+1j) + print(x.item()) #(1+1j) + print(type(x.item())) # + + x = paddle.to_tensor([[1.1, 2.2, 3.3]]) + print(x.item(2)) #3.3 + print(x.item(0, 2)) #3.3 + + """ + return self._getitem_from_offset(*args).item() + + @property + def inplace_version(self): + """ + The inplace version of current Tensor. + The version number is incremented whenever the current Tensor is modified through an inplace operation. + + **Notes: This is a read-only property** + + Examples: + .. code-block:: python + + import paddle + var = paddle.ones(shape=[4, 2, 3], dtype="float32") + print(var.inplace_version) # 0 + + var[1] = 2.2 + print(var.inplace_version) # 1 + + """ + return self._inplace_version() + + def __str__(self): + """ + Convert a VarBase object to a readable string. + + Returns(str): A readable string. + + Examples: + .. code-block:: python + + import paddle + x = paddle.rand([2, 5]) + print(x) + + # Tensor(shape=[2, 5], dtype=float32, place=CPUPlace, + # [[0.30574632, 0.55739117, 0.30902600, 0.39413780, 0.44830436], + # [0.79010487, 0.53972793, 0.09495186, 0.44267157, 0.72112119]]) + """ + if framework._in_eager_mode_: + from paddle.tensor.to_string import tensor_to_string + return tensor_to_string(self) + else: + from paddle.tensor.to_string import to_string + return to_string(self) + + def __deepcopy__(self, memo): + """ + Deep copy Tensor, it will always performs Tensor copy. + + Examples: + .. code-block:: python + + import paddle + import copy + x = paddle.to_tensor(2.) + y = copy.deepcopy(x) + + print(x) + # Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=True, + # [2.]) + + print(y) + # Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=True, + # [2.]) + + """ + if not self.is_leaf: + raise RuntimeError( + "Only Leaf Tensor support the deepcopy at the moment, non-Leaf Tensors contains graph information that does't support deepcopy" + ) + if framework._in_eager_mode_: + new_varbase = core.eager.Tensor() + else: + new_varbase = core.VarBase() + new_varbase.name = self.name + unique_name.generate("_deepcopy") + memo[id(self)] = new_varbase + new_varbase.copy_(self, True) + return new_varbase + + @property + def block(self): + return framework.default_main_program().global_block() + + def __nonzero__(self): + numel = np.prod(self.shape) + assert numel == 1, "When Variable is used as the condition of if/while , Variable can only contain one element." + if framework._in_eager_mode_: + assert self._is_initialized(), "tensor not initialized" + return bool(np.all(self.numpy() > 0)) + else: + tensor = self.value().get_tensor() + assert tensor._is_initialized(), "tensor not initialized" + return bool(np.all(tensor.__array__() > 0)) + + def __bool__(self): + return self.__nonzero__() + + def __array__(self, dtype=None): + """ + Returns a numpy array shows the value of current Tensor. + + Returns: + ndarray: The numpy value of current Tensor. + + Returns type: + ndarray: dtype is same as current Tensor + + Examples: + .. code-block:: python + + import paddle + import numpy as np + x = paddle.randn([2, 2]) + x_array = np.array(x) + + print(type(x_array)) # + print(x_array.shape) #(2, 2) + """ + array = self.numpy() + if dtype: + array = array.astype(dtype) + return array + + def contain_tensor(item): + if not isinstance(item, (tuple, list)): + item = [item] + + for slice_item in item: + if isinstance(slice_item, slice): + if isinstance(slice_item.start, Variable) \ + or isinstance(slice_item.stop, Variable) \ + or isinstance(slice_item.step, Variable): + return True + else: + if isinstance( + slice_item, + (Variable, np.ndarray)) and Variable.dtype != paddle.bool: + return True + return False + + def __getitem__(self, item): + + def is_list_tuple(index, contain_type): + + def _is_list_tuple(item): + if isinstance(item, (tuple, list)): + for s in item: + if not _is_list_tuple(s): + return False + else: + if type(item) != contain_type: + return False + return True + + if not isinstance(index, (tuple, list)): + return False + for s in index: + if not _is_list_tuple(s): + return False + return True + + if contain_tensor(item) or is_list_tuple(item, int): + # 1. Call _getitem_impl_ when item contains tensor. + # Why not call a c++ function ? Because item can't be parsed when it contains tensor. + return _getitem_impl_(self, item) + + else: + # 2. Call c++ func getitem_index_not_tensor to speedup. + return self._getitem_index_not_tensor(item) + + def __setitem__(self, item, value): + + def contain_tensor_or_list(item): + if not isinstance(item, tuple): + item = [item] + + for slice_item in item: + if isinstance(slice_item, list): + return True + elif isinstance(slice_item, Variable): + return True + + return False + + def is_combine_index(item): + var_type = None + item_type = None + if isinstance(item, (tuple, list)): + for slice_item in item: + if item_type is None: + item_type = type(slice_item) + else: + if type(slice_item) != item_type: + return True + + if isinstance(slice_item, Variable): + if var_type is None: + var_type = slice_item.dtype + else: + if var_type != slice_item.dtype: + return True + return False + + return False + + if contain_tensor_or_list(item) and not is_combine_index(item): + # To reuse code with static graph, + # Call _setitem_impl_ when item contains tensor or list. + return _setitem_impl_(self, item, value) + + else: + if framework._in_eager_mode_: + return self.__setitem_eager_tensor__(item, value) + else: + # Call c++ func __setitem_varbase__ to speedup. + return self.__setitem_varbase__(item, value) + + @framework.dygraph_only + def _grad_ivar(self): + if self.grad is not None: + if self.grad._is_initialized(): + return self.grad + return None + + @framework.dygraph_only + def _set_grad_ivar(self, value): + if isinstance(self, EagerParamBase): + self.grad = value + self._unset_fake_empty() + else: + raise TypeError( + "_set_grad_ivar is only supported for Parameter Tensor") + + @framework.dygraph_only + def clone(self): + if in_dygraph_mode(): + return _C_ops.assign(self) + + if _in_legacy_dygraph(): + output = core.VarBase() + else: + output = core.eager.Tensor() + return _legacy_C_ops.assign(self, output) + + @framework.dygraph_only + def value(self): + return self + + @framework.dygraph_only + def _slice(self, begin_idx, end_idx): + return core.eager.Tensor(self.get_tensor()._slice(begin_idx, end_idx)) + + @framework.dygraph_only + def _numel(self): + return self.get_tensor()._numel() + + @framework.dygraph_only + def _clear_data(self): + self.get_tensor()._clear() + + @framework.dygraph_only + def _uva(self, device_id=0): + ''' + Returns self tensor with the UVA(unified virtual addressing). + + Args: + device_id(int, optional): The destination GPU device id. Default: None, means current device. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + x = paddle.to_tensor([1, 2, 3], place=paddle.CPUPlace()) + x._uva() + print(x) + ''' + self._tensor_uva(device_id) + + @framework.dygraph_only + def cpu(self): + if self.place.is_cpu_place(): + return self + else: + res = self._copy_to(core.CPUPlace(), True) + res.stop_gradient = self.stop_gradient + res.persistable = self.persistable + return res + + @framework.dygraph_only + def cuda(self, device_id=None, blocking=True): + if device_id is None: + res_place = framework._current_expected_place() + if not isinstance(res_place, core.CUDAPlace): + res_place = core.CUDAPlace(0) + elif isinstance(device_id, int): + res_place = core.CUDAPlace(device_id) + else: + raise ValueError("device_id must be int|None") + + if self.place._equals(res_place): + return self + else: + res = self._copy_to(res_place, True) + res.stop_gradient = self.stop_gradient + res.persistable = self.persistable + return res + + @framework.dygraph_only + def pin_memory(self): + if self.place.is_cuda_pinned_place(): + return self + else: + res = self._copy_to(core.CUDAPinnedPlace(), True) + res.stop_gradient = self.stop_gradient + res.persistable = self.persistable + return res + + @framework.dygraph_only + def values(self): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + Get the values of current SparseTensor(COO or CSR). + + Returns: + Tensor: A DenseTensor + + Examples: + .. code-block:: python + + import paddle + from paddle.fluid.framework import _test_eager_guard + with _test_eager_guard(): + indices = [[0, 0, 1, 2, 2], [1, 3, 2, 0, 1]] + values = [1, 2, 3, 4, 5] + dense_shape = [3, 4] + sparse_x = paddle.sparse.sparse_coo_tensor(paddle.to_tensor(indices, dtype='int32'), paddle.to_tensor(values, dtype='float32'), shape=dense_shape) + print(sparse_x.values()) + #[1, 2, 3, 4, 5] + """ + return _C_ops.sparse_values(self) + + @framework.dygraph_only + def to_dense(self): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + Convert the current SparseTensor(COO or CSR) to DenseTensor. + + Returns: + Tensor: A DenseTensor + + Examples: + .. code-block:: python + + import paddle + from paddle.fluid.framework import _test_eager_guard + with _test_eager_guard(): + indices = [[0, 0, 1, 2, 2], [1, 3, 2, 0, 1]] + values = [1, 2, 3, 4, 5] + dense_shape = [3, 4] + sparse_x = paddle.sparse.sparse_coo_tensor(paddle.to_tensor(indices, dtype='int64'), paddle.to_tensor(values, dtype='float32'), shape=dense_shape) + dense_x = sparse_x.to_dense() + #[[0., 1., 0., 2.], + # [0., 0., 3., 0.], + # [4., 5., 0., 0.]] + """ + + return _C_ops.sparse_to_dense(self) + + @framework.dygraph_only + def to_sparse_coo(self, sparse_dim): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + Convert the current DenseTensor to SparseTensor in COO format. + + Returns: + Tensor: A SparseCooTensor + + Examples: + .. code-block:: python + + import paddle + from paddle.fluid.framework import _test_eager_guard + with _test_eager_guard(): + dense_x = [[0, 1, 0, 2], [0, 0, 3, 4]] + dense_x = paddle.to_tensor(dense_x, dtype='float32') + sparse_x = dense_x.to_sparse_coo(sparse_dim=2) + #indices=[[0, 0, 1, 1], + # [1, 3, 2, 3]], + #values=[1., 2., 3., 4.] + """ + + return _C_ops.sparse_to_sparse_coo(self, sparse_dim) + + if framework._in_eager_mode_ and not hasattr(core, "eager"): + return + + for method_name, method in (("__bool__", __bool__), ("__nonzero__", + __nonzero__), + ("_to_static_var", + _to_static_var), ("set_value", set_value), + ("block", block), ("backward", backward), + ("clear_grad", clear_grad), ("inplace_version", + inplace_version), + ("gradient", gradient), ("register_hook", + register_hook), + ("__str__", __str__), ("__repr__", __str__), + ("__deepcopy__", __deepcopy__), ("__module__", + "paddle"), + ("__array__", + __array__), ("__getitem__", + __getitem__), ("item", item), + ("__setitem__", + __setitem__), ("_to", _to), ("values", values), + ("to_dense", to_dense), ("to_sparse_coo", + to_sparse_coo)): + if framework._in_eager_mode_: + setattr(core.eager.Tensor, method_name, method) + else: + setattr(core.VarBase, method_name, method) + + if framework._in_eager_mode_: + setattr(core.eager.Tensor, "_grad_ivar", _grad_ivar) + setattr(core.eager.Tensor, "_set_grad_ivar", _set_grad_ivar) + setattr(core.eager.Tensor, "clone", clone) + setattr(core.eager.Tensor, "value", value) + setattr(core.eager.Tensor, "cpu", cpu) + setattr(core.eager.Tensor, "cuda", cuda) + setattr(core.eager.Tensor, "pin_memory", pin_memory) + setattr(core.eager.Tensor, "_slice", _slice) + setattr(core.eager.Tensor, "_numel", _numel) + setattr(core.eager.Tensor, "_uva", _uva) + setattr(core.eager.Tensor, "_clear_data", _clear_data) + else: + setattr(core.VarBase, "__name__", "Tensor") + setattr(core.VarBase, "grad", grad) + + global _already_patch_repr + if not _already_patch_repr: + # NOTE(zhiqiu): pybind11 will set a default __str__ method of enum class. + # So, we need to overwrite it to a more readable one. + # See details in https://github.com/pybind/pybind11/issues/2537. + origin = getattr(core.VarDesc.VarType, "__repr__") + + def dtype_str(dtype): + if dtype in _PADDLE_DTYPE_2_NUMPY_DTYPE: + numpy_dtype = _PADDLE_DTYPE_2_NUMPY_DTYPE[dtype] + if numpy_dtype == 'uint16': + numpy_dtype = 'bfloat16' + prefix = 'paddle.' + return prefix + numpy_dtype + else: + # for example, paddle.fluid.core.VarDesc.VarType.LOD_TENSOR + return origin(dtype) + + setattr(core.VarDesc.VarType, "__repr__", dtype_str) + _already_patch_repr = True + + # patch math methods for varbase + monkey_patch_math_varbase() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..849191f54630213cb38db593d6796a1139208859 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/dygraph_utils.py @@ -0,0 +1,64 @@ +# Copyright (c) 2018 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. + +from . import core +from .framework import dygraph_only, in_dygraph_mode +from paddle import _C_ops, _legacy_C_ops + + +@dygraph_only +def _append_activation_in_dygraph(input, + act=None, + use_cudnn=None, + use_mkldnn=None): + """Append activation in dygraph mode. + + Args: + input: the input variable. + act: activation type + use_mkldnn: if use mkldnn + use_cudnn: if use cudnn + + Return the Variable after append activation + """ + if act is None: + return input + + attrs = () + if use_cudnn: + attrs = ('use_cudnn', use_cudnn) + if use_mkldnn: + attrs += ('use_mkldnn', use_mkldnn) + + act_op = getattr(_legacy_C_ops, act) + return act_op(input, *attrs) + + +@dygraph_only +def _append_bias_in_dygraph(input, bias=None, axis=1, use_mkldnn=False): + """Append bias operation in dygraph mode. + + Args: + input: the input variable. + bias: the bias to be appended + axis: the axis to perform operation + use_mkldnn: whether to use mkldnn + + Return the Variable after bias operation + """ + if bias is None: + return input + + return _legacy_C_ops.elementwise_add(input, bias, 'axis', axis, + 'use_mkldnn', use_mkldnn) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/entry_attr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/entry_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..375079570429dedb1d17297f30fb7b51109ef5bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/entry_attr.py @@ -0,0 +1,76 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +__all__ = ['ProbabilityEntry', 'CountFilterEntry'] + + +class EntryAttr(object): + """ + Examples: + .. code-block:: python + + import paddle.fluid as fluid + """ + + def __init__(self): + self._name = None + + def _to_attr(self): + """ + Returns the attributes of this parameter. + + Returns: + Parameter attributes(map): The attributes of this parameter. + """ + raise NotImplementedError("EntryAttr is base class") + + +class ProbabilityEntry(EntryAttr): + + def __init__(self, probability): + super(ProbabilityEntry, self).__init__() + + if not isinstance(probability, float): + raise ValueError("probability must be a float in (0,1)") + + if probability <= 0 or probability >= 1: + raise ValueError("probability must be a float in (0,1)") + + self._name = "probability_entry" + self._probability = probability + + def _to_attr(self): + return ":".join([self._name, str(self._probability)]) + + +class CountFilterEntry(EntryAttr): + + def __init__(self, count_filter): + super(CountFilterEntry, self).__init__() + + if not isinstance(count_filter, int): + raise ValueError( + "count_filter must be a valid integer greater than 0") + + if count_filter < 0: + raise ValueError( + "count_filter must be a valid integer greater or equal than 0") + + self._name = "count_filter_entry" + self._count_filter = count_filter + + def _to_attr(self): + return ":".join([self._name, str(self._count_filter)]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/evaluator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..510733d4c1c7c97def6303d0e666bf107af007ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/evaluator.py @@ -0,0 +1,435 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import warnings +import numpy as np + +from . import layers +from .framework import Program, Variable, program_guard +from . import unique_name +from .layer_helper import LayerHelper +from .initializer import Constant +from .layers import detection + +__all__ = [ + 'ChunkEvaluator', + 'EditDistance', + 'DetectionMAP', +] + + +def _clone_var_(block, var): + assert isinstance(var, Variable) + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=True) + + +class Evaluator(object): + """ + Warning: better to use the fluid.metrics.* things, more + flexible support via pure Python and Operator, and decoupled + with executor. Short doc are intended to urge new user + start from Metrics. + + Base Class for all evaluators. + + Args: + name(str): The name of evaluator. such as, "accuracy". Used for generate + temporary variable name. + main_program(Program, optional): The evaluator should be added to this + main_program. Default default_main_program() + startup_program(Program, optional):The parameter should be added to this + startup_program. Default default_startup_program() + + Attributes: + states(list): The list of state variables. states will be reset to zero + when `reset` is invoked. + metrics(list): The list of metrics variables. They will be calculate + every mini-batch + """ + + def __init__(self, name, **kwargs): + warnings.warn( + "The %s is deprecated, because maintain a modified program inside evaluator cause bug easily, please use fluid.metrics.%s instead." + % (self.__class__.__name__, self.__class__.__name__), Warning) + self.states = [] + self.metrics = [] + self.helper = LayerHelper(name, **kwargs) + + def reset(self, executor, reset_program=None): + """ + reset metric states at the begin of each pass/user specified batch + + Args: + executor(Executor|ParallelExecutor): a executor for executing the reset_program + reset_program(Program): a single Program for reset process + """ + if reset_program is None: + reset_program = Program() + + with program_guard(main_program=reset_program): + for var in self.states: + assert isinstance(var, Variable) + g_var = _clone_var_(reset_program.current_block(), var) + layers.fill_constant(shape=g_var.shape, + value=0.0, + dtype=g_var.dtype, + out=g_var) + + executor.run(reset_program) + + def eval(self, executor, eval_program=None): + """ + Evaluate the statistics merged by multiple mini-batches. + Args: + executor(Executor|ParallelExecutor): a executor for executing the eval_program + eval_program(Program): a single Program for eval process + """ + raise NotImplementedError() + + def _create_state(self, suffix, dtype, shape): + """ + Create state variable. + + Args: + suffix(str): the state suffix. + dtype(str|core.VarDesc.VarType): the state data type + shape(tuple|list): the shape of state + + Returns: State variable + + """ + state = self.helper.create_variable(name="_".join( + [unique_name.generate(self.helper.name), suffix]), + persistable=True, + dtype=dtype, + shape=shape) + self.states.append(state) + return state + + +class ChunkEvaluator(Evaluator): + """ + Warning: This would be deprecated in the future. Please use fluid.metrics.ChunkEvaluator + instead. + + Accumulate counter numbers output by chunk_eval from mini-batches and + compute the precision recall and F1-score using the accumulated counter + numbers. + For some basics of chunking, please refer to + 'Chunking with Support Vector Machines '. + + Args: + input (Variable): prediction output of the network. + label (Variable): label of the test data set. + chunk_scheme (str): can be IOB/IOE/IOBES and IO. See the chunk_eval op for details. + num_chunk_types (int): the number of chunk type. + excluded_chunk_types (list): A list including chunk type ids, indicating chunk types that are not counted. + + Returns: + tuple: tuple containing: precision, recall, f1_score + + Examples: + .. code-block:: python + + exe = fluid.executor(place) + evaluator = fluid.Evaluator.ChunkEvaluator(input, label) + for epoch in PASS_NUM: + evaluator.reset(exe) + for data in batches: + loss = exe.run(fetch_list=[cost]) + distance, instance_error = distance_evaluator.eval(exe) + """ + + def __init__( + self, + input, + label, + chunk_scheme, + num_chunk_types, + excluded_chunk_types=None, + ): + super(ChunkEvaluator, self).__init__("chunk_eval") + main_program = self.helper.main_program + if main_program.current_block().idx != 0: + raise ValueError("You can only invoke Evaluator in root block") + + self.num_infer_chunks = self._create_state(dtype='int64', + shape=[1], + suffix='num_infer_chunks') + self.num_label_chunks = self._create_state(dtype='int64', + shape=[1], + suffix='num_label_chunks') + self.num_correct_chunks = self._create_state( + dtype='int64', shape=[1], suffix='num_correct_chunks') + precision, recall, f1_score, num_infer_chunks, num_label_chunks, num_correct_chunks = layers.chunk_eval( + input=input, + label=label, + chunk_scheme=chunk_scheme, + num_chunk_types=num_chunk_types, + excluded_chunk_types=excluded_chunk_types, + ) + layers.sums(input=[self.num_infer_chunks, num_infer_chunks], + out=self.num_infer_chunks) + layers.sums(input=[self.num_label_chunks, num_label_chunks], + out=self.num_label_chunks) + layers.sums(input=[self.num_correct_chunks, num_correct_chunks], + out=self.num_correct_chunks) + + self.metrics.extend([precision, recall, f1_score]) + + def eval(self, executor, eval_program=None): + if eval_program is None: + eval_program = Program() + block = eval_program.current_block() + num_infer_chunks, num_label_chunks, num_correct_chunks = executor.run( + eval_program, + fetch_list=[_clone_var_(block, state) for state in self.states]) + num_infer_chunks = num_infer_chunks[0] + num_label_chunks = num_label_chunks[0] + num_correct_chunks = num_correct_chunks[0] + precision = float( + num_correct_chunks) / num_infer_chunks if num_infer_chunks else 0 + recall = float( + num_correct_chunks) / num_label_chunks if num_label_chunks else 0 + f1_score = float(2 * precision * recall) / ( + precision + recall) if num_correct_chunks else 0 + return np.array([precision], dtype='float32'), np.array( + [recall], dtype='float32'), np.array([f1_score], dtype='float32') + + +class EditDistance(Evaluator): + """ + Warning: This would be deprecated in the future. Please use fluid.metrics.EditDistance + instead. + Accumulate edit distance sum and sequence number from mini-batches and + compute the average edit_distance and instance error of all batches. + + Args: + input: the sequences predicted by network. + label: the target sequences which must have same sequence count + with input. + ignored_tokens(list of int): Tokens that should be removed before + calculating edit distance. + + Examples: + .. code-block:: python + + exe = fluid.executor(place) + distance_evaluator = fluid.Evaluator.EditDistance(input, label) + for epoch in PASS_NUM: + distance_evaluator.reset(exe) + for data in batches: + loss = exe.run(fetch_list=[cost]) + distance, instance_error = distance_evaluator.eval(exe) + + In the above example: + 'distance' is the average of the edit distance in a pass. + 'instance_error' is the instance error rate in a pass. + + """ + + def __init__(self, input, label, ignored_tokens=None, **kwargs): + super(EditDistance, self).__init__("edit_distance", **kwargs) + main_program = self.helper.main_program + if main_program.current_block().idx != 0: + raise ValueError("You can only invoke Evaluator in root block") + + self.total_distance = self._create_state(dtype='float32', + shape=[1], + suffix='total_distance') + self.seq_num = self._create_state(dtype='int64', + shape=[1], + suffix='seq_num') + self.instance_error = self._create_state(dtype='int64', + shape=[1], + suffix='instance_error') + distances, seq_num = layers.edit_distance(input=input, + label=label, + ignored_tokens=ignored_tokens) + + zero = layers.fill_constant(shape=[1], value=0.0, dtype='float32') + compare_result = layers.equal(distances, zero) + compare_result_int = layers.cast(x=compare_result, dtype='int64') + seq_right_count = layers.reduce_sum(compare_result_int) + instance_error_count = layers.elementwise_sub(x=seq_num, + y=seq_right_count) + total_distance = layers.reduce_sum(distances) + layers.sums(input=[self.total_distance, total_distance], + out=self.total_distance) + layers.sums(input=[self.seq_num, seq_num], out=self.seq_num) + layers.sums(input=[self.instance_error, instance_error_count], + out=self.instance_error) + self.metrics.append(total_distance) + self.metrics.append(instance_error_count) + + def eval(self, executor, eval_program=None): + if eval_program is None: + eval_program = Program() + block = eval_program.current_block() + with program_guard(main_program=eval_program): + total_distance = _clone_var_(block, self.total_distance) + seq_num = _clone_var_(block, self.seq_num) + instance_error = _clone_var_(block, self.instance_error) + seq_num = layers.cast(x=seq_num, dtype='float32') + instance_error = layers.cast(x=instance_error, dtype='float32') + avg_distance = layers.elementwise_div(x=total_distance, y=seq_num) + avg_instance_error = layers.elementwise_div(x=instance_error, + y=seq_num) + result = executor.run(eval_program, + fetch_list=[avg_distance, avg_instance_error]) + return np.array(result[0]), np.array(result[1]) + + +class DetectionMAP(Evaluator): + """ + Warning: This would be deprecated in the future. Please use fluid.metrics.DetectionMAP + instead. + Calculate the detection mean average precision (mAP). + + The general steps are as follows: + 1. calculate the true positive and false positive according to the input + of detection and labels. + 2. calculate mAP value, support two versions: '11 point' and 'integral'. + + Please get more information from the following articles: + https://sanchom.wordpress.com/tag/average-precision/ + https://arxiv.org/abs/1512.02325 + + Args: + input (Variable): The detection results, which is a LoDTensor with shape + [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax]. + gt_label (Variable): The ground truth label index, which is a LoDTensor + with shape [N, 1]. + gt_box (Variable): The ground truth bounding box (bbox), which is a + LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax]. + gt_difficult (Variable|None): Whether this ground truth is a difficult + bounding bbox, which can be a LoDTensor [N, 1] or not set. If None, + it means all the ground truth labels are not difficult bbox. + class_num (int): The class number. + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all categories will be + considered, 0 by default. + overlap_threshold (float): The threshold for deciding true/false + positive, 0.5 by default. + evaluate_difficult (bool): Whether to consider difficult ground truth + for evaluation, True by default. This argument does not work when + gt_difficult is None. + ap_version (string): The average precision calculation ways, it must be + 'integral' or '11point'. Please check + https://sanchom.wordpress.com/tag/average-precision/ for details. + - 11point: the 11-point interpolated average precision. + - integral: the natural integral of the precision-recall curve. + + Examples: + .. code-block:: python + + exe = fluid.executor(place) + map_evaluator = fluid.Evaluator.DetectionMAP(input, + gt_label, gt_box, gt_difficult) + cur_map, accum_map = map_evaluator.get_map_var() + fetch = [cost, cur_map, accum_map] + for epoch in PASS_NUM: + map_evaluator.reset(exe) + for data in batches: + loss, cur_map_v, accum_map_v = exe.run(fetch_list=fetch) + + In the above example: + + 'cur_map_v' is the mAP of current mini-batch. + 'accum_map_v' is the accumulative mAP of one pass. + """ + + def __init__(self, + input, + gt_label, + gt_box, + gt_difficult=None, + class_num=None, + background_label=0, + overlap_threshold=0.5, + evaluate_difficult=True, + ap_version='integral'): + super(DetectionMAP, self).__init__("map_eval") + + gt_label = layers.cast(x=gt_label, dtype=gt_box.dtype) + if gt_difficult: + gt_difficult = layers.cast(x=gt_difficult, dtype=gt_box.dtype) + label = layers.concat([gt_label, gt_difficult, gt_box], axis=1) + else: + label = layers.concat([gt_label, gt_box], axis=1) + + # calculate mean average precision (mAP) of current mini-batch + map = detection.detection_map(input, + label, + class_num, + background_label, + overlap_threshold=overlap_threshold, + evaluate_difficult=evaluate_difficult, + ap_version=ap_version) + + self._create_state(dtype='int32', shape=None, suffix='accum_pos_count') + self._create_state(dtype='float32', shape=None, suffix='accum_true_pos') + self._create_state(dtype='float32', + shape=None, + suffix='accum_false_pos') + + self.has_state = None + var = self.helper.create_variable(persistable=True, + dtype='int32', + shape=[1]) + self.helper.set_variable_initializer(var, + initializer=Constant(value=int(0))) + self.has_state = var + + # calculate accumulative mAP + accum_map = detection.detection_map( + input, + label, + class_num, + background_label, + overlap_threshold=overlap_threshold, + evaluate_difficult=evaluate_difficult, + has_state=self.has_state, + input_states=self.states, + out_states=self.states, + ap_version=ap_version) + + layers.fill_constant(shape=self.has_state.shape, + value=1, + dtype=self.has_state.dtype, + out=self.has_state) + + self.cur_map = map + self.accum_map = accum_map + + def get_map_var(self): + return self.cur_map, self.accum_map + + def reset(self, executor, reset_program=None): + if reset_program is None: + reset_program = Program() + with program_guard(main_program=reset_program): + var = _clone_var_(reset_program.current_block(), self.has_state) + layers.fill_constant(shape=var.shape, + value=0, + dtype=var.dtype, + out=var) + executor.run(reset_program) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/executor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..c77def7ebf1ce78b1e1fbe71322f4a0d9346cc82 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/executor.py @@ -0,0 +1,2648 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import logging +import os +import multiprocessing +import sys +import warnings +import numpy as np +from .wrapped_decorator import signature_safe_contextmanager +import six +from .data_feeder import convert_dtype +from .framework import Program, default_main_program, Variable, Operator +from .framework import convert_np_dtype_to_dtype_, _apply_pass + +from . import core +from . import unique_name +from . import compiler +from .. import compat as cpt +from .trainer_factory import TrainerFactory +from .trainer_factory import FetchHandlerMonitor +import copy +from . import framework +from .incubate.checkpoint import auto_checkpoint as acp +from .compiler import _prune_feed_ops + +from functools import lru_cache + +__all__ = ['Executor', 'global_scope', 'scope_guard'] + +g_scope = core.Scope() +InferNativeConfig = core.NativeConfig +InferAnalysisConfig = core.AnalysisConfig + + +def global_scope(): + """ + :api_attr: Static Graph + + Get the global/default scope instance. There are a lot of APIs use + :code:`global_scope` as its default value, e.g., :code:`Executor.run` + + Returns: + Scope: The global/default scope instance. + + Examples: + .. code-block:: python + + import paddle + import numpy + + paddle.static.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), paddle.CPUPlace()) + numpy.array(paddle.static.global_scope().find_var("data").get_tensor()) + """ + return g_scope + + +def _switch_scope(scope): + global g_scope + ex = g_scope + g_scope = scope + return ex + + +@signature_safe_contextmanager +def scope_guard(scope): + """ + + This function switches scope through python `with` statement. + Scope records the mapping between variable names and variables ( :ref:`api_guide_Variable` ), + similar to brackets in programming languages. + If this function is not invoked, all variables and variable names are recorded in the default global scope. + When users need to create variables with the same name, + they need to switch scopes through this function + if they do not want the mapping of variables with the same name to be overwritten. + After switching through the `with` statement, + all variables created in the `with` block will be assigned to a new scope. + + Parameters: + scope: The new scope. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import numpy + paddle.enable_static() + + new_scope = paddle.static.Scope() + with paddle.static.scope_guard(new_scope): + paddle.static.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), paddle.CPUPlace()) + numpy.array(new_scope.find_var("data").get_tensor()) + """ + + ex = _switch_scope(scope) + try: + yield + finally: + _switch_scope(ex) + + +def as_numpy(tensor, copy=False): + """ + Convert a Tensor to a numpy.ndarray, its only support Tensor without LoD information. + For higher dimensional sequence data, please use LoDTensor directly. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + new_scope = fluid.Scope() + with fluid.scope_guard(new_scope): + fluid.global_scope().var("data").get_tensor().set(numpy.ones((2, 2)), fluid.CPUPlace()) + tensor = new_scope.find_var("data").get_tensor() + fluid.executor.as_numpy(tensor) # or numpy.array(new_scope.find_var("data").get_tensor()) + + Args: + tensor(Variable): a instance of Tensor + copy(bool, optional): Whether to use deep copy. + + Returns: + numpy.ndarray + """ + if isinstance(tensor, core.LoDTensorArray): + return [as_numpy(t, copy) for t in tensor] + if isinstance(tensor, list): + return [as_numpy(t, copy) for t in tensor] + assert isinstance(tensor, core.LoDTensor) + lod = tensor.lod() + if len(lod) > 0: + raise RuntimeError("Some of your fetched tensors hold LoD information. \ + They can not be completely cast to Python ndarray. \ + Please set the parameter 'return_numpy' as 'False' to \ + return LoDTensor itself directly.") + if tensor._is_initialized(): + if copy: + return np.array(tensor) + else: + return np.asarray(tensor) + else: + return None + + +def dtype_is_compatible_with(first, second): + """ + Returns True if the first dtype can be compatible the second one. + Currently, we require the two dtype's have to be same. + + Args: + dtype (np.dtype|VarType|str): The type of data: float32, int64, etc. + + Returns: + True if the two types are same. + """ + if not isinstance(first, core.VarDesc.VarType): + first = convert_np_dtype_to_dtype_(first) + if not isinstance(second, core.VarDesc.VarType): + second = convert_np_dtype_to_dtype_(second) + return first == second + + +def dimension_is_compatible_with(first, second): + """ + Returns True if the two dimensions are compatible. + + A dimension is compatible with the other if: + 1. The length of the dimensions are same. + 2. Each non-negative number of the two dimensions are same. + 3. For negative number or 'None' in a dimension, it means unknown so it + is compatible with any number. + + Args: + first (list/tuple): integers representing shape. "None" or negative + number means unknown. + second (list/tuple): integers representing shape. "None" or negative + number means unknown. + + Returns: + True if the two dimensions are compatible. + """ + + dim_len = len(first) + if dim_len != len(second): + return False + + for i in range(dim_len): + if first[i] is None or first[i] < 0: + continue + if second[i] is None or second[i] < 0: + continue + if first[i] != second[i]: + return False + + return True + + +def check_feed_shape_type(var, feed, num_places=1): + """ + Returns True if the variable doesn't require feed check or it is compatible + with the shape and have same dtype as the fed value. + + A dimension is compatible with the other if: + 1. The length of the dimensions are same. + 2. Each non-negative number of the two dimensions are same. + 3. For negative number or 'None' in a dimension, it means unknown so it + is compatible with any number. + + Args: + var (Variable): the Variable object + feed (LoDTensor): the fed value, which must be a LoDTensor + num_places: an integer value indicating the number of places. + ParallelExecutor will divide data into devices (CPU/GPU) evenly. + Returns: + True if the shape and dtype of variable is compatible with the feed value + Raises: + ValueError: if the shape or dtype of the variable is not compatible with + the feed value + """ + if var.desc.need_check_feed(): + diff_shape = core.diff_tensor_shape(feed, var.desc, num_places) + if diff_shape is not None: + raise ValueError( + 'The fed Variable %r should have dimensions = %d, shape = ' + '%r, but received fed shape %r on each device' % + (var.name, len(var.shape), var.shape, diff_shape)) + if not dtype_is_compatible_with(feed._dtype(), var.dtype): + var_dtype_format = convert_dtype(var.dtype) if isinstance( + var.dtype, core.VarDesc.VarType) else var.dtype + feed_dtype_format = convert_dtype(feed._dtype()) if isinstance( + feed._dtype(), core.VarDesc.VarType) else feed._dtype() + raise ValueError( + 'The data type of fed Variable %r must be %r, but received %r' % + (var.name, var_dtype_format, feed_dtype_format)) + return True + + +def has_feed_operators(block, feed_targets, feed_holder_name): + """ Check whether the block already has feed operators. + + Return false if the block does not have any feed operators. + If some feed operators have been prepended to the block, check that + the info contained in these feed operators matches the feed_targets + and feed_holder_name. Raise exception when any mismatch is found. + Return true when the block has feed operators with matching info. + + Args: + block: a block instance (typically global block of a program) + feed_targets: a dictionary of {feed_target_name: feed_target_data} + feed_holder_name: the name of the variable that holds the data of + all feed targets. The type of this feed_holder variable is + FEED_MINIBATCH, which is essentially vector. + + Returns: + A boolean value that indicates whether a block has feed operators + that match the info contained in feed_targets and feed_holder_name. + """ + + feed_count = 0 + for op in block.ops: + if op.desc.type() == 'feed': + feed_count += 1 + assert op.desc.input('X')[0] == feed_holder_name + feed_target_name = op.desc.output('Out')[0] + if feed_target_name not in feed_targets: + raise Exception( + "'feed_targets' does not have {} variable".format( + feed_target_name)) + else: + break + if feed_count > 0 and feed_count != len(feed_targets): + raise Exception( + "Feed operators in program desc do not match 'feed_targets'") + return feed_count > 0 + + +def has_fetch_operators(block, + fetch_targets, + fetch_holder_name, + fetch_op='fetch'): + """ Check whether the block already has fetch operators. + + Return false if the block does not have any fetch operators. + If some fetch operators have been appended to the block, check that + the info contained in these fetch operators matches the fetch_targets + and fetch_holder_name. Raise exception when any mismatch is found. + Return true when the block has fetch operators with matching info. + + Args: + block: a block instance (typically global block of a program) + fetch_targets: a dictionary of {fetch_target_name: fetch_target_data} + fetch_holder_name: the name of the variable that holds the data of + all fetch targets. The type of this fetch_holder variable is + FETCH_LIST, which is essentially vector. + fetch_op: the operator name of fetch + + Return: + A boolean value that indicates whether a block has fetch operators + that match the info contained in fetch_targets and fetch_holder_name. + """ + + fetch_count = 0 + for op in block.ops: + if op.desc.type() == fetch_op: + fetch_count += 1 + assert op.desc.output('Out')[0] == fetch_holder_name + fetch_target_name = op.desc.input('X')[0] + if fetch_target_name not in [ + var.desc.name() for var in fetch_targets + ]: + raise Exception( + "'fetch_targets' does not have {} variable".format( + fetch_target_name)) + idx = op.desc.attr('col') + assert fetch_target_name == fetch_targets[idx].desc.name() + if fetch_count > 0 and fetch_count != len(fetch_targets): + raise Exception( + "Fetch operators in program desc do not match 'fetch_targets'") + return fetch_count > 0 + + +def _add_feed_fetch_ops(program, + feed, + fetch_list, + feed_var_name, + fetch_var_name, + use_fetch_v2=False): + tmp_program = program.clone() + + global_block = tmp_program.global_block() + + if feed_var_name in global_block.vars: + feed_var = global_block.var(feed_var_name) + else: + feed_var = global_block.create_var( + name=feed_var_name, + type=core.VarDesc.VarType.FEED_MINIBATCH, + persistable=True) + + if fetch_var_name in global_block.vars: + fetch_var = global_block.var(fetch_var_name) + else: + fetch_var = global_block.create_var( + name=fetch_var_name, + type=core.VarDesc.VarType.FETCH_LIST, + persistable=True) + + # prepend feed operators + if not has_feed_operators(global_block, feed, feed_var_name): + for i, name in enumerate(feed): + if global_block.has_var(name): + out = global_block.var(name) + global_block._prepend_op(type='feed', + inputs={'X': [feed_var]}, + outputs={'Out': [out]}, + attrs={'col': i}) + else: + warnings.warn( + "The variable %s is not found in program. It is not declared or is pruned." + % name) + + if use_fetch_v2: + fetch_op = 'fetch_v2' + else: + fetch_op = 'fetch' + + # append fetch_operators + if not has_fetch_operators(global_block, fetch_list, fetch_var_name, + fetch_op): + for i, var in enumerate(fetch_list): + assert isinstance(var, Variable) or isinstance( + var, six.string_types), ("Wrong type for fetch_list[%s]: %s" % + (i, type(var))) + global_block.append_op(type=fetch_op, + inputs={'X': [var]}, + outputs={'Out': [fetch_var]}, + attrs={'col': i}) + + return tmp_program + + +def _apply_inplace_addto_pass(program, enable_inplace, enable_addto, + skip_var_names): + use_cuda = True if core.is_compiled_with_cuda() else False + + attrs = {"use_cuda": use_cuda, "mem_opt_skip_vars": skip_var_names} + attr_types = {"use_cuda": "bool", "mem_opt_skip_vars": "list[str]"} + + empty_startup_program = Program() + if enable_inplace: + pass_name = "buffer_shared_inplace_pass" + _apply_pass(program, empty_startup_program, pass_name, attrs, + attr_types) + if enable_addto and use_cuda: + pass_name = "inplace_addto_op_pass" + _apply_pass(program, empty_startup_program, pass_name, attrs, + attr_types) + + +def _fetch_var(name, scope=None, return_numpy=True): + """ + Fetch the value of the variable with the given name from the + given scope. + + Args: + name(str): name of the variable. Typically, only persistable variables + can be found in the scope used for running the program. + scope(core.Scope|None): scope object. It should be the scope where + you pass to Executor.run() when running your program. + If None, global_scope() will be used. Default None. + return_numpy(bool): whether convert the tensor to numpy.ndarray. + Default True. + + Returns: + LodTensor|numpy.ndarray + """ + assert isinstance(name, six.string_types) + if scope is None: + scope = global_scope() + assert isinstance(scope, core._Scope) + + var = scope.find_var(_to_name_str(name)) + assert var is not None, ( + "Cannot find " + name + " in scope. Perhaps you need to make the" + " variable persistable by using var.persistable = True in your" + " program.") + tensor = var.get_tensor() + if return_numpy: + tensor = as_numpy(tensor, copy=True) + return tensor + + +def _to_name_str(var): + + def _to_str(var): + if isinstance(var, Variable): + return var.desc.name() + elif isinstance(var, str): + return var + elif isinstance(var, six.string_types): + return str(var) + elif isinstance(var, Operator): + return str(id(var)) + else: + raise TypeError(str(var) + " should be Variable, Operator or str") + + # NOTEz(zhiqiu): The item in fetch_list may be tuple returned by Optimizer.minimize(), + # see comments in _split_optimize_ops_in_fetch_list for more details. + if isinstance(var, tuple): + var = var[0] + if isinstance(var, list): + s = [_to_str(item) for item in var] + return ','.join(s) + else: + return _to_str(var) + + +def _is_enable_standalone_executor(): + return framework._enable_standalone_executor_ is None or framework._enable_standalone_executor_ in [ + 1, '1', True, 'True', 'true' + ] + + +def _is_dy2st_enable_standalone_executor(): + return framework._dy2st_enable_standalone_executor_ in [ + 1, '1', True, 'True', 'true' + ] + + +def _prepare_fleet_executor(): + from ..distributed.fleet.proto import fleet_executor_desc_pb2 + trainer_endpoints_str = os.getenv("PADDLE_TRAINER_ENDPOINTS", "") + trainer_endpoints = trainer_endpoints_str.split(',') + fleet_exe_desc = fleet_executor_desc_pb2.FleetExecutorDesc() + cur_rank = int(os.getenv("PADDLE_TRAINER_ID", 0)) + fleet_exe_desc.cur_rank = cur_rank + nrank = len(trainer_endpoints) + for rank, endpoint in enumerate(trainer_endpoints): + rank_info = fleet_executor_desc_pb2.RankInfo() + rank_info.rank = rank + rank_info.ip_port = endpoint + fleet_exe_desc.cluster_info.append(rank_info) + fleet_exe = core.FleetExecutor(fleet_exe_desc.SerializeToString()) + return fleet_exe + + +def _get_strong_program_cache_key_for_new_exe(program, feed, fetch_list): + return program.desc.cached_hash_str() + _get_program_cache_key( + feed, fetch_list) + + +def _get_strong_program_cache_key(program, feed, fetch_list): + # TODO(zhiqiu): use hash_str to generate cache key as above + def _get_varname_from_block(block): + block_str = [] + for var_name in list(block.vars.keys()): + block_str.append(var_name) + return "\n".join(block_str) + + inner_program = program._program if isinstance( + program, compiler.CompiledProgram) else program + return _get_varname_from_block(inner_program.blocks[0]) + str( + id(program)) + _get_program_cache_key(feed, fetch_list) + + +def _get_program_cache_key(feed, fetch_list): + feed_var_names = [] + if isinstance(feed, dict): + feed_var_names = list(feed.keys()) + elif isinstance(feed, list) or isinstance(feed, tuple): + for i, each in enumerate(feed): + feed_var_names += list(each.keys()) + fetch_var_names = list(map(_to_name_str, fetch_list)) + return str(feed_var_names + fetch_var_names) + + +def _as_lodtensor(data, place, dtype=None): + """ + Convert numpy.ndarray to Tensor, its only support Tensor without LoD information. + For higher dimensional sequence data, please use LoDTensor directly. + + Examples: + >>> import paddle.fluid as fluid + >>> place = fluid.CPUPlace() + >>> exe = fluid.executor(place) + >>> data = np.array(size=(100, 200, 300)) + >>> np_outs = map(lambda x: fluid.executor._as_lodtensor(x, place), data) + >>> ... + + Args: + data(numpy.ndarray|list|tuple|scalar): a instance of array, scalar, list or tuple + data(core.Place): the place of created tensor + dtype(core.VarDesc.VarType|str): the expected data type of created tensor + + Returns: + LoDTensor + """ + #NOTE(zhiqiu): convert python builtin, like float, int, and list, to numpy ndarray + if not isinstance(data, np.ndarray): + assert dtype is not None, 'The dtype should be given when feed data is not np.ndarray' + dtype = convert_dtype(dtype) if isinstance( + dtype, core.VarDesc.VarType) else dtype + if np.isscalar(data): + data = np.array([data]).astype(dtype) + elif isinstance(data, (list, tuple)): + data = np.array(data) + if data.dtype == np.object_: + raise TypeError( + "\n\tFaild to convert input data to a regular ndarray :\n\t* Usually " + "this means the input data contains nested lists with different lengths. " + "Please consider using 'fluid.create_lod_tensor' to convert it to a LoD-Tensor." + ) + data = data.astype(dtype) + else: + raise TypeError( + "Convert data of type {} to Tensor is not supported".format( + type(data))) + + # convert numpy.ndarray to tensor + tensor = core.LoDTensor() + tensor.set(data, place) + return tensor + + +class FetchHandler(object): + + def __init__(self, var_dict=None, period_secs=60): + assert var_dict != None + self.var_dict = var_dict + self.period_secs = period_secs + + def handler(self, res_dict): + for key in res_dict: + if type(res_dict[key]) is np.ndarray: + sys.stdout.write("{}[0]: {} ".format(key, res_dict[key][0])) + sys.stdout.write("\n") + + @staticmethod + def help(): + print(""" +class FetchHandlerExample(FetchHandler): + def handler(self, res_dict): + print(res_dict["auc"]) + print("auc: {}, {}".format(res_dict["auc"], time.ctime())) + +auc = Variable() +var_dict = {"auc": auc} +handler = FetchHandlerExample(var_dict=var_dict) +""") + + +class _StandaloneExecutor(object): + + def __init__(self, place, main_program, scope): + self._place = core.Place() + self._place.set_place(place) + self._main_program = main_program + self._scope = scope + self._new_exe = self._create_new_executor() + + def run(self, scope, feed_names, fetch_list, return_numpy=True): + """ + Args: + feed_names(list): This parameter represents the input names of the model. + fetch_list(list): This parameter represents the Tensors that need to be returned + after the model runs. The default is None. + return_numpy(bool): This parameter indicates whether convert the fetched Tensors + (the Tensor specified in the fetch list) to numpy.ndarray. if it is False, + the type of the return value is a list of :code:`LoDTensor`. The default is True. + """ + fetch_list = self._check_fetch(fetch_list) + + tensors = self._new_exe.run(scope, feed_names, + fetch_list)._move_to_list() + if return_numpy: + return as_numpy(tensors, copy=True) + else: + return tensors + + def _create_new_executor(self): + new_exe = core.StandaloneExecutor(self._place, self._main_program.desc) + + return new_exe + + def _update_feed(self, feed): + """ + Update the feed dict, remove the feed item which is pruned in program. + + Notes: This is a very low level API. Users should not use this API + directly. + + Args: + feed(list|dict): feed dict or list. + + Returns: + feed:(list|dict) updated feed. + """ + if feed is None: + feed = {} + elif isinstance(feed, (list, tuple)): + assert len(feed) == 1, "Not compiled with data parallel" + feed = feed[0] + + if not isinstance(feed, dict): + raise TypeError( + "feed requires dict as its Parameter. But you passed in %s" % + (type(feed))) + + global_block = self._main_program.global_block() + for feed_name in list(feed.keys()): + if not global_block.has_var(feed_name): + feed.pop(feed_name) + warnings.warn( + "The variable %s is not found in program. It is not declared or is pruned." + % feed_name) + + return feed + + def _check_fetch(self, fetch_list): + if fetch_list is None: + fetch_list = [] + + res = [] + for fetch_var in fetch_list: + if isinstance(fetch_var, Variable): + fetch_var = fetch_var.name + elif not isinstance(fetch_var, str): + raise TypeError( + "Required fetch_var shall be str|Variable, but received {}". + format(type(fetch_var).__name__)) + + res.append(fetch_var) + return res + + +class _ExecutorCache(object): + + class _CachedData(object): + + def __init__(self, program, feed, fetch_list, feed_var_name, + fetch_var_name, place, scope): + self.program = program + self.feed = feed + self.fetch_list = fetch_list + self.feed_var_name = feed_var_name + self.fetch_var_name = fetch_var_name + self.place = place + self.scope = scope + + # NOTE(Ruibiao): Not all changeable item is considered for key at present, + # ONLY: program, feed, and fetch_list + if isinstance(self.program, compiler.CompiledProgram): + if not self.program._program: + # The program holds no _program, maybe it is constructed by graph. + # Convert graph to program in order to generate key. + self.program._program = framework.IrGraph( + self.program._graph).to_program() + self.key = hash( + _get_strong_program_cache_key_for_new_exe( + self.program._program, feed, fetch_list)) + else: + self.key = hash( + _get_strong_program_cache_key_for_new_exe( + self.program, feed, fetch_list)) + + def __eq__(self, other): + return isinstance( + other, _ExecutorCache._CachedData) and self.key == other.key + + def __hash__(self): + return self.key + + def __init__(self): + # NOTE(Ruibiao): Wrap the lru_cache in constructor so that the cache is local to + # the _ExecutorCache instance, otherwise a global cache may not be released after + # the Executor instance deleted + self._get_cached_program_and_executor = lru_cache(maxsize=8)( + self._get_program_and_executor) + + def clear(self): + self._get_cached_program_and_executor.cache_clear() + + def get_program_and_executor(self, program, feed, fetch_list, feed_var_name, + fetch_var_name, place, scope): + return self._get_cached_program_and_executor( + self._CachedData(program, feed, fetch_list, feed_var_name, + fetch_var_name, place, scope)) + + def _get_program_and_executor(self, cached_data): + program = cached_data.program + inner_program = program._program if isinstance( + program, compiler.CompiledProgram) else program + feed = cached_data.feed + fetch_list = cached_data.fetch_list + feed_var_name = cached_data.feed_var_name + fetch_var_name = cached_data.fetch_var_name + place = cached_data.place + scope = cached_data.scope + + # To apply IR pass, compile the Program to IrGraph and convert it back to Program + if isinstance(program, compiler.CompiledProgram) or isinstance( + program._graph, compiler.CompiledProgram): + compiled_program = program if isinstance( + program, compiler.CompiledProgram) else program._graph + build_strategy = compiled_program._build_strategy + # print(f"Program before convert:\n {inner_program}", flush=True) + compiled_program._compile(scope, place) + ir_graph = framework.IrGraph(compiled_program._graph) + converted_program = ir_graph.to_program() + + if hasattr(inner_program, 'lr_sheduler'): + converted_program.lr_sheduler = inner_program.lr_sheduler + + inner_program = converted_program + # print(f"Program after convert:\n {inner_program}", flush=True) + else: + build_strategy = None + from paddle.incubate.autograd import prim_enabled, prim2orig + if prim_enabled() and program == default_main_program(): + prim2orig() + + inner_program = program + + program = _add_feed_fetch_ops(program=inner_program, + feed=feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name, + use_fetch_v2=True) + + if os.environ.get('FLAGS_CONVERT_GRAPH_TO_PROGRAM', None) in [ + 1, '1', True, 'True', 'true' + ] and not program._is_start_up_program_: + if program.num_blocks > 1: + # If there are multiple blocks in the program, subblock will not be executed with the new executor in temporary + logging.warning("There are more than 1 block in program.") + elif program.num_blocks == 1: + logging.warning("There are 1 block in program.") + else: + logging.warning("There are no block in program.") + + # standalone executor will apply buffer_shared_inplace_pass and + # inplace_addto_op_pass to program according to build_strategy + enable_inplace = True if build_strategy is None or build_strategy.enable_inplace else False + enable_addto = True if build_strategy is not None and build_strategy.enable_addto else False + if enable_inplace or enable_addto: + # inplace should skip feed and fetch var + skip_var_names = eval(_get_program_cache_key(feed, fetch_list)) + _apply_inplace_addto_pass(program, enable_inplace, enable_addto, + skip_var_names) + + new_program = program.clone() + new_exe = _StandaloneExecutor(place, new_program, scope) + return new_program, new_exe + + +class Executor(object): + """ + :api_attr: Static Graph + + An Executor in Python, supports single/multiple-GPU running, + and single/multiple-CPU running. + + Args: + place(paddle.CPUPlace()|paddle.CUDAPlace(n)|str|None): This parameter represents + which device the executor runs on. When this parameter is None, PaddlePaddle + will set the default device according to its installation version. If Paddle + is CPU version, the default device would be set to `CPUPlace()` . If Paddle is + GPU version, the default device would be set to `CUDAPlace(0)` . Default is None. + If ``place`` is string, it can be ``cpu``, and ``gpu:x``, where ``x`` + is the index of the GPUs. Note: users only pass one Place or None to initialize + Executor when using multiple-cards. Other APIs will override the cards. See + `document for multiple-cards `_ + + Returns: + Executor + + Examples: + .. code-block:: python + + import paddle + import numpy + import os + + # Executor is only used in static graph mode + paddle.enable_static() + + # Set place explicitly. + # use_cuda = True + # place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() + # exe = paddle.static.Executor(place) + + # If you don't set place, PaddlePaddle sets the default device. + exe = paddle.static.Executor() + + train_program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(train_program, startup_program): + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + # Run the startup program once and only once. + # Not need to optimize/compile the startup program. + exe.run(startup_program) + + # Run the main program directly without compile. + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = exe.run(train_program, feed={"X": x}, fetch_list=[loss.name]) + + # Or, compiled the program and run. See `CompiledProgram` + # for more details. + # NOTE: If you use CPU to run the program or Paddle is + # CPU version, you need to specify the CPU_NUM, otherwise, + # PaddlePaddle will use all the number of the logic core as + # the CPU_NUM, in that case, the batch size of the input + # should be greater than CPU_NUM, if not, the process will be + # failed by an exception. + + # Set place explicitly. + # if not use_cuda: + # os.environ['CPU_NUM'] = str(2) + + # If you don't set place and PaddlePaddle is CPU version + os.environ['CPU_NUM'] = str(2) + + compiled_prog = paddle.static.CompiledProgram( + train_program).with_data_parallel(loss_name=loss.name) + loss_data, = exe.run(compiled_prog, feed={"X": x}, fetch_list=[loss.name]) + + """ + + def __init__(self, place=None): + if place is None: + expected_place = framework._current_expected_place() + self.place = expected_place + else: + self.place = framework._get_paddle_place(place) + self.program_caches = dict() + self.ctx_caches = dict() + self.trainer_caches = dict() + self.scope_caches = dict() + self.var_caches = dict() + self.pruned_program_caches = dict() + p = core.Place() + p.set_place(self.place) + self._default_executor = core.Executor(p) + self._closed = False + self.pruned_program_scope_caches = dict() + self._prepare_to_run_called = False + + self._auto_checkpoint_name = unique_name.generate( + "__auto_checkpoint_executor__") + + # NOTE: Whether to use experimental executor `StandaloneExecutor`. + self._enable_interpreter_core = _is_enable_standalone_executor() + self._executor_cache = _ExecutorCache() + + self._fleet_executor = None + # TODO(liyurui): This option will be removed and always true when the functionality + # of fleet executor with standalone executor is ready. + self._fleet_executor_with_standalone = False + + def __del__(self): + # NOTE(Ruibiao): The manually call of clear is required. Because in Python, executor_cache + # may not immediately destructed after Executor instance deleted (so does not the _StandaloneExecutor), + # that brings errors to mkl-dnn unit tests (see ClearMKLDNNCache in interpretercore.cc for why). + self._executor_cache.clear() + + def _get_scope_cache(self, program_cache_key): + return self.scope_caches.get(program_cache_key, None) + + def _get_ctx_cache(self, program_cache_key): + return self.ctx_caches.get(program_cache_key, None) + + def _get_trainer_cache(self, program_cache_key): + return self.trainer_caches.get(program_cache_key, None) + + def _get_program_cache(self, program_cache_key): + return self.program_caches.get(program_cache_key, None) + + def _add_program_cache(self, program_cache_key, program): + self.program_caches[program_cache_key] = program + + def _get_pruned_program_cache(self, program_cache_key): + return self.pruned_program_caches.get(program_cache_key, None) + + def _add_pruned_program_cache(self, program_cache_key, program): + self.pruned_program_caches[program_cache_key] = program + + def _get_pruned_program_scope_cache(self, program_cache_key): + return self.pruned_program_scope_caches.get(program_cache_key, None) + + def _add_pruned_program_scope_cache(self, program_cache_key, program): + self.pruned_program_scope_caches[program_cache_key] = program + + def _add_ctx_cache(self, ctx_cache_key, ctx): + self.ctx_caches[ctx_cache_key] = ctx + + def _add_trainer_cache(self, trainer_cache_key, ctx): + self.trainer_caches[trainer_cache_key] = ctx + + def _add_scope_cache(self, scope_cache_key, scope): + self.scope_caches[scope_cache_key] = scope + + # just for testing, will be removed later + @lru_cache() + def _log_force_set_program_cache(self, use_program_cache): + logging.warning( + f"use_program_cache is force set to {use_program_cache} by FLAGS_FORCE_USE_PROGRAM_CACHE" + ) + + def _feed_data(self, program, feed, feed_var_name, scope): + # feed var to framework + global_block = program.global_block() + for op in global_block.ops: + if op.desc.type() == 'feed': + feed_target_name = op.desc.output('Out')[0] + cur_feed = feed[feed_target_name] + var = global_block.var(feed_target_name) + if var.dtype != core.VarDesc.VarType.STRINGS: + if not isinstance(cur_feed, core.LoDTensor): + cur_feed = _as_lodtensor(cur_feed, self.place, + var.dtype) + check_feed_shape_type(var, cur_feed) + idx = op.desc.attr('col') + core.set_feed_variable(scope, cur_feed, feed_var_name, idx) + else: + break + + def _fetch_data(self, fetch_list, fetch_var_name, scope): + outs = [ + core.get_fetch_variable(scope, fetch_var_name, i) + for i in six.moves.range(len(fetch_list)) + ] + return outs + + @classmethod + def _split_optimize_ops_in_fetch_list(cls, fetch_list): + """ + Split optimize_ops from fetch_list, which provided to specify program prunning. + Args: + fetch_list(list): The original fetch_list. + Possible types of fetch_list are: + fetch_list = ['loss'] + fetch_list = [[sgd, sgd], 'loss'] + fetch_list = [([sgd, sgd], [(param, grad)]), 'loss'] + + Returns: + optimize_ops(list): The optimize operators splited from fetch_list. + fetch_list(list): The updated fetch_list which does not contain optimize operators. + """ + _optimize_ops = [] + _fetch_list = [] + + def _get_targets(_optimize_ops, _fetch_list, item): + if isinstance(item, Operator): + if item._is_optimize_op(): + _optimize_ops.append(item) + else: + raise TypeError( + "The operator in fetch_list is not an optimize_op") + elif isinstance(item, Variable) or isinstance( + item, str) or isinstance(item, six.string_types): + _fetch_list.append(item) + else: + raise TypeError( + "The item in fetch_list should be str, variable or optimize_op, but received %s.", + type(item)) + + for index, item in enumerate(fetch_list): + # NOTE(zhiqiu): to support (optimizer_ops, param_and_grads) and optimizer_ops in fetch_list + # we should handle tuple and list in fetch_list. + # TODO(zhiqiu): find a better way to handle that. + if isinstance(item, list): + for i in item: + _get_targets(_optimize_ops, _fetch_list, i) + elif isinstance(item, tuple): + if not isinstance(item[0], (list, tuple)): + raise TypeError( + "Requires fetch_list[{}][0] shall be one of (list, tuple) when type(fetch_list[{}]) is `tuple`, but received fetch_list[{}][0]'s type is `{}`." + .format(index, index, index, + type(item[0]).__name__)) + for i in item[0]: + _get_targets(_optimize_ops, _fetch_list, i) + else: + _get_targets(_optimize_ops, _fetch_list, item) + + return _fetch_list, _optimize_ops + + @classmethod + def _prune_program(cls, + program, + feed=None, + fetch_list=None, + optimize_ops=None): + """ + Prune operators and variables which are not needed to generate + :code:`fetch_list` and optimize operators. + Prune operators and variables which are needed + to generate variables to be feeded. + + Notes: This is a very low level API. Users should not use this API + directly. + + Args: + program(Program): the origin program + feed(list|dict): feed dict or list. + fetch_list(list|Variable): A list of variables need to be fetched + optimize_ops(list[Operator]): A list of optimizer operators + + Returns: + Program: A new, pruned program. + """ + compiled = isinstance(program, compiler.CompiledProgram) + if compiled: + if program._program: + origin_program = program._program + else: + warnings.warn( + "The program holds no _program, maybe it is constructed by graph, which can't be pruned yet." + ) + return + else: + origin_program = program + + feed_names = [] + if isinstance(feed, dict): + feed_names = list(feed.keys()) + elif isinstance(feed, list) or isinstance(feed, tuple): + for i, each in enumerate(feed): + feed_names += list(each.keys()) + + # if optimize_ops is [], all optimize ops in the program is used. + if not optimize_ops: + for block in origin_program.blocks: + for op in block.ops: + if op._is_optimize_op(): + optimize_ops.append(op) + + targets = fetch_list + optimize_ops + pruned_program = origin_program._prune_with_input(feed_names, targets) + + if compiled: + # for compiled program, update the underlying program, re-generate graph, + # and reset the flag so it can be compiled again. + program._program = pruned_program + program._graph = core.Graph(pruned_program.desc) + program._compiled = False + else: + program = pruned_program + + return program + + @classmethod + def _update_feed(cls, program, feed): + """ + Update the feed dict, remove the feed item which is pruned in program. + + Notes: This is a very low level API. Users should not use this API + directly. + + Args: + program(Program): the pruned program. + feed(list|dict): feed dict or list. + + Returns: + feed:(list|dict) updated feed. + """ + compiled = isinstance(program, compiler.CompiledProgram) + if compiled: + if program._program: + global_block = program._program.global_block() + else: + warnings.warn( + "The program holds no _program, maybe it is constructed by graph." + ) + return feed + else: + global_block = program.global_block() + + if isinstance(feed, dict): + for feed_name in list(feed.keys()): + if not global_block.has_var(feed_name): + feed.pop(feed_name) + warnings.warn( + "The variable %s is not found in program. It is not declared or is pruned." + % feed_name) + + elif isinstance(feed, list) or isinstance(feed, tuple): + for i, each in enumerate(feed): + for feed_name in list(each.keys()): + if not global_block.has_var(feed_name): + each.pop(feed_name) + warnings.warn( + "The variable %s is not found in program. It is not declared or is pruned." + % feed_name) + return feed + + ''' + TODO(typhoonzero): Define "no longer use" meaning? Can user create + a new Executor for the same program and run? + TODO(panyx0718): Why ParallelExecutor doesn't have close? + ''' + + def close(self): + """ + Close the executor. This interface is used for distributed training (PServers mode). + This executor can not be used after calling the interface, because + this interface releases resources associated with the current Trainer. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + cpu = paddle.CPUPlace() + exe = paddle.static.Executor(cpu) + # execute training or testing + exe.close() + """ + if not self._closed: + self._closed = True + for k, trainer_instance in self.trainer_caches.items(): + self._default_executor.release_trainer(trainer_instance) + del trainer_instance + self._default_executor.close() + + def _run_parallel(self, program, scope, feed, fetch_list, fetch_var_name, + return_numpy, return_merged): + from paddle.optimizer.lr import LRScheduler + exe = program._executor + # TODO(zhenghuihuang): quantization uses Graph in CompiledProgram + # instead of program. We will add support for checking Vars in Graph + need_check_feed = program._program is not None + if need_check_feed: + global_block = program._program.global_block() + if isinstance(feed, dict): + feed_tensor_dict = dict() + for feed_name in feed: + feed_tensor = feed[feed_name] + var = global_block.var(feed_name) if need_check_feed else None + if not isinstance(feed_tensor, core.LoDTensor): + # always set to CPU place, since the tensor need to be split + # it is fast in CPU + feed_tensor = _as_lodtensor(feed[feed_name], + core.CPUPlace(), + var.dtype if var else None) + if need_check_feed: + check_feed_shape_type(var, feed_tensor, exe.device_count()) + feed_tensor_dict[feed_name] = feed_tensor + exe.feed_and_split_tensor_into_local_scopes(feed_tensor_dict) + + elif isinstance(feed, list) or isinstance(feed, tuple): + res = list() + for i, each in enumerate(feed): + if not isinstance(each, dict): + raise TypeError( + "Each element of feed list should be a dict") + res_dict = dict() + for feed_name in each: + tensor = each[feed_name] + var = global_block.var( + feed_name) if need_check_feed else None + if not isinstance(tensor, core.LoDTensor): + tensor = _as_lodtensor(each[feed_name], + program._places[i], + var.dtype if var else None) + if need_check_feed: + check_feed_shape_type(var, tensor) + res_dict[feed_name] = tensor + res.append(res_dict) + + exe.feed_tensors_into_local_scopes(res) + + if hasattr(program._program, 'lr_sheduler'): + lr_sheduler = program._program.lr_sheduler + assert isinstance(lr_sheduler, LRScheduler), "must be LRScheduler" + lr_value = lr_sheduler() + lr_var = program._program.global_block().vars[lr_sheduler._var_name] + lr_tensor = _as_lodtensor(lr_value, core.CPUPlace(), lr_var.dtype) + if core.is_cuda_graph_capturing(): + warnings.warn( + "Caution!!! When capturing CUDA Graph, the learning rate scheduler would not " + "take any effect! Please set the learning rate manually before each batch!" + ) + else: + exe.feed_and_split_tensor_into_local_scopes( + {lr_sheduler._var_name: lr_tensor}) + + fetch_var_names = list(map(_to_name_str, fetch_list)) + tensors = exe.run(fetch_var_names, return_merged)._move_to_list() + return as_numpy(tensors) if return_numpy else tensors + + def run(self, + program=None, + feed=None, + fetch_list=None, + feed_var_name='feed', + fetch_var_name='fetch', + scope=None, + return_numpy=True, + use_program_cache=False, + return_merged=True, + use_prune=False): + """ + Run the specified :code:`Program` or :code:`CompiledProgram`. It should be noted that the executor + will execute all the operators in :code:`Program` or :code:`CompiledProgram` without pruning some + operators of the :code:`Program` or :code:`CompiledProgram` according to fetch_list. And you could + specify the scope to store the :code:`Tensor` during the executor running if the scope + is not set, the executor will use the global scope, i.e. :code:`paddle.static.global_scope()`. + + Args: + program(Program|CompiledProgram): This parameter represents the :code:`Program` or + :code:`CompiledProgram` to be executed. If this parameter is not provided, that + parameter is None, the program will be set to :code:`paddle.static.default_main_program()`. + The default is None. + feed(list|dict): This parameter represents the input Tensors of the model. + If it is single card training, the feed is dict type, and if it is multi-card + training, the parameter feed can be dict or list of Tensors. If the + parameter type is dict, the data in the feed will be split and sent to + multiple devices (CPU/GPU), that is to say, the input data will be evenly + sent to different devices, so you should make sure the number of samples of + the current mini-batch must be greater than the number of places; + if the parameter type is list, those data are copied directly to each device, + so the length of this list should be equal to the number of places. + The default is None. + fetch_list(list): This parameter represents the Tensors that need to be returned + after the model runs. The default is None. + feed_var_name(str): This parameter represents the name of the input Tensor of + the feed operator. The default is "feed". + fetch_var_name(str): This parameter represents the name of the output Tensor of + the fetch operator. The default is "fetch". + scope(Scope): the scope used to run this program, you can switch + it to different scope. default is :code:`paddle.static.global_scope()` + return_numpy(bool): This parameter indicates whether convert the fetched Tensors + (the Tensor specified in the fetch list) to numpy.ndarray. if it is False, + the type of the return value is a list of :code:`LoDTensor`. The default is True. + use_program_cache(bool): This parameter indicates whether the input :code:`Program` is cached. + If the parameter is True, the model may run faster in the following cases: + the input program is :code:`paddle.static.Program`, and the parameters(program, feed Tensor name + and fetch_list Tensor) of this interface remains unchanged during running. + The default is False. + return_merged(bool): This parameter indicates whether fetched Tensors (the Tensors + specified in the fetch list) should be merged according to the execution device dimension. + If :code:`return_merged` is False, the type of the return value is a two-dimensional list + of :code:`Tensor` / :code:`LoDTensorArray` ( :code:`return_numpy` is False) or a two-dimensional + list of :code:`numpy.ndarray` ( :code:`return_numpy` is True). If :code:`return_merged` is True, + the type of the return value is an one-dimensional list of :code:`Tensor` / :code:`LoDTensorArray` + ( :code:`return_numpy` is False) or an one-dimensional list of :code:`numpy.ndarray` + ( :code:`return_numpy` is True). Please see Examples 2 for more details. If the lengths of fetched + results are variant, please set :code:`return_merged` as False, which denotes that the fetched + results will not be merged. The default is True, but it is just for the compatibility, and may + use False as default value in the future version. + use_prune(bool): This parameter indicates whether the input :code:`Program` will be pruned. + If the parameter is True, the program will be pruned accroding to the given feed and fetch_list, + which means the operators and variables in program that generate :code:`feed` and are not + needed to generate :code:`fetch_list` will be pruned. The default is False, which means the + program will not pruned and all the operators and variables will be executed during running. + Note that if the tuple returned from :code:`Optimizer.minimize()` is passed to :code:`fetch_list`, + :code:`use_prune` will be overrided to True, and the program will be pruned. + + Returns: + + List: The fetched result list. + + NOTES: + 1. If it is multi-card running and the feed parameter is dict type, the input data + will be evenly sent to different cards. For example, using two GPUs to run the model, + the input sample number is 3, that is, [0, 1, 2], the sample number on GPU0 is 1, + that is, [0], and the sample number on GPU1 is 2, that is, [1, 2]. + If the number of samples is less than the number of devices, the program will + throw an exception, so when running the model, you should make sure that the + number of samples of the last batch of the data set should be greater than the + number of CPU cores or GPU cards, if it is less than, it is recommended that + the batch be discarded. + 2. If the number of CPU cores or GPU cards available is greater than 1, the fetch + results are spliced together in dimension 0 for the same Tensor values + (Tensors in fetch_list) on different devices. + + Examples: + .. code-block:: python + :name: code-example-1 + + import paddle + import numpy + + # First create the Executor. + paddle.enable_static() + place = paddle.CPUPlace() # paddle.CUDAPlace(0) + exe = paddle.static.Executor(place) + + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + adam = paddle.optimizer.Adam() + adam.minimize(loss) + i = paddle.zeros(shape=[1], dtype='int64') + array = paddle.fluid.layers.array_write(x=loss, i=i) + + # Run the startup program once and only once. + exe.run(paddle.static.default_startup_program()) + + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_val, array_val = exe.run(feed={'X': x}, + fetch_list=[loss.name, array.name]) + print(array_val) + # [array([0.02153828], dtype=float32)] + + .. code-block:: python + :name: code-example-2 + + # required: gpu + import paddle + import numpy as np + + # First create the Executor. + paddle.enable_static() + place = paddle.CUDAPlace(0) + exe = paddle.static.Executor(place) + + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + class_dim = 2 + prediction = paddle.static.nn.fc(data, class_dim) + loss = paddle.mean(prediction) + adam = paddle.optimizer.Adam() + adam.minimize(loss) + + # Run the startup program once and only once. + exe.run(paddle.static.default_startup_program()) + build_strategy = paddle.static.BuildStrategy() + binary = paddle.static.CompiledProgram( + paddle.static.default_main_program()).with_data_parallel( + loss_name=loss.name, build_strategy=build_strategy) + batch_size = 6 + x = np.random.random(size=(batch_size, 1)).astype('float32') + + # Set return_merged as False to fetch unmerged results: + unmerged_prediction, = exe.run(binary, + feed={'X': x}, + fetch_list=[prediction.name], + return_merged=False) + # If the user uses two GPU cards to run this python code, the printed result will be + # (2, 3, class_dim). The first dimension value of the printed result is the number of used + # GPU cards, and the second dimension value is the quotient of batch_size and the + # number of used GPU cards. + print("The unmerged prediction shape: {}".format( + np.array(unmerged_prediction).shape)) + print(unmerged_prediction) + + # Set return_merged as True to fetch merged results: + merged_prediction, = exe.run(binary, + feed={'X': x}, + fetch_list=[prediction.name], + return_merged=True) + # If the user uses two GPU cards to run this python code, the printed result will be + # (6, class_dim). The first dimension value of the printed result is the batch_size. + print("The merged prediction shape: {}".format( + np.array(merged_prediction).shape)) + print(merged_prediction) + + # Out: + # The unmerged prediction shape: (2, 3, 2) + # [array([[-0.37620035, -0.19752218], + # [-0.3561043 , -0.18697084], + # [-0.24129935, -0.12669306]], dtype=float32), array([[-0.24489994, -0.12858354], + # [-0.49041364, -0.25748932], + # [-0.44331917, -0.23276259]], dtype=float32)] + # The merged prediction shape: (6, 2) + # [[-0.37789783 -0.19921964] + # [-0.3577645 -0.18863106] + # [-0.24274671 -0.12814042] + # [-0.24635398 -0.13003758] + # [-0.49232286 -0.25939852] + # [-0.44514108 -0.2345845 ]] + + """ + # Temporary FLAGS, just for testing the performance of program cache + force_use_program_cache = os.environ.get( + 'FLAGS_FORCE_USE_PROGRAM_CACHE', None) + if force_use_program_cache is not None: + use_program_cache = force_use_program_cache in [ + 1, '1', True, 'True', 'true' + ] + self._log_force_set_program_cache(use_program_cache) + + try: + res = self._run_impl(program=program, + feed=feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name, + scope=scope, + return_numpy=return_numpy, + use_program_cache=use_program_cache, + use_prune=use_prune, + return_merged=return_merged) + core.update_autotune_status() + return res + except Exception as e: + six.reraise(*sys.exc_info()) + + def _run_impl(self, program, feed, fetch_list, feed_var_name, + fetch_var_name, scope, return_numpy, use_program_cache, + return_merged, use_prune): + if self._closed: + raise RuntimeError("Attempted to use a closed Executor") + + use_default_main_program = program is None + if program is None: + program = default_main_program() + + fetch_list = self._check_fetch_list(fetch_list) + + if isinstance(program, Program) and program._pipeline_opt: + if "fleet_opt" in program._pipeline_opt: + # Move prepare here for port conflict with nccl in startup program + if self._fleet_executor is None: + self._fleet_executor = _prepare_fleet_executor() + return self._run_using_fleet_executor( + program=program, + feed=feed, + fetch_list=fetch_list, + with_standalone_executor=self. + _fleet_executor_with_standalone) + if "startup_program" in program._pipeline_opt: + program = program._pipeline_opt["startup_program"] + else: + return self._run_pipeline(program, + fetch_list=fetch_list, + use_program_cache=use_program_cache) + + if isinstance(program, Program) and program._heter_pipeline_opt: + #print("program._heter_pipeline_opt: {}".format( + # program._heter_pipeline_opt)) + ## change default executor + heter_place = program._heter_pipeline_opt["heter_place"] + heter_place = framework._get_paddle_place(heter_place) + p = core.Place() + p.set_place(heter_place) + self._default_executor = core.Executor(p) + # TODO(zhangminxu): support heterps pipeline training using exe.run + if "startup_program" in program._heter_pipeline_opt: + #print("get startup_program from _pipeline_opt") + program = program._heter_pipeline_opt["startup_program"] + + if isinstance(program, Program) and \ + len(program.global_block().ops) == 0: + if use_default_main_program: + error_info = "Now you are using default_main_program, "\ + "but there are no operators in the program to be executed. "\ + "Please ensure you create model correctly or you can pass "\ + "the Program or the CompiledProgram manually." + else: + error_info = "There are no operators in the program to be executed. "\ + "If you pass Program manually, please use fluid.program_guard "\ + "to ensure the current Program is being used." + warnings.warn(error_info) + + if scope is None: + scope = global_scope() + + # use_prune can be overrided by putting optimize_ops in fetch_list + _origin_fetch_list = fetch_list + _origin_program = program + fetch_list, optimize_ops = self._split_optimize_ops_in_fetch_list( + fetch_list) + if optimize_ops: + use_prune = True + if use_prune: + cache_key = _get_strong_program_cache_key(program, feed, + _origin_fetch_list) + cached_pruned_program = self._get_pruned_program_cache(cache_key) + if cached_pruned_program is None: + if isinstance(program, compiler.CompiledProgram): + program_scope_cache = self._get_pruned_program_scope_cache( + str(id(_origin_program))) + # copy the original program, so it can be cached. + program = copy.copy(program) + # share the local scopes for same original CompiledProgram. + program._share_vars_from = program_scope_cache + if self._get_pruned_program_scope_cache( + str(id(_origin_program))) is None: + self._add_pruned_program_scope_cache( + str(id(_origin_program)), program) + pruned_program = self._prune_program(program, feed, fetch_list, + optimize_ops) + self._add_pruned_program_cache(cache_key, pruned_program) + else: + pruned_program = cached_pruned_program + + feed = self._update_feed(pruned_program, feed) + program = pruned_program + + def _can_use_interpreter_core(program, place): + if core.is_compiled_with_mlu() or isinstance( + place, core.CustomPlace): + return False + + use_standalone_executor_for_compiled_program = os.environ.get( + 'FLAGS_CONVERT_GRAPH_TO_PROGRAM', + None) in [1, '1', True, 'True', 'true'] + + # Only support fleet when 'FLAGS_CONVERT_GRAPH_TO_PROGRAM' is set to true + from paddle.distributed.fleet import fleet + if fleet._role_maker is not None and not use_standalone_executor_for_compiled_program: + warnings.warn("Standalone executor is not used for fleet", + UserWarning) + return False + + compiled = isinstance(program, + compiler.CompiledProgram) or isinstance( + program._graph, compiler.CompiledProgram) + if compiled: + compiled_program = program if isinstance( + program, compiler.CompiledProgram) else program._graph + # Unsupported case 1: data parallel + if compiled_program._is_data_parallel and len( + compiled_program._get_places( + place, compiled_program._places)) != 1: + warnings.warn( + "Standalone executor is not used for data parallel", + UserWarning) + return False + + # Unsupported case 2: parallel graph + if core.globals()['FLAGS_enable_parallel_graph'] in [ + 1, '1', True, 'True', 'true' + ]: + warnings.warn( + "Standalone executor is not used for parallel graph", + UserWarning) + return False + + # Unsupported case 3: inference + if compiled_program._is_inference: + warnings.warn( + "Standalone executor is not used for inference", + UserWarning) + return False + + # Unsupported case 4: CUDA Graph + if compiled_program._build_strategy is not None and compiled_program._build_strategy.allow_cuda_graph_capture: + warnings.warn( + "Standalone executor is not used for CUDA Graph", + UserWarning) + return False + + # Unsupported case 5: async mode + if compiled_program._build_strategy is not None and compiled_program._build_strategy.async_mode: + warnings.warn( + "Standalone executor is not used for async mode", + UserWarning) + return False + + return use_standalone_executor_for_compiled_program + else: + assert isinstance(program, Program) + return True + + # NOTE: This is an experimental feature. If `export FLAGS_USE_STANDALONE_EXECUTOR=1 `, + # use StandaloneExecutor to run the program. + if return_merged and self._enable_interpreter_core and _can_use_interpreter_core( + program, self.place): + + if feed is None: + feed = {} + elif isinstance(feed, (list, tuple)): + assert len(feed) == 1, "Not compiled with data parallel" + feed = feed[0] + if not isinstance(feed, dict): + raise TypeError( + "feed requires dict as its Parameter. But you passed in %s" + % (type(feed))) + feed = self._update_feed(program, feed) + + program, new_exe = self._executor_cache.get_program_and_executor( + program, feed, fetch_list, feed_var_name, fetch_var_name, + self.place, scope) + + self._feed_data(program, feed, feed_var_name, scope) + if hasattr(program, 'lr_sheduler'): + from paddle.optimizer.lr import LRScheduler + assert isinstance(program.lr_sheduler, + LRScheduler), "must be LRScheduler" + lr_sheduler = program.lr_sheduler + lr_value = lr_sheduler() + lr_var = program.global_block().vars[lr_sheduler._var_name] + data = np.array([lr_value]).astype(convert_dtype(lr_var.dtype)) + tensor = core.get_variable_tensor(scope, lr_sheduler._var_name) + # NOTE(dev): `tensor.set(data, self.place)` always call TensorCopySync that is a blocking behavior. So we use `_copy_from` to replace it. + cpu_tensor = _as_lodtensor(data, core.CPUPlace()) + # for ipu, tensor is allocated on cpu + if core.is_compiled_with_ipu(): + tensor._copy_from(cpu_tensor, tensor._place()) + else: + tensor._copy_from(cpu_tensor, self.place) + + return new_exe.run(scope, list(feed.keys()), fetch_list, + return_numpy) + + compiled = isinstance(program, compiler.CompiledProgram) + + # Check if fluid.data() variable no feed data + if use_prune: + if compiled: + global_block = program._program.global_block() + else: + global_block = program.global_block() + for varname in global_block.vars: + vardesc = global_block.desc.find_var(cpt.to_bytes(varname)) + varobj = global_block.vars[varname] + + # Can not check var build by fluid.layers.data(), bucause fluid.layers.data() had not set need_check_feed + if vardesc.persistable() == False and \ + vardesc.type() == core.VarDesc.VarType.LOD_TENSOR and \ + vardesc.need_check_feed() == True and \ + varobj.stop_gradient == True and \ + varobj.is_data == True and \ + varobj.belong_to_optimizer == False and \ + varname not in feed: + raise ValueError('Need feed data for variable %s' % varname) + + acp._auto_checkpoint(self, program) + + # For backward compatibility, run directly. + if not compiled: + # In distributed training, the compiled program is saved in Program._graph + has_compiled_graph = isinstance(program._graph, + compiler.CompiledProgram) + + if has_compiled_graph: + program._graph._compile(scope, self.place) + # _graph in program does not support inference since the _graph is optimized + # through optimizer.minimize function and should not be used as inference graph + # assert not program._graph._is_inference + return self._run_parallel(program._graph, + scope=scope, + feed=feed, + fetch_list=fetch_list, + fetch_var_name=fetch_var_name, + return_numpy=return_numpy, + return_merged=return_merged) + + return self._run_program(program, + feed=feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name, + scope=scope, + return_numpy=return_numpy, + use_program_cache=use_program_cache) + + program._compile(scope, self.place) + if program._is_inference: + return self._run_inference(program._executor, feed) + else: + return self._run_parallel(program, + scope=scope, + feed=feed, + fetch_list=fetch_list, + fetch_var_name=fetch_var_name, + return_numpy=return_numpy, + return_merged=return_merged) + + def _run_program(self, program, feed, fetch_list, feed_var_name, + fetch_var_name, scope, return_numpy, use_program_cache): + from paddle.optimizer.lr import LRScheduler + if feed is None: + feed = {} + elif isinstance(feed, (list, tuple)): + assert len(feed) == 1, "Not compiled with data parallel" + feed = feed[0] + + if not isinstance(feed, dict): + raise TypeError( + "feed requires dict as its Parameter. But you passed in %s" % + (type(feed))) + + assert program is not None, "The program should not be Empty" + if not isinstance(program, Program): + raise TypeError( + "Executor requires Program as its Parameter. But you passed in %s" + % (type(program))) + + if not isinstance(fetch_var_name, str): + raise TypeError( + "The name of fetch variable requires string as its Parameter. But you passed in %s" + % (type(fetch_var_name))) + + if use_program_cache: + cache_key = _get_strong_program_cache_key(program, feed, fetch_list) + cached_program = self._get_program_cache(cache_key) + cached_ctx = self._get_ctx_cache(cache_key) + cached_scope = self._get_scope_cache(cache_key) + if cached_program is None: + cached_program = _add_feed_fetch_ops( + program=program, + feed=feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name) + self._add_program_cache(cache_key, cached_program) + fetch_list_str = list(map(_to_name_str, fetch_list)) + cached_ctx = self._default_executor.prepare( + cached_program.desc, 0, fetch_list_str, False) + # currently, we cache program, vars, sub_scope here + # we suppose that in a life cycle of training, a user + # will not create many programs. So, here the basic + # rule of caching is to cache all unseen (program, var, scope) + # when a user use use_program_cache. + cached_scope = scope.new_scope() + self._default_executor.create_variables(cached_program.desc, + cached_scope, 0) + self._add_ctx_cache(cache_key, cached_ctx) + self._add_scope_cache(cache_key, cached_scope) + program = cached_program + ctx = cached_ctx + scope = cached_scope + else: + program = _add_feed_fetch_ops(program=program, + feed=feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name) + + self._feed_data(program, feed, feed_var_name, scope) + if hasattr(program, 'lr_sheduler'): + assert isinstance(program.lr_sheduler, + LRScheduler), "must be LRScheduler" + lr_sheduler = program.lr_sheduler + lr_value = lr_sheduler() + lr_var = program.global_block().vars[lr_sheduler._var_name] + data = np.array([lr_value]).astype(convert_dtype(lr_var.dtype)) + tensor = core.get_variable_tensor(scope, lr_sheduler._var_name) + tensor.set(data, self.place) + + if not use_program_cache: + self._default_executor.run(program.desc, scope, 0, True, True, + [fetch_var_name]) + else: + self._default_executor.run_prepared_ctx(ctx, scope, False, False, + False) + arr = scope.find_var(fetch_var_name).get_fetch_list() + tensors = arr._move_to_list() + if return_numpy: + return as_numpy(tensors) + else: + return tensors + + def _run_inference(self, exe, feed): + return exe.run(feed) + + def _check_fetch_list(self, fetch_list): + is_fetch_var = lambda var: isinstance(var, + (Variable, str, six.string_types)) + is_tuple_list = lambda var: isinstance(var, (tuple, list)) + + if fetch_list is None: return [] + if is_fetch_var(fetch_list): return [fetch_list] + + assert is_tuple_list(fetch_list), \ + "Currently , The fetch_list type only should be list or tuple, \n"\ + "but the input type is {}. For more information please refer to \n"\ + "the executor.run(...).".format(type(fetch_list)) + + res = [] + for i, var in enumerate(fetch_list): + if is_fetch_var(var): + res.append(var) + # such as [x, 'mean_out', loss] + elif is_tuple_list(var): + if all(is_fetch_var(v) for v in var): + res.extend(list(var)) + else: + res.append(var) + else: + raise TypeError( + "Require fetch_list[{}] 's type shall be one of (Variable, str), but received {}." + .format(i, + type(var).__name__)) + + return res + + def _dump_debug_info(self, program=None, trainer=None): + with open(str(id(program)) + "_train_desc.prototxt", "w") as fout: + fout.write(str(trainer)) + if program._fleet_opt and "fleet_desc" in program._fleet_opt: + with open("fleet_desc.prototxt", "w") as fout: + fout.write(str(program._fleet_opt["fleet_desc"])) + + def _adjust_pipeline_resource(self, pipeline_opt, dataset, pipeline_num): + filelist_length = len(dataset.dataset.get_filelist()) + if filelist_length < pipeline_num: + pipeline_num = filelist_length + print( + "Pipeline training: setting the pipeline num to %d is enough because there are only %d files" + % (filelist_length, filelist_length)) + if filelist_length < pipeline_num * pipeline_opt["concurrency_list"][0]: + print( + "Pipeline training: setting the 1st element in concurrency_list to %d is enough because there are only %d files" + % (filelist_length // pipeline_num, filelist_length)) + pipeline_opt["concurrency_list"][ + 0] = filelist_length // pipeline_num + dataset.set_thread(pipeline_opt["concurrency_list"][0] * pipeline_num) + return pipeline_num + + def _prepare_trainer(self, + program=None, + dataset=None, + scope=None, + thread=0, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100): + is_heter = 0 + use_ps_gpu = 0 + if not program._fleet_opt is None: + if program._fleet_opt.get("worker_class", "") == "HeterCpuWorker": + is_heter = 1 + if program._fleet_opt.get("trainer", "") == "HeterXpuTrainer": + is_heter = 1 + if program._fleet_opt.get("use_ps_gpu", False): + use_ps_gpu = True + if scope is None: + scope = global_scope() + if fetch_list is None: + fetch_list = [] + if fetch_info is None: + fetch_info = [] + assert len(fetch_list) == len(fetch_info) + compiled = isinstance(program, compiler.CompiledProgram) + if is_heter: + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fu = FleetUtil() + ret = fu.split_program_by_device(program) + if not compiled: + # TODO: Need a better way to distinguish and specify different execution mode + if program._pipeline_opt: + trainer = TrainerFactory()._create_trainer( + program._pipeline_opt) + elif program._heter_pipeline_opt: + trainer = TrainerFactory()._create_trainer( + program._heter_pipeline_opt) + else: + trainer = TrainerFactory()._create_trainer(program._fleet_opt) + trainer._set_thread_barrier(program._is_distributed) + trainer._set_program(program) + if is_heter: + trainer._set_heter_info(ret) + else: + if program._pipeline_opt: + trainer = TrainerFactory()._create_trainer( + program.program._pipeline_opt) + elif program._heter_pipeline_opt: + trainer = TrainerFactory()._create_trainer( + program.program._heter_pipeline_opt) + else: + trainer = TrainerFactory()._create_trainer( + program.program._fleet_opt) + trainer._set_program(program.program) + + if thread <= 0: + if use_ps_gpu: + trainer._set_thread(len(program._fleet_opt["worker_places"])) + elif dataset.thread_num <= 0: + raise RuntimeError( + "You should set thread num first, either in Dataset" + "or in Executor.train_from_dataset") + else: + trainer._set_thread(dataset.thread_num) + else: + trainer._set_thread(thread) + + trainer._set_debug(debug) + trainer._set_fetch_var_and_info(fetch_list, fetch_info, print_period) + return scope, trainer + + def _run_from_dataset(self, + program=None, + dataset=None, + scope=None, + thread=0, + is_infer=False, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + if program._pipeline_opt is not None: + import paddle + if dataset is not None: + raise RuntimeError("dataset should be None for pipeline mode") + # The following fake dataset is created to call + # the _prepare_trainer api, and it is meaningless. + data_vars = [] + for var in program.global_block().vars.values(): + if var.is_data: + data_vars.append(var) + if core.is_compiled_with_npu(): + dataset = paddle.fluid.DatasetFactory().create_dataset( + 'InMemoryDataset') + else: + dataset = paddle.fluid.DatasetFactory().create_dataset( + 'FileInstantDataset') + dataset.set_batch_size(1) + dataset.set_thread(1) + dataset.set_filelist(['None']) + dataset.set_use_var(data_vars) + elif program._heter_pipeline_opt is not None: + stage_id = program._heter_pipeline_opt["pipeline_stage"] + #print("test_fl_stage_id: {}".format(stage_id)) + heter_place = program._heter_pipeline_opt["heter_place"] + if stage_id != 0: + if "is_fl_mode" not in program._heter_pipeline_opt: + import paddle + if dataset is not None: + raise RuntimeError( + "dataset should be None for heter pipeline mode") + # The following fake dataset is created to call + # the _prepare_trainer api, and it is meaningless. + data_vars = [] + for var in program.global_block().vars.values(): + if var.is_data: + data_vars.append(var) + dataset = paddle.fluid.DatasetFactory().create_dataset( + 'InMemoryDataset') + dataset.set_batch_size(1) + dataset.set_thread(1) + dataset.set_filelist(['None']) + dataset.set_use_var(data_vars) + else: + if dataset is None: + raise RuntimeError( + "dataset is need and should be initialized") + ## change default executor + heter_place = framework._get_paddle_place(heter_place) + p = core.Place() + p.set_place(heter_place) + self._default_executor = core.Executor(p) + else: + if dataset is None: + raise RuntimeError("dataset is need and should be initialized") + + dataset._prepare_to_run() + real_fetch_list = [] + if program._pipeline_opt: + real_program = program._pipeline_opt["section_program"] + for fetch_var in fetch_list: + if isinstance(fetch_var, Variable): + fetch_var_name = fetch_var.name + else: + fetch_var_name = fetch_var + if fetch_var_name in real_program.global_block().vars: + real_fetch_list.append(fetch_var) + + program._pipeline_opt["section_program"] = _add_feed_fetch_ops( + program=program._pipeline_opt["section_program"], + feed=[], + fetch_list=real_fetch_list, + feed_var_name='feed', + fetch_var_name='fetch') + main_block = program._pipeline_opt["section_program"].block(0) + for op in main_block.ops: + # set the op_role of fetch op to Optimize to avoid + # erase the fetched vars by gc for pipeline + if op.type == 'fetch': + op._set_attr( + 'op_role', + core.op_proto_and_checker_maker.OpRole.Optimize) + fetch_list = None + scope, trainer = self._prepare_trainer(program=program, + dataset=dataset, + scope=scope, + thread=thread, + debug=debug, + fetch_list=fetch_list, + fetch_info=fetch_info, + print_period=print_period) + + trainer._set_infer(is_infer) + trainer._gen_trainer_desc() + + if program._pipeline_opt is None: + if program._heter_pipeline_opt is None: + self._dump_debug_info(program=program, trainer=trainer) + # warning if dataset not set psgpu in psgpu mode + if dataset.use_ps_gpu is False and trainer.proto_desc.use_ps_gpu: + logging.warning("dataset should call set_use_ps_gpu in PsGpu mode") + + dataset._dynamic_adjust_before_train(trainer.proto_desc.thread_num) + + if program._heter_pipeline_opt is None: + trainer_instance = self._default_executor.init_for_dataset( # -->InitForDataset + program.desc, trainer._desc(), scope, dataset.dataset) + else: + # cache trainer instance for heterps pipeline training + if fetch_list == None: + fetch_list = [] + cache_key = _get_strong_program_cache_key(program, None, fetch_list) + trainer_instance = self._get_trainer_cache(cache_key) + if trainer_instance is None: + trainer_instance = self._default_executor.init_for_dataset( + program.desc, trainer._desc(), scope, dataset.dataset) + #print("test_fl_ps - trainer_desc: {}\n".format(trainer)) + self._add_trainer_cache(cache_key, trainer_instance) + else: + trainer_instance.ResetDataset(dataset.dataset) + + if fetch_handler is not None: + scope0 = trainer_instance.get_worker_scope(0) + fetch_monitor = FetchHandlerMonitor(scope0, fetch_handler) + fetch_monitor.start() + self._default_executor.run_from_dataset(trainer_instance) + fetch_monitor.stop() + if program._heter_pipeline_opt is None: + self._default_executor.release_trainer(trainer_instance) + else: + self._default_executor.run_from_dataset(trainer_instance) + if program._heter_pipeline_opt is None: + self._default_executor.release_trainer(trainer_instance) + + dataset._dynamic_adjust_after_train() + dataset._finish_to_run() + if real_fetch_list: + arr = scope.find_var('fetch').get_fetch_list() + tensors = arr._move_to_list() + return as_numpy(tensors) + + return None + + def _prepare_pipeline_ctx(self, + program=None, + dataset=None, + scope=None, + thread=0, + is_infer=False, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None, + use_program_cache=False): + assert program._pipeline_opt is not None + assert dataset is None, "dataset should be None for pipeline mode" + + cache_key = _get_strong_program_cache_key(program, None, fetch_list) + ctx = self._get_ctx_cache(cache_key) + if use_program_cache and ctx is not None: + return ctx + + import paddle + + # The following fake dataset is created to call + # the _prepare_trainer api, and it is meaningless. + def _get_dataset(): + data_vars = [] + for var in program.global_block().vars.values(): + if var.is_data: + data_vars.append(var) + if core.is_compiled_with_npu(): + dataset = paddle.fluid.DatasetFactory().create_dataset( + 'InMemoryDataset') + else: + dataset = paddle.fluid.DatasetFactory().create_dataset( + 'FileInstantDataset') + dataset.set_batch_size(1) + dataset.set_thread(1) + dataset.set_filelist(['None']) + dataset.set_use_var(data_vars) + dataset._prepare_to_run() + return dataset + + dataset = _get_dataset() + + def _get_real_program_fetch_list(): + real_program = program._pipeline_opt["section_program"] + real_fetch_list = [] + for fetch_var in fetch_list: + if isinstance(fetch_var, Variable): + fetch_var_name = fetch_var.name + else: + fetch_var_name = fetch_var + if fetch_var_name in real_program.global_block().vars: + real_fetch_list.append(fetch_var) + + real_program = _add_feed_fetch_ops(program=real_program, + feed=[], + fetch_list=real_fetch_list, + feed_var_name='feed', + fetch_var_name='fetch') + main_block = real_program.block(0) + for op in main_block.ops: + # set the op_role of fetch op to Optimize to avoid + # erase the fetched vars by gc for pipeline + if op.type == 'fetch': + op._set_attr( + 'op_role', + core.op_proto_and_checker_maker.OpRole.Optimize) + return real_program, real_fetch_list + + real_program, real_fetch_list = _get_real_program_fetch_list() + + program._pipeline_opt["section_program"] = real_program + fetch_list = None + + scope, trainer = self._prepare_trainer(program=program, + dataset=dataset, + scope=scope, + thread=thread, + debug=debug, + fetch_list=fetch_list, + fetch_info=fetch_info, + print_period=print_period) + + trainer._set_infer(is_infer) + trainer._gen_trainer_desc() + + # NOTE: only for debug, very slow + # self._dump_debug_info(program=program, trainer=trainer) + + # warning if dataset not set psgpu in psgpu mode + if dataset.use_ps_gpu is False and trainer.proto_desc.use_ps_gpu: + logging.warning("dataset should call set_use_ps_gpu in PsGpu mode") + dataset._dynamic_adjust_before_train(trainer.proto_desc.thread_num) + + trainer_desc = trainer._desc() # slow, cache + trainer_instance = self._default_executor.init_for_dataset( + program.desc, trainer_desc, scope, dataset.dataset) + + ctx = [scope, real_fetch_list, trainer_instance] + if use_program_cache: self._add_ctx_cache(cache_key, ctx) + + return ctx + + def _prepare_fleet_executor_carrier(self, + carrier_id="", + program=None, + scope=None, + fleet_opt=None, + with_standalone_executor=False): + num_micro_batches = fleet_opt[ + "num_micro_batches"] if "num_micro_batches" in fleet_opt else 1 + cur_rank = int(os.getenv("PADDLE_TRAINER_ID", 0)) + trainer_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS", "").split(',') + nrank = len(trainer_endpoints) + + assert 'scheduler' in fleet_opt or 'tasks' in fleet_opt, \ + "Fleet executor need configuration for scheduler, you can choose from 1F1B or Origin. " \ + "Or you can provide a list of task nodes to init fleet executor directly." + if 'tasks' in fleet_opt: + assert 'task_id_to_rank' in fleet_opt, "If you provide tasks to init fleet executor," \ + " task_id_to_rank should also be provided." + print('fleet executor will use user defined task nodes') + tasks = [task.task_node() for task in fleet_opt['tasks']] + task_id_to_rank = fleet_opt['task_id_to_rank'] + else: + scheduler = fleet_opt['scheduler'] + if scheduler == '1F1B': + from paddle.distributed.fleet.fleet_executor_utils import run1f1b + if "dist_strategy" not in fleet_opt or \ + "pp_degree" not in fleet_opt["dist_strategy"] or \ + fleet_opt["dist_strategy"]["pp_degree"] == 1: + warnings.warn("Using 1F1B scheduler with pp_degree == 1.") + tasks, task_id_to_rank = run1f1b( + program, cur_rank, fleet_opt.get('num_micro_batches', 1), + fleet_opt.get('dist_strategy', {}), nrank, + with_standalone_executor) + elif scheduler == 'Origin': + from paddle.distributed.fleet.fleet_executor_utils import origin + if "dist_strategy" in fleet_opt and \ + "pp_degree" in fleet_opt["dist_strategy"]: + assert fleet_opt["dist_strategy"]["pp_degree"] == 1, \ + "For pipeline mode, the scheduler should be 1F1B instead of Origin." + if "num_micro_batches" in fleet_opt: + assert fleet_opt["num_micro_batches"] == 1, \ + "For origin scheduler mode, the num micro batches should be 1." + tasks, task_id_to_rank = origin(program, cur_rank) + else: + raise "Fleet_executor only supports 1F1B and Origin scheduler, " \ + "but received " + str(scheduler) + "." + # NOTE: have to hold these vars, otherwise will be destructed + fleet_opt['tasks'] = tasks + fleet_opt['task_id_to_rank'] = task_id_to_rank + place = core.Place() + place.set_place(self.place) + # NOTE: the last argument is used to force create some vars in root scope, + # won't be used during train. + self._fleet_executor.init(carrier_id, program.desc, scope, place, + num_micro_batches, tasks, task_id_to_rank, []) + + def _run_using_fleet_executor(self, + program=None, + feed=None, + feed_var_name="feed", + fetch_var_name="fetch", + fetch_list=None, + with_standalone_executor=False): + cache_key = _get_strong_program_cache_key(program, feed, fetch_list) + cached_program = self._get_program_cache(cache_key) + cached_scope = self._get_scope_cache(cache_key) + if cached_scope is None: + cached_scope = global_scope() + self._add_scope_cache(cache_key, cached_scope) + if cached_program is None: + assert program._pipeline_opt, "program should have _pipeline_opt to start carrier" + real_feed = [] if feed is None else feed + real_program = program + if "section_program" in program._pipeline_opt: + real_program = program._pipeline_opt["section_program"] + cached_program = _add_feed_fetch_ops(program=real_program, + feed=real_feed, + fetch_list=fetch_list, + feed_var_name=feed_var_name, + fetch_var_name=fetch_var_name) + main_block = cached_program.block(0) + for op in main_block.ops: + # set the op_role of fetch op to Optimize to avoid + # erase the fetched vars by gc for pipeline + if op.type == 'fetch': + op._set_attr( + 'op_role', + core.op_proto_and_checker_maker.OpRole.Optimize) + self._add_program_cache(cache_key, cached_program) + fleet_opt = program._pipeline_opt["fleet_opt"] + if 'tasks' in fleet_opt: + # Insert feed/fetch op for cloned program in each task node, + # these ops has already been inserted into the origin program. + # To avoid every task nodes all have feed/fetch ops, + # only insert feed ops into the first task node, + # then insert fetch ops into the last task node. + + # Insert feed ops + feed_task = fleet_opt['tasks'][0] + print("Inserting feed ops for task", feed_task.task_id()) + feed_program = feed_task.get_program() + feed_program = self._add_feed_ops(program=feed_program, + feed=real_feed, + feed_var_name=feed_var_name) + feed_task.set_program(feed_program) + + # Insert fetch ops + fetch_task = fleet_opt['tasks'][-1] + print("Inserting fetch ops for task", fetch_task.task_id()) + fetch_program = fetch_task.get_program() + fetch_program = self._add_fetch_ops( + program=fetch_program, + fetch_list=fetch_list, + fetch_var_name=fetch_var_name) + main_block = fetch_program.block(0) + for op in main_block.ops: + # set the op_role of fetch op to Optimize to avoid + # erase the fetched vars by gc for pipeline + if op.type == 'fetch': + op._set_attr( + 'op_role', + core.op_proto_and_checker_maker.OpRole.Optimize) + fetch_task.set_program(fetch_program) + + self._prepare_fleet_executor_carrier( + cache_key, + program=cached_program, + scope=cached_scope, + fleet_opt=fleet_opt, + with_standalone_executor=with_standalone_executor) + + if feed: + # NOTE: don't have to traverse programs in task nodes, + # since they all sub program of cached program and + # cached program is also added feed fetch var + self._feed_data(cached_program, feed, feed_var_name, cached_scope) + + from paddle.optimizer.lr import LRScheduler + if hasattr(program, 'lr_sheduler'): + lr_sheduler = program.lr_sheduler + assert isinstance(lr_sheduler, LRScheduler), "must be LRScheduler" + lr_value = lr_sheduler() + lr_var = program.global_block().vars[lr_sheduler._var_name] + data = np.array([lr_value]).astype(convert_dtype(lr_var.dtype)) + tensor = core.get_variable_tensor(cached_scope, + lr_sheduler._var_name) + tensor.set(data, self.place) + + self._fleet_executor.run(cache_key) + + if fetch_list: + arr = cached_scope.find_var(fetch_var_name).get_fetch_list() + tensors = arr._move_to_list() + return as_numpy(tensors) + return None + + def _add_feed_ops(self, program, feed, feed_var_name): + tmp_program = program.clone() + + global_block = tmp_program.global_block() + + if feed_var_name in global_block.vars: + feed_var = global_block.var(feed_var_name) + else: + feed_var = global_block.create_var( + name=feed_var_name, + type=core.VarDesc.VarType.FEED_MINIBATCH, + persistable=True) + + # prepend feed operators + if not has_feed_operators(global_block, feed, feed_var_name): + for i, name in enumerate(feed): + if global_block.has_var(name): + out = global_block.var(name) + global_block._prepend_op(type='feed', + inputs={'X': [feed_var]}, + outputs={'Out': [out]}, + attrs={'col': i}) + else: + warnings.warn( + "The variable %s is not found in program. It is not declared or is pruned." + % name) + + return tmp_program + + @classmethod + def _add_fetch_ops(cls, + program, + fetch_list, + fetch_var_name, + use_fetch_v2=False): + tmp_program = program.clone() + + global_block = tmp_program.global_block() + + if fetch_var_name in global_block.vars: + fetch_var = global_block.var(fetch_var_name) + else: + fetch_var = global_block.create_var( + name=fetch_var_name, + type=core.VarDesc.VarType.FETCH_LIST, + persistable=True) + + if use_fetch_v2: + fetch_op = 'fetch_v2' + else: + fetch_op = 'fetch' + + # append fetch_operators + if not has_fetch_operators(global_block, fetch_list, fetch_var_name, + fetch_op): + for i, var in enumerate(fetch_list): + assert isinstance(var, Variable) or isinstance( + var, + six.string_types), ("Wrong type for fetch_list[%s]: %s" % + (i, type(var))) + global_block.append_op(type=fetch_op, + inputs={'X': [var]}, + outputs={'Out': [fetch_var]}, + attrs={'col': i}) + + return tmp_program + + @classmethod + def _remove_fetch_ops(cls, program, fetch_op_name='fetch'): + tmp_program = program.clone() + global_block = tmp_program.global_block() + op_num = len(global_block.ops) + for idx in reversed(range(op_num)): + if global_block.ops[idx].type == fetch_op_name: + global_block._remove_op(idx) + + return tmp_program + + def _run_pipeline(self, + program=None, + dataset=None, + scope=None, + thread=0, + is_infer=False, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None, + use_program_cache=False): + scope, real_fetch_list, trainer_instance = \ + self._prepare_pipeline_ctx(program, dataset, scope, thread, + is_infer, debug, fetch_list, fetch_info, + print_period, fetch_handler, + use_program_cache) + + from paddle.optimizer.lr import LRScheduler + if hasattr(program, 'lr_sheduler'): + lr_sheduler = program.lr_sheduler + assert isinstance(lr_sheduler, LRScheduler), "must be LRScheduler" + lr_value = lr_sheduler() + lr_var = program.global_block().vars[lr_sheduler._var_name] + data = np.array([lr_value]).astype(convert_dtype(lr_var.dtype)) + tensor = core.get_variable_tensor(scope, lr_sheduler._var_name) + tensor.set(data, self.place) + + self._default_executor.run_from_dataset(trainer_instance) + + if not use_program_cache: + self._default_executor.release_trainer(trainer_instance) + + if real_fetch_list: + arr = scope.find_var('fetch').get_fetch_list() + tensors = arr._move_to_list() + return as_numpy(tensors) + + return None + + def infer_from_dataset(self, + program=None, + dataset=None, + scope=None, + thread=0, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + """ + Infer from a pre-defined Dataset. Dataset is defined in paddle.fluid.dataset. + Given a program, either a program or compiled program, infer_from_dataset will + consume all data samples in dataset. Input scope can be given by users. By default, + scope is global_scope(). The total number of thread run in training is `thread`. + Thread number used in training will be minimum value of threadnum in Dataset and + the value of thread in this interface. Debug can be set so that executor will display + Run-Time for all operators and the throughputs of current infer task. + + The document of infer_from_dataset is almost the same as train_from_dataset, + except that in distributed training, push gradients will be disabled in infer_from_dataset. + infer_from_dataset() can be used for evaluation in multi-threadvery easily. + + Args: + program(Program|CompiledProgram): the program that needs to be run, + if not provided, then default_main_program (not compiled) will be used. + dataset(paddle.fluid.Dataset): dataset created outside this function, + a user should provide a well-defined dataset before calling this function. + Please check the document of Dataset if needed. default is None + scope(Scope): the scope used to run this program, you can switch it to different scope + for each run. default is global_scope + thread(int): number of thread a user wants to run in this function. Default is 0, which + means using thread num of dataset + debug(bool): whether a user wants to run infer_from_dataset, default is False + fetch_list(Tensor List): fetch Tensor list, each Tensor will be printed during + training, default is None + fetch_info(String List): print information for each Tensor, default is None + print_period(int): the number of mini-batches for each print, default is 100 + fetch_handler(FetchHandler): a user define class for fetch output. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + + paddle.enable_static() + place = paddle.CPUPlace() # you can set place = paddle.CUDAPlace(0) to use gpu + exe = paddle.static.Executor(place) + x = paddle.static.data(name="x", shape=[None, 10, 10], dtype="int64") + y = paddle.static.data(name="y", shape=[None, 1], dtype="int64", lod_level=1) + dataset = paddle.fluid.DatasetFactory().create_dataset() + dataset.set_use_var([x, y]) + dataset.set_thread(1) + # you should set your own filelist, e.g. filelist = ["dataA.txt"] + filelist = [] + dataset.set_filelist(filelist) + exe.run(paddle.static.default_startup_program()) + exe.infer_from_dataset(program=paddle.static.default_main_program(), + dataset=dataset) + + """ + return self._run_from_dataset(program, dataset, scope, thread, True, + debug, fetch_list, fetch_info, + print_period, fetch_handler) + + def start_heter_trainer(self, + program=None, + scope=None, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + scope, trainer = self._prepare_trainer(program=program, + dataset=None, + scope=scope, + thread=1, + debug=debug, + fetch_list=fetch_list, + fetch_info=fetch_info, + print_period=print_period) + + trainer._set_infer(False) + trainer._gen_trainer_desc() + + self._dump_debug_info(program=program, trainer=trainer) + + trainer_instance = self._default_executor.init_for_dataset( + program.desc, trainer._desc(), scope, None) + + #if fetch_handler is not None: + # scope0 = trainer_instance.get_worker_scope(0) + # fetch_monitor = FetchHandlerMonitor(scope0, fetch_handler) + # fetch_monitor.start() + # self._default_executor.run_from_dataset(trainer_instance) + # fetch_monitor.stop() + # self._default_executor.release_trainer(trainer_instance) + #else: + + self._default_executor.run_from_dataset(trainer_instance) + #self._default_executor.release_trainer(trainer_instance) + + return trainer_instance + + def train_from_dataset(self, + program=None, + dataset=None, + scope=None, + thread=0, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + """ + Train from a pre-defined Dataset. Dataset is defined in paddle.fluid.dataset. + Given a program, either a program or compiled program, train_from_dataset will + consume all data samples in dataset. Input scope can be given by users. By default, + scope is global_scope(). The total number of thread run in training is `thread`. + Thread number used in training will be minimum value of threadnum in Dataset and + the value of thread in this interface. Debug can be set so that executor will display + Run-Time for all operators and the throughputs of current training task. + + Note: train_from_dataset will destroy all resources created within executor for each run. + + Args: + program(Program|CompiledProgram): the program that needs to be run, + if not provided, then default_main_program (not compiled) will be used. + dataset(paddle.fluid.Dataset): dataset created outside this function, + a user should provide a well-defined dataset before calling this function. + Please check the document of Dataset if needed. + scope(Scope): the scope used to run this program, you can switch it to different scope + for each run. default is global_scope + thread(int): number of thread a user wants to run in this function. Default is 0, which + means using thread num of dataset + debug(bool): whether a user wants to run train_from_dataset + fetch_list(Tensor List): fetch Tensor list, each variable will be printed + during training + fetch_info(String List): print information for each Tensor, its length should be equal + to fetch_list + print_period(int): the number of mini-batches for each print, default is 100 + fetch_handler(FetchHandler): a user define class for fetch output. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + + paddle.enable_static() + place = paddle.CPUPlace() # you can set place = paddle.CUDAPlace(0) to use gpu + exe = paddle.static.Executor(place) + x = paddle.static.data(name="x", shape=[None, 10, 10], dtype="int64") + y = paddle.static.data(name="y", shape=[None, 1], dtype="int64", lod_level=1) + dataset = paddle.fluid.DatasetFactory().create_dataset() + dataset.set_use_var([x, y]) + dataset.set_thread(1) + # you should set your own filelist, e.g. filelist = ["dataA.txt"] + filelist = [] + dataset.set_filelist(filelist) + exe.run(paddle.static.default_startup_program()) + exe.train_from_dataset(program=paddle.static.default_main_program(), + dataset=dataset) + + """ + return self._run_from_dataset(program, dataset, scope, thread, False, + debug, fetch_list, fetch_info, + print_period, fetch_handler) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/framework.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbcdc78536acfba7685182b9be6b56d59583dc0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/framework.py @@ -0,0 +1,7833 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function + +import collections +from collections import defaultdict +from collections.abc import Iterable +import contextlib +from .wrapped_decorator import signature_safe_contextmanager, wrap_decorator +import os +import re +import traceback +import six +import copy +from types import MethodType, FunctionType + +import numpy as np +import subprocess +import multiprocessing +import sys +import logging +from .. import compat as cpt +from .proto import framework_pb2 + +from . import core +from . import unique_name +import paddle.version as fluid_version +import warnings +import functools +from .variable_index import _getitem_impl_, _setitem_impl_ + +__all__ = [ + 'Program', + 'default_startup_program', + 'default_main_program', + 'program_guard', + 'name_scope', + 'ipu_shard_guard', + 'set_ipu_shard', + 'cuda_places', + 'cpu_places', + 'xpu_places', + 'mlu_places', + 'cuda_pinned_places', + '_non_static_mode', + 'in_dygraph_mode', + 'is_compiled_with_cinn', + 'is_compiled_with_cuda', + 'is_compiled_with_rocm', + 'is_compiled_with_xpu', + 'is_compiled_with_npu', + 'Variable', + 'require_version', + 'device_guard', + 'set_flags', + 'get_flags', +] + +EMPTY_VAR_NAME = core.kEmptyVarName() +TEMP_VAR_NAME = core.kTempVarName() +GRAD_VAR_SUFFIX = core.kGradVarSuffix() +ZERO_VAR_SUFFIX = core.kZeroVarSuffix() +CONTROL_DEP_VAR_PREFIX = core.kControlDepVarName() + +_dygraph_tracer_ = None +_in_eager_mode_ = os.environ.get('FLAGS_enable_eager_mode', '1') == '1' +_global_expected_place_ = None +_current_device = None +global_prog_seed = 0 +_current_pipeline_stage = None +_already_patch_eager_tensor = False +_already_patch_varbase = False +_current_cuda_graph_mode = None +_global_flags_ = core.globals() +_enable_standalone_executor_ = os.environ.get( + 'FLAGS_USE_STANDALONE_EXECUTOR', None +) +_dy2st_enable_standalone_executor_ = os.environ.get( + 'FLAGS_DY2ST_USE_STANDALONE_EXECUTOR', 0 +) + +# Some explanation of our execution system 2022.03 +# For now we have 3 kinds of execution system, since we refactored dygraph mode to +# build a fast execution system for dynamic mode. But we can't just remove all legacy +# code once we present the new system for some historical reason. That's why we have +# these flags. +# +# 1. _non_static_mode(): +# _non_static_mode means we are now running in legacy dygraph mode or dygraph mode. +# 2. dygraph_mode(): +# This flags inidicates we are now running in dygraph mode which called eager mode before. +# 3. _in_legacy_dygraph(): +# This flags inidicates we are now running in legacy dygraph mode +# +# They have a relation ship as below: +# Both dygraph_mode and _in_legacy_dygraph are _non_static_mode, but if you are running in +# dygraph mode means you are not in _in_legacy_dygraph. +# +# Why we have to make different of _in_legacy_dygraph and dygraph_mode? +# In some performance issue, we find that python if statement cause server performance problem +# and we need our new dygraph mode becomes as fast as it could be. That's why we make these flags +# to make sure in most case, we find new dygraph mode first with only one if statement. + + +def _update_monkey_methods(is_eager): + """ + Update monkey methods of VarBase or eager.Tensor while + switching eager mode and legacy mode. + """ + from paddle import _C_ops, _legacy_C_ops + from .dygraph.varbase_patch_methods import monkey_patch_varbase + from .dygraph import monkey_patch_math_varbase + + global _already_patch_eager_tensor + global _already_patch_varbase + + assert isinstance(is_eager, bool) + # switch into eager mode + if is_eager: + _legacy_C_ops.switch_to_eager_ops() + if not _already_patch_eager_tensor: + monkey_patch_varbase() + monkey_patch_math_varbase() + + _already_patch_eager_tensor = True + # switch back into legacy mode + else: + _legacy_C_ops.switch_to_core_ops() + if not _already_patch_varbase: + monkey_patch_varbase() + monkey_patch_math_varbase() + + _already_patch_varbase = True + + # switch Paddle.Tensor bind type + _switch_tensor_bind_type(is_eager) + + +def _switch_tensor_bind_type(is_eager): + import paddle + + if is_eager: + paddle.Tensor = core.eager.Tensor + else: + paddle.Tensor = core.VarBase + paddle.Tensor.__qualname__ = 'Tensor' + + +def _enable_legacy_dygraph(): + global _in_eager_mode_ + _in_eager_mode_ = False + _update_monkey_methods(is_eager=False) + + +def _disable_legacy_dygraph(): + global _in_eager_mode_ + _in_eager_mode_ = True + _update_monkey_methods(is_eager=True) + + +def _in_eager_without_dygraph_check(): + global _in_eager_mode_ + return _in_eager_mode_ + + +# FIXME(dev): We haven't fully verified eager mode on XPU/NPU et.al but +# only GPU/CPU. Remove this after we improve this feature. +_is_first_import_ = True + + +def _fallback_legacy_dygraph(): + global _in_eager_mode_ + global _is_first_import_ + need_fallback = False + # Only enable eager on CPU/GPU + is_not_support = ( + core.is_compiled_with_xpu() + or core.is_compiled_with_npu() + or core.is_compiled_with_ipu() + or core.is_compiled_with_mlu() + ) + + if _in_eager_mode_ and is_not_support: + # switch into legacy dygraph mode + warnings.warn( + "We will fallback into legacy dygraph on NPU/XPU/MLU/IPU/ROCM devices. Because we only support new eager dygraph mode on CPU/GPU currently. " + ) + _in_eager_mode_ = False + if not _is_first_import_: + _enable_legacy_dygraph() + need_fallback = True + + need_fallback = False + _is_first_import_ = False + + return need_fallback + + +# switch into legacy mode if need while import paddle +_fallback_legacy_dygraph() + + +def in_dygraph_mode(): + """ + + .. note:: + Dynamic graph mode is turn ON by default since paddle 2.0.0 + + This API checks whether paddle runs in dynamic graph mode. + + You can turn ON static graph mode by `enable_static <../dygraph/base/disable_dygraph_en.html>`_ , + and turn OFF static graph mode by `disable_static <../dygraph/base/enable_dygraph_en.html>`_ . + + Returns: + bool: Whether paddle runs in dynamic graph mode. + + Examples: + .. code-block:: python + + import paddle + print(paddle.in_dynamic_mode()) # True, dynamic mode is turn ON by default since paddle 2.0.0 + + paddle.enable_static() + print(paddle.in_dynamic_mode()) # False, Now we are in static mode + + paddle.disable_static() + print(paddle.in_dynamic_mode()) # True, Now we are in dynamic mode + + """ + return (_dygraph_tracer_ is not None) and _in_eager_mode_ + + +def _in_legacy_dygraph(): + return (not _in_eager_mode_) and (_dygraph_tracer_ is not None) + + +def _non_static_mode(): + return _dygraph_tracer_ is not None + + +@signature_safe_contextmanager +def _test_eager_guard(place=None): + # FIXME(dev): We haven't fully verified eager mode on XPU/NPU et.al but + # only GPU/CPU. Remove this after we improve this feature. + already_fallback = _fallback_legacy_dygraph() + if not already_fallback: + _disable_legacy_dygraph() + try: + yield + finally: + if not already_fallback: + _enable_legacy_dygraph() + + +global_ipu_index = -1 +global_ipu_stage = -1 +ipu_index_attr_name = 'ipu_index' +ipu_stage_attr_name = 'ipu_stage' + + +@signature_safe_contextmanager +def _enable_standalone_executor(enable=True): + global _enable_standalone_executor_ + original_ = _enable_standalone_executor_ + _enable_standalone_executor_ = enable + try: + yield + finally: + _enable_standalone_executor_ = original_ + + +@signature_safe_contextmanager +def ipu_shard_guard(index=-1, stage=-1): + """ + Used to shard the graph on IPUs. Set each Op run on which IPU in the sharding and which stage in the pipelining. + + Args: + index(int, optional): Specify which ipu the Tensor is computed on, (such as '0, 1, 2, 3'). + The default value is -1, which means the Op only run on IPU 0. + stage(int, optional): Specify the computation order of the sharded model(such as '0, 1, 2, 3'). + The sharded model will be computed from small to large. The default value is -1, + which means no pipelining computation order and run Ops in terms of graph. + + Note: + Only if the enable_manual_shard=True, the 'index' is able to be set not -1. Please refer + to :ref:`api_paddle_static_IpuStrategy`. + Only if the enable_pipelining=True, the 'stage' is able to be set not -1. Please refer + to :ref:`api_paddle_static_IpuStrategy`. + A index is allowed to match none stage or a stage. A stage is only allowed to match a new or + duplicated index. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + paddle.enable_static() + a = paddle.static.data(name='data', shape=[None, 1], dtype='int32') + with paddle.static.ipu_shard_guard(index=0, stage=0): + b = a + 1 + with paddle.static.ipu_shard_guard(index=1, stage=1): + c = b + 1 + with paddle.static.ipu_shard_guard(index=0, stage=2): + d = c + 1 + """ + if not core.is_compiled_with_ipu(): + raise ValueError( + "Can not use this function since PaddlePaddle is not compiled with IPU" + ) + + global global_ipu_index + global global_ipu_stage + prev_ipu_index = global_ipu_index + prev_ipu_stage = global_ipu_stage + global_ipu_index = index + global_ipu_stage = stage + try: + yield + finally: + global_ipu_index = prev_ipu_index + global_ipu_stage = prev_ipu_stage + + +def set_ipu_shard(call_func, index=-1, stage=-1): + """ + Shard the ipu with the given call function. Set every ops in call function to the given ipu sharding. + + Note: + Only when enable_manual_shard=True to set the index to a value other than -1. please refer to :ref:`api_paddle_static_IpuStrategy` . + Only when enable_pipelining=True to set stage to a value other than -1. please refer to :ref:`api_paddle_static_IpuStrategy` . + An index supports a corresponding None stage or a stage, and a stage only supports a new index or a duplicate index. + + Args: + call_func(Layer|function): Specify the call function to be wrapped. + index(int, optional): Specify which ipu the Tensor is computed on, (such as ‘0, 1, 2, 3’). + The default value is -1, which means the Op only run on IPU 0. + stage(int, optional): Specify the computation order of the sharded model(such as ‘0, 1, 2, 3’). + The sharded model will be computed from small to large. The default value is -1, + which means no pipelining computation order and run Ops in terms of graph. + + Returns: + The wrapped call function. + + Examples: + .. code-block:: python + + # required: ipu + + import paddle + paddle.enable_static() + a = paddle.static.data(name='data', shape=[None, 1], dtype='float32') + relu = paddle.nn.ReLU() + relu = paddle.static.set_ipu_shard(relu, index=1, stage=1) + relu(a) + """ + + def decorate(func): + def wrapper(*args, **kwargs): + with ipu_shard_guard(index=index, stage=stage): + return func(*args, **kwargs) + + return wrapper + + from .dygraph.layers import Layer + + if not isinstance(call_func, Layer): + if callable(call_func): + return decorate(call_func) + else: + raise TypeError( + "Unsupported type. Only accept paddle.nn.Layer or function." + ) + + # patch paddle.nn.Layer + class BlockFn(type(call_func)): + def __call__(self, *args, **kwargs): + with ipu_shard_guard(index=index, stage=stage): + return super().__call__(*args, **kwargs) + + BlockFn.__name__ = type(call_func).__name__ + call_func.__class__ = BlockFn + return call_func + + +def require_version(min_version, max_version=None): + """ + Check if the installed version of PaddlePaddle is in [min_version, max_version], + if the installed version is lower than ``min_version`` or higher than ``max_version``, + an exception will be thrown, NO returns if the installed version is satisfied. + + Args: + min_version (str): the minimum version required (like '1.4.0'). + max_version (str, optional): the max version required (like '1.6.0'), default is None, + meaning any version equal or higher than ``min_version`` is acceptable. + + Returns: + None. + + Raises: + TypeError: if the type of ``min_version`` is not str. + TypeError: if the type of ``max_version`` is not str or type(None). + ValueError: if the value of ``min_version`` is not in version format. + ValueError: if the value of ``max_version`` is not in version format or None. + Exception: if the installed version is lower than ``min_version`` or higher than ``max_version``. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + # any version >= 0.1.0 is acceptable. + fluid.require_version('0.1.0') + + # if 0.1.0 <= version <= 10.0.0, it is acceptable. + fluid.require_version(min_version='0.1.0', max_version='10.0.0') + """ + if not isinstance(min_version, str): + raise TypeError( + "The type of 'min_version' in require_version must be str, but received %s." + % (type(min_version)) + ) + + if not isinstance(max_version, (str, type(None))): + raise TypeError( + "The type of 'max_version' in require_version must be str or type(None), but received %s." + % (type(max_version)) + ) + + check_format = re.match(r'\d+(\.\d+){0,3}', min_version) + if check_format is None or check_format.group() != min_version: + raise ValueError( + "The value of 'min_version' in require_version must be in format '\\d+(\\.\\d+){0,3}', " + "like '1.5.2.0', but received %s" % min_version + ) + + if max_version is not None: + check_format = re.match(r'\d+(\.\d+){0,3}', max_version) + if check_format is None or check_format.group() != max_version: + raise ValueError( + "The value of 'max_version' in require_version must be in format '\\d+(\\.\\d+){0,3}', " + "like '1.5.2.0', but received %s" % max_version + ) + + version_installed = [ + fluid_version.major, + fluid_version.minor, + fluid_version.patch, + fluid_version.rc, + ] + zero_version = ['0', '0', '0', '0'] + + def version_cmp(ver_a, ver_b): + for i in six.moves.range(len(ver_a)): + if int(ver_a[i]) > int(ver_b[i]): + return 1 + elif int(ver_a[i]) < int(ver_b[i]): + return -1 + return 0 + + if version_cmp(version_installed, zero_version) == 0: + if max_version is not None: + warnings.warn( + "PaddlePaddle version in [%s, %s] required, but %s installed. " + "Maybe you are using a develop version, " + "please make sure the version is good with your code." + % (min_version, max_version, fluid_version.full_version) + ) + else: + warnings.warn( + "PaddlePaddle version %s or higher is required, but %s installed, " + "Maybe you are using a develop version, " + "please make sure the version is good with your code." + % (min_version, fluid_version.full_version) + ) + return + + min_version_split = min_version.split('.') + min_version_to_check = ( + min_version_split + zero_version[len(min_version_split) :] + ) + + if max_version is not None: + max_version_split = max_version.split('.') + max_version_to_check = ( + max_version_split + zero_version[len(max_version_split) :] + ) + + if ( + version_cmp(version_installed, max_version_to_check) > 0 + or version_cmp(version_installed, min_version_to_check) < 0 + ): + raise Exception( + "VersionError: PaddlePaddle version in [%s, %s] required, but %s installed." + % (min_version, max_version, fluid_version.full_version) + ) + else: + if version_cmp(version_installed, min_version_to_check) < 0: + raise Exception( + "VersionError: PaddlePaddle version %s or higher is required, but %s installed, " + "please upgrade your PaddlePaddle to %s or other higher version." + % (min_version, fluid_version.full_version, min_version) + ) + + +def _dygraph_not_support_(func): + def __impl__(*args, **kwargs): + assert not _non_static_mode(), ( + "We don't support %s in dynamic graph mode" % func.__name__ + ) + return func(*args, **kwargs) + + return __impl__ + + +def _dygraph_only_(func): + def __impl__(*args, **kwargs): + assert _non_static_mode(), ( + "We only support '%s()' in dynamic graph mode, please call 'paddle.disable_static()' to enter dynamic graph mode." + % func.__name__ + ) + return func(*args, **kwargs) + + return __impl__ + + +def _non_static_only_(func): + def __impl__(*args, **kwargs): + from .dygraph.base import in_declarative_mode + + assert _non_static_mode() or in_declarative_mode(), ( + "We only support '%s()' in dynamic graph mode, please call 'paddle.disable_static()' to enter dynamic graph mode." + % func.__name__ + ) + return func(*args, **kwargs) + + return __impl__ + + +def _static_only_(func): + def __impl__(*args, **kwargs): + assert not _non_static_mode(), ( + "In PaddlePaddle 2.x, we turn on dynamic graph mode by default, and '%s()' is only supported in static graph mode. So if you want to use this api, please call 'paddle.enable_static()' before this api to enter static graph mode." + % func.__name__ + ) + return func(*args, **kwargs) + + return __impl__ + + +def _set_pipeline_stage(stage): + global _current_pipeline_stage + _current_pipeline_stage = stage + + +# NOTE(zhiqiu): This decorator is used for the APIs of Variable which is only +# used to make Variable and VarBase has same interfaces, like numpy. Since VarBase is not exposed in our +# official docments, logically, we want to keep VarBase and logically consistent. While, actually, +# in our implementation, there some APIs not supported, like numpy, because Variable contains the desc. +# So, those APIs are listed under class Variable to generate docs only. +# TODO(zhiqiu): We should make VarBase consistent with Variable in future, for example, by inheritting +# same base class. +def _fake_interface_only_(func): + def __impl__(*args, **kwargs): + raise AssertionError( + "'%s' only can be called by `paddle.Tensor` in dynamic graph mode. Suggestions:\n" + " 1. If you are in static graph mode, you can switch to dynamic graph mode by turning off `paddle.enable_static()` or calling `paddle.disable_static()`.\n" + " 2. If you are using `@paddle.jit.to_static`, you can turn off ProgramTranslator by calling `paddle.jit.ProgramTranslator().enable(False)`. " + "If you have to translate dynamic graph to static graph, please use other API to replace '%s'." + % (func.__name__, func.__name__) + ) + + return __impl__ + + +# NOTE(chenweihang): There is argument name typo (stat_dict, correct name is state_dict) +# in fluid api Layer.set_dict, Optimizer.load, in order to correct the argument without +# introducing compatibility issues, add this decorator +# NOTE(chenweihang): not using `wrap_decorator` here is because `wrap_decorator` will +# move kwargs to args, which doesn't work in this decorate case +def deprecate_stat_dict(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + if 'stat_dict' in kwargs: + warnings.warn( + "The argument `stat_dict` has deprecated, please change it to `state_dict`.", + DeprecationWarning, + ) + kwargs['state_dict'] = kwargs['stat_dict'] + kwargs.pop('stat_dict') + return func(*args, **kwargs) + + return wrapper + + +dygraph_not_support = wrap_decorator(_dygraph_not_support_) +dygraph_only = wrap_decorator(_dygraph_only_) +static_only = wrap_decorator(_static_only_) +fake_interface_only = wrap_decorator(_fake_interface_only_) +non_static_only = wrap_decorator(_non_static_only_) + + +def _dygraph_tracer(): + return _dygraph_tracer_ + + +def _global_flags(): + return _global_flags_ + + +def _current_expected_place(): + global _global_expected_place_ + if _global_expected_place_ is None: + if core.is_compiled_with_cuda(): + try: + device_count = core.get_cuda_device_count() + except Exception as e: + device_count = 0 + if device_count > 0: + _global_expected_place_ = core.CUDAPlace(_cuda_ids()[0]) + else: + warnings.warn( + "You are using GPU version Paddle, but your CUDA device is not set properly. CPU device will be used by default." + ) + _global_expected_place_ = core.CPUPlace() + elif core.is_compiled_with_xpu(): + try: + device_count = core.get_xpu_device_count() + except Exception as e: + device_count = 0 + if device_count > 0: + _global_expected_place_ = core.XPUPlace(_xpu_ids()[0]) + else: + warnings.warn( + "You are using XPU version Paddle, but your XPU device is not set properly. CPU device will be used by default." + ) + _global_expected_place_ = core.CPUPlace() + elif core.is_compiled_with_mlu(): + try: + device_count = core.get_mlu_device_count() + except Exception as e: + device_count = 0 + if device_count > 0: + _global_expected_place_ = core.MLUPlace(_mlu_ids()[0]) + else: + warnings.warn( + "You are using MLU version Paddle, but your MLU device is not set properly. CPU device will be used by default." + ) + _global_expected_place_ = core.CPUPlace() + else: + _global_expected_place_ = core.CPUPlace() + + return _global_expected_place_ + + +def _set_dygraph_tracer_expected_place(place): + global _dygraph_tracer_ + if _dygraph_tracer_ is not None: + _dygraph_tracer_._expected_place = place + + +def _set_expected_place(place): + global _global_expected_place_ + _global_expected_place_ = place + _set_dygraph_tracer_expected_place(place) + + +# TODO(zhiqiu): remove this function. +def _var_base_to_np(var_base): + """ + convert VarBase tp numpy + + Args: + var_base(VarBase) : the VarBase to convert + Returns (np.ndarray): the np.ndarray contain the value of VarBase + """ + + warnings.warn( + "paddle.fluid.framework._var_base_to_np is deprecated, please use var_base.numpy() instead of _var_base_to_np(var_base)." + ) + + return var_base.numpy() + + +def _cpu_num(): + if "CPU_NUM" not in os.environ.keys(): + if multiprocessing.cpu_count() > 1: + sys.stderr.write( + '!!! The CPU_NUM is not specified, you should set CPU_NUM in the environment variable list.\n' + 'CPU_NUM indicates that how many CPUPlace are used in the current task.\n' + 'And if this parameter are set as N (equal to the number of physical CPU core) the program may be faster.\n\n' + 'export CPU_NUM={} # for example, set CPU_NUM as number of physical CPU core which is {}.\n\n' + '!!! The default number of CPU_NUM=1.\n'.format( + multiprocessing.cpu_count(), multiprocessing.cpu_count() + ) + ) + os.environ['CPU_NUM'] = str(1) + cpu_num = os.environ.get('CPU_NUM') + return int(cpu_num) + + +def _cuda_ids(): + gpus_env = os.getenv("FLAGS_selected_gpus") + if gpus_env: + device_ids = [int(s) for s in gpus_env.split(",")] + else: + device_ids = six.moves.range(core.get_cuda_device_count()) + return device_ids + + +def _xpu_ids(): + xpus_env = os.getenv("FLAGS_selected_xpus") + if xpus_env: + device_ids = [int(s) for s in xpus_env.split(",")] + else: + device_ids = six.moves.range(core.get_xpu_device_count()) + return device_ids + + +def _npu_ids(): + npus_env = os.getenv("FLAGS_selected_npus") + if npus_env: + device_ids = [int(s) for s in npus_env.split(",")] + else: + device_ids = six.moves.range(core.get_npu_device_count()) + return device_ids + + +def _mlu_ids(): + mlus_env = os.getenv("FLAGS_selected_mlus") + if mlus_env: + device_ids = [int(s) for s in mlus_env.split(",")] + else: + device_ids = six.moves.range(core.get_mlu_device_count()) + return device_ids + + +def is_compiled_with_xpu(): + """ + Whether this whl package can be used to run the model on XPU. + + Returns (bool): support xpu or not. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + support_xpu = fluid.is_compiled_with_xpu() + """ + return core.is_compiled_with_xpu() + + +def is_compiled_with_npu(): + """ + Whether this whl package can be used to run the model on NPU. + + Returns (bool): support npu or not. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + support_npu = fluid.is_compiled_with_npu() + """ + return core.is_compiled_with_npu() + + +def disable_signal_handler(): + """ + Reset signal handler registered by Paddle. + + Paddle installs signal handlers at C++ level to log debug information upon failing. + However, conflicts can happen if another python module is making use of such signal. + Such being the case, one may disblae paddle signal handler via this interface. + + Known frameworks that require disabling signal handler includes: + 1. TVM + 2. ADLIK + + Make sure you called paddle.disable_signal_handler() before using above mentioned frameworks. + + Returns: None + + Examples: + .. code-block:: python + + import paddle + paddle.disable_signal_handler() + """ + core.disable_signal_handler() + + +def is_compiled_with_cinn(): + """ + Whether this whl package can be used to run the model on CINN. + + Returns (bool): `True` if CINN is currently available, otherwise `False`. + + Examples: + .. code-block:: python + + import paddle + support_cinn = paddle.device.is_compiled_with_cinn() + """ + return core.is_compiled_with_cinn() + + +def is_compiled_with_cuda(): + """ + Whether this whl package can be used to run the model on GPU. + + Returns (bool): `True` if CUDA is currently available, otherwise `False`. + + Examples: + .. code-block:: python + + import paddle + support_gpu = paddle.device.is_compiled_with_cuda() + """ + return core.is_compiled_with_cuda() + + +def is_compiled_with_rocm(): + """ + Whether this whl package can be used to run the model on AMD or Hygon GPU(ROCm). + + Returns (bool): `True` if ROCm is currently available, otherwise `False`. + + Examples: + .. code-block:: python + + import paddle + support_gpu = paddle.device.is_compiled_with_rocm() + """ + return core.is_compiled_with_rocm() + + +def cuda_places(device_ids=None): + """ + Note: + For multi-card tasks, please use `FLAGS_selected_gpus` environment variable to set the visible GPU device. + The next version will fix the problem with `CUDA_VISIBLE_DEVICES` environment variable. + + This function creates a list of :code:`paddle.CUDAPlace` objects. + + If :code:`device_ids` is None, environment variable of + :code:`FLAGS_selected_gpus` would be checked first. For example, if + :code:`FLAGS_selected_gpus=0,1,2`, the returned list would + be [paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)]. + If :code:`FLAGS_selected_gpus` is not set, all visible + gpu places would be returned according to the :code:`CUDA_VISIBLE_DEVICES` environment variable. + + If :code:`device_ids` is not None, it should be the device + ids of GPUs. For example, if :code:`device_ids=[0,1,2]`, + the returned list would be + [paddle.CUDAPlace(0), paddle.CUDAPlace(1), paddle.CUDAPlace(2)]. + + Parameters: + device_ids (list|tuple, optional): A list/tuple of int of GPU device ids. + + Returns: + list of paddle.CUDAPlace: Created GPU place list. + + Examples: + + .. code-block:: python + + import paddle + import paddle.static as static + + # required: gpu + + paddle.enable_static() + + cuda_places = static.cuda_places() + + """ + assert core.is_compiled_with_cuda(), "Not compiled with CUDA" + if device_ids is None: + device_ids = _cuda_ids() + elif not isinstance(device_ids, (list, tuple)): + device_ids = [device_ids] + return [core.CUDAPlace(dev_id) for dev_id in device_ids] + + +def xpu_places(device_ids=None): + """ + **Note**: + For multi-card tasks, please use `FLAGS_selected_xpus` environment variable to set the visible XPU device. + This function creates a list of :code:`paddle.XPUPlace` objects. + If :code:`device_ids` is None, environment variable of + :code:`FLAGS_selected_xpus` would be checked first. For example, if + :code:`FLAGS_selected_xpus=0,1,2`, the returned list would + be [paddle.XPUPlace(0), paddle.XPUPlace(1), paddle.XPUPlace(2)]. + If :code:`FLAGS_selected_xpus` is not set, all visible + xpu places would be returned. + If :code:`device_ids` is not None, it should be the device + ids of XPUs. For example, if :code:`device_ids=[0,1,2]`, + the returned list would be + [paddle.XPUPlace(0), paddle.XPUPlace(1), paddle.XPUPlace(2)]. + + Parameters: + device_ids (list or tuple of int, optional): list of XPU device ids. + Returns: + list of paddle.XPUPlace: Created XPU place list. + Examples: + .. code-block:: python + + # required: xpu + + import paddle + import paddle.static as static + + paddle.enable_static() + xpu_places = static.xpu_places() + """ + assert core.is_compiled_with_xpu(), "Not compiled with XPU" + if device_ids is None: + device_ids = _xpu_ids() + elif not isinstance(device_ids, (list, tuple)): + device_ids = [device_ids] + return [core.XPUPlace(dev_id) for dev_id in device_ids] + + +def npu_places(device_ids=None): + """ + **Note**: + For multi-card tasks, please use `FLAGS_selected_npus` environment variable to set the visible NPU device. + + This function creates a list of :code:`paddle.NPUPlace` objects. + If :code:`device_ids` is None, environment variable of + :code:`FLAGS_selected_npus` would be checked first. For example, if + :code:`FLAGS_selected_npus=0,1,2`, the returned list would + be [paddle.NPUPlace(0), paddle.NPUPlace(1), paddle.NPUPlace(2)]. + If :code:`FLAGS_selected_npus` is not set, all visible + npu places would be returned. + If :code:`device_ids` is not None, it should be the device + ids of NPUs. For example, if :code:`device_ids=[0,1,2]`, + the returned list would be + [paddle.NPUPlace(0), paddle.NPUPlace(1), paddle.NPUPlace(2)]. + + Parameters: + device_ids (list or tuple of int, optional): list of NPU device ids. + Returns: + list of paddle.NPUPlace: Created NPU place list. + Examples: + .. code-block:: python + + # required: npu + + import paddle + import paddle.static as static + + paddle.enable_static() + npu_places = static.npu_places() + """ + assert core.is_compiled_with_npu(), "Not compiled with NPU" + if device_ids is None: + device_ids = _npu_ids() + elif not isinstance(device_ids, (list, tuple)): + device_ids = [device_ids] + return [core.NPUPlace(dev_id) for dev_id in device_ids] + + +def cpu_places(device_count=None): + """ + This function creates a list of :code:`paddle.CPUPlace` objects, and returns the created list. + + If :code:`device_count` is None, the device count would + be determined by environment variable :code:`CPU_NUM`. + If :code:`CPU_NUM` is not set, the default value is 1, + i.e. CPU_NUM=1. + :code:`CPU_NUM` indicates the number of devices used in the current task. + The running of the program can be accelerated if :code:`CPU_NUM` is the same as the number of physical cores. + + Parameters: + device_count (int, optional): device number. Default: None. + + Returns: + list of paddle.CPUPlace: Created list of CPU places. + + Examples: + + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + cpu_places = static.cpu_places() + """ + + if device_count is None: + device_count = _cpu_num() + return [core.CPUPlace()] * device_count + + +def cuda_pinned_places(device_count=None): + """ + This function creates a list of :code:`fluid.CUDAPinnedPlace` objects. + + If :code:`device_count` is None, the device count would + be determined by environment variable :code:`CPU_NUM`. + If :code:`CPU_NUM` is not set, the default value is 1, + i.e. CPU_NUM=1. + :code:`CPU_NUM` indicates the number of devices used in the current task. + The running of the program can be accelerated if :code:`CPU_NUM` is the same as the number of physical cores. + + Parameters: + device_count (int, optional): device number. Default: None. + + Returns: + list of fluid.CUDAPinnedPlace: Created list of CUDA pinned places. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cuda_pinned_places_cpu_num = fluid.cuda_pinned_places() + # or + cuda_pinned_places = fluid.cuda_pinned_places(1) + + """ + assert core.is_compiled_with_cuda(), "Not compiled with CUDA" + if device_count is None: + device_count = len(_cuda_ids()) + return [core.CUDAPinnedPlace()] * device_count + + +def mlu_places(device_ids=None): + """ + This function creates a list of :code:`paddle.device.MLUPlace` objects. + If :code:`device_ids` is None, environment variable of + :code:`FLAGS_selected_mlus` would be checked first. For example, if + :code:`FLAGS_selected_mlus=0,1,2`, the returned list would + be [paddle.device.MLUPlace(0), paddle.device.MLUPlace(1), paddle.device.MLUPlace(2)]. + If :code:`FLAGS_selected_mlus` is not set, all visible + mlu places would be returned. + If :code:`device_ids` is not None, it should be the device + ids of MLUs. For example, if :code:`device_ids=[0,1,2]`, + the returned list would be + [paddle.device.MLUPlace(0), paddle.device.MLUPlace(1), paddle.device.MLUPlace(2)]. + + Note: + For multi-card tasks, please use `FLAGS_selected_mlus` environment variable to set the visible MLU device. + + Parameters: + device_ids (list or tuple of int, optional): list of MLU device ids. + + Returns: + list of paddle.device.MLUPlace: Created MLU place list. + + Examples: + .. code-block:: python + + # required: mlu + + import paddle + import paddle.static as static + + paddle.enable_static() + mlu_places = static.mlu_places() + """ + assert core.is_compiled_with_mlu(), "Not compiled with MLU" + if device_ids is None: + device_ids = _mlu_ids() + elif not isinstance(device_ids, (list, tuple)): + device_ids = [device_ids] + return [core.MLUPlace(dev_id) for dev_id in device_ids] + + +class NameScope(object): + def __init__(self, name="", parent=None): + self._children = dict() + self._name = name + self._parent = parent + + def child(self, prefix): + if prefix not in self._children: + new_child = NameScope(prefix, self) + self._children[prefix] = [new_child] + else: + new_child = NameScope( + prefix + "_%d" % len(self._children[prefix]), self + ) + self._children[prefix].append(new_child) + return new_child + + def parent(self): + return self._parent + + def name(self): + return self._name + + +_name_scope = NameScope() + + +@signature_safe_contextmanager +def name_scope(prefix=None): + """ + + Generate hierarchical name prefix for the operators in Static Graph. + + Note: + This should only used for debugging and visualization purpose. + Don't use it for serious analysis such as graph/program transformations. + Don't use it in dygraph, since it will cause memory leak. + + Args: + prefix(str, optional): prefix. Default is none. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + with paddle.static.name_scope("s1"): + a = paddle.static.data(name='data', shape=[None, 1], dtype='int32') + b = a + 1 + with paddle.static.name_scope("s2"): + c = b * 1 + with paddle.static.name_scope("s3"): + d = c / 1 + with paddle.static.name_scope("s1"): + f = paddle.tensor.pow(d, 2.0) + with paddle.static.name_scope("s4"): + g = f - 1 + + # Op are created in the default main program. + for op in paddle.static.default_main_program().block(0).ops: + # elementwise_add is created in /s1/ + if op.type == 'elementwise_add': + assert op.desc.attr("op_namescope") == '/s1/' + # elementwise_mul is created in '/s1/s2' + elif op.type == 'elementwise_mul': + assert op.desc.attr("op_namescope") == '/s1/s2/' + # elementwise_div is created in '/s1/s3' + elif op.type == 'elementwise_div': + assert op.desc.attr("op_namescope") == '/s1/s3/' + # elementwise_sum is created in '/s4' + elif op.type == 'elementwise_sub': + assert op.desc.attr("op_namescope") == '/s4/' + # pow is created in /s1_1/ + elif op.type == 'pow': + assert op.desc.attr("op_namescope") == '/s1_1/' + """ + # TODO(panyx0718): Only [0-9a-z]. + # in dygraph we don't need namescope since it will cause mem leak + if _non_static_mode(): + yield + else: + assert prefix, "namescope prefix can not be empty." + global _name_scope + _name_scope = _name_scope.child(prefix) + try: + yield + finally: + _name_scope = _name_scope.parent() + + +def _full_name_scope(): + global _name_scope + scope = _name_scope + name = "" + while scope: + name = scope.name() + "/" + name + scope = scope.parent() + return name + + +def generate_control_dev_var_name(): + import random + + return CONTROL_DEP_VAR_PREFIX + "@" + str(random.random()) + + +def grad_var_name(var_name): + """ + Returns: + str: gradient name for a certain var name + """ + return var_name + GRAD_VAR_SUFFIX + + +def convert_np_dtype_to_dtype_(np_dtype): + """ + Convert the data type in numpy to the data type in Paddle + + Args: + np_dtype(np.dtype): the data type in numpy. + + Returns: + core.VarDesc.VarType: the data type in Paddle. + + """ + dtype = np.dtype(np_dtype) + if dtype == np.float32: + return core.VarDesc.VarType.FP32 + elif dtype == np.float64: + return core.VarDesc.VarType.FP64 + elif dtype == np.float16: + return core.VarDesc.VarType.FP16 + elif dtype == np.int32: + return core.VarDesc.VarType.INT32 + elif dtype == np.int16: + return core.VarDesc.VarType.INT16 + elif dtype == np.int64: + return core.VarDesc.VarType.INT64 + elif dtype == np.bool_: + return core.VarDesc.VarType.BOOL + elif dtype == np.uint16: + # since there is still no support for bfloat16 in NumPy, + # uint16 is used for casting bfloat16 + return core.VarDesc.VarType.BF16 + elif dtype == np.uint8: + return core.VarDesc.VarType.UINT8 + elif dtype == np.int8: + return core.VarDesc.VarType.INT8 + elif dtype == np.complex64: + return core.VarDesc.VarType.COMPLEX64 + elif dtype == np.complex128: + return core.VarDesc.VarType.COMPLEX128 + else: + raise ValueError("Not supported numpy dtype %s" % dtype) + + +def dtype_is_floating(dtype): + """ + Check the data type is floating or not. + Args: + dtype(np.dtype|core.VarDesc.VarType): data type. + Could be numpy format or Paddle format + + Returns(bool): True if data type is a float value + + """ + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + return dtype in [ + core.VarDesc.VarType.FP16, + core.VarDesc.VarType.FP32, + core.VarDesc.VarType.FP64, + ] + + +def _debug_string_(proto, throw_on_error=True): + """ + Get the debug string of a protobuf message. The message could be not + initialized. + Args: + proto(google.protobuf.message.Message): The protobuf message + throw_on_error(bool): True if raise an error when the protobuf message + is not initialized. + + Returns(str): The debug string of the protobuf message + + """ + error_fields = list() + if not proto.IsInitialized(error_fields) and throw_on_error: + raise ValueError( + "{0} are not initialized.\nThe message is {1}:\n".format( + error_fields, proto + ) + ) + return proto.__str__() + + +def _varbase_creator( + type=core.VarDesc.VarType.LOD_TENSOR, + name=None, + shape=None, + dtype=None, + persistable=None, + **kwargs +): + if dtype is not None: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if _in_eager_mode_: + eager_tensor = core.eager.Tensor( + dtype if dtype else core.VarDesc.VarType.FP32, + list(shape) if shape else [], + name, + type if type else core.VarDesc.VarType.LOD_TENSOR, + True if persistable else False, + ) + eager_tensor.retain_grads() + return eager_tensor + else: + return core.VarBase( + dtype if dtype else core.VarDesc.VarType.FP32, + list(shape) if shape else [], + name, + type if type else core.VarDesc.VarType.LOD_TENSOR, + True if persistable else False, + ) + + +def _all_is_type(vals, expected_type): + """ + Return True if type of each element is expected_type. + + NOTE: BuiltIn all() will always return True if vals is empty. + """ + assert isinstance(vals, (list, tuple)) + if not vals: + return False + return all(isinstance(v, expected_type) for v in vals) + + +class VariableMetaClass(type): + @classmethod + def __instancecheck__(cls, instance): + t = type(instance) + if in_dygraph_mode(): + return issubclass(t, core.eager.Tensor) + else: + if _in_legacy_dygraph(): + return issubclass(t, core.VarBase) + return issubclass(t, Variable) + + +class ParameterMetaClass(VariableMetaClass): + @classmethod + def __instancecheck__(cls, instance): + t = type(instance) + if in_dygraph_mode(): + return issubclass(t, EagerParamBase) + else: + if _in_legacy_dygraph(): + return issubclass(t, ParamBase) + return issubclass(t, Parameter) + + +@six.add_metaclass(VariableMetaClass) +class Variable(object): + """ + + Notes: + The constructor of Variable should not be invoked directly. + + In Static Graph Mode: Please use ** `Block.create_var` ** to create a Static variable which has no data until being feed. + + In Dygraph Mode: Please use ** :ref:`api_fluid_dygraph_to_variable` ** to create a dygraph variable with real data. + + In Fluid, every input and output of an OP is a variable. In most + cases, variables are used for holding different kinds of data or training + labels. A variable belongs to a :ref:`api_guide_Block_en` . All variable has its own name and + two variables in different :ref:`api_guide_Block_en` could have the same name. + + There are many kinds of variables. Each kind of them has its own attributes + and usages. Please refer to the `framework.proto `_ for details. + + Most of a Variable's member variables can be set to be None. It mean + it is not available or will be specified later. + + Examples: + In Static Graph Mode: + + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + + In `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ Mode: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + new_variable = fluid.dygraph.to_variable(np.arange(10)) + + """ + + def __init__( + self, + block, + type=core.VarDesc.VarType.LOD_TENSOR, + name=None, + shape=None, + dtype=None, + lod_level=None, + capacity=None, + persistable=None, + error_clip=None, + stop_gradient=False, + is_data=False, + need_check_feed=False, + belong_to_optimizer=False, + **kwargs + ): + self.block = block + if name is None: + name = unique_name.generate('_generated_var') + + if dtype is not None: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if dtype == core.VarDesc.VarType.STRINGS: + type = core.VarDesc.VarType.STRINGS + lod_level = None + + if type == core.VarDesc.VarType.SPARSE_COO: + lod_level = None + + self.belong_to_optimizer = belong_to_optimizer + + self.error_clip = error_clip + + is_new_var = False + name = cpt.to_text(name) + self.desc = self.block.desc.find_var(cpt.to_bytes(name)) + + if self.desc is None: + self.desc = self.block.desc.var(cpt.to_bytes(name)) + is_new_var = True + + if is_new_var: + self.desc.set_type(type) + elif self.desc.type() != type: + raise ValueError( + "Variable '{0}' has been created before. The " + "previous type is {1}, the new type is {2}. They" + " are not matched".format(self.name, self.desc.type(), type) + ) + + if shape is not None: + if is_new_var: + self.desc.set_shape(shape) + else: + old_shape = self.shape + shape = tuple(shape) + if shape != old_shape: + raise ValueError( + "Variable '{0}' has been created before. The previous " + "shape is {1}, the new shape is {2}. They are not " + "matched.".format(self.name, old_shape, shape) + ) + if dtype is not None: + if is_new_var: + self.desc.set_dtype(dtype) + else: + old_dtype = self.dtype + if dtype != old_dtype: + raise ValueError( + "Variable '{0}' has been created before. " + "The previous data type is {1}, the new " + "data type is {2}. They are not " + "matched.".format(self.name, old_dtype, dtype) + ) + + if lod_level is not None: + if is_new_var: + self.desc.set_lod_level(lod_level) + else: + if lod_level != self.lod_level: + raise ValueError( + "Variable '{0}' has been created before. " + "The previous lod_level is {1}, the new " + "lod_level is {2}. They are not " + "matched".format(self.name, self.lod_level, lod_level) + ) + if persistable is not None: + if is_new_var: + self.desc.set_persistable(persistable) + else: + if persistable != self.persistable: + raise ValueError( + "Variable '{0}' has been created before." + "The previous persistable is {1}, the new " + "persistable is {2}. They are not matched".format( + self.name, self.persistable, persistable + ) + ) + + if need_check_feed and is_new_var: + self.desc.set_need_check_feed(need_check_feed) + + if capacity is not None: + if is_new_var: + self.desc.set_capacity(capacity) + else: + # TODO(abhinavarora) : Compare with set capacity once, + # get_capacity is implemented + pass + + self.block.vars[name] = self + self.op = None + self.stop_gradient = stop_gradient + self.is_data = is_data + + def detach(self): + """ + + Returns a new Variable, detached from the current graph. + It will share data with origin Variable and without tensor copy. + In addition, the detached Variable doesn't provide gradient propagation. + + Returns: + ( :ref:`api_guide_Variable_en` | dtype is same as current Variable), The detached Variable. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + # create a static Variable + x = paddle.static.data(name='x', shape=[3, 2, 1]) + + # create a detached Variable + y = x.detach() + + """ + + assert ( + self.type == core.VarDesc.VarType.SELECTED_ROWS + or self.type == core.VarDesc.VarType.LOD_TENSOR + ), "only support a variable with SELECTED_ROWS or LOD_TENSOR to be detached" + + output = self.block.create_var( + name=unique_name.generate_with_ignorable_key("detach_" + self.name), + dtype=self.dtype, + type=self.type, + persistable=self.persistable, + stop_gradient=True, + ) + + self.block.append_op( + type='share_data', inputs={'X': [self]}, outputs={'Out': [output]} + ) + return output + + @fake_interface_only + def numpy(self): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + Returns a numpy array shows the value of current :ref:`api_guide_Variable_en` + + Returns: + ndarray: The numpy value of current Variable. + + Returns type: + ndarray: dtype is same as current Variable + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.dygraph.base import to_variable + from paddle.fluid.dygraph import Linear + import numpy as np + + data = np.random.uniform(-1, 1, [30, 10, 32]).astype('float32') + with fluid.dygraph.guard(): + linear = Linear(32, 64) + data = to_variable(data) + x = linear(data) + print(x.numpy()) + + """ + pass + + @fake_interface_only + def backward(self, retain_graph=False): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + Run backward of current Graph which starts from current Tensor. + + Args: + retain_graph(bool, optional): If False, the graph used to compute grads will be freed. If you would + like to add more ops to the built graph after calling this method( :code:`backward` ), set the parameter + :code:`retain_graph` to True, then the grads will be retained. Thus, seting it to False is much more memory-efficient. + Defaults to False. + + Returns: + NoneType: None + + Examples: + .. code-block:: python + + import numpy as np + import paddle + paddle.disable_static() + + x = np.ones([2, 2], np.float32) + inputs = [] + for _ in range(10): + tmp = paddle.to_tensor(x) + # if we don't set tmp's stop_gradient as False then, all path to loss will has no gradient since + # there is no one need gradient on it. + tmp.stop_gradient=False + inputs.append(tmp) + ret = paddle.add_n(inputs) + loss = paddle.sum(ret) + loss.backward() + + """ + pass + + @fake_interface_only + def gradient(self): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + Get the Gradient of Current Variable + + Returns: + ndarray or tuple of ndarray: if Variable's type is LoDTensor, return numpy value of the gradient of current Variable, if Variable's type is SelectedRows, return tuple of ndarray, first element of tuple is numpy value of the gradient of current Variable, second element of tuple is numpy value of the rows of current Variable. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + # example1: return ndarray + x = np.ones([2, 2], np.float32) + with fluid.dygraph.guard(): + inputs2 = [] + for _ in range(10): + tmp = fluid.dygraph.base.to_variable(x) + tmp.stop_gradient=False + inputs2.append(tmp) + ret2 = fluid.layers.sums(inputs2) + loss2 = fluid.layers.reduce_sum(ret2) + loss2.backward() + print(loss2.gradient()) + + # example2: return tuple of ndarray + with fluid.dygraph.guard(): + embedding = fluid.dygraph.Embedding( + size=[20, 32], + param_attr='emb.w', + is_sparse=True) + x_data = np.arange(12).reshape(4, 3).astype('int64') + x_data = x_data.reshape((-1, 3, 1)) + x = fluid.dygraph.base.to_variable(x_data) + out = embedding(x) + out.backward() + print(embedding.weight.gradient()) + + """ + pass + + @fake_interface_only + def clear_gradient(self): + """ + **Notes**: + **1. This API is ONLY available in Dygraph mode** + + **2. Use it only Variable has gradient, normally we use this for Parameters since other temporal Variable will be deleted by Python's GC** + + Clear (set to ``0`` ) the Gradient of Current Variable + + Returns: None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + x = np.ones([2, 2], np.float32) + with fluid.dygraph.guard(): + inputs2 = [] + for _ in range(10): + tmp = fluid.dygraph.base.to_variable(x) + tmp.stop_gradient=False + inputs2.append(tmp) + ret2 = fluid.layers.sums(inputs2) + loss2 = fluid.layers.reduce_sum(ret2) + loss2.backward() + print(loss2.gradient()) + loss2.clear_gradient() + print("After clear {}".format(loss2.gradient())) + + """ + pass + + @fake_interface_only + def register_hook(self, hook): + pass + + def __str__(self): + return self._to_readable_code() + + def _to_readable_code(self): + """ + Get readable debug string of Variable. + + .. note:: + If you want to get the debug string in protobuf format, + please use :code:`to_string` method. + + Returns: + string: The formatted Variable string. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + cur_program = static.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print(new_variable._to_readable_code()) + """ + # VarType.LOD_TENSOR -> LOD_TENSOR + type_str = str(self.type).split('.')[1] + if ( + self.type == core.VarDesc.VarType.SELECTED_ROWS + or self.type == core.VarDesc.VarType.LOD_TENSOR + ): + dtype_str = str(self.dtype).split('.')[1] + var_str = "{name} : {type}.shape{shape}.dtype({dtype}).stop_gradient({stop_gradient})".format( + name=self.name, + type=type_str, + shape=self.shape, + dtype=dtype_str, + stop_gradient=self.stop_gradient, + ) + else: + var_str = "{name} : {type})".format(name=self.name, type=type_str) + + if self.is_parameter: + if self.trainable: + var_str = "trainable param " + var_str + else: + var_str = "param " + var_str + else: + var_str = "var " + var_str + + if self.persistable: + var_str = "persist " + var_str + + from paddle.distributed.auto_parallel.dist_context import ( + get_default_distributed_context, + ) + + dist_context = get_default_distributed_context() + dist_tensor = dist_context.get_dist_tensor_for_program(self) + if dist_tensor is not None: + var_str += ", {name} = {value}".format( + name="dist_attr", value=dist_tensor + ) + + return var_str + + def to_string(self, throw_on_error, with_details=False): + """ + Get debug string. + + Args: + + throw_on_error (bool): True if raise an exception when self is not initialized. + + with_details (bool): more details about variables and parameters (e.g. trainable, optimize_attr, ...) will be printed when with_details is True. Default value is False; + + Returns: + str: The debug string. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print(new_variable.to_string(True)) + print("=============with detail===============") + print(new_variable.to_string(True, True)) + """ + assert isinstance(throw_on_error, bool) and isinstance( + with_details, bool + ) + protostr = self.desc.serialize_to_string() + proto = framework_pb2.VarDesc.FromString(six.binary_type(protostr)) + res_str = _debug_string_(proto, throw_on_error) + if with_details: + additional_attr = ("error_clip",) + for attr_name in additional_attr: + res_str += "%s: %s\n" % ( + attr_name, + cpt.to_text(getattr(self, attr_name)), + ) + + return res_str + + __repr__ = __str__ + + def element_size(self): + """ + Returns the size in bytes of an element in the Tensor. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x1', shape=[3, 2], dtype='bool') + x.element_size() # 1 + + x = paddle.static.data(name='x2', shape=[3, 2], dtype='int16') + x.element_size() # 2 + + x = paddle.static.data(name='x3', shape=[3, 2], dtype='float16') + x.element_size() # 2 + + x = paddle.static.data(name='x4', shape=[3, 2], dtype='float32') + x.element_size() # 4 + + x = paddle.static.data(name='x5', shape=[3, 2], dtype='float64') + x.element_size() # 8 + """ + return self.desc.element_size() + + @property + def stop_gradient(self): + """ + Indicating if we stop gradient from current Variable + + **Notes: This Property has default value as** ``True`` **in** `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ **mode, while Parameter's default value is False. However, in Static Graph Mode all Variable's default stop_gradient value is** ``False`` + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + value0 = np.arange(26).reshape(2, 13).astype("float32") + value1 = np.arange(6).reshape(2, 3).astype("float32") + value2 = np.arange(10).reshape(2, 5).astype("float32") + linear = fluid.Linear(13, 5, dtype="float32") + linear2 = fluid.Linear(3, 3, dtype="float32") + a = fluid.dygraph.to_variable(value0) + b = fluid.dygraph.to_variable(value1) + c = fluid.dygraph.to_variable(value2) + out1 = linear(a) + out2 = linear2(b) + out1.stop_gradient = True + out = fluid.layers.concat(input=[out1, out2, c], axis=1) + out.backward() + + assert linear.weight.gradient() is None + assert (out1.gradient() == 0).all() + """ + return self.desc.stop_gradient() + + @stop_gradient.setter + def stop_gradient(self, s): + self.desc.set_stop_gradient(s) + + @property + def persistable(self): + """ + Indicating if we current Variable should be long-term alive + + + **Notes: This Property will be deprecated and this API is just to help user understand concept** + + **1. All Variable's persistable is** ``False`` **except Parameters.** + + **2. In** `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ **mode, this property should not be changed** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("persistable of current Var is: {}".format(new_variable.persistable)) + """ + return self.desc.persistable() + + @persistable.setter + def persistable(self, p): + self.desc.set_persistable(p) + + @property + def is_parameter(self): + """ + Indicating if current Variable is a Parameter + + Examples: + .. code-block:: python + + import paddle + new_parameter = paddle.static.create_parameter(name="X", + shape=[10, 23, 48], + dtype='float32') + if new_parameter.is_parameter: + print("Current var is a Parameter") + else: + print("Current var is not a Parameter") + + # Current var is a Parameter + """ + return self.desc.is_parameter() + + @is_parameter.setter + def is_parameter(self, p): + self.desc.set_is_parameter(p) + + @property + def name(self): + """ + Indicating name of current Variable + + **Notes: If it has two or more Varaible share the same name in the same** :ref:`api_guide_Block_en` **, it means these Variable will share content in no-** `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ **mode. This is how we achieve Parameter sharing** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("name of current Var is: {}".format(new_variable.name)) + """ + return cpt.to_text(self.desc.name()) + + @property + def grad_name(self): + """ + Indicating name of the gradient Variable of current Variable. + + **Notes: This is a read-only property. It simply returns name of + gradient Variable from a naming convention but doesn't guarantee + the gradient exists.** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data(name="x", shape=[-1, 23, 48], dtype='float32') + print(x.grad_name) # output is "x@GRAD" + + """ + return self.name + "@GRAD" + + @name.setter + def name(self, new_name): + self.desc.set_name(new_name) + + @property + def shape(self): + """ + Indicating shape of current Variable + + **Notes: This is a read-only property** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("shape of current Var is: {}".format(new_variable.shape)) + + """ + # convert to tuple, make it as same as numpy API. + return tuple(self.desc.shape()) + + @property + def dtype(self): + """ + Indicating data type of current Variable + + **Notes: This is a read-only property** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("Dtype of current Var is: {}".format(new_variable.dtype)) + """ + return self.desc.dtype() + + @property + def lod_level(self): + """ + Indicating ``LoD`` info of current Variable, please refer to :ref:`api_fluid_LoDTensor_en` to check the meaning + of ``LoD`` + + **Notes**: + + **1. This is a read-only property** + + **2. Don't support this property in** `Dygraph <../../user_guides/howto/dygraph/DyGraph.html>`_ **mode, it's value should be** ``0(int)`` + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("LoD Level of current Var is: {}".format(new_variable.lod_level)) + """ + if self.type == core.VarDesc.VarType.SELECTED_ROWS: + raise Exception("SelectedRows DO NOT supprt lod") + if self.type == core.VarDesc.VarType.STRINGS: + return None + return self.desc.lod_level() + + @property + def type(self): + """ + Indicating Type of current Variable + + **Notes: This is a read-only property** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_variable = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + print("Type of current Var is: {}".format(new_variable.type)) + """ + return self.desc.type() + + @property + def T(self): + """ + + Permute current Variable with its dimensions reversed. + + If `n` is the dimensions of `x` , `x.T` is equivalent to `x.transpose([n-1, n-2, ..., 0])`. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.ones(shape=[2, 3, 5]) + x_T = x.T + + exe = paddle.static.Executor() + x_T_np = exe.run(paddle.static.default_main_program(), fetch_list=[x_T])[0] + print(x_T_np.shape) + # (5, 3, 2) + + """ + if len(self.shape) == 1: + return self + perm = [] + for i in range(len(self.shape)): + perm.insert(0, i) + + out = self.block.create_var( + name=unique_name.generate_with_ignorable_key(self.name + '.tmp'), + dtype=self.dtype, + type=self.type, + persistable=False, + stop_gradient=False, + ) + input_shape = self.block.create_var( + name=unique_name.generate_with_ignorable_key(self.name + '.tmp'), + dtype=self.dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False, + ) + + self.block.append_op( + type='transpose2', + inputs={'X': [self]}, + outputs={'Out': [out], 'XShape': [input_shape]}, + attrs={'axis': perm}, + ) + return out + + def clone(self): + """ + Returns a new static Variable, which is the clone of the original static + Variable. It remains in the current graph, that is, the cloned Variable + provides gradient propagation. Calling ``out = tensor.clone()`` is same + as ``out = assign(tensor)`` . + + Returns: + Variable, The cloned Variable. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + # create a static Variable + x = paddle.static.data(name='x', shape=[3, 2, 1]) + # create a cloned Variable + y = x.clone() + + """ + output = self.block.create_var( + name=unique_name.generate_with_ignorable_key(self.name + "_clone"), + dtype=self.dtype, + type=self.type, + persistable=self.persistable, + stop_gradient=self.stop_gradient, + ) + + self.block.append_op( + type='assign', inputs={'X': [self]}, outputs={'Out': [output]} + ) + return output + + def _set_error_clip(self, error_clip): + """ + + Set the error_clip. + + Args: + error_clip(BaseErrorClipAttr) : The new error_clip. + + Returns: + None + + """ + self.error_clip = error_clip + + def _set_info(self, key, value): + """ + + Set key-value information for this variable. + + Args: + key(str): Key for this information. + value(object): The value associated to the key. + + Returns: + None + + """ + if not hasattr(self, "_info"): + self._info = {} + self._info[key] = value + + def _get_info(self, key): + """ + + Get the information of this variable corresponding to key. + + Args: + key(str): Key for this information. + + Returns: + object + + """ + if hasattr(self, "_info") and key in self._info: + return self._info[key] + return None + + def _slice_indices(self, slice, length): + """ + + Reference implementation for the slice.indices method. + + """ + # Compute step and length as integers. + step = 1 if slice.step is None else slice.step + + # Raise ValueError for negative length or zero step. + if length < 0: + raise ValueError("length should not be negative") + if step == 0: + raise ValueError("slice step can not be zero") + + # Find lower and upper bounds for start and stop. + lower = -1 if step < 0 else 0 + upper = length - 1 if step < 0 else length + + # Compute start. + if slice.start is None: + start = upper if step < 0 else lower + else: + start = slice.start + start = ( + max(start + length, lower) if start < 0 else min(start, upper) + ) + + # Compute stop. + if slice.stop is None: + stop = lower if step < 0 else upper + else: + stop = slice.stop + stop = max(stop + length, lower) if stop < 0 else min(stop, upper) + + return start, stop, step + + def _detectEllipsis(self, item): + has_ellipsis = False + start = 0 + end = len(self.shape) + for index, o in enumerate(item): + if o is Ellipsis: + if has_ellipsis: + raise ValueError("Index can have one ellipsis only.") + has_ellipsis = True + start = index + else: + if has_ellipsis: + end = index + return has_ellipsis, start, end + + def _reconstructSliceinfo(self, item): + has_ellipsis, start, end = self._detectEllipsis(item) + if has_ellipsis: + newitem = [] + for i in range(start): + newitem.append(item[i]) + for i in range(start, end): + newitem.append(slice(None, None, None)) + for i in range(end, len(item)): + newitem.append(item[i]) + return newitem + else: + return None + + def _detectContinuesSlice(self, item): + starts = [] + ends = [] + for index, o in enumerate(item): + if isinstance(o, int): + start = int(o) + if (index > 0 and index >= self.shape[index]) or ( + index < 0 and (index + self.shape[index]) < 0 + ): + raise IndexError("invalid index") + start = ( + max(start + self.shape[index], 0) + if start < 0 + else min(start, self.shape[index]) + ) + starts.append(start) + ends.append(start + 1) + elif isinstance(o, slice): + start, stop, step = self._slice_indices(o, self.shape[index]) + if step == 1 or step == -1: + starts.append(start) + ends.append(stop) + else: + return False, None + else: + raise IndexError("Valid index accept int or slice or ellipsis") + return True, [starts, ends] + + def _cloneVar(self, copy=False): + if not copy: + return self.block.create_var( + name=unique_name.generate_with_ignorable_key(self.name), + dtype=self.dtype, + ) + else: + return self + + def _sliceVar(self, axes, starts, ends): + new_var = self._cloneVar() + self.block.append_op( + type="slice", + inputs={'Input': [self]}, + outputs={'Out': [new_var]}, + attrs={'axes': axes, 'starts': starts, 'ends': ends}, + ) + return new_var + + def _concatVar(self, inputs, axis): + new_var = self._cloneVar() + self.block.append_op( + type="concat", + inputs={'X': inputs}, + outputs={'Out': [new_var]}, + attrs={ + 'axis': axis, + }, + ) + return new_var + + def _sliceAndConcatVar(self, item, axis): + if isinstance(item, slice): + if self.shape[axis] < 0: + return self._cloneVar(True) + start, stop, step = self._slice_indices(item, self.shape[axis]) + if step == 1: + return self._sliceVar([axis], [start], [stop]) + else: + vars = [] + if step > 0: + while start < stop: + vars.append( + self._sliceVar([axis], [start], [start + 1]) + ) + start += step + else: + while start > stop: + vars.append( + self._sliceVar([axis], [start], [start + 1]) + ) + start += step + return self._concatVar(vars, axis) + elif isinstance(item, int): + if self.shape[axis] < 0: + return self._cloneVar(True) + index = int(item) + if (index > 0 and index >= self.shape[axis]) or ( + index < 0 and (index + self.shape[axis]) < 0 + ): + raise IndexError("invalid index") + return self._sliceVar([axis], [index], [index + 1]) + else: + raise IndexError("Valid index accept int or slice or tuple") + + def __getitem__(self, item): + return _getitem_impl_(self, item) + + def __setitem__(self, item, value): + return _setitem_impl_(self, item, value) + + def get_value(self, scope=None): + """ + Get the value of variable in given scope. + + Args: + scope(Scope, optional) : If `scope` is None, it will be set to global scope + obtained through 'paddle.static.global_scope()'. Otherwise, use `scope`. + Default: None + + Returns: + Tensor, the value in given scope. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + import numpy as np + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + + y = static.nn.fc(x, 10, name='fc') + place = paddle.CPUPlace() + exe = static.Executor(place) + prog = paddle.static.default_main_program() + exe.run(static.default_startup_program()) + inputs = np.ones((10, 10), dtype='float32') + exe.run(prog, feed={'x': inputs}, fetch_list=[y, ]) + path = 'temp/tensor_' + for var in prog.list_vars(): + if var.persistable: + t = var.get_value() + paddle.save(t, path+var.name+'.pdtensor') + + for var in prog.list_vars(): + if var.persistable: + t_load = paddle.load(path+var.name+'.pdtensor') + var.set_value(t_load) + """ + # The 'framework' is a low-level module, and 'executor' + # can not be imported at the begainning of this file. + # Therefore, the above two modules are dynamically imported. + from .executor import global_scope + + if scope is not None and not isinstance(scope, core._Scope): + raise TypeError( + "`scope` should be None or `paddle.static.Scope` type, but received {}.".format( + type(scope) + ) + ) + + if scope is None: + scope = global_scope() + var_temp = scope.find_var(self.name) + if var_temp is None: + raise ValueError( + "Can not find Variable '{}' in the Scope.".format(self.name) + ) + t = var_temp.get_tensor() + return t + + def set_value(self, value, scope=None): + ''' + + Set the value to the tensor in given scope. + + Args: + value(Tensor/ndarray) : The value to be set. + scope(Scope, optional) : If `scope` is None, it will be set to global scope + obtained through 'paddle.static.global_scope()'. Otherwise, use `scope`. + Default: None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + import numpy as np + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + + y = static.nn.fc(x, 10, name='fc') + place = paddle.CPUPlace() + exe = static.Executor(place) + prog = paddle.static.default_main_program() + exe.run(static.default_startup_program()) + inputs = np.ones((10, 10), dtype='float32') + exe.run(prog, feed={'x': inputs}, fetch_list=[y, ]) + path = 'temp/tensor_' + for var in prog.list_vars(): + if var.persistable: + t = var.get_value() + paddle.save(t, path+var.name+'.pdtensor') + + for var in prog.list_vars(): + if var.persistable: + t_load = paddle.load(path+var.name+'.pdtensor') + var.set_value(t_load) + + ''' + + # The 'framework' is a low-level module, and 'executor' + # can not be imported at the begainning of this file. + # Therefore, the above two modules are dynamically imported. + from .executor import global_scope + + if not (isinstance(value, np.ndarray) or hasattr(value, '__array__')): + raise TypeError( + "`value` should be `numpy.ndarray` or `LoDTensor`, but received {}.".format( + type(value) + ) + ) + + if scope is not None and not isinstance(scope, core._Scope): + raise TypeError( + "`scope` should be None or `paddle.static.Scope` type, but received {}.".format( + type(scope) + ) + ) + + if scope is None: + scope = global_scope() + + var_temp = scope.find_var(self.name) + if var_temp is None: + raise ValueError( + "Can not find Variable '{}' in the Scope.".format(self.name) + ) + + t = var_temp.get_tensor() + + if hasattr(value, 'shape'): + if isinstance(value.shape, (MethodType, FunctionType)): + value_shape = value.shape() + else: + value_shape = value.shape + if list(t.shape()) != list(value_shape): + raise ValueError( + "{} expected a shape {}, but the received shape is {}.".format( + self.name, list(t.shape()), list(value_shape) + ) + ) + + p = t._place() + if p.is_cpu_place(): + place = core.CPUPlace() + elif p.is_cuda_pinned_place(): + place = core.CUDAPinnedPlace() + elif p.is_xpu_place(): + p = core.Place() + p.set_place(t._place()) + place = core.XPUPlace(p.xpu_device_id()) + elif p.is_npu_place(): + p = core.Place() + p.set_place(t._place()) + place = core.NPUPlace(p.npu_device_id()) + elif p.is_mlu_place(): + p = core.Place() + p.set_place(t._place()) + place = core.MLUPlace(p.mlu_device_id()) + else: + p = core.Place() + p.set_place(t._place()) + place = core.CUDAPlace(p.gpu_device_id()) + + t.set(value, place) + + def size(self): + """ + + Returns the number of elements for current Variable, which is a int64 Variable with shape [1] + + Returns: + Variable, the number of elements for current Variable + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + # create a static Variable + x = paddle.static.data(name='x', shape=[3, 2, 1]) + + # get the number of elements of the Variable + y = x.size() + + """ + + output = self.block.create_var( + name=unique_name.generate_with_ignorable_key(self.name + "_size"), + dtype=core.VarDesc.VarType.INT64, + ) + + self.block.append_op( + type='size', inputs={'Input': [self]}, outputs={'Out': [output]} + ) + return output + + def _set_attr(self, name, val): + """ + + Set the value of attribute by attribute's name. + + Args: + name(str): the attribute name. + val(int|str|list): the value of the attribute. + + """ + self._update_desc_attr(name, val) + + def _has_attr(self, name): + """ + + Whether this Variable has the attribute with the name `name` or not. + + Args: + name(str): the attribute name. + + Returns: + bool, True if has this attribute. + + """ + return self.desc.has_attr(name) + + def _remove_attr(self, name): + self.desc.remove_attr(name) + + def _update_desc_attr(self, name, val): + """ + Update the value of desc's attribute by attribute's name. + + Args: + name(str): the attribute name. + val(int|str|list): the value of the attribute. + """ + self.desc._set_attr(name, val) + + @property + def attr_names(self): + """Get the names of all attributes defined.""" + return self.desc.attr_names() + + def _get_attr(self, name): + """ + Get the attribute by name. + + Args: + name(str): the attribute name. + + Returns: + int|str|list, The attribute value. The return value + can be any valid attribute type. + """ + return self.desc.attr(name) + + @property + def dist_attr(self): + """ + Get distributed attribute of this Variable. + """ + return self.desc.dist_attr + + @dist_attr.setter + def dist_attr(self, dist_attr): + """ + Set distributed attribute of this Variable. + """ + self.desc.dist_attr = dist_attr + + +def get_all_op_protos(): + """ + Get all registered op proto from PaddlePaddle C++ end. + + Returns: + list: list of OpProto. + """ + protostrs = core.get_all_op_protos() + ret_values = [] + for pbstr in protostrs: + op_proto = framework_pb2.OpProto.FromString(six.binary_type(pbstr)) + ret_values.append(op_proto) + return ret_values + + +class OpProtoHolder(object): + """ + A global variable to hold all OpProtos from C++ as a map + """ + + @classmethod + def instance(cls): + if not hasattr(cls, '_instance'): + cls._instance = cls() + return cls._instance + + def __init__(self): + assert not hasattr( + self.__class__, '_instance' + ), 'Please use `instance()` to get OpProtoHolder object!' + op_protos = get_all_op_protos() + self.op_proto_map = {} + for proto in op_protos: + self.op_proto_map[proto.type] = proto + + def get_op_proto(self, type): + """ + Get OpProto by a type string. + Args: + type(str): The type that operator registered in C++ side. + + Returns(framework_pb2.OpProto): The OpProto + + """ + if type not in self.op_proto_map: + raise ValueError("Operator \"%s\" has not been registered." % type) + return self.op_proto_map[type] + + def update_op_proto(self): + op_protos = get_all_op_protos() + custom_op_names = [] + for proto in op_protos: + if proto.type not in self.op_proto_map: + self.op_proto_map[proto.type] = proto + custom_op_names.append(proto.type) + + return custom_op_names + + @staticmethod + def generated_op_attr_names(): + return { + core.op_proto_and_checker_maker.kOpRoleAttrName(), + core.op_proto_and_checker_maker.kOpRoleVarAttrName(), + core.op_proto_and_checker_maker.kOpNameScopeAttrName(), + core.op_proto_and_checker_maker.kOpCreationCallstackAttrName(), + core.op_proto_and_checker_maker.kOpDeviceAttrName(), + } + + +class Operator(object): + """ + In Fluid, all the operation are represented by Operator, and Operator + is regarded as a build in an instruction of a Block. Users can use the + build in instructions to describe their neural network. + + Args: + block(Block): The block has the current operator. + desc(core.OpDesc): The protobuf description of Operator. + type(str): The type of operator. Default None. + inputs(dict): The input of this Operator. it is a dictionary, for every + element, key is the input parameter name, and value is a list of + variables. Default None. + outputs(dict): The output of this Operator. it is a dictionary, for + every element, key is the input parameter name, and value is a list + of variables. Default None. + attrs(dict): The attributes of this Operator. it is a dictionary, for + every element, key is attribute name, and value is the attribute value. + The attribute type should be as same as the type registered in C++ side. + Default None. + + Returns: + Operator: The initialized Operator. + + Raises: + ValueError: If the passed input, output and attrs doesn't match the + initializing Operator's that registered in C++ side. + + Notes: + The constructor of operator should not be invoked directly. Use + Block.append_op or Block._prepend_op instead. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cur_program = fluid.Program() + cur_block = cur_program.current_block() + # var1 += var2 + var3 + cur_block.append_op(type="sum", + inputs={"X": [var1, var2, var3]}, + outputs={"Out": [var1]}) + """ + + OP_WITHOUT_KERNEL_SET = { + 'feed', + 'fetch', + 'recurrent', + 'go', + 'rnn_memory_helper_grad', + 'conditional_block', + 'while', + 'send', + 'recv', + 'listen_and_serv', + 'fl_listen_and_serv', + 'ncclInit', + 'select', + 'checkpoint_notify', + 'gen_bkcl_id', + 'c_gen_bkcl_id', + 'gen_nccl_id', + 'c_gen_nccl_id', + 'c_comm_init', + 'c_sync_calc_stream', + 'c_sync_comm_stream', + 'queue_generator', + 'dequeue', + 'enqueue', + 'heter_listen_and_serv', + 'c_wait_comm', + 'c_wait_compute', + 'c_gen_hccl_id', + 'c_comm_init_hccl', + 'copy_cross_scope', + 'c_gen_cncl_id', + } + + def __init__( + self, block, desc, type=None, inputs=None, outputs=None, attrs=None + ): + # read attr type index from op proto to avoid unexpected type + # conversions, e.g. narrowing conversion like double to float + try: + proto = OpProtoHolder.instance().get_op_proto(type) + self._attr_types = {} + for attr in proto.attrs: + self._attr_types[attr.name] = attr.type + except ValueError: + pass + + if _non_static_mode(): + if type is None: + raise ValueError( + "`type` to initialized an Operator can not be None." + ) + self._type = type + self.attrs = attrs if attrs else {} + else: + self.block = block + self.desc = desc + # note: not add self.attrs here: + # https://github.com/PaddlePaddle/Paddle/pull/12583#pullrequestreview-145093173 + op_attrs = attrs + if op_attrs is None: + op_attrs = dict() + del attrs + + # attr for static mode cuda graph + self._cuda_graph_attr = _current_cuda_graph_mode + + op_maker = core.op_proto_and_checker_maker + + if op_maker.kOpRoleAttrName() not in op_attrs: + op_attrs[ + op_maker.kOpRoleAttrName() + ] = self.block.program._op_role + + role_var_name = op_maker.kOpRoleVarAttrName() + if ( + len(self.block.program._op_role_var) != 0 + and role_var_name not in op_attrs + ): + op_attrs[role_var_name] = self.block.program._op_role_var + + if role_var_name in op_attrs and len(op_attrs[role_var_name]) == 0: + del op_attrs[role_var_name] + + if len(self.desc.type()) != 0: + # NOTE(Aurelius84): prog.clone() will lead that var.op is always None, + # we add this to fix the problem. + for arg in self.desc.output_arg_names(): + if block.has_var(arg) and block.var(arg).op is None: + block.var(arg).op = self + return + if type is None: + raise ValueError( + "`type` to initialized an Operator can not be None." + ) + else: + callstack_var_name = op_maker.kOpCreationCallstackAttrName() + op_attrs[callstack_var_name] = [] + for frame in traceback.extract_stack(): + op_attrs[callstack_var_name].append( + ' File "{}", line {}, in {}'.format( + frame[0], frame[1], frame[2] + ) + ) + op_attrs[callstack_var_name].append( + ' {}'.format(frame[3]) + ) + + self.desc.set_type(type) + proto = OpProtoHolder.instance().get_op_proto(type) + + namescope_var_name = op_maker.kOpNameScopeAttrName() + op_attrs[namescope_var_name] = _full_name_scope() + + # set device for op with kernels, give warning for op without kernels + # when force_cpu and device_guard are used at the same time, a warning will be given. + # TODO(zhangting2020): when force_cpu is removed, clear warning below. + if _current_device is not None: + if self._has_kernel(type): + op_device = op_maker.kOpDeviceAttrName() + op_attrs[op_device] = _current_device + else: + warnings.warn( + "The Op(%s) is not support to set device." % type + ) + if 'force_cpu' in op_attrs: + if ( + type == 'less_than' and op_attrs['force_cpu'] != None + ) or op_attrs['force_cpu'] != False: + warnings.warn( + "The Attr(force_cpu) of Op(%s) will be deprecated in the future, " + "please use 'device_guard' instead. 'device_guard' has higher priority when they are " + "used at the same time." % type + ) + if _current_pipeline_stage is not None: + pipeline_attr_name = ( + 'pipeline_stage' + core.kAutoParallelSuffix() + ) + self._update_desc_attr( + pipeline_attr_name, _current_pipeline_stage + ) + + def find_name(var_list, name): + for var_name in var_list: + if var_list[var_name] is not None and var_name == name: + return True + return False + + if inputs is not None: + for in_proto in proto.inputs: + found = find_name(inputs, in_proto.name) + assert ( + found or in_proto.dispensable + ), "Input {} not found".format(in_proto.name) + if found: + in_args = inputs[in_proto.name] + if not isinstance(in_args, (list, tuple)): + in_args = [in_args] + if not in_proto.duplicable and len(in_args) > 1: + raise ValueError( + "Input %s expects only one input, but %d are given." + % (in_proto.name, len(in_args)) + ) + in_arg_names = [] + for index, arg in enumerate(in_args): + if isinstance(arg, six.string_types): + in_arg_names.append(arg) + elif isinstance(arg, six.binary_type): + in_arg_names.append(arg.decode()) + elif isinstance(arg, (Variable, core.VarBase)): + in_arg_names.append(cpt.to_text(arg.name)) + else: + raise TypeError( + "The type of '%s' in operator %s should be " + "one of [basestring(), str, Varibale] in python2, " + "or one of [str, bytes, Variable] in python3." + "but received : %s" + % (in_proto.name, type, arg) + ) + self.desc.set_input(in_proto.name, in_arg_names) + else: + self.desc.set_input(in_proto.name, []) + + if outputs is not None: + for m in proto.outputs: + if (m.name not in outputs) and m.dispensable: + continue + if not ((m.name in outputs) or m.dispensable): + raise ValueError( + ( + "Incorrect setting for output(s) of " + "operator \"%s\", should set: [%s]." + ) + % (type, m.name) + ) + for out_proto in proto.outputs: + if out_proto.name not in outputs: + continue + out_args = outputs[out_proto.name] + if not isinstance(out_args, list): + out_args = [out_args] + if not out_proto.duplicable and len(out_args) > 1: + raise ValueError( + "Output %s expects only one output, but %d are given." + % (out_proto.name, len(out_args)) + ) + out_arg_names = [] + for arg in out_args: + if isinstance(arg, six.string_types): + out_arg_names.append(arg) + else: + out_arg_names.append(cpt.to_text(arg.name)) + # TODO(minqiyang): could we remove variable's op in static mode? + if not _non_static_mode(): + if isinstance(arg, six.string_types): + block.var(arg).op = self + else: + arg.op = self + self.desc.set_output(out_proto.name, out_arg_names) + + extra_attrs_map = core.get_op_extra_attrs(type) + if op_attrs is not None: + if not isinstance(op_attrs, dict): + raise TypeError("'attrs' should be a dict.") + for attr in proto.attrs: + attr_name = attr.name + if (attr_name not in op_attrs) or ( + op_attrs[attr_name] is None + ): + continue + attr_val = op_attrs[attr_name] + self._update_desc_attr(attr_name, attr_val) + for attr_name in extra_attrs_map.keys(): + if (attr_name not in op_attrs) or ( + op_attrs[attr_name] is None + ): + self._update_desc_attr( + attr_name, extra_attrs_map[attr_name] + ) + else: + self._update_desc_attr(attr_name, op_attrs[attr_name]) + + # proto.attrs doesn't include ipu_index + if core.is_compiled_with_ipu(): + if global_ipu_index >= 0: + self._update_desc_attr( + ipu_index_attr_name, global_ipu_index + ) + if global_ipu_stage >= 0: + self._update_desc_attr( + ipu_stage_attr_name, global_ipu_stage + ) + + self.desc.check_attrs() + if self._has_kernel(type): + self.desc.infer_var_type(self.block.desc) + self.desc.infer_shape(self.block.desc) + + def _has_kernel(self, op_type): + return op_type not in self.OP_WITHOUT_KERNEL_SET + + def to_string(self, throw_on_error): + """ + Get debug string. + + Args: + throw_on_error(bool): Whether to raise exception if self is not + initialized. + + Returns: + str: The debug string. + + """ + protostr = self.desc.serialize_to_string() + proto = framework_pb2.OpDesc.FromString(six.binary_type(protostr)) + return _debug_string_(proto, throw_on_error) + + def _to_readable_code(self, skip_op_callstack=True): + """ + Get readable debug string of Operator. + + .. note:: + If you want to get the debug string in protobuf format, + please use :code:`to_string` method. + + Args: + skip_op_callstack(bool): whether to skip parsing Operator's attribute + op_callstack, default value is True + + Returns: + string: The formatted Operator string. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + cur_program = fluid.Program() + cur_block = cur_program.current_block() + var = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + new_op = cur_block.append_op(type="abs", + inputs={"X": [var]}, + outputs={"Out": [var]}) + print(new_op._to_readable_code()) + """ + assert isinstance( + skip_op_callstack, bool + ), "skip_op_callstack parameter's type is error, expect bool, received {}".format( + type(skip_op_callstack) + ) + outputs_str = "{" + for i in range(0, len(self.output_names)): + outputs_str += "{name}=".format(name=self.output_names[i]) + o = self.output(self.output_names[i]) + outputs_str += "{value}".format(value=o) + if i != len(self.output_names) - 1: + outputs_str += ", " + outputs_str += "}" + + inputs_str = "{" + for i in range(0, len(self.input_names)): + inputs_str += "{name}=".format(name=self.input_names[i]) + o = self.input(self.input_names[i]) + inputs_str += "{value}".format(value=o) + + if i != len(self.input_names) - 1: + inputs_str += ", " + inputs_str += "}" + + attr_names = sorted(self.attr_names) + attrs_str = "" + for i in range(0, len(attr_names)): + name = attr_names[i] + if skip_op_callstack and name == "op_callstack": + continue + + attr_type = self.desc.attr_type(name, True) + if attr_type == core.AttrType.VAR: + attr_var_name = self.desc.attr(name, True).name() + a = "{name} = Var['{value}']".format( + name=name, type=attr_type, value=attr_var_name + ) + attrs_str += a + if i != len(attr_names) - 1: + attrs_str += ", " + continue + + if attr_type == core.AttrType.VARS: + attr_var_names = [ + "'%s'" % var.name() for var in self.desc.attr(name, True) + ] + a = "{name} = Vars[{value}]".format( + name=name, type=attr_type, value=','.join(attr_var_names) + ) + attrs_str += a + if i != len(attr_names) - 1: + attrs_str += ", " + continue + + if attr_type == core.AttrType.BLOCK: + a = "{name} = block[{value}]".format( + name=name, type=attr_type, value=self._block_attr_id(name) + ) + attrs_str += a + if i != len(attr_names) - 1: + attrs_str += ", " + continue + + if attr_type == core.AttrType.BLOCKS: + a = "{name} = blocks{value}".format( + name=name, type=attr_type, value=self._blocks_attr_ids(name) + ) + attrs_str += a + if i != len(attr_names) - 1: + attrs_str += ", " + continue + + # it is bytes of serialized protobuf + if ( + is_compiled_with_cinn() + and self.type == 'cinn_launch' + and name == 'compilation_key' + ): + key = self.desc.attr(name) + v = core.get_serialize_comile_key(key) + prog = Program() + prog = prog.parse_from_string(v) + s = prog._to_readable_code() + lines = s.split('\n') + value = '\n'.join([' ' + line for line in lines]) + value = '\n' + value + else: + value = self.desc.attr(name) + + a = "{name} = {value}".format( + name=name, type=attr_type, value=value + ) + + attrs_str += a + if i != len(attr_names) - 1: + attrs_str += ", " + + from paddle.distributed.auto_parallel.dist_context import ( + get_default_distributed_context, + ) + + dist_context = get_default_distributed_context() + dist_op = dist_context.get_dist_op_for_program(self) + if dist_op is not None: + attrs_str += ", {name} = {value}".format( + name="dist_attr", value=dist_op + ) + + if outputs_str != "{}": + op_str = "{outputs} = {op_type}(inputs={inputs}, {attrs})".format( + outputs=outputs_str, + op_type=self.type, + inputs=inputs_str, + attrs=attrs_str, + ) + else: + op_str = "{op_type}(inputs={inputs}, {attrs})".format( + op_type=self.type, inputs=inputs_str, attrs=attrs_str + ) + return op_str + + def __str__(self): + return self._to_readable_code() + + __repr__ = __str__ + + @property + def type(self): + return self.desc.type() + + def input(self, name): + r""" + + Get the input arguments according to the input parameter name. + + Args: + name(str): The input parameter name. + + Returns: + list, return the list of argument names that associated with \ + the specific parameter name. + + """ + return self.desc.input(name) + + def _rename_input(self, old_name, new_name): + """ + Rename the `old_name` to `new_name`. + + Args: + old_name(str): The old name of the Operator's input. + new_name(str): The new name of the Operator's input. + + Returns: + None + """ + self.desc._rename_input(old_name, new_name) + + def _rename_output(self, old_name, new_name): + """ + Rename the `old_name` to `new_name`. + + Args: + old_name(str): The old name of the Operator's output. + new_name(str): The new name of the Operator's output. + + Returns: + None + """ + self.desc._rename_output(old_name, new_name) + + @property + def input_names(self): + return self.desc.input_names() + + @property + def input_arg_names(self): + return self.desc.input_arg_names() + + @property + def output_arg_names(self): + return self.desc.output_arg_names() + + def output(self, name): + r""" + Get output arguments by the output parameter name. + + Args: + name(str): The output parameter name. + + Returns: + list: return the list of argument names associated with \ + the specific parameter name. + """ + return self.desc.output(name) + + @property + def output_names(self): + return self.desc.output_names() + + @property + def idx(self): + for i, op in enumerate(self.block.ops): + if op == self: + return i + raise ValueError( + "Can't find op itself in it's block. It could be a bug of Paddle." + ) + + def has_attr(self, name): + """ + Whether this Operator has the attribute with name or not. + + Args: + name(str): the attribute name. + + Returns: + bool: True if has this attribute. + + """ + return self.desc.has_attr(name) + + def attr_type(self, name): + """ + Get the type of attribute by attribute's name. + + Args: + name(str): the attribute name. + + Returns: + core.AttrType: the attribute type. + """ + return self.desc.attr_type(name, True) + + def _set_attr(self, name, val): + """ + Set the value of attribute by attribute's name. + + Args: + name(str): the attribute name. + val(bool|int|str|float|list): the value of the attribute. + + Raises: + ValueError: If the type of value doesn't match with desc.attr_type(name). + """ + self._update_desc_attr(name, val) + + def _remove_attr(self, name): + self.desc.remove_attr(name) + + def _update_desc_attr(self, name, val): + """ + Update the value of desc's attribute by attribute's name. + + Args: + name(str): the attribute name. + val(bool|int|str|float|list): the value of the attribute. + + Raises: + ValueError: If the type of value doesn't match with desc.attr_type(name). + """ + if isinstance(val, Variable): + self.desc.set_var_attr(name, val.desc) + elif isinstance(val, list) and _all_is_type(val, Variable): + self.desc.set_vars_attr(name, [v.desc for v in val]) + elif isinstance(val, Block): + self.desc.set_block_attr(name, val.desc) + elif isinstance(val, list) and val and _all_is_type(val, Block): + self.desc.set_blocks_attr(name, [v.desc for v in val]) + elif isinstance(val, core.BlockDesc) or isinstance( + val, core.ProgramDesc + ): + self.desc.set_serialized_attr(name, val.serialize_to_string()) + else: + self._update_desc_plain_attr(name, val) + + def _update_desc_plain_attr(self, name, val): + desc = self.desc + if not hasattr(self, "_attr_types") or (name not in self._attr_types): + desc._set_attr(name, val) + return + + type_index = self._attr_types[name] + if type_index == core.AttrType.BOOL: + desc._set_bool_attr(name, val) + elif type_index == core.AttrType.INT: + desc._set_int32_attr(name, val) + elif type_index == core.AttrType.LONG: + desc._set_int64_attr(name, val) + elif type_index == core.AttrType.FLOAT: + desc._set_float32_attr(name, val) + # elif type_index == core.AttrType.FLOAT64: + # desc._set_float64_attr(name, val) + elif type_index == core.AttrType.STRING: + desc._set_str_attr(name, val) + elif type_index == core.AttrType.BOOLS: + desc._set_bools_attr(name, val) + elif type_index == core.AttrType.INTS: + desc._set_int32s_attr(name, val) + elif type_index == core.AttrType.LONGS: + desc._set_int64s_attr(name, val) + elif type_index == core.AttrType.FLOATS: + desc._set_float32s_attr(name, val) + elif type_index == core.AttrType.FLOAT64S: + desc._set_float64s_attr(name, val) + elif type_index == core.AttrType.STRINGS: + desc._set_strs_attr(name, val) + else: + # defaults to old methods + desc._set_attr(name, val) + + @property + def attr_names(self): + return self.desc.attr_names(True) + + def attr(self, name): + """ + Get the attribute by name. + + Args: + name(str): the attribute name. + + Returns: + bool|int|str|float|list: The attribute value. The return value + can be any valid attribute type. + """ + return self.desc.attr(name) + + def _block_attr_id(self, name): + """ + Get the block attribute's id by name. + + Args: + name(str): the attribute name. + + Returns: + int: the block index. + """ + return self.desc._block_attr_id(name) + + def _block_attr(self, name): + """ + Get the block attribute by name. + + Args: + name(str): the attribute name. + + Returns: + block: the block attribute. + """ + + id = self._block_attr_id(name) + assert id >= 0 and id < len(self.block.program.blocks) + return self.block.program.blocks[id] + + def _blocks_attr(self, name): + """ + Get the blocks attribute by name. + + Args: + name(str): the attribute name. + + Returns: + list: list of the blocks attribute. + """ + attrs = [] + for i in self._blocks_attr_ids(name): + assert i >= 0 and i < len(self.block.program.blocks) + attrs.append(self.block.program.blocks[i]) + + return attrs + + def _blocks_attr_ids(self, name): + """ + Get the blocks attribute's ids by name. + + Args: + name(str): the attribute name. + + Returns: + list: list of the blocks ids. + """ + + return self.desc._blocks_attr_ids(name) + + def _var_attr(self, name): + """ + Get the Variable attribute by name. + + Args: + name(str): the attribute name. + + Returns: + Variable: the Variable attribute. + """ + attr_type = self.desc.attr_type(name, True) + assert ( + attr_type == core.AttrType.VAR + ), "Required type attr({}) is Variable, but received {}".format( + name, attr_type + ) + attr_var_name = self.desc.attr(name, True).name() + return self.block._var_recursive(attr_var_name) + + def _vars_attr(self, name): + """ + Get the Variables attribute by name. + + Args: + name(str): the attribute name. + + Returns: + Variables: the Variables attribute. + """ + attr_type = self.desc.attr_type(name, True) + assert ( + attr_type == core.AttrType.VARS + ), "Required type attr({}) is list[Variable], but received {}".format( + name, attr_type + ) + attr_vars = [ + self.block._var_recursive(var.name()) + for var in self.desc.attr(name, True) + ] + return attr_vars + + def all_attrs(self): + """ + Get the attribute dict. + + Returns: + dict: The Operator's attribute dict, name->attr. + """ + attr_names = self.attr_names + attr_map = {} + for n in attr_names: + attr_type = self.desc.attr_type(n, True) + if attr_type == core.AttrType.BLOCK: + attr_map[n] = self._block_attr(n) + elif attr_type == core.AttrType.BLOCKS: + attr_map[n] = self._blocks_attr(n) + elif attr_type == core.AttrType.VAR: + attr_map[n] = self._var_attr(n) + elif attr_type == core.AttrType.VARS: + attr_map[n] = self._vars_attr(n) + else: + attr_map[n] = self.attr(n) + + return attr_map + + def _is_optimize_op(self): + op_maker = core.op_proto_and_checker_maker + OPTIMIZE = core.op_proto_and_checker_maker.OpRole.Optimize + + if not self.desc.has_attr(op_maker.kOpRoleAttrName()): + return False + + op_role = self.desc.attr(op_maker.kOpRoleAttrName()) + if op_role & int(OPTIMIZE): + return True + + return False + + def _is_backward_op(self): + op_maker = core.op_proto_and_checker_maker + BACKWARD = core.op_proto_and_checker_maker.OpRole.Backward + + if not self.desc.has_attr(op_maker.kOpRoleAttrName()): + return False + + op_role = self.desc.attr(op_maker.kOpRoleAttrName()) + if op_role & int(BACKWARD): + return True + + return False + + @property + def dist_attr(self): + """ + Get distributed attribute of this Variable. + """ + return self.desc.dist_attr + + @dist_attr.setter + def dist_attr(self, dist_attr): + """ + Set distributed attribute of this Variable. + """ + self.desc.dist_attr = dist_attr + + +class Block(object): + """ + In Fluid, a Program is consistence of multi-Block, and Block stores + VarDesc and OpDesc. In a specific Block, a VarDesc have a unique name. + One block could have some child blocks, and child block's name scopes + should inherit the parent's so that OpDesc in child block can reference + a VarDesc that is stored in the parent block. + Please reference the framework.proto for details. + + Args: + program(Program): The Program that the Block belongs to. + idx(int): The block's id in the Program. + + Notes: + The constructor of Block should not be invoked directly. Please + use `Program._create_block()` to create a block. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + cur_program = fluid.Program() + cur_block = cur_program.current_block() + var = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + cur_block.append_op(type="abs", + inputs={"X": [var]}, + outputs={"Out": [var]}) + """ + + def __init__(self, program, idx): + self.desc = program.desc.block(idx) + self.vars = collections.OrderedDict() # var_name --> var + self.ops = list() # operator list + self.program = program + self.removed_vars = collections.OrderedDict() + + def __str__(self): + return self._to_readable_code() + + def _to_readable_code(self, skip_op_callstack=True): + """ + Get readable debug string of Block. + + .. note:: + If you want to get the debug string in protobuf format, + please use :code:`to_string` method. + + Args: + skip_op_callstack(bool): whether to skip parsing Operator's attribute + op_callstack, default value is True + + Returns: + string: The formatted Block string. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + cur_program = fluid.Program() + cur_block = cur_program.current_block() + new_var = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + new_op = cur_block.append_op(type="abs", + inputs={"X": [new_var]}, + outputs={"Out": [new_var]}) + print(cur_block._to_readable_code()) + """ + assert isinstance( + skip_op_callstack, bool + ), "skip_op_callstack parameter's type is error, expect bool, received {}".format( + type(skip_op_callstack) + ) + block_str = "{ // block " + block_str += "{}\n".format(self.idx) + for var in list(self.vars.values()): + block_str += " {}\n".format(var._to_readable_code()) + block_str += "\n" + for op in self.ops: + block_str += " {}\n".format( + op._to_readable_code(skip_op_callstack) + ) + block_str += "}" + return block_str + + def to_string(self, throw_on_error, with_details=False): + """ + Get debug string. + + Args: + throw_on_error(bool): raise exception when self is not initialized + when throw_on_error is True. + with_details(bool): more details about variables and parameters + (e.g. trainable, optimize_attr, ...) will be printed when + with_details is True. Default False. + + Returns: + str: The debug string. + """ + assert isinstance(throw_on_error, bool) and isinstance( + with_details, bool + ) + if with_details: + re_add_indent = re.compile(r"\n(.)") + res_str = "blocks {\n idx: %d\n parent_idx: %d" % ( + self.idx, + self.parent_idx, + ) + for var in list(self.vars.values()): + res_str += "\n vars {\n %s }" % re_add_indent.sub( + r"\n \1", var.to_string(throw_on_error, with_details) + ) + for op in self.ops: + res_str += "\n ops {\n %s }" % re_add_indent.sub( + r"\n \1", op.to_string(throw_on_error) + ) + res_str += "\n}" + else: + protostr = self.desc.serialize_to_string() + proto = framework_pb2.BlockDesc.FromString( + six.binary_type(protostr) + ) + res_str = _debug_string_(proto, throw_on_error) + return res_str + + __repr__ = __str__ + + @property + def parent_idx(self): + return self.desc.parent + + @property + def forward_block_idx(self): + return self.desc.get_forward_block_idx() + + def _set_forward_block_idx(self, idx): + """ + Set the forward block Idx. + + Args: + idx(int): the block index. + + Returns: + None + """ + self.desc._set_forward_block_idx(idx) + + @property + def backward_block_idx(self): + cur_block_idx = self.idx + for block in self.program.blocks: + if block.forward_block_idx == cur_block_idx: + return block.idx + return -1 + + @property + def idx(self): + return self.desc.id + + def var(self, name): + """ + Get a Variable by name from this block. + + Args: + name(str): the Variable's name. + + Raises: + ValueError: The If input's type is not str, or this block + doesn't have a Variable with the giving name. + + Returns: + Variable: the Variable with the giving name. + """ + if not isinstance(name, six.string_types): + raise TypeError( + "var require string as parameter, but get %s instead." + % (type(name)) + ) + v = self.vars.get(name, None) + if v is None: + raise ValueError("var %s not in this block" % name) + return v + + def _find_var_recursive(self, name): + """ + Get a Variable by name from this block recursively. + + Args: + name(str): the Variable's name. + + Returns: + Variable: the Variable with the giving name. Or None if not found. + """ + frontier = list() + visited = set() + + frontier.append(self) + + prog = self.program + + while len(frontier) != 0: # BFS + cur = frontier[0] + frontier = frontier[1:] + + if id(cur) in visited: + continue + + if cur.has_var(name): + return cur.var(name) + + if cur.parent_idx != -1: + frontier.append(prog.block(cur.parent_idx)) + + if cur.forward_block_idx != -1: + frontier.append(prog.block(cur.forward_block_idx)) + + visited.add(id(cur)) + return None + + def _var_recursive(self, name): + """ + Get a Variable by name from this block recursively. + + Args: + name(str): the Variable's name. + + Raises: + ValueError: this block and this parent block doesn't + have a Variable with the giving name. + + Returns: + Variable: the Variable with the giving name. + """ + var = self._find_var_recursive(name) + if var: + return var + else: + raise ValueError("Var {0} is not found recursively".format(name)) + + def all_parameters(self): + return list(self.iter_parameters()) + + def iter_parameters(self): + return ( + item[1] + for item in six.iteritems(self.vars) + if isinstance(item[1], Parameter) + ) + + def create_var(self, *args, **kwargs): + if _non_static_mode(): + var = _varbase_creator(*args, **kwargs) + else: + var = Variable(block=self, *args, **kwargs) + if 'initializer' in kwargs: + kwargs['initializer'](var, self) + return var + + def has_var(self, name): + return name in self.vars + + def _rename_var(self, name, new_name): + """ + Rename variable in vars and ops' inputs and outputs + + Args: + name(str): the name that need to be renamed. + new_name(str): the name that need to rename to. + + Raises: + ValueError: If this block doesn't have this the giving name, + or the type of the var with the giving name is not Parameter + or Variable. + + Returns: + Variable: the Variable with the giving name. + """ + name = cpt.to_text(name) + new_name = cpt.to_text(new_name) + + if not self.has_var(name): + raise ValueError("var %s is not in current block" % name) + v = self.var(name) + if type(v) == Parameter: + var_type = "Parameter" + stop_gradient = v.stop_gradient + trainable = v.trainable + optimize_attr = v.optimize_attr + regularizer = v.regularizer + error_clip = v.error_clip + elif type(v) == Variable: + var_type = "Variable" + error_clip = v.error_clip + stop_gradient = v.stop_gradient + else: + raise ValueError("unsupported var type: %s", type(v)) + orig_var_type = v.type + self.desc._rename_var(cpt.to_bytes(name), cpt.to_bytes(new_name)) + # NOTE: v is destroyed by C++ after calling _rename_var. + d = self.desc.find_var(cpt.to_bytes(new_name)) + if var_type == "Parameter": + if in_dygraph_mode(): + var = EagerParamBase( + d.shape(), + d.dtype(), + type=orig_var_type, + name=new_name, + stop_gradient=stop_gradient, + trainable=trainable, + optimize_attr=optimize_attr, + regularizer=regularizer, + error_clip=error_clip, + ) + else: + if _in_legacy_dygraph(): + var = ParamBase( + d.shape(), + d.dtype(), + type=orig_var_type, + name=new_name, + stop_gradient=stop_gradient, + trainable=trainable, + optimize_attr=optimize_attr, + regularizer=regularizer, + error_clip=error_clip, + ) + else: + var = Parameter( + self, + d.shape(), + d.dtype(), + type=orig_var_type, + name=new_name, + stop_gradient=stop_gradient, + trainable=trainable, + optimize_attr=optimize_attr, + regularizer=regularizer, + error_clip=error_clip, + ) + elif var_type == "Variable": + var = Variable( + self, + type=orig_var_type, + name=new_name, + error_clip=error_clip, + stop_gradient=stop_gradient, + ) + + # rename the python side, _sync_with_cpp will only add + # new vars/ops to python side. + self.vars[new_name] = var + del self.vars[name] + self._sync_with_cpp() + return var + + def _remove_var(self, name, sync=True): + if sync == True: + self._sync_with_cpp() + self.desc._remove_var(cpt.to_bytes(name)) + del self.vars[name] + + def create_parameter(self, *args, **kwargs): + global_block = self.program.global_block() + param = None + if in_dygraph_mode(): + param = EagerParamBase(*args, **kwargs) + else: + if _in_legacy_dygraph(): + param = ParamBase(*args, **kwargs) + else: + param = Parameter(global_block, *args, **kwargs) + + if 'initializer' in kwargs: + + def _is_inited_by(block, var): + init_ops = [] + for op in block.ops: + if var.name in op.output_arg_names: + # In startup_program, "c_broadcast" and "c_sync_comm_stream" + # are treated as initialization ops that cause error. + # Think of "c_broadcast" and "c_sync_comm_stream" as a special case here. + # NOTE: "coalesce_tensor" is a special case for rnn with cudnn support + if op.type in [ + "c_broadcast", + "c_sync_comm_stream", + "coalesce_tensor", + ]: + continue + init_ops.append(op) + return init_ops + + initializer = kwargs['initializer'] + init_ops = _is_inited_by(global_block, param) + init_ops_len = len(init_ops) + if init_ops_len > 1: + raise RuntimeError( + "param " + + param.name + + " is inited by multiple init ops " + + str(init_ops) + ) + elif init_ops_len == 1: + # TODO already inited, do nothing, should log a warning + pass + else: + initializer(param, self) + return param + + def append_op(self, *args, **kwargs): + """ + Appends a new Operator according to the giving arguments. + + Returns: + Operator: the append Operator. + """ + if _non_static_mode(): + attrs = kwargs.get("attrs", {}) + inplace_map = kwargs.get("inplace_map", None) + type = kwargs.get("type", None) + warnings.warn( + "Op `%s` is executed through `append_op` under the dynamic mode, " + "the corresponding API implementation needs to be upgraded to " + "using `_C_ops` method." % type, + DeprecationWarning, + ) + op = Operator( + block=self, + desc=None, + type=type, + inputs=None, + outputs=None, + attrs=attrs, + ) + + # record ops in tracer rather than blocks + # + # TODO(minqiyang): add op stop_gradient support in static mode too. + # currently, we only support stop_gradient in dygraph mode. + + _dygraph_tracer().trace_op( + type, + kwargs.get("inputs", {}), + kwargs.get("outputs", {}), + attrs if attrs else {}, + kwargs.get("stop_gradient", False), + inplace_map, + ) + else: + from paddle.fluid.dygraph.base import param_guard + + op_desc = self.desc.append_op() + # NOTE(Aurelius84): In case of @to_static, all VarBase(s) should + # be converted into Variable(s) with same name and block location. + # This is ONE and ONLY logic of type transformation of dy2static. + inputs = kwargs.get("inputs", None) + outputs = kwargs.get("outputs", None) + with param_guard(inputs), param_guard(outputs): + op = Operator( + block=self, + desc=op_desc, + type=kwargs.get("type", None), + inputs=inputs, + outputs=outputs, + attrs=kwargs.get("attrs", None), + ) + + self.ops.append(op) + + return op + + def _insert_op(self, index, *args, **kwargs): + """ + Insert a Operator according to the giving arguments. + + Args: + index(int): the place that the operator to insert. + + Returns: + Operator: the insert Operator. + """ + self._sync_with_cpp() + return self._insert_op_without_sync(index, *args, **kwargs) + + def _insert_op_without_sync(self, index, *args, **kwargs): + """ + Insert an Operator according to the giving arguments, + without sync_with_cpp to meke the compilation faster. + + Args: + index(int): the place that the operator to insert. + + Returns: + Operator: the insert Operator. + """ + op_desc = self.desc._insert_op(index) + op = Operator(block=self, desc=op_desc, *args, **kwargs) + self.ops.insert(index, op) + return op + + def _remove_op(self, index, sync=True): + """ + Remove the specific position operator. + + Args: + index(int): the position that the operator to insert. + + Returns: + None + """ + if sync == True: + self._sync_with_cpp() + self.desc._remove_op(index, index + 1) + del self.ops[index] + + def _slice_ops(self, start, end): + """ + Return the Operator between start and end. + + Args: + start(int): the start position. + end(int): the end position. + + Returns: + list: the Operators between start and end. + """ + return self.ops[start:end] + + def _prepend_op(self, *args, **kwargs): + if _non_static_mode(): + type = kwargs.get("type", None) + attrs = kwargs.get("attrs", {}) + op = Operator( + self, None, type=type, inputs=None, outputs=None, attrs=attrs + ) + + _dygraph_tracer().trace_op( + type, + kwargs.get("inputs", {}), + kwargs.get("outputs", {}), + attrs if attrs else {}, + kwargs.get("stop_gradient", False), + ) + else: + op_desc = self.desc._prepend_op() + op = Operator( + self, + op_desc, + type=kwargs.get("type", None), + inputs=kwargs.get("inputs", None), + outputs=kwargs.get("outputs", None), + attrs=kwargs.get("attrs", None), + ) + self.ops.insert(0, op) + + return op + + def _sync_with_cpp(self): + """ + Sync from the desc on the c++ end. This method is used to synchronize + the c++ desc instance generated by backward. + """ + # sync variables from cpp + for var in self.desc.all_vars(): + if not self.has_var(var.name()): + is_stop_gradient = False + if var.has_stop_gradient(): + is_stop_gradient = var.stop_gradient() + if var.has_is_parameter() and var.is_parameter(): + self.create_parameter( + name=var.name(), + desc=var, + type=var.type(), + shape=var.shape(), + dtype=var.dtype(), + stop_gradient=is_stop_gradient, + ) + else: + self.create_var( + name=var.name(), + desc=var, + type=var.type(), + stop_gradient=is_stop_gradient, + ) + + # sync variables removed from c++ end + for var in list(self.vars.keys()): + if not self.desc.find_var(cpt.to_bytes(var)): + self.vars.pop(var) + + # sync operators from cpp + ops_in_cpp = [] + for op_idx in range(0, self.desc.op_size()): + ops_in_cpp.append(self.desc.op(op_idx)) + + if len(self.ops) != 0: + first_op_in_python = self.ops[0].desc + last_op_in_python = self.ops[len(self.ops) - 1].desc + start_index = None + end_index = None + for index in range(len(ops_in_cpp)): + if first_op_in_python == ops_in_cpp[index]: + start_index = index + if last_op_in_python == ops_in_cpp[index]: + end_index = index + assert start_index is not None + assert end_index is not None + assert start_index <= end_index + else: + start_index = 0 + end_index = -1 + + # sync ops append to the head of cpp_ops + for index in range((start_index - 1 - 1), -1, -1): + op_desc = ops_in_cpp[index] + op = Operator(self, op_desc) + self.ops.insert(0, op) + + # sync ops append to the end of cpp_ops + for index in range((end_index + 1), len(ops_in_cpp)): + op_desc = ops_in_cpp[index] + op = Operator(self, op_desc) + self.ops.append(op) + + # sync ops removed from c++ end + if end_index != -1 and end_index < len(self.ops): + ops_in_cpp_index = 0 + ops_in_python_index = 0 + while ops_in_python_index < len( + self.ops + ) and ops_in_cpp_index < len(ops_in_cpp): + if ( + self.ops[ops_in_python_index].desc + != ops_in_cpp[ops_in_cpp_index] + ): + del self.ops[ops_in_python_index] + else: + ops_in_cpp_index += 1 + ops_in_python_index += 1 + + assert len(self.ops) == len(ops_in_cpp) + for index in range(len(self.ops)): + assert self.ops[index].desc == ops_in_cpp[index] + + def _copy_param_info_from(self, other): + """ + Copy the information of parameters from the other block. + + Args: + other(Block): the other block. + + Raises: + ValueError: If type of input is not Block, or the `other` and this + block is not in the same topology. + + Returns: + None + """ + if not isinstance(other, Block): + raise TypeError( + "_copy_param_info_from should be invoked with Block" + ) + for p in other.iter_parameters(): + assert isinstance(p, Parameter) + v = self.vars.get(p.name, None) + if v is None: + # if the Parameter is pruned, v may be None + continue + assert isinstance(v, Variable) + new_p = None + if in_dygraph_mode(): + new_p = EagerParamBase( + shape=v.shape, + dtype=v.dtype, + type=v.type, + lod_level=v.lod_level, + stop_gradient=p.stop_gradient, + trainable=p.trainable, + optimize_attr=p.optimize_attr, + regularizer=p.regularizer, + error_clip=p.error_clip, + name=v.name, + ) + else: + if _in_legacy_dygraph(): + new_p = ParamBase( + shape=v.shape, + dtype=v.dtype, + type=v.type, + lod_level=v.lod_level, + stop_gradient=p.stop_gradient, + trainable=p.trainable, + optimize_attr=p.optimize_attr, + regularizer=p.regularizer, + error_clip=p.error_clip, + name=v.name, + ) + else: + new_p = Parameter( + block=self, + shape=v.shape, + dtype=v.dtype, + type=v.type, + lod_level=v.lod_level + if v.type == core.VarDesc.VarType.LOD_TENSOR + else None, + stop_gradient=p.stop_gradient, + trainable=p.trainable, + optimize_attr=p.optimize_attr, + regularizer=p.regularizer, + error_clip=p.error_clip, + name=v.name, + ) + self.vars[new_p.name] = new_p + + def _clone_variable(self, var, force_persistable=True): + """ + Clone a variable into current block. + + Args: + var: the variable to be cloned. + force_persistable(bool): True means setting the result variable to being persistable. + False means setting the persistable the same with that of input var. + default: True. + + Returns: + Variable: the new variable cloned from 'var' in current block. + """ + assert isinstance(var, Variable) + ret_var = None + # make STEP_SCOPES var can be safely cloned. + if var.type == core.VarDesc.VarType.STEP_SCOPES: + ret_var = self.create_var( + name=var.name, persistable=var.persistable, type=var.type + ) + elif var.type == core.VarDesc.VarType.RAW: + ret_var = self.create_var( + name=var.name, persistable=var.persistable, type=var.type + ) + elif var.type == core.VarDesc.VarType.SELECTED_ROWS: + ret_var = self.create_var( + name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + persistable=True if force_persistable else var.persistable, + is_data=var.is_data, + need_check_feed=var.desc.need_check_feed(), + ) + else: + ret_var = self.create_var( + name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=True if force_persistable else var.persistable, + is_data=var.is_data, + need_check_feed=var.desc.need_check_feed(), + ) + return ret_var + + +# NOTE(zjl): you should be careful that after you call this method, +# some Python Variable and all Python Operators should not be used +# again. Because all Python Variables and all Python Operators are +# re-constructed inside this method. The underlying VarDesc(OpDesc) +# of some old Python Variables(all old Python Operators) may have +# been destructed. +def _apply_pass( + main_program, startup_program, pass_name, pass_attrs={}, pass_attr_types={} +): + assert isinstance(pass_attrs, dict), "pass_attrs must be dict" + assert isinstance(pass_attr_types, dict), "pass_attr_types must be dict" + tmp_main_program = core.ProgramDesc(main_program.desc) + tmp_startup_program = core.ProgramDesc(startup_program.desc) + attrs = core.apply_pass( + tmp_main_program, + tmp_startup_program, + pass_name, + pass_attrs, + pass_attr_types, + ) + main_program._rebuild_from_desc(tmp_main_program) + startup_program._rebuild_from_desc(tmp_startup_program) + return attrs + + +class IrNode(object): + """ + Python IrNode. Beneath it is a core.Node, which is used for Ir Pass. + """ + + def __init__(self, node): + """ + Construct an IrNode using core.Node. + + Args: + node(core.Node): C++ Node. + """ + assert isinstance( + node, core.Node + ), 'node must be the instance of core.Node.' + self.node = node + + def name(self): + """ + Return the node name. + + Returns: + str: node name. + """ + return self.node.name() + + def node_type(self): + """ + Return the node type. + + Returns: + core.Node.Type: node type(core.Node.Type.Operation or core.Node.Type.Variable). + """ + return self.node.node_type() + + def var(self): + """ + Return the node variable description. + + Returns: + core.VarDesc: node variable description. + """ + return self.node.var() + + def op(self): + """ + Return the node operator description. + + Returns: + core.OpDesc: node operator description. + """ + return self.node.op() + + def id(self): + """ + Return the node id. + + Returns: + int: node id. + """ + return self.node.id() + + def is_op(self): + """ + If the node is an operator, then return true. + + Returns: + bool: indicate whether the node is an operator. + """ + return self.node.is_op() + + def is_var(self): + """ + If the node is a variable, then return true. + + Returns: + bool: indicate whether the node is a variable. + """ + return self.node.is_var() + + def is_ctrl_var(self): + """ + If the node is a control dependence variable, then return true. + + Returns: + bool: indicate whether the node is a control dependence variable. + """ + return self.node.is_ctrl_var() + + def clear_inputs(self): + """ + Clear the node inputs. After executing the `clear_inputs` function, + the node inputs will be empty. + """ + self.node.clear_inputs() + + def remove_input_by_id(self, node_id): + """ + Remove a node from inputs by the given node id. + + Args: + node_id(int): the given node id. + """ + self.node.remove_input(node_id) + + def remove_input(self, node): + """ + Remove a node from inputs. + + Args: + node(IrNode): the node being removed. + """ + self.node.remove_input(node.node) + + def append_input(self, node): + """ + Append a node in inputs. + + Args: + node(IrNode): the node being appended. + """ + self.node.append_input(node.node) + + def clear_outputs(self): + """ + Clear the node outputs. After executing the `clear_outputs` function, + the node outputs will be empty. + """ + self.node.clear_outputs() + + def remove_output_by_id(self, node_id): + """ + Remove a node from outputs by the given node id. + + Args: + node_id(int): the given node id. + """ + self.node.remove_output(node_id) + + def remove_output(self, node): + """ + Remove a node from outputs. + + Args: + node(IrNode): the node being removed. + """ + self.node.remove_output(node.node) + + def append_output(self, node): + """ + Append a node in outputs. + + Args: + node(IrNode): the node being appended. + """ + self.node.append_output(node.node) + + @property + def inputs(self): + """ + Return the node inputs. + + Returns: + list(IrNode): node inputs wrapped by IrNode. + """ + return [IrNode(n) for n in self.node.inputs] + + @property + def outputs(self): + """ + Return the node outputs. + + Returns: + list(IrNode): node outputs wrapped by IrNode. + """ + return [IrNode(n) for n in self.node.outputs] + + +class IrVarNode(IrNode): + """ + Python IrVarNode. Beneath it is a core.Node, it inherits from IrNode. + """ + + def __init__(self, node): + """ + Construct an IrVarNode using core.Node. + + Args: + node(core.Node): C++ Node. + """ + assert ( + isinstance(node, core.Node) and node.is_var() + ), 'node must be the instance of core.Node and it must be a variable node.' + super(IrVarNode, self).__init__(node) + self.node = node + + def set_shape(self, shape): + """ + Set the node variable shape. + + Args: + shape(list): shape to be set. + """ + assert ( + self.node.var() is not None + ), "The node variable description can not be None." + self.node.var().set_shape(shape) + + def persistable(self): + """ + If the variable node is a persistable variable, then return true. + + Returns: + bool: indicate whether the variable is persistable. + """ + assert ( + self.node.var() is not None + ), "The node variable description can not be None." + return self.node.var().persistable() + + def type(self): + """ + Return the variable type. + + Returns: + core.VarDesc.VarType: the variable type. + """ + assert ( + self.node.var() is not None + ), "The node variable description can not be None." + return self.node.var().type() + + def dtype(self): + """ + Return the variable data type. + + Returns: + core.VarDesc.VarType: the variable data type. + """ + assert ( + self.node.var() is not None + ), "The node variable description can not be None." + return self.node.var().dtype() + + def shape(self): + """ + Return the variable shape. + + Returns: + list: the variable shape. + """ + assert ( + self.node.var() is not None + ), "The node variable description can not be None." + return self.node.var().shape() + + @property + def inputs(self): + """ + Return the node inputs. + + Returns: + list(IrOpNode): node inputs wrapped by IrOpNode. + """ + return [IrOpNode(n) for n in self.node.inputs] + + @property + def outputs(self): + """ + Return the node outputs. + + Returns: + list(IrOpNode): node outputs wrapped by IrOpNode. + """ + return [IrOpNode(n) for n in self.node.outputs] + + +class IrOpNode(IrNode): + """ + Python IrOpNode. Beneath it is a core.Node, it inherits from IrNode. + """ + + def __init__(self, node): + """ + Construct an IrOpNode using core.Node. + + Args: + node(core.Node): C++ Node. + """ + assert ( + isinstance(node, core.Node) and node.is_op() + ), 'node must be the instance of core.Node and it must be a operator node.' + super(IrOpNode, self).__init__(node) + self.node = node + + def rename_input(self, old_input_name, new_input_name): + """ + Rename the input of this node. + + Args: + old_input_name(str): the old input name. + new_input_name(str): the new input name. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + self.node.op()._rename_input(old_input_name, new_input_name) + + def rename_output(self, old_output_name, new_output_name): + """ + Rename the output of this node. + + Args: + old_output_name(str): the old output name. + new_output_name(str): the new output name. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + self.node.op()._rename_output(old_output_name, new_output_name) + + def input(self, name): + """ + Get the argument name list by the parameter name for input. + + Args: + name(str): the parameter name. + + Returns: + list(str): the argument name list. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + return self.node.op().input(name) + + def output(self, name): + """ + Get the argument name list by the parameter name for output. + + Args: + name(str): the parameter name. + + Returns: + list(str): the argument name list. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + return self.node.op().output(name) + + def set_type(self, new_type): + """ + Change the operator type into new type. + + Args: + new_type(str): new operator type to be set. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + return self.node.op().set_type(new_type) + + def set_attr(self, name, val): + """ + Set the value of attribute by attribute's name. + + Args: + name(str): the attribute name. + val(bool|int|str|float|list): the value of the attribute. + """ + self._update_desc_attr(name, val) + + def _update_desc_attr(self, name, val): + """ + Update the value of the op desc's attribute by attribute's name. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + desc = self.node.op() + if isinstance(val, Variable): + desc.set_var_attr(name, val.desc) + elif isinstance(val, list) and _all_is_type(val, Variable): + desc.set_vars_attr(name, [v.desc for v in val]) + elif isinstance(val, Block): + desc.set_block_attr(name, val.desc) + elif isinstance(val, list) and val and _all_is_type(val, Block): + desc.set_blocks_attr(name, [v.desc for v in val]) + elif isinstance(val, core.BlockDesc) or isinstance( + val, core.ProgramDesc + ): + desc.set_serialized_attr(name, val.serialize_to_string()) + else: + desc._set_attr(name, val) + + def input_arg_names(self): + """ + Return input arguments' names of this op node. + + Returns: + list(str): input arguments' names of this op node. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + return self.node.op().input_arg_names() + + def output_arg_names(self): + """ + Return output arguments' names of this op node. + + Returns: + list(str): output arguments' names of this op node. + """ + assert ( + self.node.op() is not None + ), "The node operator description can not be None." + return self.node.op().output_arg_names() + + @property + def inputs(self): + """ + Return the node inputs. + + Returns: + list(IrVarNode): node inputs wrapped by IrVarNode. + """ + return [IrVarNode(n) for n in self.node.inputs] + + @property + def outputs(self): + """ + Return the node outputs. + + Returns: + list(IrVarNode): node outputs wrapped by IrVarNode. + """ + return [IrVarNode(n) for n in self.node.outputs] + + +class IrGraph(object): + """ + Python IrGraph. Beneath it is a core.Graph, which is used for + creating a c++ Ir Pass Graph. An IrGraph is just a graph view of + a Program. In an IrGraph, both Variables and Operators are graph + nodes. + """ + + def __init__(self, graph, for_test=False): + """ + Construct an IrGraph using core.Graph. + + Args: + graph(core.Graph): C++ Graph. + for_test(bool): True for the test graph and false for the train graph. + """ + assert isinstance( + graph, core.Graph + ), 'graph must be the instance of core.Graph.' + self.graph = graph + self._for_test = for_test + + def clone(self): + """ + Create a new and duplicated IrGraph. + + Warns: + The method only clones the graph structure, not its attributes. + + Returns: + IrGraph: A new and duplicated graph. + """ + g = self.graph.clone() + return IrGraph(g, self._for_test) + + def is_test(self): + """ + If the graph is used for testing, the function returns true. Otherwise, returns false. + """ + return self._for_test + + def all_nodes(self): + """ + Return all nodes included in the graph as a set. + """ + return {IrNode(node) for node in self.graph.nodes()} + + def all_var_nodes(self): + """ + Return all variable nodes included in the graph as a set. + """ + return {IrVarNode(node) for node in self.graph.nodes() if node.is_var()} + + def all_persistable_nodes(self): + """ + Return all persistable variable nodes included in the graph as a set. + """ + persistable_nodes = set() + for node in self.graph.nodes(): + if ( + node.is_var() + and node.var() is not None + and node.var().persistable() + ): + persistable_nodes.add(node) + return {IrVarNode(p) for p in persistable_nodes} + + def all_op_nodes(self): + """ + Return all operator nodes included in the graph as a set. + """ + return {IrOpNode(node) for node in self.graph.nodes() if node.is_op()} + + def all_sub_graphs(self, for_test=False): + """ + Return all sub_graphs included in the main graph as a set. + """ + + return [ + IrGraph(self.graph.get_sub_graph(i), for_test=for_test) + for i in range(self.graph.sub_graph_size()) + ] + + def get_sub_graph(self, i, for_test=False): + """ + Return i-th sub_graph in the main graph. + """ + return IrGraph(self.graph.get_sub_graph(i), for_test=for_test) + + def create_persistable_node(self, name, var_type, shape, var_dtype): + """ + Create a persistable variable node in the graph. In IrGraph, + it can not distinguish between persistable variables and parameters. + + Args: + name(str): the name of the persistable variable node. + vart_type(core.VarDesc.VarType): the type of the persistable variable node. + shape(list): the shape of the persistable variable node. + var_dtype(core.VarDesc.VarType): the data type of the persistable variable node. + + Returns: + IrVarNode: the created persistable variable node. + """ + var_desc = core.VarDesc(name) + var_desc.set_type(var_type) + var_desc.set_shape(shape) + var_desc.set_dtype(var_dtype) + var_desc.set_persistable(True) + return IrVarNode(self.graph.create_var_node(var_desc)) + + def create_var_node(self, name, var_type, shape, var_dtype): + """ + Create a variable node in the graph. The created variable node is + not persistable. + + Args: + name(str): the name of the variable node. + vart_type(core.VarDesc.VarType): the type of the variable node. + shape(list): the shape of the variable node. + var_dtype(core.VarDesc.VarType): the data type of the variable node. + + Returns: + IrVarNode: the created variable node. + """ + + var_desc = core.VarDesc(name) + var_desc.set_type(var_type) + var_desc.set_shape(shape) + var_desc.set_dtype(var_dtype) + return IrVarNode(self.graph.create_var_node(var_desc)) + + def create_control_dep_var(self): + """ + create a control var + """ + return IrVarNode(self.graph.create_control_dep_var()) + + def create_var_node_from_desc(self, var_desc): + """ + Create a variable node by using an existing VarDesc in the graph. + Depend on the giving VarDesc, the created variable node may be persistable. + + Args: + var_desc(core.VarDesc): the giving variable description. + + Returns: + IrVarNode: the created variable node. + """ + return IrVarNode(self.graph.create_var_node(var_desc)) + + def create_op_node(self, op_type, attrs, inputs, outputs): + """ + Create a operator node in the graph. + + Args: + op_type(str): the type of the operator node. + attrs(dict): the attributes of the operator node. + inputs(dict): the inputs of the operator node. + outputs(dict): the outputs of the operator node. + + Returns: + IrOpNode: the created operator node. + """ + op_desc = core.OpDesc() + op_desc.set_type(op_type) + for attr, value in six.iteritems(attrs): + self._update_desc_attr(op_desc, attr, value) + for input_name, var_nodes in six.iteritems(inputs): + if not isinstance(var_nodes, list): + var_nodes = [var_nodes] + op_desc.set_input( + input_name, [var_node.name() for var_node in var_nodes] + ) + for output_name, var_nodes in six.iteritems(outputs): + if not isinstance(var_nodes, list): + var_nodes = [var_nodes] + op_desc.set_output( + output_name, [var_node.name() for var_node in var_nodes] + ) + return IrOpNode(self.graph.create_op_node(op_desc)) + + def create_op_node_from_desc(self, op_desc): + """ + Create a operator node by using an existing OpDesc in the graph. + + Args: + op_desc(core.VarDesc): the giving operator description. + + Returns: + IrOpNode: the created operator node. + """ + return IrOpNode(self.graph.create_op_node(op_desc)) + + def update_input_link(self, old_input_node, new_input_node, op_node): + """ + Update the input's link of a operator node. + + Args: + old_input_node(IrNode): the old input node of the giving op_node. + new_input_node(IrNode): the new input node of the giving op_node. + op_node(IrOpNode): the operator node that is needed to update input's link. + """ + assert ( + old_input_node.node in self.graph.nodes() + and new_input_node.node in self.graph.nodes() + and op_node.node in self.graph.nodes() + ), 'The three arguments(old_input_node&new_input_node&op_node) must be in the graph nodes.' + old_input_node.remove_output(op_node) + op_node.remove_input(old_input_node) + new_input_node.append_output(op_node) + op_node.append_input(new_input_node) + op_node.rename_input(old_input_node.name(), new_input_node.name()) + + def update_output_link(self, old_output_node, new_output_node, op_node): + """ + Update the output's link of an operator node. + + Args: + old_output_node(IrNode): the old output node of the giving op_node. + new_output_node(IrNode): the new output node of the giving op_node. + op_node(IrOpNode): the operator node that is needed to update input's link. + """ + assert ( + old_output_node.node in self.graph.nodes() + and new_output_node.node in self.graph.nodes() + and op_node.node in self.graph.nodes() + ), 'The three arguments(old_output_node &new_output_node &op_node) must be in the graph nodes.' + old_output_node.remove_input(op_node) + op_node.remove_output(old_output_node) + new_output_node.append_input(op_node) + op_node.append_output(new_output_node) + op_node.rename_output(old_output_node.name(), new_output_node.name()) + + def link_to(self, node_in, node_out): + """ + Connect two nodes. + + Args: + node_in(IrNode): the input node. + node_out(IrNode): the output node. + """ + assert node_in.node in self.graph.nodes(), ( + 'node_in(%s) must be in the graph nodes.' % node_in.node.name() + ) + assert node_out.node in self.graph.nodes(), ( + 'node_out(%s) must be in the graph nodes.' % node_out.node.name() + ) + node_in.append_output(node_out) + node_out.append_input(node_in) + + def safe_remove_nodes(self, remove_nodes): + """ + Remove nodes safely since links connected to these removed nodes are + also removed. + + Args: + remove_nodes(set): the nodes prepared to be removed. + """ + if not isinstance(remove_nodes, set): + if isinstance(remove_nodes, Iterable): + remove_nodes = set(remove_nodes) + else: + remove_nodes = {remove_nodes} + original_nodes = {n.node for n in remove_nodes} + core.graph_safe_remove_nodes(self.graph, original_nodes) + + def resolve_hazard(self): + ordered_nodes = core.topology_sort(self.graph) + var_nodes = dict() + for node in ordered_nodes: + if node.is_op() and node.op() is not None: + for each_var_name in node.op().input_arg_names(): + if each_var_name not in var_nodes: + var_nodes[each_var_name] = [ + self._find_node_by_name(node.inputs, each_var_name) + ] + for each_var_name in node.op().output_arg_names(): + if each_var_name not in var_nodes: + var_nodes[each_var_name] = [ + self._find_node_by_name(node.outputs, each_var_name) + ] + else: + var_nodes[each_var_name].append( + self._find_node_by_name(node.outputs, each_var_name) + ) + self.graph.resolve_hazard(var_nodes) + + def has_circle(self): + """ + Check if the graph has a circle. + + Returns: + bool: True if the graph has a circle else False. + """ + return core.has_circle(self.graph) + + def graph_num(self): + """ + Count the number of unconnected graphs in this graph. + + Returns: + int: the number of unconnected graphs. + """ + return core.graph_num(self.graph) + + def topology_sort(self): + """ + Perform the topology sort operation on the graph. + + Notes: the `graph` can not contain a circle. + + Returns: + list(IrNode): nodes in topology order. + """ + ordered_nodes = core.topology_sort(self.graph) + return [IrNode(n) for n in ordered_nodes] + + def build_adjacency_list(self): + """ + Build an adjacency list of operations for the `graph`. + + Returns: + dict{IrNode: set(IrNode)}: the adjacency list. + """ + adj_list = core.build_adjacency_list(self.graph) + wrapped_adj_list = dict() + for k, v in six.iteritems(adj_list): + wrapped_adj_list[IrNode(k)] = {IrNode(n) for n in v} + return wrapped_adj_list + + def draw(self, save_path, name, marked_nodes=None, remove_ctr_var=True): + """ + Draw the graph. If `dot` command is installed, the drawn graph + will be saved as pdf file type, otherwise dot file type is used. + + Args: + save_path(str): the save path of drawn graph. + name(str): the name of drawn graph. + marked_nodes(set(IrNode)): nodes that are needed to be marked. + Default value is None. + remove_ctr_var(bool): If it is set True, all control variable nodes + in the graph will be removed. Default value is True. + """ + + def _convert_to_pdf(dot_file_path): + pdf_save_path = os.path.splitext(dot_file_path)[0] + '.pdf' + exited_code = subprocess.call( + 'dot -Tpdf ' + dot_file_path + ' -o ' + pdf_save_path, + shell=True, + ) + if exited_code != 0: + print('The dot command is needed for creating pdf files.') + print( + 'The {} is saved as the dot filetype.'.format(dot_file_path) + ) + + remove_ctr_vars = set() + if remove_ctr_var: + for node in self.all_var_nodes(): + if node.is_ctrl_var(): + remove_ctr_vars.add(node) + self.safe_remove_nodes(remove_ctr_vars) + print('Total ops num = {}.'.format(len(self.all_op_nodes()))) + + if marked_nodes is not None: + if not isinstance(marked_nodes, set): + if isinstance(marked_nodes, Iterable): + marked_nodes = set(marked_nodes) + else: + marked_nodes = {marked_nodes} + marked_nodes = {n.node for n in marked_nodes} + remove_ctr_vars = {n.node for n in remove_ctr_vars} + marked_nodes = marked_nodes - remove_ctr_vars + if self.graph.has('__graphviz__marked_node__'): + self.graph.erase('__graphviz__marked_node__') + self.graph.set('__graphviz__marked_node__', marked_nodes) + if not os.path.exists(save_path): + os.makedirs(save_path) + viz_dot_path = os.path.join(save_path, name) + '.dot' + viz_pass = core.get_pass('graph_viz_pass') + viz_pass.set('graph_viz_path', viz_dot_path) + viz_pass.apply(self.graph) + _convert_to_pdf(viz_dot_path) + + def to_program(self): + """ + Convert the graph into a Program. + + WARN: When the graph includes backward operator nodes, the + conversion process may be failed. Usually, this function is + only used to convert a test graph. + + Returns: + Program: a program converted from the graph. + """ + convert_pass = core.get_pass('graph_to_program_pass') + desc = core.ProgramDesc() + convert_pass.set_not_owned('program', desc) + convert_pass.apply(self.graph) + program = Program._construct_from_desc(desc) + return program + + def _find_node_by_name(self, nodes, node_name): + """ + Find a node in the giving nodes set by the name. + """ + target_node = None + for n in nodes: + if n.name() == node_name: + target_node = n + assert target_node is not None, ( + "Cannot find the target node (%s)in the giving set." % node_name + ) + return target_node + + def _update_desc_attr(self, desc, name, val): + """ + Update the value of desc's attribute by attribute's name. + """ + if isinstance(val, Variable): + desc.set_var_attr(name, val.desc) + elif isinstance(val, list) and _all_is_type(val, Variable): + desc.set_vars_attr(name, [v.desc for v in val]) + elif isinstance(val, Block): + desc.set_block_attr(name, val.desc) + elif isinstance(val, list) and val and _all_is_type(val, Block): + desc.set_blocks_attr(name, [v.desc for v in val]) + elif isinstance(val, core.BlockDesc) or isinstance( + val, core.ProgramDesc + ): + desc.set_serialized_attr(name, val.serialize_to_string()) + else: + desc._set_attr(name, val) + + +class Program(object): + """ + Create Python Program. It has at least one :ref:`api_guide_Block_en`, when the + control flow op like conditional_block, while :ref:`api_paddle_fluid_layers_While` is included, + it will contain nested block. + + Please reference the + `framework.proto `_ + for details. + + A set of Program usually contains startup program and main program. + A startup program is set to contain some initial work, eg. initialize the ``Parameter``, and the main + program will contain the network structure and vars for train. + + A set of Program can be used for test or train, in train program , + Paddle will contain all content to build a train network, in test + program Paddle will prune some content which is irrelevant to test, eg. + backward ops and vars. + + **Notes**: + **we have** :ref:`api_paddle_fluid_framework_default_startup_program` **and** :ref:`api_paddle_fluid_framework_default_main_program` + **by default, a pair of them will shared the parameters. The** :ref:`api_paddle_fluid_framework_default_startup_program` **only run once to initialize parameters,** + :ref:`api_paddle_fluid_framework_default_main_program` **run in every mini batch and adjust the weights.** + + Returns: + Program: An empty Program. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + main_program = static.Program() + startup_program = static.Program() + with static.program_guard(main_program=main_program, startup_program=startup_program): + x = static.data(name="x", shape=[-1, 784], dtype='float32') + y = static.data(name="y", shape=[-1, 1], dtype='int32') + z = static.nn.fc(name="fc", x=x, size=10, activation="relu") + + print("main program is: {}".format(main_program)) + print("start up program is: {}".format(startup_program)) + + """ + + def __init__(self): + self.desc = core.ProgramDesc() + self.blocks = [Block(self, 0)] + self.current_block_idx = 0 + global global_prog_seed + self._seed = global_prog_seed + self._current_role = core.op_proto_and_checker_maker.OpRole.Forward + self.__op_role_var = [] + + # for distribute training + # _is_distributed = True if under distributed training + self._is_distributed = False + # _is_chief = True if the trainer is the first one, usually No.0 + self._is_chief = False + # _parameters_on_pservers records all the parameters distributed on parameter servers. + self._parameters_on_pservers = None + # _endpoints is a list about parameter servers ip:port, such as ["ip:port","ip:port"] + self._endpoints = [] + # if current role is parameter server, the _ps_endpoint is its "ip:port" + self._ps_endpoint = None + # trainers_endpoints, it is used for distribution. + self._trainers_endpoints = [] + # the distributed lookup table names + self._distributed_lookup_table = None + + # use Deep gradient comrepssion or not + self._enable_dgc = False + self._use_lamb = False + + self._nccl_comm_num = 1 + self._use_hierarchical_allreduce = False + self._hierarchical_allreduce_inter_nranks = 0 + + # if this program has been optimized by distributed optimizer + # fleet_opt will be given a value + self._fleet_opt = None + self._program_config = None + + # assigned if this program has been parsed by a pipeline optimizer + self._pipeline_opt = None + + # assigned if this program has been parsed by a heter pipeline parameter server optimizer + self._heter_pipeline_opt = None + + # appending gradients times + self._appending_grad_times = 0 + + # identifier for auto checkpoint + self._auto_checkpoint_name = unique_name.generate( + "__auto_checkpoint_program__" + ) + + # compiled program, i.e. Graph + self._graph = None + # to tag whether is startup_program + self._is_start_up_program_ = False + + def _find_var_class_kwargs(self, new_desc): + # NOTE: not all variables support shape/dtype/lod_level methods. + # For example: RAW, STEP_SCOPES, etc. + def get_var_desc_attr_or_none(var_desc, attr_name, allowed_types): + if var_desc.type() in allowed_types: + return getattr(var_desc, attr_name)() + else: + return None + + old_desc = self.desc + all_new_vars = [] + block_num = new_desc.num_blocks() + for idx in range(block_num): + if idx > (len(self.blocks) - 1): + self._create_block() + new_block_desc = new_desc.block(idx) + all_new_vars.append([]) + block_new_vars = all_new_vars[-1] + for new_var_desc in new_block_desc.all_vars(): + if self.blocks[idx].has_var(new_var_desc.name()): + old_var = self.blocks[idx].var(new_var_desc.name()) + else: + old_var = None + + kwargs = { + 'type': new_var_desc.type(), + 'name': new_var_desc.name(), + 'shape': get_var_desc_attr_or_none( + new_var_desc, + "shape", + [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.SELECTED_ROWS, + core.VarDesc.VarType.LOD_TENSOR_ARRAY, + ], + ), + 'dtype': get_var_desc_attr_or_none( + new_var_desc, + "dtype", + [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.SELECTED_ROWS, + core.VarDesc.VarType.LOD_TENSOR_ARRAY, + ], + ), + 'lod_level': get_var_desc_attr_or_none( + new_var_desc, + "lod_level", + [ + core.VarDesc.VarType.LOD_TENSOR, + core.VarDesc.VarType.LOD_TENSOR_ARRAY, + ], + ), + 'error_clip': old_var.error_clip + if old_var is not None + else None, + 'stop_gradient': old_var.stop_gradient + if old_var is not None + else False, + 'is_data': old_var.is_data + if old_var is not None + else False, + 'need_check_feed': new_var_desc.need_check_feed(), + 'belong_to_optimizer': old_var.belong_to_optimizer + if old_var is not None + else False, + } + + if isinstance(old_var, Parameter): + kwargs.update( + { + 'trainable': old_var.trainable, + 'optimize_attr': old_var.optimize_attr, + 'regularizer': old_var.regularizer, + 'do_model_average': old_var.do_model_average, + 'need_clip': old_var.need_clip, + 'is_distributed': old_var.is_distributed, + 'is_parameter': old_var.is_parameter, + } + ) + block_new_vars.append( + { + 'class': Parameter, + 'kwargs': copy.deepcopy(kwargs), + } + ) + else: + kwargs['persistable'] = new_var_desc.persistable() + block_new_vars.append( + { + 'class': Variable, + 'kwargs': copy.deepcopy(kwargs), + } + ) + + return all_new_vars + + def _rebuild_from_desc(self, desc): + all_new_vars = self._find_var_class_kwargs(desc) + block_num = desc.num_blocks() + assert block_num == len(all_new_vars) + assert block_num == self.desc.num_blocks() + + # clear old blocks and desc + for idx in range(block_num): + block = self.blocks[idx] + block.vars.clear() + block.ops.clear() + + for idx in range(block_num): + block_desc = self.blocks[idx].desc + new_block_desc = desc.block(idx) + block_desc._move_from(new_block_desc) + + del desc + + # add new vars first + for idx in range(block_num): + block = self.blocks[idx] + for new_var in all_new_vars[idx]: + clazz = new_var['class'] + kwargs = new_var['kwargs'] + kwargs['block'] = block + clazz(**kwargs) + + # then append op + for idx in range(block_num): + block = self.blocks[idx] + block_desc = self.desc.block(idx) + for op_idx in range(block_desc.op_size()): + op_desc = block_desc.op(op_idx) + op = Operator(block=block, desc=op_desc) + block.ops.append(op) + + def global_seed(self, seed=0): + """ + Set global seed for Program + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + print(prog.random_seed) + ## 0 + ## the default random seed is 0 + + prog.global_seed(102) + prog1 = static.default_main_program() + print(prog1.random_seed) + ## 102 + ## the random seed is 102 + """ + global global_prog_seed + global_prog_seed = seed + self._seed = global_prog_seed + + @property + def _op_role(self): + """ + The operator role. In a enum {Forward, Backward, Optimize}. + + Notes: this is a low level API. It is used only for ParallelExecutor to + duplicate or schedule operator to devices. + + For example, the forward operator should be executed on every device. + The backward operator should be executed on every device and the + parameter gradient of backward (use :code:`_op_role_var` to get this + variable) operator should be merged to one device. The optimization + operators should be executed on only one device and broadcast the + optimization result, i.e., the new parameter, to every other device. + """ + return self._current_role + + @_op_role.setter + def _op_role(self, role): + self._current_role = role + + @property + def _op_role_var(self): + """ + The auxiliary variables for :code:`_op_role` property. + + See Also: :code:`Program._op_role`'s documentation for details. + + Notes: This is a very low-level API. Users should not use it directly. + """ + return self.__op_role_var + + @signature_safe_contextmanager + def _backward_role_guard(self): + tmp_role = self._current_role + + OpRole = core.op_proto_and_checker_maker.OpRole + self._current_role = OpRole.Backward + try: + yield + finally: + self._current_role = tmp_role + + @signature_safe_contextmanager + def _optimized_guard(self, param_and_grads): + """ + A with guard to set :code:`Optimization` :code:`OpRole` and + :code:`OpRoleVar` automatically. + + Notes: This is a very low level API. Users should not use it directly. + + Args: + param_and_grads(list): The variables (names) to be optimized. + + Examples: + + >>> import paddle.fluid as fluid + >>> p, g = backward(...) + >>> with program._optimized_guard([p,g]): + >>> p = p - 0.001 * g + """ + tmp_role = self._current_role + tmp_var = self.__op_role_var + + OpRole = core.op_proto_and_checker_maker.OpRole + self._current_role = OpRole.Optimize + self.__op_role_var = [ + var.name if isinstance(var, Variable) else var + for var in param_and_grads + ] + try: + yield + finally: + self.__op_role_var = tmp_var + self._current_role = tmp_role + + @signature_safe_contextmanager + def _lr_schedule_guard(self, is_with_opt=False): + """ + A with guard to set :code:`LRSched` :code:`OpRole` and + :code:`OpRoleVar` automatically. The :code:`OpRoleVar` is + set to the target learning rate. + + Notes: This is a very low level API. Users should not use it directly. + + Args: + is_with_opt: Only set to true if these ops a in the middle + of a bunch of optimize ops so that it can be treated + correctly. For example, sgd->lr_op->sgd->lr_op->sgd. + + Examples: + + >>> import paddle.fluid as fluid + >>> p, g = backward(...) + >>> with program.lr_schedule_guard(): + >>> lr = lr * decay + """ + + tmp_role = self._current_role + tmp_var = self.__op_role_var + + OpRole = core.op_proto_and_checker_maker.OpRole + self._current_role = OpRole.LRSched + if is_with_opt: + self._current_role = int(OpRole.LRSched) | int(OpRole.Optimize) + # TODO(typhoonzero): how to set target learning rate var + self.__op_role_var = [] + try: + yield + finally: + self.__op_role_var = tmp_var + self._current_role = tmp_role + + def __str__(self): + """ + Get the protobuf debug string of this Program. + + Returns: + (str): The protobuf debug string. + + Raises: + ValueError: If any of required fields is not set. + """ + return self._to_readable_code() + + def _to_readable_code(self, skip_op_callstack=True): + """ + Get readable debug string of Program. + + .. note:: + If you want to get the debug string in protobuf format, + please use :code:`to_string` method. + + Args: + skip_op_callstack(bool): whether to skip parsing Operator's attribute + op_callstack, default value is True + + Returns: + string: The formatted Program string. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + cur_program = static.Program() + cur_block = cur_program.current_block() + new_var = cur_block.create_var(name="X", + shape=[-1, 23, 48], + dtype='float32') + new_op = cur_block.append_op(type="abs", + inputs={"X": [new_var]}, + outputs={"Out": [new_var]}) + print(cur_program._to_readable_code()) + """ + assert isinstance( + skip_op_callstack, bool + ), "skip_op_callstack parameter's type is error, expect bool, received {}".format( + type(skip_op_callstack) + ) + program_str = "" + for block in self.blocks: + program_str += block._to_readable_code(skip_op_callstack) + program_str += '\n' + return program_str + + def to_string(self, throw_on_error, with_details=False): + """ + To debug string. + + Args: + + throw_on_error (bool): raise Value error when any of required fields is not set. + + with_details (bool): True if more details about variables and parameters, e.g., :code:`trainable`, :code:`optimize_attr`, need to print. + + Returns: + str: The debug string describe current Program. + + Raises: + ValueError: If any of required fields is not set and throw_on_error is True. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + x = static.data(name="X", shape=[2,3], dtype="float32") + pred = static.nn.fc(x, size=3) + prog_string = prog.to_string(throw_on_error=True, with_details=False) + prog_string_with_details = prog.to_string(throw_on_error=False, with_details=True) + print("program string without detail: {}".format(prog_string)) + print("program string with detail: {}".format(prog_string_with_details)) + """ + assert isinstance( + throw_on_error, bool + ), "The type of throw_on_error parameter is wrong, expected bool, but received {}.".format( + type(throw_on_error) + ) + assert isinstance( + with_details, bool + ), "The type of with_details parameter is wrong, expected bool, but received {}.".format( + type(with_details) + ) + + if with_details: + res_str = "" + for block in self.blocks: + res_str += block.to_string(throw_on_error, with_details) + else: + protostr = self.desc.serialize_to_string() + proto = framework_pb2.ProgramDesc.FromString( + six.binary_type(protostr) + ) + res_str = _debug_string_(proto, throw_on_error) + return res_str + + def _get_desc(self): + """ + Get the C++ side of `ProgramDesc` object pointer. The C++ object is + exposed by :code:`pybind`. + + Notes: This is a very low level API. Users should not use this API + directly. + """ + return self.desc + + def _version(self): + return self.desc._version() + + def clone(self, for_test=False): + """ + .. note::: + 1. :code:`Program.clone()` method DOES NOT clone :ref:`api_paddle_io_DataLoader` . + 2. Recommend you to use :code:`clone` before using :code:`Opimizer.minimize` . + 3. This API has no effect in Dygraph Mode. + + Create a new Program with forward content of original one when ``for_test=True``. + Create a new Program as same as the original one when ``for_test=False``. + + Some operators, e.g., :ref:`api_paddle_fluid_layers_batch_norm` , behave differently between + training and testing. They have an attribute, :code:`is_test`, to + control this behaviour. This method will change the :code:`is_test` + attribute of them to :code:`True` when :code:`for_test=True`. + + * Set for_test to False when you want to clone the program for training. + * Set for_test to True when you want to clone the program for testing. + We will prune the backward and optimize part of the program when you + use :code:`clone` after :code:`Opimizer.minimize`, but we still + recommend you to use :code:`clone` before using :code:`Opimizer.minimize`. + + For Example: + :: + + import paddle + import paddle.static as static + + paddle.enable_static() + + img = static.data(name='image', shape=[None, 784]) + pred = static.nn.fc(x=img, size=10, actvation='relu') + loss = paddle.mean(pred) + # Here we use clone before Momentum + test_program = static.default_main_program().clone(for_test=True) + optimizer = paddle.optimizer.Momentum(learning_rate=0.01, momentum=0.9) + optimizer.minimize(loss) + + Args: + + for_test (bool): True if change the :code:`is_test` attribute of operators to :code:`True` + and prune the backward and optimize part of the program. The default value is :code:`False` . + + Returns: + Program: A new Program with forward content of original one when ``for_test=True``. A new Program as same as the original one when ``for_test=False`` + + + Examples: + + .. note:: + The Program's order maybe different after :code:`clone` and + this will not affect your training or testing progress. In the following + example we give you an simple method :code:`print_prog(program)` to + print Program Descs inorder to make sure you have same print result + after :code:`clone`: + + .. code-block:: python + + import six + + def print_prog(prog): + for name, value in sorted(six.iteritems(prog.block(0).vars)): + print(value) + for op in prog.block(0).ops: + print("op type is {}".format(op.type)) + print("op inputs are {}".format(op.input_arg_names)) + print("op outputs are {}".format(op.output_arg_names)) + for key, value in sorted(six.iteritems(op.all_attrs())): + if key not in ['op_callstack', 'op_role_var']: + print(" [ attrs: {}: {} ]".format(key, value)) + + + 1. To clone a test program, the sample code is: + .. code-block:: python + + import six + import paddle + import paddle.static as static + import paddle.utils as utils + import paddle.nn.functional as F + + paddle.enable_static() + + def print_prog(prog): + for name, value in sorted(six.iteritems(prog.block(0).vars)): + print(value) + for op in prog.block(0).ops: + print("op type is {}".format(op.type)) + print("op inputs are {}".format(op.input_arg_names)) + print("op outputs are {}".format(op.output_arg_names)) + for key, value in sorted(six.iteritems(op.all_attrs())): + if key not in ['op_callstack', 'op_role_var']: + print(" [ attrs: {}: {} ]".format(key, value)) + + train_program = static.Program() + startup_program = static.Program() + + # startup_program is used to do some parameter init work, + # and main program is used to hold the network + with static.program_guard(train_program, startup_program): + with utils.unique_name.guard(): + img = static.data(name='image', shape=[None, 784]) + hidden = static.nn.fc(x=img, size=200, activation='relu') + hidden = F.dropout(hidden, p=0.5) + loss = F.cross_entropy( + input=static.nn.fc(x=hidden, size=10, activation='softmax'), + label=static.data(name='label', shape=[1], dtype='int64')) + avg_loss = paddle.mean(loss) + test_program = train_program.clone(for_test=True) + print_prog(test_program) + + # Due to parameter sharing usage for train and test, so we need to use startup program of train + # instead of using test startup program, while nothing is in test's startup program + + # In Paddle we will share weights by using the same Tensor name. In train and test program + # all parameters will have the same name and this can make train and test program sharing parameters, + # that's why we need to use startup program of train. And for startup program of test, it has nothing, + # since it is a new program. + + with static.program_guard(train_program, startup_program): + with utils.unique_name.guard(): + sgd = paddle.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(avg_loss) + + + 2. The clone method can be avoid if you create program for training and program for testing individually. + .. code-block:: python + + import six + import paddle + import paddle.static as static + import paddle.utils as utils + import paddle.nn.functional as F + + paddle.enable_static() + + def print_prog(prog): + for name, value in sorted(six.iteritems(prog.block(0).vars)): + print(value) + for op in prog.block(0).ops: + print("op type is {}".format(op.type)) + print("op inputs are {}".format(op.input_arg_names)) + print("op outputs are {}".format(op.output_arg_names)) + for key, value in sorted(six.iteritems(op.all_attrs())): + if key not in ['op_callstack', 'op_role_var']: + print(" [ attrs: {}: {} ]".format(key, value)) + + def network(): + img = static.data(name='image', shape=[None, 784]) + hidden = static.nn.fc(x=img, size=200, activation='relu') + hidden = F.dropout(hidden, p=0.5) + loss = F.cross_entropy( + input=static.nn.fc(x=hidden, size=10, activation='softmax'), + label=static.data(name='label', shape=[1], dtype='int64')) + avg_loss = paddle.mean(loss) + return avg_loss + + train_program_2 = static.Program() + startup_program_2 = static.Program() + test_program_2 = static.Program() + with static.program_guard(train_program_2, startup_program_2): + with utils.unique_name.guard(): + avg_loss = network() + sgd = paddle.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(avg_loss) + # the test startup program is not used. + with static.program_guard(test_program_2, startup_program_2): + with utils.unique_name.guard(): + avg_loss = network() + print_prog(test_program_2) + + The two code snippets above will generate and print same programs. + """ + + # NOTE(zhiqiu): we sync the original program first, since its program may diff with + # its desc due to modifying desc in c++ space. E.g. save op will add kLookupTablePath in desc. + self._sync_with_cpp() + + pruned_origin_block_id_map = None + if for_test: + forward_prog = Program() + forward_prog.desc, pruned_origin_block_id_map = core.prune_backward( + self.desc + ) + forward_prog.blocks = [ + Block(forward_prog, i) + for i in six.moves.range(forward_prog.desc.num_blocks()) + ] + forward_prog._sync_with_cpp() + p = forward_prog._inference_optimize(prune_read_op=False) + else: + p = Program() + p.current_block_idx = self.current_block_idx + p._seed = self._seed + p.desc = core.ProgramDesc(self.desc) + p.blocks = [ + Block(p, i) for i in six.moves.range(self.desc.num_blocks()) + ] + + p._current_role = self._current_role + p.__op_role_var = self.__op_role_var + p._appending_grad_times = self._appending_grad_times + if hasattr(self, 'lr_sheduler'): + p.lr_sheduler = self.lr_sheduler + + # NOTE(zhiqiu): we sync the cloned program, to update its program by + # its desc. + p._sync_with_cpp() + + p._copy_param_info_from(self) + p._copy_data_info_from(self, pruned_origin_block_id_map) + p._copy_dist_param_info_from(self) + return p + + def _prune(self, targets): + """ + Prune operators and variables which are not needed to generate + :code:`targets`. + + Notes: This is a very low level API. Users should not use this API + directly. This API is in flux and not stable. + + Args: + targets(list|Variable|Operator): A list of variables, operators, or variable names + need to be pruned + + Returns: + Program: A new, pruned program. + """ + return self._prune_with_input([], targets) + + def _prune_with_input(self, feeded_var_names, targets): + """ + Prune operators and variables which are not needed to generate + :code:`targets`. Prune operators and variables which are needed + to generate feeded_var + + Notes: This is a very low level API. Users should not use this API + directly. This API is in flux and not stable. + + Args: + feeded_var_names(list|str): A list of variable names from where + pruning start. If it is set as [], this API works just like _prune() + targets(list|Variable|Operator): A list of variables, operators, or variable names + need to be pruned + + Returns: + Program: A new, pruned program. + """ + + # NOTE(zhiqiu): we sync the original program first, since its program may diff with + # its desc due to modifying desc in c++ space. E.g. save op will add kLookupTablePath in desc. + self._sync_with_cpp() + + if not isinstance(feeded_var_names, list): + feeded_var_names = [feeded_var_names] + if not isinstance(targets, list): + targets = [targets] + + for var in feeded_var_names: + if not isinstance(var, six.string_types): + raise ValueError( + "All feeded_var_names of Program._prune_with_input() can only be " + "str, but received %s." % type(var) + ) + + # find out all variables that can be generated or updated with given feed + generatable_vars = set() + + for idx, op in enumerate(self.global_block().ops): + runnable_op = True + for name in op.input_arg_names: + if not self.global_block().has_var(name): + continue + if self.global_block().var(name).persistable: + continue + if name not in generatable_vars.union(feeded_var_names): + runnable_op = False + break + if runnable_op: + generatable_vars = generatable_vars.union(op.output_arg_names) + + targets_idx = [] + for t in targets: + if not isinstance(t, Operator): + if isinstance(t, Variable): + name = t.name + elif isinstance(t, six.string_types): + name = str(t) + else: + raise ValueError( + "All targets of Program._prune_with_input() can only be " + "Variable or Operator, but received %s." % type(t) + ) + + # NOTEZ(zhiqiu): For variable to be fed in fetch_list, there two cases: + # (1) the variable is leaf, it has no op that generates it; + # (2) the variable is not leaf, and we need to prune the op that generates it. + # In both cases, wo can just skip target_op of that it. + if name in feeded_var_names: + # however if the var is also updated by a runnable op, will shall keep it + if name not in generatable_vars: + continue + + # After transpiler processing, the op that output this + # variable maybe has been changed, so t.op is not reliable + # and we need to find the current op that generate this + # variable here. + target_op = None + global_block = self.global_block() + for idx, op in enumerate(global_block.ops): + if name in op.output_arg_names: + # NOTE(zhiqiu): Find op that generate target name. + # Skip optimize op except for optimize op in targets, + # since optimize op generates parameters. + if op._is_optimize_op() and op not in targets: + continue + else: + target_op = op + + if target_op is not None: + targets_idx.append([target_op.block.idx, target_op.idx]) + else: + targets_idx.append([t.block.idx, t.idx]) + + res = Program() + res.desc, pruned_origin_block_id_map = core.prune( + self.desc, set(feeded_var_names), targets_idx + ) + res.blocks = [ + Block(res, i) for i in six.moves.range(res.desc.num_blocks()) + ] + res._sync_with_cpp() + + res._copy_param_info_from(self) + res._copy_data_info_from(self, pruned_origin_block_id_map) + res._copy_dist_param_info_from(self) + + return res + + def _inference_optimize(self, prune_read_op=True): + """ + This method will create a new program and do following adjustments on it: + 1. Remove all reader variables and their creator ops if exist. + + 2. Remove the :code:`read_op` if exists. + + 3. change the :code:`is_test` + attribute of operators to :code:`True`. All the :code:`Parameter` + information will be lost. + + Args: + prune_read_op(bool): remove the read ops that are added by py_reader + for cpp inference library + + Notes: This API is a very low level API. Use + :code:`Program.clone(for_test=True)` instead. + + Returns: + Program: The new program. + """ + res = Program() + res.desc = core.ProgramDesc(self.desc) + + # remove all readers and the read_op if exist + read_op_idx = 0 + root_block = res.desc.block(0) + if prune_read_op: + while True: + if ( + read_op_idx >= root_block.op_size() + or root_block.op(read_op_idx).type() == 'read' + ): + break + read_op_idx += 1 + if read_op_idx < root_block.op_size(): + root_block._remove_op(0, read_op_idx + 1) + for var in root_block.all_vars(): + if var.type() == core.VarDesc.VarType.READER: + root_block._remove_var(cpt.to_bytes(var.name())) + + # change all `is_test` attributes to True + for i in six.moves.range(res.desc.num_blocks()): + block = res.desc.block(i) + for j in six.moves.range(block.op_size()): + op = block.op(j) + if op.has_attr('is_test'): + op._set_bool_attr('is_test', True) + if op.type() == "batch_norm": + # Remove the output ReserveSpace of batch_norm if exists. + op.remove_output("ReserveSpace") + res.blocks = [ + Block(res, i) for i in six.moves.range(res.desc.num_blocks()) + ] + res._sync_with_cpp() + return res + + def _remove_training_info(self, clip_extra=True): + """ + This method will create a new program and do following adjustments on it: + 1. Remove all variable's `is_parameter` attribute if exist. + + 2. Remove all variable's `stop_gradient` attribute if exist. + + Notes: This API is a very low level API. + + Returns: + Program: The new program. + """ + res = Program() + res.desc = core.ProgramDesc(self.desc) + + res.blocks = [ + Block(res, i) for i in six.moves.range(res.desc.num_blocks()) + ] + res._sync_with_cpp() + + # Note: The op_role and op_role_var cann't be deleted currently, + # and we will try to remove them in the future. + common_clipped_attrs_list = ['op_callstack', 'with_quant_attr'] + + for i in six.moves.range(res.desc.num_blocks()): + block = res.desc.block(i) + for var in block.all_vars(): + var.clear_is_parameter() + var.clear_stop_gradient() + if not clip_extra: + continue + for op_idx in range(0, block.op_size()): + op = block.op(op_idx) + if op.type() not in OpProtoHolder.instance().op_proto_map: + continue + + extra_attrs_map = core.get_op_extra_attrs(op.type()) + + proto = OpProtoHolder.instance().get_op_proto(op.type()) + remove_input_list = [] + for name in op.input_names(): + find = False + for input_proto in proto.inputs: + if input_proto.name != name: + continue + if input_proto.extra: + remove_input_list.append(name) + find = True + break + if not find: + remove_input_list.append(name) + # The extra input of op will be removed in the future + # for name in remove_input_list: + # op.remove_input(name) + + remove_output_list = [] + for name in op.output_names(): + find = False + for output_proto in proto.outputs: + if output_proto.name != name: + continue + if output_proto.extra: + remove_output_list.append(name) + find = True + break + if not find: + remove_output_list.append(name) + # The extra output of op will be removed in the future + # for name in remove_output_list: + # op.remove_output(name) + + op_quant_name = ( + core.op_proto_and_checker_maker.kOpWithQuantAttrName() + ) + quant = ( + bool(op.attr(op_quant_name)) + if op_quant_name in op.attr_names() + else False + ) + quant_attrs = [ + op_quant_name, + "quantization_type", + "skip_quant", + "activation_bits", + "bit_length", + "quantize_weight_bits", + "weight_quant_scale", + ] + for extra_attr_name in extra_attrs_map.keys(): + op.remove_attr(extra_attr_name) + remove_attr_list = [] + for name in op.attr_names(): + if quant: + if name in quant_attrs: + continue + if name.endswith("_threshold"): + continue + if len(extra_attrs_map) > 0: + if name in common_clipped_attrs_list: + op.remove_attr(name) + continue + find = False + for attr_proto in proto.attrs: + if attr_proto.name != name: + continue + find = True + break + if not find: + remove_attr_list.append(name) + for name in remove_attr_list: + op.remove_attr(name) + return res + + @staticmethod + def parse_from_string(binary_str): + """ + .. note:: + 1. All information about parameters will be lost after serialization; + 2. This API has no effect in Dygraph mode. + + Deserialize a Program from `protobuf `_ binary string. + This method always use to save and load model + + Args: + + binary_str_type (str): the binary prootbuf string. + + Returns: + Program: A deserialized Program. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + startup_prog = static.Program() + main_prog = static.Program() + with static.program_guard(startup_prog, main_prog): + x = static.data(name='X', shape=[1000, 784], dtype='float32') + + y = static.data(name='Y', shape=[784, 100], dtype='float32') + + z = paddle.matmul(x=x, y=y) + + binary_str = static.default_main_program().desc.serialize_to_string() + prog_restored = static.default_main_program().parse_from_string(binary_str) + + print(static.default_main_program()) + print(prog_restored) + """ + p = Program() + p.desc = core.ProgramDesc(binary_str) + p.blocks = [Block(p, i) for i in six.moves.range(p.desc.num_blocks())] + p._sync_with_cpp() + return p + + @staticmethod + def _construct_from_desc(desc): + """ + Construct a program from program desc. + + Args: + desc(core.ProgramDesc): The program desc for constructing. + + Returns: + Program: A program. + """ + p = Program() + p.desc = desc + p.blocks = [Block(p, i) for i in six.moves.range(p.desc.num_blocks())] + p._sync_with_cpp() + return p + + @property + def random_seed(self): + """ + The default random seed for random operators in Program. ``0`` means get + the random seed from random device. + + .. note:: + It must be set before the operators have been added. + + Returns: + int64: Random seed in current Program + + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + import paddle.nn.functional as F + + paddle.enable_static() + + prog = static.default_main_program() + random_seed = prog.random_seed + x_var = static.data(name="X", shape=[3,3], dtype="float32") + print(random_seed) + ## 0 + ## the default random seed is 0 + + # Here we need to set random seed before we use paddle.nn.functional.dropout + prog.random_seed = 1 + z_var = F.dropout(x_var, 0.7) + + print(prog.random_seed) + ## 1 + ## the random seed is change to 1 + """ + return self._seed + + @property + def num_blocks(self): + """ + The number of :ref:`api_guide_Block_en` in this Program. + + .. note:: + This API has no effect in Dygraph mode. + + Returns: + int(Platform-dependent size): num of :ref:`api_guide_Block_en` in current Program + + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + num_blocks = prog.num_blocks + print(num_blocks) + + # print result: + # 1 + """ + return self.desc.num_blocks() + + @random_seed.setter + def random_seed(self, seed): + if not isinstance(seed, int): + raise ValueError( + "Program.random_seed's input seed must be an integer, but received %s." + % type(seed) + ) + self._seed = seed + + def __repr__(self): + return self.__str__() + + def global_block(self): + """ + .. note:: + This API has no effect in Dygraph mode. + + Get the first :ref:`api_guide_Block_en` of this Program. + + Returns: + :ref:`api_guide_Block_en`: The first :ref:`api_guide_Block_en` of this Program. + + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + gb_block = prog.global_block() + print(gb_block) + + """ + return self.blocks[0] + + def block(self, index): + """ + .. note:: + This API has no effect in Dygraph mode. + + Get the :code:`index` :ref:`api_guide_Block_en` of this Program + + Args: + index (int) - The index of :ref:`api_guide_Block_en` to get + + Returns: + :ref:`api_guide_Block_en`: The :code:`index` block + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + block_0 = prog.block(0) + print(block_0) + """ + return self.blocks[index] + + def current_block(self): + """ + .. note:: + This API has no effect in Dygraph mode. + + Get the current :ref:`api_guide_Block_en` . The :code:`current` :ref:`api_guide_Block_en` + is the :ref:`api_guide_Block_en` to append operators. + + Returns: + :ref:`api_guide_Block_en`: The :code:`index` :ref:`api_guide_Block_en` + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + current_blk = prog.current_block() + print(current_blk) + """ + return self.blocks[self.current_block_idx] + + def _create_block(self, parent_idx=None): + """ + Create a new block with the :code:`parent_idx` and change the current block + to new block. + + Args: + + parent_idx(int): The parent block index. + + Returns: + Block: The new block. + """ + new_block_idx = len(self.blocks) + parent = ( + self.current_block() + if parent_idx is None + else self.block(parent_idx) + ) + self.desc.append_block(parent.desc) + self.current_block_idx = new_block_idx + self.blocks.append(Block(self, self.current_block_idx)) + return self.current_block() + + def _rollback(self): + """ + Exit a code block, i.e., roll back to the parent block. + Returns: + None + """ + self.current_block_idx = self.current_block().parent_idx + + def _sync_with_cpp(self): + """ + Synchronize Python instance to its binding C++ object instance. + If the program is modified in C++ space, this method should be invoked. + + Notes: This is a very low level API. Users should not invoke it + directly. + + Returns: + None + """ + for block_idx in range(len(self.blocks), self.desc.num_blocks()): + self.blocks.append(Block(self, block_idx)) + for block in self.blocks: + block._sync_with_cpp() + + def _copy_param_info_from(self, other): + """ + Copy the information of parameters from other program. + + Notes: This is a very low level API. Users should not invoke it + directly. + + Args: + other(Program): Other program + + Returns: + None + """ + if not isinstance(other, Program): + raise TypeError( + "Function Program._copy_param_info_from() needs to pass in a source Program, but received %s" + % type(other) + ) + + self.global_block()._copy_param_info_from(other.global_block()) + + def _copy_dist_param_info_from(self, other): + """ + Copy the information of distributed information from other program. + + Args: + other(Program): Other program + + Returns: + None + """ + if not isinstance(other, Program): + raise TypeError( + "Function Program._copy_param_info_from() needs to pass in a source Program, but received %s" + % type(other) + ) + self._is_distributed = other._is_distributed + self._is_chief = other._is_chief + self._parameters_on_pservers = other._parameters_on_pservers + self._endpoints = other._endpoints + self._ps_endpoint = other._ps_endpoint + self._distributed_lookup_table = other._distributed_lookup_table + + def _copy_data_info_from(self, other, pruned_origin_block_id_map=None): + """ + Copy the information of data variables from other program. + + Notes: This is a very low level API. Users should not invoke it + directly. + + Args: + other(Program): Other program + pruned_origin_block_id_map(dict{int:int}): A dict which maps the block id in program + self to the block id in program other. For example, {0:0, 1:1, 2:3} means block 0 in self is + cloned from block 0 in other, etc. Default is None, which means default mapped, + {0:0, 1:1,..., n:n}. + + Returns: + None + """ + if not isinstance(other, Program): + raise TypeError( + "Function Program._copy_param_info_from() needs to pass in a source Program, but received %s" + % type(other) + ) + + if not pruned_origin_block_id_map: + pruned_origin_block_id_map = { + i: i for i in six.moves.range(self.desc.num_blocks()) + } + + # NOTE(zhiqiu): All vars in cloned program exist in original program. + # The reverse is not true, due to backward pruning. + for i, block in enumerate(self.blocks): + other_block = other.blocks[pruned_origin_block_id_map[i]] + for var in list(block.vars.values()): + other_var = other_block.var(var.name) + if other_var.is_data: + var.is_data = True + if other_var.desc.need_check_feed(): + var.desc.set_need_check_feed(True) + if other_var.stop_gradient: + var.stop_gradient = True + + def list_vars(self): + """ + Get all Tensors from this Program. A iterable object is returned. + + Returns: + iterable Tensors: The Generator will yield every Tensor in this program. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + prog = static.default_main_program() + img = static.data(name='img', shape=[None, 1,28,28], dtype='float32') + label = static.data(name='label', shape=[None,1], dtype='int64') + for var in prog.list_vars(): + print(var) + + # var img : LOD_TENSOR.shape(-1, 1, 28, 28).dtype(float32).stop_gradient(True) + # var label : LOD_TENSOR.shape(-1, 1).dtype(int64).stop_gradient(True) + """ + for each_block in self.blocks: + for each_var in list(each_block.vars.values()): + yield each_var + + def all_parameters(self): + """ + Get all :ref:`api_guide_parameter_en` from this Program. A list object is returned. + + Returns: + list[ :ref:`api_guide_parameter_en` ]: The list contians all parameters in this program. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + program = static.default_main_program() + data = static.data(name='x', shape=[None, 13], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + loss = paddle.mean(hidden) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + for param in program.all_parameters(): + print(param) + + # Here will print all parameters in current program, in this example, + # the result is like: + # + # persist trainable param fc_0.w_0 : LOD_TENSOR.shape(13, 10).dtype(float32).stop_gradient(False) + # persist trainable param fc_0.b_0 : LOD_TENSOR.shape(10,).dtype(float32).stop_gradient(False) + # + # Here print(param) will print out all the properties of a parameter, + # including name, type and persistable, you can access to specific + # property of a parameter, such as param.name, param.type + """ + parameters = [] + for each_block in self.blocks: + parameters.extend(each_block.all_parameters()) + return parameters + + def state_dict(self, mode='all', scope=None): + """ + Get parameters and persistable buffers of program as a dict. The key is the name of the parameter or the name of the buffer. + The value is the tensor of this variable in the given scope. + + .. note:: + This function MUST called after run start_up_program + + Args: + mode(str, optional): Source of the obtained parameters and buffers. + 'opt' : The return value only contains the variable in the optimizer. + 'param' : The return value only contains the variable in the network, not the variable in the optimizer. + 'all' : The return value contains the variable in the network and optimizer. + Default: 'all' + scope(Scope, optional) : If scope is None, state_dict will be set to global scope + obtained through 'paddle.static.global_scope()'. Otherwise, value will be set to scope. + Default: None + + Retruns: + dict: a dict contains the parameters and persistable buffers. + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + path = "./temp/model.pdparams" + paddle.save(prog.state_dict(), path) + """ + # The 'framework' is a low-level module, and 'executor' + # can not be imported at the begainning of this file. + # Therefore, the above two modules are dynamically imported. + from .executor import global_scope + + if scope is not None and not isinstance(scope, core._Scope): + raise TypeError( + "`scope` should be None or `paddle.static.Scope'` type, but received {}.".format( + type(scope) + ) + ) + + if scope is None: + scope = global_scope() + + if not isinstance(mode, str): + raise TypeError( + "Type of `mode` should be string, but received {}.".format( + type(mode) + ) + ) + + def is_parameter(var): + return isinstance(var, Parameter) + + def is_persistable(var): + if ( + var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH + or var.desc.type() == core.VarDesc.VarType.FETCH_LIST + or var.desc.type() == core.VarDesc.VarType.READER + ): + return False + return var.persistable + + def is_belong_to_optimizer(var): + if not (isinstance(var, Parameter) or var.desc.need_check_feed()): + return is_persistable(var) + return False + + def condition(var): + + if mode == 'param': + return is_parameter(var) + elif mode == 'opt': + return is_belong_to_optimizer(var) + elif mode == 'all': + return is_parameter(var) or is_belong_to_optimizer(var) + else: + raise ValueError( + "`mode` string should be 'param', 'opt' or 'all', but received {}.".format( + mode + ) + ) + + var_list = filter(condition, self.list_vars()) + + state_dict = dict() + for var in var_list: + var_temp = scope.find_var(var.name) + if var_temp is None: + raise ValueError( + "Can not find Variable '{}' in the scope. Make sure it is initialized".format( + var.name + ) + ) + state_dict[var.name] = var_temp.get_tensor() + + return state_dict + + def set_state_dict(self, state_dict, scope=None): + """ + Set parameters and persistable buffers in state_dict to program. + An exception will throw if shape or dtype of the parameters is not match. + + .. note:: + This function MUST called after run start_up_program + + Args: + state_dict(dict): the dict store parameters and persistable buffers. + The key is the name of the parameter or the name of the buffer. + The value is the tensor of this variable in the given scope. + scope(Scope, optional) : If scope is None, state_dict will be set to global scope + obtained through 'paddle.static.global_scope()'. Otherwise, value will be set to scope. + Default: None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + path = "./temp/model.pdparams" + paddle.save(prog.state_dict(), path) + state_dict_load = paddle.load(path) + prog.set_state_dict(state_dict_load) + """ + + if not isinstance(state_dict, dict): + raise TypeError( + "Type of `state_dict` should be dict, but received {}.".format( + type(state_dict) + ) + ) + + vars_dict = {var.name: var for var in self.list_vars()} + condition = ( + True if 'StructuredToParameterName@@' in state_dict else False + ) + for name, value in state_dict.items(): + if condition: + if name == "StructuredToParameterName@@": + continue + if name in state_dict['StructuredToParameterName@@']: + name = state_dict['StructuredToParameterName@@'][name] + if name in vars_dict: + try: + vars_dict[name].set_value(value, scope) + except ValueError as err: + warnings.warn( + ("Skip loading for '{}'. ".format(name) + str(err)) + ) + except TypeError as err: + warnings.warn( + ("Skip loading for '{}'. ".format(name) + str(err)) + ) + else: + warnings.warn( + ( + "Skip loading for '{0}'. Because '{0}' not in the program.".format( + name + ) + ) + ) + + +@six.add_metaclass(ParameterMetaClass) +class Parameter(Variable): + """ + Parameter is derived from Variable. A parameter is a persistable + Variable, and will be updated by optimizers after each iteration. + The training of a neural network is essentially the updating of + its parameters. + + Relative to a general Variable, a Parameter has several its own + member variables: + + Args: + trainable(bool): True if the parameter need to be updated after + iterations. + optimize_attr(map): Parameter attributes related with optimizing. + Currently, it only contains 'learning_rate'. + Default: {'learning_rate': 1.0} + regularizer(WeightDecayRegularizer): The Regularizer which will + be applied on the parameter. Default: None + do_model_average(bool): True if the model average strategy will + be applied on this parameter. + need_clip (bool): Whether the parameter gradient need to be cliped + in optimizer. Default is True. + """ + + def __init__( + self, + block, + shape, + dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + **kwargs + ): + if shape is None: + raise ValueError("The shape of Parameter should not be None") + if dtype is None: + raise ValueError("The dtype of Parameter should not be None") + + if len(shape) == 0: + raise ValueError( + "The dimensions of shape for Parameter must be greater than 0" + ) + + for each in shape: + if each < 0: + raise ValueError( + "Each dimension of shape for Parameter must be greater than 0, but received %s" + % list(shape) + ) + + Variable.__init__( + self, + block, + persistable=True, + shape=shape, + dtype=dtype, + type=type, + **kwargs + ) + self.trainable = kwargs.get('trainable', True) + + self.optimize_attr = kwargs.get('optimize_attr', {'learning_rate': 1.0}) + + self.regularizer = kwargs.get('regularizer', None) + + self.do_model_average = kwargs.get('do_model_average', None) + + self.need_clip = kwargs.get('need_clip', True) + + self.is_distributed = False + + self.is_parameter = True + + def __str__(self): + return self._to_readable_code() + + def to_string(self, throw_on_error, with_details=False): + """ + To debug string. + + Args: + throw_on_error(bool): raise exception when self is not initialized + when throw_on_error is True + with_details(bool): more details about variables and parameters + (e.g. trainable, optimize_attr, ...) will be printed when with_details is True + + Returns(str): The debug string. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + prog = fluid.default_main_program() + rlt = fluid.layers.data("fake_data", shape=[1,1], dtype='float32') + debug_str = prog.to_string(throw_on_error=True, with_details=False) + print(debug_str) + """ + assert isinstance(throw_on_error, bool) and isinstance( + with_details, bool + ) + if with_details: + res_str = Variable.to_string(self, throw_on_error, True) + additional_attr = ( + "trainable", + "optimize_attr", + "regularizer", + "do_model_average", + "need_clip", + ) + for attr_name in additional_attr: + res_str += "%s: %s\n" % ( + attr_name, + cpt.to_text(getattr(self, attr_name)), + ) + else: + res_str = Variable.to_string(self, throw_on_error, False) + return res_str + + __repr__ = __str__ + + +class ParamBase(core.VarBase): + """ + ParamBase is derived from Tensor( Which is the concept in Dygraph Mode). + A ParamBase is a persistable Tensor, and will be updated by optimizers + after each iteration. + The training of a neural network is essentially the updating of + its ParamBase. + + Relative to a general Tensor, a ParamBase has several its own + member variables: + + Args: + trainable(bool): True if the ParamBase need to be updated after + iterations. + optimize_attr(map): ParamBase attributes related with optimizing. + Currently, it only contains 'learning_rate'. + Default: {'learning_rate': 1.0} + regularizer(WeightDecayRegularizer): The Regularizer which will + be applied on the ParamBase. Default: None + do_model_average(bool): True if the model average strategy will + be applied on this ParamBase. + need_clip (bool): Whether the parameter gradient need to be cliped + in optimizer. Default is True. + """ + + @dygraph_only + def __init__(self, shape, dtype, **kwargs): + if shape is None: + raise ValueError("The shape of Parameter should not be None") + if dtype is None: + raise ValueError("The dtype of Parameter should not be None") + + if len(shape) == 0: + raise ValueError( + "The dimensions of shape for Parameter must be greater than 0" + ) + + for each in shape: + if each < 0: + raise ValueError( + "Each dimension of shape for Parameter must be greater than 0, but received %s" + % list(shape) + ) + + if dtype is not None: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + name = kwargs.get('name', unique_name.generate('_param_base')) + + super(ParamBase, self).__init__( + dtype if dtype else core.VarDesc.VarType.FP32, + list(shape) if shape else [], + name, + core.VarDesc.VarType.LOD_TENSOR, + True, + ) + + trainable = kwargs.get('trainable', True) + self.stop_gradient = not trainable + + self.optimize_attr = kwargs.get('optimize_attr', {'learning_rate': 1.0}) + + self.regularizer = kwargs.get('regularizer', None) + + self.do_model_average = kwargs.get('do_model_average', None) + + self.need_clip = kwargs.get('need_clip', True) + + self.is_distributed = kwargs.get('is_distributed', False) + # self.block = default_main_program().global_block() + + @property + def trainable(self): + return not self.stop_gradient + + @trainable.setter + def trainable(self, trainable): + if isinstance(trainable, bool): + self.stop_gradient = not trainable + else: + raise ValueError( + "The type of trainable MUST be bool, but the type is ", + type(trainable), + ) + + def __str__(self): + """ + Convert a ParamBase object to a readable string. + + Returns(str): A readable string. + + Examples: + .. code-block:: python + + import paddle + linear = paddle.nn.Linear(3, 3) + print(linear.weight) + # Parameter containing: + # Tensor(shape=[3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [[ 0.48948765, 0.05829060, -0.25524026], + # [-0.70368278, 0.52986908, -0.68742192], + # [-0.54217887, 0.48439729, 0.34082305]]) + """ + return "Parameter containing:\n{tensor}".format( + tensor=super(ParamBase, self).__str__() + ) + + def __deepcopy__(self, memo): + """ + Deep copy parameter, it will always performs Tensor copy. + + Examples: + .. code-block:: python + + import paddle + import copy + linear = paddle.nn.Linear(1, 3) + linear_copy = copy.deepcopy(linear) + + print(linear.weight) + # Parameter containing: + # Tensor(shape=[1, 3], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[-0.30929261, -0.90929240, -1.07851017]]) + + print(linear_copy.weight) + # Parameter containing: + # Tensor(shape=[1, 3], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[-0.30929261, -0.90929240, -1.07851017]]) + + """ + state = copy.deepcopy(self.__dict__, memo) + state["name"] = self.name + unique_name.generate("_deepcopy") + new_param = ParamBase(self.shape, self.dtype, **state) + memo[id(self)] = new_param + new_param.copy_(self, True) + return new_param + + def _copy_to(self, device, blocking): + state = copy.deepcopy(self.__dict__) + new_param = ParamBase(self.shape, self.dtype, **state) + core.varbase_copy(self, new_param, device, blocking) + return new_param + + __repr__ = __str__ + + +if hasattr(core, "eager"): + _core_eager_eagertensor = core.eager.Tensor +else: + _core_eager_eagertensor = object + + +class EagerParamBase(_core_eager_eagertensor): + """ + EagerParamBase is derived from Tensor( Which is the concept in Eager-Dygraph Mode). + A EagerParamBase is a persistable Tensor, and will be updated by optimizers + after each iteration. + The training of a neural network is essentially the updating of + its EagerParamBase. + + Relative to a general Tensor, a EagerParamBase has several its own + member variables: + + Args: + trainable(bool): True if the EagerParamBase need to be updated after + iterations. + optimize_attr(map): EagerParamBase attributes related with optimizing. + Currently, it only contains 'learning_rate'. + Default: {'learning_rate': 1.0} + regularizer(WeightDecayRegularizer): The Regularizer which will + be applied on the EagerParamBase. Default: None + do_model_average(bool): True if the model average strategy will + be applied on this EagerParamBase. + need_clip (bool): Whether the parameter gradient need to be cliped + in optimizer. Default is True. + """ + + @dygraph_only + def __init__(self, shape, dtype, **kwargs): + if shape is None: + raise ValueError("The shape of Parameter should not be None") + if dtype is None: + raise ValueError("The dtype of Parameter should not be None") + + if len(shape) == 0: + raise ValueError( + "The dimensions of shape for Parameter must be greater than 0" + ) + + for each in shape: + if each < 0: + raise ValueError( + "Each dimension of shape for Parameter must be greater than 0, but received %s" + % list(shape) + ) + + if dtype is not None: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + name = kwargs.get('name', unique_name.generate('_eager_param_base')) + + if isinstance(shape, core.eager.Tensor): + shape = shape.numpy() + + super(EagerParamBase, self).__init__( + dtype if dtype else core.VarDesc.VarType.FP32, + list(shape) if shape else [], + name, + core.VarDesc.VarType.LOD_TENSOR, + True, + ) + self.retain_grads() + + trainable = kwargs.get('trainable', True) + self.stop_gradient = not trainable + + self.optimize_attr = kwargs.get('optimize_attr', {'learning_rate': 1.0}) + + self.regularizer = kwargs.get('regularizer', None) + + self.do_model_average = kwargs.get('do_model_average', None) + + self.need_clip = kwargs.get('need_clip', True) + + self.is_distributed = kwargs.get('is_distributed', False) + # hook functions for lazy initialization + self._init_func = None + self._init_op_creator = None + + def set_init_func(self, obj): + self._init_func = obj + + @dygraph_only + def initialize(self): + assert ( + self._init_func is not None + ), "Required self._init_func is not None, but received None." + self._init_func() + # clear function handle to release resource + self._init_func = None + + @property + def trainable(self): + return not self.stop_gradient + + @trainable.setter + def trainable(self, trainable): + if isinstance(trainable, bool): + self.stop_gradient = not trainable + else: + raise ValueError( + "The type of trainable MUST be bool, but the type is ", + type(trainable), + ) + + def _create_init_op(self, block): + """ + Call init_op_creator function to create initializer operation in block. + """ + assert ( + self._init_op_creator is not None + ), "Required self._init_op_creator is not None, but received None." + self._init_op_creator(block) + + def __str__(self): + """ + Convert a EagerParamBase object to a readable string. + + Returns(str): A readable string. + + Examples: + .. code-block:: python + + import paddle + linear = paddle.nn.Linear(3, 3) + print(linear.weight) + # Parameter containing: + # Tensor(shape=[3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [[ 0.48948765, 0.05829060, -0.25524026], + # [-0.70368278, 0.52986908, -0.68742192], + # [-0.54217887, 0.48439729, 0.34082305]]) + """ + return "Parameter containing:\n{tensor}".format( + tensor=super(EagerParamBase, self).__str__() + ) + + def __deepcopy__(self, memo): + """ + Deep copy parameter, it will always performs Tensor copy. + + Examples: + .. code-block:: python + + import paddle + import copy + linear = paddle.nn.Linear(1, 3) + linear_copy = copy.deepcopy(linear) + + print(linear.weight) + # Parameter containing: + # Tensor(shape=[1, 3], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[-0.30929261, -0.90929240, -1.07851017]]) + + print(linear_copy.weight) + # Parameter containing: + # Tensor(shape=[1, 3], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[-0.30929261, -0.90929240, -1.07851017]]) + + """ + state = copy.deepcopy(self.__dict__, memo) + state["name"] = self.name + unique_name.generate("_deepcopy") + new_param = EagerParamBase(self.shape, self.dtype, **state) + memo[id(self)] = new_param + new_param.copy_(self, True) + return new_param + + def _copy_to(self, device, blocking): + state = copy.deepcopy(self.__dict__) + new_param = EagerParamBase(self.shape, self.dtype, **state) + core.eager.tensor_copy(self, new_param, device, blocking) + return new_param + + __repr__ = __str__ + + +# program is a global instance. +_main_program_ = Program() +_startup_program_ = Program() +_startup_program_._is_start_up_program_ = True + + +def default_startup_program(): + """ + Get default/global startup program. + + The :code:`paddle.nn` function will append the initialization operators into startup program. + The :code:`startup_program` will initialize the parameters by the OPs. + + This method will return the default or the current startup program. Users can use + :ref:`api_paddle_fluid_framework_program_guard` to switch :ref:`api_paddle_fluid_framework_Program` . + + Returns: + Program: current default startup program. + + Returns type: + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + x = paddle.static.data(name="x", shape=[-1, 784], dtype='float32') + out = paddle.static.nn.fc(name="fc", x=x, size=10, activation="relu") + print("main program is: {}".format(paddle.static.default_main_program())) + print("start up program is: {}".format(paddle.static.default_startup_program())) + """ + return _startup_program_ + + +def default_main_program(): + """ + This API can be used to get ``default main program`` which store the + descriptions of Ops and tensors. + + For example ``z = paddle.add(x, y)`` will create a new ``add`` + Op and a new ``z`` tensor, and they will be recorded in ``default main program`` . + + The ``default main program`` is the default value for ``Program`` parameter in + a lot of APIs. For example, the :code:`Executor.run()` will execute the + :code:`default_main_program` when the program is not specified. + + If you want to switch the ``default main program``, you can use :ref:`api_paddle_fluid_framework_program_guard` . + + Returns: + Program: A ``Program`` which holding the descriptions of OPs and tensors in the network. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + # Sample Network: + x = paddle.static.data(name='x', shape=[100, 100], dtype='float32') + y = paddle.static.data(name='x', shape=[100, 100], dtype='float32') + out = paddle.add(x, y) + + #print the number of blocks in the program, 1 in this case + print(paddle.static.default_main_program().num_blocks) # 1 + #print the default_main_program + print(paddle.static.default_main_program()) + """ + return _main_program_ + + +def switch_main_program(program): + """ + Switch the main program to a new program. + + Args: + program(Program): The new main program + + Returns: + Program: The previous main program + """ + global _main_program_ + prev_program = _main_program_ + _main_program_ = program + return prev_program + + +def switch_startup_program(program): + """ + Switch the startup program to a new program + Args: + program(Program): The new startup program + + Returns: + Program: The previous startup program + """ + global _startup_program_ + prev_program = _startup_program_ + _startup_program_ = program + return prev_program + + +@signature_safe_contextmanager +def program_guard(main_program, startup_program=None): + """ + :api_attr: Static Graph + + Change the global main program and startup program with ``with`` statement. + Layer functions in the Python ``with`` block will append operators and + Tensors to the new main programs. + + Args: + main_program(Program): New main program inside ``with`` statement. + startup_program(Program, optional): New startup program inside ``with`` + statement. :code:`None` means not changing startup program, + default_startup_program is still used. + Default: None. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + main_program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(main_program, startup_program): + data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') + hidden = paddle.static.nn.fc(x=data, size=10, activation='relu') + + Notes: The temporary :code:`Program` can be used if the user does not need + to construct either of startup program or main program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + main_program = paddle.static.Program() + # does not care about startup program. Just pass a temporary value. + with paddle.static.program_guard(main_program, paddle.static.Program()): + data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') + + """ + from .data_feeder import check_type + + check_type( + main_program, 'main_program', Program, 'paddle.static.program_guard' + ) + main_program = switch_main_program(main_program) + if startup_program is not None: + check_type( + startup_program, + 'startup_program', + Program, + 'paddle.static.program_guard', + ) + # Tag the program __is_start_up as True + startup_program._is_start_up_program_ = True + startup_program = switch_startup_program(startup_program) + try: + yield + finally: + switch_main_program(main_program) + if startup_program is not None: + switch_startup_program(startup_program) + + +def _get_var(name, program=None): + """ + Get a variable by name from the global block of a program. + + Args: + name(str): name of the variable + program(Program|None): program object. + If None, default_global_program() will be used. + + Returns: + Variable + """ + if program is None: + program = default_main_program() + assert isinstance(name, str) + assert isinstance(program, Program) + + return program.global_block().var(name) + + +@signature_safe_contextmanager +def _dygraph_guard(tracer): + global _dygraph_tracer_ + tmp_tracer = _dygraph_tracer_ + _dygraph_tracer_ = tracer + core._switch_tracer(tracer) + + try: + yield + finally: + core._switch_tracer(tmp_tracer) + _dygraph_tracer_ = tmp_tracer + + +@signature_safe_contextmanager +def _dygraph_place_guard(place): + global _global_expected_place_ + tmp_place = _global_expected_place_ + _global_expected_place_ = place + _set_dygraph_tracer_expected_place(place) + + try: + yield + finally: + _global_expected_place_ = tmp_place + _set_dygraph_tracer_expected_place(_global_expected_place_) + + +def switch_device(device): + global _current_device + pre_device = _current_device + _current_device = device + return pre_device + + +@signature_safe_contextmanager +def device_guard(device=None): + """ + + Note: + The API only supports static mode. + + A context manager that specifies the device on which the OP will be placed. + + Args: + device(str|None): Specify the device to use in the context. It should be ``cpu``, + ``gpu`` or ``gpu:x``, where ``x`` is the index of the GPUs. + When it is set to 'cpu' or 'gpu', all OPs created in the context will be + placed on CPUPlace or CUDAPlace. When 'gpu' is set and the program runs on + single-card, the device index will be the same as the device on which the + executor runs. Default: None, OPs in this context will be automatically + assigned devices. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + paddle.enable_static() + support_gpu = paddle.is_compiled_with_cuda() + place = paddle.CPUPlace() + if support_gpu: + place = paddle.CUDAPlace(0) + + # if GPU is supported, the three OPs below will be automatically assigned to CUDAPlace(0) + data1 = paddle.full(shape=[1, 3, 8, 8], fill_value=0.5, dtype='float32') + data2 = paddle.full(shape=[1, 3, 64], fill_value=0.5, dtype='float32') + shape = paddle.shape(data2) + + with paddle.static.device_guard("cpu"): + # Ops created here will be placed on CPUPlace + shape = paddle.slice(shape, axes=[0], starts=[0], ends=[4]) + with paddle.static.device_guard('gpu'): + # if GPU is supported, OPs created here will be placed on CUDAPlace(0), otherwise on CPUPlace + out = paddle.reshape(data1, shape=shape) + + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + result = exe.run(fetch_list=[out]) + """ + + index = None + if device and ':' in device: + device, index = device.split(':') + if device == 'cpu': + raise ValueError("Should not set device id for cpu.") + if device not in ['cpu', 'gpu', 'npu', 'xpu', 'mlu', '', None]: + raise ValueError( + "The Attr(device) should be 'cpu' 'npu' 'xpu' 'mlu' or 'gpu', and it can also be empty string or None " + "when there is no need to specify device. But received %s" % device + ) + if index: + device = ":".join([device, index]) + pre_device = switch_device(device) + try: + yield + finally: + switch_device(pre_device) + + +def _switch_cuda_graph_mode(cuda_graph_attr): + global _current_cuda_graph_mode + pre_mode = _current_cuda_graph_mode + _current_cuda_graph_mode = cuda_graph_attr + return pre_mode + + +@signature_safe_contextmanager +def _cuda_graph_guard(cuda_graph_attr=None): + """ + + Note: + The API only supports static mode. + + A context manager that specifies the cuda_graph_mode which indicating the cuda graph capture under static mode. + + Args: + cuda_graph_attr(str|None): The cuda graph attr with the format of: + cuda_graph_capture_mode;memory_pool_id;cuda_graph_id + """ + assert ( + not _non_static_mode() + ), "cuda_graph_guard only works under static mode" + assert ( + core.is_compiled_with_cuda() + ), "cuda_graph_guard context can be only used when Paddle is compiled with cuda" + pre_mode = _switch_cuda_graph_mode(cuda_graph_attr) + try: + yield + finally: + _switch_cuda_graph_mode(pre_mode) + + +def set_flags(flags): + """ + This function sets the GFlags value in Paddle. + For FLAGS please refer to :ref:`en_guides_flags_flags` + + Args: + flags (dict): A dict contains flags and its value. + + Examples: + .. code-block:: python + + import paddle + paddle.set_flags({'FLAGS_eager_delete_tensor_gb': 1.0}) + """ + if not isinstance(flags, dict): + raise TypeError('flags in set_flags should be a dict') + for key, value in flags.items(): + if _global_flags().is_public(key): + _global_flags()[key] = value + else: + raise ValueError( + "Flag %s cannot set its value through this function." % (key) + ) + + +def get_flags(flags): + """ + This function gets the GFlags value in Paddle. + For FLAGS please refer to :ref:`en_guides_flags_flags` + + Args: + flags(list|tuple|str): A list/tuple of string or a string which is the flag's name. + + Returns: + flag's value in Paddle. + + Examples: + .. code-block:: python + + import paddle + + flags = ['FLAGS_eager_delete_tensor_gb', 'FLAGS_check_nan_inf'] + res = paddle.get_flags(flags) + print(res) + # {'FLAGS_eager_delete_tensor_gb': 0.0, 'FLAGS_check_nan_inf': False} + """ + flags_value = {} + if isinstance(flags, (list, tuple)): + for key in flags: + if _global_flags().is_public(key): + value = _global_flags()[key] + temp = {key: value} + flags_value.update(temp) + else: + raise ValueError( + 'Flag %s cannot get its value through this function.' + % (key) + ) + elif isinstance(flags, str): + if _global_flags().is_public(flags): + value = _global_flags()[flags] + temp = {flags: value} + flags_value.update(temp) + else: + raise ValueError( + 'Flag %s cannot get its value through this function.' % (flags) + ) + else: + raise TypeError('Flags in get_flags should be a list, tuple or string.') + return flags_value + + +def _get_paddle_place(place): + "convert the string to paddle Place" + if place is None: + return place + if isinstance( + place, + ( + core.Place, + core.XPUPlace, + core.CPUPlace, + core.CUDAPinnedPlace, + core.CUDAPlace, + core.NPUPlace, + core.IPUPlace, + core.MLUPlace, + core.CustomPlace, + ), + ): + return place + + if not isinstance(place, str): + raise ValueError( + "place only support string which is 'Place' and so on." + ) + + place = place.lower() + if place == "cpu": + return core.CPUPlace() + + if place == "device": + return core.Place() + + # GPU + avaliable_gpu_place = re.match(r'gpu:\d+', place) + if place == "gpu_pinned" or place == "gpu" or avaliable_gpu_place: + if not core.is_compiled_with_cuda(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with CUDA".format(avaliable_gpu_place) + ) + if place == "gpu_pinned": + return core.CUDAPinnedPlace() + elif place == "gpu": + return core.CUDAPlace(0) + else: + place_info_list = place.split(':', 1) + device_id = place_info_list[1] + device_id = int(device_id) + return core.CUDAPlace(device_id) + + # XPU + avaliable_xpu_place = re.match(r'xpu:\d+', place) + if avaliable_xpu_place: + if not core.is_compiled_with_xpu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with XPU".format(avaliable_xpu_place) + ) + place_info_list = place.split(':', 1) + device_id = place_info_list[1] + device_id = int(device_id) + return core.XPUPlace(device_id) + + # NPU + avaliable_npu_place = re.match(r'npu:\d+', place) + if avaliable_npu_place: + if not core.is_compiled_with_npu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with NPU".format(avaliable_npu_place) + ) + place_info_list = place.split(':', 1) + device_id = place_info_list[1] + device_id = int(device_id) + return core.NPUPlace(device_id) + + # IPU + avaliable_ipu_place = re.match(r'ipu:\d+', place) + if avaliable_ipu_place: + if not core.is_compiled_with_ipu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with IPU".format(avaliable_ipu_place) + ) + place_info_list = place.split(':', 1) + device_id = place_info_list[1] + device_id = int(device_id) + return core.IPUPlace(device_id) + + # MLU + avaliable_mlu_place = re.match(r'mlu:\d+', place) + if avaliable_mlu_place: + if not core.is_compiled_with_mlu(): + raise ValueError( + "The device should not be {}, since PaddlePaddle is " + "not compiled with MLU".format(avaliable_mlu_place) + ) + place_info_list = place.split(':', 1) + device_id = place_info_list[1] + device_id = int(device_id) + return core.MLUPlace(device_id) + + raise ValueError( + "Paddle supports CPUPlace, CUDAPlace,CUDAPinnedPlace, XPUPlace, IPUPlace, MLUPlace and NPUPlace, but received {}.".format( + place + ) + ) + + +def _get_paddle_place_list(places): + + if not isinstance(places, (list, tuple)): + raise TypeError("places must to be List or Tuple") + + ret = [] + for p in places: + p = _get_paddle_place(p) + ret.append(p) + + return ret diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/generator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce2d6a4bf3d92aff83e3f0e5b6979d01c5a204f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/generator.py @@ -0,0 +1,46 @@ +# 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. +"""This is definition of generator class, which is for managing the state of the algorithm that produces pseudo random numbers.""" + +from . import core +from .framework import _get_paddle_place + +__all__ = ['Generator'] + + +class Generator(core.Generator): + """Generator class""" + + def __init__(self, place=None): + """ + Create a generator object which manages the random number generation. ( Experimental Feature ) + + Parameters: + place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str,optional): The place to allocate Tensor. Can be + CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is + string, it can be ``cpu`` and ``gpu:x``, where ``x`` is the index of the GPUs. + + Returns: + Generator: A generator object. + + """ + self.place = _get_paddle_place(place) + if not place: + place = core.CPUPlace() + if isinstance(place, core.CPUPlace): + super(Generator, self).__init__() + else: + raise ValueError( + "Generator class with %s does is not supported yet, currently only support generator with CPUPlace " + % place) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/graphviz.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/graphviz.py new file mode 100644 index 0000000000000000000000000000000000000000..798c9914b79ca6da72cf662afa6d76c7b310ec0a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/graphviz.py @@ -0,0 +1,270 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import os +import random +import six +import functools +import subprocess +import logging + + +def crepr(v): + if isinstance(v, six.string_types): + return '"%s"' % v + return str(v) + + +class Rank(object): + + def __init__(self, kind, name, priority): + ''' + kind: str + name: str + priority: int + ''' + self.kind = kind + self.name = name + self.priority = priority + self.nodes = [] + + def __str__(self): + if not self.nodes: + return '' + + return '{' + 'rank={};'.format(self.kind) + \ + ','.join([node.name for node in self.nodes]) + '}' + + +class Graph(object): + rank_counter = 0 + + def __init__(self, title, **attrs): + self.title = title + self.attrs = attrs + self.nodes = [] + self.edges = [] + self.rank_groups = {} + + def code(self): + return self.__str__() + + def rank_group(self, kind, priority): + name = "rankgroup-%d" % Graph.rank_counter + Graph.rank_counter += 1 + rank = Rank(kind, name, priority) + self.rank_groups[name] = rank + return name + + def node(self, label, prefix, description="", **attrs): + node = Node(label, prefix, description, **attrs) + + if 'rank' in attrs: + rank = self.rank_groups[attrs['rank']] + del attrs['rank'] + rank.nodes.append(node) + self.nodes.append(node) + return node + + def edge(self, source, target, **attrs): + edge = Edge(source, target, **attrs) + self.edges.append(edge) + return edge + + def compile(self, dot_path): + file = open(dot_path, 'w') + file.write(self.__str__()) + image_path = os.path.join(os.path.dirname(dot_path), + dot_path[:-3] + "pdf") + cmd = ["dot", "-Tpdf", dot_path, "-o", image_path] + subprocess.Popen(cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + logging.warning("write block debug graph to {}".format(image_path)) + return image_path + + def show(self, dot_path): + image = self.compile(dot_path) + cmd = ["open", image] + subprocess.Popen(cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + def _rank_repr(self): + ranks = sorted(six.iteritems(self.rank_groups), + key=functools.cmp_to_key( + lambda a, b: a[1].priority > b[1].priority)) + repr = [] + for x in ranks: + repr.append(str(x[1])) + return '\n'.join(repr) + '\n' + + def __str__(self): + reprs = [ + 'digraph G {', + 'title = {}'.format(crepr(self.title)), + ] + + for attr in self.attrs: + reprs.append("{key}={value};".format(key=attr, + value=crepr(self.attrs[attr]))) + + reprs.append(self._rank_repr()) + + random.shuffle(self.nodes) + reprs += [str(node) for node in self.nodes] + + for x in self.edges: + reprs.append(str(x)) + + reprs.append('}') + return '\n'.join(reprs) + + +class Node(object): + counter = 1 + + def __init__(self, label, prefix, description="", **attrs): + self.label = label + self.name = "%s_%d" % (prefix, Node.counter) + self.description = description + self.attrs = attrs + Node.counter += 1 + + def __str__(self): + reprs = '{name} [label={label} {extra} ];'.format( + name=self.name, + label=self.label, + extra=',' + ','.join("%s=%s" % (key, crepr(value)) + for key, value in six.iteritems(self.attrs)) + if self.attrs else "") + return reprs + + +class Edge(object): + + def __init__(self, source, target, **attrs): + ''' + Link source to target. + :param source: Node + :param target: Node + :param graph: Graph + :param attrs: dic + ''' + self.source = source + self.target = target + self.attrs = attrs + + def __str__(self): + repr = "{source} -> {target} {extra}".format( + source=self.source.name, + target=self.target.name, + extra="" if not self.attrs else "[" + + ','.join("{}={}".format(attr[0], crepr(attr[1])) + for attr in six.iteritems(self.attrs)) + "]") + return repr + + +class GraphPreviewGenerator(object): + ''' + Generate a graph image for ONNX proto. + ''' + + def __init__(self, title): + # init graphviz graph + self.graph = Graph( + title, + layout="dot", + concentrate="true", + rankdir="TB", + ) + + self.op_rank = self.graph.rank_group('same', 2) + self.param_rank = self.graph.rank_group('same', 1) + self.arg_rank = self.graph.rank_group('same', 0) + + def __call__(self, path='temp.dot', show=False): + if not show: + self.graph.compile(path) + else: + self.graph.show(path) + + def add_param(self, name, data_type, highlight=False): + label = '\n'.join([ + '<', + ' ', + ' ', + ' ', + ' ', + ' ' + ' ', + '
', + ' ', + name, + ' ', + '
', + str(data_type), + '
>', + ]) + return self.graph.node(label, + prefix="param", + description=name, + shape="none", + style="rounded,filled,bold", + width="1.3", + color="#148b97" if not highlight else "orange", + fontcolor="#ffffff", + fontname="Arial") + + def add_op(self, opType, **kwargs): + highlight = False + if 'highlight' in kwargs: + highlight = kwargs['highlight'] + del kwargs['highlight'] + return self.graph.node( + "<%s>" % opType, + prefix="op", + description=opType, + shape="box", + style="rounded, filled, bold", + color="#303A3A" if not highlight else "orange", + fontname="Arial", + fontcolor="#ffffff", + width="1.3", + height="0.84", + ) + + def add_arg(self, name, highlight=False): + return self.graph.node(crepr(name), + prefix="arg", + description=name, + shape="box", + style="rounded,filled,bold", + fontname="Arial", + fontcolor="#999999", + color="#dddddd" if not highlight else "orange") + + def add_edge(self, source, target, **kwargs): + highlight = False + if 'highlight' in kwargs: + highlight = kwargs['highlight'] + del kwargs['highlight'] + return self.graph.edge(source, + target, + color="#00000" if not highlight else "orange", + **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76c5c6391fde3cafbd9a94e1d11e0ef4401420ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/__init__.py @@ -0,0 +1,17 @@ +# 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 + +# incubate directory is mainly for internal use +# after we have tested incubate APIs in industrial application for a period +# we will move stable functions into fluid +__version__ = '0.1.0' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abf198b97e6e818e1fbe59006f98492640bcee54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/auto_checkpoint.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/auto_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..b5dd3222b8ff5c9b3281178141191747b7e7ee56 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/auto_checkpoint.py @@ -0,0 +1,685 @@ +# 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. + +import sys +import logging +import hashlib +import json +import os +import six +import time +import collections +from threading import Thread, current_thread +from contextlib import contextmanager + +from paddle.fluid import unique_name, compiler +from .checkpoint_saver import SerializableBase, CheckpointSaver, PaddleModel +from paddle.fluid.framework import _non_static_mode, Program + +g_train_epoch_range = None +g_checker = None + +logger = None + +generator = unique_name.UniqueNameGenerator() + +CONST_CHECKPOINT = "checkpoint" +CONST_MEMORYINIT = "memory_init" + +# auto checkpoint by dataloader event. +CONST_DACP_TYPE = "dacp" +# auto checkpoint by loop range. +CONST_ACP_TYPE = "acp" +g_acp_type = None +g_program_attr = {} # program_name->can_be_auto_checkpoint + + +def _get_logger(log_level, name="auto_checkpoint"): + global logger + if logger != None: + return logger + + logger = logging.getLogger(name) + logger.setLevel(log_level) + logger.propagate = False + + log_handler = logging.StreamHandler() + log_format = logging.Formatter( + '%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s') + log_handler.setFormatter(log_format) + logger.addHandler(log_handler) + + return logger + + +def _thread_checker(): + assert current_thread().name == "MainThread", \ + "auto checkpoint must run under main thread" + + +class AutoCheckpointChecker(object): + + def __init__(self): + self._run_env = None + self._platform = None + self._job_id = None + self._hdfs_home = None + self._hdfs_name = None + self._hdfs_ugi = None + self._hdfs_checkpoint_path = None + self._trainer_id = None + self._ce_test = None + + self._run_env = os.getenv("PADDLE_RUNNING_ENV") + if self._run_env != "PADDLE_EDL_AUTO_CHECKPOINT": + return + + try: + self._platform = os.environ["PADDLE_RUNNING_PLATFORM"] + self._job_id = os.environ["PADDLE_JOB_ID"] + self._hdfs_home = os.environ["PADDLE_EDL_HDFS_HOME"] + self._hdfs_name = os.environ["PADDLE_EDL_HDFS_NAME"] + self._hdfs_ugi = os.environ["PADDLE_EDL_HDFS_UGI"] + self._hdfs_checkpoint_path = os.environ[ + "PADDLE_EDL_HDFS_CHECKPOINT_PATH"] + self._trainer_id = int(os.environ["PADDLE_TRAINER_ID"]) + + self._ce_test = int(os.getenv("PADDLE_EDL_ONLY_FOR_CE_TEST", "0")) + self._fs_cache = os.getenv("PADDLE_EDL_FS_CACHE", ".cache") + + self._save_checkpoint_inter = int( + os.getenv("PADDLE_EDL_SAVE_CHECKPOINT_INTER", "900")) # s + + if not self._ce_test: + assert len(self._hdfs_home) > 3 and \ + len(self._hdfs_name) > 6 and \ + len(self._hdfs_ugi) > 3 and \ + len(self._hdfs_checkpoint_path) > 0, "hdfs environ must set" + else: + assert len(self._hdfs_home) > 3 and \ + len(self._hdfs_checkpoint_path) > 0, "hdfs environ must set" + + except Exception as e: + logger.fatal("exception:{}".format(e)) + sys.exit(1) + + def get_range_checkpoint_path(self, name): + return "{}/{}/range/{}".format(self.hdfs_checkpoint_path, self.job_id, + name) + + def get_exe_checkpoint_path(self, name): + return "{}/{}/exe/{}".format(self.hdfs_checkpoint_path, self.job_id, + name) + + def get_job_path(self): + return "{}/{}".format(self.hdfs_checkpoint_path, self.job_id) + + @property + def save_checkpoint_inter(self): + return self._save_checkpoint_inter + + def valid(self): + if _non_static_mode(): + return False + + return self._run_env is not None and \ + self._platform is not None and \ + self._job_id is not None and \ + self._hdfs_home is not None and \ + self._hdfs_name is not None and \ + self._hdfs_ugi is not None and \ + self._hdfs_checkpoint_path is not None and \ + self._trainer_id is not None + + def __str__(self): + return "run_env:{} platform:{} job_id:{} \ + hdfs_home:{} hdfs_name:{} hdfs_ugi:{} \ + hdfs_checkpoint_path:{} trainer_id:{} ce_test".format( + self._run_env, self._platform, self._hdfs_home, self._hdfs_name, + self._hdfs_ugi, self._hdfs_checkpoint_path, self._trainer_id, + self._ce_test) + + @property + def trainer_id(self): + return self._trainer_id + + @property + def run_env(self): + return self._run_env + + @property + def platform(self): + return self._platform + + @property + def job_id(self): + return self._job_id + + @property + def hdfs_home(self): + return self._hdfs_home + + @property + def hdfs_name(self): + return self._hdfs_name + + @property + def ce_test(self): + return self._ce_test + + @property + def hdfs_ugi(self): + return self._hdfs_ugi + + @property + def hdfs_checkpoint_path(self): + return self._hdfs_checkpoint_path + + @staticmethod + def generate_range_name(): + return generator("_range_") + + +class ExeTrainStatus(SerializableBase): + + def __init__(self): + self._epoch_no = -1 # start epoch_no + self._hash_key = None + self._key = None + self._checkpoint_path = None + self._checkpoint_no = None + self._restored_from = None + self._exe = None + self._program = None + self._exe_name = None + self._program_name = None + + self._file_name = "exe_train_status" + + def __eq__(self, t): + return self._epoch_no == t._epoch_no and \ + self._hash_key == t._hash_key and \ + self._key == t._key and \ + self._checkpoint_path == t._checkpoint_path and \ + self._checkpoint_no == t._checkpoint_no and \ + self._exe_name == t._exe_name and \ + self._program_name == t._program_name + + def __ne__(self, t): + return not self == t + + def serialize(self, path): + file_name = "{}/{}".format(path, self._file_name) + with open(file_name, 'w') as f: + s = self._serialize() + f.write(s) + + def _serialize(self, pop_keys=["restored_from"]): + d = self._to_dict() + for k in pop_keys: + d.pop(k, None) + return json.dumps(d) + + def deserialize(self, path): + d = None + file_name = "{}/{}".format(path, self._file_name) + with open(file_name, 'r') as f: + s = f.read() + self._deserialize(s) + + def _deserialize(self, s): + d = json.loads(s) + self._epoch_no = d["epoch_no"] + self._key = d["key"] + self._hash_key = d["hash_key"] + self._checkpoint_path = d["checkpoint_path"] + self._checkpoint_no = d["checkpoint_no"] + self._exe_name = d["exe_name"] + self._program_name = d["program_name"] + + def _to_dict(self): + return { + "epoch_no": self._epoch_no, + "key": self._key, + "hash_key": self._hash_key, + "checkpoint_path": self._checkpoint_path, + "restored_from": self._restored_from, + "exe_name": self._exe_name, + "program_name": self._program_name, + "checkpoint_no": self._checkpoint_no + } + + def __str__(self): + return self._serialize([]) + + +class TrainEpochRange(SerializableBase): + + def __init__(self, + max_epoch_num, + name, + checkpoint_inter=None, + restored=True): + self._max_epoch_num = max_epoch_num + self._epoch_no = -1 # current epoch_no + self._name = name + self._restored_from = None + self._exe_status = {} + self._flag_generated = False + + self._checker = g_checker + if checkpoint_inter is not None: + self._save_checkpoint_inter = checkpoint_inter + else: + self._save_checkpoint_inter = self._checker.save_checkpoint_inter + assert self._save_checkpoint_inter >= 0, "checkpointer:{} must >=0".format( + self._save_checkpoint_inter) + self._last_checkpoint_time = time.time() + + self._load_cp_nos = None + self._checkpoint_epoch_no = None + + if not self._checker.valid(): + return + + self._file_name = "range_train_status" + + if not restored: + return + + self._checkpoint_path = self._checker.get_range_checkpoint_path(name) + + config = { + "fs.default.name": self._checker.hdfs_name, + "hadoop.job.ugi": self._checker.hdfs_ugi + } + + if self._checker.ce_test: + config = None + + from paddle.distributed.fleet.utils.fs import HDFSClient + self._hdfs = HDFSClient(self._checker.hdfs_home, config) + + self._cper = CheckpointSaver(self._hdfs) + + _thread_checker() + + self._get_last_valid_checkpoint() + + def _look_for_valid(self, cp_nos): + cps = [] + epoch_no = -1 + for i in cp_nos[::-1]: + t = TrainEpochRange(self._max_epoch_num, self.name, restored=False) + self._cper.load_checkpoint(self._checkpoint_path, [t], + self._checker.trainer_id, + checkpoint_no=i, + local_cache_path=self._checker._fs_cache) + cps.append(t) + logger.debug("look for valid:{} t:{}".format(i, t._serialize())) + if epoch_no < 0: + epoch_no = t._epoch_no + else: + if epoch_no - t._epoch_no >= 1: + return t, i + return None, None + + def _get_last_valid_checkpoint(self): + self._load_cp_nos = self._cper.get_checkpoint_no(self._checkpoint_path) + logger.info("find checkpoint nos:{}".format(self._load_cp_nos)) + + if len(self._load_cp_nos) < 1: + self._restored_from = CONST_MEMORYINIT + return + + if g_acp_type == CONST_ACP_TYPE: + # get the last one + self._cper.load_checkpoint(self._checkpoint_path, [self], + self._checker.trainer_id, + local_cache_path=self._checker._fs_cache) + self._restored_from = CONST_CHECKPOINT + self._checkpoint_epoch_no = self._epoch_no + + logger.info("load tain_epoch_range checkpoint:{}".format( + self._serialize())) + + elif g_acp_type == CONST_DACP_TYPE: + t, i = self._look_for_valid(self._load_cp_nos) + if t is None: + self._restored_from = CONST_MEMORYINIT + return + + self._cper.load_checkpoint(self._checkpoint_path, [self], + self._checker.trainer_id, + checkpoint_no=i, + local_cache_path=self._checker._fs_cache) + + self._restored_from = CONST_CHECKPOINT + self._checkpoint_epoch_no = self._epoch_no + logger.info("load tain_epoch_range checkpoint:{}".format( + self._serialize())) + else: + assert False, "not supported acp_type:{}".format(g_acp_type) + + def _to_dict(self): + d = { + "max_epoch_num": self._max_epoch_num, + "epoch_no": self._epoch_no, + "name": self._name, + "checkpoint_path": self._checkpoint_path, + "restored_from": self._restored_from, + "checkpoint_epoch_no": self._checkpoint_epoch_no + } + return d + + def __str__(self): + return self._serialize([]) + + @property + def name(self): + return self._name + + def serialize(self, path): + file_name = "{}/{}".format(path, self._file_name) + with open(file_name, 'w') as f: + s = self._serialize() + f.write(s) + + def _serialize(self, pop_keys=["restored_from", "checkpoint_epoch_no"]): + # self + d = self._to_dict() + for k in pop_keys: + d.pop(k, None) + + # registerd exes + d["exe_status"] = {} + e = d["exe_status"] + for k, t in six.iteritems(self._exe_status): + e[t._key] = t._serialize() + return json.dumps(d) + + @property + def restored_from(self): + return self._restored_from + + def deserialize(self, path): + d = None + file_name = "{}/{}".format(path, self._file_name) + with open(file_name, 'r') as f: + d = json.load(f) + + # self + self._max_epoch_num = d["max_epoch_num"] + self._epoch_no = d["epoch_no"] + self._name = d["name"] + self._checkpoint_path = d["checkpoint_path"] + + # exes status + e = d["exe_status"] + for k, v in six.iteritems(e): + t = ExeTrainStatus() + t._deserialize(v) + self._exe_status[k] = t + + def next(self): + _thread_checker() + + if self._max_epoch_num < 0: + self._max_epoch_num = sys.maxint + + assert self._epoch_no >= -1, "self._epoch_no:{} must >=-1".format( + self._epoch_no) + + self._last_checkpoint_time = time.time() + start = self._epoch_no + 1 + logger.info("started epoch_no:{} max_epoch_num:{}".format( + start, self._max_epoch_num)) + + for i in range(start, self._max_epoch_num): + self._epoch_no = i + yield i + + self.save_checkpoint() + + def get(self): + return self._epoch_no + + def save_checkpoint(self): + # not save last one because exe and program can't be restored. + if self._checker.trainer_id == 0: + + if time.time() - self._last_checkpoint_time >= \ + self._save_checkpoint_inter: + if g_acp_type == CONST_ACP_TYPE: + # not save the last one + if self._max_epoch_num > 0 and self._epoch_no != self._max_epoch_num - 1: + self._save_checkpoint() + elif g_acp_type == CONST_DACP_TYPE: + self._save_checkpoint() + else: + assert False, "not supported acp_type:{}".format(g_acp_type) + self._last_checkpoint_time = time.time() + + def _save_checkpoint(self): + """ + status => /jobid/xxx_range_xx/range/ + model => /exe/ + """ + if not self._checker.valid(): + return + + e = self._exe_status + for k, t in six.iteritems(self._exe_status): + m = PaddleModel(t._exe, t._program) + p = self._checker.get_exe_checkpoint_path(t._hash_key) + t._epoch_no = self.get() + path, checkpoint_no = self._cper.save_checkpoint( + p, [m], + self._checker.trainer_id, + local_cache_path=self._checker._fs_cache) + # index info + t._checkpoint_path = path + t._checkpoint_no = checkpoint_no + + e[t._key] = t + + logger.debug("save executor checkpoint:{}".format(t._serialize())) + + if len(self._exe_status) > 0: + self._cper.save_checkpoint(self._checkpoint_path, [self], + local_cache_path=self._checker._fs_cache) + logger.info("save train_epoch_range checkpoint:{}".format( + self._serialize())) + + self._generate_flag() + + def _generate_flag(self): + if self._flag_generated: + return + + name = "can_be_auto_checkpoint.flag" + path = self._checker.get_job_path() + "/" + name + logger.info("this job can_be_auto_checkpoint") + self._hdfs.mkdirs(self._checker.get_job_path()) + self._hdfs.touch(path, exist_ok=True) + + self._flag_generated = True + + +def _get_train_epoch_range(): + return g_train_epoch_range + + +def _check_program_oprole(program): + global_block = program.global_block() + has_backward = False + has_opt = False + for idx, op in enumerate(global_block.ops): + if op._is_backward_op(): + has_backward = True + + if op._is_optimize_op(): + has_opt = True + + if has_backward and has_opt: + return True + + return False + + +def _can_auto_checkpoint(prog): + if not isinstance(prog, compiler.CompiledProgram) and \ + not isinstance(prog, Program): + return False + + if isinstance(prog, compiler.CompiledProgram): + if prog._program is None or \ + prog._program._is_distributed: + return False + else: + if prog._is_distributed: + return False + + program = _get_valid_program(prog) + + if program._auto_checkpoint_name in g_program_attr: + if not g_program_attr[program._auto_checkpoint_name]: + return False + else: + ret = False + if isinstance(program, compiler.CompiledProgram): + ret = _check_program_oprole(program._program) + else: + ret = _check_program_oprole(program) + + g_program_attr[program._auto_checkpoint_name] = ret + if not ret: + logger.debug("program {} need't to auto checkpoint".format( + program._auto_checkpoint_name)) + return False + + return g_checker.valid() and g_train_epoch_range is not None + + +def _get_running_key(exe_name, program_name): + return "{}_{}".format(exe_name, program_name) + + +def _get_checker(): + _get_logger(20) + global g_checker + if g_checker is None: + g_checker = AutoCheckpointChecker() + + return g_checker + + +def _normal_yield(max_epoch_num): + if max_epoch_num < 0: + max_epoch_num = sys.maxint + for i in range(0, max_epoch_num): + yield i + + return + + +def train_epoch_range(max_epoch_num, save_checkpoint_inter=None): + global g_acp_type + if not _get_checker().valid(): + logger.warning( + "auto checkpoint will take effect automaticly on PaddleCloud") + for i in _normal_yield(max_epoch_num): + yield i + + return + + if g_acp_type == CONST_DACP_TYPE: + for i in _normal_yield(max_epoch_num): + yield i + + return + + g_acp_type = CONST_ACP_TYPE + logger.info("acp_type:{}".format(g_acp_type)) + + global g_train_epoch_range + try: + g_train_epoch_range = TrainEpochRange( + max_epoch_num, + g_checker.generate_range_name(), + checkpoint_inter=save_checkpoint_inter) + + for i in g_train_epoch_range.next(): + yield i + finally: + g_train_epoch_range = None + + +def _get_valid_program(prog): + if isinstance(prog, compiler.CompiledProgram): + return prog._program + + return prog + + +def _auto_checkpoint(exe, prog): + _get_checker() + + assert exe._auto_checkpoint_name != None + if not _can_auto_checkpoint(prog): + return + + program = _get_valid_program(prog) + assert program._auto_checkpoint_name != None + + exe_status = g_train_epoch_range._exe_status + key = _get_running_key(exe._auto_checkpoint_name, + program._auto_checkpoint_name) + + if g_train_epoch_range.restored_from == CONST_CHECKPOINT: + assert key in exe_status, "when restored key:{} must be in train_epoch_range:{}".format( + key, g_train_epoch_range) + + t = None + if key in exe_status: + t = exe_status[key] + if t._restored_from is None: + a = CheckpointSaver(g_train_epoch_range._hdfs) + m = PaddleModel(exe, program) + a.load_checkpoint(g_checker.get_exe_checkpoint_path(key), [m], + trainer_id=g_checker.trainer_id, + checkpoint_no=t._checkpoint_no, + local_cache_path=g_checker._fs_cache) + t._restored_from = CONST_CHECKPOINT + logger.info("load executor checkpoint {}".format(t)) + t._exe = exe + t._program = program + t._epoch_no = g_train_epoch_range.get() + else: + t = ExeTrainStatus() + t._epoch_no = g_train_epoch_range.get() + t._hash_key = key + t._key = key + t._restored_from = CONST_MEMORYINIT + t._exe = exe + t._program = program + t._exe_name = exe._auto_checkpoint_name + t._program_name = program._auto_checkpoint_name + + # register this + exe_status[key] = t + + logger.info("not found checkpoint, so train from epoch 0") + + _thread_checker() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/checkpoint_saver.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/checkpoint_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..c8aeb50f157c0f66df920fef133cf5870cd57052 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/checkpoint/checkpoint_saver.py @@ -0,0 +1,225 @@ +# 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. + +from ...compiler import CompiledProgram + + +class SerializableBase(object): + + def serialize(self, path): + raise NotImplementedError + + def deserialize(self, path): + raise NotImplementedError + + +class PaddleModel(SerializableBase): + + def __init__(self, exe, program): + self._exe = exe + self._origin_program = program + self._program = program + if isinstance(program, CompiledProgram): + self._program = program._program + + self._file_name = "_paddle_fleet_param__" + + def serialize(self, path): + from ...io import save_persistables + save_persistables(executor=self._exe, + dirname=path, + main_program=self._program, + filename=self._file_name) + + def deserialize(self, path): + from ...io import load_persistables + load_persistables(executor=self._exe, + dirname=path, + main_program=self._program, + filename=self._file_name) + + +class CheckpointSaver(object): + + def __init__(self, fs): + self._fs = fs + self._checkpoint_prefix = "__paddle_checkpoint__" + + def save_checkpoint(self, + path, + slists, + trainer_id=None, + local_cache_path=".cache"): + """ + Serialize objects in slists to path + Return really saved path and checkpoint_no + """ + if not self._fs.is_exist(path): + self._fs.mkdirs(path) + else: + assert self._fs.is_dir(path), "path:{} must be a directory".format( + path) + + max_no = self._get_last_checkpoint_no(path) + if max_no < 0: + max_no = -1 + max_no += 1 + + real_path = "{}/{}.{}".format(path, self._checkpoint_prefix, max_no) + tmp_path = "{}.tmp".format(real_path) + saved_path = tmp_path + + from paddle.distributed.fleet.utils.fs import LocalFS + local_fs = LocalFS() + + cache_path = None + if self._fs.need_upload_download(): + cache_path = "{}/{}.{}.saved_cache".format(local_cache_path, + self._checkpoint_prefix, + max_no) + + if trainer_id is not None: + cache_path = "{}.{}".format(cache_path, trainer_id) + + if not local_fs.is_exist(cache_path): + local_fs.mkdirs(cache_path) + else: + assert local_fs.is_dir(cache_path), \ + "cache path:{} must be a directory".format(cache_path) + + saved_path = cache_path + + for s in slists: + s.serialize(saved_path) + + if self._fs.need_upload_download(): + self._fs.delete(tmp_path) + self._fs.upload(cache_path, tmp_path) + local_fs.delete(cache_path) + self._fs.mv(tmp_path, real_path) + + return real_path, max_no + + def load_checkpoint(self, + path, + slists, + trainer_id, + local_cache_path=".cache", + checkpoint_no=None, + ignore_empty=True): + """ + Deserialize objects in slists from path + Return really load path + """ + if checkpoint_no is None: + max_no = self._get_last_checkpoint_no(path) + + if not ignore_empty: + assert max_no >= 0, "Can't find checkpoint" + + if max_no < 0: + return None + + checkpoint_no = max_no + else: + assert isinstance(checkpoint_no, int) + assert checkpoint_no >= 0 + + from paddle.distributed.fleet.utils.fs import LocalFS + local_fs = LocalFS() + if self._fs.need_upload_download(): + cache_path = "{}/{}.{}.load_cache".format(local_cache_path, + self._checkpoint_prefix, + checkpoint_no) + + if trainer_id is not None: + cache_path = "{}.{}".format(cache_path, trainer_id) + + if not local_fs.is_exist(local_cache_path): + local_fs.mkdirs(local_cache_path) + if local_fs.is_exist(cache_path): + local_fs.delete(cache_path) + + real_path = "{}/{}.{}".format(path, self._checkpoint_prefix, + checkpoint_no) + load_path = real_path + if self._fs.need_upload_download(): + self._fs.download(real_path, cache_path) + load_path = cache_path + + for s in slists: + s.deserialize(load_path) + + if self._fs.need_upload_download() and cache_path: + local_fs.delete(cache_path) + + return real_path + + def get_checkpoint_no(self, root_path): + a = [] + dirs = self._fs.list_dirs(root_path) + for d in dirs: + g = d.split(".") + if len(g) != 2: + continue + + if g[0] != self._checkpoint_prefix: + continue + + try: + n = int(g[1]) + a.append(n) + except: + continue + + a.sort() + return a + + def _get_last_checkpoint_no(self, root_path): + """ + only get the first depth + """ + a = self.get_checkpoint_no(root_path) + if len(a) > 0: + return a[-1] + + return -1 + + def clean_redundant_checkpoints(self, root_path, reserved=[]): + max_no = self._get_last_checkpoint_no(root_path) + if max_no < 0: + return + + s = set(reserved) + if len(s) == 0: + s.add(max_no) + + dirs = self._fs.list_dirs(root_path) + for d in dirs: + g = d.split(".") + if len(g) != 2: + continue + + if g[0] != self._checkpoint_prefix: + continue + + try: + n = int(g[1]) + if n not in s: + path = "{}/{}.{}".format(root_path, self._checkpoint_prefix, + n) + self._fs.delete(path) + except Exception as e: + print(e) + continue diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/data_generator/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/data_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ef851f52e7b8a61fc73d884b992b3fd2714f8d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/data_generator/__init__.py @@ -0,0 +1,346 @@ +# 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. + +import os +import sys + +__all__ = ['MultiSlotDataGenerator', 'MultiSlotStringDataGenerator'] + + +class DataGenerator(object): + """ + DataGenerator is a general Base class for user to inherit + A user who wants to define his/her own python processing logic + with paddle.fluid.dataset should inherit this class + """ + + def __init__(self): + self._proto_info = None + self.batch_size_ = 32 + + def _set_line_limit(self, line_limit): + if not isinstance(line_limit, int): + raise ValueError("line_limit%s must be in int type" % + type(line_limit)) + if line_limit < 1: + raise ValueError("line_limit can not less than 1") + self._line_limit = line_limit + + def set_batch(self, batch_size): + ''' + Set batch size of current DataGenerator + This is necessary only if a user wants to define generator_batch + + Example: + .. code-block:: python + import paddle.fluid.incubate.data_generator as dg + class MyData(dg.DataGenerator): + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", int_words) + return local_iter + def generate_batch(self, samples): + def local_iter(): + for s in samples: + yield ("words", s[1].extend([s[1][0]])) + mydata = MyData() + mydata.set_batch(128) + + ''' + self.batch_size_ = batch_size + + def run_from_memory(self): + ''' + This function generator data from memory, it is usually used for + debug and benchmarking + Example: + .. code-block:: python + import paddle.fluid.incubate.data_generator as dg + class MyData(dg.DataGenerator): + def generate_sample(self, line): + def local_iter(): + yield ("words", [1, 2, 3, 4]) + return local_iter + mydata = MyData() + mydata.run_from_memory() + ''' + batch_samples = [] + line_iter = self.generate_sample(None) + for user_parsed_line in line_iter(): + if user_parsed_line == None: + continue + batch_samples.append(user_parsed_line) + if len(batch_samples) == self.batch_size_: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + batch_samples = [] + if len(batch_samples) > 0: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + + def run_from_stdin(self): + ''' + This function reads the data row from stdin, parses it with the + process function, and further parses the return value of the + process function with the _gen_str function. The parsed data will + be wrote to stdout and the corresponding protofile will be + generated. + Example: + + .. code-block:: python + import paddle.fluid.incubate.data_generator as dg + class MyData(dg.DataGenerator): + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", [int_words]) + return local_iter + mydata = MyData() + mydata.run_from_stdin() + ''' + batch_samples = [] + for line in sys.stdin: + line_iter = self.generate_sample(line) + for user_parsed_line in line_iter(): + if user_parsed_line == None: + continue + batch_samples.append(user_parsed_line) + if len(batch_samples) == self.batch_size_: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + batch_samples = [] + if len(batch_samples) > 0: + batch_iter = self.generate_batch(batch_samples) + for sample in batch_iter(): + sys.stdout.write(self._gen_str(sample)) + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the datafeed,and + updating proto_info information. + Args: + line(str): the output of the process() function rewritten by user. + Returns: + Return a string data that can be read directly by the datafeed. + ''' + raise NotImplementedError( + "pls use MultiSlotDataGenerator or PairWiseDataGenerator") + + def generate_sample(self, line): + ''' + This function needs to be overridden by the user to process the + original data row into a list or tuple. + Args: + line(str): the original data row + Returns: + Returns the data processed by the user. + The data format is list or tuple: + [(name, [feasign, ...]), ...] + or ((name, [feasign, ...]), ...) + + For example: + [("words", [1926, 08, 17]), ("label", [1])] + or (("words", [1926, 08, 17]), ("label", [1])) + Note: + The type of feasigns must be in int or float. Once the float + element appears in the feasign, the type of that slot will be + processed into a float. + Example: + .. code-block:: python + import paddle.fluid.incubate.data_generator as dg + class MyData(dg.DataGenerator): + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", [int_words]) + return local_iter + ''' + raise NotImplementedError( + "Please rewrite this function to return a list or tuple: " + + "[(name, [feasign, ...]), ...] or ((name, [feasign, ...]), ...)") + + def generate_batch(self, samples): + ''' + This function needs to be overridden by the user to process the + generated samples from generate_sample(self, str) function + It is usually used as batch processing when a user wants to + do preprocessing on a batch of samples, e.g. padding according to + the max length of a sample in the batch + Args: + samples(list tuple): generated sample from generate_sample + Returns: + a python generator, the same format as return value of generate_sample + Example: + .. code-block:: python + import paddle.fluid.incubate.data_generator as dg + class MyData(dg.DataGenerator): + def generate_sample(self, line): + def local_iter(): + int_words = [int(x) for x in line.split()] + yield ("words", int_words) + return local_iter + def generate_batch(self, samples): + def local_iter(): + for s in samples: + yield ("words", s[1].extend([s[1][0]])) + mydata = MyData() + mydata.set_batch(128) + ''' + + def local_iter(): + for sample in samples: + yield sample + + return local_iter + + +# TODO: guru4elephant +# add more generalized DataGenerator that can adapt user-defined slot +# for example, [(name, float_list), (name, str_list), (name, int_list)] +class MultiSlotStringDataGenerator(DataGenerator): + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the MultiSlotDataFeed, + and updating proto_info information. + The input line will be in this format: + >>> [(name, [str(feasign), ...]), ...] + >>> or ((name, [str(feasign), ...]), ...) + The output will be in this format: + >>> [ids_num id1 id2 ...] ... + For example, if the input is like this: + >>> [("words", ["1926", "08", "17"]), ("label", ["1"])] + >>> or (("words", ["1926", "08", "17"]), ("label", ["1"])) + the output will be: + >>> 3 1234 2345 3456 1 1 + Args: + line(str): the output of the process() function rewritten by user. + Returns: + Return a string data that can be read directly by the MultiSlotDataFeed. + ''' + if not isinstance(line, list) and not isinstance(line, tuple): + raise ValueError( + "the output of process() must be in list or tuple type" + "Examples: [('words', ['1926', '08', '17']), ('label', ['1'])]") + output = "" + for index, item in enumerate(line): + name, elements = item + if output: + output += " " + out_str = [] + out_str.append(str(len(elements))) + out_str.extend(elements) + output += " ".join(out_str) + return output + "\n" + + +class MultiSlotDataGenerator(DataGenerator): + + def _gen_str(self, line): + ''' + Further processing the output of the process() function rewritten by + user, outputting data that can be directly read by the MultiSlotDataFeed, + and updating proto_info information. + The input line will be in this format: + >>> [(name, [feasign, ...]), ...] + >>> or ((name, [feasign, ...]), ...) + The output will be in this format: + >>> [ids_num id1 id2 ...] ... + The proto_info will be in this format: + >>> [(name, type), ...] + + For example, if the input is like this: + >>> [("words", [1926, 08, 17]), ("label", [1])] + >>> or (("words", [1926, 08, 17]), ("label", [1])) + the output will be: + >>> 3 1234 2345 3456 1 1 + the proto_info will be: + >>> [("words", "uint64"), ("label", "uint64")] + Args: + line(str): the output of the process() function rewritten by user. + Returns: + Return a string data that can be read directly by the MultiSlotDataFeed. + ''' + if not isinstance(line, list) and not isinstance(line, tuple): + raise ValueError( + "the output of process() must be in list or tuple type" + "Example: [('words', [1926, 08, 17]), ('label', [1])]") + output = "" + + if self._proto_info is None: + self._proto_info = [] + for item in line: + name, elements = item + if not isinstance(name, str): + raise ValueError("name%s must be in str type" % type(name)) + if not isinstance(elements, list): + raise ValueError("elements%s must be in list type" % + type(elements)) + if not elements: + raise ValueError( + "the elements of each field can not be empty, you need padding it in process()." + ) + self._proto_info.append((name, "uint64")) + if output: + output += " " + output += str(len(elements)) + for elem in elements: + if isinstance(elem, float): + self._proto_info[-1] = (name, "float") + elif not isinstance(elem, int) and not isinstance( + elem, long): + raise ValueError( + "the type of element%s must be in int or float" % + type(elem)) + output += " " + str(elem) + else: + if len(line) != len(self._proto_info): + raise ValueError( + "the complete field set of two given line are inconsistent." + ) + for index, item in enumerate(line): + name, elements = item + if not isinstance(name, str): + raise ValueError("name%s must be in str type" % type(name)) + if not isinstance(elements, list): + raise ValueError("elements%s must be in list type" % + type(elements)) + if not elements: + raise ValueError( + "the elements of each field can not be empty, you need padding it in process()." + ) + if name != self._proto_info[index][0]: + raise ValueError( + "the field name of two given line are not match: require<%s>, get<%s>." + % (self._proto_info[index][0], name)) + if output: + output += " " + output += str(len(elements)) + for elem in elements: + if self._proto_info[index][1] != "float": + if isinstance(elem, float): + self._proto_info[index] = (name, "float") + elif not isinstance(elem, int) and not isinstance( + elem, long): + raise ValueError( + "the type of element%s must be in int or float" + % type(elem)) + output += " " + str(elem) + return output + "\n" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a05baabca392b14a4cb09a3f395ae7687d8a5e62 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/__init__.py @@ -0,0 +1,14 @@ +# 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 + +__version__ = '0.1.0' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8647330f3290f3142cabca9a7e3fe162a9838dda --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/__init__.py @@ -0,0 +1,12 @@ +# 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 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/fleet_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/fleet_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa4fcf45c792614922ff1d1f917f2a5736fd9fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/fleet_base.py @@ -0,0 +1,370 @@ +# 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. + +from __future__ import print_function + +import abc + +import paddle.fluid as fluid +from paddle.fluid.executor import Executor +from paddle.fluid.optimizer import SGD +from paddle.optimizer import SGD as SGD_v2 + +from paddle.fluid.incubate.fleet.base.mode import Mode +from paddle.distributed.fleet.base.role_maker import RoleMakerBase +from paddle.fluid.contrib.mixed_precision.decorator import OptimizerWithMixedPrecision +from . import mode + +__all__ = ['Fleet', 'DistributedOptimizer'] +__all__ += mode.__all__ + + +class Fleet(object): + """ + Fleet is the base class, transpiler and pslib are implementation of Fleet. + + Args: + mode(Mode): the implementation of Fleet's mode. + + Returns: + None + """ + __metaclass__ = abc.ABCMeta + + def __init__(self, mode): + self._is_initialized = False + self._mode = mode + self._optimizer = None + self._role_maker = None + self._executor = None + + def is_first_worker(self): + """ + Check whether the node is the first instance of worker. + + Returns: + bool: True if this is the first node of worker, + False if not. + """ + return self._role_maker.is_first_worker() + + def worker_index(self): + """ + Get current worker index. + + Returns: + int: node id + """ + return self._role_maker.worker_index() + + def worker_num(self): + """ + Get current total worker number. + + Returns: + int: worker numbers + """ + return self._role_maker.worker_num() + + def is_worker(self): + """ + Check whether the node is an instance of worker. + + Returns: + bool: True if this is a node of worker, + False if not. + """ + return self._role_maker.is_worker() + + def worker_endpoints(self, to_string=False): + """ + Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. + + Returns: + list/string: server endpoints + """ + + if to_string: + return ",".join(self._role_maker.get_trainer_endpoints()) + else: + return self._role_maker.get_trainer_endpoints() + + def server_num(self): + """ + Get current total worker number. + + Returns: + int: server number + """ + return len(self._role_maker.get_pserver_endpoints()) + + def server_index(self): + """ + Get current server index. + + Returns: + int: node id + """ + return self._role_maker.server_index() + + def server_endpoints(self, to_string=False): + """ + Get current server endpoints, such as ["127.0.0.1:1001", "127.0.0.1:1002"]. + + Returns: + list/string: server endpoints + """ + + if to_string: + return ",".join(self._role_maker.get_pserver_endpoints()) + else: + return self._role_maker.get_pserver_endpoints() + + def is_server(self): + """ + Check whether the node is an instance of server. + + Returns: + bool: True if this is a node of server, + False if not + """ + return self._role_maker.is_server() + + def is_xpu(self): + """ + Check whether the node is an instance of server. + + Returns: + bool: True if this is a node of server, + False if not. + """ + return self._role_maker.is_xpu() + + def split_files(self, files): + """ + split files before distributed training, + example 1: files is [a, b, c ,d, e] and trainer_num = 2, then trainer + 0 gets [a, b, c] and trainer 1 gets [d, e]. + example 2: files is [a, b], and trainer_num = 3, then trainer 0 gets + [a], trainer 1 gets [b], trainer 2 gets [] + + Args: + files(list): file list need to be read. + + Returns: + list: files belongs to this worker. + """ + if not isinstance(files, list): + raise TypeError("files should be a list of file need to be read.") + + trainer_id = self.worker_index() + trainers = self.worker_num() + + remainder = len(files) % trainers + blocksize = len(files) // trainers + + blocks = [blocksize] * trainers + for i in range(remainder): + blocks[i] += 1 + + trainer_files = [[]] * trainers + begin = 0 + for i in range(trainers): + trainer_files[i] = files[begin:begin + blocks[i]] + begin += blocks[i] + + return trainer_files[trainer_id] + + def init(self, role_maker=None): + """ + should be called only once in user's python scripts, + init() will initialize RoleMaker which is used for identifying + current node's role, e.g. worker, server, etc. + + Args: + role_maker(RoleMakerBase): subclass of RoleMakerBase. + + Returns: + None + """ + self._executor = Executor(fluid.CPUPlace()) + + if role_maker and not isinstance(role_maker, RoleMakerBase): + from paddle.fluid.incubate.fleet.base.role_maker import RoleMakerBase as RoleMakerBaseIncubate + if role_maker and not isinstance(role_maker, RoleMakerBaseIncubate): + raise TypeError( + "role_maker must be an instance of RoleMakerBase") + + self._role_maker = role_maker + self._role_maker.generate_role() + self._is_initialized = True + + def all_reduce_worker(self, input, output): + """ + all reduce between workers, only support array of one dim. + + Args: + input(list|numpy.array): array of one dim + output(list|numpy.array): array of one dim + """ + self._role_maker.all_reduce_worker(input, output) + + def barrier_worker(self): + """ + barrier between workers + """ + self._role_maker.barrier_worker() + + @abc.abstractmethod + def init_worker(self): + pass + + @abc.abstractmethod + def init_server(self, model_dir=None, **kwargs): + pass + + @abc.abstractmethod + def run_server(self): + pass + + @abc.abstractmethod + def stop_worker(self): + pass + + @abc.abstractmethod + def distributed_optimizer(self, optimizer, strategy=None): + pass + + @abc.abstractmethod + def save_inference_model(self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True): + pass + + @abc.abstractmethod + def save_persistables(self, executor, dirname, main_program=None): + pass + + +class DistributedOptimizer(object): + """ + DistributedOptimizer is a wrapper for paddle.fluid.optimizer + A user should pass a paddle.fluid.optimizer to DistributedOptimizer + minimize() function is implemented. + DistributedOptimizer is the starting point for a user who wants to + run distributed training. The optimized information will be stored in + Fleet() instance who holds the global information about current distributed + training. + + Args: + optimizer(Optimizer): subclass of Optimizer. + strategy(any): the user define config for Optimizer. + + Returns: + None + + """ + __metaclass__ = abc.ABCMeta + + def __init__(self, optimizer, strategy=None): + if not isinstance(optimizer, SGD.__bases__) \ + and not isinstance(optimizer, OptimizerWithMixedPrecision) \ + and not isinstance(optimizer, SGD_v2.__base__): + raise TypeError("optimizer must be an instance of Optimizer") + + self._optimizer = optimizer + self._strategy = strategy + + @abc.abstractmethod + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + First part of `minimize`, do auto-diff to append backward ops for + the current program. + + Args: + loss (Variable): loss variable to run optimizations. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + callbacks (list|None): list of callables to run when appending backward + operator for one parameter. + + Return: + list: list of (param, grad) pair, grad is the output of backward. + + Examples: + See examples in `apply_gradients`. + """ + pass + + @abc.abstractmethod + def apply_gradients(self, params_grads): + """ + Second part of `minimize`, appending optimization operators for + given `params_grads` pairs. + + Args: + params_grads (list): list of (param, grad) pair to do optimization. + + Returns: + list: A list of operators appended to the current program. + + Examples: + .. code-block:: python + + loss = network() + optimizer = fluid.optimizer.SGD(learning_rate=0.1) + params_grads = optimizer.backward(loss) + # you may append operations for params_grads here + # ... + optimizer.apply_gradients(params_grads) + """ + pass + + @abc.abstractmethod + def minimize(self, + losses, + scopes=None, + startup_programs=None, + parameter_list=None, + no_grad_set=None): + """ + Add operations to minimize `loss` by updating `parameter_list`. + + This method combines interface `backward()` and + `apply_gradients()` into one. + + Args: + losses (Variable|Variable List): loss variable to run optimizations. + scopes (Scope| Scope List): scope instance. + startup_programs (Program|Program List): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + + Returns: + tuple: (optimize_ops, params_grads) which are, list of operators appended; + and list of (param, grad) Variables pair for optimization. + """ + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/mode.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/mode.py new file mode 100644 index 0000000000000000000000000000000000000000..da6519d49e630111f5cb4d9305d05548a7147e30 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/mode.py @@ -0,0 +1,26 @@ +# 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. + +from __future__ import print_function + +__all__ = ['Mode'] + + +class Mode: + """ + There are various mode for fleet, each of them is designed for different model. + """ + TRANSPILER = 1 + PSLIB = 2 + COLLECTIVE = 3 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/role_maker.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/role_maker.py new file mode 100644 index 0000000000000000000000000000000000000000..f97f46a7c49b3d9872479335d8e20cf1994c35cf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/base/role_maker.py @@ -0,0 +1,1305 @@ +# 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. +"""Defination of Role Makers.""" + +from __future__ import print_function +from multiprocessing import Process, Manager +import paddle.fluid as fluid +import os +import time + +__all__ = [ + 'Role', 'RoleMakerBase', 'MPISymetricRoleMaker', 'UserDefinedRoleMaker', + 'UserDefinedCollectiveRoleMaker', 'PaddleCloudRoleMaker', 'GeneralRoleMaker' +] + + +class Role: + WORKER = 1 + SERVER = 2 + XPU = 3 + + +class MockBarrier(object): + """ + MockBarrier is a empty impletation for barrier + mock as a real barrier for never-barrier in a specific scenario + """ + + def barrier(self): + """ + dummy barrier, do nothing + """ + pass + + def barrier_all(self): + """ + dummy all barrier, do nothing + """ + pass + + def all_reduce(self, obj): + """ + dummy all reduce, do nothing + Args: + obj(any): obj to do all reduce + """ + return obj + + def all_gather(self, obj): + """ + dummy all gather, do nothing + Args: + obj(any): obj to do all gather + """ + return [obj] + + +class RoleMakerBase(object): + """ + RoleMakerBase is a base class for assigning a role to current process + in distributed training. + A paddle developer can implement RoleMakerBase to design a role maker + for worker or pserver assignment. + """ + + def __init__(self): + self._worker_endpoints = [] + self._server_endpoints = [] + self._role_is_generated = False + self._role = None + self._current_id = -1 + + def is_worker(self): + """ + return is_worker() of current process + """ + raise NotImplementedError("Please implement this method in child class") + + def is_server(self): + """ + return is_server() of current process + """ + raise NotImplementedError("Please implement this method in child class") + + def is_first_worker(self): + """ + Check whether the node is the first instance of worker. + Returns: + bool: True if this is the first node of worker, + False if not. + """ + raise NotImplementedError("Please implement this method in child class") + + def worker_num(self): + """ + Get current total worker number. + + Returns: + int: worker number + """ + raise NotImplementedError("Please implement this method in child class") + + def role_id(self): + return self.worker_index() if self.is_worker() else self.server_index() + + def worker_index(self): + """ + Get current worker id. + + Returns: + int: node id + """ + raise NotImplementedError("Please implement this method in child class") + + def server_index(self): + """ + Get current server id. + + Returns: + int: node id + """ + raise NotImplementedError("Please implement this method in child class") + + def get_trainer_endpoints(self): + """ + return trainer endpoints + """ + return self._worker_endpoints + + def get_pserver_endpoints(self): + """ + return pserver endpoints + """ + return self._server_endpoints + + def to_string(self): + return "role: {}, current_id: {}, worker_endpoints: {}, server_endpoints: {}".format( + self._role, self._current_id, self._worker_endpoints, + self._server_endpoints) + + def all_gather(self, input): + """ + all gather between trainers and pservers + + Args: + input(int|float): input value + + Returns: + return a list of values + """ + print("warning: RoleMakerBase does not have all gather.") + return None + + def all_reduce_worker(self, input, output, mode="sum"): + """ + all reduce between trainers if current role is TRAINER, + only support array of one dim. + + Args: + input(list/numpy.array): array of one dim + output(list/numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + print("warning: RoleMakerBase does not have all reduce worker.") + + def barrier_worker(self): + """ + barrier between trainers if current role is TRAINER + """ + print("warning: RoleMakerBase does not have barrier worker.") + + def barrier_all(self): + """ + barrier between trainers if current role is PSERVER + """ + print("warning: RoleMakerBase does not have barrier all.") + + +class MPIRoleMaker(RoleMakerBase): + """ + MPIRoleMaker is a MPI-API based role maker which is a counter-part of K8SRoleMaker + mpi4py will be used if a developer inherits MPIRoleMaker + """ + + def __init__(self): + """Init.""" + super(MPIRoleMaker, self).__init__() + from mpi4py import MPI + self.MPI = MPI + self._comm = MPI.COMM_WORLD + self._node_type_comm = None + self._ips = None + self._ip = None + + def _get_rank(self): + """Return rank.""" + self._rank = self._comm.Get_rank() + return self._rank + + def _get_size(self): + """Return size.""" + self._size = self._comm.Get_size() + return self._size + + def _all_gather(self, obj): + """ + all_gather(obj) will call MPI's allgather function + """ + self._barrier_all() + return self._comm.allgather(obj) + + def _worker_gather(self, obj): + """ + worker_gather(obj) will call MPI's allgather function + """ + if self.is_worker(): + self._node_type_comm.barrier() + return self._node_type_comm.allgather(obj) + return None + + def _barrier_all(self): + """ + barrier_all() will call MPI's barrier_all function + """ + self._comm.barrier() + + def _finalize(self): + """ + finalize the current MPI instance. + """ + self.MPI.Finalize() + + def _get_ips(self): + """ + collect current distributed job's ip list + """ + if not self._ips: + self._ips = self._comm.allgather(self.get_local_ip()) + return self._ips + + def get_local_ip(self): + """Return get local ip.""" + import socket + self._ip = socket.gethostbyname(socket.gethostname()) + return self._ip + + def generate_role(self): + """ + generate_role() should be called to identify current process's role + """ + raise NotImplementedError("Please implement this method in child class") + + +class MPISymetricRoleMaker(MPIRoleMaker): + """ + MPISymetricRoleMaker is designed for worker and server assignment + under MPI. Typically, a worker and a server node will be appointed + on each physical node. This role maker can be only used under MPI. + """ + + def __init__(self): + """Init.""" + super(MPISymetricRoleMaker, self).__init__() + self._node_type = None + self._proc_per_node = 2 + self._pserver_rand_port = 0 + + def _check_role_generation(self): + """Check whether role has been generated.""" + if not self._role_is_generated: + raise NameError("generate_role() should be called first") + return True + + def all_gather(self, input): + """ + all gather between trainers and pservers + + Args: + input(int|float): input value + + Returns: + return a list of values + """ + if not self._role_is_generated: + self.generate_role() + return self._all_gather(input) + + def all_reduce_worker(self, input, output, mode="sum"): + """ + all reduce between trainers if current role is TRAINER, + only support array of one dim. + + Args: + input(list/numpy.array): array of one dim + output(list/numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + if not self._role_is_generated: + self.generate_role() + if not self.is_worker(): + print("warning: current role is not worker in all_reduce_worker") + return + self._all_reduce(input, output, mode) + + def barrier_worker(self): + """ + barrier between trainers if current role is TRAINER + """ + if not self._role_is_generated: + self.generate_role() + if self.is_worker(): + self._node_type_comm.barrier() + else: + print("warning: current role is not worker in barrier_worker") + + def barrier_all(self): + """ + barrier between trainers if current role is PSERVER + """ + if not self._role_is_generated: + self.generate_role() + self._comm.barrier() + + def is_first_worker(self): + """ + return whether current process is the first worker assigned by role maker + """ + if self._check_role_generation(): + return self.is_worker() and 0 == self.worker_index() + return False + + def get_pserver_endpoints(self): + """ + get pserver endpoints + Returns: + endpoints(list): pserver endpoints + """ + if self._pserver_rand_port <= 0: + import random + random.seed(self._server_num()) + # port will be randomly generated from 60001 to 63999 + # random seed is server num so that all nodes will get + # the same port + self._pserver_rand_port = random.randint(60001, 64000) + endpoints = [ + x + ":" + str(self._pserver_rand_port) + for x in self._server_endpoints + ] + return endpoints + + def worker_num(self): + return self._worker_num() + + def is_worker(self): + """ + return whether current process is worker assigned by role maker + """ + if self._check_role_generation(): + return self._node_type == 1 + return False + + def is_server(self): + """ + return whether current process is server assigned by role maker + """ + if self._check_role_generation(): + return self._node_type == 0 + return False + + def _worker_num(self): + """ + return the current number of worker + """ + if self._check_role_generation(): + return int(self._get_size() / self._proc_per_node) + return 0 + + def _server_num(self): + """ + return the current number of server + """ + if self._check_role_generation(): + return int(self._get_size() / self._proc_per_node) + else: + self.generate_role() + return int(self._get_size() / self._proc_per_node) + + def worker_index(self): + """ + return the index of worker + """ + if self._check_role_generation(): + return int(self._rank / self._proc_per_node) + else: + self.generate_role() + return int(self._get_size() / 2) + + def server_index(self): + """ + return the index of server + """ + if self._check_role_generation(): + return int(self._rank / self._proc_per_node) + else: + self.generate_role() + return int(self._get_size() / self._proc_per_node) + + def _all_reduce(self, input, output, mode="sum"): + """ + all reduce between trainers if current role is TRAINER, + only support array of one dim. + + Args: + input(list/numpy.array): array of one dim + output(list/numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + if not self._role_is_generated: + self.generate_role() + if mode == "sum": + mode = self.MPI.SUM + elif mode == "max": + mode = self.MPI.MAX + elif mode == "min": + mode = self.MPI.MIN + else: + raise ValueError("unknown mode: %s" % mode) + self._node_type_comm.Allreduce(input, output, op=mode) + + def _barrier_worker(self): + """ + barrier all workers in current distributed job + """ + if self._check_role_generation(): + if self.is_worker(): + self._node_type_comm.barrier() + else: + raise Exception("You should check role generation first") + + def _barrier_server(self): + """ + barrier all servers in current distributed job + """ + if self._check_role_generation(): + if self.is_server(): + self._node_type_comm.barrier() + else: + raise Exception("You should check role generation first") + + def generate_role(self): + """ + generate currently process's role + """ + if not self._role_is_generated: + # TODO(guru4elephant): only allow to be called once + self._worker_endpoints = self._get_ips()[1::2] + self._server_endpoints = self._get_ips()[::2] + + if 0 == self._get_rank() % self._proc_per_node % 2: + self._node_type = 0 + else: + self._node_type = 1 + self._node_type_comm = self._comm.Split(self._node_type) + self._role_is_generated = True + else: + raise Exception("You should check role generation first") + + +class PaddleCloudRoleMaker(RoleMakerBase): + """ + role maker for paddle cloud, + base class is RoleMakerBase + """ + + def __init__(self, is_collective=False): + super(PaddleCloudRoleMaker, self).__init__() + self._role_is_generated = False + self._is_collective = is_collective + + def generate_role(self): + """Generate role.""" + if not self._role_is_generated: + if not self._is_collective: + try: + # Environment variable PADDLE_PSERVERS_IP_PORT_LIST must be set + # format: string(ip:port), eg. 127.0.0.1:6001 + eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split( + ",") + # note that, we usually assign the same port to different ips + # if we run parameter server training in local mode + # port should be different in environment variables + + trainers_num = int(os.environ["PADDLE_TRAINERS_NUM"]) + training_role = os.environ["TRAINING_ROLE"] + + if training_role not in ["TRAINER", "PSERVER"]: + raise ValueError( + "TRAINING_ROLE must be PSERVER or TRAINER") + + if training_role == "TRAINER": + role = Role.WORKER + current_id = int(os.environ["PADDLE_TRAINER_ID"]) + elif training_role == "PSERVER": + role = Role.SERVER + cur_ip = os.environ["POD_IP"] + curr_port = os.environ["PADDLE_PORT"] + curr_endpoint = ":".join([cur_ip, curr_port]) + current_id = eplist.index(curr_endpoint) + else: + raise ValueError( + "TRAINING_ROLE must be PSERVER or TRAINER") + except ValueError as ve: + raise ValueError( + "something wrong with PaddleCloud, please check environment" + ) + + self._trainers_num = trainers_num + self._server_endpoints = eplist + self._role = role + self._current_id = current_id + else: + self._current_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) + self._training_role = os.getenv("PADDLE_TRAINING_ROLE", + "TRAINER") + assert (self._training_role == "TRAINER") + self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS") + self._current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT") + assert self._worker_endpoints is not None, "can't find PADDLE_TRAINER_ENDPOINTS" + self._worker_endpoints = self._worker_endpoints.split(",") + self._trainers_num = len(self._worker_endpoints) + + self._role_is_generated = True + + def get_pserver_endpoints(self): + if not self._role_is_generated: + self.generate_role() + return self._server_endpoints + + def is_worker(self): + if not self._role_is_generated: + self.generate_role() + return self._role == Role.WORKER + + def is_server(self): + if not self._role_is_generated: + self.generate_role() + return self._role == Role.SERVER + + def is_first_worker(self): + if not self._role_is_generated: + self.generate_role() + return self._role == Role.WORKER and self._current_id == 0 + + def worker_index(self): + if not self._role_is_generated: + self.generate_role() + return self._current_id + + def server_index(self): + if not self._role_is_generated: + self.generate_role() + return self._current_id + + def worker_num(self): + if not self._role_is_generated: + self.generate_role() + return self._trainers_num + + +class GeneralRoleMaker(RoleMakerBase): + """ + This role maker is for general use, you can set os.environ to customize: + PADDLE_PSERVERS_IP_PORT_LIST : all pservers' ip:port, separated by ',' + PADDLE_TRAINER_ENDPOINTS : all trainers' ip:port, separated by ',' + TRAINING_ROLE : TRAINER or PSERVER + PADDLE_TRAINER_ID : current trainer id (only for trainer), + it is index in PADDLE_TRAINER_ENDPOINTS + PADDLE_PSERVER_ID : current pserver id (only for pserver) + it is index in PADDLE_PSERVERS_IP_PORT_LIST + """ + + def __init__(self, **kwargs): + super(GeneralRoleMaker, self).__init__() + self._role_is_generated = False + self._hdfs_name = kwargs.get("hdfs_name", "") + self._hdfs_ugi = kwargs.get("hdfs_ugi", "") + self._hdfs_path = kwargs.get("path", "").rstrip("/") + self._init_timeout_seconds = kwargs.get("init_timeout_seconds", 3600) + self._run_timeout_seconds = kwargs.get("run_timeout_seconds", 9999999) + self._use_metric = kwargs.get("use_metric", False) + ip_port = kwargs.get("http_ip_port", "") + self._use_ps_gpu = kwargs.get("use_ps_gpu", False) + self._http_ip_port = [] + self._http_server = None + # if ip_port is not empty, it will use http instead of hdfs + if ip_port != "": + self._http_ip_port = ip_port.split(":") + # it's for communication between processes + self._manager = Manager() + # global dict to store status + self._http_server_d = self._manager.dict() + # set running status of http server + self._http_server_d["running"] = False + self._iface = self.__get_default_iface() + self._iface = "" if self._iface == "lo" else self._iface + # this environment variable can be empty + self._prefix = os.getenv("SYS_JOB_ID", "") + + def generate_role(self): + """ + generate role for general role maker + """ + if not self._role_is_generated: + eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split(",") + training_role = os.environ["TRAINING_ROLE"] + worker_endpoints = os.environ["PADDLE_TRAINER_ENDPOINTS"].split(",") + trainers_num = len(worker_endpoints) + if training_role not in ["TRAINER", "PSERVER"]: + raise ValueError("TRAINING_ROLE must be PSERVER or TRAINER") + self._is_barrier_all = 1 + if "PADDLE_IS_BARRIER_ALL_ROLE" in os.environ: + self._is_barrier_all = int( + os.environ["PADDLE_IS_BARRIER_ALL_ROLE"]) + if training_role == "TRAINER": + role = Role.WORKER + current_id = int(os.environ["PADDLE_TRAINER_ID"]) + if current_id == 0 and len(self._http_ip_port) != 0: + size_d = { + "trainer": len(worker_endpoints), + "pserver": len(eplist), + "all": len(worker_endpoints) + len(eplist) + } + # child process for http server + self._http_server = Process(target=self.__start_kv_server, + args=(self._http_server_d, + size_d)) + self._http_server.daemon = True + # set running status to True + self._http_server_d["running"] = True + # start child process + self._http_server.start() + self._node_type = 1 + self._cur_endpoint = worker_endpoints[current_id] + if self._is_barrier_all: + gloo = fluid.core.Gloo() + gloo.set_rank(current_id) + gloo.set_size(len(worker_endpoints)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + if len(self._http_ip_port) != 0: + gloo.set_http_store(self._http_ip_port[0], + int(self._http_ip_port[1]), + "trainer") + else: + gloo.set_hdfs_store(self._hdfs_path + "/trainer", + self._hdfs_name, self._hdfs_ugi) + gloo.init() + self._node_type_comm = gloo + if self._use_ps_gpu or self._use_metric: + Gloo_strategy = fluid.core.GlooParallelStrategy() + Gloo_strategy.rank = current_id + Gloo_strategy.rank_num = len(worker_endpoints) + Gloo_strategy.ip_address = self._http_ip_port[0] + Gloo_strategy.ip_port = int(self._http_ip_port[1]) + Default_init_timeout_seconds = 3600 + Default_run_timeout_seconds = 9999999 + Gloo_strategy.init_seconds = Default_init_timeout_seconds + Gloo_strategy.run_seconds = Default_run_timeout_seconds + Gloo = fluid.core.GlooParallelContext(Gloo_strategy) + Gloo.init() + else: + self._all_comm = MockBarrier() + elif training_role == "PSERVER": + role = Role.SERVER + if os.environ.get("PADDLE_PSERVER_ID") is not None: + current_id = int(os.environ["PADDLE_PSERVER_ID"]) + cur_endpoint = eplist[current_id] + else: + # this is for compatible with paddlecloud + cur_ip = os.environ["POD_IP"] + cur_port = os.environ["PADDLE_PORT"] + cur_endpoint = ":".join([cur_ip, cur_port]) + current_id = eplist.index(cur_endpoint) + self._node_type = 0 + self._cur_endpoint = cur_endpoint + gloo = fluid.core.Gloo() + gloo.set_rank(current_id) + gloo.set_size(len(eplist)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + if len(self._http_ip_port) != 0: + gloo.set_http_store(self._http_ip_port[0], + int(self._http_ip_port[1]), "pserver") + else: + gloo.set_hdfs_store(self._hdfs_path + "/pserver", + self._hdfs_name, self._hdfs_ugi) + gloo.init() + self._node_type_comm = gloo + + gloo = fluid.core.Gloo() + all_list = worker_endpoints + eplist + gloo.set_rank(all_list.index(self._cur_endpoint)) + gloo.set_size(len(all_list)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + if len(self._http_ip_port) != 0: + gloo.set_http_store(self._http_ip_port[0], + int(self._http_ip_port[1]), "all") + else: + gloo.set_hdfs_store(self._hdfs_path + "/all", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + self._all_comm = gloo + self._trainers_num = trainers_num + self._server_endpoints = eplist + self._role = role + self._current_id = current_id + self._rank = all_list.index(self._cur_endpoint) + self._size = len(all_list) + self._worker_endpoints = worker_endpoints + self._role_is_generated = True + + def all_gather(self, input): + """ + all gather between trainers and pservers + + Args: + input(int|float): input value + + Returns: + return a list of values + """ + return self._all_gather(input) + + def all_reduce_worker(self, input, output, mode="sum"): + """ + all reduce between trainers if current role is TRAINER, + only support array of one dim. + + Args: + input(list/numpy.array): array of one dim + output(list/numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + if not self.is_worker(): + return + self._all_reduce(input, output, mode) + + def barrier_worker(self): + """ + barrier between trainers if current role is TRAINER + """ + self._barrier_worker() + + def barrier_all(self): + """ + barrier between trainers if current role is PSERVER + """ + self._barrier_all() + + def get_local_endpoint(self): + """ + get local endpoint of current process + """ + if not self._role_is_generated: + self.generate_role() + return self._cur_endpoint + + def get_trainer_endpoints(self): + """ + get endpoint of all trainers + """ + if not self._role_is_generated: + self.generate_role() + return self._worker_endpoints + + def get_pserver_endpoints(self): + """ + get endpoint of all pservers + """ + if not self._role_is_generated: + self.generate_role() + return self._server_endpoints + + def is_worker(self): + """ + whether current process is worker + """ + if not self._role_is_generated: + self.generate_role() + return self._role == Role.WORKER + + def is_server(self): + """ + whether current process is server + """ + if not self._role_is_generated: + self.generate_role() + return self._role == Role.SERVER + + def is_first_worker(self): + """ + whether current process is worker of rank 0 + """ + if not self._role_is_generated: + self.generate_role() + return self._role == Role.WORKER and self._current_id == 0 + + def worker_index(self): + """ + get index of current worker + """ + if not self._role_is_generated: + self.generate_role() + return self._current_id + + def server_index(self): + """ + get index of current server + """ + if not self._role_is_generated: + self.generate_role() + return self._current_id + + def worker_num(self): + """ + retrun the current number of worker + """ + if not self._role_is_generated: + self.generate_role() + return self._worker_num() + + def server_num(self): + """ + return the current number of server + """ + if not self._role_is_generated: + self.generate_role() + return self._server_num() + + def _barrier_worker(self): + """ + barrier all workers in current distributed job + """ + if not self._role_is_generated: + self.generate_role() + if self.is_worker(): + self._node_type_comm.barrier() + + def _barrier_all(self): + """ + barrier all workers and servers in current distributed job + """ + if not self._role_is_generated: + self.generate_role() + self._all_comm.barrier() + + def _barrier_server(self): + """ + barrier all servers in current distributed job + """ + if not self._role_is_generated: + self.generate_role() + if self.is_server(): + self._node_type_comm.barrier() + + def _worker_num(self): + """ + return the current number of worker + """ + if not self._role_is_generated: + self.generate_role() + return self._trainers_num + + def _server_num(self): + """ + return the current number of server + """ + if not self._role_is_generated: + self.generate_role() + return len(self._server_endpoints) + + def _finalize(self): + """Default do nothing.""" + pass + + def _all_reduce(self, input, output, mode="sum"): + """ + all reduce between all workers + + Args: + input(list|numpy.array): array of one dim + output(list|numpy.array): array of one dim + mode(str): "sum" or "min" or "max" + """ + if not self._role_is_generated: + self.generate_role() + input_list = [i for i in input] + ans = self._node_type_comm.all_reduce(input_list, mode) + for i in range(len(ans)): + output[i] = ans[i] + + def _all_gather(self, obj): + """ + gather between all workers and pservers + """ + if not self._role_is_generated: + self.generate_role() + self._barrier_all() + return self._all_comm.all_gather(obj) + + def _worker_gather(self, obj): + """ + gather between all workers + """ + if not self._role_is_generated: + self.generate_role() + if not self.is_worker(): + return None + self._barrier_worker() + return self._node_type_comm.all_gather(obj) + + def _get_rank(self): + """ + get current rank in all workers and pservers + """ + if not self._role_is_generated: + self.generate_role() + return self._rank + + def _get_size(self): + """ + get total num of all workers and pservers + """ + if not self._role_is_generated: + self.generate_role() + return self._size + + def __get_default_iface(self): + """ + get default physical interface + """ + default1 = self.__get_default_iface_from_gateway() + default2 = self.__get_default_iface_from_interfaces() + return default2 if default1 == "lo" else default1 + + def __get_default_iface_from_gateway(self): + """ + get default physical interface + """ + res = os.popen("route -A inet").read().strip().split("\n") + + gateway_idx = None + iface_idx = None + for item in res: + item = item.split() + if "Gateway" in item and "Iface" in item: + gateway_idx = item.index("Gateway") + iface_idx = item.index("Iface") + elif gateway_idx != None and iface_idx != None: + gateway = None + if len(item) > gateway_idx: + gateway = item[gateway_idx] + if gateway and gateway != '*' and gateway != "0.0.0.0" and len( + item) > iface_idx: + return item[iface_idx] + return "lo" + + def __get_default_iface_from_interfaces(self): + """ + get default physical interface + """ + res = os.popen("ip -f inet addr | awk NR%3==1").read().strip().split( + "\n") + for item in res: + if "BROADCAST" in item: + return item.split(":")[1].strip() + return "lo" + + def __start_kv_server(self, http_server_d, size_d): + from paddle.fluid.incubate.fleet.utils.http_server import KVServer + http_server = KVServer(int(self._http_ip_port[1]), size_d) + http_server.start() + wait_seconds = 5 + while http_server_d.get("running", False): + time.sleep(wait_seconds) + http_server.stop() + + +class HeterRoleMaker(GeneralRoleMaker): + """ + This role maker is for general use, you can set os.environ to customize: + PADDLE_PSERVERS_IP_PORT_LIST : all pservers' ip:port, separated by ',' + PADDLE_TRAINER_ENDPOINTS : all trainers' ip:port, separated by ',' + TRAINING_ROLE : TRAINER or PSERVER + PADDLE_TRAINER_ID : current trainer id (only for trainer), + it is index in PADDLE_TRAINER_ENDPOINTS + PADDLE_PSERVER_ID : current pserver id (only for pserver) + it is index in PADDLE_PSERVERS_IP_PORT_LIST + """ + + def generate_role(self): + """ + generate role for general role maker + """ + if not self._role_is_generated: + eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split(",") + training_role = os.environ["TRAINING_ROLE"] + worker_endpoints = os.environ["PADDLE_TRAINER_ENDPOINTS"].split(",") + trainers_num = len(worker_endpoints) + xpu_endpoints = os.environ["PADDLE_XPU_ENDPOINTS"].split(",") + xpu_num = len(xpu_endpoints) + if training_role not in ["TRAINER", "PSERVER", "XPU"]: + raise ValueError( + "TRAINING_ROLE must be PSERVER or TRAINER or XPU") + if training_role == "TRAINER": + role = Role.WORKER + current_id = int(os.environ["PADDLE_TRAINER_ID"]) + self._node_type = 1 + self._cur_endpoint = worker_endpoints[current_id] + gloo = fluid.core.Gloo() + + gloo.set_rank(current_id) + gloo.set_size(len(worker_endpoints)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store( + self._hdfs_path.rstrip("/") + "/trainer", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + self._node_type_comm = gloo + elif training_role == "XPU": + role = Role.XPU + current_id = int(os.environ["PADDLE_XPU_ID"]) + self._node_type = 2 + self._cur_endpoint = xpu_endpoints[current_id] + gloo = fluid.core.Gloo() + + gloo.set_rank(current_id) + gloo.set_size(len(xpu_endpoints)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store( + self._hdfs_path.rstrip("/") + "/xpu", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + self._node_type_comm = gloo + elif training_role == "PSERVER": + role = Role.SERVER + if os.environ.get("PADDLE_PSERVER_ID") is not None: + current_id = int(os.environ["PADDLE_PSERVER_ID"]) + cur_endpoint = eplist[current_id] + else: + # this is for compatible with paddlecloud + cur_ip = os.environ["POD_IP"] + cur_port = os.environ["PADDLE_PORT"] + cur_endpoint = ":".join([cur_ip, cur_port]) + current_id = eplist.index(cur_endpoint) + self._node_type = 0 + self._cur_endpoint = cur_endpoint + gloo = fluid.core.Gloo() + gloo.set_rank(current_id) + gloo.set_size(len(eplist)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store( + self._hdfs_path.rstrip("/") + "/pserver", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + self._node_type_comm = gloo + + if training_role == "TRAINER" or training_role == "XPU": + gloo = fluid.core.Gloo() + heter_list = worker_endpoints + xpu_endpoints + + gloo.set_rank(heter_list.index(self._cur_endpoint)) + gloo.set_size(len(heter_list)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store( + self._hdfs_path.rstrip("/") + "/heter", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + self._heter_comm = gloo + + gloo = fluid.core.Gloo() + all_list = worker_endpoints + eplist + xpu_endpoints + + gloo.set_rank(all_list.index(self._cur_endpoint)) + gloo.set_size(len(all_list)) + gloo.set_prefix(self._prefix) + gloo.set_iface(self._iface) + gloo.set_timeout_seconds(self._init_timeout_seconds, + self._run_timeout_seconds) + gloo.set_hdfs_store( + self._hdfs_path.rstrip("/") + "/all", self._hdfs_name, + self._hdfs_ugi) + gloo.init() + + self._all_comm = gloo + self._trainers_num = trainers_num + self._server_endpoints = eplist + self._role = role + self._current_id = current_id + self._rank = all_list.index(self._cur_endpoint) + self._size = len(all_list) + self._worker_endpoints = worker_endpoints + self._xpu_endpoints = xpu_endpoints + self._role_is_generated = True + + def is_xpu(self): + """ + whether current process is server + """ + if not self._role_is_generated: + self.generate_role() + return self._role == Role.XPU + + def is_first_xpu(self): + """ + whether current process is worker of rank 0 + """ + if not self._role_is_generated: + self.generate_role() + return self._role == Role.XPU and self._current_id == 0 + + def _barrier_xpu(self): + """ + barrier all workers in current distributed job + """ + if not self._role_is_generated: + self.generate_role() + if self.is_xpu(): + self._node_type_comm.barrier() + + def _barrier_heter(self): + """ + barrier all workers in current distributed job + """ + if not self._role_is_generated: + self.generate_role() + if self.is_xpu() or self.is_worker: + self._heter_comm.barrier() + + def xpu_num(self): + """ + """ + if not self._role_is_generated: + self.generate_role() + return len(self._xpu_endpoints) + + +class UserDefinedRoleMaker(RoleMakerBase): + """ + UserDefinedRoleMaker is designed for worker and server assignment + under manual. Typically, a worker and a server node will be appointed + on each physical node, It can be assign by user. + """ + + def __init__(self, + current_id=0, + role=Role.WORKER, + worker_num=0, + server_endpoints=None): + super(UserDefinedRoleMaker, self).__init__() + + if not isinstance(server_endpoints, list): + raise TypeError("server_endpoints must be as string list") + elif len(server_endpoints) <= 0: + raise ValueError( + "the length of server_endpoints list must be greater than 0") + elif len(server_endpoints) != len(set(server_endpoints)): + raise ValueError("server_endpoints can't have duplicate elements") + else: + for server_endpoint in server_endpoints: + if not isinstance(server_endpoint, str): + raise TypeError( + "every element in server_endpoints list must be as string" + ) + self._server_endpoints = server_endpoints + + if role != Role.WORKER and role != Role.SERVER: + raise TypeError("role must be as Role") + else: + self._role = role + + if not isinstance(current_id, int): + raise TypeError("current_id must be as int") + else: + if current_id < 0: + raise ValueError( + "current_id must be greater than or equal to 0") + elif self._role == Role.SERVER and current_id >= len( + server_endpoints): + raise ValueError( + "if role is Role.SERVER, current_id must be less than or equal to len(server_endpoints) - 1" + ) + self._current_id = current_id + + if not isinstance(worker_num, int): + raise TypeError("worker_num must be as int") + else: + if worker_num <= 0: + raise ValueError("worker_num must be greater than 0") + self._worker_num = worker_num + + def generate_role(self): + self._role_is_generated = True + + def is_worker(self): + return self._role == Role.WORKER + + def is_server(self): + return self._role == Role.SERVER + + def is_first_worker(self): + return self._role == Role.WORKER and self._current_id == 0 + + def worker_index(self): + return self._current_id + + def server_index(self): + return self._current_id + + def worker_num(self): + return self._worker_num + + +class UserDefinedCollectiveRoleMaker(RoleMakerBase): + """ + UserDefinedCollectiveRoleMaker is designed for worker assignment + under manual for collective mode. + """ + + def __init__(self, current_id=0, worker_endpoints=None): + super(UserDefinedCollectiveRoleMaker, self).__init__() + + if not isinstance(worker_endpoints, list): + raise TypeError("worker_endpoints must be as string list") + elif len(worker_endpoints) <= 0: + raise ValueError( + "the length of worker_endpoints list must be greater than 0") + elif len(worker_endpoints) != len(set(worker_endpoints)): + raise ValueError("worker_endpoints can't have duplicate elements") + else: + for worker_endpoint in worker_endpoints: + if not isinstance(worker_endpoint, str): + raise TypeError( + "every element in worker_endpoints list must be as string" + ) + self._worker_endpoints = worker_endpoints + + if not isinstance(current_id, int): + raise TypeError("current_id must be as int") + else: + if current_id < 0: + raise ValueError( + "current_id must be greater than or equal to 0") + elif current_id >= len(worker_endpoints): + raise ValueError( + "current_id must be less than or equal to len(worker_endpoints) - 1" + ) + self._current_id = current_id + + self._worker_num = len(self._worker_endpoints) + + def generate_role(self): + self._role_is_generated = True + + def is_worker(self): + return True + + def is_first_worker(self): + return self._current_id == 0 + + def worker_index(self): + return self._current_id + + def worker_num(self): + return self._worker_num diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/collective/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/collective/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da4fe609ca3e65aed0737422367db54461b97d2e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/collective/__init__.py @@ -0,0 +1,514 @@ +# 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 + +import logging + +import paddle.fluid as fluid +import paddle.fluid.io as io +import paddle.fluid.transpiler.distribute_transpiler as dist_transpiler +from paddle.fluid.executor import Executor +from paddle.fluid.parallel_executor import ParallelExecutor +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.framework import Program + +from paddle.fluid.incubate.fleet.base.fleet_base import Fleet +from paddle.fluid.incubate.fleet.base.fleet_base import Mode +from paddle.fluid.incubate.fleet.base.fleet_base import DistributedOptimizer + +from paddle.fluid import compiler +from paddle.fluid.incubate.checkpoint.checkpoint_saver import PaddleModel, CheckpointSaver + +import paddle + +import os +import sys +import six +import json +import re +import shutil + + +class LambConfig(object): + + def __init__(self): + pass + + +class DistFCConfig(object): + + def __init__(self): + pass + + +class Collective(Fleet): + + def __init__(self): + super(Collective, self).__init__(Mode.COLLECTIVE) + self._local_ip = 0 + + self.startup_program = None + self._origin_program = None + self._transpiled_program = None + self.main_program = None + self._checkpoint_prefix = "__paddle_fleet_checkpoint__" + self._param_file_name = "_paddle_fleet_param__" + + def init_worker(self): + logging.warn( + "You should not call 'init_worker' method for collective mode.") + + def run_worker(self, main_programs=None, scopes=None): + logging.warn( + "You should not call 'run_worker' method for collective mode.") + + def init_server(self, model_dir=None): + logging.warn( + "You should not call 'init_server' method for collective mode.") + + def run_server(self): + logging.warn( + "You should not call 'run_server' method for collective mode.") + + def stop_worker(self): + logging.warn( + "You should not call 'stop_worker' method for collective mode.") + + def distributed_optimizer(self, optimizer, strategy=None): + self._optimizer = \ + CollectiveOptimizer(optimizer, strategy) + return self._optimizer + + def save_inference_model(self, + executor, + dirname, + feeded_var_names=None, + target_vars=None, + main_program=None, + export_for_deployment=True): + """ + Prune the given `main_program` to build a new program especially for + inference, and then save it and all related parameters to given + `dirname` by the `executor`. + """ + assert isinstance(executor, Executor), \ + "In fleet.save_inference_model() function, executor must be as" \ + " Executor type." + + if main_program is None: + main_program = self._origin_program + assert isinstance(main_program, Program), \ + "In fleet.save_inference_model() function, main_program " \ + "must be as Program type." + + io.save_inference_model(dirname, feeded_var_names, target_vars, + executor, main_program, None, None, + export_for_deployment) + + def save_persistables(self, + executor, + dirname, + main_program=None, + filename=None): + """ + This function filters out all variables with `persistable==True` from + the give `main_program` and then saves these variables to the folder + `dirname` or file `filename`. + + The `dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set `filename` None; if you would like to save all variables in a + single file, use `filename` to specify the file name. + """ + assert isinstance(executor, Executor), \ + "In fleet.save_inference_model() function, executor must be as" \ + " Executor type." + + if main_program is None: + main_program = self._origin_program + + assert isinstance(main_program, Program), \ + "In fleet.save_inference_model() function, main_program " \ + "must be as Program type." + + io.save_persistables(executor, dirname, main_program, filename=filename) + + def save_checkpoint(self, + executor, + path, + trainer_id, + train_status, + fs, + main_program=None, + local_cache_path=".cache", + remain_all_checkpoint=True): + """ + This function save persistables and current epoch num to path. + """ + if main_program == None: + main_program = self._transpiled_program + + m = PaddleModel(executor, main_program) + t = train_status + c = CheckpointSaver(fs) + real_path, checkpoint_no = c.save_checkpoint( + path=path, + slists=[m, t], + trainer_id=trainer_id, + local_cache_path=local_cache_path) + + if not remain_all_checkpoint: + c.clean_redundant_checkpoints(path) + + return real_path, checkpoint_no + + def load_checkpoint(self, + executor, + path, + trainer_id, + train_status, + fs, + main_program=None, + local_cache_path=".cache", + ignore_empty=True): + """ + This function load persistables and current epoch num from path. + """ + + if main_program == None: + main_program = self._transpiled_program + + m = PaddleModel(executor, main_program) + c = CheckpointSaver(fs) + return c.load_checkpoint(path, [m, train_status], + trainer_id=trainer_id, + ignore_empty=ignore_empty, + local_cache_path=local_cache_path) + + +fleet = Collective() + + +class DistributedStrategy(fluid.BuildStrategy): + """ + Init function of DistributedStrategy + """ + + def __init__(self): + super(DistributedStrategy, self).__init__() + self.use_local_sgd = False + self.use_dist_fc = False + + self.dist_fc_config = None # DistFCConfig + self.mode = "nccl2" # or collective + self.collective_mode = None # local_sgd or grad_allreduce + self.nccl_comm_num = 1 + self.forward_recompute = False # use RecomputeOptimizer + self.recompute_checkpoints = [] + self.use_amp = False # use mixed precision optimizer + self.amp_loss_scaling = 2**15 + + self.exec_strategy = fluid.ExecutionStrategy() + + # configurations below are used for unit test + self._ut4grad_allreduce = False + + +class CollectiveOpBasedOptimizer(DistributedOptimizer): + """ + Collective Operator Base Class For Distributed Optimizer + The class is invisible to a user + """ + + def __init__(self, optimizer, strategy=None): + assert isinstance( + strategy, + DistributedStrategy), "strategy must be DistributedStrategy" + super(CollectiveOpBasedOptimizer, self).__init__(optimizer, strategy) + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + return self._optimizer.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_gradients(self, params_grads): + return self._optimizer.apply_gradients(params_grads) + + +class CollectiveOptimizer(DistributedOptimizer): + """ + DistributedOptimizer is a wrapper for paddle.fluid.optimizer + A user should pass a paddle.fluid.optimizer to DistributedOptimizer + minimize() function is implemented. + DistributedOptimizer is the starting point for a user who wants to + run distributed training. The optimized information will be stored in + Fleet() instance who holds the global information about current distributed + training. + """ + + def __init__(self, optimizer, strategy=DistributedStrategy()): + if strategy is None: + strategy = DistributedStrategy() + super(CollectiveOptimizer, self).__init__(optimizer, strategy) + self._forward_recompute = strategy.forward_recompute + if (not isinstance(strategy.recompute_checkpoints, list)): + raise ValueError("DistStrategy.recompute_checkpoints should" + "be a List") + self._recompute_checkpoints = strategy.recompute_checkpoints + self._use_amp = strategy.use_amp + self._amp_loss_scaling = strategy.amp_loss_scaling + self.print_config = False + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + return self._optimizer.backward(loss, startup_program, parameter_list, + no_grad_set, callbacks) + + def apply_gradients(self, params_grads): + return self._optimizer.apply_gradients(params_grads) + + def _check_condition(self, name, **kwargs): + for k, v in six.iteritems(kwargs): + if v is True: + assert False, "you can't use %s and %s together" % (name, k) + + def _check_collective_mode(self, main_program, optimizer, strategy): + """ + Check the conflict conditions. + """ + if strategy.use_local_sgd: + strategy.mode = "collective" + strategy.collective_mode = "local_sgd" + self._check_condition("use_local_sgd", + use_dgc=main_program._enable_dgc, + use_dist_fc=strategy.use_dist_fc, + use_lamb=main_program._use_lamb) + + if strategy.use_dist_fc: + self._check_condition("use_dist_fc", + use_dgc=main_program._enable_dgc, + use_local_sgd=strategy.use_local_sgd, + use_lamb=main_program._use_lamb) + assert strategy.dist_fc_config is not None, "DistributedStrategy.dist_fc_config should be set" + + if strategy._ut4grad_allreduce: + strategy.mode = "collective" + strategy.collective_mode = "grad_allreduce" + self._check_condition("_ut4grad_allreduce", + use_dgc=main_program._enable_dgc, + use_lamb=main_program._use_lamb) + + if self._strategy.collective_mode=="local_sgd" \ + or self._strategy.collective_mode == "grad_allreduce": + assert self._strategy.mode == "collective", \ + "local_sgd and grad_allreduce can be used under collective mode" + + def _transpile(self, startup_program, main_program): + """ + Transpile the programs to distributed programs. And add the variables. + """ + worker_endpoints = fleet.worker_endpoints() + trainer_id = fleet.worker_index() + current_endpoint = fleet.worker_endpoints()[trainer_id] + worker_endpoints_env = ','.join(worker_endpoints) + trainers_num = fleet.worker_num() + + if self.print_config: + print("worker_endpoints:{} trainers_num:{} current_endpoint:{} \ + trainer_id:{}".format(worker_endpoints, trainers_num, + current_endpoint, trainer_id)) + + # call transpiler + config = dist_transpiler.DistributeTranspilerConfig() + config.mode = self._strategy.mode + config.collective_mode = self._strategy.collective_mode + + config.nccl_comm_num = self._strategy.nccl_comm_num + config.use_hierarchical_allreduce = self._strategy.use_hierarchical_allreduce + config.hierarchical_allreduce_inter_nranks = self._strategy.hierarchical_allreduce_inter_nranks + + t = dist_transpiler.DistributeTranspiler(config=config) + t.transpile(trainer_id=trainer_id, + trainers=worker_endpoints_env, + startup_program=startup_program, + program=main_program, + current_endpoint=current_endpoint) + + def _get_node_ips_from_endpoints(self, endpoints): + ss = set() + ips = [] + for ep in endpoints: + ip = ep.split(":")[0].strip() + if ip not in ss: + ss.add(ip) + ips.append(ip) + else: + continue + + return ips + + def _node_num(self): + worker_endpoints = fleet.worker_endpoints() + current_endpoint = fleet.worker_endpoints()[fleet.worker_index()] + worker_endpoints_env = ','.join(worker_endpoints) + + node_ips = self._get_node_ips_from_endpoints(worker_endpoints) + node_ip = current_endpoint.split(":")[0].strip() + + node_num = len(node_ips) + + return node_num + + def _try_to_compile(self, startup_program, main_program): + node_num = self._node_num() + assert node_num >= 1, "nccl2 node_num must >= 1, now:{}" % node_num + + exec_strategy = self._strategy.exec_strategy + + if node_num <= 1: + if self._strategy.nccl_comm_num > 1: + logging.warn("set nccl_comm_num=1 since you only have 1 node.") + self._strategy.nccl_comm_num = 1 + + if self._strategy.use_hierarchical_allreduce: + logging.warn( + "set use_hierarchical_allreduce=False since you only have 1 node." + ) + self._strategy.use_hierarchical_allreduce = False + + sync_allreduce = os.getenv("FLAGS_sync_nccl_allreduce") + if sync_allreduce is None or sync_allreduce == "1": + exec_strategy.num_threads = self._strategy.nccl_comm_num + 1 + if self._strategy.use_hierarchical_allreduce: + exec_strategy.num_threads = 2 * self._strategy.nccl_comm_num + 1 + if exec_strategy.num_threads > 4: + logging.warn( + "if you use use_hierarchical_allreduce or " + "with multi nccl comm, please export FLAGS_sync_nccl_allreduce = 0" + ) + + # NOTE. open sync_batch_norm will hang when use multi num_threads + sync_batch_norm = self._strategy.sync_batch_norm + if sync_batch_norm is not None and sync_batch_norm is True: + self._strategy.nccl_comm_num = 1 + self._strategy.use_hierarchical_allreduce = False + exec_strategy.num_threads = 1 + logging.warn( + "use sync_batch_norm will hang when set num_threads > 1, so " + "set num_threads=1, nccl_comm_num=1, use_hierarchical_allreduce=False." + ) + + if self.print_config: + print("node_num:", node_num, "num_threads:", + exec_strategy.num_threads, "use_hierarchical_allreduce:", + self._strategy.use_hierarchical_allreduce, "nccl_comm_num:", + self._strategy.nccl_comm_num, "FLAGS_sync_nccl_allreduce:", + sync_allreduce) + + self._transpile(startup_program, main_program) + + if self._strategy.mode == "collective": + return main_program + + self._strategy.num_trainers = fleet.worker_num() + self._strategy.trainer_id = fleet.worker_index() + self._strategy.trainers_endpoints = fleet.worker_endpoints() + self._strategy.enable_backward_optimizer_op_deps = True + + self._compiled_program = compiler.CompiledProgram(main_program) + + self._compiled_program.with_data_parallel( + loss_name=self._loss.name, + build_strategy=self._strategy, + exec_strategy=self._strategy.exec_strategy, + share_vars_from=None) + + return self._compiled_program + + def raiseOptimizeError(self, strategy_name, optimize_name): + raise ValueError("can not use {0} when you set DistStrategy.{1} " + "as True".format(optimize_name, strategy_name)) + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + minimize a program through loss + Args: + loss (Variable|Variable List): loss variable or loss variable list to run optimization. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + Returns: + tuple: (optimize_ops, params_grads) which are, list of operators appended; + and list of (param, grad) Variables pair for optimization. + Note that in parameter server mode, a worker will not get anything about optimize_os + Because optimizer algorithms run on pserver side. We will make this usable in pserver + process, but currently the optimization part is written into Fleet(). A user does not + need to care about how to startup a pserver node. + """ + + # check optimizer conflicts + if self._forward_recompute: + if self._recompute_checkpoints == []: + raise ValueError("please set strategy.recompute_checkpoints" + "when set strategy.forward_recompute as True") + if self._optimizer.__class__.__name__ in [ + "RecomputeOptimizer", "OptimizerWithMixedPrecision" + ]: + self.raiseOptimizeError("forward_recompute", + self._optimizer.__class__.__name__) + + self._optimizer = \ + fluid.optimizer.RecomputeOptimizer(self._optimizer) + self._optimizer._set_checkpoints(self._recompute_checkpoints) + + if self._use_amp: + if self._optimizer.__class__.__name__ in [ + "OptimizerWithMixedPrecision", "DGCMomentumOptimizer" + ]: + self.raiseOptimizeError("mixed_precision", + self._optimizer.__class__.__name__) + self._optimizer = fluid.contrib.mixed_precision.decorate( + self._optimizer, + init_loss_scaling=self._amp_loss_scaling, + use_dynamic_loss_scaling=True) + + main_program = loss.block.program + if startup_program is None: + startup_program = fluid.default_startup_program() + fleet.startup_program = startup_program + + self._loss = loss + + self._check_collective_mode(main_program, self._optimizer, + self._strategy) + + optimize_ops, param_grads = self._optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set=no_grad_set) + + fleet._origin_program = main_program.clone(for_test=False) + fleet._transpiled_program = main_program + fleet.main_program = self._try_to_compile(startup_program, main_program) + + return optimize_ops, param_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33ed0ecf10ec4cad807ebb6df1590de65eeeab1e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67c1a0f0f8b47470973fab7c6ea071be01a4ca69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/__init__.py @@ -0,0 +1,870 @@ +# 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. +""" +Convert the fluid program to distributed data-parallelism programs. +""" + +import os +import sys +import warnings + +from paddle import fluid +from paddle.fluid import core +from paddle.fluid.framework import default_main_program +from paddle.fluid.framework import default_startup_program +from paddle.fluid.framework import Program +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.executor import Executor +from paddle.fluid.parallel_executor import ParallelExecutor +from paddle.fluid.optimizer import Optimizer + +from paddle.fluid.transpiler.distribute_transpiler import DistributeTranspilerConfig + +from paddle.fluid.incubate.fleet.base.fleet_base import Fleet +from paddle.fluid.incubate.fleet.base.mode import Mode +from paddle.fluid.incubate.fleet.base.role_maker import MPISymetricRoleMaker + +from paddle.fluid.incubate.fleet.parameter_server import version +from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_lr_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _has_global_step +from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import TrainerRuntimeConfig, DistributedStrategy, \ + SyncStrategy, AsyncStrategy, HalfAsyncStrategy, GeoStrategy, StrategyFactory + +from paddle.fluid.transpiler.details.checkport import wait_server_ready + +from paddle.fluid.incubate.fleet.parameter_server.mode import PSMode +from paddle.fluid.incubate.fleet.base.fleet_base import DistributedOptimizer + +from paddle.fluid.incubate.fleet.parameter_server.ir import trainer_pass as worker +from paddle.fluid.incubate.fleet.parameter_server.ir import pserver_pass as server +from paddle.fluid.incubate.fleet.parameter_server.ir import public as public + + +class FleetTranspiler(Fleet): + """ + A subclass for compatibility with fluid.transpiler.DistributeTranspiler. + """ + + def __init__(self): + super(FleetTranspiler, self).__init__(Mode.TRANSPILER) + + self._inner_mode = None + + if version.is_transpiler(): + self._inner_mode = PSMode.TRANSPILER + else: + self._inner_mode = PSMode.PSLIB + + self._strategy = None + self._transpiler = None + self._origin_main_program = None + self._origin_startup_program = None + self._communicator = None + self.startup_program = None + self.main_program = None + + self._opt_info = None + self._local_ip = 0 + self._fleet_ptr = None + self._main_programs = [] + self._scopes = [] + self._client2client_request_timeout_ms = 500000 + self._client2client_connect_timeout_ms = 10000 + self._client2client_max_retry = 3 + + def init(self, role_maker=None): + if role_maker is None: + role_maker = MPISymetricRoleMaker() + super(FleetTranspiler, self).init(role_maker) + if self._fleet_ptr is None: + self._fleet_ptr = core.Fleet() + + def _init_transpiler_worker(self): + """ + `init_worker` has many many functions to do before training, + first, wait for all parameter servers launch completely. + second, run executor to initialize startup program + third, wait for all worker initialize completely. + + Returns: + None + """ + + def sync_strategy_envs(): + kwargs = {} + kwargs[ + "pserver_endpoints"] = self._role_maker.get_pserver_endpoints() + kwargs["trainer_id"] = self._role_maker.worker_index() + return kwargs + + def geo_strategy_envs(): + + def get_sparse_attrs(): + opt_init_map = {} + opt_init_map["gaussian_random"] = ["seed", "mean", "std"] + opt_init_map["fill_constant"] = ["value"] + opt_init_map["uniform_random"] = ["seed", "min", "max"] + opt_init_map["truncated_gaussian_random"] = [ + "seed", "mean", "std" + ] + + dist_varnames = get_sparse_tablenames(self._origin_main_program, + True) + sparse_varnames = get_sparse_tablenames( + self._origin_main_program, False) + + if len(dist_varnames) != 0: + raise ValueError( + "GeoStrategy can not support large scale embeding now, please use fluid.layers.embedding" + ) + + init_attrs = [] + for value_name in sparse_varnames: + value_var = self._origin_main_program.global_block( + ).vars[value_name] + value_attr = [ + value_name, + ",".join([str(dim) for dim in value_var.shape]) + ] + for op in self._origin_startup_program.global_block().ops: + if op.type in opt_init_map.keys( + ) and value_name == op.output("Out")[0]: + init_attr = [op.type] + for attr in opt_init_map[op.type]: + init_attr.append(str(op.attr(attr))) + value_attr.append("&".join(init_attr)) + init_attrs.append(":".join(value_attr)) + break + return "#".join(init_attrs) + + kwargs = {} + kwargs["trainers"] = self.worker_num() + kwargs["sparse_attrs"] = get_sparse_attrs() + return kwargs + + # if MPISymetricRoleMaker is defined + # we suppose a user wants to submit job on mpi cluster + + if isinstance(self._role_maker, MPISymetricRoleMaker): + # check whether server has been initialized + wait_server_ready(self.server_endpoints(to_string=False)) + + trainer_config = self._strategy.get_trainer_runtime_config() + + print(trainer_config) + + lrs = _has_global_step(_get_lr_ops(self._origin_main_program)) + + if lrs > 0: + kwargs = {"need_global_step": "1"} + else: + kwargs = {"need_global_step": "0"} + + if isinstance(self._strategy, GeoStrategy): + geo_kwargs = geo_strategy_envs() + kwargs.update(geo_kwargs) + if isinstance(self._strategy, SyncStrategy): + sync_kwargs = sync_strategy_envs() + kwargs.update(sync_kwargs) + + kwargs = kwargs if kwargs else None + + send_ctx = fleet.compiled_config.get_communicator_send_context() + + if self.compiled_config.is_geo_mode(): + recv_ctx = fleet.compiled_config.get_communicator_recv_context( + recv_type=4) + else: + recv_ctx = fleet.compiled_config.get_communicator_recv_context( + recv_type=1) + + from paddle.fluid.communicator import Communicator + self._communicator = Communicator( + trainer_config.mode, kwargs, + trainer_config.get_communicator_flags()) + + self._communicator.init_with_ctx(send_ctx, recv_ctx) + + if not self._communicator.is_running(): + self._communicator.start() + else: + raise ValueError( + "Communicator can only be inited once, please check") + + def init_worker(self): + """ + `init_worker` has many many functions to do before training, + first, wait for all parameter servers launch completely. + second, run executor to initialize startup program + third, wait for all worker initialize completely. + + Returns: + None + """ + if self._inner_mode == PSMode.TRANSPILER: + self._init_transpiler_worker() + else: + raise NotImplementedError("add implement later") + + def _init_transpiler_server(self, model_dir=None): + if not self.startup_program: + raise ValueError( + "startup_program is None, need invoke DistributedOptimizer.minimize first" + ) + + self._executor.run(self.startup_program) + + if model_dir: + if not os.path.isdir(model_dir): + raise ValueError("There is no directory named '%s'", model_dir) + + sparse_varnames = self.compiled_config.get_sparse_varname_on_ps( + True) + distribtued_varnames = self.compiled_config.get_sparse_varname_on_ps( + False) + + remaining_vars = list( + filter( + FleetTranspiler.__exclude_vars(sparse_varnames + + distribtued_varnames), + self.main_program.list_vars())) + + fluid.io.load_vars(self._executor, + main_program=self.main_program, + dirname=model_dir, + vars=remaining_vars) + + self._load_sparse_params(dirname=model_dir, + varnames=sparse_varnames) + + # todo(tangwei12) load distributed vars + # self._load_sparse_params(dirname=model_dir, varnames=distribtued_varnames) + + def init_server(self, model_dir=None, **kwargs): + """ + `init_server` has many many functions to do before start pserver, + first, run executor to initialize startup program, + second, if the `model_dir` is not empty, it will load parameters from it for increment training. + + Args: + model_dir(str): The directory path. + + Returns: + None + """ + + if self._inner_mode == PSMode.TRANSPILER: + self._init_transpiler_server(model_dir) + else: + raise NotImplementedError("add implement later") + + def run_server(self): + """ + `run_server` execute executor to start pserver main program. + + Returns: + None + """ + + if self._inner_mode == PSMode.TRANSPILER: + if not self.main_program: + raise ValueError( + "main_program is None, need invoke DistributedOptimizer.minimize first" + ) + + self._executor.run(self.main_program) + else: + raise NotImplementedError("add implement later") + + def stop_worker(self): + """ + Close this executor. + + For the distributed training, this method would free the resource on PServers related to + the current Trainer. + + Returns: + None + """ + + if self._inner_mode == PSMode.TRANSPILER: + self._communicator.stop() + if isinstance(self._role_maker, MPISymetricRoleMaker): + self._role_maker._finalize() + self._executor.close() + else: + raise NotImplementedError("add implement later") + + def distributed_optimizer(self, optimizer, strategy=None): + """ + Optimizer for distributed training. + + For the distributed training, this method would rebuild a new instance of DistributedOptimizer. + Which has basic Optimizer function and special features for distributed training. + + Args: + optimizer(Optimizer): The executor to run for init server. + strategy(DistributeTranspilerConfig): Extra properties for distributed optimizer. + + Returns: + TranspilerOptimizer: subclass of DistributedOptimizer. + """ + + if not isinstance(optimizer, Optimizer): + raise ValueError("optimizer must be an instance of Optimizer") + if not self._is_initialized: + raise ValueError( + "fleet.init(role) to initialize before optimizer.minimize(loss)" + ) + + if not strategy: + _strategy = StrategyFactory.create_async_strategy() + + if isinstance(strategy, DistributedStrategy): + _strategy = strategy + elif isinstance(strategy, DistributeTranspilerConfig): + if strategy.sync_mode: + _strategy = SyncStrategy() + else: + if strategy.runtime_split_send_recv: + if strategy.geo_sgd_mode: + _strategy = GeoStrategy(strategy.geo_sgd_need_push_nums) + elif strategy.half_async: + _strategy = HalfAsyncStrategy() + else: + _strategy = AsyncStrategy() + else: + _strategy = HalfAsyncStrategy() + # for half_async compatibility + strategy.half_async = True + strategy.runtime_split_send_recv = True + _strategy.set_program_config(strategy) + elif isinstance(strategy, dict): + if self._inner_mode != PSMode.PSLIB: + raise TypeError("Dict strategy can only be used at PSLIB Mode") + + _strategy = StrategyFactory.create_async_strategy() + _strategy.set_pslib_runtime_config(strategy) + else: + raise TypeError( + "strategy must be an instance of DistributeTranspilerConfig, DistributedStrategy" + ) + + self._strategy = _strategy + self._optimizer = ParameterServerOptimizer(optimizer, _strategy) + return self._optimizer + + def save_inference_model(self, + executor, + dirname, + feeded_var_names, + target_vars, + main_program=None, + export_for_deployment=True): + """ + Prune the given `main_program` to build a new program especially for inference, + and then save it and all related parameters to given `dirname` by the `executor`. + """ + + if self._inner_mode == PSMode.PSLIB: + raise NotImplementedError("add implement later") + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save_inference_model() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save_inference_model() function, executor must be as Executor type" + ) + + # Todo(MrChengmo): support recv&save GPU-Kernel for ps-gpu model save + if not isinstance(executor.place, fluid.CPUPlace): + save_executor = Executor(fluid.CPUPlace()) + else: + save_executor = executor + + if main_program is not None: + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save_inference_model() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + fluid.io.save_inference_model(dirname, feeded_var_names, + target_vars, executor, main_program, + None, None, export_for_deployment) + else: + fluid.io.save_inference_model(dirname, feeded_var_names, + target_vars, executor, + self._origin_main_program, None, None, + export_for_deployment, True) + + model_basename = "__model__" + model_filename = os.path.join(dirname, model_basename) + + with open(model_filename, "rb") as f: + program_desc_str = f.read() + + program = Program.parse_from_string(program_desc_str) + program._copy_dist_param_info_from(self.main_program) + self.save_persistables(executor, dirname, program) + + def _load_sparse_params(self, dirname, varnames): + from paddle.fluid.communicator import LargeScaleKV + scale_kv = LargeScaleKV() + for varname in varnames: + origin_varname, _, _ = public._get_varname_parts(varname) + sparse_dir = os.path.join(dirname, origin_varname, varname) + scale_kv.load(varname, sparse_dir) + + def _get_optimizer_status(self, op, param_name): + supported_opts = [ + "sgd", "adam", "adagrad", "adamax", "momentum", "lars_momentum", + "rmsprop", "decayed_adagrad", "ftrl" + ] + + reshaped_val_map = {} + reshaped_val_map["sgd"] = [] + reshaped_val_map["adam"] = ["moment1_0", "moment2_0"] + reshaped_val_map["adagrad"] = ["moment_0"] + reshaped_val_map["adamax"] = ["moment_0", "inf_norm_0"] + reshaped_val_map["momentum"] = ["velocity_0"] + reshaped_val_map["lars_momentum"] = ["velocity_0"] + reshaped_val_map["rmsprop"] = [ + "momentum_0", "mean_square_0", "mean_grad_0" + ] + reshaped_val_map["decayed_adagrad"] = ["moment_0"] + reshaped_val_map["ftrl"] = ["squared_0", "linear_0"] + + orishaped_val_map = {} + orishaped_val_map["adam"] = ["beta1_pow_acc_0", "beta2_pow_acc_0"] + orishaped_val_map["adamax"] = ["beta1_pow_acc_0"] + + if op not in supported_opts: + raise ValueError( + "fleet can not support optimizer: {}, only this can be supported: {}" + .format(op, supported_opts)) + + reshaped_names = [ + param_name + "_" + val for val in reshaped_val_map[op] + ] + + if op not in orishaped_val_map: + origin_names = [] + else: + origin_names = [ + param_name + "_" + val for val in orishaped_val_map[op] + ] + return reshaped_names, origin_names + + def _get_optimizer_op(self, param_name): + opts = public._get_optimize_ops(self._origin_main_program) + for op in opts: + if "Param" in op.input_names and \ + "LearningRate" in op.input_names and op.input("Param")[0] == param_name: + return op + + def _save_dense_params(self, executor, dirname, context, main_program): + self._communicator.recv() + + prog = Program() + block = prog.global_block() + local_vars = [] + + for name, var_ctx in context.items(): + if len(var_ctx.origin_varnames()) != 1: + raise ValueError("Dense can not support split now.") + + varname = var_ctx.origin_varnames()[0] + local_vars.append(varname) + + optimizer = self._get_optimizer_op(varname) + reshaped_varnames, origin_varnames = self._get_optimizer_status( + optimizer.type, varname) + + for var_name in [varname] + reshaped_varnames + origin_varnames: + var = self._origin_main_program.global_block().vars[var_name] + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self._role_maker.worker_index(), + "shape": + var.shape, + "slice_shapes": + [",".join([str(i) for i in var.shape])], + "slice_varnames": [var.name], + "remote_varnames": [var.name], + "is_sparse": + False, + "endpoints": + var_ctx.split_endpoints(), + "file_path": + os.path.join(dirname, var.name) + }) + + executor.run(prog) + return local_vars + + def _save_sparse_params(self, executor, dirname, context, main_program): + prog = Program() + block = prog.global_block() + local_vars = [] + + for name, var_ctx in context.items(): + if len(var_ctx.origin_varnames()) != 1: + raise ValueError("Dense can not support split now.") + + varname = var_ctx.origin_varnames()[0] + local_vars.append(varname) + + optimizer = self._get_optimizer_op(varname) + reshaped_varnames, origin_varnames = self._get_optimizer_status( + optimizer.type, varname) + + var = self._origin_main_program.global_block().vars[varname] + slice_shapes = [] + dims1 = ",".join([str(i) for i in var.shape[1:]]) + + for section in var_ctx.sections(): + slice_shapes.append(str(section) + dims1) + + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self._role_maker.worker_index(), + "shape": + var.shape, + "slice_shapes": + slice_shapes, + "slice_varnames": + var_ctx.split_varnames(), + "remote_varnames": + var_ctx.split_varnames(), + "is_sparse": + True, + "endpoints": + var_ctx.split_endpoints(), + "pserver_num": + len(self._role_maker.get_pserver_endpoints()), + "file_path": + os.path.join(dirname, var.name) + }) + + for reshaped_varname in reshaped_varnames: + var = self._origin_main_program.global_block( + ).vars[reshaped_varname] + + slice_varnames = [] + remote_varnames = [] + for i in range(len(var_ctx.split_varnames())): + slice_varnames.append("{}.block{}".format( + reshaped_varname, i)) + remote_varnames.append(reshaped_varname) + + block.append_op( + type='recv_save', + attrs={ + "trainer_id": self._role_maker.worker_index(), + "shape": var.shape, + "slice_shapes": slice_shapes, + "slice_varnames": slice_varnames, + "remote_varnames": remote_varnames, + "is_sparse": True, + "endpoints": var_ctx.split_endpoints(), + "pserver_num": + len(self._role_maker.get_pserver_endpoints()), + "file_path": os.path.join(dirname, var.name) + }) + + for origin_varname in origin_varnames: + var = self._origin_main_program.global_block( + ).vars[origin_varname] + + block.append_op(type='recv_save', + attrs={ + "trainer_id": + self._role_maker.worker_index(), + "shape": + var.shape, + "slice_shapes": + [",".join([str(i) for i in var.shape])], + "slice_varnames": [origin_varname], + "remote_varnames": [origin_varname], + "is_sparse": + False, + "endpoints": + var_ctx.split_endpoints()[:1], + "file_path": + os.path.join(dirname, var.name) + }) + executor.run(prog) + return context.keys() + + def _save_distributed_params(self, executor, dirname, context, + main_program): + prog = Program() + block = prog.global_block() + + for name, var_ctx in context.items(): + block.append_op(type='checkpoint_notify', + attrs={ + "varname": name, + "is_slice": True, + "slice_varnames": var_ctx.split_varnames(), + "remote_varnames": var_ctx.split_varnames(), + "endpoints": var_ctx.split_endpoints(), + "dirname": dirname + }) + + executor.run(prog) + return context.keys() + + def _save_distributed_persistables(self, executor, dirname, main_program): + dense_ctx = fleet.compiled_config.get_communicator_recv_context( + recv_type=1) + + sparse_ctx = fleet.compiled_config.get_communicator_recv_context( + recv_type=2) + + distributed_ctx = fleet.compiled_config.get_communicator_recv_context( + recv_type=3) + + recv_dense_varnames = self._save_dense_params(executor, dirname, + dense_ctx, main_program) + + recv_sparse_varnames = self._save_sparse_params(executor, dirname, + sparse_ctx, + main_program) + + recv_distributed_varnames = self._save_distributed_params( + executor, dirname, distributed_ctx, main_program) + + saved_varnames = recv_dense_varnames + list( + recv_sparse_varnames) + list(recv_distributed_varnames) + + remaining_vars = list( + filter(FleetTranspiler.__exclude_vars(saved_varnames), + main_program.list_vars())) + + fluid.io.save_vars(executor, + main_program=main_program, + dirname=dirname, + vars=remaining_vars) + + def save_persistables(self, executor, dirname, main_program=None, **kwargs): + """ + This function filters out all variables with `persistable==True` from the + give `main_program` and then saves these variables to the folder `dirname` + or file `filename`. + + The `dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set `filename` None; +if you would like to save all variables in a + single file, use `filename` to specify the file name. + """ + + if self._inner_mode == PSMode.PSLIB: + raise NotImplementedError("add implement later") + + if isinstance(executor, ParallelExecutor): + raise TypeError( + "in fleet.save_persistables() function, executor must be as Executor type, ParallelExecutor is not allowed" + ) + + if not isinstance(executor, Executor): + raise TypeError( + "in fleet.save_persistables() function, executor must be as Executor type" + ) + # Todo(MrChengmo): support recv&save GPU-Kernel for ps-gpu model save + if not isinstance(executor.place, fluid.CPUPlace): + save_executor = Executor(fluid.CPUPlace()) + else: + save_executor = executor + + if main_program is None: + main_program = self.main_program + + if isinstance(main_program, CompiledProgram): + raise TypeError( + "in fleet.save_persistables() function, main_program must be as Program type, CompiledProgram is not allowed" + ) + + self._save_distributed_persistables(save_executor, dirname, + main_program) + + @staticmethod + def __exclude_vars(exclude_var_names=[]): + + def is_valid(var): + if var.name in exclude_var_names: + return False + + origin_varname, _, _ = public._get_varname_parts(var.name) + if origin_varname.endswith("@GRAD"): + return False + + if origin_varname == "learning_rate_0": + return False + + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + return is_valid + + +# fleet is a global instance for parameter server. +fleet = FleetTranspiler() + + +class ParameterServerOptimizer(DistributedOptimizer): + """ + DistributedOptimizer is a wrapper for paddle.fluid.optimizer + A user should pass a paddle.fluid.optimizer to DistributedOptimizer + minimize() function is implemented. + DistributedOptimizer is the starting point for a user who wants to + run distributed training. The optimized information will be stored in + Fleet() instance who holds the global information about current distributed + training. + + Args: + optimizer(Optimizer): subclass of Optimizer. + strategy(DistributeTranspilerConfig): instance of DistributeTranspilerConfig. + + Returns: + None + """ + + def __init__(self, optimizer, strategy, mode=PSMode.TRANSPILER): + super(ParameterServerOptimizer, self).__init__(optimizer, strategy) + self._mode = mode + if self._mode == PSMode.PSLIB: + self._optimizer_name = "Distributed%s" % optimizer.type.capitalize() + if optimizer.type != "adam": + print( + "Currently, distributed optimizer only support Adam" + "Will config built-in adam for you." + "We will support more functions in DistributedOptimizer", + sys.stderr) + self._optimizer_name = "DistributedAdam" + + self._optimizer = globals()[self._optimizer_name](optimizer) + else: + self._optimizer = optimizer + + self._window = 1 + self.type = "downpour" + self.data_norm_name = [ + ".batch_size", ".batch_square_sum", ".batch_sum", + ".batch_size@GRAD", ".batch_square_sum@GRAD", ".batch_sum@GRAD" + ] + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + raise NotImplementedError() + + def apply_gradients(self, params_grads): + raise NotImplementedError() + + def _build_trainer_programs(self, compiled_config): + _main = fleet._origin_main_program.clone() + _startup = fleet._origin_startup_program.clone() + + if not compiled_config.is_geo_mode(): + # for main program + _main = worker.delete_optimizer_pass(_main, compiled_config) + _main = worker.distributed_ops_pass(_main, compiled_config) + _main = worker.append_send_ops_pass(_main, compiled_config) + + # for startup program + _startup = worker.fake_init_ops_pass(_startup, compiled_config) + _startup = worker.init_from_server_pass(_startup, compiled_config) + _startup = worker.delet_extra_optimizes_pass( + _startup, compiled_config) + else: + _main = worker.append_send_ops_pass(_main, compiled_config) + _startup = _startup + + return _main, _startup + + def _build_pserver_programs(self, compiled_config): + _main = fluid.Program() + _startup = fluid.Program() + + if not compiled_config.is_geo_mode(): + _main = server.add_listen_and_serv_pass(_main, compiled_config) + _main = server.add_rpc_global_flags_pass(_main, compiled_config) + _main = server.add_optimizer_pass(_main, compiled_config) + _main = server.large_scale_sparse_pass(_main, _main, + compiled_config, False) + _startup = server.build_pserver_startup_program_pass( + _startup, _main, compiled_config) + _startup = server.large_scale_sparse_pass(_startup, _main, + compiled_config, True) + + if not compiled_config.is_sync_mode(): + _main = server.delete_unused_in_main_pass( + _main, compiled_config) + + _startup = server.delete_unused_in_startup_pass( + _startup, _main, compiled_config) + else: + _main = server.add_listen_and_serv_pass(_main, compiled_config) + _main = server.add_rpc_global_flags_pass(_main, compiled_config) + _main = server.add_geo_optimizer_pass(_main, compiled_config) + _main = server.large_scale_sparse_pass(_main, _main, + compiled_config, False) + _startup = server.build_pserver_startup_program_pass( + _startup, _main, compiled_config) + _startup = server.large_scale_sparse_pass(_startup, _main, + compiled_config, True) + _startup = server.delete_unused_in_startup_pass( + _startup, _main, compiled_config) + + return _main, _startup + + def minimize(self, + losses, + scopes=None, + startup_programs=None, + parameter_list=None, + no_grad_set=None): + + if isinstance(losses, list): + raise ValueError("need implement later") + + self._optimizer.minimize(losses, startup_programs, parameter_list, + no_grad_set) + + fleet._origin_main_program = default_main_program().clone( + for_test=False) + fleet._origin_startup_program = default_startup_program().clone( + for_test=False) + + compiled_config = public.CompileTimeStrategy( + fleet._origin_main_program, fleet._origin_startup_program, + self._strategy, fleet._role_maker) + + fleet.compiled_config = compiled_config + fleet.main_program, fleet.startup_program = \ + self._build_trainer_programs(compiled_config) if fleet.is_worker() \ + else self._build_pserver_programs(compiled_config) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/distributed_strategy.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/distributed_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..8e40fa81ebbc4d4c6bf89f5fcce92364a054d1d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/distribute_transpiler/distributed_strategy.py @@ -0,0 +1,438 @@ +# 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. + +__all__ = [ + "TrainerRuntimeConfig", "DistributedStrategy", "SyncStrategy", + "AsyncStrategy", "HalfAsyncStrategy", "GeoStrategy", "StrategyFactory" +] + +import os +import paddle.fluid as fluid +from paddle.fluid.transpiler.distribute_transpiler import DistributeTranspilerConfig, ServerRuntimeConfig +from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode + + +class TrainerRuntimeConfig(object): + + def __init__(self): + self.mode = None + num_threads = os.getenv("CPU_NUM", "1") + + self.runtime_configs = {} + self.runtime_configs['communicator_max_merge_var_num'] = os.getenv( + "FLAGS_communicator_max_merge_var_num", num_threads) + self.runtime_configs['communicator_send_queue_size'] = os.getenv( + "FLAGS_communicator_send_queue_size", num_threads) + self.runtime_configs[ + 'communicator_independent_recv_thread'] = os.getenv( + "FLAGS_communicator_independent_recv_thread", "1") + self.runtime_configs[ + 'communicator_min_send_grad_num_before_recv'] = os.getenv( + "FLAGS_communicator_min_send_grad_num_before_recv", num_threads) + self.runtime_configs['communicator_thread_pool_size'] = os.getenv( + "FLAGS_communicator_thread_pool_size", "5") + self.runtime_configs['communicator_send_wait_times'] = os.getenv( + "FLAGS_communicator_send_wait_times", "5") + self.runtime_configs['communicator_is_sgd_optimizer'] = os.getenv( + "FLAGS_communicator_is_sgd_optimizer", "1") + + # not used + self.runtime_configs['rpc_deadline'] = os.getenv( + "FLAGS_rpc_deadline", "180000") + self.runtime_configs['rpc_retry_times'] = os.getenv( + "FLAGS_rpc_retry_times", "3") + + def get_communicator_flags(self): + need_keys = [] + num_threads = os.getenv("CPU_NUM", "1") + mode_str = "" + if self.mode is None or self.mode == DistributedMode.ASYNC: + need_keys = self.runtime_configs.keys() + mode_str = "async" + elif self.mode == DistributedMode.SYNC or self.mode == DistributedMode.HALF_ASYNC: + mode_str = "sync or half_async" + need_keys = [ + 'communicator_max_merge_var_num', + 'communicator_send_wait_times', 'communicator_thread_pool_size', + 'communicator_send_queue_size' + ] + elif self.mode == DistributedMode.GEO: + mode_str = "GEO" + need_keys = [ + 'communicator_thread_pool_size', 'communicator_send_wait_times', + 'communicator_max_merge_var_num', 'communicator_send_queue_size' + ] + else: + raise ValueError("Unsupported Mode") + + if self.mode == DistributedMode.SYNC or self.mode == DistributedMode.HALF_ASYNC: + max_merge_var_num = self.runtime_configs[ + 'communicator_max_merge_var_num'] + send_queue_size = self.runtime_configs[ + 'communicator_send_queue_size'] + if max_merge_var_num != num_threads: + print('WARNING: In {} mode, communicator_max_merge_var_num ' + 'must be equal to CPU_NUM. But received, ' + 'communicator_max_merge_var_num = {}, CPU_NUM = ' + '{}. communicator_max_merge_var_num will be fored to {}.'. + format(mode_str, max_merge_var_num, num_threads, + num_threads)) + self.runtime_configs[ + 'communicator_max_merge_var_num'] = num_threads + if send_queue_size != num_threads: + print('WARNING: In {} mode, communicator_send_queue_size ' + 'must be equal to CPU_NUM. But received, ' + 'communicator_send_queue_size = {}, CPU_NUM = ' + '{}. communicator_send_queue_size will be fored to {}.'. + format(mode_str, send_queue_size, num_threads, + num_threads)) + self.runtime_configs[ + 'communicator_send_queue_size'] = num_threads + + return dict((key, str(self.runtime_configs[key])) for key in need_keys) + + def display(self, configs): + raw0, raw1, length = 45, 5, 50 + h_format = "{:^45s}{:<5s}\n" + l_format = "{:<45s}{:<5s}\n" + + border = "".join(["="] * length) + line = "".join(["-"] * length) + + draws = "" + draws += border + "\n" + draws += h_format.format("TrainerRuntimeConfig Overview", "Value") + draws += line + "\n" + + for k, v in configs.items(): + draws += l_format.format(k, v) + + draws += border + + _str = "\n{}\n".format(draws) + return _str + + def __repr__(self): + return self.display(self.get_communicator_flags()) + + +class PSLibRuntimeConfig(object): + + def __init__(self): + self.runtime_configs = {} + + def get_runtime_configs(self): + return self.runtime_configs + + +class DistributedStrategy(object): + + def __init__(self): + self._program_config = DistributeTranspilerConfig() + self._trainer_runtime_config = TrainerRuntimeConfig() + self._pslib_runtime_config = PSLibRuntimeConfig() + self._server_runtime_config = ServerRuntimeConfig() + num_threads = int(os.getenv("CPU_NUM", "1")) + + self._execute_strategy = fluid.ExecutionStrategy() + self._build_strategy = fluid.BuildStrategy() + + self._execute_strategy.num_threads = num_threads + if num_threads > 1: + self._build_strategy.reduce_strategy = fluid.BuildStrategy.ReduceStrategy.Reduce + self.debug_opt = None + self.use_ps_gpu = False + + def set_debug_opt(self, opt_info): + self.debug_opt = opt_info + + def get_debug_opt(self): + opt_info = dict() + if self.debug_opt is not None and isinstance(self.debug_opt, dict): + opt_info["dump_slot"] = bool(self.debug_opt.get("dump_slot", 0)) + opt_info["dump_converter"] = str( + self.debug_opt.get("dump_converter", "")) + opt_info["dump_fields"] = self.debug_opt.get("dump_fields", []) + opt_info["dump_file_num"] = self.debug_opt.get("dump_file_num", 16) + opt_info["dump_fields_path"] = self.debug_opt.get( + "dump_fields_path", "") + opt_info["dump_param"] = self.debug_opt.get("dump_param", []) + return opt_info + + def get_program_config(self): + return self._program_config + + def set_program_config(self, config): + if isinstance(config, DistributeTranspilerConfig): + self._program_config = config + elif isinstance(config, dict): + for key in config: + if hasattr(self._program_config, key): + setattr(self._program_config, key, config[key]) + else: + raise ValueError( + "DistributeTranspilerConfig doesn't have key: {}". + format(key)) + else: + raise TypeError( + "program_config only accept input type: dict or DistributeTranspilerConfig" + ) + self.check_program_config() + + def check_program_config(self): + raise NotImplementedError( + "check_program_config must be implemented by derived class. You should use StrategyFactory to create DistributedStrategy." + ) + + def get_trainer_runtime_config(self): + return self._trainer_runtime_config + + def set_trainer_runtime_config(self, config): + if isinstance(config, TrainerRuntimeConfig): + self._trainer_runtime_config = config + elif isinstance(config, dict): + for key, Value in config.items(): + if key in self._trainer_runtime_config.runtime_configs: + self._trainer_runtime_config.runtime_configs[key] = Value + else: + raise ValueError( + "TrainerRuntimeConfig doesn't have key: {}".format(key)) + else: + raise TypeError( + "trainer_runtime_config only accept input type: dict or TrainerRuntimeConfig" + ) + self.check_trainer_runtime_config() + + def check_trainer_runtime_config(self): + raise NotImplementedError( + "check_trainer_runtime_config must be implemented by derived class. You should use StrategyFactory to create DistributedStrategy." + ) + + def get_pslib_runtime_config(self): + return self._pslib_runtime_config + + def set_pslib_runtime_config(self, config): + self._pslib_runtime_config.runtime_configs = config + + def get_server_runtime_config(self): + return self._server_runtime_config + + def set_server_runtime_config(self, config): + if isinstance(config, ServerRuntimeConfig): + self._server_runtime_config = config + elif isinstance(config, dict): + for key in config: + if hasattr(self._server_runtime_config, key): + setattr(self._server_runtime_config, key, config[key]) + else: + raise ValueError( + "ServerRuntimeConfig doesn't have key: {}".format(key)) + else: + raise TypeError( + "server_runtime_config only accept input type: dict or ServerRuntimeConfig" + ) + self.check_server_runtime_config() + + def check_server_runtime_config(self): + raise NotImplementedError( + "check_server_runtime_config must be implemented by derived class. You should use StrategyFactory to create DistributedStrategy." + ) + + def get_execute_strategy(self): + return self._execute_strategy + + def set_execute_strategy(self, config): + if isinstance(config, fluid.ExecutionStrategy): + self._execute_strategy = config + elif isinstance(config, dict): + for key in config: + if hasattr(self._execute_strategy, key): + setattr(self._execute_strategy, key, config[key]) + else: + raise ValueError( + "ExecutionStrategy doesn't have key: {}".format(key)) + else: + raise TypeError( + "execute_strategy only accept input type: dict or ExecutionStrategy" + ) + self.check_execute_strategy() + + def check_execute_strategy(self): + raise NotImplementedError( + "check_execute_strategy must be implemented by derived class. You should use StrategyFactory to create DistributedStrategy." + ) + + def get_build_strategy(self): + return self._build_strategy + + def set_build_strategy(self, config): + if isinstance(config, fluid.BuildStrategy): + self._build_strategy = config + elif isinstance(config, dict): + for key in config: + if hasattr(self._build_strategy, key): + setattr(self._build_strategy, key, config[key]) + else: + raise ValueError( + "BuildStrategy doesn't have key: {}".format(key)) + else: + raise TypeError( + "build_strategy only accept input type: dict or BuildStrategy") + self.check_build_strategy() + + def check_build_strategy(self): + raise NotImplementedError( + "check_build_strategy must be implemented by derived class. You should use StrategyFactory to create DistributedStrategy." + ) + + +class SyncStrategy(DistributedStrategy): + + def __init__(self): + super(SyncStrategy, self).__init__() + self.check_program_config() + self.check_trainer_runtime_config() + self.check_server_runtime_config() + self.check_build_strategy() + self.check_execute_strategy() + + def check_trainer_runtime_config(self): + self._trainer_runtime_config.mode = DistributedMode.SYNC + + def check_program_config(self): + self._program_config.sync_mode = False + self._program_config.runtime_split_send_recv = True + self._program_config.half_async = True + self._program_config.completely_not_async = True + + def check_server_runtime_config(self): + pass + + def check_execute_strategy(self): + self._execute_strategy.use_thread_barrier = True + + def check_build_strategy(self): + self._build_strategy.async_mode = True + + +class AsyncStrategy(DistributedStrategy): + + def __init__(self): + super(AsyncStrategy, self).__init__() + self.check_program_config() + self.check_trainer_runtime_config() + self.check_server_runtime_config() + self.check_build_strategy() + self.check_execute_strategy() + + def check_trainer_runtime_config(self): + self._trainer_runtime_config.mode = DistributedMode.ASYNC + + def check_program_config(self): + self._program_config.sync_mode = False + self._program_config.runtime_split_send_recv = True + + def check_server_runtime_config(self): + pass + + def check_execute_strategy(self): + pass + + def check_build_strategy(self): + self._build_strategy.async_mode = True + + +class HalfAsyncStrategy(DistributedStrategy): + + def __init__(self): + super(HalfAsyncStrategy, self).__init__() + self.check_program_config() + self.check_trainer_runtime_config() + self.check_server_runtime_config() + self.check_build_strategy() + self.check_execute_strategy() + + def check_trainer_runtime_config(self): + self._trainer_runtime_config.mode = DistributedMode.HALF_ASYNC + + def check_program_config(self): + self._program_config.sync_mode = False + self._program_config.runtime_split_send_recv = True + self._program_config.half_async = True + + def check_server_runtime_config(self): + pass + + def check_execute_strategy(self): + self._execute_strategy.use_thread_barrier = True + + def check_build_strategy(self): + self._build_strategy.async_mode = True + + +class GeoStrategy(DistributedStrategy): + + def __init__(self, update_frequency=100): + super(GeoStrategy, self).__init__() + self._program_config.geo_sgd_need_push_nums = update_frequency + self.check_program_config() + self.check_trainer_runtime_config() + self.check_server_runtime_config() + self.check_build_strategy() + self.check_execute_strategy() + + def check_program_config(self): + self._program_config.sync_mode = False + self._program_config.runtime_split_send_recv = True + self._program_config.geo_sgd_mode = True + + def check_trainer_runtime_config(self): + self._trainer_runtime_config.mode = DistributedMode.GEO + + self._trainer_runtime_config.runtime_configs[ + 'communicator_send_queue_size'] = self._program_config.geo_sgd_need_push_nums + + self._trainer_runtime_config.runtime_configs[ + 'communicator_max_merge_var_num'] = self._program_config.geo_sgd_need_push_nums + + def check_server_runtime_config(self): + pass + + def check_execute_strategy(self): + pass + + def check_build_strategy(self): + self._build_strategy.async_mode = True + + +class StrategyFactory(object): + + def __init_(self): + pass + + @staticmethod + def create_sync_strategy(): + return SyncStrategy() + + @staticmethod + def create_half_async_strategy(): + return HalfAsyncStrategy() + + @staticmethod + def create_async_strategy(): + return AsyncStrategy() + + @staticmethod + def create_geo_strategy(update_frequency=100): + return GeoStrategy(update_frequency) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abf198b97e6e818e1fbe59006f98492640bcee54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/heter_trainer_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/heter_trainer_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..0018b73e264798dd21450564812dfca5ec992038 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/heter_trainer_pass.py @@ -0,0 +1,72 @@ +# 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. + +from __future__ import print_function +import warnings + +import paddle.fluid.core as core +import paddle.fluid.framework as framework + +from paddle.fluid.transpiler.details.program_utils import delete_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import find_heter_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import union_forward_gradient_op +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import create_heter_program +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import create_trainer_program +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import find_block_joints +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import find_op_input_output +from paddle.fluid.incubate.fleet.parameter_server.ir.trainer_pass import get_vars_name_in_block + + +def split_heter_worker_ops_pass(program, config, stage_id, device): + """ + split heter worker program from origin-program + 1. find heter op (located on different device) + 2. find input&output of every heter-block + 3. create heter worker program, add listen&serv op + """ + default_deveice = "cpu" + program, heter_ops, _, program_block_ops = find_heter_ops( + program, default_deveice) + if len(heter_ops) == 0: + warnings.warn( + "Currently running in Heter Parameter Server mode, but no OP running on heterogeneous devices, Please check your code." + ) + return program + + program_block_ops = union_forward_gradient_op(program_block_ops) + block_vars_detail = find_block_joints(program, program_block_ops, heter_ops) + heter_program = framework.Program() + create_heter_program(program, config, heter_program, program_block_ops, + heter_ops, block_vars_detail, device, stage_id) + return heter_program + + +def split_trainer_ops_pass(program, config, default_device="cpu"): + """ + split cpu-trainer program from origin-program + 1. find heter op (located on different device) + 2. find input&output of every heter-block + 3. create cpu-trainer program, add send&recv op + """ + # Todo: support user define default_device (MrChengmo) + default_device_ = default_device + program, heter_ops, default_ops, program_block_ops = find_heter_ops( + program, default_device_) + program_block_ops = union_forward_gradient_op(program_block_ops) + + block_vars_detail = find_block_joints(program, program_block_ops, heter_ops) + trainer_program = program.clone() + create_trainer_program(trainer_program, program, config, program_block_ops, + block_vars_detail) + return trainer_program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ps_dispatcher.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ps_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..74ded7c09967fce5c8cd5cc6551f875074ea4279 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ps_dispatcher.py @@ -0,0 +1,125 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + + +class PSDispatcher(object): + """ + PSDispatcher is the base class for dispatching vars + into different pserver instance. + You need to implement the `dispatch` interface. + """ + + def __init__(self, pserver_endpoints): + self._eps = pserver_endpoints + self._step = 0 + + @property + def eps(self): + return self._eps + + def reset(self): + """ + reset the step counter, set it zero. + """ + self._step = 0 + + def dispatch(self, varlist): + """ + Args: + varlist(list): a list of Variables + Returns: + a map of pserver endpoint -> varname + """ + raise NotImplementedError("Interface has not been implemented.") + + +class HashName(PSDispatcher): + """ + Hash variable names to several endpoints using python + "hash()" function. + + Args: + pserver_endpoints (list): list of endpoint(ip:port). + + Examples: + .. code-block:: python + + pserver_endpoints = ["127.0.0.1:6007", "127.0.0.1:6008"] + vars = ["var1","var2","var3","var4","var5"] + + rr = RoundRobin(pserver_endpoints) + rr.dispatch(vars) + + """ + + def __init__(self, pserver_endpoints): + super(HashName, self).__init__(pserver_endpoints) + + def _hash_block(self, block_str, total): + return hash(block_str) % total + + def dispatch(self, varlist): + """ + use `HashName` method to dispatch variables with each parameter server. + Args: + varlist (list): a list of Variables + + """ + eplist = [] + for var in varlist: + server_id = self._hash_block(var.name(), len(self._eps)) + server_for_param = self._eps[server_id] + eplist.append(server_for_param) + return eplist + + +class RoundRobin(PSDispatcher): + """ + Distribute variables to several endpoints using + RondRobin method. + + Args: + pserver_endpoints (list): list of endpoint(ip:port). + + Examples: + .. code-block:: python + + pserver_endpoints = ["127.0.0.1:6007", "127.0.0.1:6008"] + vars = ["var1","var2","var3","var4","var5"] + + rr = RoundRobin(pserver_endpoints) + rr.dispatch(vars) + + """ + + def __init__(self, pserver_endpoints): + super(RoundRobin, self).__init__(pserver_endpoints) + + def dispatch(self, varlist): + """ + use `RoundRobin` method to dispatch variables with each parameter server. + Args: + varlist (list): a list of Variables + + """ + eplist = [] + for var in varlist: + server_for_param = self._eps[self._step] + eplist.append(server_for_param) + self._step += 1 + if self._step >= len(self._eps): + self._step = 0 + return eplist diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/pserver_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/pserver_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..38a4a14b02f38256d7e2d459d69438d86a4a73b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/pserver_pass.py @@ -0,0 +1,1001 @@ +# 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. + +from __future__ import print_function + +import collections +import six + +from paddle.fluid import core +from paddle.fluid.framework import Block + +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_optimize_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _orig_varname +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_varname_parts +from paddle.fluid.incubate.fleet.parameter_server.ir.public import is_distributed_sparse_op +from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablename +from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_lr_ops + +LEARNING_RATE_DECAY_COUNTER = "@LR_DECAY_COUNTER@" +OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName() +RPC_OP_ROLE_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleAttrName() +OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize +LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched + + +def _is_optimizer_op(op): + if "Param" in op.input_names and \ + "LearningRate" in op.input_names: + return True + return False + + +def _same_or_split_var(p_name, var_name): + return p_name == var_name or p_name.startswith(var_name + ".block") + + +def _get_optimizer_input_shape(op_type, varkey, orig_shape, param_shape): + """ + Returns the shape for optimizer inputs that need to be reshaped when + Param and Grad is split to multiple servers. + """ + # HACK(typhoonzero) : Should use functions of corresponding optimizer in + # optimizer.py to get the shape, do not bind this in the transpiler. + if op_type == "adam": + if varkey in ["Moment1", "Moment2"]: + return param_shape + elif op_type == "adagrad": + if varkey == "Moment": + return param_shape + elif op_type == "adamax": + if varkey in ["Moment", "InfNorm"]: + return param_shape + elif op_type in ["momentum", "lars_momentum"]: + if varkey == "Velocity": + return param_shape + elif op_type == "rmsprop": + if varkey in ["Moment", "MeanSquare"]: + return param_shape + elif op_type == "decayed_adagrad": + if varkey == "Moment": + return param_shape + elif op_type == "ftrl": + if varkey in ["SquaredAccumulator", "LinearAccumulator"]: + return param_shape + elif op_type == "sgd": + pass + else: + raise ValueError( + "Not supported optimizer for distributed training: %s" % op_type) + return orig_shape + + +def _append_pserver_non_opt_ops(optimize_block, opt_op, origin_program, config): + + def _get_pserver_grad_param_var(var, var_dict): + """ + Return pserver side grad/param variable, return None + if the variable is not grad/param, e.g. + + a@GRAD -> a@GRAD.block0 + a@GRAD -> a@GRAD (a is not split) + fc_0.w_0 -> fc_0.w_0.block_0 + fc_0.w_0 -> fc_0.w_0 (weight is not split) + _generated_var_123 -> None + """ + + grad_block = None + for _, g in six.iteritems(var_dict): + if _orig_varname(g.name) == _orig_varname(var.name): + # skip per trainer vars + if g.name.find(".trainer_") == -1: + # only param or grads have split blocks + ovar_name = _orig_varname(g.name) + if ovar_name in config.param_grad_ep_mapping: + grad_block = g + break + elif ovar_name in config.grad_param_mapping: + grad_block = g + break + + return grad_block + + program = optimize_block.program + # Append the ops for parameters that do not need to be optimized / updated + inputs = _get_input_map_from_op(origin_program.global_block().vars, opt_op) + for key, varlist in six.iteritems(inputs): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + # for ops like clipping and weight decay, get the split var(xxx.block0) + # for inputs / outputs + grad_block = _get_pserver_grad_param_var( + var, + program.global_block().vars) + if grad_block: + varlist[i] = grad_block + elif var.name not in program.global_block().vars: + tmpvar = program.global_block()._clone_variable(var) + varlist[i] = tmpvar + else: + varlist[i] = program.global_block().vars[var.name] + inputs[key] = varlist + + outputs = _get_output_map_from_op(origin_program.global_block().vars, + opt_op) + for key, varlist in six.iteritems(outputs): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + grad_block = _get_pserver_grad_param_var( + var, + program.global_block().vars) + if grad_block: + varlist[i] = grad_block + elif var.name not in program.global_block().vars: + tmpvar = program.global_block()._clone_variable(var) + varlist[i] = tmpvar + else: + varlist[i] = program.global_block().vars[var.name] + outputs[key] = varlist + + return optimize_block.append_op(type=opt_op.type, + inputs=inputs, + outputs=outputs, + attrs=opt_op.all_attrs()) + + +def _append_pserver_ops(optimize_block, opt_op, endpoint, grad_to_block_id, + origin_program, merged_var, sparse_grad_to_param, + config): + program = optimize_block.program + pserver_block = program.global_block() + new_inputs = collections.OrderedDict() + + def _get_param_block(opt_op): + # param is already created on global program + unmerged_vars = [] + merged_vars = [] + merged_ordervars = [] + + param_vars = [ + p for p in config.param_grad_ep_mapping[endpoint]["params"] + ] + + for var in param_vars: + name = var.name + orig_varname = _orig_varname(name) + + for pairs in config.merged_variables_pairs: + merged_p = pairs[0] + if merged_p.merged_var.name == orig_varname: + if merged_p.merged_var.name == merged_p.ordered_vars[ + 0].name: + unmerged_vars.append(merged_p.ordered_vars[0]) + else: + merged_vars.append(merged_p.merged_var) + merged_ordervars.append(merged_p.ordered_vars[0]) + break + + param_name = opt_op.input("Param")[0] + + for i in range(len(unmerged_vars)): + if _same_or_split_var(param_name, unmerged_vars[i].name): + for var in param_vars: + if _same_or_split_var(var.name, unmerged_vars[i].name): + return var + + for i in range(len(merged_ordervars)): + if _same_or_split_var(param_name, merged_ordervars[i].name): + for var in param_vars: + if _same_or_split_var(var.name, merged_vars[i].name): + return var + return None + + for key in opt_op.input_names: + if key == "Grad": + # Note !!This is for l2decay on sparse gradient, \ + # because it will create a new tensor for + # decayed gradient but not inplace modify the origin one + origin_grad_name = opt_op.input(key)[0] + if core.kNewGradSuffix( + ) in origin_grad_name and pserver_block.has_var(origin_grad_name): + new_grad = pserver_block.var(origin_grad_name) + new_inputs[key] = new_grad + else: + new_inputs[key] = merged_var + elif key == "Param": + param_block = _get_param_block(opt_op) + + if not param_block: + return + tmpvar = pserver_block.create_var(name=param_block.name, + persistable=True, + dtype=param_block.dtype, + shape=param_block.shape) + new_inputs[key] = tmpvar + + elif key == "LearningRate": + # learning rate variable has already be created by non - optimize op, + # don't create it once again. + lr_varname = opt_op.input(key)[0] + if lr_varname in pserver_block.vars: + new_inputs[key] = pserver_block.vars[opt_op.input(key)[0]] + else: + origin_var = origin_program.global_block().vars[lr_varname] + tmpvar = pserver_block.create_var( + name=origin_var.name, + persistable=origin_var.persistable, + dtype=origin_var.dtype, + shape=origin_var.shape) + new_inputs[key] = tmpvar + + for key in opt_op.input_names: + new_shape = None + if key in [ + "Param", "Grad", "LearningRate", "MasterParam", "Beta1Tensor", + "Beta2Tensor" + ]: + continue + var = origin_program.global_block().vars[opt_op.input(key)[0]] + param_var = new_inputs["Param"] + # update accumulator variable shape + new_shape = _get_optimizer_input_shape(opt_op.type, key, var.shape, + param_var.shape) + tmpvar = pserver_block.create_var(name=var.name, + persistable=var.persistable, + dtype=var.dtype, + shape=new_shape) + new_inputs[key] = tmpvar + + # change output's ParamOut variable + outputs = _get_output_map_from_op(origin_program.global_block().vars, + opt_op) + outputs["ParamOut"] = new_inputs["Param"] + optimize_block.append_op(type=opt_op.type, + inputs=new_inputs, + outputs=outputs, + attrs=opt_op.all_attrs()) + + # record sparse grad to param name + if new_inputs["Grad"].type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_grad_to_param.append( + str(new_inputs["Grad"].name) + ":" + str(new_inputs["Param"].name)) + + +def _get_input_map_from_op(varmap, op): + """Returns a dict from op input name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.input_names: + vars = [] + for varname in op.input(key): + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def _get_output_map_from_op(varmap, op): + """Returns a dict from op output name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.output_names: + vars = [] + for varname in op.output(key): + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def get_op_by_type(block, op_type): + for op in block.ops: + if op.type == op_type: + return op + raise ValueError("add_listen_and_serv_pass must at first") + + +def add_listen_and_serv_pass(program, config): + attrs = { + "grad_to_block_id": None, + "sparse_grad_to_param": None, + "lr_decay_block_id": None, + "dense_optimize_blocks": None, + "sparse_optimize_blocks": None, + + # runtime attribute + "endpoint": config.get_ps_endpoint(), + "pserver_id": config.get_role_id(), + "Fanin": config.get_trainers(), + "distributed_mode": config.get_distributed_mode(), + "rpc_get_thread_num": -1, + "rpc_send_thread_num": -1, + "rpc_prefetch_thread_num": -1 + } + + # step5 append the listen_and_serv op + program.global_block().append_op(type="listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + + return program + + +def add_rpc_global_flags_pass(program, config): + server_runtime = config.get_server_runtime_config() + send_threads = server_runtime._rpc_send_thread_num + get_threads = server_runtime._rpc_get_thread_num + pull_threads = server_runtime._rpc_prefetch_thread_num + + op = get_op_by_type(program.global_block(), "listen_and_serv") + + if get_threads < 1 or send_threads < 1 or pull_threads < 1: + raise ValueError( + "error arguments in get_threads/send_threads/pull_threads") + + op._set_attr("rpc_get_thread_num", get_threads) + op._set_attr("rpc_send_thread_num", send_threads) + op._set_attr("rpc_prefetch_thread_num", pull_threads) + + return program + + +def _clone_var(block, var, persistable=True): + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=persistable) + + +def add_optimizer_pass(program, config): + + def _append_pserver_grad_merge_ops(optimize_block, grad_varname_for_block, + endpoint, grad_to_block_id): + trainers = config.get_trainers() + + program = optimize_block.program + pserver_block = program.global_block() + grad_block = None + + for g in config.param_grad_ep_mapping[endpoint]["grads"]: + if _orig_varname(g.name) == \ + _orig_varname(grad_varname_for_block): + grad_block = g + break + + if not grad_block: + # do not append this op if current endpoint + # is not dealing with this grad block + return None + + orig_varname, block_name, trainer_name = _get_varname_parts( + grad_block.name) + + if block_name: + merged_var_name = '.'.join([orig_varname, block_name]) + else: + merged_var_name = orig_varname + + merged_var = pserver_block.create_var(name=grad_block.name, + persistable=True, + type=grad_block.type, + dtype=grad_block.dtype, + shape=grad_block.shape) + + grad_to_block_id.append(merged_var.name + ":" + str(optimize_block.idx)) + if config.is_sync_mode() and trainers > 1: + vars2merge = [] + for i in range(trainers): + per_trainer_name = "%s.trainer_%d" % \ + (merged_var_name, i) + per_trainer_var = pserver_block.create_var( + name=per_trainer_name, + persistable=False, + type=grad_block.type, + dtype=grad_block.dtype, + shape=grad_block.shape) + vars2merge.append(per_trainer_var) + + optimize_block.append_op(type="sum", + inputs={"X": vars2merge}, + outputs={"Out": merged_var}, + attrs={"use_mkldnn": False}) + optimize_block.append_op(type="scale", + inputs={"X": merged_var}, + outputs={"Out": merged_var}, + attrs={"scale": 1.0 / float(trainers)}) + return merged_var + + origin_program = config.get_origin_main_program() + origin_program = origin_program.clone() + ps_endpoint = config.get_ps_endpoint() + + opt_op_on_pserver = [] + # Iterate through the ops, and if an op and the optimize ops + # which located on current pserver are in one set, then + # append it into the sub program. + global_ops = [] + # sparse grad name to param name + sparse_grad_to_param = [] + + def _is_opt_op_on_pserver(endpoint, op): + param_names = [ + p.name for p in config.param_grad_ep_mapping[endpoint]["params"] + ] + + unmerged_varnames = [] + merged_varnames = [] + merged_ordernames = [] + + for name in param_names: + orig_varname = _orig_varname(name) + + for pairs in config.merged_variables_pairs: + merged_p = pairs[0] + if merged_p.merged_var.name == orig_varname: + if merged_p.merged_var.name == merged_p.ordered_vars[ + 0].name: + unmerged_varnames.append(merged_p.ordered_vars[0].name) + else: + merged_varnames.append(merged_p.merged_var.name) + merged_ordernames.append(merged_p.ordered_vars[0].name) + break + + param = op.input("Param")[0] + + if param in unmerged_varnames: + return True + + for i in range(len(merged_ordernames)): + if param == merged_ordernames[i]: + merged_p = merged_varnames[i] + merged_g = "{}@GRAD".format(merged_varnames[i]) + op._set_attr(OP_ROLE_VAR_ATTR_NAME, [merged_p, merged_g]) + return True + return False + + def __append_optimize_op__(op, block, grad_to_block_id, merged_var, lr_ops): + if _is_optimizer_op(op): + _append_pserver_ops(block, op, ps_endpoint, grad_to_block_id, + origin_program, merged_var, + sparse_grad_to_param, config) + elif op not in lr_ops: + _append_pserver_non_opt_ops(block, op, origin_program, config) + + optimize_ops = _get_optimize_ops(origin_program) + for _, op in enumerate(optimize_ops): + if _is_optimizer_op(op) and _is_opt_op_on_pserver(ps_endpoint, op): + opt_op_on_pserver.append(op) + + # append lr decay ops to the child block if exists + lr_ops = _get_lr_ops(origin_program) + has_lr_decay = True if len(lr_ops) > 0 else False + lr_decay_block_id = -1 + optimize_blocks = [] + + if has_lr_decay > 0: + counter_increment_idx = -1 + for idx, op in enumerate(lr_ops): + if op.type != 'increment': + continue + counter = op.input("X")[0] + if counter == LEARNING_RATE_DECAY_COUNTER: + counter_increment_idx = idx + break + + if counter_increment_idx != -1: + lr_ops.pop(counter_increment_idx) + + lr_decay_block = program._create_block(program.num_blocks - 1) + optimize_blocks.append(lr_decay_block) + for op in lr_ops: + cloned_op = _append_pserver_non_opt_ops(lr_decay_block, op, + origin_program, config) + # append sub blocks to pserver_program in lr_decay_op + # todo(tangwei12): __clone_lr_op_sub_block__ + lr_decay_block_id = lr_decay_block.idx + + # append op to the current block + grad_to_block_id = [] + pre_block_idx = program.num_blocks - 1 + + for idx, opt_op in enumerate(opt_op_on_pserver): + per_opt_block = program._create_block(pre_block_idx) + optimize_blocks.append(per_opt_block) + optimize_target_param_name = opt_op.attr(OP_ROLE_VAR_ATTR_NAME)[0] + # append grad merging ops before clip and weight decay + # e.g.merge grad->L2Decay op->clip op->optimize + merged_var = None + for _, op in enumerate(optimize_ops): + # find the origin grad var before clipping / L2Decay, + # merged_var should be the input var name of L2Decay + grad_varname_for_block = op.attr(OP_ROLE_VAR_ATTR_NAME)[1] + if op.attr(OP_ROLE_VAR_ATTR_NAME)[0] == optimize_target_param_name: + merged_var = _append_pserver_grad_merge_ops( + per_opt_block, grad_varname_for_block, ps_endpoint, + grad_to_block_id) + if merged_var: + break # append optimize op once then append other ops. + + if merged_var: + for _, op in enumerate(optimize_ops): + # optimizer is connected to itself + if op.attr(OP_ROLE_VAR_ATTR_NAME)[0] == optimize_target_param_name and \ + op not in global_ops: + __append_optimize_op__(op, per_opt_block, grad_to_block_id, + merged_var, lr_ops) + + # dedup grad to ids list + grad_to_block_id = list(set(grad_to_block_id)) + # append global ops + if global_ops: + opt_state_block = program._create_block(program.num_blocks - 1) + optimize_blocks.append(opt_state_block) + for glb_op in global_ops: + __append_optimize_op__(glb_op, opt_state_block, grad_to_block_id, + None, lr_ops) + + if len(optimize_blocks) == 0: + pre_block_idx = program.num_blocks - 1 + empty_block = program._create_block(pre_block_idx) + optimize_blocks.append(empty_block) + + op = get_op_by_type(program.global_block(), "listen_and_serv") + op._set_attr("optimize_blocks", optimize_blocks) + op._set_attr("grad_to_block_id", grad_to_block_id) + op._set_attr("sparse_grad_to_param", sparse_grad_to_param) + op._set_attr("lr_decay_block_id", lr_decay_block_id) + return program + + +def large_scale_sparse_pass(program, main_program, config, is_startup=False): + opt_value_map = {} + opt_value_map["sgd"] = ["Param"] + opt_value_map["adam"] = ["Param", "Moment1", "Moment2"] + opt_value_map["adagrad"] = ["Param", "Moment"] + opt_value_map["adamax"] = ["Param", "Moment", "InfNorm"] + opt_value_map["momentum"] = ["Param", "Velocity"] + opt_value_map["lars_momentum"] = ["Param", "Velocity"] + opt_value_map["rmsprop"] = ["Param", "Moment", "MeanSquare"] + opt_value_map["decayed_adagrad"] = ["Param", "Moment"] + opt_value_map["ftrl"] = ["Param", "SquaredAccumulator", "LinearAccumulator"] + + geo_value_map = {} + geo_value_map["sum"] = "Param" + + opt_init_map = {} + opt_init_map["gaussian_random"] = ["seed", "mean", "std"] + opt_init_map["fill_constant"] = ["value"] + opt_init_map["uniform_random"] = ["seed", "min", "max"] + opt_init_map["truncated_gaussian_random"] = ["seed", "mean", "std"] + + def get_entry_attr(param_name): + origin_name = _orig_varname(param_name) + o_main_program = config.get_origin_main_program() + for op in o_main_program.global_block().ops: + if is_distributed_sparse_op(op) and get_sparse_tablename( + op) == origin_name: + entry = op.attr("entry") + return entry + + def get_initializer_attrs(acture_value_names): + l_sep = "," + l_in = "&" + init_attrs = [] + o_startup_program = config.get_origin_startup_program() + + for value_name in acture_value_names: + origin_var_name = _orig_varname(value_name) + for op in o_startup_program.global_block().ops: + if op.type in opt_init_map.keys( + ) and origin_var_name == op.output("Out")[0]: + init_attr = [op.type] + for attr in opt_init_map[op.type]: + init_attr.append(str(op.attr(attr))) + init_attrs.append(l_in.join(init_attr)) + break + + return l_sep.join(init_attrs) + + def get_optimizer_values(block): + value_names = [] + acture_names = [] + value_dims = [] + grad = None + opt_idx = -1 + fuse = False + + for op in block.ops: + opt_idx += 1 + + if op.type not in opt_value_map.keys(): + continue + + if op.type in ["sgd", "adam"]: + fuse = True + + grad = main_program.global_block().vars[op.input("Grad")[0]] + + for value in opt_value_map[op.type]: + var = main_program.global_block().vars[op.input(value)[0]] + if len(var.shape) != 2: + raise ValueError("sparse param's dimension must be 2") + + value_names.append(value) + value_dims.append(var.shape[1]) + acture_names.append(var.name) + + if value_names: + break + return grad, opt_idx, value_names, value_dims, acture_names, fuse + + def add_fuse_large_scale_op(block, global_block, table_name, value_names, + acture_names, grad, is_entry, opt_idx): + + op = block.ops[opt_idx] + + if op.type == "sgd": + grad = main_program.global_block().vars[op.input("Grad")[0]] + lr = main_program.global_block().vars[op.input("LearningRate")[0]] + + block._insert_op(opt_idx, + type="lookup_sparse_table_fuse_sgd", + inputs={ + "Grad": grad, + "LearningRate": lr + }, + attrs={ + "is_entry": is_entry, + "tablename": table_name, + "value_names": value_names + }) + + elif op.type == "adam": + grad = main_program.global_block().vars[op.input("Grad")[0]] + lr = main_program.global_block().vars[op.input("LearningRate")[0]] + beta1_pow = main_program.global_block().vars[op.input("Beta1Pow") + [0]] + beta2_pow = main_program.global_block().vars[op.input("Beta2Pow") + [0]] + beta1_pow_o = main_program.global_block().vars[op.output( + "Beta1PowOut")[0]] + beta2_pow_o = main_program.global_block().vars[op.output( + "Beta2PowOut")[0]] + + beta1 = op.attr('beta1') + beta2 = op.attr('beta2') + epsilon = op.attr('epsilon') + + block._insert_op(opt_idx, + type="lookup_sparse_table_fuse_adam", + inputs={ + "Grad": grad, + "LearningRate": lr, + "Beta1Pow": beta1_pow, + "Beta2Pow": beta2_pow + }, + outputs={ + "Beta1PowOut": beta1_pow_o, + "Beta2PowOut": beta2_pow_o + }, + attrs={ + "beta1": beta1, + "beta2": beta2, + "epsilon": epsilon, + "is_entry": is_entry, + "tablename": table_name, + "value_names": value_names + }) + else: + raise ValueError("only support sgd/adam optimizer now") + + def add_large_scale_op(block, global_block, table_name, value_names, + acture_names, grad, is_entry, opt_idx): + ids = global_block.create_var(name="kSparseIDs@{}".format(table_name), + persistable=False, + dtype="int64", + shape=[1, 1], + lod_level=0) + + # insert grad split to ids and tensor op + block._insert_op(opt_idx, + type="lookup_sparse_table_grad_split", + inputs={"Grad": grad}, + outputs={ + "Row": ids, + "Value": grad + }, + attrs={ + "tablename": table_name, + "is_entry": is_entry + }) + + # insert read at first + vars = [global_block.vars[acture_name] for acture_name in acture_names] + block._insert_op(opt_idx + 1, + type="lookup_sparse_table_read", + inputs={"Ids": ids}, + outputs={"Out": vars}, + attrs={ + "tablename": table_name, + "value_names": value_names + }) + + # append write at last + inputs = {"Ids": ids, "In": vars} + + block.append_op(type="lookup_sparse_table_write", + inputs=inputs, + outputs={}, + attrs={ + "tablename": table_name, + "value_names": value_names + }) + + op = get_op_by_type(main_program.global_block(), "listen_and_serv") + + param_blockid_map = {} + grad_blockid_map = {} + grad_to_params = op.attr('sparse_grad_to_param') + grad_to_block_ids = op.attr('grad_to_block_id') + + origin_program = config.get_origin_main_program() + sparse_varnames = get_sparse_tablenames(origin_program, False) + + for grad_to_block_id in grad_to_block_ids: + grad, blockid = grad_to_block_id.split(":") + grad_blockid_map[grad] = int(blockid) + + for grad_to_param in grad_to_params: + grad, param = grad_to_param.split(":") + + if _orig_varname(param) in sparse_varnames: + continue + + param_blockid_map[param] = grad_blockid_map[grad] + + if not is_startup: + for param, blockid in param_blockid_map.items(): + opt_block = program.block(blockid) + + grad, opt_idx, value_names, value_dims, acture_names, fuse = \ + get_optimizer_values(opt_block) + + entry_attr = get_entry_attr(param) + is_entry = False if entry_attr == "none" else True + + if fuse: + add_fuse_large_scale_op(opt_block, program.global_block(), + param, value_names, acture_names, grad, + is_entry, opt_idx) + else: + add_large_scale_op(opt_block, program.global_block(), param, + value_names, acture_names, grad, is_entry, + opt_idx) + else: + large_scale_kv_metas = [] + for param, blockid in param_blockid_map.items(): + opt_block = main_program.block(blockid) + + grad, opt_idx, value_names, value_dims, acture_names, fuse = \ + get_optimizer_values(opt_block) + + entry_attr = get_entry_attr(param) + + if fuse: + # remove origin optimzier op + opt_block._remove_op(opt_idx) + + # training/infer + mode = "0" + names_str = ",".join(value_names) + dims_str = ",".join([str(dim) for dim in value_dims]) + ids_name = "kSparseIDs@{}".format(param) + cached_str = ",".join(acture_names + [ids_name]) + init_attr_str = get_initializer_attrs(acture_names) + + meta_str = ":".join([ + param, names_str, dims_str, mode, grad.name, cached_str, + init_attr_str, entry_attr + ]) + print("large_scale_metas: {}".format(meta_str)) + large_scale_kv_metas.append(meta_str) + + program.global_block().append_op( + type="lookup_sparse_table_init", + inputs=None, + outputs=None, + attrs={"large_scale_metas": large_scale_kv_metas}) + + # todo: need delete unused var. + return program + + +def get_distributed_from_listen_and_serv(program, origin_program): + op = get_op_by_type(program.global_block(), "listen_and_serv") + sparse_varnames = get_sparse_tablenames(origin_program, True) + sparse_params = [] + grad_to_params = op.attr('sparse_grad_to_param') + for grad_to_param in grad_to_params: + _, param = grad_to_param.split(":") + if _orig_varname(param) in sparse_varnames: + sparse_params.append(param) + return sparse_params + + +def delete_unused_in_main_pass(program, config): + origin_program = config.get_origin_main_program() + sparse_params = get_distributed_from_listen_and_serv( + program, origin_program) + + for var in sparse_params: + if program.global_block().has_var(var): + program.global_block()._remove_var(var) + return program + + +def delete_unused_in_startup_pass(program, main_program, config): + origin_program = config.get_origin_main_program() + sparse_params = get_distributed_from_listen_and_serv( + main_program, origin_program) + remove_ops = [] + + for op in program.global_block().ops: + if op.type in ["recv", "fetch_barrier", "concat"]: + continue + + for key in op.output_names: + if op.output(key)[0] in sparse_params: + remove_ops.append(op) + + all_ops = program.global_block().ops + op_idxs = [all_ops.index(op) for op in remove_ops] + + for idx in op_idxs[::-1]: + program.global_block()._remove_op(idx) + + for var in sparse_params: + if program.global_block().has_var(var): + program.global_block()._remove_var(var) + + return program + + +def build_pserver_startup_program_pass(program, p_main_program, config): + ps_endpoint = config.get_ps_endpoint() + o_startup_program = config.get_origin_startup_program() + program.random_seed = o_startup_program.random_seed + params = config.param_grad_ep_mapping[ps_endpoint]["params"] + merged_ordervars = [] + + for var in params: + name = var.name + orig_varname = _orig_varname(name) + + for pairs in config.merged_variables_pairs: + merged_p = pairs[0] + if merged_p.merged_var.name == orig_varname: + if merged_p.merged_var.name != merged_p.ordered_vars[0].name: + merged_ordervars.append(merged_p.ordered_vars[0]) + break + + def _get_splited_name_and_shape(varname): + for splited_param in params: + pname = splited_param.name + if _same_or_split_var(pname, varname) and varname != pname: + return pname, splited_param.shape + + for idx, ordered in enumerate(merged_ordervars): + if _same_or_split_var(varname, ordered.name): + return pname, splited_param.shape + + return "", [] + + # 1. create vars in pserver program to startup program + pserver_vars = p_main_program.global_block().vars + + created_var_map = collections.OrderedDict() + for _, var in six.iteritems(pserver_vars): + tmpvar = program.global_block()._clone_variable(var) + created_var_map[var.name] = tmpvar + + # 2. rename op outputs + for op in o_startup_program.global_block().ops: + new_outputs = collections.OrderedDict() + # do not append startup op if var is not on this pserver + op_on_pserver = False + # TODO(gongwb) : remove this line. + if op.type not in ["recv", "fetch_barrier", "concat"]: + for key in op.output_names: + newname, _ = _get_splited_name_and_shape(op.output(key)[0]) + if newname: + op_on_pserver = True + new_outputs[key] = created_var_map[newname] + elif op.output(key)[0] in pserver_vars: + op_on_pserver = True + new_outputs[key] = pserver_vars[op.output(key)[0]] + + if op_on_pserver: + # most startup program ops have no inputs + new_inputs = _get_input_map_from_op(pserver_vars, op) + + if op.type in [ + "gaussian_random", "fill_constant", "uniform_random", + "truncated_gaussian_random" + ]: + op._set_attr("shape", list(new_outputs["Out"].shape)) + + program.global_block().append_op(type=op.type, + inputs=new_inputs, + outputs=new_outputs, + attrs=op.all_attrs()) + + return program + + +def add_geo_optimizer_pass(program, config): + endpoint = config.get_ps_endpoint() + params = [p for p in config.param_grad_ep_mapping[endpoint]["params"]] + + sparse_tablenames = get_sparse_tablenames(config.get_origin_main_program(), + False) + + for param in params: + _clone_var(program.global_block(), param) + + optimize_block = [] + sparse_grad_to_param = [] + param_to_block_id = [] + pre_block_idx = program.num_blocks - 1 + + for param in params: + per_opt_block = program._create_block(pre_block_idx) + optimize_block.append(per_opt_block) + var_name = param.name + pserver_block = per_opt_block.program.global_block() + param = pserver_block.vars[var_name] + + delta_var_name = "%s.delta" % (param.name) + origin_varname = _orig_varname(param.name) + + if origin_varname in sparse_tablenames: + sparse_grad_to_param.append(":".join([delta_var_name, param.name])) + + delta_var = pserver_block.create_var(name=delta_var_name, + persistable=False, + type=param.type, + dtype=param.dtype, + shape=param.shape) + + per_opt_block.append_op(type="sum", + inputs={"X": [param, delta_var]}, + outputs={"Out": param}) + + param_to_block_id.append(delta_var_name + ":" + str(per_opt_block.idx)) + + op = get_op_by_type(program.global_block(), "listen_and_serv") + op._set_attr("optimize_blocks", optimize_block) + op._set_attr("grad_to_block_id", param_to_block_id) + op._set_attr("sparse_grad_to_param", sparse_grad_to_param) + + return program diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/public.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/public.py new file mode 100644 index 0000000000000000000000000000000000000000..5567fe309ec5e1e8afbed0d4edabae9b2bdd4430 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/public.py @@ -0,0 +1,1291 @@ +# 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. + +from __future__ import print_function +from functools import reduce + +import collections +import math +import os +import warnings +import logging +import six +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.core import CommContext +import paddle.fluid.framework as framework +from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode +from paddle.fluid.incubate.fleet.parameter_server.ir import vars_metatools +from paddle.fluid.incubate.fleet.parameter_server.ir.ps_dispatcher import RoundRobin, PSDispatcher +from paddle.fluid.transpiler.details.program_utils import delete_ops + +OP_NAME_SCOPE = "op_namescope" +CLIP_OP_NAME_SCOPE = "gradient_clip" +STEP_COUNTER = "@PS_STEP_COUNTER@" +LEARNING_RATE_DECAY_COUNTER = "@LR_DECAY_COUNTER@" + +OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName() +RPC_OP_ROLE_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleAttrName() +RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC +op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() +LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched +OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize + +SPARSE_OP_LIST = ["lookup_table", "lookup_table_v2"] +SPARSE_OP_TYPE_DICT = {"lookup_table": "W", "lookup_table_v2": "W"} + + +def _get_lr_ops(program): + lr_ops = [] + for index, op in enumerate(program.global_block().ops): + role_id = int(op.attr(RPC_OP_ROLE_ATTR_NAME)) + if role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) or \ + role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) | \ + int(OPT_OP_ROLE_ATTR_VALUE): + lr_ops.append(op) + return lr_ops + + +def _has_global_step(lr_ops): + if len(lr_ops) > 0: + for idx, op in enumerate(lr_ops): + if op.type != 'increment': + continue + counter = op.input("X")[0] + if counter == LEARNING_RATE_DECAY_COUNTER: + return True + return False + + +def is_sparse_op(op): + if op.type in SPARSE_OP_LIST and op.attr('is_sparse') is True and op.attr( + 'is_distributed') is False: + return True + + if op.type == "distributed_lookup_table" and op.attr( + 'is_distributed') is False: + return True + + return False + + +def is_distributed_sparse_op(op): + if op.type in SPARSE_OP_LIST and op.attr('is_distributed') is True: + return True + + if op.type == "distributed_lookup_table" and op.attr( + 'is_distributed') is True: + return True + + return False + + +def get_sparse_tablename(op): + return op.input("W")[0] + + +def get_sparse_tablenames(program, is_distributed): + tablenames = set() + if is_distributed: + for op in program.global_block().ops: + if is_distributed_sparse_op(op): + tablenames.add(get_sparse_tablename(op)) + else: + for op in program.global_block().ops: + if is_sparse_op(op): + tablenames.add(get_sparse_tablename(op)) + return list(tablenames) + + +class MergedVariable: + + def __init__(self, merged, ordered, offsets): + self.merged_var = merged + self.ordered_vars = ordered + self.offsets = offsets + + +def Singleton(cls): + _instance = {} + + def _singleton(*args, **kargs): + if cls not in _instance: + _instance[cls] = cls(*args, **kargs) + return _instance[cls] + + return _singleton + + +@Singleton +class CompileTimeStrategy(object): + + def __init__(self, main_program, startup_program, strategy, role_maker): + self.min_block_size = 81920 + + self.origin_main_program = main_program + self.origin_startup_program = startup_program + self.origin_ps_main_program = main_program + self.origin_ps_startup_program = startup_program + + self.strategy = strategy + self.role_maker = role_maker + self.use_ps_gpu = False + try: + self.is_heter_ps_mode = role_maker._is_heter_parameter_server_mode + except: + warnings.warn( + "Using paddle.distributed.fleet instead of paddle.fluid.incubate.fleet" + ) + self.is_heter_ps_mode = False + + self.origin_sparse_pairs = [] + self.origin_dense_pairs = [] + + self.merged_variables_pairs = [] + self.merged_dense_pairs = [] + self.merged_sparse_pairs = [] + + self.merged_variable_map = {} + self.param_name_to_grad_name = {} + self.grad_name_to_param_name = {} + + self.param_grad_ep_mapping = collections.OrderedDict() + self.grad_param_mapping = collections.OrderedDict() + + self._build_var_distributed() + + self.tensor_table_dict = {} + + # for heter-ps save variables + self.origin_merged_variables_pairs = list(self.merged_variables_pairs) + self.origin_merged_dense_pairs = list(self.merged_dense_pairs) + self.origin_merged_sparse_pairs = list(self.merged_sparse_pairs) + + def get_distributed_mode(self): + trainer = self.strategy.get_trainer_runtime_config() + return trainer.mode + + def is_sync_mode(self): + trainer = self.strategy.get_trainer_runtime_config() + return trainer.mode == DistributedMode.SYNC + + def is_geo_mode(self): + trainer = self.strategy.get_trainer_runtime_config() + return trainer.mode == DistributedMode.GEO + + def is_async_mode(self): + trainer = self.strategy.get_trainer_runtime_config() + return trainer.mode == DistributedMode.ASYNC + + def get_role_id(self): + try: + return self.role_maker._role_id() + except Exception: + return self.role_maker.role_id() + + def get_trainers(self): + try: + return self.role_maker._worker_num() + except Exception: + return self.role_maker.worker_num() + + def get_ps_endpoint(self): + try: + return self.role_maker._get_pserver_endpoints()[self.get_role_id()] + except Exception: + return self.role_maker.get_pserver_endpoints()[self.get_role_id()] + + def get_ps_endpoints(self): + try: + return self.role_maker._get_pserver_endpoints() + except Exception: + return self.role_maker.get_pserver_endpoints() + + def get_heter_worker_endpoints(self): + try: + return self.role_maker._get_heter_worker_endpoints() + except Exception: + return self.role_maker.get_heter_worker_endpoints() + + def get_next_stage_trainers(self): + try: + return self.role_maker._get_next_trainers() + except Exception: + return self.role_maker.get_next_trainers() + + def get_heter_worker_endpoint(self): + try: + return self.role_maker._get_heter_worker_endpoint() + except Exception: + return self.role_maker.get_heter_worker_endpoint() + + def get_trainer_endpoints(self): + try: + return self.role_maker._get_trainer_endpoints() + except Exception: + return self.role_maker.get_trainer_endpoints() + + def get_trainer_endpoint(self): + try: + return self.role_maker._get_trainer_endpoint() + except Exception: + return self.role_maker.get_trainer_endpoint() + + def get_previous_stage_trainers(self): + try: + return self.role_maker._get_previous_trainers() + except Exception: + return self.role_maker.get_previous_trainers() + + def get_origin_programs(self): + return self.origin_main_program, self.origin_startup_program + + def get_origin_main_program(self): + return self.origin_main_program + + def get_origin_startup_program(self): + return self.origin_startup_program + + def set_origin_ps_main_program(self, program): + self.origin_ps_main_program = program + + def set_origin_ps_startup_program(self, program): + self.origin_ps_startup_program = program + + def get_origin_ps_main_program(self): + return self.origin_ps_main_program + + def get_origin_ps_startup_program(self): + return self.origin_ps_startup_program + + def add_tensor_table(self, + feed_var_name, + fetch_var_name="", + startup_program=None, + main_program=None, + tensor_table_class=""): + self.tensor_table_dict[feed_var_name] = {} + self.tensor_table_dict[feed_var_name]["feed_var_name"] = feed_var_name + self.tensor_table_dict[feed_var_name]["fetch_var_name"] = fetch_var_name + self.tensor_table_dict[feed_var_name][ + "startup_program"] = startup_program + self.tensor_table_dict[feed_var_name]["main_program"] = main_program + self.tensor_table_dict[feed_var_name][ + "tensor_table_class"] = tensor_table_class + + def get_tensor_table_dict(self): + return self.tensor_table_dict + + def get_sparse_varname_on_ps(self, is_distributed, endpoint=None): + if not endpoint: + endpoint = self.get_ps_endpoint() + varnames = get_sparse_tablenames(self.get_origin_main_program(), + is_distributed) + + ps_sparse_varnames = [] + for varname in varnames: + tables = self.get_var_distributed(varname, True) + for i in range(len(tables)): + table, ep, _ = tables[i] + if ep == endpoint: + ps_sparse_varnames.append(table) + return ps_sparse_varnames + + def get_optimize_varname_on_ps(self, param_name): + origin_param_name, _, _ = _get_varname_parts(param_name) + optimize_var_names = [] + for op in self.get_origin_main_program().global_block().ops: + # check all optimizer op + if int(op.all_attrs()["op_role"]) == 2: + # check param name + if op.input("Param")[0] != origin_param_name: + continue + # check all input + for key in op.input_names: + if key in [ + "Param", "Grad", "LearningRate", "Beta1Tensor", + "Beta2Tensor" + ]: + continue + # check varibale shape related param, e.g: Moment1 + optimize_var_names += self._get_optimizer_param_related_var_name( + op, op.type, key) + return optimize_var_names + + def _get_optimizer_param_related_var_name(self, op, op_type, varkey): + """ + Returns the names for optimizer inputs that need to be load + """ + related_var_names = [] + if op_type == "adam": + if varkey in ["Moment1", "Moment2"]: + related_var_names.append(op.input(varkey)[0]) + elif op_type == "adagrad": + if varkey == "Moment": + related_var_names.append(op.input(varkey)[0]) + elif op_type in ["momentum", "lars_momentum"]: + if varkey == "Velocity": + related_var_names.append(op.input(varkey)[0]) + elif op_type == "rmsprop": + if varkey in ["Moment", "MeanSquare"]: + related_var_names.append(op.input(varkey)[0]) + elif op_type == "ftrl": + if varkey in ["SquaredAccumulator", "LinearAccumulator"]: + related_var_names.append(op.input(varkey)[0]) + elif op_type == "sgd": + pass + else: + raise ValueError( + "Not supported optimizer for distributed training: %s" % + op_type) + return related_var_names + + def build_ctx(self, + vars, + mapping, + is_grad, + is_sparse, + is_send, + is_distributed=False): + + def get_grad_var_ep(slices): + names = [] + eps = [] + sections = [] + + for slice in slices: + if self.is_geo_mode(): + if is_send: + names.append("{}.delta".format(slice.name)) + else: + names.append(slice.name) + elif is_grad and self.is_sync_mode( + ) and self.get_trainers() > 1: + names.append("{}.trainer_{}".format(slice.name, + self.get_role_id())) + else: + names.append(slice.name) + + sections.append(slice.shape[0]) + + for ep, pairs in self.param_grad_ep_mapping.items(): + params, grads = pairs["params"], pairs["grads"] + + for var in params + grads: + if slice.name == var.name: + eps.append(ep) + break + return names, eps, sections + + if isinstance(vars, MergedVariable): + name = vars.merged_var.name + slices = mapping[name] + names, eps, sections = get_grad_var_ep(slices) + origin_varnames = [var.name for var in vars.ordered_vars] + else: + name = vars.name + slices = mapping[name] + names, eps, sections = get_grad_var_ep(slices) + origin_varnames = [vars.name] + + trainer_id = self.get_role_id() + aggregate = True + ctx = CommContext(name, names, eps, sections, origin_varnames, + trainer_id, aggregate, is_sparse, is_distributed, []) + return ctx + + def get_trainer_send_context(self): + send_ctx = {} + distibuted_varnames = get_sparse_tablenames(self.origin_main_program, + True) + idx = 0 + + if not self.is_geo_mode(): + for merged in self.merged_dense_pairs: + grad = merged[1] + ctx = self.build_ctx(grad, self.grad_var_mapping, True, False, + True) + send_ctx[ctx.var_name()] = ctx + + for merged in self.merged_sparse_pairs: + param = merged[0] + grad = merged[1] + + param_name = param.merged_var.name + + is_distributed = True if param_name in distibuted_varnames else False + + ctx = self.build_ctx(grad, self.grad_var_mapping, True, True, + True, is_distributed) + send_ctx[ctx.var_name()] = ctx + idx += 1 + + if self.is_async_mode(): + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + else: + for pairs in self.origin_sparse_pairs: + param, grad = pairs + param_name = param.name + is_distributed = True if param_name in distibuted_varnames else False + + param_ctx = self.build_ctx(param, self.param_var_mapping, False, + True, True, is_distributed) + grad_ctx = self.build_ctx(grad, self.grad_var_mapping, True, + True, True, is_distributed) + + ctx = CommContext(param_ctx.var_name(), + param_ctx.split_varnames(), + param_ctx.split_endpoints(), + param_ctx.sections(), + grad_ctx.origin_varnames(), + param_ctx.trainer_id(), param_ctx.aggregate(), + param_ctx.is_sparse(), + param_ctx.is_distributed(), []) + + send_ctx[ctx.var_name()] = ctx + idx += 1 + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + return send_ctx + + def get_communicator_send_context(self): + send_ctx = {} + distibuted_varnames = get_sparse_tablenames(self.origin_main_program, + True) + idx = 0 + + if self.is_geo_mode(): + for pairs in self.merged_dense_pairs: + param = pairs[0] + ctx = self.build_ctx(param, self.param_var_mapping, False, + False, True) + send_ctx[ctx.var_name()] = ctx + + for pairs in self.merged_sparse_pairs: + param = pairs[0] + param_name = param.merged_var.name + is_distributed = True if param_name in distibuted_varnames else False + + ctx = self.build_ctx(param, self.param_var_mapping, False, True, + True, is_distributed) + send_ctx[ctx.var_name()] = ctx + idx += 1 + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + else: + for merged in self.merged_dense_pairs: + grad = merged[1] + ctx = self.build_ctx(grad, self.grad_var_mapping, True, False, + True) + send_ctx[ctx.var_name()] = ctx + + for merged in self.merged_sparse_pairs: + param, grad = merged + param_name = param.merged_var.name + + is_distributed = True if param_name in distibuted_varnames else False + + ctx = self.build_ctx(grad, self.grad_var_mapping, True, True, + True, is_distributed) + send_ctx[ctx.var_name()] = ctx + idx += 1 + + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + return send_ctx + + def get_communicator_recv_context(self, + recv_type=1, + use_origin_program=False): + # recv_type + # 1 : DENSE 2. SPARSE 3. DISTRIBUTED 4. ALL + distibuted_varnames = get_sparse_tablenames(self.origin_main_program, + True) + sparse_varnames = [] + for pairs in self.origin_sparse_pairs: + param, grad = pairs + sparse_varnames.append(param.name) + + dense_recv_ctx = {} + sparse_recv_ctx = {} + distributed_recv_ctx = {} + + variables_pairs = self.merged_variables_pairs if not use_origin_program else self.origin_merged_variables_pairs + for merged in variables_pairs: + params = merged[0] + if params.merged_var.name in sparse_varnames: + continue + + ctx = self.build_ctx(params, self.param_var_mapping, False, False, + False, False) + dense_recv_ctx[ctx.var_name()] = ctx + + for pairs in self.origin_sparse_pairs: + param, grad = pairs + + if param.name in distibuted_varnames: + ctx = self.build_ctx(param, self.param_var_mapping, False, True, + False, True) + distributed_recv_ctx[ctx.var_name()] = ctx + else: + ctx = self.build_ctx(param, self.param_var_mapping, False, True, + False, False) + sparse_recv_ctx[ctx.var_name()] = ctx + + if recv_type == 1: + return dense_recv_ctx + if recv_type == 2: + return sparse_recv_ctx + if recv_type == 3: + return distributed_recv_ctx + if recv_type == 4: + dense_recv_ctx.update(sparse_recv_ctx) + dense_recv_ctx.update(distributed_recv_ctx) + return dense_recv_ctx + assert ValueError( + "recv_type can only be 1/2/3/4, 1 : DENSE 2. SPARSE 3. DISTRIBUTED 4. ALL" + ) + + def get_the_one_trainer_send_context(self, split_dense_table): + if self.is_geo_mode(): + send_ctx = {} + trainer_id = self.get_role_id() + idx = 0 + + distibuted_varnames = get_sparse_tablenames( + self.origin_main_program, True) + for merged in self.merged_sparse_pairs: + param, grad = merged + grad_name = grad.merged_var.name + param_name = param.merged_var.name + is_distributed = True if param_name in distibuted_varnames else False + + var = self.origin_main_program.global_block().vars[ + grad.merged_var.name] + var_numel = reduce(lambda x, y: x * y, var.shape[1:]) + + sparse_ctx = CommContext(grad_name, [grad_name], + ["127.0.0.1:6071"], [var_numel], + [grad_name], trainer_id, True, True, + is_distributed, idx, False, False, -1, + []) + idx += 1 + send_ctx[sparse_ctx.var_name()] = sparse_ctx + + if len(send_ctx) == 0: + raise ValueError( + "GeoSGD require sparse parameters in your net.") + + if len(self.tensor_table_dict) > 0 and self.role_maker._is_worker(): + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + + return send_ctx + else: + return self.get_the_one_send_context(split_dense_table) + + def get_dense_send_context(self, + send_ctx, + idx, + merged_dense_pairs, + trainer_id, + split_dense_table=False): + if len(merged_dense_pairs) < 1: + return idx + if not split_dense_table: + origin_varnames = [] + var_numel = 0 + for merged in merged_dense_pairs: + grad = merged[1] + origin_varnames.append(grad.merged_var.name) + var = self.origin_main_program.global_block().vars[ + grad.merged_var.name] + var_numel += reduce(lambda x, y: x * y, var.shape) + grad_name = "Dense@Grad" + trainer_id = self.get_role_id() + aggregate = True + dense_ctx = CommContext(grad_name, [grad_name], ["127.0.0.1:6071"], + [var_numel], origin_varnames, trainer_id, + aggregate, False, False, idx, False, False, + -1, []) + send_ctx[grad_name] = dense_ctx + idx += 1 + else: + for merged in merged_dense_pairs: + grad = merged[1] + origin_varname = grad.merged_var.name + var = self.origin_main_program.global_block( + ).vars[origin_varname] + var_numel = reduce(lambda x, y: x * y, var.shape) + grad_name = origin_varname + aggregate = True + dense_ctx = CommContext(grad_name, [grad_name], + ["127.0.0.1:6071"], [var_numel], + [origin_varname], trainer_id, aggregate, + False, False, idx, False, False, -1, []) + send_ctx[grad_name] = dense_ctx + idx += 1 + return idx + + def get_the_one_send_context(self, + split_dense_table=False, + use_origin_program=False, + ep_list=None): + if ep_list is None: + ep_list = ["127.0.0.1:6071"] + send_ctx = {} + trainer_id = self.get_role_id() + idx = 0 + + merged_dense_pairs = self.origin_merged_dense_pairs if use_origin_program else self.merged_dense_pairs + merged_sparse_pairs = self.origin_merged_sparse_pairs if use_origin_program else self.merged_sparse_pairs + + idx += self.get_dense_send_context(send_ctx, idx, merged_dense_pairs, + trainer_id, split_dense_table) + + distibuted_varnames = get_sparse_tablenames(self.origin_main_program, + True) + for merged in merged_sparse_pairs: + param, grad = merged + grad_name = grad.merged_var.name + param_name = param.merged_var.name + splited_varname = [] + + for i in range(len(ep_list)): + splited_varname.append("{}.block{}".format(param_name, i)) + + is_distributed = True if param_name in distibuted_varnames else False + + var = self.origin_main_program.global_block().vars[ + grad.merged_var.name] + + shape = list(var.shape) + shape[0] = 0 if is_distributed else shape[0] + + sparse_ctx = CommContext(grad_name, splited_varname, ep_list, shape, + [grad_name], trainer_id, True, True, + is_distributed, idx, False, False, -1, []) + + idx += 1 + send_ctx[sparse_ctx.var_name()] = sparse_ctx + + if len(self.tensor_table_dict) > 0 and self.role_maker._is_worker(): + name, ctx = self._step_ctx(idx) + send_ctx[name] = ctx + + return send_ctx + + def get_the_one_recv_context(self, + is_dense=True, + split_dense_table=False, + use_origin_program=False): + recv_id_maps = {} + if is_dense: + send_ctx = self.get_the_one_send_context( + split_dense_table=split_dense_table, + use_origin_program=use_origin_program) + for idx, (name, ctx) in enumerate(send_ctx.items()): + if ctx.is_sparse(): + continue + if ctx.is_tensor_table(): + continue + + origin_grad_varnames = ctx.origin_varnames() + + param_names = [] + for grad_varname in origin_grad_varnames: + param_name = self.grad_name_to_param_name[grad_varname] + param_names.append(param_name) + recv_id_maps[ctx.table_id()] = param_names + else: + send_ctx = self.get_the_one_send_context() + for idx, (name, ctx) in enumerate(send_ctx.items()): + if not ctx.is_sparse(): + continue + + origin_grad_varnames = ctx.origin_varnames() + + param_names = [] + for grad_varname in origin_grad_varnames: + param_name = self.grad_name_to_param_name[grad_varname] + param_names.append(param_name) + recv_id_maps[ctx.table_id()] = param_names + return recv_id_maps + + def get_server_runtime_config(self): + return self.strategy.get_server_runtime_config() + + def get_var_distributed(self, varname, is_param): + var_distributed = [] + offset = 0 + if is_param: + params = self.param_var_mapping[varname] + param_varnames = [var.name for var in params] + for ep, pairs in self.param_grad_ep_mapping.items(): + for p in pairs["params"]: + if p.name in param_varnames: + offset += p.shape[0] + var_distributed.append((p.name, ep, p.shape[0])) + else: + grads = self.grad_var_mapping[varname] + grad_varnames = [var.name for var in grads] + for ep, pairs in self.param_grad_ep_mapping.items(): + for g in pairs["grads"]: + if g.name in grad_varnames: + var_distributed.append((g.name, ep, g.shape[0])) + return var_distributed + + def _step_ctx(self, idx): + name = STEP_COUNTER + trainer_id = self.get_role_id() + endpoints = self.get_ps_endpoints() + sections = [1] * len(endpoints) + names = [name] * len(endpoints) + ctx = CommContext(name, names, endpoints, sections, [name], trainer_id, + True, False, False, idx, True, False, -1, []) + return name, ctx + + def _create_vars_from_blocklist(self, block_list): + """ + Create vars for each split. + NOTE: only grads need to be named for different trainers, use + add_trainer_suffix to rename the grad vars. + Args: + block_list (list[(varname, block_id, block_size)]): List of gradient blocks. + add_trainer_suffix (Bool): Add trainer suffix to new variable's name if set True. + Returns: + var_mapping (collections.OrderedDict(varname->[new_varname_variable])):A dict mapping + from original var name to each var split. + """ + + # varname->[(block_id, current_block_size)] + block_map = collections.OrderedDict() + var_mapping = collections.OrderedDict() + + for block_str in block_list: + varname, offset, size = block_str.split(":") + if varname not in block_map: + block_map[varname] = [] + block_map[varname].append((int(offset), int(size))) + + for varname, split in six.iteritems(block_map): + orig_var = self.merged_variable_map[varname] + + if len(split) == 1: + var_mapping[varname] = [orig_var] + self.var_distributed.add_distributed_var(origin_var=orig_var, + slice_var=orig_var, + block_id=0, + offset=0, + is_slice=False, + vtype="Param") + else: + var_mapping[varname] = [] + orig_shape = orig_var.shape + orig_dim1_flatten = 1 + + if len(orig_shape) >= 2: + orig_dim1_flatten = reduce(lambda x, y: x * y, + orig_shape[1:]) + + for i, block in enumerate(split): + size = block[1] + rows = size // orig_dim1_flatten + splited_shape = [rows] + if len(orig_shape) >= 2: + splited_shape.extend(orig_shape[1:]) + + new_var_name = "%s.block%d" % (varname, i) + slice_var = vars_metatools.VarStruct( + name=new_var_name, + shape=splited_shape, + dtype=orig_var.dtype, + type=orig_var.type, + lod_level=orig_var.lod_level, + persistable=False) + var_mapping[varname].append(slice_var) + + self.var_distributed.add_distributed_var( + origin_var=orig_var, + slice_var=slice_var, + block_id=i, + offset=-1, + is_slice=False, + vtype="Param") + + return var_mapping + + def _dispatcher(self): + ps_dispatcher = RoundRobin(self.get_ps_endpoints()) + ps_dispatcher.reset() + grad_var_mapping_items = list(six.iteritems(self.grad_var_mapping)) + + sparse_gradnames = [grad.name for _, grad in self.origin_sparse_pairs] + + for grad_varname, splited_vars in grad_var_mapping_items: + if grad_varname in sparse_gradnames: + continue + + send_vars = [] + for _, var in enumerate(splited_vars): + send_vars.append(var) + + recv_vars = [] + for _, var in enumerate(send_vars): + recv_vars.append(self.grad_param_mapping[var]) + + eps = ps_dispatcher.dispatch(recv_vars) + + for i, ep in enumerate(eps): + self.param_grad_ep_mapping[ep]["params"].append(recv_vars[i]) + self.param_grad_ep_mapping[ep]["grads"].append(send_vars[i]) + + for grad_varname, splited_vars in grad_var_mapping_items: + if grad_varname not in sparse_gradnames: + continue + + ps_dispatcher.reset() + + send_vars = [] + for _, var in enumerate(splited_vars): + send_vars.append(var) + + recv_vars = [] + for _, var in enumerate(send_vars): + recv_vars.append(self.grad_param_mapping[var]) + + eps = ps_dispatcher.dispatch(recv_vars) + + for i, ep in enumerate(eps): + self.param_grad_ep_mapping[ep]["params"].append(recv_vars[i]) + self.param_grad_ep_mapping[ep]["grads"].append(send_vars[i]) + + def _slice_variable(self, + var_list, + slice_count, + min_block_size, + uniform=False): + """ + We may need to split dense tensor to one or more blocks and put + them equally onto parameter server. One block is a sub-tensor + aligned by dim[0] of the tensor. + + We need to have a minimal block size so that the calculations in + the parameter server side can gain better performance. By default + minimum block size 8K elements (maybe 16bit or 32bit or 64bit). + + Args: + var_list (list): List of variables. + slice_count (int): Numel of count that variables will be sliced, which + could be the pserver services' count. + min_block_size (int): Minimum split block size. + Returns: + blocks (list[(varname, block_id, current_block_size)]): A list + of VarBlocks. Each VarBlock specifies a shard of the var. + """ + blocks = [] + for var in var_list: + if not uniform: + var_numel = reduce(lambda x, y: x * y, var.shape) + + split_count = 1 + + if min_block_size == -1: + split_count = 1 + else: + split_count = slice_count + max_pserver_count = int( + math.floor(var_numel / float(min_block_size))) + if max_pserver_count == 0: + max_pserver_count = 1 + if max_pserver_count < slice_count: + split_count = max_pserver_count + block_size = int(math.ceil(var_numel / float(split_count))) + + if len(var.shape) >= 2: + # align by dim1(width) + dim1 = reduce(lambda x, y: x * y, var.shape[1:]) + remains = block_size % dim1 + if remains != 0: + block_size += dim1 - remains + # update split_count after aligning + split_count = int(math.ceil(var_numel / float(block_size))) + for block_id in range(split_count): + curr_block_size = min(block_size, + var_numel - ((block_id) * block_size)) + block = vars_metatools.VarBlock(var.name, block_id, + curr_block_size) + blocks.append(str(block)) + else: + block_size = var.shape[0] / slice_count + remainder = var.shape[0] % slice_count + + if block_size == 0: + dim0s = [block_size] * remainder + else: + dim0s = [block_size] * slice_count + for i in range(remainder): + dim0s[i] = dim0s[i] + 1 + + dim1 = reduce(lambda x, y: x * y, var.shape[1:]) + + for block_id in range(len(dim0s)): + numel = dim0s[block_id] * dim1 + block = vars_metatools.VarBlock(var.name, block_id, numel) + blocks.append(str(block)) + return blocks + + def _get_param_grad_blocks(self, pairs, min_block_size, uniform=False): + param_list = [] + grad_list = [] + param_grad_set = set() + for p, g in pairs: + # todo(tangwei12) skip parameter marked not trainable + # if type(p) == Parameter and p.trainable == False: + # continue + p = p.merged_var + g = g.merged_var + + if p.name not in param_grad_set: + param_list.append(p) + param_grad_set.add(p.name) + if g.name not in param_grad_set: + grad_list.append(g) + param_grad_set.add(g.name) + + # when we slice var up into blocks, we will slice the var according to + # pserver services' count. A pserver may have two or more listening ports. + grad_blocks = self._slice_variable(grad_list, + len(self.get_ps_endpoints()), + min_block_size, uniform) + + param_blocks = self._slice_variable(param_list, + len(self.get_ps_endpoints()), + min_block_size, uniform) + return param_blocks, grad_blocks + + def _var_slice_and_distribute(self): + # update these mappings for further transpile: + # 1. param_var_mapping : param var name->[split params vars] + # 2. grad_var_mapping : grad var name->[split grads vars] + # 3. grad_param_mapping : grad.blockx->param.blockx + # 4. param_grad_ep_mapping : ep->{"params" : [], "grads" : [] } + + dps, dgs = self._get_param_grad_blocks(self.merged_dense_pairs, + self.min_block_size, False) + sps, sgs = self._get_param_grad_blocks(self.merged_sparse_pairs, + self.min_block_size, True) + + param_blocks = dps + sps + grad_blocks = dgs + sgs + + assert (len(grad_blocks) == len(param_blocks)) + + # origin_param_name->[splited_param_vars] + self.param_var_mapping = self._create_vars_from_blocklist(param_blocks) + self.grad_var_mapping = self._create_vars_from_blocklist(grad_blocks) + + # dict(grad_splited_var->param_splited_var) + self.grad_param_mapping = collections.OrderedDict() + for g, p in zip(grad_blocks, param_blocks): + g_name, g_bid, _ = g.split(":") + p_name, p_bid, _ = p.split(":") + self.grad_param_mapping[self.grad_var_mapping[g_name][int(g_bid)]] = \ + self.param_var_mapping[p_name][int(p_bid)] + + print_maps = {} + for k, v in self.grad_param_mapping.items(): + print_maps[str(k)] = str(v) + + # create mapping of endpoint->split var to create pserver side program + self.param_grad_ep_mapping = collections.OrderedDict() + [ + self.param_grad_ep_mapping.update({ep: { + "params": [], + "grads": [] + }}) for ep in self.get_ps_endpoints() + ] + + def _build_var_distributed(self): + self.var_distributed = vars_metatools.VarsDistributed() + + sparse_pairs, dense_pairs = self.get_param_grads() + origin_for_sparse = [] + origin_for_dense = [] + param_name_grad_name = dict() + grad_name_to_param_name = dict() + + for param, grad in sparse_pairs: + param = vars_metatools.create_var_struct(param) + grad = vars_metatools.create_var_struct(grad) + origin_for_sparse.append((param, grad)) + + for param, grad in dense_pairs: + param = vars_metatools.create_var_struct(param) + grad = vars_metatools.create_var_struct(grad) + origin_for_dense.append((param, grad)) + + for dense_pair in origin_for_dense: + param, grad = dense_pair + + m_param = MergedVariable(param, [param], [0]) + m_grad = MergedVariable(grad, [grad], [0]) + self.merged_variables_pairs.append((m_param, m_grad)) + self.merged_dense_pairs.append((m_param, m_grad)) + + for sparse_pair in origin_for_sparse: + param, grad = sparse_pair + + m_param = MergedVariable(param, [param], [0]) + m_grad = MergedVariable(grad, [grad], [0]) + self.merged_variables_pairs.append((m_param, m_grad)) + self.merged_sparse_pairs.append((m_param, m_grad)) + + for merged in self.merged_variables_pairs: + m_param, m_grad = merged + self.merged_variable_map[ + m_param.merged_var.name] = m_param.merged_var + self.merged_variable_map[m_grad.merged_var.name] = m_grad.merged_var + + param_merges = [] + param_merges.extend(origin_for_sparse) + param_merges.extend(origin_for_dense) + + for param, grad in param_merges: + param_name_grad_name[param.name] = grad.name + grad_name_to_param_name[grad.name] = param.name + + self.origin_sparse_pairs = origin_for_sparse + self.origin_dense_pairs = origin_for_dense + self.param_name_to_grad_name = param_name_grad_name + self.grad_name_to_param_name = grad_name_to_param_name + + sparse_pair_map = collections.OrderedDict() + + for pair in self.origin_sparse_pairs + self.origin_dense_pairs: + param, grad = pair + sparse_pair_map[param.name] = str(param) + sparse_pair_map[grad.name] = str(grad) + + self._var_slice_and_distribute() + self._dispatcher() + + def get_param_grads(self): + origin_program = self.origin_main_program + + def _get_params_grads(sparse_varnames): + block = origin_program.global_block() + + dense_param_grads = [] + sparse_param_grads = [] + + optimize_params = set() + origin_var_dict = origin_program.global_block().vars + role_id = int(core.op_proto_and_checker_maker.OpRole.Backward) + for op in block.ops: + if _is_opt_role_op(op): + # delete clip op from opt_ops when run in Parameter Server mode + if OP_NAME_SCOPE in op.all_attrs() \ + and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE): + op._set_attr("op_role", role_id) + continue + if op.attr(OP_ROLE_VAR_ATTR_NAME): + param_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[0] + grad_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[1] + if param_name not in optimize_params: + optimize_params.add(param_name) + param_grad = (origin_var_dict[param_name], + origin_var_dict[grad_name]) + + if param_name in sparse_varnames: + sparse_param_grads.append(param_grad) + else: + dense_param_grads.append(param_grad) + return sparse_param_grads, dense_param_grads + + def _get_sparse_varnames(): + varnames = [] + for op in origin_program.global_block().ops: + if op.type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0] + varnames.append(param_name) + + return list(set(varnames)) + + sparse_varnames = _get_sparse_varnames() + sparse_param_grads, dense_param_grads = _get_params_grads( + sparse_varnames) + + return sparse_param_grads, dense_param_grads + + def remove_var_pair_by_grad(self, var_name): + + for index, pair in enumerate(self.merged_variables_pairs): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del self.merged_variables_pairs[index] + + for index, pair in enumerate(self.merged_dense_pairs): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del self.merged_dense_pairs[index] + return + + for index, pair in enumerate(self.merged_sparse_pairs): + var = pair[0] + var_grad = pair[1] + if var_grad.merged_var.name == var_name: + del self.merged_sparse_pairs[index] + return + + print("Not find {} in self.merge_pairs".format(var_name)) + + +def _is_opt_role_op(op): + # NOTE : depend on oprole to find out whether this op is for + # optimize + op_maker = core.op_proto_and_checker_maker + optimize_role = core.op_proto_and_checker_maker.OpRole.Optimize + if op_maker.kOpRoleAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(optimize_role): + return True + return False + + +def _get_optimize_ops(_program): + block = _program.global_block() + opt_ops = [] + for op in block.ops: + if _is_opt_role_op(op): + # delete clip op from opt_ops when run in Parameter Server mode + if OP_NAME_SCOPE in op.all_attrs() \ + and CLIP_OP_NAME_SCOPE in op.attr(OP_NAME_SCOPE): + op._set_attr( + "op_role", + int(core.op_proto_and_checker_maker.OpRole.Backward)) + continue + opt_ops.append(op) + return opt_ops + + +def _add_lr_decay_table_pass(main_program, compiled_config, lr_decay_steps): + if hasattr(compiled_config.origin_main_program, 'lr_sheduler'): + from paddle.optimizer.lr import LRScheduler + assert isinstance(compiled_config.origin_main_program.lr_sheduler, + LRScheduler), "must be LRScheduler" + ops = _get_optimize_ops(compiled_config.origin_main_program) + lr_param_dict = _get_lr_param_dict(ops) + lr_decay_main_program, lr_decay_startup_program, lr_name = _get_lr_sheduler_program( + compiled_config.origin_main_program.lr_sheduler, lr_param_dict, + lr_decay_steps) + compiled_config.add_tensor_table("@LR_DECAY_COUNTER@", lr_name, + lr_decay_startup_program, + lr_decay_main_program, + "GlobalStepTable") + + +def _get_lr_param_dict(opt_ops): + lr_param_dict = {} + for op in opt_ops: + lr_name = op.input("LearningRate")[0] + param_name = op.input("Param")[0] + if lr_name not in lr_param_dict: + lr_param_dict[lr_name] = [] + lr_param_dict[lr_name].append(param_name) + return lr_param_dict + + +def _get_lr_sheduler_program(lr_sheduler, lr_param_dict, lr_decay_steps): + schedler_decay = [ + 'NoamDecay', 'NaturalExpDecay', 'InverseTimeDecay', 'ExponentialDecay' + ] + + from paddle.optimizer.lr import ExponentialDecay, NoamDecay, PiecewiseDecay, NaturalExpDecay, InverseTimeDecay + from paddle.fluid.layers.learning_rate_scheduler import exponential_decay, noam_decay, piecewise_decay, natural_exp_decay, inverse_time_decay + + decay_main_program = fluid.framework.Program() + decay_startup_program = fluid.framework.Program() + lr_name = "" + + if isinstance(lr_sheduler, ExponentialDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = exponential_decay(1.0, lr_decay_steps, lr_sheduler.gamma, True) + lr_name = lr.name + logging.warn( + "ExponentialDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + elif isinstance(lr_sheduler, NoamDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = noam_decay(lr_sheduler.d_model, lr_sheduler.warmup_steps, 1.0) + lr_name = lr.name + logging.warn("NoamDecay is set, warmup steps is [ %d ]" % + lr_sheduler.warmup_steps) + elif isinstance(lr_sheduler, NaturalExpDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = natural_exp_decay(1.0, lr_decay_steps, lr_sheduler.gamma, True) + lr_name = lr.name + logging.warn( + "NaturalExpDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + elif isinstance(lr_sheduler, InverseTimeDecay): + with fluid.program_guard(decay_main_program, decay_startup_program): + lr = inverse_time_decay(1.0, lr_decay_steps, lr_sheduler.gamma, + True) + lr_name = lr.name + logging.warn( + "InverseTimeDecay is set, staircase = True, global learning rate decay step is [ %d ], Change decay steps as follow: \n" + "\t strategy = paddle.distributed.fleet.DistributedStrategy() \n " + "\t strategy.a_sync = True \n" + "\t strategy.a_sync_configs= { 'lr_decay_steps' : YOUR_DECAY_STEP } \n" + % lr_decay_steps) + else: + raise ValueError( + "Not supported current LearningRate strategy, please use follow decay strategy: {}" + .format(schedler_decay)) + + return decay_main_program, decay_startup_program, lr_name + + +def _get_varname_parts(varname): + # returns origin, blockid, trainerid + orig_var_name = "" + trainer_part = "" + block_part = "" + trainer_idx = varname.find(".trainer_") + if trainer_idx >= 0: + trainer_part = varname[trainer_idx + 1:] + else: + trainer_idx = len(varname) + block_index = varname.find(".block") + if block_index >= 0: + block_part = varname[block_index + 1:trainer_idx] + else: + block_index = len(varname) + orig_var_name = varname[0:min(block_index, trainer_idx)] + return orig_var_name, block_part, trainer_part + + +def _orig_varname(varname): + orig, _, _ = _get_varname_parts(varname) + return orig diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/trainer_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/trainer_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..18755212cc16bc5537b77805c875ba54f9bde51e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/trainer_pass.py @@ -0,0 +1,1995 @@ +# -*- coding: UTF-8 -*- +# 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. + +from __future__ import print_function +import os +import six +import collections +import warnings +import math + +from functools import reduce +import paddle.fluid as fluid +import paddle.fluid.core as core +import paddle.fluid.framework as framework +import paddle.compat as cpt + +from paddle.fluid.transpiler.details.program_utils import delete_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_optimize_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.public import _get_lr_ops +from paddle.fluid.incubate.fleet.parameter_server.ir.public import get_sparse_tablenames +from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode + +OP_NAME_SCOPE = "op_namescope" +CLIP_OP_NAME_SCOPE = "gradient_clip" +STEP_COUNTER = "@PS_STEP_COUNTER@" +OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName() +RPC_OP_ROLE_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleAttrName() +RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC +LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched +OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize +op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + +SPARSE_OP_TYPE_DICT = {"lookup_table": "W", "lookup_table_v2": "W"} +SPARSE_GRAD_OP_TYPE_DICT = { + "lookup_table_grad": "W", + "lookup_table_v2_grad": "W" +} +DEVICE_LIST = ["cpu", "gpu", "xpu"] +COMMUNICATE_OPS_TYPE = ["send", "recv", "fetch_barrier", "send_barrier"] +DEFAULT_DEVICE = 'cpu' + + +def delete_optimizer_pass(program, config): + + def _delete_optimizer_op_and_vars(_program, optimize_ops): + optimize_vars = [] + optimize_op_role_vars = [] + optimize_need_delete_vars = [] + + for op in optimize_ops: + optimize_vars.extend(op.input_arg_names) + optimize_op_role_vars.extend(op.attr("op_role_var")) + + optimize_vars = list(set(optimize_vars)) + optimize_op_role_vars = list(set(optimize_op_role_vars)) + + for var in optimize_vars: + if var not in optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + delete_ops(_program.global_block(), optimize_ops) + for var in need_delete_optimize_vars: + if _program.global_block().has_var(var): + _program.global_block()._remove_var(var) + + def _add_lr_var(main_program, compiled_config): + # Todo: hard code for pe + lr_var = compiled_config.origin_main_program.global_block( + ).vars["learning_rate_0"] + main_program.global_block().create_var(name=lr_var.name, + shape=lr_var.shape, + dtype=lr_var.dtype, + type=lr_var.type, + lod_level=lr_var.lod_level, + persistable=True) + + optimizer_ops = _get_optimize_ops(program) + lr_ops = _get_lr_ops(program) + optimizer_ops.extend(lr_ops) + _delete_optimizer_op_and_vars(program, optimizer_ops) + + if hasattr(config.origin_main_program, 'lr_sheduler'): + _add_lr_var(program, config) + + return program + + +def distributed_ops_pass(program, config, use_ps_gpu=False): + trainer_id = config.get_role_id() + send_ctx = config.get_the_one_send_context( + split_dense_table=config.is_heter_ps_mode) + w_2_table_id = {} + emb_size = {} + + def _get_pull_sparse_ops(_program): + pull_sparse_ops = {} + pull_sparse_ids = {} + push_sparse_ops = {} + ops = {} + for op in _program.global_block().ops: + if op.type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[op.type])[0] + if config.is_heter_ps_mode: + # trick for matchnet, need to modify + param_name += op.input("Ids")[0][0] + ops = pull_sparse_ops.get(param_name, []) + ops.append(op) + pull_sparse_ops[param_name] = ops + ids = pull_sparse_ids.get(param_name, []) + ids.append(op.input("Ids")[0]) + pull_sparse_ids[param_name] = ids + for op in _program.global_block().ops: + if op.type in SPARSE_GRAD_OP_TYPE_DICT.keys(): + param_name = op.input(SPARSE_GRAD_OP_TYPE_DICT[op.type])[0] + if param_name in pull_sparse_ids and op.input( + "Ids")[0] in pull_sparse_ids[param_name]: + ops = push_sparse_ops.get(param_name, []) + ops.append(op) + push_sparse_ops[param_name] = ops + return pull_sparse_ops, push_sparse_ops + + def _pull_sparse_fuse(_program, pull_sparse_ops, use_ps_gpu): + + def dag_check_up_and_reorder(program, inputs, outputs): + global_block = program.global_block() + min_output_index = len(global_block.ops) + max_input_index = -1 + input_indexes = [0] * len(global_block.ops) + output_indexes = [0] * len(global_block.ops) + for idx, op in enumerate(global_block.ops): + for i in range(0, len(op.output_names)): + if input_indexes[idx] == 1: + break + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + input_indexes[idx] = 1 + max_input_index = max(max_input_index, idx) + break + + for i in range(0, len(op.input_names)): + if output_indexes[idx] == 1: + break + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + output_indexes[idx] = 1 + min_output_index = min(min_output_index, idx) + + for i in range(len(global_block.ops)): + if input_indexes[i] == 1 and output_indexes[i] == 1: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops because a op both needs embedding table's output as input and produces ids as the same embedding table's input" + ) + return + + if min_output_index < max_input_index: + move_ops = [] + for i in range(min_output_index + 1, len(input_indexes)): + if input_indexes[i] == 1: + move_ops.append((global_block.ops[i], i)) + for i, op in enumerate(move_ops): + queue = list() + visited = set() + queue.append(op[1]) + visited.add(op[0]) + start = 0 + while start < len(queue): + pos = queue[start] + op = global_block.ops[pos] + op_inputs = [] + for k in range(0, len(op.input_names)): + ins = op.input(op.input_names[k]) + op_inputs.append(ins) + for j in range(pos - 1, min_output_index - 1, -1): + op1 = global_block.ops[j] + if op1 in visited: + continue + found = False + for k in range(0, len(op1.output_names)): + outs = op1.output(op1.output_names[k]) + for t in range(len(op_inputs)): + for y in op_inputs[t]: + if y in outs: + found = True + break + if found: + break + if found: + break + if found: + if output_indexes[j] == True: + warnings.warn( + "unable to re-arrange dags order to combine distributed embedding ops" + ) + return + queue.append(j) + visited.add(global_block.ops[j]) + start = start + 1 + + queue.sort() + for index in queue: + desc = global_block.desc._insert_op(min_output_index) + desc.copy_from(global_block.ops[index].desc) + global_block.desc._remove_op(index + 1, index + 2) + global_block.ops[index].desc = desc + insert_op = global_block.ops.pop(index) + input_state = input_indexes.pop(index) + output_state = output_indexes.pop(index) + global_block.ops.insert(min_output_index, insert_op) + input_indexes.insert(min_output_index, input_state) + output_indexes.insert(min_output_index, output_state) + min_output_index = min_output_index + 1 + + assert global_block.desc.op_size() == len(global_block.ops) + for i in range(len(global_block.ops)): + assert global_block.desc.op(i) == global_block.ops[i].desc + + for param, ops in pull_sparse_ops.items(): + all_ops = program.global_block().ops + op_device = "" + if config.is_heter_ps_mode: + op_device = ops[0].attr("op_device") + inputs = [ + program.global_block().vars[op.input("Ids")[0]] for op in ops + ] + w = program.global_block().vars[ops[0].input("W")[0]] + emb_size[param] = w.shape[1] + + grad_name = config.param_name_to_grad_name[w.name] + + table_id = -1 + + for name, ctx in send_ctx.items(): + if grad_name in ctx.origin_varnames(): + table_id = ctx.table_id() + + if table_id == -1: + raise ValueError( + "can not find suitable sparse table, please check") + + w_2_table_id[param] = table_id + padding_idx = ops[0].attr("padding_idx") + is_distributed = ops[0].attr("is_distributed") + op_type = ops[0].type + + outputs = [ + program.global_block().vars[op.output("Out")[0]] for op in ops + ] + + dag_check_up_and_reorder(program, inputs, outputs) + + op_idxs = [all_ops.index(op) for op in ops] + + for idx in op_idxs[::-1]: + program.global_block()._remove_op(idx) + + inputs_idxs = [-1] * len(inputs) + outputs_idxs = [len(program.global_block().ops) + 1] * len(outputs) + + for idx, op in enumerate(program.global_block().ops): + for i in range(0, len(op.output_names)): + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + inputs_idxs[in_id] = max(idx, inputs_idxs[in_id]) + for i in range(0, len(op.input_names)): + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + outputs_idxs[out_id] = min(idx, + outputs_idxs[out_id]) + + if min(outputs_idxs) - max(inputs_idxs) >= 1: + if max(inputs_idxs) == -1: + distributed_idx = min(op_idxs) + else: + distributed_idx = max(inputs_idxs) + 1 + + if use_ps_gpu: + program.global_block()._insert_op( + index=distributed_idx, + type="pull_gpups_sparse", + inputs={ + "Ids": inputs, + 'W': w + }, + outputs={"Out": outputs}, + attrs={ + "size": [w.shape[1] for i in inputs], + "is_distributed": True, + "is_sparse": True + }) + else: + program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": inputs, + 'W': w + }, + outputs={"Outputs": outputs}, + attrs={ + "is_distributed": is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "lookup_table_version": op_type, + "op_device": op_device + }) + else: + for i in range(len(inputs_idxs)): + distributed_idx = op_idxs[i] + + program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": [inputs[i]], + 'W': w + }, + outputs={"Outputs": [outputs[i]]}, + attrs={ + "is_distributed": is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "lookup_table_version": op_type, + "op_device": op_device + }) + + def _push_sparse_fuse(_program, push_sparse_ops, use_ps_gpu): + if use_ps_gpu: + # in ps_gpu_pass + return + if len(push_sparse_ops) == 0: + return + show = None + clk = None + use_entry = False + for param, ops in push_sparse_ops.items(): + op_first = ops[0] + break + print(op_first) + if op_first.has_attr("entry"): + entry = op_first.attr("entry") + entry = entry.split(':') + if len(entry) == 3 and entry[0] == 'show_click_entry': + show_var_name = entry[1] + click_var_name = entry[2] + if show_var_name in program.global_block( + ).vars and click_var_name in program.global_block().vars: + show = program.global_block().vars[show_var_name] + clk = program.global_block().vars[click_var_name] + use_entry = True + else: + warnings.warn( + 'ShowClickEntry configured, but cannot find show/click var, will not use' + ) + + if not use_entry: + print('ShowClickEntry not configured, will not use') + show = program.global_block().create_var( + name="show", + dtype=core.VarDesc.VarType.INT64, + persistable=False, + stop_gradient=True) + program.global_block()._insert_op( + index=0, + type='fill_constant', + inputs={}, + outputs={'Out': show}, + attrs={ + 'shape': [1], + 'dtype': show.dtype, + 'value': 1, + #OP_ROLE_KEY: OpRole.Forward + }) + + clk = program.global_block().create_var( + name="clk", + dtype=core.VarDesc.VarType.INT64, + persistable=False, + stop_gradient=True) + program.global_block()._insert_op( + index=0, + type='fill_constant', + inputs={}, + outputs={'Out': clk}, + attrs={ + 'shape': [1], + 'dtype': clk.dtype, + 'value': 0, + #OP_ROLE_KEY: OpRole.Forward + }) + + for param, ops in push_sparse_ops.items(): + all_ops = program.global_block().ops + op_idxs = [all_ops.index(op) for op in ops] + inputs = [ + program.global_block().vars[op.input("Ids")[0]] for op in ops + ] + w = program.global_block().vars[ops[0].output("W@GRAD")[0]] + table_id = w_2_table_id[param] + + padding_idx = ops[0].attr("padding_idx") + is_distributed = ops[0].attr("is_distributed") + op_type = ops[0].type + outputs = [ + program.global_block().vars[op.input("Out@GRAD")[0]] + for op in ops + ] + + for idx in op_idxs[::-1]: + program.global_block()._remove_op(idx) + + +# if use_ps_gpu: +# program.global_block().append_op( +# type="push_box_sparse", +# inputs={"Ids": inputs, +# 'Out': outputs}, +# outputs={"Out": outputs}, +# attrs={ +# "size": w.shape[1], +# "is_distributed": True, +# "is_sparse": True +# }) +# else: + program.global_block().append_op(type="distributed_push_sparse", + inputs={ + "Ids": inputs, + 'W': w, + "Outputs": outputs, + "Shows": show, + "Clicks": clk + }, + outputs={"Outputs": outputs}, + attrs={ + "is_distributed": + is_distributed, + "padding_idx": padding_idx, + "table_id": table_id, + "size": emb_size[param] + }) + + pull_sparse_ops, push_sparse_ops = _get_pull_sparse_ops(program) + _pull_sparse_fuse(program, pull_sparse_ops, use_ps_gpu) + _push_sparse_fuse(program, push_sparse_ops, use_ps_gpu) + return program + + +def append_send_ops_pass(program, config): + mode = config.get_distributed_mode() + trainer_id = config.get_role_id() + + def _append_send_op(union_vars, queue, is_sparse, table_id): + + if queue == STEP_COUNTER: + send_input_vars = [] + else: + send_input_vars = [ + program.global_block().vars[union_var] + for union_var in union_vars + ] + + dummy_output = [] + if mode in [DistributedMode.SYNC, DistributedMode.HALF_ASYNC]: + dummy_output = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + + program.global_block().append_op(type="send", + inputs={"X": send_input_vars}, + outputs={"Out": dummy_output}, + attrs={ + "send_varnames": [queue], + "is_sparse": + is_sparse, + "table_id": + table_id, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + return dummy_output + + def _append_barrier_op(dummys): + program.global_block().append_op(type="send_barrier", + inputs={"X": dummys}, + outputs={"Out": []}, + attrs={ + "trainer_id": + trainer_id, + "half_async": + True, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + dummys = [] + + sends = config.get_the_one_trainer_send_context( + split_dense_table=config.is_heter_ps_mode) + + for merged_name, send in sends.items(): + if send.is_sparse() and not config.is_geo_mode(): + continue + is_sparse = 1 if send.is_sparse() else 0 + is_sparse = 2 if send.is_distributed() else is_sparse + dummys.append( + _append_send_op(send.origin_varnames(), merged_name, is_sparse, + send.table_id())) + + if mode in [DistributedMode.SYNC, DistributedMode.HALF_ASYNC]: + _append_barrier_op(dummys) + + return program + + +def init_from_server_pass(program, config): + # 0' trainer do not need barrier, it will call barrier at the end init_worker + if config.role_maker._is_first_worker(): + return program + + fetch_barrier_out = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + + program.global_block().append_op(type="fetch_barrier", + inputs={}, + outputs={"Out": fetch_barrier_out}, + attrs={ + "endpoints": + config.get_ps_endpoints(), + "trainer_id": + config.get_role_id(), + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + return program + + +def fake_init_ops_pass(program, config): + origin_program = config.get_origin_main_program() + + def _get_sparse_table_names(): + dist_varnames = get_sparse_tablenames(origin_program, True) + sparse_varnames = get_sparse_tablenames(origin_program, False) + return list(set(dist_varnames + sparse_varnames)) + + def _fake_init_sparsetable(sparse_table_names): + # delete table init op + for table_name in sparse_table_names: + table_var = program.global_block().vars[table_name] + table_param_init_op = [] + for op in program.global_block().ops: + if table_name in op.output_arg_names: + table_param_init_op.append(op) + init_op_num = len(table_param_init_op) + if init_op_num != 1: + raise ValueError("table init op num should be 1, now is " + + str(init_op_num)) + table_init_op = table_param_init_op[0] + program.global_block().append_op( + type="fake_init", + inputs={}, + outputs={"Out": table_var}, + attrs={"shape": table_init_op.attr('shape')}) + delete_ops(program.global_block(), table_param_init_op) + + sparse_tables = _get_sparse_table_names() + _fake_init_sparsetable(sparse_tables) + + return program + + +def ps_gpu_pass(program): + + def _add_push_box_sparse_op(program): + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + for op in program.global_block().ops: + if op.type != "pull_box_sparse" and op.type != "pull_gpups_sparse": + continue + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + op.desc, cpt.to_text(set()), []) + for op_desc in grad_op_desc: + new_op_desc = program.global_block().desc.append_op() + new_op_desc.copy_from(op_desc) + new_op_desc._set_attr(op_role_attr_name, backward) + + def _remove_lookup_table_grad_op_and_var(program): + lookup_table_grad_var = {} + remove_op_index = [] + remove_var = [] + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "lookup_table_grad": + for name in op.output("W@GRAD"): + lookup_table_grad_var[name] = 1 + remove_op_index.append(idx) + remove_var.append(name) + for name in op.input("W"): + lookup_table_grad_var[name] = 1 + + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "pull_box_sparse" or op.type == "pull_gpups_sparse": + continue + for key_name in op.input_names: + for var in op.input(key_name): + if var in lookup_table_grad_var: + remove_op_index.append(idx) + break + + remove_op_index = list(set(remove_op_index)) + remove_op_index.sort(reverse=True) + for idx in remove_op_index: + program.global_block()._remove_op(idx) + for name in remove_var: + program.global_block()._remove_var(name) + + def _remove_optimizer_var(program): + + embedding_w = {} + for idx, op in list(enumerate(program.global_block().ops)): + if op.type == "lookup_table_grad": + for name in op.input("W"): + embedding_w[name] = 1 + + optimize_vars = [] + optimize_op_role_vars = [] + optimize_need_delete_vars = [] + for op in _get_optimize_ops(program): + for name in op.input("Param"): + if name in embedding_w: + optimize_op_role_vars.extend(op.attr("op_role_var")) + for key_name in op.input_names: + if key_name == "LearningRate": + continue + for var in op.input(key_name): + optimize_vars.append(var) + + optimize_vars = list(set(optimize_vars)) + optimize_op_role_vars = list(set(optimize_op_role_vars)) + + for var in optimize_vars: + if var not in optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + for name in need_delete_optimize_vars: + if program.global_block().has_var(name): + program.global_block()._remove_var(name) + + _add_push_box_sparse_op(program) + _remove_optimizer_var(program) + _remove_lookup_table_grad_op_and_var(program) + return program + + +def delete_extra_optimizes_pass(program, config): + optimize_vars = [] + optimize_op_role_vars = [] + optimize_need_delete_vars = [] + + origin_program = config.get_origin_main_program() + for op in _get_optimize_ops(origin_program): + optimize_vars.extend(op.input_arg_names) + optimize_op_role_vars.extend(op.attr("op_role_var")) + + optimize_vars = list(set(optimize_vars)) + optimize_op_role_vars = list(set(optimize_op_role_vars)) + for var in optimize_vars: + if var not in optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + init_ops = [] + for var in need_delete_optimize_vars: + param_init_op = [] + for op in program.global_block().ops: + if var in op.output_arg_names: + param_init_op.append(op) + init_ops.extend(param_init_op) + delete_ops(program.global_block(), init_ops) + + for var in need_delete_optimize_vars: + if program.global_block().has_var(var): + program.global_block()._remove_var(var) + + return program + + +def find_heter_ops(program, default_device="cpu"): + if default_device not in DEVICE_LIST: + raise ValueError("Given device {} is not in device list {}".format( + default_device, DEVICE_LIST)) + + def _is_heter_op(op, current_heter_device, default_device="cpu"): + heter_devices = list(DEVICE_LIST) + heter_devices.remove(default_device) + op_device = op.attr("op_device") + op_type = op.type + if op_device in heter_devices: + return True + elif op_type in COMMUNICATE_OPS_TYPE and current_heter_device != default_device: + # for distributed communciate ops: send & recv & barrier etc. + # Todo: need update this method + #op._set_attr('op_device', current_heter_device) + return True + elif op_device == None or op_device == default_device: + op._set_attr('op_device', default_device) + return False + return False + + def _is_same_device(op, pre_device, default_device="cpu"): + op_device = op.attr("op_device") + if op_device == pre_device: + return True + if pre_device == default_device: + return True + return False + + def _append_heter_op(op, current_heter_block_ops, heter_ops): + op_device = op.attr("op_device") + if op_device not in heter_ops: + heter_ops[op_device] = {} + current_heter_block_ops.append(op) + + origin_porgram = program.clone() + block = program.global_block() + ''' + re-place sum op to fix bug for union forward backward op + ''' + var2idx = {} + op_list = list(block.ops) + op_size = len(op_list) + + for i in range(op_size - 1, -1, -1): + op_list = list(block.ops) + op = op_list[i] + if "_grad" in op.type: + forward_op_type = op.type.split("_grad")[0] + if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[forward_op_type])[0] + if param_name in var2idx: + ## insert sum op & remove sum op from var2idx and origin place + op_list = list(block.ops) + sum_op = op_list[var2idx[param_name]] + sum_op_inputs = { + sum_op.input_names[0]: + [block.vars[input] for input in sum_op.input_arg_names] + } + sum_op_outputs = { + sum_op.output_names[0]: [ + block.vars[output] + for output in sum_op.output_arg_names + ] + } + block._insert_op(index=i + 1, + type=sum_op.type, + inputs=sum_op_inputs, + outputs=sum_op_outputs, + attrs=sum_op.all_attrs()) + block._remove_op(var2idx[param_name] + 1) + var2idx.pop(param_name) + for var_ in var2idx: + var2idx[var_] += 1 + elif forward_op_type == "elementwise_mul": + """ + get output varname of pre op + + """ + output_vars_no_grad = [] + for key in op.output_names: + for varname in op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + output_vars_no_grad.append(varname.split("@GRAD")[0]) + for no_grad_var in output_vars_no_grad: + if no_grad_var in var2idx: + """ + insert sum op & remove sum op from var2idx and origin place + + """ + op_list = list(block.ops) + sum_op = op_list[var2idx[no_grad_var]] + sum_op_inputs = { + sum_op.input_names[0]: [ + block.vars[input] + for input in sum_op.input_arg_names + ] + } + sum_op_outputs = { + sum_op.output_names[0]: [ + block.vars[output] + for output in sum_op.output_arg_names + ] + } + block._insert_op(index=i + 1, + type=sum_op.type, + inputs=sum_op_inputs, + outputs=sum_op_outputs, + attrs=sum_op.all_attrs()) + block._remove_op(var2idx[no_grad_var] + 1) + var2idx.pop(no_grad_var) + for var_ in var2idx: + var2idx[var_] += 1 + else: + if op.type == "sum": + var = op.output("Out")[0] + if "@GRAD" in var: + origin_var = var.split("@GRAD")[0] + pre_op = op_list[i - 1] + if "_grad" in pre_op.type: + forward_op_type = pre_op.type.split("_grad")[0] + if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ + and pre_op.attr('remote_prefetch') is True: + param_name = pre_op.input( + SPARSE_OP_TYPE_DICT[forward_op_type])[0] + if param_name == origin_var and op.attr( + "op_device") == pre_op.attr("op_device"): + continue + else: + var2idx[origin_var] = i + elif forward_op_type == "elementwise_mul": + output_vars = [] + for key in pre_op.output_names: + for varname in pre_op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + output_vars.append(varname) + input_vars = [] + for key in op.input_names: + for varname in op.input(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + input_vars.append(varname) + is_match = False + for varname in output_vars: + if varname in input_vars: + is_match = True + break + if is_match: + continue + else: + var2idx[origin_var] = i + else: + var2idx[origin_var] = i + + origin_porgram = program.clone() + block = program.global_block() + + program_block_ops = [] + default_ops = {default_device: {}} + heter_ops = {} + block_index = 0 + + current_heter_block_ops = [] + current_default_block_ops = [] + current_heter_device = default_device + is_heter = False + for op in block.ops: + if _is_heter_op(op, current_heter_device, default_device): + # for gpu/xpu-op + is_heter = True + + # for cpu-op block append + if len(current_default_block_ops) > 1: + default_ops[default_device][ + block_index] = current_default_block_ops + program_block_ops.append(current_default_block_ops) + current_default_block_ops = [] + block_index += 1 + + if _is_same_device(op, current_heter_device, default_device): + # for gpu-op, gpu-op -> gpu-op,... + current_heter_device = op.attr("op_device") + _append_heter_op(op, current_heter_block_ops, heter_ops) + else: + # for gpu-op -> xpu-op, ... + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + block_index += 1 + current_heter_block_ops = [] + current_heter_device = op.attr("op_device") + _append_heter_op(op, current_heter_block_ops, heter_ops) + + elif is_heter: + # for gpu/xpu-op -> cpu-op + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + block_index += 1 + current_heter_block_ops = [] + current_heter_device = default_device + is_heter = False + current_default_block_ops.append(op) + else: + # for cpu-op + current_default_block_ops.append(op) + + if current_default_block_ops != []: + default_ops[default_device][block_index] = current_default_block_ops + program_block_ops.append(current_default_block_ops) + + if current_heter_block_ops != []: + op_device = current_heter_block_ops[0].attr("op_device") + heter_ops[op_device][block_index] = current_heter_block_ops + program_block_ops.append(current_heter_block_ops) + + if len(heter_ops) == 0: + warnings.warn( + "No heterogeneous OP was found in your program , " + " please using fluid.device_guard() to run OPs on different device." + ) + + total_heter_ops = 0 + heter_blocks = 0 + for device in heter_ops.keys(): + heter_block_dict = heter_ops[device] + heter_blocks += len(heter_block_dict) + for _, heter_block in heter_block_dict.items(): + total_heter_ops += len(heter_block) + print( + "There are {} OPs in your main_program, and contains {} heter-OPs which is made up of {} heter-blocks." + .format(len(block.ops), total_heter_ops, heter_blocks)) + + return origin_porgram, heter_ops, default_ops, program_block_ops + + +def create_heter_program(program, config, heter_program, program_block_ops_list, + heter_ops, block_var_detail, current_device, stage_id): + # This function mainly includes the following contents: + # 1. For every heter block: + # a) copy heter device op from origin program + # b) create variables which belong to heter op: + # -> if variable is persistable, clone it in global_scope + # -> if variable is temp, create it in heter block + # c) create communicate related op as follow: + # joint_var.0_1 -> slice -> reshape -> origin_var + # origin_var -> origin_program + # reshape -> concat -> joint_var.1_2 + # d) copy send op from origin program for var@grad which loacted in current heter block + # e) re-check every op in current blcok if its device is not current heter devie + # 2. Create send op for step counter in last heter-block + # 3. Create Listen&Serv OP and Send&Recv OP for distributed training + # 4. update CompileTimeStrategy for heter_program + + optimizer_block = [] + grad_to_block_id = [] + send_grad_var_list = [] + + pre_block_idx = heter_program.num_blocks - 1 + stage_id = int(stage_id) + print("stage id", stage_id) + heter_block_ops_forward = program_block_ops_list[stage_id - 1]["forward"] + + heter_block_ops_backward = program_block_ops_list[stage_id - 1]["backward"] + + heter_block = heter_program._create_block(pre_block_idx) + optimizer_block.append(heter_block) + for _, op in enumerate(heter_block_ops_forward): + block_append_op(heter_program, program, heter_block, op) + + entrance_vars = block_var_detail[stage_id - 1]["forward"]["entrance"] + add_vars_by_var_list(entrance_vars, program, heter_program, heter_block) + exit_vars = block_var_detail[stage_id - 1]["forward"]["exit"] + add_vars_by_var_list(exit_vars, program, heter_program, heter_block) + + first_op_index_fp = len(heter_block.ops) + + if stage_id < len(program_block_ops_list): + + heter_block_bp = heter_program._create_block(pre_block_idx) + optimizer_block.append(heter_block_bp) + + for _, op in enumerate(heter_block_ops_backward): + block_append_op(heter_program, program, heter_block_bp, op) + + bp_entrance_vars = block_var_detail[stage_id - + 1]["backward"]["entrance"] + add_vars_by_var_list(bp_entrance_vars, program, heter_program, + heter_block_bp) + bp_exit_vars = block_var_detail[stage_id - 1]["backward"]["exit"] + add_vars_by_var_list(bp_exit_vars, program, heter_program, + heter_block_bp) + backward_comm_info = get_communicate_var_info(program, + stage_id, + bp_entrance_vars, + type="backward") + + grad_to_block_id.append(backward_comm_info["block_input_var_name"] + + ":" + str(heter_block_bp.idx)) + + else: + for _, op in enumerate(heter_block_ops_backward): + block_append_op(heter_program, program, heter_block, op) + + bp_entrance_vars = block_var_detail[stage_id - + 1]["backward"]["entrance"] + add_vars_by_var_list(bp_entrance_vars, program, heter_program, + heter_block) + bp_exit_vars = block_var_detail[stage_id - 1]["backward"]["exit"] + add_vars_by_var_list(bp_exit_vars, program, heter_program, heter_block) + + heter_block_bp = heter_block + + forward_comm_info = get_communicate_var_info(program, + stage_id, + entrance_vars, + type="forward") + + grad_to_block_id.append(forward_comm_info["block_input_var_name"] + ":" + + str(heter_block.idx)) + + first_op_index_bp = len(heter_block_bp.ops) + + if stage_id <= len(block_var_detail) - 1: + static_var = insert_communicate_op(program, config, heter_block, + stage_id, first_op_index_fp, + block_var_detail, current_device) + static_var_bp = insert_communicate_op(program, config, heter_block_bp, + stage_id, first_op_index_bp, + block_var_detail, current_device, + False) + + # add send op + send_grad_var_list = add_heter_send_op(program, heter_program, + heter_block_bp, + block_var_detail[stage_id - 1]) + + # --------------- + # add step conter + send_input_vars = [] + dummy_output = [] + pserver_endpoints = config.get_ps_endpoints() + + # optimizer_block[-1].append_op( + # type="send", + # inputs={"X": send_input_vars}, + # outputs={"Out": dummy_output}, + # attrs={ + # "send_varnames": [STEP_COUNTER], + # "merge_add": True, + # "use_send_handler": False, + # "endpoints": pserver_endpoints + # }) + + # add info in listen&serv + attrs = { + #"mode": "sync", + #"trainers": config.get_trainers(), + #"trainer_id": config.get_role_id() + config.get_trainers(), + "message_to_block_id": grad_to_block_id, + "optimize_blocks": optimizer_block, + # runtime attribute + "endpoint": config.get_heter_worker_endpoint(), + "fanin": len(config.get_previous_stage_trainers()), + "pserver_id": config.get_role_id(), + "distributed_mode": config.get_distributed_mode(), + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + # append the listen_and_serv op + heter_program.global_block().append_op(type="heter_listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + check_heter_compile_time_strategy(program, config, send_grad_var_list) + + +def check_heter_compile_time_strategy(program, config, send_grad_var_list): + origin_grad_var_list = [] + for _, var_grad in config.merged_variables_pairs: + origin_grad_var_list.append(var_grad.merged_var.name) + + origin_grad_var_list = list(set(origin_grad_var_list)) + send_grad_var_list = list(set(send_grad_var_list)) + useless_grad_var_list = list( + set(origin_grad_var_list) - set(send_grad_var_list)) + + for useless_grad_var in useless_grad_var_list: + config.remove_var_pair_by_grad(useless_grad_var) + + +def create_trainer_program(program, origin_program, config, + program_block_ops_list, block_var_detail): + # This function mainly includes the following contents: + # 1. For every heter block in origin program + # a) delete heter op and related variables + # b) add send&recv op + # c) add communicate ops as follows: + # origin_var -> reshape -> concat -> joint_var.0_1 + # send&recv op(send joint_var.0_1; recv joint_var.1_2) + # joint_var.1_2 -> slice -> reshape -> origin_var + # d) remove send op which related var@grad is not in trainer program + # 2. check every op's device + static_var = [] + for heter_block_index in range(1, len(program_block_ops_list)): + ops_list = program_block_ops_list[heter_block_index][ + "forward"] + program_block_ops_list[heter_block_index]["backward"] + static_var += replace_ops_by_communicate_op(program, config, + heter_block_index, ops_list, + block_var_detail) + remove_trainer_send_op(program, config, heter_block_index, + block_var_detail) + + optimizer_block = [] + grad_to_block_id = [] + + bp_ops_list = program_block_ops_list[0]["backward"] + delete_same_ops(program.global_block(), bp_ops_list) + delete_trainer_useless_var(config, program, static_var) + backward_block = create_backward_block(program, origin_program, config, + bp_ops_list, block_var_detail) + + bp_entrance_vars = block_var_detail[0]["backward"]["entrance"] + backward_comm_info = get_communicate_var_info(origin_program, + 1, + bp_entrance_vars, + type="backward") + + grad_to_block_id.append(backward_comm_info["block_input_var_name"] + ":" + + str(backward_block.idx)) + optimizer_block.append(backward_block) + + attrs = { + #"mode": "sync", + #"trainers": config.get_trainers(), + #"trainer_id": config.get_role_id(), + "message_to_block_id": grad_to_block_id, + "optimize_blocks": optimizer_block, + # runtime attribute + "endpoint": config.get_trainer_endpoint(), ## get trainer endpoint + "fanin": 0, ## get heter worker + "pserver_id": config.get_role_id(), + "distributed_mode": config.get_distributed_mode(), + "rpc_exec_thread_num": int(os.getenv("CPU_NUM", 32)), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + } + # append the listen_and_serv op + program.global_block()._insert_op(index=0, + type="heter_listen_and_serv", + inputs={'X': []}, + outputs={}, + attrs=attrs) + + ## TODO add check for bp block + check_op_device(program.global_block(), DEFAULT_DEVICE) + + +def insert_communicate_op(orign_program, + config, + heter_block, + stage_id, + first_op_index, + block_var_detail, + device, + is_forward=True): + + if is_forward: + next_heter_worker_endpoints = config.get_next_stage_trainers() + previous_heter_worker_endpoints = config.get_previous_stage_trainers() + entrance_var = block_var_detail[stage_id]["forward"]["entrance"] + comm_info = get_communicate_var_info(orign_program, stage_id + 1, + entrance_var) + + else: + next_heter_worker_endpoints = config.get_next_stage_trainers() + #if next_heter_worker_endpoints == "": + # next_heter_worker_endpoints = [] + previous_heter_worker_endpoints = config.get_previous_stage_trainers() + entrance_var = block_var_detail[stage_id - 1]["backward"]["exit"] + comm_info = get_communicate_var_info(orign_program, stage_id - 1, + entrance_var, "backward") + + heter_block._insert_op(index=first_op_index, + type="send_and_recv", + inputs={"X": heter_block.vars[entrance_var[0]]}, + outputs={"Out": []}, + attrs={ + "mode": "forward" if is_forward else "backward", + "send_var_name": + entrance_var + ["microbatch_id"], + "recv_var_name": [], + "message_name": + comm_info["block_input_var_name"], + "next_endpoints": next_heter_worker_endpoints, + "previous_endpoints": + previous_heter_worker_endpoints, + "trainer_id": config.get_role_id(), + "op_device": device, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return entrance_var + + +def create_backward_block(program, origin_program, config, bp_ops_list, + block_var_detail): + pre_block_idx = program.num_blocks - 1 + heter_block = program._create_block(pre_block_idx) + + for _, op in enumerate(bp_ops_list): + if op.type == "send": + send_varnames = op.attr('send_varnames') + is_skip = False + for varname in send_varnames: + if varname not in program.global_block( + ).vars and varname not in heter_block.vars: + is_skip = True + break + if is_skip == True: + continue + block_append_op(program, origin_program, heter_block, op) + + entrance_vars = block_var_detail[0]["backward"]["entrance"] + add_vars_by_var_list(entrance_vars, origin_program, program, heter_block) + exit_vars = block_var_detail[0]["backward"]["exit"] + add_vars_by_var_list(exit_vars, origin_program, program, heter_block) + return heter_block + + +def replace_ops_by_communicate_op(program, config, heter_block_index, ops_list, + block_var_detail): + all_op = program.global_block().ops + start_op = ops_list[0] + first_op_idx = -1 + for op in all_op: + if is_same_op(op, start_op): + first_op_idx = all_op.index(op) + break + assert first_op_idx != -1 + delete_same_ops(program.global_block(), ops_list) + + entrance_var = [] + + if heter_block_index == 1: + mode = config.get_distributed_mode() + next_heter_worker_endpoints = config.get_next_stage_trainers() + + entrance_var = block_var_detail[heter_block_index]["forward"][ + "entrance"] + + comm_info = get_communicate_var_info(program, heter_block_index + 1, + entrance_var) + program.global_block()._insert_op( + index=first_op_idx, + type="send_and_recv", + inputs={"X": program.global_block().vars[entrance_var[0]]}, + outputs={"Out": []}, + attrs={ + "mode": "forward", + "send_var_name": entrance_var + ["microbatch_id"], + "recv_var_name": [], + "message_name": comm_info["block_input_var_name"], + "next_endpoints": next_heter_worker_endpoints, + "previous_endpoints": [], + "trainer_id": config.get_role_id(), + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return entrance_var + + +def remove_trainer_send_op(program, config, heter_block_index, + block_var_detail): + + # if trainer do FF->BP->SEND, it has follow vars: var, var@GRAD + # if trainer only do SEND, it has one var: var@GRAD + # Delete Send op ,if trainer doesn't has pair var (var<->var@GRAD) + persistables = block_var_detail[heter_block_index]["forward"]["persistables"] + \ + block_var_detail[heter_block_index]["backward"]["persistables"] + need_remove_send_op = [] + need_remove_grad_var = [] + for op in find_send_op(program): + input_list, _ = find_op_input_output(program, program.global_block(), + op) + for var_name in input_list: + origin_var_name = var_name.split("@GRAD")[0] + if origin_var_name in persistables: + need_remove_send_op.append(op) + need_remove_grad_var.append(var_name) + need_remove_send_op = list(set(need_remove_send_op)) + delete_ops(program.global_block(), need_remove_send_op) + for grad_var_name in need_remove_grad_var: + config.remove_var_pair_by_grad(grad_var_name) + + +def add_heter_send_op(program, heter_program, block, block_var_detail): + + def _get_send_op_dict(): + send_op_dict = {} + send_op_list = find_send_op(program) + for op in send_op_list: + input_list, _ = find_op_input_output(program, + program.global_block(), op) + for var in input_list: + send_op_dict[var] = op + return send_op_dict + + # send_Op = { inputs{'X':[]}, + # outputs{'Out':dummy_output}, + # attrs{'send_varnames'"[]", + # 'is_sparse':int, + # 'table_id':int } } + send_grad_var_list = [] + send_op_dict = _get_send_op_dict() + table_dict = {} + for persistable_var in block_var_detail["backward"]["persistables"]: + # check var_name == var@GRAD + if "@GRAD" not in persistable_var: + continue + if "GRAD" != persistable_var.split("@")[-1]: + continue + if persistable_var not in send_op_dict: + continue + send_op = send_op_dict[persistable_var] + is_sparse = send_op.attr('is_sparse') + table_id = send_op.attr('table_id') + send_varnames = send_op.attr('send_varnames') + send_grad_var_list.append(persistable_var) + if table_id not in table_dict: + table_dict[table_id] = {} + table_dict[table_id]['var_list'] = [] + table_dict[table_id]['is_sparse'] = is_sparse + table_dict[table_id]['send_varnames'] = send_varnames + table_dict[table_id]['var_list'].append(persistable_var) + + for table_id in table_dict: + dummy_output = block.create_var( + name=framework.generate_control_dev_var_name()) + send_input_vars = [ + block.vars[union_var] + for union_var in table_dict[table_id]['var_list'] + ] + block.append_op(type="send", + inputs={"X": send_input_vars}, + outputs={"Out": dummy_output}, + attrs={ + "send_varnames": + table_dict[table_id]['send_varnames'], + "is_sparse": is_sparse, + "table_id": table_id, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + return send_grad_var_list + + +def find_send_op(program): + send_op_list = [] + for op in program.global_block().ops: + if op.type == "send": + send_op_list.append(op) + return send_op_list + + +def get_communicate_var_info(program, + block_index, + entrance_var_list, + type="forward"): + input_var_reshape_dim = [] + input_var_reshape_name = [] + + if type == "forward": + block_input_var_name = "forward_joint_{}_{}@Heter".format( + block_index - 1, block_index) + else: + block_input_var_name = "backward_joint_{}_{}@Heter".format( + block_index + 1, block_index) + + entrance_var_list.sort() + # input + # Heter_SERVER_BLOCK_index@JOINT_VAR -> slice -> var@Heter_SERVER_BLOCK@INPUT_RESHAPE_VAR -> reshape -> var + for name in entrance_var_list: + var = program.global_block().vars[name] + shape = var.shape + # if len(shape) < 2 or shape[0] != -1: + # raise ValueError( + # "Variable {} not support heter training. its shape is {}". + # format(name, shape)) + recv_var_dim = -1 * reduce(lambda x, y: x * y, shape) + input_var_reshape_dim.append(recv_var_dim) + input_var_reshape_name.append("{}.input_reshape@Heter".format(name)) + + # output + # var -> reshape -> var@Heter_SERVER_BLOCK@INPUT_RESHAPE_VAR -> concat -> Heter_SERVER_BLOCK_index@JOINT_VAR + #for var_name in exit_var_list: + # var = program.global_block().vars[var_name] + # shape = var.shape + # # if len(shape) < 2 or shape[0] != -1: + # # raise ValueError( + # # "Variable {} not support heter training. its shape is {}". + # # format(var_name, shape)) + # send_reshape_dim = -1 * reduce(lambda x, y: x * y, shape) + # output_var_reshape_dim.append(send_reshape_dim) + # output_var_reshape_name.append("{}.output_reshape@Heter".format( + # var_name)) + + info = { + "input_var_reshape_dim": input_var_reshape_dim, + "input_var_reshape_name": input_var_reshape_name, + "block_input_var_name": block_input_var_name, + # "output_var_reshape_dim": output_var_reshape_dim, + # "output_var_reshape_name": output_var_reshape_name, + # "block_output_var_name": block_output_var_name + } + + return info + + +def union_forward_gradient_op(program_block_ops_list): + """ + before analyzing the input & output of each block in program_block_list, we should + union the forward op and corresponding gradient op to elimincate the unnecessary variable + transmit + """ + """ + fix for 2emb model, re-place sum op + + """ + block_length = len(program_block_ops_list) + ''' + ## get the final part + final_part_idx = -1 + for i in range(block_length): + op_list = program_block_ops_list[i] + for op in op_list: + if "_grad" in op.type: + final_part_idx = i + break + if final_part_idx != -1: + break + + ## eliminate wrong partition because of sum op + ## lookup_table_v2_grad + ## every looup_table_v2_grad op block should follow a sum op + var2idx = {} + + for i in range(final_part_idx, block_length): + op_list = program_block_ops_list[i] + for j in range(len(op_list) - 1, -1, -1): + op = op_list[j] + #if op.type == "lookup_table_v2_grad": + # if j < len(op_list) - 1): + # else: + # ## get var and record place + if _grad in op.type: + forward_op_type = op.type.split("_grad")[0] + if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ + and op.attr('remote_prefetch') is True: + param_name = op.input(SPARSE_OP_TYPE_DICT[forward_op_type])[0] + + var2idx[] = [i,j] ## + + ''' + + union_program_block_ops_list = [] + assert block_length % 2 != 0, "the length of program_block_ops_list should be odd" + for i in range(0, block_length // 2): + block_op_list = {"forward": program_block_ops_list[i]} + block_op_list.update( + {"backward": program_block_ops_list[block_length - 1 - i]}) + union_program_block_ops_list.append(block_op_list) + + block_op_list = {"forward": [], "backward": []} + for op in program_block_ops_list[block_length // 2]: + if not "_grad" in op.type and not (op.type == "sum"): + block_op_list["forward"].append(op) + else: + block_op_list["backward"].append(op) + union_program_block_ops_list.append(block_op_list) + return union_program_block_ops_list + + +def find_block_joints(program, program_block_ops_list, heter_ops): + block_var_detail = find_entrance_exit_private(program, + program_block_ops_list) + block_var_detail = entrance_exit_check(program, program_block_ops_list, + block_var_detail, heter_ops) + block_var_detail = delete_block_useless_exit(program, + program_block_ops_list, + block_var_detail) + + return block_var_detail + + +def find_entrance_exit_private(program, program_block_ops_list): + block_var_detail = [] + persistables = [] + for index, block_op_list in enumerate(program_block_ops_list): + ## forward + block_input, block_output = find_ops_list_input_output( + program, block_op_list["forward"]) + persistables = screen_persistables( + program, block_input) + screen_persistables(program, block_output) + # find entrance & exit + block_private_vars = list(set(block_input) & set(block_output)) + block_entrance = list(set(block_input) - set(block_private_vars)) + block_exit = list(set(block_output) - set(block_private_vars)) + detail = { + "forward": { + "entrance": block_entrance, + "exit": block_exit, + "private": block_private_vars, + "persistables": persistables + } + } + + ## backward + bp_block_input, bp_block_output = find_ops_list_input_output( + program, block_op_list["backward"]) + bp_persistables = screen_persistables( + program, bp_block_input) + screen_persistables( + program, bp_block_output) + # find entrance & exit + bp_block_private_vars = list(set(bp_block_input) & set(bp_block_output)) + bp_block_entrance = list( + set(bp_block_input) - set(bp_block_private_vars)) + bp_block_exit = list(set(bp_block_output) - set(bp_block_private_vars)) + detail.update({ + "backward": { + "entrance": bp_block_entrance, + "exit": bp_block_exit, + "private": bp_block_private_vars, + "persistables": bp_persistables + } + }) + block_var_detail.append(detail) + return block_var_detail + + +def entrance_exit_check(program, program_block_ops_list, block_var_detail, + heter_ops): + for index in range(len(block_var_detail) - 1, -1, -1): + if index - 1 < 0: + break + previous_block_exit = block_var_detail[index - 1]["forward"]["exit"] + previous_block_exit.sort() + current_block_entrance = block_var_detail[index]["forward"]["entrance"] + + backward_entrance = block_var_detail[index]["backward"]["entrance"] + + forward_all = block_var_detail[index]["forward"][ + "entrance"] + block_var_detail[index]["forward"][ + "private"] + block_var_detail[index]["forward"]["exit"] + + for var in backward_entrance: + if not ("@GRAD" in var) and not (var in forward_all): + current_block_entrance.append(var) + + current_block_entrance.sort() + + if previous_block_exit == current_block_entrance: + continue + exist_vars = list( + set(previous_block_exit) & set(current_block_entrance)) + need_add_vars = list(set(current_block_entrance) - set(exist_vars)) + # var in different stage should not be ignored, since they are not placed in the same program & device + #need_add_vars = find_need_var_from_previous_block( + # need_add_vars, block_var_detail, index, heter_ops) + + previous_block_private = block_var_detail[index - + 1]["forward"]["private"] + previous_block_entrance = block_var_detail[index - + 1]["forward"]["entrance"] + for var in need_add_vars: + if var not in previous_block_private and var not in previous_block_entrance: + previous_block_entrance.append(var) + previous_block_exit.append(var) + if not var in current_block_entrance: + current_block_entrance.append(var) + + for index in range(0, len(block_var_detail) - 1, 1): + previous_block_exit = block_var_detail[index + 1]["backward"]["exit"] + previous_block_exit.sort() + current_block_entrance = block_var_detail[index]["backward"]["entrance"] + + current_block_entrance.sort() + + if previous_block_exit == current_block_entrance: + continue + exist_vars = list( + set(previous_block_exit) & set(current_block_entrance)) + need_add_vars = list(set(current_block_entrance) - set(exist_vars)) + need_ignore_vars = [] + for var in need_add_vars: + if not "@GRAD" in var: + need_ignore_vars.append(var) + need_add_vars = list( + set(need_add_vars).difference(set(need_ignore_vars))) + previous_block_private = block_var_detail[index + + 1]["backward"]["private"] + previous_block_entrance = block_var_detail[index + + 1]["backward"]["entrance"] + for var in need_add_vars: + if var not in previous_block_private and var not in previous_block_entrance: + previous_block_entrance.append(var) + previous_block_exit.append(var) + return block_var_detail + + +def find_need_var_from_previous_block(need_add_vars, block_var_detail, + current_index, heter_ops): + # create index_device_map + index_device_map = {} + for index in range(len(block_var_detail)): + index_device_map[index] = DEFAULT_DEVICE + for device in heter_ops: + for index in heter_ops[device].keys(): + if index < len(block_var_detail): + index_device_map[index] = device + + pre_index = current_index - 1 + need_ignore_var = [] + + # if need_add_var in current device, no need communicate + for var in need_add_vars: + while (pre_index >= 0): + previous_block_private = block_var_detail[pre_index]["private"] + previous_block_exit = block_var_detail[pre_index]["exit"] + previous_block_entrance = block_var_detail[pre_index]["entrance"] + total_var = previous_block_private + previous_block_exit + previous_block_entrance + if var in total_var: + if index_device_map[current_index] == index_device_map[ + pre_index] and index_device_map[ + current_index] == DEFAULT_DEVICE: + need_ignore_var.append(var) + break + pre_index -= 1 + + need_add_vars = list(set(need_add_vars).difference(set(need_ignore_var))) + return need_add_vars + + +def delete_block_useless_exit(program, program_block_ops_list, + block_var_detail): + ## forward + for index in range(len(block_var_detail)): + if index == len(block_var_detail) - 1: + break + current_block_exit = block_var_detail[index]["forward"]["exit"] + next_block_entrance = block_var_detail[index + 1]["forward"]["entrance"] + need_delete_var = [] + for var in current_block_exit: + if var not in next_block_entrance: + need_delete_var.append(var) + + for var in need_delete_var: + current_block_exit.remove(var) + ## backward + for index in range(len(block_var_detail) - 1, -1, -1): + if index - 1 < 0: + break + current_block_exit = block_var_detail[index]["backward"]["exit"] + next_block_entrance = block_var_detail[index - + 1]["backward"]["entrance"] + need_delete_var = [] + for var in current_block_exit: + if var not in next_block_entrance: + need_delete_var.append(var) + for var in need_delete_var: + current_block_exit.remove(var) + + return block_var_detail + + +def check_op_device(block, device): + for op in block.ops: + op._set_attr('op_device', device) + + +def screen_persistables(program, var_list): + need_remove = [] + for var_name in var_list: + if "@GRAD" in var_name: + if "GRAD" != var_name.split("@")[-1]: + continue + origin_var_name = var_name.split("@GRAD")[0] + var = program.global_block().vars[origin_var_name] + else: + var = program.global_block().vars[var_name] + + if fluid.io.is_persistable(var): + need_remove.append(var_name) + + for var_name in need_remove: + var_list.remove(var_name) + return need_remove + + +def insert_reshape_op(program, + block, + index, + var_name, + new_var_name, + new_var_shape=None): + input_var = block.vars[var_name] + + if new_var_name not in block.vars: + out = block.create_var(name=new_var_name, + shape=new_var_shape, + dtype=input_var.dtype, + type=input_var.type) + else: + out = block.vars[new_var_name] + new_var_shape = out.shape + + x_shape = block.create_var(name="{}.xshape@Heter".format(var_name), + dtype=input_var.dtype) + block._insert_op(index=index, + type="reshape2", + inputs={"X": input_var}, + attrs={'shape': new_var_shape}, + outputs={ + "Out": out, + "XShape": x_shape + }) + + +def insert_send_concat_op(program, block, index, var_name_list, new_var_name, + new_var_shape): + input_var_list = [block.vars[var_name] for var_name in var_name_list] + + out = program.global_block().create_var(name=new_var_name, + shape=new_var_shape, + dtype=input_var_list[0].dtype, + type=input_var_list[0].type) + + block._insert_op(index=index, + type='concat', + inputs={"X": input_var_list}, + outputs={'Out': [out]}, + attrs={ + 'axis': -1, + 'use_stack': False + }) + + +def insert_recv_slice_op(program, block, index, var_name, var_shape, dtype, + type, new_var_name_list, new_var_shape_list): + if var_name not in program.global_block().vars: + input_var = program.global_block().create_var(name=var_name, + shape=var_shape, + dtype=dtype, + type=type) + else: + input_var = program.global_block().vars[var_name] + + out_list = [] + for i in range(len(new_var_name_list)): + if new_var_name_list[i] not in block.vars: + out = block.create_var(name=new_var_name_list[i], + shape=new_var_shape_list[i], + dtype=input_var.dtype, + type=input_var.type) + else: + out = block.vars[new_var_name_list[i]] + out_list.append(out) + + start_index = 0 + end_index = 0 + for i in range(len(new_var_name_list)): + starts = [] + ends = [] + attrs = {'axes': [1]} + end_index += new_var_shape_list[i][1] + starts.append(start_index) + ends.append(end_index) + attrs['starts'] = starts + attrs['ends'] = ends + + block._insert_op(index=index, + type='slice', + inputs={'Input': input_var}, + attrs=attrs, + outputs={'Out': out_list[i]}) + start_index = end_index + index += 1 + + +def add_heter_trainer_useful_vars(config, program, heter_program, heter_block, + static_var): + static_var = list(set(static_var)) + for var_name in static_var: + if var_name not in heter_program.global_block( + ).vars and var_name not in heter_block.vars: + var = program.global_block().vars[var_name] + if var.persistable: + heter_program.global_block()._clone_variable( + var, force_persistable=False) + else: + heter_block._clone_variable(var, force_persistable=False) + + +def delete_trainer_useless_var(config, program, static_var): + static_var = list(set(static_var)) + program_useful_var_list = [] + for op in program.global_block().ops: + input_var_list, output_var_list = find_op_input_output( + program, program.global_block(), op) + op_var_list = list(set(input_var_list).union(set(output_var_list))) + program_useful_var_list = list( + set(program_useful_var_list).union(set(op_var_list))) + program_useful_var_list += static_var + program_useless_var_list = list( + set(get_vars_name_in_block(program.global_block())).difference( + set(program_useful_var_list))) + for var in program_useless_var_list: + program.global_block()._remove_var(var) + return program_useless_var_list + + +def block_append_op(program, origin_program, block, op): + + merge_ordereddict = origin_program.global_block().vars.copy() + merge_ordereddict.update(block.vars) + inputs = _get_input_map_from_op(merge_ordereddict, op) + for key, varlist in six.iteritems(inputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var.name not in program.global_block( + ).vars and var.name not in block.vars: + if var.persistable: + program.global_block()._clone_variable( + var, force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + outputs = _get_output_map_from_op(origin_program.global_block().vars, op) + for key, varlist in six.iteritems(outputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var.name not in program.global_block( + ).vars and var.name not in block.vars: + if var.persistable: + program.global_block()._clone_variable( + var, force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + if "_grad" not in op.type: + # for forward op + return block.append_op(type=op.type, + inputs=inputs, + outputs=outputs, + attrs=op.all_attrs()) + else: + # for grad op + op_desc = op.desc + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + + # append grad op + new_op_desc = block.desc.append_op() + new_op_desc.copy_from(op_desc) + new_op_desc._set_attr(op_role_attr_name, backward) + + # set device gard + if op.desc.has_attr(device_attr_name): + op_device = op_desc.attr(device_attr_name) + new_op_desc._set_attr(device_attr_name, op_device) + block._sync_with_cpp() + + +def add_vars_by_var_list(var_name_list, origin_program, program, block): + for var_name in var_name_list: + if var_name not in program.global_block( + ).vars and var_name not in block.vars: + var = origin_program.global_block().vars[var_name] + if var.persistable: + program.global_block()._clone_variable(var, + force_persistable=False) + else: + block._clone_variable(var, force_persistable=False) + + +def get_varlist_from_op_map(var_map): + var_list = [] + for key, varlist in six.iteritems(var_map): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + var_list.append(var.name) + return var_list + + +def find_ops_list_input_output(program, ops_list): + input_var_list = [] + output_var_list = [] + for op in ops_list: + inputs = _get_input_map_from_op(program.global_block().vars, op) + input_var_list += get_varlist_from_op_map(inputs) + outputs = _get_output_map_from_op(program.global_block().vars, op) + output_var_list += get_varlist_from_op_map(outputs) + + input_var_list = list(set(input_var_list)) + output_var_list = list(set(output_var_list)) + return input_var_list, output_var_list + + +def find_op_input_output(program, block, op): + input_var_list = [] + output_var_list = [] + inputs = _get_input_map_from_op(block.vars, op) + input_var_list += get_varlist_from_op_map(inputs) + outputs = _get_output_map_from_op(block.vars, op) + output_var_list += get_varlist_from_op_map(outputs) + input_var_list = list(set(input_var_list)) + output_var_list = list(set(output_var_list)) + return input_var_list, output_var_list + + +def get_vars_name_in_block(block): + vars_list = block.vars.keys() + vars_name_list = [var_name for var_name in vars_list] + return vars_name_list + + +def is_same_op(op1, op2): + if str(op1) != str(op2): + return False + return True + + +def _get_input_map_from_op(varmap, op): + """Returns a dict from op input name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.input_names: + vars = [] + for varname in op.input(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def _get_output_map_from_op(varmap, op): + """Returns a dict from op output name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.output_names: + vars = [] + for varname in op.output(key): + if varname == "@EMPTY@": + continue + if "lod_tensor_blocking_queue" in varname: + continue + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + +def delete_same_ops(block, ops): + for op in ops: + try: + for origin_op in block.ops: + if is_same_op(origin_op, op): + idx = list(block.ops).index(origin_op) + block._remove_op(idx) + break + except Exception as e: + print(e) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ufind.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ufind.py new file mode 100644 index 0000000000000000000000000000000000000000..aa63af7dcf7ac85031fb00ca4c39fb36d7e588b8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/ufind.py @@ -0,0 +1,66 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + + +class UnionFind(object): + """ Union-find data structure. + + Union-find is a data structure that keeps track of a set of elements partitioned + into a number of disjoint (non-overlapping) subsets. + + Reference: + https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + Args: + elements(list): The initialize element list. + """ + + def __init__(self, elementes=None): + self._parents = [] # index -> parent index + self._index = {} # element -> index + self._curr_idx = 0 + if not elementes: + elementes = [] + for ele in elementes: + self._parents.append(self._curr_idx) + self._index.update({ele: self._curr_idx}) + self._curr_idx += 1 + + def find(self, x): + # Find the root index of given element x, + # execute the path compress while findind the root index + if not x in self._index: + return -1 + idx = self._index[x] + while idx != self._parents[idx]: + t = self._parents[idx] + self._parents[idx] = self._parents[t] + idx = t + return idx + + def union(self, x, y): + # Union two given element + x_root = self.find(x) + y_root = self.find(y) + + if x_root == y_root: + return + self._parents[x_root] = y_root + + def is_connected(self, x, y): + # If two given elements have the same root index, + # then they are connected. + return self.find(x) == self.find(y) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/vars_metatools.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/vars_metatools.py new file mode 100644 index 0000000000000000000000000000000000000000..f852c1a0311d4cf2b94d4587f8c4b818d2427553 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/ir/vars_metatools.py @@ -0,0 +1,199 @@ +# Copyright (c) 2018 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. +from __future__ import print_function +from functools import reduce + +from paddle.fluid.framework import Variable +from paddle.fluid import core + +dtype_to_size = { + core.VarDesc.VarType.FP16: 2, + core.VarDesc.VarType.FP32: 4, + core.VarDesc.VarType.FP64: 8, + core.VarDesc.VarType.INT16: 2, + core.VarDesc.VarType.INT32: 4, + core.VarDesc.VarType.INT64: 8, + core.VarDesc.VarType.BOOL: 1, + core.VarDesc.VarType.UINT8: 1, +} + + +class VarBlock: + + def __init__(self, varname, offset, size): + self.varname = varname + # NOTE: real offset is offset * size + self.offset = offset + self.size = size + + def __str__(self): + return "%s:%d:%d" % (self.varname, self.offset, self.size) + + +def create_var_struct(var): + if var.type == core.VarDesc.VarType.SELECTED_ROWS: + lod_level = None + elif var.type == core.VarDesc.VarType.LOD_TENSOR: + lod_level = var.lod_level + else: + raise ValueError("can only support SELECTED_ROWS/LOD_TENSOR now") + + return VarStruct(var.name, var.shape, var.dtype, var.type, lod_level, + var.persistable) + + +class VarStruct(object): + """ + record part properties of a Variable in python. + """ + + def __init__(self, name, shape, dtype, type, lod_level, persistable): + self.name = name + self.shape = shape + self.dtype = dtype + self.type = type + self.lod_level = lod_level + self.persistable = persistable + self.m_size = 1 + self.m_size = reduce(lambda x, y: x * y, shape) + self.m_size *= dtype_to_size[dtype] + + def __str__(self): + return "N: {}, S: {}, D: {}, T: {}, LL: {}, P: {}, M: {}".format( + self.name, self.shape, self.dtype, self.type, self.lod_level, + self.persistable, self.m_size) + + +class VarDistributed(object): + """ + a class to record the var distributed on parameter servers. + the class will record the relationship between origin var and slice var. + the slice var's properties, such as type/shape/offset/endpoint. + """ + + def __init__(self, + origin_var, + slice_var, + is_slice=None, + block_id=None, + offset=None, + vtype=None, + endpoint=None): + """ + Args: + origin_var(Variable|VarStruct): origin var properties + slice_var(Variable|VarStruct): slice var properties + is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. + block_id(int|None): the number about the slice var. + offset(int|None): if the slice var is sliced, offset is the numel before the var. + vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. + endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" + """ + + if isinstance(origin_var, Variable): + self.origin = create_var_struct(origin_var) + else: + self.origin = origin_var + + if isinstance(slice_var, Variable): + self.slice = create_var_struct(slice_var) + else: + self.slice = slice_var + + if self.equal(self.origin, self.slice): + self.is_slice = False + self.block_id = 0 + self.offset = 0 + else: + self.is_slice = True + self.block_id = 0 + self.offset = 0 + + if is_slice is not None: + self.is_slice = is_slice + if block_id is not None: + self.block_id = block_id + if offset is not None: + self.offset = offset + + self.vtype = vtype + self.endpoint = endpoint + + @staticmethod + def equal(var1, var2): + """ + the two var is equal or not. + Returns: + bool: equal will return True else False + """ + assert isinstance(var1, VarStruct) and isinstance(var2, VarStruct) + + return var1.name == var2.name and \ + var1.type == var2.type and \ + var1.shape == var2.shape and \ + var1.dtype == var2.dtype and \ + var1.lod_level == var2.lod_level and \ + var1.persistable == var2.persistable + + def __str__(self): + origin_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})". \ + format(i="{", e="}", name=self.origin.name, type=self.origin.type, + shape=self.origin.shape, dtype=self.origin.dtype) + + slice_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})" \ + ".slice({is_slice}).block({block_id}).offset({offset})". \ + format(i="{", e="}", name=self.slice.name, type=self.slice.type, + shape=self.slice.shape, dtype=self.slice.dtype, + is_slice=self.is_slice, block_id=self.block_id, offset=self.offset) + + return "var owned: {}, origin var: ( {} ), slice var: ( {} ), endpoint: {} ".format( + self.vtype, origin_var_str, slice_var_str, self.endpoint) + + +class VarsDistributed(object): + """ + a gather about VarDistributed with many methods to find distributed vars. + through the class, we can get overview about the distributed parameters on parameter servers. + this class may centralized and convenient for developer to manage and get variable's distribute. + other module can also use this to find variables such io.py. + """ + + def __init__(self): + self.distributed_vars = [] + + def add_distributed_var(self, + origin_var, + slice_var, + is_slice=None, + block_id=None, + offset=None, + vtype=None, + endpoint=None): + """ + add distributed var in this. + + Args: + origin_var(Variable|VarStruct): origin var properties + slice_var(Variable|VarStruct): slice var properties + is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. + block_id(int|None): the number about the slice var. + offset(int|None): if the slice var is sliced, offset is the numel before the var. + vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. + endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" + Returns: + None + """ + self.distributed_vars.append( + VarDistributed(origin_var, slice_var, is_slice, block_id, offset, + vtype, endpoint)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/mode.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/mode.py new file mode 100644 index 0000000000000000000000000000000000000000..0733f9b8a23e42f14817b603f0ca3a3d02b132bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/mode.py @@ -0,0 +1,28 @@ +# 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. + + +class PSMode: + """ + There are various mode for fleet, each of them is designed for different model. + """ + TRANSPILER = 1 + PSLIB = 2 + + +class DistributedMode: + SYNC = 0 + ASYNC = 1 + HALF_ASYNC = 2 + GEO = 3 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d625d47f30901527d34e9138ab0b42981fb7d8f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/__init__.py @@ -0,0 +1,1173 @@ +# 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 +"""Defination of PSLib.""" + +import os +import sys +from .optimizer_factory import * +from google.protobuf import text_format +import paddle.fluid as fluid +from paddle.fluid.framework import Program + +from paddle.fluid.incubate.fleet.base.fleet_base import Fleet +from paddle.fluid.incubate.fleet.base.mode import Mode +from paddle.fluid.incubate.fleet.base.fleet_base import DistributedOptimizer +from paddle.fluid.incubate.fleet.base.role_maker import MPISymetricRoleMaker +from paddle.fluid.incubate.fleet.base.role_maker import HeterRoleMaker + + +class PSLib(Fleet): + """PSLib class.""" + + def __init__(self): + super(PSLib, self).__init__(Mode.PSLIB) + self._opt_info = None + self._local_ip = 0 + self._fleet_ptr = None + self._main_programs = [] + self._scopes = [] + self._client2client_request_timeout_ms = 500000 + self._client2client_connect_timeout_ms = 10000 + self._client2client_max_retry = 3 + + def init(self, role_maker=None): + if role_maker is None: + role_maker = MPISymetricRoleMaker() + super(PSLib, self).init(role_maker) + self._fleet_ptr = fluid.core.Fleet() + self._heter_ptr = None + if isinstance(role_maker, HeterRoleMaker): + self._heter_ptr = fluid.core.Heter() + + def _set_client_communication_config(self, request_timeout_ms, + connect_timeout_ms, max_retry): + self._client2client_request_timeout_ms = request_timeout_ms + self._client2client_connect_timeout_ms = connect_timeout_ms + self._client2client_max_retry = max_retry + + def set_pull_local_thread_num(self, thread_num): + self._fleet_ptr.set_pull_local_thread_num(thread_num) + + def init_worker(self): + """ + init_worker(): will be called by user. When a user knows current process is_server(), he/she + should call init_worker() to initialize global information about worker and connect + worker with pserver. You should run startup program before init_worker. + Args: + executor(Executor): The executor to run for init server. + programs(Program|None): The program that need to run. + """ + + if len(self._main_programs) == 0: + raise ValueError( + "You should run DistributedOptimizer.minimize() first") + + if self._opt_info: + if "fleet_desc" in self._opt_info: + self._dist_desc_str = text_format.MessageToString( + self._opt_info["fleet_desc"]) + self._dist_desc = self._opt_info["fleet_desc"] + else: + raise Exception( + "You should run DistributedOptimizer.minimize() first") + # barrier_all for init_server, wait for server starts + if isinstance(self._role_maker, HeterRoleMaker): + if self._role_maker.is_xpu(): + local_endpoint = self._role_maker.get_local_endpoint() + local_endpoint = local_endpoint.split(":") + self._heter_ptr.start_xpu_service(str(local_endpoint[0]), + int(local_endpoint[1])) + self._role_maker._barrier_all() + self.all_ips_ = self._role_maker._all_gather(self._local_ip) + # worker_index * 2 is for compatible with older versions of pslib + self._fleet_ptr.init_worker(self._dist_desc_str, self.all_ips_, + self._role_maker._get_size(), + self._role_maker.worker_index() * 2) + if isinstance(self._role_maker, HeterRoleMaker): + if self._role_maker.is_worker(): + self._heter_ptr.set_xpu_list( + self._role_maker._xpu_endpoints) + self._heter_ptr.create_client2xpu_connection() + # barrier_all for init_worker + self._role_maker._barrier_all() + # prepare for client to client communication + if self._role_maker.is_worker(): + info = self._fleet_ptr.get_clients_info() + print("Client Info: {}".format(info)) + all_info = self._role_maker._worker_gather(info[0]) + print("All Client Info: {}".format(all_info)) + self._fleet_ptr.gather_clients(all_info) + self._fleet_ptr.set_client2client_config( + self._client2client_request_timeout_ms, + self._client2client_connect_timeout_ms, + self._client2client_max_retry) + self._fleet_ptr.create_client2client_connection() + # barrier for init model + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + tables = [] + for tp in self._dist_desc.trainer_param: + for i in tp.dense_table: + tables.append(i) + for prog, scope in zip(self._main_programs, self._scopes): + prog_id = str(id(prog)) + prog_conf = self._opt_info['program_configs'][prog_id] + prog_tables = {} + for key in prog_conf: + if "dense" not in key: + continue + for table_id in prog_conf[key]: + prog_tables[int(table_id)] = 0 + for table in tables: + if int(table.table_id) not in prog_tables: + continue + var_name_list = [] + for i in range(0, len(table.dense_variable_name)): + var_name = table.dense_variable_name[i] + if scope.find_var(var_name) is None: + raise ValueError( + "var " + var_name + + " not found in scope, " + + "you should run startup program first") + var_name_list.append(var_name) + if not self._opt_info["use_ps_gpu"]: + self._fleet_ptr.init_model(scope, + int(table.table_id), + var_name_list) + # barrier for init model done + self._role_maker._barrier_worker() + else: + raise NameError( + "You should run DistributedOptimizer.minimize() first") + + def init_server(self, model_dir=None, **kwargs): + """ + init_server() will be called by user. It will load model from model_dir. + Args: + model_dir(str): load model path, can be local or hdfs/afs path. + kwargs: user-defined attributes, currently support following: + model(int): load model mode. + 0 is for load whole model, + 1 is for load delta model (load diff), + default is 0. + Example: + >>> fleet.init_server("/you/path/to/model", mode = 0) + """ + mode = kwargs.get("mode", 0) + if isinstance(self._role_maker, HeterRoleMaker): + self._role_maker._barrier_xpu() + if self._role_maker.is_first_xpu(): + self._fleet_ptr.load_model(model_dir, mode) + self._role_maker._barrier_xpu() + else: + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.load_model(model_dir, mode) + self._role_maker._barrier_worker() + + def run_server(self): + """ + init_pserver(): will be called by user. When a user knows current process is_worker(), he/she + should call init_pserver() to initialize global information about parameter server + """ + if self._opt_info: + if "fleet_desc" in self._opt_info: + self._dist_desc_str = text_format.MessageToString( + self._opt_info["fleet_desc"]) + self._dist_desc = self._opt_info["fleet_desc"] + else: + raise Exception( + "You should run DistributedOptimizer.minimize() first") + # server_index * 2 is for compatible with older versions of pslib + self._fleet_ptr.init_server(self._dist_desc_str, + self._role_maker.server_index() * 2) + if isinstance(self._role_maker, MPISymetricRoleMaker): + self._local_ip = self._fleet_ptr.run_server() + else: + local_endpoint = self._role_maker.get_local_endpoint() + local_endpoint = local_endpoint.split(":") + self._local_ip = self._fleet_ptr.run_server( + str(local_endpoint[0]), int(local_endpoint[1])) + + # barrier_all for init_server + self._role_maker._barrier_all() + self.all_ips_ = self._role_maker._all_gather(self._local_ip) + + self._fleet_ptr.gather_servers(self.all_ips_, + self._role_maker._get_size()) + # barrier_all for init_worker, wait all workers start + self._role_maker._barrier_all() + else: + raise Exception( + "You should run DistributedOptimizer.minimize() first") + + def end_pass(self, scope): + if self._role_maker.worker_index() < self._role_maker.xpu_num(): + self._heter_ptr.end_pass(scope, self._role_maker.worker_index()) + self._heter_ptr.stop_xpu_service(self._role_maker.worker_index()) + + def train_from_dataset(self, + executor, + program=None, + dataset=None, + scope=None, + thread=0, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + """ + + """ + + if self._role_maker.is_worker(): + self._role_maker._barrier_heter() + executor.train_from_dataset(program, dataset, scope, thread, debug, + fetch_list, fetch_info, print_period, + fetch_handler) + + def start_heter_trainer(self, + executor, + program=None, + scope=None, + debug=False, + fetch_list=None, + fetch_info=None, + print_period=100, + fetch_handler=None): + """ + + """ + + trainer_instance = executor.start_heter_trainer(program, scope, debug, + fetch_list, fetch_info, + print_period, + fetch_handler) + if self._role_maker.is_xpu(): + print("barrier heter") + self._role_maker._barrier_heter() + print("barrier heter") + executor._default_executor.release_trainer(trainer_instance) + + def stop_worker(self): + """ + stop(): will be called after a user finishes his/her training task. Fleet instance will be + destroyed when stop() is called. + """ + self._role_maker._barrier_worker() + # all worker should be finalize first + if self._role_maker.is_worker(): + self._fleet_ptr.finalize_worker() + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.stop_server() + if self._heter_ptr: + self._heter_ptr.stop_xpu_service() + self._role_maker._barrier_worker() + self._role_maker._barrier_all() + self._role_maker._finalize() + + def distributed_optimizer(self, optimizer, strategy={}): + """ + distributed_optimizer + Args: + optimizer(Optimizer): optimizer + strategy(dict): strategy + Examples: + .. code-block:: python + fleet.distributed_optimizer(optimizer) + Returns: + optimizer(DownpourOptimizer): downpour optimizer + """ + self._optimizer = DownpourOptimizer(optimizer, strategy) + return self._optimizer + + def save_inference_model(self, + executor, + dirname, + feeded_var_names=None, + target_vars=None, + main_program=None, + export_for_deployment=True): + """ + save pserver model called from a worker + Args: + executor(Executor): fluid executor + dirname(str): save model path + feeded_var_names(list): default None + target_vars(list): default None + main_program(Program): default None + export_for_deployment(bool): default None + Examples: + .. code-block:: python + fleet.save_inference_model(dirname="hdfs:/my/path") + """ + self._fleet_ptr.save_model(dirname, 0) + + def print_table_stat(self, table_id): + """ + print stat info of table_id, + format: tableid, feasign size, mf size + Args: + table_id(int): the id of table + Example: + .. code-block:: python + fleet.print_table_stat(0) + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.print_table_stat(table_id) + self._role_maker._barrier_worker() + + def set_file_num_one_shard(self, table_id, file_num): + """ + set file_num in one shard + Args: + table_id(int): the id of table + file_num(int): file num in one shard + Example: + .. code-block:: python + fleet.set_file_num_one_shard(0, 5) + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.set_file_num_one_shard(table_id, file_num) + self._role_maker._barrier_worker() + + def save_persistables(self, executor, dirname, main_program=None, **kwargs): + """ + save presistable parameters, + when using fleet, it will save sparse and dense feature + Args: + executor(Executor): fluid executor + dirname(str): save path. It can be hdfs/afs path or local path + main_program(Program): fluid program, default None + kwargs: use define property, current support following + mode(int): 0 means save all pserver model, + 1 means save delta pserver model (save diff), + 2 means save xbox base, + 3 means save batch model. + Example: + .. code-block:: python + fleet.save_persistables(dirname="/you/path/to/model", mode = 0) + """ + mode = kwargs.get("mode", 0) + self._fleet_ptr.client_flush() + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.save_model(dirname, mode) + self._role_maker._barrier_worker() + + def save_model_with_whitelist(self, + executor, + dirname, + whitelist_path, + main_program=None, + **kwargs): + """ + save whitelist, mode is consistent with fleet.save_persistables, + when using fleet, it will save sparse and dense feature + + Args: + executor(Executor): fluid executor + dirname(str): save path. It can be hdfs/afs path or local path + main_program(Program): fluid program, default None + kwargs: use define property, current support following + mode(int): 0 means save all pserver model, + 1 means save delta pserver model (save diff), + 2 means save xbox base, + 3 means save batch model. + + Example: + .. code-block:: python + + fleet.save_persistables(dirname="/you/path/to/model", mode = 0) + + """ + mode = kwargs.get("mode", 0) + table_id = kwargs.get("table_id", 0) + self._fleet_ptr.client_flush() + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.save_model_with_whitelist(table_id, dirname, mode, + whitelist_path) + self._role_maker._barrier_worker() + + def save_multi_table_one_path(self, table_ids, model_dir, **kwargs): + """ + save pslib multi sparse table in one path. + Args: + table_ids(list): table ids + model_dir(str): if you use hdfs, model_dir should starts with + 'hdfs:', otherwise means local dir + kwargs(dict): user-defined properties. + mode(int): the modes illustrated above, default 0 + prefix(str): the parts to save can have prefix, + for example, part-prefix-000-00000 + Examples: + .. code-block:: python + fleet.save_multi_table_one_path("[0, 1]", "afs:/user/path/") + """ + mode = kwargs.get("mode", 0) + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.save_multi_table_one_path(table_ids, model_dir, + mode) + self._role_maker._barrier_worker() + + def save_cache_model(self, executor, dirname, main_program=None, **kwargs): + """ + save sparse cache table, + when using fleet, it will save sparse cache table + Args: + executor(Executor): fluid executor + dirname(str): save path. It can be hdfs/afs path or local path + main_program(Program): fluid program, default None + kwargs: use define property, current support following + mode(int): define for feature extension in the future, + currently no use, will pass a default value 0 + table_id(int): which table to save cache, default is 0 + Returns: + feasign_num(int): cache feasign num + Example: + .. code-block:: python + fleet.save_cache_model(None, dirname="/you/path/to/model", mode = 0) + """ + mode = kwargs.get("mode", 0) + table_id = kwargs.get("table_id", 0) + self._fleet_ptr.client_flush() + self._role_maker._barrier_worker() + cache_threshold = 0.0 + + if self._role_maker.is_first_worker(): + cache_threshold = self._fleet_ptr.get_cache_threshold(table_id) + #check cache threshold right or not + self._role_maker._barrier_worker() + + if self._role_maker.is_first_worker(): + self._fleet_ptr.cache_shuffle(table_id, dirname, mode, + cache_threshold) + + self._role_maker._barrier_worker() + + feasign_num = -1 + if self._role_maker.is_first_worker(): + feasign_num = self._fleet_ptr.save_cache(table_id, dirname, mode) + + self._role_maker._barrier_worker() + return feasign_num + + def shrink_sparse_table(self): + """ + shrink cvm of all sparse embedding in pserver, the decay rate + is defined as "show_click_decay_rate" in fleet_desc.prototxt + Example: + >>> fleet.shrink_sparse_table() + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + tables = [] + for tp in self._opt_info["fleet_desc"].trainer_param: + for i in tp.sparse_table: + tables.append(i.table_id) + for i in list(set(tables)): + self._fleet_ptr.shrink_sparse_table(i) + self._role_maker._barrier_worker() + + def shrink_dense_table(self, decay, emb_dim=11, scope=None, table_id=None): + """ + shrink batch_sum in pserver by multiplying by decay + Args: + decay(float): the decay rate, usually range in (0, 1) + emb_dim(int): one element's length in datanorm layer + scope(Scope): Scope object, default is fluid.global_scope() + table_id(int): table id of shrinking dense table. None means shrink all, + you should specify it when using multiple scopes, + default is None. + Example: + >>> fleet.shrink_dense_table(0.98, 11, myscope1, 1) + >>> fleet.shrink_dense_table(0.98, 11, myscope1, 2) + >>> fleet.shrink_dense_table(0.98, 11, myscope2, 3) + """ + if scope is None: + scope = fluid.global_scope() + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + for tp in self._opt_info["fleet_desc"].trainer_param: + for i in tp.dense_table: + if table_id is not None and table_id != i.table_id: + continue + var_list = [var for var in i.dense_variable_name] + skip = False + for var in var_list: + if scope.find_var(var) is None: + skip = True + break + if skip: + continue + self._fleet_ptr.shrink_dense_table(i.table_id, scope, + var_list, decay, emb_dim) + self._role_maker._barrier_worker() + + def clear_one_table(self, table_id): + """ + clear_one_table() will be called by user. It will clear one table. + Args: + table_id(int): table id + Examples: + .. code-block:: python + fleet.clear_one_table(0) + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.clear_one_table(table_id) + self._role_maker._barrier_worker() + + def clear_model(self): + """ + clear_model() will be called by user. It will clear sparse model. + Examples: + .. code-block:: python + fleet.clear_model() + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.clear_model() + self._role_maker._barrier_worker() + + def load_pslib_whitelist(self, table_id, model_path, **kwargs): + """ + load pslib model for one table with whitelist + + Args: + table_id(int): load table id + model_path(str): load model path, can be local or hdfs/afs path + kwargs(dict): user defined params, currently support following: + only for load pslib model for one table: + mode(int): load model mode. 0 is for load whole model, 1 is + for load delta model (load diff), default is 0. + only for load params from paddle model: + scope(Scope): Scope object + model_proto_file(str): path of program desc proto binary + file, can be local or hdfs/afs file + var_names(list): var name list + load_combine(bool): load from a file or split param files + default False. + + Examples: + .. code-block:: python + + # load pslib model for one table + fleet.load_one_table(0, "hdfs:/my_fleet_model/20190714/0/") + fleet.load_one_table(1, "hdfs:/xx/xxx", mode = 0) + + # load params from paddle model + fleet.load_one_table(2, "hdfs:/my_paddle_model/", + scope = my_scope, + model_proto_file = "./my_program.bin", + load_combine = False) + + # below is how to save proto binary file + with open("my_program.bin", "wb") as fout: + my_program = fluid.default_main_program() + fout.write(my_program.desc.serialize_to_string()) + + """ + self._role_maker._barrier_worker() + mode = kwargs.get("mode", 0) + if self._role_maker.is_first_worker(): + self._fleet_ptr.load_table_with_whitelist(table_id, model_path, + mode) + self._role_maker._barrier_worker() + + def load_one_table(self, table_id, model_path, **kwargs): + """ + load pslib model for one table or load params from paddle model + Args: + table_id(int): load table id + model_path(str): load model path, can be local or hdfs/afs path + kwargs(dict): user defined params, currently support following: + only for load pslib model for one table: + mode(int): load model mode. 0 is for load whole model, 1 is + for load delta model (load diff), default is 0. + only for load params from paddle model: + scope(Scope): Scope object + model_proto_file(str): path of program desc proto binary + file, can be local or hdfs/afs file + var_names(list): var name list + load_combine(bool): load from a file or split param files + default False. + Examples: + .. code-block:: python + # load pslib model for one table + fleet.load_one_table(0, "hdfs:/my_fleet_model/20190714/0/") + fleet.load_one_table(1, "hdfs:/xx/xxx", mode = 0) + # load params from paddle model + fleet.load_one_table(2, "hdfs:/my_paddle_model/", + scope = my_scope, + model_proto_file = "./my_program.bin", + load_combine = False) + # below is how to save proto binary file + with open("my_program.bin", "wb") as fout: + my_program = fluid.default_main_program() + fout.write(my_program.desc.serialize_to_string()) + """ + self._role_maker._barrier_worker() + mode = kwargs.get("mode", 0) + scope = kwargs.get("scope", None) + model_proto_file = kwargs.get("model_proto_file", None) + var_names = kwargs.get("var_names", None) + load_combine = kwargs.get("load_combine", False) + self._role_maker._barrier_worker() + if scope is not None and model_proto_file is not None: + self._load_one_table_from_paddle_model(scope, table_id, model_path, + model_proto_file, var_names, + load_combine) + elif self._role_maker.is_first_worker(): + self._fleet_ptr.load_model_one_table(table_id, model_path, mode) + self._role_maker._barrier_worker() + + def _load_one_table_from_paddle_model(self, + scope, + table_id, + model_path, + model_proto_file, + var_names=None, + load_combine=False): + """ + load params from paddle model, and push params to pserver + Args: + scope(Scope): Scope object + table_id(int): the id of table to load + model_path(str): path of paddle model, can be local or hdfs/afs file + model_proto_file(str): path of program desc proto binary file, + can be local or hdfs/afs file + var_names(list): load var names + load_combine(bool): load from a file or split param files + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + # get fs config from fleet_desc + fs_name = self._opt_info["fleet_desc"].fs_client_param.uri + fs_ugi = self._opt_info["fleet_desc"].fs_client_param.user + "," + \ + self._opt_info["fleet_desc"].fs_client_param.passwd + hadoop_bin = self._opt_info["fleet_desc"].fs_client_param.hadoop_bin + # download model_path if it's hdfs/afs + if model_path.startswith("hdfs:") or model_path.startswith("afs:"): + dest = "./model_for_load_table_%s" % table_id + cmd = hadoop_bin + " fs -D fs.default.name=" + fs_name + \ + " -D hadoop.job.ugi=" + fs_ugi + " -get " + model_path + \ + " " + dest + ret = os.system(cmd) + if ret != 0: + raise RuntimeError("download model failed") + model_path = dest + # download model_proto_file if it's hdfs/afs + if model_proto_file.startswith("hdfs:") or \ + model_proto_file.startswith("afs:"): + dest = "./model_proto_file_for_load_table_%s" % table_id + cmd = hadoop_bin + " fs -D fs.default.name=" + fs_name + \ + " -D hadoop.job.ugi=" + fs_ugi + " -get " + \ + model_proto_file + " " + dest + ret = os.system(cmd) + if ret != 0: + raise RuntimeError("download model proto file failed") + model_proto_file = dest + for tp in self._opt_info["fleet_desc"].trainer_param: + for i in tp.dense_table: + if table_id is not None and table_id != i.table_id: + continue + table_var_names = [var for var in i.dense_variable_name] + skip = False + for var in table_var_names: + if scope.find_var(var) is None: + skip = True + break + if skip: + continue + self._fleet_ptr.load_from_paddle_model( + scope, table_id, var_names, model_path, + model_proto_file, table_var_names, load_combine) + self._role_maker._barrier_worker() + + def confirm(self): + """ + confirm all the updated params in current pass + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.confirm() + self._role_maker._barrier_worker() + + def revert(self): + """ + revert all the updated params in current pass + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.revert() + self._role_maker._barrier_worker() + + def load_model(self, model_dir=None, **kwargs): + """ + load pslib model, there are at least 4 modes, these modes are the same + in load one table/save model/save one table: + 0: load checkpoint model + 1: load delta model (delta means diff, it's usually for online predict) + 2: load base model (base model filters some feasigns in checkpoint, it's + usually for online predict) + 3: load batch model (do some statistic works in checkpoint, such as + calculate unseen days of each feasign) + Args: + model_dir(str): if you use hdfs, model_dir should starts with + 'hdfs:', otherwise means local dir + kwargs(dict): user-defined properties. + mode(int): the modes illustrated above, default 0 + Examples: + .. code-block:: python + fleet.load_model("afs:/user/path/") + """ + mode = kwargs.get("mode", 0) + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.load_model(model_dir, mode) + self._role_maker._barrier_worker() + + def save_model(self, model_dir=None, **kwargs): + """ + save pslib model, the modes are same with load model. + Args: + model_dir(str): if you use hdfs, model_dir should starts with + 'hdfs:', otherwise means local dir + kwargs(dict): user-defined properties. + mode(int): the modes illustrated above, default 0 + Examples: + .. code-block:: python + fleet.save_model("afs:/user/path/") + """ + mode = kwargs.get("mode", 0) + prefix = kwargs.get("prefix", None) + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.save_model(model_dir, mode) + self._role_maker._barrier_worker() + + def save_one_table(self, table_id, model_dir, **kwargs): + """ + save pslib model's one table, the modes are same with load model. + Args: + table_id(int): table id + model_dir(str): if you use hdfs, model_dir should starts with + 'hdfs:', otherwise means local dir + kwargs(dict): user-defined properties. + mode(int): the modes illustrated above, default 0 + prefix(str): the parts to save can have prefix, + for example, part-prefix-000-00000 + Examples: + .. code-block:: python + fleet.save_one_table("afs:/user/path/") + """ + mode = kwargs.get("mode", 0) + prefix = kwargs.get("prefix", None) + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + if prefix is not None: + self._fleet_ptr.save_model_one_table_with_prefix( + table_id, model_dir, mode, prefix) + else: + self._fleet_ptr.save_model_one_table(table_id, model_dir, mode) + self._role_maker._barrier_worker() + + def set_date(self, table_id, date): + """ + set_date, eg, 20210918 + """ + self._role_maker._barrier_worker() + if self._role_maker.is_first_worker(): + self._fleet_ptr.set_date(table_id, str(date)) + self._role_maker._barrier_worker() + + def _set_opt_info(self, opt_info): + """ + this function saves the result from DistributedOptimizer.minimize() + """ + self._opt_info = opt_info + + +fleet = PSLib() + + +def _prepare_params(input, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32'): + """ + preprocess params, this interface is not for users. + Args: + input(Variable|list of Variable): Input is a Tensor Variable + size(list of int): the embedding dim + is_sparse(bool): whether input is sparse ids + is_distributed(bool): whether in distributed mode + padding_idx(int): padding idx of input + param_attr(ParamAttr): To specify the weight parameter property + dtype(str): data type of output + """ + if param_attr is None: + raise ValueError("param_attr must be set") + name = param_attr.name + if name is None: + raise ValueError("embedding name must be set") + if not isinstance(size, list) and not isinstance(size, tuple): + raise ValueError("embedding size must be list or tuple") + size = size[-1] + global FLEET_GLOBAL_DICT + FLEET_GLOBAL_DICT["enable"] = True + d_table = FLEET_GLOBAL_DICT["emb_to_table"] + d_accessor = FLEET_GLOBAL_DICT["emb_to_accessor"] + d_size = FLEET_GLOBAL_DICT["emb_to_size"] + + # check embedding size + if d_size.get(name) is None: + d_size[name] = size + elif d_size[name] != size: + raise ValueError("embedding size error: %s vs %s" % + (size, d_size[name])) + + # check embedding accessor + accessor = FLEET_GLOBAL_DICT["cur_accessor"] + if d_accessor.get(name) is None: + d_accessor[name] = accessor + elif d_accessor[name] != accessor: + raise ValueError("embedding size error: %s vs %s" % + (d_accessor[name], accessor)) + + # check embedding table id + if d_table.get(name) is None: + d_table[name] = FLEET_GLOBAL_DICT["cur_sparse_id"] + FLEET_GLOBAL_DICT["cur_sparse_id"] += 1 + + # check other params + if not is_sparse: + raise ValueError("is_sparse must be True") + elif not is_distributed: + raise ValueError("is_distributed must be True") + elif dtype != "float32": + raise ValueError("dtype must be float32") + + +def _fleet_embedding(input, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32'): + """ + add fleet embedding, this interface is not for users. + Args: + input(Variable|list of Variable): Input is a Tensor Variable + size(list of int): the embedding dim + is_sparse(bool): whether input is sparse ids + is_distributed(bool): whether in distributed mode + padding_idx(int): padding idx of input + param_attr(ParamAttr): To specify the weight parameter property + dtype(str): data type of output + """ + # check and set params + _prepare_params(input, size, is_sparse, is_distributed, padding_idx, + param_attr, dtype) + name = param_attr.name + size = size[-1] + if padding_idx is None: + padding_idx = 0 + global FLEET_GLOBAL_DICT + return fluid.layers.nn._pull_sparse( + input=input, + size=size, + table_id=FLEET_GLOBAL_DICT["emb_to_table"][name], + accessor_class=FLEET_GLOBAL_DICT["emb_to_accessor"][name], + name=name, + ctr_label_name=FLEET_GLOBAL_DICT["click_name"], + padding_id=padding_idx, + dtype=dtype, + scale_sparse_grad=FLEET_GLOBAL_DICT["scale_sparse_grad"]) + + +def _fleet_embedding_v2(input, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32'): + """ + add fleet embedding v2, this interface is not for users. + Args: + input(Variable|list of Variable): Input is a Tensor Variable + size(list of int): the embedding dim + is_sparse(bool): whether input is sparse ids + is_distributed(bool): whether in distributed mode + padding_idx(int): padding idx of input + param_attr(ParamAttr): To specify the weight parameter property + dtype(str): data type of output + """ + # check and set params + _prepare_params(input, size, is_sparse, is_distributed, padding_idx, + param_attr, dtype) + name = param_attr.name + size = size[-1] + if padding_idx is None: + padding_idx = 0 + + return fluid.layers.nn._pull_sparse_v2( + input=input, + size=size, + table_id=FLEET_GLOBAL_DICT["emb_to_table"][name], + accessor_class=FLEET_GLOBAL_DICT["emb_to_accessor"][name], + name=name, + ctr_label_name=FLEET_GLOBAL_DICT["click_name"], + padding_id=padding_idx, + dtype=dtype, + scale_sparse_grad=FLEET_GLOBAL_DICT["scale_sparse_grad"]) + + +class fleet_embedding(object): + """ + fleet embedding class, it is used as a wrapper + Example: + .. code-block:: python + with fleet_embedding(click_name=label.name): + emb = fluid.layers.embedding( + input=var, + size=[-1, 11], + is_sparse=True, + is_distributed=True, + param_attr=fluid.ParamAttr(name="embedding")) + """ + + def __init__(self, click_name, scale_sparse_grad=True): + """Init.""" + self.origin_emb = fluid.layers.embedding + self.origin_emb_v2 = fluid.embedding + # if user uses cvm layer after embedding, click_name can be None + self.click_name = "" if click_name is None else click_name + self.scale_sparse_grad = scale_sparse_grad + # it's default value, will be modified in minimize + self.accessor = "DownpourCtrAccessor" + + def __enter__(self): + """Enter.""" + fluid.layers.embedding = _fleet_embedding + fluid.embedding = _fleet_embedding_v2 + FLEET_GLOBAL_DICT["cur_accessor"] = self.accessor + FLEET_GLOBAL_DICT["click_name"] = self.click_name + FLEET_GLOBAL_DICT["scale_sparse_grad"] = self.scale_sparse_grad + + def __exit__(self, exc_type, exc_val, exc_tb): + """Exit.""" + fluid.layers.embedding = self.origin_emb + fluid.embedding = self.origin_emb_v2 + FLEET_GLOBAL_DICT["cur_accessor"] = "" + FLEET_GLOBAL_DICT["click_name"] = "" + FLEET_GLOBAL_DICT["scale_sparse_grad"] = None + + +class DownpourOptimizer(DistributedOptimizer): + """ + DistributedOptimizer is a wrapper for paddle.fluid.optimizer + A user should pass a paddle.fluid.optimizer to DistributedOptimizer + minimize() function is implemented. + DistributedOptimizer is the starting point for a user who wants to + run distributed training. The optimized information will be stored in + Fleet() instance who holds the global information about current distributed + training. + Args: + optimizer(Optimizer): subclass of Optimizer. + strategy(any): config for DownpourOptimizer. + Returns: + None + """ + + def __init__(self, optimizer, strategy=None): + super(DownpourOptimizer, self).__init__(optimizer, strategy) + + self._optimizer = optimizer + self._optimizer_name = "Distributed%s" % optimizer.type.capitalize() + if optimizer.type != "adam": + print( + "Currently, distributed optimizer only support Adam" + "Will config built-in adam for you." + "We will support more functions in DistributedOptimizer", + sys.stderr) + self._optimizer_name = "DistributedAdam" + + self._distributed_optimizer = globals()[self._optimizer_name](optimizer) + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + Currently, backward function can not be called through DistributedOptimizer + """ + raise NotImplementedError() + + def _remove_collective_ops(self, program, name): + """ + colective init op should call once, so remove other call. + """ + block = program.global_block() + for ids, op in list(enumerate(block.ops)): + if op.type == name: + block._remove_op(ids) + return + + def apply_gradients(self, params_grads): + """ + Currently, apply_gradients function can not be called through DistributedOptimizer + """ + raise NotImplementedError() + + def get_dist_env(self): + trainer_id = int(os.getenv('PADDLE_TRAINER_ID', '0')) + trainer_endpoints = '' + current_endpoint = '' + num_trainers = 0 + if os.getenv('PADDLE_TRAINER_ENDPOINTS') and os.getenv( + 'PADDLE_CURRENT_ENDPOINT'): + trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS') + current_endpoint = os.getenv('PADDLE_CURRENT_ENDPOINT') + num_trainers = len(trainer_endpoints.split(',')) + + return { + 'trainer_id': trainer_id, + 'num_trainers': num_trainers, + 'current_endpoint': current_endpoint, + 'trainer_endpoints': trainer_endpoints + } + + def _remove_collective_op_for_embedding(self, loss, table_name): + """ + find multi-sparse-table + """ + table_name = [name + "@GRAD" for name in table_name] + need_remove_op_index = [] + block = loss.block.program.global_block() + collective_ops = ["c_sync_calc_stream", "c_allreduce_sum"] + for ids, op in list(enumerate(block.ops)): + if op.type in collective_ops: + if op.input("X")[0] in table_name: + need_remove_op_index.append(ids) + if op.type == "lookup_table_grad": + need_remove_op_index.append(ids) + try: + if op.output("Out")[0] in table_name: + need_remove_op_index.append(ids) + except: + pass + + need_remove_op_index.sort(reverse=True) + for index in need_remove_op_index: + block._remove_op(index) + + def minimize(self, + losses, + scopes=None, + startup_programs=None, + parameter_list=None, + no_grad_set=None, + program_mode="all_reduce"): + """ + minimize a program through loss, loss can be a list in DistributedOptimizer. + Note that in parameter server mode, a worker will not get anything about optimize_os + Because optimizer algorithms run on pserver side. We will make this usable in pserver + process, but currently the optimization part is written into Fleet(). A user does not + need to care about how to startup a pserver node. + Args: + losses (Variable|Variable List): loss variable or loss variable list to run optimization. + scopes (Scope| Scope List): scope instance. + startup_programs (Program|Program List): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables to update. + no_grad_set (set|None): set of Variables should be ignored. + program_mode (str|"all_reduce"): grad action for grogram when use_ps_gpu. + Returns: + tuple: (optimize_ops, params_grads) which are, list of operators appended; + and list of (param, grad) Variables pair for optimization. + """ + + if not isinstance(losses, list): + losses = [losses] + + optimize_ops, param_grads, opt_info = \ + self._distributed_optimizer._minimize( + losses, + startup_programs, + parameter_list, + no_grad_set, + self._strategy) + opt_info["mpi_rank"] = fleet.worker_index() + opt_info["mpi_size"] = fleet.worker_num() + fleet._set_opt_info(opt_info) + + programs = [loss.block.program for loss in losses] + + if scopes is None: + scopes = [fluid.global_scope()] * len(programs) + + if len(scopes) != len(programs): + raise ValueError( + "You should make sure len(scopes) == len(programs) or set scopes None" + ) + + fleet._main_programs = programs + fleet._scopes = scopes + if opt_info["use_ps_gpu"]: + from paddle.fluid.transpiler.collective import MultiThread + # check start program + if program_mode not in [ + "all_reduce", "fuse_all_reduce", "all_gather", + "all_reduce_xpu" + ]: + raise ValueError("You should set program_mode in [ all_reduce, \ + fuse_all_reduce, all_gather, all_reduce_xpu ]") + env = self.get_dist_env() + if not isinstance(losses, list): + startup_programs = [startup_programs] + for i in range(0, len(startup_programs)): + + t = MultiThread(trans_mode=program_mode) + start_program = startup_programs[i] + main_program = programs[i] + t.transpile(startup_program=start_program, + main_program=main_program, + rank=env["trainer_id"], + endpoints=env["trainer_endpoints"], + current_endpoint=env['current_endpoint'], + wait_port=False) + if i > 0: + self._remove_collective_ops(start_program, + "c_comm_init_all") + for i in range(0, len(losses)): + loss = losses[i] + embedding_table = self._distributed_optimizer._find_multi_distributed_lookup_table( + [loss]) + self._remove_collective_op_for_embedding(loss, embedding_table) + + return [optimize_ops, param_grads] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/node.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/node.py new file mode 100644 index 0000000000000000000000000000000000000000..308261cea0676d7efc621397bfbe54b645cbe638 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/node.py @@ -0,0 +1,629 @@ +# Copyright (c) 2018 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 +"""Defination of Server and Worker.""" + +from . import ps_pb2 as pslib +# NOTE: reduce removed in fuctools in python3 +from functools import reduce + + +class Server(object): + """ + A Server basic class + it's a base class, does not have implementation + """ + + def __init__(self): + pass + + +class Worker(object): + """ + A Worker basic class. + it's a base class, does not have implementation + """ + + def __init__(self): + pass + + +class DownpourServer(Server): + """ + DownpourServer class is used to generate server program_desc + Args: + server: it is pslib.ServerParameter() + Examples: + server = DownpourServer() + """ + + def __init__(self): + self._server = pslib.ServerParameter() + self._server.downpour_server_param.service_param.server_class = "DownpourBrpcPsServer" + self._server.downpour_server_param.service_param.client_class = "DownpourBrpcPsClient" + self._server.downpour_server_param.service_param.service_class = "DownpourPsService" + self._server.downpour_server_param.service_param.start_server_port = 0 + self._server.downpour_server_param.service_param.server_thread_num = 12 + + def add_sparse_table(self, table_id, strategy): + """ + Args: + table_id(int): id of sparse params table + strategy(dict): the config dict. + Returns: + return None + """ + + for table in self._server.downpour_server_param.downpour_table_param: + if table.table_id == table_id: + if table.type == pslib.PS_SPARSE_TABLE: + return + else: + raise ValueError("expect table %s type=%s, but actual type=%s" \ + %(table_id, pslib.PS_SPARSE_TABLE, table.type)) + if strategy is None: + strategy = dict() + table = self._server.downpour_server_param.downpour_table_param.add() + table.table_id = table_id + table.type = pslib.PS_SPARSE_TABLE + + support_sparse_key_list = ['sparse_table_class', 'sparse_compress_in_save', 'sparse_shard_num', \ + 'sparse_accessor_class', 'sparse_learning_rate', 'sparse_initial_g2sum', 'sparse_initial_range', \ + 'sparse_weight_bounds', 'sparse_embedx_dim', 'sparse_embedx_threshold', 'sparse_nonclk_coeff', \ + 'sparse_click_coeff', 'sparse_base_threshold', 'sparse_delta_threshold', 'sparse_delta_keep_days', \ + 'sparse_delete_after_unseen_days', 'sparse_show_click_decay_rate', 'sparse_delete_threshold', \ + 'sparse_converter', 'sparse_deconverter', 'sparse_enable_cache', 'sparse_cache_rate', \ + 'sparse_cache_file_num', 'sparse_beta1_decay_rate', 'sparse_beta2_decay_rate', \ + 'sparse_ada_epsilon', 'sparse_optimizer', 'sparse_ssd_unseenday_threshold', \ + 'embed_sparse_optimizer', 'embed_sparse_learning_rate', 'embed_sparse_weight_bounds', \ + 'embed_sparse_initial_range', 'embed_sparse_initial_g2sum', 'embed_sparse_beta1_decay_rate', \ + 'embed_sparse_beta2_decay_rate', 'embedx_sparse_optimizer', 'embedx_sparse_learning_rate', \ + 'embedx_sparse_weight_bounds', 'embedx_sparse_initial_range', 'embedx_sparse_initial_g2sum', \ + 'embedx_sparse_beta1_decay_rate', 'embedx_sparse_beta2_decay_rate'] + + for key in strategy: + if key not in support_sparse_key_list: + raise ValueError("strategy key '%s' not support" % (key)) + + support_table_calss = ['DownpourSparseTable', 'DownpourSparseSSDTable'] + if strategy.get('sparse_table_class') is not None: + table_class = strategy.get('sparse_table_class') + if table_class not in support_table_calss: + raise ValueError( + "support sparse_table_class: [ 'DownpourSparseTable', 'DownpourSparseSSDTable'], \ + but actual %s" % (table_class)) + else: + table_class = 'DownpourSparseTable' + + table.table_class = table_class + + if table_class == 'DownpourSparseTable' or table_class == 'DownpourSparseSSDTable': + table.enable_sparse_table_cache = strategy.get( + 'sparse_enable_cache', True) + table.sparse_table_cache_rate = strategy.get( + 'sparse_cache_rate', 0.00055) + table.sparse_table_cache_file_num = strategy.get( + 'sparse_cache_file_num', 16) + table.compress_in_save = strategy.get('sparse_compress_in_save', + True) + table.shard_num = strategy.get('sparse_shard_num', 1000) + # DownpourFeatureValueAccessor: for ctr task, has cvm, embedding and sgd info + # DownpourCtrAccessor : for ctr task, has cvm, slot, embedding and sgd info + # DownpourSparseValueAccessor : for general task, has embedding and sgd info + # DownpourCtrDoubleAccessor : for ctr task, which show clk are in double + # DownpourUnitAccessor : for ctr task, has cvm, slot, embedding and sgd info + + support_accessor_class = [ + 'DownpourFeatureValueAccessor', 'DownpourCtrAccessor', + 'DownpourCtrDymfAccessor', 'DownpourSparseValueAccessor', + 'DownpourCtrDoubleAccessor', 'DownpourUnitAccessor', + 'DownpourDoubleUnitAccessor' + ] + if strategy.get('sparse_accessor_class') is not None: + accessor_class = strategy.get('sparse_accessor_class') + if accessor_class not in support_accessor_class: + raise ValueError( + "support sparse_accessor_class: ['DownpourFeatureValueAccessor', 'DownpourCtrAccessor', 'DownpourCtrDymfAccessor', \ + 'DownpourSparseValueAccessor', 'DownpourCtrDoubleAccessor'], \ + but actual %s" % (accessor_class)) + else: + accessor_class = 'DownpourCtrAccessor' + + table.accessor.accessor_class = accessor_class + + if accessor_class == 'DownpourFeatureValueAccessor' \ + or accessor_class == 'DownpourCtrAccessor' \ + or accessor_class == 'DownpourCtrDymfAccessor' \ + or accessor_class == 'DownpourCtrDoubleAccessor': + table.accessor.sparse_sgd_param.learning_rate = strategy.get( + 'sparse_learning_rate', 0.05) + table.accessor.sparse_sgd_param.initial_g2sum = strategy.get( + 'sparse_initial_g2sum', 3) + table.accessor.sparse_sgd_param.initial_range = strategy.get( + 'sparse_initial_range', 1e-4) + if strategy.get('sparse_weight_bounds') is None: + table.accessor.sparse_sgd_param.weight_bounds.extend( + [-10, 10]) + else: + table.accessor.sparse_sgd_param.weight_bounds.extend( + strategy.get('sparse_weight_bounds')) + table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8) + table.accessor.embedx_threshold = strategy.get( + 'sparse_embedx_threshold', 10) + table.accessor.fea_dim = int(table.accessor.embedx_dim) + 3 + table.accessor.downpour_accessor_param.nonclk_coeff = strategy.get( + 'sparse_nonclk_coeff', 0.1) + table.accessor.downpour_accessor_param.click_coeff = strategy.get( + 'sparse_click_coeff', 1) + table.accessor.downpour_accessor_param.base_threshold = strategy.get( + 'sparse_base_threshold', 1.5) + table.accessor.downpour_accessor_param.delta_threshold = strategy.get( + 'sparse_delta_threshold', 0.25) + table.accessor.downpour_accessor_param.delta_keep_days = strategy.get( + 'sparse_delta_keep_days', 16) + table.accessor.downpour_accessor_param.delete_after_unseen_days = strategy.get( + 'sparse_delete_after_unseen_days', 30) + table.accessor.downpour_accessor_param.ssd_unseenday_threshold = strategy.get( + 'sparse_ssd_unseenday_threshold', 1) + table.accessor.downpour_accessor_param.show_click_decay_rate = strategy.get( + 'sparse_show_click_decay_rate', 0.98) + table.accessor.downpour_accessor_param.delete_threshold = strategy.get( + 'sparse_delete_threshold', 0.8) + converter = strategy.get( + 'sparse_converter', + "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)") + deconverter = strategy.get( + 'sparse_deconverter', + "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)" + ) + + table1 = table.accessor.table_accessor_save_param.add() + table1.param = 1 + table1.converter = converter + table1.deconverter = deconverter + + table2 = table.accessor.table_accessor_save_param.add() + table2.param = 2 + table2.converter = converter + table2.deconverter = deconverter + elif accessor_class == 'DownpourSparseValueAccessor': + optimizer_name = strategy.get("sparse_optimizer", "adam") + table.accessor.sparse_commonsgd_param.name = optimizer_name + table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8) + table.accessor.fea_dim = int(table.accessor.embedx_dim) + if optimizer_name == "naive": + table.accessor.sparse_commonsgd_param.naive.learning_rate = \ + strategy.get('sparse_learning_rate', 0.05) + table.accessor.sparse_commonsgd_param.naive.initial_range = \ + strategy.get('sparse_initial_range', 1e-4) + if strategy.get('sparse_weight_bounds') is None: + table.accessor.sparse_commonsgd_param.naive.weight_bounds.extend( + [-10, 10]) + else: + table.accessor.sparse_commonsgd_param.naive.weight_bounds.extend( + strategy.get('sparse_weight_bounds')) + elif optimizer_name == "adagrad": + table.accessor.sparse_commonsgd_param.adagrad.learning_rate = \ + strategy.get('sparse_learning_rate', 0.05) + table.accessor.sparse_commonsgd_param.adagrad.initial_range = \ + strategy.get('sparse_initial_range', 1e-4) + table.accessor.sparse_commonsgd_param.adagrad.initial_g2sum = strategy.get( + 'sparse_initial_g2sum', 3) + if strategy.get('sparse_weight_bounds') is None: + table.accessor.sparse_commonsgd_param.adagrad.weight_bounds.extend( + [-10, 10]) + else: + table.accessor.sparse_commonsgd_param.adagrad.weight_bounds.extend( + strategy.get('sparse_weight_bounds')) + elif optimizer_name == "adam": + table.accessor.sparse_commonsgd_param.adam.learning_rate = \ + strategy.get('sparse_learning_rate', 0.001) + table.accessor.sparse_commonsgd_param.adam.initial_range = \ + strategy.get('sparse_initial_range', 1e-4) + table.accessor.sparse_commonsgd_param.adam.beta1_decay_rate = strategy.get( + 'sparse_beta1_decay_rate', 0.9) + table.accessor.sparse_commonsgd_param.adam.beta2_decay_rate = strategy.get( + 'sparse_beta2_decay_rate', 0.999) + table.accessor.sparse_commonsgd_param.adam.ada_epsilon = strategy.get( + 'sparse_ada_epsilon', 1e-8) + if strategy.get('sparse_weight_bounds') is None: + table.accessor.sparse_commonsgd_param.adam.weight_bounds.extend( + [-10, 10]) + else: + table.accessor.sparse_commonsgd_param.adam.weight_bounds.extend( + strategy.get('sparse_weight_bounds')) + converter = strategy.get( + 'sparse_converter', + "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)") + deconverter = strategy.get( + 'sparse_deconverter', + "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)" + ) + + table1 = table.accessor.table_accessor_save_param.add() + table1.param = 1 + table1.converter = converter + table1.deconverter = deconverter + + table2 = table.accessor.table_accessor_save_param.add() + table2.param = 2 + table2.converter = converter + table2.deconverter = deconverter + elif accessor_class == 'DownpourUnitAccessor' or accessor_class == 'DownpourDoubleUnitAccessor': + self.add_sparse_table_common_config(table, strategy) + self.add_sparse_optimizer(table.accessor.embed_sgd_param, + strategy, "embed_") + self.add_sparse_optimizer(table.accessor.embedx_sgd_param, + strategy, "embedx_") + + def add_dense_table(self, table_id, param_var, grad_var, strategy, + sparse_table_names): + """ + Args: + table_id(int): id of sparse params table + param_var(list): param vars + grad_var(list): param grad vars + strategy(dict): the dense config dict + sparse_table_names(list): sparse table names + Returns: + return None + """ + fea_dim = 0 + dense_param_vars = [] + for p in param_var: + if p.name not in sparse_table_names: + dense_param_vars.append(p) + + for param in dense_param_vars: + fea_dim += reduce(lambda x, y: x * y, param.shape, 1) + + for table in self._server.downpour_server_param.downpour_table_param: + if table.table_id == table_id: + if table.type == pslib.PS_DENSE_TABLE: + table.accessor.fea_dim = fea_dim + return + else: + raise ValueError("expect table %s type=%s, but actual type=%s" \ + %(table_id, pslib.PS_DENSE_TABLE, table.type)) + + if strategy is None: + strategy = dict() + table = self._server.downpour_server_param.downpour_table_param.add() + table.table_id = table_id + support_dense_key_list = ['dense_table_class', 'dense_compress_in_save', 'dense_accessor_class', \ + 'dense_optimizer', 'dense_learning_rate', 'dense_avg_decay', 'dense_ada_decay', \ + 'dense_ada_epsilon', 'dense_mom_decay', 'dense_naive_lr'] + + for key in strategy: + if key not in support_dense_key_list: + raise ValueError("strategy key '%s' not support" % (key)) + + table.table_class = strategy.get('dense_table_class', + "DownpourDenseTable") + table.type = pslib.PS_DENSE_TABLE + table.compress_in_save = strategy.get('dense_compress_in_save', True) + table.accessor.accessor_class = strategy.get( + 'dense_accessor_class', "DownpourDenseValueAccessor") + table.accessor.dense_sgd_param.name = strategy.get( + 'dense_optimizer', "adam") + table.accessor.dense_sgd_param.adam.learning_rate = strategy.get( + 'dense_learning_rate', 5e-06) + table.accessor.dense_sgd_param.adam.avg_decay_rate = strategy.get( + 'dense_avg_decay', 0.999993) + table.accessor.dense_sgd_param.adam.ada_decay_rate = strategy.get( + 'dense_ada_decay', 0.9999) + table.accessor.dense_sgd_param.adam.ada_epsilon = strategy.get( + 'dense_ada_epsilon', 1e-8) + table.accessor.dense_sgd_param.adam.mom_decay_rate = strategy.get( + 'dense_mom_decay', 0.99) + table.accessor.dense_sgd_param.naive.learning_rate = strategy.get( + 'dense_naive_lr', 0.0002) + table.accessor.fea_dim = fea_dim + + def add_data_norm_table(self, table_id, learning_rate, param_var, grad_var, + strategy, sparse_table_names): + """ + Args: + table_id(int): id of datanorm table + learning_rate(float): the learning rate used to update parameters + param_var(list): param vars + grad_var(list): param grad vars + strategy(dict): the datanorm config dict + sparse_table_names(list): sparse table names + Returns: + return None + """ + fea_dim = 0 + dense_param_vars = [] + for p in param_var: + if p.name not in sparse_table_names: + dense_param_vars.append(p) + + for param in dense_param_vars: + fea_dim += reduce(lambda x, y: x * y, param.shape, 1) + + for table in self._server.downpour_server_param.downpour_table_param: + if table.table_id == table_id: + if table.type == pslib.PS_DENSE_TABLE: + table.accessor.fea_dim = fea_dim + return + else: + raise ValueError("expect table %s type=%s, but actual type=%s" \ + %(table_id, pslib.PS_DENSE_TABLE, table.type)) + if strategy is None: + strategy = dict() + + support_datanorm_key_list = ['datanorm_table_class', 'datanorm_compress_in_save', \ + 'datanorm_accessor_class', 'datanorm_operation', 'datanorm_decay_rate'] + + for key in strategy: + if key not in support_datanorm_key_list: + raise ValueError("strategy key '%s' not support" % (key)) + + table = self._server.downpour_server_param.downpour_table_param.add() + table.table_id = table_id + table.table_class = strategy.get('datanorm_table_class', + 'DownpourDenseTable') + table.type = pslib.PS_DENSE_TABLE + table.compress_in_save = strategy.get('datanorm_compress_in_save', True) + table.accessor.accessor_class = strategy.get( + 'datanorm_accessor_class', 'DownpourDenseValueAccessor') + table.accessor.dense_sgd_param.name = strategy.get( + 'datanorm_operation', 'summary') + table.accessor.dense_sgd_param.summary.summary_decay_rate = strategy.get( + 'datanorm_decay_rate', 0.999999) + table.accessor.fea_dim = fea_dim + + def add_sparse_optimizer(self, sgd, strategy, prefix): + optimizer_name = strategy.get(prefix + "sparse_optimizer", "adagrad") + sgd.name = optimizer_name + if optimizer_name == "naive": + sgd.naive.learning_rate = \ + strategy.get(prefix + 'sparse_learning_rate', 0.05) + sgd.naive.initial_range = \ + strategy.get(prefix + 'sparse_initial_range', 1e-4) + bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10]) + sgd.naive.weight_bounds.extend(bounds) + elif optimizer_name == "adagrad": + sgd.adagrad.learning_rate = \ + strategy.get(prefix + 'sparse_learning_rate', 0.05) + sgd.adagrad.initial_range = \ + strategy.get(prefix + 'sparse_initial_range', 1e-4) + if prefix == "embed_": + sgd.adagrad.initial_range = 0 + sgd.adagrad.initial_g2sum = strategy.get( + prefix + 'sparse_initial_g2sum', 3) + bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10]) + sgd.adagrad.weight_bounds.extend(bounds) + elif optimizer_name == "std_adagrad": + sgd.adagrad.learning_rate = \ + strategy.get(prefix + 'sparse_learning_rate', 0.05) + sgd.adagrad.initial_range = \ + strategy.get(prefix + 'sparse_initial_range', 1e-4) + if prefix == "embed_": + sgd.adagrad.initial_range = 0 + sgd.adagrad.initial_g2sum = strategy.get( + prefix + 'sparse_initial_g2sum', 3) + bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10]) + sgd.adagrad.weight_bounds.extend(bounds) + elif optimizer_name == "adam": + sgd.adam.learning_rate = \ + strategy.get(prefix + 'sparse_learning_rate', 0.001) + sgd.adam.initial_range = \ + strategy.get(prefix + 'sparse_initial_range', 1e-4) + sgd.adam.beta1_decay_rate = strategy.get( + prefix + 'sparse_beta1_decay_rate', 0.9) + sgd.adam.beta2_decay_rate = strategy.get( + prefix + 'sparse_beta2_decay_rate', 0.999) + sgd.adam.ada_epsilon = strategy.get(prefix + 'sparse_ada_epsilon', + 1e-8) + bounds = strategy.get(prefix + 'sparse_weight_bounds', [-10, 10]) + sgd.adam.weight_bounds.extend(bounds) + + def add_sparse_table_common_config(self, table, strategy): + table.accessor.embedx_dim = strategy.get('sparse_embedx_dim', 8) + table.accessor.embedx_threshold = strategy.get( + 'sparse_embedx_threshold', 10) + table.accessor.fea_dim = int(table.accessor.embedx_dim) + 3 + table.accessor.downpour_accessor_param.nonclk_coeff = strategy.get( + 'sparse_nonclk_coeff', 0.1) + table.accessor.downpour_accessor_param.click_coeff = strategy.get( + 'sparse_click_coeff', 1) + table.accessor.downpour_accessor_param.base_threshold = strategy.get( + 'sparse_base_threshold', 1.5) + table.accessor.downpour_accessor_param.delta_threshold = strategy.get( + 'sparse_delta_threshold', 0.25) + table.accessor.downpour_accessor_param.delta_keep_days = strategy.get( + 'sparse_delta_keep_days', 16) + table.accessor.downpour_accessor_param.delete_after_unseen_days = strategy.get( + 'sparse_delete_after_unseen_days', 30) + table.accessor.downpour_accessor_param.show_click_decay_rate = strategy.get( + 'sparse_show_click_decay_rate', 0.98) + table.accessor.downpour_accessor_param.delete_threshold = strategy.get( + 'sparse_delete_threshold', 0.8) + converter = strategy.get( + 'sparse_converter', + "(scripts/xbox_compressor_mf.py | bin/xbox_pb_converter)") + deconverter = strategy.get( + 'sparse_deconverter', + "(bin/xbox_pb_deconverter | scripts/xbox_decompressor_mf.awk)") + + table1 = table.accessor.table_accessor_save_param.add() + table1.param = 1 + table1.converter = converter + table1.deconverter = deconverter + + table2 = table.accessor.table_accessor_save_param.add() + table2.param = 2 + table2.converter = converter + table2.deconverter = deconverter + + def get_desc(self): + """ + Return downpour server program_desc + """ + return self._server + + +class DownpourWorker(Worker): + """ + DownpourWorker class is used to generate worker program_desc + Args: + window (int): push params frequency + worker: it is pslib.DownpourTrainerParameter + Examples: + worker = DownpourWorker(1) + """ + + def __init__(self, window): + self.window = window + self._worker = pslib.DownpourTrainerParameter() + + def add_sparse_table(self, + table_id, + slot_key_vars, + slot_value_vars, + slot_value_grads=None): + """ + Args: + table_id(int): id of sparse params table + slot_key_vars(list): slot key id + slot_value_vars(list): slot key value after embedding + slot_value_grads(list): grad of all params, default is None + Returns: + return None + """ + if slot_value_grads is None: + slot_value_grad_names = \ + [var.name + "@GRAD" for var in slot_value_vars] + else: + value_to_key = {} + for i in range(len(slot_key_vars)): + value_to_key[slot_value_vars[i].name] = slot_key_vars[i] + slot_value_grad_names = [] + all_grad_names = [var.name for var in slot_value_grads] + for var in slot_value_vars: + if var.name + "@GRAD" in all_grad_names: + slot_value_grad_names.append(var.name + "@GRAD") + sorted_slot_value_vars = [i for i in slot_value_vars if \ + i.name + "@GRAD" in slot_value_grad_names] + sorted_slot_value_vars += [i for i in slot_value_vars if \ + i.name + "@GRAD" not in slot_value_grad_names] + sorted_slot_key_vars = \ + [value_to_key[v.name] for v in sorted_slot_value_vars] + + target_table = None + for table in self._worker.sparse_table: + if table.table_id == table_id: + keys = table.slot_key + key_names = [var.name for var in sorted_slot_key_vars] + for key_name in key_names: + if key_name not in keys: + raise ValueError("sparse table %s slot_key error" % + table_id) + target_table = table + break + + table = target_table + if table is not None: + self._worker.sparse_table.remove(table) + table = self._worker.sparse_table.add() + table.table_id = table_id + table.slot_key.extend([var.name for var in sorted_slot_key_vars]) + table.slot_value.extend([var.name for var in sorted_slot_value_vars]) + table.slot_gradient.extend(slot_value_grad_names) + + def add_dense_table(self, table_id, learning_rate, param_vars, grad_vars, + dense_start_table_id, sparse_table_names): + r""" + Args: + table_id(int): id of sparse params table + learning_rate(float): the learning rate used to update parameters. \ + Can be a float value + param_vars(list): all dense param. it is a list. + grad_vars(list): all dense grad parm it is a list. + dense_start_table_id(int): dense table start index + sparse_table_names(list): sparse table names + Returns: + return None + """ + sparse_table_name_grad = [] + for name in sparse_table_names: + sparse_table_name_grad.append(name + "@GRAD") + + dense_param_name = [] + for p in param_vars: + if p.name not in sparse_table_names: + dense_param_name.append(p.name) + + dense_grad_name = [] + for g in grad_vars: + if g.name not in sparse_table_name_grad: + dense_grad_name.append(g.name) + + dense_param_name.sort() + dense_grad_name.sort() + + for table in self._worker.dense_table: + if table.table_id == table_id: + desc_dense_param_name = list(table.dense_variable_name) + desc_dense_param_name.sort() + + if dense_param_name == desc_dense_param_name: + desc_dense_grad_name = list( + table.dense_gradient_variable_name) + desc_dense_grad_name.sort() + if dense_grad_name == desc_dense_grad_name: + return + else: + raise ValueError( + "dense table %s dense_gradient_variable_name " + "error" % table_id) + else: + raise ValueError( + "dense table %s dense_variable_name error" % table_id) + + table = self._worker.dense_table.add() + table.table_id = table_id + + #def cmp_fc(x, y): + # if x.startswith("fc_") and y.startswith("fc_"): + # index_x = x.find('.') + # index_y = y.find('.') + # if index_x > 0 and index_y > 0: + # num_x = x[3:index_x] + # num_y = y[3:index_y] + # if num_x.isdigit() and num_y.isdigit(): + # if int(num_x) < int(num_y): + # return -1 + # if int(num_x) > int(num_y): + # return 1 + # if x[index_x + 1] == 'w' and y[index_y + 1] == 'b': + # return -1 + # if x[index_x + 1] == 'b' and y[index_y + 1] == 'w': + # return 1 + # if x < y: + # return -1 + # else: + # return 1 + + #table.dense_variable_name.extend(sorted(dense_param_name, cmp_fc)) + #table.dense_gradient_variable_name.extend( + # sorted(dense_grad_name, cmp_fc)) + table.dense_variable_name.extend(dense_param_name) + table.dense_gradient_variable_name.extend(dense_grad_name) + + def get_desc(self): + """ + Return downpour worker program_desc + """ + return self._worker diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/optimizer_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/optimizer_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..35cda4c34b00969012b4a9f564095309d2ee9659 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/optimizer_factory.py @@ -0,0 +1,910 @@ +# 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. +"""Optimizer Factory.""" + +__all__ = ["DistributedAdam", "FLEET_GLOBAL_DICT"] +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table_inputs +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table_outputs +from google.protobuf import text_format +from collections import OrderedDict +import copy +from .node import DownpourWorker, DownpourServer +from . import ps_pb2 as pslib +import os +import logging + +OpRole = core.op_proto_and_checker_maker.OpRole +# this dict is for store info about pull/push sparse ops. +FLEET_GLOBAL_DICT = { + # global settings + "enable": False, + "emb_to_table": {}, + "emb_to_accessor": {}, + "emb_to_size": {}, + # current embedding settings + "cur_sparse_id": 0, + "cur_accessor": "", + "click_name": "", + "scale_sparse_grad": None, +} + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s') +ch = logging.StreamHandler() +ch.setFormatter(formatter) +logger.addHandler(ch) + + +class DistributedOptimizerImplBase(object): + """ + DistributedOptimizerImplBase + base class of optimizers + """ + + def __init__(self, optimizer): + self._optimizer = optimizer + self._learning_rate = optimizer._learning_rate + self._regularization = optimizer.regularization + + def minimize(self, + losses, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + Args: + losses(Variable): loss variable defined by user + startup_program(Program): startup program that defined by user + parameter_list(str list): parameter names defined by users + no_grad_set(set): a set of variables that is defined by users + so that these variables do not need gradient computation + """ + pass + + +class DistributedAdam(DistributedOptimizerImplBase): + """ + DistributedAdam + adam optimizer in distributed training + """ + + def __init__(self, optimizer): + # todo(guru4elephant): add more optimizers here as argument + # todo(guru4elephant): make learning_rate as a variable + super(DistributedAdam, self).__init__(optimizer) + self._window = 1 + self.type = "downpour" + self.data_norm_name = [ + ".batch_size", ".batch_square_sum", ".batch_sum", + ".batch_size@GRAD", ".batch_square_sum@GRAD", ".batch_sum@GRAD" + ] + self.supported_embedding_types = [ + "lookup_table", "pull_sparse", "pull_sparse_v2", "pull_box_sparse", + "pull_gpups_sparse" + ] + self.supported_embedding_grad_types = [ + "lookup_table_grad", "push_sparse", "push_sparse_v2" + ] + op_maker = core.op_proto_and_checker_maker + self.op_role_key = op_maker.kOpRoleAttrName() + + def _find_distributed_lookup_table_inputs(self, program, table_names): + """ + Find input variable of distribute lookup table in program. + We could support multi-distribute table now. + Args: + program(Program): given program, locate distributed lookup table + table_name(str): given table names that is found beforehand + Returns: + inputs + """ + local_vars = program.current_block().vars + inputs_dict = dict() + for table_name in table_names: + inputs_dict[table_name] = [] + + for op in program.global_block().ops: + if op.type in self.supported_embedding_types: + if op.input("W")[0] in table_names: + inputs_dict[op.input("W")[0]].extend( + [local_vars[name] for name in op.input("Ids")]) + return inputs_dict + + def _find_distributed_lookup_table_outputs(self, program, table_names): + """ + Find output variable of distribute lookup table in program. + We could support multi-distribute table now. + Args: + programs(Program): given program, locate distributed lookup table + table_name(str): given table name that is found beforehand + Returns: + outputs + """ + local_vars = program.current_block().vars + outputs_dict = dict() + for table_name in table_names: + outputs_dict[table_name] = [] + + for op in program.global_block().ops: + if op.type in self.supported_embedding_types: + if op.input("W")[0] in table_names: + outputs_dict[op.input("W")[0]].extend( + [local_vars[name] for name in op.output("Out")]) + return outputs_dict + + def _find_distributed_lookup_table_grads(self, program, table_names): + local_vars = program.current_block().vars + grads_dict = dict() + for table_name in table_names: + grads_dict[table_name] = [] + + for op in program.global_block().ops: + if op.type in self.supported_embedding_grad_types: + if op.input("W")[0] in table_names: + grads_dict[op.input("W")[0]].extend( + [local_vars[name] for name in op.input("Out@GRAD")]) + return grads_dict + + def _is_optimizer_op(self, op): + return self.op_role_key in op.attr_names and \ + int(op.all_attrs()[self.op_role_key]) & int(OpRole.Optimize) + + def _remove_optimize_op_for_embedding(self, loss, table_name): + """ + find multi-sparse-table + """ + table_name = [name + "@GRAD" for name in table_name] + need_remove_op_index = [] + block = loss.block.program.global_block() + for ids, op in list(enumerate(block.ops)): + if self._is_optimizer_op(op): + if op.input("Grad")[0] in table_name: + need_remove_op_index.append(ids) + + need_remove_op_index.sort(reverse=True) + for index in need_remove_op_index: + block._remove_op(index) + + def _find_multi_distributed_lookup_table(self, losses): + """ + find multi-sparse-table + """ + table_names = set() + cnt = 0 + tmp_list = [] + ret_list = [] + for loss in losses: + for op in loss.block.program.global_block().ops: + if op.type in self.supported_embedding_types: + if op.attr('is_distributed') is True: + table_name = op.input("W")[0] + if table_name not in table_names: + table_names.add(table_name) + tmp_list.append([table_name, cnt]) + cnt += 1 + tmp_list.sort(key=lambda k: k[1]) + for x in tmp_list: + ret_list.append(x[0]) + return ret_list + + def _if_last_block(self, op, _equal_dict): + # for conditional_block op + cond_str = op.input('Cond')[0] + bool_test = False + if cond_str.startswith('equal'): + bool_test = True + vars_ = op.input('Input') + equal_keys = _equal_dict.keys() + for var_cond in vars_: + if var_cond in equal_keys: + if bool_test: + print("the conditional block is error") + return False + return True + + def _generte_cond_para_map(self, op, _fill_value_dict, _equal_fill_dict, + _now_program, _all_params): + # generate cond value to parameter map recursively + cond_str = op.input('Cond')[0] + vars_ = op.input('Input') + + if self._if_last_block(op, _equal_fill_dict): + vars_ = op.input('Input') + cond_key = "" + if cond_str.startswith('equal'): + cond_key = int(_fill_value_dict[_equal_fill_dict[cond_str]]) + else: + cond_key = -1 + p_list = [] + for var_cond in vars_: + if var_cond in _all_params: + p_list.append(var_cond) + + self._cond_params[cond_key] = p_list + self._other_params.extend(p_list) + else: + ops_cond = _now_program.block(int(op.attr('sub_block').id)).ops + for op in ops_cond: + if op.type == 'conditional_block': + self._generte_cond_para_map(op, _fill_value_dict, + _equal_fill_dict, _now_program, + _all_params) + + def _has_conditional_block(self, loss): + now_program = loss.block.program + root_block = now_program.block(0) + ops_ = root_block.ops + for op in ops_: + if op.type == 'conditional_block': + return True + return False + + def _check_params_grads(self, params, grads): + if len(params) != len(grads): + raise ValueError("params size != grads size, %s vs %s" % + (len(params), len(grads))) + + pname2grad = dict() + for i in range(len(params)): + pname = params[i].name + gname = grads[i].name + if pname != gname[:-5]: + raise ValueError(" params != grads , %s vs %s" % (pname, gname)) + pname2grad[pname] = grads[i] + + return pname2grad + + def _generate_multi_dense_table(self, + params, + grads, + cond_params, + other_params, + sparse_table_names, + dense_table_id=0): + # generate multi dense table by cond value + pname2grad = self._check_params_grads(params, grads) + root_params_list = [] + root_grads_list = [] + dense_tables = [] + for i, p in enumerate(params): + if p.name not in other_params and p.name not in sparse_table_names: + root_params_list.append(p) + root_grads_list.append(grads[i]) + if len(root_params_list) > 0: + dense_tables.append(dense_table_id) + dense_table_id += 1 + lists_params = [[] for i in range(len(cond_params.keys()))] + lists_grads = [[] for i in range(len(cond_params.keys()))] + + key_id = 0 + name2key = dict() + cond2denseid = dict() + for key, value in cond_params.items(): + cond2denseid[key] = dense_table_id + dense_tables.append(dense_table_id) + dense_table_id += 1 + for v in value: + name2key[v] = key_id + key_id += 1 + + for p in params: + if p.name in other_params: + lists_params[name2key[p.name]].append(p) + lists_grads[name2key[p.name]].append(pname2grad[p.name]) + + return dense_tables, cond2denseid, lists_params, lists_grads, root_params_list, root_grads_list + + def _gen_distributed_emb_to_size_dict(self, program): + d_size = dict() + local_vars = program.current_block().vars + + for op in program.global_block().ops: + if op.type in self.supported_embedding_types: + if op.attr('is_distributed') is True: + table_name = op.input("W")[0] + emb_size = local_vars[table_name].shape[-1] + if d_size.get(table_name) is None: + d_size[table_name] = emb_size + elif d_size[table_name] != emb_size: + raise ValueError("embedding size error: %s vs %s" % + (emb_size, d_size[table_name])) + + return d_size + + def _check_config_fleet_with_program_op(self, strategy, table_name, + emb_to_size): + if strategy.get(table_name) is None: + strategy[table_name] = dict() + st = strategy[table_name] + + accessor = "DownpourCtrAccessor" + if st.get("sparse_accessor_class") is not None: + accessor = st["sparse_accessor_class"] + + # set sparse_embedx_dim in the strategy according to accessor and use_cvm config + if accessor == "DownpourFeatureValueAccessor" \ + or accessor == "DownpourCtrAccessor" \ + or accessor == "DownpourCtrDymfAccessor" \ + or accessor == "DownpourDoubleUnitAccessor" \ + or accessor == "DownpourUnitAccessor": + if st.get("sparse_embedx_dim") is not None \ + and strategy.get("use_cvm") == True \ + and st["sparse_embedx_dim"] != emb_to_size[table_name] - 3: + raise ValueError( + "fleet config sparse_embedx_dim=%s not" + " equal to embedding dim - 3 = %s" % + (st["sparse_embedx_dim"], emb_to_size[table_name] - 3)) + if st.get("sparse_embedx_dim") is not None \ + and strategy.get("use_cvm") == False \ + and st["sparse_embedx_dim"] != emb_to_size[table_name] - 1: + raise ValueError( + "fleet config sparse_embedx_dim=%s not" + " equal to embedding dim - 1 = %s" % + (st["sparse_embedx_dim"], emb_to_size[table_name] - 1)) + if st.get("sparse_embedx_dim") is None \ + and strategy.get("use_cvm") == True: + logger.warning( + "sparse embedding dim for table name '{}' is: {}, while sparse_embedx_dim " + "with same sparse table name is not set in config_fleet.py. " + "Hence automatically set sparse_embedx_dim = {} - 3.". + format(table_name, emb_to_size[table_name], + emb_to_size[table_name])) + st["sparse_embedx_dim"] = emb_to_size[table_name] - 3 + if st.get("sparse_embedx_dim") is None \ + and strategy.get("use_cvm") == False: + logger.warning( + "sparse embedding dim for table name '{}' is: {}, while sparse_embedx_dim " + "with same sparse table name is not set in config_fleet.py. " + "Hence automatically set sparse_embedx_dim = {} - 1.". + format(table_name, emb_to_size[table_name], + emb_to_size[table_name])) + st["sparse_embedx_dim"] = emb_to_size[table_name] - 1 + elif accessor == "DownpourSparseValueAccessor": + if st.get("sparse_embedx_dim") is not None \ + and st["sparse_embedx_dim"] != emb_to_size[table_name]: + raise ValueError( + "fleet config sparse_embedx_dim=%s not" + " equal to embedding dim = %s" % + (st["sparse_embedx_dim"], emb_to_size[table_name])) + if st.get("sparse_embedx_dim") is None: + logger.warning( + "sparse embedding dim for table name '{}' is: {}, while sparse_embedx_dim " + "with same sparse table name is not set in config_fleet.py. " + "Hence automatically set sparse_embedx_dim = {}.".format( + table_name, emb_to_size[table_name], + emb_to_size[table_name])) + st["sparse_embedx_dim"] = emb_to_size[table_name] + + return strategy + + def _minimize(self, + losses, + startup_program=None, + parameter_list=None, + no_grad_set=None, + strategy={}): + """ + DownpounSGD is a distributed optimizer so + that user can call minimize to generate backward + operators and optimization operators within minimize function + Args: + loss(Variable): loss variable defined by user + startup_program(Program): startup program that defined by user + parameter_list(str list): parameter names defined by users + no_grad_set(set): a set of variables that is defined by users + so that these variables do not need gradient computation + strategy(dict): user-defined properties + Returns: + [optimize_ops, grads_and_weights] + """ + # sparse table names of each program + prog_id_to_sparse_table = OrderedDict() + # inputs_dict and outputs_dict of sparse tables of each program + prog_id_to_inputs_dict = OrderedDict() + prog_id_to_outputs_dict = OrderedDict() + # related to PSParameter + ps_param = pslib.PSParameter() + # related to ServerParameter + server = DownpourServer() + # program to worker (related to DownpourTrainerParameter) + prog_id_to_worker = OrderedDict() + # param_grads of each program + prog_id_to_param_grads = OrderedDict() + # sparse_grads of each program + prog_id_to_sparse_grads = OrderedDict() + # unique program set + program_id_set = set() + + sparse_table_to_index = OrderedDict() + sparse_table_index = 0 + for num in range(len(losses)): + loss = losses[num] + parameters = None + if parameter_list != None: + parameters = parameter_list[num] + prog_id = str(id(loss.block.program)) + # param_grads of program + params_grads = sorted(fluid.backward.append_backward( + loss, parameters, no_grad_set), + key=lambda x: x[0].name) + + flag_use_ps_gpu = strategy.get("use_ps_gpu", False) + if flag_use_ps_gpu: + if not isinstance(startup_program, list): + startup_program = [startup_program] + optimizer = copy.deepcopy(self._optimizer) + optimize_ops = optimizer.apply_optimize( + loss, + startup_program=startup_program[num], + params_grads=params_grads) + embedding_table = self._find_multi_distributed_lookup_table( + [loss]) + self._remove_optimize_op_for_embedding(loss, embedding_table) + # has condition_block op means multi-task + flag_multi_task = self._has_conditional_block(loss) + if flag_multi_task: + self._cond_params = dict() + self._other_params = [] + now_program = loss.block.program + root_block = now_program.block(0) + all_params = [] + for par in root_block.all_parameters(): + all_params.append(par.name) + + ops_ = root_block.ops + fill_value_dict = dict() + equal_fill_dict = dict() + for op in ops_: + # conditional_block op must has fill_constant and equal op + if op.type == 'fill_constant': + fill_value_dict[op.output('Out')[0]] = op.attr('value') + if op.type == 'equal': + equal_fill_dict[op.output('Out')[0]] = op.input('Y')[0] + if op.type == 'conditional_block': + self._generte_cond_para_map(op, fill_value_dict, + equal_fill_dict, + now_program, all_params) + + if prog_id not in program_id_set: + program_id_set.add(prog_id) + sparse_table = self._find_multi_distributed_lookup_table([loss]) + prog_id_to_sparse_table[prog_id] = sparse_table + + # get sparse_table_to_index + for tn in sparse_table: + if sparse_table_to_index.get(tn) is None: + sparse_table_to_index[tn] = sparse_table_index + sparse_table_index += 1 + + # get {table_name: emb_size} dict from program ops + emb_to_size = self._gen_distributed_emb_to_size_dict( + loss.block.program) + + # get inputs_dict + inputs_dict = self._find_distributed_lookup_table_inputs( + loss.block.program, sparse_table) + prog_id_to_inputs_dict[prog_id] = inputs_dict + # get outputs_dict + outputs_dict = self._find_distributed_lookup_table_outputs( + loss.block.program, sparse_table) + prog_id_to_outputs_dict[prog_id] = outputs_dict + + prog_id_to_worker[prog_id] = DownpourWorker(self._window) + + grads_dict = self._find_distributed_lookup_table_grads( + loss.block.program, sparse_table) + prog_id_to_sparse_grads[prog_id] = grads_dict + + if prog_id not in prog_id_to_param_grads: + prog_id_to_param_grads[prog_id] = [] + prog_id_to_param_grads[prog_id].append(params_grads) + + #if strategy.get("parallel_compute") + + # if user specify a fleet_desc.prototxt file, then load the file + # instead of creating default fleet_desc.prototxt. + # user can specify server_param or trainer_param or fs_client_param. + if strategy.get("fleet_desc_file") is not None: + fleet_desc_file = strategy["fleet_desc_file"] + with open(fleet_desc_file) as f: + text_format.Merge(f.read(), ps_param) + server.get_desc().CopyFrom(ps_param.server_param) + if len(ps_param.trainer_param) == 1: + for k in prog_id_to_worker: + prog_id_to_worker[k].get_desc().CopyFrom( + ps_param.trainer_param[0]) + else: + if len(ps_param.trainer_param) != len(prog_id_to_worker): + raise ValueError( + "trainer param size != program size, %s vs %s" % + (len(ps_param.trainer_param), len(prog_id_to_worker))) + idx = 0 + # prog_id_to_worker is OrderedDict + for k in prog_id_to_worker: + prog_id_to_worker[k].get_desc().CopyFrom( + ps_param.trainer_param[idx]) + idx += 1 + + # check config in op defination and fleet config + if FLEET_GLOBAL_DICT["enable"]: + one_slot = None + strategy["device_worker"] = "Hogwild" + emb_to_table = FLEET_GLOBAL_DICT["emb_to_table"] + emb_to_accessor = FLEET_GLOBAL_DICT["emb_to_accessor"] + emb_to_size = FLEET_GLOBAL_DICT["emb_to_size"] + if len(sparse_table_to_index) != len(emb_to_table): + raise ValueError( + "sparse tables from program != sparse tables from op: %s " + "vs %s" % (len(sparse_table_to_index), len(emb_to_table))) + for key in sparse_table_to_index: + if key not in emb_to_table or \ + sparse_table_to_index[key] != emb_to_table[key]: + print("sparse_table_to_index ", sparse_table_to_index) + print("emb_to_table ", emb_to_table) + raise ValueError("key error: %s" % key) + if strategy.get(key) is None: + strategy[key] = dict() + st = strategy[key] + + accessor = None + if st.get("sparse_accessor_class") is not None: + accessor = st["sparse_accessor_class"] + tables = \ + server.get_desc().downpour_server_param.downpour_table_param + for table in tables: + if table.table_id == sparse_table_to_index[key]: + accessor = table.accessor.accessor_class + break + + for loss in losses: + for op in loss.block.program.global_block().ops: + if op.type in self.supported_embedding_types: + if accessor is not None \ + and op.has_attr("AccessorClass"): + op._set_attr("AccessorClass", accessor) + if one_slot is None: + one_slot = loss.block.program. \ + global_block().var(op.input("Ids")[0]) + + # if accessor is None, use default accessor in op definition + if accessor is None: + accessor = emb_to_accessor[key] + # set sparse_embedx_dim in strategy, + # user do not have to set it in config_fleet + if accessor == "DownpourFeatureValueAccessor" \ + or accessor == "DownpourCtrDymfAccessor" \ + or accessor == "DownpourCtrAccessor" \ + or accessor == "DownpourDoubleUnitAccessor" \ + or accessor == "DownpourUnitAccessor": + if st.get("sparse_embedx_dim") is not None \ + and st["sparse_embedx_dim"] != emb_to_size[key] - 3: + raise ValueError( + "fleet config sparse_embedx_dim=%s not" + " equal to embedding size - 3 = %s" % + (st["sparse_embedx_dim"], emb_to_size[key] - 3)) + st["sparse_embedx_dim"] = emb_to_size[key] - 3 + elif accessor == "DownpourSparseValueAccessor": + if st.get("sparse_embedx_dim") is not None \ + and st["sparse_embedx_dim"] != emb_to_size[key]: + raise ValueError( + "fleet config sparse_embedx_dim=%s not" + " equal to embedding size = %s" % + (st["sparse_embedx_dim"], emb_to_size[key])) + st["sparse_embedx_dim"] = emb_to_size[key] + + # ServerParameter add all sparse tables + for tn in sparse_table_to_index: + sparse_table_index = sparse_table_to_index[tn] + st = self._check_config_fleet_with_program_op( + strategy, tn, emb_to_size) + if st.get(tn) is not None: + server.add_sparse_table(sparse_table_index, st[tn]) + else: + server.add_sparse_table(sparse_table_index, None) + + # each DownpourTrainerParameter add its own sparse tables + program_id_set.clear() + for loss in losses: + prog_id = str(id(loss.block.program)) + if prog_id not in program_id_set: + program_id_set.add(prog_id) + worker = prog_id_to_worker[prog_id] + inputs_dict = prog_id_to_inputs_dict[prog_id] + outputs_dict = prog_id_to_outputs_dict[prog_id] + for tn in prog_id_to_sparse_table[prog_id]: + sparse_table_index = sparse_table_to_index[tn] + grads_dict = prog_id_to_sparse_grads[prog_id] + worker.add_sparse_table(sparse_table_index, inputs_dict[tn], + outputs_dict[tn], grads_dict[tn]) + + dense_start_table_id = len(sparse_table_to_index) + dense_table_index = len(sparse_table_to_index) + program_configs = {} + # ServerParameter add all dense tables + # each DownpourTrainerParameter add its own dense tables + program_id_set.clear() + for loss_index in range(len(losses)): + program_id = str(id(losses[loss_index].block.program)) + if program_id not in program_id_set: + program_id_set.add(program_id) + worker = prog_id_to_worker[program_id] + sparse_table_names = prog_id_to_sparse_table[program_id] + sparse_table_index = \ + [sparse_table_to_index[i] for i in sparse_table_names] + + program_configs[program_id] = { + "pull_sparse": [t_index for t_index in sparse_table_index], + "push_sparse": [t_index for t_index in sparse_table_index] + } + + params_grads = prog_id_to_param_grads[program_id] + for pg in params_grads: + params = [] + grads = [] + data_norm_params = [] + data_norm_grads = [] + for i in pg: + is_data_norm_data = False + for data_norm_name in self.data_norm_name: + if i[0].name.endswith(data_norm_name): + is_data_norm_data = True + data_norm_params.append(i[0]) + if not is_data_norm_data: + params.append(i[0]) + + for i in pg: + is_data_norm_data = False + for data_norm_grad in self.data_norm_name: + if i[0].name.endswith(data_norm_grad): + is_data_norm_data = True + data_norm_grads.append(i[1]) + if not is_data_norm_data: + grads.append(i[1]) + # for new dense table + multi_task_dense_tables_push = [] + multi_task_dense_tables_pull = [] + if flag_multi_task: + dense_tables, cond2denseid, lists_params, lists_grads, root_params_list, root_grads_list = self._generate_multi_dense_table( + params, grads, self._cond_params, + self._other_params, sparse_table_names, + dense_table_index) + program_configs[program_id][ + 'cond2denseid'] = cond2denseid + multi_task_dense_tables_push = dense_tables + multi_task_dense_tables_pull = dense_tables[:] + + if strategy.get('dense_table') is not None: + if flag_multi_task: + server_dense_table_index = dense_table_index + if len(root_params_list) > 0: + server.add_dense_table(server_dense_table_index, + root_params_list, + root_grads_list, + strategy['dense_table'], + sparse_table_names) + server_dense_table_index += 1 + + for i in range(len(lists_params)): + server.add_dense_table(server_dense_table_index, + lists_params[i], + lists_grads[i], + strategy['dense_table'], + sparse_table_names) + server_dense_table_index += 1 + else: + server.add_dense_table(dense_table_index, params, + grads, + strategy['dense_table'], + sparse_table_names) + + else: + server.add_dense_table(dense_table_index, params, grads, + None, sparse_table_names) + + if flag_multi_task: + + if len(root_params_list) > 0: + worker.add_dense_table(dense_table_index, + self._learning_rate, + root_params_list, + root_grads_list, + dense_start_table_id, + sparse_table_names) + dense_table_index += 1 + + for i in range(len(lists_params)): + worker.add_dense_table(dense_table_index, + self._learning_rate, + lists_params[i], + lists_grads[i], + dense_start_table_id, + sparse_table_names) + dense_table_index += 1 + + dense_table_index -= 1 + else: + worker.add_dense_table(dense_table_index, + self._learning_rate, params, + grads, dense_start_table_id, + sparse_table_names) + + if FLEET_GLOBAL_DICT["enable"]: + cur_prog = losses[loss_index].block.program + cur_prog.global_block().append_op( + type="push_dense", + inputs={"Ids": one_slot}, + attrs={ + "InputNames": [i.name for i in grads], + "TableId": dense_table_index, + "ScaleDataNorm": + strategy.get("scale_datanorm", -1) + }) + + if "pull_dense" in program_configs[ + program_id] and "push_dense" in program_configs[ + program_id] and len(program_configs[program_id] + ["pull_dense"]) > 0: + if flag_multi_task: + program_configs[program_id]["pull_dense"].extend( + multi_task_dense_tables_pull) + program_configs[program_id]["push_dense"].extend( + multi_task_dense_tables_push) + else: + program_configs[program_id]["pull_dense"].extend( + [dense_table_index]) + program_configs[program_id]["push_dense"].extend( + [dense_table_index]) + else: + if flag_multi_task: + program_configs[program_id][ + "pull_dense"] = multi_task_dense_tables_pull + program_configs[program_id][ + "push_dense"] = multi_task_dense_tables_push + else: + program_configs[program_id]["pull_dense"] = [ + dense_table_index + ] + program_configs[program_id]["push_dense"] = [ + dense_table_index + ] + + if len(data_norm_params) != 0 and len(data_norm_grads) != 0: + dense_table_index += 1 + if strategy.get('datanorm_table') is not None: + server.add_data_norm_table( + dense_table_index, self._learning_rate, + data_norm_params, data_norm_grads, + strategy['datanorm_table'], sparse_table_names) + else: + server.add_data_norm_table(dense_table_index, + self._learning_rate, + data_norm_params, + data_norm_grads, None, + sparse_table_names) + + worker.add_dense_table(dense_table_index, + self._learning_rate, + data_norm_params, + data_norm_grads, + dense_start_table_id, + sparse_table_names) + + if FLEET_GLOBAL_DICT["enable"]: + cur_prog = losses[loss_index].block.program + cur_prog.global_block().append_op( + type="push_dense", + inputs={"Ids": one_slot}, + attrs={ + "InputNames": + [i.name for i in data_norm_grads], + "TableId": + dense_table_index, + "ScaleDataNorm": + strategy.get("scale_datanorm", -1) + }) + + program_configs[program_id]["pull_dense"].extend( + [dense_table_index]) + program_configs[program_id]["push_dense"].extend( + [dense_table_index]) + dense_table_index += 1 + + # Todo(guru4elephant): figure out how to support more sparse parameters + # currently only support lookup_table + worker_skipped_ops = ["lookup_table", "lookup_table_grad"] + if len(worker.get_desc().skip_op) == 0: + worker.get_desc().skip_op.extend(worker_skipped_ops) + + ps_param.server_param.CopyFrom(server.get_desc()) + # prog_id_to_worker is OrderedDict + if len(ps_param.trainer_param) == 0: + for k in prog_id_to_worker: + tp = ps_param.trainer_param.add() + tp.CopyFrom(prog_id_to_worker[k].get_desc()) + + if strategy.get("fs_uri") is not None: + ps_param.fs_client_param.uri = strategy["fs_uri"] + elif ps_param.fs_client_param.uri == "": + ps_param.fs_client_param.uri = "hdfs://your_hdfs_uri" + if strategy.get("fs_user") is not None: + ps_param.fs_client_param.user = strategy["fs_user"] + elif ps_param.fs_client_param.user == "": + ps_param.fs_client_param.user = "your_hdfs_user" + if strategy.get("fs_passwd") is not None: + ps_param.fs_client_param.passwd = strategy["fs_passwd"] + elif ps_param.fs_client_param.passwd == "": + ps_param.fs_client_param.passwd = "your_hdfs_passwd" + if strategy.get("fs_hadoop_bin") is not None: + ps_param.fs_client_param.hadoop_bin = strategy["fs_hadoop_bin"] + elif ps_param.fs_client_param.hadoop_bin == "": + ps_param.fs_client_param.hadoop_bin = "$HADOOP_HOME/bin/hadoop" + + opt_info = {} + opt_info["program_id_to_worker"] = prog_id_to_worker + opt_info["program_configs"] = program_configs + opt_info["trainer"] = strategy.get("trainer", "DistMultiTrainer") + opt_info["device_worker"] = strategy.get("device_worker", "DownpourSGD") + opt_info["optimizer"] = "DownpourSGD" + opt_info["fleet_desc"] = ps_param + opt_info["worker_skipped_ops"] = worker_skipped_ops + opt_info["use_cvm"] = strategy.get("use_cvm", False) + opt_info["no_cvm"] = strategy.get("no_cvm", False) + opt_info["scale_sparse_gradient_with_batch_size"] = strategy.get( + "scale_sparse_gradient_with_batch_size", True) + opt_info["worker_class"] = strategy.get("worker_class", + "DownpourWorker") + opt_info["stat_var_names"] = strategy.get("stat_var_names", []) + opt_info["local_tables"] = strategy.get("local_tables", []) + opt_info["async_tables"] = strategy.get("async_tables", []) + opt_info["async_tables"] = strategy.get("async_tables", []) + opt_info["scale_datanorm"] = strategy.get("scale_datanorm", -1) + opt_info["check_nan_var_names"] = strategy.get("check_nan_var_names", + []) + opt_info["dump_slot"] = False + opt_info["dump_converter"] = "" + opt_info["dump_fields"] = strategy.get("dump_fields", []) + opt_info["dump_file_num"] = strategy.get("dump_file_num", 16) + opt_info["user_define_dump_filename"] = strategy.get( + "user_define_dump_filename", "") + opt_info["dump_fields_path"] = strategy.get("dump_fields_path", "") + opt_info["dump_param"] = strategy.get("dump_param", []) + gpus_env = os.getenv("FLAGS_selected_gpus", "0") + opt_info["worker_places"] = [int(s) for s in gpus_env.split(",")] + opt_info["use_ps_gpu"] = strategy.get("use_ps_gpu", False) + if server._server.downpour_server_param.downpour_table_param[ + 0].accessor.accessor_class in [ + "DownpourCtrAccessor", "DownpourCtrDoubleAccessor", + "DownpourUnitAccessor", "DownpourDoubleUnitAccessor", + "DownpourCtrDymfAccessor" + ]: + opt_info["dump_slot"] = True + elif server._server.downpour_server_param.downpour_table_param[ + 0].accessor.accessor_class == "DownpourSparseValueAccessor": + opt_info["no_cvm"] = True + opt_info["adjust_ins_weight"] = strategy.get("adjust_ins_weight", {}) + opt_info["copy_table"] = strategy.get("copy_table", {}) + opt_info["loss_names"] = strategy.get("loss_names", []) + + for loss in losses: + loss.block.program._fleet_opt = opt_info + + param_grads_list = [] + for loss in losses: + prog_id = str(id(loss.block.program)) + param_grads_list.append(prog_id_to_param_grads[prog_id]) + return None, param_grads_list, opt_info diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/ps_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/ps_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..eec51ef827c5766e50910ba866ba7e5bc39d175b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/pslib/ps_pb2.py @@ -0,0 +1,3038 @@ +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: ps.proto + +import sys + +_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor.FileDescriptor( + name='ps.proto', + package='paddle', + syntax='proto2', + serialized_pb=_b( + '\n\x08ps.proto\x12\x06paddle\"\xb5\x02\n\x0bPSParameter\x12\x14\n\x0cworker_class\x18\x01 \x01(\t\x12\x14\n\x0cserver_class\x18\x02 \x01(\t\x12\x16\n\x0einstance_class\x18\x03 \x01(\t\x12\x15\n\x0binit_gflags\x18\x04 \x01(\t:\x00\x12-\n\x0cworker_param\x18\x65 \x01(\x0b\x32\x17.paddle.WorkerParameter\x12-\n\x0cserver_param\x18\x66 \x01(\x0b\x32\x17.paddle.ServerParameter\x12\x38\n\rtrainer_param\x18\xad\x02 \x03(\x0b\x32 .paddle.DownpourTrainerParameter\x12\x33\n\x0f\x66s_client_param\x18\xf5\x03 \x01(\x0b\x32\x19.paddle.FsClientParameter\"Q\n\x0fWorkerParameter\x12>\n\x15\x64ownpour_worker_param\x18\x01 \x01(\x0b\x32\x1f.paddle.DownpourWorkerParameter\"Q\n\x0fServerParameter\x12>\n\x15\x64ownpour_server_param\x18\x01 \x01(\x0b\x32\x1f.paddle.DownpourServerParameter\"O\n\x17\x44ownpourWorkerParameter\x12\x34\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\x16.paddle.TableParameter\"\xfd\x01\n\x18\x44ownpourTrainerParameter\x12\x30\n\x0b\x64\x65nse_table\x18\x01 \x03(\x0b\x32\x1b.paddle.DenseTableParameter\x12\x32\n\x0csparse_table\x18\x02 \x03(\x0b\x32\x1c.paddle.SparseTableParameter\x12\x1d\n\x15push_sparse_per_batch\x18\x03 \x01(\x05\x12\x1c\n\x14push_dense_per_batch\x18\x04 \x01(\x05\x12\x0f\n\x07skip_op\x18\x05 \x03(\t\x12-\n\x0eprogram_config\x18\x06 \x03(\x0b\x32\x15.paddle.ProgramConfig\"\x99\x01\n\rProgramConfig\x12\x12\n\nprogram_id\x18\x01 \x02(\t\x12\x1c\n\x14push_sparse_table_id\x18\x02 \x03(\x05\x12\x1b\n\x13push_dense_table_id\x18\x03 \x03(\x05\x12\x1c\n\x14pull_sparse_table_id\x18\x04 \x03(\x05\x12\x1b\n\x13pull_dense_table_id\x18\x05 \x03(\x05\"{\n\x13\x44\x65nseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x1b\n\x13\x64\x65nse_variable_name\x18\x02 \x03(\t\x12$\n\x1c\x64\x65nse_gradient_variable_name\x18\x03 \x03(\t\x12\x0f\n\x07\x66\x65\x61_dim\x18\x04 \x01(\x05\"z\n\x14SparseTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x05\x12\x13\n\x0b\x66\x65\x61ture_dim\x18\x02 \x01(\x05\x12\x10\n\x08slot_key\x18\x03 \x03(\t\x12\x12\n\nslot_value\x18\x04 \x03(\t\x12\x15\n\rslot_gradient\x18\x05 \x03(\t\"\x86\x01\n\x17\x44ownpourServerParameter\x12\x34\n\x14\x64ownpour_table_param\x18\x01 \x03(\x0b\x32\x16.paddle.TableParameter\x12\x35\n\rservice_param\x18\x02 \x01(\x0b\x32\x1e.paddle.ServerServiceParameter\"\xd7\x01\n\x16ServerServiceParameter\x12*\n\x0cserver_class\x18\x01 \x01(\t:\x14\x44ownpourBrpcPsServer\x12*\n\x0c\x63lient_class\x18\x02 \x01(\t:\x14\x44ownpourBrpcPsClient\x12(\n\rservice_class\x18\x03 \x01(\t:\x11\x44ownpourPsService\x12\x1c\n\x11start_server_port\x18\x04 \x01(\r:\x01\x30\x12\x1d\n\x11server_thread_num\x18\x05 \x01(\r:\x02\x31\x32\"\xc0\x02\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x13\n\x0btable_class\x18\x02 \x01(\t\x12\x17\n\tshard_num\x18\x03 \x01(\x04:\x04\x31\x30\x30\x30\x12\x30\n\x08\x61\x63\x63\x65ssor\x18\x04 \x01(\x0b\x32\x1e.paddle.TableAccessorParameter\x12\x1f\n\x04type\x18\x05 \x01(\x0e\x32\x11.paddle.TableType\x12\x1f\n\x10\x63ompress_in_save\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\'\n\x19\x65nable_sparse_table_cache\x18\x07 \x01(\x08:\x04true\x12(\n\x17sparse_table_cache_rate\x18\x08 \x01(\x01:\x07\x30.00055\x12\'\n\x1bsparse_table_cache_file_num\x18\t \x01(\r:\x02\x31\x36\"\xc1\x04\n\x16TableAccessorParameter\x12\x16\n\x0e\x61\x63\x63\x65ssor_class\x18\x01 \x01(\t\x12\x38\n\x10sparse_sgd_param\x18\x02 \x01(\x0b\x32\x1e.paddle.SparseSGDRuleParameter\x12\x36\n\x0f\x64\x65nse_sgd_param\x18\x03 \x01(\x0b\x32\x1d.paddle.DenseSGDRuleParameter\x12\x13\n\x07\x66\x65\x61_dim\x18\x04 \x01(\r:\x02\x31\x31\x12\x15\n\nembedx_dim\x18\x05 \x01(\r:\x01\x38\x12\x1c\n\x10\x65mbedx_threshold\x18\x06 \x01(\r:\x02\x31\x30\x12G\n\x17\x64ownpour_accessor_param\x18\x07 \x01(\x0b\x32&.paddle.DownpourTableAccessorParameter\x12\x45\n\x19table_accessor_save_param\x18\x08 \x03(\x0b\x32\".paddle.TableAccessorSaveParameter\x12\x44\n\x16sparse_commonsgd_param\x18\t \x01(\x0b\x32$.paddle.SparseCommonSGDRuleParameter\x12=\n\x0f\x65mbed_sgd_param\x18\n \x01(\x0b\x32$.paddle.SparseCommonSGDRuleParameter\x12>\n\x10\x65mbedx_sgd_param\x18\x0b \x01(\x0b\x32$.paddle.SparseCommonSGDRuleParameter\"\xba\x02\n\x1e\x44ownpourTableAccessorParameter\x12\x19\n\x0cnonclk_coeff\x18\x01 \x01(\x02:\x03\x30.1\x12\x16\n\x0b\x63lick_coeff\x18\x02 \x01(\x02:\x01\x31\x12\x1b\n\x0e\x62\x61se_threshold\x18\x03 \x01(\x02:\x03\x31.5\x12\x1d\n\x0f\x64\x65lta_threshold\x18\x04 \x01(\x02:\x04\x30.25\x12\x1b\n\x0f\x64\x65lta_keep_days\x18\x05 \x01(\x02:\x02\x31\x36\x12#\n\x15show_click_decay_rate\x18\x06 \x01(\x02:\x04\x30.98\x12\x1d\n\x10\x64\x65lete_threshold\x18\x07 \x01(\x02:\x03\x30.8\x12$\n\x18\x64\x65lete_after_unseen_days\x18\x08 \x01(\x02:\x02\x33\x30\x12\"\n\x17ssd_unseenday_threshold\x18\t \x01(\x05:\x01\x31\"S\n\x1aTableAccessorSaveParameter\x12\r\n\x05param\x18\x01 \x01(\r\x12\x11\n\tconverter\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65\x63onverter\x18\x03 \x01(\t\"e\n\x10PsRequestMessage\x12\x0e\n\x06\x63md_id\x18\x01 \x02(\r\x12\x10\n\x08table_id\x18\x02 \x01(\r\x12\x0e\n\x06params\x18\x03 \x03(\x0c\x12\x11\n\tclient_id\x18\x04 \x01(\x05\x12\x0c\n\x04\x64\x61ta\x18\x05 \x01(\x0c\"\x85\x01\n\x16SparseSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x18\n\rinitial_g2sum\x18\x02 \x01(\x01:\x01\x33\x12\x1d\n\rinitial_range\x18\x03 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xc6\x01\n\x1cSparseCommonSGDRuleParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x32\n\x05naive\x18\x02 \x01(\x0b\x32#.paddle.SparseNaiveSGDRuleParameter\x12\x36\n\x07\x61\x64\x61grad\x18\x03 \x01(\x0b\x32%.paddle.SparseAdagradSGDRuleParameter\x12,\n\x04\x61\x64\x61m\x18\x04 \x01(\x0b\x32\x1e.paddle.SparseAdamSGDParameter\"p\n\x1bSparseNaiveSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x03 \x03(\x02\"\x8c\x01\n\x1dSparseAdagradSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x18\n\rinitial_g2sum\x18\x02 \x01(\x01:\x01\x33\x12\x1d\n\rinitial_range\x18\x03 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xc8\x01\n\x16SparseAdamSGDParameter\x12\x1c\n\rlearning_rate\x18\x01 \x01(\x01:\x05\x30.001\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x1d\n\x10\x62\x65ta1_decay_rate\x18\x03 \x01(\x01:\x03\x30.9\x12\x1f\n\x10\x62\x65ta2_decay_rate\x18\x04 \x01(\x01:\x05\x30.999\x12\x1a\n\x0b\x61\x64\x61_epsilon\x18\x05 \x01(\x01:\x05\x31\x65-08\x12\x15\n\rweight_bounds\x18\x06 \x03(\x02\"\xe1\x01\n\x15\x44\x65nseSGDRuleParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\x04\x61\x64\x61m\x18\x02 \x01(\x0b\x32\x18.paddle.AdamSGDParameter\x12(\n\x05naive\x18\x03 \x01(\x0b\x32\x19.paddle.NaiveSGDParameter\x12,\n\x07summary\x18\x04 \x01(\x0b\x32\x1b.paddle.SummarySGDParameter\x12:\n\x0emoving_average\x18\x05 \x01(\x0b\x32\".paddle.MovingAverageRuleParameter\"\xac\x01\n\x10\x41\x64\x61mSGDParameter\x12\x1c\n\rlearning_rate\x18\x01 \x01(\x01:\x05\x35\x65-06\x12 \n\x0e\x61vg_decay_rate\x18\x02 \x01(\x01:\x08\x30.999993\x12\x1e\n\x0e\x61\x64\x61_decay_rate\x18\x03 \x01(\x01:\x06\x30.9999\x12\x1a\n\x0b\x61\x64\x61_epsilon\x18\x04 \x01(\x01:\x05\x31\x65-08\x12\x1c\n\x0emom_decay_rate\x18\x05 \x01(\x01:\x04\x30.99\"J\n\x11NaiveSGDParameter\x12\x1d\n\rlearning_rate\x18\x01 \x01(\x01:\x06\x30.0002\x12\x16\n\x0e\x61vg_decay_rate\x18\x02 \x01(\x01\";\n\x13SummarySGDParameter\x12$\n\x12summary_decay_rate\x18\x01 \x01(\x01:\x08\x30.999999\".\n\x1aMovingAverageRuleParameter\x12\x10\n\x08momentum\x18\x01 \x01(\x01\"I\n\x11PsResponseMessage\x12\x13\n\x08\x65rr_code\x18\x01 \x02(\x05:\x01\x30\x12\x11\n\x07\x65rr_msg\x18\x02 \x02(\t:\x00\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xd5\x01\n\x11\x46sClientParameter\x12:\n\x07\x66s_type\x18\x01 \x01(\x0e\x32#.paddle.FsClientParameter.FsApiType:\x04HDFS\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\x0c\n\x04user\x18\x03 \x01(\t\x12\x0e\n\x06passwd\x18\x04 \x01(\t\x12\x13\n\x0b\x62uffer_size\x18\x05 \x01(\x05\x12\x12\n\nhadoop_bin\x18\x33 \x01(\t\x12\x10\n\x08\x61\x66s_conf\x18\x65 \x01(\t\"\x1e\n\tFsApiType\x12\x08\n\x04HDFS\x10\x00\x12\x07\n\x03\x41\x46S\x10\x01*4\n\tTableType\x12\x13\n\x0fPS_SPARSE_TABLE\x10\x00\x12\x12\n\x0ePS_DENSE_TABLE\x10\x01*\xba\x04\n\x07PsCmdID\x12\x17\n\x13PS_PULL_DENSE_TABLE\x10\x00\x12\x17\n\x13PS_PUSH_DENSE_TABLE\x10\x01\x12\x18\n\x14PS_PULL_SPARSE_TABLE\x10\x02\x12\x18\n\x14PS_PUSH_SPARSE_TABLE\x10\x03\x12\x13\n\x0fPS_SHRINK_TABLE\x10\x04\x12\x15\n\x11PS_SAVE_ONE_TABLE\x10\x05\x12\x15\n\x11PS_SAVE_ALL_TABLE\x10\x06\x12\x15\n\x11PS_LOAD_ONE_TABLE\x10\x07\x12\x15\n\x11PS_LOAD_ALL_TABLE\x10\x08\x12\x16\n\x12PS_CLEAR_ONE_TABLE\x10\t\x12\x16\n\x12PS_CLEAR_ALL_TABLE\x10\n\x12\x17\n\x13PS_PUSH_DENSE_PARAM\x10\x0b\x12\x12\n\x0ePS_STOP_SERVER\x10\x0c\x12\x1b\n\x17PS_SAVE_ONE_CACHE_TABLE\x10\r\x12\x1a\n\x16PS_GET_CACHE_THRESHOLD\x10\x0e\x12\x14\n\x10PS_CACHE_SHUFFLE\x10\x0f\x12\x11\n\rPS_COPY_TABLE\x10\x10\x12\x1c\n\x18PS_COPY_TABLE_BY_FEASIGN\x10\x11\x12(\n$PS_PULL_SPARSE_TABLE_WITH_DEPENDENCY\x10\x12\x12(\n$PS_PUSH_SPARSE_TABLE_WITH_DEPENDENCY\x10\x13\x12\x17\n\x13PS_PRINT_TABLE_STAT\x10\x14\x12\x0e\n\nPS_S2S_MSG\x10\x65\x32K\n\tPsService\x12>\n\x07service\x12\x18.paddle.PsRequestMessage\x1a\x19.paddle.PsResponseMessageB\x06\x80\x01\x01\xf8\x01\x01' + )) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_TABLETYPE = _descriptor.EnumDescriptor( + name='TableType', + full_name='paddle.TableType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='PS_SPARSE_TABLE', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_DENSE_TABLE', + index=1, + number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=4679, + serialized_end=4731, +) +_sym_db.RegisterEnumDescriptor(_TABLETYPE) + +TableType = enum_type_wrapper.EnumTypeWrapper(_TABLETYPE) +_PSCMDID = _descriptor.EnumDescriptor( + name='PsCmdID', + full_name='paddle.PsCmdID', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='PS_PULL_DENSE_TABLE', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_DENSE_TABLE', + index=1, + number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PULL_SPARSE_TABLE', + index=2, + number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_SPARSE_TABLE', + index=3, + number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SHRINK_TABLE', + index=4, + number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SAVE_ONE_TABLE', + index=5, + number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SAVE_ALL_TABLE', + index=6, + number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_LOAD_ONE_TABLE', + index=7, + number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_LOAD_ALL_TABLE', + index=8, + number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_CLEAR_ONE_TABLE', + index=9, + number=9, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_CLEAR_ALL_TABLE', + index=10, + number=10, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PUSH_DENSE_PARAM', + index=11, + number=11, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_STOP_SERVER', + index=12, + number=12, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_SAVE_ONE_CACHE_TABLE', + index=13, + number=13, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_GET_CACHE_THRESHOLD', + index=14, + number=14, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_CACHE_SHUFFLE', + index=15, + number=15, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_COPY_TABLE', + index=16, + number=16, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_COPY_TABLE_BY_FEASIGN', + index=17, + number=17, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_PULL_SPARSE_TABLE_WITH_DEPENDENCY', + index=18, + number=18, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_PUSH_SPARSE_TABLE_WITH_DEPENDENCY', + index=19, + number=19, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_PRINT_TABLE_STAT', + index=20, + number=20, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='PS_S2S_MSG', + index=21, + number=101, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=4734, + serialized_end=5304, +) +_sym_db.RegisterEnumDescriptor(_PSCMDID) + +PsCmdID = enum_type_wrapper.EnumTypeWrapper(_PSCMDID) +PS_SPARSE_TABLE = 0 +PS_DENSE_TABLE = 1 +PS_PULL_DENSE_TABLE = 0 +PS_PUSH_DENSE_TABLE = 1 +PS_PULL_SPARSE_TABLE = 2 +PS_PUSH_SPARSE_TABLE = 3 +PS_SHRINK_TABLE = 4 +PS_SAVE_ONE_TABLE = 5 +PS_SAVE_ALL_TABLE = 6 +PS_LOAD_ONE_TABLE = 7 +PS_LOAD_ALL_TABLE = 8 +PS_CLEAR_ONE_TABLE = 9 +PS_CLEAR_ALL_TABLE = 10 +PS_PUSH_DENSE_PARAM = 11 +PS_STOP_SERVER = 12 +PS_SAVE_ONE_CACHE_TABLE = 13 +PS_GET_CACHE_THRESHOLD = 14 +PS_CACHE_SHUFFLE = 15 +PS_COPY_TABLE = 16 +PS_COPY_TABLE_BY_FEASIGN = 17 +PS_PULL_SPARSE_TABLE_WITH_DEPENDENCY = 18 +PS_PUSH_SPARSE_TABLE_WITH_DEPENDENCY = 19 +PS_PRINT_TABLE_STAT = 20 +PS_S2S_MSG = 101 + +_FSCLIENTPARAMETER_FSAPITYPE = _descriptor.EnumDescriptor( + name='FsApiType', + full_name='paddle.FsClientParameter.FsApiType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor(name='HDFS', + index=0, + number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor(name='AFS', + index=1, + number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=4647, + serialized_end=4677, +) +_sym_db.RegisterEnumDescriptor(_FSCLIENTPARAMETER_FSAPITYPE) + +_PSPARAMETER = _descriptor.Descriptor( + name='PSParameter', + full_name='paddle.PSParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='worker_class', + full_name='paddle.PSParameter.worker_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='server_class', + full_name='paddle.PSParameter.server_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='instance_class', + full_name='paddle.PSParameter.instance_class', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='init_gflags', + full_name='paddle.PSParameter.init_gflags', + index=3, + number=4, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='worker_param', + full_name='paddle.PSParameter.worker_param', + index=4, + number=101, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='server_param', + full_name='paddle.PSParameter.server_param', + index=5, + number=102, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_param', + full_name='paddle.PSParameter.trainer_param', + index=6, + number=301, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fs_client_param', + full_name='paddle.PSParameter.fs_client_param', + index=7, + number=501, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=21, + serialized_end=330, +) + +_WORKERPARAMETER = _descriptor.Descriptor( + name='WorkerParameter', + full_name='paddle.WorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_worker_param', + full_name='paddle.WorkerParameter.downpour_worker_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=332, + serialized_end=413, +) + +_SERVERPARAMETER = _descriptor.Descriptor( + name='ServerParameter', + full_name='paddle.ServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_server_param', + full_name='paddle.ServerParameter.downpour_server_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=415, + serialized_end=496, +) + +_DOWNPOURWORKERPARAMETER = _descriptor.Descriptor( + name='DownpourWorkerParameter', + full_name='paddle.DownpourWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', + full_name='paddle.DownpourWorkerParameter.downpour_table_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=498, + serialized_end=577, +) + +_DOWNPOURTRAINERPARAMETER = _descriptor.Descriptor( + name='DownpourTrainerParameter', + full_name='paddle.DownpourTrainerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dense_table', + full_name='paddle.DownpourTrainerParameter.dense_table', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table', + full_name='paddle.DownpourTrainerParameter.sparse_table', + index=1, + number=2, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_per_batch', + full_name='paddle.DownpourTrainerParameter.push_sparse_per_batch', + index=2, + number=3, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_per_batch', + full_name='paddle.DownpourTrainerParameter.push_dense_per_batch', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='skip_op', + full_name='paddle.DownpourTrainerParameter.skip_op', + index=4, + number=5, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='program_config', + full_name='paddle.DownpourTrainerParameter.program_config', + index=5, + number=6, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=580, + serialized_end=833, +) + +_PROGRAMCONFIG = _descriptor.Descriptor( + name='ProgramConfig', + full_name='paddle.ProgramConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='program_id', + full_name='paddle.ProgramConfig.program_id', + index=0, + number=1, + type=9, + cpp_type=9, + label=2, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_table_id', + full_name='paddle.ProgramConfig.push_sparse_table_id', + index=1, + number=2, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_table_id', + full_name='paddle.ProgramConfig.push_dense_table_id', + index=2, + number=3, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_sparse_table_id', + full_name='paddle.ProgramConfig.pull_sparse_table_id', + index=3, + number=4, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_dense_table_id', + full_name='paddle.ProgramConfig.pull_dense_table_id', + index=4, + number=5, + type=5, + cpp_type=1, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=836, + serialized_end=989, +) + +_DENSETABLEPARAMETER = _descriptor.Descriptor( + name='DenseTableParameter', + full_name='paddle.DenseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.DenseTableParameter.table_id', + index=0, + number=1, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_variable_name', + full_name='paddle.DenseTableParameter.dense_variable_name', + index=1, + number=2, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_gradient_variable_name', + full_name='paddle.DenseTableParameter.dense_gradient_variable_name', + index=2, + number=3, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', + full_name='paddle.DenseTableParameter.fea_dim', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=991, + serialized_end=1114, +) + +_SPARSETABLEPARAMETER = _descriptor.Descriptor( + name='SparseTableParameter', + full_name='paddle.SparseTableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.SparseTableParameter.table_id', + index=0, + number=1, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_dim', + full_name='paddle.SparseTableParameter.feature_dim', + index=1, + number=2, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_key', + full_name='paddle.SparseTableParameter.slot_key', + index=2, + number=3, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_value', + full_name='paddle.SparseTableParameter.slot_value', + index=3, + number=4, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='slot_gradient', + full_name='paddle.SparseTableParameter.slot_gradient', + index=4, + number=5, + type=9, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1116, + serialized_end=1238, +) + +_DOWNPOURSERVERPARAMETER = _descriptor.Descriptor( + name='DownpourServerParameter', + full_name='paddle.DownpourServerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='downpour_table_param', + full_name='paddle.DownpourServerParameter.downpour_table_param', + index=0, + number=1, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_param', + full_name='paddle.DownpourServerParameter.service_param', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1241, + serialized_end=1375, +) + +_SERVERSERVICEPARAMETER = _descriptor.Descriptor( + name='ServerServiceParameter', + full_name='paddle.ServerServiceParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='server_class', + full_name='paddle.ServerServiceParameter.server_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourBrpcPsServer").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_class', + full_name='paddle.ServerServiceParameter.client_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourBrpcPsClient").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service_class', + full_name='paddle.ServerServiceParameter.service_class', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=True, + default_value=_b("DownpourPsService").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_server_port', + full_name='paddle.ServerServiceParameter.start_server_port', + index=3, + number=4, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_thread_num', + full_name='paddle.ServerServiceParameter.server_thread_num', + index=4, + number=5, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=12, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1378, + serialized_end=1593, +) + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='table_id', + full_name='paddle.TableParameter.table_id', + index=0, + number=1, + type=4, + cpp_type=4, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_class', + full_name='paddle.TableParameter.table_class', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='shard_num', + full_name='paddle.TableParameter.shard_num', + index=2, + number=3, + type=4, + cpp_type=4, + label=1, + has_default_value=True, + default_value=1000, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='accessor', + full_name='paddle.TableParameter.accessor', + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='type', + full_name='paddle.TableParameter.type', + index=4, + number=5, + type=14, + cpp_type=8, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compress_in_save', + full_name='paddle.TableParameter.compress_in_save', + index=5, + number=6, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=False, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_sparse_table_cache', + full_name='paddle.TableParameter.enable_sparse_table_cache', + index=6, + number=7, + type=8, + cpp_type=7, + label=1, + has_default_value=True, + default_value=True, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_rate', + full_name='paddle.TableParameter.sparse_table_cache_rate', + index=7, + number=8, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.00055), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_file_num', + full_name='paddle.TableParameter.sparse_table_cache_file_num', + index=8, + number=9, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=16, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1596, + serialized_end=1916, +) + +_TABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='TableAccessorParameter', + full_name='paddle.TableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='accessor_class', + full_name='paddle.TableAccessorParameter.accessor_class', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_sgd_param', + full_name='paddle.TableAccessorParameter.sparse_sgd_param', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_sgd_param', + full_name='paddle.TableAccessorParameter.dense_sgd_param', + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', + full_name='paddle.TableAccessorParameter.fea_dim', + index=3, + number=4, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=11, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_dim', + full_name='paddle.TableAccessorParameter.embedx_dim', + index=4, + number=5, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=8, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_threshold', + full_name='paddle.TableAccessorParameter.embedx_threshold', + index=5, + number=6, + type=13, + cpp_type=3, + label=1, + has_default_value=True, + default_value=10, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='downpour_accessor_param', + full_name='paddle.TableAccessorParameter.downpour_accessor_param', + index=6, + number=7, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_accessor_save_param', + full_name='paddle.TableAccessorParameter.table_accessor_save_param', + index=7, + number=8, + type=11, + cpp_type=10, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_commonsgd_param', + full_name='paddle.TableAccessorParameter.sparse_commonsgd_param', + index=8, + number=9, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embed_sgd_param', + full_name='paddle.TableAccessorParameter.embed_sgd_param', + index=9, + number=10, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_sgd_param', + full_name='paddle.TableAccessorParameter.embedx_sgd_param', + index=10, + number=11, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=1919, + serialized_end=2496, +) + +_DOWNPOURTABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='DownpourTableAccessorParameter', + full_name='paddle.DownpourTableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nonclk_coeff', + full_name='paddle.DownpourTableAccessorParameter.nonclk_coeff', + index=0, + number=1, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(0.1), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='click_coeff', + full_name='paddle.DownpourTableAccessorParameter.click_coeff', + index=1, + number=2, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(1), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='base_threshold', + full_name='paddle.DownpourTableAccessorParameter.base_threshold', + index=2, + number=3, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(1.5), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_threshold', + full_name='paddle.DownpourTableAccessorParameter.delta_threshold', + index=3, + number=4, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(0.25), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_keep_days', + full_name='paddle.DownpourTableAccessorParameter.delta_keep_days', + index=4, + number=5, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(16), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_click_decay_rate', + full_name= + 'paddle.DownpourTableAccessorParameter.show_click_decay_rate', + index=5, + number=6, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(0.98), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_threshold', + full_name='paddle.DownpourTableAccessorParameter.delete_threshold', + index=6, + number=7, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(0.8), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_after_unseen_days', + full_name= + 'paddle.DownpourTableAccessorParameter.delete_after_unseen_days', + index=7, + number=8, + type=2, + cpp_type=6, + label=1, + has_default_value=True, + default_value=float(30), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ssd_unseenday_threshold', + full_name= + 'paddle.DownpourTableAccessorParameter.ssd_unseenday_threshold', + index=8, + number=9, + type=5, + cpp_type=1, + label=1, + has_default_value=True, + default_value=1, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2499, + serialized_end=2813, +) + +_TABLEACCESSORSAVEPARAMETER = _descriptor.Descriptor( + name='TableAccessorSaveParameter', + full_name='paddle.TableAccessorSaveParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='param', + full_name='paddle.TableAccessorSaveParameter.param', + index=0, + number=1, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='converter', + full_name='paddle.TableAccessorSaveParameter.converter', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deconverter', + full_name='paddle.TableAccessorSaveParameter.deconverter', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2815, + serialized_end=2898, +) + +_PSREQUESTMESSAGE = _descriptor.Descriptor( + name='PsRequestMessage', + full_name='paddle.PsRequestMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor(name='cmd_id', + full_name='paddle.PsRequestMessage.cmd_id', + index=0, + number=1, + type=13, + cpp_type=3, + label=2, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_id', + full_name='paddle.PsRequestMessage.table_id', + index=1, + number=2, + type=13, + cpp_type=3, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='params', + full_name='paddle.PsRequestMessage.params', + index=2, + number=3, + type=12, + cpp_type=9, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='client_id', + full_name='paddle.PsRequestMessage.client_id', + index=3, + number=4, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='data', + full_name='paddle.PsRequestMessage.data', + index=4, + number=5, + type=12, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b(""), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=2900, + serialized_end=3001, +) + +_SPARSESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseSGDRuleParameter', + full_name='paddle.SparseSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.SparseSGDRuleParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.05), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', + full_name='paddle.SparseSGDRuleParameter.initial_g2sum', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(3), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', + full_name='paddle.SparseSGDRuleParameter.initial_range', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.0001), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', + full_name='paddle.SparseSGDRuleParameter.weight_bounds', + index=3, + number=4, + type=2, + cpp_type=6, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3004, + serialized_end=3137, +) + +_SPARSECOMMONSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseCommonSGDRuleParameter', + full_name='paddle.SparseCommonSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', + full_name='paddle.SparseCommonSGDRuleParameter.name', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', + full_name='paddle.SparseCommonSGDRuleParameter.naive', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adagrad', + full_name='paddle.SparseCommonSGDRuleParameter.adagrad', + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', + full_name='paddle.SparseCommonSGDRuleParameter.adam', + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3140, + serialized_end=3338, +) + +_SPARSENAIVESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseNaiveSGDRuleParameter', + full_name='paddle.SparseNaiveSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.SparseNaiveSGDRuleParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.05), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', + full_name='paddle.SparseNaiveSGDRuleParameter.initial_range', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.0001), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', + full_name='paddle.SparseNaiveSGDRuleParameter.weight_bounds', + index=2, + number=3, + type=2, + cpp_type=6, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3340, + serialized_end=3452, +) + +_SPARSEADAGRADSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseAdagradSGDRuleParameter', + full_name='paddle.SparseAdagradSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.SparseAdagradSGDRuleParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.05), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', + full_name='paddle.SparseAdagradSGDRuleParameter.initial_g2sum', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(3), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', + full_name='paddle.SparseAdagradSGDRuleParameter.initial_range', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.0001), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', + full_name='paddle.SparseAdagradSGDRuleParameter.weight_bounds', + index=3, + number=4, + type=2, + cpp_type=6, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3455, + serialized_end=3595, +) + +_SPARSEADAMSGDPARAMETER = _descriptor.Descriptor( + name='SparseAdamSGDParameter', + full_name='paddle.SparseAdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.SparseAdamSGDParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.001), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', + full_name='paddle.SparseAdamSGDParameter.initial_range', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.0001), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta1_decay_rate', + full_name='paddle.SparseAdamSGDParameter.beta1_decay_rate', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.9), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta2_decay_rate', + full_name='paddle.SparseAdamSGDParameter.beta2_decay_rate', + index=3, + number=4, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.999), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', + full_name='paddle.SparseAdamSGDParameter.ada_epsilon', + index=4, + number=5, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(1e-08), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', + full_name='paddle.SparseAdamSGDParameter.weight_bounds', + index=5, + number=6, + type=2, + cpp_type=6, + label=3, + has_default_value=False, + default_value=[], + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3598, + serialized_end=3798, +) + +_DENSESGDRULEPARAMETER = _descriptor.Descriptor( + name='DenseSGDRuleParameter', + full_name='paddle.DenseSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', + full_name='paddle.DenseSGDRuleParameter.name', + index=0, + number=1, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', + full_name='paddle.DenseSGDRuleParameter.adam', + index=1, + number=2, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', + full_name='paddle.DenseSGDRuleParameter.naive', + index=2, + number=3, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='summary', + full_name='paddle.DenseSGDRuleParameter.summary', + index=3, + number=4, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='moving_average', + full_name='paddle.DenseSGDRuleParameter.moving_average', + index=4, + number=5, + type=11, + cpp_type=10, + label=1, + has_default_value=False, + default_value=None, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=3801, + serialized_end=4026, +) + +_ADAMSGDPARAMETER = _descriptor.Descriptor( + name='AdamSGDParameter', + full_name='paddle.AdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.AdamSGDParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(5e-06), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg_decay_rate', + full_name='paddle.AdamSGDParameter.avg_decay_rate', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.999993), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_decay_rate', + full_name='paddle.AdamSGDParameter.ada_decay_rate', + index=2, + number=3, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.9999), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', + full_name='paddle.AdamSGDParameter.ada_epsilon', + index=3, + number=4, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(1e-08), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mom_decay_rate', + full_name='paddle.AdamSGDParameter.mom_decay_rate', + index=4, + number=5, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.99), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4029, + serialized_end=4201, +) + +_NAIVESGDPARAMETER = _descriptor.Descriptor( + name='NaiveSGDParameter', + full_name='paddle.NaiveSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', + full_name='paddle.NaiveSGDParameter.learning_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.0002), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg_decay_rate', + full_name='paddle.NaiveSGDParameter.avg_decay_rate', + index=1, + number=2, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4203, + serialized_end=4277, +) + +_SUMMARYSGDPARAMETER = _descriptor.Descriptor( + name='SummarySGDParameter', + full_name='paddle.SummarySGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='summary_decay_rate', + full_name='paddle.SummarySGDParameter.summary_decay_rate', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=True, + default_value=float(0.999999), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4279, + serialized_end=4338, +) + +_MOVINGAVERAGERULEPARAMETER = _descriptor.Descriptor( + name='MovingAverageRuleParameter', + full_name='paddle.MovingAverageRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='momentum', + full_name='paddle.MovingAverageRuleParameter.momentum', + index=0, + number=1, + type=1, + cpp_type=5, + label=1, + has_default_value=False, + default_value=float(0), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4340, + serialized_end=4386, +) + +_PSRESPONSEMESSAGE = _descriptor.Descriptor( + name='PsResponseMessage', + full_name='paddle.PsResponseMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='err_code', + full_name='paddle.PsResponseMessage.err_code', + index=0, + number=1, + type=5, + cpp_type=1, + label=2, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='err_msg', + full_name='paddle.PsResponseMessage.err_msg', + index=1, + number=2, + type=9, + cpp_type=9, + label=2, + has_default_value=True, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='data', + full_name='paddle.PsResponseMessage.data', + index=2, + number=3, + type=12, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b(""), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4388, + serialized_end=4461, +) + +_FSCLIENTPARAMETER = _descriptor.Descriptor( + name='FsClientParameter', + full_name='paddle.FsClientParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fs_type', + full_name='paddle.FsClientParameter.fs_type', + index=0, + number=1, + type=14, + cpp_type=8, + label=1, + has_default_value=True, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='uri', + full_name='paddle.FsClientParameter.uri', + index=1, + number=2, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='user', + full_name='paddle.FsClientParameter.user', + index=2, + number=3, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor(name='passwd', + full_name='paddle.FsClientParameter.passwd', + index=3, + number=4, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='buffer_size', + full_name='paddle.FsClientParameter.buffer_size', + index=4, + number=5, + type=5, + cpp_type=1, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hadoop_bin', + full_name='paddle.FsClientParameter.hadoop_bin', + index=5, + number=51, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='afs_conf', + full_name='paddle.FsClientParameter.afs_conf', + index=6, + number=101, + type=9, + cpp_type=9, + label=1, + has_default_value=False, + default_value=_b("").decode('utf-8'), + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + options=None), + ], + extensions=[], + nested_types=[], + enum_types=[ + _FSCLIENTPARAMETER_FSAPITYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[], + serialized_start=4464, + serialized_end=4677, +) + +_PSPARAMETER.fields_by_name['worker_param'].message_type = _WORKERPARAMETER +_PSPARAMETER.fields_by_name['server_param'].message_type = _SERVERPARAMETER +_PSPARAMETER.fields_by_name[ + 'trainer_param'].message_type = _DOWNPOURTRAINERPARAMETER +_PSPARAMETER.fields_by_name['fs_client_param'].message_type = _FSCLIENTPARAMETER +_WORKERPARAMETER.fields_by_name[ + 'downpour_worker_param'].message_type = _DOWNPOURWORKERPARAMETER +_SERVERPARAMETER.fields_by_name[ + 'downpour_server_param'].message_type = _DOWNPOURSERVERPARAMETER +_DOWNPOURWORKERPARAMETER.fields_by_name[ + 'downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'dense_table'].message_type = _DENSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'sparse_table'].message_type = _SPARSETABLEPARAMETER +_DOWNPOURTRAINERPARAMETER.fields_by_name[ + 'program_config'].message_type = _PROGRAMCONFIG +_DOWNPOURSERVERPARAMETER.fields_by_name[ + 'downpour_table_param'].message_type = _TABLEPARAMETER +_DOWNPOURSERVERPARAMETER.fields_by_name[ + 'service_param'].message_type = _SERVERSERVICEPARAMETER +_TABLEPARAMETER.fields_by_name[ + 'accessor'].message_type = _TABLEACCESSORPARAMETER +_TABLEPARAMETER.fields_by_name['type'].enum_type = _TABLETYPE +_TABLEACCESSORPARAMETER.fields_by_name[ + 'sparse_sgd_param'].message_type = _SPARSESGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'dense_sgd_param'].message_type = _DENSESGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'downpour_accessor_param'].message_type = _DOWNPOURTABLEACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'table_accessor_save_param'].message_type = _TABLEACCESSORSAVEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'sparse_commonsgd_param'].message_type = _SPARSECOMMONSGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'embed_sgd_param'].message_type = _SPARSECOMMONSGDRULEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name[ + 'embedx_sgd_param'].message_type = _SPARSECOMMONSGDRULEPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name[ + 'naive'].message_type = _SPARSENAIVESGDRULEPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name[ + 'adagrad'].message_type = _SPARSEADAGRADSGDRULEPARAMETER +_SPARSECOMMONSGDRULEPARAMETER.fields_by_name[ + 'adam'].message_type = _SPARSEADAMSGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name['adam'].message_type = _ADAMSGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name['naive'].message_type = _NAIVESGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name[ + 'summary'].message_type = _SUMMARYSGDPARAMETER +_DENSESGDRULEPARAMETER.fields_by_name[ + 'moving_average'].message_type = _MOVINGAVERAGERULEPARAMETER +_FSCLIENTPARAMETER.fields_by_name[ + 'fs_type'].enum_type = _FSCLIENTPARAMETER_FSAPITYPE +_FSCLIENTPARAMETER_FSAPITYPE.containing_type = _FSCLIENTPARAMETER +DESCRIPTOR.message_types_by_name['PSParameter'] = _PSPARAMETER +DESCRIPTOR.message_types_by_name['WorkerParameter'] = _WORKERPARAMETER +DESCRIPTOR.message_types_by_name['ServerParameter'] = _SERVERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourWorkerParameter'] = _DOWNPOURWORKERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourTrainerParameter'] = _DOWNPOURTRAINERPARAMETER +DESCRIPTOR.message_types_by_name['ProgramConfig'] = _PROGRAMCONFIG +DESCRIPTOR.message_types_by_name['DenseTableParameter'] = _DENSETABLEPARAMETER +DESCRIPTOR.message_types_by_name['SparseTableParameter'] = _SPARSETABLEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourServerParameter'] = _DOWNPOURSERVERPARAMETER +DESCRIPTOR.message_types_by_name[ + 'ServerServiceParameter'] = _SERVERSERVICEPARAMETER +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'TableAccessorParameter'] = _TABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DownpourTableAccessorParameter'] = _DOWNPOURTABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name[ + 'TableAccessorSaveParameter'] = _TABLEACCESSORSAVEPARAMETER +DESCRIPTOR.message_types_by_name['PsRequestMessage'] = _PSREQUESTMESSAGE +DESCRIPTOR.message_types_by_name[ + 'SparseSGDRuleParameter'] = _SPARSESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'SparseCommonSGDRuleParameter'] = _SPARSECOMMONSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'SparseNaiveSGDRuleParameter'] = _SPARSENAIVESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'SparseAdagradSGDRuleParameter'] = _SPARSEADAGRADSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name[ + 'SparseAdamSGDParameter'] = _SPARSEADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name[ + 'DenseSGDRuleParameter'] = _DENSESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['AdamSGDParameter'] = _ADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name['NaiveSGDParameter'] = _NAIVESGDPARAMETER +DESCRIPTOR.message_types_by_name['SummarySGDParameter'] = _SUMMARYSGDPARAMETER +DESCRIPTOR.message_types_by_name[ + 'MovingAverageRuleParameter'] = _MOVINGAVERAGERULEPARAMETER +DESCRIPTOR.message_types_by_name['PsResponseMessage'] = _PSRESPONSEMESSAGE +DESCRIPTOR.message_types_by_name['FsClientParameter'] = _FSCLIENTPARAMETER +DESCRIPTOR.enum_types_by_name['TableType'] = _TABLETYPE +DESCRIPTOR.enum_types_by_name['PsCmdID'] = _PSCMDID + +PSParameter = _reflection.GeneratedProtocolMessageType( + 'PSParameter', + (_message.Message, ), + dict(DESCRIPTOR=_PSPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PSParameter) + )) +_sym_db.RegisterMessage(PSParameter) + +WorkerParameter = _reflection.GeneratedProtocolMessageType( + 'WorkerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_WORKERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.WorkerParameter) + )) +_sym_db.RegisterMessage(WorkerParameter) + +ServerParameter = _reflection.GeneratedProtocolMessageType( + 'ServerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SERVERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ServerParameter) + )) +_sym_db.RegisterMessage(ServerParameter) + +DownpourWorkerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourWorkerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURWORKERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourWorkerParameter) + )) +_sym_db.RegisterMessage(DownpourWorkerParameter) + +DownpourTrainerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourTrainerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURTRAINERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourTrainerParameter) + )) +_sym_db.RegisterMessage(DownpourTrainerParameter) + +ProgramConfig = _reflection.GeneratedProtocolMessageType( + 'ProgramConfig', + (_message.Message, ), + dict(DESCRIPTOR=_PROGRAMCONFIG, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ProgramConfig) + )) +_sym_db.RegisterMessage(ProgramConfig) + +DenseTableParameter = _reflection.GeneratedProtocolMessageType( + 'DenseTableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DENSETABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DenseTableParameter) + )) +_sym_db.RegisterMessage(DenseTableParameter) + +SparseTableParameter = _reflection.GeneratedProtocolMessageType( + 'SparseTableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SPARSETABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseTableParameter) + )) +_sym_db.RegisterMessage(SparseTableParameter) + +DownpourServerParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourServerParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DOWNPOURSERVERPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourServerParameter) + )) +_sym_db.RegisterMessage(DownpourServerParameter) + +ServerServiceParameter = _reflection.GeneratedProtocolMessageType( + 'ServerServiceParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SERVERSERVICEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.ServerServiceParameter) + )) +_sym_db.RegisterMessage(ServerServiceParameter) + +TableParameter = _reflection.GeneratedProtocolMessageType( + 'TableParameter', + (_message.Message, ), + dict(DESCRIPTOR=_TABLEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + +TableAccessorParameter = _reflection.GeneratedProtocolMessageType( + 'TableAccessorParameter', + (_message.Message, ), + dict(DESCRIPTOR=_TABLEACCESSORPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableAccessorParameter) + )) +_sym_db.RegisterMessage(TableAccessorParameter) + +DownpourTableAccessorParameter = _reflection.GeneratedProtocolMessageType( + 'DownpourTableAccessorParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_DOWNPOURTABLEACCESSORPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DownpourTableAccessorParameter) + )) +_sym_db.RegisterMessage(DownpourTableAccessorParameter) + +TableAccessorSaveParameter = _reflection.GeneratedProtocolMessageType( + 'TableAccessorSaveParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_TABLEACCESSORSAVEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.TableAccessorSaveParameter) + )) +_sym_db.RegisterMessage(TableAccessorSaveParameter) + +PsRequestMessage = _reflection.GeneratedProtocolMessageType( + 'PsRequestMessage', + (_message.Message, ), + dict(DESCRIPTOR=_PSREQUESTMESSAGE, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PsRequestMessage) + )) +_sym_db.RegisterMessage(PsRequestMessage) + +SparseSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'SparseSGDRuleParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SPARSESGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseSGDRuleParameter) + +SparseCommonSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'SparseCommonSGDRuleParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_SPARSECOMMONSGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseCommonSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseCommonSGDRuleParameter) + +SparseNaiveSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'SparseNaiveSGDRuleParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_SPARSENAIVESGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseNaiveSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseNaiveSGDRuleParameter) + +SparseAdagradSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'SparseAdagradSGDRuleParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_SPARSEADAGRADSGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseAdagradSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseAdagradSGDRuleParameter) + +SparseAdamSGDParameter = _reflection.GeneratedProtocolMessageType( + 'SparseAdamSGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SPARSEADAMSGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SparseAdamSGDParameter) + )) +_sym_db.RegisterMessage(SparseAdamSGDParameter) + +DenseSGDRuleParameter = _reflection.GeneratedProtocolMessageType( + 'DenseSGDRuleParameter', + (_message.Message, ), + dict(DESCRIPTOR=_DENSESGDRULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.DenseSGDRuleParameter) + )) +_sym_db.RegisterMessage(DenseSGDRuleParameter) + +AdamSGDParameter = _reflection.GeneratedProtocolMessageType( + 'AdamSGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_ADAMSGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.AdamSGDParameter) + )) +_sym_db.RegisterMessage(AdamSGDParameter) + +NaiveSGDParameter = _reflection.GeneratedProtocolMessageType( + 'NaiveSGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_NAIVESGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.NaiveSGDParameter) + )) +_sym_db.RegisterMessage(NaiveSGDParameter) + +SummarySGDParameter = _reflection.GeneratedProtocolMessageType( + 'SummarySGDParameter', + (_message.Message, ), + dict(DESCRIPTOR=_SUMMARYSGDPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.SummarySGDParameter) + )) +_sym_db.RegisterMessage(SummarySGDParameter) + +MovingAverageRuleParameter = _reflection.GeneratedProtocolMessageType( + 'MovingAverageRuleParameter', + (_message.Message, ), + dict( + DESCRIPTOR=_MOVINGAVERAGERULEPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.MovingAverageRuleParameter) + )) +_sym_db.RegisterMessage(MovingAverageRuleParameter) + +PsResponseMessage = _reflection.GeneratedProtocolMessageType( + 'PsResponseMessage', + (_message.Message, ), + dict(DESCRIPTOR=_PSRESPONSEMESSAGE, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.PsResponseMessage) + )) +_sym_db.RegisterMessage(PsResponseMessage) + +FsClientParameter = _reflection.GeneratedProtocolMessageType( + 'FsClientParameter', + (_message.Message, ), + dict(DESCRIPTOR=_FSCLIENTPARAMETER, + __module__='ps_pb2' + # @@protoc_insertion_point(class_scope:paddle.FsClientParameter) + )) +_sym_db.RegisterMessage(FsClientParameter) + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), + _b('\200\001\001\370\001\001')) +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/version.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/version.py new file mode 100644 index 0000000000000000000000000000000000000000..183c90d9dead6223a28cc2203774d29062bc0e2e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/parameter_server/version.py @@ -0,0 +1,11 @@ +from __future__ import print_function + +# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY + +from paddle.fluid.incubate.fleet.base.mode import Mode + +BUILD_MODE=Mode.TRANSPILER + +def is_transpiler(): + return Mode.TRANSPILER == BUILD_MODE + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0c32e26092f6ea25771279418582a24ea449ab2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/fleet_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/fleet_util.py new file mode 100644 index 0000000000000000000000000000000000000000..48ce51b372489fb334da8031000091f9560aac88 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/fleet_util.py @@ -0,0 +1,2200 @@ +# 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. +"""Fleet Utils.""" + +import collections +import copy +import json +import logging +import math +import numpy as np +import os +import sys +import time +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.log_helper import get_logger +from paddle.distributed.fleet.utils.fs import LocalFS, HDFSClient, AFSClient +from . import utils + +OpRole = core.op_proto_and_checker_maker.OpRole + +__all__ = ["FleetUtil", "GPUPSUtil"] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s %(levelname)s: %(message)s') + +fleet = None + + +class FleetUtil(object): + """ + FleetUtil provides some common functions for users' convenience. + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.rank0_print("my log") + + """ + + def __init__(self, mode="pslib"): + global fleet + op_maker = core.op_proto_and_checker_maker + self.op_role_key = op_maker.kOpRoleAttrName() + if mode == "pslib": + from paddle.fluid.incubate.fleet.parameter_server.pslib import fleet as fleet_pslib + fleet = fleet_pslib + elif mode == "transpiler": + from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler import fleet as fleet_transpiler + fleet = fleet_transpiler + else: + raise ValueError( + "Please choose one mode from [\"pslib\", \"transpiler\"]") + + def rank0_print(self, s): + """ + Worker of rank 0 print some log. + + Args: + s(str): string to print + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.rank0_print("my log") + + """ + if fleet.worker_index() != 0: + return + print(s) + sys.stdout.flush() + + def rank0_info(self, s): + """ + Worker of rank 0 print some log info. + + Args: + s(str): string to log + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.rank0_info("my log info") + + """ + if fleet.worker_index() != 0: + return + _logger.info(s) + + def rank0_error(self, s): + """ + Worker of rank 0 print some log error. + + Args: + s(str): string to log + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.rank0_error("my log error") + + """ + if fleet.worker_index() != 0: + return + _logger.error(s) + + def set_zero(self, + var_name, + scope=fluid.global_scope(), + place=fluid.CPUPlace(), + param_type="int64"): + """ + Set tensor of a Variable to zero. + + Args: + var_name(str): name of Variable + scope(Scope): Scope object, default is fluid.global_scope() + place(Place): Place object, default is fluid.CPUPlace() + param_type(str): param data type, default is int64 + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.set_zero(myvar.name, myscope) + + """ + param = scope.var(var_name).get_tensor() + param_array = np.zeros(param._get_dims()).astype(param_type) + param.set(param_array, place) + + def print_global_auc(self, + scope=fluid.global_scope(), + stat_pos="_generated_var_2", + stat_neg="_generated_var_3", + print_prefix=""): + r""" + Print global auc of all distributed workers. + + Args: + scope(Scope): Scope object, default is fluid.global_scope() + stat_pos(str): name of auc pos bucket Variable + stat_neg(str): name of auc neg bucket Variable + print_prefix(str): prefix of print auc + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.print_global_auc(myscope, stat_pos=stat_pos.name, + stat_neg=stat_neg.name) + + # below is part of model + emb = my_slot_net(slots, label) # emb can be fc layer of size 1 + similarity_norm = fluid.layers.sigmoid(fluid.layers.clip(\ + emb, min=-15.0, max=15.0), name="similarity_norm")\ + binary_predict = fluid.layers.concat(input=[\ + fluid.layers.elementwise_sub(\ + fluid.layers.ceil(similarity_norm), similarity_norm),\ + similarity_norm], axis=1) + auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \ + stat_neg] = fluid.layers.auc(input=binary_predict,\ + label=label, curve='ROC',\ + num_thresholds=4096) + + """ + auc_value = self.get_global_auc(scope, stat_pos, stat_neg) + self.rank0_print(print_prefix + " global auc = %s" % auc_value) + + def get_global_auc(self, + scope=fluid.global_scope(), + stat_pos="_generated_var_2", + stat_neg="_generated_var_3"): + """ + Get global auc of all distributed workers. + + Args: + scope(Scope): Scope object, default is fluid.global_scope() + stat_pos(str): name of auc pos bucket Variable + stat_neg(str): name of auc neg bucket Variable + + Returns: + auc_value(float), total_ins_num(int) + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + auc_value, _ = fleet_util.get_global_auc(myscope, + stat_pos=stat_pos, + stat_neg=stat_neg) + + """ + if scope.find_var(stat_pos) is None or scope.find_var(stat_neg) is None: + self.rank0_print("not found auc bucket") + return None + fleet._role_maker._barrier_worker() + # auc pos bucket + pos = np.array(scope.find_var(stat_pos).get_tensor()) + # auc pos bucket shape + old_pos_shape = np.array(pos.shape) + # reshape to one dim + pos = pos.reshape(-1) + global_pos = np.copy(pos) * 0 + # mpi allreduce + fleet._role_maker._all_reduce(pos, global_pos) + # reshape to its original shape + global_pos = global_pos.reshape(old_pos_shape) + + # auc neg bucket + neg = np.array(scope.find_var(stat_neg).get_tensor()) + old_neg_shape = np.array(neg.shape) + neg = neg.reshape(-1) + global_neg = np.copy(neg) * 0 + fleet._role_maker._all_reduce(neg, global_neg) + global_neg = global_neg.reshape(old_neg_shape) + + # calculate auc + num_bucket = len(global_pos[0]) + area = 0.0 + pos = 0.0 + neg = 0.0 + new_pos = 0.0 + new_neg = 0.0 + total_ins_num = 0 + for i in range(num_bucket): + index = num_bucket - 1 - i + new_pos = pos + global_pos[0][index] + total_ins_num += global_pos[0][index] + new_neg = neg + global_neg[0][index] + total_ins_num += global_neg[0][index] + area += (new_neg - neg) * (pos + new_pos) / 2 + pos = new_pos + neg = new_neg + + auc_value = None + if pos * neg == 0 or total_ins_num == 0: + auc_value = 0.5 + else: + auc_value = area / (pos * neg) + + fleet._role_maker._barrier_worker() + return auc_value + + def load_fleet_model_one_table(self, table_id, path): + """ + load pslib model to one table + + Args: + table_id(int): load model to one table, default is None, which mean + load all table. + path(str): model path + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.load_fleet_model("hdfs:/my/model/path", table_id=1) + """ + fleet.load_one_table(table_id, path) + + def load_fleet_model(self, path, mode=0): + """ + load pslib model + + Args: + path(str): model path + mode(str): 0 or 1, which means load checkpoint or delta model, + default is 0 + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + + fleet_util.load_fleet_model("hdfs:/my/model/path") + + fleet_util.load_fleet_model("hdfs:/my/model/path", mode=0) + + """ + fleet.init_server(path, mode=mode) + + def save_fleet_model(self, path, mode=0): + """ + save pslib model + + Args: + path(str): model path + mode(str): 0 or 1, which means save checkpoint or delta model, + default is 0 + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_fleet_model("hdfs:/my/model/path") + + """ + fleet.save_persistables(None, path, mode=mode) + + def _get_xbox_str(self, + output_path, + day, + model_path, + xbox_base_key, + data_path, + hadoop_fs_name, + monitor_data={}, + mode="patch"): + xbox_dict = collections.OrderedDict() + if mode == "base": + xbox_dict["id"] = str(xbox_base_key) + elif mode == "patch": + xbox_dict["id"] = str(int(time.time())) + else: + print("warning: unknown mode %s, set it to patch" % mode) + mode = "patch" + xbox_dict["id"] = str(int(time.time())) + xbox_dict["key"] = str(xbox_base_key) + if model_path.startswith("hdfs:") or model_path.startswith("afs:"): + model_path = model_path[model_path.find(":") + 1:] + xbox_dict["input"] = hadoop_fs_name + model_path.rstrip("/") + "/000" + xbox_dict["record_count"] = "111111" + xbox_dict["partition_type"] = "2" + xbox_dict["job_name"] = "default_job_name" + xbox_dict["ins_tag"] = "feasign" + xbox_dict["ins_path"] = data_path + job_id_with_host = os.popen("echo -n ${JOB_ID}").read().strip() + instance_id = os.popen("echo -n ${INSTANCE_ID}").read().strip() + start_pos = instance_id.find(job_id_with_host) + end_pos = instance_id.find("--") + if start_pos != -1 and end_pos != -1: + job_id_with_host = instance_id[start_pos:end_pos] + xbox_dict["job_id"] = job_id_with_host + # currently hard code here, set monitor_data empty string + xbox_dict["monitor_data"] = "" + xbox_dict["monitor_path"] = output_path.rstrip("/") + "/monitor/" \ + + day + ".txt" + xbox_dict["mpi_size"] = str(fleet.worker_num()) + return json.dumps(xbox_dict) + + def write_model_donefile(self, + output_path, + day, + pass_id, + xbox_base_key, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME", + donefile_name="donefile.txt"): + """ + write donefile when save model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + xbox_base_key(str|int): xbox base key + hadoop_fs_name(str): hdfs/afs fs name + hadoop_fs_ugi(str): hdfs/afs fs ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + donefile_name(str): donefile name, default is "donefile.txt" + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.write_model_donefile(output_path="hdfs:/my/output", + model_path="hdfs:/my/model", + day=20190723, + pass_id=66, + xbox_base_key=int(time.time()), + hadoop_fs_name="hdfs://xxx", + hadoop_fs_ugi="user,passwd") + + """ + day = str(day) + pass_id = str(pass_id) + xbox_base_key = int(xbox_base_key) + + if pass_id != "-1": + suffix_name = "/%s/%s/" % (day, pass_id) + model_path = output_path.rstrip("/") + suffix_name + else: + suffix_name = "/%s/0/" % day + model_path = output_path.rstrip("/") + suffix_name + + if fleet.worker_index() == 0: + donefile_path = output_path + "/" + donefile_name + content = "%s\t%lu\t%s\t%s\t%d" % (day, xbox_base_key,\ + model_path, pass_id, 0) + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if client.is_file(donefile_path): + pre_content = client.cat(donefile_path) + pre_content_list = pre_content.split("\n") + day_list = [i.split("\t")[0] for i in pre_content_list] + pass_list = [i.split("\t")[3] for i in pre_content_list] + exist = False + for i in range(len(day_list)): + if int(day) == int(day_list[i]) and \ + int(pass_id) == int(pass_list[i]): + exist = True + break + if not exist: + with open(donefile_name, "w") as f: + f.write(pre_content + "\n") + f.write(content + "\n") + client.delete(donefile_path) + client.upload(donefile_name, output_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + else: + self.rank0_error("not write %s because %s/%s already " + "exists" % (donefile_name, day, pass_id)) + else: + with open(donefile_name, "w") as f: + f.write(content + "\n") + client.upload(donefile_name, output_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + fleet._role_maker._barrier_worker() + + def write_xbox_donefile(self, + output_path, + day, + pass_id, + xbox_base_key, + data_path, + hadoop_fs_name, + hadoop_fs_ugi, + monitor_data={}, + hadoop_home="$HADOOP_HOME", + donefile_name=None): + """ + write delta donefile or xbox base donefile + + Args: + output_path(str): output path + day(str|int): training day of model + pass_id(str|int): training pass id of model + xbox_base_key(str|int): xbox base key + data_path(str|list): training data path + hadoop_fs_name(str): hdfs/afs fs name + hadoop_fs_ugi(str): hdfs/afs fs ugi + monitor_data(dict): metrics + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + donefile_name(str): donefile name, default is None" + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.write_xbox_donefile( + output_path="hdfs:/my/output/", + model_path="hdfs:/my/output/20190722/01", + day=20190722, + pass_id=1, + xbox_base_key=int(time.time()), + data_path="hdfs:/my/data/", + hadoop_fs_name="hdfs://xxx", + hadoop_fs_ugi="user,passwd", + monitor_data={} + ) + + """ + day = str(day) + pass_id = str(pass_id) + xbox_base_key = int(xbox_base_key) + mode = None + + if pass_id != "-1": + mode = "patch" + suffix_name = "/%s/delta-%s/" % (day, pass_id) + model_path = output_path.rstrip("/") + suffix_name + if donefile_name is None: + donefile_name = "xbox_patch_done.txt" + else: + mode = "base" + suffix_name = "/%s/base/" % day + model_path = output_path.rstrip("/") + suffix_name + if donefile_name is None: + donefile_name = "xbox_base_done.txt" + + if isinstance(data_path, list): + data_path = ",".join(data_path) + + if fleet.worker_index() == 0: + donefile_path = output_path + "/" + donefile_name + xbox_str = self._get_xbox_str(output_path, day, model_path, \ + xbox_base_key, data_path, hadoop_fs_name, monitor_data={}, + mode=mode) + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if client.is_file(donefile_path): + pre_content = client.cat(donefile_path) + last_dict = json.loads(pre_content.split("\n")[-1]) + last_day = last_dict["input"].split("/")[-3] + last_pass = last_dict["input"].split("/")[-2].split("-")[-1] + exist = False + if int(day) < int(last_day) or \ + int(day) == int(last_day) and \ + int(pass_id) <= int(last_pass): + exist = True + if not exist: + with open(donefile_name, "w") as f: + f.write(pre_content + "\n") + f.write(xbox_str + "\n") + client.delete(donefile_path) + client.upload(donefile_name, output_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + else: + self.rank0_error("not write %s because %s/%s already " + "exists" % (donefile_name, day, pass_id)) + else: + with open(donefile_name, "w") as f: + f.write(xbox_str + "\n") + client.upload(donefile_name, output_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + fleet._role_maker._barrier_worker() + + def write_cache_donefile(self, + output_path, + day, + pass_id, + key_num, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME", + donefile_name="sparse_cache.meta", + **kwargs): + """ + write cache donefile + + Args: + output_path(str): output path + day(str|int): training day of model + pass_id(str|int): training pass id of model + key_num(str|int): save cache return value + hadoop_fs_name(str): hdfs/afs fs name + hadoop_fs_ugi(str): hdfs/afs fs ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + donefile_name(str): donefile name, default is "sparse_cache.meta" + kwargs(dict): user defined properties + file_num(int): cache file num + table_id(int): cache table id + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.write_cache_donefile( + output_path="hdfs:/my/output/", + day=20190722, + pass_id=1, + key_num=123456, + hadoop_fs_name="hdfs://xxx", + hadoop_fs_ugi="user,passwd", + ) + + """ + day = str(day) + pass_id = str(pass_id) + key_num = int(key_num) + file_num = kwargs.get("file_num", 16) + table_id = kwargs.get("table_id", 0) + + if pass_id != "-1": + suffix_name = "/%s/delta-%s/%03d_cache" % (day, pass_id, table_id) + model_path = output_path.rstrip("/") + suffix_name + else: + suffix_name = "/%s/base/%03d_cache" % (day, table_id) + model_path = output_path.rstrip("/") + suffix_name + + if fleet.worker_index() == 0: + donefile_path = model_path + "/" + donefile_name + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if client.is_file(donefile_path): + self.rank0_error( \ + "not write because %s already exists" % donefile_path) + else: + meta_str = "file_prefix:part\npart_num:%s\nkey_num:%d\n" \ + % (file_num, key_num) + with open(donefile_name, "w") as f: + f.write(meta_str) + client.upload(donefile_name, model_path) + self.rank0_error("write %s succeed" % donefile_path) + fleet._role_maker._barrier_worker() + + def load_model(self, output_path, day, pass_id): + """ + load pslib model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.load_model("hdfs:/my/path", 20190722, 88) + + """ + day = str(day) + pass_id = str(pass_id) + suffix_name = "/%s/%s/" % (day, pass_id) + load_path = output_path + suffix_name + self.rank0_error("going to load_model %s" % load_path) + self.load_fleet_model(load_path) + self.rank0_error("load_model done") + + def save_model(self, output_path, day, pass_id): + """ + save pslib model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_model("hdfs:/my/path", 20190722, 88) + + """ + day = str(day) + pass_id = str(pass_id) + suffix_name = "/%s/%s/" % (day, pass_id) + model_path = output_path + suffix_name + self.rank0_print("going to save_model %s" % model_path) + self.save_fleet_model(model_path) + self.rank0_print("save_model done") + + def save_batch_model(self, output_path, day): + """ + save batch model + + Args: + output_path(str): output path + day(str|int): training day + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_batch_model("hdfs:/my/path", 20190722) + + """ + day = str(day) + suffix_name = "/%s/0/" % day + model_path = output_path + suffix_name + self.rank0_print("going to save_model %s" % model_path) + fleet.save_persistables(None, model_path, mode=3) + self.rank0_print("save_batch_model done") + + def save_delta_model(self, output_path, day, pass_id): + """ + save delta model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_batch_model("hdfs:/my/path", 20190722, 88) + + """ + day = str(day) + pass_id = str(pass_id) + suffix_name = "/%s/delta-%s/" % (day, pass_id) + model_path = output_path + suffix_name + self.rank0_print("going to save_delta_model %s" % model_path) + fleet.save_persistables(None, model_path, mode=1) + self.rank0_print("save_delta_model done") + + def save_xbox_base_model(self, output_path, day): + """ + save xbox base model + + Args: + output_path(str): output path + day(str|int): training day + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_xbox_base_model("hdfs:/my/path", 20190722, 88) + + """ + day = str(day) + suffix_name = "/%s/base/" % day + model_path = output_path + suffix_name + self.rank0_print("going to save_xbox_base_model " + model_path) + fleet.save_persistables(None, model_path, mode=2) + self.rank0_print("save_xbox_base_model done") + + def save_cache_model(self, output_path, day, pass_id, mode=1, **kwargs): + """ + save cache model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + mode(str|int): save mode + kwargs(dict): user defined properties + table_id(int): table id to save cache + + Returns: + key_num(int): cache key num + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_cache_model("hdfs:/my/path", 20190722, 88) + + """ + day = str(day) + pass_id = str(pass_id) + mode = int(mode) + table_id = kwargs.get("table_id", 0) + suffix_name = "/%s/delta-%s" % (day, pass_id) + model_path = output_path.rstrip("/") + suffix_name + self.rank0_print("going to save_cache_model %s" % model_path) + key_num = fleet.save_cache_model(None, + model_path, + mode=mode, + table_id=table_id) + self.rank0_print("save_cache_model done") + return key_num + + def save_cache_base_model(self, output_path, day, **kwargs): + """ + save cache model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + kwargs(dict): user defined properties + table_id(int): table id to save cache + + Returns: + key_num(int): cache key num + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_cache_base_model("hdfs:/my/path", 20190722) + + """ + day = str(day) + table_id = kwargs.get("table_id", 0) + suffix_name = "/%s/base" % day + model_path = output_path.rstrip("/") + suffix_name + self.rank0_print("going to save_cache_base_model %s" % model_path) + key_num = fleet.save_cache_model(None, + model_path, + mode=2, + table_id=table_id) + self.rank0_print("save_cache_base_model done") + return key_num + + def pull_all_dense_params(self, scope, program): + """ + pull all dense params in trainer of rank 0 + + Args: + scope(Scope): fluid Scope + program(Program): fluid Program + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.pull_all_dense_params(my_scope, my_program) + + """ + fleet._role_maker._barrier_worker() + if fleet._role_maker.is_first_worker(): + prog_id = str(id(program)) + tables = fleet._opt_info["program_id_to_worker"][prog_id].\ + get_desc().dense_table + prog_conf = fleet._opt_info['program_configs'][prog_id] + prog_tables = {} + for key in prog_conf: + if "dense" not in key: + continue + for table_id in prog_conf[key]: + prog_tables[int(table_id)] = 0 + for table in tables: + if int(table.table_id) not in prog_tables: + continue + var_name_list = [] + for i in range(0, len(table.dense_variable_name)): + var_name = table.dense_variable_name[i] + if scope.find_var(var_name) is None: + raise ValueError("var " + var_name + + " not found in scope " + + "when pull dense") + var_name_list.append(var_name) + fleet._fleet_ptr.pull_dense(scope, int(table.table_id), + var_name_list) + fleet._role_maker._barrier_worker() + + def save_paddle_inference_model(self, + executor, + scope, + program, + feeded_vars, + target_vars, + output_path, + day, + pass_id, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME", + save_combine=True): + """ + save paddle inference model, and upload to hdfs dnn_plugin path + + Args: + executor(Executor): fluid Executor + scope(Scope): fluid Scope + program(Program): fluid Program + feeded_vars(list[Variable]): feed vars + target_vars(list[variable]): fetch vars + output_path(str): hdfs/afs output path + day(str|int): training day + pass_id(str|int): training pass + hadoop_fs_name(str): hadoop fs name + hadoop_fs_ugi(str): hadoop fs ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + save_combine(bool): whether to save in a file or separate files, + default is True + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_paddle_inference_model(exe, + join_scope, + join_program, + feeded_vars, + target_vars, + "hdfs:/my/output/path/", + day=20190727, + pass_id=6, + hadoop_fs_name="xxx", + hadoop_fs_ugi="xxx,xxx") + """ + day = str(day) + pass_id = str(pass_id) + feeded_var_names = [i.name for i in feeded_vars] + model_name = "inference_model" + # pull dense before save + self.pull_all_dense_params(scope, program) + if fleet.worker_index() == 0: + with fluid.scope_guard(scope): + if save_combine: + fluid.io.save_inference_model( + dirname=model_name, + feeded_var_names=feeded_var_names, + target_vars=target_vars, + executor=executor, + main_program=program.clone(), + params_filename="params") + else: + fluid.io.save_inference_model( + dirname=model_name, + feeded_var_names=feeded_var_names, + target_vars=target_vars, + executor=executor, + main_program=program.clone()) + + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + + if pass_id == "-1": + dest = "%s/%s/base/dnn_plugin/" % (output_path, day) + else: + dest = "%s/%s/delta-%s/dnn_plugin/" % (output_path, day, + pass_id) + if not client.is_exist(dest): + client.makedirs(dest) + + client.upload(model_name, dest, multi_processes=5, overwrite=True) + + fleet._role_maker._barrier_worker() + + def save_paddle_params(self, + executor, + scope, + program, + model_name, + output_path, + day, + pass_id, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME", + var_names=None, + save_combine=True): + """ + save paddle model, and upload to hdfs dnn_plugin path + + Args: + executor(Executor): fluid Executor + scope(Scope): fluid Scope + program(Program): fluid Program + model_name(str): save model local dir or filename + output_path(str): hdfs/afs output path + day(str|int): training day + pass_id(str|int): training pass + hadoop_fs_name(str): hadoop fs name + hadoop_fs_ugi(str): hadoop fs ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + var_names(list): save persistable var names, default is None + save_combine(bool): whether to save in a file or separate files, + default is True + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.save_paddle_params(exe, + join_scope, + join_program, + "paddle_dense.model.0", + "hdfs:/my/output/path/", + day=20190727, + pass_id=6, + hadoop_fs_name="xxx", + hadoop_fs_ugi="xxx,xxx", + var_names=join_all_var_names) + fleet_util.save_paddle_params(exe, + join_scope, + join_program, + "paddle_dense.model.usr.0", + "hdfs:/my/output/path/", + day=20190727, + pass_id=6, + hadoop_fs_name="xxx", + hadoop_fs_ugi="xxx,xxx", + var_names=join_user_var_names) + fleet_util.save_paddle_params(exe, + join_scope, + join_program, + "paddle_dense.model.item.0", + "hdfs:/my/output/path/", + day=20190727, + pass_id=6, + hadoop_fs_name="xxx", + hadoop_fs_ugi="xxx,xxx", + var_names=join_user_item_names) + + """ + day = str(day) + pass_id = str(pass_id) + # pull dense before save + self.pull_all_dense_params(scope, program) + if fleet.worker_index() == 0: + vars = [program.global_block().var(i) for i in var_names] + with fluid.scope_guard(scope): + if save_combine: + fluid.io.save_vars(executor, + "./", + program, + vars=vars, + filename=model_name) + else: + fluid.io.save_vars(executor, model_name, program, vars=vars) + + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + + if pass_id == "-1": + dest = "%s/%s/base/dnn_plugin/" % (output_path, day) + else: + dest = "%s/%s/delta-%s/dnn_plugin/" % (output_path, day, + pass_id) + if not client.is_exist(dest): + client.mkdirs(dest) + client.upload(model_name, dest, multi_processes=5, overwrite=True) + + fleet._role_maker._barrier_worker() + + def get_last_save_xbox_base(self, + output_path, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME"): + r""" + get last saved base xbox info from xbox_base_done.txt + + Args: + output_path(str): output path + hadoop_fs_name(str): hdfs/afs fs_name + hadoop_fs_ugi(str): hdfs/afs fs_ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + + Returns: + [last_save_day, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + last_save_day, last_path, xbox_base_key = \ + fleet_util.get_last_save_xbox_base("hdfs:/my/path", 20190722, + 88) + + """ + donefile_path = output_path + "/xbox_base_done.txt" + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if not client.is_file(donefile_path): + return [-1, -1, int(time.time())] + pre_content = client.cat(donefile_path) + last_dict = json.loads(pre_content.split("\n")[-1]) + last_day = int(last_dict["input"].split("/")[-3]) + last_path = "/".join(last_dict["input"].split("/")[:-1]) + xbox_base_key = int(last_dict["key"]) + return [last_day, last_path, xbox_base_key] + + def get_last_save_xbox(self, + output_path, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME"): + r""" + get last saved xbox info from xbox_patch_done.txt + + Args: + output_path(str): output path + hadoop_fs_name(str): hdfs/afs fs_name + hadoop_fs_ugi(str): hdfs/afs fs_ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + + Returns: + [last_save_day, last_save_pass, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_save_pass(int): pass id of saved + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + last_save_day, last_save_pass, last_path, xbox_base_key = \ + fleet_util.get_last_save_xbox("hdfs:/my/path", 20190722, 88) + + """ + donefile_path = output_path + "/xbox_patch_done.txt" + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if not client.is_file(donefile_path): + return [-1, -1, "", int(time.time())] + pre_content = client.cat(donefile_path) + last_dict = json.loads(pre_content.split("\n")[-1]) + last_day = int(last_dict["input"].split("/")[-3]) + last_pass = int(last_dict["input"].split("/")[-2].split("-")[-1]) + last_path = "/".join(last_dict["input"].split("/")[:-1]) + xbox_base_key = int(last_dict["key"]) + return [last_day, last_pass, last_path, xbox_base_key] + + def get_last_save_model(self, + output_path, + hadoop_fs_name, + hadoop_fs_ugi, + hadoop_home="$HADOOP_HOME"): + r""" + get last saved model info from donefile.txt + + Args: + output_path(str): output path + hadoop_fs_name(str): hdfs/afs fs_name + hadoop_fs_ugi(str): hdfs/afs fs_ugi + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + + Returns: + [last_save_day, last_save_pass, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_save_pass(int): pass id of saved + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + last_save_day, last_save_pass, last_path, xbox_base_key = \ + fleet_util.get_last_save_model("hdfs:/my/path", 20190722, 88) + + """ + last_save_day = -1 + last_save_pass = -1 + last_path = "" + donefile_path = output_path + "/donefile.txt" + configs = { + "fs.default.name": hadoop_fs_name, + "hadoop.job.ugi": hadoop_fs_ugi + } + client = HDFSClient(hadoop_home, configs) + if not client.is_file(donefile_path): + return [-1, -1, "", int(time.time())] + content = client.cat(donefile_path) + content = content.split("\n")[-1].split("\t") + last_save_day = int(content[0]) + last_save_pass = int(content[3]) + last_path = content[2] + xbox_base_key = int(content[1]) + return [last_save_day, last_save_pass, last_path, xbox_base_key] + + def get_online_pass_interval(self, days, hours, split_interval, + split_per_pass, is_data_hourly_placed): + """ + get online pass interval + + Args: + days(str): days to train + hours(str): hours to train + split_interval(int|str): split interval + split_per_pass(int}str): split per pass + is_data_hourly_placed(bool): is data hourly placed + + Returns: + online_pass_interval(list) + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + online_pass_interval = fleet_util.get_online_pass_interval( + days="{20190720..20190729}", + hours="{0..23}", + split_interval=5, + split_per_pass=2, + is_data_hourly_placed=False) + + """ + days = os.popen("echo -n " + days).read().split(" ") + hours = os.popen("echo -n " + hours).read().split(" ") + split_interval = int(split_interval) + split_per_pass = int(split_per_pass) + splits_per_day = 24 * 60 // split_interval + pass_per_day = splits_per_day // split_per_pass + left_train_hour = int(hours[0]) + right_train_hour = int(hours[-1]) + + start = 0 + split_path = [] + for i in range(splits_per_day): + h = start // 60 + m = start % 60 + if h < left_train_hour or h > right_train_hour: + start += split_interval + continue + if is_data_hourly_placed: + split_path.append("%02d" % h) + else: + split_path.append("%02d%02d" % (h, m)) + start += split_interval + + start = 0 + online_pass_interval = [] + for i in range(pass_per_day): + online_pass_interval.append([]) + for j in range(start, start + split_per_pass): + online_pass_interval[i].append(split_path[j]) + start += split_per_pass + + return online_pass_interval + + def get_global_metrics(self, + scope=fluid.global_scope(), + stat_pos_name="_generated_var_2", + stat_neg_name="_generated_var_3", + sqrerr_name="sqrerr", + abserr_name="abserr", + prob_name="prob", + q_name="q", + pos_ins_num_name="pos", + total_ins_num_name="total"): + r""" + get global metrics, including auc, bucket_error, mae, rmse, + actual_ctr, predicted_ctr, copc, mean_predict_qvalue, total_ins_num. + + Args: + scope(Scope): Scope object, default is fluid.global_scope() + stat_pos_name(str): name of auc pos bucket Variable + stat_neg_name(str): name of auc neg bucket Variable + sqrerr_name(str): name of sqrerr Variable + abserr_name(str): name of abserr Variable + prob_name(str): name of prob Variable + q_name(str): name of q Variable + pos_ins_num_name(str): name of pos ins num Variable + total_ins_num_name(str): name of total ins num Variable + + Returns: + [auc, bucket_error, mae, rmse, actual_ctr, predicted_ctr, copc, + mean_predict_qvalue, total_ins_num] + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + metric_list = fleet_util.get_global_metrics(myscope, + stat_pos.name, + stat_neg.name, + local_sqrerr.name, + local_abserr.name, + local_prob.name, + local_q.name, + local_pos_ins.name, + local_total_ins.name) + + # below is part of example model + label = fluid.layers.data(name="click", shape=[-1, 1],\ + dtype="int64", lod_level=0, append_batch_size=False) + emb = my_slot_net(slots, label) # emb can be fc layer of size 1 + similarity_norm = fluid.layers.sigmoid(fluid.layers.clip(\ + emb, min=-15.0, max=15.0), name="similarity_norm")\ + binary_predict = fluid.layers.concat(input=[\ + fluid.layers.elementwise_sub(\ + fluid.layers.ceil(similarity_norm), similarity_norm),\ + similarity_norm], axis=1) + auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \ + stat_neg] = fluid.layers.auc(input=binary_predict,\ + label=label, curve='ROC',\ + num_thresholds=4096) + local_sqrerr, local_abserr, local_prob, local_q, local_pos_ins,\ + local_total_ins = fluid.contrib.layers.ctr_metric_bundle(\ + similarity_norm, label) + + """ + if scope.find_var(stat_pos_name) is None or \ + scope.find_var(stat_neg_name) is None: + self.rank0_print("not found auc bucket") + return [None] * 9 + elif scope.find_var(sqrerr_name) is None: + self.rank0_print("not found sqrerr_name=%s" % sqrerr_name) + return [None] * 9 + elif scope.find_var(abserr_name) is None: + self.rank0_print("not found abserr_name=%s" % abserr_name) + return [None] * 9 + elif scope.find_var(prob_name) is None: + self.rank0_print("not found prob_name=%s" % prob_name) + return [None] * 9 + elif scope.find_var(q_name) is None: + self.rank0_print("not found q_name=%s" % q_name) + return [None] * 9 + elif scope.find_var(pos_ins_num_name) is None: + self.rank0_print("not found pos_ins_num_name=%s" % pos_ins_num_name) + return [None] * 9 + elif scope.find_var(total_ins_num_name) is None: + self.rank0_print("not found total_ins_num_name=%s" % \ + total_ins_num_name) + return [None] * 9 + + # barrier worker to ensure all workers finished training + fleet._role_maker._barrier_worker() + + # get auc + auc = self.get_global_auc(scope, stat_pos_name, stat_neg_name) + pos = np.array(scope.find_var(stat_pos_name).get_tensor()) + # auc pos bucket shape + old_pos_shape = np.array(pos.shape) + # reshape to one dim + pos = pos.reshape(-1) + global_pos = np.copy(pos) * 0 + # mpi allreduce + fleet._role_maker._all_reduce(pos, global_pos) + # reshape to its original shape + global_pos = global_pos.reshape(old_pos_shape) + # auc neg bucket + neg = np.array(scope.find_var(stat_neg_name).get_tensor()) + old_neg_shape = np.array(neg.shape) + neg = neg.reshape(-1) + global_neg = np.copy(neg) * 0 + fleet._role_maker._all_reduce(neg, global_neg) + global_neg = global_neg.reshape(old_neg_shape) + + num_bucket = len(global_pos[0]) + + def get_metric(name): + metric = np.array(scope.find_var(name).get_tensor()) + old_metric_shape = np.array(metric.shape) + metric = metric.reshape(-1) + global_metric = np.copy(metric) * 0 + fleet._role_maker._all_reduce(metric, global_metric) + global_metric = global_metric.reshape(old_metric_shape) + return global_metric[0] + + global_sqrerr = get_metric(sqrerr_name) + global_abserr = get_metric(abserr_name) + global_prob = get_metric(prob_name) + global_q_value = get_metric(q_name) + # note: get ins_num from auc bucket is not actual value, + # so get it from metric op + pos_ins_num = get_metric(pos_ins_num_name) + total_ins_num = get_metric(total_ins_num_name) + neg_ins_num = total_ins_num - pos_ins_num + + mae = global_abserr / total_ins_num + rmse = math.sqrt(global_sqrerr / total_ins_num) + return_actual_ctr = pos_ins_num / total_ins_num + predicted_ctr = global_prob / total_ins_num + mean_predict_qvalue = global_q_value / total_ins_num + copc = 0.0 + if abs(predicted_ctr > 1e-6): + copc = return_actual_ctr / predicted_ctr + + # calculate bucket error + last_ctr = -1.0 + impression_sum = 0.0 + ctr_sum = 0.0 + click_sum = 0.0 + error_sum = 0.0 + error_count = 0.0 + click = 0.0 + show = 0.0 + ctr = 0.0 + adjust_ctr = 0.0 + relative_error = 0.0 + actual_ctr = 0.0 + relative_ctr_error = 0.0 + k_max_span = 0.01 + k_relative_error_bound = 0.05 + for i in range(num_bucket): + click = global_pos[0][i] + show = global_pos[0][i] + global_neg[0][i] + ctr = float(i) / num_bucket + if abs(ctr - last_ctr) > k_max_span: + last_ctr = ctr + impression_sum = 0.0 + ctr_sum = 0.0 + click_sum = 0.0 + impression_sum += show + ctr_sum += ctr * show + click_sum += click + if impression_sum == 0: + continue + adjust_ctr = ctr_sum / impression_sum + if adjust_ctr == 0: + continue + relative_error = \ + math.sqrt((1 - adjust_ctr) / (adjust_ctr * impression_sum)) + if relative_error < k_relative_error_bound: + actual_ctr = click_sum / impression_sum + relative_ctr_error = abs(actual_ctr / adjust_ctr - 1) + error_sum += relative_ctr_error * impression_sum + error_count += impression_sum + last_ctr = -1 + + bucket_error = error_sum / error_count if error_count > 0 else 0.0 + + return [ + auc, bucket_error, mae, rmse, return_actual_ctr, predicted_ctr, + copc, mean_predict_qvalue, + int(total_ins_num) + ] + + def print_global_metrics(self, + scope=fluid.global_scope(), + stat_pos_name="_generated_var_2", + stat_neg_name="_generated_var_3", + sqrerr_name="sqrerr", + abserr_name="abserr", + prob_name="prob", + q_name="q", + pos_ins_num_name="pos", + total_ins_num_name="total", + print_prefix=""): + r""" + print global metrics, including auc, bucket_error, mae, rmse, + actual_ctr, predicted_ctr, copc, mean_predict_qvalue, total_ins_num. + + Args: + scope(Scope): Scope object, default is fluid.global_scope() + stat_pos_name(str): name of auc pos bucket Variable + stat_neg_name(str): name of auc neg bucket Variable + sqrerr_name(str): name of sqrerr Variable + abserr_name(str): name of abserr Variable + prob_name(str): name of prob Variable + q_name(str): name of q Variable + pos_ins_num_name(str): name of pos ins num Variable + total_ins_num_name(str): name of total ins num Variable + print_prefix(str): print prefix + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + fleet_util.print_global_metrics(myscope, + stat_pos.name, + stat_neg.name, + local_sqrerr.name, + local_abserr.name, + local_prob.name, + local_q.name, + local_pos_ins.name, + local_total_ins.name) + + # below is part of model + label = fluid.layers.data(name="click", shape=[-1, 1],\ + dtype="int64", lod_level=0, append_batch_size=False) + emb = my_slot_net(slots, label) # emb can be fc layer of size 1 + similarity_norm = fluid.layers.sigmoid(fluid.layers.clip(\ + emb, min=-15.0, max=15.0), name="similarity_norm")\ + binary_predict = fluid.layers.concat(input=[\ + fluid.layers.elementwise_sub(\ + fluid.layers.ceil(similarity_norm), similarity_norm),\ + similarity_norm], axis=1) + auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, \ + stat_neg] = fluid.layers.auc(input=binary_predict,\ + label=label, curve='ROC',\ + num_thresholds=4096) + local_sqrerr, local_abserr, local_prob, local_q, local_pos_ins, \ + local_total_ins = fluid.contrib.layers.ctr_metric_bundle(\ + similarity_norm, label) + + """ + if scope.find_var(stat_pos_name) is None or \ + scope.find_var(stat_neg_name) is None: + self.rank0_print("not found auc bucket") + return + elif scope.find_var(sqrerr_name) is None: + self.rank0_print("not found sqrerr_name=%s" % sqrerr_name) + return + elif scope.find_var(abserr_name) is None: + self.rank0_print("not found abserr_name=%s" % abserr_name) + return + elif scope.find_var(prob_name) is None: + self.rank0_print("not found prob_name=%s" % prob_name) + return + elif scope.find_var(q_name) is None: + self.rank0_print("not found q_name=%s" % q_name) + return + elif scope.find_var(pos_ins_num_name) is None: + self.rank0_print("not found pos_ins_num_name=%s" % pos_ins_num_name) + return + elif scope.find_var(total_ins_num_name) is None: + self.rank0_print("not found total_ins_num_name=%s" % \ + total_ins_num_name) + return + + auc, bucket_error, mae, rmse, actual_ctr, predicted_ctr, copc,\ + mean_predict_qvalue, total_ins_num = self.get_global_metrics(\ + scope, stat_pos_name, stat_neg_name, sqrerr_name, abserr_name,\ + prob_name, q_name, pos_ins_num_name, total_ins_num_name) + self.rank0_print( + "%s global AUC=%.6f BUCKET_ERROR=%.6f MAE=%.6f " + "RMSE=%.6f Actural_CTR=%.6f Predicted_CTR=%.6f " + "COPC=%.6f MEAN Q_VALUE=%.6f Ins number=%s" % + (print_prefix, auc, bucket_error, mae, rmse, actual_ctr, + predicted_ctr, copc, mean_predict_qvalue, total_ins_num)) + + def program_type_trans(self, prog_dir, prog_fn, is_text): + return utils.program_type_trans(prog_dir, prog_fn, is_text) + + def draw_from_program_file(self, model_filename, is_text, output_dir, + output_filename): + """draw program from file""" + program = utils.load_program(model_filename, is_text) + utils.graphviz(program.global_block(), output_dir, output_filename) + + def draw_from_program(self, program, output_dir, output_name): + """draw Program""" + utils.graphviz(program.global_block(), output_dir, output_name) + + def check_two_programs(self, config): + train_prog = utils.load_program(config.train_prog_path, + config.is_text_train_program) + pruned_prog = utils.load_program(config.pruned_prog_path, + config.is_text_pruned_program) + if config.draw: + pruned_dir = os.path.dirname(config.pruned_prog_path) + self.draw_from_program(pruned_prog, pruned_dir, + config.draw_out_name) + res = utils.check_pruned_program_vars(train_prog, pruned_prog) + if res: + _logger.info("check_programs succeed.") + else: + _logger.info( + "check_programs failed. pruned program and train program not match!" + ) + return res + + def check_vars_and_dump(self, config): + _logger.info("start check_vars_and_dump.") + results = utils.check_saved_vars_try_dump( + config.dump_model_dir, config.dump_program_filename, + config.is_text_dump_program, config.feed_config, + config.fetch_config, config.batch_size, config.save_params_filename) + _logger.info("check_vars_and_dump succeed.") + return results + + def parse_program_proto(self, prog_path, is_text, output_dir): + """ + Parse program.proto into a more readable format. + This function will generate three files: + output_dir/vars_all.log, + output_dir/vars_persistable.log, + output_dir/ops.log. + + Args: + prog_path(str): proto file path to be parsed. + is_text(bool): proto file is human-readale format or not(binary). + output_dir(str): output dir. + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil + fleet_util = FleetUtil() + program_path = "./program.pbtxt" + is_text = True + output_dir = "/tmp/" + fleet_util.parse_program_proto(program_path, is_text, output_dir) + """ + program = utils.load_program(prog_path, is_text) + utils.parse_program(program, output_dir) + + def _is_optimizer_op(self, op): + return self.op_role_key in op.attr_names and \ + int(op.all_attrs()[self.op_role_key]) & int(OpRole.Optimize) + + def split_program_by_device(self, program): + ops_list = [] + type_list = [] + pre = None + type_cpu = "cpu" + for op in program.global_block().ops: + if self._is_optimizer_op(op): + break + if op.has_attr("op_device"): + cur_attr = op.attr( + "op_device") if op.attr("op_device") != "" else type_cpu + if pre is None or pre != cur_attr: + ops_list.append([]) + type_list.append(cur_attr) + ops_list[-1].append(op) + pre = cur_attr + l = len(type_list) + i = 0 + type_heter = None + while i < l: + while i < l and type_list[i] == type_cpu: + i += 1 + if i == l: + break + + type_heter = type_list[i] + i += 1 + start = i + valid = True + while i < l and type_list[i] != type_heter: + if type_list[i] != type_cpu: + valid = False + break + i += 1 + + if i == l: + break + elif not valid: + continue + + for j in range(start, i): + for op in ops_list[j]: + op._set_attr("op_device", type_heter) + type_list[j] = type_heter + j += 1 + + pre = None + merged_ops_list = [] + merged_type_list = [] + for i in range(l): + if pre is None or pre != type_list[i]: + merged_ops_list.append([]) + merged_type_list.append(type_list[i]) + merged_ops_list[-1].extend(ops_list[i]) + pre = type_list[i] + + data_vars = set() + for k in program.global_block().vars: + var = program.global_block().var(k) + if not var.persistable: + data_vars.add(var.name) + + l = len(merged_ops_list) + inputs_pre = set() + outputs_pre = set() + in_from_pre = [[] for i in range(l)] + for i in range(l): + inputs = set() + outputs = set() + for op in merged_ops_list[i]: + for input in op.input_names: + for tmp in op.input(input): + if tmp not in outputs: + inputs.add(tmp) + for output in op.output_names: + for tmp in op.output(output): + outputs.add(tmp) + if i == 0: + in_from_pre[i] = [] + elif i == 1: + in_from_pre[i] = (outputs_pre | data_vars) & inputs + else: + in_from_pre[i] = outputs_pre & inputs + inputs_pre = copy.deepcopy(inputs) + outputs_pre = copy.deepcopy(outputs) + + l = len(in_from_pre) + start_list = [] + end_list = [] + send_list = [[] for i in range(l)] + sum = 0 + program_list = [] + for i in range(l): + start_list.append(sum) + end_list.append(sum + len(merged_ops_list[i]) - 1) + sum += len(merged_ops_list[i]) + if i < l - 1: + send_list[i].extend(list(in_from_pre[i + 1])) + prog = program.clone() + if merged_type_list[i] != type_cpu: + prog = prog._prune_with_input(list(in_from_pre[i]), + list(send_list[i])) + program_list.append(prog) + else: + program_list.append(prog) + recv_list = [list(i) for i in in_from_pre] + found = False + heter_index = None + for i in range(len(merged_type_list)): + t = merged_type_list[i] + if t != type_cpu: + if found: + print("only one region of program can be heter") + found = True + heter_index = i + if heter_index is None: + print("warning: non heter program") + return None + else: + return [start_list[heter_index], end_list[heter_index], send_list[heter_index], \ + recv_list[heter_index], program_list[heter_index]] + + +class GPUPSUtil(FleetUtil): + """ + GPUPSUtil provides some common functions for users' convenience. + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + fleet_util = GPUPSUtil() + fleet_util.rank0_print("my log") + """ + + def __init__(self, fs_client=None): + super(GPUPSUtil, self).__init__("pslib") + self._afs = fs_client + # self._afs = fs_client._fs + + def init(self, fs_name, fs_user, fs_passwd, fs_conf): + r""" + init for fs config + + Args: + fs_name(str): fs name + fs_user(str): fs user + fs_passwd(str): fs password + fs_conf(str): fs and afs conf path + + Returns: + None + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + fleet_util = GPUPSUtil() + fleet_util.init(20190722, 88, 88, "./afs.conf") + """ + self._afs.init(fs_name, fs_user, fs_passwd, fs_conf) + + def set_fsclient(self, fs_client): + r""" + set fs_client for fs config + + Args: + fs_client(AFSClient): fs_client object + + Returns: + None + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + """ + self._afs = fs_client + + def get_last_save_xbox_base(self, output_path): + r""" + get last saved base xbox info from xbox_base_done.txt + + Args: + output_path(str): output path + + Returns: + [last_save_day, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + last_save_day, last_path, xbox_base_key = \ + fleet_util.get_last_save_xbox_base("hdfs:/my/path") + + """ + donefile_path = output_path + "/xbox_base_done.txt" + + if not self._afs.is_file(donefile_path): + return [-1, -1, int(time.time())] + self._afs.download(donefile_path, "./xbox_base_done.txt") + # pre_content = self._afs.cat(donefile_path) + pre_content = "" + with open("xbox_base_done.txt", "r") as f: + pre_content = f.read() + pre_content = pre_content.strip() + last_dict = json.loads(pre_content.split("\n")[-1]) + last_day = int(last_dict["input"].split("/")[-3]) + last_path = "/".join(last_dict["input"].split("/")[:-1]) + xbox_base_key = int(last_dict["key"]) + return [last_day, last_path, xbox_base_key] + + def get_last_save_xbox(self, output_path): + r""" + get last saved xbox info from xbox_patch_done.txt + + Args: + output_path(str): output path + + Returns: + [last_save_day, last_save_pass, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_save_pass(int): pass id of saved + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + last_save_day, last_save_pass, last_path, xbox_base_key = \ + fleet_util.get_last_save_xbox("hdfs:/my/path") + + """ + donefile_path = output_path + "/xbox_patch_done.txt" + + if not self._afs.is_file(donefile_path): + return [-1, -1, "", int(time.time())] + self._afs.download(donefile_path, "xbox_patch_done.txt") + pre_content = "" + with open("xbox_patch_done.txt", "r") as f: + pre_content = f.read() + pre_content = pre_content.strip() + last_dict = json.loads(pre_content.split("\n")[-1]) + last_day = int(last_dict["input"].split("/")[-3]) + last_pass = int(last_dict["input"].split("/")[-2].split("-")[-1]) + last_path = "/".join(last_dict["input"].split("/")[:-1]) + xbox_base_key = int(last_dict["key"]) + os.remove("xbox_patch_done.txt") + return [last_day, last_pass, last_path, xbox_base_key] + + def get_last_save_model(self, output_path): + r""" + get last saved model info from donefile.txt + + Args: + output_path(str): output path + + Returns: + [last_save_day, last_save_pass, last_path, xbox_base_key] + last_save_day(int): day of saved model + last_save_pass(int): pass id of saved + last_path(str): model path + xbox_base_key(int): xbox key + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + last_save_day, last_save_pass, last_path, xbox_base_key = \ + fleet_util.get_last_save_model("hdfs:/my/path") + + """ + last_save_day = -1 + last_save_pass = -1 + last_path = "" + donefile_path = output_path + "/donefile.txt" + if not self._afs.is_file(donefile_path): + return [-1, -1, "", int(time.time())] + self._afs.download(donefile_path, "./donefile.txt") + content = "" + with open("donefile.txt", "r") as f: + content = f.read() + content = content.strip().split("\n")[-1].split("\t") + last_save_day = int(content[0]) + last_save_pass = int(content[3]) + last_path = content[2] + xbox_base_key = int(content[1]) + os.remove("donefile.txt") + return [last_save_day, last_save_pass, last_path, xbox_base_key] + + def write_model_donefile(self, + output_path, + day, + pass_id, + xbox_base_key, + donefile_name="donefile.txt"): + """ + write donefile when save model + + Args: + output_path(str): output path + day(str|int): training day + pass_id(str|int): training pass id + xbox_base_key(str|int): xbox base key + donefile_name(str): donefile name, default is "donefile.txt" + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + fleet_util.write_model_donefile(output_path="hdfs:/my/output", + model_path="hdfs:/my/model", + day=20190723, + pass_id=66, + xbox_base_key=int(time.time())) + + """ + day = str(day) + pass_id = str(pass_id) + xbox_base_key = int(xbox_base_key) + + if pass_id != "-1": + suffix_name = "/%s/%s/" % (day, pass_id) + model_path = output_path.rstrip("/") + suffix_name + else: + suffix_name = "/%s/0/" % day + model_path = output_path.rstrip("/") + suffix_name + + if fleet.worker_index() == 0: + donefile_path = output_path + "/" + donefile_name + content = "%s\t%lu\t%s\t%s\t%d" % (day, xbox_base_key,\ + model_path, pass_id, 0) + if self._afs.is_file(donefile_path): + self._afs.download(donefile_path, donefile_name) + pre_content = "" + with open(donefile_name, "r") as f: + pre_content = f.read() + pre_content_list = pre_content.strip().split("\n") + day_list = [i.split("\t")[0] for i in pre_content_list] + pass_list = [i.split("\t")[3] for i in pre_content_list] + os.remove(donefile_name) + exist = False + for i in range(len(day_list)): + if int(day) == int(day_list[i]) and \ + int(pass_id) == int(pass_list[i]): + exist = True + break + if not exist: + with open(donefile_name, "w") as f: + f.write(pre_content.strip() + "\n") + f.write(content + "\n") + self._afs.delete(donefile_path) + self._afs.upload(donefile_name, donefile_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + else: + self.rank0_error("not write %s because %s/%s already " + "exists" % (donefile_name, day, pass_id)) + else: + with open(donefile_name, "w") as f: + f.write(content + "\n") + self._afs.upload(donefile_name, donefile_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + + def write_xbox_donefile(self, + output_path, + day, + pass_id, + xbox_base_key, + data_path, + hadoop_fs_name, + hadoop_fs_ugi, + monitor_data={}, + hadoop_home="$HADOOP_HOME", + donefile_name=None): + """ + write delta donefile or xbox base donefile + + Args: + output_path(str): output path + day(str|int): training day of model + pass_id(str|int): training pass id of model + xbox_base_key(str|int): xbox base key + data_path(str|list): training data path + monitor_data(dict): metrics + hadoop_home(str): hadoop home, default is "$HADOOP_HOME" + donefile_name(str): donefile name, default is None" + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + fleet_util.write_xbox_donefile( + output_path="hdfs:/my/output/", + model_path="hdfs:/my/output/20190722/01", + day=20190722, + pass_id=1, + xbox_base_key=int(time.time()), + data_path="hdfs:/my/data/", + monitor_data={}) + + """ + day = str(day) + pass_id = str(pass_id) + xbox_base_key = int(xbox_base_key) + mode = None + if pass_id != "-1": + mode = "patch" + suffix_name = "/%s/delta-%s/" % (day, pass_id) + model_path = output_path.rstrip("/") + suffix_name + if donefile_name is None: + donefile_name = "xbox_patch_done.txt" + else: + mode = "base" + suffix_name = "/%s/base/" % day + model_path = output_path.rstrip("/") + suffix_name + if donefile_name is None: + donefile_name = "xbox_base_done.txt" + + if isinstance(data_path, list): + data_path = ",".join(data_path) + if fleet.worker_index() == 0: + donefile_path = output_path + "/" + donefile_name + xbox_str = self._get_xbox_str(output_path, day, model_path, \ + xbox_base_key, data_path, hadoop_fs_name, monitor_data={}, + mode=mode) + + if self._afs.is_exist(donefile_path): + self.rank0_info("exist %s succeed" % (donefile_path)) + self._afs.download(donefile_path, donefile_name) + pre_content = "" + with open(donefile_name, "r") as f: + pre_content = f.read() + last_dict = json.loads(pre_content.strip().split("\n")[-1]) + last_day = last_dict["input"].split("/")[-3] + last_pass = last_dict["input"].split("/")[-2].split("-")[-1] + + os.remove(donefile_name) + self.rank0_info("remove %s succeed" % (donefile_name)) + exist = False + if int(day) < int(last_day) or \ + int(day) == int(last_day) and \ + int(pass_id) <= int(last_pass): + exist = True + if not exist: + with open(donefile_name, "w") as f: + f.write(pre_content.strip() + "\n") + f.write(xbox_str + "\n") + self._afs.delete(donefile_path) + self._afs.upload(donefile_name, donefile_path) + self.rank0_info("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + else: + self.rank0_info("not write %s because %s/%s already " + "exists" % (donefile_name, day, pass_id)) + else: + with open(donefile_name, "w") as f: + f.write(xbox_str + "\n") + self._afs.upload(donefile_name, donefile_path) + self.rank0_error("write %s/%s %s succeed" % \ + (day, pass_id, donefile_name)) + + def write_cache_donefile(self, + output_path, + day, + pass_id, + key_num, + donefile_name="sparse_cache.meta", + **kwargs): + """ + write cache donefile + + Args: + output_path(str): output path + day(str|int): training day of model + pass_id(str|int): training pass id of model + key_num(str|int): save cache return value + donefile_name(str): donefile name, default is "sparse_cache.meta" + kwargs(dict): user defined properties + file_num(int): cache file num + table_id(int): cache table id + + Examples: + .. code-block:: python + + from paddle.fluid.incubate.fleet.utils.fleet_util import GPUPSUtil + from paddle.distributed.fleet.utils.fs import AFSClient + hdfs_client = AFSClient() + fleet_util = GPUPSUtil() + fleet_util.set_fsclient(hdfs_client) + fleet_util.write_cache_donefile( + output_path="hdfs:/my/output/", + day=20190722, + pass_id=1, + key_num=123456) + + """ + day = str(day) + pass_id = str(pass_id) + key_num = int(key_num) + file_num = kwargs.get("file_num", 16) + table_id = kwargs.get("table_id", 0) + + if pass_id != "-1": + suffix_name = "/%s/delta-%s/%03d_cache" % (day, pass_id, table_id) + model_path = output_path.rstrip("/") + suffix_name + else: + suffix_name = "/%s/base/%03d_cache" % (day, table_id) + model_path = output_path.rstrip("/") + suffix_name + + if fleet.worker_index() == 0: + donefile_path = model_path + "/" + donefile_name + + if self._afs.is_file(donefile_path): + self.rank0_error( \ + "not write because %s already exists" % donefile_path) + else: + meta_str = "file_prefix:part\npart_num:%s\nkey_num:%d\n" \ + % (file_num, key_num) + with open(donefile_name, "w") as f: + f.write(meta_str) + self._afs.upload(donefile_name, donefile_path) + self.rank0_error("write %s succeed" % donefile_path) + + def _get_xbox_str(self, + output_path, + day, + model_path, + xbox_base_key, + data_path, + hadoop_fs_name, + monitor_data={}, + mode="patch"): + xbox_dict = collections.OrderedDict() + if mode == "base": + xbox_dict["id"] = str(xbox_base_key) + elif mode == "patch": + xbox_dict["id"] = str(int(time.time())) + else: + print("warning: unknown mode %s, set it to patch" % mode) + mode = "patch" + xbox_dict["id"] = str(int(time.time())) + xbox_dict["key"] = str(xbox_base_key) + if model_path.startswith("hdfs:") or model_path.startswith("afs:"): + model_path = model_path[model_path.find(":") + 1:] + xbox_dict["input"] = hadoop_fs_name + model_path.rstrip("/") + "/000" + xbox_dict["record_count"] = "111111" + xbox_dict["partition_type"] = "2" + xbox_dict["job_name"] = "default_job_name" + xbox_dict["ins_tag"] = "feasign" + xbox_dict["ins_path"] = data_path + xbox_dict["job_id"] = os.environ.get("PADDLE_JOB_ID", "") + # currently hard code here, set monitor_data empty string + xbox_dict["monitor_data"] = "" + xbox_dict["monitor_path"] = output_path.rstrip("/") + "/monitor/" \ + + day + ".txt" + xbox_dict["mpi_size"] = str(fleet.worker_num()) + return json.dumps(xbox_dict) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/hdfs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/hdfs.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1b36e33c504e3370cd1ed861887f0667c2260d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/hdfs.py @@ -0,0 +1,333 @@ +# Copyright (c) 2018 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. +"""HDFS Utils.""" + +import os +import sys +import subprocess +import multiprocessing +from datetime import datetime + +import re +import copy +import errno +import time +import logging +import six +#from . import fs +from paddle.distributed.fleet.utils.fs import FS, LocalFS, FSFileExistsError, FSFileNotExistsError, ExecuteError, FSTimeOut, FSShellCmdAborted +from paddle.fluid import core +import functools + +import shutil + +__all__ = ["HDFSClient"] + + +def _handle_errors(max_time_out=None): + + def decorator(f): + + @functools.wraps(f) + def handler(*args, **kwargs): + o = args[0] + time_out = max_time_out + if time_out is None: + time_out = float(o._time_out) / 1000.0 + else: + time_out /= 1000.0 + inter = float(o._sleep_inter) / 1000.0 + + start = time.time() + last_print_time = start + while True: + try: + return f(*args, **kwargs) + #important: only ExecuteError need to retry + except ExecuteError as e: + if time.time() - start >= time_out: + raise FSTimeOut("args:{} timeout:{}".format( + args, + time.time() - start)) + + time.sleep(inter) + + if time.time() - last_print_time > 30: + print("hadoop operator timeout:args:{} timeout:{}".format( + args, + time.time() - start)) + last_print_time = time.time() + + return handler + + return decorator + + +class HDFSClient(FS): + + def __init__( + self, + hadoop_home, + configs, + time_out=5 * 60 * 1000, #ms + sleep_inter=1000): #ms + # Raise exception if JAVA_HOME not exists. + + self.pre_commands = [] + hadoop_bin = '%s/bin/hadoop' % hadoop_home + self.pre_commands.append(hadoop_bin) + dfs = 'fs' + self.pre_commands.append(dfs) + + if configs: + for k, v in six.iteritems(configs): + config_command = '-D%s=%s' % (k, v) + self.pre_commands.append(config_command) + + self._time_out = time_out + self._sleep_inter = sleep_inter + self._base_cmd = " ".join(self.pre_commands) + self._bd_err_re = re.compile( + r'\s?responseErrorMsg\s?\:.*, errorCode\:\s?[0-9]+, path\:') + + def _run_cmd(self, cmd, redirect_stderr=False): + exe_cmd = "{} -{}".format(self._base_cmd, cmd) + ret, output = core.shell_execute_cmd(exe_cmd, 0, 0, redirect_stderr) + ret = int(ret) + if ret == 134: + raise FSShellCmdAborted(cmd) + return ret, output.splitlines() + + @_handle_errors() + def list_dirs(self, fs_path): + if not self.is_exist(fs_path): + return [] + + dirs, files = self._ls_dir(fs_path) + return dirs + + @_handle_errors() + def ls_dir(self, fs_path): + """ + list directory under fs_path, and only give the pure name, not include the fs_path + """ + if not self.is_exist(fs_path): + return [], [] + + return self._ls_dir(fs_path) + + def _ls_dir(self, fs_path): + cmd = "ls {}".format(fs_path) + ret, lines = self._run_cmd(cmd) + + if ret != 0: + raise ExecuteError(cmd) + + dirs = [] + files = [] + for line in lines: + arr = line.split() + if len(arr) != 8: + continue + + p = os.path.basename(arr[7]) + if arr[0][0] == 'd': + dirs.append(p) + else: + files.append(p) + + return dirs, files + + def _test_match(self, lines): + for l in lines: + m = self._bd_err_re.match(l) + if m != None: + return m + + return None + + @_handle_errors() + def is_dir(self, fs_path): + if not self.is_exist(fs_path): + return False + + return self._is_dir(fs_path) + + def _is_dir(self, fs_path): + cmd = "test -d {}".format(fs_path, redirect_stderr=True) + ret, lines = self._run_cmd(cmd) + if ret: + # other error + if self._test_match(lines): + raise ExecuteError(cmd) + + return False + + return True + + def is_file(self, fs_path): + if not self.is_exist(fs_path): + return False + + return not self._is_dir(fs_path) + + @_handle_errors() + def is_exist(self, fs_path): + cmd = "ls {} ".format(fs_path) + ret, out = self._run_cmd(cmd, redirect_stderr=True) + if ret != 0: + for l in out: + if "No such file or directory" in l: + return False + raise ExecuteError(cmd) + + return True + + # can't retry + def upload(self, local_path, fs_path): + if self.is_exist(fs_path): + raise FSFileExistsError("{} exists".format(fs_path)) + + local = LocalFS() + if not local.is_exist(local_path): + raise FSFileNotExistsError("{} not exists".format(local_path)) + + return self._try_upload(local_path, fs_path) + + @_handle_errors() + def _try_upload(self, local_path, fs_path): + cmd = "put {} {}".format(local_path, fs_path) + ret = 0 + try: + ret, lines = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + self.delete(fs_path) + raise e + + # can't retry + def download(self, fs_path, local_path): + if self.is_exist(local_path): + raise FSFileExistsError("{} exists".format(local_path)) + + if not self.is_exist(fs_path): + raise FSFileNotExistsError("{} not exits".format(fs_path)) + + return self._try_download(fs_path, local_path) + + @_handle_errors() + def _try_download(self, fs_path, local_path): + cmd = "get {} {}".format(fs_path, local_path) + ret = 0 + try: + ret, lines = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + local_fs = LocalFS() + local_fs.delete(local_path) + raise e + + @_handle_errors() + def mkdirs(self, fs_path): + if self.is_exist(fs_path): + return + + out_hdfs = False + + cmd = "mkdir {} ".format(fs_path) + ret, out = self._run_cmd(cmd, redirect_stderr=True) + if ret != 0: + for l in out: + if "No such file or directory" in l: + out_hdfs = True + break + if not out_hdfs: + raise ExecuteError(cmd) + + if out_hdfs and not self.is_exist(fs_path): + cmd = "mkdir -p {}".format(fs_path) + ret, lines = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + def mv(self, fs_src_path, fs_dst_path, overwrite=False, test_exists=True): + if overwrite and self.is_exist(fs_dst_path): + self.delete(fs_dst_path) + + if test_exists: + if not self.is_exist(fs_src_path): + raise FSFileNotExistsError( + "{} is not exists".format(fs_src_path)) + + if self.is_exist(fs_dst_path): + raise FSFileExistsError("{} exists already".format(fs_dst_path)) + + return self._try_mv(fs_src_path, fs_dst_path) + + @_handle_errors() + def _try_mv(self, fs_src_path, fs_dst_path): + cmd = "mv {} {}".format(fs_src_path, fs_dst_path) + ret = 0 + try: + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + except Exception as e: + if not self.is_exist(fs_src_path) and \ + self.is_exist(fs_dst_path): + return + raise e + + def _rmr(self, fs_path): + cmd = "rmr {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + def _rm(self, fs_path): + cmd = "rm {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError(cmd) + + @_handle_errors() + def delete(self, fs_path): + if not self.is_exist(fs_path): + return + + is_dir = self._is_dir(fs_path) + if is_dir: + return self._rmr(fs_path) + + return self._rm(fs_path) + + def touch(self, fs_path, exist_ok=True): + if self.is_exist(fs_path): + if exist_ok: + return + raise FSFileExistsError + + return self._touchz(fs_path) + + @_handle_errors() + def _touchz(self, fs_path): + cmd = "touchz {}".format(fs_path) + ret, _ = self._run_cmd(cmd) + if ret != 0: + raise ExecuteError + + def need_upload_download(self): + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/http_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/http_server.py new file mode 100644 index 0000000000000000000000000000000000000000..685228f07490ee699829b797373144cf70ea6522 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/http_server.py @@ -0,0 +1,189 @@ +# 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. +"""Http Server.""" + +import logging +# NOTE: HTTPServer has a different name in python2 and python3 +from http.server import HTTPServer +import http.server as SimpleHTTPServer +import time +import threading +import socket + + +def get_logger(name, level, fmt): + logger = logging.getLogger(name) + logger.setLevel(level) + handler = logging.FileHandler('http.log', mode='w') + formatter = logging.Formatter(fmt=fmt) + handler.setFormatter(formatter) + logger.addHandler(handler) + return logger + + +_http_server_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +class KVHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): + """ + kv handler class for kv http server, + it defines the way to get/set kv in server. + """ + + def do_GET(self): + """ + get method for kv handler, get value according to key. + """ + log_str = "GET " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + with self.server.kv_lock: + value = self.server.kv.get(scope, {}).get(key) + if value is None: + log_str += ' , key not found: ' + key + self.send_status_code(404) + else: + log_str += ' , key found: ' + key + self.send_response(200) + self.send_header("Content-Length", str(len(value))) + self.end_headers() + self.wfile.write(value) + _http_server_logger.info(log_str) + + def do_PUT(self): + """ + put method for kv handler, set value according to key. + """ + log_str = "PUT " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + content_length = int(self.headers['Content-Length']) + try: + value = self.rfile.read(content_length) + except: + print("receive error invalid request") + self.send_status_code(404) + return + with self.server.kv_lock: + if self.server.kv.get(scope) is None: + self.server.kv[scope] = {} + self.server.kv[scope][key] = value + self.send_status_code(200) + _http_server_logger.info(log_str) + + def do_DELETE(self): + """ + delete method for kv handler, set value according to key. + """ + log_str = "DELETE " + self.address_string() + self.path + paths = self.path.split('/') + if len(paths) < 3: + print('len of request path must be 3: ' + self.path) + self.send_status_code(400) + return + _, scope, key = paths + with self.server.delete_kv_lock: + if self.server.delete_kv.get(scope) is None: + self.server.delete_kv[scope] = [] + self.server.delete_kv[scope].append(key) + self.send_status_code(200) + _http_server_logger.info(log_str) + + def log_message(self, format, *args): + """ + ignore all logging messages in kv handler. + """ + pass + + def send_status_code(self, code): + """ + send status code back to client. + """ + self.send_response(code) + self.send_header("Content-Length", 0) + self.end_headers() + + +class KVHTTPServer(HTTPServer, object): + """ + it is a http server storing kv pairs. + """ + + def __init__(self, port, handler): + """Init.""" + super(KVHTTPServer, self).__init__(('', port), handler) + self.delete_kv_lock = threading.Lock() + self.delete_kv = {} + self.kv_lock = threading.Lock() + self.kv = {} + + def get_deleted_size(self, key): + """ + get deleted size in key. + """ + ret = 0 + with self.delete_kv_lock: + ret = self.delete_kv.get(key, 0) + return ret + + +class KVServer: + """ + it is a server storing kv pairs, has a http server inside. + """ + + def __init__(self, port, size={}): + """Init.""" + self.http_server = KVHTTPServer(port, KVHandler) + self.listen_thread = None + self.size = {} + + def start(self): + """ + start server until user calls stop to let it quit. + """ + self.listen_thread = threading.Thread( + target=lambda: self.http_server.serve_forever()) + self.listen_thread.start() + + def stop(self): + """ + stop server and clear its resources. + """ + self.http_server.shutdown() + self.listen_thread.join() + self.http_server.server_close() + + def should_stop(self): + """ + return whether the server should stop. + + Returns: + ret(bool): whether the server should stop + """ + for key in self.size: + s = self.http_server.get_deleted_size(key) + if s != self.size.get(key, 0): + return False + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3890da7ecec4c6a8d5dab100568aeaf6571ec080 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/incubate/fleet/utils/utils.py @@ -0,0 +1,428 @@ +# 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. + +from __future__ import print_function, absolute_import +import os +import sys +import logging +import subprocess +import numpy as np +from collections import OrderedDict +import paddle.fluid as fluid +from paddle.fluid import core +from paddle.fluid.log_helper import get_logger + +from google.protobuf import text_format +from paddle.fluid import debugger +from paddle.fluid.framework import Program +from paddle.fluid.proto import framework_pb2 + +__all__ = [ + "load_program", "save_program", "program_type_trans", + "check_saved_vars_try_dump", "parse_program", "check_pruned_program_vars", + "graphviz" +] + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s') +ch = logging.StreamHandler() +ch.setFormatter(formatter) +logger.addHandler(ch) + +persistable_vars_out_fn = "vars_persistable.log" +all_vars_out_fn = "vars_all.log" +ops_out_fn = "ops.log" + +feed_fetch_type_list = [ + core.VarDesc.VarType.FEED_MINIBATCH, core.VarDesc.VarType.FETCH_LIST +] +not_expected_op_types = ["lookup_table"] + + +def load_program(model_filename, is_text=False): + if is_text: + return load_program_text(model_filename) + return load_program_binary(model_filename) + + +def load_program_binary(model_filename): + """load program from binary string file""" + with open(model_filename, "rb") as f: + program_desc_str = f.read() + return Program.parse_from_string(program_desc_str) + + +def load_program_text(model_filename): + """load program from human-readable text file""" + with open(model_filename, "r") as f: + program_desc_text = f.read() + + prog_desc = framework_pb2.ProgramDesc() + text_format.Merge(program_desc_text, prog_desc) + return Program.parse_from_string(prog_desc.SerializeToString()) + + +def save_program(program, model_filename='__model__', is_text=False): + if is_text: + with open(model_filename, "w") as f: + f.write(str(program)) + else: + with open(model_filename, "wb") as f: + f.write(program.desc.serialize_to_string()) + + +def check_pruned_program_vars(train_prog, pruned_prog): + is_match = True + + pruned_vars = [(v.name, v) for v in pruned_prog.list_vars() + if fluid.io.is_persistable(v)] + pruned_vars = OrderedDict(pruned_vars) + pruned_vars_name = [name for name in pruned_vars] + logger.info( + "persistable vars in pruned program: {}".format(pruned_vars_name)) + + for var_name in pruned_vars: + var = pruned_vars[var_name] + # feed and fetch op is added in pruned program when pruning, not need to be found in train program + if var.type in feed_fetch_type_list: + break + try: + train_prog_var = train_prog.global_block().var(var_name) + except ValueError as e: + logger.error( + "not find variable '%s' in train program. please check pruning." + % var_name) + logger.error(e) + continue + if var.shape != train_prog_var.shape or var.dtype != train_prog_var.dtype: + logger.error( + "variable: {} not match. in pruned program shape: {} dtype:{}, in train program shape: {} dtype: {}" + .format(var_name, var.shape, var.dtype, train_prog_var.shape, + train_prog_var.dtype)) + is_match = False + return is_match + + +def graphviz(block, output_dir="", filename='debug'): + dot_path = os.path.join(output_dir, filename + '.dot') + pdf_path = os.path.join(output_dir, filename + '.pdf') + debugger.draw_block_graphviz(block, path=dot_path) + cmd = ["dot", "-Tpdf", dot_path, "-o", pdf_path] + p = subprocess.Popen(cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + p.wait() + + +def program_type_trans(prog_dir, prog_fn, is_text): + prog = load_program(os.path.join(prog_dir, prog_fn), is_text) + prog_out_fn = prog_fn + ".bin" if is_text else prog_fn + ".pbtxt" + save_program(prog, os.path.join(prog_dir, prog_out_fn), 1 - is_text) + return prog_out_fn + + +def append_save_op(block, var, path): + block.append_op(type='save', + inputs={'X': [var]}, + outputs={}, + attrs={'file_path': path}) + + +def append_load_op(block, var, path): + block.append_op(type='load', + inputs={}, + outputs={'Out': [var]}, + attrs={'file_path': path}) + + +def save_var(np_array, var_name, shape_list, dtype, save_path): + program = fluid.Program() + place = fluid.CPUPlace() + exe = fluid.Executor(place) + with fluid.program_guard(program): + d0_data = fluid.layers.data(var_name, shape=shape_list, dtype=dtype) + append_save_op(program.global_block(), d0_data, save_path) + exe.run(feed={var_name: np_array}, fetch_list=[]) + + +def load_var(var_name, shape_list, dtype, save_path): + program = fluid.Program() + place = fluid.CPUPlace() + exe = fluid.Executor(place) + with fluid.program_guard(program): + d0_data = fluid.layers.data(var_name, shape=shape_list, dtype=dtype) + append_load_op(program.global_block(), d0_data, save_path) + outs = exe.run(feed={}, fetch_list=[d0_data]) + return outs + + +def reader(batch_size, fn, dim): + data = [] + if isinstance(dim, list) or isinstance(dim, tuple): + shape = list(dim) + _temp = 1 + for x in dim: + _temp = _temp * x + dim = _temp + else: + shape = [dim] + + shape = [batch_size] + shape + dim = dim * batch_size + + for line in open(fn, 'r'): + fields = line.strip().split(' ') + fields = [float(d) for d in fields] + while len(fields) >= dim: + tmp = fields[:dim] + fields = fields[dim:] + data.append(np.array(tmp).reshape(shape)) + return data + + +def feed_gen(batch_size, feeded_vars_dims, feeded_vars_filelist): + batch_feed = [] + for i, fn in enumerate(feeded_vars_filelist): + batch_feed.append(reader(batch_size, fn, feeded_vars_dims[i])) + return batch_feed + + +def try_load_model_vars(dump_dir, dump_prog_fn, is_text_dump_program, + batch_size, feed_config, fetch_config, save_filename, + saved_params): + place = fluid.CPUPlace() + exe = fluid.Executor(place) + scope = fluid.core.Scope() + with fluid.scope_guard(scope): + if is_text_dump_program: + dump_prog_fn = program_type_trans(dump_dir, dump_prog_fn, + is_text_dump_program) + inference_program, feed_target_names, fetch_targets = \ + fluid.io.load_inference_model(dump_dir, exe, model_filename=dump_prog_fn, + params_filename=save_filename) + + # check program vars and saved vars shape + orig_para_shape = { + each_var.name: tuple(each_var.desc.shape()) + for each_var in saved_params + } + for each_var in saved_params: + var_temp = fluid.global_scope().find_var(each_var.name) + assert var_temp != None, "can't not find var: " + each_var.name + new_shape = (np.array(var_temp.get_tensor())).shape + assert each_var.name in orig_para_shape, each_var.name + "MUST in var list" + orig_shape = orig_para_shape.get(each_var.name) + if new_shape != orig_shape: + raise RuntimeError( + "Shape not matching: the Program requires a parameter with a shape of ({}), " + "while the loaded parameter (namely [ {} ]) has a shape of ({})." + .format(orig_shape, each_var.name, new_shape)) + + # check feed/fetch vars in program and config + fetch_targets_names = [v.name for v in fetch_targets] + if not feed_target_names: + logger.warning("no feed targets in program.") + if not fetch_targets_names: + logger.warning("no fetch targets in program.") + fetch_list = fetch_targets + feed_name_list = feed_target_names + if feed_config.feeded_vars_names is not None and feed_target_names != feed_config.feeded_vars_names: + logger.warning( + "feed vars in program and config are diff: feed in program: {}. feed in config {}." + .format(feed_target_names, feed_config.feeded_vars_names)) + feed_name_list = feed_config.feeded_vars_names + # remove feed op in inference_program. new feed op will be added in exe.run + global_block = inference_program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "feed": # only remove feed op here + need_to_remove_op_index.append(i) + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + if fetch_config.fetch_vars_names is not None and fetch_targets_names != fetch_config.fetch_vars_names: + logger.warning( + "fetch vars in program and config are diff: fetch in program: {}. fetch in config {}." + .format(fetch_targets_names, fetch_config.fetch_vars_names)) + fetch_list = [ + inference_program.global_block().var(i) + for i in fetch_config.fetch_vars_names + ] + # remove fetch op in inference_program. new fetch op will be added in exe.run + global_block = inference_program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "fetch": # only remove fetch op here + need_to_remove_op_index.append(i) + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + + # if fetch_list have lod tensor + return_numpy = all([v.lod_level == 0 for v in fetch_list]) + + # try dump fetch_targets + feed_tensors = [] + assert len(feed_config.feeded_vars_names) == len( + feed_config.feeded_vars_dims) == len(feed_config.feeded_vars_types) + # check program vars and feed tensor shape in config + for i in range(len(feed_config.feeded_vars_names)): + var = inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + if not isinstance(feed_config.feeded_vars_dims[i], (list, tuple)): + tensor_shape = (feed_config.feeded_vars_dims[i], ) + else: + tensor_shape = tuple(feed_config.feeded_vars_dims[i]) + feed_config.feeded_vars_dims[i] = tensor_shape + var_shape = var.shape[1:] + if tensor_shape != var_shape: + raise RuntimeError( + "feed variable '{}' shape not match. infer program shape: {}. feed tensor shape: {}" + .format(feed_config.feeded_vars_names[i], var_shape, + tensor_shape)) + + if not feed_config.feeded_vars_filelist: + logger.info("generate random feed vars.") + for i in range(len(feed_config.feeded_vars_names)): + var = inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + # create fake feed tensor. if lod_level > 1, should create_lod_tensor() + if var.lod_level == 0: + feed_tensors.append( + np.array(np.random.random( + tuple([batch_size] + + list(feed_config.feeded_vars_dims[i]))), + dtype=feed_config.feeded_vars_types[i])) + elif var.lod_level == 1: + t = np.array(np.random.random( + tuple([batch_size] + + list(feed_config.feeded_vars_dims[i]))), + dtype=feed_config.feeded_vars_types[i]) + feed_tensors.append( + fluid.create_lod_tensor(t, [[1] * batch_size], place)) + else: + raise RuntimeError( + "vars with lod_level >= 2 is not supported now in this infer program check tool." + ) + results = exe.run(inference_program, + feed={ + name: feed_tensors[i] + for i, name in enumerate(feed_name_list) + }, + fetch_list=fetch_list, + return_numpy=return_numpy) + else: + logger.info("load feed vars from files: {}.".format( + feed_config.feeded_vars_filelist)) + feed_vars = [ + inference_program.global_block().var( + feed_config.feeded_vars_names[i]) + for i in range(len(feed_config.feeded_vars_names)) + ] + feeder = fluid.DataFeeder(feed_list=feed_vars, place=place) + batch_feed = feed_gen(batch_size, feed_config.feeded_vars_dims, + feed_config.feeded_vars_filelist) + slots = [batch_feed] + results = exe.run(inference_program, + feed=feeder.feed(slots), + fetch_list=fetch_list, + return_numpy=return_numpy) + for i, v in enumerate(fetch_list): + logger.info("fetch_targets name: %s" % v.name) + logger.info("fetch_targets: {}".format(results[i])) + return results + + +def check_not_expected_ops(prog): + op_types_set = set() + for op in prog.global_block().ops: + if op.type in not_expected_op_types and op.type not in op_types_set: + logger.warning( + "find op type '{}' in program, please check if your program is pruned correctly !" + .format(op.type)) + op_types_set.add(op.type) + + +def check_saved_vars_try_dump(dump_dir, + dump_prog_fn, + is_text_dump_program, + feed_config, + fetch_config, + batch_size=1, + save_filename=None): + dump_prog = load_program(os.path.join(dump_dir, dump_prog_fn), + is_text_dump_program) + saved_params = [ + v for v in dump_prog.list_vars() if fluid.io.is_persistable(v) + ] + logger.info("persistable vars in dump program: {}".format( + [v.name for v in saved_params])) + + check_not_expected_ops(dump_prog) + + return try_load_model_vars(dump_dir, dump_prog_fn, is_text_dump_program, + batch_size, feed_config, fetch_config, + save_filename, saved_params) + + +def parse_program(program, output_dir): + # persistable vars + output = {} + persistable_vars = [ + v for v in program.list_vars() if fluid.io.is_persistable(v) + ] + output["persistable_vars"] = [{ + 'name': str(v.name), + 'shape': str(v.shape), + 'lod_level': int(v.lod_level), + 'dtype': str(v.dtype), + 'type': str(v.type) + } for v in persistable_vars] + with open(os.path.join(output_dir, persistable_vars_out_fn), 'w') as f: + f.write("persistable vars:\n") + for var in output["persistable_vars"]: + f.write(str(var)) + f.write("\n") + + # all vars + all_vars = [v for v in program.list_vars()] + output["all_vars"] = [{ + 'name': str(v.name), + 'shape': str(v.shape), + 'lod_level': int(v.lod_level), + 'dtype': str(v.dtype) + } if v.type not in feed_fetch_type_list else { + 'name': str(v.name), + 'type': str(v.type) + } for v in all_vars] + with open(os.path.join(output_dir, all_vars_out_fn), 'w') as f: + f.write("all vars:\n") + for var in output["all_vars"]: + f.write(str(var)) + f.write("\n") + + # ops + ops = program.global_block().ops + output["ops"] = [{ + 'type': op.type, + 'input_arg_names': str(op.input_arg_names), + 'output_arg_names': str(op.output_arg_names) + } for op in ops] + with open(os.path.join(output_dir, ops_out_fn), 'w') as f: + f.write("ops:\n") + for op in output["ops"]: + f.write(str(op)) + f.write("\n") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b8b102487923d84b90bafba8ce0bd52f09b6b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/__init__.py @@ -0,0 +1,18 @@ +# 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. + +from .wrapper import Config, DataType, PlaceType, PrecisionType, Tensor, Predictor +from .wrapper import convert_to_mixed_precision + +from ..core import create_predictor, get_version, _get_phi_kernel_name, get_num_bytes_of_data_type, PredictorPool, get_trt_compile_version, get_trt_runtime_version diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/wrapper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..83811012e529458e91df34d8dcedfc7efc4b0942 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/inference/wrapper.py @@ -0,0 +1,89 @@ +# 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. + +from ..core import AnalysisConfig, PaddleDType, PaddlePlace +from ..core import PaddleInferPredictor, PaddleInferTensor +from ..core import convert_to_mixed_precision_bind +from .. import core + +import os +import numpy as np +from typing import Set + +DataType = PaddleDType +PlaceType = PaddlePlace +PrecisionType = AnalysisConfig.Precision +Config = AnalysisConfig +Tensor = PaddleInferTensor +Predictor = PaddleInferPredictor + + +def tensor_copy_from_cpu(self, data): + ''' + Support input type check based on tensor.copy_from_cpu. + ''' + if isinstance(data, np.ndarray) or (isinstance(data, list) and len(data) > 0 + and isinstance(data[0], str)): + self.copy_from_cpu_bind(data) + else: + raise TypeError( + "In copy_from_cpu, we only support numpy ndarray and list[str] data type." + ) + + +def tensor_share_external_data(self, data): + ''' + Support input type check based on tensor.share_external_data. + ''' + if isinstance(data, core.LoDTensor): + self.share_external_data_bind(data) + else: + raise TypeError( + "In share_external_data, we only support LoDTensor data type.") + + +def convert_to_mixed_precision(model_file: str, + params_file: str, + mixed_model_file: str, + mixed_params_file: str, + mixed_precision: PrecisionType, + backend: PlaceType, + keep_io_types: bool = True, + black_list: Set = set()): + ''' + Convert a fp32 model to mixed precision model. + + Args: + model_file: fp32 model file, e.g. inference.pdmodel. + params_file: fp32 params file, e.g. inference.pdiparams. + mixed_model_file: The storage path of the converted mixed-precision model. + mixed_params_file: The storage path of the converted mixed-precision params. + mixed_precision: The precision, e.g. PrecisionType.Half. + backend: The backend, e.g. PlaceType.GPU. + keep_io_types: Whether the model input and output dtype remains unchanged. + black_list: Operators that do not convert precision. + ''' + mixed_model_dirname = os.path.dirname(mixed_model_file) + mixed_params_dirname = os.path.dirname(mixed_params_file) + if not os.path.exists(mixed_model_dirname): + os.makedirs(mixed_model_dirname) + if not os.path.exists(mixed_params_dirname): + os.makedirs(mixed_params_dirname) + convert_to_mixed_precision_bind(model_file, params_file, mixed_model_file, + mixed_params_file, mixed_precision, backend, + keep_io_types, black_list) + + +Tensor.copy_from_cpu = tensor_copy_from_cpu +Tensor.share_external_data = tensor_share_external_data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/initializer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/initializer.py new file mode 100644 index 0000000000000000000000000000000000000000..5e59c8be062191c1c4f1826d1b429cb0f4571d57 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/initializer.py @@ -0,0 +1,1274 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function + +import math +import functools +from . import framework +from . import core +from .framework import _non_static_mode, in_dygraph_mode, _in_legacy_dygraph, default_main_program, _current_expected_place +from .lazy_init import lazy_init_helper +from .framework import program_guard +import numpy as np +from .core import VarDesc +from . import unique_name +from .data_feeder import check_variable_and_dtype, check_type, check_dtype +from paddle import _C_ops, _legacy_C_ops +import paddle + +__all__ = [ + 'Constant', 'Uniform', 'Normal', 'TruncatedNormal', 'Xavier', 'Bilinear', + 'MSRA', 'ConstantInitializer', 'UniformInitializer', 'NormalInitializer', + 'TruncatedNormalInitializer', 'XavierInitializer', 'BilinearInitializer', + 'MSRAInitializer', 'NumpyArrayInitializer', 'set_global_initializer' +] + +_global_weight_initializer_ = None +_global_bias_initializer_ = None + + +class Initializer(object): + """Base class for variable initializers + + Defines the common interface of variable initializers. + They add operations to the init program that are used + to initialize variables. Users should not use this class + directly, but need to use one of its implementations. + """ + + def __init__(self): + pass + + def __call__(self, param, block=None): + if not lazy_init_helper().state: + return self.forward(param, block) + + return self._lazy_init(param, block) + + def forward(self, param, block=None): + """Add corresponding initialization operations to the network + """ + raise NotImplementedError() + + def _lazy_init(self, param, block=None): + """ + Apply lazy initialization + """ + assert in_dygraph_mode() + + def init_op_creator(forward, param, block): + new_var = param._to_static_var(True, block=block) + # Record initializer operator + with lazy_init_helper(): + forward(new_var, block) + + # Add hook function for initializing param in dygraph mode + param.set_init_func(functools.partial(self.forward, param, block)) + param._init_op_creator = functools.partial(init_op_creator, + self.forward, param) + + return param + + def _check_block(self, block): + if block is None: + block = default_main_program().global_block() + + return block + + def _compute_fans(self, var): + """Compute the fan_in and the fan_out for layers + + This method computes the fan_in and the fan_out + for neural network layers, if not specified. It is + not possible to perfectly estimate fan_in and fan_out. + This method will estimate it correctly for matrix multiply and + convolutions. + + Args: + var: variable for which fan_in and fan_out have to be computed + + Returns: + tuple of two integers (fan_in, fan_out) + """ + shape = var.shape + if not shape or len(shape) == 0: + fan_in = fan_out = 1 + elif len(shape) == 1: + fan_in = fan_out = shape[0] + elif len(shape) == 2: + # This is the case for simple matrix multiply + fan_in = shape[0] + fan_out = shape[1] + else: + # Assume this to be a convolutional kernel + # In PaddlePaddle, the shape of the kernel is like: + # [num_filters, num_filter_channels, ...] where the remaining + # dimensions are the filter_size + receptive_field_size = np.prod(shape[2:]) + fan_in = shape[1] * receptive_field_size + fan_out = shape[0] * receptive_field_size + + return (fan_in, fan_out) + + +class ConstantInitializer(Initializer): + """Implements the constant initializer + + Args: + value (float32): constant value to initialize the variable + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + x = fluid.data(name="data", shape=[8, 32, 32], dtype="float32") + fc = fluid.layers.fc( + input=x, + size=10, + param_attr=fluid.initializer.Constant(value=2.0)) + + """ + + def __init__(self, value=0.0, force_cpu=False): + assert value is not None + super(ConstantInitializer, self).__init__() + self._value = value + self._force_cpu = force_cpu + + def forward(self, var, block=None): + """Initialize the input tensor with constant. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert (isinstance(var, framework.Variable) + or isinstance(var, framework.EagerParamBase)) + assert isinstance(block, framework.Block) + + if in_dygraph_mode(): + place = _current_expected_place() + if self._force_cpu: + place = core.CPUPlace() + _C_ops.full_(var, var.shape, str(float(self._value)), var.dtype, + place) + return None + elif _in_legacy_dygraph(): + _legacy_C_ops.fill_constant(var, 'value', float(self._value), + 'force_cpu', self._force_cpu, 'dtype', + int(var.dtype), 'str_value', + str(float(self._value)), 'shape', + var.shape) + return None + else: + op = block.append_op(type="fill_constant", + outputs={"Out": var}, + attrs={ + "shape": var.shape, + "dtype": int(var.dtype), + "value": float(self._value), + 'str_value': str(float(self._value)), + 'force_cpu': self._force_cpu + }, + stop_gradient=True) + + var.op = op + return op + + +class UniformInitializer(Initializer): + """Implements the random uniform distribution initializer + + Args: + low (float): lower boundary of the uniform distribution + high (float): upper boundary of the uniform distribution + seed (int): random seed + diag_num (int): the number of diagonal elements to initialize. + If set to 0, diagonal initialization will be not performed. + diag_step (int): Step size between two diagonal elements, + which is generally the width of the square matrix. + diag_val (float): the value of the diagonal element to be initialized, + default 1.0. It takes effect only if the diag_num is greater than 0. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[None, 1], dtype='float32') + fc = fluid.layers.fc(input=x, size=10, + param_attr=fluid.initializer.Uniform(low=-0.5, high=0.5)) + """ + + def __init__(self, + low=-1.0, + high=1.0, + seed=0, + diag_num=0, + diag_step=0, + diag_val=1.0): + assert low is not None + assert high is not None + assert high >= low + assert seed is not None + assert diag_num is not None + assert diag_step is not None + assert diag_val is not None + if diag_num > 0 or diag_step > 0: + assert (diag_num > 0 and diag_step > 0) + super(UniformInitializer, self).__init__() + self._low = low + self._high = high + self._seed = seed + self._diag_num = diag_num + self._diag_step = diag_step + self._diag_val = diag_val + + def forward(self, var, block=None): + """Initialize the input tensor with Uniform distribution. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(block, framework.Block) + check_variable_and_dtype(var, "Out", + ["uint16", "float16", "float32", "float64"], + "uniform_random") + + if self._seed == 0: + self._seed = block.program.random_seed + + # to be compatible of fp16 initializers + if var.dtype == VarDesc.VarType.FP16: + out_dtype = VarDesc.VarType.FP32 + out_var = block.create_var(name=unique_name.generate(".".join( + ['uniform_random', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_dtype = var.dtype + out_var = var + + if framework._non_static_mode(): + if in_dygraph_mode(): + out_var = _C_ops.uniform_random(var.shape, out_dtype, self._low, + self._high, self._seed, + _current_expected_place()) + elif _in_legacy_dygraph(): + out_var = _legacy_C_ops.uniform_random( + 'shape', var.shape, 'min', self._low, 'max', self._high, + 'seed', self._seed, 'dtype', out_dtype, 'diag_num', + self._diag_num, 'diag_step', self._diag_step, 'diag_val', + self._diag_val) + if var.dtype == VarDesc.VarType.FP16: + if in_dygraph_mode(): + var_tmp = _C_ops.cast(out_var, var.dtype) + elif _in_legacy_dygraph(): + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', + out_var.dtype, 'out_dtype', + var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + op = block.append_op(type="uniform_random", + inputs={}, + outputs={"Out": out_var}, + attrs={ + "shape": var.shape, + "dtype": out_dtype, + "min": self._low, + "max": self._high, + "seed": self._seed, + "diag_num": self._diag_num, + "diag_step": self._diag_step, + "diag_val": self._diag_val + }, + stop_gradient=True) + + if var.dtype == VarDesc.VarType.FP16: + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + + var.op = op + return op + + +class NormalInitializer(Initializer): + """Implements the Random Normal(Gaussian) distribution initializer + + Args: + loc (float): mean of the normal distribution + scale (float): standard deviation of the normal distribution + seed (int): random seed + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data(name="data", shape=[None, 32, 32], dtype="float32") + fc = fluid.layers.fc(input=x, size=10, + param_attr=fluid.initializer.Normal(loc=0.0, scale=2.0)) + + """ + + def __init__(self, loc=0.0, scale=1.0, seed=0): + assert loc is not None + assert scale is not None + assert seed is not None + super(NormalInitializer, self).__init__() + self._mean = loc + self._std_dev = scale + self._seed = seed + + def forward(self, var, block=None): + """Initialize the input tensor with Normal distribution. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(block, framework.Block) + + check_variable_and_dtype(var, "Out", + ["uint16", "float16", "float32", "float64"], + "guassian_random") + + if self._seed == 0: + self._seed = block.program.random_seed + + if in_dygraph_mode(): + place = _current_expected_place() + out_var = _C_ops.gaussian_random(var.shape, self._mean, + self._std_dev, self._seed, + var.dtype, place) + out_var._share_underline_tensor_to(var) + return None + + if _in_legacy_dygraph(): + out_var = _legacy_C_ops.gaussian_random( + 'shape', var.shape, 'dtype', var.dtype, 'mean', self._mean, + 'std', self._std_dev, 'seed', self._seed, 'use_mkldnn', False) + + out_var._share_underline_tensor_to(var) + return None + else: + op = block.append_op(type="gaussian_random", + outputs={"Out": var}, + attrs={ + "shape": var.shape, + "dtype": var.dtype, + "mean": self._mean, + "std": self._std_dev, + "seed": self._seed, + "use_mkldnn": False + }, + stop_gradient=True) + var.op = op + return op + + +class TruncatedNormalInitializer(Initializer): + """Implements the Random TruncatedNormal(Gaussian) distribution initializer + + Args: + loc (float): mean of the normal distribution + scale (float): standard deviation of the normal distribution + seed (int): random seed + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[None, 1], dtype='float32') + fc = fluid.layers.fc(input=x, size=10, + param_attr=fluid.initializer.TruncatedNormal(loc=0.0, scale=2.0)) + """ + + def __init__(self, loc=0.0, scale=1.0, seed=0): + assert loc is not None + assert scale is not None + assert seed is not None + super(TruncatedNormalInitializer, self).__init__() + self._mean = loc + self._std_dev = scale + self._seed = seed + + def forward(self, var, block=None): + """Initialize the input tensor with TruncatedNormal distribution. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(var, framework.Variable) + assert isinstance(block, framework.Block) + + if self._seed == 0: + self._seed = block.program.random_seed + + # to be compatible of fp16 initalizers + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + out_dtype = VarDesc.VarType.FP32 + out_var = block.create_var(name=unique_name.generate(".".join( + ['truncated_gaussian_random', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_dtype = var.dtype + out_var = var + + if in_dygraph_mode(): + out_var = _C_ops.truncated_gaussian_random( + var.shape, self._mean, self._std_dev, self._seed, out_dtype, + _current_expected_place()) + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + var_tmp = _C_ops.cast(out_var, var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + + if _in_legacy_dygraph(): + out_var = _legacy_C_ops.truncated_gaussian_random( + 'shape', var.shape, 'dtype', out_dtype, 'mean', self._mean, + 'std', self._std_dev, 'seed', self._seed) + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', out_var.dtype, + 'out_dtype', var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + op = block.append_op(type="truncated_gaussian_random", + outputs={"Out": out_var}, + attrs={ + "shape": var.shape, + "dtype": out_dtype, + "mean": self._mean, + "std": self._std_dev, + "seed": self._seed + }, + stop_gradient=True) + + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + var.op = op + return op + + +class XavierInitializer(Initializer): + r""" + This class implements the Xavier weight initializer from the paper + `Understanding the difficulty of training deep feedforward neural + networks `_ + by Xavier Glorot and Yoshua Bengio. + + This initializer is designed to keep the scale of the gradients + approximately same in all the layers. In case of Uniform distribution, + the range is [-x, x], where + + .. math:: + + x = \sqrt{\\frac{6.0}{fan\_in + fan\_out}} + + In case of Normal distribution, the mean is 0 and the standard deviation + is + + .. math:: + + \sqrt{\\frac{2.0}{fan\_in + fan\_out}} + + + Args: + uniform (bool,default True): whether to use uniform ,if False use normal distribution + fan_in (float,default None): fan_in for Xavier initialization. If None, it is + inferred from the variable. + fan_out (float,default None): fan_out for Xavier initialization. If None, it is + inferred from the variable. + seed (int): random seed + + Note: + It is recommended to set fan_in and fan_out to None for most cases. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + queries = fluid.data(name='x', shape=[None,1], dtype='float32') + fc = fluid.layers.fc( + input=queries, size=10, + param_attr=fluid.initializer.Xavier(uniform=False)) + + """ + + def __init__(self, uniform=True, fan_in=None, fan_out=None, seed=0): + assert uniform is not None + assert seed is not None + super(XavierInitializer, self).__init__() + self._uniform = uniform + self._fan_in = fan_in + self._fan_out = fan_out + self._seed = seed + + def forward(self, var, block=None): + """Initialize the input tensor with Xavier initialization. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(block, framework.Block) + check_variable_and_dtype(var, "Out", + ["uint16", "float16", "float32", "float64"], + "xavier_init") + + f_in, f_out = self._compute_fans(var) + + # If fan_in and fan_out are passed, use them + fan_in = f_in if self._fan_in is None else self._fan_in + fan_out = f_out if self._fan_out is None else self._fan_out + + if self._seed == 0: + self._seed = block.program.random_seed + + # to be compatible of fp16 initalizers + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + out_dtype = VarDesc.VarType.FP32 + out_var = block.create_var(name=unique_name.generate(".".join( + ['xavier_init', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_dtype = var.dtype + out_var = var + + if framework._non_static_mode(): + if self._uniform: + limit = math.sqrt(6.0 / float(fan_in + fan_out)) + if in_dygraph_mode(): + out_var = _C_ops.uniform_random(out_var.shape, out_dtype, + -limit, limit, self._seed, + _current_expected_place()) + elif _in_legacy_dygraph(): + out_var = _legacy_C_ops.uniform_random( + 'shape', out_var.shape, 'min', -limit, 'max', limit, + 'seed', self._seed, 'dtype', out_dtype) + else: + std = math.sqrt(2.0 / float(fan_in + fan_out)) + + if in_dygraph_mode(): + place = _current_expected_place() + out_var = _C_ops.gaussian_random(out_var.shape, 0.0, std, + self._seed, out_dtype, + place) + else: + out_var = _legacy_C_ops.gaussian_random( + 'shape', out_var.shape, 'dtype', out_dtype, 'mean', 0.0, + 'std', std, 'seed', self._seed) + + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + if in_dygraph_mode(): + var_tmp = _C_ops.cast(out_var, var.dtype) + elif _in_legacy_dygraph(): + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', + out_var.dtype, 'out_dtype', + var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + if self._uniform: + limit = math.sqrt(6.0 / float(fan_in + fan_out)) + op = block.append_op(type="uniform_random", + inputs={}, + outputs={"Out": out_var}, + attrs={ + "shape": out_var.shape, + "dtype": out_dtype, + "min": -limit, + "max": limit, + "seed": self._seed + }, + stop_gradient=True) + else: + std = math.sqrt(2.0 / float(fan_in + fan_out)) + op = block.append_op(type="gaussian_random", + outputs={"Out": out_var}, + attrs={ + "shape": out_var.shape, + "dtype": out_var.dtype, + "mean": 0.0, + "std": std, + "seed": self._seed + }, + stop_gradient=True) + + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + + var.op = op + return op + + +class MSRAInitializer(Initializer): + r"""Implements the MSRA initializer a.k.a. Kaiming Initializer + + This class implements the weight initialization from the paper + `Delving Deep into Rectifiers: Surpassing Human-Level Performance on + ImageNet Classification `_ + by Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun. This is a + robust initialization method that particularly considers the rectifier + nonlinearities. In case of Uniform distribution, the range is [-x, x], where + + .. math:: + + x = gain \times \sqrt{\frac{3}{fan\_in}} + + In case of Normal distribution, the mean is 0 and the standard deviation + is + + .. math:: + + \frac{gain}{\sqrt{{fan\_in}}} + + Args: + uniform (bool, optional): whether to use uniform or normal distribution + fan_in (float32|None, optional): fan_in (in_features) of trainable Tensor, If None, it will be infered automaticly. If you don't want to use in_features of the Tensor, you can set the value of 'fan_in' smartly by yourself. default is None. + seed (int32, optional): random seed. + negative_slope (float, optional): negative_slope (only used with leaky_relu). default is 0.0. + nonlinearity(str, optional): the non-linear function. default is relu. + + Note: + It is recommended to set fan_in to None for most cases. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + x = fluid.data(name="data", shape=[8, 32, 32], dtype="float32") + fc = fluid.layers.fc(input=x, size=10, + param_attr=fluid.initializer.MSRA(uniform=False)) + + """ + + def __init__(self, + uniform=True, + fan_in=None, + seed=0, + negative_slope=0, + nonlinearity='relu'): + """Constructor for MSRAInitializer + """ + assert uniform is not None + assert seed is not None + super(MSRAInitializer, self).__init__() + self._uniform = uniform + self._fan_in = fan_in + self._seed = seed + self._negative_slope = negative_slope + self._nonlinearity = nonlinearity + + def forward(self, var, block=None): + """Initialize the input tensor with MSRA initialization. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(var, framework.Variable) + assert isinstance(block, framework.Block) + f_in, f_out = self._compute_fans(var) + + # If fan_in is passed, use it + fan_in = f_in if self._fan_in is None else self._fan_in + + if self._seed == 0: + self._seed = block.program.random_seed + + # to be compatible of fp16 initalizers + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + out_dtype = VarDesc.VarType.FP32 + out_var = block.create_var(name=unique_name.generate(".".join( + ['masra_init', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_dtype = var.dtype + out_var = var + + if framework._non_static_mode(): + if self._uniform: + gain = calculate_gain(self._nonlinearity, self._negative_slope) + limit = gain * math.sqrt(3.0 / float(fan_in)) + if in_dygraph_mode(): + out_var = _C_ops.uniform_random(var.shape, out_dtype, + -limit, limit, self._seed, + _current_expected_place()) + else: + out_var = _legacy_C_ops.uniform_random( + 'shape', out_var.shape, 'min', -limit, 'max', limit, + 'seed', self._seed, 'dtype', int(out_dtype)) + else: + gain = calculate_gain(self._nonlinearity, self._negative_slope) + std = gain / math.sqrt(float(fan_in)) + if in_dygraph_mode(): + place = _current_expected_place() + out_var = _C_ops.gaussian_random(out_var.shape, 0.0, std, + self._seed, out_dtype, + place) + else: + out_var = _legacy_C_ops.gaussian_random( + 'shape', out_var.shape, 'dtype', int(out_dtype), 'mean', + 0.0, 'std', std, 'seed', self._seed) + + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + if in_dygraph_mode(): + var_tmp = _C_ops.cast(out_var, var.dtype) + elif _in_legacy_dygraph(): + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', + out_var.dtype, 'out_dtype', + var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + if self._uniform: + gain = calculate_gain(self._nonlinearity, self._negative_slope) + limit = gain * math.sqrt(3.0 / float(fan_in)) + op = block.append_op(type="uniform_random", + inputs={}, + outputs={"Out": out_var}, + attrs={ + "shape": out_var.shape, + "dtype": int(out_dtype), + "min": -limit, + "max": limit, + "seed": self._seed + }, + stop_gradient=True) + + else: + gain = calculate_gain(self._nonlinearity, self._negative_slope) + std = gain / math.sqrt(float(fan_in)) + op = block.append_op(type="gaussian_random", + outputs={"Out": out_var}, + attrs={ + "shape": out_var.shape, + "dtype": int(out_dtype), + "mean": 0.0, + "std": std, + "seed": self._seed + }, + stop_gradient=True) + + if var.dtype == VarDesc.VarType.FP16 or ( + var.dtype == VarDesc.VarType.BF16 and not self._uniform): + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + + var.op = op + return op + + +class BilinearInitializer(Initializer): + """ + This initializer can be used in transposed convolution operator to + act as upsampling. Users can upsample a feature map with shape of + (B, C, H, W) by any integer factor. The usage is: + + Examples: + + .. code-block:: python + + import math + + import paddle + import paddle.nn as nn + from paddle.regularizer import L2Decay + + factor = 2 + C = 2 + B = 8 + H = W = 32 + w_attr = paddle.ParamAttr(learning_rate=0., + regularizer=L2Decay(0.), + initializer=nn.initializer.Bilinear()) + data = paddle.rand([B, 3, H, W], dtype='float32') + conv_up = nn.Conv2DTranspose(3, + out_channels=C, + kernel_size=2 * factor - factor % 2, + padding=int( + math.ceil((factor - 1) / 2.)), + stride=factor, + weight_attr=w_attr, + bias_attr=False) + x = conv_up(data) + + Where, `out_channels=C` and `groups=C` means this is channel-wise transposed + convolution. The filter shape will be (C, 1, K, K) where K is `kernel_size`, + This initializer will set a (K, K) interpolation kernel for every channel + of the filter identically. The resulting shape of the output feature map + will be (B, C, factor * H, factor * W). Note that the learning rate and the + weight decay are set to 0 in order to keep coefficient values of bilinear + interpolation unchanged during training. + + """ + + def __init__(self): + """Constructor for BilinearInitializer. + """ + super(BilinearInitializer, self).__init__() + + def forward(self, var, block=None): + """Initialize the input tensor with Bilinear initialization. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + if not isinstance(var, framework.Variable): + raise ValueError("var must be framework.Variable.") + + if not isinstance(block, framework.Block): + raise ValueError("block must be framework.Block.") + + shape = var.shape + if len(shape) != 4: + raise ValueError("the length of shape must be 4.") + if shape[2] != shape[3]: + raise ValueError("shape[2] must be equal to shape[3].") + + weight = np.zeros(np.prod(var.shape), dtype='float32') + size = shape[3] + # factor + f = np.ceil(size / 2.) + # center + c = (2 * f - 1 - f % 2) / (2. * f) + for i in range(np.prod(shape)): + x = i % size + y = (i / size) % size + weight[i] = (1 - abs(x / f - c)) * (1 - abs(y / f - c)) + weight = np.reshape(weight, shape) + + # to be compatible of fp16 initalizers + if var.dtype in [ + VarDesc.VarType.FP16, VarDesc.VarType.BF16, VarDesc.VarType.FP64 + ]: + out_dtype = VarDesc.VarType.FP32 + out_var = block.create_var(name=unique_name.generate(".".join( + ['bilinear_init', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_dtype = var.dtype + out_var = var + + if out_dtype == VarDesc.VarType.FP32: + value_name = "fp32_values" + values = [float(v) for v in weight.flat] + else: + raise TypeError("Unsupported dtype %s", var.dtype) + + if np.prod(shape) > 1024 * 1024: + raise ValueError("The size of input is too big. ") + + if framework._non_static_mode(): + if in_dygraph_mode(): + _C_ops.assign_value_(out_var, list(shape), out_dtype, values, + _current_expected_place()) + elif _in_legacy_dygraph(): + _legacy_C_ops.assign_value(out_var, 'shape', list(shape), + 'dtype', out_dtype, value_name, + values) + if var.dtype in [ + VarDesc.VarType.FP16, VarDesc.VarType.BF16, + VarDesc.VarType.FP64 + ]: + if in_dygraph_mode(): + var_tmp = _C_ops.cast(out_var, var.dtype) + elif _in_legacy_dygraph(): + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', + out_var.dtype, 'out_dtype', + var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + op = block.append_op(type='assign_value', + outputs={'Out': [out_var]}, + attrs={ + 'dtype': out_dtype, + 'shape': list(shape), + value_name: values + }) + + if var.dtype in [ + VarDesc.VarType.FP16, VarDesc.VarType.BF16, + VarDesc.VarType.FP64 + ]: + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + + var.op = op + return op + + +class NumpyArrayInitializer(Initializer): + """Init an parameter with an numpy array + This op initialize the variable by numpy array. + + Args: + value (numpy): numpy array to initialize the variable + + Returns: + A Tensor variable initialized by numpy. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + x = fluid.data(name="x", shape=[2, 1], dtype='float32') + fc = fluid.layers.fc(input=x, size=10, + param_attr=fluid.initializer.NumpyArrayInitializer(numpy.array([1,2]))) + """ + + def __init__(self, value): + import numpy + assert isinstance(value, numpy.ndarray) + super(NumpyArrayInitializer, self).__init__() + self._value = value + + def forward(self, var, block=None): + """Initialize the input tensor with Numpy array. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The initialization op + """ + block = self._check_block(block) + + assert isinstance(var, framework.Variable) + assert isinstance(block, framework.Block) + + # to be compatible of fp16 initalizers + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + out_dtype = VarDesc.VarType.FP32 + np_value = self._value.astype("float32") + out_var = block.create_var(name=unique_name.generate(".".join( + ['numpy_array_init', var.name, 'tmp'])), + shape=var.shape, + dtype=out_dtype, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_var = var + out_dtype = var.dtype + np_value = self._value + + if out_dtype == VarDesc.VarType.FP32: + value_name = "fp32_values" + values = [float(v) for v in np_value.flat] + elif out_dtype == VarDesc.VarType.INT32: + value_name = "int32_values" + values = [int(v) for v in np_value.flat] + else: + raise ValueError("Unsupported dtype %s", self._value.dtype) + if self._value.size > 1024 * 1024 * 1024: + raise ValueError("The size of input is too big. Please consider " + "saving it to file and 'load_op' to load it") + + if framework._non_static_mode(): + if in_dygraph_mode(): + _C_ops.assign_value_(out_var, + list(self._value.shape), out_dtype, values, + _current_expected_place()) + elif _in_legacy_dygraph(): + _legacy_C_ops.assign_value(out_var, 'shape', + list(self._value.shape), 'dtype', + out_dtype, value_name, values) + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + if in_dygraph_mode(): + var_tmp = _C_ops.cast(out_var, var.dtype) + elif _in_legacy_dygraph(): + var_tmp = _legacy_C_ops.cast(out_var, 'in_dtype', + out_var.dtype, 'out_dtype', + var.dtype) + var_tmp._share_underline_tensor_to(var) + else: + out_var._share_underline_tensor_to(var) + return None + else: + op = block.append_op(type='assign_value', + outputs={'Out': out_var}, + attrs={ + 'dtype': out_dtype, + 'shape': list(self._value.shape), + value_name: values + }, + stop_gradient=True) + + if var.dtype in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]: + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }) + + var.op = op + return op + + +def set_global_initializer(weight_init, bias_init=None): + """ + This API is used to set up global model parameter initializer in framework. + + After this API is invoked, the global initializer will takes effect in subsequent code. + + The model parameters include ``weight`` and ``bias`` . In the framework, they correspond + to ``paddle.ParamAttr`` , which is inherited from ``paddle.Tensor`` , and is a persistable Variable. + This API only takes effect for model parameters, not for variables created through apis such as + :ref:`api_fluid_layers_create_global_var` , :ref:`api_fluid_layers_create_tensor`. + + If the initializer is also set up by ``param_attr`` or ``bias_attr`` when creating a network layer, + the global initializer setting here will not take effect because it has a lower priority. + + If you want to cancel the global initializer in framework, please set global initializer to ``None`` . + + Args: + weight_init (Initializer): set the global initializer for ``weight`` of model parameters. + bias_init (Initializer, optional): set the global initializer for ``bias`` of model parameters. + Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + nn.initializer.set_global_initializer(nn.initializer.Uniform(), nn.initializer.Constant()) + x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.) + + # The weight of conv1 is initialized by Uniform + # The bias of conv1 is initialized by Constant + conv1 = nn.Conv2D(4, 6, (3, 3)) + y_var1 = conv1(x_var) + + # If set param_attr/bias_attr too, global initializer will not take effect + # The weight of conv2 is initialized by Xavier + # The bias of conv2 is initialized by Normal + conv2 = nn.Conv2D(4, 6, (3, 3), + weight_attr=nn.initializer.XavierUniform(), + bias_attr=nn.initializer.Normal()) + y_var2 = conv2(x_var) + + # Cancel the global initializer in framework, it will takes effect in subsequent code + nn.initializer.set_global_initializer(None) + """ + + check_type(weight_init, 'weight_init', (Initializer, type(None)), + 'set_global_initializer') + global _global_weight_initializer_ + _global_weight_initializer_ = weight_init + + check_type(bias_init, 'bias_init', (Initializer, type(None)), + 'set_global_initializer') + global _global_bias_initializer_ + _global_bias_initializer_ = bias_init + + +def _global_weight_initializer(): + """ + Return the global weight initializer, The user doesn't need to use it. + """ + return _global_weight_initializer_ + + +def _global_bias_initializer(): + """ + Return the global weight initializer, The user doesn't need to use it. + """ + return _global_bias_initializer_ + + +def calculate_gain(nonlinearity, param=None): + """ + Get the recommended ``gain`` value of some nonlinearity function. ``gain`` value can be used in some + ``paddle.nn.initializer`` api to adjust the initialization value. + + Args: + nonlinearity(str): name of nonlinearity activation function. If it is a linear function, such as: + `linear/conv1d/conv2d/conv3d/conv1d_transpose/conv2d_transpose/conv3d_transpose` , 1.0 will be returned. + param(bool|int|float, optional): optional parameter for somme nonlinearity function. Now, it only applies to + 'leaky_relu'. Default: None, it will be calculated as 0.01 in the formula. + + Returns: + A float value, which is the recommended gain for this nonlinearity function. + + Examples: + .. code-block:: python + + import paddle + gain = paddle.nn.initializer.calculate_gain('tanh') # 5.0 / 3 + gain = paddle.nn.initializer.calculate_gain('leaky_relu', param=1.0) # 1.0 = math.sqrt(2.0 / (1+param^2)) + initializer = paddle.nn.initializer.Orthogonal(gain) + + """ + if param is None: + param = 0.01 + else: + assert isinstance(param, (bool, int, float)) + param = float(param) + recommended_gain = { + 'sigmoid': 1, + 'linear': 1, + 'conv1d': 1, + 'conv2d': 1, + 'conv3d': 1, + 'conv1d_transpose': 1, + 'conv2d_transpose': 1, + 'conv3d_transpose': 1, + 'tanh': 5.0 / 3, + 'relu': math.sqrt(2.0), + 'leaky_relu': math.sqrt(2.0 / (1 + param**2)), + 'selu': 3.0 / 4 + } + if nonlinearity in recommended_gain.keys(): + return recommended_gain[nonlinearity] + else: + raise ValueError( + "nonlinearity function {} is not suppported now.".format( + nonlinearity)) + + +# We short the class name, since users will use the initializer with the package +# name. The sample code: +# +# import paddle.fluid as fluid +# +# hidden = fluid.layers.fc(..., +# param_attr=ParamAttr(fluid.initializer.Xavier())) +# +# It is no need to add an `Initializer` as the class suffix +Constant = ConstantInitializer +Uniform = UniformInitializer +Normal = NormalInitializer +TruncatedNormal = TruncatedNormalInitializer +Xavier = XavierInitializer +MSRA = MSRAInitializer +Bilinear = BilinearInitializer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/input.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/input.py new file mode 100644 index 0000000000000000000000000000000000000000..502a89ec36d366f038104d9f59a3f88b8e7397ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/input.py @@ -0,0 +1,338 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function +import warnings +from .framework import Variable, _non_static_mode, static_only +from .layer_helper import LayerHelper +from .data_feeder import check_variable_and_dtype, check_dtype +from ..utils import deprecated + +__all__ = ['one_hot', 'embedding'] + + +@deprecated(since='2.0.0', update_to='paddle.nn.functional.one_hot') +def one_hot(input, depth, allow_out_of_range=False): + """ + :alias_main: paddle.nn.functional.one_hot + :alias: paddle.nn.functional.one_hot,paddle.nn.functional.common.one_hot + :old_api: paddle.fluid.one_hot + + The operator converts each id in the input to an one-hot vector with a + depth length. The value in the vector dimension corresponding to the id + is 1, and the value in the remaining dimension is 0. + + The shape of output Tensor or LoDTensor is generated by appending depth dimension + behind the last dimension of the input shape. + + .. code-block:: text + + Example 1 (allow_out_of_range=False): + + input: + X.shape = [4] + X.data = [1, 1, 3, 0] + depth = 4 + + output: + Out.shape = [4, 4] + Out.data = [[0., 1., 0., 0.], + [0., 1., 0., 0.], + [0., 0., 0., 1.], + [1., 0., 0., 0.]] + + Example 2 (allow_out_of_range=True): + + input: + X.shape = [4] + X.data = [1, 1, 5, 0] + depth = 4 + allow_out_of_range = True + + output: + Out.shape = [4, 4] + Out.data = [[0., 1., 0., 0.], + [0., 1., 0., 0.], + [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data. + [1., 0., 0., 0.]] + + Example 3 (allow_out_of_range=False): + + input: + X.shape = [4] + X.data = [1, 1, 5, 0] + depth = 4 + allow_out_of_range = False + + output: Throw an exception for Illegal value + The second dimension in X is 5, which is greater than depth. + Allow_out_of_range =False means that does not allow the word id to exceed depth, + so it throws an exception. + + + Args: + input(Variable): Tensor or LoDTensor with shape :math:`[N_1, N_2, ..., N_k]` , + which contains at least one dimension. The data type is int32 or int64. + depth(int): An integer defining the depth of the one hot dimension. If input + is word id, depth is generally the dictionary size. + allow_out_of_range(bool): A bool value indicating whether the input + indices could be out of range :math:`[0, depth)` . When input indices are + out of range, exceptions :code:`Illegal value` is raised if :attr:`allow_out_of_range` + is False, or zero-filling representations is created if it is set True. + Default: False. + + Returns: + Variable: The one-hot representations of input. A Tensor or LoDTensor with type float32. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4]. + label = fluid.data(name="label", shape=[4], dtype="int64") + one_hot_label = fluid.one_hot(input=label, depth=4) + """ + check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'one_hot_v2') + helper = LayerHelper("one_hot_v2", **locals()) + + one_hot_out = helper.create_variable_for_type_inference(dtype='float32') + + if _non_static_mode(): + inputs = {'X': input} + attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range} + else: + if not isinstance(depth, Variable): + # user attribute + inputs = {'X': input} + attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range} + else: + depth.stop_gradient = True + inputs = {'X': input, 'depth_tensor': depth} + attrs = {'allow_out_of_range': allow_out_of_range} + helper.append_op(type="one_hot_v2", + inputs=inputs, + attrs=attrs, + outputs={'Out': one_hot_out}, + stop_gradient=True) + return one_hot_out + + +@static_only +@deprecated(since='2.0.0', update_to='paddle.nn.functional.embedding') +def embedding(input, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32'): + r""" + :api_attr: Static Graph + + The operator is used to lookup embeddings vector of ids provided by :attr:`input` . + It automatically constructs a 2D embedding matrix based on the + input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` . + + The shape of output Tensor is generated by appending an emb_size dimension to the + last dimension of the input Tensor shape. + + **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , + otherwise the program will throw an exception and exit. + + .. code-block:: text + + Case 1: + + input is a Tensor. padding_idx = -1 + input.data = [[1, 3], [2, 4], [4, 127]] + input.shape = [3, 2] + Given size = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when ids is 127. + + Case 2: + + input is a LoDTensor with 1-level LoD. padding_idx = 0 + input.lod = [[2, 3]] + input.data = [[1], [3], [2], [4], [0]] + input.shape = [5, 1] + Given size = [128, 16] + output is a LoDTensor: + out.lod = [[2, 3]] + out.shape = [5, 1, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452]], + [[0.345421456, 0.524563927, ..., 0.144534654]], + [[0.345249859, 0.124939536, ..., 0.194353745]], + [[0.945345345, 0.435394634, ..., 0.435345365]], + [[0.0, 0.0, ..., 0.0 ]]] # padding data + It will pad all-zero data when ids is 0. + + + Args: + input(Variable): A Tensor or LoDTensor with type int64, which contains the id information. + The value of the input id should satisfy :math:`0<= id < size[0]` . + size(tuple|list): The shape of lookup table parameter. It should have two elements which + indicates the size of the dictionary of embeddings and the size of each embedding vector respectively. + is_sparse(bool): The flag indicating whether to use sparse update. This parameter only + affects the performance of the backwards gradient update. It is recommended to set + True because sparse update is faster. But some optimizer does not support sparse update + In these case, is_sparse must be False. Default: False. + is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used + in multi-machine distributed CPU training. Default: False. + padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup + encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. + If set None, it makes no effect to output. Default: None. + param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. In addition, + user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. + The local word vector needs to be transformed into numpy format, and the shape of local word + vector should be consistent with :attr:`size` . + dtype(str): It refers to the data type of output Tensor. + It must be float32 or float64. Default: float32. + + Returns: + Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` . + + Static Examples: + .. code-block:: python + + import paddle + import numpy as np + paddle.enable_static() + + x = paddle.static.data(name="x", shape = [2, 4], dtype=np.int64) + embedding = paddle.nn.Embedding(10, 3, + weight_attr=paddle.nn.initializer.Constant(value=1.0)) + adam = paddle.optimizer.SGD(parameters=[embedding.weight], learning_rate=0.01) + output = embedding(x) + m_output=paddle.mean(output) + + adam.minimize(m_output) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + + x = np.array([[7, 2, 4, 5],[4, 3, 2, 9]], dtype=np.int64) + + # x is a Numpy. + # x.data = [[7, 2, 4, 5], [4, 3, 2, 9]] + # x.shape = [2, 4] + + out, = exe.run(paddle.static.default_main_program(), feed={'x':x}, fetch_list=[output]) + + # out is a Numpy. + # out.data = [[1., 1., 1.], + # [1., 1., 1.], + # [1., 1., 1.], + # [1., 1., 1.]], + # + # [[1., 1., 1.], + # [1., 1., 1.], + # [1., 1., 1.], + # [0., 0., 0.]]] + # out.shape = [2, 4, 3] + + + Dygraph Examples: + .. code-block:: python + + import paddle + import numpy as np + + x_data = np.arange(3, 6).reshape((3, 1)).astype(np.int64) + + # x is a Tensor. + # x.data = [[3], [4], [5]] + # x.shape = [3, 1] + x = paddle.to_tensor(x_data, stop_gradient=False) + + # embedding weight shape = [10, 3] + embedding = paddle.nn.Embedding(10, 3, sparse=True) + + # embedding weight data = [10, 3] + w0 = np.full(shape=(10, 3), fill_value=2).astype(np.float32) + + # embedding.weight.shape = [10, 3] + # embedding.weight.data = + # [[2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.], + # [2., 2., 2.]] + embedding.weight.set_value(w0) + + adam = paddle.optimizer.Adam( + parameters=[embedding.weight], learning_rate=0.01) + adam.clear_grad() + + # out is Tensor + # out.shape: [3, 1, 3] + # out.layout: NCHW + # out.dtype: float + # out.data: [2 2 2 2 2 2 2 2 2] + out = embedding(x) + + out.backward() + adam.step() + + """ + + helper = LayerHelper('embedding', **locals()) + check_variable_and_dtype(input, 'input', ['int64'], 'fluid.embedding') + check_dtype(dtype, 'dtype', ['float16', 'float32', 'float64', 'uint16'], + 'fluid.embedding') + remote_prefetch = is_sparse and (not is_distributed) + if remote_prefetch: + assert is_sparse is True and is_distributed is False + w = helper.create_parameter(attr=helper.param_attr, + shape=size, + dtype=dtype, + is_bias=False) + tmp = helper.create_variable_for_type_inference(dtype) + padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( + size[0] + padding_idx) + helper.append_op(type='lookup_table_v2', + inputs={ + 'Ids': input, + 'W': w + }, + outputs={'Out': tmp}, + attrs={ + 'is_sparse': is_sparse, + 'is_distributed': is_distributed, + 'remote_prefetch': remote_prefetch, + 'padding_idx': padding_idx + }) + return tmp diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/install_check.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/install_check.py new file mode 100644 index 0000000000000000000000000000000000000000..98d7fa6a037a6c62ee02ea07b0a489141d8331f2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/install_check.py @@ -0,0 +1,165 @@ +# 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. + +import os +import paddle +from .framework import Program, program_guard, unique_name, cuda_places, cpu_places +from .param_attr import ParamAttr +from .initializer import Constant +from . import layers +from . import backward +from .dygraph import Layer, nn +from . import executor +from . import optimizer +from . import core +from . import compiler +import logging +import numpy as np + +__all__ = ['run_check'] + + +class SimpleLayer(Layer): + + def __init__(self, input_size): + super(SimpleLayer, self).__init__() + self._linear1 = nn.Linear( + input_size, + 3, + param_attr=ParamAttr(initializer=Constant(value=0.1))) + + def forward(self, inputs): + x = self._linear1(inputs) + x = layers.reduce_sum(x) + return x + + +def run_check(): + """To check whether install is successful + This func should not be called only if you need to verify installation + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + fluid.install_check.run_check() + + # If installed successfully, output may be + # Running Verify Fluid Program ... + # W0805 04:24:59.496919 35357 device_context.cc:268] Please NOTE: device: 0, CUDA Capability: 70, Driver API Version: 10.2, Runtime API Version: 10.1 + # W0805 04:24:59.505594 35357 device_context.cc:276] device: 0, cuDNN Version: 7.6. + # Your Paddle Fluid works well on SINGLE GPU or CPU. + # Your Paddle Fluid works well on MUTIPLE GPU or CPU. + # Your Paddle Fluid is installed successfully! Let's start deep Learning with Paddle Fluid now + """ + paddle.enable_static() + + print("Running Verify Fluid Program ... ") + + device_list = [] + if core.is_compiled_with_cuda(): + try: + core.get_cuda_device_count() + except Exception as e: + logging.warning( + "You are using GPU version Paddle Fluid, But Your CUDA Device is not set properly" + "\n Original Error is {}".format(e)) + return 0 + device_list = cuda_places() + else: + device_list = [core.CPUPlace(), core.CPUPlace()] + + np_inp_single = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + inp = [] + for i in range(len(device_list)): + inp.append(np_inp_single) + np_inp_muti = np.array(inp) + np_inp_muti = np_inp_muti.reshape(len(device_list), 2, 2) + + def test_parallerl_exe(): + train_prog = Program() + startup_prog = Program() + scope = core.Scope() + with executor.scope_guard(scope): + with program_guard(train_prog, startup_prog): + with unique_name.guard(): + build_strategy = compiler.BuildStrategy() + build_strategy.enable_inplace = True + inp = layers.data(name="inp", shape=[2, 2]) + simple_layer = SimpleLayer(input_size=2) + out = simple_layer(inp) + exe = executor.Executor( + core.CUDAPlace(0) if core.is_compiled_with_cuda() and + (core.get_cuda_device_count() > 0) else core.CPUPlace()) + loss = paddle.mean(out) + loss.persistable = True + optimizer.SGD(learning_rate=0.01).minimize(loss) + startup_prog.random_seed = 1 + compiled_prog = compiler.CompiledProgram( + train_prog).with_data_parallel( + build_strategy=build_strategy, + loss_name=loss.name, + places=device_list) + exe.run(startup_prog) + + exe.run(compiled_prog, + feed={inp.name: np_inp_muti}, + fetch_list=[loss.name]) + + def test_simple_exe(): + train_prog = Program() + startup_prog = Program() + scope = core.Scope() + with executor.scope_guard(scope): + with program_guard(train_prog, startup_prog): + with unique_name.guard(): + inp0 = layers.data(name="inp", + shape=[2, 2], + append_batch_size=False) + simple_layer0 = SimpleLayer(input_size=2) + out0 = simple_layer0(inp0) + param_grads = backward.append_backward( + out0, + parameter_list=[simple_layer0._linear1.weight.name])[0] + exe0 = executor.Executor( + core.CUDAPlace(0) if core.is_compiled_with_cuda() and + (core.get_cuda_device_count() > 0) else core.CPUPlace()) + exe0.run(startup_prog) + exe0.run(feed={inp0.name: np_inp_single}, + fetch_list=[out0.name, param_grads[1].name]) + + test_simple_exe() + + print("Your Paddle Fluid works well on SINGLE GPU or CPU.") + try: + test_parallerl_exe() + print("Your Paddle Fluid works well on MUTIPLE GPU or CPU.") + print( + "Your Paddle Fluid is installed successfully! Let's start deep Learning with Paddle Fluid now" + ) + except Exception as e: + logging.warning( + "Your Paddle Fluid has some problem with multiple GPU. This may be caused by:" + "\n 1. There is only 1 or 0 GPU visible on your Device;" + "\n 2. No.1 or No.2 GPU or both of them are occupied now" + "\n 3. Wrong installation of NVIDIA-NCCL2, please follow instruction on https://github.com/NVIDIA/nccl-tests " + "\n to test your NCCL, or reinstall it following https://docs.nvidia.com/deeplearning/sdk/nccl-install-guide/index.html" + ) + + print("\n Original Error is: {}".format(e)) + print( + "Your Paddle Fluid is installed successfully ONLY for SINGLE GPU or CPU! " + "\n Let's start deep Learning with Paddle Fluid now") + + paddle.disable_static() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/io.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7169a90a98f4152104807df219b561a0f3369e8a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/io.py @@ -0,0 +1,2376 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import os +import errno +import warnings +import six +import logging +import pickle +import contextlib +from functools import reduce +import sys +from io import BytesIO + +import numpy as np +import math +import paddle +from paddle.fluid import layers +from paddle.fluid.executor import Executor, global_scope +from paddle.fluid.evaluator import Evaluator +from paddle.fluid.framework import Program, Parameter, default_main_program, default_startup_program, Variable, \ + program_guard, dygraph_not_support, static_only +from paddle.reader import cache, map_readers, buffered, compose, chain, shuffle, \ + ComposeNotAligned, firstn, xmap_readers, multiprocess_reader +from .wrapped_decorator import signature_safe_contextmanager +from paddle.fluid.compiler import CompiledProgram +from paddle.fluid.log_helper import get_logger +from . import reader +from . import unique_name +from .reader import * +from . import dataloader +from .dataloader import * +from . import core +from .. import compat as cpt +from paddle.utils import deprecated +from paddle.fluid.framework import static_only + +batch = paddle.batch + +__all__ = [ + 'save_vars', + 'save_params', + 'save_persistables', + 'load_vars', + 'load_params', + 'load_persistables', + 'save_inference_model', + 'load_inference_model', + 'batch', + 'save', + 'load', + 'load_program_state', + 'set_program_state', + 'get_program_parameter', + 'get_program_persistable_vars', +] + reader.__all__ + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +class _open_buffer(object): + + def __init__(self, buffer): + self.buffer = buffer + + def __enter__(self): + return self.buffer + + +class _buffer_reader(_open_buffer): + + def __init__(self, buffer): + super(_buffer_reader, self).__init__(buffer) + self.initial_tell = self.buffer.tell() + + def __exit__(self, *args): + # `args[0]` is type of exception. When the `read` is abnormal, the file pointer returns to the initial position. + if args[0] is not None: + self.buffer.seek(self.initial_tell) + + +class _buffer_writer(_open_buffer): + + def __exit__(self, *args): + self.buffer.flush() + + +def _is_file_path(path): + return isinstance(path, str) + + +def _open_file_buffer(path_or_buffer, mode): + + if _is_file_path(path_or_buffer): + return open(path_or_buffer, mode) + else: + if 'w' in mode: + return _buffer_writer(path_or_buffer) + elif 'r' in mode: + return _buffer_reader(path_or_buffer) + else: + raise ValueError( + "Expected 'r' or 'w' in mode but got {}".format(mode)) + + +def _is_memory_buffer(buffer): + return isinstance(buffer, BytesIO) + + +def is_parameter(var): + """ + Check whether the given variable is an instance of Parameter. + + Args: + var(Variable): The variable to be checked. + + Returns: + bool: True if the given `var` is an instance of Parameter, + False if not. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + param = fluid.default_main_program().global_block().var('fc.w') + res = fluid.io.is_parameter(param) + """ + return isinstance(var, Parameter) + + +def is_persistable(var): + """ + Check whether the given variable is persistable. + + Args: + var(Variable): The variable to be checked. + + Returns: + bool: True if the given `var` is persistable + False if not. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + param = fluid.default_main_program().global_block().var('fc.b') + res = fluid.io.is_persistable(param) + """ + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + +def is_belong_to_optimizer(var): + if not (isinstance(var, Parameter) or var.desc.need_check_feed()): + return is_persistable(var) + + return False + + +@dygraph_not_support +def get_program_parameter(program): + """ + Get all the parameters from Program. + + Args: + var(Program): The Program to get parameters + + Returns: + list: The list contains all parameters in the program + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + data = fluid.data(name="img", shape=[64, 784]) + w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w') + b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b') + list_para = fluid.io.get_program_parameter( fluid.default_main_program() ) + """ + return list(filter(is_parameter, program.list_vars())) + + +@dygraph_not_support +def get_program_persistable_vars(program): + """ + Get all the persistable vars from Program. + + Args: + var(Program): The Program to get persistable vars + + Returns: + list: The list contains all persistable vars in the program + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + data = fluid.data(name="img", shape=[64, 784]) + w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w') + b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b') + list_para = fluid.io.get_program_persistable_vars( fluid.default_main_program() ) + """ + return list(filter(is_persistable, program.list_vars())) + + +def _clone_var_in_block_(block, var): + assert isinstance(var, Variable) + if var.desc.type() == core.VarDesc.VarType.LOD_TENSOR: + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=True) + else: + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + persistable=True) + + +@signature_safe_contextmanager +def _load_program_scope(main=None, startup=None, scope=None): + prog = main if main else paddle.fluid.Program() + startup_prog = startup if startup else paddle.fluid.Program() + scope = scope if scope else paddle.fluid.core.Scope() + with paddle.fluid.scope_guard(scope): + with paddle.fluid.program_guard(prog, startup_prog): + with paddle.fluid.unique_name.guard(): + with paddle.fluid.framework._dygraph_guard(None): + yield + + +def _get_valid_program(main_program=None): + if main_program is None: + main_program = default_main_program() + elif isinstance(main_program, CompiledProgram): + main_program = main_program._program + if main_program is None: + raise TypeError( + "The type of input main_program is invalid, expected tyep is Program, but received None" + ) + warnings.warn( + "The input is a CompiledProgram, this is not recommended.") + if not isinstance(main_program, Program): + raise TypeError( + "The type of input main_program is invalid, expected type is fluid.Program, but received %s" + % type(main_program)) + return main_program + + +@dygraph_not_support +def save_vars(executor, + dirname, + main_program=None, + vars=None, + predicate=None, + filename=None): + """ + Save specific variables in the `Program` to files. + + There are two ways to specify the variables to be saved: set variables in + a list and assign it to the `vars`, or use the `predicate` function to select + variables that make `predicate(variable) == True`. The first way has a higher priority. + + The `dirname` is used to specify the folder where to save variables. + If you prefer to save variables in separate files in the `dirname` folder, + do not set `filename`. If you prefer to save all variables in a single file, + use `filename` to specify it. + + Args: + executor(Executor): The executor to run for saving variables. + dirname(str, optional): The folder where to save variables. + When you need to save the parameter to the memory, set it to None. + main_program(Program, optional): The program whose variables will be saved. + If it is None, the default main program will + be used automatically. + Default: None + vars(list[Variable], optional): The list contains all variables to be saved. + Default: None + predicate(function, optional): The function selects the variables that make + `predicate(variable) == True`. + Default: None + filename(str, optional): If you prefer to save all variables in a single file, + use `filename` to specify it. Otherwise, let `filename` be None. + Default: None + + Returns: + str: When saving parameters to a file, returns None. + When saving parameters to memory, returns a binary string containing parameters. + + Raises: + TypeError: If `main_program` is not an instance of Program nor None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + main_prog = fluid.Program() + startup_prog = fluid.Program() + with fluid.program_guard(main_prog, startup_prog): + data = fluid.layers.data(name="img", shape=[64, 784], append_batch_size=False) + w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w') + b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b') + hidden_w = fluid.layers.matmul(x=data, y=w) + hidden_b = fluid.layers.elementwise_add(hidden_w, b) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(startup_prog) + + # The first usage: use `vars` to set the saved variables. + var_list = [w, b] + path = "./my_paddle_vars" + fluid.io.save_vars(executor=exe, dirname=path, vars=var_list, + filename="vars_file") + # w and b will be save in a file named "var_file". + + # The second usage: use `predicate` to select the saved variable. + def name_has_fc(var): + res = "fc" in var.name + return res + param_path = "./my_paddle_model" + fluid.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog, vars=None, predicate = name_has_fc) + # all variables whose names contain "fc " are saved. + """ + save_to_memory = False + if dirname is None and filename is None: + save_to_memory = True + + main_program = _get_valid_program(main_program) + + if vars is None: + return save_vars(executor, + main_program=main_program, + dirname=dirname, + vars=list(filter(predicate, main_program.list_vars())), + filename=filename) + else: + params_var_name = "saved_params" + # give warning when there is no var in model + if len(list(vars)) == 0: + warnings.warn( + "no variable in your model, please ensure there are any variables in your model to save" + ) + return None + + save_program = Program() + save_block = save_program.global_block() + + save_var_map = {} + for each_var in vars: + # NOTE: don't save the variable which type is RAW + if each_var.type == core.VarDesc.VarType.RAW: + continue + new_var = _clone_var_in_block_(save_block, each_var) + if filename is None and save_to_memory is False: + save_file_path = os.path.join(os.path.normpath(dirname), + new_var.name) + save_block.append_op( + type='save', + inputs={'X': [new_var]}, + outputs={}, + attrs={'file_path': os.path.normpath(save_file_path)}) + else: + save_var_map[new_var.name] = new_var + + if filename is not None or save_to_memory: + save_var_list = [] + for name in sorted(save_var_map.keys()): + save_var_list.append(save_var_map[name]) + + save_path = str() + if save_to_memory is False: + save_path = os.path.join(os.path.normpath(dirname), filename) + + saved_params = save_block.create_var(type=core.VarDesc.VarType.RAW, + name=params_var_name) + saved_params.desc.set_persistable(True) + save_block.append_op(type='save_combine', + inputs={'X': save_var_list}, + outputs={'Y': saved_params}, + attrs={ + 'file_path': save_path, + 'save_to_memory': save_to_memory + }) + + # NOTE(zhiqiu): save op will add variable kLookupTablePath in save_program.desc, + # which leads to diff on save_program and its desc. Call _sync_with_cpp + # to keep consistency. + save_program._sync_with_cpp() + executor.run(save_program) + if save_to_memory: + return global_scope().find_var(params_var_name).get_bytes() + + +@dygraph_not_support +def save_params(executor, dirname, main_program=None, filename=None): + """ + Save all parameters from the :code:`main_program` to + the folder :code:`dirname` or file :code:`filename`. You can refer to + :ref:`api_guide_model_save_reader_en` for more details. + + Use the :code:`dirname` to specify the saving folder. If you would like to + save parameters in separate files, set :code:`filename` None; if you would + like to save all parameters in a single file, use :code:`filename` to specify + the file name. + + Note: + Some variables are not Parameter while they are necessary for + training, such as learning rate, global step, etc. So you can NOT save + and continue your training just by :ref:`api_fluid_io_save_params` + and :ref:`api_fluid_io_load_params`. Please use :ref:`api_fluid_io_save_persistables` + and :ref:`api_fluid_io_load_persistables` instead. + + If you want to save your model for the inference, please use the + :ref:`api_fluid_io_save_inference_model`. You can refer to + :ref:`api_guide_model_save_reader_en` for more details. + + Args: + executor(Executor): The executor to run for saving parameters, You can + refer to :ref:`api_guide_executor_en`. + dirname(str, optional): The saving directory path. + When you need to save the parameter to the memory, set it to None. + main_program(Program, optional): The program whose parameters will be + saved. You can refer to + :ref:`api_guide_Program_en` for more + details. If it is None, the default main + program will be used. + Default: None + filename(str, optional): The file to save all parameters. If you prefer + to save parameters in different files, set it + to None. + Default: None + + Returns: + str: When saving parameters to a file, returns None. + When saving parameters to memory, returns a binary string containing parameters. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + + paddle.enable_static() + params_path = "./my_paddle_model" + image = fluid.data(name='img', shape=[None, 28, 28], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + feeder = fluid.DataFeeder(feed_list=[image, label], place=fluid.CPUPlace()) + predict = fluid.layers.fc(input=image, size=10, act='softmax') + + loss = fluid.layers.cross_entropy(input=predict, label=label) + avg_loss = paddle.mean(loss) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + fluid.io.save_params(executor=exe, dirname=params_path) + # The parameters weights and bias of the fc layer in the network are going to + # be saved in different files in the path "./my_paddle_model" + """ + return save_vars(executor, + dirname=dirname, + main_program=main_program, + vars=None, + predicate=is_parameter, + filename=filename) + + +def _save_distributed_persistables(executor, dirname, main_program): + """ + save_persistables for distributed training. + the method will do things listed below: + 1.save part of persistable variables on trainer. + 2.receive "remote prefetch variables" from parameter servers and merge them. + 3.save "distributed lookup table" on parameter servers. + 4.receive "optimizer variables" from parameter servers and merge them. + + Args: + executor(Executor): The executor to run for saving parameters. + dirname(str): The saving directory path. + main_program(Program): The program whose parameters will be + saved. the main_program must be the trainer_program + get after transpiler. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + param_path = "./my_paddle_model" + t = distribute_transpiler.DistributeTranspiler() + t.transpile(...) + train_program = t.get_trainer_program() + _save_distributed_persistables(executor=exe, dirname=param_path, main_program=train_program) + """ + + def __save_remote_params(executor, dirname, remote_params_map): + """ + receive params on pserver through rpc. + if the params are be sliced, will concat them to one, then save it. + """ + if not remote_params_map: + return + + prog = Program() + block = prog.global_block() + + # recv optimize vars from pserver + for name, remote_params in remote_params_map.items(): + origin = remote_params[0].origin + is_slice = remote_params[0].is_slice + + slices = [None] * len(remote_params) + slice_varnames = [None] * len(remote_params) + remote_varnames = [None] * len(remote_params) + endpoints = [None] * len(remote_params) + + for idx, optimizer in enumerate(remote_params): + block_id = optimizer.block_id + slice = optimizer.slice + endpoint = optimizer.endpoint + + index = block_id if is_slice else idx + slices[index] = slice + slice_varnames[index] = "{}.slice.{}".format(slice.name, idx) + remote_varnames[index] = slice.name + endpoints[index] = endpoint + + slice_shapes = [] + for slice in slices: + tmp = [str(dim) for dim in slice.shape] + slice_shapes.append(",".join(tmp)) + + block.append_op(type='recv_save', + attrs={ + "trainer_id": 0, + "shape": origin.shape, + "slice_shapes": slice_shapes, + "slice_varnames": slice_varnames, + "remote_varnames": remote_varnames, + "endpoints": endpoints, + "file_path": os.path.join(dirname, origin.name) + }) + + executor.run(prog) + + def __save_distributed_lookup_tables(executor, dirname, + distributed_lookup_table, endpoints): + """ + because the distributed lookup table may too huge to merge and save at one place, + it will be saved at parameter server independent respectively. + + the save directory is dirname/"__lookup_table__". + + """ + prog = Program() + block = prog.global_block() + + # if there is lookup table, the trainer 0 will notify all pserver to save. + lookup_table_filename = os.path.join(dirname, "__lookup_table__") + attrs = {} + attrs['epmap'] = endpoints + attrs['dir'] = lookup_table_filename + attrs['lookup_table'] = distributed_lookup_table + block.append_op(type='checkpoint_notify', + inputs={}, + outputs={}, + attrs=attrs) + executor.run(prog) + + def __exclude_vars(exclude_var_names=[]): + + def is_valid(var): + if var.name in exclude_var_names: + return False + if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \ + var.desc.type() == core.VarDesc.VarType.FETCH_LIST or \ + var.desc.type() == core.VarDesc.VarType.READER: + return False + return var.persistable + + return is_valid + + if not isinstance(main_program, Program): + raise TypeError("'main_program' should be an instance of Program.") + + if not main_program._is_distributed: + raise ValueError( + "'_save_distributed_persistables' just be designed for distributed training." + ) + + remote_params_map = main_program._parameters_on_pservers.get_distributed_vars_by_vtypes( + ["Optimizer", "RemotePrefetch"], groupby=True) + + exclude_var_names = [] + if remote_params_map: + exclude_var_names.extend(remote_params_map.keys()) + + if main_program._distributed_lookup_table: + if isinstance(main_program._distributed_lookup_table, list): + exclude_var_names.extend(main_program._distributed_lookup_table) + else: + exclude_var_names.append(main_program._distributed_lookup_table) + + local_vars = list( + filter(__exclude_vars(exclude_var_names), main_program.list_vars())) + save_vars(executor, + main_program=main_program, + dirname=dirname, + vars=local_vars) + + if main_program._is_chief: + if remote_params_map: + __save_remote_params(executor, dirname, remote_params_map) + if main_program._distributed_lookup_table: + __save_distributed_lookup_tables( + executor, dirname, main_program._distributed_lookup_table, + main_program._endpoints) + + +@dygraph_not_support +def save_persistables(executor, dirname, main_program=None, filename=None): + """ + Save all persistable variables from :code:`main_program` to + the folder :code:`dirname` or file :code:`filename`. You can refer to + :ref:`api_guide_model_save_reader_en` for more details. And then + saves these persistables variables to the folder :code:`dirname` or file + :code:`filename`. + + The :code:`dirname` is used to specify the folder where persistable variables + are going to be saved. If you would like to save variables in separate + files, set :code:`filename` None; if you would like to save all variables in a + single file, use :code:`filename` to specify the file name. + + Args: + executor(Executor): The executor to run for saving persistable variables. + You can refer to :ref:`api_guide_executor_en` for + more details. + + dirname(str, optional): The saving directory path. + When you need to save the parameter to the memory, set it to None. + main_program(Program, optional): The program whose persistbale variables will + be saved. You can refer to + :ref:`api_guide_Program_en` for more details. + If it is None, the default main program will + be used. + Default: None. + filename(str, optional): The file to save all variables. If you prefer to + save variables in different files, set it to None. + Default: None. + + Returns: + str: When saving parameters to a file, returns None. + When saving parameters to memory, returns a binary string containing parameters. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + dir_path = "./my_paddle_model" + file_name = "persistables" + image = fluid.data(name='img', shape=[None, 28, 28], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + feeder = fluid.DataFeeder(feed_list=[image, label], place=fluid.CPUPlace()) + + predict = fluid.layers.fc(input=image, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=predict, label=label) + avg_loss = paddle.mean(loss) + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + fluid.io.save_persistables(executor=exe, dirname=dir_path, filename=file_name) + # The persistables variables weights and bias in the fc layer of the network + # are going to be saved in the same file named "persistables" in the path + # "./my_paddle_model" + """ + if main_program and main_program._is_distributed: + return _save_distributed_persistables(executor, + dirname=dirname, + main_program=main_program) + else: + return save_vars(executor, + dirname=dirname, + main_program=main_program, + vars=None, + predicate=is_persistable, + filename=filename) + + +def load_vars(executor, + dirname, + main_program=None, + vars=None, + predicate=None, + filename=None): + """ + :api_attr: Static Graph + + This API loads variables from files by executor. + + There are two ways to specify the variables to be loaded: the first way, set + variables in a list and assign it to the `vars`; the second way, use the + `predicate` function to select variables that make `predicate(variable) == True`. + The first way has a higher priority. + + The `dirname` is used to specify the folder where to load variables. + If variables were saved in separate files in the folder `dirname`, + set `filename` None. If all variables were saved in a single file, + use `filename` to specify it. + + Args: + executor(Executor): The executor to run for loading variables. + dirname(str): The folder where to load the variables. + main_program(Program, optional): The program whose variables will be loaded. + If it is None, the default main program will + be used automatically. + Default: None + vars(list[Variable], optional): The list that contains all variables to be loaded. + Default: None + predicate(function, optional): The function selects variables that make + `predicate(variable) == True`. + Default: None + filename(str, optional): The file which saved all required variables. If variables + were saved in separate files, set it to be None. + Default: None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + main_prog = fluid.Program() + startup_prog = fluid.Program() + with fluid.program_guard(main_prog, startup_prog): + data = fluid.layers.data(name="img", shape=[64, 784], append_batch_size=False) + w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w') + b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b') + hidden_w = fluid.layers.matmul(x=data, y=w) + hidden_b = fluid.layers.elementwise_add(hidden_w, b) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(startup_prog) + + # The first usage: using `vars` to specify the variables. + path = "./my_paddle_vars" + var_list = [w, b] + fluid.io.save_vars(executor=exe, dirname=path, vars=var_list, + filename="vars_file") + fluid.io.load_vars(executor=exe, dirname=path, vars=var_list, + filename="vars_file") + # w and b will be loaded, and they are supposed to + # be saved in the same file named 'var_file' in the path "./my_paddle_vars". + + # The second usage: using the `predicate` function to select variables + param_path = "./my_paddle_model" + def name_has_fc(var): + res = "fc" in var.name + return res + fluid.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog, + vars=None, predicate=name_has_fc) + fluid.io.load_vars(executor=exe, dirname=param_path, main_program=main_prog, + vars=None, predicate=name_has_fc) + # Load All variables in the `main_program` whose name includes "fc". + # And all the variables are supposed to be saved in separate files. + + """ + vars_from_memory = False + if dirname is not None: + dirname = os.path.normpath(dirname) + else: + vars_from_memory = True + + if vars is None: + if main_program is None: + main_program = default_main_program() + if not isinstance(main_program, Program): + raise TypeError( + "The type of input main_program is invalid, expected type is fluid.Program, but received %s" + % type(main_program)) + + load_vars(executor, + dirname=dirname, + main_program=main_program, + vars=list(filter(predicate, main_program.list_vars())), + filename=filename) + else: + load_prog = Program() + load_block = load_prog.global_block() + + if main_program is None: + main_program = default_main_program() + + if not isinstance(main_program, Program): + raise TypeError( + "The type of input main_program is invalid, expected type is fluid.Program, but received %s" + % type(main_program)) + + # save origin param shape + orig_para_shape = {} + load_var_map = {} + + check_vars = [] + sparse_vars = [] + + for each_var in vars: + assert isinstance(each_var, Variable) + + if each_var.type == core.VarDesc.VarType.RAW: + continue + + if isinstance(each_var, Parameter): + orig_para_shape[each_var.name] = tuple( + each_var.desc.get_shape()) + + if each_var.type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_vars.append(each_var) + continue + + new_var = _clone_var_in_block_(load_block, each_var) + check_vars.append(each_var) + + if filename is None: + if dirname is None: + raise ValueError( + "The directory path and params cannot be None at the same time." + ) + load_block.append_op( + type='load', + inputs={}, + outputs={'Out': [new_var]}, + attrs={'file_path': os.path.join(dirname, new_var.name)}) + else: + load_var_map[new_var.name] = new_var + + for each_var in sparse_vars: + assert isinstance(each_var, Variable) + + if filename is not None: + raise ValueError( + "SelectedRows can not be load with load_combine") + + new_var = _clone_var_in_block_(load_block, each_var) + + var_path = os.path.join(dirname, new_var.name) + if not os.path.exists(var_path): + raise ValueError( + "SelectedRows var {} can not find at {}".format( + new_var.name, var_path)) + + if os.path.isfile(var_path): + load_block.append_op( + type='load', + inputs={}, + outputs={'Out': [new_var]}, + attrs={'file_path': os.path.join(dirname, new_var.name)}) + else: + blocks = [] + block_paths = os.listdir(var_path) + + for block in block_paths: + if block.startswith(new_var.name): + blocks.append(block) + + slices = [] + for block in blocks: + slice = load_block.create_var(name=block, + type=new_var.type, + shape=new_var.shape, + dtype=new_var.dtype, + persistable=False) + slices.append(slice) + + file_path = os.path.join(var_path, block, "Param") + load_block.append_op(type='load', + inputs={}, + outputs={'Out': [slice]}, + attrs={'file_path': file_path}) + + load_block.append_op(type='lookup_sparse_table_merge', + inputs={'X': slices}, + outputs={'Out': new_var}, + attrs={}) + + if filename is not None: + load_var_list = [] + for name in sorted(load_var_map.keys()): + load_var_list.append(load_var_map[name]) + + if vars_from_memory is False: + filename = os.path.join(dirname, filename) + + load_block.append_op(type='load_combine', + inputs={}, + outputs={"Out": load_var_list}, + attrs={ + 'file_path': filename, + 'model_from_memory': vars_from_memory + }) + executor.run(load_prog) + + # check var shape + for each_var in check_vars: + if not isinstance(each_var, Parameter): + continue + var_temp = paddle.fluid.global_scope().find_var(each_var.name) + assert var_temp != None, "can't not find var: " + each_var.name + new_shape = (np.array(var_temp.get_tensor())).shape + assert each_var.name in orig_para_shape, each_var.name + "MUST in var list" + orig_shape = orig_para_shape.get(each_var.name) + if new_shape != orig_shape: + raise RuntimeError( + "Variable's shape does not match, the Program requires a parameter with the shape of ({}), " + "while the loaded parameter (namely [ {} ]) has a shape of ({})." + .format(orig_shape, each_var.name, new_shape)) + + +@dygraph_not_support +def load_params(executor, dirname, main_program=None, filename=None): + """ + :api_attr: Static Graph + + This API filters out all parameters from the give ``main_program`` + and then tries to load these parameters from the directory ``dirname`` or + the file ``filename``. + + Use the ``dirname`` to specify the directory where parameters were saved. If + parameters were saved in separate files under the directory `dirname`, set + ``filename`` as None; if all parameters were saved in a single file, use + ``filename`` to specify the file name. + + **Note**: + Some variables are not Parameter while they are necessary for + training, such as learning rate, global step, etc. So you cannot save and + continue your training just by using :ref:`api_fluid_io_save_params` and + :ref:`api_fluid_io_load_params`. Please use :ref:`api_fluid_io_save_persistables` + and :ref:`api_fluid_io_load_persistables` instead. + + If you want to load the pre-trained model structure and parameters + for the inference, please use the :ref:`api_fluid_io_load_inference_model` API. You can + refer to :ref:`api_guide_model_save_reader_en` for more details. + + Args: + executor(Executor): The executor used for loading parameters. + See :ref:`api_guide_executor_en` for more details about it. + dirname(str): The directory path. + main_program(Program, optional): The program whose parameters will be + loaded. If it is None, the ``default_main_program`` + will be used automatically. See :ref:`api_guide_Program_en` + for more about ``Program``. + Default: None. + filename(str, optional): The file which saved all parameters. If parameters + were saved in separated files, set it to None. + Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + param_path = "./my_paddle_model" + prog = fluid.default_main_program() + fluid.io.load_params(executor=exe, dirname=param_path, + main_program=None) + """ + load_vars(executor, + dirname=dirname, + main_program=main_program, + predicate=is_parameter, + filename=filename) + + +@dygraph_not_support +def load_persistables(executor, dirname, main_program=None, filename=None): + """ + :api_attr: Static Graph + + This API filters out all variables with ``persistable==True`` from the + given ``main_program`` and then tries to load these variables from the + directory ``dirname`` or the file ``filename``. + + Use the ``dirname`` to specify the directory where persistable variables + (refer to :ref:`api_guide_model_save_reader_en`) were saved. If variables + were saved in separate files, set ``filename`` as None; if all variables + were saved in a single file, use ``filename`` to specify the file name. + + Args: + executor(Executor): The executor used for loading persistable variables. + See :ref:`api_guide_executor_en` for more details about it. + dirname(str): The directory path. + main_program(Program, optional): The program whose persistable variables will + be loaded. If it is None, the ``default_main_program`` + will be used automatically. See :ref:`api_guide_Program_en` + for more about ``Program``. + Default: None. + filename(str, optional): The file which saved all persistable variables. If variables + were saved in separated files, set it to None. + Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + param_path = "./my_paddle_model" + prog = fluid.default_main_program() + fluid.io.load_persistables(executor=exe, dirname=param_path, + main_program=None) + """ + + if main_program and main_program._is_distributed: + _load_distributed_persistables(executor, + dirname=dirname, + main_program=main_program) + else: + load_vars(executor, + dirname=dirname, + main_program=main_program, + predicate=is_persistable, + filename=filename) + + +def _load_distributed_persistables(executor, dirname, main_program=None): + """ + customized load_persistables for distributed training. + it should be used on parameter server, + + Args: + executor(Executor): The executor to run for saving parameters. + dirname(str): The load directory path. + main_program(Program): The program whose parameters will be + loaded. the main_program must be the pserver_program + get after transpiler. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + param_path = "./my_paddle_model" + t = distribute_transpiler.DistributeTranspiler() + t.transpile(...) + pserver_prog = t.get_pserver_program(...) + _load_distributed_persistables(executor=exe, dirname=param_path, main_program=pserver_prog) + """ + + def __is_distributed_part_var(varname): + trainer_idx = varname.find(".trainer_") + block_idx = varname.find(".block") + return trainer_idx or block_idx + + def __load_persistable_vars(executor, dirname, need_load_vars): + load_prog = Program() + load_block = load_prog.global_block() + need_delete_vars = [] + + for param in need_load_vars: + origin_var = param.origin + slice_var = param.slice + is_slice = param.is_slice + offset = param.offset + + if is_slice: + slice = load_block.create_var(name=slice_var.name, + type=slice_var.type, + shape=slice_var.shape, + dtype=slice_var.dtype, + persistable=True) + + load_block.append_op(type='load', + inputs={}, + outputs={'Out': [slice]}, + attrs={ + 'file_path': + os.path.join(dirname, origin_var.name), + 'seek': + offset, + 'shape': + slice.shape + }) + else: + origin = load_block.create_var(name="{}".format( + origin_var.name), + type=origin_var.type, + shape=origin_var.shape, + dtype=origin_var.dtype, + persistable=True) + load_block.append_op( + type='load', + inputs={}, + outputs={'Out': [origin]}, + attrs={'file_path': os.path.join(dirname, origin_var.name)}) + + load_block.append_op( + type='delete_var', + inputs={'X': need_delete_vars}, + ) + + executor.run(load_prog) + + if not isinstance(main_program, Program): + raise TypeError("'main_program' should be an instance of Program.") + + if not main_program._is_distributed: + raise ValueError( + "'_load_distributed_persistables' just be designed for distributed training." + ) + + if not main_program._ps_endpoint: + raise ValueError( + "'_load_distributed_persistables' need current_endpoint set in DistributeTranspiler.transpile" + ) + + need_load_vars = main_program._parameters_on_pservers.get_distributed_vars_by_ep( + main_program._ps_endpoint) + __load_persistable_vars(executor, dirname, need_load_vars) + + +def prepend_feed_ops(inference_program, + feed_target_names, + feed_holder_name='feed'): + if len(feed_target_names) == 0: + return + + global_block = inference_program.global_block() + feed_var = global_block.create_var(name=feed_holder_name, + type=core.VarDesc.VarType.FEED_MINIBATCH, + persistable=True) + + for i, name in enumerate(feed_target_names): + if not global_block.has_var(name): + raise ValueError( + "The feeded_var_names[{i}]: '{name}' doesn't exist in pruned inference program. " + "Please check whether '{name}' is a valid feed_var name, or remove it from feeded_var_names " + "if '{name}' is not involved in the target_vars calculation.". + format(i=i, name=name)) + out = global_block.var(name) + global_block._prepend_op(type='feed', + inputs={'X': [feed_var]}, + outputs={'Out': [out]}, + attrs={'col': i}) + + +def append_fetch_ops(inference_program, + fetch_target_names, + fetch_holder_name='fetch'): + global_block = inference_program.global_block() + fetch_var = global_block.create_var(name=fetch_holder_name, + type=core.VarDesc.VarType.FETCH_LIST, + persistable=True) + + for i, name in enumerate(fetch_target_names): + global_block.append_op(type='fetch', + inputs={'X': [name]}, + outputs={'Out': [fetch_var]}, + attrs={'col': i}) + + +@static_only +@deprecated(since="2.0.0", update_to="paddle.static.save_inference_model") +def save_inference_model(dirname, + feeded_var_names, + target_vars, + executor, + main_program=None, + model_filename=None, + params_filename=None, + export_for_deployment=True, + program_only=False, + clip_extra=True): + """ + Prune the given `main_program` to build a new program especially for inference, + and then save it and all related parameters to given `dirname` . + If you just want to save parameters of your trained model, please use the + :ref:`api_fluid_io_save_params` . You can refer to :ref:`api_guide_model_save_reader_en` + for more details. + + Note: + The :code:`dirname` is used to specify the folder where inference model + structure and parameters are going to be saved. If you would like to save params of + Program in separate files, set `params_filename` None; if you would like to save all + params of Program in a single file, use `params_filename` to specify the file name. + + Args: + dirname(str): The directory path to save the inference model. + feeded_var_names(list[str]): list of string. Names of variables that need to be fed + data during inference. + target_vars(list[Variable]): list of Variable. Variables from which we can get + inference results. + executor(Executor): The executor that saves the inference model. You can refer + to :ref:`api_guide_executor_en` for more details. + main_program(Program, optional): The original program, which will be pruned to + build the inference model. If is set None, + the global default :code:`_main_program_` will be used. + Default: None. + model_filename(str, optional): The name of file to save the inference program + itself. If is set None, a default filename + :code:`__model__` will be used. + params_filename(str, optional): The name of file to save all related parameters. + If it is set None, parameters will be saved + in separate files . + export_for_deployment(bool, optional): If True, programs are modified to only support + direct inference deployment. Otherwise, + more information will be stored for flexible + optimization and re-training. Currently, only + True is supported. + Default: True. + program_only(bool, optional): If True, It will save inference program only, and do not + save params of Program. + Default: False. + + Returns: + list, The fetch variables' name list. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + path = "./infer_model" + + # User defined network, here a softmax regession example + image = fluid.data(name='img', shape=[None, 28, 28], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + feeder = fluid.DataFeeder(feed_list=[image, label], place=fluid.CPUPlace()) + predict = fluid.layers.fc(input=image, size=10, act='softmax') + + loss = fluid.layers.cross_entropy(input=predict, label=label) + avg_loss = paddle.mean(loss) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + # Feed data and train process + + # Save inference model. Note we don't save label and loss in this example + fluid.io.save_inference_model(dirname=path, + feeded_var_names=['img'], + target_vars=[predict], + executor=exe) + + # In this example, the save_inference_mode inference will prune the default + # main program according to the network's input node (img) and output node(predict). + # The pruned inference program is going to be saved in the "./infer_model/__model__" + # and parameters are going to be saved in separate files under folder + # "./infer_model". + + """ + if isinstance(feeded_var_names, six.string_types): + feeded_var_names = [feeded_var_names] + elif export_for_deployment: + if len(feeded_var_names) > 0: + # TODO(paddle-dev): polish these code blocks + if not (bool(feeded_var_names) and all( + isinstance(name, six.string_types) + for name in feeded_var_names)): + raise ValueError("'feed_var_names' should be a list of str.") + + if isinstance(target_vars, Variable): + target_vars = [target_vars] + elif export_for_deployment: + if not (bool(target_vars) + and all(isinstance(var, Variable) for var in target_vars)): + raise ValueError("'target_vars' should be a list of Variable.") + + main_program = _get_valid_program(main_program) + + # remind user to set auc_states to zeros if the program contains auc op + all_ops = main_program.global_block().ops + for op in all_ops: + # clear device of Op + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + op._set_attr(device_attr_name, "") + if op.type == 'auc': + warnings.warn( + "please ensure that you have set the auc states to zeros before saving inference model" + ) + break + + with program_guard(main_program): + uniq_target_vars = [] + for i, var in enumerate(target_vars): + uniq_target_vars.append(var) + target_vars = uniq_target_vars + target_var_name_list = [var.name for var in target_vars] + + # when a pserver and a trainer running on the same machine, mkdir may conflict + save_dirname = dirname + try: + save_dirname = os.path.normpath(dirname) + os.makedirs(save_dirname) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + if model_filename is not None: + model_basename = os.path.basename(model_filename) + else: + model_basename = "__model__" + model_basename = os.path.join(save_dirname, model_basename) + + # When export_for_deployment is true, we modify the program online so that + # it can only be loaded for inference directly. If it's false, the whole + # original program and related meta are saved so that future usage can be + # more flexible. + + origin_program = main_program.clone() + + if export_for_deployment: + main_program = main_program.clone() + global_block = main_program.global_block() + need_to_remove_op_index = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "feed" or op.type == "fetch": + need_to_remove_op_index.append(i) + + for index in need_to_remove_op_index[::-1]: + global_block._remove_op(index) + + main_program.desc.flush() + + main_program = main_program._prune_with_input( + feeded_var_names=feeded_var_names, targets=target_vars) + main_program = main_program._inference_optimize(prune_read_op=True) + fetch_var_names = [v.name for v in target_vars] + + for target_v in target_vars: + if not main_program.global_block().has_var(target_v.name): + main_program.global_block().create_var( + name=target_v.name, + shape=target_v.shape, + dtype=target_v.dtype, + persistable=target_v.persistable) + + prepend_feed_ops(main_program, feeded_var_names) + append_fetch_ops(main_program, fetch_var_names) + + main_program.desc._set_version() + paddle.fluid.core.save_op_version_info(main_program.desc) + with open(model_basename, "wb") as f: + f.write( + main_program._remove_training_info( + clip_extra=clip_extra).desc.serialize_to_string()) + else: + # TODO(panyx0718): Save more information so that it can also be used + # for training and more flexible post-processing. + with open(model_basename + ".main_program", "wb") as f: + f.write( + main_program._remove_training_info( + clip_extra=clip_extra).desc.serialize_to_string()) + + if program_only: + warnings.warn( + "save_inference_model specified the param `program_only` to True, It will not save params of Program." + ) + return target_var_name_list + + main_program._copy_dist_param_info_from(origin_program) + + if params_filename is not None: + params_filename = os.path.basename(params_filename) + + save_persistables(executor, save_dirname, main_program, params_filename) + return target_var_name_list + + +@static_only +@deprecated(since="2.0.0", update_to="paddle.static.load_inference_model") +def load_inference_model(dirname, + executor, + model_filename=None, + params_filename=None, + pserver_endpoints=None): + """ + Load the inference model from a given directory. By this API, you can get the model + structure(Inference Program) and model parameters. If you just want to load + parameters of the pre-trained model, please use the :ref:`api_fluid_io_load_params` API. + You can refer to :ref:`api_guide_model_save_reader_en` for more details. + + Args: + dirname(str): One of the following: + - The given directory path. + - Set to None when reading the model from memory. + executor(Executor): The executor to run for loading inference model. + See :ref:`api_guide_executor_en` for more details about it. + model_filename(str, optional): One of the following: + - The name of file to load the inference program. + - If it is None, the default filename ``__model__`` will be used. + - When ``dirname`` is ``None``, it must be set to a string containing model. + Default: ``None``. + params_filename(str, optional): It is only used for the case that all + parameters were saved in a single binary file. One of the following: + - The name of file to load all parameters. + - When ``dirname`` is ``None``, it must be set to a string containing all the parameters. + - If parameters were saved in separate files, set it as ``None``. + Default: ``None``. + + pserver_endpoints(list, optional): It is only needed by the distributed inference. + If using a distributed look up table during the training, + this table is also needed by the inference process. Its value is + a list of pserver endpoints. + + Returns: + list: The return of this API is a list with three elements: + (program, feed_target_names, fetch_targets). The `program` is a + ``Program`` (refer to :ref:`api_guide_Program_en`), which is used for inference. + The `feed_target_names` is a list of ``str``, which contains names of variables + that need to feed data in the inference program. The `fetch_targets` is a list of + ``Variable`` (refer to :ref:`api_guide_Program_en`). It contains variables from which + we can get inference results. + + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + paddle.enable_static() + # Build the model + main_prog = fluid.Program() + startup_prog = fluid.Program() + with fluid.program_guard(main_prog, startup_prog): + data = fluid.layers.data(name="img", shape=[64, 784], append_batch_size=False) + w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32') + b = fluid.layers.create_parameter(shape=[200], dtype='float32') + hidden_w = fluid.layers.matmul(x=data, y=w) + hidden_b = fluid.layers.elementwise_add(hidden_w, b) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(startup_prog) + + # Save the inference model + path = "./infer_model" + fluid.io.save_inference_model(dirname=path, feeded_var_names=['img'], + target_vars=[hidden_b], executor=exe, main_program=main_prog) + + # Demo one. Not need to set the distributed look up table, because the + # training doesn't use a distributed look up table. + [inference_program, feed_target_names, fetch_targets] = ( + fluid.io.load_inference_model(dirname=path, executor=exe)) + tensor_img = np.array(np.random.random((1, 64, 784)), dtype=np.float32) + results = exe.run(inference_program, + feed={feed_target_names[0]: tensor_img}, + fetch_list=fetch_targets) + + # Demo two. If the training uses a distributed look up table, the pserver + # endpoints list should be supported when loading the inference model. + # The below is just an example. + endpoints = ["127.0.0.1:2023","127.0.0.1:2024"] + [dist_inference_program, dist_feed_target_names, dist_fetch_targets] = ( + fluid.io.load_inference_model(dirname=path, + executor=exe, + pserver_endpoints=endpoints)) + + # In this example, the inference program was saved in the file + # "./infer_model/__model__" and parameters were saved in + # separate files under the directory "./infer_model". + # By the inference program, feed_target_names and + # fetch_targets, we can use an executor to run the inference + # program for getting the inference result. + """ + load_from_memory = False + if dirname is not None: + load_dirname = os.path.normpath(dirname) + if not os.path.isdir(load_dirname): + raise ValueError("There is no directory named '%s'" % dirname) + + if model_filename is None: + model_filename = '__model__' + + model_filename = os.path.join(load_dirname, + os.path.basename(model_filename)) + + if params_filename is not None: + params_filename = os.path.basename(params_filename) + + with open(model_filename, "rb") as f: + program_desc_str = f.read() + else: + load_from_memory = True + if params_filename is None: + raise ValueError( + "The path of params cannot be None when the directory path is None." + ) + load_dirname = dirname + program_desc_str = model_filename + params_filename = params_filename + + program = Program.parse_from_string(program_desc_str) + if not core._is_program_version_supported(program._version()): + raise ValueError("Unsupported program version: %d\n" % + program._version()) + # Binary data also need versioning. + load_persistables(executor, load_dirname, program, params_filename) + + if pserver_endpoints: + program = _endpoints_replacement(program, pserver_endpoints) + + feed_target_names = program.desc.get_feed_target_names() + fetch_target_names = program.desc.get_fetch_target_names() + fetch_targets = [ + program.global_block().var(name) for name in fetch_target_names + ] + + return [program, feed_target_names, fetch_targets] + + +def _endpoints_replacement(program, endpoints): + ENDPOINT_MAP = "epmap" + for op in program.global_block().ops: + if op.has_attr(ENDPOINT_MAP): + op.set_attr(ENDPOINT_MAP, endpoints) + program._sync_with_cpp() + return program + + +def get_parameter_value(para, executor): + """ + Get the LoDTensor value of the given parameter. + + Args: + para(Parameter): The parameter to get value from. + executor(Executor): The executor to run for retrieving the value. + + Returns: + numpy.array: The given parameter's values. + + Raises: + AssertionError: If the `para` is not an instance of Parameter. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + param = fluid.default_main_program().global_block().var('fc.w') + p = fluid.io.get_parameter_value(param, exe) + + """ + assert is_parameter(para), "The input variable is not parameter." + + get_program = Program() + block = get_program.global_block() + new_var = _clone_var_in_block_(block, para) + return executor.run(get_program, feed={}, fetch_list=[new_var])[0] + + +def get_parameter_value_by_name(name, executor, program=None): + """ + Get the LoDTensor value of a certain parameter by its name. + + Args: + name(str): The parameter's name. + executor(Executor): The executor to run for retrieving the value. + program(Program | None): The program where to find the parameter. + If it's set to be None, the function will + try to find the parameter in the default + main program. + + Returns: + numpy.array: The parameter's values. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + exe = fluid.Executor(fluid.CPUPlace()) + p = fluid.io.get_parameter_value('fc.w', exe) + """ + if program is None: + program = default_main_program() + var = program.global_block().var(name) + return get_parameter_value(var, executor) + + +def _save_persistable_nodes(executor, dirname, graph): + """ + Save persistable nodes to the given directory by the executor. + + Args: + executor(Executor): The executor to run for saving node values. + dirname(str): The directory path. + graph(IrGraph): All the required persistable nodes in the graph will be saved. + """ + persistable_node_names = set() + persistable_nodes = [] + all_persistable_nodes = graph.all_persistable_nodes() + for node in all_persistable_nodes: + name = cpt.to_text(node.name()) + if name not in persistable_node_names: + persistable_node_names.add(name) + persistable_nodes.append(node) + program = Program() + var_list = [] + for node in persistable_nodes: + var_desc = node.var() + if var_desc.type() == core.VarDesc.VarType.RAW or \ + var_desc.type() == core.VarDesc.VarType.READER: + continue + var = program.global_block().create_var( + name=var_desc.name(), + shape=var_desc.shape(), + dtype=var_desc.dtype(), + type=var_desc.type(), + lod_level=var_desc.lod_level(), + persistable=var_desc.persistable()) + var_list.append(var) + save_vars(executor=executor, dirname=dirname, vars=var_list) + + +def _load_persistable_nodes(executor, dirname, graph): + """ + Load persistable node values from the given directory by the executor. + + Args: + executor(Executor): The executor to run for loading node values. + dirname(str): The directory path. + graph(IrGraph): All the required persistable nodes in the graph will be loaded. + """ + persistable_node_names = set() + persistable_nodes = [] + all_persistable_nodes = graph.all_persistable_nodes() + for node in all_persistable_nodes: + name = cpt.to_text(node.name()) + if name not in persistable_node_names: + persistable_node_names.add(name) + persistable_nodes.append(node) + program = Program() + var_list = [] + + def _exist(var): + return os.path.exists(os.path.join(dirname, var.name)) + + for node in persistable_nodes: + var_desc = node.var() + if var_desc.type() == core.VarDesc.VarType.RAW or \ + var_desc.type() == core.VarDesc.VarType.READER: + continue + var = program.global_block().create_var( + name=var_desc.name(), + shape=var_desc.shape(), + dtype=var_desc.dtype(), + type=var_desc.type(), + lod_level=var_desc.lod_level(), + persistable=var_desc.persistable()) + if _exist(var): + var_list.append(var) + else: + _logger.warn("Cannot find the var %s!!!" % (node.name())) + load_vars(executor=executor, dirname=dirname, vars=var_list) + + +def _unpack_saved_dict(saved_obj, protocol): + temp_saved_obj = {} + unpack_infor = {} + # When pickle protocol=2 or protocol=3 the serialized object cannot be larger than 4G. + if 1 < protocol < 4: + if isinstance(saved_obj, dict): + for key, value in saved_obj.items(): + if isinstance(value, np.ndarray): + MAX_NUMBER_OF_ELEMENT = int( + (2**30 - 1) / value.dtype.itemsize) + num_element = np.prod(value.shape) + if num_element > MAX_NUMBER_OF_ELEMENT: + unpack_infor[key] = {} + unpack_infor[key]["OriginShape"] = value.shape + unpack_infor[key]["slices"] = [] + value = value.flatten() + for i in range( + int( + math.ceil(num_element * 1.0 / + MAX_NUMBER_OF_ELEMENT))): + part_name = key + "@@." + str(i) + unpack_infor[key]["slices"].append(part_name) + temp_saved_obj[part_name] = value[ + i * + MAX_NUMBER_OF_ELEMENT:MAX_NUMBER_OF_ELEMENT * + (i + 1)] + + if unpack_infor: + for key, value in unpack_infor.items(): + if key in saved_obj: + saved_obj.pop(key) + for part in value['slices']: + saved_obj[part] = temp_saved_obj[part] + saved_obj['UnpackBigParamInfor@@'] = unpack_infor + return saved_obj + + +def _pack_loaded_dict(load_obj): + if isinstance(load_obj, dict): + unpack_info = 'UnpackBigParamInfor@@' + if unpack_info in load_obj: + removes = [] + for key, value in load_obj[unpack_info].items(): + slices = [load_obj[part] for part in value["slices"]] + load_obj[key] = np.concatenate(slices).reshape( + value["OriginShape"]) + removes += value["slices"] + for key in removes: + load_obj.pop(key) + load_obj.pop(unpack_info) + + return load_obj + + +@static_only +def _legacy_save(param_dict, model_path, protocol=2): + + def get_tensor(var): + if isinstance(var, (core.VarBase, core.eager.Tensor)): + return var.numpy() + elif isinstance(var, core.LoDTensor): + return np.array(var) + return var + + param_dict = {name: get_tensor(param_dict[name]) for name in param_dict} + + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if _is_file_path( + model_path + ) and sys.platform == 'darwin' and sys.version_info.major == 3: + pickle_bytes = pickle.dumps(param_dict, protocol=protocol) + with open(model_path, 'wb') as f: + max_bytes = 2**30 + for i in range(0, len(pickle_bytes), max_bytes): + f.write(pickle_bytes[i:i + max_bytes]) + else: + with _open_file_buffer(model_path, 'wb') as f: + pickle.dump(param_dict, f, protocol=protocol) + + +@static_only +def save(program, model_path, protocol=4, **configs): + """ + + This function save parameters, optimizer information and network description to model_path. + + The parameters contains all the trainable Tensor, will save to a file with suffix ".pdparams". + The optimizer information contains all the Tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. All the information will save to a file with suffix ".pdopt". (If the optimizer have no Tensor need to save (like SGD), the fill will not generated). + The network description is the description of the program. It's only used for deployment. The description will save to a file with a suffix ".pdmodel". + + Args: + program(Program) : The program to saved. + model_path(str): the file prefix to save the program. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised + protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5. + Default: 4 + configs(dict, optional) : optional keyword arguments. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + static.save(prog, "./temp") + """ + + base_name = os.path.basename(model_path) + assert base_name != "", \ + "The input model_path MUST be format of dirname/filename [dirname\\filename in Windows system], but received model_path is empty string." + if 'pickle_protocol' in configs: + protocol = configs['pickle_protocol'] + warnings.warn( + "'pickle_protocol' is a deprecated argument. Please use 'protocol' instead." + ) + + if not isinstance(protocol, int): + raise ValueError("The 'protocol' MUST be `int`, but received {}".format( + type(protocol))) + + if protocol < 2 or protocol > 4: + raise ValueError( + "Expected 1<'protocol'<5, but received protocol={}".format( + protocol)) + + dir_name = os.path.dirname(model_path) + if dir_name and not os.path.exists(dir_name): + os.makedirs(dir_name) + + def get_tensor(var): + t = global_scope().find_var(var.name).get_tensor() + return np.array(t) + + parameter_list = list(filter(is_parameter, program.list_vars())) + param_dict = {p.name: get_tensor(p) for p in parameter_list} + + param_dict = _unpack_saved_dict(param_dict, protocol) + + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if sys.platform == 'darwin' and sys.version_info.major == 3: + pickle_bytes = pickle.dumps(param_dict, protocol=protocol) + with open(model_path + ".pdparams", 'wb') as f: + max_bytes = 2**30 + for i in range(0, len(pickle_bytes), max_bytes): + f.write(pickle_bytes[i:i + max_bytes]) + else: + with open(model_path + ".pdparams", 'wb') as f: + pickle.dump(param_dict, f, protocol=protocol) + + optimizer_var_list = list( + filter(is_belong_to_optimizer, program.list_vars())) + + opt_dict = {p.name: get_tensor(p) for p in optimizer_var_list} + with open(model_path + ".pdopt", 'wb') as f: + pickle.dump(opt_dict, f, protocol=protocol) + + main_program = program.clone() + program.desc.flush() + main_program.desc._set_version() + paddle.fluid.core.save_op_version_info(program.desc) + + with open(model_path + ".pdmodel", "wb") as f: + f.write(program.desc.serialize_to_string()) + + +def _pickle_loads_mac(path, f): + pickle_bytes = bytearray(0) + file_size = os.path.getsize(path) + max_bytes = 2**30 + for _ in range(0, file_size, max_bytes): + pickle_bytes += f.read(max_bytes) + load_result = pickle.loads(pickle_bytes, encoding='latin1') + return load_result + + +@static_only +def load(program, model_path, executor=None, var_list=None): + """ + :api_attr: Static Graph + + This function get parameters and optimizer information from program, and then get corresponding value from file. + An exception will throw if shape or dtype of the parameters is not match. + + This function can also load model file saved with [ save_params, save_persistables, save_vars ]. + var_list can not be None when load single model file + ( filename is not None When save_params, save_persistables or save_vars is called ). + + Args: + program(Program): The program will be loaded + model_path(str): The file prefix store the program + executor(Executor, optional): The executor used for initialize the parameter + When startup program is not run. + var_list(list|tuple, optional): The Tensor list/tuple to load single model file saved with + [ save_params, save_persistables, save_vars ]. + Default: None + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + static.save(prog, "./temp") + static.load(prog, "./temp") + """ + + assert executor is None or isinstance(executor, Executor) + + model_prefix = model_path + if model_prefix.endswith(".pdparams"): + model_prefix = model_prefix[:-9] + elif model_prefix.endswith(".pdopt"): + model_prefix = model_prefix[:-6] + elif model_prefix.endswith(".pdmodel"): + model_prefix = model_prefix[:-8] + + parameter_file_name = model_prefix + ".pdparams" + + if not os.path.exists(parameter_file_name): + # model file save by fluid.save not found, try to load model file saved with + # [save_vars, save_params, save_persistables] + _logger.debug( + "{} not found, try to load model file saved with [ save_params, save_persistables, save_vars ]" + .format(parameter_file_name)) + if executor is None: + raise ValueError( + "executor is required when loading model file saved with [ save_params, save_persistables, save_vars ]" + ) + + if var_list is not None: + var_list_names = [var.name for var in var_list] + else: + var_list_names = None + + if os.path.isdir(model_path): + binary_file_set = set() + for root, dirs, files in os.walk(model_path, topdown=False): + for f in files: + binary_file_set.add( + os.path.join(root, f).replace("\\", "/")) + program_var_list = list(program.list_vars()) + loaded_var_list = [] + for var in program_var_list: + var_path = os.path.join(model_path, var.name).replace("\\", "/") + load_condition = var_list_names is None or var.name in var_list_names + if var_path in binary_file_set and load_condition: + loaded_var_list.append(var) + binary_file_set.remove(var_path) + if len(binary_file_set) > 0: + unused_var_list = " ".join(list(binary_file_set)) + _logger.warning("variable file [ %s ] not used" % + (" ".join(list(binary_file_set)))) + try: + load_vars(executor=executor, + dirname=model_path, + vars=loaded_var_list) + except RuntimeError as e: + _logger.error(e) + raise e + except: + raise RuntimeError( + "Failed to load model file, please make sure model file is saved with the " + "following APIs: save_params, save_persistables, save_vars") + + return + elif os.path.isfile(model_path): + if var_list == None: + raise ValueError( + "var_list is required when loading model file saved with [ save_params, save_persistables, save_vars ]" + ) + program_var_list = program.list_vars() + program_var_name_set = set([var.name for var in program_var_list]) + + # check all the variable inlcuded in program + for var in var_list: + if var.name not in program_var_name_set: + raise LookupError( + "loaded var [{}] is not in program variable list") + + dir_name, file_name = os.path.split(model_path) + try: + load_vars(executor=executor, + dirname=dir_name, + vars=var_list, + filename=file_name) + except RuntimeError as e: + _logger.error(e) + raise e + except: + raise RuntimeError("Failed to load model file , please make sure model file is saved with the " \ + "the following APIs: [ save_params, save_persistables, save_vars ]. " \ + "When these API called, filename CANNOT be None") + + return + + def set_var(var, ndarray): + t = global_scope().find_var(var.name).get_tensor() + p = t._place() + if p.is_cpu_place(): + place = paddle.fluid.CPUPlace() + elif p.is_cuda_pinned_place(): + place = paddle.fluid.CUDAPinnedPlace() + elif p.is_xpu_place(): + p = paddle.fluid.core.Place() + p.set_place(t._place()) + place = paddle.fluid.XPUPlace(p.xpu_device_id()) + elif p.is_npu_place(): + p = paddle.fluid.core.Place() + p.set_place(t._place()) + place = paddle.fluid.NPUPlace(p.npu_device_id()) + elif p.is_mlu_place(): + p = paddle.fluid.core.Place() + p.set_place(t._place()) + place = paddle.fluid.MLUPlace(p.mlu_device_id()) + else: + p = paddle.fluid.core.Place() + p.set_place(t._place()) + place = paddle.fluid.CUDAPlace(p.gpu_device_id()) + + t.set(ndarray, place) + + parameter_list = list(filter(is_parameter, program.list_vars())) + + if executor: + paddle.fluid.core._create_loaded_parameter(parameter_list, + global_scope(), + executor._default_executor) + with open(parameter_file_name, 'rb') as f: + + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if sys.platform == 'darwin' and sys.version_info.major == 3: + load_dict = _pickle_loads_mac(parameter_file_name, f) + else: + load_dict = pickle.load(f, encoding='latin1') + load_dict = _pack_loaded_dict(load_dict) + for v in parameter_list: + assert v.name in load_dict, \ + "Can not find [{}] in model file [{}]".format( + v.name, parameter_file_name) + set_var(v, load_dict[v.name]) + + optimizer_var_list = list( + filter(is_belong_to_optimizer, program.list_vars())) + + if len(optimizer_var_list) > 0: + opt_file_name = model_prefix + ".pdopt" + assert os.path.exists(opt_file_name), \ + "Optimizer file [{}] not exits".format(opt_file_name) + + if executor: + paddle.fluid.core._create_loaded_parameter( + optimizer_var_list, global_scope(), executor._default_executor) + + with open(opt_file_name, 'rb') as f: + load_dict = pickle.load(f, encoding='latin1') + for v in optimizer_var_list: + assert v.name in load_dict, \ + "Can not find [{}] in model file [{}]".format( + v.name, opt_file_name) + set_var(v, load_dict[v.name]) + + +def load_program_state(model_path, var_list=None): + """ + + Load program state from local file + + Args: + model_path(str): The file prefix store the program + var_list(list|tuple, optional): The Tensor list/tuple to load saved with + [ save_params, save_persistables, save_vars ]. + Default: None. + The var_list is only used to get name, + will not be modified. + Returns: + state_dict(dict): the dict store Parameter and optimizer information + + Examples: + + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + static.save(prog, "./temp") + program_state = static.load_program_state("./temp") + """ + model_prefix = model_path + if model_prefix.endswith(".pdparams"): + model_prefix = model_prefix[:-9] + elif model_prefix.endswith(".pdopt"): + model_prefix = model_prefix[:-6] + elif model_prefix.endswith(".pdmodel"): + model_prefix = model_prefix[:-8] + + parameter_file_name = model_prefix + ".pdparams" + if not os.path.exists(parameter_file_name): + # model file saved with fluid.save is not found, try to load model file saved with + # [save_vars, save_params, save_persistables] + _logger.debug( + "{} not found, try to load model file saved with [ save_params, save_persistables, save_vars ]" + .format(parameter_file_name)) + + var_name_list = [] + if var_list is None and os.path.isfile(model_path): + raise ValueError( + "var_list can not be None when model_path is a file type") + + for root, dirs, files in os.walk(model_path, topdown=False): + for f in files: + file_path = os.path.join(root, f) + var_temp_name = os.path.relpath(file_path, model_path) + var_temp_name = var_temp_name.replace("\\", "/") + var_name_list.append(var_temp_name) + + with _load_program_scope(): + load_prog = Program() + load_block = load_prog.global_block() + + def clone_var_to_block(block, var): + if not isinstance(var, Variable): + raise TypeError("value in var_list must be variable") + return block.create_var( + name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level if var.desc.type() + == core.VarDesc.VarType.LOD_TENSOR else None, + persistable=True) + + def _load_vars_with_try_catch(exe, + dirname, + vars, + filename, + raise_error=True): + try: + load_vars(executor=exe, + dirname=dirname, + vars=vars, + filename=filename) + return True + except: + error_str = "Failed to load model/variables `%s`, please make sure " \ + "model/variables file is saved with the following APIs: " \ + "save_params, save_persistables, save_vars." + filenames = [var.name for var in vars + ] if filename is None else filename + if raise_error: + raise RuntimeError(error_str % filenames) + else: + warnings.warn(error_str % filenames, RuntimeWarning) + return False + + place = paddle.fluid.CPUPlace() + exe = paddle.fluid.Executor(place) + + loaded_var_list = [] + + if os.path.isfile(model_path): + # when model_path is file, var_list cannot be None + dir_name, file_name = os.path.split(model_path) + for var in var_list: + loaded_var_list.append(clone_var_to_block(load_block, var)) + _load_vars_with_try_catch(exe, dir_name, loaded_var_list, + file_name) + else: + # var_list can be None or not None + if var_list is not None: + for var in var_list: + loaded_var_list.append( + clone_var_to_block(load_block, var)) + _load_vars_with_try_catch(exe, model_path, loaded_var_list, + None) + else: + for var_name in var_name_list: + # NOTE(chenweihang): If identify which files the user wants + # to load from the disk, we load these variables one by one. + # If a file does not exist, we only warn the user that the + # file may be an irrelevant file, but does not throw an error + # to ensure that other legal variables can be loaded. + temp_var = load_block.create_var(name=var_name, + persistable=True) + if _load_vars_with_try_catch(exe, model_path, + [temp_var], None, False): + loaded_var_list.append(temp_var) + + res_dict = {} + for var in loaded_var_list: + res_dict[var.name] = np.asarray( + paddle.fluid.global_scope().find_var(var.name).get_tensor()) + + return res_dict + + assert os.path.exists(parameter_file_name), \ + "Parameter file [{}] not exits".format(parameter_file_name) + + with open(parameter_file_name, 'rb') as f: + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if sys.platform == 'darwin' and sys.version_info.major == 3: + para_dict = _pickle_loads_mac(parameter_file_name, f) + else: + para_dict = pickle.load(f, encoding='latin1') + para_dict = _pack_loaded_dict(para_dict) + + opt_file_name = model_prefix + ".pdopt" + if os.path.exists(opt_file_name): + with open(opt_file_name, 'rb') as f: + opti_dict = pickle.load(f, encoding='latin1') + + para_dict.update(opti_dict) + + return para_dict + + +@static_only +def set_program_state(program, state_dict): + """ + Set program parameter from state_dict + + An exception will throw if shape or dtype of the parameters is not match. + + NOTICE: This function MUST called after run start_up_program + + Args: + program(Program): The program to be set + state_dict(dict): the dict store Parameter and optimizer information + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + x = static.data(name="x", shape=[10, 10], dtype='float32') + y = static.nn.fc(x, 10) + z = static.nn.fc(y, 10) + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + prog = static.default_main_program() + + static.save(prog, "./temp") + program_state = static.load_program_state("./temp") + + static.set_program_state(prog, program_state) + """ + state_dict = _pack_loaded_dict(state_dict) + parameter_list = list(filter(is_persistable, program.list_vars())) + + used_para_list = {} + for para in parameter_list: + var_temp = paddle.fluid.global_scope().find_var(para.name) + assert var_temp != None, \ + "Variable [ {} ] Not found, Please make sure run startup program".format(para.name) + if para.name in state_dict: + # set value from state dict + orig_para_np = np.array(var_temp.get_tensor()) + new_para_np = state_dict[para.name] + assert orig_para_np.shape == new_para_np.shape, \ + "Parameter's shape does not match, the Program requires a parameter with the shape of ({}), " \ + "while the loaded parameter (namely [ {} ]) has a shape of ({})." \ + .format(orig_para_np.shape, para.name, new_para_np.shape) + assert orig_para_np.dtype == new_para_np.dtype, \ + "Parameter's data type does not match, the Program requires a parameter with a dtype of ({}), " \ + "while the loaded parameter (namely [ {} ]) has a dtype of ({})." \ + .format(orig_para_np.dtype, para.name, new_para_np.dtype) + + ten = var_temp.get_tensor() + ten_place = ten._place() + + #assert ten_place.is_gpu_place() or ten_place.is_cpu_place(), \ + # "Place not support, only support CPUPlace and GPUPlace, now is {}".format(str(ten_place)) + py_place = paddle.fluid.CPUPlace() + if ten_place.is_cuda_pinned_place(): + place = paddle.fluid.CUDAPinnedPlace() + elif ten_place.is_gpu_place(): + p = paddle.fluid.core.Place() + p.set_place(ten_place) + py_place = paddle.fluid.CUDAPlace(p.gpu_device_id()) + elif ten_place.is_xpu_place(): + p = paddle.fluid.core.Place() + p.set_place(ten_place) + py_place = paddle.fluid.XPUPlace(p.xpu_device_id()) + elif ten_place.is_npu_place(): + p = paddle.fluid.core.Place() + p.set_place(ten_place) + py_place = paddle.fluid.NPUPlace(p.npu_device_id()) + elif ten_place.is_mlu_place(): + p = paddle.fluid.core.Place() + p.set_place(ten_place) + py_place = paddle.fluid.MLUPlace(p.mlu_device_id()) + + ten.set(new_para_np, py_place) + + used_para_list[para.name] = 1 + + unused_para_list = [] + for k, v in state_dict.items(): + if k not in used_para_list: + unused_para_list.append(k) + if len(unused_para_list) > 0: + warnings.warn( + "This list is not set, Because of Paramerter not found in program. There are: {}" + .format(" ".join(unused_para_list))) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/ir.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/ir.py new file mode 100644 index 0000000000000000000000000000000000000000..aca134a1df55a9982a3779e03313481cce712e5f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/ir.py @@ -0,0 +1,560 @@ +# Copyright (c) 2021 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. + +import copy +import inspect +from os import path +import paddle +from . import core, unique_name +from .framework import _apply_pass, OpProtoHolder + +from .proto import framework_pb2 +try: + from .proto import pass_desc_pb2 +except ModuleNotFoundError: + import sys + sys.path.append(path.join(path.dirname(__file__), 'proto')) + from .proto import pass_desc_pb2 + + +def get_data_vars(program): + data_vars = [] + for var_name, var in program.global_block().vars.items(): + if var.is_data: + data_vars.append(var_name) + return data_vars + + +def _update_grad_persistable(main_program): + grad_merge_attr_name = "grad_merge_cond_name" + op_role_var_attr_name = core.op_proto_and_checker_maker.kOpRoleVarAttrName() + has_grad_merge = False + has_persistable_grad_var = False + grad_vars = [] + for block_id in range(main_program.num_blocks): + block = main_program.block(block_id) + for op in block.ops: + if grad_merge_attr_name in op.attr_names: + has_grad_merge = True + + if op_role_var_attr_name not in op.attr_names: + continue + + p_g = op.attr(op_role_var_attr_name) + for g in p_g[1::2]: + g_var = block._find_var_recursive(g) + if g_var is None: + continue + grad_vars.append(g_var) + if g_var.persistable: + has_persistable_grad_var = True + + if has_grad_merge and has_persistable_grad_var: + for g_var in grad_vars: + g_var.persistable = True + + +def apply_build_strategy(main_program, startup_program, build_strategy, + pass_attrs): + + def update_attr(attrs, attr_types, name, value, typ=None): + if name not in attrs: + attrs[name] = value + if typ: + attr_types[name] = typ + + def apply_pass(name): + attrs = dict(pass_attrs) + attr_types = {} + update_attr(attrs, attr_types, "nranks", 1, "size_t") + update_attr(attrs, attr_types, "use_cuda", False, "bool") + # TODO(zjl): how to skip fetch variables ? + update_attr(attrs, attr_types, "mem_opt_skip_vars", + get_data_vars(main_program), "list[str]") + _apply_pass(main_program, startup_program, name, attrs, attr_types) + + _update_grad_persistable(main_program) + use_cuda = pass_attrs.get("use_cuda", False) + build_strategy = build_strategy._copy() + if build_strategy.sync_batch_norm: + apply_pass("sync_batch_norm_pass") + build_strategy.sync_batch_norm = False + if build_strategy.fuse_relu_depthwise_conv and use_cuda: + apply_pass("fuse_relu_depthwise_conv_pass") + build_strategy.fuse_relu_depthwise_conv = False + if build_strategy.fuse_bn_act_ops and use_cuda: + apply_pass("fuse_bn_act_pass") + build_strategy.fuse_bn_act_ops = False + if build_strategy.fuse_bn_add_act_ops and use_cuda: + apply_pass("fuse_bn_add_act_pass") + build_strategy.fuse_bn_add_act_ops = False + if build_strategy.enable_auto_fusion and use_cuda: + apply_pass("fusion_group_pass") + build_strategy.enable_auto_fusion = False + if build_strategy.fuse_gemm_epilogue: + apply_pass("fuse_gemm_epilogue_pass") + build_strategy.fuse_gemm_epilogue = False + if build_strategy.fuse_elewise_add_act_ops: + apply_pass("fuse_elewise_add_act_pass") + build_strategy.fuse_elewise_add_act_ops = False + if build_strategy.fuse_all_optimizer_ops: + apply_pass([ + "coalesce_grad_tensor_pass", + "fuse_adam_op_pass", + "fuse_sgd_op_pass", + "fuse_momentum_op_pass", + ]) + build_strategy.fuse_all_optimizer_ops = False + # TODO(zjl): support fuse all reduce ops + if build_strategy.cache_runtime_context: + apply_pass("runtime_context_cache_pass") + build_strategy.cache_runtime_context = False + if build_strategy.enable_addto and use_cuda: + # NOTE: how to get fetch vars to skip memory optimization? + apply_pass("inplace_addto_op_pass") + build_strategy.enable_addto = False + if build_strategy.enable_inplace: + apply_pass("buffer_shared_inplace_pass") + build_strategy.enable_inplace = False + build_strategy._clear_finalized() + return build_strategy + + +class RegisterPassHelper(object): + _register_helpers = list() + + def __init__(self, pass_pairs, pass_type=str(), input_specs=dict()): + self._pass_type = pass_type + self._pass_pairs = pass_pairs + self._input_specs = input_specs + RegisterPassHelper._register_helpers.append(self) + + def _get_args_from_func(self, func): + args = list() + arg_specs = inspect.getfullargspec(func) + for arg_name in arg_specs.args: + input_spec = self._input_specs.get(arg_name) + if isinstance(input_spec, paddle.static.InputSpec): + args.append( + PassDesc.VarHelper(arg_name, input_spec.shape, + input_spec.dtype)) + elif isinstance(input_spec, paddle.ParamAttr): + args.append(paddle.ParamAttr(arg_name)) + else: + args.append(PassDesc.VarHelper(arg_name, [-1])) + return args + + def _prune_program_desc(self, ops): + for op_desc in ops: + default_attrs = core.get_op_attrs_default_value( + paddle.compat.to_bytes(op_desc.type)) + remove_attrs = list() + for attr in op_desc.attrs: + # attr must not in + if attr.name not in [ + "op_namescope", "op_callstack", "op_device" + ]: + attr_list_fields = attr.ListFields() + # attr format must be: name, type, value + if len(attr_list_fields) == 3: + attr_value = attr.ListFields()[-1][-1] + default_attr_value = default_attrs.get(attr.name) + # value must not default + if default_attr_value != attr_value: + continue + remove_attrs.append(attr) + for attr in remove_attrs: + op_desc.attrs.remove(attr) + + def _func_to_program_desc(self, func, ops): + vars = list() + program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(program, startup_program): + args = self._get_args_from_func(func) + vars.extend(args) + outs = func(*args) + if not isinstance(outs, (list, tuple)): + outs = [outs] + for out in outs: + if isinstance(out, PassDesc.OpHelper): + op_outs = out.Outputs() + if len(op_outs) != 1: + raise ValueError( + "Operator '{}' has multiple outputs, please specify one output variable." + .format(out._type)) + for op_out in op_outs.values(): + vars.extend(op_out) + else: + vars.append(out) + block_desc = program.current_block().desc + for i in range(block_desc.op_size()): + ops.add().ParseFromString(block_desc.op(i).serialize_to_string()) + self._prune_program_desc(ops) + return vars, program.current_block().ops + + def _convert_vars_to_pass_desc(self, patterns, replaces, desc): + + def _add_element_conditions(conditions, elements): + for element in elements: + if element._condition: + conditions.append(element._condition) + _add_element_conditions(conditions, element._elements) + + for (pattern, replace) in zip(patterns, replaces): + # Convert maps of inputs and outputs. + var_map = desc.var_maps.add() + var_map.pattern_var = pattern.name + var_map.replace_var = replace.name + conditions = desc.var_attr_conditions + # Convert shape condition. + if pattern.name in self._input_specs: + condition = conditions.add() + pattern.Attr("shape")._to_pass_desc_attr(condition.attr) + condition.condition_value.name = "" + condition.condition_value.type = framework_pb2.AttrType.LONGS + condition.condition_value.longs.extend(pattern.shape) + condition.type = pass_desc_pb2.PassDesc.ConditionType.kEQ + # Convert attr conditions. + if PassDesc.VarHelper == pattern.__class__: + for attr in pattern._attrs.values(): + _add_element_conditions(conditions, [attr]) + + def _convert_ops_to_pass_desc(self, patterns, replaces, desc): + for replace in replaces: + if isinstance(replace, PassDesc.OpHelper): + for attr in replace._attrs.values(): + # Convert attr maps. + mapped = attr._mapped + if inspect.isfunction(mapped): + mapped = mapped(patterns) + attr_map = desc.op_attr_maps.add() + mapped._to_pass_desc_attr(attr_map.pattern_attr) + attr._to_pass_desc_attr(attr_map.replace_attr) + if mapped._operation is not None: + attr_map.operation.CopyFrom(mapped._operation) + + def SerializeMultiPassDesc(self): + switch_static_mode = paddle.in_dynamic_mode() + if switch_static_mode: + paddle.enable_static() + multi_pass_desc = pass_desc_pb2.MultiPassDesc() + multi_pass_desc.pass_type = self._pass_type + # Traverse all pass pairs and convert them to PassDesc data. + # Here need to add cache in the future. + for (pattern, replace) in self._pass_pairs: + pass_desc = multi_pass_desc.pass_descs.add() + # Convert ProgramDescs of pattern and replace subgraphs. + pattern_vars, pattern_ops = self._func_to_program_desc( + pattern, pass_desc.pattern) + replace_vars, replace_ops = self._func_to_program_desc( + replace, pass_desc.replace) + self._convert_vars_to_pass_desc(pattern_vars, replace_vars, + pass_desc) + self._convert_ops_to_pass_desc(pattern_ops, replace_ops, pass_desc) + if switch_static_mode: + paddle.disable_static() + return multi_pass_desc.SerializeToString() + + +class PassDesc(object): + + class AttrHelper(object): + + def __init__(self, obj, name, element_index=None): + self._obj = obj + self._name = name + self._operation_type = None + self._element_index = element_index + self._elements = list() + self._operation = None + self._condition = None + self._mapped = None + + def __getitem__(self, index): + element = PassDesc.AttrHelper(self._obj, + self._name, + element_index=index) + self._elements.append(element) + return element + + def _to_pass_desc_attr(self, pass_desc_attr): + if isinstance(self._obj, PassDesc.VarHelper): + pass_desc_attr.role = pass_desc_pb2.PassDesc.RoleType.kVariable + pass_desc_attr.var_name = self._obj.name + else: + pass_desc_attr.role = pass_desc_pb2.PassDesc.RoleType.kOperator + pass_desc_attr.op_index = self._obj._index + pass_desc_attr.name = self._name + if self._operation_type is not None: + pass_desc_attr.operation = self._operation_type + if self._element_index is not None: + pass_desc_attr.element_index = self._element_index + + def _to_op_desc_attr(self, value, op_desc_attr): + op_desc_attr.name = "" + if isinstance(value, int): + op_desc_attr.type = framework_pb2.AttrType.INT + op_desc_attr.i = value + else: + raise NotImplementedError("Unimplemented transform operation.") + + def _clone_with_operation(self, type, value=None): + attr = PassDesc.AttrHelper(self._obj, self._name, + self._element_index) + self._elements.append(attr) + if value is None: + attr._operation_type = type + return attr + operation = pass_desc_pb2.PassDesc.Operation() + operation.type = type + if isinstance(value, PassDesc.AttrHelper): + value._to_pass_desc_attr(operation.attr) + else: + self._to_op_desc_attr(value, operation.value) + attr._operation = operation + attr._operation_type = self._operation_type + return attr + + def __sub__(self, value): + return self._clone_with_operation( + pass_desc_pb2.PassDesc.OperationType.kSub, value) + + def __add__(self, value): + return self._clone_with_operation( + pass_desc_pb2.PassDesc.OperationType.kAdd, value) + + def Mod(self, value): + return self._clone_with_operation( + pass_desc_pb2.PassDesc.OperationType.kMod, value) + + def Size(self): + return self._clone_with_operation( + pass_desc_pb2.PassDesc.OperationType.kSize) + + def _set_with_condition(self, type, value): + condition = pass_desc_pb2.PassDesc.AttrCondition() + self._to_pass_desc_attr(condition.attr) + condition.type = type + if isinstance(value, PassDesc.AttrHelper): + value._to_pass_desc_attr(condition.condition_attr) + else: + self._to_op_desc_attr(value, condition.condition_value) + if self._operation: + condition.operation.CopyFrom(self._operation) + self._condition = condition + + def EQ(self, value): + self._set_with_condition(pass_desc_pb2.PassDesc.ConditionType.kEQ, + value) + + def MappedPattern(self, + var=None, + op=None, + index=0, + name=None, + element_index=None): + if all([var, op]): + raise ValueError("Only mapped one of which var or op.") + + def mapped_var(pattern_ops): + raise NotImplementedError( + "Mapping to variable is not implemented.") + + def mapped_op(pattern_ops): + ops = [o for o in pattern_ops if o._type == op] + if len(ops) <= index: + raise ValueError( + "Index '{}' of operator '{}' is incorrect.".format( + index, op)) + return PassDesc.AttrHelper(ops[index], + name, + element_index=element_index) + + self._mapped = mapped_op if var is None else mapped_var + + class VarHelper(paddle.static.Variable): + + def __init__(self, *args, **kwargs): + block = paddle.static.default_main_program().current_block() + self._var = paddle.static.data(*args, **kwargs) + self._attrs = dict() + + def __getattr__(self, name): + return getattr(self._var, name) + + def Attr(self, name): + attr = self._attrs.get(name) + if attr is None: + attr = PassDesc.AttrHelper(self, name) + self._attrs[name] = attr + return attr + + class OpHelper(object): + + def __init__(self, type=None): + self._type = type + + def __getattr__(self, name): + op = PassDesc.OpHelper(name) + op.Init() + return op + + def __call__(self, *args, **kwargs): + if len(args) > 0: + raise ValueError( + "Each input argument needs to specify a parameter name.") + for (in_name, in_args) in kwargs.items(): + op_input = self._inputs.get(in_name) + if op_input is None: + raise ValueError( + "Operator '{}' does not have input named '{}'.".format( + self._type, in_name)) + if isinstance(in_args, (list, tuple)): + if len(in_args) == 0: + raise ValueError( + "Input '{}' of operator '{}' cannot be empty.". + format(in_name, self._type)) + else: + in_args = [in_args] + for in_arg in in_args: + if isinstance(in_arg, PassDesc.OpHelper): + op_outs = in_arg.Outputs() + if len(op_outs) != 1: + raise ValueError( + "The size of outputs of operator '{}' is not equal 1, please specify one output variable." + .format(in_arg._type)) + for op_out in op_outs.values(): + op_input.extend(op_out) + else: + op_input.append(in_arg) + self._desc.set_input(in_name, [i.name for i in op_input]) + block = paddle.static.default_main_program().current_block() + for out_name, op_output in self._outputs.items(): + op_output_name = unique_name.generate(self._type) + op_output.append(block.create_var(name=op_output_name)) + self._desc.set_output(out_name, [op_output_name]) + return self + + def Init(self): + block = paddle.static.default_main_program().current_block() + self._proto = OpProtoHolder.instance().op_proto_map.get(self._type) + if self._proto is None: + raise AttributeError( + "type object 'OpHelper' has no attribute '{}'".format( + self._type)) + self._index = len(block.ops) + self._desc = block.desc.append_op() + self._desc.set_type(self._type) + self._attrs = dict() + self._inputs = {i.name: list() for i in self._proto.inputs} + self._outputs = {o.name: list() for o in self._proto.outputs} + block.ops.append(self) + + def Attr(self, name): + attr = self._attrs.get(name) + if attr is None: + attr = PassDesc.AttrHelper(self, name) + self._attrs[name] = attr + return attr + + def SetAttr(self, name, value): + if isinstance(value, PassDesc.AttrHelper): + self.Attr(name)._mapped = value + else: + self._desc._set_attr(name, value) + + def Output(self, name): + output = self._outputs.get(name) + if output is None: + raise ValueError( + "Operator '{}' does not have output named '{}'.".format( + self._type, name)) + return output + + def Outputs(self): + return self._outputs + + def SetOutputs(self, **kwargs): + for param, arg in kwargs.items(): + if arg is None: + self._desc.remove_output(param) + else: + self._desc.set_output(param, [arg.name]) + + OP = OpHelper() + + +def RegisterPass(function=None, input_specs=dict()): + """ + The function decorator of Register Pass. Decorator @RegisterPass handles + the function and register it into a core.Pass instance. Use name of function + as Pass type. + + Args: + function (callable): The function with return of callable pair(s) that + represents the pattern subgraph and the replace subgraph. + input_specs (dict[str, InputSpec]): Dict of InputSpec to specific the shape/dtype + information of Tensor. Some operators limit the shape and dtype of datas when + create subgraph with Paddle APIs. So user need specify InputSpec of data to + ensure create a correctly subgraph. Of course, this argument is not limited to + matching subgraph. The default is dict(). + + Returns: + callables: Callable pair(s). + + Examples: + .. code-block:: python + + import paddle + from paddle.fluid.ir import RegisterPass + + @RegisterPass + def multi_add_to_addn(): + def pattern(x, y, z): + return paddle.add(paddle.add(x, y), z) + def replace(x, y, z): + return paddle.add_n([x, y, z]) + return pattern, replace + """ + + def _is_pass_pair(check_pair): + if isinstance(check_pair, (list, tuple)): + if len(check_pair) == 2: + if all(map(inspect.isfunction, check_pair)): + return True + return False + + def decorated(python_func): + pass_type = python_func.__name__ + signature = inspect.signature(python_func) + if len(signature.parameters) > 0: + raise NotImplementedError( + "Pass function with parameter is not supported now.") + elif len(signature.parameters) == 0: + pass_pairs = python_func() + if _is_pass_pair(pass_pairs): + pass_pairs = [pass_pairs] + elif not all(map(_is_pass_pair, pass_pairs)): + raise ValueError( + "Return value of Pass function must be (callable, callable)." + ) + helper = RegisterPassHelper(pass_pairs, pass_type, input_specs) + core.register_pass(pass_type, helper.SerializeMultiPassDesc) + return python_func + + if inspect.isfunction(function): + return decorated(function) + + return decorated diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..42b67a5a0dfa8599bfe454e59a4d78e3ac1627e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper.py @@ -0,0 +1,188 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import copy +import six + +from .framework import Parameter, dtype_is_floating, _non_static_mode, OpProtoHolder, _global_flags +from . import unique_name +from paddle.fluid.initializer import Constant, Xavier +from .param_attr import ParamAttr +from . import core +from six.moves import zip +from .layer_helper_base import LayerHelperBase +from .dygraph_utils import _append_activation_in_dygraph + + +class LayerHelper(LayerHelperBase): + + def __init__(self, layer_type, **kwargs): + self.kwargs = kwargs + name = self.kwargs.get('name', None) + # TODO(panyx0718, minqiyang): dygraph mode + # can not use both `layer_type` and `name`. Deprecate LayerHelper + # and write a Helper for dygraph mode. + if name is None: + self.kwargs['name'] = unique_name.generate(layer_type) + + super(LayerHelper, self).__init__(self.kwargs['name'], + layer_type=layer_type) + + def append_op(self, *args, **kwargs): + return self.main_program.current_block().append_op(*args, **kwargs) + + def multiple_input(self, input_param_name='input'): + inputs = self.kwargs.get(input_param_name, []) + ret = [] + if isinstance(inputs, list) or isinstance(inputs, tuple): + for inp in inputs: + ret.append(self.to_variable(inp)) + else: + ret.append(self.to_variable(inputs)) + return ret + + def input(self, input_param_name='input'): + inputs = self.multiple_input(input_param_name) + if len(inputs) != 1: + raise "{0} layer only takes one input".format(self.layer_type) + return inputs[0] + + @property + def param_attr(self): + return ParamAttr._to_attr(self.kwargs.get('param_attr', None)) + + @property + def bias_attr(self): + return ParamAttr._to_attr(self.kwargs.get('bias_attr', None)) + + #TODO (jiabin): reconstruct this in LayerObjHelper and avoid dependency of param_attr + def multiple_param_attr(self, length): + param_attr = self.param_attr + if isinstance(param_attr, ParamAttr): + param_attr = [param_attr] + + if len(param_attr) != 1 and len(param_attr) != length: + raise ValueError("parameter number mismatch") + elif len(param_attr) == 1 and length != 1: + tmp = [None] * length + for i in six.moves.range(length): + tmp[i] = copy.deepcopy(param_attr[0]) + param_attr = tmp + return param_attr + + def iter_inputs_and_params(self, input_param_name='input'): + inputs = self.multiple_input(input_param_name) + param_attrs = self.multiple_param_attr(len(inputs)) + for ipt, param_attr in zip(inputs, param_attrs): + yield ipt, param_attr + + def input_dtype(self, input_param_name='input'): + inputs = self.multiple_input(input_param_name) + dtype = None + for each in inputs: + if dtype is None: + dtype = each.dtype + elif dtype != each.dtype: + raise ValueError("Data Type mismatch: %d to %d" % + (dtype, each.dtype)) + return dtype + + def get_parameter(self, name): + param = self.main_program.global_block().var(name) + if not isinstance(param, Parameter): + raise ValueError("no Parameter name %s found" % name) + return param + + #TODO (jiabin): reconstruct this in LayerObjHelper and avoid dependency of bias_attr + def append_bias_op(self, input_var, dim_start=1, dim_end=None): + """ + Append bias operator and return its output. If the user does not set + bias_attr, append_bias_op will return input_var + + :param input_var: the input variable. The len(input_var.shape) is + larger or equal than 2. + :bias_initializer: an instance of a subclass of Initializer used to + initialize the bias + :param dim_start: + :param dim_end: the shape of the bias will be + input_var.shape[dim_start:dim_end]. The bias is broadcasted to other + dimensions and added to input_var to get the output + """ + size = list(input_var.shape[dim_start:dim_end]) + bias_attr = self.bias_attr + if not bias_attr: + return input_var + + b = self.create_parameter(attr=bias_attr, + shape=size, + dtype=input_var.dtype, + is_bias=True) + tmp = self.create_variable_for_type_inference(dtype=input_var.dtype) + self.append_op(type='elementwise_add', + inputs={ + 'X': [input_var], + 'Y': [b] + }, + outputs={'Out': [tmp]}, + attrs={'axis': dim_start}) + return tmp + + #TODO (jiabin): reconstruct this in LayerObjHelper and avoid dependency of act + def append_activation(self, input_var): + act = self.kwargs.get('act', None) + if act is None: + return input_var + if isinstance(act, six.string_types): + act = {'type': act} + else: + raise TypeError(str(act) + " should be unicode or str") + + use_cudnn = None + if 'use_cudnn' in self.kwargs and self.kwargs.get('use_cudnn'): + use_cudnn = self.kwargs.get('use_cudnn') + act['use_cudnn'] = use_cudnn + use_mkldnn = self.kwargs.get( + 'use_mkldnn', + _global_flags().get("FLAGS_use_mkldnn", False)) + if use_mkldnn: + act['use_mkldnn'] = use_mkldnn + act_type = act.pop('type') + if _non_static_mode(): + res = _append_activation_in_dygraph(input_var, act_type, use_cudnn, + use_mkldnn) + return res + else: + tmp = self.create_variable_for_type_inference(dtype=input_var.dtype) + self.append_op(type=act_type, + inputs={"X": [input_var]}, + outputs={"Out": [tmp]}, + attrs=act) + return tmp + + #TODO (jiabin): should we remove this since it has never be used + def _get_default_initializer(self, dtype): + if dtype is None or dtype_is_floating(dtype) is True: + return Xavier() + else: + # For integer and boolean types, initialize with all zeros + return Constant() + + #TODO (jiabin): reconstruct this in LayerObjHelper and avoid dependency of kwargs + def is_instance(self, param_name, cls): + param = self.kwargs.get(param_name, None) + if not isinstance(param, cls): + raise TypeError("The input {0} parameter of method {1} must be {2}", + param_name, self.layer_type, cls.__name__) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper_base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper_base.py new file mode 100644 index 0000000000000000000000000000000000000000..eeeea1a29090dfd6925ef9fe059c378b6facf0e9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layer_helper_base.py @@ -0,0 +1,483 @@ +# 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. + +from __future__ import print_function + +import copy +import numpy as np + +from .framework import Variable, default_main_program, default_startup_program, _non_static_mode, _current_expected_place, _in_eager_without_dygraph_check +from . import unique_name +from .param_attr import ParamAttr, WeightNormParamAttr +from . import core +from .initializer import _global_weight_initializer, _global_bias_initializer + +__all__ = ['LayerHelperBase'] + + +class LayerHelperBase(object): + # global dtype + __dtype = "float32" + + def __init__(self, name, layer_type): + self._layer_type = layer_type + self._name = name + + @property + def name(self): + return self._name + + @property + def layer_type(self): + return self._layer_type + + @property + def main_program(self): + return default_main_program() + + @property + def startup_program(self): + return default_startup_program() + + @classmethod + def set_default_dtype(cls, dtype): + cls.__dtype = dtype + + @classmethod + def get_default_dtype(cls): + return cls.__dtype + + def to_variable(self, value, name=None): + r""" + The API will create a ``Variable`` object from numpy\.ndarray or Variable object. + + Parameters: + value(ndarray): The numpy\.ndarray object that needs to be converted, it can be multi-dimension, and the data type is one of numpy\.{float16, float32, float64, int16, int32, int64, uint8, uint16}. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: ``Tensor`` created from the specified numpy\.ndarray object, data type and shape is the same as ``value`` . + + Examples: + + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + with fluid.dygraph.guard(): + x = np.ones([2, 2], np.float32) + y = fluid.dygraph.to_variable(x) + + """ + if isinstance(value, np.ndarray): + if _in_eager_without_dygraph_check(): + return core.eager.Tensor(value, _current_expected_place(), + False, False, name if name else None, + True) + else: + py_var = core.VarBase(value=value, + name=name if name else '', + persistable=False, + place=_current_expected_place(), + zero_copy=False) + return py_var + elif isinstance(value, (core.VarBase, Variable, core.eager.Tensor)): + return value + else: + raise TypeError( + "The type of input value is invalid, expected type is 'ndarray' or 'Variable', but received %s" + % type(value)) + + def _create_weight_normalize(self, attr, shape, dtype): + from .layers import elementwise_mul, elementwise_div, reshape + + # Remove these ops when LayerHelper and layers support indicating + # program and block. + def __norm_op(x, + out=None, + p=2, + dim=None, + keep_dim=False, + block=self.startup_program.global_block()): + if out is None: + out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_norm'])), + dtype=dtype, + persistable=False) + abs_out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_abs'])), + dtype=dtype, + persistable=False) + block.append_op(type='abs', + inputs={'X': x}, + outputs={'Out': abs_out}) + pow_out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_pow'])), + dtype=dtype, + persistable=False) + block.append_op(type='pow', + inputs={'X': abs_out}, + outputs={'Out': pow_out}, + attrs={'factor': float(p)}) + sum_out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_sum'])), + dtype=dtype, + persistable=False) + block.append_op(type='reduce_sum', + inputs={'X': pow_out}, + outputs={'Out': sum_out}, + attrs={ + 'dim': dim, + 'keep_dim': keep_dim, + 'reduce_all': True if dim is None else False + }) + block.append_op(type='pow', + inputs={'X': sum_out}, + outputs={'Out': out}, + attrs={'factor': 1. / p}) + return out + + def __reshape_op(x, + shape, + out=None, + block=self.startup_program.global_block()): + if out is None: + out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_reshape'])), + dtype=dtype, + persistable=False) + x_shape = block.create_var(name="Xshape", dtype=x.dtype) + block.append_op(type="reshape2", + inputs={'X': x}, + attrs={'shape': shape}, + outputs={ + "Out": out, + "XShape": x_shape + }) + return out + + def __transpose_op(x, + axis, + out=None, + block=self.startup_program.global_block()): + if out is None: + out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_transpose'])), + dtype=dtype, + persistable=False) + block.append_op(type='transpose', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'axis': axis}) + return out + + def __norm_except_dim(x, + out=None, + dim=None, + block=self.startup_program.global_block()): + """Computes the norm over all dimensions except dim""" + if out is None: + out = block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'weight_norm_norm'])), + dtype=dtype, + persistable=False) + if dim is None: + __norm_op(x, out, dim=dim, block=block) + elif dim == 0: + out_shape = [x.shape[0]] + [1] * (len(x.shape) - 1) + reshape = __reshape_op(x, shape=[x.shape[0], -1], block=block) + norm = __norm_op(reshape, dim=[1], block=block) + __reshape_op(norm, out=out, shape=out_shape, block=block) + elif dim == len(x.shape) - 1: + out_shape = [1] * (len(x.shape) - 1) + [x.shape[-1]] + reshape = __reshape_op(x, shape=[-1, x.shape[-1]], block=block) + norm = __norm_op(reshape, dim=[0], block=block) + __reshape_op(norm, out=out, shape=out_shape, block=block) + else: + perm = list(range(len(x.shape))) + perm[0], perm[dim] = dim, 0 + transpose = __transpose_op(x, perm, block=block) + out_shape = [transpose.shape[0] + ] + [1] * (len(transpose.shape) - 1) + reshape = __reshape_op(transpose, + shape=[transpose.shape[0], -1], + block=block) + norm = __norm_op(reshape, dim=[1], block=block) + reshape2 = __reshape_op(norm, shape=out_shape, block=block) + __transpose_op(reshape2, perm, out=out, block=block) + return out + + def __weight_normalize(g, v, dim): + """Calculations for weight normalization""" + norm = __norm_except_dim(v, + dim=dim, + block=self.main_program.current_block()) + scale = elementwise_div( + x=g, y=norm) # The shapes of g and norm are the same. + # Currently, elementwise_mul only support broadcast when the shape + # of y is a subset of the shape of x. Thus, we reshape y to squeeze + # to achieve the subset. + w = elementwise_mul(x=v, + y=scale if dim is None else reshape( + x=scale, shape=[v.shape[dim]]), + axis=-1 if dim is None else dim) + # To serialize the original parameter for inference, maybe a + # parameter rather than a variable should be returned. + return w + + g_param_attr = copy.deepcopy(attr) + g_param_attr.name = attr.name + '_g' + g_param_shape = [1] * len(shape) + if attr.dim is not None: + g_param_shape[attr.dim] = shape[attr.dim] + v_param_attr = copy.deepcopy(attr) + v_param_attr.name = attr.name + '_v' + v_param_shape = shape + + # Add to startup_program to initialize g and v. + # Try to reconstruct the initializer of w by initializing g and v. + # Set the initializers of g and v as below, then the distribution + # of w is the same as initializing w with the given initializer. + # For Data-Dependent Initialization, please compute the init-values + # of g and v in external and then feed the values to g and v by + # executing an extra program. + g_param = self.startup_program.global_block().create_parameter( + dtype=dtype, + shape=g_param_shape, + **g_param_attr._to_kwargs(with_initializer=False)) + v_param = self.startup_program.global_block().create_parameter( + dtype=dtype, + shape=v_param_shape, + **v_param_attr._to_kwargs(with_initializer=True)) + __norm_except_dim(x=v_param, + out=g_param, + dim=attr.dim, + block=self.startup_program.global_block()) + + # keep g_param shape to be consistent with that in main_program + __reshape_op(g_param, + g_param_shape, + out=g_param, + block=self.startup_program.global_block()) + + # Add weight normalization to main_program + g_param = self.main_program.global_block().create_parameter( + dtype=dtype, shape=g_param_shape, **g_param_attr._to_kwargs()) + v_param = self.main_program.global_block().create_parameter( + dtype=dtype, shape=v_param_shape, **v_param_attr._to_kwargs()) + w_param = __weight_normalize(g_param, v_param, dim=attr.dim) + return w_param + + # TODO: hide the func after we move the layers to Layers + def create_parameter(self, + attr, + shape, + dtype=None, + is_bias=False, + default_initializer=None, + stop_gradient=False, + type=core.VarDesc.VarType.LOD_TENSOR): + """Create parameters for this layers. + + Args: + attr: [ParamAttr] should be the parameter attribute for this parameter + shape: shape of the parameter + dtype: data type of this parameter + is_bias: if this is a bias parameter + default_initializer: set the default initializer for this parameter + + Returns created parameter Variable. + """ + # Deepcopy the attr so that parameters can be shared in program + attr = copy.deepcopy(attr) + attr = ParamAttr._to_attr(attr) + if not attr: + return None + assert isinstance(attr, ParamAttr) + for i, size in enumerate(shape): + assert size > 0, ("Expected every dim's size to be larger than 0, " + "but the size of the {}-th dim is {}".format( + i, size)) + # set global dtype + if not dtype: + dtype = self.__dtype + if is_bias: + suffix = 'b' + default_initializer = _global_bias_initializer( + ) if _global_bias_initializer() is not None else default_initializer + else: + suffix = 'w' + default_initializer = _global_weight_initializer( + ) if _global_weight_initializer( + ) is not None else default_initializer + if attr.name is None: + attr.name = unique_name.generate(".".join([self.name, suffix])) + + if default_initializer is None and attr.initializer is None: + if isinstance(dtype, core.VarDesc.VarType): + if dtype != core.VarDesc.VarType.FP32 and \ + dtype != core.VarDesc.VarType.FP64 and \ + dtype != core.VarDesc.VarType.FP16 and \ + dtype != core.VarDesc.VarType.BF16: + raise TypeError( + "Can not create parameter with default initializer when dtype is not float type. Set default_initializer to fit the parameter dtype!" + ) + else: + if not (dtype.startswith("float") + or dtype in ["double", "uint16"]): + raise TypeError( + "Can not create parameter with default initializer when dtype is not float type. Set default_initializer to fit the parameter dtype!" + ) + if is_bias: + attr._set_default_bias_initializer() + else: + attr._set_default_param_initializer() + else: + attr._set_default_initializer(default_initializer) + + # If weight normalization is set, insert extra parameters and ops. + # Refer to https://arxiv.org/pdf/1602.07868.pdf + if isinstance(attr, WeightNormParamAttr): + param = self._create_weight_normalize(attr, shape, dtype) + WeightNormParamAttr.params_with_weight_norm.append(param) + return param + if _non_static_mode(): + # In dygraph mode, we want the returned parameter to be + # initialized so that it can be used imperatively. + # check parameter name + is_used = unique_name.dygraph_parameter_name_checker(attr.name) + if is_used: + raise ValueError( + "parameter name [{}] have be been used. " + "In dygraph mode, the name of parameter can't be same." + "Please check the parameter attr value passed to self.create_parameter or " + "constructor of dygraph Layers".format(attr.name)) + return self.main_program.global_block().create_parameter( + dtype=dtype, + shape=shape, + type=type, + stop_gradient=stop_gradient, + **attr._to_kwargs(with_initializer=True)) + else: + self.startup_program.global_block().create_parameter( + dtype=dtype, + shape=shape, + type=type, + **attr._to_kwargs(with_initializer=True)) + return self.main_program.global_block().create_parameter( + dtype=dtype, shape=shape, type=type, **attr._to_kwargs()) + + def create_variable_for_type_inference(self, + dtype, + stop_gradient=False, + shape=None): + """Create a temporary variable that should be type inferred layer. + + Note: + The default type will be set to LOD_TENSOR. However, when + the var is used as operator output, its type will be updated + based on operator's `VarTypeInference` implementation in + infer_var_type. + """ + # set global dtype + if not dtype: + dtype = self.__dtype + return self.main_program.current_block().create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'tmp'])), + dtype=dtype, + shape=shape, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=stop_gradient) + + def create_sparse_variable_for_type_inference(self, + dtype, + stop_gradient=False, + shape=None): + """Create a temporary sparse variable that should be type inferred layer. + + Note: + The default type will be set to SPARSE_COO. However, when + the var is used as operator output, its type will be updated + based on operator's `VarTypeInference` implementation in + infer_var_type. + """ + # set global dtype + if not dtype: + dtype = self.__dtype + return self.main_program.current_block().create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [self.name, 'tmp'])), + dtype=dtype, + shape=shape, + type=core.VarDesc.VarType.SPARSE_COO, + persistable=False, + stop_gradient=stop_gradient) + + def create_variable(self, *args, **kwargs): + """Create Variable for this layers. + Returns created Variable. + """ + return self.main_program.current_block().create_var(*args, **kwargs) + + def create_global_variable(self, persistable=False, *args, **kwargs): + """ + create global variable, note that there is no initializer for this global variable. + Args: + persistable(bool): True if it is a checkpoint value. + *args: See create_var's documentation + **kwargs: See create_var's documentation + + Returns(Variable): the created variable. + """ + return self.main_program.global_block().create_var( + *args, persistable=persistable, **kwargs) + + def create_or_get_global_variable(self, name, *args, **kwargs): + """ + Creates a global variable if not exists and returns the variable and + a boolean flag which is true when it is a new variable. + """ + if self.main_program.global_block().has_var(name): + return self.main_program.global_block().var(name), False + else: + return self.create_global_variable(name=name, *args, **kwargs), True + + def set_variable_initializer(self, var, initializer): + """Set target Variable's initializer + + Args: + var: target Variable + initializer: initializer to use + """ + assert isinstance(var, Variable) + if _non_static_mode(): + initializer(var, self.main_program.global_block()) + else: + self.startup_program.global_block().create_var( + name=var.name, + type=var.type, + dtype=var.dtype, + shape=var.shape, + persistable=True, + initializer=initializer) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d49b9100361c00ba3530e50b1d6e5f4232ae953 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/__init__.py @@ -0,0 +1,58 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from . import ops +from .ops import * +from . import nn +from .nn import * +from . import io +from .io import * +from . import tensor +from .tensor import * +from . import control_flow +from .control_flow import * +from . import device +from .device import * +from . import math_op_patch +from .math_op_patch import * +from . import loss +from .loss import * +from . import detection +from .detection import * +from . import metric_op +from .metric_op import * +from .learning_rate_scheduler import * +from .collective import * +from .distributions import * +from .sequence_lod import * +from . import rnn + +__all__ = [] +__all__ += nn.__all__ +__all__ += io.__all__ +__all__ += tensor.__all__ +__all__ += control_flow.__all__ +__all__ += ops.__all__ +__all__ += device.__all__ +__all__ += detection.__all__ +__all__ += metric_op.__all__ +__all__ += learning_rate_scheduler.__all__ +__all__ += distributions.__all__ +__all__ += sequence_lod.__all__ +__all__ += loss.__all__ +__all__ += rnn.__all__ + +from .rnn import * diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/collective.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..0d62bb17ea4d6203c124a451f72abbcac3037dd1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/collective.py @@ -0,0 +1,195 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +from ..layer_helper import LayerHelper, unique_name +from ..framework import Variable, in_dygraph_mode, _in_legacy_dygraph +import paddle +from paddle import _C_ops, _legacy_C_ops + + +def _allreduce(x, out=None, reduce_type="sum", sync_mode=False): + helper = LayerHelper("allreduce", **locals()) + # Convert string reduce type to op int type + red_typ_int = 0 + if reduce_type == "sum": + red_typ_int = 0 + elif reduce_type == "prod": + red_typ_int = 1 + elif reduce_type == "max": + red_typ_int = 2 + elif reduce_type == "min": + red_typ_int = 3 + else: + raise TypeError("reduce type can only be [sum|prod|max|min]") + + if out is None: + out = helper.create_variable( + name=unique_name.generate_with_ignorable_key(".".join( + [x.name, 'tmp'])), + shape=x.shape, + dtype=x.dtype, + type=x.type, + persistable=x.persistable, + stop_gradient=True) + helper.append_op(type='allreduce', + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={ + "reduce_type": red_typ_int, + "sync_mode": sync_mode + }) + return out + + +def _broadcast(x, root, sync_mode=False): + helper = LayerHelper("broadcast", **locals()) + helper.append_op(type='broadcast', + inputs={'X': [x]}, + outputs={'Out': [x]}, + attrs={ + "sync_mode": sync_mode, + "root": root + }) + return x + + +def _c_allreduce(x, + out=None, + reduce_type='sum', + ring_id=0, + use_calc_stream=False): + helper = LayerHelper('c_allreduce', **locals()) + + if reduce_type not in ['sum', 'prob', 'max', 'min']: + raise TypeError('reduce type can only be "sum|prod|max|min]"') + + op_type = 'c_allreduce_' + reduce_type + if out is None: + out = helper.create_variable( + name=unique_name.generate_with_ignorable_key('.'.join( + [x.name, op_type])), + shape=x.shape, + dtype=x.dtype, + type=x.type, + persistable=x.persistable) + + helper.append_op(type=op_type, + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream + }) + return out + + +def _c_broadcast(x, root=0, ring_id=0, use_calc_stream=False): + op_type = 'c_broadcast' + helper = LayerHelper(op_type, **locals()) + helper.append_op(type=op_type, + inputs={'X': [x]}, + outputs={'Out': [x]}, + attrs={ + 'root': root, + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream + }) + return x + + +def _c_allgather(x, nranks, ring_id=0, use_calc_stream=False): + op_type = 'c_allgather' + + if in_dygraph_mode(): + group = paddle.distributed.collective._get_default_group() + tensor_shape = list(x.shape) + tensor_shape[0] *= nranks + out = paddle.empty(tensor_shape, x.dtype) + task = group.process_group.all_gather(x, out) + task.wait() + return out + + if _in_legacy_dygraph(): + attrs = ('nranks', nranks, 'ring_id', ring_id, 'use_calc_stream', + use_calc_stream) + return _legacy_C_ops.c_allgather(x, *attrs) + + helper = LayerHelper(op_type, **locals()) + out_shape = list(x.shape[:]) + if out_shape[0] > 0: + out_shape[0] *= nranks + out = helper.create_variable(name=unique_name.generate_with_ignorable_key( + '.'.join([x.name, op_type])), + shape=out_shape, + dtype=x.dtype, + type=x.type, + persistable=x.persistable) + helper.append_op(type=op_type, + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={ + 'nranks': nranks, + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream + }) + return out + + +def _c_reducescatter(x, nranks, ring_id=0, use_calc_stream=False): + if not isinstance(x, Variable): + raise TypeError('x must be a Variable') + + if x.shape[0] > 0 and x.shape[0] % nranks != 0: + raise ValueError( + 'x.shape[0](%d) cannot be evenly divided by nranks(%d)' % + (x.shape[0], nranks)) + + op_type = 'c_reducescatter' + helper = LayerHelper(op_type, **locals()) + out_shape = list(x.shape[:]) + if out_shape[0] > 0: + out_shape[0] //= nranks + out = helper.create_variable(name=unique_name.generate_with_ignorable_key( + '.'.join([x.name, op_type])), + shape=out_shape, + dtype=x.dtype, + type=x.type, + persistable=x.persistable) + helper.append_op(type=op_type, + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={ + 'nranks': nranks, + 'ring_id': ring_id, + 'use_calc_stream': use_calc_stream + }) + return out + + +def _c_sync_calc_stream(x): + op_type = 'c_sync_calc_stream' + helper = LayerHelper(op_type, **locals()) + helper.append_op(type=op_type, inputs={'X': [x]}, outputs={'Out': [x]}) + return x + + +def _c_sync_comm_stream(x, ring_id): + op_type = 'c_sync_comm_stream' + helper = LayerHelper(op_type, **locals()) + helper.append_op(type=op_type, + inputs={'X': [x]}, + outputs={'Out': [x]}, + attrs={'ring_id': ring_id}) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/control_flow.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/control_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..49a779a2eb065c096952b0cb2a8af074c941aea0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/control_flow.py @@ -0,0 +1,4518 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +from ..wrapped_decorator import signature_safe_contextmanager + +from .layer_function_generator import autodoc, templatedoc +from .tensor import assign, cast, fill_constant +from .. import core +from ..framework import ( + Program, + Variable, + Operator, + _non_static_mode, + static_only, + _in_legacy_dygraph, + in_dygraph_mode, +) +from ..layer_helper import LayerHelper, unique_name +from .nn import logical_and, logical_not, logical_or +from .utils import ( + assert_same_structure, + map_structure, + hold_mutable_vars, + copy_mutable_vars, + padding_to_same_structure, + is_sequence, + pack_sequence_as, + flatten, + to_sequence, +) +import numpy +import warnings +import six +from functools import reduce, partial +from ..data_feeder import ( + convert_dtype, + check_variable_and_dtype, + check_type, + check_dtype, +) +from ... import compat as cpt +from ..backward import _infer_var_data_type_shape_ +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'While', + 'Switch', + 'increment', + 'array_write', + 'create_array', + 'less_than', + 'less_equal', + 'greater_than', + 'greater_equal', + 'equal', + 'not_equal', + 'array_read', + 'array_length', + 'cond', + 'IfElse', + 'DynamicRNN', + 'StaticRNN', + 'reorder_lod_tensor_by_rank', + 'Print', + 'Assert', + 'is_empty', + 'case', + 'switch_case', + 'while_loop', +] + + +def select_output(input, outputs, mask): + """ + **select_output** + This API takes in one input and multiple outputs and an integer mask. It + selects the output specified by the mask and copy the input to selected + output. It is useful in control flow. + + Args: + input(Variable): The input variable + outputs(tuple|list): The output variables + mask(Variable): A tensor containing 1 integer number selecting which + output to be copied with input + + Returns: + Variable: The outputs variables + """ + helper = LayerHelper('select_output', **locals()) + check_type(input, 'input', (Variable), 'select_output') + check_variable_and_dtype(mask, 'mask', ['int32'], 'select_output') + check_type(outputs, 'outputs', (list, tuple), 'select_output') + + helper.append_op( + type='select_output', + inputs={'X': input, 'Mask': mask}, + outputs={'Out': outputs}, + ) + return outputs + + +def _select_input_infer_shape(first_shape, second_shape): + """ + This function infer the output shape by following algorithm: + 1. if the dims is different, raise a error. + 2. compare axis one by one: + if a == b: we set axis to a + if a != b: we set axis to -1 + for compatibility,non declarative mode, we just return second_shape. + """ + if len(first_shape) != len(second_shape): + warnings.warn( + f"the input shapes of select_input should have the same rank, but get {first_shape}, {second_shape}" + ) + return second_shape + out_shape = list( + map(lambda a, b: a if a == b else -1, first_shape, second_shape) + ) + return out_shape + + +def select_input(inputs, mask): + """ + **select_input** + + This API takes in multiple inputs and uses an integer mask to select one + input to output. It is useful in control flow. + + Args: + inputs(tuple|list): The input variables + mask(Variable): A tensor containing 1 integer number selecting which + input to output + + Returns: + Variable: The selected input variable + """ + helper = LayerHelper('select_input', **locals()) + check_type(inputs, 'inputs', (list, tuple), 'select_input') + check_variable_and_dtype(mask, 'mask', ['int32'], 'select_input') + + # Select input should expand the shape. If it is - 1 and valid number, use - 1 first. If the dim is different, an error will be reported directly + # assert inputs[0].dtype == inputs[1].dtype, f"Expect the inputs should have the same dtype, but get {inputs[0].dtype} and {inputs[1].dtype}" + output_shape = _select_input_infer_shape(inputs[0].shape, inputs[1].shape) + output_dtype = inputs[1].dtype + output_type = inputs[1].type + + out = helper.create_variable( + dtype=output_dtype, shape=output_shape, type=output_type + ) + helper.append_op( + type='select_input', + inputs={'X': inputs, 'Mask': mask}, + outputs={'Out': out}, + ) + return out + + +def select_input_with_buildin_type(inputs, mask, name): + from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import ( + to_static_variable, + ) + from paddle.fluid.dygraph.dygraph_to_static.utils import UndefinedVar + + false_var, true_var = inputs + + if isinstance(false_var, UndefinedVar) and isinstance( + true_var, UndefinedVar + ): + """None -> UndefinedVar, so the real value is a [None, UndefinedVar] or [None, None], we just return None.""" + return None + + if isinstance(false_var, Variable) and isinstance(true_var, Variable): + try: + return select_input(inputs, mask) + except Exception as e: + raise RuntimeError( + f"Exceptions throwed while doing select_input on {name}:\n{e}" + ) + + elif isinstance(false_var, (support_ret_buildin_type)) and isinstance( + false_var, type(true_var) + ): + if false_var == true_var: + return false_var + else: + inputs = [ + to_static_variable(false_var), + to_static_variable(true_var), + ] + # Deal with the situations like this: false_var is int and true_var is Variable + elif ( + isinstance(false_var, support_ret_buildin_type) + and isinstance(true_var, Variable) + ) or ( + isinstance(true_var, support_ret_buildin_type) + and isinstance(false_var, Variable) + ): + inputs = [to_static_variable(false_var), to_static_variable(true_var)] + warnings.warn( + "Return results from different branches in cond are not same type: " + "false_var returned by fasle_fn is '{}' and true_var of true_fn is " + "'{}'".format(type(false_var), type(true_var)) + ) + elif ( + isinstance(false_var, UndefinedVar) + and isinstance(true_var, (Variable,) + support_ret_buildin_type) + ) or ( + isinstance(true_var, UndefinedVar) + and isinstance(false_var, (Variable,) + support_ret_buildin_type) + ): + + def create_var_if_not_undefined_var(a): + if isinstance(a, UndefinedVar): + return a + return to_static_variable(a) + + true_var, false_var = to_static_variable(true_var), to_static_variable( + false_var + ) + inputs = [false_var, true_var] + else: + raise TypeError( + "Unsupported return type of true_fn and false_fn in cond: false_var " + "returned by fasle_fn is '{}' and true_var of true_fn is '{}'".format( + type(false_var), type(true_var) + ) + ) + try: + return select_input(inputs, mask) + except Exception as e: + raise RuntimeError( + f"Exceptions throwed while doing select_input on {name}:\n{e}" + ) + + +def split_lod_tensor(input, mask, level=0): + """ + This function takes in an input that contains the complete lod information, + and takes in a mask which is used to mask certain parts of the input. + The output is the true branch and the false branch with the mask applied to + the input at a certain level in the tensor. Mainly used in IfElse to split + data into two parts. + + Args: + input(Variable|tuple|list|None): The input tensor that contains complete + lod information needed to construct the output. + mask(Variable|list): A bool column vector which masks the input. + level(int): The specific lod level to split. + + Returns: + tuple(Variable, Variable): + The true branch of tensor as per the mask applied to input. + + The false branch of tensor as per the mask applied to input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[1]) + x.persistable = True + + y = fluid.layers.data(name='y', shape=[1]) + y.persistable = True + + out_true, out_false = fluid.layers.split_lod_tensor( + input=x, mask=y, level=level) + + """ + check_type( + input, + 'input', + (Variable, list, tuple, type(None)), + 'fluid.layers.split_lod_tensor', + ) + check_type(mask, 'mask', (Variable, list), 'fluid.layers.split_lod_tensor') + check_type(level, 'level', int, 'fluid.layers.split_lod_tensor') + helper = LayerHelper('split_lod_tensor', **locals()) + out_true = helper.create_variable_for_type_inference(dtype=input.dtype) + out_false = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='split_lod_tensor', + inputs={ + 'X': input, + 'Mask': mask, + }, + outputs={'OutTrue': out_true, 'OutFalse': out_false}, + attrs={'level': level}, + ) + return out_true, out_false + + +def merge_lod_tensor(in_true, in_false, x, mask, level=0): + """ + **merge_lod_tensor** + + This function takes in an input :math:`x`, the True branch, the False + branch and a binary :math:`mask`. Using this information, this function + merges the True and False branches of the tensor into a single tensor as + output at a certain lod level indicated by :math:`level`. Used in IfElse + to merge the output if True block and False Block. + + Args: + in_true(Variable|tuple|list|None): The True branch to be merged. + in_false(Variable|tuple|list|None): The False branch to be merged. + x(Variable|tuple|list|None): The input tensor that contains complete + lod information needed to construct the output. + mask(Variable|list): A bool column vector which masks the input. + level(int): The specific lod level to merge. + + Returns: + Variable: The merged output tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = layers.data( + name='x', shape=[1], dtype='float32', stop_gradient=False) + y = layers.data( + name='y', shape=[1], dtype='bool', stop_gradient=False) + + level = 0 + + out_true, out_false = layers.split_lod_tensor( + input=x, mask=y, level=level) + out = layers.merge_lod_tensor( + in_true=out_true, in_false=out_false, mask=y, x=x, level=level) + """ + helper = LayerHelper('merge_lod_tensor', **locals()) + check_type( + x, + 'x', + (Variable, list, tuple, type(None)), + 'fluid.layers.merge_lod_tensor', + ) + check_type(mask, 'mask', (Variable, list), 'fluid.layers.merge_lod_tensor') + check_type( + in_true, + 'in_true', + (Variable, list, tuple, type(None)), + 'fluid.layers.merge_lod_tensor', + ) + check_type( + in_false, + 'in_false', + (Variable, list, tuple, type(None)), + 'fluid.layers.merge_lod_tensor', + ) + out = helper.create_variable_for_type_inference(dtype=in_true.dtype) + helper.append_op( + type='merge_lod_tensor', + inputs={'X': x, 'Mask': mask, 'InTrue': in_true, 'InFalse': in_false}, + outputs={'Out': out}, + attrs={'level': level}, + ) + return out + + +@static_only +def Print( + input, + first_n=-1, + message=None, + summarize=20, + print_tensor_name=True, + print_tensor_type=True, + print_tensor_shape=True, + print_tensor_layout=True, + print_tensor_lod=True, + print_phase='both', +): + ''' + :api_attr: Static Graph + + **Print operator** + + This creates a print op that will print when a tensor is accessed. + + Wraps the tensor passed in so that whenever that a tensor is accessed, + the message `message` is printed, along with the current value of the + tensor `t`. + + Args: + input (Variable): A Tensor to print. + summarize (int): Number of elements in the tensor to be print. If it's + value is -1, then all elements in the tensor will be print. + message (str): A string message to print as a prefix. + first_n (int): Only log `first_n` number of times. + print_tensor_name (bool, optional): Print the tensor name. Default: True. + print_tensor_type (bool, optional): Print the tensor type. Defaultt: True. + print_tensor_shape (bool, optional): Print the tensor shape. Default: True. + print_tensor_layout (bool, optional): Print the tensor layout. Default: True. + print_tensor_lod (bool, optional): Print the tensor lod. Default: True. + print_phase (str): Which phase to displace, including 'forward', + 'backward' and 'both'. Default: 'both'. If set to 'backward', will + only print the gradients of input tensor; If set to 'both', will + both print the input tensor itself and the gradients of input tensor. + + Returns: + Variable: Output tensor. + + NOTES: + The input and output are two different variables, and in the + following process, you should use the output variable but not the input, + otherwise, the print layer doesn't have backward. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + x = paddle.full(shape=[2, 3], fill_value=3, dtype='int64') + out = paddle.static.Print(x, message="The content of input layer:") + + main_program = paddle.static.default_main_program() + exe = paddle.static.Executor(place=paddle.CPUPlace()) + res = exe.run(main_program, fetch_list=[out]) + # Variable: fill_constant_1.tmp_0 + # - message: The content of input layer: + # - lod: {} + # - place: CPUPlace + # - shape: [2, 3] + # - layout: NCHW + # - dtype: long + # - data: [3 3 3 3 3 3] + ''' + check_variable_and_dtype( + input, + 'input', + ['float32', 'float64', 'int32', 'int64', 'bool'], + 'fluid.layers.Print', + ) + + helper = LayerHelper('print' + "_" + input.name, **locals()) + output = helper.create_variable_for_type_inference(input.dtype) + helper.append_op( + type='print', + inputs={'In': input}, + outputs={'Out': output}, + attrs={ + 'first_n': first_n, + 'summarize': summarize, + 'message': message or "", + 'print_tensor_name': print_tensor_name, + 'print_tensor_type': print_tensor_type, + 'print_tensor_shape': print_tensor_shape, + 'print_tensor_layout': print_tensor_layout, + 'print_tensor_lod': print_tensor_lod, + 'print_phase': print_phase.upper(), + }, + ) + return output + + +def Assert(cond, data=None, summarize=20, name=None): + ''' + This API creates an op that asserts the given condition is true. If the + condition is false, prints the tensors in data. ``summarize`` specifies the + number of the elements in the tensors to print. + + Args: + cond (Variable): The boolean condition tensor whose numel should be 1. + data (list|tuple, optional): list or tuple of tensors to print when + condition is not true. If it's ``None``, no tensor will be printed. + The default value is ``None``. + summarize (int, optional): Number of elements in the tensor to be + printed. If its value is -1, then all elements in the tensor will + be printed. The default value is 20. + name (str, optional): The default value is ``None`` . Normally users + don't have to set this parameter. For more information, please + refer to :ref:`api_guide_Name` . + + Returns: + Operator: the created operation. + + Raises: + TypeError: If ``cond`` is not boolean Variable. + TypeError: If ``data`` is not a list or tuple or ``None``. + TypeError: If ``summarize`` is not int. + TypeError: If ``name`` is not a string or ``None`` . + fluid.core.EnforceNotMet: If the condition is False in running time. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + x = layers.fill_constant(shape=[2, 3], dtype='float32', value=2.0) + condition = layers.reduce_max(x) < 1.0 # False + layers.Assert(condition, [x], 10, "example_assert_layer") + + exe = fluid.Executor() + try: + exe.run(fluid.default_main_program()) + # Print x and throws paddle.fluid.core.EnforceNotMet exception + # Example printed message for x: + # + # Variable: fill_constant_0.tmp_0 + # - lod: {} + # - place: CPUPlace() + # - shape: [2, 3] + # - layout: NCHW + # - dtype: float + # - data: [2 2 2 2 2 2] + except fluid.core.EnforceNotMet as e: + print("Assert Exception Example") + + ''' + check_variable_and_dtype(cond, "cond", ["bool"], "fluid.layers.Assert") + check_type(data, "data", (list, tuple, type(None)), "fluid.layers.Assert") + check_type(summarize, "summarize", int, "fluid.layers.Assert") + check_type(name, "name", (str, type(None)), "fluid.layers.Assert") + + layer_name = name if name else ('assert_' + cond.name) + helper = LayerHelper(layer_name, **locals()) + + op = helper.append_op( + type="assert", + inputs={"Cond": cond, "Data": [] if data is None else list(data)}, + attrs={"summarize": summarize}, + ) + + return op + + +class BlockGuard(object): + """ + BlockGuard class. + + BlockGuard class is used to create a sub-block in a program by + using the Python `with` keyword. + """ + + def __init__(self, main_program): + if not isinstance(main_program, Program): + raise TypeError("BlockGuard takes a program") + self.main_program = main_program + + def __enter__(self): + self.main_program._create_block() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.main_program._rollback() + if exc_type is not None: + return False # re-raise exception + return True + + +class BlockGuardWithCompletion(BlockGuard): + """ + BlockGuardWithCompletion class. + + BlockGuardWithCompletion class is used to create an op with a block in a program. + """ + + def __init__(self, rnn): + if not isinstance(rnn, StaticRNN): + raise TypeError("BlockGuardWithCompletion takes a StaticRNN") + super(BlockGuardWithCompletion, self).__init__(rnn.helper.main_program) + self.rnn = rnn + + def __enter__(self): + self.rnn.status = StaticRNN.IN_RNN_BLOCK + return super(BlockGuardWithCompletion, self).__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is not None: + return False + self.rnn.status = StaticRNN.AFTER_RNN_BLOCK + self.rnn._complete_op() + return super(BlockGuardWithCompletion, self).__exit__( + exc_type, exc_val, exc_tb + ) + + +class StaticRNNMemoryLink(object): + """ + StaticRNNMemoryLink class. + + StaticRNNMemoryLink class is used to create a link between two + memory cells of a StaticRNN. + + + NOTE: This is a internal data structure of a very low-level API. + Please use StaticRNN instead. + + Args: + init(Variable): the initial variable for Memory. + pre_mem(Variable): the memory variable in previous time step. + mem(Variable): the memory variable in current time step. + """ + + def __init__(self, init, pre_mem, mem=None): + self.init = init + self.pre_mem = pre_mem + self.mem = mem + + +class StaticRNN(object): + """ + :api_attr: Static Graph + + StaticRNN class. + + The StaticRNN can process a batch of sequence data. The first dimension of inputs + represents sequence length, the length of each input sequence must be equal. + StaticRNN will unfold sequence into time steps, user needs to define how to process + each time step during the :code:`with` step. + + Args: + name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # create prev memory parameter, batch size comes from word + prev = rnn.memory(shape=[-1, hidden_size], batch_ref = word) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # use hidden to update prev + rnn.update_memory(prev, hidden) + # mark hidden as output + rnn.step_output(hidden) + # get StaticrNN final output + result = rnn() + + """ + + BEFORE_RNN_BLOCK = 0 + IN_RNN_BLOCK = 1 + AFTER_RNN_BLOCK = 2 + + def __init__(self, name=None): + check_type(name, "name", (str, type(None)), "fluid.layers.StaticRNN") + self.helper = LayerHelper("static_rnn", name=name) + self.memories = {} # memory map, from pre_mem.name --> MemoryLink + self.inputs = [] # input variable list in current block + self.outputs = [] # output variable list in parent block + self.status = StaticRNN.BEFORE_RNN_BLOCK # status flag. + # sequence length, since it is a static RNN, sequence length are fixed. + self.seq_len = None + + def step(self): + """ + Define operators in each step. step is used in :code:`with` block, OP in :code:`with` block + will be executed sequence_len times (sequence_len is the length of input) + """ + return BlockGuardWithCompletion(self) + + def _assert_in_rnn_block_(self, method): + if self.status != StaticRNN.IN_RNN_BLOCK: + raise ValueError("You must invoke {0} in rnn block".format(method)) + + def memory( + self, + init=None, + shape=None, + batch_ref=None, + init_value=0.0, + init_batch_dim_idx=0, + ref_batch_dim_idx=1, + ): + """ + Create a memory variable for static rnn. + If the :code:`init` is not None, :code:`memory` will be initialized by + this Variable. If the :code:`init` is None, :code:`shape` and :code:`batch_ref` + must be set, and this function will create a new variable with shape and batch_ref + to initialize :code:`init` Variable. + + Args: + init(Variable, optional): Tensor used to init memory. If it is not set, + :code:`shape` and :code:`batch_ref` must be provided. + Default: None. + shape(list|tuple): When :code:`init` is None use this arg to initialize memory shape. + NOTE the shape does not contain batch_size. Default: None. + batch_ref(Variable, optional): When :code:`init` is None, memory's batch size will + be set as batch_ref's ref_batch_dim_idx value. Default: None. + init_value(float, optional): When :code:`init` is None, used to init memory's value. Default: 0.0. + init_batch_dim_idx(int, optional): the batch_size axis of the :code:`init` Variable. Default: 0. + ref_batch_dim_idx(int, optional): the batch_size axis of the :code:`batch_ref` Variable. Default: 1. + + Returns: + Variable: The memory variable. + + Examples 1: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # create prev memory parameter, batch size comes from word + prev = rnn.memory(shape=[-1, hidden_size], batch_ref = word) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # use hidden to update prev + rnn.update_memory(prev, hidden) + + + Examples 2: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + boot_memory = fluid.layers.data(name='boot', shape=[hidden_size], dtype='float32', lod_level=1) + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # init memory + prev = rnn.memory(init=boot_memory) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # update hidden with prev + rnn.update_memory(prev, hidden) + + """ + self._assert_in_rnn_block_('memory') + check_type( + init, + "init", + (Variable, type(None)), + "fluid.layers.StaticRNN.memory", + ) + check_type( + shape, + "shape", + (list, tuple, type(None)), + "fluid.layers.StaticRNN.memory", + ) + check_type( + batch_ref, + "batch_ref", + (Variable, type(None)), + "fluid.layers.StaticRNN.memory", + ) + if init is None: + if shape is None or batch_ref is None: + raise ValueError( + "if init is None, memory at least need shape and batch_ref" + ) + parent_block = self._parent_block() + var_name = unique_name.generate_with_ignorable_key( + "@".join([self.helper.name, "memory_boot"]) + ) + boot_var = parent_block.create_var( + name=var_name, + shape=shape, + dtype=batch_ref.dtype, + persistable=False, + ) + + parent_block.append_op( + type="fill_constant_batch_size_like", + inputs={'Input': [batch_ref]}, + outputs={'Out': [boot_var]}, + attrs={ + 'value': init_value, + 'shape': boot_var.shape, + 'dtype': boot_var.dtype, + 'input_dim_idx': ref_batch_dim_idx, + 'output_dim_idx': init_batch_dim_idx, + }, + ) + + return self.memory(init=boot_var) + else: + pre_mem = self.helper.create_variable( + name=unique_name.generate_with_ignorable_key( + "@".join([self.helper.name, "mem"]) + ), + dtype=init.dtype, + shape=init.shape, + ) + self.memories[pre_mem.name] = StaticRNNMemoryLink( + init=init, pre_mem=pre_mem + ) + return pre_mem + + def step_input(self, x): + """ + Mark a sequence as a StaticRNN input. + + Args: + x(Variable): The input sequence, the shape of x + should be [seq_len, ...]. + + Returns: + Variable: The current time step data in the input sequence. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # create prev memory parameter, batch size comes from word + prev = rnn.memory(shape=[-1, hidden_size], batch_ref = word) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # use hidden to update prev + rnn.update_memory(prev, hidden) + + """ + self._assert_in_rnn_block_('step_input') + check_type(x, "x", Variable, "fluid.layers.StaticRNN.step_input") + if self.seq_len is None: + self.seq_len = x.shape[0] + elif x.shape[0] != -1 and self.seq_len != x.shape[0]: + raise ValueError("Static RNN only take fix seq_len input") + + ipt = self.helper.create_variable( + name=x.name, dtype=x.dtype, shape=list(x.shape[1:]), type=x.type + ) + self.inputs.append(ipt) + return ipt + + def step_output(self, o): + """ + Mark a sequence as a StaticRNN output. + + Args: + o(Variable): The output sequence. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # create prev memory parameter, batch size comes from word + prev = rnn.memory(shape=[-1, hidden_size], batch_ref = word) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # use hidden to update prev + rnn.update_memory(prev, hidden) + rnn.step_output(hidden) + + result = rnn() + + """ + self._assert_in_rnn_block_('step_output') + check_type(o, "o", Variable, "fluid.layers.StaticRNN.step_output") + + tmp_o = self.helper.create_variable_for_type_inference(dtype=o.dtype) + self.helper.append_op( + type='rnn_memory_helper', + inputs={'X': [o]}, + outputs={'Out': tmp_o}, + attrs={'dtype': o.dtype}, + ) + + out_var = self._parent_block().create_var( + name=tmp_o.name, + shape=[self.seq_len] + list(tmp_o.shape), + dtype=tmp_o.dtype, + ) + + self.outputs.append(out_var) + + def output(self, *outputs): + """ + Mark the StaticRNN output variables. + + Args: + outputs: The output Tensor, can mark multiple variables as output + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + vocab_size, hidden_size=10000, 200 + x = fluid.data(name="x", shape=[None, 1, 1], dtype='int64') + # create word sequence + x_emb = layers.embedding( + input=x, + size=[vocab_size, hidden_size], + dtype='float32', + is_sparse=False) + # transform batch size to dim 1 + x_emb = layers.transpose(x_emb, perm=[1, 0, 2]) + + rnn = fluid.layers.StaticRNN() + with rnn.step(): + # mark created x_emb as input, each step process a word + word = rnn.step_input(x_emb) + # create prev memory parameter, batch size comes from word + prev = rnn.memory(shape=[-1, hidden_size], batch_ref = word) + hidden = fluid.layers.fc(input=[word, prev], size=hidden_size, act='relu') + # use hidden to update prev + rnn.update_memory(prev, hidden) + # mark each step's hidden and word as output + rnn.output(hidden, word) + + result = rnn() + """ + for each in outputs: + self.step_output(each) + + def update_memory(self, mem, var): + """ + Update the memory from :code:`mem` to :code:`var`. + + Args: + mem(Variable): the memory variable. + var(Variable): the plain variable generated in RNN block, used to update memory. + var and mem should have same dims and data type. + + Returns: + None + + """ + check_type(mem, "mem", Variable, "fluid.layers.StaticRNN.update_memory") + check_type(var, "var", Variable, "fluid.layers.StaticRNN.update_memory") + self.memories[mem.name].mem = var + + def _parent_block(self): + prog = self.helper.main_program + parent_idx = prog.current_block().parent_idx + assert parent_idx >= 0 + parent_block = prog.block(parent_idx) + return parent_block + + def __call__(self, *args, **kwargs): + if self.status != StaticRNN.AFTER_RNN_BLOCK: + raise ValueError("RNN output can only be retrieved after rnn block") + if len(self.outputs) == 0: + raise ValueError("RNN has no output") + elif len(self.outputs) == 1: + return self.outputs[0] + else: + return self.outputs + + def _complete_op(self): + main_program = self.helper.main_program + rnn_block = main_program.current_block() + parent_block = self._parent_block() + + local_inputs = set() + + for op in rnn_block.ops: + assert isinstance(op, Operator) + for oname in op.output_names: + for out_var_name in op.output(oname): + local_inputs.add(out_var_name) + + for var in self.inputs: + local_inputs.add(var.name) + for m in self.memories: + local_inputs.add(m) + + # NOTE(zcd): the params have two categories of variables. + # - the variables that are the out of StaticRnn. + # - the variables that are the parameters of some layers, for example, conv2d. + params = list() + for op in rnn_block.ops: + assert isinstance(op, Operator) + for iname in op.input_names: + for in_var_name in op.input(iname): + if in_var_name not in local_inputs: + params.append(in_var_name) + + parameters = [ + parent_block._find_var_recursive(name) for name in set(params) + ] + + step_scope = parent_block.create_var( + type=core.VarDesc.VarType.STEP_SCOPES + ) + + inlinks = [parent_block.var(i.name) for i in self.inputs] + outlinks = self.outputs + + # NOTE(zcd): the states maybe empty in some case. + boot_memories = [] + pre_memories = [] + memories = [] + for _, mem in six.iteritems(self.memories): + boot_memories.append(mem.init) + pre_memories.append(mem.pre_mem.name) + assert ( + mem.mem is not None + ), "%s should be updated in every step." % (mem.init.name) + mem_var = rnn_block.var(mem.mem.name) + assert isinstance(mem_var, Variable) + new_mem = self.helper.create_variable_for_type_inference( + dtype=mem_var.dtype + ) + rnn_block.append_op( + type='rnn_memory_helper', + inputs={'X': [mem_var]}, + outputs={'Out': [new_mem]}, + attrs={'dtype': mem_var.dtype}, + ) + + memories.append(new_mem.name) + + parent_block.append_op( + type='recurrent', + inputs={ + 'inputs': inlinks, + 'initial_states': boot_memories, + 'parameters': parameters, + }, + outputs={'outputs': outlinks, 'step_scopes': [step_scope]}, + attrs={ + 'has_states': len(pre_memories) > 0, + 'ex_states': pre_memories, + 'states': memories, + 'sub_block': rnn_block, + }, + ) + + +class WhileGuard(BlockGuard): + def __init__(self, while_op): + if not isinstance(while_op, While): + raise TypeError("WhileGuard takes a while op") + super(WhileGuard, self).__init__(while_op.helper.main_program) + self.while_op = while_op + + def __enter__(self): + self.while_op.status = While.IN_WHILE_BLOCK + return super(WhileGuard, self).__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is not None: + return False + self.while_op.status = While.AFTER_WHILE_BLOCK + self.while_op._complete() + return super(WhileGuard, self).__exit__(exc_type, exc_val, exc_tb) + + +def get_inputs_outputs_in_block( + current_block, inner_inputs, inner_outputs, helper +): + """ + Find inputs and outputs in current control flow block. + :param current_block: Current control flow block. + :param inner_inputs: Input var name of ops in current block. + :param inner_outputs: Output var name of ops in current block. + :return: inner_inputs, inner_outputs + """ + + def is_ignore_vars(op, var_name): + # NOTE(dev): There are some persistable var created in some non-standard API + # such as "contrib.layers.shuffle_batch". It create a "Seed" used both in + # Input and Output. This var shall not be considered as a loop_var in + # control_flow. + IGNORE_VAR_NAMES = {"shuffle_batch": ["shuffle_batch_seed"]} + if op.type in IGNORE_VAR_NAMES: + var_names = IGNORE_VAR_NAMES[op.type] + for name in var_names: + if name in var_name: + return True + return False + + # Step1: update inner_inputs and inner_outputs + # NOTE: Here assumes that all variables are input or output of Ops, + # but some variables are created without appendding a real op. + # For example, in `arr = create_array(dtype)`, `arr` is not a output of a op. + for op in current_block.ops: + assert isinstance(op, Operator) + for iname in op.input_names: + for in_var_name in op.input(iname): + if in_var_name not in inner_outputs and not is_ignore_vars( + op, in_var_name + ): + inner_inputs.add(in_var_name) + + for oname in op.output_names: + for out_var_name in op.output(oname): + inner_outputs.add(out_var_name) + + # Step2: Remove LOD_TENSOR_ARRAY created in current control flow block. + remove_inner_inputs = set() + parent_block = helper.main_program.block(current_block.parent_idx) + + for in_var_name in inner_inputs: + parent_block_var = parent_block._find_var_recursive(in_var_name) + current_block_var = None + if current_block.has_var(in_var_name): + current_block_var = current_block.var(in_var_name) + if ( + not parent_block_var + and current_block_var + and current_block_var.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + remove_inner_inputs.add(in_var_name) + + inner_inputs = inner_inputs - remove_inner_inputs + + return inner_inputs, inner_outputs + + +class While(object): + """ + :api_attr: Static Graph + + while loop control flow. Repeat while body until cond is False. + + Note: + A new OP :ref:`api_fluid_layers_while_loop` is highly recommended instead of ``While`` if the shape of parameter ``cond`` is [1]. + OP :ref:`api_fluid_layers_while_loop` is easier to use and is called with less code but does the same thing as ``While`` . + + Notice: + Local variables created in ``While`` are similar to that created in while of C++, and cannot be referenced externally. + As a result, they cannot be obtained through ``fetch_list`` of ``Executor``. If you would like to access the variable + out of ``while`` , PaddlePaddle provides ``assign`` API to assign local variables to external. Please refer to example + code 2 or refer to `issue#22724 `_. + + Args: + cond(Variable): A Tensor whose data type is bool controlling whether to continue looping. + is_test(bool, optional): A flag indicating whether execution is in test phase. Default value is False. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Examples 1: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0) # loop counter + + loop_len = fluid.layers.fill_constant(shape=[1],dtype='int64', value=10) # loop length + + cond = fluid.layers.less_than(x=i, y=loop_len) + while_op = fluid.layers.While(cond=cond) + with while_op.block(): + i = fluid.layers.increment(x=i, value=1, in_place=True) + fluid.layers.less_than(x=i, y=loop_len, cond=cond) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + res = exe.run(fluid.default_main_program(), feed={}, fetch_list=[i]) + print(res) # [array([10])] + + + Examples 2: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0) + loop_len = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10) + one = fluid.layers.fill_constant(shape=[1], dtype='float32', value=1) + data = fluid.data(name='data', shape=[1], dtype='float32') + sums = fluid.layers.fill_constant(shape=[1], dtype='float32', value=0) # Define the variable to be obtained ouside of While, which name should be different from the variable inside the While to be obtained + + cond = fluid.layers.less_than(x=i, y=loop_len) + while_op = fluid.layers.While(cond=cond) + with while_op.block(): + sums_tensor = fluid.layers.elementwise_add(x=data, y=data) + fluid.layers.assign(sums_tensor, sums) # Update the value of sums_tensor defined in While to the sums which defined outside of While through layers.assign + i = fluid.layers.increment(x=i, value=1, in_place=True) + data = fluid.layers.elementwise_add(x=data, y=one) + fluid.layers.less_than(x=i, y=loop_len, cond=cond) + + feed_data = np.ones(1).astype('float32') + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + res = exe.run(fluid.default_main_program(), feed={'data': feed_data}, fetch_list=sums) + print(res[0]) # [2.] # Because the data in While does not update the value outside the While, the value of sums is [2.] after the loop + """ + + BEFORE_WHILE_BLOCK = 0 + IN_WHILE_BLOCK = 1 + AFTER_WHILE_BLOCK = 2 + + def __init__(self, cond, is_test=False, name=None): + self.helper = LayerHelper("while", name=name) + self.status = While.BEFORE_WHILE_BLOCK + check_variable_and_dtype(cond, 'cond', ['bool'], 'fluid.layers.While') + if reduce(lambda a, b: a * b, cond.shape, 1) != 1: + raise TypeError( + "condition expected shape as [1], but given shape as {0}.".format( + list(cond.shape) + ) + ) + self.cond_var = cond + self.is_test = is_test + + def block(self): + return WhileGuard(self) + + def _complete(self): + main_program = self.helper.main_program + while_block = main_program.current_block() + parent_block = main_program.block( + main_program.current_block().parent_idx + ) + + inner_outputs = {self.cond_var.name} + x_name_list = set() + x_name_list, inner_outputs = get_inputs_outputs_in_block( + while_block, x_name_list, inner_outputs, self.helper + ) + + out_vars = [] + for inner_out_name in inner_outputs: + inner_var = parent_block._find_var_recursive(inner_out_name) + if inner_var: + out_vars.append(inner_var) + + x_name_list |= set(map(lambda x: x.name, out_vars)) + # NOTE(dev): cond_var has been contained in Input('Condition'), so + # we remove it from Input('X') + x_name_list -= {self.cond_var.name} + + step_scope = parent_block.create_var( + type=core.VarDesc.VarType.STEP_SCOPES + ) + + parent_block.append_op( + type='while', + inputs={ + 'X': [ + parent_block._var_recursive(x_name) + for x_name in x_name_list + ], + 'Condition': [self.cond_var], + }, + outputs={'Out': out_vars, 'StepScopes': [step_scope]}, + attrs={'sub_block': while_block, "is_test": self.is_test}, + ) + + +support_ret_buildin_type = (bool, float, six.integer_types) + + +def assign_skip_lod_tensor_array(input, output): + """ + Assign input to output, but skip the process of copying LoDTensorArray unless it's created in while_block. + """ + + def has_shape_diff(x_var, y_var): + if len(x_var.shape) != len(y_var.shape): + return True + for x_dim, y_dim in zip(x_var.shape, y_var.shape): + if x_dim != y_dim and -1 not in [x_dim, y_dim]: + return True + return False + + if not isinstance(input, (Variable, core.VarBase)): + if isinstance(output, Variable) and isinstance( + input, support_ret_buildin_type + ): + assign(input, output) + else: + output = input + return + + if input.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + main_program = input.block.program + parent_block = main_program.block( + main_program.current_block().parent_idx + ) + if parent_block and not parent_block._find_var_recursive(input.name): + assign(input, output) + else: + if ( + isinstance(output, Variable) + and isinstance(input, Variable) + and has_shape_diff(input, output) + ): + warnings.warn( + "In dy2static mode, we attemp to assign a variable with shape {} into a variable with shape{}, which is not always right.".format( + input.shape, output.shape + ) + ) + assign(input, output) + + +def while_loop(cond, body, loop_vars, is_test=False, name=None): + """ + :api_attr: Static Graph + + while_loop is one of the control flows. Repeats while_loop `body` until `cond` returns False. + + Notice: + Local variables defined in ``body`` cannot be obtained through ``fetch_list`` of ``Executor`` , variables should + be defined outside ``body`` and placed in ``loop_vars`` for looping, then these variables can be fetched by ``fetch_list`` . + + Args: + cond(Callable): A callable returning a boolean tensor controlling whether to continue looping. And ``cond`` takes + as many arguments as ``loop_vars`` . + body(Callable): A callable returning a tuple or list of tensors or LoDTensorArrays of the same arity + (length and structure) and types as ``loops_vars`` . And ``body`` takes as many arguments as ``loop_vars`` . + loop_vars(list|tuple): A list or tuple of tensors or LoDTensorArrays that is passed to both ``cond`` and ``body`` . + is_test(bool, optional): A flag indicating whether execution is in test phase. Default value is False. + name(str, optional): Normally there is no need for users to set this property. For more information, please + refer to :ref:`api_guide_Name`. Default is None. + + Returns: + A list or tuple of Tensors or LoDTensorArrays which returned by ``body`` . + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + def cond(i, ten): + return i < ten + + def body(i, ten): + i = i + 1 + return [i, ten] + + main_program = paddle.static.default_main_program() + startup_program = paddle.static.default_startup_program() + with paddle.static.program_guard(main_program, startup_program): + i = paddle.full(shape=[1], fill_value=0, dtype='int64') # loop counter + ten = paddle.full(shape=[1], fill_value=10, dtype='int64') # loop length + i, ten = paddle.static.nn.while_loop(cond, body, [i, ten]) + + exe = paddle.static.Executor(paddle.CPUPlace()) + res = exe.run(main_program, feed={}, fetch_list=[i]) + print(res) # [array([10])] + """ + helper = LayerHelper('while_loop', **locals()) + + if not callable(cond): + raise TypeError("cond in while_loop should be callable") + if not callable(body): + raise TypeError("body in while_loop should be callable") + check_type(loop_vars, 'loop_vars', (list, tuple), 'fluid.layers.while_loop') + if len(loop_vars) == 0: + raise ValueError("loop_vars in while_loop should not be empty") + + pre_cond = cond(*loop_vars) + check_variable_and_dtype( + pre_cond, 'var of cond returned', ['bool'], 'fluid.layers.while_loop' + ) + if reduce(lambda a, b: a * b, pre_cond.shape, 1) != 1: + raise TypeError( + "the shape of the variable returned by cond should be [1]," + "but given shape as {0}.".format(list(pre_cond.shape)) + ) + + if _non_static_mode(): + now_cond = pre_cond.numpy()[0] + while now_cond: + output_vars = body(*loop_vars) + if not isinstance(output_vars, (list, tuple)): + output_vars = [output_vars] + if len(output_vars) != len(loop_vars): + raise ValueError( + "body in while_loop should return the same arity " + "(length and structure) and types as loop_vars" + ) + now_cond = cond(*output_vars).numpy()[0] + map_structure(assign_skip_lod_tensor_array, output_vars, loop_vars) + return loop_vars + + while_loop_block = While(pre_cond, is_test, name) + has_mutable_vars_in_loop = hold_mutable_vars(loop_vars) + with while_loop_block.block(): + # If a variable with mutable type is included in loop_vars, like `dict/list`, + # modifying it in the body function will cause origin variable to be modified + # synchronously. This will raise an assignment error out of while block. + # Here we make a copy of the mutable vars to avoid this problem. + if has_mutable_vars_in_loop: + new_loop_vars = copy_mutable_vars(loop_vars) + output_vars = body(*new_loop_vars) + else: + output_vars = body(*loop_vars) + if not isinstance(output_vars, (list, tuple)): + output_vars = [output_vars] + try: + loop_vars = _deal_with_undefined_var(output_vars, loop_vars) + assert_same_structure(output_vars, loop_vars, check_types=False) + except ValueError as e: + raise ValueError( + "body in while_loop should return the same arity " + "(length and structure) as loop_vars: {0}".format(e) + ) + now_cond = cond(*output_vars) + map_structure(assign_skip_lod_tensor_array, output_vars, loop_vars) + assign(now_cond, pre_cond) + return loop_vars + + +def _deal_with_undefined_var(output_vars, loop_vars): + """Deal with undefined var cases, We create undefined variable based on the results of body(). + In Dy2Static, we use undefined var to represent the var created in control flow. This function + expand the loop_vars and replace original loop_vars. + 1. UndefinedVar = Variable # create a variable + 2. UndefinedVar = None # create a undefined var with RETURN_NO_VALUE_MAGIC_NUM + 3. UndefinedVar = List(int) # create a list of variable + 4. UndefinedVar = value # create a variable + """ + from paddle.fluid.dygraph.dygraph_to_static.utils import ( + UndefinedVar, + create_undefined_variable, + ) + + def create_var_like(o_var): + if ( + isinstance(o_var, (Variable,) + support_ret_buildin_type) + or o_var is None + ): + return create_undefined_variable() + if is_sequence(o_var): + """ + Create a complex container class inside the body of while, including Python list and python Dict + """ + return map_structure(lambda x: create_undefined_variable(), o_var) + + if len(output_vars) != len(loop_vars): + raise ValueError("The length of loop_vars should be the same.") + + results = [] + for o_var, l_var in zip(output_vars, loop_vars): + if isinstance(l_var, UndefinedVar) or l_var is None: + results.append(create_var_like(o_var)) + else: + results.append(l_var) + return results + + +def lod_rank_table(x, level=0): + """ + LoD Rank Table Operator. Given an input variable **x** and a level number + of LoD, this layer creates a LodRankTable object. A LoDRankTable object + contains a list of bi-element tuples. Each tuple consists of an index and + a length, both of which are int type. Refering to specified level of LoD, + the index is the sequence index number and the length represents the + sequence length. Please note that the list is ranked in descending order by + the length. The following is an example: + + .. code-block:: text + + x is a LoDTensor: + x.lod = [[2, 1], + [5, 1, 1]] + x.data = [a, b, c, d, e, f, g] + + 1. set level to 0: + Create lod rank table: + lod_rank_table_obj = lod_rank_table(x, level=0) + + Get: + lod_rank_table_obj.items() = [(0, 2), (1, 1)] + + 2. set level to 1: + Create lod rank table: + lod_rank_table_obj = lod_rank_table(x, level=1) + + Get: + lod_rank_table_obj.items() = [(0, 5), (1, 1), (2, 1)] + + Args: + x (Variable): Input variable, a LoDTensor based which to create the lod + rank table. + level (int): Specify the LoD level, on which to create the lod rank + table. + + Returns: + Variable: The created LoDRankTable object. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[10], + dtype='float32', lod_level=1) + out = layers.lod_rank_table(x=x, level=0) + """ + check_type(x, 'x', (Variable, list), 'lod_rank_table') + if isinstance(x, (list)): + for i, input_x in enumerate(x): + check_type( + input_x, 'input[' + str(i) + ']', Variable, 'lod_rank_table' + ) + + helper = LayerHelper("lod_rank_table", **locals()) + table = helper.create_variable( + type=core.VarDesc.VarType.LOD_RANK_TABLE, + name=unique_name.generate("lod_rank_table"), + ) + helper.append_op( + type='lod_rank_table', + inputs={'X': x}, + outputs={'Out': table}, + attrs={'level': level}, + ) + return table + + +@templatedoc() +def max_sequence_len(rank_table): + """ + ${comment} + + >>> import paddle.fluid as fluid + >>> x = fluid.layers.data(name='x', shape=[10], dtype='float32', + >>> lod_level=1) + >>> rank_table = layers.lod_rank_table(x=x, level=0) + >>> max_seq_len = layers.max_sequence_len(rank_table) + + Args: + rank_table(${rank_table_type}): ${rank_table_comment}. + + Returns: + ${out_comment}. + """ + helper = LayerHelper("max_seqence_len", **locals()) + res = helper.create_variable_for_type_inference(dtype="int64") + helper.append_op( + type="max_sequence_len", + inputs={"RankTable": rank_table}, + outputs={"Out": res}, + ) + return res + + +def lod_tensor_to_array(x, table): + """ + Convert a LoDTensor to a LoDTensorArray. + + This function split a LoDTesnor to a LoDTensorArray according to its LoD + information. LoDTensorArray is an alias of C++ std::vector in + PaddlePaddle. The generated LoDTensorArray of this function can be further read + or written by `read_from_array()` and `write_to_array()` operators. However, + this function is generally an internal component of PaddlePaddle `DynamicRNN`. + Users should not use it directly. + + Args: + x (Variable|list): The LoDTensor to be converted to a LoDTensorArray. + table (ParamAttr|list): The variable that stores the level of lod + which is ordered by sequence length in + descending order. It is generally generated + by `layers.lod_rank_table()` API. + + Returns: + Variable: The LoDTensorArray that has been converted from the input tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[10]) + table = fluid.layers.lod_rank_table(x, level=0) + array = fluid.layers.lod_tensor_to_array(x, table) + """ + check_type(x, 'x', (Variable, list), 'lod_tensor_to_array') + if isinstance(x, (list)): + for i, input_x in enumerate(x): + check_type( + input_x, + 'input[' + str(i) + ']', + Variable, + 'lod_tensor_to_array', + ) + check_type(table, 'table', (Variable, list), 'lod_tensor_to_array') + if isinstance(table, (list)): + for i, table_x in enumerate(table): + check_type( + table_x, + 'table[' + str(i) + ']', + Variable, + 'lod_tensor_to_array', + ) + helper = LayerHelper("lod_tensor_to_array", **locals()) + array = helper.create_variable( + name=unique_name.generate("lod_tensor_to_array"), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=x.dtype, + ) + helper.append_op( + type='lod_tensor_to_array', + inputs={'X': x, 'RankTable': table}, + outputs={'Out': array}, + ) + return array + + +def array_to_lod_tensor(x, table): + """Convert a LoD_Tensor_Aarry to an LoDTensor. + + Args: + x (Variable|list): The lod tensor array to be converted to a tensor. + table (ParamAttr|list): The variable that stores the level of lod + which is ordered by sequence length in + descending order. + + Returns: + Variable: The variable of type tensor that has been converted + from an array. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[10]) + table = fluid.layers.lod_rank_table(x, level=0) + array = fluid.layers.lod_tensor_to_array(x, table) + lod_tensor = fluid.layers.array_to_lod_tensor(array, table) + """ + check_type(x, 'x', (Variable, list), 'array_to_lod_tensor') + if isinstance(x, (list)): + for i, input_x in enumerate(x): + check_type( + input_x, + 'input[' + str(i) + ']', + Variable, + 'array_to_lod_tensor', + ) + check_type(table, 'table', (Variable, list), 'array_to_lod_tensor') + if isinstance(table, (list)): + for i, table_x in enumerate(table): + check_type( + table_x, + 'table[' + str(i) + ']', + Variable, + 'array_to_lod_tensor', + ) + + helper = LayerHelper("array_to_lod_tensor", **locals()) + tmp = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="array_to_lod_tensor", + inputs={'X': x, 'RankTable': table}, + outputs={'Out': tmp}, + ) + return tmp + + +def increment(x, value=1.0, in_place=True): + """ + The OP is usually used for control flow to increment the data of :attr:`x` by an amount :attr:`value`. + Notice that the number of elements in :attr:`x` must be equal to 1. + + Parameters: + x (Variable): A tensor that must always contain only one element, its data type supports + float32, float64, int32 and int64. + value (float, optional): The amount to increment the data of :attr:`x`. Default: 1.0. + in_place (bool, optional): Whether the OP should be performed in-place. Default: True. + + Returns: + Variable: The elementwise-incremented tensor with the same shape and data type as :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + counter = fluid.layers.zeros(shape=[1], dtype='float32') # [0.] + fluid.layers.increment(counter) # [1.] + """ + if in_dygraph_mode(): + return _C_ops.increment_(x, value) + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'increment' + ) + helper = LayerHelper("increment", **locals()) + if not in_place: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + out = x + helper.append_op( + type='increment', + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={'step': float(value)}, + ) + return out + + +def array_write(x, i, array=None): + """ + This OP writes the input ``x`` into the i-th position of the ``array`` + :ref:`api_fluid_LoDTensorArray` and returns the modified array. + If ``array`` is none, a new LoDTensorArray will be created and returned. + This OP is often used together with :ref:`api_fluid_layers_array_read` OP. + + Args: + x (Variable): The input data to be written into array. It's multi-dimensional + Tensor or LoDTensor. Data type: float32, float64, int32, int64. + i (Variable): 1-D Tensor with shape [1], which represents the position into which + ``x`` is written. Data type: int64. + array (LoDTensorArray, optional): The LoDTensorArray into which ``x`` is written. + The default value is None, when a new LoDTensorArray will be created and returned + as a result. + + Returns: + Variable: The input ``array`` after ``x`` is written into. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + tmp = fluid.layers.fill_constant(shape=[3, 2], dtype='int64', value=5) + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10) + # Write tmp into the position of arr with subscript 10 and return arr. + arr = fluid.layers.array_write(tmp, i=i) + + # Now, arr is a LoDTensorArray with length 11. We can use array_read OP to read + # the data at subscript 10 and print it out. + item = fluid.layers.array_read(arr, i=i) + input = fluid.layers.Print(item, message="The content of i-th LoDTensor:") + main_program = fluid.default_main_program() + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(main_program) + + # The printed result is: + # 1570533133 The content of i-th LoDTensor: The place is:CPUPlace + # Tensor[array_read_0.tmp_0] + # shape: [3,2,] + # dtype: l + # data: 5,5,5,5,5,5, + + # the output is 2-D Tensor with shape [3,2], which is tmp above. + # dtype is the corresponding C++ data type, which may vary in different environments. + # Eg: if the data type of tensor is int64, then the corresponding C++ data type is int64_t, + # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, + # and '__int64' on Windows. They both represent 64-bit integer variables. + + """ + if _non_static_mode(): + assert isinstance( + x, Variable + ), "The input data 'x' in array_write must be Variable in dygraph mode" + assert isinstance( + i, Variable + ), "The index 'i' in array_write must be Variable in dygraph mode" + assert i.shape == [ + 1 + ], "The shape of index 'i' should be [1] in dygraph mode" + i = i.numpy().item(0) + if array is None: + array = create_array(x.dtype) + assert isinstance( + array, list + ), "The 'array' in array_write must be a list in dygraph mode" + assert i <= len( + array + ), "The index 'i' should not be greater than the length of 'array' in dygraph mode" + if i < len(array): + array[i] = x + else: + array.append(x) + return array + + check_variable_and_dtype(i, 'i', ['int64'], 'array_write') + check_type(x, 'x', (Variable), 'array_write') + helper = LayerHelper('array_write', **locals()) + if array is not None: + if ( + not isinstance(array, Variable) + or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + raise TypeError( + "array should be tensor array vairable in array_write Op" + ) + if array is None: + array = helper.create_variable( + name="{0}.out".format(helper.name), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=x.dtype, + ) + helper.append_op( + type='write_to_array', + inputs={'X': [x], 'I': [i]}, + outputs={'Out': [array]}, + ) + return array + + +def create_array(dtype, initialized_list=None): + """ + This OP creates an LOD_TENSOR_ARRAY. It is used as + the input of :ref:`api_fluid_layers_array_read` and + :ref:`api_fluid_layers_array_write`. Also it can be used + with :ref:`api_fluid_layers_While` to create RNN network. + + Args: + dtype (str): The data type of the elements in the lod_tensor_array. + Support data type: float32, float64, int32, int64. + initialized_list(list): Used to initialize as default value for created array. + All values in initialized list should be a Tensor. + + Returns: + Variable: The empty lod_tensor_array. The data type of elements in Tensor is ``dtype``. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.create_array(dtype='float32') # Create a float32 LoDTensorArray. + + """ + array = [] + if initialized_list is not None: + if not isinstance(initialized_list, (list, tuple)): + raise TypeError( + "Require type(initialized_list) should be list/tuple, but received {}".format( + type(initialized_list) + ) + ) + array = list(initialized_list) + + # NOTE: Only support plain list like [x, y,...], not support nested list in static mode. + for val in array: + if not isinstance(val, Variable): + raise TypeError( + "All values in `initialized_list` should be Variable, but recevied {}.".format( + type(val) + ) + ) + + if _non_static_mode(): + return array + + helper = LayerHelper("array", **locals()) + tensor_array = helper.create_variable( + name="{0}.out".format(helper.name), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=dtype, + ) + + for val in array: + array_write(x=val, i=array_length(tensor_array), array=tensor_array) + + return tensor_array + + +@templatedoc() +def less_than(x, y, force_cpu=None, cond=None, name=None): + """ + + ${comment} + + Args: + x(Tensor): ${x_comment}. + y(Tensor): ${y_comment}. + force_cpu(${force_cpu_type}): ${force_cpu_comment}. + cond(Tensor, optional): Optional output which can be any created Tensor + that meets the requirements to store the result of *less_than*. + if cond is None, a new Tensor will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + Returns: + ${out_comment}. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3, 4], dtype='float32') + y = paddle.to_tensor([2, 2, 1, 3], dtype='float32') + result = paddle.less_than(x, y) + print(result) # [True, False, False, False] + + """ + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "less_than" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "less_than" + ) + if cond is not None: + check_type(cond, "cond", Variable, "less_than") + if force_cpu != None: + check_type(force_cpu, "force_cpu", bool, "less_than") + + helper = LayerHelper("less_than", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + attrs = dict() + if force_cpu is not None: + attrs['force_cpu'] = force_cpu + + helper.append_op( + type='less_than', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [cond]}, + attrs=attrs, + ) + return cond + + +@templatedoc() +def less_equal(x, y, cond=None, name=None): + """ + :alias_main: paddle.less_equal + :alias: paddle.less_equal,paddle.tensor.less_equal,paddle.tensor.logic.less_equal + :old_api: paddle.fluid.layers.less_equal + + This OP returns the truth value of :math:`x <= y` elementwise, which is equivalent function to the overloaded operator `<=`. + + Args: + x(Variable): First input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + y(Variable): Second input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + cond(Variable, optional): Optional output which can be any created Variable that meets the requirements to store the result of *less_equal*. + if cond is None, a new Varibale will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable, the output data type is bool: The tensor variable storing the output, the output shape is same as input :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + label = fluid.layers.assign(np.array([1, 3], dtype='int32')) + limit = fluid.layers.assign(np.array([1, 2], dtype='int32')) + out = fluid.layers.less_equal(x=label, y=limit) #out=[True, False] + out1 = label<= limit #out1=[True, False] + + """ + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "less_equal" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "less_equal" + ) + if cond is not None: + check_type(cond, "cond", Variable, "less_equal") + + helper = LayerHelper("less_equal", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + attrs = dict() + + helper.append_op( + type='less_equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [cond]}, + attrs=attrs, + ) + return cond + + +@templatedoc() +def greater_than(x, y, cond=None, name=None): + """ + :alias_main: paddle.greater_than + :alias: paddle.greater_than,paddle.tensor.greater_than,paddle.tensor.logic.greater_than + :old_api: paddle.fluid.layers.greater_than + + This OP returns the truth value of :math:`x > y` elementwise, which is equivalent function to the overloaded operator `>`. + + Args: + x(Variable): First input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + y(Variable): Second input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + cond(Variable, optional): Optional output which can be any created Variable that meets the requirements to store the result of *greater_than*. + if cond is None, a new Varibale will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable, the output data type is bool: The tensor variable storing the output, the output shape is same as input :attr:`x` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + label = fluid.layers.assign(np.array([2, 3], dtype='int32')) + limit = fluid.layers.assign(np.array([3, 2], dtype='int32')) + out = fluid.layers.greater_than(x=label, y=limit) #out=[False, True] + out1 = label > limit #out1=[False, True] + """ + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "greater_than" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "greater_than" + ) + if cond is not None: + check_type(cond, "cond", Variable, "greater_than") + + helper = LayerHelper("greater_than", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + attrs = dict() + + if in_dygraph_mode(): + return _C_ops.greater_than(x, y, -1) + else: + helper.append_op( + type='greater_than', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [cond]}, + attrs=attrs, + ) + return cond + + +@templatedoc() +def greater_equal(x, y, cond=None, name=None): + """ + :alias_main: paddle.greater_equal + :alias: paddle.greater_equal,paddle.tensor.greater_equal,paddle.tensor.logic.greater_equal + :old_api: paddle.fluid.layers.greater_equal + + This OP returns the truth value of :math:`x >= y` elementwise, which is equivalent function to the overloaded operator `>=`. + + Args: + x(Variable): First input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + y(Variable): Second input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + cond(Variable, optional): Optional output which can be any created Variable that meets the requirements to store the result of *greater_equal*. + if cond is None, a new Varibale will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable, the output data type is bool: The tensor variable storing the output, the output shape is same as input :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + label = fluid.layers.assign(np.array([2, 2], dtype='int32')) + limit = fluid.layers.assign(np.array([2, 3], dtype='int32')) + out = fluid.layers.greater_equal(x=label, y=limit) #out=[True, False] + out_1 = label >= limit #out1=[True, False] + + """ + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "greater_equal" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "greater_equal" + ) + if cond is not None: + check_type(cond, "cond", Variable, "greater_equal") + + helper = LayerHelper("greater_equal", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + attrs = dict() + + helper.append_op( + type='greater_equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [cond]}, + attrs=attrs, + ) + return cond + + +def equal(x, y, cond=None, name=None): + """ + This layer returns the truth value of :math:`x == y` elementwise. + + Args: + x(Variable): Tensor, data type is float32, float64, int32, int64. + y(Variable): Tensor, data type is float32, float64, int32, int64. + cond(Variable, optional): Optional output which can be any created + Variable that meets the requirements to store the result of *equal*. + if cond is None, a new Varibale will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable: output Tensor, it's shape is the same as the input's Tensor, + and the data type is bool. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + out_cond =fluid.data(name="input1", shape=[2], dtype='bool') + label = fluid.layers.assign(np.array([3, 3], dtype="int32")) + limit = fluid.layers.assign(np.array([3, 2], dtype="int32")) + label_cond = fluid.layers.assign(np.array([1, 2], dtype="int32")) + out1 = fluid.layers.equal(x=label,y=limit) #out1=[True, False] + out2 = fluid.layers.equal(x=label_cond,y=limit, cond=out_cond) #out2=[False, True] out_cond=[False, True] + """ + if in_dygraph_mode(): + default_axis = -1 + return _C_ops.equal(x, y, default_axis) + + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "equal" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "equal" + ) + if cond is not None: + check_type(cond, "cond", Variable, "equal") + + helper = LayerHelper("equal", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + helper.append_op( + type='equal', inputs={'X': [x], 'Y': [y]}, outputs={'Out': [cond]} + ) + return cond + + +def not_equal(x, y, cond=None, name=None): + """ + :alias_main: paddle.not_equal + :alias: paddle.not_equal,paddle.tensor.not_equal,paddle.tensor.logic.not_equal + :old_api: paddle.fluid.layers.not_equal + + This OP returns the truth value of :math:`x != y` elementwise, which is equivalent function to the overloaded operator `!=`. + + Args: + x(Variable): First input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + y(Variable): Second input to compare which is N-D tensor. The input data type should be float32, float64, int32, int64. + cond(Variable, optional): Optional output which can be any created Variable that meets the requirements to store the result of *not_equal*. + if cond is None, a new Varibale will be created to store the result. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable, the output data type is bool: The tensor variable storing the output, the output shape is same as input :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + label = fluid.layers.data(name='label', shape=[1], dtype='int64') + limit = fluid.layers.fill_constant(shape=[1], value=1, dtype='int64') + out = fluid.layers.not_equal(x=label, y=limit) + """ + check_variable_and_dtype( + x, "x", ["float32", "float64", "int32", "int64"], "not_equal" + ) + check_variable_and_dtype( + y, "y", ["float32", "float64", "int32", "int64"], "not_equal" + ) + if cond is not None: + check_type(cond, "cond", Variable, "not_equal") + + helper = LayerHelper("not_equal", **locals()) + if cond is None: + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + helper.append_op( + type='not_equal', inputs={'X': [x], 'Y': [y]}, outputs={'Out': [cond]} + ) + return cond + + +def array_read(array, i): + """ + This OP is used to read data at the specified position from the input array + :ref:`api_fluid_LoDTensorArray` . ``array`` is the input array and ``i`` + is the specified read position. This OP is often used together with + :ref:`api_fluid_layers_array_write` OP. + + Case 1: + :: + Input: + The shape of first three tensors are [1], and that of the last one is [1,2]: + array = ([0.6], [0.1], [0.3], [0.4, 0.2]) + And: + i = [3] + + Output: + output = [0.4, 0.2] + + Args: + array (LoDTensorArray): The input LoDTensorArray. + i (Variable): 1-D Tensor, whose shape is [1] and dtype is int64. It represents the + specified read position of ``array``. + + Returns: + Variable: The LoDTensor or Tensor that is read at the specified position of ``array``. + + Examples: + .. code-block:: python + + # First we're going to create a LoDTensorArray, then we're going to write the Tensor into + # the specified position, and finally we're going to read the Tensor at that position. + import paddle.fluid as fluid + arr = fluid.layers.create_array(dtype='float32') + tmp = fluid.layers.fill_constant(shape=[3, 2], dtype='int64', value=5) + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10) + # tmp is the Tensor with shape [3,2], and if we write it into the position with subscript 10 + # of the empty-array: arr, then the length of arr becomes 11. + arr = fluid.layers.array_write(tmp, i, array=arr) + # Read the data of the position with subscript 10. + item = fluid.layers.array_read(arr, i) + + # You can print out the data via executor. + input = fluid.layers.Print(item, message="The LoDTensor of the i-th position:") + main_program = fluid.default_main_program() + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(main_program) + + # The printed result is: + + # 1569588169 The LoDTensor of the i-th position: The place is:CPUPlace + # Tensor[array_read_0.tmp_0] + # shape: [3,2,] + # dtype: l + # data: 5,5,5,5,5,5, + + # the output is 2-D Tensor with shape [3,2]. + # dtype is the corresponding C++ data type, which may vary in different environments. + # Eg: if the data type of tensor is int64, then the corresponding C++ data type is int64_t, + # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, + # and '__int64' on Windows. They both represent 64-bit integer variables. + """ + if _non_static_mode(): + assert isinstance( + array, list + ), "The 'array' in array_read must be list in dygraph mode" + assert isinstance( + i, Variable + ), "The index 'i' in array_read must be Variable in dygraph mode" + assert i.shape == [ + 1 + ], "The shape of index 'i' should be [1] in dygraph mode" + i = i.numpy().item(0) + return array[i] + + check_variable_and_dtype(i, 'i', ['int64'], 'array_read') + helper = LayerHelper('array_read', **locals()) + if ( + not isinstance(array, Variable) + or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + raise TypeError("array should be tensor array vairable") + out = helper.create_variable_for_type_inference(dtype=array.dtype) + helper.append_op( + type='read_from_array', + inputs={'X': [array], 'I': [i]}, + outputs={'Out': [out]}, + ) + return out + + +def shrink_memory(x, i, table): + """ + This function creates an operator to shrink rnn memory using the RankTable + as mentioned in the input parameter. + + NOTE: This API is very low-level API. It is used by DynamicRNN only. + + Since the Dynamic RNN uses no-padding way to implement RNN. The sequence + will be sorted by order, and the length of valid memory will be shrink after + each time step. + + Args: + x(Variable): The memory object in the previous time step. + i(Variable): The step count variable. A int scalar as LoDTensor. + table(Variable): The RNNRankTable object. + + Returns: + the memory variable after shrink. + + Examples: + + Since this API is very low level API. The example is not provided. + Please reference the implementation of class DynamicRNN for detail + usage. + """ + helper = LayerHelper('shrink_memory', **locals()) + check_type(x, 'x', Variable, 'shrink_memory') + check_type(i, 'i', Variable, 'shrink_memory') + check_type(table, 'table', Variable, 'shrink_memory') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='shrink_rnn_memory', + inputs={'X': [x], 'I': [i], 'RankTable': [table]}, + outputs={'Out': [out]}, + attrs={}, + ) + return out + + +def array_length(array): + """ + This OP is used to get the length of the input array :ref:`api_fluid_LoDTensorArray` . + It can be used together with :ref:`api_fluid_layers_array_read` , :ref:`api_fluid_layers_array_write` , + :ref:`api_fluid_layers_While` OP to traverse, read and write LoDTensorArray. + + Args: + array (LoDTensorArray): The input array that will be used to compute the length. + + Returns: + Variable: 1-D Tensor with shape [1], which is the length of array. Datatype: int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + tmp = fluid.layers.zeros(shape=[10], dtype='int32') + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10) + # tmp is 1-D Tensor with shape [10]. We write tmp into arr on subscript 10, + # then the length of arr becomes 11. + arr = fluid.layers.array_write(tmp, i=i) + # return the length of arr + arr_len = fluid.layers.array_length(arr) + + # You can use executor to print out the length of LoDTensorArray. + input = fluid.layers.Print(arr_len, message="The length of LoDTensorArray:") + main_program = fluid.default_main_program() + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(main_program) + + # The printed result is: + + # 1569576542 The length of LoDTensorArray: The place is:CPUPlace + # Tensor[array_length_0.tmp_0] + # shape: [1,] + # dtype: l + # data: 11, + + # 1-D Tensor with shape [1], whose value is 11. It means that the length of LoDTensorArray + # is 11. + # dtype is the corresponding C++ data type, which may vary in different environments. + # Eg: if the data type of tensor is int64, then the corresponding C++ data type is int64_t, + # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, + # and '__int64' on Windows. They both represent 64-bit integer variables. + """ + + if _non_static_mode(): + assert isinstance( + array, list + ), "The 'array' in array_write must be a list in dygraph mode" + return len(array) + + if ( + not isinstance(array, Variable) + or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + raise TypeError( + "array should be tensor array vairable in array_length Op" + ) + + helper = LayerHelper('array_length', **locals()) + tmp = helper.create_variable_for_type_inference(dtype='int64') + tmp.stop_gradient = True + helper.append_op( + type='lod_array_length', inputs={'X': [array]}, outputs={'Out': [tmp]} + ) + return tmp + + +class ConditionalBlockGuard(BlockGuard): + """ + ConditionalBlockGuard is derived from BlockGuard. It is dedicated for + holding a ConditionalBlock, and helping users entering and exiting the + ConditionalBlock via Python's 'with' keyword. However, ConditionalBlockGuard + is generally an internal component of IfElse, users should not use it directly. + """ + + def __init__(self, block): + check_type(block, "block", ConditionalBlock, "ConditionalBlockGuard") + super(ConditionalBlockGuard, self).__init__(block.helper.main_program) + self.block = block + + def __enter__(self): + return super(ConditionalBlockGuard, self).__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.block.complete() + return super(ConditionalBlockGuard, self).__exit__( + exc_type, exc_val, exc_tb + ) + + +class ConditionalBlock(object): + ''' + **ConditionalBlock** + + ConditionalBlock is an operator that bind a block to a specific condition, + if the condition matches, the corresponding block will be executed. + + Args: + inputs (Variable): bool conditions. + is_scalar_condition (bool): whether the branch is controlled by a scalar. + name(str): name of this ConditionalBlock. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + cond = layers.less_than(x=label, y=limit) + true_image, false_image = layers.split_lod_tensor( + input=image, mask=cond) + true_cond = layers.ConditionalBlock([true_image]) + + with true_cond.block(): + ... + with false_cond.block(): + ... + ''' + + def __init__(self, inputs, is_scalar_condition=False, name=None): + for each_input in inputs: + check_type(each_input, "input", Variable, "ConditionalBlock") + self.inputs = inputs + self.is_scalar_condition = is_scalar_condition + self.helper = LayerHelper('conditional_block', name=name) + + def block(self): + return ConditionalBlockGuard(self) + + def complete(self): + inside_block = self.helper.main_program.current_block() + parent_block = self.helper.main_program.block(inside_block.parent_idx) + + intermediate = set() + params = set() + params, intermediate = get_inputs_outputs_in_block( + inside_block, params, intermediate, helper=self.helper + ) + + # Todo(liym27) Here assume that all params are in recursive parent block + # but when minimize() called in control flow, some params may be in + # conditional grad block + param_list = [ + parent_block._var_recursive(each_name) for each_name in params + ] + + out_list = [] + for inner_out_name in intermediate: + inner_var = parent_block._find_var_recursive(inner_out_name) + if inner_var: + out_list.append(inner_var) + + step_scope = parent_block.create_var( + type=core.VarDesc.VarType.STEP_SCOPES + ) + conditional_block_op = parent_block.append_op( + type='conditional_block', + inputs={ + 'Cond': self.inputs, + 'Input': param_list, + }, + outputs={'Out': out_list, 'Scope': [step_scope]}, + attrs={ + 'sub_block': inside_block, + 'is_scalar_condition': self.is_scalar_condition, + }, + ) + + if self.need_append_conditional_block_grad(inside_block): + self.append_conditional_block_grad( + parent_block, inside_block, conditional_block_op + ) + + def need_append_conditional_block_grad(self, inside_block): + grad_sub_block_idx = inside_block.backward_block_idx + inside_block_idx = inside_block.idx + + # if inside_block have grad_block and grad_block is not itself, + # we will append conditional block grad. + return ( + grad_sub_block_idx != -1 and grad_sub_block_idx != inside_block_idx + ) + + def append_conditional_block_grad( + self, parent_block, inside_block, conditional_block_op + ): + ''' + Append op `conditional_block_grad` manually. + When `optimizer.minimize/append_backward` is called in Paddle control flow, + grad ops will be appended before appending op `conditional_block` so that + op `conditional_block_grad` can't be appended when calling + `optimizer.minimize/append_backward`. After appending op `conditional_block`, + `conditional_block_grad` is appended manually. + + Args: + parent_block (Block): The block that `conditional_block_op` blongs to. + inside_block (Block): The sub block of `conditional_block_op`. + conditional_block_op (Operator): The forward op conditional_block. + ''' + + grad_sub_block_idx = inside_block.backward_block_idx + grad_sub_block = self.helper.main_program.block(grad_sub_block_idx) + + intermediate = set() + params = set() + + for each_op in grad_sub_block.ops: + assert isinstance(each_op, Operator) + for iname in each_op.input_names: + for in_var_name in each_op.input(iname): + if in_var_name not in intermediate: + params.add(in_var_name) + + for oname in each_op.output_names: + for out_var_name in each_op.output(oname): + intermediate.add(out_var_name) + + param_list = [] + for inner_input_name in params: + inner_var = parent_block._find_var_recursive(inner_input_name) + if inner_var: + param_list.append(cpt.to_text(inner_var.name)) + + grad_op_desc, op_grad_to_var = core.get_grad_op_desc( + conditional_block_op.desc, cpt.to_text(set()), [grad_sub_block.desc] + ) + + # append op_desc in grad_op_descs to target_block + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + backward = core.op_proto_and_checker_maker.OpRole.Backward + new_op_desc = parent_block.desc.append_op() + new_op_desc.copy_from(grad_op_desc[0]) + new_op_desc._set_attr(op_role_attr_name, backward) + # set input and output manually + new_op_desc.set_input('Input', param_list) + new_op_desc.set_output( + 'Input@GRAD', [param + "@GRAD" for param in param_list] + ) + + new_vars = set() + for grad_var_name in new_op_desc.output_arg_names(): + if ( + grad_sub_block.desc.has_var_recursive( + cpt.to_bytes(grad_var_name) + ) + or grad_var_name == core.empty_var_name() + ): + continue + grad_sub_block.desc.var(cpt.to_bytes(grad_var_name)) + new_vars.add(grad_var_name) + if grad_var_name not in op_grad_to_var: + continue + + # infer_shape and infer_type + new_op_desc.infer_var_type(grad_sub_block.desc) + new_op_desc.infer_shape(grad_sub_block.desc) + + for arg in new_op_desc.output_arg_names(): + if arg in new_vars: + _infer_var_data_type_shape_(arg, grad_sub_block) + + self.helper.main_program._sync_with_cpp() + + +def copy_var_to_parent_block(var, layer_helper): + if not isinstance(var, Variable): + return var + prog = layer_helper.main_program + parent_idx = prog.current_block().parent_idx + assert ( + parent_idx >= 0 + ), "Got wrong parent block index when assigning var to parent scope in control_flow" + parent_block = prog.block(parent_idx) + + if ( + var.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY + and parent_block._find_var_recursive(var.name) + ): + parent_block_var = var + else: + parent_block_var = parent_block.create_var( + dtype=var.dtype, shape=var.shape, type=var.type + ) + assign(var, parent_block_var) + return parent_block_var + + +def cond(pred, true_fn=None, false_fn=None, name=None, return_names=None): + """ + This API returns ``true_fn()`` if the predicate ``pred`` is true else + ``false_fn()`` . Users could also set ``true_fn`` or ``false_fn`` to + ``None`` if do nothing and this API will treat the callable simply returns + ``None`` in this case. + + ``true_fn`` and ``false_fn`` should return same nest structure of tensors + or both return ``None`` if user doens't like to return anything. A nest + structure of tensors in PaddlePaddle is tensor(s), or tuple of tensors, or + list of tensors. + + Note: + 1. The tuples or lists returned by ``true_fn`` and ``false_fn`` must have + the same shape because of dataflow model of PaddlePaddle while the + tensors in the tuples or the lists can have different shapes. + + 2. This API could be used under both static mode or dygraph mode. If it + is in dygraph mode, the API only runs one branch based on condition. + + 3. If it is in static mode, any tensors or operations created outside + or inside of ``true_fn`` and ``false_fn`` will be in net building + regardless of which branch is selected at runtime. This has frequently + surprised users who expected a lazy semantics. For example: + + .. code-block:: python + + import paddle + + a = paddle.zeros((1, 1)) + b = paddle.zeros((1, 1)) + c = a * b + out = paddle.static.nn.cond(a < b, lambda: a + c, lambda: b * b) + + No matter whether ``a < b`` , ``c = a * b`` will be in net building and + run. ``a + c`` and ``b * b`` will be in net building, but only one + branch will be executed during runtime. + + Args: + pred(Tensor): A boolean tensor whose numel should be 1. The boolean + value determines whether to return the result of ``true_fn`` or + ``false_fn`` . + true_fn(callable, optional): A callable to be performed if ``pred`` is + true. The default value is ``None`` . + false_fn(callable, optional): A callable to be performed if ``pred`` is + false. The default value is ``None`` . + name(str, optional): The default value is ``None`` . Normally users + don't have to set this parameter. For more information, please + refer to :ref:`api_guide_Name` . + return_names(sequence of string, optional): The default value is ``None`` . + Normally users don't have to set this parameters. A sequence of strings + to represents the name of returned vars. The structure of sequence must + be same with return values of true_fn and false_fn. + + Returns: + Tensor|list(Tensor)|tuple(Tensor): returns ``true_fn()`` if the + predicate ``pred`` is true else ``false_fn()`` . + + Raises: + TypeError: if ``true_fn`` or ``false_fn`` is not callable. + ValueError: if ``true_fn`` and ``false_fn`` don't return the same nest + structure of tensors. + + Examples: + .. code-block:: python + + import paddle + + # + # pseudocode: + # if 0.1 < 0.23: + # return 1, True + # else: + # return 3, 2 + # + + def true_func(): + return paddle.full(shape=[1, 2], dtype='int32', + fill_value=1), paddle.full(shape=[2, 3], + dtype='bool', + fill_value=True) + + + def false_func(): + return paddle.full(shape=[3, 4], dtype='float32', + fill_value=3), paddle.full(shape=[4, 5], + dtype='int64', + fill_value=2) + + + x = paddle.full(shape=[1], dtype='float32', fill_value=0.1) + y = paddle.full(shape=[1], dtype='float32', fill_value=0.23) + pred = paddle.less_than(x=x, y=y, name=None) + ret = paddle.static.nn.cond(pred, true_func, false_func) + # ret is a tuple containing 2 tensors + # ret[0] = [[1 1]] + # ret[1] = [[ True True True] + # [ True True True]] + + """ + if _non_static_mode(): + assert isinstance(pred, Variable), "The pred in cond must be Variable" + assert pred.size == 1, "condition input's numel should be 1" + pred = pred.numpy()[0] + if pred: + if true_fn is not None: + if not callable(true_fn): + raise TypeError( + "The true_fn in cond must be callable, but received {}".format( + type(true_fn).__name__ + ) + ) + return true_fn() + else: + if false_fn is not None: + if not callable(false_fn): + raise TypeError( + "The false_fn in cond must be callable, but received {}".format( + type(false_fn).__name__ + ) + ) + return false_fn() + return None + + check_variable_and_dtype(pred, "pred", ['bool'], "fluid.layers.cond") + check_type(name, "name", (str, type(None)), "fluid.layers.cond") + helper = LayerHelper('cond', **locals()) + true_output = None + false_output = None + copy_to_parent_func = lambda var: copy_var_to_parent_block(var, helper) + if true_fn is not None: + if not callable(true_fn): + raise TypeError( + "The true_fn in cond must be callable, but received {}".format( + type(true_fn).__name__ + ) + ) + true_cond_block = ConditionalBlock([pred], is_scalar_condition=True) + with true_cond_block.block(): + origin_true_output = true_fn() + if origin_true_output is not None: + true_output = map_structure( + copy_to_parent_func, origin_true_output + ) + if false_fn is not None: + if not callable(false_fn): + raise TypeError( + "The false_fn in cond must be callable, but received {}".format( + type(false_fn).__name__ + ) + ) + false_cond_block = ConditionalBlock( + [logical_not(pred)], is_scalar_condition=True + ) + with false_cond_block.block(): + origin_false_output = false_fn() + if origin_false_output is not None: + false_output = map_structure( + copy_to_parent_func, origin_false_output + ) + + if true_output is None and false_output is None: + return None + + if true_output is None: + raise ValueError( + "Incompatible return values of true_fn and false_fn in cond: " + "true_fn returns None while false_fn returns non-None" + ) + if false_output is None: + raise ValueError( + "Incompatible return values of true_fn and false_fn in cond: " + "true_fn returns non-None while false_fn returns None" + ) + + # Merge ture and false output if they are not None + if return_names is None: + is_dy2staic = False + return_names = ["no name"] * len(_to_sequence_except_dict(true_output)) + else: + """ + dy2static will set the return_names and expand the return values to UndefinedVar. + """ + is_dy2staic = True + + # TODO: expand_undefined_var will replace None to Undefinedvar(), to fix cases like: + # a = None + # if condition: + # a = 1 + # Because we can not use variable to express 'None' + true_output, false_output = expand_undefined_var( + true_output, false_output, return_names + ) + + if len(_to_sequence_except_dict(true_output)) != len( + _to_sequence_except_dict(false_output) + ): + raise ValueError( + "true fn returns {} vars, but false fn returns {} vars, which is not equals".format( + len(_to_sequence_except_dict(true_output)), + len(_to_sequence_except_dict(false_output)), + ) + ) + for true_out, false_out, return_name in zip( + _to_sequence_except_dict(true_output), + _to_sequence_except_dict(false_output), + _to_sequence_except_dict(return_names), + ): + try: + assert_same_structure(true_out, false_out, check_types=False) + except ValueError as e: + raise ValueError( + "Incompatible return values of `{}` in true_fn and false_fn in cond: {}".format( + return_name, e + ) + ) + + def check_ret_none(seq_true, seq_false, seq_names): + for f_true, f_false, f_name in zip(seq_true, seq_false, seq_names): + f_true = flatten(f_true) + f_false = flatten(f_false) + for idx in range(len(f_true)): + if ( + f_true[idx] is None + and f_false[idx] is not None + or f_false[idx] is None + and f_true[idx] is not None + ): + warnings.warn( + "In cond : Var '{}' or part of it is set differently in ifelse branchs, " + "<{}, {}> in true branch and <{}, {}> in false branch. Set var to " + "'None' in ifelse block might lead to error.".format( + f_name, + type(f_true[idx]), + f_true[idx], + type(f_false[idx]), + f_false[idx], + ) + ) + + check_ret_none( + _to_sequence_except_dict(true_output), + _to_sequence_except_dict(false_output), + _to_sequence_except_dict(return_names), + ) + + if is_dy2staic: + true_output, false_output = change_none_to_undefinedvar( + true_output, false_output + ) + + mask = cast(pred, dtype='int32') + merge_func = ( + lambda name, false_var, true_var: select_input_with_buildin_type( + [false_var, true_var], mask, name + ) + ) + + def merge_every_var_list(false_vars, true_vars, name): + return map_structure(partial(merge_func, name), false_vars, true_vars) + + merged_output = list( + map( + merge_every_var_list, + _to_sequence_except_dict(false_output), + _to_sequence_except_dict(true_output), + _to_sequence_except_dict(return_names), + ) + ) + merged_output = pack_sequence_as(false_output, flatten(merged_output)) + return merged_output + + +def change_none_to_undefinedvar(nest1, nest2): + from paddle.fluid.dygraph.dygraph_to_static.utils import UndefinedVar + + def map_fn(x): + if x is None: + return UndefinedVar("padding") + return x + + nest1_out = pack_sequence_as(nest1, list(map(map_fn, flatten(nest1)))) + nest2_out = pack_sequence_as(nest2, list(map(map_fn, flatten(nest2)))) + return nest1_out, nest2_out + + +def _to_sequence_except_dict(x): + """ + In this function, dict is not viewed as sequence. + """ + if isinstance(x, dict): + return [x] + return to_sequence(x) + + +def _is_sequence_except_dict(x): + """ + In this function, dict is not viewed as sequence. + """ + if isinstance(x, dict): + return False + return is_sequence(x) + + +def expand_undefined_var(nest1, nest2, names): + """TODO: make this function recursively. + nest1: Var1, (UndefinedVar, [1,2,3]) + nest2: Var2, ([1,2,3,4], UndefinedVar) + In this case, we should not expand recursively. + """ + from paddle.fluid.dygraph.dygraph_to_static.utils import UndefinedVar + from paddle.fluid.dygraph.dygraph_to_static.return_transformer import ( + RETURN_VALUE_PREFIX, + ) + + def pack_undefined_var_as(seq): + return pack_sequence_as( + seq, [UndefinedVar("padding") for i in flatten(seq)] + ) + + def map_fn(n1, n2, name, order): + if not name.startswith(RETURN_VALUE_PREFIX) and ( + isinstance(n1, UndefinedVar) or n1 is None + ): + if n1 is None and n2 is not None: + if order == 0: + warnings.warn( + "In cond : Var '{}' or part of it is set differently in ifelse branchs, " + "<{}, {}> in true branch and <{}, {}> in false branch. Set var to " + "'None' in ifelse block might lead to error.".format( + name, type(n1), n1, type(n2), n2 + ) + ) + else: + warnings.warn( + "In cond : Var '{}' or part of it is set differently in ifelse branchs, " + "<{}, {}> in true branch and <{}, {}> in false branch. Set var to " + "'None' in ifelse block might lead to error.".format( + name, type(n2), n2, type(n1), n1 + ) + ) + return pack_undefined_var_as(n2) + return n1 + + nest1_out = list( + map( + map_fn, + _to_sequence_except_dict(nest1), + _to_sequence_except_dict(nest2), + _to_sequence_except_dict(names), + [0 for i in _to_sequence_except_dict(names)], + ) + ) + nest2_out = list( + map( + map_fn, + _to_sequence_except_dict(nest2), + _to_sequence_except_dict(nest1), + _to_sequence_except_dict(names), + [1 for i in _to_sequence_except_dict(names)], + ) + ) + if not _is_sequence_except_dict(nest1): + nest1_out = nest1_out[0] + if not _is_sequence_except_dict(nest2): + nest2_out = nest2_out[0] + return nest1_out, nest2_out + + +def _error_message(what, arg_name, op_name, right_value, error_value): + error_message = ( + "{what} of '{arg_name}' in {op_name} must be " + "{right_value}, but received: {error_value}.".format( + what=what, + arg_name=arg_name, + op_name=op_name, + right_value=right_value, + error_value=error_value, + ) + ) + + return error_message + + +def case(pred_fn_pairs, default=None, name=None): + ''' + :api_attr: Static Graph + + This operator works like an if-elif-elif-else chain. + + Args: + pred_fn_pairs(list|tuple): A list or tuple of (pred, fn) pairs. ``pred`` is a boolean Tensor with shape [1], ``fn`` is a callable. All callables return the same structure of Tensors. + default(callable, optional): Callable that returns a structure of Tensors. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor|list(Tensor): Tensors returned by the callable from the first pair whose pred is True, + or Tensors returned by ``default`` if no pred in ``pred_fn_pairs`` is True and ``default`` is not None, + or Tensors returned by the last callable in ``pred_fn_pairs`` if no pred in ``pred_fn_pairs`` is True and ``default`` is None. + + Raises: + TypeError: If the type of ``pred_fn_pairs`` is not list or tuple. + TypeError: If the type of elements in ``pred_fn_pairs`` is not tuple. + TypeError: If the size of tuples in ``pred_fn_pairs`` is not 2. + TypeError: If the first element of 2-tuple in ``pred_fn_pairs`` is not a Tensor. + TypeError: If the second element of 2-tuple in ``pred_fn_pairs`` is not callable. + TypeError: If ``default`` is not None but it is not callable. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + def fn_1(): + return paddle.full(shape=[1, 2], dtype='float32', fill_value=1) + + def fn_2(): + return paddle.full(shape=[2, 2], dtype='int32', fill_value=2) + + def fn_3(): + return paddle.full(shape=[3], dtype='int32', fill_value=3) + + main_program = paddle.static.default_startup_program() + startup_program = paddle.static.default_main_program() + + with paddle.static.program_guard(main_program, startup_program): + x = paddle.full(shape=[1], dtype='float32', fill_value=0.3) + y = paddle.full(shape=[1], dtype='float32', fill_value=0.1) + z = paddle.full(shape=[1], dtype='float32', fill_value=0.2) + + pred_1 = paddle.less_than(z, x) # true: 0.2 < 0.3 + pred_2 = paddle.less_than(x, y) # false: 0.3 < 0.1 + pred_3 = paddle.equal(x, y) # false: 0.3 == 0.1 + + # Call fn_1 because pred_1 is True + out_1 = paddle.static.nn.case( + pred_fn_pairs=[(pred_1, fn_1), (pred_2, fn_2)], default=fn_3) + + # Argument default is None and no pred in pred_fn_pairs is True. fn_3 will be called. + # because fn_3 is the last callable in pred_fn_pairs. + out_2 = paddle.static.nn.case(pred_fn_pairs=[(pred_2, fn_2), (pred_3, fn_3)]) + + exe = paddle.static.Executor(paddle.CPUPlace()) + res_1, res_2 = exe.run(main_program, fetch_list=[out_1, out_2]) + print(res_1) # [[1. 1.]] + print(res_2) # [3 3 3] + ''' + helper = LayerHelper('case', **locals()) + + def _case_check_args(pred_fn_pairs, default): + ''' + Check arguments pred_fn_pairs and default. Return canonical pre_fn_pairs and default. + ''' + check_type(pred_fn_pairs, 'pred_fn_pairs', (list, tuple), 'case') + + for pred_fn in pred_fn_pairs: + if not isinstance(pred_fn, tuple): + raise TypeError( + _error_message( + "The elements' type", + "pred_fn_pairs", + "case", + tuple, + type(pred_fn), + ) + ) + if len(pred_fn) != 2: + raise TypeError( + _error_message( + "The tuple's size", + "pred_fn_pairs", + "case", + "2", + str(len(pred_fn)) + "-tuple", + ) + ) + pred, fn = pred_fn + + if not isinstance(pred, Variable): + raise TypeError( + _error_message( + "The pred's type", + "pred_fn_pairs", + "case", + "boolean Variable", + type(pred), + ) + ) + + if not callable(fn): + raise TypeError( + "The fn for {} of pred_fn_pairs in Op(case) must" + " be callable.".format(pred.name) + ) + + if default is None: + default_index = len(pred_fn_pairs) - 1 # pick the last one + default = pred_fn_pairs[default_index][1] + pred_fn_pairs = pred_fn_pairs[:default_index] + elif not callable(default): + raise TypeError("The default in Op(case) must be callable.") + + return pred_fn_pairs, default + + pred_fn_pairs, default = _case_check_args(pred_fn_pairs, default) + + false_fn = default + for pred, true_fn in reversed(pred_fn_pairs): + false_fn = partial(cond, pred=pred, true_fn=true_fn, false_fn=false_fn) + + final_fn = false_fn + + return final_fn() + + +class Switch(object): + """ + :api_attr: Static Graph + + This class is used to implement Switch branch control function. + Switch branch contains several case branches and one default branch. + Switch control flow checks whether the case branch conditions are satisfied in turn, + and only executes the statement after the first case branch that satisfies the conditions. + If there is no case branch that satisfies the condition, + only the statement following the default branch is executed. + + Note: + A new OP :ref:`api_fluid_layers_case` is highly recommended instead of ``Switch`` if the shape of parameter ``cond`` is [1]. + OP :ref:`api_fluid_layers_case` is easier to use and is called with less code but does the same thing as ``Switch`` . + + Member Functions: + case(condition): The case branch of Switch whose parameter cond is a scalar Variable of bool type. Only if the cond of the current case branch is True and the cond of the previous case branch is False, the statement after the case branch will be executed, and the statement after the case branch will not be executed. + + default(): The default branch of Switch. When cond of all case branches is False, the statement after default branch is executed. + + Case and default functions can only be used inside the scope of Switch, as shown below: + + .. code-block:: python + + ''' + with fluid.layers.Switch() as switch: + with switch.case(cond1): + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=1) + with switch.case(cond2): + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=2) + with switch.default(): + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0) + ''' + + Args: + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + lr = fluid.layers.create_global_var( + shape=[1], + value=0.0, + dtype='float32', + persistable=True, + name="learning_rate") + zero_var = fluid.layers.fill_constant( + shape=[1], dtype='float32', value=0.0) + one_var = fluid.layers.fill_constant( + shape=[1], dtype='float32', value=1.0) + two_var = fluid.layers.fill_constant( + shape=[1], dtype='float32', value=2.0) + + global_step = fluid.layers.autoincreased_step_counter(counter_name='@LR_DECAY_COUNTER@', begin=0, step=1) + + with fluid.layers.control_flow.Switch() as switch: + with switch.case(global_step == zero_var): + fluid.layers.assign(input=one_var, output=lr) + with switch.default(): + fluid.layers.assign(input=two_var, output=lr) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + res = exe.run(fluid.default_main_program(), feed={}, fetch_list=[lr]) + print(res) # [array([1.], dtype=float32)] + """ + + def __init__(self, name=None): + self.helper = LayerHelper('switch', name=name) + self.inside_scope = False + self.pre_not_conditions = [] + + def case(self, condition): + if not self.inside_scope: + raise ValueError("case should be called inside with") + + check_variable_and_dtype( + condition, + 'condition', + ['bool'], + 'the member function case of fluid.layers.Switch', + ) + + if len(self.pre_not_conditions) == 0: + cond_block = ConditionalBlock([condition], is_scalar_condition=True) + not_cond = logical_not(x=condition) + self.pre_not_conditions.append(not_cond) + else: + pre_cond_num = len(self.pre_not_conditions) + pre_not_cond = self.pre_not_conditions[pre_cond_num - 1] + new_not_cond = logical_and( + x=pre_not_cond, y=logical_not(x=condition) + ) + self.pre_not_conditions.append(new_not_cond) + cond_block = ConditionalBlock( + [logical_and(x=pre_not_cond, y=condition)], + is_scalar_condition=True, + ) + + return ConditionalBlockGuard(cond_block) + + def default(self): + pre_cond_num = len(self.pre_not_conditions) + if pre_cond_num == 0: + raise ValueError("there should be at least one condition") + cond_block = ConditionalBlock( + [self.pre_not_conditions[pre_cond_num - 1]], + is_scalar_condition=True, + ) + return ConditionalBlockGuard(cond_block) + + def __enter__(self): + """ + set flag that now is inside switch.block {} + :return: + """ + self.inside_scope = True + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.inside_scope = False + if exc_type is not None: + return False # re-raise exception + + return True + + +class IfElseBlockGuard(object): + def __init__(self, is_true, ifelse): + if not isinstance(ifelse, IfElse): + raise TypeError("ifelse must be an instance of IfElse class") + + if ifelse.status != IfElse.OUT_IF_ELSE_BLOCKS: + raise ValueError("You cannot invoke IfElse.block() inside a block") + + self.is_true = is_true + self.ie = ifelse + if is_true: + self.cond_block = ifelse.conditional_true_block + else: + self.cond_block = ifelse.conditional_false_block + + if not isinstance(self.cond_block, ConditionalBlock): + raise TypeError("Unexpected situation") + + self.cond_block = self.cond_block.block() + + def __enter__(self): + self.ie.status = ( + IfElse.IN_IF_ELSE_TRUE_BLOCKS + if self.is_true + else IfElse.IN_IF_ELSE_FALSE_BLOCKS + ) + self.cond_block.__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.cond_block.__exit__(exc_type, exc_val, exc_tb): + # re-raise inside exception + return False + if len(self.ie.output_table[1 if self.is_true else 0]) == 0: + raise ValueError("Must set output inside block") + self.ie.status = IfElse.OUT_IF_ELSE_BLOCKS + + +class IfElse(object): + """ + :api_attr: Static Graph + + This class is used to implement IfElse branch control function. IfElse contains two blocks, true_block and false_block. IfElse will put data satisfying True or False conditions into different blocks to run. + + Cond is a 2-D Tensor with shape [N, 1] and data type bool, representing the execution conditions of the corresponding part of the input data. + + Note: + A new OP :ref:`api_fluid_layers_cond` is highly recommended instead of ``IfElse``. if the shape of parameter ``cond`` is [1]. + OP :ref:`api_fluid_layers_cond` is easier to use and is called with less code but does the same thing as ``IfElse`` . + + IfElse OP is different from other OPs in usage, which may cause some users confusion. Here is a simple example to illustrate this OP. + + .. code-block:: python + + # The following code completes the function: subtract 10 from the data greater than 0 in x, add 10 to the data less than 0 in x, and sum all the data. + import numpy as np + import paddle.fluid as fluid + + x = fluid.layers.data(name='x', shape=[4, 1], dtype='float32', append_batch_size=False) + y = fluid.layers.data(name='y', shape=[4, 1], dtype='float32', append_batch_size=False) + + x_d = np.array([[3], [1], [-2], [-3]]).astype(np.float32) + y_d = np.zeros((4, 1)).astype(np.float32) + + # Compare the size of x, y pairs of elements, output cond, cond is shape [4, 1], data type bool 2-D tensor. + # Based on the input data x_d, y_d, it can be inferred that the data in cond are [[true], [true], [false], [false]]. + cond = fluid.layers.greater_than(x, y) + # Unlike other common OPs, ie below returned by the OP is an IfElse OP object + ie = fluid.layers.IfElse(cond) + + with ie.true_block(): + # In this block, according to cond condition, the data corresponding to true dimension in X is obtained and subtracted by 10. + out_1 = ie.input(x) + out_1 = out_1 - 10 + ie.output(out_1) + with ie.false_block(): + # In this block, according to cond condition, get the data of the corresponding condition in X as false dimension, and add 10 + out_1 = ie.input(x) + out_1 = out_1 + 10 + ie.output(out_1) + + # According to cond condition, the data processed in the two blocks are merged. The output here is output, the type is List, and the element type in List is Variable. + output = ie() # [array([[-7.], [-9.], [ 8.], [ 7.]], dtype=float32)] + + # Get the first Variable in the output List and add all elements. + out = fluid.layers.reduce_sum(output[0]) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + res = exe.run(fluid.default_main_program(), feed={"x":x_d, "y":y_d}, fetch_list=[out]) + print(res) + # [array([-1.], dtype=float32)] + + Args: + cond (Variable): cond is a 2-D Tensor with shape [N, 1] and data type bool, representing the corresponding execution conditions of N input data. The data type is bool. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Unlike other common OPs, the OP call returns an IfElse OP object (e.g. ie in the example), which branches the input data by calling the internal functions of the object ``true_block ()``, ``false_block ()``, ``input ()``, ``output ()``, and integrates the data processed by different branches as the overall output by calling the internal ``call ()`` function. The output type is a list, and the type of each element in the list is Variable. + + Internal Functions: + The block is constructed by calling the ``with ie. true_block()`` function in the object, and the computational logic under condition true is put into the block. If no corresponding block is constructed, the input data in the corresponding conditional dimension is unchanged. + + The block is constructed by calling the ``with ie. false_block()`` function in the object, and the computational logic under condition false is put into the block. If no corresponding block is constructed, the input data in the corresponding conditional dimension is unchanged. + + ``Out = ie. input (x)`` will take out the data of the corresponding conditional dimension in X and put it into out, supporting the internal processing of multiple inputs in block. + + ``ie. output (out)`` writes the result to the output of the corresponding condition. + + There is a ``call ()`` function inside the object, that is, by calling ``output = ie ()``, all the outputs inside the block of False are fused as the whole output, the output type is a list, and the type of each element in the list is Variable. + + """ + + OUT_IF_ELSE_BLOCKS = 0 + IN_IF_ELSE_TRUE_BLOCKS = 1 + IN_IF_ELSE_FALSE_BLOCKS = 2 + + def __init__(self, cond, name=None): + check_type(cond, "cond", Variable, "fluid.layers.IfElse") + check_type(name, "name", (str, type(None)), "fluid.layers.IfElse") + self.helper = LayerHelper('ifelse', name=name) + self.cond = cond + self.input_table = {} + self.status = IfElse.OUT_IF_ELSE_BLOCKS + self.conditional_true_block = ConditionalBlock(inputs=[self.cond]) + self.conditional_false_block = ConditionalBlock(inputs=[self.cond]) + self.output_table = ([], []) # (true_outs, false_outs) + + def input(self, x): + if self.status == IfElse.OUT_IF_ELSE_BLOCKS: + raise ValueError("input must in true/false blocks") + if id(x) not in self.input_table: + parent_block = self._parent_block() + out_true = parent_block.create_var( + name=unique_name.generate_with_ignorable_key( + 'ifelse_input' + self.helper.name + ), + dtype=x.dtype, + ) + + out_false = parent_block.create_var( + name=unique_name.generate_with_ignorable_key( + 'ifelse_input' + self.helper.name + ), + dtype=x.dtype, + ) + parent_block.append_op( + type='split_lod_tensor', + inputs={ + 'X': x, + 'Mask': self.cond, + }, + outputs={'OutTrue': out_true, 'OutFalse': out_false}, + attrs={'level': 0}, + ) + self.input_table[id(x)] = (out_true, out_false) + else: + out_true, out_false = self.input_table[id(x)] + + if self.status == IfElse.IN_IF_ELSE_TRUE_BLOCKS: + return out_true + else: + return out_false + + def _parent_block(self): + current_block = self.helper.main_program.current_block() + return self.helper.main_program.block(current_block.parent_idx) + + def true_block(self): + return IfElseBlockGuard(True, self) + + def false_block(self): + return IfElseBlockGuard(False, self) + + def output(self, *outs): + if self.status == self.OUT_IF_ELSE_BLOCKS: + raise ValueError("output can only be invoked in the sub-block") + + out_table = self.output_table[ + 1 if self.status == self.IN_IF_ELSE_TRUE_BLOCKS else 0 + ] + parent_block = self._parent_block() + for each_out in outs: + check_type( + each_out, "each output", Variable, "fluid.layers.IfElse.output" + ) + # create outside tensor + outside_out = parent_block.create_var( + name=unique_name.generate_with_ignorable_key( + "_".join([self.helper.name, 'output']) + ), + dtype=each_out.dtype, + ) + out_table.append(outside_out) + + # assign local var to outside + assign(input=each_out, output=outside_out) + + def __call__(self): + if self.status != self.OUT_IF_ELSE_BLOCKS: + raise ValueError("IfElse::__call__ must be out of sub-block") + false_len, true_len = list(map(len, self.output_table)) + if false_len == 0 and true_len == 0: + raise ValueError( + "Must invoke true_block/false_block before " "__call__" + ) + elif false_len != true_len and false_len != 0 and true_len != 0: + raise ValueError("The output side must be same") + elif false_len == 0 or true_len == 0: + return self.output_table[0 if false_len != 0 else 1] + + # else none of false_len/true_len is zero + # merge together + rlist = [] + for false_var, true_var in zip(*self.output_table): + rlist.append( + merge_lod_tensor( + in_true=true_var, + in_false=false_var, + mask=self.cond, + x=self.cond, + level=0, + ) + ) + return rlist + + +class DynamicRNN(object): + """ + :api_attr: Static Graph + + **Note: the input of this class should be LoDTensor which holds the + information of variable-length sequences. If the input is fixed-length Tensor, + please use StaticRNN (fluid.layers.** :ref:`api_fluid_layers_StaticRNN` **) for + better performance.** + + DynamicRNN can process a minibatch of variable-length sequences. + The length of each sample can be different and is recorded in LoD. + In DynamicRNN, an input sequence will be unfolded into time steps and users + can define how to process each time step in :code:`block()` . + The total number of time steps is determined by the longest sequence. + DynamicRNN will not pad all sequences to the same length, instead it will + sort the sequences internally by the sequence length in descending order. + The input sequences will be shrank because only sequences of which the + length is larger than the time step will participate the remaining calculation. + + If defined :code:`drnn = DynamicRNN()`, then users can call :code:`drnn()` + to obtain the result sequences. It is a LoDTensor gained by merging all + time steps's output. When RNN's input sequence x meets :code:`x.lod_level == 1`, + the output LoDTensor will have the same LoD with x. The result of :code:`drnn()` + includes RNN's outputs of all time steps, users can call + :ref:`api_fluid_layers_sequence_last_step` to extract the data of the last time step. + + Warning: + Currently it is not supported to set :code:`is_sparse = True` of any + layers defined within DynamicRNN's :code:`block` function. + + Args: + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, + please refer to :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + sentence = fluid.data(name='sentence', shape=[None, 32], dtype='float32', lod_level=1) + encoder_proj = fluid.data(name='encoder_proj', shape=[None, 32], dtype='float32', lod_level=1) + decoder_boot = fluid.data(name='boot', shape=[None, 10], dtype='float32') + + drnn = fluid.layers.DynamicRNN() + with drnn.block(): + # Set sentence as RNN's input, each time step processes a word from the sentence + current_word = drnn.step_input(sentence) + # Set encode_proj as RNN's static input + encoder_word = drnn.static_input(encoder_proj) + # Initialize memory with boot_memory, which need reorder according to RNN's input sequences + memory = drnn.memory(init=decoder_boot, need_reorder=True) + fc_1 = fluid.layers.fc(input=encoder_word, size=30) + fc_2 = fluid.layers.fc(input=current_word, size=30) + decoder_inputs = fc_1 + fc_2 + hidden, _, _ = fluid.layers.gru_unit(input=decoder_inputs, hidden=memory, size=30) + # Update memory with hidden + drnn.update_memory(ex_mem=memory, new_mem=hidden) + out = fluid.layers.fc(input=hidden, size=10, bias_attr=True, act='softmax') + # Set hidden and out as RNN's outputs + drnn.output(hidden, out) + + # Get RNN's result + hidden, out = drnn() + # Get RNN's result of the last time step + last = fluid.layers.sequence_last_step(out) + """ + + BEFORE_RNN = 0 + IN_RNN = 1 + AFTER_RNN = 2 + + def __init__(self, name=None): + self.helper = LayerHelper('dynamic_rnn', name=name) + self.status = DynamicRNN.BEFORE_RNN + self.lod_rank_table = None + self.max_seq_len = None + self.step_idx = None + self.zero_idx = None + self.mem_dict = dict() + self.output_array = [] + self.outputs = [] + self.cond = self.helper.create_variable_for_type_inference(dtype='bool') + self.cond.stop_gradient = False + self.while_op = While(self.cond) + self.input_array = [] + self.mem_link = [] + + def step_input(self, x, level=0): + r""" + This function is used to set sequence x as DynamicRNN's input. + The maximum sequence length in x determines the number of time steps + the RNN unit will be executed. DynamicRNN can take multiple inputs. + When all inputs' :code:`lod_level` are 1, all inputs should hold the + same LoD. When :code:`x.lod_level >= 2` , the input sequence will be + unfold along specified level, and the slice of each time step is a + LoDTensor whose lod_level is :code:`x.lod_level - level - 1` . + In this case, the specified LoD level of multiple inputs should be the same. + + - Case 1: + + .. code-block:: text + + # input, where Si is slice data of shape [1, N] + level = 0 + x.lod = [[2, 1, 3]] + x.shape = [6, N] + x.data = [[S0], + [S0], + [S1], + [S2], + [S2], + [S2]] + + # output + # step 0, time step data of 3 sequences + out.lod = [[]] + out.shape = [3, N] + out.data = [[S2], + [S0], + [S1]] + + # step 1, time step data of 2 sequences + out.lod = [[]] + out.shape = [2, N] + out.data = [[S2], + [S0]] + + # step 2, time step data of 1 sequences + out.lod = [[]] + out.shape = [1, N] + out.data = [[S2]] + + + Args: + x (Variable): The input LoDTensor which holds information of a + minibatch of variable-length sequences and should meet :code:`x.lod_level >= 1` . + When RNN has multiple inputs, the first dimension should match + across all inputs, but other shape components may differ. + Optional data types are: bool, float16, float32, float64, int8, int16, int32, int64, uint8. + level (int, optional): The level of lod used to split steps. + It should be in range :math:`[0, x.lod\_level)` . The default value is 0. + + Returns: + Variable: The current time step in the input sequence. If there are :code:`num_sequences` \ + sequences in x whose length is larger than :code:`step_idx` , the returned Variable \ + will only hold the :code:`step_idx` -th time step of those `num_sequences` sequences. \ + The data type is the same as input. If :code:`x.lod_level == 1` , the return value is \ + a Tensor of shape :math:`\{num\_sequences, x.shape[1], ...\}` , or it will \ + be a variable-length LoDTensor. + + Raises: + ValueError: When :code:`step_input()` is called outside :code:`block()` . + TypeError: When x is not a Variable. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + sentence = fluid.data(name='sentence', shape=[None, 1], dtype='int64', lod_level=1) + embedding = fluid.layers.embedding(input=sentence, size=[65536, 32], is_sparse=True) + + drnn = fluid.layers.DynamicRNN() + with drnn.block(): + # Set embedding as RNN's input, each time step processes a word from the sentence + word = drnn.step_input(embedding) + # Initialize memory to a Tensor whose value is 0, shape=[batch_size, 200], + # where batch_size is the number of sequences in embedding. + memory = drnn.memory(shape=[200]) + hidden = fluid.layers.fc(input=[word, memory], size=200, act='relu') + # Update memory to hidden + drnn.update_memory(ex_mem=memory, new_mem=hidden) + # Set hidden as RNN's output + drnn.output(hidden) + + # Get RNN's result + rnn_output = drnn() + """ + self._assert_in_rnn_block_("step_input") + check_type(x, 'x', Variable, 'fluid.layers.DynamicRNN.step_input()') + parent_block = self._parent_block_() + if self.lod_rank_table is None: + self.lod_rank_table = parent_block.create_var( + name=unique_name.generate('lod_rank_table'), + type=core.VarDesc.VarType.LOD_RANK_TABLE, + ) + self.lod_rank_table.stop_gradient = True + parent_block.append_op( + type='lod_rank_table', + inputs={"X": x}, + outputs={"Out": self.lod_rank_table}, + attrs={"level": level}, + ) + self.max_seq_len = parent_block.create_var( + name=unique_name.generate('dynamic_rnn_max_seq_len'), + dtype='int64', + ) + self.max_seq_len.stop_gradient = False + parent_block.append_op( + type='max_sequence_len', + inputs={'RankTable': self.lod_rank_table}, + outputs={"Out": self.max_seq_len}, + ) + self.cond.stop_gradient = True + parent_block.append_op( + type='less_than', + inputs={'X': self.step_idx, 'Y': self.max_seq_len}, + outputs={'Out': self.cond}, + attrs={'force_cpu': True}, + ) + + input_array = parent_block.create_var( + name=unique_name.generate('dynamic_rnn_input_array'), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=x.dtype, + ) + self.input_array.append((input_array, x.dtype)) + parent_block.append_op( + type='lod_tensor_to_array', + inputs={'X': x, 'RankTable': self.lod_rank_table}, + outputs={'Out': input_array}, + ) + return array_read(array=input_array, i=self.step_idx) + + def static_input(self, x): + r""" + This function is used to set x as DynamicRNN's static input. It is optional. + + - Case 1, set static input with LoD + + .. code-block:: text + + # RNN's input is the same as the case listed in step_input + # static input, where Si is slice data of shape [1, M] + x.lod = [[3, 1, 2]] + x.shape = [6, M] + x.data = [[S0], + [S0], + [S0], + [S1], + [S2], + [S2]] + + # step 0, batch data corresponding to the 3 input sequences + out.lod = [[2, 3, 1]] + out.shape = [6, M] + out.data = [[S2], + [S2], + [S0], + [S0], + [S0], + [S1]] + + # step 1, batch data corresponding to the 2 input sequences + out.lod = [[2, 3]] + out.shape = [5, M] + out.data = [[S2], + [S2], + [S0], + [S0], + [S0]] + + # step 2, batch data corresponding to the 1 input sequences + out.lod = [[2]] + out.shape = [2, M] + out.data = [[S2], + [S2]] + + + - Case 2, set static input without LoD + + .. code-block:: text + + # RNN's input is the same as the case listed in step_input + # static input, where Si is slice data of shape [1, M] + x.lod = [[]] + x.shape = [3, M] + x.data = [[S0], + [S1], + [S2]] + + # step 0, batch data corresponding to the 3 input sequences + out.lod = [[]] + out.shape = [3, M] + out.data = [[S2], + [S0], + [S1]] + + # step 1, batch data corresponding to the 2 input sequences + out.lod = [[]] + out.shape = [2, M] + out.data = [[S2], + [S0]] + + # step 2, batch data corresponding to the 1 input sequences + out.lod = [[]] + out.shape = [1, M] + out.data = [[S2]] + + + Args: + x (Variable): The static input LoDTensor which should hold the same number of sequences + as RNN's input (the input LoDTensor set by :code:`step_input()` ). If the LoD is None, + the input x will be treated as a minibatch with :code:`x.shape[0]` sequences of length 1. + Optional data types are: bool, float16, float32, float64, int8, int16, int32, int64, uint8. + + Returns: + Variable: The input LoDTensor after sorted and shrank. If there are :code:`num_sequences` \ + sequences in RNN's input LoDTensor whose length is larger than :code:`step_idx` , \ + the static input Tensor will be sorted to the same order as RNN's input and \ + will only retain data corresponding to those :code:`num_sequences` sequences. \ + The data type is the same as input. If :code:`x.lod == None` , the return value is \ + a Tensor of shape :math:`\{num\_sequences, x.shape[1], ...\}` , or it will \ + be a variable-length LoDTensor. + + Raises: + ValueError: When :code:`static_input()` is called outside :code:`block()` . + TypeError: When x is not a Variable. + RuntimeError: When :code:`static_input()` is called before :code:`step_input()` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + sentence = fluid.data(name='sentence', shape=[None, 32], dtype='float32', lod_level=1) + encoder_proj = fluid.data(name='encoder_proj', shape=[None, 32], dtype='float32', lod_level=1) + decoder_boot = fluid.data(name='boot', shape=[None, 10], dtype='float32') + + drnn = fluid.layers.DynamicRNN() + with drnn.block(): + # Set sentence as RNN's input, each time step processes a word from the sentence + current_word = drnn.step_input(sentence) + # Set encode_proj as RNN's static input + encoder_word = drnn.static_input(encoder_proj) + # Initialize memory with boot_memory, which need reorder according to RNN's input sequences + memory = drnn.memory(init=decoder_boot, need_reorder=True) + fc_1 = fluid.layers.fc(input=encoder_word, size=30) + fc_2 = fluid.layers.fc(input=current_word, size=30) + decoder_inputs = fc_1 + fc_2 + hidden, _, _ = fluid.layers.gru_unit(input=decoder_inputs, hidden=memory, size=30) + # Update memory with hidden + drnn.update_memory(ex_mem=memory, new_mem=hidden) + out = fluid.layers.fc(input=hidden, size=10, bias_attr=True, act='softmax') + # Set out as RNN's output + drnn.output(out) + + # Get RNN's result + rnn_output = drnn() + """ + self._assert_in_rnn_block_("static_input") + check_type(x, 'x', Variable, 'fluid.layers.DynamicRNN.static_input()') + if self.lod_rank_table is None: + raise RuntimeError( + "static_input() must be called after step_input()." + ) + parent_block = self._parent_block_() + x_reordered = parent_block.create_var( + name=unique_name.generate("dynamic_rnn_static_input_reordered"), + type=core.VarDesc.VarType.LOD_TENSOR, + dtype=x.dtype, + ) + parent_block.append_op( + type='reorder_lod_tensor_by_rank', + inputs={'X': [x], 'RankTable': [self.lod_rank_table]}, + outputs={'Out': [x_reordered]}, + ) + return shrink_memory(x_reordered, self.step_idx, self.lod_rank_table) + + @signature_safe_contextmanager + def block(self): + """ + The function is used to list the operations executed during + each time step in RNN. The operation list will be executed :code:`max_sequence_len` + times (where :code:`max_sequence_len` is the maximum length of RNN's input sequences). + + Raises: + ValueError: When :code:`block()` is called multi-times. + """ + if self.status != DynamicRNN.BEFORE_RNN: + raise ValueError("rnn.block() can only be invoke once") + self.step_idx = fill_constant( + shape=[1], dtype='int64', value=0, force_cpu=True + ) + self.step_idx.stop_gradient = False + self.status = DynamicRNN.IN_RNN + with self.while_op.block(): + yield + increment(x=self.step_idx, value=1.0, in_place=True) + + for new_mem, mem_array in self.mem_link: + array_write(x=new_mem, i=self.step_idx, array=mem_array) + + less_than( + x=self.step_idx, + y=self.max_seq_len, + force_cpu=True, + cond=self.cond, + ) + + self.status = DynamicRNN.AFTER_RNN + for each_array in self.output_array: + self.outputs.append( + array_to_lod_tensor(x=each_array, table=self.lod_rank_table) + ) + + def __call__(self, *args, **kwargs): + """ + This function is used to get the output sequences of DynamicRNN. + + Args: + None + + Returns: + Variable or Variable list: RNN's output sequences. + + Raises: + ValueError: When :code:`__call__()` is called before :code:`block()` . + """ + if self.status != DynamicRNN.AFTER_RNN: + raise ValueError( + ( + "Output of the dynamic RNN can only be visited " + "outside the rnn block." + ) + ) + if len(self.outputs) == 1: + return self.outputs[0] + else: + return self.outputs + + def memory( + self, + init=None, + shape=None, + value=0.0, + need_reorder=False, + dtype='float32', + ): + r""" + Create a memory Variable for DynamicRNN to deliver data cross time steps. + It can be initialized by an existing Tensor or a constant Tensor of given + dtype and shape. + + Args: + init (Variable, optional): LoDTensor used to initialize the memory. + If init is not None, it should hold the same number of sequences + as RNN's input (the input LoDTensor set by :code:`step_input()` ) + and the memory will be initialized to it. If init's LoD is None, + it will be treated as a minibatch with :code:`init.shape[0]` sequences + of length 1. The default value is None. + shape (list|tuple, optional): When init is None, it is used to specify + the memory's shape. Note that the shape does not include the batch_size. + If setting shape to :math:`\{D_1, D_2, ...\}` , the shape of memory Tensor + will be :math:`\{batch\_size, D_1, D_2, ...\}` , where batch_size is + determined by RNN's input sequences. The default value is None. + value (float, optional): When init is None, it is used as initialized value + of memory. The default value is 0.0. + need_reorder (bool, optional): When init is not None, it determines whether + the memory needs to reorder like the RNN's input sequences. It should be + set to True when the initialized memory depends on the order of input samples. + The default value is False. + dtype (str|numpy.dtype, optional): When init is None, it is used to set the + data type of memory. The default value is "float32". Optional data types + are: "float32", "float64", "int32", "int64". + + Returns: + Variable: The memory LoDTensor after shrank. If there are :code:`num_sequences` \ + sequences in RNN's input LoDTensor whose length is larger than :code:`step_idx` , \ + the memory Tensor also need to be shrank and will only retain data \ + corresponding to those :code:`num_sequences` sequences. + + Raises: + ValueError: When :code:`memory()` is called outside :code:`block()` . + TypeError: When init is set and is not a Variable. + ValueError: When :code:`memory()` is called before :code:`step_input()` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + sentence = fluid.data(name='sentence', shape=[None, 32], dtype='float32', lod_level=1) + boot_memory = fluid.data(name='boot', shape=[None, 10], dtype='float32') + + drnn = fluid.layers.DynamicRNN() + with drnn.block(): + # Set sentence as RNN's input, each time step processes a word from the sentence + word = drnn.step_input(sentence) + # Initialize memory with boot_memory, which need reorder according to RNN's input sequences + memory = drnn.memory(init=boot_memory, need_reorder=True) + hidden = fluid.layers.fc(input=[word, memory], size=10, act='tanh') + # Update memory with hidden + drnn.update_memory(ex_mem=memory, new_mem=hidden) + # Set hidden as RNN's output + drnn.output(hidden) + + # Get RNN's result + rnn_output = drnn() + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + sentence = fluid.data(name='sentence', shape=[None, 32], dtype='float32', lod_level=1) + + drnn = fluid.layers.DynamicRNN() + with drnn.block(): + # Set sentence as RNN's input, each time step processes a word from the sentence + word = drnn.step_input(sentence) + # Initialize memory to a Tensor whose value is 0, shape=[batch_size, 10], + # where batch_size is the number of sequences in sentence. + memory = drnn.memory(shape=[10], dtype='float32', value=0) + hidden = fluid.layers.fc(input=[word, memory], size=10, act='tanh') + # Update memory with hidden + drnn.update_memory(ex_mem=memory, new_mem=hidden) + # Set hidden as RNN's output + drnn.output(hidden) + + # Get RNN's result + rnn_output = drnn() + """ + self._assert_in_rnn_block_('memory') + self._init_zero_idx_() + if shape is not None: + check_type( + shape, + 'shape', + (list, tuple), + 'fluid.layers.DynamicRNN.memory()', + ) + if init is not None: + check_type( + init, 'init', Variable, 'fluid.layers.DynamicRNN.memory()' + ) + parent_block = self._parent_block_() + init_tensor = init + if need_reorder == True: + if self.lod_rank_table is None: + raise ValueError( + 'If set need_reorder to True, make sure step_input be ' + 'invoked before ' + 'memory(init=init, need_reordered=True, ...).' + ) + init_reordered = parent_block.create_var( + name=unique_name.generate('dynamic_rnn_mem_init_reordered'), + type=core.VarDesc.VarType.LOD_TENSOR, + dtype=init.dtype, + ) + parent_block.append_op( + type='reorder_lod_tensor_by_rank', + inputs={ + 'X': [init_tensor], + 'RankTable': [self.lod_rank_table], + }, + outputs={'Out': [init_reordered]}, + ) + init_tensor = init_reordered + mem_array = parent_block.create_var( + name=unique_name.generate('dynamic_rnn_mem_array'), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=init.dtype, + ) + parent_block.append_op( + type='write_to_array', + inputs={'X': init_tensor, 'I': self.zero_idx}, + outputs={'Out': mem_array}, + ) + retv = array_read(array=mem_array, i=self.step_idx) + retv = shrink_memory( + x=retv, i=self.step_idx, table=self.lod_rank_table + ) + self.mem_dict[retv.name] = mem_array + return retv + else: + if len(self.input_array) == 0: + raise ValueError( + "step_input should be invoked before memory(shape=..., value=...)" + ) + parent_block = self._parent_block_() + init = parent_block.create_var( + name=unique_name.generate('mem_init'), dtype=dtype + ) + arr, dtype = self.input_array[0] + in0 = parent_block.create_var( + name=unique_name.generate('in0'), dtype=dtype + ) + parent_block.append_op( + type='read_from_array', + inputs={'X': [arr], 'I': [self.zero_idx]}, + outputs={'Out': [in0]}, + ) + parent_block.append_op( + type='fill_constant_batch_size_like', + inputs={'Input': [in0]}, + outputs={'Out': [init]}, + attrs={ + 'shape': [-1] + shape, + 'value': float(value), + 'dtype': init.dtype, + }, + ) + return self.memory(init=init) + + def update_memory(self, ex_mem, new_mem): + """ + Update the memory which need to be delivered across time steps. + + Args: + ex_mem (Variable): The memory data of previous time step. + new_mem (Variable): The new memory data produced in current time step. + The shape and data type of ex_mem and new_mem should be the same. + + Returns: + None + + Raises: + ValueError: When :code:`update_memory()` is called outside :code:`block()` . + TypeError: When :code:`ex_mem` or :code:`new_mem` is not a Variable. + ValueError: When :code:`ex_mem` is defined by :code:`memory()` . + ValueError: When :code:`update_memory()` is called before :code:`step_input()` . + """ + self._assert_in_rnn_block_('update_memory') + check_type( + ex_mem, + 'ex_mem', + Variable, + 'fluid.layers.DynamicRNN.update_memory()', + ) + check_type( + new_mem, + 'new_mem', + Variable, + 'fluid.layers.DynamicRNN.update_memory()', + ) + + mem_array = self.mem_dict.get(ex_mem.name, None) + if mem_array is None: + raise ValueError("Please invoke memory before update_memory") + if self.lod_rank_table is None: + raise ValueError("Please invoke step_input before update_memory") + + self.mem_link.append((new_mem, mem_array)) + + def output(self, *outputs): + """ + This function is used to set :code:`outputs` as RNN's output. + + Args: + *outputs (Variable ...): The output Tensor. DynamicRNN can mark multiple + Variables as its output. + + Returns: + None + + Raises: + ValueError: When :code:`output()` is called outside :code:`block()` . + """ + self._assert_in_rnn_block_('output') + parent_block = self._parent_block_() + for each in outputs: + check_type( + each, "outputs", Variable, "fluid.layers.DynamicRNN.output" + ) + outside_array = parent_block.create_var( + name=unique_name.generate_with_ignorable_key( + "_".join([self.helper.name, "output_array", each.name]) + ), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=each.dtype, + ) + array_write(x=each, i=self.step_idx, array=outside_array) + self.output_array.append(outside_array) + + def _init_zero_idx_(self): + if self.zero_idx is None: + parent_block = self._parent_block_() + self.zero_idx = parent_block.create_var( + name=unique_name.generate('zero_idx'), dtype='int64' + ) + parent_block.append_op( + type='fill_constant', + inputs={}, + outputs={'Out': [self.zero_idx]}, + attrs={ + 'shape': [1], + 'dtype': self.zero_idx.dtype, + 'value': float(0), + 'force_cpu': True, + }, + ) + + def _parent_block_(self): + prog = self.helper.main_program + parent_idx = prog.current_block().parent_idx + assert parent_idx >= 0 + parent_block = prog.block(parent_idx) + + return parent_block + + def _assert_in_rnn_block_(self, method): + if self.status != DynamicRNN.IN_RNN: + raise ValueError( + "{0} can only be invoked inside rnn block.".format(method) + ) + + +def switch_case(branch_index, branch_fns, default=None, name=None): + ''' + :api_attr: Static Graph + + This operator is like a C++ switch/case statement. + + Args: + branch_index(Tensor): A Tensor with shape [1] to specify which branch to execute. The data type is ``int32``, ``int64`` or ``uint8``. + branch_fns(dict|list|tuple): If it's a list or tuple, the elements in it could be pairs of (int, callable) or simple callables whose actual index will be used as the index of callable. If it's a dict, its key is a python integer and the value is a callable. All callables return the same structure of Tensors. + default(callable, optional): Callable that returns a structure of Tensors. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor|list(Tensor): Tensors returned by the callable specified by ``branch_index`` in ``branch_fns``, + or Tensors returned by ``default`` if ``default`` is not None and no index matches in ``branch_fns``, + or Tensors returned by the callable with the max index in ``branch_fns`` if ``default`` is None and no index matches in ``branch_fns``. + + Raises: + TypeError: If the type of ``branch_index`` is not Tensor. + TypeError: If the data type of ``branch_index`` is not ``int32``, ``int64`` or ``uint8``. + TypeError: If the type of ``branch_fns`` is not dict, list or tuple. + TypeError: If the elements of ``branch_fns`` is not 2-tuple. + TypeError: If the first element of 2-tuple in ``branch_fns`` is not integer. + ValueError: If the first element of 2-tuple in ``branch_fns`` is not unique. + TypeError: If the second element of 2-tuple in ``branch_fns`` is not callable. + TypeError: If ``default`` is not None but it is not callable. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + def fn_1(): + return paddle.full(shape=[1, 2], dtype='float32', fill_value=1) + + def fn_2(): + return paddle.full(shape=[2, 2], dtype='int32', fill_value=2) + + def fn_3(): + return paddle.full(shape=[3], dtype='int32', fill_value=3) + + main_program = paddle.static.default_startup_program() + startup_program = paddle.static.default_main_program() + with paddle.static.program_guard(main_program, startup_program): + index_1 = paddle.full(shape=[1], dtype='int32', fill_value=1) + index_2 = paddle.full(shape=[1], dtype='int32', fill_value=2) + + out_1 = paddle.static.nn.switch_case( + branch_index=index_1, + branch_fns={1: fn_1, 2: fn_2}, + default=fn_3) + + out_2 = paddle.static.nn.switch_case( + branch_index=index_2, + branch_fns=[(1, fn_1), (2, fn_2)], + default=fn_3) + + # Argument default is None and no index matches. fn_3 will be called because of the max index 7. + out_3 = paddle.static.nn.switch_case( + branch_index=index_2, + branch_fns=[(0, fn_1), (4, fn_2), (7, fn_3)]) + + exe = paddle.static.Executor(paddle.CPUPlace()) + res_1, res_2, res_3 = exe.run(main_program, fetch_list=[out_1, out_2, out_3]) + print(res_1) # [[1. 1.]] + print(res_2) # [[2 2] [2 2]] + print(res_3) # [3 3 3] + ''' + helper = LayerHelper('switch_case', **locals()) + + def _check_args(branch_index, branch_fns, default): + + check_variable_and_dtype( + branch_index, + 'branch_index', + ['uint8', 'int32', 'int64'], + 'switch_case', + ) + + if convert_dtype(branch_index.dtype) != "int64": + branch_index = cast(branch_index, "int64") + + check_type(branch_fns, 'branch_fns', (list, tuple, dict), 'switch_case') + + branch_fns = ( + branch_fns.items() if isinstance(branch_fns, dict) else branch_fns + ) + + branch_fns = ( + list(enumerate(branch_fns)) + if all(callable(fn) for fn in branch_fns) + else branch_fns + ) + + keys_of_fns = [] + for index_fn_pair in branch_fns: + if not isinstance(index_fn_pair, tuple): + raise TypeError( + _error_message( + "The elements' type", + "branch_fns", + "switch_case", + tuple, + type(branch_fns), + ) + ) + + if len(index_fn_pair) != 2: + raise TypeError( + _error_message( + "The tuple's size", + "branch_fns", + "switch_case", + "2", + str(len(index_fn_pair)) + "-tuple", + ) + ) + + key, fn = index_fn_pair + + if not isinstance(key, int): + raise TypeError( + _error_message( + "The key's type", + "branch_fns", + "switch_case", + int, + type(key), + ) + ) + + if key in keys_of_fns: + raise ValueError( + "The key in 'branch_fns' must be unique, but '{}' appears more than once.".format( + key + ) + ) + else: + keys_of_fns.append(key) + + if not callable(fn): + raise TypeError( + _error_message( + "The type of function for key {}".format(key), + "branch_fns", + "switch_case", + "callable", + type(fn), + ) + ) + + if default is None: + default = sorted(branch_fns)[-1][1] + branch_fns = sorted(branch_fns)[:-1] + elif not callable(default): + raise TypeError("The default in Op(case) must be callable.") + + pred_fn_pairs = [] + for index, fn in branch_fns: + new_index = fill_constant(shape=[1], dtype="int64", value=index) + pred = equal(branch_index, new_index) + pred_fn_pairs.append((pred, fn)) + + return pred_fn_pairs, default + + pred_fn_pairs, default = _check_args(branch_index, branch_fns, default) + false_fn = default + for pred, true_fn in pred_fn_pairs: + false_fn = partial(cond, pred=pred, true_fn=true_fn, false_fn=false_fn) + + final_fn = false_fn + return final_fn() + + +@templatedoc() +def reorder_lod_tensor_by_rank(x, rank_table): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment}. + rank_table(${rank_table_type}): ${rank_table_comment}. + + Returns: + out(${out_type}): ${out_comment}. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data_desc = (['input', [9], 0], ['ref', [5], 1]) + data = fluid.layers.data(name=data_desc[0][0], shape=data_desc[0][1]) + rank_data = fluid.layers.data(name=data_desc[1][0], shape=data_desc[1][1]) + table = fluid.layers.control_flow.lod_rank_table(rank_data) + new_data = fluid.layers.reorder_lod_tensor_by_rank( + x=data, rank_table=table) + + """ + + check_type(x, 'x', (Variable), 'reorder_lod_tensor_by_rank') + check_type( + rank_table, 'rank_table', (Variable), 'reorder_lod_tensor_by_rank' + ) + if rank_table.type != core.VarDesc.VarType.LOD_RANK_TABLE: + raise TypeError("The type of rank_table should be LOD_RANK_TABLE.") + + helper = LayerHelper('reorder_lod_tensor_by_rank', **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='reorder_lod_tensor_by_rank', + inputs={'X': [x], 'RankTable': [rank_table]}, + outputs={'Out': [out]}, + ) + return out + + +def is_empty(x, name=None): + """ + + Test whether a Tensor is empty. + + Args: + x (Tensor): The Tensor to be tested. + name (str, optional): The default value is ``None`` . Normally users + don't have to set this parameter. For more information, + please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: A bool scalar Tensor. True if 'x' is an empty Tensor. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand(shape=[4, 32, 32], dtype='float32') + res = paddle.is_empty(x=input) + print("res:", res) + # ('res:', Tensor: eager_tmp_1 + # - place: CPUPlace + # - shape: [1] + # - layout: NCHW + # - dtype: bool + # - data: [0]) + + """ + if in_dygraph_mode(): + return _C_ops.is_empty(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.is_empty(x) + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'is_empty' + ) + check_type(name, "name", (str, type(None)), "is_empty") + + helper = LayerHelper("is_empty", **locals()) + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + + helper.append_op( + type='is_empty', inputs={'X': [x]}, outputs={'Out': [cond]} + ) + return cond diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/detection.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/detection.py new file mode 100644 index 0000000000000000000000000000000000000000..8766e3982d673e4a8a88331934ed81231ee550ca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/detection.py @@ -0,0 +1,3877 @@ +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +All layers just related to the detection neural network. +""" + +from __future__ import print_function + +import paddle + +from .layer_function_generator import generate_layer_fn +from .layer_function_generator import autodoc, templatedoc +from ..layer_helper import LayerHelper +from ..framework import Variable, _non_static_mode, static_only, in_dygraph_mode +from .. import core +from .loss import softmax_with_cross_entropy +from . import tensor +from . import nn +from . import ops +from ... import compat as cpt +from ..data_feeder import check_variable_and_dtype, check_type, check_dtype +import math +import six +import numpy as np +from functools import reduce +from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype +from paddle.utils import deprecated +from paddle import _C_ops, _legacy_C_ops +from ..framework import in_dygraph_mode + +__all__ = [ + 'prior_box', + 'density_prior_box', + 'multi_box_head', + 'bipartite_match', + 'target_assign', + 'detection_output', + 'ssd_loss', + 'rpn_target_assign', + 'retinanet_target_assign', + 'sigmoid_focal_loss', + 'anchor_generator', + 'roi_perspective_transform', + 'generate_proposal_labels', + 'generate_proposals', + 'generate_mask_labels', + 'iou_similarity', + 'box_coder', + 'polygon_box_transform', + 'yolov3_loss', + 'yolo_box', + 'box_clip', + 'multiclass_nms', + 'locality_aware_nms', + 'matrix_nms', + 'retinanet_detection_output', + 'distribute_fpn_proposals', + 'box_decoder_and_assign', + 'collect_fpn_proposals', +] + + +def retinanet_target_assign(bbox_pred, + cls_logits, + anchor_box, + anchor_var, + gt_boxes, + gt_labels, + is_crowd, + im_info, + num_classes=1, + positive_overlap=0.5, + negative_overlap=0.4): + r""" + **Target Assign Layer for the detector RetinaNet.** + + This OP finds out positive and negative samples from all anchors + for training the detector `RetinaNet `_ , + and assigns target labels for classification along with target locations for + regression to each sample, then takes out the part belonging to positive and + negative samples from category prediction( :attr:`cls_logits`) and location + prediction( :attr:`bbox_pred`) which belong to all anchors. + + The searching principles for positive and negative samples are as followed: + + 1. Anchors are assigned to ground-truth boxes when it has the highest IoU + overlap with a ground-truth box. + + 2. Anchors are assigned to ground-truth boxes when it has an IoU overlap + higher than :attr:`positive_overlap` with any ground-truth box. + + 3. Anchors are assigned to background when its IoU overlap is lower than + :attr:`negative_overlap` for all ground-truth boxes. + + 4. Anchors which do not meet the above conditions do not participate in + the training process. + + Retinanet predicts a :math:`C`-vector for classification and a 4-vector for box + regression for each anchor, hence the target label for each positive(or negative) + sample is a :math:`C`-vector and the target locations for each positive sample + is a 4-vector. As for a positive sample, if the category of its assigned + ground-truth box is class :math:`i`, the corresponding entry in its length + :math:`C` label vector is set to 1 and all other entries is set to 0, its box + regression targets are computed as the offset between itself and its assigned + ground-truth box. As for a negative sample, all entries in its length :math:`C` + label vector are set to 0 and box regression targets are omitted because + negative samples do not participate in the training process of location + regression. + + After the assignment, the part belonging to positive and negative samples is + taken out from category prediction( :attr:`cls_logits` ), and the part + belonging to positive samples is taken out from location + prediction( :attr:`bbox_pred` ). + + Args: + bbox_pred(Variable): A 3-D Tensor with shape :math:`[N, M, 4]` represents + the predicted locations of all anchors. :math:`N` is the batch size( the + number of images in a mini-batch), :math:`M` is the number of all anchors + of one image, and each anchor has 4 coordinate values. The data type of + :attr:`bbox_pred` is float32 or float64. + cls_logits(Variable): A 3-D Tensor with shape :math:`[N, M, C]` represents + the predicted categories of all anchors. :math:`N` is the batch size, + :math:`M` is the number of all anchors of one image, and :math:`C` is + the number of categories (**Notice: excluding background**). The data type + of :attr:`cls_logits` is float32 or float64. + anchor_box(Variable): A 2-D Tensor with shape :math:`[M, 4]` represents + the locations of all anchors. :math:`M` is the number of all anchors of + one image, each anchor is represented as :math:`[xmin, ymin, xmax, ymax]`, + :math:`[xmin, ymin]` is the left top coordinate of the anchor box, + :math:`[xmax, ymax]` is the right bottom coordinate of the anchor box. + The data type of :attr:`anchor_box` is float32 or float64. Please refer + to the OP :ref:`api_fluid_layers_anchor_generator` + for the generation of :attr:`anchor_box`. + anchor_var(Variable): A 2-D Tensor with shape :math:`[M,4]` represents the expanded + factors of anchor locations used in loss function. :math:`M` is number of + all anchors of one image, each anchor possesses a 4-vector expanded factor. + The data type of :attr:`anchor_var` is float32 or float64. Please refer + to the OP :ref:`api_fluid_layers_anchor_generator` + for the generation of :attr:`anchor_var`. + gt_boxes(Variable): A 1-level 2-D LoDTensor with shape :math:`[G, 4]` represents + locations of all ground-truth boxes. :math:`G` is the total number of + all ground-truth boxes in a mini-batch, and each ground-truth box has 4 + coordinate values. The data type of :attr:`gt_boxes` is float32 or + float64. + gt_labels(variable): A 1-level 2-D LoDTensor with shape :math:`[G, 1]` represents + categories of all ground-truth boxes, and the values are in the range of + :math:`[1, C]`. :math:`G` is the total number of all ground-truth boxes + in a mini-batch, and each ground-truth box has one category. The data type + of :attr:`gt_labels` is int32. + is_crowd(Variable): A 1-level 1-D LoDTensor with shape :math:`[G]` which + indicates whether a ground-truth box is a crowd. If the value is 1, the + corresponding box is a crowd, it is ignored during training. :math:`G` is + the total number of all ground-truth boxes in a mini-batch. The data type + of :attr:`is_crowd` is int32. + im_info(Variable): A 2-D Tensor with shape [N, 3] represents the size + information of input images. :math:`N` is the batch size, the size + information of each image is a 3-vector which are the height and width + of the network input along with the factor scaling the origin image to + the network input. The data type of :attr:`im_info` is float32. + num_classes(int32): The number of categories for classification, the default + value is 1. + positive_overlap(float32): Minimum overlap required between an anchor + and ground-truth box for the anchor to be a positive sample, the default + value is 0.5. + negative_overlap(float32): Maximum overlap allowed between an anchor + and ground-truth box for the anchor to be a negative sample, the default + value is 0.4. :attr:`negative_overlap` should be less than or equal to + :attr:`positive_overlap`, if not, the actual value of + :attr:`positive_overlap` is :attr:`negative_overlap`. + + Returns: + A tuple with 6 Variables: + + **predict_scores** (Variable): A 2-D Tensor with shape :math:`[F+B, C]` represents + category prediction belonging to positive and negative samples. :math:`F` + is the number of positive samples in a mini-batch, :math:`B` is the number + of negative samples, and :math:`C` is the number of categories + (**Notice: excluding background**). The data type of :attr:`predict_scores` + is float32 or float64. + + **predict_location** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents + location prediction belonging to positive samples. :math:`F` is the number + of positive samples. :math:`F` is the number of positive samples, and each + sample has 4 coordinate values. The data type of :attr:`predict_location` + is float32 or float64. + + **target_label** (Variable): A 2-D Tensor with shape :math:`[F+B, 1]` represents + target labels for classification belonging to positive and negative + samples. :math:`F` is the number of positive samples, :math:`B` is the + number of negative, and each sample has one target category. The data type + of :attr:`target_label` is int32. + + **target_bbox** (Variable): A 2-D Tensor with shape :math:`[F, 4]` represents + target locations for box regression belonging to positive samples. + :math:`F` is the number of positive samples, and each sample has 4 + coordinate values. The data type of :attr:`target_bbox` is float32 or + float64. + + **bbox_inside_weight** (Variable): A 2-D Tensor with shape :math:`[F, 4]` + represents whether a positive sample is fake positive, if a positive + sample is false positive, the corresponding entries in + :attr:`bbox_inside_weight` are set 0, otherwise 1. :math:`F` is the number + of total positive samples in a mini-batch, and each sample has 4 + coordinate values. The data type of :attr:`bbox_inside_weight` is float32 + or float64. + + **fg_num** (Variable): A 2-D Tensor with shape :math:`[N, 1]` represents the number + of positive samples. :math:`N` is the batch size. **Notice: The number + of positive samples is used as the denominator of later loss function, + to avoid the condition that the denominator is zero, this OP has added 1 + to the actual number of positive samples of each image.** The data type of + :attr:`fg_num` is int32. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + bbox_pred = fluid.data(name='bbox_pred', shape=[1, 100, 4], + dtype='float32') + cls_logits = fluid.data(name='cls_logits', shape=[1, 100, 10], + dtype='float32') + anchor_box = fluid.data(name='anchor_box', shape=[100, 4], + dtype='float32') + anchor_var = fluid.data(name='anchor_var', shape=[100, 4], + dtype='float32') + gt_boxes = fluid.data(name='gt_boxes', shape=[10, 4], + dtype='float32') + gt_labels = fluid.data(name='gt_labels', shape=[10, 1], + dtype='int32') + is_crowd = fluid.data(name='is_crowd', shape=[1], + dtype='int32') + im_info = fluid.data(name='im_info', shape=[1, 3], + dtype='float32') + score_pred, loc_pred, score_target, loc_target, bbox_inside_weight, fg_num = \\ + fluid.layers.retinanet_target_assign(bbox_pred, cls_logits, anchor_box, + anchor_var, gt_boxes, gt_labels, is_crowd, im_info, 10) + + """ + + check_variable_and_dtype(bbox_pred, 'bbox_pred', ['float32', 'float64'], + 'retinanet_target_assign') + check_variable_and_dtype(cls_logits, 'cls_logits', ['float32', 'float64'], + 'retinanet_target_assign') + check_variable_and_dtype(anchor_box, 'anchor_box', ['float32', 'float64'], + 'retinanet_target_assign') + check_variable_and_dtype(anchor_var, 'anchor_var', ['float32', 'float64'], + 'retinanet_target_assign') + check_variable_and_dtype(gt_boxes, 'gt_boxes', ['float32', 'float64'], + 'retinanet_target_assign') + check_variable_and_dtype(gt_labels, 'gt_labels', ['int32'], + 'retinanet_target_assign') + check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'], + 'retinanet_target_assign') + check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], + 'retinanet_target_assign') + + helper = LayerHelper('retinanet_target_assign', **locals()) + # Assign target label to anchors + loc_index = helper.create_variable_for_type_inference(dtype='int32') + score_index = helper.create_variable_for_type_inference(dtype='int32') + target_label = helper.create_variable_for_type_inference(dtype='int32') + target_bbox = helper.create_variable_for_type_inference( + dtype=anchor_box.dtype) + bbox_inside_weight = helper.create_variable_for_type_inference( + dtype=anchor_box.dtype) + fg_num = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op(type="retinanet_target_assign", + inputs={ + 'Anchor': anchor_box, + 'GtBoxes': gt_boxes, + 'GtLabels': gt_labels, + 'IsCrowd': is_crowd, + 'ImInfo': im_info + }, + outputs={ + 'LocationIndex': loc_index, + 'ScoreIndex': score_index, + 'TargetLabel': target_label, + 'TargetBBox': target_bbox, + 'BBoxInsideWeight': bbox_inside_weight, + 'ForegroundNumber': fg_num + }, + attrs={ + 'positive_overlap': positive_overlap, + 'negative_overlap': negative_overlap + }) + + loc_index.stop_gradient = True + score_index.stop_gradient = True + target_label.stop_gradient = True + target_bbox.stop_gradient = True + bbox_inside_weight.stop_gradient = True + fg_num.stop_gradient = True + + cls_logits = nn.reshape(x=cls_logits, shape=(-1, num_classes)) + bbox_pred = nn.reshape(x=bbox_pred, shape=(-1, 4)) + predicted_cls_logits = nn.gather(cls_logits, score_index) + predicted_bbox_pred = nn.gather(bbox_pred, loc_index) + + return predicted_cls_logits, predicted_bbox_pred, target_label, target_bbox, bbox_inside_weight, fg_num + + +def rpn_target_assign(bbox_pred, + cls_logits, + anchor_box, + anchor_var, + gt_boxes, + is_crowd, + im_info, + rpn_batch_size_per_im=256, + rpn_straddle_thresh=0.0, + rpn_fg_fraction=0.5, + rpn_positive_overlap=0.7, + rpn_negative_overlap=0.3, + use_random=True): + """ + **Target Assign Layer for region proposal network (RPN) in Faster-RCNN detection.** + + This layer can be, for given the Intersection-over-Union (IoU) overlap + between anchors and ground truth boxes, to assign classification and + regression targets to each each anchor, these target labels are used for + train RPN. The classification targets is a binary class label (of being + an object or not). Following the paper of Faster-RCNN, the positive labels + are two kinds of anchors: (i) the anchor/anchors with the highest IoU + overlap with a ground-truth box, or (ii) an anchor that has an IoU overlap + higher than rpn_positive_overlap(0.7) with any ground-truth box. Note + that a single ground-truth box may assign positive labels to multiple + anchors. A non-positive anchor is when its IoU ratio is lower than + rpn_negative_overlap (0.3) for all ground-truth boxes. Anchors that are + neither positive nor negative do not contribute to the training objective. + The regression targets are the encoded ground-truth boxes associated with + the positive anchors. + + Args: + bbox_pred(Variable): A 3-D Tensor with shape [N, M, 4] represents the + predicted locations of M bounding bboxes. N is the batch size, + and each bounding box has four coordinate values and the layout + is [xmin, ymin, xmax, ymax]. The data type can be float32 or float64. + cls_logits(Variable): A 3-D Tensor with shape [N, M, 1] represents the + predicted confidence predictions. N is the batch size, 1 is the + frontground and background sigmoid, M is number of bounding boxes. + The data type can be float32 or float64. + anchor_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes, + each box is represented as [xmin, ymin, xmax, ymax], + [xmin, ymin] is the left top coordinate of the anchor box, + if the input is image feature map, they are close to the origin + of the coordinate system. [xmax, ymax] is the right bottom + coordinate of the anchor box. The data type can be float32 or float64. + anchor_var(Variable): A 2-D Tensor with shape [M,4] holds expanded + variances of anchors. The data type can be float32 or float64. + gt_boxes (Variable): The ground-truth bounding boxes (bboxes) are a 2D + LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth + bboxes of mini-batch input. The data type can be float32 or float64. + is_crowd (Variable): A 1-D LoDTensor which indicates groud-truth is crowd. + The data type must be int32. + im_info (Variable): A 2-D LoDTensor with shape [N, 3]. N is the batch size, + 3 is the height, width and scale. + rpn_batch_size_per_im(int): Total number of RPN examples per image. + The data type must be int32. + rpn_straddle_thresh(float): Remove RPN anchors that go outside the image + by straddle_thresh pixels. The data type must be float32. + rpn_fg_fraction(float): Target fraction of RoI minibatch that is labeled + foreground (i.e. class > 0), 0-th class is background. The data type must be float32. + rpn_positive_overlap(float): Minimum overlap required between an anchor + and ground-truth box for the (anchor, gt box) pair to be a positive + example. The data type must be float32. + rpn_negative_overlap(float): Maximum overlap allowed between an anchor + and ground-truth box for the (anchor, gt box) pair to be a negative + examples. The data type must be float32. + + Returns: + tuple: + A tuple(predicted_scores, predicted_location, target_label, + target_bbox, bbox_inside_weight) is returned. The predicted_scores + and predicted_location is the predicted result of the RPN. + The target_label and target_bbox is the ground truth, + respectively. The predicted_location is a 2D Tensor with shape + [F, 4], and the shape of target_bbox is same as the shape of + the predicted_location, F is the number of the foreground + anchors. The predicted_scores is a 2D Tensor with shape + [F + B, 1], and the shape of target_label is same as the shape + of the predicted_scores, B is the number of the background + anchors, the F and B is depends on the input of this operator. + Bbox_inside_weight represents whether the predicted loc is fake_fg + or not and the shape is [F, 4]. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + bbox_pred = fluid.data(name='bbox_pred', shape=[None, 4], dtype='float32') + cls_logits = fluid.data(name='cls_logits', shape=[None, 1], dtype='float32') + anchor_box = fluid.data(name='anchor_box', shape=[None, 4], dtype='float32') + anchor_var = fluid.data(name='anchor_var', shape=[None, 4], dtype='float32') + gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32') + is_crowd = fluid.data(name='is_crowd', shape=[None], dtype='float32') + im_info = fluid.data(name='im_infoss', shape=[None, 3], dtype='float32') + loc, score, loc_target, score_target, inside_weight = fluid.layers.rpn_target_assign( + bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, is_crowd, im_info) + + """ + + helper = LayerHelper('rpn_target_assign', **locals()) + + check_variable_and_dtype(bbox_pred, 'bbox_pred', ['float32', 'float64'], + 'rpn_target_assign') + check_variable_and_dtype(cls_logits, 'cls_logits', ['float32', 'float64'], + 'rpn_target_assign') + check_variable_and_dtype(anchor_box, 'anchor_box', ['float32', 'float64'], + 'rpn_target_assign') + check_variable_and_dtype(anchor_var, 'anchor_var', ['float32', 'float64'], + 'rpn_target_assign') + check_variable_and_dtype(gt_boxes, 'gt_boxes', ['float32', 'float64'], + 'rpn_target_assign') + check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'], + 'rpn_target_assign') + check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], + 'rpn_target_assign') + + # Assign target label to anchors + loc_index = helper.create_variable_for_type_inference(dtype='int32') + score_index = helper.create_variable_for_type_inference(dtype='int32') + target_label = helper.create_variable_for_type_inference(dtype='int32') + target_bbox = helper.create_variable_for_type_inference( + dtype=anchor_box.dtype) + bbox_inside_weight = helper.create_variable_for_type_inference( + dtype=anchor_box.dtype) + helper.append_op(type="rpn_target_assign", + inputs={ + 'Anchor': anchor_box, + 'GtBoxes': gt_boxes, + 'IsCrowd': is_crowd, + 'ImInfo': im_info + }, + outputs={ + 'LocationIndex': loc_index, + 'ScoreIndex': score_index, + 'TargetLabel': target_label, + 'TargetBBox': target_bbox, + 'BBoxInsideWeight': bbox_inside_weight + }, + attrs={ + 'rpn_batch_size_per_im': rpn_batch_size_per_im, + 'rpn_straddle_thresh': rpn_straddle_thresh, + 'rpn_positive_overlap': rpn_positive_overlap, + 'rpn_negative_overlap': rpn_negative_overlap, + 'rpn_fg_fraction': rpn_fg_fraction, + 'use_random': use_random + }) + + loc_index.stop_gradient = True + score_index.stop_gradient = True + target_label.stop_gradient = True + target_bbox.stop_gradient = True + bbox_inside_weight.stop_gradient = True + + cls_logits = nn.reshape(x=cls_logits, shape=(-1, 1)) + bbox_pred = nn.reshape(x=bbox_pred, shape=(-1, 4)) + predicted_cls_logits = nn.gather(cls_logits, score_index) + predicted_bbox_pred = nn.gather(bbox_pred, loc_index) + + return predicted_cls_logits, predicted_bbox_pred, target_label, target_bbox, bbox_inside_weight + + +def sigmoid_focal_loss(x, label, fg_num, gamma=2.0, alpha=0.25): + r""" + :alias_main: paddle.nn.functional.sigmoid_focal_loss + :alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss + :old_api: paddle.fluid.layers.sigmoid_focal_loss + + **Sigmoid Focal Loss Operator.** + + `Focal Loss `_ is used to address the foreground-background + class imbalance existed on the training phase of many computer vision tasks. This OP computes + the sigmoid value for each element in the input tensor :attr:`x`, after which focal loss is + measured between the sigmoid value and target label. + + The focal loss is given as followed: + + .. math:: + + \\mathop{loss_{i,\\,j}}\\limits_{i\\in\\mathbb{[0,\\,N-1]},\\,j\\in\\mathbb{[0,\\,C-1]}}=\\left\\{ + \\begin{array}{rcl} + - \\frac{1}{fg\_num} * \\alpha * {(1 - \\sigma(x_{i,\\,j}))}^{\\gamma} * \\log(\\sigma(x_{i,\\,j})) & & {(j +1) = label_{i,\\,0}} \\\\ + - \\frac{1}{fg\_num} * (1 - \\alpha) * {\sigma(x_{i,\\,j})}^{ \\gamma} * \\log(1 - \\sigma(x_{i,\\,j})) & & {(j +1)!= label_{i,\\,0}} + \\end{array} \\right. + + + We know that + + .. math:: + \\sigma(x_j) = \\frac{1}{1 + \\exp(-x_j)} + + + Args: + x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of + all samples. :math:`N` is the number of all samples responsible for optimization in + a mini-batch, for example, samples are anchor boxes for object detection and :math:`N` + is the total number of positive and negative samples in a mini-batch; Samples are images + for image classification and :math:`N` is the number of images in a mini-batch. :math:`C` + is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is + float32 or float64. + label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for + classification. :math:`N` is the number of all samples responsible for optimization in a + mini-batch, each sample has one target category. The values for positive samples are in the + range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label` + is int32. + fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a + mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32. + gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is + set to 2.0. + alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value + is set to 0.25. + + Returns: + Variable(the data type is float32 or float64): + A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input + tensor :attr:`x`. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + num_classes = 10 # exclude background + image_width = 16 + image_height = 16 + batch_size = 32 + max_iter = 20 + + + def gen_train_data(): + x_data = np.random.uniform(0, 255, (batch_size, 3, image_height, + image_width)).astype('float64') + label_data = np.random.randint(0, num_classes, + (batch_size, 1)).astype('int32') + return {"x": x_data, "label": label_data} + + + def get_focal_loss(pred, label, fg_num, num_classes): + pred = fluid.layers.reshape(pred, [-1, num_classes]) + label = fluid.layers.reshape(label, [-1, 1]) + label.stop_gradient = True + loss = fluid.layers.sigmoid_focal_loss( + pred, label, fg_num, gamma=2.0, alpha=0.25) + loss = fluid.layers.reduce_sum(loss) + return loss + + + def build_model(mode='train'): + x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype='float64') + output = fluid.layers.pool2d(input=x, pool_type='avg', global_pooling=True) + output = fluid.layers.fc( + input=output, + size=num_classes, + # Notice: size is set to be the number of target classes (excluding backgorund) + # because sigmoid activation will be done in the sigmoid_focal_loss op. + act=None) + if mode == 'train': + label = fluid.data(name="label", shape=[-1, 1], dtype='int32') + # Obtain the fg_num needed by the sigmoid_focal_loss op: + # 0 in label represents background, >=1 in label represents foreground, + # find the elements in label which are greater or equal than 1, then + # computed the numbers of these elements. + data = fluid.layers.fill_constant(shape=[1], value=1, dtype='int32') + fg_label = fluid.layers.greater_equal(label, data) + fg_label = fluid.layers.cast(fg_label, dtype='int32') + fg_num = fluid.layers.reduce_sum(fg_label) + fg_num.stop_gradient = True + avg_loss = get_focal_loss(output, label, fg_num, num_classes) + return avg_loss + else: + # During evaluating or testing phase, + # output of the final fc layer should be connected to a sigmoid layer. + pred = fluid.layers.sigmoid(output) + return pred + + + loss = build_model('train') + moment_optimizer = fluid.optimizer.MomentumOptimizer( + learning_rate=0.001, momentum=0.9) + moment_optimizer.minimize(loss) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for i in range(max_iter): + outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name]) + print(outs) + """ + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], + 'sigmoid_focal_loss') + check_variable_and_dtype(label, 'label', ['int32'], 'sigmoid_focal_loss') + check_variable_and_dtype(fg_num, 'fg_num', ['int32'], 'sigmoid_focal_loss') + + helper = LayerHelper("sigmoid_focal_loss", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type="sigmoid_focal_loss", + inputs={ + "X": x, + "Label": label, + "FgNum": fg_num + }, + attrs={ + "gamma": gamma, + 'alpha': alpha + }, + outputs={"Out": out}) + return out + + +def detection_output(loc, + scores, + prior_box, + prior_box_var, + background_label=0, + nms_threshold=0.3, + nms_top_k=400, + keep_top_k=200, + score_threshold=0.01, + nms_eta=1.0, + return_index=False): + """ + + Given the regression locations, classification confidences and prior boxes, + calculate the detection outputs by performing following steps: + + 1. Decode input bounding box predictions according to the prior boxes and + regression locations. + 2. Get the final detection results by applying multi-class non maximum + suppression (NMS). + + Please note, this operation doesn't clip the final output bounding boxes + to the image window. + + Args: + loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the + predicted locations of M bounding bboxes. Data type should be + float32 or float64. N is the batch size, + and each bounding box has four coordinate values and the layout + is [xmin, ymin, xmax, ymax]. + scores(Variable): A 3-D Tensor with shape [N, M, C] represents the + predicted confidence predictions. Data type should be float32 + or float64. N is the batch size, C is the + class number, M is number of bounding boxes. + prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes, + each box is represented as [xmin, ymin, xmax, ymax]. Data type + should be float32 or float64. + prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group + of variance. Data type should be float32 or float64. + background_label(int): The index of background label, + the background label will be ignored. If set to -1, then all + categories will be considered. Default: 0. + nms_threshold(float): The threshold to be used in NMS. Default: 0.3. + nms_top_k(int): Maximum number of detections to be kept according + to the confidences after filtering detections based on + score_threshold and before NMS. Default: 400. + keep_top_k(int): Number of total bboxes to be kept per image after + NMS step. -1 means keeping all bboxes after NMS step. Default: 200. + score_threshold(float): Threshold to filter out bounding boxes with + low confidence score. If not provided, consider all boxes. + Default: 0.01. + nms_eta(float): The parameter for adaptive NMS. It works only when the + value is less than 1.0. Default: 1.0. + return_index(bool): Whether return selected index. Default: False + + Returns: + + A tuple with two Variables: (Out, Index) if return_index is True, + otherwise, a tuple with one Variable(Out) is returned. + + Out (Variable): The detection outputs is a LoDTensor with shape [No, 6]. + Data type is the same as input (loc). Each row has six values: + [label, confidence, xmin, ymin, xmax, ymax]. `No` is + the total number of detections in this mini-batch. For each instance, + the offsets in first dimension are called LoD, the offset number is + N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]` + detected results, if it is 0, the i-th image has no detected results. + + Index (Variable): Only return when return_index is True. A 2-D LoDTensor + with shape [No, 1] represents the selected index which type is Integer. + The index is the absolute value cross batches. No is the same number + as Out. If the index is used to gather other attribute such as age, + one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where + N is the batch size and M is the number of boxes. + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + + pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32') + pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32') + loc = fluid.data(name='target_box', shape=[2, 21, 4], dtype='float32') + scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32') + nmsed_outs, index = fluid.layers.detection_output(scores=scores, + loc=loc, + prior_box=pb, + prior_box_var=pbv, + return_index=True) + """ + helper = LayerHelper("detection_output", **locals()) + decoded_box = box_coder(prior_box=prior_box, + prior_box_var=prior_box_var, + target_box=loc, + code_type='decode_center_size') + scores = nn.softmax(input=scores) + scores = nn.transpose(scores, perm=[0, 2, 1]) + scores.stop_gradient = True + nmsed_outs = helper.create_variable_for_type_inference( + dtype=decoded_box.dtype) + if return_index: + index = helper.create_variable_for_type_inference(dtype='int') + helper.append_op(type="multiclass_nms2", + inputs={ + 'Scores': scores, + 'BBoxes': decoded_box + }, + outputs={ + 'Out': nmsed_outs, + 'Index': index + }, + attrs={ + 'background_label': 0, + 'nms_threshold': nms_threshold, + 'nms_top_k': nms_top_k, + 'keep_top_k': keep_top_k, + 'score_threshold': score_threshold, + 'nms_eta': 1.0, + }) + index.stop_gradient = True + else: + helper.append_op(type="multiclass_nms", + inputs={ + 'Scores': scores, + 'BBoxes': decoded_box + }, + outputs={'Out': nmsed_outs}, + attrs={ + 'background_label': 0, + 'nms_threshold': nms_threshold, + 'nms_top_k': nms_top_k, + 'keep_top_k': keep_top_k, + 'score_threshold': score_threshold, + 'nms_eta': 1.0, + }) + nmsed_outs.stop_gradient = True + if return_index: + return nmsed_outs, index + return nmsed_outs + + +@templatedoc() +def iou_similarity(x, y, box_normalized=True, name=None): + """ + :alias_main: paddle.nn.functional.iou_similarity + :alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity + :old_api: paddle.fluid.layers.iou_similarity + + ${comment} + + Args: + x (Variable): ${x_comment}.The data type is float32 or float64. + y (Variable): ${y_comment}.The data type is float32 or float64. + box_normalized(bool): Whether treat the priorbox as a normalized box. + Set true by default. + Returns: + Variable: ${out_comment}.The data type is same with x. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + use_gpu = False + place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() + exe = fluid.Executor(place) + + x = fluid.data(name='x', shape=[None, 4], dtype='float32') + y = fluid.data(name='y', shape=[None, 4], dtype='float32') + iou = fluid.layers.iou_similarity(x=x, y=y) + + exe.run(fluid.default_startup_program()) + test_program = fluid.default_main_program().clone(for_test=True) + + [out_iou] = exe.run(test_program, + fetch_list=iou, + feed={'x': np.array([[0.5, 0.5, 2.0, 2.0], + [0., 0., 1.0, 1.0]]).astype('float32'), + 'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')}) + # out_iou is [[0.2857143], + # [0. ]] with shape: [2, 1] + """ + helper = LayerHelper("iou_similarity", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type="iou_similarity", + inputs={ + "X": x, + "Y": y + }, + attrs={"box_normalized": box_normalized}, + outputs={"Out": out}) + return out + + +@templatedoc() +def box_coder(prior_box, + prior_box_var, + target_box, + code_type="encode_center_size", + box_normalized=True, + name=None, + axis=0): + r""" + + **Box Coder Layer** + + Encode/Decode the target bounding box with the priorbox information. + + The Encoding schema described below: + + .. math:: + + ox = (tx - px) / pw / pxv + + oy = (ty - py) / ph / pyv + + ow = \log(\abs(tw / pw)) / pwv + + oh = \log(\abs(th / ph)) / phv + + The Decoding schema described below: + + .. math:: + + ox = (pw * pxv * tx * + px) - tw / 2 + + oy = (ph * pyv * ty * + py) - th / 2 + + ow = \exp(pwv * tw) * pw + tw / 2 + + oh = \exp(phv * th) * ph + th / 2 + + where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates, + width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote + the priorbox's (anchor) center coordinates, width and height. `pxv`, + `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`, + `ow`, `oh` denote the encoded/decoded coordinates, width and height. + + During Box Decoding, two modes for broadcast are supported. Say target + box has shape [N, M, 4], and the shape of prior box can be [N, 4] or + [M, 4]. Then prior box will broadcast to target box along the + assigned axis. + + Args: + prior_box(Variable): Box list prior_box is a 2-D Tensor with shape + [M, 4] holds M boxes and data type is float32 or float64. Each box + is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the + left top coordinate of the anchor box, if the input is image feature + map, they are close to the origin of the coordinate system. + [xmax, ymax] is the right bottom coordinate of the anchor box. + prior_box_var(List|Variable|None): prior_box_var supports three types + of input. One is variable with shape [M, 4] which holds M group and + data type is float32 or float64. The second is list consist of + 4 elements shared by all boxes and data type is float32 or float64. + Other is None and not involved in calculation. + target_box(Variable): This input can be a 2-D LoDTensor with shape + [N, 4] when code_type is 'encode_center_size'. This input also can + be a 3-D Tensor with shape [N, M, 4] when code_type is + 'decode_center_size'. Each box is represented as + [xmin, ymin, xmax, ymax]. The data type is float32 or float64. + This tensor can contain LoD information to represent a batch of inputs. + code_type(str): The code type used with the target box. It can be + `encode_center_size` or `decode_center_size`. `encode_center_size` + by default. + box_normalized(bool): Whether treat the priorbox as a normalized box. + Set true by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + axis(int): Which axis in PriorBox to broadcast for box decode, + for example, if axis is 0 and TargetBox has shape [N, M, 4] and + PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4] + for decoding. It is only valid when code type is + `decode_center_size`. Set 0 by default. + + Returns: + Variable: + + output_box(Variable): When code_type is 'encode_center_size', the + output tensor of box_coder_op with shape [N, M, 4] representing the + result of N target boxes encoded with M Prior boxes and variances. + When code_type is 'decode_center_size', N represents the batch size + and M represents the number of decoded boxes. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # For encode + prior_box_encode = fluid.data(name='prior_box_encode', + shape=[512, 4], + dtype='float32') + target_box_encode = fluid.data(name='target_box_encode', + shape=[81, 4], + dtype='float32') + output_encode = fluid.layers.box_coder(prior_box=prior_box_encode, + prior_box_var=[0.1,0.1,0.2,0.2], + target_box=target_box_encode, + code_type="encode_center_size") + # For decode + prior_box_decode = fluid.data(name='prior_box_decode', + shape=[512, 4], + dtype='float32') + target_box_decode = fluid.data(name='target_box_decode', + shape=[512, 81, 4], + dtype='float32') + output_decode = fluid.layers.box_coder(prior_box=prior_box_decode, + prior_box_var=[0.1,0.1,0.2,0.2], + target_box=target_box_decode, + code_type="decode_center_size", + box_normalized=False, + axis=1) + """ + return paddle.vision.ops.box_coder(prior_box=prior_box, + prior_box_var=prior_box_var, + target_box=target_box, + code_type=code_type, + box_normalized=box_normalized, + axis=axis, + name=name) + + +@templatedoc() +def polygon_box_transform(input, name=None): + """ + ${comment} + + Args: + input(Variable): The input with shape [batch_size, geometry_channels, height, width]. + A Tensor with type float32, float64. + name(str, Optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + + Returns: + Variable: The output with the same shape as input. A Tensor with type float32, float64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32') + out = fluid.layers.polygon_box_transform(input) + """ + check_variable_and_dtype(input, "input", ['float32', 'float64'], + 'polygon_box_transform') + helper = LayerHelper("polygon_box_transform", **locals()) + output = helper.create_variable_for_type_inference(dtype=input.dtype) + + helper.append_op(type="polygon_box_transform", + inputs={"Input": input}, + attrs={}, + outputs={"Output": output}) + return output + + +@deprecated(since="2.0.0", update_to="paddle.vision.ops.yolo_loss") +@templatedoc(op_type="yolov3_loss") +def yolov3_loss(x, + gt_box, + gt_label, + anchors, + anchor_mask, + class_num, + ignore_thresh, + downsample_ratio, + gt_score=None, + use_label_smooth=True, + name=None, + scale_x_y=1.): + """ + + ${comment} + + Args: + x (Variable): ${x_comment}The data type is float32 or float64. + gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4], + in the third dimension, x, y, w, h should be stored. + x,y is the center coordinate of boxes, w, h are the + width and height, x, y, w, h should be divided by + input image height to scale to [0, 1]. + N is the batch number and B is the max box number in + an image.The data type is float32 or float64. + gt_label (Variable): class id of ground truth boxes, should be in shape + of [N, B].The data type is int32. + anchors (list|tuple): ${anchors_comment} + anchor_mask (list|tuple): ${anchor_mask_comment} + class_num (int): ${class_num_comment} + ignore_thresh (float): ${ignore_thresh_comment} + downsample_ratio (int): ${downsample_ratio_comment} + name (string): The default value is None. Normally there is no need + for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + gt_score (Variable): mixup score of ground truth boxes, should be in shape + of [N, B]. Default None. + use_label_smooth (bool): ${use_label_smooth_comment} + scale_x_y (float): ${scale_x_y_comment} + + Returns: + Variable: A 1-D tensor with shape [N], the value of yolov3 loss + + Raises: + TypeError: Input x of yolov3_loss must be Variable + TypeError: Input gtbox of yolov3_loss must be Variable + TypeError: Input gtlabel of yolov3_loss must be Variable + TypeError: Input gtscore of yolov3_loss must be None or Variable + TypeError: Attr anchors of yolov3_loss must be list or tuple + TypeError: Attr class_num of yolov3_loss must be an integer + TypeError: Attr ignore_thresh of yolov3_loss must be a float number + TypeError: Attr use_label_smooth of yolov3_loss must be a bool value + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32') + gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32') + gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32') + gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32') + anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326] + anchor_mask = [0, 1, 2] + loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label, + gt_score=gt_score, anchors=anchors, + anchor_mask=anchor_mask, class_num=80, + ignore_thresh=0.7, downsample_ratio=32) + """ + + if not isinstance(x, Variable): + raise TypeError("Input x of yolov3_loss must be Variable") + if not isinstance(gt_box, Variable): + raise TypeError("Input gtbox of yolov3_loss must be Variable") + if not isinstance(gt_label, Variable): + raise TypeError("Input gtlabel of yolov3_loss must be Variable") + if gt_score is not None and not isinstance(gt_score, Variable): + raise TypeError("Input gtscore of yolov3_loss must be Variable") + if not isinstance(anchors, list) and not isinstance(anchors, tuple): + raise TypeError("Attr anchors of yolov3_loss must be list or tuple") + if not isinstance(anchor_mask, list) and not isinstance(anchor_mask, tuple): + raise TypeError("Attr anchor_mask of yolov3_loss must be list or tuple") + if not isinstance(class_num, int): + raise TypeError("Attr class_num of yolov3_loss must be an integer") + if not isinstance(ignore_thresh, float): + raise TypeError( + "Attr ignore_thresh of yolov3_loss must be a float number") + if not isinstance(use_label_smooth, bool): + raise TypeError( + "Attr use_label_smooth of yolov3_loss must be a bool value") + + if _non_static_mode(): + attrs = ("anchors", anchors, "anchor_mask", anchor_mask, "class_num", + class_num, "ignore_thresh", ignore_thresh, "downsample_ratio", + downsample_ratio, "use_label_smooth", use_label_smooth, + "scale_x_y", scale_x_y) + loss, _, _ = _legacy_C_ops.yolov3_loss(x, gt_box, gt_label, gt_score, + *attrs) + return loss + + helper = LayerHelper('yolov3_loss', **locals()) + loss = helper.create_variable_for_type_inference(dtype=x.dtype) + objectness_mask = helper.create_variable_for_type_inference(dtype='int32') + gt_match_mask = helper.create_variable_for_type_inference(dtype='int32') + + inputs = { + "X": x, + "GTBox": gt_box, + "GTLabel": gt_label, + } + if gt_score is not None: + inputs["GTScore"] = gt_score + + attrs = { + "anchors": anchors, + "anchor_mask": anchor_mask, + "class_num": class_num, + "ignore_thresh": ignore_thresh, + "downsample_ratio": downsample_ratio, + "use_label_smooth": use_label_smooth, + "scale_x_y": scale_x_y, + } + + helper.append_op(type='yolov3_loss', + inputs=inputs, + outputs={ + 'Loss': loss, + 'ObjectnessMask': objectness_mask, + 'GTMatchMask': gt_match_mask + }, + attrs=attrs) + return loss + + +@deprecated(since="2.0.0", update_to="paddle.vision.ops.yolo_box") +@templatedoc(op_type="yolo_box") +def yolo_box(x, + img_size, + anchors, + class_num, + conf_thresh, + downsample_ratio, + clip_bbox=True, + name=None, + scale_x_y=1., + iou_aware=False, + iou_aware_factor=0.5): + """ + + ${comment} + + Args: + x (Variable): ${x_comment} The data type is float32 or float64. + img_size (Variable): ${img_size_comment} The data type is int32. + anchors (list|tuple): ${anchors_comment} + class_num (int): ${class_num_comment} + conf_thresh (float): ${conf_thresh_comment} + downsample_ratio (int): ${downsample_ratio_comment} + clip_bbox (bool): ${clip_bbox_comment} + scale_x_y (float): ${scale_x_y_comment} + name (string): The default value is None. Normally there is no need + for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + iou_aware (bool): ${iou_aware_comment} + iou_aware_factor (float): ${iou_aware_factor_comment} + + Returns: + Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes, + and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification + scores of boxes. + + Raises: + TypeError: Input x of yolov_box must be Variable + TypeError: Attr anchors of yolo box must be list or tuple + TypeError: Attr class_num of yolo box must be an integer + TypeError: Attr conf_thresh of yolo box must be a float number + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32') + img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64') + anchors = [10, 13, 16, 30, 33, 23] + boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors, + conf_thresh=0.01, downsample_ratio=32) + """ + helper = LayerHelper('yolo_box', **locals()) + + if not isinstance(x, Variable): + raise TypeError("Input x of yolo_box must be Variable") + if not isinstance(img_size, Variable): + raise TypeError("Input img_size of yolo_box must be Variable") + if not isinstance(anchors, list) and not isinstance(anchors, tuple): + raise TypeError("Attr anchors of yolo_box must be list or tuple") + if not isinstance(class_num, int): + raise TypeError("Attr class_num of yolo_box must be an integer") + if not isinstance(conf_thresh, float): + raise TypeError("Attr ignore_thresh of yolo_box must be a float number") + + boxes = helper.create_variable_for_type_inference(dtype=x.dtype) + scores = helper.create_variable_for_type_inference(dtype=x.dtype) + + attrs = { + "anchors": anchors, + "class_num": class_num, + "conf_thresh": conf_thresh, + "downsample_ratio": downsample_ratio, + "clip_bbox": clip_bbox, + "scale_x_y": scale_x_y, + "iou_aware": iou_aware, + "iou_aware_factor": iou_aware_factor + } + + helper.append_op(type='yolo_box', + inputs={ + "X": x, + "ImgSize": img_size, + }, + outputs={ + 'Boxes': boxes, + 'Scores': scores, + }, + attrs=attrs) + return boxes, scores + + +@templatedoc() +def detection_map(detect_res, + label, + class_num, + background_label=0, + overlap_threshold=0.3, + evaluate_difficult=True, + has_state=None, + input_states=None, + out_states=None, + ap_version='integral'): + """ + ${comment} + + Args: + detect_res: ${detect_res_comment} + label: ${label_comment} + class_num: ${class_num_comment} + background_label: ${background_label_comment} + overlap_threshold: ${overlap_threshold_comment} + evaluate_difficult: ${evaluate_difficult_comment} + has_state: ${has_state_comment} + input_states: (tuple|None) If not None, It contains 3 elements: + (1) pos_count ${pos_count_comment}. + (2) true_pos ${true_pos_comment}. + (3) false_pos ${false_pos_comment}. + out_states: (tuple|None) If not None, it contains 3 elements. + (1) accum_pos_count ${accum_pos_count_comment}. + (2) accum_true_pos ${accum_true_pos_comment}. + (3) accum_false_pos ${accum_false_pos_comment}. + ap_version: ${ap_type_comment} + + Returns: + ${map_comment} + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + from fluid.layers import detection + detect_res = fluid.data( + name='detect_res', + shape=[10, 6], + dtype='float32') + label = fluid.data( + name='label', + shape=[10, 6], + dtype='float32') + + map_out = detection.detection_map(detect_res, label, 21) + """ + helper = LayerHelper("detection_map", **locals()) + + def __create_var(type): + return helper.create_variable_for_type_inference(dtype=type) + + map_out = __create_var('float32') + accum_pos_count_out = out_states[ + 0] if out_states is not None else __create_var('int32') + accum_true_pos_out = out_states[ + 1] if out_states is not None else __create_var('float32') + accum_false_pos_out = out_states[ + 2] if out_states is not None else __create_var('float32') + + pos_count = input_states[0] if input_states is not None else None + true_pos = input_states[1] if input_states is not None else None + false_pos = input_states[2] if input_states is not None else None + + helper.append_op(type="detection_map", + inputs={ + 'Label': label, + 'DetectRes': detect_res, + 'HasState': has_state, + 'PosCount': pos_count, + 'TruePos': true_pos, + 'FalsePos': false_pos + }, + outputs={ + 'MAP': map_out, + 'AccumPosCount': accum_pos_count_out, + 'AccumTruePos': accum_true_pos_out, + 'AccumFalsePos': accum_false_pos_out + }, + attrs={ + 'overlap_threshold': overlap_threshold, + 'evaluate_difficult': evaluate_difficult, + 'ap_type': ap_version, + 'class_num': class_num, + }) + return map_out + + +def bipartite_match(dist_matrix, + match_type=None, + dist_threshold=None, + name=None): + """ + + This operator implements a greedy bipartite matching algorithm, which is + used to obtain the matching with the maximum distance based on the input + distance matrix. For input 2D matrix, the bipartite matching algorithm can + find the matched column for each row (matched means the largest distance), + also can find the matched row for each column. And this operator only + calculate matched indices from column to row. For each instance, + the number of matched indices is the column number of the input distance + matrix. **The OP only supports CPU**. + + There are two outputs, matched indices and distance. + A simple description, this algorithm matched the best (maximum distance) + row entity to the column entity and the matched indices are not duplicated + in each row of ColToRowMatchIndices. If the column entity is not matched + any row entity, set -1 in ColToRowMatchIndices. + + NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor. + If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size. + If Tensor, the height of ColToRowMatchIndices is 1. + + NOTE: This API is a very low level API. It is used by :code:`ssd_loss` + layer. Please consider to use :code:`ssd_loss` instead. + + Args: + dist_matrix(Variable): This input is a 2-D LoDTensor with shape + [K, M]. The data type is float32 or float64. It is pair-wise + distance matrix between the entities represented by each row and + each column. For example, assumed one entity is A with shape [K], + another entity is B with shape [M]. The dist_matrix[i][j] is the + distance between A[i] and B[j]. The bigger the distance is, the + better matching the pairs are. NOTE: This tensor can contain LoD + information to represent a batch of inputs. One instance of this + batch can contain different numbers of entities. + match_type(str, optional): The type of matching method, should be + 'bipartite' or 'per_prediction'. None ('bipartite') by default. + dist_threshold(float32, optional): If `match_type` is 'per_prediction', + this threshold is to determine the extra matching bboxes based + on the maximum distance, 0.5 by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tuple: + + matched_indices(Variable): A 2-D Tensor with shape [N, M]. The data + type is int32. N is the batch size. If match_indices[i][j] is -1, it + means B[j] does not match any entity in i-th instance. + Otherwise, it means B[j] is matched to row + match_indices[i][j] in i-th instance. The row number of + i-th instance is saved in match_indices[i][j]. + + matched_distance(Variable): A 2-D Tensor with shape [N, M]. The data + type is float32. N is batch size. If match_indices[i][j] is -1, + match_distance[i][j] is also -1.0. Otherwise, assumed + match_distance[i][j] = d, and the row offsets of each instance + are called LoD. Then match_distance[i][j] = + dist_matrix[d+LoD[i]][j]. + + Examples: + + >>> import paddle.fluid as fluid + >>> x = fluid.data(name='x', shape=[None, 4], dtype='float32') + >>> y = fluid.data(name='y', shape=[None, 4], dtype='float32') + >>> iou = fluid.layers.iou_similarity(x=x, y=y) + >>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou) + """ + helper = LayerHelper('bipartite_match', **locals()) + match_indices = helper.create_variable_for_type_inference(dtype='int32') + match_distance = helper.create_variable_for_type_inference( + dtype=dist_matrix.dtype) + helper.append_op(type='bipartite_match', + inputs={'DistMat': dist_matrix}, + attrs={ + 'match_type': match_type, + 'dist_threshold': dist_threshold, + }, + outputs={ + 'ColToRowMatchIndices': match_indices, + 'ColToRowMatchDist': match_distance + }) + return match_indices, match_distance + + +def target_assign(input, + matched_indices, + negative_indices=None, + mismatch_value=None, + name=None): + """ + + This operator can be, for given the target bounding boxes or labels, + to assign classification and regression targets to each prediction as well as + weights to prediction. The weights is used to specify which prediction would + not contribute to training loss. + + For each instance, the output `out` and`out_weight` are assigned based on + `match_indices` and `negative_indices`. + Assumed that the row offset for each instance in `input` is called lod, + this operator assigns classification/regression targets by performing the + following steps: + + 1. Assigning all outputs based on `match_indices`: + + .. code-block:: text + + If id = match_indices[i][j] > 0, + + out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K] + out_weight[i][j] = 1. + + Otherwise, + + out[j][j][0 : K] = {mismatch_value, mismatch_value, ...} + out_weight[i][j] = 0. + + 2. Assigning outputs based on `neg_indices` if `neg_indices` is provided: + + Assumed that i-th instance in `neg_indices` is called `neg_indice`, + for i-th instance: + + .. code-block:: text + + for id in neg_indice: + out[i][id][0 : K] = {mismatch_value, mismatch_value, ...} + out_weight[i][id] = 1.0 + + Args: + input (Variable): This input is a 3D LoDTensor with shape [M, P, K]. + Data type should be int32 or float32. + matched_indices (Variable): The input matched indices + is 2D Tenosr with shape [N, P], If MatchIndices[i][j] is -1, + the j-th entity of column is not matched to any entity of row in + i-th instance. + negative_indices (Variable, optional): The input negative example indices + are an optional input with shape [Neg, 1] and int32 type, where Neg is + the total number of negative example indices. + mismatch_value (float32, optional): Fill this value to the mismatched + location. + name (string): The default value is None. Normally there is no need for + user to set this property. For more information, please refer + to :ref:`api_guide_Name`. + + Returns: + tuple: A tuple(out, out_weight) is returned. + + out (Variable): a 3D Tensor with shape [N, P, K] and same data type + with `input`, N and P is the same as they are in `matched_indices`, + K is the same as it in input of X. + + out_weight (Variable): the weight for output with the shape of [N, P, 1]. + Data type is float32. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + x = fluid.data( + name='x', + shape=[4, 20, 4], + dtype='float', + lod_level=1) + matched_id = fluid.data( + name='indices', + shape=[8, 20], + dtype='int32') + trg, trg_weight = fluid.layers.target_assign( + x, + matched_id, + mismatch_value=0) + """ + helper = LayerHelper('target_assign', **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + out_weight = helper.create_variable_for_type_inference(dtype='float32') + helper.append_op(type='target_assign', + inputs={ + 'X': input, + 'MatchIndices': matched_indices, + 'NegIndices': negative_indices + }, + outputs={ + 'Out': out, + 'OutWeight': out_weight + }, + attrs={'mismatch_value': mismatch_value}) + return out, out_weight + + +def ssd_loss(location, + confidence, + gt_box, + gt_label, + prior_box, + prior_box_var=None, + background_label=0, + overlap_threshold=0.5, + neg_pos_ratio=3.0, + neg_overlap=0.5, + loc_loss_weight=1.0, + conf_loss_weight=1.0, + match_type='per_prediction', + mining_type='max_negative', + normalize=True, + sample_size=None): + r""" + :alias_main: paddle.nn.functional.ssd_loss + :alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss + :old_api: paddle.fluid.layers.ssd_loss + + **Multi-box loss layer for object detection algorithm of SSD** + + This layer is to compute detection loss for SSD given the location offset + predictions, confidence predictions, prior boxes and ground-truth bounding + boxes and labels, and the type of hard example mining. The returned loss + is a weighted sum of the localization loss (or regression loss) and + confidence loss (or classification loss) by performing the following steps: + + 1. Find matched bounding box by bipartite matching algorithm. + + 1.1 Compute IOU similarity between ground-truth boxes and prior boxes. + + 1.2 Compute matched bounding box by bipartite matching algorithm. + + 2. Compute confidence for mining hard examples + + 2.1. Get the target label based on matched indices. + + 2.2. Compute confidence loss. + + 3. Apply hard example mining to get the negative example indices and update + the matched indices. + + 4. Assign classification and regression targets + + 4.1. Encoded bbox according to the prior boxes. + + 4.2. Assign regression targets. + + 4.3. Assign classification targets. + + 5. Compute the overall objective loss. + + 5.1 Compute confidence loss. + + 5.2 Compute localization loss. + + 5.3 Compute the overall weighted loss. + + Args: + location (Variable): The location predictions are a 3D Tensor with + shape [N, Np, 4], N is the batch size, Np is total number of + predictions for each instance. 4 is the number of coordinate values, + the layout is [xmin, ymin, xmax, ymax].The data type is float32 or + float64. + confidence (Variable): The confidence predictions are a 3D Tensor + with shape [N, Np, C], N and Np are the same as they are in + `location`, C is the class number.The data type is float32 or + float64. + gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D + LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth + bboxes of mini-batch input.The data type is float32 or float64. + gt_label (Variable): The ground-truth labels are a 2D LoDTensor + with shape [Ng, 1].Ng is the total number of ground-truth bboxes of + mini-batch input, 1 is the number of class. The data type is float32 + or float64. + prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4]. + Np and 4 are the same as they are in `location`. The data type is + float32 or float64. + prior_box_var (Variable): The variance of prior boxes are a 2D Tensor + with shape [Np, 4]. Np and 4 are the same as they are in `prior_box` + background_label (int): The index of background label, 0 by default. + overlap_threshold (float): If match_type is 'per_prediction', use + 'overlap_threshold' to determine the extra matching bboxes when finding \ + matched boxes. 0.5 by default. + neg_pos_ratio (float): The ratio of the negative boxes to the positive + boxes, used only when mining_type is 'max_negative', 3.0 by default. + neg_overlap (float): The negative overlap upper bound for the unmatched + predictions. Use only when mining_type is 'max_negative', + 0.5 by default. + loc_loss_weight (float): Weight for localization loss, 1.0 by default. + conf_loss_weight (float): Weight for confidence loss, 1.0 by default. + match_type (str): The type of matching method during training, should + be 'bipartite' or 'per_prediction', 'per_prediction' by default. + mining_type (str): The hard example mining type, should be 'hard_example' + or 'max_negative', now only support `max_negative`. + normalize (bool): Whether to normalize the SSD loss by the total number + of output locations, True by default. + sample_size (int): The max sample size of negative box, used only when + mining_type is 'hard_example'. + + Returns: + Variable(Tensor): The weighted sum of the localization loss and confidence loss, \ + with shape [N * Np, 1], N and Np are the same as they are in + `location`.The data type is float32 or float64. + + Raises: + ValueError: If mining_type is 'hard_example', now only support mining \ + type of `max_negative`. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + pb = fluid.data( + name='prior_box', + shape=[10, 4], + dtype='float32') + pbv = fluid.data( + name='prior_box_var', + shape=[10, 4], + dtype='float32') + loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32') + scores = fluid.data(name='scores', shape=[10, 21], dtype='float32') + gt_box = fluid.data( + name='gt_box', shape=[4], lod_level=1, dtype='float32') + gt_label = fluid.data( + name='gt_label', shape=[1], lod_level=1, dtype='float32') + loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv) + """ + + helper = LayerHelper('ssd_loss', **locals()) + if mining_type != 'max_negative': + raise ValueError("Only support mining_type == max_negative now.") + + num, num_prior, num_class = confidence.shape + conf_shape = nn.shape(confidence) + + def __reshape_to_2d(var): + return nn.flatten(x=var, axis=2) + + # 1. Find matched bounding box by prior box. + # 1.1 Compute IOU similarity between ground-truth boxes and prior boxes. + iou = iou_similarity(x=gt_box, y=prior_box) + # 1.2 Compute matched bounding box by bipartite matching algorithm. + matched_indices, matched_dist = bipartite_match(iou, match_type, + overlap_threshold) + + # 2. Compute confidence for mining hard examples + # 2.1. Get the target label based on matched indices + gt_label = nn.reshape(x=gt_label, + shape=(len(gt_label.shape) - 1) * (0, ) + (-1, 1)) + gt_label.stop_gradient = True + target_label, _ = target_assign(gt_label, + matched_indices, + mismatch_value=background_label) + # 2.2. Compute confidence loss. + # Reshape confidence to 2D tensor. + confidence = __reshape_to_2d(confidence) + target_label = tensor.cast(x=target_label, dtype='int64') + target_label = __reshape_to_2d(target_label) + target_label.stop_gradient = True + conf_loss = softmax_with_cross_entropy(confidence, target_label) + # 3. Mining hard examples + actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2]) + actual_shape.stop_gradient = True + # shape=(-1, 0) is set for compile-time, the correct shape is set by + # actual_shape in runtime. + conf_loss = nn.reshape(x=conf_loss, + shape=(-1, 0), + actual_shape=actual_shape) + conf_loss.stop_gradient = True + neg_indices = helper.create_variable_for_type_inference(dtype='int32') + dtype = matched_indices.dtype + updated_matched_indices = helper.create_variable_for_type_inference( + dtype=dtype) + helper.append_op(type='mine_hard_examples', + inputs={ + 'ClsLoss': conf_loss, + 'LocLoss': None, + 'MatchIndices': matched_indices, + 'MatchDist': matched_dist, + }, + outputs={ + 'NegIndices': neg_indices, + 'UpdatedMatchIndices': updated_matched_indices + }, + attrs={ + 'neg_pos_ratio': neg_pos_ratio, + 'neg_dist_threshold': neg_overlap, + 'mining_type': mining_type, + 'sample_size': sample_size, + }) + + # 4. Assign classification and regression targets + # 4.1. Encoded bbox according to the prior boxes. + encoded_bbox = box_coder(prior_box=prior_box, + prior_box_var=prior_box_var, + target_box=gt_box, + code_type='encode_center_size') + # 4.2. Assign regression targets + target_bbox, target_loc_weight = target_assign( + encoded_bbox, updated_matched_indices, mismatch_value=background_label) + # 4.3. Assign classification targets + target_label, target_conf_weight = target_assign( + gt_label, + updated_matched_indices, + negative_indices=neg_indices, + mismatch_value=background_label) + + # 5. Compute loss. + # 5.1 Compute confidence loss. + target_label = __reshape_to_2d(target_label) + target_label = tensor.cast(x=target_label, dtype='int64') + + conf_loss = softmax_with_cross_entropy(confidence, target_label) + target_conf_weight = __reshape_to_2d(target_conf_weight) + conf_loss = conf_loss * target_conf_weight + + # the target_label and target_conf_weight do not have gradient. + target_label.stop_gradient = True + target_conf_weight.stop_gradient = True + + # 5.2 Compute regression loss. + location = __reshape_to_2d(location) + target_bbox = __reshape_to_2d(target_bbox) + + loc_loss = nn.smooth_l1(location, target_bbox) + target_loc_weight = __reshape_to_2d(target_loc_weight) + loc_loss = loc_loss * target_loc_weight + + # the target_bbox and target_loc_weight do not have gradient. + target_bbox.stop_gradient = True + target_loc_weight.stop_gradient = True + + # 5.3 Compute overall weighted loss. + loss = conf_loss_weight * conf_loss + loc_loss_weight * loc_loss + # reshape to [N, Np], N is the batch size and Np is the prior box number. + # shape=(-1, 0) is set for compile-time, the correct shape is set by + # actual_shape in runtime. + loss = nn.reshape(x=loss, shape=(-1, 0), actual_shape=actual_shape) + loss = nn.reduce_sum(loss, dim=1, keep_dim=True) + if normalize: + normalizer = nn.reduce_sum(target_loc_weight) + loss = loss / normalizer + + return loss + + +def prior_box( + input, + image, + min_sizes, + max_sizes=None, + aspect_ratios=[1.], + variance=[0.1, 0.1, 0.2, 0.2], + flip=False, + clip=False, + steps=[0.0, 0.0], + offset=0.5, + name=None, + min_max_aspect_ratios_order=False, +): + """ + + This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm. + Each position of the input produce N prior boxes, N is determined by + the count of min_sizes, max_sizes and aspect_ratios, The size of the + box is in range(min_size, max_size) interval, which is generated in + sequence according to the aspect_ratios. + + Parameters: + input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64. + image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, + the data type should be float32 or float64. + min_sizes(list|tuple|float): the min sizes of generated prior boxes. + max_sizes(list|tuple|None): the max sizes of generated prior boxes. + Default: None. + aspect_ratios(list|tuple|float): the aspect ratios of generated + prior boxes. Default: [1.]. + variance(list|tuple): the variances to be encoded in prior boxes. + Default:[0.1, 0.1, 0.2, 0.2]. + flip(bool): Whether to flip aspect ratios. Default:False. + clip(bool): Whether to clip out-of-boundary boxes. Default: False. + step(list|tuple): Prior boxes step across width and height, If + step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across + height or weight of the input will be automatically calculated. + Default: [0., 0.] + offset(float): Prior boxes center offset. Default: 0.5 + min_max_aspect_ratios_order(bool): If set True, the output prior box is + in order of [min, max, aspect_ratios], which is consistent with + Caffe. Please note, this order affects the weights order of + convolution layer followed by and does not affect the final + detection results. Default: False. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tuple: A tuple with two Variable (boxes, variances) + + boxes(Variable): the output prior boxes of PriorBox. + 4-D tensor, the layout is [H, W, num_priors, 4]. + H is the height of input, W is the width of input, + num_priors is the total box count of each position of input. + + variances(Variable): the expanded variances of PriorBox. + 4-D tensor, the layput is [H, W, num_priors, 4]. + H is the height of input, W is the width of input + num_priors is the total box count of each position of input + + Examples: + .. code-block:: python + + #declarative mode + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + input = fluid.data(name="input", shape=[None,3,6,9]) + image = fluid.data(name="image", shape=[None,3,9,12]) + box, var = fluid.layers.prior_box( + input=input, + image=image, + min_sizes=[100.], + clip=True, + flip=True) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + # prepare a batch of data + input_data = np.random.rand(1,3,6,9).astype("float32") + image_data = np.random.rand(1,3,9,12).astype("float32") + + box_out, var_out = exe.run(fluid.default_main_program(), + feed={"input":input_data,"image":image_data}, + fetch_list=[box,var], + return_numpy=True) + + # print(box_out.shape) + # (6, 9, 1, 4) + # print(var_out.shape) + # (6, 9, 1, 4) + + # imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + image = dg.to_variable(image_data) + box, var = fluid.layers.prior_box( + input=input, + image=image, + min_sizes=[100.], + clip=True, + flip=True) + # print(box.shape) + # [6L, 9L, 1L, 4L] + # print(var.shape) + # [6L, 9L, 1L, 4L] + + """ + return paddle.vision.ops.prior_box( + input=input, + image=image, + min_sizes=min_sizes, + max_sizes=max_sizes, + aspect_ratios=aspect_ratios, + variance=variance, + flip=flip, + clip=clip, + steps=steps, + offset=offset, + min_max_aspect_ratios_order=min_max_aspect_ratios_order, + name=name) + + +def density_prior_box(input, + image, + densities=None, + fixed_sizes=None, + fixed_ratios=None, + variance=[0.1, 0.1, 0.2, 0.2], + clip=False, + steps=[0.0, 0.0], + offset=0.5, + flatten_to_2d=False, + name=None): + r""" + + This op generates density prior boxes for SSD(Single Shot MultiBox Detector) + algorithm. Each position of the input produce N prior boxes, N is + determined by the count of densities, fixed_sizes and fixed_ratios. + Boxes center at grid points around each input position is generated by + this operator, and the grid points is determined by densities and + the count of density prior box is determined by fixed_sizes and fixed_ratios. + Obviously, the number of fixed_sizes is equal to the number of densities. + + For densities_i in densities: + + .. math:: + + N\_density_prior\_box = SUM(N\_fixed\_ratios * densities\_i^2) + + N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios. + + Parameters: + input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64. + image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64. + the layout is NCHW. + densities(list|tuple|None): The densities of generated density prior + boxes, this attribute should be a list or tuple of integers. + Default: None. + fixed_sizes(list|tuple|None): The fixed sizes of generated density + prior boxes, this attribute should a list or tuple of same + length with :attr:`densities`. Default: None. + fixed_ratios(list|tuple|None): The fixed ratios of generated density + prior boxes, if this attribute is not set and :attr:`densities` + and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used + to generate density prior boxes. + variance(list|tuple): The variances to be encoded in density prior boxes. + Default:[0.1, 0.1, 0.2, 0.2]. + clip(bool): Whether to clip out of boundary boxes. Default: False. + step(list|tuple): Prior boxes step across width and height, If + step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across + height or weight of the input will be automatically calculated. + Default: [0., 0.] + offset(float): Prior boxes center offset. Default: 0.5 + flatten_to_2d(bool): Whether to flatten output prior boxes and variance + to 2D shape, the second dim is 4. Default: False. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tuple: A tuple with two Variable (boxes, variances) + + boxes: the output density prior boxes of PriorBox. + 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False. + 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True. + H is the height of input, W is the width of input, and num_priors is the total box count of each position of input. + + variances: the expanded variances of PriorBox. + 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False. + 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True. + H is the height of input, W is the width of input, and num_priors is the total box count of each position of input. + + + Examples: + + .. code-block:: python + + #declarative mode + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + input = fluid.data(name="input", shape=[None,3,6,9]) + image = fluid.data(name="image", shape=[None,3,9,12]) + box, var = fluid.layers.density_prior_box( + input=input, + image=image, + densities=[4, 2, 1], + fixed_sizes=[32.0, 64.0, 128.0], + fixed_ratios=[1.], + clip=True, + flatten_to_2d=True) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + # prepare a batch of data + input_data = np.random.rand(1,3,6,9).astype("float32") + image_data = np.random.rand(1,3,9,12).astype("float32") + + box_out, var_out = exe.run( + fluid.default_main_program(), + feed={"input":input_data, + "image":image_data}, + fetch_list=[box,var], + return_numpy=True) + + # print(box_out.shape) + # (1134, 4) + # print(var_out.shape) + # (1134, 4) + + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + image = dg.to_variable(image_data) + box, var = fluid.layers.density_prior_box( + input=input, + image=image, + densities=[4, 2, 1], + fixed_sizes=[32.0, 64.0, 128.0], + fixed_ratios=[1.], + clip=True) + + # print(box.shape) + # [6L, 9L, 21L, 4L] + # print(var.shape) + # [6L, 9L, 21L, 4L] + + """ + helper = LayerHelper("density_prior_box", **locals()) + dtype = helper.input_dtype() + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'density_prior_box') + + def _is_list_or_tuple_(data): + return (isinstance(data, list) or isinstance(data, tuple)) + + check_type(densities, 'densities', (list, tuple), 'density_prior_box') + check_type(fixed_sizes, 'fixed_sizes', (list, tuple), 'density_prior_box') + check_type(fixed_ratios, 'fixed_ratios', (list, tuple), 'density_prior_box') + if len(densities) != len(fixed_sizes): + raise ValueError('densities and fixed_sizes length should be euqal.') + + if not (_is_list_or_tuple_(steps) and len(steps) == 2): + raise ValueError('steps should be a list or tuple ', + 'with length 2, (step_width, step_height).') + + densities = list(map(int, densities)) + fixed_sizes = list(map(float, fixed_sizes)) + fixed_ratios = list(map(float, fixed_ratios)) + steps = list(map(float, steps)) + + attrs = { + 'variances': variance, + 'clip': clip, + 'step_w': steps[0], + 'step_h': steps[1], + 'offset': offset, + 'densities': densities, + 'fixed_sizes': fixed_sizes, + 'fixed_ratios': fixed_ratios, + 'flatten_to_2d': flatten_to_2d, + } + box = helper.create_variable_for_type_inference(dtype) + var = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="density_prior_box", + inputs={ + "Input": input, + "Image": image + }, + outputs={ + "Boxes": box, + "Variances": var + }, + attrs=attrs, + ) + box.stop_gradient = True + var.stop_gradient = True + return box, var + + +@static_only +def multi_box_head(inputs, + image, + base_size, + num_classes, + aspect_ratios, + min_ratio=None, + max_ratio=None, + min_sizes=None, + max_sizes=None, + steps=None, + step_w=None, + step_h=None, + offset=0.5, + variance=[0.1, 0.1, 0.2, 0.2], + flip=True, + clip=False, + kernel_size=1, + pad=0, + stride=1, + name=None, + min_max_aspect_ratios_order=False): + """ + :api_attr: Static Graph + + Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes, + regression location and classification confidence on multiple input feature + maps, then output the concatenate results. The details of this algorithm, + please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector + `_ . + + Args: + inputs (list(Variable)|tuple(Variable)): The list of input variables, + the format of all Variables are 4-D Tensor, layout is NCHW. + Data type should be float32 or float64. + image (Variable): The input image, layout is NCHW. Data type should be + the same as inputs. + base_size(int): the base_size is input image size. When len(inputs) > 2 + and `min_size` and `max_size` are None, the `min_size` and `max_size` + are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The + formula is as follows: + + .. code-block:: text + + min_sizes = [] + max_sizes = [] + step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2))) + for ratio in six.moves.range(min_ratio, max_ratio + 1, step): + min_sizes.append(base_size * ratio / 100.) + max_sizes.append(base_size * (ratio + step) / 100.) + min_sizes = [base_size * .10] + min_sizes + max_sizes = [base_size * .20] + max_sizes + + num_classes(int): The number of classes. + aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated + prior boxes. The length of input and aspect_ratios must be equal. + min_ratio(int): the min ratio of generated prior boxes. + max_ratio(int): the max ratio of generated prior boxes. + min_sizes(list|tuple|None): If `len(inputs) <=2`, + min_sizes must be set up, and the length of min_sizes + should equal to the length of inputs. Default: None. + max_sizes(list|tuple|None): If `len(inputs) <=2`, + max_sizes must be set up, and the length of min_sizes + should equal to the length of inputs. Default: None. + steps(list|tuple): If step_w and step_h are the same, + step_w and step_h can be replaced by steps. + step_w(list|tuple): Prior boxes step + across width. If step_w[i] == 0.0, the prior boxes step + across width of the inputs[i] will be automatically + calculated. Default: None. + step_h(list|tuple): Prior boxes step across height, If + step_h[i] == 0.0, the prior boxes step across height of + the inputs[i] will be automatically calculated. Default: None. + offset(float): Prior boxes center offset. Default: 0.5 + variance(list|tuple): the variances to be encoded in prior boxes. + Default:[0.1, 0.1, 0.2, 0.2]. + flip(bool): Whether to flip aspect ratios. Default:False. + clip(bool): Whether to clip out-of-boundary boxes. Default: False. + kernel_size(int): The kernel size of conv2d. Default: 1. + pad(int|list|tuple): The padding of conv2d. Default:0. + stride(int|list|tuple): The stride of conv2d. Default:1, + name(str): The default value is None. Normally there is no need + for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + min_max_aspect_ratios_order(bool): If set True, the output prior box is + in order of [min, max, aspect_ratios], which is consistent with + Caffe. Please note, this order affects the weights order of + convolution layer followed by and does not affect the final + detection results. Default: False. + + Returns: + tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances) + + mbox_loc (Variable): The predicted boxes' location of the inputs. The + layout is [N, num_priors, 4], where N is batch size, ``num_priors`` + is the number of prior boxes. Data type is the same as input. + + mbox_conf (Variable): The predicted boxes' confidence of the inputs. + The layout is [N, num_priors, C], where ``N`` and ``num_priors`` + has the same meaning as above. C is the number of Classes. + Data type is the same as input. + + boxes (Variable): the output prior boxes. The layout is [num_priors, 4]. + The meaning of num_priors is the same as above. + Data type is the same as input. + + variances (Variable): the expanded variances for prior boxes. + The layout is [num_priors, 4]. Data type is the same as input. + + Examples 1: set min_ratio and max_ratio: + .. code-block:: python + + import paddle + paddle.enable_static() + + images = paddle.static.data(name='data', shape=[None, 3, 300, 300], dtype='float32') + conv1 = paddle.static.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32') + conv2 = paddle.static.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32') + conv3 = paddle.static.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32') + conv4 = paddle.static.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32') + conv5 = paddle.static.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32') + conv6 = paddle.static.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32') + + mbox_locs, mbox_confs, box, var = paddle.static.nn.multi_box_head( + inputs=[conv1, conv2, conv3, conv4, conv5, conv6], + image=images, + num_classes=21, + min_ratio=20, + max_ratio=90, + aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]], + base_size=300, + offset=0.5, + flip=True, + clip=True) + + Examples 2: set min_sizes and max_sizes: + .. code-block:: python + + import paddle + paddle.enable_static() + + images = paddle.static.data(name='data', shape=[None, 3, 300, 300], dtype='float32') + conv1 = paddle.static.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32') + conv2 = paddle.static.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32') + conv3 = paddle.static.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32') + conv4 = paddle.static.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32') + conv5 = paddle.static.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32') + conv6 = paddle.static.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32') + + mbox_locs, mbox_confs, box, var = paddle.static.nn.multi_box_head( + inputs=[conv1, conv2, conv3, conv4, conv5, conv6], + image=images, + num_classes=21, + min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0], + max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0], + aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]], + base_size=300, + offset=0.5, + flip=True, + clip=True) + + """ + + def _reshape_with_axis_(input, axis=1): + out = nn.flatten(x=input, axis=axis) + return out + + def _is_list_or_tuple_(data): + return (isinstance(data, list) or isinstance(data, tuple)) + + def _is_list_or_tuple_and_equal(data, length, err_info): + if not (_is_list_or_tuple_(data) and len(data) == length): + raise ValueError(err_info) + + if not _is_list_or_tuple_(inputs): + raise ValueError('inputs should be a list or tuple.') + + num_layer = len(inputs) + + if num_layer <= 2: + assert min_sizes is not None and max_sizes is not None + assert len(min_sizes) == num_layer and len(max_sizes) == num_layer + elif min_sizes is None and max_sizes is None: + min_sizes = [] + max_sizes = [] + step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2))) + for ratio in six.moves.range(min_ratio, max_ratio + 1, step): + min_sizes.append(base_size * ratio / 100.) + max_sizes.append(base_size * (ratio + step) / 100.) + min_sizes = [base_size * .10] + min_sizes + max_sizes = [base_size * .20] + max_sizes + + if aspect_ratios: + _is_list_or_tuple_and_equal( + aspect_ratios, num_layer, + 'aspect_ratios should be list or tuple, and the length of inputs ' + 'and aspect_ratios should be the same.') + if step_h is not None: + _is_list_or_tuple_and_equal( + step_h, num_layer, + 'step_h should be list or tuple, and the length of inputs and ' + 'step_h should be the same.') + if step_w is not None: + _is_list_or_tuple_and_equal( + step_w, num_layer, + 'step_w should be list or tuple, and the length of inputs and ' + 'step_w should be the same.') + if steps is not None: + _is_list_or_tuple_and_equal( + steps, num_layer, + 'steps should be list or tuple, and the length of inputs and ' + 'step_w should be the same.') + step_w = steps + step_h = steps + + mbox_locs = [] + mbox_confs = [] + box_results = [] + var_results = [] + for i, input in enumerate(inputs): + min_size = min_sizes[i] + max_size = max_sizes[i] + + if not _is_list_or_tuple_(min_size): + min_size = [min_size] + if not _is_list_or_tuple_(max_size): + max_size = [max_size] + + aspect_ratio = [] + if aspect_ratios is not None: + aspect_ratio = aspect_ratios[i] + if not _is_list_or_tuple_(aspect_ratio): + aspect_ratio = [aspect_ratio] + step = [step_w[i] if step_w else 0.0, step_h[i] if step_w else 0.0] + + box, var = prior_box(input, image, min_size, max_size, aspect_ratio, + variance, flip, clip, step, offset, None, + min_max_aspect_ratios_order) + + box_results.append(box) + var_results.append(var) + + num_boxes = box.shape[2] + + # get loc + num_loc_output = num_boxes * 4 + mbox_loc = nn.conv2d(input=input, + num_filters=num_loc_output, + filter_size=kernel_size, + padding=pad, + stride=stride) + + mbox_loc = nn.transpose(mbox_loc, perm=[0, 2, 3, 1]) + mbox_loc_flatten = nn.flatten(mbox_loc, axis=1) + mbox_locs.append(mbox_loc_flatten) + + # get conf + num_conf_output = num_boxes * num_classes + conf_loc = nn.conv2d(input=input, + num_filters=num_conf_output, + filter_size=kernel_size, + padding=pad, + stride=stride) + conf_loc = nn.transpose(conf_loc, perm=[0, 2, 3, 1]) + conf_loc_flatten = nn.flatten(conf_loc, axis=1) + mbox_confs.append(conf_loc_flatten) + + if len(box_results) == 1: + box = box_results[0] + var = var_results[0] + mbox_locs_concat = mbox_locs[0] + mbox_confs_concat = mbox_confs[0] + else: + reshaped_boxes = [] + reshaped_vars = [] + for i in range(len(box_results)): + reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3)) + reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3)) + + box = tensor.concat(reshaped_boxes) + var = tensor.concat(reshaped_vars) + mbox_locs_concat = tensor.concat(mbox_locs, axis=1) + mbox_locs_concat = nn.reshape(mbox_locs_concat, shape=[0, -1, 4]) + mbox_confs_concat = tensor.concat(mbox_confs, axis=1) + mbox_confs_concat = nn.reshape(mbox_confs_concat, + shape=[0, -1, num_classes]) + + box.stop_gradient = True + var.stop_gradient = True + return mbox_locs_concat, mbox_confs_concat, box, var + + +def anchor_generator(input, + anchor_sizes=None, + aspect_ratios=None, + variance=[0.1, 0.1, 0.2, 0.2], + stride=None, + offset=0.5, + name=None): + """ + + **Anchor generator operator** + + Generate anchors for Faster RCNN algorithm. + Each position of the input produce N anchors, N = + size(anchor_sizes) * size(aspect_ratios). The order of generated anchors + is firstly aspect_ratios loop then anchor_sizes loop. + + Args: + input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map. + anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated + anchors, given in absolute pixels e.g. [64., 128., 256., 512.]. + For instance, the anchor size of 64 means the area of this anchor + equals to 64**2. None by default. + aspect_ratios(float32|list|tuple, optional): The height / width ratios + of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default. + variance(list|tuple, optional): The variances to be used in box + regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by + default. + stride(list|tuple, optional): The anchors stride across width and height. + The data type is float32. e.g. [16.0, 16.0]. None by default. + offset(float32, optional): Prior boxes center offset. 0.5 by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and None + by default. + + Returns: + Tuple: + + Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4]. + H is the height of input, W is the width of input, + num_anchors is the box count of each position. + Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized. + + Variances(Variable): The expanded variances of anchors + with a layout of [H, W, num_priors, 4]. + H is the height of input, W is the width of input + num_anchors is the box count of each position. + Each variance is in (xcenter, ycenter, w, h) format. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32') + anchor, var = fluid.layers.anchor_generator( + input=conv1, + anchor_sizes=[64, 128, 256, 512], + aspect_ratios=[0.5, 1.0, 2.0], + variance=[0.1, 0.1, 0.2, 0.2], + stride=[16.0, 16.0], + offset=0.5) + """ + helper = LayerHelper("anchor_generator", **locals()) + dtype = helper.input_dtype() + + def _is_list_or_tuple_(data): + return (isinstance(data, list) or isinstance(data, tuple)) + + if not _is_list_or_tuple_(anchor_sizes): + anchor_sizes = [anchor_sizes] + if not _is_list_or_tuple_(aspect_ratios): + aspect_ratios = [aspect_ratios] + if not (_is_list_or_tuple_(stride) and len(stride) == 2): + raise ValueError('stride should be a list or tuple ', + 'with length 2, (stride_width, stride_height).') + + anchor_sizes = list(map(float, anchor_sizes)) + aspect_ratios = list(map(float, aspect_ratios)) + stride = list(map(float, stride)) + + attrs = { + 'anchor_sizes': anchor_sizes, + 'aspect_ratios': aspect_ratios, + 'variances': variance, + 'stride': stride, + 'offset': offset + } + + anchor = helper.create_variable_for_type_inference(dtype) + var = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="anchor_generator", + inputs={"Input": input}, + outputs={ + "Anchors": anchor, + "Variances": var + }, + attrs=attrs, + ) + anchor.stop_gradient = True + var.stop_gradient = True + return anchor, var + + +def roi_perspective_transform(input, + rois, + transformed_height, + transformed_width, + spatial_scale=1.0, + name=None): + """ + **The** `rois` **of this op should be a LoDTensor.** + + ROI perspective transform op applies perspective transform to map each roi into an + rectangular region. Perspective transform is a type of transformation in linear algebra. + + Parameters: + input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of + input tensor is NCHW. Where N is batch size, C is the + number of input channels, H is the height of the feature, + and W is the width of the feature. The data type is float32. + rois (Variable): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed. + It should be a 2-D LoDTensor of shape (num_rois, 8). Given as + [[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the + top left coordinates, and (x2, y2) is the top right + coordinates, and (x3, y3) is the bottom right coordinates, + and (x4, y4) is the bottom left coordinates. The data type is the + same as `input` + transformed_height (int): The height of transformed output. + transformed_width (int): The width of transformed output. + spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0 + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + A tuple with three Variables. (out, mask, transform_matrix) + + out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape + (num_rois, channels, transformed_h, transformed_w). The data type is the same as `input` + + mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape + (num_rois, 1, transformed_h, transformed_w). The data type is int32 + + transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is + a 2-D tensor with shape (num_rois, 9). The data type is the same as `input` + + Return Type: + tuple + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32') + rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32') + out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0) + """ + check_variable_and_dtype(input, 'input', ['float32'], + 'roi_perspective_transform') + check_variable_and_dtype(rois, 'rois', ['float32'], + 'roi_perspective_transform') + check_type(transformed_height, 'transformed_height', int, + 'roi_perspective_transform') + check_type(transformed_width, 'transformed_width', int, + 'roi_perspective_transform') + check_type(spatial_scale, 'spatial_scale', float, + 'roi_perspective_transform') + + helper = LayerHelper('roi_perspective_transform', **locals()) + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + mask = helper.create_variable_for_type_inference(dtype="int32") + transform_matrix = helper.create_variable_for_type_inference(dtype) + out2in_idx = helper.create_variable_for_type_inference(dtype="int32") + out2in_w = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="roi_perspective_transform", + inputs={ + "X": input, + "ROIs": rois + }, + outputs={ + "Out": out, + "Out2InIdx": out2in_idx, + "Out2InWeights": out2in_w, + "Mask": mask, + "TransformMatrix": transform_matrix + }, + attrs={ + "transformed_height": transformed_height, + "transformed_width": transformed_width, + "spatial_scale": spatial_scale + }) + return out, mask, transform_matrix + + +def generate_proposal_labels(rpn_rois, + gt_classes, + is_crowd, + gt_boxes, + im_info, + batch_size_per_im=256, + fg_fraction=0.25, + fg_thresh=0.25, + bg_thresh_hi=0.5, + bg_thresh_lo=0.0, + bbox_reg_weights=[0.1, 0.1, 0.2, 0.2], + class_nums=None, + use_random=True, + is_cls_agnostic=False, + is_cascade_rcnn=False, + max_overlap=None, + return_max_overlap=False): + """ + + **Generate Proposal Labels of Faster-RCNN** + + This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth, + to sample foreground boxes and background boxes, and compute loss target. + + RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes + were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction, + If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample. + If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi, + then it was considered as a background sample. + After all foreground and background boxes are chosen (so called Rois), + then we apply random sampling to make sure + the number of foreground boxes is no more than batch_size_per_im * fg_fraction. + + For each box in Rois, we assign the classification (class label) and regression targets (box label) to it. + Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss. + + Args: + rpn_rois(Variable): A 2-D LoDTensor with shape [N, 4]. N is the number of the GenerateProposalOp's output, each element is a bounding box with [xmin, ymin, xmax, ymax] format. The data type can be float32 or float64. + gt_classes(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a class label of groundtruth. The data type must be int32. + is_crowd(Variable): A 2-D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a flag indicates whether a groundtruth is crowd. The data type must be int32. + gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format. + im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale. + + batch_size_per_im(int): Batch size of rois per images. The data type must be int32. + fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32. + fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32. + bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32. + bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32. + bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32. + class_nums(int): Class number. The data type must be int32. + use_random(bool): Use random sampling to choose foreground and background boxes. + is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes. + is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True. + max_overlap(Variable): Maximum overlap between each proposal box and ground-truth. + return_max_overlap(bool): Whether return the maximum overlap between each sampled RoI and ground-truth. + + Returns: + tuple: + A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights, max_overlap)``. + + - **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``. + - **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32. + - **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``. + - **bbox_inside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of foreground boxes' regression loss. The data type is the same as ``rpn_rois``. + - **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``. + - **max_overlap**: 1-D LoDTensor with shape ``[P]``. P is the number of output ``rois``. The maximum overlap between each sampled RoI and ground-truth. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32') + gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='int32') + is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='int32') + gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32') + im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32') + rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels( + rpn_rois, gt_classes, is_crowd, gt_boxes, im_info, + class_nums=10) + + """ + + helper = LayerHelper('generate_proposal_labels', **locals()) + + check_variable_and_dtype(rpn_rois, 'rpn_rois', ['float32', 'float64'], + 'generate_proposal_labels') + check_variable_and_dtype(gt_classes, 'gt_classes', ['int32'], + 'generate_proposal_labels') + check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'], + 'generate_proposal_labels') + if is_cascade_rcnn: + assert max_overlap is not None, "Input max_overlap of generate_proposal_labels should not be None if is_cascade_rcnn is True" + + rois = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype) + labels_int32 = helper.create_variable_for_type_inference( + dtype=gt_classes.dtype) + bbox_targets = helper.create_variable_for_type_inference( + dtype=rpn_rois.dtype) + bbox_inside_weights = helper.create_variable_for_type_inference( + dtype=rpn_rois.dtype) + bbox_outside_weights = helper.create_variable_for_type_inference( + dtype=rpn_rois.dtype) + max_overlap_with_gt = helper.create_variable_for_type_inference( + dtype=rpn_rois.dtype) + + inputs = { + 'RpnRois': rpn_rois, + 'GtClasses': gt_classes, + 'IsCrowd': is_crowd, + 'GtBoxes': gt_boxes, + 'ImInfo': im_info, + } + if max_overlap is not None: + inputs['MaxOverlap'] = max_overlap + helper.append_op(type="generate_proposal_labels", + inputs=inputs, + outputs={ + 'Rois': rois, + 'LabelsInt32': labels_int32, + 'BboxTargets': bbox_targets, + 'BboxInsideWeights': bbox_inside_weights, + 'BboxOutsideWeights': bbox_outside_weights, + 'MaxOverlapWithGT': max_overlap_with_gt + }, + attrs={ + 'batch_size_per_im': batch_size_per_im, + 'fg_fraction': fg_fraction, + 'fg_thresh': fg_thresh, + 'bg_thresh_hi': bg_thresh_hi, + 'bg_thresh_lo': bg_thresh_lo, + 'bbox_reg_weights': bbox_reg_weights, + 'class_nums': class_nums, + 'use_random': use_random, + 'is_cls_agnostic': is_cls_agnostic, + 'is_cascade_rcnn': is_cascade_rcnn + }) + + rois.stop_gradient = True + labels_int32.stop_gradient = True + bbox_targets.stop_gradient = True + bbox_inside_weights.stop_gradient = True + bbox_outside_weights.stop_gradient = True + max_overlap_with_gt.stop_gradient = True + + if return_max_overlap: + return rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights, max_overlap_with_gt + return rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights + + +def generate_mask_labels(im_info, gt_classes, is_crowd, gt_segms, rois, + labels_int32, num_classes, resolution): + r""" + + **Generate Mask Labels for Mask-RCNN** + + This operator can be, for given the RoIs and corresponding labels, + to sample foreground RoIs. This mask branch also has + a :math: `K \\times M^{2}` dimensional output targets for each foreground + RoI, which encodes K binary masks of resolution M x M, one for each of the + K classes. This mask targets are used to compute loss of mask branch. + + Please note, the data format of groud-truth segmentation, assumed the + segmentations are as follows. The first instance has two gt objects. + The second instance has one gt object, this object has two gt segmentations. + + .. code-block:: python + + #[ + # [[[229.14, 370.9, 229.14, 370.9, ...]], + # [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance + # [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance + #] + + batch_masks = [] + for semgs in batch_semgs: + gt_masks = [] + for semg in semgs: + gt_segm = [] + for polys in semg: + gt_segm.append(np.array(polys).reshape(-1, 2)) + gt_masks.append(gt_segm) + batch_masks.append(gt_masks) + + + place = fluid.CPUPlace() + feeder = fluid.DataFeeder(place=place, feed_list=feeds) + feeder.feed(batch_masks) + + Args: + im_info (Variable): A 2-D Tensor with shape [N, 3] and float32 + data type. N is the batch size, each element is + [height, width, scale] of image. Image scale is + target_size / original_size, target_size is the size after resize, + original_size is the original image size. + gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type + should be int. M is the total number of ground-truth, each + element is a class label. + is_crowd (Variable): A 2-D LoDTensor with same shape and same data type + as gt_classes, each element is a flag indicating whether a + groundtruth is crowd. + gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and + float32 data type, it's LoD level is 3. + Usually users do not needs to understand LoD, + The users should return correct data format in reader. + The LoD[0] represents the ground-truth objects number of + each instance. LoD[1] represents the segmentation counts of each + objects. LoD[2] represents the polygons number of each segmentation. + S the total number of polygons coordinate points. Each element is + (x, y) coordinate points. + rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type + float32. R is the total number of RoIs, each element is a bounding + box with (xmin, ymin, xmax, ymax) format in the range of original image. + labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type + of int32. R is the same as it in `rois`. Each element represents + a class label of a RoI. + num_classes (int): Class number. + resolution (int): Resolution of mask predictions. + + Returns: + mask_rois (Variable): A 2D LoDTensor with shape [P, 4] and same data + type as `rois`. P is the total number of sampled RoIs. Each element + is a bounding box with [xmin, ymin, xmax, ymax] format in range of + original image size. + + mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1] + and int data type, each element represents the output mask RoI + index with regard to input RoIs. + + mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int + data type, K is the classes number and M is the resolution of mask + predictions. Each element represents the binary mask targets. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + im_info = fluid.data(name="im_info", shape=[None, 3], + dtype="float32") + gt_classes = fluid.data(name="gt_classes", shape=[None, 1], + dtype="float32", lod_level=1) + is_crowd = fluid.data(name="is_crowd", shape=[None, 1], + dtype="float32", lod_level=1) + gt_masks = fluid.data(name="gt_masks", shape=[None, 2], + dtype="float32", lod_level=3) + # rois, roi_labels can be the output of + # fluid.layers.generate_proposal_labels. + rois = fluid.data(name="rois", shape=[None, 4], + dtype="float32", lod_level=1) + roi_labels = fluid.data(name="roi_labels", shape=[None, 1], + dtype="int32", lod_level=1) + mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels( + im_info=im_info, + gt_classes=gt_classes, + is_crowd=is_crowd, + gt_segms=gt_masks, + rois=rois, + labels_int32=roi_labels, + num_classes=81, + resolution=14) + """ + + helper = LayerHelper('generate_mask_labels', **locals()) + + mask_rois = helper.create_variable_for_type_inference(dtype=rois.dtype) + roi_has_mask_int32 = helper.create_variable_for_type_inference( + dtype=gt_classes.dtype) + mask_int32 = helper.create_variable_for_type_inference( + dtype=gt_classes.dtype) + + helper.append_op(type="generate_mask_labels", + inputs={ + 'ImInfo': im_info, + 'GtClasses': gt_classes, + 'IsCrowd': is_crowd, + 'GtSegms': gt_segms, + 'Rois': rois, + 'LabelsInt32': labels_int32 + }, + outputs={ + 'MaskRois': mask_rois, + 'RoiHasMaskInt32': roi_has_mask_int32, + 'MaskInt32': mask_int32 + }, + attrs={ + 'num_classes': num_classes, + 'resolution': resolution + }) + + mask_rois.stop_gradient = True + roi_has_mask_int32.stop_gradient = True + mask_int32.stop_gradient = True + + return mask_rois, roi_has_mask_int32, mask_int32 + + +def generate_proposals(scores, + bbox_deltas, + im_info, + anchors, + variances, + pre_nms_top_n=6000, + post_nms_top_n=1000, + nms_thresh=0.5, + min_size=0.1, + eta=1.0, + return_rois_num=False, + name=None): + """ + + **Generate proposal Faster-RCNN** + + This operation proposes RoIs according to each box with their + probability to be a foreground object and + the box can be calculated by anchors. Bbox_deltais and scores + to be an object are the output of RPN. Final proposals + could be used to train detection net. + + For generating proposals, this operation performs following steps: + + 1. Transposes and resizes scores and bbox_deltas in size of + (H*W*A, 1) and (H*W*A, 4) + 2. Calculate box locations as proposals candidates. + 3. Clip boxes to image + 4. Remove predicted boxes with small area. + 5. Apply NMS to get final proposals as output. + + Args: + scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents + the probability for each box to be an object. + N is batch size, A is number of anchors, H and W are height and + width of the feature map. The data type must be float32. + bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W] + represents the difference between predicted box location and + anchor location. The data type must be float32. + im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin + image information for N batch. Height and width are the input sizes + and scale is the ratio of network input size and original size. + The data type can be float32 or float64. + anchors(Variable): A 4-D Tensor represents the anchors with a layout + of [H, W, A, 4]. H and W are height and width of the feature map, + num_anchors is the box count of each position. Each anchor is + in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32. + variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of + [H, W, num_priors, 4]. Each variance is in + (xcenter, ycenter, w, h) format. The data type must be float32. + pre_nms_top_n(float): Number of total bboxes to be kept per + image before NMS. The data type must be float32. `6000` by default. + post_nms_top_n(float): Number of total bboxes to be kept per + image after NMS. The data type must be float32. `1000` by default. + nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default. + min_size(float): Remove predicted boxes with either height or + width < min_size. The data type must be float32. `0.1` by default. + eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`, + `adaptive_threshold = adaptive_threshold * eta` in each iteration. + return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's + num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents + the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model. + 'False' by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + tuple: + A tuple with format ``(rpn_rois, rpn_roi_probs)``. + + - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``. + - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32') + bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32') + im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32') + anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32') + variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32') + rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas, + im_info, anchors, variances) + + """ + return paddle.vision.ops.generate_proposals(scores=scores, + bbox_deltas=bbox_deltas, + img_size=im_info[:2], + anchors=anchors, + variances=variances, + pre_nms_top_n=pre_nms_top_n, + post_nms_top_n=post_nms_top_n, + nms_thresh=nms_thresh, + min_size=min_size, + eta=eta, + return_rois_num=return_rois_num, + name=name) + + +def box_clip(input, im_info, name=None): + """ + + Clip the box into the size given by im_info + For each input box, The formula is given as follows: + + .. code-block:: text + + xmin = max(min(xmin, im_w - 1), 0) + ymin = max(min(ymin, im_h - 1), 0) + xmax = max(min(xmax, im_w - 1), 0) + ymax = max(min(ymax, im_h - 1), 0) + + where im_w and im_h are computed from im_info: + + .. code-block:: text + + im_h = round(height / scale) + im_w = round(weight / scale) + + Args: + input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`, + the last dimension is 4 and data type is float32 or float64. + im_info(Variable): The 2-D Tensor with shape [N, 3] with layout + (height, width, scale) representing the information of image. + Height and width are the input sizes and scale is the ratio of network input + size and original size. The data type is float32 or float64. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: + + output(Variable): The clipped tensor with data type float32 or float64. + The shape is same as input. + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + boxes = fluid.data( + name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1) + im_info = fluid.data(name='im_info', shape=[-1 ,3]) + out = fluid.layers.box_clip( + input=boxes, im_info=im_info) + """ + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'box_clip') + check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], + 'box_clip') + + helper = LayerHelper("box_clip", **locals()) + output = helper.create_variable_for_type_inference(dtype=input.dtype) + inputs = {"Input": input, "ImInfo": im_info} + helper.append_op(type="box_clip", inputs=inputs, outputs={"Output": output}) + + return output + + +def retinanet_detection_output(bboxes, + scores, + anchors, + im_info, + score_threshold=0.05, + nms_top_k=1000, + keep_top_k=100, + nms_threshold=0.3, + nms_eta=1.0): + """ + **Detection Output Layer for the detector RetinaNet.** + + In the detector `RetinaNet `_ , many + `FPN `_ levels output the category + and location predictions, this OP is to get the detection results by + performing following steps: + + 1. For each FPN level, decode box predictions according to the anchor + boxes from at most :attr:`nms_top_k` top-scoring predictions after + thresholding detector confidence at :attr:`score_threshold`. + 2. Merge top predictions from all levels and apply multi-class non + maximum suppression (NMS) on them to get the final detections. + + Args: + bboxes(List): A list of Tensors from multiple FPN levels represents + the location prediction for all anchor boxes. Each element is + a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the + batch size, :math:`Mi` is the number of bounding boxes from + :math:`i`-th FPN level and each bounding box has four coordinate + values and the layout is [xmin, ymin, xmax, ymax]. The data type + of each element is float32 or float64. + scores(List): A list of Tensors from multiple FPN levels represents + the category prediction for all anchor boxes. Each element is a + 3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch + size, :math:`C` is the class number (**excluding background**), + :math:`Mi` is the number of bounding boxes from :math:`i`-th FPN + level. The data type of each element is float32 or float64. + anchors(List): A list of Tensors from multiple FPN levels represents + the locations of all anchor boxes. Each element is a 2-D Tensor + with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding + boxes from :math:`i`-th FPN level, and each bounding box has four + coordinate values and the layout is [xmin, ymin, xmax, ymax]. + The data type of each element is float32 or float64. + im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size + information of input images. :math:`N` is the batch size, the size + information of each image is a 3-vector which are the height and width + of the network input along with the factor scaling the origin image to + the network input. The data type of :attr:`im_info` is float32. + score_threshold(float): Threshold to filter out bounding boxes + with a confidence score before NMS, default value is set to 0.05. + nms_top_k(int): Maximum number of detections per FPN layer to be + kept according to the confidences before NMS, default value is set to + 1000. + keep_top_k(int): Number of total bounding boxes to be kept per image after + NMS step. Default value is set to 100, -1 means keeping all bounding + boxes after NMS step. + nms_threshold(float): The Intersection-over-Union(IoU) threshold used to + filter out boxes in NMS. + nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS. + Default value is set to 1., which represents the value of + :attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set + to be lower than 1. and the value of :attr:`nms_threshold` is set to + be higher than 0.5, everytime a bounding box is filtered out, + the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold` + = :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until + the actual value of :attr:`nms_threshold` is lower than or equal to + 0.5. + + **Notice**: In some cases where the image sizes are very small, it's possible + that there is no detection if :attr:`score_threshold` are used at all + levels. Hence, this OP do not filter out anchors from the highest FPN level + before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and + :attr:`anchors` is required to be from the highest FPN level. + + Returns: + Variable(The data type is float32 or float64): + The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`. + Each row has six values: [label, confidence, xmin, ymin, xmax, ymax]. + :math:`No` is the total number of detections in this mini-batch. + The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected + results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image + has no detected results. If all images have no detected results, + LoD will be set to 0, and the output tensor is empty (None). + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + bboxes_low = fluid.data( + name='bboxes_low', shape=[1, 44, 4], dtype='float32') + bboxes_high = fluid.data( + name='bboxes_high', shape=[1, 11, 4], dtype='float32') + scores_low = fluid.data( + name='scores_low', shape=[1, 44, 10], dtype='float32') + scores_high = fluid.data( + name='scores_high', shape=[1, 11, 10], dtype='float32') + anchors_low = fluid.data( + name='anchors_low', shape=[44, 4], dtype='float32') + anchors_high = fluid.data( + name='anchors_high', shape=[11, 4], dtype='float32') + im_info = fluid.data( + name="im_info", shape=[1, 3], dtype='float32') + nmsed_outs = fluid.layers.retinanet_detection_output( + bboxes=[bboxes_low, bboxes_high], + scores=[scores_low, scores_high], + anchors=[anchors_low, anchors_high], + im_info=im_info, + score_threshold=0.05, + nms_top_k=1000, + keep_top_k=100, + nms_threshold=0.45, + nms_eta=1.0) + """ + + check_type(bboxes, 'bboxes', (list), 'retinanet_detection_output') + for i, bbox in enumerate(bboxes): + check_variable_and_dtype(bbox, 'bbox{}'.format(i), + ['float32', 'float64'], + 'retinanet_detection_output') + check_type(scores, 'scores', (list), 'retinanet_detection_output') + for i, score in enumerate(scores): + check_variable_and_dtype(score, 'score{}'.format(i), + ['float32', 'float64'], + 'retinanet_detection_output') + check_type(anchors, 'anchors', (list), 'retinanet_detection_output') + for i, anchor in enumerate(anchors): + check_variable_and_dtype(anchor, 'anchor{}'.format(i), + ['float32', 'float64'], + 'retinanet_detection_output') + check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], + 'retinanet_detection_output') + + helper = LayerHelper('retinanet_detection_output', **locals()) + output = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('scores')) + helper.append_op(type="retinanet_detection_output", + inputs={ + 'BBoxes': bboxes, + 'Scores': scores, + 'Anchors': anchors, + 'ImInfo': im_info + }, + attrs={ + 'score_threshold': score_threshold, + 'nms_top_k': nms_top_k, + 'nms_threshold': nms_threshold, + 'keep_top_k': keep_top_k, + 'nms_eta': 1., + }, + outputs={'Out': output}) + output.stop_gradient = True + return output + + +def multiclass_nms(bboxes, + scores, + score_threshold, + nms_top_k, + keep_top_k, + nms_threshold=0.3, + normalized=True, + nms_eta=1., + background_label=0, + name=None): + """ + + **Multiclass NMS** + + This operator is to do multi-class non maximum suppression (NMS) on + boxes and scores. + + In the NMS step, this operator greedily selects a subset of detection bounding + boxes that have high scores larger than score_threshold, if providing this + threshold, then selects the largest nms_top_k confidences scores if nms_top_k + is larger than -1. Then this operator pruns away boxes that have high IOU + (intersection over union) overlap with already selected boxes by adaptive + threshold NMS based on parameters of nms_threshold and nms_eta. + Aftern NMS step, at most keep_top_k number of total bboxes are to be kept + per image if keep_top_k is larger than -1. + + See below for an example: + + .. code-block:: text + + if: + box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax) + box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4) + + box2.data = (3.0, 4.0, 8.0, 5.0) + box2.score = (0.3, 0.3, 0.1) + + nms_threshold = 0.3 + background_label = 0 + score_threshold = 0 + + + Then: + iou = 4/11 > 0.3 + out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0], + [2, 0.4, 2.0, 3.0, 7.0, 5.0]] + + Out format is (label, confidence, xmin, ymin, xmax, ymax) + Args: + bboxes (Variable): Two types of bboxes are supported: + 1. (Tensor) A 3-D Tensor with shape + [N, M, 4 or 8 16 24 32] represents the + predicted locations of M bounding bboxes, + N is the batch size. Each bounding box has four + coordinate values and the layout is + [xmin, ymin, xmax, ymax], when box size equals to 4. + The data type is float32 or float64. + 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4] + M is the number of bounding boxes, C is the + class number. The data type is float32 or float64. + scores (Variable): Two types of scores are supported: + 1. (Tensor) A 3-D Tensor with shape [N, C, M] + represents the predicted confidence predictions. + N is the batch size, C is the class number, M is + number of bounding boxes. For each category there + are total M scores which corresponding M bounding + boxes. Please note, M is equal to the 2nd dimension + of BBoxes.The data type is float32 or float64. + 2. (LoDTensor) A 2-D LoDTensor with shape [M, C]. + M is the number of bbox, C is the class number. + In this case, input BBoxes should be the second + case with shape [M, C, 4].The data type is float32 or float64. + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all + categories will be considered. Default: 0 + score_threshold (float): Threshold to filter out bounding boxes with + low confidence score. If not provided, + consider all boxes. + nms_top_k (int): Maximum number of detections to be kept according to + the confidences after the filtering detections based + on score_threshold. + nms_threshold (float): The threshold to be used in NMS. Default: 0.3 + nms_eta (float): The threshold to be used in NMS. Default: 1.0 + keep_top_k (int): Number of total bboxes to be kept per image after NMS + step. -1 means keeping all bboxes after NMS step. + normalized (bool): Whether detections are normalized. Default: True + name(str): Name of the multiclass nms op. Default: None. + + Returns: + Variable: A 2-D LoDTensor with shape [No, 6] represents the detections. + Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax] + or A 2-D LoDTensor with shape [No, 10] represents the detections. + Each row has 10 values: + [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the + total number of detections. If there is no detected boxes for all + images, lod will be set to {1} and Out only contains one value + which is -1. + (After version 1.3, when no boxes detected, the lod is changed + from {0} to {1}) + + + Examples: + .. code-block:: python + + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + boxes = fluid.data(name='bboxes', shape=[None,81, 4], + dtype='float32', lod_level=1) + scores = fluid.data(name='scores', shape=[None,81], + dtype='float32', lod_level=1) + out = fluid.layers.multiclass_nms(bboxes=boxes, + scores=scores, + background_label=0, + score_threshold=0.5, + nms_top_k=400, + nms_threshold=0.3, + keep_top_k=200, + normalized=False) + """ + check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], + 'multiclass_nms') + check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], + 'multiclass_nms') + check_type(score_threshold, 'score_threshold', float, 'multicalss_nms') + check_type(nms_top_k, 'nums_top_k', int, 'multiclass_nms') + check_type(keep_top_k, 'keep_top_k', int, 'mutliclass_nms') + check_type(nms_threshold, 'nms_threshold', float, 'multiclass_nms') + check_type(normalized, 'normalized', bool, 'multiclass_nms') + check_type(nms_eta, 'nms_eta', float, 'multiclass_nms') + check_type(background_label, 'background_label', int, 'multiclass_nms') + + helper = LayerHelper('multiclass_nms', **locals()) + output = helper.create_variable_for_type_inference(dtype=bboxes.dtype) + helper.append_op(type="multiclass_nms", + inputs={ + 'BBoxes': bboxes, + 'Scores': scores + }, + attrs={ + 'background_label': background_label, + 'score_threshold': score_threshold, + 'nms_top_k': nms_top_k, + 'nms_threshold': nms_threshold, + 'nms_eta': nms_eta, + 'keep_top_k': keep_top_k, + 'normalized': normalized + }, + outputs={'Out': output}) + output.stop_gradient = True + + return output + + +def locality_aware_nms(bboxes, + scores, + score_threshold, + nms_top_k, + keep_top_k, + nms_threshold=0.3, + normalized=True, + nms_eta=1., + background_label=-1, + name=None): + """ + **Local Aware NMS** + + `Local Aware NMS `_ is to do locality-aware non maximum + suppression (LANMS) on boxes and scores. + + Firstly, this operator merge box and score according their IOU + (intersection over union). In the NMS step, this operator greedily selects a + subset of detection bounding boxes that have high scores larger than score_threshold, + if providing this threshold, then selects the largest nms_top_k confidences scores + if nms_top_k is larger than -1. Then this operator pruns away boxes that have high + IOU overlap with already selected boxes by adaptive threshold NMS based on parameters + of nms_threshold and nms_eta. + + Aftern NMS step, at most keep_top_k number of total bboxes are to be kept + per image if keep_top_k is larger than -1. + + Args: + bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32] + represents the predicted locations of M bounding + bboxes, N is the batch size. Each bounding box + has four coordinate values and the layout is + [xmin, ymin, xmax, ymax], when box size equals to 4. + The data type is float32 or float64. + scores (Variable): A 3-D Tensor with shape [N, C, M] represents the + predicted confidence predictions. N is the batch + size, C is the class number, M is number of bounding + boxes. Now only support 1 class. For each category + there are total M scores which corresponding M bounding + boxes. Please note, M is equal to the 2nd dimension of + BBoxes. The data type is float32 or float64. + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all + categories will be considered. Default: -1 + score_threshold (float): Threshold to filter out bounding boxes with + low confidence score. If not provided, + consider all boxes. + nms_top_k (int): Maximum number of detections to be kept according to + the confidences after the filtering detections based + on score_threshold. + keep_top_k (int): Number of total bboxes to be kept per image after NMS + step. -1 means keeping all bboxes after NMS step. + nms_threshold (float): The threshold to be used in NMS. Default: 0.3 + nms_eta (float): The threshold to be used in NMS. Default: 1.0 + normalized (bool): Whether detections are normalized. Default: True + name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` . + Default: None. + + Returns: + Variable: A 2-D LoDTensor with shape [No, 6] represents the detections. + Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax] + or A 2-D LoDTensor with shape [No, 10] represents the detections. + Each row has 10 values: + [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the + total number of detections. If there is no detected boxes for all + images, lod will be set to {1} and Out only contains one value + which is -1. + (After version 1.3, when no boxes detected, the lod is changed + from {0} to {1}). The data type is float32 or float64. + + + Examples: + .. code-block:: python + + + import paddle.fluid as fluid + boxes = fluid.data(name='bboxes', shape=[None, 81, 8], + dtype='float32') + scores = fluid.data(name='scores', shape=[None, 1, 81], + dtype='float32') + out = fluid.layers.locality_aware_nms(bboxes=boxes, + scores=scores, + score_threshold=0.5, + nms_top_k=400, + nms_threshold=0.3, + keep_top_k=200, + normalized=False) + """ + check_variable_and_dtype(bboxes, 'bboxes', ['float32', 'float64'], + 'locality_aware_nms') + check_variable_and_dtype(scores, 'scores', ['float32', 'float64'], + 'locality_aware_nms') + check_type(background_label, 'background_label', int, 'locality_aware_nms') + check_type(score_threshold, 'score_threshold', float, 'locality_aware_nms') + check_type(nms_top_k, 'nms_top_k', int, 'locality_aware_nms') + check_type(nms_eta, 'nms_eta', float, 'locality_aware_nms') + check_type(nms_threshold, 'nms_threshold', float, 'locality_aware_nms') + check_type(keep_top_k, 'keep_top_k', int, 'locality_aware_nms') + check_type(normalized, 'normalized', bool, 'locality_aware_nms') + + shape = scores.shape + assert len(shape) == 3, "dim size of scores must be 3" + assert shape[ + 1] == 1, "locality_aware_nms only support one class, Tensor score shape must be [N, 1, M]" + + helper = LayerHelper('locality_aware_nms', **locals()) + + output = helper.create_variable_for_type_inference(dtype=bboxes.dtype) + out = {'Out': output} + + helper.append_op(type="locality_aware_nms", + inputs={ + 'BBoxes': bboxes, + 'Scores': scores + }, + attrs={ + 'background_label': background_label, + 'score_threshold': score_threshold, + 'nms_top_k': nms_top_k, + 'nms_threshold': nms_threshold, + 'nms_eta': nms_eta, + 'keep_top_k': keep_top_k, + 'nms_eta': nms_eta, + 'normalized': normalized + }, + outputs={'Out': output}) + output.stop_gradient = True + + return output + + +def matrix_nms(bboxes, + scores, + score_threshold, + post_threshold, + nms_top_k, + keep_top_k, + use_gaussian=False, + gaussian_sigma=2., + background_label=0, + normalized=True, + return_index=False, + name=None): + """ + **Matrix NMS** + + This operator does matrix non maximum suppression (NMS). + + First selects a subset of candidate bounding boxes that have higher scores + than score_threshold (if provided), then the top k candidate is selected if + nms_top_k is larger than -1. Score of the remaining candidate are then + decayed according to the Matrix NMS scheme. + Aftern NMS step, at most keep_top_k number of total bboxes are to be kept + per image if keep_top_k is larger than -1. + + Args: + bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the + predicted locations of M bounding bboxes, + N is the batch size. Each bounding box has four + coordinate values and the layout is + [xmin, ymin, xmax, ymax], when box size equals to 4. + The data type is float32 or float64. + scores (Variable): A 3-D Tensor with shape [N, C, M] + represents the predicted confidence predictions. + N is the batch size, C is the class number, M is + number of bounding boxes. For each category there + are total M scores which corresponding M bounding + boxes. Please note, M is equal to the 2nd dimension + of BBoxes. The data type is float32 or float64. + score_threshold (float): Threshold to filter out bounding boxes with + low confidence score. + post_threshold (float): Threshold to filter out bounding boxes with + low confidence score AFTER decaying. + nms_top_k (int): Maximum number of detections to be kept according to + the confidences after the filtering detections based + on score_threshold. + keep_top_k (int): Number of total bboxes to be kept per image after NMS + step. -1 means keeping all bboxes after NMS step. + use_gaussian (bool): Use Gaussian as the decay function. Default: False + gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0 + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all + categories will be considered. Default: 0 + normalized (bool): Whether detections are normalized. Default: True + return_index(bool): Whether return selected index. Default: False + name(str): Name of the matrix nms op. Default: None. + + Returns: + A tuple with two Variables: (Out, Index) if return_index is True, + otherwise, one Variable(Out) is returned. + + Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the + detection results. + Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax] + (After version 1.3, when no boxes detected, the lod is changed + from {0} to {1}) + + Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the + selected indices, which are absolute values cross batches. + + Examples: + .. code-block:: python + + + import paddle.fluid as fluid + boxes = fluid.data(name='bboxes', shape=[None,81, 4], + dtype='float32', lod_level=1) + scores = fluid.data(name='scores', shape=[None,81], + dtype='float32', lod_level=1) + out = fluid.layers.matrix_nms(bboxes=boxes, + scores=scores, + background_label=0, + score_threshold=0.5, + post_threshold=0.1, + nms_top_k=400, + keep_top_k=200, + normalized=False) + """ + if in_dygraph_mode(): + attrs = (score_threshold, nms_top_k, keep_top_k, post_threshold, + use_gaussian, gaussian_sigma, background_label, normalized) + + out, index = _C_ops.matrix_nms(bboxes, scores, *attrs) + if return_index: + return out, index + else: + return out + + check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], + 'matrix_nms') + check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], + 'matrix_nms') + check_type(score_threshold, 'score_threshold', float, 'matrix_nms') + check_type(post_threshold, 'post_threshold', float, 'matrix_nms') + check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms') + check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms') + check_type(normalized, 'normalized', bool, 'matrix_nms') + check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms') + check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms') + check_type(background_label, 'background_label', int, 'matrix_nms') + + helper = LayerHelper('matrix_nms', **locals()) + output = helper.create_variable_for_type_inference(dtype=bboxes.dtype) + index = helper.create_variable_for_type_inference(dtype='int') + helper.append_op(type="matrix_nms", + inputs={ + 'BBoxes': bboxes, + 'Scores': scores + }, + attrs={ + 'score_threshold': score_threshold, + 'post_threshold': post_threshold, + 'nms_top_k': nms_top_k, + 'keep_top_k': keep_top_k, + 'use_gaussian': use_gaussian, + 'gaussian_sigma': gaussian_sigma, + 'background_label': background_label, + 'normalized': normalized + }, + outputs={ + 'Out': output, + 'Index': index + }) + output.stop_gradient = True + + if return_index: + return output, index + else: + return output + + +def distribute_fpn_proposals(fpn_rois, + min_level, + max_level, + refer_level, + refer_scale, + rois_num=None, + name=None): + r""" + + **This op only takes LoDTensor as input.** In Feature Pyramid Networks + (FPN) models, it is needed to distribute all proposals into different FPN + level, with respect to scale of the proposals, the referring scale and the + referring level. Besides, to restore the order of proposals, we return an + array which indicates the original index of rois in current proposals. + To compute FPN level for each roi, the formula is given as follows: + + .. math:: + + roi\_scale &= \sqrt{BBoxArea(fpn\_roi)} + + level = floor(&\log(\\frac{roi\_scale}{refer\_scale}) + refer\_level) + + where BBoxArea is a function to compute the area of each roi. + + Args: + + fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is + float32 or float64. The input fpn_rois. + min_level(int32): The lowest level of FPN layer where the proposals come + from. + max_level(int32): The highest level of FPN layer where the proposals + come from. + refer_level(int32): The referring level of FPN layer with specified scale. + refer_scale(int32): The referring scale of FPN layer with specified level. + rois_num(Tensor): 1-D Tensor contains the number of RoIs in each image. + The shape is [B] and data type is int32. B is the number of images. + If it is not None then return a list of 1-D Tensor. Each element + is the output RoIs' number of each image on the corresponding level + and the shape is [B]. None by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tuple: + + multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4] + and data type of float32 and float64. The length is + max_level-min_level+1. The proposals in each FPN level. + + restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is + the number of total rois. The data type is int32. It is + used to restore the order of fpn_rois. + + rois_num_per_level(List): A list of 1-D Tensor and each Tensor is + the RoIs' number in each image on the corresponding level. The shape + is [B] and data type of int32. B is the number of images + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + fpn_rois = fluid.data( + name='data', shape=[None, 4], dtype='float32', lod_level=1) + multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals( + fpn_rois=fpn_rois, + min_level=2, + max_level=5, + refer_level=4, + refer_scale=224) + """ + return paddle.vision.ops.distribute_fpn_proposals(fpn_rois=fpn_rois, + min_level=min_level, + max_level=max_level, + refer_level=refer_level, + refer_scale=refer_scale, + rois_num=rois_num, + name=name) + + +@templatedoc() +def box_decoder_and_assign(prior_box, + prior_box_var, + target_box, + box_score, + box_clip, + name=None): + """ + + ${comment} + Args: + prior_box(${prior_box_type}): ${prior_box_comment} + prior_box_var(${prior_box_var_type}): ${prior_box_var_comment} + target_box(${target_box_type}): ${target_box_comment} + box_score(${box_score_type}): ${box_score_comment} + box_clip(${box_clip_type}): ${box_clip_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tuple: + + decode_box(${decode_box_type}): ${decode_box_comment} + + output_assign_box(${output_assign_box_type}): ${output_assign_box_comment} + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + pb = fluid.data( + name='prior_box', shape=[None, 4], dtype='float32') + pbv = fluid.data( + name='prior_box_var', shape=[4], dtype='float32') + loc = fluid.data( + name='target_box', shape=[None, 4*81], dtype='float32') + scores = fluid.data( + name='scores', shape=[None, 81], dtype='float32') + decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign( + pb, pbv, loc, scores, 4.135) + + """ + check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'], + 'box_decoder_and_assign') + check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'], + 'box_decoder_and_assign') + check_variable_and_dtype(box_score, 'box_score', ['float32', 'float64'], + 'box_decoder_and_assign') + helper = LayerHelper("box_decoder_and_assign", **locals()) + + decoded_box = helper.create_variable_for_type_inference( + dtype=prior_box.dtype) + output_assign_box = helper.create_variable_for_type_inference( + dtype=prior_box.dtype) + + helper.append_op(type="box_decoder_and_assign", + inputs={ + "PriorBox": prior_box, + "PriorBoxVar": prior_box_var, + "TargetBox": target_box, + "BoxScore": box_score + }, + attrs={"box_clip": box_clip}, + outputs={ + "DecodeBox": decoded_box, + "OutputAssignBox": output_assign_box + }) + return decoded_box, output_assign_box + + +def collect_fpn_proposals(multi_rois, + multi_scores, + min_level, + max_level, + post_nms_top_n, + rois_num_per_level=None, + name=None): + """ + + **This OP only supports LoDTensor as input**. Concat multi-level RoIs + (Region of Interest) and select N RoIs with respect to multi_scores. + This operation performs the following steps: + + 1. Choose num_level RoIs and scores as input: num_level = max_level - min_level + 2. Concat multi-level RoIs and scores + 3. Sort scores and select post_nms_top_n scores + 4. Gather RoIs by selected indices from scores + 5. Re-sort RoIs by corresponding batch_id + + Args: + multi_rois(list): List of RoIs to collect. Element in list is 2-D + LoDTensor with shape [N, 4] and data type is float32 or float64, + N is the number of RoIs. + multi_scores(list): List of scores of RoIs to collect. Element in list + is 2-D LoDTensor with shape [N, 1] and data type is float32 or + float64, N is the number of RoIs. + min_level(int): The lowest level of FPN layer to collect + max_level(int): The highest level of FPN layer to collect + post_nms_top_n(int): The number of selected RoIs + rois_num_per_level(list, optional): The List of RoIs' numbers. + Each element is 1-D Tensor which contains the RoIs' number of each + image on each level and the shape is [B] and data type is + int32, B is the number of images. If it is not None then return + a 1-D Tensor contains the output RoIs' number of each image and + the shape is [B]. Default: None + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: + + fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is + float32 or float64. Selected RoIs. + + rois_num(Tensor): 1-D Tensor contains the RoIs's number of each + image. The shape is [B] and data type is int32. B is the number of + images. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + multi_rois = [] + multi_scores = [] + for i in range(4): + multi_rois.append(fluid.data( + name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1)) + for i in range(4): + multi_scores.append(fluid.data( + name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1)) + + fpn_rois = fluid.layers.collect_fpn_proposals( + multi_rois=multi_rois, + multi_scores=multi_scores, + min_level=2, + max_level=5, + post_nms_top_n=2000) + """ + num_lvl = max_level - min_level + 1 + input_rois = multi_rois[:num_lvl] + input_scores = multi_scores[:num_lvl] + + if _non_static_mode(): + assert rois_num_per_level is not None, "rois_num_per_level should not be None in dygraph mode." + attrs = ('post_nms_topN', post_nms_top_n) + output_rois, rois_num = _legacy_C_ops.collect_fpn_proposals( + input_rois, input_scores, rois_num_per_level, *attrs) + + check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals') + check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals') + helper = LayerHelper('collect_fpn_proposals', **locals()) + dtype = helper.input_dtype('multi_rois') + check_dtype(dtype, 'multi_rois', ['float32', 'float64'], + 'collect_fpn_proposals') + output_rois = helper.create_variable_for_type_inference(dtype) + output_rois.stop_gradient = True + + inputs = { + 'MultiLevelRois': input_rois, + 'MultiLevelScores': input_scores, + } + outputs = {'FpnRois': output_rois} + if rois_num_per_level is not None: + inputs['MultiLevelRoIsNum'] = rois_num_per_level + rois_num = helper.create_variable_for_type_inference(dtype='int32') + rois_num.stop_gradient = True + outputs['RoisNum'] = rois_num + helper.append_op(type='collect_fpn_proposals', + inputs=inputs, + outputs=outputs, + attrs={'post_nms_topN': post_nms_top_n}) + if rois_num_per_level is not None: + return output_rois, rois_num + return output_rois diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/device.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/device.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b967a8509e47acb4b480f14eeecd26653a28b9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/device.py @@ -0,0 +1,44 @@ +# Copyright (c) 2018 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. +""" +All util layers. +""" + +from __future__ import print_function + +from .layer_function_generator import autodoc +from ..framework import unique_name +from ..layer_helper import LayerHelper +from paddle.utils import deprecated + +__all__ = [] + + +@deprecated(since='0.15.0', update_to="paddle.fluid.ParallelExecutor") +@autodoc() +def get_places(device_count=None, device_type=None): + helper = LayerHelper('get_places', **locals()) + out_places = helper.create_variable( + name=unique_name.generate_with_ignorable_key(helper.name + ".out")) + attrs = dict() + if device_count is not None: + attrs['device_count'] = int(device_count) + if device_type is not None: + attrs['device_type'] = str(device_type) + + helper.append_op(type='get_places', + outputs={"Out": [out_places]}, + attrs=attrs) + + return out_places diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/distributions.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..757ba0dc8855fb4dd1c2c0e25e7d754789fffab0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/distributions.py @@ -0,0 +1,666 @@ +# 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. + +from __future__ import print_function + +from . import control_flow +from . import tensor +from . import ops +from . import nn +import math +import numpy as np +import warnings + +from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype + +__all__ = ['Uniform', 'Normal', 'Categorical', 'MultivariateNormalDiag'] + + +class Distribution(object): + """ + Distribution is the abstract base class for probability distributions. + """ + + def sample(self): + """Sampling from the distribution.""" + raise NotImplementedError + + def entropy(self): + """The entropy of the distribution.""" + raise NotImplementedError + + def kl_divergence(self, other): + """The KL-divergence between self distributions and other.""" + raise NotImplementedError + + def log_prob(self, value): + """Log probability density/mass function.""" + raise NotImplementedError + + def _validate_args(self, *args): + """ + Argument validation for distribution args + Args: + value (float, list, numpy.ndarray, Variable) + Raises + ValueError: if one argument is Variable, all arguments should be Variable + """ + is_variable = False + is_number = False + for arg in args: + if isinstance(arg, tensor.Variable): + is_variable = True + else: + is_number = True + + if is_variable and is_number: + raise ValueError( + 'if one argument is Variable, all arguments should be Variable') + + return is_variable + + def _to_variable(self, *args): + """ + Argument convert args to Variable + + Args: + value (float, list, numpy.ndarray, Variable) + Returns: + Variable of args. + """ + numpy_args = [] + variable_args = [] + tmp = 0. + + for arg in args: + valid_arg = False + for cls in [float, list, np.ndarray, tensor.Variable]: + if isinstance(arg, cls): + valid_arg = True + break + assert valid_arg, "type of input args must be float, list, numpy.ndarray or Variable." + if isinstance(arg, float): + arg = np.zeros(1) + arg + arg_np = np.array(arg) + arg_dtype = arg_np.dtype + if str(arg_dtype) not in ['float32']: + warnings.warn( + "data type of argument only support float32, your argument will be convert to float32." + ) + arg_np = arg_np.astype('float32') + tmp = tmp + arg_np + numpy_args.append(arg_np) + + dtype = tmp.dtype + for arg in numpy_args: + arg_broadcasted, _ = np.broadcast_arrays(arg, tmp) + arg_variable = tensor.create_tensor(dtype=dtype) + tensor.assign(arg_broadcasted, arg_variable) + variable_args.append(arg_variable) + + return tuple(variable_args) + + +class Uniform(Distribution): + r"""Uniform distribution with `low` and `high` parameters. + + Mathematical Details + + The probability density function (pdf) is, + + .. math:: + + pdf(x; a, b) = \\frac{1}{Z}, \ a <=x = 0 + parent_block = prog.block(parent_idx) + return parent_block + + def complete_op(self): + from ..incubate.fleet.parameter_server.mode import DistributedMode + + main_program = self.helper.main_program + current_block = main_program.current_block() + parent_block = self.parent_block() + + parent_block.append_op( + type='listen_and_serv', + inputs={"X": self.inputs}, + outputs={}, + attrs={ + 'endpoint': self.endpoint, + 'Fanin': self.fan_in, + 'optimize_blocks': + [current_block + ], # did not support multiple optimize blocks in layers + 'distributed_mode': + DistributedMode.SYNC, # did not support async now in layers + 'grad_to_block_id': [""] + }) + + +def Send(endpoints, send_vars, dummy_output=None, sync=True): + """ + Send variables to the server side, and get vars from server + side when server have finished running server side program. + + Args: + endpoints (str): comma separated IP:PORT pairs in the order + of send_vars to send + send_vars (list): variables to send to server + sync (bool): whether to wait the request finish + + """ + assert (type(send_vars) == list) + + if dummy_output is None: + dummy_output = [] + elif isinstance(dummy_output, Variable): + dummy_output = [dummy_output] + + assert (type(dummy_output) == list) + + epmap = endpoints.split(",") + endpoints = list(set(epmap)) + + helper = LayerHelper("Send", **locals()) + rpc_op_role_name = core.op_proto_and_checker_maker.kOpRoleAttrName() + + helper.append_op(type="send", + inputs={"X": send_vars}, + outputs={"Out": dummy_output}, + attrs={ + "endpoints": + endpoints, + "epmap": + epmap, + rpc_op_role_name: + core.op_proto_and_checker_maker.OpRole.RPC + }) + if sync: + helper.append_op(type="send_barrier", + inputs={"X": dummy_output}, + outputs={"Out": []}, + attrs={"endpoints": endpoints}) + + +def Recv(endpoints, get_vars, dummy_input=None, sync=True): + """ + Receive variables from server side + + Args: + endpoints (str): comma separated IP:PORT pairs in the order + of send_vars to send + get_vars (list): vars to get from server after send completes. + sync (bool): whether to wait the request finish + + Returns: + list: list of received variables + """ + assert (type(get_vars) == list) + + if dummy_input is None: + dummy_input = [] + elif isinstance(dummy_input, Variable): + dummy_input = [dummy_input] + + assert (type(dummy_input) == list) + + epmap = endpoints.split(",") + endpoints = list(set(epmap)) + + helper = LayerHelper("Recv", **locals()) + helper.append_op(type="recv", + inputs={"X": dummy_input}, + outputs={"Out": get_vars}, + attrs={ + "endpoints": endpoints, + "epmap": epmap + }) + if sync: + helper.append_op(type="fetch_barrier", + outputs={"Out": get_vars}, + attrs={"endpoints": endpoints}) + return get_vars + + +def monkey_patch_reader_methods(reader): + + def __get_reader__(): + scope = global_scope() + var = scope.find_var(reader.name) + return var.get_reader() + + def reset(): + return __get_reader__().reset() + + reader.reset = reset + reader.stop_gradient = True + reader.persistable = True + return reader + + +def _copy_reader_var_(block, var): + new_var = block.create_var(name=var.name, type=core.VarDesc.VarType.READER) + new_var.desc.set_shapes(var.desc.shapes()) + new_var.desc.set_dtypes(var.desc.dtypes()) + new_var.desc.set_lod_levels(var.desc.lod_levels()) + new_var.persistable = True + return new_var + + +def _copy_reader_create_op_(block, op): + input_param_names = op.input_names + new_input_map = {} + for param_name in input_param_names: + new_input_map[param_name] = [] + arg_names = op.input(param_name) + for arg_name in arg_names: + new_input_map[param_name].append(block.var(arg_name)) + + output_param_names = op.output_names + new_output_map = {} + for param_name in output_param_names: + new_output_map[param_name] = [] + arg_names = op.output(param_name) + for arg_name in arg_names: + new_output_map[param_name].append(block.var(arg_name)) + + new_op = block.append_op(type=op.type, + inputs=new_input_map, + outputs=new_output_map, + attrs=op.all_attrs()) + return new_op + + +def _py_reader(capacity, + shapes, + dtypes, + lod_levels=None, + name=None, + use_double_buffer=True, + feed_list=None): + if feed_list is not None: + if not isinstance(feed_list, list): + raise TypeError("feed_list should be a list of Variable" + " instead of " + str(type(feed_list))) + lod_levels = [] + dtypes = [] + shape_concat = [] + ranks = [] + shapes = [] + need_check_feed = [] + + for feed_data in feed_list: + dtypes.append(feed_data.dtype) + shape_concat.extend(feed_data.shape) + ranks.append(len(feed_data.shape)) + shapes.append(feed_data.shape) + lod_levels.append(feed_data.lod_level) + need_check_feed.append(int(feed_data.desc.need_check_feed())) + else: + dtypes = [convert_np_dtype_to_dtype_(dt) for dt in dtypes] + need_check_feed = [0 for dt in dtypes] + shape_concat = [] + ranks = [] + + for shape in shapes: + shape_concat.extend(shape) + ranks.append(len(shape)) + + if lod_levels is None: + lod_levels = [0] * len(shapes) + dtype_int = [int(t) for t in dtypes] + if name is None: + queue_name = unique_name('lod_tensor_blocking_queue') + reader_name = unique_name('create_py_reader') + double_buffer_name = unique_name('double_buffer') + else: + queue_name = "_".join([name, "queue"]) + reader_name = "_".join([name, "reader"]) + double_buffer_name = "_".join([name, "double_buffer"]) + + var = global_scope().var(queue_name) + feed_queue = core.init_lod_tensor_blocking_queue(var, capacity, False) + + startup_blk = default_startup_program().current_block() + startup_var = startup_blk.create_var(name=reader_name) + startup_blk.append_op(type='create_py_reader', + inputs={'blocking_queue': [queue_name]}, + outputs={'Out': [startup_var]}, + attrs={ + 'shape_concat': shape_concat, + 'lod_levels': lod_levels, + 'dtypes': dtype_int, + 'need_check_feed': need_check_feed, + 'ranks': ranks + }) + + startup_var.desc.set_dtypes(dtypes) + startup_var.persistable = True + + main_prog_var = _copy_reader_var_(default_main_program().current_block(), + startup_var) + + reader = monkey_patch_reader_methods(main_prog_var) + if use_double_buffer: + double_buffer_reader = double_buffer(reader, name=double_buffer_name) + # we return a double buffer reader. However, the reset method comes from + # py_reader. + double_buffer_reader.reset = reader.reset + reader = double_buffer_reader + + # monkey patch py_reader special methods + reader.queue = feed_queue + current_reset_method = reader.reset + reader.thread = None + reader.tensor_provider = None + reader.exited = False + + def start_provide_thread(func): + + def __provider_thread__(legacy_expected_place): + try: + # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here. + _set_expected_place(legacy_expected_place) + + for tensors in func(): + array = core.LoDTensorArray() + for item in tensors: + if not isinstance(item, core.LoDTensor): + tmp = core.LoDTensor() + tmp.set(item, core.CPUPlace()) + item = tmp + + array.append(item) + + if reader.exited: + break + feed_queue.push(array) + if reader.exited: + break + feed_queue.close() + except Exception as ex: + feed_queue.kill() + logging.warn('Your decorated reader has raised an exception!') + six.reraise(*sys.exc_info()) + + reader.thread = threading.Thread(target=__provider_thread__, + args=(_current_expected_place(), )) + reader.thread.daemon = True + reader.thread.start() + + def __set_tensor_provider__(func): + reader.tensor_provider = func + + def __set_paddle_reader__(paddle_reader): + with program_guard(Program(), Program()): + actual_feed_list = feed_list + if actual_feed_list is None: + actual_feed_list = [] + counter = 0 + for dtype, shape, lod_level in zip(dtypes, shapes, lod_levels): + name = str(counter) + actual_feed_list.append( + data(name=name, + dtype=dtype, + shape=shape, + lod_level=lod_level)) + counter += 1 + + data_names = [feed_data.name for feed_data in actual_feed_list] + feeder = DataFeeder(feed_list=actual_feed_list, + place=core.CPUPlace()) + paddle_reader = feeder.decorate_reader(paddle_reader, + multi_devices=False) + + def __tensor_provider__(): + for slots in paddle_reader(): + yield [slots[data_name] for data_name in data_names] + + __set_tensor_provider__(__tensor_provider__) + + def __reset__(): + current_reset_method() + if reader.thread is not None and reader.tensor_provider is not None: + reader.exited = True + reader.thread.join() + reader.exited = False + + def __start__(): + start_provide_thread(reader.tensor_provider) + + reader.reset = __reset__ + reader.decorate_tensor_provider = __set_tensor_provider__ + reader.decorate_paddle_reader = __set_paddle_reader__ + + reader.decorate_batch_generator = __set_tensor_provider__ + reader.decorate_sample_list_generator = __set_paddle_reader__ + reader.start = __start__ + + return reader + + +def py_reader(capacity, + shapes, + dtypes, + lod_levels=None, + name=None, + use_double_buffer=True): + """ + :api_attr: Static Graph + + Create a Python reader for data feeding in Python + + This operator returns a Reader Variable. + The Reader provides :code:`decorate_paddle_reader()` and + :code:`decorate_tensor_provider()` to set a Python generator as the data + source and feed the data from the data source to the Reader Variable. + When :code:`Executor::Run()` is invoked in C++ side, the data from the + generator would be read automatically. Unlike :code:`DataFeeder.feed()`, + the data reading process and :code:`Executor::Run()` process can run in + parallel using :code:`py_reader`. The :code:`start()` method of the Reader + should be called when each pass begins, while the :code:`reset()` method + should be called when the pass ends and :code:`fluid.core.EOFException` raises. + + Note: + :code:`Program.clone()` method cannot clone :code:`py_reader`. You can + refer to :ref:`api_fluid_Program` for more details. + + The :code:`read_file` call needs to be in the program block of :code:`py_reader`. + You can refer to :ref:`api_fluid_layers_read_file` for more details. + + Args: + capacity(int): The buffer capacity maintained by :code:`py_reader`. + shapes(list|tuple): List of tuples which declaring data shapes. shapes[i] + represents the i-th data shape. + dtypes(list|tuple): List of strings which declaring data type. Supported dtype: + bool, float16, float32, float64, int8, int16, int32, int64, uint8. + lod_levels(list|tuple): List of ints which declaring data lod_level. + name(basestring): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + use_double_buffer(bool): Whether use double buffer or not. The double buffer is + for pre-reading the data of the next batch and copy the data asynchronously + from CPU to GPU. Default is True. + + Returns: + A Reader from which we can get feeding data. + + Return Type: + Variable + + Examples: + 1. The basic usage of :code:`py_reader` is as follows: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.dataset.mnist as mnist + + def network(image, label): + # user defined network, here a softmax regession example + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + reader = fluid.layers.py_reader(capacity=64, + shapes=[(-1, 1, 28, 28), (-1, 1)], + dtypes=['float32', 'int64']) + reader.decorate_paddle_reader( + paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), + buf_size=1000)) + + img, label = fluid.layers.read_file(reader) + loss = network(img, label) + + fluid.Executor(fluid.CUDAPlace(0)).run(fluid.default_startup_program()) + exe = fluid.ParallelExecutor(use_cuda=True) + for epoch_id in range(10): + reader.start() + try: + while True: + exe.run(fetch_list=[loss.name]) + except fluid.core.EOFException: + reader.reset() + + fluid.io.save_inference_model(dirname='./model', + feeded_var_names=[img.name, label.name], + target_vars=[loss], + executor=fluid.Executor(fluid.CUDAPlace(0))) + + 2. When training and testing are both performed, two different + :code:`py_reader` should be created with different names, e.g.: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.dataset.mnist as mnist + + def network(reader): + img, label = fluid.layers.read_file(reader) + # User defined network. Here a simple regression as example + predict = fluid.layers.fc(input=img, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=predict, label=label) + return fluid.layers.mean(loss) + + # Create train_main_prog and train_startup_prog + train_main_prog = fluid.Program() + train_startup_prog = fluid.Program() + with fluid.program_guard(train_main_prog, train_startup_prog): + # Use fluid.unique_name.guard() to share parameters with test program + with fluid.unique_name.guard(): + train_reader = fluid.layers.py_reader(capacity=64, + shapes=[(-1, 1, 28, 28), + (-1, 1)], + dtypes=['float32', 'int64'], + name='train_reader') + train_reader.decorate_paddle_reader( + paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), + buf_size=500)) + train_loss = network(train_reader) # some network definition + adam = fluid.optimizer.Adam(learning_rate=0.01) + adam.minimize(train_loss) + + # Create test_main_prog and test_startup_prog + test_main_prog = fluid.Program() + test_startup_prog = fluid.Program() + with fluid.program_guard(test_main_prog, test_startup_prog): + # Use fluid.unique_name.guard() to share parameters with train program + with fluid.unique_name.guard(): + test_reader = fluid.layers.py_reader(capacity=32, + shapes=[(-1, 1, 28, 28), (-1, 1)], + dtypes=['float32', 'int64'], + name='test_reader') + test_reader.decorate_paddle_reader(paddle.batch(mnist.test(), 512)) + test_loss = network(test_reader) + + fluid.Executor(fluid.CUDAPlace(0)).run(train_startup_prog) + fluid.Executor(fluid.CUDAPlace(0)).run(test_startup_prog) + + train_exe = fluid.ParallelExecutor(use_cuda=True, + loss_name=train_loss.name, + main_program=train_main_prog) + test_exe = fluid.ParallelExecutor(use_cuda=True, + loss_name=test_loss.name, + main_program=test_main_prog) + for epoch_id in range(10): + train_reader.start() + try: + while True: + train_exe.run(fetch_list=[train_loss.name]) + except fluid.core.EOFException: + train_reader.reset() + + test_reader.start() + try: + while True: + test_exe.run(fetch_list=[test_loss.name]) + except fluid.core.EOFException: + test_reader.reset() + """ + logging.warn( + 'paddle.fluid.layers.py_reader() may be deprecated in the near future. ' + 'Please use paddle.fluid.io.DataLoader.from_generator() instead.') + return _py_reader(capacity=capacity, + shapes=shapes, + dtypes=dtypes, + lod_levels=lod_levels, + name=name, + use_double_buffer=use_double_buffer) + + +def create_py_reader_by_data(capacity, + feed_list, + name=None, + use_double_buffer=True): + """ + :api_attr: Static Graph + + The OP creates a Python reader for data feeding in Python, it is similar + to :ref:`api_fluid_layers_py_reader` except that it can read data from + the list of feed variables. + + Parameters: + capacity (int): The buffer capacity maintained by :code:`py_reader`. Its unit + is batch number. Set larger :attr:`capacity` if the reader is fast. + feed_list (list(Variable)): The feed variables, are usually created by + :code:`fluid.data()`. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. Default: None. + use_double_buffer (bool, optional): Whether use double buffer. If it's True, + the OP would prefetch next batch data asynchronously. Default: True. + + Returns: + Reader: A Reader for data feeding. The data types of read data are the same as the data types of variables of :attr:`feed_list`. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.dataset.mnist as mnist + + def network(img, label): + # User defined network. Here a simple regression as example + predict = fluid.layers.fc(input=img, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=predict, label=label) + return fluid.layers.mean(loss) + + MEMORY_OPT = False + USE_CUDA = False + + image = fluid.data(name='image', shape=[None, 1, 28, 28], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + reader = fluid.layers.create_py_reader_by_data(capacity=64, + feed_list=[image, label]) + reader.decorate_paddle_reader( + paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), buf_size=500)) + img, label = fluid.layers.read_file(reader) + loss = network(img, label) # The definition of custom network and the loss function + + place = fluid.CUDAPlace(0) if USE_CUDA else fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + build_strategy = fluid.BuildStrategy() + build_strategy.memory_optimize = True if MEMORY_OPT else False + exec_strategy = fluid.ExecutionStrategy() + compiled_prog = fluid.compiler.CompiledProgram( + fluid.default_main_program()).with_data_parallel( + loss_name=loss.name, + build_strategy=build_strategy, + exec_strategy=exec_strategy) + + for epoch_id in range(2): + reader.start() + try: + while True: + exe.run(compiled_prog, fetch_list=[loss.name]) + except fluid.core.EOFException: + reader.reset() + """ + logging.warn( + 'paddle.fluid.layers.create_py_reader_by_data() may be deprecated in the near future. ' + 'Please use paddle.fluid.io.DataLoader.from_generator() instead.') + return _py_reader(capacity=capacity, + shapes=None, + dtypes=None, + lod_levels=None, + name=name, + use_double_buffer=use_double_buffer, + feed_list=feed_list) + + +def __create_shared_decorated_reader__(op_type, reader, attrs): + var_name = unique_name(op_type) + startup_blk = default_startup_program().current_block() + startup_var = startup_blk.create_var(name=var_name) + startop_op = startup_blk.append_op(type=op_type, + inputs={'UnderlyingReader': reader}, + outputs={'Out': [startup_var]}, + attrs=attrs) + startup_var.persistable = True + main_prog_block = default_main_program().current_block() + main_prog_var = _copy_reader_var_(main_prog_block, startup_var) + _copy_reader_create_op_(main_prog_block, startop_op) + return monkey_patch_reader_methods(main_prog_var) + + +def __create_unshared_decorated_reader__(op_type, reader, attrs, name=None): + new_reader_name = name if name is not None else unique_name(op_type) + main_blk = default_main_program().current_block() + new_reader = main_blk.create_var(name=new_reader_name) + main_blk.append_op(type=op_type, + inputs={'UnderlyingReader': reader}, + outputs={'Out': [new_reader]}, + attrs=attrs) + return monkey_patch_reader_methods(new_reader) + + +def double_buffer(reader, place=None, name=None): + """ + Wrap a double buffer reader. The class Reader contains DecoratedReader and FileReader. Moreover, the DecoratedReader is inherited by CustomReader and BufferedReader. This function is related to BufferedReader. The data will copy to target place with a double buffer queue. If the target place is None, the place that executor perform on will be used. + + + Args: + reader (Variable): The Reader Variable need to be wrapped. + place (Place|str, optional): The place of target data, such as CPU, GPU, and if use GPU, it's necessary to point out which card is involved. Default is the sample place of executor perform. + if ``place`` is string, It can be ``cpu``, ``gpu:x``, where ``x`` is the ndex of the GPUs. + name (str, optional): Variable name. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None. + + Returns: + Variable(Reader): wrapped reader with double buffer. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + reader = fluid.layers.py_reader(capacity=64, + shapes=[(-1, 1, 28, 28), (-1, 1)], + dtypes=['float32', 'int64'], + use_double_buffer=False) + reader = fluid.layers.double_buffer(reader) + image, label = fluid.layers.read_file(reader) + """ + attrs = dict() + if place is not None: + attrs['place'] = str(_get_paddle_place(place)).upper() + + return __create_unshared_decorated_reader__('create_double_buffer_reader', + reader, + attrs, + name=name) + + +def read_file(reader): + """ + :api_attr: Static Graph + + Execute the given reader and get data via it. + + A reader is also a Variable. It can be a raw reader generated by + `fluid.layers.open_files()` or a decorated one generated by + `fluid.layers.double_buffer()` . + + Args: + + reader(Variable): The reader to execute. + + Returns: + Tuple[Variable]: Data read from the given reader. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + reader = fluid.layers.py_reader(capacity=64, + shapes=[(-1, 1, 28, 28), (-1, 1)], + dtypes=['float32', 'int64']) + image, label = fluid.layers.read_file(reader) + """ + helper = LayerHelper('read_file') + out = [ + helper.create_variable_for_type_inference(stop_gradient=True, + dtype='float32') + for _ in range(len(reader.desc.shapes())) + ] + helper.append_op(type='read', + inputs={'Reader': [reader]}, + outputs={'Out': out}) + if len(out) == 1: + return out[0] + else: + return out + + +def load(out, file_path, load_as_fp16=None): + """ + Load operator will load a LoDTensor / SelectedRows variable from disk file. + + Args: + out(Variable): The LoDTensor / SelectedRows need to be loaded.. + + file_path(STRING): Variable will be loaded from "file_path". + + load_as_fp16(BOOLEAN): If true, the tensor will be first loaded and then converted to float16 data type. Otherwise, the tensor will be directly loaded without data type conversion. Default is false.. + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + tmp_tensor = fluid.layers.create_tensor(dtype='float32') + fluid.layers.load(tmp_tensor, "./tmp_tensor.bin") + """ + helper = LayerHelper("load", **locals()) + attrs = {"file_path": file_path} + if load_as_fp16 is not None: + attrs['load_as_fp16'] = load_as_fp16 + helper.append_op(type="load", inputs={}, outputs={"Out": out}, attrs=attrs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/layer_function_generator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/layer_function_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..65ce37157c2bcc5150a7951f27c0ce5427d93719 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/layer_function_generator.py @@ -0,0 +1,402 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import re +import functools +import warnings +import string + +from six.moves import cStringIO +from ..proto import framework_pb2 +from ..framework import OpProtoHolder, Variable, core, convert_np_dtype_to_dtype_, _non_static_mode, in_dygraph_mode, _in_legacy_dygraph +from ..layer_helper import LayerHelper +from ..data_feeder import check_variable_and_dtype +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'generate_layer_fn', 'generate_activation_fn', 'generate_inplace_fn', + 'autodoc', 'templatedoc' +] + + +def _convert_(name): + """ + Formatting. + + Args: + name: The name/alias + + This function takes in a name and converts it to a standard format of + group1_group2. Where as per the regular expression, group1 can have + alphabets and numbers and group2 has capital alphabets. + + """ + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + + +def _type_to_str_(tp): + return framework_pb2.AttrType.Name(tp) + + +_two_dollar_pattern_ = re.compile(r"\$\$([^\$]+)\$\$") +_single_dollar_pattern_ = re.compile(r"\$([^\$]+)\$") +_two_bang_pattern_ = re.compile(r"!!([^!]+)!!") + + +def escape_math(text): + #return _two_bang_pattern_.sub( + # r'$$\1$$', + # _single_dollar_pattern_.sub(r':math:\n`\1`', + # _two_dollar_pattern_.sub(r"!!\1!!", text))) + return _two_dollar_pattern_.sub(r':math:`\1`', text) + + +def _generate_doc_string_(op_proto, + additional_args_lines=None, + skip_attrs_set=None): + """ + Generate docstring by OpProto + + Args: + op_proto (framework_pb2.OpProto): a protobuf message typed OpProto + + Returns: + str: the document string + """ + + if not isinstance(op_proto, framework_pb2.OpProto): + raise TypeError("OpProto should be `framework_pb2.OpProto`") + + buf = cStringIO() + buf.write(escape_math(op_proto.comment)) + buf.write('\nArgs:\n') + for each_input in op_proto.inputs: + line_begin = ' {0}'.format(_convert_(each_input.name)) + buf.write(line_begin) + buf.write(" (Tensor): ") + buf.write(escape_math(each_input.comment)) + if each_input.duplicable: + buf.write(" Duplicatable.") + if each_input.dispensable: + buf.write(" Optional.") + buf.write('\n') + + skip_attrs = OpProtoHolder.generated_op_attr_names() + # attr use_mkldnn and is_test also should not be visible to users. + skip_attrs.add("use_mkldnn") + skip_attrs.add("is_test") + skip_attrs.add("use_cudnn") + + if skip_attrs_set: + for t in skip_attrs_set: + skip_attrs.add(t) + + for each_attr in op_proto.attrs: + if each_attr.name in skip_attrs: + continue + buf.write(' ') + buf.write(each_attr.name) + buf.write(' (') + buf.write(_type_to_str_(each_attr.type)) + buf.write('): ') + buf.write(escape_math(each_attr.comment)) + buf.write('\n') + + if additional_args_lines is not None: + for line in additional_args_lines: + line = line.strip() + buf.write(' ') + buf.write(line) + buf.write('\n') + + if len(op_proto.outputs) != 0: + buf.write('\nReturns:\n') + buf.write(' ') + for each_opt in op_proto.outputs: + if not each_opt.intermediate: + break + buf.write(_convert_(each_opt.name)) + buf.write(' (Tensor): ') + buf.write(escape_math(each_opt.comment)) + + return buf.getvalue() + + +def generate_layer_fn(op_type): + """Register the Python layer for an Operator. + + Args: + op_type: The name of the operator to be created. + + This function takes in the operator type (sigmoid, mean , average etc) and + creates the operator functionality. + + """ + op_proto = OpProtoHolder.instance().get_op_proto(op_type) + not_intermediate_outputs = \ + [output for output in op_proto.outputs if not output.intermediate] + intermediate_outputs = \ + [output for output in op_proto.outputs if output.intermediate] + + if len(not_intermediate_outputs) != 1: + raise ValueError("Only one non intermediate output operator can be", + "automatically generated. {0}".format(op_type)) + + if not_intermediate_outputs[0].duplicable: + raise ValueError( + "Only non duplicable op can be automatically generated.") + + for output in intermediate_outputs: + if output.duplicable: + raise ValueError("The op can be automatically generated only when ", + "all intermediate ops are not duplicable.") + + o_name = not_intermediate_outputs[0].name + intermediate_output_names = [output.name for output in intermediate_outputs] + + def infer_and_check_dtype(op_proto, *args, **kwargs): + """ + This function performs the sanity check for dtype and + instance type. + """ + dtype = None + for ipt in op_proto.inputs: + name = _convert_(ipt.name) + val = kwargs.pop(name, []) + if not isinstance(val, list) and not isinstance(val, tuple): + val = [val] + if len(val) == 0: + if len(args) == 0: + continue + val = [args[0]] + args = args[1:] + + for each in val: + if not isinstance(each, Variable): + raise ValueError( + "input of {0} must be variable".format(op_type)) + + if dtype is None: + dtype = each.dtype + elif dtype != each.dtype: + raise ValueError( + "operator {0} must input same dtype. {1} vs {2}".format( + op_type, dtype, each.dtype)) + + if dtype is None: + arg_dtype = kwargs.get("dtype") + if arg_dtype: + if not isinstance(arg_dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(arg_dtype) + else: + dtype = arg_dtype + else: + dtype = core.VarDesc.VarType.FP32 + return dtype + + def func(*args, **kwargs): + helper = LayerHelper(op_type, **kwargs) + + dtype = infer_and_check_dtype(op_proto, *args, **kwargs) + + inputs = dict() + for ipt in op_proto.inputs: + name = _convert_(ipt.name) + val = kwargs.pop(name, []) + if not isinstance(val, list) and not isinstance(val, tuple): + val = [val] + if len(val) == 0 and len(args) != 0: + val = args[0] + args = args[1:] + inputs[ipt.name] = val + + outputs = dict() + out = kwargs.pop(_convert_(o_name), []) + if out: + out_var = out[0] if (isinstance(out, list) + or isinstance(out, tuple)) else out + else: + out_var = helper.create_variable_for_type_inference(dtype=dtype) + outputs[o_name] = [out_var] + for name in intermediate_output_names: + outputs[name] = [ + helper.create_variable_for_type_inference(dtype=dtype) + ] + helper.append_op(type=op_type, + inputs=inputs, + outputs=outputs, + attrs=kwargs) + return helper.append_activation(out_var) + + func.__name__ = op_type + func.__doc__ = _generate_doc_string_(op_proto) + return func + + +def generate_activation_fn(op_type): + """Register the Python layer for an Operator without Attribute. + + Args: + op_type: The name of the operator to be created. + + This function takes in the operator type (sigmoid, exp , tanh etc) and + creates the operator functionality. + + """ + op_proto = OpProtoHolder.instance().get_op_proto(op_type) + + def func(x, name=None): + if in_dygraph_mode() and hasattr(_C_ops, op_type): + op = getattr(_C_ops, op_type) + return op(x) + # TODO(dev): Because some ops' yaml has not been migrated. + # Replace it with _in_legacy_dygraph while all yaml work is done. + if _non_static_mode(): + op = getattr(_legacy_C_ops, op_type) + return op(x) + + if op_type not in ["abs", "exp", "square"]: + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + op_type) + else: + # abs exp square ops support dtype(int32, int64, float16, float32, float64) + check_variable_and_dtype(x, 'x', [ + 'int32', 'int64', 'float16', 'float32', 'float64', 'complex64', + 'complex128' + ], op_type) + + helper = LayerHelper(op_type, **locals()) + + output = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=op_type, inputs={"X": x}, outputs={"Out": output}) + return output + + func.__name__ = op_type + func.__doc__ = _generate_doc_string_( + op_proto, + additional_args_lines=[ + "name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`." + ]) + return func + + +def generate_inplace_fn(inplace_op_type): + """Register the Python layer for an Inplace Operator without Attribute. + + Args: + inplace_op_type: The name of the inplace operator to be created. + + This function takes in the inplace operator type (exp_ , ceil_ etc) and + creates the operator functionality. + """ + origin_op_type = inplace_op_type[:-1] + + def func(x, name=None): + if _non_static_mode(): + op = getattr(_legacy_C_ops, inplace_op_type) + return op(x) + warnings.warn( + "In static mode, {}() is the same as {}() and does not perform inplace operation." + .format(inplace_op_type, origin_op_type)) + return generate_activation_fn(origin_op_type)(x, name) + + func.__name__ = inplace_op_type + func.__doc__ = """ +Inplace version of ``{0}`` API, the output Tensor will be inplaced with input ``x``. +Please refer to :ref:`api_fluid_layers_{1}`. +""".format(origin_op_type, origin_op_type) + + return func + + +def autodoc(comment=""): + + def __impl__(func): + func.__doc__ = _generate_doc_string_( + OpProtoHolder.instance().get_op_proto(func.__name__)) + comment + return func + + return __impl__ + + +def templatedoc(op_type=None): + """ + Decorator of layer function. It will use the docstring from the layer + function as the template. The template arguments are: + + * ${comment}: The operator comment written in CPP. + * ${{name}_comment}: The comment of ${name} written with AddAttr, AddOutput, + and AddInput. The ${name} is Python snake style. i.e., xxx_xxx. + * ${{name}_type}: The type of ${name}. + + Returns: + Decorated function. + """ + + def trim_ending_dot(msg): + return msg.rstrip('.') + + def __impl__(func): + if op_type is None: + op_type_name = func.__name__ + else: + op_type_name = op_type + op_proto = OpProtoHolder.instance().get_op_proto(op_type_name) + tmpl = string.Template(func.__doc__) + + comment_lines = op_proto.comment.split("\n") + comment = "" + for line in comment_lines: + line = line.strip() + if len(line) != 0: + comment += escape_math(line) + comment += " " + elif len(comment) != 0: + comment += "\n \n " + + args = {"comment": trim_ending_dot(comment)} + for each_input in op_proto.inputs: + input_name = _convert_(each_input.name) + args["{0}_comment".format(input_name)] = trim_ending_dot( + each_input.comment) + args["{0}_type".format(input_name)] = "Variable" + for each_attr in op_proto.attrs: + input_name = _convert_(each_attr.name) + args["{0}_comment".format(input_name)] = trim_ending_dot( + each_attr.comment) + args["{0}_type".format(input_name)] = _type_to_str_(each_attr.type) + + for each_opt in op_proto.outputs: + output_name = _convert_(each_opt.name) + args["{0}_comment".format(output_name)] = trim_ending_dot( + each_opt.comment) + args["{0}_type".format(output_name)] = "Variable" + func.__doc__ = tmpl.substitute(args) + return func + + return __impl__ + + +def add_sample_code(func, sample_code): + """ + Append sample code for dynamically generated functions. + + Args: + func: The function of the function to be append sample code to. + sample_code: sample code session in rst format. + """ + func.__doc__ = func.__doc__ + sample_code diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/learning_rate_scheduler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/learning_rate_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a65633e60e25a1fd58dd4dd2d593a519ba838e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/learning_rate_scheduler.py @@ -0,0 +1,578 @@ +# 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. +""" +When training a model, it's often useful to decay the +learning rate during training process, this is called +learning_rate_decay. There are many strategies to do +this, this module will provide some classical method. +User can also implement their own learning_rate_decay +strategy according to this module. +""" + +from __future__ import print_function + +import math +import numbers + +from . import control_flow +from . import nn +from . import ops +from . import tensor +from ..framework import default_main_program, Parameter, unique_name, name_scope +from ..framework import Variable +from ..framework import _non_static_mode +from ..dygraph import learning_rate_scheduler as imperate_lr +from ..data_feeder import check_variable_and_dtype, check_type + +__all__ = [ + 'exponential_decay', 'natural_exp_decay', 'inverse_time_decay', + 'polynomial_decay', 'piecewise_decay', 'noam_decay', 'cosine_decay', + 'linear_lr_warmup' +] + + +def _decay_step_counter(begin=0): + # the first global step is zero in learning rate decay + global_step = nn.autoincreased_step_counter( + counter_name='@LR_DECAY_COUNTER@', begin=begin, step=1) + global_step = tensor.cast(global_step, 'float32') + return global_step + + +def noam_decay(d_model, warmup_steps, learning_rate=1.0): + """ + + Noam decay method. The numpy implementation of noam decay as follows. + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + # set hyper parameters + base_lr = 0.01 + d_model = 2 + current_steps = 20 + warmup_steps = 200 + # compute + lr_value = base_lr * np.power(d_model, -0.5) * np.min([ + np.power(current_steps, -0.5), + np.power(warmup_steps, -1.5) * current_steps]) + + Please reference `attention is all you need + `_. + + Args: + d_model(Variable): The dimensionality of input and output of model. + + warmup_steps(Variable): A super parameter. + + learning_rate(Variable|float|int): The initial learning rate. If the type + is Variable, it's a tensor with shape [1], the data type can be + float32 or float64. It also can be set to python int number. Default 1.0 + + Returns: + The decayed learning rate. + Examples: + .. code-block:: python + + import paddle.fluid as fluid + warmup_steps = 100 + learning_rate = 0.01 + lr = fluid.layers.learning_rate_scheduler.noam_decay( + 1/(warmup_steps *(learning_rate ** 2)), + warmup_steps, + learning_rate) + """ + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.NoamDecay(d_model, + warmup_steps, + learning_rate=learning_rate) + return decay + else: + global_step = _decay_step_counter(1) + + a = global_step**-0.5 + b = (warmup_steps**-1.5) * global_step + lr_value = learning_rate * (d_model**-0.5) * nn.elementwise_min( + a, b) + + return lr_value + + +def exponential_decay(learning_rate, decay_steps, decay_rate, staircase=False): + """ + + Applies exponential decay to the learning rate. + + When training a model, it is often recommended to lower the learning rate as the + training progresses. By using this function, the learning rate will be decayed by + 'decay_rate' every 'decay_steps' steps. + + Decayed learning rate calculates as follows: + + >>> if staircase == True: + >>> decayed_learning_rate = learning_rate * decay_rate ^ floor(global_step / decay_steps) + >>> else: + >>> decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps) + + Args: + learning_rate(Variable|float): The initial learning rate. It should be a Variable + or a float + decay_steps(int): The learning rate decay steps. See the decay computation above. + decay_rate(float): The learning rate decay rate. See the decay computation above. + staircase(bool): If True, decay the learning rate at discrete intervals, which + means the learning rate will be decayed by `decay_rate` every + `decay_steps`. If False, learning rate will be decayed continuously + and following the formula above. Default: False + + Returns: + Variable: The decayed learning rate. The data type is float32. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + base_lr = 0.1 + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.layers.exponential_decay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True)) + + """ + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.ExponentialDecay(learning_rate, decay_steps, + decay_rate, staircase) + return decay + else: + global_step = _decay_step_counter() + + div_res = global_step / decay_steps + if staircase: + div_res = ops.floor(div_res) + decayed_lr = learning_rate * (decay_rate**div_res) + + return decayed_lr + + +def natural_exp_decay(learning_rate, decay_steps, decay_rate, staircase=False): + """ + +Applies natural exponential decay to the initial learning rate. + + When training a model, it is often recommended to lower the learning rate as the + training progresses. By using this function, the learning rate will be decayed by + natural exponential power 'decay_rate' every 'decay_steps' steps. + + Decayed learning rate calculates as follows: + + >>> if not staircase: + >>> decayed_learning_rate = learning_rate * exp(- decay_rate * (global_step / decay_steps)) + >>> else: + >>> decayed_learning_rate = learning_rate * exp(- decay_rate * floor(global_step / decay_steps)) + + Args: + learning_rate(Variable|float): The initial learning rate. It should be a Variable + or a float + decay_steps(int): The learning rate decay steps. See the decay computation above. + decay_rate(float): The learning rate decay rate. See the decay computation above. + staircase(bool): If True, decay the learning rate at discrete intervals, which + means the learning rate will be decayed by natural exponential power + `decay_rate` every `decay_steps`. If False, learning rate will be + decayed continuously and following the formula above. Default: False + + Returns: + The decayed learning rate. The data type is float32. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + base_lr = 0.1 + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.layers.natural_exp_decay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True)) + + """ + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.NaturalExpDecay(learning_rate, decay_steps, + decay_rate, staircase) + return decay + else: + global_step = _decay_step_counter() + + div_res = global_step / decay_steps + if staircase: + div_res = ops.floor(div_res) + decayed_lr = learning_rate * ops.exp(-1 * decay_rate * div_res) + + return decayed_lr + + +def inverse_time_decay(learning_rate, decay_steps, decay_rate, staircase=False): + """ + + Applies inverse time decay to the initial learning rate. + + When training a model, it is often recommended to lower the learning rate as the + training progresses. By using this function, an inverse decay function will be + applied to the initial learning rate. + + Decayed learning rate calculates as follows: + + >>> if staircase == True: + >>> decayed_learning_rate = learning_rate / (1 + decay_rate * floor(global_step / decay_step)) + >>> else: + >>> decayed_learning_rate = learning_rate / (1 + decay_rate * global_step / decay_step) + + Args: + learning_rate(Variable|float): The initial learning rate. It should be a Variable + or a float + decay_steps(int): The learning rate decay steps. See the decay computation above. + decay_rate(float): The learning rate decay rate. See the decay computation above. + staircase(bool): If True, decay the learning rate at discrete intervals, which + means the learning rate will be decayed by `decay_rate` times + every `decay_steps`. If False, learning rate will be decayed + continuously and following the formula above. Default: False + + Returns: + Variable: The decayed learning rate. The data type is float32. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + base_lr = 0.1 + sgd_optimizer = fluid.optimizer.SGD( + learning_rate=fluid.layers.inverse_time_decay( + learning_rate=base_lr, + decay_steps=10000, + decay_rate=0.5, + staircase=True)) + """ + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.InverseTimeDecay(learning_rate, decay_steps, + decay_rate, staircase) + return decay + else: + global_step = _decay_step_counter() + + div_res = global_step / decay_steps + if staircase: + div_res = ops.floor(div_res) + + decayed_lr = learning_rate / (1 + decay_rate * div_res) + + return decayed_lr + + +def polynomial_decay(learning_rate, + decay_steps, + end_learning_rate=0.0001, + power=1.0, + cycle=False): + """ + Applies polynomial decay to the initial learning rate. + + .. code-block:: text + + if cycle: + decay_steps = decay_steps * ceil(global_step / decay_steps) + else: + global_step = min(global_step, decay_steps) + decayed_learning_rate = (learning_rate - end_learning_rate) * + (1 - global_step / decay_steps) ^ power + end_learning_rate + + Args: + learning_rate(Variable|float32): A scalar float32 value or a Variable. This + will be the initial learning rate during training. + decay_steps(int32): A Python `int32` number. + end_learning_rate(float): A Python `float` number. + power(float): A Python `float` number. + cycle(bool): If set true, decay the learning rate every decay_steps. + + Returns: + Variable: The decayed learning rate + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + start_lr = 0.01 + total_step = 5000 + end_lr = 0 + lr = fluid.layers.polynomial_decay( + start_lr, total_step, end_lr, power=1) + + """ + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.PolynomialDecay(learning_rate, decay_steps, + end_learning_rate, power, cycle) + return decay + else: + global_step = _decay_step_counter() + + if cycle: + div_res = ops.ceil(global_step / decay_steps) + zero_var = tensor.fill_constant(shape=[1], + dtype='float32', + value=0.0) + one_var = tensor.fill_constant(shape=[1], + dtype='float32', + value=1.0) + + with control_flow.Switch() as switch: + with switch.case(global_step == zero_var): + tensor.assign(input=one_var, output=div_res) + decay_steps = decay_steps * div_res + else: + decay_steps_var = tensor.fill_constant(shape=[1], + dtype='float32', + value=float(decay_steps)) + global_step = nn.elementwise_min(x=global_step, + y=decay_steps_var) + + decayed_lr = (learning_rate - end_learning_rate) * \ + ((1 - global_step / decay_steps) ** power) + end_learning_rate + return decayed_lr + + +def piecewise_decay(boundaries, values): + """ + +Applies piecewise decay to the initial learning rate. + + The algorithm can be described as the code below. + + .. code-block:: text + + boundaries = [10000, 20000] + values = [1.0, 0.5, 0.1] + if step < 10000: + learning_rate = 1.0 + elif 10000 <= step < 20000: + learning_rate = 0.5 + else: + learning_rate = 0.1 + Args: + boundaries: A list of steps numbers. + values: A list of learning rate values that will be picked during + different step boundaries. + + Returns: + The decayed learning rate. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + boundaries = [10000, 20000] + values = [1.0, 0.5, 0.1] + optimizer = fluid.optimizer.Momentum( + momentum=0.9, + learning_rate=fluid.layers.piecewise_decay(boundaries=boundaries, values=values), + regularization=fluid.regularizer.L2Decay(1e-4)) + + + """ + with default_main_program()._lr_schedule_guard(): + if len(values) - len(boundaries) != 1: + raise ValueError("len(values) - len(boundaries) should be 1") + + if _non_static_mode(): + decay = imperate_lr.PiecewiseDecay(boundaries, values, 0) + return decay + else: + global_step = _decay_step_counter() + + lr = tensor.create_global_var(shape=[1], + value=0.0, + dtype='float32', + persistable=True, + name="learning_rate") + + with control_flow.Switch() as switch: + for i in range(len(boundaries)): + boundary_val = tensor.fill_constant(shape=[1], + dtype='float32', + value=float( + boundaries[i]), + force_cpu=True) + with switch.case(global_step < boundary_val): + tensor.fill_constant(shape=[1], + dtype="float32", + value=float(values[i]), + out=lr) + with switch.default(): + tensor.fill_constant(shape=[1], + dtype="float32", + value=float(values[len(values) - 1]), + out=lr) + + return lr + + +def cosine_decay(learning_rate, step_each_epoch, epochs): + r""" + + Applies cosine decay to the learning rate. + + when training a model, it is often recommended to lower the learning rate as the + training progresses. By using this function, the learning rate will be decayed by + following cosine decay strategy. + + .. math:: + + decayed\_lr = learning\_rate * 0.5 * (math.cos * (epoch * \\frac{math.pi}{epochs} ) + 1) + + Args: + learning_rate(Variable|float): The initial learning rate. + step_each_epoch(int): the number of steps in an epoch. + epochs(int): the number of epochs. + + Returns: + Variable: The decayed learning rate. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + base_lr = 0.1 + lr = fluid.layers.cosine_decay( + learning_rate = base_lr, step_each_epoch=10000, epochs=120) + """ + check_type(learning_rate, 'learning_rate', (float, tensor.Variable), + 'cosine_decay') + + with default_main_program()._lr_schedule_guard(): + if _non_static_mode(): + decay = imperate_lr.CosineDecay(learning_rate, step_each_epoch, + epochs) + return decay + else: + global_step = _decay_step_counter() + + cur_epoch = ops.floor(global_step / step_each_epoch) + decayed_lr = learning_rate * 0.5 * ( + ops.cos(cur_epoch * math.pi / epochs) + 1) + return decayed_lr + + +def linear_lr_warmup(learning_rate, warmup_steps, start_lr, end_lr): + """ + + This operator use the linear learning rate warm up strategy to adjust the learning rate preliminarily before the normal learning rate scheduling. + For more information, please refer to `Bag of Tricks for Image Classification with Convolutional Neural Networks `_ + + When global_step < warmup_steps, learning rate is updated as: + + .. code-block:: text + + linear_step = end_lr - start_lr + lr = start_lr + linear_step * (global_step / warmup_steps) + + where start_lr is the initial learning rate, and end_lr is the final learning rate; + + When global_step >= warmup_steps, learning rate is updated as: + + .. code-block:: text + + lr = learning_rate + + where lr is the learning_rate after warm-up. + + Args: + learning_rate (Variable|float): Learning_rate after warm-up, it could be 1D-Tensor or single value with the data type of float32. + warmup_steps (int): Steps for warm up. + start_lr (float): Initial learning rate of warm up. + end_lr (float): Final learning rate of warm up. + + Returns: + Variable: Warm-up learning rate with the same data type as learning_rate. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + boundaries = [100, 200] + lr_steps = [0.1, 0.01, 0.001] + learning_rate = fluid.layers.piecewise_decay(boundaries, lr_steps) #case1, 1D-Tensor + #learning_rate = 0.1 #case2, single-value + warmup_steps = 50 + start_lr = 1. / 3. + end_lr = 0.1 + decayed_lr = fluid.layers.linear_lr_warmup(learning_rate, + warmup_steps, start_lr, end_lr) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + out, = exe.run(fetch_list=[decayed_lr.name]) + print(out) + # case1: [0.33333334] + # case2: [0.33333334] + """ + dtype = 'float32' + if isinstance(learning_rate, Variable): + dtype = learning_rate.dtype + + linear_step = float(end_lr) - float(start_lr) + with default_main_program()._lr_schedule_guard(): + + if _non_static_mode(): + lr = imperate_lr.LinearLrWarmup(learning_rate, warmup_steps, + start_lr, end_lr) + return lr + else: + lr = tensor.create_global_var(shape=[1], + value=0.0, + dtype=dtype, + persistable=True, + name="learning_rate_warmup") + + global_step = _decay_step_counter() + + with control_flow.Switch() as switch: + with switch.case(global_step < warmup_steps): + decayed_lr = start_lr + linear_step * (global_step / + float(warmup_steps)) + tensor.assign(decayed_lr, lr) + with switch.default(): + if not isinstance(learning_rate, Variable): + learning_rate = tensor.fill_constant( + shape=[1], dtype=dtype, value=float(learning_rate)) + tensor.assign(learning_rate, lr) + return lr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..20c198388a9b43a40feedf67dabbe06a8baf08d8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/loss.py @@ -0,0 +1,1749 @@ +# 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. + +from __future__ import print_function + +import numpy as np +from functools import partial, reduce +import paddle +from paddle.utils import deprecated +from . import nn +from .layer_function_generator import templatedoc +from ..layer_helper import LayerHelper +from ..framework import Variable, _non_static_mode, static_only, _in_legacy_dygraph, in_dygraph_mode +from .. import core +from ..data_feeder import check_variable_and_dtype, check_type +from ..param_attr import ParamAttr +from ..initializer import NumpyArrayInitializer, Constant +from .. import core +import warnings +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'center_loss', + 'bpr_loss', + 'cross_entropy', + 'square_error_cost', + 'edit_distance', + 'warpctc', + 'nce', + 'hsigmoid', + 'sampled_softmax_with_cross_entropy', + 'softmax_with_cross_entropy', + 'rank_loss', + 'margin_rank_loss', + 'sigmoid_cross_entropy_with_logits', + 'teacher_student_sigmoid_loss', + 'huber_loss', + 'kldiv_loss', + 'npair_loss', + 'mse_loss', +] + +kIgnoreIndex = -100 + + +def center_loss(input, + label, + num_classes, + alpha, + param_attr, + update_center=True): + r""" + :api_attr: Static Graph + + **Center loss Cost layer** + + This OP accepts input (deep features,the output of the last hidden layer) + and target label and return the center loss cost. The average of the + distances of each sample in the mini-batch from the center of the + corresponding category is calculated as the center loss. + + For deep features, :math:`X`, and target labels, :math:`Y`, the equation is: + + .. math:: + + Out = \\frac{1}{2}(X - Y)^2 + + Args: + input (Variable): a 2-D tensor with shape[N x M]. Its dtype should be float32 or float64. + label (Variable): the groud truth which is a 2-D tensor + with shape[N x 1],where N is the batch size. Its dtype should be int32. + num_classes (int): the number of classification categories. + alpha (float|Variable): learning rate of centers. + param_attr (ParamAttr): Attribute initializer of centers. + update_center (bool): whether to update value of center. + + Returns: + Variable: 2-D tensor with shape [N * 1] + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + input = fluid.data(name='x',shape=[20,30],dtype='float32') + label = fluid.data(name='y',shape=[20,1],dtype='int64') + num_classes = 1000 + alpha = 0.01 + param_attr = fluid.initializer.Xavier(uniform=False) + center_loss=fluid.layers.center_loss(input=input, + label=label, + num_classes=1000, + alpha=alpha, + param_attr=fluid.initializer.Xavier(uniform=False), + update_center=True) + """ + helper = LayerHelper('center_loss', **locals()) + dtype = helper.input_dtype() + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'center_loss') + check_variable_and_dtype(label, 'label', ['int32', 'int64'], 'center_loss') + + centers_shape = [num_classes, input.shape[1]] + centers_param = helper.create_parameter(attr=param_attr, + shape=centers_shape, + dtype=dtype) + centers_param.stop_gradient = True + + if isinstance(alpha, Variable): + alpha_param = alpha + check_variable_and_dtype(alpha, 'alpha', ['float32', 'float64'], + 'center_loss') + else: + assert isinstance(alpha, float) + alpha_param = helper.create_variable( + name="centerloss_alpha", + shape=[1], + dtype="float32", + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=True, + stop_gradient=True, + initializer=Constant(alpha)) + + centersdiff = helper.create_variable_for_type_inference(dtype=input.dtype) + loss = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op(type='center_loss', + inputs={ + 'X': [input], + 'Label': [label], + 'Centers': [centers_param], + 'CenterUpdateRate': [alpha_param] + }, + outputs={ + 'SampleCenterDiff': [centersdiff], + 'Loss': [loss], + 'CentersOut': [centers_param] + }, + attrs={ + 'cluster_num': num_classes, + 'need_update': update_center + }) + return loss + + +def bpr_loss(input, label, name=None): + r""" + + **Bayesian Personalized Ranking Loss Operator** + + This operator belongs to pairwise ranking loss. Label is the desired item. + The loss at a given point in one session is defined as: + + .. math:: + Y[i] = 1/(N[i] - 1) * \sum_j{\log(\sigma(X[i, Label[i]]-X[i, j]))} + + Learn more details by reading paper . + + Args: + input (Variable|list): a 2-D tensor with shape [N x D], where N is the + batch size and D is the number of positive classes and negative classes + This input is not probability but logits. + label (Variable|list): the ground truth which is a 2-D tensor. `label` + is a tensor with shape [N x 1]. + name (str|None): A name for this layer(optional). If set None, the + layer will be named automatically. Default: None. + Returns: + A 2-D tensor with shape [N x 1], the bpr loss. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + + neg_size = 10 + label = fluid.data( + name="label", shape=[3, 1], dtype="int64") + predict = fluid.data( + name="predict", shape=[3, neg_size + 1], dtype="float32") + cost = fluid.layers.bpr_loss(input=predict, label=label) + """ + helper = LayerHelper('bpr_loss', **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], + 'bpr_loss') + helper.append_op(type='bpr_loss', + inputs={ + 'X': [input], + 'Label': [label] + }, + outputs={'Y': [out]}) + return out + + +def cross_entropy(input, label, soft_label=False, ignore_index=kIgnoreIndex): + r""" + :alias_main: paddle.nn.functional.cross_entropy + :alias: paddle.nn.functional.cross_entropy,paddle.nn.functional.loss.cross_entropy + :old_api: paddle.fluid.layers.cross_entropy + + This operator computes the cross entropy between input and label. It + supports both hard-label and and soft-label cross entropy computation. + + 1. Hard-label cross entropy: if soft_label=False, :math:`label[i_1, i_2, ..., i_k]` + is the hard label of each sample. + + .. math:: + + output[i_1, i_2, ..., i_k]=-log(input[i_1, i_2, ..., i_k, j]), label[i_1, i_2, ..., i_k] = j, j != ignore\_index + + 2. Soft-label cross entropy: if soft_label=True, :math:`label[i_1, i_2, ..., i_k, j]` + is the soft label of each sample corresponding to the j-th class. + + .. math:: + + output[i_1, i_2, ..., i_k]= -\sum_{j}label[i_1,i_2,...,i_k,j]*log(input[i_1, i_2, ..., i_k,j]) + + Args: + input (Variable): a multidimensional Tensor with shape + :math:`[N_1, N_2, ..., N_k, D]`, where the last dimension D is + the class number. The data type should be float32 or float64. + label (Variable): label value corresponding to input. If + soft_label=False, the dimension of label should be :math:`[N_1, N_2, ..., N_k]` + or :math:`[N_1, N_2, ..., N_k, 1]` , and its data type should be int64, + and the value must be inside [0, D). If soft_label=True, the shape, + data type of label should be the same with input, and the sum of + soft label value of each sample should be 1. + soft_label (bool): indicate whether label is soft. Default False, meaning that + the label is hard. If soft_label=True, the label is soft. + ignore_index (int): specify an ignorable label value. The ignored label would be + omitted when computing. If it is a negative integer, no label would + be ignored. Only valid when soft_label=False. Default -100. + + Returns: + A Variable holding Tensor representing the cross entropy, whose data type is the same with input. + If soft_label=False, the shape of output is the same with label. + If soft_label=True, the shape of output is :math:`[N_1, N_2, ..., N_k, 1]` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + class_num = 7 + x = fluid.data(name='x', shape=[None, 3, 10], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + predict = fluid.layers.fc(input=x, size=class_num, act='softmax') + cost = fluid.layers.cross_entropy(input=predict, label=label) + """ + if not soft_label: + return cross_entropy2(input, label, ignore_index) + + if _non_static_mode(): + return _legacy_C_ops.cross_entropy(input, label, "soft_label", + soft_label, "ignore_index", + ignore_index) + + inputs = {'X': [input], 'Label': [label]} + attrs = {"soft_label": soft_label, "ignore_index": ignore_index} + + check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], + 'cross_entropy') + helper = LayerHelper('cross_entropy', **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op(type='cross_entropy', + inputs=inputs, + outputs={'Y': [out]}, + attrs=attrs) + return out + + +def cross_entropy2(input, label, ignore_index=kIgnoreIndex): + if _non_static_mode(): + loss, _, _ = _legacy_C_ops.cross_entropy2(input, label, 'ignore_index', + ignore_index) + return loss + + inputs = {'X': [input], 'Label': [label]} + attrs = {'ignore_index': ignore_index} + check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], + 'cross_entropy2') + helper = LayerHelper('cross_entropy2', **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + xshape = helper.create_variable_for_type_inference(dtype=input.dtype) + match_x = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op(type='cross_entropy2', + inputs=inputs, + outputs={ + 'Y': [out], + 'MatchX': [match_x], + 'XShape': [xshape] + }, + attrs=attrs) + return out + + +def square_error_cost(input, label): + r""" + + Accept input predictions and target label and returns the + squared error cost. + + For predictions label, and target label, the equation is: + + .. math:: + + Out = (input - label)^2 + + Parameters: + input (Tensor): Input tensor, the data type should be float32. + label (Tensor): Label tensor, the data type should be float32. + + Returns: + Tensor, The tensor storing the element-wise squared + error difference between input and label. + + Examples: + + .. code-block:: python + + import paddle + input = paddle.to_tensor([1.1, 1.9]) + label = paddle.to_tensor([1.0, 2.0]) + output = paddle.nn.functional.square_error_cost(input, label) + print(output) + # [0.01, 0.01] + + """ + return paddle.nn.functional.square_error_cost(input, label) + + +def edit_distance(input, + label, + normalized=True, + ignored_tokens=None, + input_length=None, + label_length=None): + """ + This op computes the edit distances, also called Levenshtein distance, between a batch of + hypothesis strings and their references. It measures how dissimilar two strings are by counting + the minimum number of operations to transform one string into another. + The operations include insertion, deletion, and substitution. + + For example, given hypothesis string A = "kitten" and reference + B = "sitting", A will be transformed into B + at least after two substitutions and one insertion: + + "kitten" -> "sitten" -> "sittin" -> "sitting" + + So the edit distance between A and B is 3. + + The input is a Tensor, the input_length and label_length should be supported. + + The `batch_size` of labels should be same as `input`. + + The output include the edit distance value between every pair of input and related label, and the number of sequence. + If Attr(normalized) is true, + the edit distance value will be divided by the length of label. + + Parameters: + input(Tensor): The input tensor, its rank should be equal to 2 and its data type should be int64. + label(Tensor): The label tensor, its rank should be equal to 2 and its data type should be int64. + normalized(bool, default True): Indicated whether to normalize the edit distance. + ignored_tokens(list, default None): Tokens that will be removed before + calculating edit distance. + input_length(Tensor): The length for each sequence in `input` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64. + label_length(Tensor): The length for each sequence in `label` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64. + NOTE: To be avoid unexpected result, the value of every elements in input_length and label_length should be equal to the value of the second dimension of input and label. For example, The input: [[1,2,3,4],[5,6,7,8],[9,10,11,12]], the shape of input is [3,4] and the input_length should be [4,4,4] + NOTE: This Api is different from fluid.metrics.EditDistance + + Returns: + Tuple: + + distance(Tensor): edit distance result, its data type is float32, and its shape is (batch_size, 1). + sequence_num(Tensor): sequence number, its data type is float32, and its shape is (1,). + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.to_tensor([[1,2,3],[4,5,6],[4,4,4],[1,1,1]], dtype='int64') + label = paddle.to_tensor([[1,3,4,1],[4,5,8,1],[7,7,7,1],[1,1,1,1]], dtype='int64') + input_len = paddle.to_tensor([3,3,3,3], dtype='int64') + label_len = paddle.to_tensor([4,4,4,4], dtype='int64') + + distance, sequence_num = F.loss.edit_distance(input=input, label=label, input_length=input_len, label_length=label_len, normalized=False) + + # print(distance) + # [[3.] + # [2.] + # [4.] + # [1.]] + # if set normalized to True + # [[0.75] + # [0.5 ] + # [1. ] + # [0.25] + # + # print(sequence_num) + # [4] + + """ + return paddle.nn.functional.loss.edit_distance(input, label, normalized, + ignored_tokens, input_length, + label_length) + + +def warpctc(input, + label, + blank=0, + norm_by_times=False, + input_length=None, + label_length=None): + """ + An operator integrating the open source Warp-CTC library + (https://github.com/baidu-research/warp-ctc) + to compute Connectionist Temporal Classification (CTC) loss. + It can be aliased as softmax with CTC, since a native softmax activation is + interated to the Warp-CTC library to normalize values for each row of the + input tensor. + + Args: + input (Variable): The unscaled probabilities of variable-length sequences, + which is a 2-D Tensor with LoD information, or a 3-D Tensor without Lod + information. When it is a 2-D LodTensor, its shape is + `[Lp, num_classes + 1]`, where `Lp` is the sum of all input + sequences' length and `num_classes` is the true number of classes. + (not including the blank label). When it is a 3-D Tensor, its shape + is `[max_logit_length, batch_size, num_classes + 1]`, + where `max_logit_length` is the longest length of + input logit sequence. The data type should be float32 or float64. + label (Variable): The ground truth of variable-length sequence, + which must be a 2-D Tensor with LoD information or a 3-D Tensor without + LoD information, needs to be consistent with the coressponding input. + When it is a 2-D LoDTensor, its shape is `[Lg, 1]`, where `Lg` is the sum + of all labels' length. When it is a 3-D Tensor, its shape is + `[batch_size, max_label_length]`, where `max_label_length` is the longest + length of label sequence. Data type must be int32. + blank (int, default 0): The blank label index of Connectionist + Temporal Classification (CTC) loss, which is in the + half-opened interval `[0, num_classes + 1)`. The data type must be int32. + norm_by_times(bool, default false): Whether to normalize the gradients + by the number of time-step, which is also the sequence's length. + There is no need to normalize the gradients if warpctc layer was + followed by a mean_op. + input_length(Variable): The length for each input sequence if it is + of Tensor type, it should have shape `[batch_size]` and dtype int64. + label_length(Variable): The length for each label sequence if it is + of Tensor type, it should have shape `[batch_size]` and dtype int64. + + Returns: + Variable: The Connectionist Temporal Classification (CTC) loss, + which is a 2-D Tensor with the shape `[batch_size, 1]`. + The date type is the same as input. + + Examples: + + .. code-block:: python + + # using LoDTensor + import paddle + import paddle.fluid as fluid + import numpy as np + + # lengths of logit sequences + seq_lens = [2,6] + # lengths of label sequences + label_lens = [2,3] + # class num + class_num = 5 + + paddle.enable_static() + logits = fluid.data(name='logits',shape=[None, class_num+1], + dtype='float32',lod_level=1) + label = fluid.data(name='label', shape=[None, 1], + dtype='int32', lod_level=1) + cost = fluid.layers.warpctc(input=logits, label=label) + place = fluid.CPUPlace() + x = fluid.create_lod_tensor( + np.random.rand(np.sum(seq_lens), class_num+1).astype("float32"), + [seq_lens], place) + y = fluid.create_lod_tensor( + np.random.randint(0, class_num, [np.sum(label_lens), 1]).astype("int32"), + [label_lens], place) + exe = fluid.Executor(place) + output= exe.run(fluid.default_main_program(), + feed={"logits": x,"label": y}, + fetch_list=[cost.name]) + print(output) + + .. code-block:: python + + # using Tensor + import paddle + import paddle.fluid as fluid + import numpy as np + + # length of the longest logit sequence + max_seq_length = 5 + #length of the longest label sequence + max_label_length = 3 + # number of logit sequences + batch_size = 16 + # class num + class_num = 5 + paddle.enable_static() + logits = fluid.data(name='logits', + shape=[max_seq_length, batch_size, class_num+1], + dtype='float32') + logits_length = fluid.data(name='logits_length', shape=[None], + dtype='int64') + label = fluid.data(name='label', shape=[batch_size, max_label_length], + dtype='int32') + label_length = fluid.data(name='labels_length', shape=[None], + dtype='int64') + cost = fluid.layers.warpctc(input=logits, label=label, + input_length=logits_length, + label_length=label_length) + place = fluid.CPUPlace() + x = np.random.rand(max_seq_length, batch_size, class_num+1).astype("float32") + y = np.random.randint(0, class_num, [batch_size, max_label_length]).astype("int32") + exe = fluid.Executor(place) + output= exe.run(fluid.default_main_program(), + feed={"logits": x, + "label": y, + "logits_length": np.array([max_seq_length]*batch_size).astype("int64"), + "labels_length": np.array([max_label_length]*batch_size).astype("int64")}, + fetch_list=[cost.name]) + print(output) + """ + if in_dygraph_mode(): + if input_length is None or label_length is None: + raise ValueError( + "input_length and label_length must not be None in dygraph mode!" + ) + loss_out = _C_ops.warpctc(input, label, input_length, label_length, + blank, norm_by_times) + return loss_out + if _non_static_mode(): + if input_length is None or label_length is None: + raise ValueError( + "input_length and label_length must not be None in dygraph mode!" + ) + grad, loss_out = _legacy_C_ops.warpctc( + input, + label, + input_length, + label_length, + 'blank', + blank, + 'norm_by_times', + norm_by_times, + ) + return loss_out + helper = LayerHelper('warpctc', **locals()) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], "warpctc") + check_variable_and_dtype(label, 'label', ['int32'], "warpctc") + this_inputs = {'Logits': [input], 'Label': [label]} + if input_length is not None and label_length is not None: + check_variable_and_dtype(input_length, 'LogitsLength', ['int64'], + "warpctc") + check_variable_and_dtype(label_length, 'LabelLength', ['int64'], + "warpctc") + this_inputs['LogitsLength'] = [input_length] + this_inputs['LabelLength'] = [label_length] + + loss_out = helper.create_variable_for_type_inference(dtype=input.dtype) + grad_out = helper.create_variable_for_type_inference(dtype=input.dtype) + + helper.append_op(type='warpctc', + inputs=this_inputs, + outputs={ + 'WarpCTCGrad': [grad_out], + 'Loss': [loss_out] + }, + attrs={ + 'blank': blank, + 'norm_by_times': norm_by_times, + }) + return loss_out + + +# FIXME(wuyi): let docstring_checker.py understand @autodoc. +# For now, the comments in c++ use types like Tensor, but in python side +# the type is often "Variable", and arguments may vary. +@static_only +@templatedoc(op_type="nce") +def nce(input, + label, + num_total_classes, + sample_weight=None, + param_attr=None, + bias_attr=None, + num_neg_samples=None, + name=None, + sampler="uniform", + custom_dist=None, + seed=0, + is_sparse=False): + """ + :api_attr: Static Graph + + ${comment} + + Args: + input (Tensor): Input tensor, 2-D tensor with shape [batch_size, dim], + and data type is float32 or float64. + label (Tensor): Input label, 2-D tensor with shape [batch_size, num_true_class], + and data type is int64. + num_total_classes (int):${num_total_classes_comment}. + sample_weight (Tensor|None): A Tensor of shape [batch_size, 1] + storing a weight for each sample. The default weight for each + sample is 1.0. + param_attr (ParamAttr|None): To specify the weight parameter attribute. + Default: None, which means the default weight parameter property is + used. See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr|None): To specify the bias parameter attribute. + Default: None, which means the default bias parameter property is + used. See usage for details in :ref:`api_fluid_ParamAttr` . + num_neg_samples (int): ${num_neg_samples_comment}. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + sampler (str, optional): The sampler used to sample class from negative classes. + It can be 'uniform', 'log_uniform' or 'custom_dist'. + default: 'uniform'. + custom_dist (nd.array|None): A numpy ndarray with size=num_total_classes. + It is used when sampler is set to 'custom_dist'. + custom_dist[i] is the probability of i-th class to be sampled. + default: None. + seed (int, optional): The seed used in sampler. Default 0, means no random seed. + is_sparse(bool, optional): The flag indicating whether to use sparse update, + the weight@GRAD and bias@GRAD will be changed to SelectedRows. Default False. + + Returns: + Tensor: The output nce loss. + + Examples: + .. code-block:: python + + + import paddle + import numpy as np + + paddle.enable_static() + + window_size = 5 + words = [] + for i in range(window_size): + words.append(paddle.static.data( + name='word_{0}'.format(i), shape=[-1, 1], dtype='int64')) + + dict_size = 10000 + label_word = int(window_size / 2) + 1 + + embs = [] + for i in range(window_size): + if i == label_word: + continue + + emb = paddle.static.nn.embedding(input=words[i], size=[dict_size, 32], + param_attr='embed', is_sparse=True) + embs.append(emb) + + embs = paddle.concat(x=embs, axis=1) + loss = paddle.static.nn.nce(input=embs, label=words[label_word], + num_total_classes=dict_size, param_attr='nce.w_0', + bias_attr='nce.b_0') + + #or use custom distribution + dist = np.array([0.05,0.5,0.1,0.3,0.05]) + loss = paddle.static.nn.nce(input=embs, label=words[label_word], + num_total_classes=5, param_attr='nce.w_1', + bias_attr='nce.b_1', + num_neg_samples=3, + sampler="custom_dist", + custom_dist=dist) + """ + helper = LayerHelper('nce', **locals()) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'nce') + check_variable_and_dtype(label, 'label', ['int64'], 'nce') + + dim = input.shape[1] + num_true_class = label.shape[1] + w = helper.create_parameter(attr=helper.param_attr, + shape=[num_total_classes, dim], + is_bias=False, + dtype=input.dtype) + inputs = {} + if helper.bias_attr: + b = helper.create_parameter(attr=helper.bias_attr, + shape=[num_total_classes, 1], + is_bias=True, + dtype=input.dtype) + inputs['Bias'] = b + cost = helper.create_variable_for_type_inference(dtype=input.dtype) + sample_logits = helper.create_variable_for_type_inference(dtype=input.dtype) + sample_labels = helper.create_variable_for_type_inference(dtype=label.dtype) + + inputs['Input'] = input + inputs['Label'] = label + inputs['Weight'] = w + inputs['SampleWeight'] = sample_weight if sample_weight is not None else [] + + if sampler == "uniform": + sampler = 0 + elif sampler == "log_uniform": + sampler = 1 + elif sampler == "custom_dist": + assert custom_dist is not None + + custom_dist_len = num_total_classes + alias_probs_ = [0] * custom_dist_len + alias_ = [0] * custom_dist_len + bigs = [] + littles = [] + for i in range(custom_dist_len): + normal_prob = custom_dist[i] * custom_dist_len + if normal_prob - 1.0 > 0: + bigs.append((i, normal_prob)) + elif 1.0 - normal_prob > 0: + littles.append((i, normal_prob)) + else: + alias_probs_[i] = normal_prob + alias_[i] = -1 + + while len(bigs) and len(littles): + big = bigs.pop(0) + little = littles.pop(0) + + big_idx = big[0] + big_prob = big[1] + + alias_probs_[little[0]] = little[1] + alias_[little[0]] = big_idx + big_left = big[1] + little[1] - 1 + if big_left - 1.0 > 0: + bigs.append((big_idx, big_left)) + elif 1.0 - big_left > 0: + littles.append((big_idx, big_left)) + else: + alias_probs_[big_idx] = big_left + alias_[big_idx] = -1 + + if len(bigs): + big = bigs.pop(0) + alias_probs_[big[0]] = 1.0 + alias_[big[0]] = -1 + if len(littles): + little = littles.pop(0) + alias_probs_[little[0]] = 1.0 + alias_[little[0]] = -1 + + def _init_by_numpy_array(numpy_array): + ret = helper.create_parameter( + attr=ParamAttr(), + shape=numpy_array.shape, + dtype=numpy_array.dtype, + default_initializer=NumpyArrayInitializer(numpy_array)) + ret.stop_gradient = True + return ret + + inputs['CustomDistProbs'] = _init_by_numpy_array( + np.array(custom_dist).astype('float32')) + inputs['CustomDistAlias'] = _init_by_numpy_array( + np.array(alias_).astype('int32')) + inputs['CustomDistAliasProbs'] = _init_by_numpy_array( + np.array(alias_probs_).astype('float32')) + sampler = 2 + else: + raise Exception("Unsupported sampler type.") + + if num_neg_samples is None: + num_neg_samples = 10 + else: + num_neg_samples = int(num_neg_samples) + + remote_prefetch = is_sparse + print( + "With sparse mode, if your models has only small parameter prefetch may cause speed down" + ) + + attrs = { + 'num_total_classes': int(num_total_classes), + 'num_neg_samples': num_neg_samples, + 'seed': seed, + 'sampler': sampler, + 'is_sparse': is_sparse, + 'remote_prefetch': remote_prefetch + } + + helper.append_op(type='nce', + inputs=inputs, + outputs={ + 'Cost': cost, + 'SampleLogits': sample_logits, + 'SampleLabels': sample_labels + }, + attrs=attrs) + return cost / (num_neg_samples + 1) + + +def hsigmoid(input, + label, + num_classes, + param_attr=None, + bias_attr=None, + name=None, + path_table=None, + path_code=None, + is_custom=False, + is_sparse=False): + """ + :api_attr: Static Graph + + The hierarchical sigmoid organizes the classes into a complete binary tree to reduce the computational complexity + and speed up the model training, especially the training of language model. + Each leaf node of the complete binary tree represents a class(word) and each non-leaf node acts as a binary classifier. + For each class(word), there's a unique path from root to itself, hsigmoid calculate the cost for each non-leaf node on + the path, and sum them to get a total cost. + Comparing to softmax, the OP can reduce the computational complexity from :math:`O(N)` to :math:`O(logN)`, where :math:`N` + represents the number of classes or the size of word dict. + + The OP supports default tree and custom tree. For the default tree, you can refer to `Hierarchical Probabilistic Neural + Network Language Model `. For the custom + tree, you need to set :attr:`is_custom` to True, and do the following steps (take the language model as an example): + + 1. Using a custom word dict to build a binary tree, each leaf node should be an word in the word dict. + 2. Creating a dict map word_id -> path that from the word to the root node, we call it path_table. + 3. Creating a dict map word_id -> code of path that from the word to the root node, we call it path_code. + Code means the label of each binary classifier, 1 indicate true, 0 indicate false. + 4. Now, each word should has its path and code along the path, you can pass a batch of path and code related + to the same batch of inputs. + + Parameters: + input (Variable): A tensor with the shape [N, D], where N is the size of mini-batch, + and D is the feature size. Its data type supports float32 and float64. + label (Variable): A tensor contains the labels of training data. Its shape is [N, 1] + and data type is int64. + num_classes (int): The number of classes or the size of word dict, must be greater than 2. + If the default tree is used (:attr:`is_custom` is set to False), :attr:`num_classes` + should not be None. If the custom tree is used (:attr:`is_custom` is set to True), + :attr:`num_classes` should be the number of non-leaf nodes, which indicates the num of + classes using by the binary classifier. + param_attr (ParamAttr, optional): The parameter attribute for the learnable parameters/weights + of hsigmoid. If it is set to None or one attribute of ParamAttr, hsigmoid will create a + ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is + initialized with Xavier. Default: None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of hsigmoid. If it + is set to False, no bias will be added. If it is set to None or one attribute of ParamAttr, + hsigmoid will create a ParamAttr as bias_attr. If the Initializer of the bias_attr is not + set, the bias is initialized zero. Default: None. + name (str, optional): Normally there is no need for user to set this property. For more information, + please refer to :ref:`api_guide_Name`. Default: None. + path_table (Variable, optional): A tensor that stores each batch of samples' path from leaf to root + node, its shape is [N, L] and data type is int64, where L is the length of path. For each sample i, + path_table[i] is a np.array like structure and each element in this array is the indexes in parent + nodes' weight matrix. Default: None. + path_code (Variable, optional): A tensor that stores each batch of samples' code of path from leaf + to root node, its shape is [N, L] and data type is int64, which is the same as :attr:`path_table`. + Each code of path is consisted with the code of nodes from leaf to root node. Default: None. + is_custom (bool, optional): Whether use custom binary tree. If it's True, :attr:`path_table`, + :attr:`path_code` and :attr:`num_classes` should be set, otherwise :attr:`num_classes` should + be set. Default: False. + is_sparse (bool, optional): Whether use sparse updating instead of dense updating, if it's True, the + gradient of W and input will be sparse. Default: False. + + Returns: + Variable: A tensor with the cost of hierarchical sigmoid, its shape is [N, 1] and data type is the same as :attr:`input`. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.fill_constant(shape=[4, 3], value=0.9, dtype='float32') + # x = [[0.9, 0.9, 0.9], [0.9, 0.9, 0.9], [0.9, 0.9, 0.9], [0.9, 0.9, 0.9]] + y = fluid.layers.fill_constant( + shape=[4, 1], value=1, dtype='int64') + # y = [[1], [1], [1], [1]] + out = fluid.layers.hsigmoid(input=x, label=y, num_classes=2, param_attr=fluid.initializer.Constant( + value=0.05), bias_attr=fluid.initializer.Constant(value=.0)) + # out = [[0.62792355], [0.62792355], [0.62792355], [0.62792355]] + """ + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'hsigmoid') + check_variable_and_dtype(label, 'label', ['int64'], 'hsigmoid') + + helper = LayerHelper('hierarchical_sigmoid', **locals()) + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + pre_out = helper.create_variable_for_type_inference(dtype) + dim = input.shape[1] + if ((num_classes is None) or (num_classes < 2)) and (not is_custom): + raise ValueError( + "num_classes must not be less than 2 with default tree") + + if (not is_custom) and (is_sparse): + print("Sparse mode should not be used without custom tree") + is_sparse = False + + if (not is_custom) and ((path_table is not None) or + (path_code is not None)): + raise ValueError( + "only num_classes should be passed without custom tree") + + if (is_custom) and (path_code is None): + raise ValueError("path_code should not be None with custom tree") + elif (is_custom) and (path_table is None): + raise ValueError("path_table should not be None with custom tree") + elif (is_custom) and (num_classes is None): + raise ValueError("num_classes should not be None with custom tree") + else: + pass + + weights = None + remote_prefetch = is_sparse + print( + "With sparse mode, if your models has only small parameter prefetch may cause speed down" + ) + if not is_custom: + weights = helper.create_parameter(attr=helper.param_attr, + shape=[num_classes - 1, dim], + is_bias=False, + dtype=input.dtype) + else: + weights = helper.create_parameter(attr=helper.param_attr, + shape=[num_classes, dim], + is_bias=False, + dtype=input.dtype) + inputs = { + "X": input, + "W": weights, + "PathTable": path_table, + "PathCode": path_code, + "Label": label + } + if helper.bias_attr: + if not is_custom: + bias = helper.create_parameter(attr=helper.bias_attr, + shape=[num_classes - 1, 1], + is_bias=True, + dtype=input.dtype) + inputs['Bias'] = bias + else: + bias = helper.create_parameter(attr=helper.bias_attr, + shape=[num_classes, 1], + is_bias=True, + dtype=input.dtype) + inputs['Bias'] = bias + helper.append_op(type="hierarchical_sigmoid", + inputs=inputs, + outputs={ + "Out": out, + "PreOut": pre_out, + "W_Out": weights + }, + attrs={ + "num_classes": num_classes, + "is_sparse": is_sparse, + "remote_prefetch": remote_prefetch + }) + return out + + +def sampled_softmax_with_cross_entropy(logits, + label, + num_samples, + num_true=1, + remove_accidental_hits=True, + use_customized_samples=False, + customized_samples=None, + customized_probabilities=None, + seed=0): + """ + **Sampled Softmax With Cross Entropy Operator.** + + Cross entropy loss with sampled softmax is used as the output layer for + larger output classes extensively. This operator samples a number of samples + for all examples, and computes the softmax normalized values for each + row of the sampled tensor, after which cross-entropy loss is computed. + + Because this operator performs a softmax on logits internally, it expects + unscaled logits. This operator should not be used with the output of + softmax operator since that would produce incorrect results. + + For examples with T true labels (T >= 1), we assume that each true label has + a probability of 1/T. For each sample, S samples are generated using a + log uniform distribution. True labels are concatenated with these samples to + form T + S samples for each example. So, assume the shape of logits is + [N x K], the shape for samples is [N x (T+S)]. For each sampled label, a + probability is calculated, which corresponds to the Q(y|x) in + [Jean et al., 2014](http://arxiv.org/abs/1412.2007). + + Logits are sampled according to the sampled labels. Then if + remove_accidental_hits is True, if a sample[i, j] accidentally hits true + labels, then the corresponding sampled_logits[i, j] is minus by 1e20 to + make its softmax result close to zero. Then sampled logits are subtracted by + logQ(y|x), these sampled logits and re-indexed labels are used to compute + a softmax with cross entropy. + + Args: + logits (Variable): The unscaled log probabilities, which is a 2-D tensor + with shape [N x K]. N is the batch_size, and K is the class number. + label (Variable): The ground truth which is a 2-D tensor. Label is a + Tensor with shape [N x T], where T is the number of true + labels per example. + num_samples (int): The number for each example, num_samples should be + less than the number of class. + num_true(int): The number of target classes per training example. + remove_accidental_hits (bool): A flag indicating whether to remove + accidental hits when sampling. If True and if a sample[i, j] + accidentally hits true labels, then the corresponding + sampled_logits[i, j] is minus by 1e20 to make its softmax result + close to zero. Default is True. + use_customized_samples (bool): Whether to use custom samples and probabities to sample + logits. + customized_samples (Variable): User defined samples, which is a 2-D tensor + with shape [N, T + S]. S is the num_samples, and T is the number of true + labels per example. + customized_probabilities (Variable): User defined probabilities of samples, + a 2-D tensor which has the same shape with customized_samples. + seed (int): The random seed for generating random number, which is used + in the process of sampling. Default is 0. + + Returns: + Variable: Return the cross entropy loss which is a 2-D tensor with shape + [N x 1]. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + input = fluid.layers.data(name='data', shape=[256], dtype='float32') + label = fluid.layers.data(name='label', shape=[1], dtype='int64') + fc = fluid.layers.fc(input=input, size=100) + out = fluid.layers.sampled_softmax_with_cross_entropy( + logits=fc, label=label, num_samples=25) + """ + if _non_static_mode(): + sample_logits_attrs = ('use_customized_samples', use_customized_samples, + 'uniq', True, 'remove_accidental_hits', + remove_accidental_hits, 'num_samples', + num_samples, 'seed', seed) + _, _, _, _, sampled_logits_out, sampled_label_out = _legacy_C_ops.sample_logits( + logits, label, *sample_logits_attrs) + depth = num_samples + 1 + sampled_softlabel_out = _legacy_C_ops.one_hot(sampled_label_out, + 'depth', depth) + + softmax_with_cross_entropy_attrs = ('soft_label', True, + 'numeric_stable_mode', False) + + _, loss = _legacy_C_ops.softmax_with_cross_entropy( + sampled_logits_out, sampled_softlabel_out, + *softmax_with_cross_entropy_attrs) + return loss / num_true + + helper = LayerHelper('sample_logits', **locals()) + samples = customized_samples if use_customized_samples else helper.create_variable_for_type_inference( + dtype='int64') + probabilities = customized_probabilities if use_customized_samples else helper.create_variable_for_type_inference( + dtype=logits.dtype) + sampled_logits \ + = helper.create_variable_for_type_inference(dtype=logits.dtype) + sampled_label = helper.create_variable_for_type_inference(dtype='int64') + sampled_softlabel = helper.create_variable_for_type_inference( + dtype=logits.dtype) + logits_dim = helper.create_variable_for_type_inference(dtype=logits.dtype) + labels_dim = helper.create_variable_for_type_inference(dtype=label.type) + + helper.append_op(type='sample_logits', + inputs={ + 'Logits': logits, + 'Labels': label, + 'CustomizedSamples': customized_samples, + 'CustomizedProbabilities': customized_probabilities + }, + outputs={ + 'Samples': samples, + 'Probabilities': probabilities, + 'SampledLabels': sampled_label, + 'SampledLogits': sampled_logits, + 'LogitsDim': logits_dim, + 'LabelsDim': labels_dim + }, + attrs={ + 'use_customized_samples': use_customized_samples, + 'uniq': True, + 'remove_accidental_hits': remove_accidental_hits, + 'num_samples': num_samples, + 'seed': seed + }) + loss = helper.create_variable_for_type_inference(dtype=logits.dtype) + softmax = helper.create_variable_for_type_inference(dtype=logits.dtype) + helper.append_op(type='one_hot', + inputs={'X': sampled_label}, + attrs={'depth': num_samples + 1}, + outputs={'Out': sampled_softlabel}) + + helper.append_op(type='softmax_with_cross_entropy', + inputs={ + 'Logits': sampled_logits, + 'Label': sampled_softlabel + }, + outputs={ + 'Softmax': softmax, + 'Loss': loss + }, + attrs={ + 'soft_label': True, + 'ignore_index': False, + 'numeric_stable_mode': False + }) + return loss / num_true + + +def softmax_with_cross_entropy(logits, + label, + soft_label=False, + ignore_index=kIgnoreIndex, + numeric_stable_mode=True, + return_softmax=False, + axis=-1): + r""" + + This operator implements the cross entropy loss function with softmax. This function + combines the calculation of the softmax operation and the cross entropy loss function + to provide a more numerically stable gradient. + + Because this operator performs a softmax on logits internally, it expects + unscaled logits. This operator should not be used with the output of + softmax operator since that would produce incorrect results. + + When the attribute :attr:`soft_label` is set :attr:`False`, this operators + expects mutually exclusive hard labels, each sample in a batch is in exactly + one class with a probability of 1.0. Each sample in the batch will have a + single label. + + The equation is as follows: + + 1) Hard label (one-hot label, so every sample has exactly one class) + + .. math:: + + loss_j = -\\text{logits}_{label_j} + + \\log\\left(\\sum_{i=0}^{K}\\exp(\\text{logits}_i)\\right), j = 1,..., K + + 2) Soft label (each sample can have a distribution over all classes) + + .. math:: + + loss_j = -\\sum_{i=0}^{K}\\text{label}_i + \\left(\\text{logits}_i - \\log\\left(\\sum_{i=0}^{K} + \\exp(\\text{logits}_i)\\right)\\right), j = 1,...,K + + 3) If :attr:`numeric_stable_mode` is :attr:`True`, softmax is calculated first by: + + .. math:: + + max_j &= \\max_{i=0}^{K}{\\text{logits}_i} + + log\\_max\\_sum_j &= \\log\\sum_{i=0}^{K}\\exp(logits_i - max_j) + + softmax_j &= \\exp(logits_j - max_j - {log\\_max\\_sum}_j) + + and then cross entropy loss is calculated by softmax and label. + + Args: + logits (Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64. The input tensor of unscaled log probabilities. + label (Tensor): The ground truth ``Tensor`` , data type is the same + as the ``logits`` . If :attr:`soft_label` is set to :attr:`True`, + Label is a ``Tensor`` in the same shape with :attr:`logits`. + If :attr:`soft_label` is set to :attr:`True`, Label is a ``Tensor`` + in the same shape with :attr:`logits` expect shape in dimension :attr:`axis` as 1. + soft_label (bool, optional): A flag to indicate whether to interpretant the given + labels as soft labels. Default False. + ignore_index (int, optional): Specifies a target value that is ignored and does + not contribute to the input gradient. Only valid + if :attr:`soft_label` is set to :attr:`False`. + Default: kIgnoreIndex(-100). + numeric_stable_mode (bool, optional): A flag to indicate whether to use a more + numerically stable algorithm. Only valid + when :attr:`soft_label` is :attr:`False` + and GPU is used. When :attr:`soft_label` + is :attr:`True` or CPU is used, the + algorithm is always numerically stable. + Note that the speed may be slower when use + stable algorithm. Default: True. + return_softmax (bool, optional): A flag indicating whether to return the softmax + along with the cross entropy loss. Default: False. + axis (int, optional): The index of dimension to perform softmax calculations. It + should be in range :math:`[-1, rank - 1]`, while :math:`rank` + is the rank of input :attr:`logits`. Default: -1. + + Returns: + ``Tensor`` or Tuple of two ``Tensor`` : Return the cross entropy loss if \ + `return_softmax` is False, otherwise the tuple \ + (loss, softmax), softmax is in the same shape \ + with input logits and cross entropy loss is in \ + the same shape with input logits except shape \ + in dimension :attr:`axis` as 1. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + data = np.random.rand(128).astype("float32") + label = np.random.rand(1).astype("int64") + data = paddle.to_tensor(data) + label = paddle.to_tensor(label) + linear = paddle.nn.Linear(128, 100) + x = linear(data) + out = paddle.nn.functional.softmax_with_cross_entropy(logits=x, label=label) + print(out) + """ + return paddle.nn.functional.loss.fluid_softmax_with_cross_entropy( + logits, label, soft_label, ignore_index, numeric_stable_mode, + return_softmax, axis) + + +def identity_loss(x, reduction="none"): + r"""Marks a tensor as being part of the loss calculation for IPU. + + This operator is used to handle on the (final) loss of a model so that + it is used as the start of backpropagation. + + When `reduction` is `none`, return raw `Out`. + + When `reduction` is `mean`, return + + .. math:: + Out = MEAN(Out) + + When `reduction` is `sum`, return + + .. math:: + Out = SUM(Out) + + Parameters: + x (Variable): The input tensor. The shapes is [N, *], where N is batch size and `*` means any number of + additional dimensions. It's data type should be float32, float64 on CPU and float16, float32 on IPU. + reduction(str|int, optional): Reduce the loss output. Supported string values are: 'sum', 'mean', 'none' + the corresponding int values are 0, 1, 2 respectively. The default value is "none". + + Returns: + Variable: The loss ``Tensor`` with the specified reduction applied. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + loss = fluid.data(name="loss", shape=[-1, 1], dtype="float32") + out = paddle.incubate.identity_loss(loss, reduction=1) + """ + if isinstance(reduction, str): + reduction = {"sum": 0, "mean": 1, "none": 2}.get(reduction.lower()) + if reduction is None: + raise Exception("Unsupported reduction type.") + + if _non_static_mode(): + return _legacy_C_ops.identity_loss(x, "reduction", reduction) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], "identity_loss") + attrs = {'reduction': reduction} + helper = LayerHelper('identity_loss', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="identity_loss", + inputs={"X": x}, + outputs={"Out": out}, + attrs=attrs) + return out + + +def rank_loss(label, left, right, name=None): + r""" + + This operator implements the sort loss layer in the RankNet model. RankNet is a pairwise ranking model + with a training sample consisting of a pair of documents (A and B), The label (P) + indicates whether A is ranked higher than B or not. Please refer to more details: + `RankNet `_ + + Rank loss layer takes three inputs: left ( :math:`o_i` ), right ( :math:`o_j` ) and + label ( :math:`P_{i,j}` ). The inputs respectively represent RankNet's output scores + for documents A and B and the value of label P. Rank loss layer takes batch inputs + with size batch_size (batch_size >= 1), P = {0, 1} or {0, 0.5, 1}, + where 0.5 means that there is no information about the rank of the input pair. + The following equation computes rank loss C_{i,j} from the inputs: + + .. math:: + C_{i,j} &= -\\tilde{P_{ij}} * o_{i,j} + \log(1 + e^{o_{i,j}}) \\\\ + .. math:: + o_{i,j} &= o_i - o_j \\\\ + .. math:: + \\tilde{P_{i,j}} &= \\left \{0, 0.5, 1 \\right \} \ or \ \\left \{0, 1 \\right \} + + Parameters: + label (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32, batch indicates the size of the data. Indicats whether A ranked higher than B or not. + left (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32. RankNet's output score for doc A. + right (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32. RankNet's output score for doc B. + name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: ``Tensor`` indicating the output value of the sort loss layer, the data type is float32, and the return value's shape is :math:`[batch,1]` . + + Raises: + ValueError: Any of label, left, and right is not a ``Variable`` . + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + label = fluid.data(name="label", shape=[-1, 1], dtype="float32") + left = fluid.data(name="left", shape=[-1, 1], dtype="float32") + right = fluid.data(name="right", shape=[-1, 1], dtype="float32") + out = fluid.layers.rank_loss(label, left, right) + + """ + helper = LayerHelper('rank_loss', **locals()) + check_variable_and_dtype(label, 'label', ['float32'], "rank_loss") + check_variable_and_dtype(left, 'left', ['float32'], "rank_loss") + check_variable_and_dtype(right, 'right', ['float32'], "rank_loss") + + out = helper.create_variable_for_type_inference("float32") + + helper.append_op(type='rank_loss', + inputs={ + "Label": label, + "Left": left, + "Right": right + }, + outputs={'Out': out}) + return out + + +def margin_rank_loss(label, left, right, margin=0.1, name=None): + r""" + Margin Ranking Loss Layer for ranking problem, + which compares left score and right score passed in. + The ranking loss can be defined as following equation: + + .. math:: + + rank\_loss = max(0, -label * (left - right) + margin) + + Args: + label (Variable): Indicates whether the left is ranked higher than the right or not. + Data type is float32. + left (Variable): Ranking score for left. Data type float32. + right (Variable): Ranking score for right. Data type float32. + margin (float): Indicates the given margin. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Variable: The ranking loss. + + Raises: + ValueError: Any of label, left, and right is not a Variable. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + label = fluid.data(name="label", shape=[-1, 1], dtype="float32") + left = fluid.data(name="left", shape=[-1, 1], dtype="float32") + right = fluid.data(name="right", shape=[-1, 1], dtype="float32") + out = fluid.layers.margin_rank_loss(label, left, right) + """ + helper = LayerHelper('margin_rank_loss', **locals()) + check_variable_and_dtype(label, 'label', ['float32'], 'margin_rank_loss') + check_variable_and_dtype(label, 'left', ['float32'], 'margin_rank_loss') + check_variable_and_dtype(label, 'right', ['float32'], 'margin_rank_loss') + out = helper.create_variable_for_type_inference(left.dtype) + act = helper.create_variable_for_type_inference(left.dtype) + helper.append_op(type='margin_rank_loss', + inputs={ + "Label": label, + "X1": left, + "X2": right + }, + outputs={ + 'Out': out, + 'Activated': act + }, + attrs={'margin': margin}) + return out + + +@templatedoc() +def sigmoid_cross_entropy_with_logits(x, + label, + ignore_index=kIgnoreIndex, + name=None, + normalize=False): + """ + + ${comment} + + Args: + x(Tensor): a 2-D tensor with shape N x D, where N is the batch size and + D is the number of classes. This input is a tensor of logits computed + by the previous operator. Logits are unscaled log probabilities given + as log(p/(1-p)) The data type should be float32 or float64. + label (Tensor): a 2-D tensor of the same type and shape as X. + This input is a tensor of probabalistic labels for each logit. + ignore_index(int): Specifies a target value that is ignored and + does not contribute to the input gradient. + name(str|None): The default value is None. Normally there is + no need for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + normalize(bool): If true, divide the output by the number of + targets != ignore_index. + + Returns: + out(Tensor): ${out_comment} + + Examples: + .. code-block:: python + + + import paddle + + input = paddle.rand(shape=[10], dtype='float32') + label = paddle.rand(shape=[10], dtype='float32') + loss = paddle.fluid.layers.sigmoid_cross_entropy_with_logits(input, label, + ignore_index=-1, normalize=True) + print(loss) + """ + + if in_dygraph_mode(): + return _C_ops.sigmoid_cross_entropy_with_logits(x, label, normalize, + int(ignore_index)) + check_variable_and_dtype(x, 'input', ['float16', 'float32', 'float64'], + 'sigmoid_cross_entropy_with_logits') + + helper = LayerHelper("sigmoid_cross_entropy_with_logits", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type="sigmoid_cross_entropy_with_logits", + inputs={ + "X": x, + "Label": label + }, + attrs={ + "ignore_index": ignore_index, + 'normalize': normalize + }, + outputs={"Out": out}) + return out + + +def teacher_student_sigmoid_loss(input, + label, + soft_max_up_bound=15.0, + soft_max_lower_bound=-15.0): + """ + + **Teacher Student Log Loss Layer** + + This layer accepts input predictions and target label and returns the + teacher_student loss. Z is click or not, z' is value of teacher loss, label = {-2, -1, [0, 2]} + when z' is not exist, clk = 0 : label = -2; when z' is not exist, clk = 1 : label = -1; + when z' is exist , clk = 0 : label = 0 + z'; when z' is exist , clk = 1 : label = 1 + z' + + .. math:: + loss = max(x, 0) - x * z + log(1 + exp(-abs(x))) + max(x, 0) - x * z' + log(1 + exp(-abs(x))) + + Args: + input (Variable|list): a 2-D tensor with shape [N x 1], where N is the + batch size. This input is a probability computed + by the previous operator. + label (Variable|list): the ground truth which is a 2-D tensor with + shape [N x 1], where N is the batch size. + soft_max_up_bound (float): if input > soft_max_up_bound, will be bound + soft_max_lower_bound (float): if input < soft_max_lower_bound, will be bound + + Returns: + Variable: A 2-D tensor with shape [N x 1], the teacher_student_sigmoid_loss. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + batch_size = 64 + label = fluid.data( + name="label", shape=[batch_size, 1], dtype="int64") + similarity = fluid.data( + name="similarity", shape=[batch_size, 1], dtype="float32") + cost = fluid.layers.teacher_student_sigmoid_loss(input=similarity, label=label) + + """ + check_variable_and_dtype(input, "input", + ['float32', 'float64', 'int32', 'int64'], + 'teacher_student_sigmoid_loss') + check_variable_and_dtype(label, "label", + ['float32', 'float64', 'int32', 'int64'], + 'teacher_student_sigmoid_loss') + + helper = LayerHelper('teacher_student_sigmoid_loss', **locals()) + out = helper.create_variable(dtype=input.dtype) + helper.append_op( + type='teacher_student_sigmoid_loss', + inputs={'X': [input], + 'Label': [label]}, + outputs={'Y': [out]}, + attrs={"soft_max_lower_bound": float(soft_max_lower_bound), \ + "soft_max_up_bound": float(soft_max_up_bound)}) + return out + + +def huber_loss(input, label, delta): + r""" + This operator computes the Huber loss between input and label. + Huber loss is commonly used in regression tasks. Compared to square_error_cost, Huber loss is more robust and less sensitivity to outliers. + + When the absolute difference between input and label is greater than delta, the linear error is calculated: + + .. math:: + huber\_loss = delta * (label - input) - 0.5 * delta * delta + + When the absolute difference between input and label is greater than delta, the square error is calculated: + + .. math:: + huber\_loss = 0.5 * (label - input) * (label - input) + + + Args: + input (Variable): Predicted data, 2D-Tensor with the shape of [batch_size, 1]. The data type should be float32. + label (Variable): Ground truth label, 2D-Tensor with the shape of [batch_size, 1]. The data type should be float32. + delta (float): The threshold for Huber loss, which is used to control the balance between the linear error and square error. The data type should be float32. + + Returns: + Variable: The huber loss, a tensor with the same shape and data type as input. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + DATATYPE='float32' + input_data = np.array([[1.],[2.],[3.],[4.]]).astype(DATATYPE) + label_data = np.array([[3.],[3.],[4.],[4.]]).astype(DATATYPE) + + x = fluid.data(name='input', shape=[None, 1], dtype=DATATYPE) + y = fluid.data(name='label', shape=[None, 1], dtype=DATATYPE) + loss = fluid.layers.huber_loss(input=x, label=y, delta=1.0) + + place = fluid.CPUPlace() + #place = fluid.CUDAPlace(0) + exe = fluid.Executor(place) + HuberLoss, = exe.run(feed={'input':input_data ,'label':label_data}, fetch_list=[loss.name]) + print(HuberLoss) #[[1.5], [0.5], [0.5], [0. ]], dtype=float32 + """ + if in_dygraph_mode(): + out, residual = _C_ops.huber_loss(input, label, delta) + return out + + helper = LayerHelper('huber_loss', **locals()) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'huber_loss') + check_variable_and_dtype(label, 'label', ['float32', 'float64'], + 'huber_loss') + residual = helper.create_variable_for_type_inference( + dtype=helper.input_dtype()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op(type='huber_loss', + inputs={ + 'X': input, + 'Y': label + }, + outputs={ + 'Out': out, + 'Residual': residual + }, + attrs={'delta': delta}) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.kl_div") +@templatedoc() +def kldiv_loss(x, target, reduction='mean', name=None): + """ + + ${comment} + + Args: + x (Tensor): ${x_comment} + target (Tensor): ${target_comment} + reduction (Tensor): ${reduction_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The KL divergence loss. The data type is same as input tensor + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + x = paddle.rand(shape=[3,4,2,2], dtype='float32') + target = paddle.rand(shape=[3,4,2,2], dtype='float32') + + # 'batchmean' reduction, loss shape will be [1] + loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='batchmean') + print(loss.shape) # shape=[1] + + # 'mean' reduction, loss shape will be [1] + loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='mean') + print(loss.shape) # shape=[1] + + # 'sum' reduction, loss shape will be [1] + loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='sum') + print(loss.shape) # shape=[1] + + # 'none' reduction, loss shape is same with X shape + loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='none') + print(loss.shape) # shape=[3, 4, 2, 2] + + """ + helper = LayerHelper('kldiv_loss', **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'kldiv_loss') + check_variable_and_dtype(target, 'target', ['float32', 'float64'], + 'kldiv_loss') + check_type(reduction, 'reduction', str, 'kldiv_loss') + loss = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='kldiv_loss', + inputs={ + 'X': x, + 'Target': target + }, + outputs={'Loss': loss}, + attrs={'reduction': reduction}) + return loss + + +from .ops import square +from .control_flow import equal + + +def npair_loss(anchor, positive, labels, l2_reg=0.002): + """ + + Npair loss requires paired data. Npair loss has two parts: the first part is L2 + regularizer on the embedding vector; the second part is cross entropy loss which + takes the similarity matrix of anchor and positive as logits. + + For more information, please refer to: + `Improved Deep Metric Learning with Multi class N pair Loss Objective `_ + + Args: + anchor(Tensor): embedding vector for the anchor image. shape=[batch_size, embedding_dims], + the data type is float32 or float64. + positive(Tensor): embedding vector for the positive image. shape=[batch_size, embedding_dims], + the data type is float32 or float64. + labels(Tensor): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64. + l2_reg(float32): L2 regularization term on embedding vector, default: 0.002. + + + Returns: + A Tensor representing the npair loss, the data type is the same as anchor, the shape is [1]. + + Examples: + + .. code-block:: python + + import paddle + + DATATYPE = "float32" + + anchor = paddle.rand(shape=(18, 6), dtype=DATATYPE) + positive = paddle.rand(shape=(18, 6), dtype=DATATYPE) + labels = paddle.rand(shape=(18,), dtype=DATATYPE) + + npair_loss = paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg = 0.002) + print(npair_loss) + + """ + return paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg) + + +def mse_loss(input, label): + """ + + This op accepts input predications and target label and returns the mean square error. + + The loss can be described as: + + .. math:: + + Out = MEAN((input - label)^2) + + Parameters: + input (Tensor): Input tensor, the data type should be float32. + label (Tensor): Label tensor, the data type should be float32. + + Returns: + Tensor: The tensor storing the mean square error difference of input and label. + + Return type: Tensor. + + Examples: + .. code-block:: python + + import paddle + input = paddle.to_tensor([1.1, 1.9]) + label = paddle.to_tensor([1.0, 2.0]) + output = paddle.fluid.layers.mse_loss(input, label) + print(output.numpy()) + # [0.01] + """ + check_variable_and_dtype(input, "input", ['float32', 'float64'], 'mse_loss') + check_variable_and_dtype(label, "label", ['float32', 'float64'], 'mse_loss') + return nn.reduce_mean(square_error_cost(input, label)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/math_op_patch.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/math_op_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..cfa74f3505bc970801b230c292eee2b6575c410a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/math_op_patch.py @@ -0,0 +1,542 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import warnings +import inspect + +from .. import core +from ..framework import Variable, unique_name, static_only +from .layer_function_generator import OpProtoHolder +from .control_flow import array_write, array_length +from paddle.fluid.dygraph.base import in_declarative_mode + +_supported_int_dtype_ = [ + core.VarDesc.VarType.BOOL, + core.VarDesc.VarType.UINT8, + core.VarDesc.VarType.INT8, + core.VarDesc.VarType.INT16, + core.VarDesc.VarType.INT32, + core.VarDesc.VarType.INT64, +] + +compare_ops = ['__eq__', '__ne__', '__lt__', '__le__', '__gt__', '__ge__'] + +EXPRESSION_MAP = { + "__add__": "A + B", + "__radd__": "A += B", + "__sub__": "A - B", + "__rsub__": "A -= B", + "__mul__": "A * B", + "__rmul__": "A *= B", + "__div__": "A / B", + "__truediv__": "A / B", + "__rdiv__": "A /= B", + "__rtruediv__": "A /= B", + "__pow__": "A ** B", + "__rpow__": "A **= B", + "__floordiv__": "A //B", + "__mod__": "A % B", + "__matmul__": "A @ B", + "__eq__": "A == B", + "__ne__": "A != B", + "__lt__": "A < B", + "__le__": "A <= B", + "__gt__": "A > B", + "__ge__": "A >= B" +} + +_already_patch_variable = False + + +def monkey_patch_variable(): + + def unique_tmp_name(): + return unique_name.generate("tmp") + + def safe_get_dtype(var): + try: + dtype = var.dtype + except: + raise ValueError("Cannot get data type from %s", var.name) + return dtype + + def current_block(var): + return var.block.program.current_block() + + def create_new_tmp_var(block, dtype): + tmp_name = unique_tmp_name() + return block.create_var(name=tmp_name, dtype=dtype) + + def create_new_tmp_sparse_var(block, dtype, type): + tmp_name = unique_tmp_name() + return block.create_var(name=tmp_name, dtype=dtype, type=type) + + def create_tensor(block, value, dtype, shape): + value = float(value) + var = create_new_tmp_var(block, dtype) + block.append_op(type="fill_constant", + outputs={'Out': [var]}, + attrs={ + 'dtype': var.dtype, + 'shape': shape, + 'value': value, + 'force_cpu': False + }, + stop_gradient=True) + var.stop_gradient = True + return var + + def create_scalar(block, value, dtype): + return create_tensor(block, value, dtype, shape=[1]) + + def create_tensor_with_batchsize(ref_var, value, dtype): + assert isinstance(ref_var, Variable) + value = float(value) + block = current_block(ref_var) + var = create_new_tmp_var(block, dtype) + batch_dim = -1 + out_shape = [] + for i, d in enumerate(ref_var.shape): + if d < 0: + if batch_dim < 0: + batch_dim = i + out_shape.append(d) + else: + out_shape.append(1) + else: + out_shape.append(d) + assert batch_dim != -1 + block.append_op(type='fill_constant_batch_size_like', + outputs={'Out': [var]}, + inputs={'Input': [ref_var]}, + attrs={ + 'shape': out_shape, + 'value': value, + 'input_dim_idx': batch_dim, + 'output_dim_idx': batch_dim + }, + stop_gradient=True) + + var.stop_gradient = True + return var + + @static_only + def cpu(self): + """ + Variable should not have cpu() and cuda() interface. + But this interface can greatly facilitate dy2static. + We do nothing here. + """ + return self + + @static_only + def cuda(self): + """ + Variable should not have cpu() and cuda() interface. + But this interface can greatly facilitate dy2static. + We do nothing here. + """ + return self + + @static_only + def place(self): + """ + Variable don't have 'place' interface in static mode + But this interface can greatly facilitate dy2static. + So we give a warnning here and return None. + """ + warnings.warn( + "Variable do not have 'place' interface for static mode, try not to use it. None will be returned." + ) + return None + + def astype(self, dtype): + """ + **Notes**: + **The variable must be a** :ref:`api_fluid_Tensor` + + Cast a variable to a specified data type. + + Args: + + self(Variable): The source variable + + dtype: The target data type + + Returns: + Variable: Variable with new dtype + + Examples: + In Static Graph Mode: + + .. code-block:: python + + import paddle.fluid as fluid + + startup_prog = fluid.Program() + main_prog = fluid.Program() + with fluid.program_guard(startup_prog, main_prog): + original_variable = fluid.data(name = "new_variable", shape=[2,2], dtype='float32') + new_variable = original_variable.astype('int64') + print("new var's dtype is: {}".format(new_variable.dtype)) + + In Dygraph Mode: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + x = np.ones([2, 2], np.float32) + with fluid.dygraph.guard(): + original_variable = fluid.dygraph.to_variable(x) + print("original var's dtype is: {}, numpy dtype is {}".format(original_variable.dtype, original_variable.numpy().dtype)) + new_variable = original_variable.astype('int64') + print("new var's dtype is: {}, numpy dtype is {}".format(new_variable.dtype, new_variable.numpy().dtype)) + + """ + block = current_block(self) + out = create_new_tmp_var(block, dtype) + block.append_op(type="cast", + inputs={"X": [self]}, + outputs={"Out": [out]}, + attrs={ + "in_dtype": self.dtype, + "out_dtype": out.dtype + }) + out.stop_gradient = self.stop_gradient + return out + + @static_only + def append(self, var): + """ + **Notes**: + **The type variable must be LoD Tensor Array. + + """ + if not isinstance(var, Variable): + if in_declarative_mode(): + """ in dy2static mode, x may be tensorable values such as int, float, np.array + """ + from paddle.tensor.creation import to_tensor + var = to_tensor(var) + else: + raise TypeError( + "Required input var should be Variable, but received {}". + format(type(var))) + if self.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "Only Variable with VarType.LOD_TENSOR_ARRAY support `append` method, but received type: {}" + .format(self.type)) + array_write(x=var, i=array_length(self), array=self) + + @static_only + def _item(self): + """ + In order to be compatible with the item interface introduced by the dynamic graph, it does nothing but returns self. + It will check that the shape must be a 1-D tensor + """ + if len(self.shape) > 1: + raise TypeError( + "Required input var should be 1-D Variable, but received {}". + format(self.shape)) + return self + + @static_only + def pop(self, *args): + """ + The type variable must be LoD Tensor Array. + When self is LoDTensorArray, calling pop is similar to Python's pop on list. + This interface is used to simplify dygraph to static graph operations. + + Args: + self(Variable): The source variable, which must be LOD_TENSOR_ARRAY + *args: optional, a int means index. + Returns: + Variable: self[index] + """ + from paddle.fluid.dygraph.dygraph_to_static.convert_operators import _run_paddle_pop + if self.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "Only Variable with VarType.LOD_TENSOR_ARRAY support `append` method, but received type: {}" + .format(self.type)) + return _run_paddle_pop(self, *args) + + def _scalar_op_(var, scale, bias): + block = current_block(var) + out = create_new_tmp_var(block, var.dtype) + block.append_op(type="scale", + inputs={"X": [var]}, + outputs={"Out": [out]}, + attrs={ + "scale": scale, + "bias": bias + }) + return out + + def _neg_(var): + return _scalar_op_(var, -1.0, 0.0) + + @property + def _ndim_(self): + """ + Returns the dimension of current Variable + + Returns: + the dimension + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + # create a static Variable + x = paddle.static.data(name='x', shape=[3, 2, 1]) + # print the dimension of the Variable + print(x.ndim) + """ + return len(self.shape) + + def _scalar_add_(var, value): + return _scalar_op_(var, 1.0, value) + + def _scalar_sub_(var, value): + return _scalar_op_(var, 1.0, -value) + + def _scalar_rsub_(var, value): + return _scalar_op_(var, -1.0, value) + + def _scalar_mul_(var, value): + return _scalar_op_(var, value, 0.0) + + def _scalar_div_(var, value): + return _scalar_op_(var, 1.0 / value, 0.0) + + def _binary_creator_(method_name, + op_type, + reverse=False, + scalar_method=None): + + def __impl__(self, other_var): + # 1. scalar exists cases + # we need combine the tensor.dtype and scalar.dtype, cast correct object + if isinstance(other_var, float): + # in all cases(+, -, *, /, **, //, %), we need cast tensor.dtype to float + if self.dtype in _supported_int_dtype_: + self = astype(self, 'float32') + # here use `scale` replace `elementwise` to get better performance + # but only +, -, *, / can use this method + if scalar_method is not None: + return scalar_method(self, other_var) + elif isinstance(other_var, int): + # in all cases(+, -, *, /, **, //, %), we can cast it to float + # because the output tensor.dtype depend on the type of input tensor + other_var = float(other_var) + # division is a special case + # NOTE(chenweihang): because we cast tensor to float32 instead float64, + # the division result can only guarantee the numerical accuracy of 6 digits + # after the decimal point. The result of numpy calculation is of float64 type, + # so the calculation result here and the calculation result of numpy are + # different after 6 decimal point. If necessary, we can also use float64 here. + # torch's behavior here is consistent with ours + if op_type == 'elementwise_div' and self.dtype in _supported_int_dtype_: + self = astype(self, 'float32') + # here use `scale` replace `elementwise` to get better performance + # but only +, -, *, / can use this method + if scalar_method is not None: + return scalar_method(self, other_var) + else: + # do nothing + pass + + # 2. create variable for scalar + lhs_dtype = safe_get_dtype(self) + if not isinstance(other_var, Variable): + if reverse: + has_batch_size = False + for elem in self.shape: + if elem < 0: + has_batch_size = True + break + if not has_batch_size: + other_var = create_tensor(current_block(self), + other_var, + dtype=lhs_dtype, + shape=self.shape) + else: + other_var = create_tensor_with_batchsize( + self, other_var, lhs_dtype) + else: + # add fill_op to current_block + other_var = create_scalar(current_block(self), + value=other_var, + dtype=lhs_dtype) + + # 3. unify right var type to left var + rhs_dtype = safe_get_dtype(other_var) + if lhs_dtype != rhs_dtype: + other_var = astype(other_var, lhs_dtype) + if reverse: + tmp = self + self = other_var + other_var = tmp + + # NOTE(zhiqiu): the output of compare operator should be bool. + if method_name in compare_ops: + out = create_new_tmp_var(current_block(self), dtype="bool") + else: + out = create_new_tmp_var(current_block(self), dtype=lhs_dtype) + + axis = -1 + if other_var.shape[0] == -1: + stack = inspect.stack()[1] + file_name = stack[1] + line_num = stack[2] + warnings.warn( + "%s:%s\nThe behavior of expression %s has been unified with %s(X, Y, axis=-1) from Paddle 2.0. " + "If your code works well in the older versions but crashes in this version, try to use " + "%s(X, Y, axis=0) instead of %s. This transitional warning will be dropped in the future." + % (file_name, line_num, EXPRESSION_MAP[method_name], + op_type, op_type, EXPRESSION_MAP[method_name]), + category=DeprecationWarning) + current_block(self).append_op(type=op_type, + inputs={ + 'X': [self], + 'Y': [other_var] + }, + outputs={'Out': out}, + attrs={'axis': axis}) + return out + + comment = OpProtoHolder.instance().get_op_proto(op_type).comment + + __impl__.__doc__ = """ + {0} + Args: + self(Variable): left hand variable + other_var(Variable|float|int): right hand variable + + Returns: + Variable + """.format(comment) + __impl__.__name__ = method_name + return __impl__ + + def values(var): + block = current_block(var) + out = create_new_tmp_var(block, var.dtype) + block.append_op(type="sparse_values", + inputs={"x": [var]}, + outputs={"out": [out]}, + attrs={}) + return out + + def indices(var): + block = current_block(var) + out = create_new_tmp_var(block, var.dtype) + block.append_op(type="sparse_indices", + inputs={"x": [var]}, + outputs={"out": [out]}, + attrs={}) + return out + + def to_dense(var): + block = current_block(var) + out = create_new_tmp_var(block, var.dtype) + block.append_op(type="sparse_to_dense", + inputs={"x": [var]}, + outputs={"out": [out]}, + attrs={}) + return out + + variable_methods = [ + # b=-a + ('__neg__', _neg_), + ('astype', astype), + ('cpu', cpu), + ('cuda', cuda), + ('place', place), + ('append', append), + ('item', _item), + ('pop', pop), + ('dim', lambda x: len(x.shape)), + ('ndimension', lambda x: len(x.shape)), + ('ndim', _ndim_), + ('__add__', + _binary_creator_('__add__', 'elementwise_add', False, _scalar_add_)), + # a+b == b+a. Do not need to reverse explicitly + ('__radd__', + _binary_creator_('__radd__', 'elementwise_add', False, _scalar_add_)), + ('__sub__', + _binary_creator_('__sub__', 'elementwise_sub', False, _scalar_sub_)), + ('__rsub__', + _binary_creator_('__rsub__', 'elementwise_sub', True, _scalar_rsub_)), + ('__mul__', + _binary_creator_('__mul__', 'elementwise_mul', False, _scalar_mul_)), + # a*b == b*a. Do not need to reverse explicitly + ('__rmul__', + _binary_creator_('__rmul__', 'elementwise_mul', False, _scalar_mul_)), + ('__div__', + _binary_creator_('__div__', 'elementwise_div', False, _scalar_div_)), + ('__truediv__', + _binary_creator_('__truediv__', 'elementwise_div', False, + _scalar_div_)), + ('__rdiv__', _binary_creator_('__rdiv__', 'elementwise_div', True, + None)), + ('__rtruediv__', + _binary_creator_('__rtruediv__', 'elementwise_div', True, None)), + ('__pow__', _binary_creator_('__pow__', 'elementwise_pow', False, + None)), + ('__rpow__', _binary_creator_('__rpow__', 'elementwise_pow', True, + None)), + ('__floordiv__', + _binary_creator_('__floordiv__', 'elementwise_floordiv', False, None)), + ('__mod__', _binary_creator_('__mod__', 'elementwise_mod', False, + None)), + ('__matmul__', _binary_creator_('__matmul__', "matmul_v2", False, + None)), + # for logical compare + ('__eq__', _binary_creator_('__eq__', 'equal', False, None)), + ('__ne__', _binary_creator_('__ne__', 'not_equal', False, None)), + ('__lt__', _binary_creator_('__lt__', 'less_than', False, None)), + ('__le__', _binary_creator_('__le__', 'less_equal', False, None)), + ('__gt__', _binary_creator_('__gt__', 'greater_than', False, None)), + ('__ge__', _binary_creator_('__ge__', 'greater_equal', False, None)), + ('values', values), + ('indices', indices), + ('to_dense', to_dense), + ] + + global _already_patch_variable + if not _already_patch_variable: + for method in variable_methods: + method_name = method[0] + method_impl = method[1] + setattr(Variable, method_name, method_impl) + else: + import paddle.tensor + for method_name in paddle.tensor.tensor_method_func: + if hasattr(Variable, method_name): continue + method_impl = getattr(paddle.tensor, method_name, None) + if method_impl: setattr(Variable, method_name, method_impl) + + for magic_method, origin_method in paddle.tensor.magic_method_func: + impl = getattr(paddle.tensor, origin_method, None) + if impl: setattr(Variable, magic_method, impl) + + _already_patch_variable = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/metric_op.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/metric_op.py new file mode 100644 index 0000000000000000000000000000000000000000..1df224ed05048261e17f4ca6885a7a36d62fe02c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/metric_op.py @@ -0,0 +1,323 @@ +# Copyright (c) 2018 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. +""" +All layers just related to metric. +""" + +from __future__ import print_function + +import warnings +from ..layer_helper import LayerHelper +from ..initializer import Normal, Constant +from ..framework import ( + Variable, + _non_static_mode, + _varbase_creator, + _in_legacy_dygraph, + in_dygraph_mode, +) +from .. import core +from ..param_attr import ParamAttr +from . import nn +from . import tensor +from ..data_feeder import check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['accuracy', 'auc'] + + +def accuracy(input, label, k=1, correct=None, total=None): + """ + + accuracy layer. + Refer to the https://en.wikipedia.org/wiki/Precision_and_recall + This function computes the accuracy using the input and label. + If the correct label occurs in top k predictions, then correct will increment by one. + + Note: + the dtype of accuracy is determined by input. the input and label dtype can be different. + + Args: + input(Tensor): The input of accuracy layer, which is the predictions of network. A Tensor with type float32,float64. + The shape is ``[sample_number, class_dim]`` . + label(Tensor): The label of dataset. Tensor with type int32,int64. The shape is ``[sample_number, 1]`` . + k(int, optional): The top k predictions for each class will be checked. Data type is int64 or int32. Default is 1. + correct(Tensor, optional): The correct predictions count. A Tensor with type int64 or int32. Default is None. + total(Tensor, optional): The total entries count. A tensor with type int64 or int32. Default is None. + + Returns: + Tensor, The correct rate. A Tensor with type float32. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.static as static + import paddle.nn.functional as F + paddle.enable_static() + data = static.data(name="input", shape=[-1, 32, 32], dtype="float32") + label = static.data(name="label", shape=[-1,1], dtype="int") + fc_out = static.nn.fc(x=data, size=10) + predict = F.softmax(x=fc_out) + result = static.accuracy(input=predict, label=label, k=5) + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + x = np.random.rand(3, 32, 32).astype("float32") + y = np.array([[1],[0],[1]]) + output= exe.run(feed={"input": x,"label": y}, + fetch_list=[result[0]]) + print(output) + #[array([0.], dtype=float32)] + + """ + if _non_static_mode(): + if correct is None: + correct = _varbase_creator(dtype="int32") + if total is None: + total = _varbase_creator(dtype="int32") + + _k = k.numpy().item(0) if isinstance(k, Variable) else k + topk_out, topk_indices = _legacy_C_ops.top_k_v2( + input, 'k', _k, 'sorted', False + ) + _acc, _, _ = _legacy_C_ops.accuracy( + topk_out, topk_indices, label, correct, total + ) + return _acc + + helper = LayerHelper("accuracy", **locals()) + check_variable_and_dtype( + input, 'input', ['float16', 'float32', 'float64'], 'accuracy' + ) + topk_out = helper.create_variable_for_type_inference(dtype=input.dtype) + topk_indices = helper.create_variable_for_type_inference(dtype="int64") + inputs = {"X": [input]} + if isinstance(k, Variable): + inputs['K'] = [k] + else: + attrs = {'k': k} + attrs['sorted'] = False + helper.append_op( + type="top_k_v2", + inputs=inputs, + attrs=attrs, + outputs={"Out": [topk_out], "Indices": [topk_indices]}, + ) + acc_out = helper.create_variable_for_type_inference(dtype="float32") + if correct is None: + correct = helper.create_variable_for_type_inference(dtype="int32") + if total is None: + total = helper.create_variable_for_type_inference(dtype="int32") + helper.append_op( + type="accuracy", + inputs={"Out": [topk_out], "Indices": [topk_indices], "Label": [label]}, + outputs={ + "Accuracy": [acc_out], + "Correct": [correct], + "Total": [total], + }, + ) + return acc_out + + +def auc( + input, + label, + curve='ROC', + num_thresholds=2**12 - 1, + topk=1, + slide_steps=1, + ins_tag_weight=None, +): + """ + **Area Under the Curve (AUC) Layer** + + This implementation computes the AUC according to forward output and label. + It is used very widely in binary classification evaluation. + + Note: If input label contains values other than 0 and 1, it will be cast + to `bool`. Find the relevant definitions `here `_. + + There are two types of possible curves: + + 1. ROC: Receiver operating characteristic; + 2. PR: Precision Recall + + Args: + input(Tensor): A floating-point 2D Tensor, values are in the range + [0, 1]. Each row is sorted in descending order. This + input should be the output of topk. Typically, this + Tensor indicates the probability of each label. + A Tensor with type float32,float64. + label(Tensor): A 2D int Tensor indicating the label of the training + data. The height is batch size and width is always 1. + A Tensor with type int32,int64. + curve(str): Curve type, can be 'ROC' or 'PR'. Default 'ROC'. + num_thresholds(int): The number of thresholds to use when discretizing + the roc curve. Default 4095. + topk(int): only topk number of prediction output will be used for auc. + slide_steps: when calc batch auc, we can not only use step currently but the previous steps can be used. slide_steps=1 means use the current step, slide_steps=3 means use current step and the previous second steps, slide_steps=0 use all of the steps. + ins_tag_weight(Tensor): A 2D int Tensor indicating the data's tag weight, 1 means real data, 0 means fake data. Default None, and it will be assigned to a tensor of value 1. + A Tensor with type float32,float64. + + Returns: + Tensor: A tuple representing the current AUC. + The return tuple is auc_out, batch_auc_out, [ + batch_stat_pos, batch_stat_neg, stat_pos, stat_neg ] + Data type is Tensor, supporting float32, float64. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + paddle.enable_static() + + data = paddle.static.data(name="input", shape=[-1, 32,32], dtype="float32") + label = paddle.static.data(name="label", shape=[-1], dtype="int") + fc_out = paddle.static.nn.fc(x=data, size=2) + predict = paddle.nn.functional.softmax(x=fc_out) + result=paddle.static.auc(input=predict, label=label) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + + exe.run(paddle.static.default_startup_program()) + x = np.random.rand(3,32,32).astype("float32") + y = np.array([1,0,1]) + output= exe.run(feed={"input": x,"label": y}, + fetch_list=[result[0]]) + print(output) + + #you can learn the usage of ins_tag_weight by the following code. + ''' + import paddle + import numpy as np + paddle.enable_static() + + data = paddle.static.data(name="input", shape=[-1, 32,32], dtype="float32") + label = paddle.static.data(name="label", shape=[-1], dtype="int") + ins_tag_weight = paddle.static.data(name='ins_tag', shape=[-1,16], lod_level=0, dtype='float64') + fc_out = paddle.static.nn.fc(x=data, size=2) + predict = paddle.nn.functional.softmax(x=fc_out) + result=paddle.static.auc(input=predict, label=label, ins_tag_weight=ins_tag_weight) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + + exe.run(paddle.static.default_startup_program()) + x = np.random.rand(3,32,32).astype("float32") + y = np.array([1,0,1]) + z = np.array([1,0,1]) + output= exe.run(feed={"input": x,"label": y, "ins_tag_weight":z}, + fetch_list=[result[0]]) + print(output) + ''' + + """ + helper = LayerHelper("auc", **locals()) + + if ins_tag_weight is None: + ins_tag_weight = tensor.fill_constant( + shape=[1, 1], dtype="float32", value=1.0 + ) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'auc') + check_variable_and_dtype(label, 'label', ['int32', 'int64'], 'auc') + check_variable_and_dtype( + ins_tag_weight, 'ins_tag_weight', ['float32', 'float64'], 'auc' + ) + auc_out = helper.create_variable_for_type_inference(dtype="float64") + batch_auc_out = helper.create_variable_for_type_inference(dtype="float64") + # make tp, tn, fp, fn persistable, so that can accumulate all batches. + + # for batch auc + # we create slide_step+1 buckets, the first slide_steps buckets store + # historical batch-level values, and the last bucket stores the sum values of + # previous slide_step buckets. + # The index of bucket that the newest batch will use is determined by batch_id mod slide_steps, + # and batch_id is store in the last posision of following variable + batch_stat_pos = helper.create_global_variable( + persistable=True, + dtype='int64', + shape=[(1 + slide_steps) * (num_thresholds + 1) + 1], + ) + batch_stat_neg = helper.create_global_variable( + persistable=True, + dtype='int64', + shape=[(1 + slide_steps) * (num_thresholds + 1) + 1], + ) + + # for global auc + # Needn't maintain the batch id + stat_pos = helper.create_global_variable( + persistable=True, dtype='int64', shape=[1, num_thresholds + 1] + ) + stat_neg = helper.create_global_variable( + persistable=True, dtype='int64', shape=[1, num_thresholds + 1] + ) + + for var in [batch_stat_pos, batch_stat_neg, stat_pos, stat_neg]: + helper.set_variable_initializer( + var, Constant(value=0.0, force_cpu=False) + ) + + # "InsTagWeight": [ins_tag_weight] + # Batch AUC + helper.append_op( + type="auc", + inputs={ + "Predict": [input], + "Label": [label], + "StatPos": [batch_stat_pos], + "StatNeg": [batch_stat_neg], + }, + attrs={ + "curve": curve, + "num_thresholds": num_thresholds, + "slide_steps": slide_steps, + }, + outputs={ + "AUC": [batch_auc_out], + "StatPosOut": [batch_stat_pos], + "StatNegOut": [batch_stat_neg], + }, + ) + # Global AUC + helper.append_op( + type="auc", + inputs={ + "Predict": [input], + "Label": [label], + "StatPos": [stat_pos], + "StatNeg": [stat_neg], + }, + attrs={ + "curve": curve, + "num_thresholds": num_thresholds, + "slide_steps": 0, + }, + outputs={ + "AUC": [auc_out], + "StatPosOut": [stat_pos], + "StatNegOut": [stat_neg], + }, + ) + return ( + auc_out, + batch_auc_out, + [batch_stat_pos, batch_stat_neg, stat_pos, stat_neg], + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/nn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..49180f8c9670fb648257edaace136fead6c66a8c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/nn.py @@ -0,0 +1,16659 @@ +# Copyright (c) 2018 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. +""" +All layers just related to the neural network. +""" +from __future__ import print_function + +import os +import inspect +import warnings + +import numpy as np +import six + +import paddle +from ..layer_helper import LayerHelper +from paddle.fluid.framework import _in_legacy_dygraph +from ..initializer import Normal, Constant, NumpyArrayInitializer +from ..framework import ( + Variable, + OpProtoHolder, + _non_static_mode, + dygraph_only, + _dygraph_tracer, + default_main_program, + _varbase_creator, + static_only, + _global_flags, + _in_legacy_dygraph, + in_dygraph_mode, +) +from ..framework import _current_expected_place +from .. import dygraph_utils +from ..param_attr import ParamAttr +from .layer_function_generator import ( + autodoc, + templatedoc, + _generate_doc_string_, +) +from .tensor import concat, assign, fill_constant, zeros, tensor_array_to_tensor +from . import utils +from .. import unique_name +from functools import reduce +from .. import core +from ...utils import deprecated +from ..data_feeder import ( + convert_dtype, + check_variable_and_dtype, + check_type, + check_dtype, +) +import paddle +from paddle.utils import deprecated +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'fc', + 'embedding', + 'linear_chain_crf', + 'crf_decoding', + 'cos_sim', + 'chunk_eval', + 'conv2d', + 'conv3d', + 'softmax', + 'pool2d', + 'pool3d', + 'adaptive_pool2d', + 'adaptive_pool3d', + 'batch_norm', + 'inplace_abn', + 'instance_norm', + 'data_norm', + 'conv2d_transpose', + 'conv3d_transpose', + 'reduce_sum', + 'reduce_mean', + 'reduce_max', + 'reduce_min', + 'reduce_prod', + 'reduce_all', + 'reduce_any', + 'dropout', + 'split', + 'ctc_greedy_decoder', + 'l2_normalize', + 'matmul', + 'topk', + 'transpose', + 'im2sequence', + 'row_conv', + 'multiplex', + 'layer_norm', + 'group_norm', + 'spectral_norm', + 'smooth_l1', + 'one_hot', + 'autoincreased_step_counter', + 'reshape', + 'squeeze', + 'unsqueeze', + 'lod_reset', + 'lod_append', + 'lrn', + 'pad', + 'pad_constant_like', + 'label_smooth', + 'roi_pool', + 'roi_align', + 'dice_loss', + 'image_resize', + 'image_resize_short', + 'resize_linear', + 'resize_bilinear', + 'resize_trilinear', + 'resize_nearest', + 'gather', + 'gather_nd', + 'scatter', + 'scatter_nd_add', + 'scatter_nd', + 'random_crop', + 'mean_iou', + 'relu', + 'selu', + 'log', + 'crop', + 'crop_tensor', + 'elu', + 'relu6', + 'pow', + 'stanh', + 'hard_sigmoid', + 'swish', + 'prelu', + 'brelu', + 'leaky_relu', + 'soft_relu', + 'flatten', + 'stack', + 'pad2d', + 'unstack', + 'unique', + 'unique_with_counts', + 'expand', + 'expand_as', + 'scale', + 'elementwise_add', + 'elementwise_div', + 'elementwise_sub', + 'elementwise_mul', + 'elementwise_max', + 'elementwise_min', + 'elementwise_pow', + 'elementwise_mod', + 'elementwise_floordiv', + 'uniform_random_batch_size_like', + 'gaussian_random', + 'sampling_id', + 'gaussian_random_batch_size_like', + 'sum', + 'slice', + 'strided_slice', + 'shape', + 'rank', + 'size', + 'logical_and', + 'logical_or', + 'logical_xor', + 'logical_not', + 'clip', + 'clip_by_norm', + 'mean', + 'mul', + 'maxout', + 'space_to_depth', + 'affine_grid', + 'affine_channel', + 'similarity_focus', + 'hash', + 'grid_sampler', + 'log_loss', + 'add_position_encoding', + 'bilinear_tensor_product', + 'merge_selected_rows', + 'get_tensor_from_selected_rows', + 'shuffle_channel', + 'temporal_shift', + 'py_func', + 'psroi_pool', + 'prroi_pool', + 'pixel_shuffle', + 'fsp_matrix', + 'continuous_value_model', + 'where', + 'sign', + 'deformable_conv', + 'unfold', + 'deformable_roi_pooling', + 'filter_by_instag', + 'shard_index', + 'hard_swish', + 'mish', + 'gather_tree', + 'uniform_random', + 'unbind', +] + +OP_NAMEMAPPING = { + 'elementwise_max': 'maximum', + 'elementwise_min': 'minimum', + 'elementwise_pow': 'elementwise_pow', + 'elementwise_floordiv': 'floor_divide', + 'elementwise_add': 'add', + 'elementwise_sub': 'subtract', + 'elementwise_mul': 'multiply', + 'elementwise_div': 'divide', + 'elementwise_mod': 'remainder', +} + + +@dygraph_only +def _elementwise_op_in_dygraph( + x, y, axis=-1, act=None, use_mkldnn=False, op_name=None +): + def is_inplace(op_name): + return op_name[-1] == "_" + + if op_name not in OP_NAMEMAPPING.keys() or axis != -1: + op = getattr(_legacy_C_ops, op_name) + out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) + else: + if in_dygraph_mode(): + op = getattr( + _C_ops, + OP_NAMEMAPPING[op_name] if not is_inplace(op_name) else op_name, + ) + out = op(x, y) + + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, op_name) + out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) + return dygraph_utils._append_activation_in_dygraph( + out, act, use_mkldnn=use_mkldnn + ) + + +def fc( + input, + size, + num_flatten_dims=1, + param_attr=None, + bias_attr=None, + act=None, + name=None, +): + r""" + :api_attr: Static Graph + + **Fully Connected Layer** + + This operator creates a fully connected layer in the network. It can take + a Tensor(or LoDTensor) or a list of Tensor(or LoDTensor) as its inputs(see + Args in detail). It creates a variable called weight for each input Tensor, + which represents a fully connected weight matrix from each input unit to + each output unit. The fully connected layer multiplies each input Tensor + with its corresponding weight to produce an output Tensor with shape :math:`[M, size]` , + where M is batch size. If a list of Tensor is given, the results of + multiple output Tensors with shape :math:`[M, size]` will be summed up. If :attr:`bias_attr` + is not None, a bias variable will be created and added to the output. + Finally, if :attr:`act` is not None, it will be applied to the output as well. + + When the input is a single Tensor(or LoDTensor): + + .. math:: + + Out = Act({XW + b}) + + When the input is a list of Tensor(or LoDTensor): + + .. math:: + + Out = Act({\sum_{i=0}^{N-1}X_iW_i + b}) + + In the above equation: + + * :math:`N`: Number of the input. N equals to len(input) if input is list of Variable. + * :math:`X_i`: The i-th input tensor. + * :math:`W_i`: The i-th weights matrix corresponding i-th input tensor. + * :math:`b`: The bias parameter created by this layer (if needed). + * :math:`Act`: The activation function. + * :math:`Out`: The output Tensor. + + .. code-block:: text + + Case 1: + Given a single Tensor data_1, and num_flatten_dims = 2: + data_1.data = [[[0.1, 0.2], + [0.3, 0.4]]] + data_1.shape = (1, 2, 2) # 1 is batch_size + + out = fluid.layers.fc(input=data_1, size=1, num_flatten_dims=2) + + Then output is: + out.data = [[0.83234344], [0.34936576]] + out.shape = (1, 2, 1) + + Case 2: + Given a list of Tensor: + data_1.data = [[[0.1, 0.2], + [0.3, 0.4]]] + data_1.shape = (1, 2, 2) # 1 is batch_size + + data_2 = [[[0.1, 0.2, 0.3]]] + data_2.shape = (1, 1, 3) + + out = fluid.layers.fc(input=[data_1, data_2], size=2) + + Then: + out.data = [[0.18669507, 0.1893476]] + out.shape = (1, 2) + + Args: + input (Variable|list of Variable): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` or + a list of Tensor(or LoDTensor). The dimensions of the input Tensor is at least 2 and the data + type should be float32 or float64. + size(int): The number of output units in this layer, which also means the feature size of output + Tensor(or LoDTensor). + num_flatten_dims (int): The fc layer can accept an input Tensor with more than + two dimensions. If this happens, the multidimensional tensor will first be flattened + into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input + Tensor is flattened: the first :attr:`num_flatten_dims` (inclusive, index starts from 1) + dimensions will be flatten to form the first dimension of the final matrix (height of + the matrix), and the rest :math:`rank(X) - num\_flatten\_dims` dimensions are flattened to + form the second dimension of the final matrix (width of the matrix). For example, assuming that + X is a 5-dimensional Tensor with a shape [2, 3, 4, 5, 6], and :attr:`num_flatten_dims` = 3. + Then, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default: 1. + param_attr (ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr): To specify the bias parameter property. Default: None, which means the + default bias parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . + act (str): Activation to be applied to the output of this layer, such as tanh, softmax, + sigmoid, relu. For more information, please refer to :ref:`api_guide_activations_en` . Default: None. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: Tensor or LoDTensor calculated by fc layer. The data type is same with input. + + Raises: + ValueError: If dimensions of the input Tensor is less than 2. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # when input is single tensor + data = fluid.data(name="data", shape=[-1, 32], dtype="float32") + fc = fluid.layers.fc(input=data, size=1000, act="tanh") + + # when input are multiple tensors + data_1 = fluid.data(name="data_1", shape=[-1, 32], dtype="float32") + data_2 = fluid.data(name="data_2", shape=[-1, 36], dtype="float32") + fc = fluid.layers.fc(input=[data_1, data_2], size=1000, act="tanh") + """ + helper = LayerHelper("fc", **locals()) + check_type(input, 'input', (list, tuple, Variable), 'fc') + if isinstance(input, (list, tuple)): + for i, input_x in enumerate(input): + check_type(input_x, 'input[' + str(i) + ']', Variable, 'fc') + dtype = helper.input_dtype() + check_dtype( + dtype, 'input', ['float16', 'uint16', 'float32', 'float64'], 'fc' + ) + mul_results = [] + for input_var, param_attr in helper.iter_inputs_and_params(): + input_shape = input_var.shape + if num_flatten_dims == -1: + num_flatten_dims = len(input_shape) - 1 + param_shape = [ + reduce(lambda a, b: a * b, input_shape[num_flatten_dims:], 1) + ] + [size] + + w = helper.create_parameter( + attr=param_attr, shape=param_shape, dtype=dtype, is_bias=False + ) + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="mul", + inputs={"X": input_var, "Y": w}, + outputs={"Out": tmp}, + attrs={"x_num_col_dims": num_flatten_dims, "y_num_col_dims": 1}, + ) + mul_results.append(tmp) + + if len(mul_results) == 1: + pre_bias = mul_results[0] + else: + pre_bias = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="sum", + inputs={"X": mul_results}, + outputs={"Out": pre_bias}, + attrs={"use_mkldnn": False}, + ) + # add bias + pre_activation = helper.append_bias_op(pre_bias, dim_start=num_flatten_dims) + # add activation + return helper.append_activation(pre_activation) + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.embedding") +def embedding( + input, + size, + is_sparse=False, + is_distributed=False, + padding_idx=None, + param_attr=None, + dtype='float32', +): + r""" + :api_attr: Static Graph + + **WARING:** This OP will be deprecated in a future release. This OP requires the + last dimension of Tensor shape must be equal to 1. It is recommended to use + fluid. :ref:`api_fluid_embedding` . + + The operator is used to lookup embeddings vector of ids provided by :attr:`input` . + It automatically constructs a 2D embedding matrix based on the + input :attr:`size` (vocab_size, emb_size) and :attr:`dtype` . + + This OP requires the last dimension of Tensor shape must be equal to 1. The shape + of output Tensor is generated by replacing the last dimension of the input Tensor shape + with emb_size. + + **Note:** The id in :attr:`input` must satisfy :math:`0 =< id < size[0]` , + otherwise the program will throw an exception and exit. + + .. code-block:: text + + Case 1: + + input is a Tensor. padding_idx = -1 + input.data = [[[1], [3]], [[2], [4]], [[4], [127]]] + input.shape = [3, 2, 1] + Given size = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when ids is 127. + + Case 2: + + input is a LoDTensor with 1-level LoD. padding_idx = 0 + input.lod = [[2, 3]] + input.data = [[1], [3], [2], [4], [0]] + input.shape = [5, 1] + Given size = [128, 16] + output is a LoDTensor: + out.lod = [[2, 3]] + out.shape = [5, 16] + out.data = [[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654], + [0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]] # padding data + It will pad all-zero data when ids is 0. + + Args: + input(Variable): A Tensor or LoDTensor with type int64, which contains the id information. + The last dimension of Tensor shape must be equal to 1. The value of the input id should + satisfy :math:`0<= id < size[0]` . + size(tuple|list): The shape of lookup table parameter. It should have two elements which + indicates the size of the dictionary of embeddings and the size of each embedding vector respectively. + is_sparse(bool): The flag indicating whether to use sparse update. This parameter only + affects the performance of the backwards gradient update. It is recommended to set + True because sparse update is faster. But some optimizer does not support sparse update, + such as :ref:`api_fluid_optimizer_AdadeltaOptimizer` , :ref:`api_fluid_optimizer_AdamaxOptimizer` , + :ref:`api_fluid_optimizer_DecayedAdagradOptimizer` , :ref:`api_fluid_optimizer_FtrlOptimizer` , + :ref:`api_fluid_optimizer_LambOptimizer` and :ref:`api_fluid_optimizer_LarsMomentumOptimizer` . + In these case, is_sparse must be False. Default: False. + is_distributed(bool): Whether to store the embedding matrix in a distributed manner. Only used + in multi-machine distributed CPU training. Default: False. + padding_idx(int|long|None): padding_idx needs to be in the interval [-vocab_size, vocab_size). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup + encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. + If set None, it makes no effect to output. Default: None. + param_attr(ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . In addition, + user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. + The local word vector needs to be transformed into numpy format, and the shape of local word + vector should be consistent with :attr:`size` . Then :ref:`api_fluid_initializer_NumpyArrayInitializer` + is used to load custom or pre-trained word vectors. See code example 2 for details. + dtype(str|core.VarDesc.VarType): It refers to the data type of output Tensor. + It must be float32 or float64. Default: float32. + + Returns: + Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + data = fluid.data(name='x', shape=[None, 1], dtype='int64') + + # example 1 + emb_1 = fluid.embedding(input=data, size=[128, 64]) + + # example 2: load custom or pre-trained word vectors + weight_data = np.random.random(size=(128, 100)) # word vectors with numpy format + w_param_attrs = fluid.ParamAttr( + name="emb_weight", + learning_rate=0.5, + initializer=fluid.initializer.NumpyArrayInitializer(weight_data), + trainable=True) + emb_2 = fluid.layers.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32') + """ + + helper = LayerHelper('embedding', **locals()) + check_variable_and_dtype( + input, 'input', ['int64'], 'fluid.layers.embedding' + ) + check_dtype( + dtype, + 'dtype', + ['uint16', 'float16', 'float32', 'float64'], + 'fluid.layers.embedding', + ) + + if is_distributed: + is_distributed = False + warnings.warn( + "is_distributed is go out of use, `fluid.contrib.layers.sparse_embedding` is your needed" + ) + + remote_prefetch = True if is_sparse else False + + w = helper.create_parameter( + attr=helper.param_attr, shape=size, dtype=dtype, is_bias=False + ) + tmp = helper.create_variable_for_type_inference(dtype) + padding_idx = ( + -1 + if padding_idx is None + else padding_idx + if padding_idx >= 0 + else (size[0] + padding_idx) + ) + helper.append_op( + type='lookup_table', + inputs={'Ids': input, 'W': w}, + outputs={'Out': tmp}, + attrs={ + 'is_sparse': is_sparse, + 'is_distributed': is_distributed, + 'remote_prefetch': remote_prefetch, + 'padding_idx': padding_idx, + }, + ) + return tmp + + +def _pull_sparse( + input, + size, + table_id, + accessor_class, + name="embedding", + ctr_label_name="", + padding_id=0, + dtype='float32', + scale_sparse_grad=True, +): + r""" + **Pull Fleet Sparse Layer** + + This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in + Fleet lookup table. The result of this lookup is the embedding of each ID in the + :attr:`input`. + + Args: + input(Variable|list of Variable): Input is a Tensor Variable, which + contains the IDs information. + size(int): The embedding size parameter, which indicates the size of + each embedding vector respectively. + table_id(int): the fleet table id of this embedding. + accessor_class(str): the pslib accessor of the table, default is DownpourCtrAccessor. + ctr_label_name(str): the layer name of click. + padding_id(int): the padding id during lookup, default is 0. + dtype(str): The dtype refers to the data type of output tensor. Only supports + float32 now. + scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default + is True. + + Returns: + Variable|list of Variable: The tensor variable storing the embeddings of the \ + supplied inputs. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + emb = fluid.layers.nn._pull_sparse( + input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor") + """ + helper = LayerHelper(name, **locals()) + inputs = helper.multiple_input() + outs = [helper.create_variable_for_type_inference(dtype)] + input_names = [i.name for i in inputs] + attrs = { + 'EmbeddingDim': size, + 'TableId': table_id, + 'AccessorClass': accessor_class, + 'CtrLabelName': ctr_label_name, + 'PaddingId': padding_id, + 'ScaleSparseGrad': scale_sparse_grad, + 'InputNames': input_names, + # this is only for compatible with embedding op + 'is_distributed': True, + } + # this is only for compatible with embedding op + w, _ = helper.create_or_get_global_variable( + name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True + ) + helper.append_op( + type='pull_sparse', + inputs={'Ids': inputs, 'W': w}, + outputs={'Out': outs}, + attrs=attrs, + ) + if len(outs) == 1: + return outs[0] + return outs + + +def _pull_sparse_v2( + input, + size, + table_id, + accessor_class, + name="embedding", + ctr_label_name="", + padding_id=0, + dtype='float32', + scale_sparse_grad=True, +): + r""" + **Pull Fleet Sparse Layer** + + This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in + Fleet lookup table. The result of this lookup is the embedding of each ID in the + :attr:`input`. + + Args: + input(Variable|list of Variable): Input is a Tensor Variable, which + contains the IDs information. + size(int): The embedding size parameter, which indicates the size of + each embedding vector respectively. + table_id(int): the pslib table id of this embedding. + accessor_class(str): the fleet accessor of the table, default is DownpourCtrAccessor. + ctr_label_name(str): the layer name of click. + padding_id(int): the padding id during lookup, default is 0. + dtype(str): The dtype refers to the data type of output tensor. Only supports + float32 now. + scale_sparse_grad(bool): whether to scale sparse gradient with batch size. default + is True. + + Returns: + Variable|list of Variable: The tensor variable storing the embeddings of the \ + supplied inputs. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + emb = fluid.layers.nn._pull_sparse_v2( + input=data, size=11, table_id=0, accessor_class="DownpourCtrAccessor") + """ + helper = LayerHelper(name, **locals()) + inputs = helper.multiple_input() + outs = [helper.create_variable_for_type_inference(dtype)] + input_names = [i.name for i in inputs] + attrs = { + 'EmbeddingDim': size, + 'TableId': table_id, + 'AccessorClass': accessor_class, + 'CtrLabelName': ctr_label_name, + 'PaddingId': padding_id, + 'ScaleSparseGrad': scale_sparse_grad, + 'InputNames': input_names, + # this is only for compatible with embedding op + 'is_distributed': True, + } + # this is only for compatible with embedding op + w, _ = helper.create_or_get_global_variable( + name=name, shape=[size], dtype=dtype, is_bias=False, persistable=True + ) + helper.append_op( + type='pull_sparse_v2', + inputs={'Ids': inputs, 'W': w}, + outputs={'Out': outs}, + attrs=attrs, + ) + if len(outs) == 1: + return outs[0] + return outs + + +def _pull_gpups_sparse( + input, size, dtype='float32', is_distributed=False, is_sparse=False +): + r""" + **Pull GpuPS Sparse Layer** + + This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in + GpuPS lookup table. The result of this lookup is the embedding of each ID in the + :attr:`input`. + + Args: + input(Variable|list of Variable): Input is a Tensor Variable, which + contains the IDs information. + size(int|list of int): The embedding size parameter of each input, which indicates the size of + each embedding vector respectively. + dtype(str): The dtype refers to the data type of output tensor. Only supports + float32 now. + + Returns: + Variable|list of Variable: The tensor variable storing the embeddings of the \ + supplied inputs, whose size are indicated by size respectively. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + slots = [] + data_1 = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + slots.append(data_1) + data_2 = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + slots.append(data_2) + embs = fluid.layers.pull_gpups_sparse(input=slots, size=[11, 35]) + """ + helper = LayerHelper('pull_gpups_sparse', **locals()) + if dtype != 'float32': + raise ValueError( + "GpuPS only support float type embedding now, and your type is: " + + dtype + ) + helper.input_dtype() + inputs = helper.multiple_input() + outs = [ + helper.create_variable_for_type_inference(dtype) + for i in range(len(inputs)) + ] + w = helper.create_parameter( + attr=helper.param_attr, shape=[size[0]], dtype=dtype, is_bias=False + ) + helper.append_op( + type='pull_gpups_sparse', + inputs={'Ids': inputs, 'W': w}, + outputs={'Out': outs}, + attrs={ + 'size': size, + 'is_distributed': is_distributed, + 'is_sparse': is_sparse, + }, + ) + if len(outs) == 1: + return outs[0] + return outs + + +def _pull_box_sparse( + input, size, dtype='float32', is_distributed=False, is_sparse=False +): + r""" + **Pull Box Sparse Layer** + + This layer is used to lookup embeddings of IDs, provided by :attr:`input`, in + BoxPS lookup table. The result of this lookup is the embedding of each ID in the + :attr:`input`. + + Args: + input(Variable|list of Variable): Input is a Tensor Variable, which + contains the IDs information. + size(int): The embedding size parameter, which indicates the size of + each embedding vector respectively. + dtype(str): The dtype refers to the data type of output tensor. Only supports + float32 now. + + Returns: + Variable|list of Variable: The tensor variable storing the embeddings of the \ + supplied inputs. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.data(name='sequence', shape=[1], dtype='int64', lod_level=1) + emb = fluid.layers.pull_box_sparse(input=data, size=[11]) + """ + helper = LayerHelper('pull_box_sparse', **locals()) + if dtype != 'float32': + raise ValueError( + "BoxPS only support float type embedding now, and your type is: " + + dtype + ) + helper.input_dtype() + inputs = helper.multiple_input() + outs = [ + helper.create_variable_for_type_inference(dtype) + for i in range(len(inputs)) + ] + w = helper.create_parameter( + attr=helper.param_attr, shape=[size], dtype=dtype, is_bias=False + ) + helper.append_op( + type='pull_box_sparse', + inputs={'Ids': inputs, 'W': w}, + outputs={'Out': outs}, + attrs={ + 'size': size, + 'is_distributed': is_distributed, + 'is_sparse': is_sparse, + }, + ) + if len(outs) == 1: + return outs[0] + return outs + + +@templatedoc() +def linear_chain_crf(input, label, param_attr=None, length=None): + """ + :api_attr: Static Graph + + Linear Chain CRF. + + ${comment} + + Args: + input(${emission_type}): ${emission_comment} + label(${label_type}): ${label_comment} + Length(${length_type}): ${length_comment} + param_attr(ParamAttr): The attribute of the learnable parameter for transition parameter. + + Returns: + output(${emission_exps_type}): ${emission_exps_comment} \n + output(${transition_exps_type}): ${transition_exps_comment} \n + output(${log_likelihood_type}): ${log_likelihood_comment} \n + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + #define net structure, using LodTensor + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + input_data = fluid.data(name='input_data', shape=[-1,10], dtype='float32') + label = fluid.data(name='label', shape=[-1,1], dtype='int') + emission= fluid.layers.fc(input=input_data, size=10, act="tanh") + crf_cost = fluid.layers.linear_chain_crf( + input=emission, + label=label, + param_attr=fluid.ParamAttr( + name='crfw', + learning_rate=0.01)) + use_cuda = False + place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(startup_program) + #define data, using LoDTensor + a = fluid.create_lod_tensor(np.random.rand(12,10).astype('float32'), [[3,3,4,2]], place) + b = fluid.create_lod_tensor(np.array([[1],[1],[2],[3],[1],[1],[1],[3],[1],[1],[1],[1]]),[[3,3,4,2]] , place) + feed1 = {'input_data':a,'label':b} + loss= exe.run(train_program,feed=feed1, fetch_list=[crf_cost]) + print(loss) + + #define net structure, using padding + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + input_data2 = fluid.data(name='input_data2', shape=[-1,10,10], dtype='float32') + label2 = fluid.data(name='label2', shape=[-1,10,1], dtype='int') + label_length = fluid.data(name='length', shape=[-1,1], dtype='int') + emission2= fluid.layers.fc(input=input_data2, size=10, act="tanh", num_flatten_dims=2) + crf_cost2 = fluid.layers.linear_chain_crf( + input=emission2, + label=label2, + length=label_length, + param_attr=fluid.ParamAttr( + name='crfw', + learning_rate=0.01)) + + use_cuda = False + place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(startup_program) + + #define data, using padding + cc=np.random.rand(4,10,10).astype('float32') + dd=np.random.rand(4,10,1).astype('int64') + ll=np.array([[3],[3],[4],[2]]) + feed2 = {'input_data2':cc,'label2':dd,'length':ll} + loss2= exe.run(train_program,feed=feed2, fetch_list=[crf_cost2]) + print(loss2) + #[array([[ 7.8902354], + # [ 7.3602567], + # [ 10.004011], + # [ 5.86721 ]], dtype=float32)] + + #you can use find_var to get transition parameter. + transition=np.array(fluid.global_scope().find_var('crfw').get_tensor()) + print(transition) + + """ + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'linear_chain_crf' + ) + check_variable_and_dtype(label, 'label', ['int64'], 'linear_chain_crf') + helper = LayerHelper('linear_chain_crf', **locals()) + size = input.shape[2] if length else input.shape[1] + transition = helper.create_parameter( + attr=helper.param_attr, + shape=[size + 2, size], + dtype=helper.input_dtype(), + ) + alpha = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + emission_exps = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + transition_exps = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + log_likelihood = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + this_inputs = { + "Emission": [input], + "Transition": transition, + "Label": [label], + } + if length: + this_inputs['Length'] = [length] + helper.append_op( + type='linear_chain_crf', + inputs=this_inputs, + outputs={ + "Alpha": [alpha], + "EmissionExps": [emission_exps], + "TransitionExps": transition_exps, + "LogLikelihood": log_likelihood, + }, + ) + + return log_likelihood + + +@templatedoc() +def crf_decoding(input, param_attr, label=None, length=None): + """ + :api_attr: Static Graph + + ${comment} + + Args: + input(Tensor): ${emission_comment} + + param_attr (ParamAttr|None): To specify the weight parameter attribute. + Default: None, which means the default weight parameter property is + used. See usage for details in :ref:`api_paddle_fluid_param_attr_ParamAttr` . + + label(${label_type}, optional): ${label_comment} + + length(${length_type}, optional): ${length_comment} + + Returns: + Tensor: ${viterbi_path_comment} + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + # LoDTensor-based example + num_labels = 10 + feature = paddle.static.data(name='word_emb', shape=[-1, 784], dtype='float32', lod_level=1) + label = paddle.static.data(name='label', shape=[-1, 1], dtype='int64', lod_level=1) + emission = paddle.static.nn.fc(feature, size=num_labels) + + crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label, + param_attr=paddle.ParamAttr(name="crfw")) + crf_decode = paddle.static.nn.crf_decoding(input=emission, + param_attr=paddle.ParamAttr(name="crfw")) + + # Common tensor example + num_labels, max_len = 10, 20 + feature = paddle.static.data(name='word_emb_pad', shape=[-1, max_len, 784], dtype='float32') + label = paddle.static.data(name='label_pad', shape=[-1, max_len, 1], dtype='int64') + length = paddle.static.data(name='length', shape=[-1, 1], dtype='int64') + emission = paddle.static.nn.fc(feature, size=num_labels, + num_flatten_dims=2) + + crf_cost = paddle.fluid.layers.linear_chain_crf(input=emission, label=label, length=length, + param_attr=paddle.ParamAttr(name="crfw_pad")) + crf_decode = paddle.static.nn.crf_decoding(input=emission, length=length, + param_attr=paddle.ParamAttr(name="crfw_pad")) + """ + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'crf_decoding' + ) + helper = LayerHelper('crf_decoding', **locals()) + transition = helper.get_parameter(param_attr.name) + viterbi_path = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.INT64 + ) + inputs = {"Emission": [input], "Transition": transition, "Label": label} + if length: + inputs['Length'] = length + helper.append_op( + type='crf_decoding', + inputs=inputs, + outputs={"ViterbiPath": [viterbi_path]}, + ) + + return viterbi_path + + +@templatedoc() +def cos_sim(X, Y): + """ + ${comment} + + Args: + X (Tensor): ${x_comment}. + Y (Tensor): ${y_comment}. + + Returns: + A Tensor representing the output of cosine(X, Y). + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand(shape=[3, 7], dtype='float32') + y = paddle.rand(shape=[1, 7], dtype='float32') + out = paddle.fluid.layers.cos_sim(x, y) + print(out) + + """ + check_variable_and_dtype(X, 'X', ['float32'], 'cos_sim') + check_variable_and_dtype(Y, 'Y', ['float32'], 'cos_sim') + helper = LayerHelper('cos_sim', **locals()) + out = helper.create_variable_for_type_inference(dtype=X.dtype) + xnorm = helper.create_variable_for_type_inference(dtype=X.dtype) + ynorm = helper.create_variable_for_type_inference(dtype=X.dtype) + helper.append_op( + type='cos_sim', + inputs={'X': [X], 'Y': [Y]}, + outputs={'Out': [out], 'XNorm': [xnorm], 'YNorm': [ynorm]}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.dropout") +def dropout( + x, + dropout_prob, + is_test=None, + seed=None, + name=None, + dropout_implementation="downgrade_in_infer", +): + """ + + Computes dropout. + + Drop or keep each element of `x` independently. Dropout is a regularization + technique for reducing overfitting by preventing neuron co-adaption during + training. The dropout operator randomly sets (according to the given dropout + probability) the outputs of some units to zero, while others are remain + unchanged. + + dropout op can be removed from the program to make the program more efficient. + + Args: + x (Variable): The input tensor variable. The data type is float16 or float32 or float64. + dropout_prob (float): Probability of setting units to zero. + is_test (bool): A flag indicating whether it is in test phrase or not. + Default None, in dynamic graph, it use global tracer mode; in static graph, it means False. + seed (int): A Python integer used to create random seeds. If this + parameter is set to None, a random seed is used. + NOTE: If an integer seed is given, always the same output + units will be dropped. DO NOT use a fixed seed in training.Default: None. + name (str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + dropout_implementation(string): ['downgrade_in_infer'(default)|'upscale_in_train'] + + 1. downgrade_in_infer(default), downgrade the outcome at inference + + - train: out = input * mask + - inference: out = input * (1.0 - dropout_prob) + + (mask is a tensor same shape with input, value is 0 or 1 + ratio of 0 is dropout_prob) + 2. upscale_in_train, upscale the outcome at training time + + - train: out = input * mask / ( 1.0 - dropout_prob ) + - inference: out = input + + (mask is a tensor same shape with input, value is 0 or 1 + ratio of 0 is dropout_prob) + + + Returns: + A Variable holding Tensor representing the dropout, has same shape and data type with `x`. + + Examples: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + x = fluid.data(name="data", shape=[None, 32, 32], dtype="float32") + dropped = fluid.layers.dropout(x, dropout_prob=0.5) + """ + if not isinstance(dropout_prob, (float, int, Variable)): + raise TypeError( + "dropout_prob argument should be a number(int|float) or Variable" + ) + # fast return for p == 0 + if isinstance(dropout_prob, (int, float)) and dropout_prob == 0: + return x + + if _non_static_mode(): + if ( + seed is None or seed == 0 + ) and default_main_program().random_seed != 0: + seed = default_main_program().random_seed + if is_test is None: + is_test = not _dygraph_tracer()._train_mode + out, mask = _legacy_C_ops.dropout( + x, + 'dropout_prob', + dropout_prob, + 'is_test', + is_test, + 'fix_seed', + seed is not None, + 'seed', + seed if seed is not None else 0, + 'dropout_implementation', + dropout_implementation, + ) + return out + + def get_attrs(prog, dropout_prob, is_test, seed): + if (seed is None or seed == 0) and prog.random_seed != 0: + seed = prog.random_seed + if isinstance(dropout_prob, Variable) and not dropout_prob.shape != [1]: + raise TypeError( + "Required dropout_prob.shape == [1] if type(dropout_prob) is Variable, but received dropout_prob.shape = {}".format( + dropout_prob.shape + ) + ) + attrs = { + 'dropout_prob': dropout_prob, + 'is_test': is_test, + 'fix_seed': seed is not None, + 'seed': seed if seed is not None else 0, + 'dropout_implementation': dropout_implementation, + } + return attrs + + helper = LayerHelper('dropout', **locals()) + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'dropout' + ) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + mask = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True + ) + + attrs = get_attrs(helper.main_program, dropout_prob, is_test, seed) + + helper.append_op( + type='dropout', + inputs={'X': [x]}, + outputs={'Out': [out], 'Mask': [mask]}, + attrs=attrs, + ) + return out + + +@templatedoc() +def chunk_eval( + input, + label, + chunk_scheme, + num_chunk_types, + excluded_chunk_types=None, + seq_length=None, +): + r""" + This operator computes the precision, recall and F1-score for chunk detection. + It is often used in sequence tagging tasks, such as Named Entity Recognition(NER). + + For some basics of chunking, please refer to + `Chunking with Support Vector Machines `_ . + + This operator supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes. + Here is a NER example for the usage of these tagging schemes: + + .. code-block:: python + + ====== ====== ====== ===== == ============ ===== ===== ===== == ========= + Li Ming works at Agricultural Bank of China in Beijing. + ====== ====== ====== ===== == ============ ===== ===== ===== == ========= + IO I-PER I-PER O O I-ORG I-ORG I-ORG I-ORG O I-LOC + IOB B-PER I-PER O O B-ORG I-ORG I-ORG I-ORG O B-LOC + IOE I-PER E-PER O O I-ORG I-ORG I-ORG E-ORG O E-LOC + IOBES B-PER E-PER O O I-ORG I-ORG I-ORG E-ORG O S-LOC + ====== ====== ====== ===== == ============ ===== ===== ===== == ========= + + There are three chunk types(named entity types) including PER(person), ORG(organization) + and LOC(location), and we can see that the labels have the form `-` . + + Since the implementation of this operator actually uses label ids rather than + label strings, to make it work, there should be a way to map label ids to + tag types and chunk types. This operator uses the following way to do mapping: + + .. code-block:: python + + tag_type = label % num_tag_type + chunk_type = label / num_tag_type + + where `num_tag_type` is the num of tag types in the tagging scheme, `num_chunk_type` + is the num of chunk types, and `tag_type` get its value from the following table. + + .. code-block:: python + + Scheme Begin Inside End Single + plain 0 - - - + IOB 0 1 - - + IOE - 0 1 - + IOBES 0 1 2 3 + + Accordingly, in the above NER example, if the tagging scheme is IOB and chunk + types are ORG, PER and LOC, then the label ids would be as follows: + + .. code-block:: python + + B-ORG 0 + I-ORG 1 + B-PER 2 + I-PER 3 + B-LOC 4 + I-LOC 5 + O 6 + + With which we can map each label id to the corresponding tag type and chunk + type correctly. + + Args: + input (Tensor): A Tensor representing the predicted labels + from the network. Its shape would be `[N, M, 1]`, + where `N` stands for batch size, `M` for sequence length. + The data type should be int64. + label (Tensor): A Tensor representing the ground-truth labels. + It should have the same shape, lod and data type as ``input`` . + chunk_scheme (str): Indicate the tagging schemes used here. The value must + be IOB, IOE, IOBES or plain. + num_chunk_types (int): The number of chunk types. + excluded_chunk_types (list, optional): Indicate the chunk types shouldn't + be taken into account. It should be a list of chunk type ids(integer). + Default None. + seq_length(Tensor, optional): A 1D Tensor containing the length of each + sequence when ``input`` and ``label`` are Tensor. Default None. + + Returns: + tuple: A tuple including precision, recall, F1-score, chunk number detected, \ + chunk number in ground-truth, chunk number correctly detected. Each \ + is a Tensor with shape `[1]`. The data type of precision, recall and \ + F1-score all is float32, and the others' data type all is int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + dict_size = 10000 + label_dict_len = 7 + sequence = fluid.data( + name='id', shape=[None, 1], lod_level=1, dtype='int64') + embedding = fluid.embedding( + input=sequence, size=[dict_size, 512]) + hidden = fluid.layers.fc(input=embedding, size=512) + label = fluid.data( + name='label', shape=[None, 1], lod_level=1, dtype='int64') + crf = fluid.layers.linear_chain_crf( + input=hidden, label=label, param_attr=fluid.ParamAttr(name="crfw")) + crf_decode = fluid.layers.crf_decoding( + input=hidden, param_attr=fluid.ParamAttr(name="crfw")) + fluid.layers.chunk_eval( + input=crf_decode, + label=label, + chunk_scheme="IOB", + num_chunk_types=int((label_dict_len - 1) / 2)) + """ + helper = LayerHelper("chunk_eval", **locals()) + + check_variable_and_dtype(input, 'input', ['int64'], 'chunk_eval') + check_variable_and_dtype(label, 'label', ['int64'], 'chunk_eval') + + # prepare output + precision = helper.create_variable_for_type_inference(dtype="float32") + recall = helper.create_variable_for_type_inference(dtype="float32") + f1_score = helper.create_variable_for_type_inference(dtype="float32") + num_infer_chunks = helper.create_variable_for_type_inference(dtype="int64") + num_label_chunks = helper.create_variable_for_type_inference(dtype="int64") + num_correct_chunks = helper.create_variable_for_type_inference( + dtype="int64" + ) + + this_input = {"Inference": [input], "Label": [label]} + + if seq_length is not None: + this_input["SeqLength"] = [seq_length] + + helper.append_op( + type="chunk_eval", + inputs=this_input, + outputs={ + "Precision": [precision], + "Recall": [recall], + "F1-Score": [f1_score], + "NumInferChunks": [num_infer_chunks], + "NumLabelChunks": [num_label_chunks], + "NumCorrectChunks": [num_correct_chunks], + }, + attrs={ + "num_chunk_types": num_chunk_types, + "chunk_scheme": chunk_scheme, + "excluded_chunk_types": excluded_chunk_types or [], + }, + ) + return ( + precision, + recall, + f1_score, + num_infer_chunks, + num_label_chunks, + num_correct_chunks, + ) + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.softmax") +def softmax(input, use_cudnn=True, name=None, axis=-1): + r""" + This operator implements the softmax layer. The calculation process is as follows: + + 1. The dimension :attr:`axis` of the ``input`` will be permuted to the last. + + 2. Then the input tensor will be logically flattened to a 2-D matrix. The matrix's + second dimension(row length) is the same as the dimension :attr:`axis` of the input + tensor, and the first dimension(column length) is the product of all other + dimensions of the input tensor. For each row of the matrix, the softmax operator + squashes the K-dimensional(K is the width of the matrix, which is also the size + of the input tensor's dimension :attr:`axis`) vector of arbitrary real values to a + K-dimensional vector of real values in the range [0, 1] that add up to 1. + + 3. After the softmax operation is completed, the inverse operations of steps 1 and 2 + are performed to restore the two-dimensional matrix to the same dimension as the ``input``. + + It computes the exponential of the given dimension and the sum of exponential + values of all the other dimensions in the K-dimensional vector input. + Then the ratio of the exponential of the given dimension and the sum of + exponential values of all the other dimensions is the output of the softmax + operator. + + For each row :math:`i` and each column :math:`j` in the matrix, we have: + + .. math:: + + Out[i, j] = \\frac{\\exp(X[i, j])}{\\sum_j(exp(X[i, j])} + + Example: + + .. code-block:: text + + Case 1: + Input: + X.shape = [2, 3, 4] + X.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + + Attrs: + axis = -1 + + Output: + Out.shape = [2, 3, 4] + Out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.07232949, 0.19661193, 0.19661193, 0.53444665]], + [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] + + Case 2: + Input: + X.shape = [2, 3, 4] + X.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + Attrs: + axis = 1 + + Output: + Out.shape = [2, 3, 4] + Out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], + [0.01786798, 0.01786798, 0.04661262, 0.04661262], + [0.97555875, 0.97555875, 0.93623955, 0.93623955]], + [[0.00490169, 0.00490169, 0.00490169, 0.00490169], + [0.26762315, 0.26762315, 0.26762315, 0.26762315], + [0.72747516, 0.72747516, 0.72747516, 0.72747516]]] + + Args: + input (Tensor): The input tensor. A multi-dimension ``Tensor`` with type float32 or float64. + use_cudnn (bool, optional): Use cudnn kernel or not, it is valid only when the cudnn \ + library is installed. To improve performance, set use_cudnn to True by default. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . Default: None. + will be named automatically. Default: None. + axis (int, optional): The index of dimension to perform softmax calculations, it should + be in range :math:`[-1, rank - 1]`, while :math:`rank` is the rank of + input tensor. Default: -1. -1 means the last dimension. + + Returns: + Tensor: ``Tensor`` indicates the output of softmax. The data type and shape are the same as ``input`` . + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]], dtype='float32') + y = F.softmax(x, axis=1) + print(y) + # [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], + # [0.01786798, 0.01786798, 0.04661262, 0.04661262], + # [0.97555870, 0.97555870, 0.93623954, 0.93623954]], + # [[0.00490169, 0.00490169, 0.00490169, 0.00490169], + # [0.26762316, 0.26762316, 0.26762316, 0.26762316], + # [0.72747517, 0.72747517, 0.72747517, 0.72747517]]] + + """ + + if in_dygraph_mode(): + return _C_ops.softmax(input, axis) + + if _non_static_mode(): + return _legacy_C_ops.softmax( + input, 'axis', axis, 'use_cudnn', use_cudnn + ) + + inputs = {"X": [input]} + attrs = {"axis": axis, "use_cudnn": use_cudnn} + + helper = LayerHelper('softmax', **locals()) + check_variable_and_dtype( + input, 'input/x', ['float16', 'float32', 'float64'], 'softmax' + ) + + dtype = helper.input_dtype() + softmax_out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="softmax", + inputs={"X": input}, + outputs={"Out": softmax_out}, + attrs=attrs, + ) + return softmax_out + + +def conv2d( + input, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + name=None, + data_format="NCHW", +): + r""" + :api_attr: Static Graph + + The convolution2D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input and + Output are in NCHW or NHWC format, where N is batch size, C is the number of + channels, H is the height of the feature, and W is the width of the feature. + Filter is in MCHW format, where M is the number of output image channels, + C is the number of input image channels, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input image channels divided by the groups. + Please refer to UFLDL's `convolution + `_ + for more details. + If bias attribution and activation type are provided, bias is added to the + output of the convolution, and the corresponding activation function is + applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + Where: + + * :math:`X`: Input value, a tensor with NCHW or NHWC format. + * :math:`W`: Filter value, a tensor with MCHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Args: + input (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type + of input is float16 or float32 or float64. + num_filters(int): The number of filter. It is as same as the output + image channel. + filter_size (int|tuple): The filter size. If filter_size + is a tuple, it must contain two integers, (filter_size_height, + filter_size_width). Otherwise, filter_size_height = filter_size_width =\ + filter_size. + stride (int|tuple): The stride size. It means the stride in convolution. + If stride is a tuple, it must contain two integers, (stride_height, stride_width). + Otherwise, stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple): The padding size. It means the number of zero-paddings + on both sides for each dimension.If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_height, pad_width]` or + `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when + `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0], + [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `pool_padding` can be in the form + `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|tuple): The dilation size. It means the spacing between the kernel + points. If dilation is a tuple, it must contain two integers, (dilation_height, + dilation_width). Otherwise, dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int): The groups number of the Conv2d Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with :math:`Normal(0.0, std)`, + and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True + act (str): Activation type, if it is set to None, activation is not appended. + Default: None + name(str|None): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + A Tensor representing the conv2d, whose data type is the + same with input. If act is None, the tensor storing the convolution + result, and if act is not None, the tensor storing convolution + and non-linearity activation result. + + Raises: + ValueError: If the type of `use_cudnn` is not bool. + ValueError: If `data_format` is not "NCHW" or "NHWC". + ValueError: If the channel dimmention of the input is less than or equal to zero. + ValueError: If `padding` is a string, but not "SAME" or "VALID". + ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 + or the element corresponding to the input's channel is not 0. + ShapeError: If the input is not 4-D Tensor. + ShapeError: If the input's dimension size and filter's dimension size not equal. + ShapeError: If the dimension size of input minus the size of `stride` is not 2. + ShapeError: If the number of input channels is not equal to filter's channels * groups. + ShapeError: If the number of output channels is not be divided by groups. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32') + conv2d = paddle.static.nn.conv2d(input=data, num_filters=2, filter_size=3, act="relu") + print(conv2d.shape) # [-1, 2, 30, 30] + """ + + check_variable_and_dtype( + input, 'input', ['float16', 'float32', 'float64'], 'conv2d' + ) + if len(input.shape) != 4: + raise ValueError( + "Input size should be 4, " + "but received {}".format(len(input.shape)) + ) + num_channels = input.shape[1] + if not isinstance(use_cudnn, bool): + raise ValueError( + "Attr(use_cudnn) should be True or False. Received " + "Attr(use_cudnn): %s. " % str(use_cudnn) + ) + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + channel_last = data_format == "NHWC" + num_channels = input.shape[3] if channel_last else input.shape[1] + if num_channels < 0: + raise ValueError( + "The channel dimmention of the input(%s) should be defined. " + "Received: %s." % (str(input.shape), str(num_channels)) + ) + assert param_attr is not False, "param_attr should not be False here." + + if groups is None: + num_filter_channels = num_channels + elif groups <= 0: + raise ValueError( + "the groups of input must be greater than 0, " + "but received the groups of input is {}".format(groups) + ) + else: + if num_channels % groups != 0: + raise ValueError( + "the channel of input must be divisible by groups," + "received: the channel of input is {}, the shape of input is {}" + ", the groups is {}".format(num_channels, input.shape, groups) + ) + num_filter_channels = num_channels // groups + + l_type = 'conv2d' + if ( + num_channels == groups + and num_filters % num_channels == 0 + and not use_cudnn + ): + l_type = 'depthwise_conv2d' + + if ( + num_channels == groups + and num_filters % num_channels == 0 + and core.is_compiled_with_rocm() + ): + l_type = 'depthwise_conv2d' + + # NPU only supports depthwise_conv2d when "input_channel = output_channel = groups" + if core.is_compiled_with_npu(): + if num_channels == groups and num_channels == num_filters: + l_type = 'depthwise_conv2d' + else: + l_type = 'conv2d' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype() + + filter_size = utils.convert_to_list(filter_size, 2, 'filter_size') + stride = utils.convert_to_list(stride, 2, 'stride') + dilation = utils.convert_to_list(dilation, 2, 'dilation') + + # padding + def _update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, list) or isinstance(ele, tuple): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 4: + if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:4] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): + if not (padding[0] == [0, 0] and padding[3] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:3] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 4, 'padding') + if utils._is_symmetric_padding(padding, 2): + padding = [padding[0], padding[2]] + + else: + padding = utils.convert_to_list(padding, 2, 'padding') + + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." + % str(padding) + ) + if padding == "VALID": + padding_algorithm = "VALID" + padding = [0, 0] + elif padding == "SAME": + padding_algorithm = "SAME" + padding = [0, 0] + + padding = _update_padding(padding, data_format) + + filter_shape = [num_filters, int(num_filter_channels)] + filter_size + + def _get_default_param_initializer(): + filter_elem_num = filter_size[0] * filter_size[1] * num_channels + if filter_elem_num <= 0: + raise ValueError( + "Invalid filter number, excepted number is larger than 0, but" + " received {}, please check the input shape and " + "filter size.".format(filter_elem_num) + ) + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std, 0) + + filter_param = helper.create_parameter( + attr=helper.param_attr, + shape=filter_shape, + dtype=dtype, + default_initializer=_get_default_param_initializer(), + ) + + pre_bias = helper.create_variable_for_type_inference(dtype) + + if ( + core.is_compiled_with_cuda() + and paddle.fluid.get_flags("FLAGS_conv2d_disable_cudnn")[ + "FLAGS_conv2d_disable_cudnn" + ] + ): + use_cudnn = False + + helper.append_op( + type=l_type, + inputs={ + 'Input': input, + 'Filter': filter_param, + }, + outputs={"Output": pre_bias}, + attrs={ + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'use_mkldnn': False, + 'fuse_relu_before_depthwise_conv': False, + "padding_algorithm": padding_algorithm, + "data_format": data_format, + }, + ) + + if data_format == 'NCHW': + pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) + else: + pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4) + + return helper.append_activation(pre_act) + + +def conv3d( + input, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + name=None, + data_format="NCDHW", +): + r""" + :api_attr: Static Graph + + The convolution3D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are in NCDHW or NDHWC format. Where N is batch size C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. Convlution3D is similar with Convlution2D + but adds one dimension(depth). If bias attribution and activation type are + provided, bias is added to the output of the convolution, and the + corresponding activation function is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)` + + - Output: + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D_{out}&= \\frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\\\ + H_{out}&= \\frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1 + + Args: + input (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W], the data + type of input is float16 or float32 or float64. + num_filters(int): The number of filter. It is as same as the output + image channel. + filter_size (int|tuple): The filter size. If filter_size is a tuple, + it must contain three integers, (filter_size_depth, filter_size_height, + filter_size_width). Otherwise, filter_size_depth = filter_size_height = \ + filter_size_width = filter_size. + stride (int|tuple): The stride size. It means the stride in convolution. If stride is a + tuple, it must contain three integers, (stride_depth, stride_height, stride_width). + Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `pool_padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NDHWC"`, `pool_padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|tuple): The dilation size. It means the spacing between the kernel points. + If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int): The groups number of the Conv3d Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1 + param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights + of conv3d. If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv3d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True + act (str): Activation type, if it is set to None, activation is not appended. + Default: None. + name(str|None): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + A Variable holding Tensor representing the conv3d, whose data type is + the same with input. If act is None, the tensor variable storing the + convolution result, and if act is not None, the tensor variable storing + convolution and non-linearity activation result. + + Raises: + ValueError: If the type of `use_cudnn` is not bool. + ValueError: If `data_format` is not "NCDHW" or "NDHWC". + ValueError: If the channel dimmention of the input is less than or equal to zero. + ValueError: If `padding` is a string, but not "SAME" or "VALID". + ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 + or the element corresponding to the input's channel is not 0. + ShapeError: If the input is not 5-D Tensor. + ShapeError: If the input's dimension size and filter's dimension size not equal. + ShapeError: If the dimension size of input minus the size of `stride` is not 2. + ShapeError: If the number of input channels is not equal to filter's channels * groups. + ShapeError: If the number of output channels is not be divided by groups. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + paddle.enable_static() + data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32') + param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001) + res = paddle.static.nn.conv3d(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr) + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + x = np.random.rand(1, 3, 12, 32, 32).astype("float32") + output = exe.run(feed={"data": x}, fetch_list=[res]) + print(output) + """ + + l_type = 'conv3d' + assert param_attr is not False, "param_attr should not be False here." + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype() + + if not isinstance(use_cudnn, bool): + raise ValueError( + "Attr(use_cudnn) should be True or False. Received " + "Attr(use_cudnn): %s. " % str(use_cudnn) + ) + + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + channel_last = data_format == "NDHWC" + if len(input.shape) != 5: + raise ValueError( + "Input should be 5D tensor, but received input with the shape of {}".format( + input.shape + ) + ) + num_channels = input.shape[4] if channel_last else input.shape[1] + if num_channels < 0: + raise ValueError( + "The channel dimmention of the input(%s) should be defined. " + "Received: %s." % (str(input.shape), str(num_channels)) + ) + + if groups is None: + num_filter_channels = num_channels + elif groups <= 0: + raise ValueError( + "the groups of conv3d should be greater than 0. Received groups: {}".format( + groups + ) + ) + else: + if num_channels % groups != 0: + raise ValueError( + "The number of input channels must be divisible by Attr(groups). " + "Received: number of channels(%s), groups(%s)." + % (str(num_channels), str(groups)) + ) + num_filter_channels = num_channels // groups + + filter_size = utils.convert_to_list(filter_size, 3, 'filter_size') + stride = utils.convert_to_list(stride, 3, 'stride') + dilation = utils.convert_to_list(dilation, 3, 'dilation') + + def _update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, list) or isinstance(ele, tuple): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 5: + if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:5] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): + if not (padding[0] == [0, 0] and padding[4] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:4] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 6, 'padding') + if utils._is_symmetric_padding(padding, 3): + padding = [padding[0], padding[2], padding[4]] + elif is_list_or_tuple(padding) and len(padding) == 6: + padding = utils.convert_to_list(padding, 6, 'padding') + if utils._is_symmetric_padding(padding, 3): + padding = [padding[0], padding[2], padding[4]] + else: + padding = utils.convert_to_list(padding, 3, 'padding') + + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." + % str(padding) + ) + if padding == "VALID": + padding_algorithm = "VALID" + padding = [0, 0, 0] + elif padding == "SAME": + padding_algorithm = "SAME" + padding = [0, 0, 0] + + padding = _update_padding(padding, data_format) + + input_shape = input.shape + filter_shape = [num_filters, num_filter_channels] + filter_size + + def _get_default_param_initializer(): + filter_elem_num = ( + filter_size[0] * filter_size[1] * filter_size[2] * num_channels + ) + if filter_elem_num <= 0: + raise ValueError( + "Invalid filter number, excepted number is larger than 0, but" + " received {}, please check the input shape and " + "filter size.".format(filter_elem_num) + ) + + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std, 0) + + filter_param = helper.create_parameter( + attr=helper.param_attr, + shape=filter_shape, + dtype=dtype, + default_initializer=_get_default_param_initializer(), + ) + + pre_bias = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=l_type, + inputs={ + 'Input': input, + 'Filter': filter_param, + }, + outputs={"Output": pre_bias}, + attrs={ + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'use_mkldnn': False, + "padding_algorithm": padding_algorithm, + "data_format": data_format, + }, + ) + + if data_format == 'NCDHW': + pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) + else: + pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5) + + return helper.append_activation(pre_act) + + +@templatedoc() +def pool2d( + input, + pool_size=-1, + pool_type="max", + pool_stride=1, + pool_padding=0, + global_pooling=False, + use_cudnn=True, + ceil_mode=False, + name=None, + exclusive=True, + data_format="NCHW", +): + """ + + ${comment} + + Args: + input (Variable): The input tensor of pooling operator which is a 4-D tensor with + shape [N, C, H, W]. The format of input tensor is `"NCHW"` or + `"NHWC"`, where `N` is batch size, `C` is the number of channels, + `H` is the height of the feature, and `W` is the width of the + feature. The data type if float32 or float64. + pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (pool_size_Height, pool_size_Width). + Otherwise, the pool kernel size will be a square of an int. + pool_type: ${pooling_type_comment} + pool_stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain two integers, (pool_stride_Height, pool_stride_Width). + Otherwise, the pool stride size will be a square of an int. + pool_padding (string|int|list|tuple): The pool padding. If `pool_padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If pool padding size is a tuple or list, + it could be in three forms: `[pad_height, pad_width]` or + `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when `data_format` is `"NCHW"`, + `pool_padding` can be in the form `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `pool_padding` can be in the form + `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Otherwise, the pool padding size will be a square of an int. + global_pooling (bool): ${global_pooling_comment} + use_cudnn (bool): ${use_cudnn_comment} + ceil_mode (bool): ${ceil_mode_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + exclusive (bool): Whether to exclude padding points in average pooling + mode, default is `true`. + data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + Variable: The output tensor of pooling result. The data type is same as input tensor. + + Raises: + ValueError: If `pool_type` is not "max" nor "avg". + ValueError: If `global_pooling` is False and `pool_size` is -1. + TypeError: If `use_cudnn` is not a bool value. + ValueError: If `data_format` is not "NCHW" or "NHWC". + ValueError: If `pool_padding` is a string, but not "SAME" or "VALID". + ValueError: If `pool_padding` is "VALID", but `ceil_mode` is True. + ValueError: If `pool_padding` is a list or tuple, but the elements in the batch or channel dimensions are non-zero. + ShapeError: If the input is not a 4-D or 5-D Tensor. + ShapeError: If the dimension of input minus the size of `pool_stride` is not 2. + ShapeError: If the size of `pool_size` and `pool_stride` is not equal. + ShapeError: If the output's shape calculated is not greater than 0. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + + data = fluid.data(name='data', shape=[None, 3, 32, 32], dtype='float32') + + # max pool2d + pool2d = fluid.layers.pool2d( + input = data, + pool_size = 2, + pool_type = "max", + pool_stride = 1, + global_pooling=False) + + # average pool2d + pool2d = fluid.layers.pool2d( + input = data, + pool_size = 2, + pool_type = "avg", + pool_stride = 1, + global_pooling=False) + + # global average pool2d + pool2d = fluid.layers.pool2d( + input = data, + pool_size = 2, + pool_type = "avg", + pool_stride = 1, + global_pooling=True) + + # Attr(pool_padding) is a list with 4 elements, Attr(data_format) is "NCHW". + out_1 = fluid.layers.pool2d( + input = data, + pool_size = 3, + pool_type = "avg", + pool_stride = 1, + pool_padding = [1, 2, 1, 0], + data_format = "NCHW") + + # Attr(pool_padding) is a string, Attr(data_format) is "NCHW". + out_2 = fluid.layers.pool2d( + input = data, + pool_size = 3, + pool_type = "avg", + pool_stride = 1, + pool_padding = "VALID", + data_format = "NCHW") + """ + if pool_type not in ["max", "avg"]: + raise ValueError( + "Unknown Attr(pool_type): '%s'. It can only be 'max' or 'avg'.", + str(pool_type), + ) + + if global_pooling is False and pool_size == -1: + raise ValueError( + "When Attr(global_pooling) is False, Attr(pool_size) must be passed " + "and be a valid value. Received pool_size: %s." % str(pool_size) + ) + + if not isinstance(use_cudnn, bool): + raise TypeError( + "Attr(use_cudnn) should be True or False. Received " + "Attr(use_cudnn): %s." % str(use_cudnn) + ) + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + pool_size = utils.convert_to_list(pool_size, 2, 'pool_size') + pool_stride = utils.convert_to_list(pool_stride, 2, 'pool_stride') + + def update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, list) or isinstance(ele, tuple): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 4: + if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero pool_padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:4] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): + if not (padding[0] == [0, 0] and padding[3] == [0, 0]): + raise ValueError( + "Non-zero pool_padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:3] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 4, 'padding') + + if utils._is_symmetric_padding(padding, 2): + padding = [padding[0], padding[2]] + else: + padding = utils.convert_to_list(padding, 2, 'padding') + + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(pool_padding, str): + pool_padding = pool_padding.upper() + if pool_padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown Attr(pool_padding): '%s'. It can only be 'SAME' or 'VALID'." + % str(pool_padding) + ) + if pool_padding == "VALID": + padding_algorithm = "VALID" + pool_padding = [0, 0] + if ceil_mode != False: + raise ValueError( + "When Attr(pool_padding) is \"VALID\", Attr(ceil_mode) must be False. " + "Received ceil_mode: True." + ) + elif pool_padding == "SAME": + padding_algorithm = "SAME" + pool_padding = [0, 0] + + pool_padding = update_padding(pool_padding, data_format) + if in_dygraph_mode(): + return _C_ops.pool2d( + input, + pool_size, + pool_stride, + pool_padding, + ceil_mode, + exclusive, + data_format, + pool_type, + global_pooling, + False, + padding_algorithm, + use_cudnn, + ) + op_type = 'pool2d' + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": input}, + outputs={"Out": pool_out}, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "global_pooling": global_pooling, + "strides": pool_stride, + "paddings": pool_padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": use_cudnn, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": exclusive, + "data_format": data_format, + }, + ) + + return pool_out + + +@templatedoc() +def pool3d( + input, + pool_size=-1, + pool_type="max", + pool_stride=1, + pool_padding=0, + global_pooling=False, + use_cudnn=True, + ceil_mode=False, + name=None, + exclusive=True, + data_format="NCDHW", +): + """ + + ${comment} + + Args: + input (Variable): The input tensor of pooling operator, which is a 5-D tensor with + shape [N, C, D, H, W]. The format of + input tensor is `"NCDHW"` or `"NDHWC"`, where `N` is batch size, `C` is + the number of channels, `D` is the depth of the feature, + `H` is the height of the feature, and `W` is the width + of the feature. + pool_size (int|list|tuple): The pool kernel size. If pool kernel size + is a tuple or list, it must contain three integers, + (pool_size_Depth, pool_size_Height, pool_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + pool_type (string): ${pooling_type_comment} + pool_stride (string|int|list|tuple)): The pool padding. If `pool_padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If pool stride size is a tuple or list, + it must contain three integers, `[stride_Depth, stride_Height, stride_Width]`. + Otherwise, the pool stride size will be a cube of an int. + pool_padding (int|list|tuple): The pool padding size. If pool padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `pool_padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NDHWC"`, `pool_padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + global_pooling (bool): ${global_pooling_comment} + use_cudnn (bool): ${use_cudnn_comment} + ceil_mode (bool): ${ceil_mode_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + exclusive (bool): Whether to exclude padding points in average pooling + mode, default is true. + data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + + Returns: + Variable: The output tensor of pooling result. The data type is same as input tensor. + + Raises: + ValueError: If `pool_type` is not "max" nor "avg". + ValueError: If `global_pooling` is False and `pool_size` is -1. + TypeError: If `use_cudnn` is not a bool value. + ValueError: If `data_format` is not "NCDHW" or "NDHWC". + ValueError: If `pool_padding` is a string, but not "SAME" or "VALID". + ValueError: If `pool_padding` is "VALID", but `ceil_mode` is True. + ValueError: If `pool_padding` is a list or tuple, but the elements in the batch or channel dimensions are non-zero. + ShapeError: If the input is not a 4-D or 5-D Tensor. + ShapeError: If the dimension of input minus the size of `pool_stride` is not 2. + ShapeError: If the size of `pool_size` and `pool_stride` is not equal. + ShapeError: If the output's shape calculated is not greater than 0. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + + data = fluid.data(name='data', shape=[None, 3, 32, 32, 32], dtype='float32') + + # max pool3d + pool3d = fluid.layers.pool3d( + input = data, + pool_size = 2, + pool_type = "max", + pool_stride = 1, + global_pooling=False) + + # average pool3d + pool3d = fluid.layers.pool3d( + input = data, + pool_size = 2, + pool_type = "avg", + pool_stride = 1, + global_pooling=False) + + # global average pool3d + pool3d = fluid.layers.pool3d( + input = data, + pool_size = 2, + pool_type = "avg", + pool_stride = 1, + global_pooling=True) + + # example 1: + # Attr(pool_padding) is a list with 6 elements, Attr(data_format) is "NCDHW". + out_1 = fluid.layers.pool3d( + input = data, + pool_size = 2, + pool_type = "avg", + pool_stride = 1, + pool_padding = [1, 2, 1, 0, 1, 2], + global_pooling = False, + data_format = "NCDHW") + + # example 2: + # Attr(pool_padding) is a string, Attr(data_format) is "NCDHW". + out_2 = fluid.layers.pool3d( + input = data, + pool_size = 3, + pool_type = "avg", + pool_stride = 1, + pool_padding = "VALID", + global_pooling = False, + data_format = "NCDHW") + + """ + if pool_type not in ["max", "avg"]: + raise ValueError( + "Unknown Attr(pool_type): '%s'. It can only be 'max' or 'avg'.", + str(pool_type), + ) + + if global_pooling is False and pool_size == -1: + raise ValueError( + "When Attr(global_pooling) is False, Attr(pool_size) must be passed " + "and be a valid value. Received Attr(pool_size): %s." + % str(pool_size) + ) + + if not isinstance(use_cudnn, bool): + raise TypeError( + "Attr(use_cudnn) should be True or False. Received " + "Attr(use_cudnn): %s. " % str(use_cudnn) + ) + + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): %s" % str(data_format) + ) + + pool_size = utils.convert_to_list(pool_size, 3, 'pool_size') + pool_stride = utils.convert_to_list(pool_stride, 3, 'pool_stride') + + def update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, (list, tuple)): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 5: + if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero pool_padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:5] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): + if not (padding[0] == [0, 0] and padding[4] == [0, 0]): + raise ValueError( + "Non-zero pool_padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:4] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 6, 'padding') + if utils._is_symmetric_padding(padding, 3): + padding = [padding[0], padding[2], padding[4]] + + elif is_list_or_tuple(padding) and len(padding) == 6: + padding = utils.convert_to_list(padding, 6, 'padding') + if utils._is_symmetric_padding(padding, 3): + padding = [padding[0], padding[2], padding[4]] + else: + padding = utils.convert_to_list(padding, 3, 'padding') + + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(pool_padding, str): + pool_padding = pool_padding.upper() + if pool_padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown Attr(pool_padding): '%s'. It can only be 'SAME' or 'VALID'." + % str(pool_padding) + ) + if pool_padding == "VALID": + padding_algorithm = "VALID" + pool_padding = [0, 0, 0] + if ceil_mode != False: + raise ValueError( + "When Attr(pool_padding) is \"VALID\", ceil_mode must be False. " + "Received ceil_mode: True." + ) + elif pool_padding == "SAME": + padding_algorithm = "SAME" + pool_padding = [0, 0, 0] + + pool_padding = update_padding(pool_padding, data_format) + + op_type = "pool3d" + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": input}, + outputs={"Out": pool_out}, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "global_pooling": global_pooling, + "strides": pool_stride, + "paddings": pool_padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": use_cudnn, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": exclusive, + "data_format": data_format, + }, + ) + + return pool_out + + +@deprecated(since="2.0.0") +@templatedoc(op_type="pool2d") +def adaptive_pool2d( + input, pool_size, pool_type="max", require_index=False, name=None +): + r""" + + This operation calculates the output based on the input, pool_size, + pool_type parameters. Input(X) and output(Out) are in NCHW format, where N is batch + size, C is the number of channels, H is the height of the feature, and W is + the width of the feature. Parameters(pool_size) should contain two elements which + represent height and width, respectively. Also the H and W dimensions of output(Out) + is same as Parameter(pool_size). The output tensor shape will be [N, C, pool_size[0], pool_size[1]] + + For average adaptive pool2d: + + .. math:: + + hstart &= floor(i * H_{in} / H_{out}) + + hend &= ceil((i + 1) * H_{in} / H_{out}) + + wstart &= floor(j * W_{in} / W_{out}) + + wend &= ceil((j + 1) * W_{in} / W_{out}) + + Output(i ,j) &= \\frac{sum(Input[hstart:hend, wstart:wend])}{(hend - hstart) * (wend - wstart)} + + Args: + input (Tensor): The input tensor of pooling operator, which is a 4-D tensor + with shape [N, C, H, W]. The format of input tensor is NCHW, + where N is batch size, C is the number of channels, H is the + height of the feature, and W is the width of the feature. + The data type is float32 or float64. + pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (pool_size_Height, pool_size_Width). + pool_type: ${pooling_type_comment} + require_index (bool): If true, the index of max pooling point will be returned along + with outputs. It cannot be set in average pooling type. Default False. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of adaptive pooling result. The data type is same + as input tensor. + + Raises: + ValueError: 'pool_type' is not 'max' nor 'avg'. + ValueError: invalid setting 'require_index' true when 'pool_type' is 'avg'. + ValueError: 'pool_size' should be a list or tuple with length as 2. + + Examples: + .. code-block:: python + + # average adaptive pool2d + # suppose input data in shape of [N, C, H, W], `pool_size` is [m, n], + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive average pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + paddle.enable_static() + data = paddle.rand(shape=[1,3,32,32]) + pool_out = paddle.fluid.layers.adaptive_pool2d( + input=data, + pool_size=[3, 3], + pool_type='avg') + + # max adaptive pool2d + # suppose input data in shape of [N, C, H, W], `pool_size` is [m, n], + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive average pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + data = paddle.rand(shape=[1,3,32,32]) + pool_out = paddle.fluid.layers.adaptive_pool2d( + input=data, + pool_size=[3, 3], + pool_type='max') + """ + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'adaptive_pool2d', + ) + check_type(pool_type, 'pool_type', str, 'adaptive_pool2d') + check_type(pool_size, 'pool_size', (int, list, tuple), 'adaptive_pool2d') + check_type(require_index, 'require_index', bool, 'adaptive_pool2d') + if pool_type not in ["max", "avg"]: + raise ValueError( + "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.", + str(pool_type), + ) + + if pool_type == "avg" and require_index: + raise ValueError( + "invalid setting 'require_index' true when 'pool_type' is 'avg'." + ) + + pool_size = utils.convert_to_list(pool_size, 2, 'pool_size') + + if pool_type == "max": + l_type = 'max_pool2d_with_index' + else: + l_type = "pool2d" + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + + outputs = {"Out": pool_out} + if pool_type == "max": + mask = helper.create_variable_for_type_inference(dtype) + outputs["Mask"] = mask + + helper.append_op( + type=l_type, + inputs={"X": input}, + outputs=outputs, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "adaptive": True, + }, + ) + + return (pool_out, mask) if require_index else pool_out + + +@deprecated(since="2.0.0") +@templatedoc(op_type="pool3d") +def adaptive_pool3d( + input, pool_size, pool_type="max", require_index=False, name=None +): + r""" + + This operation calculates the output based on the input, pool_size, + pool_type parameters. Input(X) and output(Out) are in NCDHW format, where N is batch + size, C is the number of channels, D is the depth of the feature, H is the height of + the feature, and W is the width of the feature. Parameters(pool_size) should contain + three elements which represent height and width, respectively. Also the D, H and W + dimensions of output(Out) is same as Parameter(pool_size). The output tensor shape + will be [N, C, pool_size[0], pool_size[1], pool_size[2]] + + For average adaptive pool3d: + + .. math:: + + dstart &= floor(i * D_{in} / D_{out}) + + dend &= ceil((i + 1) * D_{in} / D_{out}) + + hstart &= floor(j * H_{in} / H_{out}) + + hend &= ceil((j + 1) * H_{in} / H_{out}) + + wstart &= floor(k * W_{in} / W_{out}) + + wend &= ceil((k + 1) * W_{in} / W_{out}) + + Output(i ,j, k) &= \\frac{sum(Input[dstart:dend, hstart:hend, wstart:wend])}{(dend - dstart) * (hend - hstart) * (wend - wstart)} + + Args: + input (Tensor): The input tensor of pooling operator, which is a 5-D tensor with + shape [N, C, D, H, W]. The format of input tensor is NCDHW, where + N is batch size, C is the number of channels, D is the depth of the feature, + H is the height of the feature, and W is the width of the feature. + The data type is float32 or float64. + pool_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain three integers, (Depth, Height, Width). + pool_type: ${pooling_type_comment} + require_index (bool): If true, the index of max pooling point will be returned along + with outputs. It cannot be set in average pooling type. Default False. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. + + Raises: + ValueError: 'pool_type' is not 'max' nor 'avg'. + ValueError: invalid setting 'require_index' true when 'pool_type' is 'avg'. + ValueError: 'pool_size' should be a list or tuple with length as 2. + + Examples: + .. code-block:: python + + # average adaptive pool3d + # suppose input data in shape of [N, C, D, H, W], `pool_size` is [l, m, n], + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into l * m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive average pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(j * H / m) + # hend = ceil((j + 1) * H / m) + # wstart = floor(k * W / n) + # wend = ceil((k + 1) * W / n) + # output[:, :, i, j, k] = + # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) + # + + import paddle + paddle.enable_static() + data = paddle.rand(shape=[1,3,32,32,32]) + pool_out = paddle.fluid.layers.adaptive_pool3d( + input=data, + pool_size=[3, 3, 3], + pool_type='avg') + + # max adaptive pool3d + # suppose input data in shape of [N, C, D, H, W], `pool_size` is [l, m, n], + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into l * m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive average pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(j * H / m) + # hend = ceil((j + 1) * H / m) + # wstart = floor(k * W / n) + # wend = ceil((k + 1) * W / n) + # output[:, :, i, j, k] = + # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) + # + + import paddle + data = paddle.rand(shape=[1,3,32,32,32]) + pool_out = paddle.fluid.layers.adaptive_pool3d( + input=data, + pool_size=[3, 3, 3], + pool_type='max') + """ + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'adaptive_pool3d', + ) + check_type(pool_type, 'pool_type', str, 'adaptive_pool3d') + check_type(pool_size, 'pool_size', (int, list, tuple), 'adaptive_pool3d') + check_type(require_index, 'require_index', bool, 'adaptive_pool3d') + if pool_type not in ["max", "avg"]: + raise ValueError( + "Unknown pool_type: '%s'. It can only be 'max' or 'avg'.", + str(pool_type), + ) + + if pool_type == "avg" and require_index: + raise ValueError( + "invalid setting 'require_index' true when 'pool_type' is 'avg'." + ) + + pool_size = utils.convert_to_list(pool_size, 3, 'pool_size') + + if pool_type == "max": + l_type = 'max_pool3d_with_index' + else: + l_type = "pool3d" + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + + outputs = {"Out": pool_out} + if pool_type == "max": + mask = helper.create_variable_for_type_inference(dtype) + outputs["Mask"] = mask + + helper.append_op( + type=l_type, + inputs={"X": input}, + outputs=outputs, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "adaptive": True, + }, + ) + + return (pool_out, mask) if require_index else pool_out + + +def batch_norm( + input, + act=None, + is_test=False, + momentum=0.9, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + data_layout='NCHW', + in_place=False, + name=None, + moving_mean_name=None, + moving_variance_name=None, + do_model_average_for_mean_and_var=True, + use_global_stats=False, +): + r""" + :api_attr: Static Graph + + **Batch Normalization Layer** + + Can be used as a normalizer function for convolution or fully_connected operations. + The required data format for this layer is one of the following: + + 1. NHWC `[batch, in_height, in_width, in_channels]` + + 2. NCHW `[batch, in_channels, in_height, in_width]` + + Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing + Internal Covariate Shift `_ + for more details. + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \\mu_{\\beta} &\\gets \\frac{1}{m} \\sum_{i=1}^{m} x_i \\qquad &//\\ + \ mini-batch\ mean \\\\ + \\sigma_{\\beta}^{2} &\\gets \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\ + \\mu_{\\beta})^2 \\qquad &//\ mini-batch\ variance \\\\ + \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ + \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ + y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift + + moving\_mean = moving\_mean * momentum + mini-batch\_mean * (1. - momentum) \\\\ + moving\_var = moving\_var * momentum + mini-batch\_var * (1. - momentum) + + + moving_mean is global mean and moving_var is global variance. + + When use_global_stats = True, the :math:`\\mu_{\\beta}` + and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch. + They are global (or running) statistics. (It usually got from the + pre-trained model.) + The training and testing (or inference) have the same behavior: + + .. math:: + + \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ + \\sigma_{\\beta}^{2} + \\epsilon}} \\\\ + y_i &\\gets \\gamma \\hat{x_i} + \\beta + + Note: + if build_strategy.sync_batch_norm=True, the batch_norm in network will use + sync_batch_norm automatically. + `is_test = True` can only be used in test program and inference program, `is_test` CANNOT be set to True in train program, if you want to use global status from pre_train model in train program, please set `use_global_stats = True`. + + Args: + input(Tensor): The rank of input Tensor can be 2, 3, 4, 5. The data type + is float16 or float32 or float64. + act(string, Default None): Activation type, linear|relu|prelu|... + is_test (bool, Default False): A flag indicating whether it is in + test phrase or not. + momentum(float|Tensor, Default 0.9): The value used for the moving_mean and + moving_var computation. This should be a float number or a Tensor with + shape [1] and data type as float32. The updated formula is: + :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` + :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` + Default is 0.9. + epsilon(float, Default 1e-05): A value added to the denominator for + numerical stability. Default is 1e-5. + param_attr(ParamAttr|None): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. + If the Initializer of the param_attr is not set, the parameter is initialized + with Xavier. Default: None. + bias_attr(ParamAttr|None): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + Default: None. + data_layout (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + in_place(bool, Default False): Make the input and output of batch norm reuse memory. + name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + moving_mean_name(str, Default None): The name of moving_mean which store the global Mean. If it + is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm + will save global mean with the string. + moving_variance_name(str, Default None): The name of the moving_variance which store the global Variance. + If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm + will save global variance with the string. + do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model + average when model average is enabled. + use_global_stats(bool, Default False): Whether to use global mean and + variance. In inference or test mode, set use_global_stats to true + or is_test to true, and the behavior is equivalent. + In train mode, when setting use_global_stats True, the global mean + and variance are also used during train period. + Returns: + A Tensor which is the result after applying batch normalization on the input, + has same shape and data type with input. + + Examples: + + .. code-block:: python + + import paddle + + paddle.enable_static() + x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32') + hidden1 = paddle.static.nn.fc(x=x, size=200) + print(hidden1.shape) + # [3, 200] + hidden2 = paddle.static.nn.batch_norm(input=hidden1) + print(hidden2.shape) + # [3, 200] + """ + assert ( + bias_attr is not False + ), "bias_attr should not be False in batch_norm." + helper = LayerHelper('batch_norm', **locals()) + + check_variable_and_dtype( + input, 'input', ['float16', 'float32', 'float64'], 'batch_norm' + ) + dtype = helper.input_dtype() + + # use fp32 for bn parameter + if dtype == core.VarDesc.VarType.FP16: + dtype = core.VarDesc.VarType.FP32 + + input_shape = input.shape + if data_layout == 'NCHW': + channel_num = input_shape[1] + else: + if data_layout == 'NHWC': + channel_num = input_shape[-1] + else: + raise ValueError("unsupported data layout:" + data_layout) + + param_shape = [channel_num] + + # create parameter + scale = helper.create_parameter( + attr=helper.param_attr, + shape=param_shape, + dtype=dtype, + default_initializer=Constant(1.0), + ) + bias = helper.create_parameter( + attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True + ) + + mean = helper.create_parameter( + attr=ParamAttr( + name=moving_mean_name, + initializer=Constant(0.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var, + ), + shape=param_shape, + dtype=dtype, + ) + mean.stop_gradient = True + + variance = helper.create_parameter( + attr=ParamAttr( + name=moving_variance_name, + initializer=Constant(1.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var, + ), + shape=param_shape, + dtype=dtype, + ) + variance.stop_gradient = True + + # create output + # mean and mean_out share the same memory + mean_out = mean + # variance and variance_out share the same memory + variance_out = variance + + if in_dygraph_mode(): + inputs_has_MomemtumTensor = False + attrs_has_momentum = False + tmp_tensor_type = core.eager.Tensor + if isinstance(momentum, tmp_tensor_type): + inputs_has_MomemtumTensor = True + else: + attrs_has_momentum = True + + attrs_ = () + if attrs_has_momentum: + attrs_ = ( + 'momentum', + momentum, + 'epsilon', + epsilon, + 'is_test', + is_test, + 'data_layout', + data_layout, + 'use_mkldnn', + False, + 'fuse_with_relu', + False, + 'use_global_stats', + use_global_stats, + ) + else: + attrs_ = ( + 'epsilon', + epsilon, + 'is_test', + is_test, + 'data_layout', + data_layout, + 'use_mkldnn', + False, + 'fuse_with_relu', + False, + 'use_global_stats', + use_global_stats, + ) + if inputs_has_MomemtumTensor: + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.batch_norm( + input, + scale, + bias, + mean, + variance, + momentum, + mean_out, + variance_out, + *attrs_, + ) + else: + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.batch_norm( + input, + scale, + bias, + mean, + variance, + None, + mean_out, + variance_out, + *attrs_, + ) + + return dygraph_utils._append_activation_in_dygraph( + batch_norm_out, act=act, use_mkldnn=False + ) + + saved_mean = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + reserve_space = None + if not is_test: + reserve_space = helper.create_variable_for_type_inference( + dtype=helper.input_dtype(), stop_gradient=True + ) + + batch_norm_out = ( + input if in_place else helper.create_variable_for_type_inference(dtype) + ) + + inputs = { + "X": input, + "Scale": scale, + "Bias": bias, + "Mean": mean, + "Variance": variance, + "MeanOut": mean_out, + "VarianceOut": variance_out, + } + attrs = { + "epsilon": epsilon, + "is_test": is_test, + "data_layout": data_layout, + "use_mkldnn": False, + "fuse_with_relu": False, + "use_global_stats": use_global_stats, + } + if isinstance(momentum, Variable): + inputs['MomemtumTensor'] = momentum + else: + attrs['momentum'] = momentum + + outputs = { + "Y": batch_norm_out, + "MeanOut": mean_out, + "VarianceOut": variance_out, + "SavedMean": saved_mean, + "SavedVariance": saved_variance, + } + if reserve_space is not None: + outputs["ReserveSpace"] = reserve_space + + helper.append_op( + type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs + ) + + return helper.append_activation(batch_norm_out) + + +def inplace_abn( + input, + act=None, + is_test=False, + momentum=0.9, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + data_layout='NCHW', + name=None, + moving_mean_name=None, + moving_variance_name=None, + do_model_average_for_mean_and_var=True, + use_global_stats=False, + act_alpha=1.0, +): + r""" + **In-place Activation Batch Normalization Layer** + + This layer calculates batch normalization and activation with in-place memory. + For batch normalization calculations, see `fluid.layers.batch_norm`. + For in-place activation batch normalization, see `In-Place Activated BatchNorm for + Memory-Optimized Training of DNNs `_ + + `inplace_abn` only support activation type as `None`, `identity`, `leaky_relu`, + `elu` currently. + `inplace_abn` only support data type as `float32`, `float64` currently. + + Note: + if build_strategy.sync_batch_norm=True, the batch_norm in network will use + sync_batch_norm automatically. + `is_test = True` can only be used in test program and inference program, `is_test` CANNOT be set to True in train program, if you want to use global status from pre_train model in train program, please set `use_global_stats = True`. + + Args: + input(Variable): The rank of input variable can be 2, 3, 4, 5. The data type + is float16 or float32 or float64. + act(string, Default None): Activation type, linear|relu|prelu|... + is_test (bool, Default False): A flag indicating whether it is in + test phrase or not. + momentum(float|Variable, Default 0.9): The value used for the moving_mean and + moving_var computation. This should be a float number or a Variable with + shape [1] and data type as float32. The updated formula is: + :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` + :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` + Default is 0.9. + epsilon(float, Default 1e-05): A value added to the denominator for + numerical stability. Default is 1e-5. + param_attr(ParamAttr|None): The parameter attribute for Parameter `scale` + of inplace_abn. If it is set to None or one attribute of ParamAttr, inplace_abn + will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. + If the Initializer of the param_attr is not set, the parameter is initialized + with Xavier. Default: None. + bias_attr(ParamAttr|None): The parameter attribute for the bias of inplace_abn. + If it is set to None or one attribute of ParamAttr, inplace_abn + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + Default: None. + data_layout (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str|None): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + moving_mean_name(str, Default None): The name of moving_mean which store the global Mean. If it + is set to None, inplace_abn will save global mean with a random name, otherwise, inplace_abn + will save global mean with the string. + moving_variance_name(str, Default None): The name of the moving_variance which store the global Variance. + If it is set to None, inplace_abn, will save global variance with a random name, otherwise, inplace_abn + will save global variance with the string. + do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance should do model + average when model average is enabled. + use_global_stats(bool, Default False): Whether to use global mean and + variance. In inference or test mode, set use_global_stats to true + or is_test to true, and the behavior is equivalent. + In train mode, when setting use_global_stats True, the global mean + and variance are also used during train period. + act_alpha(float, Default 1.0): when activation is in ['elu', 'identity', 'leaky_relu'], + inplace activative batch normalization will be used, and alpha parameter for activation + can be given by this parameter. + Returns: + A Variable holding Tensor which is the result after applying batch normalization and activation on the input, + has same shape and data type with input. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[3, 7, 3, 7], dtype='float32') + hidden1 = fluid.layers.fc(input=x, size=200, param_attr='fc1.w') + hidden2 = fluid.layers.inplace_abn(input=hidden1) + hidden3 = fluid.layers.inplace_abn(input=hidden2, act='leaky_relu', act_alpha=0.2) + + """ + assert act in [None, 'identity', 'leaky_relu', 'elu'], ( + "inplace_abn only support act as None, 'identity', " + "'leaky_relu', 'elu' currently" + ) + assert ( + bias_attr is not False + ), "bias_attr should not be False in inplace_abn." + helper = LayerHelper('inplace_abn', **locals()) + + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'inplace_abn' + ) + dtype = helper.input_dtype() + + input_shape = input.shape + if data_layout == 'NCHW': + channel_num = input_shape[1] + else: + if data_layout == 'NHWC': + channel_num = input_shape[-1] + else: + raise ValueError("unsupported data layout:" + data_layout) + + param_shape = [channel_num] + + # create parameter + scale = helper.create_parameter( + attr=helper.param_attr, + shape=param_shape, + dtype=dtype, + default_initializer=Constant(1.0), + ) + bias = helper.create_parameter( + attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True + ) + + mean = helper.create_parameter( + attr=ParamAttr( + name=moving_mean_name, + initializer=Constant(0.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var, + ), + shape=param_shape, + dtype=dtype, + ) + mean.stop_gradient = True + + variance = helper.create_parameter( + attr=ParamAttr( + name=moving_variance_name, + initializer=Constant(1.0), + trainable=False, + do_model_average=do_model_average_for_mean_and_var, + ), + shape=param_shape, + dtype=dtype, + ) + variance.stop_gradient = True + + # create output + # mean and mean_out share the same memory + mean_out = mean + # variance and variance out share the same memory + variance_out = variance + # batch_norm_out and input share the same memory + batch_norm_out = input + + if in_dygraph_mode(): + inputs_has_MomemtumTensor = False + attrs_has_momentum = False + tmp_tensor_type = core.eager.Tensor + if isinstance(momentum, tmp_tensor_type): + inputs_has_MomemtumTensor = True + else: + attrs_has_momentum = True + + attrs__ = () + if attrs_has_momentum: + attrs__ = ( + 'momentum', + momentum, + 'epsilon', + epsilon, + 'is_test', + is_test, + 'data_layout', + data_layout, + 'use_mkldnn', + False, + 'fuse_with_relu', + False, + 'use_global_stats', + use_global_stats, + 'activation', + act, + 'alpha', + act_alpha, + ) + else: + attrs__ = ( + 'epsilon', + epsilon, + 'is_test', + is_test, + 'data_layout', + data_layout, + 'use_mkldnn', + False, + 'fuse_with_relu', + False, + 'use_global_stats', + use_global_stats, + 'activation', + act, + 'alpha', + act_alpha, + ) + if inputs_has_MomemtumTensor: + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.inplace_abn_( + input, + scale, + bias, + mean, + variance, + momentum, + mean_out, + variance_out, + *attrs__, + ) + return batch_norm_out + else: + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.inplace_abn_( + input, + scale, + bias, + mean, + variance, + None, + mean_out, + variance_out, + *attrs__, + ) + return batch_norm_out + + saved_mean = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + reserve_space = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + + inputs = { + "X": input, + "Scale": scale, + "Bias": bias, + "Mean": mean, + "Variance": variance, + } + attrs = { + "epsilon": epsilon, + "is_test": is_test, + "data_layout": data_layout, + "use_mkldnn": False, + "fuse_with_relu": False, + "use_global_stats": use_global_stats, + "activation": act, + "alpha": act_alpha, + } + if isinstance(momentum, Variable): + inputs['MomemtumTensor'] = momentum + else: + attrs['momentum'] = momentum + outputs = { + "Y": batch_norm_out, + "MeanOut": mean_out, + "VarianceOut": variance_out, + "SavedMean": saved_mean, + "SavedVariance": saved_variance, + } + if reserve_space is not None: + outputs["ReserveSpace"] = reserve_space + + helper.append_op( + type="inplace_abn", inputs=inputs, outputs=outputs, attrs=attrs + ) + + return batch_norm_out + + +def instance_norm( + input, epsilon=1e-05, param_attr=None, bias_attr=None, name=None +): + r""" + :api_attr: Static Graph + + **Instance Normalization Layer** + + Can be used as a normalizer function for convolution or fully_connected operations. + The required data format for this layer is one of the following: + + DataLayout: NCHW `[batch, in_channels, in_height, in_width]` + + Refer to `Instance Normalization: The Missing Ingredient for + Fast Stylization `_ + for more details. + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \\mu_{\\beta} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW} x_i \\qquad &//\\ + \\ mean\ of\ one\ feature\ map\ in\ mini-batch \\\\ + \\sigma_{\\beta}^{2} &\\gets \\frac{1}{HW} \\sum_{i=1}^{HW}(x_i - \\ + \\mu_{\\beta})^2 \\qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\\\ + \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ + \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ + y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift + + Note: + `H` means height of feature map, `W` means width of feature map. + + Args: + input(Tensor): The rank of input tensor can be 2, 3, 4, 5. + The data type is float32 or float64. + epsilon(float, Default 1e-05): A value added to the denominator for + numerical stability. Default is 1e-5. + param_attr(ParamAttr|None|bool, optional): The parameter attribute for Parameter `scale` + of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as param_attr, the name of scale can be set in ParamAttr. + If the Initializer of the param_attr is not set, the parameter is initialized + with Xavier. If the param_attr is set to False, instance_norm will not create param_attr. + Default: None. + bias_attr(ParamAttr|None|bool, optional): The parameter attribute for the bias of instance_norm. + If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + If the bias_attr is set to False, instance_norm will not create bias_attr. + Default: None. + name(string, Default None): A name for this layer(optional). If set None, the layer + will be named automatically. + + Returns: + A Tensor which is the result after applying instance normalization on the input, + has same shape and data type with input. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + x = paddle.static.data(name='x', shape=[3, 7, 3, 7], dtype='float32') + hidden1 = paddle.static.nn.fc(x, size=200) + hidden2 = paddle.static.nn.instance_norm(hidden1) + """ + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'instance_norm' + ) + if param_attr is False: + assert ( + bias_attr is False + ), "param_attr and bias_attr must be set to Fasle at the same time in instance_norm" + + helper = LayerHelper('instance_norm', **locals()) + dtype = helper.input_dtype() + + # use fp32 for in parameter + if dtype == core.VarDesc.VarType.FP16: + dtype = core.VarDesc.VarType.FP32 + + input_shape = input.shape + if len(input.shape) < 2 or len(input.shape) > 5: + raise ValueError( + 'expected 2D or 3D or 4D or 5D input (got {}D input, input shape is: {})'.format( + len(input.shape), input_shape + ) + ) + channel_num = input_shape[1] + + param_shape = [channel_num] + + if param_attr != False and bias_attr != False: + # create parameter + scale = helper.create_parameter( + attr=helper.param_attr, + shape=param_shape, + dtype=dtype, + default_initializer=Constant(1.0), + ) + bias = helper.create_parameter( + attr=helper.bias_attr, + shape=param_shape, + dtype=dtype, + is_bias=True, + default_initializer=Constant(0.0), + ) + + # create output + saved_mean = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + + instance_norm_out = helper.create_variable_for_type_inference(dtype) + + inputs = {"X": input} + if param_attr != False and bias_attr != False: + inputs["Scale"] = scale + inputs["Bias"] = bias + + helper.append_op( + type="instance_norm", + inputs=inputs, + outputs={ + "Y": instance_norm_out, + "SavedMean": saved_mean, + "SavedVariance": saved_variance, + }, + attrs={ + "epsilon": epsilon, + }, + ) + + return instance_norm_out + + +@static_only +def data_norm( + input, + act=None, + epsilon=1e-05, + param_attr=None, + data_layout='NCHW', + in_place=False, + name=None, + moving_mean_name=None, + moving_variance_name=None, + do_model_average_for_mean_and_var=True, + slot_dim=-1, + sync_stats=False, + summary_decay_rate=0.9999999, + enable_scale_and_shift=False, +): + r""" + :api_attr: Static Graph + + **Data Normalization Layer** + + This op can be used as a normalizer function for conv2d and fully_connected operations. + The required data format for this layer is one of the following: + + 1. NHWC `[batch, in_height, in_width, in_channels]` + + 2. NCHW `[batch, in_channels, in_height, in_width]` + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \\mu_{\\beta} &\\gets \\frac{1}{m} \\sum_{i=1}^{m} x_i \\qquad &//\\ + \ mini-batch\ mean \\\\ + \\sigma_{\\beta}^{2} &\\gets \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\ + \\mu_{\\beta})^2 \\qquad &//\ mini-batch\ variance \\\\ + \\hat{x_i} &\\gets \\frac{x_i - \\mu_\\beta} {\\sqrt{\\ + \\sigma_{\\beta}^{2} + \\epsilon}} \\qquad &//\ normalize \\\\ + y_i &\\gets \\gamma \\hat{x_i} + \\beta \\qquad &//\ scale\ and\ shift + + Args: + input(Tensor): The input Tensor. + act(string, Default None): Activation type, linear|relu|prelu|... + epsilon(float, Default 1e-05): + param_attr(ParamAttr): The parameter attribute for Parameter `scale`. + data_layout (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + in_place(bool, Default False): Make the input and output of batch norm reuse memory. + name(string, Default None): A name for this layer(optional). If set None, the layer + will be named automatically. + moving_mean_name(string, Default None): The name of moving_mean which store the global Mean. + moving_variance_name(string, Default None): The name of the moving_variance which store the global Variance. + do_model_average_for_mean_and_var(bool, Default True): Whether parameter mean and variance + should do model average when model average is enabled. + slot_dim(int): The embedding dimension of one slot. Slot is a set of one specific feature. In pslib mode, we + distinguish feature ids by slot and pull their embeddings from parameter server (pslib). The first + place of the embedding is the historical show number (occurence time of this feature id with a label 0). + If the input of this op is concated by slot-wise embeddings, and the show number is zero when this slot + is new or empty, the normalization result may be impractical. To avoid this, we add slot_dim to locate + the show number and judge if the show number is zero. If so, we choose to skip normalization on this + embedding. + sync_stats(bool, Default False): When running with multiple GPU cards, using allreduce to sync the + summary messages. + summary_decay_rate(float, Default 0.9999999): The decay rate when updating summary. + enable_scale_and_shift(bool, Default False): do scale&shift after normalization. + + Returns: + Tensor: A tensor which is the result after applying data normalization on the input. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.randn(shape=[32,100]) + hidden2 = paddle.static.nn.data_norm(input=x) + """ + helper = LayerHelper('data_norm', **locals()) + dtype = helper.input_dtype() + + input_shape = input.shape + if data_layout == 'NCHW': + channel_num = input_shape[1] + else: + if data_layout == 'NHWC': + channel_num = input_shape[-1] + else: + raise ValueError("unsupported data layout:" + data_layout) + + param_shape = [channel_num] + + batch_size_default = 1e4 + batch_sum_default = 0.0 + batch_square_sum_default = 1e4 + scale_w_default = 1.0 + bias_default = 0.0 + + if param_attr and isinstance(param_attr, dict): + batch_size_default = param_attr.get("batch_size", 1e4) + batch_sum_default = param_attr.get("batch_sum", 0.0) + batch_square_sum_default = param_attr.get("batch_square", 1e4) + if enable_scale_and_shift: + scale_w_default = param_attr.get("scale_w", 1.0) + bias_default = param_attr.get("bias", 0.0) + + # create scale and shift(bias) when enable_scale_and_shift is True + if name == None: + name = "dn" + if enable_scale_and_shift: + scale_w = helper.create_parameter( + attr=ParamAttr( + name=name + '.scale_w', + initializer=Constant(value=float(scale_w_default)), + trainable=True, + ), + shape=param_shape, + dtype=input.dtype, + ) + bias = helper.create_parameter( + attr=ParamAttr( + name=name + '.bias', + initializer=Constant(value=float(bias_default)), + trainable=True, + ), + shape=param_shape, + dtype=input.dtype, + ) + # create parameter + batch_size = helper.create_parameter( + attr=ParamAttr( + name=name + '.batch_size', + initializer=Constant(value=float(batch_size_default)), + trainable=True, + ), + shape=param_shape, + dtype=input.dtype, + ) + + batch_sum = helper.create_parameter( + attr=ParamAttr( + name=name + '.batch_sum', + initializer=Constant(value=float(batch_sum_default)), + trainable=True, + ), + shape=param_shape, + dtype=input.dtype, + ) + + batch_square_sum = helper.create_parameter( + attr=ParamAttr( + name=name + '.batch_square_sum', + initializer=Constant(value=float(batch_square_sum_default)), + trainable=True, + ), + shape=param_shape, + dtype=input.dtype, + ) + + means = helper.create_variable(dtype=dtype, stop_gradient=True) + scales = helper.create_variable(dtype=dtype, stop_gradient=True) + + data_norm_out = input if in_place else helper.create_variable(dtype=dtype) + + inputs = { + "X": input, + "BatchSize": batch_size, + "BatchSum": batch_sum, + "BatchSquareSum": batch_square_sum, + } + attrs = { + "epsilon": epsilon, + "data_layout": data_layout, + "sync_stats": sync_stats, + "summary_decay_rate": summary_decay_rate, + } + if slot_dim > 0: + attrs["slot_dim"] = slot_dim + if enable_scale_and_shift: + attrs["enable_scale_and_shift"] = enable_scale_and_shift + if enable_scale_and_shift: + inputs["scale_w"] = scale_w + inputs["bias"] = bias + helper.append_op( + type="data_norm", + inputs=inputs, + outputs={ + "Y": data_norm_out, + "Means": means, + "Scales": scales, + "BatchSize": batch_size, + "BatchSum": batch_sum, + "BatchSquareSum": batch_square_sum, + }, + attrs=attrs, + ) + + return helper.append_activation(data_norm_out) + + +@templatedoc() +def layer_norm( + input, + scale=True, + shift=True, + begin_norm_axis=1, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + act=None, + name=None, +): + r""" + :api_attr: Static Graph + + **Layer Normalization Layer** + + The API implements the function of the Layer Normalization Layer and can be applied to mini-batch input data. + Refer to `Layer Normalization `_ + + The formula is as follows: + + .. math:: + + \\mu & = \\frac{1}{H}\\sum_{i=1}^{H} x_i + + \\sigma & = \\sqrt{\\frac{1}{H}\sum_{i=1}^{H}{(x_i - \\mu)^2} + \\epsilon} + + y & = f(\\frac{g}{\\sigma}(x - \\mu) + b) + + - :math:`x`: the vector representation of the summed inputs to the neurons in that layer. + - :math:`H`: the number of hidden units in a layers + - :math:`\\epsilon`: the small value added to the variance to prevent division by zero. + - :math:`g`: the trainable scale parameter. + - :math:`b`: the trainable bias parameter. + + Args: + input(Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64. + scale(bool, optional): Whether to learn the adaptive gain :math:`g` after + normalization. Default: True. + shift(bool, optional): Whether to learn the adaptive bias :math:`b` after + normalization. Default: True. + begin_norm_axis(int, optional): The normalization will be performed along + dimensions from :attr:`begin_norm_axis` to :attr:`rank(input)`. + Default: 1. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + gain :math:`g`. If :attr:`scale` is False, :attr:`param_attr` is + omitted. If :attr:`scale` is True and :attr:`param_attr` is None, + a default :code:`ParamAttr` would be added as scale. The + :attr:`param_attr` is initialized as 1 if it is added. Default: None. + bias_attr(ParamAttr, optional): The parameter attribute for the learnable + bias :math:`b`. If :attr:`shift` is False, :attr:`bias_attr` is + omitted. If :attr:`shift` is True and :attr:`param_attr` is None, + a default :code:`ParamAttr` would be added as bias. The + :attr:`bias_attr` is initialized as 0 if it is added. Default: None. + act(str, optional): Activation to be applied to the output of layer normalization. + Default: None. + name(str): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: ``Tensor`` indicating the normalized result, the data type is the same as ``input`` , and the return dimension is the same as ``input`` . + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + x = paddle.static.data(name='x', shape=[8, 32, 32], dtype='float32') + output = paddle.static.nn.layer_norm(input=x, begin_norm_axis=1) + print(output.shape) # [8, 32, 32] + """ + assert ( + _non_static_mode() is not True + ), "please use LayerNorm instead of layer_norm in dygraph mode!" + helper = LayerHelper('layer_norm', **locals()) + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'layer_norm' + ) + dtype = helper.input_dtype() + + # create intput and parameters + inputs = {'X': input} + input_shape = input.shape + param_shape = [reduce(lambda x, y: x * y, input_shape[begin_norm_axis:])] + if scale: + assert ( + param_attr is not False + ), "param_attr should not be False when using scale." + scale = helper.create_parameter( + attr=helper.param_attr, + shape=param_shape, + dtype=dtype, + default_initializer=Constant(1.0), + ) + inputs['Scale'] = scale + else: + if param_attr: + warnings.warn("param_attr is only available with scale is True.") + if shift: + assert ( + bias_attr is not False + ), "bias_attr should not be False when using shift." + bias = helper.create_parameter( + attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True + ) + inputs['Bias'] = bias + else: + if bias_attr: + warnings.warn("bias_attr is only available with shift is True.") + + # create output + mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + layer_norm_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type="layer_norm", + inputs=inputs, + outputs={ + "Y": layer_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={"epsilon": epsilon, "begin_norm_axis": begin_norm_axis}, + ) + + return helper.append_activation(layer_norm_out) + + +@templatedoc() +def group_norm( + input, + groups, + epsilon=1e-05, + param_attr=None, + bias_attr=None, + act=None, + data_layout='NCHW', + name=None, +): + """ + :api_attr: Static Graph + + **Group Normalization Layer** + + Refer to `Group Normalization `_ . + + Parameters: + input(Tensor): Tensor with dimension greater than 1, the data type is float32 or float64. + groups(int): The number of groups that divided from channels, the data type + is int32. + epsilon(float, optional): The small value added to the variance to prevent + division by zero, the data type is float32. Default: 1e-05. + param_attr(ParamAttr|bool, optional): ParamAttr object that specifies weight parameter + attribute. If a bool type, only False is supported, which means there is no weight parameter. + Default: None, the default weight parameter attribute is used. For more information, please + refer to :ref:`api_guide_ParamAttr` . + bias_attr(ParamAttr|bool, optional): ParamAttr object that specifies bias parameter + attribute. If a bool type, only False is supported, which means there is no bias parameter. + Default: None, the default bias parameter attribute is used. For more information, please + refer to :ref:`api_guide_ParamAttr` . + act(str, optional): Activation to be applied to the output of group normalization. + data_layout(str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, *]`. + name (str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: A Tensor has same data type and data format with `input`. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + data = paddle.static.data(name='data', shape=[2, 8, 32, 32], dtype='float32') + x = paddle.static.nn.group_norm(input=data, groups=4) + print(x.shape) # [2, 8, 32, 32] + """ + helper = LayerHelper('group_norm', **locals()) + dtype = helper.input_dtype() + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'group_norm' + ) + # create intput and parameters + inputs = {'X': input} + input_shape = input.shape + if len(input_shape) < 2: + raise ValueError( + f"The dimensions of Op(fluid.layers.group_norm)'s input should be more than 1. But received {len(input_shape)}" + ) + if data_layout != 'NCHW' and data_layout != 'NHWC': + raise ValueError( + "Param(data_layout) of Op(fluid.layers.group_norm) got wrong value: received " + + data_layout + + " but only NCHW or NHWC supported." + ) + channel_num = input_shape[1] if data_layout == 'NCHW' else input_shape[-1] + param_shape = [channel_num] + if param_attr: + scale = helper.create_parameter( + attr=helper.param_attr, + shape=param_shape, + dtype=dtype, + default_initializer=Constant(1.0), + ) + inputs['Scale'] = scale + if bias_attr: + bias = helper.create_parameter( + attr=helper.bias_attr, shape=param_shape, dtype=dtype, is_bias=True + ) + inputs['Bias'] = bias + + # create output + mean_out = helper.create_variable(dtype=dtype, stop_gradient=True) + variance_out = helper.create_variable(dtype=dtype, stop_gradient=True) + group_norm_out = helper.create_variable(dtype=dtype) + + helper.append_op( + type="group_norm", + inputs=inputs, + outputs={ + "Y": group_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={ + "epsilon": epsilon, + "groups": groups, + "data_layout": data_layout, + }, + ) + + return helper.append_activation(group_norm_out) + + +@templatedoc() +def spectral_norm(weight, dim=0, power_iters=1, eps=1e-12, name=None): + r""" + :api_attr: Static Graph + + **Spectral Normalization Layer** + + This operation calculates the spectral normalization value of weight parameters of + fc, conv1d, conv2d, conv3d layers which should be 2-D, 3-D, 4-D, 5-D + Parameters. Output tensor will be in same shape with input tensor. + Calculations are showed as follows. + + Step 1: + Generate vector U in shape of [H], and V in shape of [W]. + While H is the :attr:`dim` th dimension of the input weights, + and W is the product result of remaining dimensions. + + Step 2: + :attr:`power_iters` should be a positive integer, do following + calculations with U and V for :attr:`power_iters` rounds. Calculations + as follows: + + .. math:: + + \mathbf{v} := \\frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} + + \mathbf{u} := \\frac{\mathbf{W}^{T} \mathbf{v}}{\|\mathbf{W}^{T} \mathbf{v}\|_2} + + Step 3: + Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. + + .. math:: + + \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} + + \mathbf{W} = \\frac{\mathbf{W}}{\sigma(\mathbf{W})} + + + Refer to `Spectral Normalization `_ . + + Args: + weight(Tensor): ${weight_comment} + dim(int): ${dim_comment} + power_iters(int): ${power_iters_comment} + eps(float): ${eps_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: A tensor of weight parameters after spectral normalization. + The data type and shape is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + weight = paddle.static.data(name='weight', shape=[2, 8, 32, 32], dtype='float32') + x = paddle.static.nn.spectral_norm(weight=weight, dim=1, power_iters=2) + print(x.shape) # [2, 8, 32, 32] + """ + helper = LayerHelper('spectral_norm', **locals()) + check_variable_and_dtype( + weight, 'weight', ['float32', 'float64'], 'spectral_norm' + ) + check_type(dim, 'dim', int, 'spectral_norm') + check_type(power_iters, 'power_iters', int, 'spectral_norm') + check_type(eps, 'eps', float, 'spectral_norm') + dtype = weight.dtype + + # create intput and parameters + input_shape = weight.shape + assert weight.numel() > 0, "Any dimension of input cannot be equal to 0." + assert dim < len(input_shape), ( + "The input `dim` should be less than the " + "rank of `weight`, but received dim=" + "{}".format(dim) + ) + h = input_shape[dim] + w = np.prod(input_shape) // h + + u = helper.create_parameter( + attr=ParamAttr(), + shape=[h], + dtype=dtype, + default_initializer=Normal(0.0, 1.0), + ) + u.stop_gradient = True + v = helper.create_parameter( + attr=ParamAttr(), + shape=[w], + dtype=dtype, + default_initializer=Normal(0.0, 1.0), + ) + v.stop_gradient = True + + if in_dygraph_mode(): + return _C_ops.spectral_norm(weight, u, v, dim, power_iters, eps) + + inputs = {'Weight': weight} + inputs['U'] = u + inputs['V'] = v + + # create output + out = helper.create_variable(dtype=dtype) + + helper.append_op( + type="spectral_norm", + inputs=inputs, + outputs={ + "Out": out, + }, + attrs={ + "dim": dim, + "power_iters": power_iters, + "eps": eps, + }, + ) + + return out + + +def conv2d_transpose( + input, + num_filters, + output_size=None, + filter_size=None, + padding=0, + stride=1, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + name=None, + data_format='NCHW', +): + r""" + :api_attr: Static Graph + + The convolution2D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCHW or NHWC format. Where N is batch size, C is the number of channels, + H is the height of the feature, and W is the width of the feature. + Parameters(dilations, strides, paddings) are two elements. These two elements + represent height and width, respectively. The details of convolution transpose + layer, please refer to the following explanation and references + `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \\ast X + b) + + Where: + + * :math:`X`: Input value, a 4-D Tensor with NCHW or NHWC format. + * :math:`W`: Filter value, a 4-D Tensor with MCHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, a 4-D Tensor with data format 'NCHW' or 'NHWC', the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H^\prime_{out} &= (H_{in} - 1) * strides[0] - pad_height_top - pad_height_bottom + dilations[0] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[1] - pad_width_left - pad_width_right + dilations[1] * (W_f - 1) + 1 \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ] \\\\ + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ] + + Note: + The conv2d_transpose can be seen as the backward of the conv2d. For conv2d, + when stride > 1, conv2d maps multiple input shape to the same output shape, + so for conv2d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, W_{out} = W^\prime_{out}`; + else, the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[0]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[1]`, + conv2d_transpose can compute the kernel size automatically. + + Args: + input(Tensor): 4-D Tensor with [N, C, H, W] or [N, H, W, C] format, + its data type is float32 or float64. + num_filters(int): The number of the filter. It is as same as the output + image channel. + output_size(int|tuple, optional): The output image size. If output size is a + tuple, it must contain two integers, (image_height, image_width). None if use + filter_size, padding, and stride to calculate output_size. + If output_size and filter_size are specified at the same time, They + should follow the formula above. Default: None. output_size and filter_size + should not be None at the same time. + filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_height, filter_size_width). + Otherwise, filter_size_height = filter_size_width = filter_size. None if + use output size to calculate filter_size. Default: None. filter_size and + output_size should not be None at the same time. + stride(int|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a tuple, it must contain two integers, (stride_height, stride_width). + Otherwise, stride_height = stride_width = stride. Default: stride = 1. + padding(str|int|list|tuple, optional): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If `padding` is a tuple or list, + it could be in three forms: `[pad_height, pad_width]` or + `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `padding` can be in the form + `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a tuple, it must contain two integers, (dilation_height, dilation_width). + Otherwise, dilation_height = dilation_width = dilation. Default: dilation = 1. + filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_height, filter_size_width). + Otherwise, filter_size_height = filter_size_width = filter_size. None if + use output size to calculate filter_size. Default: None. + groups(int, optional): The groups number of the Conv2d transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups = 1. + param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv2d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True. + act (str, optional): Activation type, if it is set to None, activation is not appended. + Default: None. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + A Tensor representing the conv2d_transpose, whose + data type is the same with input and shape is (num_batches, channels, out_h, + out_w) or (num_batches, out_h, out_w, channels). If act is None, the tensor + storing the transposed convolution result, and if act is not None, the + tensor storing transposed convolution and non-linearity activation + result. + + Raises: + ValueError: If the type of `use_cudnn` is not bool. + ValueError: If `data_format` is not "NCHW" or "NHWC". + ValueError: If `padding` is a string, but not "SAME" or "VALID". + ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 + or the element corresponding to the input's channel is not 0. + ValueError: If `output_size` and filter_size are None at the same time. + ShapeError: If the input is not 4-D Tensor. + ShapeError: If the input's dimension size and filter's dimension size not equal. + ShapeError: If the dimension size of input minus the size of `stride` is not 2. + ShapeError: If the number of input channels is not equal to filter's channels. + ShapeError: If the size of `output_size` is not equal to that of `stride`. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + data = paddle.static.data(name='data', shape=[None, 3, 32, 32], dtype='float32') + conv2d_transpose = paddle.static.nn.conv2d_transpose(input=data, num_filters=2, filter_size=3) + print(conv2d_transpose.shape) # [-1, 2, 34, 34] + """ + assert ( + param_attr is not False + ), "param_attr should not be False in conv2d_transpose." + if len(input.shape) != 4: + raise ValueError( + "Input size should be 4, " + "but received {}".format(len(input.shape)) + ) + + if data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Attr(data_format) of Op(fluid.layers.conv2d_transpose) got wrong value: received " + + data_format + + " but only NCHW or NHWC supported." + ) + + input_channel = input.shape[1] if data_format == 'NCHW' else input.shape[-1] + op_type = 'conv2d_transpose' + if ( + input_channel == groups + and num_filters == input_channel + and not use_cudnn + ): + op_type = 'depthwise_conv2d_transpose' + + helper = LayerHelper(op_type, **locals()) + if not isinstance(input, Variable): + raise TypeError("Input of conv2d_transpose must be Variable") + + stride = utils.convert_to_list(stride, 2, 'stride') + dilation = utils.convert_to_list(dilation, 2, 'dilation') + + if not isinstance(use_cudnn, bool): + raise ValueError("use_cudnn should be True or False") + + def _update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, list) or isinstance(ele, tuple): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 4: + if is_list_or_tuple(padding[0]) and (data_format == "NCHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:4] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NHWC"): + if not (padding[0] == [0, 0] and padding[3] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:3] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 4, 'padding') + else: + padding = utils.convert_to_list(padding, 2, 'padding') + padding = [padding[0], padding[0], padding[1], padding[1]] + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." + % str(padding) + ) + if padding == "VALID": + padding_algorithm = "VALID" + padding = [0, 0, 0, 0] + elif padding == "SAME": + padding_algorithm = "SAME" + padding = [0, 0, 0, 0] + + padding = _update_padding(padding, data_format) + + if output_size is None: + output_size = [] + elif isinstance(output_size, (list, tuple)): + if utils._contain_var(output_size): + output_size = utils._convert_to_tensor_list(output_size) + else: + output_size = utils.convert_to_list(output_size, 2, 'output_size') + elif isinstance(output_size, int): + output_size = utils.convert_to_list(output_size, 2, 'output_size') + elif isinstance(output_size, Variable): + check_dtype( + output_size.dtype, + 'output_size', + ['int32', 'int64'], + 'conv2d_transpose', + ) + if len(output_size.shape) == 1 and ( + output_size.shape[0] == 1 or output_size.shape[0] == 2 + ): + if output_size.shape[0] == 1: + output_size = [output_size, output_size] + else: + raise ValueError("output_size must contain one or two integers.") + else: + raise ValueError( + "output_size should be int, list[int] or tuple[int] or Tensor" + ) + + if filter_size is None: + if output_size is []: + raise ValueError("output_size must be set when filter_size is None") + if not _non_static_mode(): + if isinstance(output_size, Variable) or utils._contain_var( + output_size + ): + raise ValueError( + "filter_size should not be None when output_size is Variable or contain Variable in static mode." + ) + else: + output_size = utils.convert_shape_to_list(output_size) + if len(output_size) == 1: + output_size = utils.convert_to_list( + output_size[0], 2, 'output_size' + ) + + h_in = input.shape[2] if data_format == 'NCHW' else input.shape[1] + w_in = input.shape[3] if data_format == 'NCHW' else input.shape[2] + + filter_size_h = ( + output_size[0] + - (h_in - 1) * stride[0] + + padding[0] + + padding[1] + - 1 + ) // dilation[0] + 1 + filter_size_w = ( + output_size[1] + - (w_in - 1) * stride[1] + + padding[2] + + padding[3] + - 1 + ) // dilation[1] + 1 + filter_size = [filter_size_h, filter_size_w] + else: + filter_size = utils.convert_to_list( + filter_size, 2, 'conv2d_transpose.filter_size' + ) + + if len(padding) == 4 and utils._is_symmetric_padding(padding, 2): + padding = [padding[0], padding[2]] + + if groups is None: + groups = 1 + elif groups <= 0: + raise ValueError( + "the groups of input must be greater than 0, " + "but received the groups of input is {}".format(groups) + ) + + filter_shape = [input_channel, num_filters // groups] + filter_size + + img_filter = helper.create_parameter( + dtype=input.dtype, shape=filter_shape, attr=helper.param_attr + ) + + pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type=op_type, + inputs={'Input': [input], 'Filter': [img_filter]}, + outputs={'Output': pre_bias}, + attrs={ + 'output_size': output_size, + 'strides': stride, + 'paddings': padding, + 'padding_algorithm': padding_algorithm, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'data_format': data_format, + }, + ) + + if data_format == 'NCHW': + pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) + else: + pre_act = helper.append_bias_op(pre_bias, dim_start=3, dim_end=4) + out = helper.append_activation(pre_act) + return out + + +def conv3d_transpose( + input, + num_filters, + output_size=None, + filter_size=None, + padding=0, + stride=1, + dilation=1, + groups=None, + param_attr=None, + bias_attr=None, + use_cudnn=True, + act=None, + name=None, + data_format='NCDHW', +): + r""" + :api_attr: Static Graph + + The convolution3D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCDHW or NDHWC format. Where N is batch size, C is the number of channels, + D is the depth of the feature, H is the height of the feature, and W + is the width of the feature. Parameters(dilations, strides, paddings) are + two elements. These two elements represent height and width, respectively. + The details of convolution transpose layer, please refer to the following + explanation and references `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a Tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a Tensor with MCDHW format. + * :math:`\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\\\ + H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\\\ + D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\\\ + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[2] ] + + Note: + The conv3d_transpose can be seen as the backward of the conv3d. For conv3d, + when stride > 1, conv3d maps multiple input shape to the same output shape, + so for conv3d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \ + H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output + size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`, + the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`, + conv3d_transpose can compute the kernel size automatically. + + Args: + input(Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C], the data type + of input is float32 or float64. + num_filters(int): The number of the filter. It is as same as the output + image channel. + output_size(int|tuple, optional): The output image size. If output size is a + tuple, it must contain three integers, (image_depth, image_height, image_width). This + parameter only works when filter_size is None. If output_size and filter_size are + specified at the same time, They should follow the formula above. Default: None. + Output_size and filter_size should not be None at the same time. + filter_size(int|tuple, optional): The filter size. If filter_size is a tuple, + it must contain three integers, (filter_size_depth, filter_size_height, + filter_size_width). Otherwise, filter_size_depth = filter_size_height = \ + filter_size_width = filter_size. None if use output size to + calculate filter_size. Default: None. filter_size and output_size should not be + None at the same time. + padding(int|list|str|tuple, optional): The padding size. The padding argument effectively + adds `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a string, + either 'VALID' or 'SAME' supported, which is the padding algorithm. If `padding` + is a tuple or list, it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `'NCDHW'`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `'NDHWC'`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + stride(int|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a tuple, it must contain three integers, (stride_depth, stride_height, + stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. + Default: stride = 1. + dilation(int|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups(int, optional): The groups number of the Conv3d transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups=1 + param_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + use_cudnn(bool, optional): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True + act (str, optional): Activation type, if it is set to None, activation is not appended. + Default: None. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + A Variable holding Tensor representing the conv3d_transpose, whose data + type is the same with input and shape is (num_batches, channels, out_d, out_h, + out_w) or (num_batches, out_d, out_h, out_w, channels). If act is None, the tensor + variable storing the transposed convolution result, and if act is not None, the tensor + variable storing transposed convolution and non-linearity activation result. + + Raises: + ValueError: If the type of `use_cudnn` is not bool. + ValueError: If `data_format` is not "NCDHW" or "NDHWC". + ValueError: If `padding` is a string, but not "SAME" or "VALID". + ValueError: If `padding` is a tuple, but the element corresponding to the input's batch size is not 0 + or the element corresponding to the input's channel is not 0. + ValueError: If `output_size` and filter_size are None at the same time. + ShapeError: If the input is not 5-D Tensor. + ShapeError: If the input's dimension size and filter's dimension size not equal. + ShapeError: If the dimension size of input minus the size of `stride` is not 2. + ShapeError: If the number of input channels is not equal to filter's channels. + ShapeError: If the size of `output_size` is not equal to that of `stride`. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + paddle.enable_static() + data = paddle.static.data(name='data', shape=[None, 3, 12, 32, 32], dtype='float32') + param_attr = paddle.framework.ParamAttr(name='conv3d.weight', initializer=paddle.nn.initializer.XavierNormal(), learning_rate=0.001) + res = paddle.static.nn.conv3d_transpose(input=data, num_filters=2, filter_size=3, act="relu", param_attr=param_attr) + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + x = np.random.rand(1, 3, 12, 32, 32).astype("float32") + output = exe.run(feed={"data": x}, fetch_list=[res]) + print(output) + """ + assert ( + param_attr is not False + ), "param_attr should not be False in conv3d_transpose." + if data_format not in ['NCDHW', 'NDHWC']: + raise ValueError( + "Param(data_format) of Op(fluid.layers.conv3d_transpose) got wrong value: received " + + data_format + + " but only NCDHW or NDHWC supported." + ) + + l_type = "conv3d_transpose" + helper = LayerHelper(l_type, **locals()) + if not isinstance(input, Variable): + raise TypeError("Input of conv3d_transpose must be Variable") + if len(input.shape) != 5: + raise ValueError( + "Input should be 5D tensor, but received input with the shape of {}".format( + input.shape + ) + ) + input_channel = ( + input.shape[1] if data_format == 'NCDHW' else input.shape[-1] + ) + + stride = utils.convert_to_list(stride, 3, 'stride') + dilation = utils.convert_to_list(dilation, 3, 'dilation') + + if not isinstance(use_cudnn, bool): + raise ValueError("use_cudnn should be True or False") + + def _update_padding(padding, data_format): + def is_list_or_tuple(ele): + if isinstance(ele, list) or isinstance(ele, tuple): + return True + return False + + if is_list_or_tuple(padding) and len(padding) == 5: + if is_list_or_tuple(padding[0]) and (data_format == "NCDHW"): + if not (padding[0] == [0, 0] and padding[1] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[2:5] + padding = [ele for a_list in padding for ele in a_list] + elif is_list_or_tuple(padding[0]) and (data_format == "NDHWC"): + if not (padding[0] == [0, 0] and padding[4] == [0, 0]): + raise ValueError( + "Non-zero padding(%s) in the batch or channel dimensions " + "is not supported." % str(padding) + ) + padding = padding[1:4] + padding = [ele for a_list in padding for ele in a_list] + padding = utils.convert_to_list(padding, 6, 'padding') + + elif is_list_or_tuple(padding) and len(padding) == 6: + padding = utils.convert_to_list(padding, 6, 'padding') + + else: + padding = utils.convert_to_list(padding, 3, 'padding') + padding = [ + padding[0], + padding[0], + padding[1], + padding[1], + padding[2], + padding[2], + ] + return padding + + padding_algorithm = "EXPLICIT" + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '%s'. It can only be 'SAME' or 'VALID'." + % str(padding) + ) + if padding == "VALID": + padding_algorithm = "VALID" + padding = [0, 0, 0, 0, 0, 0] + elif padding == "SAME": + padding_algorithm = "SAME" + padding = [0, 0, 0, 0, 0, 0] + + padding = _update_padding(padding, data_format) + + if filter_size is None: + if output_size is None: + raise ValueError("output_size must be set when filter_size is None") + if isinstance(output_size, int): + output_size = [output_size, output_size, output_size] + + d_in = input.shape[2] if data_format == 'NCDHW' else input.shape[1] + h_in = input.shape[3] if data_format == 'NCDHW' else input.shape[2] + w_in = input.shape[4] if data_format == 'NCDHW' else input.shape[3] + + filter_size_d = ( + output_size[0] + - (d_in - 1) * stride[0] + + padding[0] + + padding[1] + - 1 + ) // dilation[0] + 1 + filter_size_h = ( + output_size[1] + - (h_in - 1) * stride[1] + + padding[2] + + padding[3] + - 1 + ) // dilation[1] + 1 + filter_size_w = ( + output_size[2] + - (w_in - 1) * stride[2] + + padding[4] + + padding[5] + - 1 + ) // dilation[2] + 1 + filter_size = [filter_size_d, filter_size_h, filter_size_w] + else: + filter_size = utils.convert_to_list( + filter_size, 3, 'conv3d_transpose.filter_size' + ) + + if len(padding) == 6 and utils._is_symmetric_padding(padding, 3): + padding = [padding[0], padding[2], padding[4]] + + if output_size is None: + output_size = [] + elif isinstance(output_size, (list, tuple, int)): + output_size = utils.convert_to_list(output_size, 3, 'output_size') + else: + raise ValueError("output_size should be int, list[int] or tuple[int]") + + groups = 1 if groups is None else groups + if groups <= 0: + raise ValueError( + "the groups of conv3d_transpose should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_filters % groups != 0: + raise ValueError( + "Attr(num_filters) must be divisible by groups," + "Received: Attr(num_filters) is {}, the groups is {}".format( + num_filters, groups + ) + ) + + filter_shape = [input_channel, num_filters // groups] + filter_size + img_filter = helper.create_parameter( + dtype=input.dtype, shape=filter_shape, attr=helper.param_attr + ) + + if data_format == 'NCDHW': + data_format = 'NCHW' + if data_format == 'NDHWC': + data_format = 'NHWC' + + pre_bias = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type=l_type, + inputs={'Input': [input], 'Filter': [img_filter]}, + outputs={'Output': pre_bias}, + attrs={ + 'output_size': output_size, + 'strides': stride, + 'paddings': padding, + 'padding_algorithm': padding_algorithm, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'data_format': data_format, + }, + ) + + if data_format == 'NCHW': + pre_act = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) + else: + pre_act = helper.append_bias_op(pre_bias, dim_start=4, dim_end=5) + out = helper.append_activation(pre_act) + return out + + +def reduce_sum(input, dim=None, keep_dim=False, name=None): + """ + + Computes the sum of tensor elements over the given dimension. + + Args: + input (Variable): The input variable which is a Tensor, the data type is float32, + float64, int32, int64. + dim (list|int, optional): The dimensions along which the sum is performed. If + :attr:`None`, sum all elements of :attr:`input` and return a + Tensor variable with a single element, otherwise must be in the + range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, + the dimension to reduce is :math:`rank + dim[i]`. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true, default + value is False. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: Tensor, results of summation operation on the specified dim of input tensor, + it's data type is the same as input's Tensor. + + Raises: + TypeError, if out data type is different with the input data type. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # x is a Tensor variable with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = fluid.data(name='x', shape=[2, 4], dtype='float32') + fluid.layers.reduce_sum(x) # [3.5] + fluid.layers.reduce_sum(x, dim=0) # [0.3, 0.5, 1.1, 1.6] + fluid.layers.reduce_sum(x, dim=-1) # [1.9, 1.6] + fluid.layers.reduce_sum(x, dim=1, keep_dim=True) # [[1.9], [1.6]] + + # y is a Tensor variable with shape [2, 2, 2] and elements as below: + # [[[1, 2], [3, 4]], + # [[5, 6], [7, 8]]] + # Each example is followed by the corresponding output tensor. + y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') + fluid.layers.reduce_sum(y, dim=[1, 2]) # [10, 26] + fluid.layers.reduce_sum(y, dim=[0, 1]) # [16, 20] + + """ + if dim is not None and not isinstance(dim, list): + dim = [dim] + + if in_dygraph_mode(): + reduce_all = ( + True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False + ) + dim = dim if dim != None and dim != [] else [0] + if reduce_all: + return _C_ops.sum(input, [], None, keep_dim) + else: + return _C_ops.sum(input, dim, None, keep_dim) + elif _in_legacy_dygraph(): + reduce_all = ( + True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False + ) + dim = dim if dim != None and dim != [] else [0] + return _legacy_C_ops.reduce_sum( + input, 'dim', dim, 'keep_dim', keep_dim, 'reduce_all', reduce_all + ) + attrs = { + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + } + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'reduce_sum', + ) + helper = LayerHelper('reduce_sum', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op( + type='reduce_sum', + inputs={'X': input}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.mean") +def reduce_mean(input, dim=None, keep_dim=False, name=None): + """ + Computes the mean of the input tensor's elements along the given dimension. + + Args: + input (Variable): The input variable which is a Tensor, the data type is float32, + float64, int32, int64. + dim (list|int, optional): The dimension along which the mean is computed. If + `None`, compute the mean over all elements of :attr:`input` + and return a variable with a single element, otherwise it + must be in the range :math:`[-rank(input), rank(input))`. If + :math:`dim[i] < 0`, the dimension to reduce is + :math:`rank(input) + dim[i]`. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true, default + value is False. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: Tensor, results of average on the specified dim of input tensor, + it's data type is the same as input's Tensor. + + Raises: + TypeError, if out data type is different with the input data type. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # x is a Tensor variable with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = fluid.data(name='x', shape=[2, 4], dtype='float32') + fluid.layers.reduce_mean(x) # [0.4375] + fluid.layers.reduce_mean(x, dim=0) # [0.15, 0.25, 0.55, 0.8] + fluid.layers.reduce_mean(x, dim=-1) # [0.475, 0.4] + fluid.layers.reduce_mean(x, dim=1, keep_dim=True) # [[0.475], [0.4]] + + # y is a Tensor variable with shape [2, 2, 2] and elements as below: + # [[[1.0, 2.0], [3.0, 4.0]], + # [[5.0, 6.0], [7.0, 8.0]]] + # Each example is followed by the corresponding output tensor. + y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') + fluid.layers.reduce_mean(y, dim=[1, 2]) # [2.5, 6.5] + fluid.layers.reduce_mean(y, dim=[0, 1]) # [4.0, 5.0] + """ + + return paddle.mean(x=input, axis=dim, keepdim=keep_dim, name=name) + + +def reduce_max(input, dim=None, keep_dim=False, name=None): + """ + + Computes the maximum of tensor elements over the given dimension. + + Args: + input (Variable): The input variable which is a Tensor, the data type is float32, + float64, int32, int64. + dim (list|int, optional): The dimension along which the maximum is computed. + If :attr:`None`, compute the maximum over all elements of + :attr:`input` and return a Tensor variable with a single element, + otherwise must be in the range :math:`[-rank(input), rank(input))`. + If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true, default + value is False. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: Tensor, results of maximum on the specified dim of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # x is a Tensor variable with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = fluid.data(name='x', shape=[2, 4], dtype='float32') + fluid.layers.reduce_max(x) # [0.9] + fluid.layers.reduce_max(x, dim=0) # [0.2, 0.3, 0.6, 0.9] + fluid.layers.reduce_max(x, dim=-1) # [0.9, 0.7] + fluid.layers.reduce_max(x, dim=1, keep_dim=True) # [[0.9], [0.7]] + + # y is a Tensor variable with shape [2, 2, 2] and elements as below: + # [[[1.0, 2.0], [3.0, 4.0]], + # [[5.0, 6.0], [7.0, 8.0]]] + # Each example is followed by the corresponding output tensor. + y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') + fluid.layers.reduce_max(y, dim=[1, 2]) # [4.0, 8.0] + fluid.layers.reduce_max(y, dim=[0, 1]) # [7.0, 8.0] + """ + helper = LayerHelper('reduce_max', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + + if dim is not None and not isinstance(dim, list): + dim = [dim] + + if in_dygraph_mode(): + return _C_ops.max(input, dim if dim != None else [], keep_dim) + + helper.append_op( + type='reduce_max', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + }, + ) + return out + + +def reduce_min(input, dim=None, keep_dim=False, name=None): + """ + + Computes the minimum of tensor elements over the given dimension. + + Args: + input (Variable): The input variable which is a Tensor, the data type is float32, + float64, int32, int64. + dim (list|int, optional): The dimensions along which the minimum is computed. + If :attr:`None`, compute the minimum over all elements of + :attr:`input` and return a Tensor variable with a single element, + otherwise must be in the range :math:`[-rank(input), rank(input))`. + If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true, default + value is False. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: Tensor, result of minimum on the specified dim of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + # x is a Tensor variable with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = fluid.data(name='x', shape=[2, 4], dtype='float32') + fluid.layers.reduce_min(x) # [0.1] + fluid.layers.reduce_min(x, dim=0) # [0.1, 0.2, 0.5, 0.7] + fluid.layers.reduce_min(x, dim=-1) # [0.2, 0.1] + fluid.layers.reduce_min(x, dim=1, keep_dim=True) # [[0.2], [0.1]] + + # y is a Tensor variable with shape [2, 2, 2] and elements as below: + # [[[1.0, 2.0], [3.0, 4.0]], + # [[5.0, 6.0], [7.0, 8.0]]] + # Each example is followed by the corresponding output tensor. + y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') + fluid.layers.reduce_min(y, dim=[1, 2]) # [1.0, 5.0] + fluid.layers.reduce_min(y, dim=[0, 1]) # [1.0, 2.0] + """ + helper = LayerHelper('reduce_min', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + if dim is not None and not isinstance(dim, list): + dim = [dim] + + if in_dygraph_mode(): + return _C_ops.min(input, dim if dim != None else [], keep_dim) + + helper.append_op( + type='reduce_min', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + }, + ) + return out + + +def reduce_prod(input, dim=None, keep_dim=False, name=None): + """ + + Computes the product of tensor elements over the given dimension. + + Args: + input (Variable): The input variable which is a Tensor, the data type is float32, + float64, int32, int64. + dim (int|list|tuple, optional): The dimensions along which the product is performed. If + :attr:`None`, multiply all elements of :attr:`input` and return a + Tensor variable with a single element, otherwise must be in the + range :math:`[-rank(input), rank(input))`. If :math:`dim[i] < 0`, + the dimension to reduce is :math:`rank + dim[i]`. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true, default + value is False. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: Tensor, result of product on the specified dim of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # x is a Tensor variable with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = fluid.data(name='x', shape=[2, 4], dtype='float32') + fluid.layers.reduce_prod(x) # [0.0002268] + fluid.layers.reduce_prod(x, dim=0) # [0.02, 0.06, 0.3, 0.63] + fluid.layers.reduce_prod(x, dim=-1) # [0.027, 0.0084] + fluid.layers.reduce_prod(x, dim=1, + keep_dim=True) # [[0.027], [0.0084]] + + # y is a Tensor variable with shape [2, 2, 2] and elements as below: + # [[[1.0, 2.0], [3.0, 4.0]], + # [[5.0, 6.0], [7.0, 8.0]]] + # Each example is followed by the corresponding output tensor. + y = fluid.data(name='y', shape=[2, 2, 2], dtype='float32') + fluid.layers.reduce_prod(y, dim=[1, 2]) # [24.0, 1680.0] + fluid.layers.reduce_prod(y, dim=[0, 1]) # [105.0, 384.0] + """ + + if dim is not None and not isinstance(dim, list): + if isinstance(dim, tuple): + dim = list(dim) + elif isinstance(dim, int): + dim = [dim] + else: + raise TypeError( + "The type of axis must be int, list or tuple, but received {}".format( + type(dim) + ) + ) + if in_dygraph_mode(): + return _C_ops.reduce_prod( + input, + dim if dim != None and dim != [] else [0], + keep_dim, + True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + ) + + helper = LayerHelper('reduce_prod', **locals()) + check_variable_and_dtype( + input, 'input', ['float32', 'float64', 'int32', 'int64'], 'reduce_prod' + ) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op( + type='reduce_prod', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + }, + ) + return out + + +def reduce_all(input, dim=None, keep_dim=False, name=None): + """ + + This OP computes the ``logical and`` of tensor elements over the given dimension, and output the result. + + Args: + input (Tensor): the input tensor, it's data type should be `bool`. + dim (list|int|optional): The dimension along which the logical and is computed. + If :attr:`None`, compute the logical and over all elements of + :attr:`input` and return a Tensor variable with a single element, + otherwise must be in the range :math:`[-rank(input), rank(input))`. + If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. The default value is None. + keep_dim (bool): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true. The default value is False. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. The default value is None. + + Returns: + Tensor, the output data type is bool. : The reduced tensor variable with ``logical and`` in given dims. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.fluid.layers as layers + import numpy as np + + # x is a bool Tensor variable with following elements: + # [[True, False] + # [True, True]] + x = fluid.layers.assign(np.array([[1, 0], [1, 1]], dtype='int32')) + x = fluid.layers.cast(x, 'bool') + + out = fluid.layers.reduce_all(x) # False + out = fluid.layers.reduce_all(x, dim=0) # [True, False] + out = fluid.layers.reduce_all(x, dim=-1) # [False, True] + # keep_dim=False, x.shape=(2,2), out.shape=(2,) + + out = fluid.layers.reduce_all(x, dim=1, keep_dim=True) # [[False], [True]] + # keep_dim=True, x.shape=(2,2), out.shape=(2,1) + + """ + if dim is not None and not isinstance(dim, list): + dim = [dim] + + if in_dygraph_mode(): + return _C_ops.all(input, dim if dim != None else [], keep_dim) + + check_variable_and_dtype(input, 'input', ('bool'), 'reduce_all') + helper = LayerHelper('reduce_all', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op( + type='reduce_all', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + }, + ) + return out + + +def reduce_any(input, dim=None, keep_dim=False, name=None): + """ + This OP computes the ``logical or`` of tensor elements over the given dimension, and output the result. + + Args: + input (Tensor): the input tensor, it's data type should be `bool`. + dim (list|int|optional): The dimension along which the logical and is computed. + If :attr:`None`, compute the logical and over all elements of + :attr:`input` and return a Tensor variable with a single element, + otherwise must be in the range :math:`[-rank(input), rank(input))`. + If :math:`dim[i] < 0`, the dimension to reduce is :math:`rank + dim[i]`. The default value is None. + keep_dim (bool): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the :attr:`input` unless :attr:`keep_dim` is true. The default value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the output data type is bool. : The reduced tensor variable with ``logical or`` in given dims. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.fluid.layers as layers + import numpy as np + + # x is a bool Tensor variable with following elements: + # [[True, False] + # [False, False]] + x = fluid.layers.assign(np.array([[1, 0], [0, 0]], dtype='int32')) + x = fluid.layers.cast(x, 'bool') + + out = fluid.layers.reduce_any(x) # True + out = fluid.layers.reduce_any(x, dim=0) # [True, False] + out = fluid.layers.reduce_any(x, dim=-1) # [True, False] + # keep_dim=False, x.shape=(2,2), out.shape=(2,) + + out = fluid.layers.reduce_any(x, dim=1, + keep_dim=True) # [[True], [False]] + # keep_dim=True, x.shape=(2,2), out.shape=(2,1) + + """ + check_variable_and_dtype(input, 'input', ('bool'), 'reduce_any') + helper = LayerHelper('reduce_any', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + if dim is not None and not isinstance(dim, list): + dim = [dim] + helper.append_op( + type='reduce_any', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'dim': dim if dim != None and dim != [] else [0], + 'keep_dim': keep_dim, + 'reduce_all': True + if dim == None or dim == [] or len(dim) == len(input.shape) + else False, + }, + ) + return out + + +def split(input, num_or_sections, dim=-1, name=None): + """ + Split the input tensor into multiple sub-Tensors. + + Args: + input (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64. + num_or_sections (int|list|tuple): If ``num_or_sections`` is int, then the ``num_or_sections`` + indicates the number of equal sized sub-Tensors that the ``input`` + will be divided into. If ``num_or_sections`` is a list or tuple, the length of it + indicates the number of sub-Tensors and the elements in it indicate the sizes of sub-Tensors' + dimension orderly. The length of the list mustn't be larger than the ``input`` 's size of specified dim. + dim (int|Tensor, optional): The dimension along which to split, it can be a scalar with type ``int`` or + a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``. If :math:`dim < 0`, + the dimension to split along is :math:`rank(input) + dim`. Default is -1. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + list(Tensor): The list of segmented Tensors. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + + # input is a Tensor which shape is [3, 9, 5] + input = fluid.data( + name="input", shape=[3, 9, 5], dtype="float32") + + out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=1) + # out0.shape [3, 3, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 3, 5] + + out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, 4], dim=1) + # out0.shape [3, 2, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 4, 5] + + out0, out1, out2 = fluid.layers.split(input, num_or_sections=[2, 3, -1], dim=1) + # out0.shape [3, 2, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 4, 5] + + # dim is negative, the real dim is (rank(input) + axis) which real + # value is 1. + out0, out1, out2 = fluid.layers.split(input, num_or_sections=3, dim=-2) + # out0.shape [3, 3, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 3, 5] + + """ + if _non_static_mode(): + num = None + attrs = () + + if isinstance(dim, Variable): + dim = dim.numpy() + dim = dim.item(0) + assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" + dim = (len(input.shape) + dim) if dim < 0 else dim + attrs += ('axis', dim) + + if isinstance(num_or_sections, int): + num = num_or_sections + attrs += ('num', num_or_sections) + elif isinstance(num_or_sections, (list, tuple)): + num = len(num_or_sections) + if utils._contain_var(num_or_sections): + for index, item in enumerate(num_or_sections): + if isinstance(item, Variable): + num_or_sections[index] = num_or_sections[index].numpy()[ + 0 + ] + attrs += ('sections', list(num_or_sections)) + else: + attrs += ('sections', list(num_or_sections)) + else: + raise TypeError( + "The type of 'num_or_sections' in split must be int, list or tuple in imperative mode, but " + "received %s." % (type(num_or_sections)) + ) + if in_dygraph_mode(): + if isinstance(num_or_sections, int): + return _C_ops.split_with_num(input, num_or_sections, dim) + else: + return _C_ops.split(input, num_or_sections, dim) + elif _in_legacy_dygraph(): + out = [_varbase_creator() for n in range(num)] + _legacy_C_ops.split(input, out, *attrs) + return out + + check_variable_and_dtype( + input, + 'input', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'split', + ) + check_type(num_or_sections, 'num_or_sections', (list, int, tuple), 'split') + check_type(dim, 'dim', (int, Variable), 'split') + if isinstance(dim, Variable): + check_dtype(dim.dtype, 'dim', ['int32', 'int64'], 'split') + + helper = LayerHelper('split', **locals()) + + input_shape = input.shape + inputs = {'X': input} + attrs = {'num': num_or_sections if isinstance(num_or_sections, int) else 0} + + def _get_SectionsTensorList(one_list): + tensor_list = [] + unk_dim_idx = -1 + for idx, dim_size in enumerate(one_list): + if isinstance(dim_size, Variable): + dim_size.stop_gradient = True + tensor_list.append(dim_size) + else: + assert isinstance(dim_size, int) + if dim_size == -1: + assert unk_dim_idx == -1, ( + "Only one value of 'num_or_section' in split can " + "be -1. But received num_or_section[%d] is also -1." + % idx + ) + unk_dim_idx = idx + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant( + [1], 'int32', dim_size, force_cpu=True, out=temp_out + ) + tensor_list.append(temp_out) + return tensor_list + + if isinstance(dim, Variable): + dim.stop_gradient = True + inputs['AxisTensor'] = dim + else: + assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" + dim = (len(input_shape) + dim) if dim < 0 else dim + attrs['axis'] = dim + + if isinstance(num_or_sections, int): + assert num_or_sections > 1, 'num_or_sections must be more than 1.' + if isinstance(dim, int) and input_shape[dim] > 0: + assert input_shape[dim] % num_or_sections == 0, ( + "The input's size along the split dimension " + "must be evenly divisible by Attr(num_or_sections). " + "But %d is not evenly divisible by %d. " + % (num_or_sections, input_shape[dim]) + ) + num = num_or_sections + else: + if isinstance(dim, int) and input_shape[dim] > 0: + assert ( + len(num_or_sections) <= input_shape[dim] + ), 'len(num_or_sections) must not be more than input.shape[dim].' + num = len(num_or_sections) + attrs['sections'] = list( + map( + lambda ele: -1 if isinstance(ele, Variable) else ele, + num_or_sections, + ) + ) + if utils._contain_var(num_or_sections): + inputs['SectionsTensorList'] = _get_SectionsTensorList( + num_or_sections + ) + + outs = [ + helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + for i in range(num) + ] + helper.append_op( + type='split', inputs=inputs, outputs={'Out': outs}, attrs=attrs + ) + return outs + + +def l2_normalize(x, axis, epsilon=1e-12, name=None): + r""" + + This op normalizes `x` along dimension `axis` using an L2 + norm. For a 1-D tensor (`dim` is fixed to 0), this layer computes + + .. math:: + + y = \\frac{x}{ \sqrt{\sum {x^2} + epsion }} + + For `x` with more dimensions, this layer independently normalizes each 1-D + slice along dimension `axis`. + + Args: + x(Variable|list): The input tensor could be N-D tensor, and the input data type could be float16, float32 or float64. + axis(int): The axis on which to apply normalization. If `axis < 0`, \ + the dimension to normalization is rank(X) + axis. -1 is the + last dimension. + epsilon(float): The epsilon value is used to avoid division by zero, \ + the default value is 1e-12. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: The output has the same shape and data type with `x`. + + Examples: + + .. code-block:: python + :name: code-example1 + + import paddle + + X = paddle.randn(shape=[3, 5], dtype='float64') + out = paddle.fluid.layers.l2_normalize(X, axis=-1) + print(out) + + # [[ 0.21558504 0.56360189 0.47466096 0.46269539 -0.44326736] + # [-0.70602414 -0.52745777 0.37771788 -0.2804768 -0.04449922] + # [-0.33972208 -0.43014923 0.31772556 0.76617881 -0.10761525]] + + """ + if len(x.shape) == 1: + axis = 0 + if _non_static_mode(): + if in_dygraph_mode(): + out, _ = _C_ops.norm(x, 1 if axis is None else axis, epsilon, False) + elif _in_legacy_dygraph(): + _, out = _legacy_C_ops.norm( + x, 'axis', 1 if axis is None else axis, 'epsilon', epsilon + ) + return out + + check_variable_and_dtype(x, "X", ("float16", "float32", "float64"), "norm") + + helper = LayerHelper("l2_normalize", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + norm = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="norm", + inputs={"X": x}, + outputs={"Out": out, "Norm": norm}, + attrs={ + "axis": 1 if axis is None else axis, + "epsilon": epsilon, + }, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.matmul") +def matmul(x, y, transpose_x=False, transpose_y=False, alpha=1.0, name=None): + """ + Applies matrix multiplication to two tensors. + + Currently, the input tensors' rank can be any, but when the rank of any + inputs is bigger than 3, this two inputs' rank should be equal. + + The actual behavior depends on the shapes of :math:`x`, :math:`y` and the + flag values of :attr:`transpose_x`, :attr:`transpose_y`. Specifically: + + - If a transpose flag is specified, the last two dimensions of the tensor + are transposed. If the tensor is rank-1 of shape :math:`[D]`, then for + :math:`x` it is treated as :math:`[1, D]` in nontransposed form and as + :math:`[D, 1]` in transposed form, whereas for :math:`y` it is the + opposite: It is treated as :math:`[D, 1]` in nontransposed form and as + :math:`[1, D]` in transposed form. + + - After transpose, the two tensors are 2-D or n-D and matrix multiplication + performs in the following way. + + - If both are 2-D, they are multiplied like conventional matrices. + - If either is n-D, it is treated as a stack of matrices residing in the + last two dimensions and a batched matrix multiply supporting broadcast + applies on the two tensors. + + Also note that if the raw tensor :math:`x` or :math:`y` is rank-1 and + nontransposed, the prepended or appended dimension :math:`1` will be + removed after matrix multiplication. + + Args: + x (Variable): The input variable which is a Tensor or LoDTensor. + y (Variable): The input variable which is a Tensor or LoDTensor. + transpose_x (bool): Whether to transpose :math:`x` before multiplication. + transpose_y (bool): Whether to transpose :math:`y` before multiplication. + alpha (float): The scale of output. Default 1.0. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + + Returns: + Variable: The product Tensor (or LoDTensor) variable. + + Examples: + .. code-block:: python + + # Examples to clarify shapes of the inputs and output + # x: [B, ..., M, K], y: [B, ..., K, N] + # fluid.layers.matmul(x, y) # out: [B, ..., M, N] + + # x: [B, M, K], y: [B, K, N] + # fluid.layers.matmul(x, y) # out: [B, M, N] + + # x: [B, M, K], y: [K, N] + # fluid.layers.matmul(x, y) # out: [B, M, N] + + # x: [M, K], y: [K, N] + # fluid.layers.matmul(x, y) # out: [M, N] + + # x: [B, M, K], y: [K] + # fluid.layers.matmul(x, y) # out: [B, M] + + # x: [K], y: [K] + # fluid.layers.matmul(x, y) # out: [1] + + # x: [M], y: [N] + # fluid.layers.matmul(x, y, True, True) # out: [M, N] + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + x = fluid.layers.data(name='x', shape=[2, 3], dtype='float32') + y = fluid.layers.data(name='y', shape=[3, 2], dtype='float32') + out = fluid.layers.matmul(x, y, True, True) + """ + if _non_static_mode(): + out = _varbase_creator(dtype=x.dtype) + _legacy_C_ops.matmul( + x, + y, + out, + 'transpose_X', + transpose_x, + 'transpose_Y', + transpose_y, + 'alpha', + float(alpha), + ) + return out + + def __check_input(x, y): + var_names = {'x': x, 'y': y} + for name, val in var_names.items(): + check_variable_and_dtype( + val, name, ['float16', 'float32', 'float64'], 'matmul' + ) + x_shape = list(x.shape) + y_shape = list(y.shape) + if len(x_shape) == 1: + x_shape = [1] + x_shape + if len(y_shape) == 1: + y_shape = y_shape + [1] + + # check the inner 2 dimensions + if transpose_x: + x_shape[-2], x_shape[-1] = x_shape[-1], x_shape[-2] + if transpose_y: + y_shape[-2], y_shape[-1] = y_shape[-1], y_shape[-2] + if x_shape[-1] != y_shape[-2]: + assert (x_shape[-1] == -1) or (y_shape[-2] == -1), ( + "After performing an optional transpose, Input X's width should be " + "equal to Y's width for multiplication " + "prerequisites. But received X's shape: %s, Y's shape: %s\n" + % (x_shape, y_shape) + ) + + if len(y_shape) > 2 and len(x_shape) > 2: + for i, dim_x in enumerate(x_shape[:-2]): + # don't check neg shape + if dim_x < 0 or y_shape[i] < 0: + continue + if dim_x != y_shape[i]: + raise ValueError( + "When the matrix is larger than 2 dimensions, the higher " + "dimensional values of the two matrices need to be equal. " + "But received x_shape[%d] != y_shape[%d]. X's shape: %s, " + "Y's shape: %s.\n" % (i, i, x_shape, y_shape) + ) + + attrs = { + 'transpose_X': transpose_x, + 'transpose_Y': transpose_y, + 'alpha': float(alpha), + } + + __check_input(x, y) + + helper = LayerHelper('matmul', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='matmul', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + +def topk(input, k, name=None): + """ + :alias_main: paddle.topk + :alias: paddle.topk,paddle.tensor.topk,paddle.tensor.search.topk + :old_api: paddle.fluid.layers.topk + + This OP is used to find values and indices of the k largest entries + for the last dimension. + + If the input is a 1-D Tensor, finds the k largest entries and outputs + their values and indices. + + If the input is a Tensor with higher rank, this operator computes the top k + entries along the last dimension. + + .. code-block:: text + + Case 1: + + Input: + input.shape = [3, 4] + input.data = [[5, 4, 2, 3], + [9, 7, 10, 25], + [6, 2, 10, 1]] + k = 2 + + Output: + The first output: + values.shape = [3, 2] + values.data = [[5, 4], + [10, 25], + [6, 10]] + + The second output: + indices.shape = [3, 2] + indices.data = [[0, 1], + [2, 3], + [0, 2]] + + Args: + input(Variable): The input tensor. Support data types: float32, float64. + k(int | Variable): The number of top elements to look for along the last dimension + of input tensor. + name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. + + Returns: + Values (Variable): Input tensor's k largest elements along each last dimensional slice. The dimension is: :math:`input.shape[:-1]+[k]`. + Indices (Variable): Indices of k largest elements alone the last dimension of input. The dimension is same as values. + + Raises: + ValueError: If :math:`k < 1` or :math:`k > last dimension of input`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + # set batch size=None + input = fluid.data(name="input", shape=[None, 13, 11], dtype='float32') + top5_values, top5_indices = layers.topk(input, k=5) # top5_values.shape[None, 13, 5], top5_indices.shape=[None, 13, 5] + + # 1D Tensor + input1 = fluid.data(name="input1", shape=[None, 13], dtype='float32') + top5_values, top5_indices = layers.topk(input1, k=5) #top5_values.shape=[None, 5], top5_indices.shape=[None, 5] + + # k=Variable + input2 = fluid.data(name="input2", shape=[None, 13, 11], dtype='float32') + vk = fluid.data(name="vk", shape=[None, 1], dtype='int32') # save k in vk.data[0] + vk_values, vk_indices = layers.topk(input2, k=vk) #vk_values.shape=[None, 13, k], vk_indices.shape=[None, 13, k] + + """ + if _non_static_mode(): + _k = k.numpy().item(0) if isinstance(k, Variable) else k + out, indices = _legacy_C_ops.top_k(input, 'k', _k) + out.stop_gradient = True + indices.stop_gradient = True + return out, indices + + inputs = {"X": [input]} + attrs = {} + if isinstance(k, Variable): + inputs['K'] = [k] + else: + attrs = {'k': k} + + helper = LayerHelper("top_k", **locals()) + values = helper.create_variable_for_type_inference(dtype=input.dtype) + indices = helper.create_variable_for_type_inference(dtype="int64") + + helper.append_op( + type="top_k", + inputs=inputs, + outputs={"Out": [values], "Indices": [indices]}, + attrs=attrs, + ) + values.stop_gradient = True + indices.stop_gradient = True + return values, indices + + +def ctc_greedy_decoder( + input, blank, input_length=None, padding_value=0, name=None +): + r""" + This op is used to decode sequences by greedy policy by the following steps: + + 1. Get the indexes of maximum value for each row in input. a.k.a. + numpy.argmax(input, axis=0). + 2. For each sequence in result of step1, merge repeated tokens between two + blanks and delete all blanks. + + This op is implemented in two modes: lod and padding, either of them can be used. + The input can be either LoDTensor or Tensor, corresponding to lod and padding + mode respectively. + + A simple example as below: + + .. code-block:: text + + Given: + (1) for lod mode: + + input.data = [[0.6, 0.1, 0.3, 0.1], + [0.3, 0.2, 0.4, 0.1], + [0.1, 0.5, 0.1, 0.3], + [0.5, 0.1, 0.3, 0.1], + + [0.5, 0.1, 0.3, 0.1], + [0.2, 0.2, 0.2, 0.4], + [0.2, 0.2, 0.1, 0.5], + [0.5, 0.1, 0.3, 0.1]] + + input.lod = [[4, 4]] + + Computation: + + step1: Apply argmax to first input sequence which is input.data[0:4]. Then we get: + [[0], [2], [1], [0]] + step2: merge repeated tokens and remove blank which is 0. Then we get first output sequence: + [[2], [1]] + + Finally: + + output.data = [[2], + [1], + [3]] + + output.lod = [[2, 1]] + + (2) for padding mode: + + input.data = [[[0.6, 0.1, 0.3, 0.1], + [0.3, 0.2, 0.4, 0.1], + [0.1, 0.5, 0.1, 0.3], + [0.5, 0.1, 0.3, 0.1]], + + [[0.5, 0.1, 0.3, 0.1], + [0.2, 0.2, 0.2, 0.4], + [0.2, 0.2, 0.1, 0.5], + [0.5, 0.1, 0.3, 0.1]]] + + input_length.data = [[4], [4]] + input.shape = [2, 4, 4] + + step1: Apply argmax to first input sequence which is input.data[0:4]. Then we get: + [[0], [2], [1], [0]], for input.data[4:8] is [[0], [3], [3], [0]], shape is [2,4,1] + step2: Change the argmax result to use padding mode, then argmax result is + [[0, 2, 1, 0], [0, 3, 3, 0]], shape is [2, 4], lod is [], input_length is [[4], [4]] + step3: Apply ctc_align to padding argmax result, padding_value is 0 + + Finally: + output.data = [[2, 1, 0, 0], + [3, 0, 0, 0]] + output_length.data = [[2], [1]] + + + Parameters: + + input(Variable): the probabilities of variable-length sequences. When in lod mode, + it is a 2-D LoDTensor with LoD information. It's shape is [Lp, num_classes + 1] + where Lp is the sum of all input sequences' length and + num_classes is the true number of classes. When in padding mode, + it is a 3-D Tensor with padding, It's shape is [batch_size, N, num_classes + 1]. + (not including the blank label). The data type can be float32 or float64. + blank(int): the blank label index of Connectionist Temporal + Classification (CTC) loss, which is in the half-opened + interval [0, num_classes + 1). + input_length(Variable, optional): 2-D LoDTensor, shape is [batch_size, 1], data type is int64. + It is used for padding mode. In lod mode, input_length is None. + padding_value(int): padding value. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + For lod mode, returns the result of CTC greedy decoder, 2-D LoDTensor, shape is [Lp, 1], \ + data type is int64. 'Lp' is the sum of all output sequences' length. If all the sequences \ + in result were empty, the result LoDTensor will be [-1] with empty \ + LoD [[]]. + + For padding mode, returns a tuple of (output, output_length), which was described as below: + + output, 2-D Tensor, shape is [batch_size, N], data type is int64. + + output_length, 2-D Tensor, shape is [batch_size, 1], data type is int64. It is the length of \ + each sequence of output for padding mode. + + Return type: + For lod mode: Variable + + For padding mode: tuple of two Variables (output, output_length). + + + Examples: + .. code-block:: python + + # for lod mode + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[None, 8], dtype='float32', lod_level=1) + cost = fluid.layers.ctc_greedy_decoder(input=x, blank=0) + + # for padding mode + x_pad = fluid.data(name='x_pad', shape=[10, 4, 8], dtype='float32') + x_pad_len = fluid.data(name='x_pad_len', shape=[10, 1], dtype='int64') + out, out_len = fluid.layers.ctc_greedy_decoder(input=x_pad, blank=0, + input_length=x_pad_len) + + """ + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'ctc_greedy_decoder' + ) + + helper = LayerHelper("ctc_greedy_decoder", **locals()) + _, topk_indices = topk(input, k=1) + + # ctc align op + ctc_out = helper.create_variable_for_type_inference(dtype="int64") + + if input_length is None: + helper.append_op( + type="ctc_align", + inputs={"Input": [topk_indices]}, + outputs={"Output": [ctc_out]}, + attrs={"merge_repeated": True, "blank": blank}, + ) + return ctc_out + else: + ctc_out_len = helper.create_variable_for_type_inference(dtype="int64") + ctc_input = squeeze(topk_indices, [2]) + + helper.append_op( + type="ctc_align", + inputs={"Input": [ctc_input], "InputLength": [input_length]}, + outputs={"Output": [ctc_out], "OutputLength": [ctc_out_len]}, + attrs={ + "merge_repeated": True, + "blank": blank, + "padding_value": padding_value, + }, + ) + return ctc_out, ctc_out_len + + +def transpose(x, perm, name=None): + """ + Permute the data dimensions of `input` according to `perm`. + + The `i`-th dimension of the returned tensor will correspond to the + perm[i]-th dimension of `input`. + + Args: + x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32. + perm (list|tuple): Permute the input according to the data of perm. + name (str): The name of this layer. It is optional. + + Returns: + Tensor: A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64. + + For Example: + + .. code-block:: text + + x = [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] + [[13 14 15 16] [17 18 19 20] [21 22 23 24]]] + shape(x) = [2,3,4] + + # Example 1 + perm0 = [1,0,2] + y_perm0 = [[[ 1 2 3 4] [13 14 15 16]] + [[ 5 6 7 8] [17 18 19 20]] + [[ 9 10 11 12] [21 22 23 24]]] + shape(y_perm0) = [3,2,4] + + # Example 2 + perm1 = [2,1,0] + y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]] + [[ 2 14] [ 6 18] [10 22]] + [[ 3 15] [ 7 19] [11 23]] + [[ 4 16] [ 8 20] [12 24]]] + shape(y_perm1) = [4,3,2] + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn([2, 3, 4]) + x_transposed = paddle.transpose(x, perm=[1, 0, 2]) + print(x_transposed.shape) + # [3L, 2L, 4L] + + """ + if in_dygraph_mode(): + return _C_ops.transpose(x, perm) + else: + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.transpose2(x, 'axis', perm) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'transpose', + ) + check_type(perm, 'perm', (list, tuple), 'transpose') + if isinstance(perm, tuple): + perm = list(perm) + if len(perm) != len(x.shape): + raise ValueError( + "Input(perm) is the permutation of dimensions of Input(x), " + "its length should be equal to dimensions of Input(x), " + "but received dimension of Input(x) is %s, " + "the length of Input(perm) is %s." % (len(x.shape), len(perm)) + ) + for idx, dim in enumerate(perm): + if dim >= len(x.shape): + raise ValueError( + "Each element in Input(perm) should be less than Input(x)'s dimension, " + "but %d-th element in Input(perm) is %d which exceeds Input(x)'s " + "dimension %d." % (idx, perm[idx], len(x.shape)) + ) + + helper = LayerHelper('transpose', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='transpose2', + inputs={'X': [x]}, + outputs={'Out': [out], 'XShape': [x_shape]}, + attrs={'axis': perm}, + ) + return out + + +def im2sequence( + input, + filter_size=1, + stride=1, + padding=0, + input_image_size=None, + out_stride=1, + name=None, +): + r""" + :api_attr: Static Graph + + Extracts image patches from the input tensor to form a tensor of shape + {input.batch_size * output_height * output_width, filter_size_height * + filter_size_width * input.channels}. This op use filter to scan images + and convert these images to sequences. After expanding, the number of time step are + output_height * output_width for an image, in which output_height and + output_width are calculated by below equation: + + .. math:: + + output\_height = 1 + \ + (padding\_up + padding\_down + input\_height - filter\_size\_height + stride\_height - 1) / stride\_height \\\\ + output\_width = 1 + \ + (padding\_left + padding\_right + input\_width - filter\_size\_width + stride\_width - 1) / stride\_width + + And the dimension of each time step is filter_size_height * filter_size_width * input.channels. + + Parameters: + input (Variable): The input should be a 4-D Tensor in :math:`NCHW` format. The data type is float32. + + filter_size(int32 | List[int32]): The filter size. If filter_size is a List, + it must contain two integers, :math:`[filter\_size\_height, filter\_size\_width]` . + Otherwise, the filter size will be a square :math:`[filter\_size, filter\_size]` . Default is 1. + + stride(int32 | List[int32]): The stride size. If stride is a List, it must + contain two integers, :math:`[stride\_height, stride\_width]` . Otherwise, the stride size will be a square :math:`[stride\_size, stride\_size]` . Default is 1. + + padding(int32 | List[int32]): The padding size. If padding is a List, it can + contain four integers like :math:`[padding\_up, padding\_left, padding\_down, padding\_right]` to indicate + paddings of four direction. Or it can contain two integers :math:`[padding\_height, padding\_width]` which means + padding_up = padding_down = padding_height and + padding_left = padding_right = padding_width. Otherwise, a scalar padding means + padding_up = padding_down = padding_left = padding_right = padding. + Default is 0. + + input_image_size(Variable, optional): the input contains image real size.It's dim + is :math:`[batchsize, 2]` . It is just for batch inference when not None. Default is None. + + out_stride(int32 | List[int32]): The scaling of image through CNN. It is valid only when input_image_size is not None. + If out_stride is List, it must contain two integers, + :math:`[out\_stride\_height, out\_stride\_W]` . Otherwise, + the out_stride_height = out_stride_width = out_stride. Default is 1. + + name (str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + The output is a 2-D LoDTensor with shape {input.batch\_size * output\_height * output\_width, \ + filter\_size\_height * filter\_size\_width * input.channels}. The data type is float32. + + Return Type: Variable + + Examples: + + .. code-block:: text + + Given: + + x = [[[[ 6. 2. 1.] + [ 8. 3. 5.] + [ 0. 2. 6.]] + + [[ 2. 4. 4.] + [ 6. 3. 0.] + [ 6. 4. 7.]]] + + [[[ 6. 7. 1.] + [ 5. 7. 9.] + [ 2. 4. 8.]] + + [[ 1. 2. 1.] + [ 1. 3. 5.] + [ 9. 0. 8.]]]] + + x.dims = {2, 2, 3, 3} + + And: + + filter = [2, 2] + stride = [1, 1] + padding = [0, 0] + + Then: + + output.data = [[ 6. 2. 8. 3. 2. 4. 6. 3.] + [ 2. 1. 3. 5. 4. 4. 3. 0.] + [ 8. 3. 0. 2. 6. 3. 6. 4.] + [ 3. 5. 2. 6. 3. 0. 4. 7.] + [ 6. 7. 5. 7. 1. 2. 1. 3.] + [ 7. 1. 7. 9. 2. 1. 3. 5.] + [ 5. 7. 2. 4. 1. 3. 9. 0.] + [ 7. 9. 4. 8. 3. 5. 0. 8.]] + + output.dims = {8, 8} + + output.lod = [[4, 4]] + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + data = fluid.data(name='data', shape=[None, 3, 32, 32], + dtype='float32') + output = fluid.layers.im2sequence( + input=data, stride=[1, 1], filter_size=[2, 2]) + + + """ + assert ( + not _non_static_mode() + ), "sequence layer is not supported in dygraph mode yet." + + check_variable_and_dtype(input, 'input', ['float32'], 'im2sequence') + + if isinstance(filter_size, int): + filter_size = [filter_size, filter_size] + if isinstance(stride, int): + stride = [stride, stride] + if isinstance(padding, int): + padding = [padding, padding] + if len(padding) == 2: + padding.append(padding[0]) + padding.append(padding[1]) + inputs = {"X": input} + attrs = {"kernels": filter_size, "strides": stride, "paddings": padding} + if input_image_size: + if isinstance(out_stride, int): + out_stride = [out_stride, out_stride] + inputs["Y"] = input_image_size + attrs["out_stride"] = out_stride + helper = LayerHelper('im2sequence', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op( + type='im2sequence', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +@templatedoc() +def row_conv(input, future_context_size, param_attr=None, act=None): + """ + :api_attr: Static Graph + + ${comment} + + Args: + input (${x_type}): ${x_comment}. + future_context_size (int): Future context size. Please note, the shape + of convolution kernel is [future_context_size + 1, D]. + param_attr (ParamAttr): Attributes of parameters, including + name, initializer etc. + act (str): Non-linear activation to be applied to output variable. + + Returns: + ${out_comment}. + + Examples: + + .. code-block:: python + + # for LodTensor inputs + import paddle + paddle.enable_static() + x = paddle.static.data(name='x', shape=[9, 16], + dtype='float32', lod_level=1) + out = paddle.static.nn.row_conv(input=x, future_context_size=2) + # for Tensor inputs + x = paddle.static.data(name='x', shape=[9, 4, 16], dtype='float32') + out = paddle.static.nn.row_conv(input=x, future_context_size=2) + """ + helper = LayerHelper('row_conv', **locals()) + check_variable_and_dtype(input, 'input', ['float32'], 'row_conv') + dtype = helper.input_dtype() + filter_shape = [future_context_size + 1, input.shape[-1]] + filter_param = helper.create_parameter( + attr=helper.param_attr, shape=filter_shape, dtype=dtype + ) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='row_conv', + inputs={'X': [input], 'Filter': [filter_param]}, + outputs={'Out': [out]}, + ) + return helper.append_activation(out) + + +@templatedoc() +def multiplex(inputs, index, name=None): + """ + + Based on the given index parameter, the OP selects a specific row from each input Tensor to construct the output Tensor. + + If the input of this OP contains :math:`m` Tensors, where :math:`I_{i}` means the i-th input Tensor, :math:`i` between :math:`[0,m)` . + + And :math:`O` means the output, where :math:`O[i]` means the i-th row of the output, then the output satisfies that :math:`O[i] = I_{index[i]}[i]` . + + For Example: + + .. code-block:: text + + Given: + + inputs = [[[0,0,3,4], [0,1,3,4], [0,2,4,4], [0,3,3,4]], + [[1,0,3,4], [1,1,7,8], [1,2,4,2], [1,3,3,4]], + [[2,0,3,4], [2,1,7,8], [2,2,4,2], [2,3,3,4]], + [[3,0,3,4], [3,1,7,8], [3,2,4,2], [3,3,3,4]]] + + index = [[3],[0],[1],[2]] + + out = [[3,0,3,4], # out[0] = inputs[index[0]][0] = inputs[3][0] = [3,0,3,4] + [0,1,3,4], # out[1] = inputs[index[1]][1] = inputs[0][1] = [0,1,3,4] + [1,2,4,2], # out[2] = inputs[index[2]][2] = inputs[1][2] = [1,2,4,2] + [2,3,3,4]] # out[3] = inputs[index[3]][3] = inputs[2][3] = [2,3,3,4] + + + Args: + inputs (list): The input Tensor list. The list elements are N-D Tensors of data types float32, float64, int32, int64. All input Tensor shapes should be the same and rank must be at least 2. + index (Tensor): Used to select some rows in the input Tensor to construct an index of the output Tensor. It is a 2-D Tensor with data type int32 or int64 and shape [M, 1], where M is the number of input Tensors. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: Output of multiplex OP, with data type being float32, float64, int32, int64. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + img1 = np.array([[1, 2], [3, 4]]).astype(np.float32) + img2 = np.array([[5, 6], [7, 8]]).astype(np.float32) + inputs = [paddle.to_tensor(img1), paddle.to_tensor(img2)] + index = paddle.to_tensor(np.array([[1], [0]]).astype(np.int32)) + res = paddle.multiplex(inputs, index) + print(res) # [array([[5., 6.], [3., 4.]], dtype=float32)] + + """ + + if _in_legacy_dygraph(): + return _legacy_C_ops.multiplex(index, inputs) + if in_dygraph_mode(): + return _C_ops.multiplex(inputs, index) + helper = LayerHelper('multiplex', **locals()) + + check_type(inputs, 'inputs', (list), 'multiplex') + if len(inputs) < 2: + raise ValueError( + "inputs should be a list object with at least 2 elements." + ) + for id, x in enumerate(inputs): + check_variable_and_dtype( + x, + 'input[' + str(id) + ']', + ['float32', 'float64', 'int32', 'int64'], + 'multiplex', + ) + check_variable_and_dtype(index, "index", ['int32', 'int64'], 'multiplex') + + out = helper.create_variable_for_type_inference(inputs[0].dtype) + helper.append_op( + type='multiplex', + inputs={'X': inputs, 'Ids': index}, + outputs={'Out': [out]}, + ) + return out + + +def smooth_l1(x, y, inside_weight=None, outside_weight=None, sigma=None): + """ + + This layer computes the smooth L1 loss for Variable :attr:`x` and :attr:`y`. + It takes the first dimension of :attr:`x` and :attr:`y` as batch size. + For each instance, it computes the smooth L1 loss element by element first + and then sums all the losses. So the shape of output Variable is + [batch_size, 1]. + + Args: + x (Variable): A tensor with rank at least 2. The input value of smooth + L1 loss op with shape [batch_size, dim1, ..., dimN]. + A LoDTensor or Tensor with type float32. + y (Variable): A tensor with rank at least 2. The target value of smooth + L1 loss op with same shape as :attr:`x`. + A LoDTensor or Tensor with type float32. + inside_weight (Variable|None): A tensor with rank at least 2. This + input is optional and should have same shape with :attr:`x`. If + provided, the result of (:attr:`x` - :attr:`y`) will be multiplied + by this tensor element by element. + A Tensor with type float32. + outside_weight (Variable|None): A tensor with rank at least 2. This + input is optional and should have same shape with :attr:`x`. If + provided, the out smooth L1 loss will be multiplied by this tensor + element by element. + A Tensor with type float32. + sigma (float|None): Hyper parameter of smooth L1 loss layer. A float + scalar with default value 1.0. + + Returns: + Variable: The output smooth L1 loss with shape [batch_size, 1]. A Tensor with type float32. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + data = fluid.data(name="x", shape=[-1, 3], dtype="float32") + label = fluid.data(name="y", shape=[-1, 3], dtype="float32") + result = fluid.layers.smooth_l1(data,label) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + x = np.random.rand(3,3).astype("float32") + y = np.random.rand(3,3).astype("float32") + output= exe.run(feed={"x":x, "y":y}, + fetch_list=[result]) + print(output) + + #[array([[0.08220536], + # [0.36652038], + # [0.20541131]], dtype=float32)] + + """ + check_variable_and_dtype(x, 'X', ['float32', 'float64'], 'smooth_l1_loss') + check_variable_and_dtype(y, 'Y', ['float32', 'float64'], 'smooth_l1_loss') + + helper = LayerHelper('smooth_l1_loss', **locals()) + + diff = helper.create_variable_for_type_inference(dtype=x.dtype) + loss = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='smooth_l1_loss', + inputs={ + 'X': x, + 'Y': y, + 'InsideWeight': inside_weight, + 'OutsideWeight': outside_weight, + }, + outputs={'Diff': diff, 'Out': loss}, + attrs={'sigma': sigma if sigma is not None else 1.0}, + ) + return loss + + +@deprecated(since='2.0.0', update_to='paddle.nn.functional.one_hot') +def one_hot(input, depth, allow_out_of_range=False): + """ + + **WARING:** This OP requires the last dimension of Tensor shape must be equal to 1. + This OP will be deprecated in a future release. It is recommended to use fluid. :ref:`api_fluid_one_hot` . + + The operator converts each id in the input to an one-hot vector with a + :attr:`depth` length. The value in the vector dimension corresponding to the id + is 1, and the value in the remaining dimension is 0. + + The shape of output Tensor or LoDTensor is generated by adding :attr:`depth` dimension + behind the last dimension of the input shape. + + .. code-block:: text + + Example 1 (allow_out_of_range=False): + + input: + X.shape = [4, 1] + X.data = [[1], [1], [3], [0]] + depth = 4 + + output: + Out.shape = [4, 4] + Out.data = [[0., 1., 0., 0.], + [0., 1., 0., 0.], + [0., 0., 0., 1.], + [1., 0., 0., 0.]] + + Example 2 (allow_out_of_range=True): + + input: + X.shape = [4, 1] + X.data = [[1], [1], [5], [0]] + depth = 4 + allow_out_of_range = True + + output: + Out.shape = [4, 4] + Out.data = [[0., 1., 0., 0.], + [0., 1., 0., 0.], + [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data. + [1., 0., 0., 0.]] + + Example 3 (allow_out_of_range=False): + + input: + X.shape = [4, 1] + X.data = [[1], [1], [5], [0]] + depth = 4 + allow_out_of_range = False + + output: Throw an exception for Illegal value + The second dimension in X is 5, which is greater than depth. + Allow_out_of_range =False means that does not allow the word id to exceed depth, + so it throws an exception. + + Args: + input(Variable): Tensor or LoDTensor with shape :math:`[N_1, N_2, ..., N_k, 1]` , + which contains at least one dimension and the last dimension must be 1. + The data type is int32 or int64. + depth(scalar): An integer defining the :attr:`depth` of the one hot dimension. If input + is word id, depth is generally the dictionary size. + allow_out_of_range(bool): A bool value indicating whether the input + indices could be out of range :math:`[0, depth)` . When input indices are + out of range, exceptions :code:`Illegal value` is raised if :attr:`allow_out_of_range` + is False, or zero-filling representations is created if it is set True. + Default: False. + + Returns: + Variable: The one-hot representations of input. A Tensor or LoDTensor with type float32. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # Correspond to the first example above, where label.shape is [4, 1] and one_hot_label.shape is [4, 4]. + label = fluid.data(name="label", shape=[4, 1], dtype="int64") + one_hot_label = fluid.layers.one_hot(input=label, depth=4) + """ + if _non_static_mode(): + if isinstance(depth, Variable): + depth = depth.numpy() + assert depth.shape == ( + 1, + ), "depth of type Variable should have shape [1]" + depth = depth.item(0) + out = _legacy_C_ops.one_hot( + input, 'depth', depth, 'allow_out_of_range', allow_out_of_range + ) + out.stop_gradient = True + return out + + helper = LayerHelper("one_hot", **locals()) + check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'one_hot') + check_type(depth, 'depth', (six.integer_types, Variable), 'one_hot') + one_hot_out = helper.create_variable_for_type_inference(dtype='float32') + + if not isinstance(depth, Variable): + # user attribute + inputs = {'X': input} + attrs = {'depth': depth, 'allow_out_of_range': allow_out_of_range} + else: + depth.stop_gradient = True + inputs = {'X': input, 'depth_tensor': depth} + attrs = {'allow_out_of_range': allow_out_of_range} + helper.append_op( + type="one_hot", inputs=inputs, attrs=attrs, outputs={'Out': one_hot_out} + ) + one_hot_out.stop_gradient = True + return one_hot_out + + +def autoincreased_step_counter(counter_name=None, begin=1, step=1): + """ + :api_attr: Static Graph + + Create an auto-increase variable. which will be automatically increased + by 1 in every iteration. By default, the first return of this counter is 1, + and the step size is 1. + + Args: + counter_name(str, optional): The counter name. Default '@STEP_COUNTER@'. + begin(int, optional): The first return value of this counter. Default 1. + step(int, optional): The step size. Default 1. + + Returns: + Variable: The auto-increased Variable with data type int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + global_step = fluid.layers.autoincreased_step_counter( + counter_name='@LR_DECAY_COUNTER@', begin=0, step=1) + """ + helper = LayerHelper('global_step_counter') + if counter_name is None: + counter_name = '@STEP_COUNTER@' + counter, is_new_var = helper.create_or_get_global_variable( + name=counter_name, + dtype='int64', + shape=[1], + persistable=True, + belong_to_optimizer=True, + ) + if is_new_var: + helper.set_variable_initializer( + counter, initializer=Constant(value=begin - 1, force_cpu=True) + ) + helper.main_program.global_block()._prepend_op( + type='increment', + inputs={'X': [counter]}, + outputs={'Out': [counter]}, + attrs={'step': float(step)}, + ) + counter.stop_gradient = True + + return counter + + +def reshape(x, shape, actual_shape=None, act=None, inplace=False, name=None): + r""" + :alias_main: paddle.reshape + :alias: paddle.reshape,paddle.tensor.reshape,paddle.tensor.manipulation.reshape + + This operator changes the shape of ``x`` without changing its data. + + The target shape can be given by ``shape`` or ``actual_shape``. + When ``shape`` and ``actual_shape`` are set at the same time, + ``actual_shape`` has a higher priority than ``shape`` + but at this time ``shape`` can only be an integer list or tuple, and ``shape`` still should be set correctly to + guarantee shape inference in compile-time. + + Some tricks exist when specifying the target shape. + + 1. -1 means the value of this dimension is inferred from the total element + number of x and remaining dimensions. Thus one and only one dimension can + be set -1. + + 2. 0 means the actual dimension value is going to be copied from the + corresponding dimension of x. The index of 0s in shape can not exceed + the dimension of x. + + Here are some examples to explain it. + + 1. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape + is [6, 8], the reshape operator will transform x into a 2-D tensor with + shape [6, 8] and leaving x's data unchanged. + + 2. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape + specified is [2, 3, -1, 2], the reshape operator will transform x into a + 4-D tensor with shape [2, 3, 4, 2] and leaving x's data unchanged. In this + case, one dimension of the target shape is set to -1, the value of this + dimension is inferred from the total element number of x and remaining + dimensions. + + 3. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape + is [-1, 0, 3, 2], the reshape operator will transform x into a 4-D tensor + with shape [2, 4, 3, 2] and leaving x's data unchanged. In this case, + besides -1, 0 means the actual dimension value is going to be copied from + the corresponding dimension of x. + + **Note**: + The parameter ``actual_shape`` will be deprecated in the future and only use ``shape`` instead to represent the target shape. + + Args: + x(Tensor): An N-D Tensor. The data type is ``float32``, ``float64``, ``int32`` or ``int64``. + shape(list|tuple|Tensor): Define the target shape. At most one dimension of the target shape can be -1. + The data type is ``int32`` . If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. + If ``shape`` is an Tensor, it should be an 1-D Tensor . + actual_shape(variable, optional): An 1-D ``Tensor`` or ``LoDTensor`` . The data type is ``int32`` . If provided, reshape + according to this given shape rather than ``shape`` specifying shape. + That is to say ``actual_shape`` has a higher priority + than ``shape(list|tuple)`` but not ``shape(Tensor)``. \ + This argument ``actual_shape`` will be removed in a future version. \ + Instructions for updating: ``actual_shape`` will be removed in future versions and replaced by ``shape``. + act (str, optional): The non-linear activation to be applied to the reshaped input. Default None. + inplace(bool, optional): If ``inplace`` is True, the input and output of ``layers.reshape`` + are the same variable. Otherwise, the input and output of + ``layers.reshape`` are different variable. Default False. Note that if ``x`` + is more than one OPs' input, ``inplace`` must be False. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: A reshaped Tensor with the same data type as ``x``. It is a new tensor variable if ``inplace`` is ``False``, otherwise it is ``x``. If ``act`` is None, return the reshaped tensor variable, otherwise return the activated tensor variable. + + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # example 1: + # attr shape is a list which doesn't contain Tensors. + data_1 = fluid.data( + name='data_1', shape=[2, 4, 6], dtype='float32') + reshaped_1 = fluid.layers.reshape( + x=data_1, shape=[-1, 0, 3, 2]) + # the shape of reshaped_1 is [2,4,3,2]. + + # example 2: + # attr shape is a list which contains Tensors. + data_2 = fluid.layers.fill_constant([2,25], "int32", 3) + dim = fluid.layers.fill_constant([1], "int32", 5) + reshaped_2 = fluid.layers.reshape(data_2, shape=[dim, 10]) + # the shape of reshaped_2 is [5,10]. + + # example 3: + data_3 = fluid.data( + name="data_3", shape=[2,4,6], dtype='float32') + reshaped_3 = fluid.layers.reshape(x=data_3, shape=[6,8]) + # the shape of reshaped_3 is [6,8]. + """ + if in_dygraph_mode(): + tmp_tensor_type = core.eager.Tensor + # TODO(zhiqiu): enable inplace in dygraph mode. + if inplace: + warnings.warn( + "Inplace on reshape is not allowed and will be discarded in dygraph mode currently." + ) + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in shape + ] + out = _C_ops.reshape(x, shape) + elif isinstance(shape, tmp_tensor_type): + # TODO: Tensor shape in reshape has not been tested + shape.stop_gradient = True + out = _C_ops.reshape(x, shape) + else: + raise ValueError( + "shape must be an instance of `list`, `tuple` or `Variable`," + " got '{}.'".format(type(shape)) + ) + + return dygraph_utils._append_activation_in_dygraph(out, act) + else: + if _in_legacy_dygraph(): + tmp_tensor_type = Variable + if inplace: + warnings.warn( + "Inplace on reshape is not allowed and will be discarded in dygraph mode currently." + ) + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in shape + ] + out, _ = _legacy_C_ops.reshape2(x, None, 'shape', shape) + elif isinstance(shape, tmp_tensor_type): + shape.stop_gradient = True + out, _ = _legacy_C_ops.reshape2(x, shape) + else: + raise ValueError( + "shape must be an instance of `list`, `tuple` or `Variable`," + " got '{}.'".format(type(shape)) + ) + + return dygraph_utils._append_activation_in_dygraph(out, act) + + check_variable_and_dtype( + x, + 'x', + [ + 'float16', + 'float32', + 'float64', + 'int16', + 'int32', + 'int64', + 'bool', + 'uint16', + ], + 'reshape', + ) + check_type(shape, 'shape', (list, tuple, Variable), 'reshape') + check_type(actual_shape, 'actual_shape', (Variable, type(None)), 'reshape') + + helper = LayerHelper("reshape2", **locals()) + + def get_attr_shape(list_shape): + unk_dim_idx = -1 + attrs_shape = [] + for dim_idx, dim_size in enumerate(list_shape): + if isinstance(dim_size, Variable): + attrs_shape.append(-1) + else: + attrs_shape.append(dim_size) + if dim_size == -1: + assert unk_dim_idx == -1, ( + "Only one dimension value of 'shape' in reshape can " + "be -1. But received shape[%d] is also -1.\n" + "\n\t# N = x.shape()[2]\t\t# N is an int. " + "(NOT recommend under @to_static)\n\tN = paddle.shape(x)[2]\t\t" + "# N is a Tensor. (Recommend)\n\tz = paddle.reshape([N, -1, 4])" + "\t# z.shape is [-1, -1, 4]\n\n" + " If your target shape in Reshape represents dynamic shape, " + "please turn it into a Tensor under @to_static. See above example for details." + % dim_idx + ) + unk_dim_idx = dim_idx + elif dim_size == 0: + assert dim_idx < len(x.shape), ( + "The index of 0 in `shape` must be less than " + "the input tensor X's dimensions. " + "But received shape[%d] = 0, X's dimensions = %d." + % (dim_idx, len(x.shape)) + ) + else: + assert dim_size > 0, ( + "Each dimension value of 'shape' in reshape must not " + "be negative except one unknown dimension. " + "But received shape[%d] = %s." + % (dim_idx, str(dim_size)) + ) + return attrs_shape + + inputs = {"X": x} + attrs = {} + if isinstance(shape, Variable): + shape.stop_gradient = True + inputs["Shape"] = shape + elif isinstance(shape, (list, tuple)): + assert len(shape) > 0, ( + "The size of 'shape' in reshape can't be zero, " + "but received %s." % len(shape) + ) + attrs["shape"] = get_attr_shape(shape) + if utils._contain_var(shape): + inputs['ShapeTensor'] = utils._convert_to_tensor_list(shape) + elif isinstance(actual_shape, Variable): + actual_shape.stop_gradient = True + inputs["Shape"] = actual_shape + + out = ( + x + if inplace + else helper.create_variable_for_type_inference(dtype=x.dtype) + ) + x_shape = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="reshape2", + inputs=inputs, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return helper.append_activation(out) + + +def squeeze(input, axes, name=None): + """ + This OP will squeeze single-dimensional entries of input tensor's shape. If axes is provided, will + remove the dims by axes, the dims selected by axes should be one. If not provide axes, all dims equal + to one will be deleted. + + + .. code-block:: text + + Case1: + + Input: + X.shape = (1, 3, 1, 5) + axes = [0] + Output: + Out.shape = (3, 1, 5) + + Case2: + + Input: + X.shape = (1, 3, 1, 5) + axes = [] + Output: + Out.shape = (3, 5) + + Case3: + + Input: + X.shape = [1,3,1,5] + axes = [-2] + Output: + Out.shape = [1,3,5] + + Args: + input (Variable): The input Tensor. Supported data type: float32, float64, bool, int8, int32, int64. + axes (list): One integer or List of integers, indicating the dimensions to be squeezed. + Axes range is :math:`[-rank(input), rank(input))`. + If axes is negative, :math:`axes=axes+rank(input)`. + name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. + + Returns: + Variable: Output squeezed Tensor. Data type is same as input Tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + # set batch size=None + x = fluid.data(name='x', shape=[None, 5, 1, 10]) + y = layers.squeeze(input=x, axes=[2]) # y.shape=[None, 5, 10] + + """ + if in_dygraph_mode(): + return _C_ops.squeeze(input, axes) + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.squeeze2(input, 'axes', axes) + return out + + helper = LayerHelper("squeeze", **locals()) + check_variable_and_dtype( + input, + 'input', + [ + 'float16', + 'float32', + 'float64', + 'bool', + 'int8', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'squeeze', + ) + check_type(axes, 'axis/axes', (list, tuple, Variable), 'squeeze') + + attrs = {} + if isinstance(axes, Variable): + axes.stop_gradient = True + attrs["axes"] = axes + elif isinstance(axes, (list, tuple)): + if utils._contain_var(axes): + attrs["axes"] = utils._convert_to_tensor_list(axes) + else: + attrs["axes"] = axes + out = helper.create_variable_for_type_inference(dtype=input.dtype) + x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type="squeeze2", + inputs={"X": input}, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return out + + +def unsqueeze(input, axes, name=None): + """ + Insert single-dimensional entries to the shape of a Tensor. Takes one + required argument axes, a list of dimensions that will be inserted. + Dimension indices in axes are as seen in the output tensor. + + For example: + + .. code-block:: text + + Given a tensor such that tensor with shape [3, 4, 5], + then Unsqueezed tensor with axes=[0, 4] has shape [1, 3, 4, 5, 1]. + + Args: + input (Variable): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64. + axes (int|list|tuple|Variable): Indicates the dimensions to be inserted. The data type is ``int32`` . If ``axes`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``axes`` is an Variable, it should be an 1-D Tensor . + name (str|None): Name for this layer. + + Returns: + Variable: Unsqueezed Tensor, with the same data type as input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[5, 10]) + y = fluid.layers.unsqueeze(input=x, axes=[1]) + + """ + if _non_static_mode(): + if isinstance(axes, int): + axes = [axes] + elif isinstance(axes, Variable): + axes = axes.numpy().tolist() + elif isinstance(axes, (list, tuple)): + axes = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in axes + ] + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.unsqueeze2(input, 'axes', axes) + return out + return _C_ops.unsqueeze(input, axes) + + check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze') + check_variable_and_dtype( + input, + 'input', + [ + 'float16', + 'float32', + 'float64', + 'bool', + 'int8', + 'int16', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'unsqueeze', + ) + helper = LayerHelper("unsqueeze2", **locals()) + inputs = {"X": input} + attrs = {} + + if isinstance(axes, int): + axes = [axes] + if isinstance(axes, Variable): + axes.stop_gradient = True + inputs["AxesTensor"] = axes + elif isinstance(axes, (list, tuple)): + if utils._contain_var(axes): + inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes) + else: + attrs["axes"] = axes + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type="unsqueeze2", + inputs=inputs, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return out + + +def lod_reset(x, y=None, target_lod=None): + """ + Set LoD of :attr:`x` to a new one specified by :attr:`y` or + :attr:`target_lod`. When :attr:`y` provided, :attr:`y.lod` would be + considered as target LoD first, otherwise :attr:`y.data` would be + considered as target LoD. If :attr:`y` is not provided, target LoD should + be specified by :attr:`target_lod`. If target LoD is specified by + :attr:`y.data` or :attr:`target_lod`, only one level LoD is supported. + + .. code-block:: text + + * Example 1: + + Given a 1-level LoDTensor x: + x.lod = [[ 2, 3, 1 ]] + x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + x.dims = [6, 1] + + target_lod: [4, 2] + + then we get a 1-level LoDTensor: + out.lod = [[4, 2]] + out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + out.dims = [6, 1] + + * Example 2: + + Given a 1-level LoDTensor x: + x.lod = [[2, 3, 1]] + x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + x.dims = [6, 1] + + y is a Tensor: + y.data = [[2, 4]] + y.dims = [1, 3] + + then we get a 1-level LoDTensor: + out.lod = [[2, 4]] + out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + out.dims = [6, 1] + + * Example 3: + + Given a 1-level LoDTensor x: + x.lod = [[2, 3, 1]] + x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + x.dims = [6, 1] + + y is a 2-level LoDTensor: + y.lod = [[2, 2], [2, 2, 1, 1]] + y.data = [[1.1], [2.1], [3.1], [4.1], [5.1], [6.1]] + y.dims = [6, 1] + + then we get a 2-level LoDTensor: + out.lod = [[2, 2], [2, 2, 1, 1]] + out.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + out.dims = [6, 1] + + Args: + x (Variable): Input variable which could be a Tensor or LoDTensor. + The data type should be int32, int64, float32 or float64. + y (Variable, optional): If provided, output's LoD would be derived from :attr:`y`. + If y's lod level>0, the data type can be any type. + If y's lod level=0, the data type should be int32. + target_lod (list|tuple, optional): One level LoD which should be considered + as target LoD when :attr:`y` not provided. + + Returns: + Variable: Output variable with LoD specified by this layer. + + Raises: + ValueError: If :attr:`y` and :attr:`target_lod` are both None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[10]) + y = fluid.layers.data(name='y', shape=[10, 20], lod_level=2) + out = fluid.layers.lod_reset(x=x, y=y) + """ + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'lod_reset' + ) + helper = LayerHelper("lod_reset", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + if y is not None: + check_type(y, 'y', (Variable), 'lod_reset') + # TODO: check y.lod_level = 0 dtype + helper.append_op( + type="lod_reset", inputs={'X': x, 'Y': y}, outputs={'Out': out} + ) + elif target_lod is not None: + helper.append_op( + type="lod_reset", + inputs={'X': x}, + attrs={'target_lod': target_lod}, + outputs={'Out': out}, + ) + else: + raise ValueError("y and target_lod should not be both none.") + return out + + +def lod_append(x, level): + """ + Append level to LoD of :attr:`x`. + + .. code-block:: text + + * Example 1: + + given a 1-level LoDTensor x: + x.lod = [[ 2, 3, 1 ]] + x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + x.dims = [6, 1] + + level: [1, 1, 1, 1, 1, 1, 1] + + then we get a 2-level LoDTensor: + x.lod = [[ 2, 3, 1 ], [1, 1, 1, 1, 1, 1]] + x.data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]] + x.dims = [6, 1] + + Args: + x (Variable): Input variable which could be a tensor or LoDTensor. + The data type should be int32, int64, float32 or float64. + level (list|tuple|Variable, optional): The LoD level to be appended into LoD of x. + If level is variable and its lod level>0, the data type can be any type. + If level is variable and its lod level=0, the data type should be int32. + Returns: + Variable: Output variable with new LoD level. + + Raises: + ValueError: If :attr:`y` is None or and :attr:`level` is not Iterator. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.layers.data(name='x', shape=[6, 10], lod_level=1) + out = fluid.layers.lod_append(x, [1,1,1,1,1,1]) + """ + try: + from collections.abc import Iterable + except: + from collections import Iterable + if x is None: + raise ValueError("Input(x) can't be None.") + if (not isinstance(level, Iterable)) and (not isinstance(level, Variable)): + raise ValueError("Input(level) must be list, tuple or Variable.") + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'lod_append' + ) + + helper = LayerHelper("lod_append", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + inputs = {'X': x} + attrs = {'append': True} + + if isinstance(level, Variable): + inputs['Y'] = level + # TODO: check y.lod_level = 0 dtype + else: + attrs['target_lod'] = level + helper.append_op( + type="lod_reset", inputs=inputs, attrs=attrs, outputs={'Out': out} + ) + return out + + +def lrn( + input, n=5, k=1.0, alpha=1e-4, beta=0.75, name=None, data_format='NCHW' +): + r""" + :alias_main: paddle.nn.functional.lrn + :alias: paddle.nn.functional.lrn,paddle.nn.functional.norm.lrn + :old_api: paddle.fluid.layers.lrn + + This operator implements the Local Response Normalization Layer. + This layer performs a type of "lateral inhibition" by normalizing over local input regions. + For more information, please refer to `ImageNet Classification with Deep Convolutional Neural Networks `_ + + The formula is as follows: + + .. math:: + + Output(i, x, y) = Input(i, x, y) / \\left(k + \\alpha \\sum\\limits^{\\min(C-1, i + n/2)}_{j = \\max(0, i - n/2)}(Input(j, x, y))^2\\right)^{\\beta} + + In the above equation: + + - :math:`n` : The number of channels to sum over. + - :math:`k` : The offset (avoid being divided by 0). + - :math:`\\alpha` : The scaling parameter. + - :math:`\\beta` : The exponent parameter. + + + Args: + input (Variable): Input feature, 4D-Tensor with the shape of [N,C,H,W] or [N, H, W, C], + where N is the batch size, C is the input channel, H is Height, W is weight. The data + type is float32. The rank of this tensor must be 4, otherwise it will raise ValueError. + n (int, optional): The number of channels to sum over. Default: 5 + k (float, optional): An offset, positive. Default: 1.0 + alpha (float, optional): The scaling parameter, positive. Default:1e-4 + beta (float, optional): The exponent, positive. Default:0.75 + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name` + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + Variable: A tensor variable storing the transformation result with the same shape and data type as input. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.data( + name="data", shape=[None, 3, 112, 112], dtype="float32") + lrn = fluid.layers.lrn(input=data) + print(lrn.shape) # [-1, 3, 112, 112] + print(lrn.dtype) # float32 + """ + helper = LayerHelper('lrn', **locals()) + check_variable_and_dtype(input, 'input', ['float32'], 'lrn') + dtype = helper.input_dtype() + input_shape = input.shape + dims = len(input_shape) + + if dims != 4: + raise ValueError( + "Input's dimension size of Op(lrn) must be 4, but received %d." + % (dims) + ) + if data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Attr(data_format) of Op(lrn) got wrong value: received " + + data_format + + " but only NCHW or NHWC supported." + ) + + mid_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + lrn_out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="lrn", + inputs={"X": input}, + outputs={ + "Out": lrn_out, + "MidOut": mid_out, + }, + attrs={ + "n": n, + "k": k, + "alpha": alpha, + "beta": beta, + "data_format": data_format, + }, + ) + + return lrn_out + + +def pad(x, paddings, pad_value=0.0, name=None): + r""" + :alias_main: paddle.nn.functional.pad + :alias: paddle.nn.functional.pad,paddle.nn.functional.common.pad + :old_api: paddle.fluid.layers.pad + + This op will pad a tensor with a constant value given by :attr:`pad_value`, and the + padded shape is specified by :attr:`paddings`. + + Specifically, the number of values padded before the elements of :attr:`x` + in dimension :attr:`i` is indicated by :attr:`paddings[2*i]`, and the number + of values padded after the elements of :attr:`x` in dimension :attr:`i` is + indicated by :attr:`paddings[2*i+1]`. + + See below for an example. + + .. code-block:: text + + Given: + x = [[1, 2], [3, 4]] + + paddings = [0, 1, 1, 2] + + pad_value = 0 + + Return: + out = [[0, 1, 2, 0, 0] + [0, 3, 4, 0, 0] + [0, 0, 0, 0, 0]] + + Args: + x (Variable): Tensor, data type is float32. + paddings (list): A list of integers. Its elements specify the padded + width before and after each dimension in turn. + The length of :attr:`paddings` must be equal to + :math:`rank(x) \\times 2`. + pad_value (float): The constant value used to pad. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + The padded tensor, with the same data type and rank as :attr:`x` + + Return Type: + Variable + + Examples: + .. code-block:: python + + # x is a rank 2 tensor variable + import paddle.fluid as fluid + x = fluid.data(name='data', shape=[300, 300], dtype='float32') + out = fluid.layers.pad(x=x, paddings=[0, 1, 1, 2], pad_value=0.) + """ + check_variable_and_dtype( + x, + 'x', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + "pad", + ) + + check_type(pad_value, 'pad_value', (float, int, Variable), 'pad') + if isinstance(pad_value, int): + pad_value = float(pad_value) + + helper = LayerHelper('pad', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='pad', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'paddings': paddings, 'pad_value': pad_value}, + ) + return out + + +def pad_constant_like(x, y, pad_value=0.0, name=None): + r""" + Pad :attr:`y` with :attr:`pad_value`, the number of values padded to + the edges of each axis is specified by the difference of the shape + of :attr:`x` and :attr:`y` . ((0, shape_x_0 - shape_y_0), ... (0, shape_x_n - shape_y_n)) + specify padding widths for each axis. The input should be a k-D tensor(k > 0 and k < 7). + + See below for an example. + + .. code-block:: text + + Given: + 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]], + [[24, 25, 26], + [27, 28, 29]], + [[30, 31, 32], + [33, 34, 35]]]] + + X.shape = (2, 3, 2, 3) + + Y = [[[[35, 36, 37]], + [[38, 39, 40]], + [[41, 42, 43]]]] + + Y.shape = (1, 3, 1, 3) + + And + pad_value = 0. + + Return: + Out = [[[[35, 36, 37], + [ 0, 0, 0]], + [[38, 39, 40], + [ 0, 0, 0]], + [[41, 42, 43], + [ 0, 0, 0]]], + [[[ 0, 0, 0], + [ 0, 0, 0]], + [[ 0, 0, 0], + [ 0, 0, 0]], + [[ 0, 0, 0], + [ 0, 0, 0]]]] + + Out.shape = [2, 3, 2, 3] + + + Args: + x (Variable): Tensor, its shape specifies the shape of output. + y (Variable): Tensor, its rank is the same with :attr:`x`, and for each dimension :math:`i` , + :math:`y\_shape[i] <= x\_shape[i]` . The data type can be float32 or float64. + pad_value (float): The constant value used to pad. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + The padded tensor, with the same shape as :attr:`x` and the same data type as :attr:`y` + + Return Type: + Variable + + Examples: + .. code-block:: python + + # x is a rank 4 tensor variable, x.shape = (2, 3, 2, 3) + # y is a rank 4 tensor variable, y.shape = (1, 3, 1, 3) + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[2,3,2,3], dtype='float32') + y = fluid.data(name='y', shape=[1,3,1,3], dtype='float32') + out = fluid.layers.pad_constant_like(x=x, y=y, pad_value=0.) + # out is a rank 4 tensor variable, and out.shape = [2, 3 ,2 , 3] + """ + check_type(x, 'x', (Variable), 'pad_constant_like') + check_variable_and_dtype( + y, 'y', ['float32', 'float64', 'int32', 'int64'], "pad_constant_like" + ) + + helper = LayerHelper('pad_constant_like', **locals()) + dtype = helper.input_dtype(input_param_name='y') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='pad_constant_like', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs={'pad_value': float(pad_value)}, + ) + return out + + +def label_smooth( + label, prior_dist=None, epsilon=0.1, dtype="float32", name=None +): + r""" + :alias_main: paddle.nn.functional.label_smooth + :alias: paddle.nn.functional.label_smooth,paddle.nn.functional.common.label_smooth + :old_api: paddle.fluid.layers.label_smooth + + Label smoothing is a mechanism to regularize the classifier layer and is called + label-smoothing regularization (LSR). + + Label smoothing is proposed to encourage the model to be less confident, + since optimizing the log-likelihood of the correct label directly may + cause overfitting and reduce the ability of the model to adapt. Label + smoothing replaces the ground-truth label :math:`y` with the weighted sum + of itself and some fixed distribution :math:`\mu`. For class :math:`k`, + i.e. + + .. math:: + + \\tilde{y_k} = (1 - \epsilon) * y_k + \epsilon * \mu_k, + + where :math:`1 - \epsilon` and :math:`\epsilon` are the weights + respectively, and :math:`\\tilde{y}_k` is the smoothed label. Usually + uniform distribution is used for :math:`\mu`. + + See more details about label smoothing in https://arxiv.org/abs/1512.00567. + + Parameters: + label(Variable): The input variable containing the label data. The + label data should use one-hot representation. It's + a multidimensional tensor with a shape of + :math:`[N_1, ..., Depth]`, where Depth is class number. The dtype can be "float32" and "float64". + prior_dist(Variable, optional): The prior distribution to be used to smooth + labels. If not provided, an uniform distribution + is used. It's a multidimensional tensor with a shape of + :math:`[1, class\_num]` . The default value is None. + epsilon(float, optional): The weight used to mix up the original ground-truth + distribution and the fixed distribution. The default value is + 0.1. + dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type can be set + as 'float32', 'float64'. The default value is 'float32'. + name(str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name`. + + Returns: + Variable: The tensor variable containing the smoothed labels. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + label = layers.data(name="label", shape=[1], dtype="int32") + one_hot_label = layers.one_hot(input=label, depth=10) + smooth_label = layers.label_smooth( + label=one_hot_label, epsilon=0.1, dtype="float32") + """ + if in_dygraph_mode(): + return _C_ops.label_smooth(label, prior_dist, float(epsilon)) + + if epsilon > 1.0 or epsilon < 0.0: + raise ValueError("The value of epsilon must be between 0 and 1.") + + if _non_static_mode(): + return _legacy_C_ops.label_smooth( + label, prior_dist, 'epsilon', float(epsilon) + ) + + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'label_smooth' + ) + + helper = LayerHelper("label_smooth", **locals()) + label.stop_gradient = True + smooth_label = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="label_smooth", + inputs={"X": label, "PriorDist": prior_dist} + if prior_dist + else {"X": label}, + outputs={"Out": smooth_label}, + attrs={"epsilon": float(epsilon)}, + ) + return smooth_label + + +@templatedoc() +def roi_pool( + input, + rois, + pooled_height=1, + pooled_width=1, + spatial_scale=1.0, + rois_num=None, + name=None, +): + """ + + This operator implements the roi_pooling layer. + Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). + + The operator has three steps: + + 1. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height; + 2. Finding the largest value in each section; + 3. Copying these max values to the output buffer. + + For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn + + Args: + input (Variable): Input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. + rois (Variable): ROIs (Regions of Interest) to pool over. 2D-LoDTensor with the shape of [num_rois,4], the lod level is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. + pooled_height (int, optional): The pooled output height, data type is int32. Default: 1 + pooled_width (int, optional): The pooled output height, data type is int32. Default: 1 + spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 + rois_num (Tensor): The number of RoIs in each image. Default: None + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + + Returns: + Variable: The pooled feature, 4D-Tensor with the shape of [num_rois, C, pooled_height, pooled_width]. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + DATATYPE='float32' + + place = fluid.CPUPlace() + #place = fluid.CUDAPlace(0) + + input_data = np.array([i for i in range(1,17)]).reshape(1,1,4,4).astype(DATATYPE) + roi_data =fluid.create_lod_tensor(np.array([[1., 1., 2., 2.], [1.5, 1.5, 3., 3.]]).astype(DATATYPE),[[2]], place) + rois_num_data = np.array([2]).astype('int32') + + x = fluid.data(name='input', shape=[None,1,4,4], dtype=DATATYPE) + rois = fluid.data(name='roi', shape=[None,4], dtype=DATATYPE) + rois_num = fluid.data(name='rois_num', shape=[None], dtype='int32') + + pool_out = fluid.layers.roi_pool( + input=x, + rois=rois, + pooled_height=1, + pooled_width=1, + spatial_scale=1.0, + rois_num=rois_num) + + exe = fluid.Executor(place) + out, = exe.run(feed={'input':input_data ,'roi':roi_data, 'rois_num': rois_num_data}, fetch_list=[pool_out.name]) + print(out) #array([[[[11.]]], [[[16.]]]], dtype=float32) + print(np.array(out).shape) # (2, 1, 1, 1) + """ + if _non_static_mode(): + assert ( + rois_num is not None + ), "rois_num should not be None in dygraph mode." + pool_out, argmaxes = _legacy_C_ops.roi_pool( + input, + rois, + rois_num, + "pooled_height", + pooled_height, + "pooled_width", + pooled_width, + "spatial_scale", + spatial_scale, + ) + return pool_out, argmaxes + + check_variable_and_dtype(input, 'input', ['float32'], 'roi_pool') + check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_pool') + helper = LayerHelper('roi_pool', **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + argmaxes = helper.create_variable_for_type_inference(dtype='int32') + + inputs = { + "X": input, + "ROIs": rois, + } + if rois_num is not None: + inputs['RoisNum'] = rois_num + helper.append_op( + type="roi_pool", + inputs=inputs, + outputs={"Out": pool_out, "Argmax": argmaxes}, + attrs={ + "pooled_height": pooled_height, + "pooled_width": pooled_width, + "spatial_scale": spatial_scale, + }, + ) + return pool_out + + +@templatedoc() +def roi_align( + input, + rois, + pooled_height=1, + pooled_width=1, + spatial_scale=1.0, + sampling_ratio=-1, + rois_num=None, + name=None, +): + """ + + ${comment} + + Args: + input (Variable): ${x_comment} + rois (Variable): ROIs (Regions of Interest) to pool over.It should be + a 2-D LoDTensor of shape (num_rois, 4), the lod level is 1. The + data type is float32 or float64. Given as [[x1, y1, x2, y2], ...], + (x1, y1) is the top left coordinates, and (x2, y2) is the bottom + right coordinates. + pooled_height (int32, optional): ${pooled_height_comment} Default: 1 + pooled_width (int32, optional): ${pooled_width_comment} Default: 1 + spatial_scale (float32, optional): ${spatial_scale_comment} Default: 1.0 + sampling_ratio(int32, optional): ${sampling_ratio_comment} Default: -1 + rois_num (Tensor): The number of RoIs in each image. Default: None + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: + + Output: ${out_comment}. + + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + x = fluid.data( + name='data', shape=[None, 256, 32, 32], dtype='float32') + rois = fluid.data( + name='rois', shape=[None, 4], dtype='float32') + rois_num = fluid.data(name='rois_num', shape=[None], dtype='int32') + align_out = fluid.layers.roi_align(input=x, + rois=rois, + pooled_height=7, + pooled_width=7, + spatial_scale=0.5, + sampling_ratio=-1, + rois_num=rois_num) + """ + if in_dygraph_mode(): + assert ( + rois_num is not None + ), "rois_num should not be None in dygraph mode." + return _C_ops.roi_align( + input, + rois, + rois_num, + pooled_height, + pooled_width, + spatial_scale, + sampling_ratio, + False, + ) + if _in_legacy_dygraph(): + assert ( + rois_num is not None + ), "rois_num should not be None in dygraph mode." + align_out = _legacy_C_ops.roi_align( + input, + rois, + rois_num, + "pooled_height", + pooled_height, + "pooled_width", + pooled_width, + "spatial_scale", + spatial_scale, + "sampling_ratio", + sampling_ratio, + ) + return align_out + + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'roi_align' + ) + check_variable_and_dtype(rois, 'rois', ['float32', 'float64'], 'roi_align') + helper = LayerHelper('roi_align', **locals()) + dtype = helper.input_dtype() + align_out = helper.create_variable_for_type_inference(dtype) + inputs = { + "X": input, + "ROIs": rois, + } + if rois_num is not None: + inputs['RoisNum'] = rois_num + helper.append_op( + type="roi_align", + inputs=inputs, + outputs={"Out": align_out}, + attrs={ + "pooled_height": pooled_height, + "pooled_width": pooled_width, + "spatial_scale": spatial_scale, + "sampling_ratio": sampling_ratio, + }, + ) + return align_out + + +def dice_loss(input, label, epsilon=0.00001, name=None): + r""" + + Dice loss for comparing the similarity between the input predictions and the label. + This implementation is for binary classification, where the input is sigmoid + predictions of each pixel, usually used for segmentation task. The dice loss can + be defined as the following equation: + + .. math:: + + dice\_loss &= 1 - \frac{2 * intersection\_area}{total\_area} \\ + &= \frac{(total\_area - intersection\_area) - intersection\_area}{total\_area} \\ + &= \frac{(union\_area - intersection\_area)}{total\_area} + + + Parameters: + input (Tensor): Tensor, rank>=2, shape is :math:`[N_1, N_2, ..., N_k, D]`, where :math:`N_1` is + the batch_size, :math:`D` is the number of categories. It is usually the output + predictions of sigmoid activation. The data type can be float32 or float64. + label (Tensor): Tensor, the groud truth with the same rank as input, shape is :math:`[N_1, N_2, ..., N_k, 1]`. + where :math:`N_1` is the batch_size. The data type can be int32 or int64. + epsilon (float): The epsilon will be added to the numerator and denominator. + If both input and label are empty, it makes sure dice is 1. + Default: 0.00001 + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tensor, which shape is [1], data type is the same as `input` . + + Example: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn((3,224,224,2)) + label = paddle.randint(high=2, shape=(3,224,224,1)) + predictions = F.softmax(x) + loss = F.dice_loss(input=predictions, label=label) + """ + return paddle.nn.functional.dice_loss( + input, label, epsilon=epsilon, name=name + ) + + +def image_resize( + input, + out_shape=None, + scale=None, + name=None, + resample='BILINEAR', + actual_shape=None, + align_corners=True, + align_mode=1, + data_format='NCHW', +): + """ + + This op resizes a batch of images. + + The input must be a 3-D Tensor of the shape (num_batches, channels, in_w) + or a 4-D Tensor of the shape (num_batches, channels, in_h, in_w) + or (num_batches, in_h, in_w, channels), or a 5-D Tensor of the shape + (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels), + and the resizing only applies on the three dimensions(depth, height and width). + + **Warning:** the parameter :attr:`actual_shape` will be deprecated in the + future and only use :attr:`out_shape` instead. + + Supporting resample methods: + 'LINEAR' : Linear interpolation + + 'BILINEAR' : Bilinear interpolation + + 'TRILINEAR' : Trilinear interpolation + + 'NEAREST' : Nearest neighbor interpolation + + 'BICUBIC' : Bicubic interpolation + + Linear interpolation is the method of using a line connecting two known quantities + to determine the value of an unknown quantity between the two known quantities. + + Nearest neighbor interpolation is to perform nearest neighbor interpolation + in both the 3rd dimension(in height direction) and the 4th dimension(in width + direction) on input tensor. + + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + Trilinear interpolation is an extension of linear interpolation for + interpolating functions of three variables (e.g. D-direction, + H-direction and W-direction in this op) on a rectilinear 3D grid. + The linear interpolation is performed on three directions. + + Bicubic interpolation is an extension of cubic interpolation for interpolating + data points on a two-dimensional regular grid. The interpolated surface is + smoother than corresponding surfaces obtained by bilinear interpolation or + nearest-neighbor interpolation. + + Align_corners and align_mode are optional parameters,the calculation method + of interpolation can be selected by them. + + Example: + + .. code-block:: text + + For scale: + + if align_corners = True && out_size > 1 : + + scale_factor = (in_size-1.0)/(out_size-1.0) + + else: + + scale_factor = float(in_size/out_size) + + + Nearest neighbor interpolation: + + if: + align_corners = False + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = floor (H_{in} * scale_{factor}) + W_out = floor (W_{in} * scale_{factor}) + + else: + align_corners = True + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = round(H_{in} * scale_{factor}) + W_out = round(W_{in} * scale_{factor}) + + linear interpolation: + + if: + align_corners = False , align_mode = 0 + + input : (N,C,W_in) + output: (N,C,W_out) where: + + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + + input : (N,C,W_in) + output: (N,C,H_out,W_out) where: + + W_out = W_{in} * scale_{factor} + + Bilinear interpolation: + + if: + align_corners = False , align_mode = 0 + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + Trilinear interpolation: + + if: + align_corners = False , align_mode = 0 + + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + + else: + + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + + D_out = D_{in} * scale_{factor} + + Trilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = D_{in} * scale_{factor} + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + + For details of linear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Linear_interpolation. + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation. + + For details of trilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Trilinear_interpolation. + + For details of bicubic interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bicubic_interpolation + + Parameters: + input (Variable): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + out_shape (list|tuple|Variable|None): Output shape of image resize + layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w) + when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor. + Default: None. If a list, each element can be an integer or a Tensor Variable of shape: [1]. + If a Tensor Variable, its dimensions size should be a 1. + scale(float|Variable|None): The multiplier for the input height or width. At + least one of :attr:`out_shape` or :attr:`scale` must be set. + And :attr:`out_shape` has a higher priority than :attr:`scale`. + Default: None. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + resample(str): The resample method. It supports 'LINEAR', 'BICUBIC', 'BILINEAR', 'TRILINEAR' + and 'NEAREST' currently. Default: 'BILINEAR' + actual_shape(Variable): An optional input to specify output shape + dynamically. If provided, image resize + according to this given shape rather than + :attr:`out_shape` and :attr:`scale` specifying + shape. That is to say actual_shape has the + highest priority. It is recommended to use + :attr:`out_shape` if you want to specify output + shape dynamically, because :attr:`actual_shape` + will be deprecated. When using actual_shape to + specify output shape, one of :attr:`out_shape` + and :attr:`scale` should also be set, otherwise + errors would be occurred in graph constructing stage. + Default: None + align_corners(bool) : An optional bool, If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the + corner pixels. + Default: True + align_mode(int) : An optional for linear/bilinear/trilinear interpolation. Refer to the fomula in the + the example code above, it can be \'0\' for src_idx = scale*(dst_indx+0.5)-0.5 , + can be \'1\' for src_idx = scale*dst_index. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + + Returns: + A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels), + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). + + Raises: + TypeError: out_shape should be a list or tuple or Variable. + TypeError: actual_shape should either be Variable or None. + ValueError: The 'resample' of image_resize can only be 'LINEAR', 'BILINEAR', + 'TRILINEAR', 'BICUBIC' or 'NEAREST' currently. + ValueError: 'LINEAR' only support 3-D tensor. + ValueError: 'BICUBIC', 'BILINEAR' and 'NEAREST' only support 4-D tensor. + ValueError: 'TRILINEAR' only support 5-D tensor. + ValueError: One of out_shape and scale must not be None. + ValueError: out_shape length should be 1 for input 3-D tensor. + ValueError: out_shape length should be 2 for input 4-D tensor. + ValueError: out_shape length should be 3 for input 5-D tensor. + ValueError: scale should be greater than zero. + TypeError: align_corners should be a bool value + ValueError: align_mode can only be '0' or '1' + ValueError: data_format can only be 'NCW', 'NWC', 'NCHW', 'NHWC', 'NCDHW' or 'NDHWC'. + + Examples: + .. code-block:: python + + #declarative mode + import paddle + import paddle.fluid as fluid + import numpy as np + paddle.enable_static() + input = fluid.data(name="input", shape=[None,3,6,10]) + + #1 + output = fluid.layers.image_resize(input=input,out_shape=[12,12]) + + #2 + #x = np.array([2]).astype("int32") + #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") + #fluid.layers.assign(input=x, output=dim1) + #output = fluid.layers.image_resize(input=input,out_shape=[12,dim1]) + + #3 + #x = np.array([3,12]).astype("int32") + #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") + #fluid.layers.assign(input=x, output=shape_tensor) + #output = fluid.layers.image_resize(input=input,out_shape=shape_tensor) + + #4 + #x = np.array([0.5]).astype("float32") + #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") + #fluid.layers.assign(x,scale_tensor) + #output = fluid.layers.image_resize(input=input,scale=scale_tensor) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(2,3,6,10).astype("float32") + + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + print(output_data[0].shape) + + #1 + # (2, 3, 12, 12) + #2 + # (2, 3, 12, 2) + #3 + # (2, 3, 3, 12) + #4 + # (2, 3, 3, 5) + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + output = fluid.layers.image_resize(input=input, out_shape=[12,12]) + print(output.shape) + + # [2L, 3L, 12L, 12L] + + """ + resample_methods = { + 'LINEAR': 'linear', + 'BILINEAR': 'bilinear', + 'TRILINEAR': 'trilinear', + 'NEAREST': 'nearest', + 'LINEAR': 'linear', + } + resample = resample.upper() + if resample not in resample_methods: + raise ValueError( + "The 'resample' of image_resize can only be 'LINEAR', 'BILINEAR', 'TRILINEAR' " + "or 'NEAREST' currently." + ) + resample_type = resample_methods[resample] + + if resample == 'LINEAR' and len(input.shape) != 3: + raise ValueError("'LINER only support 3-D tensor.") + elif resample in ['BILINEAR', 'NEAREST'] and len(input.shape) != 4: + raise ValueError("'BILINEAR' and 'NEAREST' only support 4-D tensor.") + elif resample == 'TRILINEAR' and len(input.shape) != 5: + raise ValueError("'TRILINEAR'only support 5-D tensor.") + + if not isinstance(align_corners, bool): + raise TypeError("Attr align_corners should be a bool value") + if align_mode != 0 and align_mode != 1: + raise ValueError("align_mode can only be 0 or 1") + + if out_shape is None and scale is None: + raise ValueError("One of out_shape and scale must not be None.") + helper = LayerHelper('{}_interp'.format(resample_type), **locals()) + dtype = helper.input_dtype() + + if len(input.shape) == 3 and data_format not in ['NCW', 'NWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCW` or `NWC` supported for 3-D input." + ) + elif len(input.shape) == 4 and data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCHW` or `NHWC` supported for 4-D input." + ) + elif len(input.shape) == 5 and data_format not in ['NCDHW', 'NDHWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCDHW` or `NDHWC` supported for 5-D input." + ) + + def _is_list_or_turple_(data): + return isinstance(data, list) or isinstance(data, tuple) + + if data_format == 'NCHW' or data_format == 'NCDHW' or data_format == 'NCW': + data_layout = 'NCHW' + if data_format == 'NHWC' or data_format == 'NDHWC' or data_format == 'NWC': + data_layout = 'NHWC' + + inputs = {"X": input} + attrs = { + "out_d": -1, + "out_h": -1, + "out_w": -1, + "interp_method": resample_type, + "align_corners": align_corners, + "align_mode": align_mode, + "data_layout": data_layout, + } + + if out_shape is not None: + if isinstance(out_shape, Variable) and not _non_static_mode(): + out_shape.stop_gradient = True + inputs['OutSize'] = out_shape + else: + if _non_static_mode(): + if isinstance(out_shape, Variable): + out_shape = list(out_shape.numpy()) + else: + out_shape = list(out_shape) + for i, dim in enumerate(out_shape): + if isinstance(dim, Variable): + out_shape[i] = dim.numpy()[0] + if not (_is_list_or_turple_(out_shape)): + raise TypeError( + "out_shape should be a list or tuple or Variable." + ) + # Validate the shape + contain_var = False + for dim_idx, dim_size in enumerate(out_shape): + if isinstance(dim_size, Variable): + contain_var = True + continue + assert ( + dim_size > 0 + ), "Each dimension size given in out_shape must be greater than 0." + + if contain_var: + new_size_tensor = [] + size_list = [] + for dim in out_shape: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_size_tensor.append(dim) + size_list.append(-1) + else: + assert isinstance(dim, int) + temp_out = helper.create_variable_for_type_inference( + 'int32' + ) + fill_constant( + [1], 'int32', dim, force_cpu=True, out=temp_out + ) + new_size_tensor.append(temp_out) + size_list.append(dim) + inputs['SizeTensor'] = new_size_tensor + + if len(input.shape) == 3: + if len(out_shape) != 1: + raise ValueError( + "out_shape length should be 1 for " "input 3-D tensor." + ) + if contain_var: + attrs['out_w'] = size_list[0] + else: + out_shape = list(map(int, out_shape)) + attrs['out_w'] = out_shape[0] + elif len(input.shape) == 4: + if len(out_shape) != 2: + raise ValueError( + "out_shape length should be 2 for " "input 4-D tensor." + ) + if contain_var: + attrs['out_h'] = size_list[0] + attrs['out_w'] = size_list[1] + else: + out_shape = list(map(int, out_shape)) + attrs['out_h'] = out_shape[0] + attrs['out_w'] = out_shape[1] + if len(input.shape) == 5: + if len(out_shape) != 3: + raise ValueError( + "out_shape length should be 3 for " "input 5-D tensor." + ) + if contain_var: + attrs['out_d'] = size_list[0] + attrs['out_h'] = size_list[1] + attrs['out_w'] = size_list[2] + else: + out_shape = list(map(int, out_shape)) + attrs['out_d'] = out_shape[0] + attrs['out_h'] = out_shape[1] + attrs['out_w'] = out_shape[2] + + else: + if _non_static_mode() and isinstance(scale, Variable): + scale = scale.numpy() + elif isinstance(scale, Variable): + scale.stop_gradient = True + inputs["Scale"] = scale + elif isinstance(scale, float) or isinstance(scale, int): + if scale <= 0: + raise ValueError("Attr(scale) should be greater than zero.") + attrs['scale'] = float(scale) + else: + raise TypeError( + "Attr(scale)'s type should be float, int or Variable." + ) + + if isinstance(actual_shape, Variable): + warnings.warn( + "actual_shape will be deprecated, it is recommended to use " + "out_shape instead of actual_shape to specify output shape dynamically." + ) + actual_shape.stop_gradient = True + inputs["OutSize"] = actual_shape + elif actual_shape is not None: + raise TypeError("actual_shape should either be Variable or None.") + + if _non_static_mode(): + attr_list = [] + for k, v in attrs.items(): + attr_list.append(k) + attr_list.append(v) + dy_attr = tuple(attr_list) + + if resample_type == "linear": + out = _legacy_C_ops.linear_interp(input, actual_shape, *dy_attr) + elif resample_type == "bilinear": + out = _legacy_C_ops.bilinear_interp(input, actual_shape, *dy_attr) + elif resample_type == "trilinear": + out = _legacy_C_ops.trilinear_interp(input, actual_shape, *dy_attr) + elif resample_type == "nearest": + out = _legacy_C_ops.nearest_interp(input, actual_shape, *dy_attr) + elif resample_type == "bicubic": + out = _legacy_C_ops.bicubic_interp(input, actual_shape, *dy_attr) + return out + + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='{}_interp'.format(resample_type), + inputs=inputs, + outputs={"Out": out}, + attrs=attrs, + ) + return out + + +@templatedoc(op_type="linear_interp") +def resize_linear( + input, + out_shape=None, + scale=None, + name=None, + actual_shape=None, + align_corners=True, + align_mode=1, + data_format='NCW', +): + """ + This op resizes the input by performing linear interpolation based on given + output shape which specified by actual_shape, out_shape and scale + in priority order. + + **Warning:** the parameter :attr:`actual_shape` will be deprecated in + the future and only use :attr:`out_shape` instead. + + Align_corners and align_mode are optional parameters,the calculation + method of interpolation can be selected by them. + + Example: + + .. code-block:: text + + For scale: + + if align_corners = True && out_size > 1 : + + scale_factor = (in_size-1.0)/(out_size-1.0) + + else: + + scale_factor = float(in_size/out_size) + + Linear interpolation: + + if: + align_corners = False , align_mode = 0 + + input : (N,C,W_in) + output: (N,C,W_out) where: + + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = W_{in} * scale_{factor} + + Parameters: + input(Variable): 3-D Tensor(NCW), its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + out_shape(list|tuple|Variable|None): Output shape of resize linear + layer, the shape is (out_w,). Default: None. If a list, each + element can be an integer or a Tensor Variable with shape: [1]. If a + Tensor Variable, its dimension size should be 1. + scale(float|Variable|None): The multiplier for the input height or width. At + least one of :attr:`out_shape` or :attr:`scale` must be set. + And :attr:`out_shape` has a higher priority than :attr:`scale`. + Default: None. + actual_shape(Variable): An optional input to specify output shape + dynamically. If provided, image resize + according to this given shape rather than + :attr:`out_shape` and :attr:`scale` specifying + shape. That is to say actual_shape has the + highest priority. It is recommended to use + :attr:`out_shape` if you want to specify output + shape dynamically, because :attr:`actual_shape` + will be deprecated. When using actual_shape to + specify output shape, one of :attr:`out_shape` + and :attr:`scale` should also be set, otherwise + errors would be occurred in graph constructing stage. + Default: None + align_corners(bool): ${align_corners_comment} + align_mode(bool): ${align_mode_comment} + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCW"`, `"NWC"`. + The default is `"NCW"`. When it is `"NCW"`, the data is stored in the order of: + `[batch_size, input_channels, input_width]`. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: 3-D tensor(NCW or NWC). + + Examples: + .. code-block:: python + + #declarative mode + import paddle.fluid as fluid + import numpy as np + input = fluid.data(name="input", shape=[None,3,100]) + + output = fluid.layers.resize_linear(input=input,out_shape=[50,]) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(1,3,100).astype("float32") + + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + print(output_data[0].shape) + + # (1, 3, 50) + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + output = fluid.layers.resize_linear(input=input, out_shape=[50,]) + print(output.shape) + + # [1L, 3L, 50L] + + """ + + return image_resize( + input, + out_shape, + scale, + name, + 'LINEAR', + actual_shape, + align_corners, + align_mode, + data_format, + ) + + +@templatedoc(op_type="bilinear_interp") +def resize_bilinear( + input, + out_shape=None, + scale=None, + name=None, + actual_shape=None, + align_corners=True, + align_mode=1, + data_format='NCHW', +): + """ + + This op resizes the input by performing bilinear interpolation based on given + output shape which specified by actual_shape, out_shape and scale + in priority order. + + **Warning:** the parameter :attr:`actual_shape` will be deprecated in + the future and only use :attr:`out_shape` instead. + + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation + + Align_corners and align_mode are optional parameters,the calculation + method of interpolation can be selected by them. + + Example: + + .. code-block:: text + + For scale: + + if align_corners = True && out_size > 1 : + + scale_factor = (in_size-1.0)/(out_size-1.0) + + else: + + scale_factor = float(in_size/out_size) + + Bilinear interpolation: + + if: + align_corners = False , align_mode = 0 + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + Parameters: + input(Variable): 4-D Tensor(NCHW), its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + out_shape(list|tuple|Variable|None): Output shape of resize bilinear + layer, the shape is (out_h, out_w).Default: None. If a list, each + element can be an integer or a Tensor Variable with shape: [1]. If a + Tensor Variable, its dimension size should be 1. + scale(float|Variable|None): The multiplier for the input height or width. At + least one of :attr:`out_shape` or :attr:`scale` must be set. + And :attr:`out_shape` has a higher priority than :attr:`scale`. + Default: None. + actual_shape(Variable): An optional input to specify output shape + dynamically. If provided, image resize + according to this given shape rather than + :attr:`out_shape` and :attr:`scale` specifying + shape. That is to say actual_shape has the + highest priority. It is recommended to use + :attr:`out_shape` if you want to specify output + shape dynamically, because :attr:`actual_shape` + will be deprecated. When using actual_shape to + specify output shape, one of :attr:`out_shape` + and :attr:`scale` should also be set, otherwise + errors would be occurred in graph constructing stage. + Default: None + align_corners(bool): ${align_corners_comment} + align_mode(bool): ${align_mode_comment} + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: 4-D tensor(NCHW or NHWC). + + Examples: + .. code-block:: python + + #declarative mode + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + input = fluid.data(name="input", shape=[None,3,6,10]) + + #1 + output = fluid.layers.resize_bilinear(input=input,out_shape=[12,12]) + + #2 + #x = np.array([2]).astype("int32") + #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") + #fluid.layers.assign(input=x, output=dim1) + #output = fluid.layers.resize_bilinear(input=input,out_shape=[12,dim1]) + + #3 + #x = np.array([3,12]).astype("int32") + #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") + #fluid.layers.assign(input=x, output=shape_tensor) + #output = fluid.layers.resize_bilinear(input=input,out_shape=shape_tensor) + + #4 + #x = np.array([0.5]).astype("float32") + #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") + #fluid.layers.assign(x,scale_tensor) + #output = fluid.layers.resize_bilinear(input=input,scale=scale_tensor) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(2,3,6,10).astype("float32") + + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + print(output_data[0].shape) + + #1 + # (2, 3, 12, 12) + #2 + # (2, 3, 12, 2) + #3 + # (2, 3, 3, 12) + #4 + # (2, 3, 3, 5) + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + output = fluid.layers.resize_bilinear(input=input, out_shape=[12,12]) + print(output.shape) + + # [2L, 3L, 12L, 12L] + + """ + + return image_resize( + input, + out_shape, + scale, + name, + 'BILINEAR', + actual_shape, + align_corners, + align_mode, + data_format, + ) + + +@templatedoc(op_type="trilinear_interp") +def resize_trilinear( + input, + out_shape=None, + scale=None, + name=None, + actual_shape=None, + align_corners=True, + align_mode=1, + data_format='NCDHW', +): + """ + + This op resizes the input by performing trilinear interpolation based on given + output shape which specified by actual_shape, out_shape and scale + in priority order. + + **Warning:** the parameter :attr:`actual_shape` will be deprecated + in the future and only use :attr:`out_shape` instead. + + Trilinear interpolation is an extension of linear interpolation for + interpolating functions of three variables (e.g. D-direction, + H-direction and W-direction in this op) on a rectilinear 3D grid. + The linear interpolation is performed on three directions. + + For details of trilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Trilinear_interpolation + + Align_corners and align_mode are optional parameters,the calculation + method of interpolation can be selected by them. + + Example: + + .. code-block:: text + + For scale: + + if align_corners = True && out_size > 1 : + + scale_factor = (in_size-1.0)/(out_size-1.0) + + else: + + scale_factor = float(in_size/out_size) + + Bilinear interpolation: + + if: + + align_corners = False , align_mode = 0 + + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + + D_out = D_{in} * scale_{factor} + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + Parameters: + input(${x_type}): 5-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + out_shape(list|tuple|Variable|None): The output shape of resized tensor, the shape is (out_d, out_h, out_w). Default: None. Every element should be an integer or a Tensor Variable with shape: [1] if it is a list. If it is a Tensor Variable, its dimension size should be 1. + scale(float|Variable|None): The multiplier for the input depth, height or width. + At least one of :attr:`out_shape` or :attr:`scale` must be set. + And :attr:`out_shape` has a higher priority than :attr:`scale`. + Default: None. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + actual_shape(Variable): An optional input to specify output shape + dynamically. If provided, image resize + according to this given shape rather than + :attr:`out_shape` and :attr:`scale` specifying + shape. That is to say actual_shape has the + highest priority. It is recommended to use + :attr:`out_shape` if you want to specify output + shape dynamically, because :attr:`actual_shape` + will be deprecated. When using actual_shape to + specify output shape, one of :attr:`out_shape` + and :attr:`scale` should also be set, otherwise + errors would be occurred in graph constructing stage. + Default: None + align_corners(bool): ${align_corners_comment} + align_mode(bool): ${align_mode_comment} + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + + Returns: + Variable: A 5-D Tensor(NCDHW or NDHWC) + + Examples: + .. code-block:: python + + #declarative mode + import paddle.fluid as fluid + import paddle + import numpy as np + paddle.enable_static() + input = fluid.data(name="input", shape=[None,3,6,8,10]) + + #1 + output = fluid.layers.resize_trilinear(input=input,out_shape=[12,12,12]) + + #2 + #x = np.array([2]).astype("int32") + #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") + #fluid.layers.assign(input=x, output=dim1) + #output = fluid.layers.resize_trilinear(input=input,out_shape=[12,dim1,4]) + + #3 + #x = np.array([3,12,12]).astype("int32") + #shape_tensor = fluid.data(name="shape_tensor", shape=[3], dtype="int32") + #fluid.layers.assign(input=x, output=shape_tensor) + #output = fluid.layers.resize_trilinear(input=input,out_shape=shape_tensor) + + #4 + #x = np.array([0.5]).astype("float32") + #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") + #fluid.layers.assign(x,scale_tensor) + #output = fluid.layers.resize_trilinear(input=input,scale=scale_tensor) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(2,3,6,8,10).astype("float32") + + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + print(output_data[0].shape) + + #1 + # (2, 3, 12, 12, 12) + #2 + # (2, 3, 12, 2, 4) + #3 + # (2, 3, 3, 12, 12) + #4 + # (2, 3, 3, 4, 5) + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + output = fluid.layers.resize_trilinear(input=input, out_shape=[12,12,12]) + print(output.shape) + + # [2L, 3L, 12L, 12L, 12L] + + + + """ + + return image_resize( + input, + out_shape, + scale, + name, + 'TRILINEAR', + actual_shape, + align_corners, + align_mode, + data_format, + ) + + +@templatedoc(op_type="nearest_interp") +def resize_nearest( + input, + out_shape=None, + scale=None, + name=None, + actual_shape=None, + align_corners=True, + data_format='NCHW', +): + """ + + This op resizes the input by performing nearest neighbor interpolation in both the + height direction and the width direction based on given output shape + which is specified by actual_shape, out_shape and scale in priority order. + + **Warning:** the parameter :attr:`actual_shape` will be deprecated in the + future and only use :attr:`out_shape` instead. + + Example: + + .. code-block:: text + + For scale: + + if align_corners = True && out_size > 1 : + scale_factor = (in_size-1.0)/(out_size-1.0) + + else: + + scale_factor = float(in_size/out_size) + + Nearest neighbor interpolation: + + if: + align_corners = False + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = floor(H_{in} * scale_{factor}) + W_out = floor(W_{in} * scale_{factor}) + + else: + align_corners = True + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + + H_out = round(H_{in} * scale_{factor}) + W_out = round(W_{in} * scale_{factor}) + + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation + + Parameters: + input(${x_type}): 4-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + out_shape(list|tuple|Variable|None): The output shape of resized tensor, the shape is (out_h, out_w). Default: None. Every element should be an integer or a tensor Variable with shape: [1] if it is a list. If it is a tensor Variable, its dimension size should be 1. + scale(float|Variable|None): The multiplier for the input height or width. At + least one of :attr:`out_shape` or :attr:`scale` must be set. + And :attr:`out_shape` has a higher priority than :attr:`scale`. + Default: None. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + actual_shape(Variable): An optional input to specify output shape + dynamically. If provided, image resize + according to this given shape rather than + :attr:`out_shape` and :attr:`scale` specifying + shape. That is to say actual_shape has the + highest priority. It is recommended to use + :attr:`out_shape` if you want to specify output + shape dynamically, because :attr:`actual_shape` + will be deprecated. When using actual_shape to + specify output shape, one of :attr:`out_shape` + and :attr:`scale` should also be set, otherwise + errors would be occurred in graph constructing stage. + Default: None + align_corners(bool): ${align_corners_comment} + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + + Returns: + Variable: 4-D tensor(NCHW or NHWC). + + Examples: + .. code-block:: python + + #declarative mode + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + input = fluid.data(name="input", shape=[None,3,6,10]) + + #1 + output = fluid.layers.resize_nearest(input=input,out_shape=[12,12]) + + #2 + #x = np.array([2]).astype("int32") + #dim1 = fluid.data(name="dim1", shape=[1], dtype="int32") + #fluid.layers.assign(input=x, output=dim1) + #output = fluid.layers.resize_nearest(input=input,out_shape=[12,dim1]) + + #3 + #x = np.array([3,12]).astype("int32") + #shape_tensor = fluid.data(name="shape_tensor", shape=[2], dtype="int32") + #fluid.layers.assign(input=x, output=shape_tensor) + #output = fluid.layers.resize_nearest(input=input,out_shape=shape_tensor) + + #4 + #x = np.array([0.5]).astype("float32") + #scale_tensor = fluid.data(name="scale", shape=[1], dtype="float32") + #fluid.layers.assign(x,scale_tensor) + #output = fluid.layers.resize_nearest(input=input,scale=scale_tensor) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(2,3,6,10).astype("float32") + + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + print(output_data[0].shape) + + #1 + # (2, 3, 12, 12) + #2 + # (2, 3, 12, 2) + #3 + # (2, 3, 3, 12) + #4 + # (2, 3, 3, 5) + + #imperative mode + import paddle.fluid.dygraph as dg + + with dg.guard(place) as g: + input = dg.to_variable(input_data) + output = fluid.layers.resize_nearest(input=input, out_shape=[12,12]) + print(output.shape) + + # [2L, 3L, 12L, 12L] + + + + """ + + return image_resize( + input, + out_shape, + scale, + name, + 'NEAREST', + actual_shape, + align_corners, + align_mode=1, + data_format=data_format, + ) + + +def image_resize_short(input, out_short_len, resample='BILINEAR'): + """ + This op resizes a batch of images. The short edge of input images will be + resized to the given 'out_short_len'. The long edge of input images + will be resized proportionately to make images' length-width ratio + constant. + + Parameters: + input (Variable): 4-D tensor(NCHW), The input tensor of image resize layer. + out_short_len(int): The length of output images' short edge. + resample (str): resample method, default: BILINEAR. + + Returns: + Variable: 4-D tensor(NCHW). + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + input = fluid.data(name="input", shape=[None,3,6,9], dtype="float32") + out = fluid.layers.image_resize_short(input, out_short_len=3) + """ + in_shape = input.shape + if len(in_shape) != 4: + raise ValueError( + "The rank of input must be 4 (num_batches, channels, in_h, in_w)." + ) + hw = in_shape[2:4] + short_idx = hw.index(min(hw)) + long_idx = 1 - short_idx + out_shape = list(hw) + out_shape[short_idx] = out_short_len + out_shape[long_idx] = int( + float(out_shape[long_idx]) + * (float(out_short_len) / float(hw[short_idx])) + + 0.5 + ) + return image_resize(input=input, out_shape=out_shape, resample=resample) + + +@deprecated(since="2.0.0", update_to="paddle.gather") +def gather(input, index, overwrite=True): + """ + + Output is obtained by gathering entries of the outer-most dimension + of X indexed by `index` and concatenate them together. + + .. math:: + + Out = X[Index] + + + .. code-block:: text + + + Given: + + X = [[1, 2], + [3, 4], + [5, 6]] + + Index = [1, 2] + + Then: + + Out = [[3, 4], + [5, 6]] + + Args: + input (Tensor): The source input tensor with rank>=1. Supported data type is + int32, int64, float32, float64 and uint8 (only for CPU), + float16 (only for GPU). + index (Tensor): The index input tensor with rank=1. Data type is int32 or int64. + overwrite (bool, optional): The mode that updating the grad when has same index. + If True, use the overwrite mode to update the grad of the same index, + if False, use the accumulate mode to update the grad of the same index. + Default value is True. + + Returns: + output (Tensor): The output is a tensor with the same rank as input. + + Examples: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + x = fluid.data(name='x', shape=[-1, 5], dtype='float32') + index = fluid.data(name='index', shape=[-1, 1], dtype='int32') + output = fluid.layers.gather(x, index) + """ + if _non_static_mode(): + return _legacy_C_ops.gather(input, index, None, 'overwrite', overwrite) + + check_variable_and_dtype( + input, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'], + 'gather', + ) + check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather') + helper = LayerHelper('gather', **locals()) + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="gather", + inputs={"X": input, "Index": index}, + outputs={"Out": out}, + attrs={'overwrite': overwrite}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.gather_nd") +def gather_nd(input, index, name=None): + """ + **Gather Nd Layer** + + This function is actually a high-dimensional extension of :code:`gather` + and supports for simultaneous indexing by multiple axes. :attr:`index` is a + K-dimensional integer tensor, which is regarded as a (K-1)-dimensional + tensor of :attr:`index` into :attr:`input`, where each element defines + a slice of params: + + .. math:: + + output[(i_0, ..., i_{K-2})] = input[index[(i_0, ..., i_{K-2})]] + + Obviously, :code:`index.shape[-1] <= input.rank` . And, the output tensor has + shape :code:`index.shape[:-1] + input.shape[index.shape[-1]:]` . + + .. code-block:: text + + Given: + input = [[[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]], + [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]]] + input.shape = (2, 3, 4) + + * Case 1: + index = [[1]] + + gather_nd(input, index) + = [input[1, :, :]] + = [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]] + + * Case 2: + index = [[0,2]] + + gather_nd(input, index) + = [input[0, 2, :]] + = [8, 9, 10, 11] + + * Case 3: + index = [[1, 2, 3]] + + gather_nd(input, index) + = [input[1, 2, 3]] + = [23] + + Args: + input (Tensor): The input Tensor which it's data type should be bool, float32, float64, int32, int64. + index (Tensor): The index input with rank > 1, index.shape[-1] <= input.rank. + Its dtype should be int32, int64. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + output (Tensor): A tensor with the shape index.shape[:-1] + input.shape[index.shape[-1]:] + + Examples: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + x = fluid.data(name='x', shape=[3, 4, 5], dtype='float32') + index = fluid.data(name='index', shape=[2, 2], dtype='int32') + output = fluid.layers.gather_nd(x, index) + + """ + if in_dygraph_mode(): + return _C_ops.gather_nd(input, index) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.gather_nd(input, index) + check_variable_and_dtype( + input, + 'input', + ['bool', 'float32', 'float64', 'int16', 'int32', 'int64'], + 'gather_np', + ) + check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather_np') + helper = LayerHelper('gather_nd', **locals()) + dtype = helper.input_dtype() + output = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="gather_nd", + inputs={"X": input, "Index": index}, + outputs={"Out": output}, + ) + return output + + +@deprecated(since="2.0.0", update_to="paddle.scatter") +def scatter(input, index, updates, name=None, overwrite=True): + """ + :alias_main: paddle.scatter + :alias: paddle.scatter,paddle.tensor.scatter,paddle.tensor.manipulation.scatter + :old_api: paddle.fluid.layers.scatter + + **Scatter Layer** + + Output is obtained by updating the input on selected indices based on updates. + + .. code-block:: python + + import numpy as np + + #input: + input = np.array([[1, 1], [2, 2], [3, 3]]) + index = np.array([2, 1, 0, 1]) + # shape of updates should be the same as input + # shape of updates with dim > 1 should be the same as input + updates = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) + overwrite = False + + # calculation: + if not overwrite: + for i in range(len(index)): + input[index[i]] = np.zeros((2)) + + for i in range(len(index)): + if (overwrite): + input[index[i]] = updates[i] + else: + input[index[i]] += updates[i] + # output: + out = np.array([[3, 3], [6, 6], [1, 1]]) + out.shape # [3, 2] + + Args: + input (Variable): The input N-D Tensor with rank>=1. Data type can be float32. + index (Variable): The index 1-D Tensor. Data type can be int32, int64. The length of index cannot exceed updates's length, and the value in index cannot exceed input's length. + updates (Variable): update input with updates parameter based on index. shape should be the same as input, and dim value with dim > 1 should be the same as input. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + overwrite (bool): The mode that updating the output when there are same indices. + If True, use the overwrite mode to update the output of the same index, + if False, use the accumulate mode to update the output of the same index. + Default value is True. + + Returns: + Variable(Tensor|LoDTensor): The output is a Tensor with the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + import paddle.fluid as fluid + paddle.enable_static() + + input = fluid.layers.data(name='data', shape=[3, 2], dtype='float32', append_batch_size=False) + index = fluid.layers.data(name='index', shape=[4], dtype='int64', append_batch_size=False) + updates = fluid.layers.data(name='update', shape=[4, 2], dtype='float32', append_batch_size=False) + + output = fluid.layers.scatter(input, index, updates, overwrite=False) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + in_data = np.array([[1, 1], [2, 2], [3, 3]]).astype(np.float32) + index_data = np.array([2, 1, 0, 1]).astype(np.int64) + update_data = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]).astype(np.float32) + + res = exe.run(fluid.default_main_program(), feed={'data':in_data, "index":index_data, "update":update_data}, fetch_list=[output]) + print(res) + # [array([[3., 3.], + # [6., 6.], + # [1., 1.]], dtype=float32)] + """ + helper = LayerHelper('scatter', **locals()) + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="scatter", + inputs={"X": input, "Ids": index, "Updates": updates}, + attrs={'overwrite': overwrite}, + outputs={"Out": out}, + ) + return out + + +def scatter_nd_add(ref, index, updates, name=None): + r""" + **Scatter_nd_add Layer** + + Output is obtained by applying sparse addition to a single value + or slice in a Variable. + + :attr:`ref` is a Tensor with rank :math:`R` + and :attr:`index` is a Tensor with rank :math:`K` . Thus, :attr:`index` + has shape :math:`[i_0, i_1, ..., i_{K-2}, Q]` where :math:`Q \leq R` . :attr:`updates` + is a Tensor with rank :math:`K - 1 + R - Q` and its + shape is :math:`index.shape[:-1] + ref.shape[index.shape[-1]:]` . + + According to the :math:`[i_0, i_1, ..., i_{K-2}]` of :attr:`index` , + add the corresponding :attr:`updates` slice to the :attr:`ref` slice + which is obtained by the last one dimension of :attr:`index` . + + .. code-block:: text + + Given: + + * Case 1: + ref = [0, 1, 2, 3, 4, 5] + index = [[1], [2], [3], [1]] + updates = [9, 10, 11, 12] + + we get: + + output = [0, 22, 12, 14, 4, 5] + + * Case 2: + ref = [[65, 17], [-14, -25]] + index = [[], []] + updates = [[[-1, -2], [1, 2]], + [[3, 4], [-3, -4]]] + ref.shape = (2, 2) + index.shape = (2, 0) + updates.shape = (2, 2, 2) + + we get: + + output = [[67, 19], [-16, -27]] + + Args: + ref (Variable): The ref input. Its dtype should be int32, int64, float32, float64. + index (Variable): The index input with rank > 1 and index.shape[-1] <= ref.rank. + Its dtype should be int32 or int64 as it is used as indexes. + updates (Variable): The updated value of scatter_nd_add op, and it must have the same dtype + as ref. It must have the shape index.shape[:-1] + ref.shape[index.shape[-1]:]. + name (str|None): The output variable name. If set None, the layer will be named automatically. + + Returns: + output (Variable): The output is a tensor with the same shape and dtype as ref. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + ref = fluid.data(name='ref', shape=[3, 5, 9, 10], dtype='float32') + index = fluid.data(name='index', shape=[3, 2], dtype='int32') + updates = fluid.data(name='update', shape=[3, 9, 10], dtype='float32') + + output = fluid.layers.scatter_nd_add(ref, index, updates) + """ + + if in_dygraph_mode(): + return _C_ops.scatter_nd_add(ref, index, updates) + else: + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, 'scatter_nd_add') + return op(ref, index, updates) + else: + if ref.dtype != updates.dtype: + raise ValueError("ref and updates must have same data type.") + + helper = LayerHelper('scatter_nd_add', **locals()) + dtype = helper.input_dtype(input_param_name='ref') + output = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="scatter_nd_add", + inputs={"X": ref, "Index": index, "Updates": updates}, + outputs={"Out": output}, + ) + return output + + +def scatter_nd(index, updates, shape, name=None): + """ + **Scatter_nd Layer** + + Output is obtained by scattering the :attr:`updates` in a new tensor according + to :attr:`index` . This op is similar to :code:`scatter_nd_add`, except the + tensor of :attr:`shape` is zero-initialized. Correspondingly, :code:`scatter_nd(index, updates, shape)` + is equal to :code:`scatter_nd_add(paddle.zeros(shape, updates.dtype), index, updates)` . + If :attr:`index` has repeated elements, then the corresponding updates are accumulated. + Because of the numerical approximation issues, the different order of repeated elements + in :attr:`index` may cause different results. The specific calculation method can be + seen :code:`scatter_nd_add` . This op is the inverse of the :code:`gather_nd` op. + + Args: + index (Tensor): The index input with ndim > 1 and index.shape[-1] <= len(shape). + Its dtype should be int32 or int64 as it is used as indexes. + updates (Tensor): The updated value of scatter_nd op. Its dtype should be float32, float64. + It must have the shape index.shape[:-1] + shape[index.shape[-1]:] + shape(tuple|list): Shape of output tensor. + name (str|None): The output Tensor name. If set None, the layer will be named automatically. + + Returns: + output (Tensor): The output is a tensor with the same type as :attr:`updates` . + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + index_data = np.array([[1, 1], + [0, 1], + [1, 3]]).astype(np.int64) + index = paddle.to_tensor(index_data) + updates = paddle.rand(shape=[3, 9, 10], dtype='float32') + shape = [3, 5, 9, 10] + + output = paddle.scatter_nd(index, updates, shape) + """ + return scatter_nd_add(zeros(shape, updates.dtype), index, updates, name) + + +@templatedoc() +def random_crop(x, shape, seed=None): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment} + shape(${shape_type}): ${shape_comment} + seed(int|${seed_type}|None): ${seed_comment} By default, the seed will + get from `random.randint(-65536, 65535)`. + + Returns: + ${out_comment} + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + img = fluid.data("img", [None, 3, 256, 256]) + # cropped_img is [-1, 3, 224, 224] + cropped_img = fluid.layers.random_crop(img, shape=[3, 224, 224]) + + # cropped_img2 shape: [-1, 2, 224, 224] + # cropped_img2 = fluid.layers.random_crop(img, shape=[2, 224, 224]) + + # cropped_img3 shape: [-1, 3, 128, 224] + # cropped_img3 = fluid.layers.random_crop(img, shape=[128, 224]) + + """ + helper = LayerHelper("random_crop", **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'uint8', 'int16', 'int32'], 'random_crop' + ) + check_type(shape, 'shape', (list, Variable), 'random_crop') + dtype = x.dtype + out = helper.create_variable_for_type_inference(dtype) + if seed is None: + seed = np.random.randint(-65536, 65536) + op_attrs = {"shape": shape} + if isinstance(seed, int): + op_attrs["startup_seed"] = seed + seed = helper.create_variable( + name=unique_name.generate("random_crop_seed"), + dtype="int64", + persistable=True, + ) + elif not isinstance(seed, Variable): + raise ValueError("'seed' must be a Variable or an int.") + helper.append_op( + type="random_crop", + inputs={"X": x, "Seed": seed}, + outputs={"Out": out, "SeedOut": seed}, + attrs=op_attrs, + ) + return out + + +def log(x, name=None): + r""" + Calculates the natural log of the given input tensor, element-wise. + + .. math:: + + Out = \\ln(x) + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + + Returns: + Tensor: The natural log of the input Tensor computed element-wise. + + Examples: + + .. code-block:: python + + import paddle + + x = [[2,3,4], [7,8,9]] + x = paddle.to_tensor(x, dtype='float32') + res = paddle.log(x) + # [[0.693147, 1.09861, 1.38629], [1.94591, 2.07944, 2.19722]] + """ + if in_dygraph_mode(): + return _C_ops.log(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.log(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], "log") + inputs = {'X': [x]} + helper = LayerHelper('log', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="log", inputs={"X": x}, outputs={"Out": out}) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.relu") +def relu(x, name=None): + """ + ${comment} + + Args: + x(Variable): ${x_comment} + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Variable: ${out_comment} + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + in1 = np.array([[-1,0],[1,2.6]]) + with fluid.dygraph.guard(): + x1 = fluid.dygraph.to_variable(in1) + out1 = fluid.layers.relu(x1) + print(out1.numpy()) + # [[0. 0. ] + # [1. 2.6]]""" + + if in_dygraph_mode(): + return _C_ops.relu(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.relu(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu') + + inputs = {'X': [x]} + helper = LayerHelper('relu', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="relu", inputs={"X": helper.input('x')}, outputs={"Out": out} + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.selu") +def selu(x, scale=None, alpha=None, name=None): + r""" + + Selu Operator. + + The equation is: + + .. math:: + selu= \\lambda* + \\begin{cases} + x &\\quad \\text{ if } x>0 \n + \\alpha * e^x - \\alpha &\\quad \\text{ if } x<=0 + \\end{cases} + + + The input `X` can carry the LoD (Level of Details) information, + or not. And the output shares the LoD information with input `X`. + + Args: + x (Variable): The input N-D Tensor. + scale(float, optional): lambda in selu activation function, + the default value is 1.0507009873554804934193349852946. + For more information about this value, please refer + to: https://arxiv.org/abs/1706.02515. + alpha(float, optional): alpha in selu activation function, + the default value is 1.6732632423543772848170429916717. + For more information about this value, please refer + to: https://arxiv.org/abs/1706.02515. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + + Returns: + Variable(Tensor|LoDTensor): The output Tensor or LoDTensor with the same shape and LoD information as input. + + Examples: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + paddle.enable_static() + + inputs = fluid.layers.data(name="x", shape=[2, 2], dtype="float32") + output = fluid.layers.selu(inputs) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + img = np.array([[0, 1],[2, 3]]).astype(np.float32) + + res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) + print(res) # [array([[0. , 1.050701],[2.101402, 3.152103]], dtype=float32)] + """ + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'selu') + + helper = LayerHelper('selu', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + attrs = {} + if scale is not None: + attrs["scale"] = scale + if alpha is not None: + attrs["alpha"] = alpha + + helper.append_op( + type="selu", inputs={"X": x}, outputs={"Out": out}, attrs=attrs + ) + return out + + +def mean_iou(input, label, num_classes): + r""" + Mean Intersection-Over-Union is a common evaluation metric for + semantic image segmentation, which first computes the IOU for each + semantic class and then computes the average over classes. + IOU is defined as follows: + + .. math:: + + IOU = \\frac{true\_positive}{(true\_positive + false\_positive + false\_negative)}. + + The predictions are accumulated in a confusion matrix and mean-IOU + is then calculated from it. + + + Parameters: + input (Tensor): A n-D Tensor of prediction results for semantic labels with type int32 or int64. + label (Tensor): A Tensor of ground truth labels with type int32 or int64. + Its shape should be the same as input. + num_classes (int32): The possible number of labels. + + Returns: + Three Tensors. + + - mean_iou(Tensor) : A 1-D Tensor representing the mean intersection-over-union with shape [1]. \ + Data type is float32. + - out_wrong(Tensor) : A 1-D Tensor with shape [num_classes]. Data type is int32. \ + The wrong numbers of each class. + - out_correct(Tensor): A 1-D Tensor with shape [num_classes]. Data type is int32. The correct numbers of each class. + + + Examples: + + .. code-block:: python + + import paddle + + iou_shape = [64, 32, 32] + num_classes = 5 + predict = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64') + label = paddle.randint(low=0, high=255, shape=iou_shape, dtype='int64') + mean_iou, out_wrong, out_correct = paddle.metric.mean_iou(predict, label, num_classes) + """ + if _non_static_mode(): + return _legacy_C_ops.mean_iou(input, label, 'num_classes', num_classes) + + helper = LayerHelper('mean_iou', **locals()) + check_variable_and_dtype( + input, 'Predictions', ['int32', 'int64'], 'mean_iou' + ) + check_variable_and_dtype(label, 'Labels', ['int32', 'int64'], 'mean_iou') + out_mean_iou = helper.create_variable_for_type_inference(dtype='float32') + out_wrong = helper.create_variable_for_type_inference(dtype='int32') + out_correct = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op( + type="mean_iou", + inputs={"Predictions": input, "Labels": label}, + outputs={ + "OutMeanIou": out_mean_iou, + "OutWrong": out_wrong, + "OutCorrect": out_correct, + }, + attrs={"num_classes": num_classes}, + ) + return out_mean_iou, out_wrong, out_correct + + +def crop(x, shape=None, offsets=None, name=None): + """ + Crop input into output, as specified by offsets and shape. + + **Warning:** THIS OP IS DEPRECATED. It will be removed in the future version. + Instructions for updating: Use :ref:`api_fluid_layers_crop_tensor` instead. + + .. code-block:: text + + * Case 1: + Given + X = [[0, 1, 2, 0, 0] + [0, 3, 4, 0, 0] + [0, 0, 0, 0, 0]], + and + shape = [2, 2], + offsets = [0, 1], + output is: + Out = [[1, 2], + [3, 4]]. + * Case 2: + Given + X = [[0, 1, 2, 5, 0] + [0, 3, 4, 6, 0] + [0, 0, 0, 0, 0]], + and shape is tensor + shape = [[0, 0, 0] + [0, 0, 0]] + and + offsets = [0, 1], + + output is: + Out = [[1, 2, 5], + [3, 4, 6]]. + + Parameters: + x (Variable): Tensor, data type can be float32 or float64. + shape (Variable|list/tuple of integers, optional): The output shape is specified + by `shape`, which can be a Tensor or a list/tuple of integers. + If it is a Tensor, it's rank must be the same as `x` , only + it's shape will be used, and the value of it will be ignored. This way + is suitable for the case that the output shape may be changed each + iteration. If it is a list/tuple of integers, it's length must be the same + as the rank of `x` + offsets (Variable|list/tuple of integers|None, optional): Specifies the cropping + offsets at each dimension. It can be a Tensor or a list/tuple + of integers. If it is a Tensor, it's rank must be the same as `x`. + This way is suitable for the case that the offsets may be changed + each iteration. If it is a list/tuple of integers, it's length must be the + same as the rank of `x`. If None, the offsets are 0 at each dimension. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name` . Usually name is no need to set and + None by default. + + Returns: + Tensor, The cropped Tensor, which has the same rank and data type with `x`. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid as fluid + import paddle + paddle.enable_static() + x = fluid.data(name="x", shape=[3, 3, 5], dtype="float32") + y = fluid.data(name="y", shape=[2, 2, 3], dtype="float32") + crop = fluid.layers.crop(x, shape=y) + + # or + z = fluid.data(name="z", shape=[3, 3, 5], dtype="float32") + crop = fluid.layers.crop(z, shape=[2, 2, 3]) + + """ + check_variable_and_dtype(x, 'x', ['float32'], 'crop') + check_type(shape, 'shape', (list, tuple, Variable), 'crop') + helper = LayerHelper('crop', **locals()) + + if offsets is None: + offsets = [0] * len(x.shape) + + out = helper.create_variable_for_type_inference(x.dtype) + ipts = {'X': x} + attrs = {} + if isinstance(shape, Variable): + ipts['Y'] = shape + else: + attrs['shape'] = shape + if isinstance(offsets, Variable): + ipts['Offsets'] = offsets + else: + attrs['offsets'] = offsets + + helper.append_op( + type='crop', + inputs=ipts, + outputs={'Out': out}, + attrs=None if len(attrs) == 0 else attrs, + ) + return out + + +def crop_tensor(x, shape=None, offsets=None, name=None): + """ + Crop input into output, as specified by offsets and shape. + + .. code-block:: text + + * Case 1 (input is a 2-D Tensor): + Input: + X.shape = [3, 5] + X.data = [[0, 1, 2, 0, 0], + [0, 3, 4, 0, 0], + [0, 0, 0, 0, 0]] + Parameters: + shape = [2, 2] + offsets = [0, 1] + Output: + Out.shape = [2, 2] + Out.data = [[1, 2], + [3, 4]] + * Case 2 (input is a 3-D Tensor): + Input: + 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]]] + Parameters: + shape = [2, 2, -1] + offsets = [0, 0, 1] + Output: + Out.shape = [2, 2, 3] + Out.data = [[[1, 2, 3], + [5, 6, 7]], + [[3, 4, 5], + [6, 7, 8]]] + + Parameters: + x (Tensor): 1-D to 6-D Tensor, the data type is float32, float64, int32 or int64. + shape (list|tuple|Tensor): The output shape is specified + by `shape`. Its data type is int32. If a list/tuple, it's length must be + the same as the dimension size of `x`. If a Tensor, it should be a 1-D Tensor. + When it is a list, each element can be an integer or a Tensor of shape: [1]. + If Variable contained, it is suitable for the case that the shape may + be changed each iteration. + offsets (list|tuple|Variable, optional): Specifies the cropping + offsets at each dimension. Its data type is int32. If a list/tuple, it's length + must be the same as the dimension size of `x`. If a Tensor, it should be a 1-D + Tensor. When it is a list, each element can be an integer or a Tensor of shape: [1]. + If Variable contained, it is suitable for the case that the offsets may be changed + each iteration. Default: None, the offsets are 0 at each dimension. + name(str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: The cropped Tensor has same data type with `x`. + + Examples: + + .. code-block:: python + :name: code-example1 + + import paddle + x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + # x.shape = [3, 3] + # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + + # shape can be a 1-D Tensor or list or tuple. + shape = paddle.to_tensor([2, 2], dtype='int32') + # shape = [2, 2] + # shape = (2, 2) + out = paddle.crop(x, shape) + # out.shape = [2, 2] + # out = [[1,2], [4,5]] + + # offsets can be a 1-D Tensor or list or tuple. + offsets = paddle.to_tensor([0, 1], dtype='int32') + # offsets = [1, 0] + # offsets = (1, 1) + out = paddle.crop(x, shape, offsets) + # out.shape = [2, 2] + # if offsets = [0, 0], out = [[1,2], [4,5]] + # if offsets = [0, 1], out = [[2,3], [5,6]] + # if offsets = [1, 0], out = [[4,5], [7,8]] + # if offsets = [1, 1], out = [[5,6], [8,9]] + + """ + helper = LayerHelper('crop_tensor', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'crop_tensor' + ) + check_type(shape, 'shape', (list, tuple, Variable), 'crop_tensor') + check_type( + offsets, 'offsets', (list, tuple, Variable, type(None)), 'crop_tensor' + ) + + if offsets is None: + offsets = [0] * len(x.shape) + + out = helper.create_variable_for_type_inference(x.dtype) + ipts = {'X': x} + attrs = {} + + def _attr_shape_check(shape_val): + if not isinstance(shape_val, int): + raise TypeError( + "Attr(shape)'s dtype of Op(crop_tensor) should be int32, but received: %s." + % type(shape_val) + ) + if shape_val == 0: + raise ValueError( + "Attr(shape) of Op(crop_tensor) should not be zero, but received: %s." + % str(shape_val) + ) + if shape_val < -1: + raise ValueError( + "When the element in Attr(shape) of Op(crop_tensor) is negative, only -1 is supported, but received: %s." + % str(shape_val) + ) + + def _attr_offsets_check(offset_val): + if not isinstance(offset_val, int): + raise TypeError( + "Attr(offsets)'s dtype of Op(crop_tensor) should be int32, but received: %s." + % type(offset_val) + ) + if offset_val < 0: + raise ValueError( + "Attr(offsets) of Op(crop_tensor) should be greater or equal to zero, but received: %s." + % str(offset_val) + ) + + if isinstance(offsets, Variable): + offsets.stop_gradient = True + ipts['Offsets'] = offsets + attrs['offsets'] = [-1] * len(x.shape) + elif utils._contain_var(offsets): + new_offsets_tensor = [] + offsets_attr = [] + for dim in offsets: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_offsets_tensor.append(dim) + offsets_attr.append(-1) + else: + _attr_offsets_check(dim) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) + new_offsets_tensor.append(temp_out) + offsets_attr.append(dim) + ipts['OffsetsTensor'] = new_offsets_tensor + attrs['offsets'] = offsets_attr + else: + for offset in offsets: + _attr_offsets_check(offset) + attrs['offsets'] = offsets + + if isinstance(shape, Variable): + shape.stop_gradient = True + ipts['Shape'] = shape + elif utils._contain_var(shape): + new_shape_tensor = [] + shape_attr = [] + for dim_size in shape: + if isinstance(dim_size, Variable): + dim_size.stop_gradient = True + new_shape_tensor.append(dim_size) + shape_attr.append(0) + else: + _attr_shape_check(dim_size) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant( + [1], 'int32', dim_size, force_cpu=True, out=temp_out + ) + new_shape_tensor.append(temp_out) + shape_attr.append(dim_size) + ipts['ShapeTensor'] = new_shape_tensor + attrs['shape'] = shape_attr + else: + for dim_size in shape: + _attr_shape_check(dim_size) + attrs['shape'] = shape + + helper.append_op( + type='crop_tensor', + inputs=ipts, + outputs={'Out': out}, + attrs=None if len(attrs) == 0 else attrs, + ) + return out + + +def affine_grid(theta, out_shape, name=None): + """ + :alias_main: paddle.nn.functional.affine_grid + :alias: paddle.nn.functional.affine_grid,paddle.nn.functional.vision.affine_grid + :old_api: paddle.fluid.layers.affine_grid + + It generates a grid of (x,y) coordinates using the parameters of + the affine transformation that correspond to a set of points where + the input feature map should be sampled to produce the transformed + output feature map. + + Args: + theta (Variable) - A Tensor with shape [N, 2, 3]. It contains a batch of affine transform parameters. + The data type can be float32 or float64. + out_shape (Variable | list | tuple): The shape of target output with format [batch_size, channel, height, width]. + ``out_shape`` can be a Tensor or a list or tuple. The data + type must be int32. + name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Variable: A Tensor with shape [batch_size, H, W, 2] while 'H' and 'W' are the height and width of feature map in affine transformation. The data type is the same as `theta`. + + Raises: + ValueError: If the type of arguments is not supported. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + place = fluid.CPUPlace() + theta = fluid.data(name="x", shape=[None, 2, 3], dtype="float32") + out_shape = fluid.data(name="y", shape=[4], dtype="int32") + grid_0 = fluid.layers.affine_grid(theta, out_shape) + grid_1 = fluid.layers.affine_grid(theta, [5, 3, 28, 28]) + batch_size=2 + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + output= exe.run(feed={"x": np.random.rand(batch_size,2,3).astype("float32"), + "y": np.array([5, 3, 28, 28]).astype("int32")}, + fetch_list=[grid_0.name, grid_1.name]) + print(output[0]) + print(output[1]) + """ + helper = LayerHelper('affine_grid') + + check_variable_and_dtype( + theta, 'theta', ['float32', 'float64'], 'affine_grid' + ) + + if not ( + isinstance(out_shape, list) + or isinstance(out_shape, tuple) + or isinstance(out_shape, Variable) + ): + raise ValueError("The out_shape should be a list, tuple or Variable.") + + if not isinstance(theta, Variable): + raise ValueError("The theta should be a Variable.") + + out = helper.create_variable_for_type_inference(theta.dtype) + ipts = {'Theta': theta} + attrs = {} + if isinstance(out_shape, Variable): + ipts['OutputShape'] = out_shape + check_variable_and_dtype( + out_shape, 'out_shape', ['int32'], 'affine_grid' + ) + else: + attrs['output_shape'] = out_shape + if core.is_compiled_with_rocm(): + # ROCM platform do not have MIOPEN kernel for affine_grid + attrs['use_cudnn'] = False + + helper.append_op( + type='affine_grid', + inputs=ipts, + outputs={'Output': out}, + attrs=None if len(attrs) == 0 else attrs, + ) + return out + + +def pad2d( + input, + paddings=[0, 0, 0, 0], + mode='constant', + pad_value=0.0, + data_format="NCHW", + name=None, +): + """ + + Pad 2-d images according to 'paddings' and 'mode'. + If mode is 'reflect', paddings[0] and paddings[1] must be no greater + than height-1. And the width dimension has the same condition. + + Parameters: + input (Tensor): The input image with [N, C, H, W] format or [N, H, W, C] format, which is a 4-D Tensor with data type float32. + paddings (Tensor | List[int32]): The padding size. If padding is a List, it must + contain four integers, (padding_top, padding_bottom, padding_left, padding_right). + Otherwise, it is a 1-D Tensor with shape [4]. Data type is int32. + Default is [0, 0, 0, 0]. + mode (str): Three modes: 'constant' (default), 'reflect', 'edge' . + When in 'constant' mode, this op uses a constant value to pad the input tensor. + When in 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + When in 'edge' mode, uses input boundaries to pad the input tensor. + Default is 'constant' + pad_value (float32): The value to fill the padded areas in 'constant' mode . Default is 0.0 + data_format (str): An string from: "NHWC", "NCHW". Specify the data format of + the input data. + Default is "NCHW" + name (str, optional) : The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor, a 4-D Tensor padded according to paddings and mode and data type is same as input. + + Examples: + .. code-block:: text + + Input = [[[[1., 2., 3.], + [4., 5., 6.]]]] + + Case 0: + paddings = [0, 1, 2, 3], + mode = 'constant' + pad_value = 0 + Out = [[[[0., 0., 1., 2., 3., 0., 0., 0.], + [0., 0., 4., 5., 6., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.]]]] + + Case 1: + paddings = [0, 1, 2, 1], + mode = 'reflect' + Out = [[[[3., 2., 1., 2., 3., 2.], + [6., 5., 4., 5., 6., 5.], + [3., 2., 1., 2., 3., 2.]]]] + + Case 2: + paddings = [0, 1, 2, 1], + mode = 'edge' + Out = [[[[1., 1., 1., 2., 3., 3.], + [4., 4., 4., 5., 6., 6.], + [4., 4., 4., 5., 6., 6.]]]] + + Code Examples: + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn.functional as F + + # example 1 + x_shape = (1, 1, 3, 4) + x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape) + 1 + tensor_x = paddle.to_tensor(x) + y = paddle.fluid.layers.pad2d(tensor_x, paddings=[1, 2, 2, 1], pad_value=1, mode='constant') + print(y.numpy()) + # [[[[ 1. 1. 1. 1. 1. 1. 1.] + # [ 1. 1. 1. 2. 3. 4. 1.] + # [ 1. 1. 5. 6. 7. 8. 1.] + # [ 1. 1. 9. 10. 11. 12. 1.] + # [ 1. 1. 1. 1. 1. 1. 1.] + # [ 1. 1. 1. 1. 1. 1. 1.]]]] + + # example 2 + x_shape = (1, 1, 2, 3) + x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape) + 1 + tensor_x = paddle.to_tensor(x) + y = paddle.fluid.layers.pad2d(tensor_x, paddings=[1, 1, 1, 1], mode='reflect') + print(y.numpy()) + # [[[[5. 4. 5. 6. 5.] + # [2. 1. 2. 3. 2.] + # [5. 4. 5. 6. 5.] + # [2. 1. 2. 3. 2.]]]] + """ + if _non_static_mode(): + _paddings = ( + paddings.numpy().tolist() + if isinstance(paddings, Variable) + else paddings + ) + return _legacy_C_ops.pad2d( + input, + 'mode', + mode, + 'pad_value', + pad_value, + 'data_format', + data_format, + 'paddings', + _paddings, + ) + + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64', 'int32', 'int64'], + "pad2d", + ) + + attrs = {'mode': mode, 'pad_value': pad_value, 'data_format': data_format} + inputs = {'X': [input]} + if isinstance(paddings, Variable): + inputs['Paddings'] = [paddings] + attrs['paddings'] = [] + else: + attrs['paddings'] = paddings + + helper = LayerHelper('pad2d', **locals()) + + assert mode in [ + 'reflect', + 'edge', + 'constant', + ], "mode should be one of constant, reflect, edge." + + dtype = helper.input_dtype(input_param_name='input') + out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type='pad2d', inputs=inputs, outputs={"Out": out}, attrs=attrs + ) + + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.elu") +def elu(x, alpha=1.0, name=None): + """ + :alias_main: paddle.nn.functional.elu + :alias: paddle.nn.functional.elu,paddle.nn.functional.activation.elu + :old_api: paddle.fluid.layers.elu + + ${comment} + Args: + x(${x_type}): ${x_comment} + alpha(${alpha_type}|1.0): ${alpha_comment} + name(str|None): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + Returns: + ${out_type}: ${out_comment} + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + input_elu = np.array([[-1,6],[1,15.6]]) + with fluid.dygraph.guard(): + x = fluid.dygraph.to_variable(input_elu) + y = fluid.layers.elu(x, alpha=0.2) + print(y.numpy()) + # [[-0.12642411 6. ] + # [ 1. 15.6 ]] + """ + helper = LayerHelper('elu', **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'elu') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='elu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'alpha': alpha}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.relu6") +def relu6(x, threshold=6.0, name=None): + """ + + ${comment} + + Args: + x(${x_type}): ${x_comment} + threshold(float, optional): ${threshold_comment} + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + output(${out_type}): ${out_comment} + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + in1 = np.array([[-1,0],[2.5,7.8]]) + with fluid.dygraph.guard(): + x1 = fluid.dygraph.to_variable(in1) + out1 = fluid.layers.relu6(x=x1, threshold=6.0) + print(out1.numpy()) + # [[0. 0. ] + # [2.5 6. ]] + """ + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu6') + + helper = LayerHelper('relu6', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='relu6', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'threshold': threshold, + 'use_mkldnn': _global_flags()["FLAGS_use_mkldnn"], + }, + ) + return out + + +@templatedoc() +def pow(x, factor=1.0, name=None): + """ + This is Pow Activation Operator. + + :math:`out = x^{factor}` + + Args: + x(Variable): A ``Tensor`` or ``LoDTensor`` . The data type is ``float32`` or ``float64``. + factor(float32|Variable, optional): A scalar with type ``float32`` or a ``Tensor`` with shape [1] and type ``float32``. The exponential factor of Pow. Default 1.0. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: A ``Tensor`` or ``LoDTensor``. The data type is same as ``x``. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data(name="x", shape=[32,32], dtype="float32") + + # example 1: argument factor is float + y_1 = fluid.layers.pow(x, factor=2.0) + # y_1 is x^{2.0} + + # example 2: argument factor is Variable + factor_tensor = fluid.layers.fill_constant([1], "float32", 3.0) + y_2 = fluid.layers.pow(x, factor=factor_tensor) + # y_2 is x^{3.0} + """ + check_variable_and_dtype( + x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], 'pow' + ) + + helper = LayerHelper('pow', **locals()) + inputs = {'X': x} + attrs = {} + if isinstance(factor, Variable): + check_variable_and_dtype(factor, 'factor', ['float32'], 'pow') + factor.stop_gradient = True + inputs['FactorTensor'] = factor + else: + attrs['factor'] = factor + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +@templatedoc() +def stanh(x, scale_a=0.67, scale_b=1.7159, name=None): + """ + stanh activation. + + .. math:: + + out = b * \\frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + scale_a (float, optional): The scale factor a of the input. Default is 0.67. + scale_b (float, optional): The scale factor b of the output. Default is 1.7159. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = paddle.stanh(x, scale_a=0.67, scale_b=1.72) # [1.00616539, 1.49927628, 1.65933108, 1.70390463] + + """ + + if _non_static_mode(): + return _legacy_C_ops.stanh(x, 'scale_a', scale_a, 'scale_b', scale_b) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'stanh') + + helper = LayerHelper('stanh', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='stanh', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'scale_a': scale_a, 'scale_b': scale_b}, + ) + return out + + +@templatedoc() +def hard_sigmoid(x, slope=0.2, offset=0.5, name=None): + """ + ${comment} + Parameters: + x (${x_type}): ${x_comment} + slope (float, optional): ${slope_comment} + offset (float, optional): ${offset_comment} + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` + + Returns: + ${out_type}: ${out_comment} + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + data = fluid.layers.fill_constant(shape=[3, 2], value=0.5, dtype='float32') # [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] + result = fluid.layers.hard_sigmoid(data) # [[0.6, 0.6], [0.6, 0.6], [0.6, 0.6]] + """ + if _non_static_mode(): + return _legacy_C_ops.hard_sigmoid(x, 'slope', slope, 'offset', offset) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hard_sigmoid' + ) + + helper = LayerHelper('hard_sigmoid', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='hard_sigmoid', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'slope': slope, 'offset': offset}, + ) + return out + + +@templatedoc() +def swish(x, beta=1.0, name=None): + r""" + :alias_main: paddle.nn.functional.swish + :alias: paddle.nn.functional.swish,paddle.nn.functional.activation.swish + :old_api: paddle.fluid.layers.swish + + Elementwise swish activation function. See `Searching for Activation Functions `_ for more details. + + Equation: + + .. math:: + out = \\frac{x}{1 + e^{- beta * x}} + + Args: + x(Variable): Tensor or LoDTensor, dtype: float32 or float64, the input of swish activation. + + beta(float): Constant beta of swish operator, default 1.0. + + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + + Variable: Output of the swish activation, Tensor or LoDTensor, with the same dtype and shape with the input x. + + Examples: + + .. code-block:: python + + # declarative mode + import numpy as np + from paddle import fluid + + x = fluid.data(name="x", shape=(-1, 3), dtype="float32") + y = fluid.layers.swish(x, beta=2.0) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + start = fluid.default_startup_program() + main = fluid.default_main_program() + + data = np.random.randn(2, 3).astype("float32") + exe.run(start) + y_np, = exe.run(main, feed={"x": data}, fetch_list=[y]) + + data + # array([[-1.1239197 , 1.3391294 , 0.03921051], + # [ 1.1970421 , 0.02440812, 1.2055548 ]], dtype=float32) + y_np + # array([[-0.2756806 , 1.0610548 , 0.01998957], + # [ 0.9193261 , 0.01235299, 0.9276883 ]], dtype=float32) + + + .. code-block:: python + + # imperative mode + import numpy as np + from paddle import fluid + import paddle.fluid.dygraph as dg + + data = np.random.randn(2, 3).astype("float32") + place = fluid.CPUPlace() + with dg.guard(place) as g: + x = dg.to_variable(data) + y = fluid.layers.swish(x) + y_np = y.numpy() + data + # array([[-0.0816701 , 1.1603649 , -0.88325626], + # [ 0.7522361 , 1.0978601 , 0.12987892]], dtype=float32) + y_np + # array([[-0.03916847, 0.8835007 , -0.25835553], + # [ 0.51126915, 0.82324016, 0.06915068]], dtype=float32) + """ + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'swish') + + helper = LayerHelper('swish', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='swish', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'slope': beta}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.static.nn.prelu") +def prelu(x, mode, param_attr=None, data_format="NCHW", name=None): + r""" + + prelu activation. + + .. math:: + prelu(x) = max(0, x) + \alpha * min(0, x) + + There are three modes for the activation: + + .. code-block:: text + + all: All elements share same alpha. + channel: Elements in same channel share same alpha. + element: All elements do not share alpha. Each element has its own alpha. + + Parameters: + x (Tensor): The input Tensor or LoDTensor with data type float32. + mode (str): The mode for weight sharing. + param_attr (ParamAttr|None, optional): The parameter attribute for the learnable + weight (alpha), it can be create by ParamAttr. None by default. + data_format(str, optional): Data format that specifies the layout of input. + It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW". + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, A tensor with the same shape and data type as x. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-1., 2., 3.]) + param = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(0.2)) + out = paddle.static.nn.prelu(x, 'all', param) + # [-0.2, 2., 3.] + + """ + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'prelu') + + helper = LayerHelper('prelu', **locals()) + if mode not in ['all', 'channel', 'element']: + raise ValueError('mode should be one of all, channel, element.') + + alpha_shape = [1] + if mode == 'channel': + + true_data_format = [ + 'NC', + 'NCL', + 'NCHW', + 'NCDHW', + 'NLC', + 'NHWC', + 'NDHWC', + ] + if data_format not in true_data_format: + raise ValueError( + "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', " + "'NLC', 'NHWC', 'NDHWC' but receive {}".format(data_format) + ) + + data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC' + + assert ( + len(x.shape) >= 2 + ), "The size of input shape should be equal or larger than 2 in prelu() when mode is 'channel'" + # NOTE(zhiqiu): The alpha_shape should be [1, channel] + [1] * len(x.shape[2:]). + # To be consistent with Prelu, it is simplified. + # NOTE(zhiqiu): Revert shape to [1, channel, 1, 1] for compatibility with saved model of old version. + # NOTE(GuoxiaWang): support NHWC data format + if data_format == 'NHWC': + alpha_shape = [1, 1, 1, x.shape[-1]] + else: + alpha_shape = [1, x.shape[1], 1, 1] + + elif mode == 'element': + assert ( + len(x.shape) >= 1 + ), "The size of input shape should be equal or larger than 1 in prelu() when mode is 'element'" + alpha_shape = [1] + list(x.shape)[1:] + dtype = helper.input_dtype(input_param_name='x') + alpha = helper.create_parameter( + attr=helper.param_attr, + shape=alpha_shape, + dtype=dtype, + is_bias=False, + default_initializer=Constant(0.25), + ) + if in_dygraph_mode(): + return _C_ops.prelu(x, alpha, data_format, mode) + + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="prelu", + inputs={"X": x, 'Alpha': alpha}, + attrs={"mode": mode, "data_format": data_format}, + outputs={"Out": out}, + ) + return out + + +@templatedoc() +def brelu(x, t_min=0.0, t_max=24.0, name=None): + """ + ${comment} + Args: + x(${x_type}): ${x_comment} + t_min(${t_min_type}|0.0): ${t_min_comment} + t_max(${t_max_type}|24.0): ${t_max_comment} + name(str|None): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + Returns: + ${out_type}: ${out_comment} + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + import numpy as np + paddle.enable_static() + + input_brelu = np.array([[-1,6],[1,15.6]]) + with fluid.dygraph.guard(): + x = fluid.dygraph.to_variable(input_brelu) + y = fluid.layers.brelu(x, t_min=1.0, t_max=10.0) + print(y.numpy()) + #[[ 1. 6.] + #[ 1. 10.]] + """ + if _non_static_mode(): + return _legacy_C_ops.brelu(x, 't_min', t_min, 't_max', t_max) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'brelu') + + helper = LayerHelper('brelu', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='brelu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'t_min': t_min, 't_max': t_max}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.leaky_relu") +@templatedoc() +def leaky_relu(x, alpha=0.02, name=None): + """ + ${comment} + Args: + x(${x_type}): ${x_comment} + alpha(${alpha_type}|0.02): ${alpha_comment} + name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + output(${out_type}): ${out_comment} + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1, 2], [3, -4]], dtype='float32') + y = paddle.fluid.layers.leaky_relu(x, alpha=0.1) + print(y) # [[-0.1, 2], [3, -0.4]] + + """ + return paddle.nn.functional.leaky_relu(x, alpha, name) + + +def soft_relu(x, threshold=40.0, name=None): + r""" + + SoftRelu Activation Operator. + + $out = \ln(1 + \exp(\max(\min(x, threshold), -threshold)))$ + + Args: + x(Variable): Input of soft_relu operator. Data type can be float32, float64. + threshold(float, optional): The threshold value of soft_relu, default value being 40.0. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable(Tensor|LoDTensor)): Output of soft_relu operator, shape and LoD same as input. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import numpy as np + import paddle + + paddle.enable_static() + inputs = fluid.layers.data(name="x", shape=[2, 2], dtype="float32") + output = fluid.layers.soft_relu(inputs, threshold=20.0) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + img = np.array([[0, 1],[2, 3]]).astype(np.float32) + + res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) + print(res) # [array([[0.6931472, 1.3132616], [2.126928 , 3.0485873]], dtype=float32)] + """ + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'soft_relu' + ) + + helper = LayerHelper('soft_relu', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='soft_relu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold}, + ) + return out + + +def flatten(x, axis=1, name=None): + r""" + **Flatten op** + + Flatten the input tensor into a 2D matrix. + + For Example: + + .. code-block:: text + + Case 1: + + Given + X.shape = (3, 100, 100, 4) + + and + axis = 2 + + We get: + Out.shape = (3 * 100, 4 * 100) + + Case 2: + + Given + X.shape = (3, 100, 100, 4) + + and + axis = 0 + + We get: + Out.shape = (1, 3 * 100 * 100 * 4) + + Args: + x (Variable): A tensor of rank >= axis. A tensor with type float32, + float64, int8, int32, int64, uint8. + axis (int): Indicate up to which input dimensions (exclusive) should + be flattened to the outer dimension of the output. + The value for axis must be in the range [0, R], where R + is the rank of the input tensor. Default: 1. + name(str, Optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + + Returns: + Variable: A 2D tensor with the contents of the input tensor, with input \ + dimensions up to axis flattened to the outer dimension of \ + the output and remaining input dimensions flattened into the \ + inner dimension of the output. A Tensor with type same as input x. + + Raises: + ValueError: If x is not a variable. + ValueError: If axis is not in range [0, rank(x)]. + + Examples: + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + x = fluid.data(name="x", shape=[4, 4, 3], dtype="float32") + # x shape is [4, 4, 3] + out = fluid.layers.flatten(x=x, axis=2) + # out shape is [16, 3] + """ + check_variable_and_dtype( + x, + 'x', + ['float32', 'float64', 'int8', 'int32', 'int64', 'uint8'], + 'flatten', + ) + if _non_static_mode(): + return _legacy_C_ops.flatten2(x, 'axis', axis)[0] + + helper = LayerHelper('flatten', **locals()) + + if not (isinstance(x, Variable)): + raise ValueError("The input x should be a Variable") + + if not (isinstance(axis, int)) or axis > len(x.shape) or axis < 0: + raise ValueError("The axis should be a int, and in range [0, rank(x)]") + + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='flatten2', + inputs={"X": x}, + outputs={'Out': out, 'XShape': x_shape}, + attrs={"axis": axis}, + ) + return out + + +def stack(x, axis=0, name=None): + """ + + This OP stacks all the inputs :code:`x` along axis. + + .. code-block:: text + + Case 1: + + Input: + x[0].shape = [1, 2] + x[0].data = [ [1.0 , 2.0 ] ] + x[1].shape = [1, 2] + x[1].data = [ [3.0 , 4.0 ] ] + x[2].shape = [1, 2] + x[2].data = [ [5.0 , 6.0 ] ] + + Attrs: + axis = 0 + + Output: + Out.dims = [3, 1, 2] + Out.data =[ [ [1.0, 2.0] ], + [ [3.0, 4.0] ], + [ [5.0, 6.0] ] ] + + + Case 2: + + + Input: + x[0].shape = [1, 2] + x[0].data = [ [1.0 , 2.0 ] ] + x[1].shape = [1, 2] + x[1].data = [ [3.0 , 4.0 ] ] + x[2].shape = [1, 2] + x[2].data = [ [5.0 , 6.0 ] ] + + + Attrs: + axis = 1 or axis = -2 + + Output: + Out.shape = [1, 3, 2] + Out.data =[ [ [1.0, 2.0] + [3.0, 4.0] + [5.0, 6.0] ] ] + + + Args: + x (list(Variable)|tuple(Variable)): Input :code:`x` can be a :code:`list` or :code:`tuple` of Tensors, the shapes of all these Tensors + must be the same. Supposing input is N dims + Tensors :math:`[d_0, d_1, ..., d_{n-1}]`, the output is N+1 dims + Tensor :math:`[d_0, d_1, d_{axis-1}, len(x), d_{axis}, ..., d_{n-1}]`. + Supported data types: float32, float64, int32, int64. + axis (int, optional): The axis along which all inputs are stacked. ``axis`` range is ``[-(R+1), R+1)``, + where ``R`` is the number of dimensions of the first input tensor ``x[0]``. + If ``axis < 0``, ``axis = axis+R+1``. The default value of axis is 0. + name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. + + + Returns: + Variable: The stacked Tensor, has same data type with input Tensors. Output dim is :math:`rank(x[0])+1`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + # set batch size=None + x1 = fluid.data(name='x1', shape=[None, 1, 2], dtype='int32') + x2 = fluid.data(name='x2', shape=[None, 1, 2], dtype='int32') + # stack Tensor list + data = layers.stack([x1,x2]) # stack according to axis 0, data.shape=[2, None, 1, 2] + + data = layers.stack([x1,x2], axis=1) # stack according to axis 1, data.shape=[None, 2, 1, 2] + + + """ + axis = 0 if axis is None else axis + + if in_dygraph_mode(): + return _C_ops.stack(x, axis) + + if _in_legacy_dygraph(): + return _legacy_C_ops.stack(x, 'axis', axis) + + if not isinstance(x, list) and not isinstance(x, tuple): + # NOTE:(zhiqiu) Only support Variable as input if the Variable is a LOD_TENSOR_ARRAY create by create_array, array_write, array_read, etc. + # In that case, Variable is array of tensors indeed. + if ( + isinstance(x, Variable) + and x.desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + x = [x] + else: + raise TypeError( + "The type of '%s' in %s must be %s, but received %s" + % ( + 'x', + 'stack', + 'list[Tensor], tuple[Tensor] or TensorArray', + type(x), + ) + ) + + helper = LayerHelper('stack', **locals()) + + out = helper.create_variable_for_type_inference(x[0].dtype) + if x[0].desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + assert len(x) == 1, ( + "If the elements of 'x' in stack are Variable(LoDTensorArray), " + "number of the elements must be 1, but received %s." % len(x) + ) + out_index = helper.create_variable_for_type_inference(dtype="int32") + + for i in x: + check_variable_and_dtype( + i, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'stack', + ) + + helper.append_op( + type='tensor_array_to_tensor', + inputs={'X': x[0]}, + outputs={'Out': [out], 'OutIndex': [out_index]}, + attrs={'axis': axis, 'use_stack': True}, + ) + else: + helper.append_op( + type='stack', + inputs={'X': x}, + outputs={'Y': out}, + attrs={'axis': axis}, + ) + + return out + + +@templatedoc(op_type="filter_by_instag") +def filter_by_instag(ins, ins_tag, filter_tag, is_lod, out_val_if_empty=0): + """ + **Filter By Instag Layer** + + This function filter a batch of ins by instag, + There are multiple ins, and every ins belongs to some tags. + We can specify some tags we want. So the ins which belongs to that tags + remains in the output, and others removed. + + For example, one batch has 4 ins. Every ins has its tag list. + + | Ins | Ins_Tag | + |:-----:|:------:| + | 0 | 0, 1 | + | 1 | 1, 3 | + | 2 | 0, 3 | + | 3 | 2, 6 | + + And Lod is [1,1,1,1] + + And the filter tags [1] + + From the definition above, ins which has tag 1 can pass the filter + So Ins 0 and Ins 1 can pass and be seen in the output, + Ins 2 and 3 cannot pass because they do not has tag 1. + + Actually, if is_lod is false, it is normal tensor that equals to + lod_tensor with all 1, similar to the example above. + + Args: + ins (Variable): Input Variable (LoDTensor), usually it is 2D tensor + And first dimension can have lod info or not. + ins_tag (Variable): Input Variable (LoDTensor), usually it is 1D list + And split them by lod info + filter_tag (Variable): Input Variable (1D Tensor/List), usually it is + list that holds the tags. + is_lod (Bool): Boolean value to indicate ins is lod tensor or not. + out_val_if_empty(Int64): If the output after filter is empty, this value + will be set to Output tensor. + + Returns: + Variable: filtered ins (LoDTensor) and loss weight (Tensor) + + Examples: + .. code-block:: python + + import paddle.fluid.layers as layers + ins = layers.data(name='Ins', shape=[-1,32], lod_level=0, dtype='float64') + ins_tag = layers.data(name='Ins_tag', shape=[-1,16], lod_level=0, dtype='int64') + filter_tag = layers.data(name='Filter_tag', shape=[-1,16], dtype='int64') + out, loss_weight = layers.filter_by_instag(ins, ins_tag, filter_tag, True) + + """ + helper = LayerHelper('filter_by_instag', **locals()) + + out = helper.create_variable_for_type_inference(dtype=ins.dtype) + loss_weight = helper.create_variable_for_type_inference(dtype=np.float64) + mmap = helper.create_variable_for_type_inference(dtype=ins_tag.dtype) + helper.append_op( + type='filter_by_instag', + inputs={'Ins': ins, 'Ins_tag': ins_tag, 'Filter_tag': filter_tag}, + outputs={'Out': out, 'LossWeight': loss_weight, 'IndexMap': mmap}, + attrs={'is_lod': is_lod, 'out_val_if_empty': out_val_if_empty}, + ) + + return [out, loss_weight] + + +def unstack(x, axis=0, num=None): + """ + :alias_main: paddle.unstack + :alias: paddle.unstack,paddle.tensor.unstack,paddle.tensor.manipulation.unstack + :old_api: paddle.fluid.layers.unstack + + **UnStack Layer** + + This layer unstacks input Tensor :code:`x` into several Tensors along :code:`axis`. + + If :code:`axis` < 0, it would be replaced with :code:`axis+rank(x)`. + If :code:`num` is None, it would be inferred from :code:`x.shape[axis]`, + and if :code:`x.shape[axis]` <= 0 or is unknown, :code:`ValueError` is + raised. + + Args: + x (Tensor): Input Tensor. It is a N-D Tensors of data types float32, float64, int32, int64. + axis (int): The axis along which the input is unstacked. + num (int|None): The number of output variables. + + Returns: + list(Tensor): The unstacked Tensors list. The list elements are N-D Tensors of data types float32, float64, int32, int64. + + Raises: + ValueError: If x.shape[axis] <= 0 or axis is not in range [-D, D). + + Examples: + .. code-block:: python + + import paddle + x = paddle.ones(name='x', shape=[2, 3, 5], dtype='float32') # create a tensor with shape=[2, 3, 5] + y = paddle.unstack(x, axis=1) # unstack with second axis, which results 3 tensors with shape=[2, 5] + + """ + + if _non_static_mode(): + if num == None: + num = x.shape[axis] + if num == 0: + return [] + return _legacy_C_ops.unstack(x, num, 'axis', int(axis), 'num', num) + + helper = LayerHelper('unstack', **locals()) + if num is None: + if axis is None or x.shape[axis] <= 0: + raise ValueError('unknown unstack number') + else: + num = x.shape[axis] + + outs = [] + for _ in range(num): + outs.append(helper.create_variable_for_type_inference(x.dtype)) + + helper.append_op( + type='unstack', + inputs={'X': [x]}, + outputs={'Y': outs}, + attrs={'axis': axis, 'num': num}, + ) + return outs + + +@deprecated(since='2.0.0', update_to="paddle.expand") +def expand(x, expand_times, name=None): + """ + :alias_main: paddle.expand + :alias: paddle.expand,paddle.tensor.expand,paddle.tensor.manipulation.expand + :old_api: paddle.fluid.layers.expand + + This operation tiles ``x`` multiple times according to the parameter ``expand_times``. + The times number for each dimension of ``x`` is set by the parameter ``expand_times``. + The rank of ``x`` should be less than or equal to 6. Please note that size of ``expand_times`` must be the same + with X's rank. Following is a using case: + + + .. code-block:: text + + Input(X) is a 3-D tensor with shape [2, 3, 1]: + + [ + [[1], [2], [3]], + [[4], [5], [6]] + ] + + Attr(expand_times): [1, 2, 2] + + Output(Out) is a 3-D tensor with shape [2, 6, 2]: + + [ + [[1, 1], [2, 2], [3, 3], [1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6], [4, 4], [5, 5], [6, 6]] + ] + + Args: + x (Variable): A ``Tensor`` or ``LoDTensor`` with dimension in [1, 6]. The data type is ``bool``, ``float32``, ``float64`` or ``int32`` . + expand_times (list|tuple|Variable): The data type is ``int32`` . If ``expand_times`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``expand_times`` is an Variable, it should be an 1-D Tensor. + Expand times number for each dimension of ``x`` . + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: A ``Tensor`` or ``LoDTensor``. The data type is same as ``x``. After expanding, size of each dimension of output is equal to the size of the corresponding dimension of ``x`` multiplying the corresponding value given by ``expand_times`` . + + Raises: + TypeError: The type of ``expand_times`` must be list, tuple or Variable. + ValueError: The elements of ``expand_times`` cannot be negative. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + # example 1: + data_1 = fluid.layers.fill_constant(shape=[2, 3, 1], dtype='int32', value=0) + expanded_1 = fluid.layers.expand(data_1, expand_times=[1, 2, 2]) + # the shape of expanded_1 is [2, 6, 2]. + + # example 2: + data_2 = fluid.layers.fill_constant(shape=[12, 14], dtype="int32", value=3) + expand_times = fluid.layers.fill_constant(shape=[2], dtype="int32", value=4) + expanded_2 = fluid.layers.expand(data_2, expand_times=expand_times) + # the shape of expanded_2 is [48, 56]. + """ + if _non_static_mode(): + attrs = () + expand_times_tensor = None + if isinstance(expand_times, (list, tuple)): + expand_times = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in expand_times + ] + attrs += ('expand_times', expand_times) + elif isinstance(expand_times, Variable): + expand_times_tensor = expand_times + expand_times_tensor.stop_gradient = True + + return _legacy_C_ops.expand(x, expand_times_tensor, *attrs) + + inputs = {"X": [x]} + attrs = {} + check_variable_and_dtype( + x, + 'x', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'expand', + ) + check_type(expand_times, 'expand_times', (list, tuple, Variable), 'expand') + if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == True: + raise ValueError( + "expand op bool date type must set the stop_gradient to be False" + ) + + helper = LayerHelper('expand', input=x, **locals()) + + def get_attr_expand_times(list_expand_times): + attrs_expand_times = [] + for idx, times in enumerate(list_expand_times): + if isinstance(times, Variable): + attrs_expand_times.append(-1) + else: + attrs_expand_times.append(times) + assert ( + times > 0 + ), "Each element given in expand_times must not be negative." + return attrs_expand_times + + if isinstance(expand_times, Variable): + expand_times.stop_gradient = True + inputs['ExpandTimes'] = expand_times + elif isinstance(expand_times, (list, tuple)): + attrs['expand_times'] = get_attr_expand_times(expand_times) + if utils._contain_var(expand_times): + inputs['expand_times_tensor'] = utils._convert_to_tensor_list( + expand_times + ) + + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='expand', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +@deprecated(since='2.0.0', update_to="paddle.expand_as") +def expand_as(x, target_tensor, name=None): + """ + :alias_main: paddle.expand_as + :alias: paddle.expand_as,paddle.tensor.expand_as,paddle.tensor.manipulation.expand_as + :old_api: paddle.fluid.layers.expand_as + + expand_as operator tiles to the input by given expand tensor. You should set expand tensor + for each dimension by providing tensor 'target_tensor'. The rank of X + should be in [1, 6]. Please note that size of 'target_tensor' must be the same + with X's rank. Following is a using case: + + + .. code-block:: text + + Input(X) is a 3-D tensor with shape [2, 3, 1]: + + [ + [[1], [2], [3]], + [[4], [5], [6]] + ] + + target_tensor's shape: [2, 6, 2] + + Output(Out) is a 3-D tensor with shape [2, 6, 2]: + + [ + [[1, 1], [2, 2], [3, 3], [1, 1], [2, 2], [3, 3]], + [[4, 4], [5, 5], [6, 6], [4, 4], [5, 5], [6, 6]] + ] + + + Args: + x (Variable): A Tensor with dtype float64, float32, int32. + A tensor with rank in [1, 6]. + target_tensor (Variable): A Tensor with dtype float64, float32, int32. + target_tensor for expanding to Input(X). Only use target_tensor'shape. + + Returns: + Variable: A Tensor with dtype float64, float32, int32. + After expanding, size of each dimension of Output(Out) is equal to the size + of the corresponding dimension of target_tensor multiplying the corresponding + value given by target_tensor. + + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + paddle.enable_static() + + data = fluid.layers.data(name="data", shape=[-1,10], dtype='float64') + target_tensor = fluid.layers.data( + name="target_tensor", shape=[-1,20], dtype='float64') + result = fluid.layers.expand_as(x=data, target_tensor=target_tensor) + use_cuda = False + place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + x = np.random.rand(3,10) + y = np.random.rand(3,20) + output= exe.run(feed={"data":x,"target_tensor":y},fetch_list=[result.name]) + print(output[0].shape) + #(3,20) + + """ + if _non_static_mode(): + return _legacy_C_ops.expand_as(x, target_tensor) + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64', 'bool'], 'expand_as' + ) + check_variable_and_dtype( + target_tensor, + 'target_tensor', + ['float32', 'float64', 'int32', 'int64', 'bool'], + 'expand_as', + ) + helper = LayerHelper('expand_as', input=x, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + inputs = {'X': x, 'target_tensor': target_tensor} + helper.append_op(type='expand_as', inputs=inputs, outputs={'Out': out}) + return out + + +from paddle.fluid.framework import convert_np_dtype_to_dtype_ + + +@deprecated(since='1.8.0', update_to="paddle.uniform") +@templatedoc() +def uniform_random_batch_size_like( + input, + shape, + dtype='float32', + input_dim_idx=0, + output_dim_idx=0, + min=-1.0, + max=1.0, + seed=0, +): + """ + This OP initializes a variable with random values sampled from a + uniform distribution in the range [min, max). The input_dim_idx used to get the input dimension value which will be used to resize the output dimension. + + .. code-block:: text + + *Case 1: + + Given: + input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3] + shape=[2,4] + + result.shape[output_dim_idx] = input.shape[input_dim_idx], + output_dim_idx = 0, + input_dim_idx = 0, + result.shape[0] = input.shape[0], + then: + result=[[ 0.3443427 , -0.23056602, 0.3477049 , 0.06139076]] # result.shape=[1,4] + + *Case 2: + + Given: + input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3] + shape=[2,4] + input_dim_idx=1 + output_dim_idx=1 + + result.shape[output_dim_idx] = input.shape[input_dim_idx], + output_dim_idx = 1, + input_dim_idx = 1, + result.shape[1] = input.shape[1], + then: + result=[[-0.23133647, -0.84195036, 0.21441269], + [-0.08774924, 0.25605237, -0.09403259]] # result.shape=[2,3] + Args: + input (Variable): A Tensor. Supported data types: float32, float64. + shape (tuple|list): A python list or python tuple. The shape of the output Tensor, the data type is int. + input_dim_idx (int, optional): An index used to get the input dimension value which will be used to resize the output dimension. Default 0. + output_dim_idx (int, optional): An index used to indicate the specific dimension that will be replaced by corresponding input dimension value. Default 0. + min (float, optional): The lower bound on the range of random values to generate, the min is included in the range. Default -1.0. + max (float, optional): The upper bound on the range of random values to generate, the max is excluded in the range. Default 1.0. + seed (int, optional): Random seed used for generating samples. 0 means use a seed generated by the system.Note that if seed is not 0, this operator will always generate the same random numbers every time. + dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type of output Tensor. Supported data types: float32, float64. Default float32. + Returns: + Variable: A Tensor of the specified shape filled with uniform_random values. The shape of the Tensor is determined by the shape parameter and the specified dimension of the input Tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # example 1: + input = fluid.data(name="input", shape=[1, 3], dtype='float32') + out_1 = fluid.layers.uniform_random_batch_size_like(input, [2, 4]) # out_1.shape=[1, 4] + + # example 2: + out_2 = fluid.layers.uniform_random_batch_size_like(input, [2, 4], input_dim_idx=1, output_dim_idx=1) # out_2.shape=[2, 3] + + + """ + check_variable_and_dtype( + input, + 'Input', + ("float32", 'float64', "uint16"), + 'uniform_random_batch_size_like', + ) + check_type(shape, 'shape', (list, tuple), 'uniform_random_batch_size_like') + check_dtype( + dtype, + 'dtype', + ('float32', 'float64', "uint16"), + 'uniform_random_batch_size_like', + ) + + helper = LayerHelper('uniform_random_batch_size_like', **locals()) + out = helper.create_variable_for_type_inference(dtype) + c_dtype = convert_np_dtype_to_dtype_(dtype) + helper.append_op( + type='uniform_random_batch_size_like', + inputs={'Input': input}, + outputs={'Out': out}, + attrs={ + 'shape': shape, + 'input_dim_idx': input_dim_idx, + 'output_dim_idx': output_dim_idx, + 'min': min, + 'max': max, + 'seed': seed, + 'dtype': c_dtype, + }, + ) + + return out + + +@deprecated(since="2.0.0", update_to="paddle.normal") +@templatedoc() +def gaussian_random( + shape, mean=0.0, std=1.0, seed=0, dtype='float32', name=None +): + """ + This OP returns a Tensor filled with random values sampled from a Gaussian + distribution, with ``shape`` and ``dtype``. + + Args: + shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + mean(float|int, optional): Mean of the output tensor, default is 0.0. + std(float|int, optional): Standard deviation of the output tensor, default + is 1.0. + seed(int, optional): ${seed_comment} + dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of + the output Tensor. Supported data types: float32, float64. + Default is float32. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a Gaussian + distribution, with ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # example 1: + # attr shape is a list which doesn't contain Tensor. + result_1 = fluid.layers.gaussian_random(shape=[3, 4]) + # [[-0.31261674, 1.8736548, -0.6274357, 0.96988016], + # [-0.12294637, 0.9554768, 1.5690808, -1.2894802 ], + # [-0.60082096, -0.61138713, 1.5345167, -0.21834975]] + + # example 2: + # attr shape is a list which contains Tensor. + dim_1 = fluid.layers.fill_constant([1], "int64", 2) + dim_2 = fluid.layers.fill_constant([1], "int32", 3) + result_2 = fluid.layers.gaussian_random(shape=[dim_1, dim_2]) + # [[ 0.51398206, -0.3389769, 0.23597084], + # [ 1.0388143, -1.2015356, -1.0499583 ]] + + # example 3: + # attr shape is a Tensor, the data type must be int64 or int32. + var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") + result_3 = fluid.layers.gaussian_random(var_shape) + # if var_shape's value is [2, 3] + # result_3 is: + # [[-0.12310527, 0.8187662, 1.923219 ] + # [ 0.70721835, 0.5210541, -0.03214082]] + + .. code-block:: python + + # declarative mode + # required: skiptest + import numpy as np + from paddle import fluid + + x = fluid.layers.gaussian_random((2, 3), std=2., seed=10) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + start = fluid.default_startup_program() + main = fluid.default_main_program() + + exe.run(start) + x_np, = exe.run(main, feed={}, fetch_list=[x]) + + x_np + # array([[2.3060477, 2.676496 , 3.9911983], + # [0.9990833, 2.8675377, 2.2279181]], dtype=float32) + + .. code-block:: python + + # imperative mode + import numpy as np + from paddle import fluid + import paddle.fluid.dygraph as dg + + place = fluid.CPUPlace() + with dg.guard(place) as g: + x = fluid.layers.gaussian_random((2, 4), mean=2., dtype="float32", seed=10) + x_np = x.numpy() + x_np + # array([[2.3060477 , 2.676496 , 3.9911983 , 0.9990833 ], + # [2.8675377 , 2.2279181 , 0.79029655, 2.8447366 ]], dtype=float32) + """ + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + place = _current_expected_place() + return _C_ops.gaussian_random( + shape, float(mean), float(std), seed, dtype, place + ) + + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + return _legacy_C_ops.gaussian_random( + 'shape', + shape, + 'mean', + float(mean), + 'std', + float(std), + 'seed', + seed, + 'dtype', + dtype, + ) + + check_type(shape, 'shape', (list, tuple, Variable), 'gaussian_random/randn') + check_dtype(dtype, 'dtype', ['float32', 'float64'], 'gaussian_random/randn') + + inputs = {} + attrs = { + 'mean': mean, + 'std': std, + 'seed': seed, + 'dtype': dtype, + 'use_mkldnn': False, + } + utils.get_shape_tensor_inputs( + inputs=inputs, attrs=attrs, shape=shape, op_type='gaussian_random/randn' + ) + + helper = LayerHelper('gaussian_random', **locals()) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='gaussian_random', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + + return out + + +@templatedoc() +def sampling_id(x, min=0.0, max=1.0, seed=0, dtype='float32'): + """ + This op is used for sampling id from multinomial distribution from the input, sampling one id for one sample. + + Parameters: + x (Variable): 2-D tensor, [batch_size, input_feature_dimensions] + min (Float): minimum , default 0.0. + max (Float): maximum, default 1.0. + seed (Float): Random seed, default 0. if seed is not 0, will generate same number every time. + dtype(np.dtype|core.VarDesc.VarType|str): The type of output data : float32, float_16, int etc + + Returns: + Variable: sampling tensor. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data( + name="X", + shape=[13, 11], + dtype='float32') + + out = fluid.layers.sampling_id(x) + """ + + helper = LayerHelper('sampling_id', **locals()) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='sampling_id', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'min': min, 'max': max, 'seed': seed}, + ) + + return out + + +@deprecated(since='1.8.0', update_to="paddle.normal") +@templatedoc() +def gaussian_random_batch_size_like( + input, + shape, + input_dim_idx=0, + output_dim_idx=0, + mean=0.0, + std=1.0, + seed=0, + dtype='float32', +): + """ + ${comment} + + Args: + input (Variable): ${input_comment} + shape (tuple|list): ${shape_comment} + input_dim_idx (int): ${input_dim_idx_comment} + output_dim_idx (int): ${output_dim_idx_comment} + mean (float): ${mean_comment} + std (float): ${std_comment} + seed (int): ${seed_comment} + dtype(np.dtype|core.VarDesc.VarType|str): The type of output data, float32 or float_64. + + Returns: + out (Variable): ${out_comment} + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + input = fluid.data(name="input", shape=[13, 11], dtype='float32') + + out = fluid.layers.gaussian_random_batch_size_like( + input, shape=[-1, 11], mean=1.0, std=2.0) + """ + + helper = LayerHelper('gaussian_random_batch_size_like', **locals()) + check_type( + input, + 'input', + (Variable), + 'fluid.layers.gaussian_random_batch_size_like', + ) + check_type( + shape, + 'shape', + (list, tuple), + 'fluid.layers.gaussian_random_batch_size_like', + ) + check_dtype( + dtype, + 'dtype', + ['float16', 'float32', 'int'], + 'fluid.layers.gaussian_random_batch_size_like', + ) + out = helper.create_variable_for_type_inference(dtype) + c_dtype = convert_np_dtype_to_dtype_(dtype) + helper.append_op( + type='gaussian_random_batch_size_like', + inputs={'Input': input}, + outputs={'Out': out}, + attrs={ + 'shape': shape, + 'input_dim_idx': input_dim_idx, + 'output_dim_idx': output_dim_idx, + 'mean': mean, + 'std': std, + 'seed': seed, + 'dtype': c_dtype, + }, + ) + + return out + + +@templatedoc() +def sum(x): + """ + ${comment} + + Case 1: + :: + Input: + Input. Shape = [2, 3] + Input = [[1, 2, 3], + [4, 5, 6]] + + Output: + The output. Shape = [2, 3] + Output = [[1, 2, 3], + [4, 5, 6]] + + Case 2: + :: + Input: + First input: + Input1. Shape = [2, 3] + Input1 = [[1, 2, 3], + [4, 5, 6]] + + The second input: + Input2. Shape = [2, 3] + Input2 = [[7, 8, 9], + [10, 11, 12]] + + Output: + The output. Shape = [2, 3] + Output = [[8, 10, 12], + [14, 16, 18]] + + Args: + x (Variable|list(Variable)): ${x_comment} + + Returns: + Variable: ${out_comment} + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + input0 = fluid.layers.fill_constant(shape=[2, 3], dtype='int64', value=5) + input1 = fluid.layers.fill_constant(shape=[2, 3], dtype='int64', value=3) + sum = fluid.layers.sum([input0, input1]) + + # You can print out 'sum' via executor. + out = fluid.layers.Print(sum, message="the sum of input0 and input1: ") + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_main_program()) + + # The printed result is: + # 1570701754 the sum of input0 and input1: The place is:CPUPlace + # Tensor[sum_0.tmp_0] + # shape: [2,3,] + # dtype: l + # data: 8,8,8,8,8,8, + + # the sum of input0 and input1 is 2-D Tensor with shape [2,3]. + # dtype is the corresponding C++ data type, which may vary in different environments. + # Eg: if the data type of tensor is int64, then the corresponding C++ data type is int64_t, + # so the dtype value is typeid(int64_t).Name(), which is 'x' on MacOS, 'l' on Linux, + # and '__int64' on Windows. They both represent 64-bit integer variables. + """ + + return paddle.add_n(x) + + +@templatedoc() +def slice(input, axes, starts, ends): + """ + This operator produces a slice of ``input`` along multiple axes. Similar to numpy: + https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html + Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and + end dimension for each axis in the list of axes and Slice uses this information + to slice the input data tensor. If a negative value is passed to + ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the + axis :math:`i-1` (here 0 is the initial position). + If the value passed to ``starts`` or ``ends`` is greater than n + (the number of elements in this dimension), it represents n. + For slicing to the end of a dimension with unknown size, it is recommended + to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` and ``ends``. + Following examples will explain how slice works: + + .. code-block:: text + + Case1: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [1, 0] + ends = [2, 3] + Then: + result = [ [5, 6, 7], ] + + Case2: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [-1, 1000] # -1 denotes the reverse 0th position of dimension 0. + Then: + result = [ [2, 3, 4], ] # result = data[0:1, 1:4] + + Args: + input (Tensor): A ``Tensor`` . The data type is ``float16``, ``float32``, ``float64``, ``int32`` or ``int64``. + axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to . + starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``starts`` is an Tensor, it should be an 1-D Tensor. + It represents starting indices of corresponding axis in ``axes``. + ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``ends`` is an Tensor, it should be an 1-D Tensor . + It represents ending indices of corresponding axis in ``axes``. + + Returns: + Tensor: A ``Tensor``. The data type is same as ``input``. + + Raises: + TypeError: The type of ``starts`` must be list, tuple or Tensor. + TypeError: The type of ``ends`` must be list, tuple or Tensor. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand(shape=[4, 5, 6], dtype='float32') + # example 1: + # attr starts is a list which doesn't contain tensor. + axes = [0, 1, 2] + starts = [-3, 0, 2] + ends = [3, 2, 4] + sliced_1 = paddle.slice(input, axes=axes, starts=starts, ends=ends) + # sliced_1 is input[0:3, 0:2, 2:4]. + + # example 2: + # attr starts is a list which contain tensor. + minus_3 = paddle.full([1], -3, "int32") + sliced_2 = paddle.slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends) + # sliced_2 is input[0:3, 0:2, 2:4]. + """ + if in_dygraph_mode(): + attrs = () + starts_tensor = None + ends_tensor = None + + if isinstance(axes, (list, tuple)): + axes = list(axes) + if len(axes) == 0: + raise ValueError( + "Input axes should not be an empty list/tuple." + ) + for i in range(len(axes)): + if axes[i] < 0: + axes[i] = max(0, axes[i] + len(input.shape)) + else: + axes[i] = min(len(input.shape) - 1, axes[i]) + + else: + raise ValueError( + "Input axes must be a python list or tuple, but reveived {}".format( + type(axes) + ) + ) + + infer_flags = list(1 for i in range(len(axes))) + + tmp_tensor_type = core.eager.Tensor + if isinstance(starts, (list, tuple)): + starts = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in starts + ] + elif isinstance(starts, tmp_tensor_type): + tensor_t = starts.numpy() + starts = [ele for ele in tensor_t] + + if isinstance(ends, (list, tuple)): + ends = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in ends + ] + attrs += ('ends', ends) + elif isinstance(ends, tmp_tensor_type): + tensor_t = ends.numpy() + ends = [ele for ele in tensor_t] + + return _C_ops.slice(input, axes, starts, ends, infer_flags, []) + else: + if _in_legacy_dygraph(): + attrs = () + starts_tensor = None + ends_tensor = None + + if isinstance(axes, (list, tuple)): + axes = list(axes) + if len(axes) == 0: + raise ValueError( + "Input axes should not be an empty list/tuple." + ) + for i in range(len(axes)): + if axes[i] < 0: + axes[i] = max(0, axes[i] + len(input.shape)) + else: + axes[i] = min(len(input.shape) - 1, axes[i]) + + else: + raise ValueError( + "Input axes must be a python list or tuple, but reveived {}".format( + type(axes) + ) + ) + + infer_flags = list(1 for i in range(len(axes))) + + tmp_tensor_type = Variable + + if isinstance(starts, (list, tuple)): + starts = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in starts + ] + attrs += ('starts', starts) + elif isinstance(starts, tmp_tensor_type): + starts_tensor = starts + starts.stop_gradient = True + infer_flags = list(-1 for i in range(len(axes))) + + if isinstance(ends, (list, tuple)): + ends = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in ends + ] + attrs += ('ends', ends) + elif isinstance(ends, tmp_tensor_type): + ends_tensor = ends + ends_tensor.stop_gradient = True + infer_flags = list(-1 for i in range(len(axes))) + + return _legacy_C_ops.slice( + input, + starts_tensor, + ends_tensor, + None, + None, + 'axes', + axes, + 'infer_flags', + infer_flags, + *attrs, + ) + + if not isinstance(starts, (list, tuple, Variable)): + raise ValueError( + "Input starts must be an Variable, python list or tuple." + ) + if not isinstance(ends, (list, tuple, Variable)): + raise ValueError( + "Input ends must be an Variable, python list or tuple." + ) + + helper = LayerHelper('slice', **locals()) + + inputs = {'Input': input} + attrs = {'axes': axes} + infer_flags = list(1 for i in range(len(axes))) + + # starts + if isinstance(starts, Variable): + starts.stop_gradient = True + inputs['StartsTensor'] = starts + infer_flags = list(-1 for i in range(len(axes))) + elif isinstance(starts, (list, tuple)): + attrs['starts'] = [] + if utils._contain_var(starts): + inputs['StartsTensorList'] = utils._convert_to_tensor_list(starts) + for i, dim in enumerate(starts): + if isinstance(dim, Variable): + attrs['starts'].append(-1) + infer_flags[i] = -1 + else: + attrs['starts'].append(dim) + else: + attrs['starts'] = starts + + # ends + if isinstance(ends, Variable): + ends.stop_gradient = True + inputs['EndsTensor'] = ends + infer_flags = list(-1 for i in range(len(axes))) + elif isinstance(ends, (list, tuple)): + attrs['ends'] = [] + if utils._contain_var(ends): + inputs['EndsTensorList'] = utils._convert_to_tensor_list(ends) + for i, dim in enumerate(ends): + if isinstance(dim, Variable): + attrs['ends'].append(-1) + infer_flags[i] = -1 + else: + attrs['ends'].append(dim) + else: + attrs['ends'] = ends + + # infer_flags + attrs['infer_flags'] = infer_flags + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('input') + ) + helper.append_op( + type='slice', inputs=inputs, attrs=attrs, outputs={'Out': out} + ) + + return out + + +@deprecated(since='2.0.0', update_to="paddle.strided_slice") +def strided_slice(input, axes, starts, ends, strides): + """ + :alias_main: paddle.strided_slice + :alias: paddle.strided_slice,paddle.tensor.strided_slice,paddle.tensor.manipulation.strided_slice + :old_api: paddle.fluid.layers.strided_slice + + This operator produces a slice of ``input`` along multiple axes. Similar to numpy: + https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html + Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and + end dimension for each axis in the list of axes and Slice uses this information + to slice the input data tensor. If a negative value is passed to + ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the + axis :math:`i-1` th(here 0 is the initial position). The ``strides`` represents steps of + slicing and if the ``strides`` is negative, slice operation is in the opposite direction. + If the value passed to ``starts`` or ``ends`` is greater than n + (the number of elements in this dimension), it represents n. + For slicing to the end of a dimension with unknown size, it is recommended + to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` , ``ends`` and ``strides``. + Following examples will explain how strided_slice works: + + .. code-block:: text + + Case1: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [1, 0] + ends = [2, 3] + strides = [1, 1] + Then: + result = [ [5, 6, 7], ] + + Case2: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [2, 0] + strides = [1, -1] + Then: + result = [ [8, 7, 6], ] + + Case3: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [-1, 1000] + strides = [1, 3] + Then: + result = [ [2], ] + Args: + input (Variable): An N-D ``Tensor`` or ``LoDTensor`` . The data type is ``bool``, ``float32``, ``float64``, ``int32`` or ``int64``. + axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to. + It's optional. If it is not provides, it will be treated as :math:`[0,1,...,len(starts)-1]`. + starts (list|tuple|Variable): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``starts`` is an Variable, it should be an 1-D Tensor. + It represents starting indices of corresponding axis in ``axes``. + ends (list|tuple|Variable): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``ends`` is an Variable, it should be an 1-D Tensor . + It represents ending indices of corresponding axis in ``axes``. + strides (list|tuple|Variable): The data type is ``int32`` . If ``strides`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``strides`` is an Variable, it should be an 1-D Tensor . + It represents slice step of corresponding axis in ``axes``. + + Returns: + Variable: A ``Tensor`` or ``LoDTensor`` with the same dimension as ``input``. The data type is same as ``input``. + + Raises: + TypeError: The type of ``starts`` must be list, tuple or Variable. + TypeError: The type of ``ends`` must be list, tuple or Variable. + TypeError: The type of ``strides`` must be list, tuple or Variable. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + input = fluid.data( + name="input", shape=[3, 4, 5, 6], dtype='float32') + + # example 1: + # attr starts is a list which doesn't contain tensor Variable. + axes = [0, 1, 2] + starts = [-3, 0, 2] + ends = [3, 2, 4] + strides_1 = [1, 1, 1] + strides_2 = [1, 1, 2] + sliced_1 = fluid.layers.strided_slice(input, axes=axes, starts=starts, ends=ends, strides=strides_1) + # sliced_1 is input[:, 0:3:1, 0:2:1, 2:4:1]. + + + # example 2: + # attr starts is a list which contain tensor Variable. + minus_3 = fluid.layers.fill_constant([1], "int32", -3) + sliced_2 = fluid.layers.strided_slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends, strides=strides_2) + # sliced_2 is input[:, 0:3:1, 0:2:1, 2:4:2]. + """ + if in_dygraph_mode(): + return _C_ops.strided_slice(input, axes, starts, ends, strides) + + helper = LayerHelper('strided_slice', **locals()) + + check_variable_and_dtype( + input, + 'input', + ['bool', 'float32', 'float64', 'int32', 'int64'], + 'strided_slice', + ) + check_type(axes, 'axes', (list, tuple), 'strided_slice') + check_type(starts, 'starts', (list, tuple, Variable), 'strided_slice') + check_type(ends, 'ends', (list, tuple, Variable), 'strided_slice') + check_type(strides, 'strides', (list, tuple, Variable), 'strided_slice') + + def check_list_elements_dtype(list_input, input_name): + if isinstance(list_input, Variable): + check_dtype( + list_input.dtype, input_name, ['int32'], 'strided_slice' + ) + else: + for i, var in enumerate(list_input): + var_name = input_name + '[' + str(i) + ']' + if isinstance(var, Variable): + check_dtype(var.dtype, var_name, ['int32'], 'strided_slice') + + check_list_elements_dtype(axes, 'axes') + check_list_elements_dtype(starts, 'starts') + check_list_elements_dtype(ends, 'ends') + check_list_elements_dtype(strides, 'strides') + + def get_new_list_tensor(old_list): + new_list_tensor = [] + for dim in old_list: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_list_tensor.append(dim) + else: + assert isinstance(dim, int) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) + new_list_tensor.append(temp_out) + return new_list_tensor + + inputs = {'Input': input} + attrs = {'axes': axes} + infer_flags = list(1 for i in range(len(axes))) + + if _non_static_mode(): + inputs = {'Input': input} + attrs = { + 'axes': axes, + 'starts': starts, + 'ends': ends, + 'strides': strides, + 'infer_flags': infer_flags, + } + else: + # starts + if isinstance(starts, Variable): + starts.stop_gradient = True + inputs['StartsTensor'] = starts + elif isinstance(starts, (list, tuple)): + attrs['starts'] = [] + if utils._contain_var(starts): + inputs['StartsTensorList'] = get_new_list_tensor(starts) + for i, dim in enumerate(starts): + if isinstance(dim, Variable): + attrs['starts'].append(-1) + infer_flags[i] = -1 + else: + attrs['starts'].append(dim) + else: + attrs['starts'] = starts + + # ends + if isinstance(ends, Variable): + ends.stop_gradient = True + inputs['EndsTensor'] = ends + elif isinstance(ends, (list, tuple)): + attrs['ends'] = [] + if utils._contain_var(ends): + inputs['EndsTensorList'] = get_new_list_tensor(ends) + for i, dim in enumerate(ends): + if isinstance(dim, Variable): + attrs['ends'].append(-1) + infer_flags[i] = -1 + else: + attrs['ends'].append(dim) + else: + attrs['ends'] = ends + + # strides + if isinstance(strides, Variable): + strides.stop_gradient = True + inputs['StridesTensor'] = strides + elif isinstance(strides, (list, tuple)): + attrs['strides'] = [] + if utils._contain_var(strides): + inputs['StridesTensorList'] = get_new_list_tensor(strides) + for i, dim in enumerate(strides): + if isinstance(dim, Variable): + attrs['strides'].append(-1) + infer_flags[i] = -1 + else: + attrs['strides'].append(dim) + else: + attrs['strides'] = strides + attrs['infer_flags'] = infer_flags + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('input') + ) + helper.append_op( + type='strided_slice', inputs=inputs, attrs=attrs, outputs={'Out': out} + ) + + return out + + +def shape(input): + """ + :alias_main: paddle.shape + :alias: paddle.shape,paddle.tensor.shape,paddle.tensor.attribute.shape + :old_api: paddle.fluid.layers.shape + + **Shape Layer** + + Get the shape of the input. + + .. code-block:: text + + Case1: + Given N-D Tensor: + input = [ [1, 2, 3, 4], [5, 6, 7, 8] ] + + Then: + input.shape = [2, 4] + + Case2: + Given SelectedRows: + input.rows = [0, 4, 19] + input.height = 20 + input.value = [ [1, 2], [3, 4], [5, 6] ] # inner tensor + Then: + input.shape = [3, 2] + + Args: + input (Variable): The input can be N-D Tensor or SelectedRows with data type bool, float16, float32, float64, int32, int64. + If input variable is type of SelectedRows, returns the shape of it's inner tensor. + + Returns: + Variable (Tensor): The shape of the input variable. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + inputs = fluid.data(name="x", shape=[3, 100, 100], dtype="float32") + output = fluid.layers.shape(inputs) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + img = np.ones((3, 100, 100)).astype(np.float32) + + res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) + print(res) # [array([ 3, 100, 100], dtype=int32)] + """ + if in_dygraph_mode(): + out = _C_ops.shape(input) + out.stop_gradient = True + return out + if _in_legacy_dygraph(): + out = _legacy_C_ops.shape(input) + out.stop_gradient = True + return out + + check_variable_and_dtype( + input, + 'input', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'shape', + ) + helper = LayerHelper('shape', **locals()) + out = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op( + type='shape', + inputs={'Input': input}, + outputs={'Out': out}, + stop_gradient=True, + ) + + return out + + +def rank(input): + """ + + The OP returns the number of dimensions for a tensor, which is a 0-D int32 Tensor. + + Args: + input (Tensor): The input N-D tensor with shape of :math:`[N_1, N_2, ..., N_k]`, the data type is arbitrary. + + Returns: + Tensor, the output data type is int32.: The 0-D tensor with the dimensions of the input Tensor. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand((3, 100, 100)) + rank = paddle.rank(input) + print(rank) + # 3 + """ + check_type(input, 'input', (Variable), 'input') + ndims = len(input.shape) + out = assign(np.array(ndims, 'int32')) + + return out + + +@deprecated(since="2.0.0", update_to="paddle.numel") +def size(input): + """ + **Size Layer** + + Returns the number of elements for a tensor, which is a int64 Tensor with shape [1]. + + Args: + input (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64. + + Returns: + Tensor: The number of elements for the input Tensor. + + Raises: + TypeError: ``input`` must be a Tensor and the data type of ``input`` must be one of bool, float16, float32, float64, int32, int64. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid.layers as layers + paddle.enable_static() + + input = layers.data( + name="input", shape=[3, 100], dtype="float32", append_batch_size=False) + rank = layers.size(input) # 300 + """ + + if in_dygraph_mode(): + return _C_ops.size(input) + + if _in_legacy_dygraph(): + return _legacy_C_ops.size(input) + + check_variable_and_dtype( + input, + 'input', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + "size", + ) + helper = LayerHelper('size', **locals()) + out = helper.create_variable_for_type_inference(dtype='int64') + helper.append_op(type='size', inputs={'Input': input}, outputs={'Out': out}) + + return out + + +def _elementwise_op(helper): + op_type = helper.layer_type + x = helper.kwargs.get('x', None) + y = helper.kwargs.get('y', None) + + assert x is not None, 'x cannot be None in {}'.format(op_type) + assert y is not None, 'y cannot be None in {}'.format(op_type) + check_variable_and_dtype( + x, + 'x', + ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'], + op_type, + ) + check_variable_and_dtype( + y, + 'y', + ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'], + op_type, + ) + + axis = helper.kwargs.get('axis', -1) + use_mkldnn = helper.kwargs.get('use_mkldnn', False) + name = helper.kwargs.get('name', None) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type=op_type, + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs={'axis': axis, 'use_mkldnn': use_mkldnn}, + ) + return helper.append_activation(out) + + +def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): + """ + + Putting scale and bias to the input Tensor as following: + + ``bias_after_scale`` is True: + + .. math:: + Out=scale*X+bias + + ``bias_after_scale`` is False: + + .. math:: + Out=scale*(X+bias) + + Args: + x(Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8. + scale(float|Tensor): The scale factor of the input, it should be a float number or a Tensor with shape [1] and data type as float32. + bias(float): The bias to be put on the input. + bias_after_scale(bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances. + act(str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tensor: Output tensor of scale operator, with shape and data type same as input. + + Examples: + + .. code-block:: python + + # scale as a float32 number + import paddle + + data = paddle.randn(shape=[2,3], dtype='float32') + res = paddle.scale(data, scale=2.0, bias=1.0) + + .. code-block:: python + + # scale with parameter scale as a Tensor + import paddle + + data = paddle.randn(shape=[2, 3], dtype='float32') + factor = paddle.to_tensor([2], dtype='float32') + res = paddle.scale(data, scale=factor, bias=1.0) + + """ + + if in_dygraph_mode(): + out = _C_ops.scale(x, scale, float(bias), bias_after_scale) + return dygraph_utils._append_activation_in_dygraph(out) + if _non_static_mode(): + _scale = scale.numpy().item(0) if isinstance(scale, Variable) else scale + out = _legacy_C_ops.scale( + x, + 'scale', + float(_scale), + 'bias', + float(bias), + 'bias_after_scale', + bias_after_scale, + ) + return dygraph_utils._append_activation_in_dygraph(out) + + check_variable_and_dtype( + x, + "x", + [ + 'float16', + 'uint16', + 'float32', + 'float64', + 'int8', + 'int16', + 'int32', + 'int64', + 'uint8', + ], + "scale", + ) + inputs = {'X': [x]} + attrs = { + 'bias': float(bias), + 'bias_after_scale': bias_after_scale, + } + if isinstance(scale, Variable): + inputs['ScaleTensor'] = [scale] + else: + attrs['scale'] = float(scale) + helper = LayerHelper('scale', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='scale', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return helper.append_activation(out) + + +def elementwise_add(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_add(x, y) + # z = x + y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # [3., 8., 6.] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_add(x, y, axis=1) + # z = x + y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # z.shape=[2,3,4,5] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), + "y": np.random.randint(1, 5, size=[5]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[5], dtype='float32') + z = fluid.layers.elementwise_add(x, y, axis=3) + # z = x + y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + print(z_value) # z.shape=[2,3,4,5] + + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, + y, + axis=axis, + act=act, + op_name='elementwise_add', + use_mkldnn=_global_flags()["FLAGS_use_mkldnn"], + ) + + return _elementwise_op(LayerHelper('elementwise_add', **locals())) + + +@deprecated(since="2.0.0", update_to="paddle.divide") +def elementwise_div(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_div(x, y) + # z = x / y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # [2., 0.6, 2.] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_div(x, y, axis=1) + # z = x / y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # z.shape=[2,3,4,5] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), + "y": np.random.randint(1, 5, size=[5]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[5], dtype='float32') + z = fluid.layers.elementwise_div(x, y, axis=3) + # z = x / y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + print(z_value) # z.shape=[2,3,4,5] + + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_div' + ) + + return _elementwise_op(LayerHelper('elementwise_div', **locals())) + + +def elementwise_sub(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_sub(x, y) + # z = x - y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # [1., -2., 2.] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_sub(x, y, axis=1) + # z = x - y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # z.shape=[2,3,4,5] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), + "y": np.random.randint(1, 5, size=[5]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[5], dtype='float32') + z = fluid.layers.elementwise_sub(x, y, axis=3) + # z = x - y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + print(z_value) # z.shape=[2,3,4,5] + + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_sub' + ) + + return _elementwise_op(LayerHelper('elementwise_sub', **locals())) + + +@deprecated(since="2.0.0", update_to="paddle.multiply") +def elementwise_mul(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_mul(x, y) + # z = x * y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # [2., 15., 8.] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_mul(x, y, axis=1) + # z = x * y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) # z.shape=[2,3,4,5] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.random.randint(1, 5, size=[2, 3, 4, 5]).astype('float32'), + "y": np.random.randint(1, 5, size=[5]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[5], dtype='float32') + z = fluid.layers.elementwise_mul(x, y, axis=3) + # z = x * y + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + print(z_value) # z.shape=[2,3,4,5] + + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_mul' + ) + + return _elementwise_op(LayerHelper('elementwise_mul', **locals())) + + +def elementwise_max(x, y, axis=-1, act=None, name=None): + """ + :alias_main: paddle.elementwise_max + :alias: paddle.elementwise_max,paddle.tensor.elementwise_max,paddle.tensor.math.elementwise_max + :old_api: paddle.fluid.layers.elementwise_max + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_max(x, y) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) #[2, 5, 4] + + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_max(x, y, axis=1) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value)#[[[[1., 1., 1., 1., 1.] .... [1., 1., 1., 1., 1.]]]] + + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_max' + ) + + return _elementwise_op(LayerHelper('elementwise_max', **locals())) + + +def elementwise_min(x, y, axis=-1, act=None, name=None): + """ + :alias_main: paddle.elementwise_min + :alias: paddle.elementwise_min,paddle.tensor.elementwise_min,paddle.tensor.math.elementwise_min + :old_api: paddle.fluid.layers.elementwise_min + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_min(x, y) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) #[1, 3, 2] + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.ones((2, 3, 4, 5)).astype('float32'), + "y": np.zeros((3, 4)).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[2,3,4,5], dtype='float32') + y = fluid.data(name="y", shape=[3,4], dtype='float32') + z = fluid.layers.elementwise_min(x, y, axis=1) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value)#[[[[0., 0., 0., 0., 0.] .... [0., 0., 0., 0., 0.]]]] + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_min' + ) + + return _elementwise_op(LayerHelper('elementwise_min', **locals())) + + +def elementwise_pow(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([2, 3, 4]).astype('float32'), + "y": np.array([1, 5, 2]).astype('float32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='float32') + y = fluid.data(name="y", shape=[3], dtype='float32') + z = fluid.layers.elementwise_pow(x, y) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) #[2, 243, 16] + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_pow' + ) + return _elementwise_op(LayerHelper('elementwise_pow', **locals())) + + +@deprecated(since="2.0.0", update_to="paddle.remainder") +def elementwise_mod(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([10, 15, 8]).astype('int32'), + "y": np.array([3, 6, 5]).astype('int32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='int32') + y = fluid.data(name="y", shape=[3], dtype='int32') + z = fluid.layers.elementwise_mod(x, y) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) #[1, 3, 3] + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_mod' + ) + + return _elementwise_op(LayerHelper('elementwise_mod', **locals())) + + +@deprecated(since="2.0.0", update_to="paddle.floor_divide") +def elementwise_floordiv(x, y, axis=-1, act=None, name=None): + """ + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + + def gen_data(): + return { + "x": np.array([10, 15, 8]).astype('int32'), + "y": np.array([3, 7, 5]).astype('int32') + } + paddle.enable_static() + x = fluid.data(name="x", shape=[3], dtype='int32') + y = fluid.data(name="y", shape=[3], dtype='int32') + z = fluid.layers.elementwise_floordiv(x, y) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + z_value = exe.run(feed=gen_data(), + fetch_list=[z.name]) + + print(z_value) #[3, 2, 1] + """ + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_floordiv' + ) + + return _elementwise_op(LayerHelper('elementwise_floordiv', **locals())) + + +for func in [ + elementwise_add, + elementwise_div, + elementwise_sub, + elementwise_mul, + elementwise_max, + elementwise_pow, + elementwise_min, + elementwise_mod, + elementwise_floordiv, +]: + op_proto = OpProtoHolder.instance().get_op_proto(func.__name__) + + # insert the c++ doc string on top of python doc string + func.__doc__ = ( + _generate_doc_string_( + op_proto, + additional_args_lines=[ + "axis (int32, optional): If X.dimension != Y.dimension, \ + Y.dimension must be a subsequence of x.dimension. \ + And axis is the start dimension index for broadcasting Y onto X. ", + "act (string, optional): Activation applied to the output. \ + Default is None. Details: :ref:`api_guide_activations_en` ", + "name (string, optional): Name of the output. \ + Default is None. It's used to print debug info for developers. Details: \ + :ref:`api_guide_Name` ", + ], + skip_attrs_set={ + "x_data_format", + "y_data_format", + "axis", + "use_quantizer", + "mkldnn_data_type", + "Scale_x", + "Scale_y", + "Scale_out", + }, + ) + + """\n""" + + str(func.__doc__) + ) + + doc_list = func.__doc__.splitlines() + + for idx, val in enumerate(doc_list): + if ( + val.startswith("Warning: ") + and val.endswith(" instead.") + and "and will be removed in future versions." in val + ): + doc_list.insert(0, doc_list.pop(idx)) + func.__doc__ = "\n" + "\n".join(i for i in doc_list) + break + +for func in []: + op_proto = OpProtoHolder.instance().get_op_proto(func.__name__) + func.__doc__ = _generate_doc_string_( + op_proto, + additional_args_lines=[ + "act (basestring|None): Activation applied to the output.", + "name (basestring|None): Name of the output.", + ], + ) + func.__doc__ = ( + func.__doc__ + + """ + +Examples: + .. code-block:: python + + import paddle.fluid as fluid + # example 1: shape(x) = (2, 3, 4, 5), shape(y) = (2, 3, 4, 5) + x0 = fluid.layers.data(name="x0", shape=[2, 3, 4, 5], dtype='float32') + y0 = fluid.layers.data(name="y0", shape=[2, 3, 4, 5], dtype='float32') + z0 = fluid.layers.%s(x0, y0) + + # example 2: shape(X) = (2, 3, 4, 5), shape(Y) = (5) + x1 = fluid.layers.data(name="x1", shape=[2, 3, 4, 5], dtype='float32') + y1 = fluid.layers.data(name="y1", shape=[5], dtype='float32') + z1 = fluid.layers.%s(x1, y1) + + # example 3: shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2 + x2 = fluid.layers.data(name="x2", shape=[2, 3, 4, 5], dtype='float32') + y2 = fluid.layers.data(name="y2", shape=[4, 5], dtype='float32') + z2 = fluid.layers.%s(x2, y2, axis=2) + + # example 4: shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1 + x3 = fluid.layers.data(name="x3", shape=[2, 3, 4, 5], dtype='float32') + y3 = fluid.layers.data(name="y3", shape=[3, 4], dtype='float32') + z3 = fluid.layers.%s(x3, y3, axis=1) + + # example 5: shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0 + x4 = fluid.layers.data(name="x4", shape=[2, 3, 4, 5], dtype='float32') + y4 = fluid.layers.data(name="y4", shape=[2], dtype='float32') + z4 = fluid.layers.%s(x4, y4, axis=0) + + # example 6: shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0 + x5 = fluid.layers.data(name="x5", shape=[2, 3, 4, 5], dtype='float32') + y5 = fluid.layers.data(name="y5", shape=[2], dtype='float32') + z5 = fluid.layers.%s(x5, y5, axis=0) + """ + % ( + func.__name__, + func.__name__, + func.__name__, + func.__name__, + func.__name__, + func.__name__, + ) + ) + + +def _logical_op(op_name, x, y, out=None, name=None, binary_op=True): + if _non_static_mode(): + op = getattr(_legacy_C_ops, op_name) + if binary_op: + return op(x, y) + else: + return op(x) + check_variable_and_dtype( + x, + "x", + ["bool", "int8", "int16", "int32", "int64", "float32", "float64"], + op_name, + ) + if y is not None: + check_variable_and_dtype( + y, + "y", + ["bool", "int8", "int16", "int32", "int64", "float32", "float64"], + op_name, + ) + if out is not None: + check_type(out, "out", Variable, op_name) + + helper = LayerHelper(op_name, **locals()) + + if binary_op and x.dtype != y.dtype: + raise ValueError( + "(InvalidArgument) The DataType of %s Op's Variable must be consistent, but received %s and %s." + % (op_name, x.dtype, y.dtype) + ) + + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if binary_op: + helper.append_op( + type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out} + ) + else: + helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out}) + + return out + + +def logical_and(x, y, out=None, name=None): + r""" + + ``logical_and`` operator computes element-wise logical AND on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = x \&\& y + + .. note:: + ``paddle.logical_and`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True]) + y = paddle.to_tensor([True, False, True, False]) + res = paddle.logical_and(x, y) + print(res) # [True False True False] + """ + if in_dygraph_mode(): + return _C_ops.logical_and(x, y) + + return _logical_op( + op_name="logical_and", x=x, y=y, name=name, out=out, binary_op=True + ) + + +def logical_or(x, y, out=None, name=None): + """ + + ``logical_or`` operator computes element-wise logical OR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = x || y + + .. note:: + ``paddle.logical_or`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Variable`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + x_data = np.array([True, False], dtype=np.bool_).reshape(2, 1) + y_data = np.array([True, False, True, False], dtype=np.bool_).reshape(2, 2) + x = paddle.to_tensor(x_data) + y = paddle.to_tensor(y_data) + res = paddle.logical_or(x, y) + print(res) # [[ True True] [ True False]] + """ + if in_dygraph_mode(): + return _C_ops.logical_or(x, y) + return _logical_op( + op_name="logical_or", x=x, y=y, name=name, out=out, binary_op=True + ) + + +def logical_xor(x, y, out=None, name=None): + r""" + + ``logical_xor`` operator computes element-wise logical XOR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = (x || y) \&\& !(x \&\& y) + + .. note:: + ``paddle.logical_xor`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + x_data = np.array([True, False], dtype=np.bool_).reshape([2, 1]) + y_data = np.array([True, False, True, False], dtype=np.bool_).reshape([2, 2]) + x = paddle.to_tensor(x_data) + y = paddle.to_tensor(y_data) + res = paddle.logical_xor(x, y) + print(res) # [[False, True], [ True, False]] + """ + if in_dygraph_mode(): + return _C_ops.logical_xor(x, y) + + return _logical_op( + op_name="logical_xor", x=x, y=y, name=name, out=out, binary_op=True + ) + + +@templatedoc() +def logical_not(x, out=None, name=None): + """ + + ``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``. + Each element of ``out`` is calculated by + + .. math:: + + out = !x + + Args: + x(Tensor): Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output. + name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True, False, True, False]) + res = paddle.logical_not(x) + print(res) # [False True False True] + """ + if in_dygraph_mode(): + return _C_ops.logical_not(x) + return _logical_op( + op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False + ) + + +@templatedoc() +def clip(x, min, max, name=None): + """ + :old_api: paddle.fluid.layers.clip + + ${comment} + + Args: + x(${x_type}): ${x_comment} + min(float): ${min_comment} + max(float): ${max_comment} + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + ${out_comment} + + Return Type: + ${out_type} + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + input = fluid.data( + name='data', shape=[1], dtype='float32') + reward = fluid.layers.clip(x=input, min=-1.0, max=1.0) + """ + + helper = LayerHelper("clip", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'clip') + + if name is None: + name = unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp']) + ) + + out = helper.create_variable( + type=x.type, name=name, dtype=x.dtype, persistable=False + ) + + helper.append_op( + type="clip", + inputs={"X": x}, + attrs={"min": min, "max": max}, + outputs={"Out": out}, + ) + + return out + + +@templatedoc() +def clip_by_norm(x, max_norm, name=None): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment} + max_norm(${max_norm_type}): ${max_norm_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: + + out(${out_type}): ${out_comment} + + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + input = paddle.to_tensor([[2.0, 2.0], [2.0, 2.0]], dtype='float32') + reward = fluid.layers.clip_by_norm(x=input, max_norm=1.0) + # [[0.5, 0.5], [0.5, 0.5]] + """ + + if in_dygraph_mode(): + return _C_ops.clip_by_norm(x, max_norm) + if _non_static_mode(): + return _legacy_C_ops.clip_by_norm(x, 'max_norm', max_norm) + + helper = LayerHelper("clip_by_norm", **locals()) + check_variable_and_dtype(x, 'X', ['float32', 'float16'], 'clip_by_norm') + check_type(max_norm, 'max_norm', (float), 'clip_by_norm') + + if name is None: + name = unique_name.generate_with_ignorable_key( + ".".join([helper.name, 'tmp']) + ) + + out = helper.create_variable( + type=x.type, name=name, dtype=x.dtype, persistable=False + ) + + helper.append_op( + type="clip_by_norm", + inputs={"X": x}, + attrs={"max_norm": max_norm}, + outputs={"Out": out}, + ) + + return out + + +@deprecated(since="2.0.0", update_to="paddle.mean") +@templatedoc() +def mean(x, name=None): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment} + name(basestring|None): Name of the output. + + Returns: + out(${out_type}): ${out_comment} + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + input = fluid.layers.data( + name='data', shape=[2, 3], dtype='float32') + mean = paddle.mean(input) + """ + + if _in_legacy_dygraph(): + return _legacy_C_ops.mean(x) + if in_dygraph_mode(): + return _C_ops.mean_all(x) + + helper = LayerHelper("mean", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mean') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="mean", inputs={"X": x}, attrs={}, outputs={"Out": out} + ) + + return out + + +@templatedoc() +def merge_selected_rows(x, name=None): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment} + name(basestring|None): Name of the output. + + Returns: + out(${out_type}): ${out_comment} + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + b = fluid.default_main_program().global_block() + var = b.create_var( + name="X", dtype="float32", persistable=True, + type=fluid.core.VarDesc.VarType.SELECTED_ROWS) + y = fluid.layers.merge_selected_rows(var) + """ + if _non_static_mode(): + return _legacy_C_ops.merge_selected_rows(x) + + helper = LayerHelper("merge_selected_rows", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="merge_selected_rows", + inputs={"X": x}, + attrs={}, + outputs={"Out": out}, + ) + return out + + +def mul(x, y, x_num_col_dims=1, y_num_col_dims=1, name=None): + """ + Mul Operator. + This operator is used to perform matrix multiplication for input $x$ and $y$. + The equation is: + + .. math:: + Out = x * y + + Both the input $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $x$. + + Args: + x (Variable): The first input Tensor/LoDTensor of mul_op. + y (Variable): The second input Tensor/LoDTensor of mul_op. + x_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $x$ is a tensor with more than two dimensions, $x$ will be flattened into a two-dimensional matrix first. The flattening rule is: the first `num_col_dims` will be flattened to form the first dimension of the final matrix (the height of the matrix), and the rest `rank(x) - num_col_dims` dimensions are flattened to form the second dimension of the final matrix (the width of the matrix). As a result, height of the flattened matrix is equal to the product of $x$'s first `x_num_col_dims` dimensions' sizes, and width of the flattened matrix is equal to the product of $x$'s last `rank(x) - num_col_dims` dimensions' size. For example, suppose $x$ is a 6-dimensional tensor with the shape [2, 3, 4, 5, 6], and `x_num_col_dims` = 3. Thus, the flattened matrix will have a shape [2 x 3 x 4, 5 x 6] = [24, 30]. Default is 1. + y_num_col_dims (int, optional): The mul_op can take tensors with more than two dimensions as its inputs. If the input $y$ is a tensor with more than two dimensions, $y$ will be flattened into a two-dimensional matrix first. The attribute `y_num_col_dims` determines how $y$ is flattened. See comments of `x_num_col_dims` for more details. Default is 1. + name (str, optional): Name of the output. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Default is None. + + Returns: + Variable(Tensor/LoDTensor): The output Tensor/LoDTensor of mul op. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + dataX = fluid.layers.data(name="dataX", append_batch_size = False, shape=[2, 5], dtype="float32") + dataY = fluid.layers.data(name="dataY", append_batch_size = False, shape=[5, 3], dtype="float32") + output = fluid.layers.mul(dataX, dataY, + x_num_col_dims = 1, + y_num_col_dims = 1) + + + """ + if _non_static_mode(): + return _legacy_C_ops.mul( + x, + y, + 'x_num_col_dims', + x_num_col_dims, + 'y_num_col_dims', + y_num_col_dims, + ) + + inputs = {"X": [x], "Y": [y]} + attrs = {"x_num_col_dims": x_num_col_dims, "y_num_col_dims": y_num_col_dims} + helper = LayerHelper("mul", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mul') + check_variable_and_dtype(y, 'y', ['float16', 'float32', 'float64'], 'mul') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="mul", inputs={"X": x, "Y": y}, attrs=attrs, outputs={"Out": out} + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.maxout") +@templatedoc() +def maxout(x, groups, name=None, axis=1): + """ + ${comment} + + Args: + x(${x_type}): ${x_comment} + groups(int): ${groups_comment} + axis(int, optional): ${axis_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: ${out_comment} + + Raises: + ValueError: If `axis` is not 1, -1 or 3. + ValueError: If the number of input channels can not be divisible by `groups`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + input = fluid.data( + name='data', + shape=[None, 256, 32, 32], + dtype='float32') + out = fluid.layers.maxout(input, groups=2) + """ + return paddle.nn.functional.maxout(**locals()) + + +def space_to_depth(x, blocksize, name=None): + r""" + + Gives a blocksize to space_to_depth the input LoDtensor with Layout: [batch, channel, height, width] + + This op rearranges blocks of spatial data, into depth. More specifically, this op outputs a copy of \ + theinput LoDtensor where values from the height and width dimensions are moved to the channel \ + dimension. + The attr blocksize indicates the input block size. + + space_to_depth will reorganize the elements of input with shape[batch, channel, height, width] \ + according to blocksize to construct output with shape \ + [batch, channel * blocksize * blocksize, height/blocksize, width/blocksize]: + + - Non-overlapping blocks of size block_size x block size are rearranged into depth at each location. + - The Y, X coordinates within each block of the input become the high order component of the output channel index + - channel should be divisible by square of blocksize + - height, width should be divsible by blocksize + + This OP is useful for resizing the activations between convolutions \ + (but keeping all data) + + .. code-block:: text + + Given the input x with the shape [1, 1, 4, 4]: + x.data = [[[[1, 2, 5, 6], + [3, 4, 7, 8], + [9, 10, 13, 14], + [11, 12, 15, 16]]]] + blocksize = 2 + + then get the output with the shape [1, 4, 2, 2]: + out.data = [[[[1, 2], [3, 4]], + [[5, 6], [7, 8]], + [[9, 10], [11, 12]], + [[13, 14], [15, 16]]]] + + Args: + x (Variable): The input, which should be 4 dims Tensor or LodTensor, with the shape \ + [batch, channel, height, width] + blocksize (int): The blocksize to select the element on each feature map should be > 2 + name(str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The output, which should be 4 dims Tensor or LodTensor, with the shape \ + [batch, channel * blocksize * blocksize, height/blocksize, width/blocksize] + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import numpy as np + import paddle + + paddle.enable_static() + data = fluid.data( + name='data', shape=[1, 4, 2, 2], dtype='float32') + space_to_depthed = fluid.layers.space_to_depth( + x=data, blocksize=2) + + exe = fluid.Executor(fluid.CPUPlace()) + data_np = np.arange(0,16).reshape((1,4,2,2)).astype('float32') + + print(data_np) + #array([[[[ 0., 1.], [ 2., 3.]], + # [[ 4., 5.], [ 6., 7.]], + # [[ 8., 9.], [10., 11.]], + # [[12., 13.], [14., 15.]]]], dtype=float32) + + out_main = exe.run(fluid.default_main_program(), + feed={'data': data_np}, + fetch_list=[space_to_depthed]) + + print(out_main) + #[array([[[[ 0.]], [[ 4.]], [[ 1.]], [[ 5.]], + # [[ 8.]], [[12.]], [[ 9.]], [[13.]], + # [[ 2.]], [[ 6.]], [[ 3.]], [[ 7.]], + # [[10.]], [[14.]], [[11.]], [[15.]]]], dtype=float32)] + + """ + + helper = LayerHelper("space_to_depth", **locals()) + + if not (isinstance(blocksize, int)): + raise ValueError("blocksize must be a python Int") + + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'space_to_depth', + ) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="space_to_depth", + inputs={"X": x}, + attrs={"blocksize": blocksize}, + outputs={"Out": out}, + ) + return out + + +def affine_channel( + x, scale=None, bias=None, data_layout='NCHW', name=None, act=None +): + """ + + Applies a separate affine transformation to each channel of the input. + Useful for replacing spatial batch norm with its equivalent fixed + transformation. The input also can be 2D tensor and applies a affine + transformation in second dimension. + + Args: + x (Variable): Feature map input can be a 4D tensor with order NCHW + or NHWC. It also can be a 2D tensor and the affine transformation + is applied in the second dimension.The data type is float32 or float64. + scale (Variable): 1D input of shape (C), the c-th element is the scale + factor of the affine transformation for the c-th channel of + the input.The data type is float32 or float64. + bias (Variable): 1D input of shape (C), the c-th element is the bias + of the affine transformation for the c-th channel of the input. + The data type is float32 or float64. + data_layout (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. If input is 2D Tensor, you can ignore + data_layout. + name (str, default None): The name of this layer. For more information, + please refer to :ref:`api_guide_Name` . + act (str, default None): Activation to be applied to the output of this layer. + + Returns: + Variable: A tensor which has the same shape, data layout and data type with x. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + use_gpu = False + place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() + exe = fluid.Executor(place) + + data = fluid.data(name='data', shape=[None, 1, 2, 2], dtype='float32') + input_scale = fluid.layers.create_parameter(shape=[1], dtype="float32", + default_initializer=fluid.initializer.Constant(2.0)) + input_bias = fluid.layers.create_parameter(shape=[1],dtype="float32", + default_initializer=fluid.initializer.Constant(0.5)) + out = fluid.layers.affine_channel(data,scale=input_scale, + bias=input_bias) + + exe.run(fluid.default_startup_program()) + test_program = fluid.default_main_program().clone(for_test=True) + + [out_array] = exe.run(test_program, + fetch_list=out, + feed={'data': np.ones([1,1,2,2]).astype('float32')}) + # out_array is [[[[2.5, 2.5], + # [2.5, 2.5]]]] with shape: [1, 1, 2, 2] + + """ + helper = LayerHelper("affine_channel", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'affine_channel') + check_type(scale, 'scale', (Variable, type(None)), 'affine_channel') + check_type(bias, 'bias', (Variable, type(None)), 'affine_channel') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="affine_channel", + inputs={"X": x, 'Scale': scale, 'Bias': bias}, + attrs={"data_layout": data_layout}, + outputs={"Out": out}, + ) + return helper.append_activation(out) + + +def similarity_focus(input, axis, indexes, name=None): + r""" + SimilarityFocus Operator + + Generate a similarity focus mask with the same shape of input using the following method: + + 1. Extract the 3-D tensor(here the first dimension is BatchSize) corresponding + to the axis according to the indexes. For example, if axis=1 and indexes=[a], + it will get the matrix T=X[:, a, :, :]. In this case, if the shape of input X + is (BatchSize, A, B, C), the shape of tensor T is (BatchSize, B, C). + 2. For each index, find the largest numbers in the tensor T, so that the same + row and same column has at most one number(what it means is that if the + largest number has been found in the i-th row and the j-th column, then + the numbers in the i-th row or j-th column will be skipped. And then the + next largest number will be selected from the remaining numbers. Obviously + there will be min(B, C) numbers), and mark the corresponding position of the + 3-D similarity focus mask as 1, otherwise as 0. Do elementwise-or for + each index. + 3. Broadcast the 3-D similarity focus mask to the same shape of input X. + + Refer to `Similarity Focus Layer `_ + + .. code-block:: text + + * Example : + + Given a 4-D tensor x with the shape (BatchSize, C, A, B), where C is + the number of channels and the shape of feature map is (A, B): + x.shape = (2, 3, 2, 2) + x.data = [[[[0.8, 0.1], + [0.4, 0.5]], + + [[0.9, 0.7], + [0.9, 0.9]], + + [[0.8, 0.9], + [0.1, 0.2]]], + + + [[[0.2, 0.5], + [0.3, 0.4]], + + [[0.9, 0.7], + [0.8, 0.4]], + + [[0.0, 0.2], + [0.4, 0.7]]]] + + Given axis: 1 (the axis of the channel) + Given indexes: [0] + + then we get a 4-D tensor out with the same shape of input x: + out.shape = (2, 3, 2, 2) + out.data = [[[[1.0, 0.0], + [0.0, 1.0]], + + [[1.0, 0.0], + [0.0, 1.0]], + + [[1.0, 0.0], + [0.0, 1.0]]], + + [[[0.0, 1.0], + [1.0, 0.0]], + + [[0.0, 1.0], + [1.0, 0.0]], + + [[0.0, 1.0], + [1.0, 0.0]]]] + + Args: + input(Variable): The input tensor variable(default float). It should + be a 4-D tensor with shape [BatchSize, A, B, C]. Data type is + float32 or float64. + axis(int): Indicating the dimension to be selected. It can only be + 1, 2 or 3. + indexes(list): Indicating the indexes of the selected dimension. + + Returns: + Variable: A tensor variable with the same shape and same type \ + as the input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + data = fluid.data( + name='data', shape=[-1, 3, 2, 2], dtype='float32') + fluid.layers.similarity_focus(input=data, axis=1, indexes=[0]) + """ + helper = LayerHelper('similarity_focus', **locals()) + # check attrs + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], "similarity_focus" + ) + check_type(axis, 'axis', int, "similarity_focus") + check_type(indexes, 'indexes', list, "similarity_focus") + if axis != 1 and axis != 2 and axis != 3: + raise ValueError("axis must be 1, 2 or 3.") + if len(indexes) == 0: + raise ValueError("indexes can not be empty.") + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='similarity_focus', + inputs={'X': input}, + outputs={'Out': out}, + attrs={"axis": axis, "indexes": indexes}, + ) + return out + + +def hash(input, hash_size, num_hash=1, name=None): + """ + + This OP hash the input to an integer less than the hash_size. + The hash algorithm we used was xxHash - Extremely fast hash algorithm + (https://github.com/Cyan4973/xxHash/tree/v0.6.5) + + Args: + input(Variable): A **Two-Dimensional** LoDTensor with type int32, int64. + **Only support LoDTensor**. + num_hash(int, optional): The times of hash, default is 1. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Variable: A LoDTensor with the same data type as input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + place = fluid.core.CPUPlace() + + x = fluid.data(name="x", shape=[2,2], dtype="int32", lod_level=1) + res = fluid.layers.hash(name="res", input=x, hash_size=1000, num_hash=4) + + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + in1 = np.array([[1,2],[3,4]]).astype("int32") + print(in1) + x_i = fluid.create_lod_tensor(in1, [[0, 2]], place) + res = exe.run(fluid.default_main_program(), feed={'x':x_i}, fetch_list=[res], return_numpy=False) + print(np.array(res[0])) + # [[[722] + # [407] + # [337] + # [395]] + # [[603] + # [590] + # [386] + # [901]]] + """ + check_variable_and_dtype(input, 'input', ['int32', 'int64'], 'hash') + check_type(hash_size, 'hash_size', int, 'hash') + check_type(num_hash, 'num_hash', int, 'hash') + helper = LayerHelper('hash', **locals()) + out = helper.create_variable_for_type_inference( + helper.input_dtype(), stop_gradient=True + ) + helper.append_op( + type='hash', + inputs={'X': input}, + outputs={'Out': out}, + attrs={'num_hash': num_hash, 'mod_by': hash_size}, + ) + return out + + +@templatedoc() +def grid_sampler(x, grid, name=None): + """ + + This operation samples input X by using bilinear interpolation based on + flow field grid, which is usually generated by :code:`affine_grid` . The grid of + shape [N, H, W, 2] is the concatenation of (x, y) coordinates + with shape [N, H, W] each, where x is indexing the 4th dimension + (in width dimension) of input data x and y is indexing the 3rd + dimension (in height dimension), finally results is the bilinear + interpolation value of 4 nearest corner points. The output tensor + shape will be [N, C, H, W]. + + .. code-block:: text + + Step 1: + Get (x, y) grid coordinates and scale to [0, H-1/W-1]. + + .. code-block:: text + + grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) + grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) + + Step 2: + Indices input data X with grid (x, y) in each [H, W] area, and bilinear + interpolate point value by 4 nearest points. + + wn ------- y_n ------- en + | | | + | d_n | + | | | + x_w --d_w-- grid--d_e-- x_e + | | | + | d_s | + | | | + ws ------- y_s ------- wn + + x_w = floor(x) // west side x coord + x_e = x_w + 1 // east side x coord + y_n = floor(y) // north side y coord + y_s = y_s + 1 // south side y coord + + d_w = grid_x - x_w // distance to west side + d_e = x_e - grid_x // distance to east side + d_n = grid_y - y_n // distance to north side + d_s = y_s - grid_y // distance to south side + + wn = X[:, :, y_n, x_w] // north-west point value + en = X[:, :, y_n, x_e] // north-east point value + ws = X[:, :, y_s, x_w] // south-east point value + es = X[:, :, y_s, x_w] // north-east point value + + output = wn * d_e * d_s + en * d_w * d_s + + ws * d_e * d_n + es * d_w * d_n + + Args: + x(Variable): The input tensor, which is a 4-D tensor with shape + [N, C, H, W], N is the batch size, C is the channel + number, H and W is the feature height and width. + The data type is float32 or float64. + grid(Variable): Input grid tensor of shape [N, H, W, 2]. The + data type is float32 or float64. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: Output of shape [N, C, H, W] data samples input X + using bilnear interpolation based on input grid. + The data type is same as input tensor. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid as fluid + import paddle + + paddle.enable_static() + # use with affine_grid + x = fluid.data(name='x', shape=[None, 10, 32, 32], dtype='float32') + theta = fluid.layers.data(name='theta', shape=[2, 3], dtype='float32') + grid = fluid.layers.affine_grid(theta=theta, out_shape=[3, 10, 32, 32]) + out = fluid.layers.grid_sampler(x=x, grid=grid) + + """ + helper = LayerHelper("grid_sampler", **locals()) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'grid_sampler') + check_variable_and_dtype( + grid, 'grid', ['float32', 'float64'], 'grid_sampler' + ) + if not isinstance(x, Variable): + return ValueError("The x should be a Variable") + + if not isinstance(grid, Variable): + return ValueError("The grid should be a Variable") + + out = helper.create_variable_for_type_inference(x.dtype) + ipts = {'X': x, 'Grid': grid} + + attrs = {'use_cudnn': False} if core.is_compiled_with_rocm() else {} + + helper.append_op( + type='grid_sampler', inputs=ipts, outputs={'Output': out}, attrs=attrs + ) + return out + + +def log_loss(input, label, epsilon=1e-4, name=None): + r""" + + **Negative Log Loss Layer** + + This layer accepts input predictions and target label and returns the + negative log loss. + + .. math:: + + Out = -label * \log{(input + \epsilon)} + - (1 - label) * \log{(1 - input + \epsilon)} + + Args: + input (Tensor|list): A 2-D tensor with shape [N x 1], where N is the + batch size. This input is a probability computed + by the previous operator. Data type float32. + label (Tensor|list): The ground truth which is a 2-D tensor with + shape [N x 1], where N is the batch size. + Data type float32. + epsilon (float, optional): A small number for numerical stability. Default 1e-4. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Tensor, which shape is [N x 1], data type is float32. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + label = paddle.randn((10,1)) + prob = paddle.randn((10,1)) + cost = F.log_loss(input=prob, label=label) + """ + return paddle.nn.functional.log_loss(input, label, epsilon, name) + + +def add_position_encoding(input, alpha, beta, name=None): + r""" + + This operator performs weighted sum of input feature at each position + (position in the sequence) and the corresponding position encoding. + + For more details of position encoding, please refer to `Attention Is All You + Need `_ . + + The formula is as follows: + + .. math:: + PE(pos, 2i) &= \\sin{(pos / 10000^{2i / P})} \\\\ + PE(pos, 2i + 1) &= \\cos{(pos / 10000^{2i / P})} \\\\ + Out(:, pos, i) &= \\alpha * input(:, pos, i) + \\beta * PE(pos, i) + + Where: + - :math:`PE(pos, 2i)` : the value at even index `2i` for encoding of position `pos`. + - :math:`PE(pos, 2i + 1)` : the value at odd index `2i+1` for encoding of position `pos` + + Args: + input(Variable): A Tensor or LoDTensor (lod level is 1). If it is a + Tensor, the shape should be `[N, M, P]`, where `N` stands for + batch size, `M` for sequence length, `P` for the size of feature + dimension. If it is a LoDTensor, the shape should be `[N, P]`, + where `N` stands for the total sequence lengths in this mini-batch, + `P` for the size of feature. The data type should be float32 or float64. + alpha(float): Indicate the weight coefficient for `input` when performing + weighted sum. + beta(float): Indicate the weight coefficient for position encoding when + performing weighted sum. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Variable: A Tensor or LoDTensor. It has the same shape, data type and lod as `input`. + + Examples: + .. code-block:: python + + import paddle + + tensor = paddle.randn([16, 32, 64]) + position_tensor = paddle.fluid.layers.add_position_encoding( + input=tensor, alpha=1.0, beta=1.0) + + """ + if _non_static_mode(): + return _legacy_C_ops.add_position_encoding( + input, "alpha", alpha, "beta", beta + ) + + helper = LayerHelper('add_position_encoding', **locals()) + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], "add_position_encoding" + ) + dtype = helper.input_dtype() + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type="add_position_encoding", + inputs={"X": input}, + outputs={"Out": out}, + attrs={"alpha": alpha, "beta": beta}, + ) + return out + + +def bilinear_tensor_product( + x, y, size, act=None, name=None, param_attr=None, bias_attr=None +): + r""" + :api_attr: Static Graph + + **Bilinear Tensor Product Layer** + + This layer performs bilinear tensor product on two inputs. + For example: + + .. math:: + out_{i} = x * W_{i} * {y^\mathrm{T}}, i=0,1,...,size-1 + + In this formula: + - :math:`x`: the first input contains M elements, shape is [batch_size, M]. + - :math:`y`: the second input contains N elements, shape is [batch_size, N]. + - :math:`W_{i}`: the i-th learned weight, shape is [M, N]. + - :math:`out_{i}`: the i-th element of out, shape is [batch_size, size]. + - :math:`y^\mathrm{T}`: the transpose of :math:`y_{2}`. + + Args: + x (Variable): 2-D input tensor with shape [batch_size, M]. Data type + is float32 or float64. + y (Variable): 2-D input tensor with shape [batch_size, N]. Data type + should be same as **x**. + size (int): The dimension of this layer. + act (str|None): Activation to be applied to the output of this layer. Default None. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + param_attr (ParamAttr|None): To specify the weight parameter attribute. + Default: None, which means the default weight parameter property is + used. See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr|None): To specify the bias parameter attribute. + Default: None, which means the default bias parameter property is + used. See usage for details in :ref:`api_fluid_ParamAttr` . + Returns: + Variable: A 2-D Tensor of shape [batch_size, size]. Data type is the same as input **x**. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + layer1 = paddle.static.data("t1", shape=[-1, 5], dtype="float32") + layer2 = paddle.static.data("t2", shape=[-1, 4], dtype="float32") + tensor = paddle.static.nn.bilinear_tensor_product(x=layer1, y=layer2, size=1000) + """ + helper = LayerHelper('bilinear_tensor_product', **locals()) + dtype = helper.input_dtype('x') + + param_shape = [size, x.shape[1], y.shape[1]] + + w = helper.create_parameter( + attr=helper.param_attr, shape=param_shape, dtype=dtype, is_bias=False + ) + out = helper.create_variable_for_type_inference(dtype=dtype) + + inputs = {"X": x, "Y": y, "Weight": w} + if helper.bias_attr: + bias_size = [1, size] + bias = helper.create_parameter( + attr=helper.bias_attr, shape=bias_size, dtype=dtype, is_bias=True + ) + inputs["Bias"] = bias + helper.append_op( + type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out} + ) + + # add activation + return helper.append_activation(out) + + +@templatedoc() +def get_tensor_from_selected_rows(x, name=None): + """ + This operator gets tensor data from input with SelectedRows type, and outputs a LoDTensor. + + .. code-block:: text + + input x is SelectedRows: + x.rows = [0, 5, 5, 4, 19] + x.height = 20 + x.value = [[1, 1] [2, 2] [2, 2] [3, 3] [6, 6]] + + Output is LoDTensor: + out.shape = [5, 2] + out.data = [[1, 1], + [2, 2], + [2, 2], + [3, 3], + [6, 6]] + + Args: + x(SelectedRows): Input with SelectedRows type. The data type is float32, float64, int32 or int64. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: LoDTensor transformed from SelectedRows. The data type is same with input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + b = fluid.default_main_program().global_block() + input = b.create_var(name="X", dtype="float32", persistable=True, type=fluid.core.VarDesc.VarType.SELECTED_ROWS) + out = fluid.layers.get_tensor_from_selected_rows(input) + """ + + check_type(x, 'x', Variable, 'get_tensor_from_selected_rows') + if x.type != core.VarDesc.VarType.SELECTED_ROWS: + raise TypeError( + "The type of 'x' in get_tensor_from_selected_rows must be SELECTED_ROWS." + ) + helper = LayerHelper('get_tensor_from_selected_rows', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='get_tensor_from_selected_rows', + inputs={'X': x}, + outputs={'Out': out}, + attrs={}, + ) + return out + + +def shuffle_channel(x, group, name=None): + """ + This operator shuffles the channels of input x. + It divide the input channels in each group into :attr:`group` subgroups, + and obtain a new order by selecting element from every subgroup one by one. + + Please refer to the paper + https://arxiv.org/pdf/1707.01083.pdf + + .. code-block:: text + + Given a 4-D tensor input with the shape (N, C, H, W): + input.shape = (1, 4, 2, 2) + input.data =[[[[0.1, 0.2], + [0.2, 0.3]], + + [[0.3, 0.4], + [0.4, 0.5]], + + [[0.5, 0.6], + [0.6, 0.7]], + + [[0.7, 0.8], + [0.8, 0.9]]]] + Given group: 2 + then we get a 4-D tensor out with the same shape of input: + out.shape = (1, 4, 2, 2) + out.data = [[[[0.1, 0.2], + [0.2, 0.3]], + + [[0.5, 0.6], + [0.6, 0.7]], + + [[0.3, 0.4], + [0.4, 0.5]], + + [[0.7, 0.8], + [0.8, 0.9]]]] + + Args: + x(Variable): The input tensor variable. It should be a 4-D tensor with shape [N, C, H, W] + group(int): Indicating the counts of subgroups, It should divide the number of channels. + + Returns: + out(Variable): the channels shuffling result is a tensor variable with the + same shape and same type as the input. + + Raises: + ValueError: If group is not an int type variable. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + input = fluid.data(name='input', shape=[None,4,2,2], dtype='float32') + out = fluid.layers.shuffle_channel(x=input, group=2) + """ + helper = LayerHelper("shuffle_channel", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if not isinstance(group, int): + raise TypeError("group must be int type") + + helper.append_op( + type="shuffle_channel", + inputs={"X": x}, + outputs={"Out": out}, + attrs={"group": group}, + ) + return out + + +@templatedoc() +def temporal_shift(x, seg_num, shift_ratio=0.25, name=None, data_format="NCHW"): + """ + + **Temporal Shift Operator** + + ${comment} + + Args: + x(Tensor): ${x_comment} + seg_num(int): ${seg_num_comment} + shift_ratio(float): ${shift_ratio_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCHW" or "NHWC". Default: "NCHW". + + Returns: + out(Tensor): The temporal shifting result is a tensor with the + same shape and same data type as the input. + + Raises: + TypeError: seg_num must be int type. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.randn([6, 4, 2, 2]) + out = F.temporal_shift(x=input, seg_num=2, shift_ratio=0.2) + """ + return paddle.nn.functional.temporal_shift( + x, seg_num, shift_ratio, name, data_format + ) + + +class PyFuncRegistry(object): + _register_funcs = [] + + def __init__(self, func): + if func is None or not callable(func): + raise TypeError('func must be a Python function') + + self._func = func + # find named args using reflection + args = inspect.getargspec(self._func) + if len(args[0]) == 0 and args[1] is None and args[2] is None: + # Function with no inputs + self._named_args = None + else: + self._named_args = args[0] + self._id = core._append_python_callable_object_and_return_id(self) + ''' + Why record self here? + + 1. For debug usage. Users can call + :code:`py_func.registered_func(idx)` method + to find the registered function corresponding + to :code:`idx`. + + 2. For increasing reference count of self. + It seems that to release Python object + whose reference count is 1 would cause + segmentation fault error in C++ side. + May be lack of Python GC in C++ side? + ''' + PyFuncRegistry._register_funcs.append(self) + + @classmethod + def registered_func(cls, idx): + return cls._register_funcs[idx]._func + + @classmethod + def registered_func_num(cls): + return len(cls._register_funcs) + + @property + def id(self): + return self._id + + def __call__(self, *args): + if self._named_args is None: + func_ret = self._func() + else: + kwargs = dict() + idx = 0 + for arg in self._named_args: + kwargs[arg] = args[idx] + idx += 1 + func_ret = self._func(*args[idx:], **kwargs) + + if not isinstance(func_ret, (list, tuple)): + func_ret = (func_ret,) + + ret = [] + for each_ret in func_ret: + if each_ret is None or isinstance(each_ret, core.LoDTensor): + ret.append(each_ret) + continue + + if not isinstance(each_ret, np.ndarray): + each_ret = np.array(each_ret) + + tensor = core.LoDTensor() + tensor.set(each_ret, core.CPUPlace()) + ret.append(tensor) + + return tuple(ret) + + +@static_only +@templatedoc() +def py_func(func, x, out, backward_func=None, skip_vars_in_backward_input=None): + """ + :api_attr: Static Graph + + This OP is used to register customized Python OP to Paddle. The design + principe of py_func is that Tensor and numpy array can be converted to each + other easily. So you can use Python and numpy API to register a python OP. + + The forward function of the registered OP is ``func`` and the backward function + of that is ``backward_func``. Paddle will call ``func`` at forward runtime and + call ``backward_func`` at backward runtime(if ``backward_func`` is not None). + ``x`` is the input of ``func``, whose type must be Tensor; ``out`` is + the output of ``func``, whose type can be either Tensor or numpy array. + + The input of the backward function ``backward_func`` is ``x``, ``out`` and + the gradient of ``out``. If ``out`` have no gradient, the relevant input of + ``backward_func`` is None. If ``x`` do not have a gradient, the user should + return None in ``backward_func``. + + The data type and shape of ``out`` should also be set correctly before this + API is called, and the data type and shape of the gradient of ``out`` and + ``x`` will be inferred automatically. + + This API can also be used to debug the neural network by setting the ``func`` + as a function that only print variables. + + Args: + func (callable): The forward function of the registered OP. When the network + is running, the forward output ``out`` will be calculated according to this + function and the forward input ``x``. In ``func`` , it's suggested that we + actively convert Tensor into a numpy array, so that we can use Python and + numpy API arbitrarily. If not, some operations of numpy may not be compatible. + x (Tensor|tuple(Tensor)|list[Tensor]): The input of the forward function ``func``. + It can be Tensor|tuple(Tensor)|list[Tensor]. In addition, Multiple Tensor + should be passed in the form of tuple(Tensor) or list[Tensor]. + out (T|tuple(T)|list[T]): The output of the forward function ``func``, it can be + T|tuple(T)|list[T], where T can be either Tensor or numpy array. Since Paddle + cannot automatically infer the shape and type of ``out``, you must create + ``out`` in advance. + backward_func (callable, optional): The backward function of the registered OP. + Its default value is None, which means there is no reverse calculation. If + it is not None, ``backward_func`` is called to calculate the gradient of + ``x`` when the network is at backward runtime. + skip_vars_in_backward_input (Tensor, optional): It's used to limit the input + list of ``backward_func``, and it can be Tensor|tuple(Tensor)|list[Tensor]. + It must belong to either ``x`` or ``out``. The default value is None, which means + that no tensors need to be removed from ``x`` and ``out``. If it is not None, + these tensors will not be the input of ``backward_func``. This parameter is only + useful when ``backward_func`` is not None. + + Returns: + Tensor|tuple(Tensor)|list[Tensor]: The output ``out`` of the forward function ``func``. + + Examples: + .. code-block:: python + + # example 1: + import paddle + import six + import numpy as np + + paddle.enable_static() + + # Creates a forward function, Tensor can be input directly without + # being converted into numpy array. + def tanh(x): + return np.tanh(x) + + # Skip x in backward function and return the gradient of x + # Tensor must be actively converted to numpy array, otherwise, + # operations such as +/- can't be used. + def tanh_grad(y, dy): + return np.array(dy) * (1 - np.square(np.array(y))) + + # Creates a forward function for debugging running networks(print value) + def debug_func(x): + print(x) + + def create_tmp_var(name, dtype, shape): + return paddle.static.default_main_program().current_block().create_var( + name=name, dtype=dtype, shape=shape) + + def simple_net(img, label): + hidden = img + for idx in six.moves.range(4): + hidden = paddle.static.nn.fc(hidden, size=200) + new_hidden = create_tmp_var(name='hidden_{}'.format(idx), + dtype=hidden.dtype, shape=hidden.shape) + + # User-defined forward and backward + hidden = paddle.static.py_func(func=tanh, x=hidden, + out=new_hidden, backward_func=tanh_grad, + skip_vars_in_backward_input=hidden) + + # User-defined debug functions that print out the input Tensor + paddle.static.py_func(func=debug_func, x=hidden, out=None) + + prediction = paddle.static.nn.fc(hidden, size=10, activation='softmax') + ce_loss = paddle.nn.loss.CrossEntropyLoss() + return ce_loss(prediction, label) + + x = paddle.static.data(name='x', shape=[1,4], dtype='float32') + y = paddle.static.data(name='y', shape=[1,10], dtype='int64') + res = simple_net(x, y) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + input1 = np.random.random(size=[1,4]).astype('float32') + input2 = np.random.randint(1, 10, size=[1,10], dtype='int64') + out = exe.run(paddle.static.default_main_program(), + feed={'x':input1, 'y':input2}, + fetch_list=[res.name]) + print(out) + + .. code-block:: python + + # example 2: + # This example shows how to turn Tensor into numpy array and + # use numpy API to register an Python OP + import paddle + import numpy as np + + paddle.enable_static() + + def element_wise_add(x, y): + # Tensor must be actively converted to numpy array, otherwise, + # numpy.shape can't be used. + x = np.array(x) + y = np.array(y) + + if x.shape != y.shape: + raise AssertionError("the shape of inputs must be the same!") + + result = np.zeros(x.shape, dtype='int32') + for i in range(len(x)): + for j in range(len(x[0])): + result[i][j] = x[i][j] + y[i][j] + + return result + + def create_tmp_var(name, dtype, shape): + return paddle.static.default_main_program().current_block().create_var( + name=name, dtype=dtype, shape=shape) + + def py_func_demo(): + start_program = paddle.static.default_startup_program() + main_program = paddle.static.default_main_program() + + # Input of the forward function + x = paddle.static.data(name='x', shape=[2,3], dtype='int32') + y = paddle.static.data(name='y', shape=[2,3], dtype='int32') + + # Output of the forward function, name/dtype/shape must be specified + output = create_tmp_var('output','int32', [3,1]) + + # Multiple Variable should be passed in the form of tuple(Variale) or list[Variale] + paddle.static.py_func(func=element_wise_add, x=[x,y], out=output) + + exe=paddle.static.Executor(paddle.CPUPlace()) + exe.run(start_program) + + # Feed numpy array to main_program + input1 = np.random.randint(1, 10, size=[2,3], dtype='int32') + input2 = np.random.randint(1, 10, size=[2,3], dtype='int32') + out = exe.run(main_program, + feed={'x':input1, 'y':input2}, + fetch_list=[output.name]) + print("{0} + {1} = {2}".format(input1, input2, out)) + + py_func_demo() + + # Reference output: + # [[5, 9, 9] + [[7, 8, 4] = [array([[12, 17, 13] + # [7, 5, 2]] [1, 3, 3]] [8, 8, 5]], dtype=int32)] + """ + helper = LayerHelper('py_func', **locals()) + check_type(x, 'X', (list, tuple, Variable, type(None)), 'py_func') + if x is None: + x = [] + elif isinstance(x, Variable): + x = [x] + elif isinstance(x, tuple): + x = list(x) + elif not isinstance(x, (list, tuple, Variable)): + raise TypeError('Input must be Variable/list(Variable)/tuple(Variable)') + check_type(out, 'Out', (list, tuple, Variable, type(None)), 'py_func') + if out is None: + out_list = [] + elif isinstance(out, Variable): + out_list = [out] + elif isinstance(out, tuple): + out_list = list(out) + elif isinstance(out, list): + out_list = out + else: + raise TypeError( + 'Output must be Variable/list(Variable)/tuple(Variable)' + ) + + fwd_func_id = PyFuncRegistry(func).id + bwd_func_id = ( + PyFuncRegistry(backward_func).id if backward_func is not None else -1 + ) + + for each_out in out_list: + if len(each_out.shape) == 0: + raise ValueError( + 'Output shapes of py_func op should be provided by users manually' + ) + + backward_skip_vars = set() + if backward_func is not None and skip_vars_in_backward_input is not None: + if isinstance(skip_vars_in_backward_input, Variable): + skip_vars_in_backward_input = [skip_vars_in_backward_input] + + fwd_in_out = [v.name for v in x] + fwd_in_out.extend([v.name for v in out_list]) + fwd_in_out = set(fwd_in_out) + backward_skip_vars = set() + for v in skip_vars_in_backward_input: + if not v.name in fwd_in_out: + raise ValueError( + 'Variable {} is not found in forward inputs and outputs'.format( + v.name + ) + ) + backward_skip_vars.add(v.name) + + helper.append_op( + type='py_func', + inputs={'X': x}, + outputs={'Out': out_list}, + attrs={ + 'forward_callable_id': fwd_func_id, + 'backward_callable_id': bwd_func_id, + 'backward_skip_vars': list(backward_skip_vars), + }, + ) + return out + + +# For debug usage +py_func.registered_func = PyFuncRegistry.registered_func +py_func.registered_func_num = PyFuncRegistry.registered_func_num + + +@templatedoc() +def psroi_pool( + input, + rois, + output_channels, + spatial_scale, + pooled_height, + pooled_width, + name=None, +): + """ + + ${comment} + + Parameters: + input (Variable): ${x_comment} + rois (Variable): LoDTensor, ROIs (Regions of Interest) to pool over.It should be + a 2-D LoDTensor of shape (num_rois, 4), the lod level + is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is + the top left coordinates, and (x2, y2) is the bottom + right coordinates. The data type is the same as `input` + output_channels (int): ${output_channels_comment} + spatial_scale (float): ${spatial_scale_comment} Default: 1.0 + pooled_height (int): ${pooled_height_comment} Default: 1 + pooled_width (int): ${pooled_width_comment} Default: 1 + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + ${out_comment}. + + Return Type: + Variable + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + x = fluid.data(name='x', shape=[100, 490, 28, 28], dtype='float32') + rois = fluid.data(name='rois', shape=[None, 4], lod_level=1, dtype='float32') + pool_out = fluid.layers.psroi_pool(x, rois, 10, 1.0, 7, 7) + """ + helper = LayerHelper('psroi_pool', **locals()) + # check attrs + if not isinstance(output_channels, int): + raise TypeError("output_channels must be int type") + if not isinstance(spatial_scale, float): + raise TypeError("spatial_scale must be float type") + if not isinstance(pooled_height, int): + raise TypeError("pooled_height must be int type") + if not isinstance(pooled_width, int): + raise TypeError("pooled_width must be int type") + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='psroi_pool', + inputs={'X': input, 'ROIs': rois}, + outputs={'Out': out}, + attrs={ + 'output_channels': output_channels, + 'spatial_scale': spatial_scale, + 'pooled_height': pooled_height, + 'pooled_width': pooled_width, + }, + ) + return out + + +@templatedoc() +def prroi_pool( + input, + rois, + spatial_scale=1.0, + pooled_height=1, + pooled_width=1, + batch_roi_nums=None, + name=None, +): + """ + + The precise roi pooling implementation for paddle. Reference: https://arxiv.org/pdf/1807.11590.pdf + + Args: + input (Variable):The input of precise roi pooliing.The shape of input tensor is + [N,C,H,W]. Where N is batch size,C is number of input channels,H + is height of the feature, and W is the width of the feature. + rois (Variable): ROIs (Regions of Interest) to pool over.It should be + a 2-D LoDTensor or Tensor of shape (num_rois, 4), the lod level + is 1 when it is LoDTensor. The LoD include the rois's batch index + information. If rois is Tensor, its batch index information should + be provided by batch_index. + Given as [[x1, y1, x2, y2], ...], (x1, y1) is + the top left coordinates, and (x2, y2) is the bottom + right coordinates. + spatial_scale (float): Ratio of input feature map height (or width) to raw image height (or width). + Equals the reciprocal of total stride in convolutional layers, Default: 1.0. + pooled_height (integer): The pooled output height. Default: 1. + pooled_width (integer): The pooled output width. Default: 1. + batch_roi_nums (Variable): The number of roi for each image in batch. It + should be 1-D Tensor, with shape [N] and dtype int64, + where N is the batch size. Default: None. Be note: The lod of input should be + empty when batch_roi_nums has values; + name (str, default None): The name of this operation. + + Returns: + Variable(Tensor):The shape of the returned Tensor is (N, C, pooled_height, pooled_width), with value type float32,float16. N, C denote batch_size and channels of input respectively. + + Examples: + .. code-block:: python + + ## prroi_pool without batch_roi_num + import paddle.fluid as fluid + x = fluid.data(name='x', shape=[None, 490, 28, 28], dtype='float32') + rois = fluid.data(name='rois', shape=[None, 4], lod_level=1, dtype='float32') + pool_out = fluid.layers.prroi_pool(x, rois, 1.0, 7, 7) + + ## prroi_pool with batch_roi_num + batchsize=4 + x2 = fluid.data(name='x2', shape=[batchsize, 490, 28, 28], dtype='float32') + rois2 = fluid.data(name='rois2', shape=[batchsize, 4], dtype='float32') + batch_rois_num = fluid.data(name='rois_nums', shape=[batchsize], dtype='int64') + pool_out2 = fluid.layers.prroi_pool(x2, rois2, 1.0, 7, 7, batch_roi_nums=batch_rois_num) + + + """ + check_variable_and_dtype(input, 'input', ['float32'], 'prroi_pool') + check_variable_and_dtype(rois, 'rois', ['float32'], 'prroi_pool') + helper = LayerHelper('prroi_pool', **locals()) + # check attrs + if not isinstance(spatial_scale, float): + raise TypeError("spatial_scale must be float type") + if not isinstance(pooled_height, int): + raise TypeError("pooled_height must be int type") + if not isinstance(pooled_width, int): + raise TypeError("pooled_width must be int type") + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + inputs_op = {'X': input, 'ROIs': rois} + if batch_roi_nums is not None: + inputs_op['BatchRoINums'] = batch_roi_nums + helper.append_op( + type='prroi_pool', + inputs=inputs_op, + outputs={'Out': out}, + attrs={ + 'spatial_scale': spatial_scale, + 'pooled_height': pooled_height, + 'pooled_width': pooled_width, + }, + ) + return out + + +def pixel_shuffle(x, upscale_factor): + """ + + This op rearranges elements in a tensor of shape [N, C, H, W] + to a tensor of shape [N, C/r**2, H*r, W*r]. + This is useful for implementing efficient sub-pixel convolution + with a stride of 1/r. + Please refer to the paper: `Real-Time Single Image and Video Super-Resolution + Using an Efficient Sub-Pixel Convolutional Neural Network `_ . + by Shi et. al (2016) for more details. + + Parameters: + + x(Variable): 4-D tensor, the data type should be float32 or float64. + upscale_factor(int): factor to increase spatial resolution. + + Returns: + Out(Variable): Reshaped tensor according to the new dimension. + + Raises: + ValueError: If the square of upscale_factor cannot divide the channels of input. + + Examples: + .. code-block:: python + + # declarative mode + import paddle.fluid as fluid + import numpy as np + input = fluid.data(name="input", shape=[2,9,4,4]) + output = fluid.layers.pixel_shuffle(x=input, upscale_factor=3) + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + input_data = np.random.rand(2,9,4,4).astype("float32") + output_data = exe.run(fluid.default_main_program(), + feed={"input":input_data}, + fetch_list=[output], + return_numpy=True) + + # print(output.shape) + # (2L, 1L, 12L, 12L) + + """ + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_shuffle') + helper = LayerHelper("pixel_shuffle", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if not isinstance(upscale_factor, int): + raise TypeError("upscale factor must be int type") + + helper.append_op( + type="pixel_shuffle", + inputs={"X": x}, + outputs={"Out": out}, + attrs={"upscale_factor": upscale_factor}, + ) + return out + + +def fsp_matrix(x, y): + """ + + **FSP matrix op** + + This op is used to calculate the flow of solution procedure (FSP) matrix of two 4-D Tensor feature maps. + Given feature map x with shape [x_channel, h, w] and feature map y with shape + [y_channel, h, w], we can get the fsp matrix of x and y in two steps: + + 1. reshape x into matrix with shape [x_channel, h * w] and reshape and + transpose y into matrix with shape [h * w, y_channel]. + 2. multiply x and y to get fsp matrix with shape [x_channel, y_channel]. + + The output is a batch of fsp matrices. + + Args: + + x (Variable): A 4-D Tensor feature map with shape [batch_size, x_channel, height, width]. + A Tensor with type float32, float64. + y (Variable): A 4-D Tensor feature map with shape [batch_size, y_channel, height, width]. + The y_channel can be different with the x_channel of Input(X) + while the other dimensions must be the same with Input(X)'s. A Tensor with + type float32, float64. + + Returns: + + fsp matrix (Variable): The output of FSP op with shape [batch_size, x_channel, y_channel]. + The x_channel is the channel of x and the y_channel is the channel of y. A Tensor with + type float32, float64. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.data(name='data', shape=[None, 3, 32, 32]) + feature_map_0 = fluid.layers.conv2d(data, num_filters=2, + filter_size=3) + feature_map_1 = fluid.layers.conv2d(feature_map_0, num_filters=2, + filter_size=1) + loss = fluid.layers.fsp_matrix(feature_map_0, feature_map_1) + + """ + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'fsp_matrix') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'fsp_matrix') + helper = LayerHelper('fsp_matrix', **locals()) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype(input_param_name='x') + ) + helper.append_op(type='fsp', inputs={'X': x, 'Y': y}, outputs={'Out': out}) + return out + + +def continuous_value_model(input, cvm, use_cvm=True): + r""" + + **continuous_value_model layers** + + Now, this OP is used in CTR project to remove or dispose show and click value in :attr:`input`. + + :attr:`input` is an embedding vector including show and click value, whose shape is :math:`[N, D]` (N is batch size. D is `2 + embedding dim` ). + Show and click at first two dims of embedding vector D. + If :attr:`use_cvm` is True, it will calculate :math:`log(show)` and :math:`log(click)` , and output shape is :math:`[N, D]` . + If :attr:`use_cvm` is False, it will remove show and click from :attr:`input` , and output shape is :math:`[N, D - 2]` . + :attr:`cvm` is show_click info, whose shape is :math:`[N, 2]` . + + Args: + input (Variable): The input variable. A 2-D LoDTensor with shape :math:`[N, D]` , where N is the batch size, D is `2 + the embedding dim` . `lod level = 1` . + A Tensor with type float32, float64. + cvm (Variable): Show and click variable. A 2-D Tensor with shape :math:`[N, 2]` , where N is the batch size, 2 is show and click. + A Tensor with type float32, float64. + use_cvm (bool): Use show_click or not. if use, the output dim is the same as input. + if not use, the output dim is `input dim - 2` (remove show and click) + + Returns: + + Variable: A 2-D LodTensor with shape :math:`[N, M]` . if :attr:`use_cvm` = True, M is equal to input dim D. if False, M is equal to `D - 2`. \ + A Tensor with same type as input. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + input = fluid.data(name="input", shape=[64, 1], dtype="int64") + label = fluid.data(name="label", shape=[64, 1], dtype="int64") + embed = fluid.layers.embedding( + input=input, + size=[100, 11], + dtype='float32') + ones = fluid.layers.fill_constant_batch_size_like(input=label, shape=[-1, 1], dtype="int64", value=1) + show_clk = fluid.layers.cast(fluid.layers.concat([ones, label], axis=1), dtype='float32') + show_clk.stop_gradient = True + input_with_cvm = fluid.layers.continuous_value_model(embed, show_clk, True) + + """ + helper = LayerHelper('cvm', **locals()) + out = helper.create_variable(dtype=input.dtype) + check_variable_and_dtype( + input, 'input', ['float16', 'float32', 'float64'], 'cvm' + ) + helper.append_op( + type='cvm', + inputs={'X': [input], 'CVM': [cvm]}, + outputs={'Y': [out]}, + attrs={"use_cvm": use_cvm}, + ) + return out + + +def where(condition): + """ + Return an int64 tensor with rank 2, specifying the coordinate of true element in `condition`. + + Args: + condition(Variable): A bool tensor with rank at least 1, the data type is bool. + + Returns: + Variable, the output data type is int64. : The tensor variable storing a 2-D tensor, which involves all coordinate. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + import numpy as np + + # condition is a tensor [True, False, True] + condition = layers.assign(np.array([1, 0, 1], dtype='int32')) + condition = layers.cast(condition, 'bool') + out = layers.where(condition) # [[0], [2]] + + # condition is a tensor [[True, False], [False, True]] + condition = layers.assign(np.array([[1, 0], [0, 1]], dtype='int32')) + condition = layers.cast(condition, 'bool') + out = layers.where(condition) # [[0, 0], [1, 1]] + + # condition is a tensor [False, False, False] + condition = layers.assign(np.array([0, 0, 0], dtype='int32')) + condition = layers.cast(condition, 'bool') + out = layers.where(condition) # [[]] + + """ + + if in_dygraph_mode(): + return _C_ops.where_index(condition) + if _in_legacy_dygraph(): + return _legacy_C_ops.where_index(condition) + + helper = LayerHelper("where_index", **locals()) + + out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.INT64 + ) + + helper.append_op( + type='where_index', + inputs={'Condition': condition}, + outputs={'Out': [out]}, + ) + return out + + +@deprecated(since="2.0.0", update_to="paddle.sign") +def sign(x): + r""" + This OP returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero. + + Args: + x(Variable|numpy.ndarray): The input variable could be N-D tensor or N-D numpy array, \ + the input data type is float32 or float64. + + Returns: + Variable, the output data type is the same as input data type. : The output sign tensor with identical shape to input :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + # [1.0, 0.0, -1.0] + data = fluid.layers.sign(np.array([3.0, 0.0, -2.0], dtype='float32')) + """ + + helper = LayerHelper("sign", **locals()) + check_type(x, 'x', (Variable, np.ndarray), 'sign') + if isinstance(x, np.ndarray): + x = assign(x) + check_dtype(x.dtype, 'x', ['float16', 'float32', 'float64'], 'sign') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type='sign', inputs={'X': [x]}, outputs={'Out': [out]}) + + return out + + +def unique(x, dtype='int32'): + r""" + Return a unique tensor for `x` and an index tensor pointing to this unique tensor. + + Args: + x(Tensor): A 1-D input tensor, it's data type should be float32, float64, int32, int64. + dtype(np.dtype|str, optional): The type of index tensor: int32, int64. Default: int32. + + Returns: + tuple: (out, index). `out` is the unique tensor for `x`, with identical dtype to `x`, and \ + `index` is an index tensor pointing to `out`, by which user can recover the original `x` tensor. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + x = fluid.layers.assign(np.array([2, 3, 3, 1, 5, 3], dtype='int32')) + out, index = fluid.layers.unique(x) # out is [2, 3, 1, 5]; index is [0, 1, 1, 2, 3, 1] + """ + + check_variable_and_dtype( + x, "x", ['float32', 'float64', 'int32', 'int64'], "unique" + ) + helper = LayerHelper("unique", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + index = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type='unique', + inputs={'X': x}, + attrs={'dtype': convert_np_dtype_to_dtype_(dtype)}, + outputs={'Out': [out], 'Index': [index]}, + ) + + return out, index + + +def unique_with_counts(x, dtype='int32'): + r""" + This OP return a unique tensor for `x` , and count tensor that the count of unique result in raw input, \ + and an index tensor pointing to this unique tensor. + + **NOTICE**: This op support the variable type of Tensor only. + + Args: + x(Variable): A 1-D input tensor with input shape of :math:`[N]` , the input data type is float32, float64, int32, int64. + dtype(np.dtype|core.VarDesc.VarType|str): The type of count and index tensor, it could be int32, int64. Default value is int32. + + Returns: + tuple, the variable type in tuple is Tensor, the output :attr:`out` data type is the same as input :attr:`x`, \ + and data type of output :attr:`index` and :attr:`count` will be int32 or int64.: The :attr:`out` is unique tensor for input :attr:`x`,\ + the data shape is :math:`[K]`, the `K` may be different to the `N` in shape of :attr:`x`. :attr:`index` is an index tensor pointing\ + to :attr:`out`, the data shape is :math:`[N]` , the data shape is the same as input :attr:`x`. :attr:`count` is count of unique element in\ + the :attr:`x`, the data shape is :math:`[K]`, the data shape is the same as output :attr:`out`. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + x = fluid.layers.assign(np.array([2, 3, 3, 1, 5, 3], dtype='int32')) + out, index, count = fluid.layers.unique_with_counts(x) # out is [2, 3, 1, 5]; index is [0, 1, 1, 2, 3, 1] + # count is [1, 3, 1, 1] + # x.shape=(6,) out.shape=(4,), index.shape=(6,), count.shape=(4,) + """ + check_variable_and_dtype( + x, "x", ['float32', 'float64', 'int32', 'int64'], "unique_with_counts" + ) + if not (dtype == 'int32' or dtype == 'int64'): + raise TypeError( + "Op unique_with_counts, index dtype must be int32 or int64" + ) + + if x is None or len(x.shape) != 1: + raise ValueError( + "Op unique_with_counts, x must not be null and size of dim must be 1" + ) + + helper = LayerHelper("unique_with_counts", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + index = helper.create_variable_for_type_inference(dtype) + + count = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type='unique_with_counts', + inputs={'X': x}, + attrs={'dtype': convert_np_dtype_to_dtype_(dtype)}, + outputs={'Out': [out], 'Index': [index], 'Count': [count]}, + ) + + return out, index, count + + +def deformable_conv( + input, + offset, + mask, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=None, + deformable_groups=None, + im2col_step=None, + param_attr=None, + bias_attr=None, + modulated=True, + name=None, +): + r""" + :api_attr: Static Graph + + **Deformable Convolution op** + + Compute 2-D deformable convolution on 4-D input. + Given input image x, output feature map y, the deformable convolution operation can be expressed as follow: + + + Deformable Convolution v2: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k} + + Deformable Convolution v1: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)} + + Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location, + Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results + `_ and `Deformable Convolutional Networks `_. + + Example: + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + Offset shape: :math:`(N, 2 * deformable\_groups * H_f * H_w, H_{in}, W_{in})` + + Mask shape: :math:`(N, deformable\_groups * H_f * H_w, H_{in}, W_{in})` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Args: + input (Variable): The input image with [N, C, H, W] format. A Tensor with type + float32, float64. + offset (Variable): The input coordinate offset of deformable convolution layer. + A Tensor with type float32, float64. + Mask (Variable, Optional): The input mask of deformable convolution layer. + A Tensor with type float32, float64. It should be None when you use + deformable convolution v1. + num_filters(int): The number of filter. It is as same as the output + image channel. + filter_size (int|tuple): The filter size. If filter_size is a tuple, + it must contain two integers, (filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + stride (int|tuple): The stride size. If stride is a tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: stride = 1. + padding (int|tuple): The padding size. If padding is a tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: padding = 0. + dilation (int|tuple): The dilation size. If dilation is a tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: dilation = 1. + groups (int): The groups number of the deformable conv layer. According to + grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + deformable_groups (int): The number of deformable group partitions. + Default: deformable_groups = 1. + im2col_step (int): Maximum number of images per im2col computation; + The total batch size should be devisable by this value or smaller + than this value; if you face out of memory problem, you can try + to use a smaller value here. + Default: im2col_step = 64. + param_attr (ParamAttr, Optional): The parameter attribute for learnable parameters/weights + of deformable conv. If it is set to None or one attribute of ParamAttr, + deformable conv will create ParamAttr as param_attr. + If the Initializer of the param_attr is not set, the parameter is + initialized with :math:`Normal(0.0, std)`, and the + :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr|bool, Optional): The parameter attribute for the bias of + deformable conv layer. If it is set to False, no bias will be added + to the output units. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + modulated (bool): Make sure which version should be used between v1 and v2, where v2 is \ + used while True. Default: True. + name(str, Optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + Returns: + Variable: The tensor variable storing the deformable convolution \ + result. A Tensor with type float32, float64. + Raises: + ValueError: If the shapes of input, filter_size, stride, padding and + groups mismatch. + Examples: + .. code-block:: python + + #deformable conv v2: + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + C_in, H_in, W_in = 3, 32, 32 + filter_size, deformable_groups = 3, 1 + data = fluid.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') + offset = fluid.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + mask = fluid.data(name='mask', shape=[None, deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + out = fluid.layers.deformable_conv(input=data, offset=offset, mask=mask, + num_filters=2, filter_size=filter_size, padding=1, modulated=True) + + #deformable conv v1: + + import paddle.fluid as fluid + C_in, H_in, W_in = 3, 32, 32 + filter_size, deformable_groups = 3, 1 + data = fluid.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') + offset = fluid.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + out = fluid.layers.deformable_conv(input=data, offset=offset, mask=None, + num_filters=2, filter_size=filter_size, padding=1, modulated=False) + """ + + check_variable_and_dtype( + input, "input", ['float32', 'float64'], 'deformable_conv' + ) + check_variable_and_dtype( + offset, "offset", ['float32', 'float64'], 'deformable_conv' + ) + check_type(mask, 'mask', (Variable, type(None)), 'deformable_conv') + + num_channels = input.shape[1] + assert param_attr is not False, "param_attr should not be False here." + + helper = LayerHelper('deformable_conv', **locals()) + dtype = helper.input_dtype() + + if not isinstance(input, Variable): + raise TypeError("Input of deformable_conv must be Variable") + if not isinstance(offset, Variable): + raise TypeError("Input Offset of deformable_conv must be Variable") + + if groups is None: + num_filter_channels = num_channels + else: + if num_channels % groups != 0: + raise ValueError("num_channels must be divisible by groups.") + num_filter_channels = num_channels // groups + + filter_size = utils.convert_to_list(filter_size, 2, 'filter_size') + stride = utils.convert_to_list(stride, 2, 'stride') + padding = utils.convert_to_list(padding, 2, 'padding') + dilation = utils.convert_to_list(dilation, 2, 'dilation') + + input_shape = input.shape + filter_shape = [num_filters, int(num_filter_channels)] + filter_size + + def _get_default_param_initializer(): + filter_elem_num = filter_size[0] * filter_size[1] * num_channels + if filter_elem_num <= 0: + raise ValueError( + "Invalid filter number, excepted number is larger than 0, but" + " received {}, please check the input shape and " + "filter size.".format(filter_elem_num) + ) + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std, 0) + + filter_param = helper.create_parameter( + attr=helper.param_attr, + shape=filter_shape, + dtype=dtype, + default_initializer=_get_default_param_initializer(), + ) + + pre_bias = helper.create_variable_for_type_inference(dtype) + + if modulated: + helper.append_op( + type='deformable_conv', + inputs={ + 'Input': input, + 'Filter': filter_param, + 'Offset': offset, + 'Mask': mask, + }, + outputs={"Output": pre_bias}, + attrs={ + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'deformable_groups': deformable_groups, + 'im2col_step': im2col_step, + }, + ) + + else: + helper.append_op( + type='deformable_conv_v1', + inputs={ + 'Input': input, + 'Filter': filter_param, + 'Offset': offset, + }, + outputs={"Output": pre_bias}, + attrs={ + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'deformable_groups': deformable_groups, + 'im2col_step': im2col_step, + }, + ) + + output = helper.append_bias_op(pre_bias, dim_start=1, dim_end=2) + return output + + +def unfold(x, kernel_sizes, strides=1, paddings=0, dilations=1, name=None): + r""" + + This op returns a col buffer of sliding local blocks of input x, also known + as im2col for batched 2D image tensors. For each block under the convolution filter, + all element will be rearranged as a column. While the convolution filter sliding over + the input feature map, a series of such columns will be formed. + + For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout] + can be calculated as following. + + .. math:: + + dkernel[0] &= dilations[0] \times (kernel\_sizes[0] - 1) + 1 + + dkernel[1] &= dilations[1] \times (kernel\_sizes[1] - 1) + 1 + + hout &= \frac{H + paddings[0] + paddings[2] - dkernel[0]}{strides[0]} + 1 + + wout &= \frac{W + paddings[1] + paddings[3] - dkernel[1]}{strides[1]} + 1 + + Cout &= C \times kernel\_sizes[0] \times kernel\_sizes[1] + + Lout &= hout \times wout + + + Parameters: + x(Tensor): 4-D Tensor, input tensor of format [N, C, H, W], + data type can be float32 or float64 + kernel_sizes(int|list): The size of convolution kernel, should be [k_h, k_w] + or an integer k treated as [k, k]. + strides(int|list): The strides, should be [stride_h, stride_w] + or an integer stride treated as [sride, stride]. + For default, strides will be [1, 1]. + paddings(int|list): The paddings of each dimension, should be + [padding_top, padding_left, padding_bottom, padding_right] + or [padding_h, padding_w] or an integer padding. + If [padding_h, padding_w] was given, it will expanded to + [padding_h, padding_w, padding_h, padding_w]. If an integer + padding was given, [padding, padding, padding, padding] will + be used. For default, paddings will be [0, 0, 0, 0] + dilations(int|list): the dilations of convolution kernel, should be + [dilation_h, dilation_w], or an integer dilation treated as + [dilation, dilation]. For default, it will be [1, 1]. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + + Returns: + The tensor corresponding to the sliding local blocks. + The output shape is [N, Cout, Lout] as decriabled above. + Cout is the total number of values within each block, + and Lout is the total number of such blocks. + The data type of output is the same as the input :math:`x` + + Return Type: + Tensor + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn((100,3,224,224)) + y = F.unfold(x, [3, 3], 1, 1, 1) + """ + + return paddle.nn.functional.unfold( + x, kernel_sizes, strides, paddings, dilations, name + ) + + +def deformable_roi_pooling( + input, + rois, + trans, + no_trans=False, + spatial_scale=1.0, + group_size=[1, 1], + pooled_height=1, + pooled_width=1, + part_size=None, + sample_per_part=1, + trans_std=0.1, + position_sensitive=False, + name=None, +): + r""" + + Deformable ROI Pooling Layer + + Performs deformable region-of-interest pooling on inputs. As described + in `Deformable Convolutional Networks `_, it will get offset for each bin after + roi pooling so that pooling at correct region. Batch_size will change to the number of region bounding boxes after deformable_roi_pooling. + + The operation has three steps: + + 1. Dividing each region proposal into equal-sized sections with the pooled_width and pooled_height. + + 2. Add offset to pixel in ROI to get new location and the new value which are computed directly through + bilinear interpolation with four nearest pixel. + + 3. Sample several points in each bin to get average values as output. + + + Args: + input (Variable):The input of deformable roi pooling and it is tensor which value type is float32. The shape of input is + [N, C, H, W]. Where N is batch size, C is number of input channels, + H is height of the feature, and W is the width of the feature. + rois (Variable): ROIs (Regions of Interest) with type float32 to pool over. It should be + a 2-D LoDTensor of shape (num_rois, 4), and the lod level + is 1. Given as [[x1, y1, x2, y2], ...], (x1, y1) is + the top left coordinates, and (x2, y2) is the bottom + right coordinates, which value type is float32. + trans (Variable): Offset of features on ROIs while pooling which value type is float32. The format is [N, C, H, W], where + N is number of ROIs, C is number of channels, which indicate the offset distance + in the x and y directions, H is pooled height, and W is pooled width. + no_trans (bool): Whether to add offset to get new value or not while roi pooling, which value with type bool is True or False. + If value is True, no offset will be added in operation. Default: False. + spatial_scale (float): Ratio of input feature map height (or width) to raw image height (or width), which value type is float32. + Equals the reciprocal of total stride in convolutional layers, Default: 1.0. + group_size (list|tuple): The number of groups which input channels are divided and the input is list or tuple, which value type is int32. (eg.number of input channels + is k1 * k2 * (C + 1), which k1 and k2 are group width and height and C+1 is number of output + channels.) eg.(4, 6), which 4 is height of group and 6 is width of group. Default: [1, 1]. + pooled_height (int): The pooled output height which value type is int32. Default: 1. + pooled_width (int): The pooled output width which value type is int32. Default: 1. + part_size (list|tuple): The height and width of offset which values in list or tuple is int32, eg.(4, 6), which height is 4 and width is 6, and values always equal to pooled_height \ + and pooled_width. Default: if None, default value is [pooled_height, pooled_width]. + sample_per_part (int): The number of samples in each bin which value type is int32. If value is bigger, it will consume more performance. Default: 1. + trans_std (float): Coefficient of offset which value type is float32. It controls weight of offset. Default: 0.1. + position_sensitive (bool): Whether to choose deformable psroi pooling mode or not, and value type is bool(True or False). If value is False, input dimension equals to output dimension. \ + If value is True, input dimension should be output dimension * pooled_height * pooled_width. Default: False. + name (str|None): Name of layer. Default: None. + Returns: + Variable: Output of deformable roi pooling is that, if position sensitive is False, input dimension equals to output dimension. If position sensitive is True,\ + input dimension should be the result of output dimension divided by pooled height and pooled width. + + Examples: + .. code-block:: python + + # position_sensitive=True + import paddle.fluid as fluid + input = fluid.data(name="input", + shape=[2, 192, 64, 64], + dtype='float32') + rois = fluid.data(name="rois", + shape=[-1, 4], + dtype='float32', + lod_level=1) + trans = fluid.data(name="trans", + shape=[2, 384, 64, 64], + dtype='float32') + x = fluid.layers.deformable_roi_pooling(input=input, + rois=rois, + trans=trans, + no_trans=False, + spatial_scale=1.0, + group_size=(1, 1), + pooled_height=8, + pooled_width=8, + part_size=(8, 8), + sample_per_part=4, + trans_std=0.1, + position_sensitive=True) + + # position_sensitive=False + import paddle.fluid as fluid + input = fluid.data(name="input", + shape=[2, 192, 64, 64], + dtype='float32') + rois = fluid.data(name="rois", + shape=[-1, 4], + dtype='float32', + lod_level=1) + trans = fluid.data(name="trans", + shape=[2, 384, 64, 64], + dtype='float32') + x = fluid.layers.deformable_roi_pooling(input=input, + rois=rois, + trans=trans, + no_trans=False, + spatial_scale=1.0, + group_size=(1, 1), + pooled_height=8, + pooled_width=8, + part_size=(8, 8), + sample_per_part=4, + trans_std=0.1, + position_sensitive=False) + """ + + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'deformable_roi_pooling' + ) + check_variable_and_dtype( + rois, 'rois', ['float32', 'float64'], 'deformable_roi_pooling' + ) + check_variable_and_dtype( + trans, 'trans', ['float32', 'float64'], 'deformable_roi_pooling' + ) + check_type( + group_size, 'group_size', (list, tuple), 'deformable_roi_pooling' + ) + if part_size is not None: + check_type( + part_size, 'part_size', (list, tuple), 'deformable_roi_pooling' + ) + + input_channels = input.shape[1] + if position_sensitive == False: + output_channels = input_channels + else: + output_channels = input_channels / pooled_height / pooled_width + + if part_size is None: + part_height = pooled_height + part_width = pooled_width + part_size = [part_height, part_width] + part_size = utils.convert_to_list(part_size, 2, 'part_size') + group_size = utils.convert_to_list(group_size, 2, 'group_size') + helper = LayerHelper('deformable_psroi_pooling', **locals()) + dtype = helper.input_dtype() + output = helper.create_variable_for_type_inference(dtype) + top_count = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op( + type="deformable_psroi_pooling", + inputs={"Input": input, "ROIs": rois, "Trans": trans}, + outputs={"Output": output, "TopCount": top_count}, + attrs={ + "no_trans": no_trans, + "spatial_scale": spatial_scale, + "output_dim": output_channels, + "group_size": group_size, + "pooled_height": pooled_height, + "pooled_width": pooled_width, + "part_size": part_size, + "sample_per_part": sample_per_part, + "trans_std": trans_std, + }, + ) + return output + + +@deprecated(since="2.0.0", update_to="paddle.shard_index") +def shard_index(input, index_num, nshards, shard_id, ignore_value=-1): + """ + Reset the values of `input` according to the shard it beloning to. + Every value in `input` must be a non-negative integer, and + the parameter `index_num` represents the integer above the maximum + value of `input`. Thus, all values in `input` must be in the range + [0, index_num) and each value can be regarded as the offset to the beginning + of the range. The range is further split into multiple shards. Specifically, + we first compute the `shard_size` according to the following formula, + which represents the number of integers each shard can hold. So for the + i'th shard, it can hold values in the range [i*shard_size, (i+1)*shard_size). + :: + + shard_size = (index_num + nshards - 1) // nshards + + For each value `v` in `input`, we reset it to a new value according to the + following formula: + :: + + v = v - shard_id * shard_size if shard_id * shard_size <= v < (shard_id+1) * shard_size else ignore_value + + That is, the value `v` is set to the new offset within the range represented by the shard `shard_id` + if it in the range. Otherwise, we reset it to be `ignore_value`. + + Args: + input (Tensor): Input tensor with data type int64 or int32. It's last dimension must be 1. + index_num (int): An integer represents the integer above the maximum value of `input`. + nshards (int): The number of shards. + shard_id (int): The index of the current shard. + ignore_value (int): An integer value out of sharded index range. + + Returns: + Tensor. + + Examples: + .. code-block:: python + + import paddle + label = paddle.to_tensor([[16], [1]], "int64") + shard_label = paddle.shard_index(input=label, + index_num=20, + nshards=2, + shard_id=0) + print(shard_label) + # [[-1], [1]] + """ + if in_dygraph_mode(): + return _C_ops.shard_index( + input, index_num, nshards, shard_id, ignore_value + ) + + check_variable_and_dtype(input, 'input', ['int64', 'int32'], 'shard_index') + op_type = 'shard_index' + helper = LayerHelper(op_type, **locals()) + if shard_id < 0 or shard_id >= nshards: + raise ValueError( + 'The shard_id(%d) should be in [0, %d)' % (shard_id, nshards) + ) + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type=op_type, + inputs={'X': [input]}, + outputs={'Out': out}, + attrs={ + 'index_num': index_num, + 'nshards': nshards, + 'shard_id': shard_id, + 'ignore_value': ignore_value, + }, + stop_gradient=True, + ) + return out + + +@templatedoc() +def hard_swish(x, threshold=6.0, scale=6.0, offset=3.0, name=None): + r""" + This operator implements the hard_swish activation function. + Hard_swish is proposed in MobileNetV3, and performs better in computational stability and efficiency compared to swish function. + For more details please refer to: https://arxiv.org/pdf/1905.02244.pdf + + The formula is as follows: + + .. math:: + + out = \\frac{x * (min(max(0, x+offset), threshold))}{scale} + + In the above equation: + + ``threshold`` and ``scale`` should be positive, ``offset`` can be positive or negative. It is recommended to use default parameters. + + Args: + x (Variable): Input feature, multi-dimensional Tensor. The data type should be float32 or float64. + threshold (float, optional): The threshold in Relu function. Default: 6.0 + scale (float, optional): The scale factor. Default: 6.0 + offset (float, optional): The offset factor. Default: 3.0 + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: The output tensor with the same shape and data type as input. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle + import numpy as np + paddle.enable_static() + + DATATYPE='float32' + + x_data = np.array([i for i in range(1,5)]).reshape([1,1,4]).astype(DATATYPE) + + x = fluid.data(name="x", shape=[None,1,4], dtype=DATATYPE) + y = fluid.layers.hard_swish(x) + + place = fluid.CPUPlace() + #place = fluid.CUDAPlace(0) + exe = fluid.Executor(place) + out, = exe.run(feed={'x':x_data}, fetch_list=[y.name]) + print(out) # [[0.66666667, 1.66666667,3., 4.]] + """ + if _non_static_mode(): + return _legacy_C_ops.hard_swish( + x, 'threshold', threshold, 'scale', scale, 'offset', offset + ) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hard_swish' + ) + + helper = LayerHelper('hard_swish', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='hard_swish', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold, 'scale': scale, 'offset': offset}, + ) + return out + + +@templatedoc() +def mish(x, threshold=20, name=None): + r""" + This operator implements the mish activation function. + Refer to `Mish: A Self Regularized Non-Monotonic Neural + Activation Function `_ + + + The formula is as follows if :attr:`threshold` is :code:`None` or negative: + + .. math:: + + out = x * \\tanh(\\ln(1 + e^{x})) + + The formula is as follows if :attr:`threshold` is set as positive value: + + .. math:: + + out = \\begin{cases} + x \\ast \\tanh(x), \\text{if } x > \\text{threshold} \\\\ + x \\ast \\tanh(e^{x}), \\text{if } x < -\\text{threshold} \\\\ + x \\ast \\tanh(\\ln(1 + e^{x})), \\text{otherwise} + \\end{cases} + + Args: + x (Variable): Input feature, multi-dimensional Tensor. The data type + should be float16, float32 or float64. + threshold (float|None): threshold for softplus in Mish operator. + Approximate value of softplus will be used if absolute value + of input is greater than :attr:threshold and :attr:threshold + is set as positive value. For none or negative threshold, + approximate value is not used. Default 20. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name` + + Returns: + Variable: The output tensor with the same shape and data type as input. + + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + DATATYPE='float32' + + x_data = np.array([i for i in range(1,5)]).reshape([1,1,4]).astype(DATATYPE) + + x = fluid.data(name="x", shape=[None,1,4], dtype=DATATYPE) + y = fluid.layers.mish(x) + + place = fluid.CPUPlace() + # place = fluid.CUDAPlace(0) + exe = fluid.Executor(place) + out, = exe.run(feed={'x':x_data}, fetch_list=[y.name]) + print(out) # [[0.66666667, 1.66666667, 3., 4.]] + """ + if in_dygraph_mode(): + return _C_ops.mish(x, threshold) + if _in_legacy_dygraph(): + return _legacy_C_ops.mish(x, 'threshold', threshold) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'mish') + check_type(threshold, 'threshold', (float, int), 'mish') + assert ( + threshold > 0 + ), "threshold of mish should be greater than 0, " "but got {}".format( + threshold + ) + + helper = LayerHelper('mish', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='mish', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold}, + ) + return out + + +def gather_tree(ids, parents): + r""" + To be used after beam search. After beam search, we get selected ids at + each time step and the corresponding parents in the search tree. Both ids + and parents have the layout :attr:`[max_time, batch_size, beam_size]`. Then + :attr:`gather_tree` is used to backtrace from the last time step and + generate the full sequences by collecting selected ids. + + Here is an example: + + .. code-block:: text + + Given: + ids = [[[2 2] + [6 1]] + [[3 9] + [6 1]] + [[0 1] + [9 0]]] + parents = [[[0 0] + [1 1]] + [[1 0] + [1 0]] + [[0 0] + [0 1]]] + + Then: + gather_tree(ids, parents) + = [[[2 2] + [1 6]] + [[3 3] + [6 1]] + [[0 1] + [9 0]]] + + Args: + ids(Tensor): A Tensor with shape :attr:`[length, batch_size, beam_size]` + and data type :attr:`int32` or :attr:`int64`. It contains the selected + ids of all time steps. + parents(Tensor): A Tensor with the same shape and data type as :attr:`ids`, + It contains the parents corresponding to selected ids when searching + among beams. + + Returns: + A Tensor with the same shape and data type as :attr:`ids`. \ + It contains the full sequences. The sequences are collected from \ + :attr:`ids` by backtracing according to :attr:`parents`. + + Examples: + .. code-block:: python + + import paddle + + ids = paddle.to_tensor([[[2, 2], [6, 1]], [[3, 9], [6, 1]], [[0, 1], [9, 0]]]) + + parents = paddle.to_tensor([[[0, 0], [1, 1]], [[1, 0], [1, 0]], [[0, 0], [0, 1]]]) + + final_sequences = paddle.nn.functional.gather_tree(ids, parents) + # [[[2, 2], [1, 6]], [[3, 3], [6, 1]], [[0, 1], [9, 0]]] + + """ + return paddle.nn.functional.gather_tree(ids, parents) + + +@deprecated(since="2.0.0", update_to="paddle.uniform") +@templatedoc() +def uniform_random( + shape, dtype='float32', min=-1.0, max=1.0, seed=0, name=None +): + """ + This OP returns a Tensor filled with random values sampled from a uniform + distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. + + Examples: + :: + + Input: + shape = [1, 2] + + Output: + result=[[0.8505902, 0.8397286]] + + Args: + shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of + the output Tensor. Supported data types: float32, float64. + Default is float32. + min(float|int, optional): The lower bound on the range of random values + to generate, ``min`` is included in the range. Default is -1.0. + max(float|int, optional): The upper bound on the range of random values + to generate, ``max`` is excluded in the range. Default is 1.0. + seed(int, optional): Random seed used for generating samples. 0 means + use a seed generated by the system. Note that if seed is not 0, + this operator will always generate the same random numbers every + time. Default is 0. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a uniform + distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. + + Raises: + TypeError: If ``shape`` is not list, tuple, Tensor. + TypeError: If ``dtype`` is not float32, float64. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + + # example 1: + # attr shape is a list which doesn't contain Tensor. + result_1 = fluid.layers.uniform_random(shape=[3, 4]) + # [[ 0.84524226, 0.6921872, 0.56528175, 0.71690357], + # [-0.34646994, -0.45116323, -0.09902662, -0.11397249], + # [ 0.433519, 0.39483607, -0.8660099, 0.83664286]] + + # example 2: + # attr shape is a list which contains Tensor. + dim_1 = fluid.layers.fill_constant([1], "int64", 2) + dim_2 = fluid.layers.fill_constant([1], "int32", 3) + result_2 = fluid.layers.uniform_random(shape=[dim_1, dim_2]) + # [[-0.9951253, 0.30757582, 0.9899647 ], + # [ 0.5864527, 0.6607096, -0.8886161 ]] + + # example 3: + # attr shape is a Tensor, the data type must be int64 or int32. + var_shape = fluid.data(name='var_shape', shape=[2], dtype="int64") + result_3 = fluid.layers.uniform_random(var_shape) + # if var_shape's value is [2, 3] + # result_3 is: + # [[-0.8517412, -0.4006908, 0.2551912 ], + # [ 0.3364414, 0.36278176, -0.16085452]] + + """ + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + return _C_ops.uniform_random( + shape, + dtype, + float(min), + float(max), + seed, + _current_expected_place(), + ) + elif _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + return _legacy_C_ops.uniform_random( + 'shape', + shape, + 'min', + float(min), + 'max', + float(max), + 'seed', + seed, + 'dtype', + dtype, + ) + + check_type(shape, 'shape', (list, tuple, Variable), 'uniform_random/rand') + check_dtype( + dtype, 'dtype', ('float32', 'float64', 'uint16'), 'uniform_random/rand' + ) + check_type(min, 'min', (float, int, Variable), 'uniform_random/rand') + check_type(max, 'max', (float, int, Variable), 'uniform_random/rand') + + inputs = dict() + attrs = {'seed': seed, 'min': min, 'max': max, 'dtype': dtype} + utils.get_shape_tensor_inputs( + inputs=inputs, attrs=attrs, shape=shape, op_type='uniform_random/rand' + ) + + helper = LayerHelper("uniform_random", **locals()) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="uniform_random", inputs=inputs, attrs=attrs, outputs={"Out": out} + ) + utils.try_set_static_shape_tensor(out, shape) + return out + + +def unbind(input, axis=0): + """ + Removes a tensor dimension, then split the input tensor into multiple sub-Tensors. + Args: + input (Variable): The input variable which is an N-D Tensor, data type being float32, float64, int32 or int64. + + axis (int32|int64, optional): A scalar with type ``int32|int64`` shape [1]. The dimension along which to unbind. If :math:`axis < 0`, the + dimension to unbind along is :math:`rank(input) + axis`. Default is 0. + Returns: + list(Variable): The list of segmented Tensor variables. + + Example: + .. code-block:: python + import paddle + # input is a variable which shape is [3, 4, 5] + input = paddle.fluid.data( + name="input", shape=[3, 4, 5], dtype="float32") + [x0, x1, x2] = paddle.tensor.unbind(input, axis=0) + # x0.shape [4, 5] + # x1.shape [4, 5] + # x2.shape [4, 5] + [x0, x1, x2, x3] = paddle.tensor.unbind(input, axis=1) + # x0.shape [3, 5] + # x1.shape [3, 5] + # x2.shape [3, 5] + # x3.shape [3, 5] + + """ + helper = LayerHelper("unbind", **locals()) + check_type(input, 'input', (Variable), 'unbind') + dtype = helper.input_dtype() + check_dtype( + dtype, 'unbind', ['float32', 'float64', 'int32', 'int64'], 'unbind' + ) + if not isinstance(axis, (int)): + raise TypeError( + "The type of 'axis' must be int, but received %s." % (type(axis)) + ) + if isinstance(axis, np.generic): + axis = np.asscalar(axis) + input_shape = input.shape + axis_ = axis if axis >= 0 else len(input_shape) + axis + num = input_shape[axis_] + outs = [ + helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + for i in range(num) + ] + + helper.append_op( + type="unbind", + inputs={"X": input}, + outputs={"Out": outs}, + attrs={"axis": axis}, + ) + return outs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..51b72267329cf3b0725e381c32fef96127d31d73 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/ops.py @@ -0,0 +1,884 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import os +from .layer_function_generator import generate_layer_fn, generate_activation_fn, generate_inplace_fn, add_sample_code +from .. import core +from ..framework import convert_np_dtype_to_dtype_, Variable, in_dygraph_mode +from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype +from paddle.utils import deprecated +from paddle import _C_ops, _legacy_C_ops +import paddle + +__deprecated_func_name__ = { + 'tanh_shrink': 'tanhshrink', + 'logsigmoid': 'log_sigmoid' +} + +__activations_noattr__ = [ + 'sigmoid', + 'silu', + 'logsigmoid', + 'tanh_shrink', + 'softsign', + 'tanh', +] + +__unary_func__ = [ + 'exp', 'expm1', 'atan', 'sqrt', 'rsqrt', 'abs', 'ceil', 'floor', 'cos', + 'tan', 'acos', 'sin', 'sinh', 'asin', 'cosh', 'round', 'reciprocal', + 'square', 'acosh', 'asinh', 'atanh', 'lgamma' +] + +__inplace_unary_func__ = [ + 'exp_', + 'sqrt_', + 'rsqrt_', + 'ceil_', + 'floor_', + 'round_', + 'reciprocal_', +] + +__all__ = [ + 'softplus', + 'softshrink', + 'hard_shrink', + 'cumsum', + 'thresholded_relu', + 'gelu', + 'erf', +] + +for _OP in set(__all__): + globals()[_OP] = generate_layer_fn(_OP) + +# It is a hot fix in some unittest using: +# fluid.layers.scale(x=x, scale=10.0, out=out_var) +# e.g.: test_program_code.py, test_dist_train.py +globals()['_scale'] = generate_layer_fn('scale') + +globals()['_elementwise_div'] = generate_layer_fn('elementwise_div') + +__all__ += __activations_noattr__ +__all__ += __unary_func__ +__all__ += __inplace_unary_func__ + +for _OP in set(__activations_noattr__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_activation_fn(_OP) + _func = deprecated(since="2.0.0", + update_to="paddle.nn.functional.%s" % (_new_OP))(_func) + globals()[_OP] = _func + +for _OP in set(__unary_func__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_activation_fn(_OP) + _func = deprecated(since="2.0.0", update_to="paddle.%s" % (_new_OP))(_func) + globals()[_OP] = _func + +for _OP in set(__inplace_unary_func__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_inplace_fn(_OP) + _func = deprecated(since="2.0.0", update_to="paddle.%s" % (_new_OP))(_func) + globals()[_OP] = _func + +add_sample_code( + globals()["sigmoid"], r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.sigmoid(x) + print(out) + # [0.40131234 0.450166 0.52497919 0.57444252] + +""") + +add_sample_code( + globals()["silu"], r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = F.silu(x) + print(out) + # [ 0.7310586 1.7615942 2.8577224, 3.9280552 ] + +""") + +add_sample_code( + globals()["logsigmoid"], r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.log_sigmoid(x) + print(out) + # [-0.91301525 -0.79813887 -0.64439666 -0.55435524] + +""") + +add_sample_code( + globals()["exp"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.exp(x) + print(out) + # [0.67032005 0.81873075 1.10517092 1.34985881] + +""") + +add_sample_code( + globals()["expm1"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.expm1(x) + print(out) + # [-0.32967997, -0.18126924, 0.10517092, 0.34985882] + +""") + +add_sample_code( + globals()["tanh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.tanh(x) + print(out) + # [-0.37994896 -0.19737532 0.09966799 0.29131261] + +""") + +add_sample_code( + globals()["atan"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.atan(x) + print(out) + # [-0.38050638 -0.19739556 0.09966865 0.29145679] + +""") + +add_sample_code( + globals()["tanh_shrink"], r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.tanhshrink(x) + print(out) + # [-0.020051, -0.00262468, 0.000332005, 0.00868739] + +""") + +add_sample_code( + globals()["sqrt"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4]) + out = paddle.sqrt(x) + print(out) + # [0.31622777 0.4472136 0.54772256 0.63245553] + +""") + +add_sample_code( + globals()["rsqrt"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4]) + out = paddle.rsqrt(x) + print(out) + # [3.16227766 2.23606798 1.82574186 1.58113883] + +""") + +add_sample_code( + globals()["abs"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.abs(x) + print(out) + # [0.4 0.2 0.1 0.3] + +""") + +add_sample_code( + globals()["ceil"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.ceil(x) + print(out) + # [-0. -0. 1. 1.] + +""") + +add_sample_code( + globals()["floor"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.floor(x) + print(out) + # [-1. -1. 0. 0.] + +""") + +add_sample_code( + globals()["cos"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.cos(x) + print(out) + # [0.92106099 0.98006658 0.99500417 0.95533649] + +""") + +add_sample_code( + globals()["tan"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.tan(x) + print(out) + # [-0.42279324, -0.20271005, 0.10033467, 0.30933627] + +""") + +add_sample_code( + globals()["acos"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.acos(x) + print(out) + # [1.98231317 1.77215425 1.47062891 1.26610367] + +""") + +add_sample_code( + globals()["sin"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.sin(x) + print(out) + # [-0.38941834 -0.19866933 0.09983342 0.29552021] + +""") + +add_sample_code( + globals()["asin"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.asin(x) + print(out) + # [-0.41151685 -0.20135792 0.10016742 0.30469265] + +""") + +add_sample_code( + globals()["cosh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.cosh(x) + print(out) + # [1.08107237 1.02006676 1.00500417 1.04533851] + +""") + +add_sample_code( + globals()["sinh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.sinh(x) + print(out) + # [-0.41075233 -0.201336 0.10016675 0.30452029] + +""") + +add_sample_code( + globals()["asinh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.asinh(x) + print(out) + # [-0.39003533, -0.19869010, 0.09983408, 0.29567307] + +""") + +add_sample_code( + globals()["acosh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1., 3., 4., 5.]) + out = paddle.acosh(x) + print(out) + # [0. , 1.76274729, 2.06343699, 2.29243159] + +""") + +add_sample_code( + globals()["atanh"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.atanh(x) + print(out) + # [-0.42364895, -0.20273256, 0.10033535, 0.30951962] + +""") + +add_sample_code( + globals()["round"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.5, -0.2, 0.6, 1.5]) + out = paddle.round(x) + print(out) + # [-1. -0. 1. 2.] + +""") + +add_sample_code( + globals()["reciprocal"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.reciprocal(x) + print(out) + # [-2.5 -5. 10. 3.33333333] + +""") + +add_sample_code( + globals()["square"], r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.square(x) + print(out) + # [0.16 0.04 0.01 0.09] + +""") + +_softplus_ = generate_layer_fn('softplus') + + +def softplus(x, beta: float = 1.0, threshold: float = 20.0, name=None): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'softplus') + locals_val = locals().copy() + kwargs = dict() + for name, val in locals_val.items(): + if val is not None: + kwargs[name] = val + return _softplus_(**kwargs) + + +softplus.__doc__ = r""" + :alias_main: paddle.nn.functional.softplus + :alias: paddle.nn.functional.softplus, paddle.nn.functional.activation.softplus + :old_api: paddle.fluid.layers.softplus + +:strong:`Softplus Activation Operator` + +Equation: + .. math:: + out = \\frac{1}{beta} * log(1 + e^{beta * x}) + For numerical stability, the implementation reverts to the linear function when: beta * x > threshold. + +Args: + x(Tensor): Input of Softplus op, Tensor, dtype: float32 or float64 + beta(float, optional): The value of beta for softplus. Default is 1 + threshold (float, optional): The value of threshold for softplus. Default is 20 + name(str, optional): Name for the operation (optional, default is None) + +Returns: + Variable: The output of Softplus op, Tensor, dtype: float32 or float64 + +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.softplus(x) + print(out) + # [0.513015, 0.598139, 0.744397, 0.854355] +""" + +add_sample_code( + globals()["softsign"], r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.softsign(x) + print(out) + # [-0.285714, -0.166667, 0.0909091, 0.230769] + +""") + +_softshrink_ = generate_layer_fn('softshrink') + + +def softshrink(x, alpha=None): + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + 'softshrink') + + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + if name == 'alpha': + kwargs['lambda'] = val + else: + kwargs[name] = val + return _softshrink_(**kwargs) + + +softshrink.__doc__ = r""" + :alias_main: paddle.nn.functional.softshrink + :alias: paddle.nn.functional.softshrink,paddle.nn.functional.activation.softshrink + :old_api: paddle.fluid.layers.softshrink + +:strong:`Softshrink Activation Operator` + +.. math:: + out = \\begin{cases} + x - \\alpha, \\text{if } x > \\alpha \\\\ + x + \\alpha, \\text{if } x < -\\alpha \\\\ + 0, \\text{otherwise} + \\end{cases} + + +Args: + x: Input of Softshrink operator, an N-D Tensor, with data type float32, float64 or float16. + alpha (float): non-negative offset + +Returns: + Output of Softshrink operator with the same type of input. + +Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.data(name="input", shape=[None, 784]) + result = fluid.layers.softshrink(x=data, alpha=0.3) +""" + +_hard_shrink_ = generate_layer_fn('hard_shrink') + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.hardshrink") +def hard_shrink(x, threshold=None): + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + 'hard_shrink') + + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + return _hard_shrink_(**kwargs) + + +hard_shrink.__doc__ = _hard_shrink_.__doc__ + """ +Examples: + + >>> import paddle.fluid as fluid + >>> data = fluid.layers.data(name="input", shape=[784]) + >>> result = fluid.layers.hard_shrink(x=data, threshold=0.3) +""" + +_cum_sum_ = generate_layer_fn('cumsum') + + +@deprecated(since="2.0.0", + update_to="paddle.cumsum", + reason="New APIs for Paddle 2.0 are coming.") +def cumsum(x, axis=None, exclusive=None, reverse=None): + check_type(x, 'x', (Variable), 'cumsum') + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + return _cum_sum_(**kwargs) + + +cumsum.__doc__ = """ + :alias_main: paddle.cumsum + :alias: paddle.cumsum,paddle.tensor.cumsum,paddle.tensor.math.cumsum + :old_api: paddle.fluid.layers.cumsum + +The cumulative sum of the elements along a given axis. By default, the first element of the result is the same of the first element of the input. If exlusive is true, the first element of the result is 0. + +Args: + x (Variable): Input of cumsum operator, the Tensor/LoDTensor needed to be cumsumed. + axis (int, optional): The dimension to accumulate along. -1 means the last dimension. Default is -1. + exclusive (bool, optional): Whether to perform exclusive cumsum. Default is False. + reverse (bool, optional): If true, the cumsum is performed in the reversed direction. Default is False. + +Returns: + Variable(Tensor/LoDTensor): The result of cumsum operator, output of cumsum operator. + +Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.data(name="input", shape=[32, 784]) + result = fluid.layers.cumsum(data, axis=0) +""" + +_thresholded_relu_ = generate_layer_fn('thresholded_relu') + + +def thresholded_relu(x, threshold=None): + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + 'thresholded_relu') + + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + + return _thresholded_relu_(**kwargs) + + +thresholded_relu.__doc__ = r""" + :alias_main: paddle.nn.functional.thresholded_relu + :alias: paddle.nn.functional.thresholded_relu,paddle.nn.functional.activation.thresholded_relu + :old_api: paddle.fluid.layers.thresholded_relu + +:strong:`Thresholded ReLU Activation Operator` + +Equation: + .. math:: + out = \\begin{cases} + x, &if x > threshold \\\\ + 0, &otherwise + \\end{cases} + +Args: + x(Variable): The input of Thresholded ReLU op, Tensor or LoDTensor, dtype: float32 or float64. + + threshold(float, optional): The threshold value. Note that if the arg `threshold` is not set, the threshold in the equation is 1.0. + +Returns: + + Variable: The output of Thresholded ReLU op, Tensor or LoDTensor, dtype: float32 or float64, the same as the input, shape: the same as the input. + +Examples: + + .. code-block:: python + + # declarative mode + import numpy as np + from paddle import fluid + + x = fluid.data(name="x", shape=(-1, 3), dtype="float32") + y = fluid.layers.thresholded_relu(x, threshold=0.1) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + start = fluid.default_startup_program() + main = fluid.default_main_program() + + data = np.random.randn(2, 3).astype("float32") + exe.run(start) + + y_np, = exe.run(main, feed={"x": data}, fetch_list=[y]) + + data + # array([[ 0.21134382, -1.1805999 , 0.32876605], + # [-1.2210793 , -0.7365624 , 1.0013918 ]], dtype=float32) + y_np + # array([[ 0.21134382, -0. , 0.32876605], + # [-0. , -0. , 1.0013918 ]], dtype=float32) + + .. code-block:: python + + # imperative mode + import numpy as np + from paddle import fluid + import paddle.fluid.dygraph as dg + + data = np.random.randn(2, 3).astype("float32") + place = fluid.CPUPlace() + with dg.guard(place) as g: + x = dg.to_variable(data) + y = fluid.layers.thresholded_relu(x, threshold=0.1) + y_np = y.numpy() + data + # array([[ 0.21134382, -1.1805999 , 0.32876605], + # [-1.2210793 , -0.7365624 , 1.0013918 ]], dtype=float32) + y_np + # array([[ 0.21134382, -0. , 0.32876605], + # [-0. , -0. , 1.0013918 ]], dtype=float32) +""" + +_gelu_ = generate_layer_fn('gelu') + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.gelu") +def gelu(x, approximate=False): + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + return _gelu_(**kwargs) + + +gelu.__doc__ = r""" +:strong:`GeLU Activation Operator` +For more details, see [Gaussian Error Linear Units](https://arxiv.org/abs/1606.08415). + +Equation: + if approximate is True + .. math:: + out = 0.5 * x * (1 + tanh(\\sqrt{\\frac{2}{\\pi}} * (x + 0.044715x^{3}))) + + else + .. math:: + out = 0.5 * x * (1 + erf(\\frac{x}{\\sqrt{2}})) + +Args: + + x(Variable): The input of GeLU op, Tensor or LoDTensor, dtype: float32 or float64. + +Returns: + + Variable: The output of GeLU op, Tensor or LoDTensor, dtype: float32 or float64, the same as the input, shape: the same as the input. + +Examples: + + .. code-block:: python + + # declarative mode + import numpy as np + from paddle import fluid + + x = fluid.data(name="x", shape=(-1, 3), dtype="float32") + y = fluid.layers.gelu(x) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + start = fluid.default_startup_program() + main = fluid.default_main_program() + + data = np.random.randn(2, 3).astype("float32") + exe.run(start) + + y_np, = exe.run(main, feed={"x": data}, fetch_list=[y]) + + data + # array([[ 0.87165993, -1.0541513 , -0.37214822], + # [ 0.15647964, 0.32496083, 0.33045998]], dtype=float32) + y_np + # array([[ 0.70456535, -0.15380788, -0.13207214], + # [ 0.08796856, 0.20387867, 0.2080159 ]], dtype=float32) + + .. code-block:: python + + # imperative mode + import numpy as np + from paddle import fluid + import paddle.fluid.dygraph as dg + + data = np.random.randn(2, 3).astype("float32") + place = fluid.CPUPlace() + with dg.guard(place) as g: + x = dg.to_variable(data) + y = fluid.layers.gelu(x) + y_np = y.numpy() + data + # array([[ 0.87165993, -1.0541513 , -0.37214822], + # [ 0.15647964, 0.32496083, 0.33045998]], dtype=float32) + y_np + # array([[ 0.70456535, -0.15380788, -0.13207214], + # [ 0.08796856, 0.20387867, 0.2080159 ]], dtype=float32) +""" + +_erf_ = generate_layer_fn('erf') + + +def erf(x, name=None): + if in_dygraph_mode(): + return _C_ops.erf(x) + + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + return _erf_(**kwargs) + + +erf.__doc__ = r""" +:strong:`Erf Operator` +For more details, see [Error function](https://en.wikipedia.org/wiki/Error_function). + +Equation: + .. math:: + out = \\frac{2}{\\sqrt{\\pi}} \\int_{0}^{x}e^{- \\eta^{2}}d\\eta + +Args: + + x (Tensor): The input tensor, it's data type should be float32, float64. + +Returns: + + Tensor: The output of Erf op, dtype: float32 or float64, the same as the input, shape: the same as the input. + +Examples: + + .. code-block:: python + + import paddle + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.erf(x) + print(out) + # [-0.42839236 -0.22270259 0.11246292 0.32862676] +""" + + +def lgamma(x, name=None): + r""" + Calculates the lgamma of the given input tensor, element-wise. + + This operator performs elementwise lgamma for input $X$. + :math:`out = log\Gamma(x)` + + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the lgamma of the input Tensor, the shape and data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.lgamma(x) + print(out) + # [1.31452441, 1.76149750, 2.25271273, 1.09579802] + """ + return paddle.Tensor.lgamma(x) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/rnn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..6b51721aafc41a1b96dc1c3c23aca3848056fc2a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/rnn.py @@ -0,0 +1,3564 @@ +# 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. + +from __future__ import print_function + +import sys +from functools import partial, reduce +import warnings + +import paddle +from paddle.utils import deprecated +from . import nn +from . import tensor +from . import control_flow +from . import utils +from . import sequence_lod +from .utils import * +from .. import core +from ..framework import default_main_program +from ..data_feeder import convert_dtype +from ..layer_helper import LayerHelper +from ..framework import _non_static_mode +from ..param_attr import ParamAttr +from ..data_feeder import check_variable_and_dtype, check_type, check_dtype +try: + from collections.abc import Sequence +except: + from collections import Sequence + +__all__ = [ + 'RNNCell', + 'GRUCell', + 'LSTMCell', + 'Decoder', + 'BeamSearchDecoder', + 'rnn', + 'birnn', + 'dynamic_decode', + 'DecodeHelper', + 'TrainingHelper', + 'GreedyEmbeddingHelper', + 'SampleEmbeddingHelper', + 'BasicDecoder', + 'dynamic_lstm', + 'dynamic_lstmp', + 'dynamic_gru', + 'gru_unit', + 'lstm_unit', + 'lstm', + 'beam_search', + 'beam_search_decode', +] + + +class RNNCell(object): + """ + :api_attr: Static Graph + + RNNCell is the base class for abstraction representing the calculations + mapping the input and state to the output and new state. It is suitable to + and mostly used in RNN. + """ + + def call(self, inputs, states, **kwargs): + r""" + Every cell must implement this method to do the calculations mapping the + inputs and states to the output and new states. + + To be more flexible, both inputs and states can be a tensor variable or + a nested structure (list|tuple|namedtuple|dict) of tensor variable, that + is, a (possibly nested structure of) tensor variable[s]. + + Parameters: + inputs: A (possibly nested structure of) tensor variable[s]. + states: A (possibly nested structure of) tensor variable[s]. + **kwargs: Additional keyword arguments, provided by the caller. + + Returns: + tuple: outputs and new_states pair. outputs and new_states both \ + can be nested structure of tensor variables. new_states must \ + have the same structure with states. + + """ + raise NotImplementedError("RNNCell must implent the call function.") + + def __call__(self, inputs, states, **kwargs): + return self.call(inputs, states, **kwargs) + + def get_initial_states(self, + batch_ref, + shape=None, + dtype='float32', + init_value=0, + batch_dim_idx=0): + r""" + Generate initialized states according to provided shape, data type and + value. + + Parameters: + batch_ref: A (possibly nested structure of) tensor variable[s]. + The first dimension of the tensor will be used as batch size to + initialize states. + shape: A (possibly nested structure of) shape[s], where a shape is + represented as a list/tuple of integer). -1(for batch size) will + beautomatically inserted if shape is not started with it. If None, + property `state_shape` will be used. The default value is None. + dtype: A (possibly nested structure of) data type[s]. The structure + must be same as that of `shape`, except when all tensors' in states + has the same data type, a single data type can be used. If + property `cell.state_shape` is not available, float32 will be used + as the data type. The default value is float32. + init_value: A float value used to initialize states. + batch_dim_idx: An integer indicating which dimension of the tensor in + inputs represents batch size. The default value is 0. + + Returns: + Variable: tensor variable[s] packed in the same structure provided \ + by shape, representing the initialized states. + """ + if sys.version_info < (3, ): + integer_types = ( + int, + long, + ) + else: + integer_types = (int, ) + check_variable_and_dtype(batch_ref, 'batch_ref', + ['float32', 'float64', 'int32', 'int64'], + 'RNNCell') + check_type(shape, 'shape', (list, tuple, type(None), integer_types), + 'RNNCell') + if isinstance(shape, (list, tuple)): + shapes = map_structure(lambda x: x, shape) + if isinstance(shape, list): + for i, _shape in enumerate(shapes): + check_type(_shape, 'shapes[' + str(i) + ']', integer_types, + 'RNNCell') + else: + check_type(shapes, 'shapes', integer_types, 'RNNCell') + check_dtype(dtype, 'dtype', ['float32', 'float64'], 'RNNCell') + + # TODO: use inputs and batch_size + batch_ref = flatten(batch_ref)[0] + + def _is_shape_sequence(seq): + if sys.version_info < (3, ): + integer_types = ( + int, + long, + ) + else: + integer_types = (int, ) + """For shape, list/tuple of integer is the finest-grained objection""" + if (isinstance(seq, list) or isinstance(seq, tuple)): + if reduce(lambda flag, x: isinstance(x, integer_types) and flag, + seq, True): + return False + # TODO: Add check for the illegal + if isinstance(seq, dict): + return True + return (isinstance(seq, Sequence) + and not isinstance(seq, six.string_types)) + + class Shape(object): + + def __init__(self, shape): + self.shape = shape if shape[0] == -1 else ([-1] + list(shape)) + + # nested structure of shapes + states_shapes = self.state_shape if shape is None else shape + is_sequence_ori = utils.is_sequence + utils.is_sequence = _is_shape_sequence + states_shapes = map_structure(lambda shape: Shape(shape), states_shapes) + utils.is_sequence = is_sequence_ori + + # nested structure of dtypes + try: + states_dtypes = self.state_dtype if dtype is None else dtype + except NotImplementedError: # use fp32 as default + states_dtypes = "float32" + if len(flatten(states_dtypes)) == 1: + dtype = flatten(states_dtypes)[0] + states_dtypes = map_structure(lambda shape: dtype, states_shapes) + + init_states = map_structure( + lambda shape, dtype: tensor.fill_constant_batch_size_like( + input=batch_ref, + shape=shape.shape, + dtype=dtype, + value=init_value, + input_dim_idx=batch_dim_idx), states_shapes, states_dtypes) + return init_states + + @property + def state_shape(self): + """ + Abstract method (property). + Used to initialize states. + A (possibly nested structure of) shape[s], where a shape is represented + as a list/tuple of integers (-1 for batch size would be automatically + inserted into a shape if shape is not started with it). + Not necessary to be implemented if states are not initialized by + `get_initial_states` or the `shape` argument is provided when using + `get_initial_states`. + """ + raise NotImplementedError( + "Please add implementaion for `state_shape` in the used cell.") + + @property + def state_dtype(self): + """ + Abstract method (property). + Used to initialize states. + A (possibly nested structure of) data types[s]. The structure must be + same as that of `shape`, except when all tensors' in states has the same + data type, a single data type can be used. + Not necessary to be implemented if states are not initialized + by `get_initial_states` or the `dtype` argument is provided when using + `get_initial_states`. + """ + raise NotImplementedError( + "Please add implementaion for `state_dtype` in the used cell.") + + +class GRUCell(RNNCell): + r""" + :api_attr: Static Graph + + Gated Recurrent Unit cell. It is a wrapper for + `fluid.contrib.layers.rnn_impl.BasicGRUUnit` to make it adapt to RNNCell. + + The formula used is as follow: + + .. math:: + + u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u) + + r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r) + + \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c) + + h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t} + + For more details, please refer to `Learning Phrase Representations using + RNN Encoder Decoder for Statistical Machine Translation `_ + + Examples: + + .. code-block:: python + + import paddle.fluid.layers as layers + cell = layers.GRUCell(hidden_size=256) + """ + + def __init__(self, + hidden_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + dtype="float32", + name="GRUCell"): + """ + Constructor of GRUCell. + + Parameters: + hidden_size (int): The hidden size in the GRU cell. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + weight matrix. Default: None. + bias_attr (ParamAttr, optional): The parameter attribute for the bias + of GRU. Default: None. + gate_activation (function, optional): The activation function for :math:`act_g`. + Default: `fluid.layers.sigmoid`. + activation (function, optional): The activation function for :math:`act_c`. + Default: `fluid.layers.tanh`. + dtype(string, optional): The data type used in this cell. Default float32. + name(string, optional) : The name scope used to identify parameters and biases. + """ + check_type(hidden_size, 'hidden_size', (int), 'GRUCell') + check_dtype(dtype, 'dtype', ['float32', 'float64'], 'GRUCell') + self.hidden_size = hidden_size + from .. import contrib # TODO: resolve recurrent import + self.gru_unit = contrib.layers.rnn_impl.BasicGRUUnit( + name, hidden_size, param_attr, bias_attr, gate_activation, + activation, dtype) + + def call(self, inputs, states): + r""" + Perform calculations of GRU. + + Parameters: + inputs(Variable): A tensor with shape `[batch_size, input_size]`, + corresponding to :math:`x_t` in the formula. The data type + should be float32 or float64. + states(Variable): A tensor with shape `[batch_size, hidden_size]`. + corresponding to :math:`h_{t-1}` in the formula. The data type + should be float32 or float64. + + Returns: + tuple: A tuple( :code:`(outputs, new_states)` ), where `outputs` and \ + `new_states` is the same tensor shaped `[batch_size, hidden_size]`, \ + corresponding to :math:`h_t` in the formula. The data type of the \ + tensor is same as that of `states`. + """ + + check_variable_and_dtype(inputs, 'inputs', ['float32', 'float64'], + 'GRUCell') + check_variable_and_dtype(states, 'states', ['float32', 'float64'], + 'GRUCell') + new_hidden = self.gru_unit(inputs, states) + return new_hidden, new_hidden + + @property + def state_shape(self): + """ + The `state_shape` of GRUCell is a shape `[hidden_size]` (-1 for batch + size would be automatically inserted into shape). The shape corresponds + to :math:`h_{t-1}`. + """ + return [self.hidden_size] + + +class LSTMCell(RNNCell): + r""" + :api_attr: Static Graph + + Long-Short Term Memory cell. It is a wrapper for + `fluid.contrib.layers.rnn_impl.BasicLSTMUnit` to make it adapt to RNNCell. + + The formula used is as follow: + + .. math:: + + i_{t} & = act_g(W_{x_{i}}x_{t} + W_{h_{i}}h_{t-1} + b_{i}) + + f_{t} & = act_g(W_{x_{f}}x_{t} + W_{h_{f}}h_{t-1} + b_{f} + forget\\_bias) + + c_{t} & = f_{t}c_{t-1} + i_{t} act_c (W_{x_{c}}x_{t} + W_{h_{c}}h_{t-1} + b_{c}) + + o_{t} & = act_g(W_{x_{o}}x_{t} + W_{h_{o}}h_{t-1} + b_{o}) + + h_{t} & = o_{t} act_c (c_{t}) + + For more details, please refer to `RECURRENT NEURAL NETWORK REGULARIZATION `_ + + Examples: + + .. code-block:: python + + import paddle.fluid.layers as layers + cell = layers.LSTMCell(hidden_size=256) + """ + + def __init__(self, + hidden_size, + param_attr=None, + bias_attr=None, + gate_activation=None, + activation=None, + forget_bias=1.0, + dtype="float32", + name="LSTMCell"): + """ + Constructor of LSTMCell. + + Parameters: + hidden_size (int): The hidden size in the LSTM cell. + param_attr(ParamAttr, optional): The parameter attribute for the learnable + weight matrix. Default: None. + bias_attr (ParamAttr, optional): The parameter attribute for the bias + of LSTM. Default: None. + gate_activation (function, optional): The activation function for :math:`act_g`. + Default: 'fluid.layers.sigmoid'. + activation (function, optional): The activation function for :math:`act_h`. + Default: 'fluid.layers.tanh'. + forget_bias(float, optional): forget bias used when computing forget gate. + Default 1.0 + dtype(string, optional): The data type used in this cell. Default float32. + name(string, optional) : The name scope used to identify parameters and biases. + """ + + check_type(hidden_size, 'hidden_size', (int), 'LSTMCell') + check_dtype(dtype, 'dtype', ['float32', 'float64'], 'LSTMCell') + self.hidden_size = hidden_size + from .. import contrib # TODO: resolve recurrent import + self.lstm_unit = contrib.layers.rnn_impl.BasicLSTMUnit( + name, hidden_size, param_attr, bias_attr, gate_activation, + activation, forget_bias, dtype) + + def call(self, inputs, states): + r""" + Perform calculations of LSTM. + + Parameters: + inputs(Variable): A tensor with shape `[batch_size, input_size]`, + corresponding to :math:`x_t` in the formula. The data type + should be float32 or float64. + states(Variable): A list of containing two tensors, each shaped + `[batch_size, hidden_size]`, corresponding to :math:`h_{t-1}, c_{t-1}` + in the formula. The data type should be float32 or float64. + + Returns: + tuple: A tuple( :code:`(outputs, new_states)` ), where `outputs` is \ + a tensor with shape `[batch_size, hidden_size]`, corresponding \ + to :math:`h_{t}` in the formula; `new_states` is a list containing \ + two tenser variables shaped `[batch_size, hidden_size]`, corresponding \ + to :math:`h_{t}, c_{t}` in the formula. The data type of these \ + tensors all is same as that of `states`. + """ + + check_variable_and_dtype(inputs, 'inputs', ['float32', 'float64'], + 'LSTMCell') + check_type(states, 'states', list, 'LSTMCell') + if isinstance(states, list): + for i, state in enumerate(states): + check_variable_and_dtype(state, 'state[' + str(i) + ']', + ['float32', 'float64'], 'LSTMCell') + + pre_hidden, pre_cell = states + new_hidden, new_cell = self.lstm_unit(inputs, pre_hidden, pre_cell) + return new_hidden, [new_hidden, new_cell] + + @property + def state_shape(self): + """ + The `state_shape` of LSTMCell is a list with two shapes: `[[hidden_size], [hidden_size]]` + (-1 for batch size would be automatically inserted into shape). These two + shapes correspond to :math:`h_{t-1}` and :math:`c_{t-1}` separately. + """ + return [[self.hidden_size], [self.hidden_size]] + + +def rnn(cell, + inputs, + initial_states=None, + sequence_length=None, + time_major=False, + is_reverse=False, + **kwargs): + """ + rnn creates a recurrent neural network specified by RNNCell `cell`, + which performs :code:`cell.call()` (for dygraph mode :code:`cell.forward`) + repeatedly until reaches to the maximum length of `inputs`. + + Arguments: + cell(RNNCellBase): An instance of `RNNCellBase`. + inputs(Tensor): the input sequences. + If time_major is True, the shape is + `[time_steps, batch_size, input_size]` + else the shape is `[batch_size, time_steps, input_size]`. + initial_states(Tensor|tuple|list, optional): the initial state of the + rnn cell. Tensor or a possibly nested structure of tensors. If not + provided, `cell.get_initial_states` would be called to produce + the initial state. Defaults to None. + sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64 + or int32. The valid lengths of input sequences. Defaults to None. + If `sequence_length` is not None, the inputs are treated as + padded sequences. In each input sequence, elements whose time step + index are not less than the valid length are treated as paddings. + time_major (bool): Whether the first dimension of the input means the + time steps. Defaults to False. + is_reverse (bool, optional): Indicate whether to calculate in the reverse + order of input sequences. Defaults to False. + **kwargs: Additional keyword arguments to pass to `forward` of the cell. + + Returns: + (outputs, final_states) + outputs (Tensor|list|tuple): the output sequence. Tensor or nested + structure of Tensors. + If `time_major` is True, the shape of each tensor in outpus is + `[time_steps, batch_size, hidden_size]`, else + `[batch_size, time_steps, hidden_size]`. + final_states (Tensor|list|tuple): final states. A (possibly nested structure of) + tensor[s], representing the final state for RNN. It has the same + structure of intial state. Each tensor in final states has the same + shape and dtype as the corresponding tensor in initial states. + + + Examples: + + .. code-block:: python + + import paddle + paddle.disable_static() + + cell = paddle.nn.SimpleRNNCell(16, 32) + + inputs = paddle.rand((4, 23, 16)) + prev_h = paddle.randn((4, 32)) + outputs, final_states = paddle.fluid.layers.rnn(cell, inputs, prev_h) + + """ + if _non_static_mode(): + return _rnn_dynamic_graph(cell, inputs, initial_states, sequence_length, + time_major, is_reverse, **kwargs) + else: + return _rnn_static_graph(cell, inputs, initial_states, sequence_length, + time_major, is_reverse, **kwargs) + + +class ArrayWrapper(object): + + def __init__(self, x): + self.array = [x] + + def append(self, x): + self.array.append(x) + return self + + def __getitem__(self, item): + return self.array.__getitem__(item) + + +def _maybe_copy(state, new_state, step_mask): + """update rnn state or just pass the old state through""" + new_state = nn.elementwise_mul(new_state, step_mask, axis=0) \ + + nn.elementwise_mul(state, (1 - step_mask), axis=0) + return new_state + + +def _transpose_batch_time(x): + perm = [1, 0] + list(range(2, len(x.shape))) + return nn.transpose(x, perm) + + +def _rnn_dynamic_graph(cell, + inputs, + initial_states=None, + sequence_length=None, + time_major=False, + is_reverse=False, + **kwargs): + time_step_index = 0 if time_major else 1 + flat_inputs = flatten(inputs) + time_steps = flat_inputs[0].shape[time_step_index] + + if initial_states is None: + initial_states = cell.get_initial_states( + batch_ref=inputs, batch_dim_idx=1 if time_major else 0) + + if not time_major: + inputs = map_structure(_transpose_batch_time, inputs) + + if sequence_length is not None: + mask = sequence_lod.sequence_mask(sequence_length, + maxlen=time_steps, + dtype=inputs.dtype) + mask = nn.transpose(mask, [1, 0]) + + if is_reverse: + inputs = map_structure(lambda x: tensor.reverse(x, axis=[0]), inputs) + mask = tensor.reverse(mask, axis=[0]) \ + if sequence_length is not None else None + + states = initial_states + outputs = [] + for i in range(time_steps): + step_inputs = map_structure(lambda x: x[i], inputs) + step_outputs, new_states = cell(step_inputs, states, **kwargs) + if sequence_length is not None: + new_states = map_structure(partial(_maybe_copy, step_mask=mask[i]), + states, new_states) + states = new_states + outputs = map_structure(lambda x: ArrayWrapper(x), + step_outputs) if i == 0 else map_structure( + lambda x, x_array: x_array.append(x), + step_outputs, outputs) + + final_outputs = map_structure( + lambda x: nn.stack(x.array, axis=time_step_index), outputs) + + if is_reverse: + final_outputs = map_structure( + lambda x: tensor.reverse(x, axis=time_step_index), final_outputs) + + final_states = new_states + return final_outputs, final_states + + +def _rnn_static_graph(cell, + inputs, + initial_states=None, + sequence_length=None, + time_major=False, + is_reverse=False, + **kwargs): + check_type(inputs, 'inputs', (Variable, list, tuple), 'rnn') + if isinstance(inputs, (list, tuple)): + for i, input_x in enumerate(inputs): + check_variable_and_dtype(input_x, 'inputs[' + str(i) + ']', + ['float32', 'float64'], 'rnn') + check_type(initial_states, 'initial_states', + (Variable, list, tuple, type(None)), 'rnn') + + check_type(sequence_length, 'sequence_length', (Variable, type(None)), + 'rnn') + + def _switch_grad(x, stop=False): + x.stop_gradient = stop + return x + + if initial_states is None: + initial_states = cell.get_initial_states( + batch_ref=inputs, batch_dim_idx=1 if time_major else 0) + initial_states = map_structure(_switch_grad, initial_states) + + if not time_major: + inputs = map_structure(_transpose_batch_time, inputs) + + if sequence_length: + max_seq_len = nn.shape(flatten(inputs)[0])[0] + mask = sequence_lod.sequence_mask( + sequence_length, + maxlen=max_seq_len, + dtype=flatten(initial_states)[0].dtype) + mask = nn.transpose(mask, [1, 0]) + if is_reverse: + inputs = map_structure(lambda x: tensor.reverse(x, axis=[0]), inputs) + mask = tensor.reverse(mask, axis=[0]) if sequence_length else None + + # StaticRNN + rnn = control_flow.StaticRNN() + with rnn.step(): + inputs = map_structure(rnn.step_input, inputs) + states = map_structure(rnn.memory, initial_states) + copy_states = map_structure(lambda x: x, states) + outputs, new_states = cell(inputs, copy_states, **kwargs) + assert_same_structure(states, new_states) + if sequence_length: + step_mask = rnn.step_input(mask) + new_states = map_structure( + partial(_maybe_copy, step_mask=step_mask), states, new_states) + + map_structure(rnn.update_memory, states, new_states) + flat_outputs = flatten(outputs) + map_structure(rnn.step_output, outputs) + map_structure(rnn.step_output, new_states) + + rnn_out = rnn() + final_outputs = rnn_out[:len(flat_outputs)] + final_outputs = pack_sequence_as(outputs, final_outputs) + final_states = map_structure(lambda x: x[-1], rnn_out[len(flat_outputs):]) + final_states = pack_sequence_as(new_states, final_states) + + if is_reverse: + final_outputs = map_structure(lambda x: tensor.reverse(x, axis=[0]), + final_outputs) + + if not time_major: + final_outputs = map_structure(_transpose_batch_time, final_outputs) + + return (final_outputs, final_states) + + +def birnn(cell_fw, + cell_bw, + inputs, + initial_states=None, + sequence_length=None, + time_major=False, + **kwargs): + """ + birnn creates a bidirectional recurrent neural network specified by + RNNCell `cell_fw` and `cell_bw`, which performs :code:`cell.call()` + (for dygraph mode :code:`cell.forward`) repeatedly until reaches to + the maximum length of `inputs` and then concat the outputs for both RNNs + along the last axis. + + Arguments: + cell_fw(RNNCellBase): An instance of `RNNCellBase`. + cell_bw(RNNCellBase): An instance of `RNNCellBase`. + inputs(Tensor): the input sequences. + If time_major is True, the shape is + `[time_steps, batch_size, input_size]` + else the shape is `[batch_size, time_steps, input_size]`. + initial_states(tuple, optional): A tuple of initial states of + `cell_fw` and `cell_bw`. + If not provided, `cell.get_initial_states` would be called to + produce initial state for each cell. Defaults to None. + sequence_length (Tensor, optional): shape `[batch_size]`, dtype: int64 + or int32. The valid lengths of input sequences. Defaults to None. + If `sequence_length` is not None, the inputs are treated as + padded sequences. In each input sequence, elements whose time step + index are not less than the valid length are treated as paddings. + time_major (bool): Whether the first dimension of the input means the + time steps. Defaults to False. + **kwargs: Additional keyword arguments to pass to `forward` of each cell. + + Returns: + (outputs, final_states) + outputs (Tensor): the outputs of the bidirectional RNN. It is the + concatenation of the outputs from the forward RNN and backward + RNN along the last axis. + If time major is True, the shape is `[time_steps, batch_size, size]`, + else the shape is `[batch_size, time_steps, size]`, where size is + `cell_fw.hidden_size + cell_bw.hidden_size`. + final_states (tuple): A tuple of the final states of the forward + cell and backward cell. + + Examples: + + .. code-block:: python + + import paddle + paddle.disable_static() + + cell_fw = paddle.nn.LSTMCell(16, 32) + cell_bw = paddle.nn.LSTMCell(16, 32) + + inputs = paddle.rand((4, 23, 16)) + hf, cf = paddle.rand((4, 32)), paddle.rand((4, 32)) + hb, cb = paddle.rand((4, 32)), paddle.rand((4, 32)) + initial_states = ((hf, cf), (hb, cb)) + outputs, final_states = paddle.fluid.layers.birnn( + cell_fw, cell_bw, inputs, initial_states) + + """ + if initial_states is None: + states_fw = cell_fw.get_initial_states( + batch_ref=inputs, batch_dim_idx=1 if time_major else 0) + states_bw = cell_fw.get_initial_states( + batch_ref=inputs, batch_dim_idx=1 if time_major else 0) + else: + states_fw, states_bw = initial_states + outputs_fw, states_fw = rnn(cell_fw, + inputs, + states_fw, + sequence_length, + time_major=time_major, + **kwargs) + + outputs_bw, states_bw = rnn(cell_bw, + inputs, + states_bw, + sequence_length, + time_major=time_major, + is_reverse=True, + **kwargs) + + outputs = map_structure(lambda x, y: tensor.concat([x, y], -1), outputs_fw, + outputs_bw) + + final_states = (states_fw, states_bw) + return outputs, final_states + + +class Decoder(object): + """ + :api_attr: Static Graph + + Decoder is the base class for any decoder instance used in `dynamic_decode`. + It provides interface for output generation for one time step, which can be + used to generate sequences. + + The key abstraction provided by Decoder is: + + 1. :code:`(initial_input, initial_state, finished) = initialize(inits)` , + which generates the input and state for the first decoding step, and gives the + initial status telling whether each sequence in the batch is finished. + It would be called once before the decoding iterations. + + 2. :code:`(output, next_state, next_input, finished) = step(time, input, state)` , + which transforms the input and state to the output and new state, generates + input for the next decoding step, and emits the flag indicating finished status. + It is the main part for each decoding iteration. + + 3. :code:`(final_outputs, final_state) = finalize(outputs, final_state, sequence_lengths)` , + which revises the outputs(stack of all time steps' output) and final state(state from the + last decoding step) to get the counterpart for special usage. + Not necessary to be implemented if no need to revise the stacked outputs and + state from the last decoding step. If implemented, it would be called after + the decoding iterations. + + Decoder is more general compared to RNNCell, since the returned `next_input` + and `finished` make it can determine the input and when to finish by itself + when used in dynamic decoding. Decoder always wraps a RNNCell instance though + not necessary. + """ + + def initialize(self, inits): + r""" + Called once before the decoding iterations. + + Parameters: + inits: Argument provided by the caller. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \ + `initial_inputs` and `initial_states` both are a (possibly nested \ + structure of) tensor variable[s], and `finished` is a tensor with \ + bool data type. + """ + raise NotImplementedError + + def step(self, time, inputs, states, **kwargs): + r""" + Called per step of decoding. + + Parameters: + time(Variable): A Tensor with shape :math:`[1]` provided by the caller. + The data type is int64. + inputs(Variable): A (possibly nested structure of) tensor variable[s]. + states(Variable): A (possibly nested structure of) tensor variable[s]. + **kwargs: Additional keyword arguments, provided by the caller. + + Returns: + tuple: A tuple( :code:(outputs, next_states, next_inputs, finished)` ). \ + `next_inputs` and `next_states` both are a (possibly nested \ + structure of) tensor variable[s], and the structure, shape and \ + data type must be same as the counterpart from input arguments. \ + `outputs` is a (possibly nested structure of) tensor variable[s]. \ + `finished` is a Tensor with bool data type. + """ + raise NotImplementedError + + def finalize(self, outputs, final_states, sequence_lengths): + r""" + Called once after the decoding iterations if implemented. + + Parameters: + outputs(Variable): A (possibly nested structure of) tensor variable[s]. + The structure and data type is same as `output_dtype`. + The tensor stacks all time steps' output thus has shape + :math:`[time\_step, batch\_size, ...]` , which is done by the caller. + final_states(Variable): A (possibly nested structure of) tensor variable[s]. + It is the `next_states` returned by `decoder.step` at last decoding step, + thus has the same structure, shape and data type with states at any time + step. + + Returns: + tuple: A tuple( :code:`(final_outputs, final_states)` ). \ + `final_outputs` and `final_states` both are a (possibly nested \ + structure of) tensor variable[s]. + """ + raise NotImplementedError + + @property + def tracks_own_finished(self): + """ + Describes whether the Decoder keeps track of finished states by itself. + + `decoder.step()` would emit a bool `finished` value at each decoding + step. The emited `finished` can be used to determine whether every + batch entries is finished directly, or it can be combined with the + finished tracker keeped in `dynamic_decode` by performing a logical OR + to take the already finished into account. + + If `False`, the latter would be took when performing `dynamic_decode`, + which is the default. Otherwise, the former would be took, which uses + the finished value emited by the decoder as all batch entry finished + status directly, and it is the case when batch entries might be + reordered such as beams in BeamSearchDecoder. + + Returns: + bool: A python bool `False`. + """ + return False + + +class BeamSearchDecoder(Decoder): + """ + Decoder with beam search decoding strategy. It wraps a cell to get probabilities, + and follows a beam search step to calculate scores and select candidate + token ids for each decoding step. + + Please refer to `Beam search `_ + for more details. + + **NOTE** When decoding with beam search, the `inputs` and `states` of cell + would be tiled to `beam_size` (unsqueeze and tile), resulting to shapes like + `[batch_size * beam_size, ...]` , which is built into `BeamSearchDecoder` and + done automatically. Thus any other tensor with shape `[batch_size, ...]` used + in `cell.call` needs to be tiled manually first, which can be completed by using + :code:`BeamSearchDecoder.tile_beam_merge_with_batch` . The most common case + for this is the encoder output in attention mechanism. + + Returns: + BeamSearchDecoder: An instance of decoder which can be used in \ + `paddle.nn.dynamic_decode` to implement decoding. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.nn import BeamSearchDecoder, dynamic_decode + from paddle.nn import GRUCell, Linear, Embedding + trg_embeder = Embedding(100, 32) + output_layer = Linear(32, 32) + decoder_cell = GRUCell(input_size=32, hidden_size=32) + decoder = BeamSearchDecoder(decoder_cell, + start_token=0, + end_token=1, + beam_size=4, + embedding_fn=trg_embeder, + output_fn=output_layer) + + """ + + def __init__(self, + cell, + start_token, + end_token, + beam_size, + embedding_fn=None, + output_fn=None): + """ + Constructor of BeamSearchDecoder. + + Parameters: + cell(RNNCellBase): An instance of `RNNCellBase` or object with the same interface. + start_token(int): The start token id. + end_token(int): The end token id. + beam_size(int): The beam width used in beam search. + embedding_fn(optional): A callable to apply to selected candidate ids. + Mostly it is an embedding layer to transform ids to embeddings, + and the returned value acts as the `input` argument for `cell.call`. + If not provided, the id to embedding transformation must be built into + `cell.call`. Default None. + output_fn(optional): A callable to apply to the cell's output prior to + calculate scores and select candidate token ids. Default None. + """ + self.cell = cell + self.embedding_fn = embedding_fn + self.output_fn = output_fn + self.start_token = start_token + self.end_token = end_token + self.beam_size = beam_size + + @staticmethod + def tile_beam_merge_with_batch(x, beam_size): + r""" + Tile the batch dimension of a tensor. Specifically, this function takes + a tensor t shaped `[batch_size, s0, s1, ...]` composed of minibatch + entries `t[0], ..., t[batch_size - 1]` and tiles it to have a shape + `[batch_size * beam_size, s0, s1, ...]` composed of minibatch entries + `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated + `beam_size` times. + + Parameters: + x(Variable): A tensor with shape `[batch_size, ...]`. The data type + should be float32, float64, int32, int64 or bool. + beam_size(int): The beam width used in beam search. + + Returns: + Variable: A tensor with shape `[batch_size * beam_size, ...]`, whose \ + data type is same as `x`. + """ + check_type(x, 'x', (Variable), + 'BeamSearchDecoder.tile_beam_merge_with_batch') + x = nn.unsqueeze(x, [1]) # [batch_size, 1, ...] + expand_times = [1] * len(x.shape) + expand_times[1] = beam_size + x = paddle.tile(x, expand_times) # [batch_size, beam_size, ...] + x = nn.transpose(x, + list(range(2, len(x.shape))) + + [0, 1]) # [..., batch_size, beam_size] + # use 0 to copy to avoid wrong shape + x = nn.reshape(x, shape=[0] * (len(x.shape) - 2) + + [-1]) # [..., batch_size * beam_size] + x = nn.transpose( + x, [len(x.shape) - 1] + + list(range(0, + len(x.shape) - 1))) # [batch_size * beam_size, ...] + return x + + def _split_batch_beams(self, x): + r""" + Reshape a tensor with shape `[batch_size * beam_size, ...]` to a new + tensor with shape `[batch_size, beam_size, ...]`. + + Parameters: + x(Variable): A tensor with shape `[batch_size * beam_size, ...]`. The + data type should be float32, float64, int32, int64 or bool. + + Returns: + Variable: A tensor with shape `[batch_size, beam_size, ...]`, whose \ + data type is same as `x`. + """ + check_type(x, 'x', (Variable), 'BeamSearchDecoder._split_batch_beams') + # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch + return nn.reshape(x, shape=[-1, self.beam_size] + list(x.shape[1:])) + + def _merge_batch_beams(self, x): + r""" + Reshape a tensor with shape `[batch_size, beam_size, ...]` to a new + tensor with shape `[batch_size * beam_size, ...]`. + + Parameters: + x(Variable): A tensor with shape `[batch_size, beam_size, ...]`. The + data type should be float32, float64, int32, int64 or bool. + + Returns: + Variable: A tensor with shape `[batch_size * beam_size, ...]`, whose \ + data type is same as `x`. + """ + check_type(x, 'x', (Variable), 'BeamSearchDecoder._merge_batch_beams') + # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch + return nn.reshape(x, shape=[-1] + list(x.shape[2:])) + + def _expand_to_beam_size(self, x): + r""" + This function takes a tensor t shaped `[batch_size, s0, s1, ...]` composed + of minibatch entries `t[0], ..., t[batch_size - 1]` and tiles it to have a + shape `[batch_size, beam_size, s0, s1, ...]` composed of minibatch entries + `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated + `beam_size` times. + + Parameters: + x(Variable): A tensor with shape `[batch_size, ...]`, The data type + should be float32, float64, int32, int64 or bool. + + Returns: + Variable: A tensor with shape `[batch_size, beam_size, ...]`, whose \ + data type is same as `x`. + """ + check_type(x, 'x', (Variable), 'BeamSearchDecoder._expand_to_beam_size') + x = nn.unsqueeze(x, [1]) + expand_times = [1] * len(x.shape) + expand_times[1] = self.beam_size + x = paddle.tile(x, expand_times) + return x + + def _mask_probs(self, probs, finished): + r""" + Mask log probabilities. It forces finished beams to allocate all probability + mass to eos and unfinished beams to remain unchanged. + + Parameters: + probs(Variable): A tensor with shape `[batch_size, beam_size, vocab_size]`, + representing the log probabilities. Its data type should be float32 or float64. + finished(Variable): A tensor with shape `[batch_size, beam_size]`, + representing the finished status for all beams. Its data type + should be bool. + + Returns: + Variable: A tensor with the same shape and data type as `x`, \ + where unfinished beams stay unchanged and finished beams are \ + replaced with a tensor with all probability on the EOS token. + """ + check_type(probs, 'probs', (Variable), 'BeamSearchDecoder._mask_probs') + check_type(finished, 'finished', (Variable), + 'BeamSearchDecoder._mask_probs') + # TODO: use where_op + finished = tensor.cast(finished, dtype=probs.dtype) + probs = nn.elementwise_mul( + paddle.tile(nn.unsqueeze(finished, [2]), [1, 1, self.vocab_size]), + self.noend_mask_tensor, + axis=-1) - nn.elementwise_mul(probs, (finished - 1), axis=0) + return probs + + def _gather(self, x, indices, batch_size): + r""" + Gather from the tensor `x` using `indices`. + + Parameters: + x(Variable): A tensor with shape `[batch_size, beam_size, ...]`. + indices(Variable): A `int64` tensor with shape `[batch_size, beam_size]`, + representing the indices that we use to gather. + batch_size(Variable): A tensor with shape `[1]`. Its data type should + be int32 or int64. + + Returns: + Variable: A tensor with the same shape and data type as `x`, \ + representing the gathered tensor. + """ + check_type(x, 'x', (Variable), 'BeamSearchDecoder._gather') + check_type(indices, 'indices', (Variable), 'BeamSearchDecoder._gather') + check_type(batch_size, 'batch_size', (Variable), + 'BeamSearchDecoder._gather') + # TODO: compatibility of int32 and int64 + batch_size = tensor.cast( + batch_size, + indices.dtype) if batch_size.dtype != indices.dtype else batch_size + batch_size.stop_gradient = True # TODO: remove this + batch_pos = paddle.tile( + nn.unsqueeze(tensor.range(0, batch_size, 1, dtype=indices.dtype), + [1]), [1, self.beam_size]) + topk_coordinates = nn.stack([batch_pos, indices], axis=2) + topk_coordinates.stop_gradient = True + return nn.gather_nd(x, topk_coordinates) + + class OutputWrapper( + collections.namedtuple("OutputWrapper", + ("scores", "predicted_ids", "parent_ids"))): + """ + The structure for the returned value `outputs` of `decoder.step`. + A namedtuple includes scores, predicted_ids, parent_ids as fields. + """ + pass + + class StateWrapper( + collections.namedtuple( + "StateWrapper", + ("cell_states", "log_probs", "finished", "lengths"))): + """ + The structure for the argument `states` of `decoder.step`. + A namedtuple includes cell_states, log_probs, finished, lengths as fields. + """ + pass + + def initialize(self, initial_cell_states): + r""" + Initialize the BeamSearchDecoder. + + Parameters: + initial_cell_states(Variable): A (possibly nested structure of) + tensor variable[s]. An argument provided by the caller. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \ + `initial_inputs` is a tensor t filled by `start_token` with shape \ + `[batch_size, beam_size]` when `embedding_fn` is None, or the \ + returned value of `embedding_fn(t)` when `embedding_fn` is provided. \ + `initial_states` is a nested structure(namedtuple including cell_states, \ + log_probs, finished, lengths as fields) of tensor variables, where \ + `log_probs, finished, lengths` all has a tensor value shaped \ + `[batch_size, beam_size]` with data type `float32, bool, int64`. \ + cell_states has a value with the same structure as the input \ + argument `initial_cell_states` but with tiled shape `[batch_size, beam_size, ...]`. \ + `finished` is a `bool` tensor filled by False with shape `[batch_size, beam_size]`. + """ + self.kinf = 1e9 + state = flatten(initial_cell_states)[0] + self.batch_size = nn.shape(state)[0] + + self.start_token_tensor = tensor.fill_constant(shape=[1], + dtype="int64", + value=self.start_token) + self.end_token_tensor = tensor.fill_constant(shape=[1], + dtype="int64", + value=self.end_token) + + init_cell_states = map_structure(self._expand_to_beam_size, + initial_cell_states) + init_inputs = paddle.full(shape=[self.batch_size, self.beam_size], + fill_value=self.start_token_tensor, + dtype=self.start_token_tensor.dtype) + log_probs = paddle.tile( + tensor.assign( + np.array([[0.] + [-self.kinf] * (self.beam_size - 1)], + dtype="float32")), [self.batch_size, 1]) + if paddle.get_default_dtype() == "float64": + log_probs = tensor.cast(log_probs, "float64") + # TODO: remove the restriction of force_cpu + init_finished = tensor.fill_constant_batch_size_like( + input=state, + shape=[-1, self.beam_size], + dtype="bool", + value=False, + force_cpu=True) + init_lengths = tensor.zeros_like(init_inputs) + init_inputs = self.embedding_fn( + init_inputs) if self.embedding_fn else init_inputs + return init_inputs, self.StateWrapper(init_cell_states, log_probs, + init_finished, + init_lengths), init_finished + + def _beam_search_step(self, time, logits, next_cell_states, beam_state): + r""" + Calculate scores and select candidate token ids. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the caller, + representing the current time step number of decoding. + logits(Variable): A tensor with shape `[batch_size, beam_size, vocab_size]`, + representing the logits at the current time step. Its data type is float32. + next_cell_states(Variable): A (possibly nested structure of) tensor variable[s]. + It has the same structure, shape and data type as the `cell_states` of + `initial_states` returned by `initialize()`. It represents the next state + from the cell. + beam_state(Variable): A structure of tensor variables. + It is same as the `initial_states` returned by `initialize()` for + the first decoding step and `beam_search_state` returned by + `step()` for the others. + + Returns: + tuple: A tuple( :code:`(beam_search_output, beam_search_state)` ). \ + `beam_search_output` is a namedtuple(including scores, predicted_ids, \ + parent_ids as fields) of tensor variables, where \ + `scores, predicted_ids, parent_ids` all has a tensor value shaped \ + `[batch_size, beam_size]` with data type `float32, int64, int64`. + `beam_search_state` has the same structure, shape and data type \ + as the input argument `beam_state`. + + """ + self.vocab_size = logits.shape[-1] + self.vocab_size_tensor = tensor.fill_constant(shape=[1], + dtype="int64", + value=self.vocab_size) + noend_array = [-self.kinf] * self.vocab_size + noend_array[self.end_token] = 0 + + self.noend_mask_tensor = tensor.assign(np.array(noend_array, "float32")) + if paddle.get_default_dtype() == "float64": + self.noend_mask_tensor = tensor.cast(self.noend_mask_tensor, + "float64") + + step_log_probs = nn.log(nn.softmax(logits)) + step_log_probs = self._mask_probs(step_log_probs, beam_state.finished) + log_probs = nn.elementwise_add(x=step_log_probs, + y=beam_state.log_probs, + axis=0) + # TODO: length penalty + scores = log_probs + scores = nn.reshape(scores, [-1, self.beam_size * self.vocab_size]) + # TODO: add grad for topk then this beam search can be used to train + topk_scores, topk_indices = paddle.topk(x=scores, k=self.beam_size) + beam_indices = nn.elementwise_floordiv(topk_indices, + self.vocab_size_tensor) + token_indices = nn.elementwise_mod(topk_indices, self.vocab_size_tensor) + next_log_probs = self._gather( + nn.reshape(log_probs, [-1, self.beam_size * self.vocab_size]), + topk_indices, self.batch_size) + next_cell_states = map_structure( + lambda x: self._gather(x, beam_indices, self.batch_size), + next_cell_states) + next_finished = self._gather(beam_state.finished, beam_indices, + self.batch_size) + next_lengths = self._gather(beam_state.lengths, beam_indices, + self.batch_size) + next_lengths = next_lengths + tensor.cast(nn.logical_not(next_finished), + beam_state.lengths.dtype) + next_finished = control_flow.logical_or( + next_finished, + control_flow.equal(token_indices, self.end_token_tensor)) + + beam_search_output = self.OutputWrapper(topk_scores, token_indices, + beam_indices) + beam_search_state = self.StateWrapper(next_cell_states, next_log_probs, + next_finished, next_lengths) + return beam_search_output, beam_search_state + + def step(self, time, inputs, states, **kwargs): + r""" + Perform a beam search decoding step, which uses `cell` to get probabilities, + and follows a beam search step to calculate scores and select candidate + token ids. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the caller, + representing the current time step number of decoding. + inputs(Variable): A tensor variable. It is same as `initial_inputs` + returned by `initialize()` for the first decoding step and + `next_inputs` returned by `step()` for the others. + states(Variable): A structure of tensor variables. + It is same as the `initial_states` returned by `initialize()` for + the first decoding step and `beam_search_state` returned by + `step()` for the others. + **kwargs: Additional keyword arguments, provided by the caller. + + Returns: + tuple: A tuple( :code:`(beam_search_output, beam_search_state, next_inputs, finished)` ). \ + `beam_search_state` and `next_inputs` have the same structure, \ + shape and data type as the input arguments `states` and `inputs` separately. \ + `beam_search_output` is a namedtuple(including scores, predicted_ids, \ + parent_ids as fields) of tensor variables, where \ + `scores, predicted_ids, parent_ids` all has a tensor value shaped \ + `[batch_size, beam_size]` with data type `float32, int64, int64`. \ + `finished` is a `bool` tensor with shape `[batch_size, beam_size]`. + """ + inputs = map_structure(self._merge_batch_beams, inputs) + cell_states = map_structure(self._merge_batch_beams, states.cell_states) + cell_outputs, next_cell_states = self.cell(inputs, cell_states, + **kwargs) + cell_outputs = map_structure(self._split_batch_beams, cell_outputs) + next_cell_states = map_structure(self._split_batch_beams, + next_cell_states) + + if self.output_fn is not None: + cell_outputs = self.output_fn(cell_outputs) + + beam_search_output, beam_search_state = self._beam_search_step( + time=time, + logits=cell_outputs, + next_cell_states=next_cell_states, + beam_state=states) + finished = beam_search_state.finished + sample_ids = beam_search_output.predicted_ids + sample_ids.stop_gradient = True + next_inputs = self.embedding_fn( + sample_ids) if self.embedding_fn else sample_ids + + return (beam_search_output, beam_search_state, next_inputs, finished) + + def finalize(self, outputs, final_states, sequence_lengths): + r""" + Use `gather_tree` to backtrace along the beam search tree and construct + the full predicted sequences. + + Parameters: + outputs(Variable): A structure(namedtuple) of tensor variables, + The structure and data type is same as `output_dtype`. + The tensor stacks all time steps' output thus has shape + `[time_step, batch_size, ...]`, which is done by the caller. + final_states(Variable): A structure(namedtuple) of tensor variables. + It is the `next_states` returned by `decoder.step` at last + decoding step, thus has the same structure, shape and data type + with states at any time step. + sequence_lengths(Variable): An `int64` tensor shaped `[batch_size, beam_size]`. + It contains sequence lengths for each beam determined during + decoding. + + Returns: + tuple: A tuple( :code:`(predicted_ids, final_states)` ). \ + `predicted_ids` is an `int64` tensor shaped \ + `[time_step, batch_size, beam_size]`. `final_states` is the same \ + as the input argument `final_states`. + """ + predicted_ids = nn.gather_tree(outputs.predicted_ids, + outputs.parent_ids) + # TODO: use FinalBeamSearchDecoderOutput as output + return predicted_ids, final_states + + @property + def tracks_own_finished(self): + """ + BeamSearchDecoder reorders its beams and their finished state. Thus it + conflicts with `dynamic_decode` function's tracking of finished states. + Setting this property to true to avoid early stopping of decoding due + to mismanagement of the finished state. + + Returns: + bool: A python bool `True`. + """ + return True + + +def _dynamic_decode_imperative(decoder, + inits=None, + max_step_num=None, + output_time_major=False, + impute_finished=False, + is_test=False, + return_length=False, + **kwargs): + + def _maybe_copy(state, new_state, step_mask): + # TODO: use where_op + state_dtype = state.dtype + if convert_dtype(state_dtype) in ["bool"]: + state = tensor.cast(state, dtype="float32") + new_state = tensor.cast(new_state, dtype="float32") + if step_mask.dtype != state.dtype: + step_mask = tensor.cast(step_mask, dtype=state.dtype) + # otherwise, renamed bool gradients of would be summed up leading + # to sum(bool) error. + step_mask.stop_gradient = True + new_state = nn.elementwise_mul( + state, step_mask, axis=0) - nn.elementwise_mul(new_state, + (step_mask - 1), + axis=0) + if convert_dtype(state_dtype) in ["bool"]: + new_state = tensor.cast(new_state, dtype=state_dtype) + return new_state + + initial_inputs, initial_states, initial_finished = decoder.initialize(inits) + inputs, states, finished = (initial_inputs, initial_states, + initial_finished) + cond = control_flow.logical_not((nn.reduce_all(initial_finished))) + sequence_lengths = tensor.cast(tensor.zeros_like(initial_finished), "int64") + outputs = None + + step_idx = 0 + step_idx_tensor = tensor.fill_constant(shape=[1], + dtype="int64", + value=step_idx) + while cond.numpy(): + (step_outputs, next_states, next_inputs, + next_finished) = decoder.step(step_idx_tensor, inputs, states, + **kwargs) + if not decoder.tracks_own_finished: + # BeamSearchDecoder would track it own finished, since + # beams would be reordered and the finished status of each + # entry might change. Otherwise, perform logical OR which + # would not change the already finished. + next_finished = control_flow.logical_or(next_finished, finished) + # To confirm states.finished/finished be consistent with + # next_finished. + tensor.assign(next_finished, finished) + next_sequence_lengths = nn.elementwise_add( + sequence_lengths, + tensor.cast(control_flow.logical_not(finished), + sequence_lengths.dtype)) + if impute_finished: # rectify the states for the finished. + next_states = map_structure( + lambda x, y: _maybe_copy(x, y, finished), states, + next_states) + else: + warnings.warn( + "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros." + ) if not hasattr(next_states, "lengths") else None + next_sequence_lengths = getattr(next_states, "lengths", + sequence_lengths) + + outputs = map_structure( + lambda x: ArrayWrapper(x), + step_outputs) if step_idx == 0 else map_structure( + lambda x, x_array: x_array.append(x), step_outputs, outputs) + inputs, states, finished, sequence_lengths = (next_inputs, next_states, + next_finished, + next_sequence_lengths) + + control_flow.increment(x=step_idx_tensor, value=1.0, in_place=True) + step_idx += 1 + + cond = control_flow.logical_not(nn.reduce_all(finished)) + if max_step_num is not None and step_idx > max_step_num: + break + + final_outputs = map_structure(lambda x: nn.stack(x.array, axis=0), outputs) + final_states = states + + try: + final_outputs, final_states = decoder.finalize(final_outputs, + final_states, + sequence_lengths) + except NotImplementedError: + pass + + if not output_time_major: + final_outputs = map_structure( + lambda x: nn.transpose(x, [1, 0] + list(range(2, len(x.shape)))), + final_outputs) + + return (final_outputs, final_states, + sequence_lengths) if return_length else (final_outputs, + final_states) + + +def _dynamic_decode_declarative(decoder, + inits=None, + max_step_num=None, + output_time_major=False, + impute_finished=False, + is_test=False, + return_length=False, + **kwargs): + initial_inputs, initial_states, initial_finished = decoder.initialize(inits) + global_inputs, global_states, global_finished = (initial_inputs, + initial_states, + initial_finished) + global_finished.stop_gradient = True + step_idx = tensor.fill_constant(shape=[1], dtype="int64", value=0) + + cond = control_flow.logical_not((nn.reduce_all(initial_finished))) + if max_step_num is not None: + max_step_num = tensor.fill_constant(shape=[1], + dtype="int64", + value=max_step_num) + while_op = control_flow.While(cond, is_test=is_test) + + sequence_lengths = tensor.cast(tensor.zeros_like(initial_finished), "int64") + sequence_lengths.stop_gradient = True + + if is_test: + # for test, reuse inputs and states variables to save memory + inputs = map_structure(lambda x: x, initial_inputs) + states = map_structure(lambda x: x, initial_states) + else: + # inputs and states of all steps must be saved for backward and training + inputs_arrays = map_structure( + lambda x: control_flow.array_write(x, step_idx), initial_inputs) + states_arrays = map_structure( + lambda x: control_flow.array_write(x, step_idx), initial_states) + + def _maybe_copy(state, new_state, step_mask): + # TODO: use where_op + state_dtype = state.dtype + if convert_dtype(state_dtype) in ["bool"]: + state = tensor.cast(state, dtype="float32") + new_state = tensor.cast(new_state, dtype="float32") + if step_mask.dtype != state.dtype: + step_mask = tensor.cast(step_mask, dtype=state.dtype) + # otherwise, renamed bool gradients of would be summed up leading + # to sum(bool) error. + step_mask.stop_gradient = True + new_state = nn.elementwise_mul( + state, step_mask, axis=0) - nn.elementwise_mul(new_state, + (step_mask - 1), + axis=0) + if convert_dtype(state_dtype) in ["bool"]: + new_state = tensor.cast(new_state, dtype=state_dtype) + return new_state + + def _transpose_batch_time(x): + return nn.transpose(x, [1, 0] + list(range(2, len(x.shape)))) + + def _create_array_out_of_while(dtype): + current_block_idx = default_main_program().current_block_idx + default_main_program().current_block_idx = default_main_program( + ).current_block().parent_idx + tensor_array = control_flow.create_array(dtype) + default_main_program().current_block_idx = current_block_idx + return tensor_array + + # While + with while_op.block(): + if not is_test: + inputs = map_structure( + lambda array: control_flow.array_read(array, step_idx), + inputs_arrays) + states = map_structure( + lambda array: control_flow.array_read(array, step_idx), + states_arrays) + (outputs, next_states, next_inputs, + next_finished) = decoder.step(step_idx, inputs, states, **kwargs) + if not decoder.tracks_own_finished: + # BeamSearchDecoder would track it own finished, since beams would + # be reordered and the finished status of each entry might change. + # Otherwise, perform logical OR which would not change the already + # finished. + next_finished = control_flow.logical_or(next_finished, + global_finished) + next_sequence_lengths = nn.elementwise_add( + sequence_lengths, + tensor.cast(control_flow.logical_not(global_finished), + sequence_lengths.dtype)) + if impute_finished: # rectify the states for the finished. + next_states = map_structure( + lambda x, y: _maybe_copy(x, y, global_finished), + states, + next_states, + ) + else: + warnings.warn( + "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros." + ) if not hasattr(next_states, "lengths") else None + next_sequence_lengths = getattr(next_states, "lengths", + sequence_lengths) + + # create tensor array in global block after dtype[s] of outputs can be got + outputs_arrays = map_structure( + lambda x: _create_array_out_of_while(x.dtype), outputs) + + map_structure( + lambda x, x_array: control_flow.array_write( + x, i=step_idx, array=x_array), outputs, outputs_arrays) + control_flow.increment(x=step_idx, value=1.0, in_place=True) + # update the global_finished first, since it might be also in states of + # decoder, which otherwise would write a stale finished status to array + tensor.assign(next_finished, global_finished) + tensor.assign(next_sequence_lengths, sequence_lengths) + if is_test: + map_structure(tensor.assign, next_inputs, global_inputs) + map_structure(tensor.assign, next_states, global_states) + else: + map_structure( + lambda x, x_array: control_flow.array_write( + x, i=step_idx, array=x_array), next_inputs, inputs_arrays) + map_structure( + lambda x, x_array: control_flow.array_write( + x, i=step_idx, array=x_array), next_states, states_arrays) + if max_step_num is not None: + control_flow.logical_and( + control_flow.logical_not(nn.reduce_all(global_finished)), + control_flow.less_equal(step_idx, max_step_num), cond) + else: + control_flow.logical_not(nn.reduce_all(global_finished), cond) + + final_outputs = map_structure( + lambda array: tensor.tensor_array_to_tensor( + array, axis=0, use_stack=True)[0], outputs_arrays) + if is_test: + final_states = global_states + else: + final_states = map_structure( + lambda array: control_flow.array_read(array, step_idx), + states_arrays) + + try: + final_outputs, final_states = decoder.finalize(final_outputs, + final_states, + sequence_lengths) + except NotImplementedError: + pass + + if not output_time_major: + final_outputs = map_structure(_transpose_batch_time, final_outputs) + + return (final_outputs, final_states, + sequence_lengths) if return_length else (final_outputs, + final_states) + + +def dynamic_decode(decoder, + inits=None, + max_step_num=None, + output_time_major=False, + impute_finished=False, + is_test=False, + return_length=False, + **kwargs): + r""" + Dynamic decoding performs :code:`decoder.step()` repeatedly until the returned + Tensor indicating finished status contains all True values or the number of + decoding step reaches to :attr:`max_step_num`. + + :code:`decoder.initialize()` would be called once before the decoding loop. + If the `decoder` has implemented `finalize` method, :code:`decoder.finalize()` + would be called once after the decoding loop. + + Parameters: + decoder(Decoder): An instance of `Decoder`. + inits(object, optional): Argument passed to `decoder.initialize`. + Default `None`. + max_step_num(int, optional): The maximum number of steps. If not provided, + decode until the decoder is fully done, or in other words, the returned + Tensor by :code:`decoder.step()` indicating finished status contains + all True. Default `None`. + output_time_major(bool, optional): Indicate the data layout of Tensor included + in the final outputs(the first returned value of this method). If + attr:`False`, the data layout would be batch major with shape + `[batch_size, seq_len, ...]`. If attr:`True`, the data layout would + be time major with shape `[seq_len, batch_size, ...]`. Default: `False`. + impute_finished(bool, optional): If `True` and `decoder.tracks_own_finished` + is False, then states get copied through for batch entries which are + marked as finished, which differs with the unfinished using the new states + returned by :code:`decoder.step()` and ensures that the final states have + the correct values. Otherwise, states wouldn't be copied through when + finished. If the returned `final_states` is needed, it should be set as + True, which causes some slowdown. Default `False`. + is_test(bool, optional): A flag indicating whether to use test mode. In + test mode, it is more memory saving. Default `False`. + return_length(bool, optional): A flag indicating whether to return an + extra Tensor variable in the output tuple, which stores the actual + lengths of all decoded sequences. Default `False`. + **kwargs: Additional keyword arguments. Arguments passed to `decoder.step`. + + Returns: + tuple: A tuple( :code:`(final_outputs, final_states, sequence_lengths)` ) \ + when `return_length` is True, otherwise a tuple( :code:`(final_outputs, final_states)` ). \ + The final outputs and states, both are Tensor or nested structure of Tensor. \ + `final_outputs` has the same structure and data types as the :code:`outputs` \ + returned by :code:`decoder.step()` , and each Tenser in `final_outputs` \ + is the stacked of all decoding steps' outputs, which might be revised \ + by :code:`decoder.finalize()` if the decoder has implemented `finalize`. \ + `final_states` is the counterpart at last time step of initial states \ + returned by :code:`decoder.initialize()` , thus has the same structure \ + with it and has tensors with same shapes and data types. `sequence_lengths` \ + is an `int64` tensor with the same shape as `finished` returned \ + by :code:`decoder.initialize()` , and it stores the actual lengths of \ + all decoded sequences. + + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.nn import BeamSearchDecoder, dynamic_decode + from paddle.nn import GRUCell, Linear, Embedding + trg_embeder = Embedding(100, 32) + output_layer = Linear(32, 32) + decoder_cell = GRUCell(input_size=32, hidden_size=32) + decoder = BeamSearchDecoder(decoder_cell, + start_token=0, + end_token=1, + beam_size=4, + embedding_fn=trg_embeder, + output_fn=output_layer) + encoder_output = paddle.ones((4, 8, 32), dtype=paddle.get_default_dtype()) + outputs = dynamic_decode(decoder=decoder, + inits=decoder_cell.get_initial_states(encoder_output), + max_step_num=10) + """ + if _non_static_mode(): + return _dynamic_decode_imperative(decoder, inits, max_step_num, + output_time_major, impute_finished, + is_test, return_length, **kwargs) + else: + return _dynamic_decode_declarative(decoder, inits, max_step_num, + output_time_major, impute_finished, + is_test, return_length, **kwargs) + + +class DecodeHelper(object): + """ + DecodeHelper is the base class for any helper instance used in `BasicDecoder`. + It provides interface to implement sampling and produce inputs for the next + time step in dynamic decoding. + """ + + def initialize(self): + r""" + DecodeHelper initialization to produce inputs for the first decoding step + and give the initial status telling whether each sequence in the batch + is finished. It is the partial of the initialization of `BasicDecoder`. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \ + `initial_inputs` is a (possibly nested structure of) tensor \ + variable[s], and the tensor's shape is `[batch_size, ...]`. \ + `initial_finished` is a bool tensor with shape `[batch_size]`. + """ + pass + + def sample(self, time, outputs, states): + """ + Perform sampling with some strategies according to `outputs`. It is the + partial of `BasicDecoder.step`. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the caller, + representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + + Returns: + Variable: An `int64` tensor representing the sampled ids. + """ + pass + + def next_inputs(self, time, outputs, states, sample_ids): + r""" + Produce the inputs and states for next time step and give status telling + whether each minibatch entry is finished. It is called after `sample` in + `BasicDecoder.step`. It is the partial of `BasicDecoder.step`. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the caller, + representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + sample_ids(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `sample_ids` returned by `sample()`. + + Returns: + tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \ + `next_inputs` and `next_states` both are a (possibly nested \ + structure of) tensor variable[s], and the structure, shape and \ + data type of `next_states` must be same as the input argument \ + `states`. `finished` is a bool tensor with shape `[batch_size]`. + """ + pass + + +class TrainingHelper(DecodeHelper): + """ + TrainingHelper is a subclass of DecodeHelper. It is a decoding helper + slicing from the full sequence inputs as the inputs for corresponding + step. And it uses `argmax` to sample from the outputs of `cell.call()`. + + Since the needs of sequence inputs, it is used mostly for teach-forcing MLE + (maximum likelihood) training, and the sampled would not be used. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + trg_emb = fluid.data(name="trg_emb", + shape=[None, None, 128], + dtype="float32") + trg_seq_length = fluid.data(name="trg_seq_length", + shape=[None], + dtype="int64") + helper = layers.TrainingHelper(trg_emb, trg_seq_length) + decoder_cell = layers.GRUCell(hidden_size=128) + decoder = layers.BasicDecoder(decoder_cell, helper) + outputs = layers.dynamic_decode( + decoder, + inits=decoder_cell.get_initial_states(trg_emb), + is_test=False) + """ + + def __init__(self, inputs, sequence_length, time_major=False): + """ + Constructor of TrainingHelper. + + Parameters: + inputs(Variable): A (possibly nested structure of) tensor variable[s]. + The shape of tensor should be `[batch_size, sequence_length, ...]` + for `time_major == False` or `[sequence_length, batch_size, ...]` + for `time_major == True`. It represents the inputs to be sliced + from at every decoding step. + sequence_length(Variable): A tensor with shape `[batch_size]`. + It stores real length of each instance in `inputs`, by which we + can label the finished status of each instance at every decoding + step. + time_major(bool, optional): Indicate the data layout of Tensor included + in `inputs`. If `False`, the data layout would be batch major with + shape `[batch_size, sequence_length, ...]`. If `True`, the data + layout would be time major with shape `[sequence_length, batch_size, ...]`. + Default: `False`. + """ + self.inputs = inputs + self.sequence_length = sequence_length + self.time_major = time_major + # extend inputs to avoid to slice out of range in `next_inputs` + # may be easier and have better performance than condition_op + self.inputs_ = map_structure( + lambda x: nn.pad(x, + paddings=([0, 1] + [0, 0] * (len(x.shape) - 1)) + if time_major else ([0, 0, 0, 1] + [0, 0] * + (len(x.shape) - 2))), + self.inputs) + + def initialize(self): + r""" + TrainingHelper initialization produces inputs for the first decoding + step by slicing at the first time step of full sequence inputs, and it + gives initial status telling whether each sequence in the batch is + finished. It is the partial of the initialization of `BasicDecoder`. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \ + `initial_inputs` is a (possibly nested structure of) tensor \ + variable[s], and the tensor's shape is `[batch_size, ...]`. \ + `initial_finished` is a bool tensor with shape `[batch_size]`. + """ + init_finished = control_flow.equal( + self.sequence_length, + tensor.fill_constant(shape=[1], + dtype=self.sequence_length.dtype, + value=0)) + # TODO: support zero length + init_inputs = map_structure( + lambda x: x[0] if self.time_major else x[:, 0], self.inputs) + return init_inputs, init_finished + + def sample(self, time, outputs, states): + r""" + Perform sampling by using `argmax` according to the `outputs`. Mostly + the sampled ids would not be used since the inputs for next decoding + step would be got by slicing. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the + caller, representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + + Returns: + Variable: An `int64` tensor with shape `[batch_size]`, representing \ + the sampled ids. + """ + sample_ids = tensor.argmax(outputs, axis=-1) + return sample_ids + + def next_inputs(self, time, outputs, states, sample_ids): + r""" + Generate inputs for the next decoding step by slicing at corresponding + step of the full sequence inputs. Simultaneously, produce the states + for next time step by directly using the input `states` and emit status + telling whether each minibatch entry reaches to the corresponding length. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the + caller, representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`. + It is same as `sample_ids` returned by `sample()`. + + Returns: + tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \ + `next_inputs` and `next_states` both are a (possibly nested \ + structure of) tensor variable[s], and the tensor's shape is \ + `[batch_size, ...]`. `next_states` is identical to the input \ + argument `states`. `finished` is a `bool` Tensor with \ + shape `[batch_size]`. + """ + # TODO: compatibility of int32 and int64 + time = tensor.cast(time, "int32") if convert_dtype( + time.dtype) not in ["int32"] else time + if self.sequence_length.dtype != time.dtype: + self.sequence_length = tensor.cast(self.sequence_length, time.dtype) + next_time = time + 1 + finished = control_flow.less_equal(self.sequence_length, next_time) + + def _slice(x): # TODO: use Variable.__getitem__ + axes = [0 if self.time_major else 1] + return nn.squeeze(nn.slice(x, + axes=axes, + starts=[next_time], + ends=[next_time + 1]), + axes=axes) + + next_inputs = map_structure(_slice, self.inputs_) + return finished, next_inputs, states + + +class GreedyEmbeddingHelper(DecodeHelper): + """ + GreedyEmbeddingHelper is a subclass of DecodeHelper. It is a decoding helper + uses the argmax of the output (treated as logits) and passes the results + through an embedding layer to get inputs for the next decoding step. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + trg_emb = fluid.data(name="trg_emb", + shape=[None, None, 128], + dtype="float32") + + trg_embeder = lambda x: fluid.embedding( + x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding")) + output_layer = lambda x: layers.fc(x, + size=10000, + num_flatten_dims=len(x.shape) - 1, + param_attr=fluid.ParamAttr(name= + "output_w"), + bias_attr=False) + helper = layers.GreedyEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1) + decoder_cell = layers.GRUCell(hidden_size=128) + decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer) + outputs = layers.dynamic_decode( + decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output)) + """ + + def __init__(self, embedding_fn, start_tokens, end_token): + r""" + Constructor of GreedyEmbeddingHelper. + + Parameters: + embedding_fn(callable): A functor to apply on the argmax results. + Mostly it is an embedding layer to transform ids to embeddings. + **Note that fluid.embedding should be used here rather than + fluid.layers.embedding, since shape of ids is [batch_size]. + when using fluid.layers.embedding, must unsqueeze in embedding_fn.** + start_tokens(Variable): A `int64` tensor shaped `[batch_size]`, + representing the start tokens. + end_token(int): The end token id. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \ + `initial_inputs` and `initial_states` both are a (possibly nested \ + structure of) tensor variable[s], and `finished` is a tensor with \ + bool data type. + """ + self.embedding_fn = embedding_fn + self.start_tokens = start_tokens + self.end_token = tensor.fill_constant(shape=[1], + dtype="int64", + value=end_token) + + def initialize(self): + r""" + GreedyEmbeddingHelper initialization produces inputs for the first decoding + step by using `start_tokens` of the constructor, and gives initial + status telling whether each sequence in the batch is finished. + It is the partial of the initialization of `BasicDecoder`. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_finished)` ). \ + `initial_inputs` is same as `start_tokens` of the constructor. \ + `initial_finished` is a `bool` tensor filled by False and has \ + the same shape as `start_tokens`. + """ + # TODO: remove the restriction of force_cpu + init_finished = tensor.fill_constant_batch_size_like( + input=self.start_tokens, + shape=[-1], + dtype="bool", + value=False, + force_cpu=True) + init_inputs = self.embedding_fn(self.start_tokens) + return init_inputs, init_finished + + def sample(self, time, outputs, states): + r""" + Perform sampling by using `argmax` according to the `outputs`. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the + caller, representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + + Returns: + Variable: An `int64` tensor with shape `[batch_size]`, representing \ + the sampled ids. + """ + sample_ids = tensor.argmax(outputs, axis=-1) + return sample_ids + + def next_inputs(self, time, outputs, states, sample_ids): + r""" + Generate inputs for the next decoding step by applying `embedding_fn` + to `sample_ids`. Simultaneously, produce the states for next time step + by directly using the input `states` and emit status telling whether + each minibatch entry gets an `end_token` sample. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the + caller, representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + sample_ids(Variable): An `int64` tensor variable shaped `[batch_size]`. + It is same as `sample_ids` returned by `sample()`. + + Returns: + tuple: A tuple( :code:`(finished, next_inputs, next_states)` ). \ + `next_inputs` and `next_states` both are a (possibly nested \ + structure of) tensor variable[s], and the tensor's shape is \ + `[batch_size, ...]`. `next_states` is identical to the input \ + argument `states`. `finished` is a `bool` Tensor with \ + shape `[batch_size]`. + """ + finished = control_flow.equal(sample_ids, self.end_token) + next_inputs = self.embedding_fn(sample_ids) + return finished, next_inputs, states + + +class SampleEmbeddingHelper(GreedyEmbeddingHelper): + """ + SampleEmbeddingHelper is a subclass of GreedyEmbeddingHelper. It is a decoding + helper uses sampling (from a distribution) instead of argmax of the output + (treated as logits) and passes the results through an embedding layer to get + inputs for the next decoding step. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + trg_emb = fluid.data(name="trg_emb", + shape=[None, None, 128], + dtype="float32") + + trg_embeder = lambda x: fluid.embedding( + x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding")) + output_layer = lambda x: layers.fc(x, + size=10000, + num_flatten_dims=len(x.shape) - 1, + param_attr=fluid.ParamAttr(name= + "output_w"), + bias_attr=False) + helper = layers.SampleEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1) + decoder_cell = layers.GRUCell(hidden_size=128) + decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer) + outputs = layers.dynamic_decode( + decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output)) + """ + + def __init__(self, + embedding_fn, + start_tokens, + end_token, + softmax_temperature=None, + seed=None): + r""" + Constructor of SampleEmbeddingHelper. + + Parameters: + embedding_fn(callable): A functor to apply on the argmax results. + Mostly it is an embedding layer to transform ids to embeddings. + **Note that fluid.embedding should be used here rather than + fluid.layers.embedding, since shape of ids is [batch_size]. + when using fluid.layers.embedding, must unsqueeze in embedding_fn.** + start_tokens(Variable): A `int64` tensor shaped `[batch_size]`, + representing the start tokens. + end_token(int): The end token id. + softmax_temperature(float, optional): the value to divide the logits + by before computing the softmax. Higher temperatures (above 1.0) + lead to more random, while lower temperatures push the sampling + distribution towards the argmax. It must be strictly greater than + 0. Defaults to None, meaning using a temperature valued 1.0. + seed: (int, optional) The sampling seed. Defaults to None, meaning not + to use fixed seed. + + Returns: + tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \ + `initial_inputs` and `initial_states` both are a (possibly nested \ + structure of) tensor variable[s], and `finished` is a tensor with \ + bool data type. + """ + super(SampleEmbeddingHelper, self).__init__(embedding_fn, start_tokens, + end_token) + self.softmax_temperature = tensor.fill_constant( + shape=[1], dtype="float32", value=softmax_temperature + ) if softmax_temperature is not None else None + self.seed = seed + + def sample(self, time, outputs, states): + r""" + Perform sampling from a categorical distribution, and the distribution + is computed by `softmax(outputs/softmax_temperature)`. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the + caller, representing the current time step number of decoding. + outputs(Variable): A tensor variable. Usually it's data type is float32 + or float64, and it's shape is `[batch_size, vocabulary_size]`, + representing the predicted logits of current step. It is same as + `outputs` returned by `BasicDecoder.output_fn(BasicDecoder.cell.call())`. + states(Variable): A (possibly nested structure of) tensor variable[s]. + It is same as `new_states` returned by `BasicDecoder.cell.call()`. + + Returns: + Variable: An `int64` tensor with shape `[batch_size]`, representing \ + the sampled ids. + """ + logits = (outputs / self.softmax_temperature + ) if self.softmax_temperature is not None else outputs + probs = nn.softmax(logits) + # TODO: remove this stop_gradient. The stop_gradient of sample_ids can + # not pass to probs, since sampling_id op does not have corresponding + # grad op and thus can not pass. + probs.stop_gradient = True + sample_ids = nn.sampling_id(probs, + seed=self.seed, + dtype=self.start_tokens.dtype) + return sample_ids + + +class BasicDecoder(Decoder): + """ + BasicDecoder is a subclass of Decoder and assembles a RNNCell and DecodeHelper + instance as members, where the DecodeHelper helps to implement customed + decoding strategies.. It performs one decoding step as following steps: + + 1. Perform `cell_outputs, cell_states = cell.call(inputs, states)` + to get outputs and new states from cell. + + 2. Perform `sample_ids = helper.sample(time, cell_outputs, cell_states)` + to sample ids as decoded results of the current time step. + + 3. Perform `finished, next_inputs, next_states = helper.next_inputs(time, + cell_outputs, cell_states, sample_ids)` to generate inputs, states and + finished status for the next decoding step. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + trg_emb = fluid.data(name="trg_emb", + shape=[None, None, 128], + dtype="float32") + + trg_embeder = lambda x: fluid.embedding( + x, size=[10000, 128], param_attr=fluid.ParamAttr(name="trg_embedding")) + output_layer = lambda x: layers.fc(x, + size=10000, + num_flatten_dims=len(x.shape) - 1, + param_attr=fluid.ParamAttr(name= + "output_w"), + bias_attr=False) + helper = layers.SampleEmbeddingHelper(trg_embeder, start_tokens=0, end_token=1) + decoder_cell = layers.GRUCell(hidden_size=128) + decoder = layers.BasicDecoder(decoder_cell, helper, output_fn=output_layer) + outputs = layers.dynamic_decode( + decoder=decoder, inits=decoder_cell.get_initial_states(encoder_output)) + """ + + def __init__(self, cell, helper, output_fn=None): + """ + Constructor of BasicDecoder. + + Parameters: + cell(RNNCell): An instance of `RNNCell` or object with the same interface. + helper(DecodeHelper): An instance of `DecodeHelper`. + output_fn(optional): A callable to apply to the cell's output prior to + sampling. Default None. + """ + self.cell = cell + self.helper = helper + self.output_fn = output_fn + + def initialize(self, initial_cell_states): + r""" + BasicDecoder initialization includes helper initialization and cell + initialization, and cell initialization uses `initial_cell_states` as + the result directly. + + Parameters: + initial_cell_states(Variable): A (possibly nested structure of) + tensor variable[s]. An argument provided by the caller `dynamic_decode`. + + Returns: + tuple: A tuple( :code:(initial_inputs, initial_cell_states, finished)` ). \ + `initial_inputs` and `initial_states` both are a (possibly nested \ + structure of) tensor variable[s], and `finished` is a tensor with \ + bool data type. `initial_inputs` and `finished` are the results \ + of `helper.initialize()`, and `initial_cell_states` is same as \ + the input argument counterpart. + """ + (initial_inputs, initial_finished) = self.helper.initialize() + return initial_inputs, initial_cell_states, initial_finished + + class OutputWrapper( + collections.namedtuple("OutputWrapper", + ("cell_outputs", "sample_ids"))): + """ + The structure for the returned value `outputs` of `decoder.step`. + A namedtuple includes cell_outputs, sample_ids as fields. + """ + pass + + def step(self, time, inputs, states, **kwargs): + r""" + Perform one decoding step as following steps: + + 1. Perform `cell_outputs, cell_states = cell.call(inputs, states)` + to get outputs and new states from cell. + + 2. Perform `sample_ids = helper.sample(time, cell_outputs, cell_states)` + to sample ids as decoded results of the current time step. + + 3. Perform `finished, next_inputs, next_states = helper.next_inputs(time, + cell_outputs, cell_states, sample_ids)` to generate inputs, states and + finished status for the next decoding step. + + Parameters: + time(Variable): An `int64` tensor with shape `[1]` provided by the caller, + representing the current time step number of decoding. + inputs(Variable): A tensor variable. It is same as `initial_inputs` + returned by `initialize()` for the first decoding step and + `next_inputs` returned by `step()` for the others. + states(Variable): A structure of tensor variables. + It is same as the `initial_cell_states` returned by `initialize()` + for the first decoding step and `next_states` returned by + `step()` for the others. + **kwargs: Additional keyword arguments, provided by the caller + `dynamic_decode`. + + Returns: + tuple: A tuple( :code:`(outputs, next_states, next_inputs, finished)` ). \ + `outputs` is a namedtuple(including cell_outputs, sample_ids, \ + as fields) of tensor variables, where `cell_outputs` is the result \ + fof `cell.call()` and `sample_ids` is the result of `helper.sample()`. \ + `next_states` and `next_inputs` have the same structure, shape \ + and data type as the input arguments `states` and `inputs` separately. \ + `finished` is a `bool` tensor with shape `[batch_size]`. + """ + cell_outputs, cell_states = self.cell(inputs, states, **kwargs) + if self.output_fn is not None: + cell_outputs = self.output_fn(cell_outputs) + sample_ids = self.helper.sample(time=time, + outputs=cell_outputs, + states=cell_states) + sample_ids.stop_gradient = True + (finished, next_inputs, + next_states) = self.helper.next_inputs(time=time, + outputs=cell_outputs, + states=cell_states, + sample_ids=sample_ids) + outputs = self.OutputWrapper(cell_outputs, sample_ids) + return (outputs, next_states, next_inputs, finished) + + +def dynamic_lstm(input, + size, + h_0=None, + c_0=None, + param_attr=None, + bias_attr=None, + use_peepholes=True, + is_reverse=False, + gate_activation='sigmoid', + cell_activation='tanh', + candidate_activation='tanh', + dtype='float32', + name=None): + r""" + :api_attr: Static Graph + + **Note**: + 1. This OP only supports LoDTensor as inputs. If you need to deal with Tensor, please use :ref:`api_fluid_layers_lstm` . + 2. In order to improve efficiency, users must first map the input of dimension [T, hidden_size] to input of [T, 4 * hidden_size], and then pass it to this OP. + + The implementation of this OP include diagonal/peephole connections. + Please refer to `Gers, F. A., & Schmidhuber, J. (2000) `_ . + If you do not need peephole connections, please set use_peepholes to False . + + This OP computes each timestep as follows: + + .. math:: + i_t = \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_{x_i} + b_{h_i}) + .. math:: + f_t = \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_{x_f} + b_{h_f}) + .. math:: + o_t = \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_{x_o} + b_{h_o}) + .. math:: + \widetilde{c_t} = tanh(W_{cx}x_t + W_{ch}h_{t-1} + b{x_c} + b_{h_c}) + .. math:: + c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t} + .. math:: + h_t = o_t \odot tanh(c_t) + + The symbolic meanings in the formula are as follows: + + - :math:`x_{t}` represents the input at timestep :math:`t` + - :math:`h_{t}` represents the hidden state at timestep :math:`t` + - :math:`h_{t-1}, c_{t-1}` represent the hidden state and cell state at timestep :math:`t-1` , respectively + - :math:`\widetilde{c_t}` represents the candidate cell state + - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively + - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` ) + - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate) + - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid + - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension + + Parameters: + input ( :ref:`api_guide_Variable_en` ): LSTM input tensor, multi-dimensional LODTensor of shape :math:`[T, 4*hidden\_size]` . Data type is float32 or float64. + size (int): must be 4 * hidden_size. + h_0( :ref:`api_guide_Variable_en` , optional): The initial hidden state of the LSTM, multi-dimensional Tensor of shape :math:`[batch\_size, hidden\_size]` . + Data type is float32 or float64. If set to None, it will be a vector of all 0. Default: None. + c_0( :ref:`api_guide_Variable_en` , optional): The initial hidden state of the LSTM, multi-dimensional Tensor of shape :math:`[batch\_size, hidden\_size]` . + Data type is float32 or float64. If set to None, it will be a vector of all 0. `h_0` and `c_0` can be None but only at the same time. Default: None. + param_attr(ParamAttr, optional): Parameter attribute of weight. If it is None, the default weight parameter attribute is used. Please refer to ref:`api_fluid_ParamAttr' . + If the user needs to set this parameter, the dimension must be :math:`[hidden\_size, 4*hidden\_size]` . Default: None. + + - Weights = :math:`\{ W_{cr},W_{ir},W_{fr},W_{or} \}` , the shape is [hidden_size, 4*hidden_size]. + + bias_attr (ParamAttr, optional): The bias attribute for the learnable bias + weights, which contains two parts, input-hidden + bias weights and peephole connections weights if + setting `use_peepholes` to `True`. + Please refer to ref:`api_fluid_ParamAttr' . Default: None. + + 1. `use_peepholes = False` + - Biases = {:math:`b_c, b_i, b_f, b_o`}. + - The shape is [1, 4*hidden_size]. + 2. `use_peepholes = True` + - Biases = { :math:`b_c, b_i, b_f, b_o, W_{ic}, \ + W_{fc}, W_{oc}`}. + - The shape is [1, 7*hidden_size]. + + use_peepholes (bool, optional): Whether to use peephole connection or not. Default: True. + is_reverse (bool, optional): Whether to calculate reverse LSTM. Default: False. + gate_activation (str, optional): The activation for input gate, forget gate and output gate. Default: "sigmoid". + cell_activation (str, optional): The activation for cell output. Default: "tanh". + candidate_activation (str, optional): The activation for candidate hidden state. Default: "tanh". + dtype (str, optional): Data type, can be "float32" or "float64". Default: "float32". + name (str, optional): A name for this layer. Please refer to :ref:`api_guide_Name` . Default: None. + + Returns: + tuple ( :ref:`api_guide_Variable` , :ref:`api_guide_Variable` ) : + + The hidden state and cell state of LSTM + + - hidden: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input. + - cell: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + emb_dim = 256 + vocab_size = 10000 + hidden_dim = 512 + + data = fluid.data(name='x', shape=[None], dtype='int64', lod_level=1) + emb = fluid.embedding(input=data, size=[vocab_size, emb_dim], is_sparse=True) + + forward_proj = fluid.layers.fc(input=emb, size=hidden_dim * 4, + bias_attr=False) + + forward, cell = fluid.layers.dynamic_lstm( + input=forward_proj, size=hidden_dim * 4, use_peepholes=False) + forward.shape # (-1, 512) + cell.shape # (-1, 512) + """ + assert _non_static_mode( + ) is not True, "please use lstm instead of dynamic_lstm in dygraph mode!" + assert bias_attr is not False, "bias_attr should not be False in dynamic_lstm." + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'dynamic_lstm') + + check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_lstm') + if isinstance(h_0, Variable): + check_variable_and_dtype(h_0, 'h_0', ['float32', 'float64'], + 'dynamic_lstm') + + check_type(c_0, 'c_0', (Variable, type(None)), 'dynamic_lstm') + if isinstance(c_0, Variable): + check_variable_and_dtype(c_0, 'c_0', ['float32', 'float64'], + 'dynamic_lstm') + + helper = LayerHelper('lstm', **locals()) + size = size // 4 + weight = helper.create_parameter(attr=helper.param_attr, + shape=[size, 4 * size], + dtype=dtype) + bias_size = [1, 7 * size] + if not use_peepholes: + bias_size[1] = 4 * size + bias = helper.create_parameter(attr=helper.bias_attr, + shape=bias_size, + dtype=dtype, + is_bias=True) + + hidden = helper.create_variable_for_type_inference(dtype) + cell = helper.create_variable_for_type_inference(dtype) + batch_gate = helper.create_variable_for_type_inference(dtype) + batch_cell_pre_act = helper.create_variable_for_type_inference(dtype) + inputs = {'Input': input, 'Weight': weight, 'Bias': bias} + batch_size = input.shape[0] + if h_0: + assert h_0.shape == (batch_size, size), \ + 'The shape of h0 should be (batch_size, %d)' % size + inputs['H0'] = h_0 + if c_0: + assert c_0.shape == (batch_size, size), \ + 'The shape of c0 should be (batch_size, %d)' % size + inputs['C0'] = c_0 + + helper.append_op(type='lstm', + inputs=inputs, + outputs={ + 'Hidden': hidden, + 'Cell': cell, + 'BatchGate': batch_gate, + 'BatchCellPreAct': batch_cell_pre_act + }, + attrs={ + 'use_peepholes': use_peepholes, + 'is_reverse': is_reverse, + 'gate_activation': gate_activation, + 'cell_activation': cell_activation, + 'candidate_activation': candidate_activation + }) + return hidden, cell + + +@deprecated(since='2.0.0', + update_to='paddle.nn.LSTM', + reason="This API may occur CUDNN errors.") +def lstm(input, + init_h, + init_c, + max_len, + hidden_size, + num_layers, + dropout_prob=0.0, + is_bidirec=False, + is_test=False, + name=None, + default_initializer=None, + seed=-1): + r""" + :api_attr: Static Graph + + **Note**: + This OP only supports running on GPU devices. + + This OP implements LSTM operation - `Hochreiter, S., & Schmidhuber, J. (1997) `_ . + + The implementation of this OP does not include diagonal/peephole connections. + Please refer to `Gers, F. A., & Schmidhuber, J. (2000) `_ . + If you need peephole connections, please use :ref:`api_fluid_layers_dynamic_lstm` . + + This OP computes each timestep as follows: + + .. math:: + i_t = \sigma(W_{ix}x_{t} + W_{ih}h_{t-1} + b_{x_i} + b_{h_i}) + .. math:: + f_t = \sigma(W_{fx}x_{t} + W_{fh}h_{t-1} + b_{x_f} + b_{h_f}) + .. math:: + o_t = \sigma(W_{ox}x_{t} + W_{oh}h_{t-1} + b_{x_o} + b_{h_o}) + .. math:: + \widetilde{c_t} = tanh(W_{cx}x_t + W_{ch}h_{t-1} + b{x_c} + b_{h_c}) + .. math:: + c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t} + .. math:: + h_t = o_t \odot tanh(c_t) + + The symbolic meanings in the formula are as follows: + + - :math:`x_{t}` represents the input at timestep :math:`t` + - :math:`h_{t}` represents the hidden state at timestep :math:`t` + - :math:`h_{t-1}, c_{t-1}` represent the hidden state and cell state at timestep :math:`t-1` , respectively + - :math:`\widetilde{c_t}` represents the candidate cell state + - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively + - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` ) + - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate) + - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid + - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension + + Parameters: + input ( :ref:`api_guide_Variable_en` ): LSTM input tensor, 3-D Tensor of shape :math:`[batch\_size, seq\_len, input\_dim]` . Data type is float32 or float64 + init_h( :ref:`api_guide_Variable_en` ): The initial hidden state of the LSTM, 3-D Tensor of shape :math:`[num\_layers, batch\_size, hidden\_size]` . + If is_bidirec = True, shape should be :math:`[num\_layers*2, batch\_size, hidden\_size]` . Data type is float32 or float64. + max_len (int): This parameter has no effect and will be discarded. + init_c( :ref:`api_guide_Variable_en` ): The initial cell state of the LSTM, 3-D Tensor of shape :math:`[num\_layers, batch\_size, hidden\_size]` . + If is_bidirec = True, shape should be :math:`[num\_layers*2, batch\_size, hidden\_size]` . Data type is float32 or float64. + hidden_size (int): hidden size of the LSTM. + num_layers (int): total layers number of the LSTM. + dropout_prob(float, optional): dropout prob, dropout ONLY work between rnn layers, NOT between time steps + There is NO dropout work on rnn output of the last RNN layers. + Default: 0.0. + is_bidirec (bool, optional): If it is bidirectional. Default: False. + is_test (bool, optional): If it is in test phrase. Default: False. + name (str, optional): A name for this layer. If set None, the layer + will be named automatically. Default: None. + default_initializer(Initializer, optional): Where use initializer to initialize the Weight + If set None, default initializer will be used. Default: None. + seed(int, optional): Seed for dropout in LSTM, If it's -1, dropout will use random seed. Default: 1. + + + Returns: + tuple ( :ref:`api_guide_Variable_en` , :ref:`api_guide_Variable_en` , :ref:`api_guide_Variable_en` ) : + + Three tensors, rnn_out, last_h, last_c: + + - rnn_out is result of LSTM hidden, shape is :math:`[seq\_len, batch\_size, hidden\_size]` \ + if is_bidirec set to True, shape will be :math:`[seq\_len, batch\_size, hidden\_size*2]` + - last_h is the hidden state of the last step of LSTM \ + shape is :math:`[num\_layers, batch\_size, hidden\_size]` \ + if is_bidirec set to True, shape will be :math:`[num\_layers*2, batch\_size, hidden\_size]` + - last_c(Tensor): the cell state of the last step of LSTM \ + shape is :math:`[num\_layers, batch\_size, hidden\_size]` \ + if is_bidirec set to True, shape will be :math:`[num\_layers*2, batch\_size, hidden\_size]` + + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import paddle.fluid.layers as layers + paddle.enable_static() + + emb_dim = 256 + vocab_size = 10000 + data = fluid.data(name='x', shape=[None, 100], dtype='int64') + emb = fluid.embedding(input=data, size=[vocab_size, emb_dim], is_sparse=True) + batch_size = 100 + dropout_prob = 0.2 + input_size = 100 + hidden_size = 150 + num_layers = 1 + max_len = 12 + init_h = layers.fill_constant( [num_layers, batch_size, hidden_size], 'float32', 0.0 ) + init_c = layers.fill_constant( [num_layers, batch_size, hidden_size], 'float32', 0.0 ) + rnn_out, last_h, last_c = layers.lstm( emb, init_h, init_c, \ + max_len, hidden_size, num_layers, \ + dropout_prob=dropout_prob) + rnn_out.shape # (-1, 100, 150) + last_h.shape # (1, 20, 150) + last_c.shape # (1, 20, 150) + """ + + helper = LayerHelper('cudnn_lstm', **locals()) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'lstm') + check_variable_and_dtype(init_h, 'init_h', ['float32', 'float64'], 'lstm') + check_variable_and_dtype(init_c, 'init_c', ['float32', 'float64'], 'lstm') + check_type(max_len, 'max_len', (int), 'lstm') + check_type(hidden_size, 'hidden_size', (int), 'lstm') + check_type(num_layers, 'num_layers', (int), 'lstm') + dtype = input.dtype + input_shape = list(input.shape) + input_size = input_shape[-1] + weight_size = 0 + num_dirrection = 2 if is_bidirec == True else 1 + + for i in range(num_layers): + if i == 0: + input_weight_size = (input_size * hidden_size) * 4 * num_dirrection + else: + input_weight_size = (hidden_size * hidden_size) * 4 * num_dirrection + hidden_weight_size = (hidden_size * hidden_size) * 4 * num_dirrection + + weight_size += input_weight_size + hidden_weight_size + weight_size += hidden_size * 8 * num_dirrection + + weight = helper.create_parameter(attr=helper.param_attr, + shape=[weight_size], + dtype=dtype, + default_initializer=default_initializer) + + out = helper.create_variable_for_type_inference(dtype) + last_h = helper.create_variable_for_type_inference(dtype) + last_c = helper.create_variable_for_type_inference(dtype) + reserve = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) + state_out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) + state_out.persistable = True + + helper.append_op(type='cudnn_lstm', + inputs={ + 'Input': input, + 'InitH': init_h, + 'InitC': init_c, + 'W': weight, + }, + outputs={ + 'Out': out, + 'LastH': last_h, + 'LastC': last_c, + 'Reserve': reserve, + 'StateOut': state_out, + }, + attrs={ + 'is_bidirec': is_bidirec, + 'input_size': input_size, + 'hidden_size': hidden_size, + 'num_layers': num_layers, + 'is_test': is_test, + 'dropout_prob': dropout_prob, + 'seed': seed, + }) + return out, last_h, last_c + + +def dynamic_lstmp(input, + size, + proj_size, + param_attr=None, + bias_attr=None, + use_peepholes=True, + is_reverse=False, + gate_activation='sigmoid', + cell_activation='tanh', + candidate_activation='tanh', + proj_activation='tanh', + dtype='float32', + name=None, + h_0=None, + c_0=None, + cell_clip=None, + proj_clip=None): + r""" + :api_attr: Static Graph + + **Note**: + 1. In order to improve efficiency, users must first map the input of dimension [T, hidden_size] to input of [T, 4 * hidden_size], and then pass it to this OP. + + This OP implements the LSTMP (LSTM Projected) layer. + The LSTMP layer has a separate linear mapping layer behind the LSTM layer. -- `Sak, H., Senior, A., & Beaufays, F. (2014) `_ . + + Compared with the standard LSTM layer, LSTMP has an additional linear mapping layer, + which is used to map from the original hidden state :math:`h_t` to the lower dimensional state :math:`r_t` . + This reduces the total number of parameters and computational complexity, especially when the output unit is relatively large. + + The default implementation of the OP contains diagonal/peephole connections, + please refer to `Gers, F. A., & Schmidhuber, J. (2000) `_ . + If you need to disable the peephole connections, set use_peepholes to False. + + This OP computes each timestep as follows: + + .. math:: + i_t = \sigma(W_{ix}x_{t} + W_{ir}r_{t-1} + W_{ic}c_{t-1} + b_i) + .. math:: + f_t = \sigma(W_{fx}x_{t} + W_{fr}r_{t-1} + W_{fc}c_{t-1} + b_f) + .. math:: + o_t = \sigma(W_{ox}x_{t} + W_{or}r_{t-1} + W_{oc}c_{t-1} + b_o) + .. math:: + \widetilde{c_t} = act_g(W_{cx}x_t + W_{cr}r_{t-1} + b_c) + .. math:: + c_t = f_t \odot c_{t-1} + i_t \odot \widetilde{c_t} + .. math:: + h_t = o_t \odot act_h(c_t) + .. math:: + r_t = \overline{act_h}(W_{rh}h_t) + + The symbolic meanings in the formula are as follows: + + - :math:`x_{t}` represents the input at timestep :math:`t` + - :math:`h_{t}` represents the hidden state at timestep :math:`t` + - :math:`r_{t}` : represents the state of the projected output of the hidden state :math:`h_{t}` + - :math:`h_{t-1}, c_{t-1}, r_{t-1}` represent the hidden state, cell state and projected output at timestep :math:`t-1` , respectively + - :math:`\widetilde{c_t}` represents the candidate cell state + - :math:`i_t` , :math:`f_t` and :math:`o_t` represent input gate, forget gate, output gate, respectively + - :math:`W` represents weight (e.g., :math:`W_{ix}` is the weight of a linear transformation of input :math:`x_{t}` when calculating input gate :math:`i_t` ) + - :math:`b` represents bias (e.g., :math:`b_{i}` is the bias of input gate) + - :math:`\sigma` represents nonlinear activation function for gate, default sigmoid + - :math:`\odot` represents the Hadamard product of a matrix, i.e. multiplying the elements of the same position for two matrices with the same dimension to get another matrix with the same dimension + + Parameters: + input( :ref:`api_guide_Variable_en` ): The input of dynamic_lstmp layer, which supports + variable-time length input sequence. + It is a multi-dimensional LODTensor of shape :math:`[T, 4*hidden\_size]` . Data type is float32 or float64. + size(int): must be 4 * hidden_size. + proj_size(int): The size of projection output. + param_attr(ParamAttr, optional): Parameter attribute of weight. If it is None, the default weight parameter attribute is used. Please refer to ref:`api_fluid_ParamAttr' . + If the user needs to set this parameter, the dimension must be :math:`[hidden\_size, 4*hidden\_size]` . Default: None. + + - Weights = :math:`\{ W_{cr},W_{ir},W_{fr},W_{or} \}` , the shape is [P, 4*hidden_size] , where P is the projection size. + - Projection weight = :math:`\{ W_{rh} \}` , the shape is [hidden_size, P]. + + bias_attr (ParamAttr, optional): The bias attribute for the learnable bias + weights, which contains two parts, input-hidden + bias weights and peephole connections weights if + setting `use_peepholes` to `True`. + Please refer to ref:`api_fluid_ParamAttr' . Default: None. + + 1. `use_peepholes = False` + - Biases = {:math:`b_c, b_i, b_f, b_o`}. + - The shape is [1, 4*hidden_size]. + 2. `use_peepholes = True` + - Biases = { :math:`b_c, b_i, b_f, b_o, W_{ic}, \ + W_{fc}, W_{oc}`}. + - The shape is [1, 7*hidden_size]. + + use_peepholes (bool, optional): Whether to use peephole connection or not. Default True. + is_reverse (bool, optional): Whether to calculate reverse LSTM. Default False. + gate_activation (str, optional): The activation for input gate, forget gate and output gate. Default "sigmoid". + cell_activation (str, optional): The activation for cell output. Default "tanh". + candidate_activation (str, optional): The activation for candidate hidden state. Default "tanh". + proj_activation(str, optional): The activation for projection output. Default "tanh". + dtype (str, optional): Data type, can be "float32" or "float64". Default "float32". + name (str, optional): A name for this layer. Please refer to :ref:`api_guide_Name` . Default: None. + h_0( :ref:`api_guide_Variable` , optional): The initial hidden state is an optional input, default is zero. + This is a tensor with shape :math:`[batch\_size, P]` , where P is the projection size. Default: None. + c_0( :ref:`api_guide_Variable` , optional): The initial cell state is an optional input, default is zero. + This is a tensor with shape :math:`[batch\_size, P]` , where P is the projection size. + `h_0` and `c_0` can be None but only at the same time. Default: None. + cell_clip(float, optional): If not None, the cell state is clipped + by this value prior to the cell output activation. Default: None. + proj_clip(float, optional): If `num_proj > 0` and `proj_clip` is + provided, then the projected values are clipped elementwise to within + `[-proj_clip, proj_clip]`. Default: None. + + Returns: + tuple ( :ref:`api_guide_Variable` , :ref:`api_guide_Variable` ) : + + The hidden state and cell state of LSTMP + + - hidden: LoDTensor with shape of :math:`[T, P]` , and its lod and dtype is the same as the input. + - cell: LoDTensor with shape of :math:`[T, hidden\_size]` , and its lod and dtype is the same as the input. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + dict_dim, emb_dim = 128, 64 + data = fluid.data(name='sequence', shape=[None], dtype='int64', lod_level=1) + emb = fluid.embedding(input=data, size=[dict_dim, emb_dim]) + hidden_dim, proj_dim = 512, 256 + fc_out = fluid.layers.fc(input=emb, size=hidden_dim * 4, + act=None, bias_attr=None) + proj_out, last_c = fluid.layers.dynamic_lstmp(input=fc_out, + size=hidden_dim * 4, + proj_size=proj_dim, + use_peepholes=False, + is_reverse=True, + cell_activation="tanh", + proj_activation="tanh") + proj_out.shape # (-1, 256) + last_c.shape # (-1, 512) + """ + + assert _non_static_mode( + ) is not True, "please use lstm instead of dynamic_lstmp in dygraph mode!" + + assert bias_attr is not False, "bias_attr should not be False in dynamic_lstmp." + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'dynamic_lstmp') + + check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_lstmp') + if isinstance(h_0, Variable): + check_variable_and_dtype(h_0, 'h_0', ['float32', 'float64'], + 'dynamic_lstmp') + + check_type(c_0, 'c_0', (Variable, type(None)), 'dynamic_lstmp') + if isinstance(c_0, Variable): + check_variable_and_dtype(c_0, 'c_0', ['float32', 'float64'], + 'dynamic_lstmp') + + helper = LayerHelper('lstmp', **locals()) + size = size // 4 + weight = helper.create_parameter(attr=helper.param_attr, + shape=[proj_size, 4 * size], + dtype=dtype) + proj_weight = helper.create_parameter(attr=helper.param_attr, + shape=[size, proj_size], + dtype=dtype) + bias_size = [1, 7 * size] + if not use_peepholes: + bias_size[1] = 4 * size + bias = helper.create_parameter(attr=helper.bias_attr, + shape=bias_size, + dtype=dtype, + is_bias=True) + + projection = helper.create_variable_for_type_inference(dtype) + cell = helper.create_variable_for_type_inference(dtype) + ordered_proj0 = helper.create_variable_for_type_inference(dtype) + batch_hidden = helper.create_variable_for_type_inference(dtype) + batch_gate = helper.create_variable_for_type_inference(dtype) + batch_cell_pre_act = helper.create_variable_for_type_inference(dtype) + inputs = { + 'Input': input, + 'Weight': weight, + 'ProjWeight': proj_weight, + 'Bias': bias + } + batch_size = input.shape[0] + if h_0: + assert h_0.shape == (batch_size, proj_size), \ + 'The shape of h0 should be (batch_size, %d)' % proj_size + inputs['H0'] = h_0 + if c_0: + assert c_0.shape == (batch_size, size), \ + 'The shape of c0 should be (batch_size, %d)' % size + inputs['C0'] = c_0 + + if cell_clip: + assert cell_clip >= 0, "cell_clip should not be negative." + if proj_clip: + assert proj_clip >= 0, "proj_clip should not be negative." + + helper.append_op(type='lstmp', + inputs=inputs, + outputs={ + 'Projection': projection, + 'Cell': cell, + 'BatchHidden': batch_hidden, + 'BatchGate': batch_gate, + 'BatchCellPreAct': batch_cell_pre_act + }, + attrs={ + 'use_peepholes': use_peepholes, + 'cell_clip': cell_clip, + 'proj_clip': proj_clip, + 'is_reverse': is_reverse, + 'gate_activation': gate_activation, + 'cell_activation': cell_activation, + 'candidate_activation': candidate_activation, + 'proj_activation': proj_activation + }) + return projection, cell + + +def dynamic_gru(input, + size, + param_attr=None, + bias_attr=None, + is_reverse=False, + gate_activation='sigmoid', + candidate_activation='tanh', + h_0=None, + origin_mode=False): + r""" + :api_attr: Static Graph + + **Note: The input type of this must be LoDTensor. If the input type to be + processed is Tensor, use** :ref:`api_fluid_layers_StaticRNN` . + + This operator is used to perform the calculations for a single layer of + Gated Recurrent Unit (GRU) on full sequences step by step. The calculations + in one time step support these two modes: + + If ``origin_mode`` is True, then the formula used is from paper + `Learning Phrase Representations using RNN Encoder Decoder for Statistical + Machine Translation `_ . + + .. math:: + + u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u) + + r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r) + + \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c) + + h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t} + + + if ``origin_mode`` is False, then the formula used is from paper + `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence + Modeling `_ + + .. math:: + + u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u) + + r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r) + + \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c) + + h_t & = (1-u_t) \odot h_{t-1} + u_t \odot \\tilde{h_t} + + :math:`x_t` is the input of current time step, but it is not from ``input`` . + This operator does not include the calculations :math:`W_{ux}x_{t}, W_{rx}x_{t}, W_{cx}x_{t}` , + **Note** thus a fully-connect layer whose size is 3 times of ``size`` should + be used before this operator, and the output should be used as ``input`` here. + :math:`h_{t-1}` is the hidden state from previous time step. + :math:`u_t` , :math:`r_t` , :math:`\\tilde{h_t}` and :math:`h_t` stand for + update gate, reset gate, candidate hidden and hidden output separately. + :math:`W_{uh}, b_u` , :math:`W_{rh}, b_r` and :math:`W_{ch}, b_c` stand for + the weight matrix and bias used in update gate, reset gate, candidate hidden + calculations. For implementation, the three weight matrix are merged into a + tensor shaped :math:`[D, D \\times 3]` , the three bias are concatenated as + a tensor shaped :math:`[1, D \\times 3]` , where :math:`D` stands for the + hidden size; The data layout of weight tensor is: :math:`W_{uh}` and :math:`W_{rh}` + are concatenated with shape :math:`[D, D \\times 2]` lying on the first part, + and :math:`W_{ch}` lying on the latter part with shape :math:`[D, D]` . + + + Args: + input(Variable): A LoDTensor whose lod level is 1, representing the input + after linear projection. Its shape should be :math:`[T, D \\times 3]` , + where :math:`T` stands for the total sequence lengths in this mini-batch, + :math:`D` for the hidden size. The data type should be float32 or float64. + size(int): Indicate the hidden size. + param_attr(ParamAttr, optional): To specify the weight parameter property. + Default: None, which means the default weight parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr, optional): To specify the bias parameter property. + Default: None, which means the default bias parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + is_reverse(bool, optional): Whether to compute in the reversed order of + input sequences. Default False. + gate_activation(str, optional): The activation function corresponding to + :math:`act_g` in the formula. "sigmoid", "tanh", "relu" and "identity" + are supported. Default "sigmoid". + candidate_activation(str, optional): The activation function corresponding to + :math:`act_c` in the formula. "sigmoid", "tanh", "relu" and "identity" + are supported. Default "tanh". + h_0 (Variable, optional): A Tensor representing the initial hidden state. + It not provided, the default initial hidden state is 0. The shape is + :math:`[N, D]` , where :math:`N` is the number of sequences in the + mini-batch, :math:`D` for the hidden size. The data type should be + same as ``input`` . Default None. + + Returns: + Variable: A LoDTensor whose lod level is 1 and shape is :math:`[T, D]` , \ + where :math:`T` stands for the total sequence lengths in this mini-batch \ + :math:`D` for the hidden size. It represents GRU transformed sequence output, \ + and has the same lod and data type with ``input`` . + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + dict_dim, emb_dim = 128, 64 + data = fluid.data(name='sequence', + shape=[None], + dtype='int64', + lod_level=1) + emb = fluid.embedding(input=data, size=[dict_dim, emb_dim]) + hidden_dim = 512 + x = fluid.layers.fc(input=emb, size=hidden_dim * 3) + hidden = fluid.layers.dynamic_gru(input=x, size=hidden_dim) + """ + + assert _non_static_mode( + ) is not True, "please use gru instead of dynamic_gru in dygraph mode!" + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'dynamic_gru') + + check_type(h_0, 'h_0', (Variable, type(None)), 'dynamic_gru') + if isinstance(h_0, Variable): + check_variable_and_dtype(h_0, 'h_0', ['float32', 'float64'], + 'dynamic_gru') + + helper = LayerHelper('gru', **locals()) + dtype = helper.input_dtype() + + weight = helper.create_parameter(attr=helper.param_attr, + shape=[size, 3 * size], + dtype=dtype) + bias = helper.create_parameter(attr=helper.bias_attr, + shape=[1, 3 * size], + dtype=dtype, + is_bias=True) + batch_size = input.shape[0] + inputs = {'Input': input, 'Weight': weight, 'Bias': bias} + if h_0: + assert h_0.shape == ( + batch_size, + size), 'The shape of h0 should be(batch_size, %d)' % size + inputs['H0'] = h_0 + + hidden = helper.create_variable_for_type_inference(dtype) + batch_gate = helper.create_variable_for_type_inference(dtype) + batch_reset_hidden_prev = helper.create_variable_for_type_inference(dtype) + batch_hidden = helper.create_variable_for_type_inference(dtype) + + helper.append_op(type='gru', + inputs=inputs, + outputs={ + 'Hidden': hidden, + 'BatchGate': batch_gate, + 'BatchResetHiddenPrev': batch_reset_hidden_prev, + 'BatchHidden': batch_hidden + }, + attrs={ + 'is_reverse': is_reverse, + 'gate_activation': gate_activation, + 'activation': candidate_activation, + 'origin_mode': origin_mode + }) + return hidden + + +def gru_unit(input, + hidden, + size, + param_attr=None, + bias_attr=None, + activation='tanh', + gate_activation='sigmoid', + origin_mode=False): + r""" + :api_attr: Static Graph + + Gated Recurrent Unit (GRU) RNN cell. This operator performs GRU calculations for + one time step and it supports these two modes: + + If ``origin_mode`` is True, then the formula used is from paper + `Learning Phrase Representations using RNN Encoder Decoder for Statistical + Machine Translation `_ . + + .. math:: + + u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u) + + r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r) + + \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c) + + h_t & = u_t \odot h_{t-1} + (1-u_t) \odot \\tilde{h_t} + + + if ``origin_mode`` is False, then the formula used is from paper + `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence + Modeling `_ + + .. math:: + + u_t & = act_g(W_{ux}x_{t} + W_{uh}h_{t-1} + b_u) + + r_t & = act_g(W_{rx}x_{t} + W_{rh}h_{t-1} + b_r) + + \\tilde{h_t} & = act_c(W_{cx}x_{t} + W_{ch}(r_t \odot h_{t-1}) + b_c) + + h_t & = (1-u_t) \odot h_{t-1} + u_t \odot \\tilde{h_t} + + :math:`x_t` is the input of current time step, but it is not ``input`` . + This operator does not include the calculations :math:`W_{ux}x_{t}, W_{rx}x_{t}, W_{cx}x_{t}` , + **Note** thus a fully-connect layer whose size is 3 times of GRU hidden size should + be used before this operator, and the output should be used as ``input`` here. + :math:`h_{t-1}` is the hidden state from previous time step. + :math:`u_t` , :math:`r_t` , :math:`\\tilde{h_t}` and :math:`h_t` stand for + update gate, reset gate, candidate hidden and hidden output separately. + :math:`W_{uh}, b_u` , :math:`W_{rh}, b_r` and :math:`W_{ch}, b_c` stand for + the weight matrix and bias used in update gate, reset gate, candidate hidden + calculations. For implementation, the three weight matrix are merged into a + tensor shaped :math:`[D, D \\times 3]` , the three bias are concatenated as + a tensor shaped :math:`[1, D \\times 3]` , where :math:`D` stands for the + hidden size; The data layout of weight tensor is: :math:`W_{uh}` and :math:`W_{rh}` + are concatenated with shape :math:`[D, D \\times 2]` lying on the first part, + and :math:`W_{ch}` lying on the latter part with shape :math:`[D, D]` . + + + Args: + input(Variable): A 2D Tensor representing the input after linear projection + after linear projection. Its shape should be :math:`[N, D \\times 3]` , + where :math:`N` stands for batch size, :math:`D` for the hidden size. + The data type should be float32 or float64. + hidden(Variable): A 2D Tensor representing the hidden state from previous step. + Its shape should be :math:`[N, D]` , where :math:`N` stands for batch size, + :math:`D` for the hidden size. The data type should be same as ``input`` . + size(int): Indicate the hidden size. + param_attr(ParamAttr, optional): To specify the weight parameter property. + Default: None, which means the default weight parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr, optional): To specify the bias parameter property. + Default: None, which means the default bias parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + activation(str, optional): The activation function corresponding to + :math:`act_c` in the formula. "sigmoid", "tanh", "relu" and "identity" + are supported. Default "tanh". + gate_activation(str, optional): The activation function corresponding to + :math:`act_g` in the formula. "sigmoid", "tanh", "relu" and "identity" + are supported. Default "sigmoid". + + Returns: + tuple: The tuple contains three Tensor variables with the same data type \ + as ``input`` . They represent the hidden state for next time step ( :math:`h_t` ), \ + reset previous hidden state ( :math:`r_t \odot h_{t-1}` ), and the \ + concatenation of :math:`h_t, r_t, \\tilde{h_t}` . And they have shape \ + :math:`[N, D]` , :math:`[N, D]` , :math:`[N, D \times 3]` separately. \ + Usually only the hidden state for next time step ( :math:`h_t` ) is used \ + as output and state, the other two are intermediate results of calculations. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + dict_dim, emb_dim = 128, 64 + data = fluid.data(name='step_data', shape=[None], dtype='int64') + emb = fluid.embedding(input=data, size=[dict_dim, emb_dim]) + hidden_dim = 512 + x = fluid.layers.fc(input=emb, size=hidden_dim * 3) + pre_hidden = fluid.data( + name='pre_hidden', shape=[None, hidden_dim], dtype='float32') + hidden = fluid.layers.gru_unit( + input=x, hidden=pre_hidden, size=hidden_dim * 3) + + """ + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'gru_unit') + check_variable_and_dtype(hidden, 'hidden', ['float32', 'float64'], + 'gru_unit') + check_type(size, 'size', (int), 'gru_unit') + activation_dict = dict( + identity=0, + sigmoid=1, + tanh=2, + relu=3, + ) + activation = activation_dict[activation] + gate_activation = activation_dict[gate_activation] + + helper = LayerHelper('gru_unit', **locals()) + dtype = helper.input_dtype() + size = size // 3 + + # create weight + weight = helper.create_parameter(attr=helper.param_attr, + shape=[size, 3 * size], + dtype=dtype) + + gate = helper.create_variable_for_type_inference(dtype) + reset_hidden_pre = helper.create_variable_for_type_inference(dtype) + updated_hidden = helper.create_variable_for_type_inference(dtype) + inputs = {'Input': input, 'HiddenPrev': hidden, 'Weight': weight} + # create bias + if helper.bias_attr: + bias_size = [1, 3 * size] + bias = helper.create_parameter(attr=helper.bias_attr, + shape=bias_size, + dtype=dtype, + is_bias=True) + inputs['Bias'] = bias + + helper.append_op( + type='gru_unit', + inputs=inputs, + outputs={ + 'Gate': gate, + 'ResetHiddenPrev': reset_hidden_pre, + 'Hidden': updated_hidden, + }, + attrs={ + 'activation': 2, # tanh + 'gate_activation': 1, # sigmoid + 'origin_mode': origin_mode + }) + + return updated_hidden, reset_hidden_pre, gate + + +def beam_search(pre_ids, + pre_scores, + ids, + scores, + beam_size, + end_id, + level=0, + is_accumulated=True, + name=None, + return_parent_idx=False): + r""" + + Beam search is a classical algorithm for selecting candidate words in a + machine translation task. + + Refer to `Beam search `_ + for more details. + + **This operator only supports LoDTensor.** It is used after finishing + scores calculation to perform beam search for one time step. Specifically, + after ``ids`` and ``scores`` have been produced, it selects the top-K + ( `k` is ``beam_size`` ) candidate word ids of current step from ``ids`` + according to the corresponding ``scores``. Additionally, ``pre_id`` and + ``pre_scores`` are the output of `beam_search` at previous step, they + are needed for special use to handle ended candidate translations. + + Note that if ``is_accumulated`` is True, the ``scores`` passed in should + be accumulated scores. Otherwise, the ``scores`` are + considered as the probabilities of single step and would be transformed to + the log field and added up with ``pre_scores`` for final scores in this + operator. Length penalty should be done with extra operators before calculating + the accumulated scores if needed. + + Please see the following demo for a fully beam search usage example: + + fluid/tests/book/test_machine_translation.py + + Args: + pre_ids(Variable): A LodTensor variable (lod level is 2), representing + the selected ids of previous step. It is the output of beam_search + at previous step. Its shape is `[batch_size, 1]` and its lod is + `[[0, 1, ... , batch_size], [0, 1, ..., batch_size]]` at the + first step. The data type should be int64. + pre_scores(Variable): A LodTensor variable has the same shape and lod + with ``pre_ids`` , representing the accumulated scores corresponding + to the selected ids of previous step. It is the output of + beam_search at previous step. The data type should be float32 or float64. + ids(Variable|None): A LodTensor variable containing the candidates ids. + It has the same lod with ``pre_ids`` and its shape should be + `[batch_size * beam_size, K]`, where `K` supposed to be greater than + ``beam_size`` and the first dimension size (decrease as samples reach + to the end) should be same as that of ``pre_ids`` . The data type + should be int64. It can be None, which use index in ``scores`` as + ids. + scores(Variable): A LodTensor variable containing the accumulated + scores corresponding to ``ids`` . Both its shape and lod are same as + those of ``ids`` . The data type should be float32 or float64. + beam_size(int): The beam width used in beam search. + end_id(int): The id of end token. + level(int): **It can be ignored and mustn't change currently.** + The 2 level lod used in this operator has the following + meaning: The first level describes how many beams each sample has, + which would change to 0 when beams of the sample all end (batch reduce); + The second level describes how many times each beam is selected. + Default 0, which shouldn't be changed currently. + is_accumulated(bool): Whether the input ``score`` is accumulated scores. + Default True. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + return_parent_idx(bool, optional): Whether to return an extra Tensor variable + in output, which stores the selected ids' parent index in + ``pre_ids`` and can be used to update RNN's states by gather operator. + Default False. + + Returns: + tuple: The tuple contains two or three LodTensor variables. The two LodTensor, \ + representing the selected ids and the corresponding accumulated scores of \ + current step, have the same shape `[batch_size, beam_size]` and lod with 2 levels, \ + and have data types int64 and float32. If ``return_parent_idx`` is True, \ + an extra Tensor variable preserving the selected ids' parent index \ + is included, whose shape is `[batch_size * beam_size]` and data type \ + is int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + # Suppose `probs` contains predicted results from the computation + # cell and `pre_ids` and `pre_scores` is the output of beam_search + # at previous step. + beam_size = 4 + end_id = 1 + pre_ids = fluid.data( + name='pre_id', shape=[None, 1], lod_level=2, dtype='int64') + pre_scores = fluid.data( + name='pre_scores', shape=[None, 1], lod_level=2, dtype='float32') + probs = fluid.data( + name='probs', shape=[None, 10000], dtype='float32') + topk_scores, topk_indices = fluid.layers.topk(probs, k=beam_size) + accu_scores = fluid.layers.elementwise_add( + x=fluid.layers.log(x=topk_scores), + y=fluid.layers.reshape(pre_scores, shape=[-1]), + axis=0) + selected_ids, selected_scores = fluid.layers.beam_search( + pre_ids=pre_ids, + pre_scores=pre_scores, + ids=topk_indices, + scores=accu_scores, + beam_size=beam_size, + end_id=end_id) + """ + check_variable_and_dtype(pre_ids, 'pre_ids', ['int64'], 'beam_search') + check_variable_and_dtype(pre_scores, 'pre_scores', ['float32', 'float64'], + 'beam_search') + check_type(ids, 'ids', (Variable, type(None)), 'beam_search') + check_variable_and_dtype(scores, 'scores', ['float32', 'float64'], + 'beam_search') + helper = LayerHelper('beam_search', **locals()) + score_type = pre_scores.dtype + id_type = pre_ids.dtype + + inputs = {"pre_ids": pre_ids, "pre_scores": pre_scores, "scores": scores} + if ids is not None: + inputs["ids"] = ids + + selected_scores = helper.create_variable_for_type_inference( + dtype=score_type) + selected_ids = helper.create_variable_for_type_inference(dtype=id_type) + # parent_idx is a tensor used to gather cell states at the next time + # step. Though lod in selected_ids can also be used to gather by + # sequence_expand, it is not efficient. + # gather_op's index input only supports int32 dtype currently + parent_idx = helper.create_variable_for_type_inference(dtype="int32") + + helper.append_op( + type='beam_search', + inputs=inputs, + outputs={ + 'selected_ids': selected_ids, + 'selected_scores': selected_scores, + 'parent_idx': parent_idx + }, + attrs={ + # TODO(ChunweiYan) to assure other value support + 'level': level, + 'beam_size': beam_size, + 'end_id': end_id, + 'is_accumulated': is_accumulated, + }) + if return_parent_idx: + return selected_ids, selected_scores, parent_idx + else: + return selected_ids, selected_scores + + +def beam_search_decode(ids, scores, beam_size, end_id, name=None): + r""" + + This operator is used after beam search has completed. It constructs the + full predicted sequences for each sample by walking back along the search + paths stored in lod of ``ids`` . The result sequences are stored in a + LoDTensor, which uses the following way to parse: + + .. code-block:: text + + If lod = [[0, 3, 6], [0, 12, 24, 40, 54, 67, 82]] + + The first level of lod stands for: There are 2 samples each having 3 + (beam width) predicted sequence. + + The second level of lod stands for: The lengths of the first sample's + 3 predicted sequences are 12, 12, 16; The lengths of the second sample's + 3 predicted sequences are 14, 13, 15. + + + Please see the following demo for a fully beam search usage example: + fluid/tests/book/test_machine_translation.py + + Args: + ids(Variable): The LoDTensorArray variable containing the selected ids + of all steps. Each LoDTensor in it has int64 data type and 2 level + lod which can be used to get the search paths. + scores(Variable): The LodTensorArray variable containing the accumulated + scores corresponding to selected ids of all steps. It has the same size + as ``ids`` . Each LoDTensor in it has the same shape and lod as the + counterpart in ``ids`` , and has a float32 data type. + beam_size(int): The beam width used in beam search. + end_id(int): The id of end token. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + tuple: The tuple contains two LodTensor variables. The two LodTensor, \ + containing the full sequences of ids and the corresponding accumulated \ + scores, have the same shape flattened to 1D and have the same 2 level \ + lod. The lod can be used to get how many predicted sequences each sample \ + has and how many ids each predicted sequence has. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + # Suppose `ids` and `scores` are LodTensorArray variables reserving + # the selected ids and scores of all steps + ids = fluid.layers.create_array(dtype='int64') + scores = fluid.layers.create_array(dtype='float32') + finished_ids, finished_scores = fluid.layers.beam_search_decode( + ids, scores, beam_size=5, end_id=0) + """ + check_variable_and_dtype(ids, 'ids', ['int64'], 'beam_search_encode') + check_variable_and_dtype(scores, 'scores', ['float32'], + 'beam_search_encode') + helper = LayerHelper('beam_search_decode', **locals()) + sentence_ids = helper.create_variable_for_type_inference(dtype=ids.dtype) + sentence_scores = helper.create_variable_for_type_inference( + dtype=scores.dtype) + + helper.append_op(type="beam_search_decode", + inputs={ + "Ids": ids, + "Scores": scores + }, + outputs={ + "SentenceIds": sentence_ids, + "SentenceScores": sentence_scores + }, + attrs={ + "beam_size": beam_size, + "end_id": end_id + }) + + return sentence_ids, sentence_scores + + +def lstm_unit(x_t, + hidden_t_prev, + cell_t_prev, + forget_bias=0.0, + param_attr=None, + bias_attr=None, + name=None): + r""" + :api_attr: Static Graph + + Long-Short Term Memory (LSTM) RNN cell. This operator performs LSTM calculations for + one time step, whose implementation is based on calculations described in `RECURRENT + NEURAL NETWORK REGULARIZATION `_ . + + We add forget_bias to the biases of the forget gate in order to + reduce the scale of forgetting. The formula is as follows: + + .. math:: + + i_{t} & = \sigma(W_{x_{i}}x_{t} + W_{h_{i}}h_{t-1} + b_{i}) + + f_{t} & = \sigma(W_{x_{f}}x_{t} + W_{h_{f}}h_{t-1} + b_{f} + forget\\_bias) + + c_{t} & = f_{t}c_{t-1} + i_{t} tanh (W_{x_{c}}x_{t} + W_{h_{c}}h_{t-1} + b_{c}) + + o_{t} & = \sigma(W_{x_{o}}x_{t} + W_{h_{o}}h_{t-1} + b_{o}) + + h_{t} & = o_{t} tanh (c_{t}) + + :math:`x_{t}` stands for ``x_t`` , corresponding to the input of current time step; + :math:`h_{t-1}` and :math:`c_{t-1}` correspond to ``hidden_t_prev`` and ``cell_t_prev`` , + representing the output of from previous time step. + :math:`i_{t}, f_{t}, c_{t}, o_{t}, h_{t}` are input gate, forget gate, cell, output gate + and hidden calculation. + + Args: + x_t(Variable): A 2D Tensor representing the input of current time step. + Its shape should be :math:`[N, M]` , where :math:`N` stands for batch + size, :math:`M` for the feature size of input. The data type should + be float32 or float64. + hidden_t_prev(Variable): A 2D Tensor representing the hidden value from + previous step. Its shape should be :math:`[N, D]` , where :math:`N` + stands for batch size, :math:`D` for the hidden size. The data type + should be same as ``x_t`` . + cell_t_prev(Variable): A 2D Tensor representing the cell value from + previous step. It has the same shape and data type with ``hidden_t_prev`` . + forget_bias (float, optional): :math:`forget\\_bias` added to the biases + of the forget gate. Default 0. + param_attr(ParamAttr, optional): To specify the weight parameter property. + Default: None, which means the default weight parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + bias_attr (ParamAttr, optional): To specify the bias parameter property. + Default: None, which means the default bias parameter property is used. + See usage for details in :ref:`api_fluid_ParamAttr` . + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + tuple: The tuple contains two Tensor variables with the same shape and \ + data type with ``hidden_t_prev`` , representing the hidden value and \ + cell value which correspond to :math:`h_{t}` and :math:`c_{t}` in \ + the formula. + + Raises: + ValueError: Rank of x_t must be 2. + ValueError: Rank of hidden_t_prev must be 2. + ValueError: Rank of cell_t_prev must be 2. + ValueError: The 1st dimensions of x_t, hidden_t_prev and cell_t_prev must be the same. + ValueError: The 2nd dimensions of hidden_t_prev and cell_t_prev must be the same. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + + dict_dim, emb_dim, hidden_dim = 128, 64, 512 + data = fluid.data(name='step_data', shape=[None], dtype='int64') + x = fluid.embedding(input=data, size=[dict_dim, emb_dim]) + pre_hidden = fluid.data( + name='pre_hidden', shape=[None, hidden_dim], dtype='float32') + pre_cell = fluid.data( + name='pre_cell', shape=[None, hidden_dim], dtype='float32') + hidden = fluid.layers.lstm_unit( + x_t=x, + hidden_t_prev=pre_hidden, + cell_t_prev=pre_cell) + """ + helper = LayerHelper('lstm_unit', **locals()) + check_variable_and_dtype(x_t, 'x_t', ['float32', 'float64'], 'lstm_unit') + check_variable_and_dtype(hidden_t_prev, 'hidden_t_prev', + ['float32', 'float64'], 'lstm_unit') + check_variable_and_dtype(cell_t_prev, 'cell_t_prev', ['float32', 'float64'], + 'lstm_unit') + if len(x_t.shape) != 2: + raise ValueError("Rank of x_t must be 2.") + + if len(hidden_t_prev.shape) != 2: + raise ValueError("Rank of hidden_t_prev must be 2.") + + if len(cell_t_prev.shape) != 2: + raise ValueError("Rank of cell_t_prev must be 2.") + + if x_t.shape[0] != hidden_t_prev.shape[0] or x_t.shape[ + 0] != cell_t_prev.shape[0]: + raise ValueError("The 1st dimensions of x_t, hidden_t_prev and " + "cell_t_prev must be the same.") + + if hidden_t_prev.shape[1] != cell_t_prev.shape[1]: + raise ValueError("The 2nd dimensions of hidden_t_prev and " + "cell_t_prev must be the same.") + + if bias_attr is None: + bias_attr = ParamAttr() + + size = cell_t_prev.shape[1] + concat_out = nn.concat(input=[x_t, hidden_t_prev], axis=1) + fc_out = nn.fc(input=concat_out, + size=4 * size, + param_attr=param_attr, + bias_attr=bias_attr) + dtype = x_t.dtype + c = helper.create_variable_for_type_inference(dtype) + h = helper.create_variable_for_type_inference(dtype) + + helper.append_op(type='lstm_unit', + inputs={ + "X": fc_out, + "C_prev": cell_t_prev + }, + outputs={ + "C": c, + "H": h + }, + attrs={"forget_bias": forget_bias}) + + return h, c diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/sequence_lod.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/sequence_lod.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ebe1adb61b70d74523eee53a8769073c8a483e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/sequence_lod.py @@ -0,0 +1,1444 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function + +import paddle +from .layer_function_generator import templatedoc +from ..framework import core, Variable, _non_static_mode, in_dygraph_mode, _in_legacy_dygraph, convert_np_dtype_to_dtype_ +from ..layer_helper import LayerHelper +from ..data_feeder import check_variable_and_dtype, check_type, check_dtype +from ..core import VarDesc +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'sequence_conv', + 'sequence_softmax', + 'sequence_pool', + 'sequence_concat', + 'sequence_first_step', + 'sequence_last_step', + 'sequence_slice', + 'sequence_expand', + 'sequence_expand_as', + 'sequence_pad', + 'sequence_unpad', + 'sequence_reshape', + 'sequence_scatter', + 'sequence_enumerate', + 'sequence_mask', + 'sequence_reverse', +] + + +@templatedoc() +def sequence_conv(input, + num_filters, + filter_size=3, + filter_stride=1, + padding=True, + padding_start=None, + bias_attr=None, + param_attr=None, + act=None, + name=None): + r""" + + Note: + Only receives LoDTensor as input. If your input is Tensor, please use conv2d Op.(fluid.layers.** :ref:`api_fluid_layers_conv2d` ). + + This operator receives input sequences with variable length and other convolutional + configuration parameters(num_filters, filter_size) to apply the convolution operation. + It fills all-zero padding data on both sides of the sequence by default to ensure that + the output is the same length as the input. You can customize the padding behavior by + configuring the parameter :attr:`padding\_start` . + + **Warning:** the parameter :attr:`padding` take no effect and will be deprecated in the future. + + .. code-block:: text + + Here we will illustrate the details of the padding operation: + For a mini-batch of 2 variable lengths sentences, containing 3, and 1 time-steps: + Assumed input (X) is a [4, N] float LoDTensor, and for the sake of simplicity, we assume N=2. + input.data = [[1, 1], + [2, 2], + [3, 3], + [4, 4]] + + This is to say that input (X) has 4 words and the dimension of each word + representation is 2. + + * Case1: + + If padding_start is -1 and filter_size is 3. + The length of padding data is calculated as follows: + up_pad_len = max(0, -padding_start) = 1 + down_pad_len = max(0, filter_size + padding_start - 1) = 1 + + The output of the input sequence after padding is: + data_aftet_padding = [[0, 0, 1, 1, 2, 2], + [1, 1, 2, 2, 3, 3], + [2, 2, 3, 3, 0, 0], + [0, 0, 4, 4, 0, 0]] + + It will be multiplied by the filter weight to get the final output. + Assume num_filters = 3 + output.data = [[ 0.3234, -0.2334, 0.7433], + [ 0.5646, 0.9464, -0.1223], + [-0.1343, 0.5653, 0.4555], + [ 0.9954, -0.1234, -0.1234]] + output.shape = [4, 3] # 3 = num_filters + output.lod = [[0, 3, 4]] # Remain the same + + + Args: + input (Variable): LoDTensor with shape :math:`(M, K)`, where M is the total time-step of mini-batch + and K is hidden_size of input. Only lod_level of 1 is supported. The data type should be float32 or + float64. + num_filters (int): the number of filters. + filter_size (int): the height of filter. Specified filter width is not supported, the width is + hidden_size by default. Default: 3. + filter_stride (int): stride of the filter. Currently only supports :attr:`stride` = 1. + padding (bool): the parameter :attr:`padding` take no effect and will be discarded in the + future. Currently, it will always pad input to make sure the length of the output is + the same as input whether :attr:`padding` is set true or false. Because the length of + input sequence may be shorter than :attr:`filter\_size`, which will cause the convolution + result to not be computed correctly. These padding data will not be trainable or updated + while training. Default: True. + padding_start (int): It is used to indicate the start index for padding the input + sequence, which can be negative. The negative number means to pad + :attr:`|padding_start|` time-steps of all-zero data at the beginning of each instance. + The positive number means to skip :attr:`padding_start` time-steps of each instance, + and it will pad :math:`filter\_size + padding\_start - 1` time-steps of all-zero data + at the end of the sequence to ensure that the output is the same length as the input. + If set None, the same length :math:`\\frac{filter\_size}{2}` of data will be filled + on both sides of the sequence. If set 0, the length of :math:`filter\_size - 1` data + is padded at the end of each input sequence. Default: None. + bias_attr (ParamAttr): To specify the bias parameter property. Default: None, which means the + default bias parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . + param_attr (ParamAttr): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_fluid_ParamAttr` . + act (str): Activation to be applied to the output of this layer, such as tanh, softmax, + sigmoid, relu. For more information, please refer to :ref:`api_guide_activations_en` . Default: None. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: LoDTensor with the same length as input. The data type is float32 or float64, which is same as input. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[-1, 10], dtype='float32', lod_level=1) + x_conved = paddle.static.nn.sequence_conv(input=x, num_filters=2, filter_size=3, padding_start=-1) + """ + + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'sequence_conv') + helper = LayerHelper('sequence_conv', **locals()) + dtype = helper.input_dtype() + filter_shape = [filter_size * input.shape[1], num_filters] + filter_param = helper.create_parameter(attr=helper.param_attr, + shape=filter_shape, + dtype=dtype) + pre_bias = helper.create_variable_for_type_inference(dtype) + if padding_start is None: + padding_start = -int(filter_size // 2) + + helper.append_op(type='sequence_conv', + inputs={ + 'X': [input], + 'Filter': [filter_param], + }, + outputs={"Out": pre_bias}, + attrs={ + 'contextStride': filter_stride, + 'contextStart': padding_start, + 'contextLength': filter_size, + }) + pre_act = helper.append_bias_op(pre_bias) + return helper.append_activation(pre_act) + + +def sequence_softmax(input, use_cudnn=False, name=None): + r""" + + Note: + The input type of the OP must be LoDTensor. For Tensor, use:** :ref:`api_fluid_layers_softmax` + + A LoD-tensor can be regarded as several sequences, and this op apply softmax algo on each sequence. + The shape of input Tensor can be :math:`[N, 1]` or :math:`[N]`, where :math:`N` + is the sum of the length of all sequences. Recommended usage: :math:`[N]`. + + For i-th sequence in a mini-batch: + + .. math:: + + Out(X[lod[i]:lod[i+1]], :) = \\frac{\exp(X[lod[i]:lod[i+1], :])}{\sum(\exp(X[lod[i]:lod[i+1], :]))} + + For example, for a LoD-Tensor with 6 sequences ([3, 2, 4, 1, 2, 3] - sequence length list in order), + the lod in the runtime is [[0, 3, 5, 9, 10, 12, 15]], + then softmax will be computed among :math:`X[0:3,:],X[3:5,:],X[5:9,:],X[9:10,:],X[10:12,:],X[12:15,:]`, + and :math:`N` turns out to be 15. + + .. code-block:: text + + *Case 1: + + Given: + input.data = [0.7, 1, 0.6, + 1.5, 1.1, + 1.2, 0.2, 0.6, 1.9, + 3.1, + 2.5, 0.8, + 0.1, 2.4, 1.3] + input.lod = [[0, 3, 5, 9, 10, 12, 15]] + then: + output.data = [0.30724832, 0.41474187, 0.2780098, + 0.59868765, 0.40131235, + 0.2544242, 0.09359743, 0.13963096, 0.5123474, + 1., + 0.84553474, 0.15446526, + 0.06995796, 0.69777346, 0.23226859] + output.lod = [[0, 3, 5, 9, 10, 12, 15]] + + + Args: + input (Variable):A LoDTensor with shape of :math:`[N, 1]` or :math:`[N]`, Recommended usage: :math:`[N]`. + Supported data types: float32, float64. + use_cudnn (bool, optional): Use cudnn kernel or not. Effective only when the cudnn version of the paddle + library is installed and GPU is used for training or reasoning. Default: False. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: A LoD-Tensor which has the same shape and data type with input. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[7, 1], + dtype='float32', lod_level=1) + x_sequence_softmax_1 = paddle.static.nn.sequence_softmax(input=x) + + y = paddle.static.data(name='y', shape=[7], + dtype='float32', lod_level=1) + x_sequence_softmax_2 = paddle.static.nn.sequence_softmax(input=y) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_softmax', **locals()) + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'sequence_softmax') + dtype = helper.input_dtype() + softmax_out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="sequence_softmax", + inputs={"X": input}, + outputs={"Out": softmax_out}, + attrs={"use_cudnn": use_cudnn}) + return softmax_out + + +def sequence_pool(input, pool_type, is_test=False, pad_value=0.0): + r""" + + Note: + Only receives LoDTensor as input. If your input is Tensor, please use pool2d Op.(fluid.layers.** :ref:`api_fluid_layers_pool2d` ). + + This operator only supports LoDTensor as input. It will apply specified pooling + operation on the input LoDTensor. It pools features of all time-steps of each + sequence at the last lod_level using :attr:`pool_type` mentioned in the parameters, + such as sum, average, sqrt, etc. + + It supports six pool_type: + + - average: :math:`Out[i] = \\frac{\sum_i X_i}{N}` + - sum: :math:`Out[i] = \sum_jX_{ij}` + - sqrt: :math:`Out[i] = \\frac{\sum_jX_{ij}}{\sqrt{len(X_i)}}` + - max: :math:`Out[i] = max(X_i)` + - last: :math:`Out[i] = X_{N_i}` + - first: :math:`Out[i]` = X_0 + + where :math:`N_i` is the length of i-th input sequence. + + .. code-block:: text + + Case 1: + input is a 1-level LoDTensor and pad_value = 0.0: + input.lod = [[0, 2, 5, 7, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + output is LoDTensor: + out.shape = [4, 1] + with condition out.shape[0] == len(x.lod[-1]) == 4 + + for different pool_type: + average: out.data = [[2.], [4.], [3.], [0.0]], where 2.=(1. + 3.)/2, 4.=(2. + 4. + 6.)/3, 3.=(5. + 1.)/2 + sum : out.data = [[4.], [12.], [6.], [0.0]], where 4.=1. + 3., 12.=2. + 4. + 6., 6.=5. + 1. + sqrt : out.data = [[2.82], [6.93], [4.24], [0.0]], where 2.82=(1. + 3.)/sqrt(2), 6.93=(2. + 4. + 6.)/sqrt(3), 4.24=(5. + 1.)/sqrt(2) + max : out.data = [[3.], [6.], [5.], [0.0]], where 3.=max(1., 3.), 6.=max(2., 4., 6.), 5.=max(5., 1.) + last : out.data = [[3.], [6.], [1.], [0.0]], where 3.=last(1., 3.), 6.=last(2., 4., 6.), 1.=last(5., 1.) + first : out.data = [[1.], [2.], [5.], [0.0]], where 1.=first(1., 3.), 2.=first(2., 4., 6.), 5.=first(5., 1.) + + and all above [0.0] at last of out.data is padding data. + + Case 2: + input is a 2-level LoDTensor containing 3 sequences with length info [2, 0, 3], + where 0 means empty sequence. + The first sequence contains 2 subsequence with length info [1, 2]; + The last sequence contains 3 subsequence with length info [1, 0, 3]. + input.lod = [[0, 2, 2, 5], [0, 1, 3, 4, 4, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + If pool_typ = sum, it will apply pooling on last lod_level [0, 1, 3, 4, 4, 7]. pad_value = 0.0 + output is LoDTensor: + out.shape= [5, 1] + out.lod = [[0, 2, 2, 5]] + where out.shape[0] == len(x.lod[-1]) == 5 + sum: out.data = [[1.], [5.], [4.], [0.0], [12.]] + where 1.=1., 5.=3. + 2., 4.=4., 0.0=pad_value, 12.=6. + 5. + 1. + + Args: + input (variable): LoDTensor with lod_level no more than 2. The data type should be float32 or float64. + pool_type (str): The pooling type that supports average, sum, sqrt, max, last or first. + is_test (bool): Only works when :attr:`pool_type` is max. If set False, a temporary Tenosr maxIndex is + created to record the index information corresponding to the maximum value, which is used for backward + gradient calculation in the training phase. Default: False. + pad_value (float): Used to pad the pooling result for empty input sequence. Default: 0.0 + + Returns: + Variable: LoDTensor after pooling with data type float32 or float64. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 10], dtype='float32', lod_level=1) + avg_x = paddle.static.nn.sequence_pool(input=x, pool_type='average') + sum_x = paddle.static.nn.sequence_pool(input=x, pool_type='sum') + sqrt_x = paddle.static.nn.sequence_pool(input=x, pool_type='sqrt') + max_x = paddle.static.nn.sequence_pool(input=x, pool_type='max') + last_x = paddle.static.nn.sequence_pool(input=x, pool_type='last') + first_x = paddle.static.nn.sequence_pool(input=x, pool_type='first') + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'sequence_pool') + helper = LayerHelper('sequence_pool', **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + max_index = helper.create_variable_for_type_inference(dtype) + + helper.append_op(type="sequence_pool", + inputs={"X": input}, + outputs={ + "Out": pool_out, + "MaxIndex": max_index + }, + attrs={ + "pooltype": pool_type.upper(), + "is_test": is_test, + "pad_value": pad_value + }) + + # when pool_type is max, variable max_index is initialized, + # so we stop the gradient explicitly here + if pool_type == 'max': + max_index.stop_gradient = True + + return pool_out + + +@templatedoc() +def sequence_concat(input, name=None): + """ + + Note: + Only receives LoDTensor as input. If your input is Tensor, please use concat Op.(fluid.layers.** :ref:`api_fluid_layers_concat` ). + + This operator only supports LoDTensor as input. It concatenates the multiple LoDTensor from input by the LoD information, + and outputs the concatenated LoDTensor. + + .. code-block:: text + + input is a list of LoDTensor: + input = [x1, x2] + where: + x1.lod = [[0, 3, 5]] + x1.data = [[1], [2], [3], [4], [5]] + x1.shape = [5, 1] + + x2.lod = [[0, 2, 4]] + x2.data = [[6], [7], [8], [9]] + x2.shape = [4, 1] + and should satisfy: len(x1.lod[0]) == len(x2.lod[0]) + + output is LoDTensor: + out.lod = [[0, 3+2, 5+4]] + out.data = [[1], [2], [3], [6], [7], [4], [5], [8], [9]] + out.shape = [9, 1] + + Args: + input(list of Variable): List of LoDTensor to be concatenated. The length of each LoDTensor should be same. + The data type can be float32, float64 or int64. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: Output the concatenated LoDTensor. The data type is same as input. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[-1, 10], dtype='float32', lod_level=1) + y = paddle.static.data(name='y', shape=[-1, 10], dtype='float32', lod_level=1) + out = paddle.static.nn.sequence_concat(input=[x, y]) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_concat', **locals()) + + check_type(input, 'input', list, 'fluid.layers.sequence_concat') + for i, input_x in enumerate(input): + check_variable_and_dtype(input_x, 'input[' + str(i) + ']', + ['int64', 'float32', 'float64'], + 'fluid.layers.sequence_concat') + + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + helper.append_op(type='sequence_concat', + inputs={'X': input}, + outputs={'Out': [out]}) + return out + + +def sequence_first_step(input): + """ + + Only supports LoDTensor as input. Given the input LoDTensor, it will + select first time-step feature of each sequence as output. + + .. code-block:: text + + Case 1: + input is 1-level LoDTensor: + input.lod = [[0, 2, 5, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + output is a LoDTensor: + out.shape = [3, 1] + out.shape[0] == len(x.lod[-1]) == 3 + out.data = [[1.], [2.], [5.]], where 1.=first(1., 3.), 2.=first(2., 4., 6.), 5.=first(5., 1.) + + Case 2: + input is a 2-level LoDTensor containing 3 sequences with length info [2, 0, 3], + where 0 means empty sequence. + The first sequence contains 2 subsequence with length info [1, 2]; + The last sequence contains 3 subsequence with length info [1, 0, 3]. + input.lod = [[0, 2, 2, 5], [0, 1, 3, 4, 4, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + It will apply pooling on last lod_level [0, 1, 3, 4, 4, 7]. pad_value = 0.0 + output is a LoDTensor: + out.shape= [5, 1] + out.lod = [[0, 2, 2, 5]] + out.shape[0] == len(x.lod[-1]) == 5 + out.data = [[1.], [3.], [4.], [0.0], [6.]] + where 1.=first(1.), 3.=first(3., 2.), 4.=first(4.), 0.0 = pad_value, 6.=first(6., 5., 1.) + + Args: + input(Variable): LoDTensor with lod_level no more than 2. The data type should be float32 or float64. + + Returns: + Variable: LoDTensor consist of the sequence's first step vector. The data type is float32 or float64. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 10], dtype='float32', lod_level=1) + x_first_step = paddle.static.nn.sequence_first_step(input=x) + """ + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'sequence_first_step') + return sequence_pool(input=input, pool_type="first") + + +def sequence_last_step(input): + """ + + Only supports LoDTensor as input. Given the input LoDTensor, it will + select last time-step feature of each sequence as output. + + .. code-block:: text + + Case 1: + input is 1-level LoDTensor: + input.lod = [[0, 2, 5, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + output is a LoDTensor: + out.shape = [3, 1] + out.shape[0] == len(x.lod[-1]) == 3 + out.data = [[3.], [6.], [1.]], where 3.=last(1., 3.), 6.=last(2., 4., 6.), 1.=last(5., 1.) + + Case 2: + input is a 2-level LoDTensor containing 3 sequences with length info [2, 0, 3], + where 0 means empty sequence. + The first sequence contains 2 subsequence with length info [1, 2]; + The last sequence contains 3 subsequence with length info [1, 0, 3]. + input.lod = [[0, 2, 2, 5], [0, 1, 3, 4, 4, 7]] + input.data = [[1.], [3.], [2.], [4.], [6.], [5.], [1.]] + input.shape = [7, 1] + + It will apply pooling on last lod_level [0, 1, 3, 4, 4, 7]. pad_value = 0.0 + output is a LoDTensor: + out.shape= [5, 1] + out.lod = [[0, 2, 2, 5]] + out.shape[0] == len(x.lod[-1]) == 5 + out.data = [[1.], [2.], [4.], [0.0], [1.]] + where 1.=last(1.), 2.=last(3., 2.), 4.=last(4.), 0.0 = pad_value, 1=last(6., 5., 1.) + + + Args: + input(Variable): LoDTensor with lod_level no more than 2. The data type should be float32. + + Returns: + Variable: LoDTensor consist of the sequence's last step vector. The data type is float32. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 10], dtype='float32', lod_level=1) + x_last_step = paddle.static.nn.sequence_last_step(input=x) + """ + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'sequence_last_step') + return sequence_pool(input=input, pool_type="last") + + +def sequence_slice(input, offset, length, name=None): + """ + + **Sequence Slice Layer** + + The layer crops a subsequence from given sequence with given start + offset and subsequence length. + + It only supports sequence data (LoDTensor with lod_level equal to 1). + + .. code-block:: text + + - Case: + + Given the input Variable **input**: + + input.data = [[a1, a2], [b1, b2], [c1, c2], [d1, d2], [e1, e2]], + input.lod = [[3, 2]], + input.dims = (5, 2), + + with offset.data = [[0], [1]] and length.data = [[2], [1]], + + the output Variable will be + + out.data = [[a1, a2], [b1, b2], [e1, e2]], + out.lod = [[2, 1]], + out.dims = (3, 2). + + Note: + The first dimension size of **input**, **offset** and **length** + should be equal. The **offset** should start from 0. + + Args: + input(Variable): LoDTensor, The input Variable which consists of the complete + sequences.The data type can be float32, float64, int32 or int64 + offset(Variable): LoDTensor, The offset to slice each sequence. The data + type is int32 or int64. + length(Variable): LoDTensor, The length of each subsequence. The data + type is int32 or int64. + name(str|None): The default value is None. Normally there is no need + for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + + Returns: + Variable: The output subsequences. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + import numpy as np + seqs = paddle.static.data(name='x', shape=[10, 5], + dtype='float32', lod_level=1) + offset = paddle.assign(np.array([[0, 1]]).astype("int32")) + length = paddle.assign(np.array([[2, 1]]).astype("int32")) + subseqs = paddle.static.nn.sequence_slice(input=seqs, offset=offset, + length=length) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper("sequence_slice", **locals()) + + check_variable_and_dtype(input, 'input', + ['float32', 'float64', 'int32', 'int64'], + 'sequence_slice') + check_variable_and_dtype(offset, 'offset', ['int32', 'int64'], + 'sequence_slice') + check_variable_and_dtype(length, 'length', ['int32', 'int64'], + 'sequence_slice') + + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + + offset.stop_gradient = True + length.stop_gradient = True + + helper.append_op(type="sequence_slice", + inputs={ + "X": input, + "Offset": offset, + "Length": length + }, + outputs={"Out": out}) + + return out + + +def sequence_expand(x, y, ref_level=-1, name=None): + r""" + + Sequence Expand Layer. This layer will expand the input variable ``x`` \ + according to specified level ``ref_level`` lod of ``y``. Please note that \ + the lod level of ``x`` is at most 1. If the lod level of ``x`` is 1, than \ + the size of lod of ``x`` must be equal to the length of ``ref_level`` lod \ + of ``y``. If the lod level of ``x`` is 0, then the first dim of ``x`` should \ + be equal to the size of ``ref_level`` of ``y``. The rank of **x** is at least 2. \ + When rank of ``x`` is greater than 2, then it would be viewed as a 2-D tensor. + + Note: + + Please note that the input ``x`` should be LodTensor or Tensor, \ + and input ``y`` must be LodTensor. + + **Following examples will explain how sequence_expand works:** + + .. code-block:: text + + Case 1 + + Consider 2 sequences [a][b] and [c][d], now we want to expand them to [a][b], [a][b], [c][d] and [c][d]. + Sequence [a][b] expand twice and [c][d] expands twice, so the lod which according to is [2, 2]. + + Input x is a 1-level LoDTensor: + x.lod = [[2, 2]] #lod based on length may be easier to understand + x.data = [[a], [b], [c], [d]] + x.dims = [4, 1] + + input y is a LoDTensor: + y.lod = [[2, 2], #the 0th level lod, according to this level + [3, 3, 1, 1]] #the 1st level lod, it has nothing to do with this level + + ref_level: 0 + + then output is a 1-level LoDTensor out: + out.lod = [[2, 2, 2, 2]] #lod based on offset + out.data = [[a], [b], [a], [b], [c], [d], [c], [d]] + out.dims = [8, 1] + + + Case 2 + + Consider 3 sequences [a], [b], [c], now we want to expand them to [a][a], [c][c][c]. + It's obvious that the lod info of expanded sequences is [2, 0, 3]. + + x is a Tensor: + x.data = [[a], [b], [c]] + x.dims = [3, 1] + + y is a LoDTensor: + y.lod = [[2, 0, 3]] + + ref_level: -1 + + then output is a 1-level LodTensor: + out.data = [[a], [a], [c], [c], [c]] + out.dims = [5, 1] + + Args: + x (Variable): The input variable which is a Tensor or LoDTensor, with the \ + dims ``[M, K]``. The lod level is at most 1. The data type should be \ + float32, float64, int32 or int64. + y (Variable): The input variable which is a LoDTensor, the lod level is \ + at least 1. + ref_level (int): Lod level of ``y`` to be referred by ``x``. If set to -1, \ + refer the last level of lod. + name(str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The expanded variable which is a LoDTensor, with dims ``[N, K]``. \ + ``N`` depends on the lod info of ``x`` and ``y``. \ + The data type is same as input. + + Examples: + .. code-block:: python + + import paddle + from paddle import fluid + paddle.enable_static() + import numpy as np + + x = paddle.static.data(name='x', shape=[4, 1], dtype='float32') + y = paddle.static.data(name='y', shape=[8, 1], + dtype='float32', lod_level=1) + out = paddle.static.nn.sequence_expand(x=x, y=y, ref_level=0) + + exe = paddle.static.Executor(fluid.CPUPlace()) + place = paddle.CPUPlace() + + np_data = np.array([[1], [2], [3], [4]]).astype('float32') + x_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2]], place) + print(x_lod_tensor) + #lod: [[0, 2, 4]] + # dim: 4, 1 + # layout: NCHW + # dtype: float + # data: [1 2 3 4] + + np_data = np.array([[1], [2], [3], [4], [5], [6], [7], [8]]).astype('float32') + y_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2], [3,3,1,1]], place) + print(y_lod_tensor) + #lod: [[0, 2, 4][0, 3, 6, 7, 8]] + # dim: 8, 1 + # layout: NCHW + # dtype: int64_t + # data: [0 0 1 1 1 1 1 0] + + out_main = exe.run(fluid.default_main_program(), + feed={'x': x_lod_tensor, 'y': y_lod_tensor}, + fetch_list=[out], return_numpy=False) + print(out_main[0]) + #lod: [[0, 2, 4, 6, 8]] + # dim: 8, 1 + # layout: NCHW + # dtype: float + # data: [1 2 1 2 3 4 3 4] + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'sequence_expand') + helper = LayerHelper('sequence_expand', **locals()) + dtype = helper.input_dtype(input_param_name='x') + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='sequence_expand', + inputs={ + 'X': x, + 'Y': y + }, + outputs={'Out': tmp}, + attrs={'ref_level': ref_level}) + return tmp + + +def sequence_expand_as(x, y, name=None): + r""" + + Sequence Expand As Layer. This OP will expand the input variable ``x`` \ + according to the zeroth level lod of ``y``. Current implementation requires \ + the level number of ``y``'s lod must be 1, and the first dimension of \ + ``x`` should be equal to the size of ``y``'s zeroth level lod, thus \ + the expanded LodTensor has the same lod info as ``y``. The expanded result \ + has nothing to do with ``x``'s lod, so the lod of Input(X) is not considered. + + Note: + Please note that the input ``x`` should be LodTensor or Tensor, \ + and input ``y`` must be LodTensor. + + Following examples will explain how sequence_expand_as works: + + .. code-block:: text + + Case 1: + + Consider 4 sequences [a], [b], [c], [d], now we want to expand them to [a][a][a], [b][b][b], [c] and [d]. + It's obvious that the lod info of expanded sequences is [0, 3, 6, 7, 8]. + Given a 1-level LodTensor ``x``: + x.data = [[a], [b], [c], [d]] + x.dims = [4, 1] + and input ``y`` + y.lod = [[3, 3, 1, 1]] #lod based on length may be easier to understand + + then we get 1-level LoDTensor out: + Out.lod = [[0, 3, 6, 7, 8]] #based on offset + Out.data = [[a], [a], [a], [b], [b], [b], [c], [d]] + Out.dims = [8, 1] + + + Case 2: + + Given a common Tensor ``x``: + x.data = [[a, b], [c, d], [e, f]] + x.dims = [3, 2] + and input ``y``: + y.lod = [[0, 2, 3, 6]] + + then we get a 1-level LoDTensor: + out.lod = [[0, 2, 3, 6]] + out.data = [[a, b], [a, b] [c, d], [e, f], [e, f], [e, f]] + out.dims = [6, 2] + + Args: + x (Variable): The input variable which is a Tensor or LoDTensor, with the \ + dims ``[M, K]``. The data type should be float32, float64, int32 \ + or int64. + y (Variable): The input variable which is a LoDTensor with 1-level lod. + name (str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The expanded variable which is a LoDTensor with the dims ``[N, K]``. \ + ``N`` depends on the lod of ``y``, and the lod level must be 1. \ + The data type is same as input. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + paddle.enable_static() + import numpy as np + + x = paddle.static.data(name='x', shape=[4, 1], dtype='float32') + y = paddle.static.data(name='y', shape=[8, 1], dtype='float32', lod_level=1) + out = paddle.static.nn.sequence_expand_as(x=x, y=y) + + exe = fluid.Executor(fluid.CPUPlace()) + place = fluid.CPUPlace() + + np_data = np.array([[1], [2], [3], [4]]).astype('float32') + x_lod_tensor = fluid.create_lod_tensor(np_data, [[2, 2]], place) + print(x_lod_tensor) + #lod: [[0, 2, 4]] + # dim: 4, 1 + # layout: NCHW + # dtype: float + # data: [1 2 3 4] + + np_data = np.array([[1], [2], [3], [4], [5], [6], [7], [8]]).astype('float32') + y_lod_tensor = fluid.create_lod_tensor(np_data, [[3,3,1,1]], place) + print(y_lod_tensor) + #lod: [[0, 3, 6, 7, 8]] + # dim: 8, 1 + # layout: NCHW + # dtype: int64_t + # data: [0 0 1 0 1 1 1 0] + + out_main = exe.run(fluid.default_main_program(), + feed={'x': x_lod_tensor, 'y': y_lod_tensor}, + fetch_list=[out], return_numpy=False) + print(out_main[0]) + #lod: [[0, 3, 6, 7, 8]] + # dim: 8, 1 + # layout: NCHW + # dtype: float + # data: [1 1 1 2 2 2 3 4] + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'sequence_expand_as') + check_type(y, 'y', Variable, 'sequence_expand_as') + helper = LayerHelper('sequence_expand_as', **locals()) + dtype = helper.input_dtype(input_param_name='x') + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='sequence_expand_as', + inputs={ + 'X': x, + 'Y': y + }, + outputs={'Out': tmp}) + return tmp + + +def sequence_pad(x, pad_value, maxlen=None, name=None): + r""" + + This layer padding the sequences in a same batch to a common length (according + to ``maxlen``). The padding value is defined by ``pad_value``, and will be + appended to the tail of sequences. The result is a Python tuple ``(Out, Length)``: + the LodTensor ``Out`` is the padded sequences, and LodTensor ``Length`` is + the length information of input sequences. For removing padding data (unpadding operation), See :ref:`api_fluid_layers_sequence_unpad`. + + Note: + Please note that the input ``x`` should be LodTensor. + + .. code-block:: text + + Case 1: + Given input 1-level LoDTensor x: + x.lod = [[0, 2, 5]] + x.data = [[a],[b],[c],[d],[e]] + pad_value: + pad_value.data = [0] + maxlen = 4 + + the output tuple (Out, Length): + Out.data = [[[a],[b],[0],[0]],[[c],[d],[e],[0]]] + Length.data = [2, 3] #Original sequences length + + Case 2: + Given input 1-level LoDTensor x: + x.lod = [[0, 2, 5]] + x.data = [[a1,a2],[b1,b2],[c1,c2],[d1,d2],[e1,e2]] + pad_value: + pad_value.data = [0] + default maxlen = None, (the virtual value is 3, according to the shape of x) + + the output tuple (Out, Length): + Out.data = [[[a1,a2],[b1,b2],[0,0]],[[c1,c2],[d1,d2],[e1,e2]]] + Length.data = [2, 3] + + Case 3: + Given input 1-level LoDTensor x: + x.lod = [[0, 2, 5]] + x.data = [[a1,a2],[b1,b2],[c1,c2],[d1,d2],[e1,e2]] + pad_value: + pad_value.data = [p1,p2] + default maxlen = None, (the virtual value is 3) + + get tuple (Out, Length): + Out.data = [[[a1,a2],[b1,b2],[p1,p2]],[[c1,c2],[d1,d2],[e1,e2]]] + Length.data = [2, 3] + + + + Args: + x (Variable): Input 1-level LodTensor with dims ``[M, K]``. The batch \ + size is described by lod infor (the number of sequences ). \ + The data type should be float32, float64, int8, int32 or int64. + pad_value (Variable): Padding value. It can be a scalar or a 1D tensor \ + with length ``K``. If it's a scalar, it will be automatically broadcasted \ + to a Tensor. The data type should be as same as ``x``. + maxlen (int, optional): The length of padded sequences, None by default. \ + When it is None, all sequences will be padded up to the length of the \ + longest one among them; when it a certain positive value, it must be \ + greater than the length of the longest original sequence. + name (str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + tuple, A Python tuple (Out, Length): the 1st is a 0 level LodTensor \ + ``Out``, with the shape ``[batch_size, maxlen, K]``; the second is the original \ + sequences length infor ``Length``, which should be a 0-level 1D LodTensor. \ + The size of ``Length`` is equal to batch size, and the data type is int64. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.fluid as fluid + import numpy + + x = paddle.static.data(name='x', shape=[10, 5], dtype='float32', lod_level=1) + pad_value = paddle.assign( + numpy.array([0.0], dtype=numpy.float32)) + out = paddle.static.nn.sequence_pad(x=x, pad_value=pad_value) + """ + + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_pad', **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'fluid.layers.sequence_pad') + check_variable_and_dtype(pad_value, 'pad_value', + ['float32', 'float64', 'int32', 'int64'], + 'fluid.layers.sequence_pad') + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + length = helper.create_variable_for_type_inference(VarDesc.VarType.INT64) + + pad_value.stop_gradient = True + length.stop_gradient = True + + if maxlen is None: + maxlen = -1 + helper.append_op(type='sequence_pad', + inputs={ + 'X': x, + 'PadValue': pad_value + }, + outputs={ + 'Out': out, + 'Length': length + }, + attrs={'padded_length': maxlen}) + return out, length + + +def sequence_unpad(x, length, name=None): + """ + + Note: + The input of the OP is Tensor and the output is LoDTensor. For padding operation, See:** :ref:`api_fluid_layers_sequence_pad` + + Remove the padding data from the input based on the length information and returns a LoDTensor. + + .. code-block:: text + + Case 1: + + Given input Variable **x**: + x.data = [[ 1.0, 2.0, 3.0, 4.0, 5.0], + [ 6.0, 7.0, 8.0, 9.0, 10.0], + [11.0, 12.0, 13.0, 14.0, 15.0]], + + in which there are 3 sequences padded to length 5, and the actual length + specified by input Variable **length**: + + length.data = [2, 3, 4], + + after unpadding, the output Variable will be: + + out.data = [[1.0, 2.0, 6.0, 7.0, 8.0, 11.0, 12.0, 13.0, 14.0]] + out.lod = [[0, 2, 5, 9]] + + Args: + x(Variable): A Tensor which contains padding data, and its shape size can not be less than 2. + Supported data types: float32, float64, int32, int64. + length(Variable): A 1D Tensor that stores the actual length of each sample, and the Tensor + has the same shape with the 0th dimension of the X . Supported data types: int64. + name(str|None): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + Variable: A LoDTensor whose recursive sequence length is consistent with the information of the length parameter and it has the same data type with input. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + import paddle.fluid as fluid + import numpy + + # pad data + x = paddle.static.data(name='x', shape=[10, 5], dtype='float32', lod_level=1) + pad_value = paddle.assign(numpy.array([0.0], dtype=numpy.float32)) + pad_data, len = paddle.static.nn.sequence_pad(x=x, pad_value=pad_value) + + # unpad data + unpad_data = paddle.static.nn.sequence_unpad(x=pad_data, length=len) + """ + + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_unpad', **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'fluid.layers.sequence_unpad') + check_variable_and_dtype(length, 'length', ['int64'], + 'fluid.layers.sequence_unpad') + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + + length.stop_gradient = True + + helper.append_op(type='sequence_unpad', + inputs={ + 'X': x, + 'Length': length + }, + outputs={'Out': out}) + return out + + +def sequence_reshape(input, new_dim): + """ + + Note: + Only receives LoDTensor as input. If your input is Tensor, please use reshape Op.(fluid.layers.** :ref:`api_fluid_layers_reshape` ). + + Only supports LoDTensor as input. Given :attr:`new_dim` , + it will compute new shape according to original length of each sequence, + original dimensions and :attr:`new_dim` . Then it will output a new LoDTensor + containing :attr:`new_dim` . Currently it only supports 1-level LoDTensor. + Please make sure that (original length * original dimensions) can be divided + by the :attr:`new_dim` with no remainder for each sequence. + + .. code-block:: text + + input is a LoDTensor: + input.lod = [[0, 2, 6]] + input.data = [[1, 2], [3, 4], + [5, 6], [7, 8], + [9, 10], [11, 12]] + input.shape = [6, 2] + + set new_dim = 4 + out is a LoDTensor: + out.lod = [[0, 1, 3]] + out.data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out.shape = [3, 4] + + + Args: + + input (Variable): 1-level LoDTensor with shape :math:`[M, K]` . The data type should + be int32, int64, float32 or float64. + new_dim (int): New dimension that the input LoDTensor is reshaped to. + + Returns: + Variable: Reshaped LoDTensor according to new dimension. The data type is same as input. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 16], dtype='float32', lod_level=1) + x_reshaped = paddle.static.nn.sequence_reshape(input=x, new_dim=4) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_reshape', **locals()) + check_variable_and_dtype(input, 'input', + ['float32', 'float64', 'int32', 'int64'], + 'fluid.layers.sequence_reshape') + out = helper.create_variable_for_type_inference(helper.input_dtype()) + helper.append_op(type='sequence_reshape', + inputs={'X': [input]}, + outputs={'Out': [out]}, + attrs={'new_dim': new_dim}) + return out + + +def sequence_scatter(input, index, updates, name=None): + """ + + Note: + The index and updates parameters of the OP must be LoDTensor. + + Plus the updates data to the corresponding input according to the index. + + The updated algorithm is as follows: output[instance_index][index [pos]] = input[instance_index][index [pos]] + updates[pos], + where instance_idx is the K sample corresponding to pos in batch. + + The value of output[i][j] depends on whether j can be found in the i+1th interval of the index. If found, + out[i][j] = input[i][j] + update[m] [n], otherwise, out[i][j] = input[i][j]. + + For example, in the following example, the lod information for index is divided into three sequences. Among + them, because the element 0 can be found in the first interval of the index, it is updated with the value of + the corresponding position of the updates, out[0][0] = input[0][0]+updates[0][0] . Because element 1 cannot + be found in the third interval of index, out[2][1] = input[2][1]. + + .. code-block:: text + + *Case 1: + + Given: + input.data = [[1.0, 1.0, 1.0, 1.0, 1.0, 1.0], + [1.0, 1.0, 1.0, 1.0, 1.0, 1.0], + [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]] + input.dims = [3, 6] + + index.data = [[0], [1], [2], [5], [4], [3], [2], [1], [3], [2], [5], [4]] + index.lod = [[0, 3, 8, 12]] + + updates.data = [[0.3], [0.3], [0.4], [0.1], [0.2], [0.3], [0.4], [0.0], [0.2], [0.3], [0.1], [0.4]] + updates.lod = [[ 0, 3, 8, 12]] + + Then: + out.data = [[1.3, 1.3, 1.4, 1.0, 1.0, 1.0], + [1.0, 1.0, 1.4, 1.3, 1.2, 1.1], + [1.0, 1.0, 1.3, 1.2, 1.4, 1.1]] + out.dims = X.dims = [3, 6] + + Args: + input (Variable): A Tensor with shape of :math:`[N, k_1... k_n]`. Supported data types: float32, float64, int32, int64. + index (Variable): A LoDTensor contains index information. Its LoD level must be 1 and its data type can be int32 or int64. + updates (Variable): A LodTensor contains updates information. It has the same LoD level with the index and has the + same data type with the input. Supported data types: float32, float64, int32, int64. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + + Returns: + Variable: A Tensor which has been updated. It has the same shape and data type with input. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + + input = paddle.static.data(name="x", shape=[None, 3, 6], dtype='float32' ) + index = paddle.static.data(name='index', shape=[12, 1], dtype='int64', lod_level=1) + updates = paddle.static.data(name='updates', shape=[12, 1], dtype='float32', lod_level=1) + output = paddle.static.nn.sequence_scatter(input, index, updates) + + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper('sequence_scatter', **locals()) + + check_variable_and_dtype(input, 'input', + ['float32', 'float64', 'int32', 'int64'], + 'sequence_scatter') + check_variable_and_dtype(index, 'index', ['int32', 'int64'], + 'sequence_scatter') + check_variable_and_dtype(updates, 'updates', + ['float32', 'float64', 'int32', 'int64'], + 'sequence_scatter') + + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="sequence_scatter", + inputs={ + "X": input, + "Ids": index, + "Updates": updates + }, + outputs={"Out": out}) + return out + + +def sequence_enumerate(input, win_size, pad_value=0, name=None): + r""" + + Generate a new sequence for the input index sequence with \ + shape ``[d_1, win_size]``, which enumerates all the \ + sub-sequences with length ``win_size`` of the input with \ + shape ``[d_1, 1]``, and padded by ``pad_value`` if necessary in generation. + + Please note that the `input` must be LodTensor. + + .. code-block:: text + + Input x: + x.lod = [[0, 3, 5]] + x.data = [[1], [2], [3], [4], [5]] + x.dims = [5, 1] + + Attrs: + win_size = 2 + pad_value = 0 + + Output: + out.lod = [[0, 3, 5]] + out.data = [[1, 2], [2, 3], [3, 0], [4, 5], [5, 0]] + out.dims = [5, 2] + + + Args: + input (Variable): The input variable which is a index sequence, \ + which should be a LodTensor with shape ``[d_1, 1]`` and 1-level lod info. \ + The data type should be int32 or int64. + win_size (int): The window size for enumerating all sub-sequences. + pad_value (int, optional): The padding value, default 0. + name(str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The enumerate sequence variable which is a LoDTensor with \ + shape ``[d_1, win_size]`` and 1-level lod info. \ + The data type is same as ``input``. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[-1, 1], dtype='int32', lod_level=1) + out = paddle.static.nn.sequence_enumerate(input=x, win_size=3, pad_value=0) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + check_variable_and_dtype(input, 'input', ['int32', 'int64'], + 'sequence_enumerate') + helper = LayerHelper('sequence_enumerate', **locals()) + out = helper.create_variable_for_type_inference(helper.input_dtype(), + stop_gradient=True) + helper.append_op(type='sequence_enumerate', + inputs={'X': input}, + outputs={'Out': out}, + attrs={ + 'win_size': win_size, + 'pad_value': pad_value + }) + return out + + +def sequence_mask(x, maxlen=None, dtype='int64', name=None): + r""" + **SequenceMask Layer** + + This layer outputs a mask according to the input :code:`x` and + :code:`maxlen` with data type of :code:`dtype`. + + Supposing :code:`x` is a Tensor with shape [d_1, d_2, ..., d_n], the + :code:`y` is a mask with shape [d_1, d_2, ..., d_n, maxlen], where: + + .. math:: + + y(i_1, i_2,..., i_n, j) = (j < x(i_1, i_2,..., i_n)) + + .. code-block:: text + + Case: + + Consider input: + x = [3, 1, 1, 0] max_len = 4 + + then we get out: + mask = [[1, 1, 1, 0], + [1, 0, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, 0]] + + Args: + x (Variable): Input tensor of sequence_mask layer, \ + whose elements are integers less than :code:`maxlen`. \ + Tensor or LodTensor with shape [d_1, d_2, ..., d_n]. + maxlen (int, optional): Maximum length of the sequence. If :code:`maxlen` \ + is None, it would be replace with :math:`max(x)`. + dtype (np.dtype|paddle.dtype|str, optional): Data type of the output, \ + ``int64`` by default. + name(str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The output sequence mask. Tensor with shape [d_1, d_2, ..., d_n, maxlen] + and data type of :code:`dtype`. The data type should be bool, float32, float64, int8, + int32 or int64. + + Examples: + .. code-block:: python + + import paddle + + lengths = paddle.to_tensor([10, 9, 8]) + mask = paddle.nn.functional.sequence_mask(lengths) + + print(mask.numpy()) + # [[1 1 1 1 1 1 1 1 1 1] + # [1 1 1 1 1 1 1 1 1 0] + # [1 1 1 1 1 1 1 1 0 0]] + + """ + + return paddle.nn.functional.sequence_mask(x, maxlen, dtype, name) + + +@templatedoc() +def sequence_reverse(x, name=None): + """ + Note: + Only receives LoDTensor as input. If your input is Tensor, please use reverse Op.(fluid.layers.** :ref:`api_fluid_layers_reverse` ). + + Only supports LoDTensor as input. It will reverse each sequence for input LoDTensor. + Currently it only supports 1-level LoDTensor. This operator is very useful when building a + reverse :ref:`api_fluid_layers_DynamicRNN` network. + + .. code-block:: text + + input(x) is a LoDTensor: + x.lod = [[0, 2, 5]] + x.data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13,14, 15, 16], + [17,18, 19, 20]] + x.shape = [5, 4] + + output LoDTensor with same shape and LoD info: + out.lod = [[0, 2, 5]] + out.data = [[5, 6, 7, 8], + [1, 2, 3, 4], + [17,18, 19, 20], + [13,14, 15, 16], + [9, 10, 11, 12]] + out.shape = [5, 4] + + Args: + x(Variable): LoDTensor with 1-level LoD info. Currently it only supports 1-level LoDTensor. + The data type should be float32, float64, int8, int32 or int64. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Variable: LoDTensor reversed from input. The data type is same with input. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + x = paddle.static.data(name='x', shape=[None, 10], dtype='float32', lod_level=1) + x_reversed = paddle.static.nn.sequence_reverse(x) + """ + assert not _non_static_mode(), ( + "sequence layer is not supported in dygraph mode yet.") + helper = LayerHelper("sequence_reverse", **locals()) + check_variable_and_dtype(x, 'x', + ['float32', 'float64', 'int8', 'int32', 'int64'], + 'fluid.layers.sequence_reverse') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type="sequence_reverse", + inputs={"X": x}, + outputs={"Y": out}, + attrs=dict()) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/tensor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..3973a7187908bfbbc405edbfdb696ae6e1e608da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/tensor.py @@ -0,0 +1,1897 @@ +# Copyright (c) 2022 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 +# +# Unlessf 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. + +from __future__ import print_function + +import math +import numpy +import warnings + +from ..layer_helper import LayerHelper +from ..param_attr import ParamAttr +from ..initializer import Initializer +from ..framework import _current_expected_place, convert_np_dtype_to_dtype_, _non_static_mode, _varbase_creator, device_guard, _in_legacy_dygraph, in_dygraph_mode, _get_paddle_place +from ..framework import Variable +from ..initializer import Constant +from ..core import VarDesc +from .. import core +from .layer_function_generator import templatedoc +from . import utils +from ..data_feeder import check_variable_and_dtype, check_type, check_dtype, convert_dtype +from paddle.utils import deprecated + +from .utils import check_shape +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ + 'create_tensor', + 'create_parameter', + 'create_global_var', + 'cast', + 'tensor_array_to_tensor', + 'concat', + 'sums', + 'assign', + 'fill_constant_batch_size_like', + 'fill_constant', + 'argmin', + 'argmax', + 'argsort', + 'ones', + 'zeros', + 'reverse', + 'has_inf', + 'has_nan', + 'isfinite', + 'range', + 'linspace', + 'zeros_like', + 'ones_like', + 'diag', + 'eye', + 'triu', +] + + +def create_tensor(dtype, name=None, persistable=False): + """ + Create a variable, which will hold a Tensor with data type dtype. + + Args: + dtype(string|numpy.dtype): the data type of Tensor to be created, the + data type is bool, float16, float32, float64, int8, int16, int32 and int64. + name(string, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + persistable(bool): Set the persistable flag of the create tensor. + default value is False. + + Returns: + Variable: The tensor to be created according to dtype. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + tensor = fluid.layers.create_tensor(dtype='float32') + """ + check_dtype(dtype, 'dtype', [ + 'bool', 'float16', 'float32', 'float64', 'int8', 'int32', 'int32', + 'int64' + ], 'create_tensor') + helper = LayerHelper("create_tensor", **locals()) + return helper.create_variable(name=helper.name, + dtype=dtype, + persistable=persistable) + + +def create_parameter(shape, + dtype, + name=None, + attr=None, + is_bias=False, + default_initializer=None): + """ + :api_attr: Static Graph + + This function creates a parameter. The parameter is a learnable variable, which can have + gradient, and can be optimized. + + NOTE: this is a very low-level API. This API is useful when you create + operator by your self. instead of using layers. + + Parameters: + shape (list of int): Shape of the parameter + dtype (str): Data type of the parameter + name (str, optional): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + attr (ParamAttr, optional): Attributes of the parameter + is_bias (bool, optional): This can affect which default initializer is chosen + when default_initializer is None. If is_bias, + initializer.Constant(0.0) will be used. Otherwise, + Xavier() will be used. + default_initializer (Initializer, optional): Initializer for the parameter + + Returns: + The created parameter. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + W = paddle.static.create_parameter(shape=[784, 200], dtype='float32') + """ + check_type(shape, 'shape', (list, tuple, numpy.ndarray), 'create_parameter') + for item in shape: + check_type(item, 'item of shape', + (int, numpy.uint8, numpy.int8, numpy.int16, numpy.int32, + numpy.int64), 'create_parameter') + + check_dtype(dtype, 'dtype', [ + 'bool', 'float16', 'float32', 'float64', 'int8', 'int16', 'int32', + 'int64', 'uint8' + ], 'create_parameter') + check_type(attr, 'attr', (type(None), ParamAttr), 'create_parameter') + check_type(default_initializer, 'default_initializer', + (type(None), Initializer), 'create_parameter') + + helper = LayerHelper("create_parameter", **locals()) + if attr is None: + attr = ParamAttr(name=name) + return helper.create_parameter(attr, shape, convert_dtype(dtype), is_bias, + default_initializer) + + +def create_global_var(shape, + value, + dtype, + persistable=False, + force_cpu=False, + name=None): + """ + This function creates a new tensor variable with value in the global block(block 0). + + Parameters: + shape (list[int]|tuple[int]): Shape of the variable + value (float): The value of the variable. The new created + variable will be filled with it. + dtype (str): Data type of the variable + persistable (bool, optional): If this variable is persistable. + Default: False + force_cpu (bool, optional): Force this variable to be on CPU. + Default: False + name (str, optional): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Variable: The created Variable + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + var = paddle.static.create_global_var(shape=[2,3], value=1.0, dtype='float32', + persistable=True, force_cpu=True, name='new_var') + """ + check_type(shape, 'shape', (list, tuple, numpy.ndarray), + 'create_global_var') + for item in shape: + check_type(item, 'item of shape', + (int, numpy.uint8, numpy.int8, numpy.int16, numpy.int32, + numpy.int64), 'create_global_var') + + check_dtype(dtype, 'dtype', [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int8', + 'int16', + 'int32', + 'int64', + 'uint8', + 'uint16', + ], 'create_global_var') + + helper = LayerHelper("global_var", **locals()) + var = helper.create_global_variable(dtype=dtype, + shape=shape, + persistable=persistable, + name=name, + stop_gradient=True) + helper.set_variable_initializer(var, + initializer=Constant(value=float(value), + force_cpu=force_cpu)) + + return var + + +def cast(x, dtype): + """ + + This OP takes in the Tensor :attr:`x` with :attr:`x.dtype` and casts it + to the output with :attr:`dtype`. It's meaningless if the output dtype + equals the input dtype, but it's fine if you do so. + + Args: + x(Tensor): An input N-D Tensor with data type bool, float16, + float32, float64, int32, int64, uint8. + dtype(np.dtype|str): Data type of the output: + bool, float16, float32, float64, int8, int32, int64, uint8. + + Returns: + Tensor: A Tensor with the same shape as input's. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 4], 'float64') + y = paddle.cast(x, 'uint8') + """ + if in_dygraph_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + return _C_ops.cast(x, dtype) + + if _non_static_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + out = _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + return out + + check_variable_and_dtype(x, 'x', [ + 'bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64', + 'uint8', 'uint16' + ], 'cast') + check_dtype(dtype, 'dtype', [ + 'bool', 'float16', 'float32', 'float64', 'int8', 'int16', 'int32', + 'int64', 'uint8', 'uint16' + ], 'cast') + + helper = LayerHelper('cast', **locals()) + out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=x.stop_gradient) + helper.append_op(type='cast', + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={ + 'in_dtype': x.dtype, + 'out_dtype': out.dtype + }) + return out + + +def concat(input, axis=0, name=None): + """ + This OP concatenates the input along the axis. + + Args: + input(list|tuple|Tensor): ``input`` can be Tensor, Tensor list or Tensor tuple which is with data type + bool, float16, float32, float64, int32, int64. All the Tensors in ``input`` must have the same data type. + axis(int|Tensor, optional): Specify the axis to operate on the input Tensors. + It's a scalar with data type int or a Tensor with shape [1] and data type int32 or int64. + The effective range is [-R, R), where R is Rank(x). When ``axis < 0``, it works the same way + as ``axis+R``. Default is 0. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor with the same data type as ``input``. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + in1 = np.array([[1, 2, 3], + [4, 5, 6]]) + in2 = np.array([[11, 12, 13], + [14, 15, 16]]) + in3 = np.array([[21, 22], + [23, 24]]) + with fluid.dygraph.guard(): + x1 = fluid.dygraph.to_variable(in1) + x2 = fluid.dygraph.to_variable(in2) + x3 = fluid.dygraph.to_variable(in3) + # When the axis is negative, the real axis is (axis + Rank(x)). + # As follows, axis is -1, Rank(x) is 2, the real axis is 1 + out1 = fluid.layers.concat(input=[x1, x2, x3], axis=-1) + out2 = fluid.layers.concat(input=[x1, x2], axis=0) + print(out1.numpy()) + # [[ 1 2 3 11 12 13 21 22] + # [ 4 5 6 14 15 16 23 24]] + print(out2.numpy()) + # [[ 1 2 3] + # [ 4 5 6] + # [11 12 13] + # [14 15 16]] + """ + + if in_dygraph_mode(): + if isinstance(axis, Variable): + axis = axis.numpy() + axis = axis.item(0) + if not isinstance(input, Variable): + input = [t for t in input if t.shape.count(0) == 0] + out = _C_ops.concat(input, axis) + return out + + if _in_legacy_dygraph(): + if isinstance(axis, Variable): + axis = axis.numpy() + axis = axis.item(0) + if not isinstance(input, Variable): + input = [t for t in input if t.shape.count(0) == 0] + out = _varbase_creator() + _legacy_C_ops.concat(input, out, 'axis', axis) + return out + + check_type(input, 'input', (list, tuple, Variable), 'concat') + if not isinstance(input, Variable): + for id, x in enumerate(input): + check_variable_and_dtype( + x, 'input[' + str(id) + ']', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'concat') + if x.dtype != input[0].dtype: + raise TypeError( + "All the Tensors in the input must have the same data type." + ) + else: + input = [input] + check_type(axis, 'axis', (int, Variable), 'concat') + + if isinstance(axis, Variable): + check_dtype( + axis.dtype, 'axis', ['int32', 'int64'], 'concat', + "The data type of axis must be int32 or int64 when axis is a Tensor" + ) + + helper = LayerHelper('concat', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + + if input[0].desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + # NOTE(liym27): Don't remove this if branch! + # This feature is supported for Dynamic-to-Static, because after transformed, the type of inputs[0] + # is LOD_TENSOR_ARRAY in some scenarios. And this feature can be used in static mode. + + assert len(input) == 1, "If the elements of 'input' in concat are Variable(LoDTensorArray), " \ + "number of the elements must be 1, but received %s." % len(input) + out_index = helper.create_variable_for_type_inference(dtype="int32") + helper.append_op(type='tensor_array_to_tensor', + inputs={'X': input[0]}, + outputs={ + 'Out': [out], + 'OutIndex': [out_index] + }, + attrs={ + 'axis': axis, + 'use_stack': False + }) + else: + inputs = {'X': input} + attrs = {} + if isinstance(axis, Variable): + axis.stop_gradient = True + attrs['axis'] = axis + + helper.append_op(type='concat', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs) + return out + + +def tensor_array_to_tensor(input, axis=1, name=None, use_stack=False): + r""" + This function concatenates or stacks all tensors in the input LoDTensorArray + along the axis mentioned and returns that as the output. + + For Example: + + .. code-block:: text + + Case 1: + + Given: + + input.data = {[[0.6, 0.1, 0.3], + [0.5, 0.3, 0.2]], + [[1.3], + [1.8]], + [[2.3, 2.1], + [2.5, 2.4]]} + + axis = 1, use_stack = False + + Then: + + output.data = [[0.6, 0.1, 0.3, 1.3, 2.3, 2.1], + [0.5, 0.3, 0.2, 1.8, 2.5, 2.4]] + + output_index.data = [3, 1, 2] + + Case 2: + + Given: + + input.data = {[[0.6, 0.1], + [0.5, 0.3]], + [[0.3, 1.3], + [0.2, 1.8]], + [[2.3, 2.1], + [2.5, 2.4]]} + + axis = 1, use_stack = True + + Then: + + output.data = [[[0.6, 0.1] + [0.3, 1.3] + [2.3, 2.1], + [[0.5, 0.3] + [0.2, 1.8] + [2.5, 2.4]]] + + output_index.data = [2, 2, 2] + + Args: + input(Variable): A LodTensorArray variable. + axis(int): The axis along which the tensors in attr::`input` will be + concatenated or stacked. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + use_stack(bool): Act as concat_op or stack_op. For stack mode, all + tensors in the tensor array must have the same shape. + + Returns: + Variable: The concatenated or stacked tensor variable. + Variable: A 1-D tensor variable with int32 data type. The data in this \ + tensor contains all input including tensors' sizes along the axis. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + x0 = fluid.layers.assign(np.random.rand(2, 2).astype("float32")) + x1 = fluid.layers.assign(np.random.rand(2, 2).astype("float32")) + i = fluid.layers.fill_constant(shape=[1], dtype="int64", value=0) + array = fluid.layers.create_array(dtype='float32') + fluid.layers.array_write(x0, i, array) + fluid.layers.array_write(x1, i + 1, array) + output, output_index = fluid.layers.tensor_array_to_tensor(input=array) + """ + if _non_static_mode(): + assert isinstance( + input, list), "The 'input' in tensor_array_to_tensor must be list" + from .nn import stack, concat + from ..dygraph import to_variable + op = stack if use_stack else concat + res = op(input, axis=axis) + sizes = to_variable( + numpy.array(list(map(lambda x: int(x.shape[axis]), input)))) + return res, sizes + + check_type(input, 'input', (list, Variable), 'tensor_array_to_tensor') + if isinstance(input, list): + for i, input_x in enumerate(input): + check_type(input_x, 'input[' + str(i) + ']', Variable, + 'tensor_array_to_tensor') + helper = LayerHelper('tensor_array_to_tensor', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + out_index = helper.create_variable_for_type_inference(dtype="int32") + helper.append_op(type='tensor_array_to_tensor', + inputs={'X': input}, + outputs={ + 'Out': [out], + 'OutIndex': [out_index] + }, + attrs={ + 'axis': axis, + 'use_stack': use_stack + }) + return out, out_index + + +def sums(input, out=None): + r""" + This function computes the sum of multiple input Tensors elementwisely. + + - Case 1, sum of 3 Tensors + + .. code-block:: text + + # Input Tensors + x0.shape = [2, 3] + x0.data = [[1., 2., 3.], + [4., 5., 6.]] + x1.shape = [2, 3] + x1.data = [[10., 20., 30.], + [40., 50., 60.]] + x2.shape = [2, 3] + x2.data = [[100., 200., 300.], + [400., 500., 600.]] + + # Output Tensor + out.shape = [2, 3] + out.data = [[111., 222., 333.], + [444., 555., 666.]] + + Args: + input (list): A list of Variables which hold input Tensors with the same + data type and shape. Optional data types are: float32, float64, int32, int64. + out (Variable, optional): Output Tensor. It can be any existing Variable. + The default value is None, then a new Variable will be created and returned. + + Returns: + Variable: The sum of inputs. The shape and data type is the same with input. \ + If :code:`out` is not None, the returned value is :code:`out` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x0 = fluid.layers.fill_constant(shape=[16, 32], dtype='int64', value=1) + x1 = fluid.layers.fill_constant(shape=[16, 32], dtype='int64', value=2) + x2 = fluid.layers.fill_constant(shape=[16, 32], dtype='int64', value=3) + x3 = fluid.layers.fill_constant(shape=[16, 32], dtype='int64', value=0) + + # Sum of multiple Tensors, the result is stored to a new Variable sum0 (sum0=x0+x1+x2, the value is [[6, ..., 6], ..., [6, ..., 6]]) + sum0 = fluid.layers.sums(input=[x0, x1, x2]) + + # Sum of multiple Tensors, sum1 and x3 represents the same Variable (x3=x0+x1+x2, the value is [[6, ..., 6], ..., [6, ..., 6]]) + sum1 = fluid.layers.sums(input=[x0, x1, x2], out=x3) + """ + check_type(input, 'input', (Variable, tuple, list), 'sums') + if isinstance(input, list) or isinstance(input, tuple): + for input_section in input: + check_variable_and_dtype(input_section, "input", \ + ['float16', 'float32', 'float64', 'int32', 'int64'], 'sums') + else: + check_variable_and_dtype(input, "input", \ + ['float16', 'float32', 'float64', 'int32', 'int64'], 'sums') + + helper = LayerHelper('sum', **locals()) + if out is None: + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype()) + else: + check_variable_and_dtype(out, "out", + ['float32', 'float64', 'int32', 'int64'], + 'sums') + + helper.append_op(type='sum', + inputs={'X': input}, + outputs={'Out': out}, + attrs={'use_mkldnn': False}) + return out + + +def assign(input, output=None): + """ + + The OP copies the :attr:`input` to the :attr:`output`. + + Parameters: + input (Tensor|numpy.ndarray|list|tuple|scalar): A tensor, numpy ndarray, tuple/list of scalar, + or scalar. Its data type supports float16, float32, float64, int32, int64, and bool. + Note: the float64 data will be converted to float32 because of current platform protobuf + data limitation. + output (Tensor, optional): A tensor. If :attr:`output` is None, a new tensor will + be created as :attr:`output`. Default: None. + + Returns: + Tensor: A tensor with the same shape, data type and value as :attr:`input`. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + data = paddle.full(shape=[3, 2], fill_value=2.5, dtype='float64') # [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + array = np.array([[1, 1], + [3, 4], + [1, 3]]).astype(np.int64) + result1 = paddle.zeros(shape=[3, 3], dtype='float32') + paddle.assign(array, result1) # result1 = [[1, 1], [3 4], [1, 3]] + result2 = paddle.assign(data) # result2 = [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + result3 = paddle.assign(np.array([[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]], dtype='float32')) # result3 = [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + """ + helper = LayerHelper('assign', **locals()) + check_type(input, 'input', + (Variable, numpy.ndarray, list, tuple, float, int, bool), + 'assign') + is_inplace = True if output is not None else False + + if numpy.isscalar(input) and not isinstance(input, str): + input = numpy.array([input]) + elif isinstance(input, (list, tuple)): + input = numpy.array(input) + # NOTE(Aurelius84): Why we judge core.VarBase? + # In case of @to_static, a VarBase can be as input of `assign`, + # but _non_static_mode()==False under @to_static, which means + # isinstance(VarBase, Variable) == False. It will cause return None + # after this api. + if isinstance(input, (Variable, core.VarBase)): + if _non_static_mode(): + if in_dygraph_mode() and output is None: + output = _C_ops.assign(input) + elif in_dygraph_mode() and output is not None: + _C_ops.assign_out_(input, output) + else: + if output is None: + if _in_legacy_dygraph(): + output = core.VarBase() + else: + output = core.eager.Tensor() + _legacy_C_ops.assign(input, output) + else: + check_dtype(input.dtype, 'input', [ + 'float16', 'uint16', 'float32', 'float64', 'int32', 'int64', + 'uint8', 'bool' + ], 'assign', '(When the type of input in assign is Variable.)') + if output is None: + output = helper.create_variable_for_type_inference( + dtype=input.dtype) + helper.append_op(type='assign', + inputs={'X': [input]}, + outputs={'Out': [output]}) + elif isinstance(input, numpy.ndarray): + # Not support [var, var, ...] currently. + if len(input.shape) > 0 and any(isinstance(x, Variable) for x in input): + raise TypeError( + "Required type(input) numpy.ndarray, but found `list(Variable)` in input." + ) + dtype = convert_np_dtype_to_dtype_(input.dtype) + if dtype == VarDesc.VarType.FP64: + # Setting FP64 numpy data is not supported in Paddle, so we + # use FP32 here + warnings.warn( + "paddle.assign doesn't support float64 input now due " + "to current platform protobuf data limitation, we convert " + "it to float32") + dtype = VarDesc.VarType.FP32 + if dtype == VarDesc.VarType.BOOL: + value_name = "bool_values" + values = [int(v) for v in input.flat] + elif dtype == VarDesc.VarType.FP32: + value_name = "fp32_values" + values = [float(v) for v in input.flat] + elif dtype == VarDesc.VarType.INT32: + value_name = "int32_values" + values = [int(v) for v in input.flat] + elif dtype == VarDesc.VarType.INT64: + value_name = "int64_values" + values = [int(v) for v in input.flat] + else: + raise TypeError( + "When the type of 'input' in assign is numpy.ndarray, " + "the data type of 'input' must be bool, float32, int32 or int64, but " + "received %s." % convert_dtype(dtype)) + if input.size > 1024 * 1024: + raise ValueError("The size of input is too big. Please consider " + "saving it to file and 'load_op' to load it") + if in_dygraph_mode(): + if output is None: + output = zeros(list(input.shape), dtype) + _C_ops.assign_value_(output, list(input.shape), dtype, values, + _current_expected_place()) + elif _in_legacy_dygraph(): + if output is None: + output = core.VarBase() + _legacy_C_ops.assign_value(output, 'shape', list(input.shape), + 'dtype', dtype, value_name, values) + else: + if output is None: + output = helper.create_variable_for_type_inference( + dtype=input.dtype) + helper.append_op(type='assign_value', + outputs={'Out': [output]}, + attrs={ + 'dtype': dtype, + 'shape': list(input.shape), + value_name: values + }) + + if is_inplace and _non_static_mode(): + output._bump_inplace_version() + + return output + + +def fill_constant(shape, dtype, value, force_cpu=False, out=None, name=None): + """ + + This OP creates a Tensor with specified `shape` and `dtype`, and + initializes it with a constant specified by `value`. + + The attribute `stop_gradient` of the created Tensor is set to True. + + Args: + shape(list|tuple|Tensor): Shape of the output Tensor, the data type of ``shape`` is int32 or int64. + If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. + If ``shape`` is an Tensor, it should be an 1-D Tensor with date type int32 or int64. + dtype(np.dtype|str): Data type of the output Tensor which can + be float16, float32, float64, uint8, int16, int32, int64. + value(bool|float|int|Tensor): The constant value used to initialize + the Tensor to be created. If ``value`` is an Tensor, it should be an 1-D Tensor. + force_cpu(bool, optional): data should be on CPU if it's true, default value is False. + out(Tensor, optional): Optional output which can be any created + Tensor that meets the requirements to store the result of operation. + if ``out`` is None, a new Tensor will be create to store the result. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Tensor which is created according to shape and dtype. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + # attr shape is a list which doesn't contain Tensor. + data1 = fluid.layers.fill_constant(shape=[2,1], value=0, dtype='int64') # data1=[[0],[0]] + data2 = fluid.layers.fill_constant(shape=[2,1], value=5, dtype='int64', out=data1) + # data1=[[5], [5]] data2=[[5], [5]] + + # attr shape is a list which contains Tensor. + positive_2 = fluid.layers.fill_constant([1], "int32", 2) + data3 = fluid.layers.fill_constant(shape=[1, positive_2], dtype='float32', value=1.5) # data3=[[1.5, 1.5]] + + # attr shape is a Tensor. + shape = fluid.layers.fill_constant([2], "int32", 2) # shape=[2,2] + data4 = fluid.layers.fill_constant(shape=shape, dtype='bool', value=True) # data4=[[True,True],[True,True]] + + # attr value is a Tensor. + val = fluid.layers.fill_constant([1], "float32", 2.0) # val=[2.0] + data5 = fluid.layers.fill_constant(shape=[2,1], value=val, dtype='float32') #data5=[[2.0],[2.0]] + """ + + attrs = {'force_cpu': force_cpu} + dtype = convert_dtype(dtype) + if not isinstance(value, Variable): + if dtype in ['uint8', 'int16', 'int32', 'int64']: + attrs['str_value'] = str(int(value)) + attrs['value'] = int(value) + else: + attrs['str_value'] = str(float(value)) + attrs['value'] = float(value) + + if in_dygraph_mode(): + place = _current_expected_place() + if force_cpu: + place = core.CPUPlace() + if isinstance(shape, (list, tuple)): + for item in shape: + if not isinstance(item, Variable): + shape = list( + map( + lambda x: x.numpy().flat[0] + if isinstance(x, Variable) else x, shape)) + break + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if out is None: + out = _C_ops.full(shape, float(value), dtype, place) + out.stop_gradient = True + return out + + if out is not None: + # final state mode is support out is not None. + _C_ops.full_(out, shape, float(value), dtype, place) + out.stop_gradient = True + return out + + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + if out is None: + out = _varbase_creator(dtype=dtype) + + if isinstance(value, Variable): + if dtype in ['uint8', 'int16', 'int32', 'int64']: + attrs['str_value'] = str(int(value.numpy().item(0))) + else: + attrs['str_value'] = str(float(value.numpy().item(0))) + + _legacy_C_ops.fill_constant(out, 'value', float(value), 'force_cpu', + force_cpu, 'dtype', out.dtype, 'str_value', + attrs['str_value'], 'shape', shape) + out.stop_gradient = True + return out + + helper = LayerHelper("fill_constant", **locals()) + inputs = {} + if isinstance(value, Variable): + if convert_dtype(value.dtype) != dtype: + value = cast(value, dtype) + inputs['ValueTensor'] = value + + check_shape(shape) + check_dtype(dtype, 'dtype', [ + 'bool', 'float16', 'float32', 'float64', 'uint8', 'int16', 'int32', + 'int64', 'complex64', 'complex128' + ], 'fill_constant') + check_type(shape, 'shape', (Variable, list, tuple), 'fill_constant') + + if out is not None: + check_variable_and_dtype(out, 'out', [convert_dtype(dtype)], + 'fill_constant') + + helper = LayerHelper("fill_constant", **locals()) + utils.get_shape_tensor_inputs(inputs=inputs, + attrs=attrs, + shape=shape, + op_type='fill_constant') + + if out is None: + out = helper.create_variable_for_type_inference(dtype=dtype) + attrs['dtype'] = out.dtype + helper.append_op(type='fill_constant', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs, + stop_gradient=True) + out.stop_gradient = True + return out + + +@deprecated(since='1.8.0', update_to="paddle.fluid.layers.fill_constant") +@templatedoc() +def fill_constant_batch_size_like(input, + shape, + dtype, + value, + input_dim_idx=0, + output_dim_idx=0, + force_cpu=False): + """ + This OP creates a Tesnor according the shape and dtype, and initializes the + Tensor with the constants provided in ``value``. When the input is LoDTensor + and the input_dim_idx is 0, the output_dim_idx dimension is set to the value + of the batch_size input by the input, the Stop_gradient attribute of the created + Tensor is False by default. + + Args: + input(Variable): Tensor which data type is float32, float64, int32 and int64. + shape(list): The shape of Tensor to be created, Tensor's shape may be changed + according the input. + dtype(np.dtype|core.VarDesc.VarType|str): The data type of created Tensor which + can be float32, float64, int32, int64. + value(float|int): The constant value used to initialize the Tensor to be created. + input_dim_idx(int): When the value is 0 and the input is LoDTensor, the output_dim_idx + dimension of the created Tensor is set to the batch_size value of input. + The default value is 0. + output_dim_idx(int): Used to specify which dimension of Tensor is created to be set + the value of batch_size of input Tensor. The default value is 0. + force_cpu(bool): data should be on CPU if it's true, default value is False. + + Returns: + Variable: Tensor which will be created according to dtype. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + like = fluid.layers.fill_constant(shape=[1,2], value=10, dtype='int64') #like=[[10, 10]] + data = fluid.layers.fill_constant_batch_size_like( + input=like, shape=[1], value=0, dtype='int64') #like=[[10, 10]] data=[0] + + """ + if in_dygraph_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + place = _current_expected_place() + if force_cpu: + place = core.CPUPlace() + out = _C_ops.full_batch_size_like(input, shape, dtype, value, + input_dim_idx, output_dim_idx, place) + out.stop_gradient = True + return out + + helper = LayerHelper("fill_constant_batch_size_like", **locals()) + out = helper.create_variable_for_type_inference(dtype=dtype) + attrs = { + 'shape': shape, + 'dtype': out.dtype, + 'value': float(value), + 'input_dim_idx': input_dim_idx, + 'output_dim_idx': output_dim_idx, + 'force_cpu': force_cpu + } + if convert_dtype(dtype) in ['int64', 'int32']: + attrs['str_value'] = str(int(value)) + else: + attrs['str_value'] = str(float(value)) + helper.append_op(type='fill_constant_batch_size_like', + inputs={'Input': input}, + outputs={'Out': [out]}, + attrs=attrs) + out.stop_gradient = True + return out + + +def argmin(x, axis=0): + """ + :alias_main: paddle.argmin + :alias: paddle.argmin,paddle.tensor.argmin,paddle.tensor.search.argmin + :old_api: paddle.fluid.layers.argmin + + **argmin** + + This OP computes the indices of the min elements of the input tensor's + element along the provided axis. + + Args: + x(Variable): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is Rank(x). when axis<0, it works the same way + as axis+R. Default is 0. + + Returns: + Variable: A Tensor with data type int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + in1 = np.array([[[5,8,9,5], + [0,0,1,7], + [6,9,2,4]], + [[5,2,4,2], + [4,7,7,9], + [1,7,0,6]]]) + with fluid.dygraph.guard(): + x = fluid.dygraph.to_variable(in1) + out1 = fluid.layers.argmin(x=x, axis=-1) + out2 = fluid.layers.argmin(x=x, axis=0) + out3 = fluid.layers.argmin(x=x, axis=1) + out4 = fluid.layers.argmin(x=x, axis=2) + print(out1.numpy()) + # [[0 0 2] + # [1 0 2]] + print(out2.numpy()) + # [[0 1 1 1] + # [0 0 0 0] + # [1 1 1 0]] + print(out3.numpy()) + # [[1 1 1 2] + # [2 0 2 0]] + print(out4.numpy()) + # [[0 0 2] + # [1 0 2]] + """ + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'uint8', 'int16', 'int32', 'int64'], + 'argmin') + helper = LayerHelper("arg_min", **locals()) + out = helper.create_variable_for_type_inference(VarDesc.VarType.INT64) + helper.append_op(type='arg_min', + inputs={'X': x}, + outputs={'Out': [out]}, + attrs={'axis': axis}) + out.stop_gradient = True + return out + + +def argmax(x, axis=0): + """ + **argmax** + + This OP computes the indices of the max elements of the input tensor's + element along the provided axis. + + Args: + x(Variable): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is Rank(x). when axis<0, it works the same way + as axis+R. Default is 0. + + Returns: + Variable: A Tensor with data type int64. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + in1 = np.array([[[5,8,9,5], + [0,0,1,7], + [6,9,2,4]], + [[5,2,4,2], + [4,7,7,9], + [1,7,0,6]]]) + with fluid.dygraph.guard(): + x = fluid.dygraph.to_variable(in1) + out1 = fluid.layers.argmax(x=x, axis=-1) + out2 = fluid.layers.argmax(x=x, axis=0) + out3 = fluid.layers.argmax(x=x, axis=1) + out4 = fluid.layers.argmax(x=x, axis=2) + print(out1.numpy()) + # [[2 3 1] + # [0 3 1]] + print(out2.numpy()) + # [[0 0 0 0] + # [1 1 1 1] + # [0 0 0 1]] + print(out3.numpy()) + # [[2 2 0 1] + # [0 1 1 1]] + print(out4.numpy()) + # [[2 3 1] + # [0 3 1]] + """ + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'uint8', 'int16', 'int32', 'int64'], + 'argmax') + helper = LayerHelper("arg_max", **locals()) + out = helper.create_variable_for_type_inference(VarDesc.VarType.INT64) + helper.append_op(type='arg_max', + inputs={'X': x}, + outputs={'Out': [out]}, + attrs={'axis': axis}) + out.stop_gradient = True + return out + + +def argsort(input, axis=-1, descending=False, name=None): + """ + :alias_main: paddle.argsort + :alias: paddle.argsort,paddle.tensor.argsort,paddle.tensor.search.argsort + :old_api: paddle.fluid.layers.argsort + + This OP sorts the input along the given axis, and returns sorted output + data Varibale and its corresponding index Variable with the same shape as + :attr:`input`. + + Args: + input(Variable): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is Rank(x). when axis<0, it works the same way + as axis+R. Default is 0. + descending(bool, optional) : Descending is a flag, if set to true, + algorithm will sort by descending order, else sort by + ascending order. Default is false. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + tuple: A tuple of sorted data Variable(with the same shape and data + type as input) and the sorted indices(with the same shape as input's + and with data type int64). + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + in1 = np.array([[[5,8,9,5], + [0,0,1,7], + [6,9,2,4]], + [[5,2,4,2], + [4,7,7,9], + [1,7,0,6]]]).astype(np.float32) + with fluid.dygraph.guard(): + x = fluid.dygraph.to_variable(in1) + out1 = fluid.layers.argsort(input=x, axis=-1) + out2 = fluid.layers.argsort(input=x, axis=0) + out3 = fluid.layers.argsort(input=x, axis=1) + print(out1[0].numpy()) + # [[[5. 5. 8. 9.] + # [0. 0. 1. 7.] + # [2. 4. 6. 9.]] + # [[2. 2. 4. 5.] + # [4. 7. 7. 9.] + # [0. 1. 6. 7.]]] + print(out1[1].numpy()) + # [[[0 3 1 2] + # [0 1 2 3] + # [2 3 0 1]] + # [[1 3 2 0] + # [0 1 2 3] + # [2 0 3 1]]] + print(out2[0].numpy()) + # [[[5. 2. 4. 2.] + # [0. 0. 1. 7.] + # [1. 7. 0. 4.]] + # [[5. 8. 9. 5.] + # [4. 7. 7. 9.] + # [6. 9. 2. 6.]]] + print(out3[0].numpy()) + # [[[0. 0. 1. 4.] + # [5. 8. 2. 5.] + # [6. 9. 9. 7.]] + # [[1. 2. 0. 2.] + # [4. 7. 4. 6.] + # [5. 7. 7. 9.]]] + """ + check_variable_and_dtype( + input, 'input', + ['float32', 'float64', 'int16', 'int32', 'int64', 'uint8'], 'argsort') + helper = LayerHelper("argsort", **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype, + stop_gradient=True) + ids = helper.create_variable_for_type_inference(VarDesc.VarType.INT64, + stop_gradient=True) + helper.append_op(type='argsort', + inputs={'X': input}, + outputs={ + 'Out': out, + 'Indices': ids + }, + attrs={ + 'axis': axis, + 'descending': descending + }) + return out, ids + + +def ones(shape, dtype, force_cpu=False): + """ + The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 1. + Its :attr:`stop_gradient` will be set to True to stop gradient computation. + + Parameters: + shape(tuple|list|Tensor): Shape of output Tensor, the data type of shape is int32 or int64. + dtype (np.dtype|str): Data type of output Tensor, it supports + bool, float16, float32, float64, int32 and int64. + force_cpu (bool, optional): Whether force to store the output Tensor in CPU memory. + If :attr:`force_cpu` is False, the output Tensor will be stored in running device memory. + Default: False. + + Returns: + Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 1. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data0 = fluid.layers.ones(shape=[2, 4], dtype='float32') # [[1., 1., 1., 1.], [1., 1., 1., 1.]] + + # shape is a Tensor + shape = fluid.layers.fill_constant(shape=[2], dtype='int32', value=2) + data1 = fluid.layers.ones(shape=shape, dtype='int32') #[[1, 1], [1, 1]] + """ + return fill_constant(value=1.0, **locals()) + + +def zeros(shape, dtype, force_cpu=False, name=None): + """ + The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. + Its :attr:`stop_gradient` will be set to True to stop gradient computation. + + Parameters: + shape(tuple|list|Tensor): Shape of output Tensor, the data type of ``shape`` is int32 or int64. + dtype (np.dtype|str): Data type of output Tensor, it supports + bool, float16, float32, float64, int32 and int64. + force_cpu (bool, optional): Whether force to store the output Tensor in CPU memory. + If :attr:`force_cpu` is False, the output Tensor will be stored in running device memory. + Default: False. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.zeros(shape=[3, 2], dtype='float32') # [[0., 0.], [0., 0.], [0., 0.]] + + # shape is a Tensor + shape = fluid.layers.fill_constant(shape=[2], dtype='int32', value=2) + data1 = fluid.layers.zeros(shape=shape, dtype='int32') #[[0, 0], [0, 0]] + """ + return fill_constant(value=0.0, **locals()) + + +def reverse(x, axis): + """ + :alias_main: paddle.reverse + :alias: paddle.reverse,paddle.tensor.reverse,paddle.tensor.manipulation.reverse + :old_api: paddle.fluid.layers.reverse + + The OP reverses the tensor :attr:`x` along the given :attr:`axis`. + + .. code-block:: text + + Case 1: + + Given a LoDTensor: + x = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + axis = [0, 1] + + Then: + output = [[8, 7, 6], [5, 4, 3], [2, 1, 0]] + + Case 2: + + Given a LoDTensorArray: + x = {[[0, 1], [2, 3]], + [[4, 5, 6]], + [[7],[8], [9]]} + axis = 0 + + Then: + output = {[[7],[8], [9]], + [[4, 5, 6]], + [[0, 1], [2, 3]]} + + Parameters: + x (Variable): A tensor or LoDTensorArray to be reversed, its data type supports bool, float32, float64, int32, int64 and uint8. + If input is a LoDTensorArray, returns a new reversed LoDTensorArray without changing the internal order of each inner tensor. + axis (int|tuple|list): A dimension or a set of dimensions of :attr:`x` to reverse. Must be + in the range [-rank( :attr:`x` ), rank( :attr:`x` )). If it is a tuple or a list, reversing + will be apply on each axis in the tuple or list. If input is a LoDTensorArray, the value of axis shall be 0, or a + list [0] or tuple (0, ) with shape [1]. + + Returns: + Variable: The reversed tensor with the same shape and data type as :attr:`x`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + data = fluid.layers.assign(np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]], dtype='float32')) # [[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]] + result1 = fluid.layers.reverse(data, 0) # [[6., 7., 8.], [3., 4., 5.], [0., 1., 2.]] + result2 = fluid.layers.reverse(data, [0, 1]) # [[8., 7., 6.], [5., 4., 3.], [2., 1., 0.]] + + # example of LoDTensorArray + data1 = fluid.layers.assign(np.array([[0, 1, 2]], dtype='float32')) + data2 = fluid.layers.assign(np.array([[3, 4, 5]], dtype='float32')) + tensor_array = fluid.layers.create_array(dtype='float32') + i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0) + fluid.layers.array_write(data1, i, tensor_array) + fluid.layers.array_write(data2, i+1, tensor_array) + + reversed_tensor_array = fluid.layers.reverse(tensor_array, 0) # {[[3, 4, 5]], [[0, 1, 2]]} + """ + check_variable_and_dtype(x, 'x', + ('float32', 'float64', 'int32', 'int64', 'uint8'), + 'reverse') + check_type(axis, 'axis', (int, tuple, list, Variable), 'reverse') + if isinstance(axis, int): + axis = [axis] + if in_dygraph_mode(): + return _C_ops.reverse(x, axis) + helper = LayerHelper("reverse", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='reverse', + inputs={'X': x}, + outputs={'Out': [out]}, + attrs={'axis': axis}) + return out + + +def save(x, file_path, overwrite=True): + """ + Saves a variable as a file. + + Args: + x(variable): The Tensor/LoDTensor to be saved. + file_path(str): The file path where the variable will be saved. + overwrite(bool): Whether or not cover the given file when it has already + existed. If it's set 'False' and the file is existed, a runtime + error will be thrown. + """ + helper = LayerHelper("save", **locals()) + helper.append_op(type="save", + inputs={"input": x}, + outputs={}, + args={ + "file_path": file_path, + "overwrite": overwrite + }) + + +def save_combine(x, file_path, overwrite=True): + """ + Saves a list of variables into a single file. + + Args: + x(list): A list of Tensor/LoDTensor variables to be saved together in + a single file. + file_path(str): The file path where variables will be saved. + overwrite(bool): Whether or not cover the given file when it has already + existed. If it's set 'False' and the file is existed, a runtime + error will be thrown. + + Returns: + There is no return value. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + v1 = fluid.layers.data(name="data", + shape=(4, 6), + dtype="float32") + v2 = fluid.layers.data(name="data", + shape=(6, 8, 4), + dtype="float32") + normed = fluid.layers.save_combine([v1, v2], file_path="output") + """ + helper = LayerHelper("save_combine", **locals()) + helper.append_op(type="save_combine", + inputs={"input": x}, + outputs={}, + args={ + "file_path": file_path, + "overwrite": overwrite + }) + + +def load_combine(out, file_path): + """ + Loads a list of variable from a single file. + + Args: + out(list): The list of variables to be read from the disk file. + file_path(str): The path of the disk file. + """ + helper = LayerHelper("load_combine", **locals()) + helper.append_op(type="load_combine", + inputs={}, + output={"Out": out}, + args={"file_path": file_path}) + + +def has_inf(x): + """ + Test if any of x contains an infinity number + + Args: + x (Tensor): The Tensor to be checked. + + Returns: + Tensor: The tensor storing the output, only a bool value, indicating that whether there is infinity number in x or not. + + Examples: + .. code-block:: python + + import paddle + data = paddle.randn(shape=[4, 32, 32], dtype="float32") + res = paddle.fluid.layers.has_inf(data) + # [False] + + """ + if _non_static_mode(): + return _legacy_C_ops.isinf(x) + + check_type(x, 'x', (Variable), 'has_inf') + helper = LayerHelper("isinf", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type="isinf", inputs={"X": x}, outputs={"Out": out}) + return out + + +def has_nan(x): + """ + Test if any of x contains a NAN + + Args: + x (Tensor): The Tensor to be checked. + + Returns: + Tensor: The tensor variable storing the output, only a bool value, indicating that whether there is NAN in x or not. + + Examples: + .. code-block:: python + + import paddle + data = paddle.randn(shape=[2,3], dtype="float32") + res = paddle.fluid.layers.has_nan(data) + # [False] + + """ + if _non_static_mode(): + return _legacy_C_ops.isnan(x) + + check_type(x, 'x', (Variable), 'has_nan') + helper = LayerHelper("isnan", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type="isnan", inputs={"X": x}, outputs={"Out": out}) + return out + + +def isfinite(x): + """ + + Test if any of x contains an infinity/NAN number. If all the elements are finite, + returns true, else false. + + Args: + x(Tensor): The Tensor to be checked. + + Returns: + Tensor: The tensor storing the output, contains a bool value. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand(shape=[4, 6], dtype='float32') + y = paddle.fluid.layers.isfinite(x) + print(y) + + """ + check_variable_and_dtype(x, "x", ["float32", "float64", "int32", "int64"], + "isfinite") + helper = LayerHelper("isfinite", **locals()) + + out = helper.create_variable_for_type_inference(dtype='bool') + helper.append_op(type="isfinite", inputs={"X": x}, outputs={"Out": out}) + return out + + +def range(start, end, step, dtype, name=None): + """ + This OP returns a 1-D Tensor with spaced values within a given interval. + + Values are generated into the half-open interval [``start``, ``end``) with + the ``step``. (the interval including ``start`` but excluding ``end``). + + If ``dtype`` is float32 or float64, we advise adding a small epsilon to + ``end`` to avoid floating point rounding errors when comparing against ``end``. + + Parameters: + start(float|int|Tensor): Start of interval. The interval includes this + value. If ``start`` is a Tensor, it is a 1-D Tensor with shape [1], + with data type int32, int64, float32, float64. + end(float|int|Tensor): End of interval. The interval does not include + this value. If ``end`` is a Tensor, it is a 1-D Tensor with shape + [1], with data type int32, int64, float32, float64. + step(float|int|Tensor): Spacing between values. For any out, it is + the istance between two adjacent values, out[i+1] - out[i]. If + ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with data + type int32, int64, float32, float64. + dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the + output tensor. Supported data types: int32, int64, float32, float64. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A 1-D Tensor with values from the interval [``start``, ``end``) + taken with common difference ``step`` beginning from ``start``. Its + data type is set by ``dtype``. + + Raises: + TypeError: If ``dtype`` is not int32, int64, float32, float64. + + examples: + + .. code-block:: python + + import paddle.fluid as fluid + + out1 = fluid.layers.range(0, 10, 2, 'int32') + # [0, 2, 4, 6, 8] + + start_var = fluid.layers.fill_constant([1], 'int64', 3) + out2 = fluid.layers.range(start_var, 7, 1, 'int64') + # [3, 4, 5, 6] + + """ + out_shape = None + if not isinstance(start, Variable) and not isinstance( + end, Variable) and not isinstance(step, Variable): + out_shape = [int(math.ceil((end - start) / step))] + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if not isinstance(start, Variable): + with device_guard("cpu"): + start = fill_constant([1], dtype, start, force_cpu=True) + elif start.dtype != dtype: + start = cast(start, dtype) + + if not isinstance(end, Variable): + with device_guard("cpu"): + end = fill_constant([1], dtype, end, force_cpu=True) + elif end.dtype != dtype: + end = cast(end, dtype) + + if not isinstance(step, Variable): + with device_guard("cpu"): + step = fill_constant([1], dtype, step, force_cpu=True) + elif step.dtype != dtype: + step = cast(step, dtype) + + if in_dygraph_mode(): + return _C_ops.arange(start, end, step, dtype, _current_expected_place()) + + if _in_legacy_dygraph(): + out = _legacy_C_ops.range(start, end, step) + out.stop_gradient = True + return out + + check_dtype(dtype, 'dtype', ['float32', 'float64', 'int32', 'int64'], + 'range/arange') + helper = LayerHelper('range', **locals()) + out = helper.create_variable_for_type_inference(dtype, shape=out_shape) + helper.append_op(type='range', + inputs={ + 'Start': start, + 'End': end, + 'Step': step + }, + outputs={'Out': out}) + out.stop_gradient = True + if out_shape is not None: + out.desc.set_shape(out_shape) + return out + + +def linspace(start, stop, num, dtype=None, name=None): + r""" + This OP return fixed number of evenly spaced values within a given interval. + + Args: + start(int|float|Tensor): The input :attr:`start` is start variable of range. It is a scalar, \ + or a Tensor of shape [1] with input data type int32, int64, float32 or float64. + stop(int|float|Tensor): The input :attr:`stop` is start variable of range. It is a scalar, \ + or a Tensor of shape [1] with input data type int32, int64, float32 or float64. + num(int|Tensor): The input :attr:`num` is given num of the sequence. It is an int scalar, \ + or a Tensor of shape [1] with data type int32. + dtype(np.dtype|str, optional): The data type of output tensor, it could be + int32, int64, float32 and float64. Default: if None, the data type is float32. + name(str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`.Default: None. + + Returns: + Tensor: the output data type will be float32, float64. The 1-D tensor with fixed number of evenly spaced values, \ + the data shape of this tensor is :math:`[num]` . If the :attr:`num` is set 1, the output tensor just has \ + the value with input :attr:`start`. + + Examples: + .. code-block:: python + + import paddle + data = paddle.linspace(0, 10, 5, 'float32') # [0.0, 2.5, 5.0, 7.5, 10.0] + data = paddle.linspace(0, 10, 1, 'float32') # [0.0] + + """ + if dtype is None: + dtype = 'float32' + tensor_num = num + tensor_start = start + tensor_stop = stop + if not isinstance(num, Variable): + check_type(num, 'num', (int), 'linspace') + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if not isinstance(start, Variable): + with device_guard("cpu"): + tensor_start = fill_constant([1], dtype, start) + if not isinstance(stop, Variable): + with device_guard("cpu"): + tensor_stop = fill_constant([1], dtype, stop) + if not isinstance(num, Variable): + with device_guard("cpu"): + tensor_num = fill_constant([1], 'int32', num) + if in_dygraph_mode(): + return _C_ops.linspace(tensor_start, tensor_stop, tensor_num, dtype, + _current_expected_place()) + if _in_legacy_dygraph(): + return _legacy_C_ops.linspace(tensor_start, tensor_stop, tensor_num, + 'dtype', dtype) + helper = LayerHelper("linspace", **locals()) + + start_dtype = convert_dtype(tensor_start.dtype) + stop_dtype = convert_dtype(tensor_stop.dtype) + out_dtype = convert_dtype(dtype) + if isinstance(start, Variable): + check_dtype(start.dtype, 'start', + ['float32', 'float64', 'int32', 'int64'], 'linspace') + else: + check_type(start, 'start', (int, float), 'linspace') + + if isinstance(stop, Variable): + check_dtype(stop.dtype, 'stop', + ['float32', 'float64', 'int32', 'int64'], 'linspace') + else: + check_type(stop, 'stop', (int, float), 'linspace') + if isinstance(num, Variable): + check_dtype(num.dtype, 'num', ['int32'], 'linspace') + check_dtype(dtype, 'dtype', ['int32', 'int64', 'float32', 'float64'], + 'linspace') + if ((stop_dtype == "float64" or start_dtype == "float64") + and out_dtype in ["float32", "int32"]) or ( + (stop_dtype == "int64" or start_dtype == "int64") + and out_dtype == "int32"): + raise ValueError( + "The dtype of start/stop is {}/{} but the attr(dtype) of linspace is {}, " + "which may cause data type overflows. Please reset attr(dtype) of linspace." + .format(start_dtype, stop_dtype, dtype)) + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op(type='linspace', + inputs={ + 'Start': tensor_start, + 'Stop': tensor_stop, + 'Num': tensor_num + }, + attrs={'dtype': dtype}, + outputs={'Out': [out]}) + if isinstance(num, int): + out.desc.set_shape((num, )) + return out + + +def zeros_like(x, out=None): + """ + This OP creates a zeros tensor which has identical shape and dtype + with `x`. + + Args: + x(Variable): The input tensor which specifies shape and dtype, the + input data dtype could be bool, float32, float64, int32, int64. + out(Variable, optional): If is :attr:`None` , the op will create the + variable as output, the data type and shape of this variable will + be same as input :attr:`x`. If is a tensor, the data type and shape + need to be same as input :attr:`x`. The default value is :attr:`None` . + + Returns: + Variable: The N-D tensor, the element in tensor is related to input + data type, if the input data type is bool, the output value is + False, otherwise is zero. The output shape is the same as the input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + x = fluid.data(name='x', dtype='float32', shape=[3]) + data = fluid.layers.zeros_like(x) # [0.0, 0.0, 0.0] + + """ + check_variable_and_dtype(x, "x", + ['bool', 'float32', 'float64', 'int32', 'int64'], + 'zeros_like') + helper = LayerHelper("zeros_like", **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + check_variable_and_dtype( + out, "out", ['bool', 'float32', 'float64', 'int32', 'int64'], + 'zeros_like') + helper.append_op(type='fill_any_like', + inputs={'X': [x]}, + attrs={ + 'value': 0, + "dtype": x.dtype + }, + outputs={'Out': [out]}) + out.stop_gradient = True + return out + + +@deprecated(since="2.0.0", update_to="paddle.diag") +def diag(diagonal): + r""" + :alias_main: paddle.diag + :alias: paddle.diag,paddle.tensor.diag,paddle.tensor.creation.diag + :old_api: paddle.fluid.layers.diag + + This OP creates a square matrix which has diagonal values specified by input :attr:`diagonal`. + + Args: + diagonal(Variable|numpy.ndarray): The input tensor should be 1D tensor, the input shape is :math:`[ N]` , \ + specifying diagonal values by this input tensor. The input data type should be float32, float64, int32, int64. + + Returns: + Variable, the output data type is the same as input data type.: The tensor variable storing the square matrix, \ + the diagonal values specified by input :attr:`diagonal`. the output shape is :math:`[N, N]` with two dims. + + Examples: + .. code-block:: python + + # [[3, 0, 0] + # [0, 4, 0] + # [0, 0, 5] + + import paddle.fluid as fluid + import numpy as np + diagonal = np.arange(3, 6, dtype='int32') + data = fluid.layers.diag(diagonal) + # diagonal.shape=(3,) data.shape=(3, 3) + + """ + check_type(diagonal, 'diagonal', (Variable, numpy.ndarray), 'diag') + check_dtype(diagonal.dtype, 'diagonal', + ['float32', 'float64', 'int32', 'int64'], 'diag') + helper = LayerHelper("diag", **locals()) + + if not isinstance(diagonal, Variable): + diagonal = assign(diagonal) + + out = helper.create_variable_for_type_inference(dtype=diagonal.dtype) + + helper.append_op(type='diag', + inputs={'Diagonal': [diagonal]}, + outputs={'Out': [out]}) + + out.stop_gradient = True + return out + + +def eye(num_rows, + num_columns=None, + batch_shape=None, + dtype='float32', + name=None): + """ + This function constructs a or a batch of 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + num_rows(int): the number of rows in each batch tensor. + num_columns(int, optional): the number of columns in each batch tensor. + If None, default: num_rows. + batch_shape(list, optional): If provided, the returned tensor will have a leading + batch size of this shape, the data type of ``batch_shape`` is int. Default is None. + dtype(np.dtype|str, optional): The data type of the returned tensor. + It should be int32, int64, float16, float32, float64, default is 'float32'. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: An identity Tensor or LoDTensor of shape batch_shape + [num_rows, num_columns]. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + data = fluid.layers.eye(3, dtype='int32') + # [[1, 0, 0] + # [0, 1, 0] + # [0, 0, 1]] + + data = fluid.layers.eye(2, 3, dtype='int32') + # [[1, 0, 0] + # [0, 1, 0]] + + data = fluid.layers.eye(2, batch_shape=[3]) + # Construct a batch of 3 identity tensors, each 2 x 2. + # data[i, :, :] is a 2 x 2 identity tensor, i = 0, 1, 2. + + """ + + def _check_attr(attr, message): + if isinstance(attr, ((Variable, core.VarBase, core.eager.Tensor))): + assert len(attr.shape) == 1 and attr.shape[0] in [1, -1] + elif not isinstance(attr, int) or attr < 0: + raise TypeError("{} should be a non-negative int.".format(message)) + + _check_attr(num_rows, "num_rows") + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if num_columns is not None: + _check_attr(num_columns, "num_columns") + else: + num_columns = num_rows + + if in_dygraph_mode(): + out = _C_ops.eye(num_rows, num_columns, dtype, + _current_expected_place()) + elif _in_legacy_dygraph(): + out = _legacy_C_ops.eye('dtype', dtype, 'num_rows', num_rows, + 'num_columns', num_columns) + else: + helper = LayerHelper("eye", **locals()) + check_dtype(dtype, 'dtype', + ['float16', 'float32', 'float64', 'int32', 'int64'], 'eye') + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op(type='eye', + inputs={}, + outputs={'Out': [out]}, + attrs={ + 'num_rows': num_rows, + 'num_columns': num_columns, + 'dtype': dtype + }, + stop_gradient=True) + + if batch_shape is not None: + re_shape = [1] * len(batch_shape) + re_shape = re_shape + [num_rows, num_columns] + expand_times = batch_shape + [1, 1] + if _non_static_mode(): + out, _ = _legacy_C_ops.reshape2(out, None, 'shape', re_shape) + return _legacy_C_ops.expand(out, None, 'expand_times', expand_times) + + if not isinstance(batch_shape, list): + raise TypeError("batch_shape should be a list") + for batch_val in (batch_shape): + if batch_val <= 0: + raise TypeError("batch_shape should be a positive int list") + + from .nn import reshape, expand + out = reshape(x=out, shape=re_shape) + out = expand(x=out, expand_times=expand_times) + + out.stop_gradient = True + return out + + +def ones_like(x, out=None): + """ + **ones_like** + + This function creates a ones tensor which has identical shape and dtype + with `x`. + + Args: + x(Variable): The input tensor which specifies shape and dtype. + out(Variable): The output tensor. + + Returns: + out(Variable): The tensor variable storing the output. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.layers.data(name='x', dtype='float32', shape=[3], append_batch_size=False) + data = fluid.layers.ones_like(x) # [1.0, 1.0, 1.0] + + """ + check_variable_and_dtype(x, "x", + ['bool', 'float32', 'float64', 'int32', 'int64'], + 'ones_like') + + helper = LayerHelper("ones_like", **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + check_variable_and_dtype( + out, "out", ['bool', 'float32', 'float64', 'int32', 'int64'], + 'ones_like') + helper.append_op(type='fill_any_like', + inputs={'X': [x]}, + attrs={'value': 1.0}, + outputs={'Out': [out]}) + return out + + +@deprecated(since="2.0.0", update_to="paddle.triu") +def triu(input, diagonal=0, name=None): + import paddle + return paddle.tensor.triu(x=input, diagonal=diagonal, name=name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ad68366e1ed2061b9a408a5cef141b383916ef63 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/layers/utils.py @@ -0,0 +1,503 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import collections +import copy +import six +import numpy as np +from ..framework import Block, Variable, _non_static_mode +from ..data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype +from ..layer_helper import LayerHelper +from sys import version_info +try: + from collections.abc import Sequence +except: + from collections import Sequence + + +def convert_to_list(value, n, name, dtype=int): + """ + Converts a single numerical type or iterable of numerical + types into an numerical type list. + + Arguments: + value: The value to validate and convert. Could an int, or any iterable + of ints. + n: The size of the list to be returned. + name: The name of the argument being validated, e.g. "stride" or + "filter_size". This is only used to format error messages. + dtype: the numerical type of the element of the list to be returned. + + Returns: + A list of n dtypes. + + Raises: + ValueError: If something else than an int/long or iterable thereof was + passed. + """ + if isinstance(value, dtype): + return [ + value, + ] * n + else: + try: + value_list = list(value) + except TypeError: + raise ValueError("The " + name + + "'s type must be list or tuple. Received: " + + str(value)) + if len(value_list) != n: + raise ValueError("The " + name + "'s length must be " + str(n) + + ". Received: " + str(value)) + for single_value in value_list: + assert not isinstance( + single_value, Variable + ), "Required numerical type with '%s', but received Tensor." % dtype + try: + dtype(single_value) + except (ValueError, TypeError): + raise ValueError("The " + name + + "'s type must be a list or tuple of " + + str(n) + " " + str(dtype) + " . Received: " + + str(value) + " " + "including element " + str(single_value) + + " of type" + " " + str(type(single_value))) + return value_list + + +def is_sequence(seq): + """ + Whether `seq` is an entry or nested structure + """ + if isinstance(seq, dict): + return True + return (isinstance(seq, Sequence) and not isinstance(seq, six.string_types)) + + +def _hash_with_id(*args): + """ + Return int hash value calculated by id(arg) or tuple(id1,id2, ...). + """ + assert len(args) > 0 + info = tuple([id(v) for v in args]) + return hash(info) & 0xfffffff + + +def _sorted(dict_): + """ + Returns a sorted list of the dict keys, with error if keys not sortable. + """ + try: + return sorted(six.iterkeys(dict_)) + except TypeError: + raise TypeError("nest only supports dicts with sortable keys.") + + +def _yield_value(iterable): + if isinstance(iterable, dict): + # Iterate through dictionaries in a deterministic order by sorting the + # keys. Notice this means that we ignore the original order of `OrderedDict` + # instances. This is intentional, to avoid potential bugs caused by mixing + # ordered and plain dicts (e.g., flattening a dict but using a + # corresponding `OrderedDict` to pack it back). + for key in _sorted(iterable): + yield iterable[key] + else: + for value in iterable: + yield value + + +def _yield_flat_nest(nest): + for n in _yield_value(nest): + if is_sequence(n): + for ni in _yield_flat_nest(n): + yield ni + else: + yield n + + +def to_sequence(nest): + if is_sequence(nest): + return nest + else: + return [nest] + + +def flatten(nest): + """ + :alias_main: paddle.flatten + :alias: paddle.flatten,paddle.tensor.flatten,paddle.tensor.manipulation.flatten + :old_api: paddle.fluid.layers.flatten + + Traverse all entries in the nested structure and put them into an list. + """ + if is_sequence(nest): + return list(_yield_flat_nest(nest)) + else: + return [nest] + + +def _sequence_like(instance, args): + """ + Convert the sequence `args` to the same type as `instance`. + """ + if isinstance(instance, dict): + # Pack dictionaries in a deterministic order by sorting the keys. + # Notice this means that we ignore the original order of `OrderedDict` + # instances. This is intentional, to avoid potential bugs caused by mixing + # ordered and plain dicts (e.g., flattening a dict but using a + # corresponding `OrderedDict` to pack it back). + result = dict(zip(_sorted(instance), args)) + return type(instance)( + (key, result[key]) for key in six.iterkeys(instance)) + elif (isinstance(instance, tuple) and hasattr(instance, "_fields") + and isinstance(instance._fields, Sequence) + and all(isinstance(f, six.string_types) for f in instance._fields)): + # This is a namedtuple + return type(instance)(*args) + else: + # Not a namedtuple + return type(instance)(args) + + +def _packed_nest_with_indices(structure, flat, index): + """ + Helper function for pack_sequence_as. + """ + packed = [] + for s in _yield_value(structure): + if is_sequence(s): + new_index, child = _packed_nest_with_indices(s, flat, index) + packed.append(_sequence_like(s, child)) + index = new_index + else: + packed.append(flat[index]) + index += 1 + return index, packed + + +def pack_sequence_as(structure, flat_sequence): + """ + Pack a given flattened sequence into a given structure. + """ + if not is_sequence(flat_sequence): + raise TypeError("flat_sequence must be a sequence") + if not is_sequence(structure): + if len(flat_sequence) != 1: + raise ValueError( + "Structure is a scalar but len(flat_sequence) == %d > 1" % + len(flat_sequence)) + return flat_sequence[0] + flat_structure = flatten(structure) + if len(flat_structure) != len(flat_sequence): + raise ValueError( + "Could not pack sequence. Structure had %d elements, but flat_sequence " + "had %d elements. Structure: %s, flat_sequence: %s." % + (len(flat_structure), len(flat_sequence), structure, flat_sequence)) + _, packed = _packed_nest_with_indices(structure, flat_sequence, 0) + return _sequence_like(structure, packed) + + +def map_structure(func, *structure): + """ + Apply `func` to each entry in `structure` and return a new structure. + """ + flat_structure = [flatten(s) for s in structure] + entries = zip(*flat_structure) + return pack_sequence_as(structure[0], [func(*x) for x in entries]) + + +def hold_mutable_vars(structure): + """ + Returns whether structure holds sequence like `list/dict`. + """ + for s in structure: + if is_sequence(s): + return True + return False + + +def copy_mutable_vars(structure): + """ + Returns vars copied from sequence without mutable property. + """ + flat_structure = copy.copy(flatten(structure)) + return pack_sequence_as(structure, flat_structure) + + +def _recursive_assert_same_structure(nest1, nest2, check_types): + """ + Helper function for `assert_same_structure`. + """ + is_sequence_nest1 = is_sequence(nest1) + if is_sequence_nest1 != is_sequence(nest2): + raise ValueError( + "The two structures don't have the same nested structure.\n\n" + "First structure: %s\n\nSecond structure: %s." % (nest1, nest2)) + if not is_sequence_nest1: + return # finished checking + if check_types: + type_nest1 = type(nest1) + type_nest2 = type(nest2) + if type_nest1 != type_nest2: + raise TypeError( + "The two structures don't have the same sequence type. First " + "structure has type %s, while second structure has type %s." % + (type_nest1, type_nest2)) + if isinstance(nest1, dict): + keys1 = set(six.iterkeys(nest1)) + keys2 = set(six.iterkeys(nest2)) + if keys1 != keys2: + raise ValueError( + "The two dictionaries don't have the same set of keys. First " + "structure has keys {}, while second structure has keys {}." + .format(keys1, keys2)) + nest1_as_sequence = [n for n in _yield_value(nest1)] + nest2_as_sequence = [n for n in _yield_value(nest2)] + for n1, n2 in zip(nest1_as_sequence, nest2_as_sequence): + _recursive_assert_same_structure(n1, n2, check_types) + + +def padding_to_same_structure(nest1, nest2, obj=None): + + def _padding_to_same_structure_single(value, obj): + + def change_none_to_obj(x): + if x is None: return obj + return x + + if is_sequence(value): + value = pack_sequence_as( + value, [change_none_to_obj(item) for item in flatten(value)]) + else: + value = change_none_to_obj(value) + return value + + nest1 = _padding_to_same_structure_single(nest1, obj) + nest2 = _padding_to_same_structure_single(nest2, obj) + return nest1, nest2 + + +def assert_same_structure(nest1, nest2, check_types=True): + """ + Confirm two nested structures with the same structure. + """ + len_nest1 = len(flatten(nest1)) if is_sequence(nest1) else 1 + len_nest2 = len(flatten(nest2)) if is_sequence(nest2) else 1 + if len_nest1 != len_nest2: + raise ValueError("The two structures don't have the same number of " + "elements.\n\nFirst structure (%i elements): %s\n\n" + "Second structure (%i elements): %s" % + (len_nest1, nest1, len_nest2, nest2)) + _recursive_assert_same_structure(nest1, nest2, check_types) + + +def _is_symmetric_padding(padding, data_dim): + """ + Check whether padding is symmetrical. + """ + assert len(padding) == data_dim * 2 or len(padding) == data_dim + is_sys = True + if len(padding) == data_dim * 2: + for i in range(data_dim): + if padding[i * 2] != padding[i * 2 + 1]: + is_sys = False + return is_sys + + +def _contain_var(list_or_tuple): + """ + Check whether list or tuple contains variable. + """ + for item in list_or_tuple: + if isinstance(item, Variable): + return True + return False + + +def get_shape_tensor_inputs(inputs, attrs, shape, op_type): + from .tensor import fill_constant, cast + + def _get_attr_shape(list_shape): + attr_shape = [] + for idx, dim in enumerate(list_shape): + if isinstance(dim, Variable): + attr_shape.append(-1) + else: + attr_shape.append(dim) + return attr_shape + + def _get_shape_tensor(list_shape): + shape_tensor_list = [] + for idx, dim in enumerate(list_shape): + if isinstance(dim, Variable): + dim.stop_gradient = True + check_dtype( + dim.dtype, 'shape[' + str(idx) + ']', ['int32', 'int64'], + op_type, + '(When type of shape in' + op_type + 'is list or tuple.)') + if convert_dtype(dim.dtype) == 'int64': + dim = cast(x=dim, dtype='int32') + shape_tensor_list.append(dim) + else: + temp_out = fill_constant([1], 'int32', dim, force_cpu=True) + shape_tensor_list.append(temp_out) + return shape_tensor_list + + if isinstance(shape, Variable): + shape.stop_gradient = True + check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'fill_constant', + '(When type of shape in' + op_type + ' is Variable.)') + if (convert_dtype(shape.dtype) == 'int64'): + shape = cast(shape, 'int32') + inputs["ShapeTensor"] = shape + elif isinstance(shape, (list, tuple)): + assert len(shape) > 0, ("The size of 'shape' in" + op_type + + " can't be zero, " + "but received %s." % len(shape)) + attrs["shape"] = _get_attr_shape(shape) + if _contain_var(shape): + inputs['ShapeTensorList'] = _get_shape_tensor(shape) + else: + raise TypeError("Shape only supports Variable, or list, or tuple.") + + +def _convert_to_tensor_list(old_list, dtype="int32"): + """ + Converts all elements of a list to Variable. + """ + from .tensor import fill_constant + new_list_tensor = [] + for ele in old_list: + + if isinstance(ele, Variable): + ele.stop_gradient = True + new_list_tensor.append(ele) + else: + assert isinstance(ele, six.integer_types) + temp_out = fill_constant([1], dtype, ele, force_cpu=True) + new_list_tensor.append(temp_out) + return new_list_tensor + + +def convert_shape_to_list(shape): + """ + Convert shape(list, tuple, variable) to list in imperative mode + """ + if isinstance(shape, (list, tuple)): + shape = list( + map(lambda x: x.numpy().flat[0] + if isinstance(x, Variable) else x, shape)) + else: + shape = shape.numpy().astype(int).tolist() + return shape + + +def check_shape(shape): + """ + Check shape type and shape elements type before passing it to fill_constant + """ + if isinstance(shape, Variable): + check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'fill_constant') + else: + for ele in shape: + if not isinstance(ele, Variable): + if ele < 0: + raise ValueError( + "All elements in ``shape`` must be positive when it's a list or tuple" + ) + if not isinstance(ele, six.integer_types): + raise TypeError( + "All elements in ``shape`` must be integers when it's a list or tuple" + ) + + +def try_set_static_shape_tensor(tensor, shape): + """Try to set static shape of tensor from a shape tensor. + + For example, + + import paddle + paddle.enable_static() + data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32') + shape = paddle.shape(data) # shape should be [-1, 2] instead of [-1, -1] + x = paddle.uniform(shape) + print(x.shape) + # (-1, 2) + + """ + if not _non_static_mode(): + # static mode, and shape is not all inferred (contains -1) + if -1 in tensor.shape: + if isinstance(shape, Variable): + shape = try_get_constant_shape_from_tensor(shape) + if shape: + tensor.desc.set_shape(shape) + + +def try_get_constant_shape_from_tensor(shape_tensor): + """Try to get shape from a tensor with constant value. + + For example, + + import paddle + paddle.enable_static() + data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32') + shape = paddle.shape(data) # shape should be [-1, 2] instead of [-1, -1] + x = paddle.uniform(shape) + print(x.shape) + # (-1, 2) + + """ + if not _non_static_mode(): + try: + if shape_tensor.op is not None: + generate_op = shape_tensor.op + if generate_op.type == 'shape': + var = shape_tensor.block.vars[ + generate_op.input_arg_names[0]] + return var.shape + except: + return None + + return None + + +def get_inputs_outputs_in_block(block): + """ + Returns the inputs and outputs variable used in this block but not + created in this block. + """ + assert isinstance( + block, + Block), "input non-Block argument for get_inputs_outputs_in_block." + assert block.parent_idx != -1, "input block should be a sub-block, not main block." + + # Find input/output var names of all ops in block + inner_inputs = set() + inner_outputs = set() + for op in block.ops: + for iname in op.input_names: + for in_var_name in op.input(iname): + if not block.has_var(in_var_name): + # variable not created in this block + inner_inputs.add(in_var_name) + for oname in op.output_names: + for out_var_name in op.output(oname): + if not block.has_var(out_var_name): + # variable not created in this block + inner_outputs.add(out_var_name) + + return inner_inputs, inner_outputs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lazy_init.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lazy_init.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6a457ab32baa42c38c5a05dde4a6ba1ef79dee --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lazy_init.py @@ -0,0 +1,115 @@ +# Copyright (c) 2022 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. + +from . import framework + +__all__ = ["LazyGuard"] + + +class LazyInitHelper(object): + """ + A Helper Context to trigger switching mode between dygraph and static mode, + and holds the startup program resource. + """ + + def __init__(self): + self._state = False + self._tracer = None + self._in_guard = False + + def enable(self): + """ + Switch into lazy mode. + + NOTE(dev): This is a very low level API and not exposed for user. + """ + if self._state: + return + assert framework._non_static_mode( + ), "LazyInit.enable() is only available in dygraph mode." + self._state = True + + def disable(self): + """ + Exit from lazy mode. + + NOTE(dev): This is a very low level API and not exposed for user. + """ + if not self._state: + return + self._state = False + + def __enter__(self): + """ + Switch into lazy mode and set _dygraph_tracer_ with None to convert + dygraph mode into static mode. + """ + self.enable() + if self._in_guard: return + self._tracer = framework._dygraph_tracer_ + framework._dygraph_tracer_ = None + self._in_guard = True + + def __exit__(self, *args, **kwargs): + """ + Exit from lazy mode and recover _dygraph_tracer_. + """ + self.disable() + if not self._in_guard: return + assert self._tracer is not None + framework._dygraph_tracer_ = self._tracer + self._tracer = None + self._in_guard = False + + @property + def state(self): + return self._state + + +_lazy_init_helper = LazyInitHelper() + + +def lazy_init_helper(): + global _lazy_init_helper + return _lazy_init_helper + + +class LazyGuard(object): + """ + LazyGuard is a wrapper interface for nn.Layer, it forwards the construct + process of user defined Layer. Meanwhile, it provides necessary API to + trigger EagerParamBase Lazy Initialization and get startup Program. + """ + + def __enter__(self): + """ + Construct instance from class_obj by Lazy Initializing parameters. + + Examples: + + .. code-block:: python + + from paddle import LazyGuard + from paddle.nn import Linear + + with LazyGuard(): + fc = LazyInit(Linear)(10, 10) + + for param in fc.parameters(): + param.initialize() + """ + lazy_init_helper().enable() + + def __exit__(self, *args, **kwargs): + lazy_init_helper().disable() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/libpaddle.so b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/libpaddle.so new file mode 100755 index 0000000000000000000000000000000000000000..e34b2a42806ee3f01e95380dc4827891808e173e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/libpaddle.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4c791d2a6152197428f8937bec84b141ccc5e775af26c3f51388d90d1b2f707 +size 174270784 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lod_tensor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lod_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc949412947301ec64fb85f21f3f400c557b591 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/lod_tensor.py @@ -0,0 +1,167 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from . import core +from .data_feeder import DataToLoDTensorConverter +import numpy as np + +__all__ = ['create_lod_tensor', 'create_random_int_lodtensor'] + + +def create_lod_tensor(data, recursive_seq_lens, place): + """ + Create a LoDTensor from a numpy array, list or existing LoDTensor. + + The implementation is as follows: + + 1. Check whether the length-based LoD, i.e., :code:`recursive_seq_lens` + is valid. + + 2. Convert :code:`recursive_seq_lens` to a offset-based LoD. + + 3. Based on :code:`place` , copy the :code:`data` from a numpy array, list + or existing LoDTensor to CPU or GPU device. + + 4. Set offset-based LoD to the output LoDTensor. + + Suppose we want to create a LoDTensor to hold data for word sequences, + where each word is represented by an integer. If we want to create + a LoDTensor to represent two sentences, one of 2 words, and one of 3 words. + + Then :code:`data` would be a numpy array of integers with shape (5, 1). + :code:`recursive_seq_lens` would be [[2, 3]], indicating the word number + in each sentence. This length-based :code:`recursive_seq_lens` [[2, 3]] + would be converted to offset-based LoD [[0, 2, 5]] inside the function + call. + + Please reference :ref:`user_guide_lod_tensor` for more details regarding LoD. + + Args: + data (numpy.ndarray|list|LoDTensor): a numpy array, a list or ad LoDTensor + holding the data to be copied. + recursive_seq_lens (list[list[int]]): a list of lists indicating the + length-based LoD info. + place (CPUPlace|CUDAPlace): CPU or GPU place indicating where the data + in the created LoDTensor will be stored. + + Returns: + A LoDTensor with tensor data and recursive_seq_lens info. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + t = fluid.create_lod_tensor(np.ndarray([5, 30]), [[2, 3]], fluid.CPUPlace()) + """ + if isinstance(data, core.LoDTensor): + return create_lod_tensor(np.array(data), recursive_seq_lens, place) + elif isinstance(data, list): + # dtype and shape are not important here, + # we only want to reuse code of DataToLoDTensorConverter + converter = DataToLoDTensorConverter(place=place, + lod_level=len(recursive_seq_lens), + shape=[], + dtype=core.VarDesc.VarType.FP32) + + new_recursive_seq_lens = [] + for seq in data: + new_recursive_seq_lens.append(len(seq)) + converter.feed(seq) + + assert [ + new_recursive_seq_lens + ] == recursive_seq_lens, "data and recursive_seq_lens do not match" + + arr = np.array(converter.data) + + # FIXME(zjl): the original logic of create_lod_tensor would append + # 1 to the shape. Maybe it is not a right way? Currently, we only + # follow the previous logic + arr = arr.reshape(arr.shape + (1, )) + tensor = core.LoDTensor() + tensor.set(arr, place) + tensor.set_recursive_sequence_lengths(recursive_seq_lens) + return tensor + elif isinstance(data, np.ndarray): + tensor = core.LoDTensor() + tensor.set(data, place) + tensor.set_recursive_sequence_lengths(recursive_seq_lens) + assert tensor.has_valid_recursive_sequence_lengths( + ), "the provided lod info is invalid" + return tensor + else: + raise TypeError( + "data should be either a LoDTensor, a Numpy array or a list") + + +def create_random_int_lodtensor(recursive_seq_lens, base_shape, place, low, + high): + """ + :api_attr: Static Graph + + Create a LoDTensor containing random integers. + + The implementation is as follows: + + 1. Obtain the shape of output LoDTensor based on :code:`recursive_seq_lens` + and :code:`base_shape` . The first dimension of the shape is the total + length of sequences, while the other dimensions are the same as + :code:`base_shape` . + + 2. Create a numpy array of random integers, and parse the created numpy + array as parameter :code:`data` of :ref:`api_fluid_create_lod_tensor` to + create the output LoDTensor. + + Suppose we want to create a LoDTensor to hold data for 2 sequences, where + the dimension of the sequences are [2, 30] and [3, 30] respectively. + The :code:`recursive_seq_lens` would be [[2, 3]], and :code:`base_shape` + would be [30] (the other dimensions excluding the sequence length). + Therefore, the shape of the output LoDTensor would be [5, 30], where + the first dimension 5 is the total lengths of the sequences, and the + other dimensions are :code:`base_shape`. + + Args: + recursive_seq_lens (list[list[int]]): a list of lists indicating the + length-based LoD info. + base_shape (list[int]): the shape of the output LoDTensor excluding + the first dimension. + place (CPUPlace|CUDAPlace): CPU or GPU place indicating where + the data in the created LoDTensor will be stored. + low (int): the lower bound of the random integers. + high (int): the upper bound of the random integers. + + Returns: + A LoDTensor with tensor data and recursive_seq_lens info, whose data + is inside [low, high]. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + t = fluid.create_random_int_lodtensor(recursive_seq_lens=[[2, 3]], + base_shape=[30], place=fluid.CPUPlace(), low=0, high=10) + print(t.shape()) # [5, 30] + """ + assert isinstance(base_shape, list), "base_shape should be a list" + # append the total number of basic elements to the front of its shape + overall_shape = [sum(recursive_seq_lens[-1])] + base_shape + # the range of integer data elements is [low, high] + data = np.random.random_integers(low, high, overall_shape).astype("int64") + return create_lod_tensor(data, recursive_seq_lens, place) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/log_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/log_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..2a13831e8478a504ab53c36301889b6249e17442 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/log_helper.py @@ -0,0 +1,56 @@ +# 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. + +from __future__ import print_function + +import logging + +__all__ = ['get_logger'] + + +def get_logger(name, level, fmt=None): + """ + Get logger from logging with given name, level and format without + setting logging basicConfig. For setting basicConfig in paddle + will disable basicConfig setting after import paddle. + + Args: + name (str): The logger name. + level (logging.LEVEL): The base level of the logger + fmt (str): Format of logger output + + Returns: + logging.Logger: logging logger with given settings + + Examples: + .. code-block:: python + + logger = log_helper.get_logger(__name__, logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + """ + + logger = logging.getLogger(name) + logger.setLevel(level) + handler = logging.StreamHandler() + + if fmt: + formatter = logging.Formatter(fmt=fmt, datefmt='%a %b %d %H:%M:%S') + handler.setFormatter(formatter) + + logger.addHandler(handler) + + # stop propagate for propagating may print + # log multiple times + logger.propagate = False + return logger diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/memory_analysis.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/memory_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..de9a260ada89e57a730759a79b8abbeece9b4d69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/memory_analysis.py @@ -0,0 +1,77 @@ +# Copyright (c) 2021 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. + +from . import core +import numpy as np + + +def get_var_and_memory_size(block, var_name, batch_size=None): + var = block._find_var_recursive(var_name) + assert var is not None, "Variable {} cannot be found".format(var_name) + assert var.type == core.VarDesc.VarType.LOD_TENSOR, "Variable {} is not Tensor".format( + var_name) + shape = list(var.shape) + if not shape: + return var, 0 + + has_none = False + for i, s in enumerate(shape): + if s is None or s < 0: + assert not has_none + shape[i] = batch_size + has_none = True + assert all([s >= 0 + for s in shape]), "shape {} is not deterministic".format(shape) + mem_size = int(np.prod(shape)) * core.size_of_dtype(var.dtype) + return var, mem_size + + +def pre_allocate_memory(size, place): + t = core.LoDTensor() + t._set_dims([size]) + t._mutable_data(place, core.VarDesc.VarType.INT8) + del t + + +# NOTE: does not consider inplace yet. +def get_max_memory_info(program, batch_size=None): + assert program.num_blocks == 1, "only support to analysis program with only one block" + cur_tmp_mem = 0 + max_tmp_mem = 0 + max_persistable_mem = 0 + visited_vars = set() + alived_vars = [] + + block = program.global_block() + gc_vars = core._get_eager_deletion_vars(program.desc, [])[0] + for i, op in enumerate(block.ops): + var_names = op.input_arg_names + op.output_arg_names + for var_name in var_names: + if var_name in visited_vars: + continue + visited_vars.add(var_name) + var, mem_size = get_var_and_memory_size(block, var_name, batch_size) + if var.persistable: + max_persistable_mem += mem_size + else: + cur_tmp_mem += mem_size + max_tmp_mem = max(max_tmp_mem, cur_tmp_mem) + + cur_gc_vars = gc_vars[i] + for var_name in var_names: + if var_name not in cur_gc_vars: + continue + _, mem_size = get_var_and_memory_size(block, var_name, batch_size) + cur_tmp_mem -= mem_size + return max_tmp_mem, max_persistable_mem diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/metrics.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc6be7e093876855dda0b1aeef08edcbb3cac1f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/metrics.py @@ -0,0 +1,1005 @@ +# Copyright (c) 2018 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. +""" +Fluid Metrics +""" + +from __future__ import print_function + +import numpy as np +import copy +import warnings +import six + +from .layer_helper import LayerHelper +from .initializer import Constant +from . import unique_name +from .framework import Program, Variable, program_guard +from . import layers +from .layers import detection + +__all__ = [ + 'MetricBase', + 'CompositeMetric', + 'Precision', + 'Recall', + 'Accuracy', + 'ChunkEvaluator', + 'EditDistance', + 'DetectionMAP', + 'Auc', +] + + +def _is_numpy_(var): + return isinstance(var, (np.ndarray, np.generic)) + + +def _is_number_(var): + return isinstance(var, int) or isinstance(var, np.int64) or isinstance( + var, float) or (isinstance(var, np.ndarray) and var.shape == (1, )) + + +def _is_number_or_matrix_(var): + return _is_number_(var) or isinstance(var, np.ndarray) + + +class MetricBase(object): + """ + In many cases, we usually have to split the test data into mini-batches for evaluating + deep neural networks, therefore we need to collect the evaluation results of each + mini-batch and aggregate them into the final result. The paddle.fluid.metrics is + designed for a convenient way of deep neural network evaluation. + + The paddle.fluid.metrics contains serval different evaluation metrics + like precision and recall, and most of them have the following functions: + + 1. take the prediction result and the corresponding labels of a mini-batch as input, + then compute the evaluation result for the input mini-batch. + + 2. aggregate the existing evaluation results as the overall performance. + + The class Metric is the base class for all classes in paddle.fluid.metrics, it defines + the fundamental APIs for all metrics classes, including: + + 1. update(preds, labels): given the prediction results (preds) and the labels (labels) + of some mini-batch, compute the evaluation result of that mini-batch, and memorize the + evaluation result. + + 2. eval(): aggregate all existing evaluation result in the memory, and return the overall + performance across different mini-batches. + + 3. reset(): empty the memory. + + """ + + def __init__(self, name): + """ + The constructor of the metric class. + + Args: + name(str): The name of metric instance. such as, "accuracy". + It can be used to distinguish different metric instances in a model. + + Returns: + The constructed class instance. + + Return types: + The MetricBase or its succeed classes + + """ + self._name = str(name) if name != None else self.__class__.__name__ + + def __str__(self): + return self._name + + def reset(self): + """ + reset function empties the evaluation memory for previous mini-batches. + + Args: + None + + Returns: + None + + Return types: + None + + """ + states = { + attr: value + for attr, value in six.iteritems(self.__dict__) + if not attr.startswith("_") + } + for attr, value in six.iteritems(states): + if isinstance(value, int): + setattr(self, attr, 0) + elif isinstance(value, float): + setattr(self, attr, .0) + elif isinstance(value, (np.ndarray, np.generic)): + setattr(self, attr, np.zeros_like(value)) + else: + setattr(self, attr, None) + + def get_config(self): + """ + Get the metric and current states. + The states are the members who do not has "_" prefix. + + Args: + None + + Returns: + a python dict, which contains the inner states of the metric instance + + Return types: + a python dict + """ + states = { + attr: value + for attr, value in six.iteritems(self.__dict__) + if not attr.startswith("_") + } + config = {} + config.update({"name": self._name, "states": copy.deepcopy(states)}) + return config + + def update(self, preds, labels): + """ + Given the prediction results (preds) and the labels (labels) + of some mini-batch, compute the evaluation result of that mini-batch, + and memorize the evaluation result. Please notice that the update function only + memorizes the evaluation result but would not return the score. If you want to + get the evaluation result, please call eval() function. + + Args: + preds(numpy.array): the predictions of current minibatch + labels(numpy.array): the labels of current minibatch. + + Returns: + None + + Return types: + None + + """ + raise NotImplementedError( + "Should not use it directly, please extend it.") + + def eval(self): + """ + Aggregate all existing evaluation results in the memory, and return the overall + performance across different mini-batches. + + Args: + None + + Returns: + The overall performance across different mini-batches. + + Return types: + float|list(float)|numpy.array: the metrics via Python. + """ + raise NotImplementedError( + "Should not use it directly, please extend it.") + + +class CompositeMetric(MetricBase): + """ + This op creates a container that contains the union of all the added metrics. + After the metrics added in, calling eval() method will compute all the contained metrics automatically. + CAUTION: only metrics with the SAME argument list can be added in a CompositeMetric instance. + + Inherit from: `MetricBase `_ + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + import paddle.fluid as fluid + import numpy as np + preds = [[0.1], [0.7], [0.8], [0.9], [0.2], + [0.2], [0.3], [0.5], [0.8], [0.6]] + labels = [[0], [1], [1], [1], [1], + [0], [0], [0], [0], [0]] + preds = np.array(preds) + labels = np.array(labels) + comp = fluid.metrics.CompositeMetric() + precision = fluid.metrics.Precision() + recall = fluid.metrics.Recall() + comp.add_metric(precision) + comp.add_metric(recall) + comp.update(preds=preds, labels=labels) + numpy_precision, numpy_recall = comp.eval() + print("expect precision: %.2f, got %.2f" % ( 3. / 5, numpy_precision ) ) + print("expect recall: %.2f, got %.2f" % (3. / 4, numpy_recall ) ) + """ + + def __init__(self, name=None): + super(CompositeMetric, self).__init__(name) + self._metrics = [] + + def add_metric(self, metric): + """ + Add a new metric to container. Noted that the argument list + of the added one should be consistent with existed ones. + + Args: + metric(MetricBase): a instance of MetricBase + """ + if not isinstance(metric, MetricBase): + raise ValueError("SubMetric should be inherit from MetricBase.") + self._metrics.append(metric) + + def update(self, preds, labels): + """ + Update the metrics of this container. + + Args: + preds(numpy.array): predicted results of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric. + labels(numpy.array): ground truth of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric. + """ + for m in self._metrics: + m.update(preds, labels) + + def eval(self): + """ + Calculate the results of all metrics sequentially. + + Returns: + list: results of all added metrics. + The shape and dtype of each result depend on the definition of its metric. + """ + ans = [] + for m in self._metrics: + ans.append(m.eval()) + return ans + + +class Precision(MetricBase): + """ + Precision (also called positive predictive value) is the fraction of + relevant instances among the retrieved instances. Refer to + https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers + + Noted that this class manages the precision score only for binary classification task. + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + metric = fluid.metrics.Precision() + + # generate the preds and labels + + preds = [[0.1], [0.7], [0.8], [0.9], [0.2], + [0.2], [0.3], [0.5], [0.8], [0.6]] + + labels = [[0], [1], [1], [1], [1], + [0], [0], [0], [0], [0]] + + preds = np.array(preds) + labels = np.array(labels) + + metric.update(preds=preds, labels=labels) + numpy_precision = metric.eval() + + print("expect precision: %.2f and got %.2f" % ( 3.0 / 5.0, numpy_precision)) + """ + + def __init__(self, name=None): + super(Precision, self).__init__(name) + self.tp = 0 # true positive + self.fp = 0 # false positive + + def update(self, preds, labels): + """ + Update the precision based on the current mini-batch prediction results . + + Args: + preds(numpy.ndarray): prediction results of current mini-batch, + the output of two-class sigmoid function. + Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'. + labels(numpy.ndarray): ground truth (labels) of current mini-batch, + the shape should keep the same as preds. + Shape: [batch_size, 1], Dtype: 'int32' or 'int64'. + """ + if not _is_numpy_(preds): + raise ValueError("The 'preds' must be a numpy ndarray.") + if not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray.") + sample_num = labels.shape[0] + preds = np.rint(preds).astype("int32") + + for i in range(sample_num): + pred = preds[i] + label = labels[i] + if pred == 1: + if pred == label: + self.tp += 1 + else: + self.fp += 1 + + def eval(self): + """ + Calculate the final precision. + + Returns: + float: Results of the calculated Precision. Scalar output with float dtype. + """ + ap = self.tp + self.fp + return float(self.tp) / ap if ap != 0 else .0 + + +class Recall(MetricBase): + """ + Recall (also known as sensitivity) is the fraction of + relevant instances that have been retrieved over the + total amount of relevant instances + + Refer to: + https://en.wikipedia.org/wiki/Precision_and_recall + + Noted that this class manages the recall score only for binary classification task. + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + metric = fluid.metrics.Recall() + + # generate the preds and labels + + preds = [[0.1], [0.7], [0.8], [0.9], [0.2], + [0.2], [0.3], [0.5], [0.8], [0.6]] + + labels = [[0], [1], [1], [1], [1], + [0], [0], [0], [0], [0]] + + preds = np.array(preds) + labels = np.array(labels) + + metric.update(preds=preds, labels=labels) + numpy_recall = metric.eval() + + print("expect recall: %.2f and got %.2f" % ( 3.0 / 4.0, numpy_recall)) + """ + + def __init__(self, name=None): + super(Recall, self).__init__(name) + self.tp = 0 # true positive + self.fn = 0 # false negative + + def update(self, preds, labels): + """ + Update the recall based on the current mini-batch prediction results. + + Args: + preds(numpy.array): prediction results of current mini-batch, + the output of two-class sigmoid function. + Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'. + labels(numpy.array): ground truth (labels) of current mini-batch, + the shape should keep the same as preds. + Shape: [batch_size, 1], Dtype: 'int32' or 'int64'. + """ + if not _is_numpy_(preds): + raise ValueError("The 'preds' must be a numpy ndarray.") + if not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray.") + sample_num = labels.shape[0] + preds = np.rint(preds).astype("int32") + + for i in range(sample_num): + pred = preds[i] + label = labels[i] + if label == 1: + if pred == label: + self.tp += 1 + else: + self.fn += 1 + + def eval(self): + """ + Calculate the final recall. + + Returns: + float: results of the calculated Recall. Scalar output with float dtype. + """ + recall = self.tp + self.fn + return float(self.tp) / recall if recall != 0 else .0 + + +class Accuracy(MetricBase): + """ + This interface is used to calculate the mean accuracy over multiple batches. + Accuracy object has two state: value and weight. The definition of Accuracy is available at + https://en.wikipedia.org/wiki/Accuracy_and_precision + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + #suppose we have batch_size = 128 + batch_size=128 + accuracy_manager = fluid.metrics.Accuracy() + + #suppose the accuracy is 0.9 for the 1st batch + batch1_acc = 0.9 + accuracy_manager.update(value = batch1_acc, weight = batch_size) + print("expect accuracy: %.2f, get accuracy: %.2f" % (batch1_acc, accuracy_manager.eval())) + + #suppose the accuracy is 0.8 for the 2nd batch + batch2_acc = 0.8 + + accuracy_manager.update(value = batch2_acc, weight = batch_size) + #the joint acc for batch1 and batch2 is (batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2 + print("expect accuracy: %.2f, get accuracy: %.2f" % ((batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2, accuracy_manager.eval())) + + #reset the accuracy_manager + accuracy_manager.reset() + #suppose the accuracy is 0.8 for the 3rd batch + batch3_acc = 0.8 + accuracy_manager.update(value = batch3_acc, weight = batch_size) + print("expect accuracy: %.2f, get accuracy: %.2f" % (batch3_acc, accuracy_manager.eval())) + """ + + def __init__(self, name=None): + super(Accuracy, self).__init__(name) + self.value = .0 + self.weight = .0 + + def update(self, value, weight): + r""" + This function takes the minibatch states (value, weight) as input, + to accumulate and update the corresponding status of the Accuracy object. The update method is as follows: + + .. math:: + \\\\ \\begin{array}{l}{\\text { self. value }+=\\text { value } * \\text { weight }} \\\\ {\\text { self. weight }+=\\text { weight }}\\end{array} \\\\ + + Args: + value(float|numpy.array): accuracy of one minibatch. + weight(int|float): minibatch size. + """ + if not _is_number_or_matrix_(value): + raise ValueError( + "The 'value' must be a number(int, float) or a numpy ndarray.") + if not _is_number_(weight): + raise ValueError("The 'weight' must be a number(int, float).") + if _is_number_(weight) and weight < 0: + raise ValueError("The 'weight' can not be negative") + self.value += value * weight + self.weight += weight + + def eval(self): + """ + This function returns the mean accuracy (float or numpy.array) for all accumulated minibatches. + + Returns: + float or numpy.array: mean accuracy for all accumulated minibatches. + + """ + if self.weight == 0: + raise ValueError("There is no data in Accuracy Metrics. \ + Please check layers.accuracy output has added to Accuracy.") + return self.value / self.weight + + +class ChunkEvaluator(MetricBase): + """ + Accumulate counter numbers output by chunk_eval from mini-batches and + compute the precision recall and F1-score using the accumulated counter + numbers. + ChunkEvaluator has three states: num_infer_chunks, num_label_chunks and num_correct_chunks, + which correspond to the number of chunks, the number of labeled chunks, and the number of correctly identified chunks. + For some basics of chunking, please refer to + `Chunking with Support Vector Machines `_ . + ChunkEvalEvaluator computes the precision, recall, and F1-score of chunk detection, + and supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes. + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + # init the chunk-level evaluation manager + metric = fluid.metrics.ChunkEvaluator() + + # suppose the model predict 10 chucks, while 8 ones are correct and the ground truth has 9 chucks. + num_infer_chunks = 10 + num_label_chunks = 9 + num_correct_chunks = 8 + + metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks) + numpy_precision, numpy_recall, numpy_f1 = metric.eval() + + print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1)) + + # the next batch, predicting 3 perfectly correct chucks. + num_infer_chunks = 3 + num_label_chunks = 3 + num_correct_chunks = 3 + + metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks) + numpy_precision, numpy_recall, numpy_f1 = metric.eval() + + print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1)) + + """ + + def __init__(self, name=None): + super(ChunkEvaluator, self).__init__(name) + self.num_infer_chunks = 0 + self.num_label_chunks = 0 + self.num_correct_chunks = 0 + + def update(self, num_infer_chunks, num_label_chunks, num_correct_chunks): + r""" + This function takes (num_infer_chunks, num_label_chunks, num_correct_chunks) as input, + to accumulate and update the corresponding status of the ChunkEvaluator object. The update method is as follows: + + .. math:: + \\\\ \\begin{array}{l}{\\text { self. num_infer_chunks }+=\\text { num_infer_chunks }} \\\\ {\\text { self. num_Label_chunks }+=\\text { num_label_chunks }} \\\\ {\\text { self. num_correct_chunks }+=\\text { num_correct_chunks }}\\end{array} \\\\ + + Args: + num_infer_chunks(int|numpy.array): The number of chunks in Inference on the given minibatch. + num_label_chunks(int|numpy.array): The number of chunks in Label on the given mini-batch. + num_correct_chunks(int|float|numpy.array): The number of chunks both in Inference and Label on the + given mini-batch. + """ + if not _is_number_or_matrix_(num_infer_chunks): + raise ValueError( + "The 'num_infer_chunks' must be a number(int) or a numpy ndarray." + ) + if not _is_number_or_matrix_(num_label_chunks): + raise ValueError( + "The 'num_label_chunks' must be a number(int, float) or a numpy ndarray." + ) + if not _is_number_or_matrix_(num_correct_chunks): + raise ValueError( + "The 'num_correct_chunks' must be a number(int, float) or a numpy ndarray." + ) + self.num_infer_chunks += num_infer_chunks + self.num_label_chunks += num_label_chunks + self.num_correct_chunks += num_correct_chunks + + def eval(self): + """ + This function returns the mean precision, recall and f1 score for all accumulated minibatches. + + Returns: + float: mean precision, recall and f1 score. + + """ + precision = float( + self.num_correct_chunks + ) / self.num_infer_chunks if self.num_infer_chunks else 0 + recall = float(self.num_correct_chunks + ) / self.num_label_chunks if self.num_label_chunks else 0 + f1_score = float(2 * precision * recall) / ( + precision + recall) if self.num_correct_chunks else 0 + return precision, recall, f1_score + + +class EditDistance(MetricBase): + """ + This API is for the management of edit distances. + Editing distance is a method to quantify the degree of dissimilarity + between two strings, such as words, by calculating the minimum editing + operand (add, delete or replace) required to convert one string into another. + Refer to https://en.wikipedia.org/wiki/Edit_distance. + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + # suppose that batch_size is 128 + batch_size = 128 + + # init the edit distance manager + distance_evaluator = fluid.metrics.EditDistance("EditDistance") + + # generate the edit distance across 128 sequence pairs, the max distance is 10 here + edit_distances_batch0 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) + seq_num_batch0 = batch_size + + distance_evaluator.update(edit_distances_batch0, seq_num_batch0) + avg_distance, wrong_instance_ratio = distance_evaluator.eval() + print("the average edit distance for batch0 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio)) + + edit_distances_batch1 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) + seq_num_batch1 = batch_size + + distance_evaluator.update(edit_distances_batch1, seq_num_batch1) + avg_distance, wrong_instance_ratio = distance_evaluator.eval() + print("the average edit distance for batch0 and batch1 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio)) + + distance_evaluator.reset() + + edit_distances_batch2 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) + seq_num_batch2 = batch_size + + distance_evaluator.update(edit_distances_batch2, seq_num_batch2) + avg_distance, wrong_instance_ratio = distance_evaluator.eval() + print("the average edit distance for batch2 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio)) + + """ + + def __init__(self, name): + super(EditDistance, self).__init__(name) + self.total_distance = .0 + self.seq_num = 0 + self.instance_error = 0 + + def update(self, distances, seq_num): + """ + Update the overall edit distance + + Args: + distances(numpy.array): a (batch_size, 1) numpy.array, each element represents the edit distance between two sequences. + seq_num(int|float): standing for the number of sequence pairs. + """ + if not _is_numpy_(distances): + raise ValueError("The 'distances' must be a numpy ndarray.") + if not _is_number_(seq_num): + raise ValueError("The 'seq_num' must be a number(int, float).") + seq_right_count = np.sum(distances == 0) + total_distance = np.sum(distances) + self.seq_num += seq_num + self.instance_error += seq_num - seq_right_count + self.total_distance += total_distance + + def eval(self): + """ + Return two floats: + avg_distance: the average distance for all sequence pairs updated using the update function. + avg_instance_error: the ratio of sequence pairs whose edit distance is not zero. + """ + if self.seq_num == 0: + raise ValueError( + "There is no data in EditDistance Metric. Please check layers.edit_distance output has been added to EditDistance." + ) + avg_distance = self.total_distance / self.seq_num + avg_instance_error = self.instance_error / float(self.seq_num) + return avg_distance, avg_instance_error + + +class Auc(MetricBase): + """ + The auc metric is for binary classification. + Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve. + Please notice that the auc metric is implemented with python, which may be a little bit slow. + If you concern the speed, please use the fluid.layers.auc instead. + + The `auc` function creates four local variables, `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` that are used to + compute the AUC. To discretize the AUC curve, a linearly spaced set of + thresholds is used to compute pairs of recall and precision values. The area + under the ROC-curve is therefore computed using the height of the recall + values by the false positive rate, while the area under the PR-curve is the + computed using the height of the precision values by the recall. + + Args: + name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None. + curve (str): Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. + + "NOTE: only implement the ROC curve type via Python now." + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + # init the auc metric + auc_metric = fluid.metrics.Auc("ROC") + + # suppose that batch_size is 128 + batch_num = 100 + batch_size = 128 + + for batch_id in range(batch_num): + + class0_preds = np.random.random(size = (batch_size, 1)) + class1_preds = 1 - class0_preds + + preds = np.concatenate((class0_preds, class1_preds), axis=1) + + labels = np.random.randint(2, size = (batch_size, 1)) + auc_metric.update(preds = preds, labels = labels) + + # shall be some score closing to 0.5 as the preds are randomly assigned + print("auc for iteration %d is %.2f" % (batch_id, auc_metric.eval())) + """ + + def __init__(self, name, curve='ROC', num_thresholds=4095): + super(Auc, self).__init__(name=name) + self._curve = curve + self._num_thresholds = num_thresholds + + _num_pred_buckets = num_thresholds + 1 + self._stat_pos = [0] * _num_pred_buckets + self._stat_neg = [0] * _num_pred_buckets + + def update(self, preds, labels): + """ + Update the auc curve with the given predictions and labels. + + Args: + preds (numpy.array): an numpy array in the shape of (batch_size, 2), preds[i][j] denotes the probability of classifying the instance i into the class j. + labels (numpy.array): an numpy array in the shape of (batch_size, 1), labels[i] is either o or 1, representing the label of the instance i. + """ + if not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray.") + if not _is_numpy_(preds): + raise ValueError("The 'predictions' must be a numpy ndarray.") + + for i, lbl in enumerate(labels): + value = preds[i, 1] + bin_idx = int(value * self._num_thresholds) + assert bin_idx <= self._num_thresholds + if lbl: + self._stat_pos[bin_idx] += 1.0 + else: + self._stat_neg[bin_idx] += 1.0 + + @staticmethod + def trapezoid_area(x1, x2, y1, y2): + return abs(x1 - x2) * (y1 + y2) / 2.0 + + def eval(self): + """ + Return the area (a float score) under auc curve + + Return: + float: the area under auc curve + """ + tot_pos = 0.0 + tot_neg = 0.0 + auc = 0.0 + + idx = self._num_thresholds + while idx >= 0: + tot_pos_prev = tot_pos + tot_neg_prev = tot_neg + tot_pos += self._stat_pos[idx] + tot_neg += self._stat_neg[idx] + auc += self.trapezoid_area(tot_neg, tot_neg_prev, tot_pos, + tot_pos_prev) + idx -= 1 + + return auc / tot_pos / tot_neg if tot_pos > 0.0 and tot_neg > 0.0 else 0.0 + + +class DetectionMAP(object): + """ + Calculate the detection mean average precision (mAP). + + The general steps are as follows: + + 1. calculate the true positive and false positive according to the input + of detection and labels. + 2. calculate mAP value, support two versions: '11 point' and 'integral'. + 11point: the 11-point interpolated average precision. + integral: the natural integral of the precision-recall curve. + + Please get more information from the following articles: + + https://sanchom.wordpress.com/tag/average-precision/ + + https://arxiv.org/abs/1512.02325 + + Args: + input (Variable): LoDTensor, The detection results, which is a LoDTensor with shape + [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax]. + The data type is float32 or float64. + gt_label (Variable): LoDTensor, The ground truth label index, which is a LoDTensor + with shape [N, 1].The data type is float32 or float64. + gt_box (Variable): LoDTensor, The ground truth bounding box (bbox), which is a + LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax]. + The data type is float32 or float64. + gt_difficult (Variable|None): LoDTensor, Whether this ground truth is a difficult + bounding bbox, which can be a LoDTensor [N, 1] or not set. If None, + it means all the ground truth labels are not difficult bbox.The + data type is int. + class_num (int): The class number. + background_label (int): The index of background label, the background + label will be ignored. If set to -1, then all categories will be + considered, 0 by default. + overlap_threshold (float): The threshold for deciding true/false + positive, 0.5 by default. + evaluate_difficult (bool): Whether to consider difficult ground truth + for evaluation, True by default. This argument does not work when + gt_difficult is None. + ap_version (str): The average precision calculation ways, it must be + 'integral' or '11point'. Please check + https://sanchom.wordpress.com/tag/average-precision/ for details. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + import paddle + paddle.enable_static() + + batch_size = None # can be any size + image_boxs_num = 10 + bounding_bboxes_num = 21 + + pb = fluid.data(name='prior_box', shape=[image_boxs_num, 4], + dtype='float32') + + pbv = fluid.data(name='prior_box_var', shape=[image_boxs_num, 4], + dtype='float32') + + loc = fluid.data(name='target_box', shape=[batch_size, bounding_bboxes_num, 4], + dtype='float32') + + scores = fluid.data(name='scores', shape=[batch_size, bounding_bboxes_num, image_boxs_num], + dtype='float32') + + nmsed_outs = fluid.layers.detection_output(scores=scores, + loc=loc, prior_box=pb, prior_box_var=pbv) + + gt_box = fluid.data(name="gt_box", shape=[batch_size, 4], dtype="float32") + gt_label = fluid.data(name="gt_label", shape=[batch_size, 1], dtype="float32") + difficult = fluid.data(name="difficult", shape=[batch_size, 1], dtype="float32") + + exe = fluid.Executor(fluid.CUDAPlace(0)) + map_evaluator = fluid.metrics.DetectionMAP(nmsed_outs, gt_label, gt_box, difficult, class_num = 3) + + cur_map, accum_map = map_evaluator.get_map_var() + + + """ + + def __init__(self, + input, + gt_label, + gt_box, + gt_difficult=None, + class_num=None, + background_label=0, + overlap_threshold=0.5, + evaluate_difficult=True, + ap_version='integral'): + + self.helper = LayerHelper('map_eval') + gt_label = layers.cast(x=gt_label, dtype=gt_box.dtype) + if gt_difficult: + gt_difficult = layers.cast(x=gt_difficult, dtype=gt_box.dtype) + label = layers.concat([gt_label, gt_difficult, gt_box], axis=1) + else: + label = layers.concat([gt_label, gt_box], axis=1) + + # calculate mean average precision (mAP) of current mini-batch + map = detection.detection_map(input, + label, + class_num, + background_label, + overlap_threshold=overlap_threshold, + evaluate_difficult=evaluate_difficult, + ap_version=ap_version) + + states = [] + states.append( + self._create_state(dtype='int32', + shape=None, + suffix='accum_pos_count')) + states.append( + self._create_state(dtype='float32', + shape=None, + suffix='accum_true_pos')) + states.append( + self._create_state(dtype='float32', + shape=None, + suffix='accum_false_pos')) + var = self._create_state(dtype='int32', shape=[1], suffix='has_state') + self.helper.set_variable_initializer(var, + initializer=Constant(value=int(0))) + self.has_state = var + + # calculate accumulative mAP + accum_map = detection.detection_map( + input, + label, + class_num, + background_label, + overlap_threshold=overlap_threshold, + evaluate_difficult=evaluate_difficult, + has_state=self.has_state, + input_states=states, + out_states=states, + ap_version=ap_version) + + layers.fill_constant(shape=self.has_state.shape, + value=1, + dtype=self.has_state.dtype, + out=self.has_state) + + self.cur_map = map + self.accum_map = accum_map + + def _create_state(self, suffix, dtype, shape): + """ + Create state variable. + Args: + suffix(str): the state suffix. + dtype(str|core.VarDesc.VarType): the state data type + shape(tuple|list): the shape of state + Returns: State variable + """ + state = self.helper.create_variable(name="_".join( + [unique_name.generate(self.helper.name), suffix]), + persistable=True, + dtype=dtype, + shape=shape) + return state + + def get_map_var(self): + """ + Returns: mAP variable of current mini-batch and + accumulative mAP variable cross mini-batches. + """ + return self.cur_map, self.accum_map + + def reset(self, executor, reset_program=None): + """ + Reset metric states at the begin of each pass/user specified batch. + Args: + executor(Executor): a executor for executing + the reset_program. + reset_program(Program|None): a single Program for reset process. + If None, will create a Program. + """ + + def _clone_var_(block, var): + assert isinstance(var, Variable) + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=var.persistable) + + if reset_program is None: + reset_program = Program() + with program_guard(main_program=reset_program): + var = _clone_var_(reset_program.current_block(), self.has_state) + layers.fill_constant(shape=var.shape, + value=0, + dtype=var.dtype, + out=var) + executor.run(reset_program) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/multiprocess_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/multiprocess_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..73bba0069cdd21f1235a97313d613c1b87b1a51b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/multiprocess_utils.py @@ -0,0 +1,140 @@ +# 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. + +import sys +import signal +import atexit + +from . import core + +# NOTE: queue has a different name in python2 and python3 +import queue + +# multi-process worker check indices queue interval, avoid +# hanging in subprocess data loading +MP_STATUS_CHECK_INTERVAL = 5. + +# NOTE: [ mmap files clear ] If there is still data in the multiprocess queue when the main process finishes reading, +# the data in the queue needs to be popped. Then the LoDTensor read by the main process +# from the child process will automatically clear the memory-mapped file. +multiprocess_queue_set = set() + + +def _clear_multiprocess_queue_set(): + global multiprocess_queue_set + for data_queue in multiprocess_queue_set: + while True: + try: + data_queue.get_nowait() + except queue.Empty: + break + + +# NOTE: main process clear function at exit +def _cleanup(): + # NOTE: inter-process Queue shared memory objects clear function + _clear_multiprocess_queue_set() + # NOTE: main process memory map files clear funciton + core._cleanup_mmap_fds() + + +# NOTE: for child process clear function at exit +def _cleanup_mmap(): + # clear memory map files in child process + core._cleanup_mmap_fds() + + +# NOTE used for register a function to be executed at interpreter exit. +class CleanupFuncRegistrar(): + # Record the cleanup functions that have been executed + _executed_func_set = set() + # Record the cleanup functions that have been registered + _registered_func_set = set() + + @classmethod + def register(cls, function, signals=[]): + + def _func_exectuor(): + if function not in cls._executed_func_set: + try: + function() + finally: + cls._executed_func_set.add(function) + + def _func_register(function): + if not callable(function): + raise TypeError("%s is not callable object." % (function)) + # check function object whether hash-able + set([function]) + if function not in cls._registered_func_set: + atexit.register(_func_exectuor) + cls._registered_func_set.add(function) + + def _signal_handler(signum=None, frame=None): + _func_exectuor() + if signum is not None: + if signum == signal.SIGINT: + raise KeyboardInterrupt + sys.exit(signum) + + def _signal_register(signals): + signals = set(signals) + for sig in signals: + orig_handler = signal.signal(sig, _signal_handler) + if orig_handler not in (signal.SIG_DFL, signal.SIG_IGN): + if (sig == signal.SIGINT + and orig_handler is signal.default_int_handler): + continue + if orig_handler not in cls._registered_func_set: + atexit.register(orig_handler) + cls._registered_func_set.add(orig_handler) + + # deal with signals + _signal_register(signals) + # deal with function + _func_register(function) + + +# NOTE: [ mmap files clear ] When the main process exits unexpectedly, the remaining +# shared memory objects in the inter-process Queue and the main process (mostly in the +# BlockingQueue) may not be completely released, resulting in the corresponding +# memory-mapped file remaining on the disk (/dev/shm), so register this function +# to clean up shared memory objects in these two queues before the python interpreter exits. +# NOTE: Currently multi-process DataLoader only supports Linux platform +if not (sys.platform == 'darwin' or sys.platform == 'win32'): + CleanupFuncRegistrar.register(_cleanup) + +# ------------ SIGCHLD handler setting -------------- +_SIGCHLD_handler_set = False + + +def _set_SIGCHLD_handler(): + global _SIGCHLD_handler_set + if _SIGCHLD_handler_set: + return + + current_handler = signal.getsignal(signal.SIGCHLD) + if not callable(current_handler): + current_handler = None + + def __handler__(signum, frame): + # NOTE: Here the signum is SIGCHLD, when the child process exits, + # this handler will be called whenever the child process exits + # normally or abnormally. + core._throw_error_if_process_failed() + if current_handler is not None: + current_handler(signum, frame) + + signal.signal(signal.SIGCHLD, __handler__) + _SIGCHLD_handler_set = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/net_drawer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/net_drawer.py new file mode 100644 index 0000000000000000000000000000000000000000..a7323d1ead2d9193eebd641c748707c8109080d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/net_drawer.py @@ -0,0 +1,131 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import argparse +import json +import logging +from collections import defaultdict + +import paddle.fluid.core as core +import paddle.fluid.proto.framework_pb2 as framework_pb2 +from paddle.fluid.log_helper import get_logger + +logger = get_logger(__name__, logging.INFO) + +try: + from .graphviz import Graph +except ImportError: + logger.info( + 'Cannot import graphviz, which is required for drawing a network. This ' + 'can usually be installed in python with "pip install graphviz". Also, ' + 'pydot requires graphviz to convert dot files to pdf: in ubuntu, this ' + 'can usually be installed with "sudo apt-get install graphviz".') + print('net_drawer will not run correctly. Please install the correct ' + 'dependencies.') + exit(0) + +OP_STYLE = { + 'shape': 'oval', + 'color': '#0F9D58', + 'style': 'filled', + 'fontcolor': '#FFFFFF' +} + +VAR_STYLE = {} + +GRAPH_STYLE = { + "rankdir": "TB", +} + +GRAPH_ID = 0 + + +def unique_id(): + + def generator(): + GRAPH_ID += 1 + return GRAPH_ID + + return generator + + +def draw_node(op): + node = OP_STYLE + node["name"] = op.type + node["label"] = op.type + return node + + +def draw_edge(var_parent, op, var, arg): + edge = VAR_STYLE + edge["label"] = "%s(%s)" % (var.parameter, arg) + edge["head_name"] = op.type + edge["tail_name"] = var_parent[arg] + return edge + + +def parse_graph(program, graph, var_dict, **kwargs): + + # fill the known variables + for block in program.blocks: + for var in block.vars: + if var not in var_dict: + var_dict[var] = "Feed" + + temp_id = 0 + proto = framework_pb2.ProgramDesc.FromString( + program.desc.serialize_to_string()) + for block in proto.blocks: + for op in block.ops: + op.type = op.type + "_" + str(temp_id) + temp_id += 1 + graph.node(**draw_node(op)) + for o in op.outputs: + for arg in o.arguments: + var_dict[arg] = op.type + for e in op.inputs: + for arg in e.arguments: + if arg in var_dict: + graph.edge(**draw_edge(var_dict, op, e, arg)) + break # only plot the first block + + +def draw_graph(startup_program, main_program, **kwargs): + if "graph_attr" in kwargs: + GRAPH_STYLE.update(kwargs["graph_attr"]) + if "node_attr" in kwargs: + OP_STYLE.update(kwargs["node_attr"]) + if "edge_attr" in kwargs: + VAR_STYLE.update(kwargs["edge_attr"]) + + graph_id = unique_id() + filename = kwargs.get("filename") + if filename == None: + filename = str(graph_id) + ".gv" + g = Graph(name=str(graph_id), + filename=filename, + graph_attr=GRAPH_STYLE, + node_attr=OP_STYLE, + edge_attr=VAR_STYLE, + **kwargs) + + var_dict = {} + parse_graph(startup_program, g, var_dict) + parse_graph(main_program, g, var_dict) + + if filename != None: + g.save() + return g diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/nets.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/nets.py new file mode 100644 index 0000000000000000000000000000000000000000..abafb48d866bb9242c6e02b9f925dbf1860a3569 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/nets.py @@ -0,0 +1,593 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import six +from . import layers +from .data_feeder import check_variable_and_dtype, convert_dtype +from ..utils import deprecated + +__all__ = [ + "simple_img_conv_pool", + "sequence_conv_pool", + "glu", + "scaled_dot_product_attention", + "img_conv_group", +] + + +def simple_img_conv_pool(input, + num_filters, + filter_size, + pool_size, + pool_stride, + pool_padding=0, + pool_type='max', + global_pooling=False, + conv_stride=1, + conv_padding=0, + conv_dilation=1, + conv_groups=1, + param_attr=None, + bias_attr=None, + act=None, + use_cudnn=True): + r""" + :api_attr: Static Graph + + The simple_img_conv_pool api is composed of :ref:`api_fluid_layers_conv2d` and :ref:`api_fluid_layers_pool2d` . + + Args: + input (Variable): 4-D Tensor, shape is [N, C, H, W], data type can be float32 or float64. + num_filters(int): The number of filters. It is the same as the output channels. + filter_size (int|list|tuple): The filter size. If filter_size is a list or + tuple, it must contain two integers, (filter_size_H, filter_size_W). Otherwise, + the filter_size_H = filter_size_W = filter_size. + pool_size (int|list|tuple): The pooling size of pool2d layer. If pool_size + is a list or tuple, it must contain two integers, (pool_size_H, pool_size_W). + Otherwise, the pool_size_H = pool_size_W = pool_size. + pool_stride (int|list|tuple): The pooling stride of pool2d layer. If pool_stride + is a list or tuple, it must contain two integers, (pooling_stride_H, pooling_stride_W). + Otherwise, the pooling_stride_H = pooling_stride_W = pool_stride. + pool_padding (int|list|tuple): The padding of pool2d layer. If pool_padding is a list or + tuple, it must contain two integers, (pool_padding_H, pool_padding_W). + Otherwise, the pool_padding_H = pool_padding_W = pool_padding. Default 0. + pool_type (str): Pooling type can be :math:`max` for max-pooling or :math:`avg` for + average-pooling. Default :math:`max`. + global_pooling (bool): Whether to use the global pooling. If global_pooling = true, + pool_size and pool_padding while be ignored. Default False + conv_stride (int|list|tuple): The stride size of the conv2d Layer. If stride is a + list or tuple, it must contain two integers, (conv_stride_H, conv_stride_W). Otherwise, + the conv_stride_H = conv_stride_W = conv_stride. Default: conv_stride = 1. + conv_padding (int|list|tuple): The padding size of the conv2d Layer. If padding is + a list or tuple, it must contain two integers, (conv_padding_H, conv_padding_W). + Otherwise, the conv_padding_H = conv_padding_W = conv_padding. Default: conv_padding = 0. + conv_dilation (int|list|tuple): The dilation size of the conv2d Layer. If dilation is + a list or tuple, it must contain two integers, (conv_dilation_H, conv_dilation_W). + Otherwise, the conv_dilation_H = conv_dilation_W = conv_dilation. Default: conv_dilation = 1. + conv_groups (int): The groups number of the conv2d Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + param_attr (ParamAttr|None): The parameter attribute for learnable parameters/weights + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with :math:`Normal(0.0, std)`, + and the :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. + Default: None. + bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of conv2d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + act (str): Activation type for conv2d, if it is set to None, activation is not + appended. Default: None. + use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True + + Return: + 4-D Tensor, the result of input after conv2d and pool2d, with the same data type as :attr:`input` + + Return Type: + Variable + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + img = fluid.data(name='img', shape=[100, 1, 28, 28], dtype='float32') + conv_pool = fluid.nets.simple_img_conv_pool(input=img, + filter_size=5, + num_filters=20, + pool_size=2, + pool_stride=2, + act="relu") + """ + conv_out = layers.conv2d(input=input, + num_filters=num_filters, + filter_size=filter_size, + stride=conv_stride, + padding=conv_padding, + dilation=conv_dilation, + groups=conv_groups, + param_attr=param_attr, + bias_attr=bias_attr, + act=act, + use_cudnn=use_cudnn) + + pool_out = layers.pool2d(input=conv_out, + pool_size=pool_size, + pool_type=pool_type, + pool_stride=pool_stride, + pool_padding=pool_padding, + global_pooling=global_pooling, + use_cudnn=use_cudnn) + return pool_out + + +def img_conv_group(input, + conv_num_filter, + pool_size, + conv_padding=1, + conv_filter_size=3, + conv_act=None, + param_attr=None, + conv_with_batchnorm=False, + conv_batchnorm_drop_rate=0.0, + pool_stride=1, + pool_type="max", + use_cudnn=True): + """ + :api_attr: Static Graph + + The Image Convolution Group is composed of Convolution2d, BatchNorm, DropOut, + and Pool2D. According to the input arguments, img_conv_group will do serials of + computation for Input using Convolution2d, BatchNorm, DropOut, and pass the last + result to Pool2D. + + Args: + input (Variable): The input is 4-D Tensor with shape [N, C, H, W], the data type of input is float32 or float64. + conv_num_filter(list|tuple): Indicates the numbers of filter of this group. + pool_size (int|list|tuple): The pooling size of Pool2D Layer. If pool_size + is a list or tuple, it must contain two integers, (pool_size_height, pool_size_width). + Otherwise, the pool_size_height = pool_size_width = pool_size. + conv_padding (int|list|tuple): The padding size of the Conv2D Layer. If padding is + a list or tuple, its length must be equal to the length of conv_num_filter. + Otherwise the conv_padding of all Conv2D Layers are the same. Default 1. + conv_filter_size (int|list|tuple): The filter size. If filter_size is a list or + tuple, its length must be equal to the length of conv_num_filter. + Otherwise the conv_filter_size of all Conv2D Layers are the same. Default 3. + conv_act (str): Activation type for Conv2D Layer that is not followed by BatchNorm. + Default: None. + param_attr (ParamAttr): The parameters to the Conv2D Layer. Default: None + conv_with_batchnorm (bool|list): Indicates whether to use BatchNorm after Conv2D Layer. + If conv_with_batchnorm is a list, its length must be equal to the length of + conv_num_filter. Otherwise, conv_with_batchnorm indicates whether all the + Conv2D Layer follows a BatchNorm. Default False. + conv_batchnorm_drop_rate (float|list): Indicates the drop_rate of Dropout Layer + after BatchNorm. If conv_batchnorm_drop_rate is a list, its length must be + equal to the length of conv_num_filter. Otherwise, drop_rate of all Dropout + Layers is conv_batchnorm_drop_rate. Default 0.0. + pool_stride (int|list|tuple): The pooling stride of Pool2D layer. If pool_stride + is a list or tuple, it must contain two integers, (pooling_stride_H, + pooling_stride_W). Otherwise, the pooling_stride_H = pooling_stride_W = pool_stride. + Default 1. + pool_type (str): Pooling type can be :math:`max` for max-pooling and :math:`avg` for + average-pooling. Default :math:`max`. + use_cudnn (bool): Use cudnn kernel or not, it is valid only when the cudnn + library is installed. Default: True + + Return: + A Variable holding Tensor representing the final result after serial computation using Convolution2d, + BatchNorm, DropOut, and Pool2D, whose data type is the same with input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + img = fluid.data(name='img', shape=[None, 1, 28, 28], dtype='float32') + conv_pool = fluid.nets.img_conv_group(input=img, + conv_padding=1, + conv_num_filter=[3, 3], + conv_filter_size=3, + conv_act="relu", + pool_size=2, + pool_stride=2) + """ + tmp = input + assert isinstance(conv_num_filter, list) or \ + isinstance(conv_num_filter, tuple) + + def __extend_list__(obj): + if not hasattr(obj, '__len__'): + return [obj] * len(conv_num_filter) + else: + assert len(obj) == len(conv_num_filter) + return obj + + conv_padding = __extend_list__(conv_padding) + conv_filter_size = __extend_list__(conv_filter_size) + param_attr = __extend_list__(param_attr) + conv_with_batchnorm = __extend_list__(conv_with_batchnorm) + conv_batchnorm_drop_rate = __extend_list__(conv_batchnorm_drop_rate) + + for i in six.moves.range(len(conv_num_filter)): + local_conv_act = conv_act + if conv_with_batchnorm[i]: + local_conv_act = None + + tmp = layers.conv2d(input=tmp, + num_filters=conv_num_filter[i], + filter_size=conv_filter_size[i], + padding=conv_padding[i], + param_attr=param_attr[i], + act=local_conv_act, + use_cudnn=use_cudnn) + + if conv_with_batchnorm[i]: + tmp = layers.batch_norm(input=tmp, act=conv_act) + drop_rate = conv_batchnorm_drop_rate[i] + if abs(drop_rate) > 1e-5: + tmp = layers.dropout(x=tmp, dropout_prob=drop_rate) + + pool_out = layers.pool2d(input=tmp, + pool_size=pool_size, + pool_type=pool_type, + pool_stride=pool_stride, + use_cudnn=use_cudnn) + return pool_out + + +def sequence_conv_pool(input, + num_filters, + filter_size, + param_attr=None, + act="sigmoid", + pool_type="max", + bias_attr=None): + """ + :api_attr: Static Graph + + **This api takes input as an LoDTensor. If input is a Tensor, please use** + :ref:`api_fluid_nets_simple_img_conv_pool` **instead** + + The sequence_conv_pool is composed of :ref:`api_fluid_layers_sequence_conv` + and :ref:`api_fluid_layers_sequence_pool` . + + Args: + input (Variable): 2-D LoDTensor, the input of sequence_conv, + which supports variable-time length input sequence. + The underlying of input is a matrix with shape + (T, N), where T is the total time steps in this mini-batch and N is + the input_hidden_size. The data type is float32 or float64. + num_filters(int): The number of filter. + filter_size (int): The filter size. + param_attr (ParamAttr): The parameters of the sequence_conv Layer. Default: None. + act (str|None): Activation type for Sequence_conv Layer. + If set to None, no activation will be applied. Default: "sigmoid". + pool_type (str): Pooling type can be :math:`max` for max-pooling, :math:`average` for + average-pooling, :math:`sum` for sum-pooling, :math:`sqrt` for sqrt-pooling. + Default :math:`max`. + bias_attr (ParamAttr|bool|None): The parameter attribute for the bias of sequence_conv. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, sequence_conv + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + + Returns: + The final result after sequence_conv and sequence_pool. + It is a 2-D Tensor, with the same data type as :attr:`input` + + Return Type: + Variable + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + input_dim = 100 #len(word_dict) + emb_dim = 128 + hid_dim = 512 + data = fluid.data(name="words", shape=[None, 1], dtype="int64", lod_level=1) + emb = fluid.layers.embedding(input=data, size=[input_dim, emb_dim], is_sparse=True) + seq_conv = fluid.nets.sequence_conv_pool(input=emb, + num_filters=hid_dim, + filter_size=3, + act="tanh", + pool_type="sqrt") + """ + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'input') + conv_out = layers.sequence_conv(input=input, + num_filters=num_filters, + filter_size=filter_size, + param_attr=param_attr, + bias_attr=bias_attr, + act=act) + + pool_out = layers.sequence_pool(input=conv_out, pool_type=pool_type) + return pool_out + + +@deprecated(since="2.0.0", update_to="paddle.nn.functional.glu") +def glu(input, dim=-1): + r""" + :api_attr: Static Graph + + The Gated Linear Units(GLU) composed by :ref:`api_fluid_layers_split` , + :ref:`api_fluid_layers_sigmoid` and :ref:`api_fluid_layers_elementwise_mul` . + Specifically, GLU will plit the input into two equal-sized parts, + :math:`a` and :math:`b`, along the given dimension and then compute as + following: + + .. math:: + + {GLU}(a, b)= a \otimes \sigma(b) + + Refer to `Language Modeling with Gated Convolutional Networks + `_. + + Args: + input (Variable): The input variable which is a Tensor or LoDTensor. + The supported data types include float32, float64 + and float16 (only for GPU). + dim (int, optional): The dimension along which to split. If :math:`dim < 0`, the + dimension to split along is :math:`rank(input) + dim`. Default -1. + + Returns: + Variable: Variable with half the size and same data type of input. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + data = fluid.data( + name="words", shape=[-1, 6, 3, 9], dtype="float32") + # shape of output: [-1, 3, 3, 9] + output = fluid.nets.glu(input=data, dim=1) + """ + check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], + "glu") + a, b = layers.split(input, num_or_sections=2, dim=dim) + act_b = layers.sigmoid(x=b) + out = layers.elementwise_mul(x=a, y=act_b) + return out + + +def scaled_dot_product_attention(queries, + keys, + values, + num_heads=1, + dropout_rate=0.): + r""" + :api_attr: Static Graph + + This interface Multi-Head Attention using scaled dot product. + Attention mechanism can be seen as mapping a query and a set of key-value + pairs to an output. Multi-Head Attention performs attention using multi-head + parallel, and the inputs of attention would be transformed by linear projection. + The formula is as follows: + + .. math:: + + MultiHead(Q, K, V ) & = Concat(head_1, ..., head_h) + + where \ head_i & = Attention(QW_i^Q , KW_i^K , VW_i^V ) + + Attention(Q, K, V) & = softmax (\\frac{QK^\mathrm{T}}{\sqrt{d_k}}) V + + For more details, please refer to `Attention Is All You Need + `_ . + + Note that the implementation is adapted to batch, and all matrix multiplication + in :math:`Attention(Q, K, V)` is batched matrix multiplication. Refer to + :ref:`api_fluid_layers_matmul` . + + Args: + queries (Variable): A 3-D Tensor with shape :math:`[N, L_q, d_k \\times h]` , + where :math:`N` stands for batch size, :math:`L_q` for the sequence length + of query, :math:`d_k \\times h` for the feature size of query, :math:`h` for + head number. The data type should be float32 or float64. + keys (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_k \\times h]` , + where :math:`N` stands for batch size, :math:`L_k` for the sequence length + of key, :math:`d_k \\times h` for the feature size of key, :math:`h` for head + number. The data type should be the same as ``queries`` . + values (Variable): A 3-D Tensor with shape :math:`[N, L_k, d_v \\times h]` , + where :math:`N` stands for batch size, :math:`L_k` for the sequence length + of key, :math:`d_v \\times h` for the feature size of value, :math:`h` for head + number. The data type should be the same as ``queries`` . + num_heads (int, optional): Indicate the number of head. If the number + is 1, linear projection would not be performed on inputs. Default: 1. + dropout_rate (float, optional): The rate to drop the attention weight. + Default: 0.0, which means no dropout. + + Returns: + Variable: A 3-D Tensor with shape :math:`[N, L_q, d_v \\times h]` , \ + where :math:`N` stands for batch size, :math:`L_q` for the sequence \ + length of query, :math:`d_v \\times h` for the feature size of value. \ + It has the same data type with inputs, representing the output of \ + Multi-Head Attention. + + Raises: + TypeError: The dtype of inputs keys, values and queries should be the same. + ValueError: Inputs queries, keys and values should all be 3-D tensors. + ValueError: The hidden size of queries and keys should be the same. + ValueError: The max sequence length in value batch and in key batch should be the same. + ValueError: he hidden size of keys must be divisible by the number of attention heads. + ValueError: he hidden size of values must be divisible by the number of attention heads. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle + paddle.enable_static() + + queries = fluid.data(name="queries", shape=[3, 5, 9], dtype="float32") + keys = fluid.data(name="keys", shape=[3, 6, 9], dtype="float32") + values = fluid.data(name="values", shape=[3, 6, 10], dtype="float32") + contexts = fluid.nets.scaled_dot_product_attention(queries, keys, values) + contexts.shape # [3, 5, 10] + """ + check_variable_and_dtype(queries, 'queries', ['float32', 'float64'], + "scaled_dot_product_attention") + check_variable_and_dtype(keys, 'keys', ['float32', 'float64'], + "scaled_dot_product_attention") + check_variable_and_dtype(values, 'values', ['float32', 'float64'], + "scaled_dot_product_attention") + + if not (queries.dtype == keys.dtype == values.dtype): + raise TypeError( + "The dtype of keys, values and queries should be the same." + "But received queries.dtype = %s, " + " keys.dtype = %s, values.dtype) = %s." % + (convert_dtype(queries.dtype), convert_dtype( + keys.dtype), convert_dtype(values.dtype))) + + if not (len(queries.shape) == len(keys.shape) == len(values.shape) == 3): + raise ValueError( + "Inputs queries, keys and values should all be 3-D tensors." + "But received len(queries.shape) = %d, " + "len(keys.shape) = %d, len(values.shape) = %d." % + (len(queries.shape), len(keys.shape), len(values.shape))) + + if queries.shape[-1] != keys.shape[-1]: + raise ValueError( + "The hidden size of queries and keys should be the same." + "But received queries' hidden size = %d and keys' hidden size = %d." + % (queries.shape[-1], keys.shape[-1])) + if keys.shape[-2] != values.shape[-2]: + raise ValueError( + "The max sequence length in value batch and in key batch " + "should be the same. But received max sequence length in value batch " + "= %d, in key batch = %d." % (values.shape[-2], keys.shape[-2])) + if keys.shape[-1] % num_heads != 0: + raise ValueError("The hidden size of keys (%d) must be divisible " + "by the number of attention heads (%d)." % + (keys.shape[-1], num_heads)) + if values.shape[-1] % num_heads != 0: + raise ValueError("The hidden size of values (%d) must be divisible " + "by the number of attention heads (%d)." % + (values.shape[-1], num_heads)) + + def __compute_qkv(queries, keys, values, num_heads): + """ + Add linear projection to queries, keys, and values. + + Args: + queries(Tensor): a 3-D input Tensor. + keys(Tensor): a 3-D input Tensor. + values(Tensor): a 3-D input Tensor. + num_heads(int): The number of heads. Linearly project the inputs + ONLY when num_heads > 1. + + Returns: + Tensor: linearly projected output Tensors: queries', keys' and + values'. They have the same shapes with queries, keys and + values. + """ + + if num_heads == 1: + return queries, keys, values + + q = layers.fc(input=queries, size=queries.shape[-1], num_flatten_dims=2) + k = layers.fc(input=keys, size=keys.shape[-1], num_flatten_dims=2) + v = layers.fc(input=values, size=values.shape[-1], num_flatten_dims=2) + return q, k, v + + def __split_heads(x, num_heads): + """ + Reshape the last dimension of input tensor x so that it becomes two + dimensions. + + Args: + x(Tensor): a 3-D input Tensor. + num_heads(int): The number of heads. + + Returns: + Tensor: a Tensor with shape [..., n, m/num_heads], where m is size + of the last dimension of x. + """ + if num_heads == 1: + return x + + hidden_size = x.shape[-1] + # reshape the 3-D input: [batch_size, max_sequence_length, hidden_dim] + # into a 4-D output: + # [batch_size, max_sequence_length, num_heads, hidden_size_per_head]. + reshaped = layers.reshape(x=x, + shape=list(x.shape[:-1]) + + [num_heads, hidden_size // num_heads]) + + # permute the dimensions into: + # [batch_size, num_heads, max_sequence_len, hidden_size_per_head] + return layers.transpose(x=reshaped, perm=[0, 2, 1, 3]) + + def __combine_heads(x): + """ + Reshape the last two dimensions of input tensor x so that it becomes + one dimension. + + Args: + x(Tensor): a 4-D input Tensor with shape + [bs, num_heads, max_sequence_length, hidden_dim]. + + Returns: + Tensor: a Tensor with shape + [bs, max_sequence_length, num_heads * hidden_dim]. + """ + + if len(x.shape) == 3: return x + if len(x.shape) != 4: + raise ValueError("Input(x) should be a 4-D Tensor.") + + trans_x = layers.transpose(x, perm=[0, 2, 1, 3]) + return layers.reshape(x=trans_x, + shape=list( + map(int, [ + trans_x.shape[0], trans_x.shape[1], + trans_x.shape[2] * trans_x.shape[3] + ]))) + + q, k, v = __compute_qkv(queries, keys, values, num_heads) + + q = __split_heads(q, num_heads) + k = __split_heads(k, num_heads) + v = __split_heads(v, num_heads) + + key_dim_per_head = keys.shape[-1] // num_heads + scaled_q = layers.scale(x=q, scale=key_dim_per_head**-0.5) + product = layers.matmul(x=scaled_q, y=k, transpose_y=True) + + weights = layers.reshape(x=layers.reshape(x=product, + shape=[-1, product.shape[-1]], + act="softmax"), + shape=product.shape) + if dropout_rate: + weights = layers.dropout(weights, + dropout_prob=dropout_rate, + is_test=False) + ctx_multiheads = layers.matmul(weights, v) + return __combine_heads(ctx_multiheads) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/op.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/op.py new file mode 100644 index 0000000000000000000000000000000000000000..ca92ac44128953cf2839c2159c7df53a309ac252 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/op.py @@ -0,0 +1,334 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import numpy as np +import six + +import paddle.fluid.core as core +import paddle.fluid.proto.framework_pb2 as framework_pb2 + + +def get_all_op_protos(): + """ + Get all registered op proto from PaddlePaddle C++ end. + :return: A list of registered OpProto. + """ + protostrs = core.get_all_op_protos() + ret_values = [] + for pbstr in protostrs: + op_proto = framework_pb2.OpProto.FromString(six.binary_type(pbstr)) + ret_values.append(op_proto) + return ret_values + + +def is_str(s): + return isinstance(s, six.string_types) + + +class OpDescCreationMethod(object): + """ + Convert the user's input(only keyword arguments are supported) to OpDesc + based on the OpProto. + + :param op_proto: The OpProto object. + :type op_proto: op_proto_pb2.OpProto + """ + + def __init__(self, op_proto): + if not isinstance(op_proto, framework_pb2.OpProto): + raise TypeError( + "Type of op_proto should be OpProto in PaddlePaddle.") + self.__op_proto__ = op_proto + self.__extra_attrs__ = core.get_op_extra_attrs(op_proto.type) + + def __call__(self, *args, **kwargs): + """ + Convert user's input to OpDesc. Only keyword arguments are supported. + :return: The OpDesc based on user input. + :rtype: op_desc_pb2.OpDesc + """ + if len(args) != 0: + raise ValueError("Only keyword arguments are supported.") + op_desc = framework_pb2.OpDesc() + for input_parameter in self.__op_proto__.inputs: + input_arguments = kwargs.get(input_parameter.name, []) + if is_str(input_arguments): + input_arguments = [input_arguments] + + if not input_parameter.duplicable and len(input_arguments) > 1: + raise ValueError( + "Input %s expects only one input, but %d are given." % + (input_parameter.name, len(input_arguments))) + + ipt = op_desc.inputs.add() + ipt.parameter = input_parameter.name + ipt.arguments.extend(input_arguments) + + for output_parameter in self.__op_proto__.outputs: + output_arguments = kwargs.get(output_parameter.name, []) + if is_str(output_arguments): + output_arguments = [output_arguments] + + if not output_parameter.duplicable and len(output_arguments) > 1: + raise ValueError( + "Output %s expects only one output, but %d are given." % + (output_parameter.name, len(output_arguments))) + + out = op_desc.outputs.add() + out.parameter = output_parameter.name + out.arguments.extend(output_arguments) + + # Types + op_desc.type = self.__op_proto__.type + + # Attrs + for attr in self.__op_proto__.attrs: + if attr.generated: + continue + user_defined_attr = kwargs.get(attr.name, None) + if user_defined_attr is not None: + new_attr = op_desc.attrs.add() + new_attr.name = attr.name + new_attr.type = attr.type + if isinstance(user_defined_attr, np.ndarray): + user_defined_attr = user_defined_attr.tolist() + if attr.type == framework_pb2.INT: + new_attr.i = user_defined_attr + elif attr.type == framework_pb2.FLOAT: + new_attr.f = user_defined_attr + elif attr.type == framework_pb2.LONG: + new_attr.l = user_defined_attr + elif attr.type == framework_pb2.STRING: + new_attr.s = user_defined_attr + elif attr.type == framework_pb2.BOOLEAN: + new_attr.b = user_defined_attr + elif attr.type == framework_pb2.INTS: + new_attr.ints.extend(user_defined_attr) + elif attr.type == framework_pb2.FLOATS: + new_attr.floats.extend(user_defined_attr) + elif attr.type == framework_pb2.STRINGS: + new_attr.strings.extend(user_defined_attr) + elif attr.type == framework_pb2.BOOLEANS: + new_attr.bools.extend(user_defined_attr) + elif attr.type == framework_pb2.LONGS: + new_attr.longs.extend(user_defined_attr) + elif attr.type == framework_pb2.FLOAT64: + new_attr.float64 = user_defined_attr + else: + raise NotImplementedError( + "A not supported attribute type: %s." % + (str(attr.type))) + for attr_name, defalut_val in self.__extra_attrs__.items(): + user_defined_attr = kwargs.get(attr_name, None) + if user_defined_attr is not None: + attr_type = int( + core.get_attrtibute_type(op_desc.type, attr_name)) + new_attr = op_desc.attrs.add() + new_attr.name = attr_name + new_attr.type = attr_type + if isinstance(user_defined_attr, np.ndarray): + user_defined_attr = user_defined_attr.tolist() + if attr_type == framework_pb2.INT: + new_attr.i = user_defined_attr + elif attr_type == framework_pb2.FLOAT: + new_attr.f = user_defined_attr + elif attr_type == framework_pb2.LONG: + new_attr.l = user_defined_attr + elif attr_type == framework_pb2.STRING: + new_attr.s = user_defined_attr + elif attr_type == framework_pb2.BOOLEAN: + new_attr.b = user_defined_attr + elif attr_type == framework_pb2.INTS: + new_attr.ints.extend(user_defined_attr) + elif attr_type == framework_pb2.FLOATS: + new_attr.floats.extend(user_defined_attr) + elif attr_type == framework_pb2.STRINGS: + new_attr.strings.extend(user_defined_attr) + elif attr_type == framework_pb2.BOOLEANS: + new_attr.bools.extend(user_defined_attr) + elif attr_type == framework_pb2.LONGS: + new_attr.longs.extend(user_defined_attr) + else: + raise NotImplementedError( + "A not supported attribute type: %s." % + (str(attr_type))) + + return op_desc + + @staticmethod + def any_is_true(generator): + """ + Reduce a boolean array to a single boolean parameter. If any element in + the array is True, this function will return True, otherwise False. + """ + for flag in generator: + if flag: + return True + return False + + +class OpInfo(object): + + def __init__(self, name, method, inputs, outputs, attrs, extra_attrs): + self.name = name + self.method = method + self.inputs = inputs + self.outputs = outputs + self.attrs = attrs + self.extra_attrs = extra_attrs + + +def create_op_creation_method(op_proto): + """ + Generate op creation method for an OpProto. + """ + method = OpDescCreationMethod(op_proto) + + def __impl__(*args, **kwargs): + opdesc = method(*args, **kwargs) + return core.Operator.create(opdesc.SerializeToString()) + + extra_attrs_map = core.get_op_extra_attrs(op_proto.type) + + return OpInfo(method=__impl__, + name=op_proto.type, + inputs=[(var.name, var.duplicable) + for var in op_proto.inputs], + outputs=[(var.name, var.duplicable) + for var in op_proto.outputs], + attrs=[attr.name for attr in op_proto.attrs], + extra_attrs=[item for item in extra_attrs_map.keys()]) + + +class OperatorFactory(object): + + def __init__(self): + self.op_methods = dict() + + for op_proto in get_all_op_protos(): + method = create_op_creation_method(op_proto) + self.op_methods[method.name] = method + + def __call__(self, *args, **kwargs): + if "type" in kwargs: + if len(args) != 0: + raise ValueError( + "Except the argument \"type\"," + "all of the other arguments should be keyword arguments.") + t = kwargs.pop("type") + else: + if len(args) != 1: + raise ValueError( + "Except the argument \"type\"," + "all of the other arguments should be keyword arguments.") + t = args[0] + + return self.get_op_info(t).method(**kwargs) + + def types(self): + return list(self.op_methods.keys()) + + def get_op_info(self, t): + if t not in self.op_methods: + raise ValueError("The operator: %s is not registered." % t) + return self.op_methods.get(t) + + def get_op_input_names(self, type): + return [x[0] for x in self.get_op_info(type).inputs] + + def get_op_inputs(self, type): + return self.get_op_info(type).inputs + + def get_op_output_names(self, type): + return [x[0] for x in self.get_op_info(type).outputs] + + def get_op_outputs(self, type): + return self.get_op_info(type).outputs + + def get_op_attr_names(self, type): + return self.get_op_info(type).attrs + + def get_op_extra_attr_names(self, type): + return self.get_op_info(type).extra_attrs + + +class __RecurrentOp__(object): + __proto__ = None + type = "recurrent" + + def __init__(self): + # cache recurrent_op's proto + if self.__proto__ is None: + for op_proto in get_all_op_protos(): + if op_proto.type == self.type: + self.__proto__ = op_proto + + def __call__(self, *args, **kwargs): + if self.type not in args and "type" not in kwargs: + kwargs["type"] = self.type + # create proto + create_method = OpDescCreationMethod(self.__proto__) + proto = create_method(*args, **kwargs) + # create rnnop + return core.RecurrentOp.create(proto.SerializeToString()) + + +class __DynamicRecurrentOp__(object): + __proto__ = None + type = "dynamic_recurrent" + + def __init__(self): + # cache recurrent_op's proto + if self.__proto__ is None: + for op_proto in get_all_op_protos(): + if op_proto.type == self.type: + self.__proto__ = op_proto + + def __call__(self, *args, **kwargs): + if self.type not in args and "type" not in kwargs: + kwargs["type"] = self.type + # create proto + create_method = OpDescCreationMethod(self.__proto__) + proto = create_method(*args, **kwargs) + # create rnnop + return core.DynamicRecurrentOp.create(proto.SerializeToString()) + + +class __CondOp__(object): + __proto__ = None + type = "cond" + + def __init__(self): + # cache recurrent_op's proto + if self.__proto__ is None: + for op_proto in get_all_op_protos(): + if op_proto.type == self.type: + self.__proto__ = op_proto + + def __call__(self, *args, **kwargs): + if self.type not in args and "type" not in kwargs: + kwargs["type"] = self.type + # create proto + create_method = OpDescCreationMethod(self.__proto__) + proto = create_method(*args, **kwargs) + # create condop + return core.CondOp.create(proto.SerializeToString()) + + +Operator = OperatorFactory() # The default global factory +RecurrentOp = __RecurrentOp__() +DynamicRecurrentOp = __DynamicRecurrentOp__() +CondOp = __CondOp__() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c53872c0e54da9c0c741879f1c33d6b083a40306 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/optimizer.py @@ -0,0 +1,7331 @@ +# 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. + +from __future__ import print_function + +import numpy as np +import six +import os +import logging +from collections import defaultdict + +import paddle +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table +from paddle.fluid.framework import Program, Variable, Parameter, name_scope, default_main_program, default_startup_program, device_guard + +from . import framework +from . import layers +from . import unique_name +from .backward import append_backward, _some_in_set_, _append_grad_suffix_, _get_no_grad_set_name +from .clip import GradientClipBase, GradientClipByNorm, error_clip_callback, append_gradient_clip_ops, ClipGradByGlobalNorm +from .framework import program_guard +from .initializer import Constant +from .layer_helper import LayerHelper +from .layers import ops +from .dygraph import base as imperative_base +from .dygraph import no_grad +from .dygraph.learning_rate_scheduler import LearningRateDecay, _LearningRateEpochDecay +from paddle.fluid import core +from paddle.fluid.layers import tensor +from functools import reduce +from functools import cmp_to_key +from .wrapped_decorator import signature_safe_contextmanager +from .. import compat as cpt +import warnings +from paddle import _C_ops, _legacy_C_ops +from ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode, _current_expected_place + +__all__ = [ + 'SGD', 'Momentum', 'Adagrad', 'Adam', 'Adamax', 'Dpsgd', 'DecayedAdagrad', + 'Ftrl', 'SGDOptimizer', 'MomentumOptimizer', 'AdagradOptimizer', + 'AdamOptimizer', 'AdamaxOptimizer', 'DpsgdOptimizer', + 'DecayedAdagradOptimizer', 'RMSPropOptimizer', 'FtrlOptimizer', 'Adadelta', + 'AdadeltaOptimizer', 'ModelAverage', 'LarsMomentum', + 'LarsMomentumOptimizer', 'LambOptimizer', 'ExponentialMovingAverage', + 'PipelineOptimizer', 'LookaheadOptimizer', 'RecomputeOptimizer' +] + + +class Optimizer(object): + """Optimizer Base class. + + Define the common interface of an optimizer. + User should not use this class directly, + but need to use one of it's implementation. + """ + + @imperative_base.no_grad + def __init__(self, + learning_rate, + parameter_list=None, + regularization=None, + grad_clip=None, + flatten_param_grads=False, + align_size=-1, + name=None): + """ + Args: + flatten_param_grads (bool, optional): Whether to flatten all the parameters and grads. + If true, the parameters and gradients will be coalesce to contiguous mempry, + and the grad_clip ops / optimizer ops will be fuse to one operator. + """ + # Because of the loop import, so place it in the function body + from paddle.optimizer.lr import LRScheduler + self._parameter_list = list( + parameter_list) if parameter_list is not None else None + self._name = name + if framework._non_static_mode(): + if not isinstance(learning_rate, + (float, LearningRateDecay, LRScheduler)): + raise TypeError( + "learning rate should be float or LRScheduler, got %s here" + % type(learning_rate)) + if self._parameter_list is None: + raise AttributeError( + "parameter_list argument given to the Optimizer should not be None in dygraph mode." + ) + if regularization is not None: + for param in self._parameter_list: + if param.regularizer is not None: + logging.info( + "If regularizer of a Parameter has been set by 'fluid.ParamAttr' or 'fluid.WeightNormParamAttr' already. " + "The Regularization[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!" + % regularization.__str__()) + break + else: + if not isinstance(learning_rate, + (float, framework.Variable, LRScheduler)): + raise TypeError( + "learning rate should be float or LRScheduler, got %s here" + % type(learning_rate)) + + if grad_clip is not None: + if not isinstance(grad_clip, GradientClipBase): + raise TypeError( + "'grad_clip' should be an instance of GradientClipBase's derived class" + ) + self.regularization = regularization + self._grad_clip = grad_clip + self._learning_rate = learning_rate + self._flatten_param_grads = flatten_param_grads + self._align_size = align_size + + self._dtype = None + # Infer the dtype form parameter + if self._parameter_list: + self._dtype = self._parameter_list[0].dtype + + # each program should have a independent learning rate + # program -> Variable(learning_rate) + self._learning_rate_map = dict() + if isinstance(self._learning_rate, framework.Variable): + self._learning_rate_map[ + framework.default_main_program()] = self._learning_rate + # Dictionary of accumulators. Some optimizer subclasses need to + # allocate and manage extra variables associated with the parameters + # to train. These variables are called accumulators. + # {accum_name : { paramter_name : accumulator_for_parameter, ...}, ...} + self._accumulators = defaultdict(lambda: dict()) + # global_accumulator dict, {accum_name : acc_variable, ...} + self._global_accumulators = {} + self.helper = LayerHelper(self.__class__.__name__) + self._opti_name_list = [] + self._accumulators_holder = {} + self._param_device_map = dict() + # NOTE(zhiqiu): sometimes we want to add some variables(Tenosr) to the optimizer for a specific optimization, + # for example, we want to pass 'found_inf' to adam optimizer so it can skip update when found_inf is True. + # And these variables should not be the parameters of Optimizer's construnctor (because not commonly used). + # Use _auxiliary_vars together with _set_auxiliary_var/_get_auxiliary_var to achieve that. + self._auxiliary_vars = dict() + + @framework.dygraph_only + def state_dict(self): + ''' + Get state dict information from optimizer. It contain all the variable used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. If LearningRateDecay have been used, global_step will be include in state dict. + If the optimizer never be called(minimize function), the state_dict is empty. + + Args: None + Return: + state_dict(dict) : dict contains all the variable used by optimizer + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + + adam = fluid.optimizer.Adam(0.001, parameter_list=emb.parameters()) + state_dict = adam.state_dict() + + ''' + from paddle.optimizer.lr import LRScheduler + state_dict = {} + for k, v in self._accumulators.items(): + for para_name, var_tmp in v.items(): + state_dict[var_tmp.name] = var_tmp + for k, v in self._global_accumulators.items(): + state_dict[v.name] = v + # global step if use lr decay + if isinstance(self._learning_rate, LRScheduler): + state_dict["LR_Scheduler"] = self._learning_rate.state_dict() + return state_dict + if isinstance(self._learning_rate, LearningRateDecay): + state_dict["LR_Scheduler"] = self._learning_rate.state_dict() + + if not isinstance(self._learning_rate, _LearningRateEpochDecay): + var_tmp = None + var_temp = framework._varbase_creator(None, + name='global_step', + dtype='int32') + + tensor.fill_constant([1], + "int32", + self._learning_rate.step_num, + out=var_temp) + + state_dict['global_step'] = var_temp + return state_dict + + @framework.dygraph_only + def set_state_dict(self, state_dict): + ''' + Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LearningRateDecay have been used, global_step will be changed. + + Args: + state_dict(dict) : Dict contains all the Variable needed by optimizer + Return: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.disable_static() + + emb = paddle.nn.Embedding(10, 10) + + state_dict = emb.state_dict() + fluid.save_dygraph(state_dict, "paddle_dy") + + scheduler = paddle.optimizer.lr.NoamDecay( + d_model=0.01, warmup_steps=100, verbose=True) + adam = paddle.optimizer.Adam( + learning_rate=scheduler, + parameters=emb.parameters()) + state_dict = adam.state_dict() + fluid.save_dygraph(state_dict, "paddle_dy") + + para_state_dict, opti_state_dict = fluid.load_dygraph("paddle_dy") + ''' + from paddle.optimizer.lr import LRScheduler + if isinstance(self._learning_rate, LRScheduler): + self._learning_rate.set_dict(state_dict["LR_Scheduler"]) + + if isinstance(self._learning_rate, LearningRateDecay): + self._learning_rate.set_dict(state_dict["LR_Scheduler"]) + + if not isinstance(self._learning_rate, _LearningRateEpochDecay): + assert 'global_step' in state_dict, \ + 'Global step not in state dict, Dygraph use LearningRateDecay, global_step must in state_dict' + global_step = state_dict['global_step'] + + if isinstance(global_step, Variable): + step_np = global_step + step_np = np.array(step_np.value().get_tensor()) + assert step_np.shape == (1,), \ + "global step shape is (1,), the shape is {}".format( step_np.shape ) + + self._learning_rate.step_num = int(step_np[0]) + elif isinstance(global_step, np.ndarray): + assert global_step.shape == (1,), \ + "global step shape is (1,), the shape is {}".format( global_step.shape ) + self._learning_rate.step_num = global_step[0] + else: + raise RuntimeError( + "Type not supprt, value in state dict must be [VarBase, Variable, numpy], the type is ", + type(global_step)) + + def _load_state_para(state_dict, param): + var = param.value() + tensor = var.get_tensor() + model_np = np.array(tensor) + load_para = state_dict[param.name] + if isinstance(load_para, Variable): + load_para_np = load_para.numpy() + elif isinstance(load_para, core.VarBase): + load_para_np = load_para.numpy() + elif isinstance(load_para, np.ndarray): + load_para_np = load_para + else: + raise RuntimeError("State dict type {} not supprt".format( + str(type(load_para)))) + + assert model_np.shape == load_para_np.shape, \ + "Parameter shape not match, Dygraph Parameter [ {} ] need tensor with shape {} but load tensor with shape {}".format( + param.name, model_np.shape, load_para_np.shape) + + assert model_np.dtype == load_para_np.dtype, \ + "Parameter dtype not match, Dygraph Parameter [ {} ] need tensor with dtype {} but load tensor with dtype {}".format( + param.name, model_np.dtype, load_para_np.dtype) + + tensor.set(load_para_np, framework._current_expected_place()) + + self._accumulators_holder = state_dict + for k, v in self._accumulators.items(): + for para_name, var_tmp in v.items(): + assert var_tmp.name in state_dict, \ + "optimizer variable {} not found".format( var_tmp.name ) + _load_state_para(state_dict, var_tmp) + + for k, v in self._global_accumulators.items(): + assert v.name in state_dict, \ + "optimizer variable {} not found".format( v.name ) + _load_state_para(state_dict, v) + + # [aliases] Compatible with old method names + set_dict = set_state_dict + + def get_opti_var_name_list(self): + return self._opti_name_list + + def _set_auxiliary_var(self, key, val): + self._auxiliary_vars[key] = val + + def _get_auxiliary_var(self, key): + if key in self._auxiliary_vars: + return self._auxiliary_vars[key] + else: + return None + + def _create_global_learning_rate(self): + from paddle.optimizer.lr import LRScheduler + if isinstance(self._learning_rate, LRScheduler): + lr_var = self._global_learning_rate() + # only create global lr_var once + if not isinstance(lr_var, framework.Variable): + lr_name = unique_name.generate('learning_rate') + self._learning_rate._var_name = lr_name + lr_var = self.helper.create_global_variable( + name=lr_name, + shape=[1], + persistable=True, + stop_gradient=True, + dtype='float32' if self._dtype is None else self._dtype) + main_prog = framework.default_main_program() + main_prog.lr_sheduler = self._learning_rate + main_prog.lr_var = lr_var + self._learning_rate_map[ + framework.default_main_program()] = lr_var + + lr_value = float(self._learning_rate()) + self.helper.set_variable_initializer( + lr_var, initializer=Constant(value=lr_value)) + return + + if imperative_base.enabled(): + # create learning rate Variable + if isinstance(self._learning_rate, float): + lr = self._global_learning_rate() + + if isinstance(lr, framework.Variable): + return + else: + self._learning_rate_map[framework.default_main_program( + )] = layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(self._learning_rate), + dtype='float32' if self._dtype is None else self._dtype, + persistable=True) + # get learning rate Variable from LearningRateDecay + elif isinstance(self._learning_rate, LearningRateDecay): + self._learning_rate_map[ + framework.default_main_program()] = self._learning_rate() + else: + raise TypeError( + "optimizer's learning rate must be float or LearningRateDecay" + ) + else: + lr = self._global_learning_rate() + + if isinstance(lr, framework.Variable): + return + else: + if not isinstance(self._learning_rate, float): + raise TypeError( + "learning rate variable is create outside optimizer," + "can not create new learning rate variable for new program" + ) + + # create learning rate in the current main program + self._learning_rate_map[ + framework.default_main_program()] = layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(self._learning_rate), + dtype='float32' if self._dtype is None else self._dtype, + persistable=True) + + @framework.dygraph_only + def set_lr(self, value): + """ + :api_attr: imperative + + Set the value of the learning rate manually in the optimizer. If the optimizer use LearningRateDecay, + this API cannot be invoked, because it will lead to conflict. + + Args: + value (float|Variable): the value of learning rate + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + with fluid.dygraph.guard(): + linear = fluid.dygraph.nn.Linear(10, 10) + + adam = fluid.optimizer.Adam(0.1, parameter_list=linear.parameters()) + + # set learning rate manually by python float value + lr_list = [0.2, 0.3, 0.4, 0.5, 0.6] + for i in range(5): + adam.set_lr(lr_list[i]) + lr = adam.current_step_lr() + print("current lr is {}".format(lr)) + # Print: + # current lr is 0.2 + # current lr is 0.3 + # current lr is 0.4 + # current lr is 0.5 + # current lr is 0.6 + + + # set learning rate manually by framework Variable + lr_var = fluid.layers.create_global_var( + shape=[1], value=0.7, dtype='float32') + adam.set_lr(lr_var) + lr = adam.current_step_lr() + print("current lr is {}".format(lr)) + # Print: + # current lr is 0.7 + + + + """ + if not isinstance(value, (framework.Variable, float)): + raise TypeError( + "The type of 'value' in optimizer.set_lr must be (float, Variable), but received %s." + % (type(value))) + if isinstance(self._learning_rate, LearningRateDecay): + raise RuntimeError( + "optimizer's learning rate can't be LearningRateDecay when invoke this API, because this will lead to conflict." + ) + if isinstance(value, float): + self._learning_rate = value + current_lr = self._global_learning_rate() + if current_lr is not None: + if in_dygraph_mode(): + place = _current_expected_place() + _C_ops.full_(current_lr, list(current_lr.shape), + float(value), current_lr.dtype, place) + + elif _in_legacy_dygraph(): + _legacy_C_ops.fill_constant(current_lr, 'value', + float(value), 'dtype', + current_lr.dtype, 'shape', + list(current_lr.shape)) + else: + global_block = framework.default_main_program( + ).global_block() + global_block.append_op(type='fill_constant', + outputs={'Out': [current_lr]}, + attrs={ + 'dtype': current_lr.dtype, + 'shape': list(current_lr.shape), + 'value': float(value) + }, + stop_gradient=True) + else: + assert len(value.shape) == 1 and value.shape[ + 0] == 1, "optimizer's learning rate must be 1-D Tensor with shape[1]" + self._learning_rate_map[framework.default_main_program()] = value + + @framework.dygraph_only + def current_step_lr(self): + """ + :api_attr: imperative + + Get current step learning rate. The return value is all the same When LearningRateDecay is not used, + otherwise return the step learning rate. + + Returns: + float: The learning rate of the current step. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + # example1: LearningRateDecay is not used, return value is all the same + with fluid.dygraph.guard(): + emb = fluid.dygraph.Embedding([10, 10]) + adam = fluid.optimizer.Adam(0.001, parameter_list = emb.parameters()) + lr = adam.current_step_lr() + print(lr) # 0.001 + + # example2: PiecewiseDecay is used, return the step learning rate + with fluid.dygraph.guard(): + inp = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32") + linear = fluid.dygraph.nn.Linear(10, 10) + inp = fluid.dygraph.to_variable(inp) + out = linear(inp) + loss = fluid.layers.reduce_mean(out) + + bd = [2, 4, 6, 8] + value = [0.2, 0.4, 0.6, 0.8, 1.0] + adam = fluid.optimizer.Adam(fluid.dygraph.PiecewiseDecay(bd, value, 0), + parameter_list=linear.parameters()) + + # first step: learning rate is 0.2 + np.allclose(adam.current_step_lr(), 0.2, rtol=1e-06, atol=0.0) # True + + # learning rate for different steps + ret = [0.2, 0.2, 0.4, 0.4, 0.6, 0.6, 0.8, 0.8, 1.0, 1.0, 1.0, 1.0] + for i in range(12): + adam.minimize(loss) + lr = adam.current_step_lr() + np.allclose(lr, ret[i], rtol=1e-06, atol=0.0) # True + + """ + current_lr = self._global_learning_rate() + if isinstance(current_lr, framework.Variable): + return self._global_learning_rate().numpy()[0] + + if isinstance(self._learning_rate, float): + return self._learning_rate + elif isinstance(self._learning_rate, _LearningRateEpochDecay): + step_lr = self._learning_rate() + return step_lr.numpy()[0] + else: + step_lr = self._learning_rate.step() + if isinstance(step_lr, (float, int)): + return step_lr + else: + return step_lr.numpy()[0] + + def _global_learning_rate(self, program=None): + """ + get global decayed learning rate + :return: + """ + if program is None: + program = framework.default_main_program() + return self._learning_rate_map.get(program, None) + + def _append_optimize_op(self, block, param_and_grad): + """ append optimize operator to block and return all the added optimize_op + """ + raise NotImplementedError() + + def _create_param_lr(self, param_and_grad): + # create learning rate variable for every parameter + param = param_and_grad[0] + param_lr = param.optimize_attr['learning_rate'] + if type(param_lr) == Variable: + return param_lr + else: + if param_lr == 1.0: + return self._global_learning_rate() + else: + with default_main_program()._lr_schedule_guard( + is_with_opt=True), framework.name_scope( + 'scale_with_param_lr'): + return self._global_learning_rate() * param_lr + + def _create_accumulators(self, block, parameters): + """Create all accumulators needed by the parameters + + Args: + block: the block in which the loss variable is present + parameters: list of parameter variables for the optimizer + """ + pass + + def _finish_update(self, block, parameters_and_grads): + """Finish any custom updates needed + before completing an optimization step + + Args: + block: the block in which the loss variable is present + parameters: list of parameter variables for the optimizer + + Returns: + None + """ + pass + + def _add_accumulator(self, + name, + param, + dtype=None, + fill_value=0.0, + shape=None, + type=None, + device=None): + """Utility function to add an accumulator for a parameter + + Args: + block: the block in which the loss variable is present + name: name of the accumulator + param: parameter variable for which accumulator is to be added + dtype: data type of the accumulator variable + fill_value: value to initialize the accumulator variable + """ + if self._name is not None: + name = self._name + "_" + name + if (name in self._accumulators + and param.name in self._accumulators[name]): + if framework._non_static_mode(): + return self._accumulators[name][param.name] + raise Exception( + "Accumulator {} already exists for parameter {}".format( + name, param.name)) + if shape == None: + shape = param.shape + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_" + name + var_name = unique_name.generate(var_name) + self._opti_name_list.append(var_name) + + var = self.helper.create_global_variable( + name=var_name, + persistable=True, + dtype=dtype or param.dtype, + type=core.VarDesc.VarType.LOD_TENSOR + if framework._non_static_mode() else + (param.type if type is None else type), + shape=shape, + belong_to_optimizer=True) + if device is None: + device = self._get_device_for_param(param.name) + with device_guard(device): + self.helper.set_variable_initializer( + var, initializer=Constant(value=float(fill_value))) + + if framework._non_static_mode(): + if len(self._accumulators_holder) > 0: + assert var_name in self._accumulators_holder, \ + "Optimizer set error, {} should in state dict".format( var_name ) + var.set_value(self._accumulators_holder[var_name]) + + self._accumulators[name][param.name] = var + return var + + def _add_global_accumulator(self, + name, + dtype=None, + fill_value=0.0, + shape=None, + type=None, + device=None): + """Utility function to add a global accumulator for all parameters in the model + + Args: + block: the block in which the loss variable is present + name: name of the accumulator + dtype: data type of the accumulator variable + fill_value: value to initialize the accumulator variable + shape: the shape of the accumulator + type: the variable type of the accumulator + device: the target place of the accumulator + """ + if self._name is not None: + name = self._name + "_" + name + if (name in self._global_accumulators): + if framework._non_static_mode(): + return self._global_accumulators[name] + raise Exception("Global accumulator {} already exists".format(name)) + if shape == None: + shape = [1] # most case, global accumulator is of shape [1] + assert isinstance(self.helper, LayerHelper) + + var_name = name + var_name = unique_name.generate(var_name) + self._opti_name_list.append(var_name) + + var = self.helper.create_global_variable( + name=var_name, + persistable=True, + dtype=dtype if dtype else self._dtype, + type=type, + shape=shape, + belong_to_optimizer=True) + if device is None: + device = 'cpu' + with device_guard(device): + self.helper.set_variable_initializer( + var, initializer=Constant(value=float(fill_value))) + + if framework._non_static_mode(): + if len(self._accumulators_holder) > 0: + assert var_name in self._accumulators_holder, \ + "Optimizer set error, {} should in state dict".format( var_name ) + var.set_value(self._accumulators_holder[var_name]) + + self._global_accumulators[name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + + Returns: + accumulator variable + """ + if self._name is not None: + name = self._name + "_" + name + if (name not in self._accumulators + or param.name not in self._accumulators[name]): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, param.name)) + return self._accumulators[name][param.name] + + def _get_global_accumulator(self, name): + """Utility function to fetch a global accumulator + + Args: + name: name of the accumulator + + Returns: + accumulator variable + """ + if self._name is not None: + name = self._name + "_" + name + if (name not in self._global_accumulators): + raise Exception("Global accumulator {} does not exist".format(name)) + return self._global_accumulators[name] + + def _update_param_device_map(self, parameters_and_grads, target_block): + for param_and_grad in parameters_and_grads: + if param_and_grad[0].trainable is True: + param_name = param_and_grad[0].name + ops = target_block.ops + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName( + ) + for op in ops: + input_arg_names = op.input_arg_names + if param_name in input_arg_names: + self._param_device_map[param_name] = op.attr( + device_attr_name) + break + + def _get_device_for_param(self, param_name): + device = None + if param_name in self._param_device_map: + device = self._param_device_map[param_name] + return device + + def _create_optimization_pass(self, parameters_and_grads): + """Add optimization operators to update gradients to variables. + + Args: + parameters_and_grads(list(tuple(Variable, Variable))): + a list of (variable, gradient) pair to update. + + Returns: + return_op_list: a list of operators that will complete one step of + optimization. This will include parameter update ops, global step + update ops and any other custom ops required by subclasses to manage + their internal state. + """ + # This is a default implementation of create_optimization_pass that + # can be shared by most optimizers. This implementation assumes that + # the subclass will implement the _append_optimize_op method and the + # _initialize_tensors method. The subclass can extend the + # _create_accumulators method if it needs to create accumulators + # for parameters and extend _finish_update method to add custom ops. + + # Allways called under program_guard use global block as loss block + # But if current block is in control flow, append optimize op in the + # grad block of current block + + global_block = framework.default_main_program().global_block() + target_block = global_block + current_block = framework.default_main_program().current_block() + if current_block.idx != global_block.idx: + assert current_block.backward_block_idx != -1, \ + "current block is not global_block, but it doesn't have backward block." + target_block = framework.default_main_program().blocks[ + current_block.backward_block_idx] + + start = len(target_block.ops) + + self._update_param_device_map(parameters_and_grads, target_block) + self._create_accumulators( + target_block, + [p[0] for p in parameters_and_grads if p[0].trainable]) + self._create_global_learning_rate() + + if framework._non_static_mode(): + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + if param_and_grad[0].trainable is True: + self._append_optimize_op(target_block, param_and_grad) + else: + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + with param_and_grad[0].block.program._optimized_guard( + param_and_grad), name_scope("optimizer"): + if param_and_grad[0].trainable is True: + device = self._get_device_for_param( + param_and_grad[0].name) + with device_guard(device): + optimize_op = self._append_optimize_op( + target_block, param_and_grad) + + # Get custom finish ops for subclasses + # FIXME: Need to fix this once we figure out how to handle dependencies + self._finish_update(target_block, parameters_and_grads) + + end = len(target_block.ops) + return target_block._slice_ops(start, end) + + def _process_distribute_lookuptable(self, param_grads): + """ + Because distribute lookup table only support SGD optimizer for now, not support + other optimizer and regularization, so we should find the table parameter out, + and avoid to add regularization and other op for it, and add sgd optimize op + for it independently. + :param param_grads(list((Var, Var))): list of (param, grad) pair. + :param loss: the loss variable. + :param startup_program: the startup program + """ + program = framework.default_main_program() + global_block = framework.default_main_program().global_block() + table_name = find_distributed_lookup_table(program) + table_param = None + table_grad = None + new_param_grads = [] + for p, g in param_grads: + if p.name == table_name: + if table_param is not None: + raise RuntimeError( + "multi dist table var found, only support one now!") + table_param = p + table_grad = g + else: + new_param_grads.append((p, g)) + sgd_op = None + if table_param is not None: + param_and_grad = [table_param, table_grad] + with table_param.block.program._optimized_guard(param_and_grad), \ + framework.name_scope("optimizer"): + self._create_global_learning_rate() + # create the optimize op + sgd_op = global_block.append_op( + type='sgd', + inputs={ + "Param": table_param, + "Grad": table_grad, + "LearningRate": self._create_param_lr(param_and_grad) + }, + outputs={"ParamOut": param_and_grad[0]}) + return new_param_grads, (table_param, table_grad), sgd_op + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + The first part of ``minimize``, do auto-diff to append backward operations for + the current program. + + Args: + loss (Variable): ``loss`` variable to run optimizations. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameter_list``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameter_list (Iterable, optional): Iterable of ``Variable`` or ``Variable.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Variable`` or ``Variable.name`` that don't need + to be updated. The default value is None. + callbacks (list, optional): list of callable objects to run when appending backward + operator for one parameter. The default value is None. + + Return: + list: list of (param, grad) variable pairs, param is ``Parameter``, + grad is the gradient value corresponding to the parameter. + + Examples: + See examples in ``apply_gradients``. + """ + act_no_grad_set = None + if framework._non_static_mode(): + pass + else: + act_no_grad_set = self._get_no_grad_set(loss, no_grad_set) + + # Infer dtype by loss if None + if self._dtype is None: + self._dtype = loss.dtype + + if framework._non_static_mode(): + parameter_list = parameter_list if parameter_list \ + else self._parameter_list + + params_grads = [] + for param in parameter_list: + if not param.trainable: + continue + if param._grad_ivar() is not None: + # create gradient variable + grad_var = param._grad_ivar() + params_grads.append((param, grad_var)) + else: + if callbacks is None: + callbacks = [error_clip_callback] + else: + assert (isinstance(callbacks, list)) + program = loss.block.program + assert len(loss.shape) == 1 and loss.shape[0] == 1, \ + "The loss.shape should be (1L,), but the current loss.shape is {}. " \ + "Maybe that you should call paddle.mean to process the current loss.".format( + loss.shape) + parameter_list = parameter_list if parameter_list \ + else self._parameter_list + with program_guard(program, startup_program): + params_grads = append_backward(loss, parameter_list, + act_no_grad_set, callbacks) + return params_grads + + def _create_regularization_of_grad(self, param, grad, regularization=None): + """ Create and add backward regularization Operators + + Function helper of append_regularization_ops. + """ + # If no gradient or no regularization is specified, then we don't need to do anything + if grad is None or ( + (not hasattr(param, 'regularizer') or + (hasattr(param, 'regularizer') and param.regularizer is None)) + and regularization is None): + return grad + regularization_term = None + if hasattr(param, 'regularizer') and param.regularizer is not None: + # Add variable for regularization term in grad block + regularization_term = param.regularizer(param, grad, grad.block) + elif regularization is not None: + regularization_term = regularization(param, grad, grad.block) + + assert regularization_term is not None + + if framework._non_static_mode(): + return _legacy_C_ops.sum([grad, regularization_term]) + + new_grad = grad + if grad.type == core.VarDesc.VarType.SELECTED_ROWS: + # FIXME(zcd): If the grad is SELECTED_ROWS, after regularization, + # the grad's type and name will be changed. But the gradient's name + # is used in ParallelExecutor Reduce mode, so I add a flag for + # the new_grad here. + new_grad = grad.block.create_var( + name=grad.name + core.kNewGradSuffix(), + dtype=param.dtype, + shape=param.shape, + lod_level=param.lod_level, + type=core.VarDesc.VarType.LOD_TENSOR) + + inputs = {"X": [grad, regularization_term]} + outputs = {"Out": [new_grad]} + grad.block.append_op(type='sum', inputs=inputs, outputs=outputs) + + return new_grad + + def append_regularization_ops(self, + parameters_and_grads, + regularization=None): + r"""Create and add backward regularization Operators + + Creates and adds backward regularization operators in the BlockDesc. + This will add gradients of the regularizer function to the gradients + of the parameters and return these modified gradients. This is the + same as implementing weight decay in optimizers for regularization. + + Args: + parameters_and_grads: A list of (parameters, gradients) pairs + that need to be regularized. + regularization: A global regularizer. If the parameter is not + set. It will be applied with regularizer. + + Returns: + list[(Variable, Variable)]: list of (parameters, gradients) \ + pair with the regularized gradient + + Raises: + Exception: Unknown regularization type + """ + params_and_grads = [] + if framework._non_static_mode(): + for param, grad in parameters_and_grads: + new_grad = self._create_regularization_of_grad( + param, grad, regularization) + params_and_grads.append((param, new_grad)) + else: + repeate_regularizer = False + with framework.name_scope('regularization'): + for param, grad in parameters_and_grads: + if not repeate_regularizer and getattr( + param, 'regularizer', + None) is not None and regularization is not None: + repeate_regularizer = True + logging.info( + "If regularizer of a Parameter has been set by 'fluid.ParamAttr' or 'fluid.WeightNormParamAttr' already. " + "The Regularization[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!" + % regularization.__str__()) + with param.block.program._optimized_guard([param, grad]): + new_grad = self._create_regularization_of_grad( + param, grad, regularization) + params_and_grads.append((param, new_grad)) + return params_and_grads + + def flatten_param_grads(self, params_grads): + need_flatten_params = [] + need_flatten_grads = [] + for p, g in params_grads: + if g is None: + continue + g.persistable = True + if getattr(p, 'need_clip', True) is False or getattr( + p, 'regularizer', None) is not None: + warnings.warn( + "flatten_param_grads=True will be discarded since paramter '{}''s need_clip is False or " + "the regularizer is set".format(p.name)) + self._flatten_param_grads = False + return params_grads + + need_flatten_params.append(p) + need_flatten_grads.append(g) + + shape = [np.prod(p.shape) for p in need_flatten_params] + block = need_flatten_params[0].block + + flatten_param = self.helper.create_global_variable( + name='flatten_param', + persistable=True, + dtype=need_flatten_params[0].dtype, + shape=[np.sum(shape)], + belong_to_optimizer=True) + + flatten_param.trainable = True + flatten_param.optimize_attr = need_flatten_params[0].optimize_attr + flatten_param.regularizer = need_flatten_params[0].regularizer + + flatten_grad = self.helper.create_global_variable( + name='flatten_grad', + persistable=True, + dtype=need_flatten_grads[0].dtype, + shape=[np.sum(shape)], + belong_to_optimizer=True) + + with program_guard(default_main_program()): + block.append_op(type="coalesce_tensor", + inputs={"Input": need_flatten_params}, + outputs={ + "Output": need_flatten_params, + "FusedOutput": flatten_param + }, + attrs={ + "copy_data": True, + "use_align": True, + "align_size": self._align_size, + "dtype": need_flatten_params[0].dtype + }) + + block.append_op(type="coalesce_tensor", + inputs={"Input": need_flatten_grads}, + outputs={ + "Output": need_flatten_grads, + "FusedOutput": flatten_grad + }, + attrs={ + "copy_data": True, + "use_align": True, + "align_size": self._align_size, + "dtype": need_flatten_grads[0].dtype + }) + + #NOTE(zhiqiu): the initializer should be set after coalesce_tensor op, + # so the shape of flatten_param and flatten_grad will be inferred. + self.helper.set_variable_initializer(flatten_param, + initializer=Constant(0.0)) + self.helper.set_variable_initializer(flatten_grad, + initializer=Constant(0.0)) + + return [(flatten_param, flatten_grad)] + + def apply_gradients(self, params_grads): + """ + Second part of `minimize`, appending optimization operators for + given `params_grads` pairs. + + Args: + params_grads (list): list of (param, grad) pair to do optimization. + + Returns: + list: A list of operators appended to the current program. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + loss = network() + optimizer = fluid.optimizer.SGD(learning_rate=0.1) + params_grads = optimizer.backward(loss) + # you may append operations for params_grads here + # ... + optimizer.apply_gradients(params_grads) + """ + params_grads = sorted(params_grads, key=lambda x: x[0].name) + + # NOTE(zhiqiu): currently, only support ClipGradByGlobalNorm and without regularization. + if self._flatten_param_grads and self.regularization is None: + if self._grad_clip == None or isinstance(self._grad_clip, + ClipGradByGlobalNorm): + params_grads = self.flatten_param_grads(params_grads) + + # 'optimizer(grad_clip)' or 'set_gradient_clip' + if self._grad_clip is not None: + params_grads = self._grad_clip(params_grads) + else: + params_grads = append_gradient_clip_ops(params_grads) + + # Add regularization if any + params_grads = self.append_regularization_ops(params_grads, + self.regularization) + + optimize_ops = self._create_optimization_pass(params_grads) + return optimize_ops + + def apply_optimize(self, loss, startup_program, params_grads): + """ + Second part of `minimize`, appending optimization operators for + given `params_grads` pairs. + Args: + loss (Variable): loss variable to run optimizations. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + params_grads (list): list of (param, grad) pair to do optimization. + Returns: + list: A list of operators appended to the current program. + """ + if framework._non_static_mode(): + with program_guard(framework.default_main_program(), + framework.default_startup_program()): + if self._grad_clip is not None: + params_grads = self._grad_clip(params_grads) + params_grads = self.append_regularization_ops( + params_grads, self.regularization) + optimize_ops = self._create_optimization_pass(params_grads) + else: + program = loss.block.program + with program_guard(program, startup_program): + optimize_ops = self.apply_gradients(params_grads) + return optimize_ops + + def _get_no_grad_set(self, loss, no_grad_set=None): + no_grad_set = _get_no_grad_set_name(no_grad_set) + parameters = loss.block.program.global_block().all_parameters() + param_no_trainable = set( + [param.name for param in parameters if param.trainable is False]) + # If the parameter is no trainable, it should not have a gradient. + no_grad_set.update(param_no_trainable) + + return no_grad_set + + @framework.dygraph_only + def clear_gradients(self): + """ + Clear the gradients of all optimized parameters for model. + + If not, new gradient will accumulat on previous gradient. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + with fluid.dygraph.guard(): + value = np.arange(26).reshape(2, 13).astype("float32") + a = fluid.dygraph.to_variable(value) + linear = fluid.Linear(13, 5, dtype="float32") + # This can be any optimizer supported by dygraph. + adam = fluid.optimizer.Adam(learning_rate = 0.01, + parameter_list = linear.parameters()) + out = linear(a) + out.backward() + adam.minimize(out) + adam.clear_gradients() + + """ + for p in self._parameter_list: + if p.trainable: + p.clear_gradient() + + @imperative_base.no_grad + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + """ + Add operations to minimize ``loss`` by updating ``parameter_list``. + + Args: + loss (Variable): A ``Variable`` containing the value to minimize. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameter_list``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameter_list (Iterable, optional): Iterable of ``Variable`` or ``Variable.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Variable`` or ``Variable.name`` that don't need + to be updated. The default value is None. + + Returns: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by minimize and a list of (param, grad) variable pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + The returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + Please refer to the example of current Optimizer. + """ + assert isinstance(loss, Variable), "The loss should be an Variable." + + parameter_list = parameter_list if parameter_list \ + else self._parameter_list + + params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + return optimize_ops, params_grads + + +class SGDOptimizer(Optimizer): + r""" + Optimizer of the stochastic gradient descent algorithm. + + .. math:: + + param\_out = param - learning\_rate * grad + + Parameters: + learning_rate (float|Variable): The learning rate used to update parameters. \ + Can be a float value or a Variable with one float value as data element. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.layers.data(name='x', shape=[13], dtype='float32') + y = fluid.layers.data(name='y', shape=[1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001) + sgd_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + """ + + def __init__(self, + learning_rate, + parameter_list=None, + regularization=None, + grad_clip=None, + multi_precision=False, + name=None): + assert learning_rate is not None + super(SGDOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "sgd" + self._use_mkldnn = False + self._multi_precision = multi_precision + self._master_weights = {} + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first and second moments + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + continue + if p.dtype == core.VarDesc.VarType.FP16 and not self._multi_precision: + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Adam optimizer." + ) + + @no_grad + def _append_optimize_op(self, block, param_and_grad): + + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + master_weight = (self._master_weights[param_and_grad[0].name] + if find_master else None) + + lr = self._create_param_lr(param_and_grad) + if in_dygraph_mode(): + _C_ops.sgd_(param_and_grad[0], lr, param_and_grad[1], master_weight, + find_master) + return None + if _in_legacy_dygraph(): + _legacy_C_ops.sgd(param_and_grad[0], lr, param_and_grad[1], + master_weight, param_and_grad[0], master_weight) + return None + + assert isinstance(block, framework.Block) + # create the optimize op + inputs = { + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": lr + } + + outputs = {"ParamOut": param_and_grad[0]} + + attrs = {"multi_precision": find_master} + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + sgd_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return sgd_op + + +class MomentumOptimizer(Optimizer): + r""" + + Simple Momentum optimizer with velocity state + + This optimizer has a flag for Nestrov Momentum. + + The update equations are as follows: + + .. math:: + + & velocity = mu * velocity + gradient + + & if (use\_nesterov): + + &\quad param = param - (gradient + mu * velocity) * learning\_rate + + & else: + + &\quad param = param - learning\_rate * velocity + + Parameters: + learning_rate (float|Variable): The learning rate used to update parameters. \ + Can be a float value or a Variable with one float value as data element. + momentum (float): Momentum factor + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + use_nesterov (bool, optional): Enables Nesterov momentum, default is false. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.layers.data(name='x', shape=[13], dtype='float32') + y = fluid.layers.data(name='y', shape=[1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + moment_optimizer = fluid.optimizer.MomentumOptimizer(learning_rate=0.001, momentum=0.9) + moment_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + """ + _velocity_acc_str = "velocity" + + def __init__(self, + learning_rate, + momentum, + parameter_list=None, + use_nesterov=False, + regularization=None, + grad_clip=None, + name=None): + assert learning_rate is not None + assert momentum is not None + super(MomentumOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "momentum" + self._momentum = momentum + self._use_nesterov = bool(use_nesterov) + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + self._add_accumulator(self._velocity_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + velocity_acc = self._get_accumulator(self._velocity_acc_str, + param_and_grad[0]) + lr = self._create_param_lr(param_and_grad) + master_weight = None + if framework._non_static_mode(): + _, _, _ = _legacy_C_ops.momentum( + param_and_grad[0], param_and_grad[1], velocity_acc, lr, + master_weight, param_and_grad[0], velocity_acc, master_weight, + 'mu', self._momentum, 'use_nesterov', self._use_nesterov) + return None + + attrs = {"mu": self._momentum, "use_nesterov": self._use_nesterov} + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "Velocity": [velocity_acc], + "LearningRate": [lr] + } + + outputs = { + "ParamOut": [param_and_grad[0]], + "VelocityOut": [velocity_acc] + } + # create the momentum optimize op + momentum_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return momentum_op + + +class DGCMomentumOptimizer(Optimizer): + r""" + :api_attr: Static Graph + + DGC (Deep Gradient Compression) Momentum Optimizer. Original paper is https://arxiv.org/abs/1712.01887 + + DGC reduces the communication bandwidth by sending only the important gradients (sparse update):\ + only gradients larger than a threshold are transmitted. + + To avoid losing information, DGC accumulates the rest of the gradients locally. + + Eventually, these gradients become large enough to be transmitted. + + Thus, DGC sends the large gradients immediately but eventually sends all of the gradients over time. + + To ensure no loss of accuracy, DGC employs momentum correction and local gradient clipping on top of the gradient sparsification to maintain model performance. + + DGC also uses momentum factor masking and warmup training to overcome the staleness problem caused by reduced communication. + + This optimizer will do two things: + + 1. Compress the gradient by get TopK import value from tensor \ + and use it for allreduce to reduce network bandwidth. + + 2. Call momentum to optimize the cost. + + Args: + learning_rate (float|Variable): The learning rate used to update parameters. \ + It can be a float value or a Variable with one float value as a data element. + momentum (float): Momentum factor. + rampup_begin_step (int): The beginning step from which gradient compression is implemented. + rampup_step (int): Time steps used in sparsity warm-up periods. Default is 1. + For example, if the sparsity is [0.75, 0.9375, 0.984375, 0.996, 0.999], and the rampup_step is 100, \ + it will use 0.75 at 0~19 steps, and 0.9375 at 20~39 steps, and so on. \ + And when reach sparsity array ends, it will use 0.999 then and after. + sparsity (list[float]): Get top important element from gradient tensor, the ratio is (1 - current sparsity). \ + Default is [0.999]. For example, if the sparsity is [0.99, 0.999], \ + the top [1%, 0.1%] important element will be transmitted. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + use_nesterov (bool): Enables Nesterov momentum. True means use Nesterov. Default is False. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipByNorm, optional): Gradient cliping strategy. ``DGCMomentumOptimizer`` only support + :ref:`api_fluid_clip_GradientClipByNorm` , and if not, it will raise TypeError. Default None, + meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + optimizer = fluid.optimizer.DGCMomentumOptimizer( + learning_rate=0.0001, + momentum=0.9, + rampup_step=1000, + rampup_begin_step=1252, + sparsity=[0.999, 0.999]) + + """ + _u_velocity_acc_str = "_dgc_u_" + _v_velocity_acc_str = "_dgc_v_" + + def __init__(self, + learning_rate, + momentum, + rampup_begin_step, + rampup_step=1, + sparsity=[0.999], + parameter_list=None, + use_nesterov=False, + num_trainers=None, + regularization=None, + grad_clip=None, + name=None): + if framework._non_static_mode(): + raise Exception("In dygraph, don't support DGCMomentumOptimizer.") + + assert core.is_compiled_with_cuda(), \ + "Paddle is not compiled with CUDA. DGC is only support GPU for now." + + assert learning_rate is not None + assert momentum is not None + super(DGCMomentumOptimizer, + self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "dgc_momentum" + self._momentum = momentum + self._use_nesterov = bool(use_nesterov) + + assert rampup_begin_step >= 0, "rampup_begin_step must >= 0" + self._rampup_begin_step = rampup_begin_step + self._rampup_step = rampup_step + self._sparsity = sparsity + + self._rampup_begin_step_var = None + self._global_step_var = None + + self._dgc_clip_norm = None + if grad_clip is not None: + if not isinstance(grad_clip, GradientClipByNorm): + raise TypeError( + "The type of grad_clip should be 'GradientClipByNorm', because DGCMomentumOptimizer only support GradientClipByNorm" + ) + assert isinstance( + num_trainers, int + ), "The type of num_trainers should be 'int', but received %s" % type( + num_trainers) + assert num_trainers > 0, "The value of num_trainers should be greater than 0!" + + self._num_trainers = num_trainers + self._dgc_clip_norm = grad_clip.clip_norm * (num_trainers**-0.5) + + self.regular_type, self.regular_coeff = self._get_regularization_param( + self.regularization) + + def _get_regularization_param(self, regularization): + regular_type = 0 + regular_coeff = 0.0 + + if regularization is not None: + regular_coeff = regularization._regularization_coeff + from .regularizer import L1Decay, L2Decay + if isinstance(regularization, L1Decay): + regular_type = 1 + elif isinstance(regularization, L2Decay): + regular_type = 2 + else: + assert False, 'regularization must be None|L1Decay|L2Deacy' + return regular_type, regular_coeff + + def _is_use_dgc(self, param_var, grad_var): + var_numel = abs(reduce(lambda x, y: x * y, param_var.shape)) + if var_numel < 16384 or \ + param_var.type == core.VarDesc.VarType.SELECTED_ROWS or \ + grad_var.type == core.VarDesc.VarType.SELECTED_ROWS or \ + param_var.dtype != core.VarDesc.VarType.FP32 : + return False + return True + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + velocity_acc = self._get_accumulator(self._u_velocity_acc_str, + param_and_grad[0]) + assert velocity_acc is not None + + inputs = { + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Velocity": velocity_acc, + "LearningRate": self._create_param_lr(param_and_grad), + } + outputs = { + "ParamOut": param_and_grad[0], + "VelocityOut": velocity_acc, + } + attrs = {"mu": self._momentum, "use_nesterov": self._use_nesterov} + + if not self._is_use_dgc(param_and_grad[0], param_and_grad[1]): + type = "momentum" + else: + type = "dgc_momentum" + inputs.update({ + "current_step": self._global_step_var, + "nranks": self._nranks_var + }) + outputs.update({'Grad_out': param_and_grad[1]}) + attrs.update({"rampup_begin_step": float(self._rampup_begin_step)}) + + # create the dgc momentum optimize op + dgc_momentum_op = block.append_op(type=type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + return dgc_momentum_op + + def _add_auto_increment_var(self, counter_name, begin, step=1): + helper = LayerHelper('global_step_counter') + counter, is_new_var = helper.create_or_get_global_variable( + name=counter_name, dtype='float32', shape=[1], persistable=True) + if is_new_var: + helper.set_variable_initializer(counter, + initializer=Constant( + value=float(begin - 1), + force_cpu=True)) + helper.main_program.global_block()._prepend_op( + type='increment', + inputs={'X': [counter]}, + outputs={'Out': [counter]}, + attrs={'step': float(step)}, + stop_gradient=True) + counter.stop_gradient = True + + return counter + + def _add_nranks_var(self, name, value=-1): + helper = LayerHelper('global_step_counter') + counter, is_new_var = helper.create_or_get_global_variable( + name=name, dtype='float32', shape=[1], persistable=True) + if is_new_var: + helper.set_variable_initializer(counter, + initializer=Constant( + value=float(value), + force_cpu=True)) + counter.stop_gradient = True + + return counter + + def _append_dgc_ops(self, param_and_grads): + main_program = default_main_program() + main_program._enable_dgc = True + + # step counter + self._global_step_var = self._add_auto_increment_var( + counter_name=core.dgc.kDGCCounterName(), begin=0) + + self._nranks_var = self._add_nranks_var(name=core.dgc.kDGCNRanksName(), + value=-1) + + # rampup begin step var for all_reduce_op_handle + self._rampup_begin_step_var = tensor.create_global_var( + shape=[1], + dtype=core.VarDesc.VarType.FP32, + persistable=True, + name=core.dgc.kDGCRampUpBeginStepName(), + value=self._rampup_begin_step * 1.0, + force_cpu=True) + + self.helper = LayerHelper(self.__class__.__name__) + + for param_var, grad_var in param_and_grads: + # reuse velocity in dgc_op and dgc_momentum_op + u_var = self._add_accumulator(self._u_velocity_acc_str, param_var) + + if not self._is_use_dgc(param_var, grad_var): + continue + + v_var = self._add_accumulator(self._v_velocity_acc_str, param_var) + + k_var = tensor.create_global_var(shape=[1], + dtype=param_var.dtype, + persistable=True, + name=param_var.name + + core.dgc.kDGCKName(), + value=0.0, + force_cpu=True) + + encoded_var = tensor.create_global_var(shape=[1], + dtype=param_var.dtype, + persistable=True, + name=param_var.name + + core.dgc.kDGCEncodedName(), + value=0.0, + force_cpu=False) + + gather_var = tensor.create_global_var(shape=[1], + dtype=param_var.dtype, + persistable=True, + name=param_var.name + + core.dgc.kDGCGatherName(), + value=0.0, + force_cpu=False) + + # del back oprolevarname + op_maker = core.op_proto_and_checker_maker + backward = core.op_proto_and_checker_maker.OpRole.Backward + for op in main_program.global_block().ops: + if not self._is_the_backward_op(op): + continue + + var_attr = op.all_attrs()[op_maker.kOpRoleVarAttrName()] + if param_var.name not in var_attr: + continue + + var_attr.remove(param_var.name) + var_attr.remove(grad_var.name) + if len(var_attr) > 1: + op._set_attr(op_maker.kOpRoleVarAttrName(), var_attr) + else: + op._remove_attr(op_maker.kOpRoleVarAttrName()) + + clip_var = grad_var + if self._dgc_clip_norm is not None: + clip_var = self._append_clip_norm(grad_var, self._dgc_clip_norm) + self._dgc_op(param_var, clip_var, grad_var, u_var, v_var, k_var, + encoded_var, gather_var) + + def _is_the_backward_op(self, op): + op_maker = core.op_proto_and_checker_maker + backward = core.op_proto_and_checker_maker.OpRole.Backward + if op_maker.kOpRoleVarAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(backward): + return True + return False + + def _clip_by_norm(self, x, max_norm, name=None): + args = {'x': x, 'max_norm': max_norm, 'name': name} + + helper = LayerHelper("dgc_clip_by_norm_op", **args) + + if name is None: + name = unique_name.generate_with_ignorable_key(".".join( + [helper.name, 'tmp'])) + + out = helper.create_variable(type=x.type, + name=name, + dtype=x.dtype, + persistable=False) + + helper.append_op(type="dgc_clip_by_norm", + inputs={ + "X": x, + "current_step": self._global_step_var + }, + attrs={ + "max_norm": max_norm, + "rampup_begin_step": float(self._rampup_begin_step) + }, + outputs={"Out": out}) + return out + + def _append_clip_norm(self, grad_var, clip_norm): + with grad_var.block.program._backward_role_guard(): + return self._clip_by_norm(x=grad_var, + max_norm=clip_norm, + name=grad_var.name) + + def _dgc_op(self, param_var, clip_var, grad_var, u_var, v_var, k_var, + encoded_var, gather_var): + block = framework.default_main_program().global_block() + op_maker = core.op_proto_and_checker_maker + + regular_type = self.regular_type + regular_coeff = self.regular_coeff + # The regularizer of the Parameters have higher priority + if param_var.regularizer is not None: + regular_type, regular_coeff = self._get_regularization_param( + param_var.regularizer) + + dgc_op = block.append_op(type="dgc", + inputs={ + "U": u_var, + "V": v_var, + "Grad": clip_var, + "Param": param_var, + "current_step": self._global_step_var, + "nranks": self._nranks_var, + }, + outputs={ + "U_out": u_var, + "V_out": v_var, + "EncodeGrad": encoded_var, + "k": k_var, + "Grad_out": grad_var, + "GatherBuff": gather_var, + }, + attrs={ + "m": + self._momentum, + "sparsity": + self._sparsity, + "use_nesterov": + self._use_nesterov, + "rampup_begin_step": + float(self._rampup_begin_step), + "rampup_step": + float(self._rampup_step), + "regular_coeff": + float(regular_coeff), + "regular_type": + int(regular_type), + }, + stop_gradient=True) + + backward = op_maker.OpRole.Backward + dgc_op._set_attr(op_maker.kOpRoleAttrName(), backward) + dgc_op._set_attr(op_maker.kOpRoleVarAttrName(), + [param_var.name, grad_var.name]) + + @imperative_base.no_grad + def apply_gradients(self, params_grads): + # Note: since we can't use all_reduce_op now, + # dgc_op should be the last op of one grad. + # Maybe need a grad allreduce pass. + self._append_dgc_ops(params_grads) + + params_grads = sorted(params_grads, key=lambda x: x[0].name) + params_grads, table_param_and_grad, table_optimize_op = \ + self._process_distribute_lookuptable(params_grads) + + not_dgc_params_grads = [] + dgc_params_grads = [] + # DGC clip and regularization in optimizer.backward + for param, grad in params_grads: + if not self._is_use_dgc(param, grad): + not_dgc_params_grads.append((param, grad)) + else: + dgc_params_grads.append((param, grad)) + + # 'optimizer(grad_clip)' or 'set_gradient_clip' + if self._grad_clip is not None: + not_dgc_params_grads = self._grad_clip(not_dgc_params_grads) + else: + not_dgc_params_grads = append_gradient_clip_ops( + not_dgc_params_grads) + + not_dgc_params_grads = self.append_regularization_ops( + not_dgc_params_grads, self.regularization) + + params_grads = not_dgc_params_grads + dgc_params_grads + params_grads = sorted(params_grads, key=lambda x: x[0].name) + + optimize_ops = self._create_optimization_pass(params_grads) + if table_optimize_op is not None: + optimize_ops.append(table_optimize_op) + params_grads.append(table_param_and_grad) + + return optimize_ops + + +class LarsMomentumOptimizer(Optimizer): + r""" + Momentum optimizer with LARS support + + The update equations are as follows: + + .. math:: + + & local\_learning\_rate = learning\_rate * lars\_coeff * \\ + \\frac{||param||}{||gradient|| + lars\_weight\_decay * ||param||} + + & velocity = mu * velocity + local\_learning\_rate * (gradient + lars\_weight\_decay * param + epsilon) + + & param = param - velocity + + Parameters: + learning_rate (float|Variable): The learning rate used to update parameters. \ + Can be a float value or a Variable with one float value as data element. \ + momentum (float): momentum factor + lars_coeff (float): Defines how much we trust the layer to change its weights. + lars_weight_decay (float): Weight decay coefficient for decaying using LARS. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + exclude_from_weight_decay (list[str], optional): Name string of layers which will be exclude from lars weight decay. Default is None. + epsilon (float, optional): Epsilon to avoid Division by Zero when calculate local lr. Default is 0. + multi_precision (bool, optional): Whether to use multi-precision during weight updating. + rescale_grad (float, optional): Multiply the gradient with `rescale_grad` \ + before updating. Often choose to be `1.0/batch_size`. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + np_inp = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + inp = fluid.layers.data( + name="inp", shape=[2, 2], append_batch_size=False) + out = fluid.layers.fc(inp, size=3) + out = fluid.layers.reduce_sum(out) + optimizer = fluid.optimizer.LarsMomentumOptimizer(learning_rate=0.001, momentum=0.9) + optimizer.minimize(out) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + exe.run( + feed={"inp": np_inp}, + fetch_list=[out.name]) + """ + _velocity_acc_str = "velocity" + + def __init__(self, + learning_rate, + momentum, + lars_coeff=0.001, + lars_weight_decay=0.0005, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None, + exclude_from_weight_decay=None, + epsilon=0, + multi_precision=False, + rescale_grad=1.0): + assert learning_rate is not None + assert momentum is not None + super(LarsMomentumOptimizer, + self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "lars_momentum" + self._momentum = momentum + self._lars_coeff = float(lars_coeff) + self._lars_weight_decay = float(lars_weight_decay) + self._epsilon = float(epsilon) + if exclude_from_weight_decay is None: + self._exclude_from_weight_decay = [] + else: + self._exclude_from_weight_decay = exclude_from_weight_decay + self._multi_precision = multi_precision + self._rescale_grad = float(rescale_grad) + self._master_weights = {} + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + '_fp32_master' + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + target_param = self._master_weights[ + param.name] if find_master else param + target_name = target_param.name + if (name not in self._accumulators + or target_name not in self._accumulators[name]): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name)) + return self._accumulators[name][target_name] + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_accumulator(self._velocity_acc_str, master_p) + continue + if p.dtype == core.VarDesc.VarType.FP16 and not self._multi_precision: + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Lars optimizer." + ) + self._add_accumulator(self._velocity_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + _lars_weight_decay = self._lars_weight_decay + param_name = param_and_grad[0].name + if len(self._exclude_from_weight_decay) > 0: + for name in self._exclude_from_weight_decay: + if name in param_name: + _lars_weight_decay = 0.0 + break + + velocity_acc = self._get_accumulator(self._velocity_acc_str, + param_and_grad[0]) + lr = self._create_param_lr(param_and_grad) + + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + master_weight = (self._master_weights[param_and_grad[0].name] + if find_master else None) + + attrs = { + "mu": self._momentum, + "lars_coeff": self._lars_coeff, + "lars_weight_decay": [_lars_weight_decay], + "multi_precision": find_master, + "epsilon": self._epsilon, + "rescale_grad": self._rescale_grad + } + + inputs = { + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Velocity": velocity_acc, + "LearningRate": lr + } + + outputs = {"ParamOut": param_and_grad[0], "VelocityOut": velocity_acc} + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + if framework._non_static_mode(): + tmp, tmp2 = _legacy_C_ops.lars_momentum( + [param_and_grad[0]], [param_and_grad[1]], [velocity_acc], [lr], + [param_and_grad[0]], [velocity_acc], "mu", self._momentum, + "lars_coeff", self._lars_coeff, "lars_weight_decay", + [_lars_weight_decay], "multi_precision", find_master, "epsilon", + self._epsilon, "rescale_grad", self._rescale_grad) + else: + # create the momentum optimize op + momentum_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return momentum_op + + +class AdagradOptimizer(Optimizer): + r""" + The Adaptive Gradient optimizer (Adagrad for short) can adaptively assign + different learning rates to individual parameters. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + moment\_out &= moment + grad * grad + + param\_out &= param - \\frac{learning\_rate * grad}{\sqrt{moment\_out} + \epsilon} + + Related paper: `Adaptive Subgradient Methods for Online Learning and + Stochastic Optimization `_. + + The original paper does not have the ``epsilon`` attribute. It is added here + in our implementation as also proposed `Per-parameter adaptive learning rate + methods `_ + for numerical stability to avoid the division by zero error. + + Args: + learning_rate (float|Variable): The learning rate used to update ``Parameter``. + It can be a float value or a ``Variable`` with a float type. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-06. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + initial_accumulator_value (float, optional): Initial value for moment accumulator. + The default value is 0.0. + + Examples: + .. code-block:: python + + import numpy as np + import paddle.fluid as fluid + + np_inp = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + inp = fluid.data(name="inp", shape=[2, 2]) + out = fluid.layers.fc(inp, size=3) + out = fluid.layers.reduce_sum(out) + optimizer = fluid.optimizer.AdagradOptimizer(learning_rate=0.2) + optimizer.minimize(out) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + exe.run( + feed={"inp": np_inp}, + fetch_list=[out.name]) + """ + _moment_acc_str = "moment" + + def __init__(self, + learning_rate, + epsilon=1.0e-6, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None, + initial_accumulator_value=0.0): + assert learning_rate is not None + assert epsilon is not None + super(AdagradOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "adagrad" + self._epsilon = epsilon + self.initial_accumulator_value = initial_accumulator_value + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + self._add_accumulator(self._moment_acc_str, + p, + fill_value=self.initial_accumulator_value) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + moment_acc = self._get_accumulator(self._moment_acc_str, + param_and_grad[0]) + if in_dygraph_mode(): + _C_ops.adagrad_(param_and_grad[0], param_and_grad[1], moment_acc, + self._create_param_lr(param_and_grad), + self._epsilon) + return None + elif _in_legacy_dygraph(): + _legacy_C_ops.adagrad(param_and_grad[0], param_and_grad[1], + moment_acc, + self._create_param_lr(param_and_grad), + param_and_grad[0], moment_acc, "epsilon", + self._epsilon) + return None + else: + # Create the adagrad optimizer op + adagrad_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Moment": moment_acc, + "LearningRate": self._create_param_lr(param_and_grad) + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": moment_acc + }, + attrs={"epsilon": self._epsilon}, + stop_gradient=True) + + return adagrad_op + + +class AdamOptimizer(Optimizer): + r""" + The Adam optimizer uses an optimization described at the end + of section 2 of `Adam paper `_ , + it can dynamically adjusts the learning rate of each parameter using + the 1st moment estimates and the 2nd moment estimates of the gradient. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + t & = t + 1 + + moment\_1\_out & = {\\beta}_1 * moment\_1 + (1 - {\\beta}_1) * grad + + moment\_2\_out & = {\\beta}_2 * moment\_2 + (1 - {\\beta}_2) * grad * grad + + learning\_rate & = learning\_rate * \\ + \\frac{\sqrt{1 - {\\beta}_2^t}}{1 - {\\beta}_1^t} + + param\_out & = param - learning\_rate * \\frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + + Related paper: `Adam: A Method for Stochastic Optimization `_ + + Args: + learning_rate (float|Variable, optional): The learning rate used to update ``Parameter``. + It can be a float value or a ``Variable`` with a float type. The default value is 0.001. + beta1 (float|Variable, optional): The exponential decay rate for the 1st moment estimates. + It should be a float number or a Variable with shape [1] and data type as float32. + The default value is 0.9. + beta2 (float|Variable, optional): The exponential decay rate for the 2nd moment estimates. + It should be a float number or a Variable with shape [1] and data type as float32. + The default value is 0.999. + epsilon (float|Tensor, optional): A small float value for numerical stability. + It should be a float number or a Variable with shape [1] and data type as float32. + The default value is 1e-08. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators. + The accumulators are updated at every step. Every element of the two moving-average + is updated in both dense mode and sparse mode. If the size of parameter is very large, + then the update may be very slow. The lazy mode only update the element that has + gradient in current mini-batch, so it will be much more faster. But this mode has + different semantics with the original Adam algorithm and may lead to different result. + The default value is False. + use_global_beta_pow (bool, optional): Whether to use global beta_pow. If true, Adam will use global beta_pow + for whole model instead of creating beta_pow for each parameter. Default is false. + flatten_param_grads (bool, optional): Whether to flatten all parameters and gradients. Default is false. + align_size (int, optional): The alignment size when flatten parameters and gradients. Default is -1, which means + use same align_size as allocator. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.data(name='x', shape=[None, 13], dtype='float32') + y = fluid.data(name='y', shape=[None, 1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + adam_optimizer = fluid.optimizer.AdamOptimizer(0.01) + adam_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + .. code-block:: python + + # Adam with beta1/beta2 as Variable + import paddle + import paddle.fluid as fluid + import paddle.fluid.layers.learning_rate_scheduler as lr_scheduler + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.data(name='x', shape=[None, 13], dtype='float32') + y = fluid.data(name='y', shape=[None, 1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + # define beta decay variable + def get_decayed_betas(beta1_init, beta2_init, decay_steps, decay_rate, epsilon_init): + global_step = lr_scheduler._decay_step_counter() + + beta1 = fluid.layers.create_global_var( + shape=[1], + value=float(beta1_init), + dtype='float32', + # set persistable for save checkpoints and resume + persistable=True, + name="beta1") + beta2 = fluid.layers.create_global_var( + shape=[1], + value=float(beta2_init), + dtype='float32', + # set persistable for save checkpoints and resume + persistable=True, + name="beta2") + epsilon = fluid.layers.create_global_var( + shape=[1], + value=float(epsilon_init), + dtype='float32', + # set persistable for save checkpoints and resume + persistable=True, + name="epsilon") + + div_res = global_step / decay_steps + decayed_beta1 = beta1_init * (decay_rate**div_res) + decayed_beta2 = beta2_init * (decay_rate**div_res) + fluid.layers.assign(decayed_beta1, beta1) + fluid.layers.assign(decayed_beta2, beta2) + + return beta1, beta2, epsilon + + beta1, beta2, epsilon = get_decayed_betas(0.9, 0.99, 1e5, 0.9, 1e-8) + adam_optimizer = fluid.optimizer.AdamOptimizer( + learning_rate=0.01, + beta1=beta1, + beta2=beta2, + epsilon=epsilon) + adam_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + """ + _moment1_acc_str = "moment1" + _moment2_acc_str = "moment2" + _beta1_pow_acc_str = "beta1_pow_acc" + _beta2_pow_acc_str = "beta2_pow_acc" + + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None, + lazy_mode=False, + use_global_beta_pow=False, + flatten_param_grads=False, + align_size=-1): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + super(AdamOptimizer, + self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + flatten_param_grads=flatten_param_grads, + align_size=align_size, + name=name) + self.type = "adam" + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._lazy_mode = lazy_mode + self._use_global_beta_pow = use_global_beta_pow + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + # Create accumulator tensors for first and second moments + for p in parameters: + self._add_accumulator(self._moment1_acc_str, p) + self._add_accumulator(self._moment2_acc_str, p) + if not self._use_global_beta_pow: + self._add_accumulator( + name=self._beta1_pow_acc_str, + param=p, + fill_value=0.9 if isinstance(self._beta1, Variable) \ + else self._beta1, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + self._add_accumulator( + name=self._beta2_pow_acc_str, + param=p, + fill_value=0.999 if isinstance(self._beta2, Variable) \ + else self._beta2, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + if self._use_global_beta_pow: + self._add_global_accumulator( + name=self._beta1_pow_acc_str, + fill_value=0.9 if isinstance(self._beta1, Variable) \ + else self._beta1, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + self._add_global_accumulator( + name=self._beta2_pow_acc_str, + fill_value=0.999 if isinstance(self._beta2, Variable) \ + else self._beta2, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + moment1 = self._get_accumulator(self._moment1_acc_str, + param_and_grad[0]) + moment2 = self._get_accumulator(self._moment2_acc_str, + param_and_grad[0]) + if self._use_global_beta_pow: + beta1_pow_acc = self._get_global_accumulator( + self._beta1_pow_acc_str) + beta2_pow_acc = self._get_global_accumulator( + self._beta2_pow_acc_str) + else: + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param_and_grad[0]) + beta2_pow_acc = self._get_accumulator(self._beta2_pow_acc_str, + param_and_grad[0]) + lr = self._create_param_lr(param_and_grad) + # create the adam optimize op + + if framework._non_static_mode(): + _beta1 = self._beta1 if not isinstance( + self._beta1, Variable) else self._beta1.numpy().item(0) + _beta2 = self._beta2 if not isinstance( + self._beta2, Variable) else self._beta2.numpy().item(0) + master_weight = None + _, _, _, _, _, _ = _legacy_C_ops.adam( + param_and_grad[0], param_and_grad[1], lr, moment1, moment2, + beta1_pow_acc, beta2_pow_acc, master_weight, param_and_grad[0], + moment1, moment2, beta1_pow_acc, beta2_pow_acc, master_weight, + 'epsilon', self._epsilon, 'lazy_mode', self._lazy_mode, + 'min_row_size_to_use_multithread', 1000, 'beta1', _beta1, + 'beta2', _beta2, 'use_global_beta_pow', + self._use_global_beta_pow) + + return None + + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "LearningRate": [lr], + "Moment1": [moment1], + "Moment2": [moment2], + "Beta1Pow": [beta1_pow_acc], + "Beta2Pow": [beta2_pow_acc] + } + + # Pass found_inf to adam, to skip update for not only param, but also momentum and beta_pow + found_inf = self._get_auxiliary_var('found_inf') + + if found_inf: + inputs['SkipUpdate'] = found_inf + + outputs = { + "ParamOut": [param_and_grad[0]], + "Moment1Out": [moment1], + "Moment2Out": [moment2], + "Beta1PowOut": [beta1_pow_acc], + "Beta2PowOut": [beta2_pow_acc], + } + attrs = { + "lazy_mode": self._lazy_mode, + "min_row_size_to_use_multithread": 1000, + 'use_global_beta_pow': self._use_global_beta_pow + } + + if isinstance(self._beta1, Variable): + inputs['Beta1Tensor'] = self._beta1 + else: + attrs['beta1'] = self._beta1 + if isinstance(self._beta2, Variable): + inputs['Beta2Tensor'] = self._beta2 + else: + attrs['beta2'] = self._beta2 + if isinstance(self._epsilon, Variable): + inputs['EpsilonTensor'] = self._epsilon + else: + attrs['epsilon'] = self._epsilon + + adam_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return adam_op + + def _finish_update(self, block, parameters_and_grads): + r"""Update beta1_pow and beta2_pow accumulator + """ + assert isinstance(block, framework.Block) + if self._use_global_beta_pow: + beta1_pow_acc = self._get_global_accumulator( + self._beta1_pow_acc_str) + beta2_pow_acc = self._get_global_accumulator( + self._beta2_pow_acc_str) + + with block.program._optimized_guard([]): + inputs = {"X": beta1_pow_acc} + outputs = {"Out": beta1_pow_acc} + attrs = {} + if isinstance(self._beta1, Variable): + inputs["Y"] = self._beta1 + # use elementwise_mul for better performance + block.append_op(type="elementwise_mul", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + else: + attrs['scale'] = self._beta1 + block.append_op(type="scale", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + inputs = {"X": beta2_pow_acc} + outputs = {"Out": beta2_pow_acc} + attrs = {} + if isinstance(self._beta2, Variable): + inputs["Y"] = self._beta2 + # use elementwise_mul for better performance + block.append_op(type="elementwise_mul", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + else: + attrs['scale'] = self._beta2 + block.append_op(type="scale", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + +class AdamaxOptimizer(Optimizer): + r""" + The Adamax optimizer is implemented based on the Adamax Optimization + in Section 7 of `Adam paper `_. + The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm, + which makes the learning rate update algorithm more stable and simple. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + t & = t + 1 + + moment\_out & = {\\beta}_1 * moment + (1 - {\\beta}_1) * grad + + inf\_norm\_out & = max({\\beta}_2 * inf\_norm + \epsilon, |grad|) + + learning\_rate & = \\frac{learning\_rate}{1 - {\\beta}_1^t} + + param\_out & = param - learning\_rate * \\frac{moment\_out}{inf\_norm\_out} + + Related paper: `Adam: A Method for Stochastic Optimization `_ + + The original paper does not have an ``epsilon`` attribute, + it is added here for numerical stability to prevent the division by 0 error. + + Args: + learning_rate (float|Variable, optional): The learning rate used to update ``Parameter``. + It can be a float value or a ``Variable`` with a float type. The default value is 0.001. + beta1 (float, optional): The exponential decay rate for the 1st moment estimates. + The default value is 0.9. + beta2 (float, optional): The exponential decay rate for the 2nd moment estimates. + The default value is 0.999. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-08. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + **Notes**: + **Currently, AdamaxOptimizer doesn't support sparse parameter optimization.** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + # First create the Executor. + place = fluid.CPUPlace() # fluid.CUDAPlace(0) + exe = fluid.Executor(place) + + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + data = fluid.data(name='X', shape=[None, 1], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + loss = fluid.layers.mean(hidden) + adam = fluid.optimizer.AdamaxOptimizer(learning_rate=0.2) + adam.minimize(loss) + + # Run the startup program once and only once. + exe.run(startup_program) + + x = numpy.random.random(size=(10, 1)).astype('float32') + outs = exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + """ + _moment_acc_str = "moment" + _inf_norm_acc_str = "inf_norm" + _beta1_pow_acc_str = "beta1_pow_acc" + + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + super(AdamaxOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "adamax" + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + + def _create_accumulators(self, block, parameters): + # Create accumulator tensors for first moment and infinity norm + for p in parameters: + self._add_accumulator(self._moment_acc_str, p) + self._add_accumulator(self._inf_norm_acc_str, p) + self._add_accumulator(name=self._beta1_pow_acc_str, + param=p, + fill_value=self._beta1, + shape=[1]) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + moment = self._get_accumulator(self._moment_acc_str, param_and_grad[0]) + inf_norm = self._get_accumulator(self._inf_norm_acc_str, + param_and_grad[0]) + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param_and_grad[0]) + + if framework.in_dygraph_mode(): + _C_ops.adamax_(param_and_grad[0], param_and_grad[1], + self._create_param_lr(param_and_grad), moment, + inf_norm, beta1_pow_acc, self._beta1, self._beta2, + self._epsilon) + elif framework._in_legacy_dygraph(): + _legacy_C_ops.adamax(param_and_grad[0], param_and_grad[1], + self._create_param_lr(param_and_grad), moment, + inf_norm, beta1_pow_acc, param_and_grad[0], + moment, inf_norm, "beta1", self._beta1, + "beta2", self._beta2, "epsilon", self._epsilon) + else: + # create the adamax optimize op + adamax_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": self._create_param_lr(param_and_grad), + "Moment": moment, + "InfNorm": inf_norm, + "Beta1Pow": beta1_pow_acc + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": moment, + "InfNormOut": inf_norm + }, + attrs={ + "beta1": self._beta1, + "beta2": self._beta2, + "epsilon": self._epsilon + }, + stop_gradient=True) + + return adamax_op + + def _finish_update(self, block, parameters_and_grads): + """Update Beta1 Power accumulator + """ + assert isinstance(block, framework.Block) + for param, grad in parameters_and_grads: + if grad is None or param.trainable is False: + continue + with param.block.program._optimized_guard([param, grad + ]), name_scope('adamx'): + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param) + if framework._non_static_mode(): + if framework.in_dygraph_mode(): + tmp = _C_ops.scale(beta1_pow_acc, self._beta1, 0.0, + True) + else: + tmp = _legacy_C_ops.scale(beta1_pow_acc, "scale", + self._beta1) + beta1_pow_acc.copy_(tmp, False) + else: + block.append_op(type="scale", + inputs={"X": beta1_pow_acc}, + outputs={"Out": beta1_pow_acc}, + attrs={"scale": self._beta1}, + stop_gradient=True) + + +class DpsgdOptimizer(Optimizer): + r""" + We implement the Dpsgd optimizer according to CCS16 paper - + Deep Learning with Differential Privacy. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + # First create the Executor. + place = fluid.CPUPlace() # fluid.CUDAPlace(0) + exe = fluid.Executor(place) + + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + data = fluid.layers.data(name='X', shape=[1], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + loss = fluid.layers.mean(hidden) + optimizer = fluid.optimizer.Dpsgd(learning_rate=0.01, clip=10.0, batch_size=16.0, sigma=1.0) + optimizer.minimize(loss) + + # Run the startup program once and only once. + exe.run(startup_program) + + x = numpy.random.random(size=(10, 1)).astype('float32') + outs = exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + + Args: + learning_rate (float|Variable): the learning rate used to update parameters. \ + Can be a float value or a Variable with one float value as data element. + clip (float): clipping threshold + batch_size (float): batch size. + sigma (float): for gaussian noise. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + Notes: + Currently, DpsgdOptimizer doesn't support sparse parameter optimization. + """ + + def __init__(self, + learning_rate=0.001, + clip=0.9, + batch_size=0.999, + sigma=1e-8, + parameter_list=None): + assert learning_rate is not None + assert clip is not None + assert batch_size is not None + assert sigma is not None + super(DpsgdOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list) + self.type = "dpsgd" + self._clip = clip + self._batch_size = batch_size + self._sigma = sigma + ''' + Note(wangzhongpu): + This property is only used for debugging, do not need to set it! + Dpsgd operator use time(NULL) as random seed to generate random number. + However, during debugging, we need determinated result, so we will set self._seed to a fixed number. + ''' + self._seed = None + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + # create the dpsgd optimize op + if self._seed == None: + self._seed = 0 + + if framework._non_static_mode(): + _legacy_C_ops.dpsgd(param_and_grad[0], param_and_grad[1], + self._create_param_lr(param_and_grad), + param_and_grad[0], "clip", self._clip, + "batch_size", self._batch_size, "sigma", + self._sigma, "seed", self._seed) + else: + dpsgd_op = block.append_op(type=self.type, + inputs={ + "Param": + param_and_grad[0], + "Grad": + param_and_grad[1], + "LearningRate": + self._create_param_lr(param_and_grad) + }, + outputs={"ParamOut": param_and_grad[0]}, + attrs={ + "clip": self._clip, + "batch_size": self._batch_size, + "sigma": self._sigma, + "seed": self._seed + }, + stop_gradient=True) + + return dpsgd_op + + +class DecayedAdagradOptimizer(Optimizer): + r""" + The Decayed Adagrad optimizer can be seen as an Adagrad algorithm that introduces + the decay rate to solve the problem of a sharp drop in the learning rate + during model training when using the AdagradOptimizer. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + moment\_out & = decay * moment + (1 - decay) * grad * grad + + param\_out & = param - \\frac{learning\_rate * grad}{\sqrt{moment\_out} + \epsilon} + + Related paper: `Adaptive Subgradient Methods for Online Learning and Stochastic + Optimization `_. + + The original paper does not have an ``epsilon`` attribute. It is added here for numerical + stability to avoid the division by zero error. + + Args: + learning_rate (float|Variable): The learning rate used to update ``Parameter``. + It can be a float value or a ``Variable`` with a float type. + decay (float, optional): The decay rate. The default value is 0.95. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-06. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + **Notes**: + **Currently, DecayedAdagradOptimizer doesn't support sparse parameter optimization.** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data( name='x', shape=[None, 10], dtype='float32' ) + trans = fluid.layers.fc( x, 100 ) + cost = fluid.layers.reduce_mean( trans ) + optimizer = fluid.optimizer.DecayedAdagradOptimizer(learning_rate=0.2) + optimizer.minimize(cost) + """ + _moment_acc_str = "moment" + + def __init__(self, + learning_rate, + decay=0.95, + epsilon=1.0e-6, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None): + assert learning_rate is not None + assert decay is not None + assert epsilon is not None + + super(DecayedAdagradOptimizer, + self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "decayed_adagrad" + self._decay = decay + self._epsilon = epsilon + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + self._add_accumulator(self._moment_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + moment_acc = self._get_accumulator(self._moment_acc_str, + param_and_grad[0]) + + if framework._non_static_mode(): + _legacy_C_ops.decayed_adagrad(param_and_grad[0], param_and_grad[1], + moment_acc, + self._create_param_lr(param_and_grad), + param_and_grad[0], moment_acc, + "epsilon", self._epsilon, "decay", + self._decay) + else: + # Create the decayed adagrad optimizer op + decayed_adagrad_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Moment": moment_acc, + "LearningRate": self._create_param_lr(param_and_grad) + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": moment_acc + }, + attrs={ + "epsilon": self._epsilon, + "decay": self._decay + }, + stop_gradient=True) + + return decayed_adagrad_op + + +class AdadeltaOptimizer(Optimizer): + r""" + **Notes: This API does not support sparse parameter optimization.** + + Adadelta Optimizer. Please refer to this for details: + `ADADELTA: AN ADAPTIVE LEARNING RATE METHOD `_. + + The update is done as follows: + + .. math:: + + E(g_t^2) &= \\rho * E(g_{t-1}^2) + (1-\\rho) * g^2 + + learning\_rate &= \sqrt{ ( E(dx_{t-1}^2) + \\epsilon ) / ( E(g_t^2) + \\epsilon ) } + + E(dx_t^2) &= \\rho * E(dx_{t-1}^2) + (1-\\rho) * (-g*learning\_rate)^2 + + Args: + learning_rate (float|Variable): global learning rate. + epsilon (float): a small float number for numeric stability. Default 1.0e-6. + rho (float): a floating point value indicating the decay rate. Default 0.95. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + image = fluid.data(name='image', shape=[None, 28], dtype='float32') + fc = fluid.layers.fc(image, size=10) + cost = fluid.layers.reduce_mean(fc) + optimizer = fluid.optimizer.Adadelta( + learning_rate=0.0003, epsilon=1.0e-6, rho=0.95) + + # optimizer_ops is a list of optimizer operators to update parameters + # params_grads is a list of (param, param_grad), where param is each + # parameter and param_grad is the gradient variable of param. + optimizer_ops, params_grads = optimizer.minimize(cost) + """ + + _avg_squared_grad_acc_str = "_avg_squared_grad" + _avg_squared_update_acc_str = "_avg_squared_update" + + def __init__(self, + learning_rate, + epsilon=1.0e-6, + rho=0.95, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None): + if learning_rate is None: + raise ValueError("learning_rate is not set.") + if epsilon is None: + raise ValueError("epsilon is not set.") + if rho is None: + raise ValueError("rho is not set.") + super(AdadeltaOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + self.type = "adadelta" + self._epsilon = epsilon + self._rho = rho + + def _create_accumulators(self, block, parameters): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + for p in parameters: + self._add_accumulator(self._avg_squared_grad_acc_str, p) + self._add_accumulator(self._avg_squared_update_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + avg_squared_grad_acc = self._get_accumulator( + self._avg_squared_grad_acc_str, param_and_grad[0]) + avg_squared_update_acc = self._get_accumulator( + self._avg_squared_update_acc_str, param_and_grad[0]) + + if framework.in_dygraph_mode(): + _C_ops.adadelta_(param_and_grad[0], param_and_grad[1], + avg_squared_grad_acc, avg_squared_update_acc, + self._rho, self._epsilon) + elif framework._in_legacy_dygraph(): + _legacy_C_ops.adadelta(param_and_grad[0], param_and_grad[1], + avg_squared_grad_acc, avg_squared_update_acc, + param_and_grad[0], avg_squared_grad_acc, + avg_squared_update_acc, "epsilon", + self._epsilon, "rho", self._rho) + else: + # Create the adadelta optimizer op + adadelta_op = block.append_op(type=self.type, + inputs={ + "Param": + param_and_grad[0], + "Grad": + param_and_grad[1], + "AvgSquaredGrad": + avg_squared_grad_acc, + "AvgSquaredUpdate": + avg_squared_update_acc + }, + outputs={ + "ParamOut": + param_and_grad[0], + "AvgSquaredGradOut": + avg_squared_grad_acc, + "AvgSquaredUpdateOut": + avg_squared_update_acc + }, + attrs={ + "epsilon": self._epsilon, + "rho": self._rho + }, + stop_gradient=True) + + return adadelta_op + + +class RMSPropOptimizer(Optimizer): + r""" + Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning + rate method. The original slides proposed RMSProp: Slide 29 of + http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf . + + The original equation is as follows: + + .. math:: + + r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2 + + w & = w - \\frac{\\eta} {\\sqrt{r(w,t) + \\epsilon}} \\nabla Q_{i}(w) + + The first equation calculates moving average of the squared gradient for + each weight. Then dividing the gradient by :math:`sqrt{v(w,t)}`. + + In some cases, adding a momentum term :math: `\\beta` is beneficial. + In our implementation, Nesterov momentum is used: + + .. math:: + + r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2 + + v(w, t) & = \\beta v(w, t-1) + \\frac{\\eta} {\\sqrt{r(w,t) + + \\epsilon}} \\nabla Q_{i}(w) + + w & = w - v(w, t) + + if centered is True: + + .. math:: + + r(w, t) & = \\rho r(w, t-1) + (1 - \\rho)(\\nabla Q_{i}(w))^2 + + g(w, t) & = \\rho g(w, t-1) + (1 - \\rho)\\nabla Q_{i}(w) + + v(w, t) & = \\beta v(w, t-1) + \\frac{\\eta} {\\sqrt{r(w,t) - (g(w, t))^2 + + \\epsilon}} \\nabla Q_{i}(w) + + w & = w - v(w, t) + + where, :math:`\\rho` is a hyperparameter and typical values are 0.9, 0.95 + and so on. :math: `beta` is the momentum term. :math: `\\epsilon` is a + smoothing term to avoid division by zero, usually set somewhere in range + from 1e-4 to 1e-8. + + + Parameters: + learning_rate(float): Global learning rate. + rho(float): rho is :math: `\\rho` in equation, default is 0.95. + epsilon(float): :math: `\\epsilon` in equation is smoothing term to + avoid division by zero, default is 1e-6. + momentum(float): :math:`\\beta` in equation is the momentum term, + default is 0.0. + centered(bool): If True, gradients are normalized by the estimated variance of + the gradient; if False, by the uncentered second moment. Setting this to + True may help with training, but is slightly more expensive in terms of + computation and memory. Defaults to False. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Raises: + ValueError: If learning_rate, rho, epsilon, momentum are None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.layers.data(name='x', shape=[13], dtype='float32') + y = fluid.layers.data(name='y', shape=[1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + rms_optimizer = fluid.optimizer.RMSProp(learning_rate=0.1) + rms_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + """ + + _momentum_acc_str = "momentum" + _mean_square_acc_str = "mean_square" + _mean_grad_acc_str = "mean_grad" + + def __init__(self, + learning_rate, + rho=0.95, + epsilon=1.0e-6, + momentum=0.0, + centered=False, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None): + super(RMSPropOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + if learning_rate is None: + raise ValueError("learning_rate is not set.") + if rho is None: + raise ValueError("rho is not set.") + if epsilon is None: + raise ValueError("epsilon is not set.") + if momentum is None: + raise ValueError("momentum is not set.") + + self.type = "rmsprop" + self._rho = rho + self._epsilon = epsilon + self._momentum = momentum + self._centered = centered + + def _create_accumulators(self, block, parameters): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + for p in parameters: + self._add_accumulator(self._momentum_acc_str, p) + self._add_accumulator(self._mean_square_acc_str, p) + self._add_accumulator(self._mean_grad_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + momentum_acc = self._get_accumulator(self._momentum_acc_str, + param_and_grad[0]) + mean_square_acc = self._get_accumulator(self._mean_square_acc_str, + param_and_grad[0]) + mean_grad_acc = self._get_accumulator(self._mean_grad_acc_str, + param_and_grad[0]) + if in_dygraph_mode(): + _C_ops.rmsprop_(param_and_grad[0], mean_square_acc, + param_and_grad[1], momentum_acc, + self._create_param_lr(param_and_grad), + mean_grad_acc, self._epsilon, self._rho, + self._momentum, self._centered) + return None + elif _in_legacy_dygraph(): + _legacy_C_ops.rmsprop(param_and_grad[0], mean_square_acc, + self._create_param_lr(param_and_grad), + param_and_grad[1], momentum_acc, + param_and_grad[0], momentum_acc, + mean_square_acc, mean_grad_acc, "epsilon", + self._epsilon, "decay", self._rho, "momentum", + self._momentum, "centered", self._centered) + return None + else: + rmsprop_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Moment": momentum_acc, + "MeanSquare": mean_square_acc, + "MeanGrad": mean_grad_acc, + "LearningRate": self._create_param_lr(param_and_grad), + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": momentum_acc, + "MeanSquareOut": mean_square_acc, + "MeanGradOut": mean_grad_acc + }, + attrs={ + "epsilon": self._epsilon, + "decay": self._rho, + "momentum": self._momentum, + "centered": self._centered + }, + stop_gradient=True) + + return rmsprop_op + + +class FtrlOptimizer(Optimizer): + r""" + FTRL (Follow The Regularized Leader) Optimizer. + + The paper that proposed Follow The Regularized Leader (FTRL): + (https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf) + + .. math:: + + &new\_accum = squared\_accum + grad^2 + + &if (lr\_power == -0.5): + + &\quad linear\_accum += grad - \\frac{\\sqrt{new\_accum} - \\sqrt{squared\_accum}}{learning\_rate * param} + + &else: + + &\quad linear\_accum += grad - \\frac{new\_accum^{-lr\_power} - accum^{-lr\_power}}{learning\_rate * param} + + + &x = l1 * sign(linear\_accum) - linear\_accum + + &if (lr\_power == -0.5): + + &\quad y = \\frac{\\sqrt{new\_accum}}{learning\_rate} + (2 * l2) + + &\quad pre\_shrink = \\frac{x}{y} + + &\quad param = (abs(linear\_accum) > l1).select(pre\_shrink, 0.0) + + &else: + + &\quad y = \\frac{new\_accum^{-lr\_power}}{learning\_rate} + (2 * l2) + + &\quad pre\_shrink = \\frac{x}{y} + + &\quad param = (abs(linear\_accum) > l1).select(pre\_shrink, 0.0) + + &squared\_accum += grad^2 + + Parameters: + learning_rate (float|Variable): Global learning rate. + l1 (float): L1 regularization strength, default is 0.0. + l2 (float): L2 regularization strength, default is 0.0. + lr_power (float): Learning Rate Power, default is -0.5. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. \ + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Raises: + ValueError: If learning_rate, rho, epsilon, momentum are None. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + place = fluid.CPUPlace() + main = fluid.Program() + with fluid.program_guard(main): + x = fluid.layers.data(name='x', shape=[13], dtype='float32') + y = fluid.layers.data(name='y', shape=[1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_cost = fluid.layers.mean(cost) + + ftrl_optimizer = fluid.optimizer.Ftrl(learning_rate=0.1) + ftrl_optimizer.minimize(avg_cost) + + fetch_list = [avg_cost] + train_reader = paddle.batch( + paddle.dataset.uci_housing.train(), batch_size=1) + feeder = fluid.DataFeeder(place=place, feed_list=[x, y]) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + for data in train_reader(): + exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list) + + NOTE: + Currently, FtrlOptimizer doesn't support sparse parameter optimization. + """ + + _squared_acc_str = "squared" + _linear_acc_str = "linear" + + def __init__(self, + learning_rate, + l1=0.0, + l2=0.0, + lr_power=-0.5, + parameter_list=None, + regularization=None, + grad_clip=None, + name=None): + super(FtrlOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + name=name) + if learning_rate is None: + raise ValueError("learning_rate is not set.") + + self.type = "ftrl" + self._l1 = l1 + self._l2 = l2 + self._lr_power = lr_power + + def _create_accumulators(self, block, parameters): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + for p in parameters: + self._add_accumulator(self._squared_acc_str, p) + self._add_accumulator(self._linear_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + squared_acc = self._get_accumulator(self._squared_acc_str, + param_and_grad[0]) + linear_acc = self._get_accumulator(self._linear_acc_str, + param_and_grad[0]) + if framework._non_static_mode(): + _legacy_C_ops.ftrl(param_and_grad[0], squared_acc, linear_acc, + param_and_grad[1], + self._create_param_lr(param_and_grad), + param_and_grad[0], squared_acc, linear_acc, "l1", + self._l1, "l2", self._l2, "lr_power", + self._lr_power) + + else: + ftrl_op = block.append_op(type=self.type, + inputs={ + "Param": + param_and_grad[0], + "Grad": + param_and_grad[1], + "SquaredAccumulator": + squared_acc, + "LinearAccumulator": + linear_acc, + "LearningRate": + self._create_param_lr(param_and_grad), + }, + outputs={ + "ParamOut": param_and_grad[0], + "SquaredAccumOut": squared_acc, + "LinearAccumOut": linear_acc + }, + attrs={ + "l1": self._l1, + "l2": self._l2, + "lr_power": self._lr_power + }, + stop_gradient=True) + + return ftrl_op + + +class LambOptimizer(AdamOptimizer): + r""" + LAMB (Layer-wise Adaptive Moments optimizer for Batching training) Optimizer. + + LAMB Optimizer is designed to scale up the batch size of training without losing + accuracy, which supports adaptive element-wise updating and accurate layer-wise + correction. For more information, please refer to `Large Batch Optimization for + Deep Learning: Training BERT in 76 minutes `_ . + + The updating of parameters follows: + + .. math:: + + m_t &= \\beta_1 m_{t - 1}+ (1 - \\beta_1)g_t + + v_t &= \\beta_2 v_{t - 1} + (1 - \\beta_2)g_t^2 + + m_t &= \\frac{m_t}{\\beta_1^t} + + v_t &= \\frac{v_t}{\\beta_2^t} + + r_t &= \\frac{m_t}{\\sqrt{v_t}+\\epsilon} + + w_t &= w_{t-1} -\\eta_t \\frac{\\left \| w_{t-1}\\right \|}{\\left \| r_t + \\lambda w_{t-1}\\right \|} (r_t + \\lambda w_{t-1}) + + + where :math:`m` is the 1st moment, and :math:`v` the 2nd moment, :math:`\\eta` the + learning rate, :math:`\\lambda` the LAMB weight decay rate. + + Args: + learning_rate (float|Variable, optional): the learning rate used to update parameters. \ + Can be a float value or a Variable with data type float32. Default 0.001. + lamb_weight_decay (float, optional): The LAMB weight decay rate. Default 0.01. + beta1 (float, optional): The exponential decay rate for the 1st moment estimates. + Default 0.9. + beta2 (float, optional): The exponential decay rate for the 2nd moment estimates. + Default 0.999. + epsilon (float, optional): A small float value for numerical stability. Default 1e-6. + parameter_list (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_paddle_fluid_clip_ClipGradByGlobalNorm` , :ref:`api_paddle_fluid_clip_ClipGradByNorm` , + :ref:`api_paddle_fluid_clip_ClipGradByValue` ). If you want better convergence, it is recommended + to use :ref:`api_paddle_fluid_clip_ClipGradByGlobalNorm` . Default None, meaning there is no gradient clipping. + exclude_from_weight_decay_fn (function|None): Exclude a parameter from weight + decay when **exclude_from_weight_decay_fn(parameter)** returns true. + Default None. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + data = fluid.data(name='x', shape=[-1, 5], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + cost = fluid.layers.mean(hidden) + + def exclude_fn(param): + return param.name.endswith('.b_0') + + optimizer = fluid.optimizer.Lamb(learning_rate=0.002, + exclude_from_weight_decay_fn=exclude_fn) + optimizer.minimize(cost) + """ + _moment1_acc_str = "moment1" + _moment2_acc_str = "moment2" + _beta1_pow_acc_str = "beta1_pow_acc" + _beta2_pow_acc_str = "beta2_pow_acc" + + def __init__(self, + learning_rate=0.001, + lamb_weight_decay=0.01, + beta1=0.9, + beta2=0.999, + epsilon=1e-6, + parameter_list=None, + regularization=None, + grad_clip=None, + exclude_from_weight_decay_fn=None, + name=None): + assert learning_rate is not None + assert lamb_weight_decay is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + super(LambOptimizer, self).__init__(learning_rate=learning_rate, + parameter_list=parameter_list, + regularization=regularization, + grad_clip=grad_clip, + beta1=beta1, + beta2=beta2, + epsilon=epsilon, + name=name) + self.type = "lamb" + self._weight_decay = lamb_weight_decay + self._exclude_from_weight_decay_fn = exclude_from_weight_decay_fn + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + block.program._use_lamb = True + + moment1 = self._get_accumulator(self._moment1_acc_str, + param_and_grad[0]) + moment2 = self._get_accumulator(self._moment2_acc_str, + param_and_grad[0]) + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param_and_grad[0]) + beta2_pow_acc = self._get_accumulator(self._beta2_pow_acc_str, + param_and_grad[0]) + + if self._exclude_from_weight_decay_fn is not None \ + and self._exclude_from_weight_decay_fn(param_and_grad[0]): + weight_decay = 0.0 + else: + weight_decay = self._weight_decay + lr = self._create_param_lr(param_and_grad) + master_weight = None + if framework._non_static_mode(): + _legacy_C_ops.lamb(param_and_grad[0], param_and_grad[1], lr, + moment1, moment2, beta1_pow_acc, beta2_pow_acc, + master_weight, param_and_grad[0], moment1, + moment2, beta1_pow_acc, beta2_pow_acc, + master_weight, 'beta1', self._beta1, 'beta2', + self._beta2, 'epsilon', self._epsilon, + 'weight_decay', weight_decay) + return None + + # create the lamb optimize op + lamb_op = block.append_op(type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": lr, + "Moment1": moment1, + "Moment2": moment2, + "Beta1Pow": beta1_pow_acc, + "Beta2Pow": beta2_pow_acc + }, + outputs={ + "ParamOut": param_and_grad[0], + "Moment1Out": moment1, + "Moment2Out": moment2, + "Beta1PowOut": beta1_pow_acc, + "Beta2PowOut": beta2_pow_acc + }, + attrs={ + "beta1": self._beta1, + "beta2": self._beta2, + "epsilon": self._epsilon, + "weight_decay": weight_decay + }, + stop_gradient=True) + + return lamb_op + + +# We short the class name, since users will use the optimizer with the package +# name. The sample code: +# +# import paddle.fluid as fluid +# +# sgd = fluid.optimizer.SGD(...) +# +# It is no need to add an `Optimizer` as the class suffix +SGD = SGDOptimizer +Momentum = MomentumOptimizer +Adagrad = AdagradOptimizer +Adam = AdamOptimizer +Adamax = AdamaxOptimizer +Dpsgd = DpsgdOptimizer +DecayedAdagrad = DecayedAdagradOptimizer +Adadelta = AdadeltaOptimizer +RMSProp = RMSPropOptimizer +Ftrl = FtrlOptimizer +LarsMomentum = LarsMomentumOptimizer +Lamb = LambOptimizer + + +class ModelAverage(Optimizer): + r""" + :api_attr: Static Graph + + The ModelAverage optimizer accumulates specific continuous historical parameters + during training. The accumulated historical range can be controlled by the passed + ``average_window_rate`` argument. The averaged ``Parameter`` are used in the prediction, + which usually can improve the accuracy of the prediction. + + Accumulate the average of the ``Parameter`` in the sliding window, the result will be saved + in a temporary variable, can be applied to the current model's ``Parameter`` by calling + the ``apply()`` method, and the current model ``Parameter`` can be restored by calling + the ``restore()`` method. + + The window size for calculating the average is determined by ``average_window_rate``, + ``min_average_window``, ``max_average_window`` and the current ``Parameter`` update times (num_updates). + + When the cumulative times (num_accumulates) is greater than the specific window + threshold (average_window), the accumulated ``Parameter`` temporary variable is set to 0.0. + The following example will help to understand the role of these arguments: + + :: + + if num_accumulates >= min_average_window and num_accumulates >= min(max_average_window, num_updates * average_window_rate): + num_accumulates = 0 + + In the above conditional judgment statement, ``num_accumulates`` indicates the current + accumulated number, which can be abstractly understood as the length of the cumulative window. + The length of the window must be at least the length set by the ``min_average_window`` argument, + and cannot exceed the length specified by the ``max_average_window`` argument or + ``num_updates * average_window_rate``, where ``num_updates`` indicates the current ``Parameter`` + update times, ``average_window_rate`` is a coefficient that calculates the length of the window. + + Args: + average_window_rate (float): The calculate ratio of the window length relative to ``Parameter`` update times. + min_average_window (int, optional): the minimum size of average window length. The default value is 10000. + max_average_window (int, optional): The maximum size of average window length. The default value is 10000. + regularization (WeightDecayRegularizer, optional): The strategy of regularization. There are two method: \ + :ref:`api_fluid_regularizer_L1Decay` , :ref:`api_fluid_regularizer_L2Decay` . If a parameter has set \ + regularizer using :ref:`api_fluid_ParamAttr` already, the regularization setting here in optimizer will be \ + ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + # First create the Executor. + place = fluid.CPUPlace() # fluid.CUDAPlace(0) + exe = fluid.Executor(place) + + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + # build net + data = fluid.data(name='X', shape=[None, 1], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + loss = fluid.layers.mean(hidden) + optimizer = fluid.optimizer.Momentum(learning_rate=0.2, momentum=0.1) + optimizer.minimize(loss) + + # build ModelAverage optimizer + model_average = fluid.optimizer.ModelAverage(0.15, + min_average_window=10000, + max_average_window=12500) + + exe.run(startup_program) + for i in range(12500): + x = numpy.random.random(size=(10, 1)).astype('float32') + outs = exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + + # apply ModelAverage + with model_average.apply(exe): + x = numpy.random.random(size=(10, 1)).astype('float32') + exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + """ + + def __init__(self, + average_window_rate, + min_average_window=10000, + max_average_window=10000, + regularization=None, + name=None): + if framework._non_static_mode(): + raise Exception("In dygraph, don't support ModelAverage.") + super(ModelAverage, self).__init__(0.0, + regularization=regularization, + name=name) + self.average_window = average_window_rate + self.min_average_window = min_average_window + self.max_average_window = max_average_window + + self.params_grads = [] + for param in framework.default_main_program().global_block( + ).all_parameters(): + if param.do_model_average != False: + grad = param.block.create_var( + name=unique_name.generate_with_ignorable_key(".".join( + [param.name, 'tmp'])), + dtype=param.dtype, + persistable=False, + stop_gradient=True) + self.params_grads.append((param, grad)) + + for param, grad in self.params_grads: + if grad is None: + continue + with param.block.program._optimized_guard( + [param, grad]), name_scope('move_average'): + self._append_average_accumulate_op(param) + + self.apply_program = Program() + block = self.apply_program.global_block() + with program_guard(main_program=self.apply_program): + for param_grad in self.params_grads: + self._add_average_apply_op(block, param_grad) + + self.restore_program = Program() + block = self.restore_program.global_block() + with program_guard(main_program=self.restore_program): + for param_grad in self.params_grads: + self._add_average_restore_op(block, param_grad) + + def _add_average_apply_op(self, block, param_grad): + param = block._clone_variable(param_grad[0]) + grad = block._clone_variable(param_grad[1]) + sum_1 = block._clone_variable(self._get_accumulator('sum_1', param)) + sum_2 = block._clone_variable(self._get_accumulator('sum_2', param)) + sum_3 = block._clone_variable(self._get_accumulator('sum_3', param)) + num_accumulates = block._clone_variable( + self._get_accumulator('num_accumulates', param)) + old_num_accumulates = block._clone_variable( + self._get_accumulator('old_num_accumulates', param)) + num_updates = block._clone_variable( + self._get_accumulator('num_updates', param)) + # backup param value to grad + layers.assign(input=param, output=grad) + # param = (sum_1 + sum_2 + sum_3) / (num_accumulates + old_num_accumulates) + tmp = layers.sum(x=[num_accumulates, old_num_accumulates]) + sum = layers.sum(x=[sum_1, sum_2, sum_3]) + tmp = layers.cast( + x=tmp, dtype='float32' if self._dtype == None else self._dtype) + sum = layers.cast( + x=sum, dtype='float32' if self._dtype == None else self._dtype) + ops._elementwise_div(x=sum, y=tmp, out=param) + + def _add_average_restore_op(self, block, param_grad): + param = block._clone_variable(param_grad[0]) + grad = block._clone_variable(param_grad[1]) + layers.assign(input=grad, output=param) + + def _append_average_accumulate_op(self, param): + self.helper = LayerHelper("average_accumulate") + sum_1 = self._add_accumulator('sum_1', param) + sum_2 = self._add_accumulator('sum_2', param) + sum_3 = self._add_accumulator('sum_3', param) + num_accumulates = self._add_accumulator('num_accumulates', + param, + dtype='int64', + shape=[1]) + old_num_accumulates = self._add_accumulator('old_num_accumulates', + param, + dtype='int64', + shape=[1]) + num_updates = self._add_accumulator('num_updates', + param, + dtype='int64', + shape=[1]) + + self.helper.append_op(type='average_accumulates', + inputs={ + "param": param, + "in_sum_1": sum_1, + "in_sum_2": sum_2, + "in_sum_3": sum_3, + "in_num_accumulates": num_accumulates, + "in_old_num_accumulates": old_num_accumulates, + "in_num_updates": num_updates + }, + outputs={ + "out_sum_1": sum_1, + "out_sum_2": sum_2, + "out_sum_3": sum_3, + "out_num_accumulates": num_accumulates, + "out_old_num_accumulates": + old_num_accumulates, + "out_num_updates": num_updates, + }, + attrs={ + "average_window": self.average_window, + "min_average_window": self.min_average_window, + "max_average_window": self.max_average_window, + }, + stop_gradient=True) + + @signature_safe_contextmanager + def apply(self, executor, need_restore=True): + """ + Apply the average of the cumulative ``Parameter`` to the parameters of the current model. + + Args: + executor(fluid.Executor): The current network executor. + need_restore(bool): Restore flag variable, if set to True, the network will restore + the parameters of the network to the default value, if set to False, + it will not be restored. The default value is True. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + # First create the Executor. + place = fluid.CPUPlace() # fluid.CUDAPlace(0) + exe = fluid.Executor(place) + + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + # build net + data = fluid.data(name='X', shape=[None, 1], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + loss = fluid.layers.mean(hidden) + optimizer = fluid.optimizer.Momentum(learning_rate=0.2, momentum=0.1) + optimizer.minimize(loss) + + # build ModelAverage optimizer + model_average = fluid.optimizer.ModelAverage(0.15, + min_average_window=10000, + max_average_window=12500) + + exe.run(startup_program) + for i in range(12500): + x = numpy.random.random(size=(10, 1)).astype('float32') + outs = exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + + # apply ModelAverage + with model_average.apply(exe): + x = numpy.random.random(size=(10, 1)).astype('float32') + exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + """ + executor.run(self.apply_program) + try: + yield + finally: + if need_restore: + self.restore(executor) + + def restore(self, executor): + """ + Restore ``Parameter`` values of current model. + + Args: + executor(fluid.Executor): The current network executor. + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import numpy + + # First create the Executor. + place = fluid.CPUPlace() # fluid.CUDAPlace(0) + exe = fluid.Executor(place) + + train_program = fluid.Program() + startup_program = fluid.Program() + with fluid.program_guard(train_program, startup_program): + # build net + data = fluid.data(name='X', shape=[None, 1], dtype='float32') + hidden = fluid.layers.fc(input=data, size=10) + loss = fluid.layers.mean(hidden) + optimizer = fluid.optimizer.Momentum(learning_rate=0.2, momentum=0.1) + optimizer.minimize(loss) + + # build ModelAverage optimizer + model_average = fluid.optimizer.ModelAverage(0.15, + min_average_window=10000, + max_average_window=12500) + + exe.run(startup_program) + for i in range(12500): + x = numpy.random.random(size=(10, 1)).astype('float32') + outs = exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + + # apply ModelAverage + with model_average.apply(exe, False): + x = numpy.random.random(size=(10, 1)).astype('float32') + exe.run(program=train_program, + feed={'X': x}, + fetch_list=[loss.name]) + + # restore Parameters + model_average.restore(exe) + """ + executor.run(self.restore_program) + + +class ExponentialMovingAverage(object): + r""" + :api_attr: Static Graph + + Compute the moving average of parameters with exponential decay. + Given a parameter :math:`\\theta`, its exponential moving average (EMA) + will be + + .. math:: + + \\text{EMA}_0 & = 0 + + \\text{EMA}_t & = \\text{decay} * \\text{EMA}_{t-1} + (1 - \\text{decay}) * \\theta_t + + The average results calculated by **update()** method will be saved in + temporary variables which are created and maintained by the object, and can + be applied to parameters of current model by calling **apply()** method. And + the **restore()** method is used to restore the parameters. + + **Bias correction**. All EMAs are initialized to :math:`0` and hence they will be + zero biased, which can be corrected by divided by a factor + :math:`(1 - \\text{decay}^t)` , i.e., the actual EMAs applied to parameters + when calling **apply()** method would be + + .. math:: + + \\widehat{\\text{EMA}}_t = \\frac{\\text{EMA}_t}{1 - \\text{decay}^t} + + **Decay rate scheduling**. A large decay rate very close to 1 would result + in that the averages move very slowly. And a better strategy is to set a + relative smaller decay rate in the very beginning. The argument **thres_steps** + allows users to pass a Variable to schedule the decay rate, in this case, + the actual decay rate becomes + + .. math:: + + \\min(\\text{decay}, \\frac{1 + \\text{thres_steps}}{10 + \\text{thres_steps}}) + + Usually **thres_steps** can be the global training steps. + + + Args: + decay (float, optional): The exponential decay rate, usually close to 1, such as 0.999, 0.9999, ... . Default 0.999. + thres_steps (Variable|None, optional): If not `None`, schedule the decay rate. Default None. + name (str|None, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. + + + Examples: + + .. code-block:: python + + import numpy + import paddle + import paddle.static as static + from paddle.static import ExponentialMovingAverage + + paddle.enable_static() + + data = static.data(name='x', shape=[-1, 5], dtype='float32') + hidden = static.nn.fc(x=data, size=10) + cost = paddle.mean(hidden) + + test_program = static.default_main_program().clone(for_test=True) + optimizer = paddle.optimizer.Adam(learning_rate=0.001) + optimizer.minimize(cost) + + ema = ExponentialMovingAverage(0.999) + ema.update() + + place = paddle.CPUPlace() + exe = static.Executor(place) + exe.run(static.default_startup_program()) + + for pass_id in range(3): + for batch_id in range(6): + data = numpy.random.random(size=(10, 5)).astype('float32') + exe.run(program=static.default_main_program(), + feed={'x': data}, + fetch_list=[cost.name]) + + # usage 1 + with ema.apply(exe): + data = numpy.random.random(size=(10, 5)).astype('float32') + exe.run(program=test_program, + feed={'x': data}, + fetch_list=[hidden.name]) + + # usage 2 + with ema.apply(exe, need_restore=False): + data = numpy.random.random(size=(10, 5)).astype('float32') + exe.run(program=test_program, + feed={'x': data}, + fetch_list=[hidden.name]) + ema.restore(exe) + + """ + + def __init__(self, decay=0.999, thres_steps=None, name=None): + if framework._non_static_mode(): + raise Exception( + "In dygraph, don't support ExponentialMovingAverage.") + self._decay = decay + self._thres_steps = thres_steps + self._name = name if name is not None else '' + self._decay_var = self._get_ema_decay() + + self._step_counter_name = "@EMA_STEP_COUNTER@" + self._params_tmps = [] + for param in default_main_program().global_block().all_parameters(): + if param.do_model_average != False: + tmp = param.block.create_var(name=unique_name.generate(".".join( + [self._name + param.name, 'ema_tmp'])), + dtype=param.dtype, + persistable=False, + stop_gradient=True) + self._params_tmps.append((param, tmp)) + + self._ema_vars = {} + for param, tmp in self._params_tmps: + with param.block.program._optimized_guard( + [param, tmp]), name_scope('moving_average'): + self._ema_vars[param.name] = self._create_ema_vars(param) + + self.apply_program = Program() + block = self.apply_program.global_block() + with program_guard(main_program=self.apply_program): + decay_pow, global_step = self._get_decay_pow(block) + for param, tmp in self._params_tmps: + param = block._clone_variable(param) + tmp = block._clone_variable(tmp) + ema = block._clone_variable(self._ema_vars[param.name]) + layers.assign(input=param, output=tmp) + # bias correction + with layers.control_flow.Switch() as switch: + with switch.case(global_step > 0): + layers.assign(output=param, + input=ema / (1.0 - decay_pow)) + with switch.default(): + layers.assign(output=param, input=ema) + + self.restore_program = Program() + block = self.restore_program.global_block() + with program_guard(main_program=self.restore_program): + for param, tmp in self._params_tmps: + tmp = block._clone_variable(tmp) + param = block._clone_variable(param) + layers.assign(input=tmp, output=param) + + def _get_ema_decay(self): + with default_main_program()._lr_schedule_guard(): + decay_var = layers.tensor.create_global_var( + shape=[1], + value=self._decay, + dtype='float32', + persistable=True, + name="scheduled_ema_decay_rate") + + if self._thres_steps is not None: + decay_t = (self._thres_steps + 1.0) / (self._thres_steps + 10.0) + with layers.control_flow.Switch() as switch: + with switch.case(decay_t < self._decay): + layers.tensor.assign(decay_t, decay_var) + with switch.default(): + layers.tensor.assign( + np.array([self._decay], dtype=np.float32), + decay_var) + return decay_var + + def _get_decay_pow(self, block): + global_step = layers.create_global_var(name=self._step_counter_name, + shape=[1], + value=0, + dtype='int64', + persistable=True) + global_step = layers.cast(global_step, "float32") + decay_var = block._clone_variable(self._decay_var) + decay_pow_acc = layers.elementwise_pow(decay_var, global_step) + return decay_pow_acc, global_step + + def _create_ema_vars(self, param): + param_ema = layers.create_global_var( + name=unique_name.generate(self._name + param.name + '_ema'), + shape=param.shape, + value=0.0, + dtype=param.dtype, + persistable=True) + + return param_ema + + def update(self): + """ + Update Exponential Moving Average. Should only call this method in + train program. + """ + global_step = layers.autoincreased_step_counter( + counter_name=self._step_counter_name) + param_master_emas = [] + for param, tmp in self._params_tmps: + with param.block.program._optimized_guard( + [param, tmp]), name_scope('moving_average'): + param_ema = self._ema_vars[param.name] + if param.name + '.master' in self._ema_vars: + master_ema = self._ema_vars[param.name + '.master'] + param_master_emas.append([param_ema, master_ema]) + else: + ema_t = param_ema * self._decay_var + param * ( + 1 - self._decay_var) + layers.assign(input=ema_t, output=param_ema) + + # for fp16 params + for param_ema, master_ema in param_master_emas: + default_main_program().global_block().append_op( + type="cast", + inputs={"X": master_ema}, + outputs={"Out": param_ema}, + attrs={ + "in_dtype": master_ema.dtype, + "out_dtype": param_ema.dtype + }) + + @signature_safe_contextmanager + def apply(self, executor, need_restore=True): + """ + Apply moving average to parameters for evaluation. + + Args: + executor (Executor): The Executor to execute applying. + need_restore (bool, optional): Whether to restore parameters after + applying. Default True. + """ + executor.run(self.apply_program) + try: + yield + finally: + if need_restore: + self.restore(executor) + + def restore(self, executor): + """Restore parameters. + + Args: + executor (Executor): The Executor to execute restoring. + """ + executor.run(self.restore_program) + + +class PipelineOptimizer(object): + """ + :api_attr: Static Graph + + Pipeline Optimizer: Make a program to run as pipeline, that is splitting a + program into multiple sections (sub-programs) and each section run on a + device to enable the training of large scale models and the use of + heterogeneous devices. Meanwhile, all sections run in the stype of pipeline. + + Args: + optimizer (Optimizer): The optimizer to use, such as SGD. + num_microbatches (int): Number of microbatches. [Optional. Default:1]. + start_cpu_core_id (int): The first cpu core id to use. [Optional. Default:0]. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.layers as layers + + with fluid.device_guard("gpu:0"): + x = fluid.layers.data(name='x', shape=[1], dtype='int64', lod_level=0) + y = fluid.layers.data(name='y', shape=[1], dtype='int64', lod_level=0) + data_loader = fluid.io.DataLoader.from_generator( + feed_list=[x, y], + capacity=64, + use_double_buffer=True, + iterable=False) + + emb_x = layers.embedding(input=x, param_attr=fluid.ParamAttr(name="embx"), size=[10,2], is_sparse=False) + emb_y = layers.embedding(input=y, param_attr=fluid.ParamAttr(name="emby",learning_rate=0.9), size=[10,2], is_sparse=False) + + with fluid.device_guard("gpu:1"): + concat = layers.concat([emb_x, emb_y], axis=1) + fc = layers.fc(input=concat, name="fc", size=1, num_flatten_dims=1, bias_attr=False) + loss = layers.reduce_mean(fc) + optimizer = fluid.optimizer.SGD(learning_rate=0.5) + optimizer = fluid.optimizer.PipelineOptimizer(optimizer) + optimizer.minimize(loss) + + def train_reader(): + for _ in range(4): + x = np.random.random(size=[1]).astype('int64') + y = np.random.random(size=[1]).astype('int64') + yield x, y + data_loader.set_sample_generator(train_reader, batch_size=1) + + place = fluid.CUDAPlace(0) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + batch_size = 1 + data_loader.start() + exe.train_from_dataset( + fluid.default_main_program()) + data_loader.reset() + """ + + def __init__(self, optimizer, num_microbatches=1, start_cpu_core_id=0): + self._device = 'cpu' + if core.is_compiled_with_npu(): + self._device = "npu" + elif core.is_compiled_with_cuda(): + self._device = "gpu" + if framework._non_static_mode(): + raise Exception("In dygraph, don't support PipelineOptimizer.") + valid_optimizers = (Optimizer, paddle.optimizer.Optimizer, + paddle.fluid.contrib.mixed_precision.decorator. + OptimizerWithMixedPrecision) + if not isinstance(optimizer, valid_optimizers): + raise ValueError("The 'optimizer' parameter for " + "PipelineOptimizer must be an instance of " + "{}, but the given type is {}.".format( + valid_optimizers, type(optimizer))) + self._optimizer = optimizer + + # Get the original optimizer defined by users, such as SGD + self._origin_optimizer = self._optimizer + while hasattr(self._origin_optimizer, "inner_opt"): + self._origin_optimizer = self._origin_optimizer.inner_opt + + assert num_microbatches >= 1, ( + "num_microbatches must be a positive value.") + self._num_microbatches = num_microbatches + assert start_cpu_core_id >= 0, ( + "start_cpu_core_id must be a non-negative integer.") + self._start_cpu_core_id = start_cpu_core_id + self._place_list = None + op_maker = core.op_proto_and_checker_maker + self._op_role = op_maker.OpRole + self._op_role_key = op_maker.kOpRoleAttrName() + self._op_role_var_key = op_maker.kOpRoleVarAttrName() + self._op_device_key = op_maker.kOpDeviceAttrName() + self._param_device_map = None + self._pipeline_pair = [] + self._pp_ring_map = dict() + self.output_var_to_op = None + self.input_var_to_op = None + + # insert allreduce op to sync global information for global + # gradient clip and amp + def _insert_allreduce_op(self, op_idx, block): + """ + Insert allreduce op to sync global information for global + gradient clip and amp. + """ + op = block.ops[op_idx] + out_name = op.desc.output_arg_names()[0] + out_var = block.var(out_name) + offset = 0 + if op.type == "reduce_any": + # cast the bool var to int32 to use allreduce_max op + temp_var_name = unique_name.generate(out_name + "_cast_int32") + temp_var = block.create_var(name=temp_var_name, + shape=[1], + dtype="int32") + block._insert_op(op_idx + 1 + offset, + type='cast', + inputs={'X': out_var}, + outputs={'Out': temp_var}, + attrs={ + 'in_dtype': out_var.dtype, + 'out_dtype': temp_var.dtype, + self._op_role_key: self._op_role.Optimize + }) + offset += 1 + block._insert_op( + op_idx + 1 + offset, + type='c_allreduce_max' + if op.type == "reduce_any" else 'c_allreduce_sum', + inputs={'X': temp_var if op.type == "reduce_any" else out_var}, + outputs={'Out': temp_var if op.type == "reduce_any" else out_var}, + attrs={ + 'ring_id': self.global_ring_id, + self._op_role_key: self._op_role.Optimize, + 'use_calc_stream': True + }) + offset += 1 + if op.type == "reduce_any": + block._insert_op(op_idx + 1 + offset, + type='cast', + inputs={'X': temp_var}, + outputs={'Out': out_var}, + attrs={ + 'in_dtype': temp_var.dtype, + 'out_dtype': out_var.dtype, + self._op_role_key: self._op_role.Optimize + }) + offset += 1 + return offset + + def _create_vars(self, block, ori_block): + # Create vars for block, copied from ori_block + used_var_set = set() + added_op_num = 0 + op_idx = 0 + op_size = block.desc.op_size() + while op_idx < op_size + added_op_num: + # Whether to insert allreduce_sum or allreduce_max op. + # For amp and global gradient clip strategies, we should + # get the global information, so allreduce op is needed. + should_insert = False + op = block.ops[op_idx] + # For op process vars on all devices, remove its input + # vars not in this block + reserved_x = [] + if op.type == 'reduce_any' and self._is_optimize_op(op): + should_insert = True + elif op.type == 'concat' and self._is_optimize_op(op): + for input_name in op.desc.input("X"): + if block._find_var_recursive(input_name): + reserved_x.append(input_name) + op.desc.set_input('X', reserved_x) + elif op.type == 'update_loss_scaling': + for input_name in op.desc.input("X"): + if block._find_var_recursive(input_name): + reserved_x.append(input_name) + op.desc.set_input('X', reserved_x) + op.desc.set_output('Out', reserved_x) + elif op.type == 'check_finite_and_unscale': + for input_name in op.desc.input("X"): + if block._find_var_recursive(input_name): + reserved_x.append(input_name) + op.desc.set_input('X', reserved_x) + op.desc.set_output('Out', reserved_x) + if len(reserved_x) == 0: + block._remove_op(op_idx) + op_size -= 1 + continue + elif op.type == 'sum' and self._is_gradient_clip_op(op): + for input_name in op.desc.input("X"): + if block._find_var_recursive(input_name): + reserved_x.append(input_name) + op.desc.set_input('X', reserved_x) + should_insert = True + + vars = op.desc.input_arg_names() + op.desc.output_arg_names() + for var in vars: + # a var whose name contains "blocking_queue" + # only exists in startup program + if var in used_var_set or "_blocking_queue" in var: + continue + used_var_set.add(var) + if block._find_var_recursive(str(var)): continue + source_var = ori_block._var_recursive(str(var)) + if source_var.type == core.VarDesc.VarType.READER: + dest_var = block.create_var( + name=var, + type=core.VarDesc.VarType.READER, + persistable=source_var.persistable) + elif isinstance(source_var, Parameter): + dest_var = block.create_parameter( + name=source_var.name, + shape=source_var.shape, + dtype=source_var.dtype, + type=source_var.type, + lod_level=source_var.lod_level, + stop_gradient=source_var.stop_gradient, + trainable=source_var.trainable, + optimize_attr=source_var.optimize_attr, + regularizer=source_var.regularizer, + error_clip=source_var.error_clip) + else: + dest_var = block._clone_variable(source_var, False) + self._clone_var_attr(dest_var, source_var) + # When use with sharding, allreduce_sum and allreduce_max + # used for global gradient clip and amp will be added by sharding. + op_idx += 1 + if self.use_sharding or not should_insert: continue + inserted_ops = self._insert_allreduce_op(op_idx - 1, block) + added_op_num += inserted_ops + op_idx += inserted_ops + block._sync_with_cpp() + + def _is_loss_grad_op(self, op): + assert self._op_role_key in op.attr_names + op_role = int(op.attr(self._op_role_key)) + return op_role & int(self._op_role.Backward) and op_role & int( + self._op_role.Loss) + + def _is_forward_op(self, op): + return self._op_role_key in op.attr_names and (int( + op.attr(self._op_role_key)) == int(self._op_role.Forward)) + + def _is_backward_op(self, op): + return self._op_role_key in op.attr_names and ( + int(op.attr(self._op_role_key)) & int(self._op_role.Backward)) + + def _is_loss_op(self, op): + assert self._op_role_key in op.attr_names + return int(op.attr(self._op_role_key)) == int(self._op_role.Loss) + + def _is_optimize_op(self, op): + return self._op_role_key in op.attr_names and ( + int(op.attr(self._op_role_key)) & int(self._op_role.Optimize)) + + def _is_update_op(self, op): + return 'Param' in op.input_names and 'Grad' in op.input_names and ( + "LearningRate" in op.input_names) + + def _split_program(self, main_program, devices): + """ + Split a program into sections according to devices that ops run on. + The op whose op_device attr is "gpu:all" is copied to all sections. + + Args: + main_program (Program): the main program + devices: all used devices + """ + # Map from device to its corresponding section program info + device_program_map = defaultdict(Program) + + block = main_program.block(0) + for op in block.ops: + device = op.attr(self._op_device_key) + # Copy ops whose op_device set to "gpu:all" to all sections. + if device == f"{self._device}:all": + for device in devices: + program = device_program_map[device] + op_desc = op.desc + ap_op = program.global_block().desc.append_op() + ap_op.copy_from(op_desc) + ap_op._set_attr(self._op_device_key, "") + else: + program = device_program_map[device] + op_desc = op.desc + ap_op = program.global_block().desc.append_op() + ap_op.copy_from(op_desc) + ap_op._set_attr(self._op_device_key, "") + + program_list = [] + for key in devices: + program = device_program_map[key] + program._sync_with_cpp() + program_list.append(program) + + return program_list + + def _get_op_device_for_startup_program(self, var_name): + """ + For adam optimizer, it will add accumulators and initialize them + with fill_constant, and force the op device to cpu. Hence, we should + get the real op_device attribute of the fill_constant as the device + where the corresponding parameters on. + """ + assert "beta1_pow_acc" in var_name or "beta2_pow_acc" in var_name, \ + 'For accumulators for Adam, the name must contain beta1_pow_acc ' \ + 'or beta2_pow_acc.' + param_name = var_name[0:var_name.index('_beta')] + device = self._param_device_map[param_name] + return device + + def _split_startup_program(self, startup_program, device_id): + block = startup_program.global_block() + new_startup_program = Program() + for op in block.ops: + device = op.attr(self._op_device_key) + if device == "cpu": + assert op.type == "fill_constant", ( + "For ops in startup program with the op_device attribute " + "of cpu, they must be of type fill_constant.") + output_var = op.output_arg_names[0] + device = self._get_op_device_for_startup_program(output_var) + + if device: + device_index = int(device.split(':')[1]) + else: + # LR related ops + device = None + if device and device_index != device_id: continue + op_desc = op.desc + ap_op = new_startup_program.global_block().desc.append_op() + ap_op.copy_from(op_desc) + ap_op._set_attr(self._op_device_key, "") + new_startup_program._sync_with_cpp() + self._create_vars(new_startup_program.global_block(), block) + return new_startup_program + + def _find_post_op(self, index, var_name): + """ + Find the post op that has variable named var_name as input. + """ + # bugfix for uniform hybrid parallelism + if '.cast_fp32' in var_name: + var_name = var_name.replace('.cast_fp32', '') + if '.cast_fp16' in var_name: + var_name = var_name.replace('.cast_fp16', '') + + post_ops = self.input_var_to_op[var_name] + if post_ops == None: return None + result_op = None + for post_op, post_idx in reversed(post_ops): + if post_idx > index: + result_op = post_op + break + return result_op + + def _find_prev_op(self, index, var_name): + """ + Find the previous op of op with index that outputs + variable named var_name. + """ + prev_ops = self.output_var_to_op[var_name] + if prev_ops == None: return None + result_op = None + for prev_op, prev_idx in reversed(prev_ops): + if prev_idx < index: + result_op = prev_op + break + return result_op + + def _rename_arg(self, op, old_name, new_name): + op._rename_input(old_name, new_name) + op._rename_output(old_name, new_name) + + def _create_var(self, block, ref_var, name, dtype=None): + """ + Create a new var for block, which has the same type, + shape and dtype as ref_var, then rename it with the + name `name`. + """ + new_var = block.create_var( + name=name, + shape=ref_var.shape, + dtype=ref_var.dtype if dtype is None else dtype, + type=ref_var.type, + lod_level=ref_var.lod_level, + persistable=ref_var.persistable, + is_data=ref_var.is_data, + need_check_feed=ref_var.desc.need_check_feed()) + self._clone_var_attr(new_var, ref_var) + return new_var + + def _clone_var_attr(self, dest, src): + dest.stop_gradient = src.stop_gradient + if hasattr(src, 'is_distributed'): + dest.is_distributed = src.is_distributed + + def _strip_grad_suffix(self, name): + """ + Strip the grad suffix from the given variable name + """ + pos = name.find(core.grad_var_suffix()) + return name[:pos] if pos != -1 else name + + def _append_grad_suffix(self, name): + """ + Append grad suffix to the given variable name + """ + return name + core.grad_var_suffix() + + def _get_op_device_attr(self, op): + """ + Get the op_device attribute of a op. + """ + device = op.attr(self._op_device_key) \ + if op.has_attr(self._op_device_key) else None + if device: + assert device[0:3] == 'gpu' or device[0:3] == 'npu', "Now, only gpu and npu devices are " \ + "supported in pipeline parallemism." + return device + + def _add_op_device_attr_for_op(self, op, idx, block): + """ + Add op_device attrribute for ops that have not that attribute set. + We use "gpu:all" to represent the op should be put on all + sub-programs, such as lr-related ops. Note that: "gpu:all" + is only used by pipeline as an indicator. + """ + lrsched_role = int(self._op_role.LRSched) + if op.attr(self._op_role_key) == lrsched_role: + # For LRSched ops, we should put them on all sub-programs to + # make sure each sub-program update the lr correctly + op._set_attr(self._op_device_key, f"{self._device}:all") + # bugfix in hybrid parallelism + elif op.type == "sum" and self._is_backward_op(op): + # For sum ops that compute the sum of @RENAMED@ vars + for name in op.desc.input_arg_names(): + assert '@RENAME@' in name, \ + "The op must be sum used to accumulate renamed vars." + assert len(op.desc.output_arg_names()) == 1 + out_name = op.desc.output_arg_names()[0] + post_op = self._find_post_op(idx, out_name) + assert post_op.has_attr( + 'op_device'), "{} has no op_device attr for var {}".format( + post_op.type, out_name) + device = post_op.attr(self._op_device_key) + assert device, "The post op must have op_device set." + op._set_attr(self._op_device_key, device) + elif (op.type == "cast" + or op.type == "scale") and self._is_backward_op(op): + prev_op = self._find_prev_op(idx, op.desc.input("X")[0]) + op._set_attr(self._op_device_key, prev_op.attr(self._op_device_key)) + elif op.type == "memcpy" and not self._is_optimize_op(op): + # for checkpoint offloading + assert len(op.input_arg_names) == 1 and len( + op.output_arg_names) == 1 + input_name = op.input_arg_names[0] + output_name = op.output_arg_names[0] + if '@Fetch' in output_name: + post_op = self._find_post_op(idx, output_name) + op._set_attr(self._op_device_key, + post_op.attr(self._op_device_key)) + else: + prev_op = self._find_prev_op(idx, op.desc.input("X")[0]) + op._set_attr(self._op_device_key, + prev_op.attr(self._op_device_key)) + elif self._is_loss_op(op): + # For loss * loss_scaling op added by AMP + offset = 1 + while (not block.ops[idx + offset].has_attr(self._op_device_key) + or not block.ops[idx + offset].attr(self._op_device_key)): + offset += 1 + device = block.ops[idx + offset].attr(self._op_device_key) + assert device, "Please put you program within device_guard scope." + for i in range(offset): + block.ops[idx + i]._set_attr(self._op_device_key, device) + elif self._is_optimize_op(op) and op.type == "cast": + # For fp16-->fp32 cast added by AMP + grad_name = op.output('Out') + assert len(grad_name) == 1 + param_name = self._strip_grad_suffix(grad_name[0]) + device = self._param_device_map[param_name] + op._set_attr(self._op_device_key, device) + elif self._is_gradient_clip_op(op) or self._is_regularization_op(op): + # For gradient clip and regularization ops, we set their op_device + # attribute to the device where their corresponding parameters on. + assert self._op_role_var_key in op.attr_names, "gradient_clip " \ + "and regularization ops must have op_role_var attribute." + op_role_var = op.attr(self._op_role_var_key) + assert len(op_role_var) == 2, "op_role_var for gradient_clip " \ + "regularization ops must have two elements." + param_name = op_role_var[0] + device = self._param_device_map[param_name] + # For sum op added by global gradient clip, it must be + # put on all devices + if (op.type == 'sum' or op.type == 'sqrt' + or op.type == 'fill_constant' + or op.type == 'elementwise_max' + or op.type == 'elementwise_div'): + device = f"{self._device}:all" + op._set_attr(self._op_device_key, device) + elif op.type == "alloc_float_status" or op.type == "clear_float_status": + op._set_attr(self._op_device_key, f"{self._device}:all") + # NOTE(wangxi): NPU should only clear the float status + # once at each batch step + op._set_attr(self._op_role_key, self._op_role.LRSched) + + float_status_name = op.output_arg_names[0] + float_status_var = block.var(float_status_name) + # FIXME(wangxi): pipeline lr schedule will exec on sub_scope(0) + # while update will exec on sub_scope(last_micro_step), should + # set persistable to use global scope + float_status_var.persistable = True + else: + other_known_ops = [ + 'update_loss_scaling', 'reduce_any', 'concat', 'sum', + 'check_finite_and_unscale', 'memcpy' + ] + assert op.type in other_known_ops, "For other ops without " \ + "op_device set, they must be one of {}, but it " \ + "is {}".format(other_known_ops, op.type) + assert self._is_optimize_op(op) + op._set_attr(self._op_device_key, f"{self._device}:all") + + def _add_op_device_attr(self, block): + """ + Add op_device attrribute for ops in block that have + not that attribute set. + """ + for idx, op in enumerate(list(block.ops)): + if (op.type == "create_py_reader" or op.type == "read" + or op.type == "create_double_buffer_reader"): + # Copy read related ops to all section to make them exit + # after each epoch. + # We use "gpu:all" to represent the op should be put on all + # sub-programs, such as lr-related ops. Note that: "gpu:all" + # is only used by pipeline as an indicator. + op._set_attr(self._op_device_key, f"{self._device}:all") + continue + # op_device attribute has been set + if self._get_op_device_attr(op): continue + self._add_op_device_attr_for_op(op, idx, block) + + def _check_validation(self, block): + """ + Check whether ops in a block have both the op_device and the + op_role attributes set. + Then, return all devices in order. + """ + device_list = [] + # Section worker only supports the following op_role + valid_op_role_value = [ + int(self._op_role.LRSched), + int(self._op_role.Forward), + int(self._op_role.Backward), + int(self._op_role.Loss), + int(self._op_role.Optimize), + int(self._op_role.Backward) | int(self._op_role.Loss), + ] + for op in block.ops: + if not op._has_kernel(op.type): + assert op.type == "conditional_block" and (op.attr( + self._op_role_key) == int(self._op_role.LRSched)), ( + "Now, the only supported op without kernel is " + "conditional_block, and its op role must be LRSched.") + assert op.has_attr( + self._op_role_key), ("op ({}) has no {} attribute.".format( + op.type, self._op_role_key)) + op_role = op.attr(self._op_role_key) + assert int(op_role) in valid_op_role_value, \ + "op_role {} for op {} must be one of {}".format( + op_role, + op.type, + valid_op_role_value) + + assert op.has_attr( + self._op_device_key), ("op ({}) has no {} attribute.".format( + op.type, self._op_device_key)) + + device = op.attr(self._op_device_key) + assert device, ("op_device attribute for op " + "{} has not been set.".format(op.type)) + if device == f"{self._device}:all": continue + + dev_type = device.split(':')[0] + assert dev_type == "gpu" or dev_type == 'npu', ( + "Now only gpu and npu devices are supported " + "for pipeline parallelism.") + + if device not in device_list: + device_list.append(device) + + return device_list + + def _insert_sendrecv_ops_for_boundaries(self, block): + """ + Insert a pair of send and recv ops for every two + consecutive ops on different devices. + """ + # A map from var to device where op takes it as input, + # avoiding multiple send and recv ops. + input_var_to_device = dict() + # bugfix hybrid parallelism + first_optimize_index = None + for index, op in enumerate(list(block.ops)): + if self._is_optimize_op(op): + first_optimize_index = index + break + extra_index_info = { + 'index': 0, + 'first_optimize_index': first_optimize_index + } + + for index, op in enumerate(list(block.ops)): + cur_device = op.attr(self._op_device_key) + if cur_device == f"{self._device}:all": continue + for var_name in op.input_arg_names: + var = block.var(var_name) + # skip data var + if var.is_data: continue + prev_device = None + + prev_op = self._find_prev_op(index, var_name) + if prev_op is None: + if var_name not in self._param_device_map: + continue + prev_device = self._param_device_map[var_name] + + if not prev_device: + prev_device = prev_op.attr(self._op_device_key) \ + if prev_op else None + + if prev_device is None or prev_device == f"{self._device}:all": + continue + + if prev_device == cur_device: continue + + if var_name not in input_var_to_device: + input_var_to_device[var_name] = [] + if (cur_device, prev_device) in input_var_to_device[var_name]: + continue + + device_type = cur_device.split(':')[0] + ':' + + def _check_stage(cur_id, prev_id): + # check send/recv stage valid + is_forward = self._is_forward_op(op) + is_backward = self._is_backward_op(op) + assert is_forward or is_backward, \ + 'send/recv in pipeline should only be inserted in forward or backward,' \ + 'please check the op_role of op={}'.format(op) + + if is_forward: + assert prev_id < cur_id, \ + "In forward, send/recv can only be passed forward, but now " \ + "prev_stage={} great than cur_stage={}, please check op_device of op={}".format( + prev_id, cur_id, op) + elif is_backward: + assert prev_id > cur_id, \ + "In backward, send/recv can only be passed backward, but now " \ + "prev_stage={} less than cur_stage={}, please check op_device of op={}".format( + prev_id, cur_id, op) + + def _insert_send_recv(cur_id, prev_id): + cur_dev = device_type + str(cur_id) + prev_dev = device_type + str(prev_id) + if (cur_dev, prev_dev) in input_var_to_device[var_name]: + return + + if cur_id - prev_id > 1: + _insert_send_recv(cur_id - 1, prev_id) + _insert_send_recv(cur_id, cur_id - 1) + input_var_to_device[var_name].append( + (cur_dev, prev_dev)) + return + elif cur_id - prev_id < -1: + _insert_send_recv(cur_id + 1, prev_id) + _insert_send_recv(cur_id, cur_id + 1) + input_var_to_device[var_name].append( + (cur_dev, prev_dev)) + return + + assert abs(cur_id - prev_id) == 1 + input_var_to_device[var_name].append((cur_dev, prev_dev)) + + op_role = op.attr(self._op_role_key) + var = block.vars[var_name] + pair = (prev_id, cur_id) + # 1000 is just a magic number + pair_key = prev_id * 1000 + cur_id + if pair not in self._pipeline_pair: + self._pipeline_pair.append(pair) + self._pp_ring_map[pair_key] = self.ring_id + ring_id = self.ring_id + self.ring_id += 1 + else: + ring_id = self._pp_ring_map[pair_key] + + if self.schedule_mode == 'F-then-B': # F-then-B + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='send_v2', + inputs={'X': var}, + attrs={ + self._op_device_key: prev_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'peer': 1, + 'ring_id': ring_id + }) + extra_index_info['index'] += 1 + var_shape = list(var.shape) + var_shape[0] = self.micro_batch_size if var_shape[ + 0] < 0 else var_shape[0] + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='recv_v2', + outputs={'Out': [var]}, + attrs={ + 'out_shape': var_shape, + 'dtype': var.dtype, + self._op_device_key: cur_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'peer': 0, + 'ring_id': ring_id + }) + extra_index_info['index'] += 1 + elif self.schedule_mode == '1F1B': # 1F1B + var_shape = list(var.shape) + var_shape[0] = self.micro_batch_size if var_shape[ + 0] < 0 else var_shape[0] + + numel = np.prod(var_shape) + use_mp = (self.mp_degree > 1) and (numel % + self.mp_degree == 0) + + if 'subprog' in var.name: + # For recompute, if the checkpoints var is layer_norm_6.tmp_2 + # this var will be sent twice, layer_norm_6.tmp_2 for forward pass, + # layer_norm_6.tmp_2.subprog_* for recompute pass. + # We can store the first sent var and copy the value to the + # second one to reduce one send/recv op. + # The origin_ckpt_name is layer_norm_6.tmp_2, which will be used + # to find the stored var for the forward pass. + origin_name = var.name.split('subprog')[0][0:-1] + associate_var = block.var(origin_name) + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='assign', + inputs={'X': [associate_var]}, + outputs={'Out': [var]}, + attrs={ + 'out_shape': var_shape, + 'dtype': var.dtype, + self._op_device_key: cur_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + }) + extra_index_info['index'] += 1 + return + + _check_stage(cur_id, prev_id) + + block._insert_op_without_sync(index=index + + extra_index_info['index'], + type='c_sync_calc_stream', + inputs={'X': [var]}, + outputs={'Out': [var]}, + attrs={ + self._op_device_key: + prev_dev, + self._op_role_key: + op_role, + }) + extra_index_info['index'] += 1 + prefix_name = var.name.split('@')[0] + prefix_var = block.var(prefix_name) + is_param = True if isinstance(prefix_var, + Parameter) else False + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='send_v2' + if not use_mp or is_param else 'partial_send', + inputs={'X': var}, + attrs={ + self._op_device_key: prev_dev, + self._op_role_key: op_role, + 'use_calc_stream': False, + 'ring_id': ring_id, + 'peer': 1, + # if send_v2, num&id attr is not in op_attrs, will not insert + 'num': self.mp_degree, + 'id': self.mp_rank, + }) + extra_index_info['index'] += 1 + insert_index = None + if int(op_role) == int(self._op_role.Backward): + insert_index = extra_index_info[ + 'first_optimize_index'] + new_op_role = self._op_role.Optimize + else: + insert_index = index + new_op_role = self._op_role.Backward + sync_comm_op = block._insert_op_without_sync( + index=insert_index + extra_index_info['index'], + type='c_sync_comm_stream', + inputs={'X': [var]}, + outputs={'Out': [var]}, + attrs={ + self._op_device_key: prev_dev, + self._op_role_key: new_op_role, + 'ring_id': ring_id, + }) + if int(op_role) == int(self._op_role.Forward): + sync_comm_op._set_attr('pipeline_flag', '') + extra_index_info['index'] += 1 + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='recv_v2' + if not use_mp or is_param else 'partial_recv', + outputs={'Out': [var]}, + attrs={ + 'out_shape': var_shape, + 'dtype': var.dtype, + self._op_device_key: cur_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'peer': 0, + 'ring_id': ring_id, + # if recv_v2, num&id attr is not in op_attrs, will not insert + 'num': self.mp_degree, + 'id': self.mp_rank, + }) + extra_index_info['index'] += 1 + if use_mp and not is_param: + block._insert_op_without_sync( + index=index + extra_index_info['index'], + type='partial_allgather', + inputs={'X': [var]}, + outputs={'Out': [var]}, + attrs={ + self._op_device_key: cur_dev, + self._op_role_key: op_role, + 'use_calc_stream': True, + 'ring_id': 0, + # if recv_v2, num&id attr is not in op_attrs, will not insert + 'nranks': self.mp_degree, + 'rank': self.mp_rank, + }) + extra_index_info['index'] += 1 + else: + raise ValueError( + "Now only 'F-then-B' and '1F1B' are supported." + "The given value is {}.".format(self.schedule_mode)) + + _insert_send_recv(int(cur_device.split(':')[1]), + int(prev_device.split(':')[1])) + block._sync_with_cpp() + + def _insert_loss_scale(self, block): + """ + Scale the loss corresponding to number of micro-batches. + """ + if self._num_microbatches == 1: return + for index, op in reversed(tuple(enumerate(list(block.ops)))): + if self._is_loss_grad_op(op): + assert op.type == 'fill_constant', \ + "loss_grad_op must be fill_constant op, " \ + "but this op is {}".format(op.type) + assert op.has_attr('value') + loss_scale = float(op.attr('value')) + loss_scale = loss_scale / self._num_microbatches + op._set_attr('value', loss_scale) + break + + def _rename_gradient_var_name(self, block): + for index, op in enumerate(block.ops): + if not self._is_optimize_op(op): continue + input_names = op.input_arg_names + output_names = op.output_arg_names + in_out_names = input_names + output_names + if op.type == 'cast' or op.type == "c_sync_comm_stream": continue + # append "MERGED" to the names of parameter gradients, + # and mofify the op_role_var attribute (by rename_arg func). + for name in in_out_names: + if not core.grad_var_suffix() in name: continue + param_name = name.strip(core.grad_var_suffix()) + new_grad_name = name + "@MERGED" + self._rename_arg(op, name, new_grad_name) + + def _accumulate_gradients(self, + block, + pp_allreduce_in_optimize=False, + strategy=None, + shard=None): + """ + Create a new merged gradient for each parameter and accumulate the + corresponding gradient to it. + """ + fp16_allreduce = strategy.fp16_allreduce if strategy else False + if strategy and strategy.fuse_grad_merge: + fused_gradient_names = self._accumulate_gradients_with_fuse( + block, fp16_allreduce, strategy.fuse_grad_size_in_MB, shard) + return fused_gradient_names + + merged_gradient_names = [] + first_opt_op_idx = None + + merged_suffix = '@MERGED@FP16' if fp16_allreduce else '@MERGED' + dtype = paddle.float16 if fp16_allreduce else None + + for index, op in reversed(tuple(enumerate(list(block.ops)))): + # remove the cast op of fp16 grad to fp32 grad + if self._is_optimize_op(op) and op.type == 'cast': + in_name = op.input_arg_names[0] + out_name = op.output_arg_names[0] + if out_name.strip('@GRAD') in self._param_device_map: + assert in_name.replace('.cast_fp16', '') == out_name + block._remove_op(index) + continue + + if self._is_backward_op(op) and first_opt_op_idx is None: + first_opt_op_idx = index + 1 + # maybe have no optimize + # if first_opt_op_idx == len(block.ops): return + + if self._is_backward_op(op) and (self._op_role_var_key + in op.attr_names): + op_role_var = op.attr(self._op_role_var_key) + if len(op_role_var) == 0: continue + assert len(op_role_var) % 2 == 0 + for i in range(0, len(op_role_var), 2): + offset = 0 + param_name = op_role_var[i] + if not block.has_var(param_name): continue + if '@BroadCast' in param_name: continue + + param_grad_name = param_name + core.grad_var_suffix() + merged_param_grad_name = param_grad_name + merged_suffix + if not block.has_var(merged_param_grad_name): + self._create_var(block, block.vars[param_name], + merged_param_grad_name, dtype) + assert block.has_var(merged_param_grad_name) + + param_grad_var = block.var(param_grad_name) + merged_param_grad_var = block.var(merged_param_grad_name) + merged_param_grad_var.persistable = True + block._insert_op( + index=first_opt_op_idx + offset, + type='fill_constant', + inputs={}, + outputs={'Out': [merged_param_grad_var]}, + attrs={ + 'shape': + merged_param_grad_var.shape, + 'dtype': + merged_param_grad_var.dtype, + 'value': + float(0), + # a trick to run this op once per mini-batch + self._op_role_key: + self._op_role.Optimize.LRSched, + }) + offset += 1 + grad_name = op_role_var[i + 1] + grad_var = block.vars[grad_name] + + is_fp16_grad = 'cast_fp16' in grad_name + need_cast = (is_fp16_grad is not fp16_allreduce) + + if need_cast: + # if fp16_allreduce: + # cast grad to fp16 to accumulate to merged gradient + # else: + # cast grad to fp32 to accumulate to merged gradient + cast_grad_var_name = param_grad_name + '@TMP' + cast_grad_var = self._create_var( + block, param_grad_var, cast_grad_var_name, dtype) + cast_grad_var.persistable = False + block._insert_op(index=first_opt_op_idx + offset, + type='cast', + inputs={'X': grad_var}, + outputs={'Out': cast_grad_var}, + attrs={ + 'in_dtype': + grad_var.dtype, + 'out_dtype': + cast_grad_var.dtype, + self._op_role_key: + self._op_role.Backward, + }) + offset += 1 + grad_var = cast_grad_var + + block._insert_op( + index=first_opt_op_idx + offset, + type='sum', + inputs={'X': [merged_param_grad_var, grad_var]}, + outputs={'Out': merged_param_grad_var}, + attrs={ + self._op_role_key: self._op_role.Backward, + }) + offset += 1 + merged_gradient_names.append(merged_param_grad_name) + + if not fp16_allreduce: return merged_gradient_names + + first_opt_op_idx = None + for index, op in reversed(tuple(enumerate(list(block.ops)))): + if self._is_backward_op(op) and first_opt_op_idx is None: + first_opt_op_idx = index + 1 + break + assert first_opt_op_idx is not None + + # insert cast op from fp16->fp32 + # FIXME(wangxi): maybe put in sharding is better, for some grad + # is not in sharding device. + for fp16_grad_name in merged_gradient_names: + grad_name = fp16_grad_name.replace('@FP16', '') + param_name = fp16_grad_name.replace('@GRAD@MERGED@FP16', '') + + if not block.has_var(grad_name): + self._create_var(block, block.vars[param_name], grad_name) + assert block.has_var(grad_name) + + fp16_grad_var = block.var(fp16_grad_name) + grad_var = block.var(grad_name) + grad_var.persistable = False + + block._insert_op(index=first_opt_op_idx, + type='cast', + inputs={'X': fp16_grad_var}, + outputs={'Out': grad_var}, + attrs={ + 'in_dtype': fp16_grad_var.dtype, + 'out_dtype': grad_var.dtype, + self._op_role_key: self._op_role.Optimize, + }) + + return merged_gradient_names + + def _insert_accumulate_gradients_with_fuse(self, main_block, fp16, + fused_size, grad_param_pairs, + first_opt_op_idx): + grad_param_pairs = self._sort_grad_param_by_dtype( + main_block, grad_param_pairs) + + grad_param_segments = [] + merged_suffix = '@MERGED@FP16' if fp16 else '@MERGED' + dtype = paddle.float16 if fp16 else paddle.float32 + cur_size = 0. + last_dtype = None + # split the grad based on dtype and fused size + for grad, param in grad_param_pairs: + real_grad = main_block.var(grad) + # create the gradient merged var for each grad + merged_grad_var = main_block.create_var( + name=param + core.grad_var_suffix() + merged_suffix, + dtype=dtype, + shape=real_grad.shape, + persistable=True, + stop_gradient=False) + real_param = main_block.var(param) + if hasattr(real_param, 'is_distributed'): + merged_grad_var.is_distributed = real_param.is_distributed + tmp_size = self._get_var_size(real_grad) + # two strategies for splitting the grad + # 1. the current segment's size reach the user defined grad_size_in_MB + # 2. the upcoming grad holds different dtype compared with grads in current segment + if len(grad_param_segments) == 0 \ + or cur_size + tmp_size > fused_size \ + or real_grad.dtype != last_dtype: + grad_param_segments.append( + ([real_grad], [real_param], [merged_grad_var])) + last_dtype = real_grad.dtype + cur_size = 0. + else: + grad_param_segments[-1][0].append(real_grad) + grad_param_segments[-1][1].append(real_param) + grad_param_segments[-1][2].append(merged_grad_var) + cur_size += tmp_size + + fused_gradients = [] + fused_merged_gradients = [] + # create fused vars for grad and param + for grad_param_segment in grad_param_segments: + grad_segment = grad_param_segment[0] + merged_grad_segment = grad_param_segment[2] + fused_grad = main_block.create_var(name='FusedGrad_{}'.format( + grad_segment[0].name), + dtype=grad_segment[0].dtype, + persistable=False, + stop_gradient=False) + # keep the '.cast_fp16' info in the fuse var name + fused_merged_grad_name_prefix = 'FusedMergedGrad.cast_fp16.' if \ + merged_grad_segment[0].dtype == paddle.float16 else 'FusedMergedGrad' + fused_merged_grad_name = fused_merged_grad_name_prefix + '_{}'.format( + merged_grad_segment[0].name) + fused_merged_grad = main_block.create_var( + name=fused_merged_grad_name, + dtype=merged_grad_segment[0].dtype, + persistable=True, + stop_gradient=False) + fused_gradients.append(fused_grad) + fused_merged_gradients.append(fused_merged_grad) + + assert len(fused_gradients) == len(grad_param_segments) + assert len(fused_merged_gradients) == len(grad_param_segments) + + # insert coalesce op at the start of the backward pass + # use param as the coalesce input to make sure the two Fused vars are in same shape + first_back_op_idx = None + for index, op in enumerate(main_block.ops): + if self._is_backward_op(op) and first_back_op_idx is None: + first_back_op_idx = index + break + assert first_back_op_idx is not None + offset = 0 + for i in range(len(grad_param_segments)): + fused_grad = fused_gradients[i] + fused_merged_grad = fused_merged_gradients[i] + grads = grad_param_segments[i][0] + params = grad_param_segments[i][1] + merged_grads = grad_param_segments[i][2] + main_block._insert_op_without_sync( + first_back_op_idx + offset, + type="coalesce_tensor", + inputs={"Input": params}, + outputs={ + "Output": grads, + "FusedOutput": fused_grad + }, + attrs={ + # Explanation of user_defined_size_of_dtype: + # In coalesce op, the align size is 256 bytes + # the float takes 4 bytes while fp16 takes 2 bytes. + # To meet the requirement, 128 fp16 or 64 float will be aligned + # Think the total shape of the input tensors if [64], + # if the dtype is float, then the shape of the fuse var is [64] + # however if the dytpe if fp16, the shape of the fuse var is [128], + # which will cause the fused vars' shape vary between each other. + # To make sure the shape of the fused vars are identical, + # we set the dtype of float and fp16 both to 2. + # Under this way, the fused vars' shape for float and fp16 are all [128] + "user_defined_size_of_dtype": 2, + "copy_data": False, + "use_align": True, + "dtype": grads[0].dtype, + self._op_role_key: self._op_role.Backward, + # On npu, the nan/inf check login is different with gpu. + # If there are some not initialized sections in the fused var, + # and the value in those sections are nan/inf, it will trigger the nan/inf check. + # To avoid these problematic triggers, set constant is needed for npu + "set_constant": core.is_compiled_with_npu(), + "constant": float(0.0), + }) + offset += 1 + # For the gradient_merged_fused_var, given a init value during the coalesce op + # this will remove a problematic fill_constant op. This op role of this coalesce + # is set to be LRSched to make this coalesce (with init) only run once + main_block._insert_op_without_sync( + first_back_op_idx + offset, + type="coalesce_tensor", + inputs={"Input": params}, + outputs={ + "Output": merged_grads, + "FusedOutput": fused_merged_grad + }, + attrs={ + "user_defined_size_of_dtype": 2, + "set_constant": True, + "constant": float(0.0), + "copy_data": False, + "use_align": True, + "dtype": merged_grads[0].dtype, + self._op_role_key: self._op_role.Optimize.LRSched + }) + offset += 1 + + # insert gradient merge relating ops + first_opt_op_idx += offset + offset = 0 + for i in range(len(fused_gradients)): + fused_grad = fused_gradients[i] + fused_merged_grad = fused_merged_gradients[i] + is_fp16_grad = 'cast_fp16' in fused_grad.name + need_cast = (is_fp16_grad is not fp16) + if need_cast: + # for fp16 allreduce, cast fp32 grad to fp16 + # for fp32 allreduce, cast fp16 grad to fp32 + cast_grad_var_name = fused_grad.name + '@TMP' + cast_grad_var = main_block.create_var(name=cast_grad_var_name, + dtype=dtype, + persistable=False, + stop_gradient=False) + main_block._insert_op(index=first_opt_op_idx + offset, + type='cast', + inputs={'X': fused_grad}, + outputs={'Out': cast_grad_var}, + attrs={ + 'in_dtype': fused_grad.dtype, + 'out_dtype': cast_grad_var.dtype, + self._op_role_key: + self._op_role.Backward, + }) + offset += 1 + fused_grad = cast_grad_var + main_block._insert_op( + index=first_opt_op_idx + offset, + type='sum', + inputs={'X': [fused_merged_grad, fused_grad]}, + outputs={'Out': fused_merged_grad}, + attrs={self._op_role_key: self._op_role.Backward}) + offset += 1 + + if fp16: + # if using fp16 allreduce, the optimizer needs fp32 grads, cast them back to fp32 + for grad, param in grad_param_pairs: + real_grad = main_block.var(grad) + fp16_grad_name = param + core.grad_var_suffix() + '@MERGED@FP16' + assert main_block.has_var(fp16_grad_name) + fp16_grad = main_block.var(fp16_grad_name) + fp32_grad_name = param + core.grad_var_suffix() + '@MERGED' + fp32_grad = main_block.create_var(name=fp32_grad_name, + dtype=paddle.float32, + shape=real_grad.shape, + persistable=False, + stop_gradient=False) + main_block._insert_op(index=first_opt_op_idx + offset, + type='cast', + inputs={'X': fp16_grad}, + outputs={'Out': fp32_grad}, + attrs={ + 'in_dtype': paddle.float16, + 'out_dtype': paddle.float32, + self._op_role_key: + self._op_role.Optimize, + }) + offset += 1 + + # replace the var with it's name, which will be used for inserting allreduce + for i in range(len(fused_merged_gradients)): + fused_merged_gradients[i] = fused_merged_gradients[i].name + + return fused_merged_gradients, first_opt_op_idx + + def _accumulate_gradients_with_fuse(self, + main_block, + fp16, + fused_size, + shard=None): + first_opt_op_idx = None + grad_param_pairs = [] + # obtain all param/grad pairs that needed to be fused + for index, op in reversed(tuple(enumerate(list(main_block.ops)))): + # remove the cast op of fp16 grad to fp32 grad + if self._is_optimize_op(op) and op.type == 'cast': + in_name = op.input_arg_names[0] + out_name = op.output_arg_names[0] + if out_name.strip('@GRAD') in self._param_device_map: + assert in_name.replace('.cast_fp16', '') == out_name + main_block._remove_op(index) + continue + + if self._is_backward_op(op) and first_opt_op_idx is None: + first_opt_op_idx = index + 1 + # no optimize phase + if first_opt_op_idx == len(main_block.ops): + return + + if self._is_backward_op(op) and (self._op_role_var_key + in op.attr_names): + op_role_var = op.attr(self._op_role_var_key) + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + for i in range(0, len(op_role_var), 2): + param_name = op_role_var[i] + if not main_block.has_var(param_name): + continue + if '@BroadCast' in param_name: + continue + grad_param_pairs.append( + (op_role_var[i + 1], op_role_var[i])) + + if len(grad_param_pairs) == 0: + return + + nranks = shard.worker_num if shard else 1 + device_to_pairs = [[] for _ in range(nranks)] + for pair in grad_param_pairs: + root_id = shard.device(pair[1]) if shard else 0 + assert 0 <= root_id < nranks + device_to_pairs[root_id].append(pair) + + all_fused_merged_gradients = [] + for pairs in device_to_pairs: + fused_merged_gradients, first_opt_op_idx = \ + self._insert_accumulate_gradients_with_fuse( + main_block, fp16, fused_size, pairs, first_opt_op_idx) + all_fused_merged_gradients += fused_merged_gradients + + main_block._sync_with_cpp() + return all_fused_merged_gradients + + def _sort_grad_param_by_dtype(self, main_block, grad_param_pairs): + # sort the grad param paris by the dtype + fp16_pairs = [] + fp32_pairs = [] + other_pairs = [] + for pairs in grad_param_pairs: + dtype = main_block.var(pairs[0]).dtype + if dtype == paddle.float32: + fp32_pairs.append(pairs) + elif dtype == paddle.float16: + fp16_pairs.append(pairs) + else: + other_pairs.append(pairs) + sorted_pairs = fp16_pairs + sorted_pairs.extend(fp32_pairs) + sorted_pairs.extend(other_pairs) + return sorted_pairs + + def _get_var_size(self, var): + dtype_to_size = { + core.VarDesc.VarType.FP16: 2, + core.VarDesc.VarType.FP32: 4, + core.VarDesc.VarType.FP64: 8, + core.VarDesc.VarType.INT16: 2, + core.VarDesc.VarType.INT32: 4, + core.VarDesc.VarType.INT64: 8, + core.VarDesc.VarType.BOOL: 1, + core.VarDesc.VarType.UINT8: 1, + } + assert -1 not in var.shape + return reduce(lambda x, y: x * y, + var.shape) * dtype_to_size[var.dtype] / 1024.0 / 1024.0 + + def _add_sub_blocks(self, main_block, program_list): + main_program = main_block.program + for prog in program_list: + for op in prog.block(0).ops: + if not op.has_attr('sub_block'): + continue + origin_sub_block_id = op.attr('sub_block').id + origin_sub_block = main_program.block(origin_sub_block_id) + new_sub_block = prog._create_block(parent_idx=0) + for sub_op in origin_sub_block.ops: + op_desc = sub_op.desc + ap_op = new_sub_block.desc.append_op() + ap_op.copy_from(op_desc) + new_sub_block._sync_with_cpp() + self._create_vars(new_sub_block, origin_sub_block) + op._set_attr('sub_block', new_sub_block) + + def _get_device_info(self, block): + for op in block.ops: + if not op._has_kernel(op.type): continue + op_device = op.attr(self._op_device_key) + return op_device + + def _process_persistable_vars_in_multi_sections(self, main_program, + startup_prog, program_list): + """ + Special Case: process persistable vars that exist in + multiple sections, e.g., shared weight + """ + # var_info = {var_name: [program1, program2...]}, + # persistable var only + var_info = dict() + for prog in program_list: + block = prog.block(0) + for var_name in block.vars: + if var_name == "double_buffer_0": continue + var = block.var(var_name) + if not var.persistable: continue + if not var_name in var_info: + var_info[var_name] = [] + if not prog in var_info[var_name]: + var_info[var_name].append(prog) + for var_name in list(var_info.keys()): + if len(var_info[var_name]) == 1: + var_info.pop(var_name) + + # write_info = {var_name: program}, where program is the only program + # in which the var named var_name is written. + write_info = dict() + for var_name in var_info.keys(): + for prog in var_info[var_name]: + block = prog.block(0) + for op in block.ops: + if op.type == "recv_v2" or op.type == "create_py_reader" or \ + op.type == "read" or op.type == "update_loss_scaling": + continue + # We have processed lr related vars + if op.attr(self._op_role_key) == int( + self._op_role.Optimize.LRSched): + continue + if var_name in op.desc.output_arg_names(): + assert var_name not in write_info, ( + "two sections write the same var({}): second " + "op {}.".format(var_name, op)) + write_info[var_name] = prog + break + + for var_name in var_info.keys(): + # Case 1: read only variables, no special process + if not var_name in write_info: continue + + # Case 2: one write multiple reads + write_prog = write_info[var_name] + write_block = write_prog.block(0) + write_device = self._get_device_info(write_block) + write_dev_index = int(write_device.split(':')[1]) + all_progs = var_info[var_name] + for prog in all_progs: + if prog == write_prog: continue + read_block = prog.block(0) + read_device = self._get_device_info(read_block) + read_dev_index = int(read_device.split(':')[1]) + pair = (write_dev_index, read_dev_index) + pair_key = write_dev_index * 1000 + read_dev_index + if pair not in self._pipeline_pair: + self._pipeline_pair.append(pair) + self._pp_ring_map[pair_key] = self.ring_id + ring_id = self.ring_id + self.ring_id += 1 + else: + ring_id = self._pp_ring_map[pair_key] + + write_block._insert_op( + index=0, + type='send_v2', + inputs={ + 'X': write_block.var(var_name), + }, + attrs={ + self._op_device_key: + write_device, + 'use_calc_stream': + False, + # A trick to make the role LRSched to avoid copy every + # microbatch + self._op_role_key: + self._op_role.LRSched, + 'peer': + read_dev_index, + 'ring_id': + ring_id + }) + read_block._insert_op( + index=0, + type='recv_v2', + outputs={'Out': [read_block.var(var_name)]}, + attrs={ + 'out_shape': + read_block.var(var_name).shape, + 'dtype': + read_block.var(var_name).dtype, + self._op_device_key: + read_device, + 'use_calc_stream': + False, + # A trick to make the role LRSched to avoid copy every + # microbatch + self._op_role_key: + self._op_role.LRSched, + 'peer': + write_dev_index, + 'ring_id': + ring_id + }) + read_block._insert_op( + index=1, + type='c_sync_comm_stream', + inputs={'X': [read_block.var(var_name)]}, + outputs={'Out': [read_block.var(var_name)]}, + attrs={ + self._op_device_key: + read_device, + # A trick to make the role LRSched to avoid copy every + # microbatch + self._op_role_key: + self._op_role.LRSched, + 'ring_id': + ring_id + }) + + def _is_gradient_clip_op(self, op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/gradient_clip") + + def _is_regularization_op(self, op): + return op.desc.has_attr("op_namescope") \ + and op.desc.attr("op_namescope").startswith("/regularization") + + def _is_weight_decay_op(self, op): + # in AdamW namescope is /optimizer_*/weight decay/ + return op.desc.has_attr("op_namescope") \ + and 'weight decay' in op.desc.attr("op_namescope") + + def _get_input_output_info(self, block): + ''' + Get info of op input and output. + ''' + # A map from output var to op which generate it. + output_var_to_op = defaultdict(list) + # A map from var to op which takes it as input. + input_var_to_op = defaultdict(list) + + for index, op in enumerate(block.ops): + for var_name in op.input_arg_names: + input_var_to_op[var_name].append([op, index]) + for var_name in op.output_arg_names: + output_var_to_op[var_name].append([op, index]) + + return output_var_to_op, input_var_to_op + + def _optimize_forward_send_sync(self, program): + """ + optimize forward send's sync_comm_stream schedule + """ + if self.schedule_mode != '1F1B': return + + block = program.block(0) + + recv_type = 'recv_v2' if self.mp_degree == 1 else 'partial_recv' + backward_recv_index = None + for index, op in enumerate(block.ops): + if op.type == recv_type and self._is_backward_op(op): + backward_recv_index = index + break + + # last pipeline stage + if backward_recv_index is None: return + + offset = 0 + for index, op in enumerate(list(block.ops)): + if index >= backward_recv_index: break + if op.type == 'c_sync_comm_stream' and op.has_attr('pipeline_flag'): + var_name = op.input_arg_names[0] + var = block.var(var_name) + block._remove_op(index + offset, sync=False) + offset -= 1 + # NOTE: + # 1. When the backward recv is completed, it indicates + # that the forward send is completed too. So we only need + # to use the NOP op to prevent memory release. + # 2. Because we removed sync_comm_op, + # we will insert NOP after recv_op. + block._insert_op_without_sync( + index=backward_recv_index, + type='nop', + inputs={'X': [var]}, + outputs={'Out': [var]}, + attrs={self._op_role_key: self._op_role.Backward}) + block._sync_with_cpp() + + def _mv_head_recv(self, program): + """ + A pass to move the recv op to the beginning of + the forward/backward phase + """ + forward_insert_index = 0 + backward_insert_index = None + block = program.global_block() + num_ops = len(program.global_block().ops) + for i in range(num_ops): + insert_index = None + op = program.global_block().ops[i] + op_role = int(op.attr(self._op_role_key)) + if op_role == int( + self._op_role.Backward) and backward_insert_index is None: + backward_insert_index = i + if op.type != "partial_recv" and op.type != "partial_allgather" and op.type != "nop" and op.type != "recv_v2": + continue + if op_role == int(self._op_role.Forward): + if i == forward_insert_index: + forward_insert_index += 1 + continue + insert_index = forward_insert_index + elif op_role == int(self._op_role.Backward): + if i == backward_insert_index: + backward_insert_index += 1 + continue + insert_index = backward_insert_index + else: + raise ValueError("Unknown op_role: {}".format(op_role)) + op_inputs = dict() + for name in op.input_names: + op_inputs[name] = op.input(name) + op_outputs = dict() + for name in op.output_names: + op_outputs[name] = op.output(name) + block._insert_op_without_sync(index=insert_index, + type=op.type, + inputs=op_inputs, + outputs=op_outputs, + attrs=op.all_attrs()) + block._remove_op(i + 1) + if op_role == int(self._op_role.Forward): + forward_insert_index += 1 + elif op_role == int(self._op_role.Backward): + backward_insert_index += 1 + block._sync_with_cpp() + + def _check_pipeline_persist_var(self, program): + """ + Pipeline may need multiple forward before + """ + block = program.global_block() + + persist_output = set() + used_in_backward = set() + for op in block.ops: + if self._is_forward_op(op): + for var_name in op.output_arg_names: + var = block.vars[var_name] + if var.persistable: + persist_output.add(var_name) + elif self._is_backward_op(op): + for var_name in op.input_arg_names: + if var_name in persist_output: + used_in_backward.add(var_name) + if len(used_in_backward) == 0: + return + warnings.warn( + "The pipeline requires multiple forward calculations before backward, " + "so when the persistable var is changed in the forward, it may cause " + "errors in the backward calculation who using this persistable var. " + "However, some backward op don't need this var(NoNeedBufferVars), " + "there will be no error at this time.\n" + "So please check these persistable vars which changed in " + "forward and used in backward:\n{}".format(used_in_backward)) + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + main_block = loss.block + self.origin_main_block = main_block + main_program = main_block.program + if startup_program is None: + startup_program = default_startup_program() + + pipeline_opt = main_program._pipeline_opt + assert pipeline_opt, 'Please use pipeline with fleet.' + required_keys = [ + 'local_rank', + 'schedule_mode', + 'micro_batch_size', + 'ring_id', + 'global_ring_id', + 'use_sharding', + 'mp_degree', + 'mp_rank', + ] + for key in required_keys: + assert key in pipeline_opt, \ + 'Please use pipeline with fleet to use {}.'.format(key) + self.local_rank = pipeline_opt['local_rank'] + self.schedule_mode = pipeline_opt['schedule_mode'] + self.micro_batch_size = pipeline_opt['micro_batch_size'] + self.use_sharding = pipeline_opt['use_sharding'] + self.ring_id = pipeline_opt['ring_id'] + self.global_ring_id = pipeline_opt['global_ring_id'] + self.mp_degree = pipeline_opt['mp_degree'] + self.mp_rank = pipeline_opt['mp_rank'] + self.scale_gradient = pipeline_opt.get('scale_gradient', False) + assert self.mp_degree >= 1 + assert 0 <= self.mp_rank < self.mp_degree + + optimize_ops, params_grads = self._optimizer.minimize( + loss, startup_program, parameter_list, no_grad_set) + self._param_device_map = self._origin_optimizer._param_device_map + + self.output_var_to_op, self.input_var_to_op = \ + self._get_input_output_info(main_block) + # Step1: add default op_device attribute for ops. + self._add_op_device_attr(main_block) + device_list = self._check_validation(main_block) + + def device_cmp(device1, device2): + dev1_id = int(device1.split(':')[1]) + dev2_id = int(device2.split(':')[1]) + if dev1_id < dev2_id: + return -1 + elif dev1_id > dev2_id: + return 1 + else: + return 0 + + sorted_device_list = sorted(device_list, key=cmp_to_key(device_cmp)) + assert sorted_device_list == device_list, ( + "With pipeline parallelism, you must use gpu devices one after " + "another in the order of their ids.") + # Step2: add send and recv ops between section boundaries + self._insert_sendrecv_ops_for_boundaries(main_block) + + # Step3: split program into sections and add pairs of + # send and recv ops for data var. + main_program = main_block.program + program_list = self._split_program(main_program, device_list) + for p in program_list: + self._create_vars(p.global_block(), main_block) + + if os.getenv("PADDLE_MANUAL_PIPELINE_STAGE", None): + self.local_rank = int(os.getenv("PADDLE_MANUAL_PIPELINE_STAGE")) + assert self.local_rank < len(device_list), ( + "Manually specified " + "pipeline stage must be less than total number of pipeline " + "stages.") + else: + self.local_rank %= len(device_list) + # Step3.5: optimize forward send sync_comm to overlap send and recv + self._optimize_forward_send_sync(program_list[self.local_rank]) + + # Step4: Special Case: process persistable vars that exist in + # multiple sections + # FIXME + # self._process_persistable_vars_in_multi_sections( + # main_program, startup_program, program_list) + + # Step5: Add sub blocks for section programs + self._add_sub_blocks(main_block, program_list) + + place_list = [] + for dev in device_list: + dev_index = int(dev.split(":")[1]) + if core.is_compiled_with_cuda(): + place_list.append(core.CUDAPlace(dev_index % 1)) + elif core.is_compiled_with_npu(): + place_list.append(core.NPUPlace(dev_index % 1)) + + # Step6: Split startup program + new_startup_program = self._split_startup_program( + startup_program, self.local_rank) + + startup_program._pipeline_opt = { + "startup_program": new_startup_program, + } + real_block = program_list[self.local_rank].global_block() + if not self.scale_gradient: + self._insert_loss_scale(real_block) + if not self.use_sharding: + # Step7: clear gradients before each mini-batch and + # accumulate gradients during backward + self._rename_gradient_var_name(real_block) + real_block._sync_with_cpp() + self._accumulate_gradients(real_block) + real_block._sync_with_cpp() + + if core.is_compiled_with_cuda(): + place_id = int(os.getenv("FLAGS_selected_gpus", "0")) + elif core.is_compiled_with_npu(): + place_id = int(os.getenv("FLAGS_selected_npus", "0")) + # A pass to move the recv op to the beginning of + # the forward/backward phase + self._mv_head_recv(program_list[self.local_rank]) + + # A pass to check pipeline persist var which changed in + # forward and used in backward + self._check_pipeline_persist_var(program_list[self.local_rank]) + + main_program._pipeline_opt = { + "trainer": "PipelineTrainer", + "device_worker": "Section", + "pipeline_stage": self.local_rank, + "num_pipeline_stages": len(device_list), + "schedule_mode": self.schedule_mode, + "inner_parallelism": len(device_list), + "section_program": program_list[self.local_rank], + "place": place_list[self.local_rank], + "place_id": place_id, + "sync_steps": -1, + "num_microbatches": self._num_microbatches, + "start_cpu_core_id": self._start_cpu_core_id, + } + return optimize_ops, params_grads, program_list, self._pipeline_pair, self._pp_ring_map + + +class RecomputeOptimizer(Optimizer): + """ + :api_attr: Static Graph + + Recompute Optimizer Wrapper + + Normally, a training step contains three sub-steps: first, run forward + Operators to calculate the loss; second, run backward Operators to + calculate gradient of the parameters; third, apply optimization method + to update the value of the parameters. + + In the forward computation process, all variables that are needed by + backward computation process will be kept in memory, which occupy a great + amount of memory when the network becomes very deep. + + Recompute split the network to k segments. In each segment, It will + recompute the forward Operators, before running backward operators. It is + very helpful for saving memory. + + The Variables that separate a network to segments are called as checkpoints, + and users should set it manually. The usage is very simple: + + Args: + optimizer (Optimizer): The optimizer that is applied to parameters. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + def gen_data(): + return {"x": np.random.random(size=(32, 32)).astype('float32'), + "y": np.random.randint(2, size=(32, 1)).astype('int64')} + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + print(input_x) + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.RecomputeOptimizer(sgd) + sgd._set_checkpoints([fc_1, pred]) + sgd.minimize(cost) + + print("Finished optimize") + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + step = 10 + + for i in range(step): + cost_val = exe.run(feed=gen_data(), + program=fluid.default_main_program(), + fetch_list=[cost.name]) + print("step=%d cost=%f" % (i, cost_val[0])) + + """ + + def __init__(self, optimizer): + if framework._non_static_mode(): + raise Exception("In dygraph, don't support RecomputeOptimizer.") + self._optimizer = optimizer + self._checkpoints = None + self._learning_rate = self._optimizer._learning_rate + self._learning_rate_map = self._optimizer._learning_rate_map + self.enable_offload = False + + def _set_checkpoints(self, checkpoints): + """ + Args: + checkpoints (list): List of Variable or string + """ + assert isinstance( + checkpoints, list + ), "_checkpoints should be a list of Variable or a list of String" + for ckpt in checkpoints: + assert ( + isinstance(ckpt, six.string_types) + or isinstance(ckpt, Variable) + ), "_checkpoints should be a list of Variable or a list of String" + self._checkpoints = checkpoints + + # should enable offload before calling backward + def _enable_offload(self): + self.enable_offload = True + + @framework.deprecate_stat_dict + def load(self, state_dict): + """ + :api_attr: Static Graph + + load function is not supported by Recompute Optimizer for now. + :return: None + + Args: + state_dict: the dict load by load_persistable method + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.compat as cpt + + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + print("Finished FF") + + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.RecomputeOptimizer(sgd) + sgd._set_checkpoints([fc_1, pred]) + try: + state_dict = {} + sgd.load(state_dict) + except NotImplementedError as e: + print(cpt.get_exception_message(e)) + """ + raise NotImplementedError( + "load function is not supported by Recompute Optimizer for now") + + def apply_gradients(self, params_grads): + """ + call apply_gradients function of self._optimizer. + + Args: + params_grads (list): list of (param, grad) pair to do optimization. + + Returns: + list: A list of operators appended to the current program. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.framework as framework + + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + + + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + print("Finished FF") + + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.RecomputeOptimizer(sgd) + sgd._set_checkpoints([fc_1, pred]) + params_grads = sgd.backward( + cost, + startup_program=None, + parameter_list=None, + no_grad_set=None) + + program = cost.block.program + with framework.program_guard(program, None): + optimize_ops = sgd.apply_gradients(params_grads) + + print("Finished apply gradients") + """ + + return self._optimizer.apply_gradients(params_grads=params_grads) + + def _creat_vars(self, varname): + pinned_var_name = unique_name.generate(varname + "@Pinned") + fetched_var_name = unique_name.generate(varname + "@Fetch") + + pinned_var = self._main_program.global_block().create_var( + name=pinned_var_name, + shape=self.checkpoint_shape, + dtype=self._main_program.global_block().var(varname).dtype, + persistable=False, + stop_gradient=True) + + fetch_var = self._main_program.global_block().create_var( + name=fetched_var_name, + shape=self.checkpoint_shape, + dtype=self._main_program.global_block().var(varname).dtype, + persistable=False, + stop_gradient=False) + + return pinned_var_name, fetched_var_name + + def _append_fill_constant_ops(self, startup_program): + """ + add fill_constant_ops to the end of the prog + + we should fill the pinned vars before runing the main_prog + to instantiate their tensor hold_, which could tell us whether + the host memory could hold all the checkpoints from all the + GPU devices in this node. + """ + op_role = 0 + block = startup_program.global_block() + fill_constant_vars = self.checkpoint_name2pinned_name.values() + OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() + for varname in fill_constant_vars: + var = self._main_program.global_block().var(varname) + # NOTE (JZ-LIANG) to pre-allocate the CUDAPinned MEM + pinned_var = block.create_var( + name=varname, + shape=self.checkpoint_shape, + dtype=self._main_program.global_block().var(var.name).dtype, + persistable=False, + stop_gradient=True) + block.append_op(type='fill_constant', + outputs={'Out': varname}, + attrs={ + "shape": var.shape, + "dtype": var.dtype, + "value": 0.0, + "place_type": 2, + OP_ROLE_KEY: op_role, + }) + + return + + def _insert_async_memcpy_op(self, insert_idx, src_varname, dst_varname, + op_role, dst_place_type): + OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName() + self.block._insert_op_without_sync( + insert_idx, + type='memcpy', + inputs={'X': [self._main_program.global_block().var(src_varname)]}, + outputs={ + 'Out': [self._main_program.global_block().var(dst_varname)] + }, + attrs={ + "dst_place_type": int(dst_place_type), + OP_ROLE_KEY: op_role + }) + + def _insert_fetch_op(self, idx, varname): + assert varname in self.checkpoint_name2pinned_name, "Try to fetch {} from Pinned Memory, but it is NOT a checkpoint".format( + varname) + + pinned_varname = self.checkpoint_name2pinned_name[varname] + fetch_varname = self.checkpoint_name2fetch_name[varname] + self._insert_async_memcpy_op(idx, pinned_varname, fetch_varname, 1, 1) + + def _insert_offload_op(self, idx, varname): + assert varname in self.checkpoint_name2pinned_name, "Try to offload {} to Pinned Memory, but it is NOT a checkpoint".format( + varname) + pinned_varname = self.checkpoint_name2pinned_name[varname] + self._insert_async_memcpy_op(idx, varname, pinned_varname, 0, 2) + + def _insert_sync_op(self, op_idx, checkpoint_name): + # single stream offload no need sync + pass + + def _record_fetch_op(self, idx): + assert len(self.un_fetch_checkpoint_names + ) > 0, "Could NOT found checkpoint to fetch" + checkpoint_name = self.un_fetch_checkpoint_names.pop(-1) + logging.debug("Record fetch [{}]".format(checkpoint_name)) + self.idx2insertions[idx] = ("fetch", checkpoint_name) + + return checkpoint_name + + def _record_offload_op(self, idx, checkpoint_name): + expected_checkpoint_name = self.un_offload_checkpoint_names.pop(0) + assert checkpoint_name == expected_checkpoint_name, "expected to offload [{}] but got [{}]".format( + expected_checkpoint_name, checkpoint_name) + logging.debug("Record offload [{}]".format(checkpoint_name)) + self.idx2insertions[idx] = ("offload", checkpoint_name) + + def _record_sync_op(self, idx, checkpoint_name): + assert checkpoint_name not in self.synced_checkpoints, "Try to sync the checkpoint [{}] twice".format( + checkpoint_name) + self.synced_checkpoints.add(checkpoint_name) + logging.debug("Record offload sync [{}]".format(checkpoint_name)) + self.idx2insertions[idx] = ("sync", checkpoint_name) + + def _parse_backward(self): + + self.idx2insertions = {} + # don't offload the last checkpoints, to favor throughput + self.un_fetch_checkpoint_names = self.sorted_checkpoint_names[:] + self.un_fetch_checkpoint_names.pop(-1) + need_fetch_checkpoint_names = self.un_fetch_checkpoint_names[:] + self.checkpoint_usage_count = {} + for checkpoint_name in self.un_fetch_checkpoint_names: + self.checkpoint_usage_count[checkpoint_name] = 0 + + self.bw_strart_op_idx = len(self.block.ops) + for idx, op in enumerate(self.block.ops): + if int(op.desc.attr("op_role")) == 1: + self.bw_strart_op_idx = idx + break + + assert self.bw_strart_op_idx < len( + self.block.ops), "Could NOT found backword op in prog" + + # fetch second to last checkpoint at the beginning of BW + fetched_checkpoint_varname = self._record_fetch_op( + self.bw_strart_op_idx) + last_last_fetch_checkpoint = None + + for i, op in enumerate(self.block.ops[self.bw_strart_op_idx:]): + idx = self.bw_strart_op_idx + i + input_vars = op.desc.input_arg_names() + + for input_var in input_vars: + if input_var in need_fetch_checkpoint_names: + if input_var not in self.un_fetch_checkpoint_names: + # fetch the offloade checkpoint when the first usage of its previous one + if self.checkpoint_usage_count[input_var] == 0: + # TODO (JZ-LIANG) sync memcpy_stream if extra stream for memcpy + second_to_last_fetch_checkpoint = fetched_checkpoint_varname + # there is NO fetch ahead the first checkpoint + if input_var != self.sorted_checkpoint_names[0]: + fetched_checkpoint_varname = self._record_fetch_op( + idx) + + # should check the current used checkpoint is ths last fetch one + assert second_to_last_fetch_checkpoint == input_var, "Current recompute segment should use [{}] BUT got [{}]".format( + second_to_last_fetch_checkpoint, input_var) + # rename + self.block.ops[idx]._rename_input( + input_var, + self.checkpoint_name2fetch_name[input_var]) + self.checkpoint_usage_count[input_var] += 1 + else: + raise ValueError( + "use checkpoint [{}] before fetch in BW".format( + input_var)) + + assert len(self.un_fetch_checkpoint_names + ) == 0, "{} checkpoints have NOT been Recorded".format( + self.un_fetch_checkpoint_names) + + def _update_backward(self): + if len(self.idx2insertions) == 0: + return + total_op = len(self.block.ops) + for op_idx in reversed(range(self.bw_strart_op_idx, total_op)): + if op_idx in self.idx2insertions: + operation, checkpoint_name = self.idx2insertions[op_idx] + if operation == "fetch": + self._insert_fetch_op(op_idx, checkpoint_name) + logging.debug( + "Insert [{}] fetch op.".format(checkpoint_name)) + del self.idx2insertions[op_idx] + elif operation == "sync": + self._insert_sync_op(op_idx, checkpoint_name) + logging.debug("Sync [{}] fetch op.".format(checkpoint_name)) + self.block._sync_with_cpp() + assert len( + self.idx2insertions) == 0, "{} checkpoints left un-Fecthed".format( + [ele[1] for ele in self.idx2insertions.values()]) + + def _parse_forward(self): + + self.idx2insertions = {} + # don't offload the last checkpoints, faster, less memory saving + self.un_offload_checkpoint_names = self.sorted_checkpoint_names[:] + last_checkpoint = self.un_offload_checkpoint_names.pop(-1) + need_offload_checkpoint_names = self.un_offload_checkpoint_names[:] + self.checkpoint_usage_count_and_idx = {} + for checkpoint_name in self.un_offload_checkpoint_names: + self.checkpoint_usage_count_and_idx[checkpoint_name] = { + 'count': 0, + 'idx': -1 + } + self.synced_checkpoints = set() + self.fw_strart_op_idx = len(self.block.ops) + for idx, op in enumerate(self.block.ops): + if int(op.desc.attr("op_role")) == 0: + self.fw_strart_op_idx = idx + break + + assert self.fw_strart_op_idx < len( + self.block.ops), "Could NOT found Forward op in prog" + last_offload_checkpoint = None + + for i, op in enumerate( + self.block.ops[self.fw_strart_op_idx:self.bw_strart_op_idx]): + + idx = self.fw_strart_op_idx + i + output_vars = op.desc.output_arg_names() + input_vars = op.desc.input_arg_names() + + for output_var in output_vars: + if output_var in need_offload_checkpoint_names: + assert len( + output_vars + ) == 1, "chekpoint should be the only Output of a certain op, but [{}] is from [{}]".format( + output_var, op) + + if output_var in self.un_offload_checkpoint_names: + # insert sync op if last checkpoint has not been sync + if last_offload_checkpoint != None: + if self.checkpoint_usage_count_and_idx[ + last_offload_checkpoint]['count'] == 0: + self._record_sync_op(idx, + last_offload_checkpoint) + else: + last_usage_idx = self.checkpoint_usage_count_and_idx[ + last_offload_checkpoint]['idx'] + assert last_usage_idx > 0, "last_usage_idx of checkpoint [{}] should large than 0".format( + last_offload_checkpoint) + self._record_sync_op(last_usage_idx + 1, + last_offload_checkpoint) + # insert offload op after the checkpoint's generation op + self._record_offload_op(idx + 1, output_var) + last_offload_checkpoint = output_var + else: + raise ValueError( + "There should be just ONE op that output checkpoint [{}]" + .format(output_var)) + # need to sync the last need to offload checkpoint before the last checkpoint as output op + if output_var == last_checkpoint: + assert len( + output_vars + ) == 1, "chekpoint should be the only Output of a certain op, but [{}] is from [{}]".format( + output_var, op) + assert last_offload_checkpoint == self.sorted_checkpoint_names[ + -2], "the last offload chekpoint before [{}] is suppose to be [{}], but got [{}]".format( + last_checkpoint, self.sorted_checkpoint_names[-2], + last_offload_checkpoint) + # sync if last checkpoint has not been sync + if self.checkpoint_usage_count_and_idx[ + last_offload_checkpoint]['idx'] == 0: + self._record_sync_op(idx, last_offload_checkpoint) + else: + last_usage_idx = self.checkpoint_usage_count_and_idx[ + last_offload_checkpoint]['idx'] + assert last_usage_idx > 0, "last_usage_idx of checkpoint [{}] should large than 0".format( + last_offload_checkpoint) + self._record_sync_op(last_usage_idx + 1, + last_offload_checkpoint) + # record checkpoint usage + for input_var in input_vars: + if input_var in need_offload_checkpoint_names: + assert input_var not in self.synced_checkpoints, "checkpoint [{}] used after sync".format( + input_var) + self.checkpoint_usage_count_and_idx[input_var]['count'] += 1 + self.checkpoint_usage_count_and_idx[input_var]['idx'] = idx + + assert len(self.un_offload_checkpoint_names + ) == 0, "{} checkpoints have NOT been Recorded".format( + self.un_fetch_checkpoint_names) + assert len(self.synced_checkpoints) == len( + need_offload_checkpoint_names + ), "{} checkpoints have NOT been Recorded".format( + set(need_offload_checkpoint_names) - set(self.synced_checkpoints)) + + def _update_forward(self): + if len(self.idx2insertions) == 0: + return + for op_idx in reversed( + range(self.fw_strart_op_idx, self.bw_strart_op_idx)): + if op_idx in self.idx2insertions: + operation, checkpoint_name = self.idx2insertions[op_idx] + if operation == "offload": + self._insert_offload_op(op_idx, checkpoint_name) + logging.debug( + "Insert [{}] offload op.".format(checkpoint_name)) + del self.idx2insertions[op_idx] + elif operation == "sync": + self._insert_sync_op(op_idx, checkpoint_name) + logging.debug( + "Insert [{}] offload_sync op.".format(checkpoint_name)) + del self.idx2insertions[op_idx] + + self.block._sync_with_cpp() + assert len(self.idx2insertions + ) == 0, "{} checkpoints left un-Offloaded".format( + [ele[1] for ele in self.idx2insertions.values()]) + + def _check_offload_fetch(self): + # TODO(JZ-LIANG) the single stream offload need no sync + pass + + def _offload(self, loss, startup_program=None): + """ + core steps for recompute offload + 1. create pinned vars and temp vars + 2. parse & update Forward pass: offload, sync + 3. parse & update Backward pass: rename, fetch, sync + 4. verify the correctness + """ + self._main_program = loss.block.program + self.block = loss.block + if startup_program == None: + startup_program = paddle.static.default_startup_program() + + with program_guard(self._main_program, startup_program): + assert len(self.checkpoint_shape) > 0, ( + "checkpoints shape {} should be an non empty list like: [12, 512, 1024]" + .format(self.checkpoint_shape)) + assert all([ele > 0 for ele in self.checkpoint_shape]), ( + "all ele in checkpoints shape {} should be a determined integer larger than 0" + .format(self.checkpoint_shape)) + self.checkpoint_name2pinned_name = dict() + self.checkpoint_name2fetch_name = dict() + for checkpoint_varname in self.sorted_checkpoint_names: + pinned_var_name, fetch_var_name = self._creat_vars( + checkpoint_varname) + self.checkpoint_name2pinned_name[ + checkpoint_varname] = pinned_var_name + self.checkpoint_name2fetch_name[ + checkpoint_varname] = fetch_var_name + self._append_fill_constant_ops(startup_program) + # TODO (JZ-LIANG) to provide two offload stragtegy in future + # step 2. parse & update FW: rename, offload, sync + self._parse_backward() + self._update_backward() + # step 3. parse & update BW: rename, offload, sync + self._parse_forward() + self._update_forward() + # step 4. verify the correctness + self._check_offload_fetch() + + return + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + """ + call append_backward with checkpoints. + + Args: + loss (Variable): loss variable to run optimizations. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + parameter_list (list): list of Variables or Variable.names to update. + no_grad_set (set|None): set of Variables or Variables.names should be ignored. + callbacks (list|None): list of callables to run when appending backward + operator for one parameter. + checkpoints (list): list of Variables as checkpoints + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + + + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + print("Finished FF") + + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.RecomputeOptimizer(sgd) + sgd._set_checkpoints([fc_1, pred]) + params_grads = sgd.backward( + cost, + startup_program=None, + parameter_list=None, + no_grad_set=None) + print("Finished backward") + """ + assert (self._checkpoints + is not None), "You should call _set_checkpoints first" + + if framework._non_static_mode(): + raise NotImplementedError( + "DyGraph current does not support recompute") + + self._dtype = loss.dtype + program = loss.block.program + with program_guard(program, startup_program): + checkpoint_vars = [] + for ckpt in self._checkpoints: + if isinstance(ckpt, Variable): + checkpoint_vars.append(ckpt) + else: + checkpoint_vars.append(loss.block.var(ckpt)) + + # allow return to non-recompute when checkpoints is empty + if len(checkpoint_vars) > 0: + params_grads, sorted_checkpoint_names = append_backward( + loss, + parameter_list, + no_grad_set, + checkpoints=checkpoint_vars) + else: + params_grads = append_backward(loss, + parameter_list, + no_grad_set, + checkpoints=checkpoint_vars) + + if self.enable_offload: + self.sorted_checkpoint_names = sorted_checkpoint_names + self._offload(loss, startup_program=startup_program) + + return params_grads + + def apply_optimize(self, loss, startup_program, params_grads): + """ + call the apply_optimize function of self._optimizer + Args: + loss (Variable): loss variable to run optimizations. + startup_program (Program): startup_program for initializing parameters + in `parameter_list`. + params_grads (list): list of (param, grad) pair to do optimization. + Examples: + .. code-block:: python + import paddle.fluid as fluid + + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + print("Finished FF") + + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.RecomputeOptimizer(sgd) + sgd._set_checkpoints([fc_1, pred]) + params_grads = sgd.backward( + cost, + startup_program=None, + parameter_list=None, + no_grad_set=None) + + optimize_ops = sgd.apply_optimize( + cost, startup_program=None, params_grads=params_grads) + + print("Finished apply_optimize") + """ + + func = self._optimizer.apply_optimize if hasattr( + self._optimizer, + 'apply_optimize') else self._optimizer._apply_optimize + return func(loss, + startup_program=startup_program, + params_grads=params_grads) + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + assert isinstance(loss, Variable), "The loss should be an Variable." + assert (self._checkpoints + is not None), "You should call _set_checkpoints first" + if framework._non_static_mode(): + raise NotImplementedError( + "DyGraph current does not support recompute") + params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + return optimize_ops, params_grads + + +class LookaheadOptimizer(object): + r""" + :api_attr: Static Graph + + This implements the Lookahead optimizer of the + paper : https://arxiv.org/abs/1907.08610. + + Lookahead keeps two sets of params: the fast_params and + the slow_params. inner_optimizer update fast_params every + training step. Lookahead updates the slow_params and fast_params + every k training steps as follows: + + .. math:: + + slow\_param_t &= slow\_param_{t-1} + \\alpha * (fast\_param_{t-1} - slow\_param_{t-1}) + + fast\_param_t &= slow\_param_t + + Args: + inner_optimizer (Optimizer): The optimizer that update fast params step by step. + alpha (float): The learning rate of Lookahead. + k (int): The slow params is updated every k steps. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + import numpy.random as random + + paddle.enable_static() + + x = fluid.layers.data(name='x', shape=[2], dtype='float32') + label = fluid.layers.data(name="label", shape=[1], dtype="int64") + y = fluid.layers.fc(input=[x], size=2, act="softmax") + loss = fluid.layers.cross_entropy(input=y, label=label) + loss = paddle.mean(x=loss) + sgd = fluid.optimizer.SGD(learning_rate=0.01) + optimizer = fluid.optimizer.LookaheadOptimizer(sgd, + alpha=0.5, + k=5) + optimizer.minimize(loss) + main_program = fluid.default_main_program() + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + def train_reader(limit=5): + for i in range(limit): + yield random.random([2]).astype('float32'), random.random([1]).astype('int64') + + feeder = fluid.DataFeeder(feed_list=[x, label], place=place) + reader = paddle.batch(paddle.reader.shuffle(train_reader, buf_size=50000),batch_size=1) + + for batch_data in reader(): + exe.run(fluid.default_main_program(), + feed=feeder.feed(batch_data)) + + """ + + def __init__(self, inner_optimizer, alpha=0.5, k=5): + + if framework._non_static_mode(): + raise Exception("In dygraph, don't support LookaheadOptimizer.") + assert (inner_optimizer is not None), "inner optimizer can not be None" + assert ( + 0.0 <= alpha <= 1.0 + ), "alpha should be larger or equal to 0.0, and less or equal than 1.0" + assert (isinstance(k, int) and k > 0), "k should be a positive integer" + + self.inner_optimizer = inner_optimizer + self.alpha = alpha + self.k = k + self.type = "lookahead" + + def minimize(self, loss, startup_program=None): + + # Apply inner optimizer to the main_program + mini_out = self.inner_optimizer.minimize( + loss, startup_program=startup_program) + + # Get startup_program and main_program + if startup_program is None: + startup_program = default_startup_program() + main_block = loss.block + + # add some vars to the main_program + params = [param.name for param in main_block.all_parameters()] + param_to_slow = {} + for param in params: + fast_var = main_block.var(param) + assert (fast_var is not None) + slow_var = main_block.create_var(name=param + "@SLOW", + shape=fast_var.shape, + dtype=fast_var.dtype, + persistable=True) + param_to_slow[param] = slow_var + + # add some vars to the startup_program + startup_block = startup_program.global_block() + for param in params: + fast_var = startup_block.var(param) + assert (fast_var is not None) + slow_var = startup_block.create_var(name=param + "@SLOW", + shape=fast_var.shape, + dtype=fast_var.dtype, + persistable=True) + + startup_block.append_op(type="assign", + inputs={"X": fast_var}, + outputs={"Out": slow_var}) + + with framework.program_guard(main_block.program, startup_program): + # Add Var k to main prog and startup prog + k = layers.create_global_var(name="lookahead_k", + shape=[1], + value=int(self.k), + dtype='int32', + persistable=True) + + # Add Var alpha to main prog and startup prog + alpha = layers.create_global_var(name="lookahead_alpha", + shape=[1], + value=float(self.alpha), + dtype='float32', + persistable=True) + + # Add Var step + step = layers.create_global_var(name="lookahead_step", + shape=[1], + value=int(0), + dtype='int32', + persistable=True) + layers.increment(x=step, value=1.0, in_place=True) + + # lookahead + zero_var = layers.fill_constant(shape=[1], + dtype='float32', + value=0.0) + + one_var = layers.fill_constant(shape=[1], + dtype='float32', + value=1.0) + + mod = layers.elementwise_mod(step, k) + with layers.control_flow.Switch() as switch: + with switch.case(step == one_var): + for param_name in params: + fast_var = main_block.var(param_name) + slow_var = param_to_slow[param_name] + layers.assign(input=fast_var, output=slow_var) + with switch.case(mod == zero_var): + for param_name in params: + fast_var = main_block.var(param_name) + slow_var = param_to_slow[param_name] + tmp_var = layers.elementwise_add( + layers.elementwise_mul(fast_var, alpha), + layers.elementwise_mul( + slow_var, + layers.elementwise_sub(one_var, alpha))) + layers.assign(input=tmp_var, output=slow_var) + layers.assign(input=tmp_var, output=fast_var) + with switch.default(): + pass + return mini_out + + +class GradientMergeOptimizer(object): + """ + Gradient Merge, also called as Gradient Accumulation, + is a training strategy for larger batches. With this strategy, + the parameter will not be updated until specific steps. + + For each step, the forward network and the backward network + will run to calculate the gradient of the parameters. + + For every k step, the optimization network will run, + applying a specific optimization method (such as SGD, Adam) + to the parameters. + + Args: + inner_optimizer (Optimizer): The specific optimization (such as SGD, Adam) + which update the parameters + k_steps (int): the update period of the parameters + avg (bool): whether to average the gradients of each mini-batch, + the default value is `True` + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + def gen_data(batch_size): + return {"x": np.random.random(size=(batch_size, 32)).astype('float32'), + "y": np.random.random(size=(batch_size, 1)).astype('int64')} + + def mlp(input_x, input_y, hid_dim=128, label_dim=2): + fc_1 = fluid.layers.fc(input=input_x, size=hid_dim) + prediction = fluid.layers.fc(input=[fc_1], size=label_dim, act='softmax') + cost = fluid.layers.cross_entropy(input=prediction, label=input_y) + sum_cost = fluid.layers.reduce_mean(cost) + return sum_cost, fc_1, prediction + + input_x = fluid.layers.data(name="x", shape=[32], dtype='float32') + input_y = fluid.layers.data(name="y", shape=[1], dtype='int64') + cost, fc_1, pred = mlp(input_x, input_y) + sgd = fluid.optimizer.Adam(learning_rate=0.01) + sgd = fluid.optimizer.GradientMergeOptimizer(sgd, k_steps=4, avg=True) + sgd.minimize(cost) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + for i in range(10): + cost_val = exe.run(feed=gen_data(32), + program=fluid.default_main_program(), + fetch_list=[cost.name]) + print("step=%d, cost=%f" % (i, cost_val[0])) + """ + + GRAD_MERGE_COND_NAME = "grad_merge_cond_name" + + def __init__(self, inner_optimizer, k_steps=1, avg=True): + if framework._non_static_mode(): + raise Exception( + "In dygraph, we don't support GradientMergeOptimizer." + "You can do Gradient merge by yourself with k-times forward + backward, " + "and one-time optimizer.minimize()") + + assert (inner_optimizer is not None), "inner optimizer can not be None" + assert (isinstance(k_steps, int) + and k_steps > 0), "k_steps should be a positive integer" + + self.inner_optimizer = inner_optimizer + self.k_steps = k_steps + self.type = "gradient_merge" + self.avg = avg + self._optimize_ops = None + + def _set_k_steps(self, k_steps): + self.k_steps = k_steps + + def _set_avg(self, avg): + self.avg = avg + + def backward(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None, + callbacks=None): + assert isinstance(loss, Variable), "The loss should be an Variable." + assert ( + parameter_list is None + ), "The parameter_list should be None when using GradientMergeOptimizer" + assert ( + no_grad_set is None + ), "The no_grad_set should be None when using GradientMergeOptimizer" + + params_grads = self.inner_optimizer.backward( + loss, startup_program=startup_program) + return params_grads + + def apply_optimize(self, loss, startup_program, params_grads): + program = loss.block.program + with program_guard(program, startup_program): + optimize_ops = self.apply_gradients(params_grads) + return optimize_ops + + def _is_the_backward_op(self, op): + op_maker = core.op_proto_and_checker_maker + backward = core.op_proto_and_checker_maker.OpRole.Backward + if op_maker.kOpRoleVarAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(backward): + return True + return False + + def _remove_op_role_var(self, param, grad): + op_maker = core.op_proto_and_checker_maker + op = grad.op + assert self._is_the_backward_op(op), \ + 'grad.op={} is not the backward op which produces the grad={}' \ + .format(op, grad.name) + + block = grad.block + var_attr = op.all_attrs()[op_maker.kOpRoleVarAttrName()] + assert param.name in var_attr, \ + 'when using GradientMergeOptimizer, param={} must be in var_attr={}' \ + .format(param.name, var_attr) + assert grad.name in var_attr, \ + 'when using GradientMergeOptimizer, grad={} must be in var_attr={}' \ + .format(param.name, var_attr) + + # remove (param, grad) from op_role_var + var_attr.remove(param.name) + var_attr.remove(grad.name) + if len(var_attr) > 1: + op._set_attr(op_maker.kOpRoleVarAttrName(), var_attr) + else: + op._remove_attr(op_maker.kOpRoleVarAttrName()) + + def _add_gm_op_role_var(self, op, param, grad, cond): + grad.op = op + op_maker = core.op_proto_and_checker_maker + backward = op_maker.OpRole.Backward + + # NOTE(wangxi). When distributed, we will insert grad_merge_all_reduce_op_handle + # in multi_devices_graph_pass, which will allreduce(grad) if cond is True, else + # do nothing. + # In this way, the gradient can be merged first, and then communicate when the + # condition is met, reducing the number of communications to increase the + # speed. + op._set_attr(self.GRAD_MERGE_COND_NAME, cond.name) + op._set_attr(op_maker.kOpRoleAttrName(), backward) + op._set_attr(op_maker.kOpRoleVarAttrName(), [param.name, grad.name]) + + def _get_gm_cond_var(self, main_block): + # Add const var + k_step_var = layers.create_global_var(name="gradient_merge_k", + shape=[1], + value=int(self.k_steps), + dtype='int32', + persistable=True, + force_cpu=True) + + zero_var = layers.create_global_var(name="gradient_merge_zero", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + + # Add step var & cond var + step_var = layers.create_global_var(name="gradient_merge_step", + shape=[1], + value=int(0), + dtype='int32', + persistable=True, + force_cpu=True) + + cond_var = main_block.create_var(name="gradient_merge_cond", + shape=[1], + dtype='bool') + + with device_guard("cpu"): + # step_var = (step_var + 1) % k_step + layers.increment(x=step_var, value=1.0, in_place=True) + main_block.append_op(type='elementwise_mod', + inputs={ + 'X': step_var, + 'Y': k_step_var + }, + outputs={'Out': step_var}, + attrs={ + 'axis': -1, + 'use_mkldnn': False + }) + + # cond_var = (step_var == 0) + main_block.append_op(type='equal', + inputs={ + 'X': step_var, + 'Y': zero_var + }, + outputs={'Out': cond_var}) + + return cond_var + + def apply_gradients(self, params_grads): + main_program = default_main_program() + startup_program = default_startup_program() + main_block = main_program.global_block() + startup_block = startup_program.global_block() + + cond = self._get_gm_cond_var(main_block) + + #TODO(mapingshuo) support sparse embedding + # step1: remove grad.op's op_role_var + for param, grad in params_grads: + assert ( + param.type != core.VarDesc.VarType.SELECTED_ROWS + ), "SELECTED_ROWS is not supported in GradientMergeOptimizer for now" + + self._remove_op_role_var(param, grad) + + param_to_grad = {k.name: v for (k, v) in params_grads} + param_names = param_to_grad.keys() + param_to_gradient_merge = {} + + new_params_grads = [] + # step2: create gradient_merge var and init with 0 + # and update op_role_var + for param, grad in params_grads: + param_name = param.name + param_var = main_block.var(param_name) + assert (param_var is not None) + gradient_merge_var = main_block.create_var(name=param_name + + "@GRAD@GradientMerge", + shape=param_var.shape, + dtype=param_var.dtype, + persistable=True) + param_to_gradient_merge[param_name] = gradient_merge_var + + startup_gradient_merge_var = startup_block.create_var( + name=param_name + "@GRAD@GradientMerge", + shape=param_var.shape, + dtype=param_var.dtype, + persistable=True) + startup_block.append_op(type="fill_constant", + outputs={"Out": startup_gradient_merge_var}, + attrs={ + "shape": param_var.shape, + "dtype": param_var.dtype, + "value": float(0), + }) + + # grad_merge += grad + new_grad_op = main_block.append_op( + type="elementwise_add", + inputs={ + 'X': grad, + 'Y': gradient_merge_var + }, + outputs={'Out': gradient_merge_var}, + attrs={ + 'axis': -1, + 'use_mkldnn': False + }) + self._add_gm_op_role_var(new_grad_op, param, gradient_merge_var, + cond) + new_params_grads.append([param, gradient_merge_var]) + + def true_apply_gradient(): + cur_block_idx = main_program.current_block_idx + cur_block = main_program.current_block() + + # cur_block's forward_block & backward_block is itself + cur_block._set_forward_block_idx(cur_block_idx) + op_maker = core.op_proto_and_checker_maker + + if self.avg: + for param, new_grad in new_params_grads: + # grad /= k_steps + cur_block.append_op(type='scale', + inputs={'X': new_grad}, + outputs={'Out': new_grad}, + attrs={ + 'scale': 1.0 / self.k_steps, + 'bias': 0.0, + 'bias_after_scale': False + }) + new_grad.op._set_attr(op_maker.kOpRoleAttrName(), + op_maker.OpRole.Backward) + + for param, new_grad in new_params_grads: + # NOTE. regularization will append ops to grad.block, + # while new_grad's real block is global_block, + # but we want append regularization ops to cur_block, + # so we set new_grad.block = cur_block + new_grad.block = cur_block + + self._optimize_ops = self.inner_optimizer.apply_gradients( + new_params_grads) + + # clear gradient_merge_vars + for param, new_grad in new_params_grads: + layers.fill_constant(shape=new_grad.shape, + dtype=new_grad.dtype, + value=0.0, + out=new_grad) + new_grad.op._set_attr(op_maker.kOpRoleAttrName(), + op_maker.OpRole.Optimize) + + # step3. apply gradient + layers.cond(cond, true_fn=true_apply_gradient, false_fn=None) + + return self._optimize_ops + + def minimize(self, + loss, + startup_program=None, + parameter_list=None, + no_grad_set=None): + assert isinstance(loss, Variable), "The loss should be an Variable." + + params_grads = self.backward(loss, + startup_program=startup_program, + parameter_list=parameter_list, + no_grad_set=no_grad_set) + + optimize_ops = self.apply_optimize(loss, + startup_program=startup_program, + params_grads=params_grads) + + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/parallel_executor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/parallel_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..e63270c1697f460dba70974ec84032ebae97e302 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/parallel_executor.py @@ -0,0 +1,377 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +from . import core +from . import framework +from . import executor +from . import compiler +from .data_feeder import check_type +import sys + +__all__ = ['ParallelExecutor'] + +ExecutionStrategy = core.ParallelExecutor.ExecutionStrategy +BuildStrategy = core.ParallelExecutor.BuildStrategy + + +class ParallelExecutor(object): + """ + :api_attr: Static Graph + + The ParallelExecutor is an upgraded version of :code:`paddle.static.Executor` that supports multi-node model + training and testing based on the data-parallel mode. In data-parallel mode, + ParallelExecutor will broadcast the parameters from Node0 to other nodes during + construction and copy the input Program to other nodes from Node0 to make sure + that the initial state on each node is the same. Each node runs the model independently + and the parameters' gradient is aggregated between those nodes during backward + computation, and then each node independently updates its parameters. If you use + the GPU to run the model, i.e. use_cuda=True, the node refers to the GPU, + ParallelExecutor will automatically get the GPU resources available on the + current machine, users can also set the available GPU resources in the environment + variable, for example: want to use GPU0, GPU1, export CUDA_VISIBLEDEVICES=0,1; + If the operation is performed on the CPU, i.e. use_cuda=False, the node refers to the CPU. + **Note: At this time, the user needs to manually add CPU_NUM to the environment variable + and set the number of CPU devices. For example, export CPU_NUM=4, if the environment + variable is not set, the executor will add the variable to the environment variable + and set it to 1.** + + + Args: + use_cuda (bool): Whether to use CUDA or not. + loss_name (str): This parameter is the name of the loss Tensor of the + model. **Note: If it is data-parallel model training, you must set loss_name, + otherwise, the results may be wrong**. The default is None. + main_program (Program): This parameter represents the Program to be executed. + If this parameter is not provided, that parameter is None, the program will + be set to :code:`paddle.static.default_main_program()`. The default is None. + share_vars_from(ParallelExecutor): If share_vars_from is set, the current + ParallelExecutor will share the parameters with the ParallelExecutor + specified by share_vars_from. This parameter needs to be set when model testing + is required during model training, and the data parallel mode is used for + training and testing. Since ParallelExecutor will only distribute parameter + variables to other devices when it is first executed, the ParallelExecutor + specified by share_vars_from must be run before the current ParallelExecutor. + The default is None. + exec_strategy(ExecutionStrategy): exec_strategy specifies the options that can + be changed when running the current model, such as the thread pool size. + For more information about exec_strategy, please refer to :code:`paddle.static.ExecutionStrategy`. + The default is None. + build_strategy(BuildStrategy): By configuring build_strategy, we can + optimize the computational graph, such as operators' fusion in the + computational graph and memory optimization during the execution + of the computational graph. For more information about build_strategy, + please refer to :code:`paddle.static.BuildStrategy`. The default is None. + num_trainers(int): This parameter needs to be set in GPU distributed training. + If the parameter value is greater than 1, NCCL will be initialized by multi-level + nodes. Each node should have the same number of GPUs. The default is 1. + trainer_id(int): This parameter needs to be set when performing GPU distributed + training. This parameter must be used with the num_trainers parameter. + Trainer_id indicates the "rank" of the current node. The trainer_id starts + counting from 0. The default is 0. + scope(Scope): Specifies the scope in which the program is executed. + The default is paddle.static.global_scope(). + + Returns: + ParallelExecutor: The initialized ParallelExecutor object. + + Raises: + TypeError: If share_vars_from is provided, but not ParallelExecutor object. + + NOTES: + + 1. If you only use ParallelExecutor to do multi-card test, you don't need to set loss_name + and share_vars_from. + + 2. If you need to train and test the model with ParallelExecutor, the share_vars_from + must be set when building the ParallelExecutor corresponding to the model test. + Otherwise, the parameters used in the model test and the model training are inconsistent. + + Examples: + .. code-block:: python + + import paddle + import numpy + import os + + use_cuda = True + paddle.enable_static() + place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() + + # NOTE: If you use CPU to run the program, you need + # to specify the CPU_NUM, otherwise, PaddlePaddle will use + # all the number of the logic core as the CPU_NUM, + # in that case, the batch size of the input should be + # greater than CPU_NUM, if not, the process will be + # failed by an exception. + if not use_cuda: + os.environ['CPU_NUM'] = str(2) + + exe = paddle.static.Executor(place) + + train_program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(train_program, startup_program): + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + test_program = paddle.static.default_main_program().clone(for_test=True) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + exe.run(startup_program) + + train_exe = paddle.static.ParallelExecutor(use_cuda=use_cuda, + main_program=train_program, + loss_name=loss.name) + # Note: if share_vars_from is not set here, the test parameter is different to the train one + test_exe = paddle.static.ParallelExecutor(use_cuda=use_cuda, + main_program=test_program, + share_vars_from=train_exe) + + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = train_exe.run(feed={"X": x}, + fetch_list=[loss.name]) + + loss_data, = test_exe.run(feed={"X": x}, + fetch_list=[loss.name]) + + """ + + def __init__(self, + use_cuda, + loss_name=None, + main_program=None, + share_vars_from=None, + exec_strategy=None, + build_strategy=None, + num_trainers=1, + trainer_id=0, + scope=None): + if build_strategy is None: + build_strategy = BuildStrategy() + + # TODO(paddle-dev): trainer_id and num_trainers should be removed from parameter list. + if num_trainers != 1 and build_strategy.num_trainers != num_trainers: + sys.stderr.write( + 'The value of build_strategy.num_trainers[%d] is overwritten ' + 'by the passed num_trainers[%d].\n' % + (build_strategy.num_trainers, num_trainers)) + build_strategy.num_trainers = num_trainers + if trainer_id != 0 and build_strategy.trainer_id != trainer_id: + sys.stderr.write( + 'The value of build_strategy.trainer_id[%d] is overwritten ' + 'by the passed trainer_id[%d].\n' % + (build_strategy.trainer_id, trainer_id)) + build_strategy.trainer_id = trainer_id + + self._places = framework.cuda_places( + ) if use_cuda else framework.cpu_places() + self._scope = scope if scope is not None else executor.global_scope() + + main_program = main_program if main_program is not None \ + else framework.default_main_program() + + self._compiled_program = compiler.CompiledProgram(main_program) + if share_vars_from: + assert isinstance( + share_vars_from, ParallelExecutor + ), "The share_vars_from should be ParallelExecutor." + + self._compiled_program.with_data_parallel( + loss_name=loss_name, + build_strategy=build_strategy, + exec_strategy=exec_strategy, + share_vars_from=share_vars_from._compiled_program + if share_vars_from else None) + + self._place = core.CUDAPlace(0) if use_cuda else core.CPUPlace() + self._exe = executor.Executor(self._place) + + def run(self, fetch_list, feed=None, feed_dict=None, return_numpy=True): + """ + This interface is used to run the current model. It should be noted + that the executor will execute all the operators in the Program, + and will not prune some operators in the Program according to the + fetch_list. + + Args: + fetch_list(list): This parameter represents the Tensors that need to be returned + after the model runs. The default is None. + feed(list|dict): This parameter represents the input Tensors of the model. + If it is single card training, the feed is dict type, and if it is multi-card + training, the parameter feed can be dict or list of Tensor. If the + parameter type is dict, the data in the feed will be split and sent to + multiple devices (CPU/GPU), that is to say, the input data will be evenly + sent to different devices, so you should make sure the number of samples of + the current mini-batch must be greater than the number of places; + if the parameter type is list, those data are copied directly to each device, + so the length of this list should be equal to the number of places. + The default is None. + feed_dict: Alias for feed parameter, for backward compatibility. + This parameter has been deprecated. Default None. + return_numpy(bool): This parameter indicates whether convert the fetched Tensors + (the Tensor specified in the fetch list) to numpy.ndarray. if it is False, + the type of the return value is a list of :code:`LoDTensor`. The default is True. + + Returns: + List: The fetched result list. + + Raises: + ValueError: If the feed is a list, but its length is not equal the + length of active places, or its element's is not dict. + + NOTES: + 1. If the feed parameter is dict type, the input data will be evenly distributed + to different cards. For example, using two GPUs to run the model, the input + sample number is 3, that is, [0, 1, 2], the sample number on GPU0 is 1, + that is, [0], and the sample number on GPU1 is 2, that is, [1, 2]. + If the number of samples is less than the number of devices, the program will + throw an exception, so when running the model, you should make sure that the + number of samples of the last batch of the data set should be greater than the + number of CPU cores or GPU cards, if it is less than, it is recommended that + the batch be discarded. + 2. If the number of CPU cores or GPU cards available is greater than 1, the fetch + results are spliced together in dimension 0 for the same Tensor values + (Tensors in fetch_list) on different devices. + + + Examples: + .. code-block:: python + + import paddle + import numpy + import os + + use_cuda = True + paddle.enable_static() + place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() + + # NOTE: If you use CPU to run the program, you need + # to specify the CPU_NUM, otherwise, PaddlePaddle will use + # all the number of the logic core as the CPU_NUM, + # in that case, the batch size of the input should be + # greater than CPU_NUM, if not, the process will be + # failed by an exception. + if not use_cuda: + os.environ['CPU_NUM'] = str(2) + + exe = paddle.static.Executor(place) + + train_program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(train_program, startup_program): + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + exe.run(startup_program) + + train_exe = paddle.static.ParallelExecutor(use_cuda=use_cuda, + main_program=train_program, + loss_name=loss.name) + + # If the feed is a dict: + # the image will be split into devices. If there is two devices + # each device will process an image with shape (5, 1) + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = train_exe.run(feed={"X": x}, + fetch_list=[loss.name]) + + # If the feed is a list: + # each device will process each element in the list. + # the 1st device will process an image with shape (10, 1) + # the 2nd device will process an image with shape (9, 1) + # + # you can use exe.device_count to get the device number. + x2 = numpy.random.random(size=(9, 1)).astype('float32') + loss_data, = train_exe.run(feed=[{"X": x}, {"X": x2}], + fetch_list=[loss.name]) + + """ + return self._exe.run(program=self._compiled_program, + scope=self._scope, + feed=feed, + fetch_list=fetch_list, + return_numpy=return_numpy) + + @property + def device_count(self): + return len(self._places) + + def drop_local_exe_scopes(self): + """ + Drop the local execution scopes immediately. In order to avoid frequently + application and release of temporary variables, the strategy adopted by + ParallelExecutor is to drop the local execution scopes after several iterations. + ParallelExecutor provides the num_iteration_per_drop_scope option in + :code:`paddle.static.ExecutionStrategy`, which indicates how many iterations are intervened to + drop the local execution scopes. If the num_iteration_per_drop_scope value + is 100, but you want to drop the local execution scopes after 50 iterations, + you can call the interface manually. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import numpy + import os + + use_cuda = True + # NOTE: If you use CPU to run the program, you need + # to specify the CPU_NUM, otherwise, PaddlePaddle will use + # all the number of the logic core as the CPU_NUM, + # in that case, the batch size of the input should be + # greater than CPU_NUM, if not, the process will be + # failed by an exception. + if not use_cuda: + os.environ['CPU_NUM'] = str(2) + + paddle.enable_static() + train_program = paddle.static.Program() + startup_program = paddle.static.Program() + with paddle.static.program_guard(train_program, startup_program): + data = paddle.static.data(name='X', shape=[None, 1], dtype='float32') + hidden = paddle.static.nn.fc(data, 10) + loss = paddle.mean(hidden) + + place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(startup_program) + + parallel_exe = paddle.static.ParallelExecutor(use_cuda=use_cuda, + main_program=train_program, + loss_name=loss.name) + + x = numpy.random.random(size=(10, 1)).astype('float32') + loss_data, = parallel_exe.run(feed={"X": x}, + fetch_list=[loss.name]) + + parallel_exe.drop_local_exe_scopes() + + """ + check_type(self._compiled_program._executor, + "the Executor of compiled program", core.ParallelExecutor, + "ParallelExecutor.drop_local_exe_scopes") + self._compiled_program._executor.drop_local_exe_scopes() + + # This API is used to check whether DropLocalExeScopes can work. + def _need_create_local_exe_scopes(self): + check_type(self._compiled_program._executor, + "the Executor of compiled program", core.ParallelExecutor, + "ParallelExecutor._need_create_local_exe_scopes") + return self._compiled_program._executor._need_create_local_exe_scopes() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/param_attr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/param_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..6580c82536a61702975cd227d59994a5153db2dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/param_attr.py @@ -0,0 +1,306 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import six +import warnings +import sys + +from .initializer import Initializer, Xavier, Constant +from .regularizer import WeightDecayRegularizer +from paddle.fluid.data_feeder import check_type + +__all__ = [ + 'ParamAttr', + 'WeightNormParamAttr', +] + + +class ParamAttr(object): + """ + + Note: + ``gradient_clip`` of ``ParamAttr`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + There are three clipping strategies: :ref:`api_paddle_nn_ClipGradByGlobalNorm` , + :ref:`api_paddle_nn_ClipGradByNorm` , :ref:`api_paddle_nn_ClipGradByValue` . + + Create a object to represent the attribute of parameter. The attributes are: + name, initializer, learning rate, regularizer, trainable, gradient clip, + and model average. + + Parameters: + name (str, optional): The parameter's name. Default None, meaning that the name + would be created automatically. + initializer (Initializer, optional): The method to initial this parameter. Default + None, meaning that the weight parameter is initialized by Xavier initializer, + and the bias parameter is initialized by 0. + learning_rate (float, optional): The parameter's learning rate. The learning rate when + optimize is the global learning rates times the parameter's learning rate times + the factor of learning rate scheduler. Default 1.0. + regularizer (WeightDecayRegularizer, optional): Regularization strategy. There are two method: + :ref:`api_paddle_regularizer_L1Decay` , :ref:`api_paddle_regularizer_L2Decay` . If + regularizer is also set in ``optimizer`` (such as :ref:`api_paddle_optimizer_SGD` ), + that regularizer setting in optimizer will be ignored. Default None, meaning there is + no regularization. + trainable (bool, optional): Whether this parameter is trainable. Default True. + do_model_average (bool, optional): Whether this parameter should do model average + when model average is enabled. Only used in ExponentialMovingAverage. Default True. + need_clip (bool, optional): Whether the parameter gradient need to be cliped in optimizer. Default is True. + + Returns: + ParamAttr Object. + + Examples: + + .. code-block:: python + + import paddle + + weight_attr = paddle.ParamAttr(name="weight", + learning_rate=0.5, + regularizer=paddle.regularizer.L2Decay(1.0), + trainable=True) + print(weight_attr.name) # "weight" + paddle.nn.Linear(3, 4, weight_attr=weight_attr) + """ + + def __init__(self, + name=None, + initializer=None, + learning_rate=1.0, + regularizer=None, + trainable=True, + do_model_average=True, + need_clip=True): + + if sys.version_info.major == 2: + check_type(name, "name", (str, type(None), unicode), "ParamAttr") + else: + check_type(name, "name", (str, type(None)), "ParamAttr") + check_type(learning_rate, "learning_rate", (float, int), "ParamAttr") + check_type(trainable, "trainable", (bool), "ParamAttr") + check_type(do_model_average, "do_model_average", (bool), "ParamAttr") + check_type(need_clip, "need_clip", (bool), "ParamAttr") + check_type(initializer, "initializer", (Initializer, type(None)), + "ParamAttr") + check_type(regularizer, "regularizer", + (WeightDecayRegularizer, type(None)), "ParamAttr") + + self.name = name + if self.name == "": + raise ValueError("name of ParamAttr can not be empty str") + + self.initializer = initializer + self.learning_rate = learning_rate + self.regularizer = regularizer + self.trainable = trainable + self.do_model_average = do_model_average + self.need_clip = need_clip + + def _set_default_initializer(self, initializer): + """ + Set the default initializer, the initializer should be Constant, + Uniform, Normal, Xavier, MSRA. + + Args: + initializer(Initializer): the initializer to set. + + Returns: + None + """ + if initializer is None: + if self.initializer is None: + raise ValueError("ParamAttr.initializer is not set") + return + + if self.initializer is not None: + return + + self.initializer = initializer + + def _set_default_param_initializer(self): + """ + Set the default initializer for the parameter with Xavier. + + Args: + None. + + Returns: + None. + """ + self._set_default_initializer(Xavier()) + + def _set_default_bias_initializer(self): + """ + Set the default initializer for the bias with Constant(0.0). + + Args: + None. + + Returns: + None. + """ + self._set_default_initializer(Constant(0.0)) + + @staticmethod + def _to_attr(arg): + """ + Create ParamAttr[s]. + + Args: + arg: Arguments to initialize ParamAttr[s]. arg's type can be + str, Initializer, float, WeightDecayRegularizer, BaseGradientClipAttr, + bool, ParamAttr, or a list of above type. + + Returns: + ParamAttr[s]: ParamAttr[s] initialized with arg. + + Raises: + arg can not initialize a ParamAttr. + """ + if arg is None: + return ParamAttr() + elif isinstance(arg, list) or isinstance(arg, tuple): + return [ParamAttr._to_attr(a) for a in arg] + elif isinstance(arg, ParamAttr): + return arg + elif isinstance(arg, six.string_types): + return ParamAttr(name=arg) + elif isinstance(arg, Initializer): + return ParamAttr(initializer=arg) + elif isinstance(arg, WeightDecayRegularizer): + return ParamAttr(regularizer=arg) + elif isinstance(arg, bool): + return ParamAttr._to_attr(None) if arg else False + else: + raise TypeError("{0} cast to ParamAttr".format(type(arg))) + + def _to_kwargs(self, with_initializer=False): + """ + Returns the attributes of this parameter. + + Args: + with_initializer(bool): Whether to add initializer attr. + + Returns: + Parameter attributes(map): The attributes of this parameter. + """ + kwargs = { + 'name': self.name, + 'optimize_attr': { + 'learning_rate': self.learning_rate + }, + 'regularizer': self.regularizer, + 'trainable': self.trainable, + 'do_model_average': self.do_model_average, + 'need_clip': self.need_clip + } + if with_initializer: + kwargs['initializer'] = self.initializer + return kwargs + + +class WeightNormParamAttr(ParamAttr): + r""" + + Note: + Please use 'paddle.nn.utils.weight_norm' in dygraph mode. + + Note: + ``gradient_clip`` of ``ParamAttr`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + There are three clipping strategies: :ref:`api_paddle_nn_ClipGradByGlobalNorm` , + :ref:`api_paddle_nn_ClipGradByNorm` , :ref:`api_paddle_nn_ClipGradByValue` . + + Parameter of weight Norm. Weight Norm is a reparameterization of the weight vectors + in a neural network that decouples the magnitude of those weight vectors from + their direction. Weight Norm has been implemented as discussed in this + paper: `Weight Normalization: A Simple Reparameterization to Accelerate + Training of Deep Neural Networks + `_. + + Args: + dim(int, optional): Dimension over which to compute the norm. Dim is a non-negative + number which is less than the rank of weight Tensor. For Example, dim can + be chosen from 0, 1, 2, 3 for convolution whose weight shape is [cout, cin, kh, kw] + and rank is 4. Default None, meaning that all elements will be normalized. + name(str, optional): The parameter's name. Default None, meaning that the name would + be created automatically. Please refer to :ref:`api_guide_Name` for more details. + initializer(Initializer, optional): The method to initialize this parameter, such as + ``initializer = paddle.nn.initializer.Constant(1.0)``. Default None, + meaning that the weight parameter is initialized by Xavier initializer, and + the bias parameter is initialized by 0. + learning_rate(float32, optional): The parameter's learning rate when + optimizer is :math:`global\_lr * parameter\_lr * scheduler\_factor`. + Default 1.0. + regularizer (WeightDecayRegularizer, optional): Regularization strategy. There are + two method: :ref:`api_paddle_regularizer_L1Decay` , + :ref:`api_paddle_regularizer_L2Decay`. + If regularizer isralso set in ``optimizer`` + (such as :ref:`api_paddle_optimizer_SGD` ), that regularizer setting in + optimizer will be ignored. Default None, meaning there is no regularization. + trainable(bool, optional): Whether this parameter is trainable. Default True. + do_model_average(bool, optional): Whether this parameter should do model average. + Default False. + need_clip (bool, optional): Whether the parameter gradient need to be cliped in optimizer. Default is True. + + Examples: + + .. code-block:: python + + import paddle + + paddle.enable_static() + + data = paddle.static.data(name="data", shape=[3, 32, 32], dtype="float32") + + fc = paddle.static.nn.fc(x=data, + size=1000, + weight_attr=paddle.static.WeightNormParamAttr( + dim=None, + name='weight_norm_param', + initializer=paddle.nn.initializer.Constant(1.0), + learning_rate=1.0, + regularizer=paddle.regularizer.L2Decay(0.1), + trainable=True, + do_model_average=False, + need_clip=True)) + + """ + # List to record the parameters reparameterized by weight normalization. + # If these parameters are treated as Variable rather than Parameter, + # it can be used to discriminate these parameters and help to serialize + # these paramters for inference. + params_with_weight_norm = [] + + def __init__(self, + dim=None, + name=None, + initializer=None, + learning_rate=1.0, + regularizer=None, + trainable=True, + do_model_average=False, + need_clip=True): + super(WeightNormParamAttr, + self).__init__(name=name, + initializer=initializer, + learning_rate=learning_rate, + regularizer=regularizer, + trainable=trainable, + do_model_average=do_model_average, + need_clip=need_clip) + self.dim = dim diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..5739cdb2f593c0c52fa4b2a25898f22e8ddfa294 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/profiler.py @@ -0,0 +1,422 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from . import core +from .wrapped_decorator import signature_safe_contextmanager +import os +import six +import sys + +from paddle.utils.deprecated import deprecated + +__all__ = [ + 'cuda_profiler', 'reset_profiler', 'profiler', 'start_profiler', + 'stop_profiler' +] + +NVPROF_CONFIG = [ + "gpustarttimestamp", + "gpuendtimestamp", + "gridsize3d", + "threadblocksize", + "streamid", + "enableonstart 0", + "conckerneltrace", +] + + +@deprecated( + since="2.3.0", + update_to="paddle.profiler.Profiler", + level=1, + reason= + "Please use new profiler tool, this profiler tool is no longer maintained.") +@signature_safe_contextmanager +def cuda_profiler(output_file, output_mode=None, config=None): + """ + API cuda_profiler has been abandoned. If you have relevant requirements, you can use `paddle.utils.profiler.start_profiler` and `paddle.utils.profiler.stop_profiler`. + The relevant reference documents are as follows: + + + + """ + raise RuntimeError( + "API cuda_profiler has been abandoned. If you have relevant requirements, you can use `paddle.utils.profiler.start_profiler` and `paddle.utils.profiler.stop_profiler`.\nThe relevant reference documents are as follows:\n\n\n" + ) + + +@signature_safe_contextmanager +def npu_profiler(output_file, config=None): + """ + The NPU profiler. + + This fuctions is used to profile NPU program by NPU runtime application + programming interface. The profiling result will be written into + `output_file`. The users can set set the NPU profiling config by `config` argument. + + After getting the profiling result file, users can use + `tools provided by Ascend `_ + to load this output file to visualize results. + + Args: + output_file (str) : The output file name, the result will be + written into this file. It should be absolute path. + config (list, optional) : NPU profile config. For more details, please + refer to `User Guide `_ . + + Examples: + + .. code-block:: python + + import paddle.fluid as fluid + import paddle.fluid.profiler as profiler + import numpy as np + + epoc = 8 + dshape = [4, 3, 28, 28] + data = fluid.data(name='data', shape=[None, 3, 28, 28], dtype='float32') + conv = fluid.layers.conv2d(data, 20, 3, stride=[1, 1], padding=[1, 1]) + + place = fluid.NPUPlace(0) + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + output_file = 'npu.txt' + with profiler.npu_profiler(output_file) as npu_prof: + for i in range(epoc): + input = np.random.random(dshape).astype('float32') + exe.run(fluid.default_main_program(), feed={'data': input}) + # then use NPU profiler tools to load this output file + # to visualize results. + """ + # TODO: support config in python. + if not config: + config = core.npu_prof_create_config() + + core.npu_prof_init(output_file) + # Enables profiler collection by the active NPU profiling tool. + core.npu_prof_start(config) + try: + yield + # Disables profiler collection. + finally: + core.npu_prof_stop(config) + core.npu_prof_finalize() + + +@deprecated( + since="2.3.0", + update_to="paddle.profiler.Profiler", + level=1, + reason= + "Please use new profiler tool, this profiler tool is no longer maintained.") +def reset_profiler(): + """ + Clear the previous time record. It works for + `fluid.profiler.start_profiler`, `fluid.profiler.stop_profiler`, + and `fluid.profiler.profiler`. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle.fluid as fluid + import paddle.fluid.profiler as profiler + with profiler.profiler('CPU', 'total', '/tmp/profile'): + for iter in range(10): + if iter == 2: + profiler.reset_profiler() + # ... + """ + core.reset_profiler() + + +@deprecated( + since="2.3.0", + update_to="paddle.profiler.Profiler", + level=1, + reason= + "Please use new profiler tool, this profiler tool is no longer maintained.") +def start_profiler(state, tracer_option='Default'): + """ + Enable the profiler. Uers can use `fluid.profiler.start_profiler` and + `fluid.profiler.stop_profiler` to profile, which is equal to the usage + of `fluid.profiler.profiler` interface. + + Args: + state (str) : The profiling state, which should be one of 'CPU', 'GPU' + or 'All'. 'CPU' means only profiling CPU; 'GPU' means profiling + both CPU and GPU; 'All' means profiling both CPU and GPU, and + generates timeline as well. + tracer_option (str, optional) : tracer_option can be one of ['Default', 'OpDetail', 'AllOpDetail'], it + can control the profile level and print the different level profile result. `Default` option print + the different Op type profiling result and the `OpDetail` option print the detail profiling + result of different op types such as compute and data transform, `AllOpDetail` option + print the detail profiling result of different op name same as `OpDetail`. + + Raises: + ValueError: If `state` is not in ['CPU', 'GPU', 'All'] or `tracer_option` + is not in ['Default', 'OpDetail', 'AllOpDetail']. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle.fluid as fluid + import paddle.fluid.profiler as profiler + + profiler.start_profiler('GPU') + for iter in range(10): + if iter == 2: + profiler.reset_profiler() + # except each iteration + profiler.stop_profiler('total', '/tmp/profile') + + profiler.start_profiler('GPU', "OpDetail") + for iter in range(10): + if iter == 2: + profiler.reset_profiler() + # except each iteration + profiler.stop_profiler('total', '/tmp/profile') + """ + if core.is_profiler_enabled(): + return + if state not in ['CPU', 'GPU', "All"]: + raise ValueError("The state must be 'CPU' or 'GPU' or 'All'.") + if state == "GPU": + prof_state = core.ProfilerState.kCUDA + elif state == "CPU": + prof_state = core.ProfilerState.kCPU + else: + prof_state = core.ProfilerState.kAll + + if tracer_option not in ['Default', 'OpDetail', 'AllOpDetail']: + raise ValueError( + "tracer option must be 'Default', 'OpDetail', 'AllOpDetail'.") + if tracer_option == "Default": + prof_tracer_option = core.TracerOption.kDefault + elif tracer_option == "OpDetail": + prof_tracer_option = core.TracerOption.kOpDetail + else: + prof_tracer_option = core.TracerOption.kAllOpDetail + + core.set_tracer_option(prof_tracer_option) + core.enable_profiler(prof_state) + + +@deprecated( + since="2.3.0", + update_to="paddle.profiler.Profiler", + level=1, + reason= + "Please use new profiler tool, this profiler tool is no longer maintained.") +def stop_profiler(sorted_key=None, profile_path='/tmp/profile'): + """ + Stop the profiler. Uers can use `fluid.profiler.start_profiler` and + `fluid.profiler.stop_profiler` to profile, which is equal to the usage + of `fluid.profiler.profiler` interface. + + Args: + sorted_key (str, optional) : The order of profiling results, which + should be one of None, 'calls', 'total', 'max', 'min' or 'ave'. + Default is None, means the profiling results will be printed + in the order of first end time of events. + The `calls` means sorting by the number of calls. + The `total` means sorting by the total execution time. + The `max` means sorting by the maximum execution time. + The `min` means sorting by the minimum execution time. + The `ave` means sorting by the average execution time. + and write it into `profile_path`. The default profile_path is `/tmp/profile`. + profile_path (str, optional) : If state == 'All', it will generate timeline, + + Raises: + ValueError: If `sorted_key` is not in + ['calls', 'total', 'max', 'min', 'ave']. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle.fluid as fluid + import paddle.fluid.profiler as profiler + + profiler.start_profiler('GPU') + for iter in range(10): + if iter == 2: + profiler.reset_profiler() + # except each iteration + profiler.stop_profiler('total', '/tmp/profile') + """ + if not core.is_profiler_enabled(): + return + sorted_key = 'default' if sorted_key is None else sorted_key + if sorted_key not in ['default', 'calls', 'total', 'max', 'min', 'ave']: + raise ValueError("The sorted_key must be None or in 'calls', 'total', " + "'max', 'min' and 'ave'") + key_map = { + 'default': core.EventSortingKey.kDefault, + 'calls': core.EventSortingKey.kCalls, + 'total': core.EventSortingKey.kTotal, + 'max': core.EventSortingKey.kMax, + 'min': core.EventSortingKey.kMin, + 'ave': core.EventSortingKey.kAve, + } + # TODO(qingqing) : redirect C++ ostream to Python stream. + # with core.ostream_redirect(stdout=True, stderr=True): + core.disable_profiler(key_map[sorted_key], profile_path) + + +@deprecated( + since="2.3.0", + update_to="paddle.profiler.Profiler", + level=1, + reason= + "Please use new profiler tool, this profiler tool is no longer maintained.") +@signature_safe_contextmanager +def profiler(state, + sorted_key=None, + profile_path='/tmp/profile', + tracer_option='Default'): + """ + The profiler interface. This profiler can be used to profile both CPU and GPU program. + + Args: + state (str) : The profiling state, which should be one of 'CPU', 'GPU' + or 'All'. 'CPU' means only profiling CPU; 'GPU' means profiling + both CPU and GPU; 'All' means profiling both CPU and GPU, and + generates timeline as well. + sorted_key (str, optional) : The order of profiling results, which + should be one of None, 'calls', 'total', 'max', 'min' or 'ave'. + Default is None, means the profiling results will be printed + in the order of first end time of events. + The `calls` means sorting by the number of calls. + The `total` means sorting by the total execution time. + The `max` means sorting by the maximum execution time. + The `min` means sorting by the minimum execution time. + The `ave` means sorting by the average execution time. + profile_path (str, optional) : If state == 'All', it will generate timeline, + and write it into `profile_path`. The default profile_path is `/tmp/profile`. + tracer_option (str, optional) : tracer_option can be one of ['Default', 'OpDetail', 'AllOpDetail'], it + can control the profile level and print the different level profile result. `Default` option print + the different Op type profiling result and the `OpDetail` option print the detail profiling + result of different op types such as compute and data transform, `AllOpDetail` option + print the detail profiling result of different op name same as `OpDetail`. + + Raises: + ValueError: If `state` is not in ['CPU', 'GPU', 'All']. If `sorted_key` is + not in ['calls', 'total', 'max', 'min', 'ave']. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle.fluid as fluid + import paddle.fluid.profiler as profiler + import numpy as np + import paddle + paddle.enable_static() + + epoc = 8 + dshape = [4, 3, 28, 28] + data = fluid.data(name='data', shape=[None, 3, 28, 28], dtype='float32') + conv = fluid.layers.conv2d(data, 20, 3, stride=[1, 1], padding=[1, 1]) + + place = fluid.CPUPlace() + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + with profiler.profiler('CPU', 'total', '/tmp/profile', 'Default') as prof: + for i in range(epoc): + input = np.random.random(dshape).astype('float32') + exe.run(fluid.default_main_program(), feed={'data': input}) + + Examples Results: + + .. code-block:: text + + #### Examples Results #### + #### 1) sorted_key = 'total', 'calls', 'max', 'min', 'ave' #### + # The only difference in 5 sorted_key results is the following sentence: + # "Sorted by number of xxx in descending order in the same thread." + # The reason is that in this example, above 5 columns are already sorted. + -------------------------> Profiling Report <------------------------- + + Place: CPU + Time unit: ms + Sorted by total time in descending order in the same thread + #Sorted by number of calls in descending order in the same thread + #Sorted by number of max in descending order in the same thread + #Sorted by number of min in descending order in the same thread + #Sorted by number of avg in descending order in the same thread + + Event Calls Total Min. Max. Ave. Ratio. + thread0::conv2d 8 129.406 0.304303 127.076 16.1758 0.983319 + thread0::elementwise_add 8 2.11865 0.193486 0.525592 0.264832 0.016099 + thread0::feed 8 0.076649 0.006834 0.024616 0.00958112 0.000582432 + + #### 2) sorted_key = None #### + # Since the profiling results are printed in the order of first end time of Ops, + # the printed order is feed->conv2d->elementwise_add + -------------------------> Profiling Report <------------------------- + + Place: CPU + Time unit: ms + Sorted by event first end time in descending order in the same thread + + Event Calls Total Min. Max. Ave. Ratio. + thread0::feed 8 0.077419 0.006608 0.023349 0.00967738 0.00775934 + thread0::conv2d 8 7.93456 0.291385 5.63342 0.99182 0.795243 + thread0::elementwise_add 8 1.96555 0.191884 0.518004 0.245693 0.196998 + """ + start_profiler(state, tracer_option) + try: + yield + finally: + stop_profiler(sorted_key, profile_path) + + +@signature_safe_contextmanager +def _nvprof_range(iter_id, start, end, exit_after_prof=True): + ''' + A range profiler interface (not public yet). + + Examples: + + .. code-block:: python + + model = Model() + for i in range(max_iter): + paddle.fluid.profiler._nvprof_range(i, 10, 20): + out = model(in) + ''' + try: + if iter_id == start: + core.nvprof_start() + core.nvprof_enable_record_event() + if iter_id >= start: + core.nvprof_nvtx_push(str(iter_id)) + yield + finally: + if iter_id < end: + core.nvprof_nvtx_pop() + if iter_id == end: + core.nvprof_stop() + if exit_after_prof: + sys.exit() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/data_feed_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/data_feed_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..daa5fc54b3b2f3de7e64a34381907f61331196a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/data_feed_pb2.py @@ -0,0 +1,350 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: data_feed.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='data_feed.proto', + package='paddle.framework', + syntax='proto2', + serialized_pb=_b('\n\x0f\x64\x61ta_feed.proto\x12\x10paddle.framework\"b\n\x04Slot\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04type\x18\x02 \x02(\t\x12\x17\n\x08is_dense\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x16\n\x07is_used\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\r\n\x05shape\x18\x05 \x03(\x05\"H\n\rMultiSlotDesc\x12%\n\x05slots\x18\x01 \x03(\x0b\x32\x16.paddle.framework.Slot\x12\x10\n\x08uid_slot\x18\x02 \x01(\t\"\x95\x02\n\x0bGraphConfig\x12\x16\n\x0bwalk_degree\x18\x01 \x01(\x05:\x01\x31\x12\x14\n\x08walk_len\x18\x02 \x01(\x05:\x02\x32\x30\x12\x11\n\x06window\x18\x03 \x01(\x05:\x01\x35\x12%\n\x17once_sample_startid_len\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\"\n\x16sample_times_one_chunk\x18\x05 \x01(\x05:\x02\x31\x30\x12\x15\n\nbatch_size\x18\x06 \x01(\x05:\x01\x31\x12\x15\n\ndebug_mode\x18\x07 \x01(\x05:\x01\x30\x12\x17\n\x0f\x66irst_node_type\x18\x08 \x01(\t\x12\x11\n\tmeta_path\x18\t \x01(\t\x12 \n\x12gpu_graph_training\x18\n \x01(\x08:\x04true\"\xac\x02\n\x0c\x44\x61taFeedDesc\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x16\n\nbatch_size\x18\x02 \x01(\x05:\x02\x33\x32\x12\x38\n\x0fmulti_slot_desc\x18\x03 \x01(\x0b\x32\x1f.paddle.framework.MultiSlotDesc\x12\x14\n\x0cpipe_command\x18\x04 \x01(\t\x12\x12\n\nthread_num\x18\x05 \x01(\x05\x12\x13\n\x0brank_offset\x18\x06 \x01(\t\x12\x19\n\rpv_batch_size\x18\x07 \x01(\x05:\x02\x33\x32\x12\x15\n\ninput_type\x18\x08 \x01(\x05:\x01\x30\x12\x16\n\x0eso_parser_name\x18\t \x01(\t\x12\x33\n\x0cgraph_config\x18\n \x01(\x0b\x32\x1d.paddle.framework.GraphConfig') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_SLOT = _descriptor.Descriptor( + name='Slot', + full_name='paddle.framework.Slot', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.Slot.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.Slot.type', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_dense', full_name='paddle.framework.Slot.is_dense', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_used', full_name='paddle.framework.Slot.is_used', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shape', full_name='paddle.framework.Slot.shape', index=4, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=37, + serialized_end=135, +) + + +_MULTISLOTDESC = _descriptor.Descriptor( + name='MultiSlotDesc', + full_name='paddle.framework.MultiSlotDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='slots', full_name='paddle.framework.MultiSlotDesc.slots', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uid_slot', full_name='paddle.framework.MultiSlotDesc.uid_slot', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=137, + serialized_end=209, +) + + +_GRAPHCONFIG = _descriptor.Descriptor( + name='GraphConfig', + full_name='paddle.framework.GraphConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='walk_degree', full_name='paddle.framework.GraphConfig.walk_degree', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='walk_len', full_name='paddle.framework.GraphConfig.walk_len', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=20, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='window', full_name='paddle.framework.GraphConfig.window', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='once_sample_startid_len', full_name='paddle.framework.GraphConfig.once_sample_startid_len', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sample_times_one_chunk', full_name='paddle.framework.GraphConfig.sample_times_one_chunk', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='batch_size', full_name='paddle.framework.GraphConfig.batch_size', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='debug_mode', full_name='paddle.framework.GraphConfig.debug_mode', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='first_node_type', full_name='paddle.framework.GraphConfig.first_node_type', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='meta_path', full_name='paddle.framework.GraphConfig.meta_path', index=8, + number=9, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gpu_graph_training', full_name='paddle.framework.GraphConfig.gpu_graph_training', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=212, + serialized_end=489, +) + + +_DATAFEEDDESC = _descriptor.Descriptor( + name='DataFeedDesc', + full_name='paddle.framework.DataFeedDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.DataFeedDesc.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='batch_size', full_name='paddle.framework.DataFeedDesc.batch_size', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=32, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='multi_slot_desc', full_name='paddle.framework.DataFeedDesc.multi_slot_desc', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipe_command', full_name='paddle.framework.DataFeedDesc.pipe_command', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_num', full_name='paddle.framework.DataFeedDesc.thread_num', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='rank_offset', full_name='paddle.framework.DataFeedDesc.rank_offset', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pv_batch_size', full_name='paddle.framework.DataFeedDesc.pv_batch_size', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=32, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='input_type', full_name='paddle.framework.DataFeedDesc.input_type', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='so_parser_name', full_name='paddle.framework.DataFeedDesc.so_parser_name', index=8, + number=9, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_config', full_name='paddle.framework.DataFeedDesc.graph_config', index=9, + number=10, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=492, + serialized_end=792, +) + +_MULTISLOTDESC.fields_by_name['slots'].message_type = _SLOT +_DATAFEEDDESC.fields_by_name['multi_slot_desc'].message_type = _MULTISLOTDESC +_DATAFEEDDESC.fields_by_name['graph_config'].message_type = _GRAPHCONFIG +DESCRIPTOR.message_types_by_name['Slot'] = _SLOT +DESCRIPTOR.message_types_by_name['MultiSlotDesc'] = _MULTISLOTDESC +DESCRIPTOR.message_types_by_name['GraphConfig'] = _GRAPHCONFIG +DESCRIPTOR.message_types_by_name['DataFeedDesc'] = _DATAFEEDDESC + +Slot = _reflection.GeneratedProtocolMessageType('Slot', (_message.Message,), dict( + DESCRIPTOR = _SLOT, + __module__ = 'data_feed_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.Slot) + )) +_sym_db.RegisterMessage(Slot) + +MultiSlotDesc = _reflection.GeneratedProtocolMessageType('MultiSlotDesc', (_message.Message,), dict( + DESCRIPTOR = _MULTISLOTDESC, + __module__ = 'data_feed_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.MultiSlotDesc) + )) +_sym_db.RegisterMessage(MultiSlotDesc) + +GraphConfig = _reflection.GeneratedProtocolMessageType('GraphConfig', (_message.Message,), dict( + DESCRIPTOR = _GRAPHCONFIG, + __module__ = 'data_feed_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.GraphConfig) + )) +_sym_db.RegisterMessage(GraphConfig) + +DataFeedDesc = _reflection.GeneratedProtocolMessageType('DataFeedDesc', (_message.Message,), dict( + DESCRIPTOR = _DATAFEEDDESC, + __module__ = 'data_feed_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.DataFeedDesc) + )) +_sym_db.RegisterMessage(DataFeedDesc) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/distributed_strategy_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/distributed_strategy_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba70f2c82f3ec10ab6786b89887f3fb2bed2bd7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/distributed_strategy_pb2.py @@ -0,0 +1,2716 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: distributed_strategy.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='distributed_strategy.proto', + package='paddle.fleet', + syntax='proto2', + serialized_pb=_b('\n\x1a\x64istributed_strategy.proto\x12\x0cpaddle.fleet\"}\n\x0fRecomputeConfig\x12\x13\n\x0b\x63heckpoints\x18\x01 \x03(\t\x12\x1d\n\x0e\x65nable_offload\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x18\n\x10\x63heckpoint_shape\x18\x03 \x03(\x05\x12\x1c\n\renable_tuning\x18\x04 \x01(\x08:\x05\x66\x61lse\"\xe2\x03\n\x0eShardingConfig\x12\x37\n\x19sharding_segment_strategy\x18\x01 \x01(\t:\x14segment_broadcast_MB\x12 \n\x14segment_broadcast_MB\x18\x02 \x01(\x02:\x02\x33\x32\x12\x17\n\x0fsegment_anchors\x18\x03 \x03(\t\x12\x1a\n\x0fsharding_degree\x18\x04 \x01(\x05:\x01\x38\x12\x14\n\tmp_degree\x18\x05 \x01(\x05:\x01\x31\x12\x14\n\tdp_degree\x18\x06 \x01(\x05:\x01\x31\x12\x18\n\thybrid_dp\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\"\n\x17gradient_merge_acc_step\x18\x08 \x01(\x05:\x01\x31\x12\x1f\n\x10optimize_offload\x18\t \x01(\x08:\x05\x66\x61lse\x12\'\n\x18pp_allreduce_in_optimize\x18\n \x01(\x08:\x05\x66\x61lse\x12\x14\n\tpp_degree\x18\x0b \x01(\x05:\x01\x31\x12\x1c\n\roptimize_cast\x18\x0c \x01(\x08:\x05\x66\x61lse\x12(\n\x19_dp_as_optimizer_sharding\x18\r \x01(\x08:\x05\x66\x61lse\x12\x10\n\x05stage\x18\x0e \x01(\x05:\x01\x31\x12\x1c\n\renable_tuning\x18\x0f \x01(\x08:\x05\x66\x61lse\"m\n\x0cHybridConfig\x12\x15\n\tdp_degree\x18\x01 \x01(\x05:\x02-1\x12\x14\n\tmp_degree\x18\x02 \x01(\x05:\x01\x31\x12\x14\n\tpp_degree\x18\x03 \x01(\x05:\x01\x31\x12\x1a\n\x0fsharding_degree\x18\x04 \x01(\x05:\x01\x31\"\xff\x02\n\tAMPConfig\x12 \n\x11init_loss_scaling\x18\x01 \x01(\x02:\x05\x33\x32\x37\x36\x38\x12 \n\x12incr_every_n_steps\x18\x02 \x01(\x05:\x04\x31\x30\x30\x30\x12\"\n\x17\x64\x65\x63r_every_n_nan_or_inf\x18\x03 \x01(\x05:\x01\x32\x12\x15\n\nincr_ratio\x18\x04 \x01(\x02:\x01\x32\x12\x17\n\ndecr_ratio\x18\x05 \x01(\x02:\x03\x30.8\x12&\n\x18use_dynamic_loss_scaling\x18\x06 \x01(\x08:\x04true\x12\x19\n\x11\x63ustom_white_list\x18\x07 \x03(\t\x12\x19\n\x11\x63ustom_black_list\x18\x08 \x03(\t\x12\x1d\n\x15\x63ustom_black_varnames\x18\t \x03(\t\x12\x1c\n\ruse_pure_fp16\x18\n \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x0euse_fp16_guard\x18\x0b \x01(\x08:\x04true\x12!\n\x12use_optimizer_fp16\x18\x0c \x01(\x08:\x05\x66\x61lse\";\n\x0eLocalSGDConfig\x12\x12\n\x07k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x15\n\nbegin_step\x18\x02 \x01(\x05:\x01\x31\"H\n\x16\x41\x64\x61ptiveLocalSGDConfig\x12\x17\n\x0cinit_k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x15\n\nbegin_step\x18\x02 \x01(\x05:\x01\x31\"<\n\x13GradientMergeConfig\x12\x12\n\x07k_steps\x18\x01 \x01(\x05:\x01\x31\x12\x11\n\x03\x61vg\x18\x02 \x01(\x08:\x04true\"S\n\tDGCConfig\x12\x1c\n\x11rampup_begin_step\x18\x01 \x01(\x05:\x01\x30\x12\x16\n\x0brampup_step\x18\x02 \x01(\x05:\x01\x31\x12\x10\n\x08sparsity\x18\x03 \x03(\x02\"\x81\x01\n\nLarsConfig\x12\x19\n\nlars_coeff\x18\x01 \x01(\x02:\x05\x30.001\x12!\n\x11lars_weight_decay\x18\x02 \x01(\x02:\x06\x30.0005\x12\x12\n\x07\x65psilon\x18\x03 \x01(\x02:\x01\x30\x12!\n\x19\x65xclude_from_weight_decay\x18\x04 \x03(\t\"P\n\nLambConfig\x12\x1f\n\x11lamb_weight_decay\x18\x01 \x01(\x02:\x04\x30.01\x12!\n\x19\x65xclude_from_weight_decay\x18\x02 \x03(\t\"\xf6\x04\n\rBuildStrategy\x12*\n\x1b\x65nable_sequential_execution\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x66use_elewise_add_act_ops\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0f\x66use_bn_act_ops\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x66use_relu_depthwise_conv\x18\x04 \x01(\x08:\x05\x66\x61lse\x12!\n\x12\x66use_broadcast_ops\x18\x05 \x01(\x08:\x05\x66\x61lse\x12%\n\x16\x66use_all_optimizer_ops\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0e\x65nable_inplace\x18\x07 \x01(\x08:\x05\x66\x61lse\x12/\n!enable_backward_optimizer_op_deps\x18\x08 \x01(\x08:\x04true\x12$\n\x15\x63\x61\x63he_runtime_context\x18\t \x01(\x08:\x05\x66\x61lse\x12!\n\x13\x66use_bn_add_act_ops\x18\n \x01(\x08:\x04true\x12!\n\x12\x65nable_auto_fusion\x18\x0b \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0c\x65nable_addto\x18\x0c \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10\x66ix_op_run_order\x18\r \x01(\x08:\x05\x66\x61lse\x12\'\n\x18\x61llow_cuda_graph_capture\x18\x0e \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0freduce_strategy\x18\x0f \x01(\x05:\x01\x30\x12!\n\x12\x66use_gemm_epilogue\x18\x10 \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x13\x64\x65\x62ug_graphviz_path\x18\x11 \x01(\t\"\x9a\x01\n\x11\x45xecutionStrategy\x12\x16\n\x0bnum_threads\x18\x01 \x01(\x05:\x01\x31\x12(\n\x1cnum_iteration_per_drop_scope\x18\x02 \x01(\x05:\x02\x31\x30\x12 \n\x15num_iteration_per_run\x18\x03 \x01(\x05:\x01\x31\x12!\n\x12use_thread_barrier\x18\x04 \x01(\x08:\x05\x66\x61lse\"Q\n\x13GradientScaleConfig\x12\x1b\n\x0escale_strategy\x18\x01 \x01(\t:\x03\x61vg\x12\x1d\n\x0escale_gradient\x18\x02 \x01(\x08:\x05\x66\x61lse\"\x89\x03\n\x0b\x41syncConfig\x12\x13\n\x07k_steps\x18\x01 \x01(\x05:\x02-1\x12\x1c\n\x11max_merge_var_num\x18\x02 \x01(\x05:\x01\x31\x12\x1b\n\x0fsend_queue_size\x18\x03 \x01(\x05:\x02\x31\x36\x12&\n\x17independent_recv_thread\x18\x04 \x01(\x08:\x05\x66\x61lse\x12(\n\x1dmin_send_grad_num_before_recv\x18\x05 \x01(\x05:\x01\x31\x12\x1b\n\x10thread_pool_size\x18\x06 \x01(\x05:\x01\x31\x12\x1a\n\x0fsend_wait_times\x18\x07 \x01(\x05:\x01\x31\x12&\n\x17runtime_split_send_recv\x18\x08 \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x0elaunch_barrier\x18\t \x01(\x08:\x04true\x12&\n\x19heter_worker_device_guard\x18\n \x01(\t:\x03\x63pu\x12\x1a\n\x0elr_decay_steps\x18\x0b \x01(\x05:\x02\x31\x30\x12\x15\n\nuse_ps_gpu\x18\x0c \x01(\x05:\x01\x30\"\xc3\x01\n\x11TrainerDescConfig\x12\x18\n\x10\x64ump_fields_path\x18\x01 \x01(\t\x12\x13\n\x0b\x64ump_fields\x18\x02 \x03(\t\x12\x12\n\ndump_param\x18\x03 \x03(\t\x12\x16\n\x0estat_var_names\x18\x04 \x03(\t\x12\x0f\n\x07trainer\x18\x05 \x01(\t\x12\x15\n\rdevice_worker\x18\x06 \x01(\t\x12\x14\n\x0clocal_sparse\x18\x07 \x03(\t\x12\x15\n\rremote_sparse\x18\x08 \x03(\t\"\xae\x01\n\x0ePipelineConfig\x12\x1b\n\x10micro_batch_size\x18\x01 \x01(\x05:\x01\x31\x12\x1b\n\x10\x61\x63\x63umulate_steps\x18\x02 \x01(\x05:\x01\x31\x12\x1b\n\rschedule_mode\x18\x03 \x01(\t:\x04\x31\x46\x31\x42\x12\x1d\n\x0fp2p_cache_shape\x18\x04 \x01(\x08:\x04true\x12&\n\x18\x65nable_partial_send_recv\x18\x05 \x01(\x08:\x04true\"W\n\x14TensorParallelConfig\x12!\n\x16tensor_parallel_degree\x18\x01 \x01(\x05:\x01\x31\x12\x1c\n\x10tensor_init_seed\x18\x02 \x01(\x05:\x02-1\"\x8c\x01\n\tQatConfig\x12\"\n\x14\x63hannel_wise_abs_max\x18\x01 \x01(\x08:\x04true\x12\x16\n\x0bweight_bits\x18\x02 \x01(\x05:\x01\x38\x12\x1a\n\x0f\x61\x63tivation_bits\x18\x03 \x01(\x05:\x01\x38\x12\x19\n\x11not_quant_pattern\x18\x04 \x03(\t\x12\x0c\n\x04\x61lgo\x18\x05 \x01(\t\"\x9b\x03\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x12\n\ntable_name\x18\x02 \x01(\t\x12\x13\n\x0btable_class\x18\x03 \x01(\t\x12\x17\n\tshard_num\x18\x04 \x01(\x04:\x04\x31\x30\x30\x30\x12%\n\x04type\x18\x05 \x01(\x0e\x32\x17.paddle.fleet.TableType\x12\x36\n\x08\x61\x63\x63\x65ssor\x18\x06 \x01(\x0b\x32$.paddle.fleet.TableAccessorParameter\x12\x1f\n\x10\x63ompress_in_save\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\'\n\x19\x65nable_sparse_table_cache\x18\n \x01(\x08:\x04true\x12(\n\x17sparse_table_cache_rate\x18\x0b \x01(\x01:\x07\x30.00055\x12\'\n\x1bsparse_table_cache_file_num\x18\x0c \x01(\r:\x02\x31\x36\x12\x1c\n\renable_revert\x18\r \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x10shard_merge_rate\x18\x0e \x01(\x02:\x01\x31\"\xac\x03\n\x16TableAccessorParameter\x12\x16\n\x0e\x61\x63\x63\x65ssor_class\x18\x01 \x01(\t\x12\x13\n\x07\x66\x65\x61_dim\x18\x04 \x01(\r:\x02\x31\x31\x12\x15\n\nembedx_dim\x18\x05 \x01(\r:\x01\x38\x12\x1c\n\x10\x65mbedx_threshold\x18\x06 \x01(\r:\x02\x31\x30\x12>\n\x12\x63tr_accessor_param\x18\x07 \x01(\x0b\x32\".paddle.fleet.CtrAccessorParameter\x12K\n\x19table_accessor_save_param\x18\x08 \x03(\x0b\x32(.paddle.fleet.TableAccessorSaveParameter\x12\x33\n\x0f\x65mbed_sgd_param\x18\n \x01(\x0b\x32\x1a.paddle.fleet.SGDParameter\x12\x34\n\x10\x65mbedx_sgd_param\x18\x0b \x01(\x0b\x32\x1a.paddle.fleet.SGDParameter\x12\x38\n\x0fgraph_sgd_param\x18\x0c \x01(\x0b\x32\x1f.paddle.fleet.GraphSGDParameter\"S\n\x11GraphSGDParameter\x12\x19\n\x0bnodeid_slot\x18\x01 \x01(\r:\x04\x39\x30\x30\x38\x12#\n\x15\x66\x65\x61ture_learning_rate\x18\x02 \x01(\x02:\x04\x30.05\"\xc8\x01\n\x0cSGDParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05naive\x18\x02 \x01(\x0b\x32).paddle.fleet.SparseNaiveSGDRuleParameter\x12<\n\x07\x61\x64\x61grad\x18\x03 \x01(\x0b\x32+.paddle.fleet.SparseAdagradSGDRuleParameter\x12\x32\n\x04\x61\x64\x61m\x18\x04 \x01(\x0b\x32$.paddle.fleet.SparseAdamSGDParameter\"p\n\x1bSparseNaiveSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x03 \x03(\x02\"\x8c\x01\n\x1dSparseAdagradSGDRuleParameter\x12\x1b\n\rlearning_rate\x18\x01 \x01(\x01:\x04\x30.05\x12\x18\n\rinitial_g2sum\x18\x02 \x01(\x01:\x01\x33\x12\x1d\n\rinitial_range\x18\x03 \x01(\x01:\x06\x30.0001\x12\x15\n\rweight_bounds\x18\x04 \x03(\x02\"\xc8\x01\n\x16SparseAdamSGDParameter\x12\x1c\n\rlearning_rate\x18\x01 \x01(\x01:\x05\x30.001\x12\x1d\n\rinitial_range\x18\x02 \x01(\x01:\x06\x30.0001\x12\x1d\n\x10\x62\x65ta1_decay_rate\x18\x03 \x01(\x01:\x03\x30.9\x12\x1f\n\x10\x62\x65ta2_decay_rate\x18\x04 \x01(\x01:\x05\x30.999\x12\x1a\n\x0b\x61\x64\x61_epsilon\x18\x05 \x01(\x01:\x05\x31\x65-08\x12\x15\n\rweight_bounds\x18\x06 \x03(\x02\"\xca\x02\n\x14\x43trAccessorParameter\x12\x19\n\x0cnonclk_coeff\x18\x01 \x01(\x02:\x03\x30.1\x12\x16\n\x0b\x63lick_coeff\x18\x02 \x01(\x02:\x01\x31\x12\x1b\n\x0e\x62\x61se_threshold\x18\x03 \x01(\x02:\x03\x31.5\x12\x1d\n\x0f\x64\x65lta_threshold\x18\x04 \x01(\x02:\x04\x30.25\x12\x1b\n\x0f\x64\x65lta_keep_days\x18\x05 \x01(\x02:\x02\x31\x36\x12#\n\x15show_click_decay_rate\x18\x06 \x01(\x02:\x04\x30.98\x12\x1d\n\x10\x64\x65lete_threshold\x18\x07 \x01(\x02:\x03\x30.8\x12$\n\x18\x64\x65lete_after_unseen_days\x18\x08 \x01(\x02:\x02\x33\x30\x12\"\n\x17ssd_unseenday_threshold\x18\t \x01(\x05:\x01\x31\x12\x18\n\nshow_scale\x18\n \x01(\x08:\x04true\"S\n\x1aTableAccessorSaveParameter\x12\r\n\x05param\x18\x01 \x01(\r\x12\x11\n\tconverter\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65\x63onverter\x18\x03 \x01(\t\"R\n\x11\x46sClientParameter\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x0c\n\x04user\x18\x02 \x01(\t\x12\x0e\n\x06passwd\x18\x03 \x01(\t\x12\x12\n\nhadoop_bin\x18\x04 \x01(\t\"\xa3\x13\n\x13\x44istributedStrategy\x12,\n\x04mode\x18\x01 \x01(\x0e\x32\x12.paddle.fleet.Mode:\nCOLLECTIVE\x12\x12\n\x03\x61mp\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x18\n\trecompute\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08localsgd\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03\x64gc\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0egradient_merge\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04lars\x18\x07 \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04lamb\x18\x08 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08pipeline\x18\t \x01(\x08:\x05\x66\x61lse\x12\x16\n\x07\x65lastic\x18\n \x01(\x08:\x05\x66\x61lse\x12\x13\n\x04\x61uto\x18\x0b \x01(\x08:\x05\x66\x61lse\x12\x14\n\x06\x61_sync\x18\x0c \x01(\x08:\x04true\x12!\n\x13sync_nccl_allreduce\x18\r \x01(\x08:\x04true\x12\x18\n\rnccl_comm_num\x18\x0e \x01(\x05:\x01\x31\x12)\n\x1ause_hierarchical_allreduce\x18\x0f \x01(\x08:\x05\x66\x61lse\x12.\n#hierarchical_allreduce_inter_nranks\x18\x10 \x01(\x05:\x01\x31\x12\x1e\n\x0fsync_batch_norm\x18\x11 \x01(\x08:\x05\x66\x61lse\x12!\n\x13\x66use_all_reduce_ops\x18\x12 \x01(\x08:\x04true\x12 \n\x14\x66use_grad_size_in_MB\x18\x13 \x01(\x05:\x02\x33\x32\x12$\n\x18\x66use_grad_size_in_TFLOPS\x18\x14 \x01(\x02:\x02\x35\x30\x12&\n\x17\x63udnn_exhaustive_search\x18\x15 \x01(\x08:\x05\x66\x61lse\x12&\n\x19\x63onv_workspace_size_limit\x18\x16 \x01(\x05:\x03\x35\x31\x32\x12\x31\n\"cudnn_batchnorm_spatial_persistent\x18\x17 \x01(\x08:\x05\x66\x61lse\x12 \n\x11\x61\x64\x61ptive_localsgd\x18\x18 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0e\x66p16_allreduce\x18\x19 \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08sharding\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\"\n\x17last_comm_group_size_MB\x18\x1b \x01(\x02:\x01\x31\x12%\n\x16\x66ind_unused_parameters\x18\x1c \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0ftensor_parallel\x18\x1d \x01(\x08:\x05\x66\x61lse\x12)\n\x1awithout_graph_optimization\x18\x1e \x01(\x08:\x05\x66\x61lse\x12 \n\x15\x66use_grad_size_in_num\x18\x1f \x01(\x05:\x01\x38\x12$\n\x15\x63\x61lc_comm_same_stream\x18 \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03\x61sp\x18! \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0f\x66use_grad_merge\x18\" \x01(\x08:\x05\x66\x61lse\x12\x18\n\tsemi_auto\x18# \x01(\x08:\x05\x66\x61lse\x12\x19\n\nadam_d2sum\x18$ \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0b\x61uto_search\x18% \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0eheter_ccl_mode\x18& \x01(\x08:\x05\x66\x61lse\x12\x1c\n\ris_fl_ps_mode\x18\' \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x10with_coordinator\x18( \x01(\x08:\x05\x66\x61lse\x12\x12\n\x03qat\x18) \x01(\x08:\x05\x66\x61lse\x12\x18\n\nsplit_data\x18* \x01(\x08:\x04true\x12\x38\n\x11recompute_configs\x18\x65 \x01(\x0b\x32\x1d.paddle.fleet.RecomputeConfig\x12,\n\x0b\x61mp_configs\x18\x66 \x01(\x0b\x32\x17.paddle.fleet.AMPConfig\x12\x36\n\x10localsgd_configs\x18g \x01(\x0b\x32\x1c.paddle.fleet.LocalSGDConfig\x12\x41\n\x16gradient_merge_configs\x18h \x01(\x0b\x32!.paddle.fleet.GradientMergeConfig\x12,\n\x0b\x64gc_configs\x18i \x01(\x0b\x32\x17.paddle.fleet.DGCConfig\x12\x36\n\x10pipeline_configs\x18j \x01(\x0b\x32\x1c.paddle.fleet.PipelineConfig\x12\x31\n\x0e\x61_sync_configs\x18k \x01(\x0b\x32\x19.paddle.fleet.AsyncConfig\x12.\n\x0clars_configs\x18l \x01(\x0b\x32\x18.paddle.fleet.LarsConfig\x12.\n\x0clamb_configs\x18m \x01(\x0b\x32\x18.paddle.fleet.LambConfig\x12G\n\x19\x61\x64\x61ptive_localsgd_configs\x18n \x01(\x0b\x32$.paddle.fleet.AdaptiveLocalSGDConfig\x12\x36\n\x10sharding_configs\x18o \x01(\x0b\x32\x1c.paddle.fleet.ShardingConfig\x12\x32\n\x0ehybrid_configs\x18p \x01(\x0b\x32\x1a.paddle.fleet.HybridConfig\x12\x43\n\x17tensor_parallel_configs\x18q \x01(\x0b\x32\".paddle.fleet.TensorParallelConfig\x12=\n\x14trainer_desc_configs\x18r \x01(\x0b\x32\x1f.paddle.fleet.TrainerDescConfig\x12:\n\x14\x64ownpour_table_param\x18s \x03(\x0b\x32\x1c.paddle.fleet.TableParameter\x12\x38\n\x0f\x66s_client_param\x18t \x01(\x0b\x32\x1f.paddle.fleet.FsClientParameter\x12,\n\x0bqat_configs\x18u \x01(\x0b\x32\x17.paddle.fleet.QatConfig\x12\x34\n\x0e\x62uild_strategy\x18\xc9\x01 \x01(\x0b\x32\x1b.paddle.fleet.BuildStrategy\x12<\n\x12\x65xecution_strategy\x18\xca\x01 \x01(\x0b\x32\x1f.paddle.fleet.ExecutionStrategy\x12\x42\n\x16gradient_scale_configs\x18\xcb\x01 \x01(\x0b\x32!.paddle.fleet.GradientScaleConfig\"\xfe\x01\n\x12\x44istributedJobInfo\x12\x12\n\nworker_num\x18\x01 \x01(\x05\x12\x12\n\nserver_num\x18\x02 \x01(\x05\x12\x12\n\nworker_ips\x18\x03 \x03(\t\x12\x18\n\x10server_endpoints\x18\x04 \x03(\t\x12\x16\n\x0eorigin_startup\x18\x05 \x01(\t\x12\x13\n\x0borigin_main\x18\x06 \x01(\t\x12\x18\n\x10\x64istributed_main\x18\x07 \x01(\t\x12\x16\n\x0eoptimizer_name\x18\x08 \x01(\t\x12\x33\n\x08strategy\x18\x65 \x01(\x0b\x32!.paddle.fleet.DistributedStrategy*7\n\x04Mode\x12\x0e\n\nCOLLECTIVE\x10\x01\x12\x06\n\x02PS\x10\x02\x12\x0c\n\x08PIPELINE\x10\x03\x12\t\n\x05HETER\x10\x04*4\n\tTableType\x12\x13\n\x0fPS_SPARSE_TABLE\x10\x00\x12\x12\n\x0ePS_DENSE_TABLE\x10\x01') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_MODE = _descriptor.EnumDescriptor( + name='Mode', + full_name='paddle.fleet.Mode', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='COLLECTIVE', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PIPELINE', index=2, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='HETER', index=3, number=4, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=8347, + serialized_end=8402, +) +_sym_db.RegisterEnumDescriptor(_MODE) + +Mode = enum_type_wrapper.EnumTypeWrapper(_MODE) +_TABLETYPE = _descriptor.EnumDescriptor( + name='TableType', + full_name='paddle.fleet.TableType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='PS_SPARSE_TABLE', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PS_DENSE_TABLE', index=1, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=8404, + serialized_end=8456, +) +_sym_db.RegisterEnumDescriptor(_TABLETYPE) + +TableType = enum_type_wrapper.EnumTypeWrapper(_TABLETYPE) +COLLECTIVE = 1 +PS = 2 +PIPELINE = 3 +HETER = 4 +PS_SPARSE_TABLE = 0 +PS_DENSE_TABLE = 1 + + + +_RECOMPUTECONFIG = _descriptor.Descriptor( + name='RecomputeConfig', + full_name='paddle.fleet.RecomputeConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='checkpoints', full_name='paddle.fleet.RecomputeConfig.checkpoints', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_offload', full_name='paddle.fleet.RecomputeConfig.enable_offload', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='checkpoint_shape', full_name='paddle.fleet.RecomputeConfig.checkpoint_shape', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_tuning', full_name='paddle.fleet.RecomputeConfig.enable_tuning', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=44, + serialized_end=169, +) + + +_SHARDINGCONFIG = _descriptor.Descriptor( + name='ShardingConfig', + full_name='paddle.fleet.ShardingConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sharding_segment_strategy', full_name='paddle.fleet.ShardingConfig.sharding_segment_strategy', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("segment_broadcast_MB").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='segment_broadcast_MB', full_name='paddle.fleet.ShardingConfig.segment_broadcast_MB', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(32), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='segment_anchors', full_name='paddle.fleet.ShardingConfig.segment_anchors', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_degree', full_name='paddle.fleet.ShardingConfig.sharding_degree', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mp_degree', full_name='paddle.fleet.ShardingConfig.mp_degree', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dp_degree', full_name='paddle.fleet.ShardingConfig.dp_degree', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hybrid_dp', full_name='paddle.fleet.ShardingConfig.hybrid_dp', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge_acc_step', full_name='paddle.fleet.ShardingConfig.gradient_merge_acc_step', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimize_offload', full_name='paddle.fleet.ShardingConfig.optimize_offload', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_allreduce_in_optimize', full_name='paddle.fleet.ShardingConfig.pp_allreduce_in_optimize', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_degree', full_name='paddle.fleet.ShardingConfig.pp_degree', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimize_cast', full_name='paddle.fleet.ShardingConfig.optimize_cast', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='_dp_as_optimizer_sharding', full_name='paddle.fleet.ShardingConfig._dp_as_optimizer_sharding', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stage', full_name='paddle.fleet.ShardingConfig.stage', index=13, + number=14, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_tuning', full_name='paddle.fleet.ShardingConfig.enable_tuning', index=14, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=172, + serialized_end=654, +) + + +_HYBRIDCONFIG = _descriptor.Descriptor( + name='HybridConfig', + full_name='paddle.fleet.HybridConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dp_degree', full_name='paddle.fleet.HybridConfig.dp_degree', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mp_degree', full_name='paddle.fleet.HybridConfig.mp_degree', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pp_degree', full_name='paddle.fleet.HybridConfig.pp_degree', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_degree', full_name='paddle.fleet.HybridConfig.sharding_degree', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=656, + serialized_end=765, +) + + +_AMPCONFIG = _descriptor.Descriptor( + name='AMPConfig', + full_name='paddle.fleet.AMPConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='init_loss_scaling', full_name='paddle.fleet.AMPConfig.init_loss_scaling', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(32768), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='incr_every_n_steps', full_name='paddle.fleet.AMPConfig.incr_every_n_steps', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='decr_every_n_nan_or_inf', full_name='paddle.fleet.AMPConfig.decr_every_n_nan_or_inf', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=2, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='incr_ratio', full_name='paddle.fleet.AMPConfig.incr_ratio', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(2), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='decr_ratio', full_name='paddle.fleet.AMPConfig.decr_ratio', index=4, + number=5, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.8), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_dynamic_loss_scaling', full_name='paddle.fleet.AMPConfig.use_dynamic_loss_scaling', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_white_list', full_name='paddle.fleet.AMPConfig.custom_white_list', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_black_list', full_name='paddle.fleet.AMPConfig.custom_black_list', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='custom_black_varnames', full_name='paddle.fleet.AMPConfig.custom_black_varnames', index=8, + number=9, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_pure_fp16', full_name='paddle.fleet.AMPConfig.use_pure_fp16', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_fp16_guard', full_name='paddle.fleet.AMPConfig.use_fp16_guard', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_optimizer_fp16', full_name='paddle.fleet.AMPConfig.use_optimizer_fp16', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=768, + serialized_end=1151, +) + + +_LOCALSGDCONFIG = _descriptor.Descriptor( + name='LocalSGDConfig', + full_name='paddle.fleet.LocalSGDConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.LocalSGDConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='begin_step', full_name='paddle.fleet.LocalSGDConfig.begin_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1153, + serialized_end=1212, +) + + +_ADAPTIVELOCALSGDCONFIG = _descriptor.Descriptor( + name='AdaptiveLocalSGDConfig', + full_name='paddle.fleet.AdaptiveLocalSGDConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='init_k_steps', full_name='paddle.fleet.AdaptiveLocalSGDConfig.init_k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='begin_step', full_name='paddle.fleet.AdaptiveLocalSGDConfig.begin_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1214, + serialized_end=1286, +) + + +_GRADIENTMERGECONFIG = _descriptor.Descriptor( + name='GradientMergeConfig', + full_name='paddle.fleet.GradientMergeConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.GradientMergeConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='avg', full_name='paddle.fleet.GradientMergeConfig.avg', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1288, + serialized_end=1348, +) + + +_DGCCONFIG = _descriptor.Descriptor( + name='DGCConfig', + full_name='paddle.fleet.DGCConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='rampup_begin_step', full_name='paddle.fleet.DGCConfig.rampup_begin_step', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='rampup_step', full_name='paddle.fleet.DGCConfig.rampup_step', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparsity', full_name='paddle.fleet.DGCConfig.sparsity', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1350, + serialized_end=1433, +) + + +_LARSCONFIG = _descriptor.Descriptor( + name='LarsConfig', + full_name='paddle.fleet.LarsConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='lars_coeff', full_name='paddle.fleet.LarsConfig.lars_coeff', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars_weight_decay', full_name='paddle.fleet.LarsConfig.lars_weight_decay', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.0005), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='epsilon', full_name='paddle.fleet.LarsConfig.epsilon', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='exclude_from_weight_decay', full_name='paddle.fleet.LarsConfig.exclude_from_weight_decay', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1436, + serialized_end=1565, +) + + +_LAMBCONFIG = _descriptor.Descriptor( + name='LambConfig', + full_name='paddle.fleet.LambConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='lamb_weight_decay', full_name='paddle.fleet.LambConfig.lamb_weight_decay', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.01), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='exclude_from_weight_decay', full_name='paddle.fleet.LambConfig.exclude_from_weight_decay', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1567, + serialized_end=1647, +) + + +_BUILDSTRATEGY = _descriptor.Descriptor( + name='BuildStrategy', + full_name='paddle.fleet.BuildStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='enable_sequential_execution', full_name='paddle.fleet.BuildStrategy.enable_sequential_execution', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_elewise_add_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_elewise_add_act_ops', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_bn_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_bn_act_ops', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_relu_depthwise_conv', full_name='paddle.fleet.BuildStrategy.fuse_relu_depthwise_conv', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_broadcast_ops', full_name='paddle.fleet.BuildStrategy.fuse_broadcast_ops', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_all_optimizer_ops', full_name='paddle.fleet.BuildStrategy.fuse_all_optimizer_ops', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_inplace', full_name='paddle.fleet.BuildStrategy.enable_inplace', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_backward_optimizer_op_deps', full_name='paddle.fleet.BuildStrategy.enable_backward_optimizer_op_deps', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cache_runtime_context', full_name='paddle.fleet.BuildStrategy.cache_runtime_context', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_bn_add_act_ops', full_name='paddle.fleet.BuildStrategy.fuse_bn_add_act_ops', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_auto_fusion', full_name='paddle.fleet.BuildStrategy.enable_auto_fusion', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_addto', full_name='paddle.fleet.BuildStrategy.enable_addto', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fix_op_run_order', full_name='paddle.fleet.BuildStrategy.fix_op_run_order', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='allow_cuda_graph_capture', full_name='paddle.fleet.BuildStrategy.allow_cuda_graph_capture', index=13, + number=14, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='reduce_strategy', full_name='paddle.fleet.BuildStrategy.reduce_strategy', index=14, + number=15, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_gemm_epilogue', full_name='paddle.fleet.BuildStrategy.fuse_gemm_epilogue', index=15, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='debug_graphviz_path', full_name='paddle.fleet.BuildStrategy.debug_graphviz_path', index=16, + number=17, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1650, + serialized_end=2280, +) + + +_EXECUTIONSTRATEGY = _descriptor.Descriptor( + name='ExecutionStrategy', + full_name='paddle.fleet.ExecutionStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='num_threads', full_name='paddle.fleet.ExecutionStrategy.num_threads', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_iteration_per_drop_scope', full_name='paddle.fleet.ExecutionStrategy.num_iteration_per_drop_scope', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_iteration_per_run', full_name='paddle.fleet.ExecutionStrategy.num_iteration_per_run', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_thread_barrier', full_name='paddle.fleet.ExecutionStrategy.use_thread_barrier', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2283, + serialized_end=2437, +) + + +_GRADIENTSCALECONFIG = _descriptor.Descriptor( + name='GradientScaleConfig', + full_name='paddle.fleet.GradientScaleConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='scale_strategy', full_name='paddle.fleet.GradientScaleConfig.scale_strategy', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("avg").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='scale_gradient', full_name='paddle.fleet.GradientScaleConfig.scale_gradient', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2439, + serialized_end=2520, +) + + +_ASYNCCONFIG = _descriptor.Descriptor( + name='AsyncConfig', + full_name='paddle.fleet.AsyncConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='k_steps', full_name='paddle.fleet.AsyncConfig.k_steps', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='max_merge_var_num', full_name='paddle.fleet.AsyncConfig.max_merge_var_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='send_queue_size', full_name='paddle.fleet.AsyncConfig.send_queue_size', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='independent_recv_thread', full_name='paddle.fleet.AsyncConfig.independent_recv_thread', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='min_send_grad_num_before_recv', full_name='paddle.fleet.AsyncConfig.min_send_grad_num_before_recv', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_pool_size', full_name='paddle.fleet.AsyncConfig.thread_pool_size', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='send_wait_times', full_name='paddle.fleet.AsyncConfig.send_wait_times', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='runtime_split_send_recv', full_name='paddle.fleet.AsyncConfig.runtime_split_send_recv', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='launch_barrier', full_name='paddle.fleet.AsyncConfig.launch_barrier', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='heter_worker_device_guard', full_name='paddle.fleet.AsyncConfig.heter_worker_device_guard', index=9, + number=10, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("cpu").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lr_decay_steps', full_name='paddle.fleet.AsyncConfig.lr_decay_steps', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_ps_gpu', full_name='paddle.fleet.AsyncConfig.use_ps_gpu', index=11, + number=12, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2523, + serialized_end=2916, +) + + +_TRAINERDESCCONFIG = _descriptor.Descriptor( + name='TrainerDescConfig', + full_name='paddle.fleet.TrainerDescConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dump_fields_path', full_name='paddle.fleet.TrainerDescConfig.dump_fields_path', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_fields', full_name='paddle.fleet.TrainerDescConfig.dump_fields', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_param', full_name='paddle.fleet.TrainerDescConfig.dump_param', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stat_var_names', full_name='paddle.fleet.TrainerDescConfig.stat_var_names', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer', full_name='paddle.fleet.TrainerDescConfig.trainer', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_worker', full_name='paddle.fleet.TrainerDescConfig.device_worker', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='local_sparse', full_name='paddle.fleet.TrainerDescConfig.local_sparse', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='remote_sparse', full_name='paddle.fleet.TrainerDescConfig.remote_sparse', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2919, + serialized_end=3114, +) + + +_PIPELINECONFIG = _descriptor.Descriptor( + name='PipelineConfig', + full_name='paddle.fleet.PipelineConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='micro_batch_size', full_name='paddle.fleet.PipelineConfig.micro_batch_size', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='accumulate_steps', full_name='paddle.fleet.PipelineConfig.accumulate_steps', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='schedule_mode', full_name='paddle.fleet.PipelineConfig.schedule_mode', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("1F1B").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='p2p_cache_shape', full_name='paddle.fleet.PipelineConfig.p2p_cache_shape', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_partial_send_recv', full_name='paddle.fleet.PipelineConfig.enable_partial_send_recv', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3117, + serialized_end=3291, +) + + +_TENSORPARALLELCONFIG = _descriptor.Descriptor( + name='TensorParallelConfig', + full_name='paddle.fleet.TensorParallelConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='tensor_parallel_degree', full_name='paddle.fleet.TensorParallelConfig.tensor_parallel_degree', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_init_seed', full_name='paddle.fleet.TensorParallelConfig.tensor_init_seed', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3293, + serialized_end=3380, +) + + +_QATCONFIG = _descriptor.Descriptor( + name='QatConfig', + full_name='paddle.fleet.QatConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='channel_wise_abs_max', full_name='paddle.fleet.QatConfig.channel_wise_abs_max', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bits', full_name='paddle.fleet.QatConfig.weight_bits', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='activation_bits', full_name='paddle.fleet.QatConfig.activation_bits', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='not_quant_pattern', full_name='paddle.fleet.QatConfig.not_quant_pattern', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='algo', full_name='paddle.fleet.QatConfig.algo', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3383, + serialized_end=3523, +) + + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.fleet.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.fleet.TableParameter.table_id', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_name', full_name='paddle.fleet.TableParameter.table_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_class', full_name='paddle.fleet.TableParameter.table_class', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_num', full_name='paddle.fleet.TableParameter.shard_num', index=3, + number=4, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=1000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.fleet.TableParameter.type', index=4, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='accessor', full_name='paddle.fleet.TableParameter.accessor', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='compress_in_save', full_name='paddle.fleet.TableParameter.compress_in_save', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_sparse_table_cache', full_name='paddle.fleet.TableParameter.enable_sparse_table_cache', index=7, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_rate', full_name='paddle.fleet.TableParameter.sparse_table_cache_rate', index=8, + number=11, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.00055), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_table_cache_file_num', full_name='paddle.fleet.TableParameter.sparse_table_cache_file_num', index=9, + number=12, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_revert', full_name='paddle.fleet.TableParameter.enable_revert', index=10, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='shard_merge_rate', full_name='paddle.fleet.TableParameter.shard_merge_rate', index=11, + number=14, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3526, + serialized_end=3937, +) + + +_TABLEACCESSORPARAMETER = _descriptor.Descriptor( + name='TableAccessorParameter', + full_name='paddle.fleet.TableAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='accessor_class', full_name='paddle.fleet.TableAccessorParameter.accessor_class', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', full_name='paddle.fleet.TableAccessorParameter.fea_dim', index=1, + number=4, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=11, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_dim', full_name='paddle.fleet.TableAccessorParameter.embedx_dim', index=2, + number=5, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_threshold', full_name='paddle.fleet.TableAccessorParameter.embedx_threshold', index=3, + number=6, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=10, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ctr_accessor_param', full_name='paddle.fleet.TableAccessorParameter.ctr_accessor_param', index=4, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_accessor_save_param', full_name='paddle.fleet.TableAccessorParameter.table_accessor_save_param', index=5, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embed_sgd_param', full_name='paddle.fleet.TableAccessorParameter.embed_sgd_param', index=6, + number=10, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='embedx_sgd_param', full_name='paddle.fleet.TableAccessorParameter.embedx_sgd_param', index=7, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='graph_sgd_param', full_name='paddle.fleet.TableAccessorParameter.graph_sgd_param', index=8, + number=12, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3940, + serialized_end=4368, +) + + +_GRAPHSGDPARAMETER = _descriptor.Descriptor( + name='GraphSGDParameter', + full_name='paddle.fleet.GraphSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nodeid_slot', full_name='paddle.fleet.GraphSGDParameter.nodeid_slot', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=9008, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='feature_learning_rate', full_name='paddle.fleet.GraphSGDParameter.feature_learning_rate', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4370, + serialized_end=4453, +) + + +_SGDPARAMETER = _descriptor.Descriptor( + name='SGDParameter', + full_name='paddle.fleet.SGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.fleet.SGDParameter.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='naive', full_name='paddle.fleet.SGDParameter.naive', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adagrad', full_name='paddle.fleet.SGDParameter.adagrad', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam', full_name='paddle.fleet.SGDParameter.adam', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4456, + serialized_end=4656, +) + + +_SPARSENAIVESGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseNaiveSGDRuleParameter', + full_name='paddle.fleet.SparseNaiveSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseNaiveSGDRuleParameter.weight_bounds', index=2, + number=3, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4658, + serialized_end=4770, +) + + +_SPARSEADAGRADSGDRULEPARAMETER = _descriptor.Descriptor( + name='SparseAdagradSGDRuleParameter', + full_name='paddle.fleet.SparseAdagradSGDRuleParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.05), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_g2sum', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.initial_g2sum', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(3), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.initial_range', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseAdagradSGDRuleParameter.weight_bounds', index=3, + number=4, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4773, + serialized_end=4913, +) + + +_SPARSEADAMSGDPARAMETER = _descriptor.Descriptor( + name='SparseAdamSGDParameter', + full_name='paddle.fleet.SparseAdamSGDParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='learning_rate', full_name='paddle.fleet.SparseAdamSGDParameter.learning_rate', index=0, + number=1, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='initial_range', full_name='paddle.fleet.SparseAdamSGDParameter.initial_range', index=1, + number=2, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.0001), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta1_decay_rate', full_name='paddle.fleet.SparseAdamSGDParameter.beta1_decay_rate', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.9), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='beta2_decay_rate', full_name='paddle.fleet.SparseAdamSGDParameter.beta2_decay_rate', index=3, + number=4, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(0.999), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ada_epsilon', full_name='paddle.fleet.SparseAdamSGDParameter.ada_epsilon', index=4, + number=5, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=float(1e-08), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weight_bounds', full_name='paddle.fleet.SparseAdamSGDParameter.weight_bounds', index=5, + number=6, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4916, + serialized_end=5116, +) + + +_CTRACCESSORPARAMETER = _descriptor.Descriptor( + name='CtrAccessorParameter', + full_name='paddle.fleet.CtrAccessorParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nonclk_coeff', full_name='paddle.fleet.CtrAccessorParameter.nonclk_coeff', index=0, + number=1, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='click_coeff', full_name='paddle.fleet.CtrAccessorParameter.click_coeff', index=1, + number=2, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='base_threshold', full_name='paddle.fleet.CtrAccessorParameter.base_threshold', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1.5), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_threshold', full_name='paddle.fleet.CtrAccessorParameter.delta_threshold', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.25), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delta_keep_days', full_name='paddle.fleet.CtrAccessorParameter.delta_keep_days', index=4, + number=5, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(16), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_click_decay_rate', full_name='paddle.fleet.CtrAccessorParameter.show_click_decay_rate', index=5, + number=6, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.98), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_threshold', full_name='paddle.fleet.CtrAccessorParameter.delete_threshold', index=6, + number=7, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0.8), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete_after_unseen_days', full_name='paddle.fleet.CtrAccessorParameter.delete_after_unseen_days', index=7, + number=8, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(30), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ssd_unseenday_threshold', full_name='paddle.fleet.CtrAccessorParameter.ssd_unseenday_threshold', index=8, + number=9, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='show_scale', full_name='paddle.fleet.CtrAccessorParameter.show_scale', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5119, + serialized_end=5449, +) + + +_TABLEACCESSORSAVEPARAMETER = _descriptor.Descriptor( + name='TableAccessorSaveParameter', + full_name='paddle.fleet.TableAccessorSaveParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='param', full_name='paddle.fleet.TableAccessorSaveParameter.param', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='converter', full_name='paddle.fleet.TableAccessorSaveParameter.converter', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deconverter', full_name='paddle.fleet.TableAccessorSaveParameter.deconverter', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5451, + serialized_end=5534, +) + + +_FSCLIENTPARAMETER = _descriptor.Descriptor( + name='FsClientParameter', + full_name='paddle.fleet.FsClientParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='uri', full_name='paddle.fleet.FsClientParameter.uri', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='user', full_name='paddle.fleet.FsClientParameter.user', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='passwd', full_name='paddle.fleet.FsClientParameter.passwd', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hadoop_bin', full_name='paddle.fleet.FsClientParameter.hadoop_bin', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5536, + serialized_end=5618, +) + + +_DISTRIBUTEDSTRATEGY = _descriptor.Descriptor( + name='DistributedStrategy', + full_name='paddle.fleet.DistributedStrategy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='mode', full_name='paddle.fleet.DistributedStrategy.mode', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='amp', full_name='paddle.fleet.DistributedStrategy.amp', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='recompute', full_name='paddle.fleet.DistributedStrategy.recompute', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='localsgd', full_name='paddle.fleet.DistributedStrategy.localsgd', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dgc', full_name='paddle.fleet.DistributedStrategy.dgc', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge', full_name='paddle.fleet.DistributedStrategy.gradient_merge', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars', full_name='paddle.fleet.DistributedStrategy.lars', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lamb', full_name='paddle.fleet.DistributedStrategy.lamb', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline', full_name='paddle.fleet.DistributedStrategy.pipeline', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='elastic', full_name='paddle.fleet.DistributedStrategy.elastic', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='auto', full_name='paddle.fleet.DistributedStrategy.auto', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='a_sync', full_name='paddle.fleet.DistributedStrategy.a_sync', index=11, + number=12, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_nccl_allreduce', full_name='paddle.fleet.DistributedStrategy.sync_nccl_allreduce', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nccl_comm_num', full_name='paddle.fleet.DistributedStrategy.nccl_comm_num', index=13, + number=14, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_hierarchical_allreduce', full_name='paddle.fleet.DistributedStrategy.use_hierarchical_allreduce', index=14, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hierarchical_allreduce_inter_nranks', full_name='paddle.fleet.DistributedStrategy.hierarchical_allreduce_inter_nranks', index=15, + number=16, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_batch_norm', full_name='paddle.fleet.DistributedStrategy.sync_batch_norm', index=16, + number=17, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_all_reduce_ops', full_name='paddle.fleet.DistributedStrategy.fuse_all_reduce_ops', index=17, + number=18, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_MB', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_MB', index=18, + number=19, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=32, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_TFLOPS', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_TFLOPS', index=19, + number=20, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(50), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cudnn_exhaustive_search', full_name='paddle.fleet.DistributedStrategy.cudnn_exhaustive_search', index=20, + number=21, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='conv_workspace_size_limit', full_name='paddle.fleet.DistributedStrategy.conv_workspace_size_limit', index=21, + number=22, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=512, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cudnn_batchnorm_spatial_persistent', full_name='paddle.fleet.DistributedStrategy.cudnn_batchnorm_spatial_persistent', index=22, + number=23, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adaptive_localsgd', full_name='paddle.fleet.DistributedStrategy.adaptive_localsgd', index=23, + number=24, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fp16_allreduce', full_name='paddle.fleet.DistributedStrategy.fp16_allreduce', index=24, + number=25, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding', full_name='paddle.fleet.DistributedStrategy.sharding', index=25, + number=26, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='last_comm_group_size_MB', full_name='paddle.fleet.DistributedStrategy.last_comm_group_size_MB', index=26, + number=27, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='find_unused_parameters', full_name='paddle.fleet.DistributedStrategy.find_unused_parameters', index=27, + number=28, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_parallel', full_name='paddle.fleet.DistributedStrategy.tensor_parallel', index=28, + number=29, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='without_graph_optimization', full_name='paddle.fleet.DistributedStrategy.without_graph_optimization', index=29, + number=30, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_size_in_num', full_name='paddle.fleet.DistributedStrategy.fuse_grad_size_in_num', index=30, + number=31, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='calc_comm_same_stream', full_name='paddle.fleet.DistributedStrategy.calc_comm_same_stream', index=31, + number=32, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='asp', full_name='paddle.fleet.DistributedStrategy.asp', index=32, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fuse_grad_merge', full_name='paddle.fleet.DistributedStrategy.fuse_grad_merge', index=33, + number=34, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='semi_auto', full_name='paddle.fleet.DistributedStrategy.semi_auto', index=34, + number=35, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adam_d2sum', full_name='paddle.fleet.DistributedStrategy.adam_d2sum', index=35, + number=36, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='auto_search', full_name='paddle.fleet.DistributedStrategy.auto_search', index=36, + number=37, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='heter_ccl_mode', full_name='paddle.fleet.DistributedStrategy.heter_ccl_mode', index=37, + number=38, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_fl_ps_mode', full_name='paddle.fleet.DistributedStrategy.is_fl_ps_mode', index=38, + number=39, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='with_coordinator', full_name='paddle.fleet.DistributedStrategy.with_coordinator', index=39, + number=40, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='qat', full_name='paddle.fleet.DistributedStrategy.qat', index=40, + number=41, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='split_data', full_name='paddle.fleet.DistributedStrategy.split_data', index=41, + number=42, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='recompute_configs', full_name='paddle.fleet.DistributedStrategy.recompute_configs', index=42, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='amp_configs', full_name='paddle.fleet.DistributedStrategy.amp_configs', index=43, + number=102, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='localsgd_configs', full_name='paddle.fleet.DistributedStrategy.localsgd_configs', index=44, + number=103, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_merge_configs', full_name='paddle.fleet.DistributedStrategy.gradient_merge_configs', index=45, + number=104, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dgc_configs', full_name='paddle.fleet.DistributedStrategy.dgc_configs', index=46, + number=105, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline_configs', full_name='paddle.fleet.DistributedStrategy.pipeline_configs', index=47, + number=106, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='a_sync_configs', full_name='paddle.fleet.DistributedStrategy.a_sync_configs', index=48, + number=107, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lars_configs', full_name='paddle.fleet.DistributedStrategy.lars_configs', index=49, + number=108, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lamb_configs', full_name='paddle.fleet.DistributedStrategy.lamb_configs', index=50, + number=109, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adaptive_localsgd_configs', full_name='paddle.fleet.DistributedStrategy.adaptive_localsgd_configs', index=51, + number=110, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sharding_configs', full_name='paddle.fleet.DistributedStrategy.sharding_configs', index=52, + number=111, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hybrid_configs', full_name='paddle.fleet.DistributedStrategy.hybrid_configs', index=53, + number=112, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_parallel_configs', full_name='paddle.fleet.DistributedStrategy.tensor_parallel_configs', index=54, + number=113, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_desc_configs', full_name='paddle.fleet.DistributedStrategy.trainer_desc_configs', index=55, + number=114, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='downpour_table_param', full_name='paddle.fleet.DistributedStrategy.downpour_table_param', index=56, + number=115, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fs_client_param', full_name='paddle.fleet.DistributedStrategy.fs_client_param', index=57, + number=116, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='qat_configs', full_name='paddle.fleet.DistributedStrategy.qat_configs', index=58, + number=117, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='build_strategy', full_name='paddle.fleet.DistributedStrategy.build_strategy', index=59, + number=201, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='execution_strategy', full_name='paddle.fleet.DistributedStrategy.execution_strategy', index=60, + number=202, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='gradient_scale_configs', full_name='paddle.fleet.DistributedStrategy.gradient_scale_configs', index=61, + number=203, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=5621, + serialized_end=8088, +) + + +_DISTRIBUTEDJOBINFO = _descriptor.Descriptor( + name='DistributedJobInfo', + full_name='paddle.fleet.DistributedJobInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='worker_num', full_name='paddle.fleet.DistributedJobInfo.worker_num', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_num', full_name='paddle.fleet.DistributedJobInfo.server_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='worker_ips', full_name='paddle.fleet.DistributedJobInfo.worker_ips', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='server_endpoints', full_name='paddle.fleet.DistributedJobInfo.server_endpoints', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='origin_startup', full_name='paddle.fleet.DistributedJobInfo.origin_startup', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='origin_main', full_name='paddle.fleet.DistributedJobInfo.origin_main', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='distributed_main', full_name='paddle.fleet.DistributedJobInfo.distributed_main', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimizer_name', full_name='paddle.fleet.DistributedJobInfo.optimizer_name', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='strategy', full_name='paddle.fleet.DistributedJobInfo.strategy', index=8, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=8091, + serialized_end=8345, +) + +_TABLEPARAMETER.fields_by_name['type'].enum_type = _TABLETYPE +_TABLEPARAMETER.fields_by_name['accessor'].message_type = _TABLEACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['ctr_accessor_param'].message_type = _CTRACCESSORPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['table_accessor_save_param'].message_type = _TABLEACCESSORSAVEPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embed_sgd_param'].message_type = _SGDPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['embedx_sgd_param'].message_type = _SGDPARAMETER +_TABLEACCESSORPARAMETER.fields_by_name['graph_sgd_param'].message_type = _GRAPHSGDPARAMETER +_SGDPARAMETER.fields_by_name['naive'].message_type = _SPARSENAIVESGDRULEPARAMETER +_SGDPARAMETER.fields_by_name['adagrad'].message_type = _SPARSEADAGRADSGDRULEPARAMETER +_SGDPARAMETER.fields_by_name['adam'].message_type = _SPARSEADAMSGDPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['mode'].enum_type = _MODE +_DISTRIBUTEDSTRATEGY.fields_by_name['recompute_configs'].message_type = _RECOMPUTECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['amp_configs'].message_type = _AMPCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['localsgd_configs'].message_type = _LOCALSGDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['gradient_merge_configs'].message_type = _GRADIENTMERGECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['dgc_configs'].message_type = _DGCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['pipeline_configs'].message_type = _PIPELINECONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['a_sync_configs'].message_type = _ASYNCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['lars_configs'].message_type = _LARSCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['lamb_configs'].message_type = _LAMBCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['adaptive_localsgd_configs'].message_type = _ADAPTIVELOCALSGDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['sharding_configs'].message_type = _SHARDINGCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['hybrid_configs'].message_type = _HYBRIDCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['tensor_parallel_configs'].message_type = _TENSORPARALLELCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['trainer_desc_configs'].message_type = _TRAINERDESCCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['downpour_table_param'].message_type = _TABLEPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['fs_client_param'].message_type = _FSCLIENTPARAMETER +_DISTRIBUTEDSTRATEGY.fields_by_name['qat_configs'].message_type = _QATCONFIG +_DISTRIBUTEDSTRATEGY.fields_by_name['build_strategy'].message_type = _BUILDSTRATEGY +_DISTRIBUTEDSTRATEGY.fields_by_name['execution_strategy'].message_type = _EXECUTIONSTRATEGY +_DISTRIBUTEDSTRATEGY.fields_by_name['gradient_scale_configs'].message_type = _GRADIENTSCALECONFIG +_DISTRIBUTEDJOBINFO.fields_by_name['strategy'].message_type = _DISTRIBUTEDSTRATEGY +DESCRIPTOR.message_types_by_name['RecomputeConfig'] = _RECOMPUTECONFIG +DESCRIPTOR.message_types_by_name['ShardingConfig'] = _SHARDINGCONFIG +DESCRIPTOR.message_types_by_name['HybridConfig'] = _HYBRIDCONFIG +DESCRIPTOR.message_types_by_name['AMPConfig'] = _AMPCONFIG +DESCRIPTOR.message_types_by_name['LocalSGDConfig'] = _LOCALSGDCONFIG +DESCRIPTOR.message_types_by_name['AdaptiveLocalSGDConfig'] = _ADAPTIVELOCALSGDCONFIG +DESCRIPTOR.message_types_by_name['GradientMergeConfig'] = _GRADIENTMERGECONFIG +DESCRIPTOR.message_types_by_name['DGCConfig'] = _DGCCONFIG +DESCRIPTOR.message_types_by_name['LarsConfig'] = _LARSCONFIG +DESCRIPTOR.message_types_by_name['LambConfig'] = _LAMBCONFIG +DESCRIPTOR.message_types_by_name['BuildStrategy'] = _BUILDSTRATEGY +DESCRIPTOR.message_types_by_name['ExecutionStrategy'] = _EXECUTIONSTRATEGY +DESCRIPTOR.message_types_by_name['GradientScaleConfig'] = _GRADIENTSCALECONFIG +DESCRIPTOR.message_types_by_name['AsyncConfig'] = _ASYNCCONFIG +DESCRIPTOR.message_types_by_name['TrainerDescConfig'] = _TRAINERDESCCONFIG +DESCRIPTOR.message_types_by_name['PipelineConfig'] = _PIPELINECONFIG +DESCRIPTOR.message_types_by_name['TensorParallelConfig'] = _TENSORPARALLELCONFIG +DESCRIPTOR.message_types_by_name['QatConfig'] = _QATCONFIG +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorParameter'] = _TABLEACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['GraphSGDParameter'] = _GRAPHSGDPARAMETER +DESCRIPTOR.message_types_by_name['SGDParameter'] = _SGDPARAMETER +DESCRIPTOR.message_types_by_name['SparseNaiveSGDRuleParameter'] = _SPARSENAIVESGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdagradSGDRuleParameter'] = _SPARSEADAGRADSGDRULEPARAMETER +DESCRIPTOR.message_types_by_name['SparseAdamSGDParameter'] = _SPARSEADAMSGDPARAMETER +DESCRIPTOR.message_types_by_name['CtrAccessorParameter'] = _CTRACCESSORPARAMETER +DESCRIPTOR.message_types_by_name['TableAccessorSaveParameter'] = _TABLEACCESSORSAVEPARAMETER +DESCRIPTOR.message_types_by_name['FsClientParameter'] = _FSCLIENTPARAMETER +DESCRIPTOR.message_types_by_name['DistributedStrategy'] = _DISTRIBUTEDSTRATEGY +DESCRIPTOR.message_types_by_name['DistributedJobInfo'] = _DISTRIBUTEDJOBINFO +DESCRIPTOR.enum_types_by_name['Mode'] = _MODE +DESCRIPTOR.enum_types_by_name['TableType'] = _TABLETYPE + +RecomputeConfig = _reflection.GeneratedProtocolMessageType('RecomputeConfig', (_message.Message,), dict( + DESCRIPTOR = _RECOMPUTECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.RecomputeConfig) + )) +_sym_db.RegisterMessage(RecomputeConfig) + +ShardingConfig = _reflection.GeneratedProtocolMessageType('ShardingConfig', (_message.Message,), dict( + DESCRIPTOR = _SHARDINGCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.ShardingConfig) + )) +_sym_db.RegisterMessage(ShardingConfig) + +HybridConfig = _reflection.GeneratedProtocolMessageType('HybridConfig', (_message.Message,), dict( + DESCRIPTOR = _HYBRIDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.HybridConfig) + )) +_sym_db.RegisterMessage(HybridConfig) + +AMPConfig = _reflection.GeneratedProtocolMessageType('AMPConfig', (_message.Message,), dict( + DESCRIPTOR = _AMPCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AMPConfig) + )) +_sym_db.RegisterMessage(AMPConfig) + +LocalSGDConfig = _reflection.GeneratedProtocolMessageType('LocalSGDConfig', (_message.Message,), dict( + DESCRIPTOR = _LOCALSGDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LocalSGDConfig) + )) +_sym_db.RegisterMessage(LocalSGDConfig) + +AdaptiveLocalSGDConfig = _reflection.GeneratedProtocolMessageType('AdaptiveLocalSGDConfig', (_message.Message,), dict( + DESCRIPTOR = _ADAPTIVELOCALSGDCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AdaptiveLocalSGDConfig) + )) +_sym_db.RegisterMessage(AdaptiveLocalSGDConfig) + +GradientMergeConfig = _reflection.GeneratedProtocolMessageType('GradientMergeConfig', (_message.Message,), dict( + DESCRIPTOR = _GRADIENTMERGECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GradientMergeConfig) + )) +_sym_db.RegisterMessage(GradientMergeConfig) + +DGCConfig = _reflection.GeneratedProtocolMessageType('DGCConfig', (_message.Message,), dict( + DESCRIPTOR = _DGCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DGCConfig) + )) +_sym_db.RegisterMessage(DGCConfig) + +LarsConfig = _reflection.GeneratedProtocolMessageType('LarsConfig', (_message.Message,), dict( + DESCRIPTOR = _LARSCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LarsConfig) + )) +_sym_db.RegisterMessage(LarsConfig) + +LambConfig = _reflection.GeneratedProtocolMessageType('LambConfig', (_message.Message,), dict( + DESCRIPTOR = _LAMBCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.LambConfig) + )) +_sym_db.RegisterMessage(LambConfig) + +BuildStrategy = _reflection.GeneratedProtocolMessageType('BuildStrategy', (_message.Message,), dict( + DESCRIPTOR = _BUILDSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.BuildStrategy) + )) +_sym_db.RegisterMessage(BuildStrategy) + +ExecutionStrategy = _reflection.GeneratedProtocolMessageType('ExecutionStrategy', (_message.Message,), dict( + DESCRIPTOR = _EXECUTIONSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.ExecutionStrategy) + )) +_sym_db.RegisterMessage(ExecutionStrategy) + +GradientScaleConfig = _reflection.GeneratedProtocolMessageType('GradientScaleConfig', (_message.Message,), dict( + DESCRIPTOR = _GRADIENTSCALECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GradientScaleConfig) + )) +_sym_db.RegisterMessage(GradientScaleConfig) + +AsyncConfig = _reflection.GeneratedProtocolMessageType('AsyncConfig', (_message.Message,), dict( + DESCRIPTOR = _ASYNCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.AsyncConfig) + )) +_sym_db.RegisterMessage(AsyncConfig) + +TrainerDescConfig = _reflection.GeneratedProtocolMessageType('TrainerDescConfig', (_message.Message,), dict( + DESCRIPTOR = _TRAINERDESCCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TrainerDescConfig) + )) +_sym_db.RegisterMessage(TrainerDescConfig) + +PipelineConfig = _reflection.GeneratedProtocolMessageType('PipelineConfig', (_message.Message,), dict( + DESCRIPTOR = _PIPELINECONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.PipelineConfig) + )) +_sym_db.RegisterMessage(PipelineConfig) + +TensorParallelConfig = _reflection.GeneratedProtocolMessageType('TensorParallelConfig', (_message.Message,), dict( + DESCRIPTOR = _TENSORPARALLELCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TensorParallelConfig) + )) +_sym_db.RegisterMessage(TensorParallelConfig) + +QatConfig = _reflection.GeneratedProtocolMessageType('QatConfig', (_message.Message,), dict( + DESCRIPTOR = _QATCONFIG, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.QatConfig) + )) +_sym_db.RegisterMessage(QatConfig) + +TableParameter = _reflection.GeneratedProtocolMessageType('TableParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + +TableAccessorParameter = _reflection.GeneratedProtocolMessageType('TableAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableAccessorParameter) + )) +_sym_db.RegisterMessage(TableAccessorParameter) + +GraphSGDParameter = _reflection.GeneratedProtocolMessageType('GraphSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _GRAPHSGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.GraphSGDParameter) + )) +_sym_db.RegisterMessage(GraphSGDParameter) + +SGDParameter = _reflection.GeneratedProtocolMessageType('SGDParameter', (_message.Message,), dict( + DESCRIPTOR = _SGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SGDParameter) + )) +_sym_db.RegisterMessage(SGDParameter) + +SparseNaiveSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseNaiveSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSENAIVESGDRULEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseNaiveSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseNaiveSGDRuleParameter) + +SparseAdagradSGDRuleParameter = _reflection.GeneratedProtocolMessageType('SparseAdagradSGDRuleParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAGRADSGDRULEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseAdagradSGDRuleParameter) + )) +_sym_db.RegisterMessage(SparseAdagradSGDRuleParameter) + +SparseAdamSGDParameter = _reflection.GeneratedProtocolMessageType('SparseAdamSGDParameter', (_message.Message,), dict( + DESCRIPTOR = _SPARSEADAMSGDPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.SparseAdamSGDParameter) + )) +_sym_db.RegisterMessage(SparseAdamSGDParameter) + +CtrAccessorParameter = _reflection.GeneratedProtocolMessageType('CtrAccessorParameter', (_message.Message,), dict( + DESCRIPTOR = _CTRACCESSORPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.CtrAccessorParameter) + )) +_sym_db.RegisterMessage(CtrAccessorParameter) + +TableAccessorSaveParameter = _reflection.GeneratedProtocolMessageType('TableAccessorSaveParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEACCESSORSAVEPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.TableAccessorSaveParameter) + )) +_sym_db.RegisterMessage(TableAccessorSaveParameter) + +FsClientParameter = _reflection.GeneratedProtocolMessageType('FsClientParameter', (_message.Message,), dict( + DESCRIPTOR = _FSCLIENTPARAMETER, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.FsClientParameter) + )) +_sym_db.RegisterMessage(FsClientParameter) + +DistributedStrategy = _reflection.GeneratedProtocolMessageType('DistributedStrategy', (_message.Message,), dict( + DESCRIPTOR = _DISTRIBUTEDSTRATEGY, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DistributedStrategy) + )) +_sym_db.RegisterMessage(DistributedStrategy) + +DistributedJobInfo = _reflection.GeneratedProtocolMessageType('DistributedJobInfo', (_message.Message,), dict( + DESCRIPTOR = _DISTRIBUTEDJOBINFO, + __module__ = 'distributed_strategy_pb2' + # @@protoc_insertion_point(class_scope:paddle.fleet.DistributedJobInfo) + )) +_sym_db.RegisterMessage(DistributedJobInfo) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/framework_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/framework_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..bedb01b926e229bcb605abf0fb2a840337572b67 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/framework_pb2.py @@ -0,0 +1,1557 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: framework.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='framework.proto', + package='paddle.framework.proto', + syntax='proto2', + serialized_pb=_b('\n\x0f\x66ramework.proto\x12\x16paddle.framework.proto\"\x1d\n\x07Version\x12\x12\n\x07version\x18\x01 \x01(\x03:\x01\x30\"\xb4\x04\n\x06OpDesc\x12\x0c\n\x04type\x18\x03 \x02(\t\x12\x32\n\x06inputs\x18\x01 \x03(\x0b\x32\".paddle.framework.proto.OpDesc.Var\x12\x33\n\x07outputs\x18\x02 \x03(\x0b\x32\".paddle.framework.proto.OpDesc.Var\x12\x32\n\x05\x61ttrs\x18\x04 \x03(\x0b\x32#.paddle.framework.proto.OpDesc.Attr\x12\x18\n\tis_target\x18\x05 \x01(\x08:\x05\x66\x61lse\x1a\xb7\x02\n\x04\x41ttr\x12\x0c\n\x04name\x18\x01 \x02(\t\x12.\n\x04type\x18\x02 \x02(\x0e\x32 .paddle.framework.proto.AttrType\x12\t\n\x01i\x18\x03 \x01(\x05\x12\t\n\x01\x66\x18\x04 \x01(\x02\x12\t\n\x01s\x18\x05 \x01(\t\x12\x0c\n\x04ints\x18\x06 \x03(\x05\x12\x0e\n\x06\x66loats\x18\x07 \x03(\x02\x12\x0f\n\x07strings\x18\x08 \x03(\t\x12\t\n\x01\x62\x18\n \x01(\x08\x12\r\n\x05\x62ools\x18\x0b \x03(\x08\x12\x11\n\tblock_idx\x18\x0c \x01(\x05\x12\t\n\x01l\x18\r \x01(\x03\x12\x12\n\nblocks_idx\x18\x0e \x03(\x05\x12\r\n\x05longs\x18\x0f \x03(\x03\x12\x10\n\x08\x66loat64s\x18\x10 \x03(\x01\x12\x10\n\x08var_name\x18\x11 \x01(\t\x12\x11\n\tvars_name\x18\x12 \x03(\t\x12\x0f\n\x07\x66loat64\x18\x13 \x01(\x01\x1a+\n\x03Var\x12\x11\n\tparameter\x18\x01 \x02(\t\x12\x11\n\targuments\x18\x02 \x03(\t\"\xac\x04\n\x07OpProto\x12\x0c\n\x04type\x18\x01 \x02(\t\x12\x33\n\x06inputs\x18\x02 \x03(\x0b\x32#.paddle.framework.proto.OpProto.Var\x12\x34\n\x07outputs\x18\x03 \x03(\x0b\x32#.paddle.framework.proto.OpProto.Var\x12\x33\n\x05\x61ttrs\x18\x04 \x03(\x0b\x32$.paddle.framework.proto.OpProto.Attr\x12\x0f\n\x07\x63omment\x18\x05 \x02(\t\x1a\xa4\x01\n\x03Var\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0f\n\x07\x63omment\x18\x02 \x02(\t\x12\x19\n\nduplicable\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0cintermediate\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0b\x64ispensable\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x14\n\x05\x65xtra\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x14\n\x05quant\x18\x07 \x01(\x08:\x05\x66\x61lse\x1a\xba\x01\n\x04\x41ttr\x12\x0c\n\x04name\x18\x01 \x02(\t\x12.\n\x04type\x18\x02 \x02(\x0e\x32 .paddle.framework.proto.AttrType\x12\x0f\n\x07\x63omment\x18\x03 \x02(\t\x12\x18\n\tgenerated\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x14\n\x05\x65xtra\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x14\n\x05quant\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x1d\n\x0esupport_tensor\x18\x07 \x01(\x08:\x05\x66\x61lse\"\x97\x0c\n\x07VarType\x12\x32\n\x04type\x18\x01 \x02(\x0e\x32$.paddle.framework.proto.VarType.Type\x12\x41\n\rselected_rows\x18\x02 \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12\x41\n\nlod_tensor\x18\x03 \x01(\x0b\x32-.paddle.framework.proto.VarType.LoDTensorDesc\x12H\n\x0ctensor_array\x18\x04 \x01(\x0b\x32\x32.paddle.framework.proto.VarType.LoDTensorArrayDesc\x12:\n\x06reader\x18\x05 \x01(\x0b\x32*.paddle.framework.proto.VarType.ReaderDesc\x12\x34\n\x05tuple\x18\x07 \x01(\x0b\x32%.paddle.framework.proto.VarType.Tuple\x12:\n\x06string\x18\x08 \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12;\n\x07strings\x18\t \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12\x39\n\x05vocab\x18\n \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12>\n\nsparse_coo\x18\x0b \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12>\n\nsparse_csr\x18\x0c \x01(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x1aS\n\nTensorDesc\x12\x37\n\tdata_type\x18\x01 \x02(\x0e\x32$.paddle.framework.proto.VarType.Type\x12\x0c\n\x04\x64ims\x18\x02 \x03(\x03\x1a\x61\n\rLoDTensorDesc\x12:\n\x06tensor\x18\x01 \x02(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12\x14\n\tlod_level\x18\x02 \x01(\x05:\x01\x30\x1a\x66\n\x12LoDTensorArrayDesc\x12:\n\x06tensor\x18\x01 \x02(\x0b\x32*.paddle.framework.proto.VarType.TensorDesc\x12\x14\n\tlod_level\x18\x02 \x01(\x05:\x01\x30\x1aO\n\nReaderDesc\x12\x41\n\nlod_tensor\x18\x01 \x03(\x0b\x32-.paddle.framework.proto.VarType.LoDTensorDesc\x1a\x43\n\x05Tuple\x12:\n\x0c\x65lement_type\x18\x01 \x03(\x0e\x32$.paddle.framework.proto.VarType.Type\"\xab\x03\n\x04Type\x12\x08\n\x04\x42OOL\x10\x00\x12\t\n\x05INT16\x10\x01\x12\t\n\x05INT32\x10\x02\x12\t\n\x05INT64\x10\x03\x12\x08\n\x04\x46P16\x10\x04\x12\x08\n\x04\x46P32\x10\x05\x12\x08\n\x04\x46P64\x10\x06\x12\n\n\x06SIZE_T\x10\x13\x12\t\n\x05UINT8\x10\x14\x12\x08\n\x04INT8\x10\x15\x12\x08\n\x04\x42\x46\x31\x36\x10\x16\x12\r\n\tCOMPLEX64\x10\x17\x12\x0e\n\nCOMPLEX128\x10\x18\x12\x0e\n\nLOD_TENSOR\x10\x07\x12\x11\n\rSELECTED_ROWS\x10\x08\x12\x12\n\x0e\x46\x45\x45\x44_MINIBATCH\x10\t\x12\x0e\n\nFETCH_LIST\x10\n\x12\x0f\n\x0bSTEP_SCOPES\x10\x0b\x12\x12\n\x0eLOD_RANK_TABLE\x10\x0c\x12\x14\n\x10LOD_TENSOR_ARRAY\x10\r\x12\x0e\n\nPLACE_LIST\x10\x0e\x12\n\n\x06READER\x10\x0f\x12\x07\n\x03RAW\x10\x11\x12\t\n\x05TUPLE\x10\x12\x12\n\n\x06STRING\x10\x19\x12\x0b\n\x07STRINGS\x10\x1a\x12\t\n\x05VOCAB\x10\x1b\x12\r\n\tFEED_LIST\x10\x1c\x12\x0b\n\x07PSTRING\x10\x1d\x12\x0e\n\nSPARSE_COO\x10\x1e\x12\x0e\n\nSPARSE_CSR\x10\x1f\"\xdc\x02\n\x07VarDesc\x12\x0c\n\x04name\x18\x01 \x02(\t\x12-\n\x04type\x18\x02 \x02(\x0b\x32\x1f.paddle.framework.proto.VarType\x12\x1a\n\x0bpersistable\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x1e\n\x0fneed_check_feed\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0cis_parameter\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x1c\n\rstop_gradient\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x33\n\x05\x61ttrs\x18\x07 \x03(\x0b\x32$.paddle.framework.proto.VarDesc.Attr\x1ah\n\x04\x41ttr\x12\x0c\n\x04name\x18\x01 \x02(\t\x12.\n\x04type\x18\x02 \x02(\x0e\x32 .paddle.framework.proto.AttrType\x12\t\n\x01i\x18\x03 \x01(\x05\x12\t\n\x01s\x18\x04 \x01(\t\x12\x0c\n\x04ints\x18\x05 \x03(\x05\"\xa7\x01\n\tBlockDesc\x12\x0b\n\x03idx\x18\x01 \x02(\x05\x12\x12\n\nparent_idx\x18\x02 \x02(\x05\x12-\n\x04vars\x18\x03 \x03(\x0b\x32\x1f.paddle.framework.proto.VarDesc\x12+\n\x03ops\x18\x04 \x03(\x0b\x32\x1e.paddle.framework.proto.OpDesc\x12\x1d\n\x11\x66orward_block_idx\x18\x05 \x01(\x05:\x02-1\"\x1c\n\tOpVersion\x12\x0f\n\x07version\x18\x01 \x02(\x05\"\xa9\x01\n\x0cOpVersionMap\x12@\n\x04pair\x18\x01 \x03(\x0b\x32\x32.paddle.framework.proto.OpVersionMap.OpVersionPair\x1aW\n\rOpVersionPair\x12\x0f\n\x07op_name\x18\x01 \x02(\t\x12\x35\n\nop_version\x18\x02 \x02(\x0b\x32!.paddle.framework.proto.OpVersion\"\xbc\x01\n\x0bProgramDesc\x12\x31\n\x06\x62locks\x18\x01 \x03(\x0b\x32!.paddle.framework.proto.BlockDesc\x12\x30\n\x07version\x18\x04 \x01(\x0b\x32\x1f.paddle.framework.proto.Version\x12<\n\x0eop_version_map\x18\x05 \x01(\x0b\x32$.paddle.framework.proto.OpVersionMapJ\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04*\xc2\x01\n\x08\x41ttrType\x12\x07\n\x03INT\x10\x00\x12\t\n\x05\x46LOAT\x10\x01\x12\n\n\x06STRING\x10\x02\x12\x08\n\x04INTS\x10\x03\x12\n\n\x06\x46LOATS\x10\x04\x12\x0b\n\x07STRINGS\x10\x05\x12\x0b\n\x07\x42OOLEAN\x10\x06\x12\x0c\n\x08\x42OOLEANS\x10\x07\x12\t\n\x05\x42LOCK\x10\x08\x12\x08\n\x04LONG\x10\t\x12\n\n\x06\x42LOCKS\x10\n\x12\t\n\x05LONGS\x10\x0b\x12\x0c\n\x08\x46LOAT64S\x10\x0c\x12\x07\n\x03VAR\x10\r\x12\x08\n\x04VARS\x10\x0e\x12\x0b\n\x07\x46LOAT64\x10\x0f') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_ATTRTYPE = _descriptor.EnumDescriptor( + name='AttrType', + full_name='paddle.framework.proto.AttrType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='INT', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FLOAT', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRING', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INTS', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FLOATS', index=4, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRINGS', index=5, number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BOOLEAN', index=6, number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BOOLEANS', index=7, number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BLOCK', index=8, number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LONG', index=9, number=9, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BLOCKS', index=10, number=10, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LONGS', index=11, number=11, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FLOAT64S', index=12, number=12, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='VAR', index=13, number=13, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='VARS', index=14, number=14, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FLOAT64', index=15, number=15, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3677, + serialized_end=3871, +) +_sym_db.RegisterEnumDescriptor(_ATTRTYPE) + +AttrType = enum_type_wrapper.EnumTypeWrapper(_ATTRTYPE) +INT = 0 +FLOAT = 1 +STRING = 2 +INTS = 3 +FLOATS = 4 +STRINGS = 5 +BOOLEAN = 6 +BOOLEANS = 7 +BLOCK = 8 +LONG = 9 +BLOCKS = 10 +LONGS = 11 +FLOAT64S = 12 +VAR = 13 +VARS = 14 +FLOAT64 = 15 + + +_VARTYPE_TYPE = _descriptor.EnumDescriptor( + name='Type', + full_name='paddle.framework.proto.VarType.Type', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='BOOL', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INT16', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INT32', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INT64', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FP16', index=4, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FP32', index=5, number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FP64', index=6, number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SIZE_T', index=7, number=19, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='UINT8', index=8, number=20, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INT8', index=9, number=21, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BF16', index=10, number=22, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='COMPLEX64', index=11, number=23, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='COMPLEX128', index=12, number=24, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LOD_TENSOR', index=13, number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SELECTED_ROWS', index=14, number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FEED_MINIBATCH', index=15, number=9, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FETCH_LIST', index=16, number=10, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STEP_SCOPES', index=17, number=11, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LOD_RANK_TABLE', index=18, number=12, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LOD_TENSOR_ARRAY', index=19, number=13, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PLACE_LIST', index=20, number=14, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='READER', index=21, number=15, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='RAW', index=22, number=17, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TUPLE', index=23, number=18, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRING', index=24, number=25, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRINGS', index=25, number=26, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='VOCAB', index=26, number=27, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FEED_LIST', index=27, number=28, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PSTRING', index=28, number=29, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_COO', index=29, number=30, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_CSR', index=30, number=31, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2333, + serialized_end=2760, +) +_sym_db.RegisterEnumDescriptor(_VARTYPE_TYPE) + + +_VERSION = _descriptor.Descriptor( + name='Version', + full_name='paddle.framework.proto.Version', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='version', full_name='paddle.framework.proto.Version.version', index=0, + number=1, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=43, + serialized_end=72, +) + + +_OPDESC_ATTR = _descriptor.Descriptor( + name='Attr', + full_name='paddle.framework.proto.OpDesc.Attr', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.OpDesc.Attr.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.OpDesc.Attr.type', index=1, + number=2, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='i', full_name='paddle.framework.proto.OpDesc.Attr.i', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='f', full_name='paddle.framework.proto.OpDesc.Attr.f', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='s', full_name='paddle.framework.proto.OpDesc.Attr.s', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ints', full_name='paddle.framework.proto.OpDesc.Attr.ints', index=5, + number=6, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='floats', full_name='paddle.framework.proto.OpDesc.Attr.floats', index=6, + number=7, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='strings', full_name='paddle.framework.proto.OpDesc.Attr.strings', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='b', full_name='paddle.framework.proto.OpDesc.Attr.b', index=8, + number=10, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bools', full_name='paddle.framework.proto.OpDesc.Attr.bools', index=9, + number=11, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='block_idx', full_name='paddle.framework.proto.OpDesc.Attr.block_idx', index=10, + number=12, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='l', full_name='paddle.framework.proto.OpDesc.Attr.l', index=11, + number=13, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='blocks_idx', full_name='paddle.framework.proto.OpDesc.Attr.blocks_idx', index=12, + number=14, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='longs', full_name='paddle.framework.proto.OpDesc.Attr.longs', index=13, + number=15, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='float64s', full_name='paddle.framework.proto.OpDesc.Attr.float64s', index=14, + number=16, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='var_name', full_name='paddle.framework.proto.OpDesc.Attr.var_name', index=15, + number=17, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='vars_name', full_name='paddle.framework.proto.OpDesc.Attr.vars_name', index=16, + number=18, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='float64', full_name='paddle.framework.proto.OpDesc.Attr.float64', index=17, + number=19, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=283, + serialized_end=594, +) + +_OPDESC_VAR = _descriptor.Descriptor( + name='Var', + full_name='paddle.framework.proto.OpDesc.Var', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parameter', full_name='paddle.framework.proto.OpDesc.Var.parameter', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='arguments', full_name='paddle.framework.proto.OpDesc.Var.arguments', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=596, + serialized_end=639, +) + +_OPDESC = _descriptor.Descriptor( + name='OpDesc', + full_name='paddle.framework.proto.OpDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.OpDesc.type', index=0, + number=3, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='inputs', full_name='paddle.framework.proto.OpDesc.inputs', index=1, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='outputs', full_name='paddle.framework.proto.OpDesc.outputs', index=2, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attrs', full_name='paddle.framework.proto.OpDesc.attrs', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_target', full_name='paddle.framework.proto.OpDesc.is_target', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_OPDESC_ATTR, _OPDESC_VAR, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=75, + serialized_end=639, +) + + +_OPPROTO_VAR = _descriptor.Descriptor( + name='Var', + full_name='paddle.framework.proto.OpProto.Var', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.OpProto.Var.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='comment', full_name='paddle.framework.proto.OpProto.Var.comment', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='duplicable', full_name='paddle.framework.proto.OpProto.Var.duplicable', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='intermediate', full_name='paddle.framework.proto.OpProto.Var.intermediate', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dispensable', full_name='paddle.framework.proto.OpProto.Var.dispensable', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extra', full_name='paddle.framework.proto.OpProto.Var.extra', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='quant', full_name='paddle.framework.proto.OpProto.Var.quant', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=845, + serialized_end=1009, +) + +_OPPROTO_ATTR = _descriptor.Descriptor( + name='Attr', + full_name='paddle.framework.proto.OpProto.Attr', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.OpProto.Attr.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.OpProto.Attr.type', index=1, + number=2, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='comment', full_name='paddle.framework.proto.OpProto.Attr.comment', index=2, + number=3, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='generated', full_name='paddle.framework.proto.OpProto.Attr.generated', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extra', full_name='paddle.framework.proto.OpProto.Attr.extra', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='quant', full_name='paddle.framework.proto.OpProto.Attr.quant', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='support_tensor', full_name='paddle.framework.proto.OpProto.Attr.support_tensor', index=6, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1012, + serialized_end=1198, +) + +_OPPROTO = _descriptor.Descriptor( + name='OpProto', + full_name='paddle.framework.proto.OpProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.OpProto.type', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='inputs', full_name='paddle.framework.proto.OpProto.inputs', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='outputs', full_name='paddle.framework.proto.OpProto.outputs', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attrs', full_name='paddle.framework.proto.OpProto.attrs', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='comment', full_name='paddle.framework.proto.OpProto.comment', index=4, + number=5, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_OPPROTO_VAR, _OPPROTO_ATTR, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=642, + serialized_end=1198, +) + + +_VARTYPE_TENSORDESC = _descriptor.Descriptor( + name='TensorDesc', + full_name='paddle.framework.proto.VarType.TensorDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='data_type', full_name='paddle.framework.proto.VarType.TensorDesc.data_type', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dims', full_name='paddle.framework.proto.VarType.TensorDesc.dims', index=1, + number=2, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1894, + serialized_end=1977, +) + +_VARTYPE_LODTENSORDESC = _descriptor.Descriptor( + name='LoDTensorDesc', + full_name='paddle.framework.proto.VarType.LoDTensorDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='tensor', full_name='paddle.framework.proto.VarType.LoDTensorDesc.tensor', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lod_level', full_name='paddle.framework.proto.VarType.LoDTensorDesc.lod_level', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1979, + serialized_end=2076, +) + +_VARTYPE_LODTENSORARRAYDESC = _descriptor.Descriptor( + name='LoDTensorArrayDesc', + full_name='paddle.framework.proto.VarType.LoDTensorArrayDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='tensor', full_name='paddle.framework.proto.VarType.LoDTensorArrayDesc.tensor', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lod_level', full_name='paddle.framework.proto.VarType.LoDTensorArrayDesc.lod_level', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2078, + serialized_end=2180, +) + +_VARTYPE_READERDESC = _descriptor.Descriptor( + name='ReaderDesc', + full_name='paddle.framework.proto.VarType.ReaderDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='lod_tensor', full_name='paddle.framework.proto.VarType.ReaderDesc.lod_tensor', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2182, + serialized_end=2261, +) + +_VARTYPE_TUPLE = _descriptor.Descriptor( + name='Tuple', + full_name='paddle.framework.proto.VarType.Tuple', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='element_type', full_name='paddle.framework.proto.VarType.Tuple.element_type', index=0, + number=1, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2263, + serialized_end=2330, +) + +_VARTYPE = _descriptor.Descriptor( + name='VarType', + full_name='paddle.framework.proto.VarType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.VarType.type', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='selected_rows', full_name='paddle.framework.proto.VarType.selected_rows', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lod_tensor', full_name='paddle.framework.proto.VarType.lod_tensor', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tensor_array', full_name='paddle.framework.proto.VarType.tensor_array', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='reader', full_name='paddle.framework.proto.VarType.reader', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='tuple', full_name='paddle.framework.proto.VarType.tuple', index=5, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='string', full_name='paddle.framework.proto.VarType.string', index=6, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='strings', full_name='paddle.framework.proto.VarType.strings', index=7, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='vocab', full_name='paddle.framework.proto.VarType.vocab', index=8, + number=10, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_coo', full_name='paddle.framework.proto.VarType.sparse_coo', index=9, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_csr', full_name='paddle.framework.proto.VarType.sparse_csr', index=10, + number=12, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_VARTYPE_TENSORDESC, _VARTYPE_LODTENSORDESC, _VARTYPE_LODTENSORARRAYDESC, _VARTYPE_READERDESC, _VARTYPE_TUPLE, ], + enum_types=[ + _VARTYPE_TYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1201, + serialized_end=2760, +) + + +_VARDESC_ATTR = _descriptor.Descriptor( + name='Attr', + full_name='paddle.framework.proto.VarDesc.Attr', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.VarDesc.Attr.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.VarDesc.Attr.type', index=1, + number=2, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='i', full_name='paddle.framework.proto.VarDesc.Attr.i', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='s', full_name='paddle.framework.proto.VarDesc.Attr.s', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ints', full_name='paddle.framework.proto.VarDesc.Attr.ints', index=4, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3007, + serialized_end=3111, +) + +_VARDESC = _descriptor.Descriptor( + name='VarDesc', + full_name='paddle.framework.proto.VarDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.VarDesc.name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.VarDesc.type', index=1, + number=2, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='persistable', full_name='paddle.framework.proto.VarDesc.persistable', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='need_check_feed', full_name='paddle.framework.proto.VarDesc.need_check_feed', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_parameter', full_name='paddle.framework.proto.VarDesc.is_parameter', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stop_gradient', full_name='paddle.framework.proto.VarDesc.stop_gradient', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attrs', full_name='paddle.framework.proto.VarDesc.attrs', index=6, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_VARDESC_ATTR, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2763, + serialized_end=3111, +) + + +_BLOCKDESC = _descriptor.Descriptor( + name='BlockDesc', + full_name='paddle.framework.proto.BlockDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='idx', full_name='paddle.framework.proto.BlockDesc.idx', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='parent_idx', full_name='paddle.framework.proto.BlockDesc.parent_idx', index=1, + number=2, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='vars', full_name='paddle.framework.proto.BlockDesc.vars', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ops', full_name='paddle.framework.proto.BlockDesc.ops', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='forward_block_idx', full_name='paddle.framework.proto.BlockDesc.forward_block_idx', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3114, + serialized_end=3281, +) + + +_OPVERSION = _descriptor.Descriptor( + name='OpVersion', + full_name='paddle.framework.proto.OpVersion', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='version', full_name='paddle.framework.proto.OpVersion.version', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3283, + serialized_end=3311, +) + + +_OPVERSIONMAP_OPVERSIONPAIR = _descriptor.Descriptor( + name='OpVersionPair', + full_name='paddle.framework.proto.OpVersionMap.OpVersionPair', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='op_name', full_name='paddle.framework.proto.OpVersionMap.OpVersionPair.op_name', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='op_version', full_name='paddle.framework.proto.OpVersionMap.OpVersionPair.op_version', index=1, + number=2, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3396, + serialized_end=3483, +) + +_OPVERSIONMAP = _descriptor.Descriptor( + name='OpVersionMap', + full_name='paddle.framework.proto.OpVersionMap', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='pair', full_name='paddle.framework.proto.OpVersionMap.pair', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_OPVERSIONMAP_OPVERSIONPAIR, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3314, + serialized_end=3483, +) + + +_PROGRAMDESC = _descriptor.Descriptor( + name='ProgramDesc', + full_name='paddle.framework.proto.ProgramDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='blocks', full_name='paddle.framework.proto.ProgramDesc.blocks', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='version', full_name='paddle.framework.proto.ProgramDesc.version', index=1, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='op_version_map', full_name='paddle.framework.proto.ProgramDesc.op_version_map', index=2, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3486, + serialized_end=3674, +) + +_OPDESC_ATTR.fields_by_name['type'].enum_type = _ATTRTYPE +_OPDESC_ATTR.containing_type = _OPDESC +_OPDESC_VAR.containing_type = _OPDESC +_OPDESC.fields_by_name['inputs'].message_type = _OPDESC_VAR +_OPDESC.fields_by_name['outputs'].message_type = _OPDESC_VAR +_OPDESC.fields_by_name['attrs'].message_type = _OPDESC_ATTR +_OPPROTO_VAR.containing_type = _OPPROTO +_OPPROTO_ATTR.fields_by_name['type'].enum_type = _ATTRTYPE +_OPPROTO_ATTR.containing_type = _OPPROTO +_OPPROTO.fields_by_name['inputs'].message_type = _OPPROTO_VAR +_OPPROTO.fields_by_name['outputs'].message_type = _OPPROTO_VAR +_OPPROTO.fields_by_name['attrs'].message_type = _OPPROTO_ATTR +_VARTYPE_TENSORDESC.fields_by_name['data_type'].enum_type = _VARTYPE_TYPE +_VARTYPE_TENSORDESC.containing_type = _VARTYPE +_VARTYPE_LODTENSORDESC.fields_by_name['tensor'].message_type = _VARTYPE_TENSORDESC +_VARTYPE_LODTENSORDESC.containing_type = _VARTYPE +_VARTYPE_LODTENSORARRAYDESC.fields_by_name['tensor'].message_type = _VARTYPE_TENSORDESC +_VARTYPE_LODTENSORARRAYDESC.containing_type = _VARTYPE +_VARTYPE_READERDESC.fields_by_name['lod_tensor'].message_type = _VARTYPE_LODTENSORDESC +_VARTYPE_READERDESC.containing_type = _VARTYPE +_VARTYPE_TUPLE.fields_by_name['element_type'].enum_type = _VARTYPE_TYPE +_VARTYPE_TUPLE.containing_type = _VARTYPE +_VARTYPE.fields_by_name['type'].enum_type = _VARTYPE_TYPE +_VARTYPE.fields_by_name['selected_rows'].message_type = _VARTYPE_TENSORDESC +_VARTYPE.fields_by_name['lod_tensor'].message_type = _VARTYPE_LODTENSORDESC +_VARTYPE.fields_by_name['tensor_array'].message_type = _VARTYPE_LODTENSORARRAYDESC +_VARTYPE.fields_by_name['reader'].message_type = _VARTYPE_READERDESC +_VARTYPE.fields_by_name['tuple'].message_type = _VARTYPE_TUPLE +_VARTYPE.fields_by_name['string'].message_type = _VARTYPE_TENSORDESC +_VARTYPE.fields_by_name['strings'].message_type = _VARTYPE_TENSORDESC +_VARTYPE.fields_by_name['vocab'].message_type = _VARTYPE_TENSORDESC +_VARTYPE.fields_by_name['sparse_coo'].message_type = _VARTYPE_TENSORDESC +_VARTYPE.fields_by_name['sparse_csr'].message_type = _VARTYPE_TENSORDESC +_VARTYPE_TYPE.containing_type = _VARTYPE +_VARDESC_ATTR.fields_by_name['type'].enum_type = _ATTRTYPE +_VARDESC_ATTR.containing_type = _VARDESC +_VARDESC.fields_by_name['type'].message_type = _VARTYPE +_VARDESC.fields_by_name['attrs'].message_type = _VARDESC_ATTR +_BLOCKDESC.fields_by_name['vars'].message_type = _VARDESC +_BLOCKDESC.fields_by_name['ops'].message_type = _OPDESC +_OPVERSIONMAP_OPVERSIONPAIR.fields_by_name['op_version'].message_type = _OPVERSION +_OPVERSIONMAP_OPVERSIONPAIR.containing_type = _OPVERSIONMAP +_OPVERSIONMAP.fields_by_name['pair'].message_type = _OPVERSIONMAP_OPVERSIONPAIR +_PROGRAMDESC.fields_by_name['blocks'].message_type = _BLOCKDESC +_PROGRAMDESC.fields_by_name['version'].message_type = _VERSION +_PROGRAMDESC.fields_by_name['op_version_map'].message_type = _OPVERSIONMAP +DESCRIPTOR.message_types_by_name['Version'] = _VERSION +DESCRIPTOR.message_types_by_name['OpDesc'] = _OPDESC +DESCRIPTOR.message_types_by_name['OpProto'] = _OPPROTO +DESCRIPTOR.message_types_by_name['VarType'] = _VARTYPE +DESCRIPTOR.message_types_by_name['VarDesc'] = _VARDESC +DESCRIPTOR.message_types_by_name['BlockDesc'] = _BLOCKDESC +DESCRIPTOR.message_types_by_name['OpVersion'] = _OPVERSION +DESCRIPTOR.message_types_by_name['OpVersionMap'] = _OPVERSIONMAP +DESCRIPTOR.message_types_by_name['ProgramDesc'] = _PROGRAMDESC +DESCRIPTOR.enum_types_by_name['AttrType'] = _ATTRTYPE + +Version = _reflection.GeneratedProtocolMessageType('Version', (_message.Message,), dict( + DESCRIPTOR = _VERSION, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.Version) + )) +_sym_db.RegisterMessage(Version) + +OpDesc = _reflection.GeneratedProtocolMessageType('OpDesc', (_message.Message,), dict( + + Attr = _reflection.GeneratedProtocolMessageType('Attr', (_message.Message,), dict( + DESCRIPTOR = _OPDESC_ATTR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpDesc.Attr) + )) + , + + Var = _reflection.GeneratedProtocolMessageType('Var', (_message.Message,), dict( + DESCRIPTOR = _OPDESC_VAR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpDesc.Var) + )) + , + DESCRIPTOR = _OPDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpDesc) + )) +_sym_db.RegisterMessage(OpDesc) +_sym_db.RegisterMessage(OpDesc.Attr) +_sym_db.RegisterMessage(OpDesc.Var) + +OpProto = _reflection.GeneratedProtocolMessageType('OpProto', (_message.Message,), dict( + + Var = _reflection.GeneratedProtocolMessageType('Var', (_message.Message,), dict( + DESCRIPTOR = _OPPROTO_VAR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpProto.Var) + )) + , + + Attr = _reflection.GeneratedProtocolMessageType('Attr', (_message.Message,), dict( + DESCRIPTOR = _OPPROTO_ATTR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpProto.Attr) + )) + , + DESCRIPTOR = _OPPROTO, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpProto) + )) +_sym_db.RegisterMessage(OpProto) +_sym_db.RegisterMessage(OpProto.Var) +_sym_db.RegisterMessage(OpProto.Attr) + +VarType = _reflection.GeneratedProtocolMessageType('VarType', (_message.Message,), dict( + + TensorDesc = _reflection.GeneratedProtocolMessageType('TensorDesc', (_message.Message,), dict( + DESCRIPTOR = _VARTYPE_TENSORDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType.TensorDesc) + )) + , + + LoDTensorDesc = _reflection.GeneratedProtocolMessageType('LoDTensorDesc', (_message.Message,), dict( + DESCRIPTOR = _VARTYPE_LODTENSORDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType.LoDTensorDesc) + )) + , + + LoDTensorArrayDesc = _reflection.GeneratedProtocolMessageType('LoDTensorArrayDesc', (_message.Message,), dict( + DESCRIPTOR = _VARTYPE_LODTENSORARRAYDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType.LoDTensorArrayDesc) + )) + , + + ReaderDesc = _reflection.GeneratedProtocolMessageType('ReaderDesc', (_message.Message,), dict( + DESCRIPTOR = _VARTYPE_READERDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType.ReaderDesc) + )) + , + + Tuple = _reflection.GeneratedProtocolMessageType('Tuple', (_message.Message,), dict( + DESCRIPTOR = _VARTYPE_TUPLE, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType.Tuple) + )) + , + DESCRIPTOR = _VARTYPE, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarType) + )) +_sym_db.RegisterMessage(VarType) +_sym_db.RegisterMessage(VarType.TensorDesc) +_sym_db.RegisterMessage(VarType.LoDTensorDesc) +_sym_db.RegisterMessage(VarType.LoDTensorArrayDesc) +_sym_db.RegisterMessage(VarType.ReaderDesc) +_sym_db.RegisterMessage(VarType.Tuple) + +VarDesc = _reflection.GeneratedProtocolMessageType('VarDesc', (_message.Message,), dict( + + Attr = _reflection.GeneratedProtocolMessageType('Attr', (_message.Message,), dict( + DESCRIPTOR = _VARDESC_ATTR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarDesc.Attr) + )) + , + DESCRIPTOR = _VARDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.VarDesc) + )) +_sym_db.RegisterMessage(VarDesc) +_sym_db.RegisterMessage(VarDesc.Attr) + +BlockDesc = _reflection.GeneratedProtocolMessageType('BlockDesc', (_message.Message,), dict( + DESCRIPTOR = _BLOCKDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.BlockDesc) + )) +_sym_db.RegisterMessage(BlockDesc) + +OpVersion = _reflection.GeneratedProtocolMessageType('OpVersion', (_message.Message,), dict( + DESCRIPTOR = _OPVERSION, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpVersion) + )) +_sym_db.RegisterMessage(OpVersion) + +OpVersionMap = _reflection.GeneratedProtocolMessageType('OpVersionMap', (_message.Message,), dict( + + OpVersionPair = _reflection.GeneratedProtocolMessageType('OpVersionPair', (_message.Message,), dict( + DESCRIPTOR = _OPVERSIONMAP_OPVERSIONPAIR, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpVersionMap.OpVersionPair) + )) + , + DESCRIPTOR = _OPVERSIONMAP, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.OpVersionMap) + )) +_sym_db.RegisterMessage(OpVersionMap) +_sym_db.RegisterMessage(OpVersionMap.OpVersionPair) + +ProgramDesc = _reflection.GeneratedProtocolMessageType('ProgramDesc', (_message.Message,), dict( + DESCRIPTOR = _PROGRAMDESC, + __module__ = 'framework_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.ProgramDesc) + )) +_sym_db.RegisterMessage(ProgramDesc) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/pass_desc_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/pass_desc_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..36810ba0d60860c2fe1b168a2b6673fc1192c30f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/pass_desc_pb2.py @@ -0,0 +1,584 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: pass_desc.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +import framework_pb2 as framework__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='pass_desc.proto', + package='paddle.framework.proto', + syntax='proto2', + serialized_pb=_b('\n\x0fpass_desc.proto\x12\x16paddle.framework.proto\x1a\x0f\x66ramework.proto\"\xd3\x0c\n\x08PassDesc\x12/\n\x07pattern\x18\x01 \x03(\x0b\x32\x1e.paddle.framework.proto.OpDesc\x12/\n\x07replace\x18\x02 \x03(\x0b\x32\x1e.paddle.framework.proto.OpDesc\x12\x39\n\x08var_maps\x18\x03 \x03(\x0b\x32\'.paddle.framework.proto.PassDesc.VarMap\x12?\n\rvar_attr_maps\x18\x04 \x03(\x0b\x32(.paddle.framework.proto.PassDesc.AttrMap\x12>\n\x0cop_attr_maps\x18\x05 \x03(\x0b\x32(.paddle.framework.proto.PassDesc.AttrMap\x12K\n\x13var_attr_conditions\x18\x06 \x03(\x0b\x32..paddle.framework.proto.PassDesc.AttrCondition\x12J\n\x12op_attr_conditions\x18\x07 \x03(\x0b\x32..paddle.framework.proto.PassDesc.AttrCondition\x1a\xe1\x01\n\x04\x41ttr\x12\x37\n\x04role\x18\x01 \x02(\x0e\x32).paddle.framework.proto.PassDesc.RoleType\x12\x10\n\x08var_name\x18\x02 \x01(\t\x12\x10\n\x08op_index\x18\x03 \x01(\x05\x12\x0c\n\x04name\x18\x04 \x02(\t\x12\x14\n\x0c\x65lement_name\x18\x05 \x01(\t\x12\x15\n\relement_index\x18\x06 \x01(\x05\x12\x41\n\toperation\x18\x07 \x01(\x0e\x32..paddle.framework.proto.PassDesc.OperationType\x1a\xb2\x01\n\tOperation\x12<\n\x04type\x18\x01 \x02(\x0e\x32..paddle.framework.proto.PassDesc.OperationType\x12\x33\n\x04\x61ttr\x18\x02 \x01(\x0b\x32%.paddle.framework.proto.PassDesc.Attr\x12\x32\n\x05value\x18\x03 \x01(\x0b\x32#.paddle.framework.proto.OpDesc.Attr\x1a\x32\n\x06VarMap\x12\x13\n\x0bpattern_var\x18\x01 \x02(\t\x12\x13\n\x0breplace_var\x18\x02 \x02(\t\x1a\xc2\x01\n\x07\x41ttrMap\x12;\n\x0cpattern_attr\x18\x01 \x02(\x0b\x32%.paddle.framework.proto.PassDesc.Attr\x12;\n\x0creplace_attr\x18\x02 \x02(\x0b\x32%.paddle.framework.proto.PassDesc.Attr\x12=\n\toperation\x18\x03 \x01(\x0b\x32*.paddle.framework.proto.PassDesc.Operation\x1a\xbe\x02\n\rAttrCondition\x12\x33\n\x04\x61ttr\x18\x01 \x02(\x0b\x32%.paddle.framework.proto.PassDesc.Attr\x12<\n\x04type\x18\x02 \x02(\x0e\x32..paddle.framework.proto.PassDesc.ConditionType\x12=\n\x0e\x63ondition_attr\x18\x03 \x01(\x0b\x32%.paddle.framework.proto.PassDesc.Attr\x12<\n\x0f\x63ondition_value\x18\x04 \x01(\x0b\x32#.paddle.framework.proto.OpDesc.Attr\x12=\n\toperation\x18\x05 \x01(\x0b\x32*.paddle.framework.proto.PassDesc.Operation\"(\n\x08RoleType\x12\r\n\tkVariable\x10\x00\x12\r\n\tkOperator\x10\x01\"L\n\rOperationType\x12\x08\n\x04kAdd\x10\x00\x12\x08\n\x04kSub\x10\x01\x12\x08\n\x04kMul\x10\x02\x12\x08\n\x04kDiv\x10\x03\x12\t\n\x05kSize\x10\x04\x12\x08\n\x04kMod\x10\x05\"E\n\rConditionType\x12\x07\n\x03kEQ\x10\x00\x12\x07\n\x03kNE\x10\x01\x12\x07\n\x03kGT\x10\x02\x12\x07\n\x03kGE\x10\x03\x12\x07\n\x03kLT\x10\x04\x12\x07\n\x03kLE\x10\x05\"X\n\rMultiPassDesc\x12\x11\n\tpass_type\x18\x01 \x01(\t\x12\x34\n\npass_descs\x18\x02 \x03(\x0b\x32 .paddle.framework.proto.PassDesc') + , + dependencies=[framework__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_PASSDESC_ROLETYPE = _descriptor.EnumDescriptor( + name='RoleType', + full_name='paddle.framework.proto.PassDesc.RoleType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='kVariable', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kOperator', index=1, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1491, + serialized_end=1531, +) +_sym_db.RegisterEnumDescriptor(_PASSDESC_ROLETYPE) + +_PASSDESC_OPERATIONTYPE = _descriptor.EnumDescriptor( + name='OperationType', + full_name='paddle.framework.proto.PassDesc.OperationType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='kAdd', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kSub', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kMul', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kDiv', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kSize', index=4, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kMod', index=5, number=5, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1533, + serialized_end=1609, +) +_sym_db.RegisterEnumDescriptor(_PASSDESC_OPERATIONTYPE) + +_PASSDESC_CONDITIONTYPE = _descriptor.EnumDescriptor( + name='ConditionType', + full_name='paddle.framework.proto.PassDesc.ConditionType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='kEQ', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kNE', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kGT', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kGE', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kLT', index=4, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='kLE', index=5, number=5, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1611, + serialized_end=1680, +) +_sym_db.RegisterEnumDescriptor(_PASSDESC_CONDITIONTYPE) + + +_PASSDESC_ATTR = _descriptor.Descriptor( + name='Attr', + full_name='paddle.framework.proto.PassDesc.Attr', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='role', full_name='paddle.framework.proto.PassDesc.Attr.role', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='var_name', full_name='paddle.framework.proto.PassDesc.Attr.var_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='op_index', full_name='paddle.framework.proto.PassDesc.Attr.op_index', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='name', full_name='paddle.framework.proto.PassDesc.Attr.name', index=3, + number=4, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='element_name', full_name='paddle.framework.proto.PassDesc.Attr.element_name', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='element_index', full_name='paddle.framework.proto.PassDesc.Attr.element_index', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='operation', full_name='paddle.framework.proto.PassDesc.Attr.operation', index=6, + number=7, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=513, + serialized_end=738, +) + +_PASSDESC_OPERATION = _descriptor.Descriptor( + name='Operation', + full_name='paddle.framework.proto.PassDesc.Operation', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.PassDesc.Operation.type', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='attr', full_name='paddle.framework.proto.PassDesc.Operation.attr', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='paddle.framework.proto.PassDesc.Operation.value', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=741, + serialized_end=919, +) + +_PASSDESC_VARMAP = _descriptor.Descriptor( + name='VarMap', + full_name='paddle.framework.proto.PassDesc.VarMap', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='pattern_var', full_name='paddle.framework.proto.PassDesc.VarMap.pattern_var', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='replace_var', full_name='paddle.framework.proto.PassDesc.VarMap.replace_var', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=921, + serialized_end=971, +) + +_PASSDESC_ATTRMAP = _descriptor.Descriptor( + name='AttrMap', + full_name='paddle.framework.proto.PassDesc.AttrMap', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='pattern_attr', full_name='paddle.framework.proto.PassDesc.AttrMap.pattern_attr', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='replace_attr', full_name='paddle.framework.proto.PassDesc.AttrMap.replace_attr', index=1, + number=2, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='operation', full_name='paddle.framework.proto.PassDesc.AttrMap.operation', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=974, + serialized_end=1168, +) + +_PASSDESC_ATTRCONDITION = _descriptor.Descriptor( + name='AttrCondition', + full_name='paddle.framework.proto.PassDesc.AttrCondition', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='attr', full_name='paddle.framework.proto.PassDesc.AttrCondition.attr', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='paddle.framework.proto.PassDesc.AttrCondition.type', index=1, + number=2, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='condition_attr', full_name='paddle.framework.proto.PassDesc.AttrCondition.condition_attr', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='condition_value', full_name='paddle.framework.proto.PassDesc.AttrCondition.condition_value', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='operation', full_name='paddle.framework.proto.PassDesc.AttrCondition.operation', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1171, + serialized_end=1489, +) + +_PASSDESC = _descriptor.Descriptor( + name='PassDesc', + full_name='paddle.framework.proto.PassDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='pattern', full_name='paddle.framework.proto.PassDesc.pattern', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='replace', full_name='paddle.framework.proto.PassDesc.replace', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='var_maps', full_name='paddle.framework.proto.PassDesc.var_maps', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='var_attr_maps', full_name='paddle.framework.proto.PassDesc.var_attr_maps', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='op_attr_maps', full_name='paddle.framework.proto.PassDesc.op_attr_maps', index=4, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='var_attr_conditions', full_name='paddle.framework.proto.PassDesc.var_attr_conditions', index=5, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='op_attr_conditions', full_name='paddle.framework.proto.PassDesc.op_attr_conditions', index=6, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_PASSDESC_ATTR, _PASSDESC_OPERATION, _PASSDESC_VARMAP, _PASSDESC_ATTRMAP, _PASSDESC_ATTRCONDITION, ], + enum_types=[ + _PASSDESC_ROLETYPE, + _PASSDESC_OPERATIONTYPE, + _PASSDESC_CONDITIONTYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=61, + serialized_end=1680, +) + + +_MULTIPASSDESC = _descriptor.Descriptor( + name='MultiPassDesc', + full_name='paddle.framework.proto.MultiPassDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='pass_type', full_name='paddle.framework.proto.MultiPassDesc.pass_type', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pass_descs', full_name='paddle.framework.proto.MultiPassDesc.pass_descs', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1682, + serialized_end=1770, +) + +_PASSDESC_ATTR.fields_by_name['role'].enum_type = _PASSDESC_ROLETYPE +_PASSDESC_ATTR.fields_by_name['operation'].enum_type = _PASSDESC_OPERATIONTYPE +_PASSDESC_ATTR.containing_type = _PASSDESC +_PASSDESC_OPERATION.fields_by_name['type'].enum_type = _PASSDESC_OPERATIONTYPE +_PASSDESC_OPERATION.fields_by_name['attr'].message_type = _PASSDESC_ATTR +_PASSDESC_OPERATION.fields_by_name['value'].message_type = framework__pb2._OPDESC_ATTR +_PASSDESC_OPERATION.containing_type = _PASSDESC +_PASSDESC_VARMAP.containing_type = _PASSDESC +_PASSDESC_ATTRMAP.fields_by_name['pattern_attr'].message_type = _PASSDESC_ATTR +_PASSDESC_ATTRMAP.fields_by_name['replace_attr'].message_type = _PASSDESC_ATTR +_PASSDESC_ATTRMAP.fields_by_name['operation'].message_type = _PASSDESC_OPERATION +_PASSDESC_ATTRMAP.containing_type = _PASSDESC +_PASSDESC_ATTRCONDITION.fields_by_name['attr'].message_type = _PASSDESC_ATTR +_PASSDESC_ATTRCONDITION.fields_by_name['type'].enum_type = _PASSDESC_CONDITIONTYPE +_PASSDESC_ATTRCONDITION.fields_by_name['condition_attr'].message_type = _PASSDESC_ATTR +_PASSDESC_ATTRCONDITION.fields_by_name['condition_value'].message_type = framework__pb2._OPDESC_ATTR +_PASSDESC_ATTRCONDITION.fields_by_name['operation'].message_type = _PASSDESC_OPERATION +_PASSDESC_ATTRCONDITION.containing_type = _PASSDESC +_PASSDESC.fields_by_name['pattern'].message_type = framework__pb2._OPDESC +_PASSDESC.fields_by_name['replace'].message_type = framework__pb2._OPDESC +_PASSDESC.fields_by_name['var_maps'].message_type = _PASSDESC_VARMAP +_PASSDESC.fields_by_name['var_attr_maps'].message_type = _PASSDESC_ATTRMAP +_PASSDESC.fields_by_name['op_attr_maps'].message_type = _PASSDESC_ATTRMAP +_PASSDESC.fields_by_name['var_attr_conditions'].message_type = _PASSDESC_ATTRCONDITION +_PASSDESC.fields_by_name['op_attr_conditions'].message_type = _PASSDESC_ATTRCONDITION +_PASSDESC_ROLETYPE.containing_type = _PASSDESC +_PASSDESC_OPERATIONTYPE.containing_type = _PASSDESC +_PASSDESC_CONDITIONTYPE.containing_type = _PASSDESC +_MULTIPASSDESC.fields_by_name['pass_descs'].message_type = _PASSDESC +DESCRIPTOR.message_types_by_name['PassDesc'] = _PASSDESC +DESCRIPTOR.message_types_by_name['MultiPassDesc'] = _MULTIPASSDESC + +PassDesc = _reflection.GeneratedProtocolMessageType('PassDesc', (_message.Message,), dict( + + Attr = _reflection.GeneratedProtocolMessageType('Attr', (_message.Message,), dict( + DESCRIPTOR = _PASSDESC_ATTR, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc.Attr) + )) + , + + Operation = _reflection.GeneratedProtocolMessageType('Operation', (_message.Message,), dict( + DESCRIPTOR = _PASSDESC_OPERATION, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc.Operation) + )) + , + + VarMap = _reflection.GeneratedProtocolMessageType('VarMap', (_message.Message,), dict( + DESCRIPTOR = _PASSDESC_VARMAP, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc.VarMap) + )) + , + + AttrMap = _reflection.GeneratedProtocolMessageType('AttrMap', (_message.Message,), dict( + DESCRIPTOR = _PASSDESC_ATTRMAP, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc.AttrMap) + )) + , + + AttrCondition = _reflection.GeneratedProtocolMessageType('AttrCondition', (_message.Message,), dict( + DESCRIPTOR = _PASSDESC_ATTRCONDITION, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc.AttrCondition) + )) + , + DESCRIPTOR = _PASSDESC, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.PassDesc) + )) +_sym_db.RegisterMessage(PassDesc) +_sym_db.RegisterMessage(PassDesc.Attr) +_sym_db.RegisterMessage(PassDesc.Operation) +_sym_db.RegisterMessage(PassDesc.VarMap) +_sym_db.RegisterMessage(PassDesc.AttrMap) +_sym_db.RegisterMessage(PassDesc.AttrCondition) + +MultiPassDesc = _reflection.GeneratedProtocolMessageType('MultiPassDesc', (_message.Message,), dict( + DESCRIPTOR = _MULTIPASSDESC, + __module__ = 'pass_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.proto.MultiPassDesc) + )) +_sym_db.RegisterMessage(MultiPassDesc) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/profiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/profiler/profiler_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/profiler/profiler_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d27f28543f4040ef4a6b14c633f07044c1dd4548 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/profiler/profiler_pb2.py @@ -0,0 +1,374 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: profiler.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='profiler.proto', + package='paddle.platform.proto', + syntax='proto2', + serialized_pb=_b('\n\x0eprofiler.proto\x12\x15paddle.platform.proto\"\x18\n\x07MemCopy\x12\r\n\x05\x62ytes\x18\x01 \x01(\x04\"\x91\x02\n\x05\x45vent\x12\x34\n\x04type\x18\x08 \x01(\x0e\x32&.paddle.platform.proto.Event.EventType\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x08start_ns\x18\x02 \x01(\x04\x12\x0e\n\x06\x65nd_ns\x18\x03 \x01(\x04\x12\x11\n\tdevice_id\x18\x05 \x01(\x03\x12\x15\n\rsub_device_id\x18\x06 \x01(\x03\x12/\n\x07memcopy\x18\x07 \x01(\x0b\x32\x1e.paddle.platform.proto.MemCopy\x12\x13\n\x0b\x64\x65tail_info\x18\t \x01(\t\"2\n\tEventType\x12\x07\n\x03\x43PU\x10\x00\x12\r\n\tGPUKernel\x10\x01\x12\r\n\tNPUKernel\x10\x02\"\x91\x02\n\x08MemEvent\x12\x10\n\x08start_ns\x18\x01 \x01(\x04\x12\x0e\n\x06\x65nd_ns\x18\x02 \x01(\x04\x12\r\n\x05\x62ytes\x18\x03 \x01(\x04\x12\x34\n\x05place\x18\x04 \x01(\x0e\x32%.paddle.platform.proto.MemEvent.Place\x12\x11\n\tthread_id\x18\x05 \x01(\x04\x12\x11\n\tdevice_id\x18\x06 \x01(\r\x12\x10\n\x08\x61lloc_in\x18\x07 \x01(\t\x12\x0f\n\x07\x66ree_in\x18\x08 \x01(\t\"U\n\x05Place\x12\r\n\tCUDAPlace\x10\x00\x12\x0c\n\x08\x43PUPlace\x10\x01\x12\x13\n\x0f\x43UDAPinnedPlace\x10\x02\x12\x0c\n\x08XPUPlace\x10\x03\x12\x0c\n\x08NPUPlace\x10\x04\"\x8e\x01\n\x07Profile\x12,\n\x06\x65vents\x18\x01 \x03(\x0b\x32\x1c.paddle.platform.proto.Event\x12\x10\n\x08start_ns\x18\x02 \x01(\x04\x12\x0e\n\x06\x65nd_ns\x18\x03 \x01(\x04\x12\x33\n\nmem_events\x18\x04 \x03(\x0b\x32\x1f.paddle.platform.proto.MemEvent') +) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_EVENT_EVENTTYPE = _descriptor.EnumDescriptor( + name='EventType', + full_name='paddle.platform.proto.Event.EventType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='CPU', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='GPUKernel', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='NPUKernel', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=291, + serialized_end=341, +) +_sym_db.RegisterEnumDescriptor(_EVENT_EVENTTYPE) + +_MEMEVENT_PLACE = _descriptor.EnumDescriptor( + name='Place', + full_name='paddle.platform.proto.MemEvent.Place', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='CUDAPlace', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CPUPlace', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CUDAPinnedPlace', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='XPUPlace', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='NPUPlace', index=4, number=4, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=532, + serialized_end=617, +) +_sym_db.RegisterEnumDescriptor(_MEMEVENT_PLACE) + + +_MEMCOPY = _descriptor.Descriptor( + name='MemCopy', + full_name='paddle.platform.proto.MemCopy', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='bytes', full_name='paddle.platform.proto.MemCopy.bytes', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=41, + serialized_end=65, +) + + +_EVENT = _descriptor.Descriptor( + name='Event', + full_name='paddle.platform.proto.Event', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type', full_name='paddle.platform.proto.Event.type', index=0, + number=8, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='name', full_name='paddle.platform.proto.Event.name', index=1, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_ns', full_name='paddle.platform.proto.Event.start_ns', index=2, + number=2, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_ns', full_name='paddle.platform.proto.Event.end_ns', index=3, + number=3, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_id', full_name='paddle.platform.proto.Event.device_id', index=4, + number=5, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sub_device_id', full_name='paddle.platform.proto.Event.sub_device_id', index=5, + number=6, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='memcopy', full_name='paddle.platform.proto.Event.memcopy', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='detail_info', full_name='paddle.platform.proto.Event.detail_info', index=7, + number=9, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _EVENT_EVENTTYPE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=68, + serialized_end=341, +) + + +_MEMEVENT = _descriptor.Descriptor( + name='MemEvent', + full_name='paddle.platform.proto.MemEvent', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='start_ns', full_name='paddle.platform.proto.MemEvent.start_ns', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_ns', full_name='paddle.platform.proto.MemEvent.end_ns', index=1, + number=2, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bytes', full_name='paddle.platform.proto.MemEvent.bytes', index=2, + number=3, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='place', full_name='paddle.platform.proto.MemEvent.place', index=3, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_id', full_name='paddle.platform.proto.MemEvent.thread_id', index=4, + number=5, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_id', full_name='paddle.platform.proto.MemEvent.device_id', index=5, + number=6, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='alloc_in', full_name='paddle.platform.proto.MemEvent.alloc_in', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='free_in', full_name='paddle.platform.proto.MemEvent.free_in', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _MEMEVENT_PLACE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=344, + serialized_end=617, +) + + +_PROFILE = _descriptor.Descriptor( + name='Profile', + full_name='paddle.platform.proto.Profile', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='events', full_name='paddle.platform.proto.Profile.events', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_ns', full_name='paddle.platform.proto.Profile.start_ns', index=1, + number=2, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_ns', full_name='paddle.platform.proto.Profile.end_ns', index=2, + number=3, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mem_events', full_name='paddle.platform.proto.Profile.mem_events', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=620, + serialized_end=762, +) + +_EVENT.fields_by_name['type'].enum_type = _EVENT_EVENTTYPE +_EVENT.fields_by_name['memcopy'].message_type = _MEMCOPY +_EVENT_EVENTTYPE.containing_type = _EVENT +_MEMEVENT.fields_by_name['place'].enum_type = _MEMEVENT_PLACE +_MEMEVENT_PLACE.containing_type = _MEMEVENT +_PROFILE.fields_by_name['events'].message_type = _EVENT +_PROFILE.fields_by_name['mem_events'].message_type = _MEMEVENT +DESCRIPTOR.message_types_by_name['MemCopy'] = _MEMCOPY +DESCRIPTOR.message_types_by_name['Event'] = _EVENT +DESCRIPTOR.message_types_by_name['MemEvent'] = _MEMEVENT +DESCRIPTOR.message_types_by_name['Profile'] = _PROFILE + +MemCopy = _reflection.GeneratedProtocolMessageType('MemCopy', (_message.Message,), dict( + DESCRIPTOR = _MEMCOPY, + __module__ = 'profiler_pb2' + # @@protoc_insertion_point(class_scope:paddle.platform.proto.MemCopy) + )) +_sym_db.RegisterMessage(MemCopy) + +Event = _reflection.GeneratedProtocolMessageType('Event', (_message.Message,), dict( + DESCRIPTOR = _EVENT, + __module__ = 'profiler_pb2' + # @@protoc_insertion_point(class_scope:paddle.platform.proto.Event) + )) +_sym_db.RegisterMessage(Event) + +MemEvent = _reflection.GeneratedProtocolMessageType('MemEvent', (_message.Message,), dict( + DESCRIPTOR = _MEMEVENT, + __module__ = 'profiler_pb2' + # @@protoc_insertion_point(class_scope:paddle.platform.proto.MemEvent) + )) +_sym_db.RegisterMessage(MemEvent) + +Profile = _reflection.GeneratedProtocolMessageType('Profile', (_message.Message,), dict( + DESCRIPTOR = _PROFILE, + __module__ = 'profiler_pb2' + # @@protoc_insertion_point(class_scope:paddle.platform.proto.Profile) + )) +_sym_db.RegisterMessage(Profile) + + +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/trainer_desc_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/trainer_desc_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..93a29fa0ed34c2297172784d747bc4959565915b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/proto/trainer_desc_pb2.py @@ -0,0 +1,1426 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: trainer_desc.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +import data_feed_pb2 as data__feed__pb2 +import framework_pb2 as framework__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='trainer_desc.proto', + package='paddle.framework', + syntax='proto2', + serialized_pb=_b('\n\x12trainer_desc.proto\x12\x10paddle.framework\x1a\x0f\x64\x61ta_feed.proto\x1a\x0f\x66ramework.proto\"\xd7\x0b\n\x0bTrainerDesc\x12\x12\n\nclass_name\x18\x01 \x01(\t\x12\x1a\n\x12\x64\x65vice_worker_name\x18\x02 \x01(\t\x12\x12\n\nthread_num\x18\x03 \x01(\x05\x12\x1a\n\x0b\x62inding_cpu\x18\x04 \x01(\x08:\x05\x66\x61lse\x12\x10\n\x08\x66ilelist\x18\x05 \x03(\t\x12\x14\n\x05\x64\x65\x62ug\x18\x06 \x01(\x08:\x05\x66\x61lse\x12\x33\n\x0c\x66\x65tch_config\x18\x07 \x01(\x0b\x32\x1d.paddle.framework.FetchConfig\x12\x16\n\x07use_cvm\x18\x08 \x01(\x08:\x05\x66\x61lse\x12\x18\n\tdump_slot\x18\t \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x0escale_datanorm\x18\n \x01(\x02:\x02-1\x12\x14\n\x08mpi_rank\x18\x0b \x01(\x05:\x02-1\x12\x18\n\x10\x64ump_fields_path\x18\x0c \x01(\t\x12\x13\n\x0b\x64ump_fields\x18\r \x03(\t\x12\x16\n\x0e\x64ump_converter\x18\x0e \x01(\t\x12\x12\n\ndump_param\x18\x0f \x03(\t\x12\x14\n\x08mpi_size\x18\x10 \x01(\x05:\x02-1\x12\x19\n\rdump_file_num\x18\x11 \x01(\x05:\x02\x31\x36\x12\x1b\n\x13\x63heck_nan_var_names\x18\x12 \x03(\t\x12<\n\x11\x63opy_table_config\x18\x13 \x01(\x0b\x32!.paddle.framework.CopyTableConfig\x12I\n\x18\x61\x64just_ins_weight_config\x18\x14 \x01(\x0b\x32\'.paddle.framework.AdjustInsWeightConfig\x12\x15\n\x06no_cvm\x18\x15 \x01(\x08:\x05\x66\x61lse\x12\x16\n\x0ethread_barrier\x18\x16 \x01(\x08\x12\x12\n\nloss_names\x18\x17 \x03(\t\x12!\n\x12\x65nable_random_dump\x18\x18 \x01(\x08:\x05\x66\x61lse\x12!\n\x12random_with_lineid\x18\x19 \x01(\x08:\x05\x66\x61lse\x12\x1c\n\rdump_interval\x18\x1a \x01(\x05:\x05\x31\x30\x30\x30\x30\x12\x15\n\rworker_places\x18\x1b \x03(\x05\x12\x15\n\rxpu_send_list\x18\x1c \x03(\t\x12\x15\n\rxpu_recv_list\x18\x1d \x03(\t\x12\x15\n\rxpu_start_idx\x18\x1e \x01(\x05\x12\x13\n\x0bxpu_end_idx\x18\x1f \x01(\x05\x12\x19\n\nuse_ps_gpu\x18 \x01(\x08:\x05\x66\x61lse\x12!\n\x19user_define_dump_filename\x18! \x01(\t\x12\x33\n%scale_sparse_gradient_with_batch_size\x18\" \x01(\x08:\x04true\x12\x10\n\x08trainers\x18# \x03(\x05\x12\x12\n\ntrainer_id\x18$ \x01(\x05\x12\x12\n\nfleet_desc\x18% \x01(\t\x12%\n\x16is_dump_in_simple_mode\x18& \x01(\x08:\x05\x66\x61lse\x12?\n\rhogwild_param\x18\x65 \x01(\x0b\x32(.paddle.framework.HogwildWorkerParameter\x12\x41\n\x0e\x64ownpour_param\x18g \x01(\x0b\x32).paddle.framework.DownpourWorkerParameter\x12\x44\n\x10pull_dense_param\x18\x66 \x01(\x0b\x32*.paddle.framework.PullDenseWorkerParameter\x12?\n\rsection_param\x18h \x01(\x0b\x32(.paddle.framework.SectionWorkerParameter\x12J\n\x13heter_section_param\x18i \x01(\x0b\x32-.paddle.framework.HeterSectionWorkerParameter\x12\x32\n\tdata_desc\x18\xc9\x01 \x01(\x0b\x32\x1e.paddle.framework.DataFeedDesc\"B\n\x16HogwildWorkerParameter\x12\x10\n\x08skip_ops\x18\x01 \x03(\t\x12\x16\n\x0estat_var_names\x18\x02 \x03(\t\"\xa0\x02\n\x17\x44ownpourWorkerParameter\x12\x36\n\x0csparse_table\x18\x01 \x03(\x0b\x32 .paddle.framework.TableParameter\x12\x35\n\x0b\x64\x65nse_table\x18\x02 \x03(\x0b\x32 .paddle.framework.TableParameter\x12\x10\n\x08skip_ops\x18\x03 \x03(\t\x12\x37\n\x0eprogram_config\x18\x04 \x03(\x0b\x32\x1f.paddle.framework.ProgramConfig\x12\x19\n\x0bpush_sparse\x18\x05 \x01(\x08:\x04true\x12\x18\n\npush_dense\x18\x06 \x01(\x08:\x04true\x12\x16\n\x0estat_var_names\x18\x07 \x03(\t\"\xa5\x02\n\x16SectionWorkerParameter\x12\x37\n\x0esection_config\x18\x01 \x01(\x0b\x32\x1f.paddle.framework.SectionConfig\x12\x15\n\nqueue_size\x18\x02 \x01(\x05:\x01\x31\x12\x15\n\nsync_steps\x18\x03 \x01(\x03:\x01\x31\x12\x1c\n\x11start_cpu_core_id\x18\x04 \x01(\x05:\x01\x31\x12\x17\n\x0fparam_need_sync\x18\x05 \x03(\t\x12\x18\n\x10num_microbatches\x18\x06 \x01(\x05\x12\x1e\n\x13num_pipeline_stages\x18\x07 \x01(\x05:\x01\x31\x12\x19\n\x0epipeline_stage\x18\x08 \x01(\x05:\x01\x31\x12\x18\n\rschedule_mode\x18\t \x01(\x05:\x01\x30\"\x90\x02\n\x1bHeterSectionWorkerParameter\x12\x37\n\x0esection_config\x18\x01 \x01(\x0b\x32\x1f.paddle.framework.SectionConfig\x12\x15\n\nqueue_size\x18\x02 \x01(\x05:\x01\x31\x12\x15\n\nsync_steps\x18\x03 \x01(\x03:\x01\x31\x12\x1c\n\x11start_cpu_core_id\x18\x04 \x01(\x05:\x01\x31\x12\x17\n\x0fparam_need_sync\x18\x05 \x03(\t\x12\x18\n\x10num_microbatches\x18\x06 \x01(\x05\x12\x1e\n\x13num_pipeline_stages\x18\x07 \x01(\x05:\x01\x31\x12\x19\n\x0epipeline_stage\x18\x08 \x01(\x05:\x01\x31\"\xa6\x02\n\rSectionConfig\x12\x39\n\x0cprogram_desc\x18\x01 \x01(\x0b\x32#.paddle.framework.proto.ProgramDesc\x12\x34\n\x05place\x18\x02 \x01(\x0e\x32%.paddle.framework.SectionConfig.Place\x12\x16\n\x0b\x63oncurrency\x18\x03 \x01(\x05:\x01\x31\x12\x1c\n\x14section_in_var_names\x18\x04 \x03(\t\x12\x1d\n\x15section_out_var_names\x18\x05 \x03(\t\x12\x14\n\x08place_id\x18\x06 \x01(\x05:\x02-1\"9\n\x05Place\x12\x0c\n\x08\x43PUPlace\x10\x00\x12\r\n\tCUDAPlace\x10\x01\x12\x13\n\x0f\x43UDAPinnedPlace\x10\x02\"\xb1\x01\n\x0b\x46\x65tchConfig\x12\x17\n\x0f\x66\x65tch_var_names\x18\x01 \x03(\t\x12\x1c\n\x14\x66\x65tch_var_str_format\x18\x02 \x03(\t\x12\x19\n\x0cprint_period\x18\x03 \x01(\x05:\x03\x31\x30\x30\x12;\n\x06method\x18\x04 \x01(\x0e\x32$.paddle.framework.FetchConfig.Method:\x05PRINT\"\x13\n\x06Method\x12\t\n\x05PRINT\x10\x00\"\x9c\x01\n\x15\x41\x64justInsWeightConfig\x12\x1a\n\x0bneed_adjust\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\x12\n\x08nid_slot\x18\x02 \x01(\t:\x00\x12\x1d\n\x12nid_adjw_threshold\x18\x03 \x01(\x02:\x01\x30\x12\x19\n\x0enid_adjw_ratio\x18\x04 \x01(\x02:\x01\x30\x12\x19\n\x0fins_weight_slot\x18\x05 \x01(\t:\x00\"1\n\x12TableDependencyMap\x12\x0b\n\x03key\x18\x01 \x02(\x05\x12\x0e\n\x06values\x18\x02 \x03(\x05\"\x8f\x03\n\x0f\x43opyTableConfig\x12\x18\n\tneed_copy\x18\x01 \x01(\x08:\x05\x66\x61lse\x12\x16\n\tbatch_num\x18\x02 \x01(\x05:\x03\x31\x30\x30\x12\x19\n\x11src_sparse_tables\x18\x03 \x03(\x05\x12\x1a\n\x12\x64\x65st_sparse_tables\x18\x04 \x03(\x05\x12\x18\n\x10src_dense_tables\x18\x05 \x03(\x05\x12\x19\n\x11\x64\x65st_dense_tables\x18\x06 \x03(\x05\x12\x14\n\x0csrc_var_list\x18\x07 \x03(\t\x12\x15\n\rdest_var_list\x18\x08 \x03(\t\x12$\n\x15\x64\x65nse_pull_after_copy\x18\t \x01(\x08:\x05\x66\x61lse\x12$\n\x16sparse_copy_by_feasign\x18\n \x01(\x08:\x04true\x12 \n\x11\x65nable_dependency\x18\x0b \x01(\x08:\x05\x66\x61lse\x12\x43\n\x15table_denpendency_map\x18\x0c \x03(\x0b\x32$.paddle.framework.TableDependencyMap\"*\n\x0c\x43ondTableMap\x12\x0b\n\x03key\x18\x01 \x02(\x05\x12\r\n\x05value\x18\x02 \x02(\x05\"\xe2\x01\n\rProgramConfig\x12\x12\n\nprogram_id\x18\x01 \x02(\t\x12\x1c\n\x14push_sparse_table_id\x18\x02 \x03(\x05\x12\x1b\n\x13push_dense_table_id\x18\x03 \x03(\x05\x12\x1c\n\x14pull_sparse_table_id\x18\x04 \x03(\x05\x12\x1b\n\x13pull_dense_table_id\x18\x05 \x03(\x05\x12G\n\x1fpartial_pushdense_condtable_map\x18\n \x03(\x0b\x32\x1e.paddle.framework.CondTableMap\"\x95\x01\n\x18PullDenseWorkerParameter\x12\x14\n\tthreshold\x18\x01 \x01(\x05:\x01\x31\x12\x12\n\ndevice_num\x18\x02 \x01(\x05\x12\x18\n\rsleep_time_ms\x18\x03 \x01(\x05:\x01\x32\x12\x35\n\x0b\x64\x65nse_table\x18\x04 \x03(\x0b\x32 .paddle.framework.TableParameter\"\xea\x02\n\x0eTableParameter\x12\x10\n\x08table_id\x18\x01 \x01(\x04\x12\x18\n\x10\x64\x65nse_value_name\x18\x02 \x03(\t\x12\x17\n\x0f\x64\x65nse_grad_name\x18\x03 \x03(\t\x12\x1d\n\x15push_dense_wait_times\x18\x05 \x03(\x05\x12\x17\n\x0fsparse_key_name\x18\x06 \x03(\t\x12\x19\n\x11sparse_value_name\x18\x07 \x03(\t\x12\x18\n\x10sparse_grad_name\x18\x08 \x03(\t\x12\x1e\n\x16push_sparse_wait_times\x18\t \x03(\x05\x12\x0f\n\x07\x65mb_dim\x18\n \x01(\x05\x12\x0f\n\x07\x66\x65\x61_dim\x18\x0b \x01(\x05\x12\x16\n\x0elabel_var_name\x18\x0c \x01(\t\x12\x17\n\x08is_local\x18\r \x01(\x08:\x05\x66\x61lse\x12\x17\n\x08is_async\x18\x0e \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x12\x61sync_wait_op_name\x18\x0f \x01(\tB\x02H\x03') + , + dependencies=[data__feed__pb2.DESCRIPTOR,framework__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_SECTIONCONFIG_PLACE = _descriptor.EnumDescriptor( + name='Place', + full_name='paddle.framework.SectionConfig.Place', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='CPUPlace', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CUDAPlace', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CUDAPinnedPlace', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2740, + serialized_end=2797, +) +_sym_db.RegisterEnumDescriptor(_SECTIONCONFIG_PLACE) + +_FETCHCONFIG_METHOD = _descriptor.EnumDescriptor( + name='Method', + full_name='paddle.framework.FetchConfig.Method', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='PRINT', index=0, number=0, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2958, + serialized_end=2977, +) +_sym_db.RegisterEnumDescriptor(_FETCHCONFIG_METHOD) + + +_TRAINERDESC = _descriptor.Descriptor( + name='TrainerDesc', + full_name='paddle.framework.TrainerDesc', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='class_name', full_name='paddle.framework.TrainerDesc.class_name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_worker_name', full_name='paddle.framework.TrainerDesc.device_worker_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_num', full_name='paddle.framework.TrainerDesc.thread_num', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='binding_cpu', full_name='paddle.framework.TrainerDesc.binding_cpu', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='filelist', full_name='paddle.framework.TrainerDesc.filelist', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='debug', full_name='paddle.framework.TrainerDesc.debug', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fetch_config', full_name='paddle.framework.TrainerDesc.fetch_config', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_cvm', full_name='paddle.framework.TrainerDesc.use_cvm', index=7, + number=8, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_slot', full_name='paddle.framework.TrainerDesc.dump_slot', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='scale_datanorm', full_name='paddle.framework.TrainerDesc.scale_datanorm', index=9, + number=10, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(-1), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mpi_rank', full_name='paddle.framework.TrainerDesc.mpi_rank', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_fields_path', full_name='paddle.framework.TrainerDesc.dump_fields_path', index=11, + number=12, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_fields', full_name='paddle.framework.TrainerDesc.dump_fields', index=12, + number=13, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_converter', full_name='paddle.framework.TrainerDesc.dump_converter', index=13, + number=14, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_param', full_name='paddle.framework.TrainerDesc.dump_param', index=14, + number=15, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mpi_size', full_name='paddle.framework.TrainerDesc.mpi_size', index=15, + number=16, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_file_num', full_name='paddle.framework.TrainerDesc.dump_file_num', index=16, + number=17, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=16, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='check_nan_var_names', full_name='paddle.framework.TrainerDesc.check_nan_var_names', index=17, + number=18, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='copy_table_config', full_name='paddle.framework.TrainerDesc.copy_table_config', index=18, + number=19, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='adjust_ins_weight_config', full_name='paddle.framework.TrainerDesc.adjust_ins_weight_config', index=19, + number=20, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='no_cvm', full_name='paddle.framework.TrainerDesc.no_cvm', index=20, + number=21, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='thread_barrier', full_name='paddle.framework.TrainerDesc.thread_barrier', index=21, + number=22, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='loss_names', full_name='paddle.framework.TrainerDesc.loss_names', index=22, + number=23, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_random_dump', full_name='paddle.framework.TrainerDesc.enable_random_dump', index=23, + number=24, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='random_with_lineid', full_name='paddle.framework.TrainerDesc.random_with_lineid', index=24, + number=25, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dump_interval', full_name='paddle.framework.TrainerDesc.dump_interval', index=25, + number=26, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=10000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='worker_places', full_name='paddle.framework.TrainerDesc.worker_places', index=26, + number=27, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='xpu_send_list', full_name='paddle.framework.TrainerDesc.xpu_send_list', index=27, + number=28, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='xpu_recv_list', full_name='paddle.framework.TrainerDesc.xpu_recv_list', index=28, + number=29, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='xpu_start_idx', full_name='paddle.framework.TrainerDesc.xpu_start_idx', index=29, + number=30, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='xpu_end_idx', full_name='paddle.framework.TrainerDesc.xpu_end_idx', index=30, + number=31, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='use_ps_gpu', full_name='paddle.framework.TrainerDesc.use_ps_gpu', index=31, + number=32, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='user_define_dump_filename', full_name='paddle.framework.TrainerDesc.user_define_dump_filename', index=32, + number=33, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='scale_sparse_gradient_with_batch_size', full_name='paddle.framework.TrainerDesc.scale_sparse_gradient_with_batch_size', index=33, + number=34, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainers', full_name='paddle.framework.TrainerDesc.trainers', index=34, + number=35, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trainer_id', full_name='paddle.framework.TrainerDesc.trainer_id', index=35, + number=36, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fleet_desc', full_name='paddle.framework.TrainerDesc.fleet_desc', index=36, + number=37, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_dump_in_simple_mode', full_name='paddle.framework.TrainerDesc.is_dump_in_simple_mode', index=37, + number=38, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='hogwild_param', full_name='paddle.framework.TrainerDesc.hogwild_param', index=38, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='downpour_param', full_name='paddle.framework.TrainerDesc.downpour_param', index=39, + number=103, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_dense_param', full_name='paddle.framework.TrainerDesc.pull_dense_param', index=40, + number=102, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='section_param', full_name='paddle.framework.TrainerDesc.section_param', index=41, + number=104, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='heter_section_param', full_name='paddle.framework.TrainerDesc.heter_section_param', index=42, + number=105, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='data_desc', full_name='paddle.framework.TrainerDesc.data_desc', index=43, + number=201, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=75, + serialized_end=1570, +) + + +_HOGWILDWORKERPARAMETER = _descriptor.Descriptor( + name='HogwildWorkerParameter', + full_name='paddle.framework.HogwildWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='skip_ops', full_name='paddle.framework.HogwildWorkerParameter.skip_ops', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stat_var_names', full_name='paddle.framework.HogwildWorkerParameter.stat_var_names', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1572, + serialized_end=1638, +) + + +_DOWNPOURWORKERPARAMETER = _descriptor.Descriptor( + name='DownpourWorkerParameter', + full_name='paddle.framework.DownpourWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sparse_table', full_name='paddle.framework.DownpourWorkerParameter.sparse_table', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_table', full_name='paddle.framework.DownpourWorkerParameter.dense_table', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='skip_ops', full_name='paddle.framework.DownpourWorkerParameter.skip_ops', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='program_config', full_name='paddle.framework.DownpourWorkerParameter.program_config', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse', full_name='paddle.framework.DownpourWorkerParameter.push_sparse', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense', full_name='paddle.framework.DownpourWorkerParameter.push_dense', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stat_var_names', full_name='paddle.framework.DownpourWorkerParameter.stat_var_names', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1641, + serialized_end=1929, +) + + +_SECTIONWORKERPARAMETER = _descriptor.Descriptor( + name='SectionWorkerParameter', + full_name='paddle.framework.SectionWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='section_config', full_name='paddle.framework.SectionWorkerParameter.section_config', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='queue_size', full_name='paddle.framework.SectionWorkerParameter.queue_size', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_steps', full_name='paddle.framework.SectionWorkerParameter.sync_steps', index=2, + number=3, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_cpu_core_id', full_name='paddle.framework.SectionWorkerParameter.start_cpu_core_id', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='param_need_sync', full_name='paddle.framework.SectionWorkerParameter.param_need_sync', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_microbatches', full_name='paddle.framework.SectionWorkerParameter.num_microbatches', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_pipeline_stages', full_name='paddle.framework.SectionWorkerParameter.num_pipeline_stages', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline_stage', full_name='paddle.framework.SectionWorkerParameter.pipeline_stage', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='schedule_mode', full_name='paddle.framework.SectionWorkerParameter.schedule_mode', index=8, + number=9, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1932, + serialized_end=2225, +) + + +_HETERSECTIONWORKERPARAMETER = _descriptor.Descriptor( + name='HeterSectionWorkerParameter', + full_name='paddle.framework.HeterSectionWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='section_config', full_name='paddle.framework.HeterSectionWorkerParameter.section_config', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='queue_size', full_name='paddle.framework.HeterSectionWorkerParameter.queue_size', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sync_steps', full_name='paddle.framework.HeterSectionWorkerParameter.sync_steps', index=2, + number=3, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_cpu_core_id', full_name='paddle.framework.HeterSectionWorkerParameter.start_cpu_core_id', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='param_need_sync', full_name='paddle.framework.HeterSectionWorkerParameter.param_need_sync', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_microbatches', full_name='paddle.framework.HeterSectionWorkerParameter.num_microbatches', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='num_pipeline_stages', full_name='paddle.framework.HeterSectionWorkerParameter.num_pipeline_stages', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pipeline_stage', full_name='paddle.framework.HeterSectionWorkerParameter.pipeline_stage', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2228, + serialized_end=2500, +) + + +_SECTIONCONFIG = _descriptor.Descriptor( + name='SectionConfig', + full_name='paddle.framework.SectionConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='program_desc', full_name='paddle.framework.SectionConfig.program_desc', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='place', full_name='paddle.framework.SectionConfig.place', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='concurrency', full_name='paddle.framework.SectionConfig.concurrency', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='section_in_var_names', full_name='paddle.framework.SectionConfig.section_in_var_names', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='section_out_var_names', full_name='paddle.framework.SectionConfig.section_out_var_names', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='place_id', full_name='paddle.framework.SectionConfig.place_id', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _SECTIONCONFIG_PLACE, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2503, + serialized_end=2797, +) + + +_FETCHCONFIG = _descriptor.Descriptor( + name='FetchConfig', + full_name='paddle.framework.FetchConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fetch_var_names', full_name='paddle.framework.FetchConfig.fetch_var_names', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fetch_var_str_format', full_name='paddle.framework.FetchConfig.fetch_var_str_format', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='print_period', full_name='paddle.framework.FetchConfig.print_period', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=100, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='method', full_name='paddle.framework.FetchConfig.method', index=3, + number=4, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FETCHCONFIG_METHOD, + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2800, + serialized_end=2977, +) + + +_ADJUSTINSWEIGHTCONFIG = _descriptor.Descriptor( + name='AdjustInsWeightConfig', + full_name='paddle.framework.AdjustInsWeightConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='need_adjust', full_name='paddle.framework.AdjustInsWeightConfig.need_adjust', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nid_slot', full_name='paddle.framework.AdjustInsWeightConfig.nid_slot', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nid_adjw_threshold', full_name='paddle.framework.AdjustInsWeightConfig.nid_adjw_threshold', index=2, + number=3, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nid_adjw_ratio', full_name='paddle.framework.AdjustInsWeightConfig.nid_adjw_ratio', index=3, + number=4, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ins_weight_slot', full_name='paddle.framework.AdjustInsWeightConfig.ins_weight_slot', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=2980, + serialized_end=3136, +) + + +_TABLEDEPENDENCYMAP = _descriptor.Descriptor( + name='TableDependencyMap', + full_name='paddle.framework.TableDependencyMap', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='paddle.framework.TableDependencyMap.key', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='values', full_name='paddle.framework.TableDependencyMap.values', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3138, + serialized_end=3187, +) + + +_COPYTABLECONFIG = _descriptor.Descriptor( + name='CopyTableConfig', + full_name='paddle.framework.CopyTableConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='need_copy', full_name='paddle.framework.CopyTableConfig.need_copy', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='batch_num', full_name='paddle.framework.CopyTableConfig.batch_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=100, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='src_sparse_tables', full_name='paddle.framework.CopyTableConfig.src_sparse_tables', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dest_sparse_tables', full_name='paddle.framework.CopyTableConfig.dest_sparse_tables', index=3, + number=4, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='src_dense_tables', full_name='paddle.framework.CopyTableConfig.src_dense_tables', index=4, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dest_dense_tables', full_name='paddle.framework.CopyTableConfig.dest_dense_tables', index=5, + number=6, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='src_var_list', full_name='paddle.framework.CopyTableConfig.src_var_list', index=6, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dest_var_list', full_name='paddle.framework.CopyTableConfig.dest_var_list', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_pull_after_copy', full_name='paddle.framework.CopyTableConfig.dense_pull_after_copy', index=8, + number=9, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_copy_by_feasign', full_name='paddle.framework.CopyTableConfig.sparse_copy_by_feasign', index=9, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enable_dependency', full_name='paddle.framework.CopyTableConfig.enable_dependency', index=10, + number=11, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table_denpendency_map', full_name='paddle.framework.CopyTableConfig.table_denpendency_map', index=11, + number=12, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3190, + serialized_end=3589, +) + + +_CONDTABLEMAP = _descriptor.Descriptor( + name='CondTableMap', + full_name='paddle.framework.CondTableMap', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='paddle.framework.CondTableMap.key', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='paddle.framework.CondTableMap.value', index=1, + number=2, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3591, + serialized_end=3633, +) + + +_PROGRAMCONFIG = _descriptor.Descriptor( + name='ProgramConfig', + full_name='paddle.framework.ProgramConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='program_id', full_name='paddle.framework.ProgramConfig.program_id', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_table_id', full_name='paddle.framework.ProgramConfig.push_sparse_table_id', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_table_id', full_name='paddle.framework.ProgramConfig.push_dense_table_id', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_sparse_table_id', full_name='paddle.framework.ProgramConfig.pull_sparse_table_id', index=3, + number=4, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='pull_dense_table_id', full_name='paddle.framework.ProgramConfig.pull_dense_table_id', index=4, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='partial_pushdense_condtable_map', full_name='paddle.framework.ProgramConfig.partial_pushdense_condtable_map', index=5, + number=10, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3636, + serialized_end=3862, +) + + +_PULLDENSEWORKERPARAMETER = _descriptor.Descriptor( + name='PullDenseWorkerParameter', + full_name='paddle.framework.PullDenseWorkerParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='threshold', full_name='paddle.framework.PullDenseWorkerParameter.threshold', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='device_num', full_name='paddle.framework.PullDenseWorkerParameter.device_num', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sleep_time_ms', full_name='paddle.framework.PullDenseWorkerParameter.sleep_time_ms', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=2, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_table', full_name='paddle.framework.PullDenseWorkerParameter.dense_table', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=3865, + serialized_end=4014, +) + + +_TABLEPARAMETER = _descriptor.Descriptor( + name='TableParameter', + full_name='paddle.framework.TableParameter', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table_id', full_name='paddle.framework.TableParameter.table_id', index=0, + number=1, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_value_name', full_name='paddle.framework.TableParameter.dense_value_name', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dense_grad_name', full_name='paddle.framework.TableParameter.dense_grad_name', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_dense_wait_times', full_name='paddle.framework.TableParameter.push_dense_wait_times', index=3, + number=5, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_key_name', full_name='paddle.framework.TableParameter.sparse_key_name', index=4, + number=6, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_value_name', full_name='paddle.framework.TableParameter.sparse_value_name', index=5, + number=7, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sparse_grad_name', full_name='paddle.framework.TableParameter.sparse_grad_name', index=6, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='push_sparse_wait_times', full_name='paddle.framework.TableParameter.push_sparse_wait_times', index=7, + number=9, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='emb_dim', full_name='paddle.framework.TableParameter.emb_dim', index=8, + number=10, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fea_dim', full_name='paddle.framework.TableParameter.fea_dim', index=9, + number=11, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='label_var_name', full_name='paddle.framework.TableParameter.label_var_name', index=10, + number=12, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_local', full_name='paddle.framework.TableParameter.is_local', index=11, + number=13, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_async', full_name='paddle.framework.TableParameter.is_async', index=12, + number=14, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='async_wait_op_name', full_name='paddle.framework.TableParameter.async_wait_op_name', index=13, + number=15, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto2', + extension_ranges=[], + oneofs=[ + ], + serialized_start=4017, + serialized_end=4379, +) + +_TRAINERDESC.fields_by_name['fetch_config'].message_type = _FETCHCONFIG +_TRAINERDESC.fields_by_name['copy_table_config'].message_type = _COPYTABLECONFIG +_TRAINERDESC.fields_by_name['adjust_ins_weight_config'].message_type = _ADJUSTINSWEIGHTCONFIG +_TRAINERDESC.fields_by_name['hogwild_param'].message_type = _HOGWILDWORKERPARAMETER +_TRAINERDESC.fields_by_name['downpour_param'].message_type = _DOWNPOURWORKERPARAMETER +_TRAINERDESC.fields_by_name['pull_dense_param'].message_type = _PULLDENSEWORKERPARAMETER +_TRAINERDESC.fields_by_name['section_param'].message_type = _SECTIONWORKERPARAMETER +_TRAINERDESC.fields_by_name['heter_section_param'].message_type = _HETERSECTIONWORKERPARAMETER +_TRAINERDESC.fields_by_name['data_desc'].message_type = data__feed__pb2._DATAFEEDDESC +_DOWNPOURWORKERPARAMETER.fields_by_name['sparse_table'].message_type = _TABLEPARAMETER +_DOWNPOURWORKERPARAMETER.fields_by_name['dense_table'].message_type = _TABLEPARAMETER +_DOWNPOURWORKERPARAMETER.fields_by_name['program_config'].message_type = _PROGRAMCONFIG +_SECTIONWORKERPARAMETER.fields_by_name['section_config'].message_type = _SECTIONCONFIG +_HETERSECTIONWORKERPARAMETER.fields_by_name['section_config'].message_type = _SECTIONCONFIG +_SECTIONCONFIG.fields_by_name['program_desc'].message_type = framework__pb2._PROGRAMDESC +_SECTIONCONFIG.fields_by_name['place'].enum_type = _SECTIONCONFIG_PLACE +_SECTIONCONFIG_PLACE.containing_type = _SECTIONCONFIG +_FETCHCONFIG.fields_by_name['method'].enum_type = _FETCHCONFIG_METHOD +_FETCHCONFIG_METHOD.containing_type = _FETCHCONFIG +_COPYTABLECONFIG.fields_by_name['table_denpendency_map'].message_type = _TABLEDEPENDENCYMAP +_PROGRAMCONFIG.fields_by_name['partial_pushdense_condtable_map'].message_type = _CONDTABLEMAP +_PULLDENSEWORKERPARAMETER.fields_by_name['dense_table'].message_type = _TABLEPARAMETER +DESCRIPTOR.message_types_by_name['TrainerDesc'] = _TRAINERDESC +DESCRIPTOR.message_types_by_name['HogwildWorkerParameter'] = _HOGWILDWORKERPARAMETER +DESCRIPTOR.message_types_by_name['DownpourWorkerParameter'] = _DOWNPOURWORKERPARAMETER +DESCRIPTOR.message_types_by_name['SectionWorkerParameter'] = _SECTIONWORKERPARAMETER +DESCRIPTOR.message_types_by_name['HeterSectionWorkerParameter'] = _HETERSECTIONWORKERPARAMETER +DESCRIPTOR.message_types_by_name['SectionConfig'] = _SECTIONCONFIG +DESCRIPTOR.message_types_by_name['FetchConfig'] = _FETCHCONFIG +DESCRIPTOR.message_types_by_name['AdjustInsWeightConfig'] = _ADJUSTINSWEIGHTCONFIG +DESCRIPTOR.message_types_by_name['TableDependencyMap'] = _TABLEDEPENDENCYMAP +DESCRIPTOR.message_types_by_name['CopyTableConfig'] = _COPYTABLECONFIG +DESCRIPTOR.message_types_by_name['CondTableMap'] = _CONDTABLEMAP +DESCRIPTOR.message_types_by_name['ProgramConfig'] = _PROGRAMCONFIG +DESCRIPTOR.message_types_by_name['PullDenseWorkerParameter'] = _PULLDENSEWORKERPARAMETER +DESCRIPTOR.message_types_by_name['TableParameter'] = _TABLEPARAMETER + +TrainerDesc = _reflection.GeneratedProtocolMessageType('TrainerDesc', (_message.Message,), dict( + DESCRIPTOR = _TRAINERDESC, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.TrainerDesc) + )) +_sym_db.RegisterMessage(TrainerDesc) + +HogwildWorkerParameter = _reflection.GeneratedProtocolMessageType('HogwildWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _HOGWILDWORKERPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.HogwildWorkerParameter) + )) +_sym_db.RegisterMessage(HogwildWorkerParameter) + +DownpourWorkerParameter = _reflection.GeneratedProtocolMessageType('DownpourWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _DOWNPOURWORKERPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.DownpourWorkerParameter) + )) +_sym_db.RegisterMessage(DownpourWorkerParameter) + +SectionWorkerParameter = _reflection.GeneratedProtocolMessageType('SectionWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _SECTIONWORKERPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.SectionWorkerParameter) + )) +_sym_db.RegisterMessage(SectionWorkerParameter) + +HeterSectionWorkerParameter = _reflection.GeneratedProtocolMessageType('HeterSectionWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _HETERSECTIONWORKERPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.HeterSectionWorkerParameter) + )) +_sym_db.RegisterMessage(HeterSectionWorkerParameter) + +SectionConfig = _reflection.GeneratedProtocolMessageType('SectionConfig', (_message.Message,), dict( + DESCRIPTOR = _SECTIONCONFIG, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.SectionConfig) + )) +_sym_db.RegisterMessage(SectionConfig) + +FetchConfig = _reflection.GeneratedProtocolMessageType('FetchConfig', (_message.Message,), dict( + DESCRIPTOR = _FETCHCONFIG, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.FetchConfig) + )) +_sym_db.RegisterMessage(FetchConfig) + +AdjustInsWeightConfig = _reflection.GeneratedProtocolMessageType('AdjustInsWeightConfig', (_message.Message,), dict( + DESCRIPTOR = _ADJUSTINSWEIGHTCONFIG, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.AdjustInsWeightConfig) + )) +_sym_db.RegisterMessage(AdjustInsWeightConfig) + +TableDependencyMap = _reflection.GeneratedProtocolMessageType('TableDependencyMap', (_message.Message,), dict( + DESCRIPTOR = _TABLEDEPENDENCYMAP, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.TableDependencyMap) + )) +_sym_db.RegisterMessage(TableDependencyMap) + +CopyTableConfig = _reflection.GeneratedProtocolMessageType('CopyTableConfig', (_message.Message,), dict( + DESCRIPTOR = _COPYTABLECONFIG, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.CopyTableConfig) + )) +_sym_db.RegisterMessage(CopyTableConfig) + +CondTableMap = _reflection.GeneratedProtocolMessageType('CondTableMap', (_message.Message,), dict( + DESCRIPTOR = _CONDTABLEMAP, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.CondTableMap) + )) +_sym_db.RegisterMessage(CondTableMap) + +ProgramConfig = _reflection.GeneratedProtocolMessageType('ProgramConfig', (_message.Message,), dict( + DESCRIPTOR = _PROGRAMCONFIG, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.ProgramConfig) + )) +_sym_db.RegisterMessage(ProgramConfig) + +PullDenseWorkerParameter = _reflection.GeneratedProtocolMessageType('PullDenseWorkerParameter', (_message.Message,), dict( + DESCRIPTOR = _PULLDENSEWORKERPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.PullDenseWorkerParameter) + )) +_sym_db.RegisterMessage(PullDenseWorkerParameter) + +TableParameter = _reflection.GeneratedProtocolMessageType('TableParameter', (_message.Message,), dict( + DESCRIPTOR = _TABLEPARAMETER, + __module__ = 'trainer_desc_pb2' + # @@protoc_insertion_point(class_scope:paddle.framework.TableParameter) + )) +_sym_db.RegisterMessage(TableParameter) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('H\003')) +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/reader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..c590d69a621de631274346cf973ac1ed4373b723 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/reader.py @@ -0,0 +1,2034 @@ +# 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. + +from . import core +import sys +import six +import numpy as np +import threading +import paddle +import time +import copy + +from .framework import Program, Variable, program_guard, default_main_program, default_startup_program, _non_static_mode, cpu_places, _current_expected_place, _in_eager_without_dygraph_check +from .executor import global_scope +from .data_feeder import DataFeeder, BatchedTensorProvider +from .multiprocess_utils import multiprocess_queue_set, CleanupFuncRegistrar, _cleanup_mmap, _cleanup, _set_SIGCHLD_handler +from .dataloader import BatchSampler, Dataset, IterableDataset, Subset +from .dataloader.dataloader_iter import _DataLoaderIterSingleProcess, _DataLoaderIterMultiProcess, _DatasetKind, default_collate_fn +from .dataloader.batch_sampler import _InfiniteIterableSampler +from .layers.io import monkey_patch_reader_methods, _copy_reader_var_, double_buffer +from .unique_name import UniqueNameGenerator +from .framework import _get_paddle_place, _get_paddle_place_list +from paddle.fluid.framework import _set_expected_place, _current_expected_place +import logging +import warnings + +### Dygraph DataLoader configs ### +import os +import multiprocessing +import signal +# NOTE: queue has a different name in python2 and python3 +import queue +# NOTE: [ avoid hanging & failed quickly ] These value is used in getting data from another process +QUEUE_GET_TIMEOUT = 60 + +__all__ = ['PyReader', 'DataLoader', 'default_collate_fn'] + +data_loader_unique_name_generator = UniqueNameGenerator() + +KEEP_DATA_LOADER_ORDER = True +USE_PINNED_MEMORY = None +# AutoTune Flags +USE_AUTOTUNE = False +TUNING_STEPS = 500 + + +def set_autotune_config(use_autotune, tuning_steps=500): + global USE_AUTOTUNE + USE_AUTOTUNE = use_autotune + global TUNING_STEPS + TUNING_STEPS = tuning_steps + + +def keep_data_loader_order(*args): + global KEEP_DATA_LOADER_ORDER + if len(args) == 0: + return KEEP_DATA_LOADER_ORDER + else: + assert len(args) == 1 and isinstance(args[0], bool) + KEEP_DATA_LOADER_ORDER = args[0] + + +def use_pinned_memory(*args): + global USE_PINNED_MEMORY + if len(args) == 0: + return USE_PINNED_MEMORY + else: + assert len(args) == 1 and isinstance(args[0], bool) + USE_PINNED_MEMORY = args[0] + + +def _convert_places(places): + if not isinstance(places, (list, tuple)): + places = [places] + + ret = [] + for p in places: + if not isinstance(p, core.Place): + tmp = core.Place() + tmp.set_place(p) + p = tmp + + ret.append(p) + return ret + + +# NOTE(chenweihang): _reader_process_loop must be top level method to be pickled +def _reader_process_loop(batch_reader, data_queue): + try: + # set signal handler + core._set_process_signal_handler() + + # NOTE: [ mmap files clear ] When the child process exits unexpectedly, + # some shared memory objects may have been applied for but have not yet + # been put into the inter-process Queue. This part of the object needs + # to be cleaned up when the process ends. + CleanupFuncRegistrar.register(_cleanup_mmap) + + for batch in batch_reader(): + tensor_list = core._convert_to_tensor_list(batch) + data_queue.put(tensor_list) + core._remove_tensor_list_mmap_fds(tensor_list) + data_queue.put(None) + except KeyboardInterrupt: + # NOTE: Main process will raise KeyboardInterrupt anyways, ignore it in child process + pass + except: + six.reraise(*sys.exc_info()) + + +class DataLoaderBase(object): + + def __init__(self): + self._places = None + + def __call__(self): + return self + + def next(self): + ''' + Get the next item in the DataLoader object. This method + should not be called by users directly. It is used for + implementing iterator protocol of Python 2.x inside + PaddlePaddle framework. + ''' + return self.__next__() + + def __iter__(self): + raise NotImplementedError() + + def __next__(self): + raise NotImplementedError() + + @classmethod + def _check_input_array(cls, item): + arr = np.asarray(item) + if arr.dtype == np.object_: + raise TypeError( + "\n\tFaild to convert input data to a regular ndarray :\n\t* Usually " + "this means the input data contains nested lists with different lengths. " + "\n\t* Check the reader function passed to 'decorate_batch_generator'" + " to locate the data causes this issue.\n\t* Please consider using " + "'fluid.create_lod_tensor' to convert it to a LoD-Tensor.") + return arr + + +class AuToTune(object): + + def __init__(self, loader): + self.loader = loader + self.max_num_worker = multiprocessing.cpu_count() / 2 + + def __call__(self): + # use default loader + if (not USE_AUTOTUNE) or (not self.need_autotune()): + return self.loader.num_workers + + # get autotune loader + auto_tune_loader = self.get_autotune_loader() + if auto_tune_loader is None: + return self.loader.num_workers + + # pick the best num_workers + auto_tune_start = time.time() + logging.debug("========= DataLoader Auto Tune =========") + logging.debug("User config for DataLoader: " + + str(self.loader.num_workers)) + best_num_workers = 0 + min_cost = float("inf") + logging.debug("Tuning Range for num_workers: 0 ~ " + + str(self.max_num_worker)) + num_workers = 0 + while num_workers < self.max_num_worker: + auto_tune_loader.num_workers = num_workers + avg_cost = self.evaluate_reader_cost(auto_tune_loader) + if min_cost * 0.75 > avg_cost: + min_cost = avg_cost + best_num_workers = num_workers + else: + update_num = self.is_best(auto_tune_loader, best_num_workers, + min_cost, self.max_num_worker) + if update_num == best_num_workers: + break + else: + best_num_workers = update_num + logging.debug("num_workers: " + str(num_workers) + " avg_cost: " + + str(avg_cost)) + num_workers += 2 + logging.info("auto_tune dataLoader best_num_workers: " + + str(best_num_workers)) + logging.debug("AutoTuning Cost for DataLoader: " + + str(time.time() - auto_tune_start) + ' seconds') + + # tune the default loader's num_workers + return best_num_workers + + def need_autotune(self): + if (sys.platform == 'darwin' or sys.platform == 'win32'): + return False + else: + return True + + def get_sub_dataset(self, dataset, batch_size): + num_samples = min(batch_size * TUNING_STEPS, len(dataset)) + sub_dataset = Subset(dataset, indices=list(range(num_samples))) + return sub_dataset + + def get_autotune_loader(self): + loader = copy.copy(self.loader) + batch_size = self.loader.batch_sampler.batch_size + if isinstance(self.loader.batch_sampler, + paddle.io.DistributedBatchSampler): + dataset = self.loader.batch_sampler.dataset + sub_dataset = self.get_sub_dataset(dataset, batch_size) + loader.batch_sampler = paddle.io.DistributedBatchSampler( + dataset=sub_dataset, + batch_size=batch_size, + num_replicas=self.loader.batch_sampler.nranks, + rank=self.loader.batch_sampler.local_rank, + shuffle=self.loader.batch_sampler.shuffle, + drop_last=self.loader.batch_sampler.drop_last) + elif isinstance(self.loader.batch_sampler, paddle.io.BatchSampler): + dataset = self.loader.batch_sampler.sampler.data_source + sub_dataset = self.get_sub_dataset(dataset, batch_size) + loader.batch_sampler = paddle.io.BatchSampler( + dataset=sub_dataset, + batch_size=batch_size, + drop_last=self.loader.batch_sampler.drop_last) + else: + loader = None + return loader + + def evaluate_reader_cost(self, reader): + costs = [] + avg_cost = 0 + start = time.time() + for i, data in enumerate(reader): + costs.append(time.time() - start) + start = time.time() + if len(costs) > 2: + avg_cost = sum(costs[2:]) / len(costs[2:]) + else: + avg_cost = sum(costs[0:]) / len(costs[0:]) + return avg_cost + + def is_best(self, reader, best_workers, best_time, num_work_boundary): + step = 0 + num_workers = best_workers + 1 + boundary = 1 + while num_workers < num_work_boundary and step < 5: + self.loader.num_workers = num_workers + time = self.evaluate_reader_cost(reader) + logging.debug("for back num_workers: " + str(num_workers) + + " avg_cost: " + str(time)) + step += 1 + if (time < best_time * 0.70 * boundary): + return num_workers + else: + num_workers += 1 + boundary *= 0.80 + return best_workers + + +class DataLoader(object): + """ + DataLoader prodives an iterator which iterates given dataset + once by the batch_sampler. + + DataLoader supports single-process and multi-prcess data loading, + multi-process workers will be used to load data asynchronously if + :attr:`num_workers` is set as a positive number. + + DataLoader supports map-style dataset and iterable-style dataset. + + For map-style datast(can get a sample from dataset with a given + index), please see :code:`paddle.io.Dataset`. + + For iterable-style datast(get samples from dataset iteratively, + like a Python iterator), please see :code:`paddle.io.IterableDataset`. + + For :code:`batch_sampler` please see :code:`paddle.io.BatchSampler` + + .. note:: + GPU tensor operation is not supported in subprocess currently, + please don't use GPU tensor operations in pipeline which will + be performed in subprocess, such as dataset transforms, collte_fn, + etc. Numpy array and CPU tensor operation is supported. + + **Disable automatic batching** + + In certain cases such as some NLP tasks, instead of automatic batching, + handling batching manually in dataset is needed by users. For these + cases, automatic batching is disabled if both :attr:`batch_size` and + :attr:`batch_sampler` is set as None, each data got from :attr:`dataset` + should be batched data and will be processed with function define by + :attr:`collate_fn` or :attr:`default_collate_fn`. + + + .. note:: + When automatic batching is disabled, :attr:`default_collate_fn` will + do nothing to data from dataset. + + + Args: + dataset(Dataset): the dataset to load data from, should be an + instance of subclass of :code:`paddle.io.Dataset` or + :code:`paddle.io.IterableDataset`. + feed_list (list(Tensor)|tuple(Tensor), optional): feed Tensor list. + The Tensors should be created by :code:`paddle.static.data()`. + :attr:`feed_list` must be set if :attr:`return_list` is + False. Default None. + places(list(Place)|tuple(Place)|list(str), optional): a list of Place, + to put data onto, :attr:`places` can be None, if + :attr:`places` is None, default place(CPUPlace or CUDAPlace(0)) + will be used. Default None. If ``places`` is list of string, + the string in the list can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, + where ``x`` is the index of the GPUs. + return_list (bool, optional): whether the return value on each device is + presented as a list. If :attr:`return_list=False`, the return + value on each device would be a dict of str -> Tensor, where + the key of the dict is the name of each fed Tensors. If + :attr:`return_list=True`, the return value on each device would + be a list(Tensor). :attr:`return_list` can only be True + in dynamic graph mode. Default True. + batch_sampler(BatchSampler, optional): an instance of `paddle.io.BatchSampler` + to generate batch indices to draw samples from :attr:`dataset` + and combine a batch. Default None. + batch_size(int|None, optional): sample number in a mini-batch, a substitution + parameter for :attr:`batch_sampler`, if :attr:`batch_sampler` + is not set, a default `paddle.io.BatchSampler` will be used + and initialize by :attr:`batch_size`, :attr:`shuffle` and + :attr:`drop_last`. Default 1. + shuffle(bool, optional): whther to shuffle indices order before genrate + batch indices, a substitution parameter for :attr:`batch_sampler` + see :attr:`batch_size`. Default False. + drop_last(bool, optional): whether drop the last incomplete batch dataset size + is not divisible by the batch size, a substitution parameter + for :attr:`batch_sampler`, see :attr:`batch_size`. Default False + collate_fn(callable, optional): function to generate mini-batch data by merging + the sample list, None for only stack each fields of sample in axis + 0(same as :attr::`np.stack(..., axis=0)`). Default None + num_workers(int, optional): the number of subprocess to load data, 0 for no + subprocess used and loading data in main process. Default 0 + use_buffer_reader (bool, optional): whether to use bufferred reader. + If use_buffer_reader=True, the DataLoader would prefetch + batch data asynchronously, so it would speed up data feeding + and occupies a little more CPU or GPU memory, i.e., the memory + of one batch input data. Default True. + prefetch_factor (int, optional): Number of batch data the DataLoader would prefetch + if use_buffer_reader=True. Default 2. + use_shared_memory (bool, optional): whether to use shared memory to speed up + putting data into inter-process queue, set :attr:`use_shared_memory` + as True only when the shared memory space on your machine(e.g. + space of '/dev/shm' on Linux operating sysytem) is large enough. + Shared memory will only be enabled in multi-process mode(num_workers + > 0). Default True. + timeout(int, optional): the timeout value for getting data form output queue + of subprocesses. Default 0. + worker_init_fn(callable, optional): init function which will be called with + worker id on each subproces starting if not set as None. Default + None. + + Returns: + DataLoader: an iterable object for data iterating, each elemnet of the generated data is a Tensor. + + Examples: + + .. code-block:: python + + import numpy as np + + import paddle + import paddle.nn as nn + import paddle.nn.functional as F + from paddle.io import Dataset, BatchSampler, DataLoader + + BATCH_NUM = 20 + BATCH_SIZE = 16 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + + class SimpleNet(nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + self.fc = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + def forward(self, image, label=None): + return self.fc(image) + + simple_net = SimpleNet() + opt = paddle.optimizer.SGD(learning_rate=1e-3, + parameters=simple_net.parameters()) + + loader = DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + for e in range(EPOCH_NUM): + for i, (image, label) in enumerate(loader()): + out = simple_net(image) + loss = F.cross_entropy(out, label) + avg_loss = paddle.mean(loss) + avg_loss.backward() + opt.minimize(avg_loss) + simple_net.clear_gradients() + print("Epoch {} batch {}: loss = {}".format(e, i, np.mean(loss.numpy()))) + + + .. note:: + For reading iterable dataset with multiprocess Dataloader, + please see :code:`paddle.io.IterableDataset` + + """ + + def __init__(self, + dataset, + feed_list=None, + places=None, + return_list=True, + batch_sampler=None, + batch_size=1, + shuffle=False, + drop_last=False, + collate_fn=None, + num_workers=0, + use_buffer_reader=True, + prefetch_factor=2, + use_shared_memory=True, + timeout=0, + worker_init_fn=None, + persistent_workers=False): + self.return_list = return_list + self.collate_fn = collate_fn + self.use_buffer_reader = use_buffer_reader + self.prefetch_factor = prefetch_factor + self.worker_init_fn = worker_init_fn + + self.dataset = dataset + + if not return_list and not _non_static_mode(): + assert feed_list is not None, \ + "feed_list should be set when return_list=False" + self.feed_list = feed_list + + if places is None: + places = _current_expected_place() + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + self.places = _convert_places(places) + + assert num_workers >= 0, "num_workers should be a non-negative value" + if num_workers > 0 and (sys.platform == 'darwin' + or sys.platform == 'win32'): + warnings.warn( + "DataLoader with multi-process mode is not supported on MacOs and Windows currently." \ + " Please use signle-process mode with num_workers = 0 instead") + num_workers = 0 + self.num_workers = num_workers + + assert prefetch_factor > 0, "prefetch_factor should be a positive value" + + self.use_shared_memory = use_shared_memory + if use_shared_memory and num_workers == 0: + self.use_shared_memory = False + + assert timeout >= 0, "timeout should be a non-negative value" + self.timeout = timeout + + if isinstance(dataset, IterableDataset): + self.dataset_kind = _DatasetKind.ITER + if shuffle: + raise ValueError( + "IterableDataset not support shuffle, but got shuffle={}". + format(shuffle)) + if batch_sampler is not None: + raise ValueError( + "IterableDataset expect unspecified batch_sampler") + else: + self.dataset_kind = _DatasetKind.MAP + + if batch_sampler is not None: + assert batch_size == 1 and not shuffle and not drop_last, \ + "batch_size/shuffle/drop_last should not be set when " \ + "batch_sampler is given" + self.batch_sampler = batch_sampler + self.batch_size = None + elif batch_size is None: + self.batch_sampler = None + self.batch_size = None + else: + assert batch_size > 0, \ + "batch_size should be None or a positive value when " \ + "batch_sampler is not given" + self.batch_size = batch_size + if isinstance(dataset, IterableDataset): + self.batch_sampler = _InfiniteIterableSampler( + dataset, batch_size) + else: + self.batch_sampler = BatchSampler(dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last) + + self.drop_last = drop_last + self.auto_collate_batch = self.batch_sampler is not None + + self.pin_memory = False + if _non_static_mode(): + self.pin_memory = True if use_pinned_memory( + ) is None else use_pinned_memory() + + self._persistent_workers = persistent_workers + self._iterator = None + self.num_workers = AuToTune(self).__call__() + + def __len__(self): + if self.dataset_kind == _DatasetKind.ITER: + raise ValueError("length of IterableDataset not supported") + else: + if self.auto_collate_batch: + return len(self.batch_sampler) + else: + return len(self.dataset) + + def __iter__(self): + if self.num_workers == 0: + return _DataLoaderIterSingleProcess(self) + elif self._persistent_workers: + if self._iterator is None: + self._iterator = _DataLoaderIterMultiProcess(self) + else: + self._iterator._reset() + return self._iterator + else: + return _DataLoaderIterMultiProcess(self) + + def __call__(self): + return self.__iter__() + + @staticmethod + def from_generator(feed_list=None, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=False, + use_multiprocess=False, + drop_last=True): + """ + .. warning:: + This API will be deprecated in the future, it is recommended to use + :code:`paddle.io.DataLoader` which supports multi-processes acceleration. + + .. note:: + **The framework ensures that the data loading order of DataLoader is exactly the same as the user-defined data source.** + + Create a DataLoader object for loading data from Python generator. + Data would be prefetched using Python thread and be pushed + into a queue asynchronously. + + The created DataLoader object provides 3 methods to set the data source + :code:`set_sample_generator` , :code:`set_sample_list_generator` and + :code:`set_batch_generator` . Please see the following example codes + to know their usages. + + If iterable = True, the created DataLoader object is a Python generator + object, which is iterable using for-range loop. + + If iterable = False, the created DataLoader object provides + :code:`start()` and :code:`reset()` method to control the data reading + process. + + Args: + feed_list (list(Tensor)|tuple(Tensor)): feed Tensor list. + The Tensors should be created by :code:`fluid.data()`. + capacity (int): capacity of the queue maintained in DataLoader. + The unit is batch number. Set larger capacity if your reader + is fast. + use_double_buffer (bool): whether to use double_buffer_reader. + If use_double_buffer=True, the DataLoader would prefetch next + batch data asynchronously, so it would speed up data feeding + and occupies a little more CPU or GPU memory, i.e., the memory + of one batch input data. + iterable (bool): whether the created DataLoader is iterable. + return_list (bool): whether the return value on each device is + presented as a list. It is only valid when iterable=True. + If return_list=False, the return value on each device would + be a dict of str -> LoDTensor, where the key of the dict is + the name of each fed Tensors. If return_list=True, the + return value on each device would be a list(LoDTensor). It is + recommended to use return_list=False in static graph mode and + use return_list=True in dygraph mode. + use_multiprocess (bool): whether to use multi-process to speed up + the data loading process in dygraph. Note: this parameter only + can be used in the dygraph mode. In the static graph mode, + whether this parameter is set or not has no effect. + The Default value is False. + drop_last (bool): whether to drop the last batches whose number is + less than the CPU core/GPU card number. The default value is + True. In training phase, users should not set drop_last=False, + because all CPU cores/GPU cards must read data from DataLoader. + In inference phase, users can set drop_last=False, so that the + last batches whose number is less than the CPU core/GPU card + number can be tested. + + Returns: + loader (DataLoader): the created DataLoader object. + + Examples 1: + + .. code-block:: python + + ''' + Example in static graph mode + ''' + import numpy as np + + import paddle + import paddle.static as static + import paddle.nn.functional as F + + + BATCH_NUM = 10 + BATCH_SIZE = 16 + EPOCH_NUM = 4 + + CLASS_NUM = 10 + + ITERABLE = True # whether the created DataLoader object is iterable + USE_GPU = False # whether to use GPU + + DATA_FORMAT = 'batch_generator' # data format of data source user provides + + paddle.enable_static() + + def simple_net(image, label): + fc_tmp = static.nn.fc(image, size=CLASS_NUM) + cross_entropy = F.softmax_with_cross_entropy(image, label) + loss = paddle.mean(cross_entropy) + sgd = paddle.optimizer.SGD(learning_rate=1e-3) + sgd.minimize(loss) + return loss + + def get_random_images_and_labels(image_shape, label_shape): + image = np.random.random(size=image_shape).astype('float32') + label = np.random.random(size=label_shape).astype('int64') + return image, label + + # If the data generator yields one sample each time, + # use DataLoader.set_sample_generator to set the data source. + def sample_generator_creator(): + def __reader__(): + for _ in range(BATCH_NUM * BATCH_SIZE): + image, label = get_random_images_and_labels([784], [1]) + yield image, label + + return __reader__ + + # If the data generator yield list of samples each time, + # use DataLoader.set_sample_list_generator to set the data source. + def sample_list_generator_creator(): + def __reader__(): + for _ in range(BATCH_NUM): + sample_list = [] + for _ in range(BATCH_SIZE): + image, label = get_random_images_and_labels([784], [1]) + sample_list.append([image, label]) + + yield sample_list + + return __reader__ + + # If the data generator yields a batch each time, + # use DataLoader.set_batch_generator to set the data source. + def batch_generator_creator(): + def __reader__(): + for _ in range(BATCH_NUM): + batch_image, batch_label = get_random_images_and_labels([BATCH_SIZE, 784], [BATCH_SIZE, 1]) + yield batch_image, batch_label + + return __reader__ + + # If DataLoader is iterable, use for loop to train the network + def train_iterable(exe, prog, loss, loader): + for _ in range(EPOCH_NUM): + for data in loader(): + exe.run(prog, feed=data, fetch_list=[loss]) + + # If DataLoader is not iterable, use start() and reset() method to control the process + def train_non_iterable(exe, prog, loss, loader): + for _ in range(EPOCH_NUM): + loader.start() # call DataLoader.start() before each epoch starts + try: + while True: + exe.run(prog, fetch_list=[loss]) + except paddle.core.EOFException: + loader.reset() # call DataLoader.reset() after catching EOFException + + def set_data_source(loader, places): + if DATA_FORMAT == 'sample_generator': + loader.set_sample_generator(sample_generator_creator(), batch_size=BATCH_SIZE, drop_last=True, places=places) + elif DATA_FORMAT == 'sample_list_generator': + loader.set_sample_list_generator(sample_list_generator_creator(), places=places) + elif DATA_FORMAT == 'batch_generator': + loader.set_batch_generator(batch_generator_creator(), places=places) + else: + raise ValueError('Unsupported data format') + + image = static.data(name='image', shape=[None, 784], dtype='float32') + label = static.data(name='label', shape=[None, 1], dtype='int64') + + # Define DataLoader + loader = paddle.io.DataLoader.from_generator(feed_list=[image, label], capacity=16, iterable=ITERABLE) + + # Define network + loss = simple_net(image, label) + + # Set data source of DataLoader + # + # If DataLoader is iterable, places must be given and the number of places must be the same with device number. + # - If you are using GPU, call `paddle.static.cuda_places()` to get all GPU places. + # - If you are using CPU, call `paddle.static.cpu_places()` to get all CPU places. + # + # If DataLoader is not iterable, places can be None. + places = static.cuda_places() if USE_GPU else static.cpu_places() + set_data_source(loader, places) + + exe = static.Executor(places[0]) + exe.run(static.default_startup_program()) + + prog = static.CompiledProgram(static.default_main_program()).with_data_parallel(loss_name=loss.name) + + if loader.iterable: + train_iterable(exe, prog, loss, loader) + else: + train_non_iterable(exe, prog, loss, loader) + + + Examples 2: + + .. code-block:: python + + ''' + Example in dynamic graph mode. + ''' + import numpy as np + + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + import paddle.distributed as dist + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + USE_GPU = False # whether to use GPU + + def _get_random_images_and_labels(image_shape, label_shape): + image = np.random.random(size=image_shape).astype('float32') + label = np.random.random(size=label_shape).astype('int64') + return image, label + + def __reader__(): + for _ in range(BATCH_NUM): + batch_image, batch_label = _get_random_images_and_labels( + [BATCH_SIZE, IMAGE_SIZE], [BATCH_SIZE, CLASS_NUM]) + yield batch_image, batch_label + + def random_batch_reader(): + return __reader__ + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + # set device + paddle.set_device('gpu' if USE_GPU else 'cpu') + + # create network + layer = LinearNet() + dp_layer = paddle.DataParallel(layer) + loss_fn = nn.CrossEntropyLoss() + adam = opt.Adam(learning_rate=0.001, parameters=dp_layer.parameters()) + + # create data loader + loader = paddle.io.DataLoader.from_generator(capacity=5) + loader.set_batch_generator(random_batch_reader()) + + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + + loss.backward() + + adam.step() + adam.clear_grad() + print("Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + Examples 3: + + .. code-block:: python + + ''' + Example of `drop_last` using in static graph multi-cards mode + ''' + import paddle + import paddle.static as static + import numpy as np + import os + + # We use 2 CPU cores to run inference network + os.environ['CPU_NUM'] = '2' + + paddle.enable_static() + + # The data source has only 3 batches, which can not be + # divided evenly to each CPU core + def batch_generator(): + for i in range(3): + yield np.array([i+1]).astype('float32'), + + x = static.data(name='x', shape=[None], dtype='float32') + y = x * x + + def run_inference(drop_last): + loader = paddle.io.DataLoader.from_generator(feed_list=[x], + capacity=8, drop_last=drop_last) + loader.set_batch_generator(batch_generator, static.cpu_places()) + + exe = static.Executor(paddle.CPUPlace()) + prog = static.CompiledProgram(static.default_main_program()) + prog = prog.with_data_parallel() + + result = [] + for data in loader(): + each_ret, = exe.run(prog, feed=data, fetch_list=[y]) + result.extend(each_ret) + return result + + # Set drop_last to True, so that the last batch whose + # number is less than CPU core number would be discarded. + print(run_inference(drop_last=True)) # [1.0, 4.0] + + # Set drop_last to False, so that the last batch whose + # number is less than CPU core number can be tested. + print(run_inference(drop_last=False)) # [1.0, 4.0, 9.0] + """ + if _non_static_mode(): + return DygraphGeneratorLoader(feed_list, capacity, + use_double_buffer, iterable, + return_list, use_multiprocess) + else: + return GeneratorLoader(feed_list, capacity, use_double_buffer, + iterable, return_list, drop_last) + + @staticmethod + def from_dataset(dataset, places, drop_last=True): + """ + .. warning:: + This API will be deprecated in the future, it is recommended to use + :code:`paddle.io.DataLoader` which supports multi-processes acceleration. + + Create an iterable DataLoader object for loading data from Dataset. + Dataset is only supported in Linux system currently. + + Args: + dataset (InMemoryDataset|QueueDataset): the dataset object. + places (list(CUDAPlace)|list(CPUPlace)|list(str)): places where the result + data should be converted. If places is list of string, the string in the list + can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where x is the index of the GPUs. + drop_last (bool): whether to drop the last batch whose sample + number is less than batch size. If drop_last = True, they + would be dropped. If drop_last = False, they would be kept. + + Returns: + loader (DataLoader): the created DataLoader object, which can be + treated as a Python generator. + + Examples: + + .. code-block:: python + + import paddle + import paddle.static as static + + paddle.enable_static() + + image = static.data(name='image', shape=[None, 784], dtype='float32') + label = static.data(name='label', shape=[None, 1], dtype='int64') + + dataset = paddle.distributed.QueueDataset() + dataset.init( + batch_size=32, + pipe_command='cat', + use_var=[image, label]) + dataset.set_filelist(['a.txt', 'b.txt', 'c.txt']) + + loader = paddle.io.DataLoader.from_dataset(dataset, static.cpu_places()) + """ + return DatasetLoader(dataset, places, drop_last) + + +class DygraphGeneratorLoader(DataLoaderBase): + """ + The GeneratorLoader of dygraph + + The multiprocess dygraph GeneratorLoader's most functions are different from + static graph GeneratorLoader, Separate implementation to keep code readable. + """ + + def __init__(self, + feed_list=None, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=True, + use_multiprocess=False): + self._batch_reader = None + self._places = None + self._feed_list = feed_list + + if not capacity: + raise ValueError("Please give value to capacity.") + self._capacity = capacity + self._use_double_buffer = use_double_buffer + + if not iterable: + warnings.warn( + "Please NOTE: DygraphGeneratorLoader supports iterable mode only. Change to iterable mode." + ) + self._iterable = True + if not return_list: + warnings.warn( + "Please NOTE: DygraphGeneratorLoader supports returning as list only. Change to return as list." + ) + self._return_list = True + + # NOTE: the multiprocessing in different platform is incompatible, we will solve it later + self._use_multiprocess = use_multiprocess + if self._use_multiprocess and (sys.platform == 'darwin' + or sys.platform == 'win32'): + warnings.warn( + "NOTE: DygraphGeneratorLoader with multiprocess mode is not currently supported on MacOs and Windows." + ) + self._use_multiprocess = False + + if self._use_multiprocess: + # NOTE: the multiprocessing.Queue used to save loading data in self._process + self._data_queue = None + # NOTE: this process is used to load data asynchronously from self._batch_reader + self._process = None + + # NOTE: the C++ LoDTensorBlockingQueue instance + self._blocking_queue = None + # NOTE: 1. In multiprocess mode, this thread is used to get next batch data from + # self._data_queue, then push it into self._blocking_queue; 2. In singleprocess + # mode, this thread is used to get next batch data from self._batch_reader, then + # push it into self._blocking_queue + self._thread = None + self._pin_memory = True if use_pinned_memory( + ) is None else use_pinned_memory() + + @property + def queue(self): + return self._blocking_queue + + @property + def iterable(self): + return self._iterable + + def _clear_and_remove_data_queue(self): + if self._data_queue is not None: + while True: + try: + self._data_queue.get_nowait() + except queue.Empty: + break + global multiprocess_queue_set + multiprocess_queue_set.remove(self._data_queue) + + def _wait_thread_ends(self): + thread = self._thread + if thread is not None: + self._blocking_queue.close() + thread.join() + + def _wait_process_ends(self): + process = self._process + if process is not None: + process.join() + # erase process id + core._erase_process_pids(id(self)) + + def _init_iterable(self): + self._wait_thread_ends() + if self._use_multiprocess: + self._wait_process_ends() + self._var_names = [] + self._shapes = [] + self._dtypes = [] + self._need_check_feed = [] + self._blocking_queue = core.init_lod_tensor_blocking_queue( + core.Variable(), self._capacity, False) + self._reader = None + self._reader = core.create_py_reader(self.queue, self._var_names, + self._shapes, self._dtypes, + self._need_check_feed, + self._places, + self._use_double_buffer, True, + self._pin_memory) + + def _start(self): + if self._use_multiprocess: + # clear old _data_queue and remove it from multiprocess_queue_set + self._clear_and_remove_data_queue() + # set data_queue and process + self._data_queue = multiprocessing.Queue(self._capacity) + # add _data_queue into global queue set + global multiprocess_queue_set + multiprocess_queue_set.add(self._data_queue) + self._process = multiprocessing.Process(target=_reader_process_loop, + args=(self._batch_reader, + self._data_queue)) + self._process.daemon = True + self._process.start() + + # Set child process signal handler + # NOTE: [ avoiding hang ] 1. if the child process dies due to bus error/segfault + # or just hang, the main process will hang waiting for data, so here need to deal + # with SIGSEGV and SIGBUS of child process; 2. if the main process end before child + # process, it shuts the all its daemonic children down with a SIGTERM (instead of + # joining them without a timeout), so here nedd to deal with SIGTERM. + core._set_process_pids(id(self), [self._process.pid]) + _set_SIGCHLD_handler() + + # Set reader_thread + self._thread_done_event = threading.Event() + self._thread = threading.Thread( + target=self._reader_thread_loop_for_multiprocess, + args=(_current_expected_place(), )) + self._thread.daemon = True + self._thread.start() + else: + self._thread = threading.Thread( + target=self._reader_thread_loop_for_singleprocess, + args=(_current_expected_place(), )) + self._thread.daemon = True + self._thread.start() + + def _reset(self): + self._reader.reset() + self._wait_thread_ends() + if self._use_multiprocess: + self._wait_process_ends() + + def __iter__(self): + assert self.iterable, "DataLoader is not iterable" + assert self._batch_reader is not None, \ + "Data source of DataLoader has not set yet" + + self._init_iterable() + self._start() + return self + + def __next__(self): + try: + if _in_eager_without_dygraph_check(): + return core.eager.read_next_tensor_list( + self._reader.read_next_list()[0]) + else: + return self._reader.read_next_var_list() + except StopIteration: + self._reset() + six.reraise(*sys.exc_info()) + + def _exit_thread_expectedly(self): + self._thread_done_event.set() + self._blocking_queue.close() + + def _exit_thread_unexpectedly(self): + self._thread_done_event.set() + self._blocking_queue.kill() + logging.error("DataLoader reader thread raised an exception!") + + def _reader_thread_loop_for_multiprocess(self, legacy_expected_place): + # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here. + _set_expected_place(legacy_expected_place) + + while not self._thread_done_event.is_set(): + try: + # NOTE: [ avoid hanging ] Even with carefully designed data dependencies + # (i.e., a put() always corresponding to a get()), hanging on get() can + # still happen when data in queue is corrupted (e.g., due to + # Queue.cancel_join_thread or unexpected exit). So we set a timeout whenever + # we try to get data from `data_queue` + # NOTE: [ avoid failed quickly ] Here, the time setting of QUEUE_GET_TIMEOUT + # is relatively long, currently it is 60 seconds, because in some models, + # if the reader child process starts with a heavy burden, the child process + # has no enough time to put the data in the queue when the main process + # start trying to get data from queue. At this time, the child thread needs + # to wait slightly longer + tensor_list = self._data_queue.get(timeout=QUEUE_GET_TIMEOUT) + except: + # NOTE [ avoid handing ] After adding the shared memory mechanism, not only + # the queue.Empty exception will occur here, but other exceptions will also + # occur, such as mmap failure. If it is not handled here, it will hang. + self._exit_thread_unexpectedly() + logging.error( + "DataLoader reader thread failed to read data from the multiprocessing.Queue." + ) + six.reraise(*sys.exc_info()) + + if not self._thread_done_event.is_set(): + if tensor_list is not None: + try: + array = core.LoDTensorArray() + for tensor in tensor_list: + array.append(tensor) + if not self._blocking_queue.push(array): + self._blocking_queue.close() + except: + self._exit_thread_unexpectedly() + six.reraise(*sys.exc_info()) + else: + self._exit_thread_expectedly() + + def _reader_thread_loop_for_singleprocess(self, legacy_expected_place): + try: + # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here. + _set_expected_place(legacy_expected_place) + + for sample in self._batch_reader(): + array = core.LoDTensorArray() + for item in sample: + if not isinstance(item, core.LoDTensor): + item = self._check_input_array(item) + tmp = core.LoDTensor() + tmp.set(item, core.CPUPlace()) + item = tmp + + array.append(item) + + if not self._blocking_queue.push(array): + break + + self._blocking_queue.close() + self._thread = None + except Exception: + self._blocking_queue.kill() + self._thread = None + logging.warning( + "DygraphDataLoader reader thread raised an exception.") + six.reraise(*sys.exc_info()) + + def set_sample_generator(self, + reader, + batch_size, + drop_last=True, + places=None): + assert batch_size > 0, "batch_size must be larger than 0" + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + self.set_sample_list_generator(paddle.batch(reader, + batch_size=batch_size, + drop_last=drop_last), + places=places) + return self + + def set_sample_list_generator(self, reader, places=None): + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + + def __batch_reader_impl__(): + for batch in reader(): + slots = [] + for items in batch: + for i, item in enumerate(items): + if len(slots) < len(items): + slots.append([item]) + else: + slots[i].append(item) + yield slots + + self.set_batch_generator(__batch_reader_impl__, places) + return self + + def set_batch_generator(self, reader, places=None): + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + self._batch_reader = reader + if places is None: + places = _current_expected_place() + self._places = _convert_places(places) + assert len(self._places) == 1, \ + "Number of places must be 1 in imperative mode" + return self + + +class GeneratorLoader(DataLoaderBase): + + def __init__(self, + feed_list=None, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=False, + drop_last=True): + self._tensor_reader = None + self._places = None + self._thread = None + self._queue = None + self._feed_list = feed_list + self._exited = False + self._drop_last = drop_last + self._keep_order = keep_data_loader_order() + if not capacity: + raise ValueError("Please give value to capacity.") + self._iterable = iterable + self._return_list = return_list + if not self._feed_list: + raise Exception("Feed list must be given under static mode.") + self._use_double_buffer = use_double_buffer + self._capacity = capacity + if not self._iterable: + self._init_non_iterable() + + def _wait_thread_ends(self): + # Get self._thread first to prevent data race, because __thread_main__ + # would set self._thread be None at the end + thread = self._thread + if thread is not None and self._iterable: + self._queue.close() + thread.join() + + def _init_iterable(self): + self._wait_thread_ends() + self._var_names = [v.name for v in self._feed_list] + self._shapes = [v.shape for v in self._feed_list] + self._dtypes = [v.dtype for v in self._feed_list] + self._need_check_feed = [ + v.desc.need_check_feed() for v in self._feed_list + ] + self._queue = core.init_lod_tensor_blocking_queue( + core.Variable(), self._capacity, self._keep_order) + self._reader = None + self._reader = core.create_py_reader(self.queue, self._var_names, + self._shapes, self._dtypes, + self._need_check_feed, + self._places, + self._use_double_buffer, + self._drop_last, False) + + def _init_non_iterable(self): + lod_levels = [] + dtypes = [] + shape_concat = [] + ranks = [] + shapes = [] + need_check_feed = [] + + for feed_data in self._feed_list: + dtypes.append(feed_data.dtype) + shape_concat.extend(feed_data.shape) + ranks.append(len(feed_data.shape)) + shapes.append(feed_data.shape) + lod_levels.append(feed_data.lod_level) + need_check_feed.append(int(feed_data.desc.need_check_feed())) + + queue_name = data_loader_unique_name_generator( + 'lod_tensor_blocking_queue') + reader_name = data_loader_unique_name_generator('create_py_reader') + double_buffer_name = data_loader_unique_name_generator('double_buffer') + + var = global_scope().var(queue_name) + self._queue = core.init_lod_tensor_blocking_queue( + var, self._capacity, self._keep_order) + + if self._keep_order: + block = default_main_program().current_block() + else: + block = default_startup_program().current_block() + + reader_var = block.create_var(name=reader_name) + + dtype_int = [int(t) for t in dtypes] + block.append_op(type='create_py_reader', + inputs={'blocking_queue': [queue_name]}, + outputs={'Out': [reader_var]}, + attrs={ + 'shape_concat': shape_concat, + 'lod_levels': lod_levels, + 'dtypes': dtype_int, + 'need_check_feed': need_check_feed, + 'ranks': ranks + }) + + reader_var.desc.set_dtypes(dtypes) + reader_var.persistable = True + reader_var.stop_gradient = True + + if self._keep_order: + main_prog_var = reader_var + reader = main_prog_var + reader.reset = self._queue.reset + else: + main_prog_var = _copy_reader_var_( + default_main_program().current_block(), reader_var) + + main_prog_var.stop_gradient = True + main_prog_var.persistable = True + + reader = monkey_patch_reader_methods(main_prog_var) + + if self._use_double_buffer: + double_buffer_reader = double_buffer(reader, + name=double_buffer_name) + # we return a double buffer reader. However, the reset method comes from + # py_reader. + double_buffer_reader.reset = reader.reset + reader = double_buffer_reader + + self._reader = reader + + default_main_program().current_block().append_op( + type='read', + inputs={'Reader': [self._reader]}, + outputs={'Out': self._feed_list}, + attrs={'drop_last': self._drop_last}) + + @property + def queue(self): + return self._queue + + @property + def iterable(self): + return self._iterable + + def __iter__(self): + assert self.iterable, "DataLoader is not iterable" + assert self._tensor_reader is not None, \ + "Data source of DataLoader has not set yet" + + self._init_iterable() + self._start() + return self + + def __next__(self): + try: + if self._return_list: + data = self._reader.read_next_list() + for i in range(len(data)): + data[i] = data[i]._move_to_list() + return data + else: + return self._reader.read_next() + except StopIteration: + self._queue.close() + self._reset() + six.reraise(*sys.exc_info()) + + def start(self): + assert not self._iterable, "start() cannot be called when DataLoader is iterable" + self._start() + + def reset(self): + assert not self._iterable, "reset() cannot be called when DataLoader is iterable" + self._reset() + + def _start(self): + + def __thread_main__(legacy_expected_place): + try: + # See _DataLoaderIterSingleProcess._thread_loop() for why set expected place here. + _set_expected_place(legacy_expected_place) + + while not self._queue.wait_for_inited(1): + if self._exited: + return + + for tensors in self._tensor_reader(): + array = core.LoDTensorArray() + for item in tensors: + if not isinstance(item, core.LoDTensor): + item = self._check_input_array(item) + tmp = core.LoDTensor() + tmp.set(item, core.CPUPlace()) + item = tmp + + array.append(item) + + if not self._queue.push(array): + break + + self._queue.close() + self._thread = None + except Exception as ex: + self._queue.kill() + self._thread = None + logging.warning('Your reader has raised an exception!') + six.reraise(*sys.exc_info()) + + self._thread = threading.Thread(target=__thread_main__, + args=(_current_expected_place(), )) + self._thread.daemon = True + self._thread.start() + + def _reset(self): + self._queue.close() + self._exited = True + thread = self._thread + if thread is not None: + thread.join() + + self._exited = False + self._reader.reset() + + def set_sample_generator(self, + reader, + batch_size, + drop_last=True, + places=None): + assert batch_size > 0, "batch_size must be larger than 0" + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + has_lod = False + for f in self._feed_list: + if f.lod_level != 0: + has_lod = True + break + + if has_lod: + self.set_sample_list_generator(paddle.batch(reader, + batch_size=batch_size, + drop_last=drop_last), + places=places) + else: + reader = BatchedTensorProvider(feed_list=self._feed_list, + place=core.CPUPlace(), + batch_size=batch_size, + generator=reader, + drop_last=drop_last) + self.set_batch_generator(reader, places=places) + return self + + def set_sample_list_generator(self, reader, places=None): + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + with program_guard(Program(), Program()): + feeder = DataFeeder(feed_list=self._feed_list, + place=core.CPUPlace()) + paddle_reader = feeder.decorate_reader(reader, multi_devices=False) + + def __tensor_reader_impl__(): + for slots in paddle_reader(): + yield [slots[var.name] for var in self._feed_list] + + self.set_batch_generator(__tensor_reader_impl__, places) + return self + + def set_batch_generator(self, reader, places=None): + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + self._tensor_reader = reader + if self._iterable: + assert places is not None, "Places cannot be None when DataLoader is iterable" + self._places = _convert_places(places) + else: + if places is not None: + logging.info( + 'places would be ommited when DataLoader is not iterable') + return self + + +class PyReader(DataLoaderBase): + r""" + Create a reader object for data feeding in Python. + Data would be prefetched using Python thread and be pushed + into a queue asynchronously. Data in the queue would be extracted + automatically when `Executor.run(...)` is called. + + Args: + feed_list (list(Variable)|tuple(Variable)): feed variable list. + The variables should be created by :code:`fluid.layers.data()`. + capacity (int): capacity of the queue maintained in PyReader. + The unit is batch number. Set larger capacity if your reader + is fast. + use_double_buffer (bool): whether to use double_buffer_reader. + If use_double_buffer=True, PyReader would prefetch next + batch data asynchronously, so it would speed up data feeding + and occupies a little more CPU or GPU memory, i.e., the memory + of one batch input data. + iterable (bool): whether the created PyReader is iterable. + return_list (bool): whether the return value on each device is + presented as a list. It is only valid when iterable=True. + If return_list=False, the return value on each device would + be a dict of str -> LoDTensor, where the key of the dict is + the name of each fed variables. If return_list=True, the + return value on each device would be a list(LoDTensor). It is + recommended to use return_list=False in static graph mode and + use return_list=True in dygraph mode. + + Returns: + the created reader object. + + Return type: + reader(Reader) + + Examples: + 1. If iterable = False, the created PyReader object is almost the + same as :code:`fluid.layers.py_reader()`. Operators would be + inserted into the program. User should call :code:`start()` + before each epoch and catch :code:`fluid.core.EOFException` + thrown by :code:`Executor.run()` when epoch ends. Once the + exception is caught, user should call :code:`reset()` to reset + the reader manually. + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + EPOCH_NUM = 3 + ITER_NUM = 5 + BATCH_SIZE = 3 + + def network(image, label): + # User-defined network, here is an example of softmax regression. + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + def reader_creator_random_image_and_label(height, width): + def reader(): + for i in range(ITER_NUM): + fake_image = np.random.uniform(low=0, + high=255, + size=[height, width]) + fake_label = np.ones([1]) + yield fake_image, fake_label + return reader + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + + reader = fluid.io.PyReader(feed_list=[image, label], + capacity=4, + iterable=False) + + user_defined_reader = reader_creator_random_image_and_label(784, 784) + reader.decorate_sample_list_generator( + paddle.batch(user_defined_reader, batch_size=BATCH_SIZE)) + loss = network(image, label) + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + for i in range(EPOCH_NUM): + reader.start() + while True: + try: + executor.run(feed=None) + except fluid.core.EOFException: + reader.reset() + break + + + 2. If iterable=True, the created PyReader object is decoupled with + the program. No operator would be inserted into the program. + In this case, the created reader is a Python generator, which + is iterable. User should feed the data yielded from PyReader + object into :code:`Executor.run(feed=...)`. + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + EPOCH_NUM = 3 + ITER_NUM = 5 + BATCH_SIZE = 10 + + def network(image, label): + # User-defined network, here is an example of softmax regression. + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + def reader_creator_random_image(height, width): + def reader(): + for i in range(ITER_NUM): + fake_image = np.random.uniform(low=0, high=255, size=[height, width]) + fake_label = np.ones([1]) + yield fake_image, fake_label + return reader + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True, return_list=False) + + user_defined_reader = reader_creator_random_image(784, 784) + reader.decorate_sample_list_generator( + paddle.batch(user_defined_reader, batch_size=BATCH_SIZE), + fluid.core.CPUPlace()) + + loss = network(image, label) + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + + for _ in range(EPOCH_NUM): + for data in reader(): + executor.run(feed=data, fetch_list=[loss]) + + + 3. If return_list=True, the return values would be presented as list instead of dict. + This is usually used in dygraph mode. + + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + ITER_NUM = 5 + BATCH_SIZE = 10 + + def reader_creator_random_image(height, width): + def reader(): + for i in range(ITER_NUM): + yield np.random.uniform(low=0, high=255, size=[height, width]), \ + np.random.random_integers(low=0, high=9, size=[1]) + return reader + + place = fluid.CPUPlace() + with fluid.dygraph.guard(place): + py_reader = fluid.io.PyReader(capacity=2, return_list=True) + user_defined_reader = reader_creator_random_image(784, 784) + py_reader.decorate_sample_list_generator( + paddle.batch(user_defined_reader, batch_size=BATCH_SIZE), + place) + for image, label in py_reader(): + relu = fluid.layers.relu(image) + """ + + def __init__(self, + feed_list=None, + capacity=None, + use_double_buffer=True, + iterable=True, + return_list=False): + self._loader = DataLoader.from_generator(feed_list, capacity, + use_double_buffer, iterable, + return_list) + + @property + def queue(self): + return self._loader.queue + + @property + def iterable(self): + return self._loader.iterable + + def __iter__(self): + return self._loader.__iter__() + + def __next__(self): + return self._loader.__next__() + + def start(self): + ''' + Start the data feeding thread. + Can only call when the reader object is not iterable. + + Example: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + BATCH_SIZE = 10 + + def generator(): + for i in range(5): + yield np.random.uniform(low=0, high=255, size=[784, 784]), + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False) + reader.decorate_sample_list_generator( + paddle.batch(generator, batch_size=BATCH_SIZE)) + + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + for i in range(3): + reader.start() + while True: + try: + executor.run(feed=None) + except fluid.core.EOFException: + reader.reset() + break + + ''' + self._loader.start() + + def reset(self): + ''' + Reset the reader object when :code:`fluid.core.EOFException` raises. + Can only call when the reader object is not iterable. + + Example: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + BATCH_SIZE = 10 + + def generator(): + for i in range(5): + yield np.random.uniform(low=0, high=255, size=[784, 784]), + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False) + reader.decorate_sample_list_generator( + paddle.batch(generator, batch_size=BATCH_SIZE)) + + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + for i in range(3): + reader.start() + while True: + try: + executor.run(feed=None) + except fluid.core.EOFException: + reader.reset() + break + + ''' + self._loader.reset() + + def decorate_sample_generator(self, + sample_generator, + batch_size, + drop_last=True, + places=None): + ''' + Set the data source of the PyReader object. + + The provided :code:`sample_generator` should be a Python generator, + which yields list(numpy.ndarray)-typed data of each sample. + + :code:`places` must be set when the PyReader object is iterable. + + If all inputs have no lods, this method is faster than + :code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` . + + Args: + sample_generator (generator): Python generator that yields + list(numpy.ndarray)-typed sample data. + batch_size (int): batch size. Must be larger than 0. + drop_last (bool): Whether to drop the last batch when sample number + is less than batch_size. + places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must + be provided when PyReader is iterable. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + EPOCH_NUM = 3 + ITER_NUM = 15 + BATCH_SIZE = 3 + + def network(image, label): + # User-defined network, here is an example of softmax regression. + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + def random_image_and_label_generator(height, width): + def generator(): + for i in range(ITER_NUM): + fake_image = np.random.uniform(low=0, + high=255, + size=[height, width]) + fake_label = np.array([1]) + yield fake_image, fake_label + return generator + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True) + + user_defined_generator = random_image_and_label_generator(784, 784) + reader.decorate_sample_generator(user_defined_generator, + batch_size=BATCH_SIZE, + places=[fluid.CPUPlace()]) + loss = network(image, label) + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + + for _ in range(EPOCH_NUM): + for data in reader(): + executor.run(feed=data, fetch_list=[loss]) + + ''' + self._loader.set_sample_generator(sample_generator, batch_size, + drop_last, places) + + def decorate_sample_list_generator(self, reader, places=None): + ''' + Set the data source of the PyReader object. + + The provided :code:`reader` should be a Python generator, + which yields list(numpy.ndarray) typed batched data. + + :code:`places` must be set when the PyReader object is iterable. + + Args: + reader (generator): Python generator that yields + list(numpy.ndarray)-typed batched data. + places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must + be provided when PyReader is iterable. + + Example: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + import numpy as np + + EPOCH_NUM = 3 + ITER_NUM = 15 + BATCH_SIZE = 3 + + def network(image, label): + # User-defined network, here is an example of softmax regression. + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + def random_image_and_label_generator(height, width): + def generator(): + for i in range(ITER_NUM): + fake_image = np.random.uniform(low=0, + high=255, + size=[height, width]) + fake_label = np.ones([1]) + yield fake_image, fake_label + return generator + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True) + + user_defined_generator = random_image_and_label_generator(784, 784) + reader.decorate_sample_list_generator( + paddle.batch(user_defined_generator, batch_size=BATCH_SIZE), + fluid.core.CPUPlace()) + + loss = network(image, label) + executor = fluid.Executor(fluid.core.CPUPlace()) + executor.run(fluid.default_startup_program()) + + for _ in range(EPOCH_NUM): + for data in reader(): + executor.run(feed=data, fetch_list=[loss]) + + ''' + self._loader.set_sample_list_generator(reader, places) + + def decorate_batch_generator(self, reader, places=None): + ''' + Set the data source of the PyReader object. + + The provided :code:`reader` should be a Python generator, + which yields numpy.ndarray-typed or LoDTensor-typed batched data. + + :code:`places` must be set when the PyReader object is iterable. + + Args: + reader (generator): Python generator that yields LoDTensor-typed + batched data. + places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must + be provided when PyReader is iterable. + + Example: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + + EPOCH_NUM = 3 + ITER_NUM = 15 + BATCH_SIZE = 3 + + def network(image, label): + # User-defined network, here is an example of softmax regression. + predict = fluid.layers.fc(input=image, size=10, act='softmax') + return fluid.layers.cross_entropy(input=predict, label=label) + + def random_image_and_label_generator(height, width): + def generator(): + for i in range(ITER_NUM): + batch_image = np.random.uniform(low=0, + high=255, + size=[BATCH_SIZE, height, width]) + batch_label = np.ones([BATCH_SIZE, 1]) + batch_image = batch_image.astype('float32') + batch_label = batch_label.astype('int64') + yield batch_image, batch_label + return generator + + image = fluid.data(name='image', shape=[None, 784, 784], dtype='float32') + label = fluid.data(name='label', shape=[None, 1], dtype='int64') + reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True) + + user_defined_generator = random_image_and_label_generator(784, 784) + reader.decorate_batch_generator(user_defined_generator, fluid.CPUPlace()) + + loss = network(image, label) + executor = fluid.Executor(fluid.CPUPlace()) + executor.run(fluid.default_startup_program()) + + for _ in range(EPOCH_NUM): + for data in reader(): + executor.run(feed=data, fetch_list=[loss]) + + ''' + self._loader.set_batch_generator(reader, places) + + +class DatasetLoader(DataLoaderBase): + + def __init__(self, dataset, places, drop_last): + assert isinstance(dataset, paddle.distributed.fleet.dataset.DatasetBase + ), "dataset must be type of DatasetBase" + assert not _non_static_mode( + ), "DatasetLoader is not supported in dygraph mode yet" + if isinstance(places, (list, tuple)): + places = _get_paddle_place_list(places) + else: + places = _get_paddle_place(places) + + thread_num = len(places) + + assert len(dataset.filelist) >= thread_num, \ + "Filelist number of dataset {} must be not less than place number {}".format(len(dataset.filelist), thread_num) + + if dataset.thread_num != 0 and dataset.thread_num != thread_num: + logging.warn( + 'thread_num {} which is set in Dataset is ignored'.format( + dataset.thread_num)) + + dataset._set_thread(thread_num) + + if isinstance(dataset, paddle.distributed.fleet.dataset.InMemoryDataset + ) and dataset.queue_num > thread_num: + logging.warn( + "queue_num {} which is set in Dataset is ignored".format( + dataset.queue_num)) + dataset._set_queue_num(thread_num) + + self._dataset = dataset + use_slots = [ + slot.name for slot in dataset.proto_desc.multi_slot_desc.slots + if slot.is_used + ] + + self._iterable_dataset = core.IterableDatasetWrapper( + dataset.dataset, use_slots, _convert_places(places), + dataset.proto_desc.batch_size, drop_last) + + def __iter__(self): + self._dataset._finish_to_run() + self._dataset._prepare_to_run() + self._iterable_dataset._start() + return self + + def __next__(self): + return self._iterable_dataset._next() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/regularizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/regularizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7b3558753de8b8a41862ee1324b341a6b21d83 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/regularizer.py @@ -0,0 +1,284 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +import logging + +from . import framework +from .framework import _non_static_mode, _varbase_creator, in_dygraph_mode +from . import core +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['L1Decay', 'L2Decay', 'L1DecayRegularizer', 'L2DecayRegularizer'] + + +class WeightDecayRegularizer(object): + """Base class for weight decay regularizers + + Defines the common interface of weight-decay regularizers. + Weight-decay regularizers are added only during the backward + pass for faster regularization. They add operations to the network + that correspond to gradient of the regularization function. + Users should not use this class directly, but need to use one + of its implementations + """ + + def __init__(self): + pass + + def __call__(self, param, grad, block): + """Add corresponding weight decay operations to the network + """ + raise NotImplementedError() + + def __str__(self): + """Debug string + """ + raise NotImplementedError() + + +class L2DecayRegularizer(WeightDecayRegularizer): + r""" + Implement the L2 Weight Decay Regularization, which helps to prevent the model over-fitting. + + It can be set in :ref:`api_fluid_ParamAttr` or ``optimizer`` (such as :ref:`api_fluid_optimizer_SGDOptimizer` ). + When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in + ``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has + higher priority than ``optimizer`` . + + In the implementation, the formula of L2 Weight Decay Regularization is as follows: + + .. math:: + + L2WeightDecay = reg\_coeff * parameter + + Args: + regularization_coeff(float, optional): regularization coeff. Default:0.0 + + Examples: + .. code-block:: python + + # Example1: set Regularizer in optimizer + import paddle.fluid as fluid + + main_prog = fluid.Program() + startup_prog = fluid.Program() + with fluid.program_guard(main_prog, startup_prog): + data = fluid.layers.data(name='image', shape=[3, 28, 28], dtype='float32') + label = fluid.layers.data(name='label', shape=[1], dtype='int64') + hidden = fluid.layers.fc(input=data, size=128, act='relu') + prediction = fluid.layers.fc(input=hidden, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=prediction, label=label) + avg_loss = fluid.layers.mean(loss) + optimizer = fluid.optimizer.Adagrad( + learning_rate=1e-4, + regularization=fluid.regularizer.L2Decay( + regularization_coeff=0.1)) + optimizer.minimize(avg_loss) + + + # Example2: set Regularizer both in ParamAttr and optimizer + import paddle.fluid as fluid + + l1 = fluid.regularizer.L1Decay(regularization_coeff=0.1) + l2 = fluid.regularizer.L2Decay(regularization_coeff=0.1) + x = fluid.layers.uniform_random([3,4]) + + # set L1 regularization in fluid.ParamAttr + w_param = fluid.ParamAttr(regularizer=l1) + hidden1 = fluid.layers.fc(x, 8, param_attr=w_param) # fc_0.w_0(L1), fc_0.b_0 + hidden2 = fluid.layers.fc(hidden1, 16, param_attr=w_param) # fc_1.w_0(L1), fc_1.b_0 + predict = fluid.layers.fc(hidden2, 32) # fc_3.w_0, fc_3.b_0 + avg_loss = fluid.layers.mean(predict) + + # set L2 regularization in optimizer + optimizer = fluid.optimizer.SGD(learning_rate=1e-4, regularization=l2) + optimizer.minimize(avg_loss) + + # it will Print Message: + # Regularization of [fc_0.w_0, fc_1.w_0] have been set by ParamAttr or WeightNormParamAttr already. + # So, the Regularization of Optimizer will not take effect for these parameters! + + """ + + def __init__(self, regularization_coeff=0.0): + assert regularization_coeff is not None + super(L2DecayRegularizer, self).__init__() + self._regularization_coeff = regularization_coeff + + def __call__(self, param, grad, block): + """Add L2 weight decay ops to network + + Adds L2 weight decay ops. + L2WeightDecay = reg_coeff * parameter + + Args: + param: parameter variable for which regularization is applied + block: block in which variable is to be created + + Returns: + new variable for weight decay + """ + assert isinstance(param, framework.Variable) + assert isinstance(block, framework.Block) + + if framework._non_static_mode(): + if framework.in_dygraph_mode(): + return _C_ops.scale(param, self._regularization_coeff, 0.0, + True) + else: + return _legacy_C_ops.scale(param, "scale", + self._regularization_coeff) + else: + decay = block.create_var(dtype=param.dtype, + shape=param.shape, + lod_level=param.lod_level) + + # Append Op to calculate decay + block.append_op(type='scale', + inputs={"X": param}, + outputs={"Out": decay}, + attrs={"scale": self._regularization_coeff}) + + return decay + + def __str__(self): + return "L2Decay, regularization_coeff=%f" % self._regularization_coeff + + +class L1DecayRegularizer(WeightDecayRegularizer): + r""" + Implement the L1 Weight Decay Regularization, which encourages the weights to be sparse. + + It can be set in :ref:`api_fluid_ParamAttr` or ``optimizer`` (such as :ref:`api_fluid_optimizer_SGDOptimizer` ). + When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in + ``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has + higher priority than ``optimizer`` . + + In the implementation, the formula of L1 Weight Decay Regularization is as follows: + + .. math:: + + L1WeightDecay = reg\_coeff * sign(parameter) + + Args: + regularization_coeff(float, optional): regularization coeff. Default:0.0. + + Examples: + .. code-block:: python + + # Example1: set Regularizer in optimizer + import paddle.fluid as fluid + + main_prog = fluid.Program() + startup_prog = fluid.Program() + with fluid.program_guard(main_prog, startup_prog): + data = fluid.layers.data(name='image', shape=[3, 28, 28], dtype='float32') + label = fluid.layers.data(name='label', shape=[1], dtype='int64') + hidden = fluid.layers.fc(input=data, size=128, act='relu') + prediction = fluid.layers.fc(input=hidden, size=10, act='softmax') + loss = fluid.layers.cross_entropy(input=prediction, label=label) + avg_loss = fluid.layers.mean(loss) + optimizer = fluid.optimizer.Adagrad( + learning_rate=1e-4, + regularization=fluid.regularizer.L1DecayRegularizer( + regularization_coeff=0.1)) + optimizer.minimize(avg_loss) + + + # Example2: set Regularizer both in ParamAttr and optimizer + import paddle.fluid as fluid + + l1 = fluid.regularizer.L1Decay(regularization_coeff=0.1) + l2 = fluid.regularizer.L2Decay(regularization_coeff=0.1) + x = fluid.layers.uniform_random([3,4]) + + # set L1 regularization in fluid.ParamAttr + w_param = fluid.ParamAttr(regularizer=l1) + hidden1 = fluid.layers.fc(x, 8, param_attr=w_param) # fc_0.w_0(L1), fc_0.b_0 + hidden2 = fluid.layers.fc(hidden1, 16, param_attr=w_param) # fc_1.w_0(L1), fc_1.b_0 + predict = fluid.layers.fc(hidden2, 32) # fc_3.w_0, fc_3.b_0 + avg_loss = fluid.layers.mean(predict) + + # set L2 regularization in optimizer + optimizer = fluid.optimizer.SGD(learning_rate=1e-4, regularization=l2) + optimizer.minimize(avg_loss) + + # it will Print Message: + # Regularization of [fc_0.w_0, fc_1.w_0] have been set by ParamAttr or WeightNormParamAttr already. + # So, the Regularization of Optimizer will not take effect for these parameters! + + """ + + def __init__(self, regularization_coeff=0.0): + assert regularization_coeff is not None + super(L1DecayRegularizer, self).__init__() + self._regularization_coeff = regularization_coeff + + def __call__(self, param, grad, block): + """Add L1 weight decay ops to network + + Adds L1 weight decay ops. + L1WeightDecay = reg_coeff * sign(parameter) + + Args: + param: parameter variable for which regularization is applied + block: block in which variable is to be created + + Returns: + new variable for weight decay + """ + assert isinstance(param, framework.Variable) + assert isinstance(block, framework.Block) + + if framework._non_static_mode(): + sign = block.create_var(dtype=param.dtype, shape=param.shape) + decay = block.create_var(dtype=param.dtype, shape=param.shape) + else: + sign = block.create_var(dtype=param.dtype, + shape=param.shape, + lod_level=param.lod_level) + decay = block.create_var(dtype=param.dtype, + shape=param.shape, + lod_level=param.lod_level) + if in_dygraph_mode(): + sign = _C_ops.sign(param) + return _C_ops.scale(sign, self._regularization_coeff, 0.0, True) + + # Append sign op + block.append_op(type='sign', inputs={"X": param}, outputs={"Out": sign}) + + # Append scale op to the output of sign op + block.append_op(type='scale', + inputs={"X": sign}, + outputs={"Out": decay}, + attrs={"scale": self._regularization_coeff}) + + return decay + + def __str__(self): + return "L1Decay, regularization_coeff=%f" % self._regularization_coeff + + +# We short the class name, since users will use the regulaizer with the package +# name. The sample code: +# +# import paddle.fluid as fluid +# +# hidden = fluid.layers.fc(..., +# param_attr=fluid.regularizer.Xavier()) +# +# It is no need to add a `Regularizer` as the class suffix +L1Decay = L1DecayRegularizer +L2Decay = L2DecayRegularizer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_desc.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_desc.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c17c7095aa093276086b375d742e8e8b1f33ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_desc.py @@ -0,0 +1,437 @@ +# 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. +"""Defination of trainers.""" + +import sys +import os + +__all__ = [ + 'TrainerDesc', 'MultiTrainer', 'DistMultiTrainer', 'PipelineTrainer', + 'HeterXpuTrainer', 'HeterPipelineTrainer' +] + + +class TrainerDesc(object): + ''' + Set proto from python to c++. + Can be initialized from train_desc. + ''' + + def __init__(self): + ''' + self.proto_desc = data_feed_pb2.DataFeedDesc() + with open(proto_file, 'r') as f: + text_format.Parse(f.read(), self.proto_desc) + ''' + # Workaround for relative import in protobuf under python3 + # TODO: should be fixed + cur_path = os.path.dirname(__file__) + if cur_path not in sys.path: + sys.path.append(cur_path) + if cur_path + "/proto" not in sys.path: + sys.path.append(cur_path + "/proto") + + from proto import trainer_desc_pb2 + self.proto_desc = trainer_desc_pb2.TrainerDesc() + import multiprocessing as mp + # set default thread num == cpu count + self.proto_desc.thread_num = mp.cpu_count() + self._fleet_desc = None + self._device_worker = None + self._program = None + self._infer = False + + def _set_heter_info(self, ret): + #ret = = fu.split_program_by_device(program) + #start_list, end_list, send_list, recv_list, program_list = fu.split_program_by_device(program) + #if len(start_list) != 3: + # print("start_list len=", len(start_list), " will not set heter info") + # return + #for i in start_list[0]: + # self.proto_desc.op_run_start_idx.append(i) + #for i in end_list[0]: + # self.proto_desc.op_run_end_idx.append(i) + #for i in send_list[0]: + # self.proto_desc.op_run_send_list.append(i) + #for i in recv_list[0]: + # self.proto_desc.op_run_recv_list.append(i) + if ret is None: + return + #for i in ret[0]: # start_list[1]: + # self.proto_desc.xpu_start_idx.append(i) + self.proto_desc.xpu_start_idx = ret[0] + + #for i in ret[1]: #end_list[1]: + # self.proto_desc.o_end_idx.append(i) + self.proto_desc.xpu_end_idx = ret[1] + for i in ret[2]: # send_list[1]: + self.proto_desc.xpu_send_list.append(i) + for i in ret[3]: # recv_list[1]: + self.proto_desc.xpu_recv_list.append(i) + + #for i in start_list[2]: + # self.proto_desc.op_run_end_start_idx.append(i) + #for i in end_list[2]: + # self.proto_desc.op_run_end_idx.append(i) + #for i in send_list[2]: + # self.proto_desc.op_run_end_send_list.append(i) + #for i in recv_list[2]: + # self.proto_desc.op_run_end_recv_list.append(i) + + def _set_fetch_var_and_info(self, fetch_vars, fetch_info, print_period): + # convert fetch_info to list + fetch_info = list(fetch_info) + for i, v in enumerate(fetch_vars): + self.proto_desc.fetch_config.fetch_var_names.extend([v.name]) + self.proto_desc.fetch_config.fetch_var_str_format.extend( + [fetch_info[i]]) + self.proto_desc.fetch_config.print_period = print_period + + def _set_debug(self, debug): + self.proto_desc.debug = debug + + def _set_thread(self, thread_num): + self.proto_desc.thread_num = thread_num + + def _set_device_worker(self, device_worker): + self._device_worker = device_worker + + def _set_infer(self, infer): + self._infer = infer + + def _set_fleet_desc(self, fleet_desc): + self._fleet_desc = fleet_desc + ## serialize fleet_desc + from google.protobuf import text_format + fleet_desc_str = text_format.MessageToString(fleet_desc) + self.proto_desc.fleet_desc = fleet_desc_str + + def _gen_trainer_desc(self): + pass + + def _set_program(self, program): + self._program = program + + def _set_trainer_id(self, trainer_id): + self.proto_desc.trainer_id = trainer_id + + def _set_trainers(self, trainers): + for trainer_num in trainers: + self.proto_desc.trainers.append(trainer_num) + + def _set_use_cvm(self, use_cvm=False): + self.proto_desc.use_cvm = use_cvm + + def _set_no_cvm(self, no_cvm=False): + self.proto_desc.no_cvm = no_cvm + + def _set_scale_sparse_grad_with_batch_size( + self, scale_sparse_gradient_with_batch_size=True): + self.proto_desc.scale_sparse_gradient_with_batch_size = scale_sparse_gradient_with_batch_size + + def _set_scale_datanorm(self, scale_datanorm=-1): + self.proto_desc.scale_datanorm = scale_datanorm + + def _set_dump_slot(self, dump_slot): + self.proto_desc.dump_slot = dump_slot + + def _set_mpi_rank(self, mpi_rank): + self.proto_desc.mpi_rank = mpi_rank + + def _set_mpi_size(self, mpi_size): + self.proto_desc.mpi_size = mpi_size + + def _set_dump_fields(self, dump_fields): + for field in dump_fields: + self.proto_desc.dump_fields.append(field) + + def _set_is_dump_in_simple_mode(self, is_dump_in_simple_mode): + self.proto_desc.is_dump_in_simple_mode = is_dump_in_simple_mode + + def _set_dump_fields_path(self, path): + self.proto_desc.dump_fields_path = path + + def _set_dump_file_num(self, dump_file_num): + self.proto_desc.dump_file_num = dump_file_num + + def _set_user_define_dump_filename(self, user_define_dump_filename): + self.proto_desc.user_define_dump_filename = user_define_dump_filename + + def _set_dump_converter(self, converter): + self.proto_desc.dump_converter = converter + + def _set_enable_random_dump(self, enable_random_dump): + self.proto_desc.enable_random_dump = enable_random_dump + + def _set_dump_interval(self, dump_interval): + self.proto_desc.dump_interval = dump_interval + + def _set_random_with_lineid(self, random_with_lineid): + self.proto_desc.random_with_lineid = random_with_lineid + + def _set_dump_param(self, dump_param): + for param in dump_param: + self.proto_desc.dump_param.append(param) + + def _set_worker_places(self, worker_places): + for place in worker_places: + self.proto_desc.worker_places.append(place) + + def _set_use_ps_gpu(self, use_ps_gpu=False): + self.proto_desc.use_ps_gpu = use_ps_gpu + + def _set_thread_barrier(self, thread_barrier): + self.proto_desc.thread_barrier = thread_barrier + + def _set_check_nan_var_names(self, check_nan_var_names): + for var in check_nan_var_names: + self.proto_desc.check_nan_var_names.append(var) + + def _set_loss_names(self, loss_names): + for loss in loss_names: + self.proto_desc.loss_names.append(loss) + + def _set_adjust_ins_weight(self, config_dict): + self.proto_desc.adjust_ins_weight_config.need_adjust = \ + config_dict.get("need_adjust", False) + self.proto_desc.adjust_ins_weight_config.nid_slot = \ + config_dict.get("nid_slot", "") + self.proto_desc.adjust_ins_weight_config.nid_adjw_threshold = \ + config_dict.get("nid_adjw_threshold", 0.0) + self.proto_desc.adjust_ins_weight_config.nid_adjw_ratio = \ + config_dict.get("nid_adjw_ratio", 0.0) + self.proto_desc.adjust_ins_weight_config.ins_weight_slot = \ + config_dict.get("ins_weight_slot", "") + + def _set_copy_table_config(self, config_dict): + config = self.proto_desc.copy_table_config + config.need_copy = config_dict.get("need_copy", False) + config.batch_num = config_dict.get("batch_num", 100) + + src_sparse_tables = config_dict.get("src_sparse_tables", []) + if not isinstance(src_sparse_tables, list): + src_sparse_tables = [src_sparse_tables] + dest_sparse_tables = config_dict.get("dest_sparse_tables", []) + if not isinstance(dest_sparse_tables, list): + dest_sparse_tables = [dest_sparse_tables] + if len(src_sparse_tables) != len(dest_sparse_tables): + raise ValueError( + "len(src_sparse_tables) != len(dest_sparse_tables)," \ + " %s vs %s" % (len(src_sparse_tables), \ + len(dest_sparse_tables))) + for i in src_sparse_tables: + config.src_sparse_tables.append(i) + for i in dest_sparse_tables: + config.dest_sparse_tables.append(i) + + src_dense_tables = config_dict.get("src_dense_tables", []) + if not isinstance(src_dense_tables, list): + src_dense_tables = [src_dense_tables] + dest_dense_tables = config_dict.get("dest_dense_tables", []) + if not isinstance(dest_dense_tables, list): + dest_dense_tables = [dest_dense_tables] + if len(src_dense_tables) != len(dest_dense_tables): + raise ValueError( + "len(src_dense_tables) != len(dest_dense_tables)," \ + " %s vs %s" % (len(src_dense_tables), \ + len(dest_dense_tables))) + for i in src_dense_tables: + config.src_dense_tables.append(i) + for i in dest_dense_tables: + config.dest_dense_tables.append(i) + + # user can also specify dense variables to copy, + # instead of copy dense table + src_var_list = config_dict.get("src_var_list", []) + if not isinstance(src_var_list, list): + src_var_list = [src_var_list] + dest_var_list = config_dict.get("dest_var_list", []) + if not isinstance(dest_var_list, list): + dest_var_list = [dest_var_list] + if len(src_var_list) != len(dest_var_list): + raise ValueError( + "len(src_var_list) != len(dest_var_list), %s vs" \ + " %s" % (len(src_var_list), len(dest_var_list))) + for i in src_var_list: + config.src_var_list.append(i) + for i in dest_var_list: + config.dest_var_list.append(i) + + dependency_map = config_dict.get("dependency_map", {}) + for key in dependency_map: + m = config.table_denpendency_map.add() + m.key = key + values = dependency_map[key] + if not isinstance(values, list): + values = [values] + if len(values) != 1: + raise ValueError("dependency len %s != 1" % len(values)) + for value in values: + m.values.append(value) + config.dense_pull_after_copy = \ + config_dict.get("dense_pull_after_copy", True) + config.enable_dependency = \ + config_dict.get("enable_dependency", False) + config.sparse_copy_by_feasign = \ + config_dict.get("sparse_copy_by_feasign", True) + + def _desc(self): + from google.protobuf import text_format + return self.proto_desc.SerializeToString() + + def __str__(self): + from google.protobuf import text_format + return text_format.MessageToString(self.proto_desc) + + +class MultiTrainer(TrainerDesc): + ''' + Implement of MultiTrainer. + Can be init from TrainerDesc. + ''' + + def __init__(self): + super(MultiTrainer, self).__init__() + pass + + def _set_program(self, program): + super(MultiTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(MultiTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "MultiTrainer" + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) + + +class DistMultiTrainer(TrainerDesc): + """ + Implement of DistMultiTrainer. + It's for Distributed training. + """ + + def __init__(self): + super(DistMultiTrainer, self).__init__() + pass + + def _set_program(self, program): + super(DistMultiTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(DistMultiTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "DistMultiTrainer" + if self._program == None: + raise RuntimeError("None Program") + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) + + +class HeterXpuTrainer(TrainerDesc): + """ + Implement of HeterXpuTrainer. + It's for Distributed training. + """ + + def __init__(self): + super(HeterXpuTrainer, self).__init__() + pass + + def _set_program(self, program): + super(HeterXpuTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(HeterXpuTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "HeterXpuTrainer" + if self._program == None: + raise RuntimeError("None Program") + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) + + +class PSGPUTrainer(TrainerDesc): + """ + Implement of PSGPUTrainer. + It's for Distributed training. + """ + + def __init__(self): + super(PSGPUTrainer, self).__init__() + pass + + def _set_program(self, program): + super(PSGPUTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(PSGPUTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "PSGPUTrainer" + if self._program == None: + raise RuntimeError("None Program") + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) + + +class HeterPipelineTrainer(TrainerDesc): + """ + Implement of HeterPipelineTrainer. + It's for HeterPS Pipeline training. + """ + + def __init__(self): + super(HeterPipelineTrainer, self).__init__() + pass + + def _set_program(self, program): + super(HeterPipelineTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(HeterPipelineTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "HeterPipelineTrainer" + if self._program == None: + raise RuntimeError("None Program") + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) + + +class PipelineTrainer(TrainerDesc): + """ + Implement of PipelineTrainer. + It's for Pipeline. + """ + + def __init__(self): + super(PipelineTrainer, self).__init__() + pass + + def _set_program(self, program): + super(PipelineTrainer, self)._set_program(program) + self._program = program + + def _gen_trainer_desc(self): + super(PipelineTrainer, self)._gen_trainer_desc() + self.proto_desc.class_name = "PipelineTrainer" + if self._program == None: + raise RuntimeError("None Program") + self._device_worker._set_infer(self._infer) + self._device_worker._set_program(self._program) + self._device_worker._gen_worker_desc(self.proto_desc) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_factory.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba9f9eea46d1bbf759cc5414a595d00aa148460 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/trainer_factory.py @@ -0,0 +1,207 @@ +# 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. +"""Defination of TrainerFactory.""" + +import threading +import time +import logging +import numpy as np +from paddle.fluid.log_helper import get_logger + +local_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + +from .trainer_desc import MultiTrainer, DistMultiTrainer, PipelineTrainer, HeterXpuTrainer, PSGPUTrainer, HeterPipelineTrainer +from .device_worker import Hogwild, DownpourSGD, DownpourLite, Section, DownpourSGDOPT, HeterSection +from .framework import Variable +from multiprocessing import Process, Manager + +__all__ = ["TrainerFactory", "FetchHandlerMonitor"] + + +class TrainerFactory(object): + """ + Create trainer and device worker. + If opt_info is not None, it will get configs from opt_info, + otherwise create MultiTrainer and Hogwild. + """ + + def __init__(self): + pass + + def _create_trainer(self, opt_info=None): + trainer = None + device_worker = None + if not opt_info: + # default is MultiTrainer + Hogwild + trainer = MultiTrainer() + device_worker = Hogwild() + trainer._set_device_worker(device_worker) + else: + trainer_class = opt_info.get("trainer", "MultiTrainer") + device_worker_class = opt_info.get("device_worker", "Hogwild") + trainer = globals()[trainer_class]() + device_worker = globals()[device_worker_class]() + + # for debug tools + if opt_info is not None: + if opt_info.get("trainers") is not None: + trainer._set_trainers(opt_info["trainers"]) + if opt_info.get("trainer_id") is not None: + trainer._set_trainer_id(opt_info["trainer_id"]) + if opt_info.get("dump_slot") is not None: + trainer._set_dump_slot(opt_info["dump_slot"]) + if opt_info.get("mpi_rank") is not None: + trainer._set_mpi_rank(opt_info["mpi_rank"]) + if opt_info.get("mpi_size") is not None: + trainer._set_mpi_size(opt_info["mpi_size"]) + if opt_info.get("dump_fields") is not None and len( + opt_info.get("dump_fields")) != 0: + trainer._set_dump_fields(opt_info["dump_fields"]) + if opt_info.get("dump_fields_path") is not None and len( + opt_info.get("dump_fields_path")) != 0: + trainer._set_dump_fields_path(opt_info["dump_fields_path"]) + if opt_info.get("dump_file_num") is not None: + trainer._set_dump_file_num(opt_info["dump_file_num"]) + if opt_info.get("dump_converter") is not None: + trainer._set_dump_converter(opt_info["dump_converter"]) + if opt_info.get("dump_param") is not None and len( + opt_info.get("dump_param")) != 0: + trainer._set_dump_param(opt_info["dump_param"]) + if opt_info.get("worker_places") is not None: + trainer._set_worker_places(opt_info["worker_places"]) + if opt_info.get("use_ps_gpu") is not None: + trainer._set_use_ps_gpu(opt_info["use_ps_gpu"]) + if opt_info.get("is_dump_in_simple_mode") is not None: + trainer._set_is_dump_in_simple_mode( + opt_info["is_dump_in_simple_mode"]) + if opt_info.get("enable_random_dump") is not None: + trainer._set_enable_random_dump( + opt_info["enable_random_dump"]) + if opt_info.get("dump_interval") is not None: + trainer._set_dump_interval(opt_info["dump_interval"]) + if opt_info.get("random_with_lineid") is not None: + trainer._set_random_with_lineid( + opt_info["random_with_lineid"]) + + if "fleet_desc" in opt_info: + device_worker._set_fleet_desc(opt_info["fleet_desc"]) + trainer._set_fleet_desc(opt_info["fleet_desc"]) + if opt_info.get("use_cvm") is not None: + trainer._set_use_cvm(opt_info["use_cvm"]) + if opt_info.get("no_cvm") is not None: + trainer._set_no_cvm(opt_info["no_cvm"]) + if opt_info.get( + "scale_sparse_gradient_with_batch_size") is not None: + trainer._set_scale_sparse_grad_with_batch_size( + opt_info["scale_sparse_gradient_with_batch_size"]) + if opt_info.get("scale_datanorm") is not None: + trainer._set_scale_datanorm(opt_info["scale_datanorm"]) + if opt_info.get("adjust_ins_weight") is not None: + trainer._set_adjust_ins_weight( + opt_info["adjust_ins_weight"]) + if opt_info.get("copy_table") is not None: + trainer._set_copy_table_config(opt_info["copy_table"]) + if opt_info.get("check_nan_var_names") is not None: + trainer._set_check_nan_var_names( + opt_info["check_nan_var_names"]) + if opt_info.get("loss_names") is not None: + trainer._set_loss_names(opt_info["loss_names"]) + trainer._set_device_worker(device_worker) + return trainer + + +class FetchHandlerMonitor(object): + """ + Defination of FetchHandlerMonitor class, + it's for fetch handler. + """ + + def __init__(self, scope, handler): + self.fetch_instance = handler + self.fetch_thread = threading.Thread(target=self.handler_launch_func, + args=(scope, self.fetch_instance)) + self.running_lock = threading.Lock() + self.running = False + + def handler_launch_func(self, scope, handler): + fetch_instance = handler + period_secs = fetch_instance.period_secs + var_name_to_key = {} + for key in fetch_instance.var_dict: + if isinstance(fetch_instance.var_dict[key], Variable): + var_name_to_key[fetch_instance.var_dict[key].name] = key + else: + local_logger.warning( + "the value of {} is not a Variable".format(key)) + var_name_to_key["None.var"] = key + elapsed_secs = 0 + while True: + self.running_lock.acquire() + if self.running == False: + break + if elapsed_secs < period_secs: + # TODO(guru4elephant): needs customized condition + time.sleep(1) + elapsed_secs += 1 + else: + elapsed_secs = 0 + fetch_dict = {} + for key in var_name_to_key: + var = scope.find_var(key) + fetch_dict[key] = var + if var == None: + local_logger.warning( + "{} value currently not available".format( + var_name_to_key[key])) + res_dict = {} + for key in fetch_dict: + user_name = var_name_to_key[key] + if fetch_dict[key] == None: + res_dict[user_name] = None + continue + else: + res_dict[user_name] = fetch_dict[key].get_tensor() + + lod = res_dict[user_name].lod() + if len(lod) > 0: + raise RuntimeError("Some of your fetched tensors \ + hold LoD information. \ + They can not be completely cast \ + to Python ndarray. We can \ + not return LoDTensor itself directly, \ + please choose another targets") + if res_dict[user_name]._is_initialized(): + res_dict[user_name] = np.array(res_dict[user_name]) + else: + res_dict[user_name] = None + fetch_instance.handler(res_dict) + self.running_lock.release() + + def start(self): + """ + start monitor, + it will start a monitor thread. + """ + self.running_lock.acquire() + self.running = True + self.running_lock.release() + self.fetch_thread.setDaemon(True) + self.fetch_thread.start() + + def stop(self): + self.running_lock.acquire() + self.running = False + self.running_lock.release() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c5d2502ddbb4afa1dba1f97e8867174469382abe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/__init__.py @@ -0,0 +1,28 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from .distribute_transpiler import DistributeTranspiler, DistributeTranspilerConfig +from .memory_optimization_transpiler import memory_optimize, release_memory +from .ps_dispatcher import HashName, RoundRobin + +__all__ = [ + "DistributeTranspiler", + "memory_optimize", + "release_memory", + "HashName", + "RoundRobin", + "DistributeTranspilerConfig", +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ascend_transpiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ascend_transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..69fb2b1833655382d0b64202388ccae745638451 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ascend_transpiler.py @@ -0,0 +1,74 @@ +# Copyright (c) 2021 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. + +from . import collective +from .. import core + +OpRole = core.op_proto_and_checker_maker.OpRole +from paddle.distributed import fleet + + +class AscendTranspiler(collective.Collective): + + def __init__(self, startup_program, main_program): + self.nrings = 1 + super(AscendTranspiler, self).__init__(self.nrings) + self._startup_program = startup_program + self._main_program = main_program + + def _insert_allreduce_ops(self): + block = self._main_program.global_block() + ring_id = -1 + grad = None + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_backward_op(op) and \ + self.op_role_var_key in op.attr_names: + op_role_var = op.all_attrs()[self.op_role_var_key] + + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + + offset = idx + for i in range(0, len(op_role_var), 2): + param = block.vars[op_role_var[i]] + grad = block.vars[op_role_var[i + 1]] + if param.is_distributed: + continue + + # As we search ops reversedly, we should insert c_allreduce_sum + # op in the same way to keep the ring_id alternate + ring_id = (ring_id + 1) % self.nrings + block._insert_op(offset + 1, + type='c_allreduce_sum', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + block._insert_op(offset + 2, + type='scale', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'scale': 1.0 / fleet.worker_num(), + self.op_role_key: OpRole.Backward + }) + + if grad is None: + return + + def transpile(self): + self._insert_allreduce_ops() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/collective.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..cb57ea2a421cbad4a0b7daa815c341815f2249e4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/collective.py @@ -0,0 +1,740 @@ +# 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. + +from __future__ import print_function + +import sys +import math +from functools import reduce +import os + +import collections +import six +import logging + +import numpy as np + +from .. import core, unique_name +from ..framework import Program, default_main_program, default_startup_program +from .details import wait_server_ready + +__all__ = ['GradAllReduce', 'LocalSGD', 'MultiThread'] + +OpRole = core.op_proto_and_checker_maker.OpRole + + +class Collective(object): + ''' + ''' + + def __init__(self, nrings): + self.nrings = nrings + self.endpoints = None + self.current_endpoint = None + self.other_endpoints = None + self.nranks = None + self.rank = None + self.startup_program = None + self.main_program = None + op_maker = core.op_proto_and_checker_maker + self.op_role_key = op_maker.kOpRoleAttrName() + self.op_role_var_key = op_maker.kOpRoleVarAttrName() + + def transpile(self, startup_program, main_program, rank, endpoints, + current_endpoint, wait_port): + # in case of '127.0.0.1:6700,127.0.0.1:6701,...' + if isinstance(endpoints, str): + endpoints = endpoints.split(',') + + self.startup_program = startup_program + if startup_program is None: + self.startup_program = default_startup_program() + + self.main_program = main_program + if main_program is None: + self.main_program = default_main_program() + + self.nranks = len(endpoints) + if self.nranks == 1 and self.mode != "single_process_multi_thread" and self.mode != "box": + raise ValueError('the number of endpoints must > 1') + + if rank < 0: + raise ValueError('rank must >= 0') + self.rank = rank + + if current_endpoint not in endpoints: + raise ValueError('current endpoint %s is not in %s', + current_endpoint, str(endpoints)) + + self.endpoints = endpoints + self.current_endpoint = current_endpoint + + if current_endpoint: + nranks = len(endpoints) + other_endpoints = endpoints[:] + other_endpoints.remove(current_endpoint) + self.other_endpoints = other_endpoints + + self.wait_port = wait_port + + self.startup_program._origin_program = self.startup_program.clone() + self._transpile_startup_program() + + self.main_program._origin_program = self.main_program.clone() + self._transpile_main_program() + + def _transpile_main_program(self): + raise NotImplementedError('call the inherited method of subclasses') + + def _transpile_startup_program(self): + for ring_id in range(self.nrings): + self._init_communicator(self.startup_program, self.current_endpoint, + self.endpoints, self.rank, ring_id, + self.wait_port) + self._broadcast_params() + + def _init_communicator(self, + program, + current_endpoint, + endpoints, + rank, + ring_id, + wait_port, + has_multitrainer=False): + nranks = len(endpoints) + other_endpoints = endpoints[:] + other_endpoints.remove(current_endpoint) + block = program.global_block() + + if rank == 0 and wait_port: + wait_server_ready(other_endpoints) + + block = program.global_block() + if core.is_compiled_with_npu(): + hccl_id_var = block.create_var(name=unique_name.generate('hccl_id'), + persistable=True, + type=core.VarDesc.VarType.RAW) + endpoint_to_index_map = {e: idx for idx, e in enumerate(endpoints)} + block.append_op(type='c_gen_hccl_id', + inputs={}, + outputs={'Out': hccl_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + self.op_role_key: OpRole.Forward + }) + block.append_op(type='c_comm_init_hccl', + inputs={'X': hccl_id_var}, + outputs={}, + attrs={ + 'rank': rank, + 'ring_id': ring_id, + 'device_id': + int(os.getenv("FLAGS_selected_npus")), + 'rank_ids': nranks, + self.op_role_key: OpRole.Forward + }) + else: + nccl_id_var = block.create_var(name=unique_name.generate('nccl_id'), + persistable=True, + type=core.VarDesc.VarType.RAW) + block.append_op(type='c_gen_nccl_id', + inputs={}, + outputs={'Out': nccl_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + self.op_role_key: OpRole.Forward + }) + if not has_multitrainer: + block.append_op(type='c_comm_init', + inputs={'X': nccl_id_var}, + outputs={}, + attrs={ + 'nranks': nranks, + 'rank': rank, + 'ring_id': ring_id, + self.op_role_key: OpRole.Forward + }) + else: + block.append_op(type='c_comm_init_multitrainer', + inputs={'X': nccl_id_var}, + outputs={}, + attrs={ + 'ntrainers': nranks, + 'trainer_id': rank, + 'ring_id': ring_id, + self.op_role_key: OpRole.Forward + }) + + def _broadcast_params(self): + block = self.startup_program.global_block() + ring_id = -1 + for param in block.iter_parameters(): + if param.is_distributed: + continue + + ring_id = (ring_id + 1) % self.nrings + block.append_op(type='c_broadcast', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + 'root': 0, + self.op_role_key: OpRole.Forward + }) + + for ring_id in range(self.nrings): + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Forward + }) + + def _is_loss_grad_op(self, op): + if self.op_role_key not in op.attr_names: + return False + op_role = int(op.all_attrs()[self.op_role_key]) + return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss) + + def _is_backward_op(self, op): + return self.op_role_key in op.attr_names and \ + int(op.all_attrs()[self.op_role_key]) & int(OpRole.Backward) + + def _is_update_op(self, op): + return 'Param' in op.input_names and 'Grad' in op.input_names and \ + "LearningRate" in op.input_names + + def _is_optimizer_op(self, op): + return self.op_role_key in op.attr_names and \ + int(op.all_attrs()[self.op_role_key]) & int(OpRole.Optimize) + + +class GradAllReduce(Collective): + ''' + ''' + + def __init__(self, nrings=2): + Collective.__init__(self, nrings) + self.mode = "grad_allreduce" + + def _transpile_main_program(self): + self._insert_scale_loss_grad_ops() + self._insert_allreduce_ops() + + def _insert_scale_loss_grad_ops(self): + ''' + In order to keep the learning rate consistent in different numbers of + training workers, we scale the loss grad by the number of workers + ''' + block = self.main_program.global_block() + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_loss_grad_op(op): + loss_grad_var = block.vars[op.output_arg_names[0]] + block._insert_op(idx + 1, + type='scale', + inputs={'X': loss_grad_var}, + outputs={'Out': loss_grad_var}, + attrs={ + 'scale': 1.0 / self.nranks, + self.op_role_key: OpRole.Backward + }) + + def _insert_allreduce_ops(self): + block = self.main_program.global_block() + ring_id = -1 + grad = None + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_backward_op(op) and \ + self.op_role_var_key in op.attr_names: + op_role_var = op.all_attrs()[self.op_role_var_key] + + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + + offset = idx + for i in range(0, len(op_role_var), 2): + param = block.vars[op_role_var[i]] + grad = block.vars[op_role_var[i + 1]] + if param.is_distributed: + continue + + if offset == idx: + offset += 1 + block._insert_op( + offset, + type='c_sync_calc_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={self.op_role_key: OpRole.Backward}) + offset += 1 + + # As we search ops reversedly, we should insert c_allreduce_sum + # op in the same way to keep the ring_id alternate + ring_id = (ring_id + 1) % self.nrings + block._insert_op(offset, + type='c_allreduce_sum', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + + if grad is None: + return + + for idx, op in enumerate(block.ops): + if self._is_optimizer_op(op): + for ring_id in range(self.nrings): + block._insert_op(idx + ring_id, + type='c_sync_comm_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + break + + +class LocalSGD(Collective): + ''' + ''' + + def __init__(self, nrings=2): + Collective.__init__(self, nrings) + self.snapshot_key = '@SNAPSHOT' + self.mode = "local_sgd" + + def _transpile_startup_program(self): + Collective._transpile_startup_program(self) + + block = self.startup_program.global_block() + non_dist_params = [] + for param in block.iter_parameters(): + if not param.is_distributed: + non_dist_params.append(param) + + for param in non_dist_params: + snapshot = block.create_var(name=self.snapshot_name(param.name), + shape=param.shape, + persistable=True, + stop_gradient=True) + block.append_op(type='assign', + inputs={'X': [param]}, + outputs={'Out': [snapshot]}, + attrs={self.op_role_key: OpRole.Forward}) + + def snapshot_name(self, param_name): + return param_name + self.snapshot_key + + def _transpile_main_program(self): + block = self.main_program.global_block() + ordered_param_snapshot = [] + ring_id = -1 + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_update_op(op): + param = block.vars[op.input('Param')[0]] + if param.is_distributed: + continue + + snapshot = block.create_var(name=self.snapshot_name(param.name), + shape=param.shape, + persistable=True, + stop_gradient=True, + dtype=param.dtype) + + block._insert_op(idx + 1, + type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={self.op_role_key: OpRole.Optimize}) + block._insert_op(idx + 2, + type='c_sync_calc_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={self.op_role_key: OpRole.Optimize}) + ring_id = (ring_id + 1) % self.nrings + block._insert_op(idx + 3, + type='c_allreduce_sum', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Optimize + }) + + ordered_param_snapshot.append((param, snapshot)) + + for ring_id in range(self.nrings): + block.append_op(type='c_sync_comm_stream', + inputs={'X': param}, + outputs={'Out': param}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Optimize + }) + + for param_snapshot in reversed(ordered_param_snapshot): + param = param_snapshot[0] + snapshot = param_snapshot[1] + block.append_op(type='scale', + inputs={'X': [param]}, + outputs={'Out': [param]}, + attrs={ + 'scale': 1.0 / self.nranks, + self.op_role_key: OpRole.Optimize + }) + block.append_op(type='elementwise_sub', + inputs={ + 'X': [snapshot], + 'Y': [param] + }, + outputs={'Out': [param]}, + attrs={self.op_role_key: OpRole.Optimize}) + block.append_op(type='assign', + inputs={'X': [param]}, + outputs={'Out': [snapshot]}, + attrs={self.op_role_key: OpRole.Optimize}) + + +class SingleProcessMultiThread(GradAllReduce): + ''' + ''' + + def __init__(self): + GradAllReduce.__init__(self, 1) + self.mode = "single_process_multi_thread" + + def _transpile_startup_program(self): + block = self.startup_program.global_block() + block.append_op(type='c_comm_init_all', attrs={'ring_id': 0}) + + +class MultiThread(GradAllReduce): + ''' + ''' + + def __init__(self, nrings=1, trans_mode="all_reduce"): + GradAllReduce.__init__(self, nrings) + self.mode = "box" + self.trans_mode = trans_mode + self.fuse_grad_size_in_num = 128 + gpu_nums = os.getenv("FLAGS_selected_gpus", + "0,1,2,3,4,5,6,7,8").split(",") + self.gpu_num = len(gpu_nums) + + def _transpile_startup_program(self): + if len(self.endpoints) > 1: + print("begin to _transpile_startup_program for multi-node") + print("current_endpoint: ", self.current_endpoint) + print("total endpoints: ", self.endpoints) + print("rank: %d, ring_id: %d" % (self.rank, self.nrings)) + for ring_id in range(self.nrings): + self._init_communicator(self.startup_program, + self.current_endpoint, self.endpoints, + self.rank, ring_id, self.wait_port, + True) + + else: + if "xpu" in self.trans_mode: + print( + "begin to _transpile_startup_program for single-node in XPU" + ) + block = self.startup_program.global_block() + block.append_op( + type='c_comm_init_all', + attrs={ + 'devices': + list( + map(int, + os.getenv("FLAGS_selected_gpus").split(","))), + 'ring_id': + 0 + }) + else: + print("begin to _transpile_startup_program for single-node") + block = self.startup_program.global_block() + block.append_op(type='c_comm_init_all', attrs={'ring_id': 0}) + + def _transpile_main_program(self): + self._insert_scale_loss_grad_ops() + if self.trans_mode == "all_gather": + print("begin to transpile in all-gather mode") + self.allgather_ranks = self.nranks * self.gpu_num + self._insert_allgather_ops() + self._update_adam_ops() + elif self.trans_mode == "fuse_all_reduce": + print("begin to transpile in fuse all-reduce mode") + self._insert_fuse_allreduce_ops() + elif self.trans_mode == "all_reduce_xpu" and len( + os.getenv("FLAGS_selected_gpus").split(",")) == 1: + print( + "skip transpile in all-reduce-xpu mode when number of devices is only one" + ) + else: + print("begin to transpile in all-reduce mode") + self._insert_allreduce_ops() + + def _insert_allgather_ops(self): + """ + insert allgather op to the main_program + """ + block = self.main_program.global_block() + ring_id = -1 + grad = None + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_backward_op(op) and \ + self.op_role_var_key in op.attr_names: + op_role_var = op.all_attrs()[self.op_role_var_key] + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0 + + offset = idx + for i in range(0, len(op_role_var), 2): + param = block.vars[op_role_var[i]] + new_grad_var = block.create_var( + name=op_role_var[i] + "_allgather", + shape=[self.allgather_ranks] + list(param.shape), + persistable=False, + dtype=core.VarDesc.VarType.FP32, + stop_gradient=True) + grad = block.vars[op_role_var[i + 1]] + if param.is_distributed: # no need to care: used in PLSC + continue + + if offset == idx: + offset += 1 + block._insert_op( + offset, + type='c_sync_calc_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={self.op_role_key: OpRole.Backward}) + offset += 1 + + # As we search ops reversedly, we should insert c_allgather + # op in the same way to keep the ring_id alternate + ring_id = (ring_id + 1) % self.nrings + block._insert_op(offset, + type='c_allgather', + inputs={'X': grad}, + outputs={'Out': new_grad_var}, + attrs={ + 'nranks': self.allgather_ranks, + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + + if grad is None: + return + + for idx, op in enumerate(block.ops): + if self._is_optimizer_op(op): + for ring_id in range(self.nrings): + block._insert_op(idx + ring_id, + type='c_sync_comm_stream', + inputs={'X': grad}, + outputs={'Out': grad}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + break + + def _update_adam_ops(self): + """ + remove the original adam op, and add new adam ops + """ + block = self.main_program.global_block() + + for idx, op in reversed(list(enumerate(block.ops))): + if self._is_optimizer_op(op): + offset = idx + if op.type != 'adam' and op.type != 'lamb': # filter out scale op + continue + param_name = op.input("Param")[0] + inputs = { + "Param": block.vars[op.input("Param")[0]], + "LearningRate": block.vars[op.input("LearningRate")[0]], + "Moment1": block.vars[op.input("Moment1")[0]], + "Moment2": block.vars[op.input("Moment2")[0]], + "Beta1Pow": block.vars[op.input("Beta1Pow")[0]], + "Beta2Pow": block.vars[op.input("Beta2Pow")[0]] + } + outputs = { + "ParamOut": block.vars[op.output("ParamOut")[0]], + "Moment1Out": block.vars[op.output("Moment1Out")[0]], + "Moment2Out": block.vars[op.output("Moment2Out")[0]], + "Beta1PowOut": block.vars[op.output("Beta1PowOut")[0]], + "Beta2PowOut": block.vars[op.output("Beta2PowOut")[0]] + } + attrs = { + "epsilon": + op.attr('epsilon'), + "beta1": + op.attr('beta1'), + "beta2": + op.attr('beta2'), + "lazy_mode": + op.attr('lazy_mode'), + "min_row_size_to_use_multithread": + op.attr('min_row_size_to_use_multithread') + } + split_vars = [ + block.create_var( + name=param_name + "_" + str(i), + shape=block.vars[op.input("Param")[0]].shape, + persistable=False, + dtype=core.VarDesc.VarType.FP32, + stop_gradient=True) for i in range(self.allgather_ranks) + ] + block._insert_op(offset, + type="split", + inputs={ + 'X': + block.vars[op.input("Param")[0] + + "_allgather"] + }, + outputs={'Out': split_vars}, + attrs={ + 'num': self.allgather_ranks, + 'axis': 0 + }) + offset += 1 + + for i in range(self.allgather_ranks): + inputs["Grad"] = split_vars[i] + block._insert_op(offset, + type=op.type, + inputs=inputs, + outputs=outputs, + attrs=attrs) + offset += 1 + # remove the original adam op + block._remove_op(offset) + + def _insert_fuse_allreduce_ops(self): + """ + insert coalesce_tensor and all reduce ops + """ + block = self.main_program.global_block() + ring_id = 0 % self.nrings + grad = None + param_grads = [] + # find all grad params + for op in reversed(block.ops): + if self._is_backward_op(op) and \ + self.op_role_var_key in op.attr_names: + op_role_var = op.all_attrs()[self.op_role_var_key] + if len(op_role_var) == 0: + continue + assert len(op_role_var) % 2 == 0, "vars need to be one param var followed by one grad var, " \ + "but got odd number of vars" + for i in range(0, len(op_role_var), 2): + param_name = op_role_var[i] + param = block.var(param_name) + grad_name = op_role_var[i + 1] + grad = block.var(grad_name) + if param.is_distributed: + continue + param_grads.append(grad) + if grad is None: + return + + segments = [] + last_dtype = None + # split the grad based on dtype and fused size + for var in param_grads: + if len(segments) == 0 \ + or len(segments[-1]) == self.fuse_grad_size_in_num \ + or var.dtype != last_dtype: + segments.append([var]) + last_dtype = var.dtype + else: + segments[-1].append(var) + + fused_vars = [] + for idx, op in enumerate(block.ops): + if self._is_optimizer_op(op): + for segment in segments: + # insert coalesce tensor + tmp_var = block.create_var(name=unique_name.generate( + 'FusedOutput_{}'.format(segment[0].name)), + dtype=segment[0].dtype, + persistable=False, + stop_gradient=True) + fused_vars.append(tmp_var) + block._insert_op(idx, + type="coalesce_tensor", + inputs={"Input": segment}, + outputs={ + "Output": segment, + "FusedOutput": tmp_var + }, + attrs={ + "copy_data": True, + "use_align": True, + "dtype": segment[0].dtype, + self.op_role_key: OpRole.Backward + }) + break + + # insert the allreduce_sum op + for idx, op in enumerate(block.ops): + if self._is_optimizer_op(op): + for fused_var in fused_vars: + block._insert_op(idx, + type='c_allreduce_sum', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': False, + self.op_role_key: OpRole.Backward + }) + block._insert_op(idx, + type='c_sync_calc_stream', + inputs={'X': fused_var}, + outputs={'Out': fused_var}, + attrs={self.op_role_key: OpRole.Backward}) + break + + if len(fused_vars) == 0: + block._sync_with_cpp() + return + + # insert the sync comm op + for idx, op in enumerate(block.ops): + if self._is_optimizer_op(op): + block._insert_op(idx, + type='c_sync_comm_stream', + inputs={'X': fused_vars[0]}, + outputs={'Out': fused_vars[0]}, + attrs={ + 'ring_id': ring_id, + self.op_role_key: OpRole.Backward + }) + break + block._sync_with_cpp() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82d0d336e523ec48c5ceca3b92ff0963c4499123 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from .program_utils import * +from .ufind import * +from .checkport import * +from .vars_distributed import * diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/checkport.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/checkport.py new file mode 100644 index 0000000000000000000000000000000000000000..1341bdaedf99e3aa40d0159634a4246d0ee4e2f0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/checkport.py @@ -0,0 +1,60 @@ +# Copyright (c) 2018 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. + +import sys +import time +import socket +from contextlib import closing +from six import string_types + + +def wait_server_ready(endpoints): + """ + Wait until parameter servers are ready, use connext_ex to detect + port readiness. + + Args: + endpoints (list): endpoints string list, like: + ["127.0.0.1:8080", "127.0.0.1:8081"] + + Examples: + .. code-block:: python + + wait_server_ready(["127.0.0.1:8080", "127.0.0.1:8081"]) + """ + assert not isinstance(endpoints, string_types) + while True: + all_ok = True + not_ready_endpoints = [] + for ep in endpoints: + ip_port = ep.split(":") + with closing(socket.socket(socket.AF_INET, + socket.SOCK_STREAM)) as sock: + sock.settimeout(2) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + result = sock.connect_ex((ip_port[0], int(ip_port[1]))) + if result != 0: + all_ok = False + not_ready_endpoints.append(ep) + if not all_ok: + sys.stderr.write("server not ready, wait 3 sec to retry...\n") + sys.stderr.write("not ready endpoints:" + str(not_ready_endpoints) + + "\n") + sys.stderr.flush() + time.sleep(3) + else: + break diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/program_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/program_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7b9ed661ab3b15c1b393acae46ec71d1fea4aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/program_utils.py @@ -0,0 +1,51 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import six + +from paddle.fluid import core +import paddle + + +def delete_ops(block, ops): + for op in ops: + try: + idx = list(block.ops).index(op) + block._remove_op(idx) + except Exception as e: + print(e) + + +def find_op_by_input_arg(block, arg_name): + for index, op in enumerate(block.ops): + if arg_name in op.input_arg_names: + return index + return -1 + + +def find_op_by_output_arg(block, arg_name, reverse=False): + if reverse: + pos = len(block.ops) - 1 + while pos >= 0: + op = block.ops[pos] + if arg_name in op.output_arg_names: + return pos + pos -= 1 + else: + for index, op in enumerate(block.ops): + if arg_name in op.output_arg_names: + return index + return -1 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/ufind.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/ufind.py new file mode 100644 index 0000000000000000000000000000000000000000..aa63af7dcf7ac85031fb00ca4c39fb36d7e588b8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/ufind.py @@ -0,0 +1,66 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + + +class UnionFind(object): + """ Union-find data structure. + + Union-find is a data structure that keeps track of a set of elements partitioned + into a number of disjoint (non-overlapping) subsets. + + Reference: + https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + Args: + elements(list): The initialize element list. + """ + + def __init__(self, elementes=None): + self._parents = [] # index -> parent index + self._index = {} # element -> index + self._curr_idx = 0 + if not elementes: + elementes = [] + for ele in elementes: + self._parents.append(self._curr_idx) + self._index.update({ele: self._curr_idx}) + self._curr_idx += 1 + + def find(self, x): + # Find the root index of given element x, + # execute the path compress while findind the root index + if not x in self._index: + return -1 + idx = self._index[x] + while idx != self._parents[idx]: + t = self._parents[idx] + self._parents[idx] = self._parents[t] + idx = t + return idx + + def union(self, x, y): + # Union two given element + x_root = self.find(x) + y_root = self.find(y) + + if x_root == y_root: + return + self._parents[x_root] = y_root + + def is_connected(self, x, y): + # If two given elements have the same root index, + # then they are connected. + return self.find(x) == self.find(y) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/vars_distributed.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/vars_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..05e7f6e3e706376efc8af870a780d96c45642514 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/details/vars_distributed.py @@ -0,0 +1,269 @@ +# Copyright (c) 2018 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. +from __future__ import print_function +from paddle.fluid.framework import Variable + + +class VarStruct(object): + """ + record part properties of a Variable in python. + """ + + def __init__(self, name, shape, dtype, type, lod_level, persistable): + self.name = name + self.shape = shape + self.dtype = dtype + self.type = type + self.lod_level = lod_level + self.persistable = persistable + + +class VarDistributed(object): + """ + a class to record the var distributed on parameter servers. + the class will record the relationship between origin var and slice var. + the slice var's properties, such as type/shape/offset/endpoint. + """ + + def __init__(self, + origin_var, + slice_var, + is_slice=None, + block_id=None, + offset=None, + vtype=None, + endpoint=None): + """ + Args: + origin_var(Variable|VarStruct): origin var properties + slice_var(Variable|VarStruct): slice var properties + is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. + block_id(int|None): the number about the slice var. + offset(int|None): if the slice var is sliced, offset is the numel before the var. + vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. + endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" + """ + + if isinstance(origin_var, Variable): + self.origin = self.__create_var_struct(origin_var) + else: + self.origin = origin_var + + if isinstance(slice_var, Variable): + self.slice = self.__create_var_struct(slice_var) + else: + self.slice = slice_var + + if self.equal(self.origin, self.slice): + self.is_slice = False + self.block_id = 0 + self.offset = 0 + else: + self.is_slice = True + self.block_id = 0 + self.offset = 0 + + if is_slice is not None: + self.is_slice = is_slice + if block_id is not None: + self.block_id = block_id + if offset is not None: + self.offset = offset + + self.vtype = vtype + self.endpoint = endpoint + + @staticmethod + def __create_var_struct(var): + return VarStruct(var.name, var.shape, var.dtype, var.type, + var.lod_level, var.persistable) + + @staticmethod + def equal(var1, var2): + """ + the two var is equal or not. + Returns: + bool: equal will return True else False + """ + assert isinstance(var1, VarStruct) and isinstance(var2, VarStruct) + + return var1.name == var2.name and \ + var1.type == var2.type and \ + var1.shape == var2.shape and \ + var1.dtype == var2.dtype and \ + var1.lod_level == var2.lod_level and \ + var1.persistable == var2.persistable + + def __str__(self): + origin_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})". \ + format(i="{", e="}", name=self.origin.name, type=self.origin.type, + shape=self.origin.shape, dtype=self.origin.dtype) + + slice_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})" \ + ".slice({is_slice}).block({block_id}).offset({offset})". \ + format(i="{", e="}", name=self.slice.name, type=self.slice.type, + shape=self.slice.shape, dtype=self.slice.dtype, + is_slice=self.is_slice, block_id=self.block_id, offset=self.offset) + + return "var owned: {}, origin var: ( {} ), slice var: ( {} ), endpoint: {} ".format( + self.vtype, origin_var_str, slice_var_str, self.endpoint) + + +class VarsDistributed(object): + """ + a gather about VarDistributed with many methods to find distributed vars. + through the class, we can get overview about the distributed parameters on parameter servers. + this class may centralized and convenient for developer to manage and get variable's distribute. + other module can also use this to find variables such io.py. + """ + + def __init__(self): + self.distributed_vars = [] + + def add_distributed_var(self, + origin_var, + slice_var, + is_slice=None, + block_id=None, + offset=None, + vtype=None, + endpoint=None): + """ + add distributed var in this. + + Args: + origin_var(Variable|VarStruct): origin var properties + slice_var(Variable|VarStruct): slice var properties + is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. + block_id(int|None): the number about the slice var. + offset(int|None): if the slice var is sliced, offset is the numel before the var. + vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. + endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" + Returns: + None + """ + self.distributed_vars.append( + VarDistributed(origin_var, slice_var, is_slice, block_id, offset, + vtype, endpoint)) + + def get_distributed_var_by_slice(self, var_name): + """ + get distributed var by conditions. + + Args: + var_name(str): slice var name, such as "w.traier0.block1" + Returns: + VarDistributed: distributed var. + """ + for dist_var in self.distributed_vars: + if dist_var.slice.name == var_name: + return dist_var + return None + + @staticmethod + def equal(var1, var2): + """ + the two var is equal or not. + Returns: + bool: equal will return True else False + """ + return var1.name == var2.name and \ + var1.type == var2.type and \ + var1.shape == var2.shape and \ + var1.dtype == var2.dtype and \ + var1.lod_level == var2.lod_level and \ + var1.persistable == var2.persistable + + def get_distributed_var_by_origin_and_ep(self, origin_var_name, endpoint): + """ + get distributed var by conditions. + + Args: + origin_var_name(str): + endpoint(str): the parameter endpoint, such as "127.0.0.1:1001" + Returns: + VarDistributed: distributed var. + """ + for dist_var in self.distributed_vars: + if dist_var.origin.name == origin_var_name and dist_var.endpoint == endpoint: + return dist_var + return None + + def get_distributed_vars_by_vtypes(self, vtypes, groupby=False): + """ + get distributed vars by conditions. + + Args: + vtype(str|None): distributed var's vtype, such as "Optimizer", "RemotePrefetch" + groupby(bool|False): group by origin var or not. + + Returns: + list: distributed var list. + dict: distributed var map when groupby=True + """ + vtype_vars = [] + for var in self.distributed_vars: + if var.vtype in vtypes: + vtype_vars.append(var) + if not groupby: + return vtype_vars + + params_map = {} + for var in vtype_vars: + origin_var_name = var.origin.name + + if origin_var_name in params_map.keys(): + optimizers = params_map.get(origin_var_name) + else: + optimizers = [] + optimizers.append(var) + params_map[origin_var_name] = optimizers + return params_map + + def get_distributed_vars_by_ep(self, endpoint, vtype=None): + """ + get distributed vars by conditions. + + Args: + endpoint(str): the parameter server endpoint, such as "127.0.0.1:2001" + vtype(str|None): distributed var's vtype, such as "Optimizer", "RemotePrefetch" + + Returns: + list: distributed var list. + """ + endpoint_vars = [] + for var in self.distributed_vars: + if var.endpoint == endpoint: + endpoint_vars.append(var) + if not vtype: + return endpoint_vars + + vtype_vars = [] + for var in endpoint_vars: + if var.vtype == vtype: + vtype_vars.append(var) + return vtype_vars + + def overview(self): + """ + get the overview string about all params on all parameter servers. + + Returns: + Str: overview string. + + """ + vars_str = [] + for var in self.distributed_vars: + vars_str.append(str(var)) + return "\n".join(vars_str) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/distribute_transpiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/distribute_transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..31d3c817d1ed5bf44d2fc7fbd4442565d000f150 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/distribute_transpiler.py @@ -0,0 +1,2749 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function +""" +Steps to transpile trainer: +1. split variable to multiple blocks, aligned by product(dim[1:]) (width). +2. rename split grad variables to add trainer_id suffix ".trainer_%d". +3. modify trainer program add split_op to each grad variable. +4. append send_op to send split variables to server and +5. add recv_op to fetch params(split blocks or origin param) from server. +6. append concat_op to merge split blocks to update local weights. + +Steps to transpile pserver: +1. create new program for parameter server. +2. create params and grad variables that assigned to current server instance. +3. create a sub-block in the server side program +4. append ops that should run on current server instance. +5. add listen_and_serv op +""" + +import os +import sys +import math +from functools import reduce + +import collections +import six +import logging + +import numpy as np + +from .ps_dispatcher import RoundRobin, PSDispatcher +from .. import core, framework, unique_name, initializer +from ..framework import Program, default_main_program, \ + default_startup_program, Block, Parameter, grad_var_name +from .details import wait_server_ready, UnionFind, VarStruct, VarsDistributed +from .details import delete_ops, find_op_by_output_arg +from ..distribute_lookup_table import find_distributed_lookup_table +from . import collective + +LOOKUP_TABLE_TYPE = ["lookup_table", "lookup_table_v2"] +LOOKUP_TABLE_GRAD_TYPE = ["lookup_table_grad", "lookup_table_v2_grad"] +OP_NAME_SCOPE = "op_namescope" +CLIP_OP_NAME_SCOPE = "@CLIP" +OP_ROLE_VAR_ATTR_NAME = core.op_proto_and_checker_maker.kOpRoleVarAttrName() +RPC_OP_ROLE_ATTR_NAME = op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName( +) +OPT_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Optimize +RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC +DIST_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.Dist +LR_SCHED_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.LRSched + +PRINT_LOG = False + + +class DistributedMode: + SYNC = 0 + ASYNC = 1 + HALF_ASYNC = 2 + GEO = 3 + + +def log(*args): + if PRINT_LOG: + print(args) + + +class VarBlock: + + def __init__(self, varname, offset, size): + self.varname = varname + # NOTE: real offset is offset * size + self.offset = offset + self.size = size + + def __str__(self): + return "%s:%d:%d" % (self.varname, self.offset, self.size) + + +def same_or_split_var(p_name, var_name): + return p_name == var_name or p_name.startswith(var_name + ".block") + + +def slice_variable(var_list, slice_count, min_block_size): + """ + We may need to split dense tensor to one or more blocks and put + them equally onto parameter server. One block is a sub-tensor + aligned by dim[0] of the tensor. + + We need to have a minimal block size so that the calculations in + the parameter server side can gain better performance. By default + minimum block size 8K elements (maybe 16bit or 32bit or 64bit). + + Args: + var_list (list): List of variables. + slice_count (int): Numel of count that variables will be sliced, which + could be the pserver services' count. + min_block_size (int): Minimum split block size. + Returns: + blocks (list[(varname, block_id, current_block_size)]): A list + of VarBlocks. Each VarBlock specifies a shard of the var. + """ + blocks = [] + for var in var_list: + split_count = slice_count + var_numel = reduce(lambda x, y: x * y, var.shape) + max_pserver_count = int(math.floor(var_numel / float(min_block_size))) + if max_pserver_count == 0: + max_pserver_count = 1 + if max_pserver_count < slice_count: + split_count = max_pserver_count + block_size = int(math.ceil(var_numel / float(split_count))) + + if len(var.shape) >= 2: + # align by dim1(width) + dim1 = reduce(lambda x, y: x * y, var.shape[1:]) + remains = block_size % dim1 + if remains != 0: + block_size += dim1 - remains + # update split_count after aligning + split_count = int(math.ceil(var_numel / float(block_size))) + for block_id in range(split_count): + curr_block_size = min(block_size, + var_numel - ((block_id) * block_size)) + block = VarBlock(var.name, block_id, curr_block_size) + blocks.append(str(block)) + return blocks + + +class DistributeTranspilerConfig(object): + """ + :api_attr: Static Graph + + A configuration class that provide support for transpiler distributed jobs. + Some important parameters are explained as follows: + + + .. py:attribute:: slice_var_up (bool) + + Whether to do Tensor slice for parameter servers, default is True. + + .. py:attribute:: split_method (PSDispatcher) + + Methods of dispatching parameters for server, + :ref:`api_fluid_transpiler_RoundRobin` or + :ref:`api_fluid_transpiler_HashName` can be used and default is RoundRobin. + Try to choose the best method to balance loads for parameter servers. + + .. py:attribute:: min_block_size (int) + + Minimum number of split elements in block, default is 8192. + + According to : https://github.com/PaddlePaddle/Paddle/issues/8638#issuecomment-369912156 + We can use bandwidth efficiently when data size is larger than 2MB.If you + want to change it, please be sure you have read the slice_variable function. You can find + the definition of slice_variable in + https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/fluid/transpiler/distribute_transpiler.py + . + + Examples: + .. code-block:: python + + from paddle.fluid.transpiler.ps_dispatcher import RoundRobin + import paddle.fluid as fluid + + config = fluid.DistributeTranspilerConfig() + config.slice_var_up = True + config.split_method = RoundRobin + config.min_block_size = 81920 + """ + + slice_var_up = True + split_method = None + min_block_size = 8192 + enable_dc_asgd = False + # supported modes: pserver, nccl2, collective + mode = "pserver" + print_log = False + wait_port = True + # split the send recv var in runtime + __runtime_split_send_recv = False + __sync_mode = True + + # half_async + half_async = False + completely_not_async = False + + # Geo-sgd algorithm + geo_sgd_mode = False + geo_sgd_need_push_nums = 100 + + nccl_comm_num = 1 + # The picture here illustrates the principle: + # https://github.com/PaddlePaddle/Paddle/pull/17263#discussion_r285411396 + use_hierarchical_allreduce = False + # Nccl ranks in a node when use hierarchical allreduce, it's set to gpu cards' number in most cases. + hierarchical_allreduce_inter_nranks = 0 + + # if mode is collective + # supported modes: grad_allreduce, local_sgd + collective_mode = None + + def __init__(self): + pass + + @property + def runtime_split_send_recv(self): + return self.__runtime_split_send_recv + + @runtime_split_send_recv.setter + def runtime_split_send_recv(self, value): + if value is None: + raise ValueError("runtime_split_send_recv can't be None") + if value and self.__sync_mode: + raise ValueError( + "if you want to set runtime_split_send_recv to be true, make ensure config.sync_mode is false at first" + ) + self.__runtime_split_send_recv = value + + @property + def sync_mode(self): + return self.__sync_mode + + @sync_mode.setter + def sync_mode(self, value): + if value is None: + raise ValueError("sync_mode can't be None") + if value and self.__runtime_split_send_recv: + raise ValueError( + "if you want to set sync_mode to be true, make ensure config.runtime_split_send_recv is false at first" + ) + self.__sync_mode = value + + +class ServerRuntimeConfig(object): + + def __init__(self): + self._rpc_send_thread_num = int( + os.getenv("FLAGS_rpc_send_thread_num", "12")) + self._rpc_get_thread_num = int( + os.getenv("FLAGS_rpc_get_thread_num", "12")) + self._rpc_prefetch_thread_num = int( + os.getenv("FLAGS_rpc_prefetch_thread_num", "12")) + + +class DistributeTranspiler(object): + """ + :api_attr: Static Graph + + **DistributeTranspiler** + + Convert the fluid program to distributed data-parallelism programs. + Supports two modes: parameter server(pserver) mode and nccl2 mode. + + In pserver mode, the main_program will be transformed to use a remote + parameter server to do parameter optimization. And the optimization + graph will be put into a parameter server program. + + In nccl2 mode, the transpiler will append a NCCL_ID broadcasting + op in startup_program to share the NCCL_ID across the job nodes. + After transpile_nccl2 called, you ***must*** pass trainer_id and + num_trainers argument to ParallelExecutor to enable NCCL2 distributed + mode. + + Examples: + .. code-block:: python + + x = fluid.data(name='x', shape=[13], dtype='float32') + y = fluid.data(name='y', shape=[1], dtype='float32') + y_predict = fluid.layers.fc(input=x, size=1, act=None) + + cost = fluid.layers.square_error_cost(input=y_predict, label=y) + avg_loss = fluid.layers.mean(cost) + + sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001) + sgd_optimizer.minimize(avg_loss) + + # for pserver mode + pserver_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + trainer_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + current_endpoint = "192.168.0.1:6174" + trainer_id = 0 + trainers = 4 + role = "PSERVER" + t = fluid.DistributeTranspiler() + t.transpile( + trainer_id, pservers=pserver_endpoints, trainers=trainers) + if role == "PSERVER": + pserver_program = t.get_pserver_program(current_endpoint) + pserver_startup_program = t.get_startup_program(current_endpoint, + pserver_program) + elif role == "TRAINER": + trainer_program = t.get_trainer_program() + + # for nccl2 mode + trainer_num = 2 + trainer_id = 0 + config = fluid.DistributeTranspilerConfig() + config.mode = "nccl2" + trainer_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + t = fluid.DistributeTranspiler(config=config) + t.transpile(trainer_id=trainer_id, trainers=trainer_endpoints, current_endpoint="192.168.0.1:6174") + exe = fluid.ParallelExecutor( + use_cuda=True, + loss_name=avg_loss.name, + num_trainers=trainer_num, + trainer_id=trainer_id + ) + """ + + def __init__(self, config=None): + if config is not None: + self.config = config + else: + self.config = DistributeTranspilerConfig() + self._set_server_config() + + if self.config.split_method is None: + self.config.split_method = RoundRobin + + if self.config.sync_mode or self.config.completely_not_async: + self.distributed_mode = DistributedMode.SYNC + elif self.config.runtime_split_send_recv: + self.distributed_mode = DistributedMode.ASYNC + else: + self.distributed_mode = DistributedMode.HALF_ASYNC + + global PRINT_LOG + if self.config.print_log: + PRINT_LOG = True + assert (self.config.min_block_size >= 8192) + assert (self.config.split_method.__bases__[0] == PSDispatcher) + self.counter_var = None + + def _set_server_config(self, server_config=None): + if server_config is None: + self.server_config = ServerRuntimeConfig() + elif isinstance(server_config, ServerRuntimeConfig): + self.server_config = server_config + else: + raise TypeError( + "In DistributeTranspiler, server_config must be an instance of ServerRuntimeConfig" + ) + + def _transpile_nccl2(self, + trainer_id, + trainers, + current_endpoint, + startup_program=None, + wait_port=True): + if not startup_program: + startup_program = default_startup_program() + if trainer_id >= 0: + worker_endpoints = trainers.split(",") + # send NCCL_ID to others or recv from trainer 0 + worker_endpoints.remove(current_endpoint) + if trainer_id == 0 and wait_port: + wait_server_ready(worker_endpoints) + + nccl_id_var = startup_program.global_block().create_var( + name="NCCLID", persistable=True, type=core.VarDesc.VarType.RAW) + + for i in range(1, self.config.nccl_comm_num): + startup_program.global_block().create_var( + name="NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + + if self.config.use_hierarchical_allreduce: + for i in range(0, self.config.nccl_comm_num): + startup_program.global_block().create_var( + name="Hierarchical_inter_NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + startup_program.global_block().create_var( + name="Hierarchical_exter_NCCLID_{}".format(i), + persistable=True, + type=core.VarDesc.VarType.RAW) + + startup_program.global_block().append_op( + type="gen_nccl_id", + inputs={}, + outputs={"NCCLID": nccl_id_var}, + attrs={ + "trainers": + trainers.split(","), + "trainer_id": + trainer_id, + "nccl_comm_num": + self.config.nccl_comm_num, + "use_hierarchical_allreduce": + self.config.use_hierarchical_allreduce, + "hierarchical_allreduce_inter_nranks": + self.config.hierarchical_allreduce_inter_nranks + }) + return nccl_id_var + else: + raise ValueError("must set trainer_id > 0") + + def _transpile_collective(self, + collective_mode, + trainer_id, + trainers, + current_endpoint, + startup_program=None, + main_program=None, + wait_port=True): + if isinstance(trainers, str): + endpoints = trainers.split(",") + elif isinstance(trainers, list): + endpoints = trainers + elif collective_mode != "single_process_multi_thread": + raise ValueError('invalid trainers config: ' + str(trainers)) + + if len(endpoints + ) == 1 and collective_mode != "single_process_multi_thread": + raise ValueError('invalid trainer number in distributed: 1') + + if startup_program is None: + startup_program = default_startup_program() + + if main_program is None: + main_program = default_main_program() + + transpiler = None + if collective_mode == 'grad_allreduce': + transpiler = collective.GradAllReduce(self.config.nccl_comm_num) + elif collective_mode == 'local_sgd': + transpiler = collective.LocalSGD(self.config.nccl_comm_num) + elif collective_mode == "single_process_multi_thread": + transpiler = collective.SingleProcessMultiThread() + else: + raise ValueError('invalid collective_mode: %s' % collective_mode) + + transpiler.transpile(startup_program=startup_program, + main_program=main_program, + rank=trainer_id, + endpoints=endpoints, + current_endpoint=current_endpoint, + wait_port=wait_port) + + def _get_all_remote_sparse_update_op(self, main_program): + sparse_update_ops = [] + sparse_update_op_types = ["lookup_table", "nce", "lookup_table_v2"] + for op in main_program.global_block().ops: + if op.type in sparse_update_op_types and op.attr( + 'remote_prefetch') is True: + sparse_update_ops.append(op) + return sparse_update_ops + + def _update_remote_sparse_update_op(self, program, + need_sparse_update_params): + + for param_varname, attrs in need_sparse_update_params.items(): + height_sections = self.sparse_param_to_height_sections[ + param_varname] + endpoints = attrs[0] + table_names = attrs[1] + + ops = [] + op_type = "" + used_ops = [] + + for idx, op in enumerate(self.sparse_update_ops): + if param_varname in op.input_arg_names and op_type == "": + op_type = op.type + ops.append(op) + used_ops.append(idx) + + elif param_varname in op.input_arg_names and op_type == op.type: + ops.append(op) + used_ops.append(idx) + + if op_type in LOOKUP_TABLE_TYPE: + all_ops = program.global_block().ops + op_idxs = [all_ops.index(op) for op in ops] + inputs = [ + program.global_block().vars[op.input("Ids")[0]] + for op in ops + ] + w = program.global_block().vars[ops[0].input("W")[0]] + padding_idx = ops[0].attr("padding_idx") + outputs = [ + program.global_block().vars[op.output("Out")[0]] + for op in ops + ] + + for idx in op_idxs[::-1]: + program.global_block()._remove_op(idx) + + inputs_idxs = [-1] * len(inputs) + outputs_idxs = [-1] * len(outputs) + + for idx, op in enumerate(program.global_block().ops): + for i in range(0, len(op.output_names)): + outs = op.output(op.output_names[i]) + for in_id, in_var in enumerate(inputs): + if in_var.name in outs: + inputs_idxs[in_id] = idx + for i in range(0, len(op.input_names)): + ins = op.input(op.input_names[i]) + for out_id, out_var in enumerate(outputs): + if out_var.name in ins: + outputs_idxs[out_id] = idx + + if min(outputs_idxs) - max(inputs_idxs) >= 1: + distributed_idx = max(inputs_idxs) + 1 + + program.global_block()._insert_op( + index=distributed_idx, + type="distributed_lookup_table", + inputs={ + "Ids": inputs, + 'W': w + }, + outputs={"Outputs": outputs}, + attrs={ + "table_names": table_names, + "height_sections": height_sections, + "endpoints": endpoints, + "padding_idx": padding_idx, + "trainer_id": self.trainer_id, + "lookup_table_version": op_type + }) + else: + raise ValueError( + "something wrong with distribute_transpiler, submit a issue is recommended" + ) + + for idx in used_ops[::-1]: + self.sparse_update_ops.pop(idx) + + def _is_input_of_remote_sparse_update_op(self, param_name): + for op in self.sparse_update_ops: + if param_name in op.input_arg_names: + return True + return False + + def transpile(self, + trainer_id, + program=None, + pservers="127.0.0.1:6174", + trainers=1, + sync_mode=True, + startup_program=None, + current_endpoint="127.0.0.1:6174"): + """ + Transpile the input program to distributed programs with config and arguments. + + Args: + trainer_id (int): id for current trainer worker, if you have + n workers, the id may range from 0 ~ n-1 + program (Program|None): program to transpile, + default is fluid.default_main_program(). + startup_program (Program|None): startup_program to transpile, + default is fluid.default_startup_program(). + pservers (str): comma separated ip:port string for the pserver + list. + trainers (int|str): in pserver mode this is the number of + trainers, in nccl2 mode this is a string of trainer + endpoints. + sync_mode (bool): Do sync training or not, default is True. + startup_program (Program|None): startup_program to transpile, + default is fluid.default_main_program(). + current_endpoint (str): need pass current endpoint when + transpile as nccl2 distributed mode. In pserver mode + this argument is not used. + + Examples: + .. code-block:: python + + transpiler = fluid.DistributeTranspiler() + t.transpile( + trainer_id=0, + pservers="127.0.0.1:7000,127.0.0.1:7001", + trainers=2, + sync_mode=False, + current_endpoint="127.0.0.1:7000") + """ + + err_msg = """ + +API is deprecated since 2.0.0 Please use FleetAPI instead. +WIKI: https://github.com/PaddlePaddle/Fleet/blob/develop/markdown_doc/transpiler + + """ + print(err_msg, file=sys.stderr) + + if program is None: + program = default_main_program() + if startup_program is None: + startup_program = default_startup_program() + self.origin_program = program + self.startup_program = startup_program + self.origin_startup_program = self.startup_program.clone() + + if self.config.mode == "nccl2": + assert (isinstance(trainers, str)) + self.origin_program._trainers_endpoints = trainers.split(",") + self.origin_program._nccl_comm_num = self.config.nccl_comm_num + self.origin_program._use_hierarchical_allreduce = self.config.use_hierarchical_allreduce + # check use_hierarchical_allreduce options + if self.config.use_hierarchical_allreduce: + trainers_num = len(self.origin_program._trainers_endpoints) + # selected automaticly + if self.config.hierarchical_allreduce_inter_nranks <= 1: + self.config.hierarchical_allreduce_inter_nranks = core.get_cuda_device_count( + ) + + assert trainers_num > self.config.hierarchical_allreduce_inter_nranks, \ + "trainers_num:{} < hierarchical_allreduce_inter_nranks:{}".format( + trainers_num, self.config.hierarchical_allreduce_inter_nranks) + + assert trainers_num % self.config.hierarchical_allreduce_inter_nranks == 0, \ + "trainers_num:{} mod hierarchical_allreduce_inter_nranks:{} != 0".format( + trainers_num, self.config.hierarchical_allreduce_inter_nranks) + + self.origin_program._hierarchical_allreduce_inter_nranks = \ + int(self.config.hierarchical_allreduce_inter_nranks) + + self._transpile_nccl2(trainer_id, + trainers, + current_endpoint, + startup_program=startup_program, + wait_port=self.config.wait_port) + return + + if self.config.mode == "collective": + self._transpile_collective( + collective_mode=self.config.collective_mode, + trainer_id=trainer_id, + trainers=trainers, + current_endpoint=current_endpoint, + startup_program=startup_program, + main_program=program, + wait_port=self.config.wait_port) + return + + self.trainer_num = trainers + self.sync_mode = sync_mode + self.trainer_id = trainer_id + pserver_endpoints = pservers.split(",") + self.pserver_endpoints = pserver_endpoints + self.vars_overview = VarsDistributed() + self.optimize_ops, self.params_grads = self._get_optimize_pass() + + ps_dispatcher = self.config.split_method(self.pserver_endpoints) + self.table_name = find_distributed_lookup_table(self.origin_program) + self.has_distributed_lookup_table = self.table_name != None + self.param_name_to_grad_name = dict() + self.grad_name_to_param_name = dict() + for param_var, grad_var in self.params_grads: + self.param_name_to_grad_name[param_var.name] = grad_var.name + self.grad_name_to_param_name[grad_var.name] = param_var.name + + # get all sparse update ops + self.sparse_update_ops = self._get_all_remote_sparse_update_op( + self.origin_program) + # use_sparse_update_param_name -> split_height_section + self.sparse_param_to_height_sections = dict() + self.need_delete_optimize_vars = [] + + # add distributed attrs to program + self.origin_program._is_distributed = True + self.origin_program._endpoints = self.pserver_endpoints + self.origin_program._ps_endpoint = current_endpoint + self.origin_program._is_chief = self.trainer_id == 0 + self.origin_program._distributed_lookup_table = self.table_name if self.table_name else None + + # split and create vars, then put split vars in dicts for later use. + # step 1: split and create vars, then put split vars in dicts for later use. + self._init_splited_vars() + + # step 2: insert send op to send gradient vars to parameter servers + ps_dispatcher.reset() + send_vars = [] + + # in general cases, the number of pservers is times of 2, and this + # will lead to uneven distribution among weights and bias: + # fc_w@GRAD_trainer_0, fc_w@GRAD_trainer_1 --> pserver1 + # fc_b@GRAD_trainer_0, fc_b@GRAD_trainer_1 --> pserver2 + # shuffle the map will avoid the uneven distribution above + grad_var_mapping_items = list(six.iteritems(self.grad_var_mapping)) + + if not self.config.slice_var_up: + np.random.seed(self.origin_program.random_seed) + np.random.shuffle(grad_var_mapping_items) + + self.grad_name_to_send_dummy_out = dict() + + for grad_varname, splited_vars in grad_var_mapping_items: + eplist = ps_dispatcher.dispatch(splited_vars) + + if not self.config.slice_var_up: + assert (len(splited_vars) == 1) + + splited_grad_varname = grad_varname + if len(splited_vars) == 1: + splited_grad_varname = splited_vars[0].name + index = find_op_by_output_arg(program.global_block(), + splited_grad_varname, + reverse=True) + + elif len(splited_vars) > 1: + orig_var = program.global_block().vars[splited_grad_varname] + index = find_op_by_output_arg(program.global_block(), + splited_grad_varname, + reverse=True) + + if not self.config.runtime_split_send_recv: + self._insert_split_op(program, orig_var, index, + splited_vars) + index += 1 + else: + AssertionError( + "Can not insert the send op by original " + "variable name :", splited_grad_varname) + + if splited_vars[0].type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_param_name = self.grad_name_to_param_name[grad_varname] + if self._is_input_of_remote_sparse_update_op(sparse_param_name): + self.sparse_param_to_height_sections[sparse_param_name] = [ + splited_var.shape[0] for splited_var in splited_vars + ] + + dummy_output = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + self.grad_name_to_send_dummy_out[grad_varname] = dummy_output + + if self.config.runtime_split_send_recv: + send_input_vars = [ + program.global_block().vars[splited_grad_varname] + ] + sections = self._get_splited_var_sections(splited_vars) + + if self.config.completely_not_async and self.trainer_num > 1: + send_varnames = [ + "{}.trainer_{}".format(var.name, self.trainer_id) + for var in splited_vars + ] + else: + send_varnames = [var.name for var in splited_vars] + else: + send_input_vars = splited_vars + sections = [] + send_varnames = [] + + # get send op_role_var, if not split, the grad should have .trainer suffix + # if split, grad should be the original grad var name (split_by_ref and send + # will be on the same place). ParallelExecutor + # will use op_role_var to get expected device place to run this op. + program.global_block()._insert_op( + index=index + 1, + type="send", + inputs={"X": send_input_vars}, + outputs={"Out": dummy_output}, + attrs={ + "epmap": + eplist, + "sections": + sections, + "send_varnames": + send_varnames, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE, + OP_ROLE_VAR_ATTR_NAME: [ + self.grad_name_to_param_name[grad_varname], + splited_grad_varname + ] + }) + for _, var in enumerate(splited_vars): + send_vars.append(var) + + send_barrier_out = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + if self.has_distributed_lookup_table: + self.grad_name_to_send_dummy_out[ + self.table_name] = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + input_deps = list(self.grad_name_to_send_dummy_out.values()) + + if not self.sync_mode: + lr_ops = self._get_lr_ops() + if len(lr_ops) > 0 and self.counter_var: + decay_dummy_output = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + if self.config.runtime_split_send_recv: + # async mode, using communicator to merge and send + send_varnames = [self.counter_var.name] + else: + send_varnames = [] + sections = [] + program.global_block().append_op( + type="send", + inputs={"X": self.counter_var}, + outputs={"Out": decay_dummy_output}, + attrs={ + "epmap": + pserver_endpoints, + "sections": + sections, + "send_varnames": + send_varnames, + "merge_add": + True, + "use_send_handler": + False, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE, + OP_ROLE_VAR_ATTR_NAME: + [self.counter_var.name, self.counter_var.name] + }) + input_deps.append(decay_dummy_output) + + if self.sync_mode: + fetch_barrier_input = [] + + program.global_block().append_op(type="send_barrier", + inputs={"X": list(input_deps)}, + outputs={"Out": send_barrier_out}, + attrs={ + "endpoints": + pserver_endpoints, + "trainer_id": + self.trainer_id, + "half_async": + False, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + fetch_barrier_input.append(send_barrier_out) + else: + if self.config.runtime_split_send_recv and self.config.half_async: + program.global_block().append_op( + type="send_barrier", + inputs={"X": list(input_deps)}, + outputs={"Out": send_barrier_out}, + attrs={ + "endpoints": pserver_endpoints, + "trainer_id": self.trainer_id, + "half_async": True, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + # step 3: insert recv op to receive parameters from parameter server + recv_vars = [] + for _, var in enumerate(send_vars): + recv_vars.append(self.grad_param_mapping[var]) + ps_dispatcher.reset() + eplist = ps_dispatcher.dispatch(recv_vars) + + for i, ep in enumerate(eplist): + self.param_grad_ep_mapping[ep]["params"].append(recv_vars[i]) + self.param_grad_ep_mapping[ep]["grads"].append(send_vars[i]) + + distributed_var = self.vars_overview.get_distributed_var_by_slice( + recv_vars[i].name) + distributed_var.endpoint = ep + + need_sparse_update_params = {} + + # step4: Concat the parameters splits together after recv. + all_recv_outputs = [] + for param_varname, splited_var in six.iteritems(self.param_var_mapping): + eps = [] + table_names = [] + for var in splited_var: + index = [v.name for v in recv_vars].index(var.name) + eps.append(eplist[index]) + table_names.append(var.name) + if self.sync_mode: + recv_dep_in = send_barrier_out + else: + # connect deps to send op in async mode + recv_dep_in = self.grad_name_to_send_dummy_out[ + self.param_name_to_grad_name[param_varname]] + + # get recv op_role_var, if not split, the grad should have .trainer suffix + # if split, grad should be the original grad var name. ParallelExecutor + # will use op_role_var to get expected device place to run this op. + orig_grad_name = self.param_name_to_grad_name[param_varname] + recv_op_role_var_name = orig_grad_name + splited_trainer_grad = self.grad_var_mapping[orig_grad_name] + if len(splited_trainer_grad) == 1: + recv_op_role_var_name = splited_trainer_grad[0].name + + if param_varname in self.sparse_param_to_height_sections: + for table_name in table_names: + distributed_var = self.vars_overview.get_distributed_var_by_slice( + table_name) + distributed_var.vtype = "RemotePrefetch" + + need_sparse_update_params[param_varname] = (eps, table_names) + else: + recv_varnames = [] + if self.config.runtime_split_send_recv: + orig_param = program.global_block().vars[param_varname] + recv_varnames = [var.name for var in splited_var] + splited_var = [orig_param] + all_recv_outputs.extend(splited_var) + + program.global_block().append_op( + type="recv", + inputs={"X": [recv_dep_in]}, + outputs={"Out": splited_var}, + attrs={ + "epmap": + eps, + "recv_varnames": + recv_varnames, + "trainer_id": + self.trainer_id, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE, + OP_ROLE_VAR_ATTR_NAME: + [param_varname, recv_op_role_var_name] + }) + + self._update_remote_sparse_update_op(program, need_sparse_update_params) + + if self.sync_mode: + # form a WAW dependency + program.global_block().append_op(type="fetch_barrier", + inputs={"X": fetch_barrier_input}, + outputs={"Out": all_recv_outputs}, + attrs={ + "endpoints": + pserver_endpoints, + "trainer_id": + self.trainer_id, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE + }) + + for param_varname, splited_var in six.iteritems(self.param_var_mapping): + if len(splited_var) <= 1: + continue + orig_param = program.global_block().vars[param_varname] + if param_varname not in self.sparse_param_to_height_sections: + if not self.config.runtime_split_send_recv: + program.global_block().append_op( + type="concat", + inputs={"X": splited_var}, + outputs={"Out": [orig_param]}, + attrs={ + "axis": 0, + RPC_OP_ROLE_ATTR_NAME: DIST_OP_ROLE_ATTR_VALUE + }) + + self._get_trainer_startup_program(recv_vars=recv_vars, eplist=eplist) + + if self.has_distributed_lookup_table: + self._replace_lookup_table_op_with_prefetch(program, + pserver_endpoints) + self._split_table_grad_and_add_send_vars(program, pserver_endpoints) + + self._get_distributed_optimizer_vars() + self.origin_program._parameters_on_pservers = self.vars_overview + + def _get_sparse_table_names(self): + sparse_update_op_types = ["lookup_table", "nce"] + + sparse_table_names = [] + for op in self.origin_program.global_block().ops: + if op.type in sparse_update_op_types and op.attr( + 'is_sparse') is True: + sparse_table_names.append(op.input("W")[0]) + if op.type == "distributed_lookup_table": + sparse_table_names.append(op.input("W")[0]) + + if self.has_distributed_lookup_table: + sparse_table_names.append(self.table_name) + + return list(set(sparse_table_names)) + + def _fake_init_sparsetable(self, sparse_table_names): + # delete table init op + for table_name in sparse_table_names: + table_var = self.startup_program.global_block().vars[table_name] + table_param_init_op = [] + for op in self.startup_program.global_block().ops: + if table_name in op.output_arg_names: + table_param_init_op.append(op) + init_op_num = len(table_param_init_op) + if init_op_num != 1: + raise ValueError("table init op num should be 1, now is " + + str(init_op_num)) + table_init_op = table_param_init_op[0] + self.startup_program.global_block().append_op( + type="fake_init", + inputs={}, + outputs={"Out": table_var}, + attrs={"shape": table_init_op.attr('shape')}) + delete_ops(self.startup_program.global_block(), table_param_init_op) + + def _delete_trainer_optimizer(self, is_startup): + optimize_vars = [] + optimize_op_role_vars = [] + optimize_need_delete_vars = [] + + for op in self.optimize_ops: + optimize_vars.extend(op.input_arg_names) + optimize_op_role_vars.extend(op.attr("op_role_var")) + + optimize_vars = list(set(optimize_vars)) + optimize_op_role_vars = list(set(optimize_op_role_vars)) + + for var in optimize_vars: + if var not in optimize_op_role_vars: + optimize_need_delete_vars.append(var) + need_delete_optimize_vars = list(set(optimize_need_delete_vars)) + + if is_startup: + init_ops = [] + for var in need_delete_optimize_vars: + param_init_op = [] + for op in self.startup_program.global_block().ops: + if var in op.output_arg_names: + param_init_op.append(op) + init_ops.extend(param_init_op) + delete_ops(self.startup_program.global_block(), init_ops) + + for var in need_delete_optimize_vars: + if self.startup_program.global_block().has_var(var): + self.startup_program.global_block()._remove_var(var) + else: + delete_ops(self.origin_program.global_block(), self.optimize_ops) + for var in need_delete_optimize_vars: + if self.origin_program.global_block().has_var(var): + self.origin_program.global_block()._remove_var(var) + + def get_trainer_program(self, wait_port=True): + """ + Get transpiled trainer side program. The program on trainer side compared with origin program + has following difference: + + - Delete optimizer related op, because parameter updated on Pserver + - After the op which computed gradient of each parameter, add ``Send_op`` and ``Recv_op`` + + Args: + wait_port(bool): Whether to wait for the parameter server to be ready before returning to program, + default is True + + Returns: + Program: trainer side program. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + #this is an example, find available endpoints in your case + pserver_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + trainer_id = 0 + trainers = 4 + t = fluid.DistributeTranspiler() + t.transpile(trainer_id, trainers=trainers, pservers=pserver_endpoints) + trainer_program = t.get_trainer_program() + """ + # remove optimize ops and add a send op to main_program + # FIXME(typhoonzero): Also ops like clip_gradient, lrn_decay? + + self._delete_trainer_optimizer(is_startup=True) + sparse_table_names = self._get_sparse_table_names() + self._fake_init_sparsetable(sparse_table_names) + + lr_ops = self._get_lr_ops() + delete_ops(self.origin_program.global_block(), lr_ops) + self._delete_trainer_optimizer(is_startup=False) + + self.origin_program.__str__() + self.startup_program.__str__() + + if wait_port: + wait_server_ready(self.pserver_endpoints) + + return self.origin_program + + def _get_trainer_startup_program(self, recv_vars, eplist): + """ + Get transpiled trainer side startup program. + + Args: + recv_vars (list): Variable list to recv for current trainer_id + eplist (list): A list of strings indicating + + Returns: + Program: trainer side startup program. + """ + startup_program = self.startup_program + + # FIXME(gongwb): delete not need ops. + # note that: some parameter is not trainable and those ops can't be deleted. + sparse_table_names = self._get_sparse_table_names() + + # self._fake_init_sparsetable(sparse_table_names) + # self._delete_trainer_optimizer(is_startup=True) + + for varname, splited_var in six.iteritems(self.param_var_mapping): + if varname in sparse_table_names: + continue + # Get the eplist of recv vars + eps = [] + for var in splited_var: + index = [v.name for v in recv_vars].index(var.name) + eps.append(eplist[index]) + + for var in splited_var: + if startup_program.global_block().has_var(var.name): + continue + + startup_program.global_block().create_var( + name=var.name, + persistable=False, + type=var.type, + dtype=var.dtype, + shape=var.shape, + lod_level=var.lod_level) + + op = startup_program.global_block().append_op( + type="recv", + inputs={"X": []}, + outputs={"Out": splited_var}, + attrs={ + "epmap": eps, + "trainer_id": self.trainer_id, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + fetch_barrier_out = startup_program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + startup_program.global_block().append_op( + type="fetch_barrier", + inputs={}, + outputs={"Out": fetch_barrier_out}, + attrs={ + "endpoints": self.pserver_endpoints, + "trainer_id": self.trainer_id, + RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + for varname, splited_var in six.iteritems(self.param_var_mapping): + if varname in sparse_table_names: + continue + # add concat ops to merge split parameters received from parameter servers. + if len(splited_var) <= 1: + continue + # NOTE: if enable memory optimization, origin vars maybe removed. + if varname in startup_program.global_block().vars: + orig_param = startup_program.global_block().vars[varname] + else: + origin_param_var = self.origin_program.global_block( + ).vars[varname] + orig_param = startup_program.global_block().create_var( + name=varname, + persistable=origin_param_var.persistable, + type=origin_param_var.type, + dtype=origin_param_var.dtype, + shape=origin_param_var.shape) + startup_program.global_block().append_op( + type="concat", + inputs={"X": splited_var}, + outputs={"Out": [orig_param]}, + attrs={"axis": 0}) + + return startup_program + + def get_pserver_program(self, endpoint): + """ + Get parameter server side program.The program on pserver side compared with origin program + has following difference: + + - Only the following op is included: optimize-related op and communication-related op + - NO.0 block only has variable definitions and ``listen_and_serv_op`` + - Every variable which need to be updated has a unique block + + Args: + endpoint (str): current parameter server endpoint. + + Returns: + Program: the program for current parameter server to run. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + #this is an example, find available endpoints in your case + pserver_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + current_endpoint = "192.168.0.1:6174" + trainer_id = 0 + trainers = 4 + t = fluid.DistributeTranspiler() + t.transpile( + trainer_id, pservers=pserver_endpoints, trainers=trainers) + pserver_program = t.get_pserver_program(current_endpoint) + """ + # TODO(panyx0718): Revisit this assumption. what if #blocks > #pservers. + # NOTE: assume blocks of the same variable is not distributed + # on the same pserver, only change param/grad varnames for + # trainers to fetch. + sys.stderr.write( + "get_pserver_program() is deprecated, call get_pserver_programs() to get pserver main and startup in a single call.\n" + ) + # step1 + pserver_program = Program() + pserver_program.random_seed = self.origin_program.random_seed + pserver_program._copy_dist_param_info_from(self.origin_program) + + # step2: Create vars to receive vars at parameter servers. + recv_inputs = [] + for v in self.param_grad_ep_mapping[endpoint]["params"]: + self._clone_var(pserver_program.global_block(), v) + for v in self.param_grad_ep_mapping[endpoint]["grads"]: + # create vars for each trainer in global scope, so + # we don't need to create them when grad arrives. + # change client side var name to origin name by + # removing ".trainer_%d" suffix + suff_idx = v.name.find(".trainer_") + if suff_idx >= 0: + orig_var_name = v.name[:suff_idx] + else: + orig_var_name = v.name + # NOTE: single_trainer_var must be created for multi-trainer + # case to merge grads from multiple trainers + single_trainer_var = \ + pserver_program.global_block().create_var( + name=orig_var_name, + persistable=True, + type=v.type, + dtype=v.dtype, + shape=v.shape) + if self.sync_mode or self.config.completely_not_async and self.trainer_num > 1: + for trainer_id in range(self.trainer_num): + var = pserver_program.global_block().create_var( + name="%s.trainer_%d" % (orig_var_name, trainer_id), + persistable=False, + type=v.type, + dtype=v.dtype, + shape=v.shape) + recv_inputs.append(var) + else: + recv_inputs.append(single_trainer_var) + + # step 3 + # Create a union-find data structure from optimize ops, + # If two ops are connected, we could add these two ops + # into one set. + ufind = self._create_ufind(self.optimize_ops) + # step 3.2 + # Iterate through the ops and append optimize op which + # located on current pserver + opt_op_on_pserver = [] + for _, op in enumerate(self.optimize_ops): + if self._is_optimizer_op(op) and self._is_opt_op_on_pserver( + endpoint, op): + opt_op_on_pserver.append(op) + # step 3.3 + # prepare if dc asgd is enabled + if self.config.enable_dc_asgd == True: + assert (self.sync_mode == False) + self.param_bak_list = [] + # add param_bak for each trainer + for p in self.param_grad_ep_mapping[endpoint]["params"]: + # each parameter should have w_bak for each trainer id + for i in range(self.trainer_num): + param_bak_name = "%s.trainer_%d_bak" % (p.name, i) + tmpvar = pserver_program.global_block().create_var( + # NOTE: this var name format is used in `request_get_handler` + name=param_bak_name, + type=p.type, + shape=p.shape, + dtype=p.dtype) + self.param_bak_list.append((p, tmpvar)) + + # step 3.4 + # Iterate through the ops, and if an op and the optimize ops + # which located on current pserver are in one set, then + # append it into the sub program. + + global_ops = [] + + # sparse grad name to param name + sparse_grad_to_param = [] + + def __append_optimize_op__(op, block, grad_to_block_id, merged_var, + lr_ops): + if self._is_optimizer_op(op): + self._append_pserver_ops(block, op, endpoint, grad_to_block_id, + self.origin_program, merged_var, + sparse_grad_to_param) + elif op not in lr_ops: + self._append_pserver_non_opt_ops(block, op) + + def __clone_lr_op_sub_block__(op, program, lr_block): + if not op.has_attr('sub_block'): + return + + origin_block_desc = op.attr('sub_block') + origin_block = self.origin_program.block(origin_block_desc.id) + assert isinstance(origin_block, Block) + # we put the new sub block to new block to follow the block + # hierarchy of the original blocks + new_sub_block = program._create_block(lr_block.idx) + + # clone vars + for var in origin_block.vars: + new_sub_block._clone_variable(var) + + # clone ops + for origin_op in origin_block.ops: + cloned_op = self._clone_lr_op(program, new_sub_block, origin_op) + # clone sub_block of op + __clone_lr_op_sub_block__(cloned_op, program, new_sub_block) + + # reset the block of op + op._set_attr('sub_block', new_sub_block) + + # append lr decay ops to the child block if exists + lr_ops = self._get_lr_ops() + # record optimize blocks and we can run them on pserver parallel + optimize_blocks = [] + + lr_decay_block_id = -1 + if len(lr_ops) > 0: + lr_decay_block = pserver_program._create_block( + pserver_program.num_blocks - 1) + optimize_blocks.append(lr_decay_block) + for _, op in enumerate(lr_ops): + cloned_op = self._append_pserver_non_opt_ops(lr_decay_block, op) + # append sub blocks to pserver_program in lr_decay_op + __clone_lr_op_sub_block__(cloned_op, pserver_program, + lr_decay_block) + lr_decay_block_id = lr_decay_block.idx + + # append op to the current block + grad_to_block_id = [] + pre_block_idx = pserver_program.num_blocks - 1 + for idx, opt_op in enumerate(opt_op_on_pserver): + per_opt_block = pserver_program._create_block(pre_block_idx) + optimize_blocks.append(per_opt_block) + optimize_target_param_name = opt_op.attr(OP_ROLE_VAR_ATTR_NAME)[0] + # append grad merging ops before clip and weight decay + # e.g. merge grad -> L2Decay op -> clip op -> optimize + merged_var = None + for _, op in enumerate(self.optimize_ops): + # find the origin grad var before clipping/L2Decay, + # merged_var should be the input var name of L2Decay + grad_varname_for_block = op.attr(OP_ROLE_VAR_ATTR_NAME)[1] + if op.attr( + OP_ROLE_VAR_ATTR_NAME)[0] == optimize_target_param_name: + merged_var = self._append_pserver_grad_merge_ops( + per_opt_block, grad_varname_for_block, endpoint, + grad_to_block_id, self.origin_program) + if merged_var: + break # append optimize op once then append other ops. + if merged_var: + for _, op in enumerate(self.optimize_ops): + # optimizer is connected to itself + if op.attr(OP_ROLE_VAR_ATTR_NAME)[0] == optimize_target_param_name and \ + op not in global_ops: + log("append opt op: ", op.type, op.input_arg_names, + merged_var) + __append_optimize_op__(op, per_opt_block, + grad_to_block_id, merged_var, + lr_ops) + + # dedup grad to ids list + grad_to_block_id = list(set(grad_to_block_id)) + # append global ops + if global_ops: + opt_state_block = pserver_program._create_block( + pserver_program.num_blocks - 1) + optimize_blocks.append(opt_state_block) + for glb_op in global_ops: + __append_optimize_op__(glb_op, opt_state_block, + grad_to_block_id, None, lr_ops) + + # process distributed lookup_table + prefetch_var_name_to_block_id = [] + if self.has_distributed_lookup_table: + pserver_index = self.pserver_endpoints.index(endpoint) + table_opt_block = self._create_table_optimize_block( + pserver_index, pserver_program, pre_block_idx, grad_to_block_id) + optimize_blocks.append(table_opt_block) + lookup_table_var_name_to_block_id = self._create_prefetch_block( + pserver_index, pserver_program, table_opt_block) + checkpoint_block_id = self._create_checkpoint_save_block( + pserver_program, table_opt_block.idx) + + pserver_program._distributed_lookup_table = self.table_name + prefetch_var_name_to_block_id.extend( + lookup_table_var_name_to_block_id) + + if len(optimize_blocks) == 0: + logging.warn("pserver [" + str(endpoint) + + "] has no optimize block!!") + pre_block_idx = pserver_program.num_blocks - 1 + empty_block = pserver_program._create_block(pre_block_idx) + optimize_blocks.append(empty_block) + + # In some case, some parameter server will have no parameter to optimize + # So we give an empty optimize block to parameter server. + attrs = { + "optimize_blocks": optimize_blocks, + "endpoint": endpoint, + "pserver_id": self.pserver_endpoints.index(endpoint), + "Fanin": self.trainer_num, + "distributed_mode": self.distributed_mode, + "grad_to_block_id": grad_to_block_id, + "sparse_grad_to_param": sparse_grad_to_param, + "lr_decay_block_id": lr_decay_block_id, + "rpc_get_thread_num": self.server_config._rpc_get_thread_num, + "rpc_send_thread_num": self.server_config._rpc_send_thread_num, + "rpc_prefetch_thread_num": + self.server_config._rpc_prefetch_thread_num + } + + if self.has_distributed_lookup_table: + attrs['checkpint_block_id'] = checkpoint_block_id + if self.config.enable_dc_asgd: + attrs['dc_asgd'] = True + + if len(prefetch_var_name_to_block_id) > 0: + attrs[ + 'prefetch_var_name_to_block_id'] = prefetch_var_name_to_block_id + + # step5 append the listen_and_serv op + pserver_program.global_block().append_op(type="listen_and_serv", + inputs={'X': recv_inputs}, + outputs={}, + attrs=attrs) + + pserver_program._sync_with_cpp() + # save pserver program to generate pserver side startup relatively. + self.pserver_program = pserver_program + return pserver_program + + def get_pserver_programs(self, endpoint): + """ + Get pserver side main program and startup program for distributed training. + The ``main_program`` returned by this function is consistent with the + return value of the function ``get_pserver_program`` . + + Args: + endpoint (str): current pserver endpoint. + + Returns: + tuple: (main_program, startup_program), of type "Program" + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + #this is an example, find available endpoints in your case + pserver_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + current_endpoint = "192.168.0.1:6174" + trainer_id = 0 + trainers = 4 + t = fluid.DistributeTranspiler() + t.transpile( + trainer_id, pservers=pserver_endpoints, trainers=trainers) + pserver_program, pserver_startup_program = t.get_pserver_programs(current_endpoint) + """ + pserver_prog = self.get_pserver_program(endpoint) + pserver_startup = self.get_startup_program(endpoint, + pserver_program=pserver_prog) + return pserver_prog, pserver_startup + + def get_startup_program(self, + endpoint, + pserver_program=None, + startup_program=None): + """ + **Deprecated** + + Get startup program for current parameter server. + Modify operator input variables if there are variables that + were split to several blocks. + + Args: + endpoint (str): current pserver endpoint. + pserver_program (Program): deprecated, call get_pserver_program first. + startup_program (Program): deprecated, should pass startup_program + when initializing + + Returns: + Program: parameter server side startup program. + + Examples: + .. code-block:: python + + pserver_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + trainer_endpoints = "192.168.0.1:6174,192.168.0.2:6174" + current_endpoint = "192.168.0.1:6174" + trainer_id = 0 + trainers = 4 + + t = fluid.DistributeTranspiler() + t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers) + pserver_program = t.get_pserver_program(current_endpoint) + pserver_startup_program = t.get_startup_program(current_endpoint, + pserver_program) + """ + s_prog = Program() + orig_s_prog = self.startup_program + s_prog.random_seed = orig_s_prog.random_seed + params = self.param_grad_ep_mapping[endpoint]["params"] + + def _get_splited_name_and_shape(varname): + for idx, splited_param in enumerate(params): + pname = splited_param.name + if same_or_split_var(pname, varname) and varname != pname: + return pname, splited_param.shape + return "", [] + + # 1. create vars in pserver program to startup program + pserver_vars = pserver_program.global_block().vars + created_var_map = collections.OrderedDict() + for _, var in six.iteritems(pserver_vars): + tmpvar = s_prog.global_block()._clone_variable(var) + created_var_map[var.name] = tmpvar + + # 2. rename op outputs + for op in orig_s_prog.global_block().ops: + new_outputs = collections.OrderedDict() + # do not append startup op if var is not on this pserver + op_on_pserver = False + # TODO(gongwb): remove this line. + if op.type not in ["recv", "fetch_barrier", "concat"]: + for key in op.output_names: + newname, _ = _get_splited_name_and_shape(op.output(key)[0]) + if newname: + op_on_pserver = True + new_outputs[key] = created_var_map[newname] + elif op.output(key)[0] in pserver_vars: + op_on_pserver = True + new_outputs[key] = pserver_vars[op.output(key)[0]] + + if op_on_pserver: + # most startup program ops have no inputs + new_inputs = self._get_input_map_from_op(pserver_vars, op) + + if op.type in [ + "gaussian_random", "fill_constant", "uniform_random", + "truncated_gaussian_random" + ]: + op._set_attr("shape", list(new_outputs["Out"].shape)) + s_prog.global_block().append_op(type=op.type, + inputs=new_inputs, + outputs=new_outputs, + attrs=op.all_attrs()) + if self.config.enable_dc_asgd: + for p, p_bak in self.param_bak_list: + startup_param_var = s_prog.global_block().vars[p.name] + startup_tmpvar = s_prog.global_block().vars[p_bak.name] + # copy init random value to param_bak + s_prog.global_block().append_op(type="assign", + inputs={"X": startup_param_var}, + outputs={"Out": startup_tmpvar}) + + return s_prog + + # ====================== private transpiler functions ===================== + def _get_slice_var_info(self, slice_var): + block_suffix = "block" + block_idx = 0 + offset = 0 + is_slice = False + + orig_var_name, block_name, _ = self._get_varname_parts(slice_var.name) + + if not block_name: + return is_slice, block_idx, offset + + block_idx = int(block_name.split(block_suffix)[1]) + skip_dim0 = 0 + slice_vars = self.param_var_mapping[orig_var_name] + + orig_dim1_flatten = 1 + + if len(slice_vars[0].shape) >= 2: + orig_dim1_flatten = reduce(lambda x, y: x * y, + slice_vars[0].shape[1:]) + + for slice_var in slice_vars[:block_idx]: + skip_dim0 += slice_var.shape[0] + + offset = skip_dim0 * orig_dim1_flatten + is_slice = True + return is_slice, block_idx, offset + + def _get_distributed_optimizer_vars(self): + + def _get_distributed_optimizer_var(endpoint): + opt_op_on_pserver = [] + for _, op in enumerate(self.optimize_ops): + if self._is_optimizer_op(op) and self._is_opt_op_on_pserver( + endpoint, op): + opt_op_on_pserver.append(op) + + for opt_op in opt_op_on_pserver: + dist_var = None + for key in opt_op.input_names: + if key == "Param": + param_name = opt_op.input(key)[0] + dist_var = self.vars_overview.get_distributed_var_by_origin_and_ep( + param_name, endpoint) + break + for key in opt_op.input_names: + if key in [ + "Param", "Grad", "LearningRate", "Beta1Tensor", + "Beta2Tensor" + ]: + continue + origin_var = self.origin_program.global_block().vars[ + opt_op.input(key)[0]] + # update accumulator variable shape + new_shape = self._get_optimizer_input_shape( + opt_op.type, key, origin_var.shape, + dist_var.slice.shape) + + if new_shape == dist_var.slice.shape: + splited_var = VarStruct( + name=origin_var.name, + shape=new_shape, + dtype=origin_var.dtype, + type=origin_var.type, + lod_level=origin_var.lod_level, + persistable=origin_var.persistable) + + self.vars_overview.add_distributed_var( + origin_var=origin_var, + slice_var=splited_var, + is_slice=dist_var.is_slice, + block_id=dist_var.block_id, + offset=dist_var.offset, + vtype="Optimizer", + endpoint=endpoint) + else: + self.vars_overview.add_distributed_var( + origin_var=origin_var, + slice_var=origin_var, + is_slice=False, + block_id=0, + offset=0, + vtype="Optimizer", + endpoint=endpoint) + + for ep in self.pserver_endpoints: + _get_distributed_optimizer_var(ep) + + def _update_dist_lookup_table_vars(self, param_list, grad_list, + params_grads): + # TODO(wuyi): put find a way to put dist lookup table stuff all together. + # update self.table_param_grad and self.trainer_side_table_grad_list + program = self.origin_program + if self.has_distributed_lookup_table: + param_list = [ + param for param in param_list if param.name != self.table_name + ] + grad_list = [ + grad for grad in grad_list + if grad.name != grad_var_name(self.table_name) + ] + self.table_param_grad = [ + param_grad for param_grad in params_grads + if param_grad[0].name == self.table_name + ][0] + table_grad_var = self.table_param_grad[1] + if self.sync_mode: + self.trainer_side_table_grad_list = [ + program.global_block().create_var( + name="%s.trainer_%d.pserver_%d" % + (table_grad_var.name, self.trainer_id, index), + type=table_grad_var.type, + shape=table_grad_var.shape, + dtype=table_grad_var.dtype) + for index in range(len(self.pserver_endpoints)) + ] + else: + self.trainer_side_table_grad_list = [ + program.global_block().create_var( + name="%s.pserver_%d" % (table_grad_var.name, index), + type=table_grad_var.type, + shape=table_grad_var.shape, + dtype=table_grad_var.dtype) + for index in range(len(self.pserver_endpoints)) + ] + return param_list, grad_list + + def _init_splited_vars(self): + # update these mappings for further transpile: + # 1. param_var_mapping: param var name -> [split params vars] + # 2. grad_var_mapping: grad var name -> [split grads vars] + # 3. grad_param_mapping: grad.blockx -> param.blockx + # 4. param_grad_ep_mapping: ep -> {"params": [], "grads": []} + + param_list = [] + grad_list = [] + param_grad_set = set() + for p, g in self.params_grads: + # skip parameter marked not trainable + if type(p) == Parameter and p.trainable == False: + continue + if p.name not in param_grad_set: + param_list.append(p) + param_grad_set.add(p.name) + if g.name not in param_grad_set: + grad_list.append(g) + param_grad_set.add(g.name) + + param_list, grad_list = self._update_dist_lookup_table_vars( + param_list, grad_list, self.params_grads) + + if self.config.slice_var_up: + # when we slice var up into blocks, we will slice the var according to + # pserver services' count. A pserver may have two or more listening ports. + grad_blocks = slice_variable(grad_list, len(self.pserver_endpoints), + self.config.min_block_size) + param_blocks = slice_variable(param_list, + len(self.pserver_endpoints), + self.config.min_block_size) + else: + # when we do NOT slice var up into blocks, we will always slice params + # grads into one block. + grad_blocks = slice_variable(grad_list, 1, + self.config.min_block_size) + param_blocks = slice_variable(param_list, 1, + self.config.min_block_size) + assert (len(grad_blocks) == len(param_blocks)) + + # origin_param_name -> [splited_param_vars] + self.param_var_mapping = self._create_vars_from_blocklist( + self.origin_program, param_blocks) + + for orig_name, splited_vars in self.param_var_mapping.items(): + orig_var = self.origin_program.global_block().var(orig_name) + + for splited_var in splited_vars: + is_slice, block_id, offset = self._get_slice_var_info( + splited_var) + + self.vars_overview.add_distributed_var(origin_var=orig_var, + slice_var=splited_var, + block_id=block_id, + offset=offset, + is_slice=is_slice, + vtype="Param") + + # origin_grad_name -> [splited_grad_vars] + self.grad_var_mapping = self._create_vars_from_blocklist( + self.origin_program, + grad_blocks, + add_trainer_suffix=self.trainer_num > 1) + # dict(grad_splited_var -> param_splited_var) + self.grad_param_mapping = collections.OrderedDict() + for g, p in zip(grad_blocks, param_blocks): + g_name, g_bid, _ = g.split(":") + p_name, p_bid, _ = p.split(":") + self.grad_param_mapping[self.grad_var_mapping[g_name][int(g_bid)]] = \ + self.param_var_mapping[p_name][int(p_bid)] + + # create mapping of endpoint -> split var to create pserver side program + self.param_grad_ep_mapping = collections.OrderedDict() + [ + self.param_grad_ep_mapping.update({ep: { + "params": [], + "grads": [] + }}) for ep in self.pserver_endpoints + ] + + # transpiler function for dis lookup_table + def _replace_lookup_table_op_with_prefetch(self, program, + pserver_endpoints): + # 1. replace lookup_table_op with split_ids_op -> prefetch_op -> sum_op + self.all_in_ids_vars = [] + self.all_prefetch_input_vars = [] + self.all_prefetch_output_vars = [] + self.all_out_emb_vars = [] + lookup_table_op_index = -1 + + continue_search_lookup_table_op = True + while continue_search_lookup_table_op: + continue_search_lookup_table_op = False + all_ops = program.global_block().ops + for op in all_ops: + if op.type == LOOKUP_TABLE_TYPE and self.table_name == op.input( + "W")[0]: + if not op.attr('is_distributed'): + raise RuntimeError( + "lookup_table_op that lookup an distributed embedding table" + "should set is_distributed to true") + continue_search_lookup_table_op = True + + lookup_table_op_index = lookup_table_op_index if lookup_table_op_index != -1 else list( + all_ops).index(op) + ids_name = op.input("Ids") + out_name = op.output("Out") + + ids_var = program.global_block().vars[ids_name[0]] + self.all_in_ids_vars.append(ids_var) + + out_var = program.global_block().vars[out_name[0]] + self.all_out_emb_vars.append(out_var) + + # delete lookup_table_op + delete_ops(program.global_block(), [op]) + # break for loop + break + + for index in range(len(self.pserver_endpoints)): + in_var = program.global_block().create_var( + name=str("prefetch_compress_in_tmp_" + str(index)), + type=self.all_in_ids_vars[0].type, + shape=self.all_in_ids_vars[0].shape, + dtype=self.all_in_ids_vars[0].dtype) + self.all_prefetch_input_vars.append(in_var) + + out_var = program.global_block().create_var( + name=str("prefetch_compress_out_tmp_" + str(index)), + type=self.all_out_emb_vars[0].type, + shape=self.all_out_emb_vars[0].shape, + dtype=self.all_out_emb_vars[0].dtype) + self.all_prefetch_output_vars.append(out_var) + + # insert split_ids_op + program.global_block()._insert_op( + index=lookup_table_op_index, + type="split_ids", + inputs={'Ids': self.all_in_ids_vars}, + outputs={"Out": self.all_prefetch_input_vars}) + + # insert prefetch_op + program.global_block()._insert_op( + index=lookup_table_op_index + 1, + type="prefetch", + inputs={'X': self.all_prefetch_input_vars}, + outputs={"Out": self.all_prefetch_output_vars}, + attrs={ + "epmap": pserver_endpoints, + # FIXME(qiao) temporarily disable this config because prefetch + # is not act as other rpc op, it's more like a forward op + # RPC_OP_ROLE_ATTR_NAME: RPC_OP_ROLE_ATTR_VALUE + }) + + # insert concat_op + program.global_block()._insert_op( + index=lookup_table_op_index + 2, + type="merge_ids", + inputs={ + 'Ids': self.all_in_ids_vars, + 'Rows': self.all_prefetch_input_vars, + 'X': self.all_prefetch_output_vars + }, + outputs={"Out": self.all_out_emb_vars}) + + def _split_table_grad_and_add_send_vars(self, program, pserver_endpoints): + # 2. add split_ids_op and send_op to send gradient to pservers + + # there should only be one table_name + all_ops = program.global_block().ops + table_grad_name = grad_var_name(self.table_name) + for op in all_ops: + if table_grad_name in op.output_arg_names: + op_index = list(all_ops).index(op) + # insert split_ids_op + program.global_block()._insert_op( + index=op_index + 1, + type="split_ids", + inputs={ + 'Ids': [program.global_block().vars[table_grad_name]] + }, + outputs={"Out": self.trainer_side_table_grad_list}, + attrs={RPC_OP_ROLE_ATTR_NAME: DIST_OP_ROLE_ATTR_VALUE}) + program.global_block()._insert_op( + index=op_index + 2, + type="send", + inputs={'X': self.trainer_side_table_grad_list}, + outputs={ + 'Out': + [self.grad_name_to_send_dummy_out[self.table_name]] + if self.sync_mode else [] + }, + attrs={ + "epmap": + pserver_endpoints, + "trainer_id": + self.trainer_id, + RPC_OP_ROLE_ATTR_NAME: + RPC_OP_ROLE_ATTR_VALUE, + OP_ROLE_VAR_ATTR_NAME: [ + self.grad_name_to_param_name[table_grad_name], + table_grad_name + ] + }) + break + + def _create_prefetch_block(self, pserver_index, pserver_program, + optimize_block): + # STEP: create prefetch block + table_var = pserver_program.global_block().vars[self.table_name] + prefetch_var_name_to_block_id = [] + prefetch_block = pserver_program._create_block(optimize_block.idx) + trainer_ids = self.all_prefetch_input_vars[pserver_index] + pserver_ids = pserver_program.global_block().create_var( + name=trainer_ids.name, + type=trainer_ids.type, + shape=trainer_ids.shape, + dtype=trainer_ids.dtype) + trainer_out = self.all_prefetch_output_vars[pserver_index] + pserver_out = pserver_program.global_block().create_var( + name=trainer_out.name, + type=trainer_out.type, + shape=trainer_out.shape, + dtype=trainer_out.dtype) + prefetch_block.append_op( + type="lookup_sparse_table", + inputs={ + 'Ids': pserver_ids, + "W": table_var + }, + outputs={"Out": pserver_out}, + attrs={ + "is_sparse": True, # has no effect on lookup_table op + "is_distributed": True, + "padding_idx": -1 + }) + prefetch_var_name_to_block_id.append(trainer_ids.name + ":" + + str(prefetch_block.idx)) + return prefetch_var_name_to_block_id + + def _create_table_optimize_block(self, pserver_index, pserver_program, + pre_block_idx, grad_to_block_id): + # STEP: create table optimize block + table_opt_block = pserver_program._create_block(pre_block_idx) + # create table param and grad var in pserver program + # create table optimize block in pserver program + table_opt_op = [ + op for op in self.optimize_ops if 'Param' in op.input_names + and op.input("Param")[0] == self.table_name + ][0] + + origin_param_var = self.origin_program.global_block().vars[ + self.table_name] + + zero_dim = int( + math.ceil(origin_param_var.shape[0] / + float(len(self.pserver_endpoints)))) + table_shape = list(origin_param_var.shape) + table_shape[0] = zero_dim + + param_var = pserver_program.global_block().create_var( + name=origin_param_var.name, + shape=table_shape, + dtype=origin_param_var.dtype, + type=core.VarDesc.VarType.SELECTED_ROWS, + persistable=True) + + # parameter must be selected rows + param_var.desc.set_type(core.VarDesc.VarType.SELECTED_ROWS) + grad_var = pserver_program.global_block()._clone_variable( + self.origin_program.global_block().vars[grad_var_name( + self.table_name)]) + + lr_var = pserver_program.global_block()._clone_variable( + self.origin_program.global_block().vars[table_opt_op.input( + "LearningRate")[0]]) + + if self.sync_mode: + # create grad vars in pserver program + table_grad_var = self.table_param_grad[1] + pserver_side_table_grad_list = [ + pserver_program.global_block().create_var( + name="%s.trainer_%d.pserver_%d" % + (table_grad_var.name, index, pserver_index), + type=table_grad_var.type, + shape=table_grad_var.shape, + dtype=table_grad_var.dtype) + for index in range(self.trainer_num) + ] + + # append sum op for pserver_side_table_grad_list + table_opt_block.append_op( + type="sum", + inputs={"X": pserver_side_table_grad_list}, + outputs={"Out": [grad_var]}, + attrs={"use_mkldnn": False}) + else: + # in async_mode, for table gradient, it also need to be split to each parameter server + origin_grad_name = grad_var.name + splited_grad_name = self.trainer_side_table_grad_list[ + pserver_index].name + if not splited_grad_name.startswith(origin_grad_name): + raise ValueError("origin_grad_var: " + splited_grad_name + + " grad_var:" + grad_var.name) + grad_var = pserver_program.global_block()._rename_var( + origin_grad_name, splited_grad_name) + + inputs = { + "Param": [param_var], + "Grad": [grad_var], + "LearningRate": [lr_var] + } + outputs = {"ParamOut": [param_var]} + # only support sgd now + logging.warn( + "distribute lookup table only support sgd optimizer, change it's optimizer to sgd instead of " + + table_opt_op.type) + table_opt_block.append_op(type="sgd", inputs=inputs, outputs=outputs) + + # add table parameter gradient and it's block id to grad_to_block_id + grad_to_block_id.append(grad_var.name + ":" + str(table_opt_block.idx)) + + return table_opt_block + + def _create_checkpoint_save_block(self, pserver_program, pre_block_idx): + """ + create a new block to handle save checkpoint. + """ + + pserver_program.global_block().create_var(name="kLookupTablePath", + persistable=True, + type=core.VarDesc.VarType.RAW) + + checkpoint_save_block = pserver_program._create_block(pre_block_idx) + # this 'file_path' do not be used in save lookup table variable + checkpoint_save_block.append_op(type='save', + inputs={'X': [self.table_name]}, + outputs={}, + attrs={'file_path': "none"}) + + return checkpoint_save_block.idx + + def _create_vars_from_blocklist(self, + program, + block_list, + add_trainer_suffix=False): + """ + Create vars for each split. + NOTE: only grads need to be named for different trainers, use + add_trainer_suffix to rename the grad vars. + Args: + program (ProgramDesc): ProgramDesc which gradients blong. + block_list (list[(varname, block_id, block_size)]): List of gradient blocks. + add_trainer_suffix (Bool): Add trainer suffix to new variable's name if set True. + Returns: + var_mapping (collections.OrderedDict(varname->[new_varname_variable])):A dict mapping + from original var name to each var split. + """ + + # varname->[(block_id, current_block_size)] + block_map = collections.OrderedDict() + + var_mapping = collections.OrderedDict() + for block_str in block_list: + varname, offset, size = block_str.split(":") + if varname not in block_map: + block_map[varname] = [] + block_map[varname].append((int(offset), int(size))) + + for varname, split in six.iteritems(block_map): + orig_var = program.global_block().var(varname) + if len(split) == 1: + if self.sync_mode and add_trainer_suffix: + new_var_name = "%s.trainer_%d" % \ + (orig_var.name, self.trainer_id) + program.global_block()._rename_var(varname, new_var_name) + var_mapping[varname] = \ + [program.global_block().var(new_var_name)] + else: + var_mapping[varname] = \ + [program.global_block().var(orig_var.name)] + continue + var_mapping[varname] = [] + orig_shape = orig_var.shape + orig_dim1_flatten = 1 + if len(orig_shape) >= 2: + orig_dim1_flatten = reduce(lambda x, y: x * y, orig_shape[1:]) + + for i, block in enumerate(split): + size = block[1] + rows = size // orig_dim1_flatten + splited_shape = [rows] + if len(orig_shape) >= 2: + splited_shape.extend(orig_shape[1:]) + new_var_name = "" + if self.sync_mode and add_trainer_suffix: + new_var_name = "%s.block%d.trainer_%d" % \ + (varname, i, self.trainer_id) + else: + new_var_name = "%s.block%d" % \ + (varname, i) + var = program.global_block().create_var( + name=new_var_name, + persistable=False, + dtype=orig_var.dtype, + type=orig_var.type, + shape=splited_shape) # flattend split var + var_mapping[varname].append(var) + program.global_block()._sync_with_cpp() + return var_mapping + + def _clone_var(self, block, var, persistable=True): + return block.create_var(name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=persistable) + + @staticmethod + def _get_splited_var_sections(splited_vars): + height_sections = [] + for v in splited_vars: + height_sections.append(v.shape[0]) + return height_sections + + def _insert_split_op(self, program, orig_var, index, splited_vars): + height_sections = self._get_splited_var_sections(splited_vars) + + if orig_var.type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_param_name = self.grad_name_to_param_name[orig_var.name] + if self._is_input_of_remote_sparse_update_op(sparse_param_name): + self.sparse_param_to_height_sections[ + sparse_param_name] = height_sections + program.global_block()._insert_op(index=index + 1, + type="split_selected_rows", + inputs={"X": orig_var}, + outputs={"Out": splited_vars}, + attrs={ + "height_sections": + height_sections, + RPC_OP_ROLE_ATTR_NAME: + DIST_OP_ROLE_ATTR_VALUE + }) + elif orig_var.type == core.VarDesc.VarType.LOD_TENSOR: + program.global_block()._insert_op(index=index + 1, + type="split_byref", + inputs={"X": orig_var}, + outputs={"Out": splited_vars}, + attrs={ + "sections": + height_sections, + RPC_OP_ROLE_ATTR_NAME: + DIST_OP_ROLE_ATTR_VALUE + }) + else: + AssertionError("Variable type should be in set " + "[LOD_TENSOR, SELECTED_ROWS]") + + def _get_optimizer_input_shape(self, op_type, varkey, orig_shape, + param_shape): + """ + Returns the shape for optimizer inputs that need to be reshaped when + Param and Grad is split to multiple servers. + """ + # HACK(typhoonzero): Should use functions of corresponding optimizer in + # optimizer.py to get the shape, do not bind this in the transpiler. + if op_type == "adam": + if varkey in ["Moment1", "Moment2"]: + return param_shape + elif op_type == "adagrad": + if varkey == "Moment": + return param_shape + elif op_type == "adamax": + if varkey in ["Moment", "InfNorm"]: + return param_shape + elif op_type in ["momentum", "lars_momentum"]: + if varkey == "Velocity": + return param_shape + elif op_type == "rmsprop": + if varkey in ["Moment", "MeanSquare"]: + return param_shape + elif op_type == "decayed_adagrad": + if varkey == "Moment": + return param_shape + elif op_type == "ftrl": + if varkey in ["SquaredAccumulator", "LinearAccumulator"]: + return param_shape + elif op_type == "sgd": + pass + else: + raise ValueError( + "Not supported optimizer for distributed training: %s" % + op_type) + return orig_shape + + def _get_varname_parts(self, varname): + # returns origin, blockid, trainerid + orig_var_name = "" + trainer_part = "" + block_part = "" + trainer_idx = varname.find(".trainer_") + if trainer_idx >= 0: + trainer_part = varname[trainer_idx + 1:] + else: + trainer_idx = len(varname) + block_index = varname.find(".block") + if block_index >= 0: + block_part = varname[block_index + 1:trainer_idx] + else: + block_index = len(varname) + orig_var_name = varname[0:min(block_index, trainer_idx)] + return orig_var_name, block_part, trainer_part + + def _orig_varname(self, varname): + orig, _, _ = self._get_varname_parts(varname) + return orig + + def _append_pserver_grad_merge_ops(self, optimize_block, + grad_varname_for_block, endpoint, + grad_to_block_id, origin_program): + program = optimize_block.program + pserver_block = program.global_block() + grad_block = None + for g in self.param_grad_ep_mapping[endpoint]["grads"]: + if self._orig_varname(g.name) == \ + self._orig_varname(grad_varname_for_block): + grad_block = g + break + if not grad_block: + # do not append this op if current endpoint + # is not dealing with this grad block + return None + orig_varname, block_name, trainer_name = self._get_varname_parts( + grad_block.name) + if block_name: + merged_var_name = '.'.join([orig_varname, block_name]) + else: + merged_var_name = orig_varname + + merged_var = pserver_block.vars[merged_var_name] + grad_to_block_id.append(merged_var.name + ":" + str(optimize_block.idx)) + if self.sync_mode or self.config.completely_not_async and self.trainer_num > 1: + vars2merge = [] + for i in range(self.trainer_num): + per_trainer_name = "%s.trainer_%d" % \ + (merged_var_name, i) + vars2merge.append(pserver_block.vars[per_trainer_name]) + optimize_block.append_op(type="sum", + inputs={"X": vars2merge}, + outputs={"Out": merged_var}, + attrs={"use_mkldnn": False}) + optimize_block.append_op( + type="scale", + inputs={"X": merged_var}, + outputs={"Out": merged_var}, + attrs={"scale": 1.0 / float(self.trainer_num)}) + return merged_var + + def _append_dc_asgd_ops(self, block, param_var, grad_var): + # NOTE: can not use grammar candy here, should put ops in specific block + local_param_bak = block.create_var(name="%s.local_bak" % param_var.name, + shape=param_var.shape, + type=param_var.type, + dtype=param_var.dtype, + persistable=False) + # trainer_id_var is block local + trainer_id_var = block.create_var(name="@TRAINER_ID@", + type=core.VarDesc.VarType.LOD_TENSOR, + dtype=core.VarDesc.VarType.INT64, + shape=[1], + persistable=False) + + # ref_inputs = [x[1] for x in self.param_bak_list] + ref_inputs = [] + for p, p_bak in self.param_bak_list: + if p.name == param_var.name: + ref_inputs.append(p_bak) + block.append_op(type="ref_by_trainer_id", + inputs={ + "X": ref_inputs, + "TrainerId": trainer_id_var + }, + outputs={"Out": local_param_bak}) + + def __create_temp_var__(): + return block.create_var(name=unique_name.generate("tmp_dc_output"), + shape=param_var.shape, + type=param_var.type, + dtype=param_var.dtype, + persistable=False) + + o1 = __create_temp_var__() + block.append_op(type="elementwise_sub", + inputs={ + "X": param_var, + "Y": local_param_bak + }, + outputs={"Out": o1}) + o2 = __create_temp_var__() + block.append_op(type="elementwise_mul", + inputs={ + "X": o1, + "Y": grad_var + }, + outputs={"Out": o2}) + o3 = __create_temp_var__() + block.append_op(type="elementwise_mul", + inputs={ + "X": o2, + "Y": grad_var + }, + outputs={"Out": o3}) + # TODO(typhoonzero): append scale + o4 = __create_temp_var__() + block.append_op(type="elementwise_add", + inputs={ + "X": grad_var, + "Y": o3 + }, + outputs={"Out": o4}) + return o4 + + def _append_pserver_ops(self, optimize_block, opt_op, endpoint, + grad_to_block_id, origin_program, merged_var, + sparse_grad_to_param): + program = optimize_block.program + pserver_block = program.global_block() + new_inputs = collections.OrderedDict() + + def _get_param_block(opt_op): + # param is already created on global program + param_block = None + for p in self.param_grad_ep_mapping[endpoint]["params"]: + if same_or_split_var(p.name, opt_op.input("Param")[0]): + param_block = p + break + return param_block + + if self.config.enable_dc_asgd: + param_var = _get_param_block(opt_op) + dc = self._append_dc_asgd_ops(optimize_block, param_var, merged_var) + + for key in opt_op.input_names: + if key == "Grad": + if self.config.enable_dc_asgd: + new_inputs[key] = dc + else: + # Note!! This is for l2decay on sparse gradient, because it will create a new tensor for + # decayed gradient but not inplace modify the origin one + origin_grad_name = opt_op.input(key)[0] + if core.kNewGradSuffix( + ) in origin_grad_name and pserver_block.has_var( + origin_grad_name): + new_grad = pserver_block.var(origin_grad_name) + new_inputs[key] = new_grad + else: + new_inputs[key] = merged_var + elif key == "Param": + param_block = _get_param_block(opt_op) + if not param_block: + return + tmpvar = pserver_block.create_var(name=param_block.name, + persistable=True, + dtype=param_block.dtype, + shape=param_block.shape) + new_inputs[key] = tmpvar + elif key == "LearningRate": + # learning rate variable has already be created by non-optimize op, + # don't create it once again. + lr_varname = opt_op.input(key)[0] + if lr_varname in pserver_block.vars: + new_inputs[key] = pserver_block.vars[opt_op.input(key)[0]] + else: + origin_var = origin_program.global_block().vars[lr_varname] + tmpvar = pserver_block.create_var( + name=origin_var.name, + persistable=origin_var.persistable, + dtype=origin_var.dtype, + shape=origin_var.shape) + new_inputs[key] = tmpvar + + for key in opt_op.input_names: + new_shape = None + if key in [ + "Param", "Grad", "LearningRate", "Beta1Tensor", + "Beta2Tensor" + ]: + continue + var = self.origin_program.global_block().vars[opt_op.input(key)[0]] + param_var = new_inputs["Param"] + # update accumulator variable shape + new_shape = self._get_optimizer_input_shape(opt_op.type, key, + var.shape, + param_var.shape) + tmpvar = pserver_block.create_var(name=var.name, + persistable=var.persistable, + dtype=var.dtype, + shape=new_shape) + new_inputs[key] = tmpvar + + # change output's ParamOut variable + outputs = self._get_output_map_from_op( + self.origin_program.global_block().vars, opt_op) + outputs["ParamOut"] = new_inputs["Param"] + optimize_block.append_op(type=opt_op.type, + inputs=new_inputs, + outputs=outputs, + attrs=opt_op.all_attrs()) + + # record sparse grad to param name + if new_inputs["Grad"].type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_grad_to_param.append( + str(new_inputs["Grad"].name) + ":" + + str(new_inputs["Param"].name)) + + def _get_pserver_grad_param_var(self, var, var_dict): + """ + Return pserver side grad/param variable, return None + if the variable is not grad/param, e.g. + + a@GRAD -> a@GRAD.block0 + a@GRAD -> a@GRAD (a is not split) + fc_0.w_0 -> fc_0.w_0.block_0 + fc_0.w_0 -> fc_0.w_0 (weight is not split) + _generated_var_123 -> None + """ + grad_block = None + for _, g in six.iteritems(var_dict): + if self._orig_varname(g.name) == self._orig_varname(var.name): + # skip per trainer vars + if g.name.find(".trainer_") == -1: + # only param or grads have split blocks + if self._orig_varname(g.name) in self.grad_name_to_param_name or \ + self._orig_varname(g.name) in self.param_name_to_grad_name: + grad_block = g + break + return grad_block + + def _clone_lr_op(self, program, block, op): + inputs = self._get_input_map_from_op( + self.origin_program.global_block().vars, op) + for key, varlist in six.iteritems(inputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var not in program.global_block().vars: + block._clone_variable(var) + + outputs = self._get_output_map_from_op( + self.origin_program.global_block().vars, op) + for key, varlist in six.iteritems(outputs): + if not isinstance(varlist, list): + varlist = [varlist] + for var in varlist: + if var not in program.global_block().vars: + block._clone_variable(var) + + return block.append_op(type=op.type, + inputs=inputs, + outputs=outputs, + attrs=op.all_attrs()) + + def _append_pserver_non_opt_ops(self, optimize_block, opt_op): + program = optimize_block.program + # Append the ops for parameters that do not need to be optimized/updated + inputs = self._get_input_map_from_op( + self.origin_program.global_block().vars, opt_op) + for key, varlist in six.iteritems(inputs): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + # for ops like clipping and weight decay, get the split var (xxx.block0) + # for inputs/outputs + grad_block = self._get_pserver_grad_param_var( + var, + program.global_block().vars) + if grad_block: + varlist[i] = grad_block + elif var.name not in program.global_block().vars: + tmpvar = program.global_block()._clone_variable(var) + varlist[i] = tmpvar + else: + varlist[i] = program.global_block().vars[var.name] + inputs[key] = varlist + + outputs = self._get_output_map_from_op( + self.origin_program.global_block().vars, opt_op) + for key, varlist in six.iteritems(outputs): + if not isinstance(varlist, list): + varlist = [varlist] + for i in range(len(varlist)): + var = varlist[i] + grad_block = self._get_pserver_grad_param_var( + var, + program.global_block().vars) + if grad_block: + varlist[i] = grad_block + elif var.name not in program.global_block().vars: + tmpvar = program.global_block()._clone_variable(var) + varlist[i] = tmpvar + else: + varlist[i] = program.global_block().vars[var.name] + outputs[key] = varlist + + return optimize_block.append_op(type=opt_op.type, + inputs=inputs, + outputs=outputs, + attrs=opt_op.all_attrs()) + + def _is_op_connected(self, op1, op2): + # If one op's input is another op's output or + # one op's output is another op's input, we say + # the two operator is connected. + if set(op1.desc.output_arg_names()) & set(op2.desc.input_arg_names()) or \ + set(op1.desc.input_arg_names()) & set(op2.desc.output_arg_names()): + return True + return False + + def _create_ufind(self, optimize_ops): + # Create a unit find data struct by optimize ops + ufind = UnionFind(optimize_ops) + for i in range(len(optimize_ops)): + for j in range(i, len(optimize_ops)): + op1 = optimize_ops[i] + op2 = optimize_ops[j] + if self._is_op_connected(op1, op2): + ufind.union(op1, op2) + return ufind + + def _is_optimizer_op(self, op): + if "Param" in op.input_names and \ + "LearningRate" in op.input_names: + return True + return False + + def _is_opt_op_on_pserver(self, endpoint, op): + param_names = [ + p.name for p in self.param_grad_ep_mapping[endpoint]["params"] + ] + if op.input("Param")[0] in param_names: + return True + else: + for n in param_names: + param = op.input("Param")[0] + if same_or_split_var(n, param) and n != param: + return True + return False + + def _get_input_map_from_op(self, varmap, op): + """Returns a dict from op input name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.input_names: + vars = [] + for varname in op.input(key): + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + def _get_output_map_from_op(self, varmap, op): + """Returns a dict from op output name to the vars in varmap.""" + iomap = collections.OrderedDict() + for key in op.output_names: + vars = [] + for varname in op.output(key): + vars.append(varmap[varname]) + if len(vars) == 1: + iomap[key] = vars[0] + else: + iomap[key] = vars + return iomap + + def _get_lr_ops(self): + lr_ops = [] + block = self.origin_program.global_block() + for index, op in enumerate(block.ops): + role_id = int(op.attr(RPC_OP_ROLE_ATTR_NAME)) + if role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) or \ + role_id == int(LR_SCHED_OP_ROLE_ATTR_VALUE) | \ + int(OPT_OP_ROLE_ATTR_VALUE): + if self.sync_mode == False and op.type == 'increment': + inputs = self._get_input_map_from_op( + self.origin_program.global_block().vars, op) + outputs = self._get_output_map_from_op( + self.origin_program.global_block().vars, op) + for key in outputs: + counter_var = outputs[key] + all_trainer_counter_inputs = [ + self.origin_program.global_block().create_var( + name="%s.trainer_%d" % (counter_var.name, id_), + type=counter_var.type, + shape=counter_var.shape, + dtype=counter_var.dtype, + persistable=counter_var.persistable) + for id_ in range(self.trainer_num) + ] + for i, op in enumerate( + self.startup_program.global_block().ops): + if op.type == 'fill_constant': + for key in op.output_names: + if len(op.output(key)) == 1 and op.output( + key)[0] == counter_var.name: + self.startup_program.global_block( + ).ops[i]._set_attr( + 'value', float(0.0 - self.trainer_num)) + for var in all_trainer_counter_inputs: + if var.name == "%s.trainer_%d" % (counter_var.name, + self.trainer_id): + self.counter_var = var + self.startup_program.global_block().create_var( + name=var.name, + type=var.type, + dtype=var.dtype, + shape=var.shape, + persistable=var.persistable, + initializer=initializer.Constant(1)) + op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName( + ) + block._remove_op(index) + op = block._insert_op( + index, + type='sum', + inputs={'X': all_trainer_counter_inputs}, + outputs=outputs, + attrs={op_role_attr_name: LR_SCHED_OP_ROLE_ATTR_VALUE}) + lr_ops.append(op) + log("append lr op: ", op.type) + return lr_ops + + def _get_lr_ops_deprecated(self): + lr_ops = [] + # find learning rate variables by optimize op + lr_vars = set() + for op in self.optimize_ops: + if self._is_optimizer_op(op): + lr_vars.add(op.input("LearningRate")[0]) + + find_ops = [] + # find ops which output is lr var + block = self.origin_program.global_block() + for op in block.ops: + if set(op.output_arg_names) & lr_vars: + find_ops.append(op) + # make a union find struct by the ops in default_main_program + ufind = UnionFind(block.ops) + + for op1 in block.ops: + for op2 in block.ops: + # NOTE: we need to skip all optimize ops, since it is connected + # with forward/backward ops and lr ops, we only need the lr ops. + if op1 != op2 and self._is_op_connected(op1, op2) and \ + not self._is_optimizer_op(op1) and not self._is_optimizer_op(op2): + ufind.union(op1, op2) + # find all ops which is related with lr var + for op1 in block.ops: + for op2 in find_ops: + if ufind.is_connected(op1, op2): + lr_ops.append(op1) + # we only need to append op for once + break + return lr_ops + + def _is_opt_role_op(self, op): + # NOTE: depend on oprole to find out whether this op is for + # optimize + op_maker = core.op_proto_and_checker_maker + optimize_role = core.op_proto_and_checker_maker.OpRole.Optimize + if op_maker.kOpRoleAttrName() in op.attr_names and \ + int(op.all_attrs()[op_maker.kOpRoleAttrName()]) == int(optimize_role): + return True + return False + + def _get_optimize_pass(self): + """ + Get optimizer operators, parameters and gradients from origin_program + Returns: + opt_ops (list): optimize operators. + params_grads (dict): parameter->gradient. + """ + block = self.origin_program.global_block() + opt_ops = [] + params_grads = [] + # tmp set to dedup + optimize_params = set() + origin_var_dict = self.origin_program.global_block().vars + for op in block.ops: + if self._is_opt_role_op(op): + # Todo(chengmo): Whether clip related op belongs to Optimize guard should be discussed + # delete clip op from opt_ops when run in Parameter Server mode + if OP_NAME_SCOPE in op.all_attrs( + ) and CLIP_OP_NAME_SCOPE in op.attr( + OP_NAME_SCOPE + ) and self.config.mode != "nccl2" and self.config.mode != "collective": + op._set_attr( + "op_role", + int(core.op_proto_and_checker_maker.OpRole.Backward)) + continue + opt_ops.append(op) + if op.attr(OP_ROLE_VAR_ATTR_NAME): + param_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[0] + grad_name = op.attr(OP_ROLE_VAR_ATTR_NAME)[1] + if not param_name in optimize_params: + optimize_params.add(param_name) + log("adding param_grad pair: ", param_name, grad_name) + params_grads.append([ + origin_var_dict[param_name], + origin_var_dict[grad_name] + ]) + else: + pass + + # designed for special situation + special_distribute_update_vars = self._get_distribute_update_vars() + if special_distribute_update_vars: + params_grads = params_grads + special_distribute_update_vars + + return opt_ops, params_grads + + def _get_distribute_update_vars(self): + # TODO(chengmo): find more powerful and simple way to deal with these special situation + """ + This Function is used for a special model, like PyramidDnn which has pyramid hash op. + Some Parameters don't use optimizing op to update its value, but updated in its BP process. + In these cases, Transpilse can't find these special vars by optimizing op information. + So we add this function and add attr "distribute_update_vars" to tell transpiler these Parameter + need to be updated in distribute training. + We assume these special var send and receive the same var_name. + """ + block = self.origin_program.global_block() + origin_var_dict = self.origin_program.global_block().vars + params = [] + for op in block.ops: + special_attr = "distribute_update_vars" + if special_attr in op.all_attrs(): + if op.attr(special_attr): + for param_name in op.attr(special_attr).split(","): + params.append(origin_var_dict[param_name]) + unique_params = list(set(params)) + params_grads = [] + for var in unique_params: + params_grads.append([var, var]) + return params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/geo_sgd_transpiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/geo_sgd_transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..eb86ffd36a2d49be92407dab913a028e8a47ec9a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/geo_sgd_transpiler.py @@ -0,0 +1,355 @@ +# 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. + +from __future__ import print_function +""" +Steps to transpile trainer: +1. split variable to multiple blocks, aligned by product(dim[1:]) (width). +2. create delta variable in global scope which used to send +3. add send op to send sparse ids to communicator + +Steps to transpile pserver: +1. create new program for parameter server. +2. create params variables that assigned to current server instance. +3. create a sub-block in the server side program +4. append sum ops that should run on current server instance. +5. add listen_and_serv op +""" +import sys +import collections +import six +import numpy as np + +from .ps_dispatcher import RoundRobin, PSDispatcher +from .. import core, framework +from ..framework import Program, default_main_program, \ + default_startup_program, Block, Parameter +from .details import wait_server_ready, VarsDistributed +from .details import delete_ops +from ..distribute_lookup_table import find_distributed_lookup_table +from .distribute_transpiler import DistributeTranspiler, DistributeTranspilerConfig, slice_variable, same_or_split_var, ServerRuntimeConfig +from paddle.fluid.incubate.fleet.parameter_server.mode import DistributedMode + +RPC_OP_ROLE_ATTR_NAME = op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName( +) +RPC_OP_ROLE_ATTR_VALUE = core.op_proto_and_checker_maker.OpRole.RPC + + +class GeoSgdTranspiler(DistributeTranspiler): + + def __init__(self, config=None): + if config is not None: + self.config = config + else: + self.config = DistributeTranspilerConfig() + self._set_server_config() + + if self.config.split_method is None: + self.config.split_method = RoundRobin + + assert (self.config.min_block_size >= 8192) + assert (self.config.split_method.__bases__[0] == PSDispatcher) + + def transpile(self, + trainer_id, + program=None, + pservers="127.0.0.1:6174", + trainers=1, + sync_mode=False, + startup_program=None, + current_endpoint="127.0.0.1:6174"): + if program is None: + program = default_main_program() + if startup_program is None: + startup_program = default_startup_program() + self.origin_program = program + self.startup_program = startup_program + self.origin_startup_program = self.startup_program.clone() + + self.trainer_num = trainers + # geo-sgd only supply async-mode + self.sync_mode = False + self.trainer_id = trainer_id + pserver_endpoints = pservers.split(",") + self.pserver_endpoints = pserver_endpoints + self.vars_overview = VarsDistributed() + self.optimize_ops, self.params_grads = self._get_optimize_pass() + ps_dispatcher = self.config.split_method(self.pserver_endpoints) + self.param_name_to_grad_name = dict() + self.grad_name_to_param_name = dict() + for param_var, grad_var in self.params_grads: + self.param_name_to_grad_name[param_var.name] = grad_var.name + self.grad_name_to_param_name[grad_var.name] = param_var.name + + # distribute lookup table + self.table_name = find_distributed_lookup_table(self.origin_program) + self.has_distributed_lookup_table = self.table_name != None + self.origin_program._distributed_lookup_table = self.table_name if self.table_name else None + + # add distributed attrs to program + self.origin_program._is_distributed = True + self.origin_program._endpoints = self.pserver_endpoints + self.origin_program._ps_endpoint = current_endpoint + self.origin_program._is_chief = self.trainer_id == 0 + + # program info send to geo-sgd communicator + self.vars_info = collections.OrderedDict() + self.split_to_origin_mapping = collections.OrderedDict() + self.delta_vars_list = [] + self.sparse_var_list = [] + self.sparse_var_splited_list = [] + + # split and create vars, then put split vars in dicts for later use. + # step 1. split and create vars, then put split vars in dicts for later use. + self._init_splited_vars() + + # step 3. create send recv var (param after optimize) + send_vars = [] + ps_dispatcher.reset() + param_var_mapping_items = list(six.iteritems(self.param_var_mapping)) + # send_vars is the parameter which split by communicator and send to pserver,not the origin parameter + for _, splited_vars in param_var_mapping_items: + for _, var in enumerate(splited_vars): + send_vars.append(var) + + recv_vars = send_vars + + ps_dispatcher.reset() + eplist = ps_dispatcher.dispatch(recv_vars) + for i, ep in enumerate(eplist): + self.param_opt_ep_mapping[ep]["params"].append(recv_vars[i]) + distributed_var = self.vars_overview.get_distributed_var_by_slice( + recv_vars[i].name) + distributed_var.endpoint = ep + origin_name = self.split_to_origin_mapping[recv_vars[i].name] + self.vars_info[origin_name]["epmap"].append(ep) + self.origin_program._parameters_on_pservers = self.vars_overview + + # send sparse id to communicator + self.sparse_var = [] + self.sparse_tables = [] + unique_sparse_var = {} + for op in self.origin_program.global_block().ops: + if "is_sparse" in op.all_attrs(): + if op.type == "lookup_table": + op._set_attr('remote_prefetch', False) + for input_var_name, sparse_var_name in zip( + op.input("Ids"), op.input("W")): + if sparse_var_name in self.sparse_var_list: + if input_var_name in unique_sparse_var: + if unique_sparse_var[ + input_var_name] == sparse_var_name: + continue + input_var = program.global_block().var(input_var_name) + self.sparse_var.append(input_var) + self.sparse_tables.append(sparse_var_name) + unique_sparse_var[input_var_name] = sparse_var_name + + # batch training loop end flag + dummy_output = program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + program.global_block().append_op( + type="send", + inputs={"X": self.sparse_var}, + outputs={"Out": dummy_output}, + attrs={"send_varnames": self.sparse_tables}) + + # add param_init flag in trainer startup program + self.trainer_startup_program = self._get_trainer_startup_program( + recv_vars=recv_vars, eplist=eplist) + for delta_var in self.delta_vars_list: + self.trainer_startup_program.global_block().create_var( + name=delta_var.name, + persistable=delta_var.persistable, + dtype=delta_var.dtype, + type=delta_var.type, + shape=delta_var.shape) + dummy_output = self.trainer_startup_program.global_block().create_var( + name=framework.generate_control_dev_var_name()) + param_init = self.trainer_startup_program.global_block().create_var( + name="param_init") + self.trainer_startup_program.global_block().append_op( + type="send", + inputs={"X": [param_init]}, + outputs={"Out": dummy_output}, + attrs={"send_varnames": [param_init.name]}) + + def _get_vars_info(self): + return self.vars_info + + def get_trainer_program(self, wait_port=True): + if wait_port: + wait_server_ready(self.pserver_endpoints) + return self.origin_program + + def get_pserver_programs(self, endpoint): + pserver_prog = self.get_pserver_program(endpoint) + self.param_grad_ep_mapping = self.param_opt_ep_mapping + pserver_startup = self.get_startup_program(endpoint, + pserver_program=pserver_prog) + return pserver_prog, pserver_startup + + def get_pserver_program(self, endpoint): + # step1 + pserver_program = Program() + pserver_program.random_seed = self.origin_program.random_seed + pserver_program._copy_dist_param_info_from(self.origin_program) + + # step2: Create vars to receive vars at parameter servers. + recv_inputs = [] + for v in self.param_opt_ep_mapping[endpoint]["params"]: + self._clone_var(pserver_program.global_block(), v) + + optimize_block = [] + param_to_block_id = [] + sparse_grad_to_param = [] + + # append op to the current block + pre_block_idx = pserver_program.num_blocks - 1 + for var in self.param_opt_ep_mapping[endpoint]["params"]: + per_opt_block = pserver_program._create_block(pre_block_idx) + optimize_block.append(per_opt_block) + var_name = var.name + pserver_block = per_opt_block.program.global_block() + param = pserver_block.vars[var_name] + + delta_var_name = "%s.delta" % (param.name) + if var.name in self.sparse_var_splited_list: + delta_type = core.VarDesc.VarType.SELECTED_ROWS + sparse_grad_to_param.append(":".join( + [delta_var_name, param.name])) + else: + delta_type = param.type + delta_var = pserver_block.create_var(name=delta_var_name, + persistable=False, + type=delta_type, + dtype=param.dtype, + shape=param.shape) + + per_opt_block.append_op(type="sum", + inputs={"X": [param, delta_var]}, + outputs={"Out": param}) + param_to_block_id.append(delta_var_name + ":" + + str(per_opt_block.idx)) + + attrs = { + "optimize_blocks": optimize_block, + "endpoint": endpoint, + "Fanin": self.trainer_num, + "distributed_mode": DistributedMode.GEO, + "grad_to_block_id": param_to_block_id, + "sparse_grad_to_param": sparse_grad_to_param, + "rpc_get_thread_num": self.server_config._rpc_get_thread_num, + "rpc_send_thread_num": self.server_config._rpc_send_thread_num, + "rpc_prefetch_thread_num": + self.server_config._rpc_prefetch_thread_num + } + + # step5 append the listen_and_serv op + pserver_program.global_block().append_op(type="listen_and_serv", + inputs={'X': recv_inputs}, + outputs={}, + attrs=attrs) + + pserver_program._sync_with_cpp() + # save pserver program to generate pserver side startup relatively. + self.pserver_program = pserver_program + return pserver_program + + def _init_splited_vars(self): + param_list = [] + grad_list = [] + param_grad_set = set() + # step 1. create param_list + for p, g in self.params_grads: + if type(p) == Parameter and p.trainable == False: + continue + if p.name not in param_grad_set: + param_list.append(p) + param_grad_set.add(p.name) + if g.name not in param_grad_set: + grad_list.append(g) + param_grad_set.add(g.name) + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + self.sparse_var_list.append(p.name) + + # step 2. Slice vars into numbers of piece with block_size + # when we slice var up into blocks, we will slice the var according to + # pserver services' count. A pserver may have two or more listening ports. + param_blocks = slice_variable(param_list, len(self.pserver_endpoints), + self.config.min_block_size) + + # step 3. Create split param from split blocks + # origin_param_name -> [splited_param_vars] + # Todo: update _create_vars_from_blocklist + self.param_var_mapping = self._create_vars_from_blocklist( + self.origin_program, param_blocks) + + # step 4. Create mapping of endpoint -> split var to create pserver side program + self.param_opt_ep_mapping = collections.OrderedDict() + [ + self.param_opt_ep_mapping.update({ep: { + "params": [], + }}) for ep in self.pserver_endpoints + ] + + # step 5. Create delta var of Geo-Sgd & record vars information + for origin_name, splited_vars in self.param_var_mapping.items(): + origin_var = self.origin_program.global_block().var(origin_name) + self.vars_info[origin_name] = collections.OrderedDict() + self.vars_info[origin_name]["var_names"] = [] + vars_section = self._get_splited_var_sections(splited_vars) + self.vars_info[origin_name]["sections"] = [ + str(i) for i in vars_section + ] + self.vars_info[origin_name]["epmap"] = [] + self.vars_info[origin_name]["is_sparse"] = [] + # todo: add var shape(may be no need,because recv scope have) + if origin_name in self.sparse_var_list: + delta_type = core.VarDesc.VarType.SELECTED_ROWS + self.vars_info[origin_name]["is_sparse"].append("True") + else: + delta_type = origin_var.type + self.vars_info[origin_name]["is_sparse"].append("False") + + delta_var = self.origin_program.global_block().create_var( + name=".".join([origin_name, "delta"]), + persistable=False, + dtype=origin_var.dtype, + type=delta_type, + shape=origin_var.shape) + + self.delta_vars_list.append(delta_var) + + for splited_var in splited_vars: + is_slice, block_id, offset = self._get_slice_var_info( + splited_var) + self.vars_overview.add_distributed_var(origin_var=origin_var, + slice_var=splited_var, + block_id=block_id, + offset=offset, + is_slice=is_slice, + vtype="Param") + self.split_to_origin_mapping[splited_var.name] = origin_name + if origin_name in self.sparse_var_list: + self.sparse_var_splited_list.append(splited_var.name) + self.vars_info[origin_name]["var_names"].append( + splited_var.name) + if len(splited_vars) != 1: + self.origin_program.global_block().create_var( + name=".".join([splited_var.name, "delta"]), + persistable=False, + dtype=splited_var.dtype, + type=delta_type, + shape=splited_var.shape) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/memory_optimization_transpiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/memory_optimization_transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e91f2043683c8d8d4021665214252fb85beb9940 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/memory_optimization_transpiler.py @@ -0,0 +1,52 @@ +# Copyright (c) 2018 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. + +import logging + + +def memory_optimize(input_program, + skip_opt_set=None, + print_log=False, + level=0, + skip_grads=True): + """ + :api_attr: Static Graph + + This API is deprecated since 1.6. Please do not use it. The better + memory optimization strategies are enabled by default. + """ + logging.warn( + 'Caution! paddle.fluid.memory_optimize() is deprecated ' + 'and not maintained any more, since it is not stable!\n' + 'This API would not take any memory optimizations on your Program ' + 'now, since we have provided default strategies for you.\n' + 'The newest and stable memory optimization strategies (they are all ' + 'enabled by default) are as follows:\n' + ' 1. Garbage collection strategy, which is enabled by exporting ' + 'environment variable FLAGS_eager_delete_tensor_gb=0 (0 is the ' + 'default value).\n' + ' 2. Inplace strategy, which is enabled by setting ' + 'build_strategy.enable_inplace=True (True is the default value) ' + 'when using CompiledProgram or ParallelExecutor.\n') + + +def release_memory(input_program, skip_opt_set=None): + """ + :api_attr: Static Graph + + This API is deprecated since 1.6. Please do not use it. The better + memory optimization strategies are enabled by default. + """ + logging.warn('paddle.fluid.release_memory() is deprecated, it would not' + ' take any memory release on your program') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ps_dispatcher.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ps_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdd50c5523f40fe328592c554d2c18ee1f46100 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/transpiler/ps_dispatcher.py @@ -0,0 +1,129 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + + +class PSDispatcher(object): + """ + PSDispatcher is the base class for dispatching vars + into different pserver instance. + You need to implement the `dispatch` interface. + """ + + def __init__(self, pserver_endpoints): + self._eps = pserver_endpoints + self._step = 0 + + @property + def eps(self): + return self._eps + + def reset(self): + """ + reset the step counter, set it zero. + """ + self._step = 0 + + def dispatch(self, varlist): + """ + Args: + varlist(list): a list of Variables + Returns: + a map of pserver endpoint -> varname + """ + AssertionError("Interface has not been implemented.") + + +class HashName(PSDispatcher): + """ + :api_attr: Static Graph + + Hash variable names to several endpoints using python + "hash()" function. + + Args: + pserver_endpoints (list): list of endpoint(ip:port). + + Examples: + .. code-block:: python + + pserver_endpoints = ["127.0.0.1:6007", "127.0.0.1:6008"] + vars = ["var1","var2","var3","var4","var5"] + + rr = RoundRobin(pserver_endpoints) + rr.dispatch(vars) + + """ + + def __init__(self, pserver_endpoints): + super(self.__class__, self).__init__(pserver_endpoints) + + def _hash_block(self, block_str, total): + return hash(block_str) % total + + def dispatch(self, varlist): + """ + use `HashName` method to dispatch variables with each parameter server. + Args: + varlist (list): a list of Variables + + """ + eplist = [] + for var in varlist: + server_id = self._hash_block(var.name(), len(self._eps)) + server_for_param = self._eps[server_id] + eplist.append(server_for_param) + return eplist + + +class RoundRobin(PSDispatcher): + """ + :api_attr: Static Graph + + Distribute variables to several endpoints using + RondRobin method. + + Args: + pserver_endpoints (list): list of endpoint(ip:port). + + Examples: + .. code-block:: python + + pserver_endpoints = ["127.0.0.1:6007", "127.0.0.1:6008"] + vars = ["var1","var2","var3","var4","var5"] + + rr = RoundRobin(pserver_endpoints) + rr.dispatch(vars) + + """ + + def __init__(self, pserver_endpoints): + super(RoundRobin, self).__init__(pserver_endpoints) + + def dispatch(self, varlist): + """ + use `RoundRobin` method to dispatch variables with each parameter server. + Args: + varlist (list): a list of Variables + + """ + eplist = [] + for var in varlist: + server_for_param = self._eps[self._step] + eplist.append(server_for_param) + self._step += 1 + if self._step >= len(self._eps): + self._step = 0 + return eplist diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/unique_name.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/unique_name.py new file mode 100644 index 0000000000000000000000000000000000000000..090d0e8dcbb87d259a7460a8ffab655b3ea425f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/unique_name.py @@ -0,0 +1,228 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import collections +from .wrapped_decorator import signature_safe_contextmanager +import six +import sys + +__all__ = ['generate', 'switch', 'guard'] + + +class UniqueNameGenerator(object): + """ + Generate unique name with prefix. + + Args: + prefix(str): The generated name prefix. All generated name will be + started with this prefix. + """ + + def __init__(self, prefix=None): + self.ids = collections.defaultdict(int) + if prefix is None: + prefix = "" + self.prefix = prefix + + def __call__(self, key): + """ + Generate unique names with prefix + + Args: + key(str): The key of return string. + + Returns(str): A unique string with the prefix + """ + tmp = self.ids[key] + self.ids[key] += 1 + return self.prefix + "_".join([key, str(tmp)]) + + +class DygraphParameterNameChecker(object): + """ + Check whether the name of parameter is used. + """ + + def __init__(self): + self._name_set = set() + + def __call__(self, name): + ''' + Check whether the name is used. If not used, insert into the _name_set. + + Args: + name(str): The name of parameter to check. + + Returns(bool): If the name is in name_set, return True; Otherwise, return False. + + ''' + if name in self._name_set: + return True + else: + self._name_set.add(name) + return False + + +dygraph_parameter_name_checker = DygraphParameterNameChecker() + +generator = UniqueNameGenerator() + + +def generate(key): + """ + Generate unique name with prefix key. Currently, Paddle distinguishes the + names of the same key by numbering it from zero. For example, when key=fc, + it continuously generates fc_0, fc_1, fc_2, etc. + + Args: + key(str): The prefix of generated name. + + Returns: + str: A unique string with the prefix key. + + Examples: + + .. code-block:: python + + import paddle + name1 = paddle.utils.unique_name.generate('fc') + name2 = paddle.utils.unique_name.generate('fc') + print(name1, name2) # fc_0, fc_1 + """ + return generator(key) + + +# FIXME(zjl): The previous naming rule in static graph would +# cause memory leak in dygraph mode. It is because the previous +# naming rule would use `conv_0.tmp` as the key, and in dygraph +# mode, `conv_i` increases as batch increases. Thus, keys would +# increase in a way like `conv_0.tmp`, `conv_1.tmp`, .... +# Not find a better way to fix this bug in dygraph mode. In TF, +# variable name is meaningless in eager execution mode, and in +# PyTorch, there is no variable name at all. Maybe we should +# discard variable name in dygraph mode. +# +# Another concern is that save/load interfaces. Usually, user +# would save model in static graph mode, and load it in dygraph +# mode. Therefore, we keep the variable name of Parameter currently. +# +# Please fix me if a better method is found. +# +# NOTE(zhiqiu): use c++ unique_name_generator in dygraph mode, +# in order to keep name consistency. +def generate_with_ignorable_key(key): + from .framework import _non_static_mode, _dygraph_tracer + if _non_static_mode(): + return _dygraph_tracer()._generate_unique_name() + + return generator(key) + + +def switch(new_generator=None, new_para_name_checker=None): + """ + Switch the namespace of in current context to a new namespace. Though + :code:`switch()` and :code:`guard()` can both change namespace, + :code:`guard()` is recommended since it can manage the context better + together with :code:`with` statement. + + Args: + new_generator(UniqueNameGenerator, optional): A new UniqueNameGenerator, not + required normally. Default is None, which means switch to a new anonymous + namespace. + new_para_name_checker(DygraphParameterNameChecker, optional): A new DygraphParameterNameChecker, + not required normally. Default is None, which means switch to a new parameter name + checker. + + Returns: + UniqueNameGenerator: The previous UniqueNameGenerator. + DygraphParameterNameChecker: The previous DygraphParameterNameChecker + + Examples: + + .. code-block:: python + + import paddle + name1 = paddle.utils.unique_name.generate('fc') + name2 = paddle.utils.unique_name.generate('fc') + print(name1, name2) # fc_0, fc_1 + + pre_generator, pre_dygraph_name_checker = paddle.utils.unique_name.switch() # switch to a new anonymous namespace. + name2 = paddle.utils.unique_name.generate('fc') + print(name2) # fc_0 + + paddle.utils.unique_name.switch(pre_generator, pre_dygraph_name_checker) # switch back to pre_generator. + name3 = paddle.utils.unique_name.generate('fc') + print(name3) # fc_2, since pre_generator has generated fc_0, fc_1. + """ + global generator + old_generator = generator + global dygraph_parameter_name_checker + old_para_name_checker = dygraph_parameter_name_checker + if new_generator is None: + generator = UniqueNameGenerator() + else: + generator = new_generator + + if new_para_name_checker is None: + dygraph_parameter_name_checker = DygraphParameterNameChecker() + else: + dygraph_parameter_name_checker = new_para_name_checker + return old_generator, old_para_name_checker + + +@signature_safe_contextmanager +def guard(new_generator=None): + """ + Change the namespace of unique name with :code:`with` statement. After calling it, + a new namespace in the context of :code:`with` will be created, and it will number + names from zero again when calling :code:`generate()` with same key. + + Args: + new_generator(str|bytes, optional): New name of global namespace. Note that str + in Python2 was spilted into str and bytes in Python3, so here are two + types. Default is None. If not None, new_generator will be added into + the prefix of unique name generated by :code:`generate()`. + + Returns: + None. + + Examples: + + .. code-block:: python + + import paddle + with paddle.utils.unique_name.guard(): + name_1 = paddle.utils.unique_name.generate('fc') + with paddle.utils.unique_name.guard(): + name_2 = paddle.utils.unique_name.generate('fc') + print(name_1, name_2) # fc_0, fc_0 + + with paddle.utils.unique_name.guard('A'): + name_1 = paddle.utils.unique_name.generate('fc') + with paddle.utils.unique_name.guard('B'): + name_2 = paddle.utils.unique_name.generate('fc') + print(name_1, name_2) # Afc_0, Bfc_0 + """ + if isinstance(new_generator, six.string_types): + new_generator = UniqueNameGenerator(new_generator) + elif isinstance(new_generator, six.binary_type): + new_generator = UniqueNameGenerator(new_generator.decode()) + + old_generator, old_para_name_checker = switch(new_generator) + try: + yield + finally: + switch(old_generator, old_para_name_checker) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/variable_index.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/variable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..1a13e8304194c8e02d91c8695683533876d21f41 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/variable_index.py @@ -0,0 +1,798 @@ +# Copyright (c) 2021 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. + +import sys +import numpy as np +from . import unique_name +from . import core +import paddle + +MAX_INTEGER = 2**31 - 1 + + +def is_list_tuple(index, contain_type): + + def _is_list_tuple(item): + if not (isinstance(item, (list, tuple)) or type(item) == contain_type): + return False + if isinstance(item, (tuple, list)): + for s in item: + if not _is_list_tuple(s): + return False + return True + + if not isinstance(index, (tuple, list)): + return False + for s in index: + if not _is_list_tuple(s): + return False + return True + + +def is_one_dim_list(index, contain_type): + if isinstance(index, list): + for i in index: + if not isinstance(i, contain_type): + return False + else: + return False + return True + + +def get_list_index_shape(var_dims, index_dims): + var_dims_size = len(var_dims) + index_dims_size = len(index_dims) + + out_dims_size = var_dims_size - index_dims[0] + index_dims_size - 1 + + out_dims_shape = [1] * out_dims_size + + out_dims_shape[:index_dims_size - 1] = index_dims[1:] + + out_dims_shape[index_dims_size - 1:] = var_dims[index_dims[0]:] + return out_dims_shape + + +class SliceInfo: + + def __init__(self): + self.pre_shape = None + self.indexes = [] + self.dtype = None + + def update(self, index): + if is_list_tuple(index, int) or isinstance( + index, (paddle.fluid.Variable, np.ndarray)): + # convert index to Tensor + if not isinstance(index, paddle.fluid.Variable): + index = paddle.assign(index) + + if self.dtype is None: + self.dtype = index.dtype + else: + if index.dtype != self.dtype: + raise IndexError( + "Data type of Tensor/List index should be same. The current data type is {}, but the previous data type is {}." + .format(index.dtype, self.dtype)) + + self.indexes.append(index) + + if self.pre_shape is None: + self.pre_shape = index.shape + else: + if self.pre_shape != index.shape: + # broadcast + cur_shape = paddle.broadcast_shape(self.pre_shape, + index.shape) + for i in range(len(self.indexes)): + self.indexes[i] = paddle.broadcast_to( + self.indexes[i], cur_shape) + self.pre_shape = self.indexes[-1].shape + else: + raise ValueError( + "Index should be list/tuple of int or Tensor, but received {}.". + format(index)) + + def shape_stride(self, shape): + s = [1] * len(shape) + for i in range(len(shape) - 2, -1, -1): + s[i] = shape[i + 1] * s[i + 1] + + return s + + def numel(self, shape): + return reduce(lambda x, y: x * y, shape) + + def get_offset_stride(self, tensor_shape): + for index in self.indexes: + if not isinstance(index, paddle.fluid.Variable): + raise ValueError( + "only support list/tensor index, but received {}.".format( + type(index))) + + if len(self.indexes) <= len(tensor_shape) or len(self.indexes) == 1: + shape = paddle.stack(self.indexes) + axes = list(range(1, + len(self.pre_shape) + 1)) + [ + 0, + ] + + else: + raise ValueError( + "too many indices for tensor: tensor is {}-dimensional, but {} were indexed" + .format(len(tensor_shape), self.pre_shape[0])) + + shape_transpose = paddle.transpose(shape, axes) + return shape_transpose + + def get_item(self, tensor): + shape_transpose = self.get_offset_stride(tensor.shape) + index = paddle.assign(shape_transpose) + return paddle.gather_nd(tensor, index) + + def set_item(self, tensor_origin, value): + + if not isinstance(value, paddle.fluid.Variable): + value = paddle.assign(value) + tensor_type = None + + if tensor_origin.dtype in [ + core.VarDesc.VarType.FP32, core.VarDesc.VarType.FP64 + ]: + tensor = tensor_origin + else: + tensor_type = tensor_origin.dtype + tensor = tensor_origin.astype(core.VarDesc.VarType.FP32) + + if value.dtype != tensor.dtype: + value = value.astype(tensor.dtype) + + shape_transpose = self.get_offset_stride(tensor_origin.shape) + index = paddle.assign(shape_transpose) + + gather_tensor_shape = get_list_index_shape(tensor.shape, [ + len(self.indexes), + ] + list(self.indexes[-1].shape)) + + value_dims_bd = [ + 1, + ] * len(gather_tensor_shape) + value_dims_bd[-len(value.shape):] = list(value.shape) + + for i in range(len(gather_tensor_shape)): + if not (value_dims_bd[i] == gather_tensor_shape[i] + or value_dims_bd[i] == 1): + raise ValueError("{} can not broadcast into {}".format( + value.shape, gather_tensor_shape)) + + value_broadcast = paddle.broadcast_to(value, gather_tensor_shape) + + value_1d = value_broadcast.reshape( + [-1] + gather_tensor_shape[len(index.shape) - 1:]) + + index_1d = index.reshape([-1, index.shape[-1]]) + + tensor_stride = paddle.assign( + self.shape_stride(tensor.shape[:index.shape[-1]])) + inds = [] + for i in range(index_1d.shape[0]): + temp = (index_1d[i] * tensor_stride).sum() + inds.append(temp) + index_1d = paddle.stack(inds).reshape([-1]) + t_reshape = tensor.reshape([-1] + list(tensor.shape[index.shape[-1]:])) + out = paddle.scatter(t_reshape, index_1d, value_1d) + if tensor_type is not None: + out = out.astype(tensor_type) + tensor_origin[:] = out.reshape(tensor_origin.shape) + + return tensor_origin + + +def replace_ellipsis(var, item): + from .framework import Variable + # Use slice(None) to replace Ellipsis. + # For var, var.shape = [3,4,5,6] + # + # var[..., 1:2] -> var[:, :, :, 1:2] + # var[0, ...] -> var[0] + # var[0, ..., 1:2] -> var[0, :, :, 1:2] + + item = list(item) + + # Remove Variable to skip bug when counting Ellipsis + item_remove_var = [ + ele for ele in item + if not isinstance(ele, (Variable, np.ndarray)) and ele is not None + ] + ell_count = item_remove_var.count(Ellipsis) + if ell_count == 0: + return item + elif ell_count > 1: + raise IndexError("An index can only have a single ellipsis ('...')") + + ell_idx = item.index(Ellipsis) + + if ell_idx == len(item) - 1: + return item[:-1] + else: + item[ell_idx:ell_idx + + 1] = [slice(None) + ] * (len(var.shape) - len(item) + item.count(None) + 1) + + return item + + +def replace_ndarray(item): + new_item = [] + for slice_item in item: + if isinstance(slice_item, np.ndarray): + new_item.append(paddle.assign(slice_item)) + else: + new_item.append(slice_item) + return new_item + + +def replace_none(item): + new_item = [] + none_axes = [] + for i, slice_item in enumerate(item): + if slice_item is None: + none_axes.append(i) + else: + new_item.append(slice_item) + return new_item, none_axes + + +def is_integer_or_scalar_tensor(ele): + from .framework import Variable + if isinstance(ele, int): + return True + elif isinstance(ele, Variable): + if len(ele.shape) == 1 and ele.shape[0] == 1: + return True + return False + + +def is_bool_tensor(ele): + from .framework import Variable + if isinstance(ele, Variable) and ele.dtype == paddle.bool: + return True + return False + + +def deal_attrs(attrs, attr, attr_name, tensor_attr_name, inputs, infer_flags): + from .framework import Variable + from .layers import utils + + if utils._contain_var(attr): + inputs[tensor_attr_name] = utils._convert_to_tensor_list(attr, + dtype="int64") + for i, dim in enumerate(attr): + if isinstance(dim, Variable): + attrs[attr_name].append(-1) + infer_flags[i] = -1 + else: + attrs[attr_name].append(dim) + else: + attrs[attr_name] = attr + + +# the item is a tensor of bool +def get_value_for_bool_tensor(var, item): + if len(item.shape) > len(var.shape): + raise IndexError("The dims of bool index doesn't match indexed array, " + "the dims of bool index except to be equal or less " + "than {}, but received {}.".format( + len(var.shape), len(item.shape))) + for i, dim_len in enumerate(item.shape): + if dim_len != var.shape[i]: + raise IndexError( + "The dimension of bool index doesn't match indexed array along "\ + "dimension {}, the target dimension is {}, but received {}.". + format(i, var.shape[i], dim_len)) + + def idx_not_empty(var, item): + from .layers.nn import where + from ..tensor import gather_nd + + bool_2_idx = where(item == True) + return gather_nd(var, bool_2_idx) + + def idx_empty(var): + var_shape = list(var.shape) + var_shape[0] = 0 + return paddle.empty(var_shape, dtype=var.dtype) + + from .layers.control_flow import cond + return cond(item.any(), lambda: idx_not_empty(var, item), + lambda: idx_empty(var)) + + +def _getitem_impl_(var, item): + """ + Slice the variable. + + Args: + item(int/slice/tuple) : the index. + + Returns: + Sliced variable + """ + from .framework import default_main_program, Variable + if isinstance(item, list): + if not is_one_dim_list(item, int): + item = tuple(item) + + if not isinstance(item, tuple): + item = (item, ) + + decrease_axes = [] + axes = [] + starts = [] + ends = [] + steps = [] + reverse_axes = [] + + use_strided_slice = False + item = replace_ndarray(item) + item = replace_ellipsis(var, item) + item, none_axes = replace_none(item) + slice_info = SliceInfo() + + for dim, slice_item in enumerate(item): + if is_integer_or_scalar_tensor( + slice_item) and not is_bool_tensor(slice_item): + if isinstance(slice_item, + int) and var.shape[dim] is not None and var.shape[ + dim] >= 0 and slice_item >= var.shape[dim]: + # For python, if users write a, b = var, the __getitem__ + # method will iterate through 0, 1, 2 ... until __getitem__ + # throws an IndexError, then stop. The var[0], var[1] will + # be given to a, b respectively. If more values are given, + # the unpack size would cause error. + # + # We raises IndexError here to support grammar like `a, b = var` + raise IndexError( + "slice_item %d at dim %d should be >= 0 and < var.shape[%d]: %d" + % (slice_item, dim, dim, var.shape[dim])) + decrease_axes.append(dim) + start = slice_item + step = 1 + end = slice_item + 1 if slice_item != -1 else MAX_INTEGER + + elif isinstance(slice_item, slice): + start = slice_item.start + end = slice_item.stop + step = slice_item.step + + if start is None and end is None and step is None: + continue + + step = 1 if step is None else step + + if start is None: + start = 0 if step > 0 else MAX_INTEGER + if end is None: + if var.shape[dim] != -1 and ( + paddle.fluid.framework._non_static_mode() + or var.desc.type() != + core.VarDesc.VarType.LOD_TENSOR_ARRAY): + end = var.shape[dim] if step > 0 else -1 + else: + end = MAX_INTEGER if step > 0 else -1 + + elif isinstance(slice_item, list): + all_bool = True + + if is_list_tuple(slice_item, int): + slice_info.update(slice_item) + continue + + for i in slice_item: + if type(i) is int: + all_bool = False + elif not isinstance(i, bool): + raise TypeError("Only support int or bool in index list.") + + if len(item) != 1: + raise IndexError( + "When index contains a list, its length must be 1, but received {}." + .format(len(item))) + new_slice_item = [] + if all_bool: + if len(slice_item) != var.shape[0]: + raise IndexError( + "The dimension of bool index doesn't match indexed array along "\ + "dimension 0, the target dimension is {}, but received {}.". + format(var.shape[0], len(slice_item))) + for idx, ele in enumerate(slice_item): + if ele is True: + new_slice_item.append(idx) + slice_item = new_slice_item + else: + for idx, ele in enumerate(slice_item): + if type(ele) is int: + new_slice_item.append(ele) + elif ele is True: + new_slice_item.append(1) + else: + new_slice_item.append(0) + slice_item = new_slice_item + + from .layers import assign + from ..tensor import index_select + + idx = assign(np.array(slice_item).astype("int32")) + return index_select(var, index=idx, axis=0) + + elif isinstance(slice_item, (Variable, core.eager.Tensor)): + if len(item) == 1: + + from ..tensor import index_select + + if slice_item.dtype == paddle.bool: + return get_value_for_bool_tensor(var, slice_item) + else: + if len(slice_item.shape) == 1: + return index_select(var, index=slice_item, axis=0) + else: + slice_info.update(slice_item) + continue + else: + slice_info.update(slice_item) + continue + + else: + raise IndexError( + "Valid index accept int or slice or ellipsis or list, but received {}." + .format(slice_item)) + + axes.append(dim) + starts.append(start) + ends.append(end) + steps.append(step) + use_strided_slice = True if step != 1 else use_strided_slice + + if slice_info.indexes: + if len(slice_info.indexes) != len(item): + raise IndexError( + "Valid index accept int or slice or ellipsis or list, but received {}." + .format(item)) + return slice_info.get_item(var) + + inputs = {'Input': [var]} + attrs = { + 'axes': axes, + 'starts': [], + 'ends': [], + 'decrease_axis': decrease_axes + } + if use_strided_slice: + attrs['strides'] = [] + + infer_flags = [1] * len(axes) + deal_attrs(attrs, starts, "starts", "StartsTensorList", inputs, infer_flags) + deal_attrs(attrs, ends, "ends", "EndsTensorList", inputs, infer_flags) + deal_attrs(attrs, steps, "strides", "StridesTensorList", inputs, + infer_flags) + attrs['infer_flags'] = infer_flags + + out = var + if len(axes) > 0: + op_type = "strided_slice" if use_strided_slice else "slice" + if paddle.fluid.framework.in_dygraph_mode() and op_type == "slice": + if "StartsTensorList" in inputs.keys(): + st = inputs['StartsTensorList'] + else: + st = attrs['starts'] + if "EndsTensorList" in inputs.keys(): + end = inputs['EndsTensorList'] + else: + end = attrs['ends'] + out = paddle._C_ops.slice(var, axes, st, end, attrs['infer_flags'], + attrs['decrease_axis']) + else: + target_block = default_main_program().current_block() + + slice_out_var = target_block.create_var( + name=unique_name.generate_with_ignorable_key(var.name + "_" + + op_type), + dtype=var.dtype) + target_block.append_op(type=op_type, + inputs=inputs, + outputs={'Out': [slice_out_var]}, + attrs=attrs) + out = slice_out_var + + if len(reverse_axes) > 0: + from .layers.tensor import reverse + out = reverse(out, axis=reverse_axes) + + # Deal with cases when all axes are decreased. + # After slice, the shape of out is [1], which should have been [], but Paddle doesn't support scalar. + # In order to ensure the correctness of the final shape of out, one dimension of out needs to be decreased. + # For example: + # # x.shape: (2,3,4) + # out = x[0, 1, 1, None] # out.shape : (1) + if len(decrease_axes) == len(var.shape): + none_axes = none_axes[1:] + + if len(none_axes) > 0: + # Deal with cases that decrease_axes is not empty + # For example: + # # x.shape: (2,3,4) + # out = x[0, 0:2, None] # out.shape : (2, 1, 4) + for idx, axis in enumerate(none_axes): + l = len([i for i in decrease_axes if i < axis]) + new_axis = axis - l + none_axes[idx] = new_axis + + # Deal with cases when all axes are decreased. + # After slice, the shape of out is [1], which should have been [], but Paddle doesn't support scalar. + # In order to ensure the correctness of the final shape of out, one dimension of out needs to be decreased. + # For example: + # # x.shape: (2,3,4) + # out = x[0, 1, 1, None] # out.shape : (1) + + from ..tensor import unsqueeze + out = unsqueeze(out, axis=none_axes) + + return out + + +def _setitem_for_tensor_array(var, item, value): + """ branches for tensor array setitem operation. + A item can be a: + (1) int/Variable, which is a simple number/variable such as [1], [-2] + (2) Slice, which is represented by bounds such as [2:-1] + (3) Tuple, which includes the above two cases such as [2:-1, 1] + If item is case (1), we perform paddle.tensor.array_write, + in other cases, we raise a NotImplementedError. + """ + from ..framework import LayerHelper, core, _non_static_mode + from .framework import Variable + assert not _non_static_mode( + ), "setitem for tensor_array must be called in static graph mode." + if isinstance(item, (Variable, int)): + from paddle.fluid.dygraph.dygraph_to_static.variable_trans_func import to_static_variable + from paddle import cast + from paddle.tensor import array_write + item = paddle.cast(to_static_variable(item), dtype='int64') + value = to_static_variable(value) + array_write(x=value, i=item, array=var) + else: + raise NotImplementedError( + "Only support __setitem__ by Int/Variable in tensor_array, but gets {}" + .format(type(item))) + + +def _setitem_impl_(var, item, value): + from .framework import default_main_program, Variable + from paddle.fluid import core + if var.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + return _setitem_for_tensor_array(var, item, value) + + inputs = {'Input': var} + if isinstance(item, list): + if not is_one_dim_list(item, int): + item = tuple(item) + # 1. Parse item + if not isinstance(item, tuple): + item = (item, ) + + decrease_axes = [] + axes = [] + starts = [] + ends = [] + steps = [] + + item = replace_ndarray(item) + item = replace_ellipsis(var, item) + item, none_axes = replace_none(item) + slice_info = SliceInfo() + dim = 0 + for _, slice_item in enumerate(item): + if is_integer_or_scalar_tensor( + slice_item) and not is_bool_tensor(slice_item): + decrease_axes.append(dim) + start = slice_item + end = slice_item + 1 if slice_item != -1 else MAX_INTEGER + step = 1 + + elif isinstance(slice_item, slice): + start = slice_item.start + end = slice_item.stop + step = slice_item.step + + if start is None and end is None and step is None: + dim += 1 + continue + + step = 1 if step is None else step + + if not isinstance(step, Variable) and step == 0: + raise ValueError( + "When assign a value to a paddle.Tensor, step can not be 0, " + "but received step is {}.".format(step)) + + if isinstance(step, Variable) and (start is None or end is None): + raise ValueError( + "When assign a value to a paddle.Tensor, it's not supported that " + "the start or end is None when the type of step is paddle.Tensor." + ) + + if start is None: + start = 0 if step > 0 else MAX_INTEGER + + if end is None: + end = MAX_INTEGER if step > 0 else (0 - MAX_INTEGER) + elif isinstance(slice_item, list): + if is_list_tuple(slice_item, int): + slice_info.update(slice_item) + continue + + for i in slice_item: + if not isinstance(i, bool): + raise TypeError("Doesn't support {} in index list.".format( + type(i))) + + if len(item) != 1: + raise IndexError( + "When index contains a bool list, its length must be 1, but received {}." + .format(len(item))) + + from .layers import assign + idx_tensor = assign(slice_item) + return set_value_for_bool_tensor(var, idx_tensor, value) + + elif isinstance(slice_item, Variable): + if slice_item.dtype == core.VarDesc.VarType.BOOL: + if len(item) != 1: + raise IndexError( + "When index contains a bool tensor, its length must be 1, but received {}." + .format(len(item))) + return set_value_for_bool_tensor(var, slice_item, value) + else: + slice_info.update(slice_item) + continue + else: + raise IndexError( + "Valid index accept int, slice, ellipsis, None, list of bool, Variable, " + "but received {}.".format(slice_item)) + + axes.append(dim) + starts.append(start) + ends.append(end) + steps.append(step) + + dim += 1 + if slice_info.indexes: + if len(slice_info.indexes) != len(item): + raise IndexError( + "Valid index accept int or slice or ellipsis or list, but received {}." + .format(item)) + return slice_info.set_item(var, value) + attrs = { + 'axes': axes, + 'starts': starts, + 'ends': ends, + 'steps': steps, + 'decrease_axes': decrease_axes, + 'none_axes': none_axes + } + + from .layers import utils + if utils._contain_var(starts): + inputs['StartsTensorList'] = utils._convert_to_tensor_list(starts) + del attrs['starts'] + if utils._contain_var(ends): + inputs['EndsTensorList'] = utils._convert_to_tensor_list(ends) + del attrs['ends'] + if utils._contain_var(steps): + inputs['StepsTensorList'] = utils._convert_to_tensor_list(steps) + del attrs['steps'] + + # 2. Parse value + dtype = var.dtype + attrs['dtype'] = dtype + + from .data_feeder import convert_dtype + # 2.1 value is an integer of float + if isinstance(value, (int, float)): + value = np.array([value]).astype(convert_dtype(dtype)) + + # 2.2 value is a np.ndarray + if isinstance(value, np.ndarray): + shape = list(value.shape) + if dtype == core.VarDesc.VarType.BOOL: + value_name = "bool_values" + values = [int(v) for v in value.flat] + elif dtype == core.VarDesc.VarType.FP32: + value_name = "fp32_values" + values = [float(v) for v in value.flat] + elif dtype == core.VarDesc.VarType.FP64: + value_name = "fp64_values" + values = [float(v) for v in value.flat] + elif dtype == core.VarDesc.VarType.INT32: + value_name = "int32_values" + values = [int(v) for v in value.flat] + elif dtype == core.VarDesc.VarType.INT64: + value_name = "int64_values" + values = [int(v) for v in value.flat] + elif dtype == core.VarDesc.VarType.FP16: + value_name = "fp16_values" + values = [float(v) for v in value.flat] + else: + raise TypeError( + "When assign a numpy.ndarray, integer or float to a paddle.Tensor, " + "the data type of the paddle.Tensor must be bool, float32, int32, int64 or float16, but " + "received %s." % convert_dtype(dtype)) + attrs[value_name] = values + attrs["shape"] = shape + + elif isinstance(value, (Variable, core.eager.Tensor)): + inputs["ValueTensor"] = value + else: + raise TypeError( + "Only support to assign an integer, float, numpy.ndarray or " + "paddle.Tensor to a paddle.Tensor, but received {}".format( + type(value))) + + if paddle.fluid.framework._non_static_mode(): + var._bump_inplace_version() + + cur_block = default_main_program().current_block() + cur_block.append_op(type="set_value", + inputs=inputs, + outputs={'Out': var}, + attrs=attrs, + inplace_map={"Input": "Out"}) + + return var + + +# the item is a tensor of bool +def set_value_for_bool_tensor(var, item, value): + if len(item.shape) > len(var.shape): + raise IndexError("The dims of bool index doesn't match indexed array, " + "the dims of bool index except to be equal or less " + "than {}, but received {}.".format( + len(var.shape), len(item.shape))) + for i, dim_len in enumerate(item.shape): + if dim_len != var.shape[i]: + raise IndexError( + "The dimension of bool index doesn't match indexed array along " + "dimension {}, the target dimension is {}, but received {}.". + format(i, var.shape[i], dim_len)) + + def idx_not_empty(var, item, value): + from .framework import Variable + from .layers import assign + from .layers.nn import where + from ..tensor import gather_nd, scatter_nd_add + + if not isinstance(value, Variable): + value = assign(value).cast(var.dtype) + + idx = where(item) + gather_val = gather_nd(var, idx) + gather_val_new = value - gather_val + out = scatter_nd_add(var, idx, gather_val_new) + var[:] = out + + from .layers.control_flow import cond + # If all the bool index is False, just do nothing + cond(item.any(), lambda: idx_not_empty(var, item, value)) + + return var diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/wrapped_decorator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/wrapped_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..5f837b575637c561defc664f740bfc8e673c0aad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/fluid/wrapped_decorator.py @@ -0,0 +1,31 @@ +# 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. + +import decorator +import contextlib + +__all__ = ['wrap_decorator', 'signature_safe_contextmanager'] + + +def wrap_decorator(decorator_func): + + @decorator.decorator + def __impl__(func, *args, **kwargs): + wrapped_func = decorator_func(func) + return wrapped_func(*args, **kwargs) + + return __impl__ + + +signature_safe_contextmanager = wrap_decorator(contextlib.contextmanager) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34423e3f3ed6b5914dafc92232846b3580558545 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/__init__.py @@ -0,0 +1,60 @@ +# 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. + +# TODO: import framework api under this directory + +from . import random # noqa: F401 +from .random import seed # noqa: F401 +from .framework import get_default_dtype # noqa: F401 +from .framework import set_default_dtype # noqa: F401 +from .framework import set_grad_enabled # noqa: F401 +from .framework import is_grad_enabled # noqa: F401 + +from ..fluid.param_attr import ParamAttr # noqa: F401 +from ..fluid.layers.tensor import create_parameter # noqa: F401 +from ..fluid.core import CPUPlace # noqa: F401 +from ..fluid.core import IPUPlace # noqa: F401 +from ..fluid.core import CUDAPlace # noqa: F401 +from ..fluid.core import CUDAPinnedPlace # noqa: F401 +from ..fluid.core import NPUPlace # noqa: F401 +from ..fluid.core import MLUPlace # noqa: F401 +from ..fluid.core import CustomPlace # noqa: F401 +from ..fluid.core import VarBase # noqa: F401 + +from ..fluid import core # noqa: F401 +from ..fluid.dygraph.base import no_grad_ as no_grad # noqa: F401 +from ..fluid.dygraph.base import grad # noqa: F401 +from .io import save # noqa: F401 +from .io import load # noqa: F401 +from ..fluid.dygraph.parallel import DataParallel # noqa: F401 + +from ..fluid import monkey_patch_variable +from ..fluid.dygraph import monkey_patch_math_varbase +from ..fluid.framework import disable_signal_handler # noqa: F401 +from ..fluid.framework import get_flags # noqa: F401 +from ..fluid.framework import set_flags # noqa: F401 +from ..fluid.dygraph.base import enable_dygraph as disable_static # noqa: F401 +from ..fluid.dygraph.base import disable_dygraph as enable_static # noqa: F401 +from ..fluid.framework import _non_static_mode as in_dynamic_mode # noqa: F401 +from ..fluid.framework import _non_static_mode # noqa: F401; temporary used for hackson +from ..fluid.framework import _current_expected_place, _get_paddle_place # noqa: F401 +from ..fluid.framework import dygraph_only # noqa: F401 +from ..fluid.framework import convert_np_dtype_to_dtype_, _varbase_creator, OpProtoHolder # noqa: F401 +from ..fluid.framework import _dygraph_tracer # noqa: F401 + +from ..fluid.layer_helper import LayerHelper # noqa: F401 +from ..fluid.framework import in_dygraph_mode # noqa: F401 +from ..fluid.framework import _in_legacy_dygraph # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/dtype.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..6abc8e6e1aa9a7af641bb3a125e27b7a4943d688 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/dtype.py @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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. + +from ..fluid.core import VarDesc +from ..fluid.core import iinfo as core_iinfo + +dtype = VarDesc.VarType +dtype.__qualname__ = "dtype" +dtype.__module__ = "paddle" + +uint8 = VarDesc.VarType.UINT8 +int8 = VarDesc.VarType.INT8 +int16 = VarDesc.VarType.INT16 +int32 = VarDesc.VarType.INT32 +int64 = VarDesc.VarType.INT64 + +float32 = VarDesc.VarType.FP32 +float64 = VarDesc.VarType.FP64 +float16 = VarDesc.VarType.FP16 +bfloat16 = VarDesc.VarType.BF16 + +complex64 = VarDesc.VarType.COMPLEX64 +complex128 = VarDesc.VarType.COMPLEX128 + +bool = VarDesc.VarType.BOOL + + +def iinfo(dtype): + """ + + paddle.iinfo is a function that returns an object that represents the numerical properties of + an integer paddle.dtype. + This is similar to `numpy.iinfo `_. + + Args: + dtype(paddle.dtype): One of paddle.uint8, paddle.int8, paddle.int16, paddle.int32, and paddle.int64. + + Returns: + An iinfo object, which has the following 4 attributes: + + - min: int, The smallest representable integer number. + - max: int, The largest representable integer number. + - bits: int, The number of bits occupied by the type. + - dtype: str, The string name of the argument dtype. + + Examples: + .. code-block:: python + + import paddle + + iinfo_uint8 = paddle.iinfo(paddle.uint8) + print(iinfo_uint8) + # paddle.iinfo(min=0, max=255, bits=8, dtype=uint8) + print(iinfo_uint8.min) # 0 + print(iinfo_uint8.max) # 255 + print(iinfo_uint8.bits) # 8 + print(iinfo_uint8.dtype) # uint8 + + """ + return core_iinfo(dtype) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/framework.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..819c08a7f3ac97a23d417c42608409ba355d3ca5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/framework.py @@ -0,0 +1,149 @@ +# 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. + +# TODO: define framework api +from paddle.fluid.layer_helper_base import LayerHelperBase +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid.framework import _dygraph_tracer +import numpy as np +from contextlib import contextmanager + +__all__ = [] + + +def set_default_dtype(d): + """ + Set default dtype. The default dtype is initially float32. + + Args: + d(string|np.dtype): the dtype to make the default. It only + supports float16, float32 and float64. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + paddle.set_default_dtype("float32") + + """ + if isinstance(d, type): + if d in [np.float16, np.float32, np.float64]: + d = d.__name__ + else: + raise TypeError( + "set_default_dtype only supports [float16, float32, float64] " + ", but received %s" % d.__name__ + ) + else: + if d in [ + 'float16', + 'float32', + 'float64', + u'float16', + u'float32', + u'float64', + ]: + # this code is a little bit dangerous, since error could happen + # when casting no-ascii code to str in python2. + # but since the set itself is limited, so currently, it is good. + # however, jointly supporting python2 and python3, (as well as python4 maybe) + # may still be a long-lasting problem. + d = str(d) + else: + raise TypeError( + "set_default_dtype only supports [float16, float32, float64] " + ", but received %s" % str(d) + ) + + LayerHelperBase.set_default_dtype(d) + + +def get_default_dtype(): + """ + Get the current default dtype. The default dtype is initially float32. + + Args: + None. + Returns: + String, this global dtype only supports float16, float32, float64. + + Examples: + .. code-block:: python + + import paddle + paddle.get_default_dtype() + """ + return LayerHelperBase.get_default_dtype() + + +@contextmanager +def set_grad_enabled(mode): + """ + Create a context which enables or disables dygraph gradient calculation. + + Args: + mode(bool): whether to enable (`True`), or disable (`False`) grad. + + Examples: + .. code-block:: python + + import paddle + x = paddle.ones([3, 2]) + x.stop_gradient = False + with paddle.set_grad_enabled(False): + y = x * 2 + with paddle.set_grad_enabled(True): + z = x * 2 + print(y.stop_gradient) # True + print(z.stop_gradient) # False + """ + + tracer = _dygraph_tracer() + if tracer: + prev_mode = tracer._has_grad + tracer._has_grad = mode + try: + yield + finally: + tracer._has_grad = prev_mode + else: + yield + + +def is_grad_enabled(): + """ + Returns whether current dygraph gradient calculation mode is enabled. + + Returns: + bool: True if current dygraph gradient calculation mode is enabled, otherwise false. + + Examples: + .. code-block:: python + + import paddle + + # Dygraph gradient calculation mode is enabled by default. + paddle.is_grad_enabled() # True + + with paddle.set_grad_enabled(False): + paddle.is_grad_enabled() # False + + paddle.enable_static() + paddle.is_grad_enabled() # False + """ + tracer = _dygraph_tracer() + return tracer._has_grad if tracer else False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/io.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/io.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2375ca72fa60b22fccc5d8dd3b4ad73f9c91e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/io.py @@ -0,0 +1,1152 @@ +# 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. + +from __future__ import print_function + +import os +import collections +import pickle +import warnings +import sys +import numpy as np +import copyreg +import paddle + +# deprecated module import +from paddle import fluid +from paddle.fluid import core +from paddle.fluid.io import ( + _unpack_saved_dict, + _pack_loaded_dict, + _pickle_loads_mac, +) +from paddle.fluid.io import _legacy_save as _legacy_static_save +from paddle.fluid.io import _open_file_buffer, _is_file_path, _is_memory_buffer + +from paddle.fluid.framework import ( + Variable, + _varbase_creator, + _dygraph_tracer, + _non_static_mode, + ParamBase, + EagerParamBase, + _current_expected_place, + Program, +) +from paddle.fluid.dygraph.jit import _SaveLoadConfig +from paddle.fluid.dygraph.io import ( + _construct_program_holders, + _construct_params_and_buffers, +) +from paddle.fluid.dygraph.io import ( + INFER_MODEL_SUFFIX, + INFER_PARAMS_SUFFIX, + INFER_PARAMS_INFO_SUFFIX, +) + +try: + from collections.abc import Iterable +except: + from collections import Iterable + +__all__ = [] + + +def _build_saved_state_dict(state_dict): + save_dict = {} + name_table = {} + for key, value in state_dict.items(): + if isinstance(value, (Variable, core.VarBase, core.eager.Tensor)): + if value.type == core.VarDesc.VarType.VOCAB: + save_dict[key] = value.value().get_map_tensor() + else: + if not value.value().get_tensor()._is_initialized(): + raise ValueError( + "The saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model." + ) + save_dict[key] = value.numpy() + name_table[key] = value.name + else: + save_dict[key] = value + save_dict["StructuredToParameterName@@"] = name_table + + return save_dict + + +def _load_state_dict_from_save_inference_model(model_path, config): + # 1. load program desc & construct _ProgramHolder + programs = _construct_program_holders(model_path, config.model_filename) + + # 2. load layer parameters & buffers + with fluid.dygraph.guard(): + persistable_var_dict = _construct_params_and_buffers( + model_path, programs, config.params_filename, append_suffix=False + ) + + # 3. construct state_dict + load_param_dict = dict() + for var_name in persistable_var_dict: + load_param_dict[var_name] = persistable_var_dict[var_name].numpy() + + # if *.info exists, we can recover structured_name + var_info_filename = str(config.params_filename) + ".info" + var_info_path = os.path.join(model_path, var_info_filename) + if os.path.exists(var_info_path): + with open(var_info_path, 'rb') as f: + extra_var_info = pickle.load(f) + structured_para_dict = dict() + for var_name in load_param_dict: + structured_name = extra_var_info[var_name].get( + 'structured_name', None + ) + assert structured_name is not None, ( + "Cannot find saved variable (%s)'s structured name in saved model." + % var_name + ) + structured_para_dict[structured_name] = load_param_dict[ + var_name + ] + load_param_dict = structured_para_dict + + return load_param_dict + + +def _load_state_dict_from_save_params(model_path): + # Try to load all the files in the directory in VarBase format, + # the file name is used as the name of VarBase + load_var_list = [] + + # 1. load file names + var_name_list = [] + for root, _, files in os.walk(model_path): + for filename in files: + file_path = os.path.join(root, filename) + tmp_var_name = os.path.relpath(file_path, model_path) + var_name = tmp_var_name.replace("\\", "/") + var_name_list.append(var_name) + + # 2. create and load VarBase + with fluid.dygraph.guard(): + for name in var_name_list: + new_var = _varbase_creator(name=name, persistable=True) + _dygraph_tracer().trace_op( + type='load', + inputs={}, + outputs={'Out': new_var}, + attrs={'file_path': os.path.join(model_path, name)}, + ) + load_var_list.append(new_var) + + # 3. construct state_dict + load_param_dict = dict() + for var in load_var_list: + load_param_dict[var.name] = var.numpy() + + return load_param_dict + + +# NOTE(chenweihang): [ Handling of use cases of API paddle.load ] +# `paddle.load` may be used to load saved results of: +# 1. Expected cases: +# - need [full filename] when loading +# - paddle.save +# - paddle.static.save +# - paddle.fluid.save_dygraph +# - need [prefix] when loading [compatible for paddle 2.x] +# - paddle.jit.save +# - paddle.static.save_inference_model +# - need [directory] when loading [compatible for paddle 1.x] +# - paddle.fluid.io.save_inference_model +# - paddle.fluid.io.save_params/save_persistable +# 2. Error cases: +# - no error case +def _build_load_path_and_config(path, config): + # NOTE(chenweihang): If both [prefix save format] and [directory save format] exist, + # raise error, avoid confusing behavior + prefix_format_path = path + INFER_MODEL_SUFFIX + prefix_format_exist = os.path.exists(prefix_format_path) + directory_format_exist = os.path.isdir(path) + if prefix_format_exist and directory_format_exist: + raise ValueError( + "The %s.pdmodel and %s directory exist at the same time, " + "don't know which one to load, please make sure that the specified target " + "of ``path`` is unique." % (path, path) + ) + elif not prefix_format_exist and not directory_format_exist: + error_msg = "The ``path`` (%s) to load model not exists." + # if current path is a prefix, and the path.pdparams or path.pdopt + # is exist, users may want use `paddle.load` load the result of + # `fluid.save_dygraph`, we raise error here for users + params_file_path = path + ".pdparams" + opti_file_path = path + ".pdopt" + if os.path.exists(params_file_path) or os.path.exists(opti_file_path): + error_msg += ( + " If you want to load the results saved by `fluid.save_dygraph`, " + "please specify the full file name, not just the file name prefix. For " + "example, it should be written as `paddle.load('model.pdparams')` instead of " + "`paddle.load('model')`." + ) + raise ValueError(error_msg % path) + else: + if prefix_format_exist: + file_prefix = os.path.basename(path) + model_path = os.path.dirname(path) + if config.model_filename is not None: + warnings.warn( + "When loading the result saved with the " + "specified file prefix, the ``model_filename`` config does " + "not take effect." + ) + config.model_filename = file_prefix + INFER_MODEL_SUFFIX + if config.params_filename is not None: + warnings.warn( + "When loading the result saved with the " + "specified file prefix, the ``params_filename`` config does " + "not take effect." + ) + config.params_filename = file_prefix + INFER_PARAMS_SUFFIX + else: + # Compatible with the old save_inference_model format + model_path = path + + return model_path, config + + +def _parse_load_config(configs): + supported_configs = [ + 'model_filename', + 'params_filename', + 'keep_name_table', + 'return_numpy', + ] + + # input check + for key in configs: + if key not in supported_configs: + raise ValueError( + "The additional config (%s) of `paddle.load` is not supported." + % key + ) + + # construct inner config + inner_config = _SaveLoadConfig() + inner_config.model_filename = configs.get('model_filename', None) + inner_config.params_filename = configs.get('params_filename', None) + inner_config.keep_name_table = configs.get('keep_name_table', None) + inner_config.return_numpy = configs.get('return_numpy', False) + + return inner_config + + +def _parse_save_config(configs): + supported_configs = ['use_binary_format', 'pickle_protocol'] + + # input check + for key in configs: + if key not in supported_configs: + raise ValueError( + "The additional config (%s) of `paddle.save` is not supported." + % key + ) + + # construct inner config + inner_config = _SaveLoadConfig() + inner_config.use_binary_format = configs.get('use_binary_format', False) + inner_config.pickle_protocol = configs.get('pickle_protocol', None) + + return inner_config + + +def _pickle_save(obj, f, protocol): + # TODO(weixin):add support for BytesIO. + if not isinstance(protocol, int): + raise ValueError( + "The 'protocol' MUST be `int`, but received {}".format( + type(protocol) + ) + ) + + if protocol < 2 or protocol > 4: + raise ValueError( + "Expected 1<'protocol'<5, but received protocol={}".format(protocol) + ) + + def reduce_varbase(self): + data = self.numpy() + name = self.name + + return (tuple, ((name, data),)) + + def reduce_LoDTensor(self): + data = np.array(self) + + return (eval, ('data', {'data': data})) + + def reduce_Layer(self): + raise ValueError( + "paddle do not support saving `paddle.nn.Layer` object." + ) + + dispatch_table_layer = dict() + + def create_layer_dispatch_table(layer): + dispatch_table_layer[layer.__class__] = reduce_Layer + return layer + + _parse_every_object( + obj, lambda v: isinstance(v, fluid.Layer), create_layer_dispatch_table + ) + + def add_dispatch_table(): + # This is not a good method, because the pickle module has been modified. + pickle.dispatch_table[core.VarBase] = reduce_varbase + pickle.dispatch_table[ParamBase] = reduce_varbase + pickle.dispatch_table[core.eager.Tensor] = reduce_varbase + pickle.dispatch_table[EagerParamBase] = reduce_varbase + pickle.dispatch_table[core.LoDTensor] = reduce_LoDTensor + pickle.dispatch_table.update(dispatch_table_layer) + + def pop_dispatch_table(): + pickle.dispatch_table.pop(core.VarBase) + pickle.dispatch_table.pop(core.LoDTensor) + pickle.dispatch_table.pop(ParamBase) + pickle.dispatch_table.pop(core.eager.Tensor) + pickle.dispatch_table.pop(EagerParamBase) + for k in dispatch_table_layer: + pickle.dispatch_table.pop(k) + + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if sys.platform == 'darwin' and sys.version_info.major == 3: + add_dispatch_table() + pickle_bytes = pickle.dumps(obj) + pop_dispatch_table() + + max_bytes = 2**30 + for i in range(0, len(pickle_bytes), max_bytes): + f.write(pickle_bytes[i : i + max_bytes]) + else: + pickler = pickle.Pickler(f, protocol) + pickler.dispatch_table = copyreg.dispatch_table.copy() + + pickler.dispatch_table[core.VarBase] = reduce_varbase + pickler.dispatch_table[core.LoDTensor] = reduce_LoDTensor + pickler.dispatch_table[ParamBase] = reduce_varbase + pickler.dispatch_table[core.eager.Tensor] = reduce_varbase + pickler.dispatch_table[EagerParamBase] = reduce_varbase + pickler.dispatch_table.update(dispatch_table_layer) + pickler.dump(obj) + + +def _contain_x(obj, condition_func): + if isinstance(obj, core.SelectedRows): + raise NotImplementedError( + "`paddle.save` do not support saving 'SelectedRows'." + ) + + if condition_func(obj): + return True + elif type(obj) in (dict, collections.OrderedDict, list, tuple): + if type(obj) in (dict, collections.OrderedDict): + keys = list(obj.keys()) + else: + keys = range(len(obj)) + flag = False + for key in keys: + flag |= _contain_x(obj[key], condition_func) + if flag: + return True + return flag + else: + return False + + +def _is_state_dict(obj): + if isinstance(obj, dict): + + def condition(obj): + return isinstance( + obj, + ( + fluid.Layer, + Program, + core.VarBase, + core.eager.Tensor, + core.LoDTensor, + core.SelectedRows, + ), + ) + + # If the value of a dict is a core.VarBase/LoDTensor or a dict + # that does not contain a paddle type(Layer, Program, VarBase, LoDTensor, SelectedRows), + # the dict is considered to be a state_ dict. + for key, value in obj.items(): + if isinstance(value, dict): + for k, v in value.items(): + if _contain_x(v, condition): + return False + elif not isinstance( + value, (core.VarBase, core.eager.Tensor, core.LoDTensor) + ): + return False + return True + + return False + + +def _transformed_from_varbase(obj): + # In paddle2.1 version, VarBase is saved as tuple(tensor.name, tensor.numpy()). + # When executing paddle.load, use this function to determine whether to restore to VarBase/LoDTensor. + if isinstance(obj, tuple) and len(obj) == 2: + name_types = str + if isinstance(obj[0], name_types) and isinstance(obj[1], np.ndarray): + return True + return False + + +def _transformed_from_lodtensor(obj): + # In paddle2.1 version, LoDTensor is saved as np.array(tensor). + # When executing paddle.load, use this function to determine whether to restore to VarBase/LoDTensor. + if isinstance(obj, np.ndarray): + return True + return False + + +def _to_LodTensor(ndarray): + if not isinstance(ndarray, np.ndarray): + raise TypeError( + 'Type of `ndarray` should be numpy.ndarray, but received {}.'.format( + type(ndarray) + ) + ) + t = core.LoDTensor() + place = _current_expected_place() + t.set(ndarray, place) + return t + + +def _tuple_to_tensor(obj, return_numpy): + if return_numpy: + return obj[1] + if _non_static_mode(): + t = paddle.to_tensor(obj[1]) + # This function does modify the name of return value. + # Loading the same variable multiple times may cause the same name. + t.name = obj[0] + return t + else: + return _to_LodTensor(obj[1]) + + +def _ndarray_to_tensor(obj, return_numpy): + if return_numpy: + return obj + if _non_static_mode(): + return paddle.to_tensor(obj) + else: + return _to_LodTensor(obj) + + +def _lod_tensor2varbase(tensor): + return_var = _varbase_creator() + return_var.value().get_tensor().set(tensor, _current_expected_place()) + return return_var + + +def _parse_every_object(obj, condition_func, convert_func): + if condition_func(obj): + return convert_func(obj) + elif type(obj) in (dict, collections.OrderedDict, list): + if type(obj) == list: + keys = range(len(obj)) + else: + keys = list(obj.keys()) + for key in keys: + if condition_func(obj[key]): + obj[key] = convert_func(obj[key]) + else: + obj[key] = _parse_every_object( + obj[key], condition_func, convert_func + ) + return obj + elif type(obj) == tuple: + return tuple( + _parse_every_object(list(obj), condition_func, convert_func) + ) + elif type(obj) == set: + return set(_parse_every_object(list(obj), condition_func, convert_func)) + else: + if isinstance(obj, Iterable) and not isinstance( + obj, + (str, np.ndarray, core.VarBase, core.eager.Tensor, core.LoDTensor), + ): + raise NotImplementedError( + "The iteratable objects supported are tuple, list, dict, OrderedDict, string. But received {}.".format( + type(obj) + ) + ) + return obj + + +def _parse_load_result(obj, return_numpy): + def is_layer(obj): + return isinstance(obj, fluid.Layer) + + def parse_layer(obj): + temp_dict = _parse_load_result(obj.__dict__, False) + obj.__dict__.update(temp_dict) + return obj + + if _contain_x(obj, is_layer): + if not _non_static_mode(): + raise ValueError( + "Layer can only be loaded in dynamic graph mode, but now in static graph mode." + ) + + _parse_every_object(obj, is_layer, parse_layer) + + def tuple_to_tensor(obj): + return _tuple_to_tensor(obj, return_numpy=return_numpy) + + def ndarray_to_tensor(obj): + return _ndarray_to_tensor(obj, return_numpy=return_numpy) + + # tuple(name, ndarry) was converted from varbase of paddle2.1, + # and all tuple(name, ndarry) are converted to tensor. + if _contain_x(obj, _transformed_from_varbase): + return _parse_every_object( + obj, _transformed_from_varbase, tuple_to_tensor + ) + # If there is no tuple(name, ndary), it is considered to be saved by paddle2.0 + # or converted from LoDTensor, and all ndarrays are converted to tensor. + else: + return _parse_every_object( + obj, _transformed_from_lodtensor, ndarray_to_tensor + ) + + +def _save_lod_tensor(tensor, file_name): + if not tensor._is_initialized(): + raise ValueError( + "The saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model firstly." + ) + if _is_file_path(file_name): + _seek = core.save_lod_tensor(tensor, file_name) + # '_seek' is the end position of this tensor in the file. + + elif _is_memory_buffer(file_name): + tensor_bytes = core.save_lod_tensor_to_memory(tensor) + + with _open_file_buffer(file_name, 'wb') as f: + f.write(tensor_bytes) + _seek = f.tell() + + else: + raise NotImplementedError( + 'Only supports saving objects to file or BytesIO, but received {}'.format( + type(file_name) + ) + ) + return _seek + + +def _load_lod_tensor(file_name): + temp_t = paddle.fluid.core.LoDTensor() + if _is_file_path(file_name): + # '_seek' is the end position of this tensor in the file. + _seek = paddle.fluid.core.load_lod_tensor(temp_t, file_name) + + elif _is_memory_buffer(file_name): + with _open_file_buffer(file_name, 'rb') as f: + tensor_bytes = f.read() + paddle.fluid.core.load_lod_tensor_from_memory(temp_t, tensor_bytes) + _seek = f.tell() + + else: + raise NotImplementedError( + 'Only supports load objects from file or BytesIO, but received {}'.format( + type(file_name) + ) + ) + + return temp_t, _seek + + +def _save_selected_rows(selected_rows, file_name): + if not selected_rows.get_tensor()._is_initialized(): + raise ValueError("The saved tensor is not initialized.") + if _is_file_path(file_name): + # '_seek' is the end position of this SelectedRows in the file. + _seek = core.save_selected_rows(selected_rows, file_name) + + elif _is_memory_buffer(file_name): + selected_rows_bytes = core.save_selected_rows_to_memory(selected_rows) + with _open_file_buffer(file_name, 'wb') as f: + f.write(selected_rows_bytes) + _seek = f.tell() + else: + raise NotImplementedError( + 'Only supports saving objects to file or BytesIO, but received {}'.format( + type(file_name) + ) + ) + return _seek + + +def _load_selected_rows(file_name): + temp_sr = core.SelectedRows() + if _is_file_path(file_name): + # '_seek' is the end position of this SelectedRows in the file. + _seek = core.load_selected_rows(temp_sr, file_name) + + elif _is_memory_buffer(file_name): + with _open_file_buffer(file_name, 'rb') as f: + selected_rows_bytes = f.read() + paddle.fluid.core.load_selected_rows_from_memory( + temp_sr, selected_rows_bytes + ) + _seek = f.tell() + + else: + raise NotImplementedError( + 'Only supports load objects from file or BytesIO, but received {}'.format( + type(file_name) + ) + ) + + return temp_sr, _seek + + +def _save_binary_var(obj, path): + if isinstance(obj, core.LoDTensor): + _save_lod_tensor(obj, path) + elif isinstance(obj, core.SelectedRows): + _save_selected_rows(obj, path) + elif isinstance(obj, (core.VarBase, core.eager.Tensor)): + _save_lod_tensor(obj.value().get_tensor(), path) + else: + # Since the concept of 'Tensor' is only exposed to users, the error message can only contain tensor instead of 'LoDTensor' or 'SelectedRows' + raise NotImplementedError( + "When use_binary_format = True, `paddle.save` expected Tensor, but received {}.".format( + type(obj) + ) + ) + + +def save(obj, path, protocol=4, **configs): + ''' + Save an object to the specified path. + + Note: + Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program. + + Note: + Different from ``paddle.jit.save``, since the save result of ``paddle.save`` is a single file, + there is no need to distinguish multiple saved files by adding a suffix. The argument ``path`` + of ``paddle.save`` will be directly used as the saved file name instead of a prefix. + In order to unify the saved file name format, we recommend using the paddle standard suffix: + 1. for ``Layer.state_dict`` , recommend to use ``.pdparams`` ; + 2. for ``Optimizer.state_dict`` , recommend to use ``.pdopt`` . + For specific examples, please refer to API code examples. + + Args: + obj(Object) : The object to be saved. + path(str|BytesIO) : The path/buffer of the object to be saved. + If saved in the current directory, the input path string will be used as the file name. + protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5. + Default: 4 + **configs(dict, optional): optional keyword arguments. The following options are currently supported: + use_binary_format(bool): When the saved object is static graph variable, you can specify ``use_binary_for_var``. + If True, save the file in the c++ binary format when saving a single static graph variable; otherwise, save it in pickle format. + Default: False + + Returns: + None + + Examples: + .. code-block:: python + + # example 1: dynamic graph + import paddle + emb = paddle.nn.Embedding(10, 10) + layer_state_dict = emb.state_dict() + + # save state_dict of emb + paddle.save(layer_state_dict, "emb.pdparams") + + scheduler = paddle.optimizer.lr.NoamDecay( + d_model=0.01, warmup_steps=100, verbose=True) + adam = paddle.optimizer.Adam( + learning_rate=scheduler, + parameters=emb.parameters()) + opt_state_dict = adam.state_dict() + + # save state_dict of optimizer + paddle.save(opt_state_dict, "adam.pdopt") + # save weight of emb + paddle.save(emb.weight, "emb.weight.pdtensor") + + # example 2: Save multiple state_dict at the same time + from paddle import nn + from paddle.optimizer import Adam + + layer = paddle.nn.Linear(3, 4) + adam = Adam(learning_rate=0.001, parameters=layer.parameters()) + obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100} + path = 'example/model.pdparams' + paddle.save(obj, path) + + + # example 3: static graph + import paddle + import paddle.static as static + + paddle.enable_static() + + # create network + x = paddle.static.data(name="x", shape=[None, 224], dtype='float32') + z = paddle.static.nn.fc(x, 10) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + prog = paddle.static.default_main_program() + for var in prog.list_vars(): + if list(var.shape) == [224, 10]: + tensor = var.get_value() + break + + # save/load tensor + path_tensor = 'temp/tensor.pdtensor' + paddle.save(tensor, path_tensor) + + # save/load state_dict + path_state_dict = 'temp/model.pdparams' + paddle.save(prog.state_dict("param"), path_tensor) + + # example 4: save program + import paddle + + paddle.enable_static() + + data = paddle.static.data( + name='x_static_save', shape=(None, 224), dtype='float32') + y_static = z = paddle.static.nn.fc(data, 10) + main_program = paddle.static.default_main_program() + path = "example/main_program.pdmodel" + paddle.save(main_program, path) + + + # example 5: save object to memory + from io import BytesIO + import paddle + from paddle.nn import Linear + paddle.disable_static() + + linear = Linear(5, 10) + state_dict = linear.state_dict() + byio = BytesIO() + paddle.save(state_dict, byio) + tensor = paddle.randn([2, 3], dtype='float32') + paddle.save(tensor, byio) + + ''' + if _is_file_path(path): + # 1. input check + filename = os.path.basename(path) + if filename == "": + raise ValueError( + "The input path MUST be format of dirname/filename " + "[dirname\\filename in Windows system], but received " + "filename is empty string." + ) + + # 2. save object + dirname = os.path.dirname(path) + if dirname and not os.path.exists(dirname): + os.makedirs(dirname) + elif not _is_memory_buffer(path): + raise ValueError( + "only supports saving objects to file and `BytesIO`, but got {}".format( + type(path) + ) + ) + + config = _parse_save_config(configs) + + if not isinstance(config.use_binary_format, bool): + raise TypeError( + "Type of `use_binary_format` should be bool, but received {}.".format( + type(config.use_binary_format) + ) + ) + + if config.use_binary_format: + _save_binary_var(obj, path) + else: + # `protocol` need to be used, `pickle_protocol` is a deprecated arg. + if config.pickle_protocol is not None: + protocol = config.pickle_protocol + warnings.warn( + "'pickle_protocol' is a deprecated argument. Please use 'protocol' instead." + ) + + if isinstance(obj, Program): + obj.desc.flush() + with _open_file_buffer(path, "wb") as f: + f.write(obj.desc.serialize_to_string()) + + elif _is_state_dict(obj): + if _non_static_mode(): + _legacy_save(obj, path, protocol) + else: + _legacy_static_save(obj, path, protocol) + else: + with _open_file_buffer(path, 'wb') as f: + _pickle_save(obj, f, protocol) + + +def _legacy_save(obj, path, protocol=2): + # 1. input check + if not isinstance(obj, dict): + raise NotImplementedError( + "Now only supports save state_dict of Layer or Optimizer, " + "expect dict, but received %s." % type(obj) + ) + + if len(obj) == 0: + warnings.warn("The input state dict is empty, no need to save.") + + if not isinstance(protocol, int): + raise ValueError( + "The 'protocol' MUST be `int`, but received {}".format( + type(protocol) + ) + ) + + if protocol < 2 or protocol > 4: + raise ValueError( + "Expected 1<'protocol'<5, but received protocol={}".format(protocol) + ) + + if _is_file_path(path): + filename = os.path.basename(path) + if filename == "": + raise ValueError( + "The input path MUST be format of dirname/filename " + "[dirname\\filename in Windows system], but received " + "filename is empty string." + ) + # 2. save object + dirname = os.path.dirname(path) + if dirname and not os.path.exists(dirname): + os.makedirs(dirname) + + if isinstance(obj, dict): + saved_obj = _build_saved_state_dict(obj) + + saved_obj = _unpack_saved_dict(saved_obj, protocol) + + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if ( + _is_file_path(path) + and sys.platform == 'darwin' + and sys.version_info.major == 3 + ): + pickle_bytes = pickle.dumps(saved_obj, protocol=protocol) + with open(path, 'wb') as f: + max_bytes = 2**30 + for i in range(0, len(pickle_bytes), max_bytes): + f.write(pickle_bytes[i : i + max_bytes]) + else: + with _open_file_buffer(path, 'wb') as f: + pickle.dump(saved_obj, f, protocol=protocol) + + +def load(path, **configs): + ''' + Load an object can be used in paddle from specified path. + + Note: + Now supports loading ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program. + + Note: + In order to use the model parameters saved by paddle more efficiently, + ``paddle.load`` supports loading ``state_dict`` of Layer from the result of + other save APIs except ``paddle.save`` , but the argument ``path`` format is + different: + 1. loading from ``paddle.static.save`` or ``paddle.Model().save(training=True)`` , + ``path`` needs to be a complete file name, such as ``model.pdparams`` or + ``model.pdopt`` ; + 2. loading from ``paddle.jit.save`` or ``paddle.static.save_inference_model`` + or ``paddle.Model().save(training=False)`` , ``path`` need to be a file prefix, + such as ``model/mnist``, and ``paddle.load`` will get information from + ``mnist.pdmodel`` and ``mnist.pdiparams`` ; + 3. loading from paddle 1.x APIs ``paddle.fluid.io.save_inference_model`` or + ``paddle.fluid.io.save_params/save_persistables`` , ``path`` need to be a + directory, such as ``model`` and model is a directory. + + Note: + If you load ``state_dict`` from the saved result of static mode API such as + ``paddle.static.save`` or ``paddle.static.save_inference_model`` , + the structured variable name in dynamic mode will cannot be restored. + You need to set the argument ``use_structured_name=False`` when using + ``Layer.set_state_dict`` later. + + Args: + path(str|BytesIO) : The path/buffer to load the target object. Generally, the path is the target + file path. When loading state_dict from the saved result of the API used to save + the inference model, the path may be a file prefix or directory. + **configs (dict, optional): other load configuration options for compatibility. We do not + recommend using these configurations, they may be removed in the future. If not necessary, + DO NOT use them. Default None. + The following options are currently supported: + (1) model_filename (str): The inference model file name of the paddle 1.x + ``save_inference_model`` save format. Default file name is :code:`__model__` . + (2) params_filename (str): The persistable variables file name of the paddle 1.x + ``save_inference_model`` save format. No default file name, save variables separately + by default. + (3) return_numpy(bool): If specified as True, return tensor as numpy.ndarray, otherwise return tensor as paddle.Tensor. + Default False. + + Returns: + Object(Object): a target object can be used in paddle + + Examples: + .. code-block:: python + + # example 1: dynamic graph + import paddle + emb = paddle.nn.Embedding(10, 10) + layer_state_dict = emb.state_dict() + + # save state_dict of emb + paddle.save(layer_state_dict, "emb.pdparams") + + scheduler = paddle.optimizer.lr.NoamDecay( + d_model=0.01, warmup_steps=100, verbose=True) + adam = paddle.optimizer.Adam( + learning_rate=scheduler, + parameters=emb.parameters()) + opt_state_dict = adam.state_dict() + + # save state_dict of optimizer + paddle.save(opt_state_dict, "adam.pdopt") + # save weight of emb + paddle.save(emb.weight, "emb.weight.pdtensor") + + # load state_dict of emb + load_layer_state_dict = paddle.load("emb.pdparams") + # load state_dict of optimizer + load_opt_state_dict = paddle.load("adam.pdopt") + # load weight of emb + load_weight = paddle.load("emb.weight.pdtensor") + + + # example 2: Load multiple state_dict at the same time + from paddle import nn + from paddle.optimizer import Adam + + layer = paddle.nn.Linear(3, 4) + adam = Adam(learning_rate=0.001, parameters=layer.parameters()) + obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100} + path = 'example/model.pdparams' + paddle.save(obj, path) + obj_load = paddle.load(path) + + + # example 3: static graph + import paddle + import paddle.static as static + + paddle.enable_static() + + # create network + x = paddle.static.data(name="x", shape=[None, 224], dtype='float32') + z = paddle.static.nn.fc(x, 10) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + exe.run(paddle.static.default_startup_program()) + prog = paddle.static.default_main_program() + for var in prog.list_vars(): + if list(var.shape) == [224, 10]: + tensor = var.get_value() + break + + # save/load tensor + path_tensor = 'temp/tensor.pdtensor' + paddle.save(tensor, path_tensor) + load_tensor = paddle.load(path_tensor) + + # save/load state_dict + path_state_dict = 'temp/model.pdparams' + paddle.save(prog.state_dict("param"), path_tensor) + load_state_dict = paddle.load(path_tensor) + + + # example 4: load program + import paddle + + paddle.enable_static() + + data = paddle.static.data( + name='x_static_save', shape=(None, 224), dtype='float32') + y_static = z = paddle.static.nn.fc(data, 10) + main_program = paddle.static.default_main_program() + path = "example/main_program.pdmodel" + paddle.save(main_program, path) + load_main = paddle.load(path) + print(load_main) + + + # example 5: save object to memory + from io import BytesIO + import paddle + from paddle.nn import Linear + paddle.disable_static() + + linear = Linear(5, 10) + state_dict = linear.state_dict() + byio = BytesIO() + paddle.save(state_dict, byio) + tensor = paddle.randn([2, 3], dtype='float32') + paddle.save(tensor, byio) + byio.seek(0) + # load state_dict + dict_load = paddle.load(byio) + + ''' + + if _is_memory_buffer(path) or os.path.isfile(path): + config = _parse_load_config(configs) + exception_type = pickle.UnpicklingError + try: + with _open_file_buffer(path, 'rb') as f: + # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3' + if ( + _is_file_path(path) + and sys.platform == 'darwin' + and sys.version_info.major == 3 + ): + load_result = _pickle_loads_mac(path, f) + else: + load_result = pickle.load(f, encoding='latin1') + + # TODO(weixin):If `obj` is any object, the judgment condition should be more precise. + if isinstance(load_result, dict): + load_result = _pack_loaded_dict(load_result) + # paddle2.0: paddle.save/load + if "StructuredToParameterName@@" in load_result: + + for key in load_result["StructuredToParameterName@@"]: + if isinstance(load_result[key], np.ndarray): + load_result[key] = _ndarray_to_tensor( + load_result[key], config.return_numpy + ) + + if ( + not config.keep_name_table + and "StructuredToParameterName@@" in load_result + ): + del load_result["StructuredToParameterName@@"] + else: + # paddle2.1 static.save/load + load_result = _parse_load_result( + load_result, config.return_numpy + ) + + else: + load_result = _parse_load_result( + load_result, config.return_numpy + ) + + except exception_type as msg_pickle: + try: + tensor, _ = _load_selected_rows(path) + return tensor + except: + try: + tensor, _ = _load_lod_tensor(path) + if config.return_numpy: + return np.array(tensor) + else: + if _non_static_mode(): + return _lod_tensor2varbase(tensor) + return tensor + except: + try: + with _open_file_buffer(path, "rb") as f: + program_desc_str = f.read() + program = Program.parse_from_string( + program_desc_str + ) + return program + except: + raise ValueError( + "`paddle.load` can not parse the file:{}.".format( + path + ) + ) + + else: + load_result = _legacy_load(path, **configs) + + return load_result + + +def _legacy_load(path, **configs): + load_result = None + config = _parse_load_config(configs) + + if os.path.isfile(path) or _is_memory_buffer(path): + # we think path is file means this file is created by paddle.save + with _open_file_buffer(path, 'rb') as f: + load_result = pickle.load(f, encoding='latin1') + load_result = _pack_loaded_dict(load_result) + if ( + not config.keep_name_table + and "StructuredToParameterName@@" in load_result + ): + del load_result["StructuredToParameterName@@"] + else: + # file prefix and directory are compatible cases + model_path, config = _build_load_path_and_config(path, config) + # check whether model file exists + if config.model_filename is None: + model_filename = '__model__' + else: + model_filename = config.model_filename + model_file_path = os.path.join(model_path, model_filename) + + if os.path.exists(model_file_path): + # Load state dict by `jit.save/io.save_inference_model` save format + # NOTE(chenweihang): [ Compatibility of save_inference_model save format ] + # The model saved by `save_inference_model` does not completely correspond to + # the information required by the `state_dict` under the dygraph. + # `save_inference_model` not save structured name, we need to remind + # the user to configure the `use_structured_name` argument when `set_state_dict` + # NOTE(chenweihang): `jit.save` doesn't save optimizer state + load_result = _load_state_dict_from_save_inference_model( + model_path, config + ) + else: + # load state dict by `io.save_params/persistables` save format + # TODO(chenweihang): [ Now only supports loading parameters separately ] + # If users save all parameters as one file, the [ variable.name -> variable ] + # mapping info will lost, so users need to give variable list, but users build + # variable list in dygraph mode is difficult, we recommend users to use + # paddle.static.load_program_state in this case + load_result = _load_state_dict_from_save_params(model_path) + + return load_result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/random.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/random.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5ff2c8efba9c5618a1e1fd3d7acace71331c13 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/framework/random.py @@ -0,0 +1,130 @@ +# 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. + +# TODO: define random api +import paddle.fluid as fluid +from paddle.fluid import core + +__all__ = [] + + +def seed(seed): + """ + + Sets the seed for global default generator, which manages the random number generation. + + Args: + seed(int): The random seed to set. It is recommend to set a large int number. + + Returns: + Generator: The global default generator object. + + Examples: + .. code-block:: python + + import paddle + gen = paddle.seed(102) + + """ + #TODO(zhiqiu): 1. remove program.random_seed when all random-related op upgrade + # 2. support gpu generator by global device + + seed = int(seed) + + if core.is_compiled_with_cuda(): + for i in range(core.get_cuda_device_count()): + core.default_cuda_generator(i).manual_seed(seed) + + return core.default_cpu_generator().manual_seed(seed) + + +def get_cuda_rng_state(): + """ + + Get random state of cuda generators. + + Args: + None. + + Returns: + GeneratorState: object. + + Examples: + .. code-block:: python + + import paddle + sts = paddle.get_cuda_rng_state() + + """ + state_list = [] + if core.is_compiled_with_cuda(): + for i in range(core.get_cuda_device_count()): + state_list.append(core.default_cuda_generator(i).get_state()) + + return state_list + + +def set_cuda_rng_state(state_list): + """ + + Sets generator state for all cuda generators. + + Args: + state_list(list|tuple): The cuda states to set back to cuda generators. state_list is obtained from get_cuda_rng_state(). + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + sts = paddle.get_cuda_rng_state() + paddle.set_cuda_rng_state(sts) + + """ + if core.is_compiled_with_cuda(): + if not len(state_list) == core.get_cuda_device_count(): + raise ValueError( + "Length of cuda state list shoule be equal to the cuda device count" + ) + for i in range(core.get_cuda_device_count()): + core.default_cuda_generator(i).set_state(state_list[i]) + + +def _manual_program_seed(seed): + """ + Sets global seed for generating random numbers. + + NOTE(zhiqiu): This is the original implemention of seed. Keeps it temporally + since CUDA generator is not developed, so we need it in the unittest. + + Args: + seed(int): The random seed to set. It is recommend to set a large int number. + + Returns: + None + """ + fluid.default_main_program().random_seed = seed + fluid.default_startup_program().random_seed = seed + program = fluid.Program() + program.global_seed(seed) + + +def set_random_seed_generator(name, seed): + core.set_random_seed_generator(name, seed) + + +def get_random_seed_generator(name): + return core.get_random_seed_generator(name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9618bc57a203ea4c724b9ee6c406ac41c7f2ab65 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/__init__.py @@ -0,0 +1,37 @@ +# Copyright (c) 2022 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. + +from .message_passing import send_u_recv # noqa: F401 +from .message_passing import send_ue_recv # noqa: F401 +from .message_passing import send_uv # noqa: F401 +from .math import segment_sum # noqa: F401 +from .math import segment_mean # noqa: F401 +from .math import segment_min # noqa: F401 +from .math import segment_max # noqa: F401 +from .reindex import reindex_graph # noqa: F401 +from .reindex import reindex_heter_graph # noqa: F401 +from .sampling import sample_neighbors # noqa: F401 + +__all__ = [ + 'send_u_recv', + 'send_ue_recv', + 'send_uv', + 'segment_sum', + 'segment_mean', + 'segment_min', + 'segment_max', + 'reindex_graph', + 'reindex_heter_graph', + 'sample_neighbors', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/math.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/math.py new file mode 100644 index 0000000000000000000000000000000000000000..22b0f32114a2213cb4e5768fe5db26cecac7fed1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/math.py @@ -0,0 +1,264 @@ +# Copyright (c) 2022 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. + +from paddle.fluid.layer_helper import LayerHelper, _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode + +__all__ = [] + + +def segment_sum(data, segment_ids, name=None): + r""" + Segment Sum Operator. + + This operator sums the elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\sum_{j} data_{j}$ + where sum is over j such that `segment_ids[j] == i`. + + Args: + data (Tensor): A tensor, available data type float32, float64, int32, int64, float16. + segment_ids (Tensor): A 1-D tensor, which have the same size + with the first dimension of input data. + Available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - output (Tensor), the reduced result. + + Examples: + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.geometric.segment_sum(data, segment_ids) + #Outputs: [[4., 4., 4.], [4., 5., 6.]] + + """ + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "SUM")[0] + if _in_legacy_dygraph(): + out, tmp = _legacy_C_ops.segment_pool( + data, segment_ids, 'pooltype', "SUM" + ) + return out + + check_variable_and_dtype( + data, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "segment_pool", + ) + check_variable_and_dtype( + segment_ids, "SegmentIds", ("int32", "int64"), "segment_pool" + ) + + helper = LayerHelper("segment_sum", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op( + type="segment_pool", + inputs={"X": data, "SegmentIds": segment_ids}, + outputs={"Out": out, "SummedIds": summed_ids}, + attrs={"pooltype": "SUM"}, + ) + return out + + +def segment_mean(data, segment_ids, name=None): + r""" + Segment mean Operator. + + This operator calculate the mean value of input `data` which + with the same index in `segment_ids`. + It computes a tensor such that $out_i = \\frac{1}{n_i} \\sum_{j} data[j]$ + where sum is over j such that 'segment_ids[j] == i' and $n_i$ is the number + of all index 'segment_ids[j] == i'. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64, float16. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - output (Tensor), the reduced result. + + Examples: + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.geometric.segment_mean(data, segment_ids) + #Outputs: [[2., 2., 2.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "MEAN")[0] + if _in_legacy_dygraph(): + out, tmp = _legacy_C_ops.segment_pool( + data, segment_ids, 'pooltype', "MEAN" + ) + return out + + check_variable_and_dtype( + data, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "segment_pool", + ) + check_variable_and_dtype( + segment_ids, "SegmentIds", ("int32", "int64"), "segment_pool" + ) + + helper = LayerHelper("segment_mean", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op( + type="segment_pool", + inputs={"X": data, "SegmentIds": segment_ids}, + outputs={"Out": out, "SummedIds": summed_ids}, + attrs={"pooltype": "MEAN"}, + ) + return out + + +def segment_min(data, segment_ids, name=None): + r""" + Segment min operator. + + This operator calculate the minimum elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\min_{j} data_{j}$ + where min is over j such that `segment_ids[j] == i`. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64, float16. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - output (Tensor), the reduced result. + + Examples: + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.geometric.segment_min(data, segment_ids) + #Outputs: [[1., 2., 1.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "MIN")[0] + if _in_legacy_dygraph(): + out, tmp = _legacy_C_ops.segment_pool( + data, segment_ids, 'pooltype', "MIN" + ) + return out + + check_variable_and_dtype( + data, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "segment_pool", + ) + check_variable_and_dtype( + segment_ids, "SegmentIds", ("int32", "int64"), "segment_pool" + ) + + helper = LayerHelper("segment_min", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op( + type="segment_pool", + inputs={"X": data, "SegmentIds": segment_ids}, + outputs={"Out": out, "SummedIds": summed_ids}, + attrs={"pooltype": "MIN"}, + ) + return out + + +def segment_max(data, segment_ids, name=None): + r""" + Segment max operator. + + This operator calculate the maximum elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\max_{j} data_{j}$ + where max is over j such that `segment_ids[j] == i`. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64, float16. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - output (Tensor), the reduced result. + + Examples: + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.geometric.segment_max(data, segment_ids) + #Outputs: [[3., 2., 3.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "MAX")[0] + if _in_legacy_dygraph(): + out, tmp = _legacy_C_ops.segment_pool( + data, segment_ids, 'pooltype', "MAX" + ) + return out + + check_variable_and_dtype( + data, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "segment_pool", + ) + check_variable_and_dtype( + segment_ids, "SegmentIds", ("int32", "int64"), "segment_pool" + ) + + helper = LayerHelper("segment_max", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op( + type="segment_pool", + inputs={"X": data, "SegmentIds": segment_ids}, + outputs={"Out": out, "SummedIds": summed_ids}, + attrs={"pooltype": "MAX"}, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c07f9bc40c6b39967ed168afb11928eb2ba1d635 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) 2022 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. + +from .send_recv import send_u_recv # noqa: F401 +from .send_recv import send_ue_recv # noqa: F401 +from .send_recv import send_uv # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/send_recv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/send_recv.py new file mode 100644 index 0000000000000000000000000000000000000000..839b6e93e80a27043af3b99a4c44fe544238d5e2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/send_recv.py @@ -0,0 +1,515 @@ +# Copyright (c) 2022 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. + +import numpy as np +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import ( + _non_static_mode, + _in_legacy_dygraph, + in_dygraph_mode, +) +from paddle.fluid.framework import Variable +from paddle.fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, + convert_dtype, +) +from paddle import _C_ops, _legacy_C_ops + +from .utils import ( + convert_out_size_to_list, + get_out_size_tensor_inputs, + reshape_lhs_rhs, +) + +__all__ = [] + + +def send_u_recv( + x, src_index, dst_index, reduce_op="sum", out_size=None, name=None +): + """ + Graph Learning message passing api. + + This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory + consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index` + to gather the corresponding data, and then use `dst_index` to update the corresponding position of output tensor + in different reduce ops, like sum, mean, max, or min. Besides, we can use `out_size` to set necessary output shape. + + .. code-block:: text + + Given: + + x = [[0, 2, 3], + [1, 4, 5], + [2, 6, 7]] + + src_index = [0, 1, 2, 0] + + dst_index = [1, 2, 1, 0] + + reduce_op = "sum" + + out_size = None + + Then: + + out = [[0, 2, 3], + [2, 8, 10], + [1, 4, 5]] + + Args: + x (Tensor): The input tensor, and the available data type is float32, float64, int32, int64. + And we support float16 in gpu version. + src_index (Tensor): An 1-D tensor, and the available data type is int32, int64. + dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`. + The available data type is int32, int64. + reduce_op (str): Different reduce ops, including `sum`, `mean`, `max`, `min`. + Default value is `sum`. + out_size (int|Tensor|None): We can set `out_size` to get necessary output shape. If not set or + out_size is smaller or equal to 0, then this input will not be used. + Otherwise, `out_size` should be equal with or larger than + max(dst_index) + 1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out (Tensor), the output tensor, should have the same shape and same dtype as input tensor `x`. + If `out_size` is set correctly, then it should have the same shape as `x` except the 0th dimension. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum") + # Outputs: [[0., 2., 3.], [2., 8., 10.], [1., 4., 5.]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out_size = paddle.max(dst_index) + 1 + out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum", out_size=out_size) + # Outputs: [[0., 2., 3.], [[2., 8., 10.]]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out = paddle.geometric.send_u_recv(x, src_index, dst_index, reduce_op="sum") + # Outputs: [[0., 2., 3.], [2., 8., 10.], [0., 0., 0.]] + + """ + + if reduce_op not in ["sum", "mean", "max", "min"]: + raise ValueError( + "reduce_op should be `sum`, `mean`, `max` or `min`, but received %s" + % reduce_op + ) + + # TODO(daisiming): Should we add judgement for out_size: max(dst_index) + 1. + + if _in_legacy_dygraph(): + out_size = convert_out_size_to_list(out_size) + out, tmp = _legacy_C_ops.graph_send_recv( + x, + src_index, + dst_index, + None, + 'reduce_op', + reduce_op.upper(), + 'out_size', + out_size, + ) + return out + if in_dygraph_mode(): + out_size = convert_out_size_to_list(out_size) + return _C_ops.graph_send_recv( + x, src_index, dst_index, reduce_op.upper(), out_size + ) + + check_variable_and_dtype( + x, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "graph_send_recv", + ) + check_variable_and_dtype( + src_index, "Src_index", ("int32", "int64"), "graph_send_recv" + ) + check_variable_and_dtype( + dst_index, "Dst_index", ("int32", "int64"), "graph_send_recv" + ) + if out_size: + check_type( + out_size, + 'out_size', + (int, np.int32, np.int64, Variable), + 'graph_send_recv', + ) + if isinstance(out_size, Variable): + check_dtype( + out_size.dtype, 'out_size', ['int32', 'int64'], 'graph_send_recv' + ) + + helper = LayerHelper("send_u_recv", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + dst_count = helper.create_variable_for_type_inference( + dtype="int32", stop_gradient=True + ) + + inputs = {"X": x, "Src_index": src_index, "Dst_index": dst_index} + attrs = {"reduce_op": reduce_op.upper()} + get_out_size_tensor_inputs( + inputs=inputs, attrs=attrs, out_size=out_size, op_type='graph_send_recv' + ) + + helper.append_op( + type="graph_send_recv", + inputs=inputs, + outputs={"Out": out, "Dst_count": dst_count}, + attrs=attrs, + ) + return out + + +def send_ue_recv( + x, + y, + src_index, + dst_index, + message_op="add", + reduce_op="sum", + out_size=None, + name=None, +): + """ + + Graph Learning message passing api. + + This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory + consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index` + to gather the corresponding data, after computing with `y` in different message ops like add/sub/mul/div, then use `dst_index` to + update the corresponding position of output tensor in different reduce ops, like sum, mean, max, or min. + Besides, we can use `out_size` to set necessary output shape. + + .. code-block:: text + + Given: + + x = [[0, 2, 3], + [1, 4, 5], + [2, 6, 7]] + + y = [1, 1, 1] + + src_index = [0, 1, 2, 0] + + dst_index = [1, 2, 1, 0] + + message_op = "add" + + reduce_op = "sum" + + out_size = None + + Then: + + out = [[1, 3, 4], + [4, 10, 12], + [2, 5, 6]] + + Args: + x (Tensor): The input node feature tensor, and the available data type is float32, float64, int32, int64. + And we support float16 in gpu version. + y (Tensor): The input edge feature tensor, and the available data type is float32, float64, int32, int64. + And we support float16 in gpu version. + src_index (Tensor): An 1-D tensor, and the available data type is int32, int64. + dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`. + The available data type is int32, int64. + message_op (str, optional): Different message ops for x and e, including `add`, `sub`, `mul`, `div`. + reduce_op (str, optional): Different reduce ops, including `sum`, `mean`, `max`, `min`. + Default value is `sum`. + out_size (int|Tensor, optional): We can set `out_size` to get necessary output shape. If not set or + out_size is smaller or equal to 0, then this input will not be used. + Otherwise, `out_size` should be equal with or larger than + max(dst_index) + 1. Default value is `None`. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out (Tensor), the output tensor, should have the same shape and same dtype as input tensor `x`. + If `out_size` is set correctly, then it should have the same shape as `x` except the 0th dimension. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + y = paddle.to_tensor([1, 1, 1, 1], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum") + # Outputs: [[1., 3., 4.], [4., 10., 12.], [2., 5., 6.]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + y = paddle.to_tensor([1, 1, 1], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out_size = paddle.max(dst_index) + 1 + out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum", out_size=out_size) + # Outputs: [[1., 3., 4.], [[4., 10., 12.]]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + y = paddle.to_tensor([1, 1, 1], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index, dst_index = indexes[:, 0], indexes[:, 1] + out = paddle.geometric.send_ue_recv(x, y, src_index, dst_index, message_op="add", reduce_op="sum") + # Outputs: [[1., 3., 4.], [4., 10., 12.], [0., 0., 0.]] + + """ + + if message_op not in ["add", "sub", "mul", "div"]: + raise ValueError( + "message_op should be `add`, `sub`, `mul`, `div`, but received %s" + % message_op + ) + + if reduce_op not in ["sum", "mean", "max", "min"]: + raise ValueError( + "reduce_op should be `sum`, `mean`, `max` or `min`, but received %s" + % reduce_op + ) + + x, y = reshape_lhs_rhs(x, y) + + if message_op == 'sub': + message_op = 'add' + y = -y + if message_op == "div": + message_op = 'mul' + y = 1.0 / (y + 1e-12) + + # TODO(daisiming): Should we add judgement for out_size: max(dst_index) + 1. + + if _in_legacy_dygraph(): + out_size = convert_out_size_to_list(out_size) + out, tmp = _legacy_C_ops.graph_send_ue_recv( + x, + y, + src_index, + dst_index, + None, + 'message_op', + message_op.upper(), + 'reduce_op', + reduce_op.upper(), + 'out_size', + out_size, + ) + return out + if in_dygraph_mode(): + out_size = convert_out_size_to_list(out_size) + return _C_ops.graph_send_ue_recv( + x, + y, + src_index, + dst_index, + message_op.upper(), + reduce_op.upper(), + out_size, + ) + + check_variable_and_dtype( + x, + "X", + ("float32", "float64", "int32", "int64", "float16"), + "graph_send_ue_recv", + ) + check_variable_and_dtype( + y, + "Y", + ("float32", "float64", "int32", "int64", "float16"), + "graph_send_ue_recv", + ) + check_variable_and_dtype( + src_index, "Src_index", ("int32", "int64"), "graph_send_ue_recv" + ) + check_variable_and_dtype( + dst_index, "Dst_index", ("int32", "int64"), "graph_send_ue_recv" + ) + if out_size: + check_type( + out_size, + 'out_size', + (int, np.int32, np.int64, Variable), + 'graph_send_ue_recv', + ) + if isinstance(out_size, Variable): + check_dtype( + out_size.dtype, 'out_size', ['int32', 'int64'], 'graph_send_ue_recv' + ) + + helper = LayerHelper("send_ue_recv", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + dst_count = helper.create_variable_for_type_inference( + dtype="int32", stop_gradient=True + ) + + inputs = {"X": x, "Y": y, "Src_index": src_index, "Dst_index": dst_index} + attrs = {"message_op": message_op.upper(), "reduce_op": reduce_op.upper()} + get_out_size_tensor_inputs( + inputs=inputs, + attrs=attrs, + out_size=out_size, + op_type='graph_send_ue_recv', + ) + + helper.append_op( + type="graph_send_ue_recv", + inputs=inputs, + outputs={"Out": out, "Dst_count": dst_count}, + attrs=attrs, + ) + return out + + +def send_uv(x, y, src_index, dst_index, message_op="add", name=None): + """ + + Graph Learning message passing api. + + This api is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory + consumption in the process of message passing. Take `x` as the source node feature tensor, take `y` as + the destination node feature tensor. Then we use `src_index` and `dst_index` to gather the corresponding data, + and then compute the edge features in different message_ops like `add`, `sub`, `mul`, `div`. + + .. code-block:: text + + Given: + + x = [[0, 2, 3], + [1, 4, 5], + [2, 6, 7]] + + y = [[0, 1, 2], + [2, 3, 4], + [4, 5, 6]] + + src_index = [0, 1, 2, 0] + + dst_index = [1, 2, 1, 0] + + message_op = "add" + + Then: + + out = [[2, 5, 7], + [5, 9, 11], + [4, 9, 11], + [0, 3, 5]] + + Args: + x (Tensor): The source node feature tensor, and the available data type is float32, float64, int32, int64. And we support float16 in gpu version. + y (Tensor): The destination node feature tensor, and the available data type is float32, float64, int32, int64. And we support float16 in gpu version. + src_index (Tensor): An 1-D tensor, and the available data type is int32, int64. + dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`. + The available data type is int32, int64. + message_op (str): Different message ops for x and y, including `add`, `sub`, `mul` and `div`. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out (Tensor), the output tensor. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + y = paddle.to_tensor([[0, 1, 2], [2, 3, 4], [4, 5, 6]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32") + src_index = indexes[:, 0] + dst_index = indexes[:, 1] + out = paddle.geometric.send_uv(x, y, src_index, dst_index, message_op="add") + # Outputs: [[2., 5., 7.], [5., 9., 11.], [4., 9., 11.], [0., 3., 5.]] + + """ + + if message_op not in ['add', 'sub', 'mul', 'div']: + raise ValueError( + "message_op should be `add`, `sub`, `mul`, `div`, but received %s" + % message_op + ) + + x, y = reshape_lhs_rhs(x, y) + + if message_op == 'sub': + message_op = 'add' + y = -y + if message_op == 'div': + message_op = 'mul' + y = 1.0 / (y + 1e-12) + + if in_dygraph_mode(): + return _C_ops.graph_send_uv( + x, y, src_index, dst_index, message_op.upper() + ) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.graph_send_uv( + x, y, src_index, dst_index, "message_op", message_op.upper() + ) + else: + helper = LayerHelper("send_uv", **locals()) + check_variable_and_dtype( + x, + 'x', + ['int32', 'int64', 'float32', 'float64', 'float16'], + 'graph_send_uv', + ) + check_variable_and_dtype( + y, + 'y', + ['int32', 'int64', 'float32', 'float64', 'float16'], + 'graph_send_uv', + ) + check_variable_and_dtype( + src_index, 'src_index', ['int32', 'int64'], 'graph_send_uv' + ) + check_variable_and_dtype( + dst_index, 'dst_index', ['int32', 'int64'], 'graph_send_uv' + ) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + inputs = { + 'x': x, + 'y': y, + 'src_index': src_index, + 'dst_index': dst_index, + } + attrs = {'message_op': message_op.upper()} + helper.append_op( + type="graph_send_uv", + inputs=inputs, + attrs=attrs, + outputs={"out": out}, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..51c088522983b79dd9edbe4b90c866ea25eeaca1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/message_passing/utils.py @@ -0,0 +1,85 @@ +# Copyright (c) 2022 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. + +import numpy as np +import paddle +from paddle.fluid.framework import Variable +from paddle.fluid.data_feeder import check_dtype, convert_dtype +from paddle.fluid.layers.tensor import cast + + +def convert_out_size_to_list(out_size): + """ + Convert out_size(int, np.int32, np.int64, Variable) to list + in imperative mode. + """ + if out_size is None: + out_size = [0] + elif isinstance(out_size, (int, np.int32, np.int64)): + out_size = [out_size] + else: + out_size = [out_size.numpy().astype(int)[0]] + return out_size + + +def get_out_size_tensor_inputs(inputs, attrs, out_size, op_type): + """ + Convert out_size(int, np.int32, np.int64, Variable) to inputs + and attrs in static mode. + """ + if out_size is None: + attrs['out_size'] = [0] + elif isinstance(out_size, (int, np.int32, np.int64)): + attrs['out_size'] = [out_size] + elif isinstance(out_size, Variable): + out_size.stop_gradient = True + check_dtype(out_size.dtype, 'out_size', ['int32', 'int64'], 'op_type', + '(When type of out_size in' + op_type + ' is Variable.)') + if (convert_dtype(out_size.dtype) == 'int64'): + out_size = cast(out_size, 'int32') + inputs["Out_size"] = out_size + else: + raise TypeError("Out_size only supports Variable or int.") + + +def reshape_lhs_rhs(x, y): + """ + Expand dims to ensure there will be no broadcasting issues with different + number of dimensions. + """ + if len(x.shape) == 1: + x = paddle.reshape(x, [-1, 1]) + if len(y.shape) == 1: + y = paddle.reshape(y, [-1, 1]) + + x_shape = paddle.shape(x) + y_shape = paddle.shape(y) + if len(x.shape) != len(y.shape): + max_ndims = max(len(x.shape), len(y.shape)) + x_pad_ndims = max_ndims - len(x.shape) + y_pad_ndims = max_ndims - len(y.shape) + new_x_shape = [ + x_shape[0], + ] + [ + 1, + ] * x_pad_ndims + list(x_shape[1:]) + new_y_shape = [ + y_shape[0], + ] + [ + 1, + ] * y_pad_ndims + list(y_shape[1:]) + x = paddle.reshape(x, new_x_shape) + y = paddle.reshape(y, new_y_shape) + + return x, y diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/reindex.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..3b68931dfb99e7a08a9586844ab65d5eb78f51f4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/reindex.py @@ -0,0 +1,270 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode, Variable +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def reindex_graph( + x, neighbors, count, value_buffer=None, index_buffer=None, name=None +): + """ + + Reindex Graph API. + + This API is mainly used in Graph Learning domain, which should be used + in conjunction with `paddle.geometric.sample_neighbors` API. And the main purpose + is to reindex the ids information of the input nodes, and return the + corresponding graph edges after reindex. + + Take input nodes x = [0, 1, 2] as an example. If we have neighbors = [8, 9, 0, 4, 7, 6, 7], and count = [2, 3, 2], + then we know that the neighbors of 0 is [8, 9], the neighbors of 1 is [0, 4, 7], and the neighbors of 2 is [6, 7]. + Then after graph_reindex, we will have 3 different outputs: reindex_src: [3, 4, 0, 5, 6, 7, 6], reindex_dst: [0, 0, 1, 1, 1, 2, 2] + and out_nodes: [0, 1, 2, 8, 9, 4, 7, 6]. We can see that the numbers in `reindex_src` and `reindex_dst` is the corresponding index + of nodes in `out_nodes`. + + Note: + The number in x should be unique, otherwise it would cause potential errors. We will reindex all the nodes from 0. + + Args: + x (Tensor): The input nodes which we sample neighbors for. The available + data type is int32, int64. + neighbors (Tensor): The neighbors of the input nodes `x`. The data type + should be the same with `x`. + count (Tensor): The neighbor count of the input nodes `x`. And the + data type should be int32. + value_buffer (Tensor, optional): Value buffer for hashtable. The data type should be int32, + and should be filled with -1. Only useful for gpu version. Default is None. + index_buffer (Tensor, optional): Index buffer for hashtable. The data type should be int32, + and should be filled with -1. Only useful for gpu version. + `value_buffer` and `index_buffer` should be both not None + if you want to speed up by using hashtable buffer. Default is None. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - reindex_src (Tensor), the source node index of graph edges after reindex. + + - reindex_dst (Tensor), the destination node index of graph edges after reindex. + + - out_nodes (Tensor), the index of unique input nodes and neighbors before reindex, where we put the input nodes `x` in the front, and put neighbor nodes in the back. + + Examples: + .. code-block:: python + + import paddle + + x = [0, 1, 2] + neighbors = [8, 9, 0, 4, 7, 6, 7] + count = [2, 3, 2] + x = paddle.to_tensor(x, dtype="int64") + neighbors = paddle.to_tensor(neighbors, dtype="int64") + count = paddle.to_tensor(count, dtype="int32") + reindex_src, reindex_dst, out_nodes = paddle.geometric.reindex_graph(x, neighbors, count) + # reindex_src: [3, 4, 0, 5, 6, 7, 6] + # reindex_dst: [0, 0, 1, 1, 1, 2, 2] + # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6] + + """ + use_buffer_hashtable = ( + True if value_buffer is not None and index_buffer is not None else False + ) + + if _non_static_mode(): + reindex_src, reindex_dst, out_nodes = _legacy_C_ops.graph_reindex( + x, + neighbors, + count, + value_buffer, + index_buffer, + "flag_buffer_hashtable", + use_buffer_hashtable, + ) + return reindex_src, reindex_dst, out_nodes + + check_variable_and_dtype(x, "X", ("int32", "int64"), "graph_reindex") + check_variable_and_dtype( + neighbors, "Neighbors", ("int32", "int64"), "graph_reindex" + ) + check_variable_and_dtype(count, "Count", ("int32"), "graph_reindex") + + if use_buffer_hashtable: + check_variable_and_dtype( + value_buffer, "HashTable_Value", ("int32"), "graph_reindex" + ) + check_variable_and_dtype( + index_buffer, "HashTable_Index", ("int32"), "graph_reindex" + ) + + helper = LayerHelper("reindex_graph", **locals()) + reindex_src = helper.create_variable_for_type_inference(dtype=x.dtype) + reindex_dst = helper.create_variable_for_type_inference(dtype=x.dtype) + out_nodes = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="graph_reindex", + inputs={ + "X": x, + "Neighbors": neighbors, + "Count": count, + "HashTable_Value": value_buffer if use_buffer_hashtable else None, + "HashTable_Index": index_buffer if use_buffer_hashtable else None, + }, + outputs={ + "Reindex_Src": reindex_src, + "Reindex_Dst": reindex_dst, + "Out_Nodes": out_nodes, + }, + attrs={"flag_buffer_hashtable": use_buffer_hashtable}, + ) + return reindex_src, reindex_dst, out_nodes + + +def reindex_heter_graph( + x, neighbors, count, value_buffer=None, index_buffer=None, name=None +): + """ + + Reindex HeterGraph API. + + This API is mainly used in Graph Learning domain, which should be used + in conjunction with `paddle.geometric.sample_neighbors` API. And the main purpose + is to reindex the ids information of the input nodes, and return the + corresponding graph edges after reindex. + + Take input nodes x = [0, 1, 2] as an example. For graph A, suppose we have neighbors = [8, 9, 0, 4, 7, 6, 7], and count = [2, 3, 2], + then we know that the neighbors of 0 is [8, 9], the neighbors of 1 is [0, 4, 7], and the neighbors of 2 is [6, 7]. For graph B, + suppose we have neighbors = [0, 2, 3, 5, 1], and count = [1, 3, 1], then we know that the neighbors of 0 is [0], the neighbors of 1 is [2, 3, 5], + and the neighbors of 3 is [1]. We will get following outputs: reindex_src: [3, 4, 0, 5, 6, 7, 6, 0, 2, 8, 9, 1], reindex_dst: [0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2] + and out_nodes: [0, 1, 2, 8, 9, 4, 7, 6, 3, 5]. + + Note: + The number in x should be unique, otherwise it would cause potential errors. We support multi-edge-types neighbors reindexing in reindex_heter_graph api. We will reindex all the nodes from 0. + + Args: + x (Tensor): The input nodes which we sample neighbors for. The available + data type is int32, int64. + neighbors (list|tuple): The neighbors of the input nodes `x` from different graphs. + The data type should be the same with `x`. + count (list|tuple): The neighbor counts of the input nodes `x` from different graphs. + And the data type should be int32. + value_buffer (Tensor, optional): Value buffer for hashtable. The data type should be int32, + and should be filled with -1. Only useful for gpu version. Default is None. + index_buffer (Tensor, optional): Index buffer for hashtable. The data type should be int32, + and should be filled with -1. Only useful for gpu version. + `value_buffer` and `index_buffer` should be both not None + if you want to speed up by using hashtable buffer. Default is None. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - reindex_src (Tensor), the source node index of graph edges after reindex. + + - reindex_dst (Tensor), the destination node index of graph edges after reindex. + + - out_nodes (Tensor), the index of unique input nodes and neighbors before reindex, + where we put the input nodes `x` in the front, and put neighbor + nodes in the back. + + Examples: + .. code-block:: python + + import paddle + + x = [0, 1, 2] + neighbors_a = [8, 9, 0, 4, 7, 6, 7] + count_a = [2, 3, 2] + x = paddle.to_tensor(x, dtype="int64") + neighbors_a = paddle.to_tensor(neighbors_a, dtype="int64") + count_a = paddle.to_tensor(count_a, dtype="int32") + neighbors_b = [0, 2, 3, 5, 1] + count_b = [1, 3, 1] + neighbors_b = paddle.to_tensor(neighbors_b, dtype="int64") + count_b = paddle.to_tensor(count_b, dtype="int32") + neighbors = [neighbors_a, neighbors_b] + count = [count_a, count_b] + reindex_src, reindex_dst, out_nodes = paddle.geometric.reindex_heter_graph(x, neighbors, count) + # reindex_src: [3, 4, 0, 5, 6, 7, 6, 0, 2, 8, 9, 1] + # reindex_dst: [0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2] + # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6, 3, 5] + + """ + use_buffer_hashtable = ( + True if value_buffer is not None and index_buffer is not None else False + ) + + if _non_static_mode(): + neighbors = paddle.concat(neighbors, axis=0) + count = paddle.concat(count, axis=0) + reindex_src, reindex_dst, out_nodes = _legacy_C_ops.graph_reindex( + x, + neighbors, + count, + value_buffer, + index_buffer, + "flag_buffer_hashtable", + use_buffer_hashtable, + ) + return reindex_src, reindex_dst, out_nodes + + if isinstance(neighbors, Variable): + neighbors = [neighbors] + if isinstance(count, Variable): + count = [count] + + neighbors = paddle.concat(neighbors, axis=0) + count = paddle.concat(count, axis=0) + + check_variable_and_dtype(x, "X", ("int32", "int64"), "heter_graph_reindex") + check_variable_and_dtype( + neighbors, "Neighbors", ("int32", "int64"), "graph_reindex" + ) + check_variable_and_dtype(count, "Count", ("int32"), "graph_reindex") + + if use_buffer_hashtable: + check_variable_and_dtype( + value_buffer, "HashTable_Value", ("int32"), "graph_reindex" + ) + check_variable_and_dtype( + index_buffer, "HashTable_Index", ("int32"), "graph_reindex" + ) + + helper = LayerHelper("reindex_heter_graph", **locals()) + reindex_src = helper.create_variable_for_type_inference(dtype=x.dtype) + reindex_dst = helper.create_variable_for_type_inference(dtype=x.dtype) + out_nodes = helper.create_variable_for_type_inference(dtype=x.dtype) + neighbors = paddle.concat(neighbors, axis=0) + count = paddle.concat(count, axis=0) + helper.append_op( + type="graph_reindex", + inputs={ + "X": x, + "Neighbors": neighbors, + "Count": count, + "HashTable_Value": value_buffer if use_buffer_hashtable else None, + "HashTable_Index": index_buffer if use_buffer_hashtable else None, + }, + outputs={ + "Reindex_Src": reindex_src, + "Reindex_Dst": reindex_dst, + "Out_Nodes": out_nodes, + }, + attrs={"flag_buffer_hashtable": use_buffer_hashtable}, + ) + return reindex_src, reindex_dst, out_nodes diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5b24fdd60b7fbc366f23a048b0645e2df9284c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022 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. + +from .neighbors import sample_neighbors # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/neighbors.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/neighbors.py new file mode 100644 index 0000000000000000000000000000000000000000..a52570576b04c64f5e67ed0f8a540ff316bde245 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/geometric/sampling/neighbors.py @@ -0,0 +1,173 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def sample_neighbors( + row, + colptr, + input_nodes, + sample_size=-1, + eids=None, + return_eids=False, + perm_buffer=None, + name=None, +): + """ + + Graph Sample Neighbors API. + + This API is mainly used in Graph Learning domain, and the main purpose is to + provide high performance of graph sampling method. For example, we get the + CSC(Compressed Sparse Column) format of the input graph edges as `row` and + `colptr`, so as to convert graph data into a suitable format for sampling. + `input_nodes` means the nodes we need to sample neighbors, and `sample_sizes` + means the number of neighbors and number of layers we want to sample. + + Besides, we support fisher-yates sampling in GPU version. + + Args: + row (Tensor): One of the components of the CSC format of the input graph, and + the shape should be [num_edges, 1] or [num_edges]. The available + data type is int32, int64. + colptr (Tensor): One of the components of the CSC format of the input graph, + and the shape should be [num_nodes + 1, 1] or [num_nodes + 1]. + The data type should be the same with `row`. + input_nodes (Tensor): The input nodes we need to sample neighbors for, and the + data type should be the same with `row`. + sample_size (int, optional): The number of neighbors we need to sample. Default value is -1, + which means returning all the neighbors of the input nodes. + eids (Tensor, optional): The eid information of the input graph. If return_eids is True, + then `eids` should not be None. The data type should be the + same with `row`. Default is None. + return_eids (bool, optional): Whether to return eid information of sample edges. Default is False. + perm_buffer (Tensor, optional): Permutation buffer for fisher-yates sampling. If `use_perm_buffer` + is True, then `perm_buffer` should not be None. The data type should + be the same with `row`. If not None, we will use fiser-yates sampling + to speed up. Only useful for gpu version. Default is None. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out_neighbors (Tensor), the sample neighbors of the input nodes. + + - out_count (Tensor), the number of sampling neighbors of each input node, and the shape + should be the same with `input_nodes`. + + - out_eids (Tensor), if `return_eids` is True, we will return the eid information of the + sample edges. + + Examples: + .. code-block:: python + + import paddle + + # edges: (3, 0), (7, 0), (0, 1), (9, 1), (1, 2), (4, 3), (2, 4), + # (9, 5), (3, 5), (9, 6), (1, 6), (9, 8), (7, 8) + row = [3, 7, 0, 9, 1, 4, 2, 9, 3, 9, 1, 9, 7] + colptr = [0, 2, 4, 5, 6, 7, 9, 11, 11, 13, 13] + nodes = [0, 8, 1, 2] + sample_size = 2 + row = paddle.to_tensor(row, dtype="int64") + colptr = paddle.to_tensor(colptr, dtype="int64") + nodes = paddle.to_tensor(nodes, dtype="int64") + out_neighbors, out_count = paddle.geometric.sample_neighbors(row, colptr, nodes, sample_size=sample_size) + + """ + + if return_eids: + if eids is None: + raise ValueError( + f"`eids` should not be None if `return_eids` is True." + ) + + use_perm_buffer = True if perm_buffer is not None else False + + if _non_static_mode(): + ( + out_neighbors, + out_count, + out_eids, + ) = _legacy_C_ops.graph_sample_neighbors( + row, + colptr, + input_nodes, + eids, + perm_buffer, + "sample_size", + sample_size, + "return_eids", + return_eids, + "flag_perm_buffer", + use_perm_buffer, + ) + if return_eids: + return out_neighbors, out_count, out_eids + return out_neighbors, out_count + + check_variable_and_dtype( + row, "Row", ("int32", "int64"), "graph_sample_neighbors" + ) + check_variable_and_dtype( + colptr, "Col_Ptr", ("int32", "int64"), "graph_sample_neighbors" + ) + check_variable_and_dtype( + input_nodes, "X", ("int32", "int64"), "graph_sample_neighbors" + ) + if return_eids: + check_variable_and_dtype( + eids, "Eids", ("int32", "int64"), "graph_sample_neighbors" + ) + if use_perm_buffer: + check_variable_and_dtype( + perm_buffer, + "Perm_Buffer", + ("int32", "int64"), + "graph_sample_neighbors", + ) + + helper = LayerHelper("sample_neighbors", **locals()) + out_neighbors = helper.create_variable_for_type_inference(dtype=row.dtype) + out_count = helper.create_variable_for_type_inference(dtype=row.dtype) + out_eids = helper.create_variable_for_type_inference(dtype=row.dtype) + helper.append_op( + type="graph_sample_neighbors", + inputs={ + "Row": row, + "Col_Ptr": colptr, + "X": input_nodes, + "Eids": eids if return_eids else None, + "Perm_Buffer": perm_buffer if use_perm_buffer else None, + }, + outputs={ + "Out": out_neighbors, + "Out_Count": out_count, + "Out_Eids": out_eids, + }, + attrs={ + "sample_size": sample_size, + "return_eids": return_eids, + "flag_perm_buffer": use_perm_buffer, + }, + ) + if return_eids: + return out_neighbors, out_count, out_eids + return out_neighbors, out_count diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2829bbe94708981f30ffcfdeeff89fd85899e33b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/__init__.py @@ -0,0 +1,27 @@ +# 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. + +from . import logger # noqa: F401 +from . import callbacks # noqa: F401 +from . import hub # noqa: F401 +from . import progressbar # noqa: F401 +from . import static_flops # noqa: F401 + +from .model import Model # noqa: F401 +from .model_summary import summary # noqa: F401 +from .dynamic_flops import flops # noqa: F401 + +logger.setup_logger() + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/callbacks.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd79b35a499abd017e57786a8dcc4f93bff32b4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/callbacks.py @@ -0,0 +1,1125 @@ +# 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. + +import os +import time +import numbers +import warnings + +import numpy as np + +import paddle +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.utils import try_import + +from .progressbar import ProgressBar + +__all__ = [] + + +def config_callbacks(callbacks=None, + model=None, + batch_size=None, + epochs=None, + steps=None, + log_freq=2, + verbose=2, + save_freq=1, + save_dir=None, + metrics=None, + mode='train'): + cbks = callbacks or [] + cbks = cbks if isinstance(cbks, (list, tuple)) else [cbks] + if not any(isinstance(k, ProgBarLogger) for k in cbks) and verbose: + cbks = [ProgBarLogger(log_freq, verbose=verbose)] + cbks + + if not any(isinstance(k, ModelCheckpoint) for k in cbks): + cbks = cbks + [ModelCheckpoint(save_freq, save_dir)] + + for k in cbks: + if isinstance(k, EarlyStopping): + k.save_dir = save_dir + if not any(isinstance(k, LRScheduler) for k in cbks): + cbks = cbks + [LRScheduler()] + + cbk_list = CallbackList(cbks) + cbk_list.set_model(model) + metrics = metrics or [] if mode != 'test' else [] + params = { + 'batch_size': batch_size, + 'epochs': epochs, + 'steps': steps, + 'verbose': verbose, + 'metrics': metrics, + } + cbk_list.set_params(params) + return cbk_list + + +class CallbackList(object): + + def __init__(self, callbacks=None): + # copy + self.callbacks = [c for c in callbacks] + self.params = {} + self.model = None + + def append(self, callback): + self.callbacks.append(callback) + + def __iter__(self): + return iter(self.callbacks) + + def set_params(self, params): + for c in self.callbacks: + c.set_params(params) + + def set_model(self, model): + for c in self.callbacks: + c.set_model(model) + + def _call(self, name, *args): + for c in self.callbacks: + func = getattr(c, name) + func(*args) + + def _check_mode(self, mode): + assert mode in ['train', 'eval', 'predict'], \ + 'mode should be train, eval or predict' + + def on_begin(self, mode, logs=None): + self._check_mode(mode) + name = 'on_{}_begin'.format(mode) + self._call(name, logs) + + def on_end(self, mode, logs=None): + self._check_mode(mode) + name = 'on_{}_end'.format(mode) + self._call(name, logs) + + def on_epoch_begin(self, epoch=None, logs=None): + self._call('on_epoch_begin', epoch, logs) + + def on_epoch_end(self, epoch=None, logs=None): + self._call('on_epoch_end', epoch, logs) + + def on_batch_begin(self, mode, step=None, logs=None): + self._check_mode(mode) + name = 'on_{}_batch_begin'.format(mode) + self._call(name, step, logs) + + def on_batch_end(self, mode, step=None, logs=None): + self._check_mode(mode) + name = 'on_{}_batch_end'.format(mode) + self._call(name, step, logs) + + +class Callback(object): + """ + Base class used to build new callbacks. And new callbacks could also + terminate training by setting `model.stop_training=True`. + + Examples: + + .. code-block:: python + + import paddle + + # build a simple model checkpoint callback + class ModelCheckpoint(paddle.callbacks.Callback): + def __init__(self, save_freq=1, save_dir=None): + self.save_freq = save_freq + self.save_dir = save_dir + + def on_epoch_end(self, epoch, logs=None): + if self.model is not None and epoch % self.save_freq == 0: + path = '{}/{}'.format(self.save_dir, epoch) + print('save checkpoint at {}'.format(path)) + self.model.save(path) + + """ + + def __init__(self): + self.model = None + self.params = {} + + def set_params(self, params): + """ + Set parameters, which is dict. The keys contain: + + - 'batch_size': an integer. Number of samples per batch. + - 'epochs': an integer. Number of epochs. + - 'steps': an integer. Number of steps of one epoch. + - 'verbose': an integer. Verbose mode is 0, 1 or 2. 0 = silent, 1 = progress bar, 2 = one line per epoch. + - 'metrics': a list of str. Names of metrics, including 'loss' and the names of paddle.metric.Metric. + """ + self.params = params + + def set_model(self, model): + """model is instance of paddle.Model. + """ + self.model = model + + def on_train_begin(self, logs=None): + """Called at the start of training. + + Args: + logs (dict): The logs is a dict or None. + """ + + def on_train_end(self, logs=None): + """Called at the end of training. + + Args: + logs (dict): The logs is a dict or None. The keys of logs + passed by paddle.Model contains 'loss', metric names and + `batch_size`. + """ + + def on_eval_begin(self, logs=None): + """Called at the start of evaluation. + + Args: + logs (dict): The logs is a dict or None. The keys of logs + passed by paddle.Model contains 'steps' and 'metrics', + The `steps` is number of total steps of validation dataset. + The `metrics` is a list of str including 'loss' and the names + of paddle.metric.Metric. + """ + + def on_eval_end(self, logs=None): + """Called at the end of evaluation. + + Args: + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is a dict contains 'loss', metrics and 'batch_size' + of last batch of validation dataset. + """ + + def on_predict_begin(self, logs=None): + """Called at the beginning of predict. + + Args: + logs (dict): The logs is a dict or None. + """ + + def on_predict_end(self, logs=None): + """Called at the end of predict. + + Args: + logs (dict): The logs is a dict or None. + """ + + def on_epoch_begin(self, epoch, logs=None): + """Called at the beginning of each epoch. + + Args: + epoch (int): The index of epoch. + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is None. + """ + + def on_epoch_end(self, epoch, logs=None): + """Called at the end of each epoch. + + Args: + epoch (int): The index of epoch. + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is a dict, contains 'loss', metrics and 'batch_size' + of last batch. + """ + + def on_train_batch_begin(self, step, logs=None): + """Called at the beginning of each batch in training. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is empty. + """ + + def on_train_batch_end(self, step, logs=None): + """Called at the end of each batch in training. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is a dict, contains 'loss', metrics and 'batch_size' + of current batch. + """ + + def on_eval_batch_begin(self, step, logs=None): + """Called at the beginning of each batch in evaluation. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is empty. + """ + + def on_eval_batch_end(self, step, logs=None): + """Called at the end of each batch in evaluation. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. The `logs` passed by + paddle.Model is a dict, contains 'loss', metrics and 'batch_size' + of current batch. + """ + + def on_predict_batch_begin(self, step, logs=None): + """Called at the beginning of each batch in predict. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. + """ + + def on_predict_batch_end(self, step, logs=None): + """Called at the end of each batch in predict. + + Args: + step (int): The index of step (or iteration). + logs (dict): The logs is a dict or None. + """ + + +class ProgBarLogger(Callback): + """ + Logger callback function to print loss and metrics to stdout. It supports + silent mode (not print), progress bar or one line per each printing, + see arguments for more detailed. + + Args: + log_freq (int): The frequency, in number of steps, + the logs such as loss, metrics are printed. Default: 1. + verbose (int): The verbosity mode, should be 0, 1, or 2. + 0 = silent, 1 = progress bar, 2 = one line each printing, 3 = 2 + + time counter, such as average reader cost, samples per second. + Default: 2. + + Examples: + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + from paddle.static import InputSpec + + inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')] + labels = [InputSpec([None, 1], 'int64', 'label')] + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + + lenet = paddle.vision.models.LeNet() + model = paddle.Model(lenet, + inputs, labels) + + optim = paddle.optimizer.Adam(0.001, parameters=lenet.parameters()) + model.prepare(optimizer=optim, + loss=paddle.nn.CrossEntropyLoss(), + metrics=paddle.metric.Accuracy()) + + callback = paddle.callbacks.ProgBarLogger(log_freq=10) + model.fit(train_dataset, batch_size=64, callbacks=callback) + """ + + def __init__(self, log_freq=1, verbose=2): + self.epochs = None + self.steps = None + self.progbar = None + self.verbose = verbose + self.log_freq = log_freq + + def _is_print(self): + return self.verbose and ParallelEnv().local_rank == 0 + + def on_train_begin(self, logs=None): + self.epochs = self.params['epochs'] + assert self.epochs + self.train_metrics = self.params['metrics'] + assert self.train_metrics + + self._train_timer = { + 'data_time': 0, + 'batch_time': 0, + 'count': 0, + 'samples': 0, + } + if self._is_print(): + print( + "The loss value printed in the log is the current step, and the metric is the average value of previous steps." + ) + + def on_epoch_begin(self, epoch=None, logs=None): + self.steps = self.params['steps'] + self.epoch = epoch + self.train_step = 0 + if self.epochs and self._is_print(): + print('Epoch %d/%d' % (epoch + 1, self.epochs)) + self.train_progbar = ProgressBar(num=self.steps, verbose=self.verbose) + + self._train_timer['batch_start_time'] = time.time() + + def _updates(self, logs, mode): + values = [] + metrics = getattr(self, '%s_metrics' % (mode)) + progbar = getattr(self, '%s_progbar' % (mode)) + steps = getattr(self, '%s_step' % (mode)) + + for k in metrics: + if k in logs: + values.append((k, logs[k])) + + if self.verbose == 3 and hasattr(self, '_%s_timer' % (mode)): + timer = getattr(self, '_%s_timer' % (mode)) + cnt = timer['count'] if timer['count'] > 0 else 1.0 + samples = timer['samples'] if timer['samples'] > 0 else 1.0 + values.append( + ('avg_reader_cost', "%.5f sec" % (timer['data_time'] / cnt))) + values.append( + ('avg_batch_cost', "%.5f sec" % (timer['batch_time'] / cnt))) + values.append( + ('ips', "%.5f samples/sec" % + (samples / (timer['data_time'] + timer['batch_time'])))) + timer['count'] = 0 + timer['samples'] = 0 + timer['data_time'] = 0. + timer['batch_time'] = 0. + + progbar.update(steps, values) + + def on_train_batch_begin(self, step, logs=None): + self._train_timer['batch_data_end_time'] = time.time() + self._train_timer['data_time'] += ( + self._train_timer['batch_data_end_time'] - + self._train_timer['batch_start_time']) + + def on_train_batch_end(self, step, logs=None): + logs = logs or {} + self.train_step += 1 + + self._train_timer['batch_time'] += ( + time.time() - self._train_timer['batch_data_end_time']) + self._train_timer['count'] += 1 + samples = logs.get('batch_size', 1) + self._train_timer['samples'] += samples + if self._is_print() and self.train_step % self.log_freq == 0: + if self.steps is None or self.train_step < self.steps: + self._updates(logs, 'train') + self._train_timer['batch_start_time'] = time.time() + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + if self._is_print() and (self.steps is not None): + self._updates(logs, 'train') + + def on_eval_begin(self, logs=None): + self.eval_steps = logs.get('steps', None) + self.eval_metrics = logs.get('metrics', []) + self.eval_step = 0 + self.evaled_samples = 0 + + self._eval_timer = { + 'data_time': 0, + 'batch_time': 0, + 'count': 0, + 'samples': 0, + } + + self.eval_progbar = ProgressBar(num=self.eval_steps, + verbose=self.verbose) + if self._is_print(): + print('Eval begin...') + + self._eval_timer['batch_start_time'] = time.time() + + def on_eval_batch_begin(self, step, logs=None): + self._eval_timer['batch_data_end_time'] = time.time() + self._eval_timer['data_time'] += ( + self._eval_timer['batch_data_end_time'] - + self._eval_timer['batch_start_time']) + + def on_eval_batch_end(self, step, logs=None): + logs = logs or {} + self.eval_step += 1 + samples = logs.get('batch_size', 1) + self.evaled_samples += samples + + self._eval_timer['batch_time'] += ( + time.time() - self._eval_timer['batch_data_end_time']) + self._eval_timer['count'] += 1 + samples = logs.get('batch_size', 1) + self._eval_timer['samples'] += samples + + if self._is_print() and self.eval_step % self.log_freq == 0: + if self.eval_steps is None or self.eval_step < self.eval_steps: + self._updates(logs, 'eval') + + self._eval_timer['batch_start_time'] = time.time() + + def on_predict_begin(self, logs=None): + self.test_steps = logs.get('steps', None) + self.test_metrics = logs.get('metrics', []) + self.test_step = 0 + self.tested_samples = 0 + + self._test_timer = { + 'data_time': 0, + 'batch_time': 0, + 'count': 0, + 'samples': 0, + } + + self.test_progbar = ProgressBar(num=self.test_steps, + verbose=self.verbose) + if self._is_print(): + print('Predict begin...') + + self._test_timer['batch_start_time'] = time.time() + + def on_predict_batch_begin(self, step, logs=None): + self._test_timer['batch_data_end_time'] = time.time() + self._test_timer['data_time'] += ( + self._test_timer['batch_data_end_time'] - + self._test_timer['batch_start_time']) + + def on_predict_batch_end(self, step, logs=None): + logs = logs or {} + self.test_step += 1 + samples = logs.get('batch_size', 1) + self.tested_samples += samples + + self._test_timer['batch_time'] += ( + time.time() - self._test_timer['batch_data_end_time']) + self._test_timer['count'] += 1 + samples = logs.get('batch_size', 1) + self._test_timer['samples'] += samples + + if self.test_step % self.log_freq == 0 and self._is_print(): + if self.test_steps is None or self.test_step < self.test_steps: + self._updates(logs, 'test') + + self._test_timer['batch_start_time'] = time.time() + + def on_eval_end(self, logs=None): + logs = logs or {} + if self._is_print() and (self.eval_steps is not None): + self._updates(logs, 'eval') + print('Eval samples: %d' % (self.evaled_samples)) + + def on_predict_end(self, logs=None): + logs = logs or {} + if self._is_print(): + if self.test_step % self.log_freq != 0 or self.verbose == 1: + self._updates(logs, 'test') + print('Predict samples: %d' % (self.tested_samples)) + + +class ModelCheckpoint(Callback): + """ + Model checkpoint callback function to save model weights and optimizer + state during training in conjunction with model.fit(). Currently, + ModelCheckpoint only supports saving after a fixed number of epochs. + + Args: + save_freq(int): The frequency, in number of epochs, the model checkpoint + are saved. Default: 1. + save_dir(str|None): The directory to save checkpoint during training. + If None, will not save checkpoint. Default: None. + + Examples: + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + from paddle.static import InputSpec + + inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')] + labels = [InputSpec([None, 1], 'int64', 'label')] + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + + lenet = paddle.vision.models.LeNet() + model = paddle.Model(lenet, + inputs, labels) + + optim = paddle.optimizer.Adam(0.001, parameters=lenet.parameters()) + model.prepare(optimizer=optim, + loss=paddle.nn.CrossEntropyLoss(), + metrics=paddle.metric.Accuracy()) + + callback = paddle.callbacks.ModelCheckpoint(save_dir='./temp') + model.fit(train_dataset, batch_size=64, callbacks=callback) + """ + + def __init__(self, save_freq=1, save_dir=None): + self.save_freq = save_freq + self.save_dir = save_dir + + def on_epoch_begin(self, epoch=None, logs=None): + self.epoch = epoch + + def _is_save(self): + return self.model and self.save_dir and ParallelEnv().local_rank == 0 + + def on_epoch_end(self, epoch, logs=None): + if self._is_save() and self.epoch % self.save_freq == 0: + path = '{}/{}'.format(self.save_dir, epoch) + print('save checkpoint at {}'.format(os.path.abspath(path))) + self.model.save(path) + + def on_train_end(self, logs=None): + if self._is_save(): + path = '{}/final'.format(self.save_dir) + print('save checkpoint at {}'.format(os.path.abspath(path))) + self.model.save(path) + + +class LRScheduler(Callback): + """Lr scheduler callback function + + Args: + by_step(bool, optional): whether to update learning rate scheduler + by step. Default: True. + by_epoch(bool, optional): whether to update learning rate scheduler + by epoch. Default: False. + + Examples: + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.static import InputSpec + + inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')] + labels = [InputSpec([None, 1], 'int64', 'label')] + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform) + + lenet = paddle.vision.models.LeNet() + model = paddle.Model(lenet, + inputs, labels) + + base_lr = 1e-3 + boundaries = [5, 8] + wamup_steps = 4 + + def make_optimizer(parameters=None): + momentum = 0.9 + weight_decay = 5e-4 + values = [base_lr * (0.1**i) for i in range(len(boundaries) + 1)] + learning_rate = paddle.optimizer.lr.PiecewiseDecay( + boundaries=boundaries, values=values) + learning_rate = paddle.optimizer.lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=wamup_steps, + start_lr=base_lr / 5., + end_lr=base_lr, + verbose=True) + optimizer = paddle.optimizer.Momentum( + learning_rate=learning_rate, + weight_decay=weight_decay, + momentum=momentum, + parameters=parameters) + return optimizer + + optim = make_optimizer(parameters=lenet.parameters()) + model.prepare(optimizer=optim, + loss=paddle.nn.CrossEntropyLoss(), + metrics=paddle.metric.Accuracy()) + + # if LRScheduler callback not set, an instance LRScheduler update by step + # will be created auto. + model.fit(train_dataset, batch_size=64) + + # create a learning rate scheduler update by epoch + callback = paddle.callbacks.LRScheduler(by_step=False, by_epoch=True) + model.fit(train_dataset, batch_size=64, callbacks=callback) + """ + + def __init__(self, by_step=True, by_epoch=False): + if by_step and by_epoch: + raise ValueError( + "by_step option is mutually exclusive with by_epoch") + + self.by_step = by_step + self.by_epoch = by_epoch + + def on_epoch_end(self, epoch, logs=None): + if self.by_epoch: + if self.model._optimizer and \ + hasattr(self.model._optimizer, '_learning_rate') and \ + isinstance(self.model._optimizer._learning_rate, + paddle.optimizer.lr.LRScheduler): + self.model._optimizer._learning_rate.step() + + def on_train_batch_end(self, step, logs=None): + if self.by_step: + if self.model._optimizer and \ + hasattr(self.model._optimizer, '_learning_rate') and \ + isinstance(self.model._optimizer._learning_rate, + paddle.optimizer.lr.LRScheduler): + self.model._optimizer._learning_rate.step() + + +class EarlyStopping(Callback): + """Stop training when the given monitor stopped improving during evaluation + by setting `model.stop_training=True`. + + Args: + monitor(str): Quantity to be monitored. Default: 'loss'. + mode(str|None): Mode should be one of 'auto', 'min' or 'max'. In 'min' + mode, training will stop until monitored quantity stops decreasing. + In 'max' mode, training will stop until monitored quantity stops + increasing. In 'auto' mode, exact mode can be inferred by the name + of monitor. If 'acc' in monitor, the mode will be considered as + 'max', otherwise the mode will be set to 'min'. Default: 'auto'. + patience(int): Number of epochs with no improvement after which + training will be stopped. Default: 0. + verbose(int): The verbosity mode, should be 0 or 1. When verbose=0, + logs will not be printed. When verbose=1, logs will be printed. + Default: 1. + min_delta(int|float): The minimum change of monitored quantity. If + the change is less than min_delta, model could be considered as no + improvement. Default: 0. + baseline(int|float|None): Baseline value for the monitored quantity. + Training will stop if the model doesn't show improvement over the + baseline. Default: None. + save_best_model(bool): Whether to save best model. Default: True. + + Examples: + .. code-block:: python + + import paddle + from paddle import Model + from paddle.static import InputSpec + from paddle.vision.models import LeNet + from paddle.vision.datasets import MNIST + from paddle.metric import Accuracy + from paddle.nn import CrossEntropyLoss + import paddle.vision.transforms as T + + device = paddle.set_device('cpu') + sample_num = 200 + save_dir = './best_model_checkpoint' + transform = T.Compose( + [T.Transpose(), T.Normalize([127.5], [127.5])]) + train_dataset = MNIST(mode='train', transform=transform) + val_dataset = MNIST(mode='test', transform=transform) + net = LeNet() + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=net.parameters()) + + inputs = [InputSpec([None, 1, 28, 28], 'float32', 'x')] + labels = [InputSpec([None, 1], 'int64', 'label')] + + model = Model(net, inputs=inputs, labels=labels) + model.prepare( + optim, + loss=CrossEntropyLoss(reduction="sum"), + metrics=[Accuracy()]) + callbacks = paddle.callbacks.EarlyStopping( + 'loss', + mode='min', + patience=1, + verbose=1, + min_delta=0, + baseline=None, + save_best_model=True) + model.fit(train_dataset, + val_dataset, + batch_size=64, + log_freq=200, + save_freq=10, + save_dir=save_dir, + epochs=20, + callbacks=[callbacks]) + """ + + def __init__(self, + monitor='loss', + mode='auto', + patience=0, + verbose=1, + min_delta=0, + baseline=None, + save_best_model=True): + super(EarlyStopping, self).__init__() + self.monitor = monitor + self.patience = patience + self.verbose = verbose + self.baseline = baseline + self.min_delta = abs(min_delta) + self.wait_epoch = 0 + self.best_weights = None + self.stopped_epoch = 0 + self.save_best_model = save_best_model + # The value of `save_dir` is set in function `config_callbacks` + self.save_dir = None + if mode not in ['auto', 'min', 'max']: + warnings.warn('EarlyStopping mode %s is unknown, ' + 'fallback to auto mode.' % mode) + mode = 'auto' + if mode == 'min': + self.monitor_op = np.less + elif mode == 'max': + self.monitor_op = np.greater + # When mode == 'auto', the mode should be inferred by `self.monitor` + else: + if 'acc' in self.monitor: + self.monitor_op = np.greater + else: + self.monitor_op = np.less + + if self.monitor_op == np.greater: + self.min_delta *= 1 + else: + self.min_delta *= -1 + + def on_train_begin(self, logs=None): + self.wait_epoch = 0 + if self.baseline is not None: + self.best_value = self.baseline + else: + self.best_value = np.inf if self.monitor_op == np.less else -np.inf + self.best_weights = None + + def on_eval_end(self, logs=None): + if logs is None or self.monitor not in logs: + warnings.warn( + 'Monitor of EarlyStopping should be loss or metric name.') + return + current = logs[self.monitor] + if isinstance(current, (list, tuple)): + current = current[0] + elif isinstance(current, numbers.Number): + current = current + else: + return + + if self.monitor_op(current - self.min_delta, self.best_value): + self.best_value = current + self.wait_epoch = 0 + if self.save_best_model and self.save_dir is not None: + path = os.path.join(self.save_dir, 'best_model') + self.model.save(path) + else: + self.wait_epoch += 1 + if self.wait_epoch >= self.patience: + self.model.stop_training = True + if self.verbose > 0: + print('Epoch %d: Early stopping.' % (self.stopped_epoch + 1)) + if self.save_best_model and self.save_dir is not None: + print('Best checkpoint has been saved at %s' % + (os.path.abspath( + os.path.join(self.save_dir, 'best_model')))) + self.stopped_epoch += 1 + + +class VisualDL(Callback): + """ + VisualDL callback function. + + Args: + log_dir (str): The directory to save visualdl log file. + + Examples: + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.static import InputSpec + + inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')] + labels = [InputSpec([None, 1], 'int64', 'label')] + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform) + eval_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform) + + net = paddle.vision.models.LeNet() + model = paddle.Model(net, inputs, labels) + + optim = paddle.optimizer.Adam(0.001, parameters=net.parameters()) + model.prepare(optimizer=optim, + loss=paddle.nn.CrossEntropyLoss(), + metrics=paddle.metric.Accuracy()) + + ## uncomment following lines to fit model with visualdl callback function + # callback = paddle.callbacks.VisualDL(log_dir='visualdl_log_dir') + # model.fit(train_dataset, eval_dataset, batch_size=64, callbacks=callback) + + """ + + def __init__(self, log_dir): + self.log_dir = log_dir + self.epochs = None + self.steps = None + self.epoch = 0 + + def _is_write(self): + return ParallelEnv().local_rank == 0 + + def on_train_begin(self, logs=None): + self.epochs = self.params['epochs'] + assert self.epochs + self.train_metrics = self.params['metrics'] + assert self.train_metrics + self._is_fit = True + self.train_step = 0 + + def on_epoch_begin(self, epoch=None, logs=None): + self.steps = self.params['steps'] + self.epoch = epoch + + def _updates(self, logs, mode): + if not self._is_write(): + return + if not hasattr(self, 'writer'): + visualdl = try_import('visualdl') + self.writer = visualdl.LogWriter(self.log_dir) + + metrics = getattr(self, '%s_metrics' % (mode)) + current_step = getattr(self, '%s_step' % (mode)) + + if mode == 'train': + total_step = current_step + else: + total_step = self.epoch + + for k in metrics: + if k in logs: + temp_tag = mode + '/' + k + + if isinstance(logs[k], (list, tuple)): + temp_value = logs[k][0] + elif isinstance(logs[k], numbers.Number): + temp_value = logs[k] + else: + continue + + self.writer.add_scalar(tag=temp_tag, + step=total_step, + value=temp_value) + + def on_train_batch_end(self, step, logs=None): + logs = logs or {} + self.train_step += 1 + + if self._is_write(): + self._updates(logs, 'train') + + def on_eval_begin(self, logs=None): + self.eval_steps = logs.get('steps', None) + self.eval_metrics = logs.get('metrics', []) + self.eval_step = 0 + self.evaled_samples = 0 + + def on_train_end(self, logs=None): + if hasattr(self, 'writer'): + self.writer.close() + delattr(self, 'writer') + + def on_eval_end(self, logs=None): + if self._is_write(): + self._updates(logs, 'eval') + + if (not hasattr(self, '_is_fit')) and hasattr(self, 'writer'): + self.writer.close() + delattr(self, 'writer') + + +class ReduceLROnPlateau(Callback): + """Reduce learning rate when a metric of evaluation has stopped improving. + Models often benefit from reducing the learning rate by a factor + of 2-10 once learning stagnates. This callback monitors a + quantity and if no improvement is seen for a 'patience' number + of epochs, the learning rate is reduced. + + Args: + monitor(str, optional): Quantity to be monitored. Default: 'loss'. + factor(float, optional): factor by which the learning rate will be reduced. + `new_lr = lr * factor`. Default: 0.1. + patience(int, optional): Number of epochs with no improvement after which + learning rate will be reduced. Default: 10. + verbose(int, optional): The verbosity mode. 0: quiet, 1: update messages. + Default: 1. + mode(str, optional): one of `{'auto', 'min', 'max'}`. In `'min'` mode, + the learning rate will be reduced when the quantity monitored has + stopped decreasing. In 'max' mode, learning rate will reduce until + monitored quantity stops increasing. In 'auto' mode, exact mode + can be inferred by the name of monitor. If 'acc' in monitor, the + mode will be considered as 'max', otherwise the mode will be set + to 'min'. Default: 'auto'. + min_delta(int|float, optional): threshold for measuring the new optimum, + to only focus on significant changes. Default: 0. + cooldown(int, optional): number of epochs to wait before resuming normal operation after + lr has been reduced. Default: 0. + min_lr(float, optional): lower bound on the learning rate. Default: 0. + + Examples: + .. code-block:: python + + import paddle + from paddle import Model + from paddle.static import InputSpec + from paddle.vision.models import LeNet + from paddle.vision.datasets import MNIST + from paddle.metric import Accuracy + from paddle.nn.layer.loss import CrossEntropyLoss + import paddle.vision.transforms as T + sample_num = 200 + transform = T.Compose( + [T.Transpose(), T.Normalize([127.5], [127.5])]) + train_dataset = MNIST(mode='train', transform=transform) + val_dataset = MNIST(mode='test', transform=transform) + net = LeNet() + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=net.parameters()) + inputs = [InputSpec([None, 1, 28, 28], 'float32', 'x')] + labels = [InputSpec([None, 1], 'int64', 'label')] + model = Model(net, inputs=inputs, labels=labels) + model.prepare( + optim, + loss=CrossEntropyLoss(), + metrics=[Accuracy()]) + callbacks = paddle.callbacks.ReduceLROnPlateau(patience=3, verbose=1) + model.fit(train_dataset, + val_dataset, + batch_size=64, + log_freq=200, + save_freq=10, + epochs=20, + callbacks=[callbacks]) + + """ + + def __init__(self, + monitor='loss', + factor=0.1, + patience=10, + verbose=1, + mode='auto', + min_delta=1e-4, + cooldown=0, + min_lr=0): + super(ReduceLROnPlateau, self).__init__() + + self.monitor = monitor + if factor >= 1.0: + raise ValueError('ReduceLROnPlateau ' + 'does not support a factor >= 1.0.') + + self.factor = factor + self.min_lr = min_lr + self.min_delta = min_delta + self.patience = patience + self.verbose = verbose + self.cooldown = cooldown + self.cooldown_counter = 0 # Cooldown counter. + self.wait = 0 + self.best = 0 + self.mode = mode + self.monitor_op = None + self.epoch = 0 + self._reset() + + def _reset(self): + """Resets wait counter and cooldown counter. + """ + if self.mode not in ['auto', 'min', 'max']: + warnings.warn('Learning rate reduction mode %s is unknown, ' + 'fallback to auto mode.' % self.mode) + self.mode = 'auto' + if (self.mode == 'min' + or (self.mode == 'auto' and 'acc' not in self.monitor)): + self.monitor_op = lambda a, b: np.less(a, b - self.min_delta) + self.best = np.Inf + else: + self.monitor_op = lambda a, b: np.greater(a, b + self.min_delta) + self.best = -np.Inf + self.cooldown_counter = 0 + self.wait = 0 + + def on_train_begin(self, logs=None): + self._reset() + + def on_eval_end(self, logs=None): + if logs is None or self.monitor not in logs: + warnings.warn( + 'Monitor of ReduceLROnPlateau should be loss or metric name.') + return + else: + try: + lr = self.model._optimizer._learning_rate + if not isinstance(lr, float): + warnings.warn( + 'Expected learning_rate be float, bug got {}.'.format( + type(lr))) + return + except Exception as e: + warnings.warn( + 'There are something wrong when get learning_rate from optimizer: {}.' + .format(e)) + return + + current = logs[self.monitor] + if isinstance(current, (list, tuple)): + current = current[0] + elif isinstance(current, numbers.Number): + current = current + else: + return + + if self.in_cooldown(): + self.cooldown_counter -= 1 + self.wait = 0 + + if self.monitor_op(current, self.best): + self.best = current + self.wait = 0 + elif not self.in_cooldown(): + self.wait += 1 + if self.wait >= self.patience: + old_lr = self.model._optimizer.get_lr() + if old_lr > np.float32(self.min_lr): + new_lr = old_lr * self.factor + new_lr = max(new_lr, self.min_lr) + self.model._optimizer._learning_rate = new_lr + if self.verbose > 0 and ParallelEnv().local_rank == 0: + print('\nEpoch %d: ReduceLROnPlateau reducing learning ' + 'rate to %s.' % (self.epoch + 1, new_lr)) + self.cooldown_counter = self.cooldown + self.wait = 0 + self.epoch += 1 + + def in_cooldown(self): + return self.cooldown_counter > 0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/dynamic_flops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/dynamic_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..214af9f2f5986edcc085716243c19a8d160cc388 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/dynamic_flops.py @@ -0,0 +1,296 @@ +# 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. + +import paddle +import warnings +import paddle.nn as nn +import numpy as np +from .static_flops import static_flops, Table +from paddle.fluid.dygraph.dygraph_to_static.program_translator import unwrap_decorators + +__all__ = [] + + +def flops(net, input_size, custom_ops=None, print_detail=False): + """Print a table about the FLOPs of network. + + Args: + net (paddle.nn.Layer||paddle.static.Program): The network which could be a instance of paddle.nn.Layer in + dygraph or paddle.static.Program in static graph. + input_size (list): size of input tensor. Note that the batch_size in argument ``input_size`` only support 1. + custom_ops (A dict of function, optional): A dictionary which key is the class of specific operation such as + paddle.nn.Conv2D and the value is the function used to count the FLOPs of this operation. This + argument only work when argument ``net`` is an instance of paddle.nn.Layer. The details could be found + in following example code. Default is None. + print_detail (bool, optional): Whether to print the detail information, like FLOPs per layer, about the net FLOPs. + Default is False. + + Returns: + Int: A number about the FLOPs of total network. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + class LeNet(nn.Layer): + def __init__(self, num_classes=10): + super(LeNet, self).__init__() + self.num_classes = num_classes + self.features = nn.Sequential( + nn.Conv2D( + 1, 6, 3, stride=1, padding=1), + nn.ReLU(), + nn.MaxPool2D(2, 2), + nn.Conv2D( + 6, 16, 5, stride=1, padding=0), + nn.ReLU(), + nn.MaxPool2D(2, 2)) + + if num_classes > 0: + self.fc = nn.Sequential( + nn.Linear(400, 120), + nn.Linear(120, 84), + nn.Linear( + 84, 10)) + + def forward(self, inputs): + x = self.features(inputs) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x) + return x + + lenet = LeNet() + # m is the instance of nn.Layer, x is the intput of layer, y is the output of layer. + def count_leaky_relu(m, x, y): + x = x[0] + nelements = x.numel() + m.total_ops += int(nelements) + + FLOPs = paddle.flops(lenet, [1, 1, 28, 28], custom_ops= {nn.LeakyReLU: count_leaky_relu}, + print_detail=True) + print(FLOPs) + + #+--------------+-----------------+-----------------+--------+--------+ + #| Layer Name | Input Shape | Output Shape | Params | Flops | + #+--------------+-----------------+-----------------+--------+--------+ + #| conv2d_2 | [1, 1, 28, 28] | [1, 6, 28, 28] | 60 | 47040 | + #| re_lu_2 | [1, 6, 28, 28] | [1, 6, 28, 28] | 0 | 0 | + #| max_pool2d_2 | [1, 6, 28, 28] | [1, 6, 14, 14] | 0 | 0 | + #| conv2d_3 | [1, 6, 14, 14] | [1, 16, 10, 10] | 2416 | 241600 | + #| re_lu_3 | [1, 16, 10, 10] | [1, 16, 10, 10] | 0 | 0 | + #| max_pool2d_3 | [1, 16, 10, 10] | [1, 16, 5, 5] | 0 | 0 | + #| linear_0 | [1, 400] | [1, 120] | 48120 | 48000 | + #| linear_1 | [1, 120] | [1, 84] | 10164 | 10080 | + #| linear_2 | [1, 84] | [1, 10] | 850 | 840 | + #+--------------+-----------------+-----------------+--------+--------+ + #Total Flops: 347560 Total Params: 61610 + """ + if isinstance(net, nn.Layer): + # If net is a dy2stat model, net.forward is StaticFunction instance, + # we set net.forward to original forward function. + _, net.forward = unwrap_decorators(net.forward) + + inputs = paddle.randn(input_size) + return dynamic_flops(net, + inputs=inputs, + custom_ops=custom_ops, + print_detail=print_detail) + elif isinstance(net, paddle.static.Program): + return static_flops(net, print_detail=print_detail) + else: + warnings.warn( + "Your model must be an instance of paddle.nn.Layer or paddle.static.Program." + ) + return -1 + + +def count_convNd(m, x, y): + x = x[0] + kernel_ops = np.product(m.weight.shape[2:]) + bias_ops = 1 if m.bias is not None else 0 + total_ops = int( + y.numel()) * (x.shape[1] / m._groups * kernel_ops + bias_ops) + m.total_ops += abs(int(total_ops)) + + +def count_leaky_relu(m, x, y): + x = x[0] + nelements = x.numel() + m.total_ops += int(nelements) + + +def count_bn(m, x, y): + x = x[0] + nelements = x.numel() + if not m.training: + total_ops = 2 * nelements + m.total_ops += abs(int(total_ops)) + + +def count_linear(m, x, y): + total_mul = m.weight.shape[0] + num_elements = y.numel() + total_ops = total_mul * num_elements + m.total_ops += abs(int(total_ops)) + + +def count_avgpool(m, x, y): + kernel_ops = 1 + num_elements = y.numel() + total_ops = kernel_ops * num_elements + + m.total_ops += int(total_ops) + + +def count_adap_avgpool(m, x, y): + kernel = np.array(x[0].shape[2:]) // np.array(y.shape[2:]) + total_add = np.product(kernel) + total_div = 1 + kernel_ops = total_add + total_div + num_elements = y.numel() + total_ops = kernel_ops * num_elements + m.total_ops += abs(int(total_ops)) + + +def count_zero_ops(m, x, y): + m.total_ops += int(0) + + +def count_parameters(m, x, y): + total_params = 0 + for p in m.parameters(): + total_params += p.numel() + m.total_params[0] = abs(int(total_params)) + + +def count_io_info(m, x, y): + m.register_buffer('input_shape', paddle.to_tensor(x[0].shape)) + if isinstance(y, (list, tuple)): + m.register_buffer('output_shape', paddle.to_tensor(y[0].shape)) + else: + m.register_buffer('output_shape', paddle.to_tensor(y.shape)) + + +register_hooks = { + nn.Conv1D: count_convNd, + nn.Conv2D: count_convNd, + nn.Conv3D: count_convNd, + nn.Conv1DTranspose: count_convNd, + nn.Conv2DTranspose: count_convNd, + nn.Conv3DTranspose: count_convNd, + nn.layer.norm.BatchNorm2D: count_bn, + nn.BatchNorm: count_bn, + nn.ReLU: count_zero_ops, + nn.ReLU6: count_zero_ops, + nn.LeakyReLU: count_leaky_relu, + nn.Linear: count_linear, + nn.Dropout: count_zero_ops, + nn.AvgPool1D: count_avgpool, + nn.AvgPool2D: count_avgpool, + nn.AvgPool3D: count_avgpool, + nn.AdaptiveAvgPool1D: count_adap_avgpool, + nn.AdaptiveAvgPool2D: count_adap_avgpool, + nn.AdaptiveAvgPool3D: count_adap_avgpool +} + + +def dynamic_flops(model, inputs, custom_ops=None, print_detail=False): + handler_collection = [] + types_collection = set() + if custom_ops is None: + custom_ops = {} + + def add_hooks(m): + if len(list(m.children())) > 0: + return + m.register_buffer('total_ops', paddle.zeros([1], dtype='int64')) + m.register_buffer('total_params', paddle.zeros([1], dtype='int64')) + m_type = type(m) + + flops_fn = None + if m_type in custom_ops: + flops_fn = custom_ops[m_type] + if m_type not in types_collection: + print( + "Customize Function has been applied to {}".format(m_type)) + elif m_type in register_hooks: + flops_fn = register_hooks[m_type] + if m_type not in types_collection: + print("{}'s flops has been counted".format(m_type)) + else: + if m_type not in types_collection: + print( + "Cannot find suitable count function for {}. Treat it as zero FLOPs." + .format(m_type)) + + if flops_fn is not None: + flops_handler = m.register_forward_post_hook(flops_fn) + handler_collection.append(flops_handler) + params_handler = m.register_forward_post_hook(count_parameters) + io_handler = m.register_forward_post_hook(count_io_info) + handler_collection.append(params_handler) + handler_collection.append(io_handler) + types_collection.add(m_type) + + training = model.training + + model.eval() + model.apply(add_hooks) + + with paddle.framework.no_grad(): + model(inputs) + + total_ops = 0 + total_params = 0 + for m in model.sublayers(): + if len(list(m.children())) > 0: + continue + if {'total_ops', 'total_params', 'input_shape', + 'output_shape'}.issubset(set(list(m._buffers.keys()))): + total_ops += m.total_ops + total_params += m.total_params + + if training: + model.train() + for handler in handler_collection: + handler.remove() + + table = Table( + ["Layer Name", "Input Shape", "Output Shape", "Params", "Flops"]) + + for n, m in model.named_sublayers(): + if len(list(m.children())) > 0: + continue + if {'total_ops', 'total_params', 'input_shape', + 'output_shape'}.issubset(set(list(m._buffers.keys()))): + table.add_row([ + m.full_name(), + list(m.input_shape.numpy()), + list(m.output_shape.numpy()), + int(m.total_params), + int(m.total_ops) + ]) + m._buffers.pop("total_ops") + m._buffers.pop("total_params") + m._buffers.pop('input_shape') + m._buffers.pop('output_shape') + if print_detail: + table.print_table() + print('Total Flops: {} Total Params: {}'.format(int(total_ops), + int(total_params))) + return int(total_ops) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/hub.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..3217059c647d05826bbe4a91a5be70278bff3099 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/hub.py @@ -0,0 +1,302 @@ +# Copyright (c) 2021 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. + +import os +import re +import sys +import shutil +import zipfile +from paddle.utils.download import get_path_from_url + +__all__ = [] + +DEFAULT_CACHE_DIR = '~/.cache' +VAR_DEPENDENCY = 'dependencies' +MODULE_HUBCONF = 'hubconf.py' +HUB_DIR = os.path.expanduser(os.path.join('~', '.cache', 'paddle', 'hub')) + + +def _remove_if_exists(path): + if os.path.exists(path): + if os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) + + +def _import_module(name, repo_dir): + sys.path.insert(0, repo_dir) + try: + hub_module = __import__(name) + sys.modules.pop(name) + except ImportError: + sys.path.remove(repo_dir) + raise RuntimeError( + 'Please make sure config exists or repo error messages above fixed when importing' + ) + + sys.path.remove(repo_dir) + + return hub_module + + +def _git_archive_link(repo_owner, repo_name, branch, source): + if source == 'github': + return 'https://github.com/{}/{}/archive/{}.zip'.format( + repo_owner, repo_name, branch) + elif source == 'gitee': + return 'https://gitee.com/{}/{}/repository/archive/{}.zip'.format( + repo_owner, repo_name, branch) + + +def _parse_repo_info(repo, source): + branch = 'main' if source == 'github' else 'master' + if ':' in repo: + repo_info, branch = repo.split(':') + else: + repo_info = repo + repo_owner, repo_name = repo_info.split('/') + return repo_owner, repo_name, branch + + +def _make_dirs(dirname): + try: + from pathlib import Path + except ImportError: + from pathlib2 import Path + Path(dirname).mkdir(exist_ok=True) + + +def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'): + # Setup hub_dir to save downloaded files + hub_dir = HUB_DIR + + _make_dirs(hub_dir) + + # Parse github/gitee repo information + repo_owner, repo_name, branch = _parse_repo_info(repo, source) + # Github allows branch name with slash '/', + # this causes confusion with path on both Linux and Windows. + # Backslash is not allowed in Github branch name so no need to + # to worry about it. + normalized_br = branch.replace('/', '_') + # Github renames folder repo/v1.x.x to repo-1.x.x + # We don't know the repo name before downloading the zip file + # and inspect name from it. + # To check if cached repo exists, we need to normalize folder names. + repo_dir = os.path.join(hub_dir, + '_'.join([repo_owner, repo_name, normalized_br])) + + use_cache = (not force_reload) and os.path.exists(repo_dir) + + if use_cache: + if verbose: + sys.stderr.write('Using cache found in {}\n'.format(repo_dir)) + else: + cached_file = os.path.join(hub_dir, normalized_br + '.zip') + _remove_if_exists(cached_file) + + url = _git_archive_link(repo_owner, repo_name, branch, source=source) + + fpath = get_path_from_url( + url, + hub_dir, + check_exist=not force_reload, + decompress=False, + method=('wget' if source == 'gitee' else 'get')) + shutil.move(fpath, cached_file) + + with zipfile.ZipFile(cached_file) as cached_zipfile: + extraced_repo_name = cached_zipfile.infolist()[0].filename + extracted_repo = os.path.join(hub_dir, extraced_repo_name) + _remove_if_exists(extracted_repo) + # Unzip the code and rename the base folder + cached_zipfile.extractall(hub_dir) + + _remove_if_exists(cached_file) + _remove_if_exists(repo_dir) + # rename the repo + shutil.move(extracted_repo, repo_dir) + + return repo_dir + + +def _load_entry_from_hubconf(m, name): + '''load entry from hubconf + ''' + if not isinstance(name, str): + raise ValueError( + 'Invalid input: model should be a str of function name') + + func = getattr(m, name, None) + + if func is None or not callable(func): + raise RuntimeError('Cannot find callable {} in hubconf'.format(name)) + + return func + + +def _check_module_exists(name): + try: + __import__(name) + return True + except ImportError: + return False + + +def _check_dependencies(m): + dependencies = getattr(m, VAR_DEPENDENCY, None) + + if dependencies is not None: + missing_deps = [ + pkg for pkg in dependencies if not _check_module_exists(pkg) + ] + if len(missing_deps): + raise RuntimeError('Missing dependencies: {}'.format( + ', '.join(missing_deps))) + + +def list(repo_dir, source='github', force_reload=False): + r""" + List all entrypoints available in `github` hubconf. + + Args: + repo_dir(str): github or local path. + + github path (str): a str with format "repo_owner/repo_name[:tag_name]" with an optional + tag/branch. The default branch is `main` if not specified. + + local path (str): local repo path + + source (str): `github` | `gitee` | `local`, default is `github`. + force_reload (bool, optional): whether to discard the existing cache and force a fresh download, default is `False`. + Returns: + entrypoints: a list of available entrypoint names + + Example: + .. code-block:: python + + import paddle + + paddle.hub.list('lyuwenyu/paddlehub_demo:main', source='github', force_reload=False) + + """ + if source not in ('github', 'gitee', 'local'): + raise ValueError( + 'Unknown source: "{}". Allowed values: "github" | "gitee" | "local".' + .format(source)) + + if source in ('github', 'gitee'): + repo_dir = _get_cache_or_reload(repo_dir, + force_reload, + True, + source=source) + + hub_module = _import_module(MODULE_HUBCONF.split('.')[0], repo_dir) + + entrypoints = [ + f for f in dir(hub_module) + if callable(getattr(hub_module, f)) and not f.startswith('_') + ] + + return entrypoints + + +def help(repo_dir, model, source='github', force_reload=False): + """ + Show help information of model + + Args: + repo_dir(str): github or local path. + + github path (str): a str with format "repo_owner/repo_name[:tag_name]" with an optional + tag/branch. The default branch is `main` if not specified. + + local path (str): local repo path. + + model (str): model name. + source (str): `github` | `gitee` | `local`, default is `github`. + force_reload (bool, optional): default is `False`. + Return: + docs + + Example: + .. code-block:: python + + import paddle + + paddle.hub.help('lyuwenyu/paddlehub_demo:main', model='MM', source='github') + + """ + if source not in ('github', 'gitee', 'local'): + raise ValueError( + 'Unknown source: "{}". Allowed values: "github" | "gitee" | "local".' + .format(source)) + + if source in ('github', 'gitee'): + repo_dir = _get_cache_or_reload(repo_dir, + force_reload, + True, + source=source) + + hub_module = _import_module(MODULE_HUBCONF.split('.')[0], repo_dir) + + entry = _load_entry_from_hubconf(hub_module, model) + + return entry.__doc__ + + +def load(repo_dir, model, source='github', force_reload=False, **kwargs): + """ + Load model + + Args: + repo_dir(str): github or local path. + + github path (str): a str with format "repo_owner/repo_name[:tag_name]" with an optional + tag/branch. The default branch is `main` if not specified. + + local path (str): local repo path. + + model (str): model name. + source (str): `github` | `gitee` | `local`, default is `github`. + force_reload (bool, optional): default is `False`. + **kwargs: parameters using for model + Return: + paddle model + Example: + .. code-block:: python + + import paddle + paddle.hub.load('lyuwenyu/paddlehub_demo:main', model='MM', source='github') + + """ + if source not in ('github', 'gitee', 'local'): + raise ValueError( + 'Unknown source: "{}". Allowed values: "github" | "gitee" | "local".' + .format(source)) + + if source in ('github', 'gitee'): + repo_dir = _get_cache_or_reload(repo_dir, + force_reload, + True, + source=source) + + hub_module = _import_module(MODULE_HUBCONF.split('.')[0], repo_dir) + + _check_dependencies(hub_module) + + entry = _load_entry_from_hubconf(hub_module, model) + + return entry(**kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/logger.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..ea515d95324675b071f810c813fcf0849490d007 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/logger.py @@ -0,0 +1,73 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +import logging + +from paddle.fluid.dygraph.parallel import ParallelEnv + +__all__ = [] + + +def setup_logger(output=None, name="hapi", log_level=logging.INFO): + """ + Initialize logger of hapi and set its verbosity level to "INFO". + + Args: + output (str): a file name or a directory to save log. If None, will not save log file. + If ends with ".txt" or ".log", assumed to be a file name. + Otherwise, logs will be saved to `output/log.txt`. + name (str): the root module name of this logger. Default: 'hapi'. + log_level (enum): log level. eg.'INFO', 'DEBUG', 'ERROR'. Default: logging.INFO. + Returns: + logging.Logger: a logger + """ + logger = logging.getLogger(name) + logger.propagate = False + logger.setLevel(log_level) + + format_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + # stdout logging: only local rank==0 + local_rank = ParallelEnv().local_rank + if local_rank == 0 and len(logger.handlers) == 0: + ch = logging.StreamHandler(stream=sys.stdout) + ch.setLevel(log_level) + + ch.setFormatter(logging.Formatter(format_str)) + logger.addHandler(ch) + + # file logging if output is not None: all workers + if output is not None: + if output.endswith(".txt") or output.endswith(".log"): + filename = output + else: + filename = os.path.join(output, "log.txt") + + if local_rank > 0: + filename = filename + ".rank{}".format(local_rank) + + if not os.path.exists(os.path.dirname(filename)): + os.makedirs(os.path.dirname(filename)) + + fh = logging.StreamHandler(filename) + fh.setLevel(log_level) + fh.setFormatter(logging.Formatter(format_str)) + logger.addHandler(fh) + + return logger diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model.py new file mode 100644 index 0000000000000000000000000000000000000000..cea4951d8ef68373d304a4acdd3dd8f712b0d2f1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model.py @@ -0,0 +1,2443 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import inspect +import os +import pickle +import numpy as np +import six +import warnings +import time +import socket +import contextlib + +import paddle +from paddle import fluid +from paddle.fluid import core +from paddle.fluid.framework import _non_static_mode, in_dygraph_mode +from paddle.fluid.framework import Variable +from paddle.fluid.framework import _get_paddle_place +from paddle.fluid.framework import _current_expected_place as _get_device +from paddle.fluid.executor import global_scope +from paddle.fluid.io import is_belong_to_optimizer +from paddle.fluid.dygraph.base import to_variable +from paddle.fluid.dygraph.parallel import ParallelEnv +from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX +from paddle.fluid.dygraph.io import INFER_PARAMS_SUFFIX +from paddle.fluid.layers.utils import flatten +from paddle.fluid.layers import collective + +from paddle.io import DataLoader +from paddle.io import Dataset +from paddle.io import DistributedBatchSampler +from paddle.metric import Metric +from paddle.static import InputSpec as Input +from paddle.distributed.fleet.base import role_maker +from paddle.autograd import no_grad +from paddle.distributed import fleet +from paddle.distributed.parallel import init_parallel_env + +from .callbacks import config_callbacks, EarlyStopping +from .model_summary import summary + +__all__ = [] + +_parallel_context_initialized = False + + +def to_list(value): + if value is None: + return value + if isinstance(value, (list, tuple)): + return list(value) + return [value] + + +def to_numpy(var): + assert isinstance( + var, (Variable, fluid.core.VarBase, fluid.core.eager.Tensor) + ), "not a variable" + if isinstance(var, (fluid.core.VarBase, fluid.core.eager.Tensor)): + return var.numpy() + t = global_scope().find_var(var.name).get_tensor() + return np.array(t) + + +def flatten_list(l): + assert isinstance(l, list), "not a list" + outl = [] + splits = [] + for sl in l: + assert isinstance(sl, list), "sub content not a list" + splits.append(len(sl)) + outl += sl + return outl, splits + + +def restore_flatten_list(l, splits): + outl = [] + for split in splits: + assert len(l) >= split, "list length invalid" + sl, l = l[:split], l[split:] + outl.append(sl) + return outl + + +def extract_args(func): + if hasattr(inspect, 'getfullargspec'): + return inspect.getfullargspec(func)[0] + else: + return inspect.getargspec(func)[0] + + +def _all_gather(x, nranks, ring_id=0, use_calc_stream=True): + return collective._c_allgather( + x, nranks, ring_id=ring_id, use_calc_stream=use_calc_stream + ) + + +def wait_server_ready(endpoints): + assert not isinstance(endpoints, six.string_types) + while True: + all_ok = True + not_ready_endpoints = [] + for ep in endpoints: + ip_port = ep.split(":") + with contextlib.closing( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) + ) as sock: + sock.settimeout(2) + result = sock.connect_ex((ip_port[0], int(ip_port[1]))) + if result != 0: + all_ok = False + not_ready_endpoints.append(ep) + if not all_ok: + time.sleep(3) + else: + break + + +def init_communicator( + program, rank, nranks, wait_port, current_endpoint, endpoints +): + if nranks < 2: + return + other_endpoints = endpoints[:] + other_endpoints.remove(current_endpoint) + block = program.global_block() + if rank == 0 and wait_port: + wait_server_ready(other_endpoints) + if core.is_compiled_with_cuda(): + nccl_id_var = block.create_var( + name=fluid.unique_name.generate('nccl_id'), + persistable=True, + type=fluid.core.VarDesc.VarType.RAW, + ) + + block.append_op( + type='c_gen_nccl_id', + inputs={}, + outputs={'Out': nccl_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + }, + ) + + block.append_op( + type='c_comm_init', + inputs={'X': nccl_id_var}, + outputs={}, + attrs={ + 'nranks': nranks, + 'rank': rank, + 'ring_id': 0, + }, + ) + elif core.is_compiled_with_npu(): + hccl_id_var = block.create_var( + name=fluid.unique_name.generate('hccl_id'), + persistable=True, + type=core.VarDesc.VarType.RAW, + ) + block.append_op( + type='c_gen_hccl_id', + inputs={}, + outputs={'Out': hccl_id_var}, + attrs={ + 'rank': rank, + 'endpoint': current_endpoint, + 'other_endpoints': other_endpoints, + }, + ) + block.append_op( + type='c_comm_init_hccl', + inputs={'X': hccl_id_var}, + outputs={}, + attrs={ + 'rank': rank, + 'ring_id': 0, + 'device_id': int(os.getenv("FLAGS_selected_npus")), + 'rank_ids': nranks, + }, + ) + + +def prepare_distributed_context(place=None): + if place is None: + place = ( + fluid.CUDAPlace(ParallelEnv().dev_id) + if ParallelEnv().nranks > 1 + else fluid.CUDAPlace(0) + ) + + place = _get_paddle_place(place) + strategy = fluid.dygraph.parallel.ParallelStrategy() + strategy.nranks = ParallelEnv().nranks + strategy.local_rank = ParallelEnv().local_rank + strategy.trainer_endpoints = ParallelEnv().trainer_endpoints + strategy.current_endpoint = ParallelEnv().current_endpoint + + if strategy.nranks < 2: + return + + global _parallel_context_initialized + + if not _parallel_context_initialized and isinstance(place, fluid.CUDAPlace): + + def _init_context(): + communicator_prog = fluid.Program() + init_communicator( + communicator_prog, + strategy.local_rank, + strategy.nranks, + True, + strategy.current_endpoint, + strategy.trainer_endpoints, + ) + exe = fluid.Executor(place) + exe.run(communicator_prog) + + if fluid._non_static_mode(): + fluid.disable_dygraph() + _init_context() + fluid.enable_dygraph(place) + + else: + assert "Only support CUDAPlace for now." + + _parallel_context_initialized = True + return strategy + + +def _update_input_info(inputs): + "Get input shape list by given inputs in Model initialization." + shapes = None + dtypes = None + if isinstance(inputs, Input): + shapes = [list(inputs.shape)] + dtypes = [inputs.dtype] + elif isinstance(inputs, (list, tuple)): + shapes = [list(input.shape) for input in inputs] + dtypes = [input.dtype for input in inputs] + elif isinstance(inputs, dict): + shapes = [list(inputs[name].shape) for name in inputs] + dtypes = [inputs[name].dtype for name in inputs] + else: + return None + return shapes, dtypes + + +class StaticGraphAdapter(object): + """ + + Model traning/inference with a static graph. + + """ + + def __init__(self, model): + super(StaticGraphAdapter, self).__init__() + self.model = model + # with `_build_once` gone, parameters are now created in `__init__` + # so we need to keep track of the parameters already created + self._startup_prog = fluid.default_startup_program() + self._orig_prog = fluid.default_main_program() + + self._label_vars = {} # label variables + self._input_vars = {} # label variables + self._endpoints = {} + self._loss_endpoint = None + self._executor = None + self._progs = {} + self._compiled_progs = {} + + self._merge_count = { + 'eval_total': 0, + 'test_total': 0, + 'eval_batch': 0, + 'test_batch': 0, + } + + self._nranks = ParallelEnv().nranks + self._local_rank = ParallelEnv().local_rank + + self._amp_level = "O0" + self._amp_configs = {} + self._amp_custom_lists = {} + self._use_fp16_guard = None + + @property + def mode(self): + return self.model.mode + + @mode.setter + def mode(self, value): + self.model.mode = value + + def train_batch(self, inputs, labels=None, update=True): + assert ( + self.model._optimizer + ), "model not ready, please call `model.prepare()` first" + self.mode = 'train' + assert ( + update is True + ), "Does not support `update == False` in static mode by now." + return self._run(inputs, labels) + + def eval_batch(self, inputs, labels=None): + self.mode = 'eval' + return self._run(inputs, labels) + + def predict_batch(self, inputs): + self.mode = 'test' + return self._run(inputs, None) + + def parameters(self, *args, **kwargs): + return self.model.network.parameters(*args, **kwargs) + + def save(self, path): + def _save(state, path): + if not state: + return + state = { + k: to_numpy(v) if isinstance(v, Variable) else v + for k, v in state.items() + } + with open(path, 'wb') as f: + pickle.dump(state, f) + + base = os.path.basename(path) + assert base != "", "path should be of 'dirname/filename' format" + dir_name = os.path.dirname(path) + if dir_name and not os.path.exists(dir_name): + os.makedirs(dir_name) + param_path = path + ".pdparams" + _save(self.model.network.state_dict(), param_path) + prog = self._progs.get('train', None) + if prog is None or self.model._optimizer is None: + return + # XXX `optimizer.state_dict()` only work in dygraph mode + optim_path = path + ".pdopt" + optim = { + p.name: p for p in filter(is_belong_to_optimizer, prog.list_vars()) + } + if not optim: + return + + _save(optim, optim_path) + + # TODO: support save/load scaler state in static graph + def load(self, param_state_pairs, optim_state): + if self._executor is None: + executor = fluid.Executor(fluid.CPUPlace())._default_executor + else: + executor = self._executor._default_executor + + # restore parameter states + fluid.core._create_loaded_parameter( + [param for param, state in param_state_pairs], + global_scope(), + executor, + ) + for param, state in param_state_pairs: + self._set_var(param, state) + + # restore optimizer states + # FIXME what if a different optimizer is used? + if not self.model._optimizer or not optim_state: + return + self._load_optimizer(optim_state, executor) + + def _load_optimizer(self, state, executor): + prog = self._progs.get('train', None) + optim = list(filter(is_belong_to_optimizer, prog.list_vars())) + if not optim: + return + + fluid.core._create_loaded_parameter(optim, global_scope(), executor) + + converted_state = dict(state) + for var in optim: + if var.name in ["@LR_DECAY_COUNTER@", "global_step"]: + # When using learning rate scheduler, dygraph would name the + # global step var as "global_step" to save, while static-graph + # would has a state var named as "@LR_DECAY_COUNTER@". + # NOTE: dygraph saved global_step is 1 larger than that in + # static-graph, since the time of global_step to increase is + # different. + state_val = ( + (np.array(converted_state.pop("global_step")) - 1) + if "global_step" in converted_state + else converted_state.pop("@LR_DECAY_COUNTER@", None) + ) + if state_val is not None: + converted_state[var.name] = state_val + elif var.name.startswith("learning_rate_"): + # When using static learning rate, static-graph would make it + # a persistable var named 'unique_name.generate("learning_rate")', + # However, dygraph wouldn't save it. + if var.name not in state: + continue + else: + # moment and other accumulators + if var.name not in converted_state: + # try to convert from dygraph name + opt_name = self.model._optimizer._name + opt_cls_name = self.model._optimizer.__class__.__name__ + opt_unq_name = None + for name in self.model._optimizer._accumulators.keys(): + accum_name = ( + name + if opt_name is None + else name[len(opt_name) + 1 :] + ) + for ( + param_name, + state_var, + ) in self.model._optimizer._accumulators[name].items(): + if opt_unq_name is None: + # can not infer out the exact unique(opt_name), + # thus try to extract rather than generate + for state_key in sorted( + state.keys(), + key=lambda x: len(x), + reverse=True, + ): + prefix = ( + param_name + + "_" + + ( + opt_cls_name + if opt_name is None + else opt_name + ) + + "_" + ) + if state_key.startswith(prefix): + prefix_offset = state_key[ + len(prefix) : + ].find("_") + len(prefix) + opt_unq_name = state_key[ + len( + param_name + "_" + ) : prefix_offset + ] + # TODO: assert + # assert opt_unq_name is None + # gen(param.name + "_" + gen(opt_name) + "_" + accum_name) + # always end with "_0" since the unique optimizer._name + dy_state_name = ( + param_name + + "_" + + opt_unq_name + + "_" + + accum_name + + "_0" + ) + converted_state[ + state_var.name + ] = converted_state.pop(dy_state_name) + + assert ( + var.name in converted_state + ), "variable [{}] is not in optimizer state file".format(var.name) + self._set_var(var, converted_state[var.name]) + + def _set_var(self, var, ndarray): + t = global_scope().find_var(var.name).get_tensor() + p = t._place() + if p.is_cpu_place(): + place = fluid.CPUPlace() + elif p.is_cuda_pinned_place(): + place = fluid.CUDAPinnedPlace() + else: + p = fluid.core.Place() + p.set_place(t._place()) + place = fluid.CUDAPlace(p.gpu_device_id()) + + t.set(ndarray, place) + + def _run(self, inputs, labels=None): + compiled_prog = self._compiled_progs.get(self.mode, None) + assert ( + compiled_prog + ), "Model is not ready, please call `model.prepare()` first" + + inputs = to_list(inputs) + if labels is not None: + labels = to_list(labels) + assert len(inputs) == len(self._input_vars[self.mode]), ( + "number of inputs" + + " does not match number of arguments of `forward` method" + ) + + feed = {} + input_names = [v.name for v in self._input_vars[self.mode]] + input_dtypes = [v.dtype for v in self._input_vars[self.mode]] + + for idx, n in enumerate(input_names): + # train and test may take different arguments + if inputs[idx] is not None: + feed[n] = inputs[idx] + if ( + self._amp_level == 'O2' + and input_dtypes[idx] == core.VarDesc.VarType.FP16 + ): + if isinstance(feed[n], core.LoDTensor): + feed[n] = feed[n]._as_type(core.VarDesc.VarType.FP16) + elif isinstance(feed[n], np.array): + feed[n] = feed[n].astype('float16') + + if labels is not None: + for idx, v in enumerate(self._label_vars[self.mode]): + feed[v.name] = labels[idx] + + endpoints = self._endpoints[self.mode] + if self.mode == 'test': + fetch_list = endpoints['output'] + else: + metric_list, metric_splits = flatten_list(endpoints['metric']) + fetch_list = endpoints['loss'] + metric_list + num_loss = len(endpoints['loss']) + + # if fetch Variable is same as input Variable, do not fetch + # from program, get it from input directly + pruned_fetch_list = [] + pruned_fetch_idx_name_map = [""] * len(fetch_list) + for i, fetch_var in enumerate(fetch_list): + if fetch_var.name in feed.keys(): + pruned_fetch_idx_name_map[i] = fetch_var.name + else: + pruned_fetch_list.append(fetch_var) + + rets = self._executor.run( + compiled_prog, + feed=feed, + fetch_list=pruned_fetch_list, + return_numpy=False, + ) + + # restore pruned fetch_list Variable from feeds + for i, name in enumerate(pruned_fetch_idx_name_map): + if len(name) > 0: + rets.insert(i, feed[name]) + + # LoDTensor cannot be fetch as numpy directly + rets = [np.array(v) for v in rets] + if self.mode == 'test': + return rets[:] + + metric_states = restore_flatten_list(rets[num_loss:], metric_splits) + metrics = [] + for metric, state in zip(self.model._metrics, metric_states): + # cut off padding size + if ( + self.mode != 'train' + and self.model._test_dataloader is not None + and isinstance(self.model._test_dataloader, DataLoader) + and self._nranks > 1 + ): + total_size = len(self.model._test_dataloader.dataset) + # TODO: fixme if have better way to get batch size + samples = state[0].shape[0] + current_count = self._merge_count.get(self.mode + '_total', 0) + if current_count + samples >= total_size: + state = [ + s[: int(total_size - current_count), ...] for s in state + ] + self._merge_count[self.mode + '_total'] = 0 + self._merge_count[self.mode + '_batch'] = int( + total_size - current_count + ) + else: + self._merge_count[self.mode + '_total'] += samples + self._merge_count[self.mode + '_batch'] = samples + + metrics.append(metric.update(*state)) + + if num_loss and len(metrics): + return rets[:num_loss], metrics + else: + return rets[:num_loss] if num_loss else metrics + + def prepare(self): + modes = ['train', 'eval', 'test'] + for mode in modes: + self._make_program(mode) + self._compile_and_initialize(self._progs[mode], mode) + + def _make_program(self, mode): + prog = self._progs.get(mode, None) + if prog is not None: + return + + prog = self._orig_prog.clone() + # NOTE: When defining learning rate scheduling in static-graph, ops to + # increase the global step var and calculate learning rate would be + # prepended into _orig_prog. test program maked by `_orig_prog.clone` + # also would include these ops. Thus must prune these ops in test + # program, otherwise the global step would be changed in test. + if mode != 'train': + for op in list(prog.global_block().ops): + prog.global_block()._remove_op(0) + if ( + mode == 'train' + and self.model._optimizer + and self.model._optimizer._learning_rate_map + ): + # HACK workaround learning rate map issue + lr_var = self.model._optimizer._learning_rate_map[self._orig_prog] + new_lr_var = prog.global_block().vars[lr_var.name] + self.model._optimizer._learning_rate_map[prog] = new_lr_var + + losses = [] + metrics = [] + with fluid.program_guard(prog, self._startup_prog): + inputs = self.model._inputs + labels = self.model._labels if self.model._labels else [] + inputs = [k._create_feed_layer() for k in to_list(inputs)] + labels = [k._create_feed_layer() for k in to_list(labels)] + self._label_vars[mode] = labels + outputs = to_list(self.model.network.forward(*inputs)) + + if mode != 'test' and self.model._loss: + losses = self.model._loss(*(outputs + labels)) + + if self._nranks > 1 and mode != 'train': + outputs = [_all_gather(o, self._nranks) for o in outputs] + if mode != 'test': + labels = [_all_gather(l, self._nranks) for l in labels] + + if mode != 'test': + for metric in self.model._metrics: + metrics.append(to_list(metric.compute(*(outputs + labels)))) + + if mode == 'train' and self.model._optimizer: + self._loss_endpoint = fluid.layers.sum(losses) + if self._nranks > 1: + role = role_maker.PaddleCloudRoleMaker(is_collective=True) + fleet.init(role) + dist_strategy = fleet.DistributedStrategy() + if self._amp_level != 'O0': + dist_strategy.amp = True + dist_strategy.amp_configs = self._amp_configs.copy() + dist_strategy.amp_configs.update(self._amp_custom_lists) + dist_strategy.amp_configs['use_pure_fp16'] = ( + self._amp_level == 'O2' + ) + self.model._optimizer = fleet.distributed_optimizer( + self.model._optimizer, strategy=dist_strategy + ) + elif self._amp_level != "O0" and core.is_compiled_with_cuda: + amp_lists = ( + paddle.static.amp.AutoMixedPrecisionLists( + **self._amp_custom_lists + ) + if self._amp_custom_lists + else None + ) + self.model._optimizer = paddle.static.amp.decorate( + self.model._optimizer, + amp_lists=amp_lists, + use_pure_fp16=self._amp_level == "O2", + use_fp16_guard=self._use_fp16_guard, + **self._amp_configs + ) + + self.model._optimizer.minimize(self._loss_endpoint) + + if mode != 'train': # clone again to put it in test mode + prog = prog.clone(for_test=True) + + self._input_vars[mode] = inputs + + self._progs[mode] = prog + self._endpoints[mode] = { + "output": outputs, + "loss": to_list(losses), + "metric": metrics, + } + + def _compile_and_initialize(self, prog, mode): + compiled_prog = self._compiled_progs.get(mode, None) + if compiled_prog is not None: + return compiled_prog + + assert ( + self.model._place is not None + ), "device is not set, please call `model.prepare()` first" + + place = self.model._place + + # XXX *ALL WEIGHTS* should be initialized upon model construction + # even if `forward()` may run different code path for different mode + # therefore startup program only needs to run once + if self._executor is None: + self._executor = fluid.Executor(place) + # XXX incremental initialization + uninitialized = [] + for var_py in self._startup_prog.list_vars(): + var = fluid.global_scope().find_var(var_py.name) + if ( + not var_py.name.startswith('nccl_id') + and var + and var.get_tensor()._is_initialized() + ): + continue + + uninitialized.append(var_py) + if uninitialized: + startup_prog = self._startup_prog._prune(uninitialized) + self._executor.run(startup_prog) + + if ( + self._amp_level == "O2" + and mode == 'train' + and core.is_compiled_with_cuda() + ): + self.model._optimizer.amp_init(place) + + if self._nranks < 2: + compiled_prog = fluid.CompiledProgram(prog) + else: + compiled_prog = prog + + self._compiled_progs[mode] = compiled_prog + + +class DynamicGraphAdapter(object): + def __init__(self, model): + super(DynamicGraphAdapter, self).__init__() + self.model = model + self._nranks = ParallelEnv().nranks + self._local_rank = ParallelEnv().local_rank + self._merge_count = { + 'eval_total': 0, + 'test_total': 0, + 'eval_batch': 0, + 'test_batch': 0, + } + + self._input_info = None + self._amp_level = "O0" + self._amp_configs = {} + self._amp_custom_lists = {} + self._use_fp16_guard = True + + if self._nranks > 1: + init_parallel_env() + stradegy = fluid.dygraph.parallel.ParallelStrategy() + stradegy.nranks = ParallelEnv().nranks + stradegy.local_rank = ParallelEnv().local_rank + stradegy.trainer_endpoints = ParallelEnv().trainer_endpoints + stradegy.current_endpoint = ParallelEnv().current_endpoint + self.ddp_model = fluid.dygraph.parallel.DataParallel( + self.model.network, stradegy + ) + + @property + def mode(self): + return self.model.mode + + @mode.setter + def mode(self, value): + self.model.mode = value + + # TODO multi device in dygraph mode not implemented at present time + def train_batch(self, inputs, labels=None, update=True): + assert ( + self.model._optimizer + ), "model not ready, please call `model.prepare()` first" + self.model.network.train() + self.mode = 'train' + inputs = to_list(inputs) + self._input_info = _update_input_info(inputs) + labels = labels or [] + labels = [to_variable(l) for l in to_list(labels)] + + # scaler should be initialized only once + if self._amp_level != "O0" and self.model._scaler is None: + self.model._scaler = paddle.amp.GradScaler(**self._amp_configs) + + with paddle.amp.auto_cast( + enable=self._amp_level != 'O0', + **self._amp_custom_lists, + level=self._amp_level + ): + if self._nranks > 1: + outputs = self.ddp_model(*[to_variable(x) for x in inputs]) + else: + outputs = self.model.network(*[to_variable(x) for x in inputs]) + + losses = self.model._loss(*(to_list(outputs) + labels)) + losses = to_list(losses) + final_loss = fluid.layers.sum(losses) + + if self._amp_level != "O0": + scaled = self.model._scaler.scale(final_loss) + scaled.backward() + if update: + self.model._scaler.minimize(self.model._optimizer, scaled) + self.model.network.clear_gradients() + else: + final_loss.backward() + if update: + self.model._optimizer.minimize(final_loss) + self.model.network.clear_gradients() + + metrics = [] + for metric in self.model._metrics: + metric_outs = metric.compute(*(to_list(outputs) + labels)) + m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)]) + metrics.append(m) + + return ( + ([to_numpy(l) for l in losses], metrics) + if len(metrics) > 0 + else [to_numpy(l) for l in losses] + ) + + def eval_batch(self, inputs, labels=None): + self.model.network.eval() + self.mode = 'eval' + inputs = to_list(inputs) + self._input_info = _update_input_info(inputs) + labels = labels or [] + labels = [to_variable(l) for l in to_list(labels)] + + outputs = self.model.network(*[to_variable(x) for x in inputs]) + + # Transfrom data to expected device + expected_device = paddle.device.get_device() + for o in to_list(outputs): + o._to(device=expected_device) + + for l in labels: + l._to(device=expected_device) + + if self.model._loss: + losses = self.model._loss(*(to_list(outputs) + labels)) + losses = to_list(losses) + + if self._nranks > 1: + outputs = [_all_gather(o, self._nranks) for o in to_list(outputs)] + labels = [_all_gather(l, self._nranks) for l in labels] + metrics = [] + for metric in self.model._metrics: + # cut off padding value. + if ( + self.model._test_dataloader is not None + and self._nranks > 1 + and isinstance(self.model._test_dataloader, DataLoader) + ): + total_size = len(self.model._test_dataloader.dataset) + samples = outputs[0].shape[0] + current_count = self._merge_count.get(self.mode + '_total', 0) + if current_count + samples >= total_size: + outputs = [ + o[: int(total_size - current_count)] for o in outputs + ] + labels = [ + l[: int(total_size - current_count)] for l in labels + ] + self._merge_count[self.mode + '_total'] = 0 + self._merge_count[self.mode + '_batch'] = int( + total_size - current_count + ) + else: + self._merge_count[self.mode + '_total'] += samples + self._merge_count[self.mode + '_batch'] = samples + + metric_outs = metric.compute(*(to_list(outputs) + labels)) + m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)]) + metrics.append(m) + + if self.model._loss and len(metrics): + return [to_numpy(l) for l in losses], metrics + elif self.model._loss: + return [to_numpy(l) for l in losses] + else: + return metrics + + def predict_batch(self, inputs): + self.model.network.eval() + self.mode = 'test' + inputs = [to_variable(x) for x in to_list(inputs)] + self._input_info = _update_input_info(inputs) + outputs = self.model.network(*inputs) + if self._nranks > 1 and isinstance(self.model._place, fluid.CUDAPlace): + outputs = [_all_gather(o, self._nranks) for o in to_list(outputs)] + + return [to_numpy(o) for o in to_list(outputs)] + + def parameters(self, *args, **kwargs): + return self.model.network.parameters(*args, **kwargs) + + def save(self, path): + params = self.model.network.state_dict() + fluid.save_dygraph(params, path) + if self.model._optimizer is not None: + if self.model._optimizer.state_dict(): + optim = self.model._optimizer.state_dict() + fluid.save_dygraph(optim, path) + if hasattr(self.model, '_scaler') and self.model._scaler is not None: + if self.model._scaler.state_dict(): + scaler = self.model._scaler.state_dict() + paddle.save(scaler, path + '.pdscaler') + + def load(self, param_state_pairs, optim_state, scaler_state=None): + # restore parameter states + for param, state in param_state_pairs: + param.set_value(state) + + if hasattr(self.model, '_scaler') and self.model._scaler is not None: + if scaler_state: + self.model._scaler.load_state_dict(scaler_state) + + # resotre optimizer states + if not self.model._optimizer or not optim_state: + return + + # If optimizer performs set_state_dict when state vars haven't been created, + # which would happen when set_state_dict before minimize, the state would be + # stored in optimizer._accumulators_holder and loaded lazily. + # To contrive this when loading from static-graph saved states, extend + # state dict to include keys named accoring to dygraph naming rules. + # TODO: if len(self.model._optimizer._accumulators) > 0 + converted_state = dict(optim_state) + opt_unq_name = self.model._optimizer._name + if opt_unq_name is None: + opt_unq_name = '' + + opt_cls_name = self.model._optimizer.__class__.__name__ + opt_name = opt_unq_name[: opt_unq_name.rfind("_")] # remove suffix idx + param_names = [param.name for param in self.model.network.parameters()] + for var_name, state_var in sorted( + optim_state.items(), key=lambda x: len(x[0]), reverse=True + ): + if var_name in ["@LR_DECAY_COUNTER@", "global_step"]: + # NOTE: dygraph saved global_step is 1 larger than that in + # static-graph, since the time of global_step to increase is + # different. + if var_name == "@LR_DECAY_COUNTER@": + converted_state["global_step"] = ( + np.array(converted_state.pop("@LR_DECAY_COUNTER@")) + 1 + ) + else: + # moment and other accumulators + # extend state dict to include promising dygraph names + for param_name in param_names: + if var_name.startswith(param_name + "_" + opt_name): + # when init optimizer with name + accum_name = var_name[ + len(param_name + "_" + opt_name + "_") : + ] + elif ( + var_name.startswith(param_name + "_") + and opt_name == opt_cls_name + ): + # when init optimizer without name + accum_name = var_name[len(param_name + "_") :] + else: + continue + # remove suffix idx + accum_name = accum_name[: accum_name.rfind("_")] + # state names always end with "_0" in dygraph because of the + # unique optimizer._name + dy_state_name = ( + param_name + + "_" + + opt_unq_name + + "_" + + accum_name + + "_0" + ) + converted_state[dy_state_name] = state_var + + if not hasattr(self.model._optimizer, 'set_state_dict'): + warnings.warn( + "paddle.fluid.optimizer is deprecated in API 2.0, please use paddle.optimizer instead." + ) + self.model._optimizer.set_dict(converted_state) + else: + self.model._optimizer.set_state_dict(converted_state) + + def prepare(self): + if ( + self._amp_level == "O2" + and self.model.mode == 'train' + and core.is_compiled_with_cuda() + ): + self.model.network, self.model._optimizer = paddle.amp.decorate( + models=self.model.network, + optimizers=self.model._optimizer, + level='O2', + ) + if self._amp_level != "O0": + self.model._scaler = None + + +class Model(object): + """ + + An Model object is network with training and inference features. + Dynamic graph and static graph are supported at the same time, + switched by `paddle.enable_static()`. The usage is as follows. + But note, the switching between dynamic and static should be before + instantiating a Model. The input description, i.e, paddle.static.InputSpec, + must be required for static graph. + + When training on GPU, auto mixed precision (AMP O1) and pure float16 + (AMP O2) training are both supported in static mode and dynamic mode. + In static graph mode, before training with pure float16 (AMP O2), + `multi_precision` could be set to True when creating optimizer, which can + avoid poor accuracy or slow convergence in a way, and inputs of dtype float + should be cast to float16 by users. `paddle.static.amp.fp16_guard` API + should be also used to limit the range of pure float16 training, otherwise, + 'use_fp16_guard' should be set to False by users. However, limiting the + range of is not supported during training using AMP. + + Args: + network (paddle.nn.Layer): The network is an instance of + paddle.nn.Layer. + inputs (InputSpec|list|tuple|dict|None, optional): `inputs`, entry points of network, + could be a InputSpec instance, or list/tuple of InputSpec instances, + or dict ({name: InputSpec}), and it couldn't be None in static + graph. Default: None. + labels (InputSpec|list|tuple|None, optional): `labels`, entry points of network, + could be a InputSpec instnace or list/tuple of InputSpec instances, + or None. For static graph, if labels is required in loss, + labels must be set. Otherwise, it could be None. Default: None. + + + Examples: + 1. A common example + + .. code-block:: python + :name: code-example1 + + import paddle + import paddle.nn as nn + import paddle.vision.transforms as T + from paddle.static import InputSpec + + device = paddle.set_device('cpu') # or 'gpu' + + net = nn.Sequential( + nn.Flatten(1), + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10)) + + # inputs and labels are not required for dynamic graph. + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + + model = paddle.Model(net, input, label) + optim = paddle.optimizer.SGD(learning_rate=1e-3, + parameters=model.parameters()) + + model.prepare(optim, + paddle.nn.CrossEntropyLoss(), + paddle.metric.Accuracy()) + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + data = paddle.vision.datasets.MNIST(mode='train', transform=transform) + model.fit(data, epochs=2, batch_size=32, verbose=1) + + + 2. An example using mixed precision training. + + .. code-block:: python + :name: code-example2 + + # required: gpu + import paddle + import paddle.nn as nn + import paddle.vision.transforms as T + + def run_example_code(): + device = paddle.set_device('gpu') + + net = nn.Sequential(nn.Flatten(1), nn.Linear(784, 200), nn.Tanh(), + nn.Linear(200, 10)) + + model = paddle.Model(net) + optim = paddle.optimizer.SGD(learning_rate=1e-3, parameters=model.parameters()) + + amp_configs = { + "level": "O1", + "custom_white_list": {'conv2d'}, + "use_dynamic_loss_scaling": True + } + model.prepare(optim, + paddle.nn.CrossEntropyLoss(), + paddle.metric.Accuracy(), + amp_configs=amp_configs) + + transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])]) + data = paddle.vision.datasets.MNIST(mode='train', transform=transform) + model.fit(data, epochs=2, batch_size=32, verbose=1) + + # mixed precision training is only supported on GPU now. + if paddle.is_compiled_with_cuda(): + run_example_code() + + """ + + def __init__(self, network, inputs=None, labels=None): + self.mode = 'train' + self.network = network + self._inputs = None + self._labels = None + self._loss = None + self._loss_weights = None + self._optimizer = None + self._input_info = None + self._is_shape_inferred = False + self._test_dataloader = None + self.stop_training = False + + if not _non_static_mode(): + if not isinstance(inputs, (list, tuple, dict, Input)): + raise TypeError( + "'inputs' must be list or tuple or dict, and couldn't be None." + ) + elif inputs: + self._input_info = _update_input_info(inputs) + + self._inputs = self._verify_spec(inputs, is_input=True) + self._labels = self._verify_spec(labels) + + # init backend + if fluid._non_static_mode(): + self._adapter = DynamicGraphAdapter(self) + else: + self._adapter = StaticGraphAdapter(self) + + def train_batch(self, inputs, labels=None, update=True): + """ + + Run one training step on one batch of data. And using `update` indicates + whether optimizer update gradients computing by this batch. + + Args: + inputs (numpy.ndarray|Tensor|list): Batch of input data. It could + be a numpy array or paddle.Tensor, or a list of arrays or + tensors (in case the model has multiple inputs). + labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be + a numpy array or paddle.Tensor, or a list of arrays or tensors + (in case the model has multiple labels). If has no labels, + set None. Default: None. + update (bool, optional): Whether update parameters after loss.backward() computing. + Set it to False to accumulate gradients. Default: True. + + Returns: + A list of scalar training loss if the model has no metrics, + or a tuple (list of scalar loss, list of metrics) if the model + set metrics. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.static import InputSpec + + device = paddle.set_device('cpu') # or 'gpu' + + net = nn.Sequential( + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10)) + + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + model = paddle.Model(net, input, label) + optim = paddle.optimizer.SGD(learning_rate=1e-3, + parameters=model.parameters()) + model.prepare(optim, paddle.nn.CrossEntropyLoss()) + data = paddle.rand((4, 784), dtype="float32") + label = paddle.randint(0, 10, (4, 1), dtype="int64") + loss = model.train_batch([data], [label]) + print(loss) + # [array([2.192784], dtype=float32)] + + """ + loss = self._adapter.train_batch(inputs, labels, update) + if fluid._non_static_mode() and self._input_info is None: + self._update_inputs() + return loss + + @no_grad() + def eval_batch(self, inputs, labels=None): + """ + + Run one evaluating step on a batch of data. + + Args: + inputs (numpy.ndarray|Tensor|list): Batch of input data. It could + be a numpy array or paddle.Tensor, or a list of arrays or + tensors (in case the model has multiple inputs). + labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be + a numpy array or paddle.Tensor, or a list of arrays or tensors + (in case the model has multiple labels). If has no labels, + set None. Default: None. + + Returns: + A list of scalar testing loss if the model has no metrics, + or a tuple (list of scalar loss, list of metrics) if the model + set metrics. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.static import InputSpec + + device = paddle.set_device('cpu') # or 'gpu' + + net = nn.Sequential( + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10)) + + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + model = paddle.Model(net, input, label) + optim = paddle.optimizer.SGD(learning_rate=1e-3, + parameters=model.parameters()) + model.prepare(optim, + paddle.nn.CrossEntropyLoss(), metrics=paddle.metric.Accuracy()) + data = paddle.rand((4, 784), dtype="float32") + label = paddle.randint(0, 10, (4, 1), dtype="int64") + loss, acc = model.eval_batch([data], [label]) + print(loss, acc) + # [array([2.8825705], dtype=float32)] [0.0] + + """ + loss = self._adapter.eval_batch(inputs, labels) + if fluid._non_static_mode() and self._input_info is None: + self._update_inputs() + return loss + + @no_grad() + def predict_batch(self, inputs): + """ + + Run one predicting step on a batch of data. + + Args: + inputs (numpy.ndarray|Tensor|list): Batch of input data. It could + be a numpy array or paddle.Tensor, or a list of arrays or + tensors (in case the model has multiple inputs). + + Returns: + A list of numpy.ndarray of predictions, that is the outputs + of Model forward. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.static import InputSpec + + device = paddle.set_device('cpu') # or 'gpu' + + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + + net = nn.Sequential( + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10), + nn.Softmax()) + + model = paddle.Model(net, input, label) + model.prepare() + data = paddle.rand((1, 784), dtype="float32") + out = model.predict_batch([data]) + print(out) + # [array([[0.08189095, 0.16740078, 0.06889386, 0.05085445, 0.10729759, + # 0.02217775, 0.14518553, 0.1591538 , 0.01808308, 0.17906217]], + # dtype=float32)] + + """ + loss = self._adapter.predict_batch(inputs) + if fluid._non_static_mode() and self._input_info is None: + self._update_inputs() + return loss + + def save(self, path, training=True): + """ + + This function saves parameters, optimizer information or model and + paramters only for inference to path. It depends on the parameter + `training`. + + If `training` is set to True, the parameters saved contain all + the trainable Variable, will save to a file with suffix ".pdparams". + The optimizer information contains all the variable used by optimizer. + For Adam optimizer, contains beta1, beta2, momentum etc. All the + information will save to a file with suffix ".pdopt". (If the optimizer + have no variable need to save (like SGD), the fill will not generated). + This function will silently overwrite existing file at the target location. + + If `training` is set to False, only inference model will be saved. + + Args: + path (str): The file prefix to save model. The format + is 'dirname/file_prefix' or 'file_prefix'. if empty str. + A exception will be raised. + training (bool, optional): Whether to save for training. If not, save + for inference only. Default: True. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + import paddle.vision.transforms as T + from paddle.static import InputSpec + + class Mnist(nn.Layer): + def __init__(self): + super(Mnist, self).__init__() + self.net = nn.Sequential( + nn.Flatten(1), + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10), + nn.Softmax()) + + def forward(self, x): + return self.net(x) + + dynamic = True # False + # if use static graph, do not set + if not dynamic: + paddle.enable_static() + + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + model = paddle.Model(Mnist(), input, label) + optim = paddle.optimizer.SGD(learning_rate=1e-3, + parameters=model.parameters()) + model.prepare(optim, paddle.nn.CrossEntropyLoss()) + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + data = paddle.vision.datasets.MNIST(mode='train', transform=transform) + + model.fit(data, epochs=1, batch_size=32, verbose=0) + model.save('checkpoint/test') # save for training + model.save('inference_model', False) # save for inference + + """ + + if ParallelEnv().local_rank == 0: + if not training: + self._save_inference_model(path) + else: + self._adapter.save(path) + + def load(self, path, skip_mismatch=False, reset_optimizer=False): + """ + + Load from files storing the model states and optimizer states. The file + for optimizer states is not necessary if no need to restore the optimizer. + + NOTE: parameters are retrieved out from the file storing model states + accoring to their structured names. + + For fine-tuning or transfer-learning models where some of the layers have + changed, keep parameters needed to restore have same structured names in + the pre-trained model and fine-tuning model. + + Args: + path (str): The prefix of files storing the model states and + optimizer states. The files would be `path.pdparams` and + `path.pdopt` separately, and the latter is not necessary + when no need to restore. + skip_mismatch (bool, optional): Whether to skip the loading of mismatch + parameter or raise an error when mismatch happens (not found + the parameter in file storing model states of or receives a + mismatch shape). Default: False. + reset_optimizer (bool, optional): If True, ignore the providing file storing + optimizer states and initialize optimizer states from scratch. + Otherwise, restore optimizer states from `path.pdopt` if + a optimizer has been set to the model. Default: False. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.static import InputSpec + + device = paddle.set_device('cpu') + + input = InputSpec([None, 784], 'float32', 'x') + + model = paddle.Model(nn.Sequential( + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10), + nn.Softmax()), input) + + model.save('checkpoint/test') + model.load('checkpoint/test') + + """ + + def _load_state_from_path(path): + if not os.path.exists(path): + return + with open(path, 'rb') as f: + return pickle.load(f, encoding='latin1') + + def _check_match(key, param): + state = param_state.get(key, None) + if state is None: + raise ValueError( + "{} is not found in the providing file.".format(key) + ) + if list(state.shape) != list(param.shape): + raise ValueError( + "{} receives a shape {}, but the expected shape is {}.".format( + key, list(state.shape), list(param.shape) + ) + ) + return param, state + + def _strip_postfix(path): + path, ext = os.path.splitext(path) + assert ext in [ + '', + '.pdparams', + '.pdopt', + '.pdmodel', + ], "Unknown postfix {} from weights".format(ext) + return path + + path = _strip_postfix(path) + param_state = _load_state_from_path(path + ".pdparams") + assert param_state, "Failed to load parameters, please check path." + + matched_param_state = [] + for key, param in self.network.state_dict().items(): + try: + match_res = _check_match(key, param) + except ValueError as err: + if skip_mismatch: + warnings.warn( + ("Skip loading for {}. ".format(key) + str(err)) + ) + # reset optimizer when mismatch happens + reset_optimizer = True + else: + raise err + matched_param_state.append(match_res) + + optim_state = ( + None if reset_optimizer else _load_state_from_path(path + ".pdopt") + ) + + # TODO: support save/load scaler state in static graph + if _non_static_mode(): + scaler_state = None + if hasattr(self, '_scaler') and self._scaler is not None: + if os.path.exists(path + '.pdscaler'): + scaler_state = paddle.load(path + '.pdscaler') + + return self._adapter.load( + matched_param_state, optim_state, scaler_state + ) + else: + return self._adapter.load(matched_param_state, optim_state) + + def parameters(self, *args, **kwargs): + """ + + Returns a list of parameters of the model. + + Returns: + A list of Parameter in static graph. + A list of ParamBase in dynamic graph. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.static import InputSpec + + input = InputSpec([None, 784], 'float32', 'x') + + model = paddle.Model(nn.Sequential( + nn.Linear(784, 200), + nn.Tanh(), + nn.Linear(200, 10)), input) + + params = model.parameters() + + """ + return self._adapter.parameters() + + def _prepare_amp(self, amp_configs): + def _check_pure_fp16_configs(): + # pure float16 training has some restricts now + if self._adapter._amp_level == "O2" and self._optimizer._grad_clip: + # clip by value is not supported + assert isinstance( + self._optimizer._grad_clip, + (paddle.nn.ClipGradByGlobalNorm, paddle.nn.ClipGradByNorm), + ), "Only GradientClipByNorm and GradientClipByGlobalNorm are supported in amp training with level=O2 currently." + + self._adapter._amp_custom_lists = {} + self._adapter._amp_configs = {} + + # check and get level of mixed precision training + if not amp_configs: + self._adapter._amp_level = 'O0' + return + elif isinstance(amp_configs, str): + if amp_configs not in ('O0', 'O1', 'O2'): + raise ValueError( + "The level of amp_configs should be 'O0', 'O1' or 'O2'." + ) + self._adapter._amp_level = amp_configs + _check_pure_fp16_configs() + return + else: + if 'level' not in amp_configs: + self._adapter._amp_level = 'O1' + elif amp_configs['level'] not in ('O0', 'O1', 'O2'): + raise ValueError( + "amp_configs['level'] should be 'O0', 'O1' or 'O2'." + ) + else: + self._adapter._amp_level = amp_configs['level'] + amp_config_key_set = set(amp_configs.keys()) - {'level'} + if not amp_config_key_set or self._adapter._amp_level == 'O0': + return + + if 'use_pure_fp16' in amp_configs: + raise ValueError( + "'use_pure_fp16' is an invalid parameter, the level of mixed precision training only depends on 'O1' or 'O2'." + ) + + _check_pure_fp16_configs() + + # construct amp_custom_lists + if self._adapter._amp_level != 'O0' and amp_config_key_set: + for param_name in [ + 'custom_white_list', + 'custom_black_list', + 'custom_black_varnames', + ]: + if param_name in amp_config_key_set: + self._adapter._amp_custom_lists[param_name] = amp_configs[ + param_name + ] + amp_config_key_set -= {param_name} + + def _check_amp_configs(amp_config_key_set): + accepted_param_set = { + 'init_loss_scaling', + 'incr_ratio', + 'decr_ratio', + 'incr_every_n_steps', + 'decr_every_n_nan_or_inf', + 'use_dynamic_loss_scaling', + 'use_fp16_guard', + } + if amp_config_key_set - accepted_param_set: + raise ValueError( + "Except for 'level', the keys of 'amp_configs' must be accepted by mixed precision APIs, but {} could not be recognized.".format( + tuple(amp_config_key_set - accepted_param_set) + ) + ) + + if 'use_fp16_guard' in amp_config_key_set: + if _non_static_mode(): + raise ValueError( + "'use_fp16_guard' is supported in static mode only." + ) + self._adapter._use_fp16_guard = amp_configs['use_fp16_guard'] + amp_config_key_set.remove('use_fp16_guard') + + return amp_config_key_set + + amp_configs_set = _check_amp_configs(amp_config_key_set) + for key in amp_configs_set: + self._adapter._amp_configs[key] = amp_configs[key] + + def prepare( + self, optimizer=None, loss=None, metrics=None, amp_configs=None + ): + """ + + Configures the model before runing. + + Args: + optimizer (Optimizer|None, optional): Optimizer must be set in training + and should be a Optimizer instance. It can be None in eval + and test mode. Default: None. + loss (Loss|Callable|None, optional): Loss function can + be a `paddle.nn.Layer` instance or any callable function + taken the predicted values and ground truth values as input. + It can be None when there is no loss. Default: None. + metrics (Metric|list[Metric]|None, optional): If metrics is set, all + metrics will be calculated and output in train/eval mode. Default: None. + amp_configs (str|dict|None, optional): AMP configurations. If AMP or pure + float16 training is used, the key 'level' of 'amp_configs' + should be set to 'O1' or 'O2' respectively. Otherwise, the + value of 'level' defaults to 'O0', which means float32 + training. In addition to 'level', parameters consistent with + mixed precision API could also be passed in. The supported + keys are: 'init_loss_scaling', 'incr_ratio', 'decr_ratio', + 'incr_every_n_steps', 'decr_every_n_nan_or_inf', + 'use_dynamic_loss_scaling', 'custom_white_list', + 'custom_black_list', and 'custom_black_varnames'or + 'use_fp16_guard' is only supported in static mode. Mixed + precision API documentations :ref:`api_paddle_amp_auto_cast` + and :ref:`api_paddle_amp_GradScaler` could be referenced + for details. For convenience, 'amp_configs' could be set to + 'O1' or 'O2' if no more parameters are needed. 'amp_configs' + could be None in float32 training. Default: None. + + Returns: + None + + """ + self._place = _get_device() + if isinstance(self._place, fluid.CUDAPlace): + global _parallel_context_initialized + if ParallelEnv().nranks > 1 and not _parallel_context_initialized: + if fluid._non_static_mode(): + main_prog_seed = fluid.default_main_program().random_seed + startup_prog_seed = ( + fluid.default_startup_program().random_seed + ) + fluid.disable_dygraph() + paddle.disable_static(self._place) + # enable_dygraph would create and switch to a new program, + # thus also copy seed to the new program + fluid.default_main_program().random_seed = main_prog_seed + fluid.default_startup_program().random_seed = ( + startup_prog_seed + ) + else: + prepare_distributed_context(self._place) + _parallel_context_initialized = True + + self._optimizer = optimizer + if loss is not None: + if not isinstance(loss, paddle.nn.Layer) and not callable(loss): + raise TypeError( + "'loss' must be sub classes of `paddle.nn.Layer` or any callable function." + ) + self._loss = loss + + metrics = metrics or [] + for metric in to_list(metrics): + assert isinstance( + metric, Metric + ), "{} is not sub class of Metric".format(metric.__class__.__name__) + self._metrics = to_list(metrics) + self._prepare_amp(amp_configs) + + self._adapter.prepare() + + def fit( + self, + train_data=None, + eval_data=None, + batch_size=1, + epochs=1, + eval_freq=1, + log_freq=10, + save_dir=None, + save_freq=1, + verbose=2, + drop_last=False, + shuffle=True, + num_workers=0, + callbacks=None, + accumulate_grad_batches=1, + num_iters=None, + ): + """ + + Trains the model for a fixed number of epochs. If `eval_data` is set, + evaluation will be done at the end of each epoch. + + Args: + train_data (Dataset|DataLoader, optional): An iterable data loader is used for + train. An instance of paddle paddle.io.Dataset or + paddle.io.Dataloader is recomended. Default: None. + eval_data (Dataset|DataLoader, optional): An iterable data loader is used for + evaluation at the end of epoch. If None, will not do evaluation. + An instance of paddle.io.Dataset or paddle.io.Dataloader + is recomended. Default: None. + batch_size (int, optional): The batch size of train_data and eval_data. When + train_data and eval_data are both the instance of Dataloader, this + parameter will be ignored. Default: 1. + epochs (int, optional): The number of epochs to train the model. Default: 1. + eval_freq (int, optional): The frequency, in number of epochs, an evalutation + is performed. Default: 1. + log_freq (int, optional): The frequency, in number of steps, the training logs + are printed. Default: 10. + save_dir(str|None, optional): The directory to save checkpoint during training. + If None, will not save checkpoint. Default: None. + save_freq (int, optional): The frequency, in number of epochs, to save + checkpoint. Default: 1. + verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent, + 1 = progress bar, 2 = one line per epoch. Default: 2. + drop_last (bool, optional): Whether drop the last incomplete batch of + train_data when dataset size is not divisible by the batch size. + When train_data is an instance of Dataloader, this parameter + will be ignored. Default: False. + shuffle (bool, optional): Whther to shuffle train_data. When train_data is + an instance of Dataloader, this parameter will be ignored. + Default: True. + num_workers (int, optional): The number of subprocess to load data, 0 for no + subprocess used and loading data in main process. + When train_data and eval_data are both the instance of + Dataloader, this parameter will be ignored. Default: 0. + callbacks (Callback|None, optional): A list of `Callback` instances to apply + during training. If None, :ref:`api_paddle_callbacks_ProgBarLogger` and + :ref:`api_paddle_callbacks_ModelCheckpoint` are automatically inserted. Default: None. + accumulate_grad_batches (int, optional): The number of batches to accumulate gradident + during training process before optimizer updates. It can mimic large batch + size. Default: 1. + num_iters (int|None, optional): The number of iterations to evaluate the model. + If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times. + Default: None. + + Returns: + None + + Examples: + 1. An example use Dataset and set batch size, shuffle in fit. + How to make a batch is done internally. + + .. code-block:: python + :name: code-example3 + + import paddle + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + from paddle.static import InputSpec + + dynamic = True + if not dynamic: + paddle.enable_static() + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + val_dataset = MNIST(mode='test', transform=transform) + + input = InputSpec([None, 1, 28, 28], 'float32', 'image') + label = InputSpec([None, 1], 'int64', 'label') + + model = paddle.Model( + paddle.vision.models.LeNet(), + input, label) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + paddle.nn.CrossEntropyLoss(), + paddle.metric.Accuracy(topk=(1, 2))) + model.fit(train_dataset, + val_dataset, + epochs=2, + batch_size=64, + save_dir='mnist_checkpoint') + + 2. An example use DataLoader, batch size and shuffle is set in + DataLoader. + + .. code-block:: python + :name: code-example4 + + import paddle + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + from paddle.static import InputSpec + + dynamic = True + if not dynamic: + paddle.enable_static() + + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + train_dataset = MNIST(mode='train', transform=transform) + train_loader = paddle.io.DataLoader(train_dataset, + batch_size=64) + val_dataset = MNIST(mode='test', transform=transform) + val_loader = paddle.io.DataLoader(val_dataset, + batch_size=64) + + input = InputSpec([None, 1, 28, 28], 'float32', 'image') + label = InputSpec([None, 1], 'int64', 'label') + + model = paddle.Model( + paddle.vision.models.LeNet(), input, label) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + paddle.nn.CrossEntropyLoss(), + paddle.metric.Accuracy(topk=(1, 2))) + model.fit(train_loader, + val_loader, + epochs=2, + save_dir='mnist_checkpoint') + + """ + assert train_data is not None, "train_data must be given!" + + if isinstance(train_data, Dataset): + train_sampler = DistributedBatchSampler( + train_data, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last, + ) + train_loader = DataLoader( + train_data, + batch_sampler=train_sampler, + places=self._place, + num_workers=num_workers, + return_list=True, + ) + else: + train_loader = train_data + + if eval_data is not None and isinstance(eval_data, Dataset): + eval_sampler = DistributedBatchSampler( + eval_data, batch_size=batch_size + ) + eval_loader = DataLoader( + eval_data, + batch_sampler=eval_sampler, + places=self._place, + num_workers=num_workers, + return_list=True, + ) + elif eval_data is not None: + eval_loader = eval_data + else: + eval_loader = None + + do_eval = eval_loader is not None + self._test_dataloader = eval_loader + + self._accumulate = accumulate_grad_batches + + steps = self._len_data_loader(train_loader) + self.num_iters = num_iters + if ( + num_iters is not None + and isinstance(num_iters, int) + and isinstance(steps, int) + ): + assert num_iters > 0, "num_iters must be greater than 0!" + epochs = (num_iters // steps) + 1 + steps = min(num_iters, steps) + cbks = config_callbacks( + callbacks, + model=self, + epochs=epochs, + steps=steps, + log_freq=log_freq, + save_freq=save_freq, + save_dir=save_dir, + verbose=verbose, + metrics=self._metrics_name(), + ) + + if any(isinstance(k, EarlyStopping) for k in cbks) and not do_eval: + warnings.warn("EarlyStopping needs validation data.") + + cbks.on_begin('train') + for epoch in range(epochs): + cbks.on_epoch_begin(epoch) + logs = self._run_one_epoch(train_loader, cbks, 'train') + cbks.on_epoch_end(epoch, logs) + + if do_eval and epoch % eval_freq == 0: + + eval_steps = self._len_data_loader(eval_loader) + cbks.on_begin( + 'eval', + {'steps': eval_steps, 'metrics': self._metrics_name()}, + ) + + eval_logs = self._run_one_epoch(eval_loader, cbks, 'eval') + + cbks.on_end('eval', eval_logs) + if self.stop_training: + break + + cbks.on_end('train', logs) + self._test_dataloader = None + + def evaluate( + self, + eval_data, + batch_size=1, + log_freq=10, + verbose=2, + num_workers=0, + callbacks=None, + num_iters=None, + ): + """ + Evaluate the loss and metrics of the model on input dataset. + + Args: + eval_data (Dataset|DataLoader): An iterable data loader is used for + evaluation. An instance of paddle.io.Dataset or + paddle.io.Dataloader is recomended. + batch_size (int, optional): The batch size of train_data and eval_data. + When eval_data is the instance of Dataloader, this argument will be + ignored. Default: 1. + log_freq (int, optional): The frequency, in number of steps, the eval logs + are printed. Default: 10. + verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent, + 1 = progress bar, 2 = one line per epoch. Default: 2. + num_workers (int, optional): The number of subprocess to load data, + 0 for no subprocess used and loading data in main process. When + train_data and eval_data are both the instance of Dataloader, + this parameter will be ignored. Default: 0. + callbacks (Callback|None, optional): A list of `Callback` instances to apply + during training. If None, `ProgBarLogger` and `ModelCheckpoint` + are automatically inserted. Default: None. + num_iters (int|None, optional): The number of iterations to evaluate the model. + If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times. + Default: None. + Returns: + dict: Result of metric. The key is the names of Metric, + value is a scalar or numpy.array. + + Examples: + + .. code-block:: python + + import paddle + import paddle.vision.transforms as T + from paddle.static import InputSpec + + # declarative mode + transform = T.Compose([ + T.Transpose(), + T.Normalize([127.5], [127.5]) + ]) + val_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform) + + input = InputSpec([-1, 1, 28, 28], 'float32', 'image') + label = InputSpec([None, 1], 'int64', 'label') + model = paddle.Model(paddle.vision.models.LeNet(), input, label) + model.prepare(metrics=paddle.metric.Accuracy()) + result = model.evaluate(val_dataset, batch_size=64) + print(result) + # {'acc': 0.0699} + """ + + if eval_data is not None and isinstance(eval_data, Dataset): + eval_sampler = DistributedBatchSampler( + eval_data, batch_size=batch_size + ) + eval_loader = DataLoader( + eval_data, + batch_sampler=eval_sampler, + places=self._place, + num_workers=num_workers, + return_list=True, + ) + else: + eval_loader = eval_data + + self._test_dataloader = eval_loader + + cbks = config_callbacks( + callbacks, + model=self, + log_freq=log_freq, + verbose=verbose, + metrics=self._metrics_name(), + ) + + eval_steps = self._len_data_loader(eval_loader) + self.num_iters = num_iters + if ( + num_iters is not None + and isinstance(num_iters, int) + and isinstance(eval_steps, int) + ): + assert num_iters > 0, "num_iters must be greater than 0!" + eval_steps = min(num_iters, eval_steps) + self.num_iters = eval_steps + cbks.on_begin( + 'eval', {'steps': eval_steps, 'metrics': self._metrics_name()} + ) + + logs = self._run_one_epoch(eval_loader, cbks, 'eval') + + cbks.on_end('eval', logs) + + self._test_dataloader = None + + eval_result = {} + for k in self._metrics_name(): + eval_result[k] = logs[k] + + return eval_result + + def predict( + self, + test_data, + batch_size=1, + num_workers=0, + stack_outputs=False, + verbose=1, + callbacks=None, + ): + """ + Compute the output predictions on testing data. + + Args: + test_data (Dataset|DataLoader): An iterable data loader is used for + predict. An instance of paddle.io.Dataset or paddle.io.Dataloader + is recomended. + batch_size (int, optional): The batch size of test_data. When test_data is the + instance of Dataloader, this argument will be ignored. Default: 1. + num_workers (int, optional): The number of subprocess to load data, 0 for no subprocess + used and loading data in main process. When test_data is the instance of Dataloader, + this argument will be ignored. Default: 0. + stack_outputs (bool, optional): Whether stack output field like a batch, as for an output + field of a sample is in shape [X, Y], test_data contains N samples, predict + output field will be in shape [N, X, Y] if stack_output is True, and will + be a length N list in shape [[X, Y], [X, Y], ..., [X, Y]] if stack_outputs + is False. stack_outputs as False is used for LoDTensor output situation, + it is recommended set as True if outputs contains no LoDTensor. Default: False. + verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent, + 1 = progress bar, 2 = one line per batch. Default: 1. + callbacks(Callback, optional): A Callback instance, Default: None. + + Returns: + list: output of models. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + from paddle.static import InputSpec + + class MnistDataset(paddle.vision.datasets.MNIST): + def __init__(self, mode, return_label=True): + super(MnistDataset, self).__init__(mode=mode) + self.return_label = return_label + + def __getitem__(self, idx): + img = np.reshape(self.images[idx], [1, 28, 28]) + if self.return_label: + return img, np.array(self.labels[idx]).astype('int64') + return img, + + def __len__(self): + return len(self.images) + + test_dataset = MnistDataset(mode='test', return_label=False) + + # imperative mode + input = InputSpec([-1, 1, 28, 28], 'float32', 'image') + model = paddle.Model(paddle.vision.models.LeNet(), input) + model.prepare() + result = model.predict(test_dataset, batch_size=64) + print(len(result[0]), result[0][0].shape) + # 157 (64, 10) + + # declarative mode + device = paddle.set_device('cpu') + paddle.enable_static() + input = InputSpec([-1, 1, 28, 28], 'float32', 'image') + model = paddle.Model(paddle.vision.models.LeNet(), input) + model.prepare() + + result = model.predict(test_dataset, batch_size=64) + print(len(result[0]), result[0][0].shape) + # 157 (64, 10) + """ + + if test_data is not None and isinstance(test_data, Dataset): + test_sampler = DistributedBatchSampler( + test_data, batch_size=batch_size + ) + test_loader = DataLoader( + test_data, + batch_sampler=test_sampler, + places=self._place, + num_workers=num_workers, + return_list=True, + ) + else: + test_loader = test_data + + self._test_dataloader = test_loader + + cbks = config_callbacks(callbacks, model=self, verbose=verbose) + + test_steps = self._len_data_loader(test_loader) + logs = {'steps': test_steps} + + cbks.on_begin('predict', logs) + + outputs = [] + + logs, outputs = self._run_one_epoch(test_loader, cbks, 'predict') + + outputs = list(zip(*outputs)) + + # NOTE: for lod tensor output, we should not stack outputs + # for stacking may lose its detail info + if stack_outputs: + outputs = [np.vstack(outs) for outs in outputs] + + self._test_dataloader = None + + cbks.on_end('predict', logs) + return outputs + + def _save_inference_model(self, path): + """ + Save inference model can be used in static or dynamic mode. + + Args: + path (str): The path prefix to save model. The format is + ``dirname/file_prefix`` or ``file_prefix``. + Returns: + None + """ + + if fluid._non_static_mode(): + with fluid.framework._dygraph_guard(None): + layer = self.network + if self._input_info is None: # No provided or inferred + raise RuntimeError( + "Saving inference model needs 'inputs' or running before saving. Please specify 'inputs' in Model initialization or input training data and perform a training for shape derivation." + ) + if self._is_shape_inferred: + warnings.warn( + "'inputs' was not specified when Model initialization, so the input shape to be saved will be the shape derived from the user's actual inputs. The input shape to be saved is %s. For saving correct input shapes, please provide 'inputs' for Model initialization." + % self._input_info[0] + ) + + paddle.jit.save(layer, path, input_spec=self._inputs) + + else: + # path check + file_prefix = os.path.basename(path) + if file_prefix == "": + raise ValueError( + "The input path MUST be format of dirname/file_prefix " + "[dirname\\file_prefix in Windows system], but received " + "file_prefix is empty string." + ) + + dirname = os.path.dirname(path) + if dirname and not os.path.exists(dirname): + os.makedirs(dirname) + + model_path = dirname + model_filename = file_prefix + INFER_MODEL_SUFFIX + params_filename = file_prefix + INFER_PARAMS_SUFFIX + + prog = self._adapter._progs.get('test', None) + assert ( + prog + ), "Model is not ready, please call `model.prepare()` first" + + infer_prog = prog.clone(for_test=True) + + input_names = [v.name for v in self._adapter._input_vars['test']] + endpoints = self._adapter._endpoints['test']['output'] + + fluid.io.save_inference_model( + model_path, + input_names, + endpoints, + self._adapter._executor, + main_program=infer_prog, + model_filename=model_filename, + params_filename=params_filename, + ) + + def _run_one_epoch( + self, + data_loader, + callbacks, + mode, + logs={}, + ): + outputs = [] + for step, data in enumerate(data_loader): + # data might come from different types of data_loader and have + # different format, as following: + # 1. DataLoader in static graph: + # [[input1, input2, ..., label1, lable2, ...]] + # 2. DataLoader in dygraph + # [input1, input2, ..., label1, lable2, ...] + # 3. custumed iterator yield concated inputs and labels: + # [input1, input2, ..., label1, lable2, ...] + # 4. custumed iterator yield separated inputs and labels: + # ([input1, input2, ...], [label1, lable2, ...]) + # To handle all of these, flatten (nested) list to list. + data = flatten(data) + # LoDTensor.shape is callable, where LoDTensor comes from + # DataLoader in static graph + + batch_size = ( + data[0].shape()[0] + if callable(data[0].shape) + else data[0].shape[0] + ) + + callbacks.on_batch_begin(mode, step, logs) + + if mode != 'predict': + _inputs = [data[: len(self._inputs)], data[len(self._inputs) :]] + if mode == 'train': + _inputs.append( + (step + 1) % self._accumulate == 0 + or step + 1 == len(data_loader) + ) + + outs = getattr(self, mode + '_batch')(*_inputs) + + if self._metrics and self._loss: + metrics = [[l[0] for l in outs[0]]] + elif self._loss: + metrics = [[l[0] for l in outs]] + else: + metrics = [] + + # metrics + for metric in self._metrics: + res = metric.accumulate() + metrics.extend(to_list(res)) + + assert len(self._metrics_name()) == len(metrics) + for k, v in zip(self._metrics_name(), metrics): + logs[k] = v + else: + if self._inputs is not None: + outs = self.predict_batch(data[: len(self._inputs)]) + else: + outs = self.predict_batch(data) + + outputs.append(outs) + + logs['step'] = step + if ( + mode == 'train' + or self._adapter._merge_count.get(mode + '_batch', 0) <= 0 + ): + logs['batch_size'] = batch_size * ParallelEnv().nranks + else: + logs['batch_size'] = self._adapter._merge_count[mode + '_batch'] + + callbacks.on_batch_end(mode, step, logs) + if hasattr(self, 'num_iters') and self.num_iters is not None: + self.num_iters -= 1 + if self.num_iters <= 0: + self.stop_training = True + del self.num_iters + break + self._reset_metrics() + + if mode == 'predict': + return logs, outputs + return logs + + def summary(self, input_size=None, dtype=None): + """Prints a string summary of the network. + + Args: + input_size (tuple|InputSpec|list[tuple|InputSpec], optional): size of input tensor. + if not set, input_size will get from ``self._inputs`` if network only have + one input, input_size can be tuple or InputSpec. if model have multiple + input, input_size must be a list which contain every input's shape. + Default: None. + dtype (str, optional): if dtype is None, 'float32' will be used, Default: None. + + Returns: + Dict: a summary of the network including total params and total trainable params. + + Examples: + .. code-block:: python + + import paddle + from paddle.static import InputSpec + + input = InputSpec([None, 1, 28, 28], 'float32', 'image') + label = InputSpec([None, 1], 'int64', 'label') + + model = paddle.Model(paddle.vision.models.LeNet(), + input, label) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + paddle.nn.CrossEntropyLoss()) + + params_info = model.summary() + print(params_info) + # {'total_params': 61610, 'trainable_params': 61610} + + """ + assert ( + input_size is not None or self._inputs is not None + ), "'input_size' or 'self._input' must be set" + if input_size is not None: + _input_size = input_size + else: + _input_size = self._inputs + return summary(self.network, _input_size, dtypes=dtype) + + def _verify_spec(self, specs, shapes=None, dtypes=None, is_input=False): + out_specs = [] + + if specs is None: + # Note(Aurelius84): If not specific specs of `Input`, using argument names of `forward` function + # to generate `Input`. But how can we know the actual shape of each input tensor? + + if is_input: + arg_names = extract_args(self.network.forward)[1:] + # While Saving inference model in dygraph, and providing inputs only in running. + if ( + shapes is not None + and dtypes is not None + and fluid._non_static_mode() + ): + out_specs = [ + Input(name=n, dtype=dtypes[i], shape=shapes[i]) + for i, n in enumerate(arg_names) + ] + else: + out_specs = [Input(name=n, shape=[None]) for n in arg_names] + else: + out_specs = to_list(specs) + elif isinstance(specs, dict): + assert is_input is False + out_specs = [ + specs[n] + for n in extract_args(self.network.forward) + if n != 'self' + ] + else: + out_specs = to_list(specs) + # Note: checks each element has specificed `name`. + if out_specs is not None: + for i, spec in enumerate(out_specs): + assert isinstance(spec, Input) + if spec.name is None: + raise ValueError( + "Requires Input[{}].name != None, but receive `None` with {}.".format( + i, spec + ) + ) + + return out_specs + + def _reset_metrics(self): + for metric in self._metrics: + metric.reset() + + def _metrics_name(self): + metrics_name = ['loss'] if self._loss else [] + for m in self._metrics: + metrics_name.extend(to_list(m.name())) + return metrics_name + + def _len_data_loader(self, data_loader): + try: + steps = len(data_loader) + except Exception: + steps = None + return steps + + def _update_inputs(self): + "Update self._inputs according to given inputs." + self._input_info = self._adapter._input_info + if self._input_info is not None and len(self._input_info) == 2: + self._inputs = self._verify_spec( + None, self._input_info[0], self._input_info[1], True + ) + self._is_shape_inferred = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model_summary.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..26bf28ed10afdfa364a17c4cd722a188e9e19989 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/model_summary.py @@ -0,0 +1,467 @@ +# 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. + +import warnings +import numpy as np +import numbers + +import paddle +import paddle.nn as nn +from paddle.static import InputSpec +from paddle.autograd import no_grad +from collections import OrderedDict + +__all__ = [] + + +def summary(net, input_size=None, dtypes=None, input=None): + """Prints a string summary of the network. + + Args: + net (Layer): the network which must be a subinstance of Layer. + input_size (tuple|InputSpec|list[tuple|InputSpec], optional): size of input tensor. if model only + have one input, input_size can be tuple or InputSpec. if model + have multiple input, input_size must be a list which contain + every input's shape. Note that input_size only dim of + batch_size can be None or -1. Default: None. Note that + input_size and input cannot be None at the same time. + dtypes (str, optional): if dtypes is None, 'float32' will be used, Default: None. + input: the input tensor. if input is given, input_size and dtype will be ignored, Default: None. + + Returns: + Dict: a summary of the network including total params and total trainable params. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + class LeNet(nn.Layer): + def __init__(self, num_classes=10): + super(LeNet, self).__init__() + self.num_classes = num_classes + self.features = nn.Sequential( + nn.Conv2D( + 1, 6, 3, stride=1, padding=1), + nn.ReLU(), + nn.MaxPool2D(2, 2), + nn.Conv2D( + 6, 16, 5, stride=1, padding=0), + nn.ReLU(), + nn.MaxPool2D(2, 2)) + + if num_classes > 0: + self.fc = nn.Sequential( + nn.Linear(400, 120), + nn.Linear(120, 84), + nn.Linear( + 84, 10)) + + def forward(self, inputs): + x = self.features(inputs) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x) + return x + + lenet = LeNet() + + params_info = paddle.summary(lenet, (1, 1, 28, 28)) + print(params_info) + + # multi input demo + class LeNetMultiInput(LeNet): + + def forward(self, inputs, y): + x = self.features(inputs) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x + y) + return x + + lenet_multi_input = LeNetMultiInput() + + params_info = paddle.summary(lenet_multi_input, [(1, 1, 28, 28), (1, 400)], + dtypes=['float32', 'float32']) + print(params_info) + + # list input demo + class LeNetListInput(LeNet): + + def forward(self, inputs): + x = self.features(inputs[0]) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x + inputs[1]) + return x + + lenet_list_input = LeNetListInput() + input_data = [paddle.rand([1, 1, 28, 28]), paddle.rand([1, 400])] + params_info = paddle.summary(lenet_list_input, input=input_data) + print(params_info) + + # dict input demo + class LeNetDictInput(LeNet): + + def forward(self, inputs): + x = self.features(inputs['x1']) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x + inputs['x2']) + return x + + lenet_dict_input = LeNetDictInput() + input_data = {'x1': paddle.rand([1, 1, 28, 28]), + 'x2': paddle.rand([1, 400])} + params_info = paddle.summary(lenet_dict_input, input=input_data) + print(params_info) + + """ + if input_size is None and input is None: + raise ValueError("input_size and input cannot be None at the same time") + + if input_size is None and input is not None: + if paddle.is_tensor(input): + input_size = tuple(input.shape) + elif isinstance(input, (list, tuple)): + input_size = [] + for x in input: + input_size.append(tuple(x.shape)) + elif isinstance(input, dict): + input_size = [] + for key in input.keys(): + input_size.append(tuple(input[key].shape)) + elif isinstance(input, paddle.fluid.framework.Variable): + input_size = tuple(input.shape) + else: + raise ValueError( + "Input is not tensor, list, tuple and dict, unable to determine input_size, please input input_size." + ) + + if isinstance(input_size, InputSpec): + _input_size = tuple(input_size.shape) + elif isinstance(input_size, list): + _input_size = [] + for item in input_size: + if isinstance(item, int): + item = (item, ) + assert isinstance(item, + (tuple, InputSpec)), 'When input_size is list, \ + expect item in input_size is a tuple or InputSpec, but got {}'.format( + type(item)) + + if isinstance(item, InputSpec): + _input_size.append(tuple(item.shape)) + else: + _input_size.append(item) + elif isinstance(input_size, int): + _input_size = (input_size, ) + else: + _input_size = input_size + + if not paddle.in_dynamic_mode(): + warnings.warn( + "Your model was created in static mode, this may not get correct summary information!" + ) + in_train_mode = False + else: + in_train_mode = net.training + + if in_train_mode: + net.eval() + + def _is_shape(shape): + for item in shape: + if isinstance(item, (list, tuple)): + return False + return True + + def _check_shape(shape): + num_unknown = 0 + new_shape = [] + for i in range(len(shape)): + item = shape[i] + if item is None or item == -1: + num_unknown += 1 + if num_unknown > 1: + raise ValueError( + 'Option input_size only the dim of batch_size can be None or -1.' + ) + item = 1 + elif isinstance(item, numbers.Number): + if item <= 0: + raise ValueError( + "Expected element in input size greater than zero, but got {}" + .format(item)) + new_shape.append(item) + return tuple(new_shape) + + def _check_input(input_size): + if isinstance(input_size, (list, tuple)) and _is_shape(input_size): + return _check_shape(input_size) + else: + return [_check_input(i) for i in input_size] + + _input_size = _check_input(_input_size) + + result, params_info = summary_string(net, _input_size, dtypes, input) + print(result) + + if in_train_mode: + net.train() + + return params_info + + +@no_grad() +def summary_string(model, input_size=None, dtypes=None, input=None): + + def _all_is_numper(items): + for item in items: + if not isinstance(item, numbers.Number): + return False + return True + + def _build_dtypes(input_size, dtype): + if dtype is None: + dtype = 'float32' + + if isinstance(input_size, (list, tuple)) and _all_is_numper(input_size): + return [dtype] + else: + return [_build_dtypes(i, dtype) for i in input_size] + + if not isinstance(dtypes, (list, tuple)): + dtypes = _build_dtypes(input_size, dtypes) + + batch_size = 1 + + summary_str = '' + + depth = len(list(model.sublayers())) + + def _get_shape_from_tensor(x): + if isinstance(x, (paddle.fluid.Variable, paddle.fluid.core.VarBase)): + return list(x.shape) + elif isinstance(x, (list, tuple)): + return [_get_shape_from_tensor(xx) for xx in x] + + def _get_output_shape(output): + if isinstance(output, (list, tuple)): + output_shape = [_get_output_shape(o) for o in output] + elif hasattr(output, 'shape'): + output_shape = list(output.shape) + else: + output_shape = [] + return output_shape + + def register_hook(layer): + + def hook(layer, input, output): + class_name = str(layer.__class__).split(".")[-1].split("'")[0] + + try: + layer_idx = int(layer._full_name.split('_')[-1]) + except: + layer_idx = len(summary) + + m_key = "%s-%i" % (class_name, layer_idx + 1) + summary[m_key] = OrderedDict() + + try: + summary[m_key]["input_shape"] = _get_shape_from_tensor(input) + except: + warnings.warn('Get layer {} input shape failed!') + summary[m_key]["input_shape"] = [] + + try: + summary[m_key]["output_shape"] = _get_output_shape(output) + except: + warnings.warn('Get layer {} output shape failed!') + summary[m_key]["output_shape"] + + params = 0 + + if paddle.in_dynamic_mode(): + layer_state_dict = layer._parameters + else: + layer_state_dict = layer.state_dict() + + summary[m_key]["trainable_params"] = 0 + trainable_flag = False + for k, v in layer_state_dict.items(): + params += np.prod(v.shape) + + try: + if (getattr(getattr(layer, k), 'trainable')) and ( + not getattr(getattr(layer, k), 'stop_gradient')): + summary[m_key]["trainable_params"] += np.prod(v.shape) + summary[m_key]["trainable"] = True + trainable_flag = True + elif not trainable_flag: + summary[m_key]["trainable"] = False + except: + summary[m_key]["trainable"] = True + + summary[m_key]["nb_params"] = params + + if (not isinstance(layer, nn.Sequential) + and not isinstance(layer, nn.LayerList) + and (not (layer == model) or depth < 1)): + + hooks.append(layer.register_forward_post_hook(hook)) + # For rnn, gru and lstm layer + elif hasattr(layer, 'could_use_cudnn') and layer.could_use_cudnn: + hooks.append(layer.register_forward_post_hook(hook)) + + if isinstance(input_size, tuple): + input_size = [input_size] + + def build_input(input_size, dtypes): + if isinstance(input_size, (list, tuple)) and _all_is_numper(input_size): + if isinstance(dtypes, (list, tuple)): + dtype = dtypes[0] + else: + dtype = dtypes + return paddle.cast(paddle.rand(list(input_size)), dtype) + else: + return [ + build_input(i, dtype) for i, dtype in zip(input_size, dtypes) + ] + + # create properties + summary = OrderedDict() + hooks = [] + # register hook + model.apply(register_hook) + if input is not None: + x = input + model(x) + else: + x = build_input(input_size, dtypes) + # make a forward pass + model(*x) + + # remove these hooks + for h in hooks: + h.remove() + + def _get_str_length(summary): + head_length = { + 'layer_width': 15, + 'input_shape_width': 20, + 'output_shape_width': 20, + 'params_width': 15, + 'table_width': 75 + } + + for layer in summary: + if head_length['output_shape_width'] < len( + str(summary[layer]["output_shape"])): + head_length['output_shape_width'] = len( + str(summary[layer]["output_shape"])) + if head_length['input_shape_width'] < len( + str(summary[layer]["input_shape"])): + head_length['input_shape_width'] = len( + str(summary[layer]["input_shape"])) + if head_length['layer_width'] < len(str(layer)): + head_length['layer_width'] = len(str(layer)) + if head_length['params_width'] < len( + str(summary[layer]["nb_params"])): + head_length['params_width'] = len( + str(summary[layer]["nb_params"])) + + _temp_width = 0 + for k, v in head_length.items(): + if k != 'table_width': + _temp_width += v + + if head_length['table_width'] < _temp_width + 5: + head_length['table_width'] = _temp_width + 5 + + return head_length + + table_width = _get_str_length(summary) + + summary_str += "-" * table_width['table_width'] + "\n" + line_new = "{:^{}} {:^{}} {:^{}} {:^{}}".format( + "Layer (type)", table_width['layer_width'], "Input Shape", + table_width['input_shape_width'], "Output Shape", + table_width['output_shape_width'], "Param #", + table_width['params_width']) + summary_str += line_new + "\n" + summary_str += "=" * table_width['table_width'] + "\n" + total_params = 0 + total_output = 0 + trainable_params = 0 + max_length = 0 + for layer in summary: + # input_shape, output_shape, trainable, nb_params + line_new = "{:^{}} {:^{}} {:^{}} {:^{}}".format( + layer, table_width['layer_width'], + str(summary[layer]["input_shape"]), + table_width['input_shape_width'], + str(summary[layer]["output_shape"]), + table_width['output_shape_width'], "{0:,}".format( + summary[layer]["nb_params"]), table_width['params_width']) + total_params += summary[layer]["nb_params"] + + try: + total_output += np.sum( + np.prod(summary[layer]["output_shape"], axis=-1)) + except: + for output_shape in summary[layer]["output_shape"]: + total_output += np.sum(np.prod(output_shape, axis=-1)) + + if "trainable" in summary[layer]: + if summary[layer]["trainable"] == True: + trainable_params += summary[layer]["trainable_params"] + summary_str += line_new + "\n" + + def _get_input_size(input_size, size): + if isinstance(input_size, (list, tuple)) and _all_is_numper(input_size): + size = abs(np.prod(input_size) * 4. / (1024**2.)) + else: + size = sum([_get_input_size(i, size) for i in input_size]) + return size + + total_input_size = _get_input_size(input_size, 0) + + total_output_size = abs(2. * total_output * 4. / + (1024**2.)) # x2 for gradients + total_params_size = abs(total_params * 4. / (1024**2.)) + total_size = total_params_size + total_output_size + total_input_size + + summary_str += "=" * table_width['table_width'] + "\n" + summary_str += "Total params: {0:,}".format(total_params) + "\n" + summary_str += "Trainable params: {0:,}".format(trainable_params) + "\n" + summary_str += "Non-trainable params: {0:,}".format(total_params - + trainable_params) + "\n" + summary_str += "-" * table_width['table_width'] + "\n" + summary_str += "Input size (MB): %0.2f" % total_input_size + "\n" + summary_str += "Forward/backward pass size (MB): %0.2f" % total_output_size + "\n" + summary_str += "Params size (MB): %0.2f" % total_params_size + "\n" + summary_str += "Estimated Total Size (MB): %0.2f" % total_size + "\n" + summary_str += "-" * table_width['table_width'] + "\n" + + # return summary + return summary_str, { + 'total_params': total_params, + 'trainable_params': trainable_params + } diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/progressbar.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/progressbar.py new file mode 100644 index 0000000000000000000000000000000000000000..58dfdef604e7c54f019a393098bdee9098f7225d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/progressbar.py @@ -0,0 +1,211 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +import time +import numpy as np +import struct +from collections import namedtuple + +__all__ = [] + + +class ProgressBar(object): + """progress bar """ + + def __init__(self, + num=None, + width=30, + verbose=1, + start=True, + file=sys.stdout, + name='step'): + self._num = num + if isinstance(num, int) and num <= 0: + raise TypeError('num should be None or integer (> 0)') + max_width = self._get_max_width() + self._width = width if width <= max_width else max_width + self._total_width = 0 + self._verbose = verbose + self.file = file + self._values = {} + self._values_order = [] + if start: + self._start = time.time() + self._last_update = 0 + self.name = name + + self._dynamic_display = ((hasattr(self.file, 'isatty') + and self.file.isatty()) + or 'ipykernel' in sys.modules + or 'posix' in sys.modules + or 'PYCHARM_HOSTED' in os.environ) + + def _get_max_width(self): + if sys.version_info > (3, 3): + from shutil import get_terminal_size + else: + try: + from backports.shutil_get_terminal_size import get_terminal_size + except: + + def get_terminal_size(): + terminal_size = namedtuple("terminal_size", "columns lines") + return terminal_size(80, 24) + + terminal_width, _ = get_terminal_size() + terminal_width = terminal_width if terminal_width > 0 else 80 + max_width = min(int(terminal_width * 0.6), terminal_width - 50) + return max_width + + def start(self): + self.file.flush() + self._start = time.time() + + def update(self, current_num, values={}): + now = time.time() + + def convert_uint16_to_float(in_list): + in_list = np.asarray(in_list) + out = np.vectorize( + lambda x: struct.unpack('= 1 or time_per_unit == 0: + fps = ' - %.0fs/%s' % (time_per_unit, self.name) + elif time_per_unit >= 1e-3: + fps = ' - %.0fms/%s' % (time_per_unit * 1e3, self.name) + else: + fps = ' - %.0fus/%s' % (time_per_unit * 1e6, self.name) + + info = '' + if self._verbose == 1: + prev_total_width = self._total_width + + if self._dynamic_display: + sys.stdout.write('\b' * prev_total_width) + sys.stdout.write('\r') + else: + sys.stdout.write('\n') + + if self._num is not None: + numdigits = int(np.log10(self._num)) + 1 + + bar_chars = (self.name + ' %' + str(numdigits) + + 'd/%d [') % (current_num, self._num) + prog = float(current_num) / self._num + prog_width = int(self._width * prog) + + if prog_width > 0: + bar_chars += ('=' * (prog_width - 1)) + if current_num < self._num: + bar_chars += '>' + else: + bar_chars += '=' + bar_chars += ('.' * (self._width - prog_width)) + bar_chars += ']' + else: + bar_chars = self.name + ' %3d' % current_num + + self._total_width = len(bar_chars) + sys.stdout.write(bar_chars) + + for k, val in values: + info += ' - %s:' % k + val = val if isinstance(val, list) else [val] + for i, v in enumerate(val): + if isinstance(v, (float, np.float32, np.float64)): + if abs(v) > 1e-3: + info += ' %.4f' % v + else: + info += ' %.4e' % v + else: + info += ' %s' % v + + if self._num is not None and current_num < self._num: + eta = time_per_unit * (self._num - current_num) + if eta > 3600: + eta_format = '%d:%02d:%02d' % (eta // 3600, + (eta % 3600) // 60, eta % 60) + elif eta > 60: + eta_format = '%d:%02d' % (eta // 60, eta % 60) + else: + eta_format = '%ds' % eta + + info += ' - ETA: %s' % eta_format + + info += fps + self._total_width += len(info) + if prev_total_width > self._total_width: + info += (' ' * (prev_total_width - self._total_width)) + + # newline for another epoch + if self._num is not None and current_num >= self._num: + info += '\n' + if self._num is None: + info += '\n' + + sys.stdout.write(info) + sys.stdout.flush() + self._last_update = now + elif self._verbose == 2 or self._verbose == 3: + if self._num: + numdigits = int(np.log10(self._num)) + 1 + count = (self.name + ' %' + str(numdigits) + + 'd/%d') % (current_num, self._num) + else: + count = self.name + ' %3d' % current_num + info = count + info + + for k, val in values: + info += ' - %s:' % k + val = val if isinstance(val, list) else [val] + for v in val: + if isinstance(v, (float, np.float32, np.float64)): + if abs(v) > 1e-3: + info += ' %.4f' % v + else: + info += ' %.4e' % v + elif isinstance(v, np.ndarray) and \ + v.size == 1 and \ + v.dtype in [np.float32, np.float64]: + if abs(v[0]) > 1e-3: + info += ' %.4f' % v[0] + else: + info += ' %.4e' % v[0] + else: + info += ' %s' % v + + info += fps + info += '\n' + sys.stdout.write(info) + sys.stdout.flush() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/static_flops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/static_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..297199b7326a9b11ad8cd2b5e42cb2bc41b6022f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hapi/static_flops.py @@ -0,0 +1,259 @@ +# 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. + +import copy +import numpy as np +import paddle +from collections import OrderedDict +from paddle.static import Program, program_guard, Variable + +__all__ = [] + + +class VarWrapper(object): + + def __init__(self, var, graph): + assert isinstance(var, Variable) + assert isinstance(graph, GraphWrapper) + self._var = var + self._graph = graph + + def name(self): + """ + Get the name of the variable. + """ + return self._var.name + + def shape(self): + """ + Get the shape of the varibale. + """ + return self._var.shape + + +class OpWrapper(object): + + def __init__(self, op, graph): + assert isinstance(graph, GraphWrapper) + self._op = op + self._graph = graph + + def type(self): + """ + Get the type of this operator. + """ + return self._op.type + + def inputs(self, name): + """ + Get all the varibales by the input name. + """ + if name in self._op.input_names: + return [ + self._graph.var(var_name) for var_name in self._op.input(name) + ] + else: + return [] + + def outputs(self, name): + """ + Get all the varibales by the output name. + """ + return [self._graph.var(var_name) for var_name in self._op.output(name)] + + +class GraphWrapper(object): + """ + It is a wrapper of paddle.fluid.framework.IrGraph with some special functions + for paddle slim framework. + + Args: + program(framework.Program): A program with + in_nodes(dict): A dict to indicate the input nodes of the graph. + The key is user-defined and human-readable name. + The value is the name of Variable. + out_nodes(dict): A dict to indicate the input nodes of the graph. + The key is user-defined and human-readable name. + The value is the name of Variable. + """ + + def __init__(self, program=None, in_nodes=[], out_nodes=[]): + """ + """ + super(GraphWrapper, self).__init__() + self.program = Program() if program is None else program + self.persistables = {} + self.teacher_persistables = {} + for var in self.program.list_vars(): + if var.persistable: + self.persistables[var.name] = var + self.compiled_graph = None + in_nodes = [] if in_nodes is None else in_nodes + out_nodes = [] if out_nodes is None else out_nodes + self.in_nodes = OrderedDict(in_nodes) + self.out_nodes = OrderedDict(out_nodes) + self._attrs = OrderedDict() + + def ops(self): + """ + Return all operator nodes included in the graph as a set. + """ + ops = [] + for block in self.program.blocks: + for op in block.ops: + ops.append(OpWrapper(op, self)) + return ops + + def var(self, name): + """ + Get the variable by variable name. + """ + for block in self.program.blocks: + if block.has_var(name): + return VarWrapper(block.var(name), self) + return None + + +def count_convNd(op): + filter_shape = op.inputs("Filter")[0].shape() + filter_ops = np.product(filter_shape[1:]) + bias_ops = 1 if len(op.inputs("Bias")) > 0 else 0 + output_numel = np.product(op.outputs("Output")[0].shape()[1:]) + total_ops = output_numel * (filter_ops + bias_ops) + total_ops = abs(total_ops) + return total_ops + + +def count_leaky_relu(op): + total_ops = np.product(op.outputs("Output")[0].shape()[1:]) + return total_ops + + +def count_bn(op): + output_numel = np.product(op.outputs("Y")[0].shape()[1:]) + total_ops = 2 * output_numel + total_ops = abs(total_ops) + return total_ops + + +def count_linear(op): + total_mul = op.inputs("Y")[0].shape()[0] + numel = np.product(op.outputs("Out")[0].shape()[1:]) + total_ops = total_mul * numel + total_ops = abs(total_ops) + return total_ops + + +def count_pool2d(op): + input_shape = op.inputs("X")[0].shape() + output_shape = op.outputs('Out')[0].shape() + kernel = np.array(input_shape[2:]) // np.array(output_shape[2:]) + total_add = np.product(kernel) + total_div = 1 + kernel_ops = total_add + total_div + num_elements = np.product(output_shape[1:]) + total_ops = kernel_ops * num_elements + total_ops = abs(total_ops) + return total_ops + + +def count_element_op(op): + input_shape = op.inputs("X")[0].shape() + total_ops = np.product(input_shape[1:]) + total_ops = abs(total_ops) + return total_ops + + +def _graph_flops(graph, detail=False): + assert isinstance(graph, GraphWrapper) + flops = 0 + op_flops = 0 + table = Table(["OP Type", 'Param name', "Flops"]) + for op in graph.ops(): + param_name = '' + if op.type() in ['conv2d', 'depthwise_conv2d']: + op_flops = count_convNd(op) + flops += op_flops + param_name = op.inputs("Filter")[0].name() + elif op.type() == 'pool2d': + op_flops = count_pool2d(op) + flops += op_flops + + elif op.type() in ['mul', 'matmul']: + op_flops = count_linear(op) + flops += op_flops + param_name = op.inputs("Y")[0].name() + elif op.type() == 'batch_norm': + op_flops = count_bn(op) + flops += op_flops + elif op.type().startswith('element'): + op_flops = count_element_op(op) + flops += op_flops + if op_flops != 0: + table.add_row([op.type(), param_name, op_flops]) + op_flops = 0 + if detail: + table.print_table() + return flops + + +def static_flops(program, print_detail=False): + graph = GraphWrapper(program) + return _graph_flops(graph, detail=print_detail) + + +class Table(object): + + def __init__(self, table_heads): + self.table_heads = table_heads + self.table_len = [] + self.data = [] + self.col_num = len(table_heads) + for head in table_heads: + self.table_len.append(len(head)) + + def add_row(self, row_str): + if not isinstance(row_str, list): + print('The row_str should be a list') + if len(row_str) != self.col_num: + print( + 'The length of row data should be equal the length of table heads, but the data: {} is not equal table heads {}' + .format(len(row_str), self.col_num)) + for i in range(self.col_num): + if len(str(row_str[i])) > self.table_len[i]: + self.table_len[i] = len(str(row_str[i])) + self.data.append(row_str) + + def print_row(self, row): + string = '' + for i in range(self.col_num): + string += '|' + str(row[i]).center(self.table_len[i] + 2) + string += '|' + print(string) + + def print_shelf(self): + string = '' + for length in self.table_len: + string += '+' + string += '-' * (length + 2) + string += '+' + print(string) + + def print_table(self): + self.print_shelf() + self.print_row(self.table_heads) + self.print_shelf() + for data in self.data: + self.print_row(data) + self.print_shelf() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hub.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hub.py new file mode 100644 index 0000000000000000000000000000000000000000..acdb28cb6f08dfd51e9770c40283eb3f8d98a010 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/hub.py @@ -0,0 +1,21 @@ +# Copyright (c) 2021 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. + +from .hapi.hub import list # noqa: F401 +from .hapi.hub import help # noqa: F401 +from .hapi.hub import load # noqa: F401 + +__all__ = [ #noqa + 'list', 'help', 'load' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/extension.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/extension.h new file mode 100644 index 0000000000000000000000000000000000000000..1c2d546fbf039e5286832702c1df59faac3d35e1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/extension.h @@ -0,0 +1,18 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +// All paddle apis in C++ frontend +#include "paddle/phi/api/all.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/all.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/all.h new file mode 100644 index 0000000000000000000000000000000000000000..233d1dc981fb229f0cb034aa8f8df1c891ec5d0a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/all.h @@ -0,0 +1,20 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "function.h" //NOLINT +#include "layer.h" // NOLINT +#include "serializer.h" // NOLINT +#include "serializer_utils.h" // NOLINT diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/function.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/function.h new file mode 100644 index 0000000000000000000000000000000000000000..a80d46d63994606a147cdb864bcfe491ffcc4f26 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/function.h @@ -0,0 +1,47 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/api/include/tensor.h" + +namespace paddle { +namespace jit { +class BaseEngine; +using DenseTensor = phi::DenseTensor; +using Tensor = paddle::experimental::Tensor; + +class Function { + public: + Function() : engine_(nullptr) {} + explicit Function(BaseEngine* engine); + + std::vector operator()(const std::vector& inputs) const; + + std::vector operator()( + const std::vector& inputs) const; + + bool IsValid() const { return engine_ != nullptr; } + + ~Function() = default; + + private: + BaseEngine* engine_; +}; + +} // namespace jit +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/layer.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/layer.h new file mode 100644 index 0000000000000000000000000000000000000000..dd5ff5d9f91cd9fa27bd03ae220b201b7982c407 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/layer.h @@ -0,0 +1,78 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include +#include +#include + +#include "paddle/phi/api/include/tensor.h" +#include "paddle/phi/common/place.h" + +#include "function.h" //NOLINT + +namespace paddle { + +namespace framework { +class Variable; +} // namespace framework + +namespace jit { +class CompilationUnit; +class FunctionInfo; + +using DenseTensor = phi::DenseTensor; +using Tensor = paddle::experimental::Tensor; +using Variable = paddle::framework::Variable; +using VariableMap = std::unordered_map>; +using FunctionInfoMap = + std::unordered_map>; + +class Layer { + public: + Layer(const VariableMap& params_map, + const VariableMap& attrs_map_, + const FunctionInfoMap& info_map, + const phi::Place& place); + + jit::Function Function(const std::string& name) const; + + template + T Attribute(const std::string& name) const; + + std::vector forward(const std::vector& inputs); + + std::vector forward(const std::vector& inputs); + + void to(const phi::Place& place); + + void SetEngine(const std::string& name, + const std::shared_ptr& engine); + + const std::shared_ptr& FunctionInfo( + const std::string& name) const; + + std::vector FunctionNames() const; + + private: + VariableMap params_map_; + VariableMap attrs_map_; + FunctionInfoMap info_map_; + std::shared_ptr unit_; +}; + +} // namespace jit +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..b93eaa44fe63268b13bfd86b66e998ac77da3392 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer.h @@ -0,0 +1,77 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include +#include +#include + +#include "paddle/phi/common/place.h" + +namespace paddle { + +namespace framework { +class Variable; +class ProgramDesc; +} // namespace framework + +namespace jit { +class Layer; +using Variable = paddle::framework::Variable; +using VariableMap = std::unordered_map>; + +// Export Layer into local disk +class Serializer { + public: + void operator()(const Layer& layer, const std::string& file_dir); + + // private: + // void WriteTensorData(const Layer& layer, const std::string& file_name) + // const; + // void WriteExtraInfo(const Layer& layer, const std::string& file_name) + // const; + // void WriteByteCode(const Layer& layer, const std::string& file_name) + // const; +}; + +class Deserializer { + public: + Layer operator()(const std::string& dir_path, const phi::Place& place); + + private: + void ReadTensorData(const std::string& file_name, + const std::set& var_name, + const phi::Place& place, + VariableMap* params_dict) const; + + // property pb + void ReadAttributeData(const std::string& file_path, + VariableMap* attrs_dict) const; + + // void ReadExtraInfo(const std::string& file_name) const; + + // void ReadByteCode(const std::string& file_name) const; + + framework::ProgramDesc LoadProgram(const std::string& file_name); +}; + +void Export(const Layer& layer, const std::string& file_path); + +// path should be like 'dirname/file_prefix' +Layer Load(const std::string& path, const phi::Place& place); + +} // namespace jit +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0afe6be3fe2cba3521405235ac16d76c22f8e405 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/jit/serializer_utils.h @@ -0,0 +1,51 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +namespace paddle { + +namespace framework { +class VarDesc; +} // namespace framework + +namespace jit { +static const char PDMODEL_SUFFIX[] = ".pdmodel"; +static const char PDPARAMS_SUFFIX[] = ".pdiparams"; +static const char PROPERTY_SUFFIX[] = ".meta"; + +namespace utils { +bool IsPersistable(framework::VarDesc* desc_ptr); + +bool StartsWith(const std::string& str, const std::string& suffix); + +bool EndsWith(const std::string& str, const std::string& suffix); + +void ReplaceAll(std::string* str, + const std::string& old_value, + const std::string& new_value); + +bool FileExists(const std::string& file_path); + +const std::vector> PdmodelFilePaths( + const std::string& path); + +void InitKernelSignatureMap(); + +} // namespace utils +} // namespace jit +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/all.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/all.h new file mode 100644 index 0000000000000000000000000000000000000000..5838e7b2eaab7107db9897eabaf824f9b5da0994 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/all.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#if !defined(_MSC_VER) && __cplusplus < 201402L +#error C++14 or later compatible compiler is required to use Paddle. +#endif + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX // msvc max/min macro conflict with std::min/max +#endif +#endif + +// new phi apis +#include "paddle/phi/api/include/api.h" +#include "paddle/phi/api/include/context_pool.h" +#include "paddle/phi/api/include/sparse_api.h" +#include "paddle/phi/api/include/tensor.h" + +// phi common headers +#include "paddle/phi/common/backend.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/scalar.h" + +// original custom op headers +#include "paddle/phi/api/ext/dispatch.h" +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/api/ext/op_meta_info.h" +#include "paddle/phi/api/ext/tensor_compat.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/dispatch.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..aa9cd0f53a4c642b97292f77567f2b6706857f00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/dispatch.h @@ -0,0 +1,70 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/visit_type.h" + +namespace paddle { + +// Note: Keep this file only for compatibility with custom operators + +///////// Floating Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_TYPES(TYPE, NAME, ...) \ + PD_VISIT_FLOATING_TYPES(TYPE, NAME, __VA_ARGS__) + +#define PD_DISPATCH_FLOATING_AND_HALF_TYPES(TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_HALF_TYPES(TYPE, NAME, __VA_ARGS__) + +///////// Integral Dispatch Marco /////////// + +#define PD_DISPATCH_INTEGRAL_TYPES(TYPE, NAME, ...) \ + PD_VISIT_INTEGRAL_TYPES(TYPE, NAME, __VA_ARGS__) + +///////// Complex Dispatch Marco /////////// + +#define PD_DISPATCH_COMPLEX_TYPES(TYPE, NAME, ...) \ + PD_VISIT_COMPLEX_TYPES(TYPE, NAME, __VA_ARGS__) + +///////// Floating and Integral Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_AND_INTEGRAL_TYPES(TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_INTEGRAL_TYPES(TYPE, NAME, __VA_ARGS__) + +///////// Floating and Complex Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_AND_COMPLEX_TYPES(TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_COMPLEX_TYPES(TYPE, NAME, __VA_ARGS__) + +///////// Floating and Complex and other type Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_AND_COMPLEX_AND_1_TYPE( \ + SPECIFIED_TYPE, TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_COMPLEX_AND_1_TYPE( \ + SPECIFIED_TYPE, TYPE, NAME, __VA_ARGS__) + +///////// Floating and Complex and 2 other type Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_AND_COMPLEX_AND_2_TYPES( \ + SPECIFIED_TYPE1, SPECIFIED_TYPE2, TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_COMPLEX_AND_2_TYPES( \ + SPECIFIED_TYPE1, SPECIFIED_TYPE2, TYPE, NAME, __VA_ARGS__) + +///////// Floating, Integral and Complex Dispatch Marco /////////// + +#define PD_DISPATCH_FLOATING_AND_INTEGRAL_AND_COMPLEX_TYPES(TYPE, NAME, ...) \ + PD_VISIT_FLOATING_AND_INTEGRAL_AND_COMPLEX_TYPES(TYPE, NAME, __VA_ARGS__) + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/exception.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/exception.h new file mode 100644 index 0000000000000000000000000000000000000000..92b17b4898d3f7f9af26a0ba7172fc1a1ad36fe1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/exception.h @@ -0,0 +1,99 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include +#include + +namespace paddle { + +//////////////// Exception handling and Error Message ///////////////// +#if !defined(_WIN32) +#define PD_UNLIKELY(expr) (__builtin_expect(static_cast(expr), 0)) +#define PD_LIKELY(expr) (__builtin_expect(static_cast(expr), 1)) +#else +#define PD_UNLIKELY(expr) (expr) +#define PD_LIKELY(expr) (expr) +#endif + +struct PD_Exception : public std::exception { + public: + template + explicit PD_Exception(const std::string& msg, + const char* file, + int line, + const char* default_msg) { + std::ostringstream sout; + if (msg.empty()) { + sout << default_msg << "\n [" << file << ":" << line << "]"; + } else { + sout << msg << "\n [" << file << ":" << line << "]"; + } + err_msg_ = sout.str(); + } + + const char* what() const noexcept override { return err_msg_.c_str(); } + + private: + std::string err_msg_; +}; + +class ErrorMessage { + public: + template + explicit ErrorMessage(const Args&... args) { + build_string(args...); + } + + void build_string() { oss << ""; } + + template + void build_string(const T& t) { + oss << t; + } + + template + void build_string(const T& t, const Args&... args) { + build_string(t); + build_string(args...); + } + + std::string to_string() { return oss.str(); } + + private: + std::ostringstream oss; +}; + +#define PD_CHECK(COND, ...) \ + do { \ + if (PD_UNLIKELY(!(COND))) { \ + auto __message__ = ::paddle::ErrorMessage(__VA_ARGS__).to_string(); \ + throw ::paddle::PD_Exception(__message__, \ + __FILE__, \ + __LINE__, \ + "Expected " #COND \ + ", but it's not satisfied."); \ + } \ + } while (0) + +#define PD_THROW(...) \ + do { \ + auto __message__ = ::paddle::ErrorMessage(__VA_ARGS__).to_string(); \ + throw ::paddle::PD_Exception( \ + __message__, __FILE__, __LINE__, "An error occurred."); \ + } while (0) + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/op_meta_info.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/op_meta_info.h new file mode 100644 index 0000000000000000000000000000000000000000..546b0accf8ba7e41b71f672807257ffa783de0c2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/op_meta_info.h @@ -0,0 +1,672 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/api/include/dll_decl.h" +#include "paddle/phi/api/include/tensor.h" +#include "paddle/utils/any.h" + +/** + * Op Meta Info Related Define. + * + * Used to maintain operator core information. + * + */ + +namespace paddle { +namespace framework { +class PADDLE_API OpMetaInfoHelper; +} // namespace framework + +using Tensor = paddle::experimental::Tensor; + +///////////////// Util Marco Define //////////////// + +#define PD_DISABLE_COPY_AND_ASSIGN(classname) \ + private: \ + classname(const classname&) = delete; \ + classname(classname&&) = delete; \ + classname& operator=(const classname&) = delete; \ + classname& operator=(classname&&) = delete + +#define STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \ + struct __test_global_namespace_##uniq_name##__ {}; \ + static_assert(std::is_same<::__test_global_namespace_##uniq_name##__, \ + __test_global_namespace_##uniq_name##__>::value, \ + msg) + +///////////////// Util Define and Function //////////////// + +constexpr char kGradTensorSuffix[] = "@GRAD"; +constexpr char kTensorVectorSuffix[] = "@VECTOR"; +constexpr char kDoubleGradNewOutSuffix[] = "@NEW"; + +// Used for Construct Grad Tensor name +inline std::string Grad(const std::string& t_name) { + std::string result; + result.reserve(t_name.size() + 5U); + result += t_name; + result += kGradTensorSuffix; + return result; +} + +// Used for Construct std::vector name +inline std::string Vec(const std::string& t_name) { + std::string result; + result.reserve(t_name.size() + 7U); + result += t_name; + result += kTensorVectorSuffix; + return result; +} + +// Used for Construct double grad output name +inline std::string New(const std::string& t_name) { + std::string result; + result.reserve(t_name.size() + 4U); + result += t_name; + result += kDoubleGradNewOutSuffix; + return result; +} + +PADDLE_API void AssignTensorImpl(const Tensor& src, Tensor* dst); + +////////////////////// Kernel Context //////////////////////// + +class PADDLE_API CustomOpKernelContext { + public: + CustomOpKernelContext() = default; + + void EmplaceBackInput(Tensor&& input); + void EmplaceBackInputs(const std::vector& inputs); + void EmplaceBackOutput(Tensor&& output); + void EmplaceBackOutputs(const std::vector& outputs); + void EmplaceBackAttr(paddle::any attr); + void EmplaceBackAttrs(const std::vector& attrs) { + attrs_ = std::move(attrs); + } + const std::pair& InputRangeAt(size_t idx) const; + const std::pair& OutputRangeAt(size_t idx) const; + + const Tensor& InputAt(size_t idx) const; + std::vector InputsBetween(size_t start, size_t end) const; + const std::vector& Attrs() const { return attrs_; } + const std::vector>& InputRange() { + return input_range_; + } + const std::vector>& OutputRange() { + return output_range_; + } + Tensor* MutableOutputAt(size_t idx); + std::vector MutableOutputBetweeen(size_t start, size_t end); + std::vector OutputsBetweeen(size_t start, size_t end); + std::vector* AllMutableOutput(); + + template + AttrType AttrAt(size_t idx) const { + try { + return paddle::any_cast(attrs_.at(idx)); + } catch (paddle::bad_any_cast&) { + PD_THROW("Attribute cast error in Custom Op Kernel Context."); + } + } + + private: + // TODO(chenweihang): replaced be SmallVector + std::vector inputs_; + std::vector outputs_; + std::vector attrs_; + + std::vector> input_range_; + std::vector> output_range_; +}; + +////////////////////// Kernel Function (PD_KERNEL) //////////////////////// + +// Record Op kernel core function +using KernelFunc = void (*)(CustomOpKernelContext*); + +#define PD_SPECIALIZE_ComputeCallHelper(attr_type) \ + template \ + struct ComputeCallHelper { \ + template \ + static void Compute(CustomOpKernelContext* ctx, \ + const PreviousArgs&... pargs) { \ + attr_type arg = ctx->AttrAt(attr_idx); \ + ComputeCallHelper< \ + Tail...>::template Compute(ctx, \ + pargs..., \ + arg); \ + } \ + } + +template +struct TypeTag {}; + +template +struct KernelFuncImpl; + +template +struct KernelFuncImpl { + static void Compute(CustomOpKernelContext* ctx) { + ComputeCallHelper>::template Compute<0, 0, 0>(ctx); + } + + private: + template + struct ComputeCallHelper; + + template + struct ComputeCallHelper { + template + static void Compute(CustomOpKernelContext* ctx, + const PreviousArgs&... pargs) { + auto& range = ctx->InputRangeAt(in_idx); + auto& arg = ctx->InputAt(range.first); + ComputeCallHelper< + Tail...>::template Compute(ctx, + pargs..., + arg); + } + }; + + template + struct ComputeCallHelper&, Tail...> { + template + static void Compute(CustomOpKernelContext* ctx, + const PreviousArgs&... pargs) { + auto& range = ctx->InputRangeAt(in_idx); + auto arg = ctx->InputsBetween(range.first, range.second); + ComputeCallHelper< + Tail...>::template Compute(ctx, + pargs..., + arg); + } + }; + + PD_SPECIALIZE_ComputeCallHelper(bool); + PD_SPECIALIZE_ComputeCallHelper(int); + PD_SPECIALIZE_ComputeCallHelper(float); + PD_SPECIALIZE_ComputeCallHelper(int64_t); + PD_SPECIALIZE_ComputeCallHelper(const std::string&); + PD_SPECIALIZE_ComputeCallHelper(const std::vector&); + PD_SPECIALIZE_ComputeCallHelper(const std::vector&); + PD_SPECIALIZE_ComputeCallHelper(const std::vector&); + PD_SPECIALIZE_ComputeCallHelper(const std::vector&); + // TODO(chenweihang): support other attribute type if needed. + // Why not support other attribute type here? + // - paddle::blank, std::vector and std::vector + // are not used in op + // - BlockDesc* and std::vector are used in framework + + // NOTE(chenweihang): Used to be compatible with the 2.0.1 released + // interface, and will be deprecated in the future + PD_SPECIALIZE_ComputeCallHelper(const bool&); + PD_SPECIALIZE_ComputeCallHelper(const int&); + PD_SPECIALIZE_ComputeCallHelper(const float&); + PD_SPECIALIZE_ComputeCallHelper(const int64_t&); + + // NOTE(chenweihang): Used to be compatible with the 2.1 released + // interface, but not recommended + PD_SPECIALIZE_ComputeCallHelper(std::string); + PD_SPECIALIZE_ComputeCallHelper(std::vector); + PD_SPECIALIZE_ComputeCallHelper(std::vector); + PD_SPECIALIZE_ComputeCallHelper(std::vector); + PD_SPECIALIZE_ComputeCallHelper(std::vector); + + template + struct ComputeCallHelper { + template + static void Compute(CustomOpKernelContext* ctx, + const PreviousArgs&... pargs) { + auto& range = ctx->OutputRangeAt(out_idx); + auto* arg = ctx->MutableOutputAt(range.first); + ComputeCallHelper< + Tail...>::template Compute(ctx, + pargs..., + arg); + } + }; + + // TODO(chenweihang): What is the appropriate output form? + // std::vector*? or std::vector? or std::vector* + template + struct ComputeCallHelper, Tail...> { + template + static void Compute(CustomOpKernelContext* ctx, + const PreviousArgs&... pargs) { + auto& range = ctx->OutputRangeAt(out_idx); + auto arg = ctx->MutableOutputBetweeen(range.first, range.second); + ComputeCallHelper< + Tail...>::template Compute(ctx, + pargs..., + arg); + } + }; + + template + struct ComputeReturnHelper; + + // For compatibility with the original custom op form + template + struct ComputeReturnHelper> { + static void Compute(CustomOpKernelContext* ctx, const Args&... args) { + static_assert(out_idx == 0, + "If return std::vector in Custom OpKernel, " + "you cannot pass output by kernel funciton argument."); + auto outs = impl_fn(args...); + auto* orig_outs = ctx->AllMutableOutput(); + PD_CHECK(orig_outs->size() == outs.size(), + "The number of element in custom operator outputs is wrong, " + "expected contains ", + orig_outs->size(), + " Tensors, but actually contains ", + outs.size(), + " Tensors."); + for (size_t i = 0; i < outs.size(); ++i) { + AssignTensorImpl(outs.at(i), &(orig_outs->at(i))); + } + } + }; + + template + struct ComputeReturnHelper { + static void Compute(CustomOpKernelContext* ctx, const Args&... args) { + static_assert(out_idx > 0, "Custom OpKernel has no output."); + impl_fn(args...); + } + }; + + // end: base template + template + struct ComputeCallHelper> { + template + static void Compute(CustomOpKernelContext* ctx, + const PreviousArgs&... pargs) { + ComputeReturnHelper::Compute(ctx, pargs...); + } + }; +}; + +#define PD_KERNEL(...) \ + ::paddle::KernelFuncImpl::Compute + +/////////////// InferShape Function (PD_INFER_SHAPE) /////////////// + +// Record Op infershape core function +using InferShapeFunc = std::vector> (*)( + const std::vector>& input_shapes, + const std::vector>>& vec_input_shapes, + const std::vector& attrs); + +#define PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(input_type) \ + template \ + struct InferShapeCallHelper { \ + template \ + static Return InferShape( \ + const std::vector>& input_shapes, \ + const std::vector>>& \ + vec_input_shapes, \ + const std::vector& attrs, \ + const PreviousArgs&... pargs) { \ + input_type arg = input_shapes[in_idx]; \ + return InferShapeCallHelper:: \ + template InferShape( \ + input_shapes, vec_input_shapes, attrs, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES(input_type) \ + template \ + struct InferShapeCallHelper { \ + template \ + static Return InferShape( \ + const std::vector>& input_shapes, \ + const std::vector>>& \ + vec_input_shapes, \ + const std::vector& attrs, \ + const PreviousArgs&... pargs) { \ + input_type arg = vec_input_shapes[vec_in_idx]; \ + return InferShapeCallHelper:: \ + template InferShape( \ + input_shapes, vec_input_shapes, attrs, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(attr_type) \ + template \ + struct InferShapeCallHelper { \ + template \ + static Return InferShape( \ + const std::vector>& input_shapes, \ + const std::vector>>& \ + vec_input_shapes, \ + const std::vector& attrs, \ + const PreviousArgs&... pargs) { \ + try { \ + attr_type arg = paddle::any_cast(attrs[attr_idx]); \ + return InferShapeCallHelper:: \ + template InferShape( \ + input_shapes, vec_input_shapes, attrs, pargs..., arg); \ + } catch (paddle::bad_any_cast&) { \ + PD_THROW( \ + "Attribute cast error in custom operator InferShapeFn. " \ + "Expected " #attr_type \ + " value. InferShapeFn's attribute list must be exactly same as " \ + "Forward " \ + "KernelFn's attribute list except std::vector " \ + "attribute."); \ + } \ + } \ + } + +template +struct InferShapeFuncImpl; + +template +struct InferShapeFuncImpl { + static Return InferShape( + const std::vector>& input_shapes, + const std::vector>>& vec_input_shapes, + const std::vector& attrs) { + return InferShapeCallHelper>:: + template InferShape<0, 0, 0>(input_shapes, vec_input_shapes, attrs); + } + + private: + template + struct InferShapeCallHelper; + + PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(const std::vector&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES( + const std::vector>&); + + // NOTE(chenweihang): Used to be compatible with the 2.0.1 released + // interface, and will be deprecated in the future + PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPE(std::vector); + PD_SPECIALIZE_InferShapeCallHelper_FOR_SHAPES( + std::vector>); + + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(bool); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(int); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(float); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(int64_t); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::string&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const std::vector&); + // NOTE(chenweihang): InferShape can't support std::vector attr type, + // because the input type is std::vector, only can use one rule to + // parse std::vector parameter + + // NOTE(chenweihang): Used to be compatible with the 2.0.1 released + // interface, and will be deprecated in the future + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const bool&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const int&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const float&); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(const int64_t&); + + // NOTE(chenweihang): Used to be compatible with the 2.1 released + // interface, but not recommended + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::string); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector); + PD_SPECIALIZE_InferShapeCallHelper_FOR_ATTR(std::vector); + + // end: base template + template + struct InferShapeCallHelper> { + template + static Return InferShape( + const std::vector>& input_shapes, + const std::vector>>& vec_input_shapes, + const std::vector& attrs, + const Args&... args) { + return impl_fn(args...); + } + }; +}; + +#define PD_INFER_SHAPE(...) \ + ::paddle::InferShapeFuncImpl::InferShape + +/////////////// InferDataType Function (PD_INFER_DTYPE) /////////////// + +// Record Op Infer dtype core function +using InferDtypeFunc = std::vector (*)( + const std::vector& input_dtypes, + const std::vector>& vec_input_dtypes); + +#define PD_SPECIALIZE_InferDtypeCallHelper_TO_DTYPE(input_type) \ + template \ + struct InferDtypeCallHelper { \ + template \ + static Return InferDtype( \ + const std::vector& input_dtypes, \ + const std::vector>& vec_input_dtypes, \ + const PreviousArgs&... pargs) { \ + input_type arg = input_dtypes[in_idx]; \ + return InferDtypeCallHelper::template InferDtype( \ + input_dtypes, vec_input_dtypes, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(input_type) \ + template \ + struct InferDtypeCallHelper { \ + template \ + static Return InferDtype( \ + const std::vector& input_dtypes, \ + const std::vector>& vec_input_dtypes, \ + const PreviousArgs&... pargs) { \ + input_type arg = vec_input_dtypes[vec_in_idx]; \ + return InferDtypeCallHelper:: \ + template InferDtype( \ + input_dtypes, vec_input_dtypes, pargs..., arg); \ + } \ + } + +template +struct InferDtypeFuncImpl; + +template +struct InferDtypeFuncImpl { + static Return InferDtype( + const std::vector& input_dtypes, + const std::vector>& vec_input_dtypes) { + return InferDtypeCallHelper>::template InferDtype<0, + 0>( + input_dtypes, vec_input_dtypes); + } + + private: + template + struct InferDtypeCallHelper; + + PD_SPECIALIZE_InferDtypeCallHelper_TO_DTYPE(const DataType&); + PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(const std::vector&); + + // NOTE(chenweihang): Used to be compatible with the 2.0.1 released + // interface, and will be deprecated in the future + PD_SPECIALIZE_InferDtypeCallHelper_TO_DTYPE(DataType); + PD_SPECIALIZE_InferDtypeCallHelper_FOR_DTYPES(std::vector); + + // end: base template + template + struct InferDtypeCallHelper> { + template + static Return InferDtype( + const std::vector& input_dtypes, + const std::vector>& vec_input_dtypes, + const Args&... args) { + return impl_fn(args...); + } + }; +}; + +#define PD_INFER_DTYPE(...) \ + ::paddle::InferDtypeFuncImpl::InferDtype + +////////////////////// Op Meta Info ////////////////////// + +class PADDLE_API OpMetaInfo { + public: + explicit OpMetaInfo(const std::string& op_name) : name_(op_name) {} + + // format: {"", "", ...} + OpMetaInfo& Inputs(std::vector&& inputs); + + // format: {"", "", ...} + OpMetaInfo& Outputs(std::vector&& outputs); + + // format: {":", ":", ...} + OpMetaInfo& Attrs(std::vector&& attrs); + + // format: PD_KERNEL(...) + OpMetaInfo& SetKernelFn(KernelFunc&& func); + + // format: PD_INFER_SHAPE(...) + OpMetaInfo& SetInferShapeFn(InferShapeFunc&& func); + + // format: PD_INFER_DTYPE(...) + OpMetaInfo& SetInferDtypeFn(InferDtypeFunc&& func); + + private: + friend class framework::OpMetaInfoHelper; + + // 1. desc info + std::string name_; + std::vector inputs_; + std::vector outputs_; + std::vector attrs_; + // 2. func info + KernelFunc kernel_fn_{nullptr}; + InferShapeFunc infer_shape_fn_{nullptr}; + InferDtypeFunc infer_dtype_fn_{nullptr}; +}; + +//////////////// Op Meta Info Map ///////////////// + +class PADDLE_API OpMetaInfoMap { + public: + // this function's impl should keep in header file. + // if move to cc file, meta info can not be added + // into map + static OpMetaInfoMap& Instance() { + static OpMetaInfoMap g_custom_op_meta_info_map; + return g_custom_op_meta_info_map; + } + + std::vector& operator[](const std::string& name); + + const std::unordered_map>& GetMap() + const; + + private: + OpMetaInfoMap() = default; + std::unordered_map> map_; + + PD_DISABLE_COPY_AND_ASSIGN(OpMetaInfoMap); +}; + +//////////////// Op Meta Info Builder ///////////////// + +class PADDLE_API OpMetaInfoBuilder { + public: + explicit OpMetaInfoBuilder(std::string&& name, size_t index); + OpMetaInfoBuilder& Inputs(std::vector&& inputs); + OpMetaInfoBuilder& Outputs(std::vector&& outputs); + OpMetaInfoBuilder& Attrs(std::vector&& attrs); + OpMetaInfoBuilder& SetKernelFn(KernelFunc func); + OpMetaInfoBuilder& SetInferShapeFn(InferShapeFunc func); + OpMetaInfoBuilder& SetInferDtypeFn(InferDtypeFunc func); + + private: + // Forward Op name + std::string name_; + // ref current info ptr + OpMetaInfo* info_ptr_; + // The current op meta info index in vector + // - 0: op, 1: grad_op, 2: grad_grad_op + size_t index_; +}; + +/////////////////////// Op register API ///////////////////////// + +// For inference: compile directly with framework +// Call after PD_BUILD_OP(...) +void RegisterAllCustomOperator(); + +// Using this api to load compiled custom operator's dynamic library and +// register Custom +// Operator into it +void LoadCustomOperatorLib(const std::string& dso_name); + +/////////////////////// Op register Macro ///////////////////////// + +#define PD_BUILD_OP(op_name) \ + STATIC_ASSERT_GLOBAL_NAMESPACE( \ + __reg_op__##op_name, "PD_BUILD_OP must be called in global namespace."); \ + static ::paddle::OpMetaInfoBuilder __op_meta_info_##op_name##__ = \ + ::paddle::OpMetaInfoBuilder(#op_name, 0) + +#define PD_BUILD_GRAD_OP(op_name) \ + STATIC_ASSERT_GLOBAL_NAMESPACE( \ + __reg_grad_op__##op_name, \ + "PD_BUILD_GRAD_OP must be called in global namespace."); \ + static ::paddle::OpMetaInfoBuilder __grad_op_meta_info_##op_name##__ = \ + ::paddle::OpMetaInfoBuilder(#op_name, 1) + +#define PD_BUILD_DOUBLE_GRAD_OP(op_name) \ + STATIC_ASSERT_GLOBAL_NAMESPACE( \ + __reg_grad_grad_op__##op_name, \ + "PD_BUILD_DOUBLE_GRAD_OP must be called in global namespace."); \ + static ::paddle::OpMetaInfoBuilder __grad_grad_op_meta_info_##op_name##__ = \ + ::paddle::OpMetaInfoBuilder(#op_name, 2) + +} // namespace paddle + +///////////////////// C API /////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_WIN32) +// C-API to get global OpMetaInfoMap. +__declspec(dllexport) inline paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() { + return paddle::OpMetaInfoMap::Instance(); +} +#endif // _WIN32 + +#ifdef __cplusplus +} +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/tensor_compat.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/tensor_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..2833629f0ff2c9ac8d7e318d7d7b4e543852fb98 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/ext/tensor_compat.h @@ -0,0 +1,139 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/api/include/api.h" +#include "paddle/phi/api/include/tensor.h" + +// Note(chenweihang): In order to be compatible with the original custom +// operator Tensor interface, only available to external users, the file +// cannot be includeed in paddle + +namespace paddle { +using Tensor = experimental::Tensor; +// using several Tensor initialize functions in paddle namespace +using experimental::abs; +using experimental::acos; +using experimental::acosh; +using experimental::add; +using experimental::allclose; +using experimental::argsort; +using experimental::asin; +using experimental::asinh; +using experimental::atan; +using experimental::atan2; +using experimental::atanh; +using experimental::bernoulli; +using experimental::ceil; +using experimental::cholesky; +using experimental::cholesky_solve; +using experimental::clip; +using experimental::concat; +using experimental::conj; +using experimental::cos; +using experimental::cosh; +using experimental::cross; +using experimental::det; +using experimental::diag; +using experimental::diagonal; +using experimental::digamma; +using experimental::dist; +using experimental::divide; +using experimental::dot; +using experimental::elu; +using experimental::empty; +using experimental::empty_like; +using experimental::equal_all; +using experimental::erf; +using experimental::erfinv; +using experimental::exp; +using experimental::expand; +using experimental::expm1; +using experimental::flatten; +using experimental::flip; +using experimental::floor; +using experimental::floor_divide; +using experimental::full; +using experimental::gather; +using experimental::gather_nd; +using experimental::gelu; +using experimental::gumbel_softmax; +using experimental::imag; +using experimental::increment_; +using experimental::index_sample; +using experimental::is_empty; +using experimental::isclose; +using experimental::isfinite; +using experimental::isinf; +using experimental::isnan; +using experimental::kron; +using experimental::kthvalue; +using experimental::label_smooth; +using experimental::lerp; +using experimental::lgamma; +using experimental::log; +using experimental::log10; +using experimental::log1p; +using experimental::log2; +using experimental::logit; +using experimental::masked_select; +using experimental::matmul; +using experimental::matrix_power; +using experimental::maximum; +using experimental::maxout; +using experimental::minimum; +using experimental::mode; +using experimental::multi_dot; +using experimental::multinomial; +using experimental::multiply; +using experimental::mv; +using experimental::nll_loss; +using experimental::one_hot; +using experimental::ones; +using experimental::pixel_shuffle; +using experimental::poisson; +using experimental::qr; +using experimental::real; +using experimental::reciprocal; +using experimental::relu; +using experimental::reshape; +using experimental::roll; +using experimental::round; +using experimental::rsqrt; +using experimental::scatter; +using experimental::scatter_nd_add; +using experimental::selu; +using experimental::sign; +using experimental::silu; +using experimental::sin; +using experimental::sinh; +using experimental::split; +using experimental::sqrt; +using experimental::square; +using experimental::stack; +using experimental::strided_slice; +using experimental::subtract; +using experimental::tanh; +using experimental::thresholded_relu; +using experimental::tile; +using experimental::trace; +using experimental::triangular_solve; +using experimental::unbind; +using experimental::unique; +using experimental::unsqueeze; +using experimental::where; +using experimental::zeros; + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/api.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/api.h new file mode 100644 index 0000000000000000000000000000000000000000..235f96d5f01e18178b221b05ee818e51da0e243a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/api.h @@ -0,0 +1,738 @@ +#pragma once + +#include + +#include "paddle/phi/api/include/tensor.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/utils/optional.h" + +namespace paddle { +namespace experimental { + + +PADDLE_API Tensor atan2(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor bernoulli(const Tensor& x); + +PADDLE_API Tensor cholesky(const Tensor& x, bool upper = false); + +PADDLE_API Tensor cholesky_solve(const Tensor& x, const Tensor& y, bool upper = false); + +PADDLE_API Tensor cross(const Tensor& x, const Tensor& y, int axis = 9); + +PADDLE_API Tensor diag(const Tensor& x, int offset = 0, float padding_value = 0.0); + +PADDLE_API Tensor diagonal(const Tensor& x, int offset = 0, int axis1 = 0, int axis2 = 1); + +PADDLE_API Tensor digamma(const Tensor& x); + +PADDLE_API Tensor dist(const Tensor& x, const Tensor& y, float p = 2.0); + +PADDLE_API Tensor dot(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor erf(const Tensor& x); + +PADDLE_API Tensor erfinv(const Tensor& x); + +PADDLE_API Tensor& erfinv_(Tensor& x); + +PADDLE_API Tensor fft_c2c(const Tensor& x, const std::vector& axes, const std::string& normalization, bool forward); + +PADDLE_API Tensor fft_c2r(const Tensor& x, const std::vector& axes, const std::string& normalization, bool forward, int64_t last_dim_size = 0L); + +PADDLE_API Tensor fft_r2c(const Tensor& x, const std::vector& axes, const std::string& normalization, bool forward, bool onesided); + +PADDLE_API Tensor graph_send_uv(const Tensor& x, const Tensor& y, const Tensor& src_index, const Tensor& dst_index, const std::string& message_op = "ADD"); + +PADDLE_API Tensor lgamma(const Tensor& x); + +PADDLE_API Tensor mv(const Tensor& x, const Tensor& vec); + +PADDLE_API Tensor poisson(const Tensor& x); + +PADDLE_API Tensor solve(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor trace(const Tensor& x, int offset = 0, int axis1 = 0, int axis2 = 1); + +PADDLE_API Tensor trunc(const Tensor& x); + +PADDLE_API Tensor flip(const Tensor& x, const std::vector& axis); + +PADDLE_API Tensor abs(const Tensor& x); + +PADDLE_API std::tuple accuracy(const Tensor& x, const Tensor& indices, const Tensor& label); + +PADDLE_API Tensor acos(const Tensor& x); + +PADDLE_API Tensor acosh(const Tensor& x); + +PADDLE_API std::tuple adadelta_(Tensor& param, const Tensor& grad, Tensor& avg_squared_grad, Tensor& avg_squared_update, float rho, float epsilon); + +PADDLE_API std::tuple adagrad_(Tensor& param, const Tensor& grad, Tensor& moment, const Tensor& learning_rate, float epsilon); + +PADDLE_API std::tuple&> adam_(Tensor& param, const Tensor& grad, const Tensor& learning_rate, Tensor& moment1, Tensor& moment2, Tensor& beta1_pow, Tensor& beta2_pow, paddle::optional& master_param, const paddle::optional& skip_update, const Scalar& beta1, const Scalar& beta2, const Scalar& epsilon, bool lazy_mode, int64_t min_row_size_to_use_multithread, bool multi_precision, bool use_global_beta_pow); + +PADDLE_API std::tuple adamax_(Tensor& param, const Tensor& grad, const Tensor& learning_rate, Tensor& moment, Tensor& inf_norm, const Tensor& beta1_pow, float beta1, float beta2, float epsilon); + +PADDLE_API std::tuple&> adamw_(Tensor& param, const Tensor& grad, const Tensor& learning_rate, Tensor& moment1, Tensor& moment2, Tensor& beta1_pow, Tensor& beta2_pow, paddle::optional& master_param, const paddle::optional& skip_update, const Scalar& beta1, const Scalar& beta2, const Scalar& epsilon, float lr_ratio, float coeff, bool with_decay, bool lazy_mode, int64_t min_row_size_to_use_multithread, bool multi_precision, bool use_global_beta_pow); + +PADDLE_API Tensor add(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor& add_(Tensor& x, const Tensor& y); + +PADDLE_API Tensor add_n(const std::vector& x); + +PADDLE_API Tensor addmm(const Tensor& input, const Tensor& x, const Tensor& y, float alpha, float beta); + +PADDLE_API Tensor affine_grid(const Tensor& input, const IntArray& outputShape, bool use_cudnn = true, bool align_corners = true); + +PADDLE_API Tensor all(const Tensor& x, const std::vector& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor allclose(const Tensor& x, const Tensor& y, const Scalar& rtol, const Scalar& atol, bool equal_nan); + +PADDLE_API Tensor amax(const Tensor& x, const std::vector& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor amin(const Tensor& x, const std::vector& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor angle(const Tensor& x); + +PADDLE_API Tensor any(const Tensor& x, const std::vector& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor arange(const Tensor& start, const Tensor& end, const Tensor& step, DataType dtype, const Place& place = {}); + +PADDLE_API Tensor argmax(const Tensor& x, const Scalar& axis, bool keepdims, bool flatten, int dtype); + +PADDLE_API Tensor argmin(const Tensor& x, const Scalar& axis, bool keepdims, bool flatten, int dtype); + +PADDLE_API std::tuple argsort(const Tensor& x, int axis = -1, bool descending = false); + +PADDLE_API Tensor as_complex(const Tensor& x); + +PADDLE_API Tensor as_real(const Tensor& x); + +PADDLE_API Tensor asin(const Tensor& x); + +PADDLE_API Tensor asinh(const Tensor& x); + +PADDLE_API Tensor assign(const Tensor& x); + +PADDLE_API Tensor& assign_out_(const Tensor& x, Tensor& output); + +PADDLE_API Tensor& assign_value_(Tensor& output, const std::vector& shape, DataType dtype, const std::vector& values, const Place& place = {}); + +PADDLE_API Tensor atan(const Tensor& x); + +PADDLE_API Tensor atanh(const Tensor& x); + +PADDLE_API std::tuple auc(const Tensor& x, const Tensor& label, const Tensor& stat_pos, const Tensor& stat_neg, const paddle::optional& ins_tag_weight, const std::string& curve, int num_thresholds, int slide_steps); + +PADDLE_API std::tuple average_accumulates_(const Tensor& param, Tensor& in_sum_1, Tensor& in_sum_2, Tensor& in_sum_3, Tensor& in_num_accumulates, Tensor& in_old_num_accumulates, Tensor& in_num_updates, float average_window, int64_t max_average_window, int64_t min_average_window); + +PADDLE_API std::tuple batch_norm(const Tensor& x, const Tensor& scale, const Tensor& bias, const Tensor& mean, const Tensor& variance, float momentum, float epsilon, const std::string& data_layout, bool is_test, bool use_global_stats, bool trainable_statistics, bool fuse_with_relu); + +PADDLE_API Tensor bce_loss(const Tensor& input, const Tensor& label); + +PADDLE_API Tensor bicubic_interp(const Tensor& x, const paddle::optional& out_size, const paddle::optional>& size_tensor, const paddle::optional& scale_tensor, const std::string& data_layout, int out_d, int out_h, int out_w, const std::vector& scale, const std::string& interp_method, bool align_corners, int align_mode); + +PADDLE_API Tensor bilinear_interp(const Tensor& x, const paddle::optional& out_size, const paddle::optional>& size_tensor, const paddle::optional& scale_tensor, const std::string& data_layout, int out_d, int out_h, int out_w, const std::vector& scale, const std::string& interp_method, bool align_corners, int align_mode); + +PADDLE_API Tensor bilinear_tensor_product(const Tensor& x, const Tensor& y, const Tensor& weight, const paddle::optional& bias); + +PADDLE_API Tensor bitwise_and(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor bitwise_not(const Tensor& x); + +PADDLE_API Tensor bitwise_or(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor bitwise_xor(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor bmm(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor box_coder(const Tensor& prior_box, const paddle::optional& prior_box_var, const Tensor& target_box, const std::string& code_type, bool box_normalized, int axis, const std::vector& variance); + +PADDLE_API Tensor brelu(const Tensor& x, float t_min, float t_max); + +PADDLE_API Tensor cast(const Tensor& x, DataType out_dtype); + +PADDLE_API Tensor ceil(const Tensor& x); + +PADDLE_API Tensor& ceil_(Tensor& x); + +PADDLE_API Tensor celu(const Tensor& x, float alpha); + +PADDLE_API std::tuple class_center_sample(const Tensor& label, int num_classes, int num_samples, int ring_id, int rank, int nranks, bool fix_seed, int seed); + +PADDLE_API Tensor clip(const Tensor& x, const Scalar& min, const Scalar& max); + +PADDLE_API Tensor& clip_(Tensor& x, const Scalar& min, const Scalar& max); + +PADDLE_API Tensor clip_by_norm(const Tensor& x, float max_norm); + +PADDLE_API std::tuple, Tensor> coalesce_tensor(const std::vector& input, DataType dtype, bool copy_data = false, bool set_constant = false, bool persist_output = false, float constant = 0.0, bool use_align = true, int align_size = -1, int size_of_dtype = -1, const std::vector& concated_shapes = {}, const std::vector& concated_ranks = {}); + +PADDLE_API Tensor complex(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor concat(const std::vector& x, const Scalar& axis); + +PADDLE_API Tensor conj(const Tensor& x); + +PADDLE_API Tensor conv2d(const Tensor& input, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format, bool use_addto, int workspace_size_MB, bool exhaustive_search); + +PADDLE_API Tensor conv2d_transpose(const Tensor& x, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::vector& output_padding, const IntArray& output_size, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format); + +PADDLE_API Tensor conv3d(const Tensor& input, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::string& paddding_algorithm, int groups, const std::vector& dilations, const std::string& data_format, bool use_addto, int workspace_size_MB, bool exhaustive_search); + +PADDLE_API Tensor conv3d_transpose(const Tensor& x, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::vector& output_padding, const std::vector& output_size, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format); + +PADDLE_API Tensor copy_to(const Tensor& x, const Place& place, bool blocking); + +PADDLE_API Tensor cos(const Tensor& x); + +PADDLE_API Tensor cosh(const Tensor& x); + +PADDLE_API Tensor crop_tensor(const Tensor& x, const IntArray& shape, const IntArray& offsets); + +PADDLE_API std::tuple cross_entropy_with_softmax(const Tensor& input, const Tensor& label, bool soft_label, bool use_softmax, bool numeric_stable_mode, int ignore_index, int axis); + +PADDLE_API Tensor cumprod(const Tensor& x, int dim); + +PADDLE_API Tensor cumsum(const Tensor& x, const Scalar& axis, bool flatten, bool exclusive, bool reverse); + +PADDLE_API Tensor decode_jpeg(const Tensor& x, const std::string& mode); + +PADDLE_API Tensor deformable_conv(const Tensor& x, const Tensor& offset, const Tensor& filter, const paddle::optional& mask, const std::vector& strides, const std::vector& paddings, const std::vector& dilations, int deformable_groups, int groups, int im2col_step); + +PADDLE_API Tensor depthwise_conv2d(const Tensor& x, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format, bool use_addto, int workspace_size_MB, bool exhaustive_search, bool fuse_relu, bool use_gpudnn); + +PADDLE_API Tensor depthwise_conv2d_transpose(const Tensor& x, const Tensor& filter, const std::vector& strides, const std::vector& paddings, const std::vector& output_padding, const IntArray& output_size, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format); + +PADDLE_API Tensor det(const Tensor& x); + +PADDLE_API Tensor diag_embed(const Tensor& x, int offset, int dim1, int dim2); + +PADDLE_API std::tuple, std::vector, Tensor> distribute_fpn_proposals(const Tensor& fpn_rois, const paddle::optional& rois_num, int min_level, int max_level, int refer_level, int refer_scale, bool pixel_offset); + +PADDLE_API Tensor divide(const Tensor& x, const Tensor& y); + +PADDLE_API std::tuple dropout(const Tensor& x, const paddle::optional& seed_tensor, const Scalar& p, bool is_test, const std::string& mode, int seed, bool fix_seed); + +PADDLE_API std::tuple edit_distance(const Tensor& hyps, const Tensor& refs, const paddle::optional& hypslength, const paddle::optional& refslength, bool normalized = false); + +PADDLE_API std::tuple eigh(const Tensor& x, const std::string& uplo); + +PADDLE_API Tensor eigvals(const Tensor& x); + +PADDLE_API std::tuple eigvalsh(const Tensor& x, const std::string& uplo, bool is_test); + +PADDLE_API std::tuple, std::vector> einsum(const std::vector& x, const std::string& equation); + +PADDLE_API Tensor elementwise_pow(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor elu(const Tensor& x, float alpha); + +PADDLE_API Tensor& elu_(Tensor& x, float alpha); + +PADDLE_API Tensor embedding(const Tensor& x, const Tensor& weight, int64_t padding_idx = -1, bool sparse = false); + +PADDLE_API Tensor empty(const IntArray& shape, DataType dtype = DataType::FLOAT32, const Place& place = CPUPlace()); + +PADDLE_API Tensor empty_like(const Tensor& x, DataType dtype = DataType::UNDEFINED, const Place& place = {}); + +PADDLE_API Tensor equal(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor equal_all(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor exp(const Tensor& x); + +PADDLE_API Tensor& exp_(Tensor& x); + +PADDLE_API Tensor expand(const Tensor& x, const IntArray& shape); + +PADDLE_API Tensor expand_as(const Tensor& x, const paddle::optional& y, const std::vector& target_shape); + +PADDLE_API Tensor expm1(const Tensor& x); + +PADDLE_API Tensor& exponential_(Tensor& x, float lambda); + +PADDLE_API Tensor eye(const Scalar& num_rows, const Scalar& num_columns, DataType dtype = DataType::FLOAT32, const Place& place = {}); + +PADDLE_API Tensor fill(const Tensor& x, const Scalar& value); + +PADDLE_API Tensor& fill_(Tensor& x, const Scalar& value); + +PADDLE_API Tensor fill_diagonal(const Tensor& x, float value, int offset, bool wrap); + +PADDLE_API Tensor& fill_diagonal_(Tensor& x, float value, int offset, bool wrap); + +PADDLE_API Tensor fill_diagonal_tensor(const Tensor& x, const Tensor& y, int64_t offset, int dim1, int dim2); + +PADDLE_API Tensor& fill_diagonal_tensor_(Tensor& x, const Tensor& y, int64_t offset, int dim1, int dim2); + +PADDLE_API Tensor flatten(const Tensor& x, int start_axis, int stop_axis); + +PADDLE_API Tensor& flatten_(Tensor& x, int start_axis, int stop_axis); + +PADDLE_API Tensor floor(const Tensor& x); + +PADDLE_API Tensor& floor_(Tensor& x); + +PADDLE_API Tensor floor_divide(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor fmax(const Tensor& x, const Tensor& y, int axis); + +PADDLE_API Tensor fmin(const Tensor& x, const Tensor& y, int axis); + +PADDLE_API Tensor frame(const Tensor& x, int frame_length, int hop_length, int axis); + +PADDLE_API Tensor frobenius_norm(const Tensor& x, const std::vector& axis, bool keep_dim, bool reduce_all); + +PADDLE_API Tensor full(const IntArray& shape, const Scalar& value, DataType dtype = DataType::FLOAT32, const Place& place = CPUPlace()); + +PADDLE_API Tensor& full_(Tensor& output, const IntArray& shape, const Scalar& value, DataType dtype = DataType::FLOAT32, const Place& place = CPUPlace()); + +PADDLE_API Tensor full_batch_size_like(const Tensor& input, const std::vector& shape, DataType dtype, const Scalar& value, int input_dim_idx, int output_dim_idx, const Place& place = CPUPlace()); + +PADDLE_API Tensor full_like(const Tensor& x, const Scalar& value, DataType dtype = DataType::UNDEFINED, const Place& place = {}); + +PADDLE_API Tensor gather(const Tensor& x, const Tensor& index, const Scalar& axis = 0); + +PADDLE_API Tensor gather_nd(const Tensor& x, const Tensor& index); + +PADDLE_API Tensor gather_tree(const Tensor& ids, const Tensor& parents); + +PADDLE_API Tensor gaussian_random(const IntArray& shape, float mean, float std, int seed, DataType dtype, const Place& place = {}); + +PADDLE_API Tensor gelu(const Tensor& x, bool approximate); + +PADDLE_API std::tuple generate_proposals_v2(const Tensor& scores, const Tensor& bbox_deltas, const Tensor& im_shape, const Tensor& anchors, const Tensor& variances, int pre_nms_top_n, int post_nms_top_n, float nms_thresh, float min_size, float eta, bool pixel_offset = true); + +PADDLE_API Tensor graph_send_recv(const Tensor& x, const Tensor& src_index, const Tensor& dst_index, const std::string& reduce_op = "SUM", const IntArray& out_size = {0}); + +PADDLE_API Tensor graph_send_ue_recv(const Tensor& x, const Tensor& y, const Tensor& src_index, const Tensor& dst_index, const std::string& message_op, const std::string& reduce_op, const IntArray& out_size); + +PADDLE_API Tensor greater_equal(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor greater_than(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor grid_sample(const Tensor& x, const Tensor& grid, const std::string& mode, const std::string& padding_mode, bool align_corners); + +PADDLE_API Tensor group_norm(const Tensor& x, const paddle::optional& scale, const paddle::optional& bias, float epsilon, int groups, const std::string& data_layout); + +PADDLE_API Tensor gumbel_softmax(const Tensor& x, float temperature, bool hard, int axis); + +PADDLE_API Tensor hard_shrink(const Tensor& x, float threshold); + +PADDLE_API Tensor hard_sigmoid(const Tensor& x, float slope, float offset); + +PADDLE_API Tensor hard_swish(const Tensor& x, float threshold = 6.0, float scale = 6.0, float offset = 3.0); + +PADDLE_API std::tuple hierarchical_sigmoid(const Tensor& x, const Tensor& w, const Tensor& label, const paddle::optional& path, const paddle::optional& code, const paddle::optional& bias, int num_classes, bool remote_prefetch, int trainer_id, const std::vector& height_sections, const std::vector& epmap, const std::vector& table_names, bool is_sparse); + +PADDLE_API Tensor histogram(const Tensor& x, int64_t bins, int min, int max); + +PADDLE_API std::tuple huber_loss(const Tensor& input, const Tensor& label, float delta); + +PADDLE_API Tensor imag(const Tensor& x); + +PADDLE_API Tensor increment(const Tensor& x, float value); + +PADDLE_API Tensor& increment_(Tensor& x, float value); + +PADDLE_API Tensor index_add(const Tensor& x, const Tensor& index, const Tensor& add_value, int axis); + +PADDLE_API Tensor& index_add_(Tensor& x, const Tensor& index, const Tensor& add_value, int axis); + +PADDLE_API Tensor index_sample(const Tensor& x, const Tensor& index); + +PADDLE_API Tensor index_select(const Tensor& x, const Tensor& index, int dim); + +PADDLE_API Tensor instance_norm(const Tensor& x, const paddle::optional& scale, const paddle::optional& bias, float epsilon); + +PADDLE_API Tensor inverse(const Tensor& x); + +PADDLE_API Tensor is_empty(const Tensor& x); + +PADDLE_API Tensor isclose(const Tensor& x, const Tensor& y, const Scalar& rtol, const Scalar& atol, bool equal_nan); + +PADDLE_API Tensor isfinite(const Tensor& x); + +PADDLE_API Tensor isinf(const Tensor& x); + +PADDLE_API Tensor isnan(const Tensor& x); + +PADDLE_API Tensor kldiv_loss(const Tensor& x, const Tensor& label, const std::string& reduction); + +PADDLE_API Tensor kron(const Tensor& x, const Tensor& y); + +PADDLE_API std::tuple kthvalue(const Tensor& x, int k, int axis, bool keepdim); + +PADDLE_API Tensor label_smooth(const Tensor& label, const paddle::optional& prior_dist, float epsilon); + +PADDLE_API std::tuple&> lamb_(Tensor& param, const Tensor& grad, const Tensor& learning_rate, Tensor& moment1, Tensor& moment2, Tensor& beta1_pow, Tensor& beta2_pow, paddle::optional& master_param, const paddle::optional& skip_update, float weight_decay, float beta1, float beta2, float epsilon, bool multi_precision); + +PADDLE_API std::tuple layer_norm(const Tensor& x, const paddle::optional& scale, const paddle::optional& bias, float epsilon, int begin_norm_axis, bool is_test); + +PADDLE_API Tensor leaky_relu(const Tensor& x, float alpha); + +PADDLE_API Tensor lerp(const Tensor& x, const Tensor& y, const Tensor& weight); + +PADDLE_API Tensor& lerp_(Tensor& x, const Tensor& y, const Tensor& weight); + +PADDLE_API Tensor less_equal(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor less_than(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor linear_interp(const Tensor& x, const paddle::optional& out_size, const paddle::optional>& size_tensor, const paddle::optional& scale_tensor, const std::string& data_layout, int out_d, int out_h, int out_w, const std::vector& scale, const std::string& interp_method, bool align_corners, int align_mode); + +PADDLE_API Tensor linspace(const Tensor& start, const Tensor& stop, const Tensor& number, DataType dtype, const Place& place); + +PADDLE_API Tensor log(const Tensor& x); + +PADDLE_API Tensor log10(const Tensor& x); + +PADDLE_API Tensor log1p(const Tensor& x); + +PADDLE_API Tensor log2(const Tensor& x); + +PADDLE_API Tensor log_loss(const Tensor& input, const Tensor& label, float epsilon); + +PADDLE_API Tensor log_softmax(const Tensor& x, int axis); + +PADDLE_API Tensor logcumsumexp(const Tensor& x, int axis, bool flatten, bool exclusive, bool reverse); + +PADDLE_API Tensor logical_and(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor logical_not(const Tensor& x); + +PADDLE_API Tensor logical_or(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor logical_xor(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor logit(const Tensor& x, float eps = 1e-6f); + +PADDLE_API Tensor logsigmoid(const Tensor& x); + +PADDLE_API Tensor logsumexp(const Tensor& x, const std::vector& axis, bool keepdim, bool reduce_all); + +PADDLE_API std::tuple lstsq(const Tensor& x, const Tensor& y, const Scalar& rcond, const std::string& driver); + +PADDLE_API std::tuple lu(const Tensor& x, bool pivot); + +PADDLE_API std::tuple lu_unpack(const Tensor& x, const Tensor& pivots, bool unpack_ludata, bool unpack_pivots); + +PADDLE_API std::tuple margin_cross_entropy(const Tensor& logits, const Tensor& label, bool return_softmax, int ring_id, int rank, int nranks, float margin1, float margin2, float margin3, float scale); + +PADDLE_API Tensor masked_select(const Tensor& x, const Tensor& mask); + +PADDLE_API Tensor matmul(const Tensor& x, const Tensor& y, bool transpose_x = false, bool transpose_y = false); + +PADDLE_API std::tuple matrix_nms(const Tensor& bboxes, const Tensor& scores, float score_threshold, int nms_top_k, int keep_top_k, float post_threshold = 0., bool use_gaussian = false, float gaussian_sigma = 2.0, int background_label = 0, bool normalized = true); + +PADDLE_API Tensor matrix_power(const Tensor& x, int n); + +PADDLE_API Tensor matrix_rank(const Tensor& x, float tol, bool use_default_tol = true, bool hermitian = false); + +PADDLE_API Tensor matrix_rank_tol(const Tensor& x, const Tensor& atol_tensor, bool use_default_tol = true, bool hermitian = false); + +PADDLE_API Tensor max(const Tensor& x, const IntArray& dims = {}, bool keep_dim = false); + +PADDLE_API std::tuple max_pool2d_with_index(const Tensor& x, const std::vector& kernel_size, const std::vector& strides, const std::vector& paddings, bool global_pooling, bool adaptive); + +PADDLE_API std::tuple max_pool3d_with_index(const Tensor& x, const std::vector& kernel_size, const std::vector& strides, const std::vector& paddings, bool global_pooling, bool adaptive); + +PADDLE_API Tensor maximum(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor maxout(const Tensor& x, int groups, int axis); + +PADDLE_API Tensor mean(const Tensor& x, const IntArray& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor mean_all(const Tensor& x); + +PADDLE_API std::tuple&, std::vector&, std::vector&, std::vector&, std::vector&, paddle::optional>&> merged_adam_(std::vector& param, const std::vector& grad, const std::vector& learning_rate, std::vector& moment1, std::vector& moment2, std::vector& beta1_pow, std::vector& beta2_pow, paddle::optional>& master_param, const Scalar& beta1, const Scalar& beta2, const Scalar& epsilon, bool multi_precision, bool use_global_beta_pow); + +PADDLE_API std::tuple&, std::vector&, paddle::optional>&> merged_momentum_(std::vector& param, const std::vector& grad, std::vector& velocity, const std::vector& learning_rate, paddle::optional>& master_param, float mu, bool use_nesterov = false, const std::vector& regularization_method = {}, const std::vector& regularization_coeff = {}, bool multi_precision = false, float rescale_grad = 1.0f); + +PADDLE_API std::vector meshgrid(const std::vector& inputs); + +PADDLE_API Tensor min(const Tensor& x, const IntArray& dims = {}, bool keep_dim = false); + +PADDLE_API Tensor minimum(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor mish(const Tensor& x, float lambda); + +PADDLE_API std::tuple mode(const Tensor& x, int axis, bool keepdim); + +PADDLE_API std::tuple&> momentum_(Tensor& param, const Tensor& grad, Tensor& velocity, const Tensor& learning_rate, paddle::optional& master_param, float mu, bool use_nesterov = false, const std::string& regularization_method = "", float regularization_coeff = 0.0, bool multi_precision = false, float rescale_grad = 1.0f); + +PADDLE_API Tensor multi_dot(const std::vector& x); + +PADDLE_API std::tuple multiclass_nms3(const Tensor& bboxes, const Tensor& scores, const paddle::optional& rois_num, float score_threshold, int nms_top_k, int keep_top_k, float nms_threshold = 0.3, bool normalized = true, float nms_eta = 1.0, int background_label = 0); + +PADDLE_API Tensor multinomial(const Tensor& x, const Scalar& num_samples, bool replacement); + +PADDLE_API Tensor multiplex(const std::vector& ins, const Tensor& ids); + +PADDLE_API Tensor multiply(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor nearest_interp(const Tensor& x, const paddle::optional& out_size, const paddle::optional>& size_tensor, const paddle::optional& scale_tensor, const std::string& data_layout, int out_d, int out_h, int out_w, const std::vector& scale, const std::string& interp_method, bool align_corners, int align_mode); + +PADDLE_API std::tuple nll_loss(const Tensor& input, const Tensor& label, const paddle::optional& weight, int64_t ignore_index, const std::string& reduction); + +PADDLE_API Tensor nms(const Tensor& x, float threshold); + +PADDLE_API std::tuple norm(const Tensor& x, int axis, float epsilon, bool is_test); + +PADDLE_API Tensor not_equal(const Tensor& x, const Tensor& y, int axis = -1); + +PADDLE_API Tensor one_hot(const Tensor& x, const Scalar& num_classes); + +PADDLE_API Tensor ones(const IntArray& shape, DataType dtype = DataType::FLOAT32, const Place& place = CPUPlace()); + +PADDLE_API Tensor ones_like(const Tensor& x, DataType dtype = DataType::UNDEFINED, const Place& place = {}); + +PADDLE_API Tensor p_norm(const Tensor& x, float porder, int axis, float epsilon, bool keepdim, bool asvector = false); + +PADDLE_API Tensor pad(const Tensor& x, const std::vector& paddings, const Scalar& pad_value); + +PADDLE_API Tensor pad3d(const Tensor& x, const IntArray& paddings, const std::string& mode, float pad_value, const std::string& data_format); + +PADDLE_API Tensor pixel_shuffle(const Tensor& x, int upscale_factor, const std::string& data_format); + +PADDLE_API Tensor pool2d(const Tensor& x, const IntArray& kernel_size, const std::vector& strides, const std::vector& paddings, bool ceil_mode, bool exclusive, const std::string& data_format, const std::string& pooling_type, bool global_pooling, bool adaptive, const std::string& padding_algorithm, bool use_gpudnn); + +PADDLE_API Tensor pool3d(const Tensor& x, const std::vector& kernel_size, const std::vector& strides, const std::vector& paddings, bool ceil_mode, bool exclusive, const std::string& data_format, const std::string& pooling_type, bool global_pooling, bool adaptive, const std::string& padding_algorithm, bool use_gpudnn); + +PADDLE_API Tensor pow(const Tensor& x, const Scalar& s); + +PADDLE_API Tensor prelu(const Tensor& x, const Tensor& alpha, const std::string& data_format, const std::string& mode); + +PADDLE_API std::tuple prior_box(const Tensor& input, const Tensor& image, const std::vector& min_sizes, const std::vector& aspect_ratios, const std::vector& variances, const std::vector& max_sizes = {}, bool flip = true, bool clip = true, float step_w = 0.0, float step_h = 0.0, float offset = 0.5, bool min_max_aspect_ratios_order = false); + +PADDLE_API Tensor psroi_pool(const Tensor& x, const Tensor& boxes, const paddle::optional& boxes_num, int pooled_height, int pooled_width, int output_channels, float spatial_scale); + +PADDLE_API Tensor put_along_axis(const Tensor& x, const Tensor& index, const Tensor& value, int axis, const std::string& reduce); + +PADDLE_API Tensor& put_along_axis_(Tensor& x, const Tensor& index, const Tensor& value, int axis, const std::string& reduce); + +PADDLE_API std::tuple qr(const Tensor& x, const std::string& mode); + +PADDLE_API Tensor randint(int low, int high, const IntArray& shape, DataType dtype = DataType::INT64, const Place& place = {}); + +PADDLE_API Tensor randperm(int n, DataType dtype, const Place& place = {}); + +PADDLE_API Tensor real(const Tensor& x); + +PADDLE_API Tensor reciprocal(const Tensor& x); + +PADDLE_API Tensor& reciprocal_(Tensor& x); + +PADDLE_API Tensor reduce_prod(const Tensor& x, const IntArray& dims, bool keep_dim, bool reduce_all); + +PADDLE_API Tensor relu(const Tensor& x); + +PADDLE_API Tensor& relu_(Tensor& x); + +PADDLE_API Tensor relu6(const Tensor& x, float threshold); + +PADDLE_API Tensor remainder(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor& remainder_(Tensor& x, const Tensor& y); + +PADDLE_API Tensor renorm(const Tensor& x, float p, int axis, float max_norm); + +PADDLE_API Tensor repeat_interleave(const Tensor& x, int repeats, int dim); + +PADDLE_API Tensor repeat_interleave_with_tensor_index(const Tensor& x, const Tensor& repeats, int dim); + +PADDLE_API Tensor reshape(const Tensor& x, const IntArray& shape); + +PADDLE_API Tensor& reshape_(Tensor& x, const IntArray& shape); + +PADDLE_API Tensor reverse(const Tensor& x, const IntArray& axis); + +PADDLE_API std::tuple rmsprop_(Tensor& param, Tensor& mean_square, const Tensor& grad, Tensor& moment, const Tensor& learning_rate, Tensor& mean_grad, float epsilon, float decay, float momentum, bool centered); + +PADDLE_API Tensor roi_align(const Tensor& x, const Tensor& boxes, const paddle::optional& boxes_num, int pooled_height, int pooled_width, float spatial_scale, int sampling_ratio, bool aligned); + +PADDLE_API Tensor roi_pool(const Tensor& x, const Tensor& boxes, const paddle::optional& boxes_num, int pooled_height, int pooled_width, float spatial_scale); + +PADDLE_API Tensor roll(const Tensor& x, const IntArray& shifts, const std::vector& axis); + +PADDLE_API Tensor round(const Tensor& x); + +PADDLE_API Tensor& round_(Tensor& x); + +PADDLE_API Tensor rsqrt(const Tensor& x); + +PADDLE_API Tensor& rsqrt_(Tensor& x); + +PADDLE_API Tensor scale(const Tensor& x, const Scalar& scale, float bias, bool bias_after_scale); + +PADDLE_API Tensor& scale_(Tensor& x, const Scalar& scale, float bias, bool bias_after_scale); + +PADDLE_API Tensor scatter(const Tensor& x, const Tensor& index, const Tensor& updates, bool overwrite); + +PADDLE_API Tensor& scatter_(Tensor& x, const Tensor& index, const Tensor& updates, bool overwrite); + +PADDLE_API Tensor scatter_nd_add(const Tensor& x, const Tensor& index, const Tensor& updates); + +PADDLE_API Tensor searchsorted(const Tensor& sorted_sequence, const Tensor& value, bool out_int32, bool right); + +PADDLE_API std::tuple segment_pool(const Tensor& x, const Tensor& segment_ids, const std::string& pooltype); + +PADDLE_API Tensor selu(const Tensor& x, float scale, float alpha); + +PADDLE_API std::tuple&> sgd_(Tensor& param, const Tensor& learning_rate, const Tensor& grad, paddle::optional& master_param, bool multi_precision); + +PADDLE_API Tensor shape(const Tensor& input); + +PADDLE_API Tensor shard_index(const Tensor& in, int index_num, int nshards, int shard_id, int ignore_value); + +PADDLE_API Tensor sigmoid(const Tensor& x); + +PADDLE_API Tensor sigmoid_cross_entropy_with_logits(const Tensor& x, const Tensor& label, bool normalize, int ignore_index); + +PADDLE_API Tensor sign(const Tensor& x); + +PADDLE_API Tensor silu(const Tensor& x); + +PADDLE_API Tensor sin(const Tensor& x); + +PADDLE_API Tensor sinh(const Tensor& x); + +PADDLE_API Tensor size(const Tensor& x); + +PADDLE_API Tensor slice(const Tensor& input, const std::vector& axes, const IntArray& starts, const IntArray& ends, const std::vector& infer_flags, const std::vector& decrease_axis); + +PADDLE_API Tensor slogdet(const Tensor& x); + +PADDLE_API Tensor soft_shrink(const Tensor& x, float lambda); + +PADDLE_API Tensor softmax(const Tensor& x, int axis); + +PADDLE_API Tensor& softmax_(Tensor& x, int axis); + +PADDLE_API Tensor softplus(const Tensor& x, float beta, float threshold); + +PADDLE_API Tensor softsign(const Tensor& x); + +PADDLE_API Tensor spectral_norm(const Tensor& weight, const Tensor& u, const Tensor& v, int dim, int power_iters, float eps); + +PADDLE_API std::vector split(const Tensor& x, const IntArray& sections, const Scalar& axis); + +PADDLE_API std::vector split_with_num(const Tensor& x, int num, const Scalar& axis); + +PADDLE_API Tensor sqrt(const Tensor& x); + +PADDLE_API Tensor& sqrt_(Tensor& x); + +PADDLE_API Tensor square(const Tensor& x); + +PADDLE_API Tensor squared_l2_norm(const Tensor& x); + +PADDLE_API Tensor squeeze(const Tensor& x, const IntArray& axes); + +PADDLE_API Tensor& squeeze_(Tensor& x, const IntArray& axes); + +PADDLE_API Tensor stack(const std::vector& x, int axis); + +PADDLE_API Tensor strided_slice(const Tensor& x, const std::vector& axes, const IntArray& starts, const IntArray& ends, const IntArray& strides); + +PADDLE_API Tensor subtract(const Tensor& x, const Tensor& y); + +PADDLE_API Tensor& subtract_(Tensor& x, const Tensor& y); + +PADDLE_API Tensor sum(const Tensor& x, const IntArray& dims = {}, DataType out_dtype = DataType::UNDEFINED, bool keep_dim = false); + +PADDLE_API std::tuple svd(const Tensor& x, bool full_metrices); + +PADDLE_API Tensor swish(const Tensor& x, float beta = 1.0); + +PADDLE_API std::tuple sync_batch_norm_(const Tensor& x, const Tensor& scale, const Tensor& bias, Tensor& mean, Tensor& variance, float momentum, float epsilon, const std::string& data_layout, bool is_test, bool use_global_stats, bool trainable_statistics, bool fuse_with_relu); + +PADDLE_API Tensor take_along_axis(const Tensor& x, const Tensor& index, int axis); + +PADDLE_API Tensor tan(const Tensor& x); + +PADDLE_API Tensor tanh(const Tensor& x); + +PADDLE_API Tensor& tanh_(Tensor& x); + +PADDLE_API Tensor tanh_shrink(const Tensor& x); + +PADDLE_API Tensor temporal_shift(const Tensor& x, int seg_num, float shift_ratio, const std::string& data_format_str); + +PADDLE_API Tensor thresholded_relu(const Tensor& x, float threshold); + +PADDLE_API Tensor tile(const Tensor& x, const IntArray& repeat_times); + +PADDLE_API std::tuple top_k(const Tensor& x, const Scalar& k, int axis = -1, bool largest = true, bool sorted = true); + +PADDLE_API Tensor transpose(const Tensor& x, const std::vector& axis); + +PADDLE_API Tensor triangular_solve(const Tensor& x, const Tensor& y, bool upper, bool transpose, bool unitriangular); + +PADDLE_API Tensor tril_indices(int rows, int cols, int offset, DataType dtype, const Place& place = {}); + +PADDLE_API Tensor tril_triu(const Tensor& x, int diagonal, bool lower); + +PADDLE_API Tensor trilinear_interp(const Tensor& x, const paddle::optional& out_size, const paddle::optional>& size_tensor, const paddle::optional& scale_tensor, const std::string& data_layout, int out_d, int out_h, int out_w, const std::vector& scale, const std::string& interp_method, bool align_corners, int align_mode); + +PADDLE_API Tensor triu_indices(int row, int col, int offset, DataType dtype, const Place& place = {}); + +PADDLE_API Tensor truncated_gaussian_random(const std::vector& shape, float mean, float std, int seed, DataType dtype = DataType::FLOAT32, const Place& place = {}); + +PADDLE_API std::vector unbind(const Tensor& input, int axis); + +PADDLE_API Tensor unfold(const Tensor& x, const std::vector& kernel_sizes, const std::vector& strides, const std::vector& paddings, const std::vector& dilations); + +PADDLE_API Tensor uniform_random(const IntArray& shape, DataType dtype, const Scalar& min, const Scalar& max, int seed, const Place& place = {}); + +PADDLE_API std::tuple unique(const Tensor& x, bool return_index, bool return_inverse, bool return_counts, const std::vector& axis, DataType dtype = DataType::INT64); + +PADDLE_API std::tuple unique_consecutive(const Tensor& x, bool return_inverse, bool return_counts, const std::vector& axis, int dtype); + +PADDLE_API Tensor unsqueeze(const Tensor& x, const IntArray& axis); + +PADDLE_API Tensor& unsqueeze_(Tensor& x, const IntArray& axis); + +PADDLE_API std::vector unstack(const Tensor& x, int axis, int num); + +PADDLE_API std::tuple viterbi_decode(const Tensor& input, const Tensor& transition, const Tensor& length, bool include_bos_eos_tag); + +PADDLE_API Tensor warpctc(const Tensor& logits, const Tensor& label, const paddle::optional& logits_length, const paddle::optional& labels_length, int blank, bool norm_by_times); + +PADDLE_API Tensor where(const Tensor& condition, const Tensor& x, const Tensor& y); + +PADDLE_API Tensor where_index(const Tensor& condition); + +PADDLE_API std::tuple yolo_box(const Tensor& x, const Tensor& img_size, const std::vector& anchors, int class_num, float conf_thresh, int downsample_ratio, bool clip_bbox, float scale_x_y = 1.0, bool iou_aware = false, float iou_aware_factor = 0.5); + +PADDLE_API std::tuple yolov3_loss(const Tensor& x, const Tensor& gt_box, const Tensor& gt_label, const paddle::optional& gt_score, const std::vector& anchors, const std::vector& anchor_mask, int class_num, float ignore_thresh, int downsample_ratio, bool use_label_smooth = true, float scale_x_y = 1.0); + +PADDLE_API Tensor zeros(const IntArray& shape, DataType dtype = DataType::FLOAT32, const Place& place = CPUPlace()); + +PADDLE_API Tensor zeros_like(const Tensor& x, DataType dtype = DataType::UNDEFINED, const Place& place = {}); + +PADDLE_API std::vector broadcast_tensors(const std::vector& x); + +PADDLE_API Tensor dirichlet(const Tensor& alpha); + +PADDLE_API std::tuple eig(const Tensor& x); + +PADDLE_API Tensor fold(const Tensor& x, const std::vector& output_sizes, const std::vector& kernel_sizes, const std::vector& strides, const std::vector& paddings, const std::vector& dilations); + +PADDLE_API Tensor overlap_add(const Tensor& x, int hop_length, int axis); + +PADDLE_API Tensor uniform_random_inplace(const Tensor& x, float min, float max, int seed, int diag_num, int diag_step, float diag_val); + +PADDLE_API Tensor& uniform_random_inplace_(Tensor& x, float min, float max, int seed, int diag_num, int diag_step, float diag_val); + +PADDLE_API Tensor unpool(const Tensor& x, const Tensor& indices, const std::vector& ksize, const std::vector& strides, const std::vector& padding, const IntArray& output_size, const std::string& data_format); + +PADDLE_API Tensor unpool3d(const Tensor& x, const Tensor& indices, const std::vector& ksize, const std::vector& strides, const std::vector& padding, const std::vector& output_size, const std::string& data_format); + + +} // namespace experimental +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/context_pool.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/context_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..f2e797575fd576c0473782eed103d077195c3542 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/context_pool.h @@ -0,0 +1,89 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/api/include/dll_decl.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/macros.h" +#include "paddle/utils/flat_hash_map.h" + +namespace phi { +class DeviceContext; +class CPUContext; +class GPUContext; +} // namespace phi + +namespace paddle { +namespace experimental { + +template +struct DefaultDeviceContextType; + +template <> +struct DefaultDeviceContextType { + using TYPE = phi::CPUContext; +}; + +template <> +struct DefaultDeviceContextType { + using TYPE = phi::GPUContext; +}; + +/** + * The DeviceContextPool here is just a mirror of the DeviceContextPool in + * fluid, and does not manage the life cycle of the DeviceContext. + * It is mainly used for external custom operator calls and high-performance + * C++ APIs. + * + * Since DeviceContextPool in fluid is a global singleton, it always exists + * in program running, so DeviceContextPool here can always access the correct + * DeviceContext pointer. + * + * In order not to depend on the fluid's DeviceContextPool, + * the DeviceContextPool here needs to be initialized in the fluid, and cannot + * be initialized by itself. + * + * Note: DeviceContextPool is an experimental API and may be removed in the + * future. From 2.3, we recommend directly using the C++ API to combine new + * operators. + */ +class PADDLE_API DeviceContextPool { + public: + static DeviceContextPool& Instance(); + + const phi::DeviceContext* Get(const Place& place); + + phi::DeviceContext* GetMutable(const Place& place); + + template + const typename DefaultDeviceContextType::TYPE* Get(const Place& place) { + return reinterpret_cast::TYPE*>( + Get(place)); + } + + private: + DeviceContextPool() = default; + + paddle::flat_hash_map + context_map_; + std::mutex mutex_; + + DISABLE_COPY_AND_ASSIGN(DeviceContextPool); +}; + +} // namespace experimental +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/dll_decl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/dll_decl.h new file mode 100644 index 0000000000000000000000000000000000000000..37c637c102c3b84dd3a95c72ef6a503055da8d2a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/dll_decl.h @@ -0,0 +1,27 @@ +// 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. + +#pragma once + +#if defined(_WIN32) +#ifndef PADDLE_API +#ifdef PADDLE_DLL_EXPORT +#define PADDLE_API __declspec(dllexport) +#else +#define PADDLE_API __declspec(dllimport) +#endif // PADDLE_DLL_EXPORT +#endif // PADDLE_API +#else +#define PADDLE_API +#endif // _WIN32 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/sparse_api.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/sparse_api.h new file mode 100644 index 0000000000000000000000000000000000000000..7d8a9012ecaadeb43b21d85756a791edf7a4a4a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/sparse_api.h @@ -0,0 +1,243 @@ +#pragma once + +#include + +#include "paddle/phi/api/include/tensor.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/utils/optional.h" + +namespace paddle { +namespace experimental { +namespace sparse { + + +// out + +PADDLE_API Tensor abs(const Tensor& x); + + +// out + +PADDLE_API Tensor acos(const Tensor& x); + + +// out + +PADDLE_API Tensor acosh(const Tensor& x); + + +// out + +PADDLE_API Tensor add(const Tensor& x, const Tensor& y); + + +// out + +PADDLE_API Tensor asin(const Tensor& x); + + +// out + +PADDLE_API Tensor asinh(const Tensor& x); + + +// out + +PADDLE_API Tensor atan(const Tensor& x); + + +// out + +PADDLE_API Tensor atanh(const Tensor& x); + + +// out, mean_out, variance_out, saved_mean, saved_variance, reserve_space + +PADDLE_API std::tuple batch_norm_(const Tensor& x, const Tensor& scale, const Tensor& bias, Tensor& mean, Tensor& variance, float momentum, float epsilon, const std::string& data_layout, bool is_test, bool use_global_stats, bool trainable_statistics, bool fuse_with_relu); + + +// out + +PADDLE_API Tensor cast(const Tensor& x, DataType index_dtype = DataType::UNDEFINED, DataType value_dtype = DataType::UNDEFINED); + + +// out, rulebook, counter + +PADDLE_API Tensor conv3d(const Tensor& x, const Tensor& kernel, const std::vector& paddings, const std::vector& dilations, const std::vector& strides, int groups, bool subm, const std::string& key = ""); + + +// out + +PADDLE_API Tensor divide(const Tensor& x, const Tensor& y); + + +// out + +PADDLE_API Tensor divide_scalar(const Tensor& x, float scalar); + + +// out + +PADDLE_API Tensor expm1(const Tensor& x); + + +// out + +PADDLE_API Tensor leaky_relu(const Tensor& x, float alpha); + + +// out + +PADDLE_API Tensor log1p(const Tensor& x); + + +// out + +PADDLE_API Tensor multiply(const Tensor& x, const Tensor& y); + + +// out + +PADDLE_API Tensor pow(const Tensor& x, float factor); + + +// out + +PADDLE_API Tensor relu(const Tensor& x); + + +// out + +PADDLE_API Tensor relu6(const Tensor& x, float threshold); + + +// out + +PADDLE_API Tensor scale(const Tensor& x, float scale, float bias, bool bias_after_scale); + + +// out + +PADDLE_API Tensor sin(const Tensor& x); + + +// out + +PADDLE_API Tensor sinh(const Tensor& x); + + +// out + +PADDLE_API Tensor softmax(const Tensor& x, int axis = -1); + + +// out + +PADDLE_API Tensor sparse_coo_tensor(const Tensor& values, const Tensor& indices, const std::vector& shape = {}); + + +// out + +PADDLE_API Tensor sqrt(const Tensor& x); + + +// out + +PADDLE_API Tensor square(const Tensor& x); + + +// out + +PADDLE_API Tensor subtract(const Tensor& x, const Tensor& y); + + +// out + +PADDLE_API Tensor tan(const Tensor& x); + + +// out + +PADDLE_API Tensor tanh(const Tensor& x); + + +// out + +PADDLE_API Tensor to_dense(const Tensor& x); + + +// out + +PADDLE_API Tensor to_sparse_coo(const Tensor& x, int64_t sparse_dim); + + +// out + +PADDLE_API Tensor to_sparse_csr(const Tensor& x); + + +// out + +PADDLE_API Tensor values(const Tensor& x); + + +// out + +PADDLE_API Tensor addmm(const Tensor& input, const Tensor& x, const Tensor& y, float alpha = 1.0, float beta = 1.0); + + +// out + +PADDLE_API Tensor coalesce(const Tensor& x); + + +// out + +PADDLE_API Tensor full_like(const Tensor& x, const Scalar& value, DataType dtype = DataType::UNDEFINED); + + +// out, softmax + +PADDLE_API Tensor fused_attention(const Tensor& query, const Tensor& key, const Tensor& value, const Tensor& sparse_mask, const paddle::optional& key_padding_mask, const paddle::optional& attn_mask); + + +// out + +PADDLE_API Tensor masked_matmul(const Tensor& x, const Tensor& y, const Tensor& mask); + + +// out + +PADDLE_API Tensor matmul(const Tensor& x, const Tensor& y); + + +// out, rulebook, counter + +PADDLE_API Tensor maxpool(const Tensor& x, const std::vector& kernel_sizes, const std::vector& paddings, const std::vector& dilations, const std::vector& strides); + + +// out + +PADDLE_API Tensor mv(const Tensor& x, const Tensor& vec); + + +// out + +PADDLE_API Tensor transpose(const Tensor& x, const std::vector& perm); + + +// out, mean_out, variance_out, saved_mean, saved_variance, reserve_space + +PADDLE_API std::tuple sync_batch_norm_(const Tensor& x, const Tensor& scale, const Tensor& bias, Tensor& mean, Tensor& variance, float momentum, float epsilon, const std::string& data_layout, bool is_test, bool use_global_stats, bool trainable_statistics, bool fuse_with_relu); + + +// out + +PADDLE_API Tensor reshape(const Tensor& x, const IntArray& shape); + + + +} // namespace sparse +} // namespace experimental +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/strings_api.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/strings_api.h new file mode 100644 index 0000000000000000000000000000000000000000..09462311a220f6f1d4f8c9d3c042f8493f051556 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/strings_api.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include "paddle/phi/api/include/tensor.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/utils/optional.h" + +namespace paddle { +namespace experimental { +namespace strings { + + +// out@StringTensor + +PADDLE_API Tensor empty(const IntArray& shape, const Place& place = CPUPlace()); + + +// out@StringTensor + +PADDLE_API Tensor empty_like(const Tensor& x, const Place& place = {}); + + +// out@StringTensor + +PADDLE_API Tensor lower(const Tensor& x, bool use_utf8_encoding); + + +// out@StringTensor + +PADDLE_API Tensor upper(const Tensor& x, bool use_utf8_encoding); + + + +} // namespace strings +} // namespace experimental +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..67cedaf6710abd5d743a27336ece06c627b64072 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/api/include/tensor.h @@ -0,0 +1,611 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include +#include +#include + +#ifdef PADDLE_WITH_CUDA +#include +using gpuStream_t = cudaStream_t; +#endif + +#ifdef PADDLE_WITH_HIP +#include +using gpuStream_t = hipStream_t; +#endif + +#include "paddle/phi/api/include/dll_decl.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/place.h" + +namespace phi { +class DenseTensor; +} // namespace phi + +namespace phi { +class TensorBase; +class DDim; +} // namespace phi + +namespace paddle { + +namespace experimental { + +class AbstractAutogradMeta { + public: + // No AbstractAutogradMeta should be created + virtual ~AbstractAutogradMeta() {} +}; + +/** + * Tensor is the API description of the basic data structure in the + * [ "Paddle Tensor Operation (phi)" Library ]. + * + * It is not limited to a simple n-dimensional array. + * It contains a smart pointer to `TensorImpl`. The data description contained + * in Tensor is defined by TensorImpl. Tensor only defines the interface for + * computation. + * + * This is a new Tensor design, which is independent of the original + * framework::Tensor in fluid. The original Tensor will be gradually discarded + * in the future. + * + * Note: Tensor can be NULL state, Tensor is meaningful only when the + * TensorImpl to which it is pointed is not empty. + * + * Note: For the consistency of C++ API self, and the consistency between C++ + * API and Python API, all member methods of Tensor are named with lowercase + * letters and underscores. + * + * Note: Tensor cannot be inherited. The heterogeneous Tensor implementation + * can be achieved by inheriting the underlying TensorBase. + * + * Note: This Tensor API is suitable for training and custom operators, + * another simple Tensor design may be required for inference. + */ + +class PADDLE_API Tensor final { + public: + /* Part 1: Construction and destruction methods */ + + /** + * @brief Construct a new Tensor object + */ + Tensor() = default; + + /** + * @brief Construct a new Tensor object by copy + */ + Tensor(const Tensor&) = default; + + /** + * @brief Construct a new Tensor object by move + */ + Tensor(Tensor&&) = default; + + /** + * @brief Construct a new Tensor object by a TensorBase pointer + * + * @param tensor_impl + */ + explicit Tensor(std::shared_ptr tensor_impl); + + /** + * @brief Construct a new Tensor object on the target place. + * + * This is a deprecated method and may be removed in the future!!! + * + * @param place + */ + explicit Tensor(const Place& place); + + /** + * @brief Construct a new Tensor object on the target place + * with specified shape. + * + * This is a deprecated method and may be removed in the future!!! + * + * @param place + * @param shape + */ + Tensor(const Place& place, const std::vector& shape); + + /** + * @brief Construct a new Tensor object by a TensorBase pointer and name + * + * @param tensor_impl + */ + Tensor(std::shared_ptr tensor_impl, const std::string& name); + + /** + * @brief Construct a new Tensor object with name + * + * @note Internal method, used to adapt original execution mechanism and + * debug analysis in the development of new dygraph. It may be removed in + * the future. + * */ + explicit Tensor(const std::string& name) : name_(name) {} + + /* Part 2: Dimension, DataType and DataLayout methods */ + + /** + * @brief Return the number of elements of Tensor. + * + * @return int64_t + */ + int64_t numel() const; + + /** + * @brief Get the size of current tensor. + * + * The compatible method of `Tensor::numel()`. + * This is a deprecated method and may be removed in the future! + * + * @return int64_t + */ + int64_t size() const; + + /** + * @brief Return the dimensions of Tensor. + * + * @return phi::DDim + */ + const phi::DDim& dims() const; + + /** + * @brief Return the shape (dimensions) of Tensor. + * + * The compatible method of `Tensor::dims()`. + * This is a deprecated method and may be removed in the future! + * + * @return std::vector + */ + std::vector shape() const; + + /** + * @brief Reset the shape of the tensor. + * @note: This method means Reset the shape of the tensor, + * and must be called before calling mutable_data() or + * copy_to(const Place& place), this is not a standard definition of + * reshape behavior, so we will deprecated this feature in the future. + * + * @param shape + */ + void reshape(const std::vector& shape); + + /** + * @brief Return the data type of Tensor. + * + * @return DataType + */ + DataType dtype() const; + + /** + * @brief Return the data type of Tensor. + * + * The compatible method of `Tensor::dtype()`. + * This is a deprecated method and may be removed in the future! + * + * @return DataType + */ + DataType type() const; + + /** + * @brief Return the layout of Tensor. + * + * @return DataLayout + */ + DataLayout layout() const; + + /** + * @brief Determine whether tensor is DenseTensor + * + * @return true + * @return false + */ + bool is_dense_tensor() const; + + /** + * @brief Determine whether tensor is SelectedRows + * + * @return true + * @return false + */ + bool is_selected_rows() const; + + /** + * @brief Determine whether tensor is SparseCooTensor + * + * @return true + * @return false + */ + bool is_sparse_coo_tensor() const; + + /** + * @brief Determine whether tensor is SparseCsrTensor + * + * @return true + * @return false + */ + bool is_sparse_csr_tensor() const; + + /** + * @brief Determine whether tensor is StringTensor + * + * @return true + * @return false + */ + bool is_string_tensor() const; + + /* Part 3: Device and Backend methods */ + + /** + * @brief Return the place (device) of Tensor. + * + * @return Place + */ + const Place& place() const; + + /** + * @brief Determine whether the tensor device is CPU + * + * @return true + * @return false + */ + bool is_cpu() const; + + /** + * @brief Determine whether the tensor device is GPU + * + * @return true + * @return false + */ + bool is_gpu() const; + + /** + * @brief Determine whether the tensor device is GPU_PINNED + * + * @return true + * @return false + */ + bool is_gpu_pinned() const; + + /** + * @brief Determine whether the tensor device is CustomDevice + * + * @return true + * @return false + */ + bool is_custom_device() const; + + /* Part 4: Data Access methods */ + + /** + * @brief Get the memory pointer in CPU or GPU with specific data type. + * It's usually used to get the output data pointer, same as the T* data(). + * + * @tparam T + * @return T* + */ + template + T* mutable_data(); + + /** + * @brief Get the memory pointer in CPU or GPU with specific data type. + * + * It's usually used to get the output data pointer. + * This is a deprecated method and may be removed in the future! + * + * @tparam T + * @param place + * @return T* + */ + template + T* mutable_data(const Place& place); + + /** + * @brief Get the const memory pointer directly. + * It's usually used to get the output data pointer. + * + * @tparam T + * @return T* + */ + template + const T* data() const; + + /** + * @brief Get the memory pointer directly. + * It's usually used to get the mutable output data pointer. + * + * @tparam T + * @return T* + */ + template + T* data(); + + /** + * @brief Return a sub-tensor of the given tensor. + * It is usually used to extract a sub-tensor (which supports + * modifying the data of the original tensor) to perform further + * operations. + * + * @param begin_idx The index of the start row (inclusive) to slice. + * The index number begins from 0. + * @param end_idx The index of the end row (exclusive) to slice. + * The index number begins from begin_idx + 1. + * @return Tensor + */ + Tensor slice(int64_t begin_idx, int64_t end_idx) const; + + /** + * @brief Return the implemention of current Tensor. + * + * @return std::shared_ptr + */ + const std::shared_ptr& impl() const; + + /** + * @brief Set the implemention of current Tensor. + * + * @param impl + */ + void set_impl(const std::shared_ptr& impl); + + /** + * @brief Set the implemention of current Tensor. + * + * @param impl + */ + void set_impl(std::shared_ptr&& impl); + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + /** + * @brief Get the stream where the tensor is currently located + * This is a deprecated method and may be removed in the future! + * + * @return gpuStream_t + */ + gpuStream_t stream() const; +#endif + + /** + * @brief Return the name of Tensor. + * @note Used to adapt original execution mechanism and debug analysis + * in the development of new dygraph. It may be removed in the future. + * + * @return const std::string& + */ + const std::string& name() const { return name_; } + + /** + * @brief Set name of Tensor. + * @note Used to adapt original execution mechanism and debug analysis + * in the development of new dygraph. It may be removed in the future. + * + * @param const std::string& name + */ + void set_name(const std::string& name) { name_ = name; } + + /* Part 5: Data Transform methods */ + /* Alert!!!!: All copy method can only deep copy impl, autograd info only be + * copied */ + /* out of phi */ + /** + * @brief Copy the current Tensor data to the specified device + * and return the new Tensor. It's usually used to set the input tensor data. + * @note The Tensor's `copy_to` method is deprecated since version 2.3, and + * will be removed in version 2.4, please use `copy_to` method without + * template argument instead. + * reason: copying a Tensor to another device does not need to specify the + * data type template argument + * + * @tparam T + * @param target_place, the target place of which the tensor will copy to. + * @return Tensor + */ + template + Tensor copy_to(const Place& target_place) const; + + /** + * @brief Transfer the current Tensor to the specified device and return. + * + * @param place, The target place of which the tensor will copy to. + * @param blocking, Should we copy this in sync way. + * @return Tensor + */ + Tensor copy_to(const Place& place, bool blocking) const; + + /** + * @brief Transfer the source Tensor to current Tensor. + * + * @param src, the source Tensor to be copied. + * @param blocking, Should we copy this in sync way. + * @return void + */ + void copy_(const Tensor& src, const Place& target_place, bool blocking); + + /** + * @brief Cast datatype from one to another + * + * @param target_type + * @return Tensor + */ + Tensor cast(DataType target_type) const; + + /* Part 6: Status utils methods */ + + /** + * @brief Determine whether it is a meaningful Tensor + * + * @return true + * @return false + */ + bool defined() const; + + /** + * @brief Determine whether Tensor is initialized. + * + * @return true + * @return false + */ + bool initialized() const; + + /** + * @brief Determine whether Tensor is initialized. + * This is a deprecated method and may be removed in the future! + * + * @return true + * @return false + */ + bool is_initialized() const; + + /** + * @brief Reset the Tensor implementation + */ + void reset(); + + /* Part 7: Operator overloading */ + + /** + * @brief Assignment operator + * + * @param x + * @return Tensor& + */ + Tensor& operator=(const Tensor& x) &; + + /** + * @brief Move assignment operator + * + * @param x + * @return Tensor& + */ + Tensor& operator=(Tensor&& x) &; + + /* Part 8: Autograd methods */ + + /** + * @brief Get the autograd meta object pointer + * + * @return AbstractAutogradMeta* + */ + AbstractAutogradMeta* get_autograd_meta() const; + + /** + * @brief Get the shared pointer of autograd meta object + * + * @return std::shared_ptr& + */ + const std::shared_ptr& mutable_autograd_meta() const; + + /** + * @brief Set the autograd meta object + * + * @param autograd_meta + */ + void set_autograd_meta(std::shared_ptr autograd_meta); + + /* Part 9: Inplace methods */ + + /** + * @brief Increase inplace version + */ + void bump_inplace_version(); + + /** + * @brief Get current inplace version + * + * @return uint32_t + */ + uint32_t current_inplace_version(); + + /** + * @brief Reset inplace version + */ + void reset_inplace_version(bool set_to_zero = false); + + /* Part 10: Auto generated Tensor methods */ + + /* Part 11: Methods of converting underlying TensorType to each other + */ + /** + * @brief Convert DenseTensor or SparseCsrTensor to SparseCooTensor + * + * @param sparse_dim, The number of sparse dimensions + * @return Tensor + */ + Tensor to_sparse_coo(const int64_t sparse_dim) const; + + /** + * @brief Convert DenseTensor or SparseCooTensor to SparseCsrTensor + * + * @return Tensor + */ + Tensor to_sparse_csr() const; + + /** + * @brief Convert SparseCooTensor or SparseCsrTensor to DenseTensor + * + * @return Tensor + */ + Tensor to_dense() const; + + private: + /** + * [ Why use abstract TensorImpl interface here? ] + * + * We hope that the data structure at the API level of the framework can be + * unified to Tensor, but Tensor itself is heterogeneous. + * + * Tensor can generally be represented by void* and size_t, place. + * This is suitable for most scenarios including CPU, GPU, HIP, NPU, etc., + * but there are a few cases where this definition cannot be described, + * such as the Tensor representation in third-party lib such as Metal, + * OpenCL, etc., as well as some special Tensor implementations, including + * Tensor containing only one Scalar value, or Tensor representing String, + * etc. + * + * Therefore, we hope to use a unified interface to shield the underlying + * heterogeneous Tensor implementation, so that the API level can be unified + * to one `Tensor`. + */ + std::shared_ptr impl_{nullptr}; + + /** + * [ Why need abstract AbstractAutogradMeta here? ] + * + * Dynamic graphs need to hold backward information + * + * [ Why AutogradMeta not in TensorImpl? ] + * + * 1. AutogradMeta is only used in dynamic graph, It is execution-related + * information, not Tensor data description-related information. + * 2. Kernel calculation does not require AutogradMeta. + */ + std::shared_ptr autograd_meta_{nullptr}; + + /** + * Tensor name: used to adapt original execution mechanism and debug analysis + * in the development of new dygraph. It may be removed in the future. + */ + std::string name_{""}; +}; + +} // namespace experimental +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/all_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/all_context.h new file mode 100644 index 0000000000000000000000000000000000000000..392df09fcffd896c8e1926464eb35929b355adbc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/all_context.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +// Note: Some scenarios need to include all types of Context declarations. +// In order to avoid including the header files of each backend in turn, +// add this header file +// Note: Limit the entry of DeviceContext to backends to avoid multiple include +// path replacement after implementing phi DeviceContext + +#include "paddle/phi/backends/cpu/cpu_context.h" +#include "paddle/phi/backends/custom/custom_context.h" +#include "paddle/phi/backends/gpu/gpu_context.h" +#ifdef PADDLE_WITH_XPU +#include "paddle/phi/backends/xpu/xpu_context.h" +#endif + +#ifndef PADDLE_WITH_CUSTOM_KERNEL +// TODO(wilber): DeviceContextPool nees include fluid file. +#include "paddle/fluid/platform/device_context.h" + +namespace phi { +using DeviceContextPool = paddle::platform::DeviceContextPool; +} // namespace phi +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/c_comm_lib.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/c_comm_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..f2987996cbe581779c3aebf20f8bce0b0f9c787f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/c_comm_lib.h @@ -0,0 +1,60 @@ +// Copyright (c) 2022 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. + +#pragma once +#include + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/errors.h" +#include "paddle/phi/core/macros.h" + +namespace phi { +namespace ccl { +using CCLComm = void*; +using CCLRootId = std::vector; + +enum CCLReduceOp { SUM = 0, AVG, MAX, MIN, PRODUCT }; +enum CCLDataType { + CCL_DATA_TYPE_FP64 = 0, + CCL_DATA_TYPE_FP32, + CCL_DATA_TYPE_FP16, + CCL_DATA_TYPE_INT64, + CCL_DATA_TYPE_INT32, + CCL_DATA_TYPE_INT16, + CCL_DATA_TYPE_INT8 +}; + +inline CCLDataType ToCCLDataType(paddle::experimental::DataType type) { + if (type == paddle::experimental::DataType::FLOAT64) { + return CCL_DATA_TYPE_FP64; + } else if (type == paddle::experimental::DataType::FLOAT32) { + return CCL_DATA_TYPE_FP32; + } else if (type == paddle::experimental::DataType::FLOAT16) { + return CCL_DATA_TYPE_FP16; + } else if (type == paddle::experimental::DataType::INT64) { + return CCL_DATA_TYPE_INT64; + } else if (type == paddle::experimental::DataType::INT32) { + return CCL_DATA_TYPE_INT32; + } else if (type == paddle::experimental::DataType::INT8) { + return CCL_DATA_TYPE_INT8; + } else { + PADDLE_THROW( + phi::errors::Unimplemented("This datatype in CCL is not supported.")); + } +} + +} // namespace ccl +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/callback_manager.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/callback_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..2bb26745288dfebf7cb669e631b691c490fcbfd6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/callback_manager.h @@ -0,0 +1,58 @@ +// Copyright (c) 2022 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. + +#pragma once + +#ifdef PADDLE_WITH_CUDA +#include +#include +#endif + +#ifdef PADDLE_WITH_HIP +#include +#endif + +#include +#include // NOLINT +#include +#include // NOLINT + +class ThreadPool; + +namespace phi { + +namespace stream { +class Stream; +} // namespace stream + +// NOTE(zjl): clean CallbackManager to make compilation faster +// Make CallbackManager thread-safe +class CallbackManager { + public: + explicit CallbackManager(stream::Stream* stream); + + ~CallbackManager() = default; + + void AddCallback(std::function callback) const; + + void Wait() const; + + private: + stream::Stream* stream_; + mutable std::shared_ptr<::ThreadPool> thread_pool_; + mutable std::mutex mtx_; + mutable std::future last_future_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/cpu_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/cpu_context.h new file mode 100644 index 0000000000000000000000000000000000000000..58548b2e04e024ab9ab6a59b25c583bfa0cba3c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/cpu_context.h @@ -0,0 +1,48 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/backends/cpu/forwards.h" +#include "paddle/phi/core/device_context.h" + +// TODO(wilber): Do we need to use place in phi kernel? +#include "paddle/phi/common/place.h" + +namespace phi { + +class PADDLE_API CPUContext : public DeviceContext { + public: + CPUContext(); + CPUContext(CPUContext&&); + CPUContext& operator=(CPUContext&&); + explicit CPUContext(const Place&); + virtual ~CPUContext(); + Eigen::DefaultDevice* eigen_device() const; + const Place& GetPlace() const override; + + protected: + // NOTE: External users manage resources. Used in inference scenarios. + // The Set interface is for inference only, DeviceContext will mark the + // resource as external, and will not delete any resource when destructing. + void SetEigenDevice(Eigen::DefaultDevice* device); + + private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/forwards.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/forwards.h new file mode 100644 index 0000000000000000000000000000000000000000..202a414893e43b1399475db38559210646d08dc1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/cpu/forwards.h @@ -0,0 +1,21 @@ +/* Copyright (c) 2022 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. */ + +// Forward-declares. +#pragma once + +// Forward declaration of Eigen DefaultDevice types. +namespace Eigen { +struct DefaultDevice; +} // namespace Eigen diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/custom_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/custom_context.h new file mode 100644 index 0000000000000000000000000000000000000000..57be8534fa95499a26d914feaa42d872ced86873 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/custom_context.h @@ -0,0 +1,51 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +class CustomContext : public DeviceContext { + public: + explicit CustomContext(const CustomPlace&); + + virtual ~CustomContext(); + + const Place& GetPlace() const override; + + /*! \brief Return stream in the device context. */ + void* stream() const; + + // Wait for all operations completion in the stream. + void Wait() const override; + + public: + // NOTE: DeviceContext hold resources. Used in training scenarios. + // The interface used by the training scene, DeviceContext will initialize + // all resources and delete them when destructing. + void Init(); + + private: + CustomContext(); + + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/fake_cpu_device.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/fake_cpu_device.h new file mode 100644 index 0000000000000000000000000000000000000000..1fcbeab89ab30e1a8db64ecac933fe77fecd4f0f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/fake_cpu_device.h @@ -0,0 +1,295 @@ +// Copyright (c) 2022 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. + +#pragma once +#include "paddle/phi/backends/device_ext.h" + +constexpr size_t global_total_memory = 1024 * 1024UL; +static size_t global_free_memory = global_total_memory; + +C_Status Init() { return C_SUCCESS; } + +C_Status InitDevice(const C_Device device) { return C_SUCCESS; } + +C_Status SetDevice(const C_Device device) { return C_SUCCESS; } + +C_Status GetDevice(const C_Device device) { + device->id = 0; + return C_SUCCESS; +} + +C_Status DestroyDevice(const C_Device device) { return C_SUCCESS; } + +C_Status Finalize() { return C_SUCCESS; } + +C_Status GetDevicesCount(size_t *count) { + *count = 1; + return C_SUCCESS; +} + +C_Status GetDevicesList(size_t *device) { + *device = 0; + return C_SUCCESS; +} + +C_Status MemCpy(const C_Device device, + void *dst, + const void *src, + size_t size) { + memcpy(dst, src, size); + return C_SUCCESS; +} + +C_Status AsyncMemCpy(const C_Device device, + C_Stream stream, + void *dst, + const void *src, + size_t size) { + memcpy(dst, src, size); + return C_SUCCESS; +} + +C_Status Allocate(const C_Device device, void **ptr, size_t size) { + if (global_free_memory >= size) { + *ptr = malloc(size); + global_free_memory -= size; + return C_SUCCESS; + } else { + *ptr = nullptr; + return C_FAILED; + } +} + +C_Status Deallocate(const C_Device device, void *ptr, size_t size) { + free(ptr); + global_free_memory += size; + return C_SUCCESS; +} + +C_Status CreateStream(const C_Device device, C_Stream *stream) { + return C_SUCCESS; +} + +C_Status DestroyStream(const C_Device device, C_Stream stream) { + return C_SUCCESS; +} + +C_Status CreateEvent(const C_Device device, C_Event *event) { + return C_SUCCESS; +} + +C_Status RecordEvent(const C_Device device, C_Stream stream, C_Event event) { + return C_SUCCESS; +} + +C_Status DestroyEvent(const C_Device device, C_Event event) { + return C_SUCCESS; +} + +C_Status SyncDevice(const C_Device device) { return C_SUCCESS; } + +C_Status SyncStream(const C_Device device, C_Stream stream) { + return C_SUCCESS; +} + +C_Status SyncEvent(const C_Device device, C_Event event) { return C_SUCCESS; } + +C_Status StreamWaitEvent(const C_Device device, + C_Stream stream, + C_Event event) { + return C_SUCCESS; +} + +C_Status VisibleDevices(size_t *devices) { return C_SUCCESS; } + +C_Status DeviceMemStats(const C_Device device, + size_t *total_memory, + size_t *free_memory) { + *total_memory = global_total_memory; + *free_memory = global_free_memory; + return C_SUCCESS; +} + +C_Status DeviceMinChunkSize(const C_Device device, size_t *size) { + *size = 4 * 1024; + return C_SUCCESS; +} + +C_Status DeviceMaxChunkSize(const C_Device device, size_t *size) { + *size = 64 * 1024; + return C_SUCCESS; +} + +C_Status DeviceMaxAllocSize(const C_Device device, size_t *size) { + *size = global_total_memory * 0.95; + return C_SUCCESS; +} + +C_Status XcclGetUniqueIdSize(size_t *size) { + *size = sizeof(size_t); + return C_SUCCESS; +} +C_Status XcclGetUniqueId(C_CCLRootId *unique_id) { return C_SUCCESS; } +C_Status XcclCommInitRank(size_t ranks, + C_CCLRootId *unique_id, + size_t rank, + C_CCLComm *comm) { + return C_SUCCESS; +} +C_Status XcclDestroyComm(C_CCLComm comm) { return C_SUCCESS; } +C_Status XcclAllReduce(void *send_buf, + void *recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclBroadcast(void *buf, + size_t count, + C_DataType data_type, + size_t root, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclReduce(void *send_buf, + void *recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + size_t root_id, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclAllGather(void *send_buf, + void *recv_buf, + size_t count, + C_DataType data_type, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclReduceScatter(void *send_buf, + void *recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclGroupStart() { return C_SUCCESS; } +C_Status XcclGroupEnd() { return C_SUCCESS; } +C_Status XcclSend(void *send_buf, + size_t count, + C_DataType data_type, + size_t dest_rank, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} +C_Status XcclRecv(void *recv_buf, + size_t count, + C_DataType data_type, + size_t src_rank, + C_CCLComm comm, + C_Stream stream) { + return C_SUCCESS; +} + +C_Status BlasAXPBY(const C_Device device, + C_Stream stream, + C_DataType dtype, + size_t numel, + float alpha, + void *x, + float beta, + void *y) { + return C_SUCCESS; +} + +#define DEVICE_TYPE "FakeCPU" +#define SUB_DEVICE_TYPE "V100" + +void InitFakeCPUDevice(CustomRuntimeParams *params) { + params->device_type = const_cast(DEVICE_TYPE); + params->sub_device_type = const_cast(SUB_DEVICE_TYPE); + params->version.major = PADDLE_CUSTOM_RUNTIME_MAJOR_VERSION; + params->version.minor = PADDLE_CUSTOM_RUNTIME_MINOR_VERSION; + params->version.patch = PADDLE_CUSTOM_RUNTIME_PATCH_VERSION; + + memset(reinterpret_cast(params->interface), + 0, + sizeof(C_DeviceInterface)); + + params->interface->initialize = Init; + params->interface->finalize = Finalize; + + params->interface->init_device = InitDevice; + params->interface->set_device = SetDevice; + params->interface->get_device = GetDevice; + params->interface->deinit_device = DestroyDevice; + + params->interface->create_stream = CreateStream; + params->interface->destroy_stream = DestroyStream; + + params->interface->create_event = CreateEvent; + params->interface->destroy_event = DestroyEvent; + params->interface->record_event = RecordEvent; + + params->interface->synchronize_device = SyncDevice; + params->interface->synchronize_stream = SyncStream; + params->interface->synchronize_event = SyncEvent; + params->interface->stream_wait_event = StreamWaitEvent; + + params->interface->memory_copy_h2d = MemCpy; + params->interface->memory_copy_d2d = MemCpy; + params->interface->memory_copy_d2h = MemCpy; + params->interface->async_memory_copy_h2d = AsyncMemCpy; + params->interface->async_memory_copy_d2d = AsyncMemCpy; + params->interface->async_memory_copy_d2h = AsyncMemCpy; + params->interface->device_memory_allocate = Allocate; + params->interface->host_memory_allocate = Allocate; + params->interface->unified_memory_allocate = Allocate; + params->interface->device_memory_deallocate = Deallocate; + params->interface->host_memory_deallocate = Deallocate; + params->interface->unified_memory_deallocate = Deallocate; + + params->interface->get_device_count = GetDevicesCount; + params->interface->get_device_list = GetDevicesList; + params->interface->device_memory_stats = DeviceMemStats; + + params->interface->device_max_chunk_size = DeviceMaxChunkSize; + params->interface->device_min_chunk_size = DeviceMinChunkSize; + params->interface->device_max_alloc_size = DeviceMaxAllocSize; + + params->interface->xccl_get_unique_id_size = XcclGetUniqueIdSize; + params->interface->xccl_get_unique_id = XcclGetUniqueId; + params->interface->xccl_all_reduce = XcclAllReduce; + params->interface->xccl_all_gather = XcclAllGather; + params->interface->xccl_broadcast = XcclBroadcast; + params->interface->xccl_comm_init_rank = XcclCommInitRank; + params->interface->xccl_destroy_comm = XcclDestroyComm; + params->interface->xccl_group_end = XcclGroupEnd; + params->interface->xccl_group_start = XcclGroupStart; + params->interface->xccl_reduce = XcclReduce; + params->interface->xccl_reduce_scatter = XcclReduceScatter; + params->interface->xccl_send = XcclSend; + params->interface->xccl_recv = XcclRecv; + + params->interface->blas_axpby = BlasAXPBY; +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/trace_event.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/trace_event.h new file mode 100644 index 0000000000000000000000000000000000000000..3315c7d705b8f6f1308766447ab7c6f5278194a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/custom/trace_event.h @@ -0,0 +1,371 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include + +namespace paddle { +namespace platform { + +enum class TracerEventType { + // Used to mark operator record + Operator = 0, + // Used to mark dataloader record + Dataloader = 1, + // Used to mark profile step record + ProfileStep = 2, + // Used to mark cuda runtime record returned by cupti + CudaRuntime = 3, + // Used to mark kernel computation record returned by cupti + Kernel = 4, + // Used to mark memcpy record returned by cupti + Memcpy = 5, + // Used to mark memset record returned by cupti + Memset = 6, + // Used to mark record defined by user + UserDefined = 7, + // Used to mark operator detail, (such as infer shape, compute) + OperatorInner = 8, + // Used to mark model training or testing perspective, forward process + Forward = 9, + // Used to mark model training perspective, backward process + Backward = 10, + // Used to mark model training perspective, optimization process + Optimization = 11, + // Used to mark distributed training perspective + Communication = 12, + // Used to mark python api + PythonOp = 13, + // Used to mark python level userdefined + PythonUserDefined = 14, + // Used to mark mlu runtime record returned by cnpapi + MluRuntime = 15, + // A flag to denote the number of current types + NumTypes +}; + +enum class TracerMemEventType { + // Used to mark memory allocation which is managed by paddle + Allocate = 0, + // Used to mark memory free which is managed by paddle + Free = 1, + // Used to mark reserved memory allocation which is applied from device. + ReservedAllocate = 2, + // Used to mark reserved memory free which is released to device. + ReservedFree = 3, + // A flag to denote the number of current types + NumTypes +}; + +struct KernelEventInfo { + // The X-dimension block size for the kernel. + uint32_t block_x; + // The Y-dimension block size for the kernel. + uint32_t block_y; + // The Z-dimension grid size for the kernel. + uint32_t block_z; + // X-dimension of a grid. + uint32_t grid_x; + // Y-dimension of a grid. + uint32_t grid_y; + // Z-dimension of a grid. + uint32_t grid_z; + // The dynamic shared memory reserved for the kernel, in bytes. + uint32_t dynamic_shared_memory; + // The static shared memory allocated for the kernel, in bytes. + uint32_t static_shared_memory; + // The number of registers required for each thread executing the kernel. + uint32_t registers_per_thread; + // The amount of local memory reserved for each thread, in bytes. + uint32_t local_memory_per_thread; + // The total amount of local memory reserved for the kernel, in bytes. + uint32_t local_memory_total; + // The timestamp when the kernel is queued up in the command buffer, in ns. + // This timestamp is not collected by default. Use API + // cuptiActivityEnableLatencyTimestamps() to enable collection. + uint64_t queued; + // The timestamp when the command buffer containing the kernel launch is + // submitted to the GPU, in ns. + // This timestamp is not collected by default. Use API + // cuptiActivityEnableLatencyTimestamps() to enable collection. + uint64_t submitted; + // The completed timestamp for the kernel execution, in ns. + uint64_t completed; + + float blocks_per_sm; + float warps_per_sm; + // theoretical achieved occupancy + float occupancy; +}; + +static constexpr size_t kMemKindMaxLen = 50; + +struct MemcpyEventInfo { + // The number of bytes transferred by the memory copy. + uint64_t num_bytes; + // The kind of the memory copy. + // Each kind represents the source and destination targets of a memory copy. + // Targets are host, device, and array. Refer to CUpti_ActivityMemcpyKind + char copy_kind[kMemKindMaxLen]; + // The source memory kind read by the memory copy. + // Each kind represents the type of the memory accessed by a memory + // operation/copy. Refer to CUpti_ActivityMemoryKind + char src_kind[kMemKindMaxLen]; + // The destination memory kind read by the memory copy. + char dst_kind[kMemKindMaxLen]; +}; + +struct MemsetEventInfo { + // The number of bytes being set by the memory set. + uint64_t num_bytes; + // The memory kind of the memory set. Refer to CUpti_ActivityMemoryKind + char memory_kind[kMemKindMaxLen]; + // the value being assigned to memory by the memory set. + uint32_t value; +}; + +struct OperatorSupplementEvent { + OperatorSupplementEvent() = default; + OperatorSupplementEvent( + uint64_t timestamp_ns, + const std::string& op_type, + const std::map>>& + input_shapes, + const std::map>& dtypes, + const std::string& callstack, + uint64_t process_id, + uint64_t thread_id) + : timestamp_ns(timestamp_ns), + op_type(op_type), + input_shapes(input_shapes), + dtypes(dtypes), + callstack(callstack), + process_id(process_id), + thread_id(thread_id) {} + // timestamp of the record + uint64_t timestamp_ns; + // op type name + std::string op_type; + // input shapes + std::map>> input_shapes; + std::map> dtypes; + // call stack + std::string callstack; + // process id of the record + uint64_t process_id; + // thread id of the record + uint64_t thread_id; +}; + +struct HostTraceEvent { + HostTraceEvent() = default; + HostTraceEvent(const std::string& name, + TracerEventType type, + uint64_t start_ns, + uint64_t end_ns, + uint64_t process_id, + uint64_t thread_id) + : name(name), + type(type), + start_ns(start_ns), + end_ns(end_ns), + process_id(process_id), + thread_id(thread_id) {} + // record name + std::string name; + // record type, one of TracerEventType + TracerEventType type; + // start timestamp of the record + uint64_t start_ns; + // end timestamp of the record + uint64_t end_ns; + // process id of the record + uint64_t process_id; + // thread id of the record + uint64_t thread_id; +}; + +struct RuntimeTraceEvent { + RuntimeTraceEvent() = default; + RuntimeTraceEvent(const std::string& name, + uint64_t start_ns, + uint64_t end_ns, + uint64_t process_id, + uint64_t thread_id, + uint32_t correlation_id, + uint32_t callback_id) + : name(name), + start_ns(start_ns), + end_ns(end_ns), + process_id(process_id), + thread_id(thread_id), + correlation_id(correlation_id), + callback_id(callback_id) {} + + // record name + std::string name; + // record type, one of TracerEventType + TracerEventType type{TracerEventType::CudaRuntime}; + // start timestamp of the record + uint64_t start_ns; + // end timestamp of the record + uint64_t end_ns; + // process id of the record + uint64_t process_id; + // thread id of the record + uint64_t thread_id; + // correlation id, used for correlating async activities happened on device + uint32_t correlation_id; + // callback id, used to identify which cuda runtime api is called + uint32_t callback_id; +}; + +struct DeviceTraceEvent { + DeviceTraceEvent() = default; + DeviceTraceEvent(const std::string& name, + TracerEventType type, + uint64_t start_ns, + uint64_t end_ns, + uint64_t device_id, + uint64_t context_id, + uint64_t stream_id, + uint32_t correlation_id, + const KernelEventInfo& kernel_info) + : name(name), + type(type), + start_ns(start_ns), + end_ns(end_ns), + device_id(device_id), + context_id(context_id), + stream_id(stream_id), + correlation_id(correlation_id), + kernel_info(kernel_info) {} + DeviceTraceEvent(const std::string& name, + TracerEventType type, + uint64_t start_ns, + uint64_t end_ns, + uint64_t device_id, + uint64_t context_id, + uint64_t stream_id, + uint32_t correlation_id, + const MemcpyEventInfo& memcpy_info) + : name(name), + type(type), + start_ns(start_ns), + end_ns(end_ns), + device_id(device_id), + context_id(context_id), + stream_id(stream_id), + correlation_id(correlation_id), + memcpy_info(memcpy_info) {} + DeviceTraceEvent(const std::string& name, + TracerEventType type, + uint64_t start_ns, + uint64_t end_ns, + uint64_t device_id, + uint64_t context_id, + uint64_t stream_id, + uint32_t correlation_id, + const MemsetEventInfo& memset_info) + : name(name), + type(type), + start_ns(start_ns), + end_ns(end_ns), + device_id(device_id), + context_id(context_id), + stream_id(stream_id), + correlation_id(correlation_id), + memset_info(memset_info) {} + // record name + std::string name; + // record type, one of TracerEventType + TracerEventType type; + // start timestamp of the record + uint64_t start_ns; + // end timestamp of the record + uint64_t end_ns; + // device id + uint64_t device_id; + // context id + uint64_t context_id; + // stream id + uint64_t stream_id; + // correlation id, used for correlating async activities happened on device + uint32_t correlation_id; + // union, specific device record type has different detail information + union { + // used for TracerEventType::Kernel + KernelEventInfo kernel_info; + // used for TracerEventType::Memcpy + MemcpyEventInfo memcpy_info; + // used for TracerEventType::Memset + MemsetEventInfo memset_info; + }; +}; + +struct MemTraceEvent { + MemTraceEvent() = default; + MemTraceEvent(uint64_t timestamp_ns, + uint64_t addr, + TracerMemEventType type, + uint64_t process_id, + uint64_t thread_id, + int64_t increase_bytes, + const std::string& place, + uint64_t current_allocated, + uint64_t current_reserved, + uint64_t peak_allocated, + uint64_t peak_reserved) + : timestamp_ns(timestamp_ns), + addr(addr), + type(type), + process_id(process_id), + thread_id(thread_id), + increase_bytes(increase_bytes), + place(place), + current_allocated(current_allocated), + current_reserved(current_reserved), + peak_allocated(peak_allocated), + peak_reserved(peak_reserved) {} + + // timestamp of the record + uint64_t timestamp_ns; + // memory addr of allocation or free + uint64_t addr; + // memory manipulation type + TracerMemEventType type; + // process id of the record + uint64_t process_id; + // thread id of the record + uint64_t thread_id; + // increase bytes after this manipulation, allocation for sign +, free for + // sign - + int64_t increase_bytes; + // place + std::string place; + // current total allocated memory + uint64_t current_allocated; + // current total reserved memory + uint64_t current_reserved; + // current peak allocated memory + uint64_t peak_allocated; + // current peak reserved memory + uint64_t peak_reserved; +}; + +} // namespace platform +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_base.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_base.h new file mode 100644 index 0000000000000000000000000000000000000000..a0d95349196e09a9dacb0cfebfac4616fcd1ea05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_base.h @@ -0,0 +1,278 @@ +// Copyright (c) 2022 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. + +#pragma once +#ifdef PADDLE_WITH_CUSTOM_DEVICE +#include + +#include "paddle/phi/backends/c_comm_lib.h" +#include "paddle/phi/backends/event.h" +#include "paddle/phi/backends/stream.h" + +namespace paddle { +namespace platform { +class TraceEventCollector; +} // namespace platform +} // namespace paddle + +namespace phi { + +class DeviceInterface { // Driver / Runtime + public: + DeviceInterface(const std::string& type, uint8_t priority, bool is_custom) + : type_(type), priority_(priority), is_custom_(is_custom) {} + uint8_t Priority() { return priority_; } + std::string Type() { return type_; } + bool IsCustom() { return is_custom_; } + + virtual ~DeviceInterface() {} + + // Info + virtual size_t GetComputeCapability(); + + virtual size_t GetRuntimeVersion(); + + virtual size_t GetDriverVersion(); + + // Platform + //! Initialize + virtual void Initialize(); + + //! Finalize + virtual void Finalize(); + + // Device + virtual size_t GetDeviceCount() = 0; + virtual std::vector GetDeviceList() = 0; + + //! Wait for compute device to finish. + virtual void SynchronizeDevice(size_t dev_id); + + //! Initialize device. + virtual void InitDevice(size_t dev_id); + + //! Deinitialize device. + virtual void DeInitDevice(size_t dev_id); + + // ! Set device to be used. + virtual void SetDevice(size_t dev_id); + + // ! Returns which device is currently being used. + virtual int GetDevice(); + + // Stream + // ! Create an asynchronous stream + virtual void CreateStream( + size_t dev_id, + stream::Stream* stream, + const stream::Stream::Priority& priority = + stream::Stream::Priority::kNormal, + const stream::Stream::Flag& flag = stream::Stream::Flag::kDefaultFlag); + + // ! Destroys an asynchronous stream. + virtual void DestroyStream(size_t dev_id, stream::Stream* stream); + + // ! Waits for stream tasks to complete. + virtual void SynchronizeStream(size_t dev_id, const stream::Stream* stream); + + // ! Queries an asynchronous stream for completion status. + virtual bool QueryStream(size_t dev_id, const stream::Stream* stream); + + // ! Add a callback to a compute stream. + virtual void AddCallback(size_t dev_id, + stream::Stream* stream, + stream::Stream::Callback* callback); + + // Event + // ! Create an event. + virtual void CreateEvent(size_t dev_id, + event::Event* event, + event::Event::Flag flags); + + // ! Destroy an event. + virtual void DestroyEvent(size_t dev_id, event::Event* event); + + // ! Records an event. + virtual void RecordEvent(size_t dev_id, + const event::Event* event, + const stream::Stream* stream); + + // ! Waits for event to complete. + virtual void SynchronizeEvent(size_t dev_id, const event::Event* event); + // ! Queries an event for completion status. + virtual bool QueryEvent(size_t dev_id, const event::Event* event); + + // ! Make a compute stream wait on an event + virtual void StreamWaitEvent(size_t dev_id, + const stream::Stream* stream, + const event::Event* event); + + // Memory + virtual void MemoryCopyH2D(size_t dev_id, + void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + virtual void MemoryCopyD2H(size_t dev_id, + void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + virtual void MemoryCopyD2D(size_t dev_id, + void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + virtual void MemoryCopyP2P(const Place& dst_place, + void* dst, + size_t src_id, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + virtual void* MemoryAllocate(size_t dev_id, size_t size); + + virtual void MemoryDeallocate(size_t dev_id, void* ptr, size_t size); + + virtual void* MemoryAllocateHost(size_t dev_id, size_t size); + + virtual void MemoryDeallocateHost(size_t dev_id, void* ptr, size_t size); + + virtual void* MemoryAllocateUnified(size_t dev_id, size_t size); + + virtual void MemoryDeallocateUnified(size_t dev_id, void* ptr, size_t size); + + virtual void MemorySet(size_t dev_id, void* ptr, uint8_t value, size_t size); + + virtual void MemoryStats(size_t dev_id, size_t* total, size_t* free); + + virtual size_t GetMinChunkSize(size_t dev_id); + + virtual size_t GetInitAllocSize(size_t dev_id); + + virtual size_t GetReallocSize(size_t dev_id); + + virtual size_t GetMaxAllocSize(size_t dev_id); + + virtual size_t GetMaxChunkSize(size_t dev_id); + + virtual size_t GetExtraPaddingSize(size_t dev_id); + + // CCL + virtual void CCLDestroyComm(ccl::CCLComm ccl_comm); + + virtual void CCLCommInitRank(size_t num_ranks, + ccl::CCLRootId* root_id, + size_t rank_id, + ccl::CCLComm* ccl_comm); + + virtual void CCLGetUniqueId(ccl::CCLRootId* root_id); + + virtual void CCLBroadcast(void* data, + size_t num, + ccl::CCLDataType data_type, + size_t root, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + + virtual void CCLAllReduce(void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp reduce_op, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + virtual void CCLReduce(void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp reduce_op, + size_t root_id, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + virtual void CCLAllGather(void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + virtual void CCLReduceScatter(void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp op, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + virtual void CCLGroupStart(); + virtual void CCLGroupEnd(); + virtual void CCLSend(void* sendbuf, + size_t num, + ccl::CCLDataType data_type, + size_t dst_rank, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + virtual void CCLRecv(void* recvbuf, + size_t num, + ccl::CCLDataType data_type, + size_t src_rank, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + + // blas + virtual void BlasAXPBY(size_t dev_id, + const stream::Stream& stream, + paddle::experimental::DataType dtype, + size_t numel, + float alpha, + void* x, + float beta, + void* y); + + // profiler + virtual void ProfilerInitialize( + paddle::platform::TraceEventCollector* collector, void** user_data); + + virtual void ProfilerFinalize( + paddle::platform::TraceEventCollector* collector, void* user_data); + + virtual void ProfilerPrepareTracing( + paddle::platform::TraceEventCollector* collector, void* user_data); + + virtual void ProfilerStartTracing( + paddle::platform::TraceEventCollector* collector, void* user_data); + + virtual void ProfilerStopTracing( + paddle::platform::TraceEventCollector* collector, void* user_data); + + virtual void ProfilerCollectTraceData( + paddle::platform::TraceEventCollector* collector, + uint64_t start_ns, + void* user_data); + + private: + const std::string type_; + const uint8_t priority_; + const bool is_custom_; + + size_t AllocSize(size_t dev_id, bool realloc); + + size_t AvailableAllocSize(size_t dev_id); +}; + +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_ext.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_ext.h new file mode 100644 index 0000000000000000000000000000000000000000..6e4a6fcb6632f8bd42003c4ec88c70fa21fe4364 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_ext.h @@ -0,0 +1,714 @@ +// Copyright (c) 2022 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. + +#pragma once +#if !defined(_WIN32) && !defined(__APPLE__) +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define PADDLE_CUSTOM_RUNTIME_MAJOR_VERSION 0 +#define PADDLE_CUSTOM_RUNTIME_MINOR_VERSION 1 +#define PADDLE_CUSTOM_RUNTIME_PATCH_VERSION 1 + +typedef enum { + UNDEFINED = 0, + BOOL, + UINT8, + UINT16, + UINT32, + UINT64, + INT8, + INT16, + INT32, + INT64, + FLOAT16, + FLOAT32, + FLOAT64, + BFLOAT16, +} C_DataType; + +typedef enum { + ANY = 0, + NHWC, + NCHW, + NCDHW, + NDHWC, + NUM_DATA_LAYOUTS, + ALL_LAYOUT = ANY, +} C_DataLayout; + +typedef enum { + C_SUCCESS = 0, // success + C_WARNING, // results may not meet expectation (such as an asynchronous + // interface is actually synchronous) + C_FAILED, // resource exhausted/query failed + C_ERROR, // invalid argument/wrong usage/uninitialized + C_INTERNAL_ERROR // plugin error +} C_Status; + +typedef struct C_Device_st { + int id; +} * C_Device; + +typedef struct C_Stream_st* C_Stream; + +typedef struct C_Event_st* C_Event; + +typedef void (*C_Callback)(C_Device device, + C_Stream stream, + void* user_data, + C_Status* status); + +typedef struct { + size_t sz; + void* data; +} C_CCLRootId; + +typedef struct C_CCLComm_st* C_CCLComm; + +typedef enum { SUM = 0, AVG, MAX, MIN, PRODUCT } C_CCLReduceOp; + +typedef struct C_Profiler_st* C_Profiler; + +void profiler_add_runtime_trace_event(C_Profiler prof, void* event); + +void profiler_add_device_trace_event(C_Profiler prof, void* event); + +struct C_DeviceInterface { + // Core fill it and plugin must to check it + size_t size; + + /////////////////////// + // device manage api // + /////////////////////// + + /** + * @brief Initialize hardware + * + */ + C_Status (*initialize)(); + + /** + * @brief Deinitialize hardware + * + */ + C_Status (*finalize)(); + + /** + * @brief Initialize device + * + * @param[C_Device] device Core fill it with a logical id, and then plugin + * must replace it with a physical id + */ + C_Status (*init_device)(const C_Device device); + + /** + * @brief Set current device + * + * @param[C_Device] device Core fill it with a physical id + */ + C_Status (*set_device)(const C_Device device); + + /** + * @brief Get current device + * + * @param[C_Device] device Plugin fill it with a physical id + */ + C_Status (*get_device)(const C_Device device); + + /** + * @brief Deinitialize device + * + * @param[C_Device] device Core fill it with a physical id + */ + C_Status (*deinit_device)(const C_Device device); + + /** + * @brief Create a stream + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream*] stream Plugin create a stream and fill it + */ + C_Status (*create_stream)(const C_Device device, C_Stream* stream); + + /** + * @brief Destroy a stream + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + */ + C_Status (*destroy_stream)(const C_Device device, C_Stream stream); + + /** + * @brief Query a stream + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + */ + C_Status (*query_stream)(const C_Device device, C_Stream stream); + + /** + * @brief Add a callback to stream + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[C_Callback] callback + * @param[void*] user_data + */ + C_Status (*stream_add_callback)(const C_Device device, + C_Stream stream, + C_Callback callback, + void* user_data); + + /** + * @brief Create an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Event*] event Plugin create an event and fill it + */ + C_Status (*create_event)(const C_Device device, C_Event* event); + + /** + * @brief Record an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[C_Event] event + */ + C_Status (*record_event)(const C_Device device, + C_Stream stream, + C_Event event); + + /** + * @brief Destroy an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Event] event + */ + C_Status (*destroy_event)(const C_Device device, C_Event event); + + /** + * @brief Query an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Event] event + */ + C_Status (*query_event)(const C_Device device, C_Event event); + + /** + * @brief Synchronize a device + * + * @param[C_Device] device Core fill it with a physical id + */ + C_Status (*synchronize_device)(const C_Device device); + + /** + * @brief Synchronize a stream + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + */ + C_Status (*synchronize_stream)(const C_Device device, C_Stream stream); + + /** + * @brief Synchronize an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Event] event + */ + C_Status (*synchronize_event)(const C_Device device, C_Event event); + + /** + * @brief Make a stream wait on an event + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[C_Event] event + */ + C_Status (*stream_wait_event)(const C_Device device, + C_Stream stream, + C_Event event); + + void* reserved_dev_api[8]; + + /////////////////////// + // memory manage api // + /////////////////////// + + /** + * @brief Device memory allocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void**] ptr Plugin allocate an address and fill it + * @param[size_t] size + */ + C_Status (*device_memory_allocate)(const C_Device device, + void** ptr, + size_t size); + + /** + * @brief Device memory deallocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] ptr + * @param[size_t] size + */ + C_Status (*device_memory_deallocate)(const C_Device device, + void* ptr, + size_t size); + + /** + * @brief Device memory set + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] ptr + * @param[unsigned char] value + * @param[size_t] size + */ + C_Status (*device_memory_set)(const C_Device device, + void* ptr, + unsigned char value, + size_t size); + + /** + * @brief Host memory allocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void**] ptr Plugin allocate an address and fill it + * @param[size_t] size + */ + C_Status (*host_memory_allocate)(const C_Device device, + void** ptr, + size_t size); + + /** + * @brief Host memory deallocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] ptr + * @param[size_t] size + */ + C_Status (*host_memory_deallocate)(const C_Device device, + void* ptr, + size_t size); + + /** + * @brief Unified memory allocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void**] ptr Plugin allocate an address and fill it + * @param[size_t] size + */ + C_Status (*unified_memory_allocate)(const C_Device device, + void** ptr, + size_t size); + + /** + * @brief Unified memory deallocate + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] ptr + * @param[size_t] size + */ + C_Status (*unified_memory_deallocate)(const C_Device device, + void* ptr, + size_t size); + + /** + * @brief Memory copy from host to device + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*memory_copy_h2d)(const C_Device device, + void* dst, + const void* src, + size_t size); + + /** + * @brief Memory copy from device to host + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*memory_copy_d2h)(const C_Device device, + void* dst, + const void* src, + size_t size); + + /** + * @brief Memory copy from device to device + * + * @param[C_Device] device Core fill it with a physical id + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*memory_copy_d2d)(const C_Device device, + void* dst, + const void* src, + size_t size); + + /** + * @brief Peer memory copy from device to device + * + * @param[C_Device] dst_device Core fill it with a physical id + * @param[C_Device] src_device Core fill it with a physical id + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*memory_copy_p2p)(const C_Device dst_device, + const C_Device src_device, + void* dst, + const void* src, + size_t size); + + /** + * @brief Asynchonrize memory copy from host to device + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*async_memory_copy_h2d)(const C_Device device, + C_Stream stream, + void* dst, + const void* src, + size_t size); + + /** + * @brief Asynchonrize memory copy from device to host + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*async_memory_copy_d2h)(const C_Device device, + C_Stream stream, + void* dst, + const void* src, + size_t size); + + /** + * @brief Asynchonrize memory copy from device to device + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*async_memory_copy_d2d)(const C_Device device, + C_Stream stream, + void* dst, + const void* src, + size_t size); + + /** + * @brief Peer asynchonrize memory copy from host to device + * + * @param[C_Device] device Core fill it with a physical id + * @param[C_Stream] stream + * @param[void*] dst + * @param[void*] src + * @param[size_t] size + */ + C_Status (*async_memory_copy_p2p)(const C_Device dst_device, + const C_Device src_device, + C_Stream stream, + void* dst, + const void* src, + size_t size); + + void* reserved_mem_api[8]; + + ////////////// + // info api // + ////////////// + + /** + * @brief Get visible device count + * + * @param[size_t*] count Plugin fill it + */ + C_Status (*get_device_count)(size_t* count); + + /** + * @brief Get visible device list + * + * @param[size_t*] devices Plugin fill it + */ + C_Status (*get_device_list)(size_t* devices); + + /** + * @brief Device memory statistic + * + * @param[C_Device] device Core fill it with a physical id + * @param[size_t*] total_memory + * @param[size_t*] free_memory + * @param[size_t*] used_memory + */ + C_Status (*device_memory_stats)(const C_Device device, + size_t* total_memory, + size_t* free_memory); + + /** + * @brief Device minimum chunk size + * + * @param[size_t*] count + */ + C_Status (*device_min_chunk_size)(const C_Device device, size_t* count); + + /** + * @brief Device maximum chunk size + * + * @param[size_t*] count + */ + C_Status (*device_max_chunk_size)(const C_Device device, size_t* count); + + /** + * @brief Device maximum alloc size + * + * @param[size_t*] count + */ + C_Status (*device_max_alloc_size)(const C_Device device, size_t* count); + + /** + * @brief Device extra padding size + * + * @param[size_t*] size + */ + C_Status (*device_extra_padding_size)(const C_Device device, size_t* size); + + /** + * @brief Device initial allocated size + * + * @param[size_t*] size + */ + C_Status (*device_init_alloc_size)(const C_Device device, size_t* size); + + /** + * @brief Device reallocated size + * + * @param[size_t*] size + */ + C_Status (*device_realloc_size)(const C_Device device, size_t* size); + + /** + * @brief Get compute capability + * + * @param[size_t*] compute_capability + */ + C_Status (*get_compute_capability)(size_t* compute_capability); + + /** + * @brief Get runtime version + * + * @param[size_t*] version + */ + C_Status (*get_runtime_version)(size_t* version); + + /** + * @brief Get driver version + * + * @param[size_t*] version + */ + C_Status (*get_driver_version)(size_t* version); + + void* reserved_info_api[8]; + + ////////////// + // ccl api // + ////////////// + + /** + * @brief Get size of unique id + * + * @param[size_t*] size + */ + C_Status (*xccl_get_unique_id_size)(size_t* size); + + /** + * @brief Get unique id + * + * @param[C_CCLRootId*] unique_id + */ + C_Status (*xccl_get_unique_id)(C_CCLRootId* unique_id); + + /** + * @brief Initialize communicator + * + * @param[size_t] ranks + * @param[C_CCLRootId*] unique_id + * @param[size_t] rank + * @param[C_CCLComm*] comm + */ + C_Status (*xccl_comm_init_rank)(size_t ranks, + C_CCLRootId* unique_id, + size_t rank, + C_CCLComm* comm); + + /** + * @brief Destroy communicator + * + * @param[C_CCLComm] comm + */ + C_Status (*xccl_destroy_comm)(C_CCLComm comm); + + C_Status (*xccl_all_reduce)(void* send_buf, + void* recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_broadcast)(void* buf, + size_t count, + C_DataType data_type, + size_t root, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_reduce)(void* send_buf, + void* recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + size_t root, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_all_gather)(void* send_buf, + void* recv_buf, + size_t count, + C_DataType data_type, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_reduce_scatter)(void* send_buf, + void* recv_buf, + size_t count, + C_DataType data_type, + C_CCLReduceOp op, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_group_start)(); + + C_Status (*xccl_group_end)(); + + C_Status (*xccl_send)(void* send_buf, + size_t count, + C_DataType data_type, + size_t dest_rank, + C_CCLComm comm, + C_Stream stream); + + C_Status (*xccl_recv)(void* recv_buf, + size_t count, + C_DataType data_type, + size_t src_rank, + C_CCLComm comm, + C_Stream stream); + + void* reserved_ccl_api[8]; + + ////////////////// + // profiler api // + ////////////////// + + C_Status (*profiler_initialize)(C_Profiler prof, void** user_data); + + C_Status (*profiler_finalize)(C_Profiler prof, void* user_data); + + C_Status (*profiler_prepare_tracing)(C_Profiler prof, void* user_data); + + C_Status (*profiler_start_tracing)(C_Profiler prof, void* user_data); + + C_Status (*profiler_stop_tracing)(C_Profiler prof, void* user_data); + + C_Status (*profiler_collect_trace_data)(C_Profiler prof, + uint64_t start_ns, + void* user_data); + + void* reserved_profiler_api[8]; + + /////////////// + // other api // + /////////////// + + /** + * @brief y = alpha * x + beta * y + * + */ + C_Status (*blas_axpby)(const C_Device device, + C_Stream stream, + C_DataType dtype, + size_t numel, + float alpha, + void* x, + float beta, + void* y); + void* reserved_other_api[7]; +}; + +struct CustomRuntimeVersion { + size_t major, minor, patch; +}; + +struct CustomRuntimeParams { + // Core fill it and plugin must to check it + size_t size; + // Plugin fill it + C_DeviceInterface* interface; + // Plugin fill it and Core will to check it + CustomRuntimeVersion version; + // Plugin fill it + char* device_type; + // Plugin fill it + char* sub_device_type; + + char reserved[32]; +}; + +#define PADDLE_CUSTOM_RUNTIME_CHECK_VERSION(params) \ + if ((params)->size != sizeof(CustomRuntimeParams) && \ + (params)->interface->size != sizeof(C_DeviceInterface)) { \ + return; \ + } \ + (params)->version.major = PADDLE_CUSTOM_RUNTIME_MAJOR_VERSION; \ + (params)->version.minor = PADDLE_CUSTOM_RUNTIME_MINOR_VERSION; \ + (params)->version.patch = PADDLE_CUSTOM_RUNTIME_PATCH_VERSION; + +// Plugin implement it and fill CustomRuntimeParams +void InitPlugin(CustomRuntimeParams*); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_guard.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_guard.h new file mode 100644 index 0000000000000000000000000000000000000000..668951f8a1c981acb8d16a9f2781f806156c1dc6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_guard.h @@ -0,0 +1,50 @@ +// Copyright (c) 2022 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. + +#pragma once +#ifdef PADDLE_WITH_CUSTOM_DEVICE + +#include "paddle/phi/backends/device_manager.h" + +namespace phi { + +class DeviceGuard { + public: + explicit inline DeviceGuard(const Place& place) + : dev_type_(place.GetDeviceType()) { + prev_id = DeviceManager::GetDevice(dev_type_); + cur_id = place.GetDeviceId(); + + if (cur_id != prev_id) { + DeviceManager::SetDevice(dev_type_, cur_id); + } + } + + inline ~DeviceGuard() { + if (cur_id != prev_id) { + DeviceManager::SetDevice(dev_type_, prev_id); + } + } + + DeviceGuard(const DeviceGuard& o) = delete; + DeviceGuard& operator=(const DeviceGuard& o) = delete; + + private: + size_t prev_id, cur_id; + std::string dev_type_; +}; + +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_manager.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..54bafd796df46322e08cd6f8bbc444cc3a86058f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/device_manager.h @@ -0,0 +1,306 @@ +// Copyright (c) 2022 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. + +#pragma once +#ifdef PADDLE_WITH_CUSTOM_DEVICE + +#include + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/utils/rw_lock.h" + +#include "paddle/phi/backends/c_comm_lib.h" +#include "paddle/phi/backends/device_base.h" +#include "paddle/phi/backends/device_ext.h" +#include "paddle/phi/backends/dynload/port.h" +#include "paddle/phi/backends/event.h" +#include "paddle/phi/backends/stream.h" + +namespace phi { +class Device final { + public: + Device(size_t dev_id, DeviceInterface* impl) : dev_id_(dev_id), impl_(impl) {} + + // Stream + // ! Create an asynchronous stream + void CreateStream( + stream::Stream* stream, + const stream::Stream::Priority& priority = + stream::Stream::Priority::kNormal, + const stream::Stream::Flag& flag = stream::Stream::Flag::kDefaultFlag); + + // ! Destroys an asynchronous stream. + void DestroyStream(stream::Stream* stream); + + // ! Waits for stream tasks to complete. + void SynchronizeStream(const stream::Stream* stream); + + // ! Queries an asynchronous stream for completion status. + bool QueryStream(const stream::Stream* stream); + + // ! Add a callback to a compute stream. + void AddCallback(stream::Stream* stream, stream::Stream::Callback* callback); + + // Event + // ! Create an event. + void CreateEvent(event::Event* event, event::Event::Flag flags); + + // ! Destroy an event. + void DestroyEvent(event::Event* event); + + // ! Records an event. + void RecordEvent(const event::Event* event, const stream::Stream* stream); + + // ! Waits for event to complete. + void SynchronizeEvent(const event::Event* event); + + // ! Queries an event for completion status. + bool QueryEvent(const event::Event* event); + + // ! Make a compute stream wait on an event + void StreamWaitEvent(const stream::Stream* stream, const event::Event* event); + + // Memory + void MemoryCopyH2D(void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + void MemoryCopyD2H(void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + void MemoryCopyD2D(void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + void MemoryCopyP2P(const Place& dst_place, + void* dst, + const void* src, + size_t size, + const stream::Stream* stream = nullptr); + + void* MemoryAllocate(size_t size); + + void MemoryDeallocate(void* ptr, size_t size); + + void* MemoryAllocateHost(size_t size); + + void MemoryDeallocateHost(void* ptr, size_t size); + + void* MemoryAllocateUnified(size_t size); + + void MemoryDeallocateUnified(void* ptr, size_t size); + + void MemorySet(void* ptr, uint8_t value, size_t size); + + // Blas + // ! y = alpha * x + beta * y + template + void BlasAXPBY(const stream::Stream& stream, + size_t numel, + float alpha, + const T* x, + float beta, + T* y); + + std::string Type(); + + private: + size_t dev_id_; + DeviceInterface* impl_; +}; + +class DeviceManager { + public: + static bool Register(std::unique_ptr device); + static bool RegisterPinnedDevice(DeviceInterface* device); + static Device* GetDeviceWithPlace(const Place& place); + static std::vector GetAllDeviceTypes(); + static std::vector GetAllCustomDeviceTypes(); + static std::vector GetAllDeviceList(); + static std::vector GetAllCustomDeviceList(); + static bool HasDeviceType(const std::string& device_type); + static bool IsCustom(const std::string& device_type); + + // platform & device + static void Initialize(const std::string& device_type); + + static void Finalize(const std::string& device_type); + + static void SynchronizeDevice(const Place& place); + + static void InitDevice(const Place& place); + + static void DeInitDevice(const Place& place); + + static void SetDevice(const std::string& device_type, size_t device_id); + + static void SetDevice(const Place& place); + + static int GetDevice(const std::string& device_type); + + static size_t GetMinChunkSize(const Place& place); + + static size_t GetMaxChunkSize(const Place& place); + + static size_t GetMaxAllocSize(const Place& place); + + static size_t GetInitAllocSize(const Place& place); + + static size_t GetReallocSize(const Place& place); + + static size_t GetExtraPaddingSize(const Place& place); + + static void MemoryStats(const Place& place, size_t* total, size_t* free); + + static size_t GetDeviceCount(const std::string& device_type); + + static std::vector GetDeviceList(const std::string& device_type); + + static std::vector GetSelectedDeviceList( + const std::string& device_type); + + // CCL + static void CCLDestroyComm(const std::string& device_type, + ccl::CCLComm ccl_comm); + static void CCLCommInitRank(const std::string& device_type, + size_t num_ranks, + ccl::CCLRootId* root_id, + size_t rank_id, + ccl::CCLComm* ccl_comm); + static void CCLGetUniqueId(const std::string& device_type, + ccl::CCLRootId* root_id); + static void CCLBroadcast(const std::string& device_type, + void* data, + size_t num, + ccl::CCLDataType data_type, + size_t root, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLAllReduce(const std::string& device_type, + void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp reduce_op, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLReduce(const std::string& device_type, + void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp reduce_op, + size_t root_id, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLAllGather(const std::string& device_type, + void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLReduceScatter(const std::string& device_type, + void* in_data, + void* out_data, + size_t num, + ccl::CCLDataType data_type, + ccl::CCLReduceOp op, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLGroupStart(const std::string& device_type); + static void CCLGroupEnd(const std::string& device_type); + static void CCLSend(const std::string& device_type, + void* sendbuf, + size_t num, + ccl::CCLDataType data_type, + size_t dst_rank, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + static void CCLRecv(const std::string& device_type, + void* recvbuf, + size_t num, + ccl::CCLDataType data_type, + size_t src_rank, + const ccl::CCLComm& ccl_comm, + const stream::Stream& stream); + + // profiler + static void ProfilerInitialize( + const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + void** context); + static void ProfilerFinalize(const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + void* context); + static void ProfilerPrepareTracing( + const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + void* context); + static void ProfilerStartTracing( + const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + void* context); + static void ProfilerStopTracing( + const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + void* context); + static void ProfilerCollectTraceData( + const std::string& dev_type, + paddle::platform::TraceEventCollector* collector, + uint64_t start_ns, + void* context); + + static void Clear(); + + private: + DISABLE_COPY_AND_ASSIGN(DeviceManager); + DeviceManager() {} + static DeviceManager& Instance(); + static DeviceInterface* GetDeviceInterfaceWithType( + const std::string& device_type); + + std::unordered_map> + device_impl_map_; + std::unordered_map>> + device_map_; +}; + +std::vector ListAllLibraries(const std::string& library_dir); + +void LoadCustomRuntimeLib(const std::string& dso_lib_path, void* dso_handle); + +void LoadCustomRuntimeLib(const CustomRuntimeParams& runtime_params, + std::unique_ptr device_interface, + const std::string& dso_lib_path, + void* dso_handle); + +class Registrar { + public: + template + explicit Registrar(DeviceT* device_ptr) { + DeviceManager::Register(std::unique_ptr(device_ptr)); + } + + void Touch() {} +}; + +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublas.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublas.h new file mode 100644 index 0000000000000000000000000000000000000000..308ae2accef14613de3597b6d458ff05b99f183e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublas.h @@ -0,0 +1,137 @@ +/* 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. */ + +#pragma once + +#include +#include +#include + +#include // NOLINT +#include + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cublas_dso_flag; +extern void *cublas_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load cublas routine + * via operator overloading. + * + * note: default dynamic linked libs + */ +#define DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + inline auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using cublas_func = \ + decltype(::__name(std::declval()...)) (*)(Args...); \ + std::call_once(cublas_dso_flag, []() { \ + cublas_dso_handle = phi::dynload::GetCublasDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cublas_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define CUBLAS_BLAS_ROUTINE_EACH(__macro) \ + __macro(cublasSaxpy_v2); \ + __macro(cublasDaxpy_v2); \ + __macro(cublasCaxpy_v2); \ + __macro(cublasZaxpy_v2); \ + __macro(cublasSscal_v2); \ + __macro(cublasDscal_v2); \ + __macro(cublasScopy_v2); \ + __macro(cublasDcopy_v2); \ + __macro(cublasSgemv_v2); \ + __macro(cublasDgemv_v2); \ + __macro(cublasCgemv_v2); \ + __macro(cublasZgemv_v2); \ + __macro(cublasSgemm_v2); \ + __macro(cublasDgemm_v2); \ + __macro(cublasCgemm_v2); \ + __macro(cublasZgemm_v2); \ + __macro(cublasHgemm); \ + __macro(cublasSgemmEx); \ + __macro(cublasSgeam); \ + __macro(cublasDgeam); \ + __macro(cublasStrsm_v2); \ + __macro(cublasDtrsm_v2); \ + __macro(cublasCtrsm_v2); \ + __macro(cublasZtrsm_v2); \ + __macro(cublasCreate_v2); \ + __macro(cublasDestroy_v2); \ + __macro(cublasSetStream_v2); \ + __macro(cublasSetPointerMode_v2); \ + __macro(cublasGetPointerMode_v2); \ + __macro(cublasSgemmBatched); \ + __macro(cublasDgemmBatched); \ + __macro(cublasCgemmBatched); \ + __macro(cublasZgemmBatched); \ + __macro(cublasStrsmBatched); \ + __macro(cublasDtrsmBatched); \ + __macro(cublasCtrsmBatched); \ + __macro(cublasZtrsmBatched); \ + __macro(cublasSgetrfBatched); \ + __macro(cublasSgetriBatched); \ + __macro(cublasDgetrfBatched); \ + __macro(cublasDgetriBatched); \ + __macro(cublasSmatinvBatched); \ + __macro(cublasDmatinvBatched); \ + __macro(cublasSgetrsBatched); \ + __macro(cublasDgetrsBatched); + +CUBLAS_BLAS_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP) + +// APIs available after CUDA 8.0 +#if CUDA_VERSION >= 8000 +#define CUBLAS_BLAS_ROUTINE_EACH_R2(__macro) \ + __macro(cublasGemmEx); \ + __macro(cublasSgemmStridedBatched); \ + __macro(cublasDgemmStridedBatched); \ + __macro(cublasCgemmStridedBatched); \ + __macro(cublasZgemmStridedBatched); \ + __macro(cublasHgemmStridedBatched); + +CUBLAS_BLAS_ROUTINE_EACH_R2(DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP) +#endif + +// APIs available after CUDA 9.0 +#if CUDA_VERSION >= 9000 +#define CUBLAS_BLAS_ROUTINE_EACH_R3(__macro) \ + __macro(cublasSetMathMode); \ + __macro(cublasGetMathMode); + +CUBLAS_BLAS_ROUTINE_EACH_R3(DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP) +#endif + +// APIs available after CUDA 9.1 +#if CUDA_VERSION >= 9010 +#define CUBLAS_BLAS_ROUTINE_EACH_R4(__macro) \ + __macro(cublasGemmBatchedEx); \ + __macro(cublasGemmStridedBatchedEx); + +CUBLAS_BLAS_ROUTINE_EACH_R4(DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP) +#endif + +#undef DECLARE_DYNAMIC_LOAD_CUBLAS_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublasLt.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublasLt.h new file mode 100644 index 0000000000000000000000000000000000000000..90492ff4ba69d67d511c5d7d4df25660af9b8dc0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cublasLt.h @@ -0,0 +1,85 @@ +/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +Copyright (c) 2022 NVIDIA 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. */ + +#pragma once + +#include +#include + +#include // NOLINT +#include + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cublasLt_dso_flag; +extern void *cublasLt_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load cublasLt routine + * via operator overloading. + * + * note: default dynamic linked libs + */ +#define DECLARE_DYNAMIC_LOAD_CUBLASLT_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + inline auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using cublasLt_func = \ + decltype(::__name(std::declval()...)) (*)(Args...); \ + std::call_once(cublasLt_dso_flag, []() { \ + cublasLt_dso_handle = phi::dynload::GetCublasLtDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cublasLt_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +// APIs available after CUDA 10.1 +// #if CUDA_VERSION >= 10100 +#define CUBLASLT_BLAS_ROUTINE_EACH(__macro) \ + __macro(cublasLtCreate); \ + __macro(cublasLtDestroy); \ + __macro(cublasLtMatmul); \ + __macro(cublasLtMatmulDescCreate); \ + __macro(cublasLtMatmulDescDestroy); \ + __macro(cublasLtMatmulDescSetAttribute); \ + __macro(cublasLtMatmulDescGetAttribute); \ + __macro(cublasLtMatrixLayoutCreate); \ + __macro(cublasLtMatrixLayoutDestroy); \ + __macro(cublasLtMatrixLayoutSetAttribute); \ + __macro(cublasLtMatrixLayoutGetAttribute); \ + __macro(cublasLtMatmulPreferenceCreate); \ + __macro(cublasLtMatmulPreferenceDestroy); \ + __macro(cublasLtMatmulPreferenceSetAttribute); \ + __macro(cublasLtMatmulAlgoGetHeuristic); \ + __macro(cublasLtMatrixTransform); \ + __macro(cublasLtMatrixTransformDescCreate); \ + __macro(cublasLtMatrixTransformDescDestroy); \ + __macro(cublasLtMatrixTransformDescSetAttribute); \ + __macro(cublasLtMatmulAlgoInit); \ + __macro(cublasLtMatmulAlgoConfigSetAttribute); + +CUBLASLT_BLAS_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUBLASLT_WRAP) +// #endif + +#undef DECLARE_DYNAMIC_LOAD_CUBLASLT_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cuda_driver.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cuda_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..f743a33a1866fab7a968719f88041f15bf75884c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cuda_driver.h @@ -0,0 +1,83 @@ +/* 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cuda_dso_flag; +extern void* cuda_dso_handle; +extern bool HasCUDADriver(); + +#define DECLARE_DYNAMIC_LOAD_CUDA_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using cuda_func = decltype(&::__name); \ + std::call_once(cuda_dso_flag, []() { \ + cuda_dso_handle = phi::dynload::GetCUDADsoHandle(); \ + }); \ + static void* p_##__name = dlsym(cuda_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed cuda driver functions + **/ +#define CUDA_ROUTINE_EACH(__macro) \ + __macro(cuInit); \ + __macro(cuDriverGetVersion); \ + __macro(cuGetErrorString); \ + __macro(cuModuleLoadData); \ + __macro(cuModuleGetFunction); \ + __macro(cuModuleUnload); \ + __macro(cuOccupancyMaxActiveBlocksPerMultiprocessor); \ + __macro(cuLaunchKernel); \ + __macro(cuCtxCreate); \ + __macro(cuCtxGetCurrent); \ + __macro(cuDeviceGetCount); \ + __macro(cuDevicePrimaryCtxGetState); \ + __macro(cuDeviceGetAttribute); \ + __macro(cuDeviceGet) + +#if CUDA_VERSION >= 10020 +#define CUDA_ROUTINE_EACH_VVM(__macro) \ + __macro(cuMemGetAllocationGranularity); \ + __macro(cuMemAddressReserve); \ + __macro(cuMemCreate); \ + __macro(cuMemMap); \ + __macro(cuMemSetAccess); \ + __macro(cuMemUnmap); \ + __macro(cuMemRelease); \ + __macro(cuMemAddressFree) + +CUDA_ROUTINE_EACH_VVM(DECLARE_DYNAMIC_LOAD_CUDA_WRAP); +#endif + +CUDA_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUDA_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_CUDA_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cudnn.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cudnn.h new file mode 100644 index 0000000000000000000000000000000000000000..7b9004308e95b3be3b0ace2699b8fed7d616bac5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cudnn.h @@ -0,0 +1,200 @@ +/* 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. */ + +#pragma once +#ifdef PADDLE_WITH_CUDA +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cudnn_dso_flag; +extern void* cudnn_dso_handle; +extern bool HasCUDNN(); + +extern void EnforceCUDNNLoaded(const char* fn_name); +#define DECLARE_DYNAMIC_LOAD_CUDNN_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using cudnn_func = decltype(&::__name); \ + std::call_once(cudnn_dso_flag, []() { \ + cudnn_dso_handle = phi::dynload::GetCUDNNDsoHandle(); \ + }); \ + EnforceCUDNNLoaded(#__name); \ + static void* p_##__name = dlsym(cudnn_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed cudnn functions in HPPL + * different cudnn version has different interfaces + **/ +#define CUDNN_DNN_ROUTINE_EACH(__macro) \ + __macro(cudnnSetTensor4dDescriptor); \ + __macro(cudnnSetTensor4dDescriptorEx); \ + __macro(cudnnSetTensorNdDescriptor); \ + __macro(cudnnGetTensorNdDescriptor); \ + __macro(cudnnGetConvolutionNdForwardOutputDim); \ + __macro(cudnnCreateTensorDescriptor); \ + __macro(cudnnDestroyTensorDescriptor); \ + __macro(cudnnCreateFilterDescriptor); \ + __macro(cudnnSetFilter4dDescriptor); \ + __macro(cudnnSetFilterNdDescriptor); \ + __macro(cudnnGetFilterNdDescriptor); \ + __macro(cudnnSetPooling2dDescriptor); \ + __macro(cudnnSetPoolingNdDescriptor); \ + __macro(cudnnGetPoolingNdDescriptor); \ + __macro(cudnnDestroyFilterDescriptor); \ + __macro(cudnnCreateConvolutionDescriptor); \ + __macro(cudnnCreatePoolingDescriptor); \ + __macro(cudnnDestroyPoolingDescriptor); \ + __macro(cudnnSetConvolution2dDescriptor); \ + __macro(cudnnDestroyConvolutionDescriptor); \ + __macro(cudnnSetConvolutionNdDescriptor); \ + __macro(cudnnGetConvolutionNdDescriptor); \ + __macro(cudnnDeriveBNTensorDescriptor); \ + __macro(cudnnCreateSpatialTransformerDescriptor); \ + __macro(cudnnSetSpatialTransformerNdDescriptor); \ + __macro(cudnnDestroySpatialTransformerDescriptor); \ + __macro(cudnnSpatialTfGridGeneratorForward); \ + __macro(cudnnSpatialTfGridGeneratorBackward); \ + __macro(cudnnSpatialTfSamplerForward); \ + __macro(cudnnSpatialTfSamplerBackward); \ + __macro(cudnnCreate); \ + __macro(cudnnDestroy); \ + __macro(cudnnSetStream); \ + __macro(cudnnActivationForward); \ + __macro(cudnnActivationBackward); \ + __macro(cudnnConvolutionForward); \ + __macro(cudnnConvolutionBackwardBias); \ + __macro(cudnnGetConvolutionForwardWorkspaceSize); \ + __macro(cudnnTransformTensor); \ + __macro(cudnnPoolingForward); \ + __macro(cudnnPoolingBackward); \ + __macro(cudnnSoftmaxBackward); \ + __macro(cudnnSoftmaxForward); \ + __macro(cudnnGetVersion); \ + __macro(cudnnFindConvolutionForwardAlgorithmEx); \ + __macro(cudnnFindConvolutionBackwardFilterAlgorithmEx); \ + __macro(cudnnFindConvolutionBackwardFilterAlgorithm); \ + __macro(cudnnFindConvolutionBackwardDataAlgorithmEx); \ + __macro(cudnnGetErrorString); \ + __macro(cudnnCreateDropoutDescriptor); \ + __macro(cudnnDropoutGetStatesSize); \ + __macro(cudnnSetDropoutDescriptor); \ + __macro(cudnnRestoreDropoutDescriptor); \ + __macro(cudnnCreateRNNDescriptor); \ + __macro(cudnnGetRNNParamsSize); \ + __macro(cudnnGetRNNWorkspaceSize); \ + __macro(cudnnGetRNNTrainingReserveSize); \ + __macro(cudnnRNNForwardTraining); \ + __macro(cudnnRNNBackwardData); \ + __macro(cudnnRNNBackwardWeights); \ + __macro(cudnnRNNForwardInference); \ + __macro(cudnnDestroyDropoutDescriptor); \ + __macro(cudnnDestroyRNNDescriptor); \ + __macro(cudnnSetTensorNdDescriptorEx); \ + __macro(cudnnAddTensor); \ + __macro(cudnnConvolutionBackwardData); \ + __macro(cudnnConvolutionBackwardFilter); \ + __macro(cudnnGetConvolutionBackwardFilterWorkspaceSize); \ + __macro(cudnnGetConvolutionBackwardDataWorkspaceSize); \ + __macro(cudnnBatchNormalizationForwardTraining); \ + __macro(cudnnBatchNormalizationForwardInference); \ + __macro(cudnnBatchNormalizationBackward); \ + __macro(cudnnCreateActivationDescriptor); \ + __macro(cudnnSetActivationDescriptor); \ + __macro(cudnnGetActivationDescriptor); \ + __macro(cudnnDestroyActivationDescriptor); \ + __macro(cudnnSetRNNDescriptor_v6); +CUDNN_DNN_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) + +#if CUDNN_VERSION >= 7000 && CUDNN_VERSION < 8000 +#define CUDNN_DNN_ROUTINE_EACH_AFTER_R7_LESS_R8(__macro) \ + __macro(cudnnGetConvolutionBackwardFilterAlgorithm); \ + __macro(cudnnGetConvolutionForwardAlgorithm); \ + __macro(cudnnGetConvolutionBackwardDataAlgorithm); \ + __macro(cudnnSetRNNDescriptor); +CUDNN_DNN_ROUTINE_EACH_AFTER_R7_LESS_R8(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) +#endif + +#if CUDNN_VERSION >= 7001 +#define CUDNN_DNN_ROUTINE_EACH_R7(__macro) \ + __macro(cudnnSetConvolutionGroupCount); \ + __macro(cudnnSetConvolutionMathType); \ + __macro(cudnnConvolutionBiasActivationForward); \ + __macro(cudnnCreateCTCLossDescriptor); \ + __macro(cudnnDestroyCTCLossDescriptor); \ + __macro(cudnnGetCTCLossDescriptor); \ + __macro(cudnnSetCTCLossDescriptor); \ + __macro(cudnnGetCTCLossWorkspaceSize); \ + __macro(cudnnCTCLoss); \ + __macro(cudnnGetConvolutionBackwardDataAlgorithm_v7); \ + __macro(cudnnGetConvolutionBackwardFilterAlgorithm_v7); \ + __macro(cudnnGetConvolutionForwardAlgorithm_v7); \ + __macro(cudnnGetConvolutionBackwardFilterAlgorithmMaxCount); +CUDNN_DNN_ROUTINE_EACH_R7(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) +#endif + +#if CUDNN_VERSION >= 7201 +#define CUDNN_DNN_ROUTINE_EACH_AFTER_TWO_R7(__macro) \ + __macro(cudnnCreateRNNDataDescriptor); \ + __macro(cudnnDestroyRNNDataDescriptor); \ + __macro(cudnnSetRNNDataDescriptor); \ + __macro(cudnnSetRNNPaddingMode); \ + __macro(cudnnRNNForwardTrainingEx); \ + __macro(cudnnRNNBackwardDataEx); \ + __macro(cudnnRNNBackwardWeightsEx); \ + __macro(cudnnRNNForwardInferenceEx); +CUDNN_DNN_ROUTINE_EACH_AFTER_TWO_R7(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) +#endif + +#if CUDNN_VERSION >= 7401 +#define CUDNN_DNN_ROUTINE_EACH_AFTER_R7(__macro) \ + __macro(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize); \ + __macro(cudnnBatchNormalizationForwardTrainingEx); \ + __macro(cudnnGetBatchNormalizationBackwardExWorkspaceSize); \ + __macro(cudnnBatchNormalizationBackwardEx); \ + __macro(cudnnGetBatchNormalizationTrainingExReserveSpaceSize); +CUDNN_DNN_ROUTINE_EACH_AFTER_R7(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) +#endif + +#if CUDNN_VERSION >= 8000 +#define CUDNN_DNN_ROUTINE_EACH_R8(__macro) \ + __macro(cudnnSetRNNDescriptor_v8); \ + __macro(cudnnCreateFusedOpsPlan); \ + __macro(cudnnCreateFusedOpsConstParamPack); \ + __macro(cudnnCreateFusedOpsVariantParamPack); \ + __macro(cudnnDestroyFusedOpsPlan); \ + __macro(cudnnDestroyFusedOpsConstParamPack); \ + __macro(cudnnDestroyFusedOpsVariantParamPack); \ + __macro(cudnnFusedOpsExecute); \ + __macro(cudnnSetFusedOpsConstParamPackAttribute); \ + __macro(cudnnSetFusedOpsVariantParamPackAttribute); \ + __macro(cudnnMakeFusedOpsPlan); +CUDNN_DNN_ROUTINE_EACH_R8(DECLARE_DYNAMIC_LOAD_CUDNN_WRAP) +#endif + +} // namespace dynload +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cufft.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cufft.h new file mode 100644 index 0000000000000000000000000000000000000000..a27d7c3ab1eeec9da81cd5e320763e4d19aca5ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cufft.h @@ -0,0 +1,112 @@ +/* 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. */ + +#pragma once +#ifdef PADDLE_WITH_CUDA +#include +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cufft_dso_flag; +extern void* cufft_dso_handle; +extern bool HasCUFFT(); + +extern void EnforceCUFFTLoaded(const char* fn_name); +#define DECLARE_DYNAMIC_LOAD_CUFFT_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using cufft_func = decltype(&::__name); \ + std::call_once(cufft_dso_flag, []() { \ + cufft_dso_handle = phi::dynload::GetCUFFTDsoHandle(); \ + }); \ + EnforceCUFFTLoaded(#__name); \ + static void* p_##__name = dlsym(cufft_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed cufft functions in HPPL + * different cufft version has different interfaces + **/ +#define CUFFT_FFT_ROUTINE_EACH(__macro) \ + __macro(cufftPlan1d); \ + __macro(cufftPlan2d); \ + __macro(cufftPlan3d); \ + __macro(cufftPlanMany); \ + __macro(cufftMakePlan1d); \ + __macro(cufftMakePlan2d); \ + __macro(cufftMakePlan3d); \ + __macro(cufftMakePlanMany); \ + __macro(cufftMakePlanMany64); \ + __macro(cufftGetSizeMany64); \ + __macro(cufftEstimate1d); \ + __macro(cufftEstimate2d); \ + __macro(cufftEstimate3d); \ + __macro(cufftEstimateMany); \ + __macro(cufftCreate); \ + __macro(cufftGetSize1d); \ + __macro(cufftGetSize2d); \ + __macro(cufftGetSize3d); \ + __macro(cufftGetSizeMany); \ + __macro(cufftGetSize); \ + __macro(cufftSetWorkArea); \ + __macro(cufftSetAutoAllocation); \ + __macro(cufftExecC2C); \ + __macro(cufftExecR2C); \ + __macro(cufftExecC2R); \ + __macro(cufftExecZ2Z); \ + __macro(cufftExecD2Z); \ + __macro(cufftExecZ2D); \ + __macro(cufftSetStream); \ + __macro(cufftDestroy); \ + __macro(cufftGetVersion); \ + __macro(cufftGetProperty); \ + __macro(cufftXtSetGPUs); \ + __macro(cufftXtMalloc); \ + __macro(cufftXtMemcpy); \ + __macro(cufftXtFree); \ + __macro(cufftXtSetWorkArea); \ + __macro(cufftXtExecDescriptorC2C); \ + __macro(cufftXtExecDescriptorR2C); \ + __macro(cufftXtExecDescriptorC2R); \ + __macro(cufftXtExecDescriptorZ2Z); \ + __macro(cufftXtExecDescriptorD2Z); \ + __macro(cufftXtExecDescriptorZ2D); \ + __macro(cufftXtQueryPlan); \ + __macro(cufftXtSetCallback); \ + __macro(cufftXtClearCallback); \ + __macro(cufftXtSetCallbackSharedSize); \ + __macro(cufftXtMakePlanMany); \ + __macro(cufftXtGetSizeMany); \ + __macro(cufftXtExec); \ + __macro(cufftXtExecDescriptor); \ + __macro(cufftXtSetWorkAreaPolicy); + +CUFFT_FFT_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUFFT_WRAP) + +} // namespace dynload +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cupti.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cupti.h new file mode 100644 index 0000000000000000000000000000000000000000..22e21b78f4f2e6806fe1f5db6b34a6188566ea31 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cupti.h @@ -0,0 +1,77 @@ +/* Copyright (c) 2018 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. */ +#pragma once + +#ifdef PADDLE_WITH_CUPTI + +#include +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cupti_dso_flag; +extern void *cupti_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load cupti routine + * via operator overloading. + * + * note: default dynamic linked libs + */ +#define DECLARE_DYNAMIC_LOAD_CUPTI_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + inline CUptiResult CUPTIAPI operator()(Args... args) { \ + using cuptiFunc = decltype(&::__name); \ + std::call_once(cupti_dso_flag, []() { \ + cupti_dso_handle = phi::dynload::GetCUPTIDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cupti_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define CUPTI_ROUTINE_EACH(__macro) \ + __macro(cuptiActivityEnable); \ + __macro(cuptiActivityDisable); \ + __macro(cuptiActivityRegisterCallbacks); \ + __macro(cuptiActivityGetAttribute); \ + __macro(cuptiActivitySetAttribute); \ + __macro(cuptiGetTimestamp); \ + __macro(cuptiActivityGetNextRecord); \ + __macro(cuptiGetResultString); \ + __macro(cuptiActivityGetNumDroppedRecords); \ + __macro(cuptiActivityFlushAll); \ + __macro(cuptiSubscribe); \ + __macro(cuptiUnsubscribe); \ + __macro(cuptiEnableCallback); \ + __macro(cuptiEnableDomain); \ + __macro(cudaOccMaxActiveBlocksPerMultiprocessor); + +CUPTI_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUPTI_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_CUPTI_WRAP +} // namespace dynload +} // namespace phi + +#endif // PADDLE_WITH_CUPTI diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/curand.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/curand.h new file mode 100644 index 0000000000000000000000000000000000000000..f3c4496dc4d399796f89328d3a0117490462c558 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/curand.h @@ -0,0 +1,54 @@ +/* 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. */ +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag curand_dso_flag; +extern void *curand_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_CURAND_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + curandStatus_t operator()(Args... args) { \ + using curandFunc = decltype(&::__name); \ + std::call_once(curand_dso_flag, []() { \ + curand_dso_handle = phi::dynload::GetCurandDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(curand_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define CURAND_RAND_ROUTINE_EACH(__macro) \ + __macro(curandCreateGenerator); \ + __macro(curandSetStream); \ + __macro(curandSetPseudoRandomGeneratorSeed); \ + __macro(curandGenerateUniform); \ + __macro(curandGenerateUniformDouble); \ + __macro(curandGenerateNormal); \ + __macro(curandDestroyGenerator); + +CURAND_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CURAND_WRAP); + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusolver.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusolver.h new file mode 100644 index 0000000000000000000000000000000000000000..1354e310554804ea5d7402cb0cd62431365e285e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusolver.h @@ -0,0 +1,124 @@ +/* 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. */ +#pragma once + +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag cusolver_dso_flag; +extern void *cusolver_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_CUSOLVER_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + cusolverStatus_t operator()(Args... args) { \ + using cusolverFunc = decltype(&::__name); \ + std::call_once(cusolver_dso_flag, []() { \ + cusolver_dso_handle = phi::dynload::GetCusolverDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cusolver_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define CUSOLVER_ROUTINE_EACH(__macro) \ + __macro(cusolverDnCreate); \ + __macro(cusolverDnDestroy); \ + __macro(cusolverDnSetStream); \ + __macro(cusolverDnSpotrf_bufferSize); \ + __macro(cusolverDnDpotrf_bufferSize); \ + __macro(cusolverDnSpotrf); \ + __macro(cusolverDnDpotrf); \ + __macro(cusolverDnSpotrs); \ + __macro(cusolverDnDpotrs); \ + __macro(cusolverDnCpotrs); \ + __macro(cusolverDnZpotrs); \ + __macro(cusolverDnSsyevd_bufferSize); \ + __macro(cusolverDnDsyevd_bufferSize); \ + __macro(cusolverDnCheevd_bufferSize); \ + __macro(cusolverDnZheevd_bufferSize); \ + __macro(cusolverDnSsyevd); \ + __macro(cusolverDnDsyevd); \ + __macro(cusolverDnCheevd); \ + __macro(cusolverDnZheevd); + +CUSOLVER_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUSOLVER_WRAP); + +#if CUDA_VERSION >= 9020 +#define CUSOLVER_ROUTINE_EACH_R1(__macro) \ + __macro(cusolverDnSpotrfBatched); \ + __macro(cusolverDnDpotrfBatched); \ + __macro(cusolverDnSpotrsBatched); \ + __macro(cusolverDnDpotrsBatched); \ + __macro(cusolverDnSgesvdj_bufferSize); \ + __macro(cusolverDnSgetrf_bufferSize); \ + __macro(cusolverDnDgetrf_bufferSize); \ + __macro(cusolverDnCgetrf_bufferSize); \ + __macro(cusolverDnZgetrf_bufferSize); \ + __macro(cusolverDnSgeqrf_bufferSize); \ + __macro(cusolverDnDgeqrf_bufferSize); \ + __macro(cusolverDnCgeqrf_bufferSize); \ + __macro(cusolverDnZgeqrf_bufferSize); \ + __macro(cusolverDnSorgqr_bufferSize); \ + __macro(cusolverDnDorgqr_bufferSize); \ + __macro(cusolverDnSormqr_bufferSize); \ + __macro(cusolverDnDormqr_bufferSize); \ + __macro(cusolverDnCungqr_bufferSize); \ + __macro(cusolverDnZungqr_bufferSize); \ + __macro(cusolverDnDestroyGesvdjInfo); \ + __macro(cusolverDnCreateGesvdjInfo); \ + __macro(cusolverDnDgesvdj_bufferSize); \ + __macro(cusolverDnSgesvdj); \ + __macro(cusolverDnDgesvdj); \ + __macro(cusolverDnSgetrf); \ + __macro(cusolverDnDgetrf); \ + __macro(cusolverDnCgetrf); \ + __macro(cusolverDnZgetrf); \ + __macro(cusolverDnSgeqrf); \ + __macro(cusolverDnDgeqrf); \ + __macro(cusolverDnCgeqrf); \ + __macro(cusolverDnZgeqrf); \ + __macro(cusolverDnSorgqr); \ + __macro(cusolverDnDorgqr); \ + __macro(cusolverDnSormqr); \ + __macro(cusolverDnDormqr); \ + __macro(cusolverDnCungqr); \ + __macro(cusolverDnZungqr); + +CUSOLVER_ROUTINE_EACH_R1(DECLARE_DYNAMIC_LOAD_CUSOLVER_WRAP) +#endif + +#if CUDA_VERSION >= 9020 +#define CUSOLVER_ROUTINE_EACH_R2(__macro) \ + __macro(cusolverDnCreateSyevjInfo); \ + __macro(cusolverDnSsyevj_bufferSize); \ + __macro(cusolverDnDsyevj_bufferSize); \ + __macro(cusolverDnSsyevj); \ + __macro(cusolverDnDsyevj); \ + __macro(cusolverDnDestroySyevjInfo); + +CUSOLVER_ROUTINE_EACH_R2(DECLARE_DYNAMIC_LOAD_CUSOLVER_WRAP) +#endif + +#undef DECLARE_DYNAMIC_LOAD_CUSOLVER_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparse.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparse.h new file mode 100644 index 0000000000000000000000000000000000000000..2f4ec151b1ece68a5a111cbdec0a40de8cf3beaa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparse.h @@ -0,0 +1,92 @@ +/* Copyright (c) 2021 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. */ +#pragma once + +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag cusparse_dso_flag; +extern void *cusparse_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_CUSPARSE_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + cusparseStatus_t operator()(Args... args) { \ + using Func = decltype(&::__name); \ + std::call_once(cusparse_dso_flag, []() { \ + cusparse_dso_handle = phi::dynload::GetCusparseDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cusparse_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#if defined(PADDLE_WITH_CUDA) +#if CUDA_VERSION >= 11000 +#define CUSPARSE_ROUTINE_EACH(__macro) \ + __macro(cusparseCreate); \ + __macro(cusparseSetStream); \ + __macro(cusparseCreateMatDescr); \ + __macro(cusparseDestroy); \ + __macro(cusparseSnnz); \ + __macro(cusparseDnnz); \ + __macro(cusparseSetMatType); \ + __macro(cusparseSetMatIndexBase); \ + __macro(cusparseCreateCsr); \ + __macro(cusparseCreateCoo); \ + __macro(cusparseCreateDnMat); \ + __macro(cusparseCreateDnVec); \ + __macro(cusparseSpMM_bufferSize); \ + __macro(cusparseSpMM); \ + __macro(cusparseDestroySpMat); \ + __macro(cusparseDestroyDnMat); \ + __macro(cusparseDestroyDnVec); \ + __macro(cusparseSpMV_bufferSize); \ + __macro(cusparseSpMV); + +CUSPARSE_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUSPARSE_WRAP) +#endif + +#if CUDA_VERSION >= 11030 +#define CUSPARSE_ROUTINE_EACH_R2(__macro) \ + __macro(cusparseSpMM_preprocess); \ + __macro(cusparseSDDMM_bufferSize); \ + __macro(cusparseSDDMM_preprocess); \ + __macro(cusparseSDDMM); + +CUSPARSE_ROUTINE_EACH_R2(DECLARE_DYNAMIC_LOAD_CUSPARSE_WRAP) +#endif + +#if CUDA_VERSION >= 11070 +#define CUSPARSE_ROUTINE_EACH_R3(__macro) \ + __macro(cusparseDnMatSetStridedBatch); \ + __macro(cusparseCooSetStridedBatch); \ + __macro(cusparseCsrSetStridedBatch); + +CUSPARSE_ROUTINE_EACH_R3(DECLARE_DYNAMIC_LOAD_CUSPARSE_WRAP) +#endif + +#endif // PADDLE_WITH_CUDA + +#undef DECLARE_DYNAMIC_LOAD_CUSPARSE_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparseLt.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparseLt.h new file mode 100644 index 0000000000000000000000000000000000000000..8eecefab5e469c7cfc994cee14dca2361e79b854 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/cusparseLt.h @@ -0,0 +1,78 @@ +/* Copyright (c) 2022 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. */ +#pragma once + +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag cusparselt_dso_flag; +extern void *cusparselt_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load cupti routine + * via operator overloading. + * + * note: default dynamic linked libs + */ +#define DECLARE_DYNAMIC_LOAD_CUSPARSELT_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + cusparseStatus_t operator()(Args... args) { \ + using cusparseltFunc = decltype(&::__name); \ + std::call_once(cusparselt_dso_flag, []() { \ + cusparselt_dso_handle = phi::dynload::GetCusparseLtDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(cusparselt_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name +#if defined(PADDLE_WITH_CUDA) +#if CUDA_VERSION >= 11020 +#define CUSPARSELT_ROUTINE_EACH(__macro) \ + __macro(cusparseLtInit); \ + __macro(cusparseLtDestroy); \ + __macro(cusparseLtDenseDescriptorInit); \ + __macro(cusparseLtStructuredDescriptorInit); \ + __macro(cusparseLtMatmulDescriptorInit); \ + __macro(cusparseLtMatmulDescSetAttribute); \ + __macro(cusparseLtMatmulAlgSelectionInit); \ + __macro(cusparseLtMatmulAlgSetAttribute); \ + __macro(cusparseLtMatmulGetWorkspace); \ + __macro(cusparseLtMatmulPlanInit); \ + __macro(cusparseLtMatDescriptorDestroy); \ + __macro(cusparseLtSpMMACompressedSize2); \ + __macro(cusparseLtSpMMACompress2); \ + __macro(cusparseLtMatmulSearch); \ + __macro(cusparseLtMatmulAlgGetAttribute); \ + __macro(cusparseLtMatmulPlanDestroy); \ + __macro(cusparseLtMatmul); \ + __macro(cusparseGetErrorString); + +CUSPARSELT_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CUSPARSELT_WRAP); +#endif +#endif + +#undef DECLARE_DYNAMIC_LOAD_CUSPARSELT_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/dynamic_loader.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/dynamic_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..642535fc50cf3e3d187f73c512fa86ff4164017d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/dynamic_loader.h @@ -0,0 +1,53 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#include + +namespace phi { +namespace dynload { + +#ifndef _WIN32 +#define DECLARE_TYPE(__name, ...) decltype(__name(__VA_ARGS__)) +#else +#define DECLARE_TYPE(__name, ...) decltype(auto) +#endif + +void* GetCublasDsoHandle(); +void* GetCublasLtDsoHandle(); +void* GetCUDNNDsoHandle(); +void* GetCUPTIDsoHandle(); +void* GetCurandDsoHandle(); +void* GetNvjpegDsoHandle(); +void* GetCusolverDsoHandle(); +void* GetCusparseDsoHandle(); +void* GetNVRTCDsoHandle(); +void* GetCUDADsoHandle(); +void* GetWarpCTCDsoHandle(); +void* GetNCCLDsoHandle(); +void* GetHCCLDsoHandle(); +void* GetTensorRtDsoHandle(); +void* GetMKLMLDsoHandle(); +void* GetLAPACKDsoHandle(); +void* GetOpDsoHandle(const std::string& dso_name); +void* GetNvtxDsoHandle(); +void* GetCUFFTDsoHandle(); +void* GetMKLRTDsoHandle(); +void* GetROCFFTDsoHandle(); +void* GetCusparseLtDsoHandle(); + +void SetPaddleLibPath(const std::string&); + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hipfft.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hipfft.h new file mode 100644 index 0000000000000000000000000000000000000000..4d45a26b8b9816b4937026a8b3c2e005ad37757b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hipfft.h @@ -0,0 +1,122 @@ +/* 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. */ +#pragma once +#ifdef PADDLE_WITH_HIP +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag hipfft_dso_flag; +extern void *hipfft_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_HIPFFT_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using hipfftFunc = decltype(&::__name); \ + std::call_once(hipfft_dso_flag, []() { \ + hipfft_dso_handle = phi::dynload::GetROCFFTDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(hipfft_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define HIPFFT_FFT_ROUTINE_EACH(__macro) \ + __macro(hipfftPlan1d); \ + __macro(hipfftPlan2d); \ + __macro(hipfftPlan3d); \ + __macro(hipfftPlanMany); \ + __macro(hipfftMakePlan1d); \ + __macro(hipfftMakePlanMany); \ + __macro(hipfftMakePlanMany64); \ + __macro(hipfftGetSizeMany64); \ + __macro(hipfftEstimate1d); \ + __macro(hipfftEstimate2d); \ + __macro(hipfftEstimate3d); \ + __macro(hipfftEstimateMany); \ + __macro(hipfftCreate); \ + __macro(hipfftGetSize1d); \ + __macro(hipfftGetSizeMany); \ + __macro(hipfftGetSize); \ + __macro(hipfftSetWorkArea); \ + __macro(hipfftSetAutoAllocation); \ + __macro(hipfftExecC2C); \ + __macro(hipfftExecR2C); \ + __macro(hipfftExecC2R); \ + __macro(hipfftExecZ2Z); \ + __macro(hipfftExecD2Z); \ + __macro(hipfftExecZ2D); \ + __macro(hipfftSetStream); \ + __macro(hipfftDestroy); \ + __macro(hipfftGetVersion); \ + __macro(hipfftGetProperty); + +HIPFFT_FFT_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_HIPFFT_WRAP); + +inline const char *hipfftGetErrorString(hipfftResult_t status) { + switch (status) { + case HIPFFT_SUCCESS: + return "'HIPFFT_SUCCESS'. The hipFFT operation was successful."; + case HIPFFT_INVALID_PLAN: + return "'HIPFFT_INVALID_PLAN'. hipFFT was passed an invalid plan handle."; + case HIPFFT_ALLOC_FAILED: + return "'HIPFFT_ALLOC_FAILED'. hipFFT failed to allocate GPU or CPU " + "memory."; + case HIPFFT_INVALID_TYPE: + return "'HIPFFT_INVALID_TYPE'. No longer used."; + case HIPFFT_INVALID_VALUE: + return "'HIPFFT_INVALID_VALUE'. User specified an invalid pointer or " + "parameter."; + case HIPFFT_INTERNAL_ERROR: + return "'HIPFFT_INTERNAL_ERROR'. Driver or internal hipFFT library " + "error."; + case HIPFFT_EXEC_FAILED: + return "'HIPFFT_EXEC_FAILED'. Failed to execute an FFT on the GPU."; + case HIPFFT_SETUP_FAILED: + return "'HIPFFT_SETUP_FAILED'. The hipFFT library failed to initialize."; + case HIPFFT_INVALID_SIZE: + return "'HIPFFT_INVALID_SIZE'. User specified an invalid transform size."; + case HIPFFT_UNALIGNED_DATA: + return "'HIPFFT_UNALIGNED_DATA'. No longer used."; + case HIPFFT_INCOMPLETE_PARAMETER_LIST: + return "'HIPFFT_INCOMPLETE_PARAMETER_LIST'. Missing parameters in call."; + case HIPFFT_INVALID_DEVICE: + return "'HIPFFT_INVALID_DEVICE'. Execution of a plan was on different " + "GPU than plan creation."; + case HIPFFT_PARSE_ERROR: + return "'HIPFFT_PARSE_ERROR'. Internal plan database error."; + case HIPFFT_NO_WORKSPACE: + return "'HIPFFT_NO_WORKSPACE'. No workspace has been provided prior to " + "plan execution."; + case HIPFFT_NOT_IMPLEMENTED: + return "'HIPFFT_NOT_IMPLEMENTED'. Function does not implement " + "functionality for parameters given."; + case HIPFFT_NOT_SUPPORTED: + return "'HIPFFT_NOT_SUPPORTED'. Operation is not supported for " + "parameters given."; + default: + return "HIPFFT_STATUS_UNKNOWN_ERROR"; + } +} +} // namespace dynload +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprand.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprand.h new file mode 100644 index 0000000000000000000000000000000000000000..3e9502dd94d911b0cc1329b9e7c09dad59435b26 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprand.h @@ -0,0 +1,54 @@ +/* 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. */ +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag hiprand_dso_flag; +extern void *hiprand_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_CURAND_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + hiprandStatus_t operator()(Args... args) { \ + using hiprandFunc = decltype(&::__name); \ + std::call_once(hiprand_dso_flag, []() { \ + hiprand_dso_handle = phi::dynload::GetCurandDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(hiprand_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define HIPRAND_RAND_ROUTINE_EACH(__macro) \ + __macro(hiprandCreateGenerator); \ + __macro(hiprandSetStream); \ + __macro(hiprandSetPseudoRandomGeneratorSeed); \ + __macro(hiprandGenerateUniform); \ + __macro(hiprandGenerateUniformDouble); \ + __macro(hiprandGenerateNormal); \ + __macro(hiprandDestroyGenerator); + +HIPRAND_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_CURAND_WRAP); + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprtc.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprtc.h new file mode 100644 index 0000000000000000000000000000000000000000..75dd88f87bd3aa9f1aea12ec8c8c68aff4f978ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/hiprtc.h @@ -0,0 +1,64 @@ +/* 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag hiprtc_dso_flag; +extern void* hiprtc_dso_handle; +extern bool HasNVRTC(); + +#define DECLARE_DYNAMIC_LOAD_HIPRTC_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using hiprtc_func = decltype(&::__name); \ + std::call_once(hiprtc_dso_flag, []() { \ + hiprtc_dso_handle = phi::dynload::GetNVRTCDsoHandle(); \ + }); \ + static void* p_##__name = dlsym(hiprtc_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed hiprtc functions + **/ +#define HIPRTC_ROUTINE_EACH(__macro) \ + __macro(hiprtcVersion); \ + __macro(hiprtcGetErrorString); \ + __macro(hiprtcCompileProgram); \ + __macro(hiprtcCreateProgram); \ + __macro(hiprtcDestroyProgram); \ + __macro(hiprtcGetCode); \ + __macro(hiprtcGetCodeSize); \ + __macro(hiprtcGetProgramLog); \ + __macro(hiprtcGetProgramLogSize) + +HIPRTC_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_HIPRTC_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_HIPRTC_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/lapack.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/lapack.h new file mode 100644 index 0000000000000000000000000000000000000000..1a680e32d1c32ee0d4e4cea01c02fbab58911fd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/lapack.h @@ -0,0 +1,371 @@ +/* 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. */ + +#pragma once + +#include +#include + +#include "paddle/fluid/platform/complex.h" +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +// Because lapack doesn't provide appropriate header file, +// we should expose API statement yourself. + +// getrf_(For example) +extern "C" void dgetrf_( + int *m, int *n, double *a, int *lda, int *ipiv, int *info); +extern "C" void sgetrf_( + int *m, int *n, float *a, int *lda, int *ipiv, int *info); + +// evd +extern "C" void zheevd_(char *jobz, + char *uplo, + int *n, + std::complex *a, + int *lda, + double *w, + std::complex *work, + int *lwork, + double *rwork, + int *lrwork, + int *iwork, + int *liwork, + int *info); +extern "C" void cheevd_(char *jobz, + char *uplo, + int *n, + std::complex *a, + int *lda, + float *w, + std::complex *work, + int *lwork, + float *rwork, + int *lrwork, + int *iwork, + int *liwork, + int *info); +extern "C" void dsyevd_(char *jobz, + char *uplo, + int *n, + double *a, + int *lda, + double *w, + double *work, + int *lwork, + int *iwork, + int *liwork, + int *info); +extern "C" void ssyevd_(char *jobz, + char *uplo, + int *n, + float *a, + int *lda, + float *w, + float *work, + int *lwork, + int *iwork, + int *liwork, + int *info); + +// geev +extern "C" void dgeev_(char *jobvl, + char *jobvr, + int *n, + double *a, + int *lda, + double *wr, + double *wi, + double *vl, + int *ldvl, + double *vr, + int *ldvr, + double *work, + int *lwork, + int *info); +extern "C" void sgeev_(char *jobvl, + char *jobvr, + int *n, + float *a, + int *lda, + float *wr, + float *wi, + float *vl, + int *ldvl, + float *vr, + int *ldvr, + float *work, + int *lwork, + int *info); +extern "C" void zgeev_(char *jobvl, + char *jobvr, + int *n, + std::complex *a, + int *lda, + std::complex *w, + std::complex *vl, + int *ldvl, + std::complex *vr, + int *ldvr, + std::complex *work, + int *lwork, + double *rwork, + int *info); +extern "C" void cgeev_(char *jobvl, + char *jobvr, + int *n, + std::complex *a, + int *lda, + std::complex *w, + std::complex *vl, + int *ldvl, + std::complex *vr, + int *ldvr, + std::complex *work, + int *lwork, + float *rwork, + int *info); + +// gels +extern "C" void dgels_(char *trans, + int *m, + int *n, + int *nrhs, + double *a, + int *lda, + double *b, + int *ldb, + double *work, + int *lwork, + int *info); +extern "C" void sgels_(char *trans, + int *m, + int *n, + int *nrhs, + float *a, + int *lda, + float *b, + int *ldb, + float *work, + int *lwork, + int *info); + +// gelsd +extern "C" void dgelsd_(int *m, + int *n, + int *nrhs, + double *a, + int *lda, + double *b, + int *ldb, + double *s, + double *rcond, + int *rank, + double *work, + int *lwork, + int *iwork, + int *info); +extern "C" void sgelsd_(int *m, + int *n, + int *nrhs, + float *a, + int *lda, + float *b, + int *ldb, + float *s, + float *rcond, + int *rank, + float *work, + int *lwork, + int *iwork, + int *info); + +// gelsy +extern "C" void dgelsy_(int *m, + int *n, + int *nrhs, + double *a, + int *lda, + double *b, + int *ldb, + int *jpvt, + double *rcond, + int *rank, + double *work, + int *lwork, + int *info); +extern "C" void sgelsy_(int *m, + int *n, + int *nrhs, + float *a, + int *lda, + float *b, + int *ldb, + int *jpvt, + float *rcond, + int *rank, + float *work, + int *lwork, + int *info); + +// gelss +extern "C" void dgelss_(int *m, + int *n, + int *nrhs, + double *a, + int *lda, + double *b, + int *ldb, + double *s, + double *rcond, + int *rank, + double *work, + int *lwork, + int *info); +extern "C" void sgelss_(int *m, + int *n, + int *nrhs, + float *a, + int *lda, + float *b, + int *ldb, + float *s, + float *rcond, + int *rank, + float *work, + int *lwork, + int *info); + +extern "C" void zpotrs_(char *uplo, + int *n, + int *nrhs, + std::complex *a, + int *lda, + std::complex *b, + int *ldb, + int *info); +extern "C" void cpotrs_(char *uplo, + int *n, + int *nrhs, + std::complex *a, + int *lda, + std::complex *b, + int *ldb, + int *info); +extern "C" void dpotrs_(char *uplo, + int *n, + int *nrhs, + double *a, + int *lda, + double *b, + int *ldb, + int *info); +extern "C" void spotrs_(char *uplo, + int *n, + int *nrhs, + float *a, + int *lda, + float *b, + int *ldb, + int *info); +extern "C" void dgesdd_(char *, + int *, + int *, + double *, + int *, + double *, + double *, + int *, + double *, + int *, + double *, + int *, + int *, + int *); +extern "C" void sgesdd_(char *, + int *, + int *, + float *, + int *, + float *, + float *, + int *, + float *, + int *, + float *, + int *, + int *, + int *); + +namespace phi { +namespace dynload { + +extern std::once_flag lapack_dso_flag; +extern void *lapack_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load lapack routine + * via operator overloading. + */ +#define DYNAMIC_LOAD_LAPACK_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using lapackFunc = decltype(&::__name); \ + std::call_once(lapack_dso_flag, []() { \ + lapack_dso_handle = phi::dynload::GetLAPACKDsoHandle(); \ + }); \ + static void *p_##_name = dlsym(lapack_dso_handle, #__name); \ + return reinterpret_cast(p_##_name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define DECLARE_DYNAMIC_LOAD_LAPACK_WRAP(__name) \ + DYNAMIC_LOAD_LAPACK_WRAP(__name) + +#define LAPACK_ROUTINE_EACH(__macro) \ + __macro(dgetrf_); \ + __macro(sgetrf_); \ + __macro(zheevd_); \ + __macro(cheevd_); \ + __macro(dsyevd_); \ + __macro(ssyevd_); \ + __macro(dgeev_); \ + __macro(sgeev_); \ + __macro(zgeev_); \ + __macro(cgeev_); \ + __macro(dgels_); \ + __macro(sgels_); \ + __macro(dgelsd_); \ + __macro(sgelsd_); \ + __macro(dgelsy_); \ + __macro(sgelsy_); \ + __macro(dgelss_); \ + __macro(sgelss_); \ + __macro(sgesdd_); \ + __macro(dgesdd_); \ + __macro(zpotrs_); \ + __macro(cpotrs_); \ + __macro(dpotrs_); \ + __macro(spotrs_); + +LAPACK_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_LAPACK_WRAP); + +#undef DYNAMIC_LOAD_LAPACK_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/miopen.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/miopen.h new file mode 100644 index 0000000000000000000000000000000000000000..eeaf8028ec312402427fd9c23467a3a0996973a1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/miopen.h @@ -0,0 +1,197 @@ +/* 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. */ + +#pragma once +#include +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +#define MIOPEN_VERSION \ + (MIOPEN_VERSION_MAJOR * 1000 + MIOPEN_VERSION_MINOR * 10 + \ + MIOPEN_VERSION_PATCH) // NOLINT + +// MIOPEN only support NCHW, just for compatibility with CUDNN API +typedef enum { + MIOPEN_TENSOR_NCHW = 0, + MIOPEN_TENSOR_NHWC = 1, +} miopenTensorFormat_t; + +namespace phi { +namespace dynload { + +extern std::once_flag miopen_dso_flag; +extern void* miopen_dso_handle; +extern bool HasCUDNN(); + +inline const char* miopenGetErrorString(miopenStatus_t status) { + switch (status) { + case miopenStatusSuccess: + return "MIOPEN_STATUS_SUCCESS"; + case miopenStatusNotInitialized: + return "MIOPEN_STATUS_NOT_INITIALIZED"; + case miopenStatusInvalidValue: + return "MIOPEN_STATUS_INVALID_VALUE"; + case miopenStatusBadParm: + return "MIOPEN_STATUS_BAD_PARAM"; + case miopenStatusAllocFailed: + return "MIOPEN_STATUS_ALLOC_FAILED"; + case miopenStatusInternalError: + return "MIOPEN_STATUS_INTERNAL_ERROR"; + case miopenStatusNotImplemented: + return "MIOPEN_STATUS_NOT_IMPLEMENTED"; + case miopenStatusUnsupportedOp: + return "MIOPEN_STATUS_UNSUPPORTED_OP"; + case miopenStatusUnknownError: + default: + return "MIOPEN_STATUS_UNKNOWN_ERROR"; + } +} + +extern void EnforceCUDNNLoaded(const char* fn_name); +#define DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using miopen_func = decltype(&::__name); \ + std::call_once(miopen_dso_flag, []() { \ + miopen_dso_handle = phi::dynload::GetCUDNNDsoHandle(); \ + }); \ + EnforceCUDNNLoaded(#__name); \ + static void* p_##__name = dlsym(miopen_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed miopen functions in HPPL + **/ +#define MIOPEN_DNN_ROUTINE_EACH(__macro) \ + __macro(miopenGetVersion); \ + __macro(miopenOpTensor); \ + __macro(miopenSet4dTensorDescriptor); \ + __macro(miopenSetTensorDescriptor); \ + __macro(miopenInitConvolutionNdDescriptor); \ + __macro(miopenFindConvolutionForwardAlgorithm); \ + __macro(miopenGetConvolutionNdForwardOutputDim); \ + __macro(miopenFindConvolutionBackwardDataAlgorithm); \ + __macro(miopenFindConvolutionBackwardWeightsAlgorithm); \ + __macro(miopenGetTensorDescriptor); \ + __macro(miopenCreateTensorDescriptor); \ + __macro(miopenDestroyTensorDescriptor); \ + __macro(miopenGetTensorDescriptorSize); \ + __macro(miopenSet2dPoolingDescriptor); \ + __macro(miopenGet2dPoolingDescriptor); \ + __macro(miopenGetPoolingNdForwardOutputDim); \ + __macro(miopenCreateConvolutionDescriptor); \ + __macro(miopenCreatePoolingDescriptor); \ + __macro(miopenDestroyPoolingDescriptor); \ + __macro(miopenPoolingGetWorkSpaceSize); \ + __macro(miopenPoolingGetWorkSpaceSizeV2); \ + __macro(miopenSetNdPoolingDescriptor); \ + __macro(miopenInitConvolutionDescriptor); \ + __macro(miopenDestroyConvolutionDescriptor); \ + __macro(miopenGetConvolutionNdDescriptor); \ + __macro(miopenDeriveBNTensorDescriptor); \ + __macro(miopenCreate); \ + __macro(miopenDestroy); \ + __macro(miopenSetStream); \ + __macro(miopenActivationForward); \ + __macro(miopenActivationBackward); \ + __macro(miopenConvolutionBackwardWeights); \ + __macro(miopenConvolutionForward); \ + __macro(miopenConvolutionForwardBias); \ + __macro(miopenConvolutionBackwardBias); \ + __macro(miopenConvolutionForwardGetWorkSpaceSize); \ + __macro(miopenConvolutionBackwardDataGetWorkSpaceSize); \ + __macro(miopenTransformTensor); \ + __macro(miopenPoolingForward); \ + __macro(miopenPoolingBackward); \ + __macro(miopenSoftmaxBackward); \ + __macro(miopenSoftmaxBackward_V2); \ + __macro(miopenSoftmaxForward); \ + __macro(miopenSoftmaxForward_V2); \ + __macro(miopenCreateDropoutDescriptor); \ + __macro(miopenDestroyDropoutDescriptor); \ + __macro(miopenRestoreDropoutDescriptor); \ + __macro(miopenDropoutGetStatesSize); \ + __macro(miopenSetDropoutDescriptor); \ + __macro(miopenCreateRNNDescriptor); \ + __macro(miopenDestroyRNNDescriptor); \ + __macro(miopenSetRNNDescriptor); \ + __macro(miopenSetRNNDescriptor_V2); \ + __macro(miopenGetRNNParamsSize); \ + __macro(miopenGetRNNWorkspaceSize); \ + __macro(miopenGetRNNTrainingReserveSize); \ + __macro(miopenRNNForwardTraining); \ + __macro(miopenRNNBackwardData); \ + __macro(miopenRNNBackwardWeights); \ + __macro(miopenRNNForwardInference); \ + __macro(miopenGetTensorNumBytes); + +MIOPEN_DNN_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +#define MIOPEN_DNN_ROUTINE_EACH_R2(__macro) \ + __macro(miopenConvolutionBackwardData); +MIOPEN_DNN_ROUTINE_EACH_R2(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +// APIs available after R3: +#define MIOPEN_DNN_ROUTINE_EACH_AFTER_R3(__macro) \ + __macro(miopenConvolutionBackwardWeightsGetWorkSpaceSize); +MIOPEN_DNN_ROUTINE_EACH_AFTER_R3(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +// APIs available after R4: +#define MIOPEN_DNN_ROUTINE_EACH_AFTER_R4(__macro) \ + __macro(miopenBatchNormalizationForwardTraining); \ + __macro(miopenBatchNormalizationForwardInference); \ + __macro(miopenBatchNormalizationBackward); +MIOPEN_DNN_ROUTINE_EACH_AFTER_R4(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +// APIs in R5 +#define MIOPEN_DNN_ROUTINE_EACH_R5(__macro) \ + __macro(miopenCreateActivationDescriptor); \ + __macro(miopenSetActivationDescriptor); \ + __macro(miopenGetActivationDescriptor); \ + __macro(miopenDestroyActivationDescriptor); +MIOPEN_DNN_ROUTINE_EACH_R5(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +// APIs in R6 +#define MIOPEN_DNN_ROUTINE_EACH_R6(__macro) \ +/*__macro(miopenSetRNNDescriptor_v6);*/ +MIOPEN_DNN_ROUTINE_EACH_R6(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +#define MIOPEN_DNN_ROUTINE_EACH_R7(__macro) \ + __macro(miopenSetConvolutionGroupCount); \ + __macro(miopenCreateCTCLossDescriptor); \ + __macro(miopenDestroyCTCLossDescriptor); \ + __macro(miopenGetCTCLossDescriptor); \ + __macro(miopenSetCTCLossDescriptor); \ + __macro(miopenGetCTCLossWorkspaceSize); \ + __macro(miopenCTCLoss); +MIOPEN_DNN_ROUTINE_EACH_R7(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) + +#define MIOPEN_DNN_ROUTINE_EACH_AFTER_R7(__macro) \ +/*__macro(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize); \ +__macro(cudnnBatchNormalizationForwardTrainingEx); \ +__macro(cudnnGetBatchNormalizationBackwardExWorkspaceSize); \ +__macro(cudnnBatchNormalizationBackwardEx); \ +__macro(cudnnGetBatchNormalizationTrainingExReserveSpaceSize);*/ +MIOPEN_DNN_ROUTINE_EACH_AFTER_R7(DECLARE_DYNAMIC_LOAD_MIOPEN_WRAP) +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklml.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklml.h new file mode 100644 index 0000000000000000000000000000000000000000..0f0c31f8064dffe6065c78c3d68c1bcf3bb592a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklml.h @@ -0,0 +1,124 @@ +/* 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag mklml_dso_flag; +extern void *mklml_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load mklml routine + * via operator overloading. + */ +#define DYNAMIC_LOAD_MKLML_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using mklmlFunc = decltype(&::__name); \ + std::call_once(mklml_dso_flag, []() { \ + mklml_dso_handle = phi::dynload::GetMKLMLDsoHandle(); \ + }); \ + static void *p_##_name = dlsym(mklml_dso_handle, #__name); \ + return reinterpret_cast(p_##_name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define DECLARE_DYNAMIC_LOAD_MKLML_WRAP(__name) DYNAMIC_LOAD_MKLML_WRAP(__name) + +#define MKLML_ROUTINE_EACH(__macro) \ + __macro(cblas_sgemm); \ + __macro(cblas_dgemm); \ + __macro(cblas_cgemm); \ + __macro(cblas_zgemm); \ + __macro(cblas_saxpy); \ + __macro(cblas_daxpy); \ + __macro(cblas_caxpy); \ + __macro(cblas_zaxpy); \ + __macro(cblas_scopy); \ + __macro(cblas_dcopy); \ + __macro(cblas_ccopy); \ + __macro(cblas_zcopy); \ + __macro(cblas_sgemv); \ + __macro(cblas_dgemv); \ + __macro(cblas_cgemv); \ + __macro(cblas_zgemv); \ + __macro(cblas_strsm); \ + __macro(cblas_dtrsm); \ + __macro(cblas_ctrsm); \ + __macro(cblas_ztrsm); \ + __macro(cblas_sgemm_alloc); \ + __macro(cblas_dgemm_alloc); \ + __macro(cblas_sgemm_pack); \ + __macro(cblas_dgemm_pack); \ + __macro(cblas_sgemm_compute); \ + __macro(cblas_dgemm_compute); \ + __macro(cblas_sgemm_free); \ + __macro(cblas_dgemm_free); \ + __macro(cblas_sgemm_batch); \ + __macro(cblas_dgemm_batch); \ + __macro(cblas_cgemm_batch); \ + __macro(cblas_zgemm_batch); \ + __macro(cblas_sdot); \ + __macro(cblas_ddot); \ + __macro(cblas_sasum); \ + __macro(cblas_dasum); \ + __macro(cblas_isamax); \ + __macro(cblas_idamax); \ + __macro(cblas_sscal); \ + __macro(cblas_dscal); \ + __macro(vsAdd); \ + __macro(vdAdd); \ + __macro(vsSub); \ + __macro(vdSub); \ + __macro(vsMul); \ + __macro(vdMul); \ + __macro(vsDiv); \ + __macro(vdDiv); \ + __macro(vsExp); \ + __macro(vdExp); \ + __macro(vsSqr); \ + __macro(vdSqr); \ + __macro(vsPowx); \ + __macro(vdPowx); \ + __macro(vsInv); \ + __macro(vdInv); \ + __macro(vmsErf); \ + __macro(vmdErf); \ + __macro(MKL_Free_Buffers); \ + __macro(MKL_Set_Num_Threads); \ + __macro(MKL_Get_Max_Threads); + +MKLML_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_MKLML_WRAP); + +#if !defined(_WIN32) +DYNAMIC_LOAD_MKLML_WRAP(mkl_scsrmm); +DYNAMIC_LOAD_MKLML_WRAP(mkl_dcsrmm); +#endif + +#undef DYNAMIC_LOAD_MKLML_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklrt.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklrt.h new file mode 100644 index 0000000000000000000000000000000000000000..0267fb69a5932cccc3d8d0161dd3ea63912066f5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/mklrt.h @@ -0,0 +1,80 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag mklrt_dso_flag; +extern void* mklrt_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load mkldfti routine + * via operator overloading. + */ +#define DYNAMIC_LOAD_MKLRT_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using mklrtFunc = decltype(&::__name); \ + std::call_once(mklrt_dso_flag, []() { \ + mklrt_dso_handle = phi::dynload::GetMKLRTDsoHandle(); \ + }); \ + static void* p_##__name = dlsym(mklrt_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +// mkl_dfti.h has a macro that shadows the function with the same name +// un-defeine this macro so as to export that function +#undef DftiCreateDescriptor + +#define MKLDFTI_ROUTINE_EACH(__macro) \ + __macro(DftiCreateDescriptor); \ + __macro(DftiCreateDescriptor_s_1d); \ + __macro(DftiCreateDescriptor_d_1d); \ + __macro(DftiCreateDescriptor_s_md); \ + __macro(DftiCreateDescriptor_d_md); \ + __macro(DftiSetValue); \ + __macro(DftiGetValue); \ + __macro(DftiCommitDescriptor); \ + __macro(DftiComputeForward); \ + __macro(DftiComputeBackward); \ + __macro(DftiFreeDescriptor); \ + __macro(DftiErrorClass); \ + __macro(DftiErrorMessage); + +MKLDFTI_ROUTINE_EACH(DYNAMIC_LOAD_MKLRT_WRAP) + +#undef DYNAMIC_LOAD_MKLRT_WRAP + +// define another function to avoid naming conflict +DFTI_EXTERN MKL_LONG DftiCreateDescriptorX(DFTI_DESCRIPTOR_HANDLE* desc, + enum DFTI_CONFIG_VALUE prec, + enum DFTI_CONFIG_VALUE domain, + MKL_LONG dim, + MKL_LONG* sizes); + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nccl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..6c73c562caa69701baf91839b27d07cd1b381d00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nccl.h @@ -0,0 +1,87 @@ +/* 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. */ +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag nccl_dso_flag; +extern void* nccl_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_NCCL_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> decltype(__name(args...)) { \ + using nccl_func = decltype(&::__name); \ + std::call_once(nccl_dso_flag, []() { \ + nccl_dso_handle = phi::dynload::GetNCCLDsoHandle(); \ + }); \ + static void* p_##__name = dlsym(nccl_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define NCCL_RAND_ROUTINE_EACH(__macro) \ + __macro(ncclCommInitAll); \ + __macro(ncclGetUniqueId); \ + __macro(ncclCommInitRank); \ + __macro(ncclCommDestroy); \ + __macro(ncclCommCount); \ + __macro(ncclCommCuDevice); \ + __macro(ncclCommUserRank); \ + __macro(ncclAllReduce); \ + __macro(ncclBcast); \ + __macro(ncclAllGather); \ + __macro(ncclGroupStart); \ + __macro(ncclGroupEnd); \ + __macro(ncclReduce); \ + __macro(ncclReduceScatter); \ + __macro(ncclGetErrorString); + +NCCL_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_NCCL_WRAP) + +#if NCCL_VERSION_CODE >= 2212 +#define NCCL_RAND_ROUTINE_EACH_AFTER_2212(__macro) __macro(ncclBroadcast); +NCCL_RAND_ROUTINE_EACH_AFTER_2212(DECLARE_DYNAMIC_LOAD_NCCL_WRAP) +#endif + +#if NCCL_VERSION_CODE >= 2304 +#define NCCL_RAND_ROUTINE_EACH_AFTER_2304(__macro) __macro(ncclGetVersion); +NCCL_RAND_ROUTINE_EACH_AFTER_2304(DECLARE_DYNAMIC_LOAD_NCCL_WRAP) +#endif + +#if NCCL_VERSION_CODE >= 2703 +#define NCCL_RAND_ROUTINE_EACH_AFTER_2703(__macro) \ + __macro(ncclSend); \ + __macro(ncclRecv); +NCCL_RAND_ROUTINE_EACH_AFTER_2703(DECLARE_DYNAMIC_LOAD_NCCL_WRAP) +#endif + +#if NCCL_VERSION_CODE >= 21100 +#define NCCL_RAND_ROUTINE_EACH_AFTER_21100(__macro) \ + __macro(ncclRedOpCreatePreMulSum); \ + __macro(ncclRedOpDestroy); +NCCL_RAND_ROUTINE_EACH_AFTER_21100(DECLARE_DYNAMIC_LOAD_NCCL_WRAP) +#endif + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvjpeg.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvjpeg.h new file mode 100644 index 0000000000000000000000000000000000000000..6e71e6b582c059830152eca5c14c24699bc35c3a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvjpeg.h @@ -0,0 +1,52 @@ +/* Copyright (c) 2021 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. */ +#pragma once + +#ifdef PADDLE_WITH_CUDA +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag nvjpeg_dso_flag; +extern void *nvjpeg_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_NVJPEG_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + nvjpegStatus_t operator()(Args... args) { \ + using nvjpegFunc = decltype(&::__name); \ + std::call_once(nvjpeg_dso_flag, []() { \ + nvjpeg_dso_handle = phi::dynload::GetNvjpegDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(nvjpeg_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define NVJPEG_RAND_ROUTINE_EACH(__macro) \ + __macro(nvjpegCreateSimple); \ + __macro(nvjpegJpegStateCreate); \ + __macro(nvjpegGetImageInfo); \ + __macro(nvjpegJpegStateDestroy); \ + __macro(nvjpegDecode); + +NVJPEG_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_NVJPEG_WRAP); + +} // namespace dynload +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvrtc.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvrtc.h new file mode 100644 index 0000000000000000000000000000000000000000..9244e9487b2505a05466c89c9746182b7734dac9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvrtc.h @@ -0,0 +1,64 @@ +/* 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag nvrtc_dso_flag; +extern void* nvrtc_dso_handle; +extern bool HasNVRTC(); + +#define DECLARE_DYNAMIC_LOAD_NVRTC_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using nvrtc_func = decltype(&::__name); \ + std::call_once(nvrtc_dso_flag, []() { \ + nvrtc_dso_handle = phi::dynload::GetNVRTCDsoHandle(); \ + }); \ + static void* p_##__name = dlsym(nvrtc_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed nvrtc functions + **/ +#define NVRTC_ROUTINE_EACH(__macro) \ + __macro(nvrtcVersion); \ + __macro(nvrtcGetErrorString); \ + __macro(nvrtcCompileProgram); \ + __macro(nvrtcCreateProgram); \ + __macro(nvrtcDestroyProgram); \ + __macro(nvrtcGetPTX); \ + __macro(nvrtcGetPTXSize); \ + __macro(nvrtcGetProgramLog); \ + __macro(nvrtcGetProgramLogSize) + +NVRTC_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_NVRTC_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_NVRTC_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvtx.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvtx.h new file mode 100644 index 0000000000000000000000000000000000000000..a9a166b289e3320c27f93d21a5a1daf2dfec821a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/nvtx.h @@ -0,0 +1,52 @@ +/* Copyright (c) 2021 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. */ +#pragma once +#ifndef _WIN32 +#include +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { +extern std::once_flag nvtx_dso_flag; +extern void *nvtx_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_NVTX_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + int operator()(Args... args) { \ + using nvtxFunc = decltype(&::__name); \ + std::call_once(nvtx_dso_flag, []() { \ + nvtx_dso_handle = phi::dynload::GetNvtxDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(nvtx_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define NVTX_ROUTINE_EACH(__macro) \ + __macro(nvtxRangePushA); \ + __macro(nvtxRangePop); + +NVTX_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_NVTX_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_NVTX_WRAP +} // namespace dynload +} // namespace phi +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/port.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/port.h new file mode 100644 index 0000000000000000000000000000000000000000..03a2863e4dc4ee5503731e655cc1e5f9e5d281f3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/port.h @@ -0,0 +1,60 @@ +// Copyright (c) 2018 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. + +#pragma once + +#include + +#define GLOG_NO_ABBREVIATED_SEVERITIES // msvc conflict logging with windows.h + +#if !defined(_WIN32) +#include // dladdr +#include + +#else +#ifndef NOMINMAX +#define NOMINMAX // msvc max/min macro conflict with std::min/max +#endif +// solve static linking error in windows +// https://github.com/google/glog/issues/301 +#define GOOGLE_GLOG_DLL_DECL +#include // _popen, _pclose +#include +#include +#include + +#ifndef S_ISDIR // windows port for sys/stat.h +#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) +#endif // S_ISDIR + +void *dlsym(void *handle, const char *symbol_name); + +void *dlopen(const char *filename, int flag); + +int gettimeofday(struct timeval *tp, void *tzp); +#endif // !_WIN32 + +void ExecShellCommand(const std::string &cmd, std::string *message); + +bool PathExists(const std::string &path); + +// TODO(yuyang18): If the functions below are needed by other files, move them +// to paddle::filesystem namespace. +bool FileExists(const std::string &filepath); + +std::string DirName(const std::string &filepath); + +void MkDir(const char *path); + +void MkDirRecursively(const char *fullpath); diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rccl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rccl.h new file mode 100644 index 0000000000000000000000000000000000000000..2da35dc2df2db32cbe911e2a3302cafbc92e848e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rccl.h @@ -0,0 +1,75 @@ +/* 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. */ +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag rccl_dso_flag; +extern void* rccl_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_RCCL_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> decltype(__name(args...)) { \ + using nccl_func = decltype(&::__name); \ + std::call_once(rccl_dso_flag, []() { \ + rccl_dso_handle = phi::dynload::GetNCCLDsoHandle(); \ + }); \ + static void* p_##__name = dlsym(rccl_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define RCCL_RAND_ROUTINE_EACH(__macro) \ + __macro(ncclCommInitAll); \ + __macro(ncclGetUniqueId); \ + __macro(ncclCommInitRank); \ + __macro(ncclCommDestroy); \ + __macro(ncclCommCount); \ + __macro(ncclCommCuDevice); \ + __macro(ncclCommUserRank); \ + __macro(ncclAllReduce); \ + __macro(ncclBcast); \ + __macro(ncclAllGather); \ + __macro(ncclGroupStart); \ + __macro(ncclGroupEnd); \ + __macro(ncclReduce); \ + __macro(ncclReduceScatter); \ + __macro(ncclGetErrorString); + +RCCL_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_RCCL_WRAP) + +#if NCCL_VERSION_CODE >= 2212 +#define RCCL_RAND_ROUTINE_EACH_AFTER_2212(__macro) __macro(ncclBroadcast); +RCCL_RAND_ROUTINE_EACH_AFTER_2212(DECLARE_DYNAMIC_LOAD_RCCL_WRAP) +#endif + +#if NCCL_VERSION_CODE >= 2703 +#define RCCL_RAND_ROUTINE_EACH_AFTER_2703(__macro) \ + __macro(ncclSend); \ + __macro(ncclRecv); +RCCL_RAND_ROUTINE_EACH_AFTER_2703(DECLARE_DYNAMIC_LOAD_RCCL_WRAP) +#endif + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocblas.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocblas.h new file mode 100644 index 0000000000000000000000000000000000000000..a9804b3d82a7de4c5c1c5fabc12de902640cb7d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocblas.h @@ -0,0 +1,113 @@ +/* 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. */ + +#pragma once + +#include +#include + +#include // NOLINT +#include + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag rocblas_dso_flag; +extern void *rocblas_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load cublas routine + * via operator overloading. + * + * note: default dynamic linked libs + */ +#define DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + rocblas_status operator()(Args... args) { \ + using rocblas_func = decltype(&::__name); \ + std::call_once(rocblas_dso_flag, []() { \ + rocblas_dso_handle = phi::dynload::GetCublasDsoHandle(); \ + }); \ + static void *p_##__name = dlsym(rocblas_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define ROCBLAS_BLAS_ROUTINE_EACH(__macro) \ + __macro(rocblas_caxpy); \ + __macro(rocblas_saxpy); \ + __macro(rocblas_daxpy); \ + __macro(rocblas_zaxpy); \ + __macro(rocblas_sscal); \ + __macro(rocblas_dscal); \ + __macro(rocblas_scopy); \ + __macro(rocblas_dcopy); \ + __macro(rocblas_cgemv); \ + __macro(rocblas_sgemv); \ + __macro(rocblas_zgemv); \ + __macro(rocblas_dgemv); \ + __macro(rocblas_cgemm); \ + __macro(rocblas_sgemm); \ + __macro(rocblas_dgemm); \ + __macro(rocblas_hgemm); \ + __macro(rocblas_zgemm); \ + __macro(rocblas_sgeam); \ + __macro(rocblas_strsm); \ + __macro(rocblas_dtrsm); \ + __macro(rocblas_dgeam); \ + __macro(rocblas_sgemm_batched); \ + __macro(rocblas_dgemm_batched); \ + __macro(rocblas_cgemm_batched); \ + __macro(rocblas_zgemm_batched); \ + __macro(rocblas_create_handle); \ + __macro(rocblas_destroy_handle); \ + __macro(rocblas_set_stream); \ + __macro(rocblas_get_stream); \ + __macro(rocblas_set_pointer_mode); \ + __macro(rocblas_get_pointer_mode); + +ROCBLAS_BLAS_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP) + +// APIs available after CUDA 8.0 +#define ROCBLAS_BLAS_ROUTINE_EACH_R2(__macro) \ + __macro(rocblas_gemm_ex); \ + __macro(rocblas_sgemm_strided_batched); \ + __macro(rocblas_dgemm_strided_batched); \ + __macro(rocblas_cgemm_strided_batched); \ + __macro(rocblas_zgemm_strided_batched); \ + __macro(rocblas_hgemm_strided_batched); + +ROCBLAS_BLAS_ROUTINE_EACH_R2(DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP) + +// HIP not supported in ROCM3.5 +// #define ROCBLAS_BLAS_ROUTINE_EACH_R3(__macro) +// __macro(cublasSetMathMode); +// __macro(cublasGetMathMode); +// ROCBLAS_BLAS_ROUTINE_EACH_R3(DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP) + +#define ROCBLAS_BLAS_ROUTINE_EACH_R4(__macro) \ + __macro(rocblas_gemm_batched_ex); \ + __macro(rocblas_gemm_strided_batched_ex); + +ROCBLAS_BLAS_ROUTINE_EACH_R4(DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP) + +#undef DECLARE_DYNAMIC_LOAD_ROCBLAS_WRAP +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocm_driver.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocm_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..4e456db44c90403c4d1bce8e32faec5ecbbda831 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/rocm_driver.h @@ -0,0 +1,67 @@ +/* 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. */ + +#pragma once + +#include + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" + +namespace phi { +namespace dynload { + +extern std::once_flag rocm_dso_flag; +extern void* rocm_dso_handle; +extern bool HasCUDADriver(); + +#define DECLARE_DYNAMIC_LOAD_ROCM_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using rocm_func = decltype(&::__name); \ + std::call_once(rocm_dso_flag, []() { \ + rocm_dso_handle = phi::dynload::GetCUDADsoHandle(); \ + }); \ + static void* p_##__name = dlsym(rocm_dso_handle, #__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern struct DynLoad__##__name __name + +/** + * include all needed cuda driver functions + **/ +#define ROCM_ROUTINE_EACH(__macro) \ + __macro(hipDriverGetVersion); \ + __macro(hipGetErrorString); \ + __macro(hipModuleLoadData); \ + __macro(hipModuleGetFunction); \ + __macro(hipModuleUnload); \ + /*rocm3.5 not support the function*/ \ + /* __macro(hipOccupancyMaxActiveBlocksPerMultiprocessor);*/ \ + __macro(hipModuleLaunchKernel); \ + __macro(hipLaunchKernel); \ + __macro(hipGetDevice); \ + __macro(hipGetDeviceCount); \ + __macro(hipDevicePrimaryCtxGetState) + +ROCM_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_ROCM_WRAP); + +#undef DECLARE_DYNAMIC_LOAD_ROCM_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/tensorrt.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/tensorrt.h new file mode 100644 index 0000000000000000000000000000000000000000..cd8c6457f1b91b938f1ef927119c9ec63a7b6e1b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/tensorrt.h @@ -0,0 +1,118 @@ +/* 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. */ +#pragma once + +#include +#include +#if !defined(_WIN32) +#include +#endif + +#include // NOLINT + +#include "paddle/fluid/platform/enforce.h" +#include "paddle/phi/backends/dynload/dynamic_loader.h" + +namespace phi { +namespace dynload { + +void* GetTensorRtHandle(); + +extern std::once_flag tensorrt_dso_flag; +extern void* tensorrt_dso_handle; + +void* GetTensorRtPluginHandle(); +extern std::once_flag tensorrt_plugin_dso_flag; +extern void* tensorrt_plugin_dso_handle; + +#define DECLARE_DYNAMIC_LOAD_TENSORRT_POINTER_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + void* operator()(Args... args) { \ + std::call_once(tensorrt_dso_flag, []() { \ + tensorrt_dso_handle = phi::dynload::GetTensorRtHandle(); \ + }); \ + static void* p_##__name = dlsym(tensorrt_dso_handle, #__name); \ + if (p_##__name == nullptr) { \ + return nullptr; \ + } \ + using tensorrt_func = decltype(&::__name); \ + auto ret = reinterpret_cast(p_##__name)(args...); \ + return static_cast(ret); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define DECLARE_DYNAMIC_LOAD_TENSORRT_NON_POINTER_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + std::call_once(tensorrt_dso_flag, []() { \ + tensorrt_dso_handle = phi::dynload::GetTensorRtHandle(); \ + }); \ + static void* p_##__name = dlsym(tensorrt_dso_handle, #__name); \ + PADDLE_ENFORCE_NOT_NULL( \ + p_##__name, \ + phi::errors::Unavailable("Load tensorrt api %s failed", #__name)); \ + using tensorrt_func = decltype(&::__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define DECLARE_DYNAMIC_LOAD_TENSORRT_PLUGIN_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + std::call_once(tensorrt_plugin_dso_flag, []() { \ + tensorrt_plugin_dso_handle = phi::dynload::GetTensorRtPluginHandle(); \ + }); \ + static void* p_##__name = dlsym(tensorrt_plugin_dso_handle, #__name); \ + PADDLE_ENFORCE_NOT_NULL(p_##__name, \ + phi::errors::Unavailable( \ + "Load tensorrt plugin %s failed", #__name)); \ + using tensorrt_plugin_func = decltype(&::__name); \ + return reinterpret_cast(p_##__name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#ifdef NV_TENSORRT_MAJOR + +#if (NV_TENSORRT_MAJOR >= 6) +#define TENSORRT_RAND_ROUTINE_EACH_POINTER(__macro) \ + __macro(createInferBuilder_INTERNAL); \ + __macro(createInferRuntime_INTERNAL); \ + __macro(getPluginRegistry); +#else +#define TENSORRT_RAND_ROUTINE_EACH_POINTER(__macro) \ + __macro(createInferBuilder_INTERNAL); \ + __macro(createInferRuntime_INTERNAL); +#endif + +#define TENSORRT_RAND_ROUTINE_EACH_NON_POINTER(__macro) \ + __macro(getInferLibVersion); + +#define TENSORRT_PLUGIN_RAND_ROUTINE_EACH(__macro) \ + __macro(initLibNvInferPlugins); + +TENSORRT_RAND_ROUTINE_EACH_POINTER(DECLARE_DYNAMIC_LOAD_TENSORRT_POINTER_WRAP) +TENSORRT_RAND_ROUTINE_EACH_NON_POINTER( + DECLARE_DYNAMIC_LOAD_TENSORRT_NON_POINTER_WRAP) +TENSORRT_PLUGIN_RAND_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_TENSORRT_PLUGIN_WRAP) + +#endif // end of NV_TENSORRT_MAJOR + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/warpctc.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/warpctc.h new file mode 100644 index 0000000000000000000000000000000000000000..cc823f72cfbc922b99040dc5c6bc6e611369fde6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/dynload/warpctc.h @@ -0,0 +1,64 @@ +/* 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. */ + +#pragma once + +#include // NOLINT + +#include "paddle/phi/backends/dynload/dynamic_loader.h" +#include "paddle/phi/backends/dynload/port.h" +#include "warpctc/include/ctc.h" + +namespace phi { +namespace dynload { + +extern std::once_flag warpctc_dso_flag; +extern void* warpctc_dso_handle; + +/** + * The following macro definition can generate structs + * (for each function) to dynamic load warpctc routine + * via operator overloading. + */ +#define DYNAMIC_LOAD_WARPCTC_WRAP(__name) \ + struct DynLoad__##__name { \ + template \ + auto operator()(Args... args) -> DECLARE_TYPE(__name, args...) { \ + using warpctcFunc = decltype(&::__name); \ + std::call_once(warpctc_dso_flag, []() { \ + warpctc_dso_handle = phi::dynload::GetWarpCTCDsoHandle(); \ + }); \ + static void* p_##_name = dlsym(warpctc_dso_handle, #__name); \ + return reinterpret_cast(p_##_name)(args...); \ + } \ + }; \ + extern DynLoad__##__name __name + +#define DECLARE_DYNAMIC_LOAD_WARPCTC_WRAP(__name) \ + DYNAMIC_LOAD_WARPCTC_WRAP(__name) + +#define WARPCTC_ROUTINE_EACH(__macro) \ + __macro(get_warpctc_version); \ + __macro(ctcGetStatusString); \ + __macro(compute_ctc_loss); \ + __macro(compute_ctc_loss_double); \ + __macro(get_workspace_size); \ + __macro(get_workspace_size_double) + +WARPCTC_ROUTINE_EACH(DECLARE_DYNAMIC_LOAD_WARPCTC_WRAP); + +#undef DYNAMIC_LOAD_WARPCTC_WRAP + +} // namespace dynload +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/event.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/event.h new file mode 100644 index 0000000000000000000000000000000000000000..8de223528f8fdffe16809c8744a56ff1cc71824d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/event.h @@ -0,0 +1,61 @@ +// Copyright (c) 2022 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. + +#pragma once +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/macros.h" + +namespace phi { + +class Device; + +namespace stream { +class Stream; +} // namespace stream + +namespace event { +using event_t = void*; + +class Event { + public: + enum Flag { + Default = 0x0, + BlockingSync = 0x1, + DisableTiming = 0x2, + Interprocess = 0x4, + }; + + Event() = default; + // For compatible + Event(const Place& place, event_t event); + ~Event(); + event_t raw_event() const; + void set_event(event_t event); + bool Init(const Place& place, Flag flags = Flag::Default); + void Destroy(); + void Record(const stream::Stream* stream); + bool Query() const; + void Synchonrize() const; + const Place& GetPlace() const; + + private: + DISABLE_COPY_AND_ASSIGN(Event); + Place place_; + Device* device_; + event_t event_; + bool own_data_ = true; +}; +} // namespace event + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/cuda/cuda_helper.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/cuda/cuda_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..7463edc5d9ff60dbe9f8a255458af122dec75f33 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/cuda/cuda_helper.h @@ -0,0 +1,74 @@ +// 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. + +#pragma once + +namespace phi { +namespace backends { +namespace gpu { + +/* + * Summary: Grid stride looping macro in CUDA kernel + * + * [ Why need this macro? ] + * + * The original looping in CUDA kernel is: + * + * `for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < (n); \ + * i += blockDim.x * gridDim.x)` + * + * This for condition is risky. The value of `blockIdx.x * blockDim.x` + * may be large, such as over 1GB, the first iteration is no problem here, + * but when `i += blockDim.x * gridDim.x` is executed, the value of i + * will greater than INT_MAX and overflow becomes negative value, at + * this time, the cycle condition `i < (n)` is still satisfied, so it + * will cause illegal access to cuda memory. + * + * Here is a real example in ERINE, it will trigger above error. + * The related data are: + * - blockIdx.x = 2172938 + * - blockDim.x = 512 + * - blockIdx.x * blockDim.x = 1112543864 + * - INT_MAX = 2147483647 + * + * So we polish the for condition as follow, the int64_t __index__ will + * prevent overflow in the loop increment. + * + * Parameters: + * - i: loop index + * - num: total element numbers + * + * Examples: + * template + * __global__ void Scale(T* logit_grad, const T* loss_grad, const int num, + * const int d, const int remain) { + * CUDA_KERNEL_LOOP(index, num) { + * int idx_n = index / d; + * int idx_remain = index % remain; + * logit_grad[index] *= loss_grad[idx_n * remain + idx_remain]; + * } + * } + * + */ + +#define CUDA_KERNEL_LOOP_TYPE(i, num, index_type) \ + int64_t __index__ = \ + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; \ + int64_t __stride__ = static_cast(blockDim.x) * gridDim.x; \ + for (index_type i = __index__; __index__ < (num); \ + __index__ += __stride__, i = __index__) + +} // namespace gpu +} // namespace backends +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/forwards.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/forwards.h new file mode 100644 index 0000000000000000000000000000000000000000..e1f3492f7687029858ccfcebe90b704b830cd89a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/forwards.h @@ -0,0 +1,113 @@ +/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +Copyright (c) 2022 NVIDIA Corporation. 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. */ + +// Forward-declares CUDA API types used in platform-agnostic wrapper headers. +#pragma once + +/// Forward declaration of Eigen types. +namespace Eigen { +struct GpuDevice; +} // namespace Eigen + +/// Forward declaration of CUDA types. + +// Forward declaration of CUDA runtime types. +using cudaStream_t = struct CUstream_st *; +using cudaEvent_t = struct CUevent_st *; + +// Forward declaration of cuDNN types. +using cudnnHandle_t = struct cudnnContext *; +using cudnnTensorDescriptor_t = struct cudnnTensorStruct *; +using cudnnConvolutionDescriptor_t = struct cudnnConvolutionStruct *; +using cudnnPoolingDescriptor_t = struct cudnnPoolingStruct *; +using cudnnFilterDescriptor_t = struct cudnnFilterStruct *; +using cudnnLRNDescriptor_t = struct cudnnLRNStruct *; +using cudnnActivationDescriptor_t = struct cudnnActivationStruct *; +using cudnnSpatialTransformerDescriptor_t = + struct cudnnSpatialTransformerStruct *; +using cudnnOpTensorDescriptor_t = struct cudnnOpTensorStruct *; +using cudnnReduceTensorDescriptor_t = struct cudnnReduceTensorStruct *; +using cudnnCTCLossDescriptor_t = struct cudnnCTCLossStruct *; +using cudnnTensorTransformDescriptor_t = struct cudnnTensorTransformStruct *; +using cudnnDropoutDescriptor_t = struct cudnnDropoutStruct *; +using cudnnRNNDescriptor_t = struct cudnnRNNStruct *; +using cudnnPersistentRNNPlan_t = struct cudnnPersistentRNNPlan *; +using cudnnRNNDataDescriptor_t = struct cudnnRNNDataStruct *; +using cudnnAlgorithmDescriptor_t = struct cudnnAlgorithmStruct *; +using cudnnAlgorithmPerformance_t = struct cudnnAlgorithmPerformanceStruct *; +using cudnnSeqDataDescriptor_t = struct cudnnSeqDataStruct *; +using cudnnAttnDescriptor_t = struct cudnnAttnStruct *; +using cudnnFusedOpsConstParamPack_t = struct cudnnFusedOpsConstParamStruct *; +using cudnnFusedOpsVariantParamPack_t = + struct cudnnFusedOpsVariantParamStruct *; +using cudnnFusedOpsPlan_t = struct cudnnFusedOpsPlanStruct *; + +// Forward declaration of cuBLAS types. +using cublasHandle_t = struct cublasContext *; + +// Forward declaration of cuBLASLt types. +using cublasLtHandle_t = struct cublasLtContext *; + +// Forward declaration of cuSOLVER types. +using cusolverDnHandle_t = struct cusolverDnContext *; + +// Forward declaration of cuSparse types. +using cusparseHandle_t = struct cusparseContext *; + +// Forward declaration of cuFFT types. +using cufftHandle = int; + +// Forward declaration of NCCL types. +using ncclComm_t = struct ncclComm *; + +/// Forward declaration of ROCM types. +#include + +using hipDevice_t = int; +using hipCtx_t = struct ihipCtx_t *; +using hipStream_t = struct ihipStream_t *; +using hipEvent_t = struct ihipEvent_t *; + +// Forward declaration of MIOpen types. +using miopenHandle_t = struct miopenHandle *; +using miopenAcceleratorQueue_t = hipStream_t; +using miopenFusionOpDescriptor_t = struct miopenFusionOpDescriptor *; +using miopenTensorDescriptor_t = struct miopenTensorDescriptor *; +using miopenConvolutionDescriptor_t = struct miopenConvolutionDescriptor *; +using miopenPoolingDescriptor_t = struct miopenPoolingDescriptor *; +using miopenLRNDescriptor_t = struct miopenLRNDescriptor *; +using miopenActivationDescriptor_t = struct miopenActivationDescriptor *; +using miopenRNNDescriptor_t = struct miopenRNNDescriptor *; +using miopenCTCLossDescriptor_t = struct miopenCTCLossDescriptor *; +using miopenDropoutDescriptor_t = struct miopenDropoutDescriptor *; +using miopenFusionPlanDescriptor_t = struct miopenFusionPlanDescriptor *; +using miopenOperatorDescriptor_t = struct miopenOperatorDescriptor *; +using miopenOperatorArgs_t = struct miopenOperatorArgs *; +using miopenAllocatorFunction = void *(*)(void *context, size_t sizeBytes); +// using miopenDeallocatorFunction = void *(*)(void *context, void *memory); +// struct miopenConvAlgoPerf_t; +// struct miopenConvSolution_t; + +// Forward declaration of rocBLAS types. +using rocblas_handle = struct _rocblas_handle *; + +// Forward declaration of hipfft types. +using hipfftHandle = struct hipfftHandle_t *; + +// Forward declaration of rocSOLVER types. +using rocsolver_handle = rocblas_handle; + +// Forward declaration of rocSparse types. +using rocsparse_handle = struct _rocsparse_handle *; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_context.h new file mode 100644 index 0000000000000000000000000000000000000000..989bbbcbbf5f8c63ebb9b2e815ca2346189275c0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_context.h @@ -0,0 +1,268 @@ +/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +Copyright (c) 2022 NVIDIA Corporation. 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. */ + +#pragma once + +#include +#include +#include + +#include "paddle/phi/backends/gpu/forwards.h" +#include "paddle/phi/backends/gpu/gpu_decls.h" +#include "paddle/phi/backends/gpu/gpu_helper.h" +#include "paddle/phi/backends/gpu/gpu_info.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +class CUDAStream; + +class DnnWorkspaceHandle { + public: + inline DnnWorkspaceHandle(Allocator* allocator, gpuStream_t stream) + : allocator_(allocator), stream_(stream) { + mtx_.reset(new std::mutex()); + } + + inline void RunFunc(const std::function& cudnn_func, + size_t required_workspace_bytes) { + if (required_workspace_bytes > WorkspaceSize()) { + ReallocWorkspace(required_workspace_bytes); + } + { + std::lock_guard guard(*mtx_); + cudnn_func(allocation_ ? allocation_->ptr() : nullptr); + } + } + + /*! \brief Thread which call RunFuncSync() would release gpu memory after + * running the function. Currently this function is only used when cudnn + * exhaustive searching and callers have to guarantee that the input function + * is host blocking */ + void RunFuncSync(const std::function& cudnn_func, + size_t required_workspace_bytes, + bool use_cached_allocation = true); + + inline size_t WorkspaceSize() { + if (allocation_ == nullptr) { + return 0; + } + return allocation_->size(); + } + + void ResetWorkspace(); + + void ReallocWorkspace(size_t required_workspace_bytes); + + DnnWorkspaceHandle(DnnWorkspaceHandle&&) = default; + DnnWorkspaceHandle& operator=(DnnWorkspaceHandle&&) = delete; + + private: + Allocator::AllocationPtr allocation_{nullptr}; + Allocator* allocator_{nullptr}; // Not owned + gpuStream_t stream_{nullptr}; // Not owned + std::unique_ptr mtx_; +}; + +class PADDLE_API GPUContext : public DeviceContext { + public: + explicit GPUContext(const GPUPlace& place, bool init = true); + + GPUContext(GPUContext&&); + GPUContext& operator=(GPUContext&&); + + virtual ~GPUContext(); + + /*! \brief Return place in the device context. */ + const Place& GetPlace() const override; + + /*! \brief Return gpu stream in the device context. */ + gpuStream_t stream() const; + + /*! \brief Return CUDAStream in the device context. */ + CUDAStream* cuda_stream() const; + + /*! \brief Return cudnn handle in the device context. */ + dnnHandle_t cudnn_handle() const; + + /*! \brief Return cublas handle in the device context. */ + blasHandle_t cublas_handle() const; + + /*! \brief Return cublasLt handle in the device context. */ + blasLtHandle_t cublaslt_handle() const; + + /*! \brief Return cusolver handle in the device context. */ + solverHandle_t cusolver_dn_handle() const; + + /*! \brief Return cusparse handle in the device context. */ + sparseHandle_t cusparse_handle() const; + + /*! \brief Wait for all operations completion in the stream. */ + void Wait() const override; + + /*! \brief Wait for event in the stream. */ + void WaitEvent(gpuEvent_t ev) const; + + /*! \brief Check whether tensor core is supported */ + bool tensor_core_available() const; + + /*! \brief Return compute capability in the device context. */ + int GetComputeCapability() const; + + /*! \brief Return the max physical thread count in the device context */ + int GetMaxPhysicalThreadCount() const; + + /*! \brief Return the SM count in the device context */ + int GetSMCount() const; + + /*! \brief Return the Max thread num of block in the device context */ + int GetMaxThreadsPerBlock() const; + + /*! \brief Return the max grid dim size in the device context */ + std::array GetCUDAMaxGridDimSize() const; + + /*! \brief Return eigen device in the device context. */ + Eigen::GpuDevice* eigen_device() const; + + /*! \brief Return a cudnn workspace handle to call multiple cudnn + * functions without interrupting by other threads. + * Once the first cudnn function is called by the handle, a lock + * would be acquired to prevent other threads from accessing the + * workspace. Once the handle is destructed, the lock would be released. + */ + // TODO(wilber): The return type is a pointer, to be modified later. + DnnWorkspaceHandle cudnn_workspace_handle() const; + + public: + /*! \brief Call cublas function safely. */ + void CublasCall(const std::function&) const; + + /*! \brief Call cublas function with Tensor Core safely. If + Tensor Core is not available, use DEFAULT_MATH instead. */ + void TensorCoreCublasCallIfAvailable( + const std::function&) const; + + /*! \brief Call cusparse function safely. */ + void CusparseCall(const std::function&) const; + + void RecordEvent(gpuEvent_t ev, const std::function& callback) const; + + void RecordEvent(gpuEvent_t ev) const; + + void AddStreamCallback(const std::function& callback) const; + + void WaitStreamCallback() const; + + public: + /*! \brief Return nccl communicators. */ + ncclComm_t nccl_comm() const; + + /*! \brief Set nccl communicators. */ + void set_nccl_comm(ncclComm_t comm); + + public: + // NOTE: DeviceContext hold resources. Used in training scenarios. + // The interface used by the training scene, DeviceContext will initialize + // all resources and delete them when destructing. + // Note that you must set the Allocator before calling Init function. + void Init(); + + // TODO(wilber): Why does the GetAllocator interface require a stream + // parameter? + // The temporary trick method bypasses this problem, and the following + // interfaces + // need to be deleted later. + + // Note that this is a trick implementation, which can be used to partially + // initialize when the SetAllocator interface is not called. + void PartialInitWithoutAllocator(); + // Note that this is a trick implementation that can be used to initialize + // resources that require an Allocator when the SetAllocator interface is + // called. + void PartialInitWithAllocator(); + + // Note that this function is a trick implementation since all 'set' methods + // are protected by default. + // clear: whether clear the original CUDAStream or not + void SetCUDAStream(CUDAStream*, bool clear = true); + + protected: + // NOTE: External users manage resources. Used in inference scenarios. + // The Set interface is for inference only, DeviceContext will mark the + // resource as external, and will not delete any resource when destructing. + void SetStream(gpuStream_t); + + void SetEigenDevice(Eigen::GpuDevice*); + void SetEigenDevice(std::function&&); + + void SetBlasHandle(blasHandle_t); + void SetBlasHandle(std::function&&); + + void SetBlasTensorCoreHandle(blasHandle_t); + void SetBlasTensorCoreHandle(std::function&&); + + void SetBlasTF32Handle(blasHandle_t); + void SetBlasTF32Handle(std::function&&); + + void SetBlasLtHandle(blasLtHandle_t); + void SetBlasLtHandle(std::function&&); + + void SetDnnHandle(dnnHandle_t); + void SetDnnHandle(std::function&&); + + void SetSolverHandle(solverHandle_t); + void SetSolverHandle(std::function&&); + + void SetSparseHandle(sparseHandle_t); + void SetSparseHandle(std::function&&); + + void SetDnnWorkspaceHandle(DnnWorkspaceHandle*); + + void SetComputeCapability(int val); + + void SetMaxThreadsPerMultiProcessor(int val); + + void SetMultiProcessors(int val); + + void SetMaxThreadsPerBlock(int val); + + void SetMaxGridDimSize(const std::array& val); + + void SetDriverVersion(int val); + + void SetRuntimeVersion(int val); + + private: + struct Impl; + std::unique_ptr impl_; +}; + +// Note: In order to register the kernel of CUDNN, GPUDNNContext is required. +// Currently, CUDNN kernel directly uses GPUContext. But if the kernel function +// has the same name, this will lead to duplicate instantiations of GPU kernel +// and GPUDNN kernel function, so if we using GPUDNNContext = GPUContext, we +// must use different function name for cudnn kernel +using GPUDNNContext = GPUContext; + +// KPS (Kernel PrimitiveS API) needs to exist as a kind of backend, +// because we want to implement a KPS-based kernel and make it run +// on GPU and XPU at the same time, so we need KPSContext when registering +// KPS Kernel. Note: XPU and GPU cannot be compiled at the same time! +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) +using KPSContext = GPUContext; +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_decls.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_decls.h new file mode 100644 index 0000000000000000000000000000000000000000..4a6b9d2fd87f13e4b63d3da8e7e98f77d18c69a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_decls.h @@ -0,0 +1,75 @@ +// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. +// Copyright (c) 2022 NVIDIA Corporation. 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. + +#pragma once + +#include "paddle/phi/backends/gpu/forwards.h" + +namespace phi { + +#ifdef PADDLE_WITH_HIP +#define DECLARE_TYPE_FOR_GPU(GPU_TYPE, CUDA_TYPE, ROCM_TYPE) \ + using GPU_TYPE = ROCM_TYPE; + +#else // PADDLE_WITH_CDUA + +#define DECLARE_TYPE_FOR_GPU(GPU_TYPE, CUDA_TYPE, ROCM_TYPE) \ + using GPU_TYPE = CUDA_TYPE; +#endif + +DECLARE_TYPE_FOR_GPU(gpuStream_t, cudaStream_t, hipStream_t); +DECLARE_TYPE_FOR_GPU(gpuEvent_t, cudaEvent_t, hipEvent_t); + +DECLARE_TYPE_FOR_GPU(dnnActivationDescriptor, + cudnnActivationStruct, + miopenActivationDescriptor); +DECLARE_TYPE_FOR_GPU(dnnTensorDescriptor, + cudnnTensorStruct, + miopenTensorDescriptor); +DECLARE_TYPE_FOR_GPU(dnnFilterDescriptor, + cudnnFilterStruct, + miopenTensorDescriptor); +DECLARE_TYPE_FOR_GPU(dnnFilterDescriptor_t, + cudnnFilterDescriptor_t, + miopenTensorDescriptor_t); +DECLARE_TYPE_FOR_GPU(dnnConvolutionDescriptor, + cudnnConvolutionStruct, + miopenConvolutionDescriptor); +DECLARE_TYPE_FOR_GPU(dnnConvolutionDescriptor_t, + cudnnConvolutionDescriptor_t, + miopenConvolutionDescriptor_t); +DECLARE_TYPE_FOR_GPU(dnnPoolingDescriptor_t, + cudnnPoolingDescriptor_t, + miopenPoolingDescriptor_t); +DECLARE_TYPE_FOR_GPU(dnnDropoutDescriptor_t, + cudnnDropoutDescriptor_t, + miopenDropoutDescriptor_t); +DECLARE_TYPE_FOR_GPU(dnnHandle_t, cudnnHandle_t, miopenHandle_t); + +DECLARE_TYPE_FOR_GPU(blasHandle_t, cublasHandle_t, rocblas_handle); + +// TODO(Ming Huang): Since there is no blasLt handler, +// use rocblas_handle for workround. +DECLARE_TYPE_FOR_GPU(blasLtHandle_t, cublasLtHandle_t, rocblas_handle); + +DECLARE_TYPE_FOR_GPU(solverHandle_t, cusolverDnHandle_t, rocsolver_handle); + +DECLARE_TYPE_FOR_GPU(sparseHandle_t, cusparseHandle_t, rocsparse_handle); + +#undef DECLARE_TYPE_FOR_GPU + +using CUDAGraphID = unsigned long long; // NOLINT + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_helper.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..2353b42794ffdd8d37bfc54b2fa07e41533f75fa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_helper.h @@ -0,0 +1,26 @@ +// Copyright (c) 2021 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. + +#pragma once +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + +#ifdef PADDLE_WITH_HIP +#include "paddle/phi/backends/gpu/rocm/rocm_helper.h" +#else +#include "paddle/phi/backends/gpu/cuda/cuda_helper.h" +#endif + +#define CUDA_KERNEL_LOOP(i, num) CUDA_KERNEL_LOOP_TYPE(i, num, int) + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_info.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_info.h new file mode 100644 index 0000000000000000000000000000000000000000..323565c000a1c38cc0cefa2746845a7b276972e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_info.h @@ -0,0 +1,137 @@ +/* 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. */ + +#pragma once + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + +#include + +#include +#include +#include + +#include "paddle/phi/backends/gpu/gpu_types.h" + +namespace phi { +namespace backends { +namespace gpu { + +//! Get the version of dnn +int DnnVersion(); + +//! Get the total number of GPU devices in system. +int GetGPUDeviceCount(); + +//! Get the compute capability of the ith GPU (format: major * 10 + minor) +int GetGPUComputeCapability(int id); + +//! Get the runtime version of the ith GPU +int GetGPURuntimeVersion(int id); + +//! Get the driver version of the ith GPU +int GetGPUDriverVersion(int id); + +//! Wheter the current device support TensorCore +bool TensorCoreAvailable(); + +//! Get the MultiProcessors of the ith GPU. +int GetGPUMultiProcessors(int id); + +//! Get the MaxThreads of each MultiProcessor of the ith GPU. +int GetGPUMaxThreadsPerMultiProcessor(int id); + +//! Get the MaxThreads of each block of the ith GPU. +int GetGPUMaxThreadsPerBlock(int id); + +//! Get the current GPU device id in system. +int GetCurrentDeviceId(); + +//! Get the maximum GridDim size for GPU buddy allocator. +std::array GetGpuMaxGridDimSize(int); + +//! Get a list of device ids from environment variable or use all. +std::vector GetSelectedDevices(); + +//! Get the properties of the ith GPU device. +const gpuDeviceProp &GetDeviceProperties(int id); + +//! Set the GPU device id for next execution. +void SetDeviceId(int device_id); + +//! Copy memory from address src to dst asynchronously. +void GpuMemcpyAsync(void *dst, + const void *src, + size_t count, + gpuMemcpyKind kind, + gpuStream_t stream); + +//! Copy memory from address src to dst synchronously. +void GpuMemcpySync(void *dst, + const void *src, + size_t count, + gpuMemcpyKind kind); + +//! Copy memory from one device to another device asynchronously. +void GpuMemcpyPeerAsync(void *dst, + int dst_device, + const void *src, + int src_device, + size_t count, + gpuStream_t stream); + +//! Copy memory from one device to another device synchronously. +void GpuMemcpyPeerSync( + void *dst, int dst_device, const void *src, int src_device, size_t count); + +//! Set memory dst with value count size asynchronously +void GpuMemsetAsync(void *dst, int value, size_t count, gpuStream_t stream); + +//! Blocks until stream has completed all operations. +void GpuStreamSync(gpuStream_t stream); + +void GpuDestroyStream(gpuStream_t stream); + +// ! Blocks until device has completed all operations. +void GpuDeviceSync(); + +gpuError_t GpuGetLastError(); + +bool IsGPUManagedMemorySupported(int dev_id); + +bool IsGPUManagedMemoryOversubscriptionSupported(int dev_id); + +class GPUDeviceGuard { + public: + explicit inline GPUDeviceGuard(int dev_id) { + int prev_id = GetCurrentDeviceId(); + if (prev_id != dev_id) { + prev_id_ = prev_id; + SetDeviceId(dev_id); + } + } + inline ~GPUDeviceGuard() { + if (prev_id_ != -1) { + SetDeviceId(prev_id_); + } + } + GPUDeviceGuard(const GPUDeviceGuard &o) = delete; + GPUDeviceGuard &operator=(const GPUDeviceGuard &o) = delete; + + private: + int prev_id_{-1}; +}; + +} // namespace gpu +} // namespace backends +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_launch_config.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_launch_config.h new file mode 100644 index 0000000000000000000000000000000000000000..f0a37d4fb7be6c40e1ef01ecaed44c000f94469e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_launch_config.h @@ -0,0 +1,245 @@ +// 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. + +// Used for compute gpu launch parameter config + +#pragma once + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + +#ifdef PADDLE_WITH_CUDA +#include +#else +#include +#endif + +#include + +#include +#include +#include + +#include "glog/logging.h" +#include "paddle/phi/backends/gpu/gpu_context.h" +#include "paddle/phi/core/enforce.h" + +#ifdef __HIPCC__ +// HIP results in error or nan if > 256 +#define PREDEFINED_BLOCK_SIZE 256 +#else +// CUDA performs better when thread_per_block is between [64, 512] +#define PREDEFINED_BLOCK_SIZE 512 +#endif + +namespace phi { +namespace backends { +namespace gpu { + +template +inline T DivUp(T a, T b) { + return (a + b - 1) / b; +} + +// https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 +// for round integer value into next highest power of 2. +inline int64_t RoundToPowerOfTwo(int64_t n) { + n--; + n |= (n >> 1); + n |= (n >> 2); + n |= (n >> 4); + n |= (n >> 8); + n |= (n >> 16); + int64_t min_val = 32; +#ifdef __HIPCC__ + int64_t max_val = 256; +#else + int64_t max_val = 1024; +#endif + return std::min(max_val, std::max(min_val, (n + 1))); +} + +#ifdef WITH_NV_JETSON +// The number of threads cannot be assigned 1024 in some cases when the device +// is nano or tx2 . +inline void ChangeThreadNum(const phi::GPUContext& context, + int* num_thread, + int alternative_num_thread = 512) { + if (context.GetComputeCapability() == 53 || + context.GetComputeCapability() == 62) { + *num_thread = alternative_num_thread; + } +} +#endif + +struct GpuLaunchConfig { + public: + GpuLaunchConfig() {} + + size_t GetThreadNum() const { return GetBlockSize() * GetGridSize(); } + + size_t GetGridSize() const { + return block_per_grid.x * block_per_grid.y * block_per_grid.z; + } + + size_t GetBlockSize() const { + return thread_per_block.x * thread_per_block.y * thread_per_block.z; + } + + int compute_capability = 0; + dim3 thread_per_block = dim3(1, 1, 1); + dim3 block_per_grid = dim3(1, 1, 1); +}; + +/* According to NVIDIA, if number of threads per block is 64/128/256/512, + * cuda performs better. And number of blocks should be greater (at least + * 2x~4x) than number of SMs. Hence, SM count is took into account within + * this function to determine the right number of threads per block. */ +inline GpuLaunchConfig GetGpuLaunchConfig1D(const phi::GPUContext& context, + int64_t numel, + int vec_size = 1) { + PADDLE_ENFORCE_GE(numel, + 0, + phi::errors::InvalidArgument( + "numel is expected to be greater than or equal 0," + " but received %d.", + numel)); + PADDLE_ENFORCE_GE( + vec_size, + 1, + phi::errors::InvalidArgument( + "vec_size is expected greater than 0, but received %d.", vec_size)); + // Get compute_capability + const int capability = context.GetComputeCapability(); + // If thread number per block is 64/128/256/512, cuda performs better. + int limit_threads = + std::min(PREDEFINED_BLOCK_SIZE, context.GetMaxThreadsPerBlock()); +#ifdef WITH_NV_JETSON + if (capability == 53 || capability == 62) { + limit_threads = 512; + } +#endif + int threads = limit_threads; + int sm_count = context.GetSMCount(); + int64_t active_threads_num = numel / vec_size; + if (active_threads_num / (sm_count << 1) < limit_threads) { + // Round up threads number into an exponential multiple of 2, while number + // of acitve blocks is about twice of SM, to acquire better performance. + threads = RoundToPowerOfTwo(active_threads_num / (sm_count << 1)); + } else if (active_threads_num / (sm_count << 2) < limit_threads) { + // Round up threads number into an exponential multiple of 2, while number + // of acitve blocks is about 4 times of SM, to acquire better performance. + threads = RoundToPowerOfTwo(active_threads_num / (sm_count << 2)); + } + // Number of threads per block shall be larger than 64. + threads = std::max(64, threads); + int blocks = DivUp(DivUp(numel, vec_size), threads); + int limit_blocks = context.GetCUDAMaxGridDimSize()[0]; + if (blocks > limit_blocks) { + blocks = limit_blocks; + } + + GpuLaunchConfig config; + config.thread_per_block.x = threads; + config.block_per_grid.x = blocks; + config.compute_capability = capability; + + VLOG(3) << "Get 1-D launch config: numel=" << numel + << ", vec_size=" << vec_size << ", block_size=" << threads + << ", grid_size=" << blocks << ", limit_blocks=" << limit_blocks + << ", limit_threads=" << limit_threads; + return config; +} + +inline GpuLaunchConfig GetGpuLaunchConfig2D(const phi::GPUContext& context, + int64_t x_dim, + int64_t y_dim) { + PADDLE_ENFORCE_GT( + x_dim, + 0, + phi::errors::InvalidArgument("x dim number should greater than 0," + " but received value is: %d", + x_dim)); + PADDLE_ENFORCE_GT( + y_dim, + 0, + phi::errors::InvalidArgument("y dim number should greater than 0," + " but received value is: %d", + y_dim)); + + const int kThreadsPerBlock = 256; + int block_cols = std::min(x_dim, kThreadsPerBlock); + int block_rows = std::max(kThreadsPerBlock / block_cols, 1); + + int max_physical_threads = context.GetMaxPhysicalThreadCount(); + const int max_blocks = std::max(max_physical_threads / kThreadsPerBlock, 1); + + GpuLaunchConfig config; + // Noticed, block size is not align to 32, if needed do it yourself. + config.thread_per_block = dim3(block_cols, block_rows, 1); + + int grid_x = std::min(DivUp(x_dim, block_cols), max_blocks); + int grid_y = std::min(max_blocks / grid_x, + std::max(y_dim / block_rows, 1)); + + config.block_per_grid = dim3(grid_x, grid_y, 1); + return config; +} + +static inline int GetLastPow2(int n) { + n |= (n >> 1); + n |= (n >> 2); + n |= (n >> 4); + n |= (n >> 8); + n |= (n >> 16); + return std::max(1, n - (n >> 1)); +} + +inline GpuLaunchConfig GetGpuLaunchConfig3D(const phi::GPUContext& context, + int num_img, + int height, + int width) { + const int kThreadsPerBlock = 256; + int max_threads_per_block = context.GetMaxThreadsPerBlock(); // 1024 + int max_threads = std::min(kThreadsPerBlock, max_threads_per_block); + + int block_x = std::min(GetLastPow2(width), max_threads); + int block_y = std::min(GetLastPow2(height), max_threads / block_x); + int block_z = std::min(num_img, max_threads / block_x / block_y); + + std::array max_grid_dim = context.GetCUDAMaxGridDimSize(); + int grid_x = std::min(max_grid_dim[0], DivUp(width, block_x)); + int grid_y = std::min(max_grid_dim[1], DivUp(height, block_y)); + int grid_z = std::min(max_grid_dim[2], DivUp(num_img, block_z * 4)); + + const int capability = context.GetComputeCapability(); + GpuLaunchConfig config; + config.compute_capability = capability; + config.thread_per_block = dim3(block_x, block_y, block_z); + config.block_per_grid = dim3(grid_x, grid_y, grid_z); + return config; +} + +template +void LimitGridDim(const Context& ctx, dim3* grid_dim) { + auto max_grid_dim = + reinterpret_cast(ctx).GetCUDAMaxGridDimSize(); + grid_dim->x = grid_dim->x < max_grid_dim[0] ? grid_dim->x : max_grid_dim[0]; + grid_dim->y = grid_dim->y < max_grid_dim[1] ? grid_dim->y : max_grid_dim[1]; + grid_dim->z = grid_dim->z < max_grid_dim[2] ? grid_dim->z : max_grid_dim[2]; +} +} // namespace gpu +} // namespace backends +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_resources.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_resources.h new file mode 100644 index 0000000000000000000000000000000000000000..7bec5eebf5886f4caefed1a21acc2f6435b3968d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_resources.h @@ -0,0 +1,52 @@ +// Copyright (c) 2022 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. +#pragma once + +#include + +#include "paddle/phi/backends/gpu/gpu_decls.h" +#include "paddle/phi/common/place.h" + +namespace phi { + +void InitGpuProperties(Place place, + int* compute_capability, + int* runtime_version, + int* driver_version, + int* multi_process, + int* max_threads_per_mp, + int* max_threads_per_block, + std::array* max_grid_dim_size); + +void InitStream(gpuStream_t* stream); +void DestoryStream(gpuStream_t stream); + +void InitBlasHandle(blasHandle_t* blas_handle, gpuStream_t stream); +void DestroyBlasHandle(blasHandle_t handle); + +void InitBlasLtHandle(blasLtHandle_t* blaslt_handle); +void DestroyBlasLtHandle(blasLtHandle_t handle); + +void InitDnnHandle(dnnHandle_t* handle, gpuStream_t stream, Place place); +void DestroyDnnHandle(dnnHandle_t handle); + +void InitSolverHandle(solverHandle_t* handle, gpuStream_t stream); +void DestroySolverHandle(solverHandle_t solver_handle); + +void InitSparseHandle(sparseHandle_t* handle, gpuStream_t stream); +void DestroySparseHandle(sparseHandle_t handle); + +// void InitDnnWorkspace(); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_types.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_types.h new file mode 100644 index 0000000000000000000000000000000000000000..77f403795b6b3df48f0de894f311a14a3bdb9f0a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/gpu_types.h @@ -0,0 +1,83 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/backends/gpu/forwards.h" +#include "paddle/phi/backends/gpu/gpu_decls.h" + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + +#ifdef PADDLE_WITH_HIP +#include "paddle/phi/backends/dynload/miopen.h" +#include "paddle/phi/backends/dynload/rocblas.h" +#else // PADDLE_WITH_CUDA +#include "paddle/phi/backends/dynload/cublas.h" +#include "paddle/phi/backends/dynload/cudnn.h" +#endif + +namespace phi { + +#ifdef PADDLE_WITH_HIP +#define DECLARE_TYPE_FOR_GPU(GPU_TYPE, CUDA_TYPE, ROCM_TYPE) \ + using GPU_TYPE = ROCM_TYPE; + +#else // PADDLE_WITH_CDUA + +#define DECLARE_TYPE_FOR_GPU(GPU_TYPE, CUDA_TYPE, ROCM_TYPE) \ + using GPU_TYPE = CUDA_TYPE; +#endif + +DECLARE_TYPE_FOR_GPU(gpuError_t, cudaError_t, hipError_t); +DECLARE_TYPE_FOR_GPU(gpuMemcpyKind, cudaMemcpyKind, hipMemcpyKind); +DECLARE_TYPE_FOR_GPU(gpuDeviceProp, cudaDeviceProp, hipDeviceProp_t); +DECLARE_TYPE_FOR_GPU(dnnDataType_t, cudnnDataType_t, miopenDataType_t); +DECLARE_TYPE_FOR_GPU(dnnPoolingMode_t, cudnnPoolingMode_t, miopenPoolingMode_t); +DECLARE_TYPE_FOR_GPU(dnnTensorFormat_t, + cudnnTensorFormat_t, + miopenTensorFormat_t); +DECLARE_TYPE_FOR_GPU(dnnActivationMode_t, + cudnnActivationMode_t, + miopenActivationMode_t); + +#undef DECLARE_TYPE_FOR_GPU + +#ifdef PADDLE_WITH_HIP +#define DECLARE_CONSTANT_FOR_GPU(GPU_CV, CUDA_CV, ROCM_CV) \ + constexpr auto GPU_CV = ROCM_CV; +#else // PADDLE_WITH_CUDA +#define DECLARE_CONSTANT_FOR_GPU(GPU_CV, CUDA_CV, ROCM_CV) \ + constexpr auto GPU_CV = CUDA_CV; +#endif + +DECLARE_CONSTANT_FOR_GPU(gpuErrorOutOfMemory, + cudaErrorMemoryAllocation, + hipErrorOutOfMemory); +DECLARE_CONSTANT_FOR_GPU(gpuErrorNotReady, cudaErrorNotReady, hipErrorNotReady); +DECLARE_CONSTANT_FOR_GPU(gpuSuccess, cudaSuccess, hipSuccess); + +DECLARE_CONSTANT_FOR_GPU(gpuMemcpyHostToDevice, + cudaMemcpyKind::cudaMemcpyHostToDevice, + hipMemcpyKind::hipMemcpyHostToDevice); +DECLARE_CONSTANT_FOR_GPU(gpuMemcpyDeviceToHost, + cudaMemcpyKind::cudaMemcpyDeviceToHost, + hipMemcpyKind::hipMemcpyDeviceToHost); +DECLARE_CONSTANT_FOR_GPU(gpuMemcpyDeviceToDevice, + cudaMemcpyKind::cudaMemcpyDeviceToDevice, + hipMemcpyKind::hipMemcpyDeviceToDevice); + +#undef DECLARE_CONSTANT_FOR_GPU +} // namespace phi + +#endif // defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/rocm/rocm_helper.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/rocm/rocm_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..07fdde5a2f417a7afff1dff3a404012d2a8409b1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/gpu/rocm/rocm_helper.h @@ -0,0 +1,74 @@ +// 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. + +#pragma once + +namespace phi { +namespace backends { +namespace gpu { + +/* + * Summary: Grid stride looping macro in CUDA kernel + * + * [ Why need this macro? ] + * + * The original looping in CUDA kernel is: + * + * `for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < (n); \ + * i += blockDim.x * gridDim.x)` + * + * This for condition is risky. The value of `blockIdx.x * blockDim.x` + * may be large, such as over 1GB, the first iteration is no problem here, + * but when `i += blockDim.x * gridDim.x` is executed, the value of i + * will greater than INT_MAX and overflow becomes negative value, at + * this time, the cycle condition `i < (n)` is still satisfied, so it + * will cause illegal access to cuda memory. + * + * Here is a real example in ERINE, it will trigger above error. + * The related data are: + * - blockIdx.x = 2172938 + * - blockDim.x = 512 + * - blockIdx.x * blockDim.x = 1112543864 + * - INT_MAX = 2147483647 + * + * So we polish the for condition as follow, the int64_t __index__ will + * prevent overflow in the loop increment. + * + * Parameters: + * - i: loop index + * - num: total element numbers + * + * Examples: + * template + * __global__ void Scale(T* logit_grad, const T* loss_grad, const int num, + * const int d, const int remain) { + * CUDA_KERNEL_LOOP(index, num) { + * int idx_n = index / d; + * int idx_remain = index % remain; + * logit_grad[index] *= loss_grad[idx_n * remain + idx_remain]; + * } + * } + * + */ + +#define CUDA_KERNEL_LOOP_TYPE(i, num, index_type) \ + int64_t __index__ = \ + static_cast(hipBlockIdx_x) * hipBlockDim_x + hipThreadIdx_x; \ + int64_t __stride__ = static_cast(hipBlockDim_x) * hipGridDim_x; \ + for (index_type i = __index__; __index__ < (num); \ + __index__ += __stride__, i = __index__) + +} // namespace gpu +} // namespace backends +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/axpy_handler.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/axpy_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..dd9a8108f59b05fb27fec41026961aba60dc167b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/axpy_handler.h @@ -0,0 +1,61 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "dnnl.hpp" // NOLINT + +namespace phi { +namespace funcs { +/// +/// @brief Helper class for AXPY execution using oneDNN library. +/// +/// @tparam T Data type. +/// +template +class OneDNNAXPYHandler { + public: + OneDNNAXPYHandler(OneDNNAXPYHandler&) = delete; + OneDNNAXPYHandler(OneDNNAXPYHandler&&) = delete; + OneDNNAXPYHandler& operator=(OneDNNAXPYHandler&) = delete; + OneDNNAXPYHandler& operator=(OneDNNAXPYHandler&&) = delete; + /// + /// @brief Constructor. + /// + /// @param[in] n The number of elements in tensor (assumed 1D + /// tensor) + /// @param[in] alpha The alpha coefficient. + /// @param[in] onednn_engine The oneDNN engine. + /// + OneDNNAXPYHandler(int64_t n, T alpha, dnnl::engine onednn_engine); + /// + /// @brief Executes AXPY. + /// + /// @param[in] x The pointer to input X tensor data. + /// @param[out] y The pointer to output Y tensor data. + /// + void operator()(const T* x, T* y); + + private: + OneDNNAXPYHandler() = delete; + // (arogowie-intel) Private implementation idiom to hide dependency + // on OneDNN headers. + class Impl; + // We need custom deleter, since the compiler is unable to parameterize + // an allocator's default deleter due to incomple type. + std::unique_ptr pimpl_; +}; +} // namespace funcs +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_context.h new file mode 100644 index 0000000000000000000000000000000000000000..d7cf8a0ff49021bb75d3304d6ac47a664e68d9ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_context.h @@ -0,0 +1,143 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#ifdef PADDLE_WITH_MKLDNN +#include +#include // NOLINT +#include "dnnl.hpp" // NOLINT +#include "paddle/phi/backends/cpu/cpu_context.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/place.h" + +namespace phi { + +class OneDNNContextThreadLocals { + // default mkldnn session id + + typedef OneDNNContextThreadLocals self; + struct Body { + bool said_once = false; + size_t cur_mkldnn_session_id; + // Current data input shape string. + // - For fixed-shape, it's a null string in default. + // - For dynamic-shape, it's user specific. + std::string cur_input_shape_str; + // the cache capacity of different input shapes for MKLDNN. + // Default 1 means fixed input shape, not dynamic shape. + int cur_input_shape_cache_capacity; + // Recently registered data_format. This is needed to + // know for converting MKL-DNN Tensor to non MKL-DNN + DataLayout cur_paddle_data_layout; + // MKL-DNN stream used for execution of primitives (per-thread) + dnnl::engine cur_engine; + dnnl::stream cur_stream; + std::string key_suffix; // Key identifying current Executor + bool key_attach_thread_id = true; + void* exec_ptr_ = nullptr; + + Body(); + ~Body(); + void set_cur_mkldnn_session_id(size_t sid); + size_t get_cur_mkldnn_session_id(void); + void set_cur_input_shape_str(std::string input_shape_str); + void set_cur_input_shape_cache_capacity(int input_shape_cache_capacity); + void set_cur_paddle_data_layout(DataLayout dl); + DataLayout get_cur_paddle_data_layout(void); + void log_lib_version(void); + const dnnl::engine& get_engine(void) { return cur_engine; } + dnnl::stream& get_stream(void) { return cur_stream; } + void set_key_suffix(const std::string& suffix) { key_suffix = suffix; } + const std::string& get_key_suffix(void) const { return key_suffix; } + void disable_tid_in_key(void) { key_attach_thread_id = false; } + bool is_tid_used_in_key(void) const { return key_attach_thread_id; } + void set_curr_exec(void* exec_ptr) { exec_ptr_ = exec_ptr; } + void* get_curr_exec(void) const { return exec_ptr_; } + }; + OneDNNContextThreadLocals() = default; + OneDNNContextThreadLocals(const OneDNNContextThreadLocals& c) = delete; + + public: + // default mkldnn session id + static constexpr size_t kMKLDNNSessionID_Default = 0; + // mkldnn session id for cache clearing mode + static constexpr size_t kMKLDNNSessionID_CacheClearing = -1; + static Body& fetch() { + thread_local Body b; + return b; + } +}; + +class OneDNNContext : public CPUContext { + public: + template + using BlobPtr_t = std::shared_ptr; + template + using umap_value_smart_t = std::unordered_map>; + template + using umap_key_string_t = umap_value_smart_t; + + // Following three maps are used to cache MKLDNN primitives. + // There relations are: + // - BlobMap = Map + // - ShapeBlob = Map + // - KeyBlob = Map + + using KeyBlob = umap_key_string_t; + using ShapeBlob = umap_key_string_t; + using BlobMap = umap_value_smart_t; + + // Auxillary two-level structure (shape, executor) to easier control + // clearing cache objects related to specific executor + + using ExecKey = void*; + using ExecMapCacheIterPair = std::pair, KeyBlob::iterator>; + using ExecMap = + std::unordered_map>; + using ExecShape = std::unordered_map>; + + explicit OneDNNContext(const Place& place); + ~OneDNNContext(); + /* \brief Get the active engine */ + const dnnl::engine& GetEngine() const { return tls().get_engine(); } + + // Remove all entries from the blob map + void ResetBlobMap(void* ptr); + + // Prevent next ResetBlobMap() + void BlockNextCacheClearing(); + + // Get the ShapeBlob size in cur_mkldnn_session_id. + size_t GetShapeBlobSize() const; + + // Set data to blob (i.e. name/data pair). Create blob if not existing + void SetBlob(const std::string& name, std::shared_ptr data) const; + + // Calculate number of oneDNN objects cached + unsigned int GetCachedObjectsNumber(void) const; + + // Find a saved blob. Return nullptr if not found + std::shared_ptr GetBlob(const std::string& name) const; + + static auto tls() -> decltype(OneDNNContextThreadLocals::fetch()) { + return OneDNNContextThreadLocals::fetch(); + } + + private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace phi +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_helper.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..e91e02282ccc0dc2f7221caa7813d3250251d23e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_helper.h @@ -0,0 +1,280 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "dnnl.hpp" // NOLINT +#include "glog/logging.h" + +#include "paddle/phi/backends/onednn/onednn_context.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +namespace funcs { + +using OneDNNMemoryFormat = dnnl::memory::format_tag; +using OneDNNDataType = dnnl::memory::data_type; + +template +void* to_void_cast(const Type* t) { + return static_cast(const_cast(t)); +} + +inline OneDNNMemoryFormat OneDNNFormatForSize(size_t dims_size, + OneDNNMemoryFormat data_format) { + if (dims_size == 1) { + return OneDNNMemoryFormat::x; + } else if (dims_size == 2) { + return OneDNNMemoryFormat::nc; + } else if (dims_size == 3) { + if (data_format == OneDNNMemoryFormat::nchw) { + return OneDNNMemoryFormat::ncw; + } else if (data_format == OneDNNMemoryFormat::nhwc) { + return OneDNNMemoryFormat::nwc; + } + } else if (dims_size == 4) { + if (data_format == OneDNNMemoryFormat::goihw) { + return OneDNNMemoryFormat::oihw; + } + } else if (dims_size == 5) { + if (data_format == OneDNNMemoryFormat::goidhw) { + return OneDNNMemoryFormat::oidhw; + } + if (data_format == OneDNNMemoryFormat::nchw) { + return OneDNNMemoryFormat::ncdhw; + } else if (data_format == OneDNNMemoryFormat::nhwc) { + return OneDNNMemoryFormat::ndhwc; + } + } else if (dims_size == 6) { + if (data_format == OneDNNMemoryFormat::nchw) { + return OneDNNMemoryFormat::abcdef; + } + } + return data_format; +} + +inline dnnl::memory::format_tag GetPlainOneDNNFormat(int tensor_rank) { + switch (tensor_rank) { + case 1: + return dnnl::memory::format_tag::a; + case 2: + return dnnl::memory::format_tag::ab; + case 3: + return dnnl::memory::format_tag::abc; + case 4: + return dnnl::memory::format_tag::abcd; + case 5: + return dnnl::memory::format_tag::abcde; + case 6: + return dnnl::memory::format_tag::abcdef; + case 7: + return dnnl::memory::format_tag::abcdefg; + case 8: + return dnnl::memory::format_tag::abcdefgh; + case 9: + return dnnl::memory::format_tag::abcdefghi; + default: + PADDLE_THROW(phi::errors::Unimplemented( + "Paddle support tensors with rank in range <1, 9>, but received " + "tensor with rank: %d", + tensor_rank)); + } +} + +template +dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::undef; +} + +template <> +inline dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::f32; +} +template <> +inline dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::s32; +} +template <> +inline dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::s8; +} +template <> +inline dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::u8; +} + +template <> +inline dnnl::memory::data_type OneDNNGetDataType() { + return dnnl::memory::data_type::bf16; +} + +inline std::vector> ToOneDNNPadding( + const std::vector& paddings) { + if (paddings.size() == 6) { + int padding_front = paddings[0]; + int padding_back = paddings[1]; + int padding_top = paddings[2]; + int padding_bottom = paddings[3]; + int padding_left = paddings[4]; + int padding_right = paddings[5]; + + return {{padding_front, padding_top, padding_left}, + {padding_back, padding_bottom, padding_right}}; + } else { + int padding_top = paddings[0]; + int padding_bottom = paddings[1]; + int padding_left = paddings[2]; + int padding_right = paddings[3]; + + return {{padding_top, padding_left}, {padding_bottom, padding_right}}; + } +} + +template +inline void AppendKey(std::string* key, const T& num) { + key->append(std::to_string(num)); +} + +template <> +inline void AppendKey(std::string* key, + const dnnl::memory::format_tag& format) { + key->append(std::to_string(static_cast(format))); +} + +template <> +inline void AppendKey(std::string* key, + const dnnl::memory::data_type& data_type) { + key->append(std::to_string(static_cast(data_type))); +} + +template <> +inline void AppendKey(std::string* key, const dnnl::algorithm& algorithm) { + key->append(std::to_string(static_cast(algorithm))); +} + +template <> +inline void AppendKey(std::string* key, + const dnnl::normalization_flags& flags) { + key->append(std::to_string(static_cast(flags))); +} + +inline void AppendKey(std::string* key, const std::string& str) { + key->append(str); +} + +inline void AppendKey(std::string* key, const char* str) { key->append(str); } + +template +inline void AppendKey(std::string* key, const std::vector& dims) { + for (size_t i = 0; i < dims.size(); i++) { + AppendKey(key, std::to_string(dims[i])); + } +} + +template +inline std::string CreateKey(const OneDNNContext& dev_ctx, ArgTypes&&... args) { + std::string key; + key.reserve(64); + using expand_type = int[]; + expand_type{0, (AppendKey(&key, std::forward(args)), 0)...}; + key += OneDNNContext::tls().get_key_suffix(); + return key; +} + +inline void MatchShapeToLayout(DenseTensor* tensor_in, + DataLayout from, + DataLayout to) { + auto print_dims = [](const std::vector& dims) { + std::ostringstream oss; + + if (!dims.empty()) { + oss << "["; + // Convert all but the last element to avoid a trailing "," + std::copy( + dims.begin(), dims.end() - 1, std::ostream_iterator(oss, ",")); + + // Now add the last element with no delimiter + oss << dims.back() << "]"; + } + + return oss.str(); + }; + + // In these data layouts, channel dimension is either on 2nd position: nChw or + // at last nhwC, so for dim==2 these layouts are the same and nothing should + // be done. Similarly for dim==1 when you have just one possible combination. + if (tensor_in->dims().size() < 3) { + VLOG(3) << "Keeping ONEDNN/NHWC/NDHWC output_shape" + << print_dims(phi::vectorize(tensor_in->dims())); + return; + } + + switch (from) { + case DataLayout::ONEDNN: + if ((to == DataLayout::NHWC) || (to == DataLayout::NDHWC)) { + auto dims = phi::vectorize(tensor_in->dims()); + std::rotate(dims.begin() + 1, dims.begin() + 2, dims.end()); + tensor_in->Resize(phi::make_ddim(dims)); + VLOG(3) << "Rotating Shape from: ONEDNN to: NHWC/NDHWC output_shape" + << print_dims(dims); + } + break; + case DataLayout::NHWC: + case DataLayout::NDHWC: + if (to == DataLayout::ONEDNN) { + auto dims = phi::vectorize(tensor_in->dims()); + std::rotate(dims.begin() + 1, dims.end() - 1, dims.end()); + tensor_in->Resize(phi::make_ddim(dims)); + VLOG(3) << "Rotating Shape from: NHWC/NDHWC to: ONEDNN output_shape" + << print_dims(dims); + } + break; + default: + break; + } +} + +struct onednn_dummy_primitive { + struct primitive_desc {}; + struct desc {}; +}; + +inline dnnl::memory::desc OneDNNMemDesc(const std::vector& dims, + dnnl::memory::data_type data_type, + OneDNNMemoryFormat format) { + return dnnl::memory::desc({dims}, data_type, format); +} + +inline std::string ThreadIDasStr(void) { + return std::to_string( + std::hash()(std::this_thread::get_id())); +} + +inline std::string ExtendKeyWithThreadInfoIfNeeded(const OneDNNContext& dev_ctx, + const std::string& key) { + return (OneDNNContext::tls().is_tid_used_in_key() == true) + ? key + "-t:" + ThreadIDasStr() + : key; +} + +template +bool constexpr is_int8() { + return std::is_same::value || std::is_same::value; +} + +} // namespace funcs +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_reuse.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_reuse.h new file mode 100644 index 0000000000000000000000000000000000000000..cd8c076b28503c2dd76493fd8913c67d86816a58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/onednn/onednn_reuse.h @@ -0,0 +1,1153 @@ +/* Copyright (c) 2022 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. */ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "paddle/fluid/platform/profiler/event_tracing.h" +#include "paddle/phi/backends/onednn/onednn_context.h" +#include "paddle/phi/backends/onednn/onednn_helper.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/kernels/funcs/axis_utils.h" +#include "paddle/phi/kernels/funcs/data_layout_transform.h" + +namespace phi { +namespace funcs { + +using user_function = std::function(const float*)>; +using memory = dnnl::memory; + +using OneDNNMemoryFormat = dnnl::memory::format_tag; + +template +class OneDNNHandlerT { + public: + OneDNNHandlerT(const OneDNNContext& dev_ctx, + dnnl::engine engine, + Place cpu_place, + const std::string& base_key) + : dev_ctx_(dev_ctx), + engine_(engine), + place_(cpu_place), + key_common_(base_key), + key_(ExtendKeyWithThreadInfoIfNeeded(dev_ctx, base_key)), + fwd_pd_(nullptr), + bwd_pd_(nullptr) { + OneDNNContext::tls().log_lib_version(); + } + + std::shared_ptr AcquireForwardPrimitive() { + const std::string key_p = key_ + "@fwd_p"; + auto forward_p = + std::static_pointer_cast(dev_ctx_.GetBlob(key_p)); + if (forward_p == nullptr) { + forward_p = std::make_shared(*fwd_pd_); + dev_ctx_.SetBlob(key_p, forward_p); + } + return forward_p; + } + + std::shared_ptr AcquireBackwardPrimitive() { + const std::string key_p = key_ + "@bwd_p"; + auto backward_p = + std::static_pointer_cast(dev_ctx_.GetBlob(key_p)); + if (backward_p == nullptr) { + backward_p = std::make_shared(*bwd_pd_); + dev_ctx_.SetBlob(key_p, backward_p); + } + return backward_p; + } + + std::shared_ptr AcquireBackwardWeightsPrimitive() { + const std::string key_p = key_ + "@bwd_w_p"; + auto backward_p = + std::static_pointer_cast(dev_ctx_.GetBlob(key_p)); + if (backward_p == nullptr) { + PADDLE_ENFORCE_NOT_NULL( + bwd_w_pd_, + errors::Unavailable("BWD_PD should be set when " + "getting BWD prim witk key: %s .", + key_p)); + backward_p = std::make_shared(*bwd_w_pd_); + dev_ctx_.SetBlob(key_p, backward_p); + } + return backward_p; + } + + std::shared_ptr AcquireSrcMemory(const DenseTensor* input) { + const T* input_data = input->data(); + return this->AcquireMemoryFromPrimitive( + fwd_pd_->src_desc(), to_void_cast(input_data), "@src_mem_p"); + } + + template + std::shared_ptr AcquireDstMemory(DenseTensor* output) { + T_out* ptr = + output->mutable_data(place_, fwd_pd_->dst_desc().get_size()); + return this->AcquireMemoryFromPrimitive( + fwd_pd_->dst_desc(), ptr, "@dst_mem_p"); + } + + template + std::shared_ptr AcquireDstMemory(void) { + return this->AcquireMemoryFromPrimitive(fwd_pd_->dst_desc(), "@dstt_mem_p"); + } + + template + std::shared_ptr AcquireDstMemory(const DenseTensor* output) { + const T_out* output_data = output->data(); + return this->AcquireMemoryFromPrimitive(bwd_pd_->dst_desc(), + to_void_cast(output_data), + "@bwd-dst_mem_p"); + } + + std::shared_ptr AcquireDiffDstMemory( + const DenseTensor* diffdst) { + const T* ptr = diffdst->data(); + return this->AcquireMemoryFromPrimitive( + bwd_pd_->diff_dst_desc(), to_void_cast(ptr), "@diff_dst_mem_p"); + } + + std::shared_ptr AcquireDiffSrcMemory(DenseTensor* diffsrc) { + T* ptr = + diffsrc->mutable_data(place_, bwd_pd_->diff_src_desc().get_size()); + return this->AcquireMemoryFromPrimitive( + bwd_pd_->diff_src_desc(), ptr, "@diff_src_mem_p"); + } + + // Buffer of given DenseTensor is used for oneDNN computation + std::shared_ptr AcquireDiffWeightsMemory( + DenseTensor* diff_weights) { + PADDLE_ENFORCE_NOT_NULL( + bwd_w_pd_, + errors::Unavailable( + "BWD_W_PD should be set when getting BWD grad of weights.")); + T* ptr = diff_weights->mutable_data( + place_, bwd_w_pd_->diff_weights_desc().get_size()); + return this->AcquireMemoryFromPrimitive( + bwd_w_pd_->diff_weights_desc(), ptr, "@diff_wei_mem_p"); + } + + // Buffer is allocated by oneDNN to store computation results + std::shared_ptr AcquireDiffWeightsMemory(void) { + PADDLE_ENFORCE_NOT_NULL( + bwd_w_pd_, + errors::Unavailable( + "BWD_W_PD should be set when getting BWD grad of weights.")); + return this->AcquireMemoryFromPrimitive(bwd_w_pd_->diff_weights_desc(), + "@diff_wei_mem_p"); + } + + protected: + bool isCached() { + const std::string key_pd = key_ + "@fwd_pd"; + fwd_pd_ = std::static_pointer_cast( + dev_ctx_.GetBlob(key_pd)); + + return (fwd_pd_ != nullptr); + } + + bool isBwdCached() { + const std::string key_pd = key_ + "@bwd_pd"; + bwd_pd_ = std::static_pointer_cast( + dev_ctx_.GetBlob(key_pd)); + + if (bwd_pd_ == nullptr) { + return false; + } else { + if (std::is_same::value == + false) { + const std::string key_bw_w_pd = key_ + "@bwd_w_pd"; + bwd_w_pd_ = + std::static_pointer_cast( + dev_ctx_.GetBlob(key_bw_w_pd)); + } + + // When BWD is cached then still we need to Get FWD PD + const std::string key_fpd = key_ + "@fwd_pd"; + fwd_pd_ = std::static_pointer_cast( + dev_ctx_.GetBlob(key_fpd)); + PADDLE_ENFORCE_NOT_NULL( + fwd_pd_, + errors::Unavailable( + "Error: FWD PD should be set when BWD PD is cached.")); + return true; + } + } + + // If your primitive descriptor requires attributes, pass them as a + // first argument and paramters to descriptor constructor in the following + // arguments. Otherwise, all arguments will be forwarded to descriptor + // constructor, including the first one. + template + void AcquireForwardPrimitiveDescriptor(Arg&& first_arg, Args&&... args) { + // This is used when we can recreate FWD PD in BWD so + // we do not need to pass FWD to BWD + const std::string key_pd = key_ + "@fwd_pd"; + fwd_pd_ = std::static_pointer_cast( + dev_ctx_.GetBlob(key_pd)); + if (fwd_pd_ == nullptr) { + CreateForwardPrimitiveDescriptor(first_arg, std::forward(args)...); + dev_ctx_.SetBlob(key_pd, fwd_pd_); + } + } + + // Using sfinae to specialise variadic function. Workaround for not having + // if constexpr in C++ 11. + template + typename std::enable_if::type, + dnnl::primitive_attr>::value>::type + CreateForwardPrimitiveDescriptor(First&& first, Args&&... args) { + auto fwd_desc = typename TForward::desc(std::forward(args)...); + fwd_pd_ = std::make_shared( + fwd_desc, first, engine_); + } + + template + typename std::enable_if::type, + dnnl::primitive_attr>::value>::type + CreateForwardPrimitiveDescriptor(First&& first, Args&&... args) { + auto fwd_desc = typename TForward::desc(std::forward(first), + std::forward(args)...); + fwd_pd_ = + std::make_shared(fwd_desc, engine_); + } + + template + void AcquireBackwardPrimitiveDescriptor(Args&&... args) { + // fwd_pd_ is set during grad by calling + // AcquireForwardPrimitiveDescriptor + PADDLE_ENFORCE_NOT_NULL( + fwd_pd_, + errors::Unavailable("Get OneDNN Forward primitive %s failed.", + key_ + "@fwd_pd")); + const std::string key_pd = key_ + "@bwd_pd"; + bwd_pd_ = std::static_pointer_cast( + dev_ctx_.GetBlob(key_pd)); + if (bwd_pd_ == nullptr) { + auto bwd_desc = typename TBackward::desc(std::forward(args)...); + bwd_pd_ = std::make_shared( + bwd_desc, engine_, *fwd_pd_); + dev_ctx_.SetBlob(key_pd, bwd_pd_); + } + } + + template + void AcquireBackwardWeightsPrimitiveDescriptor(Args&&... args) { + // fwd_pd_ is set during grad by calling + // AcquireForwardPrimitiveDescriptor + PADDLE_ENFORCE_NOT_NULL( + fwd_pd_, + errors::Unavailable("Get OneDNN Forward primitive %s failed.", + key_ + "@fwd_pd")); + const std::string key_pd = key_ + "@bwd_w_pd"; + bwd_w_pd_ = + std::static_pointer_cast( + dev_ctx_.GetBlob(key_pd)); + if (bwd_w_pd_ == nullptr) { + auto bwd_desc = + typename TBackward_params::desc(std::forward(args)...); + bwd_w_pd_ = std::make_shared( + bwd_desc, engine_, *fwd_pd_); + dev_ctx_.SetBlob(key_pd, bwd_w_pd_); + } + } + + std::shared_ptr AcquireMemoryFromPrimitive( + const std::string& suffix) { + return std::static_pointer_cast( + dev_ctx_.GetBlob(key_ + suffix)); + } + + std::shared_ptr AcquireMemoryFromPrimitive( + dnnl::memory::desc md, void* ptr, const std::string& suffix) { + const auto local_key = key_ + suffix; + auto mem_p = + std::static_pointer_cast(dev_ctx_.GetBlob(local_key)); + if (mem_p == nullptr) { + mem_p = std::make_shared(md, engine_, ptr); + dev_ctx_.SetBlob(local_key, mem_p); + } else { + mem_p->set_data_handle(ptr); + } + return mem_p; + } + + std::shared_ptr AcquireMemoryFromPrimitive( + dnnl::memory::desc md, const std::string& suffix) { + const auto local_key = key_ + suffix; + auto mem_p = + std::static_pointer_cast(dev_ctx_.GetBlob(local_key)); + if (mem_p == nullptr) { + mem_p = std::make_shared(md, engine_); + dev_ctx_.SetBlob(local_key, mem_p); + } + return mem_p; + } + + void AcquireReorder(const std::shared_ptr& user_memory_p, + const std::shared_ptr& target_memory_p) { + auto reorder_p = + std::make_shared(*user_memory_p, *target_memory_p); + + auto& astream = OneDNNContext::tls().get_stream(); + + paddle::platform::RecordEvent record_reorder( + "int_reorder", + paddle::platform::TracerEventType::UserDefined, + 2, + paddle::platform::EventRole::kUniqueOp); + reorder_p->execute( + astream, + {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}}); + astream.wait(); + } + + template + std::shared_ptr AcquireMemoryWithReorder( + const dnnl::memory::desc& user_md, + const dnnl::memory::desc& target_md, + void* ptr, + const std::string& suffix, + bool is_persistent = false, + std::function(const F*)> custom_reorder_func = {}, + const std::vector& scale_data = {1.0f}, + int mask = 0) { + const auto target_key = key_ + suffix + "_target"; + const auto key_reorder_p = key_ + suffix + "reorder_p"; + const auto user_key = key_ + suffix + "_user"; + + auto target_memory_p = + std::static_pointer_cast(dev_ctx_.GetBlob(target_key)); + + if (target_memory_p == nullptr) { + if (custom_reorder_func) { + auto reordered_data = + custom_reorder_func(reinterpret_cast(ptr)); + dev_ctx_.SetBlob(key_reorder_p + "-custom_reorder", reordered_data); + ptr = reinterpret_cast(reordered_data.get()); + } + auto user_memory_p = + std::make_shared(user_md, engine_, ptr); + if (user_md != target_md) { + target_memory_p = std::make_shared(target_md, engine_); + dnnl::reorder::primitive_desc reorder_pdesc; + if (is_int8()) { + dnnl::primitive_attr attr; + attr.set_output_scales(mask, scale_data); + reorder_pdesc = dnnl::reorder::primitive_desc( + *user_memory_p, *target_memory_p, attr); + } else { + reorder_pdesc = + dnnl::reorder::primitive_desc(*user_memory_p, *target_memory_p); + } + auto reorder_p = std::make_shared(reorder_pdesc); + dev_ctx_.SetBlob(key_reorder_p, reorder_p); + + auto& astream = OneDNNContext::tls().get_stream(); + paddle::platform::RecordEvent record_reorder( + "int_reorder", + paddle::platform::TracerEventType::UserDefined, + 2, + paddle::platform::EventRole::kUniqueOp); + reorder_p->execute( + astream, + {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}}); + astream.wait(); + } else { + target_memory_p = user_memory_p; + } + dev_ctx_.SetBlob(user_key, user_memory_p); + dev_ctx_.SetBlob(target_key, target_memory_p); + } else if (!is_persistent) { + auto& astream = OneDNNContext::tls().get_stream(); + + auto user_memory_p = + std::static_pointer_cast(dev_ctx_.GetBlob(user_key)); + user_memory_p->set_data_handle(ptr); + + // TODO(jczaja): Here we detect if reorder is cached it means it is needed + // need to change this to get rid of keys + auto reorder_p = std::static_pointer_cast( + dev_ctx_.GetBlob(key_reorder_p)); + if (reorder_p != nullptr) { + paddle::platform::RecordEvent record_reorder( + "int_reorder", + paddle::platform::TracerEventType::UserDefined, + 2, + paddle::platform::EventRole::kUniqueOp); + reorder_p->execute( + astream, + {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}}); + astream.wait(); + } + } + return target_memory_p; + } + + std::shared_ptr AcquireMemory(const std::string& suffix) { + const auto local_key = key_ + suffix; + return std::static_pointer_cast(dev_ctx_.GetBlob(local_key)); + } + + const OneDNNContext& dev_ctx_; + dnnl::engine engine_; + Place place_; + std::string key_common_; + std::string key_; + std::shared_ptr fwd_pd_; + std::shared_ptr bwd_pd_; + std::shared_ptr bwd_w_pd_; +}; + +template +class OneDNNHandlerNoCachingT { + public: + OneDNNHandlerNoCachingT(dnnl::engine engine, Place cpu_place) + : engine_(engine), place_(cpu_place), fwd_pd_(nullptr), bwd_pd_(nullptr) { + OneDNNContext::tls().log_lib_version(); + } + + std::shared_ptr AcquireForwardPrimitive() { + return std::make_shared(*fwd_pd_); + } + + std::shared_ptr AcquireBackwardPrimitive() { + return std::make_shared(*bwd_pd_); + } + + std::shared_ptr AcquireBackwardWeightsPrimitive() { + PADDLE_ENFORCE_NOT_NULL(bwd_w_pd_, + errors::Unavailable("BWD_PD should be set when " + "getting BWD prim .")); + return std::make_shared(*bwd_w_pd_); + } + + std::shared_ptr AcquireSrcMemory(const DenseTensor* input) { + const T* input_data = input->data(); + return this->AcquireMemoryFromPrimitive(fwd_pd_->src_desc(), + to_void_cast(input_data)); + } + + template + std::shared_ptr AcquireDstMemory(DenseTensor* output) { + T_out* ptr = + output->mutable_data(place_, fwd_pd_->dst_desc().get_size()); + return this->AcquireMemoryFromPrimitive(fwd_pd_->dst_desc(), ptr); + } + + template + std::shared_ptr AcquireDstMemory(void) { + return this->AcquireMemoryFromPrimitive(fwd_pd_->dst_desc()); + } + + template + std::shared_ptr AcquireDstMemory(const DenseTensor* output) { + const T_out* output_data = output->data(); + return this->AcquireMemoryFromPrimitive(bwd_pd_->dst_desc(), + to_void_cast(output_data)); + } + + std::shared_ptr AcquireDiffDstMemory( + const DenseTensor* diffdst) { + const T* ptr = diffdst->data(); + return this->AcquireMemoryFromPrimitive(bwd_pd_->diff_dst_desc(), + to_void_cast(ptr)); + } + + std::shared_ptr AcquireDiffSrcMemory(DenseTensor* diffsrc) { + T* ptr = + diffsrc->mutable_data(place_, bwd_pd_->diff_src_desc().get_size()); + return this->AcquireMemoryFromPrimitive(bwd_pd_->diff_src_desc(), ptr); + } + + // Buffer of given DenseTensor is used for oneDNN computation + std::shared_ptr AcquireDiffWeightsMemory( + DenseTensor* diff_weights) { + PADDLE_ENFORCE_NOT_NULL( + bwd_w_pd_, + errors::Unavailable( + "BWD_W_PD should be set when getting BWD grad of weights.")); + T* ptr = diff_weights->mutable_data( + place_, bwd_w_pd_->diff_weights_desc().get_size()); + return this->AcquireMemoryFromPrimitive(bwd_w_pd_->diff_weights_desc(), + ptr); + } + + // Buffer is allocated by oneDNN to store computation results + std::shared_ptr AcquireDiffWeightsMemory(void) { + PADDLE_ENFORCE_NOT_NULL( + bwd_w_pd_, + errors::Unavailable( + "BWD_W_PD should be set when getting BWD grad of weights.")); + return this->AcquireMemoryFromPrimitive(bwd_w_pd_->diff_weights_desc()); + } + + protected: + // If your primitive descriptor requires attributes, pass them as a + // first argument and paramters to descriptor constructor in the following + // arguments. Otherwise, all arguments will be forwarded to descriptor + // constructor, including the first one. + template + void AcquireForwardPrimitiveDescriptor(Arg&& first_arg, Args&&... args) { + CreateForwardPrimitiveDescriptor(first_arg, std::forward(args)...); + } + + // Using sfinae to specialise variadic function. Workaround for not having + // if constexpr in C++ 11. + template + typename std::enable_if::type, + dnnl::primitive_attr>::value>::type + CreateForwardPrimitiveDescriptor(First&& first, Args&&... args) { + auto fwd_desc = typename TForward::desc(std::forward(args)...); + fwd_pd_ = std::make_shared( + fwd_desc, first, engine_); + } + + template + typename std::enable_if::type, + dnnl::primitive_attr>::value>::type + CreateForwardPrimitiveDescriptor(First&& first, Args&&... args) { + auto fwd_desc = typename TForward::desc(std::forward(first), + std::forward(args)...); + fwd_pd_ = + std::make_shared(fwd_desc, engine_); + } + + template + void AcquireBackwardPrimitiveDescriptor(Args&&... args) { + // fwd_pd_ is set during grad by calling + // AcquireForwardPrimitiveDescriptor + PADDLE_ENFORCE_NOT_NULL( + fwd_pd_, + errors::Unavailable("Get oneDNN Forward primitive %s failed.")); + auto bwd_desc = typename TBackward::desc(std::forward(args)...); + bwd_pd_ = std::make_shared( + bwd_desc, engine_, *fwd_pd_); + } + + template + void AcquireBackwardWeightsPrimitiveDescriptor(Args&&... args) { + // fwd_pd_ is set during grad by calling + // AcquireForwardPrimitiveDescriptor + PADDLE_ENFORCE_NOT_NULL( + fwd_pd_, + errors::Unavailable("Get oneDNN Forward primitive %s failed.")); + auto bwd_desc = + typename TBackward_params::desc(std::forward(args)...); + bwd_w_pd_ = std::make_shared( + bwd_desc, engine_, *fwd_pd_); + } + + std::shared_ptr AcquireMemoryFromPrimitive( + dnnl::memory::desc md, void* ptr) { + return std::make_shared(md, engine_, ptr); + } + + std::shared_ptr AcquireMemoryFromPrimitive( + dnnl::memory::desc md) { + return std::make_shared(md, engine_); + } + + void AcquireReorder(const std::shared_ptr& user_memory_p, + const std::shared_ptr& target_memory_p) { + auto reorder_p = + std::make_shared(*user_memory_p, *target_memory_p); + + auto& astream = OneDNNContext::tls().get_stream(); + + paddle::platform::RecordEvent record_reorder( + "int_reorder", + paddle::platform::TracerEventType::UserDefined, + 2, + paddle::platform::EventRole::kUniqueOp); + reorder_p->execute( + astream, + {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}}); + astream.wait(); + } + + template + std::shared_ptr AcquireMemoryWithReorder( + const dnnl::memory::desc& user_md, + const dnnl::memory::desc& target_md, + void* ptr, + bool is_persistent = false, + std::function(const F*)> custom_reorder_func = {}) { + std::shared_ptr target_memory_p; + if (custom_reorder_func) { + auto reordered_data = + custom_reorder_func(reinterpret_cast(ptr)); + ptr = reinterpret_cast(reordered_data.get()); + } + auto user_memory_p = std::make_shared(user_md, engine_, ptr); + if (user_md != target_md) { + target_memory_p = std::make_shared(target_md, engine_); + auto reorder_p = + std::make_shared(*user_memory_p, *target_memory_p); + + auto& astream = OneDNNContext::tls().get_stream(); + paddle::platform::RecordEvent record_reorder( + "int_reorder", + paddle::platform::TracerEventType::UserDefined, + 2, + paddle::platform::EventRole::kUniqueOp); + reorder_p->execute( + astream, + {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}}); + astream.wait(); + } else { + target_memory_p = user_memory_p; + } + return target_memory_p; + } + + dnnl::engine engine_; + Place place_; + std::shared_ptr fwd_pd_; + std::shared_ptr bwd_pd_; + std::shared_ptr bwd_w_pd_; +}; + +template +class ActivationOneDNNHandler + : public OneDNNHandlerNoCachingT { + public: + ActivationOneDNNHandler(dnnl::algorithm algorithm, + float alpha, + float beta, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + this->AcquireForwardPrimitiveDescriptor(dnnl::prop_kind::forward_training, + algorithm, + x->mem_desc(), + alpha, + beta); + } + + ActivationOneDNNHandler(dnnl::algorithm algorithm, + float alpha, + float beta, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x, + const DenseTensor* dout) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + this->AcquireForwardPrimitiveDescriptor(dnnl::prop_kind::forward_training, + algorithm, + x->mem_desc(), + alpha, + beta); + this->AcquireBackwardPrimitiveDescriptor( + algorithm, dout->mem_desc(), x->mem_desc(), alpha, beta); + } + + std::shared_ptr AcquireBackwardSrcMemory( + const DenseTensor* input) { + const T* input_data = input->data(); + return this->AcquireMemoryFromPrimitive(this->bwd_pd_->src_desc(), + to_void_cast(input_data)); + } +}; + +template +class SoftmaxOneDNNHandler + : public OneDNNHandlerNoCachingT { + public: + SoftmaxOneDNNHandler(const dnnl::engine onednn_engine, + Place cpu_place, + const DenseTensor* x, + int axis) + : OneDNNHandlerNoCachingT(onednn_engine, + cpu_place) { + const int canonical_axis = funcs::CanonicalAxis(axis, x->dims().size()); + this->AcquireForwardPrimitiveDescriptor( + dnnl::prop_kind::forward_scoring, x->mem_desc(), canonical_axis); + } + + SoftmaxOneDNNHandler(const dnnl::engine onednn_engine, + Place cpu_place, + int axis, + const DenseTensor* out, + const DenseTensor* out_grad) + : OneDNNHandlerNoCachingT(onednn_engine, + cpu_place) { + const int canonical_axis = + funcs::CanonicalAxis(axis, out_grad->dims().size()); + this->AcquireForwardPrimitiveDescriptor( + dnnl::prop_kind::forward_scoring, out->mem_desc(), canonical_axis); + this->AcquireBackwardPrimitiveDescriptor( + out_grad->mem_desc(), out->mem_desc(), canonical_axis); + } +}; + +class ReorderOneDNNHandler { + public: + ReorderOneDNNHandler(std::vector& dims, // NOLINT + DataType ptype, + dnnl::memory::data_type dtype, + dnnl::engine engine) + : dims_(dims), + ptype_(ptype), + ptype_dst_(ptype), + dtype_(dtype), + dtype_dst_(dtype), + engine_(engine) {} + + ReorderOneDNNHandler(std::vector& dims, // NOLINT + DataType ptype, + dnnl::memory::data_type dtype, + DataType ptype_dst, + dnnl::memory::data_type dtype_dst, + dnnl::engine engine) + : dims_(dims), + ptype_(ptype), + ptype_dst_(ptype_dst), + dtype_(dtype), + dtype_dst_(dtype_dst), + engine_(engine) {} + + std::shared_ptr AcquireSrcMemory(const dnnl::memory::desc& md, + void* ptr) { + return std::make_shared(md, engine_, ptr); + } + + std::shared_ptr AcquireSrcMemory(const OneDNNMemoryFormat& fmt, + void* ptr) { + auto md = dnnl::memory::desc(dims_, dtype_, fmt); + return std::make_shared(md, engine_, ptr); + } + + std::shared_ptr AcquireSubmemory( + const std::vector& dims, + const std::vector& offset, + const std::shared_ptr& mem_p) { + auto sub_md = mem_p->get_desc().submemory_desc(dims, {offset}); + auto sub_mem_p = std::make_shared( + sub_md, engine_, mem_p->get_data_handle()); + return sub_mem_p; + } + + std::shared_ptr AcquireDstMemory(DenseTensor* output, + const OneDNNMemoryFormat& fmt, + Place place) { + auto dst_md = OneDNNMemDesc(dims_, dtype_dst_, fmt); + auto dst_data = output->mutable_data(place, ptype_dst_, dst_md.get_size()); + return std::make_shared(dst_md, engine_, dst_data); + } + + std::shared_ptr AcquireDstMemory( + DenseTensor* output, const dnnl::memory::desc& src_md, Place place) { + if (ptype_dst_ == ptype_) { + auto dst_data = + output->mutable_data(place, ptype_dst_, src_md.get_size()); + return std::make_shared(src_md, engine_, dst_data); + } else { + auto dst_md = src_md; + dst_md.data.data_type = static_cast(dtype_dst_); + auto dst_data = + output->mutable_data(place, ptype_dst_, dst_md.get_size()); + return std::make_shared(dst_md, engine_, dst_data); + } + } + + std::shared_ptr AcquireDstMemory( + DenseTensor* output, + const std::vector& dims, + const OneDNNMemoryFormat& fmt, + Place place) { + auto dst_md = OneDNNMemDesc(dims, dtype_dst_, fmt); + auto dst_data = output->mutable_data(place, ptype_dst_, dst_md.get_size()); + return std::make_shared(dst_md, engine_, dst_data); + } + + std::shared_ptr AcquireReorder( + std::shared_ptr dst_memory_p, + std::shared_ptr src_memory_p) { + return std::make_shared(*(src_memory_p), *(dst_memory_p)); + } + + std::shared_ptr AcquireReorder( + std::shared_ptr dst_memory_p, + std::shared_ptr src_memory_p, + const dnnl::primitive_attr& attrs) { + return std::make_shared( + *(src_memory_p), *(dst_memory_p), attrs); + } + + private: + std::vector dims_; + DataType ptype_, ptype_dst_; + dnnl::memory::data_type dtype_, dtype_dst_; + dnnl::engine engine_; +}; + +template +class BinaryOneDNNHandler : public OneDNNHandlerNoCachingT { + public: + bool use_broadcasting_hack; + BinaryOneDNNHandler(const dnnl::algorithm algo, + const int axis, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x, + const DenseTensor* y, + DenseTensor* out, + float scale_x, + float scale_y, + float scale_out, + bool allow_hack, + const dnnl::post_ops& post_ops = dnnl::post_ops{}) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + use_broadcasting_hack = false; + const auto src_x_tz = vectorize(x->dims()); + const auto src_y_tz = vectorize(y->dims()); + // if output tensor(z) is nullptr then we are computing into oneDNN + // managed buffer + auto rankdiff = x->dims().size() - y->dims().size(); + auto dst_tz = (out == nullptr) ? (rankdiff > 0 ? src_x_tz : src_y_tz) + : vectorize(out->dims()); + + auto src0_md = x->mem_desc(); + auto src1_md = y->mem_desc(); + if (rankdiff > 0) { // Second input is of smaller rank than first + std::vector dims1_ex(rankdiff, 1); + dims1_ex.insert(next(dims1_ex.begin(), (axis == -1 ? rankdiff : axis)), + src_y_tz.begin(), + src_y_tz.end()); + // For broadcasting for NHWC we need rotate extended shape + if (OneDNNContext::tls().get_cur_paddle_data_layout() == + DataLayout::kNHWC) { + std::rotate(dims1_ex.begin() + 1, dims1_ex.end() - 1, dims1_ex.end()); + } + src1_md = src1_md.reshape(dims1_ex); + } else if (rankdiff < 0) { // First input is of smaller than second + std::vector dims0_ex(-rankdiff, 1); + dims0_ex.insert(next(dims0_ex.begin(), (axis == -1 ? -rankdiff : axis)), + src_x_tz.begin(), + src_x_tz.end()); + // For broadcasting for NHWC we need rotate extended shape + if (OneDNNContext::tls().get_cur_paddle_data_layout() == + DataLayout::kNHWC) { + std::rotate(dims0_ex.begin() + 1, dims0_ex.end() - 1, dims0_ex.end()); + } + src0_md = src0_md.reshape(dims0_ex); + } + + auto attributes = + CreateAttributes(algo, scale_x, scale_y, scale_out, post_ops); + + // Workaround for U2++ model which deletes first tensor dimensions to enable + // optimized oneDNNs broadcasting. Output tensor is reshaped back afterwards + // at the end of the kernel, after the computation + if (allow_hack && dst_tz.size() == 4 && + src0_md.dims()[2] != src1_md.dims()[2]) { + auto are_strides_plain = [](int64_t* strides, int ndims) { + for (int i = 0; i < ndims - 1; ++i) { + if (strides[i] < strides[i + 1]) { + return false; + } + } + return true; + }; + + auto src0_strides = src0_md.data.format_desc.blocking.strides; + auto src1_strides = src1_md.data.format_desc.blocking.strides; + auto src0_dims = src0_md.dims(); + auto src1_dims = src1_md.dims(); + + bool can_squeeze = src0_dims[0] == src1_dims[0] && + src0_dims[1] == src1_dims[1] && + src0_dims[3] == src1_dims[3]; + + if (can_squeeze && are_strides_plain(src0_strides, 4) && + are_strides_plain(src1_strides, 4)) { + src0_dims[1] *= dst_tz[0]; + src1_dims[1] *= dst_tz[0]; + dst_tz[1] *= dst_tz[0]; + dst_tz.erase(dst_tz.begin()); + src0_md = src0_md.reshape({src0_dims.begin() + 1, src0_dims.end()}); + src1_md = src1_md.reshape({src1_dims.begin() + 1, src1_dims.end()}); + use_broadcasting_hack = true; + } + } + + auto dst_md = + memory::desc(dst_tz, OneDNNGetDataType(), OneDNNMemoryFormat::any); + + if (x->numel() < y->numel()) { + if (algo == dnnl::algorithm::binary_sub) { + attributes = CreateAttributes( + algo, -1.0 * scale_x, -1.0 * scale_y, scale_out, post_ops); + } + this->AcquireForwardPrimitiveDescriptor( + attributes, algo, src1_md, src0_md, dst_md); + } else { + this->AcquireForwardPrimitiveDescriptor( + attributes, algo, src0_md, src1_md, dst_md); + } + } + std::shared_ptr AcquireSecondSrcMemory( + const DenseTensor* input) { + const T* input_data = input->data(); + return this->AcquireMemoryFromPrimitive(this->fwd_pd_->src1_desc(), + to_void_cast(input_data)); + } + + private: + static inline dnnl::primitive_attr CreateAttributes( + dnnl::algorithm op, + float scale_x, + float scale_y, + float scale_out, + dnnl::post_ops post_ops = dnnl::post_ops{}) { + // Scales set in attributes for inputs contibute to the output equation + // in the following way (assuming no broadcasting takes place): + // output_i = scale_0 * x_i <+ or *> scale_1 * y_i; + // Hence we have to create scales that will: + // 1. Dequantize both values, by multiplying with (1.0 / scale_x_or_y) + // 2. Quantize their result to output scale range, by multiplying with + // (scale_z) + // If we combine these two, we end up with following equation + // output = scale_out * (1/scale_x * x <* or +> 1/scale_y * y) + // Hence, to mimic such behaviour using provided interface, + // For add operation the equation is equal to: + // output = (scale_out / scale_x) * x + (scale_out / scale_y) * y + // + // For mul operation on the other hand + // output = (scale_out / scale_x) * x * (1.0 / scale_y) * y + // + float scale_0 = scale_out / scale_x; + float scale_1 = + op == dnnl::algorithm::binary_add ? scale_out / scale_y : 1.0 / scale_y; + dnnl::primitive_attr attributes; + attributes.set_scales( + /* input_x_id = */ DNNL_ARG_SRC_0, /* mask = */ 0, {scale_0}); + attributes.set_scales( + /* input_y_id = */ DNNL_ARG_SRC_1, /* mask = */ 0, {scale_1}); + if (post_ops.len() > 0) attributes.set_post_ops(post_ops); + return attributes; + } +}; + +template +class BroadcastDataOneDNNHandler + : public OneDNNHandlerNoCachingT { + public: + BroadcastDataOneDNNHandler(const dnnl::algorithm algo, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x, + DenseTensor* out, + float scale_x, + float scale_y, + const std::vector& extended_x_dims) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + const auto src0_tz = vectorize(out->dims()); + const auto src0_md = dnnl::memory::desc( + src0_tz, OneDNNGetDataType(), GetPlainOneDNNFormat(src0_tz.size())); + const auto src1_md = x->mem_desc().reshape(extended_x_dims); + + dnnl::primitive_attr attributes; + attributes.set_scales(DNNL_ARG_SRC_0, 0, {scale_x}); + attributes.set_scales(DNNL_ARG_SRC_1, 0, {scale_y}); + + this->AcquireForwardPrimitiveDescriptor( + attributes, algo, src0_md, src1_md, src0_md); + } + + template + std::shared_ptr AcquireZeroedDstMemory(DenseTensor* out) { + T_out* ptr = out->mutable_data(this->place_, + this->fwd_pd_->dst_desc().get_size()); + memset(ptr, 0, this->fwd_pd_->dst_desc().get_size()); + return this->AcquireMemoryFromPrimitive(this->fwd_pd_->dst_desc(), ptr); + } +}; + +template +class ReductionOneDNNHandler + : public OneDNNHandlerNoCachingT { + public: + ReductionOneDNNHandler(const dnnl::algorithm algo, + const float p, + const float eps, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x, + const DenseTensor* out, + std::vector out_tz, + const dnnl::primitive_attr& attrs = NULL) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + const auto out_md = memory::desc( + out_tz, OneDNNGetDataType(), dnnl::memory::format_tag::any); + + if (attrs) + this->AcquireForwardPrimitiveDescriptor( + attrs, algo, x->mem_desc(), out_md, p, eps); + else + this->AcquireForwardPrimitiveDescriptor( + algo, x->mem_desc(), out_md, p, eps); + } +}; + +template +class ClipOneDNNHandler + : public OneDNNHandlerNoCachingT { + public: + ClipOneDNNHandler(const Scalar& min, + const Scalar& max, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + float alpha = min.to(); + float beta = max.to(); + + this->AcquireForwardPrimitiveDescriptor(dnnl::prop_kind::forward_training, + dnnl::algorithm::eltwise_clip_v2, + x->mem_desc(), + alpha, + beta); + } + + ClipOneDNNHandler(const Scalar& min, + const Scalar& max, + const dnnl::engine engine, + Place cpu_place, + const DenseTensor* x, + const DenseTensor* dout) + : OneDNNHandlerNoCachingT(engine, cpu_place) { + float alpha = min.to(); + float beta = max.to(); + + this->AcquireForwardPrimitiveDescriptor(dnnl::prop_kind::forward_training, + dnnl::algorithm::eltwise_clip_v2, + x->mem_desc(), + alpha, + beta); + this->AcquireBackwardPrimitiveDescriptor(dnnl::algorithm::eltwise_clip_v2, + dout->mem_desc(), + x->mem_desc(), + alpha, + beta); + } + std::shared_ptr AcquireBackwardSrcMemory( + const DenseTensor* input) { + const T* input_data = input->data(); + return this->AcquireMemoryFromPrimitive(this->bwd_pd_->src_desc(), + to_void_cast(input_data)); + } +}; +template +class TransposeOneDNNHandler { + public: + TransposeOneDNNHandler(const OneDNNContext& dev_ctx, + std::vector& dims, // NOLINT + std::vector& axis, // NOLINT + dnnl::engine engine) + : dev_ctx_(dev_ctx), + dims_(dims), + axis_(axis), + logical_axis_(dims.size(), 0), + engine_(engine) {} + + std::shared_ptr AcquireSrcMemory(const OneDNNMemoryFormat& fmt, + void* ptr) { + // Make memory descriptor using input format, unless it + // cannot be trusted (nchw) then make up memory fmt manually + for (size_t i = 0; i < this->logical_axis_.size(); ++i) { + this->logical_axis_[i] = i; + } + + auto src_md = fmt != OneDNNMemoryFormat::nchw + ? OneDNNMemDesc(dims_, OneDNNGetDataType(), fmt) + : Axis2MemoryDesc(dims_, logical_axis_); + return std::make_shared(src_md, engine_, ptr); + } + + std::shared_ptr AcquireDstMemory(DenseTensor* output, + Place place) { + auto dst_md = Axis2MemoryDesc(dims_, axis_); + auto dst_data = dev_ctx_.Alloc(output); + return std::make_shared(dst_md, engine_, dst_data); + } + + std::shared_ptr AcquireTranspose( + std::shared_ptr dst_memory_p, + std::shared_ptr src_memory_p) { + return std::make_shared(*(src_memory_p), *(dst_memory_p)); + } + + protected: + dnnl::memory::desc Axis2MemoryDesc(std::vector& nchw_tz, // NOLINT + std::vector& axis // NOLINT + ) { + size_t ndims = axis.size(); + + std::vector strides(ndims); + unsigned int total_stride = 1; + for (int i = ndims - 1; i >= 0; --i) { + strides[axis[i]] = total_stride; + total_stride *= nchw_tz[axis[i]]; + } + dnnl::memory::desc mem_d(nchw_tz, OneDNNGetDataType(), strides); + + return mem_d; + } + + private: + const OneDNNContext& dev_ctx_; + std::vector dims_; + std::vector axis_; + std::vector logical_axis_; + dnnl::engine engine_; +}; +} // namespace funcs +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/stream.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..d1578c90ec1a97f51646dd206d48df3146c35cee --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/stream.h @@ -0,0 +1,79 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/backends/callback_manager.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/macros.h" + +namespace phi { + +class Device; + +namespace event { +class Event; +} // namespace event + +namespace stream { +using stream_t = void*; +class Stream { + public: + enum class Priority : uint8_t { + kNull = 0x0, + kHigh = 0x1, + kNormal = 0x2, + }; + + enum class Flag : uint8_t { + kDefaultFlag = 0x0, + kStreamNonBlocking = 0x1, + }; + + using Callback = std::function; + + Stream() = default; + // For compatiable + Stream(const Place& place, stream_t stream); + ~Stream(); + const stream_t& raw_stream() const; + void set_stream(stream_t stream); + bool Init(const Place& place, + const Priority& priority = Priority::kNormal, + const Flag& flag = Flag::kDefaultFlag); + template + void AddCallback(Callback&& callback) const { + callback_manager_->AddCallback(callback); + } + void RecordEvent(event::Event* event, Callback callback) const; + void RecordEvent(event::Event* event) const; + void WaitEvent(event::Event* event) const; + void Wait() const; + void WaitCallback() const; + void Destroy(); + bool Query() const; + void Synchronize() const; + const Place& GetPlace() const; + + private: + DISABLE_COPY_AND_ASSIGN(Stream); + Place place_; + Device* device_; + stream_t stream_; + std::unique_ptr callback_manager_; + bool own_data_ = true; +}; + +} // namespace stream +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/enforce_xpu.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/enforce_xpu.h new file mode 100644 index 0000000000000000000000000000000000000000..44763d408f7d784d13ab8d7cb18f273f62f853d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/enforce_xpu.h @@ -0,0 +1,212 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/fluid/platform/enforce.h" +#include "paddle/phi/backends/xpu/xpu_header.h" +#ifdef PADDLE_WITH_XPU_BKCL +#include "xpu/bkcl.h" +#endif + +namespace phi { +namespace backends { +namespace xpu { + +// Note: XPU runtime api return int, not XPUError_t +inline const char* xpuGetErrorString(int stat) { + switch (stat) { + case XPU_SUCCESS: + return "Success"; + case XPUERR_INVALID_DEVICE: + return "Invalid XPU device"; + case XPUERR_UNINIT: + return "XPU runtime not properly inited"; + case XPUERR_NOMEM: + return "Device memory not enough"; + case XPUERR_NOCPUMEM: + return "CPU memory not enough"; + case XPUERR_INVALID_PARAM: + return "Invalid parameter"; + case XPUERR_NOXPUFUNC: + return "Cannot get XPU Func"; + case XPUERR_LDSO: + return "Error loading dynamic library"; + case XPUERR_LDSYM: + return "Error loading func from dynamic library"; + case XPUERR_SIMULATOR: + return "Error from XPU Simulator"; + case XPUERR_NOSUPPORT: + return "Operation not supported"; + case XPUERR_ABNORMAL: + return "Device abnormal due to previous error"; + case XPUERR_KEXCEPTION: + return "Exception in kernel execution"; + case XPUERR_TIMEOUT: + return "Kernel execution timed out"; + case XPUERR_BUSY: + return "Resource busy"; + case XPUERR_USEAFCLOSE: + return "Use a stream after closed"; + case XPUERR_UCECC: + return "Uncorrectable ECC"; + case XPUERR_OVERHEAT: + return "Overheat"; + case XPUERR_UNEXPECT: + return "Execution error, reach unexpected control flow"; + case XPUERR_DEVRESET: + return "Device is being reset, try again later"; + case XPUERR_HWEXCEPTION: + return "Hardware module exception"; + case XPUERR_HBM_INIT: + return "Error init HBM"; + case XPUERR_DEVINIT: + return "Error init device"; + case XPUERR_PEERRESET: + return "Device is being reset, try again later"; + case XPUERR_MAXDEV: + return "Device count exceed limit"; + case XPUERR_NOIOC: + return "Unknown IOCTL command"; + case XPUERR_DMATIMEOUT: + return "DMA timed out, a reboot maybe needed"; + case XPUERR_DMAABORT: + return "DMA aborted due to error, possibly wrong address or hardware " + "state"; + case XPUERR_MCUUNINIT: + return "Firmware not initialized"; + case XPUERR_OLDFW: + return "Firmware version too old (<15), please update."; + case XPUERR_PCIE: + return "Error in PCIE"; + case XPUERR_FAULT: + return "Error copy between kernel and user space"; + case XPUERR_INTERRUPTED: + return "Execution interrupted by user"; + default: + return "unkonwn error"; + } +} + +#ifdef PADDLE_WITH_XPU_BKCL +inline const char* bkclGetErrorString(BKCLResult_t stat) { + switch (stat) { + case BKCL_SUCCESS: + return "BKCL_SUCCESS"; + case BKCL_INVALID_ARGUMENT: + return "BKCL_INVALID_ARGUMENT"; + case BKCL_RUNTIME_ERROR: + return "BKCL_RUNTIME_ERROR"; + case BKCL_SYSTEM_ERROR: + return "BKCL_SYSTEM_ERROR"; + case BKCL_INTERNAL_ERROR: + return "BKCL_INTERNAL_ERROR"; + default: + return "Unknown BKCL status"; + } +} +#endif + +inline const char* xdnnGetErrorString(int stat) { + switch (stat) { + case baidu::xpu::api::Error_t::SUCCESS: + return "XDNN_SUCCESS"; + case baidu::xpu::api::Error_t::INVALID_PARAM: + return "XDNN_INVALID_PARAM"; + case baidu::xpu::api::Error_t::RUNTIME_ERROR: + return "XDNN_RUNTIME_ERROR"; + case baidu::xpu::api::Error_t::NO_ENOUGH_WORKSPACE: + return "XDNN_NO_ENOUGH_WORKSPACE"; + case baidu::xpu::api::Error_t::NOT_IMPLEMENT: + return "XDNN_NOT_IMPLEMENT"; + default: + return "Unknown XDNN status"; + } +} + +inline std::string build_xpu_error_msg(int stat) { + std::string msg("XPU Error <" + std::to_string(stat) + ">, "); + return msg + xpuGetErrorString(stat) + " "; +} + +#ifdef PADDLE_WITH_XPU_BKCL +inline std::string build_xpu_error_msg(BKCLResult_t stat) { + std::string msg("BKCL Error, "); + return msg + bkclGetErrorString(stat) + " "; +} +#endif + +inline std::string build_xpu_xdnn_error_msg(int stat, std::string msg) { + return msg + " XDNN Error, " + xdnnGetErrorString(stat) + " "; +} + +namespace details { + +template +struct ExternalApiType {}; + +#define DEFINE_EXTERNAL_API_TYPE(type, success_value) \ + template <> \ + struct ExternalApiType { \ + using Type = type; \ + static constexpr Type kSuccess = success_value; \ + } + +DEFINE_EXTERNAL_API_TYPE(int, XPU_SUCCESS); +#ifdef PADDLE_WITH_XPU_BKCL +DEFINE_EXTERNAL_API_TYPE(BKCLResult_t, BKCL_SUCCESS); +#endif + +#undef DEFINE_EXTERNAL_API_TYPE + +} // namespace details + +#define PADDLE_ENFORCE_XPU_SUCCESS(COND) \ + do { \ + auto __cond__ = (COND); \ + using __XPU_STATUS_TYPE__ = decltype(__cond__); \ + constexpr auto __success_type__ = \ + ::phi::backends::xpu::details::ExternalApiType< \ + __XPU_STATUS_TYPE__>::kSuccess; \ + if (UNLIKELY(__cond__ != __success_type__)) { \ + auto __summary__ = phi::errors::External( \ + ::phi::backends::xpu::build_xpu_error_msg(__cond__)); \ + __THROW_ERROR_INTERNAL__(__summary__); \ + } \ + } while (0) + +#define PADDLE_ENFORCE_XDNN_SUCCESS(COND, MSG) \ + do { \ + auto __cond__ = (COND); \ + if (UNLIKELY(__cond__ != baidu::xpu::api::Error_t::SUCCESS)) { \ + auto __summary__ = phi::errors::External( \ + ::phi::backends::xpu::build_xpu_xdnn_error_msg(__cond__, MSG)); \ + __THROW_ERROR_INTERNAL__(__summary__); \ + } \ + } while (0) + +#define PADDLE_ENFORCE_XDNN_NOT_NULL(ptr) \ + do { \ + if (UNLIKELY(ptr == nullptr)) { \ + auto __summary__ = phi::errors::External( \ + ::phi::backends::xpu::build_xpu_xdnn_error_msg( \ + baidu::xpu::api::Error_t::NO_ENOUGH_WORKSPACE, \ + "XPU memory is not enough")); \ + __THROW_ERROR_INTERNAL__(__summary__); \ + } \ + } while (0) + +} // namespace xpu +} // namespace backends +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/forwards.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/forwards.h new file mode 100644 index 0000000000000000000000000000000000000000..805a74865b6d8c62019f593160c19cc661962b01 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/forwards.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2022 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. */ + +// Forward-declares. +#pragma once + +// Forward declaration of xpu context. +namespace baidu { +namespace xpu { +namespace api { + +struct Context; +typedef void* BKCLContext_t; + +} // namespace api +} // namespace xpu +} // namespace baidu diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_context.h new file mode 100644 index 0000000000000000000000000000000000000000..90fc7c97b785cdb36c8c8cbe57dcf57f8a7ee13b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_context.h @@ -0,0 +1,81 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +#include "paddle/phi/backends/xpu/forwards.h" +#include "paddle/phi/backends/xpu/xpu_header.h" +#include "paddle/phi/backends/xpu/xpu_info.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/device_context.h" + +namespace xpu = baidu::xpu::api; + +namespace phi { + +class XPUContext : public DeviceContext { + public: + XPUContext(); + + explicit XPUContext(const XPUPlace&); + + virtual ~XPUContext(); + + const Place& GetPlace() const override; + + backends::xpu::XPUVersion xpu_version() const; + + xpu::Context* x_context() const; + + // Return bkcl context. + xpu::BKCLContext_t bkcl_context() const; + void SetBkclContext(xpu::BKCLContext_t context); + + // Wait for all operations completion in the stream. + void Wait() const override; + + public: + // NOTE: DeviceContext hold resources. Used in training scenarios. + // The interface used by the training scene, DeviceContext will initialize + // all resources and delete them when destructing. + void Init(); + + public: + // NOTE: External users manage resources. Used in inference scenarios. + // The Set interface is for inference only, DeviceContext will mark the + // resource as external, and will not delete any resource when destructing. + void SetXContext(xpu::Context*); + + void SetL3Cache(int l3_size = 14155776); + + void SetXPUStream(XPUStream stream); + + XPUStream stream() const; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +// KPS (Kernel PrimitiveS API) needs to exist as a kind of backend, +// because we want to implement a KPS-based kernel and make it run +// on GPU and XPU at the same time, so we need KPSContext when registering +// KPS Kernel. Note: XPU and GPU cannot be compiled at the same time! +#if PADDLE_WITH_XPU_KP +using KPSContext = XPUContext; +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_header.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_header.h new file mode 100644 index 0000000000000000000000000000000000000000..1fe6f6d07796fa60245865906370922a57d3dd2a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_header.h @@ -0,0 +1,55 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#ifdef PADDLE_WITH_XPU +#include +#include +#include + +#include "paddle/fluid/platform/enforce.h" +#include "paddle/phi/common/bfloat16.h" +#include "paddle/phi/common/float16.h" +#include "xpu/runtime.h" +#include "xpu/runtime_ex.h" +#include "xpu/xdnn.h" + +namespace xpu = baidu::xpu::api; + +static std::map XPUAPIErrorMsg = { + {xpu::Error_t::SUCCESS, "xpu api success"}, + {xpu::Error_t::INVALID_PARAM, "xpu api invalid param"}, + {xpu::Error_t::RUNTIME_ERROR, "xpu api runtime error"}, + {xpu::Error_t::NO_ENOUGH_WORKSPACE, "xpu api no enough workspace"}}; + +template +class XPUTypeTrait { + public: + using Type = T; +}; + +template <> +class XPUTypeTrait { + public: + using Type = float16; +}; + +template <> +class XPUTypeTrait { + public: + using Type = bfloat16; +}; + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_info.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_info.h new file mode 100644 index 0000000000000000000000000000000000000000..9d5f073eaa8e62841c63b48fa32648ba0452c6a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/backends/xpu/xpu_info.h @@ -0,0 +1,95 @@ +/* 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. */ +#pragma once + +#include +#include + +#include "paddle/phi/common/place.h" + +namespace phi { + +class XPUContext; + +namespace backends { +namespace xpu { + +/***** Version Management *****/ + +//! Get the version of XPU Driver +int GetDriverVersion(); + +//! Get the version of XPU Runtime +int GetRuntimeVersion(); + +/***** Device Management *****/ + +//! Get the total number of XPU devices in system. +int GetXPUDeviceCount(); + +//! Set the XPU device id for next execution. +void SetXPUDeviceId(int device_id); + +//! Get the current XPU device id in system. +int GetXPUCurrentDeviceId(); + +//! Get a list of device ids from environment variable or use all. +std::vector GetXPUSelectedDevices(); + +/***** Memory Management *****/ + +//! Copy memory from address src to dst synchronously. +void MemcpySyncH2D(void *dst, + const void *src, + size_t count, + const phi::XPUPlace &dst_place, + const phi::XPUContext &dev_ctx); +void MemcpySyncD2H(void *dst, + const void *src, + size_t count, + const phi::XPUPlace &src_place, + const phi::XPUContext &dev_ctx); +void MemcpySyncD2D(void *dst, + const phi::XPUPlace &dst_place, + const void *src, + const phi::XPUPlace &src_place, + size_t count, + const phi::XPUContext &dev_ctx); + +class XPUDeviceGuard { + public: + explicit inline XPUDeviceGuard(int dev_id) { + int prev_id = GetXPUCurrentDeviceId(); + if (prev_id != dev_id) { + prev_id_ = prev_id; + SetXPUDeviceId(dev_id); + } + } + + inline ~XPUDeviceGuard() { + if (prev_id_ != -1) { + SetXPUDeviceId(prev_id_); + } + } + + XPUDeviceGuard(const XPUDeviceGuard &o) = delete; + XPUDeviceGuard &operator=(const XPUDeviceGuard &o) = delete; + + private: + int prev_id_{-1}; +}; + +enum XPUVersion { XPU1, XPU2 }; +XPUVersion get_xpu_version(int dev_id); + +} // namespace xpu +} // namespace backends +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/all.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/all.h new file mode 100644 index 0000000000000000000000000000000000000000..5bd31cafdf977426ea8ad4d4047df52275042e13 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/all.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" +#include "paddle/phi/capi/include/c_device_context.h" +#include "paddle/phi/capi/include/c_int_array.h" +#include "paddle/phi/capi/include/c_kernel_context.h" +#include "paddle/phi/capi/include/c_kernel_factory.h" +#include "paddle/phi/capi/include/c_kernel_registry.h" +#include "paddle/phi/capi/include/c_place.h" +#include "paddle/phi/capi/include/c_scalar.h" +#include "paddle/phi/capi/include/c_tensor.h" +#include "paddle/phi/capi/include/data_type.h" +#include "paddle/phi/capi/include/kernel_registry.h" + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/capi.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/capi.h new file mode 100644 index 0000000000000000000000000000000000000000..f8e5a90ddf883f21c771399d89790d37ac807571 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/capi.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/common.h" + +PD_DECLARE_CAPI(data_type); +PD_DECLARE_CAPI(device_context); +PD_DECLARE_CAPI(int_array); +PD_DECLARE_CAPI(kernel_context); +PD_DECLARE_CAPI(kernel_factory); +PD_DECLARE_CAPI(kernel_registry); +PD_DECLARE_CAPI(place); +PD_DECLARE_CAPI(scalar); +PD_DECLARE_CAPI(tensor); + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_data_type.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..e33d04705206c4e765bfc52711f34831d21bd606 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_data_type.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include + +#include "paddle/phi/backends/device_ext.h" +#include "paddle/phi/common/bfloat16.h" +#include "paddle/phi/common/complex.h" +#include "paddle/phi/common/float16.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef C_Status PD_Status; + +typedef C_DataType PD_DataType; + +typedef C_DataLayout PD_DataLayout; + +typedef struct { + size_t size; + void *data; +} PD_List; + +void PD_DeletePointerList(PD_List list); + +void PD_DeleteUInt8List(PD_List list); + +void PD_DeleteInt64List(PD_List list); + +void PD_DeleteInt32List(PD_List list); + +void PD_DeleteFloat64List(PD_List list); + +void PD_DeleteFloat32List(PD_List list); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_device_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_device_context.h new file mode 100644 index 0000000000000000000000000000000000000000..68621d58ad9d5786d8763f0a9f226e73c806679a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_device_context.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" +#include "paddle/phi/capi/include/c_tensor.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_DeviceContext PD_DeviceContext; + +typedef C_Stream PD_Stream; + +PD_Stream PD_DeviceContextGetStream(const PD_DeviceContext *ctx, + PD_Status *status); + +void *PD_DeviceContextAllocateTensor(const PD_DeviceContext *ctx, + PD_Tensor *tensor, + size_t size, + PD_DataType dtype, + PD_Status *status); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_int_array.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_int_array.h new file mode 100644 index 0000000000000000000000000000000000000000..dbc13b3abea4f257d12847dfdfe00174f889de09 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_int_array.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_IntArray PD_IntArray; + +PD_List PD_IntArrayGetDataPointer(PD_IntArray *int_array); + +size_t PD_IntArrayGetElementCount(PD_IntArray *int_array); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_context.h new file mode 100644 index 0000000000000000000000000000000000000000..a5524e3aee2785296e8d20dca2ed3fc9a97fc2c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_context.h @@ -0,0 +1,113 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" +#include "paddle/phi/capi/include/c_device_context.h" +#include "paddle/phi/capi/include/c_int_array.h" +#include "paddle/phi/capi/include/c_place.h" +#include "paddle/phi/capi/include/c_scalar.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_KernelContext PD_KernelContext; + +/** + * KernelContext + */ + +PD_DeviceContext *PD_KernelContextGetDeviceContext(PD_KernelContext *ctx); + +PD_Tensor *PD_KernelContextInputAt(PD_KernelContext *ctx, size_t index); + +// PD_Tensor *PD_KernelContextOptionalInputAt(PD_KernelContext *ctx, size_t +// index); + +PD_List PD_KernelContextMultiInputAt(PD_KernelContext *ctx, size_t index); + +PD_Tensor *PD_KernelContextOutputAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextMultiOutputAt(PD_KernelContext *ctx, size_t index); + +/** + * Attribute + */ + +bool PD_KernelContextBoolAttrAt(PD_KernelContext *ctx, size_t index); + +int32_t PD_KernelContextInt32AttrAt(PD_KernelContext *ctx, size_t index); + +int64_t PD_KernelContextInt64AttrAt(PD_KernelContext *ctx, size_t index); + +float PD_KernelContextFloatAttrAt(PD_KernelContext *ctx, size_t index); + +double PD_KernelContextDoubleAttrAt(PD_KernelContext *ctx, size_t index); + +PD_Scalar *PD_KernelContextScalarAttrAt(PD_KernelContext *ctx, size_t index); + +PD_IntArray *PD_KernelContextIntArrayAttrAt(PD_KernelContext *ctx, + size_t index); + +PD_DataType PD_KernelContextDataTypeAttrAt(PD_KernelContext *ctx, size_t index); + +PD_DataLayout PD_KernelContextDataLayoutAttrAt(PD_KernelContext *ctx, + size_t index); + +char *PD_KernelContextStringAttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListBoolAttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListInt32AttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListInt64AttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListFloatAttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListDoubleAttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListStringAttrAt(PD_KernelContext *ctx, size_t index); + +PD_List PD_KernelContextListScalarAttrAt(PD_KernelContext *ctx, size_t index); + +PD_Place *PD_KernelContextPlaceAttrAt(PD_KernelContext *ctx, size_t index); + +const char *PD_StringAttr(void *attr); + +PD_DataType PD_DatatTypeAttr(void *attr); + +PD_DataLayout PD_DatatLayoutAttr(void *attr); + +PD_List PD_ListInt32Attr(void *attr); + +PD_List PD_ListInt64Attr(void *attr); + +PD_List PD_ListFloatAttr(void *attr); + +PD_List PD_ListDoubleAttr(void *attr); + +PD_List PD_ListScalarAttr(void *attr); + +PD_List PD_ListStringAttr(void *attr); + +PD_List PD_ListBoolAttr(void *attr); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_factory.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..f84f16ba520110303375418be79cb9d1bbb36fd8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_factory.h @@ -0,0 +1,72 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_KernelKey PD_KernelKey; + +typedef struct PD_Kernel PD_Kernel; + +typedef struct PD_KernelArgsDef PD_KernelArgsDef; + +typedef struct PD_TensorArgDef PD_TensorArgDef; + +/** + * TensorArgDef + */ + +void PD_TensorArgDefSetDataLayout(PD_TensorArgDef *def, + PD_DataLayout layout, + PD_Status *status); + +void PD_TensorArgDefSetDataType(PD_TensorArgDef *def, + PD_DataType dtype, + PD_Status *status); + +/** + * KernelArgsDef + */ + +PD_List PD_KernelArgsDefGetInputArgDefs(PD_KernelArgsDef *def, + PD_Status *status); + +PD_List PD_KernelArgsDefGetOutputArgDefs(PD_KernelArgsDef *def, + PD_Status *status); + +/** + * KernelKey + */ + +PD_DataLayout PD_KernelKeyGetLayout(PD_KernelKey *key, PD_Status *status); + +PD_DataType PD_KernelKeyGetDataType(PD_KernelKey *key, PD_Status *status); + +/** + * Kernel + */ + +PD_KernelArgsDef *PD_KernelGetArgsDef(PD_Kernel *kernel, PD_Status *status); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_registry.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..04990be436be95ddb314064c64d5770a9b9f3f97 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_kernel_registry.h @@ -0,0 +1,77 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include + +#include "paddle/phi/capi/include/c_data_type.h" +#include "paddle/phi/capi/include/c_kernel_context.h" +#include "paddle/phi/capi/include/c_kernel_factory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PD_ARG_TYPE_CONTEXT = 0, + PD_ARG_TYPE_TENSOR, + PD_ARG_TYPE_BOOL, + PD_ARG_TYPE_BFLOAT16, + PD_ARG_TYPE_FLOAT16, + PD_ARG_TYPE_FLOAT32, + PD_ARG_TYPE_FLOAT64, + PD_ARG_TYPE_INT32, + PD_ARG_TYPE_INT64, + PD_ARG_TYPE_STRING, + PD_ARG_TYPE_SCALAR, + PD_ARG_TYPE_INT_ARRAY, + PD_ARG_TYPE_DATA_TYPE, + PD_ARG_TYPE_DATA_LAYOUT, + PD_ARG_TYPE_PLACE, + PD_ARG_TYPE_LIST_BOOL, + PD_ARG_TYPE_LIST_INT32, + PD_ARG_TYPE_LIST_INT64, + PD_ARG_TYPE_LIST_BFLOAT16, + PD_ARG_TYPE_LIST_FLOAT16, + PD_ARG_TYPE_LIST_FLOAT32, + PD_ARG_TYPE_LIST_FLOAT64, + PD_ARG_TYPE_LIST_STRING, + PD_ARG_TYPE_LIST_SCALAR, + PD_ARG_TYPE_OPTIONAL_TENSOR, + PD_ARG_TYPE_LIST_TENSOR, + PD_ARG_TYPE_OPTIONAL_MULTI_TENSOR, +} PD_KernelArgumentType; + +void PD_RegisterPhiKernel(const char *kernel_name_cstr, + const char *backend_cstr, + PD_DataType pd_dtype, + PD_DataLayout pd_layout, + size_t in_nargs, + PD_KernelArgumentType *in_args_type, + size_t attr_nargs, + PD_KernelArgumentType *attr_args_type, + size_t out_nargs, + PD_KernelArgumentType *out_args_type, + void (*args_def_fn)(const PD_KernelKey *, + PD_Kernel *), + void (*fn)(PD_KernelContext *), + void *variadic_kernel_fn); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_place.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_place.h new file mode 100644 index 0000000000000000000000000000000000000000..bbdc45cbe8d46e4e830ed310d2008058b22aaaf7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_place.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_Place PD_Place; + +bool PD_PlaceIsHost(PD_Place *place); + +int8_t PD_PlaceGetDeviceId(PD_Place *place); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_scalar.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea3c3fc12c65c2590ce738a733a519a06982fd9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_scalar.h @@ -0,0 +1,54 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_Scalar PD_Scalar; + +bool PD_ScalarGetBoolData(PD_Scalar *scalar); + +int8_t PD_ScalarGetInt8Data(PD_Scalar *scalar); + +int16_t PD_ScalarGetInt16Data(PD_Scalar *scalar); + +int32_t PD_ScalarGetInt32Data(PD_Scalar *scalar); + +int64_t PD_ScalarGetInt64Data(PD_Scalar *scalar); + +uint8_t PD_ScalarGetUInt8Data(PD_Scalar *scalar); + +uint16_t PD_ScalarGetUInt16Data(PD_Scalar *scalar); + +uint32_t PD_ScalarGetUInt32Data(PD_Scalar *scalar); + +uint64_t PD_ScalarGetUInt64Data(PD_Scalar *scalar); + +float PD_ScalarGetFloat32Data(PD_Scalar *scalar); + +double PD_ScalarGetFloat64Data(PD_Scalar *scalar); + +PD_DataType PD_ScalarGetDataType(PD_Scalar *scalar); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..2bebee977740b0dd9666aa2da6ce65ed084c862f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/c_tensor.h @@ -0,0 +1,92 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PD_Tensor PD_Tensor; + +PD_DataType PD_TensorGetPDDataType(const PD_Tensor *tensor, PD_Status *status); + +PD_DataLayout PD_TensorGetDataLayout(const PD_Tensor *tensor, + PD_Status *status); + +int64_t PD_TensorGetByteSize(const PD_Tensor *tensor, PD_Status *status); + +void *PD_TensorGetDataPointer(const PD_Tensor *tensor, PD_Status *status); + +int64_t PD_TensorGetElementCount(const PD_Tensor *tensor, PD_Status *status); + +int64_t PD_TensorGetNumDims(const PD_Tensor *tensor, PD_Status *status); + +int64_t PD_TensorGetDim(const PD_Tensor *tensor, + size_t index, + PD_Status *status); + +void PD_TensorGetLoD(const PD_Tensor *tensor, + PD_List *data, + PD_List *offset, + PD_Status *status); + +bool PD_TensorIsInitialized(const PD_Tensor *tensor, PD_Status *status); + +bool PD_TensorIsValid(const PD_Tensor *tensor, PD_Status *status); + +void *PD_TensorGetHolder(const PD_Tensor *tensor, PD_Status *status); + +void PD_TensorSetDims(PD_Tensor *tensor, + int64_t ndims, + const int64_t *dims, + PD_Status *status); + +void PD_TensorSetDataType(PD_Tensor *tensor, + PD_DataType dtype, + PD_Status *status); + +void PD_TensorSetDataLayout(PD_Tensor *tensor, + PD_DataLayout layout, + PD_Status *status); + +void PD_TensorResetLoD(PD_Tensor *tensor, + PD_List data, + PD_List offset, + PD_Status *status); + +PD_Tensor *PD_NewTensor(); + +void PD_DeleteTensor(PD_Tensor *tensor); + +void PD_TensorShareDataWith(PD_Tensor *dst, + const PD_Tensor *src, + PD_Status *status); + +void PD_TensorShareLoDWith(PD_Tensor *dst, + const PD_Tensor *src, + PD_Status *status); + +PD_Tensor *PD_OptionalTensorGetPointer(PD_Tensor *tensor); + +PD_List PD_TensorVectorToList(PD_Tensor *tensor); + +#ifdef __cplusplus +} // extern "C" +#endif +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/common.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/common.h new file mode 100644 index 0000000000000000000000000000000000000000..2d2bc231f479bf32f86dab250488baed7a240053 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/common.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 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. + +#pragma once +#if !defined(_WIN32) && !defined(__APPLE__) + +#define PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \ + _PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) + +#define _PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \ + struct __test_global_namespace_##uniq_name##__ {}; \ + static_assert(std::is_same<::__test_global_namespace_##uniq_name##__, \ + __test_global_namespace_##uniq_name##__>::value, \ + msg) + +#define PD_DECLARE_CAPI(module_name) \ + PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_DECLARE_tp_kernel_ns_check_##module_name##_, \ + "PD_DECLARE_KERNEL must be called in global namespace."); \ + extern int TouchCAPISymbolFor##module_name##_(); \ + UNUSED static int __declare_capi_symbol_for_##module_name##_ = \ + TouchCAPISymbolFor##module_name##_() + +#define PD_REGISTER_CAPI(module_name) \ + PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_DECLARE_tp_kernel_ns_check_##module_name##_, \ + "PD_DECLARE_KERNEL must be called in global namespace."); \ + int TouchCAPISymbolFor##module_name##_() { return 0; } + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/data_type.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..6acbf026e8cb6bd37d53817fb6e555dfd0b76be5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/data_type.h @@ -0,0 +1,64 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" + +namespace phi { + +namespace capi { + +#define CPP_TYPE_TO_PD_DTYPE_REGISTER(_) \ + _(bool, PD_DataType::BOOL) \ + _(phi::dtype::bfloat16, PD_DataType::BFLOAT16) \ + _(phi::dtype::float16, PD_DataType::FLOAT16) \ + _(float, PD_DataType::FLOAT32) \ + _(double, PD_DataType::FLOAT64) \ + _(uint8_t, PD_DataType::UINT8) \ + _(uint16_t, PD_DataType::UINT16) \ + _(uint32_t, PD_DataType::UINT32) \ + _(uint64_t, PD_DataType::UINT64) \ + _(int8_t, PD_DataType::INT8) \ + _(int16_t, PD_DataType::INT16) \ + _(int32_t, PD_DataType::INT32) \ + _(int64_t, PD_DataType::INT64) + +template +struct CppTypeToPDType; + +#define CPP_TYPE_TO_PD_DTYPE(x, y) \ + template <> \ + struct CppTypeToPDType { \ + constexpr static PD_DataType Type() { return y; } \ + }; + +template +struct PDTypeToCppType; + +#define PD_DTYPE_TO_CPP_TYPE(x, y) \ + template <> \ + struct PDTypeToCppType { \ + using type = x; \ + }; + +CPP_TYPE_TO_PD_DTYPE_REGISTER(CPP_TYPE_TO_PD_DTYPE) +CPP_TYPE_TO_PD_DTYPE_REGISTER(PD_DTYPE_TO_CPP_TYPE) + +} // namespace capi +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_registry.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..47ddc0bf5be7ec532c4cbe3082913ec49172b7c6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_registry.h @@ -0,0 +1,460 @@ +// Copyright (c) 2022 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. + +#pragma once +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/wrapper_base.h" + +namespace phi { +namespace capi { +// eager mode +inline std::vector PD_TensorVector(PD_Tensor *tensor) { + std::vector ret; + auto list = PD_TensorVectorToList(tensor); + auto data = reinterpret_cast(list.data); + for (size_t i = 0; i < list.size; ++i) { + ret.emplace_back(data[i]); + } + return ret; +} + +inline paddle::optional PD_OptionalTensor( + PD_Tensor *tensor) { + auto ptr = PD_OptionalTensorGetPointer(tensor); + return ptr ? paddle::optional( + phi::capi::DenseTensor(ptr)) + : paddle::optional(paddle::none); +} + +template +inline T PD_Attr(void *attr) { + return *reinterpret_cast(attr); +} + +template <> +inline std::string PD_Attr(void *attr) { + return PD_StringAttr(attr); +} + +template <> +inline PD_DataType PD_Attr(void *attr) { + return PD_DatatTypeAttr(attr); +} + +template <> +inline PD_DataLayout PD_Attr(void *attr) { + return PD_DatatLayoutAttr(attr); +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto list = PD_ListInt32Attr(attr); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto list = PD_ListInt64Attr(attr); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto list = PD_ListFloatAttr(attr); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto list = PD_ListDoubleAttr(attr); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline phi::capi::Scalar PD_Attr(void *attr) { + return phi::capi::Scalar(reinterpret_cast(attr)); +} + +template <> +inline phi::capi::IntArray PD_Attr(void *attr) { + return phi::capi::IntArray(reinterpret_cast(attr)); +} + +template <> +inline phi::capi::Place PD_Attr(void *attr) { + return phi::capi::Place(reinterpret_cast(attr)); +} + +template <> +inline std::vector PD_Attr>( + void *attr) { + auto c_list = PD_ListScalarAttr(attr); + auto data = reinterpret_cast(c_list.data); + std::vector list; + for (size_t i = 0; i < c_list.size; ++i) { + list.emplace_back(data[i]); + } + PD_DeletePointerList(c_list); + return list; +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto c_list = PD_ListStringAttr(attr); + auto data = reinterpret_cast(c_list.data); + std::vector list; + for (size_t i = 0; i < c_list.size; ++i) { + list.emplace_back(data[i]); + } + PD_DeletePointerList(c_list); + return list; +} + +template <> +inline std::vector PD_Attr>(void *attr) { + auto c_list = PD_ListBoolAttr(attr); + std::vector list; + auto data = reinterpret_cast(c_list.data); + for (size_t i = 0; i < c_list.size; ++i) { + list[i] = static_cast(data[i]); + } + PD_DeleteUInt8List(c_list); + return list; +} +// +inline phi::capi::DeviceContext PD_GetDeviceContext(PD_KernelContext *ctx) { + return phi::capi::DeviceContext(PD_KernelContextGetDeviceContext(ctx)); +} + +inline phi::capi::DenseTensor PD_InputAt(PD_KernelContext *ctx, size_t index) { + return phi::capi::DenseTensor(PD_KernelContextInputAt(ctx, index)); +} + +inline paddle::optional PD_OptionalInputAt( + PD_KernelContext *ctx, size_t index) { + auto tensor = PD_KernelContextInputAt(ctx, index); + return tensor + ? paddle::optional(phi::capi::DenseTensor( + reinterpret_cast(tensor))) + : paddle::optional(paddle::none); +} + +inline std::vector PD_MultiInputAt( + PD_KernelContext *ctx, size_t index) { + std::vector ret; + auto list = PD_KernelContextMultiInputAt(ctx, index); + auto data = reinterpret_cast(list.data); + for (size_t i = 0; i < list.size; ++i) { + ret.emplace_back(data[i]); + } + return ret; +} + +inline phi::capi::DenseTensor PD_OutputAt(PD_KernelContext *ctx, size_t index) { + return phi::capi::DenseTensor(PD_KernelContextOutputAt(ctx, index)); +} + +inline std::vector PD_MultiOutputAt( + PD_KernelContext *ctx, size_t index) { + std::vector ret; + auto list = PD_KernelContextMultiOutputAt(ctx, index); + auto data = reinterpret_cast(list.data); + for (size_t i = 0; i < list.size; ++i) { + ret.emplace_back(data[i]); + } + return ret; +} + +template +inline std::vector PD_GetPointerVector(std::vector *vec) { + std::vector ret; + for (auto &item : vec) { + ret.push_back(&item); + } + return ret; +} + +template +inline T PD_AttrAt(PD_KernelContext *ctx, size_t index); + +template <> +inline bool PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextBoolAttrAt(ctx, index); +} + +template <> +inline int32_t PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextInt32AttrAt(ctx, index); +} + +template <> +inline int64_t PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextInt64AttrAt(ctx, index); +} + +template <> +inline float PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextFloatAttrAt(ctx, index); +} + +template <> +inline double PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextDoubleAttrAt(ctx, index); +} + +template <> +inline std::string PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextStringAttrAt(ctx, index); +} + +template <> +inline PD_DataType PD_AttrAt(PD_KernelContext *ctx, size_t index) { + return PD_KernelContextDataTypeAttrAt(ctx, index); +} + +template <> +inline PD_DataLayout PD_AttrAt(PD_KernelContext *ctx, + size_t index) { + return PD_KernelContextDataLayoutAttrAt(ctx, index); +} + +template <> +inline std::vector PD_AttrAt>( + PD_KernelContext *ctx, size_t index) { + auto list = PD_KernelContextListInt32AttrAt(ctx, index); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_AttrAt>( + PD_KernelContext *ctx, size_t index) { + auto list = PD_KernelContextListInt64AttrAt(ctx, index); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_AttrAt>(PD_KernelContext *ctx, + size_t index) { + auto list = PD_KernelContextListFloatAttrAt(ctx, index); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline std::vector PD_AttrAt>(PD_KernelContext *ctx, + size_t index) { + auto list = PD_KernelContextListDoubleAttrAt(ctx, index); + auto data = reinterpret_cast(list.data); + std::vector cc_list(data, data + list.size); + return cc_list; +} + +template <> +inline phi::capi::Scalar PD_AttrAt(PD_KernelContext *ctx, + size_t index) { + auto scalar = PD_KernelContextScalarAttrAt(ctx, index); + return phi::capi::Scalar(scalar); +} + +template <> +inline phi::capi::IntArray PD_AttrAt(PD_KernelContext *ctx, + size_t index) { + auto int_array = PD_KernelContextIntArrayAttrAt(ctx, index); + return phi::capi::IntArray(int_array); +} + +template <> +inline phi::capi::Place PD_AttrAt(PD_KernelContext *ctx, + size_t index) { + auto place = PD_KernelContextPlaceAttrAt(ctx, index); + return phi::capi::Place(place); +} + +template <> +inline std::vector PD_AttrAt>( + PD_KernelContext *ctx, size_t index) { + auto c_list = PD_KernelContextListScalarAttrAt(ctx, index); + auto data = reinterpret_cast(c_list.data); + std::vector list; + for (size_t i = 0; i < c_list.size; ++i) { + list.emplace_back(data[i]); + } + PD_DeletePointerList(c_list); + return list; +} + +template <> +inline std::vector PD_AttrAt>( + PD_KernelContext *ctx, size_t index) { + auto c_list = PD_KernelContextListStringAttrAt(ctx, index); + auto data = reinterpret_cast(c_list.data); + std::vector list; + for (size_t i = 0; i < c_list.size; ++i) { + list.emplace_back(data[i]); + } + PD_DeletePointerList(c_list); + return list; +} + +template <> +inline std::vector PD_AttrAt>(PD_KernelContext *ctx, + size_t index) { + auto c_list = PD_KernelContextListBoolAttrAt(ctx, index); + std::vector list; + auto data = reinterpret_cast(c_list.data); + for (size_t i = 0; i < c_list.size; ++i) { + list[i] = static_cast(data[i]); + } + PD_DeleteUInt8List(c_list); + return list; +} + +#define CPP_TYPE_TO_PD_ARG_TYPE_REGISTER(_) \ + _(phi::capi::DenseTensor, ::PD_KernelArgumentType::PD_ARG_TYPE_TENSOR) \ + _(phi::capi::DeviceContext, ::PD_KernelArgumentType::PD_ARG_TYPE_CONTEXT) \ + _(bool, ::PD_KernelArgumentType::PD_ARG_TYPE_BOOL) \ + _(float, ::PD_KernelArgumentType::PD_ARG_TYPE_FLOAT32) \ + _(double, ::PD_KernelArgumentType::PD_ARG_TYPE_FLOAT64) \ + _(int32_t, ::PD_KernelArgumentType::PD_ARG_TYPE_INT32) \ + _(int64_t, ::PD_KernelArgumentType::PD_ARG_TYPE_INT64) \ + _(PD_DataType, ::PD_KernelArgumentType::PD_ARG_TYPE_DATA_TYPE) \ + _(PD_DataLayout, ::PD_KernelArgumentType::PD_ARG_TYPE_DATA_LAYOUT) \ + _(std::vector, ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT32) \ + _(std::vector, ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT64) \ + _(std::vector, ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT32) \ + _(std::vector, ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT64) \ + _(std::vector, ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_BOOL) \ + _(std::string, ::PD_KernelArgumentType::PD_ARG_TYPE_STRING) \ + _(phi::capi::Scalar, ::PD_KernelArgumentType::PD_ARG_TYPE_SCALAR) \ + _(phi::capi::IntArray, ::PD_KernelArgumentType::PD_ARG_TYPE_INT_ARRAY) \ + _(phi::capi::Place, ::PD_KernelArgumentType::PD_ARG_TYPE_PLACE) \ + _(std::vector, \ + ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_STRING) \ + _(std::vector, \ + ::PD_KernelArgumentType::PD_ARG_TYPE_LIST_SCALAR) + +template +struct CppTypeToPDArgumentType; + +#define CPP_TYPE_TO_PD_ARG_TYPE(x, y) \ + template <> \ + struct CppTypeToPDArgumentType { \ + constexpr static ::PD_KernelArgumentType Type() { return y; } \ + }; + +template <::PD_KernelArgumentType T> +struct PDArgumentTypeToCppType; + +#define PD_ARG_TYPE_TO_CPP_TYPE(x, y) \ + template <> \ + struct PDArgumentTypeToCppType { \ + using type = x; \ + }; + +CPP_TYPE_TO_PD_ARG_TYPE_REGISTER(CPP_TYPE_TO_PD_ARG_TYPE) +CPP_TYPE_TO_PD_ARG_TYPE_REGISTER(PD_ARG_TYPE_TO_CPP_TYPE) + +} // namespace capi + +using LoD = capi::LoD; +using Context = capi::DeviceContext; +using DenseTensor = capi::DenseTensor; +using Scalar = capi::Scalar; +using IntArray = capi::IntArray; +using Place = capi::Place; +using DataType = ::PD_DataType; +using DataLayout = ::PD_DataLayout; + +} // namespace phi + +#include "paddle/phi/capi/include/kernel_utils.h" + +// clang-format off + +#define PD_BUILD_PHI_KERNEL(kernel_name, \ + backend, \ + layout, \ + meta_kernel_fn, \ + ...) \ + static void \ + __CUSTOM_adefs_CFN_##kernel_name##_##backend##_##layout( \ + const PD_KernelKey* kernel_key, PD_Kernel* kernel); \ + template \ + struct __##kernel_name##_##backend##_##layout##__ { \ + __##kernel_name##_##backend##_##layout##__() { \ + ::phi::capi::CustomKernelArgsParseFunctor)> \ + parser; \ + PD_RegisterPhiKernel( \ + #kernel_name, \ + #backend, \ + ::phi::capi::CppTypeToPDType::Type(), \ + PD_DATALAYOUT(layout), \ + parser.in_args_type.size(), \ + parser.in_args_type.data(), \ + parser.attr_args_type.size(), \ + parser.attr_args_type.data(), \ + parser.out_args_type.size(), \ + parser.out_args_type.data(), \ + __CUSTOM_adefs_CFN_##kernel_name##_##backend##_##layout, \ + CUSTOM_PHI_KERNEL(meta_kernel_fn), \ + CUSTOM_PHI_VARIADIC_KERNEL( \ + meta_kernel_fn)); \ + } \ + static void Touch() {} \ + }; \ + PD_CUSTOM_PHI_KERNEL_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + CUSTOM_tp_ns_check_##kernel_name##_##backend##_##layout, \ + "PD_BUILD_KERNEL must be called in global namespace."); \ + static void \ + __CUSTOM_adefs_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::capi::KernelKey &kernel_key, \ + ::phi::capi::Kernel* kernel); \ + _PD_BUILD_PHI_KERNEL(__##kernel_name##_##backend##_##layout##__, \ + kernel_name, \ + backend, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__) \ + void \ + __CUSTOM_adefs_CFN_##kernel_name##_##backend##_##layout( \ + const PD_KernelKey* kernel_key, PD_Kernel* kernel) { \ + auto cc_kernel = ::phi::capi::Kernel(kernel); \ + __CUSTOM_adefs_FN_##kernel_name##_##backend##_##layout( \ + ::phi::capi::KernelKey( \ + const_cast(kernel_key)), \ + &cc_kernel); \ + } \ + void \ + __CUSTOM_adefs_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::capi::KernelKey &kernel_key, \ + ::phi::capi::Kernel* kernel) + +// clang-format on + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6c1d3f3c0ee758a4f7b97f989127d0b4c2db3a08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/kernel_utils.h @@ -0,0 +1,909 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/capi/include/common.h" + +#if !defined(_WIN32) && !defined(__APPLE__) + +namespace phi { +namespace capi { + +#define CUSTOM_PHI_KERNEL(...) \ + ::phi::capi::CustomKernelImpl::Compute + +#define CUSTOM_PHI_VARIADIC_KERNEL(...) \ + reinterpret_cast( \ + &::phi::capi::CustomKernelImpl::VariadicCompute) + +#define PD_CUSTOM_NARGS(...) \ + _PD_CUSTOM_NARGS((__VA_ARGS__, _PD_CUSTOM_RESQ_N())) +#define _PD_CUSTOM_NARGS(...) _PD_CUSTOM_ARG_N(__VA_ARGS__) +#define _PD_CUSTOM_ARG_N_EXPAND( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, N, ...) \ + N +#define _PD_CUSTOM_ARG_N(args) _PD_CUSTOM_ARG_N_EXPAND args +#define _PD_CUSTOM_RESQ_N() 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +#define PD_DATALAYOUT(arg__) PD_DataLayout::arg__ + +#ifdef __COUNTER__ +#define PD_CUSTOM_PHI_KERNEL_ID __COUNTER__ +#else +#define PD_CUSTOM_PHI_KERNEL_ID __LINE__ +#endif + +#define PD_CUSTOM_PHI_KERNEL_CONCATENATE(arg1, arg2) \ + PD_CUSTOM_PHI_KERNEL_CONCATENATE1(arg1, arg2) +#define PD_CUSTOM_PHI_KERNEL_CONCATENATE1(arg1, arg2) \ + PD_CUSTOM_PHI_KERNEL_CONCATENATE2(arg1, arg2) +#define PD_CUSTOM_PHI_KERNEL_CONCATENATE2(arg1, arg2) arg1##arg2 +#define PD_CUSTOM_PHI_KERNEL_EXPAND(x) x + +#define _PD_BUILD_KERNEL_INSTANTIATION(N, meta_kernel_fn, backend, ...) \ + PD_CUSTOM_PHI_KERNEL_CONCATENATE(_PD_BUILD_KERNEL_INSTANTIATION_, N) \ + (meta_kernel_fn, backend, __VA_ARGS__) + +#define _PD_BUILD_KERNEL_INSTANTIATION_1(meta_kernel_fn, backend, cpp_dtype) \ + template decltype(meta_kernel_fn) meta_kernel_fn +#define _PD_BUILD_KERNEL_INSTANTIATION_2( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_1(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_3( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_2(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_4( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_3(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_5( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_4(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_6( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_5(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_7( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_6(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_8( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_7(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_9( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_8(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_10( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_9(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_11( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_10(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_12( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_11(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_13( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_12(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_14( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_13(meta_kernel_fn, backend, __VA_ARGS__)) +#define _PD_BUILD_KERNEL_INSTANTIATION_15( \ + meta_kernel_fn, backend, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) meta_kernel_fn; \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_INSTANTIATION_14(meta_kernel_fn, backend, __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_1(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + int TouchCustomKernelSymbolFor_##kernel_name##_##backend##_##layout() { \ + return 0; \ + } + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_2(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_1(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_3(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_2(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_4(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_3(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_5(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_4(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_6(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_5(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_7(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_6(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_8(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_7(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_9(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_8(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_10(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_9(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_11(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_10(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_12(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_11(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_13(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_12(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_14(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_13(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT_15(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + registrar_id, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const registrar_class PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id); \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_14(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define _PD_BUILD_KERNEL_REGISTRAR_INIT( \ + N, registrar_class, kernel_name, backend, layout, meta_kernel_fn, ...) \ + PD_CUSTOM_PHI_KERNEL_EXPAND(PD_CUSTOM_PHI_KERNEL_CONCATENATE( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT_, N)(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + PD_CUSTOM_PHI_KERNEL_ID, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define PD_BUILD_KERNEL_REGISTRAR_INIT( \ + registrar_class, kernel_name, backend, layout, meta_kernel_fn, ...) \ + PD_CUSTOM_PHI_KERNEL_EXPAND( \ + _PD_BUILD_KERNEL_REGISTRAR_INIT(PD_CUSTOM_NARGS(__VA_ARGS__), \ + registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define PD_BUILD_KERNEL_INSTANTIATION(meta_kernel_fn, backend, ...) \ + _PD_BUILD_KERNEL_INSTANTIATION( \ + PD_CUSTOM_NARGS(__VA_ARGS__), meta_kernel_fn, backend, __VA_ARGS__) + +#define _PD_BUILD_2TA_KERNEL( \ + registrar_class, kernel_name, backend, layout, meta_kernel_fn, ...) \ + PD_BUILD_KERNEL_INSTANTIATION(meta_kernel_fn, backend, __VA_ARGS__); \ + PD_BUILD_KERNEL_REGISTRAR_INIT(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__); + +#define _PD_BUILD_PHI_KERNEL( \ + registrar_class, kernel_name, backend, layout, meta_kernel_fn, ...) \ + PD_CUSTOM_PHI_KERNEL_EXPAND(_PD_BUILD_2TA_KERNEL(registrar_class, \ + kernel_name, \ + backend, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_DEVICE_CONTEXT(dev_ctx) \ + template \ + struct CustomKernelCallHelper { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(in_idx == 0, \ + "Kernel's DeviceContext should appear before Inputs."); \ + static_assert( \ + attr_idx == 0, \ + "Kernel's DeviceContext should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's DeviceContext should appear before Outputs."); \ + dev_ctx arg = PD_GetDeviceContext(ctx); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + const dev_ctx &arg = std::get(ctx); \ + auto dev_ctx_wrapper = phi::capi::DeviceContext( \ + reinterpret_cast(const_cast(&arg))); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., dev_ctx_wrapper); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_INPUT(tensor_type) \ + template \ + struct CustomKernelCallHelper { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + const tensor_type arg = PD_InputAt(ctx, in_idx); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + const tensor_type &arg = std::get(ctx); \ + auto tensor = phi::capi::DenseTensor( \ + reinterpret_cast(const_cast(&arg))); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., tensor); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_OPTIONAL_INPUT(tensor_type) \ + template \ + struct CustomKernelCallHelper &, \ + Tail...> { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + auto arg = PD_OptionalInputAt(ctx, in_idx); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + auto &arg = std::get(ctx); \ + paddle::optional tensor = \ + PD_OptionalTensor(reinterpret_cast( \ + const_cast *>(&arg))); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., tensor); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_MULTI_INPUT(tensor_type) \ + template \ + struct CustomKernelCallHelper &, \ + Tail...> { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + auto arg = PD_MultiInputAt(ctx, in_idx); \ + auto arg_wrapper = PD_GetPointerVector(&arg); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg_wrapper); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + auto &arg = std::get(ctx); \ + auto tensor = PD_TensorVector(reinterpret_cast( \ + const_cast *>(&arg))); \ + auto tensor_ptr_vec = PD_GetPointerVector(&arg); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., tensor_ptr_vec); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(attr_type) \ + template \ + struct CustomKernelCallHelper { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(out_idx == 0, \ + "Kernel's Attributes should appear before Outputs."); \ + attr_type arg = PD_AttrAt(ctx, attr_idx); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + auto &arg = std::get(ctx); \ + auto attr = PD_Attr(reinterpret_cast(&arg)); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., attr); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( \ + attr_type) \ + template \ + struct CustomKernelCallHelper { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + static_assert(out_idx == 0, \ + "Kernel's Attributes should appear before Outputs."); \ + attr_type arg = PD_AttrAt(ctx, attr_idx); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + const attr_type &arg = std::get(ctx); \ + auto attr = PD_Attr( \ + reinterpret_cast(const_cast(&arg))); \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., attr); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_OUTPUT(tensor_type) \ + template \ + struct CustomKernelCallHelper { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + auto arg = PD_OutputAt(ctx, out_idx); \ + tensor_type *ptr = (arg.raw_data() ? &arg : nullptr); \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., ptr); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + tensor_type *arg = std::get(ctx); \ + auto tensor = \ + phi::capi::DenseTensor(reinterpret_cast(arg)); \ + auto tensor_ptr = tensor.raw_data() ? &tensor : nullptr; \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., tensor_ptr); \ + } \ + } + +#define PD_SPECIALIZE_CustomKernelCallHelper_FOR_MULTI_OUTPUT(tensor_type) \ + template \ + struct CustomKernelCallHelper, Tail...> { \ + template \ + static void Compute(PD_KernelContext *ctx, PreviousArgs &...pargs) { \ + auto arg = PD_MultiOutputAt(ctx, out_idx); \ + std::vector tensor_ptr_vec; \ + for (auto &tensor : arg) { \ + tensor_ptr_vec.push_back(tensor.raw_data() ? &tensor : nullptr); \ + } \ + CustomKernelCallHelper:: \ + template Compute( \ + ctx, pargs..., tensor_ptr_vec); \ + } \ + template \ + static void VariadicCompute(const std::tuple &ctx, \ + PreviousArgs &...pargs) { \ + std::vector &arg = std::get(ctx); \ + auto tensor_vec = PD_TensorVector(reinterpret_cast( \ + const_cast *>(&arg))); \ + std::vector tensor_ptr_vec; \ + for (auto &tensor : tensor_vec) { \ + tensor_ptr_vec.push_back(tensor.raw_data() ? &tensor : nullptr); \ + } \ + return CustomKernelCallHelper::template VariadicCompute( \ + ctx, pargs..., tensor_ptr_vec); \ + } \ + } + +template +struct CustomTypeTag {}; + +template +struct CustomKernelImpl; + +template +struct CustomKernelImpl { + static void Compute(PD_KernelContext *ctx) { + CustomKernelCallHelper>:: + template Compute<0, 0, 0, 0>(ctx); + } + + static void VariadicCompute(DevCtx dev_ctx, Args... args) { + const std::tuple args_tuple(dev_ctx, args...); + return CustomKernelCallHelper>:: + template VariadicCompute<0>(args_tuple); + } + + private: + template + struct CustomKernelCallHelper; + + /* DeviceContext Helpers */ + + PD_SPECIALIZE_CustomKernelCallHelper_FOR_DEVICE_CONTEXT( + phi::capi::DeviceContext); + + /* Input Helpers */ + + PD_SPECIALIZE_CustomKernelCallHelper_FOR_INPUT(phi::capi::DenseTensor); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_OPTIONAL_INPUT( + phi::capi::DenseTensor); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_MULTI_INPUT(phi::capi::DenseTensor); + + /* Attribute Helpers */ + + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(bool); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(int32_t); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(int64_t); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(float); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(double); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(PD_DataType); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(PD_DataLayout); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_ATTRIBUTE(phi::capi::Place); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::string); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + phi::capi::Scalar); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + phi::capi::IntArray); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + + /* Output Helpers */ + + PD_SPECIALIZE_CustomKernelCallHelper_FOR_OUTPUT(phi::capi::DenseTensor); + PD_SPECIALIZE_CustomKernelCallHelper_FOR_MULTI_OUTPUT(phi::capi::DenseTensor); + + /* End case */ + template + struct CustomKernelCallHelper> { + template + static void Compute(PD_KernelContext *ctx, DevCtx dev_ctx, Args &...args) { + static_assert(dev_ctx_idx > 0, + "Kernel should pass DeviceContext as argument."); + static_assert(out_idx > 0, "Kernel should have output argument."); + return kernel_fn(dev_ctx, args...); + } + + template + static void VariadicCompute(const std::tuple &ctx, + DevCtx dev_ctx, + Args... args) { + return kernel_fn(dev_ctx, args...); + } + }; +}; + +template +struct CustomKernelArgsParseFunctor; + +template +struct CustomKernelArgsParseFunctor { + using Args = std::tuple; + enum : std::size_t { Arity = sizeof...(Args_) }; + using Indices = std::make_index_sequence; + template + using Arg = typename std::tuple_element::type; + + CustomKernelArgsParseFunctor() { + auto args_type = ParseArgType(Indices{}); + + for (auto arg_type : args_type) { + if (arg_type == + std::type_index(typeid(const phi::capi::DeviceContext *))) { + } else if (arg_type == + std::type_index(typeid(const phi::capi::DenseTensor &))) { + in_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_TENSOR); + } else if (arg_type == + std::type_index(typeid( + const paddle::optional &))) { + in_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_OPTIONAL_TENSOR); + } else if (arg_type == + std::type_index(typeid( + const std::vector &))) { + in_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_LIST_TENSOR); + } else if (arg_type == + std::type_index( + typeid(const paddle::optional< + std::vector> &))) { + in_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_OPTIONAL_MULTI_TENSOR); + } else if (arg_type == std::type_index(typeid(bool))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_BOOL); + } else if (arg_type == std::type_index(typeid(float))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_FLOAT32); + } else if (arg_type == std::type_index(typeid(double))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_FLOAT64); + } else if (arg_type == std::type_index(typeid(int32_t))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_INT32); + } else if (arg_type == std::type_index(typeid(int64_t))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_INT64); + } else if (arg_type == + std::type_index(typeid(const phi::capi::Place &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_PLACE); + } else if (arg_type == std::type_index(typeid(const std::string &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_STRING); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_LIST_BOOL); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT32); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_LIST_FLOAT64); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT32); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_LIST_INT64); + } else if (arg_type == + std::type_index(typeid(const std::vector &))) { + attr_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_LIST_STRING); + } else if (arg_type == std::type_index(typeid( + const std::vector &))) { + attr_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_LIST_SCALAR); + } else if (arg_type == + std::type_index(typeid(const phi::capi::Scalar &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_SCALAR); + } else if (arg_type == + std::type_index(typeid(const phi::capi::IntArray &))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_INT_ARRAY); + } else if (arg_type == std::type_index(typeid(PD_DataType))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_DATA_TYPE); + } else if (arg_type == std::type_index(typeid(PD_DataLayout))) { + attr_args_type.push_back( + PD_KernelArgumentType::PD_ARG_TYPE_DATA_LAYOUT); + } else if (arg_type == std::type_index(typeid(PD_DataLayout))) { + attr_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_PLACE); + } else if (arg_type == + std::type_index(typeid(phi::capi::DenseTensor *))) { + out_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_TENSOR); + } else if (arg_type == std::type_index(typeid( + std::vector))) { + out_args_type.push_back(PD_KernelArgumentType::PD_ARG_TYPE_LIST_TENSOR); + } + } + } + + std::vector in_args_type; + std::vector attr_args_type; + std::vector out_args_type; + + private: + template + static std::vector ParseArgType( + std::index_sequence) { + return {std::type_index(typeid(Arg))...}; + } +}; + +} // namespace capi +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/type_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/type_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ed892c881d7150c4c7c027cb21cf7ac46fd166b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/type_utils.h @@ -0,0 +1,123 @@ +// Copyright (c) 2022 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. + +#pragma once +#if !defined(_WIN32) && !defined(__APPLE__) + +#include "paddle/phi/capi/include/c_data_type.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/core/enforce.h" + +namespace phi { +namespace capi { + +inline PD_DataType ToPDDataType(::paddle::experimental::DataType dtype) { +#define return_result(in, ret) \ + case ::paddle::experimental::DataType::in: \ + return PD_DataType::ret + switch (dtype) { + return_result(UNDEFINED, UNDEFINED); + return_result(FLOAT64, FLOAT64); + return_result(FLOAT32, FLOAT32); + return_result(FLOAT16, FLOAT16); + return_result(BFLOAT16, BFLOAT16); + return_result(INT64, INT64); + return_result(INT32, INT32); + return_result(INT16, INT16); + return_result(INT8, INT8); + return_result(UINT64, UINT64); + return_result(UINT32, UINT32); + return_result(UINT16, UINT16); + return_result(UINT8, UINT8); + return_result(BOOL, BOOL); + default: { + PADDLE_THROW( + ::phi::errors::Unavailable("DataType %d is not supported.", dtype)); + } + } +#undef return_result +} + +inline ::paddle::experimental::DataType ToPhiDataType(PD_DataType dtype) { +#define return_result(in, ret) \ + case PD_DataType::in: \ + return ::paddle::experimental::DataType::ret + switch (dtype) { + return_result(UNDEFINED, UNDEFINED); + return_result(FLOAT64, FLOAT64); + return_result(FLOAT32, FLOAT32); + return_result(FLOAT16, FLOAT16); + return_result(BFLOAT16, BFLOAT16); + return_result(INT64, INT64); + return_result(INT32, INT32); + return_result(INT16, INT16); + return_result(INT8, INT8); + return_result(UINT64, UINT64); + return_result(UINT32, UINT32); + return_result(UINT16, UINT16); + return_result(UINT8, UINT8); + return_result(BOOL, BOOL); + default: { + PADDLE_THROW( + ::phi::errors::Unavailable("DataType %d is not supported.", dtype)); + return ::paddle::experimental::DataType::UNDEFINED; + } + } +#undef return_result +} + +inline PD_DataLayout ToPDDataLayout(::paddle::experimental::DataLayout layout) { +#define return_result(in, ret) \ + case ::paddle::experimental::DataLayout::in: \ + return PD_DataLayout::ret + switch (layout) { + return_result(ANY, ANY); + return_result(NHWC, NHWC); + return_result(NCHW, NCHW); + return_result(NCDHW, NCDHW); + return_result(NDHWC, NDHWC); + default: { + PADDLE_THROW(::phi::errors::Unavailable("DataLayout %d is not supported.", + layout)); + return PD_DataLayout::ANY; + } + } +#undef return_result +} + +inline ::paddle::experimental::DataLayout ToPhiDataLayout( + PD_DataLayout layout) { +#define return_result(in, ret) \ + case PD_DataLayout::in: \ + return ::paddle::experimental::DataLayout::ret + switch (layout) { + return_result(ANY, ANY); + return_result(NHWC, NHWC); + return_result(NCHW, NCHW); + return_result(NCDHW, NCDHW); + return_result(NDHWC, NDHWC); + default: { + PADDLE_THROW(::phi::errors::Unavailable("DataLayout %d is not supported.", + layout)); + return ::paddle::experimental::DataLayout::ANY; + } + } +#undef return_result +} + +} // namespace capi +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/wrapper_base.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/wrapper_base.h new file mode 100644 index 0000000000000000000000000000000000000000..adfb2b5a0e050d0eb876fd4eb187b0d6d6d96feb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/capi/include/wrapper_base.h @@ -0,0 +1,497 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if !defined(_WIN32) && !defined(__APPLE__) + +#include +#include +#include +#include +#include +#include + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/capi/include/c_device_context.h" +#include "paddle/phi/capi/include/c_int_array.h" +#include "paddle/phi/capi/include/c_kernel_context.h" +#include "paddle/phi/capi/include/c_kernel_factory.h" +#include "paddle/phi/capi/include/c_kernel_registry.h" +#include "paddle/phi/capi/include/c_place.h" +#include "paddle/phi/capi/include/c_scalar.h" +#include "paddle/phi/capi/include/c_tensor.h" +#include "paddle/phi/capi/include/data_type.h" +#include "paddle/utils/optional.h" + +#define PD_CHECK_STATUS(status) PD_CHECK(status == C_SUCCESS) + +namespace phi { + +namespace capi { + +using LoD = std::vector>; + +template +static inline PD_List PDListFromVector(std::vector* vec) { + PD_List list; + list.data = reinterpret_cast(vec->data()); + list.size = vec->size(); + return list; +} + +template +static inline std::vector PDListToVector(PD_List list) { + return std::vector(static_cast(list.data), + static_cast(list.data) + list.size); +} + +inline std::vector PD_TensorGetDims(PD_Tensor* tensor, + PD_Status* status) { + int64_t ndims = PD_TensorGetNumDims(tensor, status); + if (ndims > 0) { + std::vector shape(ndims); + for (int64_t i = 0; i < ndims; ++i) { + shape[i] = PD_TensorGetDim(tensor, i, status); + } + return shape; + } + return std::vector(); +} + +template +class WrapperBase { + public: + explicit WrapperBase(T* ptr, bool own = false) : data_(ptr), own_(own) {} + + inline T* raw_data() const { return data_; } + + inline bool own_data() const { return own_; } + + inline void reset(const T* ptr) { data_ = ptr; } + + private: + T* data_; + bool own_; +}; + +class DenseTensor : public WrapperBase { + public: + DenseTensor() : WrapperBase(PD_NewTensor(), true) {} + + explicit DenseTensor(PD_Tensor* tensor) : WrapperBase(tensor) {} + + ~DenseTensor() { + if (own_data()) { + PD_DeleteTensor(raw_data()); + } + } + + bool valid() const { + C_Status status; + auto ret = PD_TensorIsValid(raw_data(), &status); + PD_CHECK_STATUS(status); + return ret; + } + + bool initialized() const { + C_Status status; + auto ret = PD_TensorIsInitialized(raw_data(), &status); + PD_CHECK_STATUS(status); + return ret; + } + + void* Holder() const { + C_Status status; + auto holder = PD_TensorGetHolder(raw_data(), &status); + PD_CHECK_STATUS(status); + return holder; + } + + std::vector dims() const { + C_Status status; + auto dimension = PD_TensorGetDims(raw_data(), &status); + PD_CHECK_STATUS(status); + return dimension; + } + + PD_DataType dtype() const { + C_Status status; + auto data_type = PD_TensorGetPDDataType(raw_data(), &status); + PD_CHECK_STATUS(status); + return data_type; + } + + PD_DataLayout layout() const { + C_Status status; + auto data_layout = PD_TensorGetDataLayout(raw_data(), &status); + PD_CHECK_STATUS(status); + return data_layout; + } + + int64_t numel() const { + C_Status status; + auto element_count = PD_TensorGetElementCount(raw_data(), &status); + PD_CHECK_STATUS(status); + return element_count; + } + + int64_t memory_size() const { + C_Status status; + auto byte_size = PD_TensorGetByteSize(raw_data(), &status); + PD_CHECK_STATUS(status); + return byte_size; + } + + LoD lod() const { + PD_List data, offset; + C_Status status; + PD_TensorGetLoD(raw_data(), &data, &offset, &status); + PD_CHECK_STATUS(status); + LoD lod_; + auto ptr = static_cast(data.data); + auto offset_ptr = static_cast(offset.data); + for (size_t i = 0; i < offset.size - 1; ++i) { + lod_.emplace_back(ptr + offset_ptr[i], ptr + offset_ptr[i + 1]); + } + delete[] ptr; + delete[] offset_ptr; + return lod_; + } + + void ResetLoD(const LoD& lod) { + std::vector data, offset; + offset.push_back(0); + for (const auto& item : lod) { + data.insert(data.cend(), item.cbegin(), item.cend()); + offset.push_back(item.size()); + } + PD_List data_list, offset_list; + data_list = PDListFromVector(&data); + offset_list = PDListFromVector(&offset); + + C_Status status; + PD_TensorResetLoD(raw_data(), data_list, offset_list, &status); + PD_CHECK_STATUS(status); + } + + void Resize(const std::vector& dims) { + C_Status status; + PD_TensorSetDims(raw_data(), dims.size(), dims.data(), &status); + PD_CHECK_STATUS(status); + } + + void set_dtype(PD_DataType data_type) { + C_Status status; + PD_TensorSetDataType(raw_data(), data_type, &status); + PD_CHECK_STATUS(status); + } + + void set_layout(PD_DataLayout data_layout) { + C_Status status; + PD_TensorSetDataLayout(raw_data(), data_layout, &status); + PD_CHECK_STATUS(status); + } + + template + T* data() const { + C_Status status; + auto ptr = PD_TensorGetDataPointer(raw_data(), &status); + PD_CHECK_STATUS(status); + return static_cast(ptr); + } + + // template + // T* mutable_data(int64_t size = 0, const PD_DeviceContext* ctx = nullptr) { + // C_Status status; + // auto ptr = PD_DeviceContextAllocateTensor( + // ctx, raw_data(), size, phi::capi::CppTypeToPDType::Type(), + // &status); + // PD_CHECK_STATUS(status); + // return static_cast(ptr); + // } + + // void* mutable_data(PD_DataType data_type, + // int64_t size = 0, + // const PD_DeviceContext* ctx = nullptr) { + // C_Status status; + // auto ptr = PD_DeviceContextAllocateTensor( + // ctx, raw_data(), size, data_type, &status); + // PD_CHECK_STATUS(status); + // return static_cast(ptr); + // } + + DenseTensor& ShareDataWith(const DenseTensor& src) { + C_Status status; + PD_TensorShareDataWith(raw_data(), src.raw_data(), &status); + PD_CHECK_STATUS(status); + return *this; + } + + void share_lod(const DenseTensor& src) { + C_Status status; + PD_TensorShareLoDWith(raw_data(), src.raw_data(), &status); + PD_CHECK_STATUS(status); + } +}; + +class DeviceContext : public WrapperBase { + public: + explicit DeviceContext(PD_DeviceContext* context) + : WrapperBase(context) {} + + void* stream() const { + C_Status status; + auto stream_ = PD_DeviceContextGetStream(raw_data(), &status); + PD_CHECK_STATUS(status); + return stream_; + } + + void* Alloc(DenseTensor* tensor, + PD_DataType dtype, + int64_t requested_size = 0) const { + C_Status status; + auto ptr = PD_DeviceContextAllocateTensor( + raw_data(), tensor->raw_data(), requested_size, dtype, &status); + PD_CHECK_STATUS(status); + return static_cast(ptr); + } + + template + T* Alloc(DenseTensor* tensor, int64_t requested_size = 0) const { + C_Status status; + auto ptr = + PD_DeviceContextAllocateTensor(raw_data(), + tensor->raw_data(), + requested_size, + phi::capi::CppTypeToPDType::Type(), + &status); + PD_CHECK_STATUS(status); + return static_cast(ptr); + } + + void* HostAlloc(DenseTensor* tensor, + PD_DataType dtype, + int64_t requested_size = 0) const { + C_Status status; + auto ptr = PD_DeviceContextAllocateTensor( + nullptr, tensor->raw_data(), requested_size, dtype, &status); + PD_CHECK_STATUS(status); + return static_cast(ptr); + } + + template + T* HostAlloc(DenseTensor* tensor, int64_t requested_size = 0) const { + C_Status status; + auto ptr = + PD_DeviceContextAllocateTensor(nullptr, + tensor->raw_data(), + requested_size, + phi::capi::CppTypeToPDType::Type(), + &status); + PD_CHECK_STATUS(status); + return static_cast(ptr); + } +}; + +class Scalar : public WrapperBase { + public: + explicit Scalar(PD_Scalar* scalar) : WrapperBase(scalar) {} + + PD_DataType dtype() const { return PD_ScalarGetDataType(raw_data()); } + + template + inline T to() const; +}; + +template <> +inline bool Scalar::to() const { + return PD_ScalarGetBoolData(raw_data()); +} + +template <> +inline float Scalar::to() const { + return PD_ScalarGetFloat32Data(raw_data()); +} + +template <> +inline double Scalar::to() const { + return PD_ScalarGetFloat64Data(raw_data()); +} + +template <> +inline uint8_t Scalar::to() const { + return PD_ScalarGetUInt8Data(raw_data()); +} + +template <> +inline uint16_t Scalar::to() const { + return PD_ScalarGetUInt16Data(raw_data()); +} + +template <> +inline uint32_t Scalar::to() const { + return PD_ScalarGetUInt32Data(raw_data()); +} + +template <> +inline uint64_t Scalar::to() const { + return PD_ScalarGetUInt64Data(raw_data()); +} + +template <> +inline int8_t Scalar::to() const { + return PD_ScalarGetInt8Data(raw_data()); +} + +template <> +inline int16_t Scalar::to() const { + return PD_ScalarGetInt16Data(raw_data()); +} + +template <> +inline int32_t Scalar::to() const { + return PD_ScalarGetInt32Data(raw_data()); +} + +template <> +inline int64_t Scalar::to() const { + return PD_ScalarGetInt64Data(raw_data()); +} + +class IntArray : WrapperBase { + public: + explicit IntArray(PD_IntArray* int_array) + : WrapperBase(int_array) {} + + size_t size() const { return PD_IntArrayGetElementCount(raw_data()); } + + std::vector GetData() const { + auto list = PD_IntArrayGetDataPointer(raw_data()); + auto data = reinterpret_cast(list.data); + std::vector ret(data, data + list.size); + return ret; + } +}; + +class Place : WrapperBase { + public: + explicit Place(PD_Place* place) : WrapperBase(place) {} + + bool is_host() { return PD_PlaceIsHost(raw_data()); } + + int8_t GetDeviceID() { return PD_PlaceGetDeviceId(raw_data()); } +}; + +class TensorArgDef : WrapperBase { + public: + explicit TensorArgDef(PD_TensorArgDef* tensor_arg_def) + : WrapperBase(tensor_arg_def) {} + + // TensorArgDef& SetBackend() { + // return *this; + // } + + TensorArgDef& SetDataLayout(PD_DataLayout in_layout) { + C_Status status; + PD_TensorArgDefSetDataLayout(raw_data(), in_layout, &status); + PD_CHECK_STATUS(status); + return *this; + } + + TensorArgDef& SetDataType(PD_DataType in_dtype) { + C_Status status; + PD_TensorArgDefSetDataType(raw_data(), in_dtype, &status); + PD_CHECK_STATUS(status); + return *this; + } +}; + +class KernelArgsDef : WrapperBase { + public: + explicit KernelArgsDef(PD_KernelArgsDef* kernel_args_def) + : WrapperBase(kernel_args_def) {} + + std::vector input_defs() { + C_Status status; + auto list = PD_KernelArgsDefGetInputArgDefs(raw_data(), &status); + PD_CHECK_STATUS(status); + auto ptr = reinterpret_cast(list.data); + std::vector ret; + for (size_t i = 0; i < list.size; ++i) { + ret.emplace_back(ptr[i]); + } + PD_DeletePointerList(list); + return ret; + } + + std::vector output_defs() { + C_Status status; + auto list = PD_KernelArgsDefGetOutputArgDefs(raw_data(), &status); + PD_CHECK_STATUS(status); + auto ptr = reinterpret_cast(list.data); + std::vector ret; + for (size_t i = 0; i < list.size; ++i) { + ret.emplace_back(ptr[i]); + } + PD_DeletePointerList(list); + return ret; + } + + // std::vector + // attribute_defs() { + // } +}; + +class KernelKey : WrapperBase { + public: + explicit KernelKey(PD_KernelKey* kernel_key) + : WrapperBase(kernel_key) {} + + // Backend backend() const { return backend_; } + PD_DataLayout layout() const { + PD_Status status; + auto layout_ = PD_KernelKeyGetLayout(raw_data(), &status); + PD_CHECK_STATUS(status); + return layout_; + } + + PD_DataType dtype() const { + PD_Status status; + auto dtype_ = PD_KernelKeyGetDataType(raw_data(), &status); + PD_CHECK_STATUS(status); + return dtype_; + } +}; + +class Kernel : WrapperBase { + public: + explicit Kernel(PD_Kernel* kernel) : WrapperBase(kernel) {} + + KernelArgsDef args_def() const { + C_Status status; + auto ptr = PD_KernelGetArgsDef(raw_data(), &status); + PD_CHECK_STATUS(status); + return KernelArgsDef(ptr); + } + + TensorArgDef InputAt(size_t idx) { return args_def().input_defs()[idx]; } + + TensorArgDef OutputAt(size_t idx) { return args_def().input_defs()[idx]; } +}; + +} // namespace capi +} // namespace phi + +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/amp_type_traits.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/amp_type_traits.h new file mode 100644 index 0000000000000000000000000000000000000000..ce3a469f5aeddc29e67e320141d2ebaab925fabd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/amp_type_traits.h @@ -0,0 +1,42 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/bfloat16.h" +#include "paddle/phi/common/float16.h" + +namespace phi { +namespace dtype { + +template +class MPTypeTrait { + public: + using Type = T; +}; + +template <> +class MPTypeTrait { + public: + using Type = float; +}; + +template <> +class MPTypeTrait { + public: + using Type = float; +}; + +} // namespace dtype +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/backend.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..b740815305dedfced7001a37a513de6dcfc55a23 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/backend.h @@ -0,0 +1,188 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/common/place.h" + +namespace paddle { +namespace experimental { + +/** + * [ Why need Backend? ] + * + * Backend not only means place. Backend is a superset of place. + * + * Place cannot indicate the difference in calculation methods on the device, + * but in order to make the boundary of the kernel clearer and the function + * more specific, we need to distinguish the calculation method. + * + * Such as the kernel for CPU device, it can be a native CPU kernel, + * or a kernel implemented by oneDNN library. + * + * Note(chenweihang): HIP is not needed now, we can added it if needed + * in the future + */ +enum class Backend : uint8_t { + UNDEFINED = 0, + + // basic kernel backend + CPU, + + // various acceleration devices' backends + GPU, + XPU, // XPU currently does not exist at the same time as CUDA + NPU, // NPU currently does not exist at the same time as CUDA + MLU, // MLU currently does not exist at the same time as CUDA + IPU, + + // the third library backend + ONEDNN, + GPUDNN, // cuDNN and hipDNN + + // paddle kernel primitives backend + KPS, + + // end of backend types + NUM_BACKENDS, + + /** + * [ Why we need ALL in basic kernel key member? ] + * + * For Tensor, ALL represents an illegal Backend, but for Kernel, some + * kernels may be device-independent by nature, such as reshape; and when + * and some kernels are also device-independent when implemented based on + * primitive API. + * + * In this case, we need to provide a more concise registration method, + * instead of registering the kernels for each device with almost + * repetitive code, we need one registration covers all situations, + * so if we provide the ALL field with Register the kernel in this statement. + * + * Of course, we have also considered solving this problem through different + * named macros, for example, if we define + * + * PD_REGISTER_KERNEL_FOR_ALL_BACKEND + * + * Based on this design pattern, the dtype and layout also have the same + * requirements, this cause we need to define a series of macros + * + * PD_REGISTER_KERNEL_FOR_ALL_DTYPE + * PD_REGISTER_KERNEL_FOR_ALL_LAYOUT + * PD_REGISTER_KERNEL_FOR_ALL_BACKEND_AND_LAYOUT + * PD_REGISTER_KERNEL_FOR_ALL_BACKEND_AND_DTYPE + * PD_REGISTER_KERNEL_FOR_ALL_LAYOUT_AND_DTYPE + * PD_REGISTER_KERNEL_FOR_ALL_BACKEND_AND_LAYOUT_AND_DTYPE + * + * It makes the system of registering macros more complicated, we think + * this is not a simple design, so we still adopt the design of providing + * the ALL field. + * + * Note: ALL_BACKEND only used for Kernel registration and selection + */ + ALL_BACKEND = UNDEFINED, +}; + +inline std::ostream& operator<<(std::ostream& os, Backend backend) { + switch (backend) { + case Backend::UNDEFINED: + os << "Undefined"; + break; + case Backend::CPU: + os << "CPU"; + break; + case Backend::GPU: + os << "GPU"; + break; + case Backend::XPU: + os << "XPU"; + break; + case Backend::NPU: + os << "NPU"; + break; + case Backend::MLU: + os << "MLU"; + break; + case Backend::ONEDNN: + os << "ONEDNN"; + break; + case Backend::GPUDNN: + os << "GPUDNN"; + break; + case Backend::KPS: + os << "KPS"; + break; + case Backend::IPU: + os << "IPU"; + break; + default: { + size_t device_type_id_ = static_cast(backend) - + static_cast(Backend::NUM_BACKENDS); + std::string device_type = phi::GetGlobalDeviceType(device_type_id_); + if (!device_type.empty()) { + os << device_type; + } else { + PD_THROW( + "Invalid enum backend type `", static_cast(backend), "`."); + } + } + } + return os; +} + +inline Backend StringToBackend(const char* backend_cstr) { + std::string s(backend_cstr); + if (s == std::string("Undefined")) { + return Backend::UNDEFINED; + } + if (s == std::string("CPU")) { + return Backend::CPU; + } else if (s == std::string("GPU")) { + return Backend::GPU; + } else if (s == std::string("XPU")) { + return Backend::XPU; + } else if (s == std::string("NPU")) { + return Backend::NPU; + } else if (s == std::string("MLU")) { + return Backend::MLU; + } else if (s == std::string("OneDNN")) { + return Backend::ONEDNN; + } else if (s == std::string("GPUDNN")) { + return Backend::GPUDNN; + } else if (s == std::string("KPS")) { +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + // NOTE(chenweihang) KPS is not yet a complete backend, and it still needs + // to be converted + // to GPU in the GPU environment + return Backend::GPU; +#else + return Backend::KPS; +#endif + } else if (s == std::string("IPU")) { + return Backend::IPU; + } else { + return static_cast(static_cast(Backend::NUM_BACKENDS) + + phi::GetOrRegisterGlobalDeviceTypeId(s)); + } +} + +} // namespace experimental +} // namespace paddle + +namespace phi { +using Backend = paddle::experimental::Backend; +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/bfloat16.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..5f30ee4077b5c615d73a7446fff211a6c86d69b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/bfloat16.h @@ -0,0 +1,413 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include +#include +#include +#include + +#ifdef PADDLE_WITH_CUDA +#include +#endif + +#if defined(__CUDACC__) && CUDA_VERSION >= 11000 +#define PADDLE_CUDA_BF16 +#include +#endif + +#if !defined(_WIN32) +#define PADDLE_ALIGN(x) __attribute__((aligned(x))) +#else +#define PADDLE_ALIGN(x) __declspec(align(x)) +#endif + +#if (defined(__CUDACC__) || defined(__HIPCC__)) +#define HOSTDEVICE __host__ __device__ +#define DEVICE __device__ +#define HOST __host__ +#else +#define HOSTDEVICE +#define DEVICE +#define HOST +#endif + +namespace phi { +namespace dtype { + +struct PADDLE_ALIGN(2) bfloat16 { + public: + uint16_t x; + + // Constructors + bfloat16() = default; + bfloat16(const bfloat16& o) = default; + bfloat16& operator=(const bfloat16& o) = default; + bfloat16(bfloat16&& o) = default; + bfloat16& operator=(bfloat16&& o) = default; + ~bfloat16() = default; + + HOSTDEVICE inline explicit bfloat16(float val) { +#ifdef PADDLE_WITH_HIP + uint32_t res = 0; + uint32_t* tempRes; + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + tempRes = reinterpret_cast(&val); + res = *tempRes; + x = res >> 16; +#else +#if defined(PADDLE_CUDA_BF16) + __nv_bfloat16 tmp = __float2bfloat16(val); + x = *reinterpret_cast(&tmp); +#else + std::memcpy(&x, reinterpret_cast(&val) + 2, 2); +#endif +#endif + } + +#if defined(PADDLE_CUDA_BF16) + HOSTDEVICE inline explicit bfloat16(const __nv_bfloat16& val) { + x = *reinterpret_cast(&val); // NOLINT + } +#endif + + template + HOSTDEVICE inline explicit bfloat16(const T& val) + : x(bfloat16(static_cast(val)).x) {} + +// Assignment operators +#if defined(PADDLE_CUDA_BF16) + HOSTDEVICE inline bfloat16& operator=(const __nv_bfloat16& val) { + x = *reinterpret_cast(&val); // NOLINT + return *this; + } +#endif + + HOSTDEVICE inline bfloat16& operator=(bool b) { + x = b ? 0x3f80 : 0; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(int8_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(uint8_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(int16_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(uint16_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(int32_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(uint32_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(int64_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(uint64_t val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(float val) { + x = bfloat16(val).x; + return *this; + } + + HOSTDEVICE inline bfloat16& operator=(double val) { + x = bfloat16(val).x; + return *this; + } + + // Conversion opertors + HOSTDEVICE inline explicit operator float() const { +#ifdef PADDLE_WITH_HIP + uint32_t res = 0; + // We should be using memcpy in order to respect the strict aliasing rule + // but it fails in the HIP environment. + uint16_t temp = x; + uint16_t* temp_ptr = reinterpret_cast(&temp); + res = *temp_ptr; + return res; +#else +#ifdef PADDLE_CUDA_BF16 + return __bfloat162float(*reinterpret_cast(&x)); +#else + float val = 0.f; + uint16_t temp = x; + std::memcpy( + reinterpret_cast(&val) + 2, reinterpret_cast(&temp), 2); + return val; +#endif +#endif + } + +#ifdef PADDLE_CUDA_BF16 + HOSTDEVICE inline explicit operator __nv_bfloat16() const { + return *reinterpret_cast(&x); + } +#endif + + HOSTDEVICE inline explicit operator bool() const { return (x & 0x7fff) != 0; } + + HOSTDEVICE inline explicit operator int8_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint8_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int16_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint16_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int32_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint32_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int64_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint64_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator double() const { + return static_cast(static_cast(*this)); + } +}; + +HOSTDEVICE inline bfloat16 operator+(const bfloat16& a, const bfloat16& b) { + return bfloat16(static_cast(a) + static_cast(b)); +} + +HOSTDEVICE inline bfloat16 operator-(const bfloat16& a, const bfloat16& b) { + return bfloat16(static_cast(a) - static_cast(b)); +} + +HOSTDEVICE inline bfloat16 operator*(const bfloat16& a, const bfloat16& b) { + return bfloat16(static_cast(a) * static_cast(b)); +} + +HOSTDEVICE inline bfloat16 operator/(const bfloat16& a, const bfloat16& b) { + return bfloat16(static_cast(a) / static_cast(b)); +} + +HOSTDEVICE inline bfloat16 operator-(const bfloat16& a) { + bfloat16 res; + res.x = a.x ^ 0x8000; + return res; +} + +HOSTDEVICE inline bfloat16& operator+=(bfloat16& a, // NOLINT + const bfloat16& b) { + a = bfloat16(static_cast(a) + static_cast(b)); + return a; +} + +HOSTDEVICE inline bfloat16& operator-=(bfloat16& a, // NOLINT + const bfloat16& b) { + a = bfloat16(static_cast(a) - static_cast(b)); + return a; +} + +HOSTDEVICE inline bfloat16& operator*=(bfloat16& a, // NOLINT + const bfloat16& b) { + a = bfloat16(static_cast(a) * static_cast(b)); + return a; +} + +HOSTDEVICE inline bfloat16& operator/=(bfloat16& a, // NOLINT + const bfloat16& b) { + a = bfloat16(static_cast(a) / static_cast(b)); + return a; +} + +HOSTDEVICE inline bfloat16 raw_uint16_to_bfloat16(uint16_t a) { + bfloat16 res; + res.x = a; + return res; +} + +// Comparison operators +HOSTDEVICE inline bool operator==(const bfloat16& a, const bfloat16& b) { + return static_cast(a) == static_cast(b); +} + +HOSTDEVICE inline bool operator!=(const bfloat16& a, const bfloat16& b) { + return static_cast(a) != static_cast(b); +} + +HOSTDEVICE inline bool operator<(const bfloat16& a, const bfloat16& b) { + return static_cast(a) < static_cast(b); +} + +HOSTDEVICE inline bool operator<=(const bfloat16& a, const bfloat16& b) { + return static_cast(a) <= static_cast(b); +} + +HOSTDEVICE inline bool operator>(const bfloat16& a, const bfloat16& b) { + return static_cast(a) > static_cast(b); +} + +HOSTDEVICE inline bool operator>=(const bfloat16& a, const bfloat16& b) { + return static_cast(a) >= static_cast(b); +} + +HOSTDEVICE inline bool(isnan)(const bfloat16& a) { + return (a.x & 0x7FFF) > 0x7F80; +} + +HOSTDEVICE inline bool(isinf)(const bfloat16& a) { + return (a.x & 0x7F80) == 0x7F80; +} + +HOSTDEVICE inline bool(isfinite)(const bfloat16& a) { + return !((isnan)(a)) && !((isinf)(a)); +} + +HOSTDEVICE inline bfloat16(abs)(const bfloat16& a) { + return bfloat16(std::abs(static_cast(a))); +} + +inline std::ostream& operator<<(std::ostream& os, const bfloat16& a) { + os << static_cast(a); + return os; +} + +} // namespace dtype +} // namespace phi + +namespace std { + +template <> +struct is_pod { + static const bool value = is_trivial::value && + is_standard_layout::value; +}; + +template <> +struct is_floating_point + : std::integral_constant< + bool, + std::is_same< + phi::dtype::bfloat16, + typename std::remove_cv::type>::value> {}; +template <> +struct is_signed { + static const bool value = true; +}; + +template <> +struct is_unsigned { + static const bool value = false; +}; + +inline bool isnan(const phi::dtype::bfloat16& a) { + return phi::dtype::isnan(a); +} + +inline bool isinf(const phi::dtype::bfloat16& a) { + return phi::dtype::isinf(a); +} + +template <> +struct numeric_limits { + static const bool is_specialized = true; + static const bool is_signed = true; + static const bool is_integer = false; + static const bool is_exact = false; + static const bool has_infinity = true; + static const bool has_quiet_NaN = true; + static const bool has_signaling_NaN = true; + static const float_denorm_style has_denorm = denorm_present; + static const bool has_denorm_loss = false; + static const std::float_round_style round_style = std::round_to_nearest; + static const bool is_iec559 = false; + static const bool is_bounded = false; + static const bool is_modulo = false; + static const int digits = 8; + static const int digits10 = 2; + static const int max_digits10 = 9; + static const int radix = 2; + static const int min_exponent = -125; + static const int min_exponent10 = -37; + static const int max_exponent = 128; + static const int max_exponent10 = 38; + static const bool traps = true; + static const bool tinyness_before = false; + + HOSTDEVICE static phi::dtype::bfloat16(min)() { + return phi::dtype::raw_uint16_to_bfloat16(0x007f); + } + HOSTDEVICE static phi::dtype::bfloat16 lowest() { + return phi::dtype::raw_uint16_to_bfloat16(0xff7f); + } + HOSTDEVICE static phi::dtype::bfloat16(max)() { + return phi::dtype::raw_uint16_to_bfloat16(0x7f7f); + } + HOSTDEVICE static phi::dtype::bfloat16 epsilon() { + return phi::dtype::raw_uint16_to_bfloat16(0x3400); + } + HOSTDEVICE static phi::dtype::bfloat16 round_error() { + return phi::dtype::bfloat16(0.5); + } + HOSTDEVICE static phi::dtype::bfloat16 infinity() { + return phi::dtype::raw_uint16_to_bfloat16(0x7f80); + } + HOSTDEVICE static phi::dtype::bfloat16 quiet_NaN() { + return phi::dtype::raw_uint16_to_bfloat16(0xffc1); + } + HOSTDEVICE static phi::dtype::bfloat16 signaling_NaN() { + return phi::dtype::raw_uint16_to_bfloat16(0xff81); + } + HOSTDEVICE static phi::dtype::bfloat16 denorm_min() { + return phi::dtype::raw_uint16_to_bfloat16(0x0001); + } +}; + +} // namespace std diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/complex.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/complex.h new file mode 100644 index 0000000000000000000000000000000000000000..25e9c4acac1a9191adfa60cf1fefc0bb4ee9110c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/complex.h @@ -0,0 +1,548 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include +#include +#include +#include +#ifdef PADDLE_WITH_CUDA +#include +#include +#endif // PADDLE_WITH_CUDA + +#ifdef PADDLE_WITH_HIP +#include +#include // NOLINT +#endif + +#if !defined(_WIN32) +#define PADDLE_ALIGN(x) __attribute__((aligned(x))) +#else +#define PADDLE_ALIGN(x) __declspec(align(x)) +#endif + +#if (defined(__CUDACC__) || defined(__HIPCC__)) +#define HOSTDEVICE __host__ __device__ +#define DEVICE __device__ +#define HOST __host__ +#else +#define HOSTDEVICE +#define DEVICE +#define HOST +#endif + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) +// todo +#define PADDLE_WITH_CUDA_OR_HIP_COMPLEX +#endif + +namespace phi { +namespace dtype { + +template +struct PADDLE_ALIGN(sizeof(T) * 2) complex { + public: + T real; + T imag; + + using value_type = T; + + complex() = default; + complex(const complex& o) = default; + complex& operator=(const complex& o) = default; + complex(complex&& o) = default; + complex& operator=(complex&& o) = default; + ~complex() = default; + + HOSTDEVICE complex(T real, T imag) : real(real), imag(imag) {} + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + + template + HOSTDEVICE inline explicit complex(const thrust::complex& c) { + real = c.real(); + imag = c.imag(); + } + + template + HOSTDEVICE inline explicit operator thrust::complex() const { + return thrust::complex(real, imag); + } + +#ifdef PADDLE_WITH_HIP + HOSTDEVICE inline explicit operator hipFloatComplex() const { + return make_hipFloatComplex(real, imag); + } + + HOSTDEVICE inline explicit operator hipDoubleComplex() const { + return make_hipDoubleComplex(real, imag); + } +#else + HOSTDEVICE inline explicit operator cuFloatComplex() const { + return make_cuFloatComplex(real, imag); + } + + HOSTDEVICE inline explicit operator cuDoubleComplex() const { + return make_cuDoubleComplex(real, imag); + } +#endif +#endif + + template ::value || + std::is_integral::value, + int>::type = 0> + HOSTDEVICE complex(const T1& val) { + real = static_cast(val); + imag = static_cast(0.0); + } + + template + HOSTDEVICE explicit complex( + const std::enable_if_t::value, complex>& + val) { + real = val.real; + imag = val.imag; + } + + template + HOSTDEVICE explicit complex( + const std::enable_if_t::value, complex>& + val) { + real = val.real; + imag = val.imag; + } + + template + HOSTDEVICE inline explicit operator std::complex() const { + return static_cast>(std::complex(real, imag)); + } + + template + HOSTDEVICE complex(const std::complex& val) + : real(val.real()), imag(val.imag()) {} + + template ::value || + std::is_integral::value, + int>::type = 0> + HOSTDEVICE inline complex& operator=(const T1& val) { + real = static_cast(val); + imag = static_cast(0.0); + return *this; + } + + HOSTDEVICE inline explicit operator bool() const { + return static_cast(this->real) || static_cast(this->imag); + } + + HOSTDEVICE inline explicit operator int8_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator uint8_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator int16_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator uint16_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator int32_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator uint32_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator int64_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator uint64_t() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator float() const { + return static_cast(this->real); + } + + HOSTDEVICE inline explicit operator double() const { + return static_cast(this->real); + } +}; + +template +HOSTDEVICE inline complex operator+(const complex& a, + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::complex(a) + thrust::complex(b)); +#else + return complex(a.real + b.real, a.imag + b.imag); +#endif +} + +template +HOSTDEVICE inline complex operator-(const complex& a, + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::complex(a) - thrust::complex(b)); +#else + return complex(a.real - b.real, a.imag - b.imag); +#endif +} + +template +HOSTDEVICE inline complex operator*(const complex& a, + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::complex(a) * thrust::complex(b)); +#else + return complex(a.real * b.real - a.imag * b.imag, + a.imag * b.real + b.imag * a.real); +#endif +} + +template +HOSTDEVICE inline complex operator/(const complex& a, + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::complex(a) / thrust::complex(b)); +#else + T denominator = b.real * b.real + b.imag * b.imag; + return complex((a.real * b.real + a.imag * b.imag) / denominator, + (a.imag * b.real - a.real * b.imag) / denominator); +#endif +} + +template +HOSTDEVICE inline complex operator-(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(-thrust::complex(a.real, a.imag)); +#else + complex res; + res.real = -a.real; + res.imag = -a.imag; + return res; +#endif +} + +template +HOSTDEVICE inline complex& operator+=(complex& a, // NOLINT + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + a = complex(thrust::complex(a.real, a.imag) += + thrust::complex(b.real, b.imag)); + return a; +#else + a.real += b.real; + a.imag += b.imag; + return a; +#endif +} + +template +HOSTDEVICE inline complex& operator-=(complex& a, // NOLINT + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + a = complex(thrust::complex(a.real, a.imag) -= + thrust::complex(b.real, b.imag)); + return a; +#else + a.real -= b.real; + a.imag -= b.imag; + return a; +#endif +} + +template +HOSTDEVICE inline complex& operator*=(complex& a, // NOLINT + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + a = complex(thrust::complex(a.real, a.imag) *= + thrust::complex(b.real, b.imag)); + return a; +#else + a.real = a.real * b.real - a.imag * b.imag; + a.imag = a.imag * b.real + b.imag * a.real; + return a; +#endif +} + +template +HOSTDEVICE inline complex& operator/=(complex& a, // NOLINT + const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + a = complex(thrust::complex(a.real, a.imag) /= + thrust::complex(b.real, b.imag)); + return a; +#else + T denominator = b.real * b.real + b.imag * b.imag; + a.real = (a.real * b.real + a.imag * b.imag) / denominator; + a.imag = (a.imag * b.real - a.real * b.imag) / denominator; + return a; +#endif +} + +template +HOSTDEVICE inline complex raw_uint16_to_complex64(uint16_t a) { + complex res; + res.real = a; + res.imag = 0.0; + return res; +} + +template +HOSTDEVICE inline bool operator==(const complex& a, const complex& b) { + return a.real == b.real && a.imag == b.imag; +} + +template +HOSTDEVICE inline bool operator!=(const complex& a, const complex& b) { + return a.real != b.real || a.imag != b.imag; +} + +template +HOSTDEVICE inline bool operator<(const complex& a, const complex& b) { + return a.real < b.real; +} + +template +HOSTDEVICE inline bool operator<=(const complex& a, const complex& b) { + return a.real <= b.real; +} + +template +HOSTDEVICE inline bool operator>(const complex& a, const complex& b) { + return a.real > b.real; +} + +template +HOSTDEVICE inline bool operator>=(const complex& a, const complex& b) { + return a.real >= b.real; +} + +template +HOSTDEVICE inline complex(max)(const complex& a, const complex& b) { + return (a.real >= b.real) ? a : b; +} + +template +HOSTDEVICE inline complex(min)(const complex& a, const complex& b) { + return (a.real < b.real) ? a : b; +} + +template +HOSTDEVICE inline bool(isnan)(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return ::isnan(a.real) || ::isnan(a.imag); +#else + return std::isnan(a.real) || std::isnan(a.imag); +#endif +} + +template +HOSTDEVICE inline bool isinf(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return ::isinf(a.real) || ::isinf(a.imag); +#else + return std::isinf(a.real) || std::isinf(a.imag); +#endif +} + +template +HOSTDEVICE inline bool isfinite(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return ::isfinite(a.real) || ::isfinite(a.imag); +#else + return std::isfinite(a.real) || std::isfinite(a.imag); +#endif +} + +template +HOSTDEVICE inline T abs(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return thrust::abs(thrust::complex(a)); +#else + return std::abs(std::complex(a)); +#endif +} + +template +HOSTDEVICE inline T arg(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return thrust::arg(thrust::complex(a)); +#else + return std::arg(std::complex(a)); +#endif +} + +template +HOSTDEVICE inline complex pow(const complex& a, const complex& b) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::pow(thrust::complex(a), thrust::complex(b))); +#else + return complex(std::pow(std::complex(a), std::complex(b))); +#endif +} + +template +HOSTDEVICE inline complex sqrt(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::sqrt(thrust::complex(a))); +#else + return complex(std::sqrt(std::complex(a))); +#endif +} + +template +HOSTDEVICE inline complex tanh(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::tanh(thrust::complex(a))); +#else + return complex(std::tanh(std::complex(a))); +#endif +} + +template +HOSTDEVICE inline complex log(const complex& a) { +#if defined(PADDLE_WITH_CUDA_OR_HIP_COMPLEX) && \ + (defined(__CUDA_ARCH__) || defined(__HIPCC__)) + return complex(thrust::log(thrust::complex(a))); +#else + return complex(std::log(std::complex(a))); +#endif +} + +template +inline std::ostream& operator<<(std::ostream& os, const complex& a) { + os << "real:" << a.real << " imag:" << a.imag; + return os; +} +} // namespace dtype +} // namespace phi + +namespace std { + +template +struct is_pod> { + static const bool value = true; +}; + +template +struct is_floating_point> + : std::integral_constant {}; + +template +struct is_signed> { + static const bool value = false; +}; + +template +struct is_unsigned> { + static const bool value = false; +}; + +template +inline bool isnan(const phi::dtype::complex& a) { + return phi::dtype::isnan(a); +} + +template +inline bool isinf(const phi::dtype::complex& a) { + return phi::dtype::isinf(a); +} + +template +struct numeric_limits> { + static const bool is_specialized = false; + static const bool is_signed = false; + static const bool is_integer = false; + static const bool is_exact = false; + static const bool has_infinity = false; + static const bool has_quiet_NaN = false; + static const bool has_signaling_NaN = false; + static const float_denorm_style has_denorm = denorm_absent; + static const bool has_denorm_loss = false; + static const std::float_round_style round_style = std::round_toward_zero; + static const bool is_iec559 = false; + static const bool is_bounded = false; + static const bool is_modulo = false; + static const int digits = 0; + static const int digits10 = 0; + static const int max_digits10 = 0; + static const int radix = 0; + static const int min_exponent = 0; + static const int min_exponent10 = 0; + static const int max_exponent = 0; + static const int max_exponent10 = 0; + static const bool traps = false; + static const bool tinyness_before = false; + + static phi::dtype::complex(min)() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex lowest() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex(max)() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex epsilon() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex round_error() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex infinity() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex quiet_NaN() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex signaling_NaN() { + return phi::dtype::complex(0.0, 0.0); + } + static phi::dtype::complex denorm_min() { + return phi::dtype::complex(0.0, 0.0); + } +}; + +} // namespace std diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/cpstring_impl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/cpstring_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..99a04e7ce49244cb24672ed91c7b2cb408e3fef2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/cpstring_impl.h @@ -0,0 +1,547 @@ +/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. + Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +This file is inspired by + + https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/platform/ctstring_internal.h + +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. */ + +#pragma once + +#include +#include +#include +#include + +#if (defined(__NVCC__) || defined(__HIPCC__)) +#define HOSTDEVICE __host__ __device__ +#define DEVICE __device__ +#define HOST __host__ +#else +#define HOSTDEVICE +#define DEVICE +#define HOST +#endif + +#if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || \ + defined(_WIN32) +#define PD_PSTRING_LITTLE_ENDIAN 1 +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define PD_PSTRING_LITTLE_ENDIAN 0 +#else +#error "Unable to detect endianness." +#endif + +#if defined(__clang__) || \ + (defined(__GNUC__) && \ + ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ >= 5)) +HOSTDEVICE static inline uint32_t swap32(uint32_t host_int) { + return __builtin_bswap32(host_int); +} + +#elif defined(_MSC_VER) +HOSTDEVICE static inline uint32_t swap32(uint32_t host_int) { + return _byteswap_ulong(host_int); +} + +#elif defined(__APPLE__) +HOSTDEVICE static inline uint32_t swap32(uint32_t host_int) { + return OSSwapInt32(host_int); +} + +#else +HOSTDEVICE static inline uint32_t swap32(uint32_t host_int) { +#if defined(__GLIBC__) + return bswap_32(host_int); +#else // defined(__GLIBC__) + return (((host_int & uint32_t{0xFF}) << 24) | + ((host_int & uint32_t{0xFF00}) << 8) | + ((host_int & uint32_t{0xFF0000}) >> 8) | + ((host_int & uint32_t{0xFF000000}) >> 24)); +#endif // defined(__GLIBC__) +} +#endif + +#if PD_PSTRING_LITTLE_ENDIAN || (defined(__NVCC__) || defined(__HIPCC__)) +#define PD_le32toh(x) x +#else // PD_PSTRING_LITTLE_ENDIAN +#define PD_le32toh(x) swap32(x) +#endif // PD_PSTRING_LARGE_ENDIAN + +HOSTDEVICE static inline size_t PD_align16(size_t i) { + return (i + 0xF) & ~0xF; +} + +HOSTDEVICE static inline size_t PD_max(size_t a, size_t b) { + return a > b ? a : b; +} +HOSTDEVICE static inline size_t PD_min(size_t a, size_t b) { + return a < b ? a : b; +} + +typedef enum PD_PString_Type { // NOLINT + PD_PSTR_SMALL = 0x00, + PD_PSTR_LARGE = 0x01, + PD_PSTR_OFFSET = 0x02, + PD_PSTR_VIEW = 0x03, + PD_PSTR_TYPE_MASK = 0x03 +} PD_PString_Type; + +typedef struct PD_PString_Large { // NOLINT + size_t size; + size_t cap; + char *ptr; +} PD_PString_Large; + +typedef struct PD_PString_Offset { // NOLINT + uint32_t size; + uint32_t offset; + uint32_t count; +} PD_PString_Offset; + +typedef struct PD_PString_View { // NOLINT + size_t size; + const char *ptr; +} PD_PString_View; + +typedef struct PD_PString_Raw { // NOLINT + uint8_t raw[24]; +} PD_PString_Raw; + +typedef union PD_PString_Union { // NOLINT + PD_PString_Large large; + PD_PString_Offset offset; + PD_PString_View view; + PD_PString_Raw raw; +} PD_PString_Union; + +enum { + PD_PString_SmallCapacity = + (sizeof(PD_PString_Union) - sizeof(/* null delim */ char) - + sizeof(/* uint8_t size */ uint8_t)), +}; + +typedef struct PD_PString_Small { // NOLINT + uint8_t size; + char str[PD_PString_SmallCapacity + sizeof(/* null delim */ char)]; +} PD_PString_Small; + +typedef struct PD_PString { // NOLINT + union { + PD_PString_Small smll; + PD_PString_Large large; + PD_PString_Offset offset; + PD_PString_View view; + PD_PString_Raw raw; + } u; +} PD_PString; + +HOSTDEVICE static inline PD_PString_Type PD_PString_GetType( + const PD_PString *str) { + return (PD_PString_Type)(str->u.raw.raw[0] & PD_PSTR_TYPE_MASK); // NOLINT +} + +HOSTDEVICE static inline size_t PD_PString_ToActualSizeT(size_t size) { +#if PD_PSTRING_LITTLE_ENDIAN + return size >> 2; +#else // PD_PSTRING_LITTLE_ENDIAN + // 0xFF000000 or 0xFF00000000000000 depending on platform + static const size_t mask = ~((~(size_t)0) >> 8); // NOLINT + + return (((mask << 2) & size) >> 2) | (~mask & size); +#endif // PD_PSTRING_LITTLE_ENDIAN +} + +HOSTDEVICE static inline size_t PD_PString_ToInternalSizeT( + size_t size, PD_PString_Type type) { +#if PD_PSTRING_LITTLE_ENDIAN + return (size << 2) | type; +#else // PD_PSTRING_LITTLE_ENDIAN + // 0xFF000000 or 0xFF00000000000000 depending on platform + static const size_t mask = ~((~(size_t)0) >> 8); // NOLINT + + return (mask & (size << 2)) | (~mask & size) | + ((size_t)type << ((sizeof(size_t) - 1) * 8)); // NOLINT +#endif // PD_PSTRING_LITTLE_ENDIAN +} + +/* + * Need to implement in other source file. + */ +HOSTDEVICE static inline void PD_Free(void *ptr, size_t size) { free(ptr); } + +HOSTDEVICE static inline void *PD_Memset(void *src, int ch, size_t size) { + char *dst = (char *)src; // NOLINT + for (size_t i = 0; i < size; ++i) { + dst[i] = ch; + } + return dst; +} + +HOSTDEVICE static inline void *PD_Memcpy(void *dst, + const void *src, + size_t size) { + for (size_t i = 0; i < size; ++i) { + ((char *)dst)[i] = ((const char *)src)[i]; // NOLINT + } + return dst; +} + +HOSTDEVICE static inline void *PD_Malloc(size_t size) { return malloc(size); } + +HOSTDEVICE static inline void *PD_Realloc(void *ptr, + size_t old_size, + size_t new_size) { +#if (defined(__NVCC__) || defined(__HIPCC__)) + if (old_size >= new_size) { + return ptr; + } + void *new_ptr = malloc(new_size); + PD_Memcpy(new_ptr, ptr, old_size); + free(ptr); + return new_ptr; +#else + return realloc(ptr, new_size); +#endif +} + +HOSTDEVICE static inline int PD_Memcmp(const void *s1, + const void *s2, + size_t size) { + const uint8_t *lstr = (const uint8_t *)(s1); // NOLINT + const uint8_t *rstr = (const uint8_t *)(s2); // NOLINT + for (size_t i = 0; i < size; ++i) { + if (lstr[i] != rstr[i]) { + return (lstr[i] - rstr[i]); + } + } + return 0; +} + +HOSTDEVICE static inline void *PD_Memmove(void *dest, + const void *src, + size_t size) { + const uint8_t *from = (const uint8_t *)(src); // NOLINT + uint8_t *to = (uint8_t *)(dest); // NOLINT + if (from == to || size == 0) { + return dest; + } + + if (to > from && (to - from < static_cast(size))) { + for (int i = size - 1; i >= 0; i--) { + to[i] = from[i]; + } + return dest; + } + if (from > to && (from - to < static_cast(size))) { + for (size_t i = 0; i < size; i++) { + to[i] = from[i]; + } + return dest; + } + dest = PD_Memcpy(dest, src, size); + return dest; +} + +HOSTDEVICE static inline void PD_PString_Init(PD_PString *str) { + PD_Memset(str->u.raw.raw, 0, sizeof(PD_PString_Raw)); +} + +HOSTDEVICE static inline void PD_PString_Dealloc(PD_PString *str) { + if (PD_PString_GetType(str) == PD_PSTR_LARGE && + str->u.large.ptr != NULL) { // NOLINT + PD_Free(str->u.large.ptr, str->u.large.cap + 1); + PD_PString_Init(str); + } +} + +HOSTDEVICE static inline size_t PD_PString_GetSize(const PD_PString *str) { + switch (PD_PString_GetType(str)) { + case PD_PSTR_SMALL: + return str->u.smll.size >> 2; + case PD_PSTR_LARGE: + return PD_PString_ToActualSizeT(str->u.large.size); + case PD_PSTR_OFFSET: + return PD_le32toh(str->u.offset.size) >> 2; + case PD_PSTR_VIEW: + return PD_PString_ToActualSizeT(str->u.view.size); + default: + return 0; // Unreachable. + } +} + +HOSTDEVICE static inline size_t PD_PString_GetCapacity(const PD_PString *str) { + switch (PD_PString_GetType(str)) { + case PD_PSTR_SMALL: + return PD_PString_SmallCapacity; + case PD_PSTR_LARGE: + return str->u.large.cap; + case PD_PSTR_OFFSET: + case PD_PSTR_VIEW: + default: + return 0; + } +} + +HOSTDEVICE static inline const char *PD_PString_GetDataPointer( + const PD_PString *str) { + switch (PD_PString_GetType(str)) { + case PD_PSTR_SMALL: + return str->u.smll.str; + case PD_PSTR_LARGE: + return str->u.large.ptr; + case PD_PSTR_OFFSET: + return (const char *)str + str->u.offset.offset; // NOLINT + case PD_PSTR_VIEW: + return str->u.view.ptr; + default: + // Unreachable. + return NULL; // NOLINT + } +} + +HOSTDEVICE static inline char *PD_PString_ResizeUninitialized(PD_PString *str, + size_t new_size) { + size_t curr_size = PD_PString_GetSize(str); + size_t copy_size = PD_min(new_size, curr_size); + + PD_PString_Type curr_type = PD_PString_GetType(str); + const char *curr_ptr = PD_PString_GetDataPointer(str); + + // Case: SMALL/LARGE/VIEW/OFFSET -> SMALL + if (new_size <= PD_PString_SmallCapacity) { + str->u.smll.size = (uint8_t)((new_size << 2) | PD_PSTR_SMALL); // NOLINT + str->u.smll.str[new_size] = '\0'; + + if (curr_type != PD_PSTR_SMALL && copy_size) { + PD_Memcpy(str->u.smll.str, curr_ptr, copy_size); + } + + if (curr_type == PD_PSTR_LARGE) { + PD_Free((void *)curr_ptr, str->u.large.cap + 1); // NOLINT + } + + return str->u.smll.str; + } + + // Case: SMALL/LARGE/VIEW/OFFSET -> LARGE + size_t new_cap; + size_t curr_cap = PD_PString_GetCapacity(str); + + if (new_size < curr_size && new_size < curr_cap / 2) { + new_cap = PD_align16(curr_cap / 2 + 1) - 1; + } else if (new_size > curr_cap) { + new_cap = PD_align16(new_size + 1) - 1; + } else { + new_cap = curr_cap; + } + + char *new_ptr; + if (new_cap == curr_cap) { + new_ptr = str->u.large.ptr; + } else if (curr_type == PD_PSTR_LARGE) { + new_ptr = (char *)PD_Realloc( // NOLINT + str->u.large.ptr, + curr_cap + 1, + new_cap + 1); + } else { + new_ptr = (char *)PD_Malloc(new_cap + 1); // NOLINT + if (copy_size) { + PD_Memcpy(new_ptr, curr_ptr, copy_size); + } + } + + str->u.large.size = PD_PString_ToInternalSizeT(new_size, PD_PSTR_LARGE); + str->u.large.ptr = new_ptr; + str->u.large.ptr[new_size] = '\0'; + str->u.large.cap = new_cap; + + return str->u.large.ptr; +} + +HOSTDEVICE static inline char *PD_PString_GetMutableDataPointer( + PD_PString *str) { + switch (PD_PString_GetType(str)) { + case PD_PSTR_SMALL: + return str->u.smll.str; + case PD_PSTR_OFFSET: + case PD_PSTR_VIEW: + // Convert OFFSET/VIEW to SMALL/LARGE + PD_PString_ResizeUninitialized(str, PD_PString_GetSize(str)); + return (PD_PString_GetType(str) == PD_PSTR_SMALL) ? str->u.smll.str + : str->u.large.ptr; + case PD_PSTR_LARGE: + return str->u.large.ptr; + default: + // Unreachable. + return NULL; // NOLINT + } +} + +HOSTDEVICE static inline void PD_PString_Reserve(PD_PString *str, + size_t new_cap) { + PD_PString_Type curr_type = PD_PString_GetType(str); + + if (new_cap <= PD_PString_SmallCapacity) { + // We do nothing, we let Resize/GetMutableDataPointer handle the + // conversion to SMALL from VIEW/OFFSET when the need arises. + // In the degenerate case, where new_cap <= PD_PString_SmallCapacity, + // curr_size > PD_PString_SmallCapacity, and the type is VIEW/OFFSET, we + // defer the malloc to Resize/GetMutableDataPointer. + return; + } + + if (curr_type == PD_PSTR_LARGE && new_cap <= str->u.large.cap) { + // We handle reduced cap in resize. + return; + } + + // Case: VIEW/OFFSET -> LARGE or grow an existing LARGE type + size_t curr_size = PD_PString_GetSize(str); + const char *curr_ptr = PD_PString_GetDataPointer(str); + + // Since VIEW and OFFSET types are read-only, their capacity is effectively 0. + // So we make sure we have enough room in the VIEW and OFFSET cases. + new_cap = PD_align16(PD_max(new_cap, curr_size) + 1) - 1; + size_t curr_cap = PD_PString_GetCapacity(str); + + if (curr_type == PD_PSTR_LARGE) { + str->u.large.ptr = (char *)PD_Realloc( // NOLINT + str->u.large.ptr, + curr_cap + 1, + new_cap + 1); + } else { + // Convert to Large + char *new_ptr = (char *)PD_Malloc(new_cap + 1); // NOLINT + PD_Memcpy(new_ptr, curr_ptr, curr_size); + + str->u.large.size = PD_PString_ToInternalSizeT(curr_size, PD_PSTR_LARGE); + str->u.large.ptr = new_ptr; + str->u.large.ptr[curr_size] = '\0'; + } + + str->u.large.cap = new_cap; +} + +HOSTDEVICE static inline void PD_PString_ReserveAmortized(PD_PString *str, + size_t new_cap) { + const size_t curr_cap = PD_PString_GetCapacity(str); + if (new_cap > curr_cap) { + PD_PString_Reserve(str, new_cap > 2 * curr_cap ? new_cap : 2 * curr_cap); + } +} + +HOSTDEVICE static inline char *PD_PString_Resize(PD_PString *str, + size_t new_size, + char c) { + size_t curr_size = PD_PString_GetSize(str); + char *cstr = PD_PString_ResizeUninitialized(str, new_size); + + if (new_size > curr_size) { + PD_Memset(cstr + curr_size, c, new_size - curr_size); + } + + return cstr; +} + +HOSTDEVICE static inline void PD_PString_AssignView(PD_PString *dst, + const char *src, + size_t size) { + PD_PString_Dealloc(dst); + + dst->u.view.size = PD_PString_ToInternalSizeT(size, PD_PSTR_VIEW); + dst->u.view.ptr = src; +} + +HOSTDEVICE static inline void PD_PString_AppendN(PD_PString *dst, + const char *src, + size_t src_size) { + if (!src_size) return; + + size_t dst_size = PD_PString_GetSize(dst); + + // For append use cases, we want to ensure amortized growth. + PD_PString_ReserveAmortized(dst, dst_size + src_size); + char *dst_c = PD_PString_ResizeUninitialized(dst, dst_size + src_size); + + PD_Memcpy(dst_c + dst_size, src, src_size); +} + +HOSTDEVICE static inline void PD_PString_Append(PD_PString *dst, + const PD_PString *src) { + const char *src_c = PD_PString_GetDataPointer(src); + size_t size = PD_PString_GetSize(src); + + PD_PString_AppendN(dst, src_c, size); +} + +HOSTDEVICE static inline void PD_PString_Copy(PD_PString *dst, + const char *src, + size_t size) { + char *dst_c = PD_PString_ResizeUninitialized(dst, size); + + if (size) PD_Memcpy(dst_c, src, size); +} + +HOSTDEVICE static inline void PD_PString_Assign(PD_PString *dst, + const PD_PString *src) { + if (dst == src) return; + + PD_PString_Dealloc(dst); + + switch (PD_PString_GetType(src)) { + case PD_PSTR_SMALL: + case PD_PSTR_VIEW: + *dst = *src; + return; + case PD_PSTR_LARGE: { + const char *src_c = PD_PString_GetDataPointer(src); + size_t size = PD_PString_GetSize(src); + + PD_PString_Copy(dst, src_c, size); + } + return; + default: + return; // Unreachable. + } +} + +HOSTDEVICE static inline void PD_PString_Move(PD_PString *dst, + PD_PString *src) { + if (dst == src) return; + + PD_PString_Dealloc(dst); + + switch (PD_PString_GetType(src)) { + case PD_PSTR_SMALL: + case PD_PSTR_VIEW: + *dst = *src; + return; + case PD_PSTR_LARGE: + *dst = *src; + PD_PString_Init(src); + return; + case PD_PSTR_OFFSET: { + const char *src_c = PD_PString_GetDataPointer(src); + size_t size = PD_PString_GetSize(src); + + PD_PString_AssignView(dst, src_c, size); + } + return; + default: + return; // Unreachable. + } +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/data_type.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..e9dc01687ec4bf21218016da9ff3323e7d436ddd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/data_type.h @@ -0,0 +1,231 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/common/bfloat16.h" +#include "paddle/phi/common/complex.h" +#include "paddle/phi/common/float16.h" + +namespace phi { +namespace dtype { +class pstring; +} // namespace dtype +} // namespace phi + +namespace paddle { +namespace experimental { + +using complex64 = ::phi::dtype::complex; +using complex128 = ::phi::dtype::complex; +using float16 = ::phi::dtype::float16; +using bfloat16 = ::phi::dtype::bfloat16; +using pstring = ::phi::dtype::pstring; + +// The enum valuea are consistent with jit/property.proto +enum class DataType { + UNDEFINED = 0, + + BOOL, + + UINT8, // BYte + INT8, // Char + UINT16, + INT16, + UINT32, + INT32, + UINT64, + INT64, + + FLOAT32, + FLOAT64, + + COMPLEX64, + COMPLEX128, + + // In Paddle 2.3, we add a new type of Tensor, StringTensor, which is designed + // for string data management. We design the dtype of StringTensor, pstring. + // In order to express a unique data dtype of StringTensor, we add + // DataType::PSTRING. + PSTRING, + + // IEEE754 half-precision floating-point format (16 bits wide). + // This format has 1 sign bit, 5 exponent bits, and 10 mantissa bits. + FLOAT16, + + // Non-IEEE floating-point format based on IEEE754 single-precision + // floating-point number truncated to 16 bits. + // This format has 1 sign bit, 8 exponent bits, and 7 mantissa bits. + BFLOAT16, + + NUM_DATA_TYPES, + // See Note [ Why we need ALL in baisc kernel key member? ] + ALL_DTYPE = UNDEFINED, +}; + +inline size_t SizeOf(DataType data_type) { + switch (data_type) { + case DataType::BOOL: + case DataType::UINT8: + case DataType::INT8: + return 1; + case DataType::BFLOAT16: + case DataType::FLOAT16: + case DataType::INT16: + case DataType::UINT16: + return 2; + case DataType::FLOAT32: + case DataType::INT32: + case DataType::UINT32: + return 4; + case DataType::FLOAT64: + case DataType::INT64: + case DataType::UINT64: + case DataType::COMPLEX64: + return 8; + case DataType::COMPLEX128: + return 16; + case DataType::PSTRING: + return 24; + case DataType::UNDEFINED: + return 0; + case DataType::NUM_DATA_TYPES: + PD_THROW("Data type `", + static_cast(data_type), + "` is not supported by tensor."); + } + return 0; +} + +#define PD_FOR_EACH_DATA_TYPE(_) \ + _(bool, DataType::BOOL) \ + _(int8_t, DataType::INT8) \ + _(uint8_t, DataType::UINT8) \ + _(int16_t, DataType::INT16) \ + _(uint16_t, DataType::UINT16) \ + _(int32_t, DataType::INT32) \ + _(uint32_t, DataType::UINT32) \ + _(int64_t, DataType::INT64) \ + _(uint64_t, DataType::UINT64) \ + _(bfloat16, DataType::BFLOAT16) \ + _(float16, DataType::FLOAT16) \ + _(float, DataType::FLOAT32) \ + _(double, DataType::FLOAT64) \ + _(complex64, DataType::COMPLEX64) \ + _(complex128, DataType::COMPLEX128) \ + _(pstring, DataType::PSTRING) + +template +struct DataTypeToCppType; + +template +struct CppTypeToDataType; + +#define PD_SPECIALIZE_DataTypeToCppType(cpp_type, data_type) \ + template <> \ + struct DataTypeToCppType { \ + using type = cpp_type; \ + }; + +PD_FOR_EACH_DATA_TYPE(PD_SPECIALIZE_DataTypeToCppType) + +#undef PD_SPECIALIZE_DataTypeToCppType + +#define PD_SPECIALIZE_CppTypeToDataType(cpp_type, data_type) \ + template <> \ + struct CppTypeToDataType { \ + constexpr static DataType Type() { return data_type; } \ + }; + +PD_FOR_EACH_DATA_TYPE(PD_SPECIALIZE_CppTypeToDataType) + +#undef PD_SPECIALIZE_CppTypeToDataType + +inline std::ostream& operator<<(std::ostream& os, DataType dtype) { + switch (dtype) { + case DataType::UNDEFINED: + os << "Undefined"; + break; + case DataType::BOOL: + os << "bool"; + break; + case DataType::INT8: + os << "int8"; + break; + case DataType::UINT8: + os << "uint8"; + break; + case DataType::INT16: + os << "int16"; + break; + case DataType::UINT16: + os << "uint16"; + break; + case DataType::INT32: + os << "int32"; + break; + case DataType::UINT32: + os << "uint32"; + break; + case DataType::INT64: + os << "int64"; + break; + case DataType::UINT64: + os << "uint64"; + break; + case DataType::BFLOAT16: + os << "bfloat16"; + break; + case DataType::FLOAT16: + os << "float16"; + break; + case DataType::FLOAT32: + os << "float32"; + break; + case DataType::FLOAT64: + os << "float64"; + break; + case DataType::COMPLEX64: + os << "complex64"; + break; + case DataType::COMPLEX128: + os << "complex128"; + break; + case DataType::PSTRING: + os << "pstring"; + break; + default: + PD_THROW("Invalid enum data type `", static_cast(dtype), "`."); + } + return os; +} + +} // namespace experimental +} // namespace paddle + +namespace phi { +using DataType = paddle::experimental::DataType; +} // namespace phi + +namespace paddle { +// In order to be compatible with the original custom operator Tensor interface +using DataType = paddle::experimental::DataType; +using bfloat16 = paddle::experimental::bfloat16; +using complex64 = paddle::experimental::complex64; +using complex128 = paddle::experimental::complex128; +using float16 = paddle::experimental::float16; +using pstring = paddle::experimental::pstring; + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/float16.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/float16.h new file mode 100644 index 0000000000000000000000000000000000000000..c401d8c6575e59bf976528fd6505bb82331f5dd6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/float16.h @@ -0,0 +1,1099 @@ +// Copyright (c) 2022 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. + +#pragma once + +#if defined(_M_X64) || defined(__x86_64__) || defined(_M_IX86) || \ + defined(__i386__) +#define __PADDLE_x86__ +#include +#endif +#include + +#include +#include +#include + +#ifdef PADDLE_WITH_CUDA +#include +#endif // PADDLE_WITH_CUDA + +#ifdef PADDLE_WITH_HIP +#include +#endif + +#if defined(__CUDACC__) && CUDA_VERSION >= 7050 +#define PADDLE_CUDA_FP16 +#include +#endif + +#ifdef __HIPCC__ +#define PADDLE_CUDA_FP16 +#include +#endif + +#if !defined(_WIN32) +#define PADDLE_ALIGN(x) __attribute__((aligned(x))) +#else +#define PADDLE_ALIGN(x) __declspec(align(x)) +#endif + +#define CUDA_ARCH_FP16_SUPPORTED(CUDA_ARCH) (CUDA_ARCH >= 600) + +#if (defined(__CUDACC__) || defined(__HIPCC__)) +#define HOSTDEVICE __host__ __device__ +#define DEVICE __device__ +#define HOST __host__ +#else +#define HOSTDEVICE +#define DEVICE +#define HOST +#endif + +namespace phi { +namespace dtype { + +// Use PADDLE_ALIGNED(2) to ensure that each float16 will be allocated +// and aligned at least on a 2-byte boundary, which leads to efficient +// memory access of float16 struct and also makes float16 compatible +// with CUDA half, ARM float16_t data types. +struct PADDLE_ALIGN(2) float16 { + public: + uint16_t x; + + // The following defaulted special class member functions + // are added to make float16 pass the std::is_trivial test + float16() = default; + float16(const float16& o) = default; + float16& operator=(const float16& o) = default; + float16(float16&& o) = default; + float16& operator=(float16&& o) = default; + ~float16() = default; + +// Constructors +#ifdef PADDLE_CUDA_FP16 + HOSTDEVICE inline explicit float16(const half& h) { +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) +#if defined(PADDLE_WITH_HIP) || CUDA_VERSION >= 9000 + x = reinterpret_cast<__half_raw*>(const_cast(&h))->x; +#else + x = h.x; +#endif // CUDA_VERSION >= 9000 +#endif + } +#endif // PADDLE_CUDA_FP16 + +#ifdef PADDLE_WITH_NATIVE_FP16 + // __fp16 is a native half precision data type for arm cpu, + // float16_t is an alias for __fp16 + HOSTDEVICE inline explicit float16(const float16_t& h) { + x = *reinterpret_cast(&h); + } +#endif + + HOSTDEVICE inline explicit float16(float val) { +#if defined(PADDLE_CUDA_FP16) && \ + (defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300)) + half tmp = __float2half(val); + x = *reinterpret_cast(&tmp); + +#elif defined(PADDLE_WITH_NATIVE_FP16) + float32x4_t tmp = vld1q_dup_f32(&val); + float16_t res = vget_lane_f16(vcvt_f16_f32(tmp), 0); + x = *reinterpret_cast(&res); + +#elif defined(__F16C__) and defined(__PADDLE_x86__) + x = _cvtss_sh(val, 0); + +#else + // Conversion routine adapted from + // http://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion + Bits v, s; + v.f = val; + uint32_t sign = v.si & sigN; + v.si ^= sign; + sign >>= shiftSign; // logical shift + s.si = mulN; + s.si = s.f * v.f; // correct subnormals + v.si ^= (s.si ^ v.si) & -(minN > v.si); + v.si ^= (infN ^ v.si) & -((infN > v.si) & (v.si > maxN)); + v.si ^= (nanN ^ v.si) & -((nanN > v.si) & (v.si > infN)); + v.ui >>= shift; // logical shift + v.si ^= ((v.si - maxD) ^ v.si) & -(v.si > maxC); + v.si ^= ((v.si - minD) ^ v.si) & -(v.si > subC); + x = v.ui | sign; + +#endif + } + + HOSTDEVICE inline explicit float16(bool b) : x(b ? 0x3c00 : 0) {} + + template + HOSTDEVICE inline explicit float16(const T& val) + : x(float16(static_cast(val)).x) {} + +// Assignment operators +#ifdef PADDLE_CUDA_FP16 + HOSTDEVICE inline float16& operator=(const half& rhs) { +#if defined(PADDLE_WITH_HIP) || CUDA_VERSION >= 9000 + x = reinterpret_cast<__half_raw*>(const_cast(&rhs))->x; +#else + x = rhs.x; +#endif + return *this; + } +#endif + +#ifdef PADDLE_WITH_NATIVE_FP16 + HOSTDEVICE inline float16& operator=(const float16_t& rhs) { + x = *reinterpret_cast(&rhs); + return *this; + } +#endif + + HOSTDEVICE inline float16& operator=(bool b) { + x = b ? 0x3c00 : 0; + return *this; + } + + HOSTDEVICE inline float16& operator=(int8_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(uint8_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(int16_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(uint16_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(int32_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(uint32_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(int64_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(uint64_t val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(float val) { + x = float16(val).x; + return *this; + } + + HOSTDEVICE inline float16& operator=(double val) { + x = float16(val).x; + return *this; + } + +// Conversion opertors +#ifdef PADDLE_CUDA_FP16 + HOSTDEVICE inline half to_half() const { +#if defined(PADDLE_WITH_HIP) || CUDA_VERSION >= 9000 + __half_raw h; + h.x = x; + return half(h); +#else + half h; + h.x = x; + return h; +#endif // CUDA_VERSION >= 9000 + } +#endif // PADDLE_CUDA_FP16 + +#ifdef PADDLE_WITH_NATIVE_FP16 + HOSTDEVICE inline explicit operator float16_t() const { + return *reinterpret_cast(this); + } +#endif + + HOSTDEVICE inline operator float() const { +#if defined(PADDLE_CUDA_FP16) && \ + (defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300)) + half tmp = *reinterpret_cast(this); + return __half2float(tmp); + +#elif defined(PADDLE_WITH_NATIVE_FP16) + float16x4_t res = vld1_dup_f16(reinterpret_cast(this)); + return vgetq_lane_f32(vcvt_f32_f16(res), 0); + +#elif defined(__F16C__) + return _cvtsh_ss(this->x); + +#else + // Conversion routine adapted from + // http://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion + Bits v; + v.ui = this->x; + int32_t sign = v.si & sigC; + v.si ^= sign; + sign <<= shiftSign; + v.si ^= ((v.si + minD) ^ v.si) & -(v.si > subC); + v.si ^= ((v.si + maxD) ^ v.si) & -(v.si > maxC); + Bits s; + s.si = mulC; + s.f *= v.si; + int32_t mask = -(norC > v.si); + v.si <<= shift; + v.si ^= (s.si ^ v.si) & mask; + v.si |= sign; + return v.f; + +#endif + } + + HOSTDEVICE inline explicit operator bool() const { return (x & 0x7fff) != 0; } + + HOSTDEVICE inline explicit operator int8_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint8_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int16_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint16_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int32_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint32_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator int64_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline explicit operator uint64_t() const { + return static_cast(static_cast(*this)); + } + + HOSTDEVICE inline operator double() const { + return static_cast(static_cast(*this)); + } + + private: + union Bits { + float f; + int32_t si; + uint32_t ui; + }; + + static const int shift = 13; + static const int shiftSign = 16; + + static const int32_t infN = 0x7F800000; + static const int32_t maxN = 0x477FE000; // max flt16 as flt32 + static const int32_t minN = 0x38800000; // min flt16 normal as flt32 + static const int32_t sigN = 0x80000000; // sign bit + + static constexpr int32_t infC = infN >> shift; + static constexpr int32_t nanN = (infC + 1) + << shift; // minimum flt16 nan as float32 + static constexpr int32_t maxC = maxN >> shift; + static constexpr int32_t minC = minN >> shift; + static constexpr int32_t sigC = sigN >> shiftSign; + + static const int32_t mulN = 0x52000000; // (1 << 23) / minN + static const int32_t mulC = 0x33800000; // minN / (1 << (23 - shift)) + static const int32_t subC = 0x003FF; // max flt32 subnormal downshifted + static const int32_t norC = 0x00400; // min flt32 normal downshifted + + static constexpr int32_t maxD = infC - maxC - 1; + static constexpr int32_t minD = minC - subC - 1; +}; + +// Arithmetic operators on GPU +// CUDA 9.0 provides built-in arithmetic operators for half while +// CUDA 7.5 and 8.0 do not. The arithmetic operators defined here are +// for users to write similar CUDA code in CUDA 7.5 and 8.0 as in +// CUDA 9.0 regarding the half data type. +// ROCM has built-in arithmetic operators as not defined +// __HIP_NO_HALF_OPERATORS__ +#if defined(PADDLE_CUDA_FP16) && !defined(__HIPCC__) && CUDA_VERSION < 9000 +DEVICE inline half operator+(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hadd(a, b); +#else + float res = static_cast(float16(a)) + static_cast(float16(b)); + return float16(res).to_half(); +#endif +} + +DEVICE inline half operator-(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hsub(a, b); +#else + float res = static_cast(float16(a)) - static_cast(float16(b)); + return float16(res).to_half(); +#endif +} + +DEVICE inline half operator*(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hmul(a, b); +#else + float res = static_cast(float16(a)) * static_cast(float16(b)); + return float16(res).to_half(); +#endif +} + +DEVICE inline half operator/(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + float num = __half2float(a); + float denom = __half2float(b); + return __float2half(num / denom); +#else + float res = static_cast(float16(a)) / static_cast(float16(b)); + return float16(res).to_half(); +#endif +} + +DEVICE inline half operator-(const half& a) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hneg(a); +#else + float res = -static_cast(float16(a)); + return float16(res).to_half(); +#endif +} + +#ifndef PADDLE_WITH_HIP // not defined __HIP_NO_HALF_OPERATORS__ +DEVICE inline half& operator+=(half& a, const half& b) { // NOLINT + a = a + b; + return a; +} + +DEVICE inline half& operator-=(half& a, const half& b) { // NOLINT + a = a - b; + return a; +} + +DEVICE inline half& operator*=(half& a, const half& b) { // NOLINT + a = a * b; + return a; +} + +DEVICE inline half& operator/=(half& a, const half& b) { // NOLINT + a = a / b; + return a; +} +#endif + +DEVICE inline bool operator==(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __heq(a, b); +#else + return static_cast(float16(a)) == static_cast(float16(b)); +#endif +} + +DEVICE inline bool operator!=(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hne(a, b); +#else + return static_cast(float16(a)) != static_cast(float16(b)); +#endif +} + +DEVICE inline bool operator<(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hlt(a, b); +#else + return static_cast(float16(a)) < static_cast(float16(b)); +#endif +} + +DEVICE inline bool operator<=(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hle(a, b); +#else + return static_cast(float16(a)) <= static_cast(float16(b)); +#endif +} + +DEVICE inline bool operator>(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hgt(a, b); +#else + return static_cast(float16(a)) > static_cast(float16(b)); +#endif +} + +DEVICE inline bool operator>=(const half& a, const half& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hge(a, b); +#else + return static_cast(float16(a)) >= static_cast(float16(b)); +#endif +} + +#endif // PADDLE_CUDA_FP16 + +// Arithmetic operators for float16 on GPU +#if defined(PADDLE_CUDA_FP16) +// HIPCC has compile error if call __device__ function __hadd, __hsub, etc. +// in __host__ __device__ function +#if defined(__HIPCC__) +DEVICE inline float16 operator+(const float16& a, const float16& b) { + return float16(__hadd(a.to_half(), b.to_half())); +} +HOST inline float16 operator+(const float16& a, const float16& b) { + return float16(static_cast(a) + static_cast(b)); +} +#else +HOSTDEVICE inline float16 operator+(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return float16(__hadd(a.to_half(), b.to_half())); +#else + return float16(static_cast(a) + static_cast(b)); +#endif +} +#endif + +#if defined(__HIPCC__) +DEVICE inline float16 operator-(const float16& a, const float16& b) { + return float16(__hsub(a.to_half(), b.to_half())); +} +HOST inline float16 operator-(const float16& a, const float16& b) { + return float16(static_cast(a) - static_cast(b)); +} +#else +HOSTDEVICE inline float16 operator-(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return float16(__hsub(a.to_half(), b.to_half())); +#else + return float16(static_cast(a) - static_cast(b)); +#endif +} +#endif + +#if defined(__HIPCC__) +DEVICE inline float16 operator*(const float16& a, const float16& b) { + return float16(__hmul(a.to_half(), b.to_half())); +} +HOST inline float16 operator*(const float16& a, const float16& b) { + return float16(static_cast(a) * static_cast(b)); +} +#else +HOSTDEVICE inline float16 operator*(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return float16(__hmul(a.to_half(), b.to_half())); +#else + return float16(static_cast(a) * static_cast(b)); +#endif +} +#endif + +#if defined(__HIPCC__) +DEVICE inline float16 operator/(const float16& a, const float16& b) { + return float16(__hdiv(a.to_half(), b.to_half())); +} +HOST inline float16 operator/(const float16& a, const float16& b) { + return float16(static_cast(a) / static_cast(b)); +} +#else +HOSTDEVICE inline float16 operator/(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + // TODO(kexinzhao): check which cuda version starts to support __hdiv + float num = __half2float(a.to_half()); + float denom = __half2float(b.to_half()); + return float16(num / denom); +#else + return float16(static_cast(a) / static_cast(b)); +#endif +} +#endif + +#if defined(__HIPCC__) +DEVICE inline float16 operator-(const float16& a) { + return float16(__hneg(a.to_half())); +} +HOST inline float16 operator-(const float16& a) { + float16 res; + res.x = a.x ^ 0x8000; + return res; +} +#else +HOSTDEVICE inline float16 operator-(const float16& a) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return float16(__hneg(a.to_half())); +#else + float16 res; + res.x = a.x ^ 0x8000; + return res; +#endif +} +#endif + +HOSTDEVICE inline float16& operator+=(float16& a, const float16& b) { // NOLINT + a = a + b; + return a; +} + +HOSTDEVICE inline float16& operator-=(float16& a, const float16& b) { // NOLINT + a = a - b; + return a; +} + +HOSTDEVICE inline float16& operator*=(float16& a, const float16& b) { // NOLINT + a = a * b; + return a; +} + +HOSTDEVICE inline float16& operator/=(float16& a, const float16& b) { // NOLINT + a = a / b; + return a; +} + +// HIPCC has compile error if call __device__ function __heq, __hne, etc. +// in __host__ __device__ function +#if defined(__HIPCC__) +DEVICE inline bool operator==(const float16& a, const float16& b) { + return __heq(a.to_half(), b.to_half()); +} +HOST inline bool operator==(const float16& a, const float16& b) { + return static_cast(a) == static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator==(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __heq(a.to_half(), b.to_half()); +#else + return static_cast(a) == static_cast(b); +#endif +} +#endif // __HIPCC__ + +#if defined(__HIPCC__) +DEVICE inline bool operator!=(const float16& a, const float16& b) { + return __hne(a.to_half(), b.to_half()); +} +HOST inline bool operator!=(const float16& a, const float16& b) { + return static_cast(a) != static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator!=(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hne(a.to_half(), b.to_half()); +#else + return static_cast(a) != static_cast(b); +#endif +} +#endif // __HIPCC__ + +#if defined(__HIPCC__) +DEVICE inline bool operator<(const float16& a, const float16& b) { + return __hlt(a.to_half(), b.to_half()); +} +HOST inline bool operator<(const float16& a, const float16& b) { + return static_cast(a) < static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator<(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hlt(a.to_half(), b.to_half()); +#else + return static_cast(a) < static_cast(b); +#endif +} +#endif // __HIPCC__ + +#if defined(__HIPCC__) +DEVICE inline bool operator<=(const float16& a, const float16& b) { + return __hle(a.to_half(), b.to_half()); +} +HOST inline bool operator<=(const float16& a, const float16& b) { + return static_cast(a) <= static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator<=(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hle(a.to_half(), b.to_half()); +#else + return static_cast(a) <= static_cast(b); +#endif +} +#endif // __HIPCC__ + +#if defined(__HIPCC__) +DEVICE inline bool operator>(const float16& a, const float16& b) { + return __hgt(a.to_half(), b.to_half()); +} +HOST inline bool operator>(const float16& a, const float16& b) { + return static_cast(a) > static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator>(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hgt(a.to_half(), b.to_half()); +#else + return static_cast(a) > static_cast(b); +#endif +} +#endif // __HIPCC__ + +#if defined(__HIPCC__) +DEVICE inline bool operator>=(const float16& a, const float16& b) { + return __hge(a.to_half(), b.to_half()); +} +HOST inline bool operator>=(const float16& a, const float16& b) { + return static_cast(a) >= static_cast(b); +} +#else // __HIPCC__ +HOSTDEVICE inline bool operator>=(const float16& a, const float16& b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hge(a.to_half(), b.to_half()); +#else + return static_cast(a) >= static_cast(b); +#endif +} +#endif // __HIPCC__ + +// Arithmetic operators for float16 on ARMv8.2-A CPU +#elif defined(PADDLE_WITH_NATIVE_FP16) +inline float16 operator+(const float16& a, const float16& b) { + float16 res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fadd h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&(res.x)) + : // clobbers + "memory", "v0", "v1"); + return res; +} + +inline float16 operator-(const float16& a, const float16& b) { + float16 res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fsub h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&(res.x)) + : // clobbers + "memory", "v0", "v1"); + return res; +} + +inline float16 operator*(const float16& a, const float16& b) { + float16 res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fmul h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&(res.x)) + : // clobbers + "memory", "v0", "v1"); + return res; +} + +inline float16 operator/(const float16& a, const float16& b) { + float16 res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fdiv h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&(res.x)) + : // clobbers + "memory", "v0", "v1"); + return res; +} + +inline float16 operator-(const float16& a) { + float16 res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "fneg h0, h0\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [res_ptr] "r"(&(res.x)) + : // clobbers + "memory", "v0"); + return res; +} + +inline float16& operator+=(float16& a, const float16& b) { // NOLINT + a = a + b; + return a; +} + +inline float16& operator-=(float16& a, const float16& b) { // NOLINT + a = a - b; + return a; +} + +inline float16& operator*=(float16& a, const float16& b) { // NOLINT + a = a * b; + return a; +} + +inline float16& operator/=(float16& a, const float16& b) { // NOLINT + a = a / b; + return a; +} + +inline bool operator==(const float16& a, const float16& b) { + uint16_t res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fcmeq h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&res) + : // clobbers + "memory", "v0", "v1"); + return (res & 0xffff) != 0; +} + +inline bool operator!=(const float16& a, const float16& b) { return !(a == b); } + +inline bool operator<(const float16& a, const float16& b) { + uint16_t res; + asm volatile( + "ld1 {v1.h}[0], [%[a_ptr]]\n" + "ld1 {v0.h}[0], [%[b_ptr]]\n" + "fcmgt h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&res) + : // clobbers + "memory", "v0", "v1"); + return (res & 0xffff) != 0; +} + +inline bool operator<=(const float16& a, const float16& b) { + uint16_t res; + asm volatile( + "ld1 {v1.h}[0], [%[a_ptr]]\n" + "ld1 {v0.h}[0], [%[b_ptr]]\n" + "fcmge h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&res) + : // clobbers + "memory", "v0", "v1"); + return (res & 0xffff) != 0; +} + +inline bool operator>(const float16& a, const float16& b) { + uint16_t res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fcmgt h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&res) + : // clobbers + "memory", "v0", "v1"); + return (res & 0xffff) != 0; +} + +inline bool operator>=(const float16& a, const float16& b) { + uint16_t res; + asm volatile( + "ld1 {v0.h}[0], [%[a_ptr]]\n" + "ld1 {v1.h}[0], [%[b_ptr]]\n" + "fcmge h0, h0, h1\n" + "st1 {v0.h}[0], [%[res_ptr]]\n" + : // outputs + : // inputs + [a_ptr] "r"(&(a.x)), + [b_ptr] "r"(&(b.x)), + [res_ptr] "r"(&res) + : // clobbers + "memory", "v0", "v1"); + return (res & 0xffff) != 0; +} + +// Arithmetic operators for float16, software emulated on other CPU +#else +inline float16 operator+(const float16& a, const float16& b) { + return float16(static_cast(a) + static_cast(b)); +} + +inline float16 operator-(const float16& a, const float16& b) { + return float16(static_cast(a) - static_cast(b)); +} + +inline float16 operator*(const float16& a, const float16& b) { + return float16(static_cast(a) * static_cast(b)); +} + +inline float16 operator/(const float16& a, const float16& b) { + return float16(static_cast(a) / static_cast(b)); +} + +inline float16 operator-(const float16& a) { + float16 res; + res.x = a.x ^ 0x8000; + return res; +} + +inline float16& operator+=(float16& a, const float16& b) { // NOLINT + a = float16(static_cast(a) + static_cast(b)); + return a; +} + +inline float16& operator-=(float16& a, const float16& b) { // NOLINT + a = float16(static_cast(a) - static_cast(b)); + return a; +} + +inline float16& operator*=(float16& a, const float16& b) { // NOLINT + a = float16(static_cast(a) * static_cast(b)); + return a; +} + +inline float16& operator/=(float16& a, const float16& b) { // NOLINT + a = float16(static_cast(a) / static_cast(b)); + return a; +} + +inline bool operator==(const float16& a, const float16& b) { + return static_cast(a) == static_cast(b); +} + +inline bool operator!=(const float16& a, const float16& b) { + return static_cast(a) != static_cast(b); +} + +inline bool operator<(const float16& a, const float16& b) { + return static_cast(a) < static_cast(b); +} + +inline bool operator<=(const float16& a, const float16& b) { + return static_cast(a) <= static_cast(b); +} + +inline bool operator>(const float16& a, const float16& b) { + return static_cast(a) > static_cast(b); +} + +inline bool operator>=(const float16& a, const float16& b) { + return static_cast(a) >= static_cast(b); +} +#endif + +HOSTDEVICE inline float16 raw_uint16_to_float16(uint16_t a) { + float16 res; + res.x = a; + return res; +} + +// HIPCC has compile error if call __device__ function __hisnan in __host__ +// __device__ function +#if defined(PADDLE_CUDA_FP16) && defined(__HIPCC__) +DEVICE inline bool(isnan)(const float16& a) { return __hisnan(a.to_half()); } +HOST inline bool(isnan)(const float16& a) { return (a.x & 0x7fff) > 0x7c00; } +#else +HOSTDEVICE inline bool(isnan)(const float16& a) { +#if defined(PADDLE_CUDA_FP16) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530 + return __hisnan(a.to_half()); +#else + return (a.x & 0x7fff) > 0x7c00; +#endif +} +#endif + +HOSTDEVICE inline bool(isinf)(const float16& a) { + return (a.x & 0x7fff) == 0x7c00; +} + +HOSTDEVICE inline bool(isfinite)(const float16& a) { + return !((isnan)(a)) && !((isinf)(a)); +} + +HOSTDEVICE inline float16(abs)(const float16& a) { +#if defined(PADDLE_CUDA_FP16) && \ + (defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530)) + return float16(::fabs(static_cast(a))); +#else + return float16(std::abs(static_cast(a))); +#endif +} + +inline std::ostream& operator<<(std::ostream& os, const float16& a) { + os << static_cast(a); + return os; +} + +} // namespace dtype +} // namespace phi + +namespace std { + +// Override the std::is_pod::value for float16 +// The reason is that different compilers implemented std::is_pod based on +// different C++ standards. float16 class is a plain old data in C++11 given +// that it is both trivial and standard_layout. +// However, std::is_pod in nvcc 8.0 host c++ compiler follows C++0x and is +// more restricted in that you cannot provide any customized +// constructor in float16. Hence, we override is_pod here following C++11 +// so that .cu files can be successfully compiled by nvcc. +template <> +struct is_pod { + static const bool value = is_trivial::value && + is_standard_layout::value; +}; + +template <> +struct is_floating_point + : std::integral_constant< + bool, + std::is_same< + phi::dtype::float16, + typename std::remove_cv::type>::value> {}; +template <> +struct is_signed { + static const bool value = true; +}; + +template <> +struct is_unsigned { + static const bool value = false; +}; + +inline bool isnan(const phi::dtype::float16& a) { return phi::dtype::isnan(a); } + +inline bool isinf(const phi::dtype::float16& a) { return phi::dtype::isinf(a); } + +inline bool isfinite(const phi::dtype::float16& a) { + return phi::dtype::isfinite(a); +} + +template <> +struct numeric_limits { + static const bool is_specialized = true; + static const bool is_signed = true; + static const bool is_integer = false; + static const bool is_exact = false; + static const bool has_infinity = true; + static const bool has_quiet_NaN = true; + static const bool has_signaling_NaN = true; + static const float_denorm_style has_denorm = denorm_present; + static const bool has_denorm_loss = false; + static const std::float_round_style round_style = std::round_to_nearest; + static const bool is_iec559 = false; + static const bool is_bounded = false; + static const bool is_modulo = false; + static const int digits = 11; + static const int digits10 = 3; + static const int max_digits10 = 5; + static const int radix = 2; + static const int min_exponent = -13; + static const int min_exponent10 = -4; + static const int max_exponent = 16; + static const int max_exponent10 = 4; + static const bool traps = true; + static const bool tinyness_before = false; + + HOSTDEVICE static phi::dtype::float16(min)() { + return phi::dtype::raw_uint16_to_float16(0x400); + } + HOSTDEVICE static phi::dtype::float16 lowest() { + return phi::dtype::raw_uint16_to_float16(0xfbff); + } + HOSTDEVICE static phi::dtype::float16(max)() { + return phi::dtype::raw_uint16_to_float16(0x7bff); + } + HOSTDEVICE static phi::dtype::float16 epsilon() { + return phi::dtype::raw_uint16_to_float16(0x0800); + } + HOSTDEVICE static phi::dtype::float16 round_error() { + return phi::dtype::float16(0.5); + } + HOSTDEVICE static phi::dtype::float16 infinity() { + return phi::dtype::raw_uint16_to_float16(0x7c00); + } + HOSTDEVICE static phi::dtype::float16 quiet_NaN() { + return phi::dtype::raw_uint16_to_float16(0x7e00); + } + HOSTDEVICE static phi::dtype::float16 signaling_NaN() { + return phi::dtype::raw_uint16_to_float16(0x7e00); + } + HOSTDEVICE static phi::dtype::float16 denorm_min() { + return phi::dtype::raw_uint16_to_float16(0x1); + } +}; + +HOSTDEVICE inline phi::dtype::float16 abs(const phi::dtype::float16& a) { + return phi::dtype::abs(a); +} + +} // namespace std diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/int_array.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/int_array.h new file mode 100644 index 0000000000000000000000000000000000000000..91b9ace136bc22943b8520220a0c09fc760fc958 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/int_array.h @@ -0,0 +1,115 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/api/include/tensor.h" + +namespace paddle { +namespace experimental { + +template +class IntArrayBase { + public: + // Constructor support implicit + IntArrayBase() = default; + + IntArrayBase(const std::vector& vec) : array_(vec) {} // NOLINT + + IntArrayBase(const std::vector& vec) { // NOLINT + array_.insert(array_.begin(), vec.begin(), vec.end()); + } + + IntArrayBase(std::initializer_list array_list) + : array_(array_list) {} + + IntArrayBase(const int64_t* date_value, int64_t n) { + AssignData(date_value, n); + } + + IntArrayBase(const int32_t* date_value, int64_t n) { + AssignData(date_value, n); + } + + bool FromTensor() const { return is_from_tensor_; } + + void SetFromTensor(bool val) { is_from_tensor_ = val; } + + // The Tensor must have one dim + IntArrayBase(const T& tensor); // NOLINT + + // The Tensor in vec must have only one element + IntArrayBase(const std::vector& tensor_list); // NOLINT + + template + IntArrayBase(const IntArrayBase& other) : array_(other.GetData()) {} + + size_t size() const { return array_.size(); } + + const std::vector& GetData() const { return array_; } + + private: + /// \brief Assign the data_ from const data pointer value of type T. + template + void AssignData(const TYPE* value_data, int64_t n) { + if (value_data || n == 0) { + array_.reserve(n); + for (auto i = 0; i < n; ++i) { + array_.push_back(static_cast(value_data[i])); + } + } else { + PD_THROW("The input data pointer is null."); + } + } + + void AssignDataFromTensor(const T& tensor) { + size_t n = tensor.numel(); + array_.reserve(n); + switch (tensor.dtype()) { + case DataType::INT32: + AssignData(tensor.template data(), n); + break; + case DataType::INT64: + AssignData(tensor.template data(), n); + break; + default: + PD_THROW( + "Data type error. Currently, The data type of IntArrayBase " + "only supports Tensor with int32 and int64, " + "but now received `", + tensor.dtype(), + "`."); + } + } + + private: + // TODO(zhangyunfei) Replace std::vector with a more efficient container + // structure. + std::vector array_; + bool is_from_tensor_{false}; +}; + +using IntArray = + paddle::experimental::IntArrayBase; + +} // namespace experimental +} // namespace paddle + +namespace phi { + +class DenseTensor; +using IntArray = paddle::experimental::IntArrayBase; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/layout.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/layout.h new file mode 100644 index 0000000000000000000000000000000000000000..b7f4abcc63a62670059ec7853ed9223c691e9200 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/layout.h @@ -0,0 +1,144 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/api/ext/exception.h" +namespace paddle { +namespace experimental { + +// Note: The original design of paddle DataLayout is confusing. +// It contains two levels of "layout", one is the data layout +// at the Tensor level, including Dense, Sparse, etc., and the other +// is the format at the data level, including NHWC, NCHW, etc., +// these should belong to the concept of "data format". +// The concepts of these two levels are mixed into an enumeration class, +// which leads to some strange execution scheduling logic. +// It needs to be refactored in the future. +// In order to maintain compatibility, we still use the design of the +// original framework here. + +// Note: Here the DataLayout is public api for external users, the prefix `k` +// maybe confuse users, so we use all uppercase names + +enum class DataLayout { + UNDEFINED = 0, + // TODO(chenweihang): keep ANY for compatibility, remove it later + ANY = UNDEFINED, + NHWC, + NCHW, + NCDHW, + NDHWC, + ONEDNN, + SPARSE_COO, + SPARSE_CSR, + PSTRING_UNION, + + NUM_DATA_LAYOUTS, + + // See Note [ Why we need ALL in basic kernel key member? ] + ALL_LAYOUT = UNDEFINED, + + // Note: Unify phi DataLayout and fluid::framework::DataLayout, + // for compatible with fluid DataLayout, here need prefix `k` + + // Note: The original `kAnyLayout (enum value 2)` is a strange design. + // `kAnyLayout` originally cannot represent any kind of Layout, + // at the same time, it can also represent any Layout. + // Strictly, it means "default" or "undefined" layout, + // and should not be mixed with other meaningful layouts + + kAnyLayout = ANY, + kNHWC = NHWC, + kNCHW = NCHW, + kMKLDNN = ONEDNN, // all layouts supported by ONEDNN internally + kNDHWC = NDHWC, + kNCDHW = NCDHW, +}; + +} // namespace experimental + +// In order to be compatible with the fluid implementation +namespace framework { + +using DataLayout = paddle::experimental::DataLayout; + +inline DataLayout StringToDataLayout(const std::string& str) { + std::string s(str); + for (size_t i = 0; i < s.size(); ++i) { + s[i] = toupper(s[i]); + } + + if (s == "NHWC") { + return DataLayout::kNHWC; + } else if (s == "NCHW") { + return DataLayout::kNCHW; + } else if (s == "ANYLAYOUT") { + return DataLayout::kAnyLayout; + } else if (s == "MKLDNNLAYOUT") { + return DataLayout::kMKLDNN; + } else if (s == "SPARSE_COO") { + return DataLayout::SPARSE_COO; + } else if (s == "SPARSE_CSR") { + return DataLayout::SPARSE_CSR; + } else if (s == "NDHWC") { + return DataLayout::kNDHWC; + } else if (s == "PSTRING_UNION") { + return DataLayout::PSTRING_UNION; + } else if (s == "NCDHW") { + return DataLayout::kNCDHW; + } else { + PD_THROW("Unknown data layout type string: ", s, "."); + } +} + +inline std::string DataLayoutToString(const DataLayout& layout) { + switch (layout) { + case DataLayout::kNHWC: + return "NHWC"; + case DataLayout::kNCHW: + return "NCHW"; + case DataLayout::kAnyLayout: + return "Undefined(AnyLayout)"; + case DataLayout::kMKLDNN: + return "MKLDNN"; + case DataLayout::SPARSE_COO: + return "SPARSE_COO"; + case DataLayout::SPARSE_CSR: + return "SPARSE_CSR"; + case DataLayout::kNDHWC: + return "NDHWC"; + case DataLayout::kNCDHW: + return "NCDHW"; + case DataLayout::PSTRING_UNION: + return "PSTRING_UNION"; + default: + PD_THROW("Unknown Data Layout type ", static_cast(layout), "."); + } +} +} // namespace framework + +namespace experimental { + +inline std::ostream& operator<<(std::ostream& os, DataLayout layout) { + os << framework::DataLayoutToString(layout); + return os; +} + +} // namespace experimental +} // namespace paddle + +namespace phi { +using DataLayout = paddle::experimental::DataLayout; +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/place.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/place.h new file mode 100644 index 0000000000000000000000000000000000000000..49050d31b169adc9cf3f3ea6f323bb8e4cbb3231 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/place.h @@ -0,0 +1,262 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/api/include/dll_decl.h" + +namespace paddle { +enum class PlaceType; +} + +namespace phi { + +enum class AllocationType : int8_t { + UNDEFINED = 0, + CPU = 1, + GPU = 2, + GPUPINNED = 3, + XPU = 4, + NPU = 5, + NPUPINNED = 6, + IPU = 7, + MLU = 8, + CUSTOM = 9, +}; + +const char* AllocationTypeStr(AllocationType type); + +size_t GetOrRegisterGlobalDeviceTypeId(const std::string& device_type); + +std::string GetGlobalDeviceType(size_t device_type_id_); + +/// \brief The place is used to specify where the data is stored. +class PADDLE_API Place { + public: + Place() : device(0), alloc_type_(AllocationType::UNDEFINED) {} + + explicit Place(AllocationType type, + int8_t id, + const std::string& dev_type = "") + : device(id), + alloc_type_(type), + device_type_id_(GetOrRegisterGlobalDeviceTypeId(dev_type)) {} + + explicit Place(AllocationType type, const std::string& dev_type = "") + : device(0), + alloc_type_(type), + device_type_id_(GetOrRegisterGlobalDeviceTypeId(dev_type)) {} + + // See NOTE [ Why need to temporarily adapt to PlaceType? ] + Place(paddle::PlaceType type); // NOLINT + + void Reset(AllocationType type, + int8_t device_id = 0, + const std::string& dev_type = "") noexcept { + alloc_type_ = type; + device = device_id; + if (!dev_type.empty()) { + device_type_id_ = GetOrRegisterGlobalDeviceTypeId(dev_type); + } + } + + AllocationType GetType() const { return alloc_type_; } + + int8_t GetDeviceId() const { return device; } + + std::string GetDeviceType() const { + return GetGlobalDeviceType(device_type_id_); + } + + std::string DebugString() const; + + struct Hash { + // Note: Now the number of bits we need does not exceed 32 bits, so there is + // no need to use 64 bits. If needed in the future, it can be expanded, + // but now we don’t over-design. + uint32_t operator()(const Place& place) const; + }; + + uint32_t HashValue() const { return Hash()(*this); } + + inline bool operator==(const Place& rhs) const { + return HashValue() == rhs.HashValue(); + } + inline bool operator!=(const Place& rhs) const { + return HashValue() != rhs.HashValue(); + } + inline bool operator<(const Place& rhs) const { + return HashValue() < rhs.HashValue(); + } + + public: + // TODO(wilber): Just because of backward compatibility, it needs to be + // changed to private in the future. + int8_t device{0}; + + private: + AllocationType alloc_type_{AllocationType::UNDEFINED}; + size_t device_type_id_; +}; + +class CPUPlace : public Place { + public: + CPUPlace() : Place(AllocationType::CPU) {} + + CPUPlace(const CPUPlace&) = default; + CPUPlace(const Place& place) : Place(AllocationType::CPU) {} // NOLINT +}; + +class GPUPlace : public Place { + public: + GPUPlace() : Place(AllocationType::GPU, 0) {} + explicit GPUPlace(int device_id) : Place(AllocationType::GPU, device_id) {} + + GPUPlace(const GPUPlace&) = default; + GPUPlace(const Place& place) // NOLINT + : Place(AllocationType::GPU, place.GetDeviceId()) {} +}; + +class GPUPinnedPlace : public Place { + public: + GPUPinnedPlace() : Place(AllocationType::GPUPINNED) {} + + GPUPinnedPlace(const GPUPinnedPlace&) = default; + GPUPinnedPlace(const Place& place) // NOLINT + : Place(AllocationType::GPUPINNED) {} +}; + +class XPUPlace : public Place { + public: + XPUPlace() : Place(AllocationType::XPU, 0) {} + explicit XPUPlace(int device_id) : Place(AllocationType::XPU, device_id) {} + + XPUPlace(const XPUPlace&) = default; + XPUPlace(const Place& place) // NOLINT + : Place(AllocationType::XPU, place.GetDeviceId()) {} +}; + +class NPUPlace : public Place { + public: + NPUPlace() : Place(AllocationType::NPU, 0) {} + explicit NPUPlace(int device_id) : Place(AllocationType::NPU, device_id) {} + + NPUPlace(const NPUPlace&) = default; + NPUPlace(const Place& place) // NOLINT + : Place(AllocationType::NPU, place.GetDeviceId()) {} +}; + +class NPUPinnedPlace : public Place { + public: + NPUPinnedPlace() : Place(AllocationType::NPUPINNED) {} + + NPUPinnedPlace(const NPUPinnedPlace&) = default; + NPUPinnedPlace(const Place& place) // NOLINT + : Place(AllocationType::NPUPINNED) {} +}; + +class IPUPlace : public Place { + public: + IPUPlace() : Place(AllocationType::IPU, 0) {} + explicit IPUPlace(int device_id) : Place(AllocationType::IPU, device_id) {} + + IPUPlace(const IPUPlace&) = default; + IPUPlace(const Place& place) // NOLINT + : Place(AllocationType::IPU, place.GetDeviceId()) {} +}; + +class MLUPlace : public Place { + public: + MLUPlace() : Place(AllocationType::MLU, 0) {} + explicit MLUPlace(int device_id) : Place(AllocationType::MLU, device_id) {} + + MLUPlace(const MLUPlace&) = default; + MLUPlace(const Place& place) // NOLINT + : Place(AllocationType::MLU, place.GetDeviceId()) {} +}; + +class CustomPlace : public Place { + public: + CustomPlace() : Place(AllocationType::CUSTOM, 0, "") {} + explicit CustomPlace(const std::string dev_type) + : Place(AllocationType::CUSTOM, 0, dev_type) {} + CustomPlace(const std::string dev_type, int device_id) + : Place(AllocationType::CUSTOM, device_id, dev_type) {} + + CustomPlace(const CustomPlace&) = default; + CustomPlace(const Place& place) { // NOLINT + if (place.GetType() == AllocationType::CUSTOM) { + this->Reset( + AllocationType::CUSTOM, place.GetDeviceId(), place.GetDeviceType()); + } + } +}; + +std::ostream& operator<<(std::ostream&, const Place&); + +Place GetPinnedPlace(const Place& place); + +} // namespace phi + +namespace paddle { +namespace experimental { +using AllocationType = phi::AllocationType; +using GPUPinnedPlace = phi::GPUPinnedPlace; +using XPUPlace = phi::XPUPlace; +using NPUPlace = phi::NPUPlace; +} // namespace experimental + +using AllocationType = phi::AllocationType; +using Place = phi::Place; +using CPUPlace = phi::CPUPlace; +using GPUPlace = phi::GPUPlace; + +/* NOTE [ Why need to temporarily adapt to PlaceType? ] + +`PlaceType` emum class is the place type used by custom operators since the +release of 2.0. Since 2.3, we have refactored the operator library and designed +a new external Place type. The original PlaceType is no longer suitable for use +as an internal type of the framework, but immediately delete the PlaceType, +it will cause the previous custom operators to be incompatible, so it cannot be +deleted in the short term. We'd better delete this abandoned data type in 2.4. + +Note: This type cannot add any new type!!! It is only used for compatibility +with +historical writing and we will remove this temporary type in the future. +This Type cannot be used in framework! only used for custom operator! + +The original PlaceType define: + +- enum class PlaceType { kUNK = -1, kCPU, kGPU }; + +The historical PlaceType using: + +- PD_CHECK(x.place() == paddle::PlaceType::kCPU) +- auto out = paddle::Tensor(paddle::PlaceType::kCPU, x.shape()); + +*/ +enum class PlaceType { + kUNK = static_cast(phi::AllocationType::UNDEFINED), + kCPU = static_cast(phi::AllocationType::CPU), + kGPU = static_cast(phi::AllocationType::GPU), +}; + +PADDLE_API bool operator==(const Place& place, PlaceType place_type); +PADDLE_API bool operator==(PlaceType place_type, const Place& place); + +PADDLE_API GPUPlace DefaultGPUPlace(); + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/pstring.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/pstring.h new file mode 100644 index 0000000000000000000000000000000000000000..4c89251a60c13a995c464ec8546a0e906d46dc9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/pstring.h @@ -0,0 +1,480 @@ +/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. + Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +This file is inspired by + + https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/platform/tstring.h + +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. */ + +#pragma once + +#include + +#include +#include + +#include "paddle/phi/common/cpstring_impl.h" + +namespace phi { +namespace dtype { + +// Pstring is an only dtype of StringTensor, which is +// used to manage string data. It provides almost same +// interfaces compared to std::string, including data(), +// length() and so on. Besides, pstring data can be +// manipulated in GPU. + +class pstring { + PD_PString pstr_; + + public: + enum Type { + SMALL = PD_PSTR_SMALL, + LARGE = PD_PSTR_LARGE, + OFFSET = PD_PSTR_OFFSET, + VIEW = PD_PSTR_VIEW, + }; + + typedef const char* const_iterator; + + // Ctor + HOSTDEVICE pstring(); + HOSTDEVICE pstring(const std::string& str); // NOLINT + HOSTDEVICE pstring(const char* str, size_t len); + HOSTDEVICE pstring(const char* str); // NOLINT + HOSTDEVICE pstring(size_t n, char c); + + // Copy + HOSTDEVICE pstring(const pstring& str); + + // Move + HOSTDEVICE pstring(pstring&& str) noexcept; + + // Dtor + HOSTDEVICE ~pstring(); + + // Copy Assignment + HOSTDEVICE pstring& operator=(const pstring& str); + HOSTDEVICE pstring& operator=(const std::string& str); + HOSTDEVICE pstring& operator=(const char* str); + HOSTDEVICE pstring& operator=(char ch); + + // Move Assignment + HOSTDEVICE pstring& operator=(pstring&& str); + + // Comparison + HOSTDEVICE int compare(const char* str, size_t len) const; + HOSTDEVICE bool operator<(const pstring& o) const; + HOSTDEVICE bool operator>(const pstring& o) const; + HOSTDEVICE bool operator==(const char* str) const; + HOSTDEVICE bool operator==(const pstring& o) const; + HOSTDEVICE bool operator!=(const char* str) const; + HOSTDEVICE bool operator!=(const pstring& o) const; + + // Conversion Operators + HOSTDEVICE operator std::string() const; // NOLINT + + // Attributes + HOSTDEVICE size_t size() const; + HOSTDEVICE size_t length() const; + HOSTDEVICE size_t capacity() const; + HOSTDEVICE bool empty() const; + HOSTDEVICE Type type() const; + + // Allocation + HOSTDEVICE void resize(size_t new_size, char c = 0); + // Similar to resize, but will leave the newly grown region uninitialized. + HOSTDEVICE void resize_uninitialized(size_t new_size); + HOSTDEVICE void clear() noexcept; + HOSTDEVICE void reserve(size_t n); + + // Iterators + HOSTDEVICE const_iterator begin() const; + HOSTDEVICE const_iterator end() const; + + // Const Element Access + HOSTDEVICE const char* c_str() const; + HOSTDEVICE const char* data() const; + HOSTDEVICE const char& operator[](size_t i) const; + HOSTDEVICE const char& back() const; + + // Mutable Element Access + HOSTDEVICE char* mdata(); + HOSTDEVICE char& operator[](size_t i); + + // Assignment + HOSTDEVICE pstring& assign(const char* str, size_t len); + HOSTDEVICE pstring& assign(const char* str); + + // View Assignment + HOSTDEVICE pstring& assign_as_view(const pstring& str); + HOSTDEVICE pstring& assign_as_view(const std::string& str); + HOSTDEVICE pstring& assign_as_view(const char* str, size_t len); + HOSTDEVICE pstring& assign_as_view(const char* str); + + // Modifiers + // NOTE: Invalid input will result in undefined behavior. + HOSTDEVICE pstring& append(const pstring& str); + HOSTDEVICE pstring& append(const char* str, size_t len); + HOSTDEVICE pstring& append(const char* str); + HOSTDEVICE pstring& append(size_t n, char c); + + HOSTDEVICE pstring& erase(size_t pos, size_t len); + + HOSTDEVICE pstring& insert(size_t pos, + const pstring& str, + size_t subpos, + size_t sublen); + HOSTDEVICE pstring& insert(size_t pos, size_t n, char c); + HOSTDEVICE void swap(pstring& str); + HOSTDEVICE void push_back(char ch); + + // Friends + HOSTDEVICE friend bool operator==(const char* a, const pstring& b); + HOSTDEVICE friend bool operator==(const std::string& a, const pstring& b); + HOSTDEVICE friend pstring operator+(const pstring& a, const pstring& b); + HOSTDEVICE friend std::ostream& operator<<(std::ostream& o, + const pstring& str); +}; + +// Non-member function overloads + +HOSTDEVICE bool operator==(const char* a, const pstring& b); +HOSTDEVICE bool operator==(const std::string& a, const pstring& b); +HOSTDEVICE pstring operator+(const pstring& a, const pstring& b); +HOSTDEVICE std::ostream& operator<<(std::ostream& o, const pstring& str); +HOSTDEVICE size_t strlen(const char* start); + +// Implementations + +// Ctor + +HOSTDEVICE inline pstring::pstring() { PD_PString_Init(&pstr_); } + +HOSTDEVICE inline pstring::pstring(const char* str, size_t len) { + PD_PString_Init(&pstr_); + PD_PString_Copy(&pstr_, str, len); +} + +HOSTDEVICE inline pstring::pstring(const char* str) + : pstring(str, strlen(str)) {} + +HOSTDEVICE inline pstring::pstring(size_t n, char c) { + PD_PString_Init(&pstr_); + PD_PString_Resize(&pstr_, n, c); +} + +HOSTDEVICE inline pstring::pstring(const std::string& str) + : pstring(str.data(), str.size()) {} + +HOSTDEVICE inline pstring::pstring(const pstring& str) { + PD_PString_Init(&pstr_); + PD_PString_Assign(&pstr_, &str.pstr_); +} + +// Move + +HOSTDEVICE inline pstring::pstring(pstring&& str) noexcept { + PD_PString_Init(&pstr_); + PD_PString_Move(&pstr_, &str.pstr_); +} + +// Dtor + +HOSTDEVICE inline pstring::~pstring() { PD_PString_Dealloc(&pstr_); } + +// Copy Assignment + +HOSTDEVICE inline pstring& pstring::operator=(const pstring& str) { + PD_PString_Assign(&pstr_, &str.pstr_); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::operator=(const std::string& str) { + PD_PString_Copy(&pstr_, str.data(), str.size()); + return *this; +} + +HOSTDEVICE inline pstring& pstring::operator=(const char* str) { + PD_PString_Copy(&pstr_, str, strlen(str)); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::operator=(char c) { + resize_uninitialized(1); + (*this)[0] = c; + + return *this; +} + +// Move Assignment + +HOSTDEVICE inline pstring& pstring::operator=(pstring&& str) { + PD_PString_Move(&pstr_, &str.pstr_); + + return *this; +} + +// Comparison + +HOSTDEVICE inline int pstring::compare(const char* str, size_t len) const { + int ret = PD_Memcmp(data(), str, (len < size()) ? len : size()); + + if (ret < 0) return -1; + if (ret > 0) return +1; + + if (size() < len) return -1; + if (size() > len) return +1; + + return 0; +} + +HOSTDEVICE inline bool pstring::operator<(const pstring& o) const { + return compare(o.data(), o.size()) < 0; +} + +HOSTDEVICE inline bool pstring::operator>(const pstring& o) const { + return compare(o.data(), o.size()) > 0; +} + +HOSTDEVICE inline bool pstring::operator==(const char* str) const { + return strlen(str) == size() && PD_Memcmp(data(), str, size()) == 0; +} + +HOSTDEVICE inline bool pstring::operator==(const pstring& o) const { + return o.size() == size() && PD_Memcmp(data(), o.data(), size()) == 0; +} + +HOSTDEVICE inline bool pstring::operator!=(const char* str) const { + return !(*this == str); +} + +HOSTDEVICE inline bool pstring::operator!=(const pstring& o) const { + return !(*this == o); +} + +// Conversion Operators + +HOSTDEVICE inline pstring::operator std::string() const { + return std::string(data(), size()); +} + +// Attributes + +HOSTDEVICE inline size_t pstring::size() const { + return PD_PString_GetSize(&pstr_); +} + +HOSTDEVICE inline size_t pstring::length() const { return size(); } + +HOSTDEVICE inline size_t pstring::capacity() const { + return PD_PString_GetCapacity(&pstr_); +} + +HOSTDEVICE inline bool pstring::empty() const { return size() == 0; } + +HOSTDEVICE inline pstring::Type pstring::type() const { + return static_cast(PD_PString_GetType(&pstr_)); +} + +// Allocation + +HOSTDEVICE inline void pstring::resize(size_t new_size, char c) { + PD_PString_Resize(&pstr_, new_size, c); +} + +HOSTDEVICE inline void pstring::resize_uninitialized(size_t new_size) { + PD_PString_ResizeUninitialized(&pstr_, new_size); +} + +HOSTDEVICE inline void pstring::clear() noexcept { + PD_PString_ResizeUninitialized(&pstr_, 0); +} + +HOSTDEVICE inline void pstring::reserve(size_t n) { + PD_PString_Reserve(&pstr_, n); +} + +// Iterators + +HOSTDEVICE inline pstring::const_iterator pstring::begin() const { + return &(*this)[0]; +} +HOSTDEVICE inline pstring::const_iterator pstring::end() const { + return &(*this)[size()]; +} + +// Element Access + +HOSTDEVICE inline const char* pstring::c_str() const { return data(); } + +HOSTDEVICE inline const char* pstring::data() const { + return PD_PString_GetDataPointer(&pstr_); +} + +HOSTDEVICE inline const char& pstring::operator[](size_t i) const { + return data()[i]; +} + +HOSTDEVICE inline const char& pstring::back() const { + return (*this)[size() - 1]; +} + +HOSTDEVICE inline char* pstring::mdata() { + return PD_PString_GetMutableDataPointer(&pstr_); +} + +HOSTDEVICE inline char& pstring::operator[](size_t i) { return mdata()[i]; } + +// Assignment + +HOSTDEVICE inline pstring& pstring::assign(const char* str, size_t len) { + PD_PString_Copy(&pstr_, str, len); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::assign(const char* str) { + assign(str, strlen(str)); + + return *this; +} + +// View Assignment + +HOSTDEVICE inline pstring& pstring::assign_as_view(const pstring& str) { + assign_as_view(str.data(), str.size()); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::assign_as_view(const std::string& str) { + assign_as_view(str.data(), str.size()); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::assign_as_view(const char* str, + size_t len) { + PD_PString_AssignView(&pstr_, str, len); + return *this; +} + +HOSTDEVICE inline pstring& pstring::assign_as_view(const char* str) { + assign_as_view(str, strlen(str)); + + return *this; +} + +// Modifiers + +HOSTDEVICE inline pstring& pstring::append(const pstring& str) { + PD_PString_Append(&pstr_, &str.pstr_); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::append(const char* str, size_t len) { + PD_PString_AppendN(&pstr_, str, len); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::append(const char* str) { + append(str, strlen(str)); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::append(size_t n, char c) { + // For append use cases, we want to ensure amortized growth. + const size_t new_size = size() + n; + PD_PString_ReserveAmortized(&pstr_, new_size); + resize(new_size, c); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::erase(size_t pos, size_t len) { + PD_Memmove(mdata() + pos, data() + pos + len, size() - len - pos); + + resize(size() - len); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::insert(size_t pos, + const pstring& str, + size_t subpos, + size_t sublen) { + size_t orig_size = size(); + PD_PString_ResizeUninitialized(&pstr_, orig_size + sublen); + + PD_Memmove(mdata() + pos + sublen, data() + pos, orig_size - pos); + PD_Memmove(mdata() + pos, str.data() + subpos, sublen); + + return *this; +} + +HOSTDEVICE inline pstring& pstring::insert(size_t pos, size_t n, char c) { + size_t size_ = size(); + PD_PString_ResizeUninitialized(&pstr_, size_ + n); + + PD_Memmove(mdata() + pos + n, data() + pos, size_ - pos); + PD_Memset(mdata() + pos, c, n); + + return *this; +} + +HOSTDEVICE inline void pstring::swap(pstring& str) { + std::swap(pstr_, str.pstr_); +} + +HOSTDEVICE inline void pstring::push_back(char ch) { append(1, ch); } + +// Friends + +HOSTDEVICE inline bool operator==(const char* a, const pstring& b) { + return strlen(a) == b.size() && PD_Memcmp(a, b.data(), b.size()) == 0; +} + +HOSTDEVICE inline bool operator==(const std::string& a, const pstring& b) { + return a.size() == b.size() && PD_Memcmp(a.data(), b.data(), b.size()) == 0; +} + +HOSTDEVICE inline pstring operator+(const pstring& a, const pstring& b) { + pstring r; + r.reserve(a.size() + b.size()); + r.append(a); + r.append(b); + + return r; +} + +HOSTDEVICE inline std::ostream& operator<<(std::ostream& o, + const pstring& str) { + return o.write(str.data(), str.size()); +} + +HOSTDEVICE inline size_t strlen(const char* start) { + const char* end = start; + for (; *end != '\0'; ++end) { + } + return end - start; +} + +} // namespace dtype +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/scalar.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..5aee59f52ffae28f704d7a2c9dff73a46c7d5657 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/scalar.h @@ -0,0 +1,239 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/api/include/tensor.h" + +namespace paddle { +namespace experimental { + +template +class ScalarBase { + public: + // Constructor support implicit + ScalarBase() : ScalarBase(0) {} + ScalarBase(double val) : dtype_(DataType::FLOAT64) { // NOLINT + data_.f64 = val; + } + + ScalarBase(float val) : dtype_(DataType::FLOAT32) { // NOLINT + data_.f32 = val; + } + + ScalarBase(float16 val) : dtype_(DataType::FLOAT16) { // NOLINT + data_.f16 = val; + } + + ScalarBase(bfloat16 val) : dtype_(DataType::BFLOAT16) { // NOLINT + data_.bf16 = val; + } + + ScalarBase(int64_t val) : dtype_(DataType::INT64) { // NOLINT + data_.i64 = val; + } + + ScalarBase(int32_t val) : dtype_(DataType::INT32) { // NOLINT + data_.i32 = val; + } + + ScalarBase(int16_t val) : dtype_(DataType::INT16) { // NOLINT + data_.i16 = val; + } + + ScalarBase(int8_t val) : dtype_(DataType::INT8) { // NOLINT + data_.i8 = val; + } + + ScalarBase(uint64_t val) : dtype_(DataType::UINT64) { // NOLINT + data_.ui64 = val; + } + + ScalarBase(uint32_t val) : dtype_(DataType::UINT32) { // NOLINT + data_.ui32 = val; + } + + ScalarBase(uint16_t val) : dtype_(DataType::UINT16) { // NOLINT + data_.ui16 = val; + } + + ScalarBase(uint8_t val) : dtype_(DataType::UINT8) { // NOLINT + data_.ui8 = val; + } + + ScalarBase(bool val) : dtype_(DataType::BOOL) { // NOLINT + data_.b = val; + } + + ScalarBase(complex64 val) : dtype_(DataType::COMPLEX64) { // NOLINT + data_.c64 = val; + } + + ScalarBase(complex128 val) : dtype_(DataType::COMPLEX128) { // NOLINT + data_.c128 = val; + } + + // The compatible method for fliud operators, + // and it will be removed in the future. + explicit ScalarBase(const std::string& str_value) + : dtype_(DataType::FLOAT64) { + if (str_value == "inf") { + data_.f64 = std::numeric_limits::infinity(); + } else if (str_value == "-inf") { + data_.f64 = -std::numeric_limits::infinity(); + } else if (str_value == "nan") { + data_.f64 = std::numeric_limits::quiet_NaN(); + } else { + data_.f64 = std::stod(str_value); + } + } + + // The Tensor must have one dim + ScalarBase(const T& tensor_in); // NOLINT + + template + ScalarBase(const ScalarBase& other) { + CopyScalar(other, this); + } + + // NOTE(xiongkun): some op need to judge the dtype of the Scalar, we expose a + // interface. + bool FromTensor() const { return is_from_tensor_; } + + void SetFromTensor(bool from_tensor) { is_from_tensor_ = from_tensor; } + + template + inline RT to() const { + switch (dtype_) { + case DataType::FLOAT32: + return static_cast(data_.f32); + case DataType::FLOAT64: + return static_cast(data_.f64); + case DataType::FLOAT16: + return static_cast(data_.f16); + case DataType::BFLOAT16: + return static_cast(data_.bf16); + case DataType::INT32: + return static_cast(data_.i32); + case DataType::INT64: + return static_cast(data_.i64); + case DataType::INT16: + return static_cast(data_.i16); + case DataType::INT8: + return static_cast(data_.i8); + case DataType::UINT16: + return static_cast(data_.ui16); + case DataType::UINT8: + return static_cast(data_.ui8); + case DataType::BOOL: + return static_cast(data_.b); + case DataType::COMPLEX64: + return static_cast(data_.c64); + case DataType::COMPLEX128: + return static_cast(data_.c128); + default: + PD_THROW("Invalid enum scalar data type `", dtype_, "`."); + } + } + + DataType dtype() const { return dtype_; } + + private: + template + friend void CopyScalar(const ScalarBase& src, ScalarBase* dst); + void GetDataFromTensor(const T& tensor) { + is_from_tensor_ = true; + switch (dtype_) { + case DataType::FLOAT32: + data_.f32 = tensor.template data()[0]; + break; + case DataType::FLOAT64: + data_.f64 = tensor.template data()[0]; + break; + case DataType::FLOAT16: + data_.f16 = tensor.template data()[0]; + break; + case DataType::BFLOAT16: + data_.bf16 = tensor.template data()[0]; + break; + case DataType::INT32: + data_.i32 = tensor.template data()[0]; + break; + case DataType::INT64: + data_.i64 = tensor.template data()[0]; + break; + case DataType::INT16: + data_.i16 = tensor.template data()[0]; + break; + case DataType::INT8: + data_.i8 = tensor.template data()[0]; + break; + case DataType::UINT8: + data_.ui8 = tensor.template data()[0]; + break; + case DataType::BOOL: + data_.b = tensor.template data()[0]; + break; + case DataType::COMPLEX64: + data_.c64 = tensor.template data()[0]; + break; + case DataType::COMPLEX128: + data_.c128 = tensor.template data()[0]; + break; + default: + PD_THROW("Invalid tensor data type `", dtype_, "`."); + } + } + + private: + bool is_from_tensor_{false}; + DataType dtype_; + union data { + bool b; + int8_t i8; + int16_t i16; + int32_t i32; + int64_t i64; + uint8_t ui8; + uint16_t ui16; + uint32_t ui32; + uint64_t ui64; + bfloat16 bf16; + float16 f16; + float f32; + double f64; + complex64 c64; + complex128 c128; + } data_; +}; + +template +void CopyScalar(const ScalarBase& src, ScalarBase* dst) { + dst->dtype_ = src.dtype_; + dst->data_.c128 = src.data_.c128; +} + +using Scalar = paddle::experimental::ScalarBase; + +} // namespace experimental +} // namespace paddle + +namespace phi { +class DenseTensor; +using Scalar = paddle::experimental::ScalarBase; +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/type_traits.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/type_traits.h new file mode 100644 index 0000000000000000000000000000000000000000..ef894eee4683538b2bd3fafee103e0db8b32782b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/common/type_traits.h @@ -0,0 +1,96 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" + +namespace phi { +namespace dtype { + +template +struct cond { + static constexpr bool value = B; + using type = T; +}; + +template +struct eval_if { + using type = typename TrueF::type; +}; + +template +struct eval_if { + using type = typename FalseF::type; +}; + +template +using eval_if_t = typename eval_if::type; + +template +struct select { + using type = eval_if_t>; +}; + +template +struct select { + using type = T; +}; + +template +struct select> { + // last one had better be true! + static_assert(B, "No match select type!"); + using type = T; +}; + +template +using select_t = typename select::type; + +// runtime real and complex type conversion + +template +using Real = select_t>::value, float>, + cond>::value, double>, + T>; + +template +using Complex = select_t::value, complex>, + cond::value, complex>, + T>; + +inline DataType ToReal(DataType dtype) { + switch (dtype) { + case phi::DataType::COMPLEX64: + return phi::DataType::FLOAT32; + case phi::DataType::COMPLEX128: + return phi::DataType::FLOAT64; + default: + return dtype; + } +} + +inline DataType ToComplex(DataType dtype) { + switch (dtype) { + case phi::DataType::FLOAT32: + return phi::DataType::COMPLEX64; + case phi::DataType::FLOAT64: + return phi::DataType::COMPLEX128; + default: + return dtype; + } +} + +} // namespace dtype +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/allocator.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..849fc1548c7ec91a78899777aefa8aa58d61b3df --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/allocator.h @@ -0,0 +1,109 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include +#include + +#include "paddle/phi/common/place.h" + +namespace phi { + +/// \brief Fancy pointer with deleter. The use of this data type +/// is to be compatible with allocators from different frameworks +/// without significant performance loss. This class does not +/// support being inherited. +class Allocation { + public: + using Place = phi::Place; + using DeleterFnPtr = void (*)(Allocation*); + + Allocation() = default; + + // Don't own resources, only provide access. + Allocation(void* data, size_t size, const Place& place) + : ptr_(data), size_(size), place_(place) {} + + // Own resources. + Allocation(void* data, size_t size, DeleterFnPtr deleter, const Place& place) + : ptr_(data), size_(size), deleter_(deleter), place_(place) {} + + Allocation(Allocation&& other) noexcept { swap(*this, other); } + Allocation& operator=(Allocation&& other) noexcept { + // Exchange them explicitly to avoid moving is equivalent + // to copying. + swap(*this, other); + return *this; + } + + virtual ~Allocation() { + if (deleter_) { + deleter_(this); + } + } + + // Returns the holding pointer. + // NOTE: For performance consideration, it is better not to make this method + // as a virtual method. If we want to implement a `defragmentation` later, + // we might need to make `ptr_` field as a protected field, and add a virtual + // method like `defragmentation` to change `ptr_`. + void* ptr() const noexcept { return ptr_; } + + // Returns the size of this memory buffer, i.e., ptr() + size() - 1 is the + // last valid element. + // + // NOTE: Some allocator might alloc more memory than request. The size + // could larger than its request. For example, + // the AlignedAllocator will always allocate memory as size + kAlignment. + // The raw pointer might not aligned, so an offset might be added to raw + // the pointer. The size of this allocation will be + // `size + kAlignemnt - offset`. + size_t size() const noexcept { return size_; } + + void* operator->() const noexcept { return ptr_; } + operator bool() const noexcept { return ptr_; } + const Place& place() const noexcept { return place_; } + DeleterFnPtr deleter() const noexcept { return deleter_; } + + protected: + friend void swap(Allocation& a, Allocation& b) noexcept; + void* ptr_{nullptr}; + size_t size_{}; + DeleterFnPtr deleter_{nullptr}; + // TODO(Shixiaowei02): Enum needs to be used instead to reduce + // the construction overhead by more than 50%. + Place place_; +}; + +inline void swap(Allocation& a, Allocation& b) noexcept { + ::std::swap(a.ptr_, b.ptr_); + ::std::swap(a.deleter_, b.deleter_); + ::std::swap(a.place_, b.place_); + ::std::swap(a.size_, b.size_); +} + +class Allocator { + public: + using DeleterType = std::function; + using AllocationPtr = std::unique_ptr; + + virtual ~Allocator() = default; + virtual AllocationPtr Allocate(size_t bytes_size) = 0; + + virtual bool IsAllocThreadSafe() const { return false; } +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/attribute.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/attribute.h new file mode 100644 index 0000000000000000000000000000000000000000..d8d684b9030e9dc6ac062b930d92add7daa74745 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/attribute.h @@ -0,0 +1,53 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/utils/flat_hash_map.h" +#include "paddle/utils/variant.h" + +namespace phi { + +class Place; + +// NOTE: Add needed type in the future +using Attribute = paddle::variant, + std::vector, + std::vector, + std::vector, + std::vector, + std::vector, + Scalar, + std::vector, + IntArray, + DataType, + DataLayout, + Place>; + +using RuntimeAttrs = paddle::flat_hash_map; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/arg_map_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/arg_map_context.h new file mode 100644 index 0000000000000000000000000000000000000000..d680cda4aeea247f442d3e779bdc842009e97796 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/arg_map_context.h @@ -0,0 +1,135 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include + +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/utils/any.h" +#include "paddle/utils/flat_hash_map.h" +#include "paddle/utils/small_vector.h" + +namespace phi { + +// tuple(input_names, attr_names, output_names) +using KernelArgsTuple = std::tuple, + paddle::small_vector, + paddle::small_vector>; + +struct KernelSignature { + const char* name; + paddle::small_vector input_names; + paddle::small_vector attr_names; + paddle::small_vector output_names; + + KernelSignature() = default; + + KernelSignature(const char* kernel_name, + paddle::small_vector&& inputs, + paddle::small_vector&& attrs, + paddle::small_vector&& outputs) + : name(kernel_name), + input_names(std::move(inputs)), + attr_names(std::move(attrs)), + output_names(std::move(outputs)) {} + KernelSignature(const char* kernel_name, + const paddle::small_vector& inputs, + const paddle::small_vector& attrs, + const paddle::small_vector& outputs) + : name(kernel_name), + input_names(inputs), + attr_names(attrs), + output_names(outputs) {} + + // TODO(chenweihang): add assign constructor to solve windows compile + // problem, remove it later + KernelSignature(const KernelSignature& other) + : name(other.name), + input_names(other.input_names), + attr_names(other.attr_names), + output_names(other.output_names) {} + + KernelSignature(KernelSignature&& other) noexcept + : name(other.name), + input_names(std::move(other.input_names)), + attr_names(std::move(other.attr_names)), + output_names(std::move(other.output_names)) {} + + KernelSignature& operator=(const KernelSignature& other) { + name = other.name; + input_names = other.input_names; + attr_names = other.attr_names; + output_names = other.output_names; + return *this; + } + + KernelSignature& operator=(KernelSignature&& other) noexcept { + name = other.name; + input_names = std::move(other.input_names); + attr_names = std::move(other.attr_names); + output_names = std::move(other.output_names); + return *this; + } +}; + +std::ostream& operator<<(std::ostream& os, KernelSignature signature); + +// TODO(chenweihang): Add more methods if needed in future +class ArgumentMappingContext { + public: + virtual ~ArgumentMappingContext() = default; + + virtual bool HasInput(const std::string& name) const = 0; + virtual bool HasOutput(const std::string& name) const = 0; + virtual bool HasAttr(const std::string& name) const = 0; + + // now we can't use Attribute here, it will cause phi relay on + // paddle::variant and BlockDesc + virtual paddle::any Attr(const std::string& name) const = 0; + + virtual size_t InputSize(const std::string& name) const = 0; + virtual size_t OutputSize(const std::string& name) const = 0; + + virtual bool IsDenseTensorInput(const std::string& name) const = 0; + virtual bool IsDenseTensorInputs(const std::string& name) const = 0; + virtual bool IsSelectedRowsInput(const std::string& name) const = 0; + + virtual bool IsSparseCooTensorInput(const std::string& name) const = 0; + virtual bool IsSparseCsrTensorInput(const std::string& name) const = 0; + + virtual bool IsSelectedRowsInputs(const std::string& name) const = 0; + + // For compatibility with LoDTensorArray + virtual bool IsDenseTensorVectorInput(const std::string& name) const = 0; + + virtual bool IsDenseTensorOutput(const std::string& name) const = 0; + virtual bool IsSelectedRowsOutput(const std::string& name) const = 0; + + // use this function to mark it comes from InferShapeArgumentMappingContext + // and will be used in infershape + virtual bool IsForInferShape() const = 0; + + // NOTE(paddle-dev): [ Why do we export this interface? ] + // In old Fluid framework, some operators' Attribute can be a Tensor or + // TensorList. In this case, the InferShape logic will be different + // under CompileTime and RuntimeTime. So we export this interface to + // handle it conveniently. See "gaussian_random_sig.cc" for details. + virtual bool IsRuntime() const { return true; } +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/convert_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/convert_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6200ddbc1a16fbcb7cbd78353358ba09ac94fc03 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/convert_utils.h @@ -0,0 +1,40 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/backend.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/tensor_meta.h" + +#ifdef PADDLE_WITH_MKLDNN +#include "dnnl.hpp" +#endif + +namespace phi { + +const std::string& TransToPhiKernelName(const std::string& fluid_op_name); +const std::string& TransToFluidOpName(const std::string& phi_kernel_name); + +Backend TransToPhiBackend(const phi::Place& place); +phi::Place TransToPhiPlace(const Backend& backend, bool set_device_id = true); + +#ifdef PADDLE_WITH_MKLDNN +dnnl::memory::data_type TransToOneDNNDataType( + const paddle::experimental::DataType& dtype); +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/op_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/op_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..10b859fdac260396618116e0da5efbe3f3de192f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/compat/op_utils.h @@ -0,0 +1,242 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include + +#include "glog/logging.h" +#include "paddle/phi/core/compat/arg_map_context.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/infermeta_utils.h" +#include "paddle/phi/core/macros.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/utils/flat_hash_map.h" + +namespace phi { + +const static std::string deprecated_kernel_name = "deprecated"; // NOLINT + +const std::unordered_set standard_kernel_suffixs({ + "sr", // SelectedRows kernel + "raw" // fallback kernel of origfinal fluid op +}); + +/** + * Some fluid ops are no longer used under the corresponding official API + * system of 2.0. These names need to correspond to the official API names + * after 2.0, and can no longer be occupied by the previously abandoned ops. + * They are marked here uniformly. + */ +static const std::unordered_set deprecated_op_names( + {"diag", + "flatten", + "flatten_grad", + "isinf", + "isnan", + "unsqueeze", + "unsqueeze_grad", + "squeeze", + "squeeze_grad", + "isfinite", + "fill", + "matmul", + "matmul_grad", + "matmul_grad_grad", + "max", + "max_grad", + "min", + "min_grad", + "prod", + "prod_grad", + "any", + "all", + "reshape", + "reshape_grad", + "expand", + "expand_as", + "expand_grad", + "expand_as_grad", + "one_hot", + "top_k", + "top_k_grad", + "linear_interp", + "linear_interp_grad", + "bilinear_interp", + "bilinear_interp_grad", + "trilinear_interp", + "trilinear_interp_grad", + "nearest_interp", + "nearest_interp_grad", + "bicubic_interp", + "bicubic_interp_grad"}); + +class DefaultKernelSignatureMap { + public: + static DefaultKernelSignatureMap& Instance(); + + bool Has(const std::string& op_type) const { return map_.count(op_type) > 0; } + + const KernelSignature& Get(const std::string& op_type) const { + auto it = map_.find(op_type); + PADDLE_ENFORCE_NE( + it, + map_.end(), + phi::errors::NotFound( + "Operator `%s`'s kernel signature is not registered.", op_type)); + return it->second; + } + + const KernelSignature* GetNullable(const std::string& op_type) const { + auto it = map_.find(op_type); + if (it != map_.end()) { + return &it->second; + } + return nullptr; + } + + void Insert(std::string op_type, KernelSignature signature) { + PADDLE_ENFORCE_NE( + Has(op_type), + true, + phi::errors::AlreadyExists( + "Operator (%s)'s Kernel Siginature has been registered.", op_type)); + map_.insert({std::move(op_type), std::move(signature)}); + } + + private: + DefaultKernelSignatureMap() = default; + + paddle::flat_hash_map map_; + + DISABLE_COPY_AND_ASSIGN(DefaultKernelSignatureMap); +}; + +class OpUtilsMap { + public: + static OpUtilsMap& Instance(); + + bool Contains(const std::string& op_type) const { + return base_kernel_name_map_.count(op_type) || + arg_mapping_fn_map_.count(op_type); + } + + void InsertBaseKernelName(std::string op_type, std::string base_kernel_name) { + PADDLE_ENFORCE_EQ( + base_kernel_name_map_.count(op_type), + 0UL, + phi::errors::AlreadyExists( + "Operator (%s)'s api name has been registered.", op_type)); + base_kernel_name_map_.insert( + {std::move(op_type), std::move(base_kernel_name)}); + } + + bool HasArgumentMappingFn(const std::string& op_type) const { + return arg_mapping_fn_map_.count(op_type); + } + + void InsertArgumentMappingFn(std::string op_type, ArgumentMappingFn fn) { + PADDLE_ENFORCE_EQ( + arg_mapping_fn_map_.count(op_type), + 0UL, + phi::errors::AlreadyExists( + "Operator (%s)'s argu,emt mapping function has been registered.", + op_type)); + arg_mapping_fn_map_.insert({std::move(op_type), std::move(fn)}); + } + + const std::string& GetBaseKernelName(const std::string& op_type) const { + if (deprecated_op_names.find(op_type) != deprecated_op_names.end()) { + return deprecated_kernel_name; + } + auto it = base_kernel_name_map_.find(op_type); + if (it == base_kernel_name_map_.end()) { + return op_type; + } else { + return it->second; + } + } + + const ArgumentMappingFn* GetArgumentMappingFn( + const std::string& op_type) const { + auto it = arg_mapping_fn_map_.find(op_type); + if (it == arg_mapping_fn_map_.end()) { + return nullptr; + } else { + return &it->second; + } + } + + const paddle::flat_hash_map& base_kernel_name_map() + const { + return base_kernel_name_map_; + } + + private: + OpUtilsMap() = default; + + paddle::flat_hash_map base_kernel_name_map_; + paddle::flat_hash_map arg_mapping_fn_map_; + + DISABLE_COPY_AND_ASSIGN(OpUtilsMap); +}; + +struct BaseKernelNameRegistrar { + BaseKernelNameRegistrar(const char* op_type, const char* base_kernel_name) { + OpUtilsMap::Instance().InsertBaseKernelName(op_type, base_kernel_name); + } +}; + +struct ArgumentMappingFnRegistrar { + ArgumentMappingFnRegistrar(const char* op_type, + ArgumentMappingFn arg_mapping_fn) { + OpUtilsMap::Instance().InsertArgumentMappingFn(op_type, + std::move(arg_mapping_fn)); + } +}; + +#define PD_REGISTER_BASE_KERNEL_NAME(op_type, base_kernel_name) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_REGISTER_base_kernel_name_ns_check_##op_type, \ + "PD_REGISTER_BASE_KERNEL_NAME must be called in global namespace."); \ + static const ::phi::BaseKernelNameRegistrar \ + __registrar_base_kernel_name_for_##op_type(#op_type, #base_kernel_name); \ + int TouchBaseKernelNameSymbol_##op_type() { return 0; } + +#define PD_DECLARE_BASE_KERNEL_NAME(op_type) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_DECLARE_ai_name_ns_check_##op_type, \ + "PD_DECLARE_BASE_KERNEL_NAME must be called in global namespace."); \ + extern int TouchBaseKernelNameSymbol_##op_type(); \ + UNUSED static int __declare_base_kernel_name_symbol_for_##op_type = \ + TouchBaseKernelNameSymbol_##op_type() + +#define PD_REGISTER_ARG_MAPPING_FN(op_type, arg_mapping_fn) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_REGISTER_arg_map_fn_ns_check_##op_type, \ + "PD_REGISTER_ARG_MAPPING_FN must be called in global namespace."); \ + static const ::phi::ArgumentMappingFnRegistrar \ + __registrar_arg_map_fn_for_##op_type(#op_type, arg_mapping_fn); \ + int TouchArgumentMappingFnSymbol_##op_type() { return 0; } + +#define PD_DECLARE_ARG_MAPPING_FN(op_type) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_DECLARE_arg_map_fn_ns_check_##op_type, \ + "PD_DECLARE_ARG_MAPPING_FN must be called in global namespace."); \ + extern int TouchArgumentMappingFnSymbol_##op_type(); \ + UNUSED static int __declare_arg_map_fn_symbol_for_##op_type = \ + TouchArgumentMappingFnSymbol_##op_type() + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/cuda_stream.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/cuda_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..61aa9648dbabfcb7da6c22ff90278aa1d13b197f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/cuda_stream.h @@ -0,0 +1,154 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/backends/gpu/gpu_info.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/stream.h" + +#ifdef PADDLE_WITH_CUDA +#include +using gpuStream_t = cudaStream_t; +#endif + +#ifdef PADDLE_WITH_HIP +#include +using gpuStream_t = hipStream_t; +#endif + +// TODO(phi): remove fluid headers. +#include "paddle/fluid/platform/enforce.h" + +namespace phi { + +// Currently, CudaStream is used in python-side API only +class CUDAStream { + public: + enum class Priority : uint8_t { + kNull = 0x0, + kHigh = 0x1, + kNormal = 0x2, + }; + + enum class StreamFlag : uint8_t { + kDefaultFlag = 0x0, + kStreamNonBlocking = 0x1, + }; + + public: + CUDAStream(const Place& place, const Stream& stream) + : place_(place), stream_(stream) {} + CUDAStream(const Place& place, + const Priority& priority = Priority::kNormal, + const StreamFlag& flag = StreamFlag::kDefaultFlag) { + place_ = place; + gpuStream_t stream = nullptr; + backends::gpu::GPUDeviceGuard guard(place_.device); + if (priority == Priority::kHigh) { +#ifdef PADDLE_WITH_HIP + PADDLE_ENFORCE_GPU_SUCCESS(hipStreamCreateWithPriority( + &stream, static_cast(flag), -1)); +#else + PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamCreateWithPriority( + &stream, static_cast(flag), -1)); +#endif + } else if (priority == Priority::kNormal) { +#ifdef PADDLE_WITH_HIP + PADDLE_ENFORCE_GPU_SUCCESS(hipStreamCreateWithPriority( + &stream, static_cast(flag), 0)); +#else + PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamCreateWithPriority( + &stream, static_cast(flag), 0)); +#endif + } + VLOG(10) << "CUDAStream " << stream; + stream_ = Stream(reinterpret_cast(stream)); + owned_ = true; + } + + gpuStream_t raw_stream() const { return reinterpret_cast(id()); } + + void set_raw_stream(gpuStream_t stream) { + if (owned_ && stream_.id() != 0) { + backends::gpu::GPUDeviceGuard guard(place_.device); +#ifdef PADDLE_WITH_HIP + PADDLE_ENFORCE_GPU_SUCCESS(hipStreamDestroy(raw_stream())); +#else + PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamDestroy(raw_stream())); +#endif + } + stream_ = Stream(reinterpret_cast(stream)); + } + + StreamId id() const { return stream_.id(); } + + Place place() const { return place_; } + + bool Query() const { +#ifdef PADDLE_WITH_HIP + hipError_t err = hipStreamQuery(raw_stream()); + if (err == hipSuccess) { + return true; + } + if (err == hipErrorNotReady) { + return false; + } +#else + cudaError_t err = cudaStreamQuery(raw_stream()); + if (err == cudaSuccess) { + return true; + } + if (err == cudaErrorNotReady) { + return false; + } +#endif + + PADDLE_ENFORCE_GPU_SUCCESS(err); + return false; + } + + void Synchronize() const { + VLOG(10) << "Synchronize " << raw_stream(); + backends::gpu::GpuStreamSync(raw_stream()); + } + + void WaitEvent(gpuEvent_t ev) const { +#ifdef PADDLE_WITH_HIP + PADDLE_ENFORCE_GPU_SUCCESS(hipStreamWaitEvent(raw_stream(), ev, 0)); +#else + PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamWaitEvent(raw_stream(), ev, 0)); +#endif + } + + ~CUDAStream() { + VLOG(10) << "~CUDAStream " << raw_stream(); + Synchronize(); + if (owned_ && stream_.id() != 0) { + backends::gpu::GPUDeviceGuard guard(place_.device); +#ifdef PADDLE_WITH_HIP + hipStreamDestroy(raw_stream()); +#else + cudaStreamDestroy(raw_stream()); +#endif + } + } + + private: + Place place_; + Stream stream_; + bool owned_{false}; // whether the stream is created and onwed by self +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/custom_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/custom_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5ba14de6a6131c1b2e2fefb5d4eca306d0c4e0b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/custom_kernel.h @@ -0,0 +1,49 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/kernel_factory.h" +#include "paddle/phi/core/macros.h" + +namespace phi { +/** + * Note: + * Used to store kernels' info before registered to KernelFactory. + */ +class CustomKernelMap { + public: + static CustomKernelMap& Instance() { + static CustomKernelMap g_custom_kernel_info_map; + return g_custom_kernel_info_map; + } + + void RegisterCustomKernel(const std::string& kernel_name, + const KernelKey& kernel_key, + const Kernel& kernel); + + void RegisterCustomKernels(); + + KernelNameMap& Kernels() { return kernels_; } + + const KernelNameMap& GetMap() const { return kernels_; } + + private: + CustomKernelMap() = default; + DISABLE_COPY_AND_ASSIGN(CustomKernelMap); + + KernelNameMap kernels_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/ddim.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/ddim.h new file mode 100644 index 0000000000000000000000000000000000000000..794d7051aee58e4fc63c40f2d7dd361ed6b834ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/ddim.h @@ -0,0 +1,264 @@ +// Copyright (c) 2022 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. +#pragma once +#include +#include +#include +#include +#include + +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/utils/dim.h" + +namespace phi { + +#define PADDLE_VISIT_DDIM_BASE(rank, callback) \ + case (rank): { \ + constexpr auto kRank = (rank); \ + return (callback); \ + } + +#define PADDLE_VISIT_DDIM(rank, callback) \ + switch (rank) { \ + PADDLE_VISIT_DDIM_BASE(0, callback); \ + PADDLE_VISIT_DDIM_BASE(1, callback); \ + PADDLE_VISIT_DDIM_BASE(2, callback); \ + PADDLE_VISIT_DDIM_BASE(3, callback); \ + PADDLE_VISIT_DDIM_BASE(4, callback); \ + PADDLE_VISIT_DDIM_BASE(5, callback); \ + PADDLE_VISIT_DDIM_BASE(6, callback); \ + PADDLE_VISIT_DDIM_BASE(7, callback); \ + PADDLE_VISIT_DDIM_BASE(8, callback); \ + PADDLE_VISIT_DDIM_BASE(9, callback); \ + default: \ + PADDLE_THROW(phi::errors::Unimplemented( \ + "Invalid dimension to be accessed. Now only supports access to " \ + "dimension 0 to 9, but received dimension is %d.", \ + rank)); \ + } + +template +inline void dynamic_dim_assign(const T1* in, T2* out, int n) { + PADDLE_VISIT_DDIM(n, (static_dim_assign(in, out))); +} + +/** + * \brief A dynamically sized dimension. + * + * The number of dimensions must be between [1, 9]. + */ +class DDim { + public: + constexpr static int kMaxRank = 9; + + DDim() : rank_(1) { dim_[0] = 0; } + + DDim(const DDim& ddim) : dim_() { CopyFrom(ddim); } + + DDim(const int* d, int n) : rank_(n) { + dynamic_dim_assign(d, dim_.GetMutable(), n); + } + + DDim(const int64_t* d, int n) : rank_(n) { + dynamic_dim_assign(d, dim_.GetMutable(), n); + } + + template + /*implicit*/ DDim(const Dim& in) : rank_(D) { // NOLINT + UnsafeCast() = in; + } + + /*implicit*/ DDim(std::initializer_list init_list) + : DDim(init_list.begin(), init_list.size()) {} + + inline DDim& operator=(const DDim& ddim) { return CopyFrom(ddim); } + + template + inline DDim& operator=(const Dim& dim) { + rank_ = D; + UnsafeCast() = dim; + return *this; + } + + inline int64_t& operator[](int idx) { return dim_[idx]; } + + inline int64_t operator[](int idx) const { return dim_[idx]; } + + int64_t& at(int idx) { + PADDLE_ENFORCE_GE(idx, + 0, + phi::errors::InvalidArgument( + "Invalid DDim index to be accessed. The valid index " + "is between 0 and %d, but received index is %d.", + rank_, + idx)); + PADDLE_ENFORCE_LT(idx, + rank_, + phi::errors::InvalidArgument( + "Invalid DDim index to be accessed. The valid index " + "is between 0 and %d, but received index is %d.", + rank_, + idx)); + return dim_[idx]; + } + + int64_t at(int idx) const { + PADDLE_ENFORCE_GE(idx, + 0, + phi::errors::InvalidArgument( + "Invalid DDim index to be accessed. The valid index " + "is between 0 and %d, but received index is %d.", + rank_, + idx)); + PADDLE_ENFORCE_LT(idx, + rank_, + phi::errors::InvalidArgument( + "Invalid DDim index to be accessed. The valid index " + "is between 0 and %d, but received index is %d.", + rank_, + idx)); + return dim_[idx]; + } + + template + typename std::result_of&)>::type apply_visitor( + Visitor&& visitor) { + PADDLE_VISIT_DDIM(rank_, visitor(UnsafeCast())); + } + + template + typename std::result_of&)>::type apply_visitor( + Visitor&& visitor) const { + PADDLE_VISIT_DDIM(rank_, visitor(UnsafeCast())); + } + + bool operator==(const DDim& d) const; + + bool operator!=(const DDim& d) const; + + inline const int64_t* Get() const { return dim_.Get(); } + + inline int64_t* GetMutable() { return dim_.GetMutable(); } + + inline int size() const { return rank_; } + + std::string to_str() const; + + DDim reshape(std::vector& shape) const; + + DDim transpose(const std::vector& axis) const; + + private: + template + inline Dim& UnsafeCast() { + static_assert(D >= 0 && D <= kMaxRank, "Invalid rank"); + auto* p = static_cast(&dim_); + return *reinterpret_cast*>(p); + } + + template + inline const Dim& UnsafeCast() const { + static_assert(D >= 0 && D <= kMaxRank, "Invalid rank"); + auto* p = static_cast(&dim_); + return *reinterpret_cast*>(p); + } + + inline DDim& CopyFrom(const DDim& ddim) { + PADDLE_VISIT_DDIM(ddim.rank_, (*this = ddim.UnsafeCast())); + } + + friend DDim stride(const DDim& ddim); + friend DDim stride_numel(const DDim& ddim); + + private: + Dim dim_; + int rank_; +}; + +#undef PADDLE_VISIT_DDIM_BASE +#undef PADDLE_VISIT_DDIM + +/** + * \brief Make a DDim from std::vector + * + * \param dims An vector of ints. Must be sized between [1, 9] + */ +DDim make_ddim(const std::vector& dims); + +DDim make_ddim(const std::vector& dims); + +/** + * \brief Make a DDim from an initializer list + * + * \param dims An initializer list of ints. Must be sized between [1, 9] + * + */ +DDim make_ddim(std::initializer_list dims); + +template +std::vector vectorize(const DDim& ddim) { + std::vector result(DDim::kMaxRank); + dynamic_dim_assign(ddim.Get(), result.data(), ddim.size()); + result.resize(ddim.size()); + return result; +} + +int64_t product(const DDim& ddim); + +bool contain_unknown_dim(const DDim& ddim); + +/** + * \brief Slice a ddim + * + * Slice dim with [begin, end). + * e.g. DDim d = make_ddim({1,2,3,4,5}); + * slice_ddim(d, 1, 3); ====> {2,3} + */ +DDim slice_ddim(const DDim& dim, int begin, int end); + +/** + * \brief What is the length of this dimension? + * + * \param Dynamic dimension to inspect + */ + +int arity(const DDim& ddim); + +std::ostream& operator<<(std::ostream&, const DDim&); + +/** + * \brief Flatten dim to 3d + * e.g., DDim d = mak_ddim({1, 2, 3, 4, 5, 6}) + * flatten_to_3d(d, 2, 4); ===> {1*2, 3*4, 5*6} ===> {2, 12, 30} + */ +DDim flatten_to_3d(const DDim& src, int num_row_dims, int num_col_dims); + +// Reshape a tensor to a matrix. The matrix's first dimension(column length) +// will be the product of tensor's first `num_col_dims` dimensions. +DDim flatten_to_2d(const DDim& src, int num_col_dims); + +DDim flatten_to_1d(const DDim& src); + +DDim stride(const DDim& ddim); + +DDim stride_numel(const DDim& ddim); +} // namespace phi + +namespace paddle { +namespace framework { + +using DDim = phi::DDim; + +} // namespace framework +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/dense_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/dense_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..e9a6be66b98caba1acc39ad428fb281900c44fe8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/dense_tensor.h @@ -0,0 +1,249 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/allocator.h" +#include "paddle/phi/core/stream.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" + +/* @jim19930609: Move to MKLDNN_Tensor in the future + */ +#ifdef PADDLE_WITH_MKLDNN +#include "dnnl.hpp" // NOLINT +#endif + +namespace phi { + +class DenseTensorUtils; + +/// \brief The Dense tensor stores values in a contiguous sequential block +/// of memory where all values are represented. Tensors or multi-dimensional +/// arrays are used in math operators. +/// During the entire life cycle of a DenseTensor, its device type and key +/// metadata are set unchanged. +class DenseTensor : public TensorBase, + public TypeInfoTraits { + public: + /// \brief Construct a dense tensor and allocate space. + /// \param a The allocator used to allocate space. + /// \param meta The meta data of dense tensor. + DenseTensor(Allocator* a, const DenseTensorMeta& meta); + + /// \brief Construct a dense tensor and allocate space. + /// \param a The allocator used to allocate space. + /// \param meta The meta data of dense tensor. + DenseTensor(Allocator* a, DenseTensorMeta&& meta); + + DenseTensor(const std::shared_ptr& holder, + const DenseTensorMeta& meta); + + /// \brief Because dense tensor is a kind of container, we give a default + /// constructor to use for stl container. But the dense tensor created with + /// the default constructor is not practical. + // DenseTensor() = default; + + /// \brief Because dense tensor is a resource handle, we provide a default + /// move constructor to support move semantics. + DenseTensor(DenseTensor&& other) = default; + + /// \brief DenseTensor shallow copy constructor. + DenseTensor(const DenseTensor& other); + + /// \brief DenseTensor shallow copy assignment. + DenseTensor& operator=(const DenseTensor& other); + + DenseTensor& operator=(DenseTensor&& other); + + DenseTensor(); + + /// \brief Destroy the tensor object and release exclusive resources. + virtual ~DenseTensor() = default; + + public: + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "DenseTensor"; } + + /// \brief Returns the number of elements contained in tensor. + /// \return The number of elements contained in tensor. + int64_t numel() const override; + + /// \brief Returns the dims of the tensor. + /// \return The dims of the tensor. + const DDim& dims() const noexcept override { return meta_.dims; } + + /// \brief Returns the lod of the tensor. + /// \return The lod of the tensor. + const LoD& lod() const noexcept { return meta_.lod; } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept override { return meta_.dtype; } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept override { return meta_.layout; } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const override; + + /// \brief Returns the meta information of the tensor. + /// \return The meta information of the tensor. + const DenseTensorMeta& meta() const noexcept { return meta_; } + + /// \brief Sets the meta information of the tensor. Only when the original + /// attribute of Tensor is incomplete, can it be reset. + /// \param meta The meta information of the tensor. + void set_meta(DenseTensorMeta&& meta); + + void set_meta(const DenseTensorMeta& meta); + + /// \brief Test whether the metadata is valid. + /// \return Whether the metadata is valid. + bool valid() const noexcept override { return meta_.valid(); } + + /// \brief Test whether the allocation is allocated. + /// return Whether the allocation is allocated. + bool initialized() const override { return holder_ && holder_->ptr(); } + + /// \brief Allocate memory with requested size from allocator. + /// \return The mutable data pointer value of type T. + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override; + + /// \brief Check if allocation is shared with other objects. + /// \return Whether the allocation is shared with other objects. + bool IsSharedWith(const DenseTensor& b) const; + + /// \brief Change the shape information in the metadata. If the new size is + /// larger than the original value, the allocation area will be reallocated. + /// \param dims The new dims of the dense tensor. + /// \param lod The new lod of the dense tensor. + // void Resize(const DDim& dims); + void ResizeAndAllocate(const DDim& dims); + + DenseTensor& Resize(const DDim& dims); + + /// \brief Change the lod information in the metadata. + /// \param lod The new lod of the dense tensor. + void ResetLoD(const LoD& lod); + + /// \brief Returns the actual allocation size occupied by tensor, may be + /// larger + /// than its shape dims. + /// \return The actual allocation size occupied by tensor. + size_t capacity() const { return holder_->size(); } + + /// \brief Get the const data pointer value of type T. + /// \return The const data pointer value of type T. + template + const T* data() const; + + /// \brief Get the const data pointer value of raw type. + /// \return The const data pointer value of raw type. + const void* data() const; + + template + T* data(); + + void* data(); + + private: + friend class DenseTensorUtils; + + protected: + DenseTensorMeta meta_; + std::shared_ptr holder_; + + public: + /* Temporarily put InplaceVersion inside DenseTensor. + Will move to AutogradMeta as soon as we switch to Eager Dygraph. + */ + /* + NOTE(liym27): [ What is TensorInplaceVersion used for? ] + + TensorInplaceVersion is a version counter and every Tensor has a version + counter. It's used to check whether an inplace operation will result in an + incorrect gradient calculation. Version is incremented when the data of the + Variable is modified in place. + + - Question: In what scenarios will version counters be shared? + - Answer: When two Variables/VarBases share the same C++ Tensor(its Allocation + may change), both of them share the same version counter. For examples: + 1. `z = paddle.assign(input=x, output=y)`, `z` shares the same version + counter of `y` because z and y is the same VarBase; + 2. `y = x.detach()`, `y` shares the same version counter of `x`. + + - Question: In what scenarios will version counters NOT be shared? + - Answer: Replacing a `Variable`'s data by calling + `Tensor::ShareDataWith(...)` or `Tensor::ShareBufferWith(...)`. Because they + share the same Allocation but not framework::Tensor. + + - Question: Why put the inplace_version_counter_ in framework::Tensor instead + of Allocation or Variable? + - Answer: + 1. Tensor can call ResetHolder() to reset the corresponding Allocation so + that the inplace_version_counter_ changes if it's in Allocation, which will + lead to confusing information about inplace version. + 2. If inplace_version_counter_ is in Variable, different VariableWrappers + should be able to share the same Variable. However, a VariableWrapper hold a + Variable object but not a pointer. + */ + class InplaceVersion { + public: + bool IsUnique() const { return inplace_version_ == 0; } + void Bump() { ++inplace_version_; } + uint32_t CurrentVersion() const { return inplace_version_; } + void SetInplaceVersionToZero() { inplace_version_ = 0; } + + private: + uint32_t inplace_version_{0}; + }; + + protected: + std::shared_ptr inplace_version_counter_{ + std::make_shared()}; + +/* @jim19930609: This is a hack +In general, it is badly designed to fuse MKLDNN-specific objects into a +generic Tensor. +We temporarily leave them here to unblock Tensor Unification progress. +In the final state, we should come up with a MKLDNN_Tensor and move the +following codes there. +*/ +#ifdef PADDLE_WITH_MKLDNN + /** + * @brief the detail format of memory block which have layout as kMKLDNN + * + * @note MKLDNN lib support various memory format like nchw, nhwc, nChw8C, + * nChw16c, etc. For a MKLDNN memory block, layout will be set as + * DataLayout::kMKLDNN meanwhile detail memory format will be kept in + * this field. + */ + dnnl::memory::format_tag format_ = dnnl::memory::format_tag::undef; + + /// \brief memory descriptor of tensor which have layout set as kMKLDNN + dnnl::memory::desc mem_desc_; +#endif + +#ifndef PADDLE_WITH_CUSTOM_KERNEL +#include "paddle/phi/core/dense_tensor.inl" +#endif +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/device_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/device_context.h new file mode 100644 index 0000000000000000000000000000000000000000..c845d50f77564dd0eb73f7a6e524ba6528bed3b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/device_context.h @@ -0,0 +1,196 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/api/include/dll_decl.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/allocator.h" +#include "paddle/phi/core/generator.h" + +namespace phi { +class TensorBase; + +/** + * DeviceContext provides device-related interfaces. + * + * All kernels must access the interfaces provided by the backend through + * DeviceContext. + */ +class PADDLE_API DeviceContext { + using DataType = paddle::experimental::DataType; + + public: + /** + * @brief Default construct. + */ + DeviceContext(); + + /** + * @brief Copy construct. + */ + DeviceContext(const DeviceContext&); + + /** + * @brief Move construct. + */ + DeviceContext(DeviceContext&&); + + /** + * @brief Move assign operator. + */ + DeviceContext& operator=(DeviceContext&&); + + /** + * @brief Default destruct. + */ + virtual ~DeviceContext(); + + /** + * @brief Set the device-related Allocator object. + * + * @param allocator + */ + void SetAllocator(const Allocator*); + + /** + * @brief Set the host Allocator object. + * + * @param allocator + */ + void SetHostAllocator(const Allocator*); + + /** + * @brief Set the zero-size Allocator object. + * + * @param allocator + */ + void SetZeroAllocator(const Allocator*); + + /** + * @brief Set the zero-size Allocator object. + * + * @param allocator + */ + void SetPinnedAllocator(const Allocator*); + + /** + * @brief Get the const Allocator object. + * + * @return Allocator + */ + const Allocator& GetAllocator() const; + + /** + * @brief Get the const device-related Allocator object. + * + * @return Allocator + */ + const Allocator& GetHostAllocator() const; + + const Allocator& GetZeroAllocator() const; + + const Allocator& GetPinnedAllocator() const; + +#ifdef PADDLE_WITH_CUDA + /** + * @brief Set the CUDA graph Allocator object. + * + * @param allocator + */ + void SetCUDAGraphAllocator(const Allocator*); + + /** + * @brief Get the const CUDA graph Allocator object. + * + * @return Allocator + */ + const Allocator& GetCUDAGraphAllocator() const; + + /** + * @brief Test whether the CUDA graph allocator is valid + * + * This method should be called before calling GetCUDAGraphAllocator(). + * Other unit can calls GetCUDAGraphAllocator() method, + * only when this method returns True! + * + * @return true if cuda_graph_allocator_ is valid, false otherwise + */ + bool IsCUDAGraphAllocatorValid() const; +#endif + + /** + * @brief Allocate device memory for tensor. + */ + void* Alloc(TensorBase*, + DataType dtype, + size_t requested_size = 0, + bool pinned = false) const; + + template + T* Alloc(TensorBase* tensor, + size_t requested_size = 0, + bool pinned = false) const; + + /** + * @brief Allocate host memory for tensor. + */ + void* HostAlloc(TensorBase* tensor, + DataType dtype, + size_t requested_size = 0) const; + + template + T* HostAlloc(TensorBase* tensor, size_t requested_size = 0) const; + + virtual const Place& GetPlace() const = 0; + + // TODO(wilber): The fluid framework uses wait() in many places, how to delete + // this API interface. + virtual void Wait() const {} + + /** + * @brief Set the generator for special op. + * + * @param Generator + */ + void SetGenerator(Generator*); + /** + * @brief Get the generator object. + * + * @return Generator + */ + Generator* GetGenerator() const; + + /** + * @brief Set the host generator for special op. + * + * @param Generator + */ + void SetHostGenerator(Generator*); + /** + * @brief Get the host generator object. + * + * @return Generator + */ + Generator* GetHostGenerator() const; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/enforce.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/enforce.h new file mode 100644 index 0000000000000000000000000000000000000000..8da2623bb2c2d4f64623dabb46fc115e3687cdb0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/enforce.h @@ -0,0 +1,489 @@ +/* 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. */ + +#pragma once + +#ifdef __GNUC__ +#include // for __cxa_demangle +#endif // __GNUC__ + +#if !defined(_WIN32) +#include // dladdr +#include // sleep, usleep +#else // _WIN32 +#ifndef NOMINMAX +#define NOMINMAX // msvc max/min macro conflict with std::min/max +#endif +#include // GetModuleFileName, Sleep +#endif + +#include +#include +#include +#include + +#if !defined(_WIN32) && !defined(PADDLE_WITH_MUSL) +#include +#endif + +#include "gflags/gflags.h" + +#define GLOG_NO_ABBREVIATED_SEVERITIES // msvc conflict logging with windows.h +#include "paddle/phi/core/errors.h" +#include "paddle/utils/string/printf.h" +#include "paddle/utils/string/to_string.h" + +DECLARE_int32(call_stack_level); + +namespace phi { +class ErrorSummary; +} // namespace phi + +namespace phi { +namespace enforce { + +/** HELPER MACROS AND FUNCTIONS **/ +#ifndef PADDLE_MAY_THROW +#define PADDLE_MAY_THROW noexcept(false) +#endif + +// Because most enforce conditions would evaluate to true, we can use +// __builtin_expect to instruct the C++ compiler to generate code that +// always forces branch prediction of true. +// This generates faster binary code. __builtin_expect is since C++11. +// For more details, please check https://stackoverflow.com/a/43870188/724872. +#if !defined(_WIN32) +#define UNLIKELY(condition) __builtin_expect(static_cast(condition), 0) +#else +// there is no equivalent intrinsics in msvc. +#define UNLIKELY(condition) (condition) +#endif + +#if !defined(_WIN32) +#define LIKELY(condition) __builtin_expect(static_cast(condition), 1) +#else +// there is no equivalent intrinsics in msvc. +#define LIKELY(condition) (condition) +#endif + +#if defined _WIN32 && defined PADDLE_ON_INFERENCE && defined PADDLE_NO_PYTHON +#define HANDLE_THE_ERROR try { +#define END_HANDLE_THE_ERROR \ + } \ + catch (const std::exception& e) { \ + std::cout << e.what() << std::endl; \ + throw; \ + } +#else +#define HANDLE_THE_ERROR +#define END_HANDLE_THE_ERROR +#endif + +#ifdef __GNUC__ +inline std::string demangle(std::string name) { + int status = -4; // some arbitrary value to eliminate the compiler warning + std::unique_ptr res{ + abi::__cxa_demangle(name.c_str(), NULL, NULL, &status), std::free}; + return (status == 0) ? res.get() : name; +} +#else +inline std::string demangle(std::string name) { return name; } +#endif + +namespace details { +template +inline constexpr bool IsArithmetic() { + return std::is_arithmetic::value; +} + +template +struct TypeConverterImpl { + using Type1 = typename std::common_type::type; + using Type2 = Type1; +}; + +template +struct TypeConverterImpl { + using Type1 = T1; + using Type2 = T2; +}; + +template +struct TypeConverter { + static constexpr bool kIsArithmetic = + IsArithmetic() && IsArithmetic(); + using Type1 = typename TypeConverterImpl::Type1; + using Type2 = typename TypeConverterImpl::Type2; +}; + +template +using CommonType1 = typename std::add_lvalue_reference< + typename std::add_const::Type1>::type>::type; + +template +using CommonType2 = typename std::add_lvalue_reference< + typename std::add_const::Type2>::type>::type; + +// Here, we use SFINAE to check whether T can be converted to std::string +template +struct CanToString { + private: + using YesType = uint8_t; + using NoType = uint16_t; + + template + static YesType Check(decltype(std::cout << std::declval())) { + return 0; + } + + template + static NoType Check(...) { + return 0; + } + + public: + static constexpr bool kValue = + std::is_same(std::cout))>::value; +}; + +template +struct BinaryCompareMessageConverter { + template + static std::string Convert(const char* expression, const T& value) { + return expression + std::string(":") + paddle::string::to_string(value); + } +}; + +template <> +struct BinaryCompareMessageConverter { + template + static const char* Convert(const char* expression, const T& value) { + return expression; + } +}; +} // namespace details + +std::string GetCurrentTraceBackString(bool for_signal = false); +std::string SimplifyErrorTypeFormat(const std::string& str); + +template +static std::string GetErrorSumaryString(StrType&& what, + const char* file, + int line) { + std::ostringstream sout; + if (FLAGS_call_stack_level > 1) { + sout << "\n----------------------\nError Message " + "Summary:\n----------------------\n"; + } + sout << paddle::string::Sprintf( + "%s (at %s:%d)", std::forward(what), file, line) + << std::endl; + return sout.str(); +} + +template +std::string GetCompleteTraceBackString(StrType&& what, + const char* file, + int line) { + std::ostringstream sout; + sout << "\n----------------------\nError Message " + "Summary:\n----------------------\n"; + sout << paddle::string::Sprintf( + "%s (at %s:%d)", std::forward(what), file, line) + << std::endl; + return GetCurrentTraceBackString() + sout.str(); +} + +template +static std::string GetTraceBackString(StrType&& what, + const char* file, + int line) { + if (FLAGS_call_stack_level > 1) { + // FLAGS_call_stack_level>1 means showing c++ call stack + return GetCurrentTraceBackString() + GetErrorSumaryString(what, file, line); + } else { + return GetErrorSumaryString(what, file, line); + } +} + +inline bool is_error(bool stat) { return !stat; } + +// Note: This Macro can only be used within enforce.h +#define __THROW_ERROR_INTERNAL__(__ERROR_SUMMARY) \ + do { \ + HANDLE_THE_ERROR \ + throw ::phi::enforce::EnforceNotMet(__ERROR_SUMMARY, __FILE__, __LINE__); \ + END_HANDLE_THE_ERROR \ + } while (0) + +/** ENFORCE EXCEPTION AND MACROS **/ + +struct EnforceNotMet : public std::exception { + public: + EnforceNotMet(std::exception_ptr e, const char* file, int line) { + try { + std::rethrow_exception(e); + } catch (EnforceNotMet& e) { + code_ = e.code(); + err_str_ = GetTraceBackString(e.what(), file, line); + simple_err_str_ = SimplifyErrorTypeFormat(err_str_); + } catch (std::exception& e) { + err_str_ = GetTraceBackString(e.what(), file, line); + simple_err_str_ = SimplifyErrorTypeFormat(err_str_); + } + } + + EnforceNotMet(const std::string& str, const char* file, int line) + : err_str_(GetTraceBackString(str, file, line)) { + simple_err_str_ = SimplifyErrorTypeFormat(err_str_); + } + + EnforceNotMet(const phi::ErrorSummary& error, const char* file, int line) + : code_(error.code()), + err_str_(GetTraceBackString(error.to_string(), file, line)) { + simple_err_str_ = SimplifyErrorTypeFormat(err_str_); + } + + const char* what() const noexcept override { + if (FLAGS_call_stack_level > 1) { + return err_str_.c_str(); + } else { + return simple_err_str_.c_str(); + } + } + + phi::ErrorCode code() const { return code_; } + + const std::string& error_str() const { return err_str_; } + + const std::string& simple_error_str() const { return simple_err_str_; } + + void set_error_str(std::string str) { + if (FLAGS_call_stack_level > 1) { + err_str_ = str; + } else { + simple_err_str_ = str; + } + } + + ~EnforceNotMet() override = default; + + private: + // Used to determine the final type of exception thrown + phi::ErrorCode code_ = phi::ErrorCode::LEGACY; + // Complete error message + // e.g. InvalidArgumentError: *** + std::string err_str_; + // Simple errror message used when no C++ stack and python compile stack + // e.g. (InvalidArgument) *** + std::string simple_err_str_; +}; + +#define PADDLE_THROW(...) \ + do { \ + HANDLE_THE_ERROR \ + throw ::phi::enforce::EnforceNotMet( \ + ::phi::ErrorSummary(__VA_ARGS__), __FILE__, __LINE__); \ + END_HANDLE_THE_ERROR \ + } while (0) + +#if defined(__CUDA_ARCH__) +// For cuda, the assertions can affect performance and it is therefore +// recommended to disable them in production code +// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#assertion +#define PADDLE_ENFORCE(_IS_NOT_ERROR, __FORMAT, ...) \ + do { \ + if (!(_IS_NOT_ERROR)) { \ + printf("Error: %s:%d Assertion `%s` failed. " __FORMAT "\n", \ + __FILE__, \ + __LINE__, \ + #_IS_NOT_ERROR, \ + ##__VA_ARGS__); \ + asm("trap;"); \ + } \ + } while (0) +#elif defined(__HIPCC__) +#define PADDLE_ENFORCE(_IS_NOT_ERROR, __FORMAT, ...) \ + do { \ + if (!(_IS_NOT_ERROR)) { \ + printf("Error: %s:%d Assertion `%s` failed. " __FORMAT "\n", \ + __FILE__, \ + __LINE__, \ + #_IS_NOT_ERROR, \ + ##__VA_ARGS__); \ + abort(); \ + } \ + } while (0) +#else +#define PADDLE_ENFORCE(COND, ...) \ + do { \ + auto __cond__ = (COND); \ + if (UNLIKELY(::phi::is_error(__cond__))) { \ + __THROW_ERROR_INTERNAL__(phi::ErrorSummary(__VA_ARGS__)); \ + } \ + } while (0) +#endif + +/* + * Some enforce helpers here, usage: + * int a = 1; + * int b = 2; + * PADDLE_ENFORCE_EQ(a, b); + * + * will raise an expression described as follows: + * "Expected input a == b, but received a(1) != b(2)." + * with detailed stack information. + * + * extra messages is also supported, for example: + * PADDLE_ENFORCE(a, b, "some simple enforce failed between %d numbers", 2) + */ + +#define PADDLE_ENFORCE_NOT_NULL(__VAL, ...) \ + do { \ + if (UNLIKELY(nullptr == (__VAL))) { \ + auto __summary__ = phi::ErrorSummary(__VA_ARGS__); \ + auto __message__ = ::paddle::string::Sprintf( \ + "%s\n [Hint: " #__VAL " should not be null.]", \ + __summary__.error_message()); \ + __THROW_ERROR_INTERNAL__( \ + phi::ErrorSummary(__summary__.code(), __message__)); \ + } \ + } while (0) + +#define __PADDLE_BINARY_COMPARE(__VAL1, __VAL2, __CMP, __INV_CMP, ...) \ + do { \ + auto __val1 = (__VAL1); \ + auto __val2 = (__VAL2); \ + using __TYPE1__ = decltype(__val1); \ + using __TYPE2__ = decltype(__val2); \ + using __COMMON_TYPE1__ = \ + ::phi::details::CommonType1<__TYPE1__, __TYPE2__>; \ + using __COMMON_TYPE2__ = \ + ::phi::details::CommonType2<__TYPE1__, __TYPE2__>; \ + bool __is_not_error = (static_cast<__COMMON_TYPE1__>(__val1))__CMP( \ + static_cast<__COMMON_TYPE2__>(__val2)); \ + if (UNLIKELY(!__is_not_error)) { \ + auto __summary__ = phi::ErrorSummary(__VA_ARGS__); \ + constexpr bool __kCanToString__ = \ + ::phi::details::CanToString<__TYPE1__>::kValue && \ + ::phi::details::CanToString<__TYPE2__>::kValue; \ + auto __message__ = ::paddle::string::Sprintf( \ + "%s\n [Hint: Expected %s " #__CMP \ + " %s, but received %s " #__INV_CMP " %s.]", \ + __summary__.error_message(), \ + #__VAL1, \ + #__VAL2, \ + ::phi::details::BinaryCompareMessageConverter< \ + __kCanToString__>::Convert(#__VAL1, __val1), \ + ::phi::details::BinaryCompareMessageConverter< \ + __kCanToString__>::Convert(#__VAL2, __val2)); \ + __THROW_ERROR_INTERNAL__( \ + phi::ErrorSummary(__summary__.code(), __message__)); \ + } \ + } while (0) + +#define PADDLE_ENFORCE_EQ(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, ==, !=, __VA_ARGS__) +#define PADDLE_ENFORCE_NE(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, !=, ==, __VA_ARGS__) +#define PADDLE_ENFORCE_GT(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, >, <=, __VA_ARGS__) +#define PADDLE_ENFORCE_GE(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, >=, <, __VA_ARGS__) +#define PADDLE_ENFORCE_LT(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, <, >=, __VA_ARGS__) +#define PADDLE_ENFORCE_LE(__VAL0, __VAL1, ...) \ + __PADDLE_BINARY_COMPARE(__VAL0, __VAL1, <=, >, __VA_ARGS__) + +/** EXTENDED TOOL FUNCTIONS WITH CHECKING **/ + +/* + * Summary: This macro is used to get Variable or internal type + * data (such as LoDTensor or SelectedRows) of the Input and + * Output in op, generally used when call scope.FindVar(Input/ + * Output("Name")) or ctx.Input(). + * Firstly this macro check whether the obtained pointer is null, + * and then return data if it is not null. + * + * Note: This macro is only suitable for specific scenarios and + * does not intended to be widely used. If it cannot meet the + * requirements, please use other PADDLE_ENFORCE** check macro. + * + * Parameters: + *     __PTR: pointer + * __ROLE: (string), Input or Output + * __NAME: (string), Input or Output name + * __OP_TYPE: (string), the op type + *   + * Return: The data pointed to by the pointer. + * + * Examples: + * GET_DATA_SAFELY(ctx.Input("X"), "Input", "X", "Mul"); + */ +#define GET_DATA_SAFELY(__PTR, __ROLE, __NAME, __OP_TYPE) \ + (([&]() -> std::add_lvalue_reference::type { \ + auto* __ptr = (__PTR); \ + if (UNLIKELY(nullptr == __ptr)) { \ + auto __summary__ = phi::errors::NotFound( \ + "Unable to get %s data of %s %s in operator %s. " \ + "Possible reasons are:\n" \ + " 1. The %s is not the %s of operator %s;\n" \ + " 2. The %s has no corresponding variable passed in;\n" \ + " 3. The %s corresponding variable is not initialized.", \ + phi::demangle( \ + typeid(std::add_lvalue_reference::type) \ + .name()), \ + __ROLE, \ + __NAME, \ + __OP_TYPE, \ + __NAME, \ + __ROLE, \ + __OP_TYPE, \ + __NAME, \ + __NAME); \ + auto __message__ = ::paddle::string::Sprintf( \ + "%s\n [Hint: pointer " #__PTR " should not be null.]", \ + __summary__.error_message()); \ + __THROW_ERROR_INTERNAL__( \ + phi::ErrorSummary(__summary__.code(), __message__)); \ + } \ + return *__ptr; \ + })()) + +/* + * Summary: This macro is used to check whether op has specified + * Input or Output Variables. Because op's Input and Output + * checking are written similarly, so abstract this macro. + * + * Parameters: + *     __EXPR: (bool), the bool expression + * __ROLE: (string), Input or Output + * __NAME: (string), Input or Output name + * __OP_TYPE: (string), the op type + * + * Examples: + * OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "Mul"); + */ +#define OP_INOUT_CHECK(__EXPR, __ROLE, __NAME, __OP_TYPE) \ + do { \ + PADDLE_ENFORCE_EQ( \ + __EXPR, \ + true, \ + phi::errors::NotFound( \ + "No %s(%s) found for %s operator.", __ROLE, __NAME, __OP_TYPE)); \ + } while (0) + +} // namespace enforce +using namespace enforce; // NOLINT +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/errors.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/errors.h new file mode 100644 index 0000000000000000000000000000000000000000..d1365de5196252d5060a8e87ed772aca40902c3c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/errors.h @@ -0,0 +1,146 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "paddle/utils/string/printf.h" + +namespace phi { +enum ErrorCode { + // Legacy error. + // Error type string: "Error" + LEGACY = 0, + + // Client specified an invalid argument. + // Error type string: "InvalidArgumentError" + INVALID_ARGUMENT = 1, + + // Some requested entity (e.g., file or directory) was not found. + // Error type string: "NotFoundError" + NOT_FOUND = 2, + + // Operation tried to iterate past the valid input range. E.g., seeking or + // reading past end of file. + // Error type string: "OutOfRangeError" + OUT_OF_RANGE = 3, + + // Some entity that we attempted to create (e.g., file or directory) + // already exists. + // Error type string: "AlreadyExistsError" + ALREADY_EXISTS = 4, + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // Error type string: "ResourceExhaustedError" + RESOURCE_EXHAUSTED = 5, + + // Operation was rejected because the system is not in a state + // required for the operation's execution. + // Error type string: "PreconditionNotMetError" + PRECONDITION_NOT_MET = 6, + + // The caller does not have permission to execute the specified + // operation. + // Error type string: "PermissionDeniedError" + PERMISSION_DENIED = 7, + + // Deadline expired before operation could complete. + // Error type string: "ExecutionTimeout" + EXECUTION_TIMEOUT = 8, + + // Operation is not implemented or not supported/enabled in this service. + // Error type string: "UnimpelmentedError" + UNIMPLEMENTED = 9, + + // The service is currently unavailable. This is a most likely a + // transient condition and may be corrected by retrying with + // a backoff. + // Error type string: "UnavailableError" + UNAVAILABLE = 10, + + // Fatal errors. Means some invariant expected by the underlying + // system has been broken. If you see one of these errors, + // something is very broken. + // Error type string: "FatalError" + FATAL = 11, + + // Third-party library error. + // Error type string: "ExternalError" + EXTERNAL = 12, +}; + +class ErrorSummary { + public: + // Note(chenweihang): Final deprecated constructor + // This constructor is used to be compatible with + // current existing untyped PADDLE_ENFORCE_* + // PADDLE_ENFORCE + // Note(chenweihang): Windows openblas need this + // constructor for compiling PADDLE_ENFORCE in *.cu, + // this is a bug cause we can't remove this + // constructor now. + template + explicit ErrorSummary(Args... args) { + code_ = phi::ErrorCode::LEGACY; + msg_ = paddle::string::Sprintf(args...); + } + + // Note(chenweihang): Only recommended constructor + // No longer supports PADDLE_ENFORCE without type or without error message + explicit ErrorSummary(ErrorCode code, std::string msg) + : code_(code), msg_(msg) {} + + ErrorCode code() const { return code_; } + + const std::string& error_message() const { return msg_; } + + std::string to_string() const; + + private: + ErrorCode code_; + std::string msg_; +}; + +namespace errors { + +#define REGISTER_ERROR(FUNC, CONST, ...) \ + template \ + ::phi::ErrorSummary FUNC(Args... args) { \ + return ::phi::ErrorSummary(::phi::CONST, \ + ::paddle::string::Sprintf(args...)); \ + } + +REGISTER_ERROR(InvalidArgument, ErrorCode::INVALID_ARGUMENT) +REGISTER_ERROR(NotFound, ErrorCode::NOT_FOUND) +REGISTER_ERROR(OutOfRange, ErrorCode::OUT_OF_RANGE) +REGISTER_ERROR(AlreadyExists, ErrorCode::ALREADY_EXISTS) +REGISTER_ERROR(ResourceExhausted, ErrorCode::RESOURCE_EXHAUSTED) +REGISTER_ERROR(PreconditionNotMet, ErrorCode::PRECONDITION_NOT_MET) +REGISTER_ERROR(PermissionDenied, ErrorCode::PERMISSION_DENIED) +REGISTER_ERROR(ExecutionTimeout, ErrorCode::EXECUTION_TIMEOUT) +REGISTER_ERROR(Unimplemented, ErrorCode::UNIMPLEMENTED) +REGISTER_ERROR(Unavailable, ErrorCode::UNAVAILABLE) +REGISTER_ERROR(Fatal, ErrorCode::FATAL) +REGISTER_ERROR(External, ErrorCode::EXTERNAL) + +#undef REGISTER_ERROR + +} // namespace errors +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/generator.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/generator.h new file mode 100644 index 0000000000000000000000000000000000000000..3263b2a52573271357d2e5f8751a654e06629a87 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/generator.h @@ -0,0 +1,55 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include + +namespace phi { + +class Generator { + public: + struct GeneratorState { + int64_t device = -1; + uint64_t current_seed = 34342423252; + uint64_t thread_offset = 0; + std::mt19937_64 cpu_engine; + }; + + virtual ~Generator() = default; + + // get random state + virtual GeneratorState GetState() = 0; + // set random state + virtual void SetState(const GeneratorState&) = 0; + // get current seed + virtual uint64_t GetCurrentSeed() = 0; + // random a seed and get + virtual uint64_t Seed() = 0; + // set seed + virtual void SetCurrentSeed(uint64_t seed) = 0; + // get cpu engine + virtual std::shared_ptr GetCPUEngine() = 0; + // set cpu engine + virtual void SetCPUEngine(std::shared_ptr) = 0; + virtual uint64_t Random64() = 0; + virtual std::pair IncrementOffset( + uint64_t increament_offset) = 0; + + virtual uint64_t get_device_id() = 0; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/hostdevice.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/hostdevice.h new file mode 100644 index 0000000000000000000000000000000000000000..decebbe66a5381a0d0e3b2ed94c9649013fbc7de --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/hostdevice.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#ifdef __HIPCC__ +#include +#endif + +#if defined(__xpu__) +#include + +#include "xpu/kernel/cluster_header.h" +#include "xpu/kernel/debug.h" +#include "xpu/kernel/math.h" +#endif + +#if (defined(__CUDACC__) || defined(__HIPCC__) || defined(__xpu__)) +#define HOSTDEVICE __host__ __device__ +#define DEVICE __device__ +#define HOST __host__ +#else +#define HOSTDEVICE +#define DEVICE +#define HOST +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/infermeta_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/infermeta_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..729c56352cf89f8fb5feab0792097465bd0c9b05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/infermeta_utils.h @@ -0,0 +1,331 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/attribute.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/macros.h" +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/utils/any.h" +#include "paddle/utils/flat_hash_map.h" +#include "paddle/utils/small_vector.h" + +namespace phi { + +class InferMetaContext { + public: + InferMetaContext() = default; + explicit InferMetaContext(MetaConfig config) : config_(config) {} + + void SetMetaConfig(MetaConfig config); + const MetaConfig& GetMetaConfig() const; + + void EmplaceBackInput(MetaTensor input); + void EmplaceBackOutput(MetaTensor output); + void EmplaceBackAttr(Attribute attr); + + void EmplaceBackInputs( + paddle::small_vector inputs); + void EmplaceBackOutputs( + paddle::small_vector outputs); + + virtual const MetaTensor& InputAt(size_t idx) const; + + virtual std::vector InputsBetween(size_t start, + size_t end) const; + virtual paddle::optional> + OptionalInputsBetween(size_t start, size_t end) const; + + virtual MetaTensor* MutableOutputAt(size_t idx); + virtual std::vector MutableOutputBetween(size_t start, + size_t end); + + template + const AttrType& AttrAt(size_t idx) const; + + const std::pair& InputRangeAt(size_t idx) const; + const std::pair& OutputRangeAt(size_t idx) const; + + virtual ~InferMetaContext() = default; + + protected: + MetaConfig config_; + + paddle::small_vector attrs_; + + paddle::small_vector, phi::kInputSmallVectorSize> + input_range_; + paddle::small_vector, phi::kOutputSmallVectorSize> + output_range_; + + private: + paddle::small_vector inputs_; + paddle::small_vector outputs_; +}; + +#define PD_INFER_META(...) \ + ::phi::InferMetaFnImpl::Call + +#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(attr_type) \ + template \ + struct InferMetaFnCallHelper { \ + template \ + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { \ + static_assert(out_idx == 0, \ + "InferMeta's Attributes should appear before Outputs."); \ + attr_type arg = ctx->AttrAt(attr_idx); \ + InferMetaFnCallHelper< \ + Tail...>::template Call(ctx, \ + pargs..., \ + arg); \ + } \ + } + +#define PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(attr_type) \ + template \ + struct InferMetaFnCallHelper { \ + template \ + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { \ + static_assert(out_idx == 0, \ + "InferMeta's Attributes should appear before Outputs."); \ + const attr_type& arg = ctx->AttrAt(attr_idx); \ + InferMetaFnCallHelper< \ + Tail...>::template Call(ctx, \ + pargs..., \ + arg); \ + } \ + } + +template +struct InferMetaTypeTag {}; + +template +struct InferMetaFnImpl; + +template +struct InferMetaFnImpl { + static void Call(InferMetaContext* ctx) { + InferMetaFnCallHelper>::template Call<0, 0, 0>(ctx); + } + + private: + template + struct InferMetaFnCallHelper; + + template + struct InferMetaFnCallHelper { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + static_assert(attr_idx == 0, + "InferMeta's Input should appear before Attributes."); + static_assert(out_idx == 0, + "InferMeta's Input should appear before Outputs."); + const std::pair range = ctx->InputRangeAt(in_idx); + const MetaTensor& arg = ctx->InputAt(range.first); + InferMetaFnCallHelper< + Tail...>::template Call(ctx, + pargs..., + arg); + } + }; + + template + struct InferMetaFnCallHelper&, Tail...> { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + static_assert(attr_idx == 0, + "InferMeta's Input should appear before Attributes."); + static_assert(out_idx == 0, + "InferMeta's Input should appear before Outputs."); + const std::pair range = ctx->InputRangeAt(in_idx); + std::vector arg = + ctx->InputsBetween(range.first, range.second); + InferMetaFnCallHelper< + Tail...>::template Call(ctx, + pargs..., + arg); + } + }; + + template + struct InferMetaFnCallHelper< + const paddle::optional>&, + Tail...> { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + static_assert(attr_idx == 0, + "InferMeta's Input should appear before Attributes."); + static_assert(out_idx == 0, + "InferMeta's Input should appear before Outputs."); + const std::pair range = ctx->InputRangeAt(in_idx); + paddle::optional> arg = + ctx->OptionalInputsBetween(range.first, range.second); + InferMetaFnCallHelper< + Tail...>::template Call(ctx, + pargs..., + arg); + } + }; + + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(bool); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(int); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(int64_t); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(float); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(double); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(DataType); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(Backend); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_ATTRIBUTE(DataLayout); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(std::string); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(Scalar); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(IntArray); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_InferMetaFnCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + + template + struct InferMetaFnCallHelper { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + const std::pair range = ctx->OutputRangeAt(out_idx); + MetaTensor* arg = ctx->MutableOutputAt(range.first); + InferMetaFnCallHelper< + Tail...>::template Call(ctx, + pargs..., + arg); + } + }; + + template + struct InferMetaFnCallHelper, Tail...> { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + const std::pair range = ctx->OutputRangeAt(out_idx); + std::vector arg = + ctx->MutableOutputBetween(range.first, range.second); + InferMetaFnCallHelper< + Tail...>::template Call(ctx, + pargs..., + arg); + } + }; + + template + struct InferMetaFnCallHelper { + template + static void Call(InferMetaContext* ctx, PreviousArgs&... pargs) { + MetaConfig arg = ctx->GetMetaConfig(); + InferMetaFnCallHelper::template Call( + ctx, pargs..., arg); + } + }; + + /* End case */ + template + struct InferMetaFnCallHelper> { + template + static void Call(InferMetaContext* ctx, Args&... args) { + return infer_meta_fn(args...); + } + }; +}; + +class MetaFnFactory { + public: + static MetaFnFactory& Instance(); + + bool Contains(const std::string& kernel_name_prefix) const { + return meta_fn_map_.count(kernel_name_prefix) > 0; + } + + void Insert(std::string kernel_name_prefix, InferMetaFn infer_meta_fn) { + PADDLE_ENFORCE_NE( + Contains(kernel_name_prefix), + true, + phi::errors::AlreadyExists( + "`%s`'s Series Kernel's InferMetaFn has been registered.", + kernel_name_prefix)); + meta_fn_map_.insert( + {std::move(kernel_name_prefix), std::move(infer_meta_fn)}); + } + + const InferMetaFn& Get(const std::string& kernel_name_prefix) const { + auto it = meta_fn_map_.find(kernel_name_prefix); + PADDLE_ENFORCE_NE( + it, + meta_fn_map_.end(), + phi::errors::NotFound( + "`%s`'s Series Kernel's InferMetaFn is not registered.", + kernel_name_prefix)); + return it->second; + } + + private: + MetaFnFactory() = default; + + /** + * [ Why use kernel name prefix? ] + * + * one op -> a matrix of kernels + * + * such as, scale op, it may correspond to the following kernels: + * + * - scale, scale_sr, scale_dnnl + * - scale_raw, scale_raw_sr, scale_raw_dnnl + * + * All the kernels in each row correspond to the same infershape function, + * the number of kernel arguments in the same row is the same, and only + * the tensor types in the arguments are different. + */ + paddle::flat_hash_map meta_fn_map_; + + DISABLE_COPY_AND_ASSIGN(MetaFnFactory); +}; + +struct InferMetaFnRegistrar { + InferMetaFnRegistrar(const char* kernel_name_prefix, + InferMetaFn infer_meta_fn) { + MetaFnFactory::Instance().Insert(kernel_name_prefix, + std::move(infer_meta_fn)); + } +}; + +#define PD_REGISTER_INFER_META_FN(kernel_name_prefix, variadic_infer_meta_fn) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_REGISTER_infer_meta_fn_ns_check_##kernel_name_prefix, \ + "PD_REGISTER_INFER_META_FN must be called in global namespace."); \ + static const ::phi::InferMetaFnRegistrar \ + __registrar_arg_map_fn_for_##kernel_name_prefix( \ + #kernel_name_prefix, PD_INFER_META(variadic_infer_meta_fn)) + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_context.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_context.h new file mode 100644 index 0000000000000000000000000000000000000000..107a1fe49c98f356de8d9467684da4a66793cc08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_context.h @@ -0,0 +1,168 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include +#include + +#include "paddle/phi/core/attribute.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_utils.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/utils/optional.h" +#include "paddle/utils/small_vector.h" + +namespace phi { + +/** + * Note: KernelContext doesn't manage the life of DeviceContext and Tensor + * + * Note: KernelContext does not couple the concept of framework, + * its constructor can only take the members it needs as parameters, + * not Scope, RuntimeContext, etc. as parameters + */ +class KernelContext { + public: + KernelContext() = default; + explicit KernelContext(DeviceContext* dev_ctx) : dev_ctx_(dev_ctx) {} + + void SetDeviceContext(DeviceContext* dev_ctx) { dev_ctx_ = dev_ctx; } + + template + const CtxType& GetDeviceContext() const { + return static_cast(*dev_ctx_); + } + + void EmplaceBackInput(const TensorBase* input); + + void EmplaceBackInputWithoutSetRange(const TensorBase* input); + + void EmplaceBackInputs(paddle::small_vector inputs); + + void EmplaceBackInputsWithoutSetRange( + paddle::small_vector inputs); + + void EmplaceBackOutput(TensorBase* output); + + void EmplaceBackOutputWithoutSetRange(TensorBase* output); + + void EmplaceBackOutputs(paddle::small_vector outputs); + + void EmplaceBackOutputsWithoutSetRange( + paddle::small_vector outputs); + + void EmplaceBackAttr(Attribute attr); + + const std::pair& InputRangeAt(size_t idx) const; + + const std::pair& OutputRangeAt(size_t idx) const; + + void AssignInputRange(std::pair&& range, size_t idx); + + void AssignOutputRange(std::pair&& range, size_t idx); + + template + const TensorType& InputAt(size_t idx) const { + return static_cast(*(inputs_.at(idx))); + } + + template + paddle::optional OptionalInputAt(size_t idx) const { + const auto* input = inputs_.at(idx); + return input ? paddle::make_optional( + *(static_cast(input))) + : paddle::none; + } + + template + std::vector InputsBetween(size_t start, size_t end) { + std::vector v; + for (size_t i = start; i < end; ++i) { + auto* t = static_cast(inputs_.at(i)); + v.emplace_back(t); + } + return v; + } + + template + paddle::optional> OptionalInputsBetween( + size_t start, size_t end) { + const auto& first = inputs_.at(start); + + if (first) { + std::vector v; + for (size_t i = start; i < end; ++i) { + auto* t = static_cast(inputs_.at(i)); + v.emplace_back(t); + } + return paddle::optional>(std::move(v)); + } + return paddle::none; + } + + template + TensorType* MutableOutputAt(size_t idx) { + return static_cast(outputs_.at(idx)); + } + + template + std::vector MutableOutputBetween(size_t start, size_t end) { + std::vector v; + bool is_empty_vector = true; + for (size_t i = start; i < end; ++i) { + v.emplace_back(static_cast(outputs_.at(i))); + if (outputs_.at(i) != nullptr) { + is_empty_vector = false; + } + } + if (is_empty_vector) { + v.clear(); + } + return v; + } + + template + const AttrType& AttrAt(size_t idx) const; + + const RuntimeAttrs& GetRuntimeAttrs() const { return runtime_attrs_; } + + size_t InputsSize() const { return inputs_.size(); } + size_t OutputsSize() const { return outputs_.size(); } + size_t AttrsSize() const { return attrs_.size(); } + + void ClearInputOutput() { + inputs_.clear(); + input_range_.clear(); + outputs_.clear(); + output_range_.clear(); + } + + private: + DeviceContext* dev_ctx_; + + paddle::small_vector inputs_; + paddle::small_vector outputs_; + paddle::small_vector attrs_; + + paddle::small_vector, kInputSmallVectorSize> input_range_; + paddle::small_vector, kOutputSmallVectorSize> + output_range_; + + RuntimeAttrs runtime_attrs_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_factory.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..ed9280fa475bf5b46c689b0a5e49e470484b77a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_factory.h @@ -0,0 +1,310 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include +#include +#include +#include +#include + +#include "paddle/phi/common/backend.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/core/compat/convert_utils.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/utils/flat_hash_map.h" +#include "paddle/utils/small_vector.h" + +namespace phi { + +using DataType = paddle::experimental::DataType; +using DataLayout = paddle::experimental::DataLayout; + +/** + * [ Naming considerations ] + * + * The tensor operation library contains many kernels, and the computation + * in each specific scenario is represented by an kernel. + * + * We directly named it `Kernel` instead of `Kernel`, the tensor operation + * library here and fluid are independent, avoiding developers from + * misunderstanding the relationship between the two concepts. + */ + +class KernelContext; + +class KernelKey { + public: + KernelKey() = default; + + KernelKey(Backend backend, DataLayout layout, DataType dtype) + : backend_(backend), layout_(layout), dtype_(dtype) {} + + Backend backend() const { return backend_; } + DataLayout layout() const { return layout_; } + DataType dtype() const { return dtype_; } + + struct Hash { + // Note: Now the number of bits we need does not exceed 32 bits, so there is + // no need to use 64 bits. If needed in the future, it can be expanded, + // but now we don’t over-design. + uint32_t operator()(const KernelKey& key) const; + }; + + uint32_t hash_value() const { return Hash()(*this); } + + bool operator<(const KernelKey& key) const { + return hash_value() < key.hash_value(); + } + + bool operator==(const KernelKey& key) const { + return hash_value() == key.hash_value(); + } + + bool operator!=(const KernelKey& key) const { + return hash_value() != key.hash_value(); + } + + private: + // In total should be smaller than 32. + constexpr static int kBackendBitLength = 8; + constexpr static int kDataLayoutBitLength = 4; + constexpr static int kDataTypeBitLength = 8; + + Backend backend_{Backend::UNDEFINED}; + DataLayout layout_{DataLayout::UNDEFINED}; + DataType dtype_{DataType::UNDEFINED}; +}; + +// TODO(chenweihang): how deal with vector? +struct TensorArgDef { + Backend backend; + DataLayout layout; + DataType dtype; + std::type_index type_index; + + TensorArgDef(Backend in_backend, + DataLayout in_layout, + DataType in_dtype, + std::type_index in_type_index) + : backend(in_backend), + layout(in_layout), + dtype(in_dtype), + type_index(in_type_index) {} + + TensorArgDef& SetBackend(Backend in_backend) { + backend = in_backend; + return *this; + } + + TensorArgDef& SetDataLayout(DataLayout in_layout) { + layout = in_layout; + return *this; + } + + TensorArgDef& SetDataType(DataType in_dtype) { + dtype = in_dtype; + return *this; + } +}; + +// Align the original fluid Attribute type with lower overhead +enum class AttributeType { + UNDEFINED = 0, + BOOL, + INT32, + INT64, + FLOAT32, + FLOAT64, + STRING, + BOOLS, + INT32S, + INT64S, + FLOAT32S, + FLOAT64S, + STRINGS, + SCALAR, + SCALARS, + INT_ARRAY, + DATA_TYPE, + DATA_LAYOUT, + PLACE, +}; + +struct AttributeArgDef { + AttributeType type_index; + + explicit AttributeArgDef(AttributeType type_index) : type_index(type_index) {} +}; + +class KernelArgsDef { + public: + KernelArgsDef() = default; + + void AppendInput(Backend backend, + DataLayout layout, + DataType dtype, + std::type_index type_index) { + input_defs_.emplace_back(TensorArgDef(backend, layout, dtype, type_index)); + } + + void AppendOutput(Backend backend, + DataLayout layout, + DataType dtype, + std::type_index type_index) { + output_defs_.emplace_back(TensorArgDef(backend, layout, dtype, type_index)); + } + + void AppendAttribute(AttributeType type_index) { + attribute_defs_.emplace_back(AttributeArgDef(type_index)); + } + + const paddle::small_vector& input_defs() + const { + return input_defs_; + } + + const paddle::small_vector& + output_defs() const { + return output_defs_; + } + + const paddle::small_vector& + attribute_defs() const { + return attribute_defs_; + } + + paddle::small_vector& input_defs() { + return input_defs_; + } + + paddle::small_vector& output_defs() { + return output_defs_; + } + + paddle::small_vector& + attribute_defs() { + return attribute_defs_; + } + + private: + paddle::small_vector input_defs_{{}}; + paddle::small_vector output_defs_{{}}; + paddle::small_vector attribute_defs_{ + {}}; +}; + +class Kernel { + public: + // for map element construct + Kernel() = default; + + explicit Kernel(KernelFn fn, void* variadic_fn) + : fn_(fn), variadic_fn_(variadic_fn) {} + + void operator()(KernelContext* ctx) const { fn_(ctx); } + + template + Fn GetVariadicKernelFn() const { + auto* func = reinterpret_cast(variadic_fn_); + return func; + } + + KernelArgsDef* mutable_args_def() { return &args_def_; } + + const KernelArgsDef& args_def() const { return args_def_; } + + const TensorArgDef& InputAt(size_t idx) const { + return args_def_.input_defs().at(idx); + } + + TensorArgDef& InputAt(size_t idx) { return args_def_.input_defs().at(idx); } + + const TensorArgDef& OutputAt(size_t idx) const { + return args_def_.output_defs().at(idx); + } + + TensorArgDef& OutputAt(size_t idx) { return args_def_.output_defs().at(idx); } + + bool IsValid() const { return fn_ != nullptr; } + + private: + KernelFn fn_{nullptr}; + void* variadic_fn_ = nullptr; + KernelArgsDef args_def_; +}; + +using KernelKeyMap = paddle::flat_hash_map; + +using KernelNameMap = paddle::flat_hash_map; + +struct KernelResult { + KernelResult(const Kernel& kernel, bool fallback_cpu) + : kernel(kernel), has_fallback_cpu(fallback_cpu) {} + + const Kernel& kernel; + bool has_fallback_cpu = false; +}; + +/** + * Note: Each Computation need a basic kernel map that named by kernel_name. + * Such as for scale op, KernelMap contains a `scale` kernel map, + * if it still need other overload kernel, the op name can be + * `scale.***`. + */ +class KernelFactory { + public: + static KernelFactory& Instance(); + + KernelNameMap& kernels() { return kernels_; } + + bool HasCompatiblePhiKernel(const std::string& op_type) const; + + KernelResult SelectKernelOrThrowError(const std::string& kernel_name, + const KernelKey& kernel_key, + bool use_gpudnn = false) const; + + bool HasKernel(const std::string& kernel_name, + const KernelKey& kernel_key) const; + + const Kernel& SelectKernel(const std::string& kernel_name, + const KernelKey& kernel_key) const; + + KernelKeyMap SelectKernelMap(const std::string& kernel_name) const; + + const KernelArgsDef& GetFirstKernelArgsDef( + const std::string& kernel_name) const; + + private: + KernelFactory() = default; + + KernelNameMap kernels_; +}; + +inline std::ostream& operator<<(std::ostream& os, const KernelKey& kernel_key) { + os << "(" << kernel_key.backend() << ", " << kernel_key.layout() << ", " + << kernel_key.dtype() << ")"; + return os; +} + +std::ostream& operator<<(std::ostream& os, AttributeType attr_type); + +std::ostream& operator<<(std::ostream& os, const Kernel& kernel); + +std::ostream& operator<<(std::ostream& os, KernelFactory& kernel_factory); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_registry.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..7ae01b7c725f0b23a0df136b76351982edc9e262 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_registry.h @@ -0,0 +1,1148 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "paddle/phi/core/custom_kernel.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/kernel_factory.h" +#include "paddle/phi/core/kernel_utils.h" +#include "paddle/phi/core/macros.h" +#include "paddle/phi/core/type_defs.h" + +namespace phi { + +#define BACKEND(arg__) phi::Backend::arg__ +#define DATALAYOUT(arg__) phi::DataLayout::arg__ +#define DATATYPE(arg__) phi::DataType::arg__ + +template +struct KernelArgsParseFunctor; + +template +struct KernelArgsParseFunctor { + using Args = std::tuple; + enum : std::size_t { Arity = sizeof...(Args_) }; + using Indices = std::make_index_sequence; + template + using Arg = typename std::tuple_element::type; + + static void Parse(const KernelKey& default_key, KernelArgsDef* args_def) { + // TODO(chenweihang): The fluid Tensor's default layout is NCHW, + // it is not same as kernel's layout, we should fix this error on + // fluid Tensor + auto default_tensor_layout = phi::DataLayout::NCHW; + if (default_key.layout() != phi::DataLayout::ANY) { + default_tensor_layout = default_key.layout(); + } + auto args_type = ParseArgType(Indices{}); + for (auto arg_type : args_type) { + if (arg_type == std::type_index(typeid(const CPUContext&)) +#if defined(PADDLE_WITH_MKLDNN) + || arg_type == std::type_index(typeid(const OneDNNContext&)) +#endif +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + || arg_type == std::type_index(typeid(const GPUContext&))) { +#elif defined(PADDLE_WITH_XPU) + || arg_type == std::type_index(typeid(const XPUContext&))) { +#elif defined(PADDLE_WITH_CUSTOM_DEVICE) + || arg_type == std::type_index(typeid(const CustomContext&))) { +#else + + ) { +#endif + // do nothing, skip context arg now + } else if (arg_type == std::type_index(typeid(const DenseTensor&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const paddle::optional&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == + std::type_index(typeid(const paddle::optional< + std::vector>&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const paddle::optional&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const std::vector&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const std::vector&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const std::vector&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + const std::vector&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(const SelectedRows&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(const StringTensor&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(const SparseCooTensor&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + paddle::optional))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(const SparseCsrTensor&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid( + paddle::optional))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(const TensorArray&))) { + args_def->AppendInput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(DenseTensor*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == + std::type_index(typeid(std::vector))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(SelectedRows*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(TensorArray*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(SparseCooTensor*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(SparseCsrTensor*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(StringTensor*))) { + args_def->AppendOutput(default_key.backend(), + default_tensor_layout, + default_key.dtype(), + arg_type); + } else if (arg_type == std::type_index(typeid(bool))) { + args_def->AppendAttribute(AttributeType::BOOL); + } else if (arg_type == std::type_index(typeid(int))) { + args_def->AppendAttribute(AttributeType::INT32); + } else if (arg_type == std::type_index(typeid(int64_t))) { + args_def->AppendAttribute(AttributeType::INT64); + } else if (arg_type == std::type_index(typeid(float))) { + args_def->AppendAttribute(AttributeType::FLOAT32); + } else if (arg_type == std::type_index(typeid(double))) { + args_def->AppendAttribute(AttributeType::FLOAT64); + } else if (arg_type == std::type_index(typeid(std::string))) { + args_def->AppendAttribute(AttributeType::STRING); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::BOOLS); + } else if (arg_type == std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::INT32S); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::INT64S); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::FLOAT32S); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::FLOAT64S); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::STRINGS); + } else if (arg_type == std::type_index(typeid(const Scalar&))) { + args_def->AppendAttribute(AttributeType::SCALAR); + } else if (arg_type == + std::type_index(typeid(const std::vector&))) { + args_def->AppendAttribute(AttributeType::SCALARS); + } else if (arg_type == std::type_index(typeid(const IntArray&))) { + args_def->AppendAttribute(AttributeType::INT_ARRAY); + } else if (arg_type == std::type_index(typeid(DataType))) { + args_def->AppendAttribute(AttributeType::DATA_TYPE); + } else if (arg_type == std::type_index(typeid(DataLayout))) { + args_def->AppendAttribute(AttributeType::DATA_LAYOUT); + } else if (arg_type == std::type_index(typeid(Place))) { + args_def->AppendAttribute(AttributeType::PLACE); + } else if (arg_type == std::type_index(typeid(RuntimeAttrs))) { + // do nothing + } else { + PADDLE_THROW(phi::errors::Unavailable( + "Unsupported kernel argument type `%s`.", arg_type.name())); + } + } + } + + private: + template + static std::vector ParseArgType( + std::index_sequence) { + return {std::type_index(typeid(Arg))...}; + } +}; + +// NOTE: used for making a difference between inner or outer registration. +enum class RegType : uint8_t { + INNER = 0, + OUTER, +}; + +// TODO(chenweihang): Polish the kernel selection logic, support the selection +// of ALL_DTYPE kernel, and simplify the constructor +struct KernelRegistrar { + public: + KernelRegistrar(RegType reg_type, + const char* kernel_name_cstr, + const char* backend_cstr, + DataLayout layout, + DataType dtype, + KernelArgsParseFn args_parse_fn, + KernelArgsDefFn args_def_fn, + KernelFn kernel_fn, + void* variadic_kernel_fn) { + ConstructKernel(reg_type, + kernel_name_cstr, + backend_cstr, + layout, + dtype, + args_parse_fn, + args_def_fn, + kernel_fn, + variadic_kernel_fn); + } + + KernelRegistrar(RegType reg_type, + const char* kernel_name_cstr, + const char* backend_cstr, + DataLayout layout, + KernelArgsParseFn args_parse_fn, + KernelArgsDefFn args_def_fn, + KernelFn kernel_fn, + void* variadic_kernel_fn) { + for (size_t dtype = static_cast(DataType::BOOL); + dtype != static_cast(DataType::NUM_DATA_TYPES); + dtype++) { + // NOTE(zhiqiu): why skip these types, because fluid kernel has no kernel + // of these type. + if (dtype == static_cast(DataType::UINT32) || + dtype == static_cast(DataType::UINT64) || + dtype == static_cast(DataType::UINT16)) { + continue; + } + // NOTE(zhoushunjie): Only the strings kernels can support pstring dtype + constexpr char strings_kernels_prefix[] = "strings_"; + if (dtype == static_cast(DataType::PSTRING) && + strncmp(kernel_name_cstr, + strings_kernels_prefix, + strlen(strings_kernels_prefix))) { + continue; + } + ConstructKernel(reg_type, + kernel_name_cstr, + backend_cstr, + layout, + static_cast(dtype), + args_parse_fn, + args_def_fn, + kernel_fn, + variadic_kernel_fn); + } + } + + private: + void ConstructKernel(RegType reg_type, + const char* kernel_name_cstr, + const char* backend_cstr, + DataLayout layout, + DataType dtype, + KernelArgsParseFn args_parse_fn, + KernelArgsDefFn args_def_fn, + KernelFn kernel_fn, + void* variadic_kernel_fn) { + std::string kernel_name(kernel_name_cstr); + KernelKey kernel_key( + paddle::experimental::StringToBackend(backend_cstr), layout, dtype); + Kernel kernel(kernel_fn, variadic_kernel_fn); + args_parse_fn(kernel_key, kernel.mutable_args_def()); + args_def_fn(kernel_key, &kernel); + if (reg_type == RegType::INNER) { + KernelFactory::Instance().kernels()[kernel_name][kernel_key] = kernel; + } else { + CustomKernelMap::Instance().RegisterCustomKernel( + kernel_name, kernel_key, kernel); + } + } +}; + +/** + * Reference: + * + * https://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros + * https://stackoverflow.com/questions/9183993/msvc-variadic-macro-expansion?rq=1 + * https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly + * + * Very carefully tiptoeing around an MSVC bug where it improperly expands + * __VA_ARGS__ as a single token in argument lists. See these URLs for details: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +#define PD_NARGS(...) _PD_NARGS((__VA_ARGS__, _PD_RESQ_N())) +#define _PD_NARGS(...) _PD_ARG_N(__VA_ARGS__) +#define _PD_ARG_N_EXPAND( \ + _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, N, ...) \ + N +#define _PD_ARG_N(args) _PD_ARG_N_EXPAND args +#define _PD_RESQ_N() 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 + +/** PD_REGISTER_KERNEL + * + * The most frequently used kernel registration macro, used for kernel + * registration with only data type as template parameter, and the function + * pointer of the corresponding data type is automatically instantiated + * during registration. + * + * Note: `2TA` means `2 template argument` + */ +#define PD_REGISTER_KERNEL(kernel_name, backend, layout, meta_kernel_fn, ...) \ + _PD_REGISTER_KERNEL(::phi::RegType::INNER, \ + kernel_name, \ + backend, \ + ::phi::backend##Context, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__) + +#define _PD_REGISTER_KERNEL( \ + reg_type, kernel_name, backend, context, layout, meta_kernel_fn, ...) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_REGISTER_tp_kernel_ns_check_##kernel_name##_##backend##_##layout, \ + "PD_REGISTER_KERNEL must be called in global namespace."); \ + PD_EXPAND(_PD_REGISTER_2TA_KERNEL(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +#ifndef _WIN32 +#define _PD_REGISTER_2TA_KERNEL( \ + reg_type, kernel_name, backend, context, layout, meta_kernel_fn, ...) \ + PD_KERNEL_INSTANTIATION(meta_kernel_fn, backend, context, __VA_ARGS__); \ + static void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel); \ + PD_KERNEL_REGISTRAR_INIT( \ + reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + &__PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout, \ + meta_kernel_fn, \ + __VA_ARGS__); \ + void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel) +#else +/** + * `template decltype(fn) fn` can work on gcc and clang, + * but msvc will failed, error like: + * + * error C2206: typedef cannot be used for function definition + * + * reference: + * + * https://stackoverflow.com/questions/63989585/explicit-instantiation-of-function-using-decltype-work-on-g-but-not-on-visua + * + * And msvc can work without template instantiation + */ +#define _PD_REGISTER_2TA_KERNEL( \ + reg_type, kernel_name, backend, context, layout, meta_kernel_fn, ...) \ + static void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel); \ + PD_EXPAND(PD_KERNEL_REGISTRAR_INIT( \ + reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + &__PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout, \ + meta_kernel_fn, \ + __VA_ARGS__)); \ + void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel) +#endif + +#define PD_KERNEL_INSTANTIATION(meta_kernel_fn, backend, context, ...) \ + _PD_KERNEL_INSTANTIATION( \ + PD_NARGS(__VA_ARGS__), meta_kernel_fn, backend, context, __VA_ARGS__) + +#define _PD_KERNEL_INSTANTIATION(N, meta_kernel_fn, backend, context, ...) \ + PD_CONCATENATE(_PD_KERNEL_INSTANTIATION_, N) \ + (meta_kernel_fn, backend, context, __VA_ARGS__) + +#define _PD_KERNEL_INSTANTIATION_1( \ + meta_kernel_fn, backend, context, cpp_dtype) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn +#define _PD_KERNEL_INSTANTIATION_2( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_1( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_3( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_2( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_4( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_3( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_5( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_4( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_6( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_5( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_7( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_6( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_8( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_7( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_9( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_8( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_10( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_9( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_11( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_10( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_12( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_11( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_13( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_12( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_14( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_13( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) +#define _PD_KERNEL_INSTANTIATION_15( \ + meta_kernel_fn, backend, context, cpp_dtype, ...) \ + template decltype(meta_kernel_fn) \ + meta_kernel_fn; \ + PD_EXPAND(_PD_KERNEL_INSTANTIATION_14( \ + meta_kernel_fn, backend, context, __VA_ARGS__)) + +#define PD_KERNEL_REGISTRAR_INIT(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + args_def_fn, \ + meta_kernel_fn, \ + ...) \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT(PD_NARGS(__VA_ARGS__), \ + reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +// clang-format off + +/* The =pre-commit always treats this macro into the wrong format, + and multi-line macros cannot be skipped with NOLINT.*/ +#define _PD_KERNEL_REGISTRAR_INIT(N, \ + reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + args_def_fn, \ + meta_kernel_fn, \ + ...) \ + PD_EXPAND(PD_CONCATENATE(_PD_KERNEL_REGISTRAR_INIT_, N) ( \ + reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) + +// clang-format on + +#define _PD_KERNEL_REGISTRAR_INIT_1(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + int TouchKernelSymbolFor_##kernel_name##_##backend##_##layout() { return 0; } +#define _PD_KERNEL_REGISTRAR_INIT_2(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_1(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_3(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_2(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_4(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_3(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_5(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_4(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_6(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_5(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_7(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_6(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_8(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_7(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_9(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_8(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_10(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_9(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_11(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_10(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_12(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_11(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_13(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_12(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_14(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_13(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +#define _PD_KERNEL_REGISTRAR_INIT_15(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + registrar_id, \ + args_def_fn, \ + meta_kernel_fn, \ + cpp_dtype, \ + ...) \ + static const ::phi::KernelRegistrar PD_CONCATENATE( \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout##_, registrar_id)( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::paddle::experimental::CppTypeToDataType::Type(), \ + ::phi::KernelArgsParseFunctor< \ + decltype(&meta_kernel_fn)>::Parse, \ + args_def_fn, \ + PHI_KERNEL(meta_kernel_fn), \ + PHI_VARIADIC_KERNEL(meta_kernel_fn)); \ + PD_EXPAND(_PD_KERNEL_REGISTRAR_INIT_14(reg_type, \ + kernel_name, \ + backend, \ + context, \ + layout, \ + PD_ID, \ + args_def_fn, \ + meta_kernel_fn, \ + __VA_ARGS__)) +/** PD_REGISTER_GENERAL_KERNEL + * + * Basic Kernel register marco, used to register a instantiated kernel function + * with one template argument. + */ + +#define PD_REGISTER_GENERAL_KERNEL( \ + kernel_name, backend, layout, kernel_fn, dtype) \ + _PD_REGISTER_GENERAL_KERNEL( \ + ::phi::RegType::INNER, kernel_name, backend, layout, kernel_fn, dtype) + +#define _PD_REGISTER_GENERAL_KERNEL( \ + reg_type, kernel_name, backend, layout, kernel_fn, dtype) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_REGISTER_no_t_kernel_ns_check_##kernel_name##_##backend##_##layout, \ + "PD_REGISTER_NO_TEMPLATE_KERNEL must be called in global namespace."); \ + __PD_REGISTER_GENERAL_KERNEL( \ + reg_type, kernel_name, backend, layout, kernel_fn, dtype) + +#ifndef _WIN32 +#define __PD_REGISTER_GENERAL_KERNEL( \ + reg_type, kernel_name, backend, layout, kernel_fn, dtype) \ + template decltype(kernel_fn) kernel_fn; \ + static void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel); \ + static const ::phi::KernelRegistrar \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::phi::KernelArgsParseFunctor::Parse, \ + &__PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout, \ + PHI_KERNEL(kernel_fn), \ + PHI_VARIADIC_KERNEL(kernel_fn)); \ + int TouchKernelSymbolFor_##kernel_name##_##backend##_##layout() { \ + return 0; \ + } \ + void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel) +#else +#define __PD_REGISTER_GENERAL_KERNEL( \ + reg_type, kernel_name, backend, layout, kernel_fn, dtype) \ + static void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel); \ + static const ::phi::KernelRegistrar \ + __reg_phi_kernel_##kernel_name##_##backend##_##layout( \ + reg_type, \ + #kernel_name, \ + #backend, \ + DATALAYOUT(layout), \ + ::phi::KernelArgsParseFunctor::Parse, \ + &__PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout, \ + PHI_KERNEL(kernel_fn), \ + PHI_VARIADIC_KERNEL(kernel_fn)); \ + int TouchKernelSymbolFor_##kernel_name##_##backend##_##layout() { \ + return 0; \ + } \ + void __PD_KERNEL_args_def_FN_##kernel_name##_##backend##_##layout( \ + const ::phi::KernelKey& kernel_key, ::phi::Kernel* kernel) +#endif + +/** PD_DECLARE_KERNEL + * + * Used to export the symbols of the file where the kernel is located, + * to avoid being removed by linker + */ +#define PD_DECLARE_KERNEL(kernel_name, backend, layout) \ + PD_STATIC_ASSERT_GLOBAL_NAMESPACE( \ + PD_DECLARE_tp_kernel_ns_check_##kernel_name##_##backend##_##layout, \ + "PD_DECLARE_KERNEL must be called in global namespace."); \ + extern int TouchKernelSymbolFor_##kernel_name##_##backend##_##layout(); \ + UNUSED static int \ + __declare_kernel_symbol_for_##kernel_name##_##backend##_##layout = \ + TouchKernelSymbolFor_##kernel_name##_##backend##_##layout() + +/** PD_REGISTER_BUILTIN_KERNEL + * + * Used to register kernels for built-in backends. + * Support CPU GPU XPU. + */ +#define PD_REGISTER_BUILTIN_KERNEL( \ + kernel_name, backend, layout, meta_kernel_fn, ...) \ + _PD_REGISTER_KERNEL(::phi::RegType::OUTER, \ + kernel_name, \ + backend, \ + ::phi::backend##Context, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__) + +/** PD_REGISTER_PLUGIN_KERNEL + * + * Used to register kernels for plug-in backends. + * Support user-defined backend such as 'Ascend910'. + */ +#define PD_REGISTER_PLUGIN_KERNEL( \ + kernel_name, backend, layout, meta_kernel_fn, ...) \ + _PD_REGISTER_KERNEL(::phi::RegType::OUTER, \ + kernel_name, \ + backend, \ + ::phi::CustomContext, \ + layout, \ + meta_kernel_fn, \ + __VA_ARGS__) + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..cdfdefa059cd792b144a0bdb7db72cba3e5c1306 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/kernel_utils.h @@ -0,0 +1,360 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/backends/cpu/cpu_context.h" +#include "paddle/phi/backends/custom/custom_context.h" +#include "paddle/phi/backends/gpu/gpu_context.h" +#include "paddle/phi/backends/onednn/onednn_context.h" +#ifdef PADDLE_WITH_XPU +#include "paddle/phi/backends/xpu/xpu_context.h" +#endif +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/kernel_context.h" +#include "paddle/phi/core/selected_rows.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/core/string_tensor.h" +#include "paddle/phi/core/tensor_array.h" +#include "paddle/phi/core/type_defs.h" + +namespace phi { + +// PD_KERNEL has been used by custom op api +#define PHI_KERNEL(...) \ + ::phi::KernelImpl::Compute + +#define PHI_VARIADIC_KERNEL(...) \ + reinterpret_cast(&::phi::KernelImpl::VariadicCompute) + +#define PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(dev_ctx) \ + template \ + struct KernelCallHelper { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(in_idx == 0, \ + "Kernel's DeviceContext should appear before Inputs."); \ + static_assert( \ + attr_idx == 0, \ + "Kernel's DeviceContext should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's DeviceContext should appear before Outputs."); \ + const dev_ctx& arg = ctx->GetDeviceContext(); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(tensor_type) \ + template \ + struct KernelCallHelper { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + const std::pair& range = ctx->InputRangeAt(in_idx); \ + const tensor_type& arg = ctx->InputAt(range.first); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(tensor_type) \ + template \ + struct KernelCallHelper&, Tail...> { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + const std::pair& range = ctx->InputRangeAt(in_idx); \ + auto arg = ctx->OptionalInputAt(range.first); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(tensor_type) \ + template \ + struct KernelCallHelper&, Tail...> { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + const std::pair& range = ctx->InputRangeAt(in_idx); \ + std::vector arg = std::move( \ + ctx->InputsBetween(range.first, range.second)); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_MULTI_INPUT(tensor_type) \ + template \ + struct KernelCallHelper< \ + const paddle::optional>&, \ + Tail...> { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(attr_idx == 0, \ + "Kernel's Input should appear before Attributes."); \ + static_assert(out_idx == 0, \ + "Kernel's Input should appear before Outputs."); \ + const std::pair& range = ctx->InputRangeAt(in_idx); \ + paddle::optional> arg = \ + ctx->OptionalInputsBetween(range.first, range.second); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(attr_type) \ + template \ + struct KernelCallHelper { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(out_idx == 0, \ + "Kernel's Attributes should appear before Outputs."); \ + attr_type arg = ctx->AttrAt(attr_idx); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(attr_type) \ + template \ + struct KernelCallHelper { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + static_assert(out_idx == 0, \ + "Kernel's Attributes should appear before Outputs."); \ + const attr_type& arg = ctx->AttrAt(attr_idx); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(tensor_type) \ + template \ + struct KernelCallHelper { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + const std::pair& range = ctx->OutputRangeAt(out_idx); \ + tensor_type* arg = ctx->MutableOutputAt(range.first); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +#define PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_OUTPUT(tensor_type) \ + template \ + struct KernelCallHelper, Tail...> { \ + template \ + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { \ + const std::pair& range = ctx->OutputRangeAt(out_idx); \ + std::vector arg = std::move( \ + ctx->MutableOutputBetween(range.first, range.second)); \ + KernelCallHelper:: \ + template Compute( \ + ctx, pargs..., arg); \ + } \ + } + +template +struct TypeTag {}; + +template +struct KernelImpl; + +template +struct KernelImpl { + static void Compute(KernelContext* ctx) { + KernelCallHelper>:: + template Compute<0, 0, 0, 0>(ctx); + } + + static void VariadicCompute(const DeviceContext& dev_ctx, Args... args) { + return kernel_fn(static_cast(dev_ctx), std::forward(args)...); + } + + private: + template + struct KernelCallHelper; + + /* DeviceContext Helpers */ + + PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(CPUContext); +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(GPUContext); +#endif +#ifdef PADDLE_WITH_XPU + PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(XPUContext); +#endif +#ifdef PADDLE_WITH_CUSTOM_DEVICE + PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(CustomContext); +#endif +#ifdef PADDLE_WITH_MKLDNN + PD_SPECIALIZE_KernelCallHelper_FOR_DEVICE_CONTEXT(OneDNNContext); +#endif + /* Input Helpers */ + + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(DenseTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(DenseTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(SelectedRows); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(DenseTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(TensorBase); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(SelectedRows); + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(SelectedRows); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_MULTI_INPUT(DenseTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(SparseCooTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(SparseCooTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(SparseCooTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(SparseCsrTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(SparseCsrTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(SparseCsrTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(StringTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OPTIONAL_INPUT(StringTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(StringTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_INPUT(TensorArray); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_INPUT(TensorArray); + + /* Attribute Helpers */ + + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(bool); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(float); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(double); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(int); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(int64_t); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(phi::dtype::float16); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(DataType); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(DataLayout); + PD_SPECIALIZE_KernelCallHelper_FOR_ATTRIBUTE(Place); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::string); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(Scalar); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(IntArray); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF( + std::vector); + PD_SPECIALIZE_KernelCallHelper_FOR_CONST_ATTRIBUTE_REF(std::vector); + + /* Output Helpers */ + + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(DenseTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_OUTPUT(DenseTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(SelectedRows); + + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(SparseCooTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_OUTPUT(SparseCooTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(SparseCsrTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_OUTPUT(SparseCsrTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(StringTensor); + PD_SPECIALIZE_KernelCallHelper_FOR_MULTI_OUTPUT(StringTensor); + + PD_SPECIALIZE_KernelCallHelper_FOR_OUTPUT(TensorArray); + + template + struct KernelCallHelper { + template + static void Compute(KernelContext* ctx, PreviousArgs&... pargs) { + const auto& runtime_attrs = ctx->GetRuntimeAttrs(); + KernelCallHelper:: + template Compute( + ctx, pargs..., runtime_attrs); + } + }; + + /* End case */ + template + struct KernelCallHelper> { + template + static void Compute(KernelContext* ctx, DevCtx dev_ctx, Args&... args) { + static_assert(dev_ctx_idx > 0, + "Kernel should pass DeviceContext as argument."); + return kernel_fn(dev_ctx, args...); + } + }; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/lod_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/lod_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..147fca4cb576ce1625df83cca95d3701e082e6f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/lod_utils.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once +#include +#include + +namespace phi { +using LoD = std::vector>; + +void AppendLoD(LoD* lod, const LoD& lod_length); + +/* + * Convert between length-based LoD and offset-based LoD. + * The implementation of LoDTensor class use offset-based LoD. + * However, we want to expose the more user-friendly length-based + * LoD to the Python side instead. + * + * Example: + * If offset_lod = [[0, 2, 3],[0, 3, 5, 9]] + * then length_lod = [[2, 1], [3, 2, 4]] + */ +LoD ConvertToLengthBasedLoD(const LoD& offset_lod); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/macros.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/macros.h new file mode 100644 index 0000000000000000000000000000000000000000..e48f7342e456ec1ae766c4ca9a4a2ced09f394e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/macros.h @@ -0,0 +1,62 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +namespace phi { + +// Disable the copy and assignment operator for a class. +#ifndef DISABLE_COPY_AND_ASSIGN +#define DISABLE_COPY_AND_ASSIGN(classname) \ + private: \ + classname(const classname&) = delete; \ + classname(classname&&) = delete; \ + classname& operator=(const classname&) = delete; \ + classname& operator=(classname&&) = delete +#endif + +#define PD_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \ + _PD_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) + +#define _PD_STATIC_ASSERT_GLOBAL_NAMESPACE(uniq_name, msg) \ + struct __test_global_namespace_##uniq_name##__ {}; \ + static_assert(std::is_same<::__test_global_namespace_##uniq_name##__, \ + __test_global_namespace_##uniq_name##__>::value, \ + msg) + +#ifdef __COUNTER__ +#define PD_ID __COUNTER__ +#else +#define PD_ID __LINE__ +#endif + +#if defined(_WIN32) +#define UNUSED +#define __builtin_expect(EXP, C) (EXP) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define PD_CONCATENATE(arg1, arg2) PD_CONCATENATE1(arg1, arg2) +#define PD_CONCATENATE1(arg1, arg2) PD_CONCATENATE2(arg1, arg2) +#define PD_CONCATENATE2(arg1, arg2) arg1##arg2 +#define PD_EXPAND(x) x + +#if defined(__NVCC__) || defined(__HIPCC__) +#define PADDLE_RESTRICT __restrict__ +#else +#define PADDLE_RESTRICT +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/meta_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/meta_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..1a9dfb0d3c16f0fa8b80c98bc7f40dcb27328663 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/meta_tensor.h @@ -0,0 +1,95 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/macros.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { + +// TODO(chenweihang): add other flags if needed +struct MetaConfig { + bool is_runtime{true}; + bool is_run_mkldnn_kernel{false}; + MetaConfig() = default; + + // supporting implicit construction is easier to use + MetaConfig(bool is_runtime, bool is_run_mkldnn_kernel) + : is_runtime(is_runtime), + is_run_mkldnn_kernel(is_run_mkldnn_kernel) {} // NOLINT +}; + +class MetaTensor { + public: + typedef void (*unspecified_bool_type)(); + + MetaTensor() : tensor_(nullptr) {} + + // supporting implicit construction is easier to use + MetaTensor(TensorBase* tensor) : tensor_(tensor) {} // NOLINT + MetaTensor(const TensorBase& tensor) // NOLINT + : tensor_(const_cast(&tensor)) {} + MetaTensor(TensorBase& tensor) : tensor_(&tensor) {} // NOLINT + + MetaTensor(MetaTensor&&) = default; + MetaTensor& operator=(MetaTensor&&) = default; + MetaTensor(const MetaTensor&) = default; + MetaTensor& operator=(const MetaTensor&) = default; + + virtual ~MetaTensor() = default; + + virtual int64_t numel() const; + virtual DDim dims() const; + virtual DataType dtype() const; + virtual DataLayout layout() const; + virtual void set_dims(const DDim& dims); + virtual void set_dtype(DataType dtype); + virtual void set_layout(DataLayout layout); + + virtual void share_lod(const MetaTensor& meta_tensor); + virtual void share_meta(const MetaTensor& meta_tensor); + virtual void share_dims(const MetaTensor& meta_tensor); + + virtual bool initialized() const; + + virtual bool is_selected_rows() const; + virtual bool is_dense() const; + // TODO(YuanRisheng) This API is for compatible with Fluid + // and it will be deleted in the future. + virtual bool is_tensor_array() const; + + virtual operator unspecified_bool_type() const { + return tensor_ == nullptr ? 0 : unspecified_bool_true; + } + + virtual bool operator!() const { return tensor_ == nullptr; } + + protected: + static void unspecified_bool_true() {} + + private: + // Because the lod in compiletime and runtime is different, + // so `LoD` cannot in public methods + const LoD& lod() const; + TensorBase* tensor() const; + + TensorBase* tensor_ = nullptr; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows.h new file mode 100644 index 0000000000000000000000000000000000000000..c011605809e4417e585f3ba3a4e5d577a08a1837 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows.h @@ -0,0 +1,161 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include // NOLINT +#include +#include +#include + +#include "paddle/phi/core/selected_rows_impl.h" + +namespace phi { +class SelectedRows : public TensorBase, + public TypeInfoTraits { + /* + * @brief We can use the SelectedRows structure to reproduce a sparse table. + * A sparse table is a key-value structure that the key is an `int64_t`, + * and the value is a Tensor which the first dimension is 0. + * You can use the following interface to operate the sparse table, and you + * can find + * some detail information from the comments of each interface: + * + * HasKey(key), whether the sparse table has the specified key. + * Set(key, value), set a key-value pair into the sparse table. + * Get(keys, value*), get value by given key list and apply it to the given + * value pointer + * with the specified offset. + * + */ + public: + SelectedRows(const std::vector& rows, const int64_t& height); + + SelectedRows(); + + const DenseTensor& value() const { return impl_->value(); } + + DenseTensor* mutable_value() { return impl_->mutable_value(); } + + int64_t height() const { return impl_->height(); } + + void set_height(int64_t height) { impl_->set_height(height); } + + const std::vector& rows() const { return impl_->rows(); } + + std::vector* mutable_rows() { return impl_->mutable_rows(); } + + void set_rows(const std::vector& rows) { impl_->set_rows(rows); } + /* + * @brief Get the index of key in rows + * + * @return -1 if the key does not exists. + */ + int64_t Index(int64_t key) const { return impl_->Index(key); } + /* + * @brief whether has the specified key in the table. + * + * @return true if the key is exists. + */ + bool HasKey(int64_t key) const { return impl_->HasKey(key); } + + /* + * @brief Get value by the key list. + * Note!!! this interface is only used when selected_rows is used as + * parameters + * for distribute lookup table. + * + * @return a list of pair which contains the non-exists key and the index in + * the value + */ + void Get(const DenseTensor& ids, + DenseTensor* value, + bool auto_grown = false, + bool is_test = false) { + impl_->Get(ids, value, auto_grown, is_test); + } + + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override { + return impl_->AllocateFrom(allocator, dtype, requested_size); + } + + /* + * @brief Get the index of the key from id_to_index_ map. If the key not + * exist, + * add the key into id_to_index_. + * + * Note!!! this interface is only used when selected_rows is used as + * parameters + * for distribute lookup table. + * + * @return index of the key. + */ + int64_t AutoGrownIndex(int64_t key, bool auto_grown, bool is_test = false) { + return impl_->AutoGrownIndex(key, auto_grown, is_test); + } + + /* + * @brief Get the index of the key from id_to_index_ map. + */ + inline int64_t GetIndexFromId(int64_t key) const { + return impl_->GetIndexFromId(key); + } + + void SyncIndex() { impl_->SyncIndex(); } + /* + * @brief Get complete Dims before + */ + DDim GetCompleteDims() const { return impl_->GetCompleteDims(); } + + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "SelectedRows"; } + + /// \brief Returns the number of elements contained in tensor. + /// \return The number of elements contained in tensor. + int64_t numel() const override { return impl_->numel(); }; + + /// \brief Returns the dims of the tensor. + /// \return The dims of the tensor. + const DDim& dims() const noexcept override { return impl_->dims(); } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept override { return impl_->dtype(); } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept override { return impl_->layout(); } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const override { return impl_->place(); }; + + /// \brief Test whether the metadata is valid. + /// \return Whether the metadata is valid. + bool valid() const noexcept override { return impl_->valid(); } + + /// \brief Test whether the storage is allocated. + /// return Whether the storage is allocated. + bool initialized() const override { return impl_->initialized(); } + + private: + std::shared_ptr impl_{nullptr}; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows_impl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..3c54b59a159ddfdac25ad64f083cde97cfdd39f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/selected_rows_impl.h @@ -0,0 +1,189 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include +#include // NOLINT +#include +#include +#include + +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/utils/rw_lock.h" + +namespace phi { +class SelectedRowsImpl { + /* + * @brief We can use the SelectedRowsImpl structure to reproduce a sparse + * table. + * A sparse table is a key-value structure that the key is an `int64_t`, + * and the value is a Tensor which the first dimension is 0. + * You can use the following interface to operate the sparse table, and you + * can find + * some detail information from the comments of each interface: + * + * HasKey(key), whether the sparse table has the specified key. + * Set(key, value), set a key-value pair into the sparse table. + * Get(keys, value*), get value by given key list and apply it to the given + * value pointer + * with the specified offset. + * + */ + public: + SelectedRowsImpl(const std::vector& rows, const int64_t& height) + : rows_(rows), height_(height) { + value_.reset(new DenseTensor()); + rwlock_.reset(new RWLock); + } + + SelectedRowsImpl() { + height_ = 0; + value_.reset(new DenseTensor()); + rwlock_.reset(new RWLock); + } + + const DenseTensor& value() const { return *value_; } + + DenseTensor* mutable_value() { return value_.get(); } + + int64_t height() const { return height_; } + + void set_height(int64_t height) { height_ = height; } + + const std::vector& rows() const { return rows_; } + + std::vector* mutable_rows() { return &rows_; } + + void set_rows(const std::vector& rows) { rows_ = rows; } + + /* + * @brief Get the index of key in rows + * + * @return -1 if the key does not exists. + */ + int64_t Index(int64_t key) const { + auto it = std::find(rows_.begin(), rows_.end(), key); + if (it == rows_.end()) { + PADDLE_THROW(phi::errors::NotFound( + "Input id (%lld) is not in current rows table.", key)); + } + return static_cast(std::distance(rows_.begin(), it)); + } + + /* + * @brief whether has the specified key in the table. + * + * @return true if the key is exists. + */ + bool HasKey(int64_t key) const; + + /* + * @brief Get value by the key list. + * Note!!! this interface is only used when selected_rows is used as + * parameters + * for distribute lookup table. + * + * @return a list of pair which contains the non-exists key and the index in + * the value + */ + void Get(const DenseTensor& ids, + DenseTensor* value, + bool auto_grown = false, + bool is_test = false); + + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0); + + /* + * @brief Get the index of the key from id_to_index_ map. If the key not + * exist, + * add the key into id_to_index_. + * + * Note!!! this interface is only used when selected_rows is used as + * parameters + * for distribute lookup table. + * + * @return index of the key. + */ + int64_t AutoGrownIndex(int64_t key, bool auto_grown, bool is_test = false); + + /* + * @brief Get the index of the key from id_to_index_ map. + */ + inline int64_t GetIndexFromId(int64_t key) const { + auto iter = id_to_index_.find(key); + if (iter == id_to_index_.end()) { + return -1; + } else { + return iter->second; + } + } + + void SyncIndex(); + /* + * @brief Get complete Dims before + */ + phi::DDim GetCompleteDims() const { + std::vector dims = vectorize(value_->dims()); + dims[0] = height_; + return phi::make_ddim(dims); + } + + /// \brief Returns the number of elements contained in tensor. + /// \return The number of elements contained in tensor. + int64_t numel() const { return value_->numel(); } + + /// \brief Returns the dims of the tensor. + /// \return The dims of the tensor. + const DDim& dims() const noexcept { return value_->dims(); } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept { return value_->dtype(); } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept { return value_->layout(); } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const { return value_->place(); } + + /// \brief Test whether the metadata is valid. + /// \return Whether the metadata is valid. + bool valid() const noexcept { return value_->valid(); } + + /// \brief Test whether the storage is allocated. + /// return Whether the storage is allocated. + bool initialized() const { return value_->initialized(); } + + private: + // Notice: rows can be duplicate. We can have {0, 4, 7, 0, 5, 7, 9} here. + // SelectedRowsImpl are simply concated when adding together. Until a + // SelectedRowsImpl add a Tensor, will the duplicate rows be handled. + std::vector rows_; + std::unordered_map + id_to_index_; // should not be used when rows_ has duplicate member + std::unique_ptr value_{nullptr}; + int64_t height_; // height indicates the underline tensor's height + std::unique_ptr rwlock_{nullptr}; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/serialization.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..4470b5c128f3d454e09bad67e407e818d7200b71 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/serialization.h @@ -0,0 +1,52 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +/* + * Serialize/Desiralize DenseTensor to std::ostream + * You can pass ofstream or ostringstream to serilize to file + * or to a in memory string. GPU tensor will be copied to CPU. + */ +void SerializeToStream(std::ostream& os, + const DenseTensor& tensor, + const DeviceContext& dev_ctx); +void DeserializeFromStream(std::istream& is, + DenseTensor* tensor, + const DeviceContext& dev_ctx); +void DeserializeFromStream(std::istream& is, + DenseTensor* tensor, + const DeviceContext& dev_ctx, + const size_t& seek, + const std::vector& shape); + +/* + * Serialize/Desiralize SelectedRows to std::ostream + * You can pass ofstream or ostringstream to serilize to file + * or to a in memory string. GPU tensor will be copied to CPU. + */ +void SerializeToStream(std::ostream& os, + const SelectedRows& selected_rows, + const DeviceContext& dev_ctx); +void DeserializeFromStream(std::istream& is, + SelectedRows* selected_rows, + const DeviceContext& dev_ctx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_coo_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_coo_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..a28229996c887140de13b6f3f509ff918703e7a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_coo_tensor.h @@ -0,0 +1,281 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { + +class DenseTensorUtils; + +/// \brief The SparseCooTensor uses two DenseTensors to represent +/// the non zero elements and the indices of non zero elements of +/// original DenseTensor. +/// where non_zero_elements_ represents the non zero elements of original +/// DenseTensor. +/// non_zero_indices_ represents the indices of non zero elements in original +/// DenseTensor. +class SparseCooTensor : public TensorBase, + public TypeInfoTraits { + public: + SparseCooTensor(); + /// \brief Create the sparse coo tensor + /// \param non_zero_indices The indices of non zero elements in original dense + /// tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param dims The dims of original dense tensor. + SparseCooTensor(const DenseTensor& non_zero_indices, + const DenseTensor& non_zero_elements, + const DDim& dims); + + /// \brief Create the sparse coo tensor + /// \param non_zero_indices The indices of non zero elements in original dense + /// tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param dims The dims of original dense tensor. + SparseCooTensor(DenseTensor&& non_zero_indices, + DenseTensor&& non_zero_elements, + const DDim& dims); + + /// \brief SparseCooTensor shallow copy constructor. + SparseCooTensor(const SparseCooTensor& other); + + /// \brief move constructor + SparseCooTensor(SparseCooTensor&& other); + + /// \brief SparseCooTensor shallow copy assignment. + SparseCooTensor operator=(const SparseCooTensor& other); + + /// \brief Destroy the tensor object and release exclusive resources. + virtual ~SparseCooTensor() = default; + + /// \brief Returns the indices of non zero elemetns in original dense tensor. + /// \return The indices of non zero elemetns in original dense tensor. + const DenseTensor& indices() const { return non_zero_indices_; } + + /// Note: This function will removed soon. It is recommended to use indices() + const DenseTensor& non_zero_indices() const { return non_zero_indices_; } + + /// \brief Returns the non zero elemetns in original dense tensor. + /// \return The non zero elemetns in original dense tensor. + const DenseTensor& values() const { return non_zero_elements_; } + + /// Note: This function will removed soon. It is recommended to use values() + const DenseTensor& non_zero_elements() const { return non_zero_elements_; } + + /// \brief Returns whether the indices has coalesced + /// \return whether the indices has coalesced + bool coalesced() const { return coalesced_; } + + /// \brief Set the coalesced + /// \param coalesced whether the indices has coalesced + void SetCoalesced(const bool coalesced) { coalesced_ = coalesced; } + + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "SparseCooTensor"; } + + /// \brief Returns the total number of non zero elements in original + /// DenseTensor + int64_t nnz() const; + + /// \brief Return the number of elements contained in original dense tensor + /// \return The number of elements contained in original dense tensor + int64_t numel() const override { return product(meta_.dims); } + + /// \brief Returns the dims of the original dense tensor. + /// \return The dims of the original dense tensor. + const DDim& dims() const noexcept override { return meta_.dims; } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept override { return meta_.dtype; } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept override { return meta_.layout; } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const override { return non_zero_elements_.place(); } + + /// \brief Test whether the non_zero_elements_ metadata is valid. + /// \return Whether the non_zero_elements_ metadata is valid. + bool valid() const noexcept override { return non_zero_elements_.valid(); } + + /// \brief Test whether the non_zero_elements_ storage is allocated. + /// return Whether the non_zero_elements_ storage is allocated. + bool initialized() const override { return non_zero_elements_.initialized(); } + + /// \brief resize sparse coo tensor. + /// \param dense_dims The dims of original dense tensor. + /// \param sparse_dim number of sparse dimensions + /// \param non_zero_num The total number of non zero element + void Resize(const DDim& dense_dim, + const int64_t sparse_dim, + const int64_t non_zero_num); + + /// \brief set the member of sparse coo tensor. + /// \param non_zero_indices The indices of non zero elements in original dense + /// tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param dims The dims of original dense tensor. + /// \param coalesced whether the indices has coalesced. + void SetMember(const DenseTensor& non_zero_indices, + const DenseTensor& non_zero_elements, + const DDim& dims, + const bool coalesced = false); + + /// \brief set the member of sparse coo tensor. + /// \param non_zero_indices The indices of non zero elements in original dense + /// tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param meta The meta of original dense tensor. + /// \param coalesced whether the indices has coalesced. + void SetMember(const DenseTensor& non_zero_indices, + const DenseTensor& non_zero_elements, + const SparseTensorMeta& meta, + const bool coalesced = false); + + /// \brief Get a mutable pointer of non_zero_indices_. + /// return a mutable pointer of non_zero_indices_. + DenseTensor* mutable_indices() { return &non_zero_indices_; } + + /// Note: This function will removed soon. It is recommended to use + /// mutable_indices() + DenseTensor* mutable_non_zero_indices() { return &non_zero_indices_; } + + /// \brief Get a mutable pointer of non_zero_elements. + /// return a mutable pointer of non_zero_elements. + DenseTensor* mutable_values() { return &non_zero_elements_; } + + /// Note: This function will removed soon. It is recommended to use + /// mutable_values() + DenseTensor* mutable_non_zero_elements() { return &non_zero_elements_; } + + /// \brief This function is not recommended + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override; + + /// \brief get the sparse dim + int32_t sparse_dim() const; + + /// \brief get the dnese dim + int32_t dense_dim() const; + + /// \brief Returns the meta information of the tensor. + /// \return The meta information of the tensor. + const SparseTensorMeta& meta() const noexcept { return meta_; } + + void set_meta(SparseTensorMeta&& meta); + + void set_meta(const SparseTensorMeta& meta); + + void set_dims(const DDim& dims) { meta_.dims = dims; } + + /// \brief query table according to key + const std::pair* IndicesPairs( + const std::string& key) const { + if (indices_dict_ == nullptr) { + return nullptr; + } + const auto& iter = indices_dict_->find(key); + if (iter == indices_dict_->end()) { + return nullptr; + } + return &iter->second; + } + + /// \brief save (key, indices_pairs) + void SaveIndicesPairs( + const std::string& key, + const std::pair& indices_pairs) { + if (indices_dict_ == nullptr) { + indices_dict_ = std::make_shared< + std::map>>(); + } + auto ret = indices_dict_->insert({key, indices_pairs}); + if (ret.second == false) { + ret.first->second = indices_pairs; + } + } + + /// \brief get indices_dict_ + const std::shared_ptr< + std::map>>& + GetIndicesDict() const { + return indices_dict_; + } + + /// \brief set indices_dict_ + void SetIndicesDict( + const std::shared_ptr< + std::map>>& + indices_dict) { + indices_dict_ = indices_dict; + } + + private: + friend class DenseTensorUtils; + + SparseTensorMeta meta_; + + // save the indices of non zero elements in original dense tensor + DenseTensor non_zero_indices_; + // save the non zero elements of original dense tensor + DenseTensor non_zero_elements_; + /// whether the indices has coalesced + bool coalesced_ = false; + // save the number of non zero elements in each batch + DDim dims_; + + // for submanifold conv + // SubmConv will generate a rulebook and a counter, which can be + // reused by different SubmConv. + // refer to sparse/gpu/convolution_kernel.cu. + std::shared_ptr>> + indices_dict_ = nullptr; + + /* --------------------------- */ + /* example: non zero element is scalar */ + /* --------------------------- */ + /* + dense_x = [[0, 1, 0, 0], + [2, 0, 0, 3], + [0, 0, 4, 0], + [0, 5, 0, 6]] + dims_ = (4, 4) + non_zero_elements_ = [1, 2, 3, 4, 5 ,6] + non_zero_indices_ = [[0, 1, 1, 2, 3, 3], + [1, 0, 3, 2, 1, 3]] + */ + /* --------------------------- */ + /* example: non zero element is tensor */ + /* --------------------------- */ + /* + dense_x = [[0, 1, 0, 0], + [0, 0, 0, 0], + [0, 0, 4, 0], + [0, 0, 0, 0]] + dims_ = (4, 4) + non_zero_elements_ = [[0, 1, 0, 0], [0, 0, 4, 0]] + non_zero_indices_ = [[0, 2], [1, 2]] + */ +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_csr_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_csr_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..2acb35915a9c36b0f9a45619097e6af30158e835 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/sparse_csr_tensor.h @@ -0,0 +1,237 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { + +class DenseTensorUtils; + +/// \brief The SparseCsrTensor uses three 1-D DenseTensors to represent +/// the row index , column index and non zero elements of the original +/// DenseTensor. +/// where non_zero_crows_ represents the compressed row index, +/// non_zero_cols_ represents the column index of non zero elements in original +/// DenseTensor, +/// non_zero_elements_ represents the non zero elements of original DenseTensor. +class SparseCsrTensor : public TensorBase, + public TypeInfoTraits { + public: + SparseCsrTensor(); + /// \brief Because sparse csr tensor is a resource handle, we provide a + /// default + /// move constructor to support move semantics. + SparseCsrTensor(SparseCsrTensor&& other) = default; + + /// \brief SparseCsrTensor shallow copy constructor. + SparseCsrTensor(const SparseCsrTensor& other); + + /// \brief create the sparse csr tensor. + /// \param non_zero_crows The compresessed row index of non zero elements in + /// original dense tensor. + /// \param non_zero_cols The column index of non zero elements in original + /// dense tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param dims The dims of original dense tensor. + SparseCsrTensor(const DenseTensor& non_zero_crows, + const DenseTensor& non_zero_cols, + const DenseTensor& non_zero_elements, + const DDim& dims); + + /// \brief SparseCsrTensor shallow copy assignment. + SparseCsrTensor& operator=(const SparseCsrTensor& other); + + /// \brief Destroy the tensor object and release exclusive resources. + virtual ~SparseCsrTensor() = default; + + /// \brief This function is not recommended + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override; + + public: + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "SparseCsrTensor"; } + + /// \brief Returns the compressed row index of non zero elemetns in original + /// dense tensor. + /// \return The compressed row index of non zero elemetns in original dense + /// tensor. + const DenseTensor& crows() const { return non_zero_crows_; } + + /// Note: This function will removed soon. It is recommended to use crows() + const DenseTensor& non_zero_crows() const { return non_zero_crows_; } + + /// \brief Returns the column index of non zero elemetns in original dense + /// tensor. + /// \return The column index of non zero elemetns in original dense tensor. + const DenseTensor& cols() const { return non_zero_cols_; } + + /// Note: This function will removed soon. It is recommended to use cols() + const DenseTensor& non_zero_cols() const { return non_zero_cols_; } + + /// \brief Returns the non zero elemetns in original dense tensor. + /// \return The non zero elemetns in original dense tensor. + const DenseTensor& values() const { return non_zero_elements_; } + + /// Note: This function will removed soon. It is recommended to use indices() + const DenseTensor& non_zero_elements() const { return non_zero_elements_; } + + /// \brief Returns the total number of non zero elements in original dense + /// tensor. + int64_t nnz() const { return non_zero_elements_.numel(); } + + /// \brief Return the number of elements contained in original dense tensor + /// \return The number of elements contained in original dense tensor + int64_t numel() const override { return product(meta_.dims); } + + /// \brief Returns the dims of the original dense tensor. + /// \return The dims of the original dense tensor. + const DDim& dims() const noexcept override { return meta_.dims; } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept override { return meta_.dtype; } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept override { return meta_.layout; } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const override { return non_zero_elements_.place(); } + + /// \brief Test whether the non_zero_elements_ metadata is valid. + /// \return Whether the non_zero_elements_ metadata is valid. + bool valid() const noexcept override { return non_zero_elements_.valid(); } + + /// \brief Test whether the non_zero_elements_ storage is allocated. + /// return Whether the non_zero_elements_ storage is allocated. + bool initialized() const override { return non_zero_elements_.initialized(); } + + /// \brief resize sparse csr tensor. + /// \param dense_dims The dims of original dense tensor. + /// \param non_zero_num The total number of non zero element + void Resize(const DDim& dense_dims, const int64_t non_zero_num); + + /// \brief set the member of sparse csr tensor. + /// \param non_zero_crows The compresessed row index of non zero elements in + /// original dense tensor. + /// \param non_zero_cols The column index of non zero elements in original + /// dense tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param dims The dims of original dense tensor. + void SetMember(const DenseTensor& non_zero_crows, + const DenseTensor& non_zero_cols, + const DenseTensor& non_zero_elements, + const DDim& dims); + + /// \brief set the member of sparse csr tensor. + /// \param non_zero_crows The compresessed row index of non zero elements in + /// original dense tensor. + /// \param non_zero_cols The column index of non zero elements in original + /// dense tensor. + /// \param non_zero_elements The non zero elements of original dense tensor. + /// \param meta The meta of original dense tensor. + void SetMember(const DenseTensor& non_zero_crows, + const DenseTensor& non_zero_cols, + const DenseTensor& non_zero_elements, + const SparseTensorMeta& meta); + + /// \brief Get a mutable pointer of non_zero_crows. + /// return a mutable pointer of non_zero_crows. + DenseTensor* mutable_crows() { return &non_zero_crows_; } + + /// Note: This function will removed soon. It is recommended to use + /// mutable_crows() + DenseTensor* mutable_non_zero_crows() { return &non_zero_crows_; } + + /// \brief Get a mutable pointer of non_zero_cols. + /// return a mutable pointer of non_zero_cols. + DenseTensor* mutable_cols() { return &non_zero_cols_; } + + /// Note: This function will removed soon. It is recommended to use + /// mutable_cols() + DenseTensor* mutable_non_zero_cols() { return &non_zero_cols_; } + + /// \brief Get a mutable pointer of non_zero_elements. + /// return a mutable pointer of non_zero_elements. + DenseTensor* mutable_values() { return &non_zero_elements_; } + + /// Note: This function will removed soon. It is recommended to use + /// mutable_values() + DenseTensor* mutable_non_zero_elements() { return &non_zero_elements_; } + + /// \brief Returns the meta information of the tensor. + /// \return The meta information of the tensor. + const SparseTensorMeta& meta() const noexcept { return meta_; } + + void set_meta(SparseTensorMeta&& meta); + + void set_meta(const SparseTensorMeta& meta); + + /// \brief set the dims of original dense tensor + void set_dims(const DDim& dims) { meta_.dims = dims; } + + protected: + SparseTensorMeta meta_; + + private: + friend class DenseTensorUtils; + // save the compressed rows information of non zero elements + DenseTensor non_zero_crows_; + // save the columns information of non zero elements + DenseTensor non_zero_cols_; + // save the non zero elements + DenseTensor non_zero_elements_; + /* --------------------------- */ + /* example: 2-D Tensor */ + /* --------------------------- */ + /* + x = [[0, 1, 0, 0], + [2, 0, 0, 3], + [0, 0, 4, 0], + [0, 5, 0, 6]] + dims_ = (4, 4) + non_zero_elements_ = [1, 2, 3, 4, 5, 6] + non_zero_crows_ = [0, 1, 3, 4, 6] + non_zero_cols_ = [1, 0, 3, 2, 1, 3] + */ + + /* --------------------------- */ + /* example: 3-D Tensor */ + /* the non zero elements of different batch will be concat together */ + /* --------------------------- */ + /* + x = [[[0, 1, 0, 0], + [2, 0, 0, 3], + [0, 0, 4, 0], + [0, 5, 0, 6]], + [[0, 1, 0, 0], + [2, 0, 0, 3], + [0, 0, 4, 0], + [0, 5, 0, 0]]] + dims_ = (2, 4, 4) + non_zero_elements_ = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5] + non_zero_crows_ = [0, 1, 3, 4, 6, 0, 1, 2, 4, 5] + non_zero_cols_ = [1, 0, 3, 2, 1, 3, 1, 0, 3, 2, 1] + */ +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/stream.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..593bee67ef87684f2d016bc2d7f04aaec5add700 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/stream.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +namespace phi { + +using StreamId = uint64_t; + +// device-agnostic abstraction of any-stream +class Stream final { + public: + Stream() {} + explicit Stream(StreamId id) : id_(id) {} + StreamId id() const { return id_; } + + private: + StreamId id_{0}; // not onwed the stream +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..80d6b69aa6c663fd0a212a37f312005fd55e7f35 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor.h @@ -0,0 +1,139 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/allocator.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { + +namespace dtype { +class pstring; +} // namespace dtype + +/// \brief In Paddle 2.3, we add a new type of Tensor, StringTensor, +/// which is designed for string data management. +/// During the entire life cycle of a StringTensor, its device type and key +/// metadata are set unchanged. +class StringTensorUtils; + +class StringTensor : public TensorBase, + public TypeInfoTraits { + public: + /// \brief Construct a string tensor and allocate space. + /// \param a The allocator used to allocate space. + /// \param meta The meta data of string tensor. + StringTensor(Allocator* a, const StringTensorMeta& meta); + + /// \brief Construct a string tensor and allocate space. + /// \param a The allocator used to allocate space. + /// \param meta The meta data of string tensor. + StringTensor(Allocator* a, StringTensorMeta&& meta); + + StringTensor(const std::shared_ptr& holder, + const StringTensorMeta& meta); + + /// \brief Because string tensor is a resource handle, we provide a default + /// move constructor to support move semantics. + StringTensor(StringTensor&& other) = default; + + StringTensor(const StringTensor& other); + + StringTensor(); + /// \brief StringTensor shallow copy assignment. + StringTensor& operator=(const StringTensor& other); + + StringTensor& operator=(StringTensor&& other); + /// \brief Destroy the tensor object and release exclusive resources. + virtual ~StringTensor() = default; + + public: + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "StringTensor"; } + + /// \brief Returns the number of elements contained in tensor. + /// \return The number of elements contained in tensor. + int64_t numel() const override; + + /// \brief Returns the dims of the tensor. + /// \return The dims of the tensor. + const DDim& dims() const noexcept override { return meta_.dims; } + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + const Place& place() const override; + + /// \brief Returns the meta information of the tensor. + /// \return The meta information of the tensor. + const StringTensorMeta& meta() const noexcept { return meta_; } + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + DataType dtype() const noexcept override { return DataType::PSTRING; } + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + DataLayout layout() const noexcept override { + return DataLayout::PSTRING_UNION; + } + + void set_meta(const StringTensorMeta& meta); + + /// \brief Test whether the metadata is valid. + /// \return Whether the metadata is valid. + bool valid() const noexcept override { return meta_.valid(); } + + /// \brief Test whether the storage is allocated. + /// return Whether the storage is allocated. + bool initialized() const override { return holder_ && holder_->ptr(); } + + /// \brief Check if storage is shared with other objects. + /// \return Whether the storage is shared with other objects. + bool IsSharedWith(const StringTensor& b) const; + + StringTensor& Resize(const DDim& dims); + + /// \brief Returns the actual storage size occupied by tensor, may be larger + /// than its shape dims. + /// \return The actual storage size occupied by tensor. + size_t capacity() const { return holder_->size(); } + + /// \brief Get the const data pointer value of pstring type. + /// \return The const data pointer value of pstring type. + const dtype::pstring* data() const; + dtype::pstring* data(); + + void clear() { + holder_.reset(); + meta_.offset = 0; + } + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override; + dtype::pstring* mutable_data(const phi::Place& place, + size_t requested_size = 0); + + private: + friend class StringTensorUtils; + + private: + StringTensorMeta meta_; + std::shared_ptr holder_; + void init_holder(); +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..777a24c9adfe15bf3dfafeda57c734b6c1c9a665 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/string_tensor_utils.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/string_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +class StringTensorUtils { + public: + static StringTensorMeta* GetMutableMeta(StringTensor* tensor) { + return &(tensor->meta_); + } + + static const std::shared_ptr& GetHolder( + const StringTensor& tensor) { + return tensor.holder_; + } +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_array.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_array.h new file mode 100644 index 0000000000000000000000000000000000000000..6d834a9375a26ebec24a9195858ab36dd585127f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_array.h @@ -0,0 +1,134 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/// \brief The TensorArray store a list of tensor and it is designed for +/// compatible with LodTensorArray in Fluid. It shouldn't be used widely +/// in PHI. If you want to store a list of tensor in PHI, please use std::vector +/// when ever possible. +class TensorArray : public TensorBase, + public TypeInfoTraits { + public: + /// \brief Construct a TensorArray. + /// \param vec The vector DenseTensor used to init TensorArray. + explicit TensorArray(const std::vector& vec); + + explicit TensorArray(size_t n) { + for (size_t i = 0; i < n; i++) { + tensors_.emplace_back(); + } + } + + TensorArray() = default; + + TensorArray(TensorArray&& other) = default; + + TensorArray(const TensorArray& other) = default; + + /// \brief TensorArray shallow copy assignment. + TensorArray& operator=(const TensorArray& other) = default; + + TensorArray& operator=(TensorArray&& other) = default; + + /// \brief Destroy the tensor object and release exclusive resources. + virtual ~TensorArray() = default; + + public: + /// \brief Returns the name of the class for type traits. + /// \return The name of the class. + static const char* name() { return "TensorArray"; } + + /// \brief This overrided function is not used in TensorArray. + int64_t numel() const override; + + /// \brief This overrided function is not used in TensorArray. + const DDim& dims() const override; + + /// \brief This overrided function is not used in TensorArray. + const Place& place() const override; + + /// \brief This overrided function is not used in TensorArray. + DataType dtype() const override; + + /// \brief This overrided function is not used in TensorArray. + DataLayout layout() const override; + + /// \brief This overrided function is not used in TensorArray. + bool valid() const override; + + /// \brief Test whether the tensor's storage in TensorArray is allocated. + /// return Whether all tensors in TensorArray is allocated. + bool initialized() const override; + + /// \brief Clear all tensors in TensorArray. + void clear() { tensors_.clear(); } + + /// \brief Allocate memory with requested size for all tensors from allocator. + /// \return Void pointer + void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) override; + + bool empty() const { return tensors_.empty(); } + + /// \brief Returns the number of tensors in TensorArray. + size_t size() const { return tensors_.size(); } + + /// \brief Resizes the TensorArray so that it contains n tensors. + void resize(size_t n) { tensors_.resize(n); } + + /// \brief Requests that the TensorArray capacity be at least enough to + /// contain n tensors. + void reserve(size_t n) { tensors_.reserve(n); } + + /// \brief Add the tensor to the end of TensorArray + void push_back(const DenseTensor& tensor); + + void emplace_back(); + + void emplace_back(const DenseTensor& tensor); + + /// \brief Return the last tensor in TensorArray + DenseTensor& back() { return tensors_.back(); } + + DenseTensor& at(size_t index) { return tensors_.at(index); } + + const DenseTensor& at(size_t index) const { return tensors_.at(index); } + + const DenseTensor& operator[](size_t index) const { return tensors_[index]; } + + DenseTensor& operator[](size_t index) { return tensors_[index]; } + + std::vector::iterator begin() { return tensors_.begin(); } + + std::vector::const_iterator begin() const { + return tensors_.begin(); + } + + std::vector::iterator end() { return tensors_.end(); } + + std::vector::const_iterator end() const { + return tensors_.end(); + } + + private: + std::vector tensors_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_base.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_base.h new file mode 100644 index 0000000000000000000000000000000000000000..3dc0e455a6358eddf59d7f13ee8f4aa894aa8351 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_base.h @@ -0,0 +1,82 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/backend.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/common/place.h" +#include "paddle/phi/core/allocator.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/utils/type_registry.h" + +namespace phi { + +class TensorBase { + public: + using DDim = phi::DDim; + + virtual ~TensorBase() = default; + + /// \brief Returns the number of elements contained in tensor. + /// \return The number of elements contained in tensor. + virtual int64_t numel() const = 0; + + /// \brief Returns the dims of the tensor. + /// \return The dims of the tensor. + virtual const DDim& dims() const = 0; + + /// \brief Returns the data type of the tensor. + /// \return The data type of the tensor. + virtual DataType dtype() const = 0; + + /// \brief Returns the data layout of the tensor. + /// \return The data layout of the tensor. + virtual DataLayout layout() const = 0; + + /// \brief Returns the data place of the tensor. + /// \return The data place of the tensor. + virtual const Place& place() const = 0; + + /// \brief Test whether the metadata is valid. + /// \return Whether the metadata is valid. + virtual bool valid() const = 0; + + /// \brief Test whether the storage is allocated. + /// \return Whether the storage is allocated. + virtual bool initialized() const = 0; + + // TODO(Aurelius84): This interface is under intermediate state now. + // We will remove DataType argument in the future. Please DO NOT + // rely on Datatype too much when designing and implementing other features. + + /// \brief Allocate memory with requested size from allocator. + /// \return The mutable data pointer value of type T. + virtual void* AllocateFrom(Allocator* allocator, + DataType dtype, + size_t requested_size = 0) = 0; + + /// \brief Return the type information of the derived class to support + /// safely downcast in non-rtti environment. + /// \return The type information of the derived class. + TypeInfo type_info() const { return type_info_; } + + private: + template + friend class TypeInfoTraits; + TypeInfo type_info_{TypeInfo::kUnknownType}; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_meta.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..8969ef16d95bfd24b999c18464705ae2ca1616f7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_meta.h @@ -0,0 +1,122 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +#include "paddle/phi/common/backend.h" +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/layout.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/utils/any.h" +#include "paddle/utils/optional.h" + +namespace phi { + +/* + * LoD is short for Level of Details. + * + * - in a level, each element indicates relative offset of the lower level + * - the first element should be 0 and that indicates that this sequence start + * from 0 + * - each sequence's begin and end(no-inclusive) is level[id, id+1] + * + * For example: + * 3-level LoD stores + * + * 0 2 3 + * 0 2 4 7 + * 0 2 5 7 10 12 15 20 + */ +using LoD = std::vector>; + +/// \brief The meta data of dense tensor. Take the structure type +/// and use all default operations. +/// +struct DenseTensorMeta { + using DataType = paddle::experimental::DataType; + using DataLayout = paddle::experimental::DataLayout; + + DenseTensorMeta() = default; + DenseTensorMeta(DataType dtype, const DDim& dims); + DenseTensorMeta(DataType dtype, + const DDim& dims, + DataLayout layout, + size_t offset = 0); + DenseTensorMeta(DataType dtype, + const DDim& dims, + DataLayout layout, + const LoD& lod, + size_t offset = 0); + + /// \brief Test whether the metadata is valid. Does not throw exceptions. + /// \return Whether the metadata is valid. + bool valid() const noexcept; + + bool is_scalar{false}; + DDim dims; + DataType dtype{DataType::UNDEFINED}; + DataLayout layout{DataLayout::NCHW}; + LoD lod; + size_t offset{0}; +}; + +inline bool operator==(const DenseTensorMeta& lhs, const DenseTensorMeta& rhs) { + return (lhs.is_scalar == rhs.is_scalar) && (lhs.dims == rhs.dims) && + (lhs.dtype == rhs.dtype) && (lhs.layout == rhs.layout) && + (lhs.lod == rhs.lod) && (lhs.offset == rhs.offset); +} + +struct StringTensorMeta { + StringTensorMeta() = default; + explicit StringTensorMeta(const DDim& dims); + /// \brief Test whether the metadata is valid. Does not throw exceptions. + /// \return Whether the metadata is valid. + bool valid() const noexcept; + + /// During the entire life cycle of a DenseTensor, the following attributes + /// marked with `const` are expected to remain unchanged. + bool is_scalar{false}; + DDim dims; + size_t offset{0}; +}; + +inline bool operator==(const StringTensorMeta& lhs, + const StringTensorMeta& rhs) { + return (lhs.is_scalar == rhs.is_scalar) && (lhs.dims == rhs.dims) && + (lhs.offset == rhs.offset); +} + +struct SparseTensorMeta { + using DataLayout = paddle::experimental::DataLayout; + + SparseTensorMeta() = default; + explicit SparseTensorMeta(const DDim& dims); + explicit SparseTensorMeta(const DDim& dims, const DataLayout& layout); + /// \brief Test whether the metadata is valid. Does not throw exceptions. + /// \return Whether the metadata is valid. + bool valid() const noexcept; + + DDim dims; + DataType dtype; + DataLayout layout{DataLayout::NCHW}; +}; + +inline bool operator==(const SparseTensorMeta& lhs, + const SparseTensorMeta& rhs) { + return (lhs.dims == rhs.dims) && (lhs.layout == rhs.layout); +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ceb46e2abecd7ad6b715c2a47f2384131323f9d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/tensor_utils.h @@ -0,0 +1,112 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { + +class DenseTensorUtils { + public: + static DenseTensorMeta* GetMutableMeta(DenseTensor* tensor) { + return &(tensor->meta_); + } + + static SparseTensorMeta* GetMutableMeta(SparseCooTensor* tensor) { + return &(tensor->meta_); + } + + static SparseTensorMeta* GetMutableMeta(SparseCsrTensor* tensor) { + return &(tensor->meta_); + } + + static const std::shared_ptr& GetHolder( + const DenseTensor& tensor) { + return tensor.holder_; + } + + static DenseTensor Slice(const DenseTensor& tensor, + int64_t begin_idx, + int64_t end_idx) { + size_t bytes = tensor.numel() * SizeOf(tensor.dtype()); + PADDLE_ENFORCE_GE(tensor.capacity(), + bytes, + phi::errors::InvalidArgument( + "The memory size %d should be enough to meet the " + "volume required by metadata %d.", + tensor.capacity(), + bytes)); + PADDLE_ENFORCE_GE( + begin_idx, + 0, + phi::errors::OutOfRange("The start row index must be greater than 0." + "But received the start index is d%.", + begin_idx)); + PADDLE_ENFORCE_LE( + end_idx, + tensor.dims()[0], + phi::errors::OutOfRange("The end row index is out of bound.")); + PADDLE_ENFORCE_LT( + begin_idx, + end_idx, + phi::errors::InvalidArgument( + "The start row index must be less than the end row index." + "But received the start index = %d, the end index = %d.", + begin_idx, + end_idx)); + DenseTensor ret(tensor); + if (tensor.dims()[0] != 1) { + ret.meta_.dims[0] = end_idx - begin_idx; + ret.meta_.offset = tensor.meta_.offset + + begin_idx * (tensor.numel() / tensor.dims()[0]) * + paddle::experimental::SizeOf(tensor.dtype()); + } + return ret; + } +}; + +template +void Copy(const Context& dev_ctx, + const DenseTensor& src, + Place dst_place, + bool blocking, + DenseTensor* dst); + +template +void Copy(const Context& dev_ctx, + const SelectedRows& src, + Place dst_place, + bool blocking, + SelectedRows* dst); + +template +void Copy(const Context& dev_ctx, + const SparseCooTensor& src, + Place dst_place, + bool blocking, + SparseCooTensor* dst); + +template +void Copy(const Context& dev_ctx, + const SparseCsrTensor& src, + Place dst_place, + bool blocking, + SparseCsrTensor* dst); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/type_defs.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/type_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..2edca98bfd951239f4261e5e145779e5a35fe7e1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/type_defs.h @@ -0,0 +1,45 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include +#include +#include + +namespace phi { + +class Kernel; +class KernelKey; +class KernelArgsDef; +class KernelContext; +struct KernelSignature; +class ArgumentMappingContext; +class InferMetaContext; + +using KernelFn = std::function; +using KernelArgsDefFn = void (*)(const KernelKey& kernel_key, Kernel* kernel); +using KernelArgsParseFn = void (*)(const KernelKey& default_key, + KernelArgsDef* args_def); + +using ArgumentMappingFn = + std::function; +using InferMetaFn = void (*)(InferMetaContext* ctx); + +// Global SmallVector size setting +constexpr size_t kInputSmallVectorSize = 15U; +constexpr size_t kAttrSmallVectorSize = 15U; +constexpr size_t kOutputSmallVectorSize = 15U; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/array.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/array.h new file mode 100644 index 0000000000000000000000000000000000000000..b21e0bc088c49ed0392de1a0086094b68dae5f1b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/array.h @@ -0,0 +1,142 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/utils/unroll_array_ops.h" + +namespace phi { + +template +class Array { + public: + static constexpr size_t kSize = N; + + HOSTDEVICE inline Array() {} + + template + HOSTDEVICE inline explicit Array(const T &val, Args... args) { + static_assert(N == sizeof...(Args) + 1, "Invalid argument"); + UnrollVarArgsAssign::Run(data_, val, args...); + } + + HOSTDEVICE inline void Fill(const T &val) { + UnrollFillConstant::Run(data_, val); + } + + HOSTDEVICE inline const T *Get() const { return data_; } + + HOSTDEVICE inline T *GetMutable() { return data_; } + + HOSTDEVICE inline T &operator[](size_t i) { return *advance(data_, i); } + + // Writing "return data_[i]" would cause compilation warning/error: + // "array subscript is above array bound" in Python 35 CI. + // It seems that it is a false warning of GCC if we do not check the bounds + // of array index. But for better performance, we do not check in operator[] + // like what is in STL. If users want to check the bounds, use at() instead + HOSTDEVICE inline const T &operator[](size_t i) const { + return *advance(data_, i); + } + + HOSTDEVICE inline T &at(size_t i) { +#if !defined(__CUDA_ARCH__) && !defined(__HIPCC__) + PADDLE_ENFORCE_LT( + i, N, phi::errors::OutOfRange("Array index out of bounds.")); +#endif + return (*this)[i]; + } + + HOSTDEVICE inline const T &at(size_t i) const { +#if !defined(__CUDA_ARCH__) && !defined(__HIPCC__) + PADDLE_ENFORCE_LT( + i, N, phi::errors::OutOfRange("Array index out of bounds.")); +#endif + return (*this)[i]; + } + + HOSTDEVICE constexpr size_t size() const { return N; } + + HOSTDEVICE inline bool operator==(const Array &other) const { + return UnrollCompare::Run(data_, other.data_); + } + + HOSTDEVICE inline bool operator!=(const Array &other) const { + return !(*this == other); + } + + private: + template + HOSTDEVICE static inline U *advance(U *ptr, size_t i) { + return ptr + i; + } + + T data_[N]; +}; + +template +class Array { + public: + static constexpr size_t kSize = 0; + + HOSTDEVICE inline Array() {} + + HOSTDEVICE inline void Fill(const T &val) {} + + HOSTDEVICE inline constexpr T *Get() const { return nullptr; } + + // Add constexpr to GetMutable() cause warning in MAC + HOSTDEVICE inline T *GetMutable() { return nullptr; } + + HOSTDEVICE inline T &operator[](size_t) { +#if defined(__HIPCC__) || defined(__CUDA_ARCH__) + // HIP and CUDA will have compile error, if use "obj()" + // function declared in block scope cannot have 'static' storage class + static T obj{}; + return obj; +#else + PADDLE_THROW(phi::errors::Unavailable("Array has no element.")); +#endif + } + + HOSTDEVICE inline const T &operator[](size_t) const { +#if defined(__HIPCC__) || defined(__CUDA_ARCH__) + // HIP and CUDA will have compile error, if use "obj()" + // function declared in block scope cannot have 'static' storage class + static const T obj{}; + return obj; +#else + PADDLE_THROW(phi::errors::Unavailable("Array has no element.")); +#endif + } + + HOSTDEVICE inline T &at(size_t i) { return (*this)[i]; } + + HOSTDEVICE inline const T &at(size_t i) const { return (*this)[i]; } + + HOSTDEVICE constexpr size_t size() const { return 0; } + + HOSTDEVICE constexpr bool operator==(const Array &other) const { + return true; + } + + HOSTDEVICE constexpr bool operator!=(const Array &other) const { + return false; + } +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/data_type.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..ecb51f2c0c48d5cc8ed231395d632749a0c53eb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/data_type.h @@ -0,0 +1,112 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#include +#include +#include + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/core/enforce.h" +namespace phi { + +#define _PhiForEachDataTypeHelper_(callback, cpp_type, data_type) \ + callback(cpp_type, data_type); + +#define _PhiForEachDataType_(callback) \ + _PhiForEachDataTypeHelper_(callback, float, DataType::FLOAT32); \ + _PhiForEachDataTypeHelper_( \ + callback, ::phi::dtype::float16, DataType::FLOAT16); \ + _PhiForEachDataTypeHelper_( \ + callback, ::phi::dtype::bfloat16, DataType::BFLOAT16); \ + _PhiForEachDataTypeHelper_(callback, double, DataType::FLOAT64); \ + _PhiForEachDataTypeHelper_(callback, int, DataType::INT32); \ + _PhiForEachDataTypeHelper_(callback, int64_t, DataType::INT64); \ + _PhiForEachDataTypeHelper_(callback, bool, DataType::BOOL); \ + _PhiForEachDataTypeHelper_(callback, uint8_t, DataType::UINT8); \ + _PhiForEachDataTypeHelper_(callback, int16_t, DataType::INT16); \ + _PhiForEachDataTypeHelper_(callback, int8_t, DataType::INT8); \ + _PhiForEachDataTypeHelper_( \ + callback, ::phi::dtype::complex, DataType::COMPLEX64); \ + _PhiForEachDataTypeHelper_( \ + callback, ::phi::dtype::complex, DataType::COMPLEX128); + +#define _PhiForEachDataTypeTiny_(callback) \ + _PhiForEachDataTypeHelper_(callback, int, DataType::INT32); \ + _PhiForEachDataTypeHelper_(callback, int64_t, DataType::INT64); + +template +inline void VisitDataType(phi::DataType type, Visitor visitor) { +#define PhiVisitDataTypeCallback(cpp_type, data_type) \ + do { \ + if (type == data_type) { \ + visitor.template apply(); \ + return; \ + } \ + } while (0) + + _PhiForEachDataType_(PhiVisitDataTypeCallback); +#undef PhiVisitDataTypeCallback + PADDLE_THROW(phi::errors::Unimplemented( + "Not supported phi::DataType(%d) as data type.", static_cast(type))); +} + +template +inline void VisitDataTypeTiny(phi::DataType type, Visitor visitor) { +#define PhiVisitDataTypeCallbackTiny(cpp_type, data_type) \ + do { \ + if (type == data_type) { \ + visitor.template apply(); \ + return; \ + } \ + } while (0) + + _PhiForEachDataTypeTiny_(PhiVisitDataTypeCallbackTiny); +#undef PhiVisitDataTypeCallbackTiny + PADDLE_THROW(phi::errors::Unimplemented( + "Not supported phi::DataType(%d) as data type.", static_cast(type))); +} + +inline bool IsComplexType(const DataType& type) { + return (type == DataType::COMPLEX64 || type == DataType::COMPLEX128); +} + +inline DataType ToComplexType(const DataType& type) { + switch (type) { + case DataType::FLOAT32: + return DataType::COMPLEX64; + case DataType::FLOAT64: + return DataType::COMPLEX128; + default: + PADDLE_THROW(errors::Unimplemented( + "Can not transform data type (%s) to complex type, now only support " + "float32 and float64 real value.", + type)); + } +} + +inline DataType ToRealType(const DataType& type) { + switch (type) { + case DataType::COMPLEX64: + return DataType::FLOAT32; + case DataType::COMPLEX128: + return DataType::FLOAT64; + default: + PADDLE_THROW(errors::Unimplemented( + "Can not transform data type (%s) to real type, now only support " + "complex64 and complex128 value.", + type)); + } +} +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/dim.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/dim.h new file mode 100644 index 0000000000000000000000000000000000000000..9fd1dbf4d05b6eb5f8a3b4195e7eb64e828bc2d1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/dim.h @@ -0,0 +1,106 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include +#include +#include +#include + +#include "paddle/phi/core/hostdevice.h" +#include "paddle/phi/core/utils/array.h" + +namespace phi { + +// Statically sized, statically indexed dimension +template +class Dim : public Array { + public: + static_assert(D >= 0, "D must be not less than 0"); + + static constexpr int kRank = D; + using BaseClass = Array; + + inline Dim(int64_t head, const Dim& tail) { + (*this)[0] = head; + new (this->GetMutable() + 1) Dim(tail); + } + + template + HOSTDEVICE explicit Dim(int64_t head, Args... args) + : BaseClass(head, args...) {} + + /** Construct a Dim with each dimension set to the given index */ + HOSTDEVICE explicit Dim(int64_t idx) { this->Fill(idx); } + + HOSTDEVICE Dim() = default; + + HOST std::string to_string() const; +}; + +// Product of a Dim +template +HOSTDEVICE inline int64_t product(const Dim& a) { + return UnrollProduct::Run(a.Get()); +} + +/** + * Helper function to create a Dim + * + * \param idxes The type of Dim constructed depends on the number of params + * + */ + +template +HOSTDEVICE inline Dim make_dim(Args... idxes) { + return Dim(idxes...); +} + +// Allows us to output a Dim +template +inline std::ostream& operator<<(std::ostream& os, const Dim& d) { + os << d[0]; + for (int i = 1; i < D; ++i) { + os << ", " << d[i]; + } + return os; +} + +inline std::ostream& operator<<(std::ostream& os, const Dim<0>& d) { + return os; +} + +template +HOST std::string Dim::to_string() const { + std::stringstream stream; + stream << *this; + return stream.str(); +} + +template +inline void static_dim_assign(const T1* in, T2* out) { + UnrollAssign::Run(in, out); +} + +} // namespace phi + +namespace paddle { +namespace framework { +template +using Dim = phi::Dim; + +} // namespace framework +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ptr.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ptr.h new file mode 100644 index 0000000000000000000000000000000000000000..e2e6cb7060d057f9ca136aeb0367acde3a4bf1c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ptr.h @@ -0,0 +1,164 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +#include "glog/logging.h" +#include "paddle/phi/core/enforce.h" + +namespace phi { + +template +class intrusive_ptr { + public: + using this_type = intrusive_ptr; + constexpr intrusive_ptr() noexcept = default; + + ~intrusive_ptr() { + if (px) { + intrusive_ptr_release(px); + } + } + + intrusive_ptr(intrusive_ptr&& rhs) noexcept : px(rhs.px) { rhs.px = nullptr; } + + template ::value>> + intrusive_ptr(intrusive_ptr&& rhs) noexcept : px(rhs.get()) { + rhs.reset(); + } + + intrusive_ptr& operator=(intrusive_ptr&& rhs) { + swap(rhs); + return *this; + } + + void reset() { this_type().swap(*this); } + + void reset(T* rhs) { this_type(rhs).swap(*this); } + + void reset(T* rhs, bool add_ref) { this_type(rhs, add_ref).swap(*this); } + + T* get() const noexcept { return px; } + + T* detach() noexcept { + T* ret = px; + px = nullptr; + return ret; + } + + T& operator*() const { + PADDLE_ENFORCE_NOT_NULL( + px, + phi::errors::PreconditionNotMet( + "The pointer must be non-null before the dereference operation.")); + return *px; + } + + T* operator->() const { + PADDLE_ENFORCE_NOT_NULL( + px, + phi::errors::PreconditionNotMet( + "The pointer must be non-null before the dereference operation.")); + return px; + } + + void swap(intrusive_ptr& rhs) noexcept { + T* tmp = px; + px = rhs.px; + rhs.px = tmp; + } + + private: + template ::value>> + explicit intrusive_ptr(U* p, bool add_ref = true) : px(p) { + if (px && add_ref) { + intrusive_ptr_add_ref(px); + } + } + + template + friend intrusive_ptr make_intrusive(Args&&...); + template + friend intrusive_ptr copy_intrusive(const intrusive_ptr&); + + T* px{nullptr}; +}; + +template +inline bool operator==(const intrusive_ptr& a, + const intrusive_ptr& b) noexcept { + return a.get() == b.get(); +} + +template +inline bool operator!=(const intrusive_ptr& a, + const intrusive_ptr& b) noexcept { + return a.get() != b.get(); +} + +template +inline bool operator==(const intrusive_ptr& a, U* b) noexcept { + return a.get() == b; +} + +template +inline bool operator!=(const intrusive_ptr& a, U* b) noexcept { + return a.get() != b; +} + +template +inline bool operator==(T* a, const intrusive_ptr& b) noexcept { + return a == b.get(); +} + +template +inline bool operator!=(T* a, const intrusive_ptr& b) noexcept { + return a != b.get(); +} + +template +inline bool operator==(const intrusive_ptr& p, std::nullptr_t) noexcept { + return p.get() == nullptr; +} + +template +inline bool operator==(std::nullptr_t, const intrusive_ptr& p) noexcept { + return p.get() == nullptr; +} + +template +inline bool operator!=(const intrusive_ptr& p, std::nullptr_t) noexcept { + return p.get() != nullptr; +} + +template +inline bool operator!=(std::nullptr_t, const intrusive_ptr& p) noexcept { + return p.get() != nullptr; +} + +template +inline intrusive_ptr make_intrusive(Args&&... args) { + return intrusive_ptr(new T(std::forward(args)...), false); +} + +template +inline intrusive_ptr copy_intrusive(const intrusive_ptr& rhs) { + return intrusive_ptr(rhs.get(), true); +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ref_counter.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ref_counter.h new file mode 100644 index 0000000000000000000000000000000000000000..1681f88af054f7ca9e2b6d7148cbc8b35c82b4d3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/intrusive_ref_counter.h @@ -0,0 +1,64 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +namespace phi { + +template +class intrusive_ref_counter; +template +void intrusive_ptr_add_ref(const intrusive_ref_counter* p) noexcept; +template +void intrusive_ptr_release(const intrusive_ref_counter* p) noexcept; + +template +class intrusive_ref_counter { + public: + constexpr intrusive_ref_counter() noexcept : ref_(1) {} + virtual ~intrusive_ref_counter() = default; + + unsigned int use_count() const noexcept { return ref_.load(); } + + protected: + intrusive_ref_counter(const intrusive_ref_counter&) = delete; + intrusive_ref_counter& operator=(const intrusive_ref_counter&) = delete; + + friend void intrusive_ptr_add_ref( + const intrusive_ref_counter* p) noexcept; + friend void intrusive_ptr_release( + const intrusive_ref_counter* p) noexcept; + + private: + mutable std::atomic_int_fast32_t ref_; +}; + +template +inline void intrusive_ptr_add_ref( + const intrusive_ref_counter* p) noexcept { + p->ref_.fetch_add(1, std::memory_order_relaxed); +} + +template +inline void intrusive_ptr_release( + const intrusive_ref_counter* p) noexcept { + if (p->ref_.load(std::memory_order_acquire) == 0 || + p->ref_.fetch_sub(1) == 0) { + delete static_cast(p); + } +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/rw_lock.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/rw_lock.h new file mode 100644 index 0000000000000000000000000000000000000000..fa87cfcbb5feeb138e64d73672e7cd29e47be411 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/rw_lock.h @@ -0,0 +1,103 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#if !defined(_WIN32) +#include +#else +#include // NOLINT +#endif // !_WIN32 + +#include "paddle/phi/core/enforce.h" + +namespace phi { + +#if !defined(_WIN32) +struct RWLock { + RWLock() { pthread_rwlock_init(&lock_, nullptr); } + + ~RWLock() { pthread_rwlock_destroy(&lock_); } + + inline void RDLock() { + PADDLE_ENFORCE_EQ( + pthread_rwlock_rdlock(&lock_), + 0, + phi::errors::External("The pthread failed to acquire read lock.")); + } + + inline void WRLock() { + PADDLE_ENFORCE_EQ( + pthread_rwlock_wrlock(&lock_), + 0, + phi::errors::External("The pthread failed to acquire write lock.")); + } + + inline void UNLock() { + PADDLE_ENFORCE_EQ(pthread_rwlock_unlock(&lock_), + 0, + phi::errors::External("The pthread failed to unlock.")); + } + + private: + pthread_rwlock_t lock_; +}; +// TODO(paddle-dev): Support RWLock for WIN32 for correctness. +#else +// https://stackoverflow.com/questions/7125250/making-pthread-rwlock-wrlock-recursive +// In windows, rw_lock seems like a hack. Use empty object and do nothing. +struct RWLock { + // FIXME(minqiyang): use mutex here to do fake lock + inline void RDLock() { mutex_.lock(); } + + inline void WRLock() { mutex_.lock(); } + + inline void UNLock() { mutex_.unlock(); } + + private: + std::mutex mutex_; +}; +#endif + +class AutoWRLock { + public: + explicit AutoWRLock(RWLock* rw_lock) : lock_(rw_lock) { Lock(); } + + ~AutoWRLock() { UnLock(); } + + private: + inline void Lock() { lock_->WRLock(); } + + inline void UnLock() { lock_->UNLock(); } + + private: + RWLock* lock_; +}; + +class AutoRDLock { + public: + explicit AutoRDLock(RWLock* rw_lock) : lock_(rw_lock) { Lock(); } + + ~AutoRDLock() { UnLock(); } + + private: + inline void Lock() { lock_->RDLock(); } + + inline void UnLock() { lock_->UNLock(); } + + private: + RWLock* lock_; +}; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_info.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_info.h new file mode 100644 index 0000000000000000000000000000000000000000..33a4e09933af74619007d353504fa7c8fafcb6bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_info.h @@ -0,0 +1,59 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include + +namespace phi { + +template +class TypeRegistry; + +template +class TypeInfo { + public: + const std::string& name() const; + + int8_t id() const { return id_; } + + bool operator==(TypeInfo other) const { return id_ == other.id(); } + bool operator!=(TypeInfo other) const { return id_ != other.id(); } + + static const TypeInfo kUnknownType; + + private: + friend class TypeRegistry; + explicit TypeInfo(int8_t id) : id_(id) {} + int8_t id_; +}; + +template +class TypeInfoTraits { + public: + static const TypeInfo kType; + TypeInfoTraits() { + static_cast(static_cast(this))->type_info_ = kType; + } + static bool classof(const BaseT* obj) { return obj->type_info() == kType; } +}; + +template +TypeInfo RegisterStaticType(const std::string& type); + +template +const TypeInfo TypeInfoTraits::kType = + RegisterStaticType(DerivedT::name()); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_registry.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..c233e1f743b213c50a8f49ee6b5f4f48d1826feb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/type_registry.h @@ -0,0 +1,86 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include +#include +#include +#include + +#include "paddle/phi/core/utils/type_info.h" + +namespace phi { + +template +class TypeRegistry { + public: + TypeRegistry(const TypeRegistry&) = delete; + TypeRegistry& operator=(const TypeRegistry&) = delete; + + static TypeRegistry& GetInstance(); + + TypeInfo RegisterType(const std::string& type); + const std::string& GetTypeName(TypeInfo info) const; + + private: + TypeRegistry() = default; + mutable std::mutex mutex_; + std::vector names_; + std::map name_to_id_; +}; + +template +TypeRegistry& TypeRegistry::GetInstance() { + static TypeRegistry registry; + return registry; +} + +template +TypeInfo TypeRegistry::RegisterType(const std::string& type) { + std::lock_guard guard(mutex_); + assert(name_to_id_.find(type) == name_to_id_.end()); + assert(names_.size() < static_cast( + std::numeric_limits::max())); + int8_t id = static_cast(names_.size()); + names_.emplace_back(type); + name_to_id_[type] = id; + return TypeInfo(id); +} + +template +const std::string& TypeRegistry::GetTypeName( + TypeInfo info) const { + std::lock_guard guard(mutex_); + int8_t id = info.id(); + assert(id >= 0); + assert(static_cast(id) < names_.size()); + return names_[id]; +} + +template +TypeInfo RegisterStaticType(const std::string& type) { + return TypeRegistry::GetInstance().RegisterType(type); +} + +template +const std::string& TypeInfo::name() const { + return TypeRegistry::GetInstance().GetTypeName(*this); +} + +template +const TypeInfo TypeInfo::kUnknownType = + RegisterStaticType("Unknown"); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/unroll_array_ops.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/unroll_array_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..fe3ca8ab5ac90e612c3844151fc8ba738a8792f5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/utils/unroll_array_ops.h @@ -0,0 +1,128 @@ +// Copyright (c) 2022 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. + +#pragma once +#include +#include + +#include "paddle/phi/core/hostdevice.h" + +namespace phi { +namespace detail { +template +struct UnrollFillConstant { + template + HOSTDEVICE inline static void Run(T *data, T val) { + data[kStart] = val; + UnrollFillConstant::Run(data, val); + } +}; + +template +struct UnrollFillConstant { + template + HOSTDEVICE inline static void Run(T *data, T val) {} +}; + +template +struct UnrollAssign { + template + HOSTDEVICE inline static void Run(const Tin *d1, Tout *d2) { + d2[kStart] = static_cast(d1[kStart]); + UnrollAssign::Run(d1, d2); + } +}; + +template +struct UnrollAssign { + template + HOSTDEVICE inline static void Run(const Tin *d1, Tout *d2) {} +}; + +template +struct UnrollVarArgsAssignImpl { + template + HOSTDEVICE inline static void Run(T *d, T val, Args... args) { + static_assert(sizeof...(args) + 1 == kEnd - kStart, "Wrong argument"); + d[kStart] = val; + UnrollVarArgsAssignImpl::Run( + d, args...); + } +}; + +template +struct UnrollVarArgsAssignImpl { + HOSTDEVICE inline static void Run(T *d) {} +}; + +template +struct UnrollVarArgsAssign { + template + HOSTDEVICE inline static void Run(T *d, Args... args) { + UnrollVarArgsAssignImpl::Run( + d, args...); + } +}; + +template +struct UnrollCompare { + template + HOSTDEVICE inline static bool Run(const T *d1, const T *d2) { + return d1[kStart] == d2[kStart] && + UnrollCompare::Run(d1, d2); + } +}; + +template +struct UnrollCompare { + template + HOSTDEVICE inline constexpr static bool Run(const T *d1, const T *d2) { + return true; + } +}; + +template +struct UnrollProduct { + template + HOSTDEVICE inline static T Run(const T *d) { + return d[kStart] * + UnrollProduct::Run(d); + } +}; + +template +struct UnrollProduct { + template + HOSTDEVICE inline constexpr static T Run(const T *d) { + return 1; + } +}; +} // namespace detail + +template +using UnrollFillConstant = detail::UnrollFillConstant<0, N, N == 0>; + +template +using UnrollAssign = detail::UnrollAssign<0, N, N == 0>; + +template +using UnrollVarArgsAssign = detail::UnrollVarArgsAssign; + +template +using UnrollCompare = detail::UnrollCompare<0, N, N == 0>; + +template +using UnrollProduct = detail::UnrollProduct<0, N, N == 0>; + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/visit_type.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/visit_type.h new file mode 100644 index 0000000000000000000000000000000000000000..77fa2a3decce3c91402eee1a2eb7f23bbbe30be8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/core/visit_type.h @@ -0,0 +1,352 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/api/ext/exception.h" +#include "paddle/phi/common/data_type.h" + +namespace phi { + +///////// Basic Marco /////////// + +#define PD_PRIVATE_CASE_TYPE_USING_HINT(NAME, enum_type, type, HINT, ...) \ + case enum_type: { \ + using HINT = type; \ + __VA_ARGS__(); \ + break; \ + } + +#define PD_PRIVATE_CASE_TYPE(NAME, enum_type, type, ...) \ + PD_PRIVATE_CASE_TYPE_USING_HINT(NAME, enum_type, type, data_t, __VA_ARGS__) + +///////// Floating Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +#define PD_VISIT_FLOATING_AND_HALF_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT16, paddle::float16, __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Integral Dispatch Marco /////////// + +#define PD_VISIT_INTEGRAL_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT64, int64_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT8, int8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::UINT8, uint8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT16, int16_t, __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +#define PD_VISIT_BASE_INTEGRAL_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT64, int64_t, __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Complex Dispatch Marco /////////// + +#define PD_VISIT_COMPLEX_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Floating and Integral Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_AND_INTEGRAL_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT64, int64_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT8, int8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::UINT8, uint8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT16, int16_t, __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Floating and Complex Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_AND_COMPLEX_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Floating and Complex and other type Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_AND_COMPLEX_AND_1_TYPE( \ + SPECIFIED_TYPE, TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Floating and Complex and 2 other type Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_AND_COMPLEX_AND_2_TYPES( \ + SPECIFIED_TYPE1, SPECIFIED_TYPE2, TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE1, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE2, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +///////// Floating, Integral and Complex Dispatch Marco /////////// + +#define PD_VISIT_FLOATING_AND_INTEGRAL_AND_COMPLEX_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::INT32, int, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT64, int64_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT8, int8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::UINT8, uint8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::INT16, int16_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +#define PD_VISIT_ALL_TYPES(TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::BOOL, bool, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::INT8, int8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::UINT8, uint8_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::INT16, int16_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::INT32, int32_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::INT64, int64_t, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::phi::DataType::BFLOAT16, \ + paddle::experimental::bfloat16, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::phi::DataType::FLOAT16, \ + paddle::experimental::float16, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, ::phi::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::phi::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::phi::DataType::COMPLEX64, \ + paddle::experimental::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::phi::DataType::COMPLEX128, \ + paddle::experimental::complex128, \ + __VA_ARGS__) \ + default: \ + PADDLE_THROW(phi::errors::InvalidArgument( \ + "Invalid enum data type `%d`.", static_cast(__dtype__))); \ + } \ + }() + +#define PD_VISIT_BOOL_AND_FLOATING_AND_COMPLEX_AND_3_TYPES( \ + SPECIFIED_TYPE1, SPECIFIED_TYPE2, SPECIFIED_TYPE3, TYPE, NAME, ...) \ + [&] { \ + const auto& __dtype__ = TYPE; \ + switch (__dtype__) { \ + PD_PRIVATE_CASE_TYPE(NAME, ::paddle::DataType::BOOL, bool, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, ::paddle::DataType::FLOAT64, double, __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX64, \ + ::paddle::complex64, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE(NAME, \ + ::paddle::DataType::COMPLEX128, \ + ::paddle::complex128, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE1, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE2, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + PD_PRIVATE_CASE_TYPE( \ + NAME, \ + SPECIFIED_TYPE3, \ + ::paddle::experimental::DataTypeToCppType::type, \ + __VA_ARGS__) \ + default: \ + PD_THROW("function " #NAME " is not implemented for data type `", \ + __dtype__, \ + "`"); \ + } \ + }() + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/extension.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/extension.h new file mode 100644 index 0000000000000000000000000000000000000000..19706ef3ff1ececc15a29371e2a909a86e020b26 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/extension.h @@ -0,0 +1,9 @@ +// Header file generated by paddle/phi/CMakeLists.txt for external users, +// DO NOT edit or include it within paddle. + +#pragma once + +#include "paddle/phi/include/backends.h" +#include "paddle/phi/include/core.h" +#include "paddle/phi/include/infermeta.h" +#include "paddle/phi/include/kernels.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/backends.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/backends.h new file mode 100644 index 0000000000000000000000000000000000000000..f17756599885d7339b700336aa95c73230bf09da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/backends.h @@ -0,0 +1,14 @@ +// Header file generated by paddle/phi/CMakeLists.txt for external users, +// DO NOT edit or include it within paddle. + +#pragma once + +#include "paddle/phi/backends/all_context.h" +#include "paddle/phi/backends/c_comm_lib.h" +#include "paddle/phi/backends/callback_manager.h" +#include "paddle/phi/backends/device_base.h" +#include "paddle/phi/backends/device_ext.h" +#include "paddle/phi/backends/device_guard.h" +#include "paddle/phi/backends/device_manager.h" +#include "paddle/phi/backends/event.h" +#include "paddle/phi/backends/stream.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/core.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/core.h new file mode 100644 index 0000000000000000000000000000000000000000..ee5d9d79b10213c348133ebac92c885acbca0a9b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/core.h @@ -0,0 +1,37 @@ +// Header file generated by paddle/phi/CMakeLists.txt for external users, +// DO NOT edit or include it within paddle. + +#pragma once + +#include "paddle/phi/core/allocator.h" +#include "paddle/phi/core/attribute.h" +#include "paddle/phi/core/custom_kernel.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/core/errors.h" +#include "paddle/phi/core/generator.h" +#include "paddle/phi/core/hostdevice.h" +#include "paddle/phi/core/infermeta_utils.h" +#include "paddle/phi/core/kernel_context.h" +#include "paddle/phi/core/kernel_factory.h" +#include "paddle/phi/core/kernel_registry.h" +#include "paddle/phi/core/kernel_utils.h" +#include "paddle/phi/core/lod_utils.h" +#include "paddle/phi/core/macros.h" +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/selected_rows.h" +#include "paddle/phi/core/selected_rows_impl.h" +#include "paddle/phi/core/serialization.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/core/stream.h" +#include "paddle/phi/core/string_tensor.h" +#include "paddle/phi/core/string_tensor_utils.h" +#include "paddle/phi/core/tensor_array.h" +#include "paddle/phi/core/tensor_base.h" +#include "paddle/phi/core/tensor_meta.h" +#include "paddle/phi/core/tensor_utils.h" +#include "paddle/phi/core/type_defs.h" +#include "paddle/phi/core/visit_type.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/infermeta.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/infermeta.h new file mode 100644 index 0000000000000000000000000000000000000000..f9cf59a1d2998063da3851ed74b6cda26c270bde --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/infermeta.h @@ -0,0 +1,12 @@ +// Header file generated by paddle/phi/CMakeLists.txt for external users, +// DO NOT edit or include it within paddle. + +#pragma once + +#include "paddle/phi/infermeta/backward.h" +#include "paddle/phi/infermeta/binary.h" +#include "paddle/phi/infermeta/generated.h" +#include "paddle/phi/infermeta/multiary.h" +#include "paddle/phi/infermeta/nullary.h" +#include "paddle/phi/infermeta/ternary.h" +#include "paddle/phi/infermeta/unary.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/kernels.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/kernels.h new file mode 100644 index 0000000000000000000000000000000000000000..ddabfa564a2f954b52cef99cef41db5c56648d5a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/include/kernels.h @@ -0,0 +1,254 @@ +// Header file generated by paddle/phi/CMakeLists.txt for external users, +// DO NOT edit or include it within paddle. + +#pragma once + +#include "paddle/phi/kernels/abs_kernel.h" +#include "paddle/phi/kernels/accuracy_kernel.h" +#include "paddle/phi/kernels/activation_kernel.h" +#include "paddle/phi/kernels/adadelta_kernel.h" +#include "paddle/phi/kernels/adam_kernel.h" +#include "paddle/phi/kernels/adamax_kernel.h" +#include "paddle/phi/kernels/adamw_kernel.h" +#include "paddle/phi/kernels/add_n_kernel.h" +#include "paddle/phi/kernels/addmm_kernel.h" +#include "paddle/phi/kernels/affine_grid_kernel.h" +#include "paddle/phi/kernels/allclose_kernel.h" +#include "paddle/phi/kernels/amp_kernel.h" +#include "paddle/phi/kernels/angle_kernel.h" +#include "paddle/phi/kernels/arange_kernel.h" +#include "paddle/phi/kernels/arg_min_max_kernel.h" +#include "paddle/phi/kernels/argsort_kernel.h" +#include "paddle/phi/kernels/as_complex_kernel.h" +#include "paddle/phi/kernels/as_real_kernel.h" +#include "paddle/phi/kernels/assign_kernel.h" +#include "paddle/phi/kernels/atan2_kernel.h" +#include "paddle/phi/kernels/auc_kernel.h" +#include "paddle/phi/kernels/average_accumulates_kernel.h" +#include "paddle/phi/kernels/batch_norm_kernel.h" +#include "paddle/phi/kernels/bce_loss_kernel.h" +#include "paddle/phi/kernels/bernoulli_kernel.h" +#include "paddle/phi/kernels/bilinear_tensor_product_kernel.h" +#include "paddle/phi/kernels/bincount_kernel.h" +#include "paddle/phi/kernels/bitwise_kernel.h" +#include "paddle/phi/kernels/bmm_kernel.h" +#include "paddle/phi/kernels/box_coder_kernel.h" +#include "paddle/phi/kernels/broadcast_tensors_kernel.h" +#include "paddle/phi/kernels/cast_kernel.h" +#include "paddle/phi/kernels/channel_shuffle_kernel.h" +#include "paddle/phi/kernels/cholesky_kernel.h" +#include "paddle/phi/kernels/cholesky_solve_kernel.h" +#include "paddle/phi/kernels/class_center_sample_kernel.h" +#include "paddle/phi/kernels/clip_by_norm_kernel.h" +#include "paddle/phi/kernels/clip_kernel.h" +#include "paddle/phi/kernels/coalesce_tensor_kernel.h" +#include "paddle/phi/kernels/compare_kernel.h" +#include "paddle/phi/kernels/complex_kernel.h" +#include "paddle/phi/kernels/concat_kernel.h" +#include "paddle/phi/kernels/conv_kernel.h" +#include "paddle/phi/kernels/conv_transpose_kernel.h" +#include "paddle/phi/kernels/crop_tensor_kernel.h" +#include "paddle/phi/kernels/cross_entropy_kernel.h" +#include "paddle/phi/kernels/cross_kernel.h" +#include "paddle/phi/kernels/cum_kernel.h" +#include "paddle/phi/kernels/cumprod_kernel.h" +#include "paddle/phi/kernels/decode_jpeg_kernel.h" +#include "paddle/phi/kernels/deformable_conv_kernel.h" +#include "paddle/phi/kernels/depthwise_conv_kernel.h" +#include "paddle/phi/kernels/determinant_kernel.h" +#include "paddle/phi/kernels/diag_embed_kernel.h" +#include "paddle/phi/kernels/diag_kernel.h" +#include "paddle/phi/kernels/diagonal_kernel.h" +#include "paddle/phi/kernels/digamma_kernel.h" +#include "paddle/phi/kernels/dirichlet_kernel.h" +#include "paddle/phi/kernels/dist_kernel.h" +#include "paddle/phi/kernels/distribute_fpn_proposals_kernel.h" +#include "paddle/phi/kernels/dot_kernel.h" +#include "paddle/phi/kernels/dropout_kernel.h" +#include "paddle/phi/kernels/edit_distance_kernel.h" +#include "paddle/phi/kernels/eig_kernel.h" +#include "paddle/phi/kernels/eigh_kernel.h" +#include "paddle/phi/kernels/eigvals_kernel.h" +#include "paddle/phi/kernels/eigvalsh_kernel.h" +#include "paddle/phi/kernels/einsum_kernel.h" +#include "paddle/phi/kernels/elementwise_add_kernel.h" +#include "paddle/phi/kernels/elementwise_divide_kernel.h" +#include "paddle/phi/kernels/elementwise_kernel.h" +#include "paddle/phi/kernels/elementwise_multiply_kernel.h" +#include "paddle/phi/kernels/elementwise_subtract_kernel.h" +#include "paddle/phi/kernels/embedding_kernel.h" +#include "paddle/phi/kernels/empty_kernel.h" +#include "paddle/phi/kernels/erf_kernel.h" +#include "paddle/phi/kernels/erfinv_kernel.h" +#include "paddle/phi/kernels/expand_as_kernel.h" +#include "paddle/phi/kernels/expand_kernel.h" +#include "paddle/phi/kernels/exponential_kernel.h" +#include "paddle/phi/kernels/eye_kernel.h" +#include "paddle/phi/kernels/fft_kernel.h" +#include "paddle/phi/kernels/fill_diagonal_kernel.h" +#include "paddle/phi/kernels/fill_diagonal_tensor_kernel.h" +#include "paddle/phi/kernels/fill_kernel.h" +#include "paddle/phi/kernels/flatten_kernel.h" +#include "paddle/phi/kernels/flip_kernel.h" +#include "paddle/phi/kernels/fold_kernel.h" +#include "paddle/phi/kernels/frame_kernel.h" +#include "paddle/phi/kernels/frobenius_norm_kernel.h" +#include "paddle/phi/kernels/full_kernel.h" +#include "paddle/phi/kernels/gather_kernel.h" +#include "paddle/phi/kernels/gather_nd_kernel.h" +#include "paddle/phi/kernels/gather_tree_kernel.h" +#include "paddle/phi/kernels/gaussian_random_kernel.h" +#include "paddle/phi/kernels/gelu_kernel.h" +#include "paddle/phi/kernels/generate_proposals_v2_kernel.h" +#include "paddle/phi/kernels/graph_reindex_kernel.h" +#include "paddle/phi/kernels/graph_sample_neighbors_kernel.h" +#include "paddle/phi/kernels/graph_send_recv_kernel.h" +#include "paddle/phi/kernels/graph_send_ue_recv_kernel.h" +#include "paddle/phi/kernels/graph_send_uv_kernel.h" +#include "paddle/phi/kernels/grid_sample_kernel.h" +#include "paddle/phi/kernels/group_norm_kernel.h" +#include "paddle/phi/kernels/gumbel_softmax_kernel.h" +#include "paddle/phi/kernels/hierarchical_sigmoid_kernel.h" +#include "paddle/phi/kernels/histogram_kernel.h" +#include "paddle/phi/kernels/huber_loss_kernel.h" +#include "paddle/phi/kernels/identity_loss_kernel.h" +#include "paddle/phi/kernels/increment_kernel.h" +#include "paddle/phi/kernels/index_add_kernel.h" +#include "paddle/phi/kernels/index_sample_kernel.h" +#include "paddle/phi/kernels/index_select_kernel.h" +#include "paddle/phi/kernels/instance_norm_kernel.h" +#include "paddle/phi/kernels/interpolate_kernel.h" +#include "paddle/phi/kernels/inverse_kernel.h" +#include "paddle/phi/kernels/is_empty_kernel.h" +#include "paddle/phi/kernels/isclose_kernel.h" +#include "paddle/phi/kernels/isfinite_kernel.h" +#include "paddle/phi/kernels/kldiv_loss_kernel.h" +#include "paddle/phi/kernels/kron_kernel.h" +#include "paddle/phi/kernels/kthvalue_kernel.h" +#include "paddle/phi/kernels/label_smooth_kernel.h" +#include "paddle/phi/kernels/lamb_kernel.h" +#include "paddle/phi/kernels/layer_norm_kernel.h" +#include "paddle/phi/kernels/lerp_kernel.h" +#include "paddle/phi/kernels/lgamma_kernel.h" +#include "paddle/phi/kernels/linspace_kernel.h" +#include "paddle/phi/kernels/log_loss_kernel.h" +#include "paddle/phi/kernels/log_softmax_kernel.h" +#include "paddle/phi/kernels/logical_kernel.h" +#include "paddle/phi/kernels/logspace_kernel.h" +#include "paddle/phi/kernels/logsumexp_kernel.h" +#include "paddle/phi/kernels/lstsq_kernel.h" +#include "paddle/phi/kernels/lu_kernel.h" +#include "paddle/phi/kernels/lu_unpack_kernel.h" +#include "paddle/phi/kernels/margin_cross_entropy_kernel.h" +#include "paddle/phi/kernels/masked_select_kernel.h" +#include "paddle/phi/kernels/matmul_kernel.h" +#include "paddle/phi/kernels/matrix_nms_kernel.h" +#include "paddle/phi/kernels/matrix_power_kernel.h" +#include "paddle/phi/kernels/matrix_rank_kernel.h" +#include "paddle/phi/kernels/matrix_rank_tol_kernel.h" +#include "paddle/phi/kernels/maxout_kernel.h" +#include "paddle/phi/kernels/mean_all_kernel.h" +#include "paddle/phi/kernels/memcpy_kernel.h" +#include "paddle/phi/kernels/merged_momentum_kernel.h" +#include "paddle/phi/kernels/meshgrid_kernel.h" +#include "paddle/phi/kernels/mode_kernel.h" +#include "paddle/phi/kernels/momentum_kernel.h" +#include "paddle/phi/kernels/multi_dot_kernel.h" +#include "paddle/phi/kernels/multiclass_nms3_kernel.h" +#include "paddle/phi/kernels/multinomial_kernel.h" +#include "paddle/phi/kernels/multiplex_kernel.h" +#include "paddle/phi/kernels/mv_kernel.h" +#include "paddle/phi/kernels/nanmedian_kernel.h" +#include "paddle/phi/kernels/nll_loss_kernel.h" +#include "paddle/phi/kernels/nms_kernel.h" +#include "paddle/phi/kernels/norm_kernel.h" +#include "paddle/phi/kernels/one_hot_kernel.h" +#include "paddle/phi/kernels/overlap_add_kernel.h" +#include "paddle/phi/kernels/p_norm_kernel.h" +#include "paddle/phi/kernels/pad3d_kernel.h" +#include "paddle/phi/kernels/pad_kernel.h" +#include "paddle/phi/kernels/pixel_shuffle_kernel.h" +#include "paddle/phi/kernels/pixel_unshuffle_kernel.h" +#include "paddle/phi/kernels/poisson_kernel.h" +#include "paddle/phi/kernels/pool_kernel.h" +#include "paddle/phi/kernels/prelu_kernel.h" +#include "paddle/phi/kernels/prior_box_kernel.h" +#include "paddle/phi/kernels/psroi_pool_kernel.h" +#include "paddle/phi/kernels/put_along_axis_kernel.h" +#include "paddle/phi/kernels/qr_kernel.h" +#include "paddle/phi/kernels/randint_kernel.h" +#include "paddle/phi/kernels/randperm_kernel.h" +#include "paddle/phi/kernels/reduce_all_kernel.h" +#include "paddle/phi/kernels/reduce_amax_kernel.h" +#include "paddle/phi/kernels/reduce_amin_kernel.h" +#include "paddle/phi/kernels/reduce_any_kernel.h" +#include "paddle/phi/kernels/reduce_max_kernel.h" +#include "paddle/phi/kernels/reduce_mean_kernel.h" +#include "paddle/phi/kernels/reduce_min_kernel.h" +#include "paddle/phi/kernels/reduce_prod_kernel.h" +#include "paddle/phi/kernels/reduce_sum_kernel.h" +#include "paddle/phi/kernels/renorm_kernel.h" +#include "paddle/phi/kernels/repeat_interleave_kernel.h" +#include "paddle/phi/kernels/reshape_kernel.h" +#include "paddle/phi/kernels/reverse_kernel.h" +#include "paddle/phi/kernels/rmsprop_kernel.h" +#include "paddle/phi/kernels/rnn_kernel.h" +#include "paddle/phi/kernels/roi_align_kernel.h" +#include "paddle/phi/kernels/roi_pool_kernel.h" +#include "paddle/phi/kernels/roll_kernel.h" +#include "paddle/phi/kernels/rrelu_kernel.h" +#include "paddle/phi/kernels/save_kernel.h" +#include "paddle/phi/kernels/scale_kernel.h" +#include "paddle/phi/kernels/scatter_kernel.h" +#include "paddle/phi/kernels/scatter_nd_add_kernel.h" +#include "paddle/phi/kernels/searchsorted_kernel.h" +#include "paddle/phi/kernels/segment_pool_kernel.h" +#include "paddle/phi/kernels/selu_kernel.h" +#include "paddle/phi/kernels/set_value_kernel.h" +#include "paddle/phi/kernels/sgd_kernel.h" +#include "paddle/phi/kernels/shape_kernel.h" +#include "paddle/phi/kernels/shard_index_kernel.h" +#include "paddle/phi/kernels/sigmoid_cross_entropy_with_logits_kernel.h" +#include "paddle/phi/kernels/sign_kernel.h" +#include "paddle/phi/kernels/size_kernel.h" +#include "paddle/phi/kernels/slice_kernel.h" +#include "paddle/phi/kernels/slogdeterminant_kernel.h" +#include "paddle/phi/kernels/softmax_kernel.h" +#include "paddle/phi/kernels/solve_kernel.h" +#include "paddle/phi/kernels/sparse_weight_embedding_kernel.h" +#include "paddle/phi/kernels/spectral_norm_kernel.h" +#include "paddle/phi/kernels/split_kernel.h" +#include "paddle/phi/kernels/squared_l2_norm_kernel.h" +#include "paddle/phi/kernels/squeeze_kernel.h" +#include "paddle/phi/kernels/stack_kernel.h" +#include "paddle/phi/kernels/strided_slice_kernel.h" +#include "paddle/phi/kernels/svd_kernel.h" +#include "paddle/phi/kernels/sync_batch_norm_kernel.h" +#include "paddle/phi/kernels/take_along_axis_kernel.h" +#include "paddle/phi/kernels/temporal_shift_kernel.h" +#include "paddle/phi/kernels/tile_kernel.h" +#include "paddle/phi/kernels/top_k_kernel.h" +#include "paddle/phi/kernels/trace_kernel.h" +#include "paddle/phi/kernels/transfer_layout_kernel.h" +#include "paddle/phi/kernels/transpose_kernel.h" +#include "paddle/phi/kernels/triangular_solve_kernel.h" +#include "paddle/phi/kernels/tril_indices_kernel.h" +#include "paddle/phi/kernels/tril_triu_kernel.h" +#include "paddle/phi/kernels/triu_indices_kernel.h" +#include "paddle/phi/kernels/trunc_kernel.h" +#include "paddle/phi/kernels/truncated_gaussian_random_kernel.h" +#include "paddle/phi/kernels/unbind_kernel.h" +#include "paddle/phi/kernels/unfold_kernel.h" +#include "paddle/phi/kernels/uniform_random_inplace_kernel.h" +#include "paddle/phi/kernels/uniform_random_kernel.h" +#include "paddle/phi/kernels/unique_consecutive_kernel.h" +#include "paddle/phi/kernels/unique_kernel.h" +#include "paddle/phi/kernels/unpool_kernel.h" +#include "paddle/phi/kernels/unsqueeze_kernel.h" +#include "paddle/phi/kernels/unstack_kernel.h" +#include "paddle/phi/kernels/viterbi_decode_kernel.h" +#include "paddle/phi/kernels/warpctc_kernel.h" +#include "paddle/phi/kernels/where_index_kernel.h" +#include "paddle/phi/kernels/where_kernel.h" +#include "paddle/phi/kernels/yolo_box_kernel.h" +#include "paddle/phi/kernels/yolov3_loss_kernel.h" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/backward.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/backward.h new file mode 100644 index 0000000000000000000000000000000000000000..3e7cfa3ad83810c5fe8770ff57339e0efe78e95c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/backward.h @@ -0,0 +1,407 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/infermeta/binary.h" +#include "paddle/phi/infermeta/multiary.h" +#include "paddle/phi/infermeta/ternary.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +// Common InferMeta Functions for backward operators. +// +// NOTE: The InferMeta Functions in this file are arranged in alphabetic order. + +void AffineGridGradInferMeta(const MetaTensor& output_grad, + const IntArray& outputShape, + bool align_corners, + MetaTensor* input_grad); + +void AngleGradInferMeta(const MetaTensor& x, + const MetaTensor& out_grad, + MetaTensor* x_grad); + +void BilinearTensorProductGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& weight, + const MetaTensor& dout, + MetaTensor* dx, + MetaTensor* dy, + MetaTensor* dweight, + MetaTensor* dbias); + +void BmmGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& out_grad, + MetaTensor* x_grad, + MetaTensor* y_grad); + +void ChannelShuffleGradInferMeta(const MetaTensor& out_grad, + int groups, + const std::string& data_format, + MetaTensor* x_grad); + +void ComplexGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& dout, + MetaTensor* dx, + MetaTensor* dy); + +void ConvTransposeGradInferMeta(const MetaTensor& x, + const MetaTensor& filter, + const MetaTensor& dout, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const std::vector& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* dx, + MetaTensor* dfilter); + +void Conv2dTransposeGradInferMeta(const MetaTensor& x, + const MetaTensor& filter, + const MetaTensor& dout, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* dx, + MetaTensor* dfilter); + +void Conv2dTransposeDoubleGradInferMeta(const MetaTensor& x, + const MetaTensor& filter, + const MetaTensor& dout, + const MetaTensor& ddx, + const MetaTensor& ddfilter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* dx, + MetaTensor* dfilter, + MetaTensor* ddout); + +void CropTensorGradInferMeta(const MetaTensor& out_grad, + const MetaTensor& x, + const IntArray& offsets, + MetaTensor* x_grad); + +void CrossEntropyWithSoftmaxGradInferMeta(const MetaTensor& label, + const MetaTensor& softmax, + const MetaTensor& loss_grad, + bool soft_label, + bool use_softmax, + bool numeric_stable_mode, + int ignore_index, + int axis, + MetaTensor* logits_grad, + MetaConfig config = MetaConfig()); + +void DeformableConvGradInferMeta(const MetaTensor& x, + const MetaTensor& offset, + const MetaTensor& filter, + const MetaTensor& mask, + const MetaTensor& out_grad, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + int deformable_groups, + int groups, + int im2col_step, + MetaTensor* dx, + MetaTensor* offset_grad, + MetaTensor* filter_grad, + MetaTensor* mask_grad); + +void EigGradInferMeta(const MetaTensor& out_w, + const MetaTensor& out_v, + const MetaTensor& dout_w, + const MetaTensor& dout_v, + MetaTensor* dx); + +void EigvalshGradInferMeta(const MetaTensor& out_v, + const MetaTensor& out_w_grad, + const std::string& uplo, + bool is_test, + MetaTensor* x_grad); + +void FFTC2RGradInferMeta(const MetaTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + int64_t last_dim_size, + MetaTensor* out, + MetaConfig = MetaConfig()); + +void FillDiagonalGradInferMeta( + const MetaTensor& dout, float value, int offset, bool wrap, MetaTensor* dx); + +void FillDiagonalTensorGradInferMeta(const MetaTensor& out_grad, + int64_t offset, + int dim1, + int dim2, + MetaTensor* x_grad); + +void GatherNdGradInferMeta(const MetaTensor& x, + const MetaTensor& index, + const MetaTensor& out_grad, + MetaTensor* x_grad); + +void GeneralUnaryGradInferMeta(const MetaTensor& x, MetaTensor* dx); + +void GeneralBinaryGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* dx, + MetaTensor* dy); + +void GeneralTernaryGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& z, + MetaTensor* dx, + MetaTensor* dy, + MetaTensor* dz); + +void GeneralQuaternaryGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& z, + const MetaTensor& k, + MetaTensor* dx, + MetaTensor* dy, + MetaTensor* dz, + MetaTensor* dk); + +void GeneralQuinaryGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& z, + const MetaTensor& k, + const MetaTensor& l, + MetaTensor* dx, + MetaTensor* dy, + MetaTensor* dz, + MetaTensor* dk, + MetaTensor* dl); + +void GumbelSoftmaxGradInferMeta(const MetaTensor& out, + const MetaTensor& dout, + int axis, + MetaTensor* dx); + +void InstanceNormGradInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& saved_mean, + const MetaTensor& saved_variance, + const MetaTensor& y_grad, + float epsilon, + MetaTensor* x_grad, + MetaTensor* scale_grad, + MetaTensor* bias_grad); + +void InstanceNormDoubleGradInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& saved_mean, + const MetaTensor& saved_variance, + const MetaTensor& dy, + const MetaTensor& ddx, + const MetaTensor& ddscale, + const MetaTensor& ddbias, + float epsilon, + MetaTensor* dx, + MetaTensor* dscale, + MetaTensor* ddy); + +void InverseGradInferMeta(const MetaTensor& out, + const MetaTensor& dout, + MetaTensor* dx); + +void KernelWithXShapeInferMeta(const MetaTensor& xshape, MetaTensor* dx); + +void LUGradInferMeta(const MetaTensor& x, + const MetaTensor& out, + const MetaTensor& pivots, + const MetaTensor& out_grad, + bool pivot, + MetaTensor* x_grad); + +void LUUnpackGradInferMeta(const MetaTensor& x, + const MetaTensor& pivots, + const MetaTensor& l, + const MetaTensor& u, + const MetaTensor& pmat, + const MetaTensor& l_grad, + const MetaTensor& u_grad, + bool unpack_ludata, + bool unpack_pivots, + MetaTensor* x_grad); + +void MarginCrossEntropyGradInferMeta(const MetaTensor& logits, + const MetaTensor& label, + const MetaTensor& softmax, + const MetaTensor& loss_grad, + bool return_softmax, + int ring_id, + int rank, + int nranks, + float margin1, + float margin2, + float margin3, + float scale, + MetaTensor* logits_grad); + +void MaxPoolWithIndexGradInferMeta(const MetaTensor& x, + const MetaTensor& mask, + const MetaTensor& dout, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + MetaTensor* dx); + +void MeshgridGradInferMeta(const std::vector& inputs, + const std::vector& outputs_grad, + std::vector inputs_grad); + +void MultiDotGradInferMeta(const std::vector& x, + const MetaTensor& out_grad, + std::vector x_grad); + +void MultiplexGradInferMeta(const MetaTensor& ids, + const MetaTensor& out_grad, + std::vector ins_grad); + +void NanmedianGradInferMeta(const MetaTensor& x, + const MetaTensor& median_index, + const MetaTensor& out_grad, + const IntArray& axes, + bool keep_dim, + MetaTensor* x_grad); + +void NllLossGradInferMeta(const MetaTensor& input, + const MetaTensor& label, + const MetaTensor& weight, + const MetaTensor& total_weight, + const MetaTensor& out_grad, + int64_t ignore_index, + const std::string& reduction, + MetaTensor* intput_grad, + MetaConfig config = MetaConfig()); + +void PixelUnshuffleGradInferMeta(const MetaTensor& out_grad, + int downscale_factor, + const std::string& data_format, + MetaTensor* x_grad); + +void OverlapAddGradInferMeta(const MetaTensor& x, + const MetaTensor& out_grad, + int hop_length, + int axis, + MetaTensor* x_grad); + +void PsroiPoolGradInferMeta(const MetaTensor& x, + const MetaTensor& rois, + const MetaTensor& rois_num, + const MetaTensor& dout, + int pooled_height, + int pooled_width, + int output_channels, + float spatial_scale, + MetaTensor* dx); + +void RealAndImagGradInferMeta(const MetaTensor& out_grad, MetaTensor* dx); + +void ReshapeDoubleGradInferMeta(const MetaTensor& out_grad, + const MetaTensor& x_grad_grad, + MetaTensor* out_grad_grad); + +void ScatterGradInferMeta(const MetaTensor& index, + const MetaTensor& updates, + const MetaTensor& out_grad, + bool overwrite, + MetaTensor* x_grad, + MetaTensor* updates_grad); + +void ScatterNdAddGradInferMeta(const MetaTensor& index, + const MetaTensor& updates, + const MetaTensor& out_grad, + MetaTensor* x_grad, + MetaTensor* updates_grad); + +void SpectralNormGradInferMeta(const MetaTensor& weight, + const MetaTensor& u, + const MetaTensor& v, + const MetaTensor& out_grad, + int dim, + int power_iters, + float eps, + MetaTensor* weight_grad); + +void StackGradInferMeta(const MetaTensor& out_grad, + int axis, + std::vector x_grad); + +void UniformRandomInplaceGradInferMeta(const MetaTensor& out_grad, + float min, + float max, + int seed, + int diag_num, + int diag_step, + float diag_val, + MetaTensor* x_grad); + +void UnStackGradInferMeta(const std::vector& out_grad, + int axis, + MetaTensor* x_grad); + +void Yolov3LossGradInferMeta(const MetaTensor& x, + const MetaTensor& gt_box, + const MetaTensor& gt_label, + const MetaTensor& gt_score, + const MetaTensor& objectness_mask, + const MetaTensor& gt_match_mask, + const MetaTensor& loss_grad, + const std::vector& anchors, + const std::vector& anchor_mask, + int class_num, + float ignore_thresh, + int downsample_ratio, + bool use_label_smooth, + float scale_x_y, + MetaTensor* x_grad, + MetaTensor* gt_box_grad, + MetaTensor* gt_label_grad, + MetaTensor* gt_score_grad); + +void IndexAddGradInferMeta(const MetaTensor& index, + const MetaTensor& add_value, + const MetaTensor& out_grad, + int axis, + MetaTensor* x_grad, + MetaTensor* add_tensor_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/binary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/binary.h new file mode 100644 index 0000000000000000000000000000000000000000..59fedfe2550690de3e35b39cd1d0a9db1b4d5f81 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/binary.h @@ -0,0 +1,441 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/meta_tensor.h" + +namespace phi { + +// Common InferMeta Functions for binary operators, The format like: +// +// 1. void [FunctionDesc|OpName]InferMeta(const MetaTensor& x, +// const MetaTensor& y, +// ..., +// MetaTensor* out) {} +// +// NOTE: The name "InferShape" may be not appropriate. "InferMeta" may be good. +// Because functions in this file not only can infer shape, but also need +// infer lod or other useful data. +// +// The InferMeta Functions in this file are arranged in alphabetic order. + +void AllValueCompareInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void EmbeddingInferMeta(const MetaTensor& input, + const MetaTensor& weight, + int64_t padding_idx, + MetaTensor* out); + +void KLDivInferMeta(const MetaTensor& x, + const MetaTensor& label, + const std::string& reduction, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void Atan2InferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out); + +void BCELossInferMeta(const MetaTensor& input, + const MetaTensor& label, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void BincountInferMeta(const MetaTensor& x, + const MetaTensor& weights, + const Scalar& minlength, + MetaTensor* out); + +void BmmInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out); + +void CholeskySolveInferMeta(const MetaTensor& x, + const MetaTensor& y, + bool upper, + MetaTensor* out); + +void CompareAllInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out); + +void CompareInferMeta(const MetaTensor& x, + const MetaTensor& y, + int axis, + MetaTensor* out); + +void ComplexInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out); + +void ConvInferMeta(const MetaTensor& input, + const MetaTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ConvInferInferMeta(const MetaTensor& input, + const MetaTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ConvTransposeInferMeta(const MetaTensor& x, + const MetaTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const std::vector& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void Conv2dTransposeInferMeta(const MetaTensor& x, + const MetaTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void CrossInferMeta(const MetaTensor& x, + const MetaTensor& y, + int axis, + MetaTensor* out); + +void CrossEntropyWithSoftmaxInferMeta(const MetaTensor& logits, + const MetaTensor& label, + bool soft_label, + bool use_softmax, + bool numeric_stable_mode, + int ignore_index, + int axis, + MetaTensor* softmax, + MetaTensor* loss, + MetaConfig config = MetaConfig()); + +void DistInferMeta(const MetaTensor& x, + const MetaTensor& y, + float p, + MetaTensor* out); + +void DistributeFpnProposalsInferMeta( + const MetaTensor& fpn_rois, + const MetaTensor& rois_num, + int min_level, + int max_level, + int refer_level, + int refer_scale, + bool pixel_offset, + std::vector multi_fpn_rois, + std::vector multi_level_rois_num, + MetaTensor* restore_index, + MetaConfig config = MetaConfig()); + +void DotInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out); + +void DropoutInferMeta(const MetaTensor& x, + const MetaTensor& seed_tensor, + const Scalar& p, + bool is_test, + const std::string& mode, + int seed, + bool fix_seed, + MetaTensor* out, + MetaTensor* mask); + +void DropoutNdInferMeta(const MetaTensor& x, + const MetaTensor& seed_tensor, + const Scalar& p, + bool is_test, + const std::string& mode, + int seed, + bool fix_seed, + const std::vector& axis, + MetaTensor* out, + MetaTensor* mask); + +void ElementwiseInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out); + +void ElementwiseRawInferMeta(const MetaTensor& x_meta, + const MetaTensor& y_meta, + int axis, + MetaTensor* out); + +void EmbeddingInferMeta(const MetaTensor& x, + const MetaTensor& weight, + int64_t padding_idx, + bool sparse, + MetaTensor* out); + +void ExpandAsInferMeta(const MetaTensor& x, + const MetaTensor& y, + const std::vector& target_shape, + MetaTensor* out); + +void FillDiagonalTensorInferMeta(const MetaTensor& x, + const MetaTensor& y, + int64_t offset, + int dim1, + int dim2, + MetaTensor* out); + +void GatherInferMeta(const MetaTensor& x, + const MetaTensor& index, + const Scalar& axis, + MetaTensor* out); + +void GatherNdInferMeta(const MetaTensor& x, + const MetaTensor& index, + MetaTensor* out); + +void GatherTreeMeta(const MetaTensor& ids, + const MetaTensor& parents, + MetaTensor* out); + +void GridSampleBaseInferMeta(const MetaTensor& x, + const MetaTensor& grid, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void HuberLossInferMeta(const MetaTensor& input_meta, + const MetaTensor& label_meta, + float delta, + MetaTensor* out, + MetaTensor* residual, + MetaConfig config = MetaConfig()); + +void IndexSampleInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void IndexSelectInferMeta(const MetaTensor& x, + const MetaTensor& index, + int dim, + MetaTensor* output); + +void IndexAddInferMeta(const MetaTensor& x, + const MetaTensor& index, + const MetaTensor& add_value, + int axis, + MetaTensor* output); + +void KronInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out); + +void LogLossInferMeta(const MetaTensor& input, + const MetaTensor& label, + float epsilon, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void LUUnpackInferMeta(const MetaTensor& x, + const MetaTensor& pivots, + bool unpack_ludata, + bool unpack_pivots, + MetaTensor* pmat, + MetaTensor* l, + MetaTensor* u); + +void MarginCrossEntropyInferMeta(const MetaTensor& logits, + const MetaTensor& label, + bool return_softmax, + int ring_id, + int rank, + int nranks, + float margin1, + float margin2, + float margin3, + float scale, + MetaTensor* softmax, + MetaTensor* loss, + MetaConfig config = MetaConfig()); + +void MaskedSelectInferMeta(const MetaTensor& x, + const MetaTensor& mask, + MetaTensor* out); + +void MatmulInferMeta(const MetaTensor& x, + const MetaTensor& y, + bool trans_x, + bool trans_y, + MetaTensor* out); + +void MatmulWithFlattenInferMeta(const MetaTensor& x, + const MetaTensor& y, + int x_num_col_dims, + int y_num_col_dims, + MetaTensor* out); + +void MatrixNMSInferMeta(const MetaTensor& bboxes, + const MetaTensor& scores, + float score_threshold, + int nms_top_k, + int keep_top_k, + float post_threshold, + bool use_gaussian, + float gaussian_sigma, + int background_label, + bool normalized, + MetaTensor* out, + MetaTensor* index, + MetaTensor* roisnum, + MetaConfig config = MetaConfig()); + +void MatrixRankTolInferMeta(const MetaTensor& x, + const MetaTensor& atol_tensor, + bool use_default_tol, + bool hermitian, + MetaTensor* out); + +void MvInferMeta(const MetaTensor& x, const MetaTensor& vec, MetaTensor* out); + +void PReluInferMeta(const MetaTensor& x, + const MetaTensor& alpha, + const std::string& data_format, + const std::string& mode, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void RepeatInterleaveWithTensorIndexInferMeta(const MetaTensor& x, + const MetaTensor& repeats, + int dim, + MetaTensor* out); +void PriorBoxInferMeta(const MetaTensor& input, + const MetaTensor& image, + const std::vector& min_sizes, + const std::vector& aspect_ratios, + const std::vector& variances, + const std::vector& max_sizes, + bool flip, + bool clip, + float step_w, + float step_h, + float offset, + bool min_max_aspect_ratios_order, + MetaTensor* out, + MetaTensor* var); + +void SearchsortedInferMeta(const MetaTensor& sorted_sequence, + const MetaTensor& value, + bool out_int32, + bool right, + MetaTensor* out); + +void SoftmaxMaskFuseInferMeta(const MetaTensor& x, + const MetaTensor& mask, + MetaTensor* out); + +void SegmentPoolInferMeta(const MetaTensor& x, + const MetaTensor& segment_ids, + const std::string& pooltype, + MetaTensor* out, + MetaTensor* summed_ids, + MetaConfig config = MetaConfig()); + +void SigmoidCrossEntropyWithLogitsInferMeta(const MetaTensor& x, + const MetaTensor& label, + bool normalize, + int ignore_index, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void TakeAlongAxisInferMeta(const MetaTensor& x, + const MetaTensor& index, + int axis, + MetaTensor* out); + +void TriangularSolveInferMeta(const MetaTensor& x, + const MetaTensor& y, + bool upper, + bool transpose, + bool unitriangular, + MetaTensor* out); + +void LstsqInferMeta(const MetaTensor& x, + const MetaTensor& y, + const Scalar& rcond, + const std::string& driver, + MetaTensor* solution, + MetaTensor* residuals, + MetaTensor* rank, + MetaTensor* singular_values); + +void YoloBoxInferMeta(const MetaTensor& x, + const MetaTensor& img_size, + const std::vector& anchors, + int class_num, + float conf_thresh, + int downsample_ratio, + bool clip_bbox, + float scale_x_y, + bool iou_aware, + float iou_aware_factor, + MetaTensor* boxes, + MetaTensor* scores, + MetaConfig config = MetaConfig()); + +void ValueCompareInferMeta(const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SolveInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out); + +void UnpoolInferMeta(const MetaTensor& x, + const MetaTensor& indices, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const IntArray& output_size, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void Unpool3dInferMeta(const MetaTensor& x, + const MetaTensor& indices, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_size, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/generated.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/generated.h new file mode 100644 index 0000000000000000000000000000000000000000..c1b491e1e2db65b413f415bae7a66da98aa1d88d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/generated.h @@ -0,0 +1,85 @@ +#pragma once + +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/common/int_array.h" + +namespace phi { + +void AllcloseInferMeta(const MetaTensor& x, const MetaTensor& y, const Scalar& rtol, const Scalar& atol, bool equal_nan, MetaTensor* out); + +void Assign_valueInferMeta(const std::vector& shape, DataType dtype, const std::vector& values, MetaTensor* out); + +void BreluInferMeta(const MetaTensor& x, float t_min, float t_max, MetaTensor* out); + +void CeluInferMeta(const MetaTensor& x, float alpha, MetaTensor* out); + +void ClipInferMeta(const MetaTensor& x, const Scalar& min, const Scalar& max, MetaTensor* out); + +void CumprodInferMeta(const MetaTensor& x, int dim, MetaTensor* out); + +void Depthwise_conv2dInferMeta(const MetaTensor& x, const MetaTensor& filter, const std::vector& strides, const std::vector& paddings, const std::string& padding_algorithm, int groups, const std::vector& dilations, const std::string& data_format, bool use_addto, int workspace_size_MB, bool exhaustive_search, bool fuse_relu, MetaTensor* out); + +void EluInferMeta(const MetaTensor& x, float alpha, MetaTensor* out); + +void ExponentialInferMeta(const MetaTensor& x, float lambda, MetaTensor* out); + +void FillInferMeta(const MetaTensor& x, const Scalar& value, MetaTensor* out); + +void FmaxInferMeta(const MetaTensor& x, const MetaTensor& y, int axis, MetaTensor* out); + +void FminInferMeta(const MetaTensor& x, const MetaTensor& y, int axis, MetaTensor* out); + +void FullInferMeta(const IntArray& shape, const Scalar& value, DataType dtype, MetaTensor* out); + +void Full_likeInferMeta(const MetaTensor& x, const Scalar& value, DataType dtype, MetaTensor* out); + +void GeluInferMeta(const MetaTensor& x, bool approximate, MetaTensor* out); + +void Grid_sampleInferMeta(const MetaTensor& x, const MetaTensor& grid, const std::string& mode, const std::string& padding_mode, bool align_corners, MetaTensor* out); + +void Hard_shrinkInferMeta(const MetaTensor& x, float threshold, MetaTensor* out); + +void Hard_sigmoidInferMeta(const MetaTensor& x, float slope, float offset, MetaTensor* out); + +void Hard_swishInferMeta(const MetaTensor& x, float threshold, float scale, float offset, MetaTensor* out); + +void IscloseInferMeta(const MetaTensor& x, const MetaTensor& y, const Scalar& rtol, const Scalar& atol, bool equal_nan, MetaTensor* out); + +void Label_smoothInferMeta(const MetaTensor& label, const MetaTensor& prior_dist, float epsilon, MetaTensor* out); + +void Leaky_reluInferMeta(const MetaTensor& x, float alpha, MetaTensor* out); + +void LogitInferMeta(const MetaTensor& x, float eps, MetaTensor* out); + +void Matrix_powerInferMeta(const MetaTensor& x, int n, MetaTensor* out); + +void Matrix_rankInferMeta(const MetaTensor& x, float tol, bool use_default_tol, bool hermitian, MetaTensor* out); + +void MishInferMeta(const MetaTensor& x, float lambda, MetaTensor* out); + +void PowInferMeta(const MetaTensor& x, const Scalar& s, MetaTensor* out); + +void Put_along_axisInferMeta(const MetaTensor& x, const MetaTensor& index, const MetaTensor& value, int axis, const std::string& reduce, MetaTensor* out); + +void Relu6InferMeta(const MetaTensor& x, float threshold, MetaTensor* out); + +void RenormInferMeta(const MetaTensor& x, float p, int axis, float max_norm, MetaTensor* out); + +void ScaleInferMeta(const MetaTensor& x, const Scalar& scale, float bias, bool bias_after_scale, MetaTensor* out); + +void SeluInferMeta(const MetaTensor& x, float scale, float alpha, MetaTensor* out); + +void Soft_shrinkInferMeta(const MetaTensor& x, float lambda, MetaTensor* out); + +void SoftplusInferMeta(const MetaTensor& x, float beta, float threshold, MetaTensor* out); + +void SwishInferMeta(const MetaTensor& x, float beta, MetaTensor* out); + +void Take_along_axisInferMeta(const MetaTensor& x, const MetaTensor& index, int axis, MetaTensor* out); + +void Thresholded_reluInferMeta(const MetaTensor& x, float threshold, MetaTensor* out); + +void Uniform_randomInferMeta(const IntArray& shape, DataType dtype, const Scalar& min, const Scalar& max, int seed, MetaTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/multiary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/multiary.h new file mode 100644 index 0000000000000000000000000000000000000000..8c601182e8fc84877796c464fb31fc64a4a69f98 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/multiary.h @@ -0,0 +1,521 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/meta_tensor.h" +namespace phi { + +// Common InferMeta Functions for multiary operators, The format like: +// +// 1. The number of input MetaTensor is more than 3: +// void [FunctionDesc|OpName]InferMeta(const MetaTensor& x, +// const MetaTensor& y, +// const MetaTensor& z, +// const MetaTensor& w, +// ..., +// MetaTensor* out) {} +// +// 2. There are `const vector&` in params: +// void [FunctionDesc|OpName]InferMeta(const vector& x, +// ..., +// MetaTensor* out) {} +// +// NOTE: The InferMeta Functions in this file are arranged in alphabetic order. + +std::vector GetMetaTensorsDim( + const std::vector& tensors); + +void AdadeltaInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& avg_squared_grad, + const MetaTensor& avg_squared_update, + float rho, + float epsilon, + MetaTensor* param_out, + MetaTensor* avg_squared_grad_out, + MetaTensor* avg_squared_update_out); + +void AdagradInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& moment, + const MetaTensor& learning_rate, + float epsilon, + MetaTensor* param_out, + MetaTensor* moment_out); + +void AdamaxInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& learning_rate, + const MetaTensor& moment, + const MetaTensor& inf_norm, + const MetaTensor& beta1_pow, + float beta1, + float beta2, + float epsilon, + MetaTensor* param_out, + MetaTensor* moment_out, + MetaTensor* inf_norm_out); + +void AdamInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& learning_rate, + const MetaTensor& moment1, + const MetaTensor& moment2, + const MetaTensor& beta1_pow, + const MetaTensor& beta2_pow, + const MetaTensor& master_param, + const MetaTensor& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + MetaTensor* param_out, + MetaTensor* moment1_out, + MetaTensor* moment2_out, + MetaTensor* beta1_pow_out, + MetaTensor* beta2_pow_out, + MetaTensor* master_param_outs); + +void AdamwInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& learning_rate, + const MetaTensor& moment1, + const MetaTensor& moment2, + const MetaTensor& beta1_pow, + const MetaTensor& beta2_pow, + const MetaTensor& master_param, + const MetaTensor& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + float lr_ratio, + float coeff, + bool with_decay, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + MetaTensor* param_out, + MetaTensor* moment1_out, + MetaTensor* moment2_out, + MetaTensor* beta1_pow_out, + MetaTensor* beta2_pow_out, + MetaTensor* master_param_outs); + +void AddNInferMeta(const std::vector& x, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void AddNTensorArrayInferMeta(const std::vector& x, + MetaTensor* out, + MetaConfig config); + +void AucInferMeta(const MetaTensor& input, + const MetaTensor& label, + const MetaTensor& stat_pos, + const MetaTensor& stat_neg, + const MetaTensor& ins_tag_weight, + const std::string& curve, + int num_thresholds, + int slide_steps, + MetaTensor* auc, + MetaTensor* stat_pos_out, + MetaTensor* stat_neg_out, + MetaConfig config = MetaConfig()); + +void AverageAccumulatesInferMeta(const MetaTensor& param, + const MetaTensor& in_sum_1, + const MetaTensor& in_sum_2, + const MetaTensor& in_sum_3, + const MetaTensor& in_num_accumulates, + const MetaTensor& in_old_num_accumulates, + const MetaTensor& in_num_updates, + float average_window, + int64_t max_average_window, + int64_t min_average_window, + MetaTensor* out_sum_1, + MetaTensor* out_sum_2, + MetaTensor* out_sum_3, + MetaTensor* out_num_accumulates, + MetaTensor* out_old_num_accumulates, + MetaTensor* out_num_updates); + +void BatchNormInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& bias, + const MetaTensor& mean, + const MetaTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + MetaTensor* y, + MetaTensor* mean_out, + MetaTensor* variance_out, + MetaTensor* saved_mean, + MetaTensor* saved_variance, + MetaTensor* reserve_space, + MetaConfig config = MetaConfig()); + +void BatchNormInferInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& bias, + const MetaTensor& mean, + const MetaTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + MetaTensor* y, + MetaTensor* mean_out, + MetaTensor* variance_out, + MetaConfig config = MetaConfig()); + +void BilinearTensorProductInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& weight, + const MetaTensor& bias, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void BroadcastTensorsInferMeta(const std::vector& x, + std::vector out); + +void CheckFiniteAndUnscaleInferMeta(const std::vector& xs, + const MetaTensor& scale, + std::vector outs, + MetaTensor* found_infinite); + +void CoalesceTensorInferMeta(const std::vector& input, + DataType dtype, + bool copy_data, + bool set_constant, + bool persist_output, + float constant, + bool use_align, + int align_size, + int size_of_dtype, + const std::vector& concated_shapes, + const std::vector& concated_ranks, + std::vector output, + MetaTensor* fused_output, + MetaConfig config = MetaConfig()); + +void ConcatInferMeta(const std::vector& x, + const Scalar& axis_scalar, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void DeformableConvInferMeta(const MetaTensor& x, + const MetaTensor& offset, + const MetaTensor& filter, + const MetaTensor& mask, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + int deformable_groups, + int groups, + int im2col_step, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void EditDistanceInferMeta(const MetaTensor& hyps, + const MetaTensor& refs, + const MetaTensor& hypslength, + const MetaTensor& refslength, + bool normalized, + MetaTensor* sequencenum, + MetaTensor* out); + +void GenerateProposalsV2InferMeta(const MetaTensor& scores, + const MetaTensor& bbox_deltas, + const MetaTensor& im_shape, + const MetaTensor& anchors, + const MetaTensor& variances, + int pre_nms_top_n, + int post_nms_top_n, + float nms_thresh, + float min_size, + float eta, + bool pixel_offset, + MetaTensor* rpn_rois, + MetaTensor* rpn_roi_probs, + MetaTensor* rpn_rois_num); + +void GraphReindexInferMeta(const MetaTensor& x, + const MetaTensor& neighbors, + const MetaTensor& count, + const MetaTensor& hashtable_value, + const MetaTensor& hashtable_index, + bool flag_buffer_hashtable, + MetaTensor* reindex_src, + MetaTensor* reindex_dst, + MetaTensor* out_nodes); + +void GraphSampleNeighborsInferMeta(const MetaTensor& row, + const MetaTensor& col_ptr, + const MetaTensor& x, + const MetaTensor& eids, + const MetaTensor& perm_buffer, + int sample_size, + bool return_eids, + bool flag_perm_buffer, + MetaTensor* out, + MetaTensor* out_count, + MetaTensor* out_eids); + +void HierarchicalSigmoidInferMeta(const MetaTensor& x, + const MetaTensor& w, + const MetaTensor& label, + const MetaTensor& path, + const MetaTensor& code, + const MetaTensor& bias, + int num_classes, + bool remote_prefetch, + int trainer_id, + const std::vector& height_sections, + const std::vector& epmap, + const std::vector& table_names, + bool is_sparse, + MetaTensor* out, + MetaTensor* pre_out, + MetaTensor* w_out); + +void InterpolateInferMeta( + const MetaTensor& x, + const MetaTensor& out_size, + const paddle::optional>& size_tensor, + const MetaTensor& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + MetaTensor* output, + MetaConfig config = MetaConfig()); + +void LambInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& learning_rate, + const MetaTensor& moment1, + const MetaTensor& moment2, + const MetaTensor& beta1_pow, + const MetaTensor& beta2_pow, + const MetaTensor& master_param, + const MetaTensor& skip_update, + float weight_decay, + float beta1, + float beta2, + float epsilon, + bool multi_precision, + MetaTensor* param_out, + MetaTensor* moment1_out, + MetaTensor* moment2_out, + MetaTensor* beta1_pow_out, + MetaTensor* beta2_pow_out, + MetaTensor* master_param_outs); + +void LogspaceInferMeta(const MetaTensor& start, + const MetaTensor& stop, + const MetaTensor& number, + const MetaTensor& base, + MetaTensor* out); + +void MergedAdamInferMeta( + const std::vector& param, + const std::vector& grad, + const std::vector& learning_rate, + const std::vector& moment1, + const std::vector& moment2, + const std::vector& beta1_pow, + const std::vector& beta2_pow, + const paddle::optional>& master_param, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + bool multi_precision, + bool use_global_beta_pow, + std::vector param_out, + std::vector moment1_out, + std::vector moment2_out, + std::vector beta1_pow_out, + std::vector beta2_pow_out, + std::vector master_param_out); + +void MergedMomentumInferMeta( + const std::vector& param, + const std::vector& grad, + const std::vector& velocity, + const std::vector& learning_rate, + const paddle::optional>& master_param, + float mu, + bool use_nesterov, + const std::vector& regularization_method, + const std::vector& regularization_coeff, + bool multi_precision, + float rescale_grad, + std::vector param_out, + std::vector velocity_out, + std::vector master_param_out); + +void MeshgridInferMeta(const std::vector& inputs, + std::vector outputs); + +void MomentumInferMeta(const MetaTensor& param, + const MetaTensor& grad, + const MetaTensor& velocity, + const MetaTensor& learning_rate, + const MetaTensor& master_param, + float mu, + bool use_nesterov, + const std::string& regularization_method, + float regularization_coeff, + bool multi_precision, + float rescale_grad, + MetaTensor* param_out, + MetaTensor* velocity_out, + MetaTensor* master_param_out); + +void MultiDotInferMeta(const std::vector& x, + MetaTensor* out); + +void MultiplexInferMeta(const std::vector& ins, + const MetaTensor& ids, + MetaTensor* out); + +void PsroiPoolInferMeta(const MetaTensor& x, + const MetaTensor& rois, + const MetaTensor& rois_num, + int pooled_height, + int pooled_width, + int output_channels, + float spatial_scale, + MetaTensor* out); + +void RmspropInferMeta(const MetaTensor& param, + const MetaTensor& mean_square, + const MetaTensor& grad, + const MetaTensor& moment, + const MetaTensor& learning_rate, + const MetaTensor& mean_grad, + float epsilon, + float decay, + float momentum, + bool centered, + MetaTensor* param_out, + MetaTensor* moment_out, + MetaTensor* mean_square_out, + MetaTensor* mean_grad_out); + +void RnnInferMeta(const MetaTensor& x, + const std::vector& pre_state, + const std::vector& weight_list, + const MetaTensor& sequence_length, + float dropout_prob, + bool is_bidirec, + int input_size, + int hidden_size, + int num_layers, + const std::string& mode, + int seed, + bool is_test, + MetaTensor* out, + MetaTensor* dropout_state, + std::vector state, + MetaTensor* reserve); + +void SgdInferMeta(const MetaTensor& param, + const MetaTensor& learning_rate, + const MetaTensor& grad, + const MetaTensor& master_param, + bool multi_precision, + MetaTensor* param_out, + MetaTensor* master_param_out); + +void StackInferMeta(const std::vector& x, + int axis, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void UnchangedMultiInferMeta(const std::vector& x, + std::vector out); + +void UpdateLossScalingInferMeta(const std::vector& xs, + const MetaTensor& found_infinite, + const MetaTensor& prev_loss_scaling, + const MetaTensor& in_good_steps, + const MetaTensor& in_bad_steps, + std::vector outs, + MetaTensor* loss_scaling, + MetaTensor* out_good_steps, + MetaTensor* out_bad_steps); + +void WarpctcInferMeta(const MetaTensor& logits, + const MetaTensor& label, + const MetaTensor& logits_length, + const MetaTensor& labels_length, + int blank, + bool norm_by_times, + MetaTensor* warpctcgrad, + MetaTensor* loss); + +void WhereInferMeta(const MetaTensor& condition, + const MetaTensor& x, + const MetaTensor& y, + MetaTensor* out); + +void Yolov3LossInferMeta(const MetaTensor& x, + const MetaTensor& gt_box, + const MetaTensor& gt_label, + const MetaTensor& gt_score, + const std::vector& anchors, + const std::vector& anchor_mask, + int class_num, + float ignore_thresh, + int downsample_ratio, + bool use_label_smooth, + float scale_x_y, + MetaTensor* loss, + MetaTensor* objectness_mask, + MetaTensor* gt_match_mask); + +void GraphSendUERecvInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& src_index, + const MetaTensor& dst_index, + const std::string& message_op, + const std::string& reduce_op, + const IntArray& out_size, + MetaTensor* out, + MetaTensor* dst_count); + +void GraphSendUVInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& src_index, + const MetaTensor& dst_index, + const std::string& message_op, + MetaTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/nullary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/nullary.h new file mode 100644 index 0000000000000000000000000000000000000000..27c89821a319e885ce237056b6391b27b9410086 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/nullary.h @@ -0,0 +1,79 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/meta_tensor.h" + +namespace phi { + +// Common InferMeta Functions for 0-nary operators(no input tensor), The format +// like: +// +// 1. void [FunctionDesc|OpName]InferMeta(..., MetaTensor* out) +// +// NOTE: The name "InferShape" may be not appropriate. "InferMeta" may be good. +// Because functions in this file not only can infer shape, but also need +// infer lod or other useful data. +// +// The InferMeta Functions in this file are arranged in alphabetic order. + +void AssignValueInferMeta(const std::vector& shape, + DataType dtype, + MetaTensor* out); + +void CreateInferMeta(const IntArray& shape, DataType dtype, MetaTensor* out); + +void CreateInferMetaBase(const std::vector& shape, + DataType dtype, + DataLayout layout, + MetaTensor* out); + +void EyeInferMeta(const Scalar& num_rows, + const Scalar& num_columns, + DataType dtype, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void GaussianRandomInferMeta(const IntArray& shape, + float mean, + float std, + int seed, + DataType dtype, + MetaTensor* out); + +void RandpermInferMeta(int n, DataType dtype, MetaTensor* out); + +void RandintInferMeta( + int low, int high, const IntArray& shape, DataType dtype, MetaTensor* out); + +void TruncatedGaussianRandomInferMeta(const std::vector& shape, + float mean, + float std, + int seed, + DataType dtype, + MetaTensor* out); + +void UniformRandomInferMeta(const IntArray& shape, + DataType dtype, + MetaTensor* out); + +void TrilIndicesInferMeta( + int rows, int cols, int offset, DataType dtype, MetaTensor* out); + +void TriuIndicesInferMeta( + int row, int col, int offset, DataType dtype, MetaTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/backward.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/backward.h new file mode 100644 index 0000000000000000000000000000000000000000..e5c797923dfbc53c60ed00738d37324108731a6c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/backward.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +namespace sparse { + +void FusedAttentionGradInferMeta(const MetaTensor& query, + const MetaTensor& key, + const MetaTensor& value, + const MetaTensor& softmax, + const MetaTensor& out_grad, + MetaTensor* query_grad, + MetaTensor* key_grad, + MetaTensor* value_grad); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/binary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/binary.h new file mode 100644 index 0000000000000000000000000000000000000000..a2c3e6fe5705c51ed2b76cfd31fa43cb61eec829 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/binary.h @@ -0,0 +1,52 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/infermeta_utils.h" +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +namespace sparse { + +void Conv3dInferMeta(const MetaTensor& x, + const MetaTensor& kernel, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + const int groups, + const bool subm, + const std::string& key, + MetaTensor* out, + MetaTensor* rulebook, + MetaTensor* counter); + +void Pool3dInferMeta(const MetaTensor& x, + const std::vector& kernel_sizes, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + MetaTensor* out, + MetaTensor* rulebook, + MetaTensor* counter); + +void SparseCooTensorInferMeta(const MetaTensor& values, + const MetaTensor& indices, + const std::vector& shape, + MetaTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/multiary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/multiary.h new file mode 100644 index 0000000000000000000000000000000000000000..20070e2cd9d63b5da7e606261d6838282f9f7400 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/multiary.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/meta_tensor.h" + +namespace phi { +namespace sparse { + +void FusedAttentionInferMeta(const MetaTensor& query, + const MetaTensor& key, + const MetaTensor& value, + const MetaTensor& sparse_mask, + const MetaTensor& key_padding_mask, + const MetaTensor& attn_mask, + MetaTensor* out, + MetaTensor* softmax); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/unary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/unary.h new file mode 100644 index 0000000000000000000000000000000000000000..880e90b7ae697ffeb25cf7f74642c224798932bd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/sparse/unary.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +namespace sparse { + +void IndicesInferMeta(const MetaTensor& x, MetaTensor* out); + +void ValuesInferMeta(const MetaTensor& x, MetaTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/nullary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/nullary.h new file mode 100644 index 0000000000000000000000000000000000000000..8fbcc63b2ae5d7cd1128b9c67ec5ac7672ce8564 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/nullary.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +namespace strings { + +void CreateInferMeta(const std::vector& shape, MetaTensor* out); +void CreateInferMeta(const IntArray& shape, MetaTensor* out); + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/unary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/unary.h new file mode 100644 index 0000000000000000000000000000000000000000..13b94ec1ace78b6daf161ab6574494f78fa185ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/strings/unary.h @@ -0,0 +1,31 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +// See Note [ Why still include the fluid headers? ] +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/infermeta_utils.h" +#include "paddle/phi/core/meta_tensor.h" +#include "paddle/phi/core/tensor_meta.h" + +namespace phi { +namespace strings { +// Common InferMeta Functions of StringTensor for unary operators: +void UnchangedInferMeta(const StringTensorMeta& x_meta, MetaTensor* out); + +void CreateLikeInferMeta(const MetaTensor& x, MetaTensor* out); + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/ternary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/ternary.h new file mode 100644 index 0000000000000000000000000000000000000000..5314b8f45affee80e03e9e1c32d886799e4f701f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/ternary.h @@ -0,0 +1,206 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/meta_tensor.h" + +namespace phi { + +// Common InferMeta Functions for ternary operators, The format like: +// +// 1. void [FunctionDesc|OpName]InferMeta(const MetaTensor& x, +// const MetaTensor& y, +// const MetaTensor& z, +// ..., +// MetaTensor* out) {} +// +// NOTE: The name "InferShape" may be not appropriate. "InferMeta" may be good. +// Because functions in this file not only can infer shape, but also need +// infer lod or other useful data. +// +// The InferMeta Functions in this file are arranged in alphabetic order. + +void AccuracyInferMeta(const MetaTensor& out, + const MetaTensor& indice, + const MetaTensor& label, + MetaTensor* accuracy, + MetaTensor* correct, + MetaTensor* total, + MetaConfig config = MetaConfig()); + +void AddmmInferMeta(const MetaTensor& input, + const MetaTensor& x, + const MetaTensor& y, + float alpha, + float beta, + MetaTensor* out); + +void ArangeInferMeta(const MetaTensor& start, + const MetaTensor& end, + const MetaTensor& step, + MetaTensor* out); + +void BoxCoderInferMeta(const MetaTensor& prior_box, + const MetaTensor& prior_box_var, + const MetaTensor& target_box, + const std::string& code_type, + bool box_normalized, + int axis, + const std::vector& variance, + MetaTensor* output_box, + MetaConfig config = MetaConfig()); + +void InstanceNormInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& bias, + float epsilon, + MetaTensor* y, + MetaTensor* saved_mean, + MetaTensor* saved_variance, + MetaConfig config = MetaConfig()); + +void GraphSendRecvInferMeta(const MetaTensor& x, + const MetaTensor& src_index, + const MetaTensor& dst_index, + const std::string& reduce_op, + const IntArray& out_size, + MetaTensor* out, + MetaTensor* dst_count); + +void GroupNormInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& bias, + float epsilon, + int groups, + const std::string& data_layout, + MetaTensor* y, + MetaTensor* mean, + MetaTensor* variance); + +void LayerNormInferMeta(const MetaTensor& x, + const MetaTensor& scale, + const MetaTensor& bias, + float epsilon, + int begin_norm_axis, + bool is_test, + MetaTensor* out, + MetaTensor* mean, + MetaTensor* variance, + MetaConfig config = MetaConfig()); + +void LayerNormGradInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& z, + MetaTensor* dx, + MetaTensor* dy, + MetaTensor* dz); + +void LerpInferMeta(const MetaTensor& x, + const MetaTensor& y, + const MetaTensor& weight, + MetaTensor* out); + +void LinspaceRawInferMeta(const MetaTensor& start, + const MetaTensor& stop, + const MetaTensor& number, + MetaTensor* out); + +void LinspaceInferMeta(const MetaTensor& start, + const MetaTensor& stop, + const MetaTensor& number, + DataType dtype, + MetaTensor* out); + +void MultiClassNMSInferMeta(const MetaTensor& bboxes, + const MetaTensor& scores, + const MetaTensor& rois_num, + float score_threshold, + int nms_top_k, + int keep_top_k, + float nms_threshold, + bool normalized, + float nms_eta, + int background_label, + MetaTensor* out, + MetaTensor* index, + MetaTensor* nms_rois_num, + MetaConfig config = MetaConfig()); + +void NllLossRawInferMeta(const MetaTensor& input, + const MetaTensor& label, + const MetaTensor& weight, + int64_t ignore_index, + const std::string& reduction, + MetaTensor* out, + MetaTensor* total_weight, + MetaConfig config = MetaConfig()); + +void PutAlongAxisInferMeta(const MetaTensor& x, + const MetaTensor& index, + const MetaTensor& value, + int axis, + const std::string& reduce, + MetaTensor* out); + +void RoiAlignInferMeta(const MetaTensor& x, + const MetaTensor& boxes, + const MetaTensor& boxes_num, + int pooled_height, + int pooled_width, + float spatial_scale, + int sampling_ratio, + bool aligned, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void RoiPoolInferMeta(const MetaTensor& x, + const MetaTensor& boxes, + const MetaTensor& boxes_num, + int pooled_height, + int pooled_width, + float spatial_scale, + MetaTensor* out, + MetaTensor* arg_max); + +void ScatterInferMeta(const MetaTensor& x, + const MetaTensor& index, + const MetaTensor& updates, + bool overwrite, + MetaTensor* out); + +void ScatterNdAddInferMeta(const MetaTensor& x, + const MetaTensor& index, + const MetaTensor& updates, + MetaTensor* out); + +void SpectralNormInferMeta(const MetaTensor& weight, + const MetaTensor& u, + const MetaTensor& v, + int dim, + int power_iters, + float eps, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ViterbiDecodeInferMeta(const MetaTensor& input, + const MetaTensor& transition, + const MetaTensor& length, + bool include_bos_eos_tag, + MetaTensor* scores, + MetaTensor* path, + MetaConfig config = MetaConfig()); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/unary.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/unary.h new file mode 100644 index 0000000000000000000000000000000000000000..3273a043735a504f653e6ed4c2b02c21dff24898 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/infermeta/unary.h @@ -0,0 +1,685 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +// See Note [ Why still include the fluid headers? ] +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/meta_tensor.h" + +namespace phi { + +class MetaConfig; + +// Common InferMeta Functions for unary operators, The format like: +// +// void [FunctionDesc|OpName]InferMeta(const MetaTensor& x, ..., MetaTensor* +// out) {} +// +// NOTE: The name "InferShape" may be not appropriate. "InferMeta" may be good. +// Because functions in this file not only can infer shape, but also need +// infer lod or other useful data. +// +// The InferMeta Functions in this file are arranged in alphabetic order. + +void AffineGridInferMeta(const MetaTensor& input, + const IntArray& outputShape, + bool align_corners, + MetaTensor* output); + +void ArgMinMaxInferMeta(const MetaTensor& x, + const Scalar& axis, + bool keepdims, + bool flatten, + int dtype, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ArgsortInferMeta(const MetaTensor& input, + int axis, + bool descending, + MetaTensor* output, + MetaTensor* indices); + +void AsRealInferMeta(const MetaTensor& input, MetaTensor* output); + +void AsComplexInferMeta(const MetaTensor& input, MetaTensor* output); + +void BatchSizeLikeInferMeta(const MetaTensor& x, + const std::vector& shape, + int x_batch_size_dim, + int out_batch_size_dim, + MetaTensor* out); + +void CastInferMeta(const MetaTensor& x, DataType out_dtype, MetaTensor* out); + +void CholeskyInferMeta(const MetaTensor& x, bool upper, MetaTensor* out); + +void ClassCenterSampleInferMeta(const MetaTensor& label, + int num_classes, + int num_samples, + int ring_id, + int rank, + int nranks, + bool fix_seed, + int seed, + MetaTensor* remapped_label, + MetaTensor* sampled_local_class_center); + +void ClipByNormInferMeta(const MetaTensor& x, float max_norm, MetaTensor* out); + +void CreateLikeInferMeta(const MetaTensor& x, DataType dtype, MetaTensor* out); + +void CropTensorInferMeta(const MetaTensor& x, + const IntArray& shape, + const IntArray& offsets, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void CumInferMeta(const MetaTensor& x, + int axis, + bool flatten, + bool exclusive, + bool reverse, + MetaTensor* out); + +void CumScalarAxisInferMeta(const MetaTensor& x, + const Scalar& axis, + bool flatten, + bool exclusive, + bool reverse, + MetaTensor* out); + +void DecodeJpegInferMeta(const MetaTensor& x, + const std::string& mode, + MetaTensor* out); + +void DiagEmbedInferMeta( + const MetaTensor& x, int offset, int dim1, int dim2, MetaTensor* out); + +void DiagInferMeta(const MetaTensor& x, + int offset, + float padding_value, + MetaTensor* out); + +void DiagonalInferMeta( + const MetaTensor& input, int offset, int axis1, int axis2, MetaTensor* out); + +void DirichletInferMeta(const MetaTensor& alpha, MetaTensor* out); + +void EigInferMeta(const MetaTensor& x, MetaTensor* out_w, MetaTensor* out_v); + +void EighInferMeta(const MetaTensor& x, + const std::string& uplo, + MetaTensor* out_w, + MetaTensor* out_v); + +void EigvalsInferMeta(const MetaTensor& x, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void EigvalshInferMeta(const MetaTensor& x, + const std::string& uplo, + bool is_test, + MetaTensor* out_w, + MetaTensor* out_v); + +void EinsumInferMeta(const std::vector& inputs, + const std::string& equation, + MetaTensor* out); + +void EinsumRawInferMeta(const std::vector& inputs, + const std::string& equation, + MetaTensor* out, + std::vector inner_cache, + std::vector xshape); + +void ExpandInferMeta(const MetaTensor& x, + const IntArray& shape, + MetaTensor* out); + +void FillDiagonalInferMeta( + const MetaTensor& x, float value, int offset, bool wrap, MetaTensor* out); + +void FFTC2CInferMeta(const MetaTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + MetaTensor* out, + MetaConfig = MetaConfig()); + +void FFTC2RInferMeta(const MetaTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + int64_t last_dim_size, + MetaTensor* out, + MetaConfig = MetaConfig()); + +void FFTR2CInferMeta(const MetaTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + bool onesided, + MetaTensor* out, + MetaConfig = MetaConfig()); + +void FlattenInferMeta(const MetaTensor& x, + int start_axis, + int stop_axis, + MetaTensor* out); + +void FlattenWithXShapeInferMeta(const MetaTensor& x, + int start_axis, + int stop_axis, + MetaTensor* out, + MetaTensor* xshape); + +void FlipInferMeta(const MetaTensor& x, + const std::vector& axis, + MetaTensor* out); + +void FrameInferMeta(const MetaTensor& x, + int frame_length, + int hop_length, + int axis, + MetaTensor* out, + MetaConfig = MetaConfig()); + +void FullBatchSizeLikeInferMeta(const MetaTensor& x, + const std::vector& shape, + const Scalar& val, + DataType dtype, + int x_batch_size_dim, + int out_batch_size_dim, + MetaTensor* out); + +void GumbelSoftmaxInferMeta(const MetaTensor& x, + float temperature, + bool hard, + int axis, + MetaTensor* out); +void HistogramInferMeta( + const MetaTensor& input, int64_t bins, int min, int max, MetaTensor* out); + +void IncrementInferMeta(const MetaTensor& x, float value, MetaTensor* out); + +void InferMetaFromVecValue(const MetaTensor& x, + const std::vector& shape, + MetaTensor* out); + +void InverseInferMeta(const MetaTensor& x, MetaTensor* out); + +void IsEmptyInferMeta(const MetaTensor& x, MetaTensor* out); + +void IsfiniteInferMeta(const MetaTensor& input, MetaTensor* out); + +void KthvalueInferMeta(const MetaTensor& x, + int k, + int axis, + bool keepdim, + MetaTensor* out, + MetaTensor* indices, + MetaConfig = MetaConfig()); + +void LogsumexpInferMeta(const MetaTensor& input, + const std::vector& axis, + bool keepdim, + bool reduce_all, + MetaTensor* out); + +void LUInferMeta(const MetaTensor& x, + bool pivot, + MetaTensor* out, + MetaTensor* pivots, + MetaTensor* infos); + +void MatrixPowerInferMeta(const MetaTensor& x, int n, MetaTensor* out); + +void MatrixRankInferMeta(const MetaTensor& x, + bool use_default_tol, + bool hermitian, + MetaTensor* out); + +void MaxOutInferMeta(const MetaTensor& x, + int groups, + int axis, + MetaTensor* out); + +void MaxPoolWithIndexInferMeta(const MetaTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + MetaTensor* out, + MetaTensor* mask, + MetaConfig config = MetaConfig()); + +void MeanAllInferMeta(const MetaTensor& x, MetaTensor* out); + +void ModeInferMeta(const MetaTensor& x, + int axis, + bool keepdim, + MetaTensor* out, + MetaTensor* indices); + +void MultinomialInferMeta(const MetaTensor& x, + const Scalar& num_samples, + bool replacement, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void NanmedianInferMeta(const MetaTensor& x, + const IntArray& axes, + bool keep_dim, + MetaTensor* out, + MetaTensor* median_index); + +void NMSInferMeta(const MetaTensor& x, float threshold, MetaTensor* out); + +void NormInferMeta(const MetaTensor& x, + int axis, + float epsilon, + bool is_test, + MetaTensor* out, + MetaTensor* norm); + +void OverlapAddInferMeta(const MetaTensor& x, + int hop_length, + int axis, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void PadInferMeta(const MetaTensor& input, + const std::vector& paddings, + const Scalar& padding_value, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void Pad3dInferMeta(const MetaTensor& x, + const IntArray& paddings, + const std::string& mode, + float value, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void PixelShuffleInferMeta(const MetaTensor& x, + int upscale_factor, + const std::string& data_format, + MetaTensor* out); + +void PixelShuffleGradInferMeta(const MetaTensor& out_grad, + int upscale_factor, + const std::string& data_format, + MetaTensor* x_grad); + +void PixelUnshuffleInferMeta(const MetaTensor& x, + int downscale_factor, + const std::string& data_format, + MetaTensor* out); + +void PNormInferMeta(const MetaTensor& x, + float porder, + int axis, + float epsilon, + bool keepdim, + bool asvector, + MetaTensor* out); + +void PoolInferMeta(const MetaTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void Pool2DInferMeta(const MetaTensor& x, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void QrInferMeta(const MetaTensor& x, + const std::string& mode, + MetaTensor* q, + MetaTensor* r); + +void RealAndImagInferMeta(const MetaTensor& x, MetaTensor* out); + +void ReduceInferMeta(const MetaTensor& x, + const std::vector& axis, + bool keep_dim, + MetaTensor* out); + +void ReduceInferMetaBase(const MetaTensor& x, + const std::vector& axis, + bool keep_dim, + bool reduce_all, + MetaTensor* out); + +void ReduceIntArrayAxisInferMetaBase(const MetaTensor& x, + const IntArray& axis, + bool keep_dim, + bool reduce_all, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ReduceIntArrayAxisInferMeta(const MetaTensor& x, + const IntArray& axis, + bool keep_dim, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void RepeatInterleaveInferMeta(const MetaTensor& x, + int repeats, + int dim, + MetaTensor* out); + +void ReshapeInferMeta(const MetaTensor& x, + const IntArray& shape, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ReshapeWithXShapeInferMeta(const MetaTensor& x, + const IntArray& shape, + MetaTensor* out, + MetaTensor* xshape, + MetaConfig config = MetaConfig()); + +void ReverseInferMeta(const MetaTensor& x, + const IntArray& axis, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void ReverseArrayInferMeta(const std::vector& x, + const IntArray& axis, + std::vector out, + MetaConfig config = MetaConfig()); + +void RollInferMeta(const MetaTensor& x, + const IntArray& shifts, + const std::vector& axis, + MetaTensor* out); + +void RReluInferMeta(const MetaTensor& x, + float lower, + float upper, + bool is_test, + MetaTensor* out, + MetaTensor* noise); + +void RReluGradInferMeta(const MetaTensor& out_grad, + const MetaTensor& noise, + MetaTensor* x_grad); + +void SetValueInferMeta(const MetaTensor& x, MetaTensor* out); + +void ShapeInferMeta(const MetaTensor& input, MetaTensor* out); + +void ShardIndexInferMeta(const MetaTensor& in, + int index_num, + int nshards, + int shard_id, + int ignore_value, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SizeInferMeta(const MetaTensor& input, MetaTensor* out); + +void SliceRawInferMeta(const MetaTensor& input, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const std::vector& infer_flags, + const std::vector& decrease_axis, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SoftmaxInferMeta(const MetaTensor& x, int axis, MetaTensor* out); + +int GetSplitAxisValue(const MetaTensor& x, + const Scalar& axis, + MetaConfig config); + +void FillSplitOutDims(const MetaTensor& x, + const int axis_value, + const std::vector& sections_vec, + std::vector* out); + +void SplitInferMeta(const MetaTensor& x_meta, + const IntArray& sections, + const Scalar& axis, + std::vector out, + MetaConfig config = MetaConfig()); + +void SplitWithNumInferMeta(const MetaTensor& x_meta, + int num, + const Scalar& axis, + std::vector out, + MetaConfig config = MetaConfig()); + +void SquaredL2NormInferMeta(const MetaTensor& x, MetaTensor* out); + +void SqueezeInferMeta(const MetaTensor& x, + const IntArray& axes, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SqueezeWithXShapeInferMeta(const MetaTensor& x, + const IntArray& axes, + MetaTensor* out, + MetaTensor* xshape, + MetaConfig config = MetaConfig()); + +void StridedSliceRawInferMeta(const MetaTensor& x, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + const std::vector& infer_flags, + const std::vector& decrease_axis, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void StridedSliceInferMeta(const MetaTensor& x, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SumInferMeta(const MetaTensor& x, + const IntArray& axis, + DataType dtype, + bool keep_dim, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SumRawInferMeta(const MetaTensor& x, + const IntArray& axis, + bool keep_dim, + bool reduce_all, + DataType dtype, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void SvdInferMeta(const MetaTensor& x, + bool full_matrices, + MetaTensor* u, + MetaTensor* s, + MetaTensor* vh); + +void TemporalShiftInferMeta(const MetaTensor& x, + int seg_num, + float shift_ratio, + const std::string& data_format, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void TileInferMeta(const MetaTensor& x, + const IntArray& repeat_times, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void TopKInferMeta(const MetaTensor& x, + const Scalar& k_scalar, + int axis, + bool largest, + bool sorted, + MetaTensor* out, + MetaTensor* indices, + MetaConfig config = MetaConfig()); + +void TraceInferMeta( + const MetaTensor& x, int offset, int axis1, int axis2, MetaTensor* out); + +void TransferLayoutInferMeta(const MetaTensor& x, + int src_layout, + int dst_layout, + MetaTensor* out); + +void TransposeInferMeta(const MetaTensor& x, + const std::vector& axis, + MetaTensor* out); + +void TransposeGradInferMeta(const MetaTensor& x, + const std::vector& axis, + MetaTensor* out); + +void TrilTriuInferMeta(const MetaTensor& x, + int diagonal, + bool lower, + MetaTensor* out); + +void UnbindInferMeta(const MetaTensor& x, + int axis, + std::vector outs); + +void UnchangedInferMeta(const MetaTensor& x, MetaTensor* out); + +// meta x -> out without change, check if axis in range [-Rank(x), Rank(x)-1] +void UnchangedInferMetaCheckAxis(const MetaTensor& x, + int axis, + MetaTensor* out); + +void UnfoldInferMeta(const MetaTensor& x, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void UniformRandomInplaceInferMeta(const MetaTensor& x, + float min, + float max, + int seed, + int diag_num, + int diag_step, + float diag_val, + MetaTensor* out); + +void UniqueConsecutiveInferMeta(const MetaTensor& x, + bool return_inverse, + bool return_counts, + const std::vector& axis, + int dtype, + MetaTensor* out, + MetaTensor* index, + MetaTensor* counts); + +void UniqueInferMeta(const MetaTensor& x, + bool return_index, + bool return_inverse, + bool return_counts, + const std::vector& axis, + DataType dtype, + MetaTensor* out, + MetaTensor* indices, + MetaTensor* index, + MetaTensor* counts); + +void UniqueRawInferMeta(const MetaTensor& x, + bool return_index, + bool return_inverse, + bool return_counts, + const std::vector& axis, + DataType dtype, + bool is_sorted, + MetaTensor* out, + MetaTensor* indices, + MetaTensor* index, + MetaTensor* counts); + +void UnsqueezeInferMeta(const MetaTensor& x, + const IntArray& axes, + MetaTensor* out, + MetaConfig config = MetaConfig()); + +void UnsqueezeWithXShapeInferMeta(const MetaTensor& x, + const IntArray& axes, + MetaTensor* out, + MetaTensor* xshape, + MetaConfig config = MetaConfig()); + +void UnStackInferMeta(const MetaTensor& x, + int axis, + int num, + std::vector outs); + +void OneHotRawInferMeta(const MetaTensor& x, + const Scalar& depth, + DataType dtype, + bool allow_out_of_range, + MetaTensor* out); + +void OneHotInferMeta(const MetaTensor& x, const Scalar& depth, MetaTensor* out); + +void WhereIndexInferMeta(const MetaTensor& condition, MetaTensor* out); + +void ChannelShuffleInferMeta(const MetaTensor& x, + int groups, + const std::string& data_format, + MetaTensor* out); + +void IdentityLossInferMeta(const MetaTensor& x, int reduction, MetaTensor* out); + +void FoldInferMeta(const MetaTensor& x, + const std::vector& output_sizes, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + MetaTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..29223c2d913a43949531a45d36ad8a1a6f4e4a12 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void AbsGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& dout, + DenseTensor* dx); + +template +void AbsDoubleGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& ddx, + DenseTensor* ddout); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e79216a021ad08af4e23c7f7ede5d6cf771e0e7a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/abs_kernel.h @@ -0,0 +1,25 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void AbsKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/accuracy_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/accuracy_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8f2dbb96f86544882c3218a937225dd27978c15f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/accuracy_kernel.h @@ -0,0 +1,30 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AccuracyRawKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& indices, + const DenseTensor& label, + DenseTensor* accuracy, + DenseTensor* correct, + DenseTensor* total); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..46a9830882f6f3ae002b52e692854a8ac338dcbb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_grad_kernel.h @@ -0,0 +1,251 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/utils/optional.h" + +namespace phi { + +#define DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(name) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + const DenseTensor& dout, \ + DenseTensor* dx); + +#define DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(name, attr) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + const DenseTensor& dout, \ + float attr, \ + DenseTensor* dx); + +#define DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPX(name, attr1, attr2) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + const DenseTensor& dout, \ + float attr1, \ + float attr2, \ + DenseTensor* dx); + +#define DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(name) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& out, \ + const DenseTensor& dout, \ + DenseTensor* dx); + +#define DECLARE_ACTIVATION_GRAD_KERNEL_NODEP(name) \ + template \ + void name##GradKernel( \ + const Context& dev_ctx, const DenseTensor& dout, DenseTensor* dx); + +#define DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPOUT(name, attr) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& out, \ + const DenseTensor& dout, \ + float attr, \ + DenseTensor* dx); + +#define DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPOUT(name, attr1, attr2) \ + template \ + void name##GradKernel(const Context& dev_ctx, \ + const DenseTensor& out, \ + const DenseTensor& dout, \ + float attr1, \ + float attr2, \ + DenseTensor* dx); + +template +void ReluDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& ddx, + DenseTensor* ddout); + +template +void TanhDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dout, + const DenseTensor& ddx, + DenseTensor* dout_new, + DenseTensor* ddout); + +template +void TanhTripleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dout, + const DenseTensor& ddx, + const DenseTensor& d_dout_new, + const DenseTensor& d_ddout, + DenseTensor* d_out_new, + DenseTensor* d_dout, + DenseTensor* d_ddx); + +template +void LeakyReluDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& ddx, + float alpha, + DenseTensor* ddout); + +template +void EluGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + float alpha, + DenseTensor* dx); + +template +void EluDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + const DenseTensor& ddx, + float alpha, + DenseTensor* dx, + DenseTensor* ddout); + +template +void SigmoidDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dout, + const DenseTensor& ddx, + DenseTensor* dout_new, + DenseTensor* ddout); + +template +void SigmoidTripleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dout, + const DenseTensor& ddx, + const DenseTensor& d_dout_new, + const paddle::optional& d_ddout, + DenseTensor* d_out_new, + DenseTensor* d_dout, + DenseTensor* d_ddx); + +template +void LogDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + const DenseTensor& ddx, + DenseTensor* dx, + DenseTensor* ddout); + +template +void SqrtDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dx, + const DenseTensor& ddx, + DenseTensor* dout, + DenseTensor* ddout); + +template +void RsqrtDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dx, + const DenseTensor& ddx, + DenseTensor* dout, + DenseTensor* ddout); + +template +void CeluDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + const DenseTensor& ddx, + float alpha, + DenseTensor* dx, + DenseTensor* ddout); + +template +void SquareDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + const DenseTensor& ddx, + DenseTensor* dx, + DenseTensor* ddout); + +template +void HardSwishGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + float threshold, + float scale, + float offset, + DenseTensor* dx); + +template +void PowGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + const Scalar& factor, + DenseTensor* dx); + +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Cos); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Tan); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Acos); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Sin); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Asin); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Atan); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Sinh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Cosh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Asinh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Acosh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Atanh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(TanhShrink); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Silu); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Square); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Softsign); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(LogSigmoid); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Log); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Log2); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Log10); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPX(Log1p); + +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Exp); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Expm1); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Reciprocal); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Rsqrt); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Relu); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Tanh); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Sigmoid); +DECLARE_ACTIVATION_GRAD_KERNEL_DEPOUT(Sqrt); + +DECLARE_ACTIVATION_GRAD_KERNEL_NODEP(Round); +DECLARE_ACTIVATION_GRAD_KERNEL_NODEP(Floor); +DECLARE_ACTIVATION_GRAD_KERNEL_NODEP(Ceil); + +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(LeakyRelu, alpha); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(ThresholdedRelu, threshold); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(SoftShrink, lambda); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(HardShrink, threshold); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(Swish, beta); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(Logit, eps); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(Mish, threshold); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPX(Celu, alpha); +DECLARE_ACT_GRAD_KERNEL_WITH_ONE_ATTRS_DEPOUT(Relu6, threshold); + +DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPX(BRelu, t_min, t_max); +DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPX(STanh, scale_a, scale_b); +DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPX(Softplus, beta, threshold); +DECLARE_ACT_GRAD_KERNEL_WITH_TWO_ATTRS_DEPOUT(HardSigmoid, slope, offset); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8a83226b23027eafb8c0295f7cd4724fcd1b78ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/activation_kernel.h @@ -0,0 +1,118 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +#define DECLARE_ACTIVATION_KERNEL(name) \ + template \ + void name##Kernel( \ + const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +#define DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(name, attr) \ + template \ + void name##Kernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + float attr, \ + DenseTensor* out); + +#define DECLARE_ACTIVATION_KERNEL_WITH_TWO_ATTRS(name, attr1, attr2) \ + template \ + void name##Kernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + float attr1, \ + float attr2, \ + DenseTensor* out); + +DECLARE_ACTIVATION_KERNEL(Sin) +DECLARE_ACTIVATION_KERNEL(Cos) +DECLARE_ACTIVATION_KERNEL(Tan) +DECLARE_ACTIVATION_KERNEL(Asin) +DECLARE_ACTIVATION_KERNEL(Atan) +DECLARE_ACTIVATION_KERNEL(Acos) +DECLARE_ACTIVATION_KERNEL(Sinh) +DECLARE_ACTIVATION_KERNEL(Cosh) +DECLARE_ACTIVATION_KERNEL(Asinh) +DECLARE_ACTIVATION_KERNEL(Acosh) +DECLARE_ACTIVATION_KERNEL(Atanh) +DECLARE_ACTIVATION_KERNEL(Relu) +DECLARE_ACTIVATION_KERNEL(Tanh) +DECLARE_ACTIVATION_KERNEL(TanhShrink) +DECLARE_ACTIVATION_KERNEL(Silu) +DECLARE_ACTIVATION_KERNEL(Exp) +DECLARE_ACTIVATION_KERNEL(Expm1) +DECLARE_ACTIVATION_KERNEL(Reciprocal) +DECLARE_ACTIVATION_KERNEL(Square) +DECLARE_ACTIVATION_KERNEL(Sqrt) +DECLARE_ACTIVATION_KERNEL(Rsqrt) +DECLARE_ACTIVATION_KERNEL(Softsign) +DECLARE_ACTIVATION_KERNEL(Sigmoid) +DECLARE_ACTIVATION_KERNEL(LogSigmoid) +DECLARE_ACTIVATION_KERNEL(Log) +DECLARE_ACTIVATION_KERNEL(Log2) +DECLARE_ACTIVATION_KERNEL(Log10) +DECLARE_ACTIVATION_KERNEL(Log1p) +DECLARE_ACTIVATION_KERNEL(Round) +DECLARE_ACTIVATION_KERNEL(Floor) +DECLARE_ACTIVATION_KERNEL(Ceil) +DECLARE_ACTIVATION_KERNEL(Negative) + +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(LeakyRelu, alpha) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(ThresholdedRelu, threshold) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Relu6, threshold) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(SoftShrink, lambda) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Mish, threshold) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(HardShrink, threshold) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(SoftShrink, lambda) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Elu, alpha) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Swish, beta) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Celu, alpha) +DECLARE_ACTIVATION_KERNEL_WITH_ONE_ATTRS(Logit, eps) + +DECLARE_ACTIVATION_KERNEL_WITH_TWO_ATTRS(BRelu, t_min, t_max) +DECLARE_ACTIVATION_KERNEL_WITH_TWO_ATTRS(STanh, scale_a, scale_b) +DECLARE_ACTIVATION_KERNEL_WITH_TWO_ATTRS(Softplus, beta, threshold) +DECLARE_ACTIVATION_KERNEL_WITH_TWO_ATTRS(HardSigmoid, slope, offset) + +template +void HardSwishKernel(const Context& dev_ctx, + const DenseTensor& x, + float threshold, + float scale, + float offset, + DenseTensor* out); + +template +void PowKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& factor, + DenseTensor* out); + +template +DenseTensor Pow(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& factor) { + DenseTensor out; + MetaTensor meta_out(out); + UnchangedInferMeta(x, &meta_out); + PowKernel(dev_ctx, x, factor, &out); + return out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adadelta_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adadelta_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..65a6aad415193be62424a6c6ac19c1aec6927e8b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adadelta_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AdadeltaKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& avg_squared_grad, + const DenseTensor& avg_squared_update, + float rho, + float epsilon, + DenseTensor* param_out, + DenseTensor* avg_squared_grad_out, + DenseTensor* avg_squared_update_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adagrad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adagrad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cac662fddf264657a0dcdab3271e83674c3f9231 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adagrad_kernel.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void AdagradDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& moment, + const DenseTensor& learning_rate, + float epsilon, + DenseTensor* param_out, + DenseTensor* moment_out); + +template +void AdagradSparseKernel(const Context& dev_ctx, + const DenseTensor& param, + const SelectedRows& grad, + const DenseTensor& moment, + const DenseTensor& learning_rate, + float epsilon, + DenseTensor* param_out, + DenseTensor* moment_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adam_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adam_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b1a7f5a686530cd591c4409f3ae2f30d7321b8d1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adam_kernel.h @@ -0,0 +1,70 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AdamDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +template +void MergedAdamKernel( + const Context& dev_ctx, + const std::vector& param, + const std::vector& grad, + const std::vector& learning_rate, + const std::vector& moment1, + const std::vector& moment2, + const std::vector& beta1_pow, + const std::vector& beta2_pow, + const paddle::optional>& master_param, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + bool multi_precision, + bool use_global_beta_pow, + std::vector param_out, + std::vector moment1_out, + std::vector moment2_out, + std::vector beta1_pow_out, + std::vector beta2_pow_out, + std::vector master_param_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..feaf996f16266abbada655907fee68f4ab25bad3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamax_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AdamaxKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment, + const DenseTensor& inf_norm, + const DenseTensor& beta1_pow, + float beta1, + float beta2, + float epsilon, + DenseTensor* param_out, + DenseTensor* moment_out, + DenseTensor* inf_norm_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamw_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamw_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5cbb38143ff6f776e9677cb837ad155ee150bb94 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/adamw_kernel.h @@ -0,0 +1,50 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AdamwDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + float lr_ratio, + float coeff, + bool with_decay, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/add_n_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/add_n_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..13d974a5877923702bafce7d283e6cb53977e05f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/add_n_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" + +namespace phi { + +// Note(YuanRisheng): std::vector shouldn't be widely used in +// PHI. Here, we use it to be compatible with Fluid. +template +void AddNKernel(const Context& dev_ctx, + const std::vector& x, + DenseTensor* out); + +template +void AddNArrayKernel(const Context& dev_ctx, + const std::vector& x, + TensorArray* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0d2f445a61de0cb186bdd7fbe7a8a7c0bce2869e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_grad_kernel.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AddmmGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + float alpha, + float beta, + DenseTensor* input_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3674305796cde35f164289f5f405fee4c30e1216 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/addmm_kernel.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AddmmKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& x, + const DenseTensor& y, + float alpha, + float beta, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..df2dfca10b0b33d7b4a183ccaf5fc8c26ef160ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" + +namespace phi { + +template +void AffineGridGradKernel(const Context& dev_ctx, + const DenseTensor& output_grad, + const IntArray& outputShape, + bool align_corners, + DenseTensor* input_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..57ac0007b1c021eb34632acca0a5e69728fdb055 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/affine_grid_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" + +namespace phi { + +template +void AffineGridKernel(const Context& dev_ctx, + const DenseTensor& input, + const IntArray& outputShape, + bool align_corners, + DenseTensor* output); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/allclose_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/allclose_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3f24078b86ca1736411cb929754441d737ee6028 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/allclose_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AllCloseKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const Scalar& rtol, + const Scalar& atol, + bool equal_nan, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/amp_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/amp_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e22a730db676333f35775a43f09cf088b5105609 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/amp_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CheckFiniteAndUnscaleKernel(const Context& dev_ctx, + const std::vector& xs, + const DenseTensor& scale, + std::vector outs, + DenseTensor* found_infinite); + +template +void UpdateLossScalingKernel(const Context& dev_ctx, + const std::vector& xs, + const DenseTensor& found_infinite, + const DenseTensor& prev_loss_scaling, + const DenseTensor& in_good_steps, + const DenseTensor& in_bad_steps, + int incr_every_n_steps, + int decr_every_n_nan_or_inf, + float incr_ratio, + float decr_ratio, + const Scalar& stop_update, + std::vector outs, + DenseTensor* loss_scaling, + DenseTensor* out_good_steps, + DenseTensor* out_bad_steps); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3082ef7e477d1dbb61fdf11d347295630a1782da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AngleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e947fe0e3e38d905010cebc401d4c9398e63f9b4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/angle_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES +#endif +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AngleKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arange_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arange_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..be60824ac2be23abb28564d42ea2bd804222a1ec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arange_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ArangeKernel(const Context& dev_ctx, + const DenseTensor& start, + const DenseTensor& end, + const DenseTensor& step, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arg_min_max_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arg_min_max_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..258c8f21e0540b04d844287ad7c85212a3f4f9c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/arg_min_max_kernel.h @@ -0,0 +1,40 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ArgMinKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& axis, + bool keepdims, + bool flatten, + int dtype, + DenseTensor* out); + +template +void ArgMaxKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& axis, + bool keepdims, + bool flatten, + int dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b91bd69911351dcd330325fabb515df0eebba29f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ArgsortGradKernel(const Context& dev_ctx, + const DenseTensor& indices, + const DenseTensor& input, + const DenseTensor& out_grad, + int axis, + bool descending, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..519f2b88547f689738a341c3755ea2b8892d8102 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/argsort_kernel.h @@ -0,0 +1,49 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Performs sorting on the input tensor along the given axis and outputs + * two tensors, Output(Out) and Output(Indices). They reserve the same + * shape with Input(X), and Output(Out) represents the sorted tensor + * while Output(Indices) gives the sorted order along the given axis + * Attr(axis). + * @param ctx device context + * @param x The input of Argsort + * @param axis The axis along which to sort the tensor. + * When axis < 0, the actual axis will be the |axis|'th + * counting backwards + * @param descending The descending attribute is a flag to tell + * algorithm how to sort the input data. + * If descending is true, will sort by descending order, + * else if false, sort by ascending order + * @param out The sorted tensor of Argsort op, with the same shape as + * x + * @param indices The indices of a tensor giving the sorted order, with + * the same shape as x + */ +template +void ArgsortKernel(const Context& dev_ctx, + const DenseTensor& input, + int axis, + bool descending, + DenseTensor* output, + DenseTensor* indices); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_complex_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_complex_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bdf5392b1c5a3f7c620db1b6b3bf20456f3e7220 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_complex_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AsComplexKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_real_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_real_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e600f3ce39a6d0b8d686dfb910d7e976edafa7ca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/as_real_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AsRealKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/assign_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/assign_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7fa0350ad0ed6458adafb69e32ad2085b7330289 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/assign_kernel.h @@ -0,0 +1,61 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void AssignKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +template +DenseTensor Assign(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor out; + MetaTensor meta_out(&out); + MetaTensor meta_x(x); + UnchangedInferMeta(meta_x, &meta_out); + AssignKernel(dev_ctx, x, &out); + return out; +} + +// In order to be compatible with the `AsDispensable` input in the original +// assign op maker, the input parameter here needs to be dispensable, but +// this looks weird +template +void AssignRawKernel(const Context& dev_ctx, + const paddle::optional& x, + DenseTensor* out); + +template +void AssignArrayKernel(const Context& dev_ctx, + const TensorArray& x, + TensorArray* out); + +template +void AssignValueKernel(const Context& dev_ctx, + const std::vector& shape, + DataType dtype, + const std::vector& values, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ddd87c9da156d4b9ff983972010b90a74a231c4a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Atan2GradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..38276fa4f73ce5c0c94383a90e6f6f711efd9bcf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/atan2_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Atan2Kernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/auc_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/auc_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..dd85b409786ebde52ca548f44ca05dce10a1ec73 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/auc_kernel.h @@ -0,0 +1,38 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AucKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + const DenseTensor& stat_pos, + const DenseTensor& stat_neg, + const paddle::optional& ins_tag_weight, + const std::string& curve, + int num_thresholds, + int slide_steps, + DenseTensor* auc, + DenseTensor* stat_pos_out, + DenseTensor* stat_neg_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/average_accumulates_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/average_accumulates_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..63f2b362cfde3a37a292845f4b0530d93e53192c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/average_accumulates_kernel.h @@ -0,0 +1,57 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GetAccumulators(const Context& dev_ctx, + const DenseTensor& in_num_accumulates, + const DenseTensor& in_old_num_accumulates, + const DenseTensor& in_num_updates, + int64_t* num_updates, + int64_t* num_accumulates, + int64_t* old_num_accumulates); + +template +void SetAccumulators(const Context& dev_ctx, + int64_t num_updates, + int64_t num_accumulates, + int64_t old_num_accumulates, + DenseTensor* out_num_accumulates, + DenseTensor* out_old_num_accumulates, + DenseTensor* out_num_updates); + +template +void AverageAccumulatesKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& in_sum_1, + const DenseTensor& in_sum_2, + const DenseTensor& in_sum_3, + const DenseTensor& in_num_accumulates, + const DenseTensor& in_old_num_accumulates, + const DenseTensor& in_num_updates, + float average_window, + int64_t max_average_window, + int64_t min_average_window, + DenseTensor* out_sum_1, + DenseTensor* out_sum_2, + DenseTensor* out_sum_3, + DenseTensor* out_num_accumulates, + DenseTensor* out_old_num_accumulates, + DenseTensor* out_num_updates); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..afbb0c78ca9811582f8e7a66282615b2d773693c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_grad_kernel.h @@ -0,0 +1,91 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BatchNormGradRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const paddle::optional& mean, + const paddle::optional& variance, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const paddle::optional& reserve_space, + const DenseTensor& y_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + bool is_inplace, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +template +void BatchNormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const paddle::optional& mean, + const paddle::optional& variance, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const paddle::optional& reserve_space, + const DenseTensor& y_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +template +void BatchNormDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const paddle::optional& mean, + const paddle::optional& variance, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const DenseTensor& y_grad, + const DenseTensor& x_grad_grad, + const DenseTensor& scale_grad_grad, + const DenseTensor& bias_grad_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* y_grad_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..be589e43647c1c6b433deec27465c328a67b89e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/batch_norm_kernel.h @@ -0,0 +1,58 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BatchNormKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& mean, + const DenseTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + DenseTensor* y, + DenseTensor* mean_out, + DenseTensor* variance_out, + DenseTensor* saved_mean, + DenseTensor* saved_variance, + DenseTensor* reserve_space); + +template +void BatchNormInferKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& mean, + const DenseTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + DenseTensor* y, + DenseTensor* mean_out, + DenseTensor* variance_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..14bf52196ac40d81bb925c3fa10c021f173d5218 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BCELossGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + const DenseTensor& out_grad, + DenseTensor* input_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6459ea911666e7151c2e2fc6645f4a477215f82b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bce_loss_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BCELossKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bernoulli_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bernoulli_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4e0f9b5267fda9d298da45b56d33cc7499d601ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bernoulli_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +/** + * @brief This Kernel returns a Tensor filled with random binary(0 or 1) number + * from a Bernoulli distribution. + * @param ctx device context + * @param x A tensor with probabilities for generating the random binary + * number + * @param out A Tensor filled with random binary number + */ +template +void BernoulliKernel(const Context& ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..499aa1e0b2ea958935c20bc9bbcde89d6a15d9a4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BilinearTensorProductGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& weight, + const DenseTensor& dout, + DenseTensor* dx, + DenseTensor* dy, + DenseTensor* dweight, + DenseTensor* dbias); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bd01ed94868e2c50cf5670403f5d00c9964a0fc9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bilinear_tensor_product_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void BilinearTensorProductKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& weight, + const paddle::optional& bias, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bincount_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bincount_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7b72a1fabd8f52e7a1a88b1027343d42535fcfd5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bincount_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BincountKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& weights, + const Scalar& minlength, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bitwise_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bitwise_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..17307004f360e10ada708fba276ec8de1a129259 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bitwise_kernel.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BitwiseAndKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void BitwiseOrKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void BitwiseXorKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void BitwiseNotKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1b56641d113c5767a007c22aa48638d55dfa8b70 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BmmGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..09e7f9647b68ebd7209c205881d0b6e599c685ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/bmm_kernel.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Bmm Kernel. + * Applies batched matrix multiplication to two tensors. + * + * Both of the two input tensors must be three-dementional + * and share the same batch size. + * if x is a (b, m, k) tensor, y is a (b, k, n) tensor, + * the output will be a (b, m, n) tensor. + * + * @param ctx device context + * @param x The input tensor + * @param y The input tensor + * @param out The product Tensor + */ +template +void BmmKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/box_coder_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/box_coder_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9e5c52bd5be78b43ca19e914b7ba0a9c4dde9a0b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/box_coder_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BoxCoderKernel(const Context& dev_ctx, + const DenseTensor& prior_box, + const paddle::optional& prior_box_var, + const DenseTensor& target_box, + const std::string& code_type, + bool box_normalized, + int axis, + const std::vector& variance, + DenseTensor* output_box); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..79d5b8a445b48eb320f80341b9c8863186f97de6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BroadcastTensorsGradKernel(const Context& ctx, + const std::vector& dout, + std::vector dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..dccaebcf41ffeeeb40cb3f771709bcfa2e35b3ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/broadcast_tensors_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BroadcastTensorsKernel(const Context& ctx, + const std::vector& x, + std::vector out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6b98bc88de7dd3119a57957694ce535b35354f1f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_grad_kernel.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CastGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5e07388f5fb20d3a791bcf288e1e6597479e12c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cast_kernel.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void CastKernel(const Context& dev_ctx, + const DenseTensor& x, + DataType out_dtype, + DenseTensor* out); + +template +DenseTensor Cast(const Context& dev_ctx, + const DenseTensor& x, + DataType out_dtype) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + CastInferMeta(x, out_dtype, &meta_out); + CastKernel(dev_ctx, x, out_dtype, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d75d887d0fcd81ac3f2537785fe764b7dc4b783b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ChannelShuffleGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + int groups, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c15e06fb552bfe4a41274d077710b406dab5fc2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/channel_shuffle_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ChannelShuffleKernel(const Context& dev_ctx, + const DenseTensor& x, + int groups, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b170a3d7ffcfacdf8186d0f54450a38b536949d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_grad_kernel.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CholeskyGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& out_grad, + bool upper, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b7e0a44e81e5f4b7daa1b4440082cde47aac80c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_kernel.h @@ -0,0 +1,42 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Computes the Cholesky decomposition of one symmetric positive-definite + * matrix or batches of symmetric positive-definite matrices. + * @param ctx device context + * @param x The input tensor of cholesky op. Its shape should be + * [*, M, M] where * is zero or more batch dimensions, + * and matrices on the inner-most 2 dimensions all + * should be symmetric positive-definite + * @param upper flag indicating whether to return upper or lower triangular + * matrices + * @param out The output tensor of cholesky kernel. It has the same + * shape as the input, and it is composed of upper-triangular or + * lower-triangular Cholesky factors of each of the individual + * matrices + */ +template +void CholeskyKernel(const Context& dev_ctx, + const DenseTensor& x, + bool upper, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e2ce67abae6234d1bfbc919cef06250bcd7c6b6e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CholeskySolveGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& dout, + bool upper, + DenseTensor* dx, + DenseTensor* dy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cd49937737f92ead4242b6470fc39a326a21c002 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cholesky_solve_kernel.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Solves a linear system of equations with a positive semidefinite + * matrix to be inverted given its Cholesky factor matrix uu + * @param ctx device context + * @param x The input tensor, shape of (*,m,k) + * @param y The input tensor, shape of (*,m,m) composed of upper or lower + * triangular Cholesky factor + * @param upper whether to consider the Cholesky factor as a lower or upper + * triangular matrix + * @param out The output tensor, shape same to x + */ +template +void CholeskySolveKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + bool upper, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/class_center_sample_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/class_center_sample_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..61717e250c20fddbf986f643a810b4f780e5ba54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/class_center_sample_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ClassCenterSampleKernel(const Context& dev_ctx, + const DenseTensor& label, + int num_classes, + int num_samples, + int ring_id, + int rank, + int nranks, + bool fix_seed, + int seed, + DenseTensor* remapped_label, + DenseTensor* sampled_local_class_center); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_by_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_by_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..debff5d08b6466568ca6fed02ee2247c58e1dff3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_by_norm_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ClipByNormKernel(const Context& dev_ctx, + const DenseTensor& x, + float max_norm, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8a7e5b99fd9248e752dc22d33695fde533b78016 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void ClipGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const Scalar& min, + const Scalar& max, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..14ac8342e03bcfab4b43bbc80ec87ee5f6326755 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/clip_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void ClipKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& min, + const Scalar& max, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/coalesce_tensor_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/coalesce_tensor_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cbfe2c18bb0238bf241938b98a876096c7d10b55 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/coalesce_tensor_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CoalesceTensorKernel(const Context& dev_ctx, + const std::vector& input, + DataType dtype, + bool copy_data, + bool set_constant, + bool persist_output, + float constant, + bool use_align, + int align_size, + int size_of_dtype, + const std::vector& concated_shapes, + const std::vector& concated_ranks, + std::vector output, + DenseTensor* fused_output); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/compare_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/compare_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5b6b8cd868f9fcb9048e00526b272e3cd4c54682 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/compare_kernel.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +#define DECALRE_COMPARE_KERNEL(compare_kernel) \ + template \ + void compare_kernel(const Context& ctx, \ + const DenseTensor& x, \ + const DenseTensor& y, \ + int axis, \ + DenseTensor* out); + +DECALRE_COMPARE_KERNEL(LessThanKernel) +DECALRE_COMPARE_KERNEL(LessEqualKernel) +DECALRE_COMPARE_KERNEL(GreaterThanKernel) +DECALRE_COMPARE_KERNEL(GreaterEqualKernel) +DECALRE_COMPARE_KERNEL(EqualKernel) +DECALRE_COMPARE_KERNEL(NotEqualKernel) +#undef DECALRE_COMPARE_KERNEL + +#define DECALRE_COMPARE_ALL_KERNEL(compare_all_kernel) \ + template \ + void compare_all_kernel(const Context& ctx, \ + const DenseTensor& x, \ + const DenseTensor& y, \ + DenseTensor* out); + +DECALRE_COMPARE_ALL_KERNEL(EqualAll) +#undef DECALRE_COMPARE_KERNEL + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..91c47538e958d4450a2ad08a89f13f8990571200 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_grad_kernel.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RealGradKernel(const Context& dev_ctx, + const DenseTensor& dout, + DenseTensor* dx); + +template +void ImagGradKernel(const Context& dev_ctx, + const DenseTensor& dout, + DenseTensor* dx); + +template +void ComplexGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + DenseTensor* dx, + DenseTensor* dy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ad66b890b3d5ab70aabaf9911b726a4b9d2261ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/complex_kernel.h @@ -0,0 +1,117 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/complex.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void ConjKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +template +void RealKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +template +void ImagKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +template +void ComplexKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +// If T is complex +template < + typename T, + typename Context, + std::enable_if_t>::value || + std::is_same>::value, + bool> = true> +DenseTensor Conj(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + UnchangedInferMeta(x, &meta_out); + ConjKernel(dev_ctx, x, &dense_out); + return dense_out; +} + +// If T is not complex +template < + typename T, + typename Context, + std::enable_if_t>::value && + !std::is_same>::value, + bool> = true> +DenseTensor Conj(const Context& dev_ctx, const DenseTensor& x) { + return x; +} + +// If T is complex +template < + typename T, + typename Context, + std::enable_if_t>::value || + std::is_same>::value, + bool> = true> +DenseTensor Real(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + RealAndImagInferMeta(x, &meta_out); + RealKernel(dev_ctx, x, &dense_out); + return dense_out; +} + +// If T is not complex +template < + typename T, + typename Context, + std::enable_if_t>::value && + !std::is_same>::value, + bool> = true> +DenseTensor Real(const Context& dev_ctx, const DenseTensor& x) { + return x; +} + +// If T is complex +template < + typename T, + typename Context, + std::enable_if_t>::value || + std::is_same>::value, + bool> = true> +DenseTensor Imag(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + RealAndImagInferMeta(x, &meta_out); + ImagKernel(dev_ctx, x, &dense_out); + return dense_out; +} + +// If T is not complex +template < + typename T, + typename Context, + std::enable_if_t>::value && + !std::is_same>::value, + bool> = true> +DenseTensor Imag(const Context& dev_ctx, const DenseTensor& x) { + return x; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e407d73bb49ee79f62eb93c8194470919803971d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/multiary.h" +#include "paddle/phi/kernels/empty_kernel.h" +namespace phi { + +template +void ConcatGradKernel(const Context& dev_ctx, + const std::vector& x, + const DenseTensor& out_grad, + const Scalar& axis_scalar, + std::vector x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f5ac2d3cbb75e9d175d7fad342723a5aa1db1dea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/concat_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/multiary.h" +#include "paddle/phi/kernels/empty_kernel.h" +namespace phi { + +template +void ConcatKernel(const Context& dev_ctx, + const std::vector& x, + const Scalar& axis, + DenseTensor* out); + +template +DenseTensor Concat(const Context& dev_ctx, + const std::vector& x, + const Scalar& axis) { + std::vector meta_x; + meta_x.reserve(x.size()); + std::vector meta_x_ptr; + for (const auto* t : x) { + meta_x.emplace_back(*t); + meta_x_ptr.push_back(&meta_x.back()); + } + + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ConcatInferMeta(meta_x_ptr, axis.to(), &meta_out); + ConcatKernel(dev_ctx, x, axis, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f25cbe384c21399104ee88367b8a60a1ac40afbe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_grad_kernel.h @@ -0,0 +1,61 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ConvGradGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const DenseTensor& out_grad, + const paddle::optional& input_grad_grad, + const paddle::optional& filter_grad_grad, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* input_grad, + DenseTensor* filter_grad, + DenseTensor* out_grad_grad); + +template +void Conv3DGradGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const DenseTensor& out_grad, + const paddle::optional& input_grad_grad, + const paddle::optional& filter_grad_grad, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* input_grad, + DenseTensor* filter_grad, + DenseTensor* out_grad_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a6b970e0996be94187378036a53e0c157257b44c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_grad_kernel.h @@ -0,0 +1,73 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ConvGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const DenseTensor& out_grad, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* input_grad, + DenseTensor* filter_grad); + +template +void Conv3DGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const DenseTensor& out_grad, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* input_grad, + DenseTensor* filter_grad); + +template +void DepthwiseConvGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const DenseTensor& out_grad, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + bool fuse_relu, + DenseTensor* input_grad, + DenseTensor* filter_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a105fe794f94d796b83f3db620f914ab5b640188 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_kernel.h @@ -0,0 +1,79 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ConvKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* out); + +template +void Conv3DKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + DenseTensor* out); + +template +void DepthwiseConvKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + bool use_addto, + int workspace_size_MB, + bool exhaustive_search, + bool fuse_relu, + DenseTensor* out); + +template +void ConvInferKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::string& paddding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c137a1914e4954f6de2cebb0aeb20a456e0665c0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_grad_kernel.h @@ -0,0 +1,92 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Conv2dTransposeGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const DenseTensor& dout, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* dx, + DenseTensor* dfilter); + +template +void Conv2dTransposeDoubleGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const DenseTensor& dout, + const DenseTensor& ddx, + const DenseTensor& ddfilter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* dx, + DenseTensor* dfilter, + DenseTensor* ddout); + +template +void Conv3dTransposeGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const DenseTensor& dout, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const std::vector& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* dx, + DenseTensor* dfilter); + +template +void DepthwiseConv2dTransposeGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const DenseTensor& dout, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* dx, + DenseTensor* dfilter); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bb82b971b45734671fbd3c020dac7857d54f6fc5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/conv_transpose_kernel.h @@ -0,0 +1,67 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Conv2dTransposeKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* out); + +template +void Conv3dTransposeKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const std::vector& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* out); + +template +void DepthwiseConv2dTransposeKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& filter, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_padding, + const IntArray& output_size, + const std::string& padding_algorithm, + int groups, + const std::vector& dilations, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..97f1fbf5b029aa0ad226afe912dc97525693392f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CropTensorGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& offsets, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..079959eb05c145a42936a0be1ccd623a8b06b64e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/crop_tensor_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CropTensorKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& shape, + const IntArray& offsets, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ae4b0436c93ca09707407a00f120ef78b3a2ca0a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_grad_kernel.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CrossEntropyWithSoftmaxGradKernel(const Context& dev_ctx, + const DenseTensor& label, + const DenseTensor& softmax, + const DenseTensor& loss_grad, + bool soft_label, + bool use_softmax, + bool numeric_stable_mode, + int ignore_index, + int axis, + DenseTensor* logits_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..621c5f366621351137fc2000e618149375ab842b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_entropy_kernel.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +// The deformed product of operator iterative upgrade, there is no strict 2.0 +// API corresponding to it! In 2.0 API paddle.nn.functional.cross_entropy, +// use_softmax has become an optional argument, which may be called +// CrossEntropyWithSoftmax more accurately, here we keep this kernel arguments +// same as original OpMaker, and if need a CrossEntropyKernel like +// paddle.nn.functional.cross_entropy, we can reuse this kernel +template +void CrossEntropyWithSoftmaxKernel(const Context& dev_ctx, + const DenseTensor& logits, + const DenseTensor& label, + bool soft_label, + bool use_softmax, + bool numeric_stable_mode, + int ignore_index, + int axis, + DenseTensor* softmax, + DenseTensor* loss); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9ea0804a94b6b5d145a13c8f794a9f01498bf7db --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CrossGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c983164d2a251440214bb5889c58779ac37e8df9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cross_kernel.h @@ -0,0 +1,40 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Returns the cross product of vectors in dimension dim of + * input and other. Input and other must have the same size, + * and the size of their dim dimension should be 3. + * If dim is not given, it defaults to the first dimension + * found with the size 3. + * @param ctx device context + * @param x the input tensor + * @param y the second input tensor + * @param axis the dimension to take the cross-product in + * @param out the output tensor + */ +template +void CrossKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cum_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cum_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..870a305573b680e4bcbadfccf3568d11ab8efa12 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cum_kernel.h @@ -0,0 +1,40 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CumsumKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& axis, + bool flatten, + bool exclusive, + bool reverse, + DenseTensor* out); + +template +void LogcumsumexpKernel(const Context& dev_ctx, + const DenseTensor& x, + int axis, + bool flatten, + bool exclusive, + bool reverse, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7610cad31e32774fe44615eb80b7cd3ba5ec2bca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CumprodGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + int dim, + DenseTensor* dx); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bb8b1427b30c46206059bf0f359203ef7a5f2620 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/cumprod_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void CumprodKernel(const Context& dev_ctx, + const DenseTensor& x, + int dim, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/decode_jpeg_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/decode_jpeg_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..55227516eb644227c82d7aa7dfb239f222976611 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/decode_jpeg_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DecodeJpegKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::string& mode, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..04fe7904a45092c042d84aa467617982c84be453 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_grad_kernel.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DeformableConvGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& offset, + const DenseTensor& filter, + const paddle::optional& mask, + const DenseTensor& out_grad, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + int deformable_groups, + int groups, + int im2col_step, + DenseTensor* dx, + DenseTensor* offset_grad, + DenseTensor* filter_grad, + DenseTensor* mask_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7b66e506b89283dd92315c20c9901299d54f9608 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/deformable_conv_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void DeformableConvKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& offset, + const DenseTensor& filter, + const paddle::optional& mask, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + int deformable_groups, + int groups, + int im2col_step, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b5eff76e90c472f6deda08ebb560b4763337ab53 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_grad_kernel.h @@ -0,0 +1,19 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi {} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b5eff76e90c472f6deda08ebb560b4763337ab53 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/depthwise_conv_kernel.h @@ -0,0 +1,19 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi {} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..87228afc51b52bb95838d3161f372c2ebae19b2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DeterminantGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..abd5f5691b3e5df6274db1bcd3a915c80bf93ec4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/determinant_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DeterminantKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_embed_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_embed_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e47eab82474fb9759fe6fa916c056d1237a7e39f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_embed_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DiagEmbedKernel(const Context& dev_ctx, + const DenseTensor& x, + int offset, + int dim1, + int dim2, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b9edab9bec44c367db2d36dfce05c425dcb07785 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DiagGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + int offset, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..704632a52086e7abc7d85b46ce9ed5aae866cab6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diag_kernel.h @@ -0,0 +1,61 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +/** + * @brief If ``x`` is a vector (1-D tensor), a 2-D square tensor with the + * elements of ``x`` as the diagonal is returned. + * If ``x`` is a matrix (2-D tensor), a 1-D tensor with the diagonal + * elements of ``x`` is returned. + * + * The argument ``offset`` controls the diagonal offset: + * If ``offset`` = 0, it is the main diagonal. + * If ``offset`` > 0, it is superdiagonal. If ``offset`` < 0, + * it is subdiagonal. + * @param ctx device context + * @param x The input tensor. Its shape is either 1-D or 2-D. + * @param offset The diagonal offset. A positive value represents + * superdiagonal, 0 represents the main diagonal, and a + * negative value represents subdiagonal. + * @param padding_value Use this value to fill the area outside the specified + * diagonal band. Only takes effect when the input is a + * 1-D Tensor. The default value is 0. + * @param out The output tensor. A square matrix or a vector. + */ +template +void DiagKernel(const Context& dev_ctx, + const DenseTensor& x, + int offset, + float padding_value, + DenseTensor* out); + +template +DenseTensor Diag(const Context& dev_ctx, + const DenseTensor& x, + int offset, + float padding_value) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DiagInferMeta(x, offset, padding_value, &meta_out); + DiagKernel(dev_ctx, x, offset, padding_value, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..33586d04c7015e7ce9f62de87afdfbe36ccb950c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DiagonalGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + int offset, + int axis1, + int axis2, + DenseTensor* in_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2d866d4e301b1912e374567d8bf9bc97bd2504b2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/diagonal_kernel.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Return a partial view of input with the its diagonal elements + * of the input tensor. The behavior of this operator is similar to + * how `numpy.diagonal` works. + * @param ctx device context + * @param x the input tensor, from which the diagonals are taken + * @param offset offset of the diagonal from the main diagonal. Can be both + * positive and negative + * @param axis1 the first axis of the 2-D planes from which the diagonals + * should be taken. Can be either positive or negative + * @param axis2 the second axis of the 2-D planes from which the diagonals + * should be taken. Can be either positive or negative + * @param out the partial view of input with the its diagonal elements + */ +template +void DiagonalKernel(const Context& dev_ctx, + const DenseTensor& x, + int offset, + int axis1, + int axis2, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..abd8634518d2c6b12aebaa6e0fa9bdbeb404494f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DigammaGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b45b7070d2deeca46efcb3f77e4fdbdaf5964a9c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/digamma_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief This kernrel is used to perform elementwise digamma for x. + * $$out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) }$$ + * @param ctx device context + * @param x the input tensor of digamma + * @param out the output tensor of digamma + */ +template +void DigammaKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dirichlet_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dirichlet_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a758eb8db023f90f1179da489d30c7d5ed84dc9f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dirichlet_kernel.h @@ -0,0 +1,25 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Dirichletkernel(const Context& dev_ctx, + const DenseTensor& alpha, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1f8d7ff21f2fe42de029829a5cfa67df9e0e42b1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DistGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& out_grad, + float p, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8c1f6674aa5b5a26947886d6ac8f2c139c430545 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dist_kernel.h @@ -0,0 +1,59 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Given two tensors x and y, compute Lp-norm of (x-y). + * It is not a norm in a strict sense, only as a measure of distance. + * The shapes of x and y must be broadcastable. Where, z = x - y, + * + * When p = 0, defining $0^0 = 0$, the zero-norm of z is simply + * the number of non-zero elements of z. + * $$ + * ||z||_{0} = \lim_{p \rightarrow 0} \sum_{i=1}^{m} |z_i|^p + * $$ + * + * When p = inf, the inf-norm of z is the maximum element of z. + * $$ + * ||z||_\infty=\max_i |z_i| + * $$ + * + * When p = -inf, the negative-inf-norm of z is the minimum element of z. + * $$ + * ||z||_{-\infty}=\min_i |z_i| + * $$ + * + * Otherwise, the p-norm of z follows the formula, + * $$ + * ||z||_{p} = (\sum_{i=i}^{m} |z_i|^p)^{1/p} + * $$ + * @param ctx device context + * @param x the input Tensor of Dist + * @param y the Right-hand-side input Tensor of Dist + * @param p the norm to be computed + * @param out the output of Dist, which is the p-norm of (x - y) + */ +template +void DistKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + float p, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/distribute_fpn_proposals_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/distribute_fpn_proposals_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9a7bb2f6e0e7fa1cec35f8c9a768bddb2f405a67 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/distribute_fpn_proposals_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DistributeFpnProposalsKernel( + const Context& ctx, + const DenseTensor& fpn_rois, + const paddle::optional& rois_num, + int min_level, + int max_level, + int refer_level, + int refer_scale, + bool pixel_offset, + std::vector multi_fpn_rois, + std::vector multi_level_rois_num, + DenseTensor* restore_index); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3e7f478878ba5ed3b0e0f1a475578a99fe96fe90 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_grad_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DotGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + DenseTensor* dx, + DenseTensor* dy); + +template +void DotDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& ddx, + const DenseTensor& ddy, + const DenseTensor& dout, + DenseTensor* dx, + DenseTensor* dy, + DenseTensor* ddout); + +template +void DotTripleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& ddx, + const DenseTensor& ddy, + const DenseTensor& d_dx, + const DenseTensor& d_dy, + const DenseTensor& dout, + const DenseTensor& d_ddout, + DenseTensor* d_x, + DenseTensor* d_y, + DenseTensor* d_ddx, + DenseTensor* d_ddy, + DenseTensor* d_dout); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9c7703440d8aeea4dd518436a5bb62dac2f12519 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dot_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" +#include "paddle/phi/kernels/empty_kernel.h" +namespace phi { + +template +void DotKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Dot(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DotInferMeta(x, y, &meta_out); + DotKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c61e4d0b8598dc2fc2c21edbea6d72c3f97ea2e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_grad_kernel.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DropoutGradRawKernel(const Context& dev_ctx, + const DenseTensor& mask, + const DenseTensor& out_grad, + const Scalar& p, + bool is_test, + const std::string& mode, + DenseTensor* x_grad); + +template +void DropoutNdGradKernel(const Context& dev_ctx, + const DenseTensor& mask, + const DenseTensor& out_grad, + const Scalar& p, + bool is_test, + const std::string& mode, + const std::vector& axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ff718d641bedcedcee30dc1515476fe609d3d001 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/dropout_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void DropoutRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& seed_tensor, + const Scalar& p, + bool is_test, + const std::string& mode, + int seed, + bool fix_seed, + DenseTensor* out, + DenseTensor* mask); + +template +void DropoutNdKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& seed_tensor, + const Scalar& p, + bool is_test, + const std::string& mode, + int seed, + bool fix_seed, + const std::vector& axis, + DenseTensor* out, + DenseTensor* mask); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/edit_distance_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/edit_distance_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..40b3e5f0aa025dc7ed8fea3ecfe49cc30b54be6f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/edit_distance_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EditDistanceKernel(const Context& ctx, + const DenseTensor& hyps, + const DenseTensor& refs, + const paddle::optional& hypslength, + const paddle::optional& refslength, + bool normalized, + DenseTensor* sequencenum, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..93ae707f6f95f3f3ae43c8a232edcda3d6b3c37b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EigGardKernel(const Context& dev_ctx, + const DenseTensor& out_w, + const DenseTensor& out_v, + const DenseTensor& dout_w, + const DenseTensor& dout_v, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fd894c35862332be52e3f4e84d5e8bb05bb72a30 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eig_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EigKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out_w, + DenseTensor* out_v); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..73df76e676a8b4a7eee570f466f9e94f619c5443 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EighGardKernel(const Context& dev_ctx, + const DenseTensor& out_w, + const DenseTensor& out_v, + const DenseTensor& dout_w, + const DenseTensor& dout_v, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..19653918302412e2f7e4dfa8caf71b6c9146a83f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigh_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EighKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::string& uplo, + DenseTensor* out_w, + DenseTensor* out_v); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvals_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvals_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..dd9f3370bd08ea077ab9d39be1f3fdf91d2aeabd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvals_kernel.h @@ -0,0 +1,25 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void EigvalsKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..934586f9b7bfbd756fc7242e63104ed2c50953d1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_grad_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EigvalshGradKernel(const Context& dev_ctx, + const DenseTensor& out_v, + const DenseTensor& out_w_grad, + const std::string& uplo, + bool is_test, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bd586a615924c848071416bc691ac57579df31c0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eigvalsh_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EigvalshKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::string& uplo, + bool is_test, + DenseTensor* out_w, + DenseTensor* out_v); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..06785c8532e70d560a61fbf9e50b8f891fcdd317 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EinsumGradKernel(const Context& dev_ctx, + const std::vector& x, + const std::vector& inner_cache, + const DenseTensor& out_grad, + const std::string& equation, + std::vector x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..569cf7a55afd4a62783e6708c6b2d339d9fabd3c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/einsum_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EinsumKernel(const Context& dev_ctx, + const std::vector& inputs, + const std::string& equation, + DenseTensor* out); + +template +void EinsumKernelRaw(const Context& dev_ctx, + const std::vector& inputs, + const std::string& equation, + DenseTensor* out, + std::vector inner_cache, + std::vector xshape); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8fc31c8878b6aab9f285b5f5a18650da0a3aa15d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_grad_kernel.h @@ -0,0 +1,49 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void AddGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void AddDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& y, + const DenseTensor& dout, + const paddle::optional& ddx, + const paddle::optional& ddy, + int axis, + DenseTensor* ddout); + +template +void AddTripleGradKernel(const Context& dev_ctx, + const DenseTensor& ddx, + const DenseTensor& ddy, + const DenseTensor& d_ddout, + int axis, + DenseTensor* d_ddx, + DenseTensor* d_ddy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3245c450aaebea72e5d642a39a8e33b95aa8ce9f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_add_kernel.h @@ -0,0 +1,45 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { +template +void AddRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void AddKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Add(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + AddKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c764f05c3983fb093c38f6329a69d00f6aed1360 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_grad_kernel.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void DivideGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void DivideDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& dx, + const paddle::optional& ddx, + const paddle::optional& ddy, + int axis, + DenseTensor* dy, + DenseTensor* dout, + DenseTensor* ddout); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5555b69fde1dea84870bb19bd16d9b65fb92786e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_divide_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { + +template +void DivideRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void DivideKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Divide(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + DivideKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b1e6ecaee6746afca94695a2f4616b077c2679eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_grad_kernel.h @@ -0,0 +1,75 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void ElementwiseFMaxGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad, + DenseTensor* y_grad); + +template +void ElementwiseFMinGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad, + DenseTensor* y_grad); + +template +void MaximumGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void MinimumGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void ElementwiseHeavisideGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void ElementwisePowGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..65040e1937a59a399549ae3637f1115e2d13bdec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_kernel.h @@ -0,0 +1,180 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { + +template +void FMaxKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void FMinKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void MaximumRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void MaximumKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void MinimumRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void MinimumKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void RemainderRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void RemainderKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void FloorDivideRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void FloorDivideKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void ElementwisePowRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void ElementwisePowKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +void ElementwiseHeavisideRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void ElementwiseHeavisideKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Maximum(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + MaximumKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +template +DenseTensor Minimum(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + MinimumKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +template +DenseTensor Remainder(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + RemainderKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +template +DenseTensor FloorDivide(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + FloorDivideKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +template +DenseTensor ElementwiseHeaviside(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + ElementwiseHeavisideKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +template +DenseTensor ElementwisePow(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + ElementwisePowKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9cbd5040666cf825a3b65c2bdf64291bbf522841 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_grad_kernel.h @@ -0,0 +1,60 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void MultiplyGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void MultiplyDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + const paddle::optional& ddx, + const paddle::optional& ddy, + int axis, + DenseTensor* dx, + DenseTensor* dy, + DenseTensor* ddout); + +template +void MultiplyTripleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + const paddle::optional& ddx, + const paddle::optional& ddy, + const DenseTensor& d_dx, + const DenseTensor& d_dy, + const paddle::optional& d_ddout, + int axis, + DenseTensor* d_x, + DenseTensor* d_y, + DenseTensor* d_dout, + DenseTensor* d_ddx, + DenseTensor* d_ddy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..608ae95d2ba4b8ee4a3f9b38d3387faafc8589ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_multiply_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { + +template +void MultiplyRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void MultiplyKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Multiply(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + MultiplyKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..536d859b46a7b31f544ee26e5892059947ed548d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_grad_kernel.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { +template +void SubtractGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + int axis, + DenseTensor* dx, + DenseTensor* dy); + +template +void SubtractDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& y, + const DenseTensor& dout, + const paddle::optional& ddx, + const paddle::optional& ddy, + int axis, + DenseTensor* ddout); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1f6c4383df5d8661a766600a1f969aa6ffb90231 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/elementwise_subtract_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { + +template +void SubtractRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int axis, + DenseTensor* out); + +template +void SubtractKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +template +DenseTensor Subtract(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + ElementwiseInferMeta(x, y, &meta_out); + SubtractKernel(dev_ctx, x, y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..40ffe6ec886c447a1d5f762cdbe01c95edb39764 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_grad_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void EmbeddingGradKernel(const Context& ctx, + const DenseTensor& input, + const DenseTensor& weight, + const DenseTensor& out_grad, + int64_t padding_idx, + DenseTensor* weight_grad); + +template +void EmbeddingSparseGradKernel(const Context& ctx, + const DenseTensor& input, + const DenseTensor& weight, + const DenseTensor& out_grad, + int64_t padding_idx, + SelectedRows* weight_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cd7d675d6dc6cd7d71486437d9c56c4e73431af1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/embedding_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EmbeddingKernel(const Context& ctx, + const DenseTensor& inputx, + const DenseTensor& weight, + int64_t padding_idx, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/empty_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/empty_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..163179e578d9a39e9df34b3551eafc6777168f79 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/empty_kernel.h @@ -0,0 +1,65 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/infermeta/nullary.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void EmptyKernel(const Context& dev_ctx, + const IntArray& shape, + DataType dtype, + DenseTensor* out); + +template +void EmptyLikeKernel(const Context& dev_ctx, + const DenseTensor& x, + DataType dtype, + DenseTensor* out); + +template +DenseTensor Empty(const Context& dev_ctx, DenseTensorMeta&& meta) { + phi::DenseTensor dense_out; + dense_out.set_meta(meta); + dev_ctx.Alloc(&dense_out, dense_out.dtype()); + return dense_out; +} + +template +DenseTensor Empty(const Context& dev_ctx, const IntArray& shape) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DataType dtype = paddle::experimental::CppTypeToDataType::Type(); + CreateInferMeta(shape, dtype, &meta_out); + EmptyKernel(dev_ctx, shape, dtype, &dense_out); + return dense_out; +} + +template +DenseTensor EmptyLike(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DataType dtype = paddle::experimental::CppTypeToDataType::Type(); + CreateLikeInferMeta(x, dtype, &meta_out); + EmptyLikeKernel(dev_ctx, x, dtype, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8957fcaf79b9a0a83323682ffa6efaf28f5362bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_grad_kernel.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ErfGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9a7e7f8f0f3b47bc0fed75e61a2cae5b26fe7733 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erf_kernel.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Erf Kernel. + * The equation is: + * $$ + * f(x) = \frac{2}{\sqrt{\pi}} \int_{0}^{x}e^{- \eta^{2}}d\eta + * $$ + * + * The input `x` can carry the LoD (Level of Details) information, + * or not. And the output shares the LoD information with input `x`. + * @param ctx device context + * @param x The input tensor of erf kernel + * @param out The output tensor of erf kernel + */ +template +void ErfKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..67e70ad38caf4f74864500757b1f733188dbbc86 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ErfinvGradKernel(const Context& ctx, + const DenseTensor& out, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3ddb1ecbdfd80b9ea2d1fa51e0de42d85376ada6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/erfinv_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief This kernel is used to compute inverse error function of x. + * + * The equation is: + * $$erfinv(x) = {ndtri({x \over 2} + 0.5)} \over {\sqrt{2}}$$ + * + * The input `x` can carry the LoD (Level of Details) information, + * or not. And the output shares the LoD information with `x` + * @param ctx device context + * @param x the input tensor of erfinv + * @param out the output tensor of erfinv + */ +template +void ErfinvKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..675e03c42a34732bf313a1a497e067170f828e33 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ExpandAsGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& target_shape, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6bc6c73e737d788c515b6e423eaf8eb30467772a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_as_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ExpandAsKernel(const Context& ctx, + const DenseTensor& x, + const paddle::optional& y, + const std::vector& target_shape, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a734498b9870df182c2b483a224f8a32e48142a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void ExpandGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& shape, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..930240db6ccca737d9bc7435587895848c3c35e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/expand_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void ExpandKernel(const Context& ctx, + const DenseTensor& x, + const IntArray& shape, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/exponential_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/exponential_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..736baacca4cc9b3013388f13fc0690684638b408 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/exponential_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ExponentialKernel(const Context &dev_ctx, + const DenseTensor &x, + float lambda, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eye_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eye_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c7c2a627d705b4064e22f6f5d0064c5ccbd67426 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/eye_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void EyeKernel(const Context& ctx, + const Scalar& num_rows, + const Scalar& num_columns, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8f5237f1fd08c7aa8c492dbbbc32dab6ebae2fc6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_grad_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void FFTC2CGradKernel(const Context& ctx, + const DenseTensor& out_grad, + const std::vector& axes, + const std::string& normalization, + bool forward, + DenseTensor* x_grad); + +template +void FFTC2RGradKernel(const Context& ctx, + const DenseTensor& out_grad, + const std::vector& axes, + const std::string& normalization, + bool forward, + int64_t last_dim_size, + DenseTensor* x_grad); + +template +void FFTR2CGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& axes, + const std::string& normalization, + bool forward, + bool onesided, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6105ec4d0b3ec9e72bf4842ac192c312badc48a1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fft_kernel.h @@ -0,0 +1,47 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void FFTC2CKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + DenseTensor* out); + +template +void FFTC2RKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + int64_t last_dim_size, + DenseTensor* out); + +template +void FFTR2CKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& axes, + const std::string& normalization, + bool forward, + bool onesided, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e1d55364945e65672977dda3b8585f6eac22b890 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FillDiagonalGradKernel(const Context& ctx, + const DenseTensor& out_grad, + float value, + int offset, + bool wrap, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6d4dc78e8240f04019e7f829113adda621f1ffad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void FillDiagonalKernel(const Context& ctx, + const DenseTensor& x, + float value, + int offset, + bool wrap, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c44d782593d9dd6dc5bf2693e4b5b4864d9b5228 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_grad_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FillDiagonalTensorGradKernel(const Context &ctx, + const DenseTensor &out_grad, + int64_t offset, + int dim1, + int dim2, + DenseTensor *x_grad); + +void CalMatDims(phi::DDim out_dims, + int dim1, + int dim2, + int64_t *offset, + int64_t *new_dims, + int64_t *strides, + int64_t *matoffset); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9d6c8da93edb52af20b152ed8a08c896ec4ef800 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_diagonal_tensor_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FillDiagonalTensorKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + int64_t offset, + int dim1, + int dim2, + DenseTensor* out); + +void CalMatDims(phi::DDim out_dims, + int dim1, + int dim2, + int64_t* offset, + int64_t* new_dims, + int64_t* strides, + int64_t* matoffset); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8e43d996489cbae84e15e4e6379a37b524954981 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FillGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + const Scalar& value, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9af3f465303b3636dc8f3ca12f0179375027de91 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fill_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FillKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& value, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..abd120e69b2e9ba0f6a6ce09bc0909f8520adcb7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_grad_kernel.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FlattenGradKernel(const Context& dev_ctx, + const DenseTensor& xshape, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..808af7d9b7beedfc01da7ac53234d9b469c5239f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flatten_kernel.h @@ -0,0 +1,50 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void FlattenKernel(const Context& dev_ctx, + const DenseTensor& x, + int start_axis, + int stop_axis, + DenseTensor* out); + +template +void FlattenWithXShape(const Context& dev_ctx, + const DenseTensor& x, + int start_axis, + int stop_axis, + DenseTensor* out, + DenseTensor* xshape); + +template +DenseTensor Flatten(const Context& dev_ctx, + const DenseTensor& x, + int start_axis, + int stop_axis) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + FlattenInferMeta(x, start_axis, stop_axis, &meta_out); + FlattenKernel(dev_ctx, x, start_axis, stop_axis, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flip_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flip_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4470486fec0fb6ba1e176d9696bf43b559b62485 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/flip_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FlipKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2e8614484aa040232b4a4c7ff16c422383ce8ba9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FoldGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& output_sizes, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + DenseTensor* x_grad); +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3fd6281b2cc7f4fa0523159f9b832dc70c3a1a9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/fold_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FoldKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& output_sizes, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + DenseTensor* out); +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..eaca698d763d294e69717514939730cef9d029cf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_grad_kernel.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FrameGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + int frame_length, + int hop_length, + int axis, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..66a6cff3472690274d73c47ab0dec40e44843b3a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frame_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void FrameKernel(const Context& dev_ctx, + const DenseTensor& x, + int frame_length, + int hop_length, + int axis, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..65db8dd9e0a108acfc45e218fa5dacffe5d36832 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FrobeniusNormGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + const std::vector& axis, + bool keep_dim, + bool reduce_all, + DenseTensor* dx); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..30122cb416094df06a934a930286af8f20ca47b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/frobenius_norm_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void FrobeniusNormKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& axis, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/full_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/full_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..228e862a09c7906816c6120f4928897ba96608d3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/full_kernel.h @@ -0,0 +1,89 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/nullary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void FullKernel(const Context& dev_ctx, + const IntArray& shape, + const Scalar& val, + DataType dtype, + DenseTensor* out); + +template +void FullLikeKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& val, + DataType dtype, + DenseTensor* out); + +// In order to be compatible with fill_constant_batch_size_like op +// that are still used in the 2.x APIs +template +void FullBatchSizeLikeKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& shape, + const Scalar& val, + DataType dtype, + int x_batch_size_dim, + int out_batch_size_dim, + DenseTensor* out); + +template +void Full(const Context& dev_ctx, + const IntArray& shape, + const Scalar& val, + DenseTensor* out) { + FullKernel(dev_ctx, + shape, + val, + paddle::experimental::CppTypeToDataType::Type(), + out); +} + +template +DenseTensor Full(const Context& dev_ctx, + const IntArray& shape, + const Scalar& val) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DataType dtype = paddle::experimental::CppTypeToDataType::Type(); + CreateInferMeta(shape, dtype, &meta_out); + FullKernel(dev_ctx, shape, val, dtype, &dense_out); + return dense_out; +} + +template +DenseTensor FullLike(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& val) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + DataType dtype = paddle::experimental::CppTypeToDataType::Type(); + CreateLikeInferMeta(x, dtype, &meta_out); + FullLikeKernel(dev_ctx, x, val, dtype, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e53da7b471c7b82efef2319915cc57537ee824b5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GatherGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& out_grad, + const Scalar& axis, + bool overwrite, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..78ac09125b69298c59622fc69469ba8d28cae919 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GatherKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + const Scalar& axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..050034714957fe749d6608243dfedc4d30d66e88 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GatherGradNdKernel(const Context &ctx, + const DenseTensor &x, + const DenseTensor &index, + const DenseTensor &out_grad, + DenseTensor *x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d2393eb3b0709345cb2d3ec63d739cb223a79683 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_nd_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GatherNdKernel(const Context &ctx, + const DenseTensor &x, + const DenseTensor &index, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_tree_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_tree_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b3e6ffbc4297a2ae6a067e6b1ec5f2f88f7ef2ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gather_tree_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GatherTreeKernel(const Context &dev_ctx, + const DenseTensor &ids, + const DenseTensor &parents, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gaussian_random_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gaussian_random_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7424ad484a1fdde61912210b83aad31605e82615 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gaussian_random_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void GaussianRandomKernel(const Context& ctx, + const IntArray& shape, + float mean, + float std, + int seed, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fd70e8d54bc8d004373efd1874f4b07a9ebde6a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES // use M_2_SQRTPI on Windows +#endif + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GeluGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + bool approximate, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bc106a04031fbcc2a96209e170d60eda8cc7b5e1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gelu_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES // use M_2_SQRTPI on Windows +#endif + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +#define GELU_CONSTANT 0.044715 + +template +void GeluKernel(const Context& dev_ctx, + const DenseTensor& x, + bool approximate, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/generate_proposals_v2_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/generate_proposals_v2_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c2fc2677039f9a8ba22a41063374d903d968abb7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/generate_proposals_v2_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GenerateProposalsV2Kernel(const Context& ctx, + const DenseTensor& scores, + const DenseTensor& bbox_deltas, + const DenseTensor& im_shape, + const DenseTensor& anchors, + const DenseTensor& variances, + int pre_nms_top_n, + int post_nms_top_n, + float nms_thresh, + float min_size, + float eta, + bool pixel_offset, + DenseTensor* rpn_rois, + DenseTensor* rpn_roi_probs, + DenseTensor* rpn_rois_num); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_reindex_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_reindex_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..12a742006ee7324baa91ac79fb94a911b0de5e4c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_reindex_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphReindexKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& neighbors, + const DenseTensor& count, + const paddle::optional& hashtable_value, + const paddle::optional& hashtable_index, + bool flag_buffer_hashtable, + DenseTensor* reindex_src, + DenseTensor* reindex_dst, + DenseTensor* out_nodes); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_sample_neighbors_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_sample_neighbors_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..065c7f141225de08651b51b712ddfecf29028178 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_sample_neighbors_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphSampleNeighborsKernel( + const Context& dev_ctx, + const DenseTensor& row, + const DenseTensor& col_ptr, + const DenseTensor& x, + const paddle::optional& eids, + const paddle::optional& perm_buffer, + int sample_size, + bool return_eids, + bool flag_perm_buffer, + DenseTensor* out, + DenseTensor* out_count, + DenseTensor* out_eids); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1b618c6fede21fcefbe6d2a45512cd7b0a74cf8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void GraphSendRecvGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const paddle::optional& out, + const paddle::optional& dst_count, + const DenseTensor& out_grad, + const std::string& reduce_op, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..023e86064ff512d365efe4dabd0f2c9f2aeed2a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_recv_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphSendRecvKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const std::string& reduce_op, + const IntArray& out_size, + DenseTensor* out, + DenseTensor* dst_count); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..74050d126259dcc9e368275bcda24244b0a6ddb8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_grad_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void GraphSendUERecvGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const paddle::optional& out, + const paddle::optional& dst_count, + const DenseTensor& out_grad, + const std::string& message_op, + const std::string& reduce_op, + DenseTensor* x_grad, + DenseTensor* y_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a308a78800f3a0e53eaec75ec036915b8b4f0b0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_ue_recv_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphSendUERecvKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const std::string& message_op, + const std::string& reduce_op, + const IntArray& out_size, + DenseTensor* out, + DenseTensor* dst_count); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fa2285627a4b72e6150fd482afd9a913d495b6cb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_grad_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphSendUVGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const DenseTensor& out_grad, + const std::string& message_op, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7b723122c1a7f81754341667914b53e782d38402 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/graph_send_uv_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GraphSendUVKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& src_index, + const DenseTensor& dst_index, + const std::string& message_op, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..50a8d5be260bd387476467e2cdddaeb59f943b9b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GridSampleGradKernel(const Context &dev_ctx, + const DenseTensor &x, + const DenseTensor &grid, + const DenseTensor &out_grid, + const std::string &mode, + const std::string &padding_mode, + bool align_corners, + DenseTensor *x_grad, + DenseTensor *grid_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2e1e9b508649b22de086a103537f4984b7f693e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/grid_sample_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GridSampleKernel(const Context &dev_ctx, + const DenseTensor &x, + const DenseTensor &grid, + const std::string &mode, + const std::string &padding_mode, + bool align_corners, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cc404f0213252ab4a3c52187ebab29f6f29d851b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_grad_kernel.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GroupNormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& scale, + const paddle::optional& bias, + const DenseTensor& y, + const DenseTensor& mean, + const DenseTensor& variance, + const DenseTensor& d_y, + float epsilon, + int groups, + const std::string& data_layout, + DenseTensor* d_x, + DenseTensor* d_scale, + DenseTensor* d_bias); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8a8812d2a1784b1d487ca5a673d3b2af7b859ca1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/group_norm_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/backends/gpu/gpu_decls.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void GroupNormKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& scale, + const paddle::optional& bias, + float epsilon, + int groups, + const std::string& data_layout, + DenseTensor* y, + DenseTensor* mean, + DenseTensor* variance); + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) +template +class GroupNormDirectCUDAFunctor { + public: + void operator()(gpuStream_t stream, + const T* input, + std::vector input_shape, + const T* bias, + const T* scale, + T* temp_mean, + T* temp_variance, + int groups, + float eps, + T* output, + T* mean, + T* variance, + const DataLayout data_layout); +}; +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e3f02d90fcb6ad347468fc4943d6ab445cb1c5f0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void GumbelSoftmaxGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& dout, + int axis, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4ba1e56142d9bd427fee72187a771db75b69d4c2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/gumbel_softmax_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void GumbelSoftmaxKernel(const Context& dev_ctx, + const DenseTensor& x, + float temperature, + bool hard, + int axis, + DenseTensor* out); + +template +void GumbelSoftmaxInferKernel(const Context& dev_ctx, + const DenseTensor& x, + float temperature, + bool hard, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c0da8faadd592135f370c4c6aa8ed9e5dec5ed60 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_grad_kernel.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void HierarchicalSigmoidGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& w, + const DenseTensor& label, + const paddle::optional& path, + const paddle::optional& code, + const paddle::optional& bias, + const DenseTensor& pre_out, + const DenseTensor& out_grad, + int num_classes, + bool remote_prefetch, + int trainer_id, + const std::vector& height_sections, + const std::vector& epmap, + const std::vector& table_names, + bool is_sparse, + DenseTensor* x_grad, + DenseTensor* w_grad, + DenseTensor* bias_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e32306b645a6fb13b34651c502a16e699616ff25 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/hierarchical_sigmoid_kernel.h @@ -0,0 +1,40 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void HierarchicalSigmoidKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& w, + const DenseTensor& label, + const paddle::optional& path, + const paddle::optional& code, + const paddle::optional& bias, + int num_classes, + bool remote_prefetch, + int trainer_id, + const std::vector& height_sections, + const std::vector& epmap, + const std::vector& table_names, + bool is_sparse, + DenseTensor* out, + DenseTensor* pre_out, + DenseTensor* w_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/histogram_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/histogram_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0020f7b0435da268da7fcb1ac550b2e02d2235fa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/histogram_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void HistogramKernel(const Context& dev_ctx, + const DenseTensor& input, + int64_t bins, + int min, + int max, + DenseTensor* output); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c6246b1553197993e7c4cba2342120fa81f98ac4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void HuberLossGradKernel(const Context& dev_ctx, + const DenseTensor& residual, + const DenseTensor& out_grad, + float delta, + DenseTensor* input_grad, + DenseTensor* label_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3533a9ec6ded525f304e68aa510b57f9989ccce9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/huber_loss_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void HuberLossKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + float delta, + DenseTensor* out, + DenseTensor* residual); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..02422fd936bda391940a29c14d6e7d2886592aed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void IdentityLossGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const int reduction, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..895b565894b2255a5e74fc8c3ca75c097f08d2ad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/identity_loss_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void IdentityLossKernel(const Context& dev_ctx, + const DenseTensor& x, + const int reduction, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/increment_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/increment_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7c5bc2a20279106905edca0209f325cf2c7f1e78 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/increment_kernel.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IncrementKernel(const Context& ctx, + const DenseTensor& x, + float value, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3ba130c60cebae40eff92e84d2f2deea224d6f92 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexAddGradKernel(const Context& ctx, + const DenseTensor& index, + const DenseTensor& add_value, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad, + DenseTensor* add_value_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..62693af8229426a3f54d30a21cc4472c695596f4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_add_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexAddKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& add_value, + int axis, + DenseTensor* output); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2b66076ee0a2b39c3be88762d0b4918859bd06d8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexSampleGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& out_grad, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fb43c0c6c5f97c6d47381c72786c6e44441e7762 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_sample_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexSampleKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& index, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c3dc1595989bf2879c3e20187eaa53b6df75a7f0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexSelectGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& out_grad, + int dim, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..124b6897311575223859fba882488a535a6310f4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/index_select_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IndexSelectKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& index, + int dim, + DenseTensor* output); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2a661a3fd3853befe12fdb64b15c8164271d59da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_grad_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void InstanceNormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& scale, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const DenseTensor& y_grad, + float epsilon, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +template +void InstanceNormDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& scale, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const DenseTensor& dy, + const paddle::optional& ddx, + const paddle::optional& ddscale, + const paddle::optional& ddbias, + float epsilon, + DenseTensor* dx, + DenseTensor* dscale, + DenseTensor* ddy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f1bbe1287a26d87112cdf44f2bc7a29ee403a4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/instance_norm_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void InstanceNormKernel(const Context& dev_ctx, + const DenseTensor& x, + const paddle::optional& scale, + const paddle::optional& bias, + float epsilon, + DenseTensor* y, + DenseTensor* saved_mean, + DenseTensor* saved_variance); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b8eefad61a7689000f89f6e6433629a69861c232 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_grad_kernel.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BilinearInterpGradKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const DenseTensor& out_grad, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c531461c12e295d691959720a8ffa88dbefcf4b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/interpolate_kernel.h @@ -0,0 +1,106 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void BilinearInterpKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* output); + +template +void NearestInterpKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* output); + +template +void TrilinearInterpKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* output); + +template +void LinearInterpKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* output); + +template +void BicubicInterpKernel( + const Context& ctx, + const DenseTensor& x, + const paddle::optional& out_size, + const paddle::optional>& size_tensor, + const paddle::optional& scale_tensor, + const std::string& data_layout, + int out_d, + int out_h, + int out_w, + const std::vector& scale, + const std::string& interp_method, + bool align_corners, + int align_mode, + DenseTensor* output); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3fccb87897ab009b2075f1f3f4e47c499d5d6d9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void InverseGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& out_grad, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2fa90b6f179eb61633fc3a22b35d8e1139452158 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/inverse_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void InverseKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/is_empty_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/is_empty_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3bcf6f9054ed50a81f9b237e754d7d8aed51353a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/is_empty_kernel.h @@ -0,0 +1,24 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IsEmptyKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isclose_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isclose_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8c468da055082005568002952f695ebedda31c3c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isclose_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void IscloseKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const Scalar& rtol, + const Scalar& atol, + bool equal_nan, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isfinite_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isfinite_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e695a8e0742235a1da3fa829f82fd96c05fada34 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/isfinite_kernel.h @@ -0,0 +1,31 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +#define DEFINE_ISFINITE_KERNEL(isfinite_kernel) \ + template \ + void isfinite_kernel( \ + const Context& ctx, const DenseTensor& x, DenseTensor* out); + +DEFINE_ISFINITE_KERNEL(IsinfKernel) +DEFINE_ISFINITE_KERNEL(IsnanKernel) +DEFINE_ISFINITE_KERNEL(IsfiniteKernel) +#undef DEFINE_ISFINITE_KERNEL + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6e05c7992eb6114186f766ae799e3fd86823fd5e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void KLDivLossGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& label, + const DenseTensor& d_out, + const std::string& reduction, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7c6cc231c94806b4fd6d7dec8211c1cc98532fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kldiv_loss_kernel.h @@ -0,0 +1,30 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void KLDivLossKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& label, + const std::string& reduction, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3daa9dcfba9f0d89bd8dec88905f0ddb321f630a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void KronGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4451ac757a9534f4a48db97da81acc2047c26be2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kron_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void KronKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c2eac0a3e3de936535c881033974891d0ec24c54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_grad_kernel.h @@ -0,0 +1,30 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void KthvalueGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const DenseTensor& d_out, + int k, + int axis, + bool keepdim, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4809b9af4832f5d9c036d26adfc6ba5c7a808889 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/kthvalue_kernel.h @@ -0,0 +1,30 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void KthvalueKernel(const Context& dev_ctx, + const DenseTensor& x, + int k, + int axis, + bool keepdim, + DenseTensor* out, + DenseTensor* indices); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..993e967814aee4a23511d03698752412134ea590 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void LabelSmoothGradKernel(const Context& ctx, + const DenseTensor& out_grad, + float epsilon, + DenseTensor* label_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2db35e1bff346a9fdee2fadc611412fa4b3cbadf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/label_smooth_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void LabelSmoothKernel(const Context& ctx, + const DenseTensor& label, + const paddle::optional& prior_dist, + float epsilon, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lamb_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lamb_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f69948453d9b62c3a0f28fd841f527ae6dbd7bda --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lamb_kernel.h @@ -0,0 +1,44 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LambKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + float weight_decay, + float beta1, + float beta2, + float epsilon, + bool multi_precision, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7d7cd13109be1ec26f33fd88970f8439b6d68389 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_grad_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LayerNormGradKernel(const Context& ctx, + const DenseTensor& x, + const paddle::optional& scale, + const paddle::optional& bias, + const DenseTensor& mean, + const DenseTensor& variance, + const DenseTensor& out_grad, + float epsilon, + int begin_norm_axis, + bool is_test, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..26c04b61af96b96f53f1c6ea787500a62eb85df4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/layer_norm_kernel.h @@ -0,0 +1,51 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/backends/gpu/gpu_decls.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LayerNormKernel(const Context& ctx, + const DenseTensor& x, + const paddle::optional& scale, + const paddle::optional& bias, + float epsilon, + int begin_norm_axis, + bool is_test, + DenseTensor* out, + DenseTensor* mean, + DenseTensor* variance); + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) +template +class LayerNormDirectCUDAFunctor { + public: + void operator()(gpuStream_t stream, + const T* input, + std::vector input_shape, + const T* bias, + const T* scale, + T* output, + T* mean, + T* variance, + int begin_norm_axis, + float eps); +}; +#endif + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b44af08f03dbe9afab72065bed03e8b5a7959075 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LerpGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& weight, + const DenseTensor& out, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0f73c5bcf9ed628ca81e6d723afb1ab8b769d0d2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lerp_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LerpKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& weight, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d7f0ef399eaa0f5296c13db4d537c39f79ccf786 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_grad_kernel.h @@ -0,0 +1,27 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LgammaGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& d_out, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f61b3a1ce859eeee77d49ecb38ee0e96c3a9f0ee --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lgamma_kernel.h @@ -0,0 +1,26 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LgammaKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/linspace_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/linspace_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ca2b940aef965b6772f113a6a96f84d64fb3d1a2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/linspace_kernel.h @@ -0,0 +1,26 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LinspaceKernel(const Context& ctx, + const DenseTensor& start, + const DenseTensor& stop, + const DenseTensor& number, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6853140b19b907e0dc427e14b88f77726157612f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogLossGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + const DenseTensor& out_grad, + float epsilon, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cd16c0f2c7ce2cb4711250c44fd3081e3b05e867 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_loss_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogLossKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + float epsilon, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6336bc14105bb55deacbfdc20a69a56c6ceca81a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogSoftmaxGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2caaa86d46c35888c5aaa944019c070f0dd64e17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/log_softmax_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogSoftmaxKernel(const Context& dev_ctx, + const DenseTensor& x, + int axis, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logcumsumexp_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logcumsumexp_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e78a79550657eb67c07c8bbd5a34b2e5e4e9f3dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logcumsumexp_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogcumsumexpGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& d_out, + int axis, + bool flatten, + bool exclusive, + bool reverse, + DenseTensor* d_x); +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logical_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logical_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3ccc03a5b598a0a939cde00d74e1f6126808f655 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logical_kernel.h @@ -0,0 +1,38 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +#define DECLEAR_LOGICAL_BINARY_KERNEL(type) \ + template \ + void Logical##type##Kernel(const Context& dev_ctx, \ + const DenseTensor& x, \ + const DenseTensor& y, \ + DenseTensor* out); + +DECLEAR_LOGICAL_BINARY_KERNEL(And) +DECLEAR_LOGICAL_BINARY_KERNEL(Or) +DECLEAR_LOGICAL_BINARY_KERNEL(Xor) +#undef DECLEAR_LOGICAL_BINARY_KERNEL + +template +void LogicalNotKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logspace_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logspace_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..59862514e78aec7e9d04822d418e9d51a5e3903c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logspace_kernel.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogspaceKernel(const Context& ctx, + const DenseTensor& start, + const DenseTensor& stop, + const DenseTensor& number, + const DenseTensor& base, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..170f1c6c557ea0db3c1b90299d537963a60778ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogsumexpGradKernel(const Context& ctx, + const DenseTensor& in, + const DenseTensor& out, + const DenseTensor& out_grad, + const std::vector& axis, + bool keepdim, + bool reduce_all, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ba1b18230fa52845bede77331cadd8d61bbd5244 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/logsumexp_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LogsumexpKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& axis, + bool keepdim, + bool reduce_all, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lstsq_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lstsq_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1ad58615b4b3d08179a96a82c5fa87131f0e8921 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lstsq_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LstsqKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const Scalar& rcond, + const std::string& driver, + DenseTensor* solution, + DenseTensor* residuals, + DenseTensor* rank, + DenseTensor* singular_values); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..23d4ac26840fa1b694605407b54123d76253c556 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LUGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& pivots, + const DenseTensor& out_grad, + bool pivot, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..636bfd0683f7f5fd95c443faa4d15ea9856fb290 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LUKernel(const Context& dev_ctx, + const DenseTensor& x, + bool pivot, + DenseTensor* out, + DenseTensor* pivots, + DenseTensor* infos); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..056f2096d96e5876f76ede256c79e62e634648b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LUUnpackGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& pivots, + const DenseTensor& l, + const DenseTensor& u, + const DenseTensor& pmat, + const DenseTensor& l_grad, + const DenseTensor& u_grad, + bool unpack_ludata, + bool unpack_pivots, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..48acc3cc566ebf2ca093abc5050d6bf59d3ecf3e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/lu_unpack_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void LUUnpackKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& pivots, + bool unpack_ludata, + bool unpack_pivots, + DenseTensor* pmat, + DenseTensor* l, + DenseTensor* u); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2d0715149751edd586ef1910309295e651446e53 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { +template +void MarginCrossEntropyGradKernel(const Context& dev_ctx, + const DenseTensor& logits, + const DenseTensor& label, + const DenseTensor& softmax, + const DenseTensor& loss_grad, + bool return_softmax, + int ring_id, + int rank, + int nranks, + float margin1, + float margin2, + float margin3, + float scale, + DenseTensor* logits_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..df58256597695b09fbca54436ee5e93d5b82b473 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/margin_cross_entropy_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MarginCrossEntropyKernel(const Context& dev_ctx, + const DenseTensor& logits, + const DenseTensor& label, + bool return_softmax, + int ring_id, + int rank, + int nranks, + float margin1, + float margin2, + float margin3, + float scale, + DenseTensor* softmax, + DenseTensor* loss); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f8aa06024c58e664b1ddc850dc8ef1de5b55c202 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void MaskedSelectGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& mask, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d6fef8569d751ba1060288a173f895e44f35f4aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/masked_select_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void MaskedSelectKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& mask, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..47c6acdcb392309e3ca7849298f89b0e5cf9ef1e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_grad_kernel.h @@ -0,0 +1,87 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void MatmulGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + bool transpose_x, + bool transpose_y, + DenseTensor* dx, + DenseTensor* dy); + +template +void MatmulDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + const paddle::optional& ddx, + const paddle::optional& ddy, + bool transpose_x, + bool transpose_y, + DenseTensor* dx, + DenseTensor* dy, + DenseTensor* ddout); + +template +void MatmulTripleGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + const DenseTensor& ddx, + const DenseTensor& ddy, + const paddle::optional& d_dx, + const paddle::optional& d_dy, + const paddle::optional& d_ddout, + bool transpose_x, + bool transpose_y, + DenseTensor* out_d_x, + DenseTensor* out_d_y, + DenseTensor* out_d_dout, + DenseTensor* out_d_ddx, + DenseTensor* out_d_ddy); + +template +void MatmulWithFlattenGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + int x_num_col_dims, + int y_num_col_dims, + DenseTensor* x_grad, + DenseTensor* y_grad); + +template +void MatmulWithFlattenDoubleGradKernel( + const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + const paddle::optional& x_grad_grad, + const paddle::optional& y_grad_grad, + int x_num_col_dims, + int y_num_col_dims, + DenseTensor* x_grad, + DenseTensor* y_grad, + DenseTensor* out_grad_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7f4de8d5792ace6728282556c380c804db220a17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matmul_kernel.h @@ -0,0 +1,54 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void MatmulKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + bool transpose_x, + bool transpose_y, + DenseTensor* out); + +// In order to be compatible with `mul` op in fluid, +// it is no longer used in 2.x API +template +void MatmulWithFlattenKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + int x_num_col_dims, + int y_num_col_dims, + DenseTensor* out); + +template +DenseTensor Matmul(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + bool transpose_x = false, + bool transpose_y = false) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + MatmulInferMeta(x, y, transpose_x, transpose_y, &meta_out); + MatmulKernel(dev_ctx, x, y, transpose_x, transpose_y, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_nms_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_nms_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..895829a712f7f98e8accd30b1cae84d6666d6653 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_nms_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MatrixNMSKernel(const Context& ctx, + const DenseTensor& bboxes, + const DenseTensor& scores, + float score_threshold, + int nms_top_k, + int keep_top_k, + float post_threshold, + bool use_gaussian, + float gaussian_sigma, + int background_label, + bool normalized, + DenseTensor* out, + DenseTensor* index, + DenseTensor* roisnum); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4f70cf6e34d491bacf00c575bc28c1d7a39f859a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MatrixPowerGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + int n, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..39a1bc85e3fe77e79ef8172f1bc4a22029b83d9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_power_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MatrixPowerKernel(const Context& ctx, + const DenseTensor& x, + int n, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6edea2723e589340f2c6dc3cfb0be6f895bf08bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MatrixRankKernel(const Context& dev_ctx, + const DenseTensor& x, + float tol, + bool use_default_tol, + bool hermitian, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_tol_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_tol_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..351358dfa04aa7ad2091ad0e01bc63e50046eda0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/matrix_rank_tol_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MatrixRankTolKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& atol_tensor, + bool use_default_tol, + bool hermitian, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1ee4e8cc89676f49fa84e3a6e481e8e5d687614e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MaxOutGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + int groups, + int axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e582575678d4d17d3f9d55183e58043fc6444225 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/maxout_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MaxOutKernel(const Context& dev_ctx, + const DenseTensor& x, + int groups, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bede8ac9e049a4f9ca28b33426b90abb612fd47f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MeanAllGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a332526643710a49104296e6be339d9548498b14 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mean_all_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +// In order to be compatible with `mean` op in fluid, +// it is no longer used in 2.x API. It can not implement by call +// ReduceMeanKernel because ReduceMeanKernel doesn't support bfloat16 now, +// maybe we can unify this kernel to ReduceMeanKernel series in the future +template +void MeanAllKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/memcpy_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/memcpy_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..72a58982b05c373a487257c09063d64840a598ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/memcpy_kernel.h @@ -0,0 +1,49 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" + +namespace phi { + +// used in new executor, for memory copy from host to device +template +void MemcpyH2DKernel(const Context& dev_ctx, + const DenseTensor& x, + int dst_place_type, + DenseTensor* out); + +// used in new executor, for memory copy from device to host +template +void MemcpyD2HKernel(const Context& dev_ctx, + const DenseTensor& x, + int dst_place_type, + DenseTensor* out); + +template +void MemcpyD2HMultiIOKernel(const Context& dev_ctx, + const TensorArray& array, + int dst_place_type, + TensorArray* out_array); + +template +void MemcpyKernel(const Context& dev_ctx, + const DenseTensor& x, + int dst_place_type, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/merged_momentum_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/merged_momentum_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9f21b988b4bedd0a07431e503a922deb6b1dcb1a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/merged_momentum_kernel.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MergedMomentumKernel( + const Context& dev_ctx, + const std::vector& param, + const std::vector& grad, + const std::vector& velocity, + const std::vector& learning_rate, + const paddle::optional>& master_param, + float mu, + bool use_nesterov, + const std::vector& regularization_method, + const std::vector& regularization_coeff, + bool multi_precision, + float rescale_grad, + std::vector param_out, + std::vector velocity_out, + std::vector master_param_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9ce98db63cb5d599fb5cc3b851a3bbb3fe78ad46 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MeshgridGradKernel(const Context& ctx, + const std::vector& inputs, + const std::vector& outputs_grad, + std::vector inputs_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d468c7c1398aa0dad86f564bb366725ed3d8d6d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/meshgrid_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MeshgridKernel(const Context& ctx, + const std::vector& inputs, + std::vector outputs); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ccde8c3648fa556401f1937c78039743daf43f4c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ModeGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const DenseTensor& out_grad, + int axis, + bool keepdim, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..831c4369304e5c5d27cddf01bcba021745bf7083 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mode_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ModeKernel(const Context& dev_ctx, + const DenseTensor& x, + int axis, + bool keepdim, + DenseTensor* out, + DenseTensor* indices); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/momentum_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/momentum_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..172b345af163c513e78711e64033ed64aaa28237 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/momentum_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void MomentumDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& grad, + const DenseTensor& velocity, + const DenseTensor& learning_rate, + const paddle::optional& master_param, + float mu, + bool use_nesterov, + const std::string& regularization_method, + float regularization_coeff, + bool multi_precision, + float rescale_grad, + DenseTensor* param_out, + DenseTensor* velocity_out, + DenseTensor* master_param_out); + +template +void MomentumSparseKernel(const Context& dev_ctx, + const DenseTensor& param, + const SelectedRows& grad, + const DenseTensor& velocity, + const DenseTensor& learning_rate, + const paddle::optional& master_param, + float mu, + bool use_nesterov, + const std::string& regularization_method, + float regularization_coeff, + bool multi_precision, + float rescale_grad, + DenseTensor* param_out, + DenseTensor* velocity_out, + DenseTensor* master_param_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f495c7045207991aa51d109fd41600d71f9b76ca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultiDotGradKernel(const Context& ctx, + const std::vector& x, + const DenseTensor& out_grad, + std::vector x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..09866e8dde5eaa8adc773a481c98178da8ffed9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multi_dot_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultiDotKernel(const Context& ctx, + const std::vector& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiclass_nms3_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiclass_nms3_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2d1dd383930888fd2712bdf91f4d039bcf425f1a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiclass_nms3_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultiClassNMSKernel(const Context& ctx, + const DenseTensor& bboxes, + const DenseTensor& scores, + const paddle::optional& rois_num, + float score_threshold, + int nms_top_k, + int keep_top_k, + float nms_threshold, + bool normalized, + float nms_eta, + int background_label, + DenseTensor* out, + DenseTensor* index, + DenseTensor* nms_rois_num); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multinomial_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multinomial_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bef22d196687f2fd246ff8c75fa3912806e28e67 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multinomial_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultinomialKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& num_samples, + bool replacement, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b32c9dbe100584f7076f34d848d3e5112315f83d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultiplexGradKernel(const Context& ctx, + const DenseTensor& ids, + const DenseTensor& out_grad, + std::vector ins_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..341c6d5cabb7ce1d67090c7533bc8c45622f4786 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/multiplex_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MultiplexKernel(const Context& ctx, + const std::vector& ins, + const DenseTensor& ids, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..edc73d89367ff9d074bbbaef5af38f8222e57de9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_grad_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +// Using dimensional constraints on matrix multiplication, it is +// straight-forward to check the following table for when X and Y +// are both matrices. +// +// dX = | dOut vec^T +// dVec = | X^T dOut +template +void MvGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& vec, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* vec_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ad2794d9e425a56d3f675afbde897d72e9bfb597 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/mv_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief This kernel is used to perform matrix vector multiplication + * of the input tensors `X` and `Vec` + * @param ctx device context + * @param x The matrix input of mv + * @param vec The vector input of mv + * @param out The output of mv + */ +template +void MvKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& vec, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e8fb01b7060a78f2ea4ebfff6ba33aff2bf762cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void NanmedianGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& median_index, + const DenseTensor& out_grad, + const IntArray& axes, + bool keep_dim, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4bb382a443144f598da132ebb0213b7317e68b76 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nanmedian_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void NanmedianKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + bool keep_dim, + DenseTensor* out, + DenseTensor* medians); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b682edc24df0e90a7e4bd66408889b7a77f46c83 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void NllLossGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& label, + const paddle::optional& weight, + const DenseTensor& total_weight, + const DenseTensor& d_out, + int64_t ignore_index, + const std::string& reduction, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cffaa3148602519dab258737e03b58dc22554ad0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nll_loss_kernel.h @@ -0,0 +1,33 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void NllLossRawKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& label, + const paddle::optional& weight, + int64_t ignore_index, + const std::string& reduction, + DenseTensor* out, + DenseTensor* total_weight); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nms_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nms_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e8511f4c4a49f37ffbac5058f14d17ab1bae203c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/nms_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/hostdevice.h" + +namespace phi { + +HOSTDEVICE static inline int64_t CeilDivide(int64_t n, int64_t m) { + return (n + m - 1) / m; +} + +template +HOSTDEVICE inline bool CalculateIoU(const T* const box_1, + const T* const box_2, + const float threshold) { + auto box_1_x0 = box_1[0], box_1_y0 = box_1[1]; + auto box_1_x1 = box_1[2], box_1_y1 = box_1[3]; + auto box_2_x0 = box_2[0], box_2_y0 = box_2[1]; + auto box_2_x1 = box_2[2], box_2_y1 = box_2[3]; + + auto inter_box_x0 = box_1_x0 > box_2_x0 ? box_1_x0 : box_2_x0; + auto inter_box_y0 = box_1_y0 > box_2_y0 ? box_1_y0 : box_2_y0; + auto inter_box_x1 = box_1_x1 < box_2_x1 ? box_1_x1 : box_2_x1; + auto inter_box_y1 = box_1_y1 < box_2_y1 ? box_1_y1 : box_2_y1; + + auto inter_width = + inter_box_x1 - inter_box_x0 > 0 ? inter_box_x1 - inter_box_x0 : 0; + auto inter_height = + inter_box_y1 - inter_box_y0 > 0 ? inter_box_y1 - inter_box_y0 : 0; + auto inter_area = inter_width * inter_height; + auto union_area = (box_1_x1 - box_1_x0) * (box_1_y1 - box_1_y0) + + (box_2_x1 - box_2_x0) * (box_2_y1 - box_2_y0) - inter_area; + return inter_area / union_area > threshold; +} + +template +void NMSKernel(const Context& dev_ctx, + const DenseTensor& boxes, + float threshold, + DenseTensor* output); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a67e757ba510f03f211cf383cc68b38e3099ae3c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void NormGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& norm, + const DenseTensor& out_grad, + int axis, + float epsilon, + bool is_test, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a8c3c65a7689fb288577df1a0d97faf264d3be43 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/norm_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void NormKernel(const Context& ctx, + const DenseTensor& x, + int axis, + float epsilon, + bool is_test, + DenseTensor* out, + DenseTensor* norm); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/one_hot_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/one_hot_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..79af88473b278ee93b5c3272768a722cc2935561 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/one_hot_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void OneHotKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& num_classes, + DenseTensor* out); + +template +void OneHotRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& depth, + DataType dtype, + bool allow_out_of_range, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..62fcce2e44f15db2a0cc243b71f699e50239ee16 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void OverlapAddGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + int hop_length, + int axis, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..46df3c8e097d67cb041e071e9220d6537fcc354f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/overlap_add_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void OverlapAddKernel(const Context& dev_ctx, + const DenseTensor& x, + int hop_length, + int axis, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a64c8ceee4f2e63a8b918f6d591237068faa6ef2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PNormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + float porder, + int axis, + float epsilon, + bool keepdim, + bool asvector, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8e9af01ba33286a21708b9a51070dbb4e6ae675a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/p_norm_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PNormKernel(const Context& dev_ctx, + const DenseTensor& x, + float porder, + int axis, + float epsilon, + bool keepdim, + bool asvector, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bbad50f4d83bd46197d677b11e5b7466794421ad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Pad3dGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& paddings, + const std::string& mode, + float pad_value, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1589ff854ec23d2a9dbbfa42200b73e33e58cf9f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad3d_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Pad3dKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& paddings, + const std::string& mode, + float pad_value, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..aef30f8f5e21dc09a6e14559475bf9b5100d612e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_grad_kernel.h @@ -0,0 +1,29 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PadGradKernel(const Context& dev_ctx, + const DenseTensor& d_out, + const std::vector& paddings, + const Scalar& pad_value, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f3496edba0ff5f1e75dbe332aad7c0d80f8f6c92 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pad_kernel.h @@ -0,0 +1,29 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PadKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& paddings, + const Scalar& pad_value, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c42731d354b5a8cb324aae0f96b61bc12c7cdd2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PixelShuffleGradKernel(const Context& ctx, + const DenseTensor& out_grad, + int upscale_factor, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bf7c9f07224a06919992d271f0d71b4ffe2f63cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_shuffle_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PixelShuffleKernel(const Context& ctx, + const DenseTensor& x, + int upscale_factor, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..43919d9e63f9423a207445fcf92362a772a0619b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PixelUnshuffleGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + int downscale_factor, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f91326d384c39ea7cf6f932d2dfc3bfd36089db7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pixel_unshuffle_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PixelUnshuffleKernel(const Context& dev_ctx, + const DenseTensor& x, + int downscale_factor, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3ef60d7a5167682383a01079c8f809cc1ea32fe9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void PoissonGradKernel(const Context& ctx, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b2b2ea97f014e4308848bdd3bffb5b89548b14c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/poisson_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief This kernel generate random value that obey poisson distribution. + * @param ctx device context + * @param x The input tensor of poisson kernel + * @param out The output tensor of poisson kernel, it has the same shape and + * dtype with input. Each element corresponds to input tensor + */ +template +void PoissonKernel(const Context& ctx, const DenseTensor& x, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..64ad99a6d3eae1f4d99c88aa32ccffb798c637e4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_grad_kernel.h @@ -0,0 +1,147 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Pool2dGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* dx); + +template +void Pool2dGradGPUDNNKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* dx); + +template +void Pool2dDoubleGradKernel(const Context& ctx, + const DenseTensor& x, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void Pool2dDoubleGradGPUDNNKernel(const Context& ctx, + const DenseTensor& x, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void MaxPool2dWithIndexGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& mask, + const DenseTensor& dout, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + DenseTensor* dx); + +template +void Pool3dGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* dx); + +template +void Pool3dGradGPUDNNKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& dout, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* dx); + +template +void MaxPool3dWithIndexGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& mask, + const DenseTensor& dout, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c1a7dd471a02f755fbe6d146b4ee6b501c9ecd97 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/pool_kernel.h @@ -0,0 +1,107 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Pool2dKernel(const Context& ctx, + const DenseTensor& x, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void Pool2dGPUDNNKernel(const Context& ctx, + const DenseTensor& x, + const IntArray& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void MaxPool2dWithIndexKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + DenseTensor* out, + DenseTensor* mask); + +template +void Pool3dKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void Pool3dGPUDNNKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool ceil_mode, + bool exclusive, + const std::string& data_format, + const std::string& pooling_type, + bool global_pooling, + bool adaptive, + const std::string& padding_algorithm, + DenseTensor* out); + +template +void MaxPool3dWithIndexKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& kernel_size, + const std::vector& strides, + const std::vector& paddings, + bool global_pooling, + bool adaptive, + DenseTensor* out, + DenseTensor* mask); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d36f529640d7d0f61cd4e720d76987613e00c3c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_grad_kernel.h @@ -0,0 +1,31 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PReluGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& alpha, + const DenseTensor& out_grad, + const std::string& data_format, + const std::string& mode, + DenseTensor* x_grad, + DenseTensor* alpha_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7e273ecfd2fa1165c7bb335ebfc313e4da7ba8eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prelu_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PReluKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& alpha, + const std::string& data_format, + const std::string& mode, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives.h new file mode 100644 index 0000000000000000000000000000000000000000..2265077d51bb8bf5287929d4f1864e1961519a0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives.h @@ -0,0 +1,720 @@ +// Copyright (c) 2021 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. + +#pragma once + +#ifdef PADDLE_WITH_CUDA +#include +#endif +#ifdef PADDLE_WITH_HIP +#include +#endif + +#include "paddle/fluid/platform/device/gpu/gpu_device_function.h" +#include "paddle/phi/common/float16.h" + +namespace phi { +namespace kps { +namespace details { + +#ifdef __HIPCC__ +constexpr int kReduceMaxThread = 256; +constexpr int kWarpSize = 64; +#else +constexpr int kReduceMaxThread = 128; +constexpr int kWarpSize = 32; +#endif + +// kGlobalMode: block reduce, each block gets an output; +// kLocalMode: thread reduce, each thread gets an output; +enum ReduceMode { kGlobalMode, kLocalMode }; + +template +class MPTypeTrait { + public: + using Type = T; +}; + +template <> +class MPTypeTrait { + public: + using Type = float; +}; + +/** + * @brief Will be used in BlockYReduce, get the index of reduce_num in shared + * memory. + */ +__device__ __forceinline__ int SharedMemoryIndex(int index) { + return (threadIdx.y + index) * blockDim.x + threadIdx.x; +} + +template +__device__ __forceinline__ T WarpReduce(T val, ReduceOp reducer) { + unsigned mask = 0u; + CREATE_SHFL_MASK(mask, true); + for (int stride = details::kWarpSize / 2; stride > 0; stride >>= 1) { + T temp = paddle::platform::CudaShuffleDownSync(mask, val, stride); + val = reducer(val, temp); + } + return val; +} + +/* e.g. + * |---------block---------| + * |warp0|warp1|warp2|warp3| + * |0~31|32~63|64~95|96~127| ---->blockDim.x = 128 + * \|/ \|/ \|/ \|/ ---->1. First WarpReduce in each warp + * res0 res1 res2 res3 ---->2. Store result of each warp to shared memory + * \ \ / / ---->3. Load the result above from shared memory + * res to warp0 and process the second WarpReduce + */ + +/** + * @brief BlockXReduce reduce along blockDim.x. + */ +template +__device__ __forceinline__ T BlockXReduce(T val, ReduceOp reducer) { + __syncthreads(); + using details::kWarpSize; + __shared__ T shared[2 * kWarpSize]; + int block_dim_x = blockDim.x; + if (blockDim.x > kWarpSize) { + block_dim_x = blockDim.x / kWarpSize; + int lane = threadIdx.x % kWarpSize; + int tid = threadIdx.y * blockDim.x + threadIdx.x; + int wid = tid / kWarpSize; + int bid = threadIdx.y; + val = WarpReduce(val, reducer); + if (lane == 0) { + shared[wid] = val; + } + __syncthreads(); + val = shared[bid * block_dim_x + lane]; + } + + unsigned mask = 0u; + CREATE_SHFL_MASK(mask, true); + for (int stride = 1; stride < block_dim_x; stride <<= 1) { + T temp = paddle::platform::CudaShuffleDownSync(mask, val, stride); + val = reducer(val, temp); + } + if (threadIdx.x == 0) { + shared[threadIdx.y] = val; + } + __syncthreads(); + return shared[threadIdx.y]; +} + +/** + * @brief BlockYReduce reduce along blockDim.y. + */ +template +__device__ __forceinline__ T BlockYReduce(T val, ReduceOp reducer) { + __shared__ T shared_memory[1024]; + shared_memory[SharedMemoryIndex(0)] = val; + for (int stride = blockDim.y / 2; stride > 0; stride >>= 1) { + __syncthreads(); + if (threadIdx.y < stride && threadIdx.y + stride < blockDim.y) { + T temp = shared_memory[SharedMemoryIndex(stride)]; + val = reducer(val, temp); + } + shared_memory[SharedMemoryIndex(0)] = val; + } + __syncthreads(); + return shared_memory[threadIdx.x]; +} + +/** + * @brief Swap data + */ +template +__device__ __forceinline__ void Swap(T* first_value, T* second_value) { + T t_value; + t_value = (*first_value); + (*first_value) = (*second_value); + (*second_value) = t_value; +} + +/** + * @brief Swap data according to monotonic_type. + */ +template +__device__ __forceinline__ void Comparator(T* first_value, + T* second_value, + int monotonic_type) { + if (((*first_value) > (*second_value)) == monotonic_type) { + Swap(first_value, second_value); + } +} + +/** + * @brief Swap data and data index according to monotonic_type. + */ +template +__device__ __forceinline__ void ComparatorWithIndex(T* first_value, + + T* second_value, + IndexType* first_index, + IndexType* second_index, + int monotonic_type) { + if ((*first_value > (*second_value)) == monotonic_type) { + // swap value + Swap(first_value, second_value); + // swap index + Swap(first_index, second_index); + } +} + +/** + * @brief get the last pow of 2 + */ +__device__ inline int GetLastPow2(int n) { + n |= (n >> 1); + n |= (n >> 2); + n |= (n >> 4); + n |= (n >> 8); + n |= (n >> 16); + return std::max(1, n - (n >> 1)); +} + +} // namespace details + +/** + * @brief Perform unary calculation according to OpFunc. Shape of input and + * output are the same. + * + * @template paraments + * InT: The data type of in. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE OutT operator()(const InT& a) const { + * return ...; + * } + * }; + * + * @param: + * out: The register pointer of out, the size is NX * NY. + * in: The register pointer of in, the size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseUnary(OutT* out, + const InT* in, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; idx++) { + out[idx] = static_cast(compute(in[idx])); + } +} + +/** + * @brief Binary calculation according to OpFunc. Shape of The input and output + * are the same. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns computed by each thread. + * NY: The number of data rows computed by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * + * @param: + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * NY. + * in2: The register pointer of second input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseBinary(OutT* out, + const InT* in1, + const InT* in2, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx])); + } +} + +template +__device__ __forceinline__ void ElementwiseBinary( + OutT* out, const InT* in1, const InT* in2, OpFunc compute, int read_lens) { +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx])); + } +} + +/** + * @brief Ternary calculation according to OpFunc. Shape of input and output + * are the same. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b, const InT& c) + * const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * NY. + * in2: The register pointer of second input, size is NX * NY. + * in3: The register pointer of third input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseTernary( + OutT* out, const InT* in1, const InT* in2, const InT* in3, OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx], in3[idx])); + } +} + +/** + * @brief Multivariate calculation according to OpFunc. Shape of inputs and + * output are the same. + * + * @template paraments + * InT: The data type of in1, in2 and in3. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * Arity: The size of ins. + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT* args) const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * ins: A pointers of array consisting of multiple inputs. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseAny(OutT* out, + InT (*ins)[NX * NY], + OpFunc compute) { + InT args[Arity]; +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { +#pragma unroll + for (int j = 0; j < Arity; ++j) { + args[j] = ins[j][idx]; + } + out[idx] = static_cast(compute(args)); + } +} + +/** + * @brief Binary calculation according to OpFunc. Shape of in1 and in2 are the + * different. Shape of in1 is [1, NX], but in2's shape is [NY, NX], the output + * shape is [NY, NX]. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE OutT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * 1. + * in2: The register pointer of second input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void CycleBinary(OutT* out, + const InT* in1, + const InT* in2, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX; idx++) { +#pragma unroll + for (int idy = 0; idy < NY; idy++) { + out[idx + idy * NX] = + static_cast(compute(in1[idx], in2[idx + idy * NX])); + } + } +} + +/** + * @brief The Reduce provides collective methods for computing a parallel + * reduction of items partitioned across a CUDA block and intra thread. When + * ReduceMode == kLocalMode, thread reduce along nx. When ReduceMode == + * kGlobalMode, use shared memory to reduce between threads. + * + * @template paraments + * T: The type of data. + * NX: The number of data continuously loaded by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * ReduceFunctor: Compute functor which has an operator() as following + * template + * struct ReduceFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * ReduceMode: Reduce mode, can be kLocalMode, kGlobalMode. + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in: The register pointer of in, the size is NX * NY. + * reducer: Compute function which was declared like ReduceFunctor(). + * reduce_last_dim: if the last dim gets involved in reduction. + */ +template +__device__ __forceinline__ void Reduce(T* out, + const T* in, + ReduceFunctor reducer, + bool reduce_last_dim) { + int block_index = blockDim.y; + + if (Mode == details::ReduceMode::kGlobalMode) { + bool block_reduce_y = (!reduce_last_dim) && (block_index > 1); + // when reduce is not required for the last dim, and reduce num has been + // split into multiple threads + if (block_reduce_y) { +#pragma unroll + for (int i = 0; i < NY * NX; i++) { // reduce along blockdim.y + out[i] = details::BlockYReduce(out[i], reducer); + } + } + + // when last dimension need to be reduced + if (reduce_last_dim) { +#pragma unroll + for (int i = 0; i < NY * NX; i++) { // reduce along blockDim.x + out[i] = details::BlockXReduce(out[i], reducer); + } + } + } else { // else kLocalMode +#pragma unroll + for (int i = 0; i < NY; ++i) { +#pragma unroll + for (int j = 0; j < NX; ++j) { + out[i] = reducer(out[i], in[i * NX + j]); + } + } + } +} + +/* + * @brief Fill register with a constant according to OpFunc + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * GPU was supported. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()() + * const { + * return a; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseConstant(OutT* out, OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; idx++) { + out[idx] = static_cast(compute()); + } +} + +/* + * @brief Get ReturnsCount random data fromm compute according to state, state + * can be curandStatePhilox4_32_10_t, hiprandStatePhilox4_32_10_t which has beed + * initialized. + * + * @template paraments + * StateType: the type of state, can be curandStatePhilox4_32_10_t or + * hiprandStatePhilox4_32_10_t. + * OutT: the type of out register. + * ReturnsCount: The number of random data generated by OpFunc. + * GPU was supported. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(StateType state) + * const { + * return ranomd(state); // Returns ReturnsCount random numbers with + * data type T + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ + +template +__device__ __forceinline__ void ElementwiseRandom(OutT* out, + OpFunc compute, + StateType* state) { + auto random_tuple = compute(state); +#pragma unroll + for (int i = 0; i < ReturnsCount; i++) { + out[i] = static_cast((&random_tuple.x)[i]); + } +} + +/* + * @brief Complete the prefix and in the block, each thread calculates 2 data, + * the size of out and in is 2, and BlockDim.x must be less then 512. + * + * @template paraments + * InT: the type of input register. + * OutT: the type of out register. + * GPU was supported. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(T a, T b) + * const { + * return a + b; + * } + * }; + * + * @param + * out: The register pointer of out, the size is 2; + * in: The register pointer of input, the size is 2; + * compute: Compute function which was declared like OpFunc(). + */ + +#define SHARED_SIZE_LIMIT 512 +template +__device__ __forceinline__ void Cumsum(OutT* out, + const InT* in, + OpFunc compute) { + constexpr int kSize = SHARED_SIZE_LIMIT * 2 + (SHARED_SIZE_LIMIT * 2) / 32; + __shared__ InT temp[kSize]; + int stride_size = blockDim.x; + int tidx = threadIdx.x; + temp[tidx + tidx / 32] = in[0]; + temp[stride_size + tidx + (stride_size + tidx) / 32] = in[1]; + for (int stride = 1; stride <= stride_size; stride *= 2) { + __syncthreads(); + int index = (tidx + 1) * 2 * stride - 1; + if (index < (blockDim.x * 2)) { + temp[index + index / 32] = + compute(temp[index + index / 32], + temp[index - stride + (index - stride) / 32]); + } + } + for (int stride = (blockDim.x * 2) / 4; stride > 0; stride /= 2) { + __syncthreads(); + int index = (tidx + 1) * 2 * stride - 1; + if ((index + stride) < (blockDim.x * 2)) { + temp[index + stride + (stride + index) / 32] = + compute(temp[index + stride + (stride + index) / 32], + temp[index + (index) / 32]); + } + } + + __syncthreads(); + out[0] = static_cast(temp[tidx + tidx / 32]); + out[1] = + static_cast(temp[tidx + stride_size + (tidx + stride_size) / 32]); +} +#undef SHARED_SIZE_LIMIT + +/* + * @brief Sort data in this block, each thread calculates 2 data, the size of + * out and in is 2, and BlockDim.x must be less then 512. + * + * @template paraments + * InT: the type of input register. + * OutT: the type of out register. + * GPU was supported. + * + * @param + * out: The register pointer of out, the size is 2. + * in: The register pointer of input, the size is 2. + * num: The num of this block + * monotonic_type: if monotonic_type = 1 then sorted in ascending order, eles + * sorted in escending. + */ +#define SHARED_SIZE_LIMIT 1024 +// each thread load 2 data from global memory so SHARED_SIZE_LIMIT must +// larger than blockDim.x * 2 +template +__device__ __forceinline__ void Sort(OutT* out, + const InT* in, + int num, + int monotonic_type) { + int upper_bound = blockDim.x; + // update upper_bound + upper_bound = std::min(details::GetLastPow2(num), upper_bound); + // shareMem for value and index num must smaller than SHARED_SIZE_LIMIT / 2 + __shared__ InT value[SHARED_SIZE_LIMIT]; + int stride_size = blockDim.x; + // shareMem's size must larger than blockDim * 2 + // Copy value from in + value[threadIdx.x] = in[0]; + value[threadIdx.x + stride_size] = in[1]; + // make bitonicSort + for (int size = 2; size < upper_bound; size <<= 1) { + int bitonic_type = (threadIdx.x & (size / 2)) != 0; + for (int stride = size / 2; stride > 0; stride >>= 1) { + __syncthreads(); + int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1)); + details::Comparator(&value[pos], &value[pos + stride], bitonic_type); + } + } + // last sort + for (int stride = stride_size; stride > 0; stride >>= 1) { + __syncthreads(); + int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1)); + // last sort when monotonic_type = 1 then increase + details::Comparator(&value[pos], &value[pos + stride], monotonic_type); + } + __syncthreads(); + out[0] = static_cast(value[threadIdx.x]); + out[1] = static_cast(value[threadIdx.x + stride_size]); +} + +/* + * @brief Sort data with data_index in this block, each thread calculates 2 + * data, the size of out and in is 2, and BlockDim.x must be less then 512. + * + * @template paraments + * InT: The type of input register. + * OutT: The type of out register. + * IndexType: The type of index. + * GPU was supported. + * + * @param + * out: The register pointer of out, the size is 2. + * out_index: The register pointer of out_index, the size is 2. + * in: The register pointer of input, the size is 2. + * in_index: The register pointer of in_index, the size is 2. + * num: The num of this block. + * monotonic_type: if monotonic_type = 1 then sorted in ascending order, eles + * sorted in escending. + */ +template +__device__ __forceinline__ void Sort(OutT* out, + IndexType* out_index, + const InT* in, + IndexType* in_index, + int num, + int monotonic_type) { + int upper_bound = blockDim.x; + // update upper_bound + upper_bound = std::min(details::GetLastPow2(num), upper_bound); + // shareMem for value and index num must smaller than SHARED_SIZE_LIMIT / 2 + __shared__ InT value[SHARED_SIZE_LIMIT]; + // shareMem's size must larger than blockDim * 2 + __shared__ IndexType index[SHARED_SIZE_LIMIT]; + // Copy value and index from in and in_index + int stride_size = blockDim.x; + value[threadIdx.x] = in[0]; + value[threadIdx.x + stride_size] = in[1]; + // index + index[threadIdx.x] = in_index[0]; + index[threadIdx.x + stride_size] = in_index[1]; + // make bitonicSort + for (int size = 2; size < upper_bound; size <<= 1) { + int bitonic_type = (threadIdx.x & (size / 2)) != 0; + for (int stride = size / 2; stride > 0; stride >>= 1) { + __syncthreads(); + int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1)); + details::ComparatorWithIndex(&value[pos], + &value[pos + stride], + &index[pos], + &index[pos + stride], + bitonic_type); + } + } + + for (int stride = stride_size; stride > 0; stride >>= 1) { + __syncthreads(); + int pos = 2 * threadIdx.x - (threadIdx.x & (stride - 1)); + // last sort when monotonic_type = 1 then increase + details::ComparatorWithIndex(&value[pos], + &value[pos + stride], + &index[pos], + &index[pos + stride], + monotonic_type); + } + + __syncthreads(); + out[0] = static_cast(value[threadIdx.x]); + out[1] = static_cast(value[threadIdx.x + stride_size]); + out_index[0] = index[threadIdx.x]; + out_index[1] = index[threadIdx.x + stride_size]; +} + +template +HOSTDEVICE __forceinline__ void OperatorTernary( + OutT* out, const T1* in1, const T2* in2, OpFunc func, int num) { + func(out, in1, in2, num); +} + +template +HOSTDEVICE __forceinline__ void OperatorBinary(OutT* out, + const InT* in, + OpFunc func, + int num) { + func(out, in, num); +} + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives_xpu2.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives_xpu2.h new file mode 100644 index 0000000000000000000000000000000000000000..2fecebaf3d2687243d759037d6381f694f0be55c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/compute_primitives_xpu2.h @@ -0,0 +1,357 @@ +// Copyright (c) 2021 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. + +#pragma once +#include "paddle/phi/common/float16.h" +#include "xpu/kernel/cluster_header.h" +#include "xpu/kernel/debug.h" +#include "xpu/kernel/math.h" +#include "xpu/kernel/simd_header.h" + +namespace phi { +namespace kps { +namespace details { + +// kGlobalMode: block reduce, each block gets an output; +// kLocalMode: thread reduce, each thread gets an output; +enum ReduceMode { kGlobalMode, kLocalMode }; + +template +class MPTypeTrait { + public: + using Type = T; +}; + +template <> +class MPTypeTrait { + public: + using Type = float; +}; + +static inline __device__ void sync_all() { + __asm__ __volatile__( + "sync_local\t\n" + "csr_set csr3, %0\t\n" + "sync_group csr3" ::"r"(-1)); +} + +#define ncores 64 +template +__device__ void BlockXReduce(T* out, const T* data, OpFunc reducer) { + __shared__ T sum_array[ncores * VecSize]; + int core_idx = core_id() * VecSize; + mfence(); + sync_all(); + +#pragma unroll + for (int i = 0; i < VecSize; i++) { + mfence(); + sum_array[i * ncores + core_idx] = data[i]; + mfence(); + } + sync_all(); +#pragma unroll + for (int i = 0; i < VecSize; i++) { + T start = data[i * ncores]; +#pragma unroll + for (int j = 1; j < ncores; j++) { + mfence(); + T tmp = sum_array[i * ncores + j]; + mfence(); + start = reducer(start, tmp); + mfence(); + } + out[i] = start; + } + sync_all(); +} +#undef ncores + +} // namespace details + +/** + * @brief Perform unary calculation according to OpFunc. Shape of input and + * output are the same. + * + * @template paraments + * InT: The data type of in. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE OutT operator()(const InT& a) const { + * return ...; + * } + * }; + * + * @param: + * out: The register pointer of out, the size is NX * NY. + * in: The register pointer of in, the size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseUnary(OutT* out, + const InT* in, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; idx++) { + out[idx] = static_cast(compute(in[idx])); + } +} + +/** + * @brief Binary calculation according to OpFunc. Shape of The input and output + * are the same. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns computed by each thread. + * NY: The number of data rows computed by each thread. + * core_id() is used as the index. + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * + * @param: + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * NY. + * in2: The register pointer of second input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseBinary(OutT* out, + const InT* in1, + const InT* in2, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx])); + } +} + +template +__device__ __forceinline__ void ElementwiseBinary( + OutT* out, const InT* in1, const InT* in2, OpFunc compute, int read_lens) { + for (int idx = 0; idx < read_lens; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx])); + } +} + +/** + * @brief Ternary calculation according to OpFunc. Shape of input and output + * are the same. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b, const InT& c) + * const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * NY. + * in2: The register pointer of second input, size is NX * NY. + * in3: The register pointer of third input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseTernary( + OutT* out, const InT* in1, const InT* in2, const InT* in3, OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { + out[idx] = static_cast(compute(in1[idx], in2[idx], in3[idx])); + } +} + +/** + * @brief Multivariate calculation according to OpFunc. Shape of inputs and + * output are the same. + * + * @template paraments + * InT: The data type of in1, in2 and in3. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * Arity: The size of ins + * OpFunc: Compute functor which has an operator() as following: + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()(const InT* args) const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * ins: A pointers of array consisting of multiple inputs. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseAny(OutT* out, + InT (*ins)[NX * NY], + OpFunc compute) { + __local__ InT args[Arity]; +#pragma unroll + for (int idx = 0; idx < NX * NY; ++idx) { +#pragma unroll + for (int j = 0; j < Arity; ++j) { + args[j] = ins[j][idx]; + } + out[idx] = static_cast(compute(args)); + } +} + +/** + * @brief Binary calculation according to OpFunc. The shape of in1 and in2 are + * different. When in1's shape is [1, NX], in2's shape is [NY, NX], then + * output's shape is [NY, NX]. + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE OutT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in1: The register pointer of fist input, size is NX * 1. + * in2: The register pointer of second input, size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void CycleBinary(OutT* out, + const InT* in1, + const InT* in2, + OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX; idx++) { +#pragma unroll + for (int idy = 0; idy < NY; idy++) { + out[idx + idy * NX] = + static_cast(compute(in1[idx], in2[idx + idy * NX])); + } + } +} + +/** + * @brief The Reduce provides collective methods for computing a parallel + * reduction of items partitioned across a CUDA block and intra thread. When + * ReduceMode == kLocalMode, thread reduce along nx. When ReduceMode == + * kGlobalMode, use shared memory to reduce between threads. + * + * @template paraments + * T: The type of data. + * NX: The number of data continuously loaded by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * core_id() is used as the index. + * ReduceFunctor: Compute functor which has an operator() as following + * template + * struct ReduceFunctor { + * HOSTDEVICE InT operator()(const InT& a, const InT& b) const { + * return ...; + * } + * }; + * ReduceMode: Reduce mode, can be kLocalMode, kGlobalMode. + * + * @param + * out: The register pointer of out, the size is NX * NY. + * in: The register pointer of in, the size is NX * NY. + * reducer: Compute function which was declared like ReduceFunctor(). + * reduce_last_dim: if the last dim gets involved in reduction. + */ +template +__device__ __forceinline__ void Reduce(T* out, + const T* in, + ReduceFunctor reducer, + bool reduce_last_dim) { + if (Mode == details::kGlobalMode) { + if (reduce_last_dim) { +#pragma unroll + for (int i = 0; i < NY * NX; i++) { // reduce along blockDim.x + details::BlockXReduce(&out[i], &in[i], reducer); + } + } + } else { // else kLocalMode +#pragma unroll + for (int i = 0; i < NY; ++i) { +#pragma unroll + for (int j = 0; j < NX; ++j) { + out[i] = reducer(out[i], in[i * NX + j]); + } + } + } +} + +/* + * @brief Fill register with a constant according to OpFunc + * + * @template paraments + * InT: The data type of in1 and in2. + * OutT: The data type of out. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * OpFunc: Compute functor which has an operator() as following + * template + * struct XxxFunctor { + * HOSTDEVICE InT operator()() + * const { + * return a; + * } + * }; + * + * @param + * out: The register pointer of out, the size is NX * NY. + * compute: Compute function which was declared like OpFunc(). + */ +template +__device__ __forceinline__ void ElementwiseConstant(OutT* out, OpFunc compute) { +#pragma unroll + for (int idx = 0; idx < NX * NY; idx++) { + out[idx] = static_cast(compute()); + } +} + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives.h new file mode 100644 index 0000000000000000000000000000000000000000..3f6148c7efd8000fb5d014a7e3433b2b756b2a96 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives.h @@ -0,0 +1,819 @@ +// Copyright (c) 2021 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. + +#pragma once +#ifdef PADDLE_WITH_CUDA +#include +#include +#endif +#ifdef PADDLE_WITH_HIP +#include +#endif +#include "paddle/phi/core/ddim.h" + +namespace phi { +namespace kps { +namespace details { + +#define INT_BITS 32 + +template +struct alignas(sizeof(T) * VecSize) VectorType { + T val[VecSize]; +}; +/** + * Fast division : Replace division in CUDA with multiplication to improve + * kernel performance. + * 1. Complete the division calculation on the CPU, and record the calculation + * results by using the divider and shift_val. + * 2. Set the divisor on the GPU through Div() to complete the calculation. + */ +struct FastDivMod { + // 1st value represents the result of input number divides by recorded divisor + // 2nd value represents the result of input number modulo by recorded divisor + using DivModT = VectorType; + + FastDivMod() {} + HOSTDEVICE FastDivMod(uint32_t d) : divisor(d) { + static_assert(sizeof(unsigned int) == 4, + "Only Support 32-bit unsigned int."); + + for (shift_val = 0; shift_val < INT_BITS; ++shift_val) { + auto shift_limit = 1 << shift_val; + if (shift_limit >= divisor) break; + } + uint64_t long_one = 1; + uint64_t temp_div = + ((long_one << INT_BITS) * ((long_one << shift_val) - divisor)) / + divisor + + 1; + multiplier = temp_div; + } + + __device__ __forceinline__ uint32_t Div(uint32_t n) const { + uint32_t t = __umulhi(n, multiplier); + return (t + n) >> shift_val; + } + + __device__ __forceinline__ DivModT Divmod(uint32_t n) const { + uint32_t q = Div(n); + DivModT result = {q, n - q * divisor}; + return result; + } + + int32_t divisor; + int32_t shift_val; + uint32_t multiplier; +}; + +/** + * Configuration of broadcast. Calculate the input data index according to the + * index of the output data. if input or output shape is [dim0, dim1] then dims + * must be [dim1, dim0]. + */ +struct BroadcastConfig { + FastDivMod divmoders[phi::DDim::kMaxRank]; + uint32_t strides[phi::DDim::kMaxRank]; + int kDims; + HOSTDEVICE BroadcastConfig() {} + + HOSTDEVICE BroadcastConfig(const std::vector& out_dims, + const std::vector& in_dims, + int dim_size) { + std::vector strides_in; + std::vector divmoders_in; + // for divmoders + divmoders_in.resize(dim_size); + for (int i = 0; i < dim_size; ++i) { + divmoders_in[i] = FastDivMod(out_dims[i]); + } + // for strides + strides_in.resize(dim_size, 1); + for (int i = 0; i < dim_size; ++i) { + strides_in[i] = in_dims[i] == 1 ? 0 : strides_in[i]; + strides_in[i] = (i != 0 && strides_in[i] != 0) + ? std::accumulate(in_dims.begin(), + in_dims.begin() + i, + 1, + std::multiplies()) + : strides_in[i]; + } + kDims = dim_size; + memcpy(strides, strides_in.data(), kDims * sizeof(uint32_t)); + memcpy(divmoders, divmoders_in.data(), kDims * sizeof(FastDivMod)); + } +}; + +template +__device__ __forceinline__ void WriteData(T* dst, + T* __restrict__ src, + int num) { + for (int i = 0; i < num; i++) { + dst[i] = src[i]; + } +} + +template +__device__ __forceinline__ void ReadData(T* dst, + const T* __restrict__ src, + int num) { + for (int i = 0; i < num; i++) { + dst[i] = src[i]; + } +} +#undef INT_BITS +} // namespace details + +/** + * @brief Read 2D data from global memory to register according to Tx type, and + * store it as Ty type into register. + * + * @template paraments + * Tx: The type of data stored in the global memory. + * Ty: The type of data that needs to be stored in registers. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size_nx: The maximum offset of the current block is size_nx elements in the + * lowest dimension. The parameters are only calculated when isboundary = true. + * size_ny: The maximum offset of the current block is size_ny elements in the + * first dimension. The parameters are only calculated when isboundary = true. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __forceinline__ void ReadData(Ty* dst, + const Tx* __restrict__ src, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny) { + int thread_offset = threadIdx.x; + int left_size_nx = size_nx - thread_offset; + + // Each branch is added for better performance + if (NX == 1 && NY == 1) { // for NX == 1 and NY == 1 + if (IsBoundary) { + if (left_size_nx > 0) { + dst[0] = static_cast(src[thread_offset]); + } + } else { + dst[0] = static_cast(src[thread_offset]); + } + } else if (NX == 1) { // for NX == 1 and NY != 1 +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + dst[idy] = static_cast(src[thread_offset + idy * stride_ny]); + } + } else if (NY == 1) { // for NY == 1 and NX != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } + dst[idx] = static_cast(src[thread_offset + idx * stride_nx]); + } + } else { // for NX != 1 and NY != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + dst[idy * NX + idx] = static_cast( + src[thread_offset + idx * stride_nx + idy * stride_ny]); + } + } + } +} + +/** + * @brief Initialize register with init_data. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: Initial value. + */ +template +__device__ __forceinline__ void Init(T* dst, T init_data) { +#pragma unroll + for (int i = 0; i < NX; i++) { + dst[i] = init_data; + } +} + +template +__device__ __forceinline__ void Init(T* dst, T init_data, int read_lens) { +#pragma unroll + for (int i = 0; i < NX; i++) { + dst[i] = init_data; + } +} + +/** + * The difference from the above function is that + * it supports different data types of inputs. + */ +template +__device__ __forceinline__ void Init(ArgsT* dst, T init_data, int read_lens) { +#pragma unroll + for (int i = 0; i < NX; i++) { + std::get(dst[i]) = init_data; + } +} + +/** + * @brief Read 1D data from global memory to register. When IsBoundary = true + * and (NX % 4 == 0 or Nx % 2 == 0), vectorized load data will be used to + * improve memory access efficiency. + * + * @template paraments + * T: The type of data. + * NX: Each thread load NX data from global memory continuously. + * NY: Each thread need to load NY rows, only NY = 1 was supported. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * IsBoundary: Whether to make an out-of-bounds judgment on access to memory. + * When the number of data processed by this block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size: The current block needs to load size data continuously. + */ +template +__device__ __forceinline__ void ReadData(T* dst, + const T* __restrict__ src, + int num) { + if (IsBoundary) { // blockDim.x * NX > num + int thread_offset = threadIdx.x * NX; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (idx + thread_offset < num) { + dst[idx] = src[thread_offset + idx]; + } + } + } else { // blockDim,x * NX < num + constexpr int kVectorSize = (NX % 4 == 0) ? 4 : (NX % 2 == 0) ? 2 : 1; + constexpr int kVectorsPerThread = NX / kVectorSize; + int thread_offset = threadIdx.x * kVectorsPerThread; + + using VecType = details::VectorType; + const VecType* vec_input = reinterpret_cast(src); + VecType vec_temp[kVectorsPerThread]; + +#pragma unroll + for (int i = 0; i < kVectorsPerThread; ++i) { + vec_temp[i] = vec_input[thread_offset + i]; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + dst[idx] = *(reinterpret_cast(vec_temp) + idx); + } + } + } +} + +template +__device__ __forceinline__ void ReadData(T* dst, + const T* __restrict__ src, + int num, + int read_lens) { + if (IsBoundary) { // blockDim.x * NX > num + int thread_offset = threadIdx.x * NX; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (idx + thread_offset < num) { + dst[idx] = src[thread_offset + idx]; + } + } + } else { // blockDim,x * NX < num + constexpr int kVectorSize = (NX % 4 == 0) ? 4 : (NX % 2 == 0) ? 2 : 1; + constexpr int kVectorsPerThread = NX / kVectorSize; + int thread_offset = threadIdx.x * kVectorsPerThread; + + using VecType = details::VectorType; + const VecType* vec_input = reinterpret_cast(src); + VecType vec_temp[kVectorsPerThread]; + +#pragma unroll + for (int i = 0; i < kVectorsPerThread; ++i) { + vec_temp[i] = vec_input[thread_offset + i]; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + dst[idx] = *(reinterpret_cast(vec_temp) + idx); + } + } + } +} +/** + * @brief Read 1D data from global memory to register. The difference + * from the above function is that it supports different data types of inputs. + * + * @template paraments + * T: The type of data. + * NX: Each thread load NX data from global memory continuously. + * NY: Each thread need to load NY rows, only NY = 1 was supported. + * ArgsT: The Type if dst, ArgsT can be std::tuple or std::tuple + * Index: The index of data stored in dst. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * IsBoundary: Whether to make an out-of-bounds judgment on access to memory. + * When the number of data processed by this block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size: The current block needs to load size data continuously. + */ +template +__device__ __forceinline__ void ReadData(ArgsT* dst, + const T* __restrict__ src, + int num, + int read_lens) { + if (IsBoundary) { // blockDim.x * NX > num + int thread_offset = threadIdx.x * NX; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (idx + thread_offset < num) { + std::get(dst[idx]) = src[thread_offset + idx]; + } + } + } else { // blockDim,x * NX < num + constexpr int kVectorSize = (NX % 4 == 0) ? 4 : (NX % 2 == 0) ? 2 : 1; + constexpr int kVectorsPerThread = NX / kVectorSize; + int thread_offset = threadIdx.x * kVectorsPerThread; + + using VecType = details::VectorType; + const VecType* vec_input = reinterpret_cast(src); + VecType vec_temp[kVectorsPerThread]; + +#pragma unroll + for (int i = 0; i < kVectorsPerThread; ++i) { + vec_temp[i] = vec_input[thread_offset + i]; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + std::get(dst[idx]) = *(reinterpret_cast(vec_temp) + idx); + } + } + } +} + +/** + * @brief Read 2D data from global memory to registers with broadcast form. + * + * @template paraments + * T: The type of data stored in the global memory. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The original input data pointer of this kernel. + * block_offset: The data offset of this block, blockDim.x * blockIdx.x * NX. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * total_num_output: Total number of original output. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __forceinline__ void ReadDataBc( + T* dst, + const T* __restrict__ src, + uint32_t block_offset, + const details::BroadcastConfig& config, + int total_num_output, + int stride_nx, + int stride_ny) { + uint32_t thread_offset = block_offset + threadIdx.x; + uint32_t index_src = 0; + +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { +#pragma unroll + for (uint32_t nx = 0; nx < NX; ++nx) { + uint32_t index_output = thread_offset + ny * stride_ny + nx * stride_nx; + index_src = 0; + if (IsBoundary) { + if (index_output >= total_num_output) { + break; + } + } +#pragma unroll + for (int i = 0; i < phi::DDim::kMaxRank; ++i) { + if (i >= config.kDims) break; + auto fast_divmoder = config.divmoders[i].Divmod(index_output); + index_output = fast_divmoder.val[0]; + index_src += fast_divmoder.val[1] * config.strides[i]; + } + dst[nx + ny * NX] = src[index_src]; + } + } +} + +/** + * @brief Read 2D data from global memory to register with reduce form. + * + * @template paraments + * T: The type of data. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The input data pointer of this block. + * block_offset: The data offset of this block, blockDim.x * blockIdx.x * NX. + * index_cal: Calculation configuration of Reduce. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * size_nx: The current block needs to load size_nx columns of data, this + * parameter will participate in the calculation when isboundary = true. + * size_ny: The current block needs to load size_ny rows of data, this parameter + * will participate in the calculation when isboundary = true. + * will be used when IsBoundary = true. + * stride_nx: Each read one element stride stride_nx columns. + * stride_ny: Each read one element stride stride_ny raws. + * reduce_last_dim: Used to indicate whether the dimension of reduce contains + * the lowest dimension. + */ +template +__device__ __forceinline__ void ReadDataReduce(Ty* dst, + const Tx* __restrict__ src, + int block_offset, + const IndexCal& index_cal, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny, + Functor func, + bool reduce_last_dim) { + int thread_offset = 0; + int left_idx = 0; + if (reduce_last_dim) { + thread_offset = threadIdx.x; + left_idx = threadIdx.y; + } else { + thread_offset = threadIdx.y; + left_idx = threadIdx.x; + } + + if (NX == 1) { +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { + if (IsBoundary) { + if (thread_offset >= size_ny) { + break; + } + } + uint32_t index_src = index_cal(thread_offset + block_offset); + dst[ny] = static_cast(func(src[index_src])); + thread_offset += stride_ny; + } + } else { +#pragma unroll + for (int nx = 0; nx < NX; ++nx) { +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { + if (IsBoundary) { + if ((thread_offset >= size_ny) || + (left_idx + nx * stride_nx >= size_nx)) { + break; + } + } + uint32_t index_src = index_cal(thread_offset + block_offset); + dst[nx + ny * NX] = static_cast(func(src[index_src])); + thread_offset += stride_ny; + } + } + } +} + +/** + * @brief Write 2D data from registers to global memory. When IsBoundary = true + * and (NX % 4 == 0 or Nx % 2 == 0), the data will be vectorized to improve the + * data loading efficiency + * + * @template paraments + * T: The type of data. + * NX: The number of data continuously writed by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The data pointer of the current block. + * src: The register pointer, the size is NX * NY. + * size: The current block needs to load size elements continuously. + */ +template +__device__ __forceinline__ void WriteData(T* dst, + T* __restrict__ src, + int num) { + if (IsBoundary) { + int thread_offset = threadIdx.x * NX; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if ((thread_offset + idx) < num) { + dst[thread_offset + idx] = src[idx]; + } + } + } else { + // Vector type + constexpr int kVectorSize = (NX % 4 == 0) ? 4 : (NX % 2 == 0) ? 2 : 1; + constexpr int kVectorsPerThread = NX / kVectorSize; + + int thread_offset = threadIdx.x * kVectorsPerThread; + using VecType = details::VectorType; + VecType* vec_dst = reinterpret_cast(dst); + VecType vec_temp[kVectorsPerThread]; +#pragma unroll + for (int idx = 0; idx < kVectorsPerThread; ++idx) { + vec_temp[idx] = *(reinterpret_cast(src) + idx); + vec_dst[thread_offset + idx] = vec_temp[idx]; + } + } +} + +template +__device__ __forceinline__ void WriteData(T* dst, + T* __restrict__ src, + int num, + int read_lens) { + if (IsBoundary) { + int thread_offset = threadIdx.x * NX; +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if ((thread_offset + idx) < num) { + dst[thread_offset + idx] = src[idx]; + } + } + } else { + // Vector type + constexpr int kVectorSize = (NX % 4 == 0) ? 4 : (NX % 2 == 0) ? 2 : 1; + constexpr int kVectorsPerThread = NX / kVectorSize; + + int thread_offset = threadIdx.x * kVectorsPerThread; + using VecType = details::VectorType; + VecType* vec_dst = reinterpret_cast(dst); + VecType vec_temp[kVectorsPerThread]; +#pragma unroll + for (int idx = 0; idx < kVectorsPerThread; ++idx) { + vec_temp[idx] = *(reinterpret_cast(src) + idx); + vec_dst[thread_offset + idx] = vec_temp[idx]; + } + } +} + +/** + * @brief Write 2D data from register to global memory according to Tx type, and + * store it as Ty type. + * + * @template paraments + * Tx: The type of data that needs to be stored in registers. + * Ty: The type of data that stored in the global memory. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The data pointer of the current block. + * src: The register pointer of the thread, the size is NX * NY. + * size_nx: The maximum offset of the current block is size_nx elements in the + * lowest dimension. The parameters are only calculated when isboundary = true. + * size_ny: The maximum offset of the current block is size_ny elements in the + * first dimension. The parameters are only calculated when isboundary = true. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __forceinline__ void WriteData(Ty* dst, + const Tx* __restrict__ src, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny) { + int thread_offset = threadIdx.x; + int left_size_nx = size_nx - thread_offset; + + // Each branch is added for better performance + if (NX == 1 && NY == 1) { // for NX == 1 and NY == 1 + if (IsBoundary) { + if (left_size_nx > 0) { + dst[thread_offset] = static_cast(src[0]); + } + } else { + dst[thread_offset] = static_cast(src[0]); + } + } else if (NX == 1) { // for NX == 1 and NY != 1 +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + dst[thread_offset + idy * stride_ny] = static_cast(src[idy]); + } + } else if (NY == 1) { // for NY == 1 and NX != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } + dst[thread_offset + idx * stride_nx] = static_cast(src[idx]); + } + } else { // for NX != 1 and NY != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + dst[thread_offset + idx * stride_nx + idy * stride_ny] = + static_cast(src[idy * NX + idx]); + } + } + } +} + +/** + * @brief Initialize register with init_data. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: The register pointer of init data, the size is NX. + */ +template +__device__ __forceinline__ void Init(T* dst, T* init_data, int num) { +#pragma unroll + for (int i = 0; i < NX; i++) { + if (IsBoundary) { + if (i >= num) { + break; + } + } + dst[i] = init_data[i]; + } +} + +/** + * @brief Read 1D data from global memory to register with broadcast form. + * + * @template paraments + * T: The type of data stored in the global memory. + * NX: The number of data continuously loaded by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The original input data pointer of kernel. + * block_offset: The data offset of this block, blockDim.x * blockIdx.x * NX; + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * total_num_output: Total number of original output. + */ +template +__device__ __forceinline__ void ReadDataBc( + T* dst, + const T* __restrict__ src, + uint32_t block_offset, + const details::BroadcastConfig& config, + int total_num_output, + int read_lens = NX) { + uint32_t thread_offset = block_offset + threadIdx.x * NX; + uint32_t index_src = 0; + +#pragma unroll + for (uint32_t nx = 0; nx < NX; ++nx) { + uint32_t index_output = thread_offset + nx; + index_src = 0; + if (IsBoundary) { + if (index_output >= total_num_output) { + break; + } + } +#pragma unroll + for (int i = 0; i < phi::DDim::kMaxRank; ++i) { + if (i >= config.kDims) break; + auto fast_divmoder = config.divmoders[i].Divmod(index_output); + index_output = fast_divmoder.val[0]; + index_src += fast_divmoder.val[1] * config.strides[i]; + } + dst[nx] = src[index_src]; + } +} + +/** + * @brief Initialize register with data index. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * NY: Number of data to initialize, NY only can be 1. + * threadIdx.x is used as the thread index. Currently only GPU was supported. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: The register pointer of init data, the size is NX. + */ +template +__device__ __forceinline__ void InitWithDataIndex(T* dst, int block_offset) { + int thread_offset = block_offset + threadIdx.x * NX; +#pragma unroll + for (int nx = 0; nx < NX; ++nx) { + dst[nx] = static_cast(thread_offset + nx); + } +} + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives_xpu2.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives_xpu2.h new file mode 100644 index 0000000000000000000000000000000000000000..14a66516f5b632c2b94343645e04d7ae5165b983 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/datamover_primitives_xpu2.h @@ -0,0 +1,1237 @@ +// Copyright (c) 2021 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. + +#pragma once +#include "xpu/kernel/cluster_header.h" +#include "xpu/kernel/debug.h" +#include "xpu/kernel/math.h" + +namespace phi { +namespace kps { +namespace details { + +static inline int RoundUpDiv(int n, int k) { return (n + k - 1) / k; } + +static inline int GetXpuReadLens(int numel, int block_num, int grid_num) { + const int buf_size = 256; + int nthreads = block_num * grid_num; + if (numel / nthreads == 1) { + return numel / nthreads * 4; + } + int read_lens = std::min(buf_size, RoundUpDiv(numel, 32 * nthreads) * 32); + return read_lens; +} + +enum class OptType { // Optimize type of calc after input shape compressed + CanNotOptimize = -1, // can not optimize, broadcast first + N_1, // just like {1} op {100} or {100} op {1} + MN_N, // just like {100} op {3, 100} or {3, 100} op {100} + MN_M, // just like {3} op {3, 100} or {3, 100} op {3} + MNK_1N1, // just like {3} op {2, 3, 100} or {2, 3, 100} op {3} + MNK_M1K, // just like {2, 1, 100} op {2, 3, 100} or {2, 3, 100} op {2, 1, + // 100} +}; + +// Rules to determine whether dimensions can be merged +// rule 0 - xshape[idx] == yshape[idx] +// rule 1 - xshape[idx] == 1 && yshape[idx] != 1 +// rule 2 - xshape[idx] != 1 && yshape[idx] == 1 +static int judge_case(int a, int b) { + if (a == b) { + return 0; + } else if (a == 1 && b != 1) { + return 1; + } else if (a != 1 && b == 1) { + return 2; + } + return -1; +} + +static bool case_is_same(int case_front, int case_back) { + if (case_front == case_back) { + return true; + } else { + return false; + } +} + +template +struct alignas(sizeof(T) * VecSize) VectorType { + T val[VecSize]; +}; + +/** + * Configuration of broadcast. Calculate the input data index according to the + * index of the output data. if input or output shape is [dim0, dim1] then dims + * must be [dim1, dim0]. + */ +#pragma pack(4) +struct BroadcastConfig { + int strides_in[phi::DDim::kMaxRank]; + int strides_out[phi::DDim::kMaxRank]; + int in_dim[phi::DDim::kMaxRank]; + int dim_after_cmp[phi::DDim::kMaxRank]; + int y_dim_after_cmp[phi::DDim::kMaxRank]; + int dim_size_after_cmp = 0; + int cmp_res = 0; + OptType cmp_type = OptType::CanNotOptimize; + int m = 1; + int n = 1; + int k = 1; + int buf_len = 0; + int kDims; + HOSTDEVICE BroadcastConfig() {} + + HOSTDEVICE BroadcastConfig(const std::vector& out_dims, + const std::vector& in_dims, + const std::vector& y_in_dims, + int dim_size) { + std::vector strides_in_tmp; + std::vector strides_out_tmp; + std::vector dim_tmp; + strides_in_tmp.resize(dim_size, 1); + strides_out_tmp.resize(dim_size, 1); + dim_tmp.resize(dim_size, 1); + for (int i = 1; i < dim_size; i++) { + strides_in_tmp[i] = strides_in_tmp[i - 1] * in_dims[i - 1]; + strides_out_tmp[i] = strides_out_tmp[i - 1] * out_dims[i - 1]; + } + + int numel_out = 1; + for (int i = 0; i < dim_size; i++) { + dim_tmp[i] = in_dims[i]; + numel_out = out_dims[i] * numel_out; + } + kDims = dim_size; + memcpy(strides_in, strides_in_tmp.data(), kDims * sizeof(int)); + memcpy(strides_out, strides_out_tmp.data(), kDims * sizeof(int)); + memcpy(in_dim, dim_tmp.data(), kDims * sizeof(int)); + + cmp_res = get_mnk_for_broadcast_ops(in_dims, y_in_dims); + get_opt_type(); + buf_len = get_buf_len(numel_out); + int numel_x = 1; + int numel_y = 1; + for (int i = 0; i < dim_size; i++) { + numel_x = in_dims[i] * numel_x; + numel_y = y_in_dims[i] * numel_y; + } + if (numel_out == numel_x && numel_out == numel_y) { + buf_len = GetXpuReadLens(numel_out, 8, 64); + } + } + + int get_buf_len(int numel) { + if (cmp_type == OptType::CanNotOptimize) { + return 256; + } + if (cmp_type == OptType::N_1) { + return kps::details::GetXpuReadLens(numel, 8, 64); + } + int max_buf_len = 512; + int buf_len = m / 16 * 16; + if (buf_len == 0) { + buf_len = m; + } + return std::min(max_buf_len, buf_len); + } + + __device__ inline int operator()(int index_output) const { + int index_src = 0; + + switch (cmp_type) { + int div, mod, tmp_index; + case OptType::MNK_M1K: + div = index_output / (m * n); + mod = index_output % (m * n) % m; + index_src = div * m + mod; + break; + case OptType::MNK_1N1: + // index_src = index_output / m % n; + index_src = index_output % (m * n) / m; + break; + case OptType::N_1: + index_src = 0; + break; + case OptType::MN_N: + index_src = index_output / m; + break; + case OptType::MN_M: + index_src = index_output % m; + break; + case OptType::CanNotOptimize: + for (int i = kDims - 1; i >= 0; --i) { + tmp_index = (index_output / strides_out[i]); + index_output = index_output - tmp_index * strides_out[i]; + index_src += (tmp_index % in_dim[i]) * strides_in[i]; + } + break; + } + return index_src; + } + + void get_opt_type() { + if (dim_size_after_cmp == 1) { + if (dim_after_cmp[0] == 1 && y_dim_after_cmp[0] != 1) { // {1} op {n} + n = y_dim_after_cmp[0]; + cmp_type = OptType::N_1; + } else if (dim_after_cmp[0] != 1 && + y_dim_after_cmp[0] == 1) { // {n} op {1} + n = dim_after_cmp[0]; + cmp_type = OptType::N_1; + } else { + cmp_type = OptType::CanNotOptimize; // xshape == yshape + } + } + if (dim_size_after_cmp == 2) { + if (dim_after_cmp[0] == 1 && dim_after_cmp[1] != 1 && + y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] != 1) { // {n} op {m, n} + m = y_dim_after_cmp[0]; + n = y_dim_after_cmp[1]; + cmp_type = OptType::MN_N; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] == 1 && + y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] != 1) { // {m} op {m, n} + m = y_dim_after_cmp[0]; + n = y_dim_after_cmp[1]; + cmp_type = OptType::MN_M; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] != 1 && + y_dim_after_cmp[0] == 1 && + y_dim_after_cmp[1] != 1) { // {m, n} op {n} + m = dim_after_cmp[0]; + n = dim_after_cmp[1]; + cmp_type = OptType::MN_N; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] != 1 && + y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] == 1) { // {m, n} op {m} + m = dim_after_cmp[0]; + n = dim_after_cmp[1]; + cmp_type = OptType::MN_M; + } else { + cmp_type = OptType::CanNotOptimize; + } + } + if (dim_size_after_cmp == 3) { + if (dim_after_cmp[0] == 1 && dim_after_cmp[1] != 1 && + dim_after_cmp[2] == 1 && y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] != 1 && + y_dim_after_cmp[2] != 1) { // {1, n, 1} op {m, n, k} + m = y_dim_after_cmp[0]; + n = y_dim_after_cmp[1]; + k = y_dim_after_cmp[2]; + cmp_type = OptType::MNK_1N1; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] != 1 && + dim_after_cmp[2] != 1 && y_dim_after_cmp[0] == 1 && + y_dim_after_cmp[1] != 1 && + y_dim_after_cmp[2] == 1) { // {m, n, k} op {1, n, 1} + m = dim_after_cmp[0]; + n = dim_after_cmp[1]; + k = dim_after_cmp[2]; + cmp_type = OptType::MNK_1N1; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] == 1 && + dim_after_cmp[2] != 1 && y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] != 1 && + y_dim_after_cmp[2] != 1) { // {m, 1, k} op {m, n, k} + m = y_dim_after_cmp[0]; + n = y_dim_after_cmp[1]; + k = y_dim_after_cmp[2]; + cmp_type = OptType::MNK_M1K; + } else if (dim_after_cmp[0] != 1 && dim_after_cmp[1] != 1 && + dim_after_cmp[2] != 1 && y_dim_after_cmp[0] != 1 && + y_dim_after_cmp[1] == 1 && + y_dim_after_cmp[2] != 1) { // {m, n, k} op {m, 1, k} + m = dim_after_cmp[0]; + n = dim_after_cmp[1]; + k = dim_after_cmp[2]; + cmp_type = OptType::MNK_M1K; + } else { + cmp_type = OptType::CanNotOptimize; + } + } + } + + int get_mnk_for_broadcast_ops(const std::vector& xshape, + const std::vector& yshape) { + int idx = 0; + int cmp_x = 0; + int cmp_y = 0; + bool is_same = false; + + std::vector xshape_after_remove_ones = xshape; + std::vector yshape_after_remove_ones = yshape; + // first step: remove excess ones + std::vector::iterator x_iter = xshape_after_remove_ones.begin(); + std::vector::iterator y_iter = yshape_after_remove_ones.begin(); + for (; x_iter != xshape_after_remove_ones.end();) { + if (*x_iter == 1 && *y_iter == 1) { + x_iter = xshape_after_remove_ones.erase(x_iter); + y_iter = yshape_after_remove_ones.erase(y_iter); + } else { + x_iter++; + y_iter++; + } + } + // second step: compress dims + int after_cmp_idx = 0; + for (int i = 0; i < 3; i++) { + cmp_x = xshape_after_remove_ones[idx]; + cmp_y = yshape_after_remove_ones[idx]; + while ((idx + 1) < xshape_after_remove_ones.size()) { + is_same = case_is_same(judge_case(xshape_after_remove_ones[idx], + yshape_after_remove_ones[idx]), + judge_case(xshape_after_remove_ones[idx + 1], + yshape_after_remove_ones[idx + 1])); + if (is_same) { + cmp_x = cmp_x * xshape_after_remove_ones[idx + 1]; + cmp_y = cmp_y * yshape_after_remove_ones[idx + 1]; + idx++; + } else { + break; + } + } + idx = idx + 1; + dim_after_cmp[after_cmp_idx] = cmp_x; + y_dim_after_cmp[after_cmp_idx] = cmp_y; + after_cmp_idx++; + if (idx == xshape_after_remove_ones.size()) { + dim_size_after_cmp = after_cmp_idx; + return 0; + } + } + return -1; // can not compress dims + } +}; +#pragma pack() + +template +__device__ __forceinline__ void WriteData(T _global_ptr_* dst, + T* src, + int num) { + if (num > 0) { + mfence_local(); + LM2GM(src, dst, num * sizeof(T)); + } +} +#undef INT_BITS + +} // namespace details + +/** + * @brief Read 2D data from global memory to register according to Tx type, and + * store it as Ty type into register. + * + * @template paraments + * Tx: The type of data stored in the global memory. + * Ty: The type of data that needs to be stored in registers. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size_nx: The maximum offset of the current block is size_nx elements in the + * lowest dimension. The parameters are only calculated when isboundary = true. + * size_ny: The maximum offset of the current block is size_ny elements in the + * first dimension. The parameters are only calculated when isboundary = true. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __inline__ void ReadData(Ty* dst, + const Tx _global_ptr_* src, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny) { + int thread_offset = core_id(); + int left_size_nx = size_nx - thread_offset; + __local__ Tx in_temp[1]; + // Each branch is added for better performance + if (NX == 1 && NY == 1) { // for NX == 1 and NY == 1 + if (IsBoundary) { + if (left_size_nx > 0) { + GM2LM(src + thread_offset, in_temp, sizeof(Tx)); + dst[0] = static_cast(in_temp[0]); + } + } else { + GM2LM(src + thread_offset, in_temp, sizeof(Tx)); + dst[0] = static_cast(in_temp[0]); + } + } else if (NX == 1) { // for NX == 1 and NY != 1 +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + mfence_local(); + GM2LM(src + thread_offset + idy * stride_ny, in_temp, sizeof(Tx)); + dst[idy] = static_cast(in_temp[0]); + } + } else if (NY == 1) { // for NY == 1 and NX != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } + mfence_local(); + GM2LM(src + thread_offset + idx * stride_nx, in_temp, sizeof(Tx)); + dst[idx] = static_cast(in_temp[0]); + } + } else { // for NX != 1 and NY != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny || idx * stride_nx >= left_size_nx) { + break; + } + } + int fix = thread_offset + idx * stride_nx + idy * stride_ny; + mfence_local(); + GM2LM(src + fix, in_temp, sizeof(Tx)); + dst[idy * NX + idx] = static_cast(in_temp[0]); + } + } + } +} + +/** + * @brief Initialize register with init_data. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: Initial value. + */ +template +__device__ __inline__ void Init(T* dst, T init_data) { +#pragma unroll + for (int i = 0; i < NX; i++) { + dst[i] = init_data; + } +} + +template +__device__ __inline__ void Init(T* dst, T init_data, int read_lens) { +#pragma unroll + for (int i = 0; i < read_lens; i++) { + dst[i] = init_data; + } +} + +/** + * The difference from the above function is that + * it supports different data types of inputs. + */ +template +__device__ __forceinline__ void Init(ArgsT* dst, T init_data, int read_lens) { + mfence(); +#pragma unroll + for (int i = 0; i < read_lens; i++) { + std::get(dst[i]) = init_data; + } +} + +/** + * @brief Read 1D data from global memory to register. When IsBoundary = true + * and (NX % 4 == 0 or Nx % 2 == 0), vectorized load data will be used to + * improve memory access efficiency. + * + * @template paraments + * T: The type of data. + * NX: Each thread load NX data from global memory continuously. + * NY: Each thread need to load NY rows, only NY = 1 was supported. + * core_id() is used as the index. + * IsBoundary: Whether to make an out-of-bounds judgment on access to memory. + * When the number of data processed by this block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size: The current block needs to load size data continuously. + */ +template +__device__ __inline__ void ReadData(T* dst, + const T _global_ptr_* src, + int num) { + mfence_local(); + int thread_offset = core_id() * NX; + if (IsBoundary) { // core_num() * NX > num +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (idx + thread_offset < num) { + GM2LM(src + thread_offset + idx, dst + idx, sizeof(T)); + } + } + } else { // core_num() * NX < num + GM2LM(src + thread_offset, dst, NX * sizeof(T)); + } +} + +template +__device__ __inline__ void ReadData(T* dst, + const T _global_ptr_* src, + int num, + int read_lens) { + int thread_offset = core_id() * read_lens; + mfence_local(); + if (IsBoundary) { // core_num() * read_lens > num +#pragma unroll + for (int idx = 0; idx < read_lens; ++idx) { + if (idx + thread_offset < num) { + GM2LM(src + thread_offset + idx, dst + idx, sizeof(T)); + } + } + } else { // core_num() * read_lens < num + GM2LM(src + thread_offset, dst, read_lens * sizeof(T)); + } +} + +/** + * @brief Read 1D data from global memory to register. The difference + * from the above function is that it supports different data types of inputs. + * + * @template paraments + * T: The type of data. + * NX: Each thread load NX data from global memory continuously. + * NY: Each thread need to load NY rows, only NY = 1 was supported. + * ArgsT: The Type if dst, ArgsT can be std::tuple or std::tuple + * Index: The index of data stored in dst. + * core_id() is used as the index. + * IsBoundary: Whether to make an out-of-bounds judgment on access to memory. + * When the number of data processed by this block is less than + * NX x NY x blockDim.x, boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The data pointer of the current block. + * size: The current block needs to load size data continuously. + */ +template +__device__ __forceinline__ void ReadData(ArgsT* dst, + const T _global_ptr_* src, + int num, + int read_lens) { + int thread_offset = core_id() * read_lens; + __local__ T in_temp[1]; + __local__ T in_vec[NX]; + if (IsBoundary) { // core_num() * read_lens > num +#pragma unroll + for (int idx = 0; idx < read_lens; ++idx) { + if (idx + thread_offset < num) { + GM2LM(src + thread_offset + idx, in_temp, sizeof(T)); + std::get(dst[idx]) = in_temp[0]; + mfence(); + } + } + } else { // core_num() * read_lens < num + GM2LM(src + thread_offset, in_vec, read_lens * sizeof(T)); +#pragma unroll + for (int idx = 0; idx < read_lens; ++idx) { + std::get(dst[idx]) = in_vec[idx]; + } + } +} + +/** + * @brief Read 2D data from global memory to registers with broadcast form. + * + * @template paraments + * T: The type of data stored in the global memory. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: Raw input data pointer of kernel. + * block_offset: Data offset of this block, core_num() * cluster_id() * NX; + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * total_num_output: Total number of original output. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __inline__ void ReadDataBc(T* dst, + const T _global_ptr_* src, + uint32_t block_offset, + const details::BroadcastConfig& config, + int total_num_output, + int stride_nx, + int stride_ny) { + uint32_t thread_offset = block_offset + core_id(); + uint32_t index_src = 0; + mfence_local(); +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { +#pragma unroll + for (uint32_t nx = 0; nx < NX; ++nx) { + uint32_t index_output = thread_offset + ny * stride_ny + nx * stride_nx; + index_src = 0; + if (IsBoundary) { + if (index_output >= (uint32_t)total_num_output) { + break; + } + } + index_src = config(index_output); + GM2LM(src + index_src, dst + nx + ny * NX, sizeof(T)); + } + } +} + +/** + * @brief Read 2D data from global memory to register with reduce form. + * + * @template paraments + * T: The type of data. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The input data pointer of this block. + * block_offset: The data offset of this block, blockDim.x * cluster_id() * NX. + * index_cal: Calculation configuration of Reduce. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * size_nx: The current block needs to load size_nx columns of data, this + * parameter will participate in the calculation when isboundary = true. + * size_ny: The current block needs to load size_ny rows of data, this parameter + * will participate in the calculation when isboundary = true. + * will be used when IsBoundary = true. + * stride_nx: Each read one element stride stride_nx columns. + * stride_ny: Each read one element stride stride_ny raws. + * reduce_last_dim: Used to indicate whether the dimension of reduce contains + * the lowest dimension. + */ +template +__device__ __forceinline__ void ReadDataReduce( + Ty* dst, + const Tx _global_ptr_* __restrict__ src, + int block_offset, + const IndexCal& index_cal, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny, + Functor func, + bool reduce_last_dim) { + __local__ Tx in_temp[1]; + int thread_offset = 0; + int left_idx = 0; + if (reduce_last_dim) { + thread_offset = core_id(); + left_idx = 0; + } else { + thread_offset = 0; + left_idx = 0; + } + + if (NX == 1) { +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { + if (IsBoundary) { + if (thread_offset >= size_ny) { + break; + } + } + uint32_t index_src = index_cal(thread_offset + block_offset); + mfence_local(); + GM2LM(src + index_src, in_temp, sizeof(Tx)); + dst[ny] = static_cast(func(in_temp[0])); + + thread_offset += stride_ny; + } + } else { +#pragma unroll + for (int nx = 0; nx < NX; ++nx) { +#pragma unroll + for (int ny = 0; ny < NY; ++ny) { + if (IsBoundary) { + if ((thread_offset >= size_ny) || + (left_idx + nx * stride_nx >= size_nx)) { + break; + } + } + uint32_t index_src = index_cal(thread_offset + block_offset); + mfence_local(); + GM2LM(src + index_src, in_temp, sizeof(Tx)); + dst[nx + ny * NX] = static_cast(func(in_temp[0])); + thread_offset += stride_ny; + } + } + } +} +/** + * @brief Write 1D data from registers to global memory. When IsBoundary = true + * and (NX % 4 == 0 or Nx % 2 == 0), the data will be vectorized to improve the + * data loading efficiency + * + * @template paraments + * T: The type of data. + * NX: The number of data continuously writed by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * core_id() is used as the index. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The data pointer of the current block. + * src: The register pointer, the size is NX * NY. + * size: The current block needs to load size elements continuously. + */ + +template +__device__ void WriteData(T _global_ptr_* dst, + const T* src, + int num, + int read_lens) { + int thread_offset = core_id() * read_lens; + mfence_local(); + + if (IsBoundary) { // core_num() * read_lens > num +#pragma unroll + for (int idx = 0; idx < read_lens; ++idx) { + if (idx + thread_offset < num) { + LM2GM(src + idx, dst + idx + thread_offset, sizeof(T)); + } + } + } else { // core_num() * read_lens < num + LM2GM(src, dst + thread_offset, read_lens * sizeof(T)); + } +} + +template +__device__ void WriteData(T _global_ptr_* dst, const T* src, int num) { + int thread_offset = core_id() * NX; + mfence_local(); + + if (IsBoundary) { // core_num() * NX > num +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (idx + thread_offset < num) { + LM2GM(src + idx, dst + idx + thread_offset, sizeof(T)); + } + } + } else { // core_num() * NX < num + mfence_local(); + LM2GM(src, dst + thread_offset, NX * sizeof(T)); + } +} + +/** + * @brief Write 2D data from register to global memory according to Tx type, and + * store it as Ty type. + * + * @template paraments + * Tx: The type of data that needs to be stored in registers. + * Ty: The type of data stored in the global memory. + * NX: The number of data columns loaded by each thread. + * NY: The number of data rows loaded by each thread. + * core_id() is used as the index. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: Data pointer of the current block. + * src: The register pointer of the thread, the size is NX * NY. + * size_nx: The current block needs to load size_nx columns of data, this + * parameter will be used when IsBoundary = true. + * size_ny: The current block needs to load size_ny rows of data. This parameter + * will be used when IsBoundary = true. + * stride_nx: Each read one element stride stride_nx elements in the last dim. + * stride_ny: Each read one element stride stride_ny elements in the first dim. + */ +template +__device__ __inline__ void WriteData(Ty _global_ptr_* dst, + const Tx* src, + int size_nx, + int size_ny, + int stride_nx, + int stride_ny) { + int thread_offset = core_id(); + int left_size_nx = size_nx - thread_offset; + __local__ Ty in_temp[1]; + + // Each branch is added for better performance + if (NX == 1 && NY == 1) { + if (IsBoundary) { + if (left_size_nx > 0) { + in_temp[0] = static_cast(src[0]); + mfence_local(); + LM2GM(in_temp, dst + thread_offset, sizeof(Ty)); + } + } else { + in_temp[0] = static_cast(src[0]); + mfence_local(); + LM2GM(in_temp, dst + thread_offset, sizeof(Ty)); + } + } else if (NX == 1) { +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + + in_temp[0] = static_cast(src[idy]); + mfence_local(); + LM2GM(in_temp, dst + thread_offset + idy * stride_ny, sizeof(Ty)); + } + } else if (NY == 1) { // for NY == 1 and NX != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } + + in_temp[0] = static_cast(src[idx]); + mfence_local(); + LM2GM(in_temp, dst + thread_offset + idx * stride_nx, sizeof(Ty)); + } + } else { // for NX != 1 and NY != 1 +#pragma unroll + for (int idx = 0; idx < NX; ++idx) { + if (IsBoundary) { + if (idx * stride_nx >= left_size_nx) { + break; + } + } +#pragma unroll + for (int idy = 0; idy < NY; ++idy) { + if (IsBoundary) { + if (idy * stride_ny >= size_ny) { + break; + } + } + in_temp[0] = static_cast(src[idx + idy * NX]); + mfence_local(); + LM2GM(in_temp, + dst + thread_offset + idx * stride_nx + idy * stride_ny, + sizeof(Ty)); + } + } + } +} + +/** + * @brief Initialize register with init_data. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: The register pointer of init data, the size is NX. + */ +template +__device__ __inline__ void Init(T* dst, T* init_data, int num) { +#pragma unroll + for (int i = 0; i < NX; i++) { + if (IsBoundary) { + if (i >= num) { + break; + } + } + dst[i] = init_data[i]; + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * {m, 1, k}-> {m, n, k} form. + * + * @template paraments + * T: Data type of register. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBcM1kMnk( + T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + int m = config.m; + int n = config.n; + + int m_pos = index_base % m; + if ((m - m_pos) < read_lens) { + int last_col = m - m_pos; + GM2LM(src + index_base, dst, last_col * sizeof(T)); + int n_pos = index_output % (m * n) / m; + int next_part_index = 0; + if (n_pos != config.n - 1) { + next_part_index = index_base / m * m; + } else { + next_part_index = (index_base / m + 1) * m; + } + GM2LM(src + next_part_index, + dst + last_col, + (read_lens - last_col) * sizeof(T)); + } else { + GM2LM(src + index_base, dst, read_lens * sizeof(T)); + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * {m, 1}-> {m, n} form. + * + * @template paraments + * T: Data type of register. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBcM1Mn( + T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + int m = config.m; + int n = config.n; + + int m_pos = index_base % m; + if ((m - m_pos) < read_lens) { + int last_col = m - m_pos; + GM2LM(src + index_base, dst, last_col * sizeof(T)); + GM2LM(src, dst + last_col, (read_lens - last_col) * sizeof(T)); + } else { + GM2LM(src + index_base, dst, read_lens * sizeof(T)); + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * {1, n}-> {m, n} form. + * + * @template paraments + * T: Data type of register. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBc1NMn( + T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + int m = config.m; + int n = config.n; + T in_temp; + + int m_pos = index_output % m; + if ((m - m_pos) < read_lens) { + int last_col = m - m_pos; + GM2LM(src + index_base, &in_temp, sizeof(T)); + for (int i = 0; i < last_col; i++) { + dst[i] = in_temp; + } + mfence_local(); + GM2LM(src + index_base + 1, &in_temp, sizeof(T)); + for (int i = 0; i < read_lens - last_col; i++) { + dst[last_col + i] = in_temp; + } + } else { + GM2LM(src + index_base, &in_temp, sizeof(T)); + for (int i = 0; i < read_lens; i++) { + dst[i] = in_temp; + } + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * {1, n, 1}-> {m, n, k} form. + * + * @template paraments + * T: Data type of register. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBc1N1Mnk( + T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + int m = config.m; + int n = config.n; + T in_temp; + + int m_pos = index_output % m; + if ((m - m_pos) < read_lens) { + int last_col = m - m_pos; + GM2LM(src + index_base, &in_temp, sizeof(T)); + for (int i = 0; i < last_col; i++) { + dst[i] = in_temp; + } + int n_pos = index_output % (m * n) / m; + int next_part_index = 0; + if (n_pos != n - 1) { + next_part_index = n_pos + 1; + } else { + next_part_index = 0; + } + mfence_local(); + GM2LM(src + next_part_index, &in_temp, sizeof(T)); + for (int i = 0; i < read_lens - last_col; i++) { + dst[last_col + i] = in_temp; + } + } else { + GM2LM(src + index_base, &in_temp, sizeof(T)); + for (int i = 0; i < read_lens; i++) { + dst[i] = in_temp; + } + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * {1}-> {n} form. + * + * @template paraments + * T: Data type of register. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBc1N(T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + T in_temp; + + GM2LM(src + index_base, &in_temp, sizeof(T)); + for (int i = 0; i < read_lens; i++) { + dst[i] = in_temp; + } +} + +/** + * @brief Read data from global memory to local memory with broadcast + * form which can not compress. + * + * @template paraments + * T: Data type of register. + * Rank: The shape size of out. eg in[1, 35], out[32, 35] then shape size is 2. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * src: The original input data pointer of kernel. + * thread_offset: The data offset of this thread. + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * total_num_output: Total number of original output. + * read_lens: The number of data continuously loaded by each thread. + */ +template +__device__ __inline__ void ReadDataBcCanNotCmp( + T* dst, + const T _global_ptr_* src, + int thread_offset, + const details::BroadcastConfig& config, + int total_num_output, + int read_lens) { + int index_output = thread_offset; + int index_base = config(index_output); + T in_temp; + int cache_size = 256; + __local__ T src_temp[cache_size]; + GM2LM(src + index_base, src_temp, cache_size * sizeof(T)); + + for (int nx = 0; nx < read_lens; ++nx) { + index_output = thread_offset + nx; + if (IsBoundary) { + if (index_output >= total_num_output) { + break; + } + } + int index_src = config(index_output); + if (index_src >= index_base && index_src < index_base + cache_size) { + in_temp = src_temp[index_src - index_base]; + } else { + mfence_local(); + GM2LM(src + index_src, &in_temp, sizeof(T)); + } + dst[nx] = in_temp; + } +} + +/** + * @brief Read 1D data from global memory to register with broadcast form. + * + * @template paraments + * T: The type of data stored in the global memory. + * NX: The number of data continuously loaded by each thread. + * NY: The number of data rows loaded by each thread, only NY = 1 was supported. + * core_id() is used as the index. + * IsBoundary: Indicates whether to perform block access storage out-of-bounds + * judgment. When the number of data processed by the block is less than + * NX x NY x core_num(), boundary judgment is required to avoid memory access + * crossing the boundary. + * + * @param: + * dst: The register pointer of the thread, the size is NX * NY. + * src: The original input data pointer of kernel. + * block_offset: The data offset of this block, core_num() * blockIdx.x * NX; + * config: Calculation configuration of broadcast. It is used to calculate the + * coordinate mapping relationship between output data and input data. + * read_lens: The number of data continuously loaded by each thread. + * total_num_output: Total number of original output. + */ +template +__device__ __inline__ void ReadDataBc(T* dst, + const T _global_ptr_* src, + uint32_t block_offset, + const details::BroadcastConfig& config, + int total_num_output, + int read_lens) { + int thread_offset = block_offset + core_id() * read_lens; + + if (config.cmp_type == details::OptType::MNK_M1K) { + ReadDataBcM1kMnk(dst, src, thread_offset, config, read_lens); + } else if (config.cmp_type == details::OptType::N_1) { + ReadDataBc1N(dst, src, thread_offset, config, read_lens); + } else if (config.cmp_type == details::OptType::MN_M) { + ReadDataBcM1Mn(dst, src, thread_offset, config, read_lens); + } else if (config.cmp_type == details::OptType::MN_N) { + ReadDataBc1NMn(dst, src, thread_offset, config, read_lens); + } else if (config.cmp_type == details::OptType::MNK_1N1) { + ReadDataBc1N1Mnk(dst, src, thread_offset, config, read_lens); + } else { + ReadDataBcCanNotCmp( + dst, src, thread_offset, config, total_num_output, read_lens); + } +} + +/** + * @brief Initialize register with data index. + * + * @template paraments + * T: Data type of register. + * NX: Number of data to initialize. + * NY: Number of data to initialize, NY only can be 1. + * core_id() is used as the index. + * + * @param: + * dst: The register pointer of the thread, the size is NX. + * init_data: The register pointer of init data, the size is NX. + */ +template +__device__ __forceinline__ void InitWithDataIndex(T* dst, int block_offset) { + int thread_offset = block_offset + core_id() * NX; +#pragma unroll + for (int nx = 0; nx < NX; ++nx) { + dst[nx] = static_cast(thread_offset + nx); + } +} + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives.h new file mode 100644 index 0000000000000000000000000000000000000000..700ba00088517236729ca6ee982111f507ad0c6c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives.h @@ -0,0 +1,255 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/fluid/operators/amp/fp16_type_traits.h" +#include "paddle/phi/common/float16.h" +#include "paddle/phi/core/enforce.h" +#include "paddle/phi/kernels/funcs/eigen/extensions.h" + +namespace phi { +namespace kps { +namespace details { + +static __device__ __forceinline__ phi::dtype::float16 Exp( + phi::dtype::float16 x) { + return ::Eigen::numext::exp(x); +} + +static __device__ __forceinline__ float Exp(float x) { return expf(x); } + +static __device__ __forceinline__ double Exp(double x) { return exp(x); } + +static __device__ __forceinline__ phi::dtype::float16 Log( + phi::dtype::float16 x) { + return ::Eigen::numext::log(x); +} + +static __device__ __forceinline__ float Log(float x) { return logf(x); } + +static __device__ __forceinline__ double Log(double x) { return log(x); } + +} // namespace details + +/******************************** Unary Functor *******************************/ + +/** + * @brief Default unary exp functor + */ +template +struct ExpFunctor { + HOSTDEVICE inline ExpFunctor() {} + + HOSTDEVICE explicit inline ExpFunctor(int n) {} + + HOSTDEVICE inline Ty operator()(const Tx x) const { + return static_cast(details::Exp(x)); + } +}; + +/** + * @brief Default unary identity functor + */ +template +struct IdentityFunctor { + HOSTDEVICE inline IdentityFunctor() {} + + HOSTDEVICE explicit inline IdentityFunctor(int n) {} + + HOSTDEVICE inline Ty operator()(const Tx x) const { + return static_cast(x); + } +}; + +/** + * @brief Default unary div functor. Divide by a constant + */ +template +struct DivideFunctor { + private: + using MPType = typename ::paddle::operators::details::MPTypeTrait::Type; + + public: + HOSTDEVICE inline DivideFunctor() { n_inv = static_cast(1.0f); } + + HOSTDEVICE explicit inline DivideFunctor(int n) : n_inv((MPType)(1.0 / n)) {} + + HOSTDEVICE inline Ty operator()(const Tx x) const { + return static_cast(static_cast(x) * n_inv); + } + + private: + MPType n_inv; +}; + +/** + * @brief Default inverse functor + */ +template +struct InverseFunctor { + HOSTDEVICE inline InverseFunctor() {} + + HOSTDEVICE explicit inline InverseFunctor(int n) {} + + HOSTDEVICE inline Ty operator()(const Tx x) const { + return static_cast(-x); + } +}; + +/** + * @brief Default unary square functor + */ +template +struct SquareFunctor { + HOSTDEVICE inline SquareFunctor() {} + + HOSTDEVICE explicit inline SquareFunctor(int n) {} + + HOSTDEVICE inline Ty operator()(const Tx x) const { + return static_cast(x) * static_cast(x); + } +}; + +/****************************** Binary Functor ********************************/ + +/** + * @brief Default binary min functor + */ +template +struct MinFunctor { + inline T initial() { return static_cast(std::numeric_limits::max()); } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return (b < a) ? b : a; + } +}; + +/** + * @brief Default binary max functor + */ +template +struct MaxFunctor { + inline T initial() { + return static_cast(std::numeric_limits::lowest()); + } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return (b > a) ? b : a; + } +}; + +/** + * @brief Default binary add functor + */ +template +struct AddFunctor { + inline T initial() { return static_cast(0.0f); } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return b + a; + } +}; + +/** + * @brief Default binary add functor + */ +template +struct MulFunctor { + inline T initial() { return static_cast(1.0f); } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return b * a; + } +}; + +/** + * @brief Default binary logic or functor + */ +template +struct LogicalOrFunctor { + inline T initial() { return static_cast(false); } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return b || a; + } +}; + +/** + * @brief Default binary logic and functor + */ +template +struct LogicalAndFunctor { + inline T initial() { return static_cast(true); } + + __device__ __forceinline__ T operator()(const T a, const T b) const { + return b && a; + } +}; + +/** + * @brief Default binary sub functor + */ +template +struct SubFunctor { + inline T initial() { return static_cast(0.0f); } + + inline HOSTDEVICE T operator()(const T a, const T b) const { return a - b; } +}; + +/** + * @brief Default binary div functor + */ +template +struct DivFunctor { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T a, const T b) const { return a / b; } +}; + +template +struct DivFunctor::value>::type> { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T a, const T b) const { + // For int32/int64, need to check whether the divison is zero. + PADDLE_ENFORCE_NE(b, + 0, + phi::errors::InvalidArgument( + "Integer division by zero encountered " + "in (floor) divide. Please check the input value.")); + return a / b; + } +}; + +/** + * @brief Default binary floor divide functor + */ +template +struct FloorDivFunctor { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T a, const T b) const { + PADDLE_ENFORCE_NE(b, + 0, + phi::errors::InvalidArgument( + "Integer division by zero encountered " + "in (floor) divide. Please check the input value.")); + return static_cast(std::trunc(a / b)); + } +}; + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives_xpu2.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives_xpu2.h new file mode 100644 index 0000000000000000000000000000000000000000..35cea6e6927871c6d47049d0fe0523f655301723 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/functor_primitives_xpu2.h @@ -0,0 +1,215 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "xpu/kernel/cluster_header.h" +#include "xpu/kernel/debug.h" +#include "xpu/kernel/math.h" + +namespace phi { +namespace kps { +/** + * @brief Default unary identity functor + */ +template +struct IdentityFunctor { +#ifdef PADDLE_WITH_XPU_KP + HOSTDEVICE inline IdentityFunctor() {} + HOSTDEVICE explicit inline IdentityFunctor(int n) {} + HOSTDEVICE Ty operator()(const Tx x) const { return static_cast(x); } + HOSTDEVICE inline void SetDiv(int n) {} +#else + inline IdentityFunctor() {} + + explicit inline IdentityFunctor(int n) {} + + inline Ty operator()(const Tx& x) const { return static_cast(x); } + __device__ inline IdentityFunctor() {} + + __device__ explicit inline IdentityFunctor(int n) {} + + __device__ inline Ty operator()(const Tx& x) const { + return static_cast(x); + } + __device__ inline void SetDiv(int n) {} +#endif +}; + +/** + * @brief Default unary div functor. Divide by a constant + */ +template +struct DivideFunctor { + inline DivideFunctor() { n_inv = static_cast(1.0f); } + + explicit inline DivideFunctor(int n) + : n_inv(static_cast(1.0f / (static_cast(n)))) {} + + inline Ty operator()(const Tx& x) const { return static_cast(x * n_inv); } + + __device__ inline DivideFunctor() { n_inv = static_cast(1.0f); } + + __device__ inline DivideFunctor(int n) + : n_inv(static_cast(1.0f / (static_cast(n)))) {} + + __device__ inline Ty operator()(const Tx& x) const { + return static_cast(x * n_inv); + } + + __device__ inline void SetDiv(int n) { + n_inv = static_cast(1.0f / (static_cast(n))); + } + + private: + Tx n_inv; +}; + +/** + * @brief Default unary square functor + */ +template +struct SquareFunctor { + HOSTDEVICE inline SquareFunctor() {} + + HOSTDEVICE explicit inline SquareFunctor(int n) {} + + HOSTDEVICE inline Ty operator()(const Tx& x) const { + return static_cast(x) * static_cast(x); + } +}; + +/****************************** Binary Functor ********************************/ + +/** + * @brief Default binary min functor + */ +template +struct MinFunctor { + inline T initial() { return static_cast(std::numeric_limits::max()); } + + __device__ T operator()(const T& a, const T& b) const { + return (b < a) ? b : a; + } +}; + +/** + * @brief Default binary max functor + */ +template +struct MaxFunctor { + inline T initial() { + return static_cast(std::numeric_limits::lowest()); + } + + __device__ T operator()(const T& a, const T& b) const { + return (b > a) ? b : a; + } +}; + +/** + * @brief Default binary add functor + */ +template +struct AddFunctor { + inline T initial() { return static_cast(0.0f); } + + __device__ T operator()(const T a, const T b) const { return b + a; } +}; + +/** + * @brief Default binary add functor + */ +template +struct MulFunctor { + inline T initial() { return static_cast(1.0f); } + + __device__ T operator()(const T& a, const T& b) const { return b * a; } +}; + +/** + * @brief Default binary logic or functor + */ +template +struct LogicalOrFunctor { + inline T initial() { return static_cast(false); } + + __device__ T operator()(const T& a, const T& b) const { return b || a; } +}; + +/** + * @brief Default binary logic and functor + */ +template +struct LogicalAndFunctor { + inline T initial() { return static_cast(true); } + + __device__ T operator()(const T& a, const T& b) const { return b && a; } +}; + +/** + * @brief Default binary sub functor + */ +template +struct SubFunctor { + inline T initial() { return static_cast(0.0f); } + + inline HOSTDEVICE T operator()(const T& a, const T& b) const { return a - b; } +}; + +/** + * @brief Default binary div functor + */ +template +struct DivFunctor { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T& a, const T& b) const { return a / b; } +}; + +template +struct DivFunctor::value>::type> { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T& a, const T& b) const { + // For int32/int64, need to check whether the divison is zero. + PADDLE_ENFORCE_NE(b, + 0, + phi::errors::InvalidArgument( + "Integer division by zero encountered " + "in (floor) divide. Please check the input value.")); + return a / b; + } +}; + +/** + * @brief Default binary floor divide functor + */ +template +struct FloorDivFunctor { + inline T initial() { return static_cast(1.0f); } + + inline HOSTDEVICE T operator()(const T& a, const T& b) const { + PADDLE_ENFORCE_NE(b, + 0, + phi::errors::InvalidArgument( + "Integer division by zero encountered " + "in (floor) divide. Please check the input value.")); + return static_cast(std::trunc(a / b)); + } +}; + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/helper_primitives.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/helper_primitives.h new file mode 100644 index 0000000000000000000000000000000000000000..85a9e0c420c384945cd384ab9ea843287c148b55 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/helper_primitives.h @@ -0,0 +1,67 @@ +// Copyright (c) 2022 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. + +#pragma once + +namespace phi { +namespace kps { + +#ifdef PADDLE_WITH_XPU_KP +struct dim3 { + int x; + int y; + int z; + + explicit inline dim3(int split_x = 1, int split_y = 1, int split_z = 1) { + x = split_x; + y = split_y; + z = split_z; + } +}; +#endif + +struct DimConfig { + int split_num_x; + int split_num_y; + int split_num_z; + int deal_size_x; + int deal_size_y; + int deal_size_z; + int rem_x; + int rem_y; + int rem_z; + + HOSTDEVICE explicit inline DimConfig(int split_x, + int split_y, + int split_z, + int size_x, + int size_y, + int size_z) { + split_num_x = split_x; + split_num_y = split_y; + split_num_z = split_z; + deal_size_x = size_x; + deal_size_y = size_y; + deal_size_z = size_z; + } + + HOSTDEVICE void SetRem(int rem_nx, int rem_ny, int rem_nz) { + rem_x = rem_nx; + rem_y = rem_ny; + rem_z = rem_nz; + } +}; + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/kernel_primitives.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/kernel_primitives.h new file mode 100644 index 0000000000000000000000000000000000000000..729402ed55945236e19f8f785511a3e319beefeb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/primitive/kernel_primitives.h @@ -0,0 +1,102 @@ +// Copyright (c) 2021 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. + +#pragma once + +#include "paddle/phi/kernels/primitive/helper_primitives.h" + +// macro +#ifdef PADDLE_WITH_XPU_KP + +#define KPStream XPUStream +#define KPDevice phi::XPUContext +#define _ptr_ _global_ptr_ +#define __forceinline__ __inline__ +#define __restrict__ + +#define THREAD_ID_X core_id() +#define THREAD_ID_Y 0 +#define THREAD_ID_Z 0 + +#define BLOCK_NUM_X core_num() +#define BLOCK_NUM_Y 0 +#define BLOCK_NUM_Z 0 + +#define BLOCK_ID_X cluster_id() +#define BLOCK_ID_Y 0 +#define BLOCK_ID_Z 0 + +#define GRID_NUM_X cluster_num() +#define GRID_NUM_Y 0 +#define GRID_NUM_Z 0 +#define VecSizeL 512 +#define VecSizeM 256 +#define VecSizeS 128 +#else + +#define KPStream gpuStream_t +#define KPDevice phi::GPUContext +#define _ptr_ +#define __simd__ + +#define THREAD_ID_X threadIdx.x +#define THREAD_ID_Y threadIdx.y +#define THREAD_ID_Z threadIdx.z + +#define BLOCK_NUM_X blockDim.x +#define BLOCK_NUM_Y blockDim.y +#define BLOCK_NUM_Z blockDim.z + +#define BLOCK_ID_X blockIdx.x +#define BLOCK_ID_Y blockIdx.y +#define BLOCK_ID_Z blockIdx.z + +#define GRID_NUM_X gridDim.x +#define GRID_NUM_Y gridDim.y +#define GRID_NUM_Z gridDim.z + +#define VecSizeL 4 +#define VecSizeM 2 +#define VecSizeS 1 +#endif + +// include file +#ifdef PADDLE_WITH_XPU_KP + +#include "paddle/phi/backends/xpu/xpu_context.h" +#include "paddle/phi/kernels/primitive/compute_primitives_xpu2.h" +#include "paddle/phi/kernels/primitive/datamover_primitives_xpu2.h" +#include "paddle/phi/kernels/primitive/functor_primitives_xpu2.h" + +#else + +#include "paddle/phi/backends/gpu/gpu_context.h" +#include "paddle/phi/kernels/primitive/compute_primitives.h" +#include "paddle/phi/kernels/primitive/datamover_primitives.h" +#include "paddle/phi/kernels/primitive/functor_primitives.h" + +#endif + +namespace phi { +namespace kps { + +#ifdef PADDLE_WITH_XPU_KP +// The type of index used in kernel +using IndexType = int; +#else +using IndexType = int64_t; +#endif + +} // namespace kps +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prior_box_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prior_box_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7a25b7d8e6d4635efca70145cb5cead4139e424a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/prior_box_kernel.h @@ -0,0 +1,62 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PriorBoxKernel(const Context& ctx, + const DenseTensor& input, + const DenseTensor& image, + const std::vector& min_sizes, + const std::vector& aspect_ratios, + const std::vector& variances, + const std::vector& max_sizes, + bool flip, + bool clip, + float step_w, + float step_h, + float offset, + bool min_max_aspect_ratios_order, + DenseTensor* out, + DenseTensor* var); + +inline void ExpandAspectRatios(const std::vector& input_aspect_ratior, + bool flip, + std::vector* output_aspect_ratior) { + constexpr float epsilon = 1e-6; + output_aspect_ratior->clear(); + output_aspect_ratior->push_back(1.0f); + for (size_t i = 0; i < input_aspect_ratior.size(); ++i) { + float ar = input_aspect_ratior[i]; + bool already_exist = false; + for (size_t j = 0; j < output_aspect_ratior->size(); ++j) { + if (fabs(ar - output_aspect_ratior->at(j)) < epsilon) { + already_exist = true; + break; + } + } + if (!already_exist) { + output_aspect_ratior->push_back(ar); + if (flip) { + output_aspect_ratior->push_back(1.0f / ar); + } + } + } +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8dcf81194e26985a6ba912a9d2b8ecce3b49628a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void PsroiPoolGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& rois, + const paddle::optional& rois_num, + const DenseTensor& dout, + int pooled_height, + int pooled_width, + int output_channels, + float spatial_scale, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5838fa895119d76fad5eda04c1038de2677f8270 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/psroi_pool_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void PsroiPoolKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& rois, + const paddle::optional& rois_num, + int pooled_height, + int pooled_width, + int output_channels, + float spatial_scale, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2141443da7ab17776a72572fd7634bbf822a7f66 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_grad_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PutAlongAxisGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& out_grad, + int axis, + const std::string& reduce, + DenseTensor* x_grad, + DenseTensor* value_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..797d0e364b48d46372992590f7807b4c6af5f242 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/put_along_axis_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void PutAlongAxisKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& value, + int axis, + const std::string& reduce, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..51d24dc533a5a098938cc976924dffd67fea61dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void QrGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& q, + const DenseTensor& r, + const DenseTensor& q_grad, + const DenseTensor& r_grad, + const std::string& mode, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9c3dfb16601267ec8a1d2535f6854c2a31dba5a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/qr_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void QrKernel(const Context& ctx, + const DenseTensor& x, + const std::string& mode, + DenseTensor* q, + DenseTensor* r); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randint_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randint_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..85d440e305635d6126833526b450946ed4c169c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randint_kernel.h @@ -0,0 +1,39 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RandintKernel(const Context& dev_ctx, + int low, + int high, + const IntArray& shape, + DataType dtype, + DenseTensor* out); + +template +void RandintRawKernel(const Context& dev_ctx, + int low, + int high, + const IntArray& shape, + DataType dtype, + int seed, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randperm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randperm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..70b95db98bef95f364802ad14a54966dc47d13fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/randperm_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void RandpermRawKernel( + const Context& dev_ctx, int n, DataType dtype, int seed, DenseTensor* out); + +template +void RandpermKernel(const Context& dev_ctx, + int n, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_all_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_all_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..af34a0a5d4c6f202a74b0088f19519b481bde63a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_all_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AllRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void AllKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..82518c11675c39bafef409ab92c6cd605b2ebc3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ReduceAMaxGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..79a287b4871364acb1cf9a77006b6967044eb58e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amax_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AMaxRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void AMaxKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..96f157e2038628773875ed816ae01bef670c183f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ReduceAMinGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b36351dd5258f8a50ca18525037e3d13810200e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_amin_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void AMinRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void AMinKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_any_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_any_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9514d02dbdf94a069f0f0352b4ca630c59724247 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_any_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void AnyRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void AnyKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d1522667935f61a2bbb18bcc58cadb82e3c39453 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void ReduceMaxGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2af22a2ddde3d00c2bc4c67f34b008b2259ee167 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_max_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void MaxRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void MaxKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..572e5a0f6fb0c65144650fe62f44961c10f3122f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void ReduceMeanGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..13c387a86e2286fd293b73c6933c2db0defbacbd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_mean_kernel.h @@ -0,0 +1,49 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void MeanRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void MeanKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + DenseTensor* out); + +template +DenseTensor Mean(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axis, + bool keep_dim) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + SumRawInferMeta(x, axis, keep_dim, false, x.dtype(), &meta_out); + MeanKernel(dev_ctx, x, axis, keep_dim, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c73776143908926deb2e3e21d3b58e8b2c316f2f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void ReduceMinGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e6f133cc9ca005593d7ca7f695007431678cba51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_min_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void MinRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void MinKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fb773f167f90b48c37a673701a905a99670df29a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void ReduceProdGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..91de087ccbc735d7c66270c2296ba848b0eaf700 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_prod_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { +template +void ProdRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* out); + +template +void ProdKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8cea1f4b34594b4a4ae1979ba52fae8093ee6091 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +namespace phi { + +template +void ReduceSumGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3bcf025d96bc4c59d40e0a04b4546633583e6401 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reduce_sum_kernel.h @@ -0,0 +1,52 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { +template +void SumRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + bool keep_dim, + bool reduce_all, + DataType out_dtype, + DenseTensor* out); + +template +void SumKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& dims, + DataType out_dtype, + bool keep_dim, + DenseTensor* out); + +template +DenseTensor Sum(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axis, + DataType dtype, + bool keep_dim) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + SumInferMeta(x, axis, dtype, keep_dim, &meta_out); + SumKernel(dev_ctx, x, axis, dtype, keep_dim, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..508cbe371b33c598eaa4c3e3c47a1a9abbad031c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RenormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + float p, + int axis, + float max_norm, + DenseTensor* dx); +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e5db2a34a71f280a64a86330bee4fc28c95eda86 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/renorm_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RenormKernel(const Context& dev_ctx, + const DenseTensor& x, + float p, + int axis, + float max_norm, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..75f493bd99f93774f8960b3bc8f3d3e2b5aac8b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_grad_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RepeatInterleaveGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + int repeats, + int dim, + DenseTensor* x_grad); + +template +void RepeatInterleaveWithTensorIndexGradKernel( + const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& repeats_tensor, + const DenseTensor& out_grad, + int dim, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..871b7208000d2c6b3eb46fb9b29d83a608558c59 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/repeat_interleave_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RepeatInterleaveKernel(const Context& dev_ctx, + const DenseTensor& x, + int repeats, + int dim, + DenseTensor* out); + +template +void RepeatInterleaveWithTensorIndexKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& repeat_tensor, + int dim, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..06ec3de15ab223c99c646fbf5868356cb38fb26d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_grad_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ReshapeGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +template +void ReshapeDoubleGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + const DenseTensor& x_grad_grad, + DenseTensor* out_grad_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..88b1bd958714089291a63ea1f8714d5549400277 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reshape_kernel.h @@ -0,0 +1,48 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void ReshapeKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& shape, + DenseTensor* out); + +template +void ReshapeWithXShape(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& shape, + DenseTensor* out, + DenseTensor* xshape); + +template +DenseTensor Reshape(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& shape) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + InferMetaFromVecValue(x, shape, &meta_out); + ReshapeKernel(dev_ctx, x, IntArray(shape), &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reverse_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reverse_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9e4d5fc512d07ca15bc458b0461b5a67ad9a4006 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/reverse_kernel.h @@ -0,0 +1,37 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" + +namespace phi { + +template +void ReverseKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axis, + DenseTensor* out); + +template +void ReverseArrayKernel(const Context& dev_ctx, + const TensorArray& x, + const IntArray& axis, + TensorArray* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rmsprop_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rmsprop_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fba2095cc8bce273c55a9866a8f2497ee58895e9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rmsprop_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void RmspropDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& mean_square, + const DenseTensor& grad, + const DenseTensor& moment, + const DenseTensor& learning_rate, + const paddle::optional& mean_grad, + float epsilon, + float decay, + float momentum, + bool centered, + DenseTensor* param_out, + DenseTensor* moment_out, + DenseTensor* mean_square_out, + DenseTensor* mean_grad_out); + +template +void RmspropSparseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& mean_square, + const SelectedRows& grad, + const DenseTensor& moment, + const DenseTensor& learning_rate, + const paddle::optional& mean_grad, + float epsilon, + float decay, + float momentum, + bool centered, + DenseTensor* param_out, + DenseTensor* moment_out, + DenseTensor* mean_square_out, + DenseTensor* mean_grad_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..024ed287bb13f6619ca1d0fe227bfc1ae7dbaf3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_grad_kernel.h @@ -0,0 +1,45 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void RnnGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& pre_state, + const std::vector& weight_list, + const paddle::optional& sequence_length, + const DenseTensor& out, + const DenseTensor& dropout_state, + const DenseTensor& reserve, + const DenseTensor& out_grad, + const std::vector& state_grad, + float dropout_prob, + bool is_bidirec, + int input_size, + int hidden_size, + int num_layers, + const std::string& mode, + int seed, + bool is_test, + DenseTensor* x_grad, + std::vector pre_state_grad, + std::vector weight_grad_list); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..61dfb6f56d79846a1ca3176047f98e3ade663629 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rnn_kernel.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void RnnKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& pre_state, + const std::vector& weight_list, + const paddle::optional& sequence_length, + float dropout_prob, + bool is_bidirec, + int input_size, + int hidden_size, + int num_layers, + const std::string& mode, + int seed, + bool is_test, + DenseTensor* out, + DenseTensor* dropout_state, + std::vector state, + DenseTensor* reserve); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a7c2ed3beb53a8c88fbf56c72333f8d4d8a56c8b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_grad_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void RoiAlignGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& boxes, + const paddle::optional& boxes_num, + const DenseTensor& out_grad, + int pooled_height, + int pooled_width, + float spatial_scale, + int sampling_ratio, + bool aligned, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fa3161e3238dfdd04981b5e40670bdeb7415421c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_align_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void RoiAlignKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& boxes, + const paddle::optional& boxes_num, + int pooled_height, + int pooled_width, + float spatial_scale, + int sampling_ratio, + bool aligned, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f18bd1d65e6440a4119e14e11945661cfa696d58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void RoiPooGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& boxes, + const paddle::optional& boxes_num, + const DenseTensor& arg_max, + const DenseTensor& out_grad, + int pooled_height, + int pooled_width, + float spatial_scale, + DenseTensor* dx); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e7ed2587968f56c9dc59375406819aa7d68c5e8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roi_pool_kernel.h @@ -0,0 +1,35 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +static constexpr int kROISize = 4; + +template +void RoiPoolKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& boxes, + const paddle::optional& boxes_num, + int pooled_height, + int pooled_width, + float spatial_scale, + DenseTensor* out, + DenseTensor* arg_max); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..82e9c0249f7af8907d5c0f4ad2ddec3c46b006ab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RollGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& shifts, + const std::vector& axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4e0c41b8b8de841eef6030d3e8b9c55b4630e8e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/roll_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RollKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& shifts, + const std::vector& axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b6172fca10e53432d60d04ee4e81ccfa8dd54434 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_grad_kernel.h @@ -0,0 +1,28 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RReluGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& noise, + const DenseTensor& out_grad, + DenseTensor* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8deb52daaae136fe7b7bf3965b580c8a5052d669 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/rrelu_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void RReluKernel(const Context& dev_ctx, + const DenseTensor& x, + const float lower, + const float upper, + bool is_test, + DenseTensor* out, + DenseTensor* noise); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/save_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/save_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9aa32f56209b769d022c92778bb09ca07a185c5b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/save_kernel.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SaveKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::string& file_path, + bool overwrite, + bool save_as_fp16); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scale_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scale_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7537dc1130b83ea3963ae128bf8ce3859411c199 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scale_kernel.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" +namespace phi { + +template +void ScaleKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& scale, + float bias, + bool bias_after_scale, + DenseTensor* out); + +template +DenseTensor Scale(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& scale, + float bias, + bool bias_after_scale) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + UnchangedInferMeta(x, &meta_out); + ScaleKernel( + dev_ctx, x, scale, bias, bias_after_scale, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cf1482fca7f667eae530e09a95df0020186aef77 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ScatterGradKernel(const Context &ctx, + const DenseTensor &index, + const DenseTensor &updates, + const DenseTensor &out_grad, + bool overwrite, + DenseTensor *x_grad, + DenseTensor *updates_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5191d6bce45f26c69d5a2fe61c23f71039c2433c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ScatterKernel(const Context &ctx, + const DenseTensor &x, + const DenseTensor &index, + const DenseTensor &updates, + bool overwrite, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..bcfdb2cdb2f09e53ed9da1bc3995587737f9492c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ScatterNdAddGradKernel(const Context &ctx, + const DenseTensor &index, + const DenseTensor &updates, + const DenseTensor &out_grad, + DenseTensor *x_grad, + DenseTensor *updates_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c20709dccc08c16650dd1fc00ec10a91c333e13f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/scatter_nd_add_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ScatterNdAddKernel(const Context &ctx, + const DenseTensor &x, + const DenseTensor &index, + const DenseTensor &updates, + DenseTensor *out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/searchsorted_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/searchsorted_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e425c7fd7955544cc429fb0a071e8f8038b47063 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/searchsorted_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SearchsortedKernel(const Context& ctx, + const DenseTensor& sorted_sequence, + const DenseTensor& value, + bool out_int32, + bool right, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..edf9ff9c7568c86ed16c8a3a0092b85a8abaa341 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SegmentPoolGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& segment_ids, + const DenseTensor& out, + const paddle::optional& summed_ids, + const DenseTensor& out_grad, + const std::string& pooltype, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8f7b30c2e8603d1b59c8217ef3e9e21d072bf1d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/segment_pool_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SegmentPoolKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& segment_ids, + const std::string& pooltype, + DenseTensor* out, + DenseTensor* summed_ids); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/activation_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/activation_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6518f9553961868e5a2a867167024ef036552754 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/activation_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void SquareKernel(const Context& dev_ctx, + const SelectedRows& x, + SelectedRows* out); + +template +void SqrtKernel(const Context& dev_ctx, + const SelectedRows& x, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adam_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adam_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..79f87a8ed75c0c496cabd19885f662efbc6d9a15 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adam_kernel.h @@ -0,0 +1,51 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void AdamDenseParamSparseGradKernel( + const Context& dev_ctx, + const DenseTensor& param, + const SelectedRows& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adamw_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adamw_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5dda8107d52e3e20ace2f2d2b3f7027602b400ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/adamw_kernel.h @@ -0,0 +1,54 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void AdamwDenseParamSparseGradKernel( + const Context& dev_ctx, + const DenseTensor& param, + const SelectedRows& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + const Scalar& beta1, + const Scalar& beta2, + const Scalar& epsilon, + float lr_ratio, + float coeff, + bool with_decay, + bool lazy_mode, + int64_t min_row_size_to_use_multithread, + bool multi_precision, + bool use_global_beta_pow, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/add_n_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/add_n_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c56985fb0723f9c7671d6052f774eb8da53aa06f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/add_n_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void AddNKernel(const Context& dev_ctx, + const std::vector& x, + SelectedRows* out); +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/assign_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/assign_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2ba465615a73a3036d4b029c8ecb54002b86cb97 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/assign_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void AssignKernel(const Context& dev_ctx, + const SelectedRows& x, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_by_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_by_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..975aac23ff3ac6974e44ba6527d48ef0318a87fd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_by_norm_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void ClipByNormKernel(const Context& dev_ctx, + const SelectedRows& x, + float max_norm, + SelectedRows* out); +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ec56d92c513ea25897f63dd31a25f574df8c6fbc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/clip_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/fluid/operators/math/selected_rows_functor.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" +#include "paddle/phi/core/selected_rows.h" +#include "paddle/phi/kernels/impl/clip_kernel_impl.h" + +namespace phi { +namespace sr { + +template +void ClipSparseKernel(const Context& dev_ctx, + const SelectedRows& x, + const Scalar& min, + const Scalar& max, + SelectedRows* out); +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/elementwise_multiply_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/elementwise_multiply_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f90fd47882b89f7c040b7b7c79c3fae7dec6a7e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/elementwise_multiply_kernel.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void MultiplyRawKernel(const Context& dev_ctx, + const SelectedRows& x, + const DenseTensor& y, + int axis, + SelectedRows* out); + +template +void MultiplyKernel(const Context& dev_ctx, + const SelectedRows& x, + const DenseTensor& y, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/full_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/full_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d4b1859fdfcfb6ec6bdfccfcc9dfc28741b12bc5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/full_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void FullKernel(const Context& dev_ctx, + const IntArray& shape, + const Scalar& val, + DataType dtype, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/hierarchical_sigmoid_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/hierarchical_sigmoid_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..aca355f515c44378ab007d4f93c766bfe1b629e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/hierarchical_sigmoid_grad_kernel.h @@ -0,0 +1,45 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void HierarchicalSigmoidGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& w, + const DenseTensor& label, + const paddle::optional& path, + const paddle::optional& code, + const paddle::optional& bias, + const DenseTensor& pre_out, + const DenseTensor& out_grad, + int num_classes, + bool remote_prefetch, + int trainer_id, + const std::vector& height_sections, + const std::vector& epmap, + const std::vector& table_names, + bool is_sparse, + DenseTensor* x_grad, + SelectedRows* w_grad, + DenseTensor* bias_grad); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/isfinite_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/isfinite_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..447edd6580561fdf4ebed647977985e4b9bdd111 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/isfinite_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/selected_rows.h" +#include "paddle/phi/kernels/isfinite_kernel.h" + +namespace phi { + +#define DEFINE_ISFINITE_SR(isfinite_sr) \ + template \ + void isfinite_sr( \ + const Context& ctx, const SelectedRows& x, SelectedRows* out); + +DEFINE_ISFINITE_SR(IsinfSR) +DEFINE_ISFINITE_SR(IsnanSR) +DEFINE_ISFINITE_SR(IsfiniteSR) +#undef DEFINE_ISFINITE_SR + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/lamb_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/lamb_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..306f1ca0ff79bce523783d1459cd9803252f0b69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/lamb_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void LambKernel(const Context& dev_ctx, + const DenseTensor& param, + const SelectedRows& grad, + const DenseTensor& learning_rate, + const DenseTensor& moment1, + const DenseTensor& moment2, + const DenseTensor& beta1_pow, + const DenseTensor& beta2_pow, + const paddle::optional& master_param, + const paddle::optional& skip_update, + float weight_decay, + float beta1, + float beta2, + float epsilon, + bool multi_precision, + DenseTensor* param_out, + DenseTensor* moment1_out, + DenseTensor* moment2_out, + DenseTensor* beta1_pow_out, + DenseTensor* beta2_pow_out, + DenseTensor* master_param_outs); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/save_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/save_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..eb6440d96c5766ae8b906b292a8264a3a5a5b429 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/save_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void SaveKernel(const Context& dev_ctx, + const SelectedRows& x, + const std::string& file_path, + bool overwrite, + bool save_as_fp16); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/scale_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/scale_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..85c2c4ddff0333cdd0603f2fb4235b17bbdaffad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/scale_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void ScaleKernel(const Context& dev_ctx, + const SelectedRows& x, + const Scalar& scale, + float bias, + bool bias_after_scale, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/shape_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/shape_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..86ba52982b5967481f50cb661b15c84ed3751edd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/shape_kernel.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void ShapeKernel(const Context& ctx, + const SelectedRows& input, + DenseTensor* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/uniform_random_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/uniform_random_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..237b01532c7bd824b4ae36ae85fe588c76defa59 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selected_rows/uniform_random_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { +namespace sr { + +template +void UniformRandomRawKernel(const Context& dev_ctx, + const IntArray& shape, + DataType dtype, + const Scalar& min, + const Scalar& max, + int seed, + int diag_num, + int diag_step, + float diag_val, + SelectedRows* out); + +template +void UniformRandomKernel(const Context& dev_ctx, + const IntArray& shape, + DataType dtype, + const Scalar& min, + const Scalar& max, + int seed, + SelectedRows* out); + +} // namespace sr +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..42cde6deabe1c27c42397ec97221ff6790c8ed7a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_grad_kernel.h @@ -0,0 +1,29 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SeluGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& d_out, + float scale, + float alpha, + DenseTensor* d_x); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b8130d239869197997c0f162d380b2dc08baf160 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/selu_kernel.h @@ -0,0 +1,28 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SeluKernel(const Context& dev_ctx, + const DenseTensor& x, + float scale, + float alpha, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3ee95d76281935ff34399d9e9117513b3bf89b87 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_grad_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SetValueGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + const IntArray& starts, + const IntArray& ends, + const IntArray& steps, + const std::vector& axes, + const std::vector& decrease_axes, + const std::vector& none_axes, + DenseTensor* x_grad, + DenseTensor* value_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..69fd88f02e8521be2dc7e44d71673bce01e1ca5c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/set_value_kernel.h @@ -0,0 +1,49 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void SetTensorValueKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& value, + const IntArray& starts, + const IntArray& ends, + const IntArray& steps, + const std::vector& axes, + const std::vector& decrease_axes, + const std::vector& none_axes, + DenseTensor* out); + +template +void SetValueKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& starts, + const IntArray& ends, + const IntArray& steps, + const std::vector& axes, + const std::vector& decrease_axes, + const std::vector& none_axes, + const std::vector& shape, + const std::vector& values, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sgd_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sgd_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..226a719b90244d3417ad16e3505414c22d654613 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sgd_kernel.h @@ -0,0 +1,54 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void SGDDenseKernel(const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& learning_rate, + const DenseTensor& grad, + const paddle::optional& master_param, + bool multi_precision, + DenseTensor* param_out, + DenseTensor* master_param_out); + +template +void SGDDenseParamSparseGradKernel( + const Context& dev_ctx, + const DenseTensor& param, + const DenseTensor& learning_rate, + const SelectedRows& grad, + const paddle::optional& master_param, + bool multi_precision, + DenseTensor* param_out, + DenseTensor* master_param_out); + +template +void SGDSparseParamSparseGradKernel( + const Context& dev_ctx, + const SelectedRows& param, + const DenseTensor& learning_rate, + const SelectedRows& grad, + const paddle::optional& master_param, + bool multi_precision, + SelectedRows* param_out, + SelectedRows* master_param_out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shape_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shape_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..444c481812e88dfb6413d8af51dca4f1b704efbf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shape_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ShapeKernel(const Context& ctx, + const DenseTensor& input, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shard_index_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shard_index_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..54ad9a14fa023e41d5261cfe9f03039a1fa031ec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/shard_index_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ShardIndexKernel(const Context& dev_ctx, + const DenseTensor& in, + int index_num, + int nshards, + int shard_id, + int ignore_value, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6bc75b7670fcc2100908af2543455964be324b54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SigmoidCrossEntropyWithLogitsGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& label, + const DenseTensor& out_grad, + bool normalize, + int ignore_index, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7ea3e6589f7ed070eb6229a24fb75e7444e94151 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sigmoid_cross_entropy_with_logits_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SigmoidCrossEntropyWithLogitsKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& label, + bool normalize, + int ignore_index, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sign_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sign_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4b5900d90f45daa01c117b9f1649a152734c5b76 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sign_kernel.h @@ -0,0 +1,35 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void SignKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out); + +template +DenseTensor Sign(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + UnchangedInferMeta(x, &meta_out); + SignKernel(dev_ctx, x, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/size_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/size_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2d7a29104db0813f4d4dca340575d0c1a5885d4c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/size_kernel.h @@ -0,0 +1,24 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SizeKernel(const Context& ctx, const DenseTensor& input, DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a74b432c2b1b9edae25f830b55319ddbf9d9df31 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_grad_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SliceGradRawKernel(const Context& ctx, + const DenseTensor& input, + const DenseTensor& out_grad, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const std::vector& infer_flags, + const std::vector& decrease_axis, + DenseTensor* input_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e01ff3d74fbc5307c73f5b6d138c58a98b93eb58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slice_kernel.h @@ -0,0 +1,50 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void SliceRawKernel(const Context& ctx, + const DenseTensor& input, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const std::vector& infer_flags, + const std::vector& decrease_axis, + DenseTensor* out); + +template +DenseTensor SliceKernel(const Context& ctx, + const DenseTensor& input, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const std::vector& infer_flags, + const std::vector& decrease_axis) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + SliceRawInferMeta( + input, axes, starts, ends, infer_flags, decrease_axis, &meta_out); + SliceRawKernel( + ctx, input, axes, starts, ends, infer_flags, decrease_axis, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..23bc12afda469fef98a469602b522c80c6510c69 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SlogDeterminantGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out, + const DenseTensor& out_grad, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..46413bd06e48b8fbf960f17defdf8a41fdb33df1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/slogdeterminant_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SlogDeterminantKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4ecf65c1f17c789b028b3a0a8ad270cca7aa69d9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_grad_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/kernels/cast_kernel.h" + +namespace phi { + +template +void SoftmaxGradKernel(const Context& dev_ctx, + const DenseTensor& out, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4edd562ca885301b02b8ecc737c8590831e3cac4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/softmax_kernel.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/kernels/cast_kernel.h" + +namespace phi { + +template +void SoftmaxKernel(const Context& dev_ctx, + const DenseTensor& x, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d2f1b6aef70c301557e2616b5e6cb940d93dce10 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_grad_kernel.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SolveGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& dout, + DenseTensor* dx, + DenseTensor* dy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..72f2feb47580f5887346251b35bfcbbf1ba73ade --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/solve_kernel.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief This kernrel is used to computes the solution of a square system of + * linear equations with a unique solution for input x and y. + * $$Out = X^-1 * Y$$ + * @param ctx device context + * @param x the input tensor of solve + * @param y the input tensor of solve + * @param out the output tensor of solve + */ +template +void SolveKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e320ba954139c1a4205bf51e4f4e839ed8a6fb5f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_grad_kernel.h @@ -0,0 +1,77 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +// TODO(zhouwei25): implement Backward of " COO + COO @ COO -> COO" +template +void AddmmCooCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& input, + const SparseCooTensor& x, + const SparseCooTensor& y, + const SparseCooTensor& dout, + float alpha, + float beta, + SparseCooTensor* dinput, + SparseCooTensor* dx, + SparseCooTensor* dy); + +// Backward of "DENSE + COO @ DENSE -> DENSE" +template +void AddmmCooDenseGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const SparseCooTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + float alpha, + float beta, + DenseTensor* dinput, + SparseCooTensor* dx, + DenseTensor* dy); + +// TODO(zhouwei25): implement Backward of " CSR + CSR @ CSR -> CSR" +template +void AddmmCsrCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& input, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + const SparseCsrTensor& dout, + float alpha, + float beta, + SparseCsrTensor* dinput, + SparseCsrTensor* dx, + SparseCsrTensor* dy); + +/* Backward of "DENSE + CSR @ DENSE -> DENSE" */ +template +void AddmmCsrDenseGradKernel(const Context& dev_ctx, + const DenseTensor& input, + const SparseCsrTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + float alpha, + float beta, + DenseTensor* dinput, + SparseCsrTensor* dx, + DenseTensor* dy); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf21fbca2f810739ee5508e3675340c81f2f641 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/addmm_kernel.h @@ -0,0 +1,65 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +// TODO(zhouwei25): implement " COO + COO @ COO -> COO" +template +void AddmmCooCooKernel(const Context& dev_ctx, + const SparseCooTensor& input, + const SparseCooTensor& x, + const SparseCooTensor& y, + float alpha, + float beta, + SparseCooTensor* out); + +/* DENSE + COO @ DENSE -> DENSE */ +template +void AddmmCooDenseKernel(const Context& dev_ctx, + const DenseTensor& input, + const SparseCooTensor& x, + const DenseTensor& y, + float alpha, + float beta, + DenseTensor* out); + +// TODO(zhouwei25): implement " CSR + CSR @ CSR -> CSR" +template +void AddmmCsrCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& input, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + float alpha, + float beta, + SparseCsrTensor* out); + +/* DENSE + CSR @ DENSE -> DENSE */ +template +void AddmmCsrDenseKernel(const Context& dev_ctx, + const DenseTensor& input, + const SparseCsrTensor& x, + const DenseTensor& y, + float alpha, + float beta, + DenseTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b7051683170e637613746dd082f11329cccaff64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_grad_kernel.h @@ -0,0 +1,48 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" + +namespace phi { +namespace sparse { + +template +void BatchNormCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const paddle::optional& mean, + const paddle::optional& variance, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const paddle::optional& reserve_space, + const SparseCooTensor& y_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + SparseCooTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a94a1203c8cdc19870b2440e8772bc9853990d83 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/batch_norm_kernel.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" + +namespace phi { +namespace sparse { + +template +void BatchNormCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& mean, + const DenseTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + SparseCooTensor* y, + DenseTensor* mean_out, + DenseTensor* variance_out, + DenseTensor* saved_mean, + DenseTensor* saved_variance, + DenseTensor* reserve_space); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/coalesce_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/coalesce_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cb8b98fd87404d421c0ac9ad8bba43633f59859b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/coalesce_kernel.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +template +void CoalesceKernel(const Context& dev_ctx, + const SparseCooTensor& x, + SparseCooTensor* out); + +template +SparseCooTensor Coalesce(const Context& dev_ctx, const SparseCooTensor& x) { + SparseCooTensor coo; + CoalesceKernel(dev_ctx, x, &coo); + return coo; +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..867f6b5a53f37fcbb3d72ead20f02187f0f01590 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_grad_kernel.h @@ -0,0 +1,79 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +template +void Conv3dCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& kernel, + const SparseCooTensor& out, + const DenseTensor& rulebook, + const DenseTensor& counter, + const SparseCooTensor& out_grad, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + const int groups, + const bool subm, + const std::string& key, + SparseCooTensor* x_grad, + DenseTensor* kernel_grad); + +template +std::tuple Conv3dCooGrad( + const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& kernel, + const SparseCooTensor& out, + const DenseTensor& rulebook, + const DenseTensor& counter, + const SparseCooTensor& out_grad, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + const int groups, + const bool subm, + const std::string& key) { + SparseCooTensor x_grad; + DenseTensor kernel_grad; + + // TODO(zhangkaihuo): call InferMeta func here + Conv3dCooGradKernel(dev_ctx, + x, + kernel, + out, + rulebook, + counter, + out_grad, + paddings, + dilations, + strides, + groups, + subm, + key, + &x_grad, + &kernel_grad); + return std::make_tuple(x_grad, kernel_grad); +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0c5a2081a6f3df3e6fe5c014eb1b08754ec2191c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/conv_kernel.h @@ -0,0 +1,68 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" +#include "paddle/phi/kernels/funcs/sparse/convolution.h" + +namespace phi { +namespace sparse { + +template +void Conv3dCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& kernel, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + const int groups, + const bool subm, + const std::string& key, + SparseCooTensor* out, + DenseTensor* rulebook, + DenseTensor* counter); + +template +SparseCooTensor Conv3dCoo(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor kernel, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + const int groups, + const bool subm, + const std::string& key, + DenseTensor* rulebook, + DenseTensor* counter) { + SparseCooTensor coo; + Conv3dCooKernel(dev_ctx, + x, + kernel, + paddings, + dilations, + strides, + groups, + subm, + key, + &coo, + rulebook, + counter); + return coo; +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f16e2f95d47eb2002c0fd17d5a340b7687fc363b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_grad_kernel.h @@ -0,0 +1,148 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/kernels/elementwise_add_grad_kernel.h" +#include "paddle/phi/kernels/sparse/empty_kernel.h" + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/infermeta/sparse/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +#define DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD(name) \ + DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD_WITH_TYPE(name, Csr) \ + \ + DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD_WITH_TYPE(name, Coo) + +#define DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC(name) \ + DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC_WITH_TYPE(name, Csr) \ + \ + DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC_WITH_TYPE(name, Coo) + +#define DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD_WITH_TYPE(name, type) \ + template \ + void ElementWise##name##type##GradKernel(const Context& dev_ctx, \ + const Sparse##type##Tensor& x, \ + const Sparse##type##Tensor& y, \ + const Sparse##type##Tensor& dout, \ + Sparse##type##Tensor* dx, \ + Sparse##type##Tensor* dy); + +#define DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC_WITH_TYPE(name, type) \ + template \ + std::vector ElementWise##name##type##Grad( \ + const Context& dev_ctx, \ + const Sparse##type##Tensor& x, \ + const Sparse##type##Tensor& y, \ + const Sparse##type##Tensor& dout) { \ + Sparse##type##Tensor dx; \ + Sparse##type##Tensor dy; \ + MetaTensor meta_dx(&dx), meta_dy(&dy); \ + phi::UnchangedInferMeta(x, &meta_dx); \ + phi::UnchangedInferMeta(y, &meta_dy); \ + ElementWise##name##type##GradKernel( \ + dev_ctx, x, y, dout, &dx, &dy); \ + return std::vector{dx, dy}; \ + } + +DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD(Add) +DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD(Subtract) +DEFINE_ELEMENTWISE_GRAD_KERNEL_HEAD(Multiply) + +DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC(Add) +DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC(Subtract) +DEFINE_ELEMENTWISE_GRAD_KERNEL_FUNC(Multiply) + +template +void ElementWiseDivideCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + const SparseCsrTensor& out, + const SparseCsrTensor& dout, + SparseCsrTensor* dx, + SparseCsrTensor* dy); + +template +void ElementWiseDivideCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& y, + const SparseCooTensor& out, + const SparseCooTensor& dout, + SparseCooTensor* dx, + SparseCooTensor* dy); + +template +std::vector ElementWiseDivideCsrGrad( + const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + const SparseCsrTensor& out, + const SparseCsrTensor& dout) { + SparseCsrTensor dx; + SparseCsrTensor dy; + MetaTensor meta_dx(&dx), meta_dy(&dy); + phi::UnchangedInferMeta(x, &meta_dx); + phi::UnchangedInferMeta(y, &meta_dy); + ElementWiseDivideCsrGradKernel( + dev_ctx, x, y, out, dout, &dx, &dy); + return std::vector{dx, dy}; +} + +template +std::vector ElementWiseDivideCooGrad( + const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& y, + const SparseCooTensor& out, + const SparseCooTensor& dout) { + SparseCooTensor dx; + SparseCooTensor dy; + MetaTensor meta_dx(&dx), meta_dy(&dy); + phi::UnchangedInferMeta(x, &meta_dx); + phi::UnchangedInferMeta(y, &meta_dy); + ElementWiseDivideCooGradKernel( + dev_ctx, x, y, out, dout, &dx, &dy); + return std::vector{dx, dy}; +} + +template +void ElementWiseAddDenseGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& y, + const SparseCooTensor& dout, + SparseCooTensor* dx, + DenseTensor* dy) { + DenseTensor* x_values_grad = nullptr; + DenseTensor* y_grad = nullptr; + if (dx) { + EmptyLikeCooKernel(dev_ctx, x, dx); + x_values_grad = dx->mutable_values(); + } + + if (dy) { + *dy = phi::EmptyLike(dev_ctx, y); + y_grad = dy; + } + phi::AddGradKernel( + dev_ctx, x.values(), y, dout.values(), -1, x_values_grad, y_grad); +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..515644d4fcfce299ff25bd475bfb959aa5970c23 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/elementwise_kernel.h @@ -0,0 +1,102 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/kernels/elementwise_add_kernel.h" +#include "paddle/phi/kernels/sparse/elementwise_kernel.h" +#include "paddle/phi/kernels/sparse/empty_kernel.h" + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { +namespace sparse { + +#define DEFINE_ELEMENTWISE_KERNEL_HEAD(name) \ + DEFINE_ELEMENTWISE_KERNEL_HEAD_WITH_TYPE(name, Csr) \ + \ + DEFINE_ELEMENTWISE_KERNEL_HEAD_WITH_TYPE(name, Coo) + +#define DEFINE_ELEMENTWISE_KERNEL_FUNC(name) \ + DEFINE_CSR_ELEMENTWISE_KERNEL_FUNC(name) \ + \ + DEFINE_COO_ELEMENTWISE_KERNEL_FUNC(name) + +#define DEFINE_ELEMENTWISE_KERNEL_HEAD_WITH_TYPE(name, type) \ + template \ + void ElementWise##name##type##Kernel(const Context& dev_ctx, \ + const Sparse##type##Tensor& x, \ + const Sparse##type##Tensor& y, \ + Sparse##type##Tensor* out); + +#define DEFINE_CSR_ELEMENTWISE_KERNEL_FUNC(name) \ + template \ + SparseCsrTensor ElementWise##name##Csr(const Context& dev_ctx, \ + const SparseCsrTensor& x, \ + const SparseCsrTensor& y) { \ + DenseTensor crows; \ + DenseTensor cols; \ + DenseTensor values; \ + SparseCsrTensor out(crows, cols, values, x.dims()); \ + MetaTensor meta_out(out); \ + phi::ElementwiseInferMeta(x, y, &meta_out); \ + ElementWise##name##CsrKernel(dev_ctx, x, y, &out); \ + return out; \ + } + +#define DEFINE_COO_ELEMENTWISE_KERNEL_FUNC(name) \ + template \ + SparseCooTensor ElementWise##name##Coo(const Context& dev_ctx, \ + const SparseCooTensor& x, \ + const SparseCooTensor& y) { \ + DenseTensor indices; \ + DenseTensor values; \ + SparseCooTensor out(indices, values, x.dims()); \ + MetaTensor meta_out(out); \ + phi::ElementwiseInferMeta(x, y, &meta_out); \ + ElementWise##name##CooKernel(dev_ctx, x, y, &out); \ + return out; \ + } + +DEFINE_ELEMENTWISE_KERNEL_HEAD(Add) +DEFINE_ELEMENTWISE_KERNEL_HEAD(Subtract) +DEFINE_ELEMENTWISE_KERNEL_HEAD(Multiply) +DEFINE_ELEMENTWISE_KERNEL_HEAD(Divide) + +DEFINE_ELEMENTWISE_KERNEL_FUNC(Add) +DEFINE_ELEMENTWISE_KERNEL_FUNC(Subtract) +DEFINE_ELEMENTWISE_KERNEL_FUNC(Multiply) +DEFINE_ELEMENTWISE_KERNEL_FUNC(Divide) + +template +void ElementWiseAddDenseKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& y, + SparseCooTensor* out) { + // TODO(zhangkaiuo): to support universal sparse + dense + if (y.dims().size() == 1 && y.dims()[0] == x.dims()[x.dims().size() - 1]) { + EmptyLikeCooKernel(dev_ctx, x, out); + phi::AddKernel(dev_ctx, x.values(), y, out->mutable_values()); + out->SetIndicesDict(x.GetIndicesDict()); + } else { + PADDLE_THROW( + errors::Unimplemented("Not support Sparse + Dense in GPU mode")); + } +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/empty_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/empty_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..29eb20af583da95c6585a8123d4e3f21170da9e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/empty_kernel.h @@ -0,0 +1,34 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +template +void EmptyLikeCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + SparseCooTensor* out); + +template +void EmptyLikeCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + SparseCsrTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/full_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/full_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8c84d43ff02194980a647df84a0159910fe05401 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/full_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/data_type.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { + +template +void CooFullLikeKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const Scalar& val, + DataType dtype, + SparseCooTensor* out); + +template +void CsrFullLikeKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const Scalar& val, + DataType dtype, + SparseCsrTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0a025d21f94f3ae5dec465d4801320d3c682a796 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_grad_kernel.h @@ -0,0 +1,35 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +template +void FusedAttentionCsrGradKernel(const Context& dev_ctx, + const DenseTensor& query, + const DenseTensor& key, + const DenseTensor& value, + const SparseCsrTensor& softmax, + const DenseTensor& dout, + DenseTensor* dquery, + DenseTensor* dkey, + DenseTensor* dvalue); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..340fdce0196c3f4ab35c6762083e4b231deb45a1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/fused_attention_kernel.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +template +void FusedAttentionCsrKernel( + const Context& dev_ctx, + const DenseTensor& query, + const DenseTensor& key, + const DenseTensor& value, + const SparseCsrTensor& sparse_mask, + const paddle::optional& key_padding_mask, + const paddle::optional& attn_mask, + DenseTensor* out, + SparseCsrTensor* softmax); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mask_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mask_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..88899e3dc672ee4f56961e9b55b804b94559317b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mask_kernel.h @@ -0,0 +1,36 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" + +namespace phi { +namespace sparse { + +template +void SparseMaskKernel(const Context& dev_ctx, + const DenseTensor& x, + const SparseCooTensor& mask, + SparseCooTensor* out); + +template +void SparseMaskHelperKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& mask_indices, + DenseTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4acb7bb7e1eb5d7021247af08337df0faeab545c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_grad_kernel.h @@ -0,0 +1,70 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +// TODO(zhouwei25): implement Backward of " COO @ COO -> COO" +template +void MatmulCooCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& y, + const SparseCooTensor& dout, + SparseCooTensor* dx, + SparseCooTensor* dy); + +// Backward of " COO @ DENSE -> DENSE" +template +void MatmulCooDenseGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + SparseCooTensor* dx, + DenseTensor* dy); + +// TODO(zhouwei25): implement Backward of " CSR @ CSR -> CSR" +template +void MatmulCsrCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + const SparseCsrTensor& dout, + SparseCsrTensor* dx, + SparseCsrTensor* dy); + +/* Backward of "CSR @ DENSE -> DENSE" */ +template +void MatmulCsrDenseGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const DenseTensor& y, + const DenseTensor& dout, + SparseCsrTensor* dx, + DenseTensor* dy); + +/* Backward of "DENSE @ DENSE * CSR_MASK -> CSR" */ +template +void MaskedMatmulCsrGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const SparseCsrTensor& dout, + DenseTensor* dx, + DenseTensor* dy); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a261bbf3cd3f757fb65198262097dad673e3838d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/matmul_kernel.h @@ -0,0 +1,61 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +// TODO(zhouwei25): implement " COO @ COO -> COO" +template +void MatmulCooCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& y, + SparseCooTensor* out); + +/* COO @ DENSE -> DENSE */ +template +void MatmulCooDenseKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& y, + DenseTensor* out); + +// TODO(zhouwei25): implement " CSR @ CSR -> CSR" +template +void MatmulCsrCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& y, + SparseCsrTensor* out); + +/* CSR @ DENSE -> DENSE */ +template +void MatmulCsrDenseKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const DenseTensor& y, + DenseTensor* out); + +/* DENSE @ DENSE * CSR_MASK -> CSR */ +template +void MaskedMatmulCsrKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const SparseCsrTensor& mask, + SparseCsrTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..778429992d3b926cb1ec502d1cf7fae3db4be087 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_grad_kernel.h @@ -0,0 +1,43 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +/* backward of COO @ DENSE VEC -> DENSE VEC */ +template +void MvCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& vec, + const DenseTensor& dout, + SparseCooTensor* dx, + DenseTensor* dvec); + +/* backward of CSR @ DENSE VEC -> DENSE VEC */ +template +void MvCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const DenseTensor& vec, + const DenseTensor& dout, + SparseCsrTensor* dx, + DenseTensor* dvec); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..57c598698d6d6a2944f9e57e9c3ec9e0a7a8809b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/mv_kernel.h @@ -0,0 +1,39 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +/* COO @ DENSE VEC -> DENSE VEC */ +template +void MvCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& vec, + DenseTensor* out); + +/* CSR @ DENSE VEC -> DENSE VEC */ +template +void MvCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const DenseTensor& vec, + DenseTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..47f3df6f9fb731436c64cfe30a730a5aa4becc32 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_grad_kernel.h @@ -0,0 +1,49 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +template +void MaxPoolCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& rulebook, + const DenseTensor& counter, + const SparseCooTensor& out, + const SparseCooTensor& out_grad, + const std::vector& kernel_sizes, + SparseCooTensor* x_grad); + +template +SparseCooTensor MaxPoolCooGrad(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& rulebook, + const DenseTensor& counter, + const SparseCooTensor& out, + const SparseCooTensor& out_grad, + const std::vector& kernel_sizes) { + SparseCooTensor x_grad; + MaxPoolCooGradKernel( + dev_ctx, x, rulebook, counter, out, out_grad, kernel_sizes, &x_grad); + return x_grad; +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..085cea82d3350eeef29221beb946e26ee95fa2be --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/pool_kernel.h @@ -0,0 +1,58 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +template +void MaxPoolCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const std::vector& kernel_sizes, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + SparseCooTensor* out, + DenseTensor* rulebook, + DenseTensor* counter); + +template +SparseCooTensor MaxPoolCoo(const Context& dev_ctx, + const SparseCooTensor& x, + const std::vector& kernel_sizes, + const std::vector& paddings, + const std::vector& dilations, + const std::vector& strides, + DenseTensor* rulebook, + DenseTensor* counter) { + SparseCooTensor coo; + MaxPoolCooKernel(dev_ctx, + x, + kernel_sizes, + paddings, + dilations, + strides, + &coo, + rulebook, + counter); + return coo; +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..abc5c26e8a5316ebca94dc970f7835720243bc22 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_grad_kernel.h @@ -0,0 +1,30 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +template +void SoftmaxCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& out, + const SparseCsrTensor& dout, + int axis, + SparseCsrTensor* dx); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..13f25dc7d23fc386f605b6cd2258282f42c091c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/softmax_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +template +void SoftmaxCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& X, + int axis, + SparseCsrTensor* out); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..08e68658d84e11fae1adc9e1b52970cada1f953d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_grad_kernel.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/kernels/sparse/mask_kernel.h" + +namespace phi { +namespace sparse { + +template +void ValuesCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& out_grad, + SparseCooTensor* x_grad); + +template +void CooToDenseGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& out_grad, + SparseCooTensor* x_grad); + +template +void SparseCooTensorGradKernel(const Context& dev_ctx, + const DenseTensor& indices, + const SparseCooTensor& out_grad, + DenseTensor* values_grad) { + SparseMaskHelperKernel(dev_ctx, out_grad, indices, values_grad); +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8639f91469454d1625773b287f4a17a87f6e7ff8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sparse_utils_kernel.h @@ -0,0 +1,177 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { +namespace sparse { + +template +void DenseToCooKernel(const Context& dev_ctx, + const DenseTensor& x, + const int64_t sparse_dim, + SparseCooTensor* out); + +template +SparseCooTensor DenseToCoo(const Context& dev_ctx, + const DenseTensor& x, + const int64_t sparse_dim) { + DenseTensor indices; + DenseTensor values; + SparseCooTensor coo(indices, values, x.dims()); + MetaTensor meta_out(&coo); + phi::UnchangedInferMeta(x, &meta_out); + DenseToCooKernel(dev_ctx, x, sparse_dim, &coo); + return coo; +} + +template +void CsrToCooKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + SparseCooTensor* out); + +template +SparseCooTensor CsrToCoo(const Context& dev_ctx, const SparseCsrTensor& x) { + DenseTensor indices; + DenseTensor values; + SparseCooTensor coo(indices, values, x.dims()); + MetaTensor meta_out(&coo); + phi::UnchangedInferMeta(x, &meta_out); + CsrToCooKernel(dev_ctx, x, &coo); + return coo; +} + +template +void CooToCsrKernel(const Context& dev_ctx, + const SparseCooTensor& x, + SparseCsrTensor* out); + +template +SparseCsrTensor CooToCsr(const Context& dev_ctx, const SparseCooTensor& x) { + DenseTensor crows; + DenseTensor cols; + DenseTensor non_zero_elements; + SparseCsrTensor csr(crows, cols, non_zero_elements, x.dims()); + MetaTensor meta_out(&csr); + phi::UnchangedInferMeta(x, &meta_out); + CooToCsrKernel(dev_ctx, x, &csr); + return csr; +} + +template +void DenseToCsrKernel(const Context& dev_ctx, + const DenseTensor& x, + SparseCsrTensor* out) { + const auto& x_dims = x.dims(); + bool valid = x_dims.size() == 2 || x_dims.size() == 3; + PADDLE_ENFORCE_EQ(valid, + true, + phi::errors::InvalidArgument( + "SparseCsrTensor only support 2-D or 3-D Tensor.")); + + const int64_t sparse_dim = x_dims.size() == 2 ? 2 : 3; + DenseTensor indices; + DenseTensor values; + SparseCooTensor coo(indices, values, x.dims()); + MetaTensor meta_out(&coo); + phi::UnchangedInferMeta(x, &meta_out); + DenseToCooKernel(dev_ctx, x, sparse_dim, &coo); + CooToCsrKernel(dev_ctx, coo, out); +} + +template +SparseCsrTensor DenseToCsr(const Context& dev_ctx, const DenseTensor& x) { + DenseTensor crows; + DenseTensor cols; + DenseTensor non_zero_elements; + SparseCsrTensor csr(crows, cols, non_zero_elements, x.dims()); + MetaTensor meta_out(&csr); + phi::UnchangedInferMeta(x, &meta_out); + DenseToCsrKernel(dev_ctx, x, &csr); + return csr; +} + +template +void CooToDenseKernel(const Context& dev_ctx, + const SparseCooTensor& x, + DenseTensor* out); + +template +DenseTensor CooToDense(const Context& dev_ctx, const SparseCooTensor& x) { + DenseTensorMeta meta(x.dtype(), x.dims(), x.non_zero_elements().layout()); + DenseTensor dense = phi::Empty(dev_ctx, std::move(meta)); + CooToDenseKernel(dev_ctx, x, &dense); + return dense; +} + +template +void CsrToDenseKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + DenseTensor* out) { + DenseTensor indices; + DenseTensor values; + SparseCooTensor coo(indices, values, x.dims()); + MetaTensor meta_out(&coo); + phi::UnchangedInferMeta(x, &meta_out); + CsrToCooKernel(dev_ctx, x, &coo); + CooToDenseKernel(dev_ctx, coo, out); +} + +template +DenseTensor CsrToDense(const Context& dev_ctx, const SparseCsrTensor& x) { + DenseTensorMeta meta(x.dtype(), x.dims(), x.non_zero_elements().layout()); + DenseTensor dense = phi::Empty(dev_ctx, std::move(meta)); + CsrToDenseKernel(dev_ctx, x, &dense); + return dense; +} + +template +void ValuesCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + DenseTensor* out) { + *out = x.non_zero_elements(); +} + +template +void ValuesCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + DenseTensor* out) { + *out = x.non_zero_elements(); +} + +template +void IndicesCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + DenseTensor* out) { + *out = x.indices(); +} + +template +void SparseCooTensorKernel(const Context& dev_ctx, + const DenseTensor& values, + const DenseTensor& indices, + const std::vector& shape, + SparseCooTensor* out) { + *out = SparseCooTensor(indices, values, phi::make_ddim(shape)); +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9591e6f035ca79695b1f9aed813154705928176c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_grad_kernel.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" + +namespace phi { +namespace sparse { + +template +void SyncBatchNormCooGradKernel( + const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const paddle::optional& reserve_space, + const SparseCooTensor& y_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + SparseCooTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7ee4baa107971f84940f9c8da583b33116dfb5ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/sync_batch_norm_kernel.h @@ -0,0 +1,47 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/sparse_coo_tensor.h" + +namespace phi { +namespace sparse { + +template +void SyncBatchNormCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& mean, + const DenseTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + SparseCooTensor* y, + DenseTensor* mean_out, + DenseTensor* variance_out, + DenseTensor* saved_mean, + DenseTensor* saved_variance, + DenseTensor* reserve_space); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b446e1b99ed411ff748f6cd5d2369f440d52c0f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_grad_kernel.h @@ -0,0 +1,105 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +#define DECLARE_SPARSE_UNARY_GRAD_KERNEL(prefix) \ + template \ + void prefix##CooGradKernel(const Context& dev_ctx, \ + const SparseCooTensor& x_or_out, \ + const SparseCooTensor& dout, \ + SparseCooTensor* dx); \ + \ + template \ + void prefix##CsrGradKernel(const Context& dev_ctx, \ + const SparseCsrTensor& x_or_out, \ + const SparseCsrTensor& dout, \ + SparseCsrTensor* dx); + +#define DECLARE_SPARSE_UNARY_GRAD_KERNEL_WITH_ONE_ATTR(prefix, attr) \ + template \ + void prefix##CooGradKernel(const Context& dev_ctx, \ + const SparseCooTensor& x_or_out, \ + const SparseCooTensor& dout, \ + float attr, \ + SparseCooTensor* dx); \ + \ + template \ + void prefix##CsrGradKernel(const Context& dev_ctx, \ + const SparseCsrTensor& x_or_out, \ + const SparseCsrTensor& dout, \ + float attr, \ + SparseCsrTensor* dx); + +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Sin) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Tan) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Asin) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Atan) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Sinh) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Asinh) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Atanh) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Relu) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Tanh) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Square) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Sqrt) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Log1p) +DECLARE_SPARSE_UNARY_GRAD_KERNEL(Abs) +DECLARE_SPARSE_UNARY_GRAD_KERNEL_WITH_ONE_ATTR(Pow, factor) + +template +void CastCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& dout, + DataType value_dtype, + SparseCooTensor* dx); + +template +void CastCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& dout, + DataType value_dtype, + SparseCsrTensor* dx); + +template +void TransposeCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& dout, + const std::vector& perm, + SparseCooTensor* dx); + +template +void TransposeCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& dout, + const std::vector& perm, + SparseCsrTensor* dx); + +template +void ReshapeCooGradKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const SparseCooTensor& dout, + SparseCooTensor* dx); + +template +void ReshapeCsrGradKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const SparseCsrTensor& dout, + SparseCsrTensor* dx); + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a81e724d1fe481b6fa421222162b6c01d43d1aef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse/unary_kernel.h @@ -0,0 +1,199 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/sparse_coo_tensor.h" +#include "paddle/phi/core/sparse_csr_tensor.h" + +namespace phi { +namespace sparse { + +#define DECLARE_SPARSE_UNARY_KERNEL(prefix) \ + template \ + void prefix##CooKernel( \ + const Context& dev_ctx, const SparseCooTensor& x, SparseCooTensor* out); \ + \ + template \ + void prefix##CsrKernel( \ + const Context& dev_ctx, const SparseCsrTensor& x, SparseCsrTensor* out); + +#define DECLARE_SPARSE_UNARY_KERNEL_WITH_ONE_ATTR(prefix, attr) \ + template \ + void prefix##CooKernel(const Context& dev_ctx, \ + const SparseCooTensor& x, \ + float attr, \ + SparseCooTensor* out); \ + \ + template \ + void prefix##CsrKernel(const Context& dev_ctx, \ + const SparseCsrTensor& x, \ + float attr, \ + SparseCsrTensor* out); + +DECLARE_SPARSE_UNARY_KERNEL(Sin) +DECLARE_SPARSE_UNARY_KERNEL(Tan) +DECLARE_SPARSE_UNARY_KERNEL(Asin) +DECLARE_SPARSE_UNARY_KERNEL(Atan) +DECLARE_SPARSE_UNARY_KERNEL(Sinh) +DECLARE_SPARSE_UNARY_KERNEL(Asinh) +DECLARE_SPARSE_UNARY_KERNEL(Atanh) +DECLARE_SPARSE_UNARY_KERNEL(Relu) +DECLARE_SPARSE_UNARY_KERNEL(Tanh) +DECLARE_SPARSE_UNARY_KERNEL(Square) +DECLARE_SPARSE_UNARY_KERNEL(Sqrt) +DECLARE_SPARSE_UNARY_KERNEL(Log1p) +DECLARE_SPARSE_UNARY_KERNEL(Abs) +DECLARE_SPARSE_UNARY_KERNEL_WITH_ONE_ATTR(Pow, factor) + +template +void ScaleCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + float scale, + float bias, + bool bias_after_scale, + SparseCooTensor* out); + +template +void ScaleCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + float scale, + float bias, + bool bias_after_scale, + SparseCsrTensor* out); + +template +void DivCooScalarKernel(const Context& dev_ctx, + const SparseCooTensor& x, + float scalar, + SparseCooTensor* out); + +template +void DivCsrScalarKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + float scalar, + SparseCsrTensor* out); + +template +void CastCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + DataType index_dtype, + DataType value_dtype, + SparseCooTensor* out); + +template +void CastCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + DataType index_dtype, + DataType value_dtype, + SparseCsrTensor* out); + +template +void TransposeCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const std::vector& perm, + SparseCooTensor* out); + +template +void TransposeCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const std::vector& perm, + SparseCsrTensor* out); + +template +SparseCooTensor TransposeCoo(const Context& dev_ctx, + const SparseCooTensor& x, + const std::vector& perm) { + PADDLE_ENFORCE_EQ(x.sparse_dim(), + perm.size(), + phi::errors::InvalidArgument( + "size of perm must be equal than the x.sparse_dim()")); + SparseCooTensor coo; + TransposeCooKernel(dev_ctx, x, perm, &coo); + return coo; +} + +template +SparseCsrTensor TransposeCsr(const Context& dev_ctx, + const SparseCsrTensor& x, + const std::vector& perm) { + PADDLE_ENFORCE_LE( + 2, + perm.size(), + phi::errors::InvalidArgument("size of perm must be equal to 2 or 3")); + PADDLE_ENFORCE_GE( + 3, + perm.size(), + phi::errors::InvalidArgument("size of perm must be equal to 2 or 3")); + SparseCsrTensor csr; + TransposeCsrKernel(dev_ctx, x, perm, &csr); + return csr; +} + +template +SparseCooTensor ReluCoo(const Context& dev_ctx, const SparseCooTensor& x) { + SparseCooTensor coo; + ReluCooKernel(dev_ctx, x, &coo); + return coo; +} + +template +SparseCooTensor ReluCsr(const Context& dev_ctx, const SparseCooTensor& x) { + SparseCooTensor csr; + ReluCsrKernel(dev_ctx, x, &csr); + return csr; +} + +template +void ReshapeCooKernel(const Context& dev_ctx, + const SparseCooTensor& x, + const phi::IntArray& shape, + SparseCooTensor* out); + +template +void ReshapeCsrKernel(const Context& dev_ctx, + const SparseCsrTensor& x, + const phi::IntArray& shape, + SparseCsrTensor* out); + +template +SparseCooTensor ReshapeCoo(const Context& dev_ctx, + const SparseCooTensor& x, + const phi::IntArray& shape) { + SparseCooTensor coo; + ReshapeCooKernel(dev_ctx, x, shape, &coo); + return coo; +} + +template +SparseCsrTensor ReshapeCsr(const Context& dev_ctx, + const SparseCsrTensor& x, + const phi::IntArray& shape) { + PADDLE_ENFORCE_LE( + 2, + shape.size(), + phi::errors::InvalidArgument("size of shape must be equal to 2 or 3")); + PADDLE_ENFORCE_GE( + 3, + shape.size(), + phi::errors::InvalidArgument("size of shape must be equal to 2 or 3")); + SparseCsrTensor csr; + ReshapeCsrKernel(dev_ctx, x, shape, &csr); + return csr; +} + +} // namespace sparse +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..772268c2cc3889db6c328fa99425dc6996320050 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_grad_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void SparseWeightEmbeddingGradKernel(const Context& ctx, + const DenseTensor& input, + const SelectedRows& weight, + const DenseTensor& out_grad, + int64_t padding_idx, + DenseTensor* weight_grad); + +template +void SparseWeightEmbeddingSparseGradKernel(const Context& ctx, + const DenseTensor& input, + const SelectedRows& weight, + const DenseTensor& out_grad, + int64_t padding_idx, + SelectedRows* weight_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c7392b691aa0fa4f0bc28e35cc29bb6aa902c34f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sparse_weight_embedding_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/selected_rows.h" + +namespace phi { + +template +void SparseWeightEmbeddingKernel(const Context& ctx, + const DenseTensor& inputx, + const SelectedRows& weight, + int64_t padding_idx, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..504cfba4b95e766fcc349b69637e00ade372e434 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_grad_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SpectrumNormGradKernel(const Context& dev_ctx, + const DenseTensor& weight, + const DenseTensor& u, + const DenseTensor& v, + const DenseTensor& out_grad, + int dim, + int power_iters, + float eps, + DenseTensor* weight_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..26b1699898ea6e09bf1700617aebfc341daefa0d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/spectral_norm_kernel.h @@ -0,0 +1,28 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SpectrumNormKernel(const Context& dev_ctx, + const DenseTensor& weight, + const DenseTensor& u, + const DenseTensor& v, + int dim, + int power_iters, + float eps, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/split_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/split_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..32d6cb4b64d77927cb63529ab54dad4e4ee0e5c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/split_kernel.h @@ -0,0 +1,97 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void SplitKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& sections, + const Scalar& axis, + std::vector out); + +template +void SplitWithNumKernel(const Context& dev_ctx, + const DenseTensor& x, + int num, + const Scalar& axis, + std::vector out); + +template +std::vector Split(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& sections, + const Scalar& axis) { + size_t out_number; + out_number = sections.GetData().size(); + + std::vector out_meta; + std::vector out_meta_ptr; + out_meta.reserve(out_number); + out_meta_ptr.reserve(out_number); + std::vector result(out_number); + + for (size_t i = 0; i < out_number; ++i) { + out_meta.emplace_back(&result[i]); + out_meta_ptr.push_back(&out_meta.back()); + } + SplitInferMeta(x, sections, axis, out_meta_ptr); + std::vector outs; + outs.reserve(out_meta.size()); + for (size_t i = 0; i < out_meta.size(); ++i) { + outs.push_back(&result[i]); + } + + SplitKernel(dev_ctx, x, sections, axis, outs); + return result; +} + +template +std::vector SplitWithNum(const Context& dev_ctx, + const DenseTensor& x, + int num, + const Scalar& axis) { + size_t out_number = num; + + std::vector out_meta; + std::vector out_meta_ptr; + out_meta.reserve(out_number); + out_meta_ptr.reserve(out_number); + std::vector result(out_number); + + for (size_t i = 0; i < out_number; ++i) { + out_meta.emplace_back(&result[i]); + out_meta_ptr.push_back(&out_meta.back()); + } + SplitWithNumInferMeta(x, num, axis, out_meta_ptr); + + std::vector outs; + outs.reserve(out_meta.size()); + for (size_t i = 0; i < out_meta.size(); ++i) { + outs.push_back(&result[i]); + } + + SplitWithNumKernel(dev_ctx, x, num, axis, outs); + + return result; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..78928ae3bfa076d843c17ed25b7dc7febd5b6f32 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_grad_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SquaredL2NormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& dout, + DenseTensor* dx); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e1dbbaa3cf458b89b44aca6b9afc92a1ee05cce4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squared_l2_norm_kernel.h @@ -0,0 +1,25 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SquaredL2NormKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8582012d2f6b65304b330e57fd9d5b4a14ad526a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_grad_kernel.h @@ -0,0 +1,29 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SqueezeGradKernel(const Context& dev_ctx, + const DenseTensor& xshape, + const DenseTensor& dout, + const IntArray& axes, + DenseTensor* dx); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..03d708b312089827f8032ef9b40f83bb2abd255b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/squeeze_kernel.h @@ -0,0 +1,47 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void SqueezeKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out); + +template +void SqueezeWithXShapeKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out, + DenseTensor* xshape); + +template +void Squeeze(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out) { + MetaTensor meta_out(out); + SqueezeInferMeta(x, axes, &meta_out); + SqueezeKernel(dev_ctx, x, axes, out); +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..32451e606f26ab207c932e39846fc3ad91960bc7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void StackGradKernel(const Context& dev_ctx, + const DenseTensor& out, + int axis, + std::vector x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..679c74063080e09127c778c737146f000c2687cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/stack_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void StackKernel(const Context& dev_ctx, + const std::vector& x, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8dfd3fd5bcc07dd927b43562f9441bd8c96f7bf4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_grad_kernel.h @@ -0,0 +1,56 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" + +namespace phi { + +template +void StridedSliceRawGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + const std::vector& infer_flags, + const std::vector& decrease_axis, + DenseTensor* x_grad); + +template +void StridedSliceGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + DenseTensor* x_grad); + +template +void StridedSliceArrayGradKernel(const Context& dev_ctx, + const TensorArray& x, + const TensorArray& out_grad, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + const std::vector& infer_flags, + const std::vector& decrease_axis, + TensorArray* x_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..35ffbeebd4a9a887688737efc6c3671b0a2fec25 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strided_slice_kernel.h @@ -0,0 +1,53 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/tensor_array.h" + +namespace phi { + +template +void StridedSliceRawKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + const std::vector& infer_flags, + const std::vector& decrease_axis, + DenseTensor* out); + +template +void StridedSliceKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + DenseTensor* out); + +template +void StridedSliceArrayKernel(const Context& dev_ctx, + const TensorArray& x, + const std::vector& axes, + const IntArray& starts, + const IntArray& ends, + const IntArray& strides, + const std::vector& infer_flags, + const std::vector& decrease_axis, + TensorArray* out); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/case_utils.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/case_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..66744c6915bc67dd7a606bb7d423c3b3d2ae8fb4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/case_utils.h @@ -0,0 +1,74 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#include + +#include "paddle/phi/common/pstring.h" +#include "paddle/phi/kernels/strings/unicode.h" +#if defined(__NVCC__) || defined(__HIPCC__) +#include +#include + +#include "paddle/phi/backends/gpu/gpu_context.h" +#endif + +namespace phi { +namespace strings { + +using pstring = dtype::pstring; +struct AsciiToLower { + HOSTDEVICE char operator()(char in) const { + return ('A' <= in && in <= 'Z') ? in - ('Z' - 'z') : in; + } +}; + +struct AsciiToUpper { + HOSTDEVICE char operator()(char in) const { + return ('a' <= in && in <= 'z') ? in ^ 0x20 : in; + } +}; + +template +struct UTF8ToLower { + HOSTDEVICE UTF8ToLower(const uint8_t* unicode_flag_map, + const uint16_t* cases_map) + : unicode_flag_map_(unicode_flag_map), cases_map_(cases_map) {} + + HOSTDEVICE uint32_t operator()(uint32_t in) const { + uint32_t flg = (in <= 0x00FFFF ? unicode_flag_map_[in] : 0); + return (strings::IsUpper(flg) ? cases_map_[in] : in); + } + + const uint8_t* unicode_flag_map_; + const uint16_t* cases_map_; +}; + +template +struct UTF8ToUpper { + HOSTDEVICE UTF8ToUpper(const uint8_t* unicode_flag_map, + const uint16_t* cases_map) + : unicode_flag_map_(unicode_flag_map), cases_map_(cases_map) {} + + HOSTDEVICE uint32_t operator()(uint32_t in) const { + uint32_t flg = (in <= 0x00FFFF ? unicode_flag_map_[in] : 0); + return (strings::IsLower(flg) ? cases_map_[in] : in); + } + + const uint8_t* unicode_flag_map_; + const uint16_t* cases_map_; +}; + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_copy_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_copy_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..557c6c0c5817d431f8be57ee415f96d138f19412 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_copy_kernel.h @@ -0,0 +1,29 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/string_tensor.h" + +namespace phi { +namespace strings { + +template +void Copy(const Context& dev_ctx, + const StringTensor& src, + bool blocking, + StringTensor* dst); + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_empty_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_empty_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8a014f2a78c2c2a25a0ce35e1b328aa3fb63f0d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_empty_kernel.h @@ -0,0 +1,68 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/api/lib/utils/allocator.h" +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/string_tensor.h" +#include "paddle/phi/infermeta/strings/nullary.h" +#include "paddle/phi/infermeta/strings/unary.h" + +namespace phi { +namespace strings { + +template +void EmptyKernel(const Context& dev_ctx, + const IntArray& shape, + StringTensor* out); + +template +void EmptyLikeKernel(const Context& dev_ctx, StringTensor* out); + +// TODO(zhoushunjie): the tensor creation method need to be replaced later, +// all kernel api call Empty here instead of making tensor self +template +StringTensor Empty(const Context& dev_ctx, StringTensorMeta&& meta) { + auto allocator = std::make_unique( + dev_ctx.GetPlace()); + phi::StringTensor string_out(allocator.get(), std::move(meta)); + return string_out; +} + +template +StringTensor Empty(const Context& dev_ctx) { + return Empty(dev_ctx, {{-1}}); +} + +template +StringTensor Empty(const Context& dev_ctx, const IntArray& shape) { + StringTensor string_out; + MetaTensor meta_out(&string_out); + phi::strings::CreateInferMeta(shape, &meta_out); + EmptyKernel(dev_ctx, shape, &string_out); + return string_out; +} + +template +StringTensor EmptyLike(const Context& dev_ctx, const StringTensor& x) { + StringTensor string_out; + MetaTensor meta_out(&string_out); + phi::strings::UnchangedInferMeta(x.meta(), &meta_out); + EmptyLikeKernel(dev_ctx, &string_out); + return string_out; +} + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_lower_upper_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_lower_upper_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..36486bc3ec686e87e0aedbaa8ae5e29b673fa3d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/strings_lower_upper_kernel.h @@ -0,0 +1,122 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#include +#include + +#include "paddle/phi/api/lib/utils/allocator.h" +#include "paddle/phi/core/string_tensor.h" +#include "paddle/phi/infermeta/strings/unary.h" +#include "paddle/phi/kernels/strings/case_utils.h" + +using pstring = ::phi::dtype::pstring; + +namespace phi { +namespace strings { + +template +void StringLowerKernel(const ContextT& dev_ctx, + const StringTensor& x, + bool use_utf8_encoding, + StringTensor* out); + +template +void StringUpperKernel(const ContextT& dev_ctx, + const StringTensor& x, + bool use_utf8_encoding, + StringTensor* out); + +template +StringTensor StringLower(const ContextT& dev_ctx, + const StringTensor& x, + bool use_utf8_encoding) { + StringTensor string_out; + MetaTensor meta_out(&string_out); + UnchangedInferMeta(x.meta(), &meta_out); + StringLowerKernel(dev_ctx, x, use_utf8_encoding, &string_out); + return string_out; +} + +template +StringTensor StringUpper(const ContextT& dev_ctx, + const StringTensor& x, + bool use_utf8_encoding) { + StringTensor string_out; + MetaTensor meta_out(&string_out); + UnchangedInferMeta(x.meta(), &meta_out); + StringUpperKernel(dev_ctx, x, use_utf8_encoding, &string_out); + return string_out; +} + +template +struct StringCaseConvertKernel { + void operator()(const ContextT& dev_ctx, + const StringTensor& x, + bool use_utf8_encoding, + StringTensor* out) { + AsciiCoverter ascii_converter; + UTF8Converter utf8_converter; + const pstring* in_ptr = x.data(); + pstring* out_ptr = dev_ctx.template Alloc(out); + auto num = x.numel(); + if (!use_utf8_encoding) { + ascii_converter(dev_ctx, in_ptr, out_ptr, num); + } else { + utf8_converter(dev_ctx, in_ptr, out_ptr, num); + } + } +}; + +template +struct AsciiCaseConverter { + void operator()(const DeviceContext& dev_ctx, + const pstring* in, + pstring* out, + size_t num) const { + for (size_t i = 0; i < num; ++i) { + std::transform( + in[i].begin(), in[i].end(), out[i].mdata(), CharConverter()); + } + } +}; + +template + typename CharConverter> +struct UTF8CaseConverter { + void operator()(const DeviceContext& dev_ctx, + const pstring* in, + pstring* out, + size_t num) const { + auto unicode_flag_map = GetUniFlagMap(); + auto cases_map = GetCharcasesMap(); + for (size_t i = 0; i < num; ++i) { + uint32_t unicode_len = GetUnicodeStrLen(in[i].data(), in[i].size()); + std::vector unicode_in(unicode_len, 0); + GetUnicodeStr(in[i].data(), unicode_in.data(), unicode_len); + std::transform(unicode_in.begin(), + unicode_in.end(), + unicode_in.begin(), + CharConverter(unicode_flag_map, cases_map)); + uint32_t utf8_len = GetUTF8StrLen(unicode_in.data(), unicode_len); + std::vector result(utf8_len, 0); + GetUTF8Str(unicode_in.data(), result.data(), unicode_len); + out[i] = result.data(); + } + } +}; + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode.h new file mode 100644 index 0000000000000000000000000000000000000000..45e41b72d086c0a32797a694a9c0972d7b8634f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode.h @@ -0,0 +1,198 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include +#include + +#include "paddle/phi/core/hostdevice.h" +#include "paddle/phi/core/macros.h" + +namespace phi { +namespace strings { + +HOSTDEVICE inline bool IsSpace(uint32_t chr) { return (chr & 16) > 0; } + +HOSTDEVICE inline bool IsAlpha(uint32_t chr) { return (chr & 8) > 0; } + +HOSTDEVICE inline bool IsDigit(uint32_t chr) { return (chr & 4) > 0; } + +HOSTDEVICE inline bool IsNumeric(uint32_t chr) { return (chr & 2) > 0; } + +HOSTDEVICE inline bool IsDecimal(uint32_t chr) { return (chr & 1) > 0; } + +HOSTDEVICE inline bool IsAlphaNum(uint32_t chr) { return (chr & 15) > 0; } + +HOSTDEVICE inline bool IsUpper(uint32_t chr) { return (chr & 32) > 0; } + +HOSTDEVICE inline bool IsLower(uint32_t chr) { return (chr & 64) > 0; } + +HOSTDEVICE inline uint32_t BytesInUtf8Char(uint8_t byte) { + unsigned int count = 1; + // no if-statements means no divergence + count += static_cast((byte & 0xF0) == 0xF0); + count += static_cast((byte & 0xE0) == 0xE0); + count += static_cast((byte & 0xC0) == 0xC0); + count -= static_cast((byte & 0xC0) == 0x80); + return count; +} + +HOSTDEVICE inline uint32_t UTF8ToUInt32(const char* pSrc, uint32_t* chr) { + uint32_t chwidth = BytesInUtf8Char(static_cast(*pSrc)); + *chr = static_cast(*pSrc++) & 0xFF; + if (chwidth > 1) { + *chr = (*chr) << 8; + *chr |= (static_cast(*pSrc++) & 0xFF); // << 8; + if (chwidth > 2) { + *chr = (*chr) << 8; + *chr |= (static_cast(*pSrc++) & 0xFF); // << 16; + if (chwidth > 3) { + *chr = (*chr) << 8; + *chr |= (static_cast(*pSrc++) & 0xFF); // << 24; + } + } + } + return chwidth; +} + +HOSTDEVICE inline uint32_t UTF8ToUnicode(uint32_t utf8) { + uint32_t unchr = 0; + if (utf8 < 0x00000080) { + unchr = utf8; + } else if (utf8 < 0x0000E000) { + unchr = (utf8 & 0x1F00) >> 2; + unchr |= (utf8 & 0x003F); + } else if (utf8 < 0x00F00000) { + unchr = (utf8 & 0x0F0000) >> 4; + unchr |= (utf8 & 0x003F00) >> 2; + unchr |= (utf8 & 0x00003F); + } else if (utf8 <= static_cast(0xF8000000)) { + unchr = (utf8 & 0x03000000) >> 6; + unchr |= (utf8 & 0x003F0000) >> 4; + unchr |= (utf8 & 0x00003F00) >> 2; + unchr |= (utf8 & 0x0000003F); + } + return unchr; +} + +HOSTDEVICE inline uint32_t UnicodeToUTF8(uint32_t unchr) { + uint32_t utf8 = 0; + if (unchr < 0x00000080) { + utf8 = unchr; + } else if (unchr < 0x00000800) { + utf8 = (unchr << 2) & 0x1F00; + utf8 |= (unchr & 0x3F); + utf8 |= 0x0000C080; + } else if (unchr < 0x00010000) { + utf8 = (unchr << 4) & 0x0F0000; // upper 4 bits + utf8 |= (unchr << 2) & 0x003F00; // next 6 bits + utf8 |= (unchr & 0x3F); // last 6 bits + utf8 |= 0x00E08080; + } else if (unchr < 0x00110000) { // 3-byte unicode + utf8 = (unchr << 6) & 0x07000000; // upper 3 bits + utf8 |= (unchr << 4) & 0x003F0000; // next 6 bits + utf8 |= (unchr << 2) & 0x00003F00; // next 6 bits + utf8 |= (unchr & 0x3F); // last 6 bits + utf8 |= static_cast(0xF0808080); + } + return utf8; +} + +HOSTDEVICE inline uint32_t BytesInUnicodeChar(uint32_t chr) { + uint32_t count = 1; + // no if-statements means no divergence + count += static_cast((chr & static_cast(0x0000FF00)) > 0); + count += static_cast((chr & static_cast(0x00FF0000)) > 0); + count += static_cast((chr & static_cast(0xFF000000)) > 0); + return count; +} + +HOSTDEVICE inline uint32_t UnicodeToUTF8Char(uint32_t chr, char* dst) { + uint32_t chwidth = BytesInUnicodeChar(chr); + for (uint32_t idx = 0; idx < chwidth; ++idx) { + dst[chwidth - idx - 1] = static_cast(chr & 0xFF); + chr = chr >> 8; + } + return chwidth; +} + +HOSTDEVICE inline void GetUnicodeStr(const char* pSrc, + uint32_t* unicode_str, + size_t unicode_len) { + uint32_t curr_unicode_char; + uint32_t count = UTF8ToUInt32(pSrc, &curr_unicode_char); + curr_unicode_char = UTF8ToUnicode(curr_unicode_char); + for (size_t i = 0; i < unicode_len; ++i) { + unicode_str[i] = curr_unicode_char; + pSrc += count; + count = UTF8ToUInt32(pSrc, &curr_unicode_char); + curr_unicode_char = UTF8ToUnicode(curr_unicode_char); + } +} + +HOSTDEVICE inline uint32_t GetUnicodeStrLen(const char* pSrc, size_t size) { + uint32_t curr_unicode_char; + uint32_t count = 0; + uint32_t offset = 0; + uint32_t curr_count = 0; + while (offset < size) { + curr_count = UTF8ToUInt32(pSrc, &curr_unicode_char); + offset += curr_count; + pSrc += curr_count; + if (curr_count == 0) { + break; + } + ++count; + } + return count; +} + +HOSTDEVICE inline uint32_t GetUTF8StrLen(const uint32_t* unicode_str, + size_t unicode_len) { + uint32_t utf8_str_count = 0; + for (size_t i = 0; i < unicode_len; ++i) { + uint32_t utf8_uint32 = UnicodeToUTF8(unicode_str[i]); + utf8_str_count += BytesInUnicodeChar(utf8_uint32); + } + // +1 means '\0' + return utf8_str_count + 1; +} +// Need to gurantee utf8_str has enough memory + +HOSTDEVICE inline void GetUTF8Str(const uint32_t* unicode_str, + char* utf8_str, + size_t unicode_len) { + char dst_char[5] = {0}; + for (size_t i = 0; i < unicode_len; ++i) { + uint32_t utf8_uint32 = UnicodeToUTF8(unicode_str[i]); + uint32_t utf8_char_count = UnicodeToUTF8Char(utf8_uint32, dst_char); + dst_char[utf8_char_count] = '\0'; + memcpy(utf8_str, dst_char, utf8_char_count); + utf8_str += utf8_char_count; + } + *utf8_str = '\0'; +} + +const uint8_t* GetUniFlagMap(); +const uint16_t* GetCharcasesMap(); + +#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) + +const uint8_t* GetGPUUniflagMap(); +const uint16_t* GetGPUCharcasesMap(); +#endif + +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode_flag.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode_flag.h new file mode 100644 index 0000000000000000000000000000000000000000..7e97b80c2c642a3e16b033b1311f3bdd0212f94b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/strings/unicode_flag.h @@ -0,0 +1,3473 @@ +/* Copyright (c) 2022 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. */ + +#pragma once +#include "paddle/phi/core/macros.h" + +namespace phi { +namespace strings { +UNUSED static uint8_t UNIFLAG_MAP[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, 0, 0, 0, + 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, + 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 72, 0, 0, 0, 6, 72, 0, 2, 2, + 2, 0, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 0, 40, 40, 40, 40, 40, 40, 40, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 0, 72, 72, 72, 72, 72, 72, 72, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 40, 72, 40, + 72, 40, 72, 72, 72, 40, 40, 72, 40, 72, 40, 40, 72, 40, 40, 40, 72, 72, 40, + 40, 40, 40, 72, 40, 40, 72, 40, 40, 40, 72, 72, 72, 40, 40, 72, 40, 40, 72, + 40, 72, 40, 72, 40, 40, 72, 40, 72, 72, 40, 72, 40, 40, 72, 40, 40, 40, 72, + 40, 72, 40, 40, 72, 72, 8, 40, 72, 72, 72, 8, 8, 8, 8, 40, 8, 72, 40, + 8, 72, 40, 8, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 72, 40, 8, 72, 40, 72, 40, 40, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 72, 72, 72, 72, 72, + 40, 40, 72, 40, 40, 72, 72, 40, 72, 40, 40, 40, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 8, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 8, 8, 8, 8, 8, 8, + 8, 72, 72, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 72, 72, 72, 72, + 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 40, 72, 40, 72, 8, 0, 40, 72, 0, 0, 72, 72, 72, + 72, 0, 40, 0, 0, 0, 0, 0, 0, 40, 0, 40, 40, 40, 0, 40, 0, 40, 40, + 72, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 40, 72, 72, 40, 40, 40, 72, 72, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 72, 72, 72, 72, 40, 72, 0, 40, 72, 40, 40, 72, 72, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 0, 0, 0, 0, 0, + 0, 0, 0, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 0, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, + 0, 8, 0, 0, 0, 0, 0, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, + 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 8, 8, 0, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, + 0, 0, 0, 0, 0, 0, 0, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 8, 8, 8, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, + 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 0, 0, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 0, 0, 0, 8, 8, 8, + 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, + 8, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, + 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 8, 8, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, + 8, 8, 8, 8, 8, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 0, 8, 0, 0, 0, 0, 0, + 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 8, 8, 8, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, + 8, 0, 8, 8, 0, 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 0, + 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 0, 8, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 0, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 8, 8, 0, 8, 8, + 8, 8, 0, 0, 0, 8, 8, 0, 8, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, + 0, 8, 8, 8, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 2, 2, 2, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, + 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 0, 8, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 0, 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, + 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 2, 2, 2, 2, + 2, 2, 2, 8, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 8, 8, 8, 8, 8, 8, 0, 0, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 8, 0, + 0, 8, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, + 8, 0, 8, 8, 8, 0, 8, 0, 8, 0, 0, 8, 8, 0, 8, 8, 8, 8, 0, + 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 8, 8, 8, 8, + 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 0, 0, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 0, 8, 8, 8, 8, 0, 0, 0, 8, 0, 0, 0, 8, 8, + 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 0, 40, 0, 0, 0, 0, 0, 40, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 0, 8, 0, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, + 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, + 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 0, 8, 8, 8, 8, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, + 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, + 0, 72, 72, 72, 72, 72, 72, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 2, + 2, 2, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 0, 0, 0, 0, 8, 0, 0, 0, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 0, 8, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 0, 0, 0, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 0, 8, 8, 8, 8, + 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 72, 72, 72, 72, 72, 72, 72, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 40, 40, 40, 40, 40, 40, 40, 40, 72, 72, 72, 72, 72, 72, 0, 0, 40, + 40, 40, 40, 40, 40, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 40, 40, 40, 40, + 40, 40, 40, 40, 72, 72, 72, 72, 72, 72, 72, 72, 40, 40, 40, 40, 40, 40, 40, + 40, 72, 72, 72, 72, 72, 72, 0, 0, 40, 40, 40, 40, 40, 40, 0, 0, 72, 72, + 72, 72, 72, 72, 72, 72, 0, 40, 0, 40, 0, 40, 0, 40, 72, 72, 72, 72, 72, + 72, 72, 72, 40, 40, 40, 40, 40, 40, 40, 40, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 8, 8, 8, + 8, 8, 8, 8, 8, 72, 72, 72, 72, 72, 72, 72, 72, 8, 8, 8, 8, 8, 8, + 8, 8, 72, 72, 72, 72, 72, 72, 72, 72, 8, 8, 8, 8, 8, 8, 8, 8, 72, + 72, 72, 72, 72, 0, 72, 72, 40, 40, 40, 40, 8, 0, 72, 0, 0, 0, 72, 72, + 72, 0, 72, 72, 40, 40, 40, 40, 8, 0, 0, 0, 72, 72, 72, 72, 0, 0, 72, + 72, 40, 40, 40, 40, 0, 0, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 40, 40, + 40, 40, 40, 0, 0, 0, 0, 0, 72, 72, 72, 0, 72, 72, 40, 40, 40, 40, 8, + 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 6, 72, 0, 0, 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0, 72, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, + 40, 0, 0, 72, 40, 40, 40, 72, 72, 40, 40, 40, 72, 0, 40, 0, 0, 0, 40, + 40, 40, 40, 40, 0, 0, 0, 0, 0, 0, 40, 0, 40, 0, 40, 0, 40, 40, 40, + 40, 0, 72, 40, 40, 40, 40, 72, 8, 8, 8, 8, 72, 0, 0, 72, 72, 40, 40, + 0, 0, 0, 0, 0, 40, 72, 72, 72, 72, 0, 0, 0, 0, 72, 0, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 34, 34, 34, 34, 34, 34, + 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 66, 66, 66, 66, 66, 66, 66, 66, 66, + 66, 66, 66, 66, 66, 66, 66, 2, 2, 2, 40, 72, 2, 2, 2, 2, 2, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 6, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 2, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 40, 72, + 40, 40, 40, 72, 72, 40, 72, 40, 72, 40, 72, 40, 40, 40, 40, 72, 40, 72, 72, + 40, 72, 72, 72, 72, 72, 72, 72, 72, 40, 40, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 0, 0, + 0, 0, 0, 0, 40, 72, 40, 72, 0, 0, 0, 40, 72, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 2, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 0, 72, 0, 0, 0, 0, 0, 72, 0, 0, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, + 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, + 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, + 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, + 8, 8, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 0, 0, 2, 2, 2, 8, 8, 0, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, + 8, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 2, 2, + 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 10, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, + 8, 8, 10, 8, 8, 8, 10, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 10, 8, 10, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 10, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, + 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, + 10, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 10, 10, 10, + 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 8, 10, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 10, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, + 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 72, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 72, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 40, 72, 40, 72, 40, 40, 72, 40, 72, 40, + 72, 40, 72, 40, 72, 8, 0, 0, 40, 72, 40, 72, 8, 40, 72, 40, 72, 72, 72, + 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, 72, 40, + 72, 40, 40, 40, 40, 40, 0, 40, 40, 40, 40, 40, 72, 40, 72, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 72, 72, 72, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, 0, 8, + 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, 0, 8, 0, + 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 8, 8, 8, + 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, + 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 8, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 0, 0, + 0, 8, 8, 0, 0, 8, 8, 8, 8, 8, 0, 0, 8, 0, 8, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 0, 0, 0, 0, 0, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, + 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, + 8, 0, 8, 8, 8, 8, 8, 8, 8, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, + 10, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 10, + 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 72, + 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 72, + 72, 72, 72, 0, 0, 0, 0, 0, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 8, 8, 8, + 8, 8, 0, 8, 0, 8, 8, 0, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 8, 8, 8, 8, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, 0, + 0, 0, 0, 0, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, + 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, 8, 8, 8, 0, 0, 8, 8, 8, + 8, 8, 8, 0, 0, 8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, +}; +} // namespace strings +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..66331a71912859627c832aacc3152bd243904197 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SvdGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& u, + const DenseTensor& vh, + const DenseTensor& s, + const paddle::optional& u_grad, + const paddle::optional& vh_grad, + const paddle::optional& s_grad, + bool full_matrices, + DenseTensor* X_grad); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1497f5a604f971aa17be0971c5a8e3ca27e035ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/svd_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SvdKernel(const Context& dev_ctx, + const DenseTensor& X, + bool full_matrices, + DenseTensor* U, + DenseTensor* S, + DenseTensor* VH); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a38f42c29f62d090cce9debb54543043b26f51ad --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_grad_kernel.h @@ -0,0 +1,43 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SyncBatchNormGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& saved_mean, + const DenseTensor& saved_variance, + const paddle::optional& reserve_space, + const DenseTensor& y_grad, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + DenseTensor* x_grad, + DenseTensor* scale_grad, + DenseTensor* bias_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5071eaabf8653404951566c44b0294ef3b4441c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/sync_batch_norm_kernel.h @@ -0,0 +1,43 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void SyncBatchNormKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& scale, + const DenseTensor& bias, + const DenseTensor& mean, + const DenseTensor& variance, + float momentum, + float epsilon, + const std::string& data_layout, + bool is_test, + bool use_global_stats, + bool trainable_statistics, + bool fuse_with_relu, + DenseTensor* y, + DenseTensor* mean_out, + DenseTensor* variance_out, + DenseTensor* saved_mean, + DenseTensor* saved_variance, + DenseTensor* reserve_space); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a312c235f66fc6f58f7bbb2a29f78d8ff4b427eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TakeAlongAxisGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + const DenseTensor& out_grad, + int axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e8fb78556d9bbe9c6ceced660a03c7ddc3dd1dc6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/take_along_axis_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TakeAlongAxisKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& index, + int axis, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1bcd3d61c26f538827896411a21a5b1e5aa1c127 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TemporalShiftGradKernel(const Context& ctx, + const DenseTensor& out_grad, + int seg_num, + float shift_ratio, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a927d7fb23aae68e6422ed0ac80dbfaa8ac0da58 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/temporal_shift_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TemporalShiftKernel(const Context& ctx, + const DenseTensor& x, + int seg_num, + float shift_ratio, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d40a0f4dfce7b24b63b18395f3c4fea83279e44e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_grad_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +#define MAX_RANK_SUPPORTED 6 + +namespace phi { + +template +void TileGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const IntArray& repeat_times, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..32e3685e8569e46b509e1df4e554f2bdbde933a7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tile_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +#define MAX_RANK_SUPPORTED 6 + +namespace phi { + +template +void TileKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& repeat_times, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e4fde92dad8fdebf97bd66861a9f9d61ee774694 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_grad_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TopkGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const DenseTensor& out_grad, + const Scalar& k, + int axis, + bool largest, + bool sorted, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fea76e448b5438634b8475c4fb783688d62c4905 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/top_k_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TopkKernel(const Context& dev_ctx, + const DenseTensor& x, + const Scalar& k_scalar, + int axis, + bool largest, + bool sorted, + DenseTensor* out, + DenseTensor* indices); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4884e53b4efe50e1cb805ea616ebb332c976e0a7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TraceGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + int offset, + int axis1, + int axis2, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3f5bc333c21369b1c4091187a9e5eed8b5aa043b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trace_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Trace Kernel. + * Return the sum along diagonals of the input tensor. + * The behavior of this operator is similar to how `numpy.trace` works. + * + * If Input is 2-D, returns the sum of diagonal. + * If Input has larger dimensions, then returns an tensor of diagonals + * sum, diagonals be taken from the 2-D planes specified by dim1 and + * dim2. + * @param ctx device context + * @param x The input tensor, from which the diagonals are taken + * @param offset offset of the diagonal from the main diagonal. + * Can be bothpositive and negative. + * @param axis1 the first axis of the 2-D planes from which the diagonals + * should be taken. Can be either positive or negative + * @param axis2 the second axis of the 2-D planes from which the diagonals + * should be taken. Can be either positive or negative + * @param out the sum along diagonals of the input tensor + */ +template +void TraceKernel(const Context& ctx, + const DenseTensor& x, + int offset, + int axis1, + int axis2, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transfer_layout_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transfer_layout_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..73e12927d7ffe5c32cfad64f3b6d1c24d97538fa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transfer_layout_kernel.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2022 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void TransferLayoutKernel(const Context& dev_ctx, + const DenseTensor& x, + int src_layout, + int dst_layout, + DenseTensor* out); + +template +DenseTensor TransferLayout(const Context& dev_ctx, + const DenseTensor& x, + DataLayout dst_layout) { + phi::DenseTensor dense_out = + phi::Empty(dev_ctx, {x.dtype(), x.dims(), dst_layout}); + TransferLayoutKernel(dev_ctx, + x, + static_cast(x.layout()), + static_cast(dst_layout), + &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e224da81a25d0702e63af0bab31e1bc4afbfc607 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_grad_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TransposeGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + const std::vector& axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b8d7fbaa2757d76db1005ce57498d181046d77c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/transpose_kernel.h @@ -0,0 +1,53 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" +#include "paddle/phi/kernels/empty_kernel.h" + +namespace phi { + +template +void TransposeKernel(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& axis, + DenseTensor* out); + +template +DenseTensor Transpose(const Context& dev_ctx, + const DenseTensor& x, + const std::vector& axis) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + TransposeInferMeta(x, axis, &meta_out); + TransposeKernel(dev_ctx, x, axis, &dense_out); + return dense_out; +} + +template +DenseTensor TransposeLast2Dim(const Context& dev_ctx, const DenseTensor& x) { + size_t rank = x.dims().size(); + std::vector axis(rank); + for (size_t i = 0; i < rank; ++i) { + axis[i] = i; + } + std::swap(axis[rank - 1], axis[rank - 2]); + return Transpose(dev_ctx, x, axis); +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..eb5a5ab461a1dcbbdec916dff57e65df5d9cfd9b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_grad_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/backends/cpu/cpu_context.h" +#include "paddle/phi/backends/gpu/gpu_context.h" +#include "paddle/phi/core/ddim.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TriangularSolveGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out, + const DenseTensor& dout, + bool upper, + bool transpose, + bool unitriangular, + DenseTensor* dx, + DenseTensor* dy); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3aa5b931249fdc52bbe55b568f81e7f52fe5c5af --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triangular_solve_kernel.h @@ -0,0 +1,46 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/binary.h" + +namespace phi { + +template +void TriangularSolveKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& y, + bool upper, + bool transpose, + bool unitriangular, + DenseTensor* out); + +template +DenseTensor TriangularSolve(const Context& ctx, + const DenseTensor& x, + const DenseTensor& y, + bool upper, + bool transpose, + bool unitriangular) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + TriangularSolveInferMeta(x, y, upper, transpose, unitriangular, &meta_out); + TriangularSolveKernel( + ctx, x, y, upper, transpose, unitriangular, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_indices_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_indices_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1132a539ee6d11ec5cbc44cbb75a1303d406b407 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_indices_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TrilIndicesKernel(const Context& dev_ctx, + int rows, + int cols, + int offset, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..10faf5c48d5bffab9f5199ebeefe7d5a2267ecea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_grad_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TrilTriuGradKernel(const Context& ctx, + const DenseTensor& out_grad, + int diagonal, + bool lower, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..8d4c44c5b35e296ca2a6b732e49d75b41dfa30d7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/tril_triu_kernel.h @@ -0,0 +1,41 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void TrilTriuKernel(const Context& ctx, + const DenseTensor& x, + int diagonal, + bool lower, + DenseTensor* out); + +template +DenseTensor TrilTriu(const Context& ctx, + const DenseTensor& x, + int diagonal, + bool lower) { + DenseTensor dense_out; + MetaTensor meta_out(&dense_out); + TrilTriuInferMeta(x, diagonal, lower, &meta_out); + TrilTriuKernel(ctx, x, diagonal, lower, &dense_out); + return dense_out; +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triu_indices_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triu_indices_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5f1e09a8b65e4f43ef19ed98ec983262974416b2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/triu_indices_kernel.h @@ -0,0 +1,29 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TriuIndicesKernel(const Context& dev_ctx, + int row, + int col, + int offset, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f3f8032d3a23c689cd8ac67383edfbafdfb4db4f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_grad_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TruncGradKernel(const Context& dev_ctx, + const DenseTensor& out_grad, + DenseTensor* in_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d9a7ea633934884baf7174579c5b9b41fc1585a1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/trunc_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/** + * @brief Returns a new tensor with the truncated integer values of input. + * @param ctx device context + * @param x The input tensor of trunc kernel + * @param out The output tensor of trunc kernel + */ +template +void TruncKernel(const Context& dev_ctx, + const DenseTensor& x, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/truncated_gaussian_random_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/truncated_gaussian_random_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..773bfc8c71eacc3cf2707dfcde246cd5ae11c1ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/truncated_gaussian_random_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void TruncatedGaussianRandomKernel(const Context& dev_ctx, + const std::vector& shape, + float mean, + float std, + int seed, + DataType dtype, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unbind_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unbind_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..30ee9a15d084e7d33ab6b392592be0c9b8f3789a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unbind_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +/* + * All tensors' dimension should be the same and the values of + * each dimension must be the same, except the axis dimension. + */ +template +void UnbindKernel(const Context& ctx, + const DenseTensor& x, + int axis, + std::vector outs); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6578cf8c650b4ac3da7f94489717b80c28451d56 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void UnfoldGradKernel(const Context& ctx, + const DenseTensor& x, + const DenseTensor& out_grad, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..d26805e97869746f1170dee4a08a37c32405d089 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unfold_kernel.h @@ -0,0 +1,31 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void UnfoldKernel(const Context& ctx, + const DenseTensor& x, + const std::vector& kernel_sizes, + const std::vector& strides, + const std::vector& paddings, + const std::vector& dilations, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ae74fbe2fd78c48cfc19939cd25265e83e9b72cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_grad_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UniformRandomInplaceGradKernel(const Context& ctx, + const DenseTensor& out_grad, + float min, + float max, + int seed, + int diag_num, + int diag_step, + float diag_val, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..97a79375aff194c70c1db017593dc445a71df460 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_inplace_kernel.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2021 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. */ + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UniformRandomInplaceKernel(const Context& ctx, + const DenseTensor& x, + float min, + float max, + int seed, + int diag_num, + int diag_step, + float diag_val, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..1395a4663b91400343b41314dc6988e52b25e789 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/uniform_random_kernel.h @@ -0,0 +1,45 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/common/scalar.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/core/device_context.h" + +namespace phi { + +template +void UniformRandomRawKernel(const Context& dev_ctx, + const IntArray& shape, + DataType dtype, + const Scalar& min, + const Scalar& max, + int seed, + int diag_num, + int diag_step, + float diag_val, + DenseTensor* out); + +template +void UniformRandomKernel(const Context& dev_ctx, + const IntArray& shape, + DataType dtype, + const Scalar& min, + const Scalar& max, + int seed, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_consecutive_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_consecutive_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ade35d4d49730e5813987cb3ddd6fba1f864d504 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_consecutive_kernel.h @@ -0,0 +1,34 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UniqueConsecutiveKernel(const Context& dev_ctx, + const DenseTensor& x, + bool return_inverse, + bool return_counts, + const std::vector& axis, + int dtype, + DenseTensor* out, + DenseTensor* index, + DenseTensor* counts); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..353570c8e7da3faba8f56e669c46a0538ff52eb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unique_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UniqueKernel(const Context& dev_ctx, + const DenseTensor& x, + bool return_index, + bool return_inverse, + bool return_counts, + const std::vector& axis, + DataType dtype, + DenseTensor* out, + DenseTensor* indices, + DenseTensor* index, + DenseTensor* counts); + +template +void UniqueRawKernel(const Context& dev_ctx, + const DenseTensor& x, + bool return_index, + bool return_inverse, + bool return_counts, + const std::vector& axis, + DataType dtype, + bool is_sorted, + DenseTensor* out, + DenseTensor* indices, + DenseTensor* index, + DenseTensor* counts); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..998151fcdd32b73159618b352ec39f282df140aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_grad_kernel.h @@ -0,0 +1,48 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UnpoolGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const DenseTensor& out, + const DenseTensor& out_grad, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const IntArray& output_size, + const std::string& data_format, + DenseTensor* x_grad); + +template +void Unpool3dGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const DenseTensor& out, + const DenseTensor& out_grad, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_size, + const std::string& data_format, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..099792c2edac37ca90fba5a9058b031d888092cd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unpool_kernel.h @@ -0,0 +1,44 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UnpoolKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const IntArray& output_size, + const std::string& data_format, + DenseTensor* out); + +template +void Unpool3dKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& indices, + const std::vector& ksize, + const std::vector& strides, + const std::vector& paddings, + const std::vector& output_size, + const std::string& data_format, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0c5afe7be6039d408e4ad0b05144cc2fbe2c11cf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_grad_kernel.h @@ -0,0 +1,27 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UnsqueezeGradKernel(const Context& dev_ctx, + const DenseTensor& x_shape, + const DenseTensor& dout, + DenseTensor* dx); +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..35a0515c92da3c1b191f0f4d0ef14fef9ab8b911 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unsqueeze_kernel.h @@ -0,0 +1,48 @@ + +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/common/int_array.h" +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/phi/infermeta/unary.h" + +namespace phi { + +template +void UnsqueezeKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out); + +template +void UnsqueezeWithXShapeKernel(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out, + DenseTensor* xshape); + +template +void Unsqueeze(const Context& dev_ctx, + const DenseTensor& x, + const IntArray& axes, + DenseTensor* out, + DenseTensor* xshape) { + MetaTensor meta_out(out); + UnsqueezeInferMeta(x, axes, &meta_out); + UnsqueezeKernel(dev_ctx, x, axes, out); +} + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..de0e3004d8038dea3114920739ee099546fbcb68 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_grad_kernel.h @@ -0,0 +1,27 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UnStackGradKernel(const Context& dev_ctx, + const std::vector& x, + int axis, + DenseTensor* x_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0494aa6327c21311f2ac1688a27ce514fb78e9d7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/unstack_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void UnStackKernel(const Context& dev_ctx, + const DenseTensor& x, + int axis, + int num, + std::vector outs); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/viterbi_decode_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/viterbi_decode_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..27eb94d89cec4a30a056490b40c13332fd808711 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/viterbi_decode_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void ViterbiDecodeKernel(const Context& dev_ctx, + const DenseTensor& input, + const DenseTensor& transition, + const DenseTensor& length, + bool include_bos_eos_tag, + DenseTensor* scores, + DenseTensor* path); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cc87130c7f622410a1162ac71ded9b0e6cce8e98 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_grad_kernel.h @@ -0,0 +1,32 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void WarpctcGradKernel(const Context& dev_ctx, + const DenseTensor& logits, + const paddle::optional& logits_length, + const DenseTensor& warpctcgrad, + const DenseTensor& loss_grad, + int blank, + bool norm_by_times, + DenseTensor* logits_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a4b1defd050c775e82271e2668fafe96a90237ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/warpctc_kernel.h @@ -0,0 +1,33 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" +#include "paddle/utils/optional.h" + +namespace phi { + +template +void WarpctcKernel(const Context& dev_ctx, + const DenseTensor& logits, + const DenseTensor& label, + const paddle::optional& logits_length, + const paddle::optional& labels_length, + int blank, + bool norm_by_times, + DenseTensor* loss, + DenseTensor* warpctcgrad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..5f596da93e9c2e9027fe49f68746f71d46021e9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_grad_kernel.h @@ -0,0 +1,30 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void WhereGradKernel(const Context& ctx, + const DenseTensor& condition, + const DenseTensor& x, + const DenseTensor& y, + const DenseTensor& out_grad, + DenseTensor* x_grad, + DenseTensor* y_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_index_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_index_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..68b094637c8d55ba424f61f3afea642db073c13f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_index_kernel.h @@ -0,0 +1,26 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void WhereIndexKernel(const Context& dev_ctx, + const DenseTensor& condition, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6348177e697647756e50934784e76df889b18194 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/where_kernel.h @@ -0,0 +1,28 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void WhereKernel(const Context& ctx, + const DenseTensor& condition, + const DenseTensor& x, + const DenseTensor& y, + DenseTensor* out); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolo_box_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolo_box_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..9553d300cad2b78719958077aea297a500c9359a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolo_box_kernel.h @@ -0,0 +1,36 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void YoloBoxKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& img_size, + const std::vector& anchors, + int class_num, + float conf_thresh, + int downsample_ratio, + bool clip_bbox, + float scale_x_y, + bool iou_aware, + float iou_aware_factor, + DenseTensor* boxes, + DenseTensor* scores); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_grad_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_grad_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4d0be5bebb6f9c3f2be5c4c07be70d7cc76524b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_grad_kernel.h @@ -0,0 +1,42 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Yolov3LossGradKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& gt_box, + const DenseTensor& gt_label, + const paddle::optional& gt_score, + const DenseTensor& objectness_mask, + const DenseTensor& gt_match_mask, + const DenseTensor& loss_grad, + const std::vector& anchors, + const std::vector& anchor_mask, + int class_num, + float ignore_thresh, + int downsample_ratio, + bool use_label_smooth, + float scale_x_Y, + DenseTensor* x_grad, + DenseTensor* gt_box_grad, + DenseTensor* gt_label_grad, + DenseTensor* gt_score_grad); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_kernel.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3dabe5ce820ee0d9c2e14a870fa1a2423e101908 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/phi/kernels/yolov3_loss_kernel.h @@ -0,0 +1,38 @@ +// Copyright (c) 2022 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. + +#pragma once + +#include "paddle/phi/core/dense_tensor.h" + +namespace phi { + +template +void Yolov3LossKernel(const Context& dev_ctx, + const DenseTensor& x, + const DenseTensor& gt_box, + const DenseTensor& gt_label, + const paddle::optional& gt_score, + const std::vector& anchors, + const std::vector& anchor_mask, + int class_num, + float ignore_thresh, + int downsample_ratio, + bool use_label_smooth, + float scale_x_Y, + DenseTensor* loss, + DenseTensor* objectness_mask, + DenseTensor* gt_match_mask); + +} // namespace phi diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/any.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/any.h new file mode 100644 index 0000000000000000000000000000000000000000..148d3f45b56ec5bedc79d296eeb87986b136ccc7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/any.h @@ -0,0 +1,176 @@ +// This file copy from boost/any.hpp and boost version: 1.41.0 +// Modified the following points: +// 1. modify namespace from boost::any to paddle::any +// 2. remove the depending boost header files +// 3. remove/modify some macro + +// See http://www.boost.org/libs/any for Documentation. + +#pragma once + +// what: variant type boost::any +// who: contributed by Kevlin Henney, +// with features contributed and bugs found by +// Ed Brey, Mark Rodgers, Peter Dimov, and James Curran +// when: July 2001 +// where: tested with BCC 5.5, MSVC 6.0, and g++ 2.95 + +#include +#include +#include + +// See boost/python/type_id.hpp +// TODO: add BOOST_TYPEID_COMPARE_BY_NAME to config.hpp +#if (defined(__GNUC__) && __GNUC__ >= 3) || defined(_AIX) || \ + (defined(__sgi) && defined(__host_mips)) || \ + (defined(__hpux) && defined(__HP_aCC)) || \ + (defined(linux) && defined(__INTEL_COMPILER) && defined(__ICC)) +#define BOOST_AUX_ANY_TYPE_ID_NAME +#include +#endif + +namespace paddle { +class any { + public: // structors + any() : content(0) {} + + template + any(const ValueType &value) : content(new holder(value)) {} + + any(const any &other) : content(other.content ? other.content->clone() : 0) {} + + ~any() { delete content; } + + public: // modifiers + any &swap(any &rhs) { + std::swap(content, rhs.content); + return *this; + } + + template + any &operator=(const ValueType &rhs) { + any(rhs).swap(*this); + return *this; + } + + any &operator=(any rhs) { + rhs.swap(*this); + return *this; + } + + public: // queries + bool empty() const { return !content; } + + const std::type_info &type() const { + return content ? content->type() : typeid(void); + } + + public: // types (public so any_cast can be non-friend) + class placeholder { + public: // structors + virtual ~placeholder() {} + + public: // queries + virtual const std::type_info &type() const = 0; + + virtual placeholder *clone() const = 0; + }; + + template + class holder : public placeholder { + public: // structors + holder(const ValueType &value) : held(value) {} + + public: // queries + virtual const std::type_info &type() const { return typeid(ValueType); } + + virtual placeholder *clone() const { return new holder(held); } + + public: // representation + ValueType held; + + private: // intentionally left unimplemented + holder &operator=(const holder &); + }; + + public: // representation (public so any_cast can be non-friend) + placeholder *content; +}; + +class bad_any_cast : public std::bad_cast { + public: + virtual const char *what() const throw() { + return "paddle::bad_any_cast: " + "failed conversion using paddle::any_cast"; + } +}; + +template +ValueType *any_cast(any *operand) { + return operand && +#ifdef BOOST_AUX_ANY_TYPE_ID_NAME + std::strcmp(operand->type().name(), + typeid(ValueType).name()) == 0 +#else + operand->type() == typeid(ValueType) +#endif + ? &static_cast *>(operand->content)->held + : 0; +} + +template +inline const ValueType *any_cast(const any *operand) { + return any_cast(const_cast(operand)); +} + +template +ValueType any_cast(any &operand) { + typedef typename std::remove_reference::type nonref; + + // If 'nonref' is still reference type, it means the user has not + // specialized 'remove_reference'. + + // Please use BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION macro + // to generate specialization of remove_reference for your class + // See type traits library documentation for details + static_assert(!std::is_reference::value, + "!std::is_reference::value"); + + nonref *result = any_cast(&operand); + if (!result) throw bad_any_cast(); + return *result; +} + +template +inline ValueType any_cast(const any &operand) { + typedef typename std::remove_reference::type nonref; + + // The comment in the above version of 'any_cast' explains when this + // assert is fired and what to do. + static_assert(!std::is_reference::value, + "!std::is_reference::value"); + + return any_cast(const_cast(operand)); +} + +// Note: The "unsafe" versions of any_cast are not part of the +// public interface and may be removed at any time. They are +// required where we know what type is stored in the any and can't +// use typeid() comparison, e.g., when our types may travel across +// different shared libraries. +template +inline ValueType *unsafe_any_cast(any *operand) { + return &static_cast *>(operand->content)->held; +} + +template +inline const ValueType *unsafe_any_cast(const any *operand) { + return unsafe_any_cast(const_cast(operand)); +} +} // namespace paddle + +// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/array_ref.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/array_ref.h new file mode 100644 index 0000000000000000000000000000000000000000..6731ad80e935010255de7f0b0e0f8872fd6e4e37 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/array_ref.h @@ -0,0 +1,347 @@ +// This file copy from llvm/ADT/ArrayRef.h, version: 12.0.0 +// Modified the following points +// 1. remove hash_value functions +// 2. replace with the llvm::NoneType with paddle::none_t +// 3. remove drop_while, drop_until, take_while, take_until methods +// 4. change ArrayRef to array_ref to unify naming style of utils + +//===- ArrayRef.h - Array Reference Wrapper ---------------------*- C++ +//-*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "paddle/utils/none.h" +#include "paddle/utils/small_vector.h" + +namespace paddle { + +/// array_ref - Represent a constant reference to an array (0 or more elements +/// consecutively in memory), i.e. a start pointer and a length. It allows +/// various APIs to take consecutive elements easily and conveniently. +/// +/// This class does not own the underlying data, it is expected to be used in +/// situations where the data resides in some other buffer, whose lifetime +/// extends past that of the array_ref. For this reason, it is not in general +/// safe to store an array_ref. +/// +/// This is intended to be trivially copyable, so it should be passed by +/// value. +template +class array_ref { + public: + using iterator = const T *; + using const_iterator = const T *; + using size_type = size_t; + using reverse_iterator = std::reverse_iterator; + + private: + /// The start of the array, in an external buffer. + const T *Data = nullptr; + + /// The number of elements. + size_type Length = 0; + + public: + /// @name Constructors + /// @{ + + /// Construct an empty array_ref. + /*implicit*/ array_ref() = default; + + /// Construct an empty array_ref from None. + /*implicit*/ array_ref(none_t) {} + + /// Construct an array_ref from a single element. + /*implicit*/ array_ref(const T &OneElt) : Data(&OneElt), Length(1) {} + + /// Construct an array_ref from a pointer and length. + /*implicit*/ array_ref(const T *data, size_t length) + : Data(data), Length(length) {} + + /// Construct an array_ref from a range. + array_ref(const T *begin, const T *end) : Data(begin), Length(end - begin) {} + + /// Construct an array_ref from a small_vector. This is templated in order to + /// avoid instantiating small_vector_template_common whenever we + /// copy-construct an array_ref. + template + /*implicit*/ array_ref(const small_vector_template_common &Vec) + : Data(Vec.data()), Length(Vec.size()) {} + + /// Construct an array_ref from a std::vector. + template + /*implicit*/ array_ref(const std::vector &Vec) + : Data(Vec.data()), Length(Vec.size()) {} + + /// Construct an array_ref from a std::array + template + /*implicit*/ constexpr array_ref(const std::array &Arr) + : Data(Arr.data()), Length(N) {} + + /// Construct an array_ref from a C array. + template + /*implicit*/ constexpr array_ref(const T (&Arr)[N]) : Data(Arr), Length(N) {} + +/// Construct an array_ref from a std::initializer_list. +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 9 +// Disable gcc's warning in this constructor as it generates an enormous +// amount +// of messages. Anyone using array_ref should already be aware of the fact that +// it does not do lifetime extension. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winit-list-lifetime" +#endif + /*implicit*/ array_ref(const std::initializer_list &Vec) + : Data(Vec.begin() == Vec.end() ? (T *)nullptr : Vec.begin()), + Length(Vec.size()) {} +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 9 +#pragma GCC diagnostic pop +#endif + + /// Construct an array_ref from array_ref. This uses SFINAE to + /// ensure that only ArrayRefs of pointers can be converted. + template + array_ref(const array_ref &A, + std::enable_if_t::value> + * = nullptr) + : Data(A.data()), Length(A.size()) {} + + /// Construct an array_ref from a small_vector. This is + /// templated in order to avoid instantiating small_vector_template_common + /// whenever we copy-construct an array_ref. + template + /*implicit*/ array_ref( + const small_vector_template_common &Vec, + std::enable_if_t::value> * = + nullptr) + : Data(Vec.data()), Length(Vec.size()) {} + + /// Construct an array_ref from std::vector. This uses SFINAE + /// to ensure that only vectors of pointers can be converted. + template + array_ref( + const std::vector &Vec, + std::enable_if_t::value> * = 0) + : Data(Vec.data()), Length(Vec.size()) {} + + /// @} + /// @name Simple Operations + /// @{ + + iterator begin() const { return Data; } + iterator end() const { return Data + Length; } + + reverse_iterator rbegin() const { return reverse_iterator(end()); } + reverse_iterator rend() const { return reverse_iterator(begin()); } + + /// empty - Check if the array is empty. + bool empty() const { return Length == 0; } + + const T *data() const { return Data; } + + /// size - Get the array size. + size_t size() const { return Length; } + + /// front - Get the first element. + const T &front() const { + assert(!empty()); + return Data[0]; + } + + /// back - Get the last element. + const T &back() const { + assert(!empty()); + return Data[Length - 1]; + } + + // copy - Allocate copy in Allocator and return array_ref to it. + template + array_ref copy(Allocator &A) { + T *Buff = A.template Allocate(Length); + std::uninitialized_copy(begin(), end(), Buff); + return array_ref(Buff, Length); + } + + /// equals - Check for element-wise equality. + bool equals(array_ref RHS) const { + if (Length != RHS.Length) return false; + return std::equal(begin(), end(), RHS.begin()); + } + + /// slice(n, m) - Chop off the first N elements of the array, and keep M + /// elements in the array. + array_ref slice(size_t N, size_t M) const { + assert(N + M <= size() && "Invalid specifier"); + return array_ref(data() + N, M); + } + + /// slice(n) - Chop off the first N elements of the array. + array_ref slice(size_t N) const { return slice(N, size() - N); } + + /// Drop the first \p N elements of the array. + array_ref drop_front(size_t N = 1) const { + assert(size() >= N && "Dropping more elements than exist"); + return slice(N, size() - N); + } + + /// Drop the last \p N elements of the array. + array_ref drop_back(size_t N = 1) const { + assert(size() >= N && "Dropping more elements than exist"); + return slice(0, size() - N); + } + + /// Return a copy of *this with only the first \p N elements. + array_ref take_front(size_t N = 1) const { + if (N >= size()) return *this; + return drop_back(size() - N); + } + + /// Return a copy of *this with only the last \p N elements. + array_ref take_back(size_t N = 1) const { + if (N >= size()) return *this; + return drop_front(size() - N); + } + + /// @} + /// @name Operator Overloads + /// @{ + const T &operator[](size_t Index) const { + assert(Index < Length && "Invalid index!"); + return Data[Index]; + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t::value, array_ref> &operator=( + U &&Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t::value, array_ref> &operator=( + std::initializer_list) = delete; + + /// @} + /// @name Expensive Operations + /// @{ + std::vector vec() const { return std::vector(Data, Data + Length); } + + /// @} + /// @name Conversion operators + /// @{ + operator std::vector() const { + return std::vector(Data, Data + Length); + } + + /// @} +}; + +/// @name array_ref Convenience constructors +/// @{ + +/// Construct an array_ref from a single element. +template +array_ref make_array_ref(const T &OneElt) { + return OneElt; +} + +/// Construct an array_ref from a pointer and length. +template +array_ref make_array_ref(const T *data, size_t length) { + return array_ref(data, length); +} + +/// Construct an array_ref from a range. +template +array_ref make_array_ref(const T *begin, const T *end) { + return array_ref(begin, end); +} + +/// Construct an array_ref from a small_vector. +template +array_ref make_array_ref(const small_vector_impl &Vec) { + return Vec; +} + +/// Construct an array_ref from a small_vector. +template +array_ref make_array_ref(const small_vector &Vec) { + return Vec; +} + +/// Construct an array_ref from a std::vector. +template +array_ref make_array_ref(const std::vector &Vec) { + return Vec; +} + +/// Construct an array_ref from a std::array. +template +array_ref make_array_ref(const std::array &Arr) { + return Arr; +} + +/// Construct an array_ref from an array_ref (no-op) (const) +template +array_ref make_array_ref(const array_ref &Vec) { + return Vec; +} + +/// Construct an array_ref from an array_ref (no-op) +template +array_ref &make_array_ref(array_ref &Vec) { + return Vec; +} + +/// Construct an array_ref from a C array. +template +array_ref make_array_ref(const T (&Arr)[N]) { + return array_ref(Arr); +} + +/// @} +/// @name array_ref Comparison Operators +/// @{ + +template +inline bool operator==(array_ref LHS, array_ref RHS) { + return LHS.equals(RHS); +} + +template +inline bool operator==(small_vector_impl &LHS, array_ref RHS) { + return array_ref(LHS).equals(RHS); +} + +template +inline bool operator!=(array_ref LHS, array_ref RHS) { + return !(LHS == RHS); +} + +template +inline bool operator!=(small_vector_impl &LHS, array_ref RHS) { + return !(LHS == RHS); +} + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/blank.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/blank.h new file mode 100644 index 0000000000000000000000000000000000000000..dd863c92897af89b9caf043c3e3cda96323210e2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/blank.h @@ -0,0 +1,52 @@ +/* Copyright (c) 2022 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. */ + +// This file copy from boost/blank.hpp, boost version: 1.41.0 +// Modified the following points: +// 1. modify namespace from boost to paddle +// 2. remove the depending boost header files +// 3. remove the type traits specializations +// 4. remove streaming support + +//----------------------------------------------------------------------------- +// boost blank.hpp header file +// See http://www.boost.org for updates, documentation, and revision history. +//----------------------------------------------------------------------------- +// +// Copyright (c) 2003 +// Eric Friedman +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +namespace paddle { + +struct blank {}; + +inline bool operator==(const blank&, const blank&) { return true; } + +inline bool operator<=(const blank&, const blank&) { return true; } + +inline bool operator>=(const blank&, const blank&) { return true; } + +inline bool operator!=(const blank&, const blank&) { return false; } + +inline bool operator<(const blank&, const blank&) { return false; } + +inline bool operator>(const blank&, const blank&) { return false; } + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/flat_hash_map.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/flat_hash_map.h new file mode 100644 index 0000000000000000000000000000000000000000..56318ab90e6c8ceb9d4cc49206709f30719097cb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/flat_hash_map.h @@ -0,0 +1,1742 @@ +// Copy from https://github.com/skarupke/flat_hash_map +// Modify the following points: +// 1. modify namespace ska to namespace paddle +// 2. modify std::max to (std::max) to fix the building failed problem on +// windows platform + +// Copyright Malte Skarupke 2017. +// Distributed under the Boost Software License, Version 1.0. +// (See http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#define SKA_NOINLINE(...) __declspec(noinline) __VA_ARGS__ +#else +#define SKA_NOINLINE(...) __VA_ARGS__ __attribute__((noinline)) +#endif + +namespace paddle { +struct prime_number_hash_policy; +struct power_of_two_hash_policy; +struct fibonacci_hash_policy; + +namespace detailv3 { +template +struct functor_storage : Functor { + functor_storage() = default; + functor_storage(const Functor &functor) : Functor(functor) {} + template + Result operator()(Args &&...args) { + return static_cast(*this)(std::forward(args)...); + } + template + Result operator()(Args &&...args) const { + return static_cast(*this)(std::forward(args)...); + } +}; +template +struct functor_storage { + typedef Result (*function_ptr)(Args...); + function_ptr function; + functor_storage(function_ptr function) : function(function) {} + Result operator()(Args... args) const { + return function(std::forward(args)...); + } + operator function_ptr &() { return function; } + operator const function_ptr &() { return function; } +}; +template +struct KeyOrValueHasher : functor_storage { + typedef functor_storage hasher_storage; + KeyOrValueHasher() = default; + KeyOrValueHasher(const hasher &hash) : hasher_storage(hash) {} + size_t operator()(const key_type &key) { + return static_cast(*this)(key); + } + size_t operator()(const key_type &key) const { + return static_cast(*this)(key); + } + size_t operator()(const value_type &value) { + return static_cast(*this)(value.first); + } + size_t operator()(const value_type &value) const { + return static_cast(*this)(value.first); + } + template + size_t operator()(const std::pair &value) { + return static_cast(*this)(value.first); + } + template + size_t operator()(const std::pair &value) const { + return static_cast(*this)(value.first); + } +}; +template +struct KeyOrValueEquality : functor_storage { + typedef functor_storage equality_storage; + KeyOrValueEquality() = default; + KeyOrValueEquality(const key_equal &equality) : equality_storage(equality) {} + bool operator()(const key_type &lhs, const key_type &rhs) { + return static_cast(*this)(lhs, rhs); + } + bool operator()(const key_type &lhs, const value_type &rhs) { + return static_cast(*this)(lhs, rhs.first); + } + bool operator()(const value_type &lhs, const key_type &rhs) { + return static_cast(*this)(lhs.first, rhs); + } + bool operator()(const value_type &lhs, const value_type &rhs) { + return static_cast(*this)(lhs.first, rhs.first); + } + template + bool operator()(const key_type &lhs, const std::pair &rhs) { + return static_cast(*this)(lhs, rhs.first); + } + template + bool operator()(const std::pair &lhs, const key_type &rhs) { + return static_cast(*this)(lhs.first, rhs); + } + template + bool operator()(const value_type &lhs, const std::pair &rhs) { + return static_cast(*this)(lhs.first, rhs.first); + } + template + bool operator()(const std::pair &lhs, const value_type &rhs) { + return static_cast(*this)(lhs.first, rhs.first); + } + template + bool operator()(const std::pair &lhs, const std::pair &rhs) { + return static_cast(*this)(lhs.first, rhs.first); + } +}; +static constexpr int8_t min_lookups = 4; +template +struct sherwood_v3_entry { + sherwood_v3_entry() {} + sherwood_v3_entry(int8_t distance_from_desired) + : distance_from_desired(distance_from_desired) {} + ~sherwood_v3_entry() {} + static sherwood_v3_entry *empty_default_table() { + static sherwood_v3_entry result[min_lookups] = { + {}, {}, {}, {special_end_value}}; + return result; + } + + bool has_value() const { return distance_from_desired >= 0; } + bool is_empty() const { return distance_from_desired < 0; } + bool is_at_desired_position() const { return distance_from_desired <= 0; } + template + void emplace(int8_t distance, Args &&...args) { + new (std::addressof(value)) T(std::forward(args)...); + distance_from_desired = distance; + } + + void destroy_value() { + value.~T(); + distance_from_desired = -1; + } + + int8_t distance_from_desired = -1; + static constexpr int8_t special_end_value = 0; + union { + T value; + }; +}; + +inline int8_t log2(size_t value) { + static constexpr int8_t table[64] = { + 63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, + 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, + 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, + 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5}; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value |= value >> 32; + return table[((value - (value >> 1)) * 0x07EDD5E59A4E28C2) >> 58]; +} + +template +struct AssignIfTrue { + void operator()(T &lhs, const T &rhs) { lhs = rhs; } + void operator()(T &lhs, T &&rhs) { lhs = std::move(rhs); } +}; +template +struct AssignIfTrue { + void operator()(T &, const T &) {} + void operator()(T &, T &&) {} +}; + +inline size_t next_power_of_two(size_t i) { + --i; + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + i |= i >> 32; + ++i; + return i; +} + +template +using void_t = void; + +template +struct HashPolicySelector { + typedef fibonacci_hash_policy type; +}; +template +struct HashPolicySelector> { + typedef typename T::hash_policy type; +}; + +template +class sherwood_v3_table : private EntryAlloc, private Hasher, private Equal { + using Entry = detailv3::sherwood_v3_entry; + using AllocatorTraits = std::allocator_traits; + using EntryPointer = typename AllocatorTraits::pointer; + struct convertible_to_iterator; + + public: + using value_type = T; + using size_type = size_t; + using difference_type = std::ptrdiff_t; + using hasher = ArgumentHash; + using key_equal = ArgumentEqual; + using allocator_type = EntryAlloc; + using reference = value_type &; + using const_reference = const value_type &; + using pointer = value_type *; + using const_pointer = const value_type *; + + sherwood_v3_table() {} + explicit sherwood_v3_table(size_type bucket_count, + const ArgumentHash &hash = ArgumentHash(), + const ArgumentEqual &equal = ArgumentEqual(), + const ArgumentAlloc &alloc = ArgumentAlloc()) + : EntryAlloc(alloc), Hasher(hash), Equal(equal) { + rehash(bucket_count); + } + sherwood_v3_table(size_type bucket_count, const ArgumentAlloc &alloc) + : sherwood_v3_table( + bucket_count, ArgumentHash(), ArgumentEqual(), alloc) {} + sherwood_v3_table(size_type bucket_count, + const ArgumentHash &hash, + const ArgumentAlloc &alloc) + : sherwood_v3_table(bucket_count, hash, ArgumentEqual(), alloc) {} + explicit sherwood_v3_table(const ArgumentAlloc &alloc) : EntryAlloc(alloc) {} + template + sherwood_v3_table(It first, + It last, + size_type bucket_count = 0, + const ArgumentHash &hash = ArgumentHash(), + const ArgumentEqual &equal = ArgumentEqual(), + const ArgumentAlloc &alloc = ArgumentAlloc()) + : sherwood_v3_table(bucket_count, hash, equal, alloc) { + insert(first, last); + } + template + sherwood_v3_table(It first, + It last, + size_type bucket_count, + const ArgumentAlloc &alloc) + : sherwood_v3_table( + first, last, bucket_count, ArgumentHash(), ArgumentEqual(), alloc) { + } + template + sherwood_v3_table(It first, + It last, + size_type bucket_count, + const ArgumentHash &hash, + const ArgumentAlloc &alloc) + : sherwood_v3_table( + first, last, bucket_count, hash, ArgumentEqual(), alloc) {} + sherwood_v3_table(std::initializer_list il, + size_type bucket_count = 0, + const ArgumentHash &hash = ArgumentHash(), + const ArgumentEqual &equal = ArgumentEqual(), + const ArgumentAlloc &alloc = ArgumentAlloc()) + : sherwood_v3_table(bucket_count, hash, equal, alloc) { + if (bucket_count == 0) rehash(il.size()); + insert(il.begin(), il.end()); + } + sherwood_v3_table(std::initializer_list il, + size_type bucket_count, + const ArgumentAlloc &alloc) + : sherwood_v3_table( + il, bucket_count, ArgumentHash(), ArgumentEqual(), alloc) {} + sherwood_v3_table(std::initializer_list il, + size_type bucket_count, + const ArgumentHash &hash, + const ArgumentAlloc &alloc) + : sherwood_v3_table(il, bucket_count, hash, ArgumentEqual(), alloc) {} + sherwood_v3_table(const sherwood_v3_table &other) + : sherwood_v3_table( + other, + AllocatorTraits::select_on_container_copy_construction( + other.get_allocator())) {} + sherwood_v3_table(const sherwood_v3_table &other, const ArgumentAlloc &alloc) + : EntryAlloc(alloc), + Hasher(other), + Equal(other), + _max_load_factor(other._max_load_factor) { + rehash_for_other_container(other); + try { + insert(other.begin(), other.end()); + } catch (...) { + clear(); + deallocate_data(entries, num_slots_minus_one, max_lookups); + throw; + } + } + sherwood_v3_table(sherwood_v3_table &&other) noexcept + : EntryAlloc(std::move(other)), + Hasher(std::move(other)), + Equal(std::move(other)) { + swap_pointers(other); + } + sherwood_v3_table(sherwood_v3_table &&other, + const ArgumentAlloc &alloc) noexcept + : EntryAlloc(alloc), Hasher(std::move(other)), Equal(std::move(other)) { + swap_pointers(other); + } + sherwood_v3_table &operator=(const sherwood_v3_table &other) { + if (this == std::addressof(other)) return *this; + + clear(); + if (AllocatorTraits::propagate_on_container_copy_assignment::value) { + if (static_cast(*this) != + static_cast(other)) { + reset_to_empty_state(); + } + AssignIfTrue< + EntryAlloc, + AllocatorTraits::propagate_on_container_copy_assignment::value>()( + *this, other); + } + _max_load_factor = other._max_load_factor; + static_cast(*this) = other; + static_cast(*this) = other; + rehash_for_other_container(other); + insert(other.begin(), other.end()); + return *this; + } + sherwood_v3_table &operator=(sherwood_v3_table &&other) noexcept { + if (this == std::addressof(other)) + return *this; + else if (AllocatorTraits::propagate_on_container_move_assignment::value) { + clear(); + reset_to_empty_state(); + AssignIfTrue< + EntryAlloc, + AllocatorTraits::propagate_on_container_move_assignment::value>()( + *this, std::move(other)); + swap_pointers(other); + } else if (static_cast(*this) == + static_cast(other)) { + swap_pointers(other); + } else { + clear(); + _max_load_factor = other._max_load_factor; + rehash_for_other_container(other); + for (T &elem : other) emplace(std::move(elem)); + other.clear(); + } + static_cast(*this) = std::move(other); + static_cast(*this) = std::move(other); + return *this; + } + ~sherwood_v3_table() { + clear(); + deallocate_data(entries, num_slots_minus_one, max_lookups); + } + + const allocator_type &get_allocator() const { + return static_cast(*this); + } + const ArgumentEqual &key_eq() const { + return static_cast(*this); + } + const ArgumentHash &hash_function() const { + return static_cast(*this); + } + + template + struct templated_iterator { + templated_iterator() = default; + templated_iterator(EntryPointer current) : current(current) {} + EntryPointer current = EntryPointer(); + + using iterator_category = std::forward_iterator_tag; + using value_type = ValueType; + using difference_type = ptrdiff_t; + using pointer = ValueType *; + using reference = ValueType &; + + friend bool operator==(const templated_iterator &lhs, + const templated_iterator &rhs) { + return lhs.current == rhs.current; + } + friend bool operator!=(const templated_iterator &lhs, + const templated_iterator &rhs) { + return !(lhs == rhs); + } + + templated_iterator &operator++() { + do { + ++current; + } while (current->is_empty()); + return *this; + } + templated_iterator operator++(int) { + templated_iterator copy(*this); + ++*this; + return copy; + } + + ValueType &operator*() const { return current->value; } + ValueType *operator->() const { return std::addressof(current->value); } + + operator templated_iterator() const { return {current}; } + }; + using iterator = templated_iterator; + using const_iterator = templated_iterator; + + iterator begin() { + for (EntryPointer it = entries;; ++it) { + if (it->has_value()) return {it}; + } + } + const_iterator begin() const { + for (EntryPointer it = entries;; ++it) { + if (it->has_value()) return {it}; + } + } + const_iterator cbegin() const { return begin(); } + iterator end() { + return {entries + + static_cast(num_slots_minus_one + max_lookups)}; + } + const_iterator end() const { + return {entries + + static_cast(num_slots_minus_one + max_lookups)}; + } + const_iterator cend() const { return end(); } + + iterator find(const FindKey &key) { + size_t index = + hash_policy.index_for_hash(hash_object(key), num_slots_minus_one); + EntryPointer it = entries + ptrdiff_t(index); + for (int8_t distance = 0; it->distance_from_desired >= distance; + ++distance, ++it) { + if (compares_equal(key, it->value)) return {it}; + } + return end(); + } + const_iterator find(const FindKey &key) const { + return const_cast(this)->find(key); + } + size_t count(const FindKey &key) const { return find(key) == end() ? 0 : 1; } + std::pair equal_range(const FindKey &key) { + iterator found = find(key); + if (found == end()) + return {found, found}; + else + return {found, std::next(found)}; + } + std::pair equal_range( + const FindKey &key) const { + const_iterator found = find(key); + if (found == end()) + return {found, found}; + else + return {found, std::next(found)}; + } + + template + std::pair emplace(Key &&key, Args &&...args) { + size_t index = + hash_policy.index_for_hash(hash_object(key), num_slots_minus_one); + EntryPointer current_entry = entries + ptrdiff_t(index); + int8_t distance_from_desired = 0; + for (; current_entry->distance_from_desired >= distance_from_desired; + ++current_entry, ++distance_from_desired) { + if (compares_equal(key, current_entry->value)) + return {{current_entry}, false}; + } + return emplace_new_key(distance_from_desired, + current_entry, + std::forward(key), + std::forward(args)...); + } + + std::pair insert(const value_type &value) { + return emplace(value); + } + std::pair insert(value_type &&value) { + return emplace(std::move(value)); + } + template + iterator emplace_hint(const_iterator, Args &&...args) { + return emplace(std::forward(args)...).first; + } + iterator insert(const_iterator, const value_type &value) { + return emplace(value).first; + } + iterator insert(const_iterator, value_type &&value) { + return emplace(std::move(value)).first; + } + + template + void insert(It begin, It end) { + for (; begin != end; ++begin) { + emplace(*begin); + } + } + void insert(std::initializer_list il) { + insert(il.begin(), il.end()); + } + + void rehash(size_t num_buckets) { + num_buckets = (std::max)( + num_buckets, + static_cast( + std::ceil(num_elements / static_cast(_max_load_factor)))); + if (num_buckets == 0) { + reset_to_empty_state(); + return; + } + auto new_prime_index = hash_policy.next_size_over(num_buckets); + if (num_buckets == bucket_count()) return; + int8_t new_max_lookups = compute_max_lookups(num_buckets); + EntryPointer new_buckets( + AllocatorTraits::allocate(*this, num_buckets + new_max_lookups)); + EntryPointer special_end_item = + new_buckets + static_cast(num_buckets + new_max_lookups - 1); + for (EntryPointer it = new_buckets; it != special_end_item; ++it) + it->distance_from_desired = -1; + special_end_item->distance_from_desired = Entry::special_end_value; + std::swap(entries, new_buckets); + std::swap(num_slots_minus_one, num_buckets); + --num_slots_minus_one; + hash_policy.commit(new_prime_index); + int8_t old_max_lookups = max_lookups; + max_lookups = new_max_lookups; + num_elements = 0; + for (EntryPointer + it = new_buckets, + end = it + static_cast(num_buckets + old_max_lookups); + it != end; + ++it) { + if (it->has_value()) { + emplace(std::move(it->value)); + it->destroy_value(); + } + } + deallocate_data(new_buckets, num_buckets, old_max_lookups); + } + + void reserve(size_t num_elements) { + size_t required_buckets = num_buckets_for_reserve(num_elements); + if (required_buckets > bucket_count()) rehash(required_buckets); + } + + // the return value is a type that can be converted to an iterator + // the reason for doing this is that it's not free to find the + // iterator pointing at the next element. if you care about the + // next iterator, turn the return value into an iterator + convertible_to_iterator erase(const_iterator to_erase) { + EntryPointer current = to_erase.current; + current->destroy_value(); + --num_elements; + for (EntryPointer next = current + ptrdiff_t(1); + !next->is_at_desired_position(); + ++current, ++next) { + current->emplace(next->distance_from_desired - 1, std::move(next->value)); + next->destroy_value(); + } + return {to_erase.current}; + } + + iterator erase(const_iterator begin_it, const_iterator end_it) { + if (begin_it == end_it) return {begin_it.current}; + for (EntryPointer it = begin_it.current, end = end_it.current; it != end; + ++it) { + if (it->has_value()) { + it->destroy_value(); + --num_elements; + } + } + if (end_it == this->end()) return this->end(); + ptrdiff_t num_to_move = + std::min(static_cast(end_it.current->distance_from_desired), + end_it.current - begin_it.current); + EntryPointer to_return = end_it.current - num_to_move; + for (EntryPointer it = end_it.current; !it->is_at_desired_position();) { + EntryPointer target = it - num_to_move; + target->emplace(it->distance_from_desired - num_to_move, + std::move(it->value)); + it->destroy_value(); + ++it; + num_to_move = std::min(static_cast(it->distance_from_desired), + num_to_move); + } + return {to_return}; + } + + size_t erase(const FindKey &key) { + auto found = find(key); + if (found == end()) + return 0; + else { + erase(found); + return 1; + } + } + + void clear() { + for (EntryPointer it = entries, + end = it + static_cast(num_slots_minus_one + + max_lookups); + it != end; + ++it) { + if (it->has_value()) it->destroy_value(); + } + num_elements = 0; + } + + void shrink_to_fit() { rehash_for_other_container(*this); } + + void swap(sherwood_v3_table &other) { + using std::swap; + swap_pointers(other); + swap(static_cast(*this), + static_cast(other)); + swap(static_cast(*this), + static_cast(other)); + if (AllocatorTraits::propagate_on_container_swap::value) + swap(static_cast(*this), static_cast(other)); + } + + size_t size() const { return num_elements; } + size_t max_size() const { + return (AllocatorTraits::max_size(*this)) / sizeof(Entry); + } + size_t bucket_count() const { + return num_slots_minus_one ? num_slots_minus_one + 1 : 0; + } + size_type max_bucket_count() const { + return (AllocatorTraits::max_size(*this) - min_lookups) / sizeof(Entry); + } + size_t bucket(const FindKey &key) const { + return hash_policy.index_for_hash(hash_object(key), num_slots_minus_one); + } + float load_factor() const { + size_t buckets = bucket_count(); + if (buckets) + return static_cast(num_elements) / bucket_count(); + else + return 0; + } + void max_load_factor(float value) { _max_load_factor = value; } + float max_load_factor() const { return _max_load_factor; } + + bool empty() const { return num_elements == 0; } + + private: + EntryPointer entries = Entry::empty_default_table(); + size_t num_slots_minus_one = 0; + typename HashPolicySelector::type hash_policy; + int8_t max_lookups = detailv3::min_lookups - 1; + float _max_load_factor = 0.5f; + size_t num_elements = 0; + + static int8_t compute_max_lookups(size_t num_buckets) { + int8_t desired = detailv3::log2(num_buckets); + return (std::max)(detailv3::min_lookups, desired); + } + + size_t num_buckets_for_reserve(size_t num_elements) const { + return static_cast(std::ceil( + num_elements / std::min(0.5, static_cast(_max_load_factor)))); + } + void rehash_for_other_container(const sherwood_v3_table &other) { + rehash( + std::min(num_buckets_for_reserve(other.size()), other.bucket_count())); + } + + void swap_pointers(sherwood_v3_table &other) { + using std::swap; + swap(hash_policy, other.hash_policy); + swap(entries, other.entries); + swap(num_slots_minus_one, other.num_slots_minus_one); + swap(num_elements, other.num_elements); + swap(max_lookups, other.max_lookups); + swap(_max_load_factor, other._max_load_factor); + } + + template + SKA_NOINLINE(std::pair) + emplace_new_key(int8_t distance_from_desired, + EntryPointer current_entry, + Key &&key, + Args &&...args) { + using std::swap; + if (num_slots_minus_one == 0 || distance_from_desired == max_lookups || + num_elements + 1 > + (num_slots_minus_one + 1) * static_cast(_max_load_factor)) { + grow(); + return emplace(std::forward(key), std::forward(args)...); + } else if (current_entry->is_empty()) { + current_entry->emplace(distance_from_desired, + std::forward(key), + std::forward(args)...); + ++num_elements; + return {{current_entry}, true}; + } + value_type to_insert(std::forward(key), std::forward(args)...); + swap(distance_from_desired, current_entry->distance_from_desired); + swap(to_insert, current_entry->value); + iterator result = {current_entry}; + for (++distance_from_desired, ++current_entry;; ++current_entry) { + if (current_entry->is_empty()) { + current_entry->emplace(distance_from_desired, std::move(to_insert)); + ++num_elements; + return {result, true}; + } else if (current_entry->distance_from_desired < distance_from_desired) { + swap(distance_from_desired, current_entry->distance_from_desired); + swap(to_insert, current_entry->value); + ++distance_from_desired; + } else { + ++distance_from_desired; + if (distance_from_desired == max_lookups) { + swap(to_insert, result.current->value); + grow(); + return emplace(std::move(to_insert)); + } + } + } + } + + void grow() { rehash((std::max)(size_t(4), 2 * bucket_count())); } + + void deallocate_data(EntryPointer begin, + size_t num_slots_minus_one, + int8_t max_lookups) { + if (begin != Entry::empty_default_table()) { + AllocatorTraits::deallocate( + *this, begin, num_slots_minus_one + max_lookups + 1); + } + } + + void reset_to_empty_state() { + deallocate_data(entries, num_slots_minus_one, max_lookups); + entries = Entry::empty_default_table(); + num_slots_minus_one = 0; + hash_policy.reset(); + max_lookups = detailv3::min_lookups - 1; + } + + template + size_t hash_object(const U &key) { + return static_cast(*this)(key); + } + template + size_t hash_object(const U &key) const { + return static_cast(*this)(key); + } + template + bool compares_equal(const L &lhs, const R &rhs) { + return static_cast(*this)(lhs, rhs); + } + + struct convertible_to_iterator { + EntryPointer it; + + operator iterator() { + if (it->has_value()) + return {it}; + else + return ++iterator{it}; + } + operator const_iterator() { + if (it->has_value()) + return {it}; + else + return ++const_iterator{it}; + } + }; +}; +} // namespace detailv3 + +struct prime_number_hash_policy { + static size_t mod0(size_t) { return 0llu; } + static size_t mod2(size_t hash) { return hash % 2llu; } + static size_t mod3(size_t hash) { return hash % 3llu; } + static size_t mod5(size_t hash) { return hash % 5llu; } + static size_t mod7(size_t hash) { return hash % 7llu; } + static size_t mod11(size_t hash) { return hash % 11llu; } + static size_t mod13(size_t hash) { return hash % 13llu; } + static size_t mod17(size_t hash) { return hash % 17llu; } + static size_t mod23(size_t hash) { return hash % 23llu; } + static size_t mod29(size_t hash) { return hash % 29llu; } + static size_t mod37(size_t hash) { return hash % 37llu; } + static size_t mod47(size_t hash) { return hash % 47llu; } + static size_t mod59(size_t hash) { return hash % 59llu; } + static size_t mod73(size_t hash) { return hash % 73llu; } + static size_t mod97(size_t hash) { return hash % 97llu; } + static size_t mod127(size_t hash) { return hash % 127llu; } + static size_t mod151(size_t hash) { return hash % 151llu; } + static size_t mod197(size_t hash) { return hash % 197llu; } + static size_t mod251(size_t hash) { return hash % 251llu; } + static size_t mod313(size_t hash) { return hash % 313llu; } + static size_t mod397(size_t hash) { return hash % 397llu; } + static size_t mod499(size_t hash) { return hash % 499llu; } + static size_t mod631(size_t hash) { return hash % 631llu; } + static size_t mod797(size_t hash) { return hash % 797llu; } + static size_t mod1009(size_t hash) { return hash % 1009llu; } + static size_t mod1259(size_t hash) { return hash % 1259llu; } + static size_t mod1597(size_t hash) { return hash % 1597llu; } + static size_t mod2011(size_t hash) { return hash % 2011llu; } + static size_t mod2539(size_t hash) { return hash % 2539llu; } + static size_t mod3203(size_t hash) { return hash % 3203llu; } + static size_t mod4027(size_t hash) { return hash % 4027llu; } + static size_t mod5087(size_t hash) { return hash % 5087llu; } + static size_t mod6421(size_t hash) { return hash % 6421llu; } + static size_t mod8089(size_t hash) { return hash % 8089llu; } + static size_t mod10193(size_t hash) { return hash % 10193llu; } + static size_t mod12853(size_t hash) { return hash % 12853llu; } + static size_t mod16193(size_t hash) { return hash % 16193llu; } + static size_t mod20399(size_t hash) { return hash % 20399llu; } + static size_t mod25717(size_t hash) { return hash % 25717llu; } + static size_t mod32401(size_t hash) { return hash % 32401llu; } + static size_t mod40823(size_t hash) { return hash % 40823llu; } + static size_t mod51437(size_t hash) { return hash % 51437llu; } + static size_t mod64811(size_t hash) { return hash % 64811llu; } + static size_t mod81649(size_t hash) { return hash % 81649llu; } + static size_t mod102877(size_t hash) { return hash % 102877llu; } + static size_t mod129607(size_t hash) { return hash % 129607llu; } + static size_t mod163307(size_t hash) { return hash % 163307llu; } + static size_t mod205759(size_t hash) { return hash % 205759llu; } + static size_t mod259229(size_t hash) { return hash % 259229llu; } + static size_t mod326617(size_t hash) { return hash % 326617llu; } + static size_t mod411527(size_t hash) { return hash % 411527llu; } + static size_t mod518509(size_t hash) { return hash % 518509llu; } + static size_t mod653267(size_t hash) { return hash % 653267llu; } + static size_t mod823117(size_t hash) { return hash % 823117llu; } + static size_t mod1037059(size_t hash) { return hash % 1037059llu; } + static size_t mod1306601(size_t hash) { return hash % 1306601llu; } + static size_t mod1646237(size_t hash) { return hash % 1646237llu; } + static size_t mod2074129(size_t hash) { return hash % 2074129llu; } + static size_t mod2613229(size_t hash) { return hash % 2613229llu; } + static size_t mod3292489(size_t hash) { return hash % 3292489llu; } + static size_t mod4148279(size_t hash) { return hash % 4148279llu; } + static size_t mod5226491(size_t hash) { return hash % 5226491llu; } + static size_t mod6584983(size_t hash) { return hash % 6584983llu; } + static size_t mod8296553(size_t hash) { return hash % 8296553llu; } + static size_t mod10453007(size_t hash) { return hash % 10453007llu; } + static size_t mod13169977(size_t hash) { return hash % 13169977llu; } + static size_t mod16593127(size_t hash) { return hash % 16593127llu; } + static size_t mod20906033(size_t hash) { return hash % 20906033llu; } + static size_t mod26339969(size_t hash) { return hash % 26339969llu; } + static size_t mod33186281(size_t hash) { return hash % 33186281llu; } + static size_t mod41812097(size_t hash) { return hash % 41812097llu; } + static size_t mod52679969(size_t hash) { return hash % 52679969llu; } + static size_t mod66372617(size_t hash) { return hash % 66372617llu; } + static size_t mod83624237(size_t hash) { return hash % 83624237llu; } + static size_t mod105359939(size_t hash) { return hash % 105359939llu; } + static size_t mod132745199(size_t hash) { return hash % 132745199llu; } + static size_t mod167248483(size_t hash) { return hash % 167248483llu; } + static size_t mod210719881(size_t hash) { return hash % 210719881llu; } + static size_t mod265490441(size_t hash) { return hash % 265490441llu; } + static size_t mod334496971(size_t hash) { return hash % 334496971llu; } + static size_t mod421439783(size_t hash) { return hash % 421439783llu; } + static size_t mod530980861(size_t hash) { return hash % 530980861llu; } + static size_t mod668993977(size_t hash) { return hash % 668993977llu; } + static size_t mod842879579(size_t hash) { return hash % 842879579llu; } + static size_t mod1061961721(size_t hash) { return hash % 1061961721llu; } + static size_t mod1337987929(size_t hash) { return hash % 1337987929llu; } + static size_t mod1685759167(size_t hash) { return hash % 1685759167llu; } + static size_t mod2123923447(size_t hash) { return hash % 2123923447llu; } + static size_t mod2675975881(size_t hash) { return hash % 2675975881llu; } + static size_t mod3371518343(size_t hash) { return hash % 3371518343llu; } + static size_t mod4247846927(size_t hash) { return hash % 4247846927llu; } + static size_t mod5351951779(size_t hash) { return hash % 5351951779llu; } + static size_t mod6743036717(size_t hash) { return hash % 6743036717llu; } + static size_t mod8495693897(size_t hash) { return hash % 8495693897llu; } + static size_t mod10703903591(size_t hash) { return hash % 10703903591llu; } + static size_t mod13486073473(size_t hash) { return hash % 13486073473llu; } + static size_t mod16991387857(size_t hash) { return hash % 16991387857llu; } + static size_t mod21407807219(size_t hash) { return hash % 21407807219llu; } + static size_t mod26972146961(size_t hash) { return hash % 26972146961llu; } + static size_t mod33982775741(size_t hash) { return hash % 33982775741llu; } + static size_t mod42815614441(size_t hash) { return hash % 42815614441llu; } + static size_t mod53944293929(size_t hash) { return hash % 53944293929llu; } + static size_t mod67965551447(size_t hash) { return hash % 67965551447llu; } + static size_t mod85631228929(size_t hash) { return hash % 85631228929llu; } + static size_t mod107888587883(size_t hash) { return hash % 107888587883llu; } + static size_t mod135931102921(size_t hash) { return hash % 135931102921llu; } + static size_t mod171262457903(size_t hash) { return hash % 171262457903llu; } + static size_t mod215777175787(size_t hash) { return hash % 215777175787llu; } + static size_t mod271862205833(size_t hash) { return hash % 271862205833llu; } + static size_t mod342524915839(size_t hash) { return hash % 342524915839llu; } + static size_t mod431554351609(size_t hash) { return hash % 431554351609llu; } + static size_t mod543724411781(size_t hash) { return hash % 543724411781llu; } + static size_t mod685049831731(size_t hash) { return hash % 685049831731llu; } + static size_t mod863108703229(size_t hash) { return hash % 863108703229llu; } + static size_t mod1087448823553(size_t hash) { + return hash % 1087448823553llu; + } + static size_t mod1370099663459(size_t hash) { + return hash % 1370099663459llu; + } + static size_t mod1726217406467(size_t hash) { + return hash % 1726217406467llu; + } + static size_t mod2174897647073(size_t hash) { + return hash % 2174897647073llu; + } + static size_t mod2740199326961(size_t hash) { + return hash % 2740199326961llu; + } + static size_t mod3452434812973(size_t hash) { + return hash % 3452434812973llu; + } + static size_t mod4349795294267(size_t hash) { + return hash % 4349795294267llu; + } + static size_t mod5480398654009(size_t hash) { + return hash % 5480398654009llu; + } + static size_t mod6904869625999(size_t hash) { + return hash % 6904869625999llu; + } + static size_t mod8699590588571(size_t hash) { + return hash % 8699590588571llu; + } + static size_t mod10960797308051(size_t hash) { + return hash % 10960797308051llu; + } + static size_t mod13809739252051(size_t hash) { + return hash % 13809739252051llu; + } + static size_t mod17399181177241(size_t hash) { + return hash % 17399181177241llu; + } + static size_t mod21921594616111(size_t hash) { + return hash % 21921594616111llu; + } + static size_t mod27619478504183(size_t hash) { + return hash % 27619478504183llu; + } + static size_t mod34798362354533(size_t hash) { + return hash % 34798362354533llu; + } + static size_t mod43843189232363(size_t hash) { + return hash % 43843189232363llu; + } + static size_t mod55238957008387(size_t hash) { + return hash % 55238957008387llu; + } + static size_t mod69596724709081(size_t hash) { + return hash % 69596724709081llu; + } + static size_t mod87686378464759(size_t hash) { + return hash % 87686378464759llu; + } + static size_t mod110477914016779(size_t hash) { + return hash % 110477914016779llu; + } + static size_t mod139193449418173(size_t hash) { + return hash % 139193449418173llu; + } + static size_t mod175372756929481(size_t hash) { + return hash % 175372756929481llu; + } + static size_t mod220955828033581(size_t hash) { + return hash % 220955828033581llu; + } + static size_t mod278386898836457(size_t hash) { + return hash % 278386898836457llu; + } + static size_t mod350745513859007(size_t hash) { + return hash % 350745513859007llu; + } + static size_t mod441911656067171(size_t hash) { + return hash % 441911656067171llu; + } + static size_t mod556773797672909(size_t hash) { + return hash % 556773797672909llu; + } + static size_t mod701491027718027(size_t hash) { + return hash % 701491027718027llu; + } + static size_t mod883823312134381(size_t hash) { + return hash % 883823312134381llu; + } + static size_t mod1113547595345903(size_t hash) { + return hash % 1113547595345903llu; + } + static size_t mod1402982055436147(size_t hash) { + return hash % 1402982055436147llu; + } + static size_t mod1767646624268779(size_t hash) { + return hash % 1767646624268779llu; + } + static size_t mod2227095190691797(size_t hash) { + return hash % 2227095190691797llu; + } + static size_t mod2805964110872297(size_t hash) { + return hash % 2805964110872297llu; + } + static size_t mod3535293248537579(size_t hash) { + return hash % 3535293248537579llu; + } + static size_t mod4454190381383713(size_t hash) { + return hash % 4454190381383713llu; + } + static size_t mod5611928221744609(size_t hash) { + return hash % 5611928221744609llu; + } + static size_t mod7070586497075177(size_t hash) { + return hash % 7070586497075177llu; + } + static size_t mod8908380762767489(size_t hash) { + return hash % 8908380762767489llu; + } + static size_t mod11223856443489329(size_t hash) { + return hash % 11223856443489329llu; + } + static size_t mod14141172994150357(size_t hash) { + return hash % 14141172994150357llu; + } + static size_t mod17816761525534927(size_t hash) { + return hash % 17816761525534927llu; + } + static size_t mod22447712886978529(size_t hash) { + return hash % 22447712886978529llu; + } + static size_t mod28282345988300791(size_t hash) { + return hash % 28282345988300791llu; + } + static size_t mod35633523051069991(size_t hash) { + return hash % 35633523051069991llu; + } + static size_t mod44895425773957261(size_t hash) { + return hash % 44895425773957261llu; + } + static size_t mod56564691976601587(size_t hash) { + return hash % 56564691976601587llu; + } + static size_t mod71267046102139967(size_t hash) { + return hash % 71267046102139967llu; + } + static size_t mod89790851547914507(size_t hash) { + return hash % 89790851547914507llu; + } + static size_t mod113129383953203213(size_t hash) { + return hash % 113129383953203213llu; + } + static size_t mod142534092204280003(size_t hash) { + return hash % 142534092204280003llu; + } + static size_t mod179581703095829107(size_t hash) { + return hash % 179581703095829107llu; + } + static size_t mod226258767906406483(size_t hash) { + return hash % 226258767906406483llu; + } + static size_t mod285068184408560057(size_t hash) { + return hash % 285068184408560057llu; + } + static size_t mod359163406191658253(size_t hash) { + return hash % 359163406191658253llu; + } + static size_t mod452517535812813007(size_t hash) { + return hash % 452517535812813007llu; + } + static size_t mod570136368817120201(size_t hash) { + return hash % 570136368817120201llu; + } + static size_t mod718326812383316683(size_t hash) { + return hash % 718326812383316683llu; + } + static size_t mod905035071625626043(size_t hash) { + return hash % 905035071625626043llu; + } + static size_t mod1140272737634240411(size_t hash) { + return hash % 1140272737634240411llu; + } + static size_t mod1436653624766633509(size_t hash) { + return hash % 1436653624766633509llu; + } + static size_t mod1810070143251252131(size_t hash) { + return hash % 1810070143251252131llu; + } + static size_t mod2280545475268481167(size_t hash) { + return hash % 2280545475268481167llu; + } + static size_t mod2873307249533267101(size_t hash) { + return hash % 2873307249533267101llu; + } + static size_t mod3620140286502504283(size_t hash) { + return hash % 3620140286502504283llu; + } + static size_t mod4561090950536962147(size_t hash) { + return hash % 4561090950536962147llu; + } + static size_t mod5746614499066534157(size_t hash) { + return hash % 5746614499066534157llu; + } + static size_t mod7240280573005008577(size_t hash) { + return hash % 7240280573005008577llu; + } + static size_t mod9122181901073924329(size_t hash) { + return hash % 9122181901073924329llu; + } + static size_t mod11493228998133068689(size_t hash) { + return hash % 11493228998133068689llu; + } + static size_t mod14480561146010017169(size_t hash) { + return hash % 14480561146010017169llu; + } + static size_t mod18446744073709551557(size_t hash) { + return hash % 18446744073709551557llu; + } + + using mod_function = size_t (*)(size_t); + + mod_function next_size_over(size_t &size) const { + // prime numbers generated by the following method: + // 1. start with a prime p = 2 + // 2. go to wolfram alpha and get p = NextPrime(2 * p) + // 3. repeat 2. until you overflow 64 bits + // you now have large gaps which you would hit if somebody called reserve() + // with an unlucky number. + // 4. to fill the gaps for every prime p go to wolfram alpha and get + // ClosestPrime(p * 2^(1/3)) and ClosestPrime(p * 2^(2/3)) and put those in + // the gaps + // 5. get PrevPrime(2^64) and put it at the end + static constexpr const size_t prime_list[] = {2llu, + 3llu, + 5llu, + 7llu, + 11llu, + 13llu, + 17llu, + 23llu, + 29llu, + 37llu, + 47llu, + 59llu, + 73llu, + 97llu, + 127llu, + 151llu, + 197llu, + 251llu, + 313llu, + 397llu, + 499llu, + 631llu, + 797llu, + 1009llu, + 1259llu, + 1597llu, + 2011llu, + 2539llu, + 3203llu, + 4027llu, + 5087llu, + 6421llu, + 8089llu, + 10193llu, + 12853llu, + 16193llu, + 20399llu, + 25717llu, + 32401llu, + 40823llu, + 51437llu, + 64811llu, + 81649llu, + 102877llu, + 129607llu, + 163307llu, + 205759llu, + 259229llu, + 326617llu, + 411527llu, + 518509llu, + 653267llu, + 823117llu, + 1037059llu, + 1306601llu, + 1646237llu, + 2074129llu, + 2613229llu, + 3292489llu, + 4148279llu, + 5226491llu, + 6584983llu, + 8296553llu, + 10453007llu, + 13169977llu, + 16593127llu, + 20906033llu, + 26339969llu, + 33186281llu, + 41812097llu, + 52679969llu, + 66372617llu, + 83624237llu, + 105359939llu, + 132745199llu, + 167248483llu, + 210719881llu, + 265490441llu, + 334496971llu, + 421439783llu, + 530980861llu, + 668993977llu, + 842879579llu, + 1061961721llu, + 1337987929llu, + 1685759167llu, + 2123923447llu, + 2675975881llu, + 3371518343llu, + 4247846927llu, + 5351951779llu, + 6743036717llu, + 8495693897llu, + 10703903591llu, + 13486073473llu, + 16991387857llu, + 21407807219llu, + 26972146961llu, + 33982775741llu, + 42815614441llu, + 53944293929llu, + 67965551447llu, + 85631228929llu, + 107888587883llu, + 135931102921llu, + 171262457903llu, + 215777175787llu, + 271862205833llu, + 342524915839llu, + 431554351609llu, + 543724411781llu, + 685049831731llu, + 863108703229llu, + 1087448823553llu, + 1370099663459llu, + 1726217406467llu, + 2174897647073llu, + 2740199326961llu, + 3452434812973llu, + 4349795294267llu, + 5480398654009llu, + 6904869625999llu, + 8699590588571llu, + 10960797308051llu, + 13809739252051llu, + 17399181177241llu, + 21921594616111llu, + 27619478504183llu, + 34798362354533llu, + 43843189232363llu, + 55238957008387llu, + 69596724709081llu, + 87686378464759llu, + 110477914016779llu, + 139193449418173llu, + 175372756929481llu, + 220955828033581llu, + 278386898836457llu, + 350745513859007llu, + 441911656067171llu, + 556773797672909llu, + 701491027718027llu, + 883823312134381llu, + 1113547595345903llu, + 1402982055436147llu, + 1767646624268779llu, + 2227095190691797llu, + 2805964110872297llu, + 3535293248537579llu, + 4454190381383713llu, + 5611928221744609llu, + 7070586497075177llu, + 8908380762767489llu, + 11223856443489329llu, + 14141172994150357llu, + 17816761525534927llu, + 22447712886978529llu, + 28282345988300791llu, + 35633523051069991llu, + 44895425773957261llu, + 56564691976601587llu, + 71267046102139967llu, + 89790851547914507llu, + 113129383953203213llu, + 142534092204280003llu, + 179581703095829107llu, + 226258767906406483llu, + 285068184408560057llu, + 359163406191658253llu, + 452517535812813007llu, + 570136368817120201llu, + 718326812383316683llu, + 905035071625626043llu, + 1140272737634240411llu, + 1436653624766633509llu, + 1810070143251252131llu, + 2280545475268481167llu, + 2873307249533267101llu, + 3620140286502504283llu, + 4561090950536962147llu, + 5746614499066534157llu, + 7240280573005008577llu, + 9122181901073924329llu, + 11493228998133068689llu, + 14480561146010017169llu, + 18446744073709551557llu}; + static constexpr size_t (*const mod_functions[])(size_t) = { + &mod0, + &mod2, + &mod3, + &mod5, + &mod7, + &mod11, + &mod13, + &mod17, + &mod23, + &mod29, + &mod37, + &mod47, + &mod59, + &mod73, + &mod97, + &mod127, + &mod151, + &mod197, + &mod251, + &mod313, + &mod397, + &mod499, + &mod631, + &mod797, + &mod1009, + &mod1259, + &mod1597, + &mod2011, + &mod2539, + &mod3203, + &mod4027, + &mod5087, + &mod6421, + &mod8089, + &mod10193, + &mod12853, + &mod16193, + &mod20399, + &mod25717, + &mod32401, + &mod40823, + &mod51437, + &mod64811, + &mod81649, + &mod102877, + &mod129607, + &mod163307, + &mod205759, + &mod259229, + &mod326617, + &mod411527, + &mod518509, + &mod653267, + &mod823117, + &mod1037059, + &mod1306601, + &mod1646237, + &mod2074129, + &mod2613229, + &mod3292489, + &mod4148279, + &mod5226491, + &mod6584983, + &mod8296553, + &mod10453007, + &mod13169977, + &mod16593127, + &mod20906033, + &mod26339969, + &mod33186281, + &mod41812097, + &mod52679969, + &mod66372617, + &mod83624237, + &mod105359939, + &mod132745199, + &mod167248483, + &mod210719881, + &mod265490441, + &mod334496971, + &mod421439783, + &mod530980861, + &mod668993977, + &mod842879579, + &mod1061961721, + &mod1337987929, + &mod1685759167, + &mod2123923447, + &mod2675975881, + &mod3371518343, + &mod4247846927, + &mod5351951779, + &mod6743036717, + &mod8495693897, + &mod10703903591, + &mod13486073473, + &mod16991387857, + &mod21407807219, + &mod26972146961, + &mod33982775741, + &mod42815614441, + &mod53944293929, + &mod67965551447, + &mod85631228929, + &mod107888587883, + &mod135931102921, + &mod171262457903, + &mod215777175787, + &mod271862205833, + &mod342524915839, + &mod431554351609, + &mod543724411781, + &mod685049831731, + &mod863108703229, + &mod1087448823553, + &mod1370099663459, + &mod1726217406467, + &mod2174897647073, + &mod2740199326961, + &mod3452434812973, + &mod4349795294267, + &mod5480398654009, + &mod6904869625999, + &mod8699590588571, + &mod10960797308051, + &mod13809739252051, + &mod17399181177241, + &mod21921594616111, + &mod27619478504183, + &mod34798362354533, + &mod43843189232363, + &mod55238957008387, + &mod69596724709081, + &mod87686378464759, + &mod110477914016779, + &mod139193449418173, + &mod175372756929481, + &mod220955828033581, + &mod278386898836457, + &mod350745513859007, + &mod441911656067171, + &mod556773797672909, + &mod701491027718027, + &mod883823312134381, + &mod1113547595345903, + &mod1402982055436147, + &mod1767646624268779, + &mod2227095190691797, + &mod2805964110872297, + &mod3535293248537579, + &mod4454190381383713, + &mod5611928221744609, + &mod7070586497075177, + &mod8908380762767489, + &mod11223856443489329, + &mod14141172994150357, + &mod17816761525534927, + &mod22447712886978529, + &mod28282345988300791, + &mod35633523051069991, + &mod44895425773957261, + &mod56564691976601587, + &mod71267046102139967, + &mod89790851547914507, + &mod113129383953203213, + &mod142534092204280003, + &mod179581703095829107, + &mod226258767906406483, + &mod285068184408560057, + &mod359163406191658253, + &mod452517535812813007, + &mod570136368817120201, + &mod718326812383316683, + &mod905035071625626043, + &mod1140272737634240411, + &mod1436653624766633509, + &mod1810070143251252131, + &mod2280545475268481167, + &mod2873307249533267101, + &mod3620140286502504283, + &mod4561090950536962147, + &mod5746614499066534157, + &mod7240280573005008577, + &mod9122181901073924329, + &mod11493228998133068689, + &mod14480561146010017169, + &mod18446744073709551557}; + const size_t *found = std::lower_bound( + std::begin(prime_list), std::end(prime_list) - 1, size); + size = *found; + return mod_functions[1 + found - prime_list]; + } + void commit(mod_function new_mod_function) { + current_mod_function = new_mod_function; + } + void reset() { current_mod_function = &mod0; } + + size_t index_for_hash(size_t hash, size_t /*num_slots_minus_one*/) const { + return current_mod_function(hash); + } + size_t keep_in_range(size_t index, size_t num_slots_minus_one) const { + return index > num_slots_minus_one ? current_mod_function(index) : index; + } + + private: + mod_function current_mod_function = &mod0; +}; + +struct power_of_two_hash_policy { + size_t index_for_hash(size_t hash, size_t num_slots_minus_one) const { + return hash & num_slots_minus_one; + } + size_t keep_in_range(size_t index, size_t num_slots_minus_one) const { + return index_for_hash(index, num_slots_minus_one); + } + int8_t next_size_over(size_t &size) const { + size = detailv3::next_power_of_two(size); + return 0; + } + void commit(int8_t) {} + void reset() {} +}; + +struct fibonacci_hash_policy { + size_t index_for_hash(size_t hash, size_t /*num_slots_minus_one*/) const { + return (11400714819323198485ull * hash) >> shift; + } + size_t keep_in_range(size_t index, size_t num_slots_minus_one) const { + return index & num_slots_minus_one; + } + + int8_t next_size_over(size_t &size) const { + size = (std::max)(size_t(2), detailv3::next_power_of_two(size)); + return 64 - detailv3::log2(size); + } + void commit(int8_t shift) { this->shift = shift; } + void reset() { shift = 63; } + + private: + int8_t shift = 63; +}; + +template , + typename E = std::equal_to, + typename A = std::allocator>> +class flat_hash_map + : public detailv3::sherwood_v3_table< + std::pair, + K, + H, + detailv3::KeyOrValueHasher, H>, + E, + detailv3::KeyOrValueEquality, E>, + A, + typename std::allocator_traits::template rebind_alloc< + detailv3::sherwood_v3_entry>>> { + using Table = detailv3::sherwood_v3_table< + std::pair, + K, + H, + detailv3::KeyOrValueHasher, H>, + E, + detailv3::KeyOrValueEquality, E>, + A, + typename std::allocator_traits::template rebind_alloc< + detailv3::sherwood_v3_entry>>>; + + public: + using key_type = K; + using mapped_type = V; + + using Table::Table; + flat_hash_map() {} + + inline V &operator[](const K &key) { + return emplace(key, convertible_to_value()).first->second; + } + inline V &operator[](K &&key) { + return emplace(std::move(key), convertible_to_value()).first->second; + } + V &at(const K &key) { + auto found = this->find(key); + if (found == this->end()) + throw std::out_of_range("Argument passed to at() was not in the map."); + return found->second; + } + const V &at(const K &key) const { + auto found = this->find(key); + if (found == this->end()) + throw std::out_of_range("Argument passed to at() was not in the map."); + return found->second; + } + + using Table::emplace; + std::pair emplace() { + return emplace(key_type(), convertible_to_value()); + } + template + std::pair insert_or_assign( + const key_type &key, M &&m) { + auto emplace_result = emplace(key, std::forward(m)); + if (!emplace_result.second) + emplace_result.first->second = std::forward(m); + return emplace_result; + } + template + std::pair insert_or_assign(key_type &&key, + M &&m) { + auto emplace_result = emplace(std::move(key), std::forward(m)); + if (!emplace_result.second) + emplace_result.first->second = std::forward(m); + return emplace_result; + } + template + typename Table::iterator insert_or_assign(typename Table::const_iterator, + const key_type &key, + M &&m) { + return insert_or_assign(key, std::forward(m)).first; + } + template + typename Table::iterator insert_or_assign(typename Table::const_iterator, + key_type &&key, + M &&m) { + return insert_or_assign(std::move(key), std::forward(m)).first; + } + + friend bool operator==(const flat_hash_map &lhs, const flat_hash_map &rhs) { + if (lhs.size() != rhs.size()) return false; + for (const typename Table::value_type &value : lhs) { + auto found = rhs.find(value.first); + if (found == rhs.end()) + return false; + else if (value.second != found->second) + return false; + } + return true; + } + friend bool operator!=(const flat_hash_map &lhs, const flat_hash_map &rhs) { + return !(lhs == rhs); + } + + private: + struct convertible_to_value { + operator V() const { return V(); } + }; +}; + +template , + typename E = std::equal_to, + typename A = std::allocator> +class flat_hash_set + : public detailv3::sherwood_v3_table< + T, + T, + H, + detailv3::functor_storage, + E, + detailv3::functor_storage, + A, + typename std::allocator_traits::template rebind_alloc< + detailv3::sherwood_v3_entry>> { + using Table = detailv3::sherwood_v3_table< + T, + T, + H, + detailv3::functor_storage, + E, + detailv3::functor_storage, + A, + typename std::allocator_traits::template rebind_alloc< + detailv3::sherwood_v3_entry>>; + + public: + using key_type = T; + + using Table::Table; + flat_hash_set() {} + + template + std::pair emplace(Args &&...args) { + return Table::emplace(T(std::forward(args)...)); + } + std::pair emplace(const key_type &arg) { + return Table::emplace(arg); + } + std::pair emplace(key_type &arg) { + return Table::emplace(arg); + } + std::pair emplace(const key_type &&arg) { + return Table::emplace(std::move(arg)); + } + std::pair emplace(key_type &&arg) { + return Table::emplace(std::move(arg)); + } + + friend bool operator==(const flat_hash_set &lhs, const flat_hash_set &rhs) { + if (lhs.size() != rhs.size()) return false; + for (const T &value : lhs) { + if (rhs.find(value) == rhs.end()) return false; + } + return true; + } + friend bool operator!=(const flat_hash_set &lhs, const flat_hash_set &rhs) { + return !(lhs == rhs); + } +}; + +template +struct power_of_two_std_hash : std::hash { + typedef paddle::power_of_two_hash_policy hash_policy; +}; + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/none.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/none.h new file mode 100644 index 0000000000000000000000000000000000000000..965855f556226227271470283fb8cd05b50e23e2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/none.h @@ -0,0 +1,39 @@ +// This file copy from boost/none_t.hpp and boost/none.hpp and boost version: +// 1.41.0 +// Modified the following points: +// 1. modify namespace from boost::none to paddle::none +// 2. modify namespace from boost::none_t to paddle::none_t + +// Copyright (C) 2003, Fernando Luis Cacciola Carballal. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/optional for documentation. +// +// You are welcome to contact the author at: +// fernando_cacciola@hotmail.com +// +#pragma once + +namespace paddle { + +namespace detail { +struct none_helper {}; +} // namespace detail + +typedef int detail::none_helper::*none_t; + +} // namespace paddle + +// NOTE: Borland users have to include this header outside any precompiled +// headers +// (bcc<=5.64 cannot include instance data in a precompiled header) +// -- * To be verified, now that there's no unnamed namespace + +namespace paddle { + +none_t const none = ((none_t)0); + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/optional.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/optional.h new file mode 100644 index 0000000000000000000000000000000000000000..0b5189b70f1ef556b59aebd76d1939162a3888a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/optional.h @@ -0,0 +1,868 @@ +// This file copy from boost/optional/optional.hpp and boost version: 1.41.0 +// Modified the following points: +// 1. modify namespace from boost::optional to paddle::optional +// 2. remove the depending boost header files +// 3. remove/modify some macro +// 4. copy some necessary data structures which are the depended by optional +// 5. replace type_with_alignment with std::aligned_storage + +// Copyright (C) 2003, Fernando Luis Cacciola Carballal. +// +// Use, modification, and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/lib/optional for documentation. +// +// You are welcome to contact the author at: +// fernando_cacciola@hotmail.com +// +#pragma once + +#include +#include +#include +#include +#include + +#include "none.h" + +namespace paddle { + +// Daniel Wallin discovered that bind/apply.hpp badly interacts with the apply<> +// member template of a factory as used in the optional<> implementation. +// He proposed this simple fix which is to move the call to apply<> outside +// namespace boost. +namespace paddle_optional_detail { +template +void construct(Factory const& factory, void* address) { + factory.template apply(address); +} +} // namespace paddle_optional_detail + +template +class optional; + +class in_place_factory_base {}; +class typed_in_place_factory_base {}; + +// template bool equal_pointees(OP const& x, OP const& y); +// template struct equal_pointees_t; +// +// Being OP a model of OptionalPointee (either a pointer or an optional): +// +// If both x and y have valid pointees, returns the result of (*x == *y) +// If only one has a valid pointee, returns false. +// If none have valid pointees, returns true. +// No-throw +template +inline bool equal_pointees(OptionalPointee const& x, OptionalPointee const& y) { + return (!x) != (!y) ? false : (!x ? true : (*x) == (*y)); +} + +template +struct equal_pointees_t + : std::binary_function { + bool operator()(OptionalPointee const& x, OptionalPointee const& y) const { + return equal_pointees(x, y); + } +}; + +// template bool less_pointees(OP const& x, OP const& y); +// template struct less_pointees_t; +// +// Being OP a model of OptionalPointee (either a pointer or an optional): +// +// If y has not a valid pointee, returns false. +// ElseIf x has not a valid pointee, returns true. +// ElseIf both x and y have valid pointees, returns the result of (*x < *y) +// No-throw +template +inline bool less_pointees(OptionalPointee const& x, OptionalPointee const& y) { + return !y ? false : (!x ? true : (*x) < (*y)); +} + +template +struct less_pointees_t + : std::binary_function { + bool operator()(OptionalPointee const& x, OptionalPointee const& y) const { + return less_pointees(x, y); + } +}; + +namespace detail { + +template +class reference_content { + private: // representation + RefT content_; + + public: // structors + ~reference_content() {} + + reference_content(RefT r) : content_(r) {} + + reference_content(const reference_content& operand) + : content_(operand.content_) {} + + private: // non-Assignable + reference_content& operator=(const reference_content&); + + public: // queries + RefT get() const { return content_; } +}; + +template +struct make_reference_content { + typedef T type; +}; + +template +struct make_reference_content { + typedef reference_content type; +}; + +} // namespace detail + +namespace optional_detail { + +// This local class is used instead of that in "aligned_storage.hpp" +// because I've found the 'official' class to ICE BCB5.5 +// when some types are used with optional<> +// (due to sizeof() passed down as a non-type template parameter) +template +class aligned_storage { + // Borland ICEs if unnamed unions are used for this! + union dummy_u { + char data[sizeof(T)]; + typename std::aligned_storage<::std::alignment_of::value>::type aligner_; + } dummy_; + + public: + void const* address() const { return &dummy_.data[0]; } + void* address() { return &dummy_.data[0]; } +}; + +template +struct types_when_isnt_ref { + typedef T const& reference_const_type; + typedef T& reference_type; + typedef T const* pointer_const_type; + typedef T* pointer_type; + typedef T const& argument_type; +}; +template +struct types_when_is_ref { + typedef typename std::remove_reference::type raw_type; + + typedef raw_type& reference_const_type; + typedef raw_type& reference_type; + typedef raw_type* pointer_const_type; + typedef raw_type* pointer_type; + typedef raw_type& argument_type; +}; + +struct optional_tag {}; + +template +class optional_base : public optional_tag { + private: + typedef + typename ::paddle::detail::make_reference_content::type internal_type; + + typedef aligned_storage storage_type; + + typedef types_when_isnt_ref types_when_not_ref; + typedef types_when_is_ref types_when_ref; + + typedef optional_base this_type; + + protected: + typedef T value_type; + + typedef std::true_type is_reference_tag; + typedef std::false_type is_not_reference_tag; + + typedef typename std::is_reference::type is_reference_predicate; + + typedef typename std::conditional::type types; + + typedef bool (this_type::*unspecified_bool_type)() const; + + typedef typename types::reference_type reference_type; + typedef typename types::reference_const_type reference_const_type; + typedef typename types::pointer_type pointer_type; + typedef typename types::pointer_const_type pointer_const_type; + typedef typename types::argument_type argument_type; + + // Creates an optional uninitialized. + // No-throw + optional_base() : m_initialized(false) {} + + // Creates an optional uninitialized. + // No-throw + optional_base(none_t) : m_initialized(false) {} + + // Creates an optional initialized with 'val'. + // Can throw if T::T(T const&) does + optional_base(argument_type val) : m_initialized(false) { construct(val); } + + // Creates an optional initialized with 'val' IFF cond is true, otherwise + // creates an uninitialzed optional. + // Can throw if T::T(T const&) does + optional_base(bool cond, argument_type val) : m_initialized(false) { + if (cond) construct(val); + } + + // Creates a deep copy of another optional + // Can throw if T::T(T const&) does + optional_base(optional_base const& rhs) : m_initialized(false) { + if (rhs.is_initialized()) construct(rhs.get_impl()); + } + + // This is used for both converting and in-place constructions. + // Derived classes use the 'tag' to select the appropriate + // implementation (the correct 'construct()' overload) + template + explicit optional_base(Expr const& expr, Expr const* tag) + : m_initialized(false) { + construct(expr, tag); + } + + // No-throw (assuming T::~T() doesn't) + ~optional_base() { destroy(); } + + // Assigns from another optional (deep-copies the rhs value) + void assign(optional_base const& rhs) { + if (is_initialized()) { + if (rhs.is_initialized()) + assign_value(rhs.get_impl(), is_reference_predicate()); + else + destroy(); + } else { + if (rhs.is_initialized()) construct(rhs.get_impl()); + } + } + + // Assigns from another _convertible_ optional (deep-copies the rhs value) + template + void assign(optional const& rhs) { + if (is_initialized()) { + if (rhs.is_initialized()) + assign_value(static_cast(rhs.get()), + is_reference_predicate()); + else + destroy(); + } else { + if (rhs.is_initialized()) construct(static_cast(rhs.get())); + } + } + + // Assigns from a T (deep-copies the rhs value) + void assign(argument_type val) { + if (is_initialized()) + assign_value(val, is_reference_predicate()); + else + construct(val); + } + + // Assigns from "none", destroying the current value, if any, leaving this + // UNINITIALIZED + // No-throw (assuming T::~T() doesn't) + void assign(none_t) { destroy(); } + + template + void assign_expr(Expr const& expr, Expr const* tag) { + if (is_initialized()) + assign_expr_to_initialized(expr, tag); + else + construct(expr, tag); + } + + public: + // Destroys the current value, if any, leaving this UNINITIALIZED + // No-throw (assuming T::~T() doesn't) + void reset() { destroy(); } + + // Replaces the current value -if any- with 'val' + void reset(argument_type val) { assign(val); } + + // Returns a pointer to the value if this is initialized, otherwise, + // returns NULL. + // No-throw + pointer_const_type get_ptr() const { + return m_initialized ? get_ptr_impl() : 0; + } + pointer_type get_ptr() { return m_initialized ? get_ptr_impl() : 0; } + + bool is_initialized() const { return m_initialized; } + + protected: + void construct(argument_type val) { + new (m_storage.address()) internal_type(val); + m_initialized = true; + } + + // Constructs in-place using the given factory + template + void construct(Expr const& factory, in_place_factory_base const*) { + static_assert(!is_reference_predicate::value, + "!is_reference_predicate::value"); + paddle_optional_detail::construct(factory, m_storage.address()); + m_initialized = true; + } + + // Constructs in-place using the given typed factory + template + void construct(Expr const& factory, typed_in_place_factory_base const*) { + static_assert(!is_reference_predicate::value, + "!is_reference_predicate::value"); + factory.apply(m_storage.address()); + m_initialized = true; + } + + template + void assign_expr_to_initialized(Expr const& factory, + in_place_factory_base const* tag) { + destroy(); + construct(factory, tag); + } + + // Constructs in-place using the given typed factory + template + void assign_expr_to_initialized(Expr const& factory, + typed_in_place_factory_base const* tag) { + destroy(); + construct(factory, tag); + } + + // Constructs using any expression implicitely convertible to the single + // argument + // of a one-argument T constructor. + // Converting constructions of optional from optional uses this function + // with + // 'Expr' being of type 'U' and relying on a converting constructor of T from + // U. + template + void construct(Expr const& expr, void const*) { + new (m_storage.address()) internal_type(expr); + m_initialized = true; + } + + // Assigns using a form any expression implicitely convertible to the single + // argument + // of a T's assignment operator. + // Converting assignments of optional from optional uses this function + // with + // 'Expr' being of type 'U' and relying on a converting assignment of T from + // U. + template + void assign_expr_to_initialized(Expr const& expr, void const*) { + assign_value(expr, is_reference_predicate()); + } + + void assign_value(argument_type val, is_not_reference_tag) { + get_impl() = val; + } + void assign_value(argument_type val, is_reference_tag) { construct(val); } + + void destroy() { + if (m_initialized) destroy_impl(is_reference_predicate()); + } + + unspecified_bool_type safe_bool() const { + return m_initialized ? &this_type::is_initialized : 0; + } + + reference_const_type get_impl() const { + return dereference(get_object(), is_reference_predicate()); + } + reference_type get_impl() { + return dereference(get_object(), is_reference_predicate()); + } + + pointer_const_type get_ptr_impl() const { + return cast_ptr(get_object(), is_reference_predicate()); + } + pointer_type get_ptr_impl() { + return cast_ptr(get_object(), is_reference_predicate()); + } + + private: + // internal_type can be either T or reference_content + internal_type const* get_object() const { + return static_cast(m_storage.address()); + } + internal_type* get_object() { + return static_cast(m_storage.address()); + } + + // reference_content lacks an implicit conversion to T&, so the following + // is needed to obtain a proper reference. + reference_const_type dereference(internal_type const* p, + is_not_reference_tag) const { + return *p; + } + reference_type dereference(internal_type* p, is_not_reference_tag) { + return *p; + } + reference_const_type dereference(internal_type const* p, + is_reference_tag) const { + return p->get(); + } + reference_type dereference(internal_type* p, is_reference_tag) { + return p->get(); + } + + void destroy_impl(is_not_reference_tag) { + get_ptr_impl()->T::~T(); + m_initialized = false; + } + + void destroy_impl(is_reference_tag) { m_initialized = false; } + + // If T is of reference type, trying to get a pointer to the held value must + // result in a compile-time error. + // Decent compilers should disallow conversions from reference_content* to + // T*, but just in case, + // the following olverloads are used to filter out the case and guarantee an + // error in case of T being a reference. + pointer_const_type cast_ptr(internal_type const* p, + is_not_reference_tag) const { + return p; + } + pointer_type cast_ptr(internal_type* p, is_not_reference_tag) { return p; } + pointer_const_type cast_ptr(internal_type const* p, is_reference_tag) const { + return &p->get(); + } + pointer_type cast_ptr(internal_type* p, is_reference_tag) { + return &p->get(); + } + + bool m_initialized; + storage_type m_storage; +}; + +} // namespace optional_detail + +template +class optional : public optional_detail::optional_base { + typedef optional_detail::optional_base base; + + typedef typename base::unspecified_bool_type unspecified_bool_type; + + public: + typedef optional this_type; + + typedef typename base::value_type value_type; + typedef typename base::reference_type reference_type; + typedef typename base::reference_const_type reference_const_type; + typedef typename base::pointer_type pointer_type; + typedef typename base::pointer_const_type pointer_const_type; + typedef typename base::argument_type argument_type; + + // Creates an optional uninitialized. + // No-throw + optional() : base() {} + + // Creates an optional uninitialized. + // No-throw + optional(none_t none_) : base(none_) {} + + // Creates an optional initialized with 'val'. + // Can throw if T::T(T const&) does + optional(argument_type val) : base(val) {} + + // Creates an optional initialized with 'val' IFF cond is true, otherwise + // creates an uninitialized optional. + // Can throw if T::T(T const&) does + optional(bool cond, argument_type val) : base(cond, val) {} + + // Creates a deep copy of another convertible optional + // Requires a valid conversion from U to T. + // Can throw if T::T(U const&) does + template + explicit optional(optional const& rhs) : base() { + if (rhs.is_initialized()) this->construct(rhs.get()); + } + + // Creates an optional with an expression which can be either + // (a) An instance of InPlaceFactory (i.e. in_place(a,b,...,n); + // (b) An instance of TypedInPlaceFactory ( i.e. in_place(a,b,...,n); + // (c) Any expression implicitely convertible to the single type + // of a one-argument T's constructor. + // (d*) Weak compilers (BCB) might also resolved Expr as optional and + // optional + // even though explicit overloads are present for these. + // Depending on the above some T ctor is called. + // Can throw is the resolved T ctor throws. + template + explicit optional(Expr const& expr) : base(expr, &expr) {} + + // Creates a deep copy of another optional + // Can throw if T::T(T const&) does + optional(optional const& rhs) : base(rhs) {} + + // No-throw (assuming T::~T() doesn't) + ~optional() {} + + // Assigns from an expression. See corresponding constructor. + // Basic Guarantee: If the resolved T ctor throws, this is left UNINITIALIZED + template + optional& operator=(Expr expr) { + this->assign_expr(expr, &expr); + return *this; + } + + // Assigns from another convertible optional (converts && deep-copies the + // rhs value) + // Requires a valid conversion from U to T. + // Basic Guarantee: If T::T( U const& ) throws, this is left UNINITIALIZED + template + optional& operator=(optional const& rhs) { + this->assign(rhs); + return *this; + } + + // Assigns from another optional (deep-copies the rhs value) + // Basic Guarantee: If T::T( T const& ) throws, this is left UNINITIALIZED + // (NOTE: On BCB, this operator is not actually called and left is left + // UNMODIFIED in case of a throw) + optional& operator=(optional const& rhs) { + this->assign(rhs); + return *this; + } + + // Assigns from a T (deep-copies the rhs value) + // Basic Guarantee: If T::( T const& ) throws, this is left UNINITIALIZED + optional& operator=(argument_type val) { + this->assign(val); + return *this; + } + + // Assigns from a "none" + // Which destroys the current value, if any, leaving this UNINITIALIZED + // No-throw (assuming T::~T() doesn't) + optional& operator=(none_t none_) { + this->assign(none_); + return *this; + } + + // Returns a reference to the value if this is initialized, otherwise, + // the behaviour is UNDEFINED + // No-throw + reference_const_type get() const { + assert(this->is_initialized()); + return this->get_impl(); + } + reference_type get() { + assert(this->is_initialized()); + return this->get_impl(); + } + + // Returns a copy of the value if this is initialized, 'v' otherwise + reference_const_type get_value_or(reference_const_type v) const { + return this->is_initialized() ? get() : v; + } + reference_type get_value_or(reference_type v) { + return this->is_initialized() ? get() : v; + } + + // Returns a pointer to the value if this is initialized, otherwise, + // the behaviour is UNDEFINED + // No-throw + pointer_const_type operator->() const { + assert(this->is_initialized()); + return this->get_ptr_impl(); + } + pointer_type operator->() { + assert(this->is_initialized()); + return this->get_ptr_impl(); + } + + // Returns a reference to the value if this is initialized, otherwise, + // the behaviour is UNDEFINED + // No-throw + reference_const_type operator*() const { return this->get(); } + reference_type operator*() { return this->get(); } + + // implicit conversion to "bool" + // No-throw + operator unspecified_bool_type() const { return this->safe_bool(); } + + // This is provided for those compilers which don't like the conversion to + // bool + // on some contexts. + bool operator!() const { return !this->is_initialized(); } +}; + +// Returns optional(v) +template +inline optional make_optional(T const& v) { + return optional(v); +} + +// Returns optional(cond,v) +template +inline optional make_optional(bool cond, T const& v) { + return optional(cond, v); +} + +// Returns a reference to the value if this is initialized, otherwise, the +// behaviour is UNDEFINED. +// No-throw +template +inline typename optional::reference_const_type get(optional const& opt) { + return opt.get(); +} + +template +inline typename optional::reference_type get(optional& opt) { + return opt.get(); +} + +// Returns a pointer to the value if this is initialized, otherwise, returns +// NULL. +// No-throw +template +inline typename optional::pointer_const_type get(optional const* opt) { + return opt->get_ptr(); +} + +template +inline typename optional::pointer_type get(optional* opt) { + return opt->get_ptr(); +} + +// Returns a reference to the value if this is initialized, otherwise, the +// behaviour is UNDEFINED. +// No-throw +template +inline typename optional::reference_const_type get_optional_value_or( + optional const& opt, typename optional::reference_const_type v) { + return opt.get_value_or(v); +} + +template +inline typename optional::reference_type get_optional_value_or( + optional& opt, typename optional::reference_type v) { + return opt.get_value_or(v); +} + +// Returns a pointer to the value if this is initialized, otherwise, returns +// NULL. +// No-throw +template +inline typename optional::pointer_const_type get_pointer( + optional const& opt) { + return opt.get_ptr(); +} + +template +inline typename optional::pointer_type get_pointer(optional& opt) { + return opt.get_ptr(); +} + +// optional's relational operators ( ==, !=, <, >, <=, >= ) have deep-semantics +// (compare values). +// WARNING: This is UNLIKE pointers. Use equal_pointees()/less_pointess() in +// generic code instead. + +// +// optional vs optional cases +// + +template +inline bool operator==(optional const& x, optional const& y) { + return equal_pointees(x, y); +} + +template +inline bool operator<(optional const& x, optional const& y) { + return less_pointees(x, y); +} + +template +inline bool operator!=(optional const& x, optional const& y) { + return !(x == y); +} + +template +inline bool operator>(optional const& x, optional const& y) { + return y < x; +} + +template +inline bool operator<=(optional const& x, optional const& y) { + return !(y < x); +} + +template +inline bool operator>=(optional const& x, optional const& y) { + return !(x < y); +} + +// +// optional vs T cases +// +template +inline bool operator==(optional const& x, T const& y) { + return equal_pointees(x, optional(y)); +} + +template +inline bool operator<(optional const& x, T const& y) { + return less_pointees(x, optional(y)); +} + +template +inline bool operator!=(optional const& x, T const& y) { + return !(x == y); +} + +template +inline bool operator>(optional const& x, T const& y) { + return y < x; +} + +template +inline bool operator<=(optional const& x, T const& y) { + return !(y < x); +} + +template +inline bool operator>=(optional const& x, T const& y) { + return !(x < y); +} + +// +// T vs optional cases +// + +template +inline bool operator==(T const& x, optional const& y) { + return equal_pointees(optional(x), y); +} + +template +inline bool operator<(T const& x, optional const& y) { + return less_pointees(optional(x), y); +} + +template +inline bool operator!=(T const& x, optional const& y) { + return !(x == y); +} + +template +inline bool operator>(T const& x, optional const& y) { + return y < x; +} + +template +inline bool operator<=(T const& x, optional const& y) { + return !(y < x); +} + +template +inline bool operator>=(T const& x, optional const& y) { + return !(x < y); +} + +// +// optional vs none cases +// + +template +inline bool operator==(optional const& x, none_t) { + return equal_pointees(x, optional()); +} + +template +inline bool operator<(optional const& x, none_t) { + return less_pointees(x, optional()); +} + +template +inline bool operator!=(optional const& x, none_t y) { + return !(x == y); +} + +template +inline bool operator>(optional const& x, none_t y) { + return y < x; +} + +template +inline bool operator<=(optional const& x, none_t y) { + return !(y < x); +} + +template +inline bool operator>=(optional const& x, none_t y) { + return !(x < y); +} + +// +// none vs optional cases +// + +template +inline bool operator==(none_t x, optional const& y) { + return equal_pointees(optional(), y); +} + +template +inline bool operator<(none_t x, optional const& y) { + return less_pointees(optional(), y); +} + +template +inline bool operator!=(none_t x, optional const& y) { + return !(x == y); +} + +template +inline bool operator>(none_t x, optional const& y) { + return y < x; +} + +template +inline bool operator<=(none_t x, optional const& y) { + return !(y < x); +} + +template +inline bool operator>=(none_t x, optional const& y) { + return !(x < y); +} + +namespace optional_detail { + +// optional's swap: +// If both are initialized, calls swap(T&, T&). If this swap throws, both will +// remain initialized but their values are now unspecified. +// If only one is initialized, calls U.reset(*I), THEN I.reset(). +// If U.reset(*I) throws, both are left UNCHANGED (U is kept uinitialized and I +// is never reset) +// If both are uninitialized, do nothing (no-throw) +template +inline void optional_swap(optional& x, optional& y) { + if (!x && !!y) { + x.reset(*y); + y.reset(); + } else if (!!x && !y) { + y.reset(*x); + x.reset(); + } else if (!!x && !!y) { + // allow for Koenig lookup + using std::swap; + swap(*x, *y); + } +} + +} // namespace optional_detail + +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/small_vector.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/small_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..5a8abdb4d2386f51a8b6ef8936fc0ca433c1b017 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/small_vector.h @@ -0,0 +1,1486 @@ +// This file copy from llvm/ADT/SmallVector.h, version: 12.0.0 +// Modified the following points +// 1. remove macro +// 2. remove LLVM_LIKELY and LLVM_UNLIKELY +// 3. add at(index) method for small vector +// 4. wrap the call to max and min with parenthesis to prevent the macro +// expansion to fix the build error on windows platform +// 5. change SmallVector to small_vector to unify naming style of utils + +//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the SmallVector class. +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace paddle { + +/// A range adaptor for a pair of iterators. +/// +/// This just wraps two iterators into a range-compatible interface. Nothing +/// fancy at all. +template +class iterator_range { + IteratorT begin_iterator, end_iterator; + + public: + // TODO: Add SFINAE to test that the Container's iterators match the range's + // iterators. + template + iterator_range(Container &&c) + // TODO: Consider ADL/non-member begin/end calls. + : begin_iterator(c.begin()), end_iterator(c.end()) {} + iterator_range(IteratorT begin_iterator, IteratorT end_iterator) + : begin_iterator(std::move(begin_iterator)), + end_iterator(std::move(end_iterator)) {} + + IteratorT begin() const { return begin_iterator; } + IteratorT end() const { return end_iterator; } + bool empty() const { return begin_iterator == end_iterator; } +}; + +/// Convenience function for iterating over sub-ranges. +/// +/// This provides a bit of syntactic sugar to make using sub-ranges +/// in for loops a bit easier. Analogous to std::make_pair(). +template +iterator_range make_range(T x, T y) { + return iterator_range(std::move(x), std::move(y)); +} + +template +iterator_range make_range(std::pair p) { + return iterator_range(std::move(p.first), std::move(p.second)); +} + +/// This is all the stuff common to all SmallVectors. +/// +/// The template parameter specifies the type which should be used to hold the +/// Size and Capacity of the small_vector, so it can be adjusted. +/// Using 32 bit size is desirable to shrink the size of the small_vector. +/// Using 64 bit size is desirable for cases like small_vector, where a +/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for +/// buffering bitcode output - which can exceed 4GB. +template +class small_vector_base { + protected: + void *BeginX; + Size_T Size = 0, Capacity; + + /// The maximum value of the Size_T used. + static constexpr size_t SizeTypeMax() { + return (std::numeric_limits::max)(); + } + + small_vector_base() = delete; + small_vector_base(void *FirstEl, size_t TotalCapacity) + : BeginX(FirstEl), Capacity(TotalCapacity) {} + + /// This is a helper for \a grow() that's out of line to reduce code + /// duplication. This function will report a fatal error if it can't grow at + /// least to \p MinSize. + void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity); + + /// This is an implementation of the grow() method which only works + /// on POD-like data types and is out of line to reduce code duplication. + /// This function will report a fatal error if it cannot increase capacity. + void grow_pod(void *FirstEl, size_t MinSize, size_t TSize); + + public: + size_t size() const { return Size; } + size_t capacity() const { return Capacity; } + + bool empty() const { return !Size; } + + /// Set the array size to \p N, which the current array must have enough + /// capacity for. + /// + /// This does not construct or destroy any elements in the vector. + /// + /// Clients can use this in conjunction with capacity() to write past the end + /// of the buffer when they know that more elements are available, and only + /// update the size later. This avoids the cost of value initializing elements + /// which will only be overwritten. + void set_size(size_t N) { + assert(N <= capacity()); + Size = N; + } +}; + +template +using SmallVectorSizeType = typename std:: + conditional= 8, uint64_t, uint32_t>::type; + +/// Figure out the offset of the first element. +template +struct SmallVectorAlignmentAndSize { + alignas(small_vector_base>) char Base[sizeof( + small_vector_base>)]; + alignas(T) char FirstEl[sizeof(T)]; +}; + +/// This is the part of small_vector_template_base which does not depend on +/// whether +/// the type T is a POD. The extra dummy template argument is used by array_ref +/// to avoid unnecessarily requiring T to be complete. +template +class small_vector_template_common + : public small_vector_base> { + using Base = small_vector_base>; + + /// Find the address of the first element. For this pointer math to be valid + /// with small-size of 0 for T with lots of alignment, it's important that + /// small_vector_storage is properly-aligned even for small-size of 0. + void *getFirstEl() const { + return const_cast(reinterpret_cast( + reinterpret_cast(this) + + offsetof(SmallVectorAlignmentAndSize, FirstEl))); + } + // Space after 'FirstEl' is clobbered, do not add any instance vars after it. + + protected: + small_vector_template_common(size_t Size) : Base(getFirstEl(), Size) {} + + void grow_pod(size_t MinSize, size_t TSize) { + Base::grow_pod(getFirstEl(), MinSize, TSize); + } + + /// Return true if this is a smallvector which has not had dynamic + /// memory allocated for it. + bool isSmall() const { return this->BeginX == getFirstEl(); } + + /// Put this vector in a state of being small. + void resetToSmall() { + this->BeginX = getFirstEl(); + this->Size = this->Capacity = + 0; // FIXME: Setting Capacity to 0 is suspect. + } + + /// Return true if V is an internal reference to the given range. + bool isReferenceToRange(const void *V, + const void *First, + const void *Last) const { + // Use std::less to avoid UB. + std::less<> LessThan; + return !LessThan(V, First) && LessThan(V, Last); + } + + /// Return true if V is an internal reference to this vector. + bool isReferenceToStorage(const void *V) const { + return isReferenceToRange(V, this->begin(), this->end()); + } + + /// Return true if First and Last form a valid (possibly empty) range in this + /// vector's storage. + bool isRangeInStorage(const void *First, const void *Last) const { + // Use std::less to avoid UB. + std::less<> LessThan; + return !LessThan(First, this->begin()) && !LessThan(Last, First) && + !LessThan(this->end(), Last); + } + + /// Return true unless Elt will be invalidated by resizing the vector to + /// NewSize. + bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) { + // Past the end. + if (!isReferenceToStorage(Elt)) return true; + + // Return false if Elt will be destroyed by shrinking. + if (NewSize <= this->size()) return Elt < this->begin() + NewSize; + + // Return false if we need to grow. + return NewSize <= this->capacity(); + } + + /// Check whether Elt will be invalidated by resizing the vector to NewSize. + void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) { + assert(isSafeToReferenceAfterResize(Elt, NewSize) && + "Attempting to reference an element of the vector in an operation " + "that invalidates it"); + } + + /// Check whether Elt will be invalidated by increasing the size of the + /// vector by N. + void assertSafeToAdd(const void *Elt, size_t N = 1) { + this->assertSafeToReferenceAfterResize(Elt, this->size() + N); + } + + /// Check whether any part of the range will be invalidated by clearing. + void assertSafeToReferenceAfterClear(const T *From, const T *To) { + if (From == To) return; + this->assertSafeToReferenceAfterResize(From, 0); + this->assertSafeToReferenceAfterResize(To - 1, 0); + } + template < + class ItTy, + std::enable_if_t, T *>::value, + bool> = false> + void assertSafeToReferenceAfterClear(ItTy, ItTy) {} + + /// Check whether any part of the range will be invalidated by growing. + void assertSafeToAddRange(const T *From, const T *To) { + if (From == To) return; + this->assertSafeToAdd(From, To - From); + this->assertSafeToAdd(To - 1, To - From); + } + template < + class ItTy, + std::enable_if_t, T *>::value, + bool> = false> + void assertSafeToAddRange(ItTy, ItTy) {} + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + template + static const T *reserveForParamAndGetAddressImpl(U *This, + const T &Elt, + size_t N) { + size_t NewSize = This->size() + N; + if (NewSize <= This->capacity()) return &Elt; + + bool ReferencesStorage = false; + int64_t Index = -1; + if (!U::TakesParamByValue) { + if (This->isReferenceToStorage(&Elt)) { + ReferencesStorage = true; + Index = &Elt - This->begin(); + } + } + This->grow(NewSize); + return ReferencesStorage ? This->begin() + Index : &Elt; + } + + public: + using size_type = size_t; + using difference_type = ptrdiff_t; + using value_type = T; + using iterator = T *; + using const_iterator = const T *; + + using const_reverse_iterator = std::reverse_iterator; + using reverse_iterator = std::reverse_iterator; + + using reference = T &; + using const_reference = const T &; + using pointer = T *; + using const_pointer = const T *; + + using Base::capacity; + using Base::empty; + using Base::size; + + // forward iterator creation methods. + iterator begin() { return (iterator)this->BeginX; } + const_iterator begin() const { return (const_iterator)this->BeginX; } + iterator end() { return begin() + size(); } + const_iterator end() const { return begin() + size(); } + + // reverse iterator creation methods. + reverse_iterator rbegin() { return reverse_iterator(end()); } + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end()); + } + reverse_iterator rend() { return reverse_iterator(begin()); } + const_reverse_iterator rend() const { + return const_reverse_iterator(begin()); + } + + size_type size_in_bytes() const { return size() * sizeof(T); } + size_type max_size() const { + return (std::min)(this->SizeTypeMax(), size_type(-1) / sizeof(T)); + } + + size_t capacity_in_bytes() const { return capacity() * sizeof(T); } + + /// Return a pointer to the vector's buffer, even if empty(). + pointer data() { return pointer(begin()); } + /// Return a pointer to the vector's buffer, even if empty(). + const_pointer data() const { return const_pointer(begin()); } + + reference operator[](size_type idx) { + assert(idx < size()); + return begin()[idx]; + } + const_reference operator[](size_type idx) const { + assert(idx < size()); + return begin()[idx]; + } + + reference at(size_type idx) { + assert(idx < size()); + return begin()[idx]; + } + const_reference at(size_type idx) const { + assert(idx < size()); + return begin()[idx]; + } + + reference front() { + assert(!empty()); + return begin()[0]; + } + const_reference front() const { + assert(!empty()); + return begin()[0]; + } + + reference back() { + assert(!empty()); + return end()[-1]; + } + const_reference back() const { + assert(!empty()); + return end()[-1]; + } +}; + +/// small_vector_template_base - This is where we put +/// method implementations that are designed to work with non-trivial T's. +/// +/// We approximate is_trivially_copyable with trivial move/copy construction and +/// trivial destruction. While the standard doesn't specify that you're allowed +/// copy these types with memcpy, there is no way for the type to observe this. +/// This catches the important case of std::pair, which is not +/// trivially assignable. +template ::value) && + (std::is_trivially_move_constructible::value) && + std::is_trivially_destructible::value> +class small_vector_template_base : public small_vector_template_common { + friend class small_vector_template_common; + + protected: + static constexpr bool TakesParamByValue = false; + using ValueParamT = const T &; + + small_vector_template_base(size_t Size) + : small_vector_template_common(Size) {} + + static void destroy_range(T *S, T *E) { + while (S != E) { + --E; + E->~T(); + } + } + + /// Move the range [I, E) into the uninitialized memory starting with "Dest", + /// constructing elements as needed. + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) { + std::uninitialized_copy( + std::make_move_iterator(I), std::make_move_iterator(E), Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory starting with "Dest", + /// constructing elements as needed. + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + std::uninitialized_copy(I, E, Dest); + } + + /// Grow the allocated memory (without initializing new elements), doubling + /// the size of the allocated memory. Guarantees space for at least one more + /// element, or MinSize more elements if specified. + void grow(size_t MinSize = 0); + + /// Create a new allocation big enough for \p MinSize and pass back its size + /// in \p NewCapacity. This is the first section of \a grow(). + T *mallocForGrow(size_t MinSize, size_t &NewCapacity) { + return static_cast( + small_vector_base>::mallocForGrow( + MinSize, sizeof(T), NewCapacity)); + } + + /// Move existing elements over to the new allocation \p NewElts, the middle + /// section of \a grow(). + void moveElementsForGrow(T *NewElts); + + /// Transfer ownership of the allocation, finishing up \a grow(). + void takeAllocationForGrow(T *NewElts, size_t NewCapacity); + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) { + return this->reserveForParamAndGetAddressImpl(this, Elt, N); + } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) { + return const_cast( + this->reserveForParamAndGetAddressImpl(this, Elt, N)); + } + + static T &&forward_value_param(T &&V) { return std::move(V); } + static const T &forward_value_param(const T &V) { return V; } + + void growAndAssign(size_t NumElts, const T &Elt) { + // Grow manually in case Elt is an internal reference. + size_t NewCapacity; + T *NewElts = mallocForGrow(NumElts, NewCapacity); + std::uninitialized_fill_n(NewElts, NumElts, Elt); + this->destroy_range(this->begin(), this->end()); + takeAllocationForGrow(NewElts, NewCapacity); + this->set_size(NumElts); + } + + template + T &growAndEmplaceBack(ArgTypes &&...Args) { + // Grow manually in case one of Args is an internal reference. + size_t NewCapacity; + T *NewElts = mallocForGrow(0, NewCapacity); + ::new ((void *)(NewElts + this->size())) T(std::forward(Args)...); + moveElementsForGrow(NewElts); + takeAllocationForGrow(NewElts, NewCapacity); + this->set_size(this->size() + 1); + return this->back(); + } + + public: + void push_back(const T &Elt) { + const T *EltPtr = reserveForParamAndGetAddress(Elt); + ::new ((void *)this->end()) T(*EltPtr); + this->set_size(this->size() + 1); + } + + void push_back(T &&Elt) { + T *EltPtr = reserveForParamAndGetAddress(Elt); + ::new ((void *)this->end()) T(::std::move(*EltPtr)); + this->set_size(this->size() + 1); + } + + void pop_back() { + this->set_size(this->size() - 1); + this->end()->~T(); + } +}; + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void small_vector_template_base::grow(size_t MinSize) { + size_t NewCapacity; + T *NewElts = mallocForGrow(MinSize, NewCapacity); + moveElementsForGrow(NewElts); + takeAllocationForGrow(NewElts, NewCapacity); +} + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void small_vector_template_base::moveElementsForGrow( + T *NewElts) { + // Move the elements over. + this->uninitialized_move(this->begin(), this->end(), NewElts); + + // Destroy the original elements. + destroy_range(this->begin(), this->end()); +} + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void small_vector_template_base::takeAllocationForGrow( + T *NewElts, size_t NewCapacity) { + // If this wasn't grown from the inline copy, deallocate the old space. + if (!this->isSmall()) free(this->begin()); + + this->BeginX = NewElts; + this->Capacity = NewCapacity; +} + +/// small_vector_template_base - This is where we put +/// method implementations that are designed to work with trivially copyable +/// T's. This allows using memcpy in place of copy/move construction and +/// skipping destruction. +template +class small_vector_template_base + : public small_vector_template_common { + friend class small_vector_template_common; + + protected: + /// True if it's cheap enough to take parameters by value. Doing so avoids + /// overhead related to mitigations for reference invalidation. + static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *); + + /// Either const T& or T, depending on whether it's cheap enough to take + /// parameters by value. + using ValueParamT = + typename std::conditional::type; + + small_vector_template_base(size_t Size) + : small_vector_template_common(Size) {} + + // No need to do a destroy loop for POD's. + static void destroy_range(T *, T *) {} + + /// Move the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) { + // Just do a copy. + uninitialized_copy(I, E, Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + // Arbitrary iterator types; just use the basic implementation. + std::uninitialized_copy(I, E, Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_copy( + T1 *I, + T1 *E, + T2 *Dest, + std::enable_if_t::type, + T2>::value> * = nullptr) { + // Use memcpy for PODs iterated by pointers (which includes small_vector + // iterators): std::uninitialized_copy optimizes to memmove, but we can + // use memcpy here. Note that I and E are iterators and thus might be + // invalid for memcpy if they are equal. + if (I != E) memcpy(reinterpret_cast(Dest), I, (E - I) * sizeof(T)); + } + + /// Double the size of the allocated memory, guaranteeing space for at + /// least one more element or MinSize if specified. + void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) { + return this->reserveForParamAndGetAddressImpl(this, Elt, N); + } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) { + return const_cast( + this->reserveForParamAndGetAddressImpl(this, Elt, N)); + } + + /// Copy \p V or return a reference, depending on \a ValueParamT. + static ValueParamT forward_value_param(ValueParamT V) { return V; } + + void growAndAssign(size_t NumElts, T Elt) { + // Elt has been copied in case it's an internal reference, side-stepping + // reference invalidation problems without losing the realloc optimization. + this->set_size(0); + this->grow(NumElts); + std::uninitialized_fill_n(this->begin(), NumElts, Elt); + this->set_size(NumElts); + } + + template + T &growAndEmplaceBack(ArgTypes &&...Args) { + // Use push_back with a copy in case Args has an internal reference, + // side-stepping reference invalidation problems without losing the realloc + // optimization. + push_back(T(std::forward(Args)...)); + return this->back(); + } + + public: + void push_back(ValueParamT Elt) { + const T *EltPtr = reserveForParamAndGetAddress(Elt); + memcpy(reinterpret_cast(this->end()), EltPtr, sizeof(T)); + this->set_size(this->size() + 1); + } + + void pop_back() { this->set_size(this->size() - 1); } +}; + +/// This class consists of common code factored out of the small_vector class to +/// reduce code duplication based on the small_vector 'N' template parameter. +template +class small_vector_impl : public small_vector_template_base { + using SuperClass = small_vector_template_base; + + public: + using iterator = typename SuperClass::iterator; + using const_iterator = typename SuperClass::const_iterator; + using reference = typename SuperClass::reference; + using size_type = typename SuperClass::size_type; + + protected: + using small_vector_template_base::TakesParamByValue; + using ValueParamT = typename SuperClass::ValueParamT; + + // Default ctor - Initialize to empty. + explicit small_vector_impl(unsigned N) : small_vector_template_base(N) {} + + public: + small_vector_impl(const small_vector_impl &) = delete; + + ~small_vector_impl() { + // Subclass has already destructed this vector's elements. + // If this wasn't grown from the inline copy, deallocate the old space. + if (!this->isSmall()) free(this->begin()); + } + + void clear() { + this->destroy_range(this->begin(), this->end()); + this->Size = 0; + } + + private: + template + void resizeImpl(size_type N) { + if (N < this->size()) { + this->pop_back_n(this->size() - N); + } else if (N > this->size()) { + this->reserve(N); + for (auto I = this->end(), E = this->begin() + N; I != E; ++I) + if (ForOverwrite) + new (&*I) T; + else + new (&*I) T(); + this->set_size(N); + } + } + + public: + void resize(size_type N) { resizeImpl(N); } + + /// Like resize, but \ref T is POD, the new values won't be initialized. + void resize_for_overwrite(size_type N) { resizeImpl(N); } + + void resize(size_type N, ValueParamT NV) { + if (N == this->size()) return; + + if (N < this->size()) { + this->pop_back_n(this->size() - N); + return; + } + + // N > this->size(). Defer to append. + this->append(N - this->size(), NV); + } + + void reserve(size_type N) { + if (this->capacity() < N) this->grow(N); + } + + void pop_back_n(size_type NumItems) { + assert(this->size() >= NumItems); + this->destroy_range(this->end() - NumItems, this->end()); + this->set_size(this->size() - NumItems); + } + + T pop_back_val() { + T Result = ::std::move(this->back()); + this->pop_back(); + return Result; + } + + void swap(small_vector_impl &RHS); + + /// Add the specified range to the end of the small_vector. + template ::iterator_category, + std::input_iterator_tag>::value>> + void append(in_iter in_start, in_iter in_end) { + this->assertSafeToAddRange(in_start, in_end); + size_type NumInputs = std::distance(in_start, in_end); + this->reserve(this->size() + NumInputs); + this->uninitialized_copy(in_start, in_end, this->end()); + this->set_size(this->size() + NumInputs); + } + + /// Append \p NumInputs copies of \p Elt to the end. + void append(size_type NumInputs, ValueParamT Elt) { + const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs); + std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr); + this->set_size(this->size() + NumInputs); + } + + void append(std::initializer_list IL) { append(IL.begin(), IL.end()); } + + void append(const small_vector_impl &RHS) { append(RHS.begin(), RHS.end()); } + + void assign(size_type NumElts, ValueParamT Elt) { + // Note that Elt could be an internal reference. + if (NumElts > this->capacity()) { + this->growAndAssign(NumElts, Elt); + return; + } + + // Assign over existing elements. + std::fill_n(this->begin(), (std::min)(NumElts, this->size()), Elt); + if (NumElts > this->size()) + std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt); + else if (NumElts < this->size()) + this->destroy_range(this->begin() + NumElts, this->end()); + this->set_size(NumElts); + } + + // FIXME: Consider assigning over existing elements, rather than clearing & + // re-initializing them - for all assign(...) variants. + + template ::iterator_category, + std::input_iterator_tag>::value>> + void assign(in_iter in_start, in_iter in_end) { + this->assertSafeToReferenceAfterClear(in_start, in_end); + clear(); + append(in_start, in_end); + } + + void assign(std::initializer_list IL) { + clear(); + append(IL); + } + + void assign(const small_vector_impl &RHS) { assign(RHS.begin(), RHS.end()); } + + iterator erase(const_iterator CI) { + // Just cast away constness because this is a non-const member function. + iterator I = const_cast(CI); + + assert(this->isReferenceToStorage(CI) && + "Iterator to erase is out of bounds."); + + iterator N = I; + // Shift all elts down one. + std::move(I + 1, this->end(), I); + // Drop the last elt. + this->pop_back(); + return (N); + } + + iterator erase(const_iterator CS, const_iterator CE) { + // Just cast away constness because this is a non-const member function. + iterator S = const_cast(CS); + iterator E = const_cast(CE); + + assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds."); + + iterator N = S; + // Shift all elts down. + iterator I = std::move(E, this->end(), S); + // Drop the last elts. + this->destroy_range(I, this->end()); + this->set_size(I - this->begin()); + return (N); + } + + private: + template + iterator insert_one_impl(iterator I, ArgType &&Elt) { + // Callers ensure that ArgType is derived from T. + static_assert( + std::is_same>, + T>::value, + "ArgType must be derived from T!"); + + if (I == this->end()) { // Important special case for empty vector. + this->push_back(::std::forward(Elt)); + return this->end() - 1; + } + + assert(this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Grow if necessary. + size_t Index = I - this->begin(); + std::remove_reference_t *EltPtr = + this->reserveForParamAndGetAddress(Elt); + I = this->begin() + Index; + + ::new ((void *)this->end()) T(::std::move(this->back())); + // Push everything else over. + std::move_backward(I, this->end() - 1, this->end()); + this->set_size(this->size() + 1); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + static_assert(!TakesParamByValue || std::is_same::value, + "ArgType must be 'T' when taking by value!"); + if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end())) + ++EltPtr; + + *I = ::std::forward(*EltPtr); + return I; + } + + public: + iterator insert(iterator I, T &&Elt) { + return insert_one_impl(I, this->forward_value_param(std::move(Elt))); + } + + iterator insert(iterator I, const T &Elt) { + return insert_one_impl(I, this->forward_value_param(Elt)); + } + + iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) { + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + if (I == this->end()) { // Important special case for empty vector. + append(NumToInsert, Elt); + return this->begin() + InsertElt; + } + + assert(this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Ensure there is enough space, and get the (maybe updated) address of + // Elt. + const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert); + + // Uninvalidate the iterator. + I = this->begin() + InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end() - I) >= NumToInsert) { + T *OldEnd = this->end(); + append(std::move_iterator(this->end() - NumToInsert), + std::move_iterator(this->end())); + + // Copy the existing elements that get replaced. + std::move_backward(I, OldEnd - NumToInsert, OldEnd); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) + EltPtr += NumToInsert; + + std::fill_n(I, NumToInsert, *EltPtr); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Move over the elements that we're about to overwrite. + T *OldEnd = this->end(); + this->set_size(this->size() + NumToInsert); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) + EltPtr += NumToInsert; + + // Replace the overwritten part. + std::fill_n(I, NumOverwritten, *EltPtr); + + // Insert the non-overwritten middle part. + std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr); + return I; + } + + template ::iterator_category, + std::input_iterator_tag>::value>> + iterator insert(iterator I, ItTy From, ItTy To) { + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + if (I == this->end()) { // Important special case for empty vector. + append(From, To); + return this->begin() + InsertElt; + } + + assert(this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Check that the reserve that follows doesn't invalidate the iterators. + this->assertSafeToAddRange(From, To); + + size_t NumToInsert = std::distance(From, To); + + // Ensure there is enough space. + reserve(this->size() + NumToInsert); + + // Uninvalidate the iterator. + I = this->begin() + InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end() - I) >= NumToInsert) { + T *OldEnd = this->end(); + append(std::move_iterator(this->end() - NumToInsert), + std::move_iterator(this->end())); + + // Copy the existing elements that get replaced. + std::move_backward(I, OldEnd - NumToInsert, OldEnd); + + std::copy(From, To, I); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Move over the elements that we're about to overwrite. + T *OldEnd = this->end(); + this->set_size(this->size() + NumToInsert); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); + + // Replace the overwritten part. + for (T *J = I; NumOverwritten > 0; --NumOverwritten) { + *J = *From; + ++J; + ++From; + } + + // Insert the non-overwritten middle part. + this->uninitialized_copy(From, To, OldEnd); + return I; + } + + void insert(iterator I, std::initializer_list IL) { + insert(I, IL.begin(), IL.end()); + } + + template + reference emplace_back(ArgTypes &&...Args) { + if (this->size() >= this->capacity()) + return this->growAndEmplaceBack(std::forward(Args)...); + + ::new ((void *)this->end()) T(std::forward(Args)...); + this->set_size(this->size() + 1); + return this->back(); + } + + small_vector_impl &operator=(const small_vector_impl &RHS); + + small_vector_impl &operator=(small_vector_impl &&RHS); + + bool operator==(const small_vector_impl &RHS) const { + if (this->size() != RHS.size()) return false; + return std::equal(this->begin(), this->end(), RHS.begin()); + } + bool operator!=(const small_vector_impl &RHS) const { + return !(*this == RHS); + } + + bool operator<(const small_vector_impl &RHS) const { + return std::lexicographical_compare( + this->begin(), this->end(), RHS.begin(), RHS.end()); + } +}; + +template +void small_vector_impl::swap(small_vector_impl &RHS) { + if (this == &RHS) return; + + // We can only avoid copying elements if neither vector is small. + if (!this->isSmall() && !RHS.isSmall()) { + std::swap(this->BeginX, RHS.BeginX); + std::swap(this->Size, RHS.Size); + std::swap(this->Capacity, RHS.Capacity); + return; + } + this->reserve(RHS.size()); + RHS.reserve(this->size()); + + // Swap the shared elements. + size_t NumShared = this->size(); + if (NumShared > RHS.size()) NumShared = RHS.size(); + for (size_type i = 0; i != NumShared; ++i) std::swap((*this)[i], RHS[i]); + + // Copy over the extra elts. + if (this->size() > RHS.size()) { + size_t EltDiff = this->size() - RHS.size(); + this->uninitialized_copy(this->begin() + NumShared, this->end(), RHS.end()); + RHS.set_size(RHS.size() + EltDiff); + this->destroy_range(this->begin() + NumShared, this->end()); + this->set_size(NumShared); + } else if (RHS.size() > this->size()) { + size_t EltDiff = RHS.size() - this->size(); + this->uninitialized_copy(RHS.begin() + NumShared, RHS.end(), this->end()); + this->set_size(this->size() + EltDiff); + this->destroy_range(RHS.begin() + NumShared, RHS.end()); + RHS.set_size(NumShared); + } +} + +template +small_vector_impl &small_vector_impl::operator=( + const small_vector_impl &RHS) { + // Avoid self-assignment. + if (this == &RHS) return *this; + + // If we already have sufficient space, assign the common elements, then + // destroy any excess. + size_t RHSSize = RHS.size(); + size_t CurSize = this->size(); + if (CurSize >= RHSSize) { + // Assign common elements. + iterator NewEnd; + if (RHSSize) + NewEnd = std::copy(RHS.begin(), RHS.begin() + RHSSize, this->begin()); + else + NewEnd = this->begin(); + + // Destroy excess elements. + this->destroy_range(NewEnd, this->end()); + + // Trim. + this->set_size(RHSSize); + return *this; + } + + // If we have to grow to have enough elements, destroy the current elements. + // This allows us to avoid copying them during the grow. + // FIXME: don't do this if they're efficiently moveable. + if (this->capacity() < RHSSize) { + // Destroy current elements. + this->clear(); + CurSize = 0; + this->grow(RHSSize); + } else if (CurSize) { + // Otherwise, use assignment for the already-constructed elements. + std::copy(RHS.begin(), RHS.begin() + CurSize, this->begin()); + } + + // Copy construct the new elements in place. + this->uninitialized_copy( + RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); + + // Set end. + this->set_size(RHSSize); + return *this; +} + +template +small_vector_impl &small_vector_impl::operator=( + small_vector_impl &&RHS) { + // Avoid self-assignment. + if (this == &RHS) return *this; + + // If the RHS isn't small, clear this vector and then steal its buffer. + if (!RHS.isSmall()) { + this->destroy_range(this->begin(), this->end()); + if (!this->isSmall()) free(this->begin()); + this->BeginX = RHS.BeginX; + this->Size = RHS.Size; + this->Capacity = RHS.Capacity; + RHS.resetToSmall(); + return *this; + } + + // If we already have sufficient space, assign the common elements, then + // destroy any excess. + size_t RHSSize = RHS.size(); + size_t CurSize = this->size(); + if (CurSize >= RHSSize) { + // Assign common elements. + iterator NewEnd = this->begin(); + if (RHSSize) NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd); + + // Destroy excess elements and trim the bounds. + this->destroy_range(NewEnd, this->end()); + this->set_size(RHSSize); + + // Clear the RHS. + RHS.clear(); + + return *this; + } + + // If we have to grow to have enough elements, destroy the current elements. + // This allows us to avoid copying them during the grow. + // FIXME: this may not actually make any sense if we can efficiently move + // elements. + if (this->capacity() < RHSSize) { + // Destroy current elements. + this->clear(); + CurSize = 0; + this->grow(RHSSize); + } else if (CurSize) { + // Otherwise, use assignment for the already-constructed elements. + std::move(RHS.begin(), RHS.begin() + CurSize, this->begin()); + } + + // Move-construct the new elements in place. + this->uninitialized_move( + RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); + + // Set end. + this->set_size(RHSSize); + + RHS.clear(); + return *this; +} + +/// Storage for the small_vector elements. This is specialized for the N=0 case +/// to avoid allocating unnecessary storage. +template +struct small_vector_storage { + alignas(T) char InlineElts[N * sizeof(T)]; +}; + +/// We need the storage to be properly aligned even for small-size of 0 so that +/// the pointer math in \a small_vector_template_common::getFirstEl() is +/// well-defined. +template +struct alignas(T) small_vector_storage {}; + +/// Forward declaration of small_vector so that +/// calculateSmallVectorDefaultInlinedElements can reference +/// `sizeof(small_vector)`. +template +class small_vector; + +/// Helper class for calculating the default number of inline elements for +/// `small_vector`. +/// +/// This should be migrated to a constexpr function when our minimum +/// compiler support is enough for multi-statement constexpr functions. +template +struct CalculateSmallVectorDefaultInlinedElements { + // Parameter controlling the default number of inlined elements + // for `small_vector`. + // + // The default number of inlined elements ensures that + // 1. There is at least one inlined element. + // 2. `sizeof(small_vector) <= kPreferredSmallVectorSizeof` unless + // it contradicts 1. + static constexpr size_t kPreferredSmallVectorSizeof = 64; + + // static_assert that sizeof(T) is not "too big". + // + // Because our policy guarantees at least one inlined element, it is possible + // for an arbitrarily large inlined element to allocate an arbitrarily large + // amount of inline storage. We generally consider it an antipattern for a + // small_vector to allocate an excessive amount of inline storage, so we want + // to call attention to these cases and make sure that users are making an + // intentional decision if they request a lot of inline storage. + // + // We want this assertion to trigger in pathological cases, but otherwise + // not be too easy to hit. To accomplish that, the cutoff is actually somewhat + // larger than kPreferredSmallVectorSizeof (otherwise, + // `small_vector>` would be one easy way to trip it, and that + // pattern seems useful in practice). + // + // One wrinkle is that this assertion is in theory non-portable, since + // sizeof(T) is in general platform-dependent. However, we don't expect this + // to be much of an issue, because most LLVM development happens on 64-bit + // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for + // 32-bit hosts, dodging the issue. The reverse situation, where development + // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a + // 64-bit host, is expected to be very rare. + static_assert( + sizeof(T) <= 256, + "You are trying to use a default number of inlined elements for " + "`small_vector` but `sizeof(T)` is really big! Please use an " + "explicit number of inlined elements with `small_vector` to make " + "sure you really want that much inline storage."); + + // Discount the size of the header itself when calculating the maximum inline + // bytes. + static constexpr size_t PreferredInlineBytes = + kPreferredSmallVectorSizeof - sizeof(small_vector); + static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T); + static constexpr size_t value = + NumElementsThatFit == 0 ? 1 : NumElementsThatFit; +}; + +/// This is a 'vector' (really, a variable-sized array), optimized +/// for the case when the array is small. It contains some number of elements +/// in-place, which allows it to avoid heap allocation when the actual number of +/// elements is below that threshold. This allows normal "small" cases to be +/// fast without losing generality for large inputs. +/// +/// \note +/// In the absence of a well-motivated choice for the number of inlined +/// elements \p N, it is recommended to use \c small_vector (that is, +/// omitting the \p N). This will choose a default number of inlined elements +/// reasonable for allocation on the stack (for example, trying to keep \c +/// sizeof(small_vector) around 64 bytes). +/// +/// \warning This does not attempt to be exception safe. +/// +/// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h +template ::value> +class small_vector : public small_vector_impl, small_vector_storage { + public: + small_vector() : small_vector_impl(N) {} + + ~small_vector() { + // Destroy the constructed elements in the vector. + this->destroy_range(this->begin(), this->end()); + } + + explicit small_vector(size_t Size, const T &Value = T()) + : small_vector_impl(N) { + this->assign(Size, Value); + } + + template ::iterator_category, + std::input_iterator_tag>::value>> + small_vector(ItTy S, ItTy E) : small_vector_impl(N) { + this->append(S, E); + } + + template + explicit small_vector(const iterator_range &R) + : small_vector_impl(N) { + this->append(R.begin(), R.end()); + } + + small_vector(std::initializer_list IL) : small_vector_impl(N) { + this->assign(IL); + } + + small_vector(const small_vector &RHS) : small_vector_impl(N) { + if (!RHS.empty()) small_vector_impl::operator=(RHS); + } + + small_vector &operator=(const small_vector &RHS) { + small_vector_impl::operator=(RHS); + return *this; + } + + small_vector(small_vector &&RHS) : small_vector_impl(N) { + if (!RHS.empty()) small_vector_impl::operator=(::std::move(RHS)); + } + + small_vector(small_vector_impl &&RHS) : small_vector_impl(N) { + if (!RHS.empty()) small_vector_impl::operator=(::std::move(RHS)); + } + + small_vector &operator=(small_vector &&RHS) { + small_vector_impl::operator=(::std::move(RHS)); + return *this; + } + + small_vector &operator=(small_vector_impl &&RHS) { + small_vector_impl::operator=(::std::move(RHS)); + return *this; + } + + small_vector &operator=(std::initializer_list IL) { + this->assign(IL); + return *this; + } +}; + +template +inline size_t capacity_in_bytes(const small_vector &X) { + return X.capacity_in_bytes(); +} + +/// Given a range of type R, iterate the entire range and return a +/// small_vector with elements of the vector. This is useful, for example, +/// when you want to iterate a range and then sort the results. +template +small_vector()))>::type>::type, + Size> +to_vector(R &&Range) { + return {std::begin(Range), std::end(Range)}; +} + +inline void *safe_malloc(size_t Sz) { + void *Result = std::malloc(Sz); + if (Result == nullptr) { + // It is implementation-defined whether allocation occurs if the space + // requested is zero (ISO/IEC 9899:2018 7.22.3). Retry, requesting + // non-zero, if the space requested was zero. + if (Sz == 0) return safe_malloc(1); + throw std::bad_alloc(); + } + return Result; +} + +inline void *safe_calloc(size_t Count, size_t Sz) { + void *Result = std::calloc(Count, Sz); + if (Result == nullptr) { + // It is implementation-defined whether allocation occurs if the space + // requested is zero (ISO/IEC 9899:2018 7.22.3). Retry, requesting + // non-zero, if the space requested was zero. + if (Count == 0 || Sz == 0) return safe_malloc(1); + throw std::bad_alloc(); + } + return Result; +} + +inline void *safe_realloc(void *Ptr, size_t Sz) { + void *Result = std::realloc(Ptr, Sz); + if (Result == nullptr) { + // It is implementation-defined whether allocation occurs if the space + // requested is zero (ISO/IEC 9899:2018 7.22.3). Retry, requesting + // non-zero, if the space requested was zero. + if (Sz == 0) return safe_malloc(1); + throw std::bad_alloc(); + } + return Result; +} + +// Check that no bytes are wasted and everything is well-aligned. +namespace { +struct Struct16B { + alignas(16) void *X; +}; +struct Struct32B { + alignas(32) void *X; +}; +} // namespace +static_assert(sizeof(small_vector) == + sizeof(unsigned) * 2 + sizeof(void *), + "wasted space in small_vector size 0"); +static_assert(alignof(small_vector) >= alignof(Struct16B), + "wrong alignment for 16-byte aligned T"); +static_assert(alignof(small_vector) >= alignof(Struct32B), + "wrong alignment for 32-byte aligned T"); +static_assert(sizeof(small_vector) >= alignof(Struct16B), + "missing padding for 16-byte aligned T"); +static_assert(sizeof(small_vector) >= alignof(Struct32B), + "missing padding for 32-byte aligned T"); +static_assert(sizeof(small_vector) == + sizeof(unsigned) * 2 + sizeof(void *) * 2, + "wasted space in small_vector size 1"); + +static_assert(sizeof(small_vector) == + sizeof(void *) * 2 + sizeof(void *), + "1 byte elements have word-sized type for size and capacity"); + +/// Report that MinSize doesn't fit into this vector's size type. Throws +/// std::length_error or calls report_fatal_error. +static void report_size_overflow(size_t MinSize, size_t MaxSize); +static void report_size_overflow(size_t MinSize, size_t MaxSize) { + std::string Reason = "small_vector unable to grow. Requested capacity (" + + std::to_string(MinSize) + + ") is larger than maximum value for size type (" + + std::to_string(MaxSize) + ")"; + throw std::length_error(Reason); +} + +/// Report that this vector is already at maximum capacity. Throws +/// std::length_error or calls report_fatal_error. +static void report_at_maximum_capacity(size_t MaxSize); +static void report_at_maximum_capacity(size_t MaxSize) { + std::string Reason = + "small_vector capacity unable to grow. Already at maximum size " + + std::to_string(MaxSize); + throw std::length_error(Reason); +} + +// Note: Moving this function into the header may cause performance regression. +template +static size_t getNewCapacity(size_t MinSize, size_t TSize, size_t OldCapacity) { + constexpr size_t MaxSize = (std::numeric_limits::max)(); + + // Ensure we can fit the new capacity. + // This is only going to be applicable when the capacity is 32 bit. + if (MinSize > MaxSize) report_size_overflow(MinSize, MaxSize); + + // Ensure we can meet the guarantee of space for at least one more element. + // The above check alone will not catch the case where grow is called with a + // default MinSize of 0, but the current capacity cannot be increased. + // This is only going to be applicable when the capacity is 32 bit. + if (OldCapacity == MaxSize) report_at_maximum_capacity(MaxSize); + + // In theory 2*capacity can overflow if the capacity is 64 bit, but the + // original capacity would never be large enough for this to be a problem. + size_t NewCapacity = 2 * OldCapacity + 1; // Always grow. + return (std::min)((std::max)(NewCapacity, MinSize), MaxSize); +} + +// Note: Moving this function into the header may cause performance regression. +template +void *small_vector_base::mallocForGrow(size_t MinSize, + size_t TSize, + size_t &NewCapacity) { + NewCapacity = getNewCapacity(MinSize, TSize, this->capacity()); + return safe_malloc(NewCapacity * TSize); +} + +// Note: Moving this function into the header may cause performance regression. +template +void small_vector_base::grow_pod(void *FirstEl, + size_t MinSize, + size_t TSize) { + size_t NewCapacity = getNewCapacity(MinSize, TSize, this->capacity()); + void *NewElts; + if (BeginX == FirstEl) { + NewElts = safe_malloc(NewCapacity * TSize); + + // Copy the elements over. No need to run dtors on PODs. + memcpy(NewElts, this->BeginX, size() * TSize); + } else { + // If this wasn't grown from the inline copy, grow the allocated space. + NewElts = safe_realloc(this->BeginX, NewCapacity * TSize); + } + + this->BeginX = NewElts; + this->Capacity = NewCapacity; +} + +template class paddle::small_vector_base; + +// Disable the uint64_t instantiation for 32-bit builds. +// Both uint32_t and uint64_t instantiations are needed for 64-bit builds. +// This instantiation will never be used in 32-bit builds, and will cause +// warnings when sizeof(Size_T) > sizeof(size_t). +#if SIZE_MAX > UINT32_MAX +template class paddle::small_vector_base; + +// Assertions to ensure this #if stays in sync with SmallVectorSizeType. +static_assert(sizeof(SmallVectorSizeType) == sizeof(uint64_t), + "Expected small_vector_base variant to be in use."); +#else +static_assert(sizeof(SmallVectorSizeType) == sizeof(uint32_t), + "Expected small_vector_base variant to be in use."); +#endif + +} // namespace paddle + +namespace std { + +/// Implement std::swap in terms of small_vector swap. +template +inline void swap(paddle::small_vector_impl &LHS, + paddle::small_vector_impl &RHS) { + LHS.swap(RHS); +} + +/// Implement std::swap in terms of small_vector swap. +template +inline void swap(paddle::small_vector &LHS, + paddle::small_vector &RHS) { + LHS.swap(RHS); +} + +} // namespace std diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/piece.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/piece.h new file mode 100644 index 0000000000000000000000000000000000000000..8dda484eaac4d62b758e57ac5e81bfe68a5c60d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/piece.h @@ -0,0 +1,105 @@ +// Copyright (c) 2018 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. + +#pragma once + +#include +#include + +namespace paddle { +namespace string { + +// Piece points into a std::string object but doesn't own the +// string. It is for efficient access to strings. Like Go's string +// type. Not that Piece doesn't mutate the underlying string, +// so it is thread-safe given that the underlying string doesn't +// change. Because Piece contains a little data members, and +// its syntax is simple as it doesn't own/manage the string, it is +// cheap to construct Pieces and pass them around. +class Piece { + public: + static const size_t npos = static_cast(-1); + + // We provide non-explicit singleton constructors so users can + // pass in a "const char*" or a "string" wherever a "Piece" + // is expected. These constructors ensure that if data_ is NULL, + // size_ is 0. + Piece(); + Piece(const char* d, size_t n); + Piece(const char* d); // NOLINT: accept C string into Piece. + Piece(const std::string& s); // NOLINT: accept C++ string into Piece. + + const char* data() const { return data_; } + size_t len() const { return size_; } + + char operator[](size_t n) const; + + // Piece doesn't own the string, so both iterator and const + // iterator are const char* indeed. + typedef const char* const_iterator; + typedef const char* iterator; + iterator begin() const { return data_; } + iterator end() const { return data_ + size_; } + + // Return a string that contains the copy of the referenced data. + std::string ToString() const { return std::string(data_, size_); } + + private: + const char* data_; + size_t size_; + + // Intentionally copyable +}; + +int Compare(Piece a, Piece b); + +bool operator==(Piece x, Piece y); +bool operator!=(Piece x, Piece y); +bool operator<(Piece x, Piece y); +bool operator>(Piece x, Piece y); +bool operator<=(Piece x, Piece y); +bool operator>=(Piece x, Piece y); + +bool HasPrefix(Piece s, Piece prefix); +bool HasSuffix(Piece s, Piece suffix); + +Piece SkipPrefix(Piece s, size_t n); +Piece SkipSuffix(Piece s, size_t n); + +// Skip the prefix (or suffix) if it matches with the string. +Piece TrimPrefix(Piece s, Piece prefix); +Piece TrimSuffix(Piece s, Piece suffix); + +// Returns if s contains sub. Any s except for empty s contains an +// empty sub. +bool Contains(Piece s, Piece sub); + +// Return the first occurrence of sub in s, or npos. If both s and +// sub is empty, it returns npos; otherwise, if only sub is empty, it +// returns 0. +size_t Index(Piece s, Piece sub); + +// Return the first occurrence of c in s[pos:end], or npos. +size_t Find(Piece s, char c, size_t pos); + +// Search range is [0..pos] inclusive. If pos == npos, search everything. +size_t RFind(Piece s, char c, size_t pos); + +Piece SubStr(Piece s, size_t pos, size_t n); + +// allow Piece to be logged +std::ostream& operator<<(std::ostream& o, Piece piece); + +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/pretty_log.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/pretty_log.h new file mode 100644 index 0000000000000000000000000000000000000000..9de7ce24abd72d96708d970afe1ee41d476e8c27 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/pretty_log.h @@ -0,0 +1,90 @@ +// Copyright (c) 2018 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. +#pragma once + +#include +#include +#include +#include + +#include "gflags/gflags.h" +#include "paddle/utils/string/printf.h" + +DECLARE_bool(color); + +namespace paddle { + +namespace string { + +inline std::string black() { return FLAGS_color ? "\e[30m" : ""; } +inline std::string red() { return FLAGS_color ? "\e[31m" : ""; } +inline std::string b_red() { return FLAGS_color ? "\e[41m" : ""; } +inline std::string green() { return FLAGS_color ? "\e[32m" : ""; } +inline std::string yellow() { return FLAGS_color ? "\e[33m" : ""; } +inline std::string blue() { return FLAGS_color ? "\e[34m" : ""; } +inline std::string purple() { return FLAGS_color ? "\e[35m" : ""; } +inline std::string cyan() { return FLAGS_color ? "\e[36m" : ""; } +inline std::string light_gray() { return FLAGS_color ? "\e[37m" : ""; } +inline std::string white() { return FLAGS_color ? "\e[37m" : ""; } +inline std::string light_red() { return FLAGS_color ? "\e[91m" : ""; } +inline std::string dim() { return FLAGS_color ? "\e[2m" : ""; } +inline std::string bold() { return FLAGS_color ? "\e[1m" : ""; } +inline std::string underline() { return FLAGS_color ? "\e[4m" : ""; } +inline std::string blink() { return FLAGS_color ? "\e[5m" : ""; } +inline std::string reset() { return FLAGS_color ? "\e[0m" : ""; } + +using TextBlock = std::pair; + +struct Style { + static std::string info() { return black(); } + static std::string warn() { return b_red(); } + static std::string suc() { return green(); } + static std::string H1() { return bold() + purple(); } + static std::string H2() { return green(); } + static std::string H3() { return green(); } + static std::string detail() { return light_gray(); } +}; + +template +static void PrettyLogEndl(const std::string &style, + const char *fmt, + const Args &...args) { + std::cerr << style << Sprintf(fmt, args...) << reset() << std::endl; +} +template +static void PrettyLog(const std::string &style, + const char *fmt, + const Args &...args) { + std::cerr << style << Sprintf(fmt, args...) << reset(); +} + +template +static void PrettyLogInfo(const char *fmt, const Args &...args) { + PrettyLogEndl(Style::info(), fmt, args...); +} +template +static void PrettyLogDetail(const char *fmt, const Args &...args) { + PrettyLogEndl(Style::detail(), fmt, args...); +} +template +static void PrettyLogH1(const char *fmt, const Args &...args) { + PrettyLogEndl(Style::H1(), fmt, args...); +} +template +static void PrettyLogH2(const char *fmt, const Args &...args) { + PrettyLogEndl(Style::H2(), fmt, args...); +} + +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/printf.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/printf.h new file mode 100644 index 0000000000000000000000000000000000000000..f4576c6bc4aa543a25604638c2047eeaeb179a74 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/printf.h @@ -0,0 +1,124 @@ +// Copyright (c) 2022 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. + +// Compared with std::stringstream, there are primary purpose of +// string::Printf: +// +// 1. Type-safe printing, with why and how explained in +// http://www.drdobbs.com/stringprintf-a-typesafe-printf-family-fo/184401999. +// Implementation includes +// +// https://github.com/c42f/tinyformat +// boost::format +// std::stringstream +// +// std::stringstream is not convenient enough in many cases. For example: +// +// std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; +// +// boost::format is the most convenient one. We can have +// +// std::cout << format("%2% %1%") % 36 % 77; +// +// or +// +// format fmter("%2% %1%"); +// fmter % 36; fmter % 77; +// std::cout << fmter.c_str(); +// +// But the overloading of % might be overkilling and it would be +// more efficient if it can write to std::cout directly. +// +// tinyformat has an interface compatible with the C-printf style, +// and it can writes to a stream or returns a std::string: +// +// std::cout << tfm::printf( +// "%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); +// +// or +// +// tfm::format(std::cout, +// "%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); +// +// 2. High-performance -- most printed strings are not too long and +// doens't need dynamic memory allocation. Many StringPrintf +// implementations doesn't enforce type-safe, but are +// high-performance, including +// +// https://developers.google.com/optimization/reference/base/stringprintf/ +// https://github.com/adobe/chromium/blob/master/base/stringprintf.h +// https://github.com/google/protobuf/blob/master/src/google/protobuf/stubs/stringprintf.h +// +// According to +// https://github.com/c42f/tinyformat#compile-time-and-code-bloat, +// boost::format runs too slow and results in large executable binary +// files. So here we port tinyformat. + +#pragma once + +#include +#include +#include +#include + +#include "paddle/utils/string/tinyformat/tinyformat.h" // https://github.com/c42f/tinyformat + +namespace paddle { +namespace string { + +template +void Fprintf(std::ostream& out, const char* fmt, const Args&... args) { + tinyformat::vformat(out, fmt, tinyformat::makeFormatList(args...)); +} + +inline std::string Sprintf() { return ""; } + +template +std::string Sprintf(const Args&... args) { + std::ostringstream oss; + Fprintf(oss, "%s", args...); + return oss.str(); +} + +template +std::string Sprintf(const char* fmt, const Args&... args) { + std::ostringstream oss; + Fprintf(oss, fmt, args...); + return oss.str(); +} + +template +void Printf(const char* fmt, const Args&... args) { + Fprintf(std::cout, fmt, args...); +} + +inline std::string HumanReadableSize(double f_size) { + size_t i = 0; + double orig = f_size; + const std::vector units( + {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}); + while (f_size >= 1024) { + f_size /= 1024; + i++; + } + if (i >= units.size()) { + return Sprintf("%fB", orig); + } + return Sprintf("%f%s", f_size, units[i]); +} + +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/split.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/split.h new file mode 100644 index 0000000000000000000000000000000000000000..ccb96b8a9cb68f03acbca592a2149ba5001f34d2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/split.h @@ -0,0 +1,37 @@ +/* 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. */ + +#pragma once +#include +#include +#include + +namespace paddle { +namespace string { + +static inline std::vector Split(std::string const& original, + char separator) { + std::vector results; + std::string token; + std::istringstream is(original); + while (std::getline(is, token, separator)) { + if (!token.empty()) { + results.push_back(token); + } + } + return results; +} + +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/string_helper.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/string_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..b84c7fa75209df87b199055fcd479bf69047db8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/string_helper.h @@ -0,0 +1,357 @@ +// 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. + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace paddle { +namespace string { + +inline size_t count_spaces(const char* s) { + size_t count = 0; + + while (*s != 0 && isspace(*s++)) { + count++; + } + + return count; +} + +inline size_t count_nonspaces(const char* s) { + size_t count = 0; + + while (*s != 0 && !isspace(*s++)) { + count++; + } + + return count; +} + +template +void format_string_append(std::string& str, // NOLINT + const char* fmt, // NOLINT + ARGS&&... args) { + int len = snprintf(NULL, 0, fmt, args...); + assert(len == 0); + size_t oldlen = str.length(); + str.resize(oldlen + len + 1); + int new_len = + snprintf(&str[oldlen], (size_t)len + 1, fmt, args...); // NOLINT + (void)new_len; + assert(new_len == len); + str.resize(oldlen + len); +} + +template +void format_string_append(std::string& str, // NOLINT + const std::string& fmt, // NOLINT + ARGS&&... args) { + format_string_append(str, fmt.c_str(), args...); +} + +template +std::string format_string(const char* fmt, ARGS&&... args) { + std::string str; + format_string_append(str, fmt, args...); + return str; +} + +template +std::string format_string(const std::string& fmt, ARGS&&... args) { + return format_string(fmt.c_str(), args...); +} + +// remove leading and tailing spaces +std::string trim_spaces(const std::string& str); + +// erase all spaces in str +std::string erase_spaces(const std::string& str); + +inline int str_to_float(const char* str, float* v) { + const char* head = str; + char* cursor = NULL; + int index = 0; + while (*(head += count_spaces(head)) != 0) { + v[index++] = std::strtof(head, &cursor); + if (head == cursor) { + break; + } + head = cursor; + } + return index; +} + +inline float* str_to_float(std::string& str) { + return (float*)const_cast(str.c_str()); +} + +inline float* str_to_float(const char* str) { + return (float*)const_cast(str); +} + +// checks whether the test string is a suffix of the input string. +bool ends_with(std::string const& input, std::string const& test); + +// split string by delim +template +std::vector split_string(const std::string& str, const std::string& delim) { + size_t pre_pos = 0; + size_t pos = 0; + std::string tmp_str; + std::vector res_list; + res_list.clear(); + if (str.empty()) { + return res_list; + } + while ((pos = str.find(delim, pre_pos)) != std::string::npos) { + tmp_str.assign(str, pre_pos, pos - pre_pos); + res_list.push_back(tmp_str); + pre_pos = pos + 1; + } + tmp_str.assign(str, pre_pos, str.length() - pre_pos); + if (!tmp_str.empty()) { + res_list.push_back(tmp_str); + } + return res_list; +} + +// split string by spaces. Leading and tailing spaces are ignored. Consecutive +// spaces are treated as one delim. +template +std::vector split_string(const std::string& str) { + std::vector list; + const char* p; + int pre_pos = 0; + int pos = 0; + std::string tmp_str; + if (str.empty()) { + return list; + } + for (p = str.c_str(); *p != 0;) { + if (!isspace(*p)) { + pos = pre_pos; + p++; + + while (*p != 0 && !isspace(*p)) { + pos++; + p++; + } + tmp_str.assign(str, pre_pos, pos - pre_pos + 1); + list.push_back(tmp_str); + pre_pos = pos + 1; + } else { + pre_pos++; + p++; + } + } + return list; +} + +template +std::string join_strings(const Container& strs, char delim) { + std::string str; + + size_t i = 0; + for (auto& elem : strs) { + if (i > 0) { + str += delim; + } + + std::stringstream ss; + ss << elem; + str += ss.str(); + ++i; + } + + return str; +} + +template +std::string join_strings(const Container& strs, const std::string& delim) { + std::string str; + + size_t i = 0; + for (auto& elem : strs) { + if (i > 0) { + str += delim; + } + + std::stringstream ss; + ss << elem; + str += ss.str(); + ++i; + } + + return str; +} + +template +std::string join_strings(const Container& strs, + DelimT&& delim, + ConvertFunc&& func) { + std::stringstream ss; + size_t i = 0; + for (const auto& elem : strs) { + if (i > 0) { + ss << delim; + } + ss << func(elem); + ++i; + } + + return ss.str(); +} +struct str_ptr { + const char* ptr; + size_t len; + str_ptr(const char* p, size_t n) : ptr(p), len(n) {} + str_ptr(str_ptr& other) { + ptr = other.ptr; + len = other.len; + } + str_ptr(str_ptr&& other) { + ptr = other.ptr; + len = other.len; + } + size_t find_ptr(const char c) { + for (size_t i = 0; i < len; ++i) { + if (ptr[i] == c) { + return i; + } + } + return -1; + } + std::string to_string(void) { return std::string(ptr, len); } +}; + +struct str_ptr_stream { + char* ptr = NULL; + char* end = NULL; + str_ptr_stream() {} + str_ptr_stream(const str_ptr& p) { reset(p.ptr, p.len); } + void reset(const str_ptr& p) { reset(p.ptr, p.len); } + void reset(const char* p, size_t len) { + ptr = const_cast(p); + end = ptr + len; + } + char* cursor(void) { return ptr; } + char* finish(void) { return end; } + void set_cursor(char* p) { ptr = p; } + bool is_finish(void) { return (ptr == end); } + template + str_ptr_stream& operator>>(T& x) { + *this >> x; + return *this; + } +}; +inline str_ptr_stream& operator>>(str_ptr_stream& ar, float& c) { + char* next = NULL; + c = strtof(ar.cursor(), &next); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline str_ptr_stream& operator>>(str_ptr_stream& ar, double& c) { + char* next = NULL; + c = strtod(ar.cursor(), &next); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline str_ptr_stream& operator>>(str_ptr_stream& ar, int32_t& c) { + char* next = NULL; + c = strtol(ar.cursor(), &next, 10); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline str_ptr_stream& operator>>(str_ptr_stream& ar, uint32_t& c) { + char* next = NULL; + c = strtoul(ar.cursor(), &next, 10); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline str_ptr_stream& operator>>(str_ptr_stream& ar, uint64_t& c) { + char* next = NULL; + c = strtoul(ar.cursor(), &next, 10); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline str_ptr_stream& operator>>(str_ptr_stream& ar, int64_t& c) { + char* next = NULL; + c = strtoll(ar.cursor(), &next, 10); + ar.set_cursor(std::min(++next, ar.finish())); + return ar; +} +inline int split_string_ptr(const char* str, + size_t len, + char delim, + std::vector* values) { + if (len <= 0) { + return 0; + } + + int num = 0; + const char* p = str; + const char* end = str + len; + const char* last = str; + while (p < end) { + if (*p != delim) { + ++p; + continue; + } + values->emplace_back(last, (size_t)(p - last)); + ++num; + ++p; + // skip continue delim + while (*p == delim) { + ++p; + } + last = p; + } + if (p > last) { + values->emplace_back(last, (size_t)(p - last)); + ++num; + } + return num; +} + +// A helper class for reading lines from file. A line buffer is maintained. It +// doesn't need to know the maximum possible length of a line. + +class LineFileReader { + public: + LineFileReader() {} + LineFileReader(LineFileReader&&) = delete; + LineFileReader(const LineFileReader&) = delete; + ~LineFileReader() { ::free(_buffer); } + char* getline(FILE* f) { return this->getdelim(f, '\n'); } + char* getdelim(FILE* f, char delim); + char* get() { return _buffer; } + size_t length() { return _length; } + + private: + char* _buffer = NULL; + size_t _buf_size = 0; + size_t _length = 0; +}; +} // end namespace string +} // end namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/tinyformat/tinyformat.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/tinyformat/tinyformat.h new file mode 100644 index 0000000000000000000000000000000000000000..f9c55fe1835fd22c52f47e4347ea0aa610b97116 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/tinyformat/tinyformat.h @@ -0,0 +1,919 @@ +// Copyright (c) 2018 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. + +// tinyformat.h +// Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com] +// +// Boost Software License - Version 1.0 +// +// Permission is hereby granted, free of charge, to any person or organization +// obtaining a copy of the software and accompanying documentation covered by +// this license (the "Software") to use, reproduce, display, distribute, +// execute, and transmit the Software, and to prepare derivative works of the +// Software, and to permit third-parties to whom the Software is furnished to +// do so, all subject to the following: +// +// The copyright notices in the Software and this entire statement, including +// the above license grant, this restriction and the following disclaimer, +// must be included in all copies of the Software, in whole or in part, and +// all derivative works of the Software, unless such copies or derivative +// works are solely in the form of machine-executable object code generated by +// a source language processor. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +//------------------------------------------------------------------------------ +// Tinyformat: A minimal type safe printf replacement +// +// tinyformat.h is a type safe printf replacement library in a single C++ +// header file. Design goals include: +// +// * Type safety and extensibility for user defined types. +// * C99 printf() compatibility, to the extent possible using std::ostream +// * Simplicity and minimalism. A single header file to include and distribute +// with your projects. +// * Augment rather than replace the standard stream formatting mechanism +// * C++98 support, with optional C++11 niceties +// +// +// Main interface example usage +// ---------------------------- +// +// To print a date to std::cout: +// +// std::string weekday = "Wednesday"; +// const char* month = "July"; +// size_t day = 27; +// long hour = 14; +// int min = 44; +// +// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); +// +// The strange types here emphasize the type safety of the interface; it is +// possible to print a std::string using the "%s" conversion, and a +// size_t using the "%d" conversion. A similar result could be achieved +// using either of the tfm::format() functions. One prints on a user provided +// stream: +// +// tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); +// +// The other returns a std::string: +// +// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n", +// weekday, month, day, hour, min); +// std::cout << date; +// +// These are the three primary interface functions. There is also a +// convenience function printfln() which appends a newline to the usual result +// of printf() for super simple logging. +// +// +// User defined format functions +// ----------------------------- +// +// Simulating variadic templates in C++98 is pretty painful since it requires +// writing out the same function for each desired number of arguments. To make +// this bearable tinyformat comes with a set of macros which are used +// internally to generate the API, but which may also be used in user code. +// +// The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and +// TINYFORMAT_PASSARGS(n) will generate a list of n argument types, +// type/name pairs and argument names respectively when called with an integer +// n between 1 and 16. We can use these to define a macro which generates the +// desired user defined function with n arguments. To generate all 16 user +// defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an +// example, see the implementation of printf() at the end of the source file. +// +// Sometimes it's useful to be able to pass a list of format arguments through +// to a non-template function. The FormatList class is provided as a way to do +// this by storing the argument list in a type-opaque way. Continuing the +// example from above, we construct a FormatList using makeFormatList(): +// +// FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, +// min); +// +// The format list can now be passed into any non-template function and used +// via a call to the vformat() function: +// +// tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList); +// +// +// Additional API information +// -------------------------- +// +// Error handling: Define TINYFORMAT_ERROR to customize the error handling for +// format strings which are unsupported or have the wrong number of format +// specifiers (calls assert() by default). +// +// User defined types: Uses operator<< for user defined types by default. +// Overload formatValue() for more control. + +#pragma once + +#include +#include +#include +#include + +#include "paddle/utils/string/to_string.h" + +namespace paddle { +namespace string { +namespace tinyformat { + +#ifndef TINYFORMAT_ERROR +#define TINYFORMAT_ERROR(reason) assert(0 && reason) +#endif + +//------------------------------------------------------------------------------ +namespace detail { + +// Test whether type T1 is convertible to type T2 +template +struct is_convertible { + private: + // two types of different size + struct fail { + char dummy[2]; + }; + struct succeed { + char dummy; + }; + // Try to convert a T1 to a T2 by plugging into tryConvert + static fail tryConvert(...); + static succeed tryConvert(const T2 &); + static const T1 &makeT1(); + + public: + // Standard trick: the (...) version of tryConvert will be chosen from + // the overload set only if the version taking a T2 doesn't match. + // Then we compare the sizes of the return types to check which + // function matched. Very neat, in a disgusting kind of way :) + static const bool value = sizeof(tryConvert(makeT1())) == sizeof(succeed); +}; + +// Format the value by casting to type fmtT. This default implementation +// should never be called. +template ::value> +struct formatValueAsType { + static void invoke(std::ostream & /*out*/, const T & /*value*/) { assert(0); } +}; +// Specialized version for types that can actually be converted to fmtT, as +// indicated by the "convertible" template parameter. +template +struct formatValueAsType { + static void invoke(std::ostream &out, const T &value) { + out << static_cast(value); + } +}; + +// Convert an arbitrary type to integer. The version with convertible=false +// throws an error. +template ::value> +struct convertToInt { + static int invoke(const T & /*value*/) { + TINYFORMAT_ERROR( + "tinyformat: Cannot convert from argument type to " + "integer for use as variable width or precision"); + return 0; + } +}; +// Specialization for convertToInt when conversion is possible +template +struct convertToInt { + static int invoke(const T &value) { return static_cast(value); } +}; + +// Format at most ntrunc characters to the given stream. +template +inline void formatTruncated(std::ostream &out, const T &value, int ntrunc) { + std::ostringstream tmp; + tmp << value; + std::string result = tmp.str(); + out.write(result.c_str(), + (std::min)(ntrunc, static_cast(result.size()))); +} +#define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type) \ + inline void formatTruncated(std::ostream &out, type *value, int ntrunc) { \ + std::streamsize len = 0; \ + while (len < ntrunc && value[len] != 0) ++len; \ + out.write(value, len); \ + } +// Overload for const char* and char*. Could overload for signed & unsigned +// char too, but these are technically unneeded for printf compatibility. +TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char) +TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char) +#undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR + +} // namespace detail + +//------------------------------------------------------------------------------ +// Variable formatting functions. May be overridden for user-defined types if +// desired. + +/// Format a value into a stream, delegating to operator<< by default. +/// +/// Users may override this for their own types. When this function is called, +/// the stream flags will have been modified according to the format string. +/// The format specification is provided in the range [fmtBegin, fmtEnd). For +/// truncating conversions, ntrunc is set to the desired maximum number of +/// characters, for example "%.7s" calls formatValue with ntrunc = 7. +/// +/// By default, formatValue() uses the usual stream insertion operator +/// operator<< to format the type T, with special cases for the %c and %p +/// conversions. +template +inline void formatValue(std::ostream &out, + const char * /*fmtBegin*/, + const char *fmtEnd, + int ntrunc, + const T &value) { + // The mess here is to support the %c and %p conversions: if these + // conversions are active we try to convert the type to a char or const + // void* respectively and format that instead of the value itself. For the + // %p conversion it's important to avoid dereferencing the pointer, which + // could otherwise lead to a crash when printing a dangling (const char*). + const bool canConvertToChar = detail::is_convertible::value; + const bool canConvertToVoidPtr = + detail::is_convertible::value; + if (canConvertToChar && *(fmtEnd - 1) == 'c') { + detail::formatValueAsType::invoke(out, value); + } else if (canConvertToVoidPtr && *(fmtEnd - 1) == 'p') { + detail::formatValueAsType::invoke(out, value); + } else if (ntrunc >= 0) { + // Take care not to overread C strings in truncating conversions like + // "%.4s" where at most 4 characters may be read. + detail::formatTruncated(out, value, ntrunc); + } else { + out << value; + } +} + +// Overloaded version for char types to support printing as an integer +#define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \ + inline void formatValue(std::ostream &out, \ + const char * /*fmtBegin*/, \ + const char *fmtEnd, \ + int /**/, \ + charType value) { \ + switch (*(fmtEnd - 1)) { \ + case 'u': \ + case 'd': \ + case 'i': \ + case 'o': \ + case 'X': \ + case 'x': \ + out << static_cast(value); \ + break; \ + default: \ + out << value; \ + break; \ + } \ + } +// per 3.9.1: char, signed char and unsigned char are all distinct types +TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char) +TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char) +TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char) +#undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR + +//------------------------------------------------------------------------------ +// Tools for emulating variadic templates in C++98. The basic idea here is +// stolen from the boost preprocessor metaprogramming library and cut down to +// be just general enough for what we need. + +#define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_##n +#define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_##n +#define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_##n +#define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_##n + +// To keep it as transparent as possible, the macros below have been generated +// using python via the excellent cog.py code generation script. This avoids +// the need for a bunch of complex (but more general) preprocessor tricks as +// used in boost.preprocessor. +// +// To rerun the code generation in place, use `cog.py -r tinyformat.h` +// (see http://nedbatchelder.com/code/cog). Alternatively you can just create +// extra versions by hand. + +/*[[[cog +maxParams = 16 + +def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1): + for j in range(startInd,maxParams+1): + list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) + cog.outl(lineTemplate % {'j':j, 'list':list}) + +makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s', + 'class T%(i)d') + +cog.outl() +makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s', + 'const T%(i)d& v%(i)d') + +cog.outl() +makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d') + +cog.outl() +cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1') +makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s', + 'v%(i)d', startInd = 2) + +cog.outl() +cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' + + ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)])) +]]]*/ +#define TINYFORMAT_ARGTYPES_1 class T1 +#define TINYFORMAT_ARGTYPES_2 class T1, class T2 +#define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3 +#define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4 +#define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5 +#define TINYFORMAT_ARGTYPES_6 \ + class T1, class T2, class T3, class T4, class T5, class T6 +#define TINYFORMAT_ARGTYPES_7 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7 +#define TINYFORMAT_ARGTYPES_8 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8 +#define TINYFORMAT_ARGTYPES_9 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9 +#define TINYFORMAT_ARGTYPES_10 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10 +#define TINYFORMAT_ARGTYPES_11 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11 +#define TINYFORMAT_ARGTYPES_12 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11, class T12 +#define TINYFORMAT_ARGTYPES_13 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11, class T12, class T13 +#define TINYFORMAT_ARGTYPES_14 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11, class T12, class T13, \ + class T14 +#define TINYFORMAT_ARGTYPES_15 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11, class T12, class T13, \ + class T14, class T15 +#define TINYFORMAT_ARGTYPES_16 \ + class T1, class T2, class T3, class T4, class T5, class T6, class T7, \ + class T8, class T9, class T10, class T11, class T12, class T13, \ + class T14, class T15, class T16 + +#define TINYFORMAT_VARARGS_1 const T1 &v1 +#define TINYFORMAT_VARARGS_2 const T1 &v1, const T2 &v2 +#define TINYFORMAT_VARARGS_3 const T1 &v1, const T2 &v2, const T3 &v3 +#define TINYFORMAT_VARARGS_4 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4 +#define TINYFORMAT_VARARGS_5 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5 +#define TINYFORMAT_VARARGS_6 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6 +#define TINYFORMAT_VARARGS_7 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7 +#define TINYFORMAT_VARARGS_8 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8 +#define TINYFORMAT_VARARGS_9 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9 +#define TINYFORMAT_VARARGS_10 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10 +#define TINYFORMAT_VARARGS_11 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11 +#define TINYFORMAT_VARARGS_12 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11, const T12 &v12 +#define TINYFORMAT_VARARGS_13 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11, const T12 &v12, const T13 &v13 +#define TINYFORMAT_VARARGS_14 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11, const T12 &v12, const T13 &v13, const T14 &v14 +#define TINYFORMAT_VARARGS_15 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11, const T12 &v12, const T13 &v13, const T14 &v14, \ + const T15 &v15 +#define TINYFORMAT_VARARGS_16 \ + const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4, const T5 &v5, \ + const T6 &v6, const T7 &v7, const T8 &v8, const T9 &v9, const T10 &v10, \ + const T11 &v11, const T12 &v12, const T13 &v13, const T14 &v14, \ + const T15 &v15, const T16 &v16 + +#define TINYFORMAT_PASSARGS_1 v1 +#define TINYFORMAT_PASSARGS_2 v1, v2 +#define TINYFORMAT_PASSARGS_3 v1, v2, v3 +#define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4 +#define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5 +#define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6 +#define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7 +#define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8 +#define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9 +#define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 +#define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 +#define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 +#define TINYFORMAT_PASSARGS_13 \ + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 +#define TINYFORMAT_PASSARGS_14 \ + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 +#define TINYFORMAT_PASSARGS_15 \ + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 +#define TINYFORMAT_PASSARGS_16 \ + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 + +#define TINYFORMAT_PASSARGS_TAIL_1 +#define TINYFORMAT_PASSARGS_TAIL_2 , v2 +#define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3 +#define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4 +#define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5 +#define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6 +#define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7 +#define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8 +#define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9 +#define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10 +#define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 +#define TINYFORMAT_PASSARGS_TAIL_12 \ + , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 +#define TINYFORMAT_PASSARGS_TAIL_13 \ + , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 +#define TINYFORMAT_PASSARGS_TAIL_14 \ + , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 +#define TINYFORMAT_PASSARGS_TAIL_15 \ + , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 +#define TINYFORMAT_PASSARGS_TAIL_16 \ + , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 + +#define TINYFORMAT_FOREACH_ARGNUM(m) \ + m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) \ + m(15) m(16) +// [[[end]]] + +namespace detail { + +// Type-opaque holder for an argument to format(), with associated actions on +// the type held as explicit function pointers. This allows FormatArg's for +// each argument to be allocated as a homogenous array inside FormatList +// whereas a naive implementation based on inheritance does not. +class FormatArg { + public: + FormatArg() {} // NOLINT + + template + FormatArg(const T &value) // NOLINT + : m_value(static_cast(&value)), + m_formatImpl(&formatImpl), + m_toIntImpl(&toIntImpl) {} + + void format(std::ostream &out, + const char *fmtBegin, + const char *fmtEnd, + int ntrunc) const { + m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value); + } + + int toInt() const { return m_toIntImpl(m_value); } + + private: + template + static void formatImpl(std::ostream &out, + const char *fmtBegin, + const char *fmtEnd, + int ntrunc, + const void *value) { + formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast(value)); + } + + template + static int toIntImpl(const void *value) { + return convertToInt::invoke(*static_cast(value)); + } + + const void *m_value; + void (*m_formatImpl)(std::ostream &out, + const char *fmtBegin, + const char *fmtEnd, + int ntrunc, + const void *value); + int (*m_toIntImpl)(const void *value); +}; + +// Parse and return an integer from the string c, as atoi() +// On return, c is set to one past the end of the integer. +inline int parseIntAndAdvance(const char *&c) { // NOLINT + int i = 0; + for (; *c >= '0' && *c <= '9'; ++c) i = 10 * i + (*c - '0'); + return i; +} + +// Print literal part of format string and return next format spec +// position. +// +// Skips over any occurrences of '%%', printing a literal '%' to the +// output. The position of the first % character of the next +// nontrivial format spec is returned, or the end of string. +inline const char *printFormatStringLiteral(std::ostream &out, + const char *fmt) { + const char *c = fmt; + for (;; ++c) { + switch (*c) { + case '\0': + out.write(fmt, c - fmt); + return c; + case '%': + out.write(fmt, c - fmt); + if (*(c + 1) != '%') return c; + // for "%%", tack trailing % onto next literal section. + fmt = ++c; + break; + default: + break; + } + } +} + +// Parse a format string and set the stream state accordingly. +// +// The format mini-language recognized here is meant to be the one from C99, +// with the form "%[flags][width][.precision][length]type". +// +// Formatting options which can't be natively represented using the ostream +// state are returned in spacePadPositive (for space padded positive numbers) +// and ntrunc (for truncating conversions). argIndex is incremented if +// necessary to pull out variable width and precision . The function returns a +// pointer to the character after the end of the current format spec. +inline const char *streamStateFromFormat(std::ostream &out, // NOLINT + bool &spacePadPositive, // NOLINT + int &ntrunc, // NOLINT + const char *fmtStart, + const detail::FormatArg *formatters, + int &argIndex, // NOLINT + int numFormatters) { + if (*fmtStart != '%') { + TINYFORMAT_ERROR( + "tinyformat: Not enough conversion specifiers in format string"); + return fmtStart; + } + // Reset stream state to defaults. + out.width(0); + out.precision(6); + out.fill(' '); + // Reset most flags; ignore irrelevant unitbuf & skipws. + out.unsetf(std::ios::adjustfield | std::ios::basefield | + std::ios::floatfield | std::ios::showbase | std::ios::boolalpha | + std::ios::showpoint | std::ios::showpos | std::ios::uppercase); + bool precisionSet = false; + bool widthSet = false; + int widthExtra = 0; + const char *c = fmtStart + 1; + // 1) Parse flags + for (;; ++c) { + switch (*c) { + case '#': + out.setf(std::ios::showpoint | std::ios::showbase); + continue; + case '0': + // overridden by left alignment ('-' flag) + if (!(out.flags() & std::ios::left)) { + // Use internal padding so that numeric values are + // formatted correctly, eg -00010 rather than 000-10 + out.fill('0'); + out.setf(std::ios::internal, std::ios::adjustfield); + } + continue; + case '-': + out.fill(' '); + out.setf(std::ios::left, std::ios::adjustfield); + continue; + case ' ': + // overridden by show positive sign, '+' flag. + if (!(out.flags() & std::ios::showpos)) spacePadPositive = true; + continue; + case '+': + out.setf(std::ios::showpos); + spacePadPositive = false; + widthExtra = 1; + continue; + default: + break; + } + break; + } + // 2) Parse width + if (*c >= '0' && *c <= '9') { + widthSet = true; + out.width(parseIntAndAdvance(c)); + } + if (*c == '*') { + widthSet = true; + int width = 0; + if (argIndex < numFormatters) + width = formatters[argIndex++].toInt(); + else + TINYFORMAT_ERROR( + "tinyformat: Not enough arguments to read variable width"); + if (width < 0) { + // negative widths correspond to '-' flag set + out.fill(' '); + out.setf(std::ios::left, std::ios::adjustfield); + width = -width; + } + out.width(width); + ++c; + } + // 3) Parse precision + if (*c == '.') { + ++c; + int precision = 0; + if (*c == '*') { + ++c; + if (argIndex < numFormatters) + precision = formatters[argIndex++].toInt(); + else + TINYFORMAT_ERROR( + "tinyformat: Not enough arguments to read variable precision"); + } else { + if (*c >= '0' && *c <= '9') + precision = parseIntAndAdvance(c); + else if (*c == '-') // negative precisions ignored, treated as zero. + parseIntAndAdvance(++c); + } + out.precision(precision); + precisionSet = true; + } + // 4) Ignore any C99 length modifier + while (*c == 'l' || *c == 'h' || *c == 'L' || *c == 'j' || *c == 'z' || + *c == 't') + ++c; + // 5) We're up to the conversion specifier character. + // Set stream flags based on conversion specifier (thanks to the + // boost::format class for forging the way here). + bool intConversion = false; + switch (*c) { + case 'u': + case 'd': + case 'i': + out.setf(std::ios::dec, std::ios::basefield); + intConversion = true; + break; + case 'o': + out.setf(std::ios::oct, std::ios::basefield); + intConversion = true; + break; + case 'X': + out.setf(std::ios::uppercase); + case 'x': + case 'p': + out.setf(std::ios::hex, std::ios::basefield); + intConversion = true; + break; + case 'E': + out.setf(std::ios::uppercase); + case 'e': + out.setf(std::ios::scientific, std::ios::floatfield); + out.setf(std::ios::dec, std::ios::basefield); + break; + case 'F': + out.setf(std::ios::uppercase); + case 'f': + out.setf(std::ios::fixed, std::ios::floatfield); + break; + case 'G': + out.setf(std::ios::uppercase); + case 'g': + out.setf(std::ios::dec, std::ios::basefield); + // As in boost::format, let stream decide float format. + out.flags(out.flags() & ~std::ios::floatfield); + break; + case 'a': + case 'A': + TINYFORMAT_ERROR( + "tinyformat: the %a and %A conversion specs " + "are not supported"); + break; + case 'c': + // Handled as special case inside formatValue() + break; + case 's': + if (precisionSet) ntrunc = static_cast(out.precision()); + // Make %s print booleans as "true" and "false" + out.setf(std::ios::boolalpha); + break; + case 'n': + // Not supported - will cause problems! + TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported"); + break; + case '\0': + TINYFORMAT_ERROR( + "tinyformat: Conversion spec incorrectly " + "terminated by end of string"); + return c; + default: + break; + } + if (intConversion && precisionSet && !widthSet) { + // "precision" for integers gives the minimum number of digits (to be + // padded with zeros on the left). This isn't really supported by the + // iostreams, but we can approximately simulate it with the width if + // the width isn't otherwise used. + out.width(out.precision() + widthExtra); + out.setf(std::ios::internal, std::ios::adjustfield); + out.fill('0'); + } + return c + 1; +} + +//------------------------------------------------------------------------------ +inline void formatImpl(std::ostream &out, + const char *fmt, + const detail::FormatArg *formatters, + int numFormatters) { + // Saved stream state + std::streamsize origWidth = out.width(); + std::streamsize origPrecision = out.precision(); + std::ios::fmtflags origFlags = out.flags(); + char origFill = out.fill(); + + for (int argIndex = 0; argIndex < numFormatters; ++argIndex) { + // Parse the format string + fmt = printFormatStringLiteral(out, fmt); + bool spacePadPositive = false; + int ntrunc = -1; + const char *fmtEnd = streamStateFromFormat(out, + spacePadPositive, + ntrunc, + fmt, + formatters, + argIndex, + numFormatters); + if (argIndex >= numFormatters) { + // Check args remain after reading any variable width/precision + TINYFORMAT_ERROR("tinyformat: Not enough format arguments"); + return; + } + const FormatArg &arg = formatters[argIndex]; + // Format the arg into the stream. + if (!spacePadPositive) { + arg.format(out, fmt, fmtEnd, ntrunc); + } else { + // The following is a special case with no direct correspondence + // between stream formatting and the printf() behaviour. Simulate + // it crudely by formatting into a temporary string stream and + // munging the resulting string. + std::ostringstream tmpStream; + tmpStream.copyfmt(out); + tmpStream.setf(std::ios::showpos); + arg.format(tmpStream, fmt, fmtEnd, ntrunc); + std::string result = tmpStream.str(); // allocates... yuck. + for (size_t i = 0, iend = result.size(); i < iend; ++i) + if (result[i] == '+') result[i] = ' '; + out << result; + } + fmt = fmtEnd; + } + + // Print remaining part of format string. + fmt = printFormatStringLiteral(out, fmt); + if (fmt != nullptr && *fmt != '\0' && *fmt != 0) + TINYFORMAT_ERROR( + "tinyformat: Too many conversion specifiers in format string"); + + // Restore stream state + out.width(origWidth); + out.precision(origPrecision); + out.flags(origFlags); + out.fill(origFill); +} + +} // namespace detail + +/// List of template arguments format(), held in a type-opaque way. +/// +/// A const reference to FormatList (typedef'd as FormatListRef) may be +/// conveniently used to pass arguments to non-template functions: All type +/// information has been stripped from the arguments, leaving just enough of a +/// common interface to perform formatting as required. +class FormatList { + public: + FormatList(detail::FormatArg *formatters, int N) + : m_formatters(formatters), m_N(N) {} + + friend void vformat(std::ostream &out, + const char *fmt, + const FormatList &list); + + private: + const detail::FormatArg *m_formatters; + int m_N; +}; + +/// Reference to type-opaque format list for passing to vformat() +typedef const FormatList &FormatListRef; + +namespace detail { + +// Format list subclass with fixed storage to avoid dynamic allocation +template +class FormatListN : public FormatList { + public: + template + FormatListN(const Args &...args) // NOLINT + : FormatList(&m_formatterStore[0], N), + m_formatterStore{FormatArg(args)...} { + static_assert(sizeof...(args) == N, "Number of args must be N"); + } + + private: + FormatArg m_formatterStore[N]; +}; + +// Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard +template <> +class FormatListN<0> : public FormatList { + public: + FormatListN() : FormatList(0, 0) {} +}; + +} // namespace detail + +//------------------------------------------------------------------------------ +// Primary API functions + +/// Make type-agnostic format list from list of template arguments. +/// +/// The exact return type of this function is an implementation detail and +/// shouldn't be relied upon. Instead it should be stored as a FormatListRef: +/// +/// FormatListRef formatList = makeFormatList( /*...*/ ); +template +detail::FormatListN makeFormatList(const Args &...args) { + return detail::FormatListN(args...); +} // NOLINT + +/// Format list of arguments to the stream according to the given format string. +/// +/// The name vformat() is chosen for the semantic similarity to vprintf(): the +/// list of format arguments is held in a single function argument. +inline void vformat(std::ostream &out, const char *fmt, FormatListRef list) { + detail::formatImpl(out, fmt, list.m_formatters, list.m_N); +} + +/// Format list of arguments to the stream according to given format string. +template +void format(std::ostream &out, const char *fmt, const Args &...args) { + vformat(out, fmt, makeFormatList(args...)); +} + +/// Format list of arguments according to the given format string and return +/// the result as a string. +template +std::string format(const char *fmt, const Args &...args) { + std::ostringstream oss; + format(oss, fmt, args...); + return oss.str(); +} + +/// Format list of arguments to std::cout, according to the given format string +template +void printf(const char *fmt, const Args &...args) { + format(std::cout, fmt, args...); +} + +template +void printfln(const char *fmt, const Args &...args) { + format(std::cout, fmt, args...); + std::cout << '\n'; +} + +} // namespace tinyformat +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/to_string.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/to_string.h new file mode 100644 index 0000000000000000000000000000000000000000..3cec88a4571b6bf50ccebb7f9b2c6224f42166e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/string/to_string.h @@ -0,0 +1,81 @@ +/* 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. */ + +#pragma once +#include +#include +#include +#include +#include + +namespace paddle { +namespace string { +inline std::ostream& operator<<(std::ostream& s, const std::type_index& t) { + s << t.name(); + return s; +} + +template ::value, int>::type = 0> +inline std::string to_string(T v) { + std::ostringstream sout; + sout << v; + return sout.str(); +} + +template ::value, int>::type = 0> +inline std::string to_string(T v) { + return std::to_string(static_cast(v)); +} + +template <> +inline std::string to_string(std::type_index t) { + return t.name(); +} + +// Faster std::string/const char* type +template <> +inline std::string to_string(std::string v) { + return v; +} + +template <> +inline std::string to_string(const char* v) { + return std::string(v); +} + +inline std::ostream& operator<<(std::ostream& os, + const std::vector>& lod) { + os << "{"; + for (auto& v : lod) { + os << "{"; + bool is_first = true; + for (auto& i : v) { + if (is_first) { + os << i; + is_first = false; + } else { + os << ", " << i; + } + } + os << "}"; + } + os << "}"; + + return os; +} + +} // namespace string +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/tribool.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/tribool.h new file mode 100644 index 0000000000000000000000000000000000000000..f08cc5805f1fc2529dc98f2259ff0ed9a9d80f6a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/tribool.h @@ -0,0 +1,438 @@ +// Copyright (c) 2022 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. + +// This file copy from boost/logic/tribool.hpp, boost version: 1.41.0 +// Modified the following points: +// 1. modify namespace from boost to paddle +// 2. remove the depending boost header files +// 3. remove the dummy_ in indeterminate_t, which is specially implemented for +// Borland C++ Builder +// 4. remove unnecessary macro BOOST_TRIBOOL_THIRD_STATE + +// Three-state boolean logic library + +// Copyright Douglas Gregor 2002-2004. Use, modification and +// distribution is subject to the Boost Software License, Version +// 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// For more information, see http://www.boost.org + +#pragma once + +namespace paddle { +namespace logic { + +/// INTERNAL ONLY +namespace detail { +/** + * INTERNAL ONLY + * + * \brief A type used only to uniquely identify the 'indeterminate' + * function/keyword. + */ +struct indeterminate_t {}; + +} // end namespace detail + +class tribool; + +/** + * INTERNAL ONLY + * The type of the 'indeterminate' keyword. This has the same type as the + * function 'indeterminate' so that we can recognize when the keyword is + * used. + */ +typedef bool (*indeterminate_keyword_t)(tribool, detail::indeterminate_t); + +/** + * \brief Keyword and test function for the indeterminate tribool value + * + * The \c indeterminate function has a dual role. It's first role is + * as a unary function that tells whether the tribool value is in the + * "indeterminate" state. It's second role is as a keyword + * representing the indeterminate (just like "true" and "false" + * represent the true and false states). + * + * \returns x.value == tribool::indeterminate_value + * \throws nothrow + */ +inline bool indeterminate( + tribool x, detail::indeterminate_t dummy = detail::indeterminate_t()); + +/** + * \brief A 3-state boolean type. + * + * 3-state boolean values are either true, false, or + * indeterminate. + */ +class tribool { + private: + /// INTERNAL ONLY + struct dummy { + void nonnull() {} + }; + + typedef void (dummy::*safe_bool)(); + + public: + /** + * Construct a new 3-state boolean value with the value 'false'. + * + * \throws nothrow + */ + tribool() : value(false_value) {} + + /** + * Construct a new 3-state boolean value with the given boolean + * value, which may be \c true or \c false. + * + * \throws nothrow + */ + tribool(bool value) : value(value ? true_value : false_value) {} // NOLINT + + /** + * Construct a new 3-state boolean value with an indeterminate value. + * + * \throws nothrow + */ + tribool(indeterminate_keyword_t) : value(indeterminate_value) {} // NOLINT + + /** + * Use a 3-state boolean in a boolean context. Will evaluate true in a + * boolean context only when the 3-state boolean is definitely true. + * + * \returns true if the 3-state boolean is true, false otherwise + * \throws nothrow + */ + operator safe_bool() const { + return value == true_value ? &dummy::nonnull : 0; + } + + /** + * The actual stored value in this 3-state boolean, which may be false, true, + * or indeterminate. + */ + enum value_t { false_value, true_value, indeterminate_value } value; +}; + +// Check if the given tribool has an indeterminate value. Also doubles as a +// keyword for the 'indeterminate' value +inline bool indeterminate(tribool x, detail::indeterminate_t) { + return x.value == tribool::indeterminate_value; +} + +/** @defgroup logical Logical operations + */ +//@{ +/** + * \brief Computes the logical negation of a tribool + * + * \returns the logical negation of the tribool, according to the + * table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
!
+ *
false
true
true
false
indeterminate
indeterminate
+ * \throws nothrow + */ +inline tribool operator!(tribool x) { + return x.value == tribool::false_value ? tribool(true) + : x.value == tribool::true_value ? tribool(false) + : tribool(indeterminate); +} + +/** + * \brief Computes the logical conjuction of two tribools + * + * \returns the result of logically ANDing the two tribool values, + * according to the following table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
&&
false
true
indeterminate
false
false
false
false
true
false
true
indeterminate
indeterminate
false
indeterminate
indeterminate
+ * \throws nothrow + */ +inline tribool operator&&(tribool x, tribool y) { + if (static_cast(!x) || static_cast(!y)) + return false; + else if (static_cast(x) && static_cast(y)) + return true; + else + return indeterminate; +} + +/** + * \overload + */ +inline tribool operator&&(tribool x, bool y) { return y ? x : tribool(false); } + +/** + * \overload + */ +inline tribool operator&&(bool x, tribool y) { return x ? y : tribool(false); } + +/** + * \overload + */ +inline tribool operator&&(indeterminate_keyword_t, tribool x) { + return !x ? tribool(false) : tribool(indeterminate); +} + +/** + * \overload + */ +inline tribool operator&&(tribool x, indeterminate_keyword_t) { + return !x ? tribool(false) : tribool(indeterminate); +} + +/** + * \brief Computes the logical disjunction of two tribools + * + * \returns the result of logically ORing the two tribool values, + * according to the following table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
||
false
true
indeterminate
false
false
true
indeterminate
true
true
true
true
indeterminate
indeterminate
true
indeterminate
+ * \throws nothrow + */ +inline tribool operator||(tribool x, tribool y) { + if (static_cast(!x) && static_cast(!y)) + return false; + else if (static_cast(x) || static_cast(y)) + return true; + else + return indeterminate; +} + +/** + * \overload + */ +inline tribool operator||(tribool x, bool y) { return y ? tribool(true) : x; } + +/** + * \overload + */ +inline tribool operator||(bool x, tribool y) { return x ? tribool(true) : y; } + +/** + * \overload + */ +inline tribool operator||(indeterminate_keyword_t, tribool x) { + return x ? tribool(true) : tribool(indeterminate); +} + +/** + * \overload + */ +inline tribool operator||(tribool x, indeterminate_keyword_t) { + return x ? tribool(true) : tribool(indeterminate); +} +//@} + +/** + * \brief Compare tribools for equality + * + * \returns the result of comparing two tribool values, according to + * the following table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
==
false
true
indeterminate
false
true
false
indeterminate
true
false
true
indeterminate
indeterminate
indeterminate
indeterminate
indeterminate
+ * \throws nothrow + */ +inline tribool operator==(tribool x, tribool y) { + if (indeterminate(x) || indeterminate(y)) + return indeterminate; + else + return (x && y) || (!x && !y); +} + +/** + * \overload + */ +inline tribool operator==(tribool x, bool y) { return x == tribool(y); } + +/** + * \overload + */ +inline tribool operator==(bool x, tribool y) { return tribool(x) == y; } + +/** + * \overload + */ +inline tribool operator==(indeterminate_keyword_t, tribool x) { + return tribool(indeterminate) == x; +} + +/** + * \overload + */ +inline tribool operator==(tribool x, indeterminate_keyword_t) { + return tribool(indeterminate) == x; +} + +/** + * \brief Compare tribools for inequality + * + * \returns the result of comparing two tribool values for inequality, + * according to the following table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
!=
false
true
indeterminate
false
false
true
indeterminate
true
true
false
indeterminate
indeterminate
indeterminate
indeterminate
indeterminate
+ * \throws nothrow + */ +inline tribool operator!=(tribool x, tribool y) { + if (indeterminate(x) || indeterminate(y)) + return indeterminate; + else + return !((x && y) || (!x && !y)); +} + +/** + * \overload + */ +inline tribool operator!=(tribool x, bool y) { return x != tribool(y); } + +/** + * \overload + */ +inline tribool operator!=(bool x, tribool y) { return tribool(x) != y; } + +/** + * \overload + */ +inline tribool operator!=(indeterminate_keyword_t, tribool x) { + return tribool(indeterminate) != x; +} + +/** + * \overload + */ +inline tribool operator!=(tribool x, indeterminate_keyword_t) { + return x != tribool(indeterminate); +} + +} // namespace logic +} // namespace paddle + +// Pull tribool and indeterminate into namespace "boost" +namespace paddle { +using logic::indeterminate; +using logic::tribool; +} // namespace paddle diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/variant.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/variant.h new file mode 100644 index 0000000000000000000000000000000000000000..045ffbb6a3fa36a0d2220e092403f3bf866f9b1e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/paddle/utils/variant.h @@ -0,0 +1,2855 @@ +// Copy from +// https://github.com/mpark/variant/blob/single-header/v1.4.0/variant.hpp +// Modify the following points: +// 1. modify namespace mpark to namespace paddle +// 2. add type() member function for variant class +// 3. remove the visitation implementation under the branhch with +// MPARK_CPP14_CONSTEXPR defined since lib::cpp14::array could not be converted +// to std::initializer_list in Paddle's compilation +// 4. decorate PYBIND11_HIDDEN for struct value_visitor + +// MPark.Variant +// +// Copyright Michael Park, 2015-2017 +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.md or copy at +// http://boost.org/LICENSE_1_0.txt) + +#pragma once + +// gcc >= 9 has a bug that creates a false positive warning. +// Reference: +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92145 +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89381 +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 9 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-copy" +#endif + +#if !defined(PYBIND11_HIDDEN) +#ifdef _WIN32 +#define PYBIND11_HIDDEN __declspec(dllexport) +#else +#define PYBIND11_HIDDEN __attribute__((visibility("hidden"))) +#endif +#endif + +/* + variant synopsis + +namespace std { + + // 20.7.2, class template variant + template + class variant { + public: + + // 20.7.2.1, constructors + constexpr variant() noexcept(see below); + variant(const variant&); + variant(variant&&) noexcept(see below); + + template constexpr variant(T&&) noexcept(see below); + + template + constexpr explicit variant(in_place_type_t, Args&&...); + + template + constexpr explicit variant( + in_place_type_t, initializer_list, Args&&...); + + template + constexpr explicit variant(in_place_index_t, Args&&...); + + template + constexpr explicit variant( + in_place_index_t, initializer_list, Args&&...); + + // 20.7.2.2, destructor + ~variant(); + + // 20.7.2.3, assignment + variant& operator=(const variant&); + variant& operator=(variant&&) noexcept(see below); + + template variant& operator=(T&&) noexcept(see below); + + // 20.7.2.4, modifiers + template + T& emplace(Args&&...); + + template + T& emplace(initializer_list, Args&&...); + + template + variant_alternative& emplace(Args&&...); + + template + variant_alternative& emplace(initializer_list, Args&&...); + + // 20.7.2.5, value status + constexpr bool valueless_by_exception() const noexcept; + constexpr size_t index() const noexcept; + + // 20.7.2.6, swap + void swap(variant&) noexcept(see below); + }; + + // 20.7.3, variant helper classes + template struct variant_size; // undefined + + template + constexpr size_t variant_size_v = variant_size::value; + + template struct variant_size; + template struct variant_size; + template struct variant_size; + + template + struct variant_size>; + + template struct variant_alternative; // undefined + + template + using variant_alternative_t = typename variant_alternative::type; + + template struct variant_alternative; + template struct variant_alternative; + template struct variant_alternative; + + template + struct variant_alternative>; + + constexpr size_t variant_npos = -1; + + // 20.7.4, value access + template + constexpr bool holds_alternative(const variant&) noexcept; + + template + constexpr variant_alternative_t>& + get(variant&); + + template + constexpr variant_alternative_t>&& + get(variant&&); + + template + constexpr variant_alternative_t> const& + get(const variant&); + + template + constexpr variant_alternative_t> const&& + get(const variant&&); + + template + constexpr T& get(variant&); + + template + constexpr T&& get(variant&&); + + template + constexpr const T& get(const variant&); + + template + constexpr const T&& get(const variant&&); + + template + constexpr add_pointer_t>> + get_if(variant*) noexcept; + + template + constexpr add_pointer_t>> + get_if(const variant*) noexcept; + + template + constexpr add_pointer_t + get_if(variant*) noexcept; + + template + constexpr add_pointer_t + get_if(const variant*) noexcept; + + // 20.7.5, relational operators + template + constexpr bool operator==(const variant&, const variant&); + + template + constexpr bool operator!=(const variant&, const variant&); + + template + constexpr bool operator<(const variant&, const variant&); + + template + constexpr bool operator>(const variant&, const variant&); + + template + constexpr bool operator<=(const variant&, const variant&); + + template + constexpr bool operator>=(const variant&, const variant&); + + // 20.7.6, visitation + template + constexpr see below visit(Visitor&&, Variants&&...); + + // 20.7.7, class monostate + struct monostate; + + // 20.7.8, monostate relational operators + constexpr bool operator<(monostate, monostate) noexcept; + constexpr bool operator>(monostate, monostate) noexcept; + constexpr bool operator<=(monostate, monostate) noexcept; + constexpr bool operator>=(monostate, monostate) noexcept; + constexpr bool operator==(monostate, monostate) noexcept; + constexpr bool operator!=(monostate, monostate) noexcept; + + // 20.7.9, specialized algorithms + template + void swap(variant&, variant&) noexcept(see below); + + // 20.7.10, class bad_variant_access + class bad_variant_access; + + // 20.7.11, hash support + template struct hash; + template struct hash>; + template <> struct hash; + +} // namespace std + +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// MPark.Variant +// +// Copyright Michael Park, 2015-2017 +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.md or copy at +// http://boost.org/LICENSE_1_0.txt) + +#ifndef MPARK_CONFIG_HPP +#define MPARK_CONFIG_HPP + +// MSVC 2015 Update 3. +#if __cplusplus < 201103L && (!defined(_MSC_VER) || _MSC_FULL_VER < 190024210) +#error "MPark.Variant requires C++11 support." +#endif + +#ifndef __has_attribute +#define __has_attribute(x) 0 +#endif + +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#ifndef __has_include +#define __has_include(x) 0 +#endif + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#if __has_attribute(always_inline) || defined(__GNUC__) +#define MPARK_ALWAYS_INLINE __attribute__((__always_inline__)) inline +#elif defined(_MSC_VER) +#define MPARK_ALWAYS_INLINE __forceinline +#else +#define MPARK_ALWAYS_INLINE inline +#endif + +#if __has_builtin(__builtin_addressof) || \ + (defined(__GNUC__) && __GNUC__ >= 7) || defined(_MSC_VER) +#define MPARK_BUILTIN_ADDRESSOF +#endif + +#if __has_builtin(__builtin_unreachable) || defined(__GNUC__) +#define MPARK_BUILTIN_UNREACHABLE __builtin_unreachable() +#elif defined(_MSC_VER) +#define MPARK_BUILTIN_UNREACHABLE __assume(false) +#else +#define MPARK_BUILTIN_UNREACHABLE +#endif + +#if __has_builtin(__type_pack_element) +#define MPARK_TYPE_PACK_ELEMENT +#endif + +#if defined(__cpp_constexpr) && __cpp_constexpr >= 200704 && \ + !(defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 9) +#define MPARK_CPP11_CONSTEXPR +#endif + +#if defined(__cpp_constexpr) && __cpp_constexpr >= 201304 +#define MPARK_CPP14_CONSTEXPR +#endif + +#if __has_feature(cxx_exceptions) || defined(__cpp_exceptions) || \ + (defined(_MSC_VER) && defined(_CPPUNWIND)) +#define MPARK_EXCEPTIONS +#endif + +#if defined(__cpp_generic_lambdas) || defined(_MSC_VER) +#define MPARK_GENERIC_LAMBDAS +#endif + +#if defined(__cpp_lib_integer_sequence) +#define MPARK_INTEGER_SEQUENCE +#endif + +#if defined(__cpp_return_type_deduction) || defined(_MSC_VER) +#define MPARK_RETURN_TYPE_DEDUCTION +#endif + +#if defined(__cpp_lib_transparent_operators) || defined(_MSC_VER) +#define MPARK_TRANSPARENT_OPERATORS +#endif + +#if defined(__cpp_variable_templates) || defined(_MSC_VER) +#define MPARK_VARIABLE_TEMPLATES +#endif + +#if !defined(__GLIBCXX__) || __has_include() // >= libstdc++-5 +#define MPARK_TRIVIALITY_TYPE_TRAITS +#define MPARK_INCOMPLETE_TYPE_TRAITS +#endif + +#endif // MPARK_CONFIG_HPP + +// MPark.Variant +// +// Copyright Michael Park, 2015-2017 +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.md or copy at +// http://boost.org/LICENSE_1_0.txt) + +#ifndef MPARK_IN_PLACE_HPP +#define MPARK_IN_PLACE_HPP + +#include + +namespace paddle { + +struct in_place_t { + explicit in_place_t() = default; +}; + +template +struct in_place_index_t { + explicit in_place_index_t() = default; +}; + +template +struct in_place_type_t { + explicit in_place_type_t() = default; +}; + +#ifdef MPARK_VARIABLE_TEMPLATES +constexpr in_place_t in_place{}; + +template +constexpr in_place_index_t in_place_index{}; + +template +constexpr in_place_type_t in_place_type{}; +#endif + +} // namespace paddle + +#endif // MPARK_IN_PLACE_HPP + +// MPark.Variant +// +// Copyright Michael Park, 2015-2017 +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.md or copy at +// http://boost.org/LICENSE_1_0.txt) + +#ifndef MPARK_LIB_HPP +#define MPARK_LIB_HPP + +#include +#include +#include +#include + +#define MPARK_RETURN(...) \ + noexcept(noexcept(__VA_ARGS__))->decltype(__VA_ARGS__) { return __VA_ARGS__; } + +namespace paddle { +namespace lib { +template +struct identity { + using type = T; +}; + +inline namespace cpp14 { +template +struct array { + constexpr const T &operator[](std::size_t index) const { return data[index]; } + + T data[N == 0 ? 1 : N]; +}; + +template +using add_pointer_t = typename std::add_pointer::type; + +template +using common_type_t = typename std::common_type::type; + +template +using decay_t = typename std::decay::type; + +template +using enable_if_t = typename std::enable_if::type; + +template +using remove_const_t = typename std::remove_const::type; + +template +using remove_reference_t = typename std::remove_reference::type; + +template +inline constexpr T &&forward(remove_reference_t &t) noexcept { + return static_cast(t); +} + +template +inline constexpr T &&forward(remove_reference_t &&t) noexcept { + static_assert(!std::is_lvalue_reference::value, + "can not forward an rvalue as an lvalue"); + return static_cast(t); +} + +template +inline constexpr remove_reference_t &&move(T &&t) noexcept { + return static_cast &&>(t); +} + +#ifdef MPARK_INTEGER_SEQUENCE +using std::index_sequence; +using std::index_sequence_for; +using std::integer_sequence; +using std::make_index_sequence; +#else +template +struct integer_sequence { + using value_type = T; + static constexpr std::size_t size() noexcept { return sizeof...(Is); } +}; + +template +using index_sequence = integer_sequence; + +template +struct make_index_sequence_concat; + +template +struct make_index_sequence_concat, + index_sequence> + : identity> {}; + +template +struct make_index_sequence_impl; + +template +using make_index_sequence = typename make_index_sequence_impl::type; + +template +struct make_index_sequence_impl + : make_index_sequence_concat, + make_index_sequence> {}; + +template <> +struct make_index_sequence_impl<0> : identity> {}; + +template <> +struct make_index_sequence_impl<1> : identity> {}; + +template +using index_sequence_for = make_index_sequence; +#endif + +// +#ifdef MPARK_TRANSPARENT_OPERATORS +using equal_to = std::equal_to<>; +#else +struct equal_to { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) == lib::forward(rhs)) +}; +#endif + +#ifdef MPARK_TRANSPARENT_OPERATORS +using not_equal_to = std::not_equal_to<>; +#else +struct not_equal_to { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) != lib::forward(rhs)) +}; +#endif + +#ifdef MPARK_TRANSPARENT_OPERATORS +using less = std::less<>; +#else +struct less { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) < lib::forward(rhs)) +}; +#endif + +#ifdef MPARK_TRANSPARENT_OPERATORS +using greater = std::greater<>; +#else +struct greater { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) > lib::forward(rhs)) +}; +#endif + +#ifdef MPARK_TRANSPARENT_OPERATORS +using less_equal = std::less_equal<>; +#else +struct less_equal { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) <= lib::forward(rhs)) +}; +#endif + +#ifdef MPARK_TRANSPARENT_OPERATORS +using greater_equal = std::greater_equal<>; +#else +struct greater_equal { + template + inline constexpr auto operator()(Lhs &&lhs, Rhs &&rhs) const + MPARK_RETURN(lib::forward(lhs) >= lib::forward(rhs)) +}; +#endif +} // namespace cpp14 + +inline namespace cpp17 { +// +template +using bool_constant = std::integral_constant; + +template +struct voider : identity {}; + +template +using void_t = typename voider::type; + +namespace detail { +namespace swappable { + +using std::swap; + +template +struct is_swappable { + private: + template (), std::declval()))> + inline static std::true_type test(int); + + template + inline static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +template +struct is_nothrow_swappable { + static constexpr bool value = + noexcept(swap(std::declval(), std::declval())); +}; + +template +struct is_nothrow_swappable : std::false_type {}; + +} // namespace swappable +} // namespace detail + +using detail::swappable::is_swappable; + +template +using is_nothrow_swappable = + detail::swappable::is_nothrow_swappable::value, T>; + +// +namespace detail { + +template +struct is_reference_wrapper : std::false_type {}; + +template +struct is_reference_wrapper> : std::true_type {}; + +template +struct Invoke; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&...args) + MPARK_RETURN((lib::forward(arg).*pmf)(lib::forward(args)...)) +}; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&...args) + MPARK_RETURN((lib::forward(arg).get().* + pmf)(lib::forward(args)...)) +}; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmf, Arg &&arg, Args &&...args) + MPARK_RETURN(((*lib::forward(arg)).* + pmf)(lib::forward(args)...)) +}; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmo, Arg &&arg) + MPARK_RETURN(lib::forward(arg).*pmo) +}; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmo, Arg &&arg) + MPARK_RETURN(lib::forward(arg).get().*pmo) +}; + +template <> +struct Invoke { + template + inline static constexpr auto invoke(R T::*pmo, Arg &&arg) + MPARK_RETURN((*lib::forward(arg)).*pmo) +}; + +template +inline constexpr auto invoke(R T::*f, Arg &&arg, Args &&...args) + MPARK_RETURN(Invoke::value, + (std::is_base_of>::value ? 0 + : is_reference_wrapper>::value + ? 1 + : 2)>::invoke(f, + lib::forward(arg), + lib::forward(args)...)) + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4100) +#endif + template + inline constexpr auto invoke(F &&f, Args &&...args) + MPARK_RETURN(lib::forward(f)(lib::forward(args)...)) +#ifdef _MSC_VER +#pragma warning(pop) +#endif +} // namespace detail + +template +inline constexpr auto invoke(F &&f, Args &&...args) + MPARK_RETURN(detail::invoke(lib::forward(f), + lib::forward(args)...)) + + namespace detail { + template + struct invoke_result {}; + + template + struct invoke_result< + void_t(), std::declval()...))>, + F, + Args...> : identity(), + std::declval()...))> {}; + +} // namespace detail + +template +using invoke_result = detail::invoke_result; + +template +using invoke_result_t = typename invoke_result::type; + +namespace detail { + +template +struct is_invocable : std::false_type {}; + +template +struct is_invocable>, F, Args...> + : std::true_type {}; + +template +struct is_invocable_r : std::false_type {}; + +template +struct is_invocable_r>, R, F, Args...> + : std::is_convertible, R> {}; + +} // namespace detail + +template +using is_invocable = detail::is_invocable; + +template +using is_invocable_r = detail::is_invocable_r; + +namespace detail { + +template +struct is_nothrow_invocable { + static constexpr bool value = + noexcept(lib::invoke(std::declval(), std::declval()...)); +}; + +template +struct is_nothrow_invocable : std::false_type {}; + +template +struct is_nothrow_invocable_r { + private: + inline static R impl() { + return lib::invoke(std::declval(), std::declval()...); + } + + public: + static constexpr bool value = noexcept(impl()); +}; + +template +struct is_nothrow_invocable_r : std::false_type {}; + +} // namespace detail + +template +using is_nothrow_invocable = + detail::is_nothrow_invocable::value, F, Args...>; + +template +using is_nothrow_invocable_r = detail:: + is_nothrow_invocable_r::value, R, F, Args...>; + +// +#ifdef MPARK_BUILTIN_ADDRESSOF +template +inline constexpr T *addressof(T &arg) noexcept { + return __builtin_addressof(arg); +} +#else +namespace detail { + +namespace has_addressof_impl { + +struct fail; + +template +inline fail operator&(T &&); + +template +inline static constexpr bool impl() { + return (std::is_class::value || std::is_union::value) && + !std::is_same()), fail>::value; +} + +} // namespace has_addressof_impl + +template +using has_addressof = bool_constant()>; + +template +inline constexpr T *addressof(T &arg, std::true_type) noexcept { + return std::addressof(arg); +} + +template +inline constexpr T *addressof(T &arg, std::false_type) noexcept { + return &arg; +} + +} // namespace detail + +template +inline constexpr T *addressof(T &arg) noexcept { + return detail::addressof(arg, detail::has_addressof{}); +} +#endif + +template +inline constexpr T *addressof(const T &&) = delete; + +} // namespace cpp17 + +template +struct remove_all_extents : identity {}; + +template +struct remove_all_extents> : remove_all_extents {}; + +template +using remove_all_extents_t = typename remove_all_extents::type; + +template +using size_constant = std::integral_constant; + +template +struct indexed_type : size_constant { + using type = T; +}; + +template +using all = std::is_same, + integer_sequence>; + +#ifdef MPARK_TYPE_PACK_ELEMENT +template +using type_pack_element_t = __type_pack_element; +#else +template +struct type_pack_element_impl { + private: + template + struct set; + + template + struct set> : indexed_type... {}; + + template + inline static std::enable_if impl(indexed_type); + + inline static std::enable_if impl(...); + + public: + using type = decltype(impl(set>{})); +}; + +template +using type_pack_element = typename type_pack_element_impl::type; + +template +using type_pack_element_t = typename type_pack_element::type; +#endif + +#ifdef MPARK_TRIVIALITY_TYPE_TRAITS +using std::is_trivially_copy_assignable; +using std::is_trivially_copy_constructible; +using std::is_trivially_move_assignable; +using std::is_trivially_move_constructible; +#else +template +struct is_trivially_copy_constructible + : bool_constant::value &&__has_trivial_copy( + T)> {}; + +template +struct is_trivially_move_constructible : bool_constant<__is_trivial(T)> {}; + +template +struct is_trivially_copy_assignable + : bool_constant::value &&__has_trivial_assign( + T)> {}; + +template +struct is_trivially_move_assignable : bool_constant<__is_trivial(T)> {}; +#endif + +template +struct dependent_type : T {}; + +template +struct push_back; + +template +using push_back_t = typename push_back::type; + +template +struct push_back, J> { + using type = index_sequence; +}; + +} // namespace lib +} // namespace paddle + +#undef MPARK_RETURN + +#endif // MPARK_LIB_HPP + +namespace paddle { + +#ifdef MPARK_RETURN_TYPE_DEDUCTION + +#define AUTO auto +#define AUTO_RETURN(...) \ + { return __VA_ARGS__; } + +#define AUTO_REFREF auto && +#define AUTO_REFREF_RETURN(...) \ + { return __VA_ARGS__; } + +#define DECLTYPE_AUTO decltype(auto) +#define DECLTYPE_AUTO_RETURN(...) \ + { return __VA_ARGS__; } + +#else + +#define AUTO auto +#define AUTO_RETURN(...) \ + ->lib::decay_t { return __VA_ARGS__; } + +#define AUTO_REFREF auto +#define AUTO_REFREF_RETURN(...) \ + ->decltype((__VA_ARGS__)) { \ + static_assert(std::is_reference::value, ""); \ + return __VA_ARGS__; \ + } + +#define DECLTYPE_AUTO auto +#define DECLTYPE_AUTO_RETURN(...) \ + ->decltype(__VA_ARGS__) { return __VA_ARGS__; } + +#endif + +class bad_variant_access : public std::exception { + public: + virtual const char *what() const noexcept override { + return "bad_variant_access"; + } +}; + +[[noreturn]] inline void throw_bad_variant_access() { +#ifdef MPARK_EXCEPTIONS + throw bad_variant_access{}; +#else + std::terminate(); + MPARK_BUILTIN_UNREACHABLE; +#endif +} + +template +class variant; + +template +struct variant_size; + +#ifdef MPARK_VARIABLE_TEMPLATES +template +constexpr std::size_t variant_size_v = variant_size::value; +#endif + +template +struct variant_size : variant_size {}; + +template +struct variant_size : variant_size {}; + +template +struct variant_size : variant_size {}; + +template +struct variant_size> : lib::size_constant {}; + +template +struct variant_alternative; + +template +using variant_alternative_t = typename variant_alternative::type; + +template +struct variant_alternative + : std::add_const> {}; + +template +struct variant_alternative + : std::add_volatile> {}; + +template +struct variant_alternative + : std::add_cv> {}; + +template +struct variant_alternative> { + static_assert(I < sizeof...(Ts), + "index out of bounds in `std::variant_alternative<>`"); + using type = lib::type_pack_element_t; +}; + +constexpr std::size_t variant_npos = static_cast(-1); + +namespace detail { + +constexpr std::size_t not_found = static_cast(-1); +constexpr std::size_t ambiguous = static_cast(-2); + +#ifdef MPARK_CPP14_CONSTEXPR +template +inline constexpr std::size_t find_index() { + constexpr lib::array matches = { + {std::is_same::value...}}; + std::size_t result = not_found; + for (std::size_t i = 0; i < sizeof...(Ts); ++i) { + if (matches[i]) { + if (result != not_found) { + return ambiguous; + } + result = i; + } + } + return result; +} +#else +inline constexpr std::size_t find_index_impl(std::size_t result, std::size_t) { + return result; +} + +template +inline constexpr std::size_t find_index_impl(std::size_t result, + std::size_t idx, + bool b, + Bs... bs) { + return b ? (result != not_found ? ambiguous + : find_index_impl(idx, idx + 1, bs...)) + : find_index_impl(result, idx + 1, bs...); +} + +template +inline constexpr std::size_t find_index() { + return find_index_impl(not_found, 0, std::is_same::value...); +} +#endif + +template +using find_index_sfinae_impl = + lib::enable_if_t>; + +template +using find_index_sfinae = find_index_sfinae_impl()>; + +template +struct find_index_checked_impl : lib::size_constant { + static_assert(I != not_found, "the specified type is not found."); + static_assert(I != ambiguous, "the specified type is ambiguous."); +}; + +template +using find_index_checked = find_index_checked_impl()>; + +struct valueless_t {}; + +enum class Trait { TriviallyAvailable, Available, Unavailable }; + +template + class IsTriviallyAvailable, + template + class IsAvailable> +inline constexpr Trait trait() { + return IsTriviallyAvailable::value ? Trait::TriviallyAvailable + : IsAvailable::value ? Trait::Available + : Trait::Unavailable; +} + +#ifdef MPARK_CPP14_CONSTEXPR +template +inline constexpr Trait common_trait(Traits... traits_) { + Trait result = Trait::TriviallyAvailable; + lib::array traits = {{traits_...}}; + for (std::size_t i = 0; i < sizeof...(Traits); ++i) { + Trait t = traits[i]; + if (static_cast(t) > static_cast(result)) { + result = t; + } + } + return result; +} +#else +inline constexpr Trait common_trait_impl(Trait result) { return result; } + +template +inline constexpr Trait common_trait_impl(Trait result, Trait t, Traits... ts) { + return static_cast(t) > static_cast(result) + ? common_trait_impl(t, ts...) + : common_trait_impl(result, ts...); +} + +template +inline constexpr Trait common_trait(Traits... ts) { + return common_trait_impl(Trait::TriviallyAvailable, ts...); +} +#endif + +template +struct traits { + static constexpr Trait copy_constructible_trait = + common_trait(trait()...); + + static constexpr Trait move_constructible_trait = + common_trait(trait()...); + + static constexpr Trait copy_assignable_trait = + common_trait(copy_constructible_trait, + trait()...); + + static constexpr Trait move_assignable_trait = + common_trait(move_constructible_trait, + trait()...); + + static constexpr Trait destructible_trait = common_trait( + trait()...); +}; + +namespace access { + +struct recursive_union { +#ifdef MPARK_RETURN_TYPE_DEDUCTION + template + inline static constexpr auto &&get_alt(V &&v, in_place_index_t<0>) { + return lib::forward(v).head_; + } + + template + inline static constexpr auto &&get_alt(V &&v, in_place_index_t) { + return get_alt(lib::forward(v).tail_, in_place_index_t{}); + } +#else + template + struct get_alt_impl { + template + inline constexpr AUTO_REFREF operator()(V &&v) const + AUTO_REFREF_RETURN(get_alt_impl{}(lib::forward(v).tail_)) + }; + + template + struct get_alt_impl<0, Dummy> { + template + inline constexpr AUTO_REFREF operator()(V &&v) const + AUTO_REFREF_RETURN(lib::forward(v).head_) + }; + + template + inline static constexpr AUTO_REFREF get_alt(V &&v, in_place_index_t) + AUTO_REFREF_RETURN(get_alt_impl{}(lib::forward(v))) +#endif +}; + +struct base { + template + inline static constexpr AUTO_REFREF get_alt(V &&v) +#ifdef _MSC_VER + AUTO_REFREF_RETURN(recursive_union::get_alt(lib::forward(v).data_, + in_place_index_t{})) +#else + AUTO_REFREF_RETURN(recursive_union::get_alt(data(lib::forward(v)), + in_place_index_t{})) +#endif +}; + +struct variant { + template + inline static constexpr AUTO_REFREF get_alt(V &&v) + AUTO_REFREF_RETURN(base::get_alt(lib::forward(v).impl_)) +}; + +} // namespace access + +namespace visitation { + +#if defined(MPARK_CPP14_CONSTEXPR) && !defined(_MSC_VER) +#define MPARK_VARIANT_SWITCH_VISIT +#endif + +struct base { + template + using dispatch_result_t = + decltype(lib::invoke(std::declval(), + access::base::get_alt<0>(std::declval())...)); + + template + struct expected { + template + inline static constexpr bool but_got() { + return std::is_same::value; + } + }; + + template + struct visit_return_type_check { + static_assert(expected::template but_got(), + "`visit` requires the visitor to have a single return type"); + + template + inline static constexpr DECLTYPE_AUTO invoke(Visitor &&visitor, + Alts &&...alts) + DECLTYPE_AUTO_RETURN(lib::invoke(lib::forward(visitor), + lib::forward(alts)...)) + }; + +#ifdef MPARK_VARIANT_SWITCH_VISIT + template + struct dispatcher; + + template + struct dispatcher { + template + MPARK_ALWAYS_INLINE static constexpr R dispatch(F &&, + typename ITs::type &&..., + Vs &&...) { + MPARK_BUILTIN_UNREACHABLE; + } + + template + MPARK_ALWAYS_INLINE static constexpr R dispatch_case(F &&, Vs &&...) { + MPARK_BUILTIN_UNREACHABLE; + } + + template + MPARK_ALWAYS_INLINE static constexpr R dispatch_at(std::size_t, + F &&, + Vs &&...) { + MPARK_BUILTIN_UNREACHABLE; + } + }; + + template + struct dispatcher { + template + MPARK_ALWAYS_INLINE static constexpr R dispatch( + F &&f, typename ITs::type &&...visited_vs) { + using Expected = R; + using Actual = decltype(lib::invoke( + lib::forward(f), + access::base::get_alt( + lib::forward(visited_vs))...)); + return visit_return_type_check::invoke( + lib::forward(f), + access::base::get_alt( + lib::forward(visited_vs))...); + } + + template + MPARK_ALWAYS_INLINE static constexpr R dispatch( + F &&f, typename ITs::type &&...visited_vs, V &&v, Vs &&...vs) { +#define MPARK_DISPATCH(I) \ + dispatcher<(I < lib::decay_t::size()), \ + R, \ + ITs..., \ + lib::indexed_type>:: \ + template dispatch<0>(lib::forward(f), \ + lib::forward(visited_vs)..., \ + lib::forward(v), \ + lib::forward(vs)...) + +#define MPARK_DEFAULT(I) \ + dispatcher<(I < lib::decay_t::size()), R, ITs...>::template dispatch( \ + lib::forward(f), \ + lib::forward(visited_vs)..., \ + lib::forward(v), \ + lib::forward(vs)...) + + switch (v.index()) { + case B + 0: + return MPARK_DISPATCH(B + 0); + case B + 1: + return MPARK_DISPATCH(B + 1); + case B + 2: + return MPARK_DISPATCH(B + 2); + case B + 3: + return MPARK_DISPATCH(B + 3); + case B + 4: + return MPARK_DISPATCH(B + 4); + case B + 5: + return MPARK_DISPATCH(B + 5); + case B + 6: + return MPARK_DISPATCH(B + 6); + case B + 7: + return MPARK_DISPATCH(B + 7); + case B + 8: + return MPARK_DISPATCH(B + 8); + case B + 9: + return MPARK_DISPATCH(B + 9); + case B + 10: + return MPARK_DISPATCH(B + 10); + case B + 11: + return MPARK_DISPATCH(B + 11); + case B + 12: + return MPARK_DISPATCH(B + 12); + case B + 13: + return MPARK_DISPATCH(B + 13); + case B + 14: + return MPARK_DISPATCH(B + 14); + case B + 15: + return MPARK_DISPATCH(B + 15); + case B + 16: + return MPARK_DISPATCH(B + 16); + case B + 17: + return MPARK_DISPATCH(B + 17); + case B + 18: + return MPARK_DISPATCH(B + 18); + case B + 19: + return MPARK_DISPATCH(B + 19); + case B + 20: + return MPARK_DISPATCH(B + 20); + case B + 21: + return MPARK_DISPATCH(B + 21); + case B + 22: + return MPARK_DISPATCH(B + 22); + case B + 23: + return MPARK_DISPATCH(B + 23); + case B + 24: + return MPARK_DISPATCH(B + 24); + case B + 25: + return MPARK_DISPATCH(B + 25); + case B + 26: + return MPARK_DISPATCH(B + 26); + case B + 27: + return MPARK_DISPATCH(B + 27); + case B + 28: + return MPARK_DISPATCH(B + 28); + case B + 29: + return MPARK_DISPATCH(B + 29); + case B + 30: + return MPARK_DISPATCH(B + 30); + case B + 31: + return MPARK_DISPATCH(B + 31); + default: + return MPARK_DEFAULT(B + 32); + } + +#undef MPARK_DEFAULT +#undef MPARK_DISPATCH + } + + template + MPARK_ALWAYS_INLINE static constexpr R dispatch_case(F &&f, Vs &&...vs) { + using Expected = R; + using Actual = decltype(lib::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...)); + return visit_return_type_check::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...); + } + + template + MPARK_ALWAYS_INLINE static constexpr R dispatch_at(std::size_t index, + F &&f, + V &&v, + Vs &&...vs) { + static_assert(lib::all<(lib::decay_t::size() == + lib::decay_t::size())...>::value, + "all of the variants must be the same size."); +#define MPARK_DISPATCH_AT(I) \ + dispatcher<(I < lib::decay_t::size()), R>::template dispatch_case( \ + lib::forward(f), lib::forward(v), lib::forward(vs)...) + +#define MPARK_DEFAULT(I) \ + dispatcher<(I < lib::decay_t::size()), R>::template dispatch_at( \ + index, lib::forward(f), lib::forward(v), lib::forward(vs)...) + + switch (index) { + case B + 0: + return MPARK_DISPATCH_AT(B + 0); + case B + 1: + return MPARK_DISPATCH_AT(B + 1); + case B + 2: + return MPARK_DISPATCH_AT(B + 2); + case B + 3: + return MPARK_DISPATCH_AT(B + 3); + case B + 4: + return MPARK_DISPATCH_AT(B + 4); + case B + 5: + return MPARK_DISPATCH_AT(B + 5); + case B + 6: + return MPARK_DISPATCH_AT(B + 6); + case B + 7: + return MPARK_DISPATCH_AT(B + 7); + case B + 8: + return MPARK_DISPATCH_AT(B + 8); + case B + 9: + return MPARK_DISPATCH_AT(B + 9); + case B + 10: + return MPARK_DISPATCH_AT(B + 10); + case B + 11: + return MPARK_DISPATCH_AT(B + 11); + case B + 12: + return MPARK_DISPATCH_AT(B + 12); + case B + 13: + return MPARK_DISPATCH_AT(B + 13); + case B + 14: + return MPARK_DISPATCH_AT(B + 14); + case B + 15: + return MPARK_DISPATCH_AT(B + 15); + case B + 16: + return MPARK_DISPATCH_AT(B + 16); + case B + 17: + return MPARK_DISPATCH_AT(B + 17); + case B + 18: + return MPARK_DISPATCH_AT(B + 18); + case B + 19: + return MPARK_DISPATCH_AT(B + 19); + case B + 20: + return MPARK_DISPATCH_AT(B + 20); + case B + 21: + return MPARK_DISPATCH_AT(B + 21); + case B + 22: + return MPARK_DISPATCH_AT(B + 22); + case B + 23: + return MPARK_DISPATCH_AT(B + 23); + case B + 24: + return MPARK_DISPATCH_AT(B + 24); + case B + 25: + return MPARK_DISPATCH_AT(B + 25); + case B + 26: + return MPARK_DISPATCH_AT(B + 26); + case B + 27: + return MPARK_DISPATCH_AT(B + 27); + case B + 28: + return MPARK_DISPATCH_AT(B + 28); + case B + 29: + return MPARK_DISPATCH_AT(B + 29); + case B + 30: + return MPARK_DISPATCH_AT(B + 30); + case B + 31: + return MPARK_DISPATCH_AT(B + 31); + default: + return MPARK_DEFAULT(B + 32); + } + +#undef MPARK_DEFAULT +#undef MPARK_DISPATCH_AT + } + }; +#else + template + inline static constexpr const T &at(const T &elem) noexcept { + return elem; + } + + template + inline static constexpr const lib::remove_all_extents_t &at( + const lib::array &elems, std::size_t i, Is... is) noexcept { + return at(elems[i], is...); + } + + template + inline static constexpr lib::array, sizeof...(Fs) + 1> + make_farray(F &&f, Fs &&...fs) { + return {{lib::forward(f), lib::forward(fs)...}}; + } + + template + struct make_fmatrix_impl { + template + inline static constexpr dispatch_result_t dispatch(F &&f, + Vs &&...vs) { + using Expected = dispatch_result_t; + using Actual = decltype(lib::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...)); + return visit_return_type_check::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...); + } + +#ifdef MPARK_RETURN_TYPE_DEDUCTION + template + inline static constexpr auto impl(lib::index_sequence) { + return &dispatch; + } + + template + inline static constexpr auto impl(Is, + lib::index_sequence, + Ls... ls) { + return make_farray(impl(lib::push_back_t{}, ls...)...); + } +#else + template + struct impl; + + template + struct impl> { + inline constexpr AUTO operator()() const AUTO_RETURN(&dispatch) + }; + + template + struct impl, Ls...> { + inline constexpr AUTO operator()() const + AUTO_RETURN(make_farray(impl, Ls...>{}()...)) + }; +#endif + }; + +#ifdef MPARK_RETURN_TYPE_DEDUCTION + template + inline static constexpr auto make_fmatrix() { + return make_fmatrix_impl::impl( + lib::index_sequence<>{}, + lib::make_index_sequence::size()>{}...); + } +#else + template + inline static constexpr AUTO make_fmatrix() + AUTO_RETURN(typename make_fmatrix_impl::template impl< + lib::index_sequence<>, + lib::make_index_sequence::size()>...>{}()) +#endif + + template + struct make_fdiagonal_impl { + template + inline static constexpr dispatch_result_t dispatch(F &&f, + Vs &&...vs) { + using Expected = dispatch_result_t; + using Actual = decltype(lib::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...)); + return visit_return_type_check::invoke( + lib::forward(f), + access::base::get_alt(lib::forward(vs))...); + } + + template + inline static constexpr AUTO impl(lib::index_sequence) + AUTO_RETURN(make_farray(&dispatch...)) + }; + + template + inline static constexpr auto make_fdiagonal() + -> decltype(make_fdiagonal_impl::impl( + lib::make_index_sequence::size()>{})) { + static_assert(lib::all<(lib::decay_t::size() == + lib::decay_t::size())...>::value, + "all of the variants must be the same size."); + return make_fdiagonal_impl::impl( + lib::make_index_sequence::size()>{}); + } +#endif +}; + +#if !defined(MPARK_VARIANT_SWITCH_VISIT) && \ + (!defined(_MSC_VER) || _MSC_VER >= 1910) +template +using fmatrix_t = decltype(base::make_fmatrix()); + +template +struct fmatrix { + static constexpr fmatrix_t value = base::make_fmatrix(); +}; + +template +constexpr fmatrix_t fmatrix::value; + +template +using fdiagonal_t = decltype(base::make_fdiagonal()); + +template +struct fdiagonal { + static constexpr fdiagonal_t value = + base::make_fdiagonal(); +}; + +template +constexpr fdiagonal_t fdiagonal::value; +#endif + +struct alt { + template + inline static constexpr DECLTYPE_AUTO visit_alt(Visitor &&visitor, Vs &&...vs) +#ifdef MPARK_VARIANT_SWITCH_VISIT + DECLTYPE_AUTO_RETURN( + base::dispatcher(vs)))...>>:: + template dispatch<0>(lib::forward(visitor), + as_base(lib::forward(vs))...)) +#elif !defined(_MSC_VER) || _MSC_VER >= 1910 + DECLTYPE_AUTO_RETURN( + base::at(fmatrix(vs)))...>::value, + vs.index()...)(lib::forward(visitor), + as_base(lib::forward(vs))...)) +#else + DECLTYPE_AUTO_RETURN(base::at( + base::make_fmatrix(vs)))...>(), + vs.index()...)(lib::forward(visitor), + as_base(lib::forward(vs))...)) +#endif + + template + inline static constexpr DECLTYPE_AUTO + visit_alt_at(std::size_t index, Visitor &&visitor, Vs &&...vs) +#ifdef MPARK_VARIANT_SWITCH_VISIT + DECLTYPE_AUTO_RETURN( + base::dispatcher< + true, + base::dispatch_result_t< + Visitor, + decltype(as_base(lib::forward(vs)))...>>:: + template dispatch_at<0>(index, + lib::forward(visitor), + as_base(lib::forward(vs))...)) +#elif !defined(_MSC_VER) || _MSC_VER >= 1910 + DECLTYPE_AUTO_RETURN(base::at( + fdiagonal(vs)))...>::value, + index)(lib::forward(visitor), + as_base(lib::forward(vs))...)) +#else + DECLTYPE_AUTO_RETURN( + base::at(base::make_fdiagonal< + Visitor &&, + decltype(as_base(lib::forward(vs)))...>(), + index)(lib::forward(visitor), + as_base(lib::forward(vs))...)) +#endif +}; + +struct variant { + private: + template + struct visitor { + template + inline static constexpr bool does_not_handle() { + return lib::is_invocable::value; + } + }; + + template + struct visit_exhaustiveness_check { + static_assert(visitor::template does_not_handle(), + "`visit` requires the visitor to be exhaustive."); + + inline static constexpr DECLTYPE_AUTO invoke(Visitor &&visitor, + Values &&...values) + DECLTYPE_AUTO_RETURN(lib::invoke(lib::forward(visitor), + lib::forward(values)...)) + }; + + template + struct PYBIND11_HIDDEN value_visitor { + Visitor &&visitor_; + + template + inline constexpr DECLTYPE_AUTO operator()(Alts &&...alts) const + DECLTYPE_AUTO_RETURN(visit_exhaustiveness_check< + Visitor, + decltype((lib::forward(alts).value))...>:: + invoke(lib::forward(visitor_), + lib::forward(alts).value...)) + }; + + template + inline static constexpr AUTO make_value_visitor(Visitor &&visitor) + AUTO_RETURN(value_visitor{lib::forward(visitor)}) + + public + : template + inline static constexpr DECLTYPE_AUTO + visit_alt(Visitor &&visitor, Vs &&...vs) + DECLTYPE_AUTO_RETURN(alt::visit_alt(lib::forward(visitor), + lib::forward(vs).impl_...)) + + template + inline static constexpr DECLTYPE_AUTO + visit_alt_at(std::size_t index, Visitor &&visitor, Vs &&...vs) + DECLTYPE_AUTO_RETURN( + alt::visit_alt_at(index, + lib::forward(visitor), + lib::forward(vs).impl_...)) + + template + inline static constexpr DECLTYPE_AUTO + visit_value(Visitor &&visitor, Vs &&...vs) DECLTYPE_AUTO_RETURN( + visit_alt(make_value_visitor(lib::forward(visitor)), + lib::forward(vs)...)) + + template + inline static constexpr DECLTYPE_AUTO + visit_value_at(std::size_t index, Visitor &&visitor, Vs &&...vs) + DECLTYPE_AUTO_RETURN( + visit_alt_at(index, + make_value_visitor(lib::forward(visitor)), + lib::forward(vs)...)) +}; + +} // namespace visitation + +template +struct alt { + using value_type = T; + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#endif + template + inline explicit constexpr alt(in_place_t, Args &&...args) + : value(lib::forward(args)...) {} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + + T value; +}; + +template +union recursive_union; + +template +union recursive_union {}; + +#define MPARK_VARIANT_RECURSIVE_UNION(destructible_trait, destructor) \ + template \ + union recursive_union { \ + public: \ + inline explicit constexpr recursive_union(valueless_t) noexcept \ + : dummy_{} {} \ + \ + template \ + inline explicit constexpr recursive_union(in_place_index_t<0>, \ + Args &&...args) \ + : head_(in_place_t{}, lib::forward(args)...) {} \ + \ + template \ + inline explicit constexpr recursive_union(in_place_index_t, \ + Args &&...args) \ + : tail_(in_place_index_t{}, lib::forward(args)...) {} \ + \ + recursive_union(const recursive_union &) = default; \ + recursive_union(recursive_union &&) = default; \ + \ + destructor \ + \ + recursive_union & \ + operator=(const recursive_union &) = default; \ + recursive_union &operator=(recursive_union &&) = default; \ + \ + private: \ + char dummy_; \ + alt head_; \ + recursive_union tail_; \ + \ + friend struct access::recursive_union; \ + } + +MPARK_VARIANT_RECURSIVE_UNION(Trait::TriviallyAvailable, + ~recursive_union() = default;); +MPARK_VARIANT_RECURSIVE_UNION(Trait::Available, ~recursive_union(){}); +MPARK_VARIANT_RECURSIVE_UNION(Trait::Unavailable, ~recursive_union() = delete;); + +#undef MPARK_VARIANT_RECURSIVE_UNION + +using index_t = unsigned int; + +template +class base { + public: + inline explicit constexpr base(valueless_t tag) noexcept + : data_(tag), index_(static_cast(-1)) {} + + template + inline explicit constexpr base(in_place_index_t, Args &&...args) + : data_(in_place_index_t{}, lib::forward(args)...), index_(I) {} + + inline constexpr bool valueless_by_exception() const noexcept { + return index_ == static_cast(-1); + } + + inline constexpr std::size_t index() const noexcept { + return valueless_by_exception() ? variant_npos : index_; + } + + protected: + using data_t = recursive_union; + + friend inline constexpr base &as_base(base &b) { return b; } + friend inline constexpr const base &as_base(const base &b) { return b; } + friend inline constexpr base &&as_base(base &&b) { return lib::move(b); } + friend inline constexpr const base &&as_base(const base &&b) { + return lib::move(b); + } + + friend inline constexpr data_t &data(base &b) { return b.data_; } + friend inline constexpr const data_t &data(const base &b) { return b.data_; } + friend inline constexpr data_t &&data(base &&b) { return lib::move(b).data_; } + friend inline constexpr const data_t &&data(const base &&b) { + return lib::move(b).data_; + } + + inline static constexpr std::size_t size() { return sizeof...(Ts); } + + data_t data_; + index_t index_; + + friend struct access::base; + friend struct visitation::base; +}; + +struct dtor { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4100) +#endif + template + inline void operator()(Alt &alt) const noexcept { + alt.~Alt(); + } +#ifdef _MSC_VER +#pragma warning(pop) +#endif +}; + +#if !defined(_MSC_VER) || _MSC_VER >= 1910 +#define MPARK_INHERITING_CTOR(type, base) using base::base; +#else +#define MPARK_INHERITING_CTOR(type, base) \ + template \ + inline explicit constexpr type(Args &&...args) \ + : base(lib::forward(args)...) {} +#endif + +template +class destructor; + +#define MPARK_VARIANT_DESTRUCTOR(destructible_trait, definition, destroy) \ + template \ + class destructor, destructible_trait> \ + : public base { \ + using super = base; \ + \ + public: \ + MPARK_INHERITING_CTOR(destructor, super) \ + using super::operator=; \ + \ + destructor(const destructor &) = default; \ + destructor(destructor &&) = default; \ + definition destructor &operator=(const destructor &) = default; \ + destructor &operator=(destructor &&) = default; \ + \ + protected: \ + destroy \ + } + +MPARK_VARIANT_DESTRUCTOR( + Trait::TriviallyAvailable, ~destructor() = default; + , inline void destroy() noexcept { + this->index_ = static_cast(-1); + }); + +MPARK_VARIANT_DESTRUCTOR( + Trait::Available, + ~destructor() { destroy(); }, + inline void destroy() noexcept { + if (!this->valueless_by_exception()) { + visitation::alt::visit_alt(dtor{}, *this); + } + this->index_ = static_cast(-1); + }); + +MPARK_VARIANT_DESTRUCTOR(Trait::Unavailable, ~destructor() = delete; + , inline void destroy() noexcept = delete;); + +#undef MPARK_VARIANT_DESTRUCTOR + +template +class constructor : public destructor { + using super = destructor; + + public: + MPARK_INHERITING_CTOR(constructor, super) + using super::operator=; + + protected: +#ifndef MPARK_GENERIC_LAMBDAS + struct ctor { + template + inline void operator()(LhsAlt &lhs_alt, RhsAlt &&rhs_alt) const { + constructor::construct_alt(lhs_alt, lib::forward(rhs_alt).value); + } + }; +#endif + + template + inline static T &construct_alt(alt &a, Args &&...args) { + auto *result = ::new (static_cast(lib::addressof(a))) + alt(in_place_t{}, lib::forward(args)...); + return result->value; + } + + template + inline static void generic_construct(constructor &lhs, Rhs &&rhs) { + lhs.destroy(); + if (!rhs.valueless_by_exception()) { + visitation::alt::visit_alt_at( + rhs.index(), +#ifdef MPARK_GENERIC_LAMBDAS + [](auto &lhs_alt, auto &&rhs_alt) { + constructor::construct_alt( + lhs_alt, lib::forward(rhs_alt).value); + } +#else + ctor {} +#endif + , + lhs, + lib::forward(rhs)); + lhs.index_ = rhs.index_; + } + } +}; + +template +class move_constructor; + +#define MPARK_VARIANT_MOVE_CONSTRUCTOR(move_constructible_trait, definition) \ + template \ + class move_constructor, move_constructible_trait> \ + : public constructor> { \ + using super = constructor>; \ + \ + public: \ + MPARK_INHERITING_CTOR(move_constructor, super) \ + using super::operator=; \ + \ + move_constructor(const move_constructor &) = default; \ + definition ~move_constructor() = default; \ + move_constructor &operator=(const move_constructor &) = default; \ + move_constructor &operator=(move_constructor &&) = default; \ + } + +MPARK_VARIANT_MOVE_CONSTRUCTOR( + Trait::TriviallyAvailable, + move_constructor(move_constructor &&that) = default;); + +MPARK_VARIANT_MOVE_CONSTRUCTOR( + Trait::Available, + move_constructor(move_constructor &&that) noexcept( + lib::all::value...>::value) + : move_constructor(valueless_t{}) { + this->generic_construct(*this, lib::move(that)); + }); + +MPARK_VARIANT_MOVE_CONSTRUCTOR(Trait::Unavailable, + move_constructor(move_constructor &&) = delete;); + +#undef MPARK_VARIANT_MOVE_CONSTRUCTOR + +template +class copy_constructor; + +#define MPARK_VARIANT_COPY_CONSTRUCTOR(copy_constructible_trait, definition) \ + template \ + class copy_constructor, copy_constructible_trait> \ + : public move_constructor> { \ + using super = move_constructor>; \ + \ + public: \ + MPARK_INHERITING_CTOR(copy_constructor, super) \ + using super::operator=; \ + \ + definition copy_constructor(copy_constructor &&) = default; \ + ~copy_constructor() = default; \ + copy_constructor &operator=(const copy_constructor &) = default; \ + copy_constructor &operator=(copy_constructor &&) = default; \ + } + +MPARK_VARIANT_COPY_CONSTRUCTOR( + Trait::TriviallyAvailable, + copy_constructor(const copy_constructor &that) = default;); + +MPARK_VARIANT_COPY_CONSTRUCTOR( + Trait::Available, copy_constructor(const copy_constructor &that) + : copy_constructor(valueless_t{}) { + this->generic_construct(*this, that); + }); + +MPARK_VARIANT_COPY_CONSTRUCTOR( + Trait::Unavailable, copy_constructor(const copy_constructor &) = delete;); + +#undef MPARK_VARIANT_COPY_CONSTRUCTOR + +template +class assignment : public copy_constructor { + using super = copy_constructor; + + public: + MPARK_INHERITING_CTOR(assignment, super) + using super::operator=; + + template + inline /* auto & */ auto emplace(Args &&...args) + -> decltype(this->construct_alt(access::base::get_alt(*this), + lib::forward(args)...)) { + this->destroy(); + auto &result = this->construct_alt(access::base::get_alt(*this), + lib::forward(args)...); + this->index_ = I; + return result; + } + + protected: +#ifndef MPARK_GENERIC_LAMBDAS + template + struct assigner { + template + inline void operator()(ThisAlt &this_alt, ThatAlt &&that_alt) const { + self->assign_alt(this_alt, lib::forward(that_alt).value); + } + assignment *self; + }; +#endif + + template + inline void assign_alt(alt &a, Arg &&arg) { + if (this->index() == I) { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#endif + a.value = lib::forward(arg); +#ifdef _MSC_VER +#pragma warning(pop) +#endif + } else { + struct { + void operator()(std::true_type) const { + this_->emplace(lib::forward(arg_)); + } + void operator()(std::false_type) const { + this_->emplace(T(lib::forward(arg_))); + } + assignment *this_; + Arg &&arg_; + } impl{this, lib::forward(arg)}; + impl(lib::bool_constant < std::is_nothrow_constructible::value || + !std::is_nothrow_move_constructible::value > {}); + } + } + + template + inline void generic_assign(That &&that) { + if (this->valueless_by_exception() && that.valueless_by_exception()) { + // do nothing. + } else if (that.valueless_by_exception()) { + this->destroy(); + } else { + visitation::alt::visit_alt_at( + that.index(), +#ifdef MPARK_GENERIC_LAMBDAS + [this](auto &this_alt, auto &&that_alt) { + this->assign_alt(this_alt, + lib::forward(that_alt).value); + } +#else + assigner { this } +#endif + , + *this, + lib::forward(that)); + } + } +}; + +template +class move_assignment; + +#define MPARK_VARIANT_MOVE_ASSIGNMENT(move_assignable_trait, definition) \ + template \ + class move_assignment, move_assignable_trait> \ + : public assignment> { \ + using super = assignment>; \ + \ + public: \ + MPARK_INHERITING_CTOR(move_assignment, super) \ + using super::operator=; \ + \ + move_assignment(const move_assignment &) = default; \ + move_assignment(move_assignment &&) = default; \ + ~move_assignment() = default; \ + move_assignment &operator=(const move_assignment &) = default; \ + definition \ + } + +MPARK_VARIANT_MOVE_ASSIGNMENT( + Trait::TriviallyAvailable, + move_assignment &operator=(move_assignment &&that) = default;); + +MPARK_VARIANT_MOVE_ASSIGNMENT( + Trait::Available, + move_assignment & + operator=(move_assignment &&that) noexcept( + lib::all<(std::is_nothrow_move_constructible::value && + std::is_nothrow_move_assignable::value)...>::value) { + this->generic_assign(lib::move(that)); + return *this; + }); + +MPARK_VARIANT_MOVE_ASSIGNMENT( + Trait::Unavailable, + move_assignment &operator=(move_assignment &&) = delete;); + +#undef MPARK_VARIANT_MOVE_ASSIGNMENT + +template +class copy_assignment; + +#define MPARK_VARIANT_COPY_ASSIGNMENT(copy_assignable_trait, definition) \ + template \ + class copy_assignment, copy_assignable_trait> \ + : public move_assignment> { \ + using super = move_assignment>; \ + \ + public: \ + MPARK_INHERITING_CTOR(copy_assignment, super) \ + using super::operator=; \ + \ + copy_assignment(const copy_assignment &) = default; \ + copy_assignment(copy_assignment &&) = default; \ + ~copy_assignment() = default; \ + definition copy_assignment &operator=(copy_assignment &&) = default; \ + } + +MPARK_VARIANT_COPY_ASSIGNMENT( + Trait::TriviallyAvailable, + copy_assignment &operator=(const copy_assignment &that) = default;); + +MPARK_VARIANT_COPY_ASSIGNMENT( + Trait::Available, copy_assignment &operator=(const copy_assignment &that) { + this->generic_assign(that); + return *this; + }); + +MPARK_VARIANT_COPY_ASSIGNMENT( + Trait::Unavailable, + copy_assignment &operator=(const copy_assignment &) = delete;); + +#undef MPARK_VARIANT_COPY_ASSIGNMENT + +template +class impl : public copy_assignment> { + using super = copy_assignment>; + + public: + MPARK_INHERITING_CTOR(impl, super) + using super::operator=; + + template + inline void assign(Arg &&arg) { + this->assign_alt(access::base::get_alt(*this), lib::forward(arg)); + } + + inline void swap(impl &that) { + if (this->valueless_by_exception() && that.valueless_by_exception()) { + // do nothing. + } else if (this->index() == that.index()) { + visitation::alt::visit_alt_at( + this->index(), +#ifdef MPARK_GENERIC_LAMBDAS + [](auto &this_alt, auto &that_alt) { + using std::swap; + swap(this_alt.value, that_alt.value); + } +#else + swapper {} +#endif + , + *this, + that); + } else { + impl *lhs = this; + impl *rhs = lib::addressof(that); + if (lhs->move_nothrow() && !rhs->move_nothrow()) { + std::swap(lhs, rhs); + } + impl tmp(lib::move(*rhs)); +#ifdef MPARK_EXCEPTIONS + // EXTENSION: When the move construction of `lhs` into `rhs` throws + // and `tmp` is nothrow move constructible then we move `tmp` back + // into `rhs` and provide the strong exception safety guarantee. + try { + this->generic_construct(*rhs, lib::move(*lhs)); + } catch (...) { + if (tmp.move_nothrow()) { + this->generic_construct(*rhs, lib::move(tmp)); + } + throw; + } +#else + this->generic_construct(*rhs, lib::move(*lhs)); +#endif + this->generic_construct(*lhs, lib::move(tmp)); + } + } + + inline const std::type_info &type() const { + return visitation::alt::visit_alt_at( + this->index(), +#ifdef MPARK_GENERIC_LAMBDAS + [](auto &alt) -> const std::type_info & { return typeid(alt.value); } +#else + typer {} +#endif + , + *this); + } + + private: +#ifndef MPARK_GENERIC_LAMBDAS + struct swapper { + template + inline void operator()(ThisAlt &this_alt, ThatAlt &that_alt) const { + using std::swap; + swap(this_alt.value, that_alt.value); + } + }; + + struct typer { + template + inline const std::type_info &operator()(Alt &alt) const { + return typeid(alt.value); + } + }; +#endif + + inline constexpr bool move_nothrow() const { + return this->valueless_by_exception() || + lib::array{{std::is_nothrow_move_constructible< + Ts>::value...}}[this->index()]; + } +}; + +#undef MPARK_INHERITING_CTOR + +template +struct overload_leaf { + using F = lib::size_constant (*)(T); + operator F() const { return nullptr; } +}; + +template +struct overload_impl { + private: + template + struct impl; + + template + struct impl> : overload_leaf... {}; + + public: + using type = impl>; +}; + +template +using overload = typename overload_impl::type; + +template +using best_match = lib::invoke_result_t, T &&>; + +template +struct is_in_place_index : std::false_type {}; + +template +struct is_in_place_index> : std::true_type {}; + +template +struct is_in_place_type : std::false_type {}; + +template +struct is_in_place_type> : std::true_type {}; + +} // namespace detail + +template +class variant { + static_assert(0 < sizeof...(Ts), + "variant must consist of at least one alternative."); + + static_assert(lib::all::value...>::value, + "variant can not have an array type as an alternative."); + + static_assert(lib::all::value...>::value, + "variant can not have a reference type as an alternative."); + + static_assert(lib::all::value...>::value, + "variant can not have a void type as an alternative."); + + public: + template < + typename Front = lib::type_pack_element_t<0, Ts...>, + lib::enable_if_t::value, int> = 0> + inline constexpr variant() noexcept( + std::is_nothrow_default_constructible::value) + : impl_(in_place_index_t<0>{}) {} + + variant(const variant &) = default; + variant(variant &&) = default; + + template < + typename Arg, + typename Decayed = lib::decay_t, + lib::enable_if_t::value, int> = 0, + lib::enable_if_t::value, int> = 0, + lib::enable_if_t::value, int> = 0, + std::size_t I = detail::best_match::value, + typename T = lib::type_pack_element_t, + lib::enable_if_t::value, int> = 0> + inline constexpr variant(Arg &&arg) noexcept( + std::is_nothrow_constructible::value) + : impl_(in_place_index_t{}, lib::forward(arg)) {} + + template , + lib::enable_if_t::value, int> = 0> + inline explicit constexpr variant( + in_place_index_t, + Args &&...args) noexcept(std::is_nothrow_constructible::value) + : impl_(in_place_index_t{}, lib::forward(args)...) {} + + template < + std::size_t I, + typename Up, + typename... Args, + typename T = lib::type_pack_element_t, + lib::enable_if_t< + std::is_constructible &, Args...>::value, + int> = 0> + inline explicit constexpr variant( + in_place_index_t, + std::initializer_list il, + Args &&...args) noexcept(std:: + is_nothrow_constructible< + T, + std::initializer_list &, + Args...>::value) + : impl_(in_place_index_t{}, il, lib::forward(args)...) {} + + template ::value, + lib::enable_if_t::value, int> = 0> + inline explicit constexpr variant( + in_place_type_t, + Args &&...args) noexcept(std::is_nothrow_constructible::value) + : impl_(in_place_index_t{}, lib::forward(args)...) {} + + template < + typename T, + typename Up, + typename... Args, + std::size_t I = detail::find_index_sfinae::value, + lib::enable_if_t< + std::is_constructible &, Args...>::value, + int> = 0> + inline explicit constexpr variant( + in_place_type_t, + std::initializer_list il, + Args &&...args) noexcept(std:: + is_nothrow_constructible< + T, + std::initializer_list &, + Args...>::value) + : impl_(in_place_index_t{}, il, lib::forward(args)...) {} + + ~variant() = default; + + variant &operator=(const variant &) = default; + variant &operator=(variant &&) = default; + + template , variant>::value, + int> = 0, + std::size_t I = detail::best_match::value, + typename T = lib::type_pack_element_t, + lib::enable_if_t<(std::is_assignable::value && + std::is_constructible::value), + int> = 0> + inline variant &operator=(Arg &&arg) noexcept( + (std::is_nothrow_assignable::value && + std::is_nothrow_constructible::value)) { + impl_.template assign(lib::forward(arg)); + return *this; + } + + template , + lib::enable_if_t::value, int> = 0> + inline T &emplace(Args &&...args) { + return impl_.template emplace(lib::forward(args)...); + } + + template < + std::size_t I, + typename Up, + typename... Args, + typename T = lib::type_pack_element_t, + lib::enable_if_t< + std::is_constructible &, Args...>::value, + int> = 0> + inline T &emplace(std::initializer_list il, Args &&...args) { + return impl_.template emplace(il, lib::forward(args)...); + } + + template ::value, + lib::enable_if_t::value, int> = 0> + inline T &emplace(Args &&...args) { + return impl_.template emplace(lib::forward(args)...); + } + + template < + typename T, + typename Up, + typename... Args, + std::size_t I = detail::find_index_sfinae::value, + lib::enable_if_t< + std::is_constructible &, Args...>::value, + int> = 0> + inline T &emplace(std::initializer_list il, Args &&...args) { + return impl_.template emplace(il, lib::forward(args)...); + } + + inline constexpr bool valueless_by_exception() const noexcept { + return impl_.valueless_by_exception(); + } + + inline constexpr std::size_t index() const noexcept { return impl_.index(); } + + template , + Dummy>::value && + lib::dependent_type, + Dummy>::value)...>::value, + int> = 0> + inline void swap(variant &that) noexcept( + lib::all<(std::is_nothrow_move_constructible::value && + lib::is_nothrow_swappable::value)...>::value) { + impl_.swap(that.impl_); + } + + inline const std::type_info &type() const noexcept { return impl_.type(); } + + private: + detail::impl impl_; + + friend struct detail::access::variant; + friend struct detail::visitation::variant; +}; + +template +inline constexpr bool holds_alternative(const variant &v) noexcept { + return v.index() == I; +} + +template +inline constexpr bool holds_alternative(const variant &v) noexcept { + return holds_alternative::value>(v); +} + +namespace detail { +template +struct generic_get_impl { + constexpr generic_get_impl(int) noexcept {} + + constexpr AUTO_REFREF operator()(V &&v) const + AUTO_REFREF_RETURN(access::variant::get_alt(lib::forward(v)).value) +}; + +template +inline constexpr AUTO_REFREF generic_get(V &&v) + AUTO_REFREF_RETURN(generic_get_impl(holds_alternative(v) + ? 0 + : (throw_bad_variant_access(), + 0))(lib::forward(v))) +} // namespace detail + +template +inline constexpr variant_alternative_t> &get( + variant &v) { + return detail::generic_get(v); +} + +template +inline constexpr variant_alternative_t> &&get( + variant &&v) { + return detail::generic_get(lib::move(v)); +} + +template +inline constexpr const variant_alternative_t> &get( + const variant &v) { + return detail::generic_get(v); +} + +template +inline constexpr const variant_alternative_t> &&get( + const variant &&v) { + return detail::generic_get(lib::move(v)); +} + +template +inline constexpr T &get(variant &v) { + return get::value>(v); +} + +template +inline constexpr T &&get(variant &&v) { + return get::value>(lib::move(v)); +} + +template +inline constexpr const T &get(const variant &v) { + return get::value>(v); +} + +template +inline constexpr const T &&get(const variant &&v) { + return get::value>(lib::move(v)); +} + +namespace detail { + +template +inline constexpr /* auto * */ AUTO generic_get_if(V *v) noexcept + AUTO_RETURN(v &&holds_alternative(*v) + ? lib::addressof(access::variant::get_alt(*v).value) + : nullptr) + +} // namespace detail + +template +inline constexpr lib::add_pointer_t>> +get_if(variant *v) noexcept { + return detail::generic_get_if(v); +} + +template +inline constexpr lib::add_pointer_t< + const variant_alternative_t>> +get_if(const variant *v) noexcept { + return detail::generic_get_if(v); +} + +template +inline constexpr lib::add_pointer_t get_if(variant *v) noexcept { + return get_if::value>(v); +} + +template +inline constexpr lib::add_pointer_t get_if( + const variant *v) noexcept { + return get_if::value>(v); +} + +namespace detail { +template +struct convert_to_bool { + template + inline constexpr bool operator()(Lhs &&lhs, Rhs &&rhs) const { + static_assert( + std::is_convertible, bool>::value, + "relational operators must return a type" + " implicitly convertible to bool"); + return lib::invoke(RelOp{}, lib::forward(lhs), lib::forward(rhs)); + } +}; +} // namespace detail + +template +inline constexpr bool operator==(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using equal_to = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (lhs.index() != rhs.index()) return false; + if (lhs.valueless_by_exception()) return true; + return variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs); +#else + return lhs.index() == rhs.index() && + (lhs.valueless_by_exception() || + variant::visit_value_at(lhs.index(), equal_to{}, lhs, rhs)); +#endif +} + +template +inline constexpr bool operator!=(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using not_equal_to = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (lhs.index() != rhs.index()) return true; + if (lhs.valueless_by_exception()) return false; + return variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs); +#else + return lhs.index() != rhs.index() || + (!lhs.valueless_by_exception() && + variant::visit_value_at(lhs.index(), not_equal_to{}, lhs, rhs)); +#endif +} + +template +inline constexpr bool operator<(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using less = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (rhs.valueless_by_exception()) return false; + if (lhs.valueless_by_exception()) return true; + if (lhs.index() < rhs.index()) return true; + if (lhs.index() > rhs.index()) return false; + return variant::visit_value_at(lhs.index(), less{}, lhs, rhs); +#else + return !rhs.valueless_by_exception() && + (lhs.valueless_by_exception() || lhs.index() < rhs.index() || + (lhs.index() == rhs.index() && + variant::visit_value_at(lhs.index(), less{}, lhs, rhs))); +#endif +} + +template +inline constexpr bool operator>(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using greater = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (lhs.valueless_by_exception()) return false; + if (rhs.valueless_by_exception()) return true; + if (lhs.index() > rhs.index()) return true; + if (lhs.index() < rhs.index()) return false; + return variant::visit_value_at(lhs.index(), greater{}, lhs, rhs); +#else + return !lhs.valueless_by_exception() && + (rhs.valueless_by_exception() || lhs.index() > rhs.index() || + (lhs.index() == rhs.index() && + variant::visit_value_at(lhs.index(), greater{}, lhs, rhs))); +#endif +} + +template +inline constexpr bool operator<=(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using less_equal = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (lhs.valueless_by_exception()) return true; + if (rhs.valueless_by_exception()) return false; + if (lhs.index() < rhs.index()) return true; + if (lhs.index() > rhs.index()) return false; + return variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs); +#else + return lhs.valueless_by_exception() || + (!rhs.valueless_by_exception() && + (lhs.index() < rhs.index() || + (lhs.index() == rhs.index() && + variant::visit_value_at(lhs.index(), less_equal{}, lhs, rhs)))); +#endif +} + +template +inline constexpr bool operator>=(const variant &lhs, + const variant &rhs) { + using detail::visitation::variant; + using greater_equal = detail::convert_to_bool; +#ifdef MPARK_CPP14_CONSTEXPR + if (rhs.valueless_by_exception()) return true; + if (lhs.valueless_by_exception()) return false; + if (lhs.index() > rhs.index()) return true; + if (lhs.index() < rhs.index()) return false; + return variant::visit_value_at(lhs.index(), greater_equal{}, lhs, rhs); +#else + return rhs.valueless_by_exception() || + (!lhs.valueless_by_exception() && + (lhs.index() > rhs.index() || + (lhs.index() == rhs.index() && + variant::visit_value_at(lhs.index(), greater_equal{}, lhs, rhs)))); +#endif +} + +struct monostate {}; + +inline constexpr bool operator<(monostate, monostate) noexcept { return false; } + +inline constexpr bool operator>(monostate, monostate) noexcept { return false; } + +inline constexpr bool operator<=(monostate, monostate) noexcept { return true; } + +inline constexpr bool operator>=(monostate, monostate) noexcept { return true; } + +inline constexpr bool operator==(monostate, monostate) noexcept { return true; } + +inline constexpr bool operator!=(monostate, monostate) noexcept { + return false; +} + +namespace detail { + +template +inline constexpr bool all_impl(const lib::array &bs, std::size_t idx) { + return idx >= N || (bs[idx] && all_impl(bs, idx + 1)); +} + +template +inline constexpr bool all(const lib::array &bs) { + return all_impl(bs, 0); +} + +} // namespace detail + +template +inline constexpr DECLTYPE_AUTO visit(Visitor &&visitor, Vs &&...vs) + DECLTYPE_AUTO_RETURN( + (detail::all(lib::array{ + {!vs.valueless_by_exception()...}}) + ? (void)0 + : throw_bad_variant_access()), + detail::visitation::variant::visit_value(lib::forward(visitor), + lib::forward(vs)...)) + + template + inline auto swap(variant &lhs, + variant &rhs) noexcept(noexcept(lhs.swap(rhs))) + -> decltype(lhs.swap(rhs)) { + lhs.swap(rhs); +} + +namespace detail { + +template +using enabled_type = T; + +namespace hash { + +template +constexpr bool meets_requirements() noexcept { + return std::is_copy_constructible::value && + std::is_move_constructible::value && + lib::is_invocable_r::value; +} + +template +constexpr bool is_enabled() noexcept { + using H = std::hash; + return meets_requirements() && + std::is_default_constructible::value && + std::is_copy_assignable::value && std::is_move_assignable::value; +} + +} // namespace hash + +} // namespace detail + +#undef AUTO +#undef AUTO_RETURN + +#undef AUTO_REFREF +#undef AUTO_REFREF_RETURN + +#undef DECLTYPE_AUTO +#undef DECLTYPE_AUTO_RETURN + +} // namespace paddle + +namespace std { + +template +struct hash, + paddle::lib::enable_if_t>()...>::value>>> { + using argument_type = paddle::variant; + using result_type = std::size_t; + + inline result_type operator()(const argument_type &v) const { + using paddle::detail::visitation::variant; + std::size_t result = + v.valueless_by_exception() + ? 299792458 // Random value chosen by the universe upon creation + : variant::visit_alt( +#ifdef MPARK_GENERIC_LAMBDAS + [](const auto &alt) { + using alt_type = paddle::lib::decay_t; + using value_type = paddle::lib::remove_const_t< + typename alt_type::value_type>; + return hash{}(alt.value); + } +#else + hasher {} +#endif + , + v); + return hash_combine(result, hash{}(v.index())); + } + + private: +#ifndef MPARK_GENERIC_LAMBDAS + struct hasher { + template + inline std::size_t operator()(const Alt &alt) const { + using alt_type = paddle::lib::decay_t; + using value_type = + paddle::lib::remove_const_t; + return hash{}(alt.value); + } + }; +#endif + + static std::size_t hash_combine(std::size_t lhs, std::size_t rhs) { + return lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2); + } +}; + +template <> +struct hash { + using argument_type = paddle::monostate; + using result_type = std::size_t; + + inline result_type operator()(const argument_type &) const noexcept { + return 66740831; // return a fundamentally attractive random value. + } +}; + +} // namespace std + +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 9 +#pragma GCC diagnostic pop +#endif diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.h new file mode 100644 index 0000000000000000000000000000000000000000..bc74bf644f4b628018d7a9103ba63320abc466d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_H +#define DNNL_H + +#include "oneapi/dnnl/dnnl.h" + +#endif /* DNNL_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.hpp b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3c8835cacf35effc8e5c89a041f8bdcbe8203daa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_HPP +#define DNNL_HPP + +#include "oneapi/dnnl/dnnl.hpp" + +#endif /* DNNL_HPP */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_config.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_config.h new file mode 100644 index 0000000000000000000000000000000000000000..48925e1e3ab49ae135c6e9c4c501aa2f5e030913 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_config.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_CONFIG_H +#define DNNL_CONFIG_H + +#include "oneapi/dnnl/dnnl_config.h" + +#endif /* DNNL_CONFIG_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_debug.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_debug.h new file mode 100644 index 0000000000000000000000000000000000000000..5044971832bbbe56127920a527508b207a803eea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_debug.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_DEBUG_H +#define DNNL_DEBUG_H + +#include "oneapi/dnnl/dnnl_debug.h" + +#endif /* DNNL_DEBUG_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.h new file mode 100644 index 0000000000000000000000000000000000000000..ad731150b28babe7bd5a911acd8de70c57e85254 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_OCL_H +#define DNNL_OCL_H + +#include "oneapi/dnnl/dnnl_ocl.h" + +#endif /* DNNL_OCL_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.hpp b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..150254227927f032195f71451bc5c9768d7bc627 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_ocl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_OCL_HPP +#define DNNL_OCL_HPP + +#include "oneapi/dnnl/dnnl_ocl.hpp" + +#endif /* DNNL_OCL_HPP */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.h new file mode 100644 index 0000000000000000000000000000000000000000..4501598c2f461021f0fa818e95fd1972ce2d3ace --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_SYCL_H +#define DNNL_SYCL_H + +#include "oneapi/dnnl/dnnl_sycl.h" + +#endif /* DNNL_SYCL_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.hpp b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2479ceca3544363779e9d5d53028c93712a091af --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_SYCL_HPP +#define DNNL_SYCL_HPP + +#include "oneapi/dnnl/dnnl_sycl.hpp" + +#endif /* DNNL_SYCL_HPP */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl_types.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a4a854a4cf138103f4c53030083e119cc0732cf1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_sycl_types.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_SYCL_TYPES_H +#define DNNL_SYCL_TYPES_H + +#include "oneapi/dnnl/dnnl_sycl_types.h" + +#endif /* DNNL_SYCL_TYPES_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..e27e584a65ed16740d4fde93da3a1a049dd111aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_H +#define DNNL_THREADPOOL_H + +#include "oneapi/dnnl/dnnl_threadpool.h" + +#endif /* DNNL_THREADPOOL_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.hpp b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6aa65d60129389ab2b5e3bec1b5c4d7bee495081 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_HPP +#define DNNL_THREADPOOL_HPP + +#include "oneapi/dnnl/dnnl_threadpool.hpp" + +#endif /* DNNL_THREADPOOL_HPP */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool_iface.hpp b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool_iface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..82639005efcd9477843c9e486b102fbbf34ef29b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_threadpool_iface.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_IFACE_HPP +#define DNNL_THREADPOOL_IFACE_HPP + +#include "oneapi/dnnl/dnnl_threadpool_iface.hpp" + +#endif /* DNNL_THREADPOOL_IFACE_HPP */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_types.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..6f4261b712dc37ec2416ba60c0c68bb30f6995e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_types.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_TYPES_H +#define DNNL_TYPES_H + +#include "oneapi/dnnl/dnnl_types.h" + +#endif /* DNNL_TYPES_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_version.h b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_version.h new file mode 100644 index 0000000000000000000000000000000000000000..32a3d5cf839b1d593f069520febfd60b323730e9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/include/third_party/dnnl_version.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* 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. +*******************************************************************************/ + +#ifndef DNNL_VERSION_H +#define DNNL_VERSION_H + +#include "oneapi/dnnl/dnnl_version.h" + +#endif /* DNNL_VERSION_H */ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68c7db054991a02b7c0a098b07680b9f6a193436 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/__init__.py @@ -0,0 +1,56 @@ +# 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. + +from .optimizer import LookAhead # noqa: F401 +from .optimizer import ModelAverage # noqa: F401 +from .optimizer import DistributedFusedLamb # noqa: F401 +from .checkpoint import auto_checkpoint # noqa: F401 +from ..fluid.layer_helper import LayerHelper # noqa: F401 +from .operators import softmax_mask_fuse_upper_triangle # noqa: F401 +from .operators import softmax_mask_fuse # noqa: F401 +from .operators import graph_send_recv +from .operators import graph_khop_sampler +from .operators import graph_sample_neighbors +from .operators import graph_reindex +from .tensor import segment_sum +from .tensor import segment_mean +from .tensor import segment_max +from .tensor import segment_min +from .passes import fuse_resnet_unit_pass + +from . import autograd #noqa: F401 +from . import autotune #noqa: F401 +from . import nn #noqa: F401 +from . import asp #noqa: F401 + +from ..fluid.layers.loss import identity_loss + +from ..fluid.incubate import fleet +from . import xpu + +__all__ = [ + 'LookAhead', + 'ModelAverage', + 'softmax_mask_fuse_upper_triangle', + 'softmax_mask_fuse', + 'graph_send_recv', + 'graph_khop_sampler', + 'graph_sample_neighbors', + 'graph_reindex', + 'segment_sum', + 'segment_mean', + 'segment_max', + 'segment_min', + 'identity_loss', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/asp/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/asp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a56fd117c41de59a8d5162fbc5f7533691c6e1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/asp/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from ...fluid.contrib.sparsity import calculate_density #noqa: F401 +from ...fluid.contrib.sparsity import decorate #noqa: F401 +from ...fluid.contrib.sparsity import prune_model #noqa: F401 +from ...fluid.contrib.sparsity import set_excluded_layers #noqa: F401 +from ...fluid.contrib.sparsity import reset_excluded_layers #noqa: F401 + +__all__ = [ #noqa + 'calculate_density', 'decorate', 'prune_model', 'set_excluded_layers', + 'reset_excluded_layers' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ff3b18d4d4945af4dfb8a243f5ad32378b014a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/__init__.py @@ -0,0 +1,22 @@ +# Copyright (c) 2021 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. +from .functional import Hessian, Jacobian, jvp, vjp +from .primapi import forward_grad, grad +from .primx import prim2orig +from .utils import disable_prim, enable_prim, prim_enabled + +__all__ = [ # noqa + 'vjp', 'jvp', 'Jacobian', 'Hessian', 'enable_prim', 'disable_prim', + 'forward_grad', 'grad' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/functional.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..79ba7d33097107404ed1327a9b9dfc4aaed59527 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/functional.py @@ -0,0 +1,677 @@ +# Copyright (c) 2021 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. + +import functools +import typing + +import paddle +from paddle.fluid import framework +from paddle.incubate.autograd import primapi, utils + + +def vjp(func, xs, v=None): + r"""Computes the Vector-Jacobian product, a functional form of + reverse mode automatic differentiation. + + Warning: + This API is in beta, the signatures could be changed in future version. + + Args: + func(Callable): A function that takes ``xs`` as inputs parameter and + returns a sequence of Tensors or a Tensor. + xs(Tensor|Sequence[Tensor]): Used as positional arguments to evaluate + ``func``. ``xs`` is accepted as one Tensor or a sequence of Tensors. + v(Tensor|Sequence[Tensor]|None, optional): The cotangent vector invovled + in the VJP computation. ``v`` matches the size and shape of + ``func`` 's output. Defaults to None, which is equivalent to all + ones the same size of ``func`` 's output. + + Returns: + output(tuple): + + - func_out(Tensor|tuple[Tensor]): The output of ``func(xs)`` . + - vjp(Tensor|tuple[Tensor]): The vjp result. + + Examples: + + .. code-block:: python + + import paddle + + def func(x): + return paddle.matmul(x, x) + + x = paddle.ones(shape=[2, 2], dtype='float32') + _, vjp_result = paddle.incubate.autograd.vjp(func, x) + print(vjp_result) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[4., 4.], + # [4., 4.]]) + + v = paddle.to_tensor([[1.0, 0.0], [0.0, 0.0]]) + _, vjp_result = paddle.incubate.autograd.vjp(func, x, v) + print(vjp_result) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[2., 1.], + # [1., 0.]]) + """ + _check_inputs(func, xs, v) + + # ``_seprate`` breaks the dependencies between ``xs`` and other + # variables. See more ``_seprate`` . + if paddle.fluid._non_static_mode() or not utils.prim_enabled(): + xs, v = _separate(xs), _separate(v) + ys = func(*xs) if isinstance(xs, typing.Sequence) else func(xs) + _check_v_shape(v, ys) + + return ys, _grad(ys, xs, v) + + +def jvp(func, xs, v=None): + r""" + Computes the Jacobian-Vector product for a function at the given + inputs and a vector in the tangent space induced by the inputs. + + Warning: + This API is in beta, the signatures could be changed in future version. + + Args: + func(Callable): The ``func`` takes as input a Tensor or a Sequence + of Tensors and returns a Tensor or a Sequence of Tensors. + xs(Tensor|Sequence[Tensor]): Used as positional arguments to + evaluate ``func``. The ``xs`` is accepted as one Tensor or a + Sequence of Tensors. + v(Tensor|Sequence[Tensor]|None, Optional): The tangent vector invovled + in the JVP computation. The ``v`` matches the size and shape of + ``xs`` . Default value is None and in this case is equivalent to + all ones the same size of ``xs`` . + + Returns: + output(tuple): + + - func_out(Tensor|tuple[Tensor]): The output of ``func(xs)`` . + - jvp(Tensor|tuple[Tensor]): The jvp result. + + Examples: + + .. code-block:: python + + import paddle + + + def func(x): + return paddle.matmul(x, x) + + + x = paddle.ones(shape=[2, 2], dtype='float32') + _, jvp_result = paddle.incubate.autograd.jvp(func, x) + print(jvp_result) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[4., 4.], + # [4., 4.]]) + v = paddle.to_tensor([[1.0, 0.0], [0.0, 0.0]]) + _, jvp_result = paddle.incubate.autograd.jvp(func, x, v) + print(jvp_result) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[2., 1.], + # [1., 0.]]) + + """ + _check_inputs(func, xs, v) + # ``_seprate`` breaks the dependencies between ``xs`` and other + # variables. See more ``_seprate`` . + if paddle.fluid._non_static_mode() or not utils.prim_enabled(): + xs, v = _separate(xs), _separate(v) + ys = func(*xs) if isinstance(xs, typing.Sequence) else func(xs) + _check_v_shape(v, xs) + + if not paddle.fluid._non_static_mode() and utils.prim_enabled(): + return ys, primapi.forward_grad(ys, xs, v) + else: + return ys, _double_backward_trick(ys, xs, v) + + +def _double_backward_trick(ys, xs, v): + """Double backward trick for computing ``jvp`` by ``vjp`` + see details: https://j-towns.github.io/2017/06/12/A-new-trick.html + """ + # The value of ys_grad is not important, it can be any random value in + # theory, but it's required to set stop_gradient=False. + ys_grad = _zeros_like_with_grad(ys) + xs_grad = _grad(ys, xs, ys_grad) + return _grad(xs_grad, ys_grad, v) + + +def _zeros_like_with_grad(xs): + """Create a zero or zeros sequence Tensor like ``xs`` with a flag + ``stop_graident=False`` . + """ + if not isinstance(xs, typing.Sequence): + ys = paddle.zeros_like(xs) + ys.stop_gradient = False + else: + ys = [] + for x in xs: + y = paddle.zeros_like(x) + y.stop_gradient = False + ys.append(y) + return ys + + +class Jacobian(object): + r""" + Computes the Jacobian matrix of a given function. + + If the function has multiple inputs and multiple outputs, during internal + implementation, all input tensors are concatenated after being flatten, + the batch dimension is retained, and the output is subject to the same + processing rules. + + Once the Jacobian ``J`` is constructed, you can use a multidimensional index + to retrieve the submatrix of ``J``, as same as slicing a Tensor. The + submatrix is lazily evaluated along row axis, and will be cached once + evaluated. + + For examples, supposing ``is_batched=True``, you can retrieve the submatrix + by following methods: + + * J[:], retrieving the full matrix. + * J[:, :, j], retrieving the partial derivatives w.r.t. the j'th input + variable. + * J[:, i, :], retrieving the partial derivatives w.r.t. the i'th output + variable. + * J[:, i, j], retrieving the partial derivatives w.r.t. the i'th output + variable and the j'th input variable. + + Notes: + + Eclipsis index is not supported currently. + + Warning: + This API is in beta, the signatures could be changed in future version. + + Args: + + func (Callable): A python function that takes a Tensor or a sequence of + Tensors as inputs(the first dimension is batch size) and + returns a Tensor a sequence of Tensors. + xs (Tensor|Sequence[Tensor]): The input to the function ``func`` . + is_batched (bool): If true, the first axis is batch axis. Defaults to + False. + + Returns: + + Jacobian (Object): A python object retains the Jacobian matrix. + + Examples: + + .. code-block:: python + + import paddle + + + def func(x, y): + return paddle.matmul(x, y) + + + x = paddle.to_tensor([[1., 2.], [3., 4.]]) + J = paddle.incubate.autograd.Jacobian(func, [x, x]) + print(J[:, :]) + # Tensor(shape=[4, 8], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[1., 3., 0., 0., 1., 0., 2., 0.], + # [2., 4., 0., 0., 0., 1., 0., 2.], + # [0., 0., 1., 3., 3., 0., 4., 0.], + # [0., 0., 2., 4., 0., 3., 0., 4.]]) + + print(J[0, :]) + # Tensor(shape=[8], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [1., 3., 0., 0., 1., 0., 2., 0.]) + print(J[:, 0]) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [1., 2., 0., 0.]) + + """ + + def __init__(self, func, xs, is_batched=False): + if not is_batched: + self._jacobian = _JacobianNoBatch(func, xs) + else: + self._jacobian = _JacobianBatchFirst(func, xs) + + def __getitem__(self, indexes): + return self._jacobian[indexes] + + @property + def shape(self): + """The shape of flattened Jacobian matrix. + """ + return self._jacobian.shape + + +class Hessian(object): + """ + Computes the Hessian matrix with a given ``func`` with respect to ``xs`` . + + If the function has multiple inputs, during internal implementation, + all input tensors are concatenated after being flatten, the batch dimension + is retained. + + The Hessian submatrix is lazily evaluated, and can be retrieved with a + multidimensional indexes. See details ``Jacobian`` . + + Warning: + This API is in beta, the signatures could be changed in future version. + + Args: + func (Callable): A python function that takes a Tensor or a Tensor + sequence as inputs and returns a Tensor with shape + ``[batch_size, 1]`` with batch or ``[1]`` without batch. + xs (Tensor|Sequence(Tensor)): The input Tensor or Tensor sequence of + the function ``func``. + is_batched (bool): If true, the first axis is batch axis. Defaults to + False. + + Returns: + + Hessian (Object): A python object retains the Hessian matrix. + + + Examples: + + .. code-block:: python + + import paddle + + + def reducer(x): + return paddle.sum(x * x) + + + x = paddle.rand([2, 2]) + h = paddle.incubate.autograd.Hessian(reducer, x) + print(h[:]) + # Tensor(shape=[4, 4], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[2., 0., 0., 0.], + # [0., 2., 0., 0.], + # [0., 0., 2., 0.], + # [0., 0., 0., 2.]]) + """ + + def __init__(self, func, xs, is_batched=False): + + def _jac_func(*xs): + jac = Jacobian(func, xs, is_batched=is_batched) + if (is_batched and jac.shape[1] != 1) or (not is_batched + and jac.shape[0] != 1): + raise RuntimeError( + "The function given to Hessian shoud return as single element Tensor or batched single element Tensor." + ) + return jac[:, 0, :] if is_batched else jac[0, :] + + self.symbolic = Jacobian(_jac_func, xs, is_batched=is_batched) + + def __getitem__(self, indexes): + return self.symbolic[indexes] + + @property + def shape(self): + """The shape of flattened Hessian matrix. + """ + return self.symbolic.shape + + +class _Jacobian(object): + """The base class for computing Jacobian matrix. + + ``_Jacobian`` implementes the core logic of multidimensional index and lazy + evaluation for Jacobian matrix, subclass only need to overwrite following + methods: + + * ``_lazy_axis()``, return the axis along which will be lazy + evaluating. + * ``_flatten(xs)``, flattens the inputs ``xs``. + * ``_evaluate(index)``, evaluates one slice along ``_lazy_axis`` . + + Notes: + + Because currently PaddlePaddle only support reverse differentiation by + ``paddle.grad``, so lazy evaluation is only supported along the row of + Jacobian matrix, which means that slicing along row will get better + performance. + + """ + + def __init__(self, func, xs): + # Skip separating in prim mode temporarily, as detach and clone are not + # primitive operators. + if not paddle.fluid._non_static_mode() and utils.prim_enabled(): + self._xs = xs + else: + self._xs = _separate(xs) + self._ys = func(*utils.as_tensors(self._xs)) + self._flatten_xs = self._flatten(utils.as_tensors(self._xs)) + self._flatten_ys = self._flatten(utils.as_tensors(self._ys)) + self._cache = {} + + @property + def shape(self): + raise NotImplementedError + + @property + def _lazy_axis(self): + """"The axis of lazily evaluated.""" + raise NotImplementedError + + def _lazy_indexes(self, indexes): + idx = indexes[self._lazy_axis] + return (idx, ) if isinstance(idx, int) else tuple( + range(idx.start, idx.stop, idx.step)) + + def _flatten(self, xs): + raise NotImplementedError + + def _shifted_indexes(self, indexes, lazy_axis_size=0): + idx = indexes[self._lazy_axis] + shifted_lazy_axis_idx = 0 if isinstance(idx, int) else slice( + 0, lazy_axis_size, 1) + return indexes[:self._lazy_axis] + ( + shifted_lazy_axis_idx, ) + indexes[self._lazy_axis + 1:] + + def __getitem__(self, indexes): + indexes = _multi_index(indexes, self.shape) + + if isinstance(indexes[self._lazy_axis], int): + other_indexes = indexes[:self._lazy_axis] + \ + indexes[self._lazy_axis+1:] + return self._cached_evaluate( + indexes[self._lazy_axis])[other_indexes] + lazy_indexes = self._lazy_indexes(indexes) + # Using concat and reshape to replace stack operator temporarily, as + # it is not a primitive operator. + shape = list(self.shape) + shape[self._lazy_axis] = len(lazy_indexes) + part_jac = paddle.concat( + [self._cached_evaluate(i) for i in lazy_indexes], + axis=self._lazy_axis).reshape(shape) + return part_jac[self._shifted_indexes(indexes, len(lazy_indexes))] + + def _cached_evaluate(self, k): + v = self._cache.get(k) + if v is None: + v = self._evaluate(k) + self._cache[k] = v + return v + + def _evaluate(self, index): + """Evaluate one slice at along lazy axis.""" + raise NotImplementedError + + +class _JacobianNoBatch(_Jacobian): + """Compute Jacobian matrix without batch dimension. + Suppose the mapping is :math:`f: R^M \to R^N`, the output shape is + ``(N, M)`` . + """ + + def __init__(self, func, xs): + super(_JacobianNoBatch, self).__init__(func, xs) + + @property + def shape(self): + return (self._flatten_ys.shape[0], self._flatten_xs.shape[0]) + + @property + def _lazy_axis(self): + return 0 + + def _flatten(self, xs): + return paddle.concat(tuple(x.reshape((-1, )) for x in xs)) + + def _evaluate(self, row_index): + return self._flatten(_grad( + self._flatten_ys[row_index], + self._xs, + )) + + +class _JacobianBatchFirst(_Jacobian): + """Compute Jacobian matrix with batch at first axis. + Suppose the mapping is :math:`f: R^{B,M} \to R^{B,N}`, the output shape is + ``(B, N, M)`` . + """ + + def __init__(self, func, xs): + super(_JacobianBatchFirst, self).__init__(func, xs) + + @property + def shape(self): + return (self._flatten_xs.shape[0], self._flatten_ys.shape[1], + self._flatten_xs.shape[1]) + + @property + def _lazy_axis(self): + return 1 + + def _flatten(self, xs): + return paddle.concat( + tuple(x.reshape((x.shape[0], -1)) for x in utils.as_tensors(xs)), 1) + + def _evaluate(self, row_index): + return self._flatten(_grad(self._flatten_ys[:, row_index], self._xs)) + + +def _multi_index(indexes, shape): + """A tool for parsing N-dimensional index into a standard format. + + Currently supporting following input format: + * ([positive|negative|slice], ...), the right-most elements can be + omited. + + The standard format after converted is slice tuple which contains N elements: + * ([positive|slice], ..., [positive|slice]) + + Notes: + Ellipsis indexes such as ``(..., i), (i, ...)`` is not supported. + + Args: + indexes (tuple): The input indexes. + shape (tuple): The input shape. + + Returns: + tuple: The standard format index as the above description. + """ + indexes = indexes if isinstance(indexes, typing.Sequence) else (indexes, ) + if any(isinstance(i, type(Ellipsis)) for i in indexes): + raise IndexError('Ellipsis index currently is not supported.') + # Fill the right-most elements. + indexes = indexes + (slice(0, None, None), ) * (len(shape) - len(indexes)) + # Convert to positive index. + positive_indexes = [] + for i, index in enumerate(indexes): + if isinstance(index, slice): + index = slice(index.start or 0, index.stop or shape[i], index.step + or 1) + positive_indexes.append( + slice( + index.start + shape[i] if index.start < 0 else index.start, + index.stop + shape[i] if index.stop < 0 else index.stop, + # Negative step means index backward, no need to convert to + # positive interger. + index.step)) + elif isinstance(index, int): + positive_indexes.append(index + shape[i] if index < 0 else index) + else: + raise TypeError(f'Not supported index type {index}.') + return tuple(positive_indexes) + + +def _replace_none_with_zero_tensor(xs, refs): + if xs is None: + xs = paddle.zeros_like(refs) + xs.stop_gradient = refs.stop_gradient + return xs + elif isinstance(xs, typing.Sequence): + return tuple( + _replace_none_with_zero_tensor(x, refs[i]) + for i, x in enumerate(xs)) + else: + return xs + + +def _grad(ys, xs, v=None): + """A gradient function that can be used in dynamic graph and static graph. + + The ``grad`` combines ``paddle.grad`` used in dynamic graph and + ``paddle.static.gradients`` used in static graph, and do following changes: + + * The ``allow_unused`` flag is removed and set defaults to true internally, + none in outputs will be replaced by zero tensor. + * The ``create_graph`` flag is removed and set defaults to true internally, + only makes sense in dynamic graph. + * When xs is a single Tensor, ``paddle.grad`` returns a list which only + contains one Tensor. It may confuse users, thus in this case we improve + to return a single Tensor in _grad interface. + + Args: + ys (Tensor|Sequence[Tensor]): The output tensor or tensor sequence of + the graph to compute gradients. + xs (Tensor|Sequence[Tensor]): The input tensor or tensor sequence of the graph to + compute gradients. The returned values of this API are the + gradients of inputs . + v (Tensor|Sequence[Tensor]|None,optional): The initial gradient values + of outputs . If grad_outputs is None, the initial gradient values of + outputs would be Tensors filled with 1; if grad_outputs is not None, + it must have the same length as outputs , and in this case, the + initial gradient value of the i-th outputs would be: (1) a Tensor + filled with 1 when the i-th element of grad_outputs is None; + (2) the i-th element of grad_outputs when the i-th element of + grad_outputs is a Tensor. Default None. + + Returns: + Tensor|tuple[Tensor]: Tensor or a tuple of Tensors, whose length is the + same as the Tensor number inside inputs, and the i-th returned + Tensor is the sum of gradients of outputs with respect to the i-th + inputs. + """ + if paddle.fluid._non_static_mode(): + # paddle.grad returns a list though the inputs is a signle Tensor. The + # follow code snippet fixes the problem by return the first element of + # xs_grad when the xs is a signle Tensor. + xs_grad = paddle.grad(ys, xs, v, create_graph=True, allow_unused=True) + if isinstance(xs, paddle.fluid.framework.Variable) and isinstance( + xs_grad, typing.Sequence) and len(xs_grad) > 0: + xs_grad = xs_grad[0] + else: + xs_grad = paddle.incubate.autograd.grad(ys, xs, v) + return _replace_none_with_zero_tensor(xs_grad, xs) + + +def _separate(xs): + """ + ``_separate`` separates ``xs`` from the computation graph through ``clone`` + or ``deteach`` . + + Interally, ``paddle.grad(xs, ys)`` is stateful API implemented based on + computional graph, which will reduce gradients along all path from ys to xs. + + However, funcional autograd API such as ``vjp``, ``jvp`` is stateless, and + only compute gradients with a given ``func`` . + + For example, given a ``func`` :math:`y0=f(x0)`, supposing forward path is: + ``x0 -> y0``, ``x0 -> x1 -> y0`` . + ``paddle.grad(y0, x0)`` will reduce gradients along ``y0->x0`` and + ``y0->x1->x0``, and ``vjp`` only need reduce along ``y0->x0``. + + So, it's needed to clone or detach xs for breaking the dependencies with + other variables. + + Examples: + + .. code-block:: python + + import paddle + from paddle.autograd.functional import _separate + + + def func(x, y): + return x * y + + + x = paddle.ones((1,)) + x.stop_gradient = False + + y = func(x, x) + print(paddle.grad(y, x)) + # [Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2.])] + + x1, x2 = _separate((x, x)) + y = func(x1, x2) + print(paddle.grad(y, x1)) + # [Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.])] + + """ + if isinstance(xs, typing.Sequence): + return tuple(_single_separate(x) for x in xs) + else: + return _single_separate(xs) + + +def _single_separate(x): + if x is None: # x maybe none because grad input's v defaults to none. + return x + if not x.stop_gradient: + return paddle.assign(x) + else: # use detach to share memory when no need gradients. + x = x.detach() + x.stop_gradient = False + return x + return x + + +def _check_inputs(func, xs, v=None): + if not callable(func): + raise TypeError(f"Expected 'fun' is Callable, but got {type(func)}.") + + if not isinstance(xs, (framework.Variable, typing.Sequence)): + raise TypeError(f"Expected 'xs' is a Tensor|Sequence[Tensor]," + f"but got {type(xs)}.") + if isinstance(xs, typing.Sequence) and not all( + isinstance(x, framework.Variable) for x in xs): + raise TypeError("All elements of 'xs' shoule be Tensor.") + + if not isinstance(v, (framework.Variable, typing.Sequence, type(None))): + raise TypeError( + f"Expected 'v' is Tensor|Sequence[Tensor]|None, but got {type(v)}.") + + if isinstance(v, typing.Sequence) and not all( + isinstance(e, framework.Variable) for e in v): + raise TypeError("All elements of 'xs' shoule be Tensor.") + + +def _check_v_shape(v, refs): + if v is None: + return + + v, refs = utils.as_tensors(v), utils.as_tensors(refs) + if len(refs) != len(v): + raise RuntimeError(f"The argument v is a tuple of invalid length:" + f"should be {len(refs)} but got {len(v)}.") + + for index, (element_v, element_ref) in enumerate(zip(v, refs)): + if element_v.shape != element_ref.shape: + raise RuntimeError( + f"The v[{index}] has invalid shape: should " + f"be {element_ref.shape} but got {element_v.shape}.") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primapi.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primapi.py new file mode 100644 index 0000000000000000000000000000000000000000..18a06af5dca7fccc7cc6645e92a6c8397c851182 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primapi.py @@ -0,0 +1,213 @@ +# Copyright (c) 2022 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. + +import typing + +from paddle.fluid import backward, framework +from paddle.incubate.autograd import primx, utils + + +@framework.static_only +def forward_grad(outputs, inputs, grad_inputs=None): + """Forward mode of automatic differentiation. + + Note: + **ONLY available in the static mode and primitive operators.** + + Args: + outputs(Tensor|Sequence[Tensor]): The output tensor or tensors. + inputs(Tensor|Sequence[Tensor]): The input tensor or tensors. + grad_inputs(Tensor|Sequence[Tensor]): Optional, the gradient Tensor or + Tensors of inputs which has the same shape with inputs, Defaults to + None, in this case is equivalent to all ones. + + Returns: + grad_outputs(Tensor|Sequence[Tensor]): The gradients for outputs. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + paddle.enable_static() + paddle.incubate.autograd.enable_prim() + + startup_program = paddle.static.Program() + main_program = paddle.static.Program() + + with paddle.static.program_guard(main_program, startup_program): + x = paddle.static.data('x', shape=[1], dtype='float32') + y = x * x + y_grad = paddle.incubate.autograd.forward_grad(y, x) + paddle.incubate.autograd.prim2orig() + + exe = paddle.static.Executor() + exe.run(startup_program) + y_grad = exe.run(main_program, feed={'x': np.array([2.]).astype('float32')}, fetch_list=[y_grad]) + print(y_grad) + # [array([4.], dtype=float32)] + + paddle.incubate.autograd.disable_prim() + paddle.disable_static() + """ + if not utils.prim_enabled(): + raise RuntimeError( + 'forward_grad must be running on primitive' + 'operators, use enable_prim to turn it on.' + ) + + if not isinstance(outputs, (framework.Variable, typing.Sequence)): + raise TypeError( + f'Expected outputs is Tensor|Sequence[Tesnor], ' + f'but got {type(outputs)}.' + ) + + if not isinstance(inputs, (framework.Variable, typing.Sequence)): + raise TypeError( + f'Expected inputs is Tensor|Sequence[Tesnor], ' + f'but got {type(inputs)}.' + ) + + ys, xs, xs_dot = ( + utils.as_tensors(outputs), + utils.as_tensors(inputs), + utils.as_tensors(grad_inputs), + ) + + block = framework.default_main_program().current_block() + if any(x.block != block for x in xs + ys): + raise RuntimeError( + 'Variable in inputs and targets should exist in current block of ' + 'main program.' + ) + + primx.orig2prim(block) + ad = primx.Transform(ys[0].block) + _, ys_dot = ad.linearize(xs, ys, xs_dot) + + return ys_dot[0] if isinstance(outputs, framework.Variable) else ys_dot + + +@framework.static_only +def grad(outputs, inputs, grad_outputs=None): + """Reverse mode of automatic differentiation. + + Note: + **ONLY available in the static mode and primitive operators** + + Args: + outputs(Tensor|Sequence[Tensor]): The output Tensor or Tensors. + inputs(Tensor|Sequence[Tensor]): The input Tensor or Tensors. + grad_outputs(Tensor|Sequence[Tensor]): Optional, the gradient Tensor or + Tensors of outputs which has the same shape with outputs, Defaults + to None, in this case is equivalent to all ones. + + Returns: + grad_inputs(Tensor|Tensors): The gradients for inputs. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + + paddle.enable_static() + paddle.incubate.autograd.enable_prim() + + startup_program = paddle.static.Program() + main_program = paddle.static.Program() + with paddle.static.program_guard(main_program, startup_program): + x = paddle.static.data('x', shape=[1], dtype='float32') + x.stop_gradients = False + y = x * x + x_grad = paddle.incubate.autograd.grad(y, x) + paddle.incubate.autograd.prim2orig() + + exe = paddle.static.Executor() + exe.run(startup_program) + x_grad = exe.run(main_program, feed={'x': np.array([2.]).astype('float32')}, fetch_list=[x_grad]) + print(x_grad) + # [array([4.], dtype=float32)] + + paddle.incubate.autograd.disable_prim() + paddle.disable_static() + """ + if not utils.prim_enabled(): + grad_inputs = backward.gradients(outputs, inputs, grad_outputs) + # backward.gradients returns a list though the inputs is a signle Tensor. + # The follow code snippet fixes the problem by return the first element + # of grad_inputs when the inputs is a signle Tensor. + if ( + isinstance(inputs, framework.Variable) + and isinstance(grad_inputs, typing.Sequence) + and len(grad_inputs) > 0 + ): + return grad_inputs[0] + else: + return grad_inputs + + if not isinstance(outputs, (framework.Variable, typing.Sequence)): + raise TypeError( + f'Expected outputs is Tensor|Sequence[Tesnor], ' + f'but got {type(outputs)}.' + ) + + if not isinstance(inputs, (framework.Variable, typing.Sequence)): + raise TypeError( + f'Expected inputs is Tensor|Sequence[Tesnor], ' + f'but got {type(inputs)}.' + ) + + ys, xs, ys_bar = ( + utils.as_tensors(outputs), + utils.as_tensors(inputs), + utils.as_tensors(grad_outputs), + ) + block = framework.default_main_program().current_block() + if any((x is not None and x.block != block) for x in xs + ys): + raise RuntimeError( + 'Variable in inputs and outputs should be None or in current block of main program' + ) + + # TODO(Tongxin) without any prior knowledge about whether the program + # is completely lowered to primitive ops, it's mandatory to run the lowering + # pass once and again. This is obviously inefficient and needs to be + # optimized. + primx.orig2prim(block) + ad = primx.Transform(block) + xs_dot, ys_dot = ad.linearize(xs, ys) + if any(var is None for var in ys_dot): + raise RuntimeError( + 'Grads cannot be computed. The given outputs does not depend on inputs' + ) + ys_bar, xs_bar = ad.transpose(ys_dot, xs_dot, ys_bar) + + # remove xs_dot and their constructor ops + op_indexes = [] + for var in xs_dot: + if var is not None: + op_index = block.ops.index(var.op) + if op_index < 0: + raise ValueError( + f'op_index should be greater than or equal to 0, but op_index={op_index}.' + ) + op_indexes.append(op_index) + + ad.erase_ops(sorted(op_indexes)) + ad.erase_dots(xs_dot) + + return xs_bar[0] if isinstance(inputs, framework.Variable) else xs_bar diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primops.py new file mode 100644 index 0000000000000000000000000000000000000000..636dc8922049053daf4546823864acc483e45b02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primops.py @@ -0,0 +1,396 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper + +from .primreg import REGISTER_FN + + +def _simple_unop(helper): + optype = helper.layer_type + x, out = tuple(map(helper.kwargs.get, ('x', 'out'))) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=optype, inputs={'X': x}, outputs={'Y': out}, attrs={}) + return out + + +def _simple_binop(helper): + optype = helper.layer_type + x, y, out = tuple(map(helper.kwargs.get, ('x', 'y', 'out'))) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=optype, + inputs={ + 'X': x, + 'Y': y + }, + outputs={'Z': out}, + attrs={}) + return out + + +def _manipulation_unop(helper): + optype = helper.layer_type + x, out = tuple(map(helper.kwargs.get, ('x', 'out'))) + + attrs = { + k: helper.kwargs[k] + for k in ('shape', 'axis', 'index') if k in helper.kwargs + } + + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=optype, + inputs={'X': x}, + outputs={'Y': out}, + attrs=attrs) + return out + + +# Each primitive op is given a Python constructor for sake of convenience. +def fill_const(value, shape, dtype, out=None): + attrs = {'value': value, 'shape': shape, 'dtype': dtype} + helper = LayerHelper('fill_constant_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type=helper.layer_type, outputs={'Y': out}, attrs=attrs) + return out + + +def neg(x, out=None): + zero = fill_const(0.0, x.shape, x.dtype) + return sub(zero, x) + + +def set_value(x, y, axis, starts, ends, strides, out): + assert x is out, "x and out should be the same Tensor in set_value" + attrs = {'axes': axis, 'starts': starts, 'ends': ends, 'steps': strides} + helper = LayerHelper('set_value', **locals()) + helper.append_op(type=helper.layer_type, + inputs={ + 'Input': x, + 'ValueTensor': y + }, + outputs={'Out': out}, + attrs=attrs) + return out + + +@REGISTER_FN('add_p', 'X', 'Y', 'Z') +def add(x, y, out=None): + return _simple_binop(LayerHelper('add_p', **locals())) + + +@REGISTER_FN('sub_p', 'X', 'Y', 'Z') +def sub(x, y, out=None): + return _simple_binop(LayerHelper('sub_p', **locals())) + + +@REGISTER_FN('mul_p', 'X', 'Y', 'Z') +def mul(x, y, out=None): + return _simple_binop(LayerHelper('mul_p', **locals())) + + +@REGISTER_FN('div_p', 'X', 'Y', 'Z') +def div(x, y, out=None): + return _simple_binop(LayerHelper('div_p', **locals())) + + +@REGISTER_FN('sqrt_p', 'X', 'Y') +def sqrt(x, out=None): + return _simple_unop(LayerHelper('sqrt_p', **locals())) + + +@REGISTER_FN('tanh_p', 'X', 'Y') +def tanh(x, out=None): + return _simple_unop(LayerHelper('tanh_p', **locals())) + + +@REGISTER_FN('sin_p', 'X', 'Y') +def sin(x, out=None): + return _simple_unop(LayerHelper('sin_p', **locals())) + + +@REGISTER_FN('cos_p', 'X', 'Y') +def cos(x, out=None): + return _simple_unop(LayerHelper('cos_p', **locals())) + + +@REGISTER_FN('exp_p', 'X', 'Y') +def exp(x, out=None): + return _simple_unop(LayerHelper('exp_p', **locals())) + + +@REGISTER_FN('abs_p', 'X', 'Y') +def abs(x, out=None): + return _simple_unop(LayerHelper('abs_p', **locals())) + + +@REGISTER_FN('reshape_p', 'X', 'Y') +def reshape(x, shape, out=None): + return _manipulation_unop(LayerHelper('reshape_p', **locals())) + + +@REGISTER_FN('broadcast_p', 'X', 'Y') +def broadcast(x, shape, out=None): + return _manipulation_unop(LayerHelper('broadcast_p', **locals())) + + +@REGISTER_FN('transpose_p', 'X', 'Y') +def transpose(x, axis=None, out=None): + return _manipulation_unop(LayerHelper('transpose_p', **locals())) + + +@REGISTER_FN('split_p', 'X', 'YS') +def split(x, num_or_sections, axis=0, outs=None): + if isinstance(num_or_sections, (list, tuple)): + n = len(num_or_sections) + else: + if not isinstance(num_or_sections, int): + raise TypeError( + f'num_or_sections must be int, but got {type(num_or_sections)}.' + ) + n = num_or_sections + + attrs = {'num_or_sections': num_or_sections, 'axis': axis} + + helper = LayerHelper('split_p', **locals()) + if outs is None: + outs = [ + helper.create_variable_for_type_inference(dtype=x.dtype) + for i in range(n) + ] + helper.append_op(type=helper.layer_type, + inputs={'X': x}, + outputs={'YS': outs}, + attrs=attrs) + return outs + + +@REGISTER_FN('concat_p', 'XS', 'Y') +def concat(xs, axis=0, out=None): + if isinstance(xs, paddle.fluid.framework.Variable): + xs = [xs] + attrs = {'axis': axis} + helper = LayerHelper('concat_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=xs[0].dtype) + helper.append_op(type=helper.layer_type, + inputs={'XS': xs}, + outputs={'Y': out}, + attrs=attrs) + return out + + +@REGISTER_FN('reduce_sum_p', 'X', 'Y') +def reduce_sum(x, axis=None, keepdim=False, out=None): + axes = axis or tuple(range(0, len(x.shape))) + axes = (axes, ) if isinstance(axes, int) else axes + if not isinstance(axis, (tuple, list)): + raise TypeError(f'axis must be tuple or list, but got {type(axis)}') + if not isinstance(keepdim, bool): + raise TypeError(f'keepdim must be bool, but got {type(keepdim)}') + + attrs = {'axis': axis, 'keepdim': keepdim} + helper = LayerHelper('reduce_sum_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type=helper.layer_type, + inputs={'X': x}, + outputs={'Y': out}, + attrs=attrs) + return out + + +@REGISTER_FN('matmul_p', 'X', 'Y', 'Z') +def matmul(x, y, out=None): + return _simple_binop(LayerHelper('matmul_p', **locals())) + + +@REGISTER_FN('slice_select_p', 'X', 'Y') +def slice_select(x, axis, starts, ends, strides, out=None): + if not isinstance(axis, (list, tuple)): + raise TypeError(f'Argument type error. `axis` is supposed to be list or' + f' tuple but found {type(axis)}.') + if not isinstance(starts, (list, tuple)): + raise TypeError( + f'Argument type error. `starts` is supposed to be list or' + f' tuple but found {type(starts)}.') + if not isinstance(ends, (list, tuple)): + raise TypeError(f'Argument type error. `ends` is supposed to be list or' + f' tuple but found {type(ends)}.') + assert len(axis) == len(starts) == len(ends) == len(strides), ( + f'len(axis), len(starts), len(ends) and len(strides) should be equal, ' + f'but len(axis)={len(axis)}, len(starts)={len(starts)}, ' + f'len(ends)={len(ends)} and len(strides)={len(strides)}') + + attrs = {'axis': axis, 'starts': starts, 'ends': ends, 'strides': strides} + helper = LayerHelper('slice_select_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=helper.layer_type, + inputs={'X': x}, + outputs={'Y': out}, + attrs=attrs) + return out + + +@REGISTER_FN('slice_assign_p', 'X', 'Y', 'Z') +def slice_assign(x, y, axis, starts, ends, strides, out=None): + assert len(starts) == len(ends) == len(strides) == len(axis), ( + f'len(starts), len(ends), len(strides) and len(axis) should be equal, ' + f'but len(starts)={len(starts)}, len(ends)={len(ends)}, ' + f'len(strides)={len(strides)} and len(axis)={len(axis)}') + assert len(y.shape) == len(x.shape), ( + f'len(y.shape) should be equal to len(x.shape), ' + f'but len(y.shape)={len(y.shape)} and len(x.shape)={len(x.shape)}.') + + attrs = {'axis': axis, 'starts': starts, 'ends': ends, 'strides': strides} + helper = LayerHelper('slice_assign_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=helper.layer_type, + inputs={ + 'X': x, + 'Y': y + }, + outputs={'Z': out}, + attrs=attrs) + return out + + +@REGISTER_FN('gather_p', 'X', 'IndexTensor', 'Y') +def gather(x, indextensor, axis, out=None): + attrs = {'axis': axis} + helper = LayerHelper('gather_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=helper.layer_type, + inputs={ + 'X': x, + 'IndexTensor': indextensor + }, + outputs={'Y': out}, + attrs=attrs) + return out + + +@REGISTER_FN('scatter_add_p', 'X', 'Y', 'IndexTensor', 'Z') +def scatter_add(x, y, indextensor, axis, out=None): + assert len(x.shape) == len(y.shape), ( + f'len(x.shape) should be equal to len(y.shape), ' + f'but len(x.shape)={len(x.shape)} and len(y.shape)={len(y.shape)}.') + assert len( + indextensor.shape + ) == 1, f'len(indextensor.shape) must be equal to 1, but got {len(indextensor.shape)}.' + assert y.shape[axis] == indextensor.shape[0], ( + f'y.shape[axis] should be equal to indextensor.shape[0], ' + f'but y.shape[axis]={y.shape[axis]} and ' + f'indextensor.shape[0]={indextensor.shape[0]}.') + attrs = {'axis': axis} + helper = LayerHelper('scatter_add_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=helper.layer_type, + inputs={ + 'X': x, + 'Y': y, + 'IndexTensor': indextensor + }, + outputs={'Z': out}, + attrs=attrs) + return out + + +@REGISTER_FN('log_p', 'X', 'Y') +def log(x, out=None): + return _simple_unop(LayerHelper('log_p', **locals())) + + +@REGISTER_FN('select_p', 'Condition', 'X', 'Y', 'Z') +def select(cond, x, y, out=None): + if len(cond.shape) != len(x.shape): + raise ValueError( + "len(cond.shape) should be equal to len(x.shape), but len(cond.shape)={} and len(x.shape)={}." + .format(len(cond.shape), len(x.shape))) + + if len(x.shape) != len(y.shape): + raise ValueError( + "len(x.shape) should be equal to len(y.shape), but len(x.shape)={} and len(y.shape)={}." + .format(len(x.shape), len(y.shape))) + + helper = LayerHelper('select_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=helper.layer_type, + inputs={ + 'Condition': cond, + 'X': x, + 'Y': y + }, + outputs={'Z': out}) + return out + + +@REGISTER_FN('eq_p', 'X', 'Y', 'Z') +def eq(x, y, out=None): + return _simple_binop(LayerHelper('eq_p', **locals())) + + +@REGISTER_FN('gt_p', 'X', 'Y', 'Z') +def gt(x, y, out=None): + return _simple_binop(LayerHelper('gt_p', **locals())) + + +@REGISTER_FN('ge_p', 'X', 'Y', 'Z') +def ge(x, y, out=None): + return _simple_binop(LayerHelper('ge_p', **locals())) + + +@REGISTER_FN('ne_p', 'X', 'Y', 'Z') +def ne(x, y, out=None): + return _simple_binop(LayerHelper('ne_p', **locals())) + + +@REGISTER_FN('pow_p', 'X', 'Y', 'Z') +def pow(x, y, out=None): + return _simple_binop(LayerHelper('pow_p', **locals())) + + +@REGISTER_FN('max_p', 'X', 'Y', 'Z') +def max(x, y, out=None): + return _simple_binop(LayerHelper('max_p', **locals())) + + +@REGISTER_FN('erf_p', 'X', 'Y') +def erf(x, out=None): + return _simple_unop(LayerHelper('erf_p', **locals())) + + +@REGISTER_FN('cast_p', 'X', 'Y') +def cast(x, dtype, out=None): + helper = LayerHelper('cast_p', **locals()) + if out is None: + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type=helper.layer_type, + inputs={'X': x}, + outputs={'Y': out}, + attrs={'dtype': dtype}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primreg.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primreg.py new file mode 100644 index 0000000000000000000000000000000000000000..34b1c7f48334845947d81b5f3de5b4edf14b2f0a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primreg.py @@ -0,0 +1,293 @@ +# Copyright (c) 2022 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. + +import functools + + +class Registry(object): + """ A general registry object. """ + __slots__ = ['name', 'tab'] + + def __init__(self, name): + self.name = name + self.tab = {} + + def register(self, name, value): + assert name not in self.tab, f'name "{name}" should not be registered before.' + self.tab[name] = value + + def lookup(self, name): + return self.tab.get(name) + + +_primop_fn = Registry('primop_fn') +_orig2prim = Registry('orig2prim') +_prim2orig = Registry('prim2orig') +_primop_jvp = Registry('primop_jvp') +_primop_transpose = Registry('primop_transpose') +_primop_position_argnames = Registry('primop_position_argnames') + + +def lookup_fn(optype): + return _primop_fn.lookup(optype) + + +def lookup_orig2prim(optype): + return _orig2prim.lookup(optype) + + +def lookup_prim2orig(optype): + return _prim2orig.lookup(optype) + + +def lookup_jvp(optype): + return _primop_jvp.lookup(optype) + + +def lookup_transpose(optype): + return _primop_transpose.lookup(optype) + + +def op_position_inputs(op): + """ + Returns the position inputs of `op` as registered with REGISTER_FN. + + Args: + op(Operator): The op that needs to get the inputs + + Returns: + Tensor(s): Inputs of the op + + Examples: + .. code-block:: python + @REGISTER_FN('div_p', 'X', 'Y', 'Z') + def div(x, y, out=None): + return _simple_binop(LayerHelper('div_p', **locals())) + + The registered inputs are ['X', 'Y'] for div_p and accordingly this + function will return inputs in the order of X then Y. + + """ + args = _primop_position_argnames.lookup(op.type) + assert args is not None, f'args of {op.type} should not be None in op_position_inputs().' + *input_names, _ = args + + inputs = [] + for name in input_names: + vars = list(map(op.block.var, op.input(name))) + assert len( + vars + ) >= 0, f'len(vars) should be greater than or equal to 0, but len(vars)={len(vars)}.' + if len(vars) > 1: + inputs.append(vars) + else: + inputs.append(vars[0]) + + return inputs + + +def op_position_output(op): + """ + Returns the output of `op` as registered with REGISTER_FN. + + Args: + op(Operator): The op that needs to get the output + + Returns: + Tensor(s): Output of the op + + Examples: + .. code-block:: python + @REGISTER_FN('div_p', 'X', 'Y', 'Z') + def div(x, y, out=None): + return _simple_binop(LayerHelper('div_p', **locals())) + + The registered output is ['Z'] for div_p and accordingly this + function will return output Z. + + """ + args = _primop_position_argnames.lookup(op.type) + assert args is not None, 'args should not be None in op_position_output().' + *_, output_name = args + + outvars = list(map(op.block.var, op.output(output_name))) + assert len( + outvars + ) >= 0, f'len(outvars) should be greater than or equal to 0, but len(outvars)={len(outvars)}.' + if len(outvars) > 1: + output = outvars + else: + output = outvars[0] + + return output + + +def REGISTER_FN(op_type, *position_argnames): + """ + Decorator for registering the Python function for a primitive op. + + Args: + op_type(str): The op name + position_argnames(list[str]): Input and ouput names of the op + + Returns: + wrapper: Inner wrapper function + + Examples: + .. code-block:: python + @REGISTER_FN('tanh_p', 'X', 'Y') + def tanh(x, out=None): + return _simple_unop(LayerHelper('tanh_p', **locals())) + + """ + + if not isinstance(op_type, str): + raise TypeError(f'op_type must be str, but got {type(op_type)}.') + + _primop_position_argnames.register(op_type, position_argnames) + + def wrapper(f): + _primop_fn.register(op_type, f) + return f + + return wrapper + + +def REGISTER_ORIG2PRIM(op_type): + """ + Decorator for registering the lower function for an original op into sequence of primitive ops. + + Args: + op_type(str): The op name + + Returns: + wrapper: Inner wrapper function + + Examples: + .. code-block:: python + @REGISTER_ORIG2PRIM('tanh') + def tanh_orig2prim(op): + x, = get_input_var_list(op) + return primops.tanh(x) + + """ + if not isinstance(op_type, str): + raise TypeError(f'op_type must be str, but got {type(op_type)}.') + + def wrapper(f): + + def _lower(op, *args, **kwargs): + assert op.type == op_type, f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}' + return f(op, *args, **kwargs) + + _orig2prim.register(op_type, _lower) + + return wrapper + + +def REGISTER_PRIM2ORIG(op_type): + """ + Decorator for registering the lower function for an primitive op into sequence of original ops. + + Args: + op_type(str): The op name + + Returns: + wrapper: Inner wrapper function + + Examples: + .. code-block:: python + @REGISTER_PRIM2ORIG('tanh_p') + def tanh_prim2orig(op): + x, = get_input_var_list(op) + return paddle.tanh(x) + + """ + if not isinstance(op_type, str): + raise TypeError(f'op_type must be str, but got {type(op_type)}.') + + def wrapper(f): + + def _lower(op, *args, **kwargs): + assert op.type == op_type, f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}' + return f(op, *args, **kwargs) + + _prim2orig.register(op_type, _lower) + + return wrapper + + +def REGISTER_JVP(op_type): + """ + Decorator for registering the JVP function for a primitive op. + + Args: + op_type(str): The op name + + Returns: + wrapper: Inner wrapper function + + Examples: + .. code-block:: python + @REGISTER_JVP('add_p') + def add_jvp(op, x_dot, y_dot): + return primops.add(x_dot, y_dot) + + """ + if not isinstance(op_type, str): + raise TypeError(f'op_type must be str, but got {type(op_type)}.') + + def wrapper(f): + + def _jvp(op, *args, **kwargs): + assert op.type == op_type, f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}' + return f(op, *args, **kwargs) + + _primop_jvp.register(op_type, _jvp) + return f + + return wrapper + + +def REGISTER_TRANSPOSE(op_type): + """ + Decorator for registering the transpose function for a primitive op + that denotes a linear operation in the forward AD graph. + + Args: + op_type(str): The op name + + Returns: + wrapper: Inner wrapper function + + Examples: + .. code-block:: python + @REGISTER_TRANSPOSE('add_p') + def add_transpose(op, z_bar): + return z_bar, z_bar + + """ + if not isinstance(op_type, str): + raise TypeError(f'op_type must be str, but got {type(op_type)}.') + + def wrapper(f): + + def _transpose(op, dot_checker, *args, **kwargs): + assert op.type == op_type, f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}' + return f(op, dot_checker, *args, **kwargs) + + _primop_transpose.register(op_type, _transpose) + return f + + return wrapper diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primrules.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primrules.py new file mode 100644 index 0000000000000000000000000000000000000000..4625cfd362f07030feba94c7191b178108384474 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primrules.py @@ -0,0 +1,1181 @@ +# Copyright (c) 2022 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. +import functools +import math +import operator +import typing + +import paddle + +from . import primops +from .primops import (add, broadcast, concat, cos, div, eq, erf, exp, + fill_const, gather, ge, gt, log, matmul, max, mul, ne, + neg, reduce_sum, reshape, scatter_add, select, set_value, + sin, slice_assign, slice_select, split, sqrt, sub, tanh, + transpose) +from .primreg import (REGISTER_JVP, REGISTER_ORIG2PRIM, REGISTER_PRIM2ORIG, + REGISTER_TRANSPOSE, lookup_fn, lookup_jvp, + lookup_orig2prim, lookup_prim2orig, lookup_transpose, + op_position_inputs, op_position_output) +from .utils import INT_DTYPE_2_STRING, get_input_var_list, get_output_var_list +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid.framework import convert_np_dtype_to_dtype_ + + +def _orig2prim(op, *args): + _lowerrule = lookup_orig2prim(op.type) + return _lowerrule(op, *args) + + +def _prim2orig(op, *args): + _lowerrule = lookup_prim2orig(op.type) + return _lowerrule(op, *args) + + +def _jvp(op, *args): + _jvprule = lookup_jvp(op.type) + return _jvprule(op, *args) + + +def _transpose(op, dot_checker, *args): + _transposerule = lookup_transpose(op.type) + return _transposerule(op, dot_checker, *args) + + +def linear_jvp(op, *args, **kwargs): + fn = lookup_fn(op.type) + out_dot = fn(*args, **kwargs) + return out_dot + + +## Register orig2prim lower rules +""" +These original ops are fully supported: + +elementwise_add +elementwise_sub +elementwise_mul +tanh +fill_zeros_like +fill_any_like +sum +index_select +scale +assign +sqrt +log +select +equal +elementwise_pow + +These original ops are partially supported: + +matmul_v2 +reshape2 +concat +slice +p_norm +""" + + +@REGISTER_ORIG2PRIM('elementwise_add') +def elementwise_add_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + if op.attr('Scale_x') - 1.0 > 1e-5: + scale_x = fill_const(shape=x.shape, + dtype=x.dtype, + value=op.attr('Scale_x')) + x = mul(x, scale_x) + if op.attr('Scale_y') - 1.0 > 1e-5: + scale_y = fill_const(shape=y.shape, + dtype=y.dtype, + value=op.attr('Scale_y')) + y = mul(y, scale_y) + z = add(x, y) + if op.attr('Scale_out') - 1.0 > 1e-5: + scale_out = fill_const(shape=z.shape, + dtype=z.dtype, + value=op.attr('Scale_out')) + z = mul(z, scale_out) + return z + + +@REGISTER_ORIG2PRIM('elementwise_sub') +def elementwise_sub_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + if op.attr('Scale_x') - 1.0 > 1e-5: + scale_x = fill_const(shape=x.shape, + dtype=x.dtype, + value=op.attr('Scale_x')) + x = mul(x, scale_x) + if op.attr('Scale_y') - 1.0 > 1e-5: + scale_y = fill_const(shape=y.shape, + dtype=y.dtype, + value=op.attr('Scale_y')) + y = mul(y, scale_y) + z = sub(x, y) + if op.attr('Scale_out') - 1.0 > 1e-5: + scale_out = fill_const(shape=z.shape, + dtype=z.dtype, + value=op.attr('Scale_out')) + z = mul(z, scale_out) + return z + + +@REGISTER_ORIG2PRIM('elementwise_mul') +def elementwise_mul_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + if op.attr('Scale_x') - 1.0 > 1e-5: + scale_x = fill_const(shape=x.shape, + dtype=x.dtype, + value=op.attr('Scale_x')) + x = mul(x, scale_x) + if op.attr('Scale_y') - 1.0 > 1e-5: + scale_y = fill_const(shape=y.shape, + dtype=y.dtype, + value=op.attr('Scale_y')) + y = mul(y, scale_y) + z = mul(x, y) + if op.attr('Scale_out') - 1.0 > 1e-5: + scale_out = fill_const(shape=z.shape, + dtype=z.dtype, + value=op.attr('Scale_out')) + z = mul(z, scale_out) + return z + + +@REGISTER_ORIG2PRIM('elementwise_div') +def elementwise_div_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return primops.div(x, y) + + +@REGISTER_ORIG2PRIM('tanh') +def tanh_orig2prim(op, x): + return tanh(x) + + +@REGISTER_ORIG2PRIM('sin') +def sin_orig2prim(op, x): + return sin(x) + + +@REGISTER_ORIG2PRIM('cos') +def cos_orig2prim(op, x): + return cos(x) + + +@REGISTER_ORIG2PRIM('exp') +def exp_orig2prim(op, x): + return exp(x) + + +@REGISTER_ORIG2PRIM('erf') +def erf_orig2prim(op, x): + return erf(x) + + +@REGISTER_ORIG2PRIM('abs') +def abs_orig2prim(op, x): + return primops.abs(x) + + +@REGISTER_ORIG2PRIM('log') +def log_orig2prim(op, x): + return log(x) + + +@REGISTER_ORIG2PRIM('fill_zeros_like') +def fill_zeros_like_orig2prim(op, x): + return fill_const(value=0.0, shape=x.shape, dtype=x.dtype) + + +@REGISTER_ORIG2PRIM('fill_any_like') +def fill_any_like_orig2prim(op, x): + if op.attr('dtype') == -1: + return fill_const(value=op.attr('value'), shape=x.shape, dtype=x.dtype) + return fill_const(value=op.attr('value'), + shape=x.shape, + dtype=convert_np_dtype_to_dtype_( + convert_dtype(INT_DTYPE_2_STRING[op.attr('dtype')]))) + + +@REGISTER_ORIG2PRIM('sum') +def sum_orig2prim(op, xs): + x0 = xs[0] + for x in xs[1:]: + x0 = add(x0, x) + return x0 + + +@REGISTER_ORIG2PRIM('index_select') +def index_select_orig2prim(op, index_t, x): + return gather(x, indextensor=index_t, axis=op.attr('dim')) + + +@REGISTER_ORIG2PRIM('scale') +def scale_orig2prim(op, scale_t, x): + if scale_t is None: + scale_t = fill_const(shape=x.shape, + dtype=x.dtype, + value=op.attr('scale')) + bias_t = fill_const(shape=x.shape, dtype=x.dtype, value=op.attr('bias')) + if op.attr('bias_after_scale'): + return add(mul(x, scale_t), bias_t) + else: + return mul(add(x, bias_t), scale_t) + + +@REGISTER_ORIG2PRIM('assign') +def assign_orig2prim(op, x): + zero_t = fill_const(shape=x.shape, dtype=x.dtype, value=0.0) + return add(x, zero_t) + + +@REGISTER_ORIG2PRIM('sqrt') +def sqrt_orig2prim(op, x): + return sqrt(x) + + +@REGISTER_ORIG2PRIM('matmul_v2') +def matmul_v2_orig2prim(op, x, y): + + def trans(shape): + ret = [i for i in range(len(shape))] + ret[-1], ret[-2] = ret[-2], ret[-1] + return ret + + assert len(x.shape) < 4 and len( + y.shape) < 4, 'Do not support multi batchsize dimensions currently.' + + if len(x.shape) == 1: + x = broadcast(x, shape=[1, x.shape[0]]) + if len(y.shape) == 1: + y = broadcast(y, shape=[y.shape[0], 1]) + if op.attr('trans_x'): + x = transpose(x, axis=trans(x.shape)) + if op.attr('trans_y'): + y = transpose(y, axis=trans(y.shape)) + return matmul(x, y) + + +## NOTE(lml): The second output of reshape2 Xshape, which is only used in reshape2_grad, is meanlingless in new autograd mechanism, thus we use a zero tensor instead. +@REGISTER_ORIG2PRIM('reshape2') +def reshape2_orig2prim(op, shape_t, shape_tl, x): + assert shape_t is None, 'Can not lower reshape2 into prim ops with shapetensor.' + assert shape_tl is None, 'Can not lower reshape2 into prim ops with shapetensorlist.' + y, xshape = get_output_var_list(op) + return reshape(x, shape=y.shape), fill_const(shape=xshape.shape, + dtype=xshape.dtype, + value=0.0) + + +@REGISTER_ORIG2PRIM('concat') +def concat_orig2prim(op, axis_t, xs): + assert axis_t is None, 'Can not lower concat into prim ops with axistensor.' + return concat(xs, axis=op.attr('axis')) + + +@REGISTER_ORIG2PRIM('slice') +def slice_orig2prim(op, ends_t, ends_tl, x, starts_t, starts_tl): + assert starts_t is None, 'Can not lower concat into prim ops with startstensor.' + assert ends_t is None, 'Can not lower concat into prim ops with endstensor.' + assert starts_tl is None, 'Can not lower concat into prim ops with startstensorlist.' + assert ends_tl is None, 'Can not lower concat into prim ops with endstensorlist.' + starts = op.attr('starts') + ends = op.attr('ends') + strides = [1 for _ in starts] + axis = op.attr('axes') + y = slice_select(x, starts=starts, ends=ends, strides=strides, axis=axis) + if op.attr('decrease_axis'): + y = reshape(y, shape=get_output_var_list(op)[0].shape) + return y + + +@REGISTER_ORIG2PRIM('p_norm') +def p_norm_orig2prim(op, x): + + def num_el(shape): + n = 1 + for s in shape: + n = n * s + return n + + assert op.attr( + 'asvector'), 'Only support lower pnorm when asvector=True currently' + if len(x.shape) > 1: + x = reshape(x, shape=[num_el(x.shape)]) + + if abs(op.attr('porder') - 2.0) < 1e-5: + return sqrt(reduce_sum(mul(x, x), axis=[0])) + elif abs(op.attr('porder') - 1.0) < 1e-5: + return reduce_sum(sqrt(mul(x, x)), axis=[0]) + else: + raise RuntimeError('Only support lower l2/l1 norm currently') + + +@REGISTER_ORIG2PRIM('cast') +def cast_orig2prim(op, x): + return primops.cast(x, paddle.dtype(op.attr('out_dtype'))) + + +# TODO: support broadcast +@REGISTER_ORIG2PRIM('where') +def select_orig2prim(op, condition, x, y): + return select(condition, x, y) + + +@REGISTER_ORIG2PRIM('equal') +def equal_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return eq(x, y) + + +@REGISTER_ORIG2PRIM('not_equal') +def ne_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return ne(x, y) + + +@REGISTER_ORIG2PRIM('greater_than') +def gt_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return gt(x, y) + + +@REGISTER_ORIG2PRIM('greater_equal') +def ge_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return ge(x, y) + + +# paddle.pow API use "elementwise_pow" operator when y is a Tensor. +@REGISTER_ORIG2PRIM('elementwise_pow') +def elementwise_pow_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + z = primops.pow(x, y) + return z + + +# paddle.pow API use "pow" operator when y is a scalar. +@REGISTER_ORIG2PRIM('pow') +def pow_orig2prim(op, x, y): + # x is factorTensor defined in paddle phi op. Currently it is None. + return primops.pow(y, fill_const(op.attr('factor'), y.shape, y.dtype)) + + +@REGISTER_ORIG2PRIM('square') +def square_orig2prim(op, x): + return primops.pow(x, fill_const(2., x.shape, x.dtype)) + + +@REGISTER_ORIG2PRIM('elementwise_max') +def elementwise_max_orig2prim(op, x, y): + if x.shape != y.shape: + y = broadcast(y, shape=x.shape) + return primops.max(x, y) + + +@REGISTER_ORIG2PRIM('gelu') +def gelu_orig2prim(op, x): + if op.attr('approximate'): + cdf = mul( + fill_const(0.5, x.shape, x.dtype), + add( + fill_const(1.0, x.shape, x.dtype), + tanh( + mul( + fill_const(math.sqrt(2 / math.pi), x.shape, x.dtype), + add( + x, + mul( + fill_const(0.044715, x.shape, x.dtype), + primops.pow(x, fill_const(3., x.shape, + x.dtype)))))))) + return mul(x, cdf) + else: + return mul( + mul(fill_const(0.5, x.shape, x.dtype), x), + add(fill_const(1.0, x.shape, x.dtype), + erf(mul(x, fill_const(1 / math.sqrt(2.), x.shape, x.dtype))))) + + +@REGISTER_ORIG2PRIM('reduce_sum') +def reduce_sum_orig2prim(op, x): + axes = tuple(range(0, len( + x.shape))) if op.attr('reduce_all') else op.attr('dim') + return reduce_sum(x, axis=axes, keepdim=op.attr('keep_dim')) + + +@REGISTER_ORIG2PRIM('reduce_mean') +def reduce_mean_orig2prim(op, x): + axes = tuple(range(0, len( + x.shape))) if op.attr('reduce_all') else op.attr('dim') + sum = reduce_sum(x, axis=axes, keepdim=op.attr('keep_dim')) + norm = fill_const(shape=sum.shape, + value=functools.reduce(operator.mul, + [x.shape[axis] for axis in axes]), + dtype=sum.dtype) + return div(sum, norm) + + +@REGISTER_ORIG2PRIM('size') +def size_orig2prim(op, x): + return fill_const(functools.reduce(operator.mul, x.shape), (1, ), + paddle.int64) + + +## Register prim2orig lower rules +@REGISTER_PRIM2ORIG('add_p') +def add_prim2orig(op, x, y): + return paddle.add(x, y) + + +@REGISTER_PRIM2ORIG('sub_p') +def sub_prim2orig(op, x, y): + return paddle.subtract(x, y) + + +@REGISTER_PRIM2ORIG('mul_p') +def mul_prim2orig(op, x, y): + return paddle.multiply(x, y) + + +@REGISTER_PRIM2ORIG('div_p') +def div_prim2orig(op, x, y): + return paddle.divide(x, y) + + +@REGISTER_PRIM2ORIG('sqrt_p') +def sqrt_prim2orig(op, x): + return paddle.sqrt(x) + + +@REGISTER_PRIM2ORIG('tanh_p') +def tanh_prim2orig(op, x): + return paddle.tanh(x) + + +@REGISTER_PRIM2ORIG('sin_p') +def sin_prim2orig(op, x): + return paddle.sin(x) + + +@REGISTER_PRIM2ORIG('cos_p') +def cos_prim2orig(op, x): + return paddle.cos(x) + + +@REGISTER_PRIM2ORIG('exp_p') +def exp_prim2orig(op, x): + return paddle.exp(x) + + +@REGISTER_PRIM2ORIG('erf_p') +def erf_prim2orig(op, x): + return paddle.erf(x) + + +@REGISTER_PRIM2ORIG('abs_p') +def abs_prim2orig(op, x): + return paddle.abs(x) + + +@REGISTER_PRIM2ORIG('log_p') +def log_prim2orig(op, x): + return paddle.log(x) + + +@REGISTER_PRIM2ORIG('reshape_p') +def reshape_prim2orig(op, x): + return paddle.reshape(x, shape=op.attr('shape')) + + +@REGISTER_PRIM2ORIG('broadcast_p') +def broadcast_prim2orig(op, x): + return paddle.broadcast_to(x, shape=op.attr('shape')) + + +@REGISTER_PRIM2ORIG('transpose_p') +def transpose_prim2orig(op, x): + return paddle.transpose(x, perm=op.attr('axis')) + + +@REGISTER_PRIM2ORIG('split_p') +def split_prim2orig(op, x): + num_or_sections = op.attr('num_or_sections') + if len(num_or_sections) == 1: + num_or_sections = num_or_sections[0] + return paddle.split(x, + num_or_sections=num_or_sections, + axis=op.attr('axis')) + + +@REGISTER_PRIM2ORIG('concat_p') +def concat_prim2orig(op, xs): + return paddle.concat(xs, axis=op.attr('axis')) + + +@REGISTER_PRIM2ORIG('reduce_sum_p') +def reduce_prim2orig(op, x): + return paddle.sum(x, axis=op.attr('axis'), keepdim=op.attr('keepdim')) + + +@REGISTER_PRIM2ORIG('matmul_p') +def matmul_prim2orig(op, x, y): + return paddle.matmul(x, y) + + +@REGISTER_PRIM2ORIG('slice_select_p') +def slice_select_prim2orig(op, x): + return paddle.strided_slice(x, + axes=op.attr('axis'), + starts=op.attr('starts'), + ends=op.attr('ends'), + strides=op.attr('strides')) + + +@REGISTER_PRIM2ORIG('slice_assign_p') +def slice_assign_prim2orig(op, x, y): + x_copy = paddle.assign(x) + return set_value(x_copy, + y, + axis=op.attr('axis'), + starts=op.attr('starts'), + ends=op.attr('ends'), + strides=op.attr('strides'), + out=x_copy) + + +@REGISTER_PRIM2ORIG('gather_p') +def gather_prim2orig(op, index_t, x): + return paddle.gather(x, index_t, axis=op.attr('axis')) + + +@REGISTER_PRIM2ORIG('scatter_add_p') +def scatter_add_prim2orig(op, index_t, x, y): + assert op.attr('axis') == 0, 'Only support axis==0 currently' + zeros = paddle.zeros_like(x=x, dtype=x.dtype) + tmp = paddle.scatter(x=zeros, index=index_t, updates=y, overwrite=False) + return paddle.add(x, tmp) + + +@REGISTER_PRIM2ORIG('fill_constant_p') +def fill_constant_prim2orig(op): + return paddle.full(shape=op.attr('shape'), + fill_value=op.attr('value'), + dtype=INT_DTYPE_2_STRING[op.attr('dtype')]) + + +@REGISTER_PRIM2ORIG('select_p') +def select_prim2orig(op, condition, x, y): + return paddle.where(condition, x, y) + + +@REGISTER_PRIM2ORIG('eq_p') +def eq_prim2orig(op, x, y): + return paddle.equal(x, y) + + +@REGISTER_PRIM2ORIG('gt_p') +def gt_prim2orig(op, x, y): + return paddle.greater_than(x, y) + + +@REGISTER_PRIM2ORIG('ge_p') +def ge_prim2orig(op, x, y): + return paddle.greater_equal(x, y) + + +@REGISTER_PRIM2ORIG('ne_p') +def ne_prim2orig(op, x, y): + return paddle.not_equal(x, y) + + +@REGISTER_PRIM2ORIG('pow_p') +def pow_prim2orig(op, x, y): + return paddle.pow(x, y) + + +@REGISTER_PRIM2ORIG('max_p') +def max_prim2orig(op, x, y): + return paddle.maximum(x, y) + + +@REGISTER_PRIM2ORIG('cast_p') +def cast_prim2orig(op, x): + return paddle.cast(x, paddle.dtype(op.attr('dtype'))) + + +## Register linearize rules +@REGISTER_JVP('add_p') +def add_jvp(op, x_dot, y_dot): + if x_dot is None: + return y_dot + elif y_dot is None: + return x_dot + else: + return linear_jvp(op, x_dot, y_dot) + + +@REGISTER_JVP('sub_p') +def sub_jvp(op, x_dot, y_dot): + if x_dot is None: + return neg(y_dot) + elif y_dot is None: + return x_dot + else: + return linear_jvp(op, x_dot, y_dot) + + +@REGISTER_JVP('mul_p') +def mul_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, y = op_position_inputs(op) + if x_dot is None: + return mul(x, y_dot) + elif y_dot is None: + return mul(x_dot, y) + else: + t1, t2 = mul(x_dot, y), mul(x, y_dot) + z_dot = add(t1, t2) + return z_dot + + +@REGISTER_JVP('div_p') +def div_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, y = op_position_inputs(op) + if y_dot is None: + return div(x_dot, y) + elif x_dot is None: + return neg(div(mul(x, y_dot), mul(y, y))) + else: + t1 = div(x_dot, y) + t2 = div(mul(x, y_dot), mul(y, y)) + return sub(t1, t2) + + +@REGISTER_JVP('sqrt_p') +def sqrt_jvp(op, x_dot): + if x_dot is None: + return None + y = op_position_output(op) + c2 = fill_const(value=2.0, shape=y.shape, dtype=y.dtype) + y_dot = div(x_dot, mul(c2, y)) + return y_dot + + +@REGISTER_JVP('tanh_p') +def tanh_jvp(op, x_dot): + if x_dot is None: + return None + y = op_position_output(op) + c1 = fill_const(value=1.0, shape=y.shape, dtype=y.dtype) + y_dot = mul(x_dot, sub(c1, mul(y, y))) + return y_dot + + +@REGISTER_JVP('sin_p') +def sin_jvp(op, x_dot): + if x_dot is None: + return None + x, = op_position_inputs(op) + return mul(x_dot, cos(x)) + + +@REGISTER_JVP('cos_p') +def cos_jvp(op, x_dot): + if x_dot is None: + return None + x, = op_position_inputs(op) + return mul(x_dot, neg(sin(x))) + + +@REGISTER_JVP('exp_p') +def exp_jvp(op, x_dot): + if x_dot is None: + return None + y = op_position_output(op) + return mul(x_dot, y) + + +@REGISTER_JVP('erf_p') +def erf_jvp(op, x_dot): + if x_dot is None: + return None + x, = op_position_inputs(op) + return mul( + fill_const(2. / math.sqrt(math.pi), x.shape, x.dtype), + mul(x_dot, exp(neg(primops.pow(x, fill_const(2., x.shape, x.dtype)))))) + + +@REGISTER_JVP('abs_p') +def abs_jvp(op, x_dot): + if x_dot is None: + return None + x, = op_position_inputs(op) + return select(ge(x, fill_const(0., x.shape, x.dtype)), x_dot, neg(x_dot)) + + +@REGISTER_JVP('log_p') +def log_jvp(op, x_dot): + if x_dot is None: + return None + x, = op_position_inputs(op) + return div(x_dot, x) + + +@REGISTER_JVP('reshape_p') +def reshape_jvp(op, x_dot): + if x_dot is None: + return None + shape = op.attr('shape') + return linear_jvp(op, x_dot, shape=shape) + + +@REGISTER_JVP('broadcast_p') +def broadcast_jvp(op, x_dot): + if x_dot is None: + return None + shape = op.attr('shape') + return linear_jvp(op, x_dot, shape=shape) + + +@REGISTER_JVP('transpose_p') +def transpose_jvp(op, x_dot): + if x_dot is None: + return None + axis = op.attr('axis') + return linear_jvp(op, x_dot, axis=axis) + + +@REGISTER_JVP('split_p') +def split_jvp(op, x_dot): + if x_dot is None: + return None + num_or_sections = op.attr('num_or_sections') + axis = op.attr('axis') + return linear_jvp(op, x_dot, num_or_sections=num_or_sections, axis=axis) + + +@REGISTER_JVP('concat_p') +def concat_jvp(op, xs_dot): + if xs_dot is None: + return None + axis = op.attr('axis') + return linear_jvp(op, xs_dot, axis=axis) + + +@REGISTER_JVP('reduce_sum_p') +def reduce_sum_jvp(op, x_dot): + if x_dot is None: + return None + axis = op.attr('axis') + keepdim = op.attr('keepdim') + return linear_jvp(op, x_dot, axis=axis, keepdim=keepdim) + + +@REGISTER_JVP('matmul_p') +def matmul_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, y = op_position_inputs(op) + if x_dot is None: + return matmul(x, y_dot) + elif y_dot is None: + return matmul(x_dot, y) + else: + t1 = matmul(x, y_dot) + t2 = matmul(x_dot, y) + return add(t1, t2) + + +@REGISTER_JVP('slice_select_p') +def slice_select_jvp(op, x_dot): + if x_dot is None: + return x_dot + axis = op.attr('axis') + starts = op.attr('starts') + ends = op.attr('ends') + strides = op.attr('strides') + return linear_jvp(op, + x_dot, + axis=axis, + starts=starts, + ends=ends, + strides=strides) + + +@REGISTER_JVP('slice_assign_p') +def slice_assign_jvp(op, x_dot, y_dot): + if x_dot is None: + assert y_dot is None, 'y_dot must be None.' + return None + else: + assert y_dot is not None, 'y_dot should not be None.' + axis = op.attr('axis') + starts = op.attr('starts') + ends = op.attr('ends') + strides = op.attr('strides') + return linear_jvp(op, + x_dot, + y_dot, + axis=axis, + starts=starts, + ends=ends, + strides=strides) + + +@REGISTER_JVP('gather_p') +def gather_jvp(op, x_dot, indextensor): + if x_dot is None: + return None + _, indextensor = op_position_inputs(op) + axis = op.attr('axis') + return linear_jvp(op, x_dot, indextensor, axis=axis) + + +@REGISTER_JVP('scatter_add_p') +def scatter_add_jvp(op, x_dot, y_dot): + if x_dot is None: + return None + _, _, indextensor = op_position_inputs(op) + axis = op.attr('axis') + return linear_jvp(op, x_dot, y_dot, indextensor, axis=axis) + + +@REGISTER_JVP('select_p') +def select_jvp(op, cond_dot, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + + cond, x, y = op_position_inputs(op) + if x_dot is None: + x_dot = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + if y_dot is None: + y_dot = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + return select(cond, x_dot, y_dot) + + +@REGISTER_JVP('eq_p') +def eq_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, _ = op_position_inputs(op) + z_dot = fill_const(value=0., shape=x.shape, dtype=x.dtype) + return z_dot + + +@REGISTER_JVP('gt_p') +def gt_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, _ = op_position_inputs(op) + z_dot = fill_const(value=0., shape=x.shape, dtype=x.dtype) + return z_dot + + +@REGISTER_JVP('ge_p') +def ge_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, _ = op_position_inputs(op) + z_dot = fill_const(value=0., shape=x.shape, dtype=x.dtype) + return z_dot + + +@REGISTER_JVP('ne_p') +def ne_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + x, _ = op_position_inputs(op) + z_dot = fill_const(value=0., shape=x.shape, dtype=x.dtype) + return z_dot + + +@REGISTER_JVP('pow_p') +def pow_jvp(op, x_dot, y_dot): + + def _compute_t1(x, y): + zero_y = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + one_y = fill_const(value=1.0, shape=y.shape, dtype=y.dtype) + + cond = eq(y, zero_y) + new_y = select(cond, one_y, sub(y, one_y)) + t1 = mul(x_dot, mul(y, primops.pow(x, new_y))) + return t1 + + if x_dot is None and y_dot is None: + return None + x, y = op_position_inputs(op) + z = op_position_output(op) + + if y_dot is None: + return _compute_t1(x, y) + elif x_dot is None: + return mul(y_dot, mul(log(x), z)) + else: + t1, t2 = _compute_t1(x, y), mul(y_dot, mul(log(x), z)) + z_dot = add(t1, t2) + return z_dot + + +@REGISTER_JVP('max_p') +def max_jvp(op, x_dot, y_dot): + if x_dot is None and y_dot is None: + return None + + x, y = op_position_inputs(op) + z = op_position_output(op) + z_zeros = fill_const(value=0.0, shape=z.shape, dtype=z.dtype) + + # To make the grad of max_p consistent with paddle.maximum when x==y, + # we just let z_dot = y_dot when compute z_dot to y and x==y, + # instead of using balance_eq like Jax. + if y_dot is None: + return select(eq(y, z), z_zeros, x_dot) + elif x_dot is None: + return select(eq(y, z), y_dot, z_zeros) + else: + return select(eq(y, z), y_dot, x_dot) + + +@REGISTER_JVP('cast_p') +def cast_jvp(op, x_dot): + y = op_position_output(op) + return primops.cast(x_dot, y.dtype) + + +## Register transpose rules + + +@REGISTER_TRANSPOSE('add_p') +def add_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert check_dot(x) or check_dot(y), ( + f'(check_dot(x) or check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + x_bar = z_bar if check_dot(x) else None + y_bar = z_bar if check_dot(y) else None + return x_bar, y_bar + + +@REGISTER_TRANSPOSE('sub_p') +def sub_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert check_dot(x) or check_dot(y), ( + f'(check_dot(x) or check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + x_bar = z_bar if check_dot(x) else None + y_bar = neg(z_bar) if check_dot(y) else None + return x_bar, y_bar + + +@REGISTER_TRANSPOSE('mul_p') +def mul_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert check_dot(x) ^ check_dot(y), ( + f'(check_dot(x) ^ check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + if check_dot(x): + return mul(z_bar, y), None + else: + return None, mul(x, z_bar) + + +@REGISTER_TRANSPOSE('div_p') +def div_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert not check_dot(y), 'check_dot(y) must be False' + x_bar = div(z_bar, y) if check_dot(x) else None + return x_bar, None + + +@REGISTER_TRANSPOSE('reshape_p') +def reshape_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + return reshape(y_bar, shape=x.shape) + + +@REGISTER_TRANSPOSE('broadcast_p') +def broadcast_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + bat = len(y_bar.shape) - len(x.shape) + axis = list(range(bat)) + keepdim = [(bat + i) for i, s in enumerate(x.shape) if s == 1] + axis += keepdim + # TODO: Change it. keepdim boolean + out = reduce_sum(y_bar, axis=axis, keepdim=False) + return reshape(out, x.shape) + + +@REGISTER_TRANSPOSE('transpose_p') +def transpose_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + axis = op.attr('axis') + reordered = sorted((k, i) for i, k in enumerate(axis)) + axis = [i for k, i in reordered] + return transpose(y_bar, axis=axis) + + +@REGISTER_TRANSPOSE('split_p') +def split_transpose(op, check_dot, ys_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + return concat(ys_bar, axis=op.attr('axis')) + + +@REGISTER_TRANSPOSE('concat_p') +def concat_transpose(op, check_dot, y_bar): + xs, = op_position_inputs(op) + if not isinstance(xs, typing.Sequence): + xs = [xs] + for x in xs: + assert check_dot(x), 'check_dot(x) must be True' + axis = op.attr('axis') + sections = [x.shape[axis] for x in xs] + if len(sections) == 1: + return y_bar + return split(y_bar, num_or_sections=sections, axis=axis) + + +@REGISTER_TRANSPOSE('reduce_sum_p') +def reduce_sum_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + axes = op.attr('axis') + shape = tuple(1 if i in axes else size for i, size in enumerate(x.shape)) + t = reshape(y_bar, shape=shape) + return broadcast(t, shape=x.shape) + + +@REGISTER_TRANSPOSE('matmul_p') +def matmul_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert check_dot(x) ^ check_dot(y), ( + f'(check_dot(x) ^ check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + # TODO: replace it. this is hacky + axis = [1, 0] if len(x.shape) == 2 else [0, 2, 1] + if check_dot(x): + return matmul(z_bar, transpose(y, axis=axis)), None + else: + return None, matmul(transpose(x, axis=axis), z_bar) + + +@REGISTER_TRANSPOSE('slice_select_p') +def slice_select_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + zeros = fill_const(value=0.0, shape=x.shape, dtype=x.dtype) + axis = op.attr('axis') + starts = op.attr('starts') + ends = op.attr('ends') + strides = op.attr('strides') + return slice_assign(zeros, + y_bar, + axis=axis, + starts=starts, + ends=ends, + strides=strides) + + +@REGISTER_TRANSPOSE('slice_assign_p') +def slice_assign_transpose(op, check_dot, z_bar): + x, y = op_position_inputs(op) + assert check_dot(x) and check_dot(y), ( + f'(check_dot(x) and check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + zeros = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + axis = op.attr('axis') + starts = op.attr('starts') + ends = op.attr('ends') + strides = op.attr('strides') + x_bar = slice_assign(z_bar, + zeros, + axis=axis, + starts=starts, + ends=ends, + strides=strides) + y_bar = slice_select(z_bar, + axis=axis, + starts=starts, + ends=ends, + strides=strides) + return x_bar, y_bar + + +@REGISTER_TRANSPOSE('gather_p') +def gather_transpose(op, check_dot, y_bar): + x, indextensor = op_position_inputs(op) + assert check_dot(x), 'check_dot(x) must be True' + axis = op.attr('axis') + zeros = fill_const(0.0, x.shape, x.dtype) + x_bar = scatter_add(zeros, y_bar, indextensor, axis=axis) + indextensor_bar = None + return x_bar, indextensor_bar + + +@REGISTER_TRANSPOSE('scatter_add_p') +def scatter_add_transpose(op, check_dot, z_bar): + x, y, indextensor = op_position_inputs(op) + assert check_dot(x) and check_dot(y), ( + f'(check_dot(x) and check_dot(y)) must be True, ' + f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.') + axis = op.attr('axis') + zeros = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + x_bar = scatter_add(z_bar, zeros, indextensor, axis=axis) + y_bar = gather(z_bar, indextensor, axis=axis) + indextensor_bar = None + return x_bar, y_bar, indextensor_bar + + +@REGISTER_TRANSPOSE('select_p') +def select_transpose(op, check_dot, z_bar): + cond, x, y = op_position_inputs(op) + assert check_dot(cond) or check_dot(x) or check_dot(y), ( + f'check_dot(cond) ^ (check_dot(x) ^ check_dot(y)) must be True, ' + f'but check_dot(cond)={check_dot(cond)}, check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.' + ) + + zeros_x = fill_const(value=0.0, shape=x.shape, dtype=x.dtype) + zeros_y = fill_const(value=0.0, shape=y.shape, dtype=y.dtype) + + cond_bar = fill_const(value=0.0, shape=y.shape, + dtype=cond.dtype) if check_dot(cond) else None + x_bar = select(cond, z_bar, zeros_x) if check_dot(x) else None + y_bar = select(cond, zeros_y, z_bar) if check_dot(y) else None + + return cond_bar, x_bar, y_bar + + +@REGISTER_TRANSPOSE('cast_p') +def cast_transpose(op, check_dot, y_bar): + x, = op_position_inputs(op) + return primops.cast(y_bar, x.dtype) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primx.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primx.py new file mode 100644 index 0000000000000000000000000000000000000000..66a400d9c06f1fdb0eae760ac8b635078fc221fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/primx.py @@ -0,0 +1,616 @@ +# Copyright (c) 2022 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. + +from collections import OrderedDict + +import paddle +from paddle import compat as cpt +from paddle.fluid import framework as framework +from paddle.fluid.framework import Operator, default_main_program +from paddle.incubate.autograd.utils import as_tensors + +from .primops import add, fill_const +from .primreg import ( + lookup_orig2prim, + lookup_prim2orig, + op_position_inputs, + op_position_output, +) +from .primrules import _jvp, _orig2prim, _prim2orig, _transpose +from .utils import ( + flatten, + flatten_and_remove_none, + get_input_var_list, + get_output_var_list, +) + + +def topo_path(xs, ys, block=None): + """Returns the list of ops on the path from `xs` to `ys` in topological + order. + + TODO(Tongxin): supporting control flow and nested blocks. + Args: + xs: a list|tuple of vars as source + ys: a list|tuple of vars as sink + block: the program block containing the path, optional + Returns: + (path, unused_xs, unreached_ys): a tuple comprised of the resulting op + path, the unused variables in `xs`, and the unreached variables in `ys` + """ + + block = default_main_program().current_block() if block is None else block + + path = [] + backpath = [] + reached_vars = OrderedDict() + used_vars = OrderedDict() + + # Initialize reached vars + for x in xs: + assert ( + x is None or x.block == block + ), f'x is not None and x.block != block' + reached_vars[id(x)] = x + + # Reaching test, returning whether an op is reached from the given input + reaching = lambda op: any( + id(v) in reached_vars + for v in flatten_and_remove_none(get_input_var_list(op)) + ) + + # block.ops are supposedly in the order that preserves correct data + # dependence. + # Forward pass to identify all reached variables and ops + for op in block.ops: + if reaching(op): + path.append(op) + for var in flatten_and_remove_none(get_output_var_list(op)): + reached_vars[id(var)] = var + + used_vars = OrderedDict((id(y), y) for y in ys if id(y) in reached_vars) + back_reaching = lambda op: any( + id(out) in used_vars + for out in flatten_and_remove_none(get_output_var_list(op)) + ) + + # Backward pass to find all used variables + for op in reversed(path): + if back_reaching(op): + backpath.append(op) + for var in flatten_and_remove_none(get_input_var_list(op)): + used_vars[id(var)] = var + + unused_xs = [x for x in xs if id(x) not in used_vars] + unreached_ys = [y for y in ys if id(y) not in reached_vars] + + return list(reversed(backpath)), unused_xs, unreached_ys + + +def output_vars_on_path(path): + """Returns the output variables of all the ops on the path from `xs` + to `ys`. + + Args: + path: a list of ops on which to find the output variables + + Returns: + vars: the output vars + """ + vars = OrderedDict() + for op in path: + for out in flatten_and_remove_none(get_output_var_list(op)): + vars[id(out)] = out + + return vars + + +class VarMap(object): + """A general map data structure for linking variables to variables. + + An example is linking variables to their gradients. + """ + + __slots__ = ['name', 'varset', 'tab'] + + def __init__(self, name, varset): + self.name = name + self.varset = varset + self.tab = OrderedDict() + + def add(self, key_var, value_var): + self.tab[id(key_var)] = id(value_var) + + def add_rec(self, key_vars, value_vars): + if value_vars is None: + return + if isinstance(key_vars, paddle.fluid.framework.Variable): + if not isinstance(value_vars, paddle.fluid.framework.Variable): + raise TypeError( + f'value_vars must be Variable, but got {type(value_vars)}' + ) + self.tab[id(key_vars)] = id(value_vars) + else: + assert len(key_vars) == len(value_vars), ( + f'len(key_vars) shoule be equal to len(value_vars), ' + f'but len(key_vars)={len(key_vars)} and len(value_vars)={len(value_vars)}.' + ) + for key_var, value_var in zip(key_vars, value_vars): + self.add_rec(key_var, value_var) + + def lookup(self, key_var): + value_id = self.tab.get(id(key_var)) + if value_id is not None: + return self.varset.get(value_id) + else: + return None + + def delete(self, key_var): + varid = id(key_var) + if varid in self.tab: + del self.tab[id(key_var)] + + def delete_keyvars(self, key_vars): + for var in key_vars: + varid = id(var) + if varid in self.tab: + del self.tab[varid] + + def delete_valuevars(self, value_vars): + ids = [id(v) for v in value_vars] + keys = [k for k, v in self.tab.items() if v in ids] + for k in keys: + del self.tab[k] + + def contain_var(self, key_var): + return self.tab.__contains__(id(key_var)) + + def contain_value(self, value_var): + return id(value_var) in self.tab.values() + + +# TODO(lml): supporting control flow, nested blocks, and block other than current block of main program. +class Transform(object): + """An object that maintains the state of transformations applied to a + primitve program.""" + + def __init__(self, block): + assert ( + block == default_main_program().current_block() + ), f'only support transform on current block of main program.' + self.block = block + self.vars = self.init_vars(block) + self.var2dot = VarMap('var2dot', self.vars) + self.dot2bar = VarMap('dot2var', self.vars) + + def init_vars(self, block): + vars = OrderedDict() + for _, var in block.vars.items(): + vars[id(var)] = var + return vars + + def add_vars(self, new_vars): + self.vars.update({id(v): v for v in new_vars if v is not None}) + + def add_vars_rec(self, new_vars): + if new_vars is None: + return + if isinstance(new_vars, paddle.fluid.framework.Variable): + self.vars.update({id(new_vars): new_vars}) + return + if not isinstance(new_vars, list): + raise TypeError(f'new_vars must be list, but got {type(new_vars)}') + for var in new_vars: + self.add_vars_rec(var) + + def erase_ops(self, ordered_indexes): + block = self.block + for op_index in reversed(ordered_indexes): + block.desc._remove_op(op_index, op_index + 1) + + # remove from block.ops + for op_index in reversed(ordered_indexes): + del block.ops[op_index] + + block._sync_with_cpp() + + def erase_dots(self, vars_to_erase): + for var in vars_to_erase: + if id(var) in self.vars: + del self.vars[id(var)] + self.dot2bar.delete_keyvars(vars_to_erase) + self.var2dot.delete_valuevars(vars_to_erase) + block = self.block + for var in vars_to_erase: + name = var.name + block.desc._remove_var(cpt.to_bytes(name)) + del block.vars[name] + block._sync_with_cpp() + + def var2dot_rec(self, vars): + """Lookup var2dot recursively.""" + if isinstance(vars, paddle.fluid.framework.Variable): + dot = self.var2dot.lookup(vars) + return dot + + dots = [self.var2dot_rec(var) for var in vars] + return dots + + def dot2bar_rec(self, dots): + + if isinstance(dots, paddle.fluid.framework.Variable): + bar = self.dot2bar.lookup(dots) + assert bar is not None, 'bar must be not None' + return bar + + bars = [self.dot2bar_rec(dot) for dot in dots] + return bars + + def linearize(self, xs, ys, xs_dot=None): + """Performs the linearization transform, a.k.a, forward mode AD + transform, on a primitive lowered program. + + Args: + xs: a list of input variables + ys: a list of output variables + xs_dot: optional, a list of gradient input variables. The list size + must be equal to `len(xs)`. The shape and dtype of each element + must be the same as in `xs` + + Returns: + (xs_dot, ys_dot): a tuple of two lists. `xs_dot` is the list of + gradient inputs of the resulting linearized program. `ys_dot` is + the list gradient outputs of the resulting linearized program + + """ + if xs_dot is None: + xs_dot = [fill_const(1.0, shape=x.shape, dtype=x.dtype) for x in xs] + self.add_vars(xs_dot) + else: + assert len(xs) == len(xs_dot), ( + f'len(xs) should be equal to len(xs_dot), ' + f'but len(xs)={len(xs)} and len(xs_dot)={len(xs_dot)}' + ) + + for x, dot in zip(xs, xs_dot): + assert x.dtype == dot.dtype, ( + f'x.dtype should be equal to dot.dtype, ' + f'but x.dtype={x.dtype} and dot.dtype={dot.dtype}' + ) + assert x.shape == dot.shape, ( + f'x.shape should be equal to dot.shape, ' + f'but x.shape={x.shape} and dot.shape={dot.shape}' + ) + self.var2dot.add(x, dot) + + path, unused_xs, _ = topo_path(xs, ys, self.block) + + # No need to track unused inputs + for x in unused_xs: + self.var2dot.delete(x) + + for op in path: + # An input var may not be on the input-output path, which implies + # there may be None's in `ins_dot`. In this case we place + # the original input in the position of the otherwise forward + # gradient. + ins = op_position_inputs(op) + jvp_ins = self.var2dot_rec(ins) + # apply op's forward ad rule + outs_dot = _jvp(op, *jvp_ins) + self.add_vars_rec(outs_dot) + outs = op_position_output(op) + self.var2dot.add_rec(outs, outs_dot) + + ys_dot = [self.var2dot.lookup(y) for y in ys] + return xs_dot, ys_dot + + def transpose(self, ys_dot, xs_dot, ys_bar=None, retain_fwd=False): + """Performs the transpose transform, a.k.a, reverse mode AD + transform, on a linearized primitive program. + + Note, `transpose` is supposed to be used in couple with `linearize`. + + Args: + ys_dot: a list of outputs of the linearized program. + xs_dot: a list of inputs of the linearized program. + ys_bar: optional, a list of inputs of the resulting transposed + program. The list size must be equal to `len(ys_dot)`. The shape + and dtype of each element must be the same as in `ys_dot` + + Returns: + (ys_bar, xs_bar): a tuple of two lists. `ys_bar` is the list of + inputs of the resulting transposed program. `xs_bar` is + the list outputs of the resulting transposed program + + """ + assert all(v is not None for v in xs_dot), f'`xs_dot` includes None.' + assert all(v is not None for v in ys_dot), f'`ys_dot` includes None.' + + if ys_bar is None: + ys_bar = [] + for y in ys_dot: + ys_bar.append(fill_const(1.0, shape=y.shape, dtype=y.dtype)) + self.add_vars(ys_bar) + else: + assert len(ys_dot) == len(ys_bar), ( + f'len(ys_dot) should be equal to len(ys_bar), ' + f'but len(ys_dot)={len(ys_dot)} and len(ys_bar)={len(ys_bar)}' + ) + for y_dot, y_bar in zip(ys_dot, ys_bar): + assert y_dot.shape == y_bar.shape, ( + f'y_dot.shape should be equal to y_bar.shape, ' + f'but y_dot.shape={y_dot.shape} and y_bar.shape={y_bar.shape}' + ) + assert y_dot.dtype == y_bar.dtype, ( + f'y_dot.dtype should be equal to y_bar.dtype, ' + f'but y_dot.dtype={y_dot.dtype} and y_bar.dtype={y_bar.dtype}' + ) + + for dot, bar in zip(ys_dot, ys_bar): + self.dot2bar.add(dot, bar) + + # find all the relevant forward gradients + path, unused_xs_dot, _ = topo_path(xs_dot, ys_dot, self.block) + + # No need to track unused inputs + for dot in unused_xs_dot: + self.dot2bar.delete(dot) + + dotvars = output_vars_on_path(path) + dotvars.update((id(var), var) for var in xs_dot) + + is_dot = lambda v: id(v) in dotvars + + for op in reversed(path): + out = op_position_output(op) + out_bar_rec = self.dot2bar_rec(out) + ins_bar_rec = _transpose(op, is_dot, out_bar_rec) + + # TODO(Tongxin): this is hacky. Tuple implies the Transpose rule + # returns multiple entities. There should be better ways to handle + # outputs. + if isinstance(ins_bar_rec, tuple): + ins_bar_rec = list(ins_bar_rec) + else: + ins_bar_rec = [ins_bar_rec] + self.add_vars_rec(ins_bar_rec) + + ins_bar = flatten(ins_bar_rec) + ins = flatten(op_position_inputs(op)) + assert len(ins) == len(ins_bar), ( + f'len(ins) should be equal to len(ins_bar), ' + f'but len(ins)={len(ins)} and len(ins_bar)={len(ins_bar)}' + ) + + for dot, bar in zip(ins, ins_bar): + if bar is not None: + # aggregate gradient + grad = self.dot2bar.lookup(dot) + if grad is None: + self.dot2bar.add(dot, bar) + else: + grad = add(grad, bar) + self.add_vars([grad]) + self.dot2bar.add(dot, grad) + + xs_bar = [self.dot2bar.lookup(x) for x in xs_dot] + + if not retain_fwd and len(path) > 0: + vars_to_remove = set() + for op in path: + vars_to_remove.update( + flatten_and_remove_none(get_output_var_list(op)) + ) + + op_indexes = [] + + block = self.block + for i, op in enumerate(block.ops): + if op in path: + op_indexes.append(i) + path.pop(0) + if len(path) == 0: + break + + self.erase_ops(op_indexes) + self.erase_dots(vars_to_remove) + + return ys_bar, xs_bar + + +# TODO(lml): supporting control flow, nested blocks, and block other than current block of main program. +def _lower(block, reverse, blacklist): + # Some functions which are only used in _lower. + def bind(args, to_bind, value_table): + for i in range(len(args)): + if isinstance(args[i], list): + bind(args[i], to_bind, value_table) + elif args[i] is not None and args[i].name in to_bind: + args[i] = value_table[to_bind[args[i].name]] + + def bind_name(names, to_bind): + return_list = [] + for name in names: + if isinstance(name, list): + return_list.append(bind_name(name, to_bind)) + else: + return_list.append(to_bind[name] if name in to_bind else name) + return return_list + + def expand_nested_list(xs): + return_list = [] + for x in xs: + if isinstance(x, list): + return_list = return_list + expand_nested_list(x) + else: + return_list.append(x) + return return_list + + # Step1: Do some preparatory work for lower + lower_fn = _prim2orig if reverse else _orig2prim + lookup_fn = lookup_prim2orig if reverse else lookup_orig2prim + + value_table = {} + to_bind = {} + to_bind_rev = {} + for var in block.desc.all_vars(): + value_table[var.name()] = block.var(var.name()) + + ops_to_remove = [] + vars_to_remove = set() + + # Step2: Process all ops in the target block + for op_idx in range(len(block.ops)): + op = block.ops[op_idx] + ops_to_remove.append(op_idx) + if lookup_fn(op.type) is not None and op.type not in blacklist: + input_args = get_input_var_list(op) + bind(input_args, to_bind, value_table) + + for orig_out, new_out in zip( + expand_nested_list(get_output_var_list(op)), + expand_nested_list(as_tensors(lower_fn(op, *input_args))), + ): + assert not (orig_out is None) ^ ( + new_out is None + ), "orig_out and new_out should match." + vars_to_remove.add(new_out.name) + value_table[new_out.name] = new_out + to_bind[orig_out.name] = new_out.name + to_bind_rev[new_out.name] = orig_out.name + else: + inputs = {} + for i in range(len(op.input_names)): + inputs[op.input_names[i]] = bind_name( + op.input(op.input_names[i]), to_bind + ) + + outputs = {} + for i in range(len(op.output_names)): + outputs[op.output_names[i]] = op.output(op.output_names[i]) + + attrs = {} + for name in sorted(op.attr_names): + attrs[name] = op.attr(name) + from paddle.fluid.dygraph.base import param_guard + + new_op_desc = block.desc.append_op() + with param_guard(inputs), param_guard(outputs): + op = Operator( + block=block, + desc=new_op_desc, + type=op.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + ) + block.ops.append(op) + + # Step3: Do some post-processing work + for op_idx in reversed(ops_to_remove): + block.desc._remove_op(op_idx, op_idx + 1) + del block.ops[op_idx] + block._sync_with_cpp() + + for op_idx in range(len(block.ops)): + op = block.ops[op_idx] + for in_name in op.input_arg_names: + if in_name in to_bind_rev: + op._rename_input(in_name, to_bind_rev[in_name]) + + for out_name in op.output_arg_names: + if out_name in to_bind_rev: + op._rename_output(out_name, to_bind_rev[out_name]) + + for var_name in sorted(vars_to_remove): + assert ( + var_name in to_bind_rev + ), 'var_name "{}" is not in to_bind_rev.'.format(var_name) + if var_name != to_bind_rev[var_name]: + block.desc._remove_var(cpt.to_bytes(var_name)) + del block.vars[var_name] + block._sync_with_cpp() + + +@framework.static_only +def orig2prim(block=None): + """ + Note: + **This API is ONLY available in the static mode.** + **Args block must be None or current block of main program.** + + All operators in the target block are processed as follows. + If it is an original operator, it will be transformed into + one or a series of automatic differential basic operators with + equivalent function. + + Args: + block(paddle.static.Block|None, optional): The + target block to process on. Default None, and will + process on the current block of main program. + """ + + block = default_main_program().current_block() if block is None else block + assert ( + block == default_main_program().current_block() + ), f'block is neither None nor current block of main program' + _lower(block, reverse=False, blacklist=[]) + + +@framework.static_only +def prim2orig(block=None, blacklist=None): + """ + Note: + **ONLY available in the static mode.** + **Args block must be None or current block of main program.** + + All operators in the target block are processed as follows. + If it is an automatic differential basic operator, it will be + transformed into one or a series of original operators with + equivalent function to support execution. + + Args: + block(paddle.static.Block|None, optional): The + target block to process on. Default None, and will + process on the current block of main program. + blacklist(list[string]|None, optional): The names of automatic + differential basic operator that will not be transformed + into original operators. Default None, and the blacklist + is treated as empty list. + + Examples: + + .. code-block:: python + + import paddle + from paddle.incubate.autograd import enable_prim, prim_enabled, prim2orig + + paddle.enable_static() + enable_prim() + + x = paddle.ones(shape=[2, 2], dtype='float32') + x.stop_gradients = False + y = x * x + dy_dx = paddle.static.gradients(y, x) + if prim_enabled(): + prim2orig() + """ + + block = default_main_program().current_block() if block is None else block + assert ( + block == default_main_program().current_block() + ), f'block is neither None nor current block of main program' + blacklist = [] if blacklist is None else blacklist + _lower(block, reverse=True, blacklist=blacklist) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b8082bf48de7a83b585e38418ca8951fab548ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autograd/utils.py @@ -0,0 +1,181 @@ +# Copyright (c) 2022 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. +import typing + +import paddle +from paddle.fluid import framework as framework + + +class PrimOption(object): + def __init__(self): + self.enable_prim = False + + def get_status(self): + return self.enable_prim + + def set_status(self, flag): + self.enable_prim = flag + + +prim_option = PrimOption() + + +@framework.static_only +def prim_enabled(): + """ + Note: + **ONLY available in the static mode.** + + Shows whether the automatic differentiation mechanism based on + automatic differential basic operators is ON. Defaults to OFF. + + Returns: + flag(bool): Whether the automatic differentiation mechanism based on automatic differential basic operators is ON. + + Examples: + + .. code-block:: python + + import paddle + from paddle.incubate.autograd import enable_prim, disable_prim, prim_enabled + + paddle.enable_static() + enable_prim() + + print(prim_enabled()) # True + + disable_prim() + + print(prim_enabled()) # False + """ + return prim_option.get_status() + + +@framework.static_only +def enable_prim(): + """ + Note: + **ONLY available in the static mode.** + + Turns ON automatic differentiation mechanism based on automatic + differential basic operators. + + Examples: + + .. code-block:: python + + import paddle + from paddle.incubate.autograd import enable_prim, prim_enabled + + paddle.enable_static() + enable_prim() + + print(prim_enabled()) # True + """ + prim_option.set_status(True) + + +@framework.static_only +def disable_prim(): + """ + Note: + **ONLY available in the static mode.** + + Turns OFF automatic differentiation mechanism based on automatic + differential basic operators. + + Examples: + + .. code-block:: python + + import paddle + from paddle.incubate.autograd import enable_prim, disable_prim, prim_enabled + + paddle.enable_static() + enable_prim() + + print(prim_enabled()) # True + + disable_prim() + + print(prim_enabled()) # False + """ + prim_option.set_status(False) + + +INT_DTYPE_2_STRING = { + int(0): 'bool', + int(1): 'int16', + int(2): 'int32', + int(3): 'int64', + int(4): 'float16', + int(5): 'float32', + int(6): 'float64', + int(20): 'uint8', + int(21): 'int8', + int(23): 'complex64', + int(24): 'complex128', +} + + +def get_var_block(block, names): + assert isinstance(names, list) + if len(names) == 0: + return None + elif len(names) == 1: + return block.var(names[0]) + else: + return [block.var(name) for name in names] + + +def get_input_var_list(op): + if op.input_names is None: + return [] + else: + return [ + get_var_block(op.block, op.input(n)) for n in sorted(op.input_names) + ] + + +def get_output_var_list(op): + if op.output_names is None: + return [] + else: + return [ + get_var_block(op.block, op.output(n)) + for n in sorted(op.output_names) + ] + + +def flatten(inp): + if inp is None or isinstance(inp, paddle.fluid.framework.Variable): + return [inp] + flattened = [] + for part in inp: + flattened += flatten(part) + return flattened + + +def flatten_and_remove_none(inp): + flattened = flatten(inp) + return [var for var in flattened if var is not None] + + +def as_tensors(xs): + if isinstance(xs, framework.Variable): + return (xs,) + elif isinstance(xs, typing.Sequence): + return tuple(xs) + else: + return xs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autotune.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autotune.py new file mode 100644 index 0000000000000000000000000000000000000000..4c577cba3e70c3348dd47dd1d9b987d5029be2a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/autotune.py @@ -0,0 +1,156 @@ +# Copyright (c) 2022 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. + +import paddle +import json +import warnings +from paddle.fluid import core + +__all__ = ['set_config'] + + +def set_config(config=None): + r""" + Set the configuration for kernel, layout and dataloader auto-tuning. + + 1. kernel: When it is enabled, exhaustive search method will be used to select + and cache the best algorithm for the operator in the tuning iteration. Tuning + parameters are as follows: + + - enable(bool): Whether to enable kernel tuning. + - tuning_range(list): Start and end iteration for auto-tuning. Default: [1, 10]. + + 2. layout: When it is enabled, the best data layout such as NCHW or NHWC will be + determined based on the device and data type. When the origin layout setting is + not best, layout transformation will be automaticly performed to improve model + performance. Layout auto-tuning only supports dygraph mode currently. Tuning + parameters are as follows: + + - enable(bool): Whether to enable layout tuning. + + 3. dataloader: When it is enabled, the best num_workers will be selected to replace + the origin dataloader setting. Tuning parameters are as follows: + + - enable(bool): Whether to enable dataloader tuning. + + Args: + config (dict|str|None, optional): Configuration for auto-tuning. If it is a + dictionary, the key is the tuning type, and the value is a dictionary + of the corresponding tuning parameters. If it is a string, the path of + a json file will be specified and the tuning configuration will be set + by the json file. Default: None, auto-tuning for kernel, layout and + dataloader will be enabled. + + Examples: + .. code-block:: python + + import paddle + import json + + # config is a dict. + config = { + "kernel": { + "enable": True, + "tuning_range": [1, 5], + }, + "layout": { + "enable": True, + }, + "dataloader": { + "enable": True, + } + } + paddle.incubate.autotune.set_config(config) + + # config is the path of json file. + config_json = json.dumps(config) + with open('config.json', 'w') as json_file: + json_file.write(config_json) + paddle.incubate.autotune.set_config('config.json') + + """ + if config is None: + core.enable_autotune() + core.enable_layout_autotune() + paddle.fluid.reader.set_autotune_config(use_autotune=True) + return + + config_dict = {} + if isinstance(config, dict): + config_dict = config + elif isinstance(config, str): + try: + with open(config, 'r') as filehandle: + config_dict = json.load(filehandle) + except Exception as e: + print('Load config error: {}'.format(e)) + warnings.warn("Use default configuration for auto-tuning.") + + if "kernel" in config_dict: + kernel_config = config_dict["kernel"] + if "enable" in kernel_config: + if isinstance(kernel_config['enable'], bool): + if kernel_config['enable']: + core.enable_autotune() + else: + core.disable_autotune() + else: + warnings.warn( + "The auto-tuning configuration of the kernel is incorrect." + "The `enable` should be bool. Use default parameter instead." + ) + if "tuning_range" in kernel_config: + if isinstance(kernel_config['tuning_range'], list): + tuning_range = kernel_config['tuning_range'] + assert len(tuning_range) == 2 + core.set_autotune_range(tuning_range[0], tuning_range[1]) + else: + warnings.warn( + "The auto-tuning configuration of the kernel is incorrect." + "The `tuning_range` should be list. Use default parameter instead." + ) + if "layout" in config_dict: + layout_config = config_dict["layout"] + if "enable" in layout_config: + if isinstance(layout_config['enable'], bool): + if layout_config['enable']: + core.enable_layout_autotune() + else: + core.disable_layout_autotune() + else: + warnings.warn( + "The auto-tuning configuration of the layout is incorrect." + "The `enable` should be bool. Use default parameter instead." + ) + if "dataloader" in config_dict: + dataloader_config = config_dict["dataloader"] + use_autoune = False + if "enable" in dataloader_config: + if isinstance(dataloader_config['enable'], bool): + use_autoune = dataloader_config['enable'] + else: + warnings.warn( + "The auto-tuning configuration of the dataloader is incorrect." + "The `enable` should be bool. Use default parameter instead." + ) + if "tuning_steps" in dataloader_config: + if isinstance(dataloader_config['tuning_steps'], int): + paddle.fluid.reader.set_autotune_config( + use_autoune, dataloader_config['tuning_steps']) + else: + warnings.warn( + "The auto-tuning configuration of the dataloader is incorrect." + "The `tuning_steps` should be int. Use default parameter instead." + ) + paddle.fluid.reader.set_autotune_config(use_autoune) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/checkpoint/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79e6259de0275410664b9bfb2c34c33e21c5d529 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/checkpoint/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2021 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. + +from ...fluid.incubate.checkpoint import auto_checkpoint # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/fleet/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/fleet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94e1a7c8bbe77bbf763f462d48fc5812243817f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/fleet/__init__.py @@ -0,0 +1,17 @@ +# Copyright (c) 2022 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. + +from paddle.distributed.fleet.recompute import recompute_sequential, recompute_hybrid + +__all__ = ["recompute_sequential", "recompute_hybrid"] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..795c939e81fbb73fe77418b7ae138fec57ff2eca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) 2022 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. + +from .gate import GShardGate, BaseGate, SwitchGate, NaiveGate +from .moe_layer import MoELayer +from .grad_clip import ClipGradForMOEByGlobalNorm + +ClipGradByGlobalNorm = ClipGradForMOEByGlobalNorm diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2bfa5cd62cd497bbd552034542dc1302e57baa33 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2022 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. + +from .gshard_gate import GShardGate +from .switch_gate import SwitchGate +from .naive_gate import NaiveGate +from .base_gate import BaseGate diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/base_gate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/base_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..9715f4b2a25a60ee7459294d25284e6503b8e293 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/base_gate.py @@ -0,0 +1,44 @@ +# Copyright (c) 2022 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/gates/base_gate.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +import paddle.nn as nn + + +class BaseGate(nn.Layer): + + def __init__(self, num_expert, world_size): + super().__init__() + self.world_size = world_size + self.num_expert = num_expert + self.tot_expert = world_size * num_expert + self.loss = None + + def forward(self, x): + raise NotImplementedError("Please implement the forward function.") + + def set_loss(self, loss): + self.loss = loss + + def get_loss(self, clear=True): + loss = self.loss + if clear: + self.loss = None + return loss diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/gshard_gate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/gshard_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..643e23feff164ce4e344f7e9bed0430e885130b5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/gshard_gate.py @@ -0,0 +1,72 @@ +# Copyright (c) 2022 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/gates/gshard_gate.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +import math +import paddle +import paddle.nn.functional as F +import numpy as np +from .naive_gate import NaiveGate +from ..utils import limit_by_capacity + + +class GShardGate(NaiveGate): + + def __init__(self, + d_model, + num_expert, + world_size, + topk=2, + capacity=(1.2, 2.4), + random_routing=True, + group=None): + assert topk == 2, "topk should be 2 in gshard" + super().__init__(d_model, num_expert, world_size) + self.capacity = capacity + self.random_routing = random_routing + self.group = group + + def forward(self, x): + topk_val, topk_idx, gate_score = super().forward(x, + return_all_scores=True) + s = gate_score.shape[0] + top1_idx = topk_idx.flatten() + c_e = paddle.scatter(paddle.zeros(shape=[self.tot_expert]), + top1_idx, + paddle.ones_like(top1_idx, dtype="float32"), + overwrite=False) / s + m_e = paddle.mean(F.softmax(gate_score, axis=1), axis=0) + loss = paddle.mean(c_e * m_e) * (self.num_expert**2) + self.set_loss(loss) + + cap_rate = self.capacity[0 if self.training else 1] + capacity = math.ceil(cap_rate * x.shape[0]) + _new_lec, _new_gec, topk_idx = limit_by_capacity(topk_idx, + self.num_expert, + self.world_size, + capacity, + group=self.group) + + if self.random_routing: + rand_routing_prob = paddle.rand(shape=[gate_score.shape[0]], + dtype="float32") + topk_idx = paddle.distributed.models.moe.utils._random_routing( + topk_idx, topk_val, rand_routing_prob) + return topk_val, topk_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/naive_gate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/naive_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..476f99b9f4431ce5a3884a78ee07d4b8557fef7d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/naive_gate.py @@ -0,0 +1,48 @@ +# Copyright (c) 2022 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/gates/naive_gate.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +from .base_gate import BaseGate + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + + +class NaiveGate(BaseGate): + + def __init__(self, d_model, num_expert, world_size, topk=2): + super().__init__(num_expert, world_size) + self.gate = nn.Linear(d_model, self.tot_expert) + self.gate.weight.name = "gate_" + self.gate.weight.name + self.gate.bias.name = "gate_" + self.gate.bias.name + self.top_k = topk + + def forward(self, inp, return_all_scores=False): + gate = self.gate(inp) + gate_top_k_val, gate_top_k_idx = paddle.topk(gate, + k=self.top_k, + axis=-1, + largest=True, + sorted=False) + + if return_all_scores: + return gate_top_k_val, gate_top_k_idx, gate + return gate_top_k_val, gate_top_k_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/switch_gate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/switch_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..604751985406a5da6669583714acecd7281cc811 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/gate/switch_gate.py @@ -0,0 +1,76 @@ +# Copyright (c) 2022 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/gates/switch_gate.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +import math +import paddle +import paddle.nn as nn +import paddle.nn.functional as F +from .naive_gate import NaiveGate +from ..utils import limit_by_capacity + + +class SwitchGate(NaiveGate): + + def __init__(self, + d_model, + num_expert, + world_size, + topk=1, + switch_eps=.1, + capacity=(1.2, 2.4), + group=None): + assert topk == 1, "topk should be 1 in switch" + super().__init__(d_model, num_expert, world_size, topk=1) + self.switch_eps = switch_eps + self.capacity = capacity + self.group = group + + def forward(self, inp): + score = self.gate(inp) + + if self.training: + noise = paddle.rand(shape=score.shape) + noise = noise * 2 * self.switch_eps + 1.0 - self.switch_eps + score += noise + + score = F.softmax(score, axis=-1) + top1_score, top1_idx = paddle.topk(score, k=1, axis=-1, largest=True) + + cap_rate = self.capacity[0 if self.training else 1] + capacity = math.ceil(cap_rate * inp.shape[0]) + _new_lec, _new_gec, top1_idx = limit_by_capacity(top1_idx, + self.num_expert, + self.world_size, + capacity, + group=self.group) + valid_idx = top1_idx[top1_idx > -1] + valid_idx_tmp = paddle.reshape(valid_idx, shape=[len(valid_idx), 1]) + fraction_expert = paddle.scatter_nd_add( + x=paddle.zeros(shape=[self.tot_expert]), + index=valid_idx_tmp, + updates=paddle.ones_like(valid_idx, dtype=paddle.float32).reshape( + shape=[len(valid_idx)]), + ) / valid_idx.numel() + prob_expert = score.sum(axis=0) / valid_idx.numel() + loss = (fraction_expert * prob_expert).sum() * self.tot_expert + self.set_loss(loss) + + return top1_score, top1_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/grad_clip.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/grad_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..83e491a08745bee62de1290a5abf1bd136b6c855 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/grad_clip.py @@ -0,0 +1,222 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +from paddle.fluid.clip import ClipGradBase, _squared_l2_norm +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid import core, layers, framework +from paddle.distributed import collective +import six +import warnings +import copy + + +class ClipGradForMOEByGlobalNorm(ClipGradBase): + r""" + The Algrithm is the same as paddle.fluid.clip.ClipGradByGlobalNorm + Given a list of Tensor :math:`t\_list` , calculate the global norm for the elements of all tensors in + :math:`t\_list` , and limit it to ``clip_norm`` . + + - If the global norm is greater than ``clip_norm`` , all elements of :math:`t\_list` will be compressed by a ratio. + + - If the global norm is less than or equal to ``clip_norm`` , nothing will be done. + + The list of Tensor :math:`t\_list` is not passed from this class, but the gradients of all parameters set in ``optimizer``. + If ``need_clip`` of specific param is ``False`` in its ``ParamAttr``, then the gradients of this param will not be clipped. + + Gradient clip will takes effect after being set in ``optimizer`` , see the document ``optimizer`` + (for example: :ref:`api_paddle_optimizer_SGD`). + + The clipping formula is: + + .. math:: + + t\_list[i] = t\_list[i] * \frac{clip\_norm}{\max(global\_norm, clip\_norm)} + + where: + + .. math:: + + global\_norm = \sqrt{\sum_{i=0}^{N-1}(l2norm(t\_list[i]))^2} + + Note: + ``need_clip`` of ``ClipGradyGlobalNorm`` HAS BEEN DEPRECATED since 2.0. + Please use ``need_clip`` in ``ParamAttr`` to speficiy the clip scope. + + Reference: + https://github.com/laekov/fastmoe/blob/master/examples/megatron/clip-grad-v2.2.patch + Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 + + + Args: + clip_norm (float): The maximum norm value. + is_expert_param_func (function): a function to decide whether a param should be put into moe_params_grads + moe_group (Group): group for moe experts communication. + group_name (str, optional): The group name for this clip. Default value is ``default_moe_group``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.uniform([10, 10], min=-1.0, max=1.0, dtype='float32') + linear = paddle.nn.Linear(in_features=10, out_features=10, + weight_attr=paddle.ParamAttr(need_clip=True), + bias_attr=paddle.ParamAttr(need_clip=False)) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + + is_expert_func = lambda param: "expert_" in param.name + clip = paddle.nn.ClipGradForMOEByGlobalNorm(clip_norm=1.0,is_expert_func, None) + sdg = paddle.optimizer.SGD(learning_rate=0.1, parameters=linear.parameters(), grad_clip=clip) + sdg.step() + """ + + def __init__(self, + clip_norm, + is_expert_param_func=None, + moe_group=None, + group_name="default_moe_group"): + super(ClipGradForMOEByGlobalNorm, self).__init__() + self.clip_norm = float(clip_norm) + self.group_name = group_name + self.moe_group = moe_group + if moe_group is not None and moe_group.nranks > 1: + assert is_expert_param_func is not None, \ + "When moe group size > 1, a function for selecting expert params must be specified." + self.is_expert_param_func = is_expert_param_func + + def __str__(self): + return "Gradient Clip By GlobalNorm, global_norm=%f" % (self.clip_norm) + + @staticmethod + def get_l2_norm_pow(params_grads, sum_dtype=None): + sum_square_list = [] + sum_square_list_fp16 = [] + sum_square_list_fp32 = [] + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + continue + merge_grad = g + if g.type == core.VarDesc.VarType.SELECTED_ROWS: + merge_grad = layers.merge_selected_rows(g) + merge_grad = layers.get_tensor_from_selected_rows(merge_grad) + sum_square = _squared_l2_norm(merge_grad) + if sum_square.dtype == core.VarDesc.VarType.FP16: + sum_square_list_fp16.append(sum_square) + elif sum_square.dtype == core.VarDesc.VarType.FP32: + sum_square_list_fp32.append(sum_square) + else: + sum_square_list.append(sum_square) + + # all parameters have been filterd out + if len(sum_square_list) + len(sum_square_list_fp16) + len( + sum_square_list_fp32) == 0: + return None, None + assert sum_dtype in ["float64", "float32", None], \ + "sum's type must be float64/ float32 / None" + if sum_dtype != "float64": + sum_dtype = 'float64' if len(sum_square_list) > 0 else "float32" + + global_norm_var = [] + if len(sum_square_list_fp16) > 0: + global_norm_var_fp16 = layers.concat(sum_square_list_fp16) + global_norm_var_fp16 = layers.reduce_sum(global_norm_var_fp16) + global_norm_var.append(global_norm_var_fp16.astype(sum_dtype)) + if len(sum_square_list_fp32) > 0: + global_norm_var_fp32 = layers.concat(sum_square_list_fp32) + global_norm_var_fp32 = layers.reduce_sum(global_norm_var_fp32) + if sum_dtype == 'float32': + global_norm_var.append(global_norm_var_fp32) + else: + global_norm_var.append(global_norm_var_fp32.astype(sum_dtype)) + if len(sum_square_list) > 0: + global_norm_var_fp64 = layers.concat(sum_square_list) + global_norm_var_fp64 = layers.reduce_sum(global_norm_var_fp64) + global_norm_var.append(global_norm_var_fp64) + global_norm_var = layers.concat(global_norm_var) + global_norm_var = layers.reduce_sum(global_norm_var) + return global_norm_var, sum_dtype + + @imperative_base.no_grad + def _dygraph_clip(self, params_grads): + normal_params_grads = [] + moe_params_grads = [] + + # separate moe params from normal params + if self.moe_group is not None and self.moe_group.nranks > 1: + for p, g in params_grads: + if self.is_expert_param_func(p): + moe_params_grads.append((p, g)) + else: + normal_params_grads.append((p, g)) + else: + normal_params_grads = params_grads + + # why to return sum_dtype? + # we will call `get_l2_norm_pow` twice and the precisions may be different. + # For convenience and simplification, we use sum_dtype directly instead of global_norm_var_normal.dtype + global_norm_var_normal, sum_dtype \ + = self.get_l2_norm_pow(normal_params_grads) + global_norm_var_moe = None + if len(moe_params_grads) > 0: + global_norm_var_moe, _ \ + = self.get_l2_norm_pow(moe_params_grads, sum_dtype) + if global_norm_var_moe is not None: + collective.all_reduce(global_norm_var_moe, + op=collective.ReduceOp.SUM, + group=self.moe_group) + + if global_norm_var_normal is None and global_norm_var_moe is None: + return params_grads + elif global_norm_var_normal is None: + global_norm_var = global_norm_var_moe + elif global_norm_var_moe is None: + global_norm_var = global_norm_var_normal + else: + if global_norm_var_normal.dtype != global_norm_var_moe.dtype: + # compared with normal norm, moe norm is the later one, + # so its precision is no lower than normal norm + global_norm_var_normal = \ + global_norm_var_normal.astype(global_norm_var_moe.dtype) + global_norm_var = global_norm_var_normal + global_norm_var_moe + + params_and_grads = [] + global_norm_var = layers.sqrt(global_norm_var) + max_global_norm = layers.fill_constant(shape=[1], + dtype=global_norm_var.dtype, + value=self.clip_norm) + clip_var = layers.elementwise_div(x=max_global_norm, + y=layers.elementwise_max( + x=global_norm_var, + y=max_global_norm)) + for p, g in params_grads: + if g is None: + continue + if getattr(p, 'need_clip', True) is False: + params_and_grads.append((p, g)) + continue + # TODO(wangxi): use inplace elementwise_mul + clip_input = (clip_var.astype('float16') + if g.dtype == core.VarDesc.VarType.FP16 else clip_var) + new_grad = layers.elementwise_mul(x=g, y=clip_input) + params_and_grads.append((p, new_grad)) + return params_and_grads + + +ClipGradByGlobalNorm = ClipGradForMOEByGlobalNorm diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/moe_layer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/moe_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..0a0fe32a8e9186be8a2f48f3488ac0137df45538 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/moe_layer.py @@ -0,0 +1,445 @@ +# Copyright (c) 2021 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/layers.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +import collections +import math + +import numpy as np +import paddle +import paddle.nn as nn +import paddle.nn.functional as F +from paddle.distributed.utils.moe_utils import global_scatter, global_gather +from paddle.distributed import alltoall, all_gather + +from paddle.distributed.fleet.meta_parallel import get_rng_state_tracker +from paddle.distributed import fleet +from paddle.autograd import PyLayer +from .gate import NaiveGate, GShardGate, SwitchGate, BaseGate +from .utils import count_by_gate +from paddle import fluid +from paddle.fluid.framework import in_dygraph_mode +from paddle.incubate.distributed.fleet import recompute_hybrid + + +def _local_scatter(inp, pos): + if pos.shape != [0]: + inp_buf = paddle.index_select(inp, pos, 0) + else: + inp_buf = paddle.empty([0, inp.shape[1]], dtype=inp.dtype) + return inp_buf + + +def _local_gather(inp, pos, out_batch_size, maybe_overlap=True): + if pos.shape != [0]: + origin_dtype = inp.dtype + inp = paddle.cast(inp, dtype="float32") + inp_buf = paddle.scatter(paddle.zeros( + shape=[out_batch_size, inp.shape[-1]], dtype="float32"), + pos, + inp, + overwrite=True) + inp_buf = paddle.cast(inp_buf, dtype=origin_dtype) + else: + inp_buf = paddle.zeros([out_batch_size, inp.shape[-1]], dtype=inp.dtype) + return inp_buf + + +def _all_gather(tensor, group=None, use_calc_stream=True): + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = paddle.distributed.collective._get_default_group( + ) if group is None else group + tensor_shape = list(tensor.shape) + tensor_shape[0] *= group.nranks + out = paddle.empty(tensor_shape, tensor.dtype) + + task = group.process_group.all_gather(tensor, out) + task.wait() + return out + else: + ring_id = 0 if group is None else group.id + nranks = paddle.distributed.collective._get_global_group( + ).nranks if group is None else group.nranks + return paddle._legacy_C_ops.c_allgather(tensor, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id, 'nranks', nranks) + + +class MoEScatter(PyLayer): + r""" + Scatter input samples from [batch x sequences] to contiguous alone experts. + If `world_size` is greater than 1, the samples will first be locally + scattered, and then exchanged across workers. + """ + + @staticmethod + def forward(ctx, + inp, + pos, + local_expert_count, + global_expert_count, + fwd_batch_size, + world_size, + group=None): + local_input_buf = _local_scatter(inp, pos) + if world_size > 1: + global_input_buf = global_scatter(local_input_buf, + local_expert_count, + global_expert_count, + group=group) + else: + global_input_buf = local_input_buf + + ctx.moe_args = inp.shape[0], world_size, group + + variables = (pos, local_expert_count, global_expert_count) + ctx.save_for_backward(*variables) + return global_input_buf + + @staticmethod + def backward(ctx, grad): + (pos, local_expert_count, global_expert_count) = ctx.saved_tensor() + (inp_batch_size, world_size, group) = ctx.moe_args + + if world_size > 1: + local_grad_in = global_gather(grad, + local_expert_count, + global_expert_count, + group=group) + else: + local_grad_in = grad + grad_in = _local_gather(local_grad_in, pos, inp_batch_size) + return grad_in, None, None, None + + +class MoEGather(PyLayer): + r""" + Gather output samples from contiguous alone experts back to [batch x + sequences]. Works symmetrically with MoEScatter. + """ + + @staticmethod + def forward(ctx, + global_output_buf, + pos, + local_expert_count, + global_expert_count, + local_batch_size, + world_size, + group=None): + if world_size > 1: + local_output_buf = global_gather(global_output_buf, + local_expert_count, + global_expert_count, + group=group) + else: + local_output_buf = global_output_buf + output = _local_gather(local_output_buf, + pos, + local_batch_size, + maybe_overlap=False) + + ctx.moe_args = (global_output_buf.shape[0], world_size, group) + variables = (pos, local_expert_count, global_expert_count) + ctx.save_for_backward(*variables) + return output + + @staticmethod + def backward(ctx, grad_out): + pos, local_expert_count, global_expert_count = ctx.saved_tensor() + fwd_batch_size, world_size, group = ctx.moe_args + grad_out_buf = _local_scatter(grad_out, pos) + if world_size > 1: + global_grad_out_buf = global_scatter(grad_out_buf, + local_expert_count, + global_expert_count, + group=group) + else: + global_grad_out_buf = grad_out_buf + return global_grad_out_buf, None, None, None + + +class AllGather(PyLayer): + r""" + A wrapper for the All-Gather function to support auto-differentiation. + """ + + @staticmethod + def forward(ctx, inp, rank, world_size, group): + tensor_list = [] + paddle.distributed.all_gather(tensor_list, inp, group=group) + output = paddle.concat(tensor_list, axis=0) + ctx.args = rank, inp.shape[0] + return output + + @staticmethod + def backward(ctx, grad_out): + rank, dim0 = ctx.args + return paddle.slice(grad_out, + axes=[0], + starts=[rank * dim0], + ends=[(rank + 1) * dim0]) + + +class Slice(PyLayer): + r""" + A wrapper for the Slice function to support auto-differentiation. + """ + + @staticmethod + def forward(ctx, inp, rank, world_size, group): + B = inp.shape[0] + local_batch_size = B // world_size + batch_start = local_batch_size * rank + batch_end = min(batch_start + local_batch_size, B) + inp = paddle.slice(inp, + axes=[0], + starts=[batch_start], + ends=[batch_end]) + ctx.args = world_size, group + return inp + + @staticmethod + def backward(ctx, grad_out): + world_size, group = ctx.args + return _all_gather(grad_out, group=group) + + +def prepare_forward(gate, num_expert, world_size, moe_group): + pos, local_expert_count, global_expert_count = count_by_gate( + gate, num_expert, world_size, group=moe_group) + with paddle.no_grad(): + fwd_expert_count = global_expert_count.reshape_( + [world_size, num_expert]).sum(axis=0) + fwd_batch_size = int(fwd_expert_count.sum().item()) + return ( + pos, + local_expert_count, + global_expert_count, + fwd_expert_count, + fwd_batch_size, + ) + + +class MoELayer(nn.Layer): + """MoE Layer + Args: + d_model: (int) model dimention + experts: (nn.LayerList) expert networks list + gate: (dict|NaiveGate|SwitchGate|NaiveGate): + if gate is a dict: + gate is a gate network config, containing 2 keys: + `type`(str) value can be: "naive", "gshard", "switch" or None, default is "gshard" + `top_k`(int) default value is 2 + else gate is an instance of NaiveGate|SwitchGate|NaiveGate: + + moe_group: moe group for experts communication + mp_group: mp group for mp commutication + recompute_interval(int, optional): whether to use recompute, default 0, means to disable recompute. + recompute_ctx(dict, optional): the context for recompute, if recompute_interval > 1, recompute_ctx must be given. + Examples: + .. code-block:: python + from paddle.nn import layer, LayerList + from paddle.distributed.moe import MoElayer + from paddle.distributed.collective import Group + from paddle.distributed import fleet + + moe_group = Group(fleet.worker_index(), + 0, + list(range(fleet.worker_num()))) + mp_group = None + + num_experts=8 + dim_feedforward=512 + d_model=8 + top_k=2 + + class ExpertLayer(Layer): + def __init__(self, d_model, d_hidden, name=None,rank=0, windex = 0, num_expert=1): + super(ExpertLayer, self).__init__() + self.htoh4 = nn.Linear(d_model, d_hidden) + self.h4toh = nn.Linear(d_hidden, d_model) + + def forward(self, x): + x = self.htoh4(x) + x = self.h4toh(x) + return x + + gate_config = { + "type": "gshard", + "top_k": top_k, + } + + experts_list = LayerList() + for expi in range(num_experts): + exp_layer = ExpertLayer(d_model, dim_feedforward // top_k, windex=expi, num_expert=num_experts) + experts_list.append(exp_layer) + + moeLayer = MoELayer(d_model = d_model, + experts=experts_list, + gate=gate_config, + moe_group=moe_group, + mp_group=mp_group, + recompute_interval=0) + + """ + + def __init__(self, + d_model, + experts, + gate=None, + moe_group=None, + mp_group=None, + recompute_interval=0, + recompute_ctx=None): + super(MoELayer, self).__init__() + + self.recompute_ctx = recompute_ctx + + if gate is None: + gate = dict() + + assert isinstance(gate, (dict, BaseGate)), \ + "gate config' type must be dict or an instance of BaseGate" + # only support mp/dp + self.group = moe_group + + self.world_size = 1 + if self.group is not None: + self.world_size = self.group.nranks + self.num_expert = len(experts) + self.recompute_interval = recompute_interval + assert experts is not None + self.experts = experts + + self.mp_group = mp_group + self.d_model = d_model + if isinstance(gate, dict): + self.top_k = gate.get("top_k", 2) + gate = gate.get("type", "gshard") + if gate == "naive" or gate is None: + gate = NaiveGate(self.d_model, + num_expert=len(experts), + world_size=self.world_size, + topk=self.top_k) + elif gate == "gshard": + gate = GShardGate(self.d_model, + num_expert=len(experts), + world_size=self.world_size, + topk=self.top_k, + group=self.group) + elif gate == "switch": + gate = SwitchGate(self.d_model, + num_expert=len(experts), + world_size=self.world_size, + topk=self.top_k, + group=self.group) + else: + assert False, "We only support naive gate, \ + gshard gate and switch gate, \ + but you choose {} gate.".format(str(gate)) + elif isinstance(gate, NaiveGate): + self.top_k = gate.top_k + elif isinstance(gate, BaseGate): + raise TypeError("Unimplemented gate type: ", type(gate)) + else: + raise TypeError("gate's type must be either dict or moe.BaseGate") + self.gate = gate + + def forward(self, inp): + # inp shape: b * s * m + assert len(inp.shape) == 3 + origin_shape = inp.shape + inp = inp.reshape_([-1, origin_shape[2]]) + + mp_rank = 0 + mp_size = 1 + if self.mp_group is not None: + mp_rank = self.mp_group.rank + mp_size = self.mp_group.nranks + if mp_size > 1: + inp = Slice.apply(inp, mp_rank, mp_size, self.mp_group) + value, gate = self.gate(inp) + + ( + pos, + local_expert_count, + global_expert_count, + fwd_expert_count, + fwd_batch_size, + ) = prepare_forward(gate, self.num_expert, self.world_size, self.group) + + topk = 1 + if len(gate.shape) == 2: + topk = gate.shape[1] + + if pos.shape != [0]: + temp_pos = pos // topk + else: + temp_pos = pos + assert topk == self.top_k + + x = MoEScatter.apply(inp, temp_pos, local_expert_count, + global_expert_count, fwd_batch_size, + self.world_size, self.group) + + d_model = self.d_model + + def experts_fwd(x, fwd_expert_count, experts): + + if x.shape[0] == 0: + return x + y = [] + last_index = 0 + assert isinstance(fwd_expert_count, np.ndarray) + assert len(experts) == len(fwd_expert_count) + for idx, expert_count in enumerate(fwd_expert_count): + if expert_count <= 0: + continue + y.append(experts[idx](x[last_index:expert_count + last_index])) + last_index = expert_count + last_index + return paddle.concat(y, axis=0) + + if self.recompute_interval <= 0 or x.shape[0] == 0: + x = experts_fwd(x, fwd_expert_count.numpy(), self.experts) + else: + x = recompute_hybrid(self.recompute_ctx, experts_fwd, x, + fwd_expert_count.numpy(), self.experts) + + out_batch_size = inp.shape[0] + if len(gate.shape) == 2: + out_batch_size *= gate.shape[1] + + x = MoEGather.apply(x, pos, local_expert_count, global_expert_count, + out_batch_size, self.world_size, self.group) + + x = x.reshape([-1, self.top_k, d_model]) + value = value.reshape([x.shape[0], 1, self.top_k]) + x = paddle.bmm(value, x).reshape([-1, d_model]) + + if mp_size > 1: + x = AllGather.apply(x, mp_rank, mp_size, self.mp_group) + + x = paddle.reshape_(x, origin_shape) + + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..10203a0cd18aae913aab9363d4665d13c406dd8a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/distributed/models/moe/utils.py @@ -0,0 +1,81 @@ +# Copyright (c) 2022 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. +# +# The file has been adapted from the file: +# https://github.com/laekov/fastmoe/blob/master/fmoe/functions.py +# Git commit hash: 295a615aacce7e54a37e7935274ba15e901c78e4 +# We retain the following license from the original files: +# Copyright 2021, Jiaao He. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"). + +from paddle.distributed.models.moe.utils import _number_count, _limit_by_capacity, _prune_gate_by_capacity, _assign_pos +import paddle +from paddle.fluid.framework import in_dygraph_mode + + +def _alltoall(in_tensor_list, group=None, use_calc_stream=True): + if group is not None and not group.is_member(): + return + + if in_dygraph_mode(): + group = paddle.distributed.collective._get_default_group( + ) if group is None else group + out = paddle.empty(in_tensor_list.shape, in_tensor_list.dtype) + task = group.process_group.alltoall(in_tensor_list, out) + task.wait() + return out + else: + ring_id = 0 if group is None else group.id + return paddle._legacy_C_ops.alltoall(in_tensor_list, 'use_calc_stream', + use_calc_stream, 'ring_id', + ring_id) + + +def count_by_gate(gate, num_expert, world_size, require_pos=True, group=None): + total_expert_count = num_expert * world_size + with paddle.no_grad(): + local_expert_count = _number_count(gate, total_expert_count) + + if world_size > 1: + global_expert_count = _alltoall(local_expert_count, group=group) + else: + global_expert_count = local_expert_count + if not require_pos: + pos = None + else: + lec_cum = paddle.cumsum(local_expert_count, axis=0) + pos = _assign_pos(gate, lec_cum) + return pos, local_expert_count, global_expert_count + + +def limit_by_capacity(topk_idx, num_expert, world_size, capacity, group=None): + with paddle.no_grad(): + capacity = paddle.ones(shape=[num_expert], + dtype=paddle.int64) * capacity + pos, lec, gec = count_by_gate(topk_idx, + num_expert, + world_size, + require_pos=False, + group=group) + new_gec = _limit_by_capacity(gec, capacity, world_size) + if world_size > 1: + assert group.nranks == world_size + new_lec = _alltoall(new_gec, group=group) + else: + new_lec = new_gec + + topk_idx = _prune_gate_by_capacity(topk_idx, new_lec, num_expert, + world_size) + + return new_lec, new_gec, topk_idx diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df0f98f74d58bcc64adb396baf834466f4ac6876 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022 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. + +from .reductions import init_reductions +import multiprocessing + +__all__ = [] + +from multiprocessing import * # noqa: F403 + +# Only support linux for now +# Only support file_system sharing strategy. + +init_reductions() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/reductions.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..54d40312268aa1d0ca4019e8266a019e6e6a2833 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/multiprocessing/reductions.py @@ -0,0 +1,190 @@ +# Copyright (c) 2022 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. + +import paddle + +# TODO: check the hooks of tensor +# TODO: check serializing named tensor +# TODO: check influence on autograd +import os +import sys +import warnings +import math +import copy +import threading +import multiprocessing +from multiprocessing.util import register_after_fork +from multiprocessing.reduction import ForkingPickler + +from collections import OrderedDict + + +def _supported_check(): + if sys.platform != "linux": + # warnings.warn("`paddle.multiprocessing` only support linux for now, " + # " import this will not take any effect !") + + return False + + if not sys.version_info >= (3, 4): + warnings.warn("Use `paddle.multiprocessing` to share paddle tensor " + "requires python version greater than 3.4 ." + " `paddle.multiprocessing` will not take any effect !!!") + return False + + return True + + +class LRUSharedCache(OrderedDict): + + def __init__(self): + self.limit = 128 + self._after_fork() + register_after_fork(self, LRUSharedCache._after_fork) + + def _after_fork(self): + self.lock = threading.Lock() + + def get(self, key): + with self.lock: + try: + value = super().pop(key) + super().__setitem__(key, value) + return value + except KeyError: + return None + + def __setitem__(self, key, value): + with self.lock: + try: + super().__delitem__(key) + except KeyError: + if len(self) >= self.limit: + super().popitem(last=False) + super().__setitem__(key, value) + + +shared_cache = LRUSharedCache() + + +def cuda_from_cache(key): + lodtensor = shared_cache.get(key) + if lodtensor is None: + return None + return lodtensor + + +def rebuild_tensor(cls, lodtensor, metadata): + if cls == paddle.fluid.framework.ParamBase: + tensor = paddle.fluid.framework.ParamBase(lodtensor.shape(), + lodtensor._dtype(), + **metadata) + tensor.value().get_tensor()._share_data_with(lodtensor) + else: + size, stop_gradient = metadata + tensor = paddle.fluid.core.VarBase() + if lodtensor._is_initialized(): + tensor.value().get_tensor()._share_data_with(lodtensor) + else: + tensor = paddle.to_tensor([], dtype=lodtensor._dtype()) + tensor.stop_gradient = stop_gradient + return tensor + + +def reduce_tensor(tensor): + lodtensor = tensor.value().get_tensor() + + if not tensor.stop_gradient and not tensor.is_leaf: + raise RuntimeError( + "Refusing to serialize non-leaf tensor which not stop_gradient, you can detach it!" + ) + # TODO: add serializing name and hooks check + if tensor.place.is_cpu_place() or tensor.place.is_gpu_place( + ) or tensor.place.is_cuda_pinned_place(): + if type(tensor) == paddle.fluid.framework.ParamBase: + metadata = copy.deepcopy(tensor.__dict__) + else: + metadata = (tensor.size, tensor.stop_gradient) + + return (rebuild_tensor, (type(tensor), lodtensor, metadata)) + else: + raise ValueError( + "Only support tensors of CPU/CUDA/CUDAPinned Place, Not support %s for now!" + % tensor.place) + + +def rebuild_lodtensor_filename(cls, ipc_name, size, type_idx, dims, lod): + lodtensor = cls._new_shared_filename((ipc_name, size, type_idx, dims, lod)) + lodtensor._shared_decref() + return lodtensor + + +def rebuild_cuda_tensor(cls, handle, offset_bytes, size, type_idx, dims, lod, + device_idx): + cache_tensor = cuda_from_cache((handle, offset_bytes)) + if cache_tensor is None: + lodtensor = cls._new_shared_cuda( + (handle, offset_bytes, size, type_idx, dims, lod, device_idx)) + # We only cache cuda shared tensor here. + # The opening cost of cudaIpcMemoryHandle is very high. + # Since we cache the recived tensor directly, + # The sender may reallocate the tensor space, + # you should manualy maintian the lifecycle of ipc tensor + shared_cache[(handle, offset_bytes)] = lodtensor + else: + lodtensor = paddle.fluid.core.LoDTensor() + lodtensor._share_buffer_with(cache_tensor, + (size, type_idx, dims, lod, device_idx)) + + return lodtensor + + +def rebuild_lodtensor_empty(cls): + #TODO: check if tensor initialized + #TODO: handle the dtype of empty tensor + return cls() + + +def reduce_lodtensor(lodtensor): + if lodtensor._place().is_cpu_place() or lodtensor._place( + ).is_cuda_pinned_place(): + for dim in lodtensor.shape(): + if dim == 0: + # Empty tensors have nothing be mmapped. + return (rebuild_lodtensor_empty, (type(lodtensor), )) + + # Default use share filename stratege + metadata = lodtensor._share_filename( + ) # ipc_name, size, type_idx, dims, lod + rebuild = rebuild_lodtensor_filename + lodtensor._shared_incref() + # TODO, maintain reference for lodtensor + # TODO: support file_discriptor stratege + elif lodtensor._place().is_gpu_place(): + metadata = lodtensor._share_cuda() + rebuild = rebuild_cuda_tensor + else: + raise RuntimeError("We only support pass cpu/gpu lodtensor for now!") + + return (rebuild, (type(lodtensor), ) + metadata) + + +def init_reductions(): + if not _supported_check(): + return + + ForkingPickler.register(paddle.Tensor, reduce_tensor) + ForkingPickler.register(paddle.fluid.core.VarBase, reduce_tensor) + ForkingPickler.register(paddle.fluid.framework.ParamBase, reduce_tensor) + ForkingPickler.register(paddle.fluid.core.LoDTensor, reduce_lodtensor) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf15ee7d8ffaa321b2700c38b2dbea8682ad0a3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/__init__.py @@ -0,0 +1,29 @@ +# Copyright (c) 2021 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. + +from .layer.fused_transformer import FusedMultiHeadAttention # noqa: F401 +from .layer.fused_transformer import FusedFeedForward # noqa: F401 +from .layer.fused_transformer import FusedTransformerEncoderLayer # noqa: F401 +from .layer.fused_transformer import FusedMultiTransformer # noqa: F401 +from .layer.fused_linear import FusedLinear # noqa: F401 +from .layer.fused_transformer import FusedBiasDropoutResidualLayerNorm # noqa: F401 + +__all__ = [ #noqa + 'FusedMultiHeadAttention', + 'FusedFeedForward', + 'FusedTransformerEncoderLayer', + 'FusedMultiTransformer', + 'FusedLinear', + 'FusedBiasDropoutResidualLayerNorm', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9894990455abf65972457ce67cdfeb164711b2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/__init__.py @@ -0,0 +1,28 @@ +# Copyright (c) 2021 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. + +from .fused_transformer import fused_multi_head_attention +from .fused_transformer import fused_feedforward +from .fused_transformer import fused_multi_transformer +from .fused_matmul_bias import fused_matmul_bias, fused_linear +from .fused_transformer import fused_bias_dropout_residual_layer_norm + +__all__ = [ + 'fused_multi_head_attention', + 'fused_feedforward', + 'fused_multi_transformer', + 'fused_matmul_bias', + 'fused_linear', + 'fused_bias_dropout_residual_layer_norm', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_matmul_bias.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_matmul_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..58e51c5fa5e9a7f1e8ed995319137cc9c2936d60 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_matmul_bias.py @@ -0,0 +1,109 @@ +# Copyright (c) 2022 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. + +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.tensor.linalg import matmul +from paddle import _C_ops, _legacy_C_ops + + +def fused_matmul_bias(x, + y, + bias=None, + transpose_x=False, + transpose_y=False, + name=None): + """ + Applies matrix multiplication of two tensors and then bias addition if provided. + This method requires CUDA version >= 11.6. + + Args: + x (Tensor): the first input Tensor to be multiplied. + y (Tensor): the second input Tensor to be multiplied. Its rank must be 2. + bias (Tensor|None): the input bias Tensor. If it is None, no bias addition would + be performed. Otherwise, the bias is added to the matrix multiplication result. + transpose_x (bool): Whether to transpose :math:`x` before multiplication. + transpose_y (bool): Whether to transpose :math:`y` before multiplication. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Tensor: the output Tensor. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn.functional import fused_matmul_bias + + x = paddle.randn([3, 4]) + y = paddle.randn([4, 5]) + bias = paddle.randn([5]) + out = fused_matmul_bias(x, y, bias) + print(out.shape) # [3, 5] + """ + if bias is None: + return matmul(x, y, transpose_x, transpose_y, name) + if _non_static_mode(): + return _legacy_C_ops.fused_gemm_epilogue(x, y, bias, 'trans_x', + transpose_x, 'trans_y', + transpose_y) + + helper = LayerHelper('fused_matmul_bias', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='fused_gemm_epilogue', + inputs={ + 'X': x, + 'Y': y, + 'Bias': bias + }, + outputs={'Out': out}, + attrs={ + 'trans_x': transpose_x, + 'trans_y': transpose_y + }) + return out + + +def fused_linear(x, weight, bias=None, transpose_weight=False, name=None): + """ + Fully-connected linear transformation operator. This method requires CUDA version >= 11.6. + + Args: + x (Tensor): the input Tensor to be multiplied. + weight (Tensor): the weight Tensor to be multiplied. Its rank must be 2. + bias (Tensor|None): the input bias Tensor. If it is None, no bias addition would + be performed. Otherwise, the bias is added to the matrix multiplication result. + transpose_weight (bool): Whether to transpose :math:`weight` before multiplication. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Tensor: the output Tensor. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn.functional import fused_linear + + x = paddle.randn([3, 4]) + weight = paddle.randn([4, 5]) + bias = paddle.randn([5]) + out = fused_linear(x, weight, bias) + print(out.shape) # [3, 5] + """ + return fused_matmul_bias(x, weight, bias, False, transpose_weight, name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..02b844751a8898ee3a6908c0b8c84c3f0b9a89eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/functional/fused_transformer.py @@ -0,0 +1,1101 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode, default_main_program +from paddle.fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle.fluid import core, dygraph_utils +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def _verify_dropout_rate(dropout_rate): + if not isinstance(dropout_rate, (float, int)): + raise TypeError("dropout_rate argument should be a number") + if dropout_rate < 0 or dropout_rate > 1: + raise ValueError("dropout_rate argument should between 0 and 1") + + +def fused_feedforward( + x, + linear1_weight, + linear2_weight, + linear1_bias=None, + linear2_bias=None, + ln1_scale=None, + ln1_bias=None, + ln2_scale=None, + ln2_bias=None, + dropout1_rate=0.5, + dropout2_rate=0.5, + activation="relu", + ln1_epsilon=1e-5, + ln2_epsilon=1e-5, + pre_layer_norm=False, + training=True, + mode='upscale_in_train', + ring_id=-1, + add_residual=True, + name=None, +): + r""" + This is a fusion operator to compute feed forward layer in transformer model architecture. + This operator only supports running on GPU. The function of the operator is consistent with + the following pseudo code: + + .. code-block:: python + + residual = x + if pre_layer_norm: + out = layer_norm1(x) + else: + out = x + out = linear2(dropout1(activation(linear1(src)))) + if add_residual: + out = residual + dropout2(out) + else: + out = dropout2(out) + if not pre_layer_norm: + out = layer_norm2(out) + + + Args: + x (Tensor): the input tensor could be 3-D tensor, the input data type could be float16, float32 or float64, the shape is`[batch\_size, sequence\_length, d_model]`. + linear1_weight (Tensor): The weight of first linear, the data type is same as `x`, the shape is `[d\_model, dim\_feedforward]`. + linear2_weight (Tensor): The weight of second linear, the data type is same as `x`, the shape is `[dim\_feedforward, d\_model]`. + linear1_bias (Tensor, optional): The bias of first linear, the data type is same as `x`, the shape is `[dim_feedforward]`. Default None. + linear2_bias (Tensor, optional): The bias of second linear, the data type is same as `x`, the shape is `[d_model]`. Default None. + ln1_scale (Tensor, optional): the weight of first layer_norm, the data type is float32 or float64, the shape is same as `x`. Default None. + ln1_bias (Tensor, optional): The bias of first layer_norm, the data type is float32 or float64, the shape is `[d\_model]`. Default None. + ln2_scale (Tensor, optional): The weight of second layer_norm, the data type is float32 or float64, the shape is same as `x`. Default None. + ln2_bias (Tensor, optional): The bias of second layer_norm, the data type is float32 or float64, the shape is `[d\_model]`. Default None. + dropout1_rate (float, optional): The first dropout probability of setting units to zero. Default 0.5. + dropout2_rate (float, optional): The second dropout probability of setting units to zero. Default 0.5. + activation (str, optional): The activation. Default "relu". + ln1_epsilon (float, optional): Small float of first layer_norm added to denominator to avoid dividing by zero. Default is 1e-5. + ln2_epsilon (float, optional): Small float of second layer_norm added to denominator to avoid dividing by zero. Default is 1e-5. + pre_layer_norm (bool, optional): add layer_norm in the pre-processing stage or post-processing state. + training (bool, optional): A flag indicating whether it is in train phrase or not. Default True. + mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'] + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + ring_id (int, optional): For distributed forward in tensor model parallel, only support NCCL. Default is -1, means not using tensor parallel. + add_residual (bool, optional): Whether add residual at the end. Default is True. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output Tensor, the data type and shape is same as `x`. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate.nn.functional as F + + x = paddle.randn(shape=(1, 8, 8), dtype="float32") + linear1_weight = paddle.randn(shape=(8, 8), dtype="float32") + linear2_weight = paddle.randn(shape=(8, 8), dtype="float32") + out = F.fused_feedforward(x, linear1_weight, linear2_weight) + print(out.shape) + # (1, 8, 8) + """ + _verify_dropout_rate(dropout1_rate) + _verify_dropout_rate(dropout2_rate) + + seed = None + if mode not in ('downscale_in_infer', 'upscale_in_train'): + raise ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'" + ) + mode = ( + 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode + ) # semantic transfer + + if _non_static_mode(): + if default_main_program().random_seed != 0: + seed = default_main_program().random_seed + out, _, _, _, _, _, _, _, _, _, _ = _legacy_C_ops.fused_feedforward( + x, + None, + None, + linear1_weight, + linear1_bias, + linear2_weight, + linear2_bias, + ln1_scale, + ln1_bias, + ln2_scale, + ln2_bias, + 'pre_layer_norm', + pre_layer_norm, + 'ln1_epsilon', + ln1_epsilon, + 'ln2_epsilon', + ln2_epsilon, + 'act_method', + activation, + 'dropout1_rate', + dropout1_rate, + 'dropout2_rate', + dropout2_rate, + "is_test", + not training, + "dropout1_fix_seed", + seed is not None, + "dropout2_fix_seed", + seed is not None, + "dropout1_seed", + seed if seed is not None else 0, + "dropout2_seed", + seed if seed is not None else 0, + 'dropout1_implementation', + mode, + 'dropout2_implementation', + mode, + 'add_residual', + add_residual, + 'ring_id', + ring_id, + ) + return out + + helper = LayerHelper("fused_feedforward") + dtype = x.dtype + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'fused_feedforward' + ) + check_dtype( + dtype, 'dtype', ['float16', 'float32', 'float64'], 'fused_feedforward' + ) + + out = helper.create_variable_for_type_inference(x.dtype) + dropout1_mask = helper.create_variable_for_type_inference( + 'uint8', stop_gradient=True + ) + dropout2_mask = helper.create_variable_for_type_inference( + 'uint8', stop_gradient=True + ) + ln1_mean = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + ln1_variance = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + ln2_mean = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + ln2_variance = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + linear1_out = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + ln1_out = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + dropout1_out = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + dropout2_out = helper.create_variable_for_type_inference( + x.dtype, stop_gradient=True + ) + + if (seed is None or seed == 0) and helper.main_program.random_seed != 0: + seed = helper.main_program.random_seed + + helper.append_op( + type='fused_feedforward', + inputs={ + 'X': x, + 'Linear1Weight': linear1_weight, + 'Linear1Bias': linear1_bias, + 'Linear2Weight': linear2_weight, + 'Linear2Bias': linear2_bias, + 'Ln1Scale': ln1_scale, + 'Ln1Bias': ln1_bias, + 'Ln2Scale': ln2_scale, + 'Ln2Bias': ln2_bias, + }, + outputs={ + 'Out': out, + 'Dropout1Mask': dropout1_mask, + 'Dropout2Mask': dropout2_mask, + 'Ln1Mean': ln1_mean, + 'Ln1Variance': ln1_variance, + 'Ln2Mean': ln2_mean, + 'Ln2Variance': ln2_variance, + 'Linear1Out': linear1_out, + 'Ln1Out': ln1_out, + 'Dropout1Out': dropout1_out, + 'Dropout2Out': dropout2_out, + }, + attrs={ + 'dropout1_rate': dropout1_rate, + 'dropout2_rate': dropout2_rate, + 'act_method': activation, + 'pre_layer_norm': pre_layer_norm, + 'ln1_epsilon': ln1_epsilon, + 'ln2_epsilon': ln2_epsilon, + 'is_test': not training, + 'dropout1_fix_seed': seed is not None, + 'dropout2_fix_seed': seed is not None, + 'dropout1_seed': seed if seed is not None else 0, + 'dropout2_seed': seed if seed is not None else 0, + 'dropout1_implementation': mode, + 'dropout2_implementation': mode, + 'add_residual': add_residual, + 'ring_id': ring_id, + }, + ) + return out + + +def fused_bias_dropout_residual_layer_norm( + x, + residual, + bias=None, + ln_scale=None, + ln_bias=None, + dropout_rate=0.5, + ln_epsilon=1e-5, + training=True, + mode='upscale_in_train', + name=None, +): + r""" + + The fused_bias_dropout_residual_layer_norm operator. The pseudo code is as follows: + + .. code-block:: python + + y = layer_norm(residual + dropout(bias + x)) + + Parameters: + x (Tensor): The input tensor. The shape is `[*, embed\_dim]`. + residual (Tensor): The residual tensor. The shape is same as x. + bias (Tensor, optional): The bias of linear. The shape is `[embed_dim]`. Default None. + ln_scale (Tensor, optional): The weight tensor of layernorm. The shape is `[embed_dim]`. Default None. + ln_bias (Tensor, optional): The bias tensor of layernorm. The shape is `[embed_dim]`. Default None. + dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout after attention. + 0 for no dropout. Default 0.5. + ln_epsilon (float, optional): Small float value added to denominator of layer_norm + to avoid dividing by zero. Default is 1e-5. + training (bool, optional): A flag indicating whether it is in train phrase or not. Default True. + mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'] + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, The output Tensor, the data type and shape is same as `x`. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate.nn.functional as F + + # input: [batch_size, seq_len, embed_dim] + x = paddle.rand(shape=(2, 4, 128), dtype="float32") + # residual: [batch_size, seq_len, embed_dim] + residual = paddle.rand(shape=(2, 4, 128), dtype="float32") + # linear bias: [embed_dim] + bias = paddle.rand(shape=[128], dtype="float32") + # output: [batch_size, seq_len, embed_dim] + output = F.fused_bias_dropout_residual_layer_norm( + x, residual, bias) + # [2, 4, 128] + print(output.shape) + + """ + seed = None + if mode not in ('downscale_in_infer', 'upscale_in_train'): + raise ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'" + ) + mode = ( + 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode + ) # semantic transfer + + if ln_scale is not None: + assert ( + len(ln_scale.shape) == 1 + ), "The dims of the shape of ln_scale should be 1." + assert ( + x.shape[len(x.shape) - 1] == ln_scale.shape[0] + ), "The dim of ln_scale must equal to the last dim of x." + if ln_bias is not None: + assert ( + len(ln_bias.shape) == 1 + ), "The dims of the shape of ln_bias should be 1." + assert ( + x.shape[len(x.shape) - 1] == ln_bias.shape[0] + ), "The dim of ln_bias must equal to the last dim of x." + + if _non_static_mode(): + if default_main_program().random_seed != 0: + seed = default_main_program().random_seed + ( + _, + _, + _, + _, + final_out, + ) = _legacy_C_ops.fused_bias_dropout_residual_layer_norm( + x, + residual, + bias, + ln_scale, + ln_bias, + 'dropout_rate', + dropout_rate, + 'ln_epsilon', + ln_epsilon, + 'is_test', + not training, + 'dropout_fix_seed', + seed is not None, + 'dropout_seed', + seed if seed is not None else 0, + 'dropout_implementation', + mode, + ) + return final_out + else: + helper = LayerHelper( + 'fused_bias_dropout_residual_layer_norm', **locals() + ) + dtype = x.dtype + # check dtypes + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64'], + 'fused_bias_dropout_residual_layer_norm', + ) + check_dtype( + dtype, + 'dtype', + ['float16', 'float32', 'float64'], + 'fused_bias_dropout_residual_layer_norm', + ) + # set inputs + inputs = dict() + inputs['X'] = [x] + inputs['Residual'] = [residual] + if bias is not None: + inputs['Bias'] = [bias] + if ln_scale: + inputs['LnScale'] = [ln_scale] + if ln_bias: + inputs['LnBias'] = [ln_bias] + if (seed is None or seed == 0) and helper.main_program.random_seed != 0: + seed = helper.main_program.random_seed + # set attrs + attrs = { + 'ln_epsilon': ln_epsilon, + 'dropout_rate': dropout_rate, + 'is_test': not training, + 'dropout_fix_seed': seed is not None, + 'dropout_seed': seed if seed is not None else 0, + 'dropout_implementation': mode, + } + # set outputs + dropout_mask_out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True + ) + ln_mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + ln_variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + bias_dropout_residual_out = helper.create_variable_for_type_inference( + dtype=dtype + ) + final_out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='fused_bias_dropout_residual_layer_norm', + inputs=inputs, + outputs={ + "BiasDropoutResidualOut": bias_dropout_residual_out, + "DropoutMaskOut": dropout_mask_out, + "LnMean": ln_mean_out, + "LnVariance": ln_variance_out, + 'Y': final_out, + }, + attrs=attrs, + ) + return final_out + + +def fused_multi_head_attention( + x, + qkv_weight, + linear_weight, + pre_layer_norm=False, + pre_ln_scale=None, + pre_ln_bias=None, + ln_scale=None, + ln_bias=None, + pre_ln_epsilon=1e-05, + qkv_bias=None, + linear_bias=None, + cache_kv=None, + attn_mask=None, + dropout_rate=0.5, + attn_dropout_rate=0.5, + ln_epsilon=1e-05, + training=True, + mode='upscale_in_train', + ring_id=-1, + add_residual=True, + name=None, +): + r""" + Attention mapps queries and a set of key-value pairs to outputs, and + Multi-Head Attention performs multiple parallel attention to jointly attending + to information from different representation subspaces. This API only + support self_attention. The pseudo code is as follows: + + .. code-block:: python + + residual = x + if pre_layer_norm: + out = layer_norm(x) + else: + out = x + # compute q, k, v + out = matmul(out, qkv_weight) + qkv_bias + out = transpose(out, perm=[2, 0, 3, 1, 4]) + # extract q, k and v from out + q = out[0:1,::] * (head_dim ** -0.5) + k = out[1:2,::] + v = out[2:3,::] + out = matmul(q, k, transpose_y=True) + out = out + attn_mask + out = softmax(out) + out = dropout(out) + out = matmul(out, v) + # combine heads + out = transpose(out, perm=[0, 2, 1, 3]) + # project to output + out = linear(out) + if add_residual: + out = residual + dropout(out) + else: + out = dropout(out) + if not pre_layer_norm: + out = layer_norm(out) + + + Parameters: + x (Tensor): The input tensor of fused_multi_head_attention. The shape is + `[batch\_size, sequence\_len, embed\_dim]`. + qkv_weight (Tensor): The qkv weight tensor. The shape is `[3, num_head, dim_head, dim_embed]`. + linear_weight (Tensor): The linear weight tensor. The shape is `[embed_dim, embed_dim]`. + pre_layer_norm (bool, optional): whether it is pre_layer_norm (True) or post_layer_norm architecture + (False). Default False. + pre_ln_scale (Tensor, optional): The weight tensor of pre layernorm. Default None. + pre_ln_bias (Tensor, optional): The bias tensor of pre layernorm. Default None. + ln_scale (Tensor, optional): The weight tensor of layernorm. Default None. + ln_bias (Tensor, optional): The bias tensor of layernorm. Default None. + pre_ln_epsilon (float, optional): Small float value added to denominator of the pre layer_norm + to avoid dividing by zero. Default is 1e-5. + qkv_bias (Tensor, optional): The bias of qkv computation. The shape is `[3, num_head, dim_head]`. + Default None. + linear_bias (Tensor, optional): The bias of linear. The shape is `[embed_dim]`. Default None. + cache_kv (Tensor, optional): For generation model, cache structure. The shape is `[2, bsz, num_head, seq_len, head_dim]`. Default None. + attn_mask (Tensor, optional): A tensor used in multi-head attention to prevents attention to + some unwanted positions, usually the paddings or the subsequent positions. It is a tensor + with shape broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. When the + data type is bool, the unwanted positions have `False` values and the others have `True` values. + When the data type is int, the unwanted positions have 0 values and the others have 1 values. + When the data type is float, the unwanted positions have `-INF` values and the others have 0 values. + It can be None when nothing wanted or needed to be prevented attention to. Default None. + dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout after attention. + 0 for no dropout. Default 0.5. + attn_dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout in attention. + 0 for no dropout. Default 0.5. + ln_epsilon (float, optional): Small float value added to denominator of layer_norm + to avoid dividing by zero. Default is 1e-5. + training (bool, optional): A flag indicating whether it is in train phrase or not. Default True. + mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'] + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + ring_id (int, optional): For distributed forward in mp, only support NCCL and forward. Default is -1, means not using mp + add_residual (bool, optional): Whether add residual at the end. Default is True. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output Tensor, the data type and shape is same as `x`. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate.nn.functional as F + + # input: [batch_size, seq_len, embed_dim] + x = paddle.rand(shape=(2, 4, 128), dtype="float32") + # qkv_weight: [3, num_head, head_dim, embed_dim] + qkv_weight = paddle.rand(shape=(3, 4, 32, 128), dtype="float32") + # qkv_bias: [3, num_head, head_dim] + qkv_bias = paddle.rand(shape=(3, 4, 32), dtype="float32") + # linear_weight: [embed_dim, embed_dim] + linear_weight = paddle.rand(shape=(128, 128), dtype="float32") + # linear_bias: [embed_dim] + linear_bias = paddle.rand(shape=[128], dtype="float32") + # self attention mask: [batch_size, num_heads, seq_len, seq_len] + attn_mask = paddle.rand(shape=(2, 4, 4, 4), dtype="float32") + + # output: [batch_size, seq_len, embed_dim] + output = F.fused_multi_head_attention( + x, qkv_weight, linear_weight, False, + None, None, None, None, 1e-5, qkv_bias, + linear_bias, None, attn_mask) + # [2, 4, 128] + print(output.shape) + """ + + seed = None + if mode not in ('downscale_in_infer', 'upscale_in_train'): + raise ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'" + ) + mode = ( + 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode + ) # semantic transfer + + if _non_static_mode(): + if default_main_program().random_seed != 0: + seed = default_main_program().random_seed + # pre_ln_mean, pre_ln_variance, pre_ln_out, qkv_out, qkv_bias_out, transpose_out, qk_out, + # qktv_out, softmax_out, attn_dropout_mask_out, attn_dropout_out, attn_mask_out, fmha_out, + # linear_out, dropout_mask_out, ln_mean_out, ln_var_out, bias_dropout_residual_out, final_out + assert ( + len(qkv_weight.shape) == 4 + ), "The dims of the shape of qkv_weight should be 4." + assert ( + qkv_weight.shape[0] == 3 + ), "The shape of qkv_weight should be [3, num_head, head_dim, embed_dim]." + assert ( + qkv_weight.shape[3] == x.shape[2] + ), "The 3rd dim of qkv_weight and 2nd dim of x should be the same, i.e., embed_dim." + if ring_id == -1: + # under mp, the num head will be split, this equation will not hold + assert ( + qkv_weight.shape[1] * qkv_weight.shape[2] == qkv_weight.shape[3] + ), "embed_dim must be divisible by num_heads." + + ( + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + cache_kv_out, + final_out, + ) = _legacy_C_ops.fused_attention( + x, + pre_ln_scale, + pre_ln_bias, + qkv_weight, + qkv_bias, + cache_kv, + attn_mask, + linear_weight, + linear_bias, + ln_scale, + ln_bias, + 'pre_layer_norm', + pre_layer_norm, + 'epsilon', + pre_ln_epsilon, + 'dropout_rate', + dropout_rate, + 'attn_dropout_rate', + attn_dropout_rate, + 'ln_epsilon', + ln_epsilon, + 'is_test', + not training, + 'attn_dropout_fix_seed', + seed is not None, + 'dropout_fix_seed', + seed is not None, + 'attn_dropout_seed', + seed if seed is not None else 0, + 'dropout_seed', + seed if seed is not None else 0, + 'attn_dropout_implementation', + mode, + 'dropout_implementation', + mode, + 'add_residual', + add_residual, + 'ring_id', + ring_id, + ) + if cache_kv is not None: + return final_out, cache_kv_out + return final_out + else: + helper = LayerHelper('fused_multi_head_attention', **locals()) + dtype = x.dtype + # check dtypes + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64'], + 'fused_multihead_attention', + ) + check_dtype( + dtype, + 'dtype', + ['float16', 'float32', 'float64'], + 'fused_multi_head_attention', + ) + + # set inputs + inputs = dict() + inputs['X'] = [x] + if pre_ln_scale: + inputs['LnScale'] = [pre_ln_scale] + if pre_ln_bias: + inputs['LnBias'] = [pre_ln_bias] + inputs['QKVW'] = [qkv_weight] + if qkv_bias is not None: + inputs['QKVBias'] = [qkv_bias] + inputs['SrcMask'] = attn_mask + inputs['OutLinearW'] = [linear_weight] + if linear_bias is not None: + inputs['OutLinearBias'] = [linear_bias] + if ln_scale: + inputs['Ln2Scale'] = [ln_scale] + if ln_bias: + inputs['Ln2Bias'] = [ln_bias] + if cache_kv: + inputs['CacheKV'] = [cache_kv] + + if (seed is None or seed == 0) and helper.main_program.random_seed != 0: + seed = helper.main_program.random_seed + + # set attrs + attrs = { + 'pre_layer_norm': pre_layer_norm, + 'epsilon': pre_ln_epsilon, + 'ln_epsilon': ln_epsilon, + 'dropout_rate': dropout_rate, + 'attn_dropout_rate': attn_dropout_rate, + 'is_test': not training, + 'attn_dropout_fix_seed': seed is not None, + 'dropout_fix_seed': seed is not None, + 'attn_dropout_seed': seed if seed is not None else 0, + 'dropout_seed': seed if seed is not None else 0, + 'attn_dropout_implementation': mode, + 'dropout_implementation': mode, + 'add_residual': add_residual, + 'ring_id': ring_id, + } + + # set outputs + pre_ln_mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + pre_ln_variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + pre_ln_out = helper.create_variable_for_type_inference(dtype=dtype) + + qkv_out = helper.create_variable_for_type_inference(dtype=dtype) + qkv_bias_out = helper.create_variable_for_type_inference(dtype=dtype) + + transpose_out = helper.create_variable_for_type_inference(dtype=dtype) + qk_out = helper.create_variable_for_type_inference(dtype=dtype) + qktv_out = helper.create_variable_for_type_inference(dtype=dtype) + softmax_out = helper.create_variable_for_type_inference(dtype=dtype) + attn_dropout_mask_out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True + ) + attn_dropout_out = helper.create_variable_for_type_inference( + dtype=dtype + ) + attn_mask_out = helper.create_variable_for_type_inference(dtype=dtype) + fmha_out = helper.create_variable_for_type_inference(dtype=dtype) + out_linear_out = helper.create_variable_for_type_inference(dtype=dtype) + dropout_mask_out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True + ) + ln_mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + ln_variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + bias_dropout_residual_out = helper.create_variable_for_type_inference( + dtype=dtype + ) + final_out = helper.create_variable_for_type_inference(dtype=dtype) + cache_kv_out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='fused_attention', + inputs=inputs, + outputs={ + "LnMean": pre_ln_mean_out, + "LnVariance": pre_ln_variance_out, + "LnOut": pre_ln_out, + "QKVOut": qkv_out, + "QKVBiasOut": qkv_bias_out, + "TransposeOut2": transpose_out, + "QKOut": qk_out, + "QKTVOut": qktv_out, + "SoftmaxOut": softmax_out, + "AttnDropoutMaskOut": attn_dropout_mask_out, + "AttnDropoutOut": attn_dropout_out, + "SrcMaskOut": attn_mask_out, + "FMHAOut": fmha_out, + "OutLinearOut": out_linear_out, + "DropoutMaskOut": dropout_mask_out, + "Ln2Mean": ln_mean_out, + "Ln2Variance": ln_variance_out, + "BiasDropoutResidualOut": bias_dropout_residual_out, + 'Y': final_out, + 'CacheKVOut': cache_kv_out, + }, + attrs=attrs, + ) + + return (final_out, cache_kv_out) if cache_kv else final_out + + +def fused_multi_transformer( + x, + ln_scales, + ln_biases, + qkv_weights, + qkv_biases, + linear_weights, + linear_biases, + ffn_ln_scales, + ffn_ln_biases, + ffn1_weights, + ffn1_biases, + ffn2_weights, + ffn2_biases, + pre_layer_norm=True, + epsilon=1e-05, + cache_kvs=None, + time_step=None, + attn_mask=None, + dropout_rate=0.0, + activation="gelu", + training=False, + mode='upscale_in_train', + trans_qkvw=True, + ring_id=-1, + name=None, +): + r""" + This is a fusion operator to compute multi transformer layers in transformer model architecture. + This operator only supports running on GPU. The function of the transformer layer is consistent + with the following pseudo code: + + .. code-block:: python + + if pre_layer_norm: + out = layer_norm(x) + out = qkv_linear(out) + qkv_bias + else: + out = qkv_linear(x) + qkv_bias + out = transpose(out, perm=[2, 0, 3, 1, 4]) + # extract q, k and v from out. + q = out[0:1, ::] + k = out[1:2, ::] + v = out[2:3, ::] + out = q * k^t + out = attn_mask + out + out = softmax(out) + out = dropout(out) + out = out * v + out = transpose(out, perm=[0, 2, 1, 3]) + out = linear(out) + if pre_layer_norm: + out = x + dropout(out + bias) + else: + out = layer_norm(x + dropout(out + bias)) + + residual = out; + if pre_layer_norm: + out = ffn_layer_norm(out) + out = ffn1_linear(out) + out = dropout(activation(out + ffn1_bias)) + out = ffn2_linear(out) + out = residual + dropout(out + ffn2_bias) + if not pre_layer_norm: + out = ffn_layer_norm(out) + + Args: + x (Tensor): the input tensor could be 3-D tensor, the input data type could be float16 or float32, the shape is `[batch\_size, sequence\_length, d\_model]`. + ln_scales (list(Tensor)|tuple(Tensor)): The weight tensors of attention layer_norm, the shape is `[d\_model]`. + ln_biases (list(Tensor)|tuple(Tensor)): The bias tensors of attention layer_norm. the shape is `[d\_model]`. + qkv_weights (list(Tensor)|tuple(Tensor)): The weight tensors of attention qkv computation. The shape is `[3, num\_head, dim\_head, d\_model]`. + qkv_biases (list(Tensor)|tuple(Tensor)|None): The bias tensors of attention qkv computation. The shape is `[3, num\_head, dim\_head]`. + linear_weights (list(Tensor)|tuple(Tensor)): The weight tensors of attention linear. The shape is `[num\_head * dim\_head, d\_model]`. + linear_biases (list(Tensor)|tuple(Tensor)|None): The bias tensors of attention linear. The shape is `[d\_model]`. + ffn_ln_scales (list(Tensor)|tuple(Tensor)): The weight tensors of feedforward layer_norm, the shape is `[d\_model]` + ffn_ln_biases (list(Tensor)|tuple(Tensor)): The bias tensors of feedforward layer_norm, the shape is `[d\_model]` + ffn1_weights (list(Tensor)|tuple(Tensor)): The weight tensors of feedforward first linear, the shape is `[d\_model, dim\_feedforward]`. + ffn1_biases (list(Tensor)|tuple(Tensor)|None): The bias tensors of feedforward first linear, the shape is `[dim\_feedforward]`. + ffn2_weights (list(Tensor)|tuple(Tensor)): The weight tensors of feedforward second linear, the shape is `[dim\_feedforward, d\_model]`. + ffn2_biases (list(Tensor)|tuple(Tensor)|None): The bias tensors of feedforward second linear, the shape is `[d_model]`. + pre_layer_norm (bool, optional): whether it is pre_layer_norm(True) or post_layer_norm(False). Default True. + epsilon (float, optional): Small float value added to denominator of the layer_norm to avoid dividing by zero. Default is 1e-5. + cache_kvs (list(Tensor)|tuple(Tensor), optional): The cache structure tensors for the generation model. The shape is `[2, bsz, num\_head, max\_seq\_len, head\_dim]`. Default None. + time_step (Tensor, optional): The time step tensor for the generation model. Which used in decode stage, to represent the time step, that is, the real seq_len of CacheKV. The shape is `[1]`, must be in CPUPlace. Default None. + attn_mask (Tensor, optional): A tensor used in multi-head attention to prevents attention to + some unwanted positions, usually the paddings or the subsequent positions. It is a tensor + with shape `[batch_size, 1, sequence_length, sequence_length]`. Default None. + dropout_rate (float, optional): The dropout probability of setting units to zero. Default 0.0. + activation (str, optional): The activation. Default "gelu". + training (bool, optional): A flag indicating whether it is in train phrase or not. Default False. + mode (str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'] + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + trans_qkvw (bool, optional): Whether to transpose for weights of qkv. + If true, the shape eights of qkv should be [3, num_head, dim_head, dim_embed]. + Otherwise the shape of weights of qkv should be [dim_embed, 3, num_head, dim_head]. Default True. + ring_id (int, optional): For distributed forward in tensor model parallel, only support NCCL. Default is -1, means not using mp. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor|tuple: If `cache_kvs` is None, return a tensor that has + the same shape and data type with `x`, representing the output + of Transformer layers. If `cache_kvs` is not None, return the + tuple (output, cache_kvs), which output is the output of + Transformer layers, cache_kvs is inplace with input `cache_kvs`. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate.nn.functional as F + + # input: [batch_size, seq_len, embed_dim] + x = paddle.rand(shape=(2, 4, 128), dtype="float32") + + # ln_scale: [embed_dim], ln_bias: [embed_dim] + ln_scale = paddle.rand(shape=(128,), dtype="float32") + ln_bias = paddle.rand(shape=(128,), dtype="float32") + + # qkv_weight: [3, num_head, head_dim, embed_dim], qkv_bias: [3, num_head, head_dim] + qkv_weight = paddle.rand(shape=(3, 4, 32, 128), dtype="float32") + qkv_bias = paddle.rand(shape=(3, 4, 32), dtype="float32") + + # linear_weight: [embed_dim, embed_dim], linear_bias: [embed_dim] + linear_weight = paddle.rand(shape=(128, 128), dtype="float32") + linear_bias = paddle.rand(shape=(128,), dtype="float32") + + # ffn_ln_scale: [embed_dim], ffn_ln_bias: [embed_dim] + ffn_ln_scale = paddle.rand(shape=(128,), dtype="float32") + ffn_ln_bias = paddle.rand(shape=(128,), dtype="float32") + + # ffn1_weight: [embed_dim, 4*embed_dim], ffn1_bias: [4*embed_dim] + ffn1_weight = paddle.rand(shape=(128, 4*128), dtype="float32") + ffn1_bias = paddle.rand(shape=(4*128,), dtype="float32") + + # ffn2_weight: [4*embed_dim, embed_dim], ffn2_bias: [embed_dim] + ffn2_weight = paddle.rand(shape=(4*128, 128), dtype="float32") + ffn2_bias = paddle.rand(shape=(128,), dtype="float32") + + # self attention mask: [batch_size, 1, seq_len, seq_len] + attn_mask = paddle.rand(shape=(2, 1, 4, 4), dtype="float32") + + # output: [batch_size, seq_len, embed_dim] + output = F.fused_multi_transformer( + x, [ln_scale], [ln_bias], [qkv_weight], [qkv_bias], + [linear_weight], [linear_bias], [ffn_ln_scale], [ffn_ln_bias], + [ffn1_weight], [ffn1_bias], [ffn2_weight], [ffn2_bias], + attn_mask=attn_mask) + # [2, 4, 128] + print(output.shape) + """ + if mode not in ('downscale_in_infer', 'upscale_in_train'): + raise ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'" + ) + mode = ( + 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode + ) # semantic transfer + + if _non_static_mode(): + cache_kv_out, final_out = _legacy_C_ops.fused_multi_transformer( + x, + ln_scales, + ln_biases, + qkv_weights, + qkv_biases, + cache_kvs, + time_step, + attn_mask, + linear_weights, + linear_biases, + ffn_ln_scales, + ffn_ln_biases, + ffn1_weights, + ffn1_biases, + ffn2_weights, + ffn2_biases, + cache_kvs, + 'pre_layer_norm', + pre_layer_norm, + 'epsilon', + epsilon, + 'dropout_rate', + dropout_rate, + 'is_test', + not training, + 'dropout_implementation', + mode, + 'act_method', + activation, + 'trans_qkvw', + trans_qkvw, + 'ring_id', + ring_id, + ) + if cache_kvs is not None: + return final_out, cache_kv_out + return final_out + else: + helper = LayerHelper('fused_multi_transformer', **locals()) + dtype = x.dtype + # check dtypes + check_variable_and_dtype( + x, 'x', ['float16', 'float32'], 'fused_multi_transformer' + ) + check_dtype( + dtype, 'dtype', ['float16', 'float32'], 'fused_multi_transformer' + ) + + # set inputs + inputs = dict() + inputs['X'] = [x] + inputs['LnScale'] = ln_scales + inputs['LnBias'] = ln_biases + inputs['QKVW'] = qkv_weights + if qkv_biases is not None: + inputs['QKVBias'] = qkv_biases + if cache_kvs is not None: + assert len(cache_kvs) == len(qkv_weights) + inputs['CacheKV'] = cache_kvs + if time_step is not None: + inputs['TimeStep'] = time_step + inputs['SrcMask'] = attn_mask + inputs['OutLinearW'] = linear_weights + if linear_biases is not None: + inputs['OutLinearBias'] = linear_biases + + inputs['FFNLnScale'] = ffn_ln_scales + inputs['FFNLnBias'] = ffn_ln_biases + inputs['FFN1Weight'] = ffn1_weights + if ffn1_biases is not None: + inputs['FFN1Bias'] = ffn1_biases + inputs['FFN2Weight'] = ffn2_weights + if ffn2_biases is not None: + inputs['FFN2Bias'] = ffn2_biases + + # set attrs + attrs = { + 'pre_layer_norm': pre_layer_norm, + 'epsilon': epsilon, + 'dropout_rate': dropout_rate, + 'is_test': not training, + 'dropout_implementation': mode, + 'act_method': activation, + 'trans_qkvw': trans_qkvw, + 'ring_id': ring_id, + } + + outputs = dict() + final_out = helper.create_variable_for_type_inference(dtype=dtype) + outputs['Out'] = final_out + if cache_kvs: + # NOTE: inplace + outputs['CacheKVOut'] = cache_kvs + + helper.append_op( + type='fused_multi_transformer', + inputs=inputs, + outputs=outputs, + attrs=attrs, + ) + + return (final_out, cache_kvs) if cache_kvs else final_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_linear.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8800afce61a00887a30fe1c9bc8f013ecc9b51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_linear.py @@ -0,0 +1,95 @@ +# Copyright (c) 2022 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. + +from paddle.nn import Layer +from paddle.incubate.nn import functional as F + + +class FusedLinear(Layer): + """ + Linear layer takes only one multi-dimensional tensor as input with the + shape :math:`[batch\_size, *, in\_features]` , where :math:`*` means any + number of additional dimensions. It multiplies input tensor with the weight + (a 2-D tensor of shape :math:`[in\_features, out\_features]` ) and produces + an output tensor of shape :math:`[batch\_size, *, out\_features]` . + If :math:`bias\_attr` is not False, the bias (a 1-D tensor of + shape :math:`[out\_features]` ) will be created and added to the output. + + Parameters: + in_features (int): The number of input units. + out_features (int): The number of output units. + weight_attr (ParamAttr, optional): The attribute for the learnable + weight of this layer. The default value is None and the weight will be + initialized to zero. For detailed information, please refer to + paddle.ParamAttr. + transpose_weight (bool): Whether to transpose the `weight` Tensor before + multiplication. + bias_attr (ParamAttr|bool, optional): The attribute for the learnable bias + of this layer. If it is set to False, no bias will be added to the output. + If it is set to None or one kind of ParamAttr, a bias parameter will + be created according to ParamAttr. For detailed information, please refer + to paddle.ParamAttr. The default value is None and the bias will be + initialized to zero. + name (str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Attribute: + **weight** (Parameter): the learnable weight of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + - input: Multi-dimentional tensor with shape :math:`[batch\_size, *, in\_features]` . + - output: Multi-dimentional tensor with shape :math:`[batch\_size, *, out\_features]` . + + Examples: + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn import FusedLinear + + x = paddle.randn([3, 4]) + linear = FusedLinear(4, 5) + y = linear(x) + print(y.shape) # [3, 5] + """ + + def __init__(self, + in_features, + out_features, + weight_attr=None, + bias_attr=None, + transpose_weight=False, + name=None): + super(FusedLinear, self).__init__() + if transpose_weight: + weight_shape = [out_features, in_features] + else: + weight_shape = [in_features, out_features] + dtype = self._helper.get_default_dtype() + self.weight = self.create_parameter(shape=weight_shape, + attr=weight_attr, + dtype=dtype, + is_bias=False) + self.bias = self.create_parameter(shape=[out_features], + attr=bias_attr, + dtype=dtype, + is_bias=True) + self.transpose_weight = transpose_weight + self.name = name + + def forward(self, input): + return F.fused_linear(input, self.weight, self.bias, + self.transpose_weight, self.name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c3655c9d93a2745c7bfd8fbc5f6c00621121bf55 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/nn/layer/fused_transformer.py @@ -0,0 +1,1420 @@ +# Copyright (c) 2021 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. +from paddle.nn import functional as F +from paddle.incubate.nn import functional as incubate_f +from paddle.nn import Layer +from paddle.framework import ParamAttr +import paddle +from paddle.nn.layer.transformer import ( + _convert_attention_mask, + _convert_param_attr_to_list, +) +from paddle.nn.initializer import Constant +from paddle.fluid.dygraph import no_grad +from paddle.fluid.framework import convert_np_dtype_to_dtype_, _non_static_mode +from paddle.fluid.core import VarDesc +from paddle.fluid import core +import numpy as np + + +# for distributed tensor model parallel +def _set_var_distributed(var): + if var is None: + return + + var.is_distributed = True + + if not _non_static_mode(): + # NOTE: use current_block and find_var_recursive to support while_loop + startup_block = paddle.static.default_startup_program().current_block() + main_block = paddle.static.default_main_program().current_block() + startup_block._find_var_recursive(var.name).is_distributed = True + main_block._find_var_recursive(var.name).is_distributed = True + + +def _to_dtype(t, dtype): + # this function is a prune of Layer._transform function to fix fused op under amp.decorator(O2) + if not paddle.is_floating_point(t): + return t + + if type(dtype) is not VarDesc.VarType: + dtype = convert_np_dtype_to_dtype_(dtype) + + if t.place.is_gpu_place(): + size_dtype = core.size_of_dtype(dtype) + waiting_alloc_memory = ( + ((np.prod(t.shape) * size_dtype) / 256 + 1) * 256 * 1.2 + ) + gpu_memory_available = core.gpu_memory_available() + if gpu_memory_available < waiting_alloc_memory: + t_used = t._copy_to(paddle.CPUPlace(), False) + t.value().get_tensor()._clear() + else: + t_used = t + else: + t_used = t + + if dtype is not None and dtype != t_used.dtype: + with paddle.fluid.framework._dygraph_place_guard(place=t_used.place): + t_casted = t_used.cast(dtype=dtype) + else: + t_casted = t_used + + new_t = t_casted + + dst_tensor = t.value().get_tensor() + src_tensor = new_t.value().get_tensor() + dst_tensor._share_data_with(src_tensor) + + return t + + +class FusedBiasDropoutResidualLayerNorm(Layer): + """ + Applies fused_bias_dropout_residual_layer_norm operation. + + Parameters: + embed_dim (int): The expected feature size in the input and output. + dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout after attention. + 0 for no dropout. Default 0.5. + bias_attr (ParamAttr|bool, optional): To specify the bias parameter property. + Default: None, which means the default bias parameter property is used. + If it is set to False, this layer will not have trainable bias parameter. + See usage for details in :code:`ParamAttr`. + epsilon (float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + # input: [batch_size, seq_len, embed_dim] + x = paddle.rand((2, 4, 128)) + # residual: [batch_size, seq_len, embed_dim] + residual = paddle.rand((2, 4, 128)) + fused_bias_dropout_residual_ln = paddle.incubate.nn.FusedBiasDropoutResidualLayerNorm(128) + output = fused_bias_dropout_residual_ln(x, residual) # [2, 4, 128] + """ + + def __init__( + self, + embed_dim, + dropout_rate=0.5, + weight_attr=None, + bias_attr=None, + epsilon=1e-5, + name=None, + ): + super(FusedBiasDropoutResidualLayerNorm, self).__init__() + assert embed_dim > 0, ( + "Expected embed_dim to be greater than 0, " + "but recieved {}".format(embed_dim) + ) + self._dtype = self._helper.get_default_dtype() + self._bias_attr = bias_attr + self._weight_attr = weight_attr + self.embed_dim = embed_dim + self.linear_bias = self.create_parameter( + shape=[embed_dim], + attr=self._bias_attr, + dtype=self._dtype, + is_bias=True, + ) + self.ln_scale = self.create_parameter( + attr=self._weight_attr, + shape=[embed_dim], + default_initializer=Constant(value=1.0), + ) + self.ln_bias = self.create_parameter( + attr=self._bias_attr, shape=[embed_dim], is_bias=True + ) + self.dropout_rate = dropout_rate + self._epsilon = epsilon + + self.name = name + + def forward(self, x, residual): + """ + Applies fused_bias_dropout_residual_layer_norm operation. + + Parameters: + x (Tensor): The input tensor. It is a tensor with shape + `[batch_size, seq_len, embed_dim]`. The data type should be + float32 or float64. + residual (Tensor, optional): The residual tensor. It is a tensor + with shape `[batch_size, value_length, vdim]`. The data type + should be float32 or float64. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `x`. + """ + + out = incubate_f.fused_bias_dropout_residual_layer_norm( + x=x, + residual=residual, + bias=self.linear_bias, + ln_scale=self.ln_scale, + ln_bias=self.ln_bias, + dropout_rate=self.dropout_rate, + ln_epsilon=self._epsilon, + training=self.training, + mode='upscale_in_train', + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'embed_dim={}, seq_len={}, dropout_rate={}, epsilon={}, dtype={}{}'.format( + self.embed_dim, + self.seq_len, + self.dropout_rate, + self._epsilon, + self._dtype, + name_str, + ) + + +class FusedMultiHeadAttention(Layer): + """ + Attention mapps queries and a set of key-value pairs to outputs, and + Multi-Head Attention performs multiple parallel attention to jointly attending + to information from different representation subspaces. + Please refer to `Attention Is All You Need `_ + for more details. + + Parameters: + embed_dim (int): The expected feature size in the input and output. + num_heads (int): The number of heads in multi-head attention. + dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout after attention. + 0 for no dropout. Default 0.5. + attn_dropout_rate (float, optional): The dropout probability used on attention + weights to drop some attention targets for the dropout in attention. + 0 for no dropout. Default 0.5. + kdim (int, optional): The feature size in key. If None, assumed equal to + `embed_dim`. Default None. + vdim (int, optional): The feature size in value. If None, assumed equal to + `embed_dim`. Default None. + normalize_before (bool, optional): Indicate whether it is pre_layer_norm + (True) or post_layer_norm architecture (False). Default False. + need_weights (bool, optional): Indicate whether to return the attention + weights. Now, only False is supported. Default False. + qkv_weight_attr(ParamAttr, optional): To specify the weight parameter property + for QKV projection computation. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + qkv_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for QKV projection computation. The `False` value means the corresponding layer + would not have trainable bias parameter. Default: None, which means the + default bias parameter property is used. See usage for details in :code:`ParamAttr`. + linear_weight_attr(ParamAttr, optional): To specify the weight parameter property + for linear projection computation. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + linear_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for linear projection computation. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + pre_ln_scale_attr(ParamAttr, optional): To specify the weight parameter property + for pre_layer_norm computation. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + pre_ln_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for pre_layer_norm computation. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ln_scale_attr(ParamAttr, optional): To specify the weight parameter property + for post_layer_norm computation. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ln_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for post_layer_norm computation. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + epsilon (float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + nranks (int, optional): Distributed tensor model parallel nranks. Default is 1, means not using tensor parallel. + ring_id (int, optional): For distributed tensor model parallel. Default is -1, means not using tensor parallel. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + # input: [batch_size, sequence_length, embed_dim] + query = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, num_heads, query_len, query_len] + attn_mask = paddle.rand((2, 2, 4, 4)) + multi_head_attn = paddle.incubate.nn.FusedMultiHeadAttention(128, 2) + output = multi_head_attn(query, None, None, attn_mask=attn_mask) # [2, 4, 128] + """ + + def __init__( + self, + embed_dim, + num_heads, + dropout_rate=0.5, + attn_dropout_rate=0.5, + kdim=None, + vdim=None, + normalize_before=False, + need_weights=False, + qkv_weight_attr=None, + qkv_bias_attr=None, + linear_weight_attr=None, + linear_bias_attr=None, + pre_ln_scale_attr=None, + pre_ln_bias_attr=None, + ln_scale_attr=None, + ln_bias_attr=None, + epsilon=1e-5, + nranks=1, + ring_id=-1, + name=None, + ): + super(FusedMultiHeadAttention, self).__init__() + + assert embed_dim > 0, ( + "Expected embed_dim to be greater than 0, " + "but received {}".format(embed_dim) + ) + assert ( + num_heads > 0 + ), "Expected nhead to be greater than 0, " "but received {}".format( + num_heads + ) + + self.normalize_before = normalize_before + self._dtype = self._helper.get_default_dtype() + self._epsilon = epsilon + self._ring_id = ring_id + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.head_dim = embed_dim // num_heads + self.kdim = kdim + self.vdim = vdim + self.need_weights = need_weights + assert ( + self.head_dim * num_heads == embed_dim + ), "embed_dim must be divisible by num_heads" + assert need_weights is False, "Only support need_weight is False now." + + # tensor model parallel + assert num_heads % nranks == 0 + num_heads = num_heads // nranks + + self.qkv_weight = self.create_parameter( + shape=[3, num_heads, self.head_dim, embed_dim], + attr=qkv_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + self.qkv_bias = self.create_parameter( + shape=[3, num_heads, self.head_dim], + attr=qkv_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + self.linear_weight = self.create_parameter( + shape=[num_heads * self.head_dim, embed_dim], + attr=linear_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + self.linear_bias = self.create_parameter( + shape=[embed_dim], + attr=linear_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + + # tensor model parallel + if nranks > 1: + assert ring_id != -1 + # column parallel + _set_var_distributed(self.qkv_weight) + _set_var_distributed(self.qkv_bias) + # row parallel + _set_var_distributed(self.linear_weight) + + if normalize_before: + self.pre_ln_scale = self.create_parameter( + attr=pre_ln_scale_attr, + shape=[embed_dim], + default_initializer=Constant(value=1.0), + ) + self.pre_ln_bias = self.create_parameter( + attr=pre_ln_bias_attr, shape=[embed_dim], is_bias=True + ) + self.ln_scale = None + self.ln_bias = None + else: + self.pre_ln_scale = None + self.pre_ln_bias = None + self.ln_scale = self.create_parameter( + attr=ln_scale_attr, + shape=[embed_dim], + default_initializer=Constant(value=1.0), + ) + self.ln_bias = self.create_parameter( + attr=ln_bias_attr, shape=[embed_dim], is_bias=True + ) + + self.dropout_rate = dropout_rate + self.attn_dropout_rate = attn_dropout_rate + + self.name = name + + def forward(self, query, key=None, value=None, attn_mask=None, cache=None): + """ + Applies multi-head attention to map queries and a set of key-value pairs + to outputs. + + Parameters: + query (Tensor): The queries for multi-head attention. It is a + tensor with shape `[batch_size, query_length, embed_dim]`. The + data type should be float32 or float64. + key (Tensor, optional): The keys for multi-head attention. It is + a tensor with shape `[batch_size, key_length, kdim]`. The + data type should be float32 or float64. If None, use `query` as + `key`. Default None. + value (Tensor, optional): The values for multi-head attention. It + is a tensor with shape `[batch_size, value_length, vdim]`. + The data type should be float32 or float64. If None, use `query` as + `value`. Default None. + attn_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (MultiHeadAttention.Cache|MultiHeadAttention.StaticCache, optional): + Now, only None is supported. Default None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `query`, representing attention output. + """ + if attn_mask is not None: + # Support bool or int mask + attn_mask = _convert_attention_mask(attn_mask, query.dtype) + + out = incubate_f.fused_multi_head_attention( + x=query, + qkv_weight=self.qkv_weight, + linear_weight=self.linear_weight, + pre_layer_norm=self.normalize_before, + pre_ln_scale=self.pre_ln_scale, + pre_ln_bias=self.pre_ln_bias, + ln_scale=self.ln_scale, + ln_bias=self.ln_bias, + pre_ln_epsilon=self._epsilon, + qkv_bias=self.qkv_bias, + linear_bias=self.linear_bias, + cache_kv=cache, + attn_mask=attn_mask, + dropout_rate=self.dropout_rate, + attn_dropout_rate=self.attn_dropout_rate, + ln_epsilon=self._epsilon, + training=self.training, + ring_id=self._ring_id, + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'embed_dim={}, num_heads={}, dropout_rate={}, attn_dropout_rate={}, epsilon={}, kdim={}, vdim={}, normalize_before={}, need_weights={}, dtype={}{}'.format( + self.embed_dim, + self.num_heads, + self.dropout_rate, + self.attn_dropout_rate, + self._epsilon, + self.kdim, + self.vdim, + self.normalize_before, + self.need_weights, + self._dtype, + name_str, + ) + + def _amp_decorate(self, dtype): + # tmp fix for amp.decorator(O2) + layer_norm_params_id = [] + if self.normalize_before: + layer_norm_params_id.append(id(self.pre_ln_scale)) + layer_norm_params_id.append(id(self.pre_ln_bias)) + else: + layer_norm_params_id.append(id(self.ln_scale)) + layer_norm_params_id.append(id(self.ln_bias)) + + for key, param in self._parameters.items(): + if id(param) in layer_norm_params_id: + continue + if param is not None: + with no_grad(): + param_applied = _to_dtype(param, dtype) + + self._dtype = dtype + + +class FusedFeedForward(Layer): + """ + Parameters: + d_model (int): The expected feature size in the input and output. + dim_feedforward (int): The hidden layer size. + dropout_rate (float, optional): The dropout probability used in pre-process + and post-precess. Default 0.1 + epsilon (float, optional): he small value added to the variance to prevent + division by zero. Default: 1e-05. + activation (str, optional): The activation function. Default relu. + act_dropout_rate (float, optional): The dropout probability after activition. + If None, use the value of `dropout_rate`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into, preprocessing or postprocessing. Default False + linear1_weight_attr(ParamAttr, optional): To specify the weight parameter property + for FFN first linear. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + linear1_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for FFN first linear. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + linear2_weight_attr(ParamAttr, optional): To specify the weight parameter property + for FFN second linear. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + linear2_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for FFN second linear. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ln1_scale_attr(ParamAttr, optional): To specify the weight parameter property + for FFN pre_layer_norm. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ln1_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for FFN pre_layer_norm. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ln2_scale_attr(ParamAttr, optional): To specify the weight parameter property + for FFN post_layer_norm. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ln2_bias_attr(ParamAttr|bool, optional): To specify the bias parameter property + for FFN layer_norm. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + nranks (int, optional): Distributed tensor model parallel nranks. Default is 1, means not using tensor parallel. + ring_id (int, optional): For distributed tensor model parallel. Default is -1, means not using tensor parallel. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn import FusedFeedForward + + fused_feedforward_layer = FusedFeedForward(8, 8) + x = paddle.rand((1, 8, 8)) + out = fused_feedforward_layer(x) + print(out.numpy().shape) + # (1, 8, 8) + """ + + def __init__( + self, + d_model, + dim_feedforward, + dropout_rate=0.1, + epsilon=1e-05, + activation="relu", + act_dropout_rate=None, + normalize_before=False, + linear1_weight_attr=None, + linear1_bias_attr=None, + linear2_weight_attr=None, + linear2_bias_attr=None, + ln1_scale_attr=None, + ln1_bias_attr=None, + ln2_scale_attr=None, + ln2_bias_attr=None, + nranks=1, + ring_id=-1, + name=None, + ): + + super(FusedFeedForward, self).__init__() + assert ( + d_model > 0 + ), "Expected d_model to be greater than 0, but received {}".format( + d_model + ) + assert ( + dim_feedforward > 0 + ), "Expected dim_feedforward to be greater than 0, but received {}".format( + dim_feedforward + ) + + self._dtype = self._helper.get_default_dtype() + self._d_model = d_model + + assert dim_feedforward % nranks == 0 + dim_feedforward = dim_feedforward // nranks + self._dim_feedforward = dim_feedforward + self._dropout_rate = dropout_rate + self._act_dropout_rate = ( + dropout_rate if act_dropout_rate is None else act_dropout_rate + ) + self._act_method = activation + self._normalize_before = normalize_before + self._epsilon = epsilon + self._ring_id = ring_id + + self._linear1_weight = self.create_parameter( + shape=[d_model, dim_feedforward], + attr=linear1_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + self._linear1_bias = self.create_parameter( + shape=[dim_feedforward], + attr=linear1_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + + self._linear2_weight = self.create_parameter( + shape=[dim_feedforward, d_model], + attr=linear2_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + + self._linear2_bias = self.create_parameter( + shape=[d_model], + attr=linear2_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + + if nranks > 1: + assert ring_id != -1 + # column parallel + _set_var_distributed(self._linear1_weight) + _set_var_distributed(self._linear1_bias) + _set_var_distributed(self._linear2_weight) + + if normalize_before: + self._ln1_scale = self.create_parameter( + shape=[d_model], + attr=ln1_scale_attr, + is_bias=False, + default_initializer=Constant(1.0), + ) + self._ln1_bias = self.create_parameter( + shape=[d_model], attr=ln1_bias_attr, is_bias=True + ) + self._ln2_scale = None + self._ln2_bias = None + else: + self._ln1_scale = None + self._ln1_bias = None + self._ln2_scale = self.create_parameter( + shape=[d_model], + attr=ln2_scale_attr, + is_bias=False, + default_initializer=Constant(1.0), + ) + self._ln2_bias = self.create_parameter( + shape=[d_model], attr=ln2_bias_attr, is_bias=True + ) + + self.name = name + + def forward(self, src, cache=None): + out = incubate_f.fused_feedforward( + src, + self._linear1_weight, + self._linear2_weight, + self._linear1_bias, + self._linear2_bias, + self._ln1_scale, + self._ln1_bias, + self._ln2_scale, + self._ln2_bias, + dropout1_rate=self._act_dropout_rate, + dropout2_rate=self._dropout_rate, + activation=self._act_method, + ln1_epsilon=self._epsilon, + ln2_epsilon=self._epsilon, + pre_layer_norm=self._normalize_before, + training=self.training, + ring_id=self._ring_id, + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'd_model={}, dim_feedforward={}, dropout_rate={}, epsilon={}, activation={}, act_dropout_rate={}, normalize_before={}, dtype={}{}'.format( + self._d_model, + self._dim_feedforward, + self._dropout_rate, + self._epsilon, + self._act_method, + self._act_dropout_rate, + self._normalize_before, + self._dtype, + name_str, + ) + + def _amp_decorate(self, dtype): + # tmp fix for amp.decorator(O2) + layer_norm_params_id = [] + if self._normalize_before: + layer_norm_params_id.append(id(self._ln1_scale)) + layer_norm_params_id.append(id(self._ln1_bias)) + else: + layer_norm_params_id.append(id(self._ln2_scale)) + layer_norm_params_id.append(id(self._ln2_bias)) + + for key, param in self._parameters.items(): + if id(param) in layer_norm_params_id: + continue + if param is not None: + with no_grad(): + param_applied = _to_dtype(param, dtype) + + self._dtype = dtype + + +class FusedTransformerEncoderLayer(Layer): + """ + + FusedTransformerEncoderLayer is composed of two sub-layers which are self (multi-head) + attention and feedforward network. Before and after each sub-layer, pre-process + and post-precess would be applied on the input and output accordingly. If + `normalize_before` is True, pre-process is layer normalization and post-precess + includes dropout, residual connection. Otherwise, no pre-process and post-precess + includes dropout, residual connection, layer normalization. + + Parameters: + d_model (int): The expected feature size in the input and output. + nhead (int): The number of heads in multi-head attention(MHA). + dim_feedforward (int): The hidden layer size in the feedforward network(FFN). + dropout_rate (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.1 + activation (str, optional): The activation function in the feedforward + network. Default relu. + attn_dropout_rate (float, optional): The dropout probability used + in MHA to drop some attention target. If None, use the value of + `dropout`. Default None + act_dropout_rate (float, optional): The dropout probability used after FFN + activition. If None, use the value of `dropout`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default False + weight_attr(ParamAttr|list|tuple, optional): To specify the weight parameter property. + If it is a list/tuple, `weight_attr[0]` would be used as `weight_attr` for + MHA, and `weight_attr[1]` would be used as `weight_attr` for linear in FFN. + Otherwise, MHA and FFN both use it as `weight_attr` to create parameters. + Default: None, which means the default weight parameter property is used. + See usage for details in :code:`ParamAttr` . + bias_attr (ParamAttr|list|tuple|bool, optional): To specify the bias parameter property. + If it is a list/tuple, `bias_attr[0]` would be used as `bias_attr` for + MHA, and `bias_attr[1]` would be used as `bias_attr` for linear in FFN. + Otherwise, MHA and FFN both use it as `bias_attr` to create parameters. + The `False` value means the corresponding layer would not have trainable + bias parameter. See usage for details in :code:`ParamAttr` . Default: None, + which means the default bias parameter property is used. + + + Examples: + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn import FusedTransformerEncoderLayer + + # encoder input: [batch_size, src_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, n_head, src_len, src_len] + attn_mask = paddle.rand((2, 2, 4, 4)) + encoder_layer = FusedTransformerEncoderLayer(128, 2, 512) + enc_output = encoder_layer(enc_input, attn_mask) # [2, 4, 128] + + """ + + def __init__( + self, + d_model, + nhead, + dim_feedforward, + dropout_rate=0.1, + activation="relu", + attn_dropout_rate=None, + act_dropout_rate=None, + normalize_before=False, + weight_attr=None, + bias_attr=None, + ): + self._config = locals() + self._config.pop("self") + self._config.pop("__class__", None) # py3 + + super(FusedTransformerEncoderLayer, self).__init__() + assert ( + d_model > 0 + ), "Expected d_model to be greater than 0, " "but received {}".format( + d_model + ) + assert ( + nhead > 0 + ), "Expected nhead to be greater than 0, " "but received {}".format( + nhead + ) + assert dim_feedforward > 0, ( + "Expected dim_feedforward to be greater than 0, " + "but received {}".format(dim_feedforward) + ) + attn_dropout_rate = ( + dropout_rate if attn_dropout_rate is None else attn_dropout_rate + ) + act_dropout_rate = ( + dropout_rate if act_dropout_rate is None else act_dropout_rate + ) + self.normalize_before = normalize_before + + weight_attrs = _convert_param_attr_to_list(weight_attr, 2) + bias_attrs = _convert_param_attr_to_list(bias_attr, 2) + + self.fused_attn = FusedMultiHeadAttention( + d_model, + nhead, + dropout_rate=dropout_rate, + attn_dropout_rate=attn_dropout_rate, + normalize_before=self.normalize_before, + qkv_weight_attr=weight_attrs[0], + qkv_bias_attr=bias_attrs[0], + linear_weight_attr=weight_attrs[0], + linear_bias_attr=bias_attrs[0], + pre_ln_scale_attr=weight_attrs[0], + pre_ln_bias_attr=bias_attrs[0], + ln_scale_attr=weight_attrs[0], + ln_bias_attr=bias_attrs[0], + ) + + self.ffn = FusedFeedForward( + d_model, + dim_feedforward, + dropout_rate=dropout_rate, + activation=activation, + act_dropout_rate=act_dropout_rate, + normalize_before=self.normalize_before, + linear1_weight_attr=weight_attrs[1], + linear1_bias_attr=bias_attrs[1], + linear2_weight_attr=weight_attrs[1], + linear2_bias_attr=bias_attrs[1], + ) + + def forward(self, src, src_mask=None, cache=None): + """ + + Applies a Transformer encoder layer on the input. + + Parameters: + src (Tensor): The input of Transformer encoder layer. It is + a tensor with shape `[batch_size, sequence_length, d_model]`. + The data type should be float32 or float64. + src_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (Tensor, optional): It is an instance of `MultiHeadAttention.Cache`. + See :ref:`api_paddle_nn_TransformerEncoderLayer`.gen_cache for more details. It is + only used for inference and should be None for training. Default + None. + + Returns: + Tensor|tuple, It is a tensor that has the same shape and data type \ + as `enc_input`, representing the output of Transformer encoder \ + layer. Or a tuple if `cache` is not None, except for encoder \ + layer output, the tuple includes the new cache which is same \ + as input `cache` argument but `incremental_cache` has an \ + incremental length. See `MultiHeadAttention.gen_cache` and \ + `MultiHeadAttention.forward` for more details. + + """ + src_mask = _convert_attention_mask(src_mask, src.dtype) + if cache is None: + attn_out = self.fused_attn(src, attn_mask=src_mask) + else: + attn_out, incremental_cache = self.fused_attn( + src, attn_mask=src_mask, cache=cache + ) + + ffn_out = self.ffn(attn_out) + + return ffn_out if cache is None else (ffn_out, incremental_cache) + + +class FusedTransformer(Layer): + """ + A Transformer model composed of an instance of `TransformerEncoder` and an + instance of `TransformerDecoder`. While the embedding layer and output layer + are not included. + + Please refer to `Attention is all you need `_ , + and see `TransformerEncoder` and `TransformerDecoder` for more details. + + Users can configurate the model architecture with corresponding parameters. + Note the usage of `normalize_before` representing where to apply layer + normalization (in pre-process or post-precess of multi-head attention or FFN), + and some transformer like models are different on this, such as + `BERT `_ and `GPT2 `_ . + The default architecture here places layer normalization in post-process and + applies another layer normalization on the output of last encoder/decoder layer. + + Parameters: + d_model (int, optional): The expected feature size in the encoder/decoder input + and output. Default 512 + nhead (int, optional): The number of heads in multi-head attention(MHA). Default 8 + num_encoder_layers (int, optional): The number of layers in encoder. Default 6 + num_decoder_layers (int, optional): The number of layers in decoder. Default 6 + dim_feedforward (int, optional): The hidden layer size in the feedforward network(FFN). Default 2048 + dropout (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.1 + activation (str, optional): The activation function in the feedforward + network. Default relu. + attn_dropout (float, optional): The dropout probability used + in MHA to drop some attention target. If None, use the value of + `dropout`. Default None + act_dropout (float, optional): The dropout probability used after FFN + activition. If None, use the value of `dropout`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default False + weight_attr(ParamAttr|list|tuple, optional): To specify the weight parameter property. + If it is a list/tuple, the length of `weight_attr` could be 1, 2 or 3. If it is 3, + `weight_attr[0]` would be used as `weight_attr` for self attention, `weight_attr[1]` + would be used as `weight_attr` for cross attention of `TransformerDecoder`, + and `weight_attr[2]` would be used as `weight_attr` for linear in FFN. + If it is 2, `weight_attr[0]` would be used as `weight_attr` both for self attention + and cross attntion and `weight_attr[1]` would be used as `weight_attr` for + linear in FFN. If it is 1, `weight_attr[0]` would be used as `weight_attr` + for self attention, cross attention and linear in FFN. Otherwise, + the three sub-layers all uses it as `weight_attr` to create parameters. + Default: None, which means the default weight parameter property is used. + See usage for details + in :code:`ParamAttr` . + bias_attr (ParamAttr|list|tuple|bool, optional): To specify the bias parameter property. + If it is a list/tuple, the length of `bias_attr` could be 1, 2 or 3. If it is 3, + `bias_attr[0]` would be used as `bias_attr` for self attention, `bias_attr[1]` + would be used as `bias_attr` for cross attention of `TransformerDecoder`, + and `bias_attr[2]` would be used as `bias_attr` for linear in FFN. + If it is 2, `bias_attr[0]` would be used as `bias_attr` both for self attention + and cross attntion and `bias_attr[1]` would be used as `bias_attr` for + linear in FFN. If it is 1, `bias_attr[0]` would be used as `bias_attr` + for self attention, cross attention and linear in FFN. Otherwise, + the three sub-layers all uses it as `bias_attr` to create parameters. + The `False` value means the corresponding layer would not have trainable + bias parameter. See usage for details in :code:`ParamAttr` . + Default: None,which means the default bias parameter property is used. + custom_encoder (Layer, optional): If custom encoder is provided, use it as the encoder. + Default None + custom_decoder (Layer, optional): If custom decoder is provided, use it as the decoder. + Default None + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import Transformer + + # src: [batch_size, tgt_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # tgt: [batch_size, src_len, d_model] + dec_input = paddle.rand((2, 6, 128)) + # src_mask: [batch_size, n_head, src_len, src_len] + enc_self_attn_mask = paddle.rand((2, 2, 4, 4)) + # tgt_mask: [batch_size, n_head, tgt_len, tgt_len] + dec_self_attn_mask = paddle.rand((2, 2, 6, 6)) + # memory_mask: [batch_size, n_head, tgt_len, src_len] + cross_attn_mask = paddle.rand((2, 2, 6, 4)) + transformer = Transformer(128, 2, 4, 4, 512) + output = transformer(enc_input, + dec_input, + enc_self_attn_mask, + dec_self_attn_mask, + cross_attn_mask) # [2, 6, 128] + """ + + def __init__( + self, + d_model=512, + nhead=8, + num_encoder_layers=6, + num_decoder_layers=6, + dim_feedforward=2048, + dropout=0.1, + activation="relu", + attn_dropout=None, + act_dropout=None, + normalize_before=False, + weight_attr=None, + bias_attr=None, + custom_encoder=None, + custom_decoder=None, + ): + super(fusedTransformer, self).__init__() + raise NotImplementedError() + + def forward(self, src, tgt, src_mask=None, tgt_mask=None, memory_mask=None): + raise NotImplementedError() + + +class FusedMultiTransformer(Layer): + """ + FusedMultiTransformer is composed of multi transformer layers which contains two + sub-layers which are self (multi-head) attention and feedforward network. The + function of one transformer layer is consistent with the following pseudo code: + + .. code-block:: python + + if pre_layer_norm: + out = layer_norm(x) + out = qkv_linear(out) + qkv_bias + else: + out = qkv_linear(x) + qkv_bias + out = transpose(out, perm=[2, 0, 3, 1, 4]) + # extract q, k and v from out. + q = out[0:1, ::] + k = out[1:2, ::] + v = out[2:3, ::] + out = q * k^t + out = attn_mask + out + out = softmax(out) + out = dropout(out) + out = out * v + out = transpose(out, perm=[0, 2, 1, 3]) + out = linear(out) + if pre_layer_norm: + out = x + dropout(out + bias) + else: + out = layer_norm(x + dropout(out + bias)) + + residual = out; + if pre_layer_norm: + out = ffn_layer_norm(out) + out = ffn1_linear(out) + out = dropout(activation(out + ffn1_bias)) + out = ffn2_linear(out) + out = residual + dropout(out + ffn2_bias) + if not pre_layer_norm: + out = ffn_layer_norm(out) + + Parameters: + embed_dim (int): The expected feature size in the input and output. + num_heads (int): The number of heads in multi-head attention(MHA). + dim_feedforward (int): The hidden layer size in the feedforward network(FFN). + dropout_rate (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.0 + activation (str, optional): The activation function in the feedforward + network. Default "gelu". + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default True + ln_scale_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for Attention layer_norm. For Attention layer_norm weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ln_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for Attention layer_norm. For Attention layer_norm bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + qkv_weight_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for Attention qkv computation. For Attention qkv weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + qkv_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for Attention qkv computation. For Attention qkv bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + linear_weight_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for Attention linear. For Attention linear weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + linear_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for Attention linear computation. For Attention linear bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn_ln_scale_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for FFN layer_norm. For FFN layer_norm weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn_ln_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for FFN layer_norm. For FFN layer_norm bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn1_weight_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for FFN first linear. For FFN first linear weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn1_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for FFN first linear. For FFN first linear bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn2_weight_attrs(ParamAttr|list|tuple, optional): To specify the weight parameter property + for FFN second linear. For FFN second linear weight, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. Default: None, which means the default weight + parameter property is used. See usage for details in :code:`ParamAttr`. + ffn2_bias_attrs(ParamAttr|list|tuple|bool, optional): To specify the bias parameter property + for FFN second linear. For FFN second linear bias, if it is a list/tuple, `attrs[0]` + would be used as `attr` for transformer layer 0, and `attrs[1]` would be used as + `attr` for transformer layer 1,etc. Otherwise, all layers both use it as + `attr` to create parameters. The `False` value means the corresponding layer would + not have trainable bias parameter. Default: None, which means the default bias + parameter property is used. See usage for details in :code:`ParamAttr`. + epsilon (float, optional): Small float value added to denominator of the layer_norm to + avoid dividing by zero. Default: 1e-05. + num_layers (int, optional): The number of layers of the transformer. If `qkv_weight_attrs` + is a list or tuple, the number of layers is obtained from `qkv_weight_attrs`. num_layers + only takes effect when `qkv_weight_attrs` is not a list or tuple. Default: -1. + nranks (int, optional): Distributed tensor model parallel nranks. Default is 1, means not using mp. + trans_qkvw (bool, optional): Whether to transpose for weights of qkv. + If true, the shape eights of qkv should be [3, num_head, dim_head, dim_embed]. + Otherwise the shape of weights of qkv should be [dim_embed, 3, num_head, dim_head]. Default: True. + ring_id (int, optional): For distributed tensor model parallel. Default is -1, means not using mp. + name (str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + from paddle.incubate.nn import FusedMultiTransformer + + # encoder input: [batch_size, src_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, 1, src_len, src_len] + attn_mask = paddle.rand((2, 1, 4, 4)) + encoder_layers = FusedMultiTransformer(128, 2, 512, num_layers=1) + enc_output = encoder_layers(enc_input, attn_mask) # [2, 4, 128] + """ + + def __init__( + self, + embed_dim, + num_heads, + dim_feedforward, + dropout_rate=0.0, + activation="gelu", + normalize_before=True, + ln_scale_attrs=None, + ln_bias_attrs=None, + qkv_weight_attrs=None, + qkv_bias_attrs=None, + linear_weight_attrs=None, + linear_bias_attrs=None, + ffn_ln_scale_attrs=None, + ffn_ln_bias_attrs=None, + ffn1_weight_attrs=None, + ffn1_bias_attrs=None, + ffn2_weight_attrs=None, + ffn2_bias_attrs=None, + epsilon=1e-5, + num_layers=-1, + nranks=1, + trans_qkvw=True, + ring_id=-1, + name=None, + ): + super(FusedMultiTransformer, self).__init__() + + assert embed_dim > 0, ( + "Expected embed_dim to be greater than 0, " + "but received {}".format(embed_dim) + ) + assert ( + num_heads > 0 + ), "Expected nhead to be greater than 0, " "but received {}".format( + num_heads + ) + assert ( + dim_feedforward > 0 + ), "Expected dim_feedforward to be greater than 0, but received {}".format( + dim_feedforward + ) + + self.normalize_before = normalize_before + self._dtype = self._helper.get_default_dtype() + self._epsilon = epsilon + self._trans_qkvw = trans_qkvw + self._ring_id = ring_id + + self.embed_dim = embed_dim + self.num_heads = num_heads + self.head_dim = embed_dim // num_heads + assert ( + self.head_dim * num_heads == embed_dim + ), "embed_dim must be divisible by num_heads" + + # tensor model parallel + if nranks > 1: + assert ring_id != -1 + assert num_heads % nranks == 0 + assert dim_feedforward % nranks == 0 + num_heads = num_heads // nranks + dim_feedforward = dim_feedforward // nranks + self._dim_feedforward = dim_feedforward + + if isinstance(qkv_weight_attrs, (list, tuple)): + num_layers = len(qkv_weight_attrs) + assert num_layers > 0 + + self.ln_scales, self.ln_biases = [], [] + self.qkv_weights, self.qkv_biases = [], [] + self.linear_weights, self.linear_biases = [], [] + self.ffn_ln_scales, self.ffn_ln_biases = [], [] + self.ffn1_weights, self.ffn1_biases = [], [] + self.ffn2_weights, self.ffn2_biases = [], [] + + def get_attr(attrs, idx): + if isinstance(attrs, (list, tuple)): + assert len(attrs) == num_layers + return attrs[idx] + return attrs + + for i in range(num_layers): + ln_scale_attr = get_attr(ln_scale_attrs, i) + ln_bias_attr = get_attr(ln_bias_attrs, i) + qkv_weight_attr = get_attr(qkv_weight_attrs, i) + qkv_bias_attr = get_attr(qkv_bias_attrs, i) + linear_weight_attr = get_attr(linear_weight_attrs, i) + linear_bias_attr = get_attr(linear_bias_attrs, i) + + ffn_ln_scale_attr = get_attr(ffn_ln_scale_attrs, i) + ffn_ln_bias_attr = get_attr(ffn_ln_bias_attrs, i) + ffn1_weight_attr = get_attr(ffn1_weight_attrs, i) + ffn1_bias_attr = get_attr(ffn1_bias_attrs, i) + ffn2_weight_attr = get_attr(ffn2_weight_attrs, i) + ffn2_bias_attr = get_attr(ffn2_bias_attrs, i) + + ln_scale = self.create_parameter( + attr=ln_scale_attr, + shape=[embed_dim], + default_initializer=Constant(value=1.0), + ) + ln_bias = self.create_parameter( + attr=ln_bias_attr, shape=[embed_dim], is_bias=True + ) + qkv_weight = self.create_parameter( + shape=[3, num_heads, self.head_dim, embed_dim] + if trans_qkvw + else [embed_dim, 3, num_heads, self.head_dim], + attr=qkv_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + qkv_bias = self.create_parameter( + shape=[3, num_heads, self.head_dim], + attr=qkv_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + linear_weight = self.create_parameter( + shape=[num_heads * self.head_dim, embed_dim], + attr=linear_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + linear_bias = self.create_parameter( + shape=[embed_dim], + attr=linear_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + + ffn_ln_scale = self.create_parameter( + shape=[embed_dim], + attr=ffn_ln_scale_attr, + is_bias=False, + default_initializer=Constant(1.0), + ) + ffn_ln_bias = self.create_parameter( + shape=[embed_dim], attr=ffn_ln_bias_attr, is_bias=True + ) + ffn1_weight = self.create_parameter( + shape=[embed_dim, dim_feedforward], + attr=ffn1_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + ffn1_bias = self.create_parameter( + shape=[dim_feedforward], + attr=ffn1_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + ffn2_weight = self.create_parameter( + shape=[dim_feedforward, embed_dim], + attr=ffn2_weight_attr, + dtype=self._dtype, + is_bias=False, + ) + ffn2_bias = self.create_parameter( + shape=[embed_dim], + attr=ffn2_bias_attr, + dtype=self._dtype, + is_bias=True, + ) + + # tensor model parallel + if nranks > 1: + # column parallel + _set_var_distributed(qkv_weight) + _set_var_distributed(qkv_bias) + _set_var_distributed(ffn1_weight) + _set_var_distributed(ffn1_bias) + # row parallel + _set_var_distributed(linear_weight) + _set_var_distributed(ffn2_weight) + + self.ln_scales.append(ln_scale) + self.ln_biases.append(ln_bias) + self.qkv_weights.append(qkv_weight) + self.qkv_biases.append(qkv_bias) + self.linear_weights.append(linear_weight) + self.linear_biases.append(linear_bias) + + self.ffn_ln_scales.append(ffn_ln_scale) + self.ffn_ln_biases.append(ffn_ln_bias) + self.ffn1_weights.append(ffn1_weight) + self.ffn1_biases.append(ffn1_bias) + self.ffn2_weights.append(ffn2_weight) + self.ffn2_biases.append(ffn2_bias) + + self.dropout_rate = dropout_rate + self.activation = activation + self.name = name + + def forward(self, src, attn_mask=None, caches=None, time_step=None): + """ + Applies multi transformer layers on the input. + + Parameters: + src (Tensor): The input of Transformer layers. It is + a tensor with shape `[batch_size, sequence_length, d_model]`. + The data type should be float16 or float32. + attn_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + `[batch_size, 1, sequence_length, sequence_length]`. It can be + None when nothing wanted or needed to be prevented attention to. + Default None. + caches (list(Tensor)|tuple(Tensor), optional): The cache structure + tensors for the inference generation model. It is only used for + inference and should be None for training. The shape is + `[2, batch_size, num_head, max_seq_len, head_dim]`. Default None. + time_step (Tensor, optional): The time step tensor for the generation + model. Which used in decode stage, to represent the time step, + that is, the real seq_len of CacheKV. The shape is `[1]`, must be + in CPUPlace. Default None. + + Returns: + Tensor|tuple: If `caches` is None, return a tensor that has + the same shape and data type with `src`, representing the output + of Transformer layers. If `caches` is not None, return the + tuple (output, caches), which output is the output of + Transformer layers, caches is inplace with input `caches`. + """ + + if caches is not None: + assert len(caches) == len(self.qkv_weights) + out = incubate_f.fused_multi_transformer( + src, + self.ln_scales, + self.ln_biases, + self.qkv_weights, + self.qkv_biases, + self.linear_weights, + self.linear_biases, + self.ffn_ln_scales, + self.ffn_ln_biases, + self.ffn1_weights, + self.ffn1_biases, + self.ffn2_weights, + self.ffn2_biases, + pre_layer_norm=self.normalize_before, + epsilon=self._epsilon, + cache_kvs=caches, + time_step=time_step, + attn_mask=attn_mask, + dropout_rate=self.dropout_rate, + activation=self.activation, + training=self.training, + mode='upscale_in_train', + trans_qkvw=self._trans_qkvw, + ring_id=self._ring_id, + name=self.name, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4ba8c3890fda80cc8001a925cb24cdff890ca0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) 2021 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. + +from .softmax_mask_fuse_upper_triangle import softmax_mask_fuse_upper_triangle # noqa: F401 +from .softmax_mask_fuse import softmax_mask_fuse # noqa: F401 +from .resnet_unit import ResNetUnit #noqa: F401 +from .graph_send_recv import graph_send_recv #noqa: F401 +from .graph_khop_sampler import graph_khop_sampler #noqa: F401 +from .graph_sample_neighbors import graph_sample_neighbors #noqa: F401 +from .graph_reindex import graph_reindex #noqa: F401 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_khop_sampler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_khop_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..b23eb5e630516498810433ea1828e7b749975126 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_khop_sampler.py @@ -0,0 +1,178 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops + + +def graph_khop_sampler( + row, + colptr, + input_nodes, + sample_sizes, + sorted_eids=None, + return_eids=False, + name=None, +): + """ + + Graph Khop Sampler API. + + This API is mainly used in Graph Learning domain, and the main purpose is to + provide high performance graph khop sampling method with subgraph reindex step. + For example, we get the CSC(Compressed Sparse Column) format of the input graph + edges as `row` and `colptr`, so as to covert graph data into a suitable format + for sampling. And the `input_nodes` means the nodes we need to sample neighbors, + and `sample_sizes` means the number of neighbors and number of layers we want + to sample. + + Args: + row (Tensor): One of the components of the CSC format of the input graph, and + the shape should be [num_edges, 1] or [num_edges]. The available + data type is int32, int64. + colptr (Tensor): One of the components of the CSC format of the input graph, + and the shape should be [num_nodes + 1, 1] or [num_nodes]. + The data type should be the same with `row`. + input_nodes (Tensor): The input nodes we need to sample neighbors for, and the + data type should be the same with `row`. + sample_sizes (list|tuple): The number of neighbors and number of layers we want + to sample. The data type should be int, and the shape + should only have one dimension. + sorted_eids (Tensor, optional): The sorted edge ids, should not be None when `return_eids` + is True. The shape should be [num_edges, 1], and the data + type should be the same with `row`. Default is None. + return_eids (bool, optional): Whether to return the id of the sample edges. Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - edge_src (Tensor), The src index of the output edges, also means the first column of + the edges. The shape is [num_sample_edges, 1] currently. + - edge_dst (Tensor), The dst index of the output edges, also means the second column + of the edges. The shape is [num_sample_edges, 1] currently. + - sample_index (Tensor), The original id of the input nodes and sampled neighbor nodes. + - reindex_nodes (Tensor), The reindex id of the input nodes. + - edge_eids (Tensor), Return the id of the sample edges if `return_eids` is True. + + Examples: + .. code-block:: python + + import paddle + + row = [3, 7, 0, 9, 1, 4, 2, 9, 3, 9, 1, 9, 7] + colptr = [0, 2, 4, 5, 6, 7, 9, 11, 11, 13, 13] + nodes = [0, 8, 1, 2] + sample_sizes = [2, 2] + row = paddle.to_tensor(row, dtype="int64") + colptr = paddle.to_tensor(colptr, dtype="int64") + nodes = paddle.to_tensor(nodes, dtype="int64") + + edge_src, edge_dst, sample_index, reindex_nodes = paddle.incubate.graph_khop_sampler(row, colptr, nodes, sample_sizes, False) + + """ + + if _non_static_mode(): + if return_eids: + if sorted_eids is None: + raise ValueError( + f"`sorted_eid` should not be None " + f"if return_eids is True." + ) + ( + edge_src, + edge_dst, + sample_index, + reindex_nodes, + edge_eids, + ) = _legacy_C_ops.graph_khop_sampler( + row, + sorted_eids, + colptr, + input_nodes, + "sample_sizes", + sample_sizes, + "return_eids", + True, + ) + return edge_src, edge_dst, sample_index, reindex_nodes, edge_eids + else: + ( + edge_src, + edge_dst, + sample_index, + reindex_nodes, + _, + ) = _legacy_C_ops.graph_khop_sampler( + row, + None, + colptr, + input_nodes, + "sample_sizes", + sample_sizes, + "return_eids", + False, + ) + return edge_src, edge_dst, sample_index, reindex_nodes + + check_variable_and_dtype( + row, "Row", ("int32", "int64"), "graph_khop_sampler" + ) + + if return_eids: + if sorted_eids is None: + raise ValueError( + f"`sorted_eid` should not be None " f"if return_eids is True." + ) + check_variable_and_dtype( + sorted_eids, "Eids", ("int32", "int64"), "graph_khop_sampler" + ) + + check_variable_and_dtype( + colptr, "Col_Ptr", ("int32", "int64"), "graph_khop_sampler" + ) + check_variable_and_dtype( + input_nodes, "X", ("int32", "int64"), "graph_khop_sampler" + ) + + helper = LayerHelper("graph_khop_sampler", **locals()) + edge_src = helper.create_variable_for_type_inference(dtype=row.dtype) + edge_dst = helper.create_variable_for_type_inference(dtype=row.dtype) + sample_index = helper.create_variable_for_type_inference(dtype=row.dtype) + reindex_nodes = helper.create_variable_for_type_inference(dtype=row.dtype) + edge_eids = helper.create_variable_for_type_inference(dtype=row.dtype) + helper.append_op( + type="graph_khop_sampler", + inputs={ + "Row": row, + "Eids": sorted_eids, + "Col_Ptr": colptr, + "X": input_nodes, + }, + outputs={ + "Out_Src": edge_src, + "Out_Dst": edge_dst, + "Sample_Index": sample_index, + "Reindex_X": reindex_nodes, + "Out_Eids": edge_eids, + }, + attrs={"sample_sizes": sample_sizes, "return_eids": return_eids}, + ) + if return_eids: + return edge_src, edge_dst, sample_index, reindex_nodes, edge_eids + else: + return edge_src, edge_dst, sample_index, reindex_nodes diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_reindex.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_reindex.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c771ba45cdc998994b966bd8c8e28fba84c104 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_reindex.py @@ -0,0 +1,167 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops +import paddle.utils.deprecated as deprecated + + +@deprecated( + since="2.4.0", + update_to="paddle.geometric.reindex_graph", + level=1, + reason="paddle.incubate.graph_reindex will be removed in future", +) +def graph_reindex( + x, + neighbors, + count, + value_buffer=None, + index_buffer=None, + flag_buffer_hashtable=False, + name=None, +): + """ + + Graph Reindex API. + + This API is mainly used in Graph Learning domain, which should be used + in conjunction with `graph_sample_neighbors` API. And the main purpose + is to reindex the ids information of the input nodes, and return the + corresponding graph edges after reindex. + + Notes: + The number in x should be unique, otherwise it would cause potential errors. + Besides, we also support multi-edge-types neighbors reindexing. If we have different + edge_type neighbors for x, we should concatenate all the neighbors and count of x. + We will reindex all the nodes from 0. + + Take input nodes x = [0, 1, 2] as an example. + If we have neighbors = [8, 9, 0, 4, 7, 6, 7], and count = [2, 3, 2], + then we know that the neighbors of 0 is [8, 9], the neighbors of 1 + is [0, 4, 7], and the neighbors of 2 is [6, 7]. + + Args: + x (Tensor): The input nodes which we sample neighbors for. The available + data type is int32, int64. + neighbors (Tensor): The neighbors of the input nodes `x`. The data type + should be the same with `x`. + count (Tensor): The neighbor count of the input nodes `x`. And the + data type should be int32. + value_buffer (Tensor, optional): Value buffer for hashtable. The data type should + be int32, and should be filled with -1. Default is None. + index_buffer (Tensor, optional): Index buffer for hashtable. The data type should + be int32, and should be filled with -1. Default is None. + flag_buffer_hashtable (bool, optional): Whether to use buffer for hashtable to speed up. + Default is False. Only useful for gpu version currently. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - reindex_src (Tensor), The source node index of graph edges after reindex. + - reindex_dst (Tensor), The destination node index of graph edges after reindex. + - out_nodes (Tensor), The index of unique input nodes and neighbors before reindex, + where we put the input nodes `x` in the front, and put neighbor + nodes in the back. + + Examples: + .. code-block:: python + + import paddle + + x = [0, 1, 2] + neighbors_e1 = [8, 9, 0, 4, 7, 6, 7] + count_e1 = [2, 3, 2] + x = paddle.to_tensor(x, dtype="int64") + neighbors_e1 = paddle.to_tensor(neighbors_e1, dtype="int64") + count_e1 = paddle.to_tensor(count_e1, dtype="int32") + + reindex_src, reindex_dst, out_nodes = \ + paddle.incubate.graph_reindex(x, neighbors_e1, count_e1) + # reindex_src: [3, 4, 0, 5, 6, 7, 6] + # reindex_dst: [0, 0, 1, 1, 1, 2, 2] + # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6] + + neighbors_e2 = [0, 2, 3, 5, 1] + count_e2 = [1, 3, 1] + neighbors_e2 = paddle.to_tensor(neighbors_e2, dtype="int64") + count_e2 = paddle.to_tensor(count_e2, dtype="int32") + + neighbors = paddle.concat([neighbors_e1, neighbors_e2]) + count = paddle.concat([count_e1, count_e2]) + reindex_src, reindex_dst, out_nodes = \ + paddle.incubate.graph_reindex(x, neighbors, count) + # reindex_src: [3, 4, 0, 5, 6, 7, 6, 0, 2, 8, 9, 1] + # reindex_dst: [0, 0, 1, 1, 1, 2, 2, 0, 1, 1, 1, 2] + # out_nodes: [0, 1, 2, 8, 9, 4, 7, 6, 3, 5] + + """ + if flag_buffer_hashtable: + if value_buffer is None or index_buffer is None: + raise ValueError( + f"`value_buffer` and `index_buffer` should not" + "be None if `flag_buffer_hashtable` is True." + ) + + if _non_static_mode(): + reindex_src, reindex_dst, out_nodes = _legacy_C_ops.graph_reindex( + x, + neighbors, + count, + value_buffer, + index_buffer, + "flag_buffer_hashtable", + flag_buffer_hashtable, + ) + return reindex_src, reindex_dst, out_nodes + + check_variable_and_dtype(x, "X", ("int32", "int64"), "graph_reindex") + check_variable_and_dtype( + neighbors, "Neighbors", ("int32", "int64"), "graph_reindex" + ) + check_variable_and_dtype(count, "Count", ("int32"), "graph_reindex") + + if flag_buffer_hashtable: + check_variable_and_dtype( + value_buffer, "HashTable_Value", ("int32"), "graph_reindex" + ) + check_variable_and_dtype( + index_buffer, "HashTable_Index", ("int32"), "graph_reindex" + ) + + helper = LayerHelper("graph_reindex", **locals()) + reindex_src = helper.create_variable_for_type_inference(dtype=x.dtype) + reindex_dst = helper.create_variable_for_type_inference(dtype=x.dtype) + out_nodes = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="graph_reindex", + inputs={ + "X": x, + "Neighbors": neighbors, + "Count": count, + "HashTable_Value": value_buffer if flag_buffer_hashtable else None, + "HashTable_Index": index_buffer if flag_buffer_hashtable else None, + }, + outputs={ + "Reindex_Src": reindex_src, + "Reindex_Dst": reindex_dst, + "Out_Nodes": out_nodes, + }, + attrs={"flag_buffer_hashtable": flag_buffer_hashtable}, + ) + return reindex_src, reindex_dst, out_nodes diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_sample_neighbors.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_sample_neighbors.py new file mode 100644 index 0000000000000000000000000000000000000000..980071b384b3f73c5d8858cd3fbb5a8c3bd50ed8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_sample_neighbors.py @@ -0,0 +1,183 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops +import paddle.utils.deprecated as deprecated + + +@deprecated( + since="2.4.0", + update_to="paddle.geometric.sample_neighbors", + level=1, + reason="paddle.incubate.graph_sample_neighbors will be removed in future", +) +def graph_sample_neighbors( + row, + colptr, + input_nodes, + eids=None, + perm_buffer=None, + sample_size=-1, + return_eids=False, + flag_perm_buffer=False, + name=None, +): + """ + + Graph Sample Neighbors API. + + This API is mainly used in Graph Learning domain, and the main purpose is to + provide high performance of graph sampling method. For example, we get the + CSC(Compressed Sparse Column) format of the input graph edges as `row` and + `colptr`, so as to convert graph data into a suitable format for sampling. + `input_nodes` means the nodes we need to sample neighbors, and `sample_sizes` + means the number of neighbors and number of layers we want to sample. + + Besides, we support fisher-yates sampling in GPU version. + + Args: + row (Tensor): One of the components of the CSC format of the input graph, and + the shape should be [num_edges, 1] or [num_edges]. The available + data type is int32, int64. + colptr (Tensor): One of the components of the CSC format of the input graph, + and the shape should be [num_nodes + 1, 1] or [num_nodes + 1]. + The data type should be the same with `row`. + input_nodes (Tensor): The input nodes we need to sample neighbors for, and the + data type should be the same with `row`. + eids (Tensor): The eid information of the input graph. If return_eids is True, + then `eids` should not be None. The data type should be the + same with `row`. Default is None. + perm_buffer (Tensor): Permutation buffer for fisher-yates sampling. If `flag_perm_buffer` + is True, then `perm_buffer` should not be None. The data type should + be the same with `row`. Default is None. + sample_size (int): The number of neighbors we need to sample. Default value is + -1, which means returning all the neighbors of the input nodes. + return_eids (bool): Whether to return eid information of sample edges. Default is False. + flag_perm_buffer (bool): Using the permutation for fisher-yates sampling in GPU. Default + value is false, means not using it. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out_neighbors (Tensor), The sample neighbors of the input nodes. + - out_count (Tensor), The number of sampling neighbors of each input node, and the shape should be the same with `input_nodes`. + - out_eids (Tensor), If `return_eids` is True, we will return the eid information of the sample edges. + + Examples: + .. code-block:: python + + import paddle + # edges: (3, 0), (7, 0), (0, 1), (9, 1), (1, 2), (4, 3), (2, 4), + # (9, 5), (3, 5), (9, 6), (1, 6), (9, 8), (7, 8) + row = [3, 7, 0, 9, 1, 4, 2, 9, 3, 9, 1, 9, 7] + colptr = [0, 2, 4, 5, 6, 7, 9, 11, 11, 13, 13] + nodes = [0, 8, 1, 2] + sample_size = 2 + row = paddle.to_tensor(row, dtype="int64") + colptr = paddle.to_tensor(colptr, dtype="int64") + nodes = paddle.to_tensor(nodes, dtype="int64") + out_neighbors, out_count = \ + paddle.incubate.graph_sample_neighbors(row, colptr, nodes, + sample_size=sample_size) + + """ + + if return_eids: + if eids is None: + raise ValueError( + f"`eids` should not be None if `return_eids` is True." + ) + + if flag_perm_buffer: + if perm_buffer is None: + raise ValueError( + f"`perm_buffer` should not be None if `flag_perm_buffer`" + "is True." + ) + + if _non_static_mode(): + ( + out_neighbors, + out_count, + out_eids, + ) = _legacy_C_ops.graph_sample_neighbors( + row, + colptr, + input_nodes, + eids, + perm_buffer, + "sample_size", + sample_size, + "return_eids", + return_eids, + "flag_perm_buffer", + flag_perm_buffer, + ) + if return_eids: + return out_neighbors, out_count, out_eids + return out_neighbors, out_count + + check_variable_and_dtype( + row, "Row", ("int32", "int64"), "graph_sample_neighbors" + ) + check_variable_and_dtype( + colptr, "Col_Ptr", ("int32", "int64"), "graph_sample_neighbors" + ) + check_variable_and_dtype( + input_nodes, "X", ("int32", "int64"), "graph_sample_neighbors" + ) + if return_eids: + check_variable_and_dtype( + eids, "Eids", ("int32", "int64"), "graph_sample_neighbors" + ) + if flag_perm_buffer: + check_variable_and_dtype( + perm_buffer, + "Perm_Buffer", + ("int32", "int64"), + "graph_sample_neighbors", + ) + + helper = LayerHelper("graph_sample_neighbors", **locals()) + out_neighbors = helper.create_variable_for_type_inference(dtype=row.dtype) + out_count = helper.create_variable_for_type_inference(dtype=row.dtype) + out_eids = helper.create_variable_for_type_inference(dtype=row.dtype) + helper.append_op( + type="graph_sample_neighbors", + inputs={ + "Row": row, + "Col_Ptr": colptr, + "X": input_nodes, + "Eids": eids if return_eids else None, + "Perm_Buffer": perm_buffer if flag_perm_buffer else None, + }, + outputs={ + "Out": out_neighbors, + "Out_Count": out_count, + "Out_Eids": out_eids, + }, + attrs={ + "sample_size": sample_size, + "return_eids": return_eids, + "flag_perm_buffer": flag_perm_buffer, + }, + ) + if return_eids: + return out_neighbors, out_count, out_eids + return out_neighbors, out_count diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_send_recv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_send_recv.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b01f9aad2e6bd510b2f0a4bc3bd6f1cac510f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/graph_send_recv.py @@ -0,0 +1,201 @@ +# Copyright (c) 2021 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. + +import numpy as np +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode, _in_legacy_dygraph, in_dygraph_mode +from paddle.fluid.framework import Variable +from paddle.fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype, convert_dtype +from paddle.fluid.layers.tensor import cast +from paddle import _C_ops, _legacy_C_ops +import paddle.utils.deprecated as deprecated + + +@deprecated( + since="2.4.0", + update_to="paddle.geometric.send_u_recv", + level=1, + reason="graph_send_recv in paddle.incubate will be removed in future") +def graph_send_recv(x, + src_index, + dst_index, + pool_type="sum", + out_size=None, + name=None): + r""" + + Graph Learning Send_Recv combine operator. + + This operator is mainly used in Graph Learning domain, and the main purpose is to reduce intermediate memory + consumption in the process of message passing. Take `x` as the input tensor, we first use `src_index` + to gather the corresponding data, and then use `dst_index` to update the corresponding position of output tensor + in different pooling types, like sum, mean, max, or min. Besides, we can set `out_size` to get necessary output shape. + + .. code-block:: text + + Given: + + X = [[0, 2, 3], + [1, 4, 5], + [2, 6, 7]] + + src_index = [0, 1, 2, 0] + + dst_index = [1, 2, 1, 0] + + pool_type = "sum" + + out_size = None + + Then: + + Out = [[0, 2, 3], + [2, 8, 10], + [1, 4, 5]] + + Args: + x (Tensor): The input tensor, and the available data type is float32, float64, int32, int64. + src_index (Tensor): An 1-D tensor, and the available data type is int32, int64. + dst_index (Tensor): An 1-D tensor, and should have the same shape as `src_index`. + The available data type is int32, int64. + pool_type (str): The pooling types of graph_send_recv, including `sum`, `mean`, `max`, `min`. + Default value is `sum`. + out_size (int|Tensor|None): We can set `out_size` to get necessary output shape. If not set or + out_size is smaller or equal to 0, then this input will not be used. + Otherwise, `out_size` should be equal with or larger than + max(dst_index) + 1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): The output tensor, should have the same shape and same dtype as input tensor `x`. + If `out_size` is set correctly, then it should have the same shape as `x` except + the 0th dimension. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [1, 2], [2, 1], [0, 0]], dtype="int32") + src_index = indexes[:, 0] + dst_index = indexes[:, 1] + out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum") + # Outputs: [[0., 2., 3.], [2., 8., 10.], [1., 4., 5.]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index = indexes[:, 0] + dst_index = indexes[:, 1] + out_size = paddle.max(dst_index) + 1 + out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum", out_size=out_size) + # Outputs: [[0., 2., 3.], [[2., 8., 10.]]] + + x = paddle.to_tensor([[0, 2, 3], [1, 4, 5], [2, 6, 7]], dtype="float32") + indexes = paddle.to_tensor([[0, 1], [2, 1], [0, 0]], dtype="int32") + src_index = indexes[:, 0] + dst_index = indexes[:, 1] + out = paddle.incubate.graph_send_recv(x, src_index, dst_index, pool_type="sum") + # Outputs: [[0., 2., 3.], [2., 8., 10.], [0., 0., 0.]] + + """ + + if pool_type not in ["sum", "mean", "max", "min"]: + raise ValueError( + "pool_type should be `sum`, `mean`, `max` or `min`, but received %s" + % pool_type) + + # TODO(daisiming): Should we add judgement for out_size: max(dst_index) + 1. + + if _in_legacy_dygraph(): + out_size = convert_out_size_to_list(out_size) + out, tmp = _legacy_C_ops.graph_send_recv(x, src_index, dst_index, + None, 'reduce_op', + pool_type.upper(), 'out_size', + out_size) + return out + if in_dygraph_mode(): + out_size = convert_out_size_to_list(out_size) + return _C_ops.graph_send_recv(x, src_index, dst_index, + pool_type.upper(), out_size) + + check_variable_and_dtype(x, "X", ("float32", "float64", "int32", "int64"), + "graph_send_recv") + check_variable_and_dtype(src_index, "Src_index", ("int32", "int64"), + "graph_send_recv") + check_variable_and_dtype(dst_index, "Dst_index", ("int32", "int64"), + "graph_send_recv") + if out_size: + check_type(out_size, 'out_size', (int, np.int32, np.int64, Variable), + 'graph_send_recv') + if isinstance(out_size, Variable): + check_dtype(out_size.dtype, 'out_size', ['int32', 'int64'], + 'graph_send_recv') + + helper = LayerHelper("graph_send_recv", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + dst_count = helper.create_variable_for_type_inference(dtype="int32", + stop_gradient=True) + + inputs = {"X": x, "Src_index": src_index, "Dst_index": dst_index} + attrs = {"reduce_op": pool_type.upper()} + get_out_size_tensor_inputs(inputs=inputs, + attrs=attrs, + out_size=out_size, + op_type='graph_send_recv') + + helper.append_op(type="graph_send_recv", + inputs=inputs, + outputs={ + "Out": out, + "Dst_count": dst_count + }, + attrs=attrs) + return out + + +def convert_out_size_to_list(out_size): + """ + Convert out_size(int, np.int32, np.int64, Variable) to list + in imperative mode. + """ + if out_size is None: + out_size = [0] + elif isinstance(out_size, (int, np.int32, np.int64)): + out_size = [out_size] + else: + out_size = [out_size.numpy().astype(int)[0]] + return out_size + + +def get_out_size_tensor_inputs(inputs, attrs, out_size, op_type): + """ + Convert out_size(int, np.int32, np.int64, Variable) to inputs + and attrs in static mode. + """ + if out_size is None: + attrs['out_size'] = [0] + elif isinstance(out_size, (int, np.int32, np.int64)): + attrs['out_size'] = [out_size] + elif isinstance(out_size, Variable): + out_size.stop_gradient = True + check_dtype(out_size.dtype, 'out_size', ['int32', 'int64'], op_type, + '(When type of out_size in' + op_type + ' is Variable.)') + if (convert_dtype(out_size.dtype) == 'int64'): + out_size = cast(out_size, 'int32') + inputs["Out_size"] = out_size + else: + raise TypeError("Out_size only supports Variable or int.") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/resnet_unit.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/resnet_unit.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4cb4d3bde90c6a9438f8fd949afdcce2598f02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/resnet_unit.py @@ -0,0 +1,279 @@ +# Copyright (c) 2021 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. + +import copy +import collections +import itertools +import six +import math +import sys +import warnings +from functools import partial, reduce + +import numpy as np +import paddle +import paddle.fluid as fluid +from paddle import framework +from paddle.device import get_device, get_cudnn_version +from paddle.nn import initializer as I +from paddle.nn import Layer, LayerList +from paddle.fluid.layers import utils +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.layers.utils import map_structure, flatten, pack_sequence_as +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid.param_attr import ParamAttr +from paddle import _C_ops, _legacy_C_ops + + +def resnet_unit(x, filter_x, scale_x, bias_x, mean_x, var_x, z, filter_z, + scale_z, bias_z, mean_z, var_z, stride, stride_z, padding, + dilation, groups, momentum, eps, data_format, fuse_add, + has_shortcut, use_global_stats, is_test, act): + + helper = LayerHelper('resnet_unit', **locals()) + bn_param_dtype = fluid.core.VarDesc.VarType.FP32 + bit_mask_dtype = fluid.core.VarDesc.VarType.INT32 + out = helper.create_variable_for_type_inference(x.dtype) + bit_mask = helper.create_variable_for_type_inference(dtype=bit_mask_dtype, + stop_gradient=True) + # intermediate_out for x + conv_x = helper.create_variable_for_type_inference(dtype=x.dtype, + stop_gradient=True) + saved_mean_x = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) + saved_invstd_x = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) + running_mean_x = mean_x + running_var_x = var_x + # intermediate_out for z + conv_z = helper.create_variable_for_type_inference(dtype=x.dtype, + stop_gradient=True) + saved_mean_z = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) + saved_invstd_z = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) + running_mean_z = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) if mean_z is None else mean_z + running_var_z = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True) if var_z is None else var_z + + inputs = { + 'X': x, + 'FilterX': filter_x, + 'ScaleX': scale_x, + 'BiasX': bias_x, + 'MeanX': mean_x, + 'VarX': var_x, + 'Z': z, + 'FilterZ': filter_z, + 'ScaleZ': scale_z, + 'BiasZ': bias_z, + 'MeanZ': mean_z, + 'VarZ': var_z + } + + attrs = { + 'stride': stride, + 'stride_z': stride_z, + 'padding': padding, + 'dilation': dilation, + 'group': groups, + 'momentum': momentum, + 'epsilon': eps, + 'data_format': data_format, + 'fuse_add': fuse_add, + 'has_shortcut': has_shortcut, + 'use_global_stats': use_global_stats, + 'is_test': is_test, + 'act_type': act + } + + outputs = { + 'Y': out, + 'BitMask': bit_mask, + 'ConvX': conv_x, + 'SavedMeanX': saved_mean_x, + 'SavedInvstdX': saved_invstd_x, + 'RunningMeanX': running_mean_x, + 'RunningVarX': running_var_x, + 'ConvZ': conv_z, + 'SavedMeanZ': saved_mean_z, + 'SavedInvstdZ': saved_invstd_z, + 'RunningMeanZ': running_mean_z, + 'RunningVarZ': running_var_z, + } + + helper.append_op(type='resnet_unit', + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return out + + +class ResNetUnit(Layer): + r""" + ******Temporary version******. + ResNetUnit is designed for optimize the performence by using cudnnv8 API. + """ + + def __init__(self, + num_channels_x, + num_filters, + filter_size, + stride=1, + momentum=0.9, + eps=1e-5, + data_format='NHWC', + act='relu', + fuse_add=False, + has_shortcut=False, + use_global_stats=False, + is_test=False, + filter_x_attr=None, + scale_x_attr=None, + bias_x_attr=None, + moving_mean_x_name=None, + moving_var_x_name=None, + num_channels_z=1, + stride_z=1, + filter_z_attr=None, + scale_z_attr=None, + bias_z_attr=None, + moving_mean_z_name=None, + moving_var_z_name=None): + super(ResNetUnit, self).__init__() + self._stride = stride + self._stride_z = stride_z + self._dilation = 1 + self._kernel_size = utils.convert_to_list(filter_size, 2, 'kernel_size') + self._padding = (filter_size - 1) // 2 + self._groups = 1 + self._momentum = momentum + self._eps = eps + self._data_format = data_format + self._act = act + self._fuse_add = fuse_add + self._has_shortcut = has_shortcut + self._use_global_stats = use_global_stats + self._is_test = is_test + + # check format + valid_format = {'NHWC', 'NCHW'} + if data_format not in valid_format: + raise ValueError( + "conv_format must be one of {}, but got conv_format='{}'". + format(valid_format, data_format)) + + def _get_default_param_initializer(channels): + filter_elem_num = np.prod(self._kernel_size) * channels + std = (2.0 / filter_elem_num)**0.5 + return I.Normal(0.0, std) + + is_nchw = (data_format == 'NCHW') + # initial filter + bn_param_dtype = fluid.core.VarDesc.VarType.FP32 + if not is_nchw: + bn_param_shape = [1, 1, 1, num_filters] + filter_x_shape = [ + num_filters, filter_size, filter_size, num_channels_x + ] + filter_z_shape = [ + num_filters, filter_size, filter_size, num_channels_z + ] + else: + bn_param_shape = [1, num_filters, 1, 1] + filter_x_shape = [ + num_filters, num_channels_x, filter_size, filter_size + ] + filter_z_shape = [ + num_filters, num_channels_z, filter_size, filter_size + ] + + self.filter_x = self.create_parameter( + shape=filter_x_shape, + attr=filter_x_attr, + default_initializer=_get_default_param_initializer(num_channels_x)) + self.scale_x = self.create_parameter( + shape=bn_param_shape, + attr=scale_x_attr, + dtype=bn_param_dtype, + default_initializer=I.Constant(1.0)) + self.bias_x = self.create_parameter(shape=bn_param_shape, + attr=bias_x_attr, + dtype=bn_param_dtype, + is_bias=True) + self.mean_x = self.create_parameter(attr=ParamAttr( + name=moving_mean_x_name, + initializer=I.Constant(0.0), + trainable=False), + shape=bn_param_shape, + dtype=bn_param_dtype) + self.mean_x.stop_gradient = True + self.var_x = self.create_parameter(attr=ParamAttr( + name=moving_var_x_name, + initializer=I.Constant(1.0), + trainable=False), + shape=bn_param_shape, + dtype=bn_param_dtype) + self.var_x.stop_gradient = True + if has_shortcut: + self.filter_z = self.create_parameter( + shape=filter_z_shape, + attr=filter_z_attr, + default_initializer=_get_default_param_initializer( + num_channels_z)) + self.scale_z = self.create_parameter( + shape=bn_param_shape, + attr=scale_z_attr, + dtype=bn_param_dtype, + default_initializer=I.Constant(1.0)) + self.bias_z = self.create_parameter(shape=bn_param_shape, + attr=bias_z_attr, + dtype=bn_param_dtype, + is_bias=True) + self.mean_z = self.create_parameter(attr=ParamAttr( + name=moving_mean_z_name, + initializer=I.Constant(0.0), + trainable=False), + shape=bn_param_shape, + dtype=bn_param_dtype) + self.mean_z.stop_gradient = True + self.var_z = self.create_parameter(attr=ParamAttr( + name=moving_var_z_name, + initializer=I.Constant(1.0), + trainable=False), + shape=bn_param_shape, + dtype=bn_param_dtype) + self.var_z.stop_gradient = True + else: + self.filter_z = None + self.scale_z = None + self.bias_z = None + self.mean_z = None + self.var_z = None + + def forward(self, x, z=None): + if self._fuse_add and z is None: + raise ValueError("z can not be None") + + out = resnet_unit(x, self.filter_x, self.scale_x, self.bias_x, + self.mean_x, self.var_x, z, self.filter_z, + self.scale_z, self.bias_z, self.mean_z, self.var_z, + self._stride, self._stride_z, self._padding, + self._dilation, self._groups, self._momentum, + self._eps, self._data_format, self._fuse_add, + self._has_shortcut, self._use_global_stats, + self._is_test, self._act) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse.py new file mode 100644 index 0000000000000000000000000000000000000000..b02903d87fe6a3b6a875110cd8c3c3af942d18a5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse.py @@ -0,0 +1,72 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function + +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops + + +def softmax_mask_fuse(x, mask, name=None): + """ + Do a masked softmax on x. + + This is designed for speeding up Transformer structure. + Used for reducing operation such as: tmp = x + mask, out = softmax(tmp). + The equation is: + + .. math:: + out = softmax(x + mask) + + **Note**: + This API only supports GPU. + + Args: + x (4-D Tensor): The input tensor, should be in 4D shape, it's data type should be float16, float32. + The fourth dimension of x must be larger or equal to 32 and less then 8192. + mask (4-D Tensor): The input tensor, should be in 4D shape, it's data type should be float16, float32. + The second dimension of mask must be 1, and other dimensions must be same with x. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + 4-D Tensor. A location into which the result is stored. It’s dimension is 4D. Has same shape with x. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate as incubate + + x = paddle.rand([2, 8, 8, 32]) + mask = paddle.rand([2, 1, 8, 32]) + + rst = incubate.softmax_mask_fuse(x, mask) + # [[[[0.02404429, 0.04658398, 0.02746007, ..., 0.01489375, 0.02397441, 0.02851614] ... ]]] + """ + if _non_static_mode(): + out = _legacy_C_ops.fused_softmax_mask(x, mask) + return out + helper = LayerHelper('fused_softmax_mask', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='fused_softmax_mask', + inputs={ + 'X': [x], + 'Mask': [mask] + }, + outputs={'Out': [out]}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse_upper_triangle.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse_upper_triangle.py new file mode 100644 index 0000000000000000000000000000000000000000..e287df1e710c4a97e5134bc9f034261cb3be4e1b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/operators/softmax_mask_fuse_upper_triangle.py @@ -0,0 +1,72 @@ +# Copyright (c) 2021 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. + +from __future__ import print_function + +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.framework import _non_static_mode +from paddle.fluid import core +from paddle import _C_ops, _legacy_C_ops + + +def softmax_mask_fuse_upper_triangle(x): + """ + Do a masked softmax on x, which will always mask upper triangle part of x. + + This is designed for speeding up GPT kind Transformer structure. + Used for reducing operation such as: tmp = x + mask, out = softmax(tmp), where the mask is + always be an upper triangle matrix. + The equation is: + + .. math:: + out = softmax(LowerTriangular(x)) + + **Note**: + This API only supports GPU. + + Args: + x (4-D Tensor): The input tensor, should be in 4D shape, it's data type should be float16, float32 + The fourth dimension of x must be larger or equal to 32 and less then 8192. + The third dimension of x must be same with the fourth dimension of x. + + Returns: + 4-D Tensor. A location into which the result is stored. It’s dimension is 4D. Has same dimension with x. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.incubate as incubate + + x = paddle.rand((1, 1, 32, 32)) + + rst = incubate.softmax_mask_fuse_upper_triangle(x) + # [[[[1. , 0. , 0. , ..., 0., 0., 0.], + # [0.45324376, 0.54675621, 0. , ..., 0., 0., 0.], + # [0.32674268, 0.28156221, 0.39169508, ..., 0., 0., 0.] + # ... ]]] + """ + if _non_static_mode(): + out = _legacy_C_ops.fused_softmax_mask_upper_triangle(x) + return out + + helper = LayerHelper('fused_softmax_mask_upper_triangle', **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type='fused_softmax_mask_upper_triangle', + inputs={'X': [x]}, + outputs={'Out': [out]}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c24f85896c93a51abd1ee0150cd2f07f6f48bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/__init__.py @@ -0,0 +1,20 @@ +# 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. + +from .lookahead import LookAhead # noqa: F401 +from .modelaverage import ModelAverage # noqa: F401 +from .distributed_fused_lamb import DistributedFusedLamb # noqa: F401 +from . import functional # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/distributed_fused_lamb.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/distributed_fused_lamb.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3df92be5ebeb686990c7279487d02871de148a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/distributed_fused_lamb.py @@ -0,0 +1,455 @@ +# Copyright (c) 2021 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. + +import os +import paddle +from paddle.fluid import framework, core, layers, unique_name +from paddle.fluid.framework import Variable +from paddle.fluid.clip import ClipGradByGlobalNorm +from paddle.fluid.initializer import Constant +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.optimizer import Optimizer +from paddle.distributed.collective import new_group +from paddle.fluid.executor import global_scope +from paddle.fluid.framework import name_scope +from paddle.fluid import core, unique_name +import numpy as np + + +def init_communicator(block, rank, ranks, ring_id): + eps = os.environ['PADDLE_TRAINER_ENDPOINTS'] + eps = [ep.strip() for ep in eps.split(",") if ep.strip()] + cur_ep = eps[rank] + other_eps = [eps[r] for r in ranks if r != rank] + + local_rank = ranks.index(rank) + comm_var_name = unique_name.generate('comm_id') + comm_id_var = block.create_var(name=comm_var_name, + persistable=True, + type=core.VarDesc.VarType.RAW) + block.append_op(type='c_gen_nccl_id', + inputs={}, + outputs={'Out': comm_id_var}, + attrs={ + 'rank': local_rank, + 'endpoint': cur_ep, + 'other_endpoints': other_eps, + 'ring_id': ring_id + }) + block.append_op(type='c_comm_init', + inputs={'X': comm_id_var}, + outputs={}, + attrs={ + 'nranks': len(ranks), + 'rank': local_rank, + 'ring_id': ring_id + }) + tmp_var = block.create_var(name=unique_name.generate('tmp')) + block.append_op(type='fill_constant', + outputs={'Out': tmp_var}, + attrs={'value': 1}) + block.append_op(type='c_allreduce_sum', + inputs={'X': tmp_var}, + outputs={'Out': tmp_var}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True + }) + block.append_op(type='c_sync_calc_stream', + inputs={'X': tmp_var}, + outputs={'Out': tmp_var}) + return ring_id + + +def broadcast_parameters(block, parameters, ring_id): + for p in parameters: + block.append_op(type='c_broadcast', + inputs={'X': p}, + outputs={'Out': p}, + attrs={ + 'ring_id': ring_id, + 'use_calc_stream': True + }) + + +class DistributedFusedLamb(Optimizer): + + def __init__(self, + learning_rate=0.001, + lamb_weight_decay=0.01, + beta1=0.9, + beta2=0.999, + epsilon=1e-6, + parameters=None, + grad_clip=None, + exclude_from_weight_decay_fn=None, + clip_after_allreduce=True, + is_grad_scaled_by_nranks=True, + alignment=128, + use_master_param_norm=True, + gradient_accumulation_steps=1, + use_master_acc_grad=True, + nproc_per_node=None, + use_hierarchical_allreduce=False, + name=None): + assert not framework._non_static_mode( + ), "DistributedFusedLamb does not support dygraph mode" + super(DistributedFusedLamb, self).__init__(learning_rate=learning_rate, + grad_clip=None, + name=name) + + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._weight_decay = lamb_weight_decay if lamb_weight_decay is not None else 0.0 + if grad_clip is not None: + assert isinstance( + grad_clip, ClipGradByGlobalNorm + ), "Only ClipGradByGlobalNorm is supported in DistributedFusedLamb" + max_global_grad_norm = grad_clip.clip_norm + else: + max_global_grad_norm = -1.0 + self._max_global_grad_norm = max_global_grad_norm + self._alignment = alignment if alignment is not None else -1 + self._clip_after_allreduce = clip_after_allreduce + self._is_grad_scaled_by_nranks = is_grad_scaled_by_nranks + self._exclude_from_weight_decay_fn = exclude_from_weight_decay_fn + self._scale = None + self._use_master_param_norm = use_master_param_norm + self._gradient_accumulation_steps = gradient_accumulation_steps + self._use_master_acc_grad = use_master_acc_grad + self._nproc_per_node = nproc_per_node + self._use_hierarchical_allreduce = use_hierarchical_allreduce + assert self._gradient_accumulation_steps >= 1 + + self.helper = LayerHelper('distributed_fused_lamb') + self._supports_check_nan_inf = True # very import flag for AMP + + main_block = self.helper.main_program.global_block() + self._found_inf = main_block.create_var( + name=unique_name.generate('found_inf'), + shape=[1], + dtype=core.VarDesc.VarType.BOOL) + self._step = None + + if self._gradient_accumulation_steps > 1: + self._stop_update = main_block.create_var( + name=unique_name.generate('stop_update'), + shape=[1], + dtype=core.VarDesc.VarType.BOOL) + else: + self._stop_update = None + + self._param_to_master_param = {} + + def _get_stop_update_var(self): + return self._stop_update if self._stop_update is not None else False + + def _set_step(self, step): + self._step = step + + def _get_or_create_step(self): + if self._step is None: + self._step = self._create_persistable_var('step', dtype='int64') + return self._step + + def _set_scale(self, scale): + assert scale is not None + if not isinstance(scale, Variable): + scale = self._create_scale_from_constant(scale) + self._scale = scale + + def _create_scale_from_constant(self, value): + name = unique_name.generate('global_scale') + return layers.create_global_var(name=name, + shape=[1], + dtype='float32', + value=float(value), + persistable=True) + + def _get_or_create_scale(self): + if self._scale is None: + self._scale = self._create_scale_from_constant(1.0) + return self._scale + + def _create_persistable_var(self, name=None, shape=[-1], dtype='float32'): + startup_block = self.helper.startup_program.global_block() + if name is not None: + name = unique_name.generate(name) + startup_var = startup_block.create_var(name=name, + shape=shape, + dtype=dtype, + persistable=True, + stop_gradient=True) + main_block = self.helper.main_program.global_block() + main_var = main_block.create_var(name=startup_var.name, + shape=startup_var.shape, + dtype=startup_var.dtype, + persistable=True, + stop_gradient=True) + return main_var + + def _get_parameter(self, name, scope=None): + if scope is None: + scope = global_scope() + + master_param = self._param_to_master_param.get(name) + assert master_param is not None + + master_param_t = scope.find_var(master_param).get_tensor() + assert master_param_t._dtype() == core.VarDesc.VarType.FP32 + + param_t = scope.find_var(name).get_tensor() + if param_t._dtype() == core.VarDesc.VarType.FP32: + assert param_t._ptr() == master_param_t._ptr() + return param_t, None + else: + assert param_t._dtype() == core.VarDesc.VarType.FP16 + assert param_t.shape() == master_param_t.shape() + return param_t, master_param_t + + def apply_optimize(self, params_grads): + self.apply_gradients(params_grads) + + def apply_gradients(self, params_grads): + flattened = [] + for p, g in params_grads: + flattened.extend([p, g]) + with flattened[0].block.program._optimized_guard(flattened), name_scope( + "optimizer"): + self._apply_gradients_impl(params_grads) + + def _apply_gradients_impl(self, params_grads): + for p, g in params_grads: + assert g.type == core.VarDesc.VarType.LOD_TENSOR, "Only support dense gradient" + g.persistable = True # the gradient must be persistable for fusion + + fp32_fused_param = self._create_persistable_var('fp32_fused_param') + fp32_fused_grad = self._create_persistable_var('fp32_fused_grad') + fp16_fused_param = self._create_persistable_var('fp16_fused_param', + dtype='float16') + fp16_fused_grad = self._create_persistable_var('fp16_fused_grad', + dtype='float16') + + master_params = [] + for p, g in params_grads: + master_p = self._create_persistable_var('master_weight') + self._param_to_master_param[p.name] = master_p.name + master_params.append(master_p) + + moment1 = self._create_persistable_var('moment1') + moment1.is_distributed = True + moment2 = self._create_persistable_var('moment2') + moment2.is_distributed = True + beta1pow = self._create_persistable_var('beta1pow') + beta2pow = self._create_persistable_var('beta2pow') + + param_info = self._create_persistable_var('param_info', dtype='int32') + param_info.is_distributed = True + + fused_offsets = self._create_persistable_var('fused_offsets', + dtype='int32') + + fp32_partial_fused_offsets = self._create_persistable_var( + 'fp32_partial_fused_offsets', dtype='int32') + fp32_partial_fused_offsets.is_distributed = True + + fp16_partial_fused_offsets = self._create_persistable_var( + 'fp16_partial_fused_offsets', dtype='int32') + fp16_partial_fused_offsets.is_distributed = True + + param_order = self._create_persistable_var('param_order', dtype='int32') + param_order.is_distributed = True + + if self._gradient_accumulation_steps > 1: + fp32_acc_fused_grad = [ + self._create_persistable_var('fp32_acc_fused_grad') + ] + fp16_acc_fused_grad = [ + self._create_persistable_var('fp16_acc_fused_grad', + dtype='float16') + ] + acc_step = [self._create_persistable_var('acc_step', dtype='int64')] + else: + fp32_acc_fused_grad = [] + fp16_acc_fused_grad = [] + acc_step = [] + + step = self._get_or_create_step() + + rank = paddle.distributed.get_rank() + nranks = paddle.distributed.get_world_size() + if self._nproc_per_node is None: + nproc_per_node = nranks + else: + nproc_per_node = self._nproc_per_node + assert nranks % nproc_per_node == 0, "nranks should be exactly divided by nproc_per_node" + + shard_inside_node = (nranks > nproc_per_node) + local_rank = rank % nproc_per_node + node_id = int(rank / nproc_per_node) + node_num = int(nranks / nproc_per_node) + ring_ids = [] + startup_block = self.helper.startup_program.global_block() + if nranks > 1: + ring_id = init_communicator(startup_block, rank, + list(range(nranks)), 0) + ring_ids.append(ring_id) + + use_hierarchical_allreduce = False + if node_num > 1 and len(ring_ids) <= 1 and shard_inside_node: + local_group_ranks = list( + range(node_id * nproc_per_node, (node_id + 1) * nproc_per_node)) + ring_id = init_communicator(startup_block, rank, local_group_ranks, + 1) + ring_ids.append(ring_id) + + if self._use_hierarchical_allreduce and nranks > nproc_per_node: + use_hierarchical_allreduce = True + outer_group_ranks = list( + range(rank % nproc_per_node, nranks, nproc_per_node)) + ring_id = init_communicator(startup_block, rank, + outer_group_ranks, ring_ids[-1] + 1) + ring_ids.append(ring_id) + + scale = self._get_or_create_scale() + + params = [p for p, _ in params_grads] + grads = [g for _, g in params_grads] + apply_weight_decay = [1] * len(params) + if self._exclude_from_weight_decay_fn is not None: + for i, p in enumerate(params): + if self._exclude_from_weight_decay_fn(p): + apply_weight_decay[i] = 0 + + for g in grads: + startup_block.create_var(name=g.name, + type=g.type, + dtype=g.dtype, + persistable=g.persistable, + shape=g.shape) + + if nranks > 1: + broadcast_parameters(startup_block, params, ring_ids[0]) + + startup_block.append_op( + type='distributed_fused_lamb_init', + inputs={ + 'Param': params, + 'Grad': grads, + }, + outputs={ + 'FP32FusedParam': [fp32_fused_param], + 'FP32FusedGrad': [fp32_fused_grad], + 'FP16FusedParam': [fp16_fused_param], + 'FP16FusedGrad': [fp16_fused_grad], + 'Moment1': [moment1], + 'Moment2': [moment2], + 'Beta1Pow': [beta1pow], + 'Beta2Pow': [beta2pow], + 'GlobalScale': [scale], + 'ParamInfo': [param_info], + 'ParamOut': params, + 'MasterParamOut': master_params, + 'GradOut': grads, + 'FP32ShardFusedParamOffsets': [fp32_partial_fused_offsets], + 'FP16ShardFusedParamOffsets': [fp16_partial_fused_offsets], + 'FusedParamOffsets': [fused_offsets], + 'ParamOrder': [param_order], + 'Step': [step], + }, + attrs={ + 'alignment': self._alignment, + 'rank': local_rank if shard_inside_node else rank, + 'nranks': nproc_per_node if shard_inside_node else nranks, + 'apply_weight_decay': apply_weight_decay, + 'moment1': 0.0, + 'moment2': 0.0, + 'beta1': self._beta1, + 'beta2': self._beta2, + }) + + main_block = self.helper.main_program.global_block() + self._create_global_learning_rate() + lr = None + for p_g in params_grads: + if lr is None: + lr = self._create_param_lr(p_g) + else: + new_lr = self._create_param_lr(p_g) + assert id(lr) == id( + new_lr + ), "The learning rate for each parameter should be the same" + assert lr is not None + + lamb_op = main_block.append_op( + type='distributed_fused_lamb', + inputs={ + 'FP32FusedParam': [fp32_fused_param], + 'FP32FusedGrad': [fp32_fused_grad], + 'FP16FusedParam': [fp16_fused_param], + 'FP16FusedGrad': [fp16_fused_grad], + 'LearningRate': [lr], + 'Moment1': [moment1], + 'Moment2': [moment2], + 'Beta1Pow': [beta1pow], + 'Beta2Pow': [beta2pow], + 'GlobalScale': [scale], + 'ParamInfo': [param_info], + 'Param': params, + 'Grad': grads, + 'FusedParamOffsets': [fused_offsets], + 'FP32ShardFusedParamOffsets': [fp32_partial_fused_offsets], + 'FP16ShardFusedParamOffsets': [fp16_partial_fused_offsets], + 'ParamOrder': [param_order], + }, + outputs={ + 'FP32FusedParamOut': [fp32_fused_param], + 'FP16FusedParamOut': [fp16_fused_param], + 'Moment1Out': [moment1], + 'Moment2Out': [moment2], + 'Beta1PowOut': [beta1pow], + 'Beta2PowOut': [beta2pow], + 'ParamOut': + params, + 'GradOut': + grads, + 'FoundInf': [self._found_inf], + 'FP32AccFusedGrad': + fp32_acc_fused_grad, + 'FP16AccFusedGrad': + fp16_acc_fused_grad, + 'AccStep': + acc_step, + 'StopUpdate': + self._stop_update if self._stop_update is not None else [], + 'Step': [step], + }, + attrs={ + 'weight_decay': self._weight_decay, + 'beta1': self._beta1, + 'beta2': self._beta2, + 'epsilon': self._epsilon, + 'max_global_grad_norm': self._max_global_grad_norm, + 'clip_after_allreduce': self._clip_after_allreduce, + 'rank': rank, + 'nranks': nranks, + 'ring_id': ring_ids, + 'use_master_param_norm': self._use_master_param_norm, + 'is_grad_scaled_by_nranks': self._is_grad_scaled_by_nranks, + 'acc_steps': self._gradient_accumulation_steps, + 'use_master_acc_grad': self._use_master_acc_grad, + 'use_hierarchical_allreduce': use_hierarchical_allreduce, + }) + return [lamb_op] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fc863a923d88ffc6d1e68d45d7a7dff4613a9e05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) 2021 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. + +from .bfgs import minimize_bfgs # noqa: F401 +from .lbfgs import minimize_lbfgs # noqa: F401 + +__all__ = ['minimize_bfgs', 'minimize_lbfgs'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/bfgs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/bfgs.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf7b71c65aed64aabf4c19fd9a76ed6f10a5316 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/bfgs.py @@ -0,0 +1,179 @@ +# Copyright (c) 2022 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. + +import numpy as np + +from .line_search import strong_wolfe +from .utils import _value_and_gradient, check_input_type, check_initial_inverse_hessian_estimate + +import paddle + + +def minimize_bfgs(objective_func, + initial_position, + max_iters=50, + tolerance_grad=1e-7, + tolerance_change=1e-9, + initial_inverse_hessian_estimate=None, + line_search_fn='strong_wolfe', + max_line_search_iters=50, + initial_step_length=1.0, + dtype='float32', + name=None): + r""" + Minimizes a differentiable function `func` using the BFGS method. + The BFGS is a quasi-Newton method for solving an unconstrained optimization problem over a differentiable function. + Closely related is the Newton method for minimization. Consider the iterate update formula: + + .. math:: + x_{k+1} = x_{k} + H_k \nabla{f_k} + + If :math:`H_k` is the inverse Hessian of :math:`f` at :math:`x_k`, then it's the Newton method. + If :math:`H_k` is symmetric and positive definite, used as an approximation of the inverse Hessian, then + it's a quasi-Newton. In practice, the approximated Hessians are obtained + by only using the gradients, over either whole or part of the search + history, the former is BFGS, the latter is L-BFGS. + + Reference: + Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, 2006. pp140: Algorithm 6.1 (BFGS Method). + + Args: + objective_func: the objective function to minimize. ``objective_func`` accepts a 1D Tensor and returns a scalar. + initial_position (Tensor): the starting point of the iterates, has the same shape with the input of ``objective_func`` . + max_iters (int, optional): the maximum number of minimization iterations. Default value: 50. + tolerance_grad (float, optional): terminates if the gradient norm is smaller than this. Currently gradient norm uses inf norm. Default value: 1e-7. + tolerance_change (float, optional): terminates if the change of function value/position/parameter between two iterations is smaller than this value. Default value: 1e-9. + initial_inverse_hessian_estimate (Tensor, optional): the initial inverse hessian approximation at initial_position. It must be symmetric and positive definite. If not given, will use an identity matrix of order N, which is size of ``initial_position`` . Default value: None. + line_search_fn (str, optional): indicate which line search method to use, only support 'strong wolfe' right now. May support 'Hager Zhang' in the futrue. Default value: 'strong wolfe'. + max_line_search_iters (int, optional): the maximum number of line search iterations. Default value: 50. + initial_step_length (float, optional): step length used in first iteration of line search. different initial_step_length may cause different optimal result. For methods like Newton and quasi-Newton the initial trial step length should always be 1.0. Default value: 1.0. + dtype ('float32' | 'float64', optional): data type used in the algorithm, the data type of the input parameter must be consistent with the dtype. Default value: 'float32'. + name (str, optional): Name for the operation. For more information, please refer to :ref:`api_guide_Name`. Default value: None. + + Returns: + output(tuple): + + - is_converge (bool): Indicates whether found the minimum within tolerance. + - num_func_calls (int): number of objective function called. + - position (Tensor): the position of the last iteration. If the search converged, this value is the argmin of the objective function regrading to the initial position. + - objective_value (Tensor): objective function value at the `position`. + - objective_gradient (Tensor): objective function gradient at the `position`. + - inverse_hessian_estimate (Tensor): the estimate of inverse hessian at the `position`. + + Examples: + .. code-block:: python + + import paddle + + def func(x): + return paddle.dot(x, x) + + x0 = paddle.to_tensor([1.3, 2.7]) + results = paddle.incubate.optimizer.functional.minimize_bfgs(func, x0) + print("is_converge: ", results[0]) + print("the minimum of func is: ", results[2]) + # is_converge: is_converge: Tensor(shape=[1], dtype=bool, place=Place(gpu:0), stop_gradient=True, + # [True]) + # the minimum of func is: Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0., 0.]) + """ + + if dtype not in ['float32', 'float64']: + raise ValueError( + "The dtype must be 'float32' or 'float64', but the specified is {}." + .format(dtype)) + + op_name = 'minimize_bfgs' + check_input_type(initial_position, 'initial_position', op_name) + + I = paddle.eye(initial_position.shape[0], dtype=dtype) + if initial_inverse_hessian_estimate is None: + initial_inverse_hessian_estimate = I + else: + check_input_type(initial_inverse_hessian_estimate, + 'initial_inverse_hessian_estimate', op_name) + check_initial_inverse_hessian_estimate(initial_inverse_hessian_estimate) + + Hk = paddle.assign(initial_inverse_hessian_estimate) + # use detach and assign to create new tensor rather than =, or xk will share memory and grad with initial_position + xk = paddle.assign(initial_position.detach()) + + value, g1 = _value_and_gradient(objective_func, xk) + num_func_calls = paddle.full(shape=[1], fill_value=1, dtype='int64') + + # when the dim of x is 1000, it needs more than 30 iters to get all element converge to minimum. + k = paddle.full(shape=[1], fill_value=0, dtype='int64') + done = paddle.full(shape=[1], fill_value=False, dtype='bool') + is_converge = paddle.full(shape=[1], fill_value=False, dtype='bool') + + def cond(k, done, is_converge, num_func_calls, xk, value, g1, Hk): + return (k < max_iters) & ~done + + def body(k, done, is_converge, num_func_calls, xk, value, g1, Hk): + ############# compute pk ############# + pk = -paddle.matmul(Hk, g1) + + ############# compute alpha by line serach ############# + if line_search_fn == 'strong_wolfe': + alpha, value, g2, ls_func_calls = strong_wolfe( + f=objective_func, + xk=xk, + pk=pk, + initial_step_length=initial_step_length, + dtype=dtype) + else: + raise NotImplementedError( + "Currently only support line_search_fn = 'strong_wolfe', but the specified is '{}'" + .format(line_search_fn)) + num_func_calls += ls_func_calls + + ############# update Hk ############# + sk = alpha * pk + yk = g2 - g1 + + xk = xk + sk + g1 = g2 + + sk = paddle.unsqueeze(sk, 0) + yk = paddle.unsqueeze(yk, 0) + + rhok_inv = paddle.dot(yk, sk) + rhok = paddle.static.nn.cond( + rhok_inv == 0., + lambda: paddle.full(shape=[1], fill_value=1000.0, dtype=dtype), + lambda: 1. / rhok_inv) + + Vk_transpose = I - rhok * sk * yk.t() + Vk = I - rhok * yk * sk.t() + Hk = paddle.matmul(paddle.matmul(Vk_transpose, Hk), + Vk) + rhok * sk * sk.t() + + k += 1 + + ############# check convergence ############# + gnorm = paddle.linalg.norm(g1, p=np.inf) + pk_norm = paddle.linalg.norm(pk, p=np.inf) + paddle.assign( + done | (gnorm < tolerance_grad) | (pk_norm < tolerance_change), + done) + paddle.assign(done, is_converge) + # when alpha=0, there is no chance to get xk change. + paddle.assign(done | (alpha == 0.), done) + return [k, done, is_converge, num_func_calls, xk, value, g1, Hk] + + paddle.static.nn.while_loop( + cond=cond, + body=body, + loop_vars=[k, done, is_converge, num_func_calls, xk, value, g1, Hk]) + return is_converge, num_func_calls, xk, value, g1, Hk diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/lbfgs.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/lbfgs.py new file mode 100644 index 0000000000000000000000000000000000000000..d09ba5c6952e03045bb3ad66920dbd71bcb60155 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/lbfgs.py @@ -0,0 +1,236 @@ +# Copyright (c) 2022 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. + +import numpy as np + +from .line_search import strong_wolfe +from .utils import _value_and_gradient, check_input_type, check_initial_inverse_hessian_estimate + +import paddle + + +def minimize_lbfgs(objective_func, + initial_position, + history_size=100, + max_iters=50, + tolerance_grad=1e-8, + tolerance_change=1e-8, + initial_inverse_hessian_estimate=None, + line_search_fn='strong_wolfe', + max_line_search_iters=50, + initial_step_length=1.0, + dtype='float32', + name=None): + r""" + Minimizes a differentiable function `func` using the L-BFGS method. + The L-BFGS is a quasi-Newton method for solving an unconstrained optimization problem over a differentiable function. + Closely related is the Newton method for minimization. Consider the iterate update formula: + + .. math:: + x_{k+1} = x_{k} + H_k \nabla{f_k} + + If :math:`H_k` is the inverse Hessian of :math:`f` at :math:`x_k`, then it's the Newton method. + If :math:`H_k` is symmetric and positive definite, used as an approximation of the inverse Hessian, then + it's a quasi-Newton. In practice, the approximated Hessians are obtained + by only using the gradients, over either whole or part of the search + history, the former is BFGS, the latter is L-BFGS. + + Reference: + Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, 2006. pp179: Algorithm 7.5 (L-BFGS). + + Args: + objective_func: the objective function to minimize. ``objective_func`` accepts a 1D Tensor and returns a scalar. + initial_position (Tensor): the starting point of the iterates, has the same shape with the input of ``objective_func`` . + history_size (Scalar): the number of stored vector pairs {si,yi}. Default value: 100. + max_iters (int, optional): the maximum number of minimization iterations. Default value: 50. + tolerance_grad (float, optional): terminates if the gradient norm is smaller than this. Currently gradient norm uses inf norm. Default value: 1e-7. + tolerance_change (float, optional): terminates if the change of function value/position/parameter between two iterations is smaller than this value. Default value: 1e-9. + initial_inverse_hessian_estimate (Tensor, optional): the initial inverse hessian approximation at initial_position. It must be symmetric and positive definite. If not given, will use an identity matrix of order N, which is size of ``initial_position`` . Default value: None. + line_search_fn (str, optional): indicate which line search method to use, only support 'strong wolfe' right now. May support 'Hager Zhang' in the futrue. Default value: 'strong wolfe'. + max_line_search_iters (int, optional): the maximum number of line search iterations. Default value: 50. + initial_step_length (float, optional): step length used in first iteration of line search. different initial_step_length may cause different optimal result. For methods like Newton and quasi-Newton the initial trial step length should always be 1.0. Default value: 1.0. + dtype ('float32' | 'float64', optional): data type used in the algorithm, the data type of the input parameter must be consistent with the dtype. Default value: 'float32'. + name (str, optional): Name for the operation. For more information, please refer to :ref:`api_guide_Name`. Default value: None. + + Returns: + output(tuple): + + - is_converge (bool): Indicates whether found the minimum within tolerance. + - num_func_calls (int): number of objective function called. + - position (Tensor): the position of the last iteration. If the search converged, this value is the argmin of the objective function regrading to the initial position. + - objective_value (Tensor): objective function value at the `position`. + - objective_gradient (Tensor): objective function gradient at the `position`. + + Examples: + .. code-block:: python + + import paddle + + def func(x): + return paddle.dot(x, x) + + x0 = paddle.to_tensor([1.3, 2.7]) + results = paddle.incubate.optimizer.functional.minimize_lbfgs(func, x0) + print("is_converge: ", results[0]) + print("the minimum of func is: ", results[2]) + # is_converge: is_converge: Tensor(shape=[1], dtype=bool, place=Place(gpu:0), stop_gradient=True, + # [True]) + # the minimum of func is: Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0., 0.]) + """ + if dtype not in ['float32', 'float64']: + raise ValueError( + "The dtype must be 'float32' or 'float64', but the specified is {}." + .format(dtype)) + + op_name = 'minimize_lbfgs' + check_input_type(initial_position, 'initial_position', op_name) + + if initial_inverse_hessian_estimate is None: + H0 = paddle.eye(initial_position.shape[0], dtype=dtype) + else: + check_input_type(initial_inverse_hessian_estimate, + 'initial_inverse_hessian_estimate', op_name) + check_initial_inverse_hessian_estimate(initial_inverse_hessian_estimate) + H0 = initial_inverse_hessian_estimate + + # use detach and assign to create new tensor rather than =, or xk will share memory and grad with initial_position + xk = paddle.assign(initial_position.detach()) + value, g1 = _value_and_gradient(objective_func, xk) + + k = paddle.full(shape=[1], fill_value=0, dtype='int64') + done = paddle.full(shape=[1], fill_value=False, dtype='bool') + is_converge = paddle.full(shape=[1], fill_value=False, dtype='bool') + num_func_calls = paddle.full(shape=[1], fill_value=1, dtype='int64') + + history_size = paddle.full(shape=[1], + fill_value=history_size, + dtype='int64') + head = paddle.full(shape=[1], fill_value=1, dtype='int64') + tail = paddle.full(shape=[1], fill_value=0, dtype='int64') + + shape = initial_position.shape[0] + # Use tensor as array of fixed length, rather than flexible tensor array. Because in static mode, + # tensor array will produce tensor of shape[-1], which will cause error when calling jacobian. In this way, can not use append + # or pop, so we need head and tail to record where is the newest data and where is the oldest. + # Totally speaking, realized a stack by array. + sk_vec = paddle.zeros((history_size + 1, shape), dtype=dtype) + yk_vec = paddle.zeros((history_size + 1, shape), dtype=dtype) + rhok_vec = paddle.zeros((history_size + 1, 1), dtype=dtype) + ai_vec = paddle.zeros((history_size + 1, 1), dtype=dtype) + + def cond(k, done, is_converge, num_func_calls, value, xk, g1, sk_vec, + yk_vec, rhok_vec, head, tail): + return (k < max_iters) & ~done + + def body(k, done, is_converge, num_func_calls, value, xk, g1, sk_vec, + yk_vec, rhok_vec, head, tail): + # use assign to cut off the relevance between g1 and q, or they will change together. + + ############# compute p_k by two-loop recursion ############# + q = paddle.assign(g1) + # In a array circle, the index may out of range, so must use mod. + i = paddle.full(shape=[1], + fill_value=(head - 1).mod(history_size), + dtype='int64') + + def cond(i, q): + return i != tail + + def body(i, q): + ai_vec[i] = rhok_vec[i] * paddle.dot(sk_vec[i], q) + q = q - ai_vec[i] * yk_vec[i] + i = (i - 1).mod(history_size) + return i, q + + paddle.static.nn.while_loop(cond=cond, body=body, loop_vars=[i, q]) + + r = paddle.matmul(H0, q) + + i = paddle.full(shape=[1], fill_value=tail + 1, dtype='int64') + + def cond(i, r): + return i != head + + def body(i, r): + beta = rhok_vec[i] * paddle.dot(yk_vec[i], r) + r = r + sk_vec[i] * (ai_vec[i] - beta) + i = (i + 1).mod(history_size) + return i, r + + paddle.static.nn.while_loop(cond=cond, body=body, loop_vars=[i, r]) + + pk = -r + + ############# compute alpha by line serach ############# + if line_search_fn == 'strong_wolfe': + alpha, value, g2, ls_func_calls = strong_wolfe( + f=objective_func, + xk=xk, + pk=pk, + initial_step_length=initial_step_length, + dtype=dtype) + else: + raise NotImplementedError( + "Currently only support line_search_fn = 'strong_wolfe', but the specified is '{}'" + .format(line_search_fn)) + paddle.assign(num_func_calls + ls_func_calls, num_func_calls) + + ############# update sk_vec, yk_vec, rhok_vec ############# + sk = alpha * pk + yk = g2 - g1 + + rhok_inv = paddle.dot(yk, sk) + rhok = paddle.static.nn.cond( + rhok_inv == 0., + lambda: paddle.full(shape=[1], fill_value=1000.0, dtype=dtype), + lambda: 1. / rhok_inv) + + sk_vec[head] = sk + yk_vec[head] = yk + rhok_vec[head] = rhok + head = (head + 1) % history_size + + def true_fn(tail): + paddle.assign(tail + 1, tail) + + # when array is full, the tail should move forward too. + paddle.static.nn.cond(head == tail, lambda: true_fn(tail), None) + + xk = xk + sk + g1 = g2 + k += 1 + + ############# check convergence ############# + gnorm = paddle.linalg.norm(g1, p=np.inf) + pk_norm = paddle.linalg.norm(pk, p=np.inf) + paddle.assign( + done | (gnorm < tolerance_grad) | (pk_norm < tolerance_change), + done) + paddle.assign(done, is_converge) + # when alpha=0, there is no chance to get xk change. + paddle.assign(done | (alpha == 0.), done) + + return [ + k, done, is_converge, num_func_calls, value, xk, g1, sk_vec, yk_vec, + rhok_vec, head, tail + ] + + paddle.static.nn.while_loop(cond=cond, + body=body, + loop_vars=[ + k, done, is_converge, num_func_calls, value, + xk, g1, sk_vec, yk_vec, rhok_vec, head, tail + ]) + return is_converge, num_func_calls, xk, value, g1 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/line_search.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/line_search.py new file mode 100644 index 0000000000000000000000000000000000000000..3aacb137e6e47bde710304f11a3fc244892e29c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/line_search.py @@ -0,0 +1,296 @@ +# Copyright (c) 2022 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. + +from .utils import _value_and_gradient +import paddle + + +def cubic_interpolation_(x1, f1, g1, x2, f2, g2): + r"""Cubic interpolation between (x1, f1, g1) and (x2, f2, g2). + Use two points and their gradient to determine a cubic function and get the minimun point + between them in the cubic curve. + + Reference: + Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, 2006. + pp59: formula 3.59 + + Args: + x1, f1, g1: point1's position, value and gradient. + x2, f2, g2: point2's position, value and gradient. + Returns: + min_pos: the minimun point between the specified points in the cubic curve. + """ + xmin, xmax = paddle.static.nn.cond(x1 <= x2, lambda: (x1, x2), lambda: + (x2, x1)) + d1 = g1 + g2 - 3 * (f1 - f2) / (x1 - x2) + d2_square = d1**2 - g1 * g2 + + def true_func1(): + d2 = d2_square.sqrt() + + def true_fn2(): + return x2 - (x2 - x1) * ((g2 + d2 - d1) / (g2 - g1 + 2 * d2)) + + def false_fn2(): + return x1 - (x1 - x2) * ((g1 + d2 - d1) / (g1 - g2 + 2 * d2)) + + pred = paddle.less_equal(x=x1, y=x2) + min_pos = paddle.static.nn.cond(pred, true_fn2, false_fn2) + + return paddle.minimum(paddle.maximum(min_pos, xmin), xmax) + + def false_func1(): + return (xmin + xmax) / 2. + + min_pos = paddle.static.nn.cond(d2_square >= 0., true_func1, false_func1) + return min_pos + + +def strong_wolfe(f, + xk, + pk, + max_iters=20, + tolerance_change=1e-8, + initial_step_length=1.0, + c1=1e-4, + c2=0.9, + alpha_max=10, + dtype='float32'): + r"""Implements of line search algorithm that satisfies the strong Wolfe conditions using double zoom. + + Reference: + Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, 2006. + pp60: Algorithm 3.5 (Line Search Algorithm). + + Args: + f: the objective function to minimize. ``f`` accepts a multivariate input and returns a scalar. + xk (Tensor): the starting point of the iterates. + pk (Tensor): search direction. + max_iters (Scalar): the maximum number of iterations. + tolerance_grad (Scalar): terminates if the gradient norm is smaller than + this. Currently gradient norm uses inf norm. + tolerance_change (Scalar): terminates if the change of function value/position/parameter between + two iterations is smaller than this value. + initial_step_length (Scalar): step length used in first iteration. + c1 (Scalar): parameter for sufficient decrease condition. + c2 (Scalar): parameter for curvature condition. + alpha_max (float): max step length. + dtype ('float32' | 'float64'): the datatype to be used. + + Returns: + num_func_calls (float): number of objective function called in line search process. + a_star(Tensor): optimal step length, or 0. if the line search algorithm did not converge. + phi_star (Tensor): phi at a_star. + derphi_star (Tensor): derivative of phi at a_star. + + Following summarizes the essentials of the strong Wolfe line search algorithm. + Some notations used in the description: + + - `f` denotes the objective function. + - `phi` is a function of step size alpha, restricting `f` on a line. + + phi = f(xk + a * pk), + where xk is the position of k'th iterate, pk is the line search direction(decent direction), + and a is the step size. + - a : substitute of alpha + - a1 is a of last iteration, which is alpha_(i-1). + - a2 is a of current iteration, which is alpha_i. + - a_lo is a in left position when calls zoom, which is alpha_low. + - a_hi is a in right position when calls zoom, which is alpha_high. + + Line Search Algorithm: + repeat + Compute phi(a2) and derphi(a2). + 1. If phi(a2) > phi(0) + c_1 * a2 * phi'(0) or [phi(a2) >= phi(a1) and i > 1], + a_star= zoom(a1, a2) and stop; + + 2. If |phi'(a2)| <= -c_2 * phi'(0), + a_star= a2 and stop; + + 3. If phi'(a2) >= 0, + a_star= zoom(a2, a1) and stop; + + a1 = a2 + a2 = min(2 * a2, a2) + i = i + 1 + end(repeat) + + zoom(a_lo, a_hi) Algorithm: + repeat + aj = cubic_interpolation(a_lo, a_hi) + Compute phi(aj) and derphi(aj). + 1. If phi(aj) > phi(0) + c_1 * aj * phi'(0) or phi(aj) >= phi(a_lo), + then a_hi <- aj; + 2. + 2.1. If |phi'(aj)| <= -c_2 * phi'(0), then a_star= a2 and stop; + + 2.2. If phi'(aj) * (a2 - a1) >= 0, then a_hi = a_lo + + a_lo = aj; + end(repeat) + """ + + def phi_and_derphi(a): + r"""Compute function value and derivative of phi at a. + phi = f(xk + a * pk) + phi'(a) = f'(xk + a * pk) * pk + """ + phi_value, f_grad = _value_and_gradient(f, xk + a * pk) + phi_grad = paddle.dot(f_grad, pk) + # return f_grad to be used in bfgs/l-bfgs to compute yk to avoid computint repeatly. + return phi_value, f_grad, phi_grad + + def zoom(a_lo, phi_lo, derphi_lo, derf_lo, a_hi, phi_hi, derphi_hi, phi_0, + derphi_0): + # find the exact a from the bracket [a_lo, a_hi] + max_zoom_iters = max_iters + j = paddle.full(shape=[1], fill_value=0, dtype='int64') + done_zoom = paddle.full(shape=[1], fill_value=False, dtype='bool') + + def cond_zoom(j, done_zoom, a_lo, phi_lo, derphi_lo, derf_lo, a_hi, + phi_hi, derphi_hi): + pred = paddle.abs(a_hi - a_lo) < tolerance_change + paddle.assign(done_zoom | pred, done_zoom) + return (j < max_zoom_iters) & ~done_zoom + + def body_zoom(j, done_zoom, a_lo, phi_lo, derphi_lo, derf_lo, a_hi, + phi_hi, derphi_hi): + aj = cubic_interpolation_(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, + derphi_hi) # 21 + min_change = 0.1 * paddle.abs(a_hi - a_lo) + pred = paddle.minimum(paddle.abs(aj - a_lo), + paddle.abs(aj - a_hi)) < min_change + aj = paddle.static.nn.cond(pred, lambda: 0.5 * (a_lo + a_hi), + lambda: aj) + + phi_j, derf_j, derphi_j = phi_and_derphi(aj) + + def true_fn(): + # use assing to modify the variable in-place + paddle.assign(aj, a_hi) + paddle.assign(phi_j, phi_hi) + paddle.assign(derphi_j, derphi_hi) + + def false_fn(a_lo, done_zoom): + pred3 = (paddle.abs(derphi_j) <= -c2 * derphi_0) + paddle.assign(pred3, done_zoom) + + def true_fn(): + paddle.assign(a_lo, a_hi) + paddle.assign(phi_lo, phi_hi) + paddle.assign(derphi_lo, derphi_hi) + + pred4 = ~done_zoom & (derphi_j * (a_hi - a_lo) >= 0) + paddle.static.nn.cond(pred4, true_fn, None) + + paddle.assign(aj, a_lo) + paddle.assign(phi_j, phi_lo) + paddle.assign(derphi_j, derphi_lo) + paddle.assign(derf_j, derf_lo) + + pred2 = (phi_j > phi_0 + c1 * aj * derphi_0) | (phi_j >= phi_lo) + paddle.static.nn.cond(pred2, true_fn, + lambda: false_fn(a_lo, done_zoom)) + j = paddle.static.nn.cond(done_zoom, lambda: j, lambda: j + 1) + return [ + j, done_zoom, a_lo, phi_lo, derphi_lo, derf_lo, a_hi, phi_hi, + derphi_hi + ] + + paddle.static.nn.while_loop(cond=cond_zoom, + body=body_zoom, + loop_vars=[ + j, done_zoom, a_lo, phi_lo, derphi_lo, + derf_lo, a_hi, phi_hi, derphi_hi + ]) + # j is the number of object function called in zoom. + return j + + alpha_max = paddle.full(shape=[1], fill_value=alpha_max, dtype=dtype) + + a1 = paddle.full(shape=[1], fill_value=0., dtype=dtype) + a2 = paddle.full(shape=[1], fill_value=initial_step_length, dtype=dtype) + + phi_1, derf_1, derphi_1 = phi_and_derphi(a1) + # use assign to cut off binding between two variables + phi_0 = paddle.assign(phi_1) + derphi_0 = paddle.assign(derphi_1) + ls_func_calls = paddle.full(shape=[1], fill_value=1, dtype='int64') + + # If not found the a_star, will return alpha=0 and f(xk), derf(xk) + a_star = paddle.full(shape=[1], fill_value=0, dtype=dtype) + phi_star = paddle.assign(phi_1) + derf_star = paddle.assign(derf_1) + + i = paddle.full(shape=[1], fill_value=0, dtype='int64') + done = paddle.full(shape=[1], fill_value=False, dtype='bool') + + def cond(i, ls_func_calls, a1, a2, phi_1, derf_1, done): + return (i < max_iters) & ~done + + def body(i, ls_func_calls, a1, a2, phi_1, derf_1, done): + phi_2, derf_2, derphi_2 = phi_and_derphi(a2) + paddle.assign(ls_func_calls + 1, ls_func_calls) + paddle.assign(done | paddle.any(paddle.isinf(phi_2)), done) + + def true_fn1(): + j = zoom(a1, phi_1, derphi_1, derf_1, a2, phi_2, derphi_2, phi_0, + derphi_0) + paddle.assign(a1, a_star) + paddle.assign(phi_1, phi_star) + paddle.assign(derf_1, derf_star) + paddle.assign(ls_func_calls + j, ls_func_calls) + + pred1 = ~done & ((phi_2 > phi_0 + c1 * a2 * derphi_0) | + ((phi_2 >= phi_0) & (i > 1))) + paddle.assign(done | pred1, done) + paddle.static.nn.cond(pred1, true_fn1, None) + + def true_fn2(): + paddle.assign(a2, a_star) + paddle.assign(phi_2, phi_star) + paddle.assign(derf_2, derf_star) + + pred2 = ~done & (paddle.abs(derphi_2) <= -c2 * derphi_0) + paddle.assign(done | pred2, done) + paddle.static.nn.cond(pred2, true_fn2, None) + + def true_fn3(): + j = zoom(a2, phi_2, derphi_2, derf_2, a1, phi_1, derphi_1, phi_0, + derphi_0) + paddle.assign(a2, a_star) + paddle.assign(phi_2, phi_star) + paddle.assign(derf_2, derf_star) + paddle.assign(ls_func_calls + j, ls_func_calls) + + pred3 = ~done & (derphi_2 >= 0) + paddle.assign(done | pred3, done) + paddle.static.nn.cond(pred3, true_fn3, None) + + def false_fn(): + paddle.assign(a2, a1) + paddle.assign(phi_2, phi_1) + paddle.assign(derf_2, derf_1) + paddle.assign(paddle.minimum(2 * a2, alpha_max), a2) + paddle.assign(i + 1, i) + + paddle.static.nn.cond(done, None, false_fn) + return [i, ls_func_calls, a1, a2, phi_1, derf_1, done] + + paddle.static.nn.while_loop( + cond=cond, + body=body, + loop_vars=[i, ls_func_calls, a1, a2, phi_1, derf_1, done]) + + return a_star, phi_star, derf_star, ls_func_calls diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f69a354918d8468b18a9b3308558c0cbd7cace --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/functional/utils.py @@ -0,0 +1,99 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle.fluid.framework import Variable +from paddle.fluid.data_feeder import check_type, check_dtype + + +def check_input_type(input, name, op_name): + r"""Check whether the input is tensor or variable.""" + if paddle.in_dynamic_mode(): + if not isinstance(input, paddle.Tensor): + raise ValueError("The input: {} must be tensor.".format(input)) + else: + check_type(input, name, Variable, op_name) + + +def check_initial_inverse_hessian_estimate(H0): + r"""Check whether the specified initial_inverse_hessian_estimate is symmetric and positive definite. + Raise errors when precondition not met. + + Note: + In static graph can not raise error directly, so use py_func make raise_func as a op, + and use paddle.static.nn.cond to decide if put the op in net. + cholesky is the fast way to check positive definition, but in static graph can not catch + exception to raise value error, so use eigvals rather than cholesky in static graph. + """ + is_symmetric = paddle.all(paddle.equal(H0, H0.t())) + + def raise_func(): + raise ValueError( + "The initial_inverse_hessian_estimate should be symmetric and positive definite, but the specified is not." + ) + + if paddle.in_dynamic_mode(): + if not is_symmetric: + raise_func() + try: + paddle.linalg.cholesky(H0) + except RuntimeError as error: + raise_func() + else: + + def create_tmp_var(program, name, dtype, shape): + return program.current_block().create_var(name=name, + dtype=dtype, + shape=shape) + + out_var = create_tmp_var(paddle.static.default_main_program(), + name='output', + dtype='float32', + shape=[-1]) + + def false_fn(): + paddle.static.nn.py_func(func=raise_func, + x=is_symmetric, + out=out_var) + + paddle.static.nn.cond(is_symmetric, None, false_fn) + # eigvals only support cpu + paddle.set_device("cpu") + eigvals = paddle.paddle.linalg.eigvals(H0) + is_positive = paddle.all(eigvals.real() > 0.) and paddle.all( + eigvals.imag() == 0.) + paddle.static.nn.cond(is_positive, None, false_fn) + + +def _value_and_gradient(f, x, v=None): + r"""Compute function value and gradient of f at x. + + Args: + f (Callable): the objective function. + x (Tensor): the input tensor. + Returns: + value: a tensor that holds the function value. + gradient: a tensor that holds the function gradients. + """ + # use detach to cut off relation between x and original graph + x = x.detach() + x.stop_gradient = False + value = f(x) + if paddle.in_dynamic_mode(): + # only need to compute first order derivative, and some op dont support high order derivative. + gradient = paddle.grad([value], [x], create_graph=False)[0] + else: + gradient = paddle.static.gradients([value], [x])[0] + # use detach to make results real number without grad to avoid assign error + return value.detach(), gradient.detach() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/lookahead.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/lookahead.py new file mode 100644 index 0000000000000000000000000000000000000000..c04eaadffd8c1f71dae90d751f43958f1c536e21 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/lookahead.py @@ -0,0 +1,310 @@ +# 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. + +from paddle.optimizer import Optimizer +from paddle.fluid import core, framework, layers, unique_name +from paddle.fluid.framework import ( + Program, + Variable, + name_scope, + default_main_program, + default_startup_program, + device_guard, +) +from paddle.fluid.layer_helper import LayerHelper +import paddle +import numpy as np +from paddle.fluid.dygraph import base as imperative_base + +__all__ = [] + + +class LookAhead(Optimizer): + r""" + This implements the Lookahead optimizer of the + paper : https://arxiv.org/abs/1907.08610. + + Lookahead keeps two sets of params: the fast_params and + the slow_params. inner_optimizer update fast_params every + training step. Lookahead updates the slow_params and fast_params + every k training steps as follows: + + .. math:: + + slow\_param_t &= slow\_param_{t-1} + \\alpha * (fast\_param_{t-1} - slow\_param_{t-1}) + + fast\_param_t &= slow\_param_t + + Args: + inner_optimizer (Optimizer): The optimizer that update fast params step by step. + alpha (float, optinal): The learning rate of Lookahead. The default value is 0.5. + k (int, optinal): The slow params is updated every k steps. The default value is 5. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, + (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + self.bias = self._linear.bias + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + opt.clear_grad() + print("Train Epoch {} batch {}: loss = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()))) + + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + optimizer = paddle.optimizer.SGD(learning_rate=0.1, parameters=layer.parameters()) + lookahead = paddle.incubate.LookAhead(optimizer, alpha=0.2, k=5) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader( + dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + + train(layer, loader, loss_fn, lookahead) + + """ + _slow_str = "slow" + + def __init__(self, inner_optimizer, alpha=0.5, k=5, name=None): + assert inner_optimizer is not None, "inner optimizer can not be None" + assert ( + 0.0 <= alpha <= 1.0 + ), "alpha should be larger or equal to 0.0, and less or equal than 1.0" + assert isinstance(k, int) and k > 0, "k should be a positive integer" + + self.inner_optimizer = inner_optimizer + if self.inner_optimizer._parameter_list is None: + parameters = ( + framework.default_main_program().global_block().all_parameters() + ) + else: + parameters = self.inner_optimizer._parameter_list + + super(LookAhead, self).__init__( + learning_rate=alpha, + parameters=parameters, + weight_decay=None, + grad_clip=None, + name=name, + ) + + self.alpha = alpha + self.k = k + self.type = "lookahead" + self.helper = LayerHelper(self.__class__.__name__) + self._global_step_var = None + self._k_var = None + + @framework.dygraph_only + @imperative_base.no_grad + def step(self): + """ + Execute the optimizer and update parameters once. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + inp = paddle.rand([1,10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + lookahead = paddle.incubate.LookAhead(sgd, alpha=0.2, k=5) + loss.backward() + lookahead.step() + lookahead.clear_grad() + + """ + self.inner_optimizer.step() + + self._increment_global_var() + params_grads = [] + for param in self._parameter_list: + if not param.trainable: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + params_grads.append((param, grad_var)) + + self._apply_optimize( + loss=None, startup_program=None, params_grads=params_grads + ) + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for p in parameters: + self._add_accumulator(self._slow_str, p) + + def _increment_global_var(self): + if self._global_step_var is None: + self._global_step_var = layers.create_global_var( + name=unique_name.generate("lookahead_step"), + shape=[1], + value=0, + dtype='int32', + persistable=True, + ) + + self.helper.append_op( + type='increment', + inputs={'X': [self._global_step_var]}, + outputs={'Out': [self._global_step_var]}, + attrs={'step': 1.0}, + ) + + def _append_optimize_op(self, block, param_and_grad): + one_var = paddle.ones(shape=[1], dtype='int32', name='lookahead_ones') + zero_var = paddle.zeros( + shape=[1], dtype='int32', name='lookahead_zeros' + ) + k_var = layers.create_global_var( + name=unique_name.generate("lookahead_k"), + shape=[1], + value=self.k, + dtype='int32', + persistable=True, + ) + + mod = paddle.remainder(self._global_step_var, k_var) + + cond_1 = paddle.equal(self._global_step_var, one_var) + cond_1 = paddle.cast(cond_1, dtype='float32') + + cond_2 = paddle.equal(mod, zero_var) + cond_2 = paddle.cast(cond_2, dtype='float32') + + slow_var = self._get_accumulator(self._slow_str, param_and_grad[0]) + + tmp_var = cond_1 * param_and_grad[0] + (1 - cond_1) * slow_var + paddle.assign(tmp_var, slow_var) + + tmp_var = self.alpha * param_and_grad[0] + (1.0 - self.alpha) * slow_var + tmp_var_1 = cond_2 * tmp_var + (1 - cond_2) * param_and_grad[0] + paddle.assign(tmp_var_1, param_and_grad[0]) + + tmp_var_1 = cond_2 * tmp_var + (1 - cond_2) * slow_var + paddle.assign(tmp_var_1, slow_var) + + @imperative_base.no_grad + def minimize( + self, loss, startup_program=None, parameters=None, no_grad_set=None + ): + """ + Add operations to minimize ``loss`` by updating ``parameters``. + + Args: + loss (Tensor): A ``Tensor`` containing the value to minimize. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameters``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't need + to be updated. The default value is None. + + Returns: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by minimize and a list of (param, grad) tensor pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + In static graph mode, the returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + + .. code-block:: python + + import paddle + + inp = paddle.rand([1, 10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + lookahead = paddle.incubate.LookAhead(sgd, alpha=0.2, k=5) + loss.backward() + lookahead.minimize(loss) + lookahead.clear_grad() + + """ + assert isinstance(loss, Variable), "The loss should be an Tensor." + + # Apply inner optimizer to the main_program + optimize_ops, params_grads = self.inner_optimizer.minimize( + loss, + startup_program=startup_program, + parameters=parameters, + no_grad_set=no_grad_set, + ) + + self._increment_global_var() + + _ = self._apply_optimize( + loss, startup_program=startup_program, params_grads=params_grads + ) + + return optimize_ops, params_grads diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/modelaverage.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/modelaverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6247ce6e72768c17884ed8c68ae92465871e25c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/optimizer/modelaverage.py @@ -0,0 +1,566 @@ +# 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. + +from paddle.optimizer import Optimizer +from paddle.fluid import core, framework, layers +from paddle.fluid.framework import Program, Variable +from paddle.fluid.layer_helper import LayerHelper +import paddle +import numpy as np +from paddle.fluid.dygraph import base as imperative_base +from paddle.fluid.wrapped_decorator import signature_safe_contextmanager +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import in_dygraph_mode + +__all__ = [] + + +class ModelAverage(Optimizer): + r""" + The ModelAverage optimizer accumulates specific continuous historical + parameters during training. The accumulated historical range can be controlled + by the passed ``average_window_rate`` argument. The averaged ``Parameter`` are + used in the prediction, which usually can improve the accuracy of the prediction. + + Accumulate the average of the ``Parameter`` in the sliding window, the result will be saved + in a temporary variable, can be applied to the current model's ``Parameter`` by calling + the ``apply()`` method, and the current model ``Parameter`` can be restored by calling + the ``restore()`` method. + + The window size for calculating the average is determined by ``average_window_rate``, + ``min_average_window``, ``max_average_window`` and the current ``Parameter`` update times (num_updates). + + When the cumulative times (num_accumulates) is greater than the specific window + threshold (average_window), the accumulated ``Parameter`` temporary variable is set to 0.0. + The following example will help to understand the role of these arguments: + + :: + + if num_accumulates >= min_average_window and num_accumulates >= min(max_average_window, num_updates * average_window_rate): + num_accumulates = 0 + + In the above conditional judgment statement, ``num_accumulates`` indicates the current + accumulated number, which can be abstractly understood as the length of the cumulative window. + The length of the window must be at least the length set by the ``min_average_window`` argument, + and cannot exceed the length specified by the ``max_average_window`` argument or + ``num_updates * average_window_rate``, where ``num_updates`` indicates the current ``Parameter`` + update times, ``average_window_rate`` is a coefficient that calculates the length of the window. + + Args: + average_window_rate (float): The calculate ratio of the window length relative to ``Parameter`` update times. + parameters (list, optional): List of ``Tensor`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + min_average_window (int, optional): the minimum size of average window length. The default value is 10000. + max_average_window (int, optional): The maximum size of average window length. The default value is 10000. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + Examples: + + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + import paddle.optimizer as opt + + BATCH_SIZE = 16 + BATCH_NUM = 4 + EPOCH_NUM = 4 + + IMAGE_SIZE = 784 + CLASS_NUM = 10 + + # define a random dataset + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = np.random.random([IMAGE_SIZE]).astype('float32') + label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64') + return image, label + + def __len__(self): + return self.num_samples + + class LinearNet(nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM) + self.bias = self._linear.bias + + @paddle.jit.to_static + def forward(self, x): + return self._linear(x) + + def train(layer, loader, loss_fn, opt, model_average): + for epoch_id in range(EPOCH_NUM): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + opt.step() + model_average.step() + opt.clear_grad() + model_average.clear_grad() + print("Train Epoch {} batch {}: loss = {}, bias = {}".format( + epoch_id, batch_id, np.mean(loss.numpy()), layer.bias.numpy())) + def evaluate(layer, loader, loss_fn): + for batch_id, (image, label) in enumerate(loader()): + out = layer(image) + loss = loss_fn(out, label) + loss.backward() + print("Evaluate batch {}: loss = {}, bias = {}".format( + batch_id, np.mean(loss.numpy()), layer.bias.numpy())) + + # create network + layer = LinearNet() + loss_fn = nn.CrossEntropyLoss() + optimizer = opt.Momentum(learning_rate=0.2, momentum=0.1, parameters=layer.parameters()) + model_average = paddle.incubate.ModelAverage(0.15, + parameters=layer.parameters(), + min_average_window=2, + max_average_window=10) + + # create data loader + dataset = RandomDataset(BATCH_NUM * BATCH_SIZE) + loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=2) + # create data loader + eval_loader = paddle.io.DataLoader(dataset, + batch_size=BATCH_SIZE, + shuffle=True, + drop_last=True, + num_workers=1) + + # train + train(layer, loader, loss_fn, optimizer, model_average) + + print("\nEvaluate With ModelAverage") + with model_average.apply(need_restore=False): + evaluate(layer, eval_loader, loss_fn) + + print("\nEvaluate With Restored Paramters") + model_average.restore() + evaluate(layer, eval_loader, loss_fn) + + """ + + def __init__( + self, + average_window_rate, + parameters=None, + min_average_window=10000, + max_average_window=10000, + name=None, + ): + super(ModelAverage, self).__init__( + learning_rate=0.0, + parameters=parameters, + weight_decay=None, + grad_clip=None, + name=name, + ) + + self.helper = LayerHelper(self.__class__.__name__) + self.average_window = average_window_rate + self.min_average_window = min_average_window + self.max_average_window = max_average_window + self.type = "average_accumulates" + + if not framework._non_static_mode(): + global_block = framework.default_main_program().global_block() + all_parameters = ( + parameters if parameters else global_block.all_parameters() + ) + + self._create_accumulators(global_block, all_parameters) + for param in all_parameters: + self._append_optimize_op(global_block, [param, None]) + self.apply_program = Program() + block = self.apply_program.global_block() + with framework.program_guard(main_program=self.apply_program): + for param in all_parameters: + self._add_average_apply_op(block, param) + self.restore_program = Program() + block = self.restore_program.global_block() + with framework.program_guard(main_program=self.restore_program): + for param in all_parameters: + self._add_average_restore_op(block, param) + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + for param in parameters: + self._add_accumulator('sum_1', param) + self._add_accumulator('sum_2', param) + self._add_accumulator('sum_3', param) + self._add_accumulator('restore', param) + self._add_accumulator( + 'num_accumulates', param, dtype='int64', shape=[1] + ) + self._add_accumulator( + 'old_num_accumulates', param, dtype='int64', shape=[1] + ) + self._add_accumulator( + 'num_updates', param, dtype='int64', shape=[1] + ) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + sum_1 = self._get_accumulator('sum_1', param_and_grad[0]) + sum_2 = self._get_accumulator('sum_2', param_and_grad[0]) + sum_3 = self._get_accumulator('sum_3', param_and_grad[0]) + num_accumulates = self._get_accumulator( + 'num_accumulates', param_and_grad[0] + ) + old_num_accumulates = self._get_accumulator( + 'old_num_accumulates', param_and_grad[0] + ) + num_updates = self._get_accumulator('num_updates', param_and_grad[0]) + + if in_dygraph_mode(): + _, _, _, _, _, _ = _C_ops.average_accumulates_( + param_and_grad[0], + sum_1, + sum_2, + sum_3, + num_accumulates, + old_num_accumulates, + num_updates, + self.average_window, + self.max_average_window, + self.min_average_window, + ) + return None + elif framework._non_static_mode(): + _, _, _, _, _, _ = _legacy_C_ops.average_accumulates( + param_and_grad[0], + sum_1, + sum_2, + sum_3, + num_accumulates, + old_num_accumulates, + num_updates, + sum_1, + sum_2, + sum_3, + num_accumulates, + old_num_accumulates, + num_updates, + 'average_window', + self.average_window, + 'min_average_window', + self.min_average_window, + 'max_average_window', + self.max_average_window, + ) + return None + + block = framework.default_main_program().global_block() + attrs = { + "average_window": self.average_window, + "min_average_window": self.min_average_window, + "max_average_window": self.max_average_window, + } + + inputs = { + "param": param_and_grad[0], + "in_sum_1": sum_1, + "in_sum_2": sum_2, + "in_sum_3": sum_3, + "in_num_accumulates": num_accumulates, + "in_old_num_accumulates": old_num_accumulates, + "in_num_updates": num_updates, + } + + outputs = { + "out_sum_1": sum_1, + "out_sum_2": sum_2, + "out_sum_3": sum_3, + "out_num_accumulates": num_accumulates, + "out_old_num_accumulates": old_num_accumulates, + "out_num_updates": num_updates, + } + + average_accumulates_op = block.append_op( + type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True, + ) + + return average_accumulates_op + + @imperative_base.no_grad + def minimize( + self, loss, startup_program=None, parameters=None, no_grad_set=None + ): + """ + Add operations to minimize ``loss`` by updating ``parameters``. + + Args: + loss (Tensor): A ``Tensor`` containing the value to minimize. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameters``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't need + to be updated. The default value is None. + + Returns: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by minimize and a list of (param, grad) tensor pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + In static graph mode, the returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + + .. code-block:: python + + import paddle + inp = paddle.rand([1, 10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + loss.backward() + + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + sgd.minimize(loss) + + modelaverage = paddle.incubate.ModelAverage(0.15, + parameters=linear.parameters(), + min_average_window=2, + max_average_window=4) + modelaverage.minimize(loss) + sgd.clear_grad() + modelaverage.clear_grad() + + """ + if framework._non_static_mode(): + self.step() + + @framework.dygraph_only + @imperative_base.no_grad + def step(self): + """ + Execute the optimizer and update parameters once. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + inp = paddle.rand([1, 10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + modelaverage = paddle.incubate.ModelAverage(0.15, + parameters=linear.parameters(), + min_average_window=2, + max_average_window=4) + loss.backward() + sgd.step() + modelaverage.step() + sgd.clear_grad() + modelaverage.clear_grad() + """ + + params_grads = [] + for param in self._parameter_list: + if not param.trainable: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + params_grads.append((param, grad_var)) + + block = framework.default_main_program().global_block() + self._create_accumulators(block, self._parameter_list) + for param_and_grad in params_grads: + self._append_optimize_op(block, param_and_grad) + + @signature_safe_contextmanager + @imperative_base.no_grad + def apply(self, executor=None, need_restore=True): + """ + Apply the average of the cumulative ``Parameter`` to the parameters of the current model. + + Args: + executor(Executor): The network executor in static-graph mode. The default value is None in dygraph mode. + need_restore(bool): Restore flag variable, if set to True, the network will restore + the parameters of the network to the default value, if set to False, + it will not be restored. The default value is True. + + Examples: + + .. code-block:: python + + import paddle + inp = paddle.rand([1, 10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + loss.backward() + + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + + modelaverage = paddle.incubate.ModelAverage(0.15, + parameters=linear.parameters(), + min_average_window=2, + max_average_window=4) + sgd.step() + modelaverage.step() + + with modelaverage.apply(): + for param in linear.parameters(): + print(param) + + for param in linear.parameters(): + print(param) + """ + if framework._non_static_mode(): + for param in self._parameter_list: + num_accumulates = self._get_accumulator( + 'num_accumulates', param + ) + old_num_accumulates = self._get_accumulator( + 'old_num_accumulates', param + ) + sum_1 = self._get_accumulator('sum_1', param) + sum_2 = self._get_accumulator('sum_2', param) + sum_3 = self._get_accumulator('sum_3', param) + param_restore = self._get_accumulator('restore', param) + + paddle.assign(param, param_restore) + total_param = sum_1 + sum_2 + sum_3 + total_accumulates = num_accumulates + old_num_accumulates + total_param = paddle.cast(total_param, dtype='float32') + total_accumulates = paddle.cast( + total_accumulates, dtype='float32' + ) + average_param = total_param / total_accumulates + paddle.assign(average_param, param) + try: + yield + finally: + if need_restore: + self.restore() + return + if executor is None: + raise RuntimeError( + "Executor should not be None in static graph mode." + ) + executor.run(self.apply_program) + try: + yield + finally: + if need_restore: + self.restore(executor) + + @imperative_base.no_grad + def restore(self, executor=None): + """ + Restore ``Parameter`` values of current model. + + Args: + executor(Executor): The network executor in static-graph mode. The default value is None in dygraph mode + + Examples: + + .. code-block:: python + + import paddle + inp = paddle.rand([1, 10], dtype="float32") + linear = paddle.nn.Linear(10, 1) + out = linear(inp) + loss = paddle.mean(out) + loss.backward() + + sgd = paddle.optimizer.SGD(learning_rate=0.1,parameters=linear.parameters()) + + modelaverage = paddle.incubate.ModelAverage(0.15, + parameters=linear.parameters(), + min_average_window=2, + max_average_window=4) + sgd.step() + modelaverage.step() + + with modelaverage.apply(need_restore=False): + for param in linear.parameters(): + print(param) + + for param in linear.parameters(): + print(param) + + modelaverage.restore() + + for param in linear.parameters(): + print(param) + """ + if framework._non_static_mode(): + for param in self._parameter_list: + param_restore = self._get_accumulator('restore', param) + paddle.assign(param_restore, param) + return + if executor is None: + raise RuntimeError( + "Executor should not be None in static graph mode." + ) + executor.run(self.restore_program) + + def _add_average_apply_op(self, block, param): + param = block._clone_variable(param) + grad = block._clone_variable(self._get_accumulator('restore', param)) + sum_1 = block._clone_variable(self._get_accumulator('sum_1', param)) + sum_2 = block._clone_variable(self._get_accumulator('sum_2', param)) + sum_3 = block._clone_variable(self._get_accumulator('sum_3', param)) + num_accumulates = block._clone_variable( + self._get_accumulator('num_accumulates', param) + ) + old_num_accumulates = block._clone_variable( + self._get_accumulator('old_num_accumulates', param) + ) + # backup param value to grad + layers.assign(input=param, output=grad) + # param = (sum_1 + sum_2 + sum_3) / (num_accumulates + old_num_accumulates) + tmp = layers.sum(x=[num_accumulates, old_num_accumulates]) + sum = layers.sum(x=[sum_1, sum_2, sum_3]) + tmp = layers.cast( + x=tmp, dtype='float32' if self._dtype is None else self._dtype + ) + sum = layers.cast( + x=sum, dtype='float32' if self._dtype is None else self._dtype + ) + layers.ops._elementwise_div(x=sum, y=tmp, out=param) + + def _add_average_restore_op(self, block, param): + param = block._clone_variable(param) + grad = block._clone_variable(self._get_accumulator('restore', param)) + layers.assign(input=grad, output=param) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba160fcc405544a74aa4a387e2fd0bffa4055831 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2021 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/fuse_resnet_unit_pass.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/fuse_resnet_unit_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..451ea1908f910d02c1eded6565495f1930eed246 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/passes/fuse_resnet_unit_pass.py @@ -0,0 +1,109 @@ +# Copyright (c) 2021 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. + +import paddle +import paddle.fluid.ir as ir + + +def set_resnet_unit_attrs(resnet_unit, has_shortcut): + resnet_unit.SetAttr("fuse_add", False) + resnet_unit.SetAttr("act_type", "relu") + resnet_unit.SetAttr("has_shortcut", has_shortcut) + resnet_unit.SetAttr("data_format", 'NHWC') + resnet_unit.SetAttr("dilation", 1) + resnet_unit.Attr("stride").MappedPattern(op="conv2d", + name="strides", + element_index=0) + resnet_unit.Attr("padding").MappedPattern(op="conv2d", + name="paddings", + element_index=0) + resnet_unit.Attr("group").MappedPattern(op="conv2d", name="groups") + resnet_unit.Attr("op_device").MappedPattern(op="conv2d", name="op_device") + resnet_unit.Attr("op_namescope").MappedPattern(op="conv2d", + name="op_namescope") + resnet_unit.Attr("momentum").MappedPattern(op="batch_norm", name="momentum") + resnet_unit.Attr("epsilon").MappedPattern(op="batch_norm", name="epsilon") + resnet_unit.Attr("use_global_stats").MappedPattern(op="batch_norm", + name="use_global_stats") + + +def set_resnet_unit_outputs(resnet_unit, meanX, varX, meanZ=None, varZ=None): + resnet_unit.SetOutputs(RunningMeanX=meanX, + RunningVarX=varX, + RunningMeanZ=meanZ, + RunningVarZ=varZ) + + +@ir.RegisterPass +def fuse_resnet_unit(): + + def pattern_conv_bn(x, filter, scale, bias, mean, var): + filter.Attr("shape")[0].Mod(32).EQ(0) + filter.Attr("shape")[1].Mod(8).EQ(0) + filter.Attr("shape")[2].EQ(1) + filter.Attr("shape")[3].EQ(1) + conv2d = ir.PassDesc.OP.conv2d(Input=x, Filter=filter) + conv2d.SetAttr("data_format", 'NHWC') + bn = ir.PassDesc.OP.batch_norm(X=conv2d, + Bias=bias, + Mean=mean, + Scale=scale, + Variance=var) + return bn + + def pattern_one_input(x, filter, scale, bias, mean, var): + bn = pattern_conv_bn(x, filter, scale, bias, mean, var) + relu = ir.PassDesc.OP.relu(X=bn.Output("Y")) + return relu + + def replace_one_input(x, filter, scale, bias, mean, var): + resnet_unit = ir.PassDesc.OP.resnet_unit(X=x, + FilterX=filter, + ScaleX=scale, + BiasX=bias, + MeanX=mean, + VarX=var) + set_resnet_unit_attrs(resnet_unit, False) + set_resnet_unit_outputs(resnet_unit, mean, var) + return resnet_unit.Output("Y") + + def pattern_two_input(x, filterX, scaleX, biasX, meanX, varX, z, filterZ, + scaleZ, biasZ, meanZ, varZ): + bnX = pattern_conv_bn(x, filterX, scaleX, biasX, meanX, varX) + bnZ = pattern_conv_bn(x, filterZ, scaleZ, biasZ, meanZ, varZ) + ewadd = ir.PassDesc.OP.elementwise_add(X=bnX.Output("Y"), + Y=bnZ.Output("Y")) + relu = ir.PassDesc.OP.relu(X=ewadd) + return relu + + def replace_two_input(x, filterX, scaleX, biasX, meanX, varX, z, filterZ, + scaleZ, biasZ, meanZ, varZ): + resnet_unit = ir.PassDesc.OP.resnet_unit(X=x, + FilterX=filterX, + ScaleX=scaleX, + BiasX=biasX, + MeanX=meanX, + VarX=varX, + Z=z, + FilterZ=filterZ, + ScaleZ=scaleZ, + BiasZ=biasZ, + MeanZ=meanZ, + VarZ=varZ) + set_resnet_unit_attrs(resnet_unit, True) + set_resnet_unit_outputs(resnet_unit, meanX, varX, meanZ, varZ) + return resnet_unit.Output("Y") + + return (pattern_one_input, replace_one_input), (pattern_two_input, + replace_two_input) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01dfab4482d66c505f9fa212093022e2e65fa627 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2021 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. + +from .math import segment_sum +from .math import segment_mean +from .math import segment_max +from .math import segment_min + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/math.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/math.py new file mode 100644 index 0000000000000000000000000000000000000000..745df5fccf7512fec00f7f37b6d6692484a49b51 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/tensor/math.py @@ -0,0 +1,284 @@ +# Copyright (c) 2021 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. + +from paddle.fluid.layer_helper import LayerHelper, _non_static_mode +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode +import paddle.utils.deprecated as deprecated + +__all__ = [] + + +@deprecated(since="2.4.0", + update_to="paddle.geometric.segment_sum", + level=1, + reason="paddle.incubate.segment_sum will be removed in future") +def segment_sum(data, segment_ids, name=None): + r""" + Segment Sum Operator. + + This operator sums the elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\sum_{j} data_{j}$ + where sum is over j such that `segment_ids[j] == i`. + + Args: + data (Tensor): A tensor, available data type float32, float64, int32, int64. + segment_ids (Tensor): A 1-D tensor, which have the same size + with the first dimension of input data. + Available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): the reduced result. + + Examples: + + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.incubate.segment_sum(data, segment_ids) + #Outputs: [[4., 4., 4.], [4., 5., 6.]] + + """ + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "SUM")[0] + if _in_legacy_dygraph(): + out, tmp = _legacy_C_ops.segment_pool(data, segment_ids, 'pooltype', + "SUM") + return out + + check_variable_and_dtype(data, "X", + ("float32", "float64", "int32", "int64"), + "segment_pool") + check_variable_and_dtype(segment_ids, "SegmentIds", ("int32", "int64"), + "segment_pool") + + helper = LayerHelper("segment_sum", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op(type="segment_pool", + inputs={ + "X": data, + "SegmentIds": segment_ids + }, + outputs={ + "Out": out, + "SummedIds": summed_ids + }, + attrs={"pooltype": "SUM"}) + return out + + +@deprecated(since="2.4.0", + update_to="paddle.geometric.segment_mean", + level=1, + reason="paddle.incubate.segment_mean will be removed in future") +def segment_mean(data, segment_ids, name=None): + r""" + Segment mean Operator. + + Ihis operator calculate the mean value of input `data` which + with the same index in `segment_ids`. + It computes a tensor such that $out_i = \\frac{1}{n_i} \\sum_{j} data[j]$ + where sum is over j such that 'segment_ids[j] == i' and $n_i$ is the number + of all index 'segment_ids[j] == i'. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): the reduced result. + + Examples: + + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.incubate.segment_mean(data, segment_ids) + #Outputs: [[2., 2., 2.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "MEAN")[0] + if _non_static_mode(): + out, tmp = _legacy_C_ops.segment_pool(data, segment_ids, 'pooltype', + "MEAN") + return out + + check_variable_and_dtype(data, "X", + ("float32", "float64", "int32", "int64"), + "segment_pool") + check_variable_and_dtype(segment_ids, "SegmentIds", ("int32", "int64"), + "segment_pool") + + helper = LayerHelper("segment_mean", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op(type="segment_pool", + inputs={ + "X": data, + "SegmentIds": segment_ids + }, + outputs={ + "Out": out, + "SummedIds": summed_ids + }, + attrs={"pooltype": "MEAN"}) + return out + + +@deprecated(since="2.4.0", + update_to="paddle.geometric.segment_min", + level=1, + reason="paddle.incubate.segment_min will be removed in future") +def segment_min(data, segment_ids, name=None): + r""" + Segment min operator. + + This operator calculate the minimum elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\min_{j} data_{j}$ + where min is over j such that `segment_ids[j] == i`. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): the reduced result. + + Examples: + + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.incubate.segment_min(data, segment_ids) + #Outputs: [[1., 2., 1.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + return _C_ops.segment_pool(data, segment_ids, "MIN")[0] + + if _non_static_mode(): + out, tmp = _legacy_C_ops.segment_pool(data, segment_ids, 'pooltype', + "MIN") + return out + + check_variable_and_dtype(data, "X", + ("float32", "float64", "int32", "int64"), + "segment_pool") + check_variable_and_dtype(segment_ids, "SegmentIds", ("int32", "int64"), + "segment_pool") + + helper = LayerHelper("segment_min", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op(type="segment_pool", + inputs={ + "X": data, + "SegmentIds": segment_ids + }, + outputs={ + "Out": out, + "SummedIds": summed_ids + }, + attrs={"pooltype": "MIN"}) + return out + + +@deprecated(since="2.4.0", + update_to="paddle.geometric.segment_max", + level=1, + reason="paddle.incubate.segment_max will be removed in future") +def segment_max(data, segment_ids, name=None): + r""" + Segment max operator. + + This operator calculate the maximum elements of input `data` which with + the same index in `segment_ids`. + It computes a tensor such that $out_i = \\max_{j} data_{j}$ + where max is over j such that `segment_ids[j] == i`. + + Args: + data (tensor): a tensor, available data type float32, float64, int32, int64. + segment_ids (tensor): a 1-d tensor, which have the same size + with the first dimension of input data. + available data type is int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): the reduced result. + + Examples: + + .. code-block:: python + + import paddle + data = paddle.to_tensor([[1, 2, 3], [3, 2, 1], [4, 5, 6]], dtype='float32') + segment_ids = paddle.to_tensor([0, 0, 1], dtype='int32') + out = paddle.incubate.segment_max(data, segment_ids) + #Outputs: [[3., 2., 3.], [4., 5., 6.]] + + """ + + if in_dygraph_mode(): + out, tmp = _C_ops.segment_pool(data, segment_ids, "MAX") + return out + + if _non_static_mode(): + out, tmp = _legacy_C_ops.segment_pool(data, segment_ids, 'pooltype', + "MAX") + return out + + check_variable_and_dtype(data, "X", + ("float32", "float64", "int32", "int64"), + "segment_pool") + check_variable_and_dtype(segment_ids, "SegmentIds", ("int32", "int64"), + "segment_pool") + + helper = LayerHelper("segment_max", **locals()) + out = helper.create_variable_for_type_inference(dtype=data.dtype) + summed_ids = helper.create_variable_for_type_inference(dtype=data.dtype) + helper.append_op(type="segment_pool", + inputs={ + "X": data, + "SegmentIds": segment_ids + }, + outputs={ + "Out": out, + "SummedIds": summed_ids + }, + attrs={"pooltype": "MAX"}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33a93b00f51daf574c7dadbed7de3fc3be0b4cbf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2022 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. + +from .resnet_block import ResNetBasicBlock diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/resnet_block.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/resnet_block.py new file mode 100644 index 0000000000000000000000000000000000000000..6c83f5bda498ab3a688378ed0006c82d91fe3e0d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/incubate/xpu/resnet_block.py @@ -0,0 +1,718 @@ +# Copyright (c) 2022 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. + +import copy +import collections +import itertools +import six +import math +import sys +import warnings +from functools import partial, reduce + +import numpy as np +import paddle +import paddle.fluid as fluid +from paddle import framework +from paddle.nn import initializer as I +from paddle.nn import Layer, LayerList +from paddle.fluid.layers import utils +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.data_feeder import convert_dtype +from paddle.fluid.param_attr import ParamAttr +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['resnet_basic_block', 'ResNetBasicBlock'] + + +def resnet_basic_block( + x, + filter1, + scale1, + bias1, + mean1, + var1, + filter2, + scale2, + bias2, + mean2, + var2, + filter3, + scale3, + bias3, + mean3, + var3, + stride1, + stride2, + stride3, + padding1, + padding2, + padding3, + dilation1, + dilation2, + dilation3, + groups, + momentum, + eps, + data_format, + has_shortcut, + use_global_stats=None, + training=False, + trainable_statistics=False, + find_conv_max=True, +): + + if fluid.framework.in_dygraph_mode(): + attrs = ( + 'stride1', + stride1, + 'stride2', + stride2, + 'stride3', + stride3, + 'padding1', + padding1, + 'padding2', + padding2, + 'padding3', + padding3, + 'dilation1', + dilation1, + 'dilation2', + dilation2, + 'dilation3', + dilation3, + 'group', + groups, + 'momentum', + momentum, + 'epsilon', + eps, + 'data_format', + data_format, + 'has_shortcut', + has_shortcut, + 'use_global_stats', + use_global_stats, + "trainable_statistics", + trainable_statistics, + 'is_test', + not training, + 'act_type', + "relu", + 'find_conv_input_max', + find_conv_max, + ) + + ( + out, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + _, + ) = getattr(_C_ops, "resnet_basic_block")( + x, + filter1, + scale1, + bias1, + mean1, + var1, + filter2, + scale2, + bias2, + mean2, + var2, + filter3, + scale3, + bias3, + mean3, + var3, + mean1, + var1, + mean2, + var2, + mean3, + var3, + *attrs + ) + return out + helper = LayerHelper('resnet_basic_block', **locals()) + bn_param_dtype = fluid.core.VarDesc.VarType.FP32 + max_dtype = fluid.core.VarDesc.VarType.FP32 + + out = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + conv1 = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + saved_mean1 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + saved_invstd1 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + running_mean1 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if mean1 is None + else mean1 + ) + running_var1 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if var1 is None + else var1 + ) + conv2 = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + conv2_input = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + saved_mean2 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + saved_invstd2 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + running_mean2 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if mean2 is None + else mean2 + ) + running_var2 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if var2 is None + else var2 + ) + conv3 = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + saved_mean3 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + saved_invstd3 = helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + running_mean3 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if mean3 is None + else mean3 + ) + running_var3 = ( + helper.create_variable_for_type_inference( + dtype=bn_param_dtype, stop_gradient=True + ) + if var3 is None + else var3 + ) + conv1_input_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + conv1_filter_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + conv2_input_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + conv2_filter_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + conv3_input_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + conv3_filter_max = helper.create_variable_for_type_inference( + dtype=max_dtype, stop_gradient=True + ) + + inputs = { + 'X': x, + 'Filter1': filter1, + 'Scale1': scale1, + 'Bias1': bias1, + 'Mean1': mean1, + 'Var1': var1, + 'Filter2': filter2, + 'Scale2': scale2, + 'Bias2': bias2, + 'Mean2': mean2, + 'Var2': var2, + 'Filter3': filter3, + 'Scale3': scale3, + 'Bias3': bias3, + 'Mean3': mean3, + 'Var3': var3, + } + + attrs = { + 'stride1': stride1, + 'stride2': stride2, + 'stride3': stride3, + 'padding1': padding1, + 'padding2': padding2, + 'padding3': padding3, + 'dilation1': dilation1, + 'dilation2': dilation2, + 'dilation3': dilation3, + 'group': groups, + 'momentum': momentum, + 'epsilon': eps, + 'data_format': data_format, + 'has_shortcut': has_shortcut, + 'use_global_stats': use_global_stats, + "trainable_statistics": trainable_statistics, + 'is_test': not training, + 'act_type': "relu", + 'find_conv_input_max': find_conv_max, + } + + outputs = { + 'Y': out, + 'Conv1': conv1, + 'SavedMean1': saved_mean1, + 'SavedInvstd1': saved_invstd1, + 'Mean1Out': running_mean1, + 'Var1Out': running_var1, + 'Conv2': conv2, + 'SavedMean2': saved_mean2, + 'SavedInvstd2': saved_invstd2, + 'Mean2Out': running_mean2, + 'Var2Out': running_var2, + 'Conv2Input': conv2_input, + 'Conv3': conv3, + 'SavedMean3': saved_mean3, + 'SavedInvstd3': saved_invstd3, + 'Mean3Out': running_mean3, + 'Var3Out': running_var3, + 'MaxInput1': conv1_input_max, + 'MaxFilter1': conv1_filter_max, + 'MaxInput2': conv2_input_max, + 'MaxFilter2': conv2_filter_max, + 'MaxInput3': conv3_input_max, + 'MaxFilter3': conv3_filter_max, + } + helper.append_op( + type='resnet_basic_block', inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +class ResNetBasicBlock(Layer): + r""" + + ResNetBasicBlock is designed for optimize the performence of the basic unit of ssd resnet block. + If has_shortcut = True, it can calculate 3 Conv2D, 3 BatchNorm and 2 ReLU in one time. + If has_shortcut = False, it can calculate 2 Conv2D, 2 BatchNorm and 2 ReLU in one time. In this + case the shape of output is same with input. + + + Args: + num_channels (int): The number of input image channel. + num_filter (int): The number of filter. It is as same as the output image channel. + filter_size (int|list|tuple): The filter size. If filter_size + is a tuple, it must contain two integers, (filter_size_height, + filter_size_width). Otherwise, filter_size_height = filter_size_width =\ + filter_size. + stride (int, optional): The stride size. It means the stride in convolution. + If stride is a tuple, it must contain two integers, (stride_height, stride_width). + Otherwise, stride_height = stride_width = stride. Default: stride = 1. + act (str, optional): Activation type, if it is set to None, activation is not appended. + Default: None + momentum (float, optional): The value used for the moving_mean and + moving_var computation. This should be a float number or a Tensor with + shape [1] and data type as float32. The updated formula is: + :math:`moving\_mean = moving\_mean * momentum + new\_mean * (1. - momentum)` + :math:`moving\_var = moving\_var * momentum + new\_var * (1. - momentum)` + Default is 0.9. + eps (float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. Now is only support `"NCHW"`, the data is stored in + the order of: `[batch_size, input_channels, input_height, input_width]`. + has_shortcut (bool, optional): Whether to calculate CONV3 and BN3. Default: False. + use_global_stats (bool, optional): Whether to use global mean and + variance. In inference or test mode, set use_global_stats to true + or is_test to true, and the behavior is equivalent. + In train mode, when setting use_global_stats True, the global mean + and variance are also used during train period. Default: False. + is_test (bool, optional): A flag indicating whether it is in + test phrase or not. Default: False. + filter_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. Default: None. + scale_attr (ParamAttr, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm will create ParamAttr + as param_attr, the name of scale can be set in ParamAttr. If the Initializer of the param_attr is not set, + the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + Default: None. + moving_mean_name (str, optional): The name of moving_mean which store the global Mean. If it + is set to None, batch_norm will save global mean with a random name, otherwise, batch_norm + will save global mean with the string. Default: None. + moving_var_name (str, optional): The name of the moving_variance which store the global Variance. + If it is set to None, batch_norm will save global variance with a random name, otherwise, batch_norm + will save global variance with the string. Default: None. + padding (int, optional): The padding size. It is only spupport padding_height = padding_width = padding. + Default: padding = 0. + dilation (int, optional): The dilation size. It means the spacing between the kernel + points. It is only spupport dilation_height = dilation_width = dilation. + Default: dilation = 1. + trainable_statistics (bool, optional): Whether to calculate mean and var in eval mode. In eval mode, when + setting trainable_statistics True, mean and variance will be calculated by current batch statistics. + Default: False. + find_conv_max (bool, optional): Whether to calculate max value of each conv2d. Default: True. + + + Returns: + A Tensor representing the ResNetBasicBlock, whose data type is the same with input. + + + Examples: + .. code-block:: python + + # required: xpu + import paddle + from paddle.incubate.xpu.resnet_block import ResNetBasicBlock + + ch_in = 4 + ch_out = 8 + x = paddle.uniform((2, ch_in, 16, 16), dtype='float32', min=-1., max=1.) + resnet_basic_block = ResNetBasicBlock(num_channels1=ch_in, + num_filter1=ch_out, + filter1_size=3, + num_channels2=ch_out, + num_filter2=ch_out, + filter2_size=3, + num_channels3=ch_in, + num_filter3=ch_out, + filter3_size=1, + stride1=1, + stride2=1, + stride3=1, + act='relu', + padding1=1, + padding2=1, + padding3=0, + has_shortcut=True) + out = resnet_basic_block.forward(x) + + print(out.shape) # [2, 8, 16, 16] + + """ + + def __init__( + self, + num_channels1, + num_filter1, + filter1_size, + num_channels2, + num_filter2, + filter2_size, + num_channels3, + num_filter3, + filter3_size, + stride1=1, + stride2=1, + stride3=1, + act='relu', + momentum=0.9, + eps=1e-5, + data_format='NCHW', + has_shortcut=False, + use_global_stats=False, + is_test=False, + filter1_attr=None, + scale1_attr=None, + bias1_attr=None, + moving_mean1_name=None, + moving_var1_name=None, + filter2_attr=None, + scale2_attr=None, + bias2_attr=None, + moving_mean2_name=None, + moving_var2_name=None, + filter3_attr=None, + scale3_attr=None, + bias3_attr=None, + moving_mean3_name=None, + moving_var3_name=None, + padding1=0, + padding2=0, + padding3=0, + dilation1=1, + dilation2=1, + dilation3=1, + trainable_statistics=False, + find_conv_max=True, + ): + super(ResNetBasicBlock, self).__init__() + self._stride1 = stride1 + self._stride2 = stride2 + self._kernel1_size = utils.convert_to_list( + filter1_size, 2, 'filter1_size' + ) + self._kernel2_size = utils.convert_to_list( + filter2_size, 2, 'filter2_size' + ) + self._dilation1 = dilation1 + self._dilation2 = dilation2 + self._padding1 = padding1 + self._padding2 = padding2 + self._groups = 1 + self._momentum = momentum + self._eps = eps + self._data_format = data_format + self._act = act + self._has_shortcut = has_shortcut + self._use_global_stats = use_global_stats + self._is_test = is_test + self._trainable_statistics = trainable_statistics + self._find_conv_max = find_conv_max + + if has_shortcut: + self._kernel3_size = utils.convert_to_list( + filter3_size, 2, 'filter3_size' + ) + self._padding3 = padding3 + self._stride3 = stride3 + self._dilation3 = dilation3 + else: + self._kernel3_size = None + self._padding3 = 1 + self._stride3 = 1 + self._dilation3 = 1 + + # check format + valid_format = {'NCHW'} + if data_format not in valid_format: + raise ValueError( + "conv_format must be one of {}, but got conv_format={}".format( + valid_format, data_format + ) + ) + + def _get_default_param_initializer(channels, kernel_size): + filter_elem_num = np.prod(kernel_size) * channels + std = (2.0 / filter_elem_num) ** 0.5 + return I.Normal(0.0, std) + + # init filter + bn_param_dtype = fluid.core.VarDesc.VarType.FP32 + bn1_param_shape = [1, 1, num_filter1] + bn2_param_shape = [1, 1, num_filter2] + filter1_shape = [num_filter1, num_channels1, filter1_size, filter1_size] + filter2_shape = [num_filter2, num_channels2, filter2_size, filter2_size] + + self.filter_1 = self.create_parameter( + shape=filter1_shape, + attr=filter1_attr, + default_initializer=_get_default_param_initializer( + num_channels1, self._kernel1_size + ), + ) + self.scale_1 = self.create_parameter( + shape=bn1_param_shape, + attr=scale1_attr, + dtype=bn_param_dtype, + default_initializer=I.Constant(1.0), + ) + self.bias_1 = self.create_parameter( + shape=bn1_param_shape, + attr=bias1_attr, + dtype=bn_param_dtype, + is_bias=True, + ) + self.mean_1 = self.create_parameter( + attr=ParamAttr( + name=moving_mean1_name, + initializer=I.Constant(0.0), + trainable=False, + ), + shape=bn1_param_shape, + dtype=bn_param_dtype, + ) + self.mean_1.stop_gradient = True + self.var_1 = self.create_parameter( + attr=ParamAttr( + name=moving_var1_name, + initializer=I.Constant(1.0), + trainable=False, + ), + shape=bn1_param_shape, + dtype=bn_param_dtype, + ) + self.var_1.stop_gradient = True + + self.filter_2 = self.create_parameter( + shape=filter2_shape, + attr=filter2_attr, + default_initializer=_get_default_param_initializer( + num_channels2, self._kernel2_size + ), + ) + self.scale_2 = self.create_parameter( + shape=bn2_param_shape, + attr=scale2_attr, + dtype=bn_param_dtype, + default_initializer=I.Constant(1.0), + ) + self.bias_2 = self.create_parameter( + shape=bn2_param_shape, + attr=bias2_attr, + dtype=bn_param_dtype, + is_bias=True, + ) + self.mean_2 = self.create_parameter( + attr=ParamAttr( + name=moving_mean2_name, + initializer=I.Constant(0.0), + trainable=False, + ), + shape=bn2_param_shape, + dtype=bn_param_dtype, + ) + self.mean_2.stop_gradient = True + self.var_2 = self.create_parameter( + attr=ParamAttr( + name=moving_var2_name, + initializer=I.Constant(1.0), + trainable=False, + ), + shape=bn2_param_shape, + dtype=bn_param_dtype, + ) + self.var_2.stop_gradient = True + + if has_shortcut: + bn3_param_shape = [1, 1, num_filter3] + filter3_shape = [ + num_filter3, + num_channels3, + filter3_size, + filter3_size, + ] + self.filter_3 = self.create_parameter( + shape=filter3_shape, + attr=filter3_attr, + default_initializer=_get_default_param_initializer( + num_channels3, self._kernel3_size + ), + ) + self.scale_3 = self.create_parameter( + shape=bn3_param_shape, + attr=scale3_attr, + dtype=bn_param_dtype, + default_initializer=I.Constant(1.0), + ) + self.bias_3 = self.create_parameter( + shape=bn3_param_shape, + attr=bias3_attr, + dtype=bn_param_dtype, + is_bias=True, + ) + self.mean_3 = self.create_parameter( + attr=ParamAttr( + name=moving_mean3_name, + initializer=I.Constant(0.0), + trainable=False, + ), + shape=bn3_param_shape, + dtype=bn_param_dtype, + ) + self.mean_3.stop_gradient = True + self.var_3 = self.create_parameter( + attr=ParamAttr( + name=moving_var3_name, + initializer=I.Constant(1.0), + trainable=False, + ), + shape=bn3_param_shape, + dtype=bn_param_dtype, + ) + self.var_3.stop_gradient = True + else: + self.filter_3 = None + self.scale_3 = None + self.bias_3 = None + self.mean_3 = None + self.var_3 = None + + def forward(self, x): + out = resnet_basic_block( + x, + self.filter_1, + self.scale_1, + self.bias_1, + self.mean_1, + self.var_1, + self.filter_2, + self.scale_2, + self.bias_2, + self.mean_2, + self.var_2, + self.filter_3, + self.scale_3, + self.bias_3, + self.mean_3, + self.var_3, + self._stride1, + self._stride2, + self._stride3, + self._padding1, + self._padding2, + self._padding3, + self._dilation1, + self._dilation2, + self._dilation3, + self._groups, + self._momentum, + self._eps, + self._data_format, + self._has_shortcut, + use_global_stats=self._use_global_stats, + training=self.training, + trainable_statistics=self._trainable_statistics, + find_conv_max=self._find_conv_max, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e033a366d9ae81952e88aeae71a19b379f6cd9e4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/__init__.py @@ -0,0 +1,35 @@ +# 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. + +from ..fluid.inference import Config # noqa: F401 +from ..fluid.inference import DataType # noqa: F401 +from ..fluid.inference import PlaceType # noqa: F401 +from ..fluid.inference import PrecisionType # noqa: F401 +from ..fluid.inference import Tensor # noqa: F401 +from ..fluid.inference import Predictor # noqa: F401 +from ..fluid.inference import create_predictor # noqa: F401 +from ..fluid.inference import _get_phi_kernel_name +from ..fluid.inference import get_version # noqa: F401 +from ..fluid.inference import get_trt_compile_version # noqa: F401 +from ..fluid.inference import get_trt_runtime_version # noqa: F401 +from ..fluid.inference import convert_to_mixed_precision # noqa: F401 +from ..fluid.inference import get_num_bytes_of_data_type # noqa: F401 +from ..fluid.inference import PredictorPool # noqa: F401 + +__all__ = [ # noqa + 'Config', 'DataType', 'PlaceType', 'PrecisionType', 'Tensor', 'Predictor', + 'create_predictor', 'get_version', '_get_phi_kernel_name', + 'get_trt_compile_version', 'convert_to_mixed_precision', + 'get_trt_runtime_version', 'get_num_bytes_of_data_type', 'PredictorPool' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0ea85344b7e0c679730356928c8749cf71cd66 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) 2021 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5252504925073ca22b70f95dfd3bd99a69fb98 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/inference/contrib/utils/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2021 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. + +from ....fluid.core import copy_tensor # noqa: F401 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/io/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87acda904b5dae6251d72cd0f371286c0b94d1df --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/io/__init__.py @@ -0,0 +1,38 @@ +# 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. + +# TODO: define all functions about input & output in this directory + +from ..fluid.io import DataLoader # noqa: F401 +from ..fluid.dataloader import Dataset # noqa: F401 +from ..fluid.dataloader import IterableDataset # noqa: F401 +from ..fluid.dataloader import BatchSampler # noqa: F401 +from ..fluid.dataloader import get_worker_info # noqa: F401 +from ..fluid.dataloader import TensorDataset # noqa: F401 +from ..fluid.dataloader import Sampler # noqa: F401 +from ..fluid.dataloader import SequenceSampler # noqa: F401 +from ..fluid.dataloader import RandomSampler # noqa: F401 +from ..fluid.dataloader import DistributedBatchSampler # noqa: F401 +from ..fluid.dataloader import ComposeDataset # noqa: F401 +from ..fluid.dataloader import ChainDataset # noqa: F401 +from ..fluid.dataloader import WeightedRandomSampler # noqa: F401 +from ..fluid.dataloader import Subset # noqa: F401 +from ..fluid.dataloader import random_split # noqa: F401 + +__all__ = [ #noqa + 'Dataset', 'IterableDataset', 'TensorDataset', 'ComposeDataset', + 'ChainDataset', 'BatchSampler', 'DistributedBatchSampler', 'DataLoader', + 'get_worker_info', 'Sampler', 'SequenceSampler', 'RandomSampler', + 'WeightedRandomSampler', 'random_split', 'Subset' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a31dad82e0536ecef9c03a8d31230820ec6b510 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/__init__.py @@ -0,0 +1,33 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from __future__ import print_function + +from ..fluid.dygraph.jit import save # noqa: F401 +from ..fluid.dygraph.jit import load # noqa: F401 +from ..fluid.dygraph.jit import TracedLayer # noqa: F401 +from ..fluid.dygraph.jit import set_code_level # noqa: F401 +from ..fluid.dygraph.jit import set_verbosity # noqa: F401 +from ..fluid.dygraph.jit import declarative as to_static # noqa: F401 +from ..fluid.dygraph.jit import not_to_static # noqa: F401 +from ..fluid.dygraph import ProgramTranslator # noqa: F401 +from ..fluid.dygraph.io import TranslatedLayer # noqa: F401 + +from . import dy2static # noqa: F401 + +__all__ = [ # noqa + 'save', 'load', 'TracedLayer', 'to_static', 'ProgramTranslator', + 'TranslatedLayer', 'set_code_level', 'set_verbosity', 'not_to_static' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8cfc2ee6a36acda667626e86cc51c78ff946dbd8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/__init__.py @@ -0,0 +1,36 @@ +# 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. + +from .base import saw +from .base import UndefinedVar +from .convert_operators import convert_logical_and as And # noqa: F401 +from .convert_operators import convert_var_dtype as AsDtype # noqa: F401 +from .convert_operators import convert_assert as Assert # noqa: F401 +from .convert_call_func import convert_call as Call # noqa: F401 +from .convert_operators import convert_ifelse as IfElse # noqa: F401 +from .convert_operators import convert_len as Len # noqa: F401 +from .convert_operators import convert_logical_not as Not # noqa: F401 +from .convert_operators import convert_logical_or as Or # noqa: F401 +from .convert_operators import convert_pop as Pop # noqa: F401 +from .convert_operators import convert_print as Print # noqa: F401 +from .convert_operators import convert_shape as Shape # noqa: F401 +from .convert_operators import convert_while_loop as While # noqa: F401 +from .convert_operators import unpack_by_structure as Unpack # noqa: F401 +from .convert_operators import convert_attr as Attr # noqa: F401 +from .convert_operators import indexable as Indexable # noqa: F401 +from .variable_trans_func import create_bool_as_type # noqa: F401 +from .variable_trans_func import to_static_variable # noqa: F401 +from .convert_operators import convert_shape_compare # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/base.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8b902f386174c9fd94225c5f136a380f35cd5e14 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/base.py @@ -0,0 +1,19 @@ +# 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. +from __future__ import print_function + +from ...fluid.dygraph.dygraph_to_static.utils import saw # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.utils import UndefinedVar # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_call_func.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_call_func.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6197a3cba6ae811998def0d59a221d2265ce0c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_call_func.py @@ -0,0 +1,18 @@ +# 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. +from __future__ import print_function + +from ...fluid.dygraph.dygraph_to_static.convert_call_func import convert_call # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_operators.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..fd809768e08ce817b5a91d3b1237371da656219a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/convert_operators.py @@ -0,0 +1,31 @@ +# 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. +from __future__ import print_function + +from ...fluid.dygraph.dygraph_to_static.convert_operators import cast_bool_if_necessary # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_assert # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_ifelse # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_len # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_logical_and # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_logical_not # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_logical_or # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_pop # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_print # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_shape_compare # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_var_dtype # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_shape # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import convert_while_loop # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.convert_operators import unpack_by_structure, indexable, convert_attr # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/variable_trans_func.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/variable_trans_func.py new file mode 100644 index 0000000000000000000000000000000000000000..49a0d6a31e5914a5d166339e984171e981008abb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/dy2static/variable_trans_func.py @@ -0,0 +1,20 @@ +# 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. + +from __future__ import print_function + +from ...fluid.dygraph.dygraph_to_static.variable_trans_func import create_bool_as_type # noqa: F401 +from ...fluid.dygraph.dygraph_to_static.variable_trans_func import to_static_variable # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/layer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..97b598948500b1772656bfc4bd9154caa1e6078e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/jit/layer.py @@ -0,0 +1,53 @@ +# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from paddle.fluid import core +from paddle.fluid.core import Load + + +class Layer(object): + + def __init__(self): + self.cpp_layer = None + # {name: Function} + self.functions = {} + + def load(self, load_path, place): + self.cpp_layer = Load(load_path, place) + + for name in self.cpp_layer.function_names(): + function = self.cpp_layer.function(name) + info = self.cpp_layer.function_info(name) + self.functions[name] = Function(function, info) + setattr(self, name, self.functions[name]) + + +class Function(): + + def __init__(self, function, info): + self.function = function + self.info = FunctionInfo(info) + + def __call__(self, *args): + return core.eager.jit_function_call(self.function, args) + + +class FunctionInfo(): + + def __init__(self, info): + self.info = info + + def name(self): + return self.info.name() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libblas.so.3 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libblas.so.3 new file mode 100755 index 0000000000000000000000000000000000000000..0219c8c296ae4fbb56ad59108233ddccf8c464cb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libblas.so.3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aa37a3929095a40a8af3e7578b659ae2b04f3d829539ae9d618ea65a9d3bc3d +size 547096 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.1 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.1 new file mode 100755 index 0000000000000000000000000000000000000000..c5f465f1678fdd57305907126c96dec52bc61522 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78d32e51db90bf1f98e2ea7838f65a6cecbef15fe1019f1c71278417d3c22ba3 +size 36539272 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.2 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.2 new file mode 100755 index 0000000000000000000000000000000000000000..c5f465f1678fdd57305907126c96dec52bc61522 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libdnnl.so.2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78d32e51db90bf1f98e2ea7838f65a6cecbef15fe1019f1c71278417d3c22ba3 +size 36539272 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libgfortran.so.3 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libgfortran.so.3 new file mode 100755 index 0000000000000000000000000000000000000000..a8b220c0ca2ceca6fa9838c0c4c67423f297b23a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libgfortran.so.3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:426eb80df096bcd0b2a821522086ce1aeccf0bf7b9c65197389bc8659b456408 +size 1229288 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libiomp5.so b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libiomp5.so new file mode 100755 index 0000000000000000000000000000000000000000..65baf91d727ffd8c904fa246688217ecf43bb7bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libiomp5.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85d288e9799382766377a042b1d2f8044bb0a0af76ed6ff19b41f27a2029414e +size 1932448 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/liblapack.so.3 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/liblapack.so.3 new file mode 100755 index 0000000000000000000000000000000000000000..d2c1694fa13e308b9f31ce63841ca534f7685eae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/liblapack.so.3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fb4dcb814e6f242dedc6fc9d3d6887a9d39c42eff1822d820c783fe00b7356d +size 9546272 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmkldnn.so.0 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmkldnn.so.0 new file mode 100755 index 0000000000000000000000000000000000000000..4e36c89db877d59eee1721eabdef1fc0fd2eaf0f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmkldnn.so.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0079f0c61e671a70dd1807df0e8f7ed51af318e8b8acfed1deb9dba0b8a324b +size 36574424 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmklml_intel.so b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmklml_intel.so new file mode 100755 index 0000000000000000000000000000000000000000..4b7c59a066e3a454498e86e3a53cc16320fcd337 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libmklml_intel.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51fbd95a70504b0c6b7a1fbc316560580a32bf308cca7af4eea7bacd1e0d137b +size 130096544 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libquadmath.so.0 b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libquadmath.so.0 new file mode 100755 index 0000000000000000000000000000000000000000..2ba785abc7b7f452caeeea95b379186d0fe3fc47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libquadmath.so.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96973f995bad4e4b80eaa188b7bac60bd0df44b22ee67bd046b3aa4ecb9e34fd +size 244904 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libwarpctc.so b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libwarpctc.so new file mode 100755 index 0000000000000000000000000000000000000000..6e3aa8b244464aca48505bc5596f6f8b2767f040 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/libs/libwarpctc.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3a8f90627b565d5e6b94b4c2a7308724ddd4588a464349a6c6c5f279c32fe08 +size 38920 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/linalg.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..834b631e5c51981cbf20cec977a135ba78b9d426 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/linalg.py @@ -0,0 +1,65 @@ +# Copyright (c) 2021 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. + +from .tensor.linalg import cholesky # noqa: F401 +from .tensor.linalg import norm # noqa: F401 +from .tensor.linalg import eig # noqa: F401 +from .tensor.linalg import cov # noqa: F401 +from .tensor.linalg import corrcoef # noqa: F401 +from .tensor.linalg import cond # noqa: F401 +from .tensor.linalg import matrix_power # noqa: F401 +from .tensor.linalg import solve # noqa: F401 +from .tensor.linalg import cholesky_solve # noqa: F401 +from .tensor import inverse as inv # noqa: F401 +from .tensor.linalg import eigvals # noqa: F401 +from .tensor.linalg import multi_dot # noqa: F401 +from .tensor.linalg import matrix_rank # noqa: F401 +from .tensor.linalg import svd # noqa: F401 +from .tensor.linalg import eigvalsh # noqa: F401 +from .tensor.linalg import qr # noqa: F401 +from .tensor.linalg import lu # noqa: F401 +from .tensor.linalg import lu_unpack # noqa: F401 +from .tensor.linalg import eigh # noqa: F401 +from .tensor.linalg import det # noqa: F401 +from .tensor.linalg import slogdet # noqa: F401 +from .tensor.linalg import pinv # noqa: F401 +from .tensor.linalg import triangular_solve # noqa: F401 +from .tensor.linalg import lstsq + +__all__ = [ + 'cholesky', #noqa + 'norm', + 'cond', + 'cov', + 'corrcoef', + 'inv', + 'eig', + 'eigvals', + 'multi_dot', + 'matrix_rank', + 'svd', + 'qr', + 'lu', + 'lu_unpack', + 'matrix_power', + 'det', + 'slogdet', + 'eigh', + 'eigvalsh', + 'pinv', + 'solve', + 'cholesky_solve', + 'triangular_solve', + 'lstsq' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70fe075e57744bff725c8ff24b1ff6f4ee6f89fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/__init__.py @@ -0,0 +1,24 @@ +# 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. + +from .metrics import Metric # noqa: F401 +from .metrics import Accuracy # noqa: F401 +from .metrics import Precision # noqa: F401 +from .metrics import Recall # noqa: F401 +from .metrics import Auc # noqa: F401 +from .metrics import accuracy # noqa: F401 + +__all__ = [ #noqa + 'Metric', 'Accuracy', 'Precision', 'Recall', 'Auc', 'accuracy' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/metrics.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..84b18b69e8659e0c7f0d21c69a6f19a04aff275a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/metric/metrics.py @@ -0,0 +1,833 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six +import abc +import numpy as np + +from ..fluid.data_feeder import check_variable_and_dtype +from ..fluid.layer_helper import LayerHelper +from ..fluid.framework import core, _varbase_creator, _non_static_mode, _in_legacy_dygraph +import paddle +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def _is_numpy_(var): + return isinstance(var, (np.ndarray, np.generic)) + + +@six.add_metaclass(abc.ABCMeta) +class Metric(object): + r""" + Base class for metric, encapsulates metric logic and APIs + Usage: + + .. code-block:: text + + m = SomeMetric() + for prediction, label in ...: + m.update(prediction, label) + m.accumulate() + + Advanced usage for :code:`compute`: + + Metric calculation can be accelerated by calculating metric states + from model outputs and labels by build-in operators not by Python/NumPy + in :code:`compute`, metric states will be fetched as NumPy array and + call :code:`update` with states in NumPy format. + Metric calculated as follows (operations in Model and Metric are + indicated with curly brackets, while data nodes not): + + .. code-block:: text + + inputs & labels || ------------------ + | || + {model} || + | || + outputs & labels || + | || tensor data + {Metric.compute} || + | || + metric states(tensor) || + | || + {fetch as numpy} || ------------------ + | || + metric states(numpy) || numpy data + | || + {Metric.update} \/ ------------------ + + Examples: + + For :code:`Accuracy` metric, which takes :code:`pred` and :code:`label` + as inputs, we can calculate the correct prediction matrix between + :code:`pred` and :code:`label` in :code:`compute`. + For examples, prediction results contains 10 classes, while :code:`pred` + shape is [N, 10], :code:`label` shape is [N, 1], N is mini-batch size, + and we only need to calculate accurary of top-1 and top-5, we could + calculate the correct prediction matrix of the top-5 scores of the + prediction of each sample like follows, while the correct prediction + matrix shape is [N, 5]. + + .. code-block:: text + + def compute(pred, label): + # sort prediction and slice the top-5 scores + pred = paddle.argsort(pred, descending=True)[:, :5] + # calculate whether the predictions are correct + correct = pred == label + return paddle.cast(correct, dtype='float32') + + With the :code:`compute`, we split some calculations to OPs (which + may run on GPU devices, will be faster), and only fetch 1 tensor with + shape as [N, 5] instead of 2 tensors with shapes as [N, 10] and [N, 1]. + :code:`update` can be define as follows: + + .. code-block:: text + + def update(self, correct): + accs = [] + for i, k in enumerate(self.topk): + num_corrects = correct[:, :k].sum() + num_samples = len(correct) + accs.append(float(num_corrects) / num_samples) + self.total[i] += num_corrects + self.count[i] += num_samples + return accs + """ + + def __init__(self): + pass + + @abc.abstractmethod + def reset(self): + """ + Reset states and result + """ + raise NotImplementedError( + "function 'reset' not implemented in {}.".format( + self.__class__.__name__)) + + @abc.abstractmethod + def update(self, *args): + """ + Update states for metric + + Inputs of :code:`update` is the outputs of :code:`Metric.compute`, + if :code:`compute` is not defined, the inputs of :code:`update` + will be flatten arguments of **output** of mode and **label** from data: + :code:`update(output1, output2, ..., label1, label2,...)` + + see :code:`Metric.compute` + """ + raise NotImplementedError( + "function 'update' not implemented in {}.".format( + self.__class__.__name__)) + + @abc.abstractmethod + def accumulate(self): + """ + Accumulates statistics, computes and returns the metric value + """ + raise NotImplementedError( + "function 'accumulate' not implemented in {}.".format( + self.__class__.__name__)) + + @abc.abstractmethod + def name(self): + """ + Returns metric name + """ + raise NotImplementedError( + "function 'name' not implemented in {}.".format( + self.__class__.__name__)) + + def compute(self, *args): + """ + This API is advanced usage to accelerate metric calculating, calulations + from outputs of model to the states which should be updated by Metric can + be defined here, where Paddle OPs is also supported. Outputs of this API + will be the inputs of "Metric.update". + + If :code:`compute` is defined, it will be called with **outputs** + of model and **labels** from data as arguments, all outputs and labels + will be concatenated and flatten and each filed as a separate argument + as follows: + :code:`compute(output1, output2, ..., label1, label2,...)` + + If :code:`compute` is not defined, default behaviour is to pass + input to output, so output format will be: + :code:`return output1, output2, ..., label1, label2,...` + + see :code:`Metric.update` + """ + return args + + +class Accuracy(Metric): + """ + Encapsulates accuracy metric logic. + + Args: + topk (list[int]|tuple[int]): Number of top elements to look at + for computing accuracy. Default is (1,). + name (str, optional): String name of the metric instance. Default + is `acc`. + + Example by standalone: + + .. code-block:: python + + import numpy as np + import paddle + + x = paddle.to_tensor(np.array([ + [0.1, 0.2, 0.3, 0.4], + [0.1, 0.4, 0.3, 0.2], + [0.1, 0.2, 0.4, 0.3], + [0.1, 0.2, 0.3, 0.4]])) + y = paddle.to_tensor(np.array([[0], [1], [2], [3]])) + + m = paddle.metric.Accuracy() + correct = m.compute(x, y) + m.update(correct) + res = m.accumulate() + print(res) # 0.75 + + + Example with Model API: + + .. code-block:: python + + import paddle + from paddle.static import InputSpec + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + + input = InputSpec([None, 1, 28, 28], 'float32', 'image') + label = InputSpec([None, 1], 'int64', 'label') + transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])]) + train_dataset = MNIST(mode='train', transform=transform) + + model = paddle.Model(paddle.vision.models.LeNet(), input, label) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + loss=paddle.nn.CrossEntropyLoss(), + metrics=paddle.metric.Accuracy()) + + model.fit(train_dataset, batch_size=64) + + """ + + def __init__(self, topk=(1, ), name=None, *args, **kwargs): + super(Accuracy, self).__init__(*args, **kwargs) + self.topk = topk + self.maxk = max(topk) + self._init_name(name) + self.reset() + + def compute(self, pred, label, *args): + """ + Compute the top-k (maximum value in `topk`) indices. + + Args: + pred (Tensor): The predicted value is a Tensor with dtype + float32 or float64. Shape is [batch_size, d0, ..., dN]. + label (Tensor): The ground truth value is Tensor with dtype + int64. Shape is [batch_size, d0, ..., 1], or + [batch_size, d0, ..., num_classes] in one hot representation. + + Return: + Tensor: Correct mask, a tensor with shape [batch_size, d0, ..., topk]. + """ + pred = paddle.argsort(pred, descending=True) + pred = paddle.slice(pred, + axes=[len(pred.shape) - 1], + starts=[0], + ends=[self.maxk]) + if (len(label.shape) == 1) or \ + (len(label.shape) == 2 and label.shape[-1] == 1): + # In static mode, the real label data shape may be different + # from shape defined by paddle.static.InputSpec in model + # building, reshape to the right shape. + label = paddle.reshape(label, (-1, 1)) + elif label.shape[-1] != 1: + # one-hot label + label = paddle.argmax(label, axis=-1, keepdim=True) + correct = pred == label + return paddle.cast(correct, dtype='float32') + + def update(self, correct, *args): + """ + Update the metrics states (correct count and total count), in order to + calculate cumulative accuracy of all instances. This function also + returns the accuracy of current step. + + Args: + correct: Correct mask, a tensor with shape [batch_size, d0, ..., topk]. + + Return: + Tensor: the accuracy of current step. + """ + if isinstance(correct, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + correct = correct.numpy() + num_samples = np.prod(np.array(correct.shape[:-1])) + accs = [] + for i, k in enumerate(self.topk): + num_corrects = correct[..., :k].sum() + accs.append(float(num_corrects) / num_samples) + self.total[i] += num_corrects + self.count[i] += num_samples + accs = accs[0] if len(self.topk) == 1 else accs + return accs + + def reset(self): + """ + Resets all of the metric state. + """ + self.total = [0.] * len(self.topk) + self.count = [0] * len(self.topk) + + def accumulate(self): + """ + Computes and returns the accumulated metric. + """ + res = [] + for t, c in zip(self.total, self.count): + r = float(t) / c if c > 0 else 0. + res.append(r) + res = res[0] if len(self.topk) == 1 else res + return res + + def _init_name(self, name): + name = name or 'acc' + if self.maxk != 1: + self._name = ['{}_top{}'.format(name, k) for k in self.topk] + else: + self._name = [name] + + def name(self): + """ + Return name of metric instance. + """ + return self._name + + +class Precision(Metric): + """ + Precision (also called positive predictive value) is the fraction of + relevant instances among the retrieved instances. Refer to + https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers + + Noted that this class manages the precision score only for binary + classification task. + + Args: + name (str, optional): String name of the metric instance. + Default is `precision`. + + Example by standalone: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([0.1, 0.5, 0.6, 0.7]) + y = np.array([0, 1, 1, 1]) + + m = paddle.metric.Precision() + m.update(x, y) + res = m.accumulate() + print(res) # 1.0 + + + Example with Model API: + + .. code-block:: python + + import numpy as np + + import paddle + import paddle.nn as nn + + class Data(paddle.io.Dataset): + def __init__(self): + super(Data, self).__init__() + self.n = 1024 + self.x = np.random.randn(self.n, 10).astype('float32') + self.y = np.random.randint(2, size=(self.n, 1)).astype('float32') + + def __getitem__(self, idx): + return self.x[idx], self.y[idx] + + def __len__(self): + return self.n + + model = paddle.Model(nn.Sequential( + nn.Linear(10, 1), + nn.Sigmoid() + )) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + loss=nn.BCELoss(), + metrics=paddle.metric.Precision()) + + data = Data() + model.fit(data, batch_size=16) + """ + + def __init__(self, name='precision', *args, **kwargs): + super(Precision, self).__init__(*args, **kwargs) + self.tp = 0 # true positive + self.fp = 0 # false positive + self._name = name + + def update(self, preds, labels): + """ + Update the states based on the current mini-batch prediction results. + + Args: + preds (numpy.ndarray): The prediction result, usually the output + of two-class sigmoid function. It should be a vector (column + vector or row vector) with data type: 'float64' or 'float32'. + labels (numpy.ndarray): The ground truth (labels), + the shape should keep the same as preds. + The data type is 'int32' or 'int64'. + """ + if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + preds = preds.numpy() + elif not _is_numpy_(preds): + raise ValueError("The 'preds' must be a numpy ndarray or Tensor.") + + if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + labels = labels.numpy() + elif not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray or Tensor.") + + sample_num = labels.shape[0] + preds = np.floor(preds + 0.5).astype("int32") + + for i in range(sample_num): + pred = preds[i] + label = labels[i] + if pred == 1: + if pred == label: + self.tp += 1 + else: + self.fp += 1 + + def reset(self): + """ + Resets all of the metric state. + """ + self.tp = 0 + self.fp = 0 + + def accumulate(self): + """ + Calculate the final precision. + + Returns: + A scaler float: results of the calculated precision. + """ + ap = self.tp + self.fp + return float(self.tp) / ap if ap != 0 else .0 + + def name(self): + """ + Returns metric name + """ + return self._name + + +class Recall(Metric): + """ + Recall (also known as sensitivity) is the fraction of + relevant instances that have been retrieved over the + total amount of relevant instances + + Refer to: + https://en.wikipedia.org/wiki/Precision_and_recall + + Noted that this class manages the recall score only for + binary classification task. + + Args: + name (str, optional): String name of the metric instance. + Default is `recall`. + + Example by standalone: + + .. code-block:: python + + import numpy as np + import paddle + + x = np.array([0.1, 0.5, 0.6, 0.7]) + y = np.array([1, 0, 1, 1]) + + m = paddle.metric.Recall() + m.update(x, y) + res = m.accumulate() + print(res) # 2.0 / 3.0 + + + Example with Model API: + + .. code-block:: python + + import numpy as np + + import paddle + import paddle.nn as nn + + class Data(paddle.io.Dataset): + def __init__(self): + super(Data, self).__init__() + self.n = 1024 + self.x = np.random.randn(self.n, 10).astype('float32') + self.y = np.random.randint(2, size=(self.n, 1)).astype('float32') + + def __getitem__(self, idx): + return self.x[idx], self.y[idx] + + def __len__(self): + return self.n + + model = paddle.Model(nn.Sequential( + nn.Linear(10, 1), + nn.Sigmoid() + )) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + model.prepare( + optim, + loss=nn.BCELoss(), + metrics=[paddle.metric.Precision(), paddle.metric.Recall()]) + + data = Data() + model.fit(data, batch_size=16) + """ + + def __init__(self, name='recall', *args, **kwargs): + super(Recall, self).__init__(*args, **kwargs) + self.tp = 0 # true positive + self.fn = 0 # false negative + self._name = name + + def update(self, preds, labels): + """ + Update the states based on the current mini-batch prediction results. + + Args: + preds(numpy.array): prediction results of current mini-batch, + the output of two-class sigmoid function. + Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'. + labels(numpy.array): ground truth (labels) of current mini-batch, + the shape should keep the same as preds. + Shape: [batch_size, 1], Dtype: 'int32' or 'int64'. + """ + if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + preds = preds.numpy() + elif not _is_numpy_(preds): + raise ValueError("The 'preds' must be a numpy ndarray or Tensor.") + + if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + labels = labels.numpy() + elif not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray or Tensor.") + + sample_num = labels.shape[0] + preds = np.rint(preds).astype("int32") + + for i in range(sample_num): + pred = preds[i] + label = labels[i] + if label == 1: + if pred == label: + self.tp += 1 + else: + self.fn += 1 + + def accumulate(self): + """ + Calculate the final recall. + + Returns: + A scaler float: results of the calculated Recall. + """ + recall = self.tp + self.fn + return float(self.tp) / recall if recall != 0 else .0 + + def reset(self): + """ + Resets all of the metric state. + """ + self.tp = 0 + self.fn = 0 + + def name(self): + """ + Returns metric name + """ + return self._name + + +class Auc(Metric): + """ + The auc metric is for binary classification. + Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve. + Please notice that the auc metric is implemented with python, which may be a little bit slow. + + The `auc` function creates four local variables, `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` that are used to + compute the AUC. To discretize the AUC curve, a linearly spaced set of + thresholds is used to compute pairs of recall and precision values. The area + under the ROC-curve is therefore computed using the height of the recall + values by the false positive rate, while the area under the PR-curve is the + computed using the height of the precision values by the recall. + + Args: + curve (str): Specifies the mode of the curve to be computed, + 'ROC' or 'PR' for the Precision-Recall-curve. Default is 'ROC'. + num_thresholds (int): The number of thresholds to use when + discretizing the roc curve. Default is 4095. + 'ROC' or 'PR' for the Precision-Recall-curve. Default is 'ROC'. + name (str, optional): String name of the metric instance. Default + is `auc`. + + "NOTE: only implement the ROC curve type via Python now." + + Example by standalone: + .. code-block:: python + + import numpy as np + import paddle + + m = paddle.metric.Auc() + + n = 8 + class0_preds = np.random.random(size = (n, 1)) + class1_preds = 1 - class0_preds + + preds = np.concatenate((class0_preds, class1_preds), axis=1) + labels = np.random.randint(2, size = (n, 1)) + + m.update(preds=preds, labels=labels) + res = m.accumulate() + + + Example with Model API: + + .. code-block:: python + + import numpy as np + import paddle + import paddle.nn as nn + + class Data(paddle.io.Dataset): + def __init__(self): + super(Data, self).__init__() + self.n = 1024 + self.x = np.random.randn(self.n, 10).astype('float32') + self.y = np.random.randint(2, size=(self.n, 1)).astype('int64') + + def __getitem__(self, idx): + return self.x[idx], self.y[idx] + + def __len__(self): + return self.n + + model = paddle.Model(nn.Sequential( + nn.Linear(10, 2), nn.Softmax()) + ) + optim = paddle.optimizer.Adam( + learning_rate=0.001, parameters=model.parameters()) + + def loss(x, y): + return nn.functional.nll_loss(paddle.log(x), y) + + model.prepare( + optim, + loss=loss, + metrics=paddle.metric.Auc()) + data = Data() + model.fit(data, batch_size=16) + """ + + def __init__(self, + curve='ROC', + num_thresholds=4095, + name='auc', + *args, + **kwargs): + super(Auc, self).__init__(*args, **kwargs) + self._curve = curve + self._num_thresholds = num_thresholds + + _num_pred_buckets = num_thresholds + 1 + self._stat_pos = np.zeros(_num_pred_buckets) + self._stat_neg = np.zeros(_num_pred_buckets) + self._name = name + + def update(self, preds, labels): + """ + Update the auc curve with the given predictions and labels. + + Args: + preds (numpy.array): An numpy array in the shape of + (batch_size, 2), preds[i][j] denotes the probability of + classifying the instance i into the class j. + labels (numpy.array): an numpy array in the shape of + (batch_size, 1), labels[i] is either o or 1, + representing the label of the instance i. + """ + if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + labels = labels.numpy() + elif not _is_numpy_(labels): + raise ValueError("The 'labels' must be a numpy ndarray or Tensor.") + + if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + preds = preds.numpy() + elif not _is_numpy_(preds): + raise ValueError("The 'preds' must be a numpy ndarray or Tensor.") + + for i, lbl in enumerate(labels): + value = preds[i, 1] + bin_idx = int(value * self._num_thresholds) + assert bin_idx <= self._num_thresholds + if lbl: + self._stat_pos[bin_idx] += 1.0 + else: + self._stat_neg[bin_idx] += 1.0 + + @staticmethod + def trapezoid_area(x1, x2, y1, y2): + return abs(x1 - x2) * (y1 + y2) / 2.0 + + def accumulate(self): + """ + Return the area (a float score) under auc curve + + Return: + float: the area under auc curve + """ + tot_pos = 0.0 + tot_neg = 0.0 + auc = 0.0 + + idx = self._num_thresholds + while idx >= 0: + tot_pos_prev = tot_pos + tot_neg_prev = tot_neg + tot_pos += self._stat_pos[idx] + tot_neg += self._stat_neg[idx] + auc += self.trapezoid_area(tot_neg, tot_neg_prev, tot_pos, + tot_pos_prev) + idx -= 1 + + return auc / tot_pos / tot_neg if tot_pos > 0.0 and tot_neg > 0.0 else 0.0 + + def reset(self): + """ + Reset states and result + """ + _num_pred_buckets = self._num_thresholds + 1 + self._stat_pos = np.zeros(_num_pred_buckets) + self._stat_neg = np.zeros(_num_pred_buckets) + + def name(self): + """ + Returns metric name + """ + return self._name + + +def accuracy(input, label, k=1, correct=None, total=None, name=None): + """ + accuracy layer. + Refer to the https://en.wikipedia.org/wiki/Precision_and_recall + + This function computes the accuracy using the input and label. + If the correct label occurs in top k predictions, then correct will increment by one. + Note: the dtype of accuracy is determined by input. the input and label dtype can be different. + + Args: + input(Tensor): The input of accuracy layer, which is the predictions of network. A Tensor with type float32,float64. + The shape is ``[sample_number, class_dim]`` . + label(Tensor): The label of dataset. Tensor with type int64 or int32. The shape is ``[sample_number, 1]`` . + k(int, optional): The top k predictions for each class will be checked. Data type is int64 or int32. + correct(Tensor, optional): The correct predictions count. A Tensor with type int64 or int32. + total(Tensor, optional): The total entries count. A tensor with type int64 or int32. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tensor, the correct rate. A Tensor with type float32. + + Examples: + .. code-block:: python + + import paddle + + predictions = paddle.to_tensor([[0.2, 0.1, 0.4, 0.1, 0.1], [0.2, 0.3, 0.1, 0.15, 0.25]], dtype='float32') + label = paddle.to_tensor([[2], [0]], dtype="int64") + result = paddle.metric.accuracy(input=predictions, label=label, k=1) + # [0.5] + """ + if label.dtype == paddle.int32: + label = paddle.cast(label, paddle.int64) + if _non_static_mode(): + if correct is None: + correct = _varbase_creator(dtype="int32") + if total is None: + total = _varbase_creator(dtype="int32") + + topk_out, topk_indices = paddle.topk(input, k=k) + _acc, _, _ = _legacy_C_ops.accuracy(topk_out, topk_indices, label, + correct, total) + + return _acc + + helper = LayerHelper("accuracy", **locals()) + check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'], + 'accuracy') + topk_out, topk_indices = paddle.topk(input, k=k) + acc_out = helper.create_variable_for_type_inference(dtype="float32") + if correct is None: + correct = helper.create_variable_for_type_inference(dtype="int32") + if total is None: + total = helper.create_variable_for_type_inference(dtype="int32") + helper.append_op(type="accuracy", + inputs={ + "Out": [topk_out], + "Indices": [topk_indices], + "Label": [label] + }, + outputs={ + "Accuracy": [acc_out], + "Correct": [correct], + "Total": [total], + }) + return acc_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e47fa8c3c5480d0b33ae0fa21a04245f217638f3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/__init__.py @@ -0,0 +1,325 @@ +# 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. + +# TODO: import all neural network related api under this directory, +# including layers, linear, conv, rnn etc. +from ..fluid.dygraph.layers import Layer # noqa: F401 +from ..fluid.dygraph.container import LayerList # noqa: F401 +from ..fluid.dygraph.container import ParameterList # noqa: F401 +from ..fluid.dygraph.container import Sequential # noqa: F401 + +from .clip import ClipGradByGlobalNorm # noqa: F401 +from .clip import ClipGradByNorm # noqa: F401 +from .clip import ClipGradByValue # noqa: F401 +from .decode import BeamSearchDecoder # noqa: F401 +from .decode import dynamic_decode # noqa: F401 +from .layer.activation import CELU # noqa: F401 +from .layer.activation import ELU # noqa: F401 +from .layer.activation import GELU # noqa: F401 +from .layer.activation import Tanh # noqa: F401 +from .layer.activation import Hardshrink # noqa: F401 +from .layer.activation import Hardswish # noqa: F401 +from .layer.activation import Hardtanh # noqa: F401 +from .layer.activation import PReLU # noqa: F401 +from .layer.activation import ReLU # noqa: F401 +from .layer.activation import ReLU6 # noqa: F401 +from .layer.activation import SELU # noqa: F401 +from .layer.activation import Silu # noqa: F401 +from .layer.activation import LeakyReLU # noqa: F401 +from .layer.activation import Sigmoid # noqa: F401 +from .layer.activation import Hardsigmoid # noqa: F401 +from .layer.activation import LogSigmoid # noqa: F401 +from .layer.activation import Softmax # noqa: F401 +from .layer.activation import Softmax2D # noqa: F401 +from .layer.activation import Softplus # noqa: F401 +from .layer.activation import Softshrink # noqa: F401 +from .layer.activation import Softsign # noqa: F401 +from .layer.activation import Swish # noqa: F401 +from .layer.activation import Mish # noqa: F401 +from .layer.activation import Tanhshrink # noqa: F401 +from .layer.activation import ThresholdedReLU # noqa: F401 +from .layer.activation import LogSoftmax # noqa: F401 +from .layer.activation import Maxout # noqa: F401 +from .layer.activation import RReLU # noqa: F401 +from .layer.common import Pad1D # noqa: F401 +from .layer.common import Pad2D # noqa: F401 +from .layer.common import ZeroPad2D # noqa: F401 +from .layer.common import Pad3D # noqa: F401 +from .layer.common import CosineSimilarity # noqa: F401 +from .layer.common import Embedding # noqa: F401 +from .layer.common import Linear # noqa: F401 +from .layer.common import Identity # noqa: F401 +from .layer.common import Flatten # noqa: F401 +from .layer.common import Upsample # noqa: F401 +from .layer.common import UpsamplingNearest2D # noqa: F401 +from .layer.common import UpsamplingBilinear2D # noqa: F401 +from .layer.common import Bilinear # noqa: F401 +from .layer.common import Dropout # noqa: F401 +from .layer.common import Dropout2D # noqa: F401 +from .layer.common import Dropout3D # noqa: F401 +from .layer.common import AlphaDropout # noqa: F401 +from .layer.common import Unfold # noqa: F401 +from .layer.common import Fold # noqa: F401 + +from .layer.pooling import AvgPool1D # noqa: F401 +from .layer.pooling import AvgPool2D # noqa: F401 +from .layer.pooling import AvgPool3D # noqa: F401 +from .layer.pooling import MaxPool1D # noqa: F401 +from .layer.pooling import MaxPool2D # noqa: F401 +from .layer.pooling import MaxPool3D # noqa: F401 +from .layer.pooling import MaxUnPool1D # noqa: F401 +from .layer.pooling import MaxUnPool2D # noqa: F401 +from .layer.pooling import MaxUnPool3D # noqa: F401 +from .layer.pooling import AdaptiveAvgPool1D # noqa: F401 +from .layer.pooling import AdaptiveAvgPool2D # noqa: F401 +from .layer.pooling import AdaptiveAvgPool3D # noqa: F401 +from .layer.pooling import AdaptiveMaxPool1D # noqa: F401 +from .layer.pooling import AdaptiveMaxPool2D # noqa: F401 +from .layer.pooling import AdaptiveMaxPool3D # noqa: F401 + +from .layer.conv import Conv1D # noqa: F401 +from .layer.conv import Conv2D # noqa: F401 +from .layer.conv import Conv3D # noqa: F401 +from .layer.conv import Conv1DTranspose # noqa: F401 +from .layer.conv import Conv2DTranspose # noqa: F401 +from .layer.conv import Conv3DTranspose # noqa: F401 + +from .layer.loss import BCEWithLogitsLoss # noqa: F401 +from .layer.loss import CrossEntropyLoss # noqa: F401 +from .layer.loss import HSigmoidLoss # noqa: F401 +from .layer.loss import MSELoss # noqa: F401 +from .layer.loss import L1Loss # noqa: F401 +from .layer.loss import NLLLoss # noqa: F401 +from .layer.loss import BCELoss # noqa: F401 +from .layer.loss import KLDivLoss # noqa: F401 +from .layer.loss import MarginRankingLoss # noqa: F401 +from .layer.loss import MultiLabelSoftMarginLoss +from .layer.loss import CTCLoss # noqa: F401 +from .layer.loss import SmoothL1Loss # noqa: F401 +from .layer.loss import HingeEmbeddingLoss # noqa: F401 +from .layer.loss import CosineEmbeddingLoss # noqa: F401 +from .layer.loss import TripletMarginWithDistanceLoss +from .layer.loss import TripletMarginLoss +from .layer.loss import SoftMarginLoss +from .layer.norm import BatchNorm # noqa: F401 +from .layer.norm import SyncBatchNorm # noqa: F401 +from .layer.norm import GroupNorm # noqa: F401 +from .layer.norm import LayerNorm # noqa: F401 +from .layer.norm import SpectralNorm # noqa: F401 +from .layer.norm import InstanceNorm1D # noqa: F401 +from .layer.norm import InstanceNorm2D # noqa: F401 +from .layer.norm import InstanceNorm3D # noqa: F401 +from .layer.norm import BatchNorm1D # noqa: F401 +from .layer.norm import BatchNorm2D # noqa: F401 +from .layer.norm import BatchNorm3D # noqa: F401 +from .layer.norm import LocalResponseNorm # noqa: F401 + +from .layer.rnn import RNNCellBase # noqa: F401 +from .layer.rnn import SimpleRNNCell # noqa: F401 +from .layer.rnn import LSTMCell # noqa: F401 +from .layer.rnn import GRUCell # noqa: F401 +from .layer.rnn import RNN # noqa: F401 +from .layer.rnn import BiRNN # noqa: F401 +from .layer.rnn import SimpleRNN # noqa: F401 +from .layer.rnn import LSTM # noqa: F401 +from .layer.rnn import GRU # noqa: F401 + +from .layer.transformer import MultiHeadAttention # noqa: F401 +from .layer.transformer import TransformerEncoderLayer # noqa: F401 +from .layer.transformer import TransformerEncoder # noqa: F401 +from .layer.transformer import TransformerDecoderLayer # noqa: F401 +from .layer.transformer import TransformerDecoder # noqa: F401 +from .layer.transformer import Transformer # noqa: F401 +from .layer.distance import PairwiseDistance # noqa: F401 + +from .layer.vision import PixelShuffle # noqa: F401 +from .layer.vision import PixelUnshuffle # noqa: F401 +from .layer.vision import ChannelShuffle # noqa: F401 +from .layer.container import LayerDict # noqa: F401 + +from .utils.spectral_norm_hook import spectral_norm + +# TODO: remove loss, keep it for too many used in unitests +from .layer import loss # noqa: F401 + +from . import utils # noqa: F401 +from . import functional # noqa: F401 +from . import initializer # noqa: F401 +from . import quant # noqa: F401 + +# TODO: remove 'diag_embed', 'remove_weight_norm', 'weight_norm' months later. +import paddle.utils.deprecated as deprecated + + +@deprecated(since="2.0.0", + update_to="paddle.nn.funcitional.diag_embed", + level=1, + reason="diag_embed in paddle.nn will be removed in future") +def diag_embed(*args): + ''' + alias name of paddle.nn.functional.diag_embed + ''' + return functional.diag_embed(*args) + + +@deprecated(since="2.0.0", + update_to="paddle.nn.utils.remove_weight_norm", + level=1, + reason="remove_weight_norm in paddle.nn will be removed in future") +def remove_weight_norm(*args): + ''' + alias name of paddle.nn.utils.remove_weight_norm + ''' + return utils.remove_weight_norm(*args) + + +@deprecated(since="2.0.0", + update_to="paddle.nn.utils.weight_norm", + level=1, + reason="weight_norm in paddle.nn will be removed in future") +def weight_norm(*args): + ''' + alias name of paddle.nn.utils.weight_norm + ''' + return utils.weight_norm(*args) + + +__all__ = [ # noqa + 'BatchNorm', + 'CELU', + 'GroupNorm', + 'LayerNorm', + 'SpectralNorm', + 'BatchNorm1D', + 'BatchNorm2D', + 'BatchNorm3D', + 'InstanceNorm1D', + 'InstanceNorm2D', + 'InstanceNorm3D', + 'SyncBatchNorm', + 'LocalResponseNorm', + 'Embedding', + 'Linear', + 'Upsample', + 'UpsamplingNearest2D', + 'UpsamplingBilinear2D', + 'Pad1D', + 'Pad2D', + 'Pad3D', + 'CosineSimilarity', + 'Dropout', + 'Dropout2D', + 'Dropout3D', + 'Bilinear', + 'AlphaDropout', + 'Unfold', + 'Fold', + 'RNNCellBase', + 'SimpleRNNCell', + 'LSTMCell', + 'GRUCell', + 'RNN', + 'BiRNN', + 'SimpleRNN', + 'LSTM', + 'GRU', + 'dynamic_decode', + 'MultiHeadAttention', + 'Maxout', + 'Softsign', + 'Transformer', + 'MSELoss', + 'LogSigmoid', + 'BeamSearchDecoder', + 'ClipGradByNorm', + 'ReLU', + 'PairwiseDistance', + 'BCEWithLogitsLoss', + 'SmoothL1Loss', + 'MaxPool3D', + 'AdaptiveMaxPool2D', + 'Hardshrink', + 'Softplus', + 'KLDivLoss', + 'AvgPool2D', + 'L1Loss', + 'LeakyReLU', + 'AvgPool1D', + 'AdaptiveAvgPool3D', + 'AdaptiveMaxPool3D', + 'NLLLoss', + 'Conv1D', + 'Sequential', + 'Hardswish', + 'Conv1DTranspose', + 'AdaptiveMaxPool1D', + 'TransformerEncoder', + 'Softmax', + 'Softmax2D', + 'ParameterList', + 'Conv2D', + 'Softshrink', + 'Hardtanh', + 'TransformerDecoderLayer', + 'CrossEntropyLoss', + 'GELU', + 'SELU', + 'Silu', + 'Conv2DTranspose', + 'CTCLoss', + 'ThresholdedReLU', + 'AdaptiveAvgPool2D', + 'MaxPool1D', + 'Layer', + 'TransformerDecoder', + 'Conv3D', + 'Tanh', + 'Conv3DTranspose', + 'Flatten', + 'AdaptiveAvgPool1D', + 'Tanhshrink', + 'HSigmoidLoss', + 'PReLU', + 'TransformerEncoderLayer', + 'AvgPool3D', + 'MaxPool2D', + 'MarginRankingLoss', + 'LayerList', + 'ClipGradByValue', + 'BCELoss', + 'Hardsigmoid', + 'ClipGradByGlobalNorm', + 'LogSoftmax', + 'Sigmoid', + 'Swish', + 'Mish', + 'PixelShuffle', + 'PixelUnshuffle', + 'ChannelShuffle', + 'ELU', + 'ReLU6', + 'LayerDict', + 'ZeroPad2D', + 'MaxUnPool1D', + 'MaxUnPool2D', + 'MaxUnPool3D', + 'MultiLabelSoftMarginLoss', + 'HingeEmbeddingLoss', + 'Identity', + 'CosineEmbeddingLoss', + 'RReLU', + 'TripletMarginWithDistanceLoss', + 'TripletMarginLoss', + 'SoftMarginLoss', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/clip.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..61143175fd4af5070ab72036de7c0cc47778aa43 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/clip.py @@ -0,0 +1,20 @@ +# 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. + +# TODO: define the functions to clip gradient of parameter +from ..fluid.clip import ClipGradByGlobalNorm # noqa: F401 +from ..fluid.clip import ClipGradByNorm # noqa: F401 +from ..fluid.clip import ClipGradByValue # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/decode.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/decode.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4a6e4f482af5958c76079c9987cc20e5ea935d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/decode.py @@ -0,0 +1,18 @@ +# 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. + +from ..fluid.layers import BeamSearchDecoder # noqa: F401 +from ..fluid.layers import dynamic_decode # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..701997e0d0ab59b54566fb710e19eda404805cf1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/__init__.py @@ -0,0 +1,245 @@ +# 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. + +# TODO: import all neural network related api under this directory, +# including layers, linear, conv, rnn etc. + +from .activation import celu # noqa: F401 +from .activation import elu # noqa: F401 +from .activation import elu_ # noqa: F401 +from .activation import gelu # noqa: F401 +from .activation import hardshrink # noqa: F401 +from .activation import hardtanh # noqa: F401 +from .activation import hardsigmoid # noqa: F401 +from .activation import hardswish # noqa: F401 +from .activation import leaky_relu # noqa: F401 +from .activation import log_sigmoid # noqa: F401 +from .activation import maxout # noqa: F401 +from .activation import prelu # noqa: F401 +from .activation import relu # noqa: F401 +from .activation import relu_ # noqa: F401 +from .activation import relu6 # noqa: F401 +from .activation import selu # noqa: F401 +from .activation import sigmoid # noqa: F401 +from .activation import silu # noqa: F401 +from .activation import softmax # noqa: F401 +from .activation import softmax_ # noqa: F401 +from .activation import softplus # noqa: F401 +from .activation import softshrink # noqa: F401 +from .activation import softsign # noqa: F401 +from .activation import swish # noqa: F401 +from .activation import mish # noqa: F401 +from .activation import tanh # noqa: F401 +from .activation import tanh_ # noqa: F401 +from .activation import tanhshrink # noqa: F401 +from .activation import thresholded_relu # noqa: F401 +from .activation import log_softmax # noqa: F401 +from .activation import glu # noqa: F401 +from .activation import gumbel_softmax # noqa: F401 +from .activation import rrelu # noqa: F401 +from .common import dropout # noqa: F401 +from .common import dropout2d # noqa: F401 +from .common import dropout3d # noqa: F401 +from .common import alpha_dropout # noqa: F401 +from .common import label_smooth # noqa: F401 +from .common import pad # noqa: F401 +from .common import zeropad2d # noqa: F401 +from .common import cosine_similarity # noqa: F401 +from .common import unfold # noqa: F401 +from .common import fold +from .common import interpolate # noqa: F401 +from .common import upsample # noqa: F401 +from .common import bilinear # noqa: F401 +from .common import class_center_sample # noqa: F401 +from .conv import conv1d # noqa: F401 +from .conv import conv1d_transpose # noqa: F401 +from .common import linear # noqa: F401 +from .conv import conv2d # noqa: F401 +from .conv import conv2d_transpose # noqa: F401 +from .conv import conv3d # noqa: F401 +from .conv import conv3d_transpose # noqa: F401 +from .distance import pairwise_distance # noqa: F401 +from .extension import diag_embed # noqa: F401 +from .extension import sequence_mask +from .loss import binary_cross_entropy # noqa: F401 +from .loss import binary_cross_entropy_with_logits # noqa: F401 +from .loss import cross_entropy # noqa: F401 +from .loss import dice_loss # noqa: F401 +from .loss import hsigmoid_loss # noqa: F401 +from .loss import kl_div # noqa: F401 +from .loss import l1_loss # noqa: F401 +from .loss import log_loss # noqa: F401 +from .loss import margin_ranking_loss # noqa: F401 +from .loss import mse_loss # noqa: F401 +from .loss import nll_loss # noqa: F401 +from .loss import npair_loss # noqa: F401 +from .loss import sigmoid_focal_loss # noqa: F401 +from .loss import smooth_l1_loss # noqa: F401 +from .loss import softmax_with_cross_entropy # noqa: F401 +from .loss import margin_cross_entropy # noqa: F401 +from .loss import square_error_cost # noqa: F401 +from .loss import ctc_loss # noqa: F401 +from .loss import hinge_embedding_loss # noqa: F401 +from .loss import cosine_embedding_loss # noqa: F401 +from .loss import multi_label_soft_margin_loss +from .loss import triplet_margin_with_distance_loss +from .loss import triplet_margin_loss +from .loss import soft_margin_loss +from .norm import batch_norm # noqa: F401 +from .norm import instance_norm # noqa: F401 +from .norm import layer_norm # noqa: F401 +from .norm import local_response_norm # noqa: F401 +from .norm import normalize # noqa: F401 +from .pooling import avg_pool1d # noqa: F401 +from .pooling import avg_pool2d # noqa: F401 +from .pooling import avg_pool3d # noqa: F401 +from .pooling import max_pool1d # noqa: F401 +from .pooling import max_pool2d # noqa: F401 +from .pooling import max_pool3d # noqa: F401 + +from .pooling import adaptive_max_pool1d # noqa: F401 +from .pooling import adaptive_max_pool2d # noqa: F401 +from .pooling import adaptive_max_pool3d # noqa: F401 +from .pooling import adaptive_avg_pool1d # noqa: F401 +from .pooling import adaptive_avg_pool2d # noqa: F401 +from .pooling import adaptive_avg_pool3d # noqa: F401 +from .pooling import max_unpool1d # noqa: F401 +from .pooling import max_unpool2d # noqa: F401 +from .pooling import max_unpool3d # noqa: F401 + +from .vision import affine_grid # noqa: F401 +from .vision import grid_sample # noqa: F401 +from .vision import pixel_shuffle # noqa: F401 +from .vision import pixel_unshuffle # noqa: F401 +from .vision import channel_shuffle # noqa: F401 +from .input import one_hot # noqa: F401 +from .input import embedding # noqa: F401 +from .extension import gather_tree # noqa: F401 +from .extension import temporal_shift # noqa: F401 + +from .sparse_attention import sparse_attention + +__all__ = [ # noqa + 'celu', + 'conv1d', + 'conv1d_transpose', + 'conv2d', + 'conv2d_transpose', + 'conv3d', + 'conv3d_transpose', + 'pairwise_distance', + 'elu', + 'elu_', + 'gelu', + 'hardshrink', + 'hardtanh', + 'hardsigmoid', + 'hardswish', + 'leaky_relu', + 'log_sigmoid', + 'maxout', + 'prelu', + 'relu', + 'relu_', + 'relu6', + 'selu', + 'softmax', + 'softmax_', + 'softplus', + 'softshrink', + 'softsign', + 'sigmoid', + 'silu', + 'swish', + 'mish', + 'tanh', + 'tanh_', + 'tanhshrink', + 'thresholded_relu', + 'log_softmax', + 'glu', + 'gumbel_softmax', + 'diag_embed', + 'sequence_mask', + 'dropout', + 'dropout2d', + 'dropout3d', + 'alpha_dropout', + 'label_smooth', + 'linear', + 'pad', + 'zeropad2d', + 'unfold', + 'interpolate', + 'upsample', + 'bilinear', + 'cosine_similarity', + 'avg_pool1d', + 'avg_pool2d', + 'avg_pool3d', + 'max_pool1d', + 'max_pool2d', + 'max_pool3d', + 'max_unpool1d', + 'max_unpool2d', + 'max_unpool3d', + 'adaptive_avg_pool1d', + 'adaptive_avg_pool2d', + 'adaptive_avg_pool3d', + 'adaptive_max_pool1d', + 'adaptive_max_pool2d', + 'adaptive_max_pool3d', + 'binary_cross_entropy', + 'binary_cross_entropy_with_logits', + 'cross_entropy', + 'dice_loss', + 'hsigmoid_loss', + 'kl_div', + 'l1_loss', + 'log_loss', + 'mse_loss', + 'margin_ranking_loss', + 'multi_label_soft_margin_loss', + 'nll_loss', + 'npair_loss', + 'sigmoid_focal_loss', + 'smooth_l1_loss', + 'softmax_with_cross_entropy', + 'margin_cross_entropy', + 'square_error_cost', + 'ctc_loss', + 'hinge_embedding_loss', + 'affine_grid', + 'grid_sample', + 'local_response_norm', + 'pixel_shuffle', + 'pixel_unshuffle', + 'channel_shuffle', + 'embedding', + 'gather_tree', + 'one_hot', + 'normalize', + 'temporal_shift', + 'batch_norm', + 'layer_norm', + 'instance_norm', + 'class_center_sample', + 'sparse_attention', + 'fold', + 'cosine_embedding_loss', + 'rrelu', + 'triplet_margin_with_distance_loss', + 'triplet_margin_loss', + 'soft_margin_loss', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/activation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..cda61ade77d8d02b331518796c5a357075207270 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/activation.py @@ -0,0 +1,1773 @@ +# 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. + +from ...tensor.ops import sigmoid # noqa: F401 +from ...tensor.math import tanh # noqa: F401 +from ...tensor.math import tanh_ # noqa: F401 + +from ...fluid.dygraph.inplace_utils import inplace_apis_in_dygraph_only +from ...tensor.manipulation import chunk +from ...tensor.math import multiply + +import warnings +from ...fluid.layer_helper import LayerHelper +from ...fluid.framework import convert_np_dtype_to_dtype_ +from ...fluid.framework import ( + _in_legacy_dygraph, + in_dygraph_mode, + _non_static_mode, +) +from ...fluid.data_feeder import check_variable_and_dtype, check_dtype +import paddle +from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode +from paddle.framework import core +from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode + +__all__ = [] + + +def celu(x, alpha=1.0, name=None): + r""" + celu activation. + + .. math:: + + celu(x) = max(0, x) + min(0, \alpha * (e^{x/\alpha}-1)) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + alpha (float, optional): The 'alpha' value of the CELU formulation. Default is 1.0. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + x = paddle.to_tensor([[-1., 6.], [1., 15.6]]) + out = F.celu(x, alpha=0.2) + # [[-0.19865242, 6. ], + # [ 1. , 15.60000038]] + """ + if alpha == 0: + raise ZeroDivisionError("alpha cannot be 0 for celu") + + if _in_legacy_dygraph(): + return _legacy_C_ops.celu(x, 'alpha', alpha) + if in_dygraph_mode(): + return _C_ops.celu(x, alpha) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'celu') + helper = LayerHelper("celu", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='celu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'alpha': alpha}, + ) + return out + + +def elu(x, alpha=1.0, name=None): + r""" + elu activation. + + .. math:: + + elu(x)= + \left\{ + \begin{array}{lcl} + x,& &\text{if } \ x > 0 \\ + alpha * (e^{x} - 1),& &\text{if } \ x <= 0 + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + alpha (float, optional): The 'alpha' value of the ELU formulation. Default is 1.0. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[-1., 6.], [1., 15.6]]) + out = F.elu(x, alpha=0.2) + # [[-0.12642411 6. ] + # [ 1. 15.6 ]] + """ + + if in_dygraph_mode(): + return _C_ops.elu(x, alpha) + + if _in_legacy_dygraph(): + return _legacy_C_ops.elu(x, 'alpha', alpha) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'elu') + helper = LayerHelper("elu", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='elu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'alpha': alpha}, + ) + return out + + +@inplace_apis_in_dygraph_only +def elu_(x, alpha=1.0, name=None): + r""" + Inplace version of ``elu`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_nn_cn_elu`. + """ + assert alpha >= 0.0, "elu_ only support alpha >= 0, please use elu instead." + if in_dygraph_mode(): + return _C_ops.elu_(x, alpha) + return _legacy_C_ops.elu_(x, 'alpha', alpha) + + +def gelu(x, approximate=False, name=None): + r""" + gelu activation. + + The activation function of Gelu is calculated element by element. More information refers to :ref: `Gaussian Error Linear Units`. + + if approximate is True + + .. math:: + + gelu(x) = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) + + else + + .. math:: + + gelu(x) = 0.5 * x * (1 + erf(\frac{x}{\sqrt{2}})) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + approximate (bool, optional): Whether to enable approximation. Default is False. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[-1, 0.5], [1, 1.5]]) + out1 = F.gelu(x) + # [[-0.15865529, 0.34573123], + # [ 0.84134471, 1.39978933]] + out2 = F.gelu(x, True) + # [[-0.15880799, 0.34571400], + # [ 0.84119201, 1.39957154]] + """ + + if in_dygraph_mode(): + return _C_ops.gelu(x, approximate) + + if _in_legacy_dygraph(): + return _legacy_C_ops.gelu(x, 'approximate', approximate) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'gelu') + helper = LayerHelper("gelu", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='gelu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'approximate': approximate}, + ) + return out + + +def hardshrink(x, threshold=0.5, name=None): + r""" + hard shrinkage activation + + .. math:: + + hardshrink(x)= + \left\{ + \begin{array}{rcl} + x,& &if \ {x > threshold} \\ + x,& &if \ {x < -threshold} \\ + 0,& &if \ {others} & + \end{array} + \right. + + Args: + x (Tensor): The input Tensor with data type float32, float64. + threshold (float, optional): The value of threshold for hardthrink. Default is 0.5. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-1, 0.3, 2.5]) + out = F.hardshrink(x) # [-1., 0., 2.5] + + """ + if in_dygraph_mode(): + return _C_ops.hard_shrink(x, threshold) + + if _in_legacy_dygraph(): + return _legacy_C_ops.hard_shrink(x, 'threshold', threshold) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hardshrink' + ) + helper = LayerHelper('hardshrink', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='hard_shrink', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold}, + ) + return out + + +def hardtanh(x, min=-1.0, max=1.0, name=None): + r""" + hardtanh activation. Calculate the `hardtanh` of input `x`. + + .. math:: + + hardtanh(x)= + \left\{ + \begin{array}{cll} + max,& & \text{if } x > max \\ + min,& & \text{if } x < min \\ + x,& & \text{otherwise} + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + min (float, optional): The minimum value of the linear region range. Default is -1. + max (float, optional): The maximum value of the linear region range. Default is 1. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-1.5, 0.3, 2.5]) + out = F.hardtanh(x) # [-1., 0.3, 1.] + """ + + if in_dygraph_mode(): + return _C_ops.brelu(x, min, max) + + if _in_legacy_dygraph(): + return _legacy_C_ops.brelu(x, 't_min', min, 't_max', max) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hardtanh' + ) + + helper = LayerHelper('hardtanh', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='brelu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'t_min': min, 't_max': max}, + ) + return out + + +def hardsigmoid(x, slope=0.1666667, offset=0.5, name=None): + r""" + hardsigmoid activation. Calculate the `hardsigmoid` of input `x`. + A 3-part piecewise linear approximation of sigmoid(https://arxiv.org/abs/1603.00391), + which is much faster than sigmoid. + + .. math:: + + hardsigmoid(x)= + \left\{ + \begin{array}{lcl} + 0, & &\text{if } \ x \leq -3 \\ + 1, & &\text{if } \ x \geq 3 \\ + slope * x + offset, & &\text{otherwise} + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + slope (float, optional): The slope of hardsigmoid function. Default is 0.1666667. + offset (float, optional): The offset of hardsigmoid function. Default is 0.5. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-4., 5., 1.]) + out = F.hardsigmoid(x) # [0., 1., 0.666667] + """ + + if in_dygraph_mode(): + return _C_ops.hard_sigmoid(x, slope, offset) + + if _in_legacy_dygraph(): + return _legacy_C_ops.hard_sigmoid(x, 'slope', slope, 'offset', offset) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hardsigmoid' + ) + + helper = LayerHelper('hardsigmoid', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='hard_sigmoid', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'slope': slope, 'offset': offset}, + ) + return out + + +def hardswish(x, name=None): + r""" + hardswish activation. hardswish is proposed in MobileNetV3, and performs + better in computational stability and efficiency compared to swish function. + For more details please refer to: https://arxiv.org/pdf/1905.02244.pdf + + .. math:: + + hardswish(x)= + \left\{ + \begin{array}{cll} + 0 &, & \text{if } x \leq -3 \\ + x &, & \text{if } x \geq 3 \\ + \frac{x(x+3)}{6} &, & \text{otherwise} + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-4., 5., 1.]) + out = F.hardswish(x) # [0., 5., 0.666667] + """ + + if _in_legacy_dygraph(): + return _legacy_C_ops.hard_swish(x) + if in_dygraph_mode(): + return _C_ops.hard_swish(x, 6, 6, 3) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'hardswish' + ) + + helper = LayerHelper('hardswish', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='hard_swish', inputs={'X': x}, outputs={'Out': out}) + return out + + +def leaky_relu(x, negative_slope=0.01, name=None): + r""" + leaky_relu activation. The calculation formula is: + + .. math:: + leaky\_relu(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + negative\_slope * x, & & otherwise \\ + \end{array} + \right. + + Args: + x (Tensor): The input Tensor with data type float32, float64. + negative_slope (float, optional): Slope of the activation function at + :math:`x < 0` . Default is 0.01. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-2., 0., 1.]) + out = F.leaky_relu(x) + print(out) + # [-0.02, 0., 1.] + + """ + if in_dygraph_mode(): + return _C_ops.leaky_relu(x, negative_slope) + + if _in_legacy_dygraph(): + return _legacy_C_ops.leaky_relu(x, 'alpha', negative_slope) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'leaky_relu' + ) + helper = LayerHelper('leaky_relu', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='leaky_relu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'alpha': negative_slope}, + ) + return out + + +def prelu(x, weight, data_format="NCHW", name=None): + """ + prelu activation. + + .. math:: + + prelu(x) = max(0, x) + weight * min(0, x) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + weight (Tensor): The learnable parameter with data type same as ``x``. + The weight shape is [1] or [in], where `in` is the input channel of ``x``. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + data_format(str, optional): Data format that specifies the layout of input. + It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW". + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0], + [ 3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[ 1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [ 6.0, 7.0, 8.0, 9.0]]]], dtype='float32') + + w = paddle.to_tensor([0.25], dtype='float32') + out = F.prelu(data, w) + print(out) + # [[[[-0.5 , 3. , -1. , 5. ], + # [ 3. , -1. , 5. , -1.5 ], + # [-1.75, -2. , 8. , 9. ]], + # [[ 1. , -0.5 , -0.75, 4. ], + # [-1.25, 6. , 7. , -2. ], + # [ 6. , 7. , 8. , 9. ]]]] + """ + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'prelu') + check_variable_and_dtype( + weight, 'weight', ['float16', 'float32', 'float64'], 'prelu' + ) + + assert ( + len(weight.shape) == 1 + ), "The dim count of weight shape should be 1 in prelu()." + + mode = 'all' + if weight.shape[0] > 1: + + true_data_format = [ + 'NC', + 'NCL', + 'NCHW', + 'NCDHW', + 'NLC', + 'NHWC', + 'NDHWC', + ] + if data_format not in true_data_format: + raise ValueError( + "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', " + "'NLC', 'NHWC', 'NDHWC' but receive {}".format(data_format) + ) + + data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC' + + assert ( + len(x.shape) > 1 + ), "The dim count of x should be equal or larger than 2 in prelu() when weight shape is not [1]." + + # NOTE(GuoxiaWang): support NHWC data format + if data_format == 'NHWC': + assert ( + weight.shape[0] == x.shape[-1] + ), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]." + else: + assert ( + weight.shape[0] == x.shape[1] + ), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]." + mode = 'channel' + + if in_dygraph_mode(): + return _C_ops.prelu(x, weight, data_format, mode) + if _in_legacy_dygraph(): + return _legacy_C_ops.prelu( + x, weight, 'mode', mode, 'data_format', data_format + ) + + helper = LayerHelper('prelu', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type="prelu", + inputs={"X": x, "Alpha": weight}, + outputs={"Out": out}, + attrs={"mode": mode, "data_format": data_format}, + ) + return out + + +def rrelu(x, lower=1.0 / 8.0, upper=1.0 / 3.0, training=True, name=None): + r""" + rrelu activation. + + Applies the randomized leaky rectified liner unit function to improve generalization performance, + as described in the paper: + `Empirical Evaluation of Rectified Activations in Convolutional Network `_ + + During training, randomly samples the negative slope for activation values as described below: + + .. math:: + + rrelu(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + a * x, & & otherwise \\ + \end{array} + \right. + + where :math:`x` is the input tensor, + :math:`a` is randomly sampled from uniform distribution in range (:math:`lower`, :math:`upper`), + + In the test phase, the negative slope will take the average value of :math:`lower` and :math:`upper`: + + .. math:: + + rrelu(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + (lower + upper) * 0.5 * x, & & otherwise \\ + \end{array} + \right. + + where :math:`x` is the input tensor, + :math:`lower` and :math:`upper` are the bounds of uniform distribution. + + Parameters: + x (Tensor): The input Tensor with data type float16, float32, float64. + lower (float, optional): The lower bound of uniform distribution. Default: 0.125. + upper (float, optional): The upper bound of uniform distribution. Default: 0.333. + training (bool, optional): Current mode is in training or others. Default is True. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input_tensor = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0], + [ 3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[ 1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [ 6.0, 7.0, 8.0, 9.0]]]], dtype='float32') + + out = F.rrelu(input_tensor, 0.1, 0.3) + print(out) + #[[[[-0.20000899 3. -0.8810822 5. ] + # [ 3. -0.55175185 5. -1.0776101 ] + # [-1.0680687 -1.9896201 8. 9. ]] + # [[ 1. -0.5238267 -0.65515125 4. ] + # [-1.3766339 6. 7. -2.3465784 ] + # [ 6. 7. 8. 9. ]]]] + """ + + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'X', ['float16', 'float32', 'float64'], 'rrelu' + ) + + if not isinstance(lower, float) or not isinstance(upper, float): + raise TypeError( + "The lower and upper values must be float type. Received: lower {}, upper {}.".format( + lower, upper + ) + ) + + if lower < 0 or lower > 1: + raise ValueError( + "The lower value must be no less than zero or greater than one. Received: {}.".format( + lower + ) + ) + + if upper < lower: + raise ValueError( + "The upper value must be greater than lower value. Received: lower {}, upper {}.".format( + lower, upper + ) + ) + + if upper > 1: + raise ValueError( + "The upper value must be no greater than one. Received: {}.".format( + upper + ) + ) + + is_test = not training + + if _in_legacy_dygraph(): + out, noise = _legacy_C_ops.rrelu( + x, 'lower', lower, 'upper', upper, 'is_test', is_test + ) + return out + + helper = LayerHelper('rrelu', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + noise = helper.create_variable_for_type_inference(dtype=x.dtype) + attrs = {'lower': lower, 'upper': upper, 'is_test': is_test} + helper.append_op( + type='rrelu', + inputs={"X": x}, + outputs={"Out": out, "Noise": noise}, + attrs=attrs, + ) + return out + + +def relu(x, name=None): + """ + relu activation. + + .. math:: + + out = max(x, 0) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-2, 0, 1], dtype='float32') + out = F.relu(x) + print(out) + # [0., 0., 1.] + """ + + if in_dygraph_mode(): + return _C_ops.relu(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.relu(x) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu') + helper = LayerHelper('relu', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='relu', inputs={'X': x}, outputs={'Out': out}) + return out + + +@inplace_apis_in_dygraph_only +def relu_(x, name=None): + """ + Inplace version of ``relu`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_nn_cn_relu`. + """ + if in_dygraph_mode(): + return _C_ops.relu_(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.relu_(x) + + +def log_sigmoid(x, name=None): + r""" + log_sigmoid activation. + + .. math:: + + log\_sigmoid(x) = log \frac{1}{1 + e^{-x}} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = F.log_sigmoid(x) # [-0.313262 -0.126928 -0.0485874 -0.0181499] + """ + + if in_dygraph_mode(): + return _C_ops.logsigmoid(x) + + if _in_legacy_dygraph(): + return _legacy_C_ops.logsigmoid(x) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'log_sigmoid' + ) + helper = LayerHelper("log_sigmoid", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='logsigmoid', inputs={'X': x}, outputs={'Out': out}) + return out + + +def maxout(x, groups, axis=1, name=None): + r""" + maxout activation. + + Assumed the input shape is (N, Ci, H, W). + The output shape is (N, Co, H, W). + Then Co = Ci/groups and the operator formula is as follows: + + .. math:: + + \begin{array}{l} + &out_{si+j} = \max_{k} x_{gsi + sk + j} \\ + &g = groups \\ + &s = \frac{input.size}{num\_channels} \\ + &0 \le i < \frac{num\_channels}{groups} \\ + &0 \le j < s \\ + &0 \le k < groups + \end{array} + + + Parameters: + x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C], the data type + of input is float32 or float64. + groups (int, optional): The groups number of maxout. `groups` specifies the + index of channel dimension where maxout will be performed. This must be + a factor of number of features. Default is 1. + axis (int, optional): The axis along which to perform maxout calculations. + It should be 1 when data format is NCHW, be -1 or 3 when data format + is NHWC. If ``axis`` < 0, it works the same way as :math:`axis + D` , + where D is the dimensions of ``x`` . ``axis`` only supports 1, 3 or -1. + Default is 1. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.rand([1, 2, 3, 4]) + # [[[[0.5002636 0.22272532 0.17402348 0.2874594 ] + # [0.95313174 0.6228939 0.7129065 0.7087491 ] + # [0.02879342 0.88725346 0.61093384 0.38833922]] + # [[0.5231306 0.03807496 0.91661984 0.15602879] + # [0.666127 0.616567 0.30741522 0.24044901] + # [0.7142536 0.7351477 0.31588817 0.23782359]]]] + out = F.maxout(x, groups=2) + # [[[[0.5231306 0.22272532 0.91661984 0.2874594 ] + # [0.95313174 0.6228939 0.7129065 0.7087491 ] + # [0.7142536 0.88725346 0.61093384 0.38833922]]]] + """ + if _in_legacy_dygraph(): + return _legacy_C_ops.maxout(x, 'groups', groups, 'axis', axis) + if in_dygraph_mode(): + return _C_ops.maxout(x, groups, axis) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'maxout') + if axis not in [1, -1, 3]: + raise ValueError( + "Attr(axis) should be 1 when data format is NCHW, -1 or 3 when data format is NHWC. Received " + "Attr(axis): %s." % str(axis) + ) + if axis == -1: + axis = 3 + + helper = LayerHelper('maxout', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='maxout', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'groups': groups, 'axis': axis}, + ) + return out + + +def relu6(x, name=None): + """ + relu6 activation + + .. math:: + + relu6(x) = min(max(0,x), 6) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-1, 0.3, 6.5]) + out = F.relu6(x) + print(out) + # [0, 0.3, 6] + """ + threshold = 6.0 + if in_dygraph_mode(): + return _C_ops.relu6(x, threshold) + if in_dynamic_mode(): + return _legacy_C_ops.relu6(x, 'threshold', threshold) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'relu6') + helper = LayerHelper('relu6', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='relu6', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold}, + ) + return out + + +def selu( + x, + scale=1.0507009873554804934193349852946, + alpha=1.6732632423543772848170429916717, + name=None, +): + r""" + selu activation + + .. math:: + + selu(x)= scale * + \left\{ + \begin{array}{lcl} + x,& &\text{if } \ x > 0 \\ + alpha * e^{x} - alpha,& &\text{if } \ x <= 0 + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + scale (float, optional): The value of scale(must be greater than 1.0) for selu. Default is 1.0507009873554804934193349852946 + alpha (float, optional): The value of alpha(must be no less than zero) for selu. Default is 1.6732632423543772848170429916717 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[0.0, 1.0],[2.0, 3.0]]) + out = F.selu(x) + print(out) + # [[0, 1.050701],[2.101402, 3.152103]] + """ + if scale <= 1.0: + raise ValueError( + "The scale must be greater than 1.0. Received: {}.".format(scale) + ) + + if alpha < 0: + raise ValueError( + "The alpha must be no less than zero. Received: {}.".format(alpha) + ) + + if in_dygraph_mode(): + return _C_ops.selu(x, scale, alpha) + if _in_legacy_dygraph(): + return _legacy_C_ops.selu(x, 'scale', scale, 'alpha', alpha) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'selu') + helper = LayerHelper('selu', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='selu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'scale': scale, 'alpha': alpha}, + ) + return out + + +def silu(x, name=None): + r""" + silu activation + + .. math:: + + silu(x) = \frac{x}{1 + e^{-x}} + + Where :math:`x` is the input Tensor. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as :attr:`x`. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = F.silu(x) # [ 0.731059, 1.761594, 2.857722, 3.928055 ] + """ + + if in_dygraph_mode(): + return _C_ops.silu(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.silu(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'silu') + helper = LayerHelper("silu", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='silu', inputs={'X': x}, outputs={'Out': out}) + return out + + +def softmax(x, axis=-1, dtype=None, name=None): + r""" + This operator implements the softmax layer. The calculation process is as follows: + + 1. The dimension :attr:`axis` of ``x`` will be permuted to the last. + + 2. Then ``x`` will be logically flattened to a 2-D matrix. The matrix's second + dimension(row length) is the same as the dimension :attr:`axis` of ``x``, + and the first dimension(column length) is the product of all other dimensions + of ``x``. For each row of the matrix, the softmax operator squashes the + K-dimensional(K is the width of the matrix, which is also the size of ``x``'s + dimension :attr:`axis`) vector of arbitrary real values to a K-dimensional + vector of real values in the range [0, 1] that add up to 1. + + 3. After the softmax operation is completed, the inverse operations of steps 1 and 2 + are performed to restore the two-dimensional matrix to the same dimension as the ``x`` . + + It computes the exponential of the given dimension and the sum of exponential + values of all the other dimensions in the K-dimensional vector input. + Then the ratio of the exponential of the given dimension and the sum of + exponential values of all the other dimensions is the output of the softmax + operator. + + For each row :math:`i` and each column :math:`j` in the matrix, we have: + + .. math:: + + softmax[i, j] = \frac{\exp(x[i, j])}{\sum_j(exp(x[i, j])} + + Example: + + .. code-block:: text + + Case 1: + Input: + x.shape = [2, 3, 4] + x.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + + Attrs: + axis = -1 + + Output: + out.shape = [2, 3, 4] + out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.07232949, 0.19661193, 0.19661193, 0.53444665]], + [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] + + Case 2: + Input: + x.shape = [2, 3, 4] + x.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + Attrs: + axis = 1 + + Output: + out.shape = [2, 3, 4] + out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], + [0.01786798, 0.01786798, 0.04661262, 0.04661262], + [0.97555875, 0.97555875, 0.93623955, 0.93623955]], + [[0.00490169, 0.00490169, 0.00490169, 0.00490169], + [0.26762315, 0.26762315, 0.26762315, 0.26762315], + [0.72747516, 0.72747516, 0.72747516, 0.72747516]]] + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + axis (int, optional): The axis along which to perform softmax + calculations. It should be in range [-D, D), where D is the + rank of ``x`` . If ``axis`` < 0, it works the same way as + :math:`axis + D` . Default is -1. + dtype (str, optional): The data type of the output tensor, can be float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same shape and data type (use ``dtype`` if it is + specified) as x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]],dtype='float32') + out1 = F.softmax(x) + out2 = F.softmax(x, dtype='float64') + # out1's data type is float32; out2's data type is float64 + # out1 and out2's value is as follows: + # [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.07232949, 0.19661193, 0.19661193, 0.53444665]], + # [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] + """ + + if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)): + dtype = convert_np_dtype_to_dtype_(dtype) + use_cudnn = True + + if in_dygraph_mode(): + outs_cast = x if dtype is None else _C_ops.cast(x, dtype) + return _C_ops.softmax(outs_cast, axis) + + if _in_legacy_dygraph(): + outs_cast = ( + x + if dtype is None + else _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + ) + return _legacy_C_ops.softmax( + outs_cast, 'axis', axis, 'use_cudnn', use_cudnn + ) + + if dtype is None: + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'softmax' + ) + else: + check_dtype( + dtype, + 'dtype', + ['float32', 'float64'], + 'softmax', + 'If dtype is not None, it only support float32 or float64.', + ) + + helper = LayerHelper("softmax", **locals()) + outs_cast = x + if dtype is not None: + outs_cast = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='cast', + inputs={'X': x}, + outputs={'Out': outs_cast}, + attrs={'in_dtype': x.dtype, 'out_dtype': dtype}, + ) + + outs_softmax = helper.create_variable_for_type_inference(outs_cast.dtype) + helper.append_op( + type='softmax', + inputs={'X': outs_cast}, + outputs={'Out': outs_softmax}, + attrs={'axis': axis, 'use_cudnn': use_cudnn}, + ) + + return outs_softmax + + +@inplace_apis_in_dygraph_only +def softmax_(x, axis=-1, dtype=None, name=None): + r""" + Inplace version of ``softmax`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_nn_cn_softmax`. + """ + if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)): + dtype = convert_np_dtype_to_dtype_(dtype) + use_cudnn = True + + if in_dygraph_mode(): + outs_cast = ( + x + if dtype is None + else _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + ) + return _C_ops.softmax_(outs_cast, axis) + + if _in_legacy_dygraph(): + outs_cast = ( + x + if dtype is None + else _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + ) + return _legacy_C_ops.softmax_( + outs_cast, 'axis', axis, 'use_cudnn', use_cudnn + ) + + +def softplus(x, beta=1, threshold=20, name=None): + r""" + softplus activation + + .. math:: + softplus(x)=\begin{cases} + \frac{1}{\beta} * \log(1 + e^{\beta * x}),&x\leqslant\frac{\varepsilon}{\beta};\\ + x,&x>\frac{\varepsilon}{\beta}. + \end{cases} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + beta (float, optional): The value of :math:`\beta` for softplus. Default is 1 + threshold (float, optional): The value of :math:`\varepsilon` for softplus. Default is 20 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3], dtype='float32') + out = F.softplus(x) # [0.513015, 0.598139, 0.744397, 0.854355] + """ + + if in_dygraph_mode(): + return _C_ops.softplus(x, beta, threshold) + + if _in_legacy_dygraph(): + return _legacy_C_ops.softplus(x, 'beta', beta, 'threshold', threshold) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'softplus' + ) + helper = LayerHelper('softplus', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='softplus', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'beta': beta, 'threshold': threshold}, + ) + return out + + +def softshrink(x, threshold=0.5, name=None): + r""" + softshrink activation + + .. math:: + + softshrink(x)= + \left\{ + \begin{array}{rcl} + x - threshold,& & \text{if } x > threshold \\ + x + threshold,& & \text{if } x < -threshold \\ + 0,& & \text{otherwise} + \end{array} + \right. + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + threshold (float, optional): The value of threshold(must be no less than zero) for softplus. Default is 0.5 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.9, -0.2, 0.1, 0.8]) + out = F.softshrink(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.39999998, 0. , 0. , 0.30000001]) + """ + if threshold < 0: + raise ValueError( + "The threshold must be no less than zero. Received: {}.".format( + threshold + ) + ) + + if in_dygraph_mode(): + return _C_ops.soft_shrink(x, threshold) + if _in_legacy_dygraph(): + return _legacy_C_ops.softshrink(x, 'lambda', threshold) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'softshrink' + ) + helper = LayerHelper('softshrink', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='softshrink', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'lambda': threshold}, + ) + return out + + +def softsign(x, name=None): + r""" + softsign activation + + .. math:: + + softsign(x) = \frac{x}{1 + |x|} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.softsign(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.28571430, -0.16666666, 0.09090909, 0.23076925]) + """ + if in_dygraph_mode(): + return _C_ops.softsign(x) + if in_dynamic_mode(): + return _legacy_C_ops.softsign(x) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'softsign' + ) + helper = LayerHelper('softsign', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='softsign', inputs={'X': x}, outputs={'Out': out}) + return out + + +def swish(x, name=None): + r""" + swish activation. + + .. math:: + + swish(x) = \frac{x}{1 + e^{-x}} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-2., 0., 1.]) + out = F.swish(x) + print(out) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.23840584, 0. , 0.73105854]) + """ + if in_dygraph_mode(): + return _C_ops.swish(x, 1.0) + if _in_legacy_dygraph(): + return _legacy_C_ops.swish(x, 'beta', 1.0) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'swish') + helper = LayerHelper('swish', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='swish', inputs={'X': x}, outputs={'Out': out}, attrs={'beta': 1.0} + ) + return out + + +def mish(x, name=None): + r""" + mish activation. + + .. math:: + + softplus(x) = \begin{cases} + x, \text{if } x > \text{threshold} \\ + \ln(1 + e^{x}), \text{otherwise} + \end{cases} + + mish(x) = x * \tanh(softplus(x)) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-5., 0., 5.]) + out = F.mish(x) # [-0.03357624, 0., 4.99955208] + """ + if in_dygraph_mode(): + return _C_ops.mish(x, 20) + if _in_legacy_dygraph(): + return _legacy_C_ops.mish(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'mish') + helper = LayerHelper('mish', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='mish', inputs={'X': x}, outputs={'Out': out}) + return out + + +def tanhshrink(x, name=None): + """ + tanhshrink activation + + .. math:: + + tanhshrink(x) = x - tanh(x) + + Args: + x (Tensor): The input Tensor with data type float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.tanhshrink(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.02005106, -0.00262468, 0.00033200, 0.00868741]) + """ + if in_dygraph_mode(): + return _C_ops.tanh_shrink(x) + + if _in_legacy_dygraph(): + return _legacy_C_ops.tanh_shrink(x) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'tanhshrink' + ) + helper = LayerHelper('tanh_shrink', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='tanh_shrink', inputs={'X': x}, outputs={'Out': out}) + return out + + +def thresholded_relu(x, threshold=1.0, name=None): + r""" + thresholded relu activation. + + .. math:: + + thresholded\_relu(x) = + \left\{ + \begin{array}{rl} + x,& \text{if } \ x > threshold \\ + 0,& \text{otherwise} + \end{array} + \right. + + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + threshold (float, optional): The value of threshold for thresholded_relu. Default is 1.0 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([2., 0., 1.]) + out = F.thresholded_relu(x) + print(out) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2., 0., 0.]) + """ + + if in_dygraph_mode(): + return _C_ops.thresholded_relu(x, threshold) + + if _in_legacy_dygraph(): + return _legacy_C_ops.thresholded_relu(x, 'threshold', threshold) + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'thresholded_relu' + ) + helper = LayerHelper('thresholded_relu', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='thresholded_relu', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'threshold': threshold}, + ) + return out + + +def log_softmax(x, axis=-1, dtype=None, name=None): + r""" + This operator implements the log_softmax layer. The calculation process is + as follows: + + .. math:: + + \begin{aligned} + log\_softmax[i, j] &= log(softmax(x)) \\ + &= log(\frac{\exp(X[i, j])}{\sum_j(\exp(X[i, j])}) + \end{aligned} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + axis (int, optional): The axis along which to perform log_softmax + calculations. It should be in range [-D, D), where D is the + dimensions of ``x`` . If ``axis`` < 0, it works the same way as + :math:`axis + D` . Default is -1. + dtype (str|np.dtype|core.VarDesc.VarType, optional): The desired data + type of the output tensor. If dtype is specified, ``x`` is casted + to ``dtype`` before the operation is performed. This is useful for + preventing data type overflows. Supported dtype: float32, float64. + If ``dtype`` is None, the output Tensor has the same dtype as x. + Default is None. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same shape and data type (use ``dtype`` if it is + specified) as x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = [[[-2.0, 3.0, -4.0, 5.0], + [3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [6.0, 7.0, 8.0, 9.0]]] + x = paddle.to_tensor(x) + out1 = F.log_softmax(x) + out2 = F.log_softmax(x, dtype='float64') + # out1's data type is float32; out2's data type is float64 + # out1 and out2's value is as follows: + # [[[ -7.1278396 -2.1278396 -9.127839 -0.12783948] + # [ -2.1270514 -9.127051 -0.12705144 -11.127051 ] + # [-16.313261 -17.313261 -1.3132617 -0.31326184]] + # [[ -3.0518122 -6.051812 -7.051812 -0.051812 ] + # [-12.313267 -1.3132664 -0.3132665 -15.313267 ] + # [ -3.4401896 -2.4401896 -1.4401896 -0.44018966]]] + """ + + if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + if dtype is not None: + x = _C_ops.cast(x, dtype) + return _C_ops.log_softmax(x, axis) + + if _in_legacy_dygraph(): + if dtype is not None: + x = _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + return _legacy_C_ops.log_softmax(x, 'axis', axis) + + if dtype is None: + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'log_softmax' + ) + else: + check_dtype( + dtype, + 'dtype', + ['float32', 'float64'], + 'log_softmax', + 'If dtype is not None, it only support float32 or float64.', + ) + + helper = LayerHelper("log_softmax", **locals()) + out_cast = x + if dtype is not None: + out_cast = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='cast', + inputs={'X': x}, + outputs={'Out': out_cast}, + attrs={'in_dtype': x.dtype, 'out_dtype': dtype}, + ) + + out = helper.create_variable_for_type_inference(out_cast.dtype) + helper.append_op( + type='log_softmax', + inputs={'X': out_cast}, + outputs={'Out': out}, + attrs={'axis': axis}, + ) + + return out + + +def glu(x, axis=-1, name=None): + r""" + The gated linear unit. The input is evenly splited into 2 parts along a + given axis. The first part is used as the content, and the second part is + passed through a sigmoid function then used as the gate. The output is a + elementwise multiplication of the content and the gate. + + .. math:: + + \mathrm{GLU}(a, b) = a \otimes \sigma(b) + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + axis (int, optional): The axis along which split the input tensor. It + should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` < 0, it works the same way as :math:`axis + D` . + Default is -1. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A Tensor with the same data type as x. The size of the given aixs is + halved. + + Examples: + .. code-block:: python + + import paddle + from paddle.nn import functional as F + + x = paddle.to_tensor( + [[-0.22014759, -1.76358426, 0.80566144, 0.04241343], + [-1.94900405, -1.89956081, 0.17134808, -1.11280477]] + ) + print(F.glu(x).numpy()) + # array([[-0.15216254, -0.9004892 ], + # [-1.0577879 , -0.46985325]], dtype=float32) + + """ + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], "glu" + ) + a, b = chunk(x, 2, axis=axis, name=name) + gate = sigmoid(b, name=name) + out = paddle.multiply(a, gate, name=name) + return out + + +def gumbel_softmax(x, temperature=1.0, hard=False, axis=-1, name=None): + r""" + Samples from the Gumbel-Softmax distribution and optionally discretizes. + temperature is denoted by t. The calculation process is as follows: + + First, generate gumbel noise: + + .. math:: + + G_i = -log(-log(U_i)), U_i \sim U(0,1) + + Second, add noise to ``x``: + + .. math:: + + v = [x_1 + G_1,...,x_n + G_n] + + Finally, calculate gumbel_softmax and generate samples: + + .. math:: + gumbel\_softmax(v_i)=\frac{e^{v_i/t}}{\sum_{j=1}^n{e^{v_j/t}}},i=1,2,3...n + + Parameters: + x (Tensor): An N-D Tensor, the first N - 1 dimensions index into a batch + of independent distributions and the last dimension represents + a vector of probabilities with datatype float32, float64. + temperature (float, optional): non-negative scalar temperature. + Default is 1.0. + hard (bool, optional): if True, the returned samples will be discretized as + one-hot vectors, but will be differentiated as if it is the soft sample + in autograd. Default is False. + axis (int, optional): The axis along will be calculated softmax value. + Default is -1. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Sampled tensor of same shape as ``x`` from the Gumbel-Softmax distribution. + If ``hard = True``, the returned samples will be one-hot, otherwise they will be + probability distributions that sum to 1 across ``axis``. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + logits = paddle.randn([4, 6]) + temperature = 0.01 + gumbel_softmax = F.gumbel_softmax(logits, temperature) + print(gumbel_softmax) + # out's value is as follows: + # [[0.00000001, 1. , 0.00000000, 0.00000000, 0.00000006, 0.00000000], + # [0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 1. ], + # [0.00000062, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.99999940], + # [0.00000000, 0.00000000, 0.00000000, 0.00001258, 0.99998736, 0.00000000]] + + """ + if in_dygraph_mode(): + return _C_ops.gumbel_softmax(x, temperature, hard, axis) + + if in_dynamic_mode(): + return _legacy_C_ops.gumbel_softmax( + x, 'temperature', temperature, 'hard', hard, 'axis', axis + ) + + helper = LayerHelper("gumbel_softmax", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'gumbel_softmax') + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='gumbel_softmax', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'temperature': temperature, 'hard': hard, 'axis': axis}, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/common.py new file mode 100644 index 0000000000000000000000000000000000000000..011acc3096cccc0398a4077a737be48ffcac4dbf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/common.py @@ -0,0 +1,2388 @@ +# 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. + +import warnings +import paddle +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.layers.tensor import fill_constant +from ...tensor import concat +from ...tensor.creation import zeros +from paddle.static import Variable +from ...fluid import dygraph_utils + +# TODO: define the common functions to build a neural network +from ...tensor.manipulation import squeeze +from ...tensor.manipulation import unsqueeze +from ...tensor import clip +from ...tensor import sum +from ...tensor import sqrt +from ...fluid.data_feeder import ( + check_variable_and_dtype, + check_dtype, + check_type, +) +from ...fluid.framework import ( + _varbase_creator, + _in_legacy_dygraph, + in_dygraph_mode, + _non_static_mode, +) + +from ...fluid import dygraph_utils + +from paddle import _C_ops, _legacy_C_ops +from paddle.framework import in_dynamic_mode +from paddle.tensor.creation import full +from paddle.framework import core +from paddle.fluid.framework import _in_legacy_dygraph +from paddle.static import default_main_program + +__all__ = [] + + +def unfold(x, kernel_sizes, strides=1, paddings=0, dilations=1, name=None): + r""" + + Return a col buffer of sliding local blocks of input x, also known + as im2col for batched 2D image tensors. For each block under the convolution filter, + all element will be rearranged as a column. While the convolution filter sliding over + the input feature map, a series of such columns will be formed. + + For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout] + can be calculated as following. + + .. math:: + + dkernel[0] &= dilations[0] \times (kernel\_sizes[0] - 1) + 1 + + dkernel[1] &= dilations[1] \times (kernel\_sizes[1] - 1) + 1 + + hout &= \frac{H + paddings[0] + paddings[2] - dkernel[0]}{strides[0]} + 1 + + wout &= \frac{W + paddings[1] + paddings[3] - dkernel[1]}{strides[1]} + 1 + + Cout &= C \times kernel\_sizes[0] \times kernel\_sizes[1] + + Lout &= hout \times wout + + + Parameters: + x(Tensor): 4-D Tensor, input tensor of format [N, C, H, W], + data type can be float32 or float64 + kernel_sizes(int|list): The size of convolution kernel, should be [k_h, k_w] + or an integer k treated as [k, k]. + strides(int|list): The strides, should be [stride_h, stride_w] + or an integer stride treated as [sride, stride]. + For default, strides will be [1, 1]. + paddings(int|list): The paddings of each dimension, should be + [padding_top, padding_left, padding_bottom, padding_right] + or [padding_h, padding_w] or an integer padding. + If [padding_h, padding_w] was given, it will expanded to + [padding_h, padding_w, padding_h, padding_w]. If an integer + padding was given, [padding, padding, padding, padding] will + be used. For default, paddings will be [0, 0, 0, 0] + dilations(int|list): the dilations of convolution kernel, should be + [dilation_h, dilation_w], or an integer dilation treated as + [dilation, dilation]. For default, it will be [1, 1]. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + + Returns: + Tensor, The tensor corresponding to the sliding local blocks. + The output shape is [N, Cout, Lout] as decriabled above. + Cout is the total number of values within each block, + and Lout is the total number of such blocks. + The data type of output is the same as the input :math:`x` + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn((100,3,224,224)) + y = F.unfold(x, [3, 3], 1, 1, 1) + """ + + helper = LayerHelper("unfold", **locals()) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'unfold') + + assert len(x.shape) == 4, "input should be the format of [N, C, H, W]" + + if isinstance(kernel_sizes, int): + kernel_sizes = [kernel_sizes, kernel_sizes] + else: + assert isinstance(kernel_sizes, list) and ( + len(kernel_sizes) == 2 + ), "kernel_sizes should either be an integer or a list of two integers" + + if isinstance(strides, int): + strides = [strides, strides] + else: + assert isinstance(strides, list) and ( + len(strides) == 2 + ), "strides should either be an integer or a list of two integers" + + if isinstance(dilations, int): + dilations = [dilations, dilations] + else: + assert isinstance(dilations, list) and ( + len(dilations) == 2 + ), "dilations should either be an integer or a list of two integers" + + if isinstance(paddings, int): + paddings = [paddings] * 4 + elif isinstance(paddings, list): + if len(paddings) == 2: + paddings = paddings * 2 + elif len(paddings) == 4: + pass + else: + raise ValueError( + "paddings should either be an integer or a list of 2 or 4 integers" + ) + else: + raise ValueError( + "Unexpected type of paddings, it should be either an integer or a list" + "of 2 or 4 integers" + ) + + if in_dygraph_mode(): + return _C_ops.unfold(x, kernel_sizes, strides, paddings, dilations) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="unfold", + inputs={"X": x}, + outputs={"Y": out}, + attrs={ + "kernel_sizes": kernel_sizes, + "strides": strides, + "paddings": paddings, + "dilations": dilations, + }, + ) + return out + + +def interpolate( + x, + size=None, + scale_factor=None, + mode='nearest', + align_corners=False, + align_mode=0, + data_format='NCHW', + name=None, +): + """ + + This API resizes a batch of images. + + The input must be a 3-D Tensor of the shape (num_batches, channels, in_w) + or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape + (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels), + Where in_w is width of the input tensor, in_h is the height of the input tensor, + in_d is the depth of the intput tensor. + and the resizing only applies on the three dimensions(depth, height and width). + + Supporting resample methods: + + - 'linear' : Linear interpolation + - 'bilinear' : Bilinear interpolation + - 'trilinear' : Trilinear interpolation + - 'nearest' : Nearest neighbor interpolation + - 'bicubic' : Bicubic interpolation + - 'area': Area interpolation + + Linear interpolation is the method of using a line connecting two known quantities + to determine the value of an unknown quantity between the two known quantities. + + Nearest neighbor interpolation is to perform nearest neighbor interpolation + in both the 3rd dimension(in height direction) and the 4th dimension(in width + direction) on input tensor. + + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + Trilinear interpolation is an extension of linear interpolation for + interpolating functions of three variables (e.g. D-direction, + H-direction and W-direction in this op) on a rectilinear 3D grid. + The linear interpolation is performed on three directions. + align_corners and align_mode are optional parameters,the calculation method + of interpolation can be selected by them. + + Bicubic interpolation is an extension of cubic interpolation for interpolating + data points on a two-dimensional regular grid. The interpolated surface is + smoother than corresponding surfaces obtained by bilinear interpolation or + nearest-neighbor interpolation. + + Area interpolation is to perform area interpolation + in both the 3rd dimension(in height direction) , the 4th dimension(in width + direction) and the 5th dimension(in depth direction) on input tensor. Set to + area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or + `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`. + + Example: + + .. code-block:: text + + # For scale_factor: + if align_corners = True && out_size > 1 : + scale_factor = (in_size-1.0)/(out_size-1.0) + else: + scale_factor = float(in_size/out_size) + + # Linear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = W_{in} * scale_{factor} + + # Nearest neighbor interpolation: + + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = floor (H_{in} * scale_{factor}) + W_out = floor (W_{in} * scale_{factor}) + + # Bilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + # Bicubic interpolation: + if: + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + # Trilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = D_{in} * scale_{factor} + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + For details of linear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Linear_interpolation. + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation. + + For details of trilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Trilinear_interpolation. + + For details of bicubic interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bicubic_interpolation + + Parameters: + x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + size (list|tuple|Tensor|None): Output shape of image resize + layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w) + when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor. + Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1]. + If a Tensor, its dimensions size should be a 1. + scale_factor (float|Tensor|list|tuple|None): The multiplier for the input height or width. At + least one of :attr:`size` or :attr:`scale_factor` must be set. + And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if it is either a list or a tuple or a Tensor. + Default: None. + mode (str): The resample method. It supports 'linear', 'area', 'nearest', 'bilinear', + 'bicubic' and 'trilinear' currently. Default: 'nearest' + align_corners(bool) : An optional bool, If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the + corner pixels.This only has an effect when 'linear', 'bilinear', 'bicubic' or 'trilinear'. + Default: False + align_mode(int) : An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above, + it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for + src_idx = scale_factor*dst_index. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + Returns: + A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels), + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32) + output_1 = F.interpolate(x=input_data, size=[12,12]) + print(output_1.shape) + # [2L, 3L, 12L, 12L] + + # given scale + output_2 = F.interpolate(x=input_data, scale_factor=[2,1]) + print(output_2.shape) + # [2L, 3L, 12L, 10L] + + # bilinear interp + output_3 = F.interpolate(x=input_data, scale_factor=[2,1], mode="bilinear") + print(output_2.shape) + # [2L, 3L, 12L, 10L] + """ + data_format = data_format.upper() + resample = mode.upper() + resample_type = mode.lower() + + resample_methods = [ + 'LINEAR', + 'BILINEAR', + 'TRILINEAR', + 'NEAREST', + 'BICUBIC', + 'AREA', + ] + if resample not in resample_methods: + raise ValueError( + "The 'resample' of image_resize can only be 'area', 'linear', 'bilinear', 'trilinear', " + " 'bicubic' or 'nearest' currently." + ) + + if resample in ['LINEAR'] and len(x.shape) != 3: + raise ValueError("'linear' only support 3-D tensor.") + + if resample in ['NEAREST'] and len(x.shape) != 4 and len(x.shape) != 5: + raise ValueError("'NEAREST' only support 4-D or 5-D tensor.") + + if resample in ['BILINEAR', 'BICUBIC'] and len(x.shape) != 4: + raise ValueError("'bilinear' and 'bicubic' only support 4-D tensor.") + if resample == 'TRILINEAR' and len(x.shape) != 5: + raise ValueError("'trilinear'only support 5-D tensor.") + + if size is None and scale_factor is None: + raise ValueError("One of size and scale_factor must not be None.") + + if not isinstance(align_corners, bool): + raise TypeError("Attr align_corners should be a bool value") + + if align_mode != 0 and align_mode != 1: + raise ValueError("align_mode can only be 0 or 1") + if align_corners != 0 and resample == 'NEAREST': + raise ValueError( + "align_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinear" + ) + + if resample == 'AREA': + if ( + isinstance(size, list) + or isinstance(size, tuple) + or isinstance(size, Variable) + ): + if len(size) == 0: + raise ValueError("output size can not be empty") + if len(x.shape) == 3: + return paddle.nn.functional.adaptive_avg_pool1d(x, size) + elif len(x.shape) == 4: + return paddle.nn.functional.adaptive_avg_pool2d(x, size) + elif len(x.shape) == 5: + return paddle.nn.functional.adaptive_avg_pool3d(x, size) + + helper = LayerHelper('{}_interp_v2'.format(resample_type), **locals()) + dtype = helper.input_dtype(input_param_name='x') + if len(x.shape) == 3 and data_format not in ['NCW', 'NWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCW` or `NWC` supported for 3-D input." + ) + elif len(x.shape) == 4 and data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCHW` or `NHWC` supported for 4-D input." + ) + elif len(x.shape) == 5 and data_format not in ['NCDHW', 'NDHWC']: + raise ValueError( + "Got wrong value for param `data_format`: " + + data_format + + " received but only `NCDHW` or `NDHWC` supported for 5-D input." + ) + + def _is_list_or_turple_(data): + return isinstance(data, list) or isinstance(data, tuple) + + if data_format == 'NCHW' or data_format == 'NCDHW' or data_format == 'NCW': + data_layout = 'NCHW' + if data_format == 'NHWC' or data_format == 'NDHWC' or data_format == 'NWC': + data_layout = 'NHWC' + + if resample == 'NEAREST': + align_corners = False + + inputs = {"X": x} + attrs = { + "out_d": -1, + "out_h": -1, + "out_w": -1, + "interp_method": resample_type, + "align_corners": align_corners, + "align_mode": align_mode, + "data_layout": data_layout, + } + + out_shape = size + scale = scale_factor + if out_shape is not None and scale is not None: + raise ValueError("Only one of size or scale_factor should be defined.") + if out_shape is not None: + if isinstance(out_shape, Variable) and not in_dynamic_mode(): + out_shape.stop_gradient = True + inputs['OutSize'] = out_shape + else: + if in_dynamic_mode(): + if isinstance(out_shape, Variable): + out_shape = list(out_shape.numpy()) + else: + out_shape = list(out_shape) + for i, dim in enumerate(out_shape): + if isinstance(dim, Variable): + out_shape[i] = dim.numpy()[0] + if not (_is_list_or_turple_(out_shape)): + raise TypeError("size should be a list or tuple or Variable.") + # Validate the shape + contain_var = False + for dim_idx, dim_size in enumerate(out_shape): + if isinstance(dim_size, Variable): + contain_var = True + continue + assert ( + dim_size > 0 + ), "Each dimension size given in out_shape must be greater than 0." + + if contain_var: + new_size_tensor = [] + size_list = [] + for dim in out_shape: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_size_tensor.append(dim) + size_list.append(-1) + else: + assert isinstance(dim, int) + temp_out = helper.create_variable_for_type_inference( + 'int32' + ) + fill_constant( + [1], 'int32', dim, force_cpu=True, out=temp_out + ) + new_size_tensor.append(temp_out) + size_list.append(dim) + inputs['SizeTensor'] = new_size_tensor + + if len(x.shape) == 3: + if len(out_shape) != 1: + raise ValueError( + "size length should be 2 for input 3-D tensor" + ) + if contain_var: + attrs['out_w'] = size_list[0] + else: + out_shape = list(map(int, out_shape)) + attrs['out_w'] = out_shape[0] + if len(x.shape) == 4: + if len(out_shape) != 2: + raise ValueError( + "size length should be 2 for " "input 4-D tensor." + ) + if contain_var: + attrs['out_h'] = size_list[0] + attrs['out_w'] = size_list[1] + else: + out_shape = list(map(int, out_shape)) + attrs['out_h'] = out_shape[0] + attrs['out_w'] = out_shape[1] + if len(x.shape) == 5: + if len(out_shape) != 3: + raise ValueError( + "size length should be 3 for " "input 5-D tensor." + ) + if contain_var: + attrs['out_d'] = size_list[0] + attrs['out_h'] = size_list[1] + attrs['out_w'] = size_list[2] + else: + out_shape = list(map(int, out_shape)) + attrs['out_d'] = out_shape[0] + attrs['out_h'] = out_shape[1] + attrs['out_w'] = out_shape[2] + + else: + if in_dynamic_mode() and isinstance(scale, Variable): + scale = list(scale.numpy()) + if isinstance(scale, Variable): + scale.stop_gradient = True + inputs["Scale"] = scale + elif isinstance(scale, float) or isinstance(scale, int): + if scale <= 0: + raise ValueError("Attr(scale) should be greater than zero.") + scale_list = [] + for i in range(len(x.shape) - 2): + scale_list.append(scale) + attrs['scale'] = list(map(float, scale_list)) + elif isinstance(scale, list) or isinstance(scale, tuple): + if len(scale) != len(x.shape) - 2: + raise ValueError( + "scale_shape length should be {} for " + "input {}-D tensor.".format(len(x.shape) - 2, len(x.shape)) + ) + for value in scale: + if value <= 0: + raise ValueError("Attr(scale) should be greater than zero.") + attrs['scale'] = list(map(float, scale)) + else: + raise TypeError( + "Attr(scale)'s type should be float, int, list, tuple, or Tensor." + ) + + if in_dynamic_mode(): + attr_list = [] + for k, v in attrs.items(): + attr_list.append(k) + attr_list.append(v) + dy_attr = tuple(attr_list) + + if resample_type == "linear": + if in_dygraph_mode(): + out = _C_ops.linear_interp( + x, + inputs['OutSize'] if 'OutSize' in inputs else None, + inputs['SizeTensor'] if 'SizeTensor' in inputs else None, + inputs['Scale'] if 'Scale' in inputs else None, + attrs['data_layout'], + attrs['out_d'], + attrs['out_h'], + attrs['out_w'], + attrs['scale'] if 'scale' in attrs else [], + attrs['interp_method'], + attrs['align_corners'], + attrs['align_mode'], + ) + else: + out = _legacy_C_ops.linear_interp_v2(x, *dy_attr) + elif resample_type == "bilinear": + if in_dygraph_mode(): + out = _C_ops.bilinear_interp( + x, + inputs['OutSize'] if 'OutSize' in inputs else None, + inputs['SizeTensor'] if 'SizeTensor' in inputs else None, + inputs['Scale'] if 'Scale' in inputs else None, + attrs['data_layout'], + attrs['out_d'], + attrs['out_h'], + attrs['out_w'], + attrs['scale'] if 'scale' in attrs else [], + attrs['interp_method'], + attrs['align_corners'], + attrs['align_mode'], + ) + else: + out = _legacy_C_ops.bilinear_interp_v2(x, *dy_attr) + elif resample_type == "trilinear": + if in_dygraph_mode(): + out = _C_ops.trilinear_interp( + x, + inputs['OutSize'] if 'OutSize' in inputs else None, + inputs['SizeTensor'] if 'SizeTensor' in inputs else None, + inputs['Scale'] if 'Scale' in inputs else None, + attrs['data_layout'], + attrs['out_d'], + attrs['out_h'], + attrs['out_w'], + attrs['scale'] if 'scale' in attrs else [], + attrs['interp_method'], + attrs['align_corners'], + attrs['align_mode'], + ) + else: + out = _legacy_C_ops.trilinear_interp_v2(x, *dy_attr) + elif resample_type == "nearest": + if in_dygraph_mode(): + out = _C_ops.nearest_interp( + x, + inputs['OutSize'] if 'OutSize' in inputs else None, + inputs['SizeTensor'] if 'SizeTensor' in inputs else None, + inputs['Scale'] if 'Scale' in inputs else None, + attrs['data_layout'], + attrs['out_d'], + attrs['out_h'], + attrs['out_w'], + attrs['scale'] if 'scale' in attrs else [], + attrs['interp_method'], + attrs['align_corners'], + attrs['align_mode'], + ) + else: + out = _legacy_C_ops.nearest_interp_v2(x, *dy_attr) + elif resample_type == "bicubic": + if in_dygraph_mode(): + out = _C_ops.bicubic_interp( + x, + inputs['OutSize'] if 'OutSize' in inputs else None, + inputs['SizeTensor'] if 'SizeTensor' in inputs else None, + inputs['Scale'] if 'Scale' in inputs else None, + attrs['data_layout'], + attrs['out_d'], + attrs['out_h'], + attrs['out_w'], + attrs['scale'] if 'scale' in attrs else [], + attrs['interp_method'], + attrs['align_corners'], + attrs['align_mode'], + ) + else: + out = _legacy_C_ops.bicubic_interp_v2(x, *dy_attr) + return out + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='{}_interp_v2'.format(resample_type), + inputs=inputs, + outputs={"Out": out}, + attrs=attrs, + ) + return out + + +def upsample( + x, + size=None, + scale_factor=None, + mode='nearest', + align_corners=False, + align_mode=0, + data_format='NCHW', + name=None, +): + """ + + This API resizes a batch of images. + + The input must be a 3-D Tensor of the shape (num_batches, channels, in_w) + or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape + (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels), + Where in_w is width of the input tensor, in_h is the height of the input tensor, + in_d is the depth of the intput tensor. + and the resizing only applies on the three dimensions(depth, height and width). + + Supporting resample methods: + - 'linear' : Linear interpolation + - 'bilinear' : Bilinear interpolation + - 'trilinear' : Trilinear interpolation + - 'nearest' : Nearest neighbor interpolation + - 'bicubic' : Bicubic interpolation + + Linear interpolation is the method of using a line connecting two known quantities + to determine the value of an unknown quantity between the two known quantities. + + Nearest neighbor interpolation is to perform nearest neighbor interpolation + in both the 3rd dimension(in height direction) and the 4th dimension(in width + direction) on input tensor. + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + Bicubic interpolation is an extension of cubic interpolation for interpolating + data points on a two-dimensional regular grid. The interpolated surface is + smoother than corresponding surfaces obtained by bilinear interpolation or + nearest-neighbor interpolation. + + Trilinear interpolation is an extension of linear interpolation for + interpolating functions of three variables (e.g. D-direction, + H-direction and W-direction in this op) on a rectilinear 3D grid. + + The linear interpolation is performed on three directions. + align_corners and align_mode are optional parameters,the calculation method + of interpolation can be selected by them. + + Area interpolation is to perform area interpolation + in both the 3rd dimension(in height direction) , the 4th dimension(in width + direction) and the 5th dimension(in depth direction) on input tensor. Set to + area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or + `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`. + + Example: + .. code-block:: text + + For scale_factor: + if align_corners = True && out_size > 1 : + scale_factor = (in_size-1.0)/(out_size-1.0) + else: + scale_factor = float(in_size/out_size) + Linear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = W_{in} * scale_{factor} + Nearest neighbor interpolation: + if: + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = floor (H_{in} * scale_{factor}) + W_out = floor (W_{in} * scale_{factor}) + else: + align_corners = True + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = round(H_{in} * scale_{factor}) + W_out = round(W_{in} * scale_{factor}) + + Bilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + Bicubic interpolation: + if: + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + Trilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = D_{in} * scale_{factor} + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + For details of linear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Linear_interpolation. + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation. + + For details of bicubic interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bicubic_interpolation + + For details of trilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Trilinear_interpolation. + + Parameters: + x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + size (list|tuple|Tensor|None, optional): Output shape of image resize + layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w) + when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor. + Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1]. + If a Tensor , its dimensions size should be a 1. + scale_factor (float|Tensor|list|tuple|None, optional): The multiplier for the input height or width. At + least one of :attr:`size` or :attr:`scale_factor` must be set. + And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if + it is either a list or a tuple or a Tensor. + Default: None. + mode (str, optional): The resample method. It supports 'linear', 'nearest', 'bilinear', + 'bicubic' and 'trilinear' currently. Default: 'nearest' + align_corners(bool, optional) : An optional bool, If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the + corner pixels. + Default: False + align_mode(int, optional) : An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above, + it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for + src_idx = scale_factor*dst_index. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels), + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32) + upsample_out = paddle.nn.Upsample(size=[12,12]) + + output = upsample_out(x=input_data) + print(output.shape) + # [2L, 3L, 12L, 12L] + + """ + return interpolate( + x, size, scale_factor, mode, align_corners, align_mode, data_format + ) + + +def bilinear(x1, x2, weight, bias=None, name=None): + """ + + This layer performs bilinear on two inputs. + See :ref:`api_nn_Bilinear` for details and output shape. + + Parameters: + x1 (Tensor): the first input tensor, it's data type should be float32, float64. + x2 (Tensor): the second input tensor, it's data type should be float32, float64. + weight (Parameter): The learnable weights of this layer, shape is [out_features, in1_features, in2_features]. + bias (Parameter, optional): The learnable bias(Bias) of this layer, shape is [1, out_features]. If it is set to None, no bias will be added to the output units. The default value is None. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None. + + Returns: + Tensor: A 2-D Tensor of shape [batch_size, out_features]. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x1 = paddle.randn((5, 5)).astype(paddle.float32) + x2 = paddle.randn((5, 4)).astype(paddle.float32) + w = paddle.randn((1000, 5, 4)).astype(paddle.float32) + b = paddle.randn((1, 1000)).astype(paddle.float32) + + result = F.bilinear(x1, x2, w, b) + print(result.shape) + # [5, 1000] + """ + + if in_dygraph_mode(): + return _C_ops.bilinear_tensor_product(x1, x2, weight, bias) + elif _non_static_mode(): + return _legacy_C_ops.bilinear_tensor_product(x1, x2, weight, bias) + + check_variable_and_dtype(x1, 'x1', ['float32', 'float64'], 'bilinear') + check_variable_and_dtype(x2, 'x2', ['float32', 'float64'], 'bilinear') + + inputs = {"X": x1, "Y": x2, "Weight": weight} + if bias is not None: + inputs["Bias"] = bias + + helper = LayerHelper("bilinear", **locals()) + out = helper.create_variable_for_type_inference(dtype=x1.dtype) + + helper.append_op( + type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out} + ) + + return out + + +def dropout( + x, p=0.5, axis=None, training=True, mode="upscale_in_train", name=None +): + """ + Dropout is a regularization technique for reducing overfitting by preventing + neuron co-adaption during training. The dropout operator randomly sets the + outputs of some units to zero, while upscale others according to the given + dropout probability. + + Args: + x (Tensor): The input tensor. The data type is float32 or float64. + p (float|int, optional): Probability of setting units to zero. Default 0.5. + axis (int|list|tuple, optional): The axis along which the dropout is performed. Default None. + training (bool, optional): A flag indicating whether it is in train phrase or not. Default True. + mode(str, optional): ['upscale_in_train'(default) | 'downscale_in_infer']. + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - dropout_prob ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - dropout_prob) + + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor representing the dropout, has same shape and data type as `x` . + + + Examples: + We use ``p=0.5`` in the following description for simplicity. + + 1. When ``axis=None`` , this is commonly used dropout, which dropout each element of x randomly. + + .. code-block:: text + + Let's see a simple case when x is a 2d tensor with shape 2*3: + [[1 2 3] + [4 5 6]] + we generate mask with the same shape as x, which is 2*3. The value of mask is + sampled from a Bernoulli distribution randomly. For example, we may get such mask: + [[0 1 0] + [1 0 1]] + So the output is obtained from elementwise multiply of x and mask: + [[0 2 0] + [4 0 6]] + Using default setting, i.e. ``mode='upscale_in_train'`` , + if in training phase, the final upscale output is: + [[0 4 0 ] + [8 0 12]] + if in test phase, the output is the same as input: + [[1 2 3] + [4 5 6]] + we can also set ``mode='downscale_in_infer'`` , then + if in training phase, the final output is: + [[0 2 0] + [4 0 6]] + if in test phase, the scale output is: + [[0.5 1. 1.5] + [2. 2.5 3. ]] + + + + 2. When ``axis!=None`` , this is useful for dropping whole channels from an image or sequence. + + .. code-block:: text + + Let's see the simple case when x is a 2d tensor with shape 2*3 again: + [[1 2 3] + [4 5 6]] + (1) If ``axis=0`` , this means the dropout is only performed in axis `0` . + we generate mask with the shape 2*1. Only in axis `0` the value is randomly selected. + For example, we may get such mask: + [[1] + [0]] + The output is obtained from elementwise multiply of x and mask. Doing that the mask will be + broadcast from 2*1 to 2*3: + [[1 1 1] + [0 0 0]] + and the result after elementwise multiply is: + [[1 2 3] + [0 0 0]] + then we can do upscale or downscale according to the setting of other arguments. + (2) If ``axis=1`` , this means the dropout is only performed in axis `1` . + we generate mask with the shape 1*3. Only in axis `1` the value is randomly selected. + For example, we may get such mask: + [[1 0 1]] + Doing elementwise multiply the mask will be broadcast from 1*3 to 2*3: + [[1 0 1] + [1 0 1]] + and the result after elementwise multiply is: + [[1 0 3] + [4 0 6]] + (3) What about ``axis=[0, 1]`` ? This means the dropout is performed in all axes of x, + which is the same case as default setting ``axis=None`` . + (4) You may note that logically `axis=None` means the dropout is performed in none axis of x, + We generate mask with the shape 1*1. Whole input is randomly selected or dropped. + For example, we may get such mask: + [[0]] + Doing elementwise multiply the mask will be broadcast from 1*1 to 2*3: + [[0 0 0] + [0 0 0]] + and the result after elementwise multiply is: + [[0 0 0] + [0 0 0]] + Actually this is not what we want because all elements may set to zero~ + + When x is a 4d tensor with shape `NCHW`, we can set ``axis=[0,1]`` and the dropout will be performed in channel `N` and `C`, `H` and `W` is tied, i.e. paddle.nn.dropout(x, p, axis=[0,1]) . Please refer to ``paddle.nn.functional.dropout2d`` for more details. + Similarly, when x is a 5d tensor with shape `NCDHW`, we can set ``axis=[0,1]`` to perform dropout3d. Please refer to ``paddle.nn.functional.dropout3d`` for more details. + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1,2,3], [4,5,6]]).astype(paddle.float32) + y_train = paddle.nn.functional.dropout(x, 0.5) + y_test = paddle.nn.functional.dropout(x, 0.5, training=False) + y_0 = paddle.nn.functional.dropout(x, axis=0) + y_1 = paddle.nn.functional.dropout(x, axis=1) + y_01 = paddle.nn.functional.dropout(x, axis=[0,1]) + print(x) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[1., 2., 3.], + # [4., 5., 6.]]) + print(y_train) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[2. , 0. , 6. ], + # [8. , 0. , 12.]]) + print(y_test) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[1., 2., 3.], + # [4., 5., 6.]]) + print(y_0) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[0. , 0. , 0. ], + # [8. , 10., 12.]]) + print(y_1) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[2. , 0. , 6. ], + # [8. , 0. , 12.]]) + print(y_01) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[0. , 0. , 0. ], + # [8. , 0. , 12.]]) + + """ + if not isinstance(p, (float, int, Variable)): + raise TypeError("p argument should be a number or Variable") + + if isinstance(p, (int, float)): + # fast return for p == 0 + if p == 0: + return x + elif p < 0 or p > 1: + raise ValueError("p argument should between 0 and 1") + if mode not in ('downscale_in_infer', 'upscale_in_train'): + raise ValueError( + "mode argument should be 'downscale_in_infer' or 'upscale_in_train'" + ) + if axis and not isinstance(axis, (int, list, tuple)): + raise TypeError("datatype of axis argument should be int or list") + + if axis == None: # commonly used dropout + seed = None + mode = ( + 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode + ) # semantic transfer + + if _non_static_mode(): + if default_main_program().random_seed != 0: + seed = default_main_program().random_seed + + if in_dygraph_mode(): + out, mask = _C_ops.dropout( + x, + None, + p, + not training, + mode, + seed if seed is not None else 0, + seed is not None, + ) + + return out + out, mask = _legacy_C_ops.dropout( + x, + 'dropout_prob', + p, + 'is_test', + not training, + 'fix_seed', + seed is not None, + 'seed', + seed if seed is not None else 0, + 'dropout_implementation', + mode, + ) + return out + + helper = LayerHelper('dropout', **locals()) + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'dropout' + ) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + mask = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True + ) + + def get_attrs(prog, dropout_prob, is_test, seed): + if (seed is None or seed == 0) and prog.random_seed != 0: + seed = prog.random_seed + + if isinstance( + dropout_prob, Variable + ) and not dropout_prob.shape != [1]: + raise TypeError( + "Required p.shape == [1] if type(p) is Variable, but received p.shape = {}".format( + p.shape + ) + ) + attrs = { + 'dropout_prob': dropout_prob, + 'is_test': is_test, + 'fix_seed': seed is not None, + 'seed': seed if seed is not None else 0, + 'dropout_implementation': mode, + } + return attrs + + attrs = get_attrs(helper.main_program, p, not training, seed) + + helper.append_op( + type='dropout', + inputs={'X': [x]}, + outputs={'Out': [out], 'Mask': [mask]}, + attrs=attrs, + ) + return out + else: # sometimes called dropout_nd #TODO: optimize with c++ + if not in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'dropout') + dtype = x.dtype + keep_prob = 1 - p + if training: + if in_dynamic_mode() and p == 1.0: + return paddle.scale(x, scale=0.0) + + scale_input = ( + paddle.scale(x, scale=1 / keep_prob) + if mode == 'upscale_in_train' + else x + ) + + # get mask shape + input_shape = x.shape + if not in_dynamic_mode(): + input_shape_tensor = paddle.shape(x) + drop_axes = [axis] if isinstance(axis, int) else list(axis) + if min(drop_axes) < 0 or max(drop_axes) > len(input_shape) - 1: + raise ValueError( + "axis value should be greater than or equal to 0 and less than dimensions of x:{}, but get axis value:{} ".format( + len(input_shape), max(drop_axes) + ) + ) + if len(drop_axes) > len(input_shape): + raise ValueError( + "length of axis should not be greater than dimensions of x:{}, but get length of axis: {}".format( + len(input_shape), len(drop_axes) + ) + ) + mask_shape = [1] * len(input_shape) + if not in_dynamic_mode(): + for i in drop_axes: + mask_shape[i] = input_shape_tensor[i] + else: + for i in drop_axes: + mask_shape[i] = input_shape[i] + + # get mask + random_tensor = paddle.uniform( + mask_shape, dtype='float32', min=0.0, max=1.0 + ) + p = full(shape=[1], fill_value=p, dtype='float32') + keep_mask = paddle.greater_equal(random_tensor, p) + + scale_input = paddle.cast(scale_input, dtype) + keep_mask = paddle.cast(keep_mask, dtype) + ret = paddle.multiply(scale_input, keep_mask, name=name) + return ret + else: # test + ret = ( + paddle.scale(x, scale=keep_prob) + if mode == 'downscale_in_infer' + else x + ) + return ret + + +def dropout2d(x, p=0.5, training=True, data_format='NCHW', name=None): + """ + Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` , + a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently + on every forward call with probability `p` using samples from a Bernoulli distribution. + + See ``paddle.nn.functional.dropout`` for more details. + + Args: + x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C]. + The data type is float32 or float64. + p (float): Probability of setting units to zero. Default 0.5. + training (bool): A flag indicating whether it is in train phrase or not. Default True. + data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC` . The default is `NCHW` . When it is `NCHW` , the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor representing the dropout2d, has same shape and data type as `x` . + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randn(shape=(2, 3, 4, 5)).astype(paddle.float32) + y_train = paddle.nn.functional.dropout2d(x) #train + y_test = paddle.nn.functional.dropout2d(x, training=False) #test + for i in range(2): + for j in range(3): + print(x[i,j,:,:]) + print(y_train[i,j,:,:]) # may all 0 + print(y_test[i,j,:,:]) + + """ + input_shape = x.shape + if len(input_shape) != 4: + raise ValueError( + "dimensions of x should be 4, but received {} != 4".format( + len(input_shape) + ) + ) + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + return dropout( + x, + p=p, + axis=[0, 1] if data_format == 'NCHW' else [0, 3], + training=training, + mode="upscale_in_train", + name=name, + ) + + +def dropout3d(x, p=0.5, training=True, data_format='NCDHW', name=None): + """ + Randomly zero out entire channels (in the batched input 5d tensor with the shape `NCDHW` , + a channel is a 3D feature map with the shape `DHW` ). Each channel will be zeroed out independently + on every forward call with probability `p` using samples from a Bernoulli distribution. + + See ``paddle.nn.functional.dropout`` for more details. + + Args: + x (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C]. + The data type is float32 or float64. + p (float): Probability of setting units to zero. Default 0.5. + training (bool): A flag indicating whether it is in train phrase or not. Default True. + data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from ``NCDHW`` or ``NDHWC``. The default is ``NCDHW`` . When it is ``NCDHW`` , the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor representing the dropout3d, has same shape and data type with `x` . + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randn(shape=(2, 3, 4, 5, 6)).astype(paddle.float32) + y_train = paddle.nn.functional.dropout3d(x) #train + y_test = paddle.nn.functional.dropout3d(x, training=False) #test + print(x[0,0,:,:,:]) + print(y_train[0,0,:,:,:]) # may all 0 + print(y_test[0,0,:,:,:]) + + """ + + input_shape = x.shape + if len(input_shape) != 5: + raise ValueError( + "dimensions of x should be 5, but received {} != 5".format( + len(input_shape) + ) + ) + + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + return dropout( + x, + p=p, + axis=[0, 1] if data_format == 'NCDHW' else [0, 4], + training=training, + mode="upscale_in_train", + name=name, + ) + + +def alpha_dropout(x, p=0.5, training=True, name=None): + """ + Alpha Dropout is a type of Dropout that maintains the self-normalizing property. + For an input with zero mean and unit standard deviation, the output of Alpha Dropout + maintains the original mean and standard deviation of the input. + Alpha Dropout fits well to SELU activate function by randomly setting activations to the negative saturation value. + + Args: + x (Tensor): The input tensor. The data type is float32 or float64. + p (float | int): Probability of setting units to zero. Default 0.5. + training (bool): A flag indicating whether it is in train phrase or not. Default True. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor representing the dropout, has same shape and data type as `x`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1, 1], [-1, 1]]).astype(paddle.float32) + y_train = paddle.nn.functional.alpha_dropout(x, 0.5) + y_test = paddle.nn.functional.alpha_dropout(x, 0.5, training=False) + print(y_train) + # Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[-0.10721093, -0.77919382], + # [-0.10721093, 1.66559887]]) (randomly) + print(y_test) + # Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[-1., 1.], + # [-1., 1.]]) + """ + if not isinstance(p, (float, int)): + raise TypeError("p argument should be a float or int") + if p < 0 or p > 1: + raise ValueError("p argument should between 0 and 1") + + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float32', 'float64'], 'alpha_dropout' + ) + + if training: + if p == 1: + return paddle.scale(x, scale=0.0) + # get transformation params + alpha = 1.6732632423543772848170429916717 + scale = 1.0507009873554804934193349852946 + alpha_p = -alpha * scale + a = ((1 - p) * (1 + p * alpha_p**2)) ** -0.5 + b = -a * alpha_p * p + + dtype = x.dtype + input_shape = x.shape + + # get mask + random_tensor = paddle.uniform( + input_shape, dtype='float32', min=0.0, max=1.0 + ) + p = full(shape=[1], fill_value=p, dtype='float32') + keep_mask = paddle.greater_equal(random_tensor, p) + keep_mask = paddle.cast(keep_mask, dtype) + drop_mask = paddle.subtract( + full(shape=input_shape, fill_value=1.0, dtype=dtype), keep_mask + ) + + # apply mask + b = full(shape=[1], fill_value=b, dtype=dtype) + y = paddle.add( + paddle.multiply(x, keep_mask), + paddle.scale(drop_mask, scale=alpha_p), + ) + res = paddle.add(paddle.scale(y, scale=a), b, name=name) + return res + else: # test + return x + + +def pad(x, pad, mode='constant', value=0, data_format="NCHW", name=None): + """ + Pad tensor according to 'pad' and 'mode'. + If mode is 'constant' and length of pad is twice as length of x dimension, + then the padding will be started from the first dimension and moved back onto x + according to 'pad' and 'value'. + If mode is 'reflect', pad[0] and pad[1] must be no greater + than width-1. The height and depth dimension has the same condition. + + Parameters: + x (Tensor): The input tensor with data type float32/double/int32/int64_t. + pad (Tensor|list[int]|tuple[int]): The padding size with data type int. + If mode is 'constant' and length of pad is twice as length of x dimension, then x will + be padded from the first dimension to the last dimension. + Else: 1. If input dimension is 3, then the pad has the form (pad_left, + pad_right). 2. If the input dimension is 4, then the pad has the form (pad_left, pad_right, + pad_top, pad_bottom). 3. If the input dimension is 5, then the pad has the form + (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back). + mode (str, optional): Four modes: 'constant' (default), 'reflect', 'replicate', 'circular'. Default is 'constant' + + - 'constant' mode, uses a constant value to pad the input tensor. + - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + - 'replicate' mode, uses input boundaries to pad the input tensor. + - 'circular' mode, uses circular input to pad the input tensor. + + value (float, optional): The value to fill the padded areas in 'constant' mode . Default is :math:`0.0`, + data_format (str, optional): An string from: "NCL", "NLC", NHWC", "NCHW", "NCDHW", "NDHWC". Specify the data format of + the input data. Default is "NCHW", + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, a Tensor padded according to pad and mode and data type is same as input. + + Example: + + .. code-block:: text + + x = [[[[[1., 2., 3.], + [4., 5., 6.]]]]] + + Case 0: + pad = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0], + mode = 'constant' + value = 0 + Out = [[[[[0., 0., 0.], + [1., 2., 3.], + [4., 5., 6.], + [0., 0., 0.]]]]] + + Case 1: + pad = [2, 2, 1, 1, 0, 0], + mode = 'constant' + value = 0 + Out = [[[[[0. 0. 0. 0. 0. 0. 0.] + [0. 0. 1. 2. 3. 0. 0.] + [0. 0. 4. 5. 6. 0. 0.] + [0. 0. 0. 0. 0. 0. 0.]]]]] + + Case 2: + pad = [2, 2, 1, 1, 0, 0], + mode = 'reflect' + Out = [[[[[6. 5. 4. 5. 6. 5. 4.] + [3. 2. 1. 2. 3. 2. 1.] + [6. 5. 4. 5. 6. 5. 4.] + [3. 2. 1. 2. 3. 2. 1.]]]]] + + Case 3: + pad = [2, 2, 1, 1, 0, 0], + mode = 'replicate' + Out = [[[[[1. 1. 1. 2. 3. 3. 3.] + [1. 1. 1. 2. 3. 3. 3.] + [4. 4. 4. 5. 6. 6. 6.] + [4. 4. 4. 5. 6. 6. 6.]]]]] + + Case 4: + pad = [2, 2, 1, 1, 0, 0], + mode = 'circular' + Out = [[[[[5. 6. 4. 5. 6. 4. 5.] + [2. 3. 1. 2. 3. 1. 2.] + [5. 6. 4. 5. 6. 4. 5.] + [2. 3. 1. 2. 3. 1. 2.]]]]] + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # example 1 + x_shape = (1, 1, 3) + x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1 + y = F.pad(x, [0, 0, 0, 0, 2, 3], value=1, mode='constant', data_format="NCL") + print(y) + # [[[1. 1. 1. 2. 3. 1. 1. 1.]]] + + # example 2 + x_shape = (1, 1, 3) + x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1 + y = F.pad(x, [2, 3], value=1, mode='constant', data_format="NCL") + print(y) + # [[[1. 1. 1. 2. 3. 1. 1. 1.]]] + + # example 3 + x_shape = (1, 1, 2, 3) + x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1 + y = F.pad(x, [1, 2, 1, 1], value=1, mode='circular') + print(y) + # [[[[6. 4. 5. 6. 4. 5.] + # [3. 1. 2. 3. 1. 2.] + # [6. 4. 5. 6. 4. 5.] + # [3. 1. 2. 3. 1. 2.]]]] + """ + assert mode in [ + 'reflect', + 'replicate', + 'constant', + 'circular', + ], "mode should be one of constant, reflect, replicate, circular, but got {}.".format( + mode + ) + + data_format = data_format.upper() + assert data_format in ["NCL", "NCHW", "NCDHW", "NLC", "NHWC", "NDHWC"], ( + "data_format should be in one of [NCL, NCHW, NCDHW, NLC, NHWC, NDHWC], " + "but got {}".format(data_format) + ) + + x_dim = len(x.shape) + + if ( + mode == "constant" + and isinstance(pad, (list, tuple)) + and len(pad) == x_dim * 2 + ): + paddings = pad + pad_value = value + + if in_dygraph_mode(): + out = _C_ops.pad(x, paddings, float(pad_value)) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + "pad", + ) + + check_type(pad_value, 'pad_value', (float, int, Variable), 'pad') + if isinstance(pad_value, int): + pad_value = float(pad_value) + + helper = LayerHelper('pad', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='pad', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'paddings': paddings, 'pad_value': pad_value}, + ) + return out + + assert x_dim in [ + 3, + 4, + 5, + ], "input tesor dimension must be in [3, 4, 5] but got {}".format(x_dim) + + supported_format_map = { + 3: ["NCL", "NLC"], + 4: ["NCHW", "NHWC"], + 5: ["NCDHW", "NDHWC"], + } + assert ( + data_format in supported_format_map[x_dim] + ), "input tensor dimension is {}, it's data format should be in {} but got {}".format( + x_dim, supported_format_map[x_dim], data_format + ) + + unsqueezed_dim = [] + + if isinstance(pad, Variable): + if data_format in ["NCL", "NCHW", "NCDHW"]: + data_format = "NCDHW" + if x_dim == 3: + pad = concat([zeros((4,), dtype="int32"), pad], axis=0) + unsqueezed_dim = [3, 4] + x = unsqueeze(x, axis=unsqueezed_dim) + elif x_dim == 4: + pad = concat([pad, zeros((2,), dtype="int32")], axis=0) + unsqueezed_dim = [2] + x = unsqueeze(x, axis=unsqueezed_dim) + elif data_format in ["NLC", "NHWC", "NDHWC"]: + data_format = "NDHWC" + if x_dim == 3: + pad = concat([zeros((4,), dtype="int32"), pad], axis=0) + unsqueezed_dim = [2, 3] + x = unsqueeze(x, axis=unsqueezed_dim) + elif x_dim == 4: + pad = concat([pad, zeros((2,), dtype="int32")], axis=0) + unsqueezed_dim = [1] + x = unsqueeze(x, axis=unsqueezed_dim) + else: + pad = list(pad) + if data_format in ["NCL", "NCHW", "NCDHW"]: + data_format = "NCDHW" + if x_dim == 3: + pad = [0, 0, 0, 0] + pad + unsqueezed_dim = [3, 4] + x = unsqueeze(x, axis=unsqueezed_dim) + elif x_dim == 4: + pad = pad + [0, 0] + unsqueezed_dim = [2] + x = unsqueeze(x, axis=unsqueezed_dim) + elif data_format in ["NLC", "NHWC", "NDHWC"]: + data_format = "NDHWC" + if x_dim == 3: + pad = [0, 0, 0, 0] + pad + unsqueezed_dim = [2, 3] + x = unsqueeze(x, axis=unsqueezed_dim) + elif x_dim == 4: + pad = pad + [0, 0] + unsqueezed_dim = [1] + x = unsqueeze(x, axis=unsqueezed_dim) + + if in_dygraph_mode(): + if isinstance(pad, Variable): + pad = pad.numpy().tolist() + out = _C_ops.pad3d(x, pad, mode, value, data_format) + else: + if _in_legacy_dygraph(): + if isinstance(pad, Variable): + pad = pad.numpy().tolist() + out = _legacy_C_ops.pad3d( + x, + "paddings", + pad, + "mode", + mode, + "value", + value, + "data_format", + data_format, + "name", + name, + ) + else: + attrs = {'mode': mode, 'value': value, 'data_format': data_format} + inputs = {'X': [x]} + if isinstance(pad, Variable): + inputs['Paddings'] = [pad] + attrs['paddings'] = [] + else: + attrs['paddings'] = pad + + helper = LayerHelper('pad3d', **locals()) + + dtype = helper.input_dtype(input_param_name='input') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='pad3d', inputs=inputs, outputs={"Out": out}, attrs=attrs + ) + + if len(unsqueezed_dim) != 0: + out = squeeze(out, axis=unsqueezed_dim) + + return out + + +def zeropad2d(x, padding, data_format="NCHW", name=None): + """ + Pads the input tensor boundaries with zero according to 'pad'. + + Args: + x(Tensor): The input tensor with data type float16/float32/float64/int32/int64. + padding(int | Tensor | List[int] | Tuple[int]): The padding size with data type int. + The input dimension should be 4 and pad has the form (pad_left, pad_right, + pad_top, pad_bottom). + data_format(str, optional): An string from: "NHWC", "NCHW". Specify the data format of + the input data. Default: "NCHW". + name(str, optional): The default value is None. Normally there is no need for user + to set this property. + + Returns: + Tensor, padded with 0 according to pad and data type is same as input. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + import paddle.nn.functional as F + + x_shape = (1, 1, 2, 3) + x = paddle.arange(np.prod(x_shape), dtype="float32").reshape(x_shape) + 1 + y = F.zeropad2d(x, [1, 2, 1, 1]) + # [[[[0. 0. 0. 0. 0. 0.] + # [0. 1. 2. 3. 0. 0.] + # [0. 4. 5. 6. 0. 0.] + # [0. 0. 0. 0. 0. 0.]]]] + """ + + return pad( + x, + pad=padding, + mode='constant', + value=0, + data_format=data_format, + name=name, + ) + + +def cosine_similarity(x1, x2, axis=1, eps=1e-8): + """ + Compute cosine similarity between x1 and x2 along axis. + + Parameters: + x1 (Tensor): First input. float32/double. + x2 (Tensor): Second input. float32/double. + axis (int, optional): Dimension of vectors to compute cosine similarity. Default is 1. + eps(float, optional): Small value to avoid division by zero. Default is 1e-8. + + Returns: + Tensor, a Tensor representing cosine similarity between x1 and x2 along axis. + + Examples: + .. code-block:: text + + Case 0: + x1 = [[0.8024077 0.9927354 0.27238318 0.8344984 ] + [0.48949873 0.5797396 0.65444374 0.66510963] + [0.1031398 0.9614342 0.08365563 0.6796464 ] + [0.10760343 0.7461209 0.7726148 0.5801006 ]] + x2 = [[0.62913156 0.1536727 0.9847992 0.04591406] + [0.9098952 0.15715368 0.8671125 0.3156102 ] + [0.4427798 0.54136837 0.5276275 0.32394758] + [0.3769419 0.8535014 0.48041078 0.9256797 ]] + axis = 1 + eps = 1e-8 + Out: [0.5275037 0.8368967 0.75037485 0.9245899] + + Code Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + paddle.seed(1) + x1 = paddle.randn(shape=[2, 3]) + x2 = paddle.randn(shape=[2, 3]) + + result = paddle.nn.functional.cosine_similarity(x1, x2, axis=0) + print(result) + # [0.97689527, 0.99996042, -0.55138415] + + """ + w12 = sum(paddle.multiply(x1, x2), axis=axis) + w1 = sum(paddle.multiply(x1, x1), axis=axis) + w2 = sum(paddle.multiply(x2, x2), axis=axis) + n12 = sqrt(clip(w1 * w2, min=eps * eps)) + cos_sim = w12 / n12 + return cos_sim + + +def linear(x, weight, bias=None, name=None): + r""" + + Fully-connected linear transformation operator. For each input :math:`X` , + the equation is: + + .. math:: + + Out = XW + b + + where :math:`W` is the weight and :math:`b` is the bias. + + If the weight is a 2-D tensor of shape :math:`[in\_features, out\_features]` , + input should be a multi-dimensional tensor of shape + :math:`[batch\_size, *, in\_features]` , where :math:`*` means any number of + additional dimensions. The linear operator multiplies input tensor with + weight and produces an output tensor of shape :math:`[batch\_size, *, out\_features]` , + If :math:`bias` is not None, the bias should be a 1-D tensor of shape + :math:`[out\_features]` and will be added to the output. + + Parameters: + x (Tensor): Input tensor. The data type should be float16, float32 or float64. + weight (Tensor): Weight tensor. The data type should be float16, float32 or float64. + bias (Tensor, optional): Bias tensor. The data type should be float16, float32 or float64. + If it is set to None, no bias will be added to the output units. + name (str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor, the shape is :math:`[batch\_size, *, out\_features]` and the + data type is the same with input :math:`x` . + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randn((3, 2), dtype="float32") + # x: [[-0.32342386 -1.200079 ] + # [ 0.7979031 -0.90978354] + # [ 0.40597573 1.8095392 ]] + weight = paddle.full(shape=[2, 4], fill_value="0.5", dtype="float32", name="weight") + # weight: [[0.5 0.5 0.5 0.5] + # [0.5 0.5 0.5 0.5]] + bias = paddle.ones(shape=[4], dtype="float32", name="bias") + # bias: [1. 1. 1. 1.] + y = paddle.nn.functional.linear(x, weight, bias) + # y: [[0.23824859 0.23824859 0.23824859 0.23824859] + # [0.9440598 0.9440598 0.9440598 0.9440598 ] + # [2.1077576 2.1077576 2.1077576 2.1077576 ]] + """ + if in_dygraph_mode(): + # TODO(jiabin): using addmm for fast forward route + return _C_ops.linear(x, weight, bias) + else: + if _in_legacy_dygraph(): + pre_bias = _legacy_C_ops.matmul_v2( + x, weight, 'trans_x', False, 'trans_y', False + ) + + if bias is None: + return pre_bias + + return _legacy_C_ops.elementwise_add(pre_bias, bias) + else: + helper = LayerHelper('linear', **locals()) + dtype = x.dtype + + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'linear' + ) + check_dtype( + dtype, 'dtype', ['float16', 'float32', 'float64'], 'linear' + ) + + inputs = {'X': [x], 'Y': [weight]} + attrs = {'trans_x': False, 'trans_y': False} + tmp = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='matmul_v2', + inputs=inputs, + outputs={'Out': tmp}, + attrs=attrs, + ) + if bias is not None: + res = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='elementwise_add', + inputs={'X': [tmp], 'Y': [bias]}, + outputs={'Out': [res]}, + attrs={'axis': len(x.shape) - 1}, + ) + else: + res = tmp + return res + + +def label_smooth(label, prior_dist=None, epsilon=0.1, name=None): + r""" + Label smoothing is a mechanism to regularize the classifier layer and is called + label-smoothing regularization (LSR).Label smoothing is proposed to encourage + the model to be less confident, since optimizing the log-likelihood of the + correct label directly may cause overfitting and reduce the ability of the + model to adapt. + + Label smoothing replaces the ground-truth label :math:`y` with the weighted sum + of itself and some fixed distribution :math:`\mu`. For class :math:`k`, + i.e. + + .. math:: + + \\tilde{y_k} = (1 - \epsilon) * y_k + \epsilon * \mu_k, + + where :math:`1 - \epsilon` and :math:`\epsilon` are the weights + respectively, and :math:`\\tilde{y}_k` is the smoothed label. Usually + uniform distribution is used for :math:`\mu`. + + See more details about label smoothing in https://arxiv.org/abs/1512.00567. + + Parameters: + label(Tensor): The input variable containing the label data. The + label data should use one-hot representation. It's + a multidimensional tensor with a shape of + :math:`[N_1, ..., Depth]`, where Depth is class number. The dtype can be "float32" and "float64". + prior_dist(Tensor, optional): The prior distribution to be used to smooth + labels. If not provided, an uniform distribution + is used. It's a multidimensional tensor with a shape of + :math:`[1, class\_num]` . The default value is None. + epsilon(float, optional): The weight used to mix up the original ground-truth + distribution and the fixed distribution. The default value is + 0.1. + name(str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name`. + + Returns: + Tensor: The tensor containing the smoothed labels. + + Examples: + .. code-block:: python + + import paddle + paddle.disable_static() + + x = paddle.to_tensor([[[0, 1, 0], + [ 1, 0, 1]]], dtype="float32", stop_gradient=False) + + output = paddle.nn.functional.label_smooth(x) + print(output) + # Tensor(shape=[1, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[0.03333334, 0.93333334, 0.03333334], + # [0.93333334, 0.03333334, 0.93333334]]]) + """ + if epsilon > 1.0 or epsilon < 0.0: + raise ValueError("The value of epsilon must be between 0 and 1.") + + if in_dygraph_mode(): + return _C_ops.label_smooth(label, prior_dist, float(epsilon)) + + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.label_smooth( + label, prior_dist, 'epsilon', float(epsilon) + ) + + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'label_smooth' + ) + + helper = LayerHelper("label_smooth", **locals()) + label.stop_gradient = True + smooth_label = helper.create_variable_for_type_inference(label.dtype) + helper.append_op( + type="label_smooth", + inputs={"X": label, "PriorDist": prior_dist} + if prior_dist + else {"X": label}, + outputs={"Out": smooth_label}, + attrs={"epsilon": float(epsilon)}, + ) + return smooth_label + + +def class_center_sample(label, num_classes, num_samples, group=None): + """ + Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers. + The process of sampling subset class centers is straightforward: + + 1. First select the positive class centers; + 2. Then randomly sample negative class centers. + + Specifically, given a label tensor, shape [batch_size], select all the positive class centers and randomly + sample negative class centers, then remap the input label tensor using the sampled class centers. + + For more information, Partial FC: Training 10 Million Identities on a Single Machine + arxiv: https://arxiv.org/abs/2010.05222 + + .. hint:: + If the number of the positive class centers is greater than the input num_samples, it keeps all the positive + class centers and the shape of sampled_class_center will be [num_positive_class_centers]. + + The API supports CPU, single GPU and multi GPU. + + For data parallel mode, set ``group=False``. + + For model parallel mode, set ``group=None`` or the group instance return by paddle.distributed.new_group. + + Args: + label (Tensor): 1-D tensor with shape [N], each label in [0, num_classes) + num_classes (int): A positive integer to specify the number of classes at local rank. + Note that num_classes of each GPU can be different. + num_samples (int): A positive integer to specify the number of class center to sample. + group (Group, optional): The group instance return by paddle.distributed.new_group + or ``None`` for global default group or ``False`` for data parallel (do not communication cross ranks). + Default is ``None``. + + Returns: + Tuple of two ``Tensor`` : (remapped_label, sampled_class_center), remapped label using sampled class center, + sampled class center from [0, num_classes). + + Examples: + + .. code-block:: python + :name: code-example1 + + # CPU or single GPU + import paddle + num_classes = 20 + batch_size = 10 + num_samples = 6 + label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64') + remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes, num_samples) + + print(label) + print(remapped_label) + print(sampled_class_index) + + # the output is + #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, + # [11, 5 , 1 , 3 , 12, 2 , 15, 19, 18, 19]) + #Tensor(shape=[10], dtype=int64, place=CPUPlace, stop_gradient=True, + # [4, 3, 0, 2, 5, 1, 6, 8, 7, 8]) + #Tensor(shape=[9], dtype=int64, place=CPUPlace, stop_gradient=True, + # [1 , 2 , 3 , 5 , 11, 12, 15, 18, 19]) + + .. code-block:: python + :name: code-example2 + + # required: distributed + # Multi GPU, test_class_center_sample.py + import paddle + import paddle.distributed as dist + strategy = dist.fleet.DistributedStrategy() + dist.fleet.init(is_collective=True, strategy=strategy) + batch_size = 10 + num_samples = 6 + rank_id = dist.get_rank() + # num_classes of each GPU can be different, e.g num_classes_list = [10, 8] + num_classes_list = [10, 10] + num_classes = paddle.sum(paddle.to_tensor(num_classes_list)) + label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64') + label_list = [] + dist.all_gather(label_list, label) + label = paddle.concat(label_list, axis=0) + remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes_list[rank_id], num_samples) + + print(label) + print(remapped_label) + print(sampled_class_index) + + #python -m paddle.distributed.launch --gpus=0,1 test_class_center_sample.py + # rank 0 output: + #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) + #Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) + #Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [0, 2, 4, 8, 9, 3]) + + # rank 1 output: + #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, + # [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ]) + #Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True, + # [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ]) + #Tensor(shape=[7], dtype=int64, place=CUDAPlace(1), stop_gradient=True, + # [0, 1, 2, 3, 5, 7, 8]) + """ + if not (group == False or group is None or hasattr(group, 'is_member')): + raise ValueError( + 'Expected group is False, None or instance of paddle.distributed.collective.Group \ + (got group: {})'.format( + group + ) + ) + return + + if hasattr(group, 'is_member') and not group.is_member(): + return + + ring_id = 0 + rank = 0 + nranks = 1 + if group != False: + if core.is_compiled_with_dist(): + parallel_env = paddle.distributed.ParallelEnv() + global_rank = parallel_env.rank + rank = ( + global_rank + if group is None + else group.get_group_rank(global_rank) + ) + nranks = parallel_env.world_size if group is None else group.nranks + + if num_samples > num_classes: + raise ValueError( + 'Expected num_samples less than or equal to {}, got num_samples {}'.format( + num_classes, num_samples + ) + ) + + label_size = 1 + for dim in list(label.shape): + label_size *= dim + if label_size != -1 and label_size < 1: + raise ValueError( + 'Expected label_size > 0 \ + (got label_size: {})'.format( + label_size + ) + ) + + label_dims = len(list(label.shape)) + if label_dims != 1: + raise ValueError( + 'Expected label_dims == 1 \ + (got label_dims: {})'.format( + label_dims + ) + ) + + seed = None + if (seed is None or seed == 0) and default_main_program().random_seed != 0: + seed = default_main_program().random_seed + + if in_dygraph_mode(): + return _C_ops.class_center_sample( + label, + num_classes, + num_samples, + ring_id, + rank, + nranks, + seed is not None, + seed if seed is not None else 0, + ) + elif paddle.in_dynamic_mode(): + ( + remapped_label, + sampled_class_center, + ) = _legacy_C_ops.class_center_sample( + label, + 'num_classes', + num_classes, + 'num_samples', + num_samples, + 'ring_id', + ring_id, + 'nranks', + nranks, + 'rank', + rank, + 'fix_seed', + seed is not None, + 'seed', + seed if seed is not None else 0, + ) + return remapped_label, sampled_class_center + + check_variable_and_dtype( + label, 'label', ['int64', 'int32'], 'class_center_sample' + ) + op_type = 'class_center_sample' + helper = LayerHelper(op_type, **locals()) + remapped_label = helper.create_variable_for_type_inference( + dtype=label.dtype + ) + sampled_class_center = helper.create_variable_for_type_inference( + dtype=label.dtype + ) + helper.append_op( + type=op_type, + inputs={'Label': label}, + outputs={ + 'RemappedLabel': remapped_label, + 'SampledLocalClassCenter': sampled_class_center, + }, + attrs={ + 'num_classes': num_classes, + 'num_samples': num_samples, + 'ring_id': ring_id, + 'nranks': nranks, + 'rank': rank, + 'fix_seed': seed is not None, + 'seed': seed if seed is not None else 0, + }, + ) + return remapped_label, sampled_class_center + + +def fold( + x, output_sizes, kernel_sizes, strides=1, paddings=0, dilations=1, name=None +): + r""" + + Combines an array of sliding local blocks into a large containing + tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each + combined value in the resulting large tensor by summing all values from all containing blocks. + + + For each input :math:`x` with shape [N, C_in , L], the output shape [N, C_out, H_out, W_out] + can be calculated as following. + + .. math:: + + H_{out} &= output\_size[0] \\ + W_{out} &= output\_size[1] \\ + C_{out} &= \frac{C_{in}}{kernel\_sizes[0]\times kernel\_sizes[1]} \\ + + Parameters: + x(Tensor): 3-D Tensor, input tensor of format [N, C, L], + data type can be float32 or float64 + output_sizes(int|list|tuple): The size of output size, should be [output_size_h, output_size_w] + or an interger o treated as [o, o]. + kernel_sizes(int|list|tuple): The size of convolution kernel, should be [k_h, k_w] + or an integer k treated as [k, k]. + strides(int|list|tuple, optional): The strides, should be [stride_h, stride_w] + or an integer stride treated as [sride, stride]. + For default, strides will be [1, 1]. + paddings(int|list|tuple, optional): The paddings of each dimension, should be + [padding_top, padding_left, padding_bottom, padding_right] + or [padding_h, padding_w] or an integer padding. + If [padding_h, padding_w] was given, it will expanded to + [padding_h, padding_w, padding_h, padding_w]. If an integer + padding was given, [padding, padding, padding, padding] will + be used. For default, paddings will be [0, 0, 0, 0] + dilations(int|list|tuple, optional): the dilations of convolution kernel, should be + [dilation_h, dilation_w], or an integer dilation treated as + [dilation, dilation]. For default, it will be [1, 1]. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + + Returns: + The tensor formed by combining a group of sliding local blocks + The output shape is [N, Cout, H, W] as decriabled above. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn([2,3*2*2,12]) + y = F.fold(x, output_sizes=[4, 5], kernel_sizes=2) + # y.shape = [2,3,4,5] + + """ + + helper = LayerHelper("fold", **locals()) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'fold') + + assert len(x.shape) == 3, "input should be the format of [N, C, L]" + + def _is_list_or_turple_(data): + return isinstance(data, list) or isinstance(data, tuple) + + if isinstance(output_sizes, int): + output_sizes = [output_sizes, output_sizes] + else: + assert _is_list_or_turple_(output_sizes) and ( + len(output_sizes) == 2 + ), "output_sizes should either be an integer or a list/tuple of two integers" + + if isinstance(kernel_sizes, int): + kernel_sizes = [kernel_sizes, kernel_sizes] + else: + assert _is_list_or_turple_(kernel_sizes) and ( + len(kernel_sizes) == 2 + ), "kernel_sizes should either be an integer or a list/tuple of two integers" + + if isinstance(strides, int): + strides = [strides, strides] + else: + assert _is_list_or_turple_(strides) and ( + len(strides) == 2 + ), "strides should either be an integer or a list/tuple of two integers" + + if isinstance(dilations, int): + dilations = [dilations, dilations] + else: + assert _is_list_or_turple_(dilations) and ( + len(dilations) == 2 + ), "dilations should either be an integer or a list/tuple of two integers" + + if isinstance(paddings, int): + paddings = [paddings] * 4 + elif isinstance(paddings, list): + if len(paddings) == 2: + paddings = paddings * 2 + elif len(paddings) == 4: + pass + else: + raise ValueError( + "paddings should either be an integer or a list of 2 or 4 integers" + ) + else: + raise ValueError( + "Unexpected type of paddings, it should be either an integer or a list" + "of 2 or 4 integers" + ) + + if in_dygraph_mode(): + out = _C_ops.fold( + x, output_sizes, kernel_sizes, strides, paddings, dilations + ) + elif in_dynamic_mode(): + out = _legacy_C_ops.fold( + x, + "output_sizes", + output_sizes, + "kernel_sizes", + kernel_sizes, + "strides", + strides, + "paddings", + paddings, + "dilations", + dilations, + ) + else: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="fold", + inputs={"X": x}, + outputs={"Y": out}, + attrs={ + "output_sizes": output_sizes, + "kernel_sizes": kernel_sizes, + "strides": strides, + "paddings": paddings, + "dilations": dilations, + }, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/conv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..d62ddc6a1ed5882b095ebd8d6988b4c6e9a4df52 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/conv.py @@ -0,0 +1,1884 @@ +# 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. +from __future__ import print_function + +import numpy as np +from ...device import get_cudnn_version +from ...static import Variable +from ...fluid import dygraph_utils +from ...fluid.layers.utils import ( + convert_to_list, + _is_symmetric_padding, + _contain_var, + _convert_to_tensor_list, +) +from ...fluid.data_feeder import check_variable_and_dtype, check_dtype +from ...framework import ParamAttr +from ...fluid.layer_helper import LayerHelper +from ...tensor.manipulation import unsqueeze, squeeze +from ...tensor.math import add +from ...fluid.layers import nn +from paddle import _C_ops, _legacy_C_ops +from paddle import get_flags +from paddle import in_dynamic_mode +from paddle.device import is_compiled_with_cuda +from paddle.device import is_compiled_with_npu +from paddle import in_dynamic_mode +from paddle import get_flags +from paddle.device import is_compiled_with_rocm +from paddle.fluid.framework import _global_flags +from paddle.fluid.framework import _in_legacy_dygraph +from paddle.fluid.framework import in_dygraph_mode +from paddle.fluid.framework import _non_static_mode + +__all__ = [] + + +def _is_list_or_tuple(input): + return isinstance(input, (list, tuple)) + + +def _zero_padding_in_batch_and_channel(padding, channel_last): + if channel_last: + return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0] + else: + return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0] + + +def _exclude_padding_in_batch_and_channel(padding, channel_last): + padding_ = padding[1:-1] if channel_last else padding[2:] + padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim] + return padding_ + + +def _update_padding_nd(padding, channel_last, num_dims): + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.".format( + padding + ) + ) + if padding == "VALID": + padding_algorithm = "VALID" + padding = [0] * num_dims + else: + padding_algorithm = "SAME" + padding = [0] * num_dims + elif _is_list_or_tuple(padding): + # for padding like + # [(pad_before, pad_after), (pad_before, pad_after), ...] + # padding for batch_dim and channel_dim included + if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]): + if not _zero_padding_in_batch_and_channel(padding, channel_last): + raise ValueError( + "Non-zero padding({}) in the batch or channel dimensions " + "is not supported.".format(padding) + ) + padding_algorithm = "EXPLICIT" + padding = _exclude_padding_in_batch_and_channel( + padding, channel_last + ) + if _is_symmetric_padding(padding, num_dims): + padding = padding[0::2] + # for padding like [pad_before, pad_after, pad_before, pad_after, ...] + elif len(padding) == 2 * num_dims and isinstance(padding[0], int): + padding_algorithm = "EXPLICIT" + padding = convert_to_list(padding, 2 * num_dims, 'padding') + if _is_symmetric_padding(padding, num_dims): + padding = padding[0::2] + # for padding like [pad_d1, pad_d2, ...] + elif len(padding) == num_dims and isinstance(padding[0], int): + padding_algorithm = "EXPLICIT" + padding = convert_to_list(padding, num_dims, 'padding') + else: + raise ValueError("In valid padding: {}".format(padding)) + # for integer padding + else: + padding_algorithm = "EXPLICIT" + padding = convert_to_list(padding, num_dims, 'padding') + if not all([p >= 0 for p in padding]): + raise ValueError( + "Invalid padding, all value should be larger than or equal to 0, but received: {}".format( + padding + ) + ) + return padding, padding_algorithm + + +def _conv_nd( + x, + weight, + bias=None, + stride=1, + padding=0, + padding_algorithm=None, + dilation=1, + groups=1, + data_format="NCHW", + channel_dim=1, + op_type="conv2d", + use_cudnn=True, + use_mkldnn=False, + name=None, +): + + # Due to the poor performance of NHWC, we transpose the input to NCHW. + if in_dygraph_mode() and op_type == "conv2d": + pre_bias = _C_ops.conv2d( + x, + weight, + stride, + padding, + padding_algorithm, + groups, + dilation, + data_format, + False, + -1, + False, + ) + if bias is not None: + channel_dim = ( + channel_dim + len(x.shape) if channel_dim < 0 else channel_dim + ) + if isinstance(x, tuple): + x = x[0] + if isinstance(bias, tuple): + bias = bias[0] + if len(bias.shape) < len(x.shape): + tmp_bias = _C_ops.reshape( + bias, + [1 for i in range(channel_dim)] + + bias.shape + + [1 for i in range(len(x.shape) - channel_dim - 1)], + ) + return _C_ops.add(pre_bias, tmp_bias) + else: + return _C_ops.add(pre_bias, bias) + else: + return pre_bias + + if in_dygraph_mode() and op_type == "depthwise_conv2d": + pre_bias = _C_ops.depthwise_conv2d( + x, + weight, + stride, + padding, + padding_algorithm, + groups, + dilation, + data_format, + False, + -1, + False, + False, + use_cudnn, + ) + if bias is not None: + channel_dim = ( + channel_dim + len(x.shape) if channel_dim < 0 else channel_dim + ) + tmp_bias = _C_ops.reshape( + bias, + [1 for i in range(channel_dim)] + + bias.shape + + [1 for i in range(len(x.shape) - channel_dim - 1)], + ) + return _C_ops.add(pre_bias, tmp_bias) + else: + return pre_bias + + if in_dygraph_mode() and op_type == "conv3d": + pre_bias = _C_ops.conv3d( + x, + weight, + stride, + padding, + padding_algorithm, + groups, + dilation, + data_format, + False, + -1, + False, + ) + if bias is not None: + channel_dim = ( + channel_dim + len(x.shape) if channel_dim < 0 else channel_dim + ) + tmp_bias = _C_ops.reshape( + bias, + bias.shape + [1 for i in range(len(x.shape) - channel_dim - 1)], + ) + return _C_ops.add(pre_bias, tmp_bias) + else: + return pre_bias + + if in_dynamic_mode(): + attrs = ( + 'strides', + stride, + 'paddings', + padding, + 'dilations', + dilation, + 'groups', + groups, + 'use_cudnn', + use_cudnn, + 'use_mkldnn', + use_mkldnn, + 'fuse_relu_before_depthwise_conv', + False, + "padding_algorithm", + padding_algorithm, + "data_format", + data_format, + ) + pre_bias = getattr(_legacy_C_ops, op_type)(x, weight, *attrs) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + out = pre_bias + else: + inputs = {'Input': [x], 'Filter': [weight]} + attrs = { + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'use_mkldnn': use_mkldnn, + 'fuse_relu_before_depthwise_conv': False, + "padding_algorithm": padding_algorithm, + "data_format": data_format, + } + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], op_type + ) + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pre_bias = helper.create_variable_for_type_inference(dtype) + outputs = {"Output": [pre_bias]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + if bias is not None: + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='elementwise_add', + inputs={'X': [pre_bias], 'Y': [bias]}, + outputs={'Out': [out]}, + attrs={'axis': channel_dim, 'use_mkldnn': use_mkldnn}, + ) + else: + out = pre_bias + return out + + +def conv1d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + data_format='NCL', + name=None, +): + r""" + The convolution1D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input and + Output are in NCL format, where N is batch size, C is the number of + channels, L is the length of the feature. + Filter is in MCK format, where M is the number of output image channels, + C is the number of input image channels, K is the size of the kernel. + If the groups is greater than 1, C will equal the number of input image + channels divided by the groups. If bias attribution and activation type + are provided, bias is added to the output of the convolution, and the + corresponding activation function is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a tensor with NCL format. + * :math:`W`: Kernel value, a tensor with MCK format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, L_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, L_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, L_{out})` + + Where + + .. math:: + + L_{out} = \frac{(L_{in} + 2 * padding - (dilation * (L_f - 1) + 1))}{stride} + 1 + + Args: + x (Tensor): The input is 3-D Tensor with shape [N, C, L], the data type + of input is float16 or float32 or float64. + weight (Tensor): The convolution kernel with shape [M, C/g, K], where M is + the number of output channels, g is the number of groups, K is the kernel's size. + bias (Tensor, optional): The bias with shape [M,]. Default: None. + stride (int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain one integers, (stride_size). Default: 1. + padding(int|str|tuple|list, optional): The padding size. Padding could be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means the feature map is zero paded by size of `padding` on both sides. + 3. a list[int] or tuple[int] whose length is 1, which means the feature map is zero paded by size of `padding[0]` on both sides. + 4. a list[int] or tuple[int] whose length is 2. It has the form [pad_before, pad_after]. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + dilation (int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain one integer, (dilation_size). Default: 1. + groups (int, optional): The groups number of the conv1d function. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: 1. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCL"`, `"NLC"`. + The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of: + `[batch_size, input_channels, feature_length]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A tensor representing the conv1d, whose data type is the + same with input. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([[[4, 8, 1, 9], + [7, 2, 0, 9], + [6, 9, 2, 6]]], dtype="float32") + w = paddle.to_tensor([[[9, 3, 4], + [0, 0, 7], + [2, 5, 6]], + [[0, 3, 4], + [2, 9, 7], + [5, 6, 8]]], dtype="float32") + + y = F.conv1d(x, w) + print(y) + # Tensor(shape=[1, 2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[133., 238.], + # [160., 211.]]]) + """ + cudnn_version = get_cudnn_version() + if cudnn_version is not None: + use_cudnn = True + else: + use_cudnn = False + + if data_format not in ["NCL", "NLC"]: + raise ValueError( + "Attr(data_format) should be 'NCL' or 'NLC'. " + "Received Attr(data_format): {}.".format(data_format) + ) + + channel_last = data_format == "NLC" + channel_dim = -1 if channel_last else 1 + conv2d_data_format = "NHWC" if channel_last else "NCHW" + if len(x.shape) != 3: + raise ValueError( + "Input x should be 3D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + num_filters = weight.shape[0] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) " + "should be defined. Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv1d should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "the channel of input must be divisible by groups," + "received: the channel of input is {}, the shape of input is {}" + ", the groups is {}".format(num_channels, x.shape, groups) + ) + if num_filters % groups != 0: + raise ValueError( + "the number of filters must be divisible by groups," + "received: the number of filters is {}, the shape of weight is {}" + ", the groups is {}".format(num_filters, weight.shape, groups) + ) + + # update attrs + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 1) + + if len(padding) == 2: + padding = [0] * 2 + padding + elif len(padding) == 1: + padding = [0] + padding + else: + raise ValueError( + "The size of padding's dimension should be 1 or 2. But got padding={}".format( + padding + ) + ) + stride = [1] + convert_to_list(stride, 1, 'stride') + dilation = [1] + convert_to_list(dilation, 1, 'dilation') + weight = unsqueeze(weight, axis=[-2]) + + l_type = "conv2d" + + # When "groups==num_channels and num_filters% num_channels == 0" using depthwise_conv2d has better performance + if ( + is_compiled_with_cuda() + and num_channels == groups + and num_channels != 1 + and num_filters % num_channels == 0 + ): + l_type = 'depthwise_conv2d' + use_cudnn = False + + # NPU only supports depthwise_conv2d when "input_channel = output_channel = groups" + if is_compiled_with_npu(): + if num_channels == groups and num_channels == num_filters: + l_type = 'depthwise_conv2d' + else: + l_type = 'conv2d' + + squeeze_aixs = -3 if channel_last else -2 + x = unsqueeze(x, axis=[squeeze_aixs]) + + if in_dygraph_mode(): + out = getattr(_C_ops, l_type)( + x, + weight, + stride, + padding, + padding_algorithm, + groups, + dilation, + conv2d_data_format, + False, + -1, + False, + False, + use_cudnn, + ) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + elif _in_legacy_dygraph(): + attrs = ( + 'strides', + stride, + 'paddings', + padding, + 'dilations', + dilation, + 'groups', + groups, + 'use_cudnn', + use_cudnn, + 'use_mkldnn', + False, + 'fuse_relu_before_depthwise_conv', + False, + "padding_algorithm", + padding_algorithm, + "data_format", + conv2d_data_format, + ) + out = getattr(_legacy_C_ops, l_type)(x, weight, *attrs) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + else: + inputs = {'Input': [x], 'Filter': [weight]} + attrs = { + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'use_mkldnn': False, + 'fuse_relu_before_depthwise_conv': False, + "padding_algorithm": padding_algorithm, + "data_format": conv2d_data_format, + } + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], 'conv2d' + ) + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + outputs = {"Output": [out]} + helper.append_op( + type=l_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + out = squeeze(out, axis=[squeeze_aixs]) + return out + + +def conv2d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + data_format="NCHW", + name=None, +): + r""" + + The convolution2D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input and + Output are in NCHW or NHWC format, where N is batch size, C is the number of + channels, H is the height of the feature, and W is the width of the feature. + Filter is in MCHW format, where M is the number of output image channels, + C is the number of input image channels, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input image channels divided by the groups. + Please refer to UFLDL's `convolution + `_ + for more details. + If bias attribution and activation type are provided, bias is added to the + output of the convolution, and the corresponding activation function is + applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a tensor with NCHW or NHWC format. + * :math:`W`: Filter value, a tensor with MCHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Args: + x (Tensor): The input is 4-D Tensor with shape [N, C, H, W], the data type + of input is float16 or float32 or float64. + weight (Tensor): The convolution kernel with shape [M, C/g, kH, kW], where M is + the number of output channels, g is the number of groups, kH is the filter's + height, kW is the filter's width. + bias (Tensor, optional): The bias with shape [M,]. + stride (int|list|tuple): The stride size. It means the stride in convolution. + If stride is a list/tuple, it must contain two integers, (stride_height, stride_width). + Otherwise, stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple): The padding size. It means the number of zero-paddings + on both sides for each dimension.If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_height, pad_width]` or + `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, and when + `data_format` is `"NCHW"`, `padding` can be in the form `[[0,0], [0,0], + [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `padding` can be in the form + `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|list|tuple): The dilation size. It means the spacing between the kernel + points. If dilation is a list/tuple, it must contain two integers, (dilation_height, + dilation_width). Otherwise, dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int): The groups number of the Conv2D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A Tensor representing the conv2d result, whose data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x_var = paddle.randn((2, 3, 8, 8), dtype='float32') + w_var = paddle.randn((6, 3, 3, 3), dtype='float32') + + y_var = F.conv2d(x_var, w_var) + y_np = y_var.numpy() + + print(y_np.shape) + # (2, 6, 6, 6) + """ + # entry checks + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. " + "Received Attr(data_format): {}.".format(data_format) + ) + + channel_last = data_format == "NHWC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 4: + raise ValueError( + "Input x should be 4D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + num_filters = weight.shape[0] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) " + "should be defined. Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv2d should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "the channel of input must be divisible by groups," + "received: the channel of input is {}, the shape of input is {}" + ", the groups is {}".format(num_channels, x.shape, groups) + ) + if num_filters % groups != 0: + raise ValueError( + "the number of filters must be divisible by groups," + "received: the number of filters is {}, the shape of weight is {}" + ", the groups is {}".format(num_filters, weight.shape, groups) + ) + + cudnn_version = get_cudnn_version() + + use_cudnn = ( + True + if (is_compiled_with_cuda() and cudnn_version is not None) + else False + ) + + # update attrs + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 2) + stride = convert_to_list(stride, 2, 'stride') + dilation = convert_to_list(dilation, 2, 'dilation') + + l_type = "conv2d" + if ( + num_channels == groups + and num_channels != 1 + and num_filters % num_channels == 0 + ): + l_type = 'depthwise_conv2d' + if is_compiled_with_rocm(): + use_cudnn = True + else: + use_cudnn = False + else: + if in_dygraph_mode(): + pre_bias = _C_ops.conv2d( + x, + weight, + stride, + padding, + padding_algorithm, + groups, + dilation, + data_format, + False, + -1, + False, + ) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + return out + else: + return pre_bias + + use_mkldnn = _global_flags()["FLAGS_use_mkldnn"] + + # NPU only supports depthwise_conv2d when "input_channel = output_channel = groups" + if is_compiled_with_npu(): + if num_channels == groups and num_channels == num_filters: + l_type = 'depthwise_conv2d' + else: + l_type = 'conv2d' + + if ( + is_compiled_with_cuda() + and get_flags("FLAGS_conv2d_disable_cudnn")[ + "FLAGS_conv2d_disable_cudnn" + ] + ): + use_cudnn = False + + return _conv_nd( + x, + weight, + bias, + stride, + padding, + padding_algorithm, + dilation, + groups, + data_format, + channel_dim, + l_type, + use_cudnn, + use_mkldnn, + name, + ) + + +def conv1d_transpose( + x, + weight, + bias=None, + stride=1, + padding=0, + output_padding=0, + groups=1, + dilation=1, + output_size=None, + data_format="NCL", + name=None, +): + r""" + The 1-D convolution transpose layer calculates the output based on the input, + filter, and dilation, stride, padding. Input(Input) and output(Output) + are in 'NCL' format or 'NLC' where N is batch size, C is the number of channels, + L is the length of the feature. The details of convolution transpose + layer, please refer to the following explanation and references + `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a 3-D Tensor with 'NCL' format or 'NLC' format. + * :math:`W`: Filter value, a 3-D Tensor with 'MCK' format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, a 3-D Tensor with data format 'NCL' or 'NLC', the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, L_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, L_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, L_{out})` + + Where + + .. math:: + + L^\prime_{out} &= (L_{in} - 1) * stride - pad_top - pad_bottom + dilation * (L_f - 1) + 1 + output_padding \\\\ + L_{out} &\in [ L^\prime_{out}, L^\prime_{out} + stride ] + + Note: + The conv1d_transpose can be seen as the backward of the conv1d. For conv1d, + when stride > 1, conv1d maps multiple input shape to the same output shape, + so for conv1d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`L_{out} = L^\prime_{out}`; + else, the :math:`L_{out}` of the output size must between :math:`L^\prime_{out}` + and :math:`L^\prime_{out} + stride`. + + Args: + x(Tensor): 3-D tensor with [N, C, L] or [N, L, C] format, + its data type is float32 or float64. + weight(Tensor): The convolution kernel, a Tensor with shape [C, M/g, K], + where M is the number of output channels(filters), g is the number of groups, + K is the size of the kernel. + bias(Tensor, optional): The bias, a Tensor with shape [M, ]. + stride(int|tuple|list, optional): The stride size. It means the stride in transposed convolution. + If stride is a list/tuple, it must contain one integer, `(stride_size)`. + Default: stride = 1. + padding(int|list|str|tuple, optional): The padding size. The padding argument effectively adds + `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a + string, either 'VALID' or 'SAME' supported, which is the padding algorithm. + If `padding` is a tuple or list, it could be in two forms: + `[pad]` or `[pad_left, pad_right]`. Default: padding = 0. + output_padding(int|list|tuple, optional): The count of zeros to be added to tail of each dimension. + If it is a list/tuple, it must contain one integer. Default: 0. + groups(int, optional): The groups number of the conv1d transpose function. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups = 1. + dilation(int|tuple|list, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain one integer, `(dilation_size)`. + Default: dilation = 1. + output_size(int|tuple|list, optional): The output image size. If output size is a + tuple/list, it must contain one integer, `(feature_length)`. None if use + filter_size(shape of weight), padding, and stride to calculate output_size. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCL"`, `"NLC"`. + The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of: + `[batch_size, input_channels, input_length]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A tensor representing the result of 1-D transpose convolution, whose + data type is the same with input. And its shape is (num_batches, channels, length) + when data_format is `"NCL"` and (num_batches, length, channels) when data_format is + `"NLC"`. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # shape: (1, 2, 4) + x = paddle.to_tensor([[[4, 0, 9, 7], + [8, 0, 9, 2,]]], dtype="float32") + # shape: (2, 1, 2) + w = paddle.to_tensor([[[7, 0]], + [[4, 2]]], dtype="float32") + + y = F.conv1d_transpose(x, w) + print(y) + # Tensor(shape=[1, 1, 5], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[60., 16., 99., 75., 4. ]]]) + """ + cudnn_version = get_cudnn_version() + if cudnn_version is not None: + use_cudnn = True + else: + use_cudnn = False + + if data_format not in ['NCL', 'NLC']: + raise ValueError( + "Attr(data_format) of conv2d_transpose got wrong value: " + "received {}, but only 'NCL' or 'NLC' are supported.".format( + data_format + ) + ) + channel_last = data_format == "NLC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 3: + raise ValueError( + "Input x should be 3D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + + num_channels = x.shape[channel_dim] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) " + "should be defined. Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv1d_transpose should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "the channel of input must be divisible by groups," + "received: the channel of input is {}, the shape of input is {}" + ", the groups is {}".format(num_channels, x.shape, groups) + ) + + # update attrs + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 1) + + if len(padding) == 2: + padding = padding + [0] * 2 + elif len(padding) == 1: + padding = padding + [0] + else: + raise ValueError( + "The size of padding's dimension should 1 or 2. But got padding={}".format( + padding + ) + ) + + stride = convert_to_list(stride, 1, 'stride') + [1] + dilation = convert_to_list(dilation, 1, 'dilation') + [1] + + if output_size is None: + output_size = [] + else: + if output_padding != 0: + raise ValueError( + 'output_padding option is mutually exclusive with ' + 'output_size' + ) + if isinstance(output_size, (list, tuple, int)): + output_size = convert_to_list(output_size, 1, 'output_size') + [1] + else: + raise ValueError( + "output_size should be int, or list, tuple of ints" + ) + + if output_padding == 0: + output_padding = [] + else: + output_padding = convert_to_list( + output_padding, 1, 'output_padding' + ) + [0] + + if len(output_padding) > 0 and output_padding[0] > stride[0]: + raise ValueError( + "The size of output_padding should not be greater than stride." + "But got output_padding={} and stride={}".format( + output_padding[0], stride[0] + ) + ) + + op_type = 'conv2d_transpose' + num_filters = weight.shape[1] + if ( + num_channels == groups + and num_channels != 1 + and num_filters == 1 + and not use_cudnn + ): + op_type = 'depthwise_conv2d_transpose' + use_cudnn = False + + squeeze_axis = -2 if channel_last else -1 + conv2d_data_format = "NHWC" if channel_last else "NCHW" + + x = unsqueeze(x, axis=[squeeze_axis]) + weight = unsqueeze(weight, axis=[-1]) + + if in_dygraph_mode(): + out = getattr(_C_ops, op_type)( + x, + weight, + stride, + padding, + output_padding, + output_size, + padding_algorithm, + groups, + dilation, + conv2d_data_format, + ) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + elif _in_legacy_dygraph(): + attrs = ( + 'output_padding', + output_padding, + 'output_size', + output_size, + 'strides', + stride, + 'paddings', + padding, + 'padding_algorithm', + padding_algorithm, + 'dilations', + dilation, + 'groups', + groups, + 'use_cudnn', + use_cudnn, + 'data_format', + conv2d_data_format, + ) + out = getattr(_legacy_C_ops, op_type)(x, weight, *attrs) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + else: + inputs = {'Input': [x], 'Filter': [weight]} + attrs = { + 'output_padding': output_padding, + 'output_size': output_size, + 'strides': stride, + 'paddings': padding, + 'padding_algorithm': padding_algorithm, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'data_format': conv2d_data_format, + } + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], 'conv2d_transpose' + ) + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + outputs = {"Output": [out]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + if bias is not None: + out = nn.elementwise_add(out, bias, axis=channel_dim) + + out = squeeze(out, axis=[squeeze_axis]) + return out + + +def conv2d_transpose( + x, + weight, + bias=None, + stride=1, + padding=0, + output_padding=0, + dilation=1, + groups=1, + output_size=None, + data_format='NCHW', + name=None, +): + r""" + + The convolution2D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCHW or NHWC format. Where N is batch size, C is the number of channels, + H is the height of the feature, and W is the width of the feature. + Parameters(dilations, strides, paddings) are two elements. These two elements + represent height and width, respectively. The details of convolution transpose + layer, please refer to the following explanation and references + `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + See more detail in :ref:`api_nn_conv_ConvTranspose2d` . + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a 4-D Tensor with NCHW or NHWC format. + * :math:`W`: Filter value, a 4-D Tensor with MCHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, a 4-D Tensor with data format 'NCHW' or 'NHWC', the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H^\prime_{out} &= (H_{in} - 1) * strides[0] - pad_height_top - pad_height_bottom + dilations[0] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[1] - pad_width_left - pad_width_right + dilations[1] * (W_f - 1) + 1 \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ] \\\\ + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ] + + Note: + The conv2d_transpose can be seen as the backward of the conv2d. For conv2d, + when stride > 1, conv2d maps multiple input shape to the same output shape, + so for conv2d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, W_{out} = W^\prime_{out}`; + else, the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[0]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[1]`. + + Args: + x(Tensor): 4-D Tensor with [N, C, H, W] or [N, H, W, C] format, + whose data type is float32 or float64. + weight(Tensor): The convolution kernel, a Tensor with shape [C, M/g, kH, kW], + where M is the number of output channels(filters), g is the number of groups, + kH is the height of the kernel, and kW is the width of the kernel. + bias(Tensor, optional): The bias, a Tensor with shape [M, ]. + stride(int|list|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a list/tuple, it must contain two integers, (stride_height, stride_width). + Otherwise, stride_height = stride_width = stride. Default: stride = 1. + padding(str|int|list|tuple, optional): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_height, pad_width]` or + `[pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `padding` can be in the form + `[[0,0], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + output_padding(int|list|tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0. + groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups = 1. + dilation(int|list|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain two integers, (dilation_height, dilation_width). + Otherwise, dilation_height = dilation_width = dilation. Default: dilation = 1. + output_size(int|tuple|list, optional): The output image size. If output size is a + tuple/list, it must contain two integers, (image_height, image_width). None if use + filter_size(shape of weight), padding, and stride to calculate output_size. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A Tensor representing the conv2d_transpose, whose + data type is the same with input and shape is (num_batches, channels, out_h, + out_w) or (num_batches, out_h, out_w, channels). The tensor variable storing + transposed convolution result. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x_var = paddle.randn((2, 3, 8, 8), dtype='float32') + w_var = paddle.randn((3, 6, 3, 3), dtype='float32') + + y_var = F.conv2d_transpose(x_var, w_var) + y_np = y_var.numpy() + + print(y_np.shape) + # (2, 6, 10, 10) + """ + + if data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Attr(data_format) of conv2d_transpose got wrong value: " + "received {}, but only 'NCHW' or 'NHWC' are supported.".format( + data_format + ) + ) + channel_last = data_format == "NHWC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 4: + raise ValueError( + "Input x should be 4D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) " + "should be defined. Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv2d_transpose should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "the channel of input must be divisible by groups," + "received: the channel of input is {}, the shape of input is {}" + ", the groups is {}".format(num_channels, x.shape, groups) + ) + + cudnn_version = get_cudnn_version() + + use_cudnn = ( + True + if (is_compiled_with_cuda() and cudnn_version is not None) + else False + ) + + # update attrs + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 2) + stride = convert_to_list(stride, 2, 'stride') + dilation = convert_to_list(dilation, 2, 'dilation') + + if output_size is None: + output_size = [] + else: + if output_padding != 0: + raise ValueError( + 'output_padding option is mutually exclusive with ' + 'output_size' + ) + if isinstance(output_size, (list, tuple)): + if _contain_var(output_size): + output_size = _convert_to_tensor_list(output_size) + else: + output_size = convert_to_list(output_size, 2, 'output_size') + elif isinstance(output_size, int): + output_size = convert_to_list(output_size, 2, 'output_size') + elif isinstance(output_size, Variable): + check_dtype( + output_size.dtype, + 'output_size', + ['int32', 'int64'], + 'conv2d_transpose', + ) + if len(output_size.shape) == 1 and ( + output_size.shape[0] == 1 or output_size.shape[0] == 2 + ): + if output_size.shape[0] == 1: + output_size = [output_size, output_size] + else: + raise ValueError( + "output_size must contain one or two integers." + ) + else: + raise ValueError( + "output_size should be int or Tensor or list, tuple of ints or Tensor" + ) + + if output_padding == 0: + output_padding = [] + else: + output_padding = convert_to_list(output_padding, 2, 'output_padding') + + op_type = 'conv2d_transpose' + num_filters = weight.shape[1] + if num_channels == groups and num_channels != 1 and num_filters == 1: + op_type = 'depthwise_conv2d_transpose' + use_cudnn = False + + if in_dygraph_mode(): + op = ( + _C_ops.conv2d_transpose + if op_type == 'conv2d_transpose' + else _C_ops.depthwise_conv2d_transpose + ) + pre_bias = op( + x, + weight, + stride, + padding, + output_padding, + output_size, + padding_algorithm, + groups, + dilation, + data_format, + ) + if bias is not None: + return nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + return pre_bias + + if _in_legacy_dygraph(): + attrs = ( + 'output_padding', + output_padding, + 'output_size', + output_size, + 'strides', + stride, + 'paddings', + padding, + 'padding_algorithm', + padding_algorithm, + 'dilations', + dilation, + 'groups', + groups, + 'use_cudnn', + use_cudnn, + 'data_format', + data_format, + ) + pre_bias = getattr(_legacy_C_ops, op_type)(x, weight, *attrs) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + out = pre_bias + else: + inputs = {'Input': [x], 'Filter': [weight]} + attrs = { + 'output_padding': output_padding, + 'output_size': output_size, + 'strides': stride, + 'paddings': padding, + 'padding_algorithm': padding_algorithm, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + 'data_format': data_format, + } + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'conv2d_transpose' + ) + helper = LayerHelper(op_type, **locals()) + pre_bias = helper.create_variable_for_type_inference(x.dtype) + outputs = {"Output": [pre_bias]} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + out = pre_bias + + return out + + +def conv3d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + data_format="NCDHW", + name=None, +): + r""" + + The convolution3D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are in NCDHW or NDHWC format. Where N is batch size C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. Convlution3D is similar with Convlution2D + but adds one dimension(depth). If bias attribution and activation type are + provided, bias is added to the output of the convolution, and the + corresponding activation function is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, D_f, H_f, W_f)` + + - Output: + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D_{out}&= \\frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (D_f - 1) + 1))}{strides[0]} + 1 \\\\ + H_{out}&= \\frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (H_f - 1) + 1))}{strides[1]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (W_f - 1) + 1))}{strides[2]} + 1 + + Args: + x (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W], the data + type of input is float16 or float32 or float64. + weight (Tensor): The convolution kernel, a Tensor with shape [M, C/g, kD, kH, kW], + where M is the number of filters(output channels), g is the number of groups, + kD, kH, kW are the filter's depth, height and width respectively. + bias (Tensor, optional): The bias, a Tensor of shape [M, ]. + stride (int|list|tuple, optional): The stride size. It means the stride in convolution. If stride is a + list/tuple, it must contain three integers, (stride_depth, stride_height, stride_width). + Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple, optional): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NDHWC"`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|list|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1 + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str|None, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A Tensor representing the conv3d, whose data type is + the same with input. If act is None, the tensor storing the + convolution result, and if act is not None, the tensor storing + convolution and non-linearity activation result. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x_var = paddle.randn((2, 3, 8, 8, 8), dtype='float32') + w_var = paddle.randn((6, 3, 3, 3, 3), dtype='float32') + + y_var = F.conv3d(x_var, w_var) + y_np = y_var.numpy() + + print(y_np.shape) + # (2, 6, 6, 6, 6) + """ + # entry check + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): {}.".format(data_format) + ) + + channel_last = data_format == "NDHWC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 5: + raise ValueError( + "Input x should be 5D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + num_filters = weight.shape[0] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) should be defined. " + "Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv3d should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "The number of input channels must be divisible by Attr(groups). " + "Received: number of channels({}), groups({}).".format( + num_channels, groups + ) + ) + if num_filters % groups != 0: + raise ValueError( + "The number of filters must be divisible by Attr(groups). " + "Received: number of filters({}), groups({}).".format( + num_filters, groups + ) + ) + + cudnn_version = get_cudnn_version() + use_cudnn = ( + True + if (is_compiled_with_cuda() and cudnn_version is not None) + else False + ) + + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 3) + stride = convert_to_list(stride, 3, 'stride') + dilation = convert_to_list(dilation, 3, 'dilation') + op_type = "conv3d" + + return _conv_nd( + x, + weight, + bias, + stride, + padding, + padding_algorithm, + dilation, + groups, + data_format, + channel_dim, + op_type, + use_cudnn, + False, + name, + ) + + +def conv3d_transpose( + x, + weight, + bias=None, + stride=1, + padding=0, + output_padding=0, + groups=1, + dilation=1, + output_size=None, + data_format='NCDHW', + name=None, +): + r""" + The convolution3d transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCDHW or NDHWC format. Where N is batch size, C is the number of channels, + D is the depth of the feature, H is the height of the feature, and W + is the width of the feature. Parameters(dilations, strides, paddings) are + two elements. These two elements represent height and width, respectively. + The details of convolution transpose layer, please refer to the following + explanation and references `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + See more detail in :ref:`api_nn_conv_ConvTranspose3d` . + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a Tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a Tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, D_f, H_f, W_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (D_f - 1) + 1 \\\\ + H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (H_f - 1) + 1 \\\\ + W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (W_f - 1) + 1 \\\\ + D_{out} &\in [ D^\prime_{out}, D^\prime_{out} + strides[0] ] \\\\ + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[1] ] \\\\ + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[2] ] + + Note: + The conv3d_transpose can be seen as the backward of the conv3d. For conv3d, + when stride > 1, conv3d maps multiple input shape to the same output shape, + so for conv3d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \ + H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output + size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`, + the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`. + + Args: + x(Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C], the data type + of input is float32 or float64. + weight (Tensor): The convolution kernel, a Tensor with shape [C, M/g, kD, kH, kW], + where M is the number of filters(output channels), g is the number of groups, + kD, kH, kW are the filter's depth, height and width respectively. + bias (Tensor, optional): The bias, a Tensor of shape [M, ]. + stride(int|list|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a list/tuple, it must contain three integers, (stride_depth, stride_height, + stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. + Default: stride = 1. + padding (string|int|list|tuple, optional): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NDHWC"`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + output_padding(int|list|tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0. + groups(int, optional): The groups number of the Conv3D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups=1 + dilation(int|list|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + output_size(int|list|tuple, optional): The output image size. If output size is a + list/tuple, it must contain three integers, (image_depth, image_height, image_width). + None if use filter_size(shape of weight), padding, and stride to calculate output_size. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A Tensor representing the conv3d_transpose, whose data + type is the same with input and shape is (num_batches, channels, out_d, out_h, + out_w) or (num_batches, out_d, out_h, out_w, channels). If act is None, the tensor + variable storing the transposed convolution result, and if act is not None, the tensor + variable storing transposed convolution and non-linearity activation result. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x_var = paddle.randn((2, 3, 8, 8, 8), dtype='float32') + w_var = paddle.randn((3, 6, 3, 3, 3), dtype='float32') + + y_var = F.conv3d_transpose(x_var, w_var) + y_np = y_var.numpy() + + print(y_np.shape) + # (2, 6, 10, 10, 10) + """ + # entry checks + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): {}.".format(data_format) + ) + + channel_last = data_format == "NDHWC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 5: + raise ValueError( + "Input x should be 5D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + num_filters = weight.shape[1] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) should be defined. " + "Received: {}.".format(x.shape, num_channels) + ) + if groups <= 0: + raise ValueError( + "The groups of conv3d_transpose should be greater than 0. Received groups: {}".format( + groups + ) + ) + if num_channels % groups != 0: + raise ValueError( + "The number of input channels must be divisible by Attr(groups). " + "Received: number of channels({}), groups({}).".format( + num_channels, groups + ) + ) + + padding, padding_algorithm = _update_padding_nd(padding, channel_last, 3) + stride = convert_to_list(stride, 3, 'stride') + dilation = convert_to_list(dilation, 3, 'dilation') + if output_size is None: + output_size = [] + else: + if output_padding != 0: + raise ValueError( + 'output_padding option is mutually exclusive with ' + 'output_size' + ) + if isinstance(output_size, (list, tuple, int)): + output_size = convert_to_list(output_size, 3, 'output_size') + else: + raise ValueError( + "output_size should be int, or list, tuple of ints" + ) + + if output_padding == 0: + output_padding = [] + else: + output_padding = convert_to_list(output_padding, 3, 'output_padding') + + cudnn_version = get_cudnn_version() + + # TODO(LielinJiang): whether to use cudnn according to the version of cudnn + use_cudnn = ( + True + if (is_compiled_with_cuda() and cudnn_version is not None) + else False + ) + + op_type = 'conv3d_transpose' + data_format_ = "NHWC" if channel_last else "NCHW" + + if in_dygraph_mode(): + pre_bias = _C_ops.conv3d_transpose( + x, + weight, + stride, + padding, + output_padding, + output_size, + padding_algorithm, + groups, + dilation, + data_format_, + ) + if bias is not None: + return nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + return pre_bias + + if _in_legacy_dygraph(): + attrs = ( + 'output_padding', + output_padding, + 'output_size', + output_size, + 'paddings', + padding, + "padding_algorithm", + padding_algorithm, + 'strides', + stride, + 'dilations', + dilation, + 'groups', + groups, + 'use_cudnn', + use_cudnn, + "data_format", + data_format_, + ) + pre_bias = getattr(_legacy_C_ops, op_type)(x, weight, *attrs) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + out = pre_bias + else: + inputs = {'Input': [x], 'Filter': [weight]} + attrs = { + 'output_padding': output_padding, + 'output_size': output_size, + 'paddings': padding, + "padding_algorithm": padding_algorithm, + 'strides': stride, + 'dilations': dilation, + 'groups': groups, + 'use_cudnn': use_cudnn, + "data_format": data_format_, + } + helper = LayerHelper(op_type, **locals()) + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'conv3d' + ) + + pre_bias = helper.create_variable_for_type_inference(x.dtype) + outputs = {"Output": [pre_bias]} + + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=channel_dim) + else: + out = pre_bias + + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/distance.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/distance.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3a1a8b0d72a429e3ad0d48b2640e8e328ceb79 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/distance.py @@ -0,0 +1,111 @@ +# Copyright (c) 2022 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. + +import paddle +from ...fluid.data_feeder import check_variable_and_dtype, check_type +from ...fluid.layer_helper import LayerHelper +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph + +__all__ = [] + + +def pairwise_distance(x, y, p=2., epsilon=1e-6, keepdim=False, name=None): + r""" + + It computes the pairwise distance between two vectors. The + distance is calculated by p-oreder norm: + + .. math:: + + \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}. + + Parameters: + x (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N` + is batch size, :math:`D` is the dimension of vector. Available dtype is + float32, float64. + y (Tensor): Tensor, shape is :math:`[N, D]` or :math:`[D]`, where :math:`N` + is batch size, :math:`D` is the dimension of vector. Available dtype is + float32, float64. + p (float, optional): The order of norm. Default: :math:`2.0`. + epsilon (float, optional): Add small value to avoid division by zero. + Default: :math:`1e-6`. + keepdim (bool, optional): Whether to reserve the reduced dimension + in the output Tensor. The result tensor is one dimension less than + the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + + Returns: + Tensor, the dtype is same as input tensor. + + - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`, + depending on whether the input has data shaped as :math:`[N, D]`. + - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`, + depending on whether the input has data shaped as :math:`[N, D]`. + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64) + y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64) + distance = paddle.nn.functional.pairwise_distance(x, y) + print(distance.numpy()) # [5. 5.] + + """ + check_type(p, 'porder', (float, int), 'PairwiseDistance') + check_type(epsilon, 'epsilon', (float), 'PairwiseDistance') + check_type(keepdim, 'keepdim', (bool), 'PairwiseDistance') + if in_dygraph_mode(): + sub = _C_ops.subtract(x, y) + # p_norm op has not uesd epsilon, so change it to the following. + if epsilon != 0.0: + epsilon = paddle.fluid.dygraph.base.to_variable([epsilon], + dtype=sub.dtype) + sub = _C_ops.add(sub, epsilon) + return _C_ops.p_norm(sub, p, -1, 0., keepdim, False) + + if _in_legacy_dygraph(): + sub = _legacy_C_ops.elementwise_sub(x, y) + if epsilon != 0.0: + epsilon = paddle.fluid.dygraph.base.to_variable([epsilon], + dtype=sub.dtype) + sub = _legacy_C_ops.elementwise_add(sub, epsilon) + return _legacy_C_ops.p_norm(sub, 'axis', -1, 'porder', p, 'keepdim', + keepdim, 'epsilon', 0.) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'PairwiseDistance') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'PairwiseDistance') + sub = paddle.subtract(x, y) + if epsilon != 0.0: + epsilon_var = sub.block.create_var(dtype=sub.dtype) + epsilon_var = paddle.full(shape=[1], + fill_value=epsilon, + dtype=sub.dtype) + sub = paddle.add(sub, epsilon_var) + helper = LayerHelper("PairwiseDistance", name=name) + attrs = { + 'axis': -1, + 'porder': p, + 'keepdim': keepdim, + 'epsilon': 0., + } + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='p_norm', + inputs={'X': sub}, + outputs={'Out': out}, + attrs=attrs) + + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/extension.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..ce92e4aba200e8dbc2753da2755b395aea61663d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/extension.py @@ -0,0 +1,416 @@ +# 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. + +# TODO: define the extention functions + +import numpy as np +from ...fluid.data_feeder import check_dtype +from ...fluid.layer_helper import LayerHelper +from ...static import Variable +from ...tensor.creation import assign +from ...fluid import dygraph_utils +from ...tensor.layer_function_generator import templatedoc +from paddle import in_dynamic_mode +from paddle import _C_ops, _legacy_C_ops +from ...fluid.framework import ( + _non_static_mode, + _in_legacy_dygraph, + in_dygraph_mode, +) +from ...fluid.data_feeder import check_variable_and_dtype, check_type +from ...framework import core +from ...common_ops_import import convert_np_dtype_to_dtype_ + +__all__ = [] + + +def diag_embed(input, offset=0, dim1=-2, dim2=-1): + """ + This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) + are filled by ``input``. By default, a 2D plane formed by the last two dimensions + of the returned tensor will be selected. + + The argument ``offset`` determines which diagonal is generated: + + - If offset = 0, it is the main diagonal. + - If offset > 0, it is above the main diagonal. + - If offset < 0, it is below the main diagonal. + + Args: + input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64. + offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal). + dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2. + dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1. + + Returns: + Tensor, the output data type is the same as input data type. + + Examples: + .. code-block:: python + + import paddle.nn.functional as F + import numpy as np + + diag_embed = np.random.randn(2, 3).astype('float32') + # [[ 0.7545889 , -0.25074545, 0.5929117 ], + # [-0.6097662 , -0.01753256, 0.619769 ]] + + data1 = F.diag_embed(diag_embed) + data1.numpy() + # [[[ 0.7545889 , 0. , 0. ], + # [ 0. , -0.25074545, 0. ], + # [ 0. , 0. , 0.5929117 ]], + + # [[-0.6097662 , 0. , 0. ], + # [ 0. , -0.01753256, 0. ], + # [ 0. , 0. , 0.619769 ]]] + + data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2) + data2.numpy() + # [[[ 0. , 0. , 0. , 0. ], + # [ 0.7545889 , 0. , 0. , 0. ], + # [ 0. , -0.25074545, 0. , 0. ], + # [ 0. , 0. , 0.5929117 , 0. ]], + # + # [[ 0. , 0. , 0. , 0. ], + # [-0.6097662 , 0. , 0. , 0. ], + # [ 0. , -0.01753256, 0. , 0. ], + # [ 0. , 0. , 0.619769 , 0. ]]] + + data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2) + data3.numpy() + # [[[ 0. , 0.7545889 , 0. , 0. ], + # [ 0. , -0.6097662 , 0. , 0. ]], + # + # [[ 0. , 0. , -0.25074545, 0. ], + # [ 0. , 0. , -0.01753256, 0. ]], + # + # [[ 0. , 0. , 0. , 0.5929117 ], + # [ 0. , 0. , 0. , 0.619769 ]], + # + # [[ 0. , 0. , 0. , 0. ], + # [ 0. , 0. , 0. , 0. ]]] + """ + if not isinstance(input, Variable): + input = assign(input) + + if in_dygraph_mode(): + return _C_ops.diag_embed(input, offset, dim1, dim2) + elif in_dynamic_mode(): + return _legacy_C_ops.diag_embed( + input, "offset", offset, "dim1", dim1, "dim2", dim2 + ) + + inputs = {'Input': [input]} + attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2} + + def __check_input(input, offset, dim1, dim2): + check_dtype( + input.dtype, + 'Input', + ['int32', 'int64', 'float16', 'float32', 'float64'], + 'diag_embed', + ) + + input_shape = list(input.shape) + assert len(input_shape) >= 1, ( + "Input must be at least 1-dimensional, " + "But received Input's dimensional: %s.\n" % len(input_shape) + ) + + assert np.abs(dim1) <= len(input_shape), ( + "Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\n" + % (-(len(input_shape) + 1), len(input_shape), dim1) + ) + + assert np.abs(dim2) <= len(input_shape), ( + "Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\n" + % (-(len(input_shape) + 1), len(input_shape), dim2) + ) + + dim1_ = dim1 if dim1 >= 0 else len(input_shape) + dim1 + 1 + dim2_ = dim2 if dim2 >= 0 else len(input_shape) + dim2 + 1 + assert dim1_ != dim2_, ( + "dim1 and dim2 cannot be the same dimension." + "But received dim1 = %d, dim2 = %d\n" % (dim1, dim2) + ) + + __check_input(input, offset, dim1, dim2) + helper = LayerHelper("diag_embed", **locals()) + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + + helper.append_op( + type='diag_embed', + inputs={'Input': [input]}, + attrs={'offset': offset, 'dim1': dim1, 'dim2': dim2}, + outputs={'Out': [out]}, + ) + out.stop_gradient = True + return out + + +def sequence_mask(x, maxlen=None, dtype='int64', name=None): + r""" + **SequenceMask Layer** + + This layer outputs a mask according to the input :code:`x` and + :code:`maxlen` with data type of :code:`dtype`. + + Supposing :code:`x` is a Tensor with shape [d_1, d_2, ..., d_n], the + :code:`y` is a mask with shape [d_1, d_2, ..., d_n, maxlen], where: + + .. math:: + + y(i_1, i_2,..., i_n, j) = (j < x(i_1, i_2,..., i_n)) + + .. code-block:: text + + Case: + + Consider input: + x = [3, 1, 1, 0] max_len = 4 + + then we get out: + mask = [[1, 1, 1, 0], + [1, 0, 0, 0], + [1, 0, 0, 0], + [0, 0, 0, 0]] + + Args: + x (Variable): Input tensor of sequence_mask layer, \ + whose elements are integers less than :code:`maxlen`. \ + Tensor or LodTensor with shape [d_1, d_2, ..., d_n]. + maxlen (int, optional): Maximum length of the sequence. If :code:`maxlen` \ + is None, it would be replace with :math:`max(x)`. + dtype (np.dtype|paddle.dtype|str, optional): Data type of the output, \ + ``int64`` by default. + name(str, optional): For detailed information, please refer \ + to :ref:`api_guide_Name`. Usually name is no need to set and \ + None by default. + + Returns: + Tensor, The output sequence mask. Tensor with shape [d_1, d_2, ..., d_n, maxlen] \ + and data type of :code:`dtype`. The data type should be bool, float32, float64, int8, \ + int32 or int64. + + Examples: + .. code-block:: python + + import paddle + + lengths = paddle.to_tensor([10, 9, 8]) + mask = paddle.nn.functional.sequence_mask(lengths) + + print(mask.numpy()) + # [[1 1 1 1 1 1 1 1 1 1] + # [1 1 1 1 1 1 1 1 1 0] + # [1 1 1 1 1 1 1 1 0 0]] + + """ + + if in_dygraph_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if maxlen is not None: + if isinstance(maxlen, core.eager.Tensor): + attrs = ('out_dtype', dtype) + out = _legacy_C_ops.sequence_mask(x, maxlen, *attrs) + else: + attrs = ('out_dtype', dtype, 'maxlen', maxlen) + out = _legacy_C_ops.sequence_mask(x, None, *attrs) + out.stop_gradient = True + return out + + helper = LayerHelper('sequence_mask', **locals()) + out = helper.create_variable_for_type_inference(dtype=dtype) + + inputs = {'X': [x]} + attrs = {'out_dtype': out.dtype} + if maxlen is not None: + if isinstance(maxlen, Variable): + inputs['MaxLenTensor'] = maxlen + else: + attrs['maxlen'] = maxlen + + helper.append_op( + type='sequence_mask', inputs=inputs, outputs={'Y': out}, attrs=attrs + ) + + out.stop_gradient = True + return out + + +def gather_tree(ids, parents): + r""" + To be used after beam search. After beam search, we get selected ids at + each time step and the corresponding parents in the search tree. Both ids + and parents have the layout :attr:`[max_time, batch_size, beam_size]`. Then + :attr:`gather_tree` is used to backtrace from the last time step and + generate the full sequences by collecting selected ids. + + Here is an example: + + .. code-block:: text + + Given: + ids = [[[2 2] + [6 1]] + [[3 9] + [6 1]] + [[0 1] + [9 0]]] + parents = [[[0 0] + [1 1]] + [[1 0] + [1 0]] + [[0 0] + [0 1]]] + + Then: + gather_tree(ids, parents) + = [[[2 2] + [1 6]] + [[3 3] + [6 1]] + [[0 1] + [9 0]]] + + Args: + ids(Tensor): A Tensor with shape :attr:`[length, batch_size, beam_size]` + and data type :attr:`int32` or :attr:`int64`. It contains the selected + ids of all time steps. + parents(Tensor): A Tensor with the same shape and data type as :attr:`ids`, + It contains the parents corresponding to selected ids when searching + among beams. + + Returns: + A Tensor with the same shape and data type as :attr:`ids`. \ + It contains the full sequences. The sequences are collected from \ + :attr:`ids` by backtracing according to :attr:`parents`. + + Examples: + .. code-block:: python + + import paddle + + ids = paddle.to_tensor([[[2, 2], [6, 1]], [[3, 9], [6, 1]], [[0, 1], [9, 0]]]) + + parents = paddle.to_tensor([[[0, 0], [1, 1]], [[1, 0], [1, 0]], [[0, 0], [0, 1]]]) + + final_sequences = paddle.nn.functional.gather_tree(ids, parents) + # [[[2, 2], [1, 6]], [[3, 3], [6, 1]], [[0, 1], [9, 0]]] + + """ + if ids.ndim != 3: + raise ValueError( + "The input ids must be a 3D tensor with shape [length, batch_size, beam_size]" + ) + if ids.ndim != parents.ndim: + raise ValueError("The ids's shape must be the same as parents' shape. ") + + if in_dygraph_mode(): + return _C_ops.gather_tree(ids, parents) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.gather_tree(ids, parents) + else: + helper = LayerHelper('gather_tree', **locals()) + check_variable_and_dtype( + ids, 'ids', ['int32', 'int64'], 'gather_tree' + ) + check_variable_and_dtype( + parents, 'parents', ['int32', 'int64'], 'gather_tree' + ) + out = helper.create_variable_for_type_inference(dtype=ids.dtype) + + helper.append_op( + type="gather_tree", + inputs={"Ids": ids, "Parents": parents}, + outputs={"Out": out}, + ) + + return out + + +@templatedoc() +def temporal_shift(x, seg_num, shift_ratio=0.25, name=None, data_format="NCHW"): + """ + + **Temporal Shift Operator** + + ${comment} + + Args: + x(Tensor): ${x_comment} + seg_num(int): ${seg_num_comment} + shift_ratio(float): ${shift_ratio_comment} + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCHW" or "NHWC". Default: "NCHW". + + Returns: + out(Tensor): The temporal shifting result is a tensor with the + same shape and same data type as the input. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.randn([6, 4, 2, 2]) + out = F.temporal_shift(x=input, seg_num=2, shift_ratio=0.2) + """ + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. " + "Received Attr(data_format): {}.".format(data_format) + ) + if in_dygraph_mode(): + return _C_ops.temporal_shift(x, seg_num, shift_ratio, data_format) + if _non_static_mode(): + return _legacy_C_ops.temporal_shift( + x, + 'seg_num', + seg_num, + 'shift_ratio', + shift_ratio, + 'data_format', + data_format, + ) + + helper = LayerHelper("temporal_shift", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'temporal_shift') + check_type(seg_num, 'seg_num', int, 'temporal_shift') + check_type(shift_ratio, 'shift_ratio', float, 'temporal_shift') + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if not isinstance(seg_num, int): + raise TypeError("seg_num must be int type.") + + helper.append_op( + type="temporal_shift", + inputs={"X": x}, + outputs={"Out": out}, + attrs={ + "seg_num": seg_num, + "shift_ratio": shift_ratio, + "data_format": data_format, + }, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/input.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/input.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed7d314b08368f2a8b9fb895672e5d81871f66d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/input.py @@ -0,0 +1,234 @@ +# 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. + +from __future__ import print_function +import warnings +from ...static import Variable +from ...fluid.layer_helper import LayerHelper +from ...fluid.data_feeder import check_variable_and_dtype, check_dtype +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from ...fluid.framework import _in_legacy_dygraph, in_dygraph_mode + +__all__ = [] + + +def one_hot(x, num_classes, name=None): + """ + + The operator converts each id in the input 'x' to an one-hot vector with a + num_classes length. The value in the vector dimension corresponding to the id + is 1, and the value in the remaining dimension is 0. + + The shape of output Tensor is generated by appending num_classes dimension + behind the last dimension of the 'x' shape. + + .. code-block:: text + + Example 1: + + input: + x.shape = [4] + x.data = [1, 1, 3, 0] + num_classes = 4 + + output: + Out.shape = [4, 4] + Out.data = [[0., 1., 0., 0.], + [0., 1., 0., 0.], + [0., 0., 0., 1.], + [1., 0., 0., 0.]] + + Example 2: + + input: + x.shape = [4] + x.data = [1, 1, 5, 0] + num_classes = 4 + + output: Throw an exception for Illegal value + The second dimension in X is 5, which is greater than num_classes, + so it throws an exception. + + + Args: + x(Tensor): Tensor with shape :math:`[N_1, N_2, ..., N_k]` , + which contains at least one dimension. The data type is int32 or int64. + num_classes(int): An integer defining the num_classes of the one hot dimension. If input 'x' + is word id, num_classes is generally the dictionary size. + + Returns: + Tensor: The one-hot representations of 'x'. A Tensor with type float32. + + Examples: + .. code-block:: python + + import paddle + # Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4]. + label = paddle.to_tensor([1, 1, 3, 0], dtype='int64') + # label.shape = [4] + one_hot_label = paddle.nn.functional.one_hot(label, num_classes=4) + # one_hot_label.shape = [4, 4] + # one_hot_label = [[0., 1., 0., 0.], + # [0., 1., 0., 0.], + # [0., 0., 0., 1.], + # [1., 0., 0., 0.]] + + """ + + if in_dygraph_mode(): + return _C_ops.one_hot(x, num_classes) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.one_hot_v2(x, 'depth', num_classes, + 'allow_out_of_range', False) + else: + check_variable_and_dtype(x, 'input', ['int32', 'int64'], + 'one_hot_v2') + helper = LayerHelper("one_hot_v2", **locals()) + + one_hot_out = helper.create_variable_for_type_inference( + dtype='float32') + if not isinstance(num_classes, Variable): + # user attribute + inputs = {'X': x} + attrs = {'depth': num_classes, 'allow_out_of_range': False} + else: + num_classes.stop_gradient = True + inputs = {'X': x, 'depth_tensor': num_classes} + attrs = {'allow_out_of_range': False} + helper.append_op(type="one_hot_v2", + inputs=inputs, + attrs=attrs, + outputs={'Out': one_hot_out}, + stop_gradient=True) + return one_hot_out + + +def embedding(x, weight, padding_idx=None, sparse=False, name=None): + r""" + Used to lookup embeddings vector of ids provided by :attr:`x` . + + The shape of output Tensor is generated by appending the last dimension of the input Tensor shape + with embedding size. + + Note: + The id in :attr:`x` must satisfy :math:`0 =< id < weight.shape[0]` , + otherwise the program will throw an exception and exit. + + .. code-block:: text + + x is a Tensor. + padding_idx = -1 + x.data = [[1, 3], [2, 4], [4, 127]] + x.shape = [3, 2] + weight.shape = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when id is 127. + + Args: + x(Tensor): A Tensor with type int32/int64, which contains the id information. The value of the input id should + satisfy :math:`0<= id < weight.shape[0]` . + weight (Tensor): The weight. A Tensor with shape of lookup table parameter. It should have two elements which + indicates the size of the dictionary of embeddings and the size of each embedding vector respectively. + sparse(bool, optional): The flag indicating whether to use sparse update. This parameter only + affects the performance of the backwards gradient update. It is recommended to set + True because sparse update is faster. But some optimizers does not support sparse update, + such as :ref:`api_paddle_optimizer_adadelta_Adadelta` , :ref:`api_paddle_optimizer_adamax_Adamax` , :ref:`api_paddle_optimizer_lamb_Lamb`. + In these cases, sparse must be False. Default: False. + padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-weight.shape[0], weight.shape[0]). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`weight.shape[0] + padding\_idx` . It will output all-zero padding data whenever lookup + encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. + If set None, it makes no effect to output. Default: None. + name(str|None, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: Embedding Tensor mapped by x. The data type is the same as :attr:`weight`. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + x0 = paddle.arange(3, 6).reshape((3, 1)).astype(paddle.int64) + w0 = paddle.full(shape=(10, 3), fill_value=2).astype(paddle.float32) + + # x.data = [[3], [4], [5]] + # x.shape = [3, 1] + x = paddle.to_tensor(x0, stop_gradient=False) + + # w.data = [[2. 2. 2.] ... [2. 2. 2.]] + # w.shape = [10, 3] + w = paddle.to_tensor(w0, stop_gradient=False) + + # emb.data = [[[2., 2., 2.]], [[2., 2., 2.]], [[2., 2., 2.]]] + # emb.shape = [3, 1, 3] + emb = nn.functional.embedding( + x=x, weight=w, sparse=True, name="embedding") + + """ + padding_idx = -1 if padding_idx is None else padding_idx if padding_idx >= 0 else ( + weight.shape[0] + padding_idx) + + if padding_idx >= weight.shape[0] or padding_idx < -weight.shape[0]: + raise ValueError("padding_idx must be within [-{}, {})".format( + weight.shape[0], weight.shape[0])) + + if in_dygraph_mode(): + return _C_ops.embedding(x, weight, padding_idx, sparse) + elif _in_legacy_dygraph(): + return _legacy_C_ops.lookup_table_v2(weight, x, 'is_sparse', sparse, + 'is_distributed', False, + 'remote_prefetch', False, + 'padding_idx', padding_idx) + else: + helper = LayerHelper('embedding', **locals()) + dtype = helper.input_dtype(input_param_name='weight') + + check_variable_and_dtype(x, 'input', + ['uint8', 'int8', 'int16', 'int32', 'int64'], + 'embedding') + + is_distributed = False + remote_prefetch = sparse and (not is_distributed) + + tmp = helper.create_variable_for_type_inference(dtype) + + helper.append_op(type='lookup_table_v2', + inputs={ + 'Ids': x, + 'W': weight + }, + outputs={'Out': tmp}, + attrs={ + 'is_sparse': sparse, + 'is_distributed': is_distributed, + 'remote_prefetch': remote_prefetch, + 'padding_idx': padding_idx + }) + return tmp diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb19343c13a64325ab6216d49f78cac3881b74c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/loss.py @@ -0,0 +1,3895 @@ +# -*- coding: utf-8 -* +# 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. + +import paddle +from ...fluid.data_feeder import check_variable_and_dtype + +# TODO: define loss functions of neural network +import numpy as np +import paddle +import paddle.fluid as fluid +from ...fluid.layers.nn import _elementwise_op_in_dygraph +from ...tensor.manipulation import reshape +from ...fluid.layer_helper import LayerHelper +from ...fluid.framework import _varbase_creator +from ...static import Variable +from paddle.utils import deprecated +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from paddle.framework import core, _non_static_mode +from ...fluid.framework import ( + _in_legacy_dygraph, + in_dygraph_mode, + _non_static_mode, + _current_expected_place, +) + +__all__ = [] + + +def dice_loss(input, label, epsilon=0.00001, name=None): + r""" + + Dice loss for comparing the similarity between the input predictions and the label. + This implementation is for binary classification, where the input is sigmoid + predictions of each pixel, usually used for segmentation task. The dice loss can + be defined as the following equation: + + .. math:: + + dice\_loss &= 1 - \frac{2 * intersection\_area}{total\_area} \\ + &= \frac{(total\_area - intersection\_area) - intersection\_area}{total\_area} \\ + &= \frac{(union\_area - intersection\_area)}{total\_area} + + + Parameters: + input (Tensor): Tensor, rank>=2, shape is :math:`[N_1, N_2, ..., N_k, D]`, where :math:`N_1` is + the batch_size, :math:`D` is the number of categories. It is usually the output + predictions of sigmoid activation. The data type can be float32 or float64. + label (Tensor): Tensor, the groud truth with the same rank as input, shape is :math:`[N_1, N_2, ..., N_k, 1]`. + where :math:`N_1` is the batch_size. The data type can be int32 or int64. + epsilon (float): The epsilon will be added to the numerator and denominator. + If both input and label are empty, it makes sure dice is 1. + Default: 0.00001 + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tensor, which shape is [1], data type is the same as `input` . + + Example: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn((3,224,224,2)) + label = paddle.randint(high=2, shape=(3,224,224,1)) + predictions = F.softmax(x) + loss = F.dice_loss(input=predictions, label=label) + """ + assert input.dtype in (paddle.float32, paddle.float64) + assert label.dtype in (paddle.int32, paddle.int64) + assert ( + len(input.shape) >= 2 + ), "The rank of input should be greater than or equal to 2." + assert len(input.shape) == len(label.shape), ( + "The rank of input and label should be equal, " + "but received input: %d, label: %d." + % (len(input.shape), len(label.shape)) + ) + assert label.shape[-1] == 1, ( + "The last dimension of label should be 1, " + "but received %d." % label.shape[-1] + ) + assert ( + input.shape[:-1] == label.shape[:-1] + ), "All dimensions should be equal except the last one." + assert ( + input.numel() > 0 and label.numel() > 0 + ), "Any dimension of input and label cannot be equal to 0." + + label = paddle.squeeze(label, [-1]) + label = paddle.nn.functional.one_hot(label, input.shape[-1]) + reduce_dim = list(range(1, len(input.shape))) + inse = paddle.sum(input * label, axis=reduce_dim) + dice_denominator = paddle.sum(input, axis=reduce_dim) + paddle.sum( + label, axis=reduce_dim + ) + dice_score = 1 - inse * 2 / (dice_denominator + epsilon) + return paddle.mean(dice_score) + + +def log_loss(input, label, epsilon=1e-4, name=None): + r""" + + **Negative Log Loss Layer** + + This layer accepts input predictions and target label and returns the + negative log loss. + + .. math:: + + Out = -label * \log{(input + \epsilon)} + - (1 - label) * \log{(1 - input + \epsilon)} + + Args: + input (Tensor|list): A 2-D tensor with shape [N x 1], where N is the + batch size. This input is a probability computed + by the previous operator. Data type float32. + label (Tensor|list): The ground truth which is a 2-D tensor with + shape [N x 1], where N is the batch size. + Data type float32. + epsilon (float, optional): A small number for numerical stability. Default 1e-4. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + + Returns: + Tensor, which shape is [N x 1], data type is float32. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + label = paddle.randn((10,1)) + prob = paddle.randn((10,1)) + cost = F.log_loss(input=prob, label=label) + """ + if in_dygraph_mode(): + return _C_ops.log_loss(input, label, epsilon) + + helper = LayerHelper('log_loss', **locals()) + check_variable_and_dtype(input, 'input', ['float32'], 'log_loss') + check_variable_and_dtype(label, 'label', ['float32'], 'log_loss') + + loss = helper.create_variable_for_type_inference(dtype=input.dtype) + + helper.append_op( + type='log_loss', + inputs={'Predicted': [input], 'Labels': [label]}, + outputs={'Loss': [loss]}, + attrs={'epsilon': epsilon}, + ) + return loss + + +def fluid_softmax_with_cross_entropy( + logits, + label, + soft_label=False, + ignore_index=-100, + numeric_stable_mode=True, + return_softmax=False, + axis=-1, +): + r""" + + This operator implements the cross entropy loss function with softmax. This function + combines the calculation of the softmax operation and the cross entropy loss function + to provide a more numerically stable gradient. + + Because this operator performs a softmax on logits internally, it expects + unscaled logits. This operator should not be used with the output of + softmax operator since that would produce incorrect results. + + When the attribute :attr:`soft_label` is set :attr:`False`, this operators + expects mutually exclusive hard labels, each sample in a batch is in exactly + one class with a probability of 1.0. Each sample in the batch will have a + single label. + + The equation is as follows: + + 1) Hard label (one-hot label, so every sample has exactly one class) + + .. math:: + \\loss_j=-\text{logits}_{label_j} +\log\left(\sum_{i=0}^{K}\exp(\text{logits}_i)\right), j = 1,..., K + + 2) Soft label (each sample can have a distribution over all classes) + + .. math:: + \\loss_j= -\sum_{i=0}^{K}\text{label}_i\left(\text{logits}_i - \log\left(\sum_{i=0}^{K}\exp(\text{logits}_i)\right)\right), j = 1,...,K + + 3) If :attr:`numeric_stable_mode` is :attr:`True`, softmax is calculated first by: + + .. math:: + \\max_j&=\max_{i=0}^{K}{\text{logits}_i} \\ + log\_max\_sum_j &= \log\sum_{i=0}^{K}\exp(logits_i - max_j)\\ + softmax_j &= \exp(logits_j - max_j - {log\_max\_sum}_j) + + and then cross entropy loss is calculated by softmax and label. + + Args: + logits (Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64. The input tensor of unscaled log probabilities. + label (Tensor): The ground truth ``Tensor`` , data type is the same + as the ``logits`` . If :attr:`soft_label` is set to :attr:`True`, + Label is a ``Tensor`` in the same shape with :attr:`logits`. + If :attr:`soft_label` is set to :attr:`True`, Label is a ``Tensor`` + in the same shape with :attr:`logits` expect shape in dimension :attr:`axis` as 1. + soft_label (bool, optional): A flag to indicate whether to interpretant the given + labels as soft labels. Default False. + ignore_index (int, optional): Specifies a target value that is ignored and does + not contribute to the input gradient. Only valid + if :attr:`soft_label` is set to :attr:`False`. + Default: kIgnoreIndex(-100). + numeric_stable_mode (bool, optional): A flag to indicate whether to use a more + numerically stable algorithm. Only valid + when :attr:`soft_label` is :attr:`False` + and GPU is used. When :attr:`soft_label` + is :attr:`True` or CPU is used, the + algorithm is always numerically stable. + Note that the speed may be slower when use + stable algorithm. Default: True. + return_softmax (bool, optional): A flag indicating whether to return the softmax + along with the cross entropy loss. Default: False. + axis (int, optional): The index of dimension to perform softmax calculations. It + should be in range :math:`[-1, rank - 1]`, while :math:`rank` + is the rank of input :attr:`logits`. Default: -1. + + Returns: + ``Tensor`` or Tuple of two ``Tensor`` : Return the cross entropy loss if \ + `return_softmax` is False, otherwise the tuple \ + (loss, softmax), softmax is in the same shape \ + with input logits and cross entropy loss is in \ + the same shape with input logits except shape \ + in dimension :attr:`axis` as 1. + + Examples: + .. code-block:: python + + import paddle + + logits = paddle.to_tensor([0.4, 0.6, 0.9]) + label = paddle.randint(high=2, shape=[1], dtype="int64") + + out = paddle.nn.functional.softmax_with_cross_entropy(logits=logits, label=label) + print(out) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.15328646]) + """ + if _non_static_mode(): + if core.is_compiled_with_npu(): + softmax, backprop, loss = _legacy_C_ops.softmax_with_cross_entropy( + logits, + label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + numeric_stable_mode, + 'axis', + axis, + ) + else: + if in_dygraph_mode(): + softmax, loss = _C_ops.cross_entropy_with_softmax( + logits, + label, + soft_label, + True, + numeric_stable_mode, + ignore_index, + axis, + ) + if _in_legacy_dygraph(): + softmax, loss = _legacy_C_ops.softmax_with_cross_entropy( + logits, + label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + numeric_stable_mode, + 'axis', + axis, + ) + if not return_softmax: + return loss + else: + return loss, softmax + + attrs = { + 'soft_label': soft_label, + 'ignore_index': ignore_index, + 'numeric_stable_mode': numeric_stable_mode, + 'axis': axis, + } + helper = LayerHelper('softmax_with_cross_entropy', **locals()) + softmax = helper.create_variable_for_type_inference(dtype=logits.dtype) + loss = helper.create_variable_for_type_inference(dtype=logits.dtype) + + outputs = {'Softmax': softmax, 'Loss': loss} + if core.is_compiled_with_npu() or core.is_compiled_with_mlu(): + backprop = helper.create_variable_for_type_inference(dtype=logits.dtype) + outputs['Backprop'] = backprop + helper.append_op( + type='softmax_with_cross_entropy', + inputs={'Logits': logits, 'Label': label}, + outputs=outputs, + attrs=attrs, + ) + + if return_softmax: + return loss, softmax + + return loss + + +def npair_loss(anchor, positive, labels, l2_reg=0.002): + """ + + Npair loss requires paired data. Npair loss has two parts: the first part is L2 + regularizer on the embedding vector; the second part is cross entropy loss which + takes the similarity matrix of anchor and positive as logits. + + For more information, please refer to: + `Improved Deep Metric Learning with Multi class N pair Loss Objective `_ + + Args: + anchor(Tensor): embedding vector for the anchor image. shape=[batch_size, embedding_dims], + the data type is float32 or float64. + positive(Tensor): embedding vector for the positive image. shape=[batch_size, embedding_dims], + the data type is float32 or float64. + labels(Tensor): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64. + l2_reg(float32): L2 regularization term on embedding vector, default: 0.002. + + + Returns: + A Tensor representing the npair loss, the data type is the same as anchor, the shape is [1]. + + Examples: + + .. code-block:: python + + import paddle + + DATATYPE = "float32" + + anchor = paddle.rand(shape=(18, 6), dtype=DATATYPE) + positive = paddle.rand(shape=(18, 6), dtype=DATATYPE) + labels = paddle.rand(shape=(18,), dtype=DATATYPE) + + npair_loss = paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg = 0.002) + print(npair_loss) + + """ + check_variable_and_dtype( + anchor, 'anchor', ['float32', 'float64'], 'npair_loss' + ) + check_variable_and_dtype( + positive, 'positive', ['float32', 'float64'], 'positive' + ) + check_variable_and_dtype( + labels, 'labels', ['float32', 'float64', 'int64'], 'labels' + ) + Beta = 0.25 + batch_size = labels.shape[0] + + labels = paddle.reshape(labels, shape=[batch_size, 1]) + labels = paddle.tile(labels, repeat_times=[1, batch_size]) + + labels = paddle.equal(labels, paddle.transpose(labels, perm=[1, 0])).astype( + 'float32' + ) + labels = labels / paddle.sum(labels, axis=1, keepdim=True) + + l2loss = paddle.mean(paddle.sum(paddle.square(anchor), 1)) + paddle.mean( + paddle.sum(paddle.square(positive), 1) + ) + l2loss = l2loss * Beta * l2_reg + + similarity_matrix = paddle.matmul( + anchor, positive, transpose_x=False, transpose_y=True + ) + softmax_ce = fluid_softmax_with_cross_entropy( + logits=similarity_matrix, label=labels, soft_label=True + ) + cross_entropy = paddle.sum(labels * softmax_ce, 0) + celoss = paddle.mean(cross_entropy) + + return l2loss + celoss + + +def square_error_cost(input, label): + r""" + + This op accepts input predictions and target label and returns the + squared error cost. + + For predictions label, and target label, the equation is: + + .. math:: + + Out = (input - label)^2 + + Parameters: + input (Tensor): Input tensor, the data type should be float32. + label (Tensor): Label tensor, the data type should be float32. + + Returns: + Tensor, The tensor storing the element-wise squared error + difference between input and label. + + Examples: + + .. code-block:: python + + import paddle + input = paddle.to_tensor([1.1, 1.9]) + label = paddle.to_tensor([1.0, 2.0]) + output = paddle.nn.functional.square_error_cost(input, label) + print(output) + # [0.01, 0.01] + + """ + if in_dygraph_mode(): + minus_out = _C_ops.subtract(input, label) + square_out = _C_ops.square(minus_out) + return square_out + elif _in_legacy_dygraph(): + minus_out = _legacy_C_ops.elementwise_sub(input, label) + square_out = _legacy_C_ops.square(minus_out) + return square_out + + check_variable_and_dtype( + input, "input", ['float32', 'float64'], 'square_error_cost' + ) + check_variable_and_dtype( + label, "label", ['float32', 'float64'], 'square_error_cost' + ) + helper = LayerHelper('square_error_cost', **locals()) + minus_out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='elementwise_sub', + inputs={'X': [input], 'Y': [label]}, + outputs={'Out': [minus_out]}, + ) + + square_out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='square', inputs={'X': [minus_out]}, outputs={'Out': [square_out]} + ) + return square_out + + +def edit_distance( + input, + label, + normalized=True, + ignored_tokens=None, + input_length=None, + label_length=None, +): + """ + This op computes the edit distances, also called Levenshtein distance, between a batch of + hypothesis strings and their references. It measures how dissimilar two strings are by counting + the minimum number of operations to transform one string into another. + The operations include insertion, deletion, and substitution. + + For example, given hypothesis string A = "kitten" and reference + B = "sitting", A will be transformed into B + at least after two substitutions and one insertion: + + "kitten" -> "sitten" -> "sittin" -> "sitting" + + So the edit distance between A and B is 3. + + The input is a Tensor, the input_length and label_length should be supported. + + The `batch_size` of labels should be same as `input`. + + The output include the edit distance value between every pair of input and related label, and the number of sequence. + If Attr(normalized) is true, + the edit distance value will be divided by the length of label. + + Parameters: + input(Tensor): The input tensor, its rank should be equal to 2 and its data type should be int64. + label(Tensor): The label tensor, its rank should be equal to 2 and its data type should be int64. + normalized(bool, default True): Indicated whether to normalize the edit distance. + ignored_tokens(list, default None): Tokens that will be removed before + calculating edit distance. + input_length(Tensor): The length for each sequence in `input` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64. + label_length(Tensor): The length for each sequence in `label` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64. + NOTE: To be avoid unexpected result, the value of every elements in input_length and label_length should be equal to the value of the second dimension of input and label. For example, The input: [[1,2,3,4],[5,6,7,8],[9,10,11,12]], the shape of input is [3,4] and the input_length should be [4,4,4] + NOTE: This Api is different from fluid.metrics.EditDistance + + Returns: + Tuple: + + distance(Tensor): edit distance result, its data type is float32, and its shape is (batch_size, 1). + sequence_num(Tensor): sequence number, its data type is float32, and its shape is (1,). + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.to_tensor([[1,2,3],[4,5,6],[4,4,4],[1,1,1]], dtype='int64') + label = paddle.to_tensor([[1,3,4,1],[4,5,8,1],[7,7,7,1],[1,1,1,1]], dtype='int64') + input_len = paddle.to_tensor([3,3,3,3], dtype='int64') + label_len = paddle.to_tensor([4,4,4,4], dtype='int64') + + distance, sequence_num = F.loss.edit_distance(input=input, label=label, input_length=input_len, label_length=label_len, normalized=False) + + # print(distance) + # [[3.] + # [2.] + # [4.] + # [1.]] + # if set normalized to True + # [[0.75] + # [0.5 ] + # [1. ] + # [0.25] + # + # print(sequence_num) + # [4] + + """ + check_variable_and_dtype(input, 'input', ['int64'], 'edit_distance') + check_variable_and_dtype(label, 'label', ['int64'], 'edit_distance') + helper = LayerHelper("edit_distance", **locals()) + + # remove some tokens from input and labels + if ignored_tokens is not None and len(ignored_tokens) > 0: + erased_input = helper.create_variable_for_type_inference(dtype="int64") + erased_label = helper.create_variable_for_type_inference(dtype="int64") + + helper.append_op( + type="sequence_erase", + inputs={"X": [input]}, + outputs={"Out": [erased_input]}, + attrs={"tokens": ignored_tokens}, + ) + input = erased_input + + helper.append_op( + type="sequence_erase", + inputs={"X": [label]}, + outputs={"Out": [erased_label]}, + attrs={"tokens": ignored_tokens}, + ) + label = erased_label + + if in_dygraph_mode(): + return _C_ops.edit_distance( + input, label, input_length, label_length, normalized + ) + + this_inputs = {"Hyps": [input], "Refs": [label]} + if input_length is not None and label_length is not None: + this_inputs['HypsLength'] = [input_length] + this_inputs['RefsLength'] = [label_length] + + # edit distance op + edit_distance_out = helper.create_variable_for_type_inference(dtype="int64") + sequence_num = helper.create_variable_for_type_inference(dtype="int64") + helper.append_op( + type="edit_distance", + inputs=this_inputs, + outputs={"Out": [edit_distance_out], "SequenceNum": [sequence_num]}, + attrs={"normalized": normalized}, + ) + + return edit_distance_out, sequence_num + + +def binary_cross_entropy( + input, label, weight=None, reduction='mean', name=None +): + """ + This op measures the binary_cross_entropy loss between input predictions ``input`` + and target labels ``label`` . The binary_cross_entropy loss can be described as: + + If :attr:`weight` is set, the loss is: + + .. math:: + Out = -1 * weight * (label * log(input) + (1 - label) * log(1 - input)) + + If :attr:`weight` is None, the loss is: + + .. math:: + Out = -1 * (label * log(input) + (1 - label) * log(1 - input)) + + If :attr:`reduction` set to ``'none'``, the interface will return the original loss `Out`. + + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is: + + .. math:: + Out = MEAN(Out) + + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is: + + .. math:: + Out = SUM(Out) + + Note that the input predictions ``input`` always be the output of sigmoid, and the target labels ``label`` + should be numbers between 0 and 1. + + Parameters: + input (Tensor): The input predications tensor. 2-D tensor with shape: [N, *], + N is batch_size, `*` means number of additional dimensions. The ``input`` + should always be the output of sigmod. Available dtype is float32, float64. + label (Tensor): The target labels tensor. 2-D tensor with the same shape as + ``input``. The target labels which values should be numbers between 0 and 1. + Available dtype is float32, float64. + weight (Tensor, optional): A manual rescaling weight given to the loss of each + batch element. If given, has to be a Tensor of size nbatch and the data type + is float32, float64. Default is ``'None'``. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + + Returns: + output (Tensor): If ``reduction`` is ``'none'``, the shape of output is + same as ``input`` , else the shape of output is scalar. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([0.5, 0.6, 0.7], 'float32') + label = paddle.to_tensor([1.0, 0.0, 1.0], 'float32') + output = paddle.nn.functional.binary_cross_entropy(input, label) + print(output) # [0.65537095] + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in binary_cross_entropy should be 'sum', " + "'mean' or 'none', but received %s, which is not allowed." + % reduction + ) + + if in_dygraph_mode(): + out = _C_ops.bce_loss(input, label) + if weight is not None: + out = _C_ops.multiply(out, weight, 'axis', -1) + + if reduction == 'sum': + return _C_ops.sum(out, [], None, False) + + elif reduction == 'mean': + return _C_ops.mean_all(out) + else: + return out + else: + if _in_legacy_dygraph(): + out = _legacy_C_ops.bce_loss(input, label) + if weight is not None: + out = _legacy_C_ops.elementwise_mul(out, weight, 'axis', -1) + if reduction == 'sum': + return _legacy_C_ops.reduce_sum( + out, 'dim', [0], 'keep_dim', False, "reduce_all", True + ) + elif reduction == 'mean': + return _legacy_C_ops.mean(out) + else: + return out + else: + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'binary_cross_entropy' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'binary_cross_entropy' + ) + + sub_name = name if weight is None and reduction == 'none' else None + helper = LayerHelper("binary_cross_entropy", name=sub_name) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='bce_loss', + inputs={ + 'X': [input], + 'Label': [label], + }, + outputs={'Out': [out]}, + ) + + if weight is not None: + if isinstance(weight, paddle.static.Variable): + weight_name = name if reduction == 'none' else None + out = paddle.multiply(out, weight, name=weight_name) + else: + raise ValueError( + "The weight is not a Tensor, please convert to Tensor." + ) + + if reduction == 'sum': + return paddle.sum(out, name=name) + elif reduction == 'mean': + return paddle.mean(out, name=name) + else: + return out + + +def binary_cross_entropy_with_logits( + logit, label, weight=None, reduction='mean', pos_weight=None, name=None +): + r""" + This operator combines the sigmoid layer and the :ref:`api_nn_loss_BCELoss` layer. + Also, we can see it as the combine of ``sigmoid_cross_entropy_with_logits`` + layer and some reduce operations. + + This measures the element-wise probability error in classification tasks + in which each class is independent. + This can be thought of as predicting labels for a data-point, where labels + are not mutually exclusive. For example, a news article can be about + politics, technology or sports at the same time or none of these. + + First this operator calculate loss function as follows: + + .. math:: + Out = -Labels * \log(\sigma(Logit)) - (1 - Labels) * \log(1 - \sigma(Logit)) + + We know that :math:`\sigma(Logit) = \frac{1}{1 + e^{-Logit}}`. By substituting this we get: + + .. math:: + Out = Logit - Logit * Labels + \log(1 + e^{-Logit}) + + For stability and to prevent overflow of :math:`e^{-Logit}` when Logit < 0, + we reformulate the loss as follows: + + .. math:: + Out = \max(Logit, 0) - Logit * Labels + \log(1 + e^{-\|Logit\|}) + + Then, if ``weight`` or ``pos_weight`` is not None, this operator multiply the + weight tensor on the loss `Out`. The ``weight`` tensor will attach different + weight on every items in the batch. The ``pos_weight`` will attach different + weight on the positive label of each class. + + Finally, this operator applies reduce operation on the loss. + If :attr:`reduction` set to ``'none'``, the operator will return the original loss `Out`. + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is :math:`Out = MEAN(Out)`. + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is :math:`Out = SUM(Out)`. + + Note that the target labels ``label`` should be numbers between 0 and 1. + + Args: + logit (Tensor): The input predications tensor. 2-D tensor with shape: [N, *], + N is batch_size, `*` means number of additional dimensions. The ``logit`` + is usually the output of Linear layer. Available dtype is float32, float64. + label (Tensor): The target labels tensor. 2-D tensor with the same shape as + ``logit``. The target labels which values should be numbers between 0 and 1. + Available dtype is float32, float64. + weight (Tensor, optional): A manual rescaling weight given to the loss of each + batch element. If given, it has to be a 1D Tensor whose size is `[N, ]`, + The data type is float32, float64. Default is ``'None'``. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + pos_weight (Tensor, optional): A weight of positive examples. Must be a vector + with length equal to the number of classes. The data type is float32, float64. + Default is ``'None'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): If ``reduction`` is ``'none'``, the shape of output is + same as ``logit`` , else the shape of output is scalar. + + Examples: + + .. code-block:: python + + import paddle + + logit = paddle.to_tensor([5.0, 1.0, 3.0]) + label = paddle.to_tensor([1.0, 0.0, 1.0]) + output = paddle.nn.functional.binary_cross_entropy_with_logits(logit, label) + print(output) # [0.45618808] + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in binary_cross_entropy_with_logits " + "should be 'sum', 'mean' or 'none', but received %s, which is not allowed." + % reduction + ) + + if in_dygraph_mode(): + one = _C_ops.full( + [1], + float(1.0), + core.VarDesc.VarType.FP32, + _current_expected_place(), + ) + out = _C_ops.sigmoid_cross_entropy_with_logits( + logit, label, False, -100 + ) + if pos_weight is not None: + log_weight = _C_ops.add( + _C_ops.multiply(label, _C_ops.subtract(pos_weight, one)), one + ) + out = _C_ops.multiply(out, log_weight) + if weight is not None: + out = _C_ops.multiply(out, weight) + + if reduction == "sum": + return _C_ops.sum(out, [], None, False) + elif reduction == "mean": + return _C_ops.mean_all(out) + else: + return out + elif _in_legacy_dygraph(): + one = _varbase_creator(dtype=logit.dtype) + _legacy_C_ops.fill_constant( + one, + 'value', + float(1.0), + 'force_cpu', + False, + 'dtype', + one.dtype, + 'str_value', + '1.0', + 'shape', + [1], + ) + out = _legacy_C_ops.sigmoid_cross_entropy_with_logits(logit, label) + if pos_weight is not None: + log_weight = _legacy_C_ops.elementwise_add( + _legacy_C_ops.elementwise_mul( + label, _legacy_C_ops.elementwise_sub(pos_weight, one) + ), + one, + ) + out = _legacy_C_ops.elementwise_mul(out, log_weight) + if weight is not None: + out = _legacy_C_ops.elementwise_mul(out, weight) + + if reduction == "sum": + return _legacy_C_ops.reduce_sum(out, 'reduce_all', True) + elif reduction == "mean": + return _legacy_C_ops.mean(out) + else: + return out + + check_variable_and_dtype( + logit, + 'logit', + ['float32', 'float64'], + 'binary_cross_entropy_with_logits', + ) + check_variable_and_dtype( + label, + 'label', + ['float32', 'float64'], + 'binary_cross_entropy_with_logits', + ) + sigmoid_name = None + if reduction == 'none' and pos_weight is None and weight is None: + sigmoid_name = name + + out = paddle.fluid.layers.sigmoid_cross_entropy_with_logits( + logit, label, name=sigmoid_name + ) + + one = paddle.full(shape=[1], fill_value=1.0, dtype=logit.dtype) + if pos_weight is not None: + check_variable_and_dtype( + pos_weight, + 'pos_weight', + ['float32', 'float64'], + 'binary_cross_entropy_with_logits', + ) + log_weight = paddle.add( + paddle.multiply(label, paddle.subtract(pos_weight, one)), one + ) + pos_weight_name = ( + name if reduction == 'none' and weight is None else None + ) + out = paddle.multiply(out, log_weight, name=pos_weight_name) + + if weight is not None: + check_variable_and_dtype( + weight, + 'weight', + ['float32', 'float64'], + 'binary_cross_entropy_with_logits', + ) + weight_name = name if reduction == 'none' else None + out = paddle.multiply(out, weight, name=weight_name) + + if reduction == "sum": + return paddle.sum(out, name=name) + elif reduction == "mean": + return paddle.mean(out, name=name) + return out + + +def hsigmoid_loss( + input, + label, + num_classes, + weight, + bias=None, + path_table=None, + path_code=None, + is_sparse=False, + name=None, +): + """ + The hierarchical sigmoid organizes the classes into a complete binary tree to reduce the computational complexity + and speed up the model training, especially the training of language model. + + Each leaf node of the complete binary tree represents a class(word) and each non-leaf node acts as a binary classifier. + For each class(word), there's a unique path from root to itself, hsigmoid calculate the cost for each non-leaf node on + the path, and sum them to get a total cost. + + Comparing to softmax, hsigmoid can reduce the computational complexity from :math:`O(N)` to :math:`O(logN)`, where :math:`N` + represents the number of classes or the size of word dict. + + The API supports default tree and custom tree. For the default tree, you can refer to `Hierarchical Probabilistic Neural + Network Language Model `_. + + For the custom tree, you need to set :attr:`is_custom` to True, and do the following steps (take the language model as an example): + + 1. Using a custom word dict to build a binary tree, each leaf node should be an word in the word dict. + 2. Creating a dict map word_id -> path that from the word to the root node, we call it path_table. + 3. Creating a dict map word_id -> code of path that from the word to the root node, we call it path_code. + Code means the label of each binary classifier, 1 indicate true, 0 indicate false. + 4. Now, each word should has its path and code along the path, you can pass a batch of path and code related + to the same batch of inputs. + + Parameters: + input (Tensor): A tensor with the shape [N, D], where N is the size of mini-batch, + and D is the feature size. Its data type supports float32 or float64. + label (Tensor): A tensor contains the labels of training data. Its shape is [N, 1] + and data type is int64. + num_classes (int): The number of classes or the size of word dict, must be greater than 2. + If the default tree is used (path_code and path_table is None are None), `num_classes` + should not be None. If the custom tree is used (path_code and path_table is None are not None), + `num_classes` should be the number of non-leaf nodes, which indicates the num of + classes using by the binary classifier. + weight (Tensor): A tensor with shape (num_classes - 1, D), with the same data type as `input`. + bias (Tensor, optional): A tensor with shape (num_classes - 1, 1), with the same data type as `input`. + If `bias` is None, no bias will be add. Default is None. + path_table (Tensor, optional): A tensor that stores each batch of samples' path from leaf to root + node, its shape is [N, L] and data type is int64, where L is the length of path. For each sample i, + path_table[i] is a np.array like structure and each element in this array is the indexes in parent + nodes' weight matrix. If `path_table` and `path_code` are None, the default tree will be used. + Default is None. + path_code (Tensor, optional): A tensor that stores each batch of samples' code of path from leaf + to root node, its shape is [N, L] and data type is int64, which is the same as :attr:`path_table`. + Each code of path is consisted with the code of nodes from leaf to root node. If `path_table` and + `path_code` are None, the default tree will be used. Default is None. + is_sparse (bool, optional): Whether use sparse updating instead of dense updating. If `is_sparse` is True, + the gradient of `weight` and `input` will be sparse. Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A tensor with the cost of hierarchical sigmoid, its shape is [N, 1] and data type is the same as `input`. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + paddle.set_device('cpu') + + input = paddle.uniform([4, 3]) + # [[0.45424712 -0.77296764 0.82943869] # random + # [0.85062802 0.63303483 0.35312140] # random + # [0.57170701 0.16627562 0.21588242] # random + # [0.27610803 -0.99303514 -0.17114788]] # random + label = paddle.to_tensor([0, 1, 4, 5]) + num_classes = 5 + weight=paddle.uniform([num_classes-1, 3]) + # [[-0.64477652 0.24821866 -0.17456549] # random + # [-0.04635394 0.07473493 -0.25081766] # random + # [ 0.05986035 -0.12185556 0.45153677] # random + # [-0.66236806 0.91271877 -0.88088769]] # random + + out=F.hsigmoid_loss(input, label, num_classes, weight) + # [[1.96709502] + # [2.40019274] + # [2.11009121] + # [1.92374969]] + """ + if in_dygraph_mode(): + out, _, _ = _C_ops.hierarchical_sigmoid( + input, + weight, + label, + path_table, + path_code, + bias, + num_classes, + is_sparse, + 0, + [], + [], + [], + is_sparse, + ) + return out + elif _in_legacy_dygraph(): + out, _, _ = _legacy_C_ops.hierarchical_sigmoid( + input, + weight, + label, + path_table, + path_code, + bias, + 'num_classes', + num_classes, + 'is_sparse', + is_sparse, + 'remote_prefetch', + is_sparse, + ) + return out + + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'hsigmoid_loss' + ) + check_variable_and_dtype(label, 'label', ['int64'], 'hsigmoid_loss') + check_variable_and_dtype( + weight, 'weight', ['float32', 'float64'], 'hsigmoid_loss' + ) + if bias is not None: + check_variable_and_dtype( + bias, 'bias', ['float32', 'float64'], 'hsigmoid_loss' + ) + if path_table is not None: + check_variable_and_dtype( + path_table, 'path_table', ['int64'], 'hsigmoid_loss' + ) + if path_code is not None: + check_variable_and_dtype( + path_code, 'path_code', ['int64'], 'hsigmoid_loss' + ) + + attrs = { + "num_classes": num_classes, + "is_sparse": is_sparse, + "remote_prefetch": is_sparse, + } + + inputs = { + "X": input, + "W": weight, + "Bias": bias, + "PathTable": path_table, + "PathCode": path_code, + "Label": label, + } + + helper = LayerHelper('hsigmoid_loss', **locals()) + out = helper.create_variable_for_type_inference(input.dtype) + pre_out = helper.create_variable_for_type_inference(input.dtype) + outputs = {"Out": out, "PreOut": pre_out, "W_Out": weight} + + helper.append_op( + type="hierarchical_sigmoid", inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +def smooth_l1_loss(input, label, reduction='mean', delta=1.0, name=None): + r""" + Calculate smooth_l1_loss. Creates a criterion that uses a squared + term if the absolute element-wise error falls below 1 and an L1 term otherwise. + In some cases it can prevent exploding gradients and it is more robust and less + sensitivity to outliers. Also known as the Huber loss: + + .. math:: + + loss(x,y) = \frac{1}{n}\sum_{i}z_i + + + where :math:`z_i` is given by: + + .. math:: + + \mathop{z_i} = \left\{\begin{array}{rcl} + 0.5(x_i - y_i)^2 & & {if |x_i - y_i| < \delta} \\ + \delta * |x_i - y_i| - 0.5 * \delta^2 & & {otherwise} + \end{array} \right. + + Parameters: + input (Tensor): Input tensor, the data type is float32 or float64. Shape is + (N, C), where C is number of classes, and if shape is more than 2D, this + is (N, C, D1, D2,..., Dk), k >= 1. + label (Tensor): Label tensor, the data type is float32 or float64. The shape of label + is the same as the shape of input. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + delta (float, optional): Specifies the hyperparameter :math:`\delta` to be used. + The value determines how large the errors need to be to use L1. Errors + smaller than delta are minimized with L2. Parameter is ignored for + negative/zero values. Default = 1.0 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, The tensor variable storing the smooth_l1_loss of input and label. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand([3, 3]).astype('float32') + label = paddle.rand([3, 3]).astype('float32') + output = paddle.nn.functional.smooth_l1_loss(input, label) + print(output) + # [0.068004] + """ + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'smooth_l1_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'smooth_l1_loss' + ) + + if in_dygraph_mode(): + out, residual = _C_ops.huber_loss(input, label, delta) + else: + helper = LayerHelper('huber_loss', **locals()) + residual = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + helper.append_op( + type='huber_loss', + inputs={'X': input, 'Y': label}, + outputs={'Out': out, 'Residual': residual}, + attrs={'delta': delta}, + ) + + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in smooth_l1_loss should be 'sum', 'mean' or" + " 'none', but received %s, which is not allowed." % reduction + ) + if reduction == 'none': + return out + elif reduction == 'mean': + return paddle.mean(out) + elif reduction == 'sum': + return paddle.sum(out) + + +def margin_ranking_loss( + input, other, label, margin=0.0, reduction='mean', name=None +): + r""" + + Calcluate the margin rank loss between the input, other and label, use the math function as follows. + + .. math:: + margin\_rank\_loss = max(0, -label * (input - other) + margin) + + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is: + + .. math:: + Out = MEAN(margin\_rank\_loss) + + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is: + + .. math:: + Out = SUM(margin\_rank\_loss) + + If :attr:`reduction` set to ``'none'``, just return the origin ``margin_rank_loss``. + + Parameters: + input(Tensor): the first input tensor, it's data type should be float32, float64. + other(Tensor): the second input tensor, it's data type should be float32, float64. + label(Tensor): the label value corresponding to input, it's data type should be float32, float64. + margin (float, optional): The margin value to add, default value is 0; + reduction (str, optional): Indicate the reduction to apply to the loss, the candicates are ``'none'``, ``'mean'``, ``'sum'``.If :attr:`reduction` is ``'none'``, the unreduced loss is returned; If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned. If :attr:`reduction` is ``'sum'``, the reduced sum loss is returned. Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, if :attr:`reduction` is ``'mean'`` or ``'sum'``, the out shape is :math:`[1]`, otherwise the shape is the same as `input` .The same dtype as input tensor. + + Examples: + + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1, 2], [3, 4]], dtype='float32') + other = paddle.to_tensor([[2, 1], [2, 4]], dtype='float32') + label = paddle.to_tensor([[1, -1], [-1, -1]], dtype='float32') + loss = paddle.nn.functional.margin_ranking_loss(input, other, label) + print(loss) # [0.75] + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in MarginRankingLoss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + if in_dygraph_mode(): + out = _C_ops.subtract(other, input) + out = _C_ops.multiply(out, label) + if margin != 0.0: + margin = fluid.dygraph.base.to_variable([margin], dtype=out.dtype) + out = _C_ops.add(out, margin) + out = _C_ops.relu(out) + if reduction == 'sum': + return _C_ops.sum(out, [], None, False) + elif reduction == 'mean': + return _C_ops.mean_all(out) + return out + elif _in_legacy_dygraph(): + out = _legacy_C_ops.elementwise_sub(other, input) + out = _legacy_C_ops.elementwise_mul(out, label) + if margin != 0.0: + margin = fluid.dygraph.base.to_variable([margin], dtype=out.dtype) + out = _legacy_C_ops.elementwise_add(out, margin) + out = _legacy_C_ops.relu(out) + if reduction == 'sum': + return _legacy_C_ops.reduce_sum(out, 'reduce_all', True) + elif reduction == 'mean': + return _legacy_C_ops.mean(out) + return out + + helper = LayerHelper("margin_ranking_loss", **locals()) + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'margin_rank_loss' + ) + check_variable_and_dtype( + other, 'other', ['float32', 'float64'], 'margin_rank_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'margin_rank_loss' + ) + + out = paddle.subtract(other, input) + out = paddle.multiply(out, label) + + if margin != 0.0: + margin_var = out.block.create_var(dtype=out.dtype) + margin_var = paddle.full(shape=[1], fill_value=margin, dtype=out.dtype) + out = paddle.add(out, margin_var) + + result_out = helper.create_variable_for_type_inference(input.dtype) + + if reduction == 'none': + helper.append_op( + type="relu", inputs={"X": out}, outputs={"Out": result_out} + ) + return result_out + elif reduction == 'sum': + out = paddle.nn.functional.relu(out) + attrs = {"dim": [0], "keep_dim": False, "reduce_all": True} + helper.append_op( + type="reduce_sum", + inputs={"X": out}, + outputs={"Out": result_out}, + attrs=attrs, + ) + return result_out + elif reduction == 'mean': + out = paddle.nn.functional.relu(out) + helper.append_op( + type="mean", + inputs={"X": out}, + outputs={"Out": result_out}, + attrs={}, + ) + return result_out + + +def l1_loss(input, label, reduction='mean', name=None): + r""" + + Computes the L1 Loss of Tensor ``input`` and ``label`` as follows. + + If `reduction` set to ``'none'``, the loss is: + + .. math:: + Out = \lvert input - label \rvert + + If `reduction` set to ``'mean'``, the loss is: + + .. math:: + Out = MEAN(\lvert input - label \rvert) + + If `reduction` set to ``'sum'``, the loss is: + + .. math:: + Out = SUM(\lvert input - label \rvert) + + + Parameters: + input (Tensor): The input tensor. The shapes is [N, `*`], where N is batch size and `*` means any number of additional dimensions. It's data type should be float32, float64, int32, int64. + label (Tensor): label. The shapes is [N, `*`], same shape as ``input`` . It's data type should be float32, float64, int32, int64. + reduction (str, optional): Indicate the reduction to apply to the loss, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'none'``, the unreduced loss is returned; + If `reduction` is ``'mean'``, the reduced mean loss is returned. + If `reduction` is ``'sum'``, the reduced sum loss is returned. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the L1 Loss of Tensor ``input`` and ``label``. + If `reduction` is ``'none'``, the shape of output loss is :math:`[N, *]`, the same as ``input`` . + If `reduction` is ``'mean'`` or ``'sum'``, the shape of output loss is [1]. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1.5, 0.8], [0.2, 1.3]]) + label = paddle.to_tensor([[1.7, 1], [0.4, 0.5]]) + + l1_loss = paddle.nn.functional.l1_loss(input, label) + print(l1_loss.numpy()) + # [0.35] + + l1_loss = paddle.nn.functional.l1_loss(input, label, reduction='none') + print(l1_loss.numpy()) + # [[0.20000005 0.19999999] + # [0.2 0.79999995]] + + l1_loss = paddle.nn.functional.l1_loss(input, label, reduction='sum') + print(l1_loss.numpy()) + # [1.4] + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in L1Loss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + + if in_dygraph_mode(): + unreduced = _C_ops.abs(_C_ops.subtract(input, label)) + + if reduction == 'mean': + return _C_ops.mean_all(unreduced) + elif reduction == 'sum': + return _C_ops.sum(unreduced, [], None, False) + else: + return unreduced + elif _in_legacy_dygraph(): + unreduced = _elementwise_op_in_dygraph( + input, label, axis=-1, act='abs', op_name='elementwise_sub' + ) + if reduction == 'mean': + return _legacy_C_ops.mean(unreduced) + elif reduction == 'sum': + return _legacy_C_ops.reduce_sum( + unreduced, 'dim', [0], 'keep_dim', False, 'reduce_all', True + ) + else: + return unreduced + + check_variable_and_dtype( + input, 'input', ['float32', 'float64', 'int32', 'int64'], 'l1_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64', 'int32', 'int64'], 'l1_loss' + ) + + if reduction == 'sum': + unreduced = paddle.fluid.layers.elementwise_sub(input, label, act='abs') + return paddle.sum(unreduced, name=name) + elif reduction == 'mean': + unreduced = paddle.fluid.layers.elementwise_sub(input, label, act='abs') + return paddle.mean(unreduced, name=name) + else: + return paddle.fluid.layers.elementwise_sub( + input, label, act='abs', name=name + ) + + +def nll_loss( + input, label, weight=None, ignore_index=-100, reduction='mean', name=None +): + """ + This api returns negative log likelihood. + See more detail in :ref:`api_nn_loss_NLLLoss` . + + Parameters: + input (Tensor): Input tensor, the shape is :math:`[N, C]`, `C` is the number of classes. + But in K-dimension situation, the shape is :math:`[N, C, d_1, d_2, ..., d_K]`. + The data type is float32, float64. + label (Tensor): Label tensor, the shape is :math:`[N,]` or :math:`[N, d_1, d_2, ..., d_K]`. + The data type is int64. + weight (Tensor, optional): Weight tensor, a manual rescaling weight given + to each class. If given, it has to be a 1D Tensor whose size is `[C, ]`. Otherwise, + it treated as if having all ones. the data type is + float32, float64, Default is ``'None'``. + ignore_index (int, optional): Specifies a target value that is ignored + and does not contribute to the input gradient. Default is -100. + reduction (str, optional): Indicate how to average the loss, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'mean'``, the reduced mean loss is returned; + if `reduction` is ``'sum'``, the reduced sum loss is returned; + if `reduction` is ``'none'``, no reduction will be apllied. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + `Tensor`, the value of negative log likelihood loss. + + Examples: + .. code-block:: python + + import paddle + from paddle.nn.functional import nll_loss + log_softmax = paddle.nn.LogSoftmax(axis=1) + + input = paddle.to_tensor([[0.88103855, 0.9908683 , 0.6226845 ], + [0.53331435, 0.07999352, 0.8549948 ], + [0.25879037, 0.39530203, 0.698465 ], + [0.73427284, 0.63575995, 0.18827209], + [0.05689114, 0.0862954 , 0.6325046 ]], "float32") + log_out = log_softmax(input) + label = paddle.to_tensor([0, 2, 1, 1, 0], "int64") + result = nll_loss(log_out, label) + print(result) # Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=True, [1.07202101]) + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in nll_loss should be 'sum', 'mean' or " + "'none', but received %s, which is not allowed." % reduction + ) + + input_shape = list(input.shape) + input_dims = len(input_shape) + if input_dims < 2: + raise ValueError( + 'Expected 2 or more dimensions (got {})'.format(input_dims) + ) + n = input_shape[0] + c = input_shape[1] + if in_dygraph_mode(): + if input_dims != 2 and input_dims != 4: + input = _C_ops.reshape(input, [n, c, 1, -1]) + label = _C_ops.reshape(label, [n, 1, -1]) + out_shape = [n] + input_shape[2:] + out, total_weight = _C_ops.nll_loss( + input, label, weight, ignore_index, reduction + ) + if input_dims != 2 and input_dims != 4 and reduction == 'none': + out = _C_ops.reshape(out, out_shape) + return out + elif _in_legacy_dygraph(): + if input_dims != 2 and input_dims != 4: + input, _ = _legacy_C_ops.reshape2( + input, None, 'shape', [n, c, 1, -1] + ) + label, _ = _legacy_C_ops.reshape2(label, None, 'shape', [n, 1, -1]) + out_shape = [n] + input_shape[2:] + + out, total_weight = _legacy_C_ops.nll_loss( + input, + label, + weight, + 'ignore_index', + ignore_index, + 'reduction', + reduction, + ) + if input_dims != 2 and input_dims != 4 and reduction == 'none': + out, _ = _legacy_C_ops.reshape2(out, None, 'shape', out_shape) + return out + + helper = LayerHelper('nll_loss', **locals()) + + if input_dims != 2 and input_dims != 4: + input = reshape(input, shape=[n, c, 1, -1]) + label = reshape(label, shape=[n, 1, -1]) + out_shape = [n] + input_shape[2:] + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'nll_loss') + check_variable_and_dtype(label, 'label', ['int64'], 'nll_loss') + inputs = {'X': input, 'Label': label} + attrs = {'reduction': reduction, 'ignore_index': ignore_index} + if weight is not None: + if isinstance(weight, Variable): + inputs['Weight'] = weight + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + total_weight = helper.create_variable_for_type_inference(dtype=input.dtype) + outputs = {'Out': out, 'Total_weight': total_weight} + + helper.append_op( + type='nll_loss', inputs=inputs, outputs=outputs, attrs=attrs + ) + if input_dims != 2 and input_dims != 4 and reduction == 'none': + out = reshape(out, shape=out_shape) + + return out + + +def kl_div(input, label, reduction='mean', name=None): + r""" + Calculate the Kullback-Leibler divergence loss + between Input(X) and Input(Target). Notes that Input(X) is the + log-probability and Input(Target) is the probability. + + KL divergence loss is calculated as follows: + + $$l(x, y) = y * (\log(y) - x)$$ + + While :math:`x` is input and :math:`y` is label. + + While :attr:`reduction` is :attr:`none`, output loss is in + the same shape as input, loss in each point is calculated + separately and no reduction is applied. + + While :attr:`reduction` is :attr:`mean`, output loss is in + shape of [1] and loss value is the mean value of all losses. + + While :attr:`reduction` is :attr:`sum`, output loss is in + shape of [1] and loss value is the sum value of all losses. + + While :attr:`reduction` is :attr:`batchmean`, output loss is + in shape of [1] and loss value is the sum value of all losses + divided by batch size. + + Args: + input (Tensor): The input tensor. The shapes is [N, *], where N is batch size and `*` means + any number of additional dimensions. It's data type should be float32, float64. + label (Tensor): label. The shapes is [N, *], same shape as ``input`` . It's data type should be float32, float64. + reduction (Tensor): Indicate how to average the loss, + the candicates are ``'none'`` | ``'batchmean'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'mean'``, the reduced mean loss is returned; + If `reduction` is ``'batchmean'``, the sum loss divided by batch size is returned; + if `reduction` is ``'sum'``, the reduced sum loss is returned; + if `reduction` is ``'none'``, no reduction will be apllied. + Default is ``'mean'``. + name(str, optional): Name for the operation (optional, default is None). For more information, + please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The KL divergence loss. The data type is same as input tensor + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + shape = (5, 20) + x = paddle.uniform(shape, min=-10, max=10).astype('float32') + target = paddle.uniform(shape, min=-10, max=10).astype('float32') + + # 'batchmean' reduction, loss shape will be [1] + pred_loss = F.kl_div(x, target, reduction='batchmean') + # shape=[1] + + # 'mean' reduction, loss shape will be [1] + pred_loss = F.kl_div(x, target, reduction='mean') + # shape=[1] + + # 'sum' reduction, loss shape will be [1] + pred_loss = F.kl_div(x, target, reduction='sum') + # shape=[1] + + # 'none' reduction, loss shape is same with input shape + pred_loss = F.kl_div(x, target, reduction='none') + # shape=[5, 20] + + """ + # ugly type promotion + if ( + fluid.data_feeder.convert_dtype(input.dtype) == 'float32' + and fluid.data_feeder.convert_dtype(label.dtype) == 'float64' + ): + input = paddle.cast(input, 'float64') + elif ( + fluid.data_feeder.convert_dtype(input.dtype) == 'float64' + and fluid.data_feeder.convert_dtype(label.dtype) == 'float32' + ): + label = paddle.cast(label, 'float64') + + if in_dygraph_mode(): + out = _C_ops.kldiv_loss(input, label, 'none') + if reduction == 'mean': + out = paddle.mean(out) + elif reduction == 'sum': + out = paddle.sum(out) + elif reduction == 'batchmean': + if len(input.shape) > 0: + batch_size = input.shape[0] + out = paddle.sum(out) / batch_size + return out + elif _in_legacy_dygraph(): + out = _legacy_C_ops.kldiv_loss(input, label, 'reduction', 'none') + if reduction == 'mean': + out = paddle.mean(out) + elif reduction == 'sum': + out = paddle.sum(out) + elif reduction == 'batchmean': + if len(input.shape) > 0: + batch_size = input.shape[0] + out = paddle.sum(out) / batch_size + return out + + helper = LayerHelper('kl_div', **locals()) + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'kl_div') + check_variable_and_dtype(label, 'label', ['float32', 'float64'], 'kl_div') + fluid.data_feeder.check_type(reduction, 'reduction', str, 'kl_div') + + loss = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='kldiv_loss', + inputs={'X': input, 'Target': label}, + outputs={'Loss': loss}, + attrs={'reduction': 'none'}, + ) + + if reduction == 'mean': + loss = paddle.mean(loss) + elif reduction == 'sum': + loss = paddle.sum(loss) + elif reduction == 'batchmean': + batch_size = paddle.shape(input)[0] + loss = paddle.sum(loss) / batch_size + return loss + + +def mse_loss(input, label, reduction='mean', name=None): + r""" + Accept input predications and label and returns the mean square error. + + If :attr:`reduction` is set to ``'none'``, loss is calculated as: + + .. math:: + Out = (input - label)^2 + + If :attr:`reduction` is set to ``'mean'``, loss is calculated as: + + .. math:: + Out = \operatorname{mean}((input - label)^2) + + If :attr:`reduction` is set to ``'sum'``, loss is calculated as: + + .. math:: + Out = \operatorname{sum}((input - label)^2) + + Parameters: + input (Tensor): Input tensor, the data type should be float32 or float64. + label (Tensor): Label tensor, the data type should be float32 or float64. + reduction (string, optional): The reduction method for the output, + could be 'none' | 'mean' | 'sum'. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned. + If :attr:`reduction` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + + Returns: + Tensor, The tensor tensor storing the mean square error difference of input and label. + + Examples: + + .. code-block:: python + + import paddle + mse_loss = paddle.nn.loss.MSELoss() + input = paddle.to_tensor(1.5) + label = paddle.to_tensor(1.7) + output = mse_loss(input, label) + print(output) + # [0.04000002] + + """ + + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'mse_loss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + + if not in_dynamic_mode(): + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'mse_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'mse_loss' + ) + + if reduction == 'none': + return paddle.square(paddle.subtract(input, label), name=name) + elif reduction == 'mean': + return paddle.mean( + paddle.square(paddle.subtract(input, label)), name=name + ) + else: + return paddle.sum( + paddle.square(paddle.subtract(input, label)), name=name + ) + + +def ctc_loss( + log_probs, + labels, + input_lengths, + label_lengths, + blank=0, + reduction='mean', + norm_by_times=False, +): + """ + + An operator integrating the open source Warp-CTC library (https://github.com/baidu-research/warp-ctc) + to compute Connectionist Temporal Classification (CTC) loss. + It can be aliased as softmax with CTC, since a native softmax activation + is interated to the Warp-CTC library to normalize values for each row of the input tensor. + + Parameters: + log_probs (Tensor): The unscaled probability sequence with padding, which is a 3-D Tensor. The tensor shape is [max_logit_length, batch_size, num_classes + 1], where max_logit_length is the longest length of input logit sequence. The data type should be float32 or float64. + labels (Tensor): The ground truth sequence with padding, which must be a 3-D Tensor. The tensor shape is [batch_size, max_label_length], where max_label_length is the longest length of label sequence. The data type must be int32. + input_lengths (Tensor): The length for each input sequence, it should have shape [batch_size] and dtype int64. + label_lengths (Tensor): The length for each label sequence, it should have shape [batch_size] and dtype int64. + blank (int, optional): The blank label index of Connectionist Temporal Classification (CTC) loss, which is in the half-opened interval [0, num_classes + 1). The data type must be int32. Default is 0. + reduction (string, optional): Indicate how to average the loss, the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. If :attr:`reduction` is ``'mean'``, the output loss will be divided by the label_lengths, and then return the mean of quotient; If :attr:`reduction` is ``'sum'``, return the sum of loss; If :attr:`reduction` is ``'none'``, no reduction will be applied. Default is ``'mean'``. + norm_by_times (bool, default False) – Whether to normalize the gradients by the number of time-step, which is also the sequence’s length. There is no need to normalize the gradients if reduction mode is 'mean'. + + Returns: + Tensor, The Connectionist Temporal Classification (CTC) loss between ``log_probs`` and ``labels``. If attr:`reduction` is ``'none'``, the shape of loss is [batch_size], otherwise, the shape of loss is [1]. Data type is the same as ``log_probs``. + + Examples: + + .. code-block:: python + + # declarative mode + import paddle.nn.functional as F + import paddle + + # length of the longest logit sequence + max_seq_length = 4 + #length of the longest label sequence + max_label_length = 3 + # number of logit sequences + batch_size = 2 + # class num + class_num = 3 + + log_probs = paddle.to_tensor([[[4.17021990e-01, 7.20324516e-01, 1.14374816e-04], + [3.02332580e-01, 1.46755889e-01, 9.23385918e-02]], + + [[1.86260208e-01, 3.45560730e-01, 3.96767467e-01], + [5.38816750e-01, 4.19194520e-01, 6.85219526e-01]], + + [[2.04452246e-01, 8.78117442e-01, 2.73875929e-02], + [6.70467496e-01, 4.17304814e-01, 5.58689833e-01]], + + [[1.40386939e-01, 1.98101491e-01, 8.00744593e-01], + [9.68261600e-01, 3.13424170e-01, 6.92322612e-01]], + + [[8.76389146e-01, 8.94606650e-01, 8.50442126e-02], + [3.90547849e-02, 1.69830427e-01, 8.78142476e-01]]], + dtype="float32") + labels = paddle.to_tensor([[1, 2, 2], + [1, 2, 2]], dtype="int32") + input_lengths = paddle.to_tensor([5, 5], dtype="int64") + label_lengths = paddle.to_tensor([3, 3], dtype="int64") + + loss = F.ctc_loss(log_probs, labels, + input_lengths, + label_lengths, + blank=0, + reduction='none') + print(loss) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [3.91798496, 2.90765190]) + + loss = F.ctc_loss(log_probs, labels, + input_lengths, + label_lengths, + blank=0, + reduction='mean') + print(loss) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.13760614]) + + """ + + loss_out = fluid.layers.warpctc( + log_probs, labels, blank, norm_by_times, input_lengths, label_lengths + ) + + loss_out = paddle.squeeze(loss_out, [-1]) + assert reduction in ['mean', 'sum', 'none'] + if reduction == 'mean': + loss_out = paddle.mean(loss_out / label_lengths) + elif reduction == 'sum': + loss_out = paddle.sum(loss_out) + return loss_out + + +def margin_cross_entropy( + logits, + label, + margin1=1.0, + margin2=0.5, + margin3=0.0, + scale=64.0, + group=None, + return_softmax=False, + reduction='mean', +): + r""" + .. math:: + + L=-\frac{1}{N}\sum^N_{i=1}\log\frac{e^{s(cos(m_{1}\theta_{y_i}+m_{2})-m_{3})}}{e^{s(cos(m_{1}\theta_{y_i}+m_{2})-m_{3})}+\sum^n_{j=1,j\neq y_i} e^{scos\theta_{y_i}}} + + where the :math:`\theta_{y_i}` is the angle between the feature :math:`x` and + the representation of class :math:`i`. The details of ArcFace loss + could be referred to https://arxiv.org/abs/1801.07698. + + .. hint:: + The API supports single GPU and multi GPU, and don't supports CPU. + For data parallel mode, set ``group=False``. + For model parallel mode, set ``group=None`` or the group instance return by paddle.distributed.new_group. + And logits.shape[-1] can be different at each rank. + + Args: + logits (Tensor): shape[N, local_num_classes], the output of the normalized X multiply the normalized W. + The logits is shard_logits when using model parallel. + label (Tensor): shape[N] or shape[N, 1], the groud truth label. + margin1 (float, optional): m1 of margin loss, default value is `1.0`. + margin2 (float, optional): m2 of margin loss, default value is `0.5`. + margin3 (float, optional): m3 of margin loss, default value is `0.0`. + scale (float, optional): s of margin loss, default value is `64.0`. + group (Group, optional): The group instance return by paddle.distributed.new_group + or ``None`` for global default group or ``False`` for data parallel (do not communication cross ranks). + Default is ``None``. + return_softmax (bool, optional): Whether return softmax probability. Default value is `False`. + reduction (str, optional): The candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'mean'``, return the average of loss; + If :attr:`reduction` is ``'sum'``, return the sum of loss; + If :attr:`reduction` is ``'none'``, no reduction will be applied. + Default value is `'mean'`. + + Returns: + Tensor|tuple[Tensor, Tensor], return the cross entropy loss if + `return_softmax` is False, otherwise the tuple (loss, softmax), + softmax is shard_softmax when using model parallel, otherwise + softmax is in the same shape with input logits. If + ``reduction == None``, the shape of loss is ``[N, 1]``, otherwise + the shape is ``[1]``. + + Examples: + + .. code-block:: python + :name: code-example1 + + # required: gpu + # Single GPU + import paddle + m1 = 1.0 + m2 = 0.5 + m3 = 0.0 + s = 64.0 + batch_size = 2 + feature_length = 4 + num_classes = 4 + + label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64') + + X = paddle.randn( + shape=[batch_size, feature_length], + dtype='float64') + X_l2 = paddle.sqrt(paddle.sum(paddle.square(X), axis=1, keepdim=True)) + X = paddle.divide(X, X_l2) + + W = paddle.randn( + shape=[feature_length, num_classes], + dtype='float64') + W_l2 = paddle.sqrt(paddle.sum(paddle.square(W), axis=0, keepdim=True)) + W = paddle.divide(W, W_l2) + + logits = paddle.matmul(X, W) + loss, softmax = paddle.nn.functional.margin_cross_entropy( + logits, label, margin1=m1, margin2=m2, margin3=m3, scale=s, return_softmax=True, reduction=None) + + print(logits) + print(label) + print(loss) + print(softmax) + + #Tensor(shape=[2, 4], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[ 0.85204151, -0.55557678, 0.04994566, 0.71986042], + # [-0.20198586, -0.35270476, -0.55182702, 0.09749021]]) + #Tensor(shape=[2], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [2, 3]) + #Tensor(shape=[2, 1], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[82.37059586], + # [12.13448420]]) + #Tensor(shape=[2, 4], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[0.99978819, 0.00000000, 0.00000000, 0.00021181], + # [0.99992995, 0.00006468, 0.00000000, 0.00000537]]) + + .. code-block:: python + :name: code-example2 + + # required: distributed + # Multi GPU, test_margin_cross_entropy.py + import paddle + import paddle.distributed as dist + strategy = dist.fleet.DistributedStrategy() + dist.fleet.init(is_collective=True, strategy=strategy) + rank_id = dist.get_rank() + m1 = 1.0 + m2 = 0.5 + m3 = 0.0 + s = 64.0 + batch_size = 2 + feature_length = 4 + num_class_per_card = [4, 8] + num_classes = paddle.sum(paddle.to_tensor(num_class_per_card)) + + label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64') + label_list = [] + dist.all_gather(label_list, label) + label = paddle.concat(label_list, axis=0) + + X = paddle.randn( + shape=[batch_size, feature_length], + dtype='float64') + X_list = [] + dist.all_gather(X_list, X) + X = paddle.concat(X_list, axis=0) + X_l2 = paddle.sqrt(paddle.sum(paddle.square(X), axis=1, keepdim=True)) + X = paddle.divide(X, X_l2) + + W = paddle.randn( + shape=[feature_length, num_class_per_card[rank_id]], + dtype='float64') + W_l2 = paddle.sqrt(paddle.sum(paddle.square(W), axis=0, keepdim=True)) + W = paddle.divide(W, W_l2) + + logits = paddle.matmul(X, W) + loss, softmax = paddle.nn.functional.margin_cross_entropy( + logits, label, margin1=m1, margin2=m2, margin3=m3, scale=s, return_softmax=True, reduction=None) + + print(logits) + print(label) + print(loss) + print(softmax) + + # python -m paddle.distributed.launch --gpus=0,1 test_margin_cross_entropy.py + ## for rank0 input + #Tensor(shape=[4, 4], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[ 0.32888934, 0.02408748, -0.02763289, 0.18173063], + # [-0.52893978, -0.10623845, -0.21596515, -0.06432517], + # [-0.00536345, -0.03924667, 0.66735314, -0.28640926], + # [-0.09907366, -0.48534973, -0.10365338, -0.39472322]]) + #Tensor(shape=[4], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [11, 1 , 10, 11]) + + ## for rank1 input + #Tensor(shape=[4, 8], dtype=float64, place=CUDAPlace(1), stop_gradient=True, + # [[ 0.68654754, 0.28137170, 0.69694954, -0.60923933, -0.57077653, 0.54576703, -0.38709028, 0.56028204], + # [-0.80360371, -0.03042448, -0.45107338, 0.49559349, 0.69998950, -0.45411693, 0.61927630, -0.82808600], + # [ 0.11457570, -0.34785879, -0.68819499, -0.26189226, -0.48241491, -0.67685711, 0.06510185, 0.49660849], + # [ 0.31604851, 0.52087884, 0.53124749, -0.86176582, -0.43426329, 0.34786144, -0.10850784, 0.51566383]]) + #Tensor(shape=[4], dtype=int64, place=CUDAPlace(1), stop_gradient=True, + # [11, 1 , 10, 11]) + + ## for rank0 output + #Tensor(shape=[4, 1], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[38.96608230], + # [81.28152394], + # [69.67229865], + # [31.74197251]]) + #Tensor(shape=[4, 4], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[0.00000000, 0.00000000, 0.00000000, 0.00000000], + # [0.00000000, 0.00000000, 0.00000000, 0.00000000], + # [0.00000000, 0.00000000, 0.99998205, 0.00000000], + # [0.00000000, 0.00000000, 0.00000000, 0.00000000]]) + ## for rank1 output + #Tensor(shape=[4, 1], dtype=float64, place=CUDAPlace(1), stop_gradient=True, + # [[38.96608230], + # [81.28152394], + # [69.67229865], + # [31.74197251]]) + #Tensor(shape=[4, 8], dtype=float64, place=CUDAPlace(1), stop_gradient=True, + # [[0.33943993, 0.00000000, 0.66051859, 0.00000000, 0.00000000, 0.00004148, 0.00000000, 0.00000000], + # [0.00000000, 0.00000000, 0.00000000, 0.00000207, 0.99432097, 0.00000000, 0.00567696, 0.00000000], + # [0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00001795], + # [0.00000069, 0.33993085, 0.66006319, 0.00000000, 0.00000000, 0.00000528, 0.00000000, 0.00000000]]) + """ + + assert reduction in ['mean', 'sum', 'none', None] + if not (group == False or group is None or hasattr(group, 'is_member')): + raise ValueError( + 'Expected group is False, None or instance of paddle.distributed.collective.Group \ + (got group: {})'.format( + group + ) + ) + return + + if hasattr(group, 'is_member') and not group.is_member(): + return + + ring_id = 0 + rank = 0 + nranks = 1 + if group != False: + ring_id = 0 if group is None else group.id + if core.is_compiled_with_dist(): + parallel_env = paddle.distributed.ParallelEnv() + global_rank = parallel_env.rank + rank = ( + global_rank + if group is None + else group.get_group_rank(global_rank) + ) + nranks = parallel_env.world_size if group is None else group.nranks + + input_dims = len(list(logits.shape)) + label_dims = len(list(label.shape)) + if input_dims - 1 != label_dims and input_dims != label_dims: + raise ValueError( + 'Expected input_dims - 1 = label_dims or input_dims == label_dims\ + (got nput_dims{}, label_dims{})'.format( + input_dims, label_dims + ) + ) + if input_dims - 1 == label_dims: + label = paddle.unsqueeze(label, axis=-1) + + if in_dygraph_mode(): + softmax, loss = _C_ops.margin_cross_entropy( + logits, + label, + return_softmax, + ring_id, + rank, + nranks, + margin1, + margin2, + margin3, + scale, + ) + if reduction == 'mean': + loss = paddle.mean(loss) + elif reduction == 'sum': + loss = paddle.sum(loss) + if not return_softmax: + return loss + else: + return loss, softmax + elif _in_legacy_dygraph(): + softmax, loss = _legacy_C_ops.margin_cross_entropy( + logits, + label, + 'ring_id', + ring_id, + 'rank', + rank, + 'nranks', + nranks, + 'margin1', + margin1, + 'margin2', + margin2, + 'margin3', + margin3, + 'scale', + scale, + 'return_softmax', + return_softmax, + ) + if reduction == 'mean': + loss = paddle.mean(loss) + elif reduction == 'sum': + loss = paddle.sum(loss) + if not return_softmax: + return loss + else: + return loss, softmax + + op_type = 'margin_cross_entropy' + helper = LayerHelper(op_type, **locals()) + softmax = helper.create_variable_for_type_inference(dtype=logits.dtype) + loss = helper.create_variable_for_type_inference(dtype=logits.dtype) + + check_variable_and_dtype( + logits, + 'logits', + ['float16', 'float32', 'float64'], + 'margin_cross_entropy', + ) + check_variable_and_dtype( + label, 'label', ['int32', 'int64'], 'margin_cross_entropy' + ) + + helper.append_op( + type=op_type, + inputs={'Logits': logits, 'Label': label}, + outputs={'Softmax': softmax, 'Loss': loss}, + attrs={ + 'return_softmax': return_softmax, + 'ring_id': ring_id, + 'rank': rank, + 'nranks': nranks, + 'margin1': margin1, + 'margin2': margin2, + 'margin3': margin3, + 'scale': scale, + }, + ) + + if reduction == 'mean': + loss = paddle.mean(loss) + elif reduction == 'sum': + loss = paddle.sum(loss) + + if not return_softmax: + return loss + else: + return loss, softmax + + +@deprecated( + since="2.0.0", + update_to="paddle.nn.functional.cross_entropy", + level=1, + reason=( + 'Please notice that behavior of "paddle.nn.functional.softmax_with_cross_entropy" ' + 'and "paddle.nn.functional.cross_entropy" is different.' + ), +) +def softmax_with_cross_entropy( + logits, + label, + soft_label=False, + ignore_index=-100, + numeric_stable_mode=True, + return_softmax=False, + axis=-1, +): + r""" + This operator implements the cross entropy loss function with softmax. This function + combines the calculation of the softmax operation and the cross entropy loss function + to provide a more numerically stable gradient. + + Because this operator performs a softmax on logits internally, it expects + unscaled logits. This operator should not be used with the output of + softmax operator since that would produce incorrect results. + + When the attribute :attr:`soft_label` is set :attr:`False`, this operators + expects mutually exclusive hard labels, each sample in a batch is in exactly + one class with a probability of 1.0. Each sample in the batch will have a + single label. + + The equation is as follows: + + 1) Hard label (one-hot label, so every sample has exactly one class) + + .. math:: + \\loss_j=-\text{logits}_{label_j} +\log\left(\sum_{i=0}^{K}\exp(\text{logits}_i)\right), j = 1,..., K + + 2) Soft label (each sample can have a distribution over all classes) + + .. math:: + \\loss_j= -\sum_{i=0}^{K}\text{label}_i\left(\text{logits}_i - \log\left(\sum_{i=0}^{K}\exp(\text{logits}_i)\right)\right), j = 1,...,K + + 3) If :attr:`numeric_stable_mode` is :attr:`True`, softmax is calculated first by: + + .. math:: + \\max_j&=\max_{i=0}^{K}{\text{logits}_i} \\ + log\_max\_sum_j &= \log\sum_{i=0}^{K}\exp(logits_i - max_j)\\ + softmax_j &= \exp(logits_j - max_j - {log\_max\_sum}_j) + + and then cross entropy loss is calculated by softmax and label. + + Args: + logits (Tensor): A multi-dimension ``Tensor`` , and the data type is float32 or float64. The input tensor of unscaled log probabilities. + label (Tensor): The ground truth ``Tensor`` , data type is the same + as the ``logits`` . If :attr:`soft_label` is set to :attr:`True`, + Label is a ``Tensor`` in the same shape with :attr:`logits`. + If :attr:`soft_label` is set to :attr:`True`, Label is a ``Tensor`` + in the same shape with :attr:`logits` expect shape in dimension :attr:`axis` as 1. + soft_label (bool, optional): A flag to indicate whether to interpretant the given + labels as soft labels. Default False. + ignore_index (int, optional): Specifies a target value that is ignored and does + not contribute to the input gradient. Only valid + if :attr:`soft_label` is set to :attr:`False`. + Default: kIgnoreIndex(-100). + numeric_stable_mode (bool, optional): A flag to indicate whether to use a more + numerically stable algorithm. Only valid + when :attr:`soft_label` is :attr:`False` + and GPU is used. When :attr:`soft_label` + is :attr:`True` or CPU is used, the + algorithm is always numerically stable. + Note that the speed may be slower when use + stable algorithm. Default: True. + return_softmax (bool, optional): A flag indicating whether to return the softmax + along with the cross entropy loss. Default: False. + axis (int, optional): The index of dimension to perform softmax calculations. It + should be in range :math:`[-1, rank - 1]`, while :math:`rank` + is the rank of input :attr:`logits`. Default: -1. + + Returns: + ``Tensor`` or Tuple of two ``Tensor`` : Return the cross entropy loss if \ + `return_softmax` is False, otherwise the tuple \ + (loss, softmax), softmax is in the same shape \ + with input logits and cross entropy loss is in \ + the same shape with input logits except shape \ + in dimension :attr:`axis` as 1. + + Examples: + .. code-block:: python + + import paddle + + logits = paddle.to_tensor([0.4, 0.6, 0.9], dtype="float32") + label = paddle.to_tensor([1], dtype="int64") + + out = paddle.nn.functional.softmax_with_cross_entropy(logits=logits, label=label) + print(out) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.15328646]) + """ + return fluid_softmax_with_cross_entropy( + logits, + label, + soft_label, + ignore_index, + numeric_stable_mode, + return_softmax, + axis, + ) + + +def cross_entropy( + input, + label, + weight=None, + ignore_index=-100, + reduction='mean', + soft_label=False, + axis=-1, + use_softmax=True, + name=None, +): + r""" + + By default, this operator implements the cross entropy loss function with softmax. This function + combines the calculation of the softmax operation and the cross entropy loss function + to provide a more numerically stable computing. + + This operator will calculate the cross entropy loss function without softmax when use_softmax=False. + + By default, this operator will calculate the mean of the result, and you can also affect + the default behavior by using the reduction parameter. Please refer to the part of + parameters for details. + + This operator can be used to calculate the softmax cross entropy loss with soft and hard labels. + Where, the hard labels mean the actual label value, 0, 1, 2, etc. And the soft labels + mean the probability of the actual label, 0.6, 0.8, 0.2, etc. + + The calculation of this operator includes the following two steps. + + - **1.softmax cross entropy** + + 1. Hard label (each sample can only be assigned into one category) + + 1.1. when use_softmax=True + + .. math:: + \\loss_j=-\text{logits}_{label_j}+\log\left(\sum_{i=0}^{C}\exp(\text{logits}_i)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories. + + 1.2. when use_softmax=False + + .. math:: + \\loss_j=-\log\left({P}_{label_j}\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories, P is input(the output of softmax). + + + 2. Soft label (each sample is assigned to multiple categories with a certain probability, and the probability sum is 1). + + 2.1. when use_softmax=True + + .. math:: + \\loss_j=-\sum_{i=0}^{C}\text{label}_i\left(\text{logits}_i-\log\left(\sum_{i=0}^{C}\exp(\text{logits}_i)\right)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories. + + 2.2. when use_softmax=False + + .. math:: + \\loss_j=-\sum_{j=0}^{C}\left({label}_j*\log\left({P}_{label_j}\right)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories, P is input(the output of softmax). + + + + + - **2. Weight and reduction processing** + + 1. Weight + + If the ``weight`` parameter is ``None`` , go to the next step directly. + + If the ``weight`` parameter is not ``None`` , the cross entropy of each sample is weighted by weight + according to soft_label = False or True as follows. + + 1.1. Hard labels (soft_label = False) + + .. math:: + \\loss_j=loss_j*weight[label_j] + + + 1.2. Soft labels (soft_label = True) + + .. math:: + \\loss_j=loss_j*\sum_{i}\left(weight[label_i]*logits_i\right) + + 2. reduction + + 2.1 if the ``reduction`` parameter is ``none`` + + Return the previous result directly + + 2.2 if the ``reduction`` parameter is ``sum`` + + Return the sum of the previous results + + .. math:: + \\loss=\sum_{j}loss_j + + 2.3 if the ``reduction`` parameter is ``mean`` , it will be processed according to + the ``weight`` parameter as follows. + + 2.3.1. If the ``weight`` parameter is ``None`` + + Return the average value of the previous results + + .. math:: + \\loss=\sum_{j}loss_j/N + + where, N is the number of samples and C is the number of categories. + + 2.3.2. If the 'weight' parameter is not 'None', the weighted average value of the previous result will be returned + + 1. Hard labels (soft_label = False) + + .. math:: + \\loss=\sum_{j}loss_j/\sum_{j}weight[label_j] + + 2. Soft labels (soft_label = True) + + .. math:: + \\loss=\sum_{j}loss_j/\sum_{j}\left(\sum_{i}weight[label_i]\right) + + + Parameters: + input (Tensor): the data type is float32, float64. Shape is :math:`[N_1, N_2, ..., N_k, C]`, where C is number of classes, ``k >= 1`` . + + Note: + 1. when use_softmax=True, it expects unscaled logits. This operator should not be used with the output of softmax operator, which will produce incorrect results. + 2. when use_softmax=False, it expects the output of softmax operator. + + label (Tensor): + 1. If soft_label=False, the shape is + :math:`[N_1, N_2, ..., N_k]` or :math:`[N_1, N_2, ..., N_k, 1]`, k >= 1. + the data type is int32, int64, float32, float64, where each value is [0, C-1]. + + 2. If soft_label=True, the shape and data type should be same with ``input`` , + and the sum of the labels for each sample should be 1. + + weight (Tensor, optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size C and the data type is float32, float64. + Default is ``'None'`` . + ignore_index (int64, optional): Specifies a target value that is ignored + and does not contribute to the loss. A negative value means that no label + value needs to be ignored. Only valid when soft_label = False. + Default is ``-100`` . + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`size_average` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + soft_label (bool, optional): Indicate whether label is soft. Default is ``False``. + axis (int, optional):The index of dimension to perform softmax calculations. + It should be in range :math:`[-1, rank - 1]`, where :math:`rank` is the + number of dimensions of input :attr:`input`. + Default is ``-1`` . + use_softmax (bool, optional): Indicate whether compute softmax before cross_entropy. + Default is ``True``. + name (str, optional): The name of the operator. Default is ``None`` . + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + + Tensor. Return the softmax cross_entropy loss of ``input`` and ``label``. + The data type is the same as input. + + If :attr:`reduction` is ``'mean'`` or ``'sum'`` , the dimension of return value is ``1``. + + If :attr:`reduction` is ``'none'``: + + 1. If soft_label = False, the dimension of return value is the same with ``label`` . + + 2. if soft_label = True, the dimension of return value is :math:`[N_1, N_2, ..., N_k, 1]` . + + Examples: + .. code-block:: python + + # hard labels + import paddle + paddle.seed(99999) + N=100 + C=200 + reduction='mean' + input = paddle.rand([N, C], dtype='float64') + label = paddle.randint(0, C, shape=[N], dtype='int64') + weight = paddle.rand([C], dtype='float64') + + cross_entropy_loss = paddle.nn.loss.CrossEntropyLoss( + weight=weight, reduction=reduction) + dy_ret = cross_entropy_loss( + input, + label) + print(dy_ret.numpy()) #[5.41993642] + + .. code-block:: python + + # soft labels + import paddle + paddle.seed(99999) + axis = -1 + ignore_index = -100 + N = 4 + C = 3 + shape = [N, C] + reduction='mean' + weight = None + logits = paddle.uniform(shape, dtype='float64', min=0.1, max=1.0) + labels = paddle.uniform(shape, dtype='float64', min=0.1, max=1.0) + labels /= paddle.sum(labels, axis=axis, keepdim=True) + paddle_loss_mean = paddle.nn.functional.cross_entropy( + logits, + labels, + soft_label=True, + axis=axis, + weight=weight, + reduction=reduction) + print(paddle_loss_mean.numpy()) #[1.12908343] + + """ + + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in softmax_cross_entropy" + "should be 'sum', 'mean' or 'none', but received %s, which is not allowed." + % reduction + ) + if ignore_index > 0 and soft_label == True: + raise ValueError( + "When soft_label == True, the value of 'ignore_index' in softmax_cross_entropy" + "should be '-100', but received %s, which is not allowed." + % ignore_index + ) + + input_dims = len(list(input.shape)) + if input_dims == 0: + raise ValueError('The dimention of input should be larger than zero!') + + label_dims = len(list(label.shape)) + if input_dims - 1 != label_dims and input_dims != label_dims: + raise ValueError( + 'Expected nput_dims - 1 = label_dims or input_dims == label_dims\ + (got nput_dims{}, label_dims{})'.format( + input_dims, label_dims + ) + ) + if input_dims - 1 == label_dims: + label = paddle.unsqueeze(label, axis=axis) + + if in_dygraph_mode(): + if soft_label == False: + valid_label = ( + paddle.cast(label != ignore_index, dtype=label.dtype) * label + ) + if core.is_compiled_with_npu() or core.is_compiled_with_mlu(): + if soft_label == False: + _, _, out = _legacy_C_ops.softmax_with_cross_entropy( + input, + valid_label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + True, + 'axis', + axis, + 'use_softmax', + use_softmax, + ) + else: + _, _, out = _legacy_C_ops.softmax_with_cross_entropy( + input, + label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + True, + 'axis', + axis, + 'use_softmax', + use_softmax, + ) + else: + _, out = _C_ops.cross_entropy_with_softmax( + input, label, soft_label, use_softmax, True, ignore_index, axis + ) + + if weight is not None: + + # trans weight from class to sample, shape:N or [N,H,W] for 1d and 2d cases. + if soft_label == True: + # chajchaj: + # weight's shape is C, where C is class num. + # for 1d case: label's shape is [N,C], weight_gather's shape is N. + # for 2d case: label's shape is [N,H,W,C], weight_gather's shape is [N,H,W]. + weight_gather = paddle.matmul( + x=paddle.cast(label, weight.dtype), + y=weight, + transpose_x=False, + transpose_y=True, + ) + out_shape = list(out.shape) + weight_gather_reshape = reshape(weight_gather, shape=out_shape) + out = paddle.cast(out, weight_gather_reshape.dtype) + + out = _C_ops.multiply(out, weight_gather_reshape) + else: + if input.shape[axis] != weight.shape[-1]: + raise ValueError( + "input's class_dimension({}) must equal to " + "weight's class_dimension({}) " + "when weight is provided".format( + input.shape[axis], weight.shape[-1] + ) + ) + + ignore_weight_mask = paddle.cast( + (label != ignore_index), out.dtype + ) + if ( + ignore_weight_mask.ndim > 1 + and ignore_weight_mask.shape[axis] == 1 + ): + # TODO: Temporarily use squeeze instead of squeeze_ + ignore_weight_mask = paddle.squeeze( + ignore_weight_mask, axis + ) + if axis != -1 and axis != valid_label.ndim - 1: + temp_perm = ( + list(range(axis % valid_label.ndim)) + + list( + range( + (axis % valid_label.ndim + 1), valid_label.ndim + ) + ) + + [axis % valid_label.ndim] + ) + weight_gather = _C_ops.gather_nd( + weight, valid_label.transpose(temp_perm) + ) + else: + weight_gather = _C_ops.gather_nd(weight, valid_label) + weight_gather = _C_ops.multiply( + weight_gather, ignore_weight_mask + ) + input_shape = list(label.shape) + weight_gather_reshape = reshape( + weight_gather, shape=input_shape + ) + out = paddle.cast(out, weight_gather_reshape.dtype) + out = _C_ops.multiply(out, weight_gather_reshape) + + if reduction == "sum": + # because of fluid_softmax_with_cross_entropy op's inner logic, + # in the out tensor of this op, the loss of sample with class_index==ignore_index is 0 + # so, reduce_sum all directly is ok + return _C_ops.sum(out, [], None, False) + elif reduction == "mean": + # 1. if weight==none, + # numerator: reduce_sum all loss directly is ok causeof fluid_softmax_with_cross_entropy's inner logic + # denominator: count sample num with class_index!=ignore_index + # 2. else + # numerator: loss's weighted sum + # denominator: cal the sum of weight where the sample's class_index!=ignore_index + if ignore_index >= 0: + out_sum = _C_ops.sum(out, [], None, False) + # for each label[i],set 1 or 0, according to ignore_index + # mask[i]=0, if label[i]==ignore_index + # mask[i]=1, otherwise + mask = label != ignore_index + if weight is None: + mask = paddle.cast(mask, dtype=out_sum.dtype) + count = _C_ops.sum(mask, [], None, False) + ret = out_sum / (count + (count == 0.0)) + else: + mask = paddle.cast(mask, weight_gather_reshape.dtype) + weight_ignored = _C_ops.multiply( + mask, weight_gather_reshape + ) + weight_sum = _C_ops.sum(weight_ignored, [], None, False) + ret = out_sum / (weight_sum + (weight_sum == 0.0)) + return ret + elif weight is not None: + out_sum = _C_ops.sum(out, [], None, False) + total_weight = _C_ops.sum( + weight_gather_reshape, [], None, False + ) + return out_sum / (total_weight + (total_weight == 0.0)) + else: + return _C_ops.mean_all(out) + + else: + if input_dims - 1 == label_dims: + out = paddle.squeeze(out, axis=axis) + return out + + elif _in_legacy_dygraph(): + if soft_label == False: + valid_label = ( + paddle.cast(label != ignore_index, dtype=label.dtype) * label + ) + label_min = paddle.min(valid_label) + label_max = paddle.max(valid_label) + if label_min < 0: + raise ValueError( + "Target {} is out of lower bound.".format(label_min.item()) + ) + if label_max >= input.shape[axis]: + raise ValueError( + "Target {} is out of upper bound.".format(label_max.item()) + ) + if core.is_compiled_with_npu() or core.is_compiled_with_mlu(): + if soft_label == False: + _, _, out = _legacy_C_ops.softmax_with_cross_entropy( + input, + valid_label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + True, + 'axis', + axis, + 'use_softmax', + use_softmax, + ) + else: + _, _, out = _legacy_C_ops.softmax_with_cross_entropy( + input, + label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + True, + 'axis', + axis, + 'use_softmax', + use_softmax, + ) + else: + _, out = _legacy_C_ops.softmax_with_cross_entropy( + input, + label, + 'soft_label', + soft_label, + 'ignore_index', + ignore_index, + 'numeric_stable_mode', + True, + 'axis', + axis, + 'use_softmax', + use_softmax, + ) + + if weight is not None: + + # trans weight from class to sample, shape:N or [N,H,W] for 1d and 2d cases. + if soft_label == True: + # chajchaj: + # weight's shape is C, where C is class num. + # for 1d case: label's shape is [N,C], weight_gather's shape is N. + # for 2d case: label's shape is [N,H,W,C], weight_gather's shape is [N,H,W]. + weight_gather = paddle.matmul( + x=paddle.cast(label, weight.dtype), + y=weight, + transpose_x=False, + transpose_y=True, + ) + out_shape = list(out.shape) + weight_gather_reshape = reshape(weight_gather, shape=out_shape) + out = paddle.cast(out, weight_gather_reshape.dtype) + + out = _legacy_C_ops.elementwise_mul(out, weight_gather_reshape) + + else: + if input.shape[axis] != weight.shape[-1]: + raise ValueError( + "input's class_dimension({}) must equal to " + "weight's class_dimension({}) " + "when weight is provided".format( + input.shape[axis], weight.shape[-1] + ) + ) + + ignore_weight_mask = paddle.cast( + (label != ignore_index), out.dtype + ) + if ( + ignore_weight_mask.ndim > 1 + and ignore_weight_mask.shape[axis] == 1 + ): + # TODO: Temporarily use squeeze instead of squeeze_ + ignore_weight_mask = paddle.squeeze( + ignore_weight_mask, axis + ) + if axis != -1 and axis != valid_label.ndim - 1: + temp_perm = ( + list(range(axis % valid_label.ndim)) + + list( + range( + (axis % valid_label.ndim + 1), valid_label.ndim + ) + ) + + [axis % valid_label.ndim] + ) + weight_gather = _legacy_C_ops.gather_nd( + weight, valid_label.transpose(temp_perm) + ) + else: + weight_gather = _legacy_C_ops.gather_nd(weight, valid_label) + weight_gather = _legacy_C_ops.elementwise_mul( + weight_gather, ignore_weight_mask + ) + input_shape = list(label.shape) + weight_gather_reshape = reshape( + weight_gather, shape=input_shape + ) + out = paddle.cast(out, weight_gather_reshape.dtype) + out = _legacy_C_ops.elementwise_mul(out, weight_gather_reshape) + + if reduction == "sum": + # because of fluid_softmax_with_cross_entropy op's inner logic, + # in the out tensor of this op, the loss of sample with class_index==ignore_index is 0 + # so, reduce_sum all directly is ok + return _legacy_C_ops.reduce_sum(out, 'reduce_all', True) + elif reduction == "mean": + # 1. if weight==none, + # numerator: reduce_sum all loss directly is ok causeof fluid_softmax_with_cross_entropy's inner logic + # denominator: count sample num with class_index!=ignore_index + # 2. else + # numerator: loss's weighted sum + # denominator: cal the sum of weight where the sample's class_index!=ignore_index + if ignore_index >= 0: + out_sum = _legacy_C_ops.reduce_sum(out, 'reduce_all', True) + # for each label[i],set 1 or 0, according to ignore_index + # mask[i]=0, if label[i]==ignore_index + # mask[i]=1, otherwise + mask = label != ignore_index + if weight is None: + mask = paddle.cast(mask, dtype=out_sum.dtype) + count = _legacy_C_ops.reduce_sum(mask, 'reduce_all', True) + ret = out_sum / (count + (count == 0.0)) + else: + mask = paddle.cast(mask, weight_gather_reshape.dtype) + weight_ignored = _legacy_C_ops.elementwise_mul( + mask, weight_gather_reshape + ) + weight_sum = _legacy_C_ops.reduce_sum( + weight_ignored, 'reduce_all', True + ) + ret = out_sum / (weight_sum + (weight_sum == 0.0)) + return ret + elif weight is not None: + out_sum = _legacy_C_ops.reduce_sum(out, 'reduce_all', True) + total_weight = _legacy_C_ops.reduce_sum( + weight_gather_reshape, 'reduce_all', True + ) + return out_sum / (total_weight + (total_weight == 0.0)) + else: + return _legacy_C_ops.mean(out) + else: + if input_dims - 1 == label_dims: + out = paddle.squeeze(out, axis=axis) + return out + + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64'], + 'softmax_cross_entropy', + ) + check_variable_and_dtype( + label, + 'label', + ['uint8', 'int8', 'int16', 'int32', 'int64', 'float32', 'float64'], + 'softmax_cross_entropy', + ) + attrs = { + 'soft_label': soft_label, + 'ignore_index': ignore_index, + 'numeric_stable_mode': True, + 'axis': axis, + 'use_softmax': use_softmax, + } + helper = LayerHelper('softmax_with_cross_entropy', **locals()) + softmax = helper.create_variable_for_type_inference(dtype=input.dtype) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + + outputs = {'Softmax': softmax, 'Loss': out} + if core.is_compiled_with_npu() or core.is_compiled_with_mlu(): + backprop = helper.create_variable_for_type_inference(dtype=input.dtype) + outputs['Backprop'] = backprop + helper.append_op( + type='softmax_with_cross_entropy', + inputs={'Logits': input, 'Label': label}, + outputs=outputs, + attrs=attrs, + ) + + if weight is not None: + check_variable_and_dtype( + weight, 'weight', ['float32', 'float64'], 'softmax_cross_entropy' + ) + weight_name = name if reduction == 'none' else None + if soft_label == True: + # chajchaj: + # trans weight from class to sample, shape:N or [N,H,W] for 1d and 2d cases. + # weight's shape is C, where C is class num. + # for 1d case: label's shape is [N,C], weight_gather's shape is N. + # for 2d case: label's shape is [N,H,W,C], weight_gather's shape is [N,H,W]. + weight_gather = paddle.matmul( + x=paddle.cast(label, weight.dtype), + y=weight, + transpose_x=False, + transpose_y=True, + ) + + out_shape = list(out.shape) + weight_gather_reshape = reshape(weight_gather, shape=out_shape) + out = paddle.cast(out, weight_gather_reshape.dtype) + else: + if input.shape[axis] != weight.shape[-1]: + raise ValueError( + "input's class_dimension({}) must equal to " + "weight's class_dimension({}) " + "when weight is provided".format( + input.shape[axis], weight.shape[-1] + ) + ) + + valid_label = paddle.multiply( + paddle.cast(label != ignore_index, dtype=label.dtype), label + ) + ignore_weight_mask = paddle.cast( + (label != ignore_index), input.dtype + ) + if ( + ignore_weight_mask.ndim > 1 + and ignore_weight_mask.shape[axis] == 1 + ): + ignore_weight_mask = paddle.squeeze(ignore_weight_mask, axis) + if axis != -1 and axis != valid_label.ndim - 1: + temp_perm = ( + list(range(axis % valid_label.ndim)) + + list( + range((axis % valid_label.ndim + 1), valid_label.ndim) + ) + + [axis % valid_label.ndim] + ) + weight_gather = paddle.gather_nd( + weight, paddle.transpose(valid_label, temp_perm) + ) + else: + weight_gather = paddle.gather_nd(weight, valid_label) + weight_gather = paddle.multiply(weight_gather, ignore_weight_mask) + + input_shape = list(label.shape) + weight_gather_reshape = reshape(weight_gather, shape=input_shape) + out = paddle.multiply(out, weight_gather_reshape, name=weight_name) + + if reduction == "sum": + return paddle.sum(out, name=name) + elif reduction == "mean": + if ignore_index >= 0: + out_sum = paddle.sum(out, name=name) + # for each label[i],set 1 or 0, according to ignore_index + # mask[i]=0, if label[i]==ignore_index + # mask[i]=1, otherwise + mask = label != ignore_index + if weight is None: + mask = paddle.cast(mask, dtype=out_sum.dtype) + count = paddle.sum(mask, name=name) + ret = out_sum / (count + (count == 0.0)) + else: + mask = paddle.cast(mask, weight_gather_reshape.dtype) + weight_ignored = paddle.multiply(mask, weight_gather_reshape) + weight_sum = paddle.sum(weight_ignored, name=name) + ret = out_sum / (weight_sum + (weight_sum == 0.0)) + return ret + elif weight is not None: + out_sum = paddle.sum(out, name=name) + total_weight = paddle.sum(weight_gather_reshape) + return out_sum / (total_weight + (total_weight == 0.0)) + else: + return paddle.mean(out, name=name) + + else: + if input_dims - 1 == label_dims: + out = paddle.squeeze(out, axis=axis) + + return out + + +def sigmoid_focal_loss( + logit, + label, + normalizer=None, + alpha=0.25, + gamma=2.0, + reduction='sum', + name=None, +): + r""" + `Focal Loss `_ is proposed to address the + foreground-background class imbalance for classification tasks. It down-weights + easily-classified examples and thus focuses training on hard examples. For example, + it is used in one-stage object detection where the foreground-background class + imbalance is extremely high. + + This operator measures focal loss function as follows: + + .. math:: + Out = -Labels * alpha * {(1 - \sigma(Logit))}^{gamma}\log(\sigma(Logit)) - (1 - Labels) * (1 - alpha) * {\sigma(Logit)}^{gamma}\log(1 - \sigma(Logit)) + + We know that :math:`\sigma(Logit) = \frac{1}{1 + \exp(-Logit)}`. + + Then, if :attr:`normalizer` is not None, this operator divides the + normalizer tensor on the loss `Out`: + + .. math:: + Out = \frac{Out}{normalizer} + + Finally, this operator applies reduce operation on the loss. + If :attr:`reduction` set to ``'none'``, the operator will return the original loss `Out`. + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is :math:`Out = MEAN(Out)`. + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is :math:`Out = SUM(Out)`. + + Note that the target ``label`` is 0 for the negative class and is 1 for the positive class. + + Args: + logit (Tensor): The input logit tensor. The shape is [N, *], where N is batch_size, + `*` means any number of additional dimensions. The ``logit`` is usually the + output of a convolution layer. Available dtype is float32, float64. + label (Tensor): The target label tensor with the same shape as + ``logit``. The target label whose value should be numbers between 0 and 1. + Available dtype is float32, float64. + normalizer (Tensor, optional): The number normalizes the focal loss. It has to be + a 1-D Tensor whose shape is `[1, ]`. The data type is float32, float64. + For object detection task, it is the number of positive samples. + If set to None, the focal loss will not be normalized. Default is None. + alpha(int|float, optional): Hyper-parameter to balance the positive and negative example, + it should be between 0 and 1. Default value is set to 0.25. + gamma(int|float, optional): Hyper-parameter to modulate the easy and hard examples. + Default value is set to 2.0. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'sum'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, if :attr:`reduction` is ``'mean'`` or ``'sum'``, the out shape is :math:`[1]`, otherwise the shape is the same as ``logit``. The same dtype as ``logit`` tensor. + + Examples: + + .. code-block:: python + + import paddle + + logit = paddle.to_tensor([[0.97, 0.91, 0.03], [0.55, 0.43, 0.71]], dtype='float32') + label = paddle.to_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype='float32') + one = paddle.to_tensor([1.], dtype='float32') + fg_label = paddle.greater_equal(label, one) + fg_num = paddle.sum(paddle.cast(fg_label, dtype='float32')) + output = paddle.nn.functional.sigmoid_focal_loss(logit, label, normalizer=fg_num) + print(output) # [0.65782464] + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in sigmoid_focal_loss " + "should be 'sum', 'mean' or 'none', but received %s, which is not allowed." + % reduction + ) + + if normalizer is not None: + check_variable_and_dtype( + normalizer, + 'normalizer', + ['float32', 'float64'], + 'sigmoid_focal_loss', + ) + normalizer_shape = list(normalizer.shape) + normalizer_dims = len(normalizer_shape) + if normalizer_dims > 1: + raise ValueError( + "Expected one dimension of normalizer in sigmoid_focal_loss but got {}.".format( + normalizer_dims + ) + ) + + if in_dygraph_mode(): + place = _current_expected_place() + one = _C_ops.full(logit.shape, float(1.0), logit.dtype, place) + + loss = _C_ops.sigmoid_cross_entropy_with_logits( + logit, label, False, -100 + ) + + pred = _C_ops.sigmoid(logit) + + p_t = _C_ops.add( + _C_ops.multiply(pred, label), + _C_ops.multiply( + _C_ops.subtract(one, pred), _C_ops.subtract(one, label) + ), + ) + + alpha = fluid.dygraph.base.to_variable([alpha], dtype=loss.dtype) + alpha_t = _C_ops.add( + _C_ops.multiply(alpha, label), + _C_ops.multiply( + _C_ops.subtract(one, alpha), _C_ops.subtract(one, label) + ), + ) + loss = _C_ops.multiply(alpha_t, loss) + + gamma = fluid.dygraph.base.to_variable([gamma], dtype=loss.dtype) + gamma_t = _C_ops.pow(_C_ops.subtract(one, p_t), gamma) + loss = _C_ops.multiply(gamma_t, loss) + + if normalizer is not None: + loss = _C_ops.divide(loss, normalizer) + + if reduction == "sum": + return _C_ops.sum(loss, [], None, False) + elif reduction == "mean": + return _C_ops.mean_all(loss) + + return loss + + elif _in_legacy_dygraph(): + one = _varbase_creator(dtype=logit.dtype) + _legacy_C_ops.fill_constant( + one, + 'value', + float(1.0), + 'force_cpu', + False, + 'dtype', + one.dtype, + 'str_value', + '1.0', + 'shape', + logit.shape, + ) + loss = _legacy_C_ops.sigmoid_cross_entropy_with_logits(logit, label) + + pred = _legacy_C_ops.sigmoid(logit) + + p_t = _legacy_C_ops.elementwise_add( + _legacy_C_ops.elementwise_mul(pred, label), + _legacy_C_ops.elementwise_mul( + _legacy_C_ops.elementwise_sub(one, pred), + _legacy_C_ops.elementwise_sub(one, label), + ), + ) + + alpha = fluid.dygraph.base.to_variable([alpha], dtype=loss.dtype) + alpha_t = _legacy_C_ops.elementwise_add( + _legacy_C_ops.elementwise_mul(alpha, label), + _legacy_C_ops.elementwise_mul( + _legacy_C_ops.elementwise_sub(one, alpha), + _legacy_C_ops.elementwise_sub(one, label), + ), + ) + loss = _legacy_C_ops.elementwise_mul(alpha_t, loss) + + gamma = fluid.dygraph.base.to_variable([gamma], dtype=loss.dtype) + gamma_t = _legacy_C_ops.elementwise_pow( + _legacy_C_ops.elementwise_sub(one, p_t), gamma + ) + loss = _legacy_C_ops.elementwise_mul(gamma_t, loss) + + if normalizer is not None: + loss = _legacy_C_ops.elementwise_div(loss, normalizer) + + if reduction == "sum": + return _legacy_C_ops.reduce_sum(loss, 'reduce_all', True) + elif reduction == "mean": + return _legacy_C_ops.mean(loss) + + return loss + + check_variable_and_dtype( + logit, 'logit', ['float32', 'float64'], 'sigmoid_focal_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'sigmoid_focal_loss' + ) + + bce_name = None + if reduction == 'none' and normalizer is None: + bce_name = name + loss = paddle.nn.functional.binary_cross_entropy_with_logits( + logit, label, reduction='none', name=bce_name + ) + + pred = paddle.nn.functional.sigmoid(logit) + p_t = pred * label + (1 - pred) * (1 - label) + + alpha_t = alpha * label + (1 - alpha) * (1 - label) + loss = paddle.multiply(alpha_t, loss) + + gamma_t = paddle.pow((1 - p_t), gamma) + loss = paddle.multiply(gamma_t, loss) + + if normalizer is not None: + normalizer_name = name if reduction == 'none' else None + loss = paddle.divide(loss, normalizer, name=normalizer_name) + + if reduction == 'mean': + loss = paddle.mean(loss, name=name) + elif reduction == 'sum': + loss = paddle.sum(loss, name=name) + + return loss + + +def multi_label_soft_margin_loss( + input, label, weight=None, reduction="mean", name=None +): + r""" + Calculate a multi-class multi-classification + hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) + and output :math:`y` (which is a 2D `Tensor` of target class indices). + For each sample in the mini-batch: + + .. math:: + \text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)} + + where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`, \ + :math:`y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}`, \ + :math:`0 \leq y[j] \leq \text{x.size}(0)-1`, \ + and :math:`i \neq y[j]` for all :math:`i` and :math:`j`. + :math:`y` and :math:`x` must have the same size. + + Parameters: + input (Tensor): Input tensor, the data type is float32 or float64. Shape is (N, C), where C is number of classes, and if shape is more than 2D, this is (N, C, D1, D2,..., Dk), k >= 1. + label (Tensor): Label tensor, the data type is float32 or float64. The shape of label is the same as the shape of input. + weight (Tensor,optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size C and the data type is float32, float64. + Default is ``'None'`` . + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + input: N-D Tensor, the shape is [N, \*], N is batch size and `\*` means number of classes, available dtype is float32, float64. The sum operationoperates over all the elements. + label: N-D Tensor, same shape as the input. + weight:N-D Tensor, the shape is [N,1] + output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the input. + + Returns: + Tensor, The tensor variable storing the multi_label_soft_margin_loss of input and label. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + input = paddle.to_tensor([[1, -2, 3], [0, -1, 2], [1, 0, 1]], dtype=paddle.float32) + # label elements in {1., -1.} + label = paddle.to_tensor([[-1, 1, -1], [1, 1, 1], [1, -1, 1]], dtype=paddle.float32) + loss = F.multi_label_soft_margin_loss(input, label, reduction='none') + print(loss) + # Tensor([3.49625897, 0.71111226, 0.43989015]) + loss = F.multi_label_soft_margin_loss(input, label, reduction='mean') + print(loss) + # Tensor([1.54908717]) + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'multi_label_soft_margin_loss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + + if not (input.shape == label.shape): + raise ValueError( + "The input and label should have same dimension," + "but received {}!={}".format(input.shape, label.shape) + ) + + if not _non_static_mode(): + check_variable_and_dtype( + input, + 'input', + ['float32', 'float64'], + 'multilabel_soft_margin_loss', + ) + check_variable_and_dtype( + label, + 'label', + ['float32', 'float64'], + 'multilabel_soft_margin_loss', + ) + + loss = -( + label * paddle.nn.functional.log_sigmoid(input) + + (1 - label) * paddle.nn.functional.log_sigmoid(-input) + ) + + if weight is not None: + if not _non_static_mode(): + check_variable_and_dtype( + weight, + 'weight', + ['float32', 'float64'], + 'multilabel_soft_margin_loss', + ) + loss = loss * weight + + loss = loss.mean(axis=-1) # only return N loss values + + if reduction == "none": + return loss + elif reduction == "mean": + return paddle.mean(loss) + elif reduction == "sum": + return paddle.sum(loss) + + +def hinge_embedding_loss(input, label, margin=1.0, reduction='mean', name=None): + r""" + Calculates hinge_embedding_loss. Measures the loss given an input tensor :math:`x` and a labels tensor :math:`y`(containing 1 or -1). + This is usually used for measuring whether two inputs are similar or dissimilar, e.g. using the L1 pairwise distance as :math:`x`, + and is typically used for learning nonlinear embeddings or semi-supervised learning. + + The loss function for :math:`n`-th sample in the mini-batch is + + .. math:: + l_n = \begin{cases} + x_n, & \text{if}\; y_n = 1,\\ + \max \{0, \Delta - x_n\}, & \text{if}\; y_n = -1, + \end{cases} + + and the total loss functions is + + .. math:: + \ell(x, y) = \begin{cases} + \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\ + \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.} + \end{cases} + + where :math:`L = \{l_1,\dots,l_N\}^\top`. + + Parameters: + input (Tensor): Input tensor, the data type is float32 or float64. + the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + label (Tensor): Label tensor containing 1 or -1, the data type is float32 or float64. + The shape of label is the same as the shape of input. + margin (float, optional): Specifies the hyperparameter margin to be used. + The value determines how large the input need to be to calculate in + hinge_embedding_loss. When label is -1, Input smaller than margin are minimized with hinge_embedding_loss. + Default = 1.0 + reduction (str, optional): Indicate how to average the loss by batch_size. + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + + input: N-D Tensor, the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. The sum operationoperates over all the elements. + + label: N-D Tensor, same shape as the input. tensor elements should containing 1 or -1, the data type is float32 or float64. + + output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the input. + + Returns: + Tensor. The tensor variable storing the hinge_embedding_loss of input and label. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.to_tensor([[1, -2, 3], [0, -1, 2], [1, 0, 1]], dtype=paddle.float32) + # label elements in {1., -1.} + label = paddle.to_tensor([[-1, 1, -1], [1, 1, 1], [1, -1, 1]], dtype=paddle.float32) + + loss = F.hinge_embedding_loss(input, label, margin=1.0, reduction='none') + print(loss) + # Tensor([[0., -2., 0.], + # [0., -1., 2.], + # [1., 1., 1.]]) + + loss = F.hinge_embedding_loss(input, label, margin=1.0, reduction='mean') + print(loss) + # Tensor([0.22222222]) + """ + + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'hinge_embedding_loss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + + if not _non_static_mode(): + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'hinge_embedding_loss' + ) + check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'hinge_embedding_loss' + ) + + zero_ = paddle.zeros([1], dtype=input.dtype) + loss = paddle.where(label == 1.0, input, zero_) + paddle.where( + label == -1.0, paddle.nn.functional.relu(margin - input), zero_ + ) + + if reduction == 'mean': + return paddle.mean(loss, name=name) + elif reduction == 'sum': + return paddle.sum(loss, name=name) + elif reduction == 'none': + return loss + + +def cosine_embedding_loss( + input1, input2, label, margin=0, reduction='mean', name=None +): + r""" + This operator computes the cosine embedding loss of Tensor ``input1``, ``input2`` and ``label`` as follows. + + If label = 1, then the loss value can be calculated as follow: + + .. math:: + Out = 1 - cos(input1, input2) + + If label = -1, then the loss value can be calculated as follow: + + .. math:: + Out = max(0, cos(input1, input2)) - margin + + The operator cos can be described as follow: + .. math:: + cos(x1, x2) = \frac{x1 \cdot{} x2}{\Vert x1 \Vert_2 * \Vert x2 \Vert_2} + + Parameters: + input1 (Tensor): tensor with shape: [N, M] or [M], 'N' means batch size, 'M' means the length of input array. + Available dtypes are float32, float64. + input2 (Tensor): tensor with shape: [N, M] or [M], 'N' means batch size, 'M' means the length of input array. + Available dtypes are float32, float64. + label (Tensor): tensor with shape: [N] or [1]. The target labels values should be -1 or 1. + Available dtypes are int32, int64, float32, float64. + margin (float, optional): Should be a number from :math:`-1` to :math:`1`, + :math:`0` to :math:`0.5` is suggested. If :attr:`margin` is missing, the + default value is :math:`0`. + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, + ``'mean'``: the sum of the output will be divided by the number of elements in the output + ``'sum'``: the output will be summed. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the cosine embedding Loss of Tensor ``input1`` ``input2`` and ``label``. + If `reduction` is ``'none'``, the shape of output loss is [N], the same as ``input`` . + If `reduction` is ``'mean'`` or ``'sum'``, the shape of output loss is [1]. + + Examples: + .. code-block:: python + + import paddle + + input1 = paddle.to_tensor([[1.6, 1.2, -0.5], [3.2, 2.6, -5.8]], 'float32') + input2 = paddle.to_tensor([[0.5, 0.5, -1.8], [2.3, -1.4, 1.1]], 'float32') + label = paddle.to_tensor([1, -1], 'int64') + + output = paddle.nn.functional.cosine_embedding_loss(input1, input2, label, margin=0.5, reduction='mean') + print(output) # [0.21155193] + + output = paddle.nn.functional.cosine_embedding_loss(input1, input2, label, margin=0.5, reduction='sum') + print(output) # [0.42310387] + + output = paddle.nn.functional.cosine_embedding_loss(input1, input2, label, margin=0.5, reduction='none') + print(output) # [0.42310387, 0. ] + + """ + if len(label.shape) != 1: + raise ValueError( + "1D target tensor expected, multi-target not supported" + ) + + if input1.shape != input2.shape: + raise ValueError( + "the shape of input tensor 1 should be equal to input tensor 2, but found inputs with " + "different sizes" + ) + + if len(input1.shape) > 2: + raise ValueError( + "1D target tensor expects 1D or 2D input tensors, but found inputs with different sizes" + ) + + if input1.dtype not in [paddle.float32, paddle.float64]: + raise ValueError( + "The data type of input Variable must be 'float32' or 'float64'" + ) + if label.dtype not in [ + paddle.int32, + paddle.int64, + paddle.float32, + paddle.float64, + ]: + raise ValueError( + "The data type of label Variable must be 'int32', 'int64', 'float32', 'float64'" + ) + + prod_sum = (input1 * input2).sum(axis=-1) + mag_square1 = paddle.square(input1).sum(axis=-1) + 10e-12 + mag_square2 = paddle.square(input2).sum(axis=-1) + 10e-12 + denom = paddle.sqrt(mag_square1 * mag_square2) + cos = prod_sum / denom + zeros = paddle.zeros_like(cos) + pos = 1 - cos + neg = paddle.clip(cos - margin, min=0) + out_pos = paddle.where(label == 1, pos, zeros) + out_neg = paddle.where(label == -1, neg, zeros) + out = out_pos + out_neg + + if reduction == 'none': + return out + if reduction == 'mean': + return paddle.mean(out, name=name) + elif reduction == 'sum': + return paddle.sum(out, name=name) + + +def triplet_margin_with_distance_loss( + input, + positive, + negative, + distance_function=None, + margin=1.0, + swap=False, + reduction='mean', + name=None, +): + r""" + Measures the triplet loss given an input + tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`. + This is used for measuring a relative similarity between samples. A triplet + is composed by `input`, `positive` and `negative` (i.e., `input`, `positive examples` and `negative + examples` respectively). The shapes of all input tensors should be + :math:`(N, D)`. + + The loss function for each sample in the mini-batch is: + + .. math:: + L(input, pos, neg) = \max \{d(input_i, pos_i) - d(input_i, neg_i) + {\rm margin}, 0\} + + + where the default distance function + + .. math:: + d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p + + or user can defined their own distance functions. `margin` is a nonnegative margin representing the minimum difference + between the positive and negative distances that is required for the loss to be 0. If `swap` is true, it will compare distance of (input, negative) with + distance of (negative, positive) and change it to the smaller one. For more details see http://www.bmva.org/bmvc/2016/papers/paper119/paper119.pdf. + + Parameters: + + input (Tensor):Input tensor, the data type is float32 or float64. + the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + + positive (Tensor):Positive tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + negative (Tensor):Negative tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + distance_function (callable, optional): Quantifies the distance between two tensors. if not specified, 2 norm functions will be used. + + margin (float, optional):Default: :math:`1`.A nonnegative margin representing the minimum difference + between the positive and negative distances required for the loss to be 0. + + swap (bool, optional):The distance swap changes the negative distance to the swap distance (distance between positive samples + and negative samples) if swap distance smaller than negative distance. Default: ``False``. + + reduction (str, optional):Indicate how to average the loss by batch_size. + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Output: Tensor. The tensor variable storing the triplet_margin_with_distance_loss of input and positive and negative. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.to_tensor([[1, 5, 3], [0, 3, 2], [1, 4, 1]], dtype=paddle.float32) + positive= paddle.to_tensor([[5, 1, 2], [3, 2, 1], [3, -1, 1]], dtype=paddle.float32) + negative = paddle.to_tensor([[2, 1, -3], [1, 1, -1], [4, -2, 1]], dtype=paddle.float32) + loss = F.triplet_margin_with_distance_loss(input, positive, negative, margin=1.0, reduction='none') + print(loss) + # Tensor([0. , 0.57496738, 0. ]) + + + loss = F.triplet_margin_with_distance_loss(input, positive, negative, margin=1.0, reduction='mean') + print(loss) + # Tensor([0.19165580]) + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'triplet_margin_with_distance_loss' " + "should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + if margin < 0: + raise ValueError( + "The margin between positive samples and negative samples should be greater than 0." + ) + if not _non_static_mode(): + check_variable_and_dtype( + input, + 'input', + ['float32', 'float64'], + 'triplet_margin_with_distance_loss', + ) + check_variable_and_dtype( + positive, + 'positive', + ['float32', 'float64'], + 'triplet_margin_with_distance_loss', + ) + check_variable_and_dtype( + negative, + 'negative', + ['float32', 'float64'], + 'triplet_margin_with_distance_loss', + ) + + if not (input.shape == positive.shape == negative.shape): + raise ValueError( + "input's shape must equal to " + "positive's shape and " + "negative's shape" + ) + + distance_function = ( + distance_function + if distance_function is not None + else paddle.nn.PairwiseDistance(2) + ) + + positive_dist = distance_function(input, positive) + negative_dist = distance_function(input, negative) + + if swap: + swap_dist = distance_function(positive, negative) + negative_dist = paddle.minimum(negative_dist, swap_dist) + + if not paddle.all(positive_dist > 0) or not paddle.all(negative_dist > 0): + raise ValueError( + "The positive distance or negative distance should be greater than 0, " + "The distance functions should be checked." + ) + + loss = paddle.clip(positive_dist - negative_dist + margin, min=0.0) + + if reduction == 'mean': + return paddle.mean(loss, name=name) + elif reduction == 'sum': + return paddle.sum(loss, name=name) + elif reduction == 'none': + return loss + + +def triplet_margin_loss( + input, + positive, + negative, + margin=1.0, + p=2, + epsilon=1e-6, + swap=False, + reduction='mean', + name=None, +): + r""" + Measures the triplet loss given an input + tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`. + This is used for measuring a relative similarity between samples. A triplet + is composed by `input`, `positive` and `negative` (i.e., `input`, `positive examples` and `negative + examples` respectively). The shapes of all input tensors should be + :math:`(N, *)`. + + The loss function for each sample in the mini-batch is: + + .. math:: + L(input, pos, neg) = \max \{d(input_i, pos_i) - d(input_i, neg_i) + {\rm margin}, 0\} + + + where + + .. math:: + d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p + + Parameters: + input (Tensor): Input tensor, the data type is float32 or float64. + the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + + positive (Tensor): Positive tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + negative (Tensor): Negative tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + margin (float, Optional): Default: :math:`1`. + + p (int, Optional): The norm degree for pairwise distance. Default: :math:`2`. + + epsilon (float, Optional): Add small value to avoid division by zero, + default value is 1e-6. + + swap (bool,Optional): The distance swap change the negative distance to the distance between + positive sample and negative sample. For more details, see `Learning shallow convolutional feature descriptors with triplet losses`. + Default: ``False``. + + + reduction (str, Optional):Indicate how to average the loss by batch_size. + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + + name (str, Optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Output: Tensor. The tensor variable storing the triplet_margin_loss of input and positive and negative. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + input = paddle.to_tensor([[1, 5, 3], [0, 3, 2], [1, 4, 1]], dtype=paddle.float32) + positive= paddle.to_tensor([[5, 1, 2], [3, 2, 1], [3, -1, 1]], dtype=paddle.float32) + negative = paddle.to_tensor([[2, 1, -3], [1, 1, -1], [4, -2, 1]], dtype=paddle.float32) + loss = F.triplet_margin_loss(input, positive, negative, margin=1.0, reduction='none') + print(loss) + # Tensor([0. , 0.57496738, 0. ]) + + + loss = F.triplet_margin_loss(input, positive, negative, margin=1.0, reduction='mean') + print(loss) + # Tensor([0.19165580]) + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'triplet_margin_loss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + if margin < 0: + raise ValueError( + "The margin between positive samples and negative samples should be greater than 0." + ) + if not _non_static_mode(): + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'triplet_margin_loss' + ) + check_variable_and_dtype( + positive, 'positive', ['float32', 'float64'], 'triplet_margin_loss' + ) + check_variable_and_dtype( + negative, 'negative', ['float32', 'float64'], 'triplet_margin_loss' + ) + + if not (input.shape == positive.shape == negative.shape): + raise ValueError( + "input's shape must equal to " + "positive's shape and " + "negative's shape" + ) + + distance_function = paddle.nn.PairwiseDistance(p, epsilon=epsilon) + positive_dist = distance_function(input, positive) + negative_dist = distance_function(input, negative) + + if swap: + swap_dist = distance_function(positive, negative) + negative_dist = paddle.minimum(negative_dist, swap_dist) + + loss = paddle.clip(positive_dist - negative_dist + margin, min=0.0) + + if reduction == 'mean': + return paddle.mean(loss, name=name) + elif reduction == 'sum': + return paddle.sum(loss, name=name) + elif reduction == 'none': + return loss + + +def soft_margin_loss(input, label, reduction='mean', name=None): + """ + + The API measures the soft margin loss between input predictions ``input`` + and target labels ``label`` . It can be described as: + + .. math:: + Out = log(1 + exp((-label * input))) + + Parameters: + + input (Tensor): The input predications tensor with shape: ``[N, *]``, + N is batch_size, `*` means any number of additional dimensions. The ``input`` ranges from -inf to inf. + Available dtype is float32, float64. + + label (Tensor): The target labels tensor with the same shape as + ``input``. The target labels which values should be numbers -1 or 1. + Available dtype is int32, int64, float32, float64. + + reduction (str, optional): Indicate how to average the loss by batch_size, + the candidates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + + Output (Tensor): If ``reduction`` is ``'none'``, the shape of output is same as ``input`` , else the shape of output is [1]. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[0.5, 0.6, 0.7],[0.3, 0.5, 0.2]], 'float32') + label = paddle.to_tensor([[1.0, -1.0, 1.0],[-1.0, 1.0, 1.0]], 'float32') + output = paddle.nn.functional.soft_margin_loss(input, label) + print(output) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.64022040]) + + input = paddle.uniform(shape=(5, 5), dtype="float32", min=0.1, max=0.8) + label = paddle.randint(0, 2, shape=(5, 5), dtype="int64") + label[label==0]=-1 + + output = paddle.nn.functional.soft_margin_loss(input, label, reduction='none') + print(output) + # Tensor(shape=[5, 5], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1.09917796, 0.52613139, 0.56263304, 0.82736146, 0.38776723], + # [1.07179427, 1.11924267, 0.49877715, 1.10026348, 0.46184641], + # [0.84367639, 0.74795729, 0.44629076, 0.55123353, 0.77659678], + # [0.39465919, 0.76651484, 0.54485321, 0.76609844, 0.77166790], + # [0.51283568, 0.84757161, 0.78913331, 1.05268764, 0.45318675]]) + + """ + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in soft_margin_loss should be 'sum', " + "'mean' or 'none', but received %s, which is not allowed." + % reduction + ) + + if not _non_static_mode(): + fluid.data_feeder.check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'soft_margin_loss' + ) + fluid.data_feeder.check_variable_and_dtype( + label, + 'label', + ['int32', 'int64', 'float32', 'float64'], + 'soft_margin_loss', + ) + + if not (input.shape == label.shape): + raise ValueError("input's shape must equal to " "label's shape") + + label = fluid.layers.cast(label, input.dtype) + out = paddle.log(1 + paddle.exp(-label * input)) + + if reduction == 'sum': + return paddle.sum(out, name=name) + elif reduction == 'mean': + return paddle.mean(out, name=name) + else: + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/norm.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5829ea0dbdea7e4b243cced47c987c103ff902 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/norm.py @@ -0,0 +1,667 @@ +# 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. + +# TODO: define normalization api +import paddle +import paddle.fluid as fluid +from ...fluid.data_feeder import check_variable_and_dtype, check_type +from ...fluid.layer_helper import LayerHelper +from ...framework import create_parameter +from ..initializer import Constant +from ...framework import ParamAttr +from ...fluid import dygraph_utils +import numbers +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from paddle.fluid.framework import ( + core, + _non_static_mode, + in_dygraph_mode, + _in_legacy_dygraph, +) + +__all__ = [] + + +def normalize(x, p=2, axis=1, epsilon=1e-12, name=None): + r""" + Normalize ``x`` along dimension ``axis`` using :math:`L_p` norm. This layer computes + + .. math:: + + y = \frac{x}{ \max\left( \lvert \lvert x \rvert \rvert_p, epsilon\right) } + + .. math:: + \lvert \lvert x \rvert \rvert_p = \left( \sum_i {\lvert x_i \rvert^p} \right)^{1/p} + + where, :math:`\sum_i{\lvert x_i \rvert^p}` is calculated along the ``axis`` dimension. + + + Parameters: + x (Tensor): The input tensor could be N-D tensor, and the input data type could be float32 or float64. + p (float|int, optional): The exponent value in the norm formulation. Default: 2. + axis (int, optional): The axis on which to apply normalization. If `axis < 0`, the dimension to normalization is `x.ndim + axis`. -1 is the last dimension. + epsilon (float, optional): Small float added to denominator to avoid dividing by zero. Default is 1e-12. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the output has the same shape and data type with ``x``. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + paddle.disable_static() + x = paddle.arange(6, dtype="float32").reshape([2,3]) + y = F.normalize(x) + print(y) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0. , 0.44721359, 0.89442718], + # [0.42426404, 0.56568539, 0.70710671]]) + + y = F.normalize(x, p=1.5) + print(y) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0. , 0.40862012, 0.81724024], + # [0.35684016, 0.47578689, 0.59473360]]) + + y = F.normalize(x, axis=0) + print(y) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0. , 0.24253564, 0.37139067], + # [1. , 0.97014254, 0.92847669]]) + """ + if in_dygraph_mode(): + eps = fluid.dygraph.base.to_variable([epsilon], dtype=x.dtype) + out = _C_ops.p_norm(x, float(p), axis, epsilon, True, False) + return x / _C_ops.maximum(out, eps) + + if _in_legacy_dygraph(): + eps = fluid.dygraph.base.to_variable([epsilon], dtype=x.dtype) + out = _legacy_C_ops.p_norm( + x, + 'axis', + axis, + 'porder', + float(p), + 'keepdim', + True, + 'epsilon', + epsilon, + ) + return x / _legacy_C_ops.elementwise_max(out, eps) + + check_type(p, 'p', (float, int), 'normalize') + check_type(axis, 'axis', (int), 'normalize') + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'normalize' + ) + if len(x.shape) == 1 and axis != 0 and axis != -1: + raise ValueError( + "Axis must be 0 or -1 when x is a 1-D tensor, but received axis = {}".format( + axis + ) + ) + + attrs = { + 'axis': axis, + 'porder': float(p), + 'keepdim': True, + 'epsilon': epsilon, + } + helper = LayerHelper('p_norm', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='p_norm', inputs={'X': x}, outputs={'Out': out}, attrs=attrs + ) + eps = out.block.create_var(dtype=out.dtype) + eps = paddle.full(shape=[1], fill_value=epsilon, dtype=out.dtype) + return paddle.divide(x, paddle.maximum(out, eps), name=name) + + +def batch_norm( + x, + running_mean, + running_var, + weight, + bias, + training=False, + momentum=0.9, + epsilon=1e-05, + data_format="NCHW", + use_global_stats=None, + name=None, +): + """ + Applies Batch Normalization as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . + + nn.functional.batch_norm is uesd for nn.BatchNorm1D, nn.BatchNorm2D, nn.BatchNorm3D. Please use above API for BatchNorm. + + Parameters: + x(Tesnor): input value. It's data type should be float32, float64. + running_mean(Tensor): running mean. + running_var(Tensor): running variance. + weight(Tensor): The weight tensor of batch_norm, can not be None. + bias(Tensor): The bias tensor of batch_norm can not be None. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + training(bool, optional): True means train mode which compute by batch data and track global mean and var during train period. False means inference mode which compute by global mean and var which calculated by train period. Default False. + data_format(str, optional): Specify the input data format, may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default "NCHW". + use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None. + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(12, dtype="float32").reshape([2, 1, 2, 3]) + print(x) + # Tensor(shape=[2, 1, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[0. , 1. , 2. ], + # [3. , 4. , 5. ]]], + + # [[[6. , 7. , 8. ], + # [9. , 10., 11.]]]]) + + running_mean = paddle.to_tensor([0], dtype="float32") + running_variance = paddle.to_tensor([1], dtype="float32") + weight = paddle.to_tensor([2], dtype="float32") + bias = paddle.to_tensor([1], dtype="float32") + + batch_norm_out = paddle.nn.functional.batch_norm(x, running_mean, + running_variance, weight, bias) + print(batch_norm_out) + # Tensor(shape=[2, 1, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[1. , 2.99998999 , 4.99997997 ], + # [6.99996948 , 8.99995995 , 10.99994946]]], + + # [[[12.99993896, 14.99992943, 16.99991989], + # [18.99990845, 20.99989891, 22.99988937]]]]) + """ + assert len(x.shape) >= 2, "input dim must be larger than 1" + + # input ad out must share the memory + mean_out = running_mean + variance_out = running_var + + true_data_format = ['NC', 'NCL', 'NCHW', 'NCDHW', 'NLC', 'NHWC', 'NDHWC'] + if data_format not in true_data_format: + raise ValueError( + "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', " + "'NLC', 'NHWC', 'NDHWC' but receive {}".format(data_format) + ) + + data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC' + + if use_global_stats == None: + use_global_stats = not training + trainable_statistics = False + else: + trainable_statistics = not use_global_stats + + if in_dygraph_mode(): + batch_norm_out, _, _, _, _, _ = _C_ops.batch_norm( + x, + weight, + bias, + running_mean, + running_var, + momentum, + epsilon, + data_format, + not training, + use_global_stats, + trainable_statistics, + False, + ) + + return dygraph_utils._append_activation_in_dygraph( + batch_norm_out, act=None + ) + + elif _in_legacy_dygraph(): + # for dygraph need tuple + attrs = ( + "momentum", + momentum, + "epsilon", + epsilon, + "is_test", + not training, + "data_layout", + data_format, + "use_mkldnn", + False, + "fuse_with_relu", + False, + "use_global_stats", + use_global_stats, + "trainable_statistics", + trainable_statistics, + ) + + batch_norm_out, _, _, _, _, _ = _legacy_C_ops.batch_norm( + x, + weight, + bias, + running_mean, + running_var, + None, + mean_out, + variance_out, + *attrs + ) + + return dygraph_utils._append_activation_in_dygraph( + batch_norm_out, act=None + ) + + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], 'BatchNorm' + ) + + # for static need dict + attrs = { + "momentum": momentum, + "epsilon": epsilon, + "is_test": not training, + "data_layout": data_format, + "use_mkldnn": False, + "fuse_with_relu": False, + "use_global_stats": use_global_stats, + "trainable_statistics": trainable_statistics, + } + + inputs = { + "X": [x], + "Scale": [weight], + "Bias": [bias], + "Mean": [running_mean], + "Variance": [running_var], + } + + helper = LayerHelper('batch_norm', **locals()) + + param_dtype = x.dtype if x.dtype != 'float16' else 'float32' + saved_mean = helper.create_variable_for_type_inference( + dtype=param_dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=param_dtype, stop_gradient=True + ) + batch_norm_out = helper.create_variable_for_type_inference(x.dtype) + + outputs = { + "Y": [batch_norm_out], + "MeanOut": [running_mean], + "VarianceOut": [running_var], + "SavedMean": [saved_mean], + "SavedVariance": [saved_variance], + } + + if training or trainable_statistics: + # reserve_space is only used for training. + reserve_space = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + outputs["ReserveSpace"] = [reserve_space] + + helper.append_op( + type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs + ) + + return helper.append_activation(batch_norm_out) + + +def layer_norm( + x, normalized_shape, weight=None, bias=None, epsilon=1e-05, name=None +): + """ + see more detail in paddle.nn.LayerNorm + + Parameters: + x(Tensor): Input Tensor. It's data type should be float32, float64. + normalized_shape(int|list|tuple): Input shape from an expected input of + size :math:`[*, normalized_shape[0], normalized_shape[1], ..., normalized_shape[-1]]`. + If it is a single integer, this module will normalize over the last dimension + which is expected to be of that specific size. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + weight(Tensor, optional): The weight tensor of batch_norm. Default: None. + bias(Tensor, optional): The bias tensor of batch_norm. Default: None. + name(str, optional): Name for the LayerNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 2, 3)) + layer_norm_out = paddle.nn.functional.layer_norm(x, x.shape[1:]) + print(layer_norm_out) + """ + input_shape = list(x.shape) + input_ndim = len(input_shape) + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = [normalized_shape] + elif isinstance(normalized_shape, tuple): + normalized_shape = list(normalized_shape) + elif not isinstance(normalized_shape, list): + raise ValueError( + "`normalized_shape` should be int, list of ints or tuple of ints." + ) + + normalized_ndim = len(normalized_shape) + begin_norm_axis = input_ndim - normalized_ndim + if ( + input_ndim < normalized_ndim + or input_shape[begin_norm_axis:] != normalized_shape + ): + str_normalized_shape = str(normalized_shape) + raise ValueError( + 'Given normalized_shape is ' + + str_normalized_shape + + ', expected input with shape [*, ' + + str_normalized_shape[1:] + + ', but got input shape ' + + str(input_shape) + ) + + if in_dygraph_mode(): + ( + pre_act, + _, + _, + ) = _C_ops.layer_norm(x, weight, bias, epsilon, begin_norm_axis, False) + + return dygraph_utils._append_activation_in_dygraph(pre_act, act=None) + + if _in_legacy_dygraph(): + pre_act, _, _ = _legacy_C_ops.layer_norm( + x, + weight, + bias, + 'epsilon', + epsilon, + 'begin_norm_axis', + begin_norm_axis, + ) + return dygraph_utils._append_activation_in_dygraph(pre_act, act=None) + + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], 'LayerNorm' + ) + + inputs = dict() + inputs['X'] = [x] + if weight: + inputs['Scale'] = [weight] + if bias: + inputs['Bias'] = [bias] + attrs = {"epsilon": epsilon, "begin_norm_axis": begin_norm_axis} + + # create output + helper = LayerHelper('layer_norm', **locals()) + + dtype = x.dtype + mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + layer_norm_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type="layer_norm", + inputs=inputs, + outputs={ + "Y": layer_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={"epsilon": epsilon, "begin_norm_axis": begin_norm_axis}, + ) + + return helper.append_activation(layer_norm_out) + + +def instance_norm( + x, + running_mean=None, + running_var=None, + weight=None, + bias=None, + use_input_stats=True, + momentum=0.9, + eps=1e-05, + data_format="NCHW", + name=None, +): + """ + See more detail in nn.layer.InstanceNorm2D. + + Parameters: + x(Tensor): Input Tensor. It's data type should be float32, float64. + running_mean(Tensor, optional): running mean. Default None. + running_var(Tensor, optional): running variance. Default None. + weight(Tensor, optional): The weight tensor of instance_norm. Default: None. + bias(Tensor, optional): The bias tensor of instance_norm. Default: None. + eps(float, optional): A value added to the denominator for numerical stability. Default is 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + use_input_stats(bool, optional): Default True. + data_format(str, optional): Specify the input data format, may be "NC", "NCL", "NCHW" or "NCDHW". Defalut "NCHW". + name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Returns: + None. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 2, 3)) + instance_norm_out = paddle.nn.functional.instance_norm(x) + + print(instance_norm_out) + + """ + if in_dygraph_mode(): + out = _C_ops.instance_norm(x, weight, bias, eps) + return out + if _in_legacy_dygraph(): + out, _, _ = _legacy_C_ops.instance_norm( + x, + weight, + bias, + "epsilon", + eps, + "momentum", + momentum, + "data_format", + data_format, + ) + return out + + check_variable_and_dtype(x, 'input', ['float32', 'float64'], "InstanceNorm") + + attrs = {"epsilon": eps, "momentum": momentum, "data_format": data_format} + + if weight and bias: + inputs = {"X": [x], "Scale": [weight], "Bias": [bias]} + else: + inputs = {"X": [x]} + + helper = LayerHelper('instance_norm', **locals()) + saved_mean = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + instance_norm_out = helper.create_variable_for_type_inference(x.dtype) + + outputs = { + "Y": [instance_norm_out], + "SavedMean": [saved_mean], + "SavedVariance": [saved_variance], + } + + helper.append_op( + type="instance_norm", inputs=inputs, outputs=outputs, attrs=attrs + ) + return instance_norm_out + + +def local_response_norm( + x, size, alpha=1e-4, beta=0.75, k=1.0, data_format="NCHW", name=None +): + r""" + Local Response Normalization performs a type of "lateral inhibition" by normalizing over local input regions. + For more information, please refer to `ImageNet Classification with Deep Convolutional Neural Networks `_ + + The formula is as follows: + + .. math:: + + Output(i, x, y) = Input(i, x, y) / \left(k + \alpha \sum\limits^{\min(C-1, i + size/2)}_{j = \max(0, i - size/2)}(Input(j, x, y))^2\right)^{\beta} + + In the above equation: + + - :math:`size` : The number of channels to sum over. + - :math:`k` : The offset (avoid being divided by 0). + - :math:`\\alpha` : The scaling parameter. + - :math:`\\beta` : The exponent parameter. + + + Args: + x (Tensor): The input 3-D/4-D/5-D tensor. The data type is float32. + size (int): The number of channels to sum over. + alpha (float, optional): The scaling parameter, positive. Default:1e-4 + beta (float, optional): The exponent, positive. Default:0.75 + k (float, optional): An offset, positive. Default: 1.0 + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: + If x is 3-D Tensor, the string could be `"NCL"` or `"NLC"` . When it is `"NCL"`, + the data is stored in the order of: `[batch_size, input_channels, feature_length]`. + If x is 4-D Tensor, the string could be `"NCHW"`, `"NHWC"`. When it is `"NCHW"`, + the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. + If x is 5-D Tensor, the string could be `"NCDHW"`, `"NDHWC"` . When it is `"NCDHW"`, + the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name (str, optional): Name for the operation (optional, default is None). For more information, + please refer to :ref:`api_guide_Name`. + + Returns: + A tensor storing the transformation result with the same shape and data type as input. + + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand(shape=(3, 3, 112, 112), dtype="float32") + y = paddle.nn.functional.local_response_norm(x, size=5) + print(y.shape) # [3, 3, 112, 112] + """ + if not in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32'], 'local_response_norm') + if data_format not in ['NCL', 'NLC', 'NCHW', 'NHWC', 'NCDHW', 'NDHWC']: + raise ValueError( + "data_format should be in one of [NCL, NCHW, NCDHW, NLC, NHWC, NDHWC], " + "but got {}".format(data_format) + ) + + sizes = x.shape + dim = len(sizes) + if dim < 3: + raise ValueError( + 'Expected 3D or higher dimensionality input, but got {} dimensions'.format( + dim + ) + ) + + for i, sz in enumerate(sizes): + if not sz > 0 and i > 0: + raise ValueError( + "Expected every dim's size to be larger than 0, " + "but the size of the {}-th dim is {}".format(i, sz) + ) + + channel_last = True if data_format[-1] == "C" else False + + from functools import reduce + + sum_sizes = reduce(lambda x, y: x * y, sizes[1:]) + + div = paddle.unsqueeze(paddle.multiply(x, x), axis=1) + if not channel_last: + pad4d_shape = [0, 0, size // 2, (size - 1) // 2] + pool2d_shape = (size, 1) + reshape_shape = [ + sizes[0], + 1, + sizes[1], + sizes[2], + int(sum_sizes / (sizes[1] * sizes[2])), + ] + pad5d_shape = [0, 0, 0, 0, size // 2, (size - 1) // 2] + pool3d_shape = (size, 1, 1) + else: + pad4d_shape = [size // 2, (size - 1) // 2, 0, 0] + pool2d_shape = (1, size) + reshape_shape = [ + sizes[0], + 1, + sizes[1], + int(sum_sizes / (sizes[1] * sizes[-1])), + sizes[-1], + ] + pad5d_shape = [size // 2, (size - 1) // 2, 0, 0, 0, 0] + pool3d_shape = (1, 1, size) + + if dim == 3: + div = paddle.nn.functional.pad(div, pad=pad4d_shape) + div = paddle.nn.functional.avg_pool2d( + div, kernel_size=pool2d_shape, stride=1 + ) + div = paddle.squeeze(div, axis=1) + else: + div = paddle.reshape(div, shape=reshape_shape) + div = paddle.nn.functional.pad( + div, pad=pad5d_shape, data_format='NCDHW' + ) + div = paddle.nn.functional.avg_pool3d( + div, kernel_size=pool3d_shape, stride=1 + ) + div = paddle.reshape(paddle.squeeze(div, axis=1), sizes) + + div = paddle.scale(div, scale=alpha, bias=k) + div = paddle.pow(div, beta) + res = paddle.divide(x, div, name=name) + return res diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/pooling.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..388ab4c6944cc01c80c2e4ca8988573b57dc31b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/pooling.py @@ -0,0 +1,2317 @@ +# 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. + +# TODO: define pooling functions +from ...fluid.layers import utils, LayerHelper +from ...tensor.manipulation import unsqueeze, squeeze +from ...fluid.data_feeder import check_type, check_variable_and_dtype +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from paddle.fluid import core +from paddle.fluid.framework import _in_legacy_dygraph, Variable +from paddle.fluid.framework import in_dygraph_mode, _non_static_mode + +__all__ = [] + + +def _is_list_or_tuple(input): + return isinstance(input, (list, tuple)) + + +def _check_input(x, dimension): + if len(x.shape) != dimension: + raise ValueError( + "Excepted Input X is {}-D tensor, but received {}-D {}".format( + dimension, len(x.shape), type(x) + ) + ) + + +def _check_instance(x, x_name, types=(int, float)): + + if not isinstance(x, types): + raise ValueError( + "Excepted {} type for {} but received type: {}. ".format( + types, x_name, type(x) + ) + ) + + +def _check_value_limitation(x, x_name, min_limit=1e-3): + def _check_value(x, x_name, min_limit=1e-3): + if isinstance(x, int) and min_limit is not None and x < min_limit: + raise ValueError( + "Excepted the input {} to be greater than {} but received x: {}. ".format( + x_name, min_limit, x + ) + ) + + for ele in x: + _check_value(ele, x_name) + + +def _zero_padding_in_batch_and_channel(padding, channel_last): + if channel_last: + return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0] + else: + return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0] + + +def _exclude_padding_in_batch_and_channel(padding, channel_last): + padding_ = padding[1:-1] if channel_last else padding[2:] + padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim] + return padding_ + + +def _channel_last(data_format, num_dims): + if num_dims == 1: + if data_format not in ['NCL', 'NLC']: + raise ValueError( + "Attr(data_format) should be 'NCL' or 'NLC'. Received " + "Attr(data_format): %s" % str(data_format) + ) + else: + return True if data_format == "NLC" else False + if num_dims == 2: + if data_format not in ['NCHW', 'NHWC']: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s" % str(data_format) + ) + else: + return True if data_format == "NHWC" else False + if num_dims == 3: + if data_format not in ['NCDHW', 'NDHWC']: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): %s" % str(data_format) + ) + else: + return True if data_format == "NDHWC" else False + + +def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False): + if isinstance(padding, str): + padding = padding.upper() + if padding not in ["SAME", "VALID"]: + raise ValueError( + "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.".format( + padding + ) + ) + if padding == "VALID": + if ceil_mode != False: + raise ValueError( + "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. " + "Received ceil_mode: True." + ) + + padding_algorithm = "VALID" + padding = [0] * num_dims + else: + padding_algorithm = "SAME" + padding = [0] * num_dims + elif _is_list_or_tuple(padding): + # for padding like + # [(pad_before, pad_after), (pad_before, pad_after), ...] + # padding for batch_dim and channel_dim included + if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]): + if not _zero_padding_in_batch_and_channel(padding, channel_last): + raise ValueError( + "Non-zero padding({}) in the batch or channel dimensions " + "is not supported.".format(padding) + ) + padding_algorithm = "EXPLICIT" + padding = _exclude_padding_in_batch_and_channel( + padding, channel_last + ) + if utils._is_symmetric_padding(padding, num_dims): + padding = padding[0::2] + # for padding like [pad_before, pad_after, pad_before, pad_after, ...] + elif len(padding) == 2 * num_dims and isinstance(padding[0], int): + padding_algorithm = "EXPLICIT" + padding = utils.convert_to_list(padding, 2 * num_dims, 'padding') + if utils._is_symmetric_padding(padding, num_dims): + padding = padding[0::2] + # for padding like [pad_d1, pad_d2, ...] + elif len(padding) == num_dims and isinstance(padding[0], int): + padding_algorithm = "EXPLICIT" + padding = utils.convert_to_list(padding, num_dims, 'padding') + else: + raise ValueError("Invalid padding: {}".format(padding)) + # for integer padding + else: + padding_algorithm = "EXPLICIT" + padding = utils.convert_to_list(padding, num_dims, 'padding') + return padding, padding_algorithm + + +def _expand_low_nd_padding(padding): + # 1d to 2d fake input + if len(padding) == 2: + padding = [0] * 2 + padding + elif len(padding) == 1: + padding = [0] + padding + else: + raise ValueError( + "The size of padding's dimmention should be 1 or 2. But got padding={}".format( + padding + ) + ) + return padding + + +def avg_pool1d( + x, + kernel_size, + stride=None, + padding=0, + exclusive=True, + ceil_mode=False, + name=None, +): + """ + This API implements average pooling 1d operation, + See more details in :ref:`api_nn_pooling_AvgPool1d` . + + Args: + x (Tensor): The input tensor of pooling operator which is a 3-D tensor with + shape [N, C, L]. where `N` is batch size, `C` is the number of channels, + `L` is the length of the feature. The data type is float32 or float64. + kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain an integer. + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. + 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + exclusive (bool): Whether to exclude padding points in average pooling + mode, default is `True`. + ceil_mode (bool): ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width. + If it is set to False, the floor function will be used. The default value is False. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + data = paddle.uniform([1, 3, 32], paddle.float32) + AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0) + pool_out = AvgPool1D(data) + # pool_out shape: [1, 3, 16] + """ + """NCL to NCHW""" + data_format = "NCHW" + if not in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool1d') + _check_input(x, 3) + x = unsqueeze(x, [2]) + kernel_size = utils.convert_to_list(kernel_size, 1, 'kernel_size') + kernel_size = [1] + kernel_size + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 1, 'pool_stride') + stride = [1] + stride + + _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3) + _check_value_limitation(stride, "stride", min_limit=1e-3) + + channel_last = _channel_last("NCL", 1) + padding, padding_algorithm = _update_padding_nd( + padding, 1, channel_last=channel_last, ceil_mode=ceil_mode + ) + + # use 2d to implenment 1d should expand padding in advance. + padding = _expand_low_nd_padding(padding) + + if in_dygraph_mode(): + output = _C_ops.pool2d( + x, + kernel_size, + stride, + padding, + ceil_mode, + exclusive, + data_format, + 'avg', + False, + False, + padding_algorithm, + True, + ) + return squeeze(output, [2]) + + if _in_legacy_dygraph(): + output = _legacy_C_ops.pool2d( + x, + 'pooling_type', + 'avg', + 'ksize', + kernel_size, + 'global_pooling', + False, + 'strides', + stride, + 'paddings', + padding, + 'padding_algorithm', + padding_algorithm, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + exclusive, + 'data_format', + data_format, + ) + return squeeze(output, [2]) + + op_type = 'pool2d' + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs={"Out": pool_out}, + attrs={ + "pooling_type": 'avg', + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": exclusive, + "data_format": data_format, + }, + ) + + return squeeze(pool_out, [2]) + + +def avg_pool2d( + x, + kernel_size, + stride=None, + padding=0, + ceil_mode=False, + exclusive=True, + divisor_override=None, + data_format="NCHW", + name=None, +): + """ + This API implements average pooling 2d operation. + See more details in :ref:`api_nn_pooling_AvgPool2d` . + + Args: + x (Tensor): The input tensor of pooling operator which is a 4-D tensor with + shape [N, C, H, W]. The format of input tensor is `"NCHW"` or + `"NHWC"`, where `N` is batch size, `C` is the number of channels, + `H` is the height of the feature, and `W` is the width of the + feature. The data type if float32 or float64. + kernel_size (int|list|tuple): The pool kernel size. If it is a tuple or list, + it must contain two integers, (kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be a square of an int. + stride (int|list|tuple): The stride size. If it is a tuple or list, + it must contain two integers, (stride_Height, stride_Width). + Otherwise, the stride size will be a square of an int. + + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape + exclusive (bool): Whether to exclude padding points in average pooling + mode, default is `true`. + divisor_override (float): if specified, it will be used as divisor, otherwise kernel_size will be used. Default None. + data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # avg pool2d + x = paddle.uniform([1, 3, 32, 32], paddle.float32) + out = F.avg_pool2d(x, + kernel_size=2, + stride=2, padding=0) + # out.shape [1, 3, 16, 16] + """ + kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 2, 'pool_stride') + + _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3) + _check_value_limitation(stride, "stride", min_limit=1e-3) + + channel_last = _channel_last(data_format, 2) + padding, padding_algorithm = _update_padding_nd( + padding, 2, channel_last, ceil_mode=ceil_mode + ) + + if _non_static_mode(): + if in_dygraph_mode(): + output = _C_ops.pool2d( + x, + kernel_size, + stride, + padding, + ceil_mode, + exclusive, + data_format, + 'avg', + False, + False, + padding_algorithm, + True, + ) + else: + output = _legacy_C_ops.pool2d( + x, + 'pooling_type', + 'avg', + 'ksize', + kernel_size, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'strides', + stride, + 'paddings', + padding, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + exclusive, + 'data_format', + data_format, + ) + if divisor_override is None: + return output + else: + _check_instance(divisor_override, "divisor_override") + return output * (kernel_size[0] * kernel_size[1]) / divisor_override + + op_type = 'pool2d' + helper = LayerHelper(op_type, **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool2d') + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs={"Out": pool_out}, + attrs={ + "pooling_type": "avg", + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": exclusive, + "data_format": data_format, + }, + ) + + if divisor_override is None: + return pool_out + else: + _check_instance(divisor_override, "divisor_override") + return pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override + + +def avg_pool3d( + x, + kernel_size, + stride=None, + padding=0, + ceil_mode=False, + exclusive=True, + divisor_override=None, + data_format="NCDHW", + name=None, +): + """ + This API implements average pooling 3d operation. + See more details in :ref:`api_nn_pooling_AvgPool3d` . + + Args: + x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with + shape [N, C, D, H, W], where `N` represents the batch size, `C` represents + the number of channels, `D`, `H` and `W` represent the depth, height and width of the feature respectively. + kernel_size (int|list|tuple): The pool kernel size. If pool kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode (bool): ${ceil_mode_comment} + exclusive (bool): Whether to exclude padding points in average pooling + mode, default is True. + divisor_override (int|float) if specified, it will be used as divisor, otherwise kernel_size will be used. Default None. + data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.uniform([1, 3, 32, 32, 32], paddle.float32) + # avg pool3d + out = paddle.nn.functional.avg_pool3d( + x, + kernel_size = 2, + stride = 2, + padding=0) + # out.shape: [1, 3, 16, 16, 16] + """ + kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 3, 'pool_stride') + + channel_last = _channel_last(data_format, 3) + padding, padding_algorithm = _update_padding_nd( + padding, 3, channel_last=channel_last, ceil_mode=ceil_mode + ) + + _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3) + _check_value_limitation(stride, "stride", min_limit=1e-3) + + if in_dygraph_mode(): + pool_out = _C_ops.pool3d( + x, + kernel_size, + stride, + padding, + ceil_mode, + exclusive, + data_format, + 'avg', + False, + False, + padding_algorithm, + True, + ) + elif _in_legacy_dygraph(): + pool_out = _legacy_C_ops.pool3d( + x, + 'pooling_type', + 'avg', + 'ksize', + kernel_size, + 'strides', + stride, + 'paddings', + padding, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + exclusive, + 'data_format', + data_format, + ) + else: + op_type = "pool3d" + helper = LayerHelper(op_type, **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + outputs = {"Out": pool_out} + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'avg', + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": exclusive, + "data_format": data_format, + }, + ) + + if divisor_override is None: + return pool_out + else: + _check_instance(divisor_override, "divisor_override") + return ( + pool_out + * (kernel_size[0] * kernel_size[1] * kernel_size[2]) + / divisor_override + ) + + +def max_pool1d( + x, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + name=None, +): + """ + This API implements max pooling 1d opereation. + See more details in :ref:`api_nn_pooling_MaxPool1d` . + + Args: + x (Tensor): The input tensor of pooling operator which is a 3-D tensor with + shape [N, C, L], where `N` is batch size, `C` is the number of channels, + `L` is the length of the feature. The data type if float32 or float64. + kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain an integer. + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An integer, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. + 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + return_mask (bool): Whether return the max indices along with the outputs. default is `False`. + ceil_mode (bool): Whether to use the ceil function to calculate output height and width. False is the default. + If it is set to False, the floor function will be used. Default False. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.uniform([1, 3, 32], paddle.float32) + pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0) + # pool_out shape: [1, 3, 16] + pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16] + """ + """NCL to NCHW""" + data_format = "NCHW" + if not in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d') + _check_input(x, 3) + x = unsqueeze(x, [2]) + kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride') + + padding, padding_algorithm = _update_padding_nd( + padding, 1, ceil_mode=ceil_mode + ) + + # use 2d to implenment 1d should expand padding in advance. + padding = _expand_low_nd_padding(padding) + + if in_dygraph_mode(): + if return_mask: + pool_out = _C_ops.max_pool2d_with_index( + x, kernel_size, stride, padding, False, False + ) + return ( + (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) + if return_mask + else squeeze(pool_out[0], [2]) + ) + else: + pool_out = _C_ops.pool2d( + x, + kernel_size, + stride, + padding, + ceil_mode, + True, + data_format, + 'max', + False, + False, + padding_algorithm, + True, + ) + return squeeze(pool_out, [2]) + + if _in_legacy_dygraph(): + if return_mask: + pool_out = _legacy_C_ops.max_pool2d_with_index( + x, + 'ksize', + kernel_size, + 'global_pooling', + False, + 'strides', + stride, + 'paddings', + padding, + 'padding_algorithm', + padding_algorithm, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return ( + (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) + if return_mask + else squeeze(pool_out[0], [2]) + ) + else: + pool_out = _legacy_C_ops.pool2d( + x, + 'pooling_type', + 'max', + 'ksize', + kernel_size, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'strides', + stride, + 'paddings', + padding, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return squeeze(pool_out, [2]) + + op_type = 'max_pool2d_with_index' if return_mask else "pool2d" + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + mask = helper.create_variable_for_type_inference('int32') + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'max', + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": True, + "data_format": data_format, + }, + ) + + return ( + (squeeze(pool_out, [2]), squeeze(mask, [2])) + if return_mask + else squeeze(pool_out, [2]) + ) + + +def _unpool_output_size(x, kernel_size, stride, padding, output_size): + assert output_size is None or isinstance(output_size, (list, tuple)), ( + "Required output_size is None|list|tuple, but received %s" % output_size + ) + input_size = x.shape + default_size = [] + for d in range(len(kernel_size)): + default_size.append( + (input_size[-len(kernel_size) + d] - 1) * stride[d] + + kernel_size[d] + - 2 * padding[d] + ) + + has_static_var = False + if output_size is None: + return default_size + elif utils._contain_var(output_size): + if not _non_static_mode(): + has_static_var = True + output_size = utils._convert_to_tensor_list(output_size) + else: + for i, var in enumerate(output_size): + if isinstance(var, Variable): + output_size[i] = var.numpy()[0] + + if len(output_size) == len(kernel_size) + 2: + output_size = output_size[2:] + if len(output_size) != len(kernel_size): + raise ValueError( + "output_size should be a sequence containing " + "{} or {} elements, but it has a length of '{}'".format( + len(kernel_size), len(kernel_size) + 2, len(output_size) + ) + ) + if not has_static_var: + for d in range(len(kernel_size)): + min_size = default_size[d] - stride[d] + max_size = default_size[d] + stride[d] + if not (min_size < output_size[d] < max_size): + raise ValueError( + 'invalid output_size "{}" (dim {} must be between {} and {})'.format( + output_size, d, min_size, max_size + ) + ) + + return output_size + + +def max_unpool1d( + x, + indices, + kernel_size, + stride=None, + padding=0, + data_format="NCL", + output_size=None, + name=None, +): + r""" + This API implements max unpooling 1d opereation. + `max_unpool1d` accepts the output of `max_pool1d` as input, + including the indices of the maximum value and calculate the partial inverse. + All non-maximum values ​​are set to zero. + + - Input: :math:`(N, C, L_{in})` + - Output: :math:`(N, C, L_{out})`, where + + .. math:: + L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size + + or as given by :attr:`output_size` in the call operator. + + + Args: + x (Tensor): The input tensor of unpooling operator which is a 3-D tensor with + shape [N, C, L]. The format of input tensor is `"NCL"`, + where `N` is batch size, `C` is the number of channels, `L` is + the length of the feature. The data type is float32 or float64. + indices (Tensor): The indices given out by maxpooling1d which is a 3-D tensor with + shape [N, C, L]. The format of input tensor is `"NCL"` , + where `N` is batch size, `C` is the number of channels, `L` is + the length of the featuree. The data type is float32 or float64. + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, stride, padding). + data_format (string): The data format of the input and output data. + The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of: + `[batch_size, input_channels, input_length]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of unpooling result. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1, 3, 16]) + pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 3, 8], indices shape: [1, 3, 8] + unpool_out = F.max_unpool1d(pool_out, indices, kernel_size=2, padding=0) + # unpool_out shape: [1, 3, 16] + + """ + """NCL to NCHW""" + if data_format not in ["NCL"]: + raise ValueError( + "Attr(data_format) should be 'NCL'. Received " + "Attr(data_format): %s." % str(data_format) + ) + data_format = "NCHW" + x = unsqueeze(x, [2]) + indices = unsqueeze(indices, [2]) + kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride') + padding, padding_algorithm = _update_padding_nd(padding, 1) + # use 2d to implenment 1d should expand padding in advance. + padding = _expand_low_nd_padding(padding) + + output_size = _unpool_output_size( + x, kernel_size, stride, padding, output_size + ) + + if in_dygraph_mode(): + output = _C_ops.unpool( + x, indices, kernel_size, stride, padding, output_size, data_format + ) + return squeeze(output, [2]) + elif in_dynamic_mode(): + output = _legacy_C_ops.unpool( + x, + indices, + 'unpooling_type', + 'max', + 'ksize', + kernel_size, + 'strides', + stride, + 'paddings', + padding, + "output_size", + output_size, + "data_format", + data_format, + ) + return squeeze(output, [2]) + + op_type = "unpool" + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name="x") + unpool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": x, "Indices": indices}, + outputs={"Out": unpool_out}, + attrs={ + "unpooling_type": "max", + "ksize": kernel_size, + "strides": stride, + "paddings": padding, + "output_size": output_size, + }, + ) + return squeeze(unpool_out, [2]) + + +def max_unpool2d( + x, + indices, + kernel_size, + stride=None, + padding=0, + data_format="NCHW", + output_size=None, + name=None, +): + r""" + This API implements max unpooling 2d opereation. + See more details in :ref:`api_nn_pooling_MaxUnPool2D` . + + + Args: + x (Tensor): The input tensor of unpooling operator which is a 4-D tensor with + shape [N, C, H, W]. The format of input tensor is `"NCHW"`, + where `N` is batch size, `C` is the number of channels, + `H` is the height of the feature, and `W` is the width of the + feature. The data type if float32 or float64. + indices (Tensor): The indices given out by maxpooling2d which is a 4-D tensor with + shape [N, C, H, W]. The format of input tensor is `"NCHW"` , + where `N` is batch size, `C` is the number of channels, + `H` is the height of the feature, and `W` is the width of the + feature. The data type if float32 or float64. + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, padding). + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + + - Input: :math:`(N, C, H_{in}, W_{in})` + - Output: :math:`(N, C, H_{out}, W_{out})`, where + + .. math:: + H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]} + + .. math:: + W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]} + + or as given by :attr:`output_size` in the call operator + + Returns: + Tensor: The output tensor of unpooling result. + + Raises: + ValueError: If the input is not a 4-D tensor. + ValueError: If indeces shape is not equal input shape. + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1,1,6,6]) + pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 1, 3, 3], indices shape: [1, 1, 3, 3] + unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0) + # unpool_out shape: [1, 1, 6, 6] + + # specify a different output size than input size + unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0, output_size=[7,7]) + # unpool_out shape: [1, 1, 7, 7] + + """ + kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 2, 'pool_stride') + padding = utils.convert_to_list(padding, 2, 'padding') + + if data_format not in ["NCHW"]: + raise ValueError( + "Attr(data_format) should be 'NCHW'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + output_size = _unpool_output_size( + x, kernel_size, stride, padding, output_size + ) + + if in_dygraph_mode(): + output = _C_ops.unpool( + x, indices, kernel_size, stride, padding, output_size, data_format + ) + return output + elif in_dynamic_mode(): + output = _legacy_C_ops.unpool( + x, + indices, + 'unpooling_type', + 'max', + 'ksize', + kernel_size, + 'strides', + stride, + 'paddings', + padding, + "output_size", + output_size, + "data_format", + data_format, + ) + return output + + op_type = "unpool" + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name="x") + unpool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": x, "Indices": indices}, + outputs={"Out": unpool_out}, + attrs={ + "unpooling_type": "max", + "ksize": kernel_size, + "strides": stride, + "paddings": padding, + "output_size": output_size, + }, + ) + return unpool_out + + +def max_unpool3d( + x, + indices, + kernel_size, + stride=None, + padding=0, + data_format="NCDHW", + output_size=None, + name=None, +): + r""" + This API implements max unpooling 3d opereation. + `max_unpool3d` accepts the output of `max_pool3d` as input, + including the indices of the maximum value and calculate the partial inverse. + All non-maximum values ​​are set to zero. + + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where + + .. math:: + D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0] + + .. math:: + H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1] + + .. math:: + W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2] + + or as given by :attr:`output_size` in the call operator + + + Args: + x (Tensor): The input tensor of unpooling operator which is a 5-D tensor with + shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`, + where `N` is batch size, `C` is the number of channels, `D` is + the depth of the feature, `H` is the height of the feature, + and `W` is the width of the feature. The data type is float32 or float64. + indices (Tensor): The indices given out by maxpooling3d which is a 5-D tensor with + shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` , + where `N` is batch size, `C` is the number of channels, `D` is + the depth of the feature, `H` is the height of the feature, + and `W` is the width of the feature. The data type is float32 or float64. + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, stride, padding). + data_format (string): The data format of the input and output data. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of unpooling result. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1, 1, 4, 4, 6]) + pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 1, 2, 2, 3], indices shape: [1, 1, 2, 2, 3] + unpool_out = F.max_unpool3d(pool_out, indices, kernel_size=2, padding=0) + # unpool_out shape: [1, 1, 4, 4, 6] + + """ + kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 3, 'pool_stride') + padding = utils.convert_to_list(padding, 3, 'padding') + + if data_format not in ["NCDHW"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + output_size = _unpool_output_size( + x, kernel_size, stride, padding, output_size + ) + + if in_dygraph_mode(): + output = _C_ops.unpool3d( + x, indices, kernel_size, stride, padding, output_size, data_format + ) + return output + elif in_dynamic_mode(): + output = _legacy_C_ops.unpool3d( + x, + indices, + 'unpooling_type', + 'max', + 'ksize', + kernel_size, + 'strides', + stride, + 'paddings', + padding, + "output_size", + output_size, + "data_format", + data_format, + ) + return output + + op_type = "unpool3d" + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name="x") + unpool_out = helper.create_variable_for_type_inference(dtype) + + helper.append_op( + type=op_type, + inputs={"X": x, "Indices": indices}, + outputs={"Out": unpool_out}, + attrs={ + "unpooling_type": "max", + "ksize": kernel_size, + "strides": stride, + "paddings": padding, + "output_size": output_size, + }, + ) + return unpool_out + + +def max_pool2d( + x, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + data_format="NCHW", + name=None, +): + """ + This API implements max pooling 2d operation. + See more details in :ref:`api_nn_pooling_MaxPool2d` . + + Args: + x (Tensor): The input tensor of pooling operator which is a 4-D tensor with + shape [N, C, H, W]. The format of input tensor is `"NCHW"` or + `"NHWC"`, where `N` is batch size, `C` is the number of channels, + `H` is the height of the feature, and `W` is the width of the + feature. The data type if float32 or float64. + kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be a square of an int. + stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain two integers, (stride_Height, stride_Width). + Otherwise, the pool stride size will be a square of an int. + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape + return_mask (bool): Whether to return the max indices along with the outputs. Default False, only support `"NCHW"` data format + data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # max pool2d + x = paddle.uniform([1, 3, 32, 32], paddle.float32) + out = F.max_pool2d(x, kernel_size=2, stride=2, padding=0) + # output.shape [1, 3, 16, 16] + # for return_mask=True + out, max_indices = F.max_pool2d(x, kernel_size=2, stride=2, padding=0, return_mask=True) + # out.shape [1, 3, 16, 16], max_indices.shape [1, 3, 16, 16], + """ + + kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 2, 'pool_stride') + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + channel_last = True if data_format == "NHWC" else False + + padding, padding_algorithm = _update_padding_nd( + padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode + ) + + if data_format == "NHWC" and return_mask: + raise ValueError( + "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d" + ) + + if in_dygraph_mode(): + if return_mask: + output = _C_ops.max_pool2d_with_index( + x, kernel_size, stride, padding, False, False + ) + return output if return_mask else output[0] + else: + return _C_ops.pool2d( + x, + kernel_size, + stride, + padding, + ceil_mode, + True, + data_format, + 'max', + False, + False, + padding_algorithm, + True, + ) + + if _in_legacy_dygraph(): + if return_mask: + output = _legacy_C_ops.max_pool2d_with_index( + x, + 'ksize', + kernel_size, + 'global_pooling', + False, + 'strides', + stride, + 'paddings', + padding, + 'padding_algorithm', + padding_algorithm, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return output if return_mask else output[0] + else: + output = _legacy_C_ops.pool2d( + x, + 'pooling_type', + 'max', + 'ksize', + kernel_size, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'strides', + stride, + 'paddings', + padding, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return output + + op_type = 'max_pool2d_with_index' if return_mask else "pool2d" + helper = LayerHelper(op_type, **locals()) + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'max_pool2d' + ) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + mask = helper.create_variable_for_type_inference("int32") + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'max', + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": True, + "data_format": data_format, + }, + ) + + return (pool_out, mask) if return_mask else pool_out + + +def max_pool3d( + x, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + data_format="NCDHW", + name=None, +): + """ + This API implements max pooling 2d operation. + See more details in :ref:`api_nn_pooling_MaxPool3d` . + + Args: + x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with + shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` or `"NDHWC"`, where N represents batch size, C represents the number of channels, D, H and W represent the depth, height and width of the feature respectively. + kernel_size (int|list|tuple): The pool kernel size. If the kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode (bool): ${ceil_mode_comment} + return_mask (bool): Whether to return the max indices along with the outputs. Default False. Only support "NDCHW" data_format. + data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # max pool3d + x = paddle.uniform([1, 3, 32, 32, 32]) + output = F.max_pool3d(x, + kernel_size=2, + stride=2, padding=0) + # output.shape [1, 3, 16, 16, 16] + # for return_mask=True + x = paddle.uniform([1, 3, 32, 32, 32]) + output, max_indices = paddle.nn.functional.max_pool3d(x, + kernel_size=2, + stride=2, + padding=0, + return_mask=True) + + # output.shape [1, 3, 16, 16, 16], max_indices.shape [1, 3, 16, 16, 16] + """ + + kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 3, 'pool_stride') + + channel_last = _channel_last(data_format, 3) + + padding, padding_algorithm = _update_padding_nd( + padding, 3, channel_last=channel_last, ceil_mode=ceil_mode + ) + + if data_format == "NDHWC" and return_mask: + raise ValueError( + "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d" + ) + + if in_dygraph_mode(): + if return_mask: + output = _C_ops.max_pool3d_with_index( + x, kernel_size, stride, padding, False, False + ) + return output if return_mask else output[0] + else: + return _C_ops.pool3d( + x, + kernel_size, + stride, + padding, + ceil_mode, + True, + data_format, + 'max', + False, + False, + padding_algorithm, + True, + ) + + if _in_legacy_dygraph(): + if return_mask: + output = _legacy_C_ops.max_pool3d_with_index( + x, + 'pooling_type', + 'max', + 'ksize', + kernel_size, + 'strides', + stride, + 'paddings', + padding, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return output if return_mask else output[0] + else: + output = _legacy_C_ops.pool3d( + x, + 'pooling_type', + 'max', + 'ksize', + kernel_size, + 'global_pooling', + False, + 'padding_algorithm', + padding_algorithm, + 'strides', + stride, + 'paddings', + padding, + 'use_cudnn', + True, + 'ceil_mode', + ceil_mode, + 'use_mkldnn', + False, + 'exclusive', + True, + 'data_format', + data_format, + ) + return output + + op_type = "max_pool3d_with_index" if return_mask else "pool3d" + helper = LayerHelper(op_type, **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + mask = helper.create_variable_for_type_inference('int32') + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=op_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'max', + "ksize": kernel_size, + "global_pooling": False, + "strides": stride, + "paddings": padding, + "padding_algorithm": padding_algorithm, + "use_cudnn": True, + "ceil_mode": ceil_mode, + "use_mkldnn": False, + "exclusive": False, + "data_format": data_format, + }, + ) + + return (pool_out, mask) if return_mask else pool_out + + +def adaptive_avg_pool1d(x, output_size, name=None): + """ + Adaptive average pooling 1d operation on :attr:`x` according to :attr:`output_size`. + + Notes: + See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` . + + Args: + x (Tensor): The input Tensor of pooling, which is a 3-D tensor with shape :math:`[N, C, L]`, where :math:`N` is batch size, :math:`C` is the number of channels and :math:`L` is the length of the feature. The data type is float32 or float64. + output_size (int): The target output size. Its data type must be int. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: The result of 1D adaptive average pooling. Its data type is same as input. + + Examples: + .. code-block:: python + + # average adaptive pool1d + # suppose input data in shape of [N, C, L], `output_size` is m or [m], + # output shape is [N, C, m], adaptive pool divide L dimension + # of input data into m grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # lstart = floor(i * L / m) + # lend = ceil((i + 1) * L / m) + # output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend) + # + import paddle + import paddle.nn.functional as F + + data = paddle.uniform([1, 3, 32]) + pool_out = F.adaptive_avg_pool1d(data, output_size=16) + # pool_out shape: [1, 3, 16]) + """ + pool_type = 'avg' + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'adaptive_pool2d' + ) + check_type(output_size, 'pool_size', (int), 'adaptive_pool1d') + _check_input(x, 3) + pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') + + x = unsqueeze(x, [2]) + if in_dygraph_mode(): + pool_out = _C_ops.pool2d( + x, + pool_size, + [1, 1], + [0, 0], + False, + True, + "NCHW", + pool_type, + False, + True, + "EXPLICIT", + False, + ) + return squeeze(pool_out, [2]) + if _in_legacy_dygraph(): + pool_out = _legacy_C_ops.pool2d( + x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True + ) + return squeeze(pool_out, [2]) + + l_type = "pool2d" + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + outputs = {"Out": pool_out} + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "adaptive": True, + }, + ) + + return squeeze(pool_out, [2]) + + +def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None): + r""" + + Applies 2D adaptive avg pooling on input tensor. The h and w dimensions + of the output tensor are determined by the parameter output_size. + + For avg adaptive pool2d: + + .. math:: + hstart &= floor(i * H_{in} / H_{out}) \\ + hend &= ceil((i + 1) * H_{in} / H_{out}) \\ + wstart &= floor(j * W_{in} / W_{out}) \\ + wend &= ceil((j + 1) * W_{in} / W_{out}) \\ + Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)} + + Args: + x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor. + The data type can be float32 or float64. + output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two element, (H, W). H and W can be either a int, or None which means + the size will be the same as that of the input. + data_format (str, optional): The data format of the input and output data. An optional string + from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in + the order of: [batch_size, input_channels, input_height, input_width]. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor, The output tensor of avg adaptive pool2d result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + # adaptive avg pool2d + # suppose input data in shape of [N, C, H, W], `output_size` is [m, n], + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive avg pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + + x = paddle.rand([2, 3, 32, 32]) + # x.shape is [2, 3, 32, 32] + out = paddle.nn.functional.adaptive_avg_pool2d( + x = x, + output_size=[3, 3]) + # out.shape is [2, 3, 3, 3] + + """ + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d' + ) + check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d') + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + if data_format == "NCHW": + in_h, in_w = x.shape[2:4] + else: + in_h, in_w = x.shape[1:3] + + if isinstance(output_size, int): + output_size = utils.convert_to_list(output_size, 2, 'output_size') + else: + output_size = list(output_size) + if output_size[0] is None: + output_size[0] = in_h + if output_size[1] is None: + output_size[1] = in_w + + if _non_static_mode(): + output_size = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in output_size + ] + # output_size support Variable in static mode + elif utils._contain_var(output_size): + output_size = utils._convert_to_tensor_list(output_size) + + if in_dygraph_mode(): + return _C_ops.pool2d( + x, + output_size, + [1, 1], + [0, 0], + False, + True, + data_format, + 'avg', + False, + True, + "EXPLICIT", + False, + ) + + if _in_legacy_dygraph(): + return _legacy_C_ops.pool2d( + x, + 'pooling_type', + 'avg', + 'ksize', + output_size, + 'global_pooling', + False, + 'adaptive', + True, + 'data_format', + data_format, + ) + + l_type = 'pool2d' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + outputs = {"Out": pool_out} + + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": "avg", + "ksize": output_size, + "adaptive": True, + "data_format": data_format, + }, + ) + + return pool_out + + +def adaptive_avg_pool3d(x, output_size, data_format='NCDHW', name=None): + r""" + + This operation applies 3D adaptive avg pooling on input tensor. The h and w dimensions + of the output tensor are determined by the parameter output_size. + + For avg adaptive pool3d: + + .. math:: + dstart &= floor(i * D_{in} / D_{out}) \\ + dend &= ceil((i + 1) * D_{in} / D_{out}) \\ + hstart &= floor(j * H_{in} / H_{out}) \\ + hend &= ceil((j + 1) * H_{in} / H_{out}) \\ + wstart &= floor(k * W_{in} / W_{out}) \\ + wend &= ceil((k + 1) * W_{in} / W_{out}) \\ + Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]} + {(dend - dstart) * (hend - hstart) * (wend - wstart)} + + Args: + x (Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor. + The data type can be float32, float64. + output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or + list, it must contain three elements, (D, H, W). D, H and W can be either a int, + or None which means the size will be the same as that of the input. + data_format (str, optional): The data format of the input and output data. An optional string + from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in + the order of: [batch_size, input_channels, input_depth, input_height, input_width]. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + Returns: + Tensor, The output tensor of avg adaptive pool3d result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + # adaptive avg pool3d + # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n], + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into l * m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive avg pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(j * H / m) + # hend = ceil((j + 1) * H / m) + # wstart = floor(k * W / n) + # wend = ceil((k + 1) * W / n) + # output[:, :, i, j, k] = + # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) + import paddle + + input_data = paddle.randn(shape=(2, 3, 8, 32, 32)) + out = paddle.nn.functional.adaptive_avg_pool3d( + x = input_data, + output_size=[3, 3, 3]) + # out.shape is [2, 3, 3, 3, 3] + + """ + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float32', 'float64'], 'adaptive_avg_pool3d' + ) + check_type(data_format, 'data_format', str, 'adaptive_avg_pool3d') + + if data_format not in ["NCDHW", "NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " + "Attr(data_format): %s." % str(data_format) + ) + + if data_format == "NCDHW": + in_l, in_h, in_w = x.shape[2:5] + else: + in_l, in_h, in_w = x.shape[1:4] + + if isinstance(output_size, int): + output_size = utils.convert_to_list(output_size, 3, 'output_size') + else: + output_size = list(output_size) + if output_size[0] is None: + output_size[0] = in_l + if output_size[1] is None: + output_size[1] = in_h + if output_size[2] is None: + output_size[2] = in_w + + if in_dygraph_mode(): + return _C_ops.pool3d( + x, + output_size, + [1, 1, 1], + [0, 0, 0], + False, + True, + data_format, + 'avg', + False, + True, + "EXPLICIT", + False, + ) + elif _in_legacy_dygraph(): + return _legacy_C_ops.pool3d( + x, + 'pooling_type', + 'avg', + 'ksize', + output_size, + 'global_pooling', + False, + 'adaptive', + True, + 'data_format', + data_format, + ) + + l_type = 'pool3d' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + outputs = {"Out": pool_out} + + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": "avg", + "ksize": output_size, + "adaptive": True, + "data_format": data_format, + }, + ) + + return pool_out + + +def adaptive_max_pool1d(x, output_size, return_mask=False, name=None): + """ + This API implements adaptive max pooling 1d operation. + See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` . + + Args: + x (Tensor): The input tensor of pooling operator, which is a 3-D tensor + with shape [N, C, L]. The format of input tensor is NCL, + where N is batch size, C is the number of channels, L is the + length of the feature. The data type is float32 or float64. + output_size (int): The pool kernel size. The value should be an integer. + return_mask (bool): If true, the index of max pooling point will be returned along + with outputs. It cannot be set in average pooling type. Default False. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + Returns: + Tensor: The output tensor of adaptive pooling result. The data type is same + as input tensor. + + Examples: + .. code-block:: python + + # max adaptive pool1d + # suppose input data in shape of [N, C, L], `output_size` is m or [m], + # output shape is [N, C, m], adaptive pool divide L dimension + # of input data into m grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # lstart = floor(i * L / m) + # lend = ceil((i + 1) * L / m) + # output[:, :, i] = max(input[:, :, lstart: lend]) + # + import paddle + import paddle.nn.functional as F + + data = paddle.uniform([1, 3, 32], paddle.float32) + pool_out = F.adaptive_max_pool1d(data, output_size=16) + # pool_out shape: [1, 3, 16]) + pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True) + # pool_out shape: [1, 3, 16] indices shape: [1, 3, 16] + """ + pool_type = 'max' + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d' + ) + check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d') + check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d') + _check_input(x, 3) + + pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') + + x = unsqueeze(x, [2]) + if in_dygraph_mode(): + pool_out = _C_ops.max_pool2d_with_index( + x, pool_size, [1, 1], [0, 0], False, True + ) + return ( + (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) + if return_mask + else squeeze(pool_out[0], [2]) + ) + if _in_legacy_dygraph(): + pool_out = _legacy_C_ops.max_pool2d_with_index( + x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True + ) + return ( + (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) + if return_mask + else squeeze(pool_out[0], [2]) + ) + + l_type = 'max_pool2d_with_index' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + mask = helper.create_variable_for_type_inference('int32') + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": pool_type, + "ksize": pool_size, + "adaptive": True, + }, + ) + + return ( + (squeeze(pool_out, [2]), squeeze(mask, [2])) + if return_mask + else squeeze(pool_out, [2]) + ) + + +def adaptive_max_pool2d(x, output_size, return_mask=False, name=None): + """ + This operation applies a 2D adaptive max pooling on input tensor. + See more details in :ref:`api_nn_pooling_AdaptiveMaxPool2d` . + + Args: + x (Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor. The data type can be float16, float32, float64, int32 or int64. + output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two elements, (H, W). H and W can be either a int, or None which means the size will be the same as that of the input. + return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. + + Returns: + Tensor: The output tensor of adaptive max pool2d result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + # max adaptive pool2d + # suppose input data in the shape of [N, C, H, W], `output_size` is [m, n] + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m*n grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + + input_data = paddle.randn(shape=(2, 3, 32, 32)) + out = paddle.nn.functional.adaptive_max_pool2d( + x = input_data, + output_size=[3, 3]) + # out.shape is [2, 3, 3, 3] + """ + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d' + ) + check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d') + # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d') + _check_input(x, 4) + + in_h, in_w = x.shape[2:4] + if isinstance(output_size, int): + output_size = utils.convert_to_list(output_size, 2, 'output_size') + else: + output_size = list(output_size) + if output_size[0] == None: + output_size[0] = in_h + if output_size[1] == None: + output_size[1] = in_w + if in_dygraph_mode(): + pool_out = _C_ops.max_pool2d_with_index( + x, output_size, [1, 1], [0, 0], False, True + ) + return pool_out if return_mask else pool_out[0] + if _in_legacy_dygraph(): + pool_out = _legacy_C_ops.max_pool2d_with_index( + x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True + ) + return pool_out if return_mask else pool_out[0] + + l_type = 'max_pool2d_with_index' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + mask = helper.create_variable_for_type_inference('int32') + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'max', + "ksize": output_size, + "adaptive": True, + }, + ) + # return (pool_out, mask) if return_mask else pool_out + return pool_out + + +def adaptive_max_pool3d(x, output_size, return_mask=False, name=None): + """ + This operation applies a 3D adaptive max pooling on input tensor. + See more details in :ref:`api_nn_pooling_AdaptiveMaxPool3d` . + + Args: + x (Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor. The data type can be float32, float64. + output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of the input. + return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. + + Returns: + Tensor: The output tensor of adaptive max pool3d result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + # adaptive max pool3d + # suppose input data in the shape of [N, C, D, H, W], `output_size` is [l, m, n] + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into m*n grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j, k] = max(input[:, :, dstart: dend, hstart: hend, wstart: wend]) + # + import paddle + + input_data = paddle.randn(shape=(2, 3, 8, 32, 32)) + out = paddle.nn.functional.adaptive_max_pool3d( + x = input_data, + output_size=[3, 3, 3]) + # out.shape is [2, 3, 3, 3, 3] + """ + + if not in_dynamic_mode(): + check_variable_and_dtype( + x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d' + ) + check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d') + # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d') + _check_input(x, 5) + + in_l, in_h, in_w = x.shape[2:5] + if isinstance(output_size, int): + output_size = utils.convert_to_list(output_size, 3, 'output_size') + else: + output_size = list(output_size) + if output_size[0] == None: + output_size[0] = in_l + if output_size[1] == None: + output_size[1] = in_h + if output_size[2] == None: + output_size[2] = in_w + + if in_dynamic_mode(): + if in_dygraph_mode(): + # By default, strides is [1,1,1] and paddings is [0, 0, 0] + pool_out = _C_ops.max_pool3d_with_index( + x, output_size, [1, 1, 1], [0, 0, 0], False, True + ) + elif _in_legacy_dygraph(): + pool_out = _legacy_C_ops.max_pool3d_with_index( + x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True + ) + return pool_out if return_mask else pool_out[0] + + l_type = 'max_pool3d_with_index' + + helper = LayerHelper(l_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + pool_out = helper.create_variable_for_type_inference(dtype) + + mask = helper.create_variable_for_type_inference('int32') + outputs = {"Out": pool_out, "Mask": mask} + + helper.append_op( + type=l_type, + inputs={"X": x}, + outputs=outputs, + attrs={ + "pooling_type": 'max', + "ksize": output_size, + "adaptive": True, + }, + ) + + return (pool_out, mask) if return_mask else pool_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/sparse_attention.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/sparse_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f6c8464ead515acaed48be4a507dd41a61b72c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/sparse_attention.py @@ -0,0 +1,176 @@ +# Copyright (c) 2021 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. + +import warnings +import paddle +from ...fluid.framework import default_main_program +from paddle.fluid.layer_helper import LayerHelper +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode + + +def sparse_attention( + query, + key, + value, + sparse_csr_offset, + sparse_csr_columns, + key_padding_mask=None, + attn_mask=None, + name=None, +): + r""" + This operator sparsify the Attention matrix in Transformer module + to achieve the effect of reducing memory consumption and computation. + The sparse layout is expressed in CSR format and contains two parameters, + ``offset`` and ``columns``. The equation is: + + .. math:: + + result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V + + where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module. + The dimensions of the three parameters are the same. + ``d`` represents the size of the last dimension of the three parameters. + + Warning: + This API is only used in ``CUDA 11.3`` and above versions. + + Args: + query(Tensor): The query tensor in the Attention module. + 4-D tensor with shape: + [batch_size, num_heads, seq_len, head_dim]. + The dtype can be float32 and float64. + key(Tensor): The key tensor in the Attention module. + 4-D tensor with shape: + [batch_size, num_heads, seq_len, head_dim]. + The dtype can be float32 and float64. + value(Tensor): The value tensor in the Attention module. + 4-D tensor with shape: + [batch_size, num_heads, seq_len, head_dim]. + The dtype can be float32 and float64. + sparse_csr_offset(Tensor): The sparsity feature in the Attention module + is expressed in the CSR format, and the offset represents + the number of non-zero elements in each row of the matrix. + 3-D tensor with shape: + [batch_size, num_heads, seq_len + 1]. + The dtype should be int32. + sparse_csr_columns(Tensor): The sparsity feature in the Attention module + is expressed in the CSR format, and the columns represent + the column index values of non-zero elements in the matrix. + 3-D tensor with shape: + [batch_size, num_heads, sparse_nnz]. + The dtype should be int32. + key_padding_mask(Tensor, optional):The key padding mask tensor in the Attention module. + 2-D tensor with shape: [batch_size, seq_len]. + The dtype can be float32 and float64. + A value of 0 means that the position is masked. + attn_mask(Tensor, optional):The attention mask tensor in the Attention module. + 2-D tensor with shape: [seq_len, seq_len]. + The dtype can be float32 and float64. + A value of 0 means that the position is masked. + name(str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name`. + + Returns: + 4-D tensor with shape: + [batch_size, num_heads, seq_len, head_dim]. + The dtype can be float32 or float64. + + Examples: + .. code-block:: python + + # required: skiptest + import paddle + + paddle.disable_static() + + # `query`, `key` and `value` all have shape [1, 1, 4, 2] + query = paddle.to_tensor([[[[0, 1, ], [2, 3], + [0, 1], [2, 3]]]], dtype="float32") + key = paddle.to_tensor([[[[0, 1], [2, 3], + [0, 1], [2, 3]]]], dtype="float32") + value = paddle.to_tensor([[[[0, 1], [2, 3], + [0, 1], [2, 3]]]], dtype="float32") + + + offset = paddle.to_tensor([[[0, 2, 4, 6, 8]]], dtype="int32") + columns = paddle.to_tensor([[[0, 1, 0, 1, 2, 3, 2, 3]]], dtype="int32") + + print(offset.shape) # (1, 1, 5) + print(columns.shape) # (1, 1, 8) + + key_padding_mask = paddle.to_tensor([[1, 1, 1, 0]], dtype="float32") + attention_mask = paddle.to_tensor([[1, 0, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype="float32") + output_mask = paddle.nn.functional.sparse_attention(query, key, + value, offset, columns, + key_padding_mask=key_padding_mask, + attn_mask=attention_mask) + print(output_mask) + # Tensor(shape=[1, 1, 4, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[[0. , 1. ], + # [1.99830270, 2.99830270], + # [0. , 1. ], + # [0. , 1. ]]]]) + + output = paddle.nn.functional.sparse_attention(query, key, + value, offset, columns) + print(output) + # Tensor(shape=[1, 1, 4, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[[1.60885942, 2.60885954], + # [1.99830270, 2.99830270], + # [1.60885942, 2.60885954], + # [1.99830270, 2.99830270]]]]) + """ + if in_dynamic_mode(): + ( + result_attention, + result_sdd, + result_softmax, + ) = _legacy_C_ops.sparse_attention( + query, + key, + value, + sparse_csr_offset, + sparse_csr_columns, + key_padding_mask, + attn_mask, + ) + return result_attention + + helper = LayerHelper('sparse_attention', **locals()) + dtype = helper.input_dtype(input_param_name='Q') + out = helper.create_variable_for_type_inference(dtype) + result_sdd = helper.create_variable_for_type_inference(dtype) + result_softmax = helper.create_variable_for_type_inference(dtype) + inputs = { + 'Q': query, + 'K': key, + 'V': value, + 'Offset': sparse_csr_offset, + 'Columns': sparse_csr_columns, + 'KeyPaddingMask': key_padding_mask, + 'AttnMask': attn_mask, + } + outputs = { + 'Out': out, + 'SparseDotSdd': result_sdd, + 'Softmax': result_softmax, + } + helper.append_op(type='sparse_attention', inputs=inputs, outputs=outputs) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..2b926b5ab369046fc07c3d3d8cd56431d7f740a7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/transformer.py @@ -0,0 +1,16 @@ +# 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. + +# TODO: define the classes of Transformer neural network +# __all__ = [ ] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/vision.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c425a3a295fd65e1c37915850ac52c218a2138 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/functional/vision.py @@ -0,0 +1,536 @@ +# 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. + +from ...device import get_cudnn_version +from ...static import Variable +from ...fluid.layer_helper import LayerHelper +from ...fluid.data_feeder import check_variable_and_dtype +from ...fluid import dygraph_utils +import numpy as np +from paddle import _C_ops, _legacy_C_ops +from ...device import is_compiled_with_rocm +from paddle import in_dynamic_mode +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph +from paddle.framework import _non_static_mode + +__all__ = [] + + +def affine_grid(theta, out_shape, align_corners=True, name=None): + """ + It generates a grid of (x,y) or (x,y,z) coordinates using the parameters of + the affine transformation that correspond to a set of points where + the input feature map should be sampled to produce the transformed + output feature map. + + Args: + theta (Tensor) - A tensor with shape [N, 2, 3] or [N, 3, 4]. It contains a batch of affine transform parameters. + The data type can be float32 or float64. + out_shape (Tensor | list | tuple): Type can be a 1-D Tensor, list, or tuple. It is used to represent the shape of the output in an affine transformation, in the format ``[N, C, H, W]`` or ``[N, C, D, H, W]``. + When the format is ``[N, C, H, W]``, it represents the batch size, number of channels, height and width. When the format is ``[N, C, D, H, W]``, it represents the batch size, number of channels, depth, height and width. + The data type must be int32. + align_corners(bool, optional): if True, aligns the centers of the 4 (4D) or 8 (5D) corner pixels of the input and output tensors, and preserves the value of the corner pixels. Default: True + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, A Tensor with shape [batch_size, H, W, 2] or [batch, D, H, W, 3] while ('D')'H', 'W' are the (depth)height, width of feature map in affine transformation. The data type is the same as `theta`. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + # theta shape = [1, 2, 3] + theta = paddle.to_tensor([[[-0.7, -0.4, 0.3], + [ 0.6, 0.5, 1.5]]], dtype="float32") + y_t = F.affine_grid( + theta, + [1, 2, 3, 3], + align_corners=False) + print(y_t) + + #[[[[ 1.0333333 0.76666665] + # [ 0.76666665 1.0999999 ] + # [ 0.5 1.4333333 ]] + # + # [[ 0.5666667 1.1666666 ] + # [ 0.3 1.5 ] + # [ 0.03333333 1.8333334 ]] + # + # [[ 0.10000002 1.5666667 ] + # [-0.16666666 1.9000001 ] + # [-0.43333334 2.2333333 ]]]] + """ + if not isinstance(theta, Variable): + raise ValueError("The theta should be a Tensor.") + + cudnn_version = get_cudnn_version() + if cudnn_version is not None and cudnn_version >= 6000 and align_corners: + use_cudnn = True + else: + use_cudnn = False + if theta.shape[1] == 3: + use_cudnn = False + if is_compiled_with_rocm(): + use_cudnn = ( + False # ROCM platform do not have MIOPEN kernel for affine_grid + ) + + if in_dygraph_mode(): + _out_shape = ( + out_shape.numpy().tolist() + if isinstance(out_shape, Variable) + else out_shape + ) + return _C_ops.affine_grid(theta, _out_shape, use_cudnn, align_corners) + elif in_dynamic_mode(): + _out_shape = ( + out_shape.numpy().tolist() + if isinstance(out_shape, Variable) + else out_shape + ) + return _legacy_C_ops.affine_grid( + theta, + "output_shape", + _out_shape, + "align_corners", + align_corners, + "use_cudnn", + use_cudnn, + ) + + helper = LayerHelper('affine_grid') + check_variable_and_dtype( + theta, 'theta', ['float32', 'float64'], 'affine_grid' + ) + out = helper.create_variable_for_type_inference(theta.dtype) + ipts = {'Theta': theta} + attrs = {"align_corners": align_corners, "use_cudnn": use_cudnn} + if isinstance(out_shape, Variable): + ipts['OutputShape'] = out_shape + check_variable_and_dtype( + out_shape, 'out_shape', ['int32'], 'affine_grid' + ) + else: + attrs['output_shape'] = out_shape + + helper.append_op( + type='affine_grid', + inputs=ipts, + outputs={'Output': out}, + attrs=None if len(attrs) == 0 else attrs, + ) + return out + + +def grid_sample( + x, + grid, + mode='bilinear', + padding_mode='zeros', + align_corners=True, + name=None, +): + """ + Sample input X by using bilinear interpolation or + nearest interpolation based on flow field grid, which is usually + generated by :code:`affine_grid` . When the input X is 4-D Tensor, + the grid of shape [N, H, W, 2] is the concatenation of (x, y) + coordinates with shape [N, H, W] each, where x is indexing the 4th + dimension (in width dimension) of input data x and y is indexing + the 3rd dimension (in height dimension), finally results is the + bilinear interpolation or nearest value of 4 nearest corner + points. The output tensor shape will be [N, C, H, W]. When the input X + is 5-D Tensor, the grid of shape [N, D, H, W, 3] is the concatenation + of (x, y, z) coordinates with shape [N, D, H, W] each, where x is + indexing the 5th dimension (in width dimension) of input data x, y is + indexing the 4th dimension (in height dimension) and z is indexing the + 3rd dimension (in depth dimension) finally results is the bilinear + interpolation or nearest value of 8 nearest cornerpoints. The output + tensor shape will be [N, C, D, H, W]. + + + + Step 1: + + Get (x, y) grid coordinates and scale to [0, H-1/W-1]. + + .. code-block:: text + + grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1) + grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1) + + Step 2: + + Indices input data X with grid (x, y) in each [H, W] area, and bilinear + interpolate point value by 4 nearest points or nearest interpolate point value + by nearest point. + + .. code-block:: text + + wn ------- y_n ------- en + | | | + | d_n | + | | | + x_w --d_w-- grid--d_e-- x_e + | | | + | d_s | + | | | + ws ------- y_s ------- wn + + For bilinear interpolation: + x_w = floor(x) // west side x coord + x_e = x_w + 1 // east side x coord + y_n = floor(y) // north side y coord + y_s = y_s + 1 // south side y coord + d_w = grid_x - x_w // distance to west side + d_e = x_e - grid_x // distance to east side + d_n = grid_y - y_n // distance to north side + d_s = y_s - grid_y // distance to south side + wn = X[:, :, y_n, x_w] // north-west point value + en = X[:, :, y_n, x_e] // north-east point value + ws = X[:, :, y_s, x_w] // south-east point value + es = X[:, :, y_s, x_w] // north-east point value + + output = wn * d_e * d_s + en * d_w * d_s + + ws * d_e * d_n + es * d_w * d_n + + Args: + x(Tensor): The input tensor, which is a 4-d tensor with shape + [N, C, H, W] or a 5-d tensor with shape [N, C, D, H, W], + N is the batch size, C is the channel number, + D, H and W is the feature depth, height and width. + The data type is float32 or float64. + grid(Tensor): Input grid tensor, which is a 4-d tensor with shape [N, grid_H, + grid_W, 2] or a 5-d tensor with shape [N, grid_D, grid_H, + grid_W, 3]. The data type is float32 or float64. + mode(str, optional): The interpolation method which can be 'bilinear' or 'nearest'. + Default: 'bilinear'. + padding_mode(str, optional) The padding method used when source index + is out of input images. It can be 'zeros', 'reflection' and 'border'. + Default: zeros. + align_corners(bool, optional): If `align_corners` is true, it will projects + -1 and 1 to the centers of the corner pixels. Otherwise, it will + projects -1 and 1 to the image edges. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + + Tensor, The shape of output is [N, C, grid_H, grid_W] or [N, C, grid_D, grid_H, grid_W] in which `grid_D` is the depth of grid, + `grid_H` is the height of grid and `grid_W` is the width of grid. The data type is same as input tensor. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + # x shape=[1, 1, 3, 3] + x = paddle.to_tensor([[[[-0.6, 0.8, -0.5], + [-0.5, 0.2, 1.2], + [ 1.4, 0.3, -0.2]]]],dtype='float64') + # grid shape = [1, 3, 4, 2] + grid = paddle.to_tensor([[[[ 0.2, 0.3], + [-0.4, -0.3], + [-0.9, 0.3], + [-0.9, -0.6]], + [[ 0.4, 0.1], + [ 0.9, -0.8], + [ 0.4, 0.5], + [ 0.5, -0.2]], + [[ 0.1, -0.8], + [-0.3, -1. ], + [ 0.7, 0.4], + [ 0.2, 0.8]]]],dtype='float64') + y_t = F.grid_sample( + x, + grid, + mode='bilinear', + padding_mode='border', + align_corners=True) + print(y_t) + + # output shape = [1, 1, 3, 4] + # [[[[ 0.34 0.016 0.086 -0.448] + # [ 0.55 -0.076 0.35 0.59 ] + # [ 0.596 0.38 0.52 0.24 ]]]] + """ + + _modes = ['bilinear', 'nearest'] + _padding_modes = ['zeros', 'reflection', 'border'] + if mode not in _modes: + raise ValueError( + "The mode of grid sample function should be in {}, but got: {}".format( + _modes, mode + ) + ) + if padding_mode not in _padding_modes: + raise ValueError( + "The padding mode of grid sample function should be in {}, but got: {}".format( + _padding_modes, padding_mode + ) + ) + + if not isinstance(align_corners, bool): + raise ValueError( + "The align corners should be bool, but got: {}".format( + align_corners + ) + ) + + cudnn_version = get_cudnn_version() + use_cudnn = False + if ( + not is_compiled_with_rocm() + and (cudnn_version is not None) + and align_corners + and mode == 'bilinear' + and padding_mode == 'zeros' + ): + use_cudnn = True + # CUDNN always computes gradients for all inputs + x.stop_gradient = False + grid.stop_gradient = False + + if len(grid.shape) == 5: + use_cudnn = False + + if in_dygraph_mode(): + return _C_ops.grid_sample(x, grid, mode, padding_mode, align_corners) + elif in_dynamic_mode(): + attrs = ( + 'mode', + mode, + 'padding_mode', + padding_mode, + 'align_corners', + align_corners, + 'use_cudnn', + use_cudnn, + ) + out = getattr(_legacy_C_ops, 'grid_sampler')(x, grid, *attrs) + else: + helper = LayerHelper("grid_sample", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'grid_sample') + check_variable_and_dtype( + grid, 'grid', ['float32', 'float64'], 'grid_sample' + ) + ipts = {'X': x, 'Grid': grid} + attrs = { + 'mode': mode, + 'padding_mode': padding_mode, + 'align_corners': align_corners, + 'use_cudnn': use_cudnn, + } + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='grid_sampler', + inputs=ipts, + attrs=attrs, + outputs={'Output': out}, + ) + return out + + +def pixel_shuffle(x, upscale_factor, data_format="NCHW", name=None): + """ + This API implements pixel shuffle operation. + See more details in :ref:`api_nn_vision_PixelShuffle` . + + + Parameters: + x(Tensor): 4-D tensor, the data type should be float32 or float64. + upscale_factor(int): factor to increase spatial resolution. + data_format (str, optional): The data format of the input and output data. An optional string from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + + Returns: + Out(tensor): Reshaped tensor according to the new dimension. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.randn(shape=[2,9,4,4]) + out_var = F.pixel_shuffle(x, 3) + out = out_var.numpy() + print(out.shape) + # (2, 1, 12, 12) + """ + if not isinstance(upscale_factor, int): + raise TypeError("upscale factor must be int type") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'." + "But recevie Attr(data_format): {} ".format(data_format) + ) + if in_dygraph_mode(): + return _C_ops.pixel_shuffle(x, upscale_factor, data_format) + + if _in_legacy_dygraph(): + return _legacy_C_ops.pixel_shuffle( + x, "upscale_factor", upscale_factor, "data_format", data_format + ) + + helper = LayerHelper("pixel_shuffle", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_shuffle') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="pixel_shuffle", + inputs={"X": x}, + outputs={"Out": out}, + attrs={"upscale_factor": upscale_factor, "data_format": data_format}, + ) + return out + + +def pixel_unshuffle(x, downscale_factor, data_format="NCHW", name=None): + """ + This API implements pixel unshuffle operation. + See more details in :ref:`api_nn_vision_PixelUnshuffle` . + + Parameters: + x (Tensor): 4-D tensor, the data type should be float32 or float64. + downscale_factor (int): Factor to decrease spatial resolution. + data_format (str, optional): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Out (Tensor): Reshaped tensor according to the new dimension. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + x = paddle.randn([2, 1, 12, 12]) + out = F.pixel_unshuffle(x, 3) + print(out.shape) + # [2, 9, 4, 4] + """ + if len(x.shape) != 4: + raise ValueError( + "Input x should be 4D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + + if not isinstance(downscale_factor, int): + raise TypeError("Downscale factor must be int type") + + if downscale_factor <= 0: + raise ValueError("Downscale factor must be positive") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'." + "But recevie Attr(data_format): {} ".format(data_format) + ) + + if _non_static_mode(): + return _legacy_C_ops.pixel_unshuffle( + x, "downscale_factor", downscale_factor, "data_format", data_format + ) + + helper = LayerHelper("pixel_unshuffle", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pixel_unshuffle') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="pixel_unshuffle", + inputs={"X": x}, + outputs={"Out": out}, + attrs={ + "downscale_factor": downscale_factor, + "data_format": data_format, + }, + ) + return out + + +def channel_shuffle(x, groups, data_format="NCHW", name=None): + """ + This API implements channel shuffle operation. + See more details in :ref:`api_nn_vision_ChannelShuffle` . + + Parameters: + x (Tensor): 4-D tensor, the data type should be float32 or float64. + groups (int): Number of groups to divide channels in. + data_format (str): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Out (Tensor): Rearranged tensor keeping the original tensor shape. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + x = paddle.arange(0, 0.6, 0.1, 'float32') + x = paddle.reshape(x, [1, 6, 1, 1]) + # [[[[0. ]], + # [[0.10000000]], + # [[0.20000000]], + # [[0.30000001]], + # [[0.40000001]], + # [[0.50000000]]]] + y = F.channel_shuffle(x, 3) + # [[[[0. ]], + # [[0.20000000]], + # [[0.40000001]], + # [[0.10000000]], + # [[0.30000001]], + # [[0.50000000]]]] + """ + if len(x.shape) != 4: + raise ValueError( + "Input x should be 4D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + + if not isinstance(groups, int): + raise TypeError("groups must be int type") + + if groups <= 0: + raise ValueError("groups must be positive") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError( + "Attr(data_format) should be 'NCHW' or 'NHWC'." + "But recevie Attr(data_format): {} ".format(data_format) + ) + + if _non_static_mode(): + return _legacy_C_ops.channel_shuffle( + x, "groups", groups, "data_format", data_format + ) + + helper = LayerHelper("channel_shuffle", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'channel_shuffle') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="channel_shuffle", + inputs={"X": x}, + outputs={"Out": out}, + attrs={"groups": groups, "data_format": data_format}, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..530c52bf5f26d269046ea734fd14544cdeb8e29f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/__init__.py @@ -0,0 +1,43 @@ +# 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. + +# TODO: define the initializers to create a Parameter in neural network +from ...fluid.initializer import Bilinear # noqa: F401 +from ...fluid.initializer import set_global_initializer # noqa: F401 +from ...fluid.initializer import calculate_gain # noqa: F401 + +from .constant import Constant # noqa: F401 + +from .kaiming import KaimingNormal # noqa: F401 +from .kaiming import KaimingUniform # noqa: F401 + +from .xavier import XavierNormal # noqa: F401 +from .xavier import XavierUniform # noqa: F401 + +from .assign import Assign # noqa: F401 + +from .normal import Normal # noqa: F401 +from .normal import TruncatedNormal # noqa: F401 + +from .uniform import Uniform # noqa: F401 + +from .orthogonal import Orthogonal # noqa: F401 + +from .dirac import Dirac # noqa: F401 + +__all__ = [ #noqa + 'Bilinear', 'Constant', 'KaimingUniform', 'KaimingNormal', 'XavierNormal', + 'XavierUniform', 'Assign', 'Normal', 'TruncatedNormal', 'Uniform', + 'Orthogonal', 'Dirac', 'set_global_initializer', 'calculate_gain' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/assign.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/assign.py new file mode 100644 index 0000000000000000000000000000000000000000..746d2b67b2a1d396b377b9f6edbcd6ee233eaabd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/assign.py @@ -0,0 +1,97 @@ +# 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. +import paddle +from ...fluid.data_feeder import check_type +from ...fluid.initializer import NumpyArrayInitializer + +__all__ = [] + + +class Assign(NumpyArrayInitializer): + """Init an parameter with a numpy array, list, or tensor. + + Args: + value (Tensor|numpy.ndarray|list|tuple): numpy array, list, tuple, or tensor to initialize the parameter. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A parameter initialized by the input numpy array, list, or tensor. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # numpy array + data_1 = paddle.ones(shape=[1, 2], dtype='float32') + weight_attr_1 = paddle.framework.ParamAttr( + name="linear_weight_1", + initializer=paddle.nn.initializer.Assign(np.array([2, 2]))) + bias_attr_1 = paddle.framework.ParamAttr( + name="linear_bias_1", + initializer=paddle.nn.initializer.Assign(np.array([2]))) + linear_1 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_1, bias_attr=bias_attr_1) + # linear_1.weight: [2. 2.] + # linear_1.bias: [2.] + + res_1 = linear_1(data_1) + # res_1: [6.] + + # python list + data_2 = paddle.ones(shape=[1, 2], dtype='float32') + weight_attr_2 = paddle.framework.ParamAttr( + name="linear_weight_2", + initializer=paddle.nn.initializer.Assign([2, 2])) + bias_attr_2 = paddle.framework.ParamAttr( + name="linear_bias_2", + initializer=paddle.nn.initializer.Assign([2])) + linear_2 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_2, bias_attr=bias_attr_2) + # linear_2.weight: [2. 2.] + # linear_2.bias: [2.] + + res_2 = linear_2(data_2) + # res_2: [6.] + + # tensor + data_3 = paddle.ones(shape=[1, 2], dtype='float32') + weight_attr_3 = paddle.framework.ParamAttr( + name="linear_weight_3", + initializer=paddle.nn.initializer.Assign(paddle.full([2], 2))) + bias_attr_3 = paddle.framework.ParamAttr( + name="linear_bias_3", + initializer=paddle.nn.initializer.Assign(paddle.full([1], 2))) + linear_3 = paddle.nn.Linear(2, 2, weight_attr=weight_attr_3, bias_attr=bias_attr_3) + # linear_3.weight: [2. 2.] + # linear_3.bias: [2.] + + res_3 = linear_3(data_3) + # res_3: [6.] + """ + + def __init__(self, value, name=None): + import numpy + check_type(value, 'value', + (numpy.ndarray, list, tuple, paddle.static.Variable), + 'Assign') + + if (isinstance(value, (list, tuple))): + value = numpy.array(value) + + # TODO: value is already is a tensor, accounting efficiency maybe it does not need to convert tensor to numpy data and then initialized. + if (isinstance(value, paddle.static.Variable)): + value = value.numpy() + + super(Assign, self).__init__(value) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/constant.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc5e60c2e0a325370147c58b1ce65ffa417a1b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/constant.py @@ -0,0 +1,46 @@ +# 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. + +# TODO: define the initializers of Constant in neural network +from ...fluid.initializer import ConstantInitializer + +__all__ = [] + + +class Constant(ConstantInitializer): + """Implement the constant initializer. + + Args: + value (float32|float64, optional): constant value to initialize the parameter. Default: 0.0. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + data = paddle.rand([30, 10, 2], dtype='float32') + linear = nn.Linear(2, + 4, + weight_attr=nn.initializer.Constant(value=2.0)) + res = linear(data) + print(linear.weight.numpy()) + #result is [[2. 2. 2. 2.],[2. 2. 2. 2.]] + + """ + + def __init__(self, value=0.0): + if value is None: + raise ValueError("value must not be none.") + super(Constant, self).__init__(value=value, force_cpu=False) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/dirac.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/dirac.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6cfc009cafca25c1e60dfaca5135375db9bdfb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/dirac.py @@ -0,0 +1,284 @@ +# Copyright (c) 2021 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. + +from ...fluid.initializer import Initializer +from ...fluid.data_feeder import check_variable_and_dtype +from ...fluid.core import VarDesc +from ...fluid import framework +from ...fluid.framework import _current_expected_place +from paddle import in_dynamic_mode +from paddle.utils import unique_name +from paddle import _C_ops, _legacy_C_ops +from ... import fluid + +__all__ = [] + + +class Dirac(Initializer): + r"""Initialize the 3D/4D/5D Tensor with Dirac delta function. + + It can reserve the feature of convolution layer input, which means that + as many channels are reserved as possible. + + In this initialize method, elements in the middle of convolution kernels will + be set to 1 . The formula can be described as follow. + + .. math:: + + X[d, d, shape[2]//2, shape[3]//2, ...]=1, \ d=0,1...N + + where, ``N`` is the minimum value of ``in_channels`` and ``out_channels`` + + Args: + groups(int, optional): 0-dimension of the Tensor will be divided by groups, + each group has the same value. Default: 1. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Dirac initializer instance objects. + + Examples: + .. code-block:: python + + import paddle + + #1. For kernel_size is uneven number: + + attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Dirac()) + conv = paddle.nn.Conv1D(3, 2, 3, weight_attr=attr) + conv.weight + # Tensor(shape=[2, 3, 3], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[[0., 1., 0.], + # [0., 0., 0.], + # [0., 0., 0.]], + # + # [[0., 0., 0.], + # [0., 1., 0.], + # [0., 0., 0.]]]) + + input = paddle.rand([8, 3, 10]) + output = conv(input) + output == input[:, 0:2, 1:9] + # output.shape is [8, 2, 8], It means output is almost the same with input, 2 channels are reserved + + + #2. For kernel_size is even number: + attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Dirac()) + conv = paddle.nn.Conv1D(3, 2, 4, weight_attr=attr) + conv.weight + # Tensor(shape=[2, 3, 4], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[[0., 0., 1., 0.], + # [0., 0., 0., 0.], + # [0., 0., 0., 0.]], + # + # [[0., 0., 0., 0.], + # [0., 0., 1., 0.], + # [0., 0., 0., 0.]]]) + """ + + def __init__(self, groups=1, name=None): + assert groups > 0 and isinstance( + groups, int), " 'groups' must be a positive integer. " + super(Dirac, self).__init__() + self._groups = groups + + def __call__(self, var, block=None): + """Initialize the input tensor with dirac initializer. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The most critical OP(scatter) in this initializer, which contains 7~8 ops in total. + """ + block = self._check_block(block) + assert isinstance(var, framework.Parameter) + assert isinstance(block, framework.Block) + check_variable_and_dtype(var, "Out", + ['float16', 'bfloat16', 'float32', 'float64'], + 'Dirac') + + assert len(var.shape) in [ + 3, 4, 5 + ], "Only Tensor with 3/4/5 dimensions can be initialized by Dirac" + assert ( + var.shape[0] % + self._groups) == 0, "Tensor 0-dimension must be divisible by groups" + + if var.dtype != VarDesc.VarType.FP32: + out_var = block.create_var(name=unique_name.generate(".".join( + ['dirac', var.name, 'tmp'])), + shape=var.shape, + dtype=VarDesc.VarType.FP32, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False) + else: + out_var = var + op = None + if framework.in_dygraph_mode(): + with fluid.dygraph.no_grad(): + place = _current_expected_place() + _C_ops.full_(out_var, out_var.shape, str(float(0)), + out_var.dtype, place) + + else: + block.append_op(type='fill_constant', + inputs={}, + outputs={'Out': out_var}, + attrs={ + 'value': float(0), + 'dtype': out_var.dtype, + 'shape': out_var.shape, + }, + stop_gradient=True) + + origin_shape = var.shape + num_per_group = origin_shape[0] // self._groups + min_shape = min(num_per_group, origin_shape[1]) + + idx_list = [] + value_list = [] + strides = [] + prod = 1 + for dim in reversed(origin_shape): + strides.insert(0, prod) + prod *= dim + for i in range(self._groups): + for j in range(min_shape): + value_list.append(1.0) + offset = 0 + for (k, stride) in enumerate(strides): + if (k == 0): + offset += (j + i * num_per_group) * stride + elif (k == 1): + offset += j * stride + else: + offset += origin_shape[k] // 2 * stride + idx_list.append(offset) + if framework.in_dygraph_mode(): + with fluid.dygraph.no_grad(): + tmp_out = _C_ops.reshape(out_var, [-1]) + tmp_out._share_underline_tensor_to(out_var) + else: + x_shape = block.create_var(name=unique_name.generate(".".join( + [out_var.name, "XShape"])), + dtype=out_var.dtype, + shape=out_var.shape, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + block.append_op(type="reshape2", + inputs={"X": out_var}, + attrs={'shape': [-1]}, + outputs={ + "Out": out_var, + "XShape": x_shape + }, + stop_gradient=True) + + index_tensor = block.create_var( + name=unique_name.generate('scatter_index'), + persistable=False, + stop_gradient=True) + + if framework.in_dygraph_mode(): + with fluid.dygraph.no_grad(): + tmp_tensor = framework._varbase_creator() + _C_ops.assign_value_(tmp_tensor, [len(idx_list)], + VarDesc.VarType.INT64, idx_list, + _current_expected_place()) + tmp_tensor._share_underline_tensor_to(index_tensor) + else: + block.append_op(type='assign_value', + outputs={'Out': index_tensor}, + attrs={ + 'dtype': VarDesc.VarType.INT64, + 'shape': [len(idx_list)], + 'int64_values': idx_list + }, + stop_gradient=True) + + value_tensor = block.create_var( + name=unique_name.generate('scatter_value'), + persistable=False, + stop_gradient=True) + + if framework.in_dygraph_mode(): + with fluid.dygraph.no_grad(): + tmp_tensor = framework._varbase_creator() + _C_ops.assign_value_(tmp_tensor, [len(value_list)], + VarDesc.VarType.FP32, value_list, + _current_expected_place()) + + tmp_tensor._share_underline_tensor_to(value_tensor) + else: + block.append_op(type='assign_value', + outputs={'Out': value_tensor}, + attrs={ + 'dtype': VarDesc.VarType.FP32, + 'shape': [len(value_list)], + 'fp32_values': value_list + }, + stop_gradient=True) + + if framework.in_dygraph_mode(): + with fluid.dygraph.no_grad(): + tmp_out = _C_ops.scatter(out_var, index_tensor, value_tensor, + True) + tmp_out._share_underline_tensor_to(out_var) + tmp_reshape_out = _C_ops.reshape(out_var, origin_shape) + tmp_reshape_out._share_underline_tensor_to(out_var) + if var.dtype != VarDesc.VarType.FP32: + tmp_cast_out = _C_ops.cast(out_var, var.dtype) + tmp_cast_out._share_underline_tensor_to(var) + else: + op = block.append_op(type="scatter", + inputs={ + "X": out_var, + "Ids": index_tensor, + "Updates": value_tensor + }, + attrs={'overwrite': True}, + outputs={"Out": out_var}, + stop_gradient=True) + x_shape = block.create_var(name=unique_name.generate(".".join( + [out_var.name, "XShape"])), + dtype=out_var.dtype, + shape=out_var.shape, + type=VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + block.append_op(type="reshape2", + inputs={"X": out_var}, + attrs={'shape': origin_shape}, + outputs={ + "Out": out_var, + "XShape": x_shape + }, + stop_gradient=True) + if var.dtype != VarDesc.VarType.FP32: + block.append_op(type="cast", + inputs={"X": out_var}, + outputs={"Out": var}, + attrs={ + "in_dtype": out_var.dtype, + "out_dtype": var.dtype + }, + stop_gradient=True) + if not in_dynamic_mode(): + var.op = op + return op diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/kaiming.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/kaiming.py new file mode 100644 index 0000000000000000000000000000000000000000..38394eb5b93168e66929eed9e4490060edc5581e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/kaiming.py @@ -0,0 +1,111 @@ +# Copyright (c) 2022 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. + +# TODO: define the initializers of Kaiming functions in neural network +from ...fluid.initializer import MSRAInitializer + +__all__ = [] + + +class KaimingNormal(MSRAInitializer): + r"""Implements the Kaiming Normal initializer + + This class implements the weight initialization from the paper + `Delving Deep into Rectifiers: Surpassing Human-Level Performance on + ImageNet Classification `_ + by Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun. This is a + robust initialization method that particularly considers the rectifier + nonlinearities. + + In case of Normal distribution, the mean is 0 and the standard deviation + is + + .. math:: + + \frac{gain}{\sqrt{{fan\_in}}} + + Args: + fan_in (float32|None, optional): fan_in (in_features) of trainable Tensor, If None, it will be infered automaticly. If you don't want to use in_features of the Tensor, you can set the value of 'fan_in' smartly by yourself. default is None. + negative_slope (float, optional): negative_slope (only used with leaky_relu). default is 0.0. + nonlinearity(str, optional): the non-linear function. default is relu. + + Note: + It is recommended to set fan_in to None for most cases. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + linear = nn.Linear(2, + 4, + weight_attr=nn.initializer.KaimingNormal()) + data = paddle.rand([30, 10, 2], dtype='float32') + res = linear(data) + + """ + + def __init__(self, fan_in=None, negative_slope=0.0, nonlinearity='relu'): + super(KaimingNormal, self).__init__(uniform=False, + fan_in=fan_in, + seed=0, + negative_slope=negative_slope, + nonlinearity=nonlinearity) + + +class KaimingUniform(MSRAInitializer): + r"""Implements the Kaiming Uniform initializer + + This class implements the weight initialization from the paper + `Delving Deep into Rectifiers: Surpassing Human-Level Performance on + ImageNet Classification `_ + by Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun. This is a + robust initialization method that particularly considers the rectifier + nonlinearities. + + In case of Uniform distribution, the range is [-x, x], where + + .. math:: + + x = gain \times \sqrt{\frac{3}{fan\_in}} + + Args: + fan_in (float32|None, optional): fan_in (in_features) of trainable Tensor, If None, it will be infered automaticly. If you don't want to use in_features of the Tensor, you can set the value of 'fan_in' smartly by yourself. default is None. + negative_slope (float, optional): negative_slope (only used with leaky_relu). default is 0.0. + nonlinearity(str, optional): the non-linear function. default is relu. + + Note: + It is recommended to set fan_in to None for most cases. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + linear = nn.Linear(2, + 4, + weight_attr=nn.initializer.KaimingUniform()) + data = paddle.rand([30, 10, 2], dtype='float32') + res = linear(data) + + """ + + def __init__(self, fan_in=None, negative_slope=0.0, nonlinearity='relu'): + super(KaimingUniform, self).__init__(uniform=True, + fan_in=fan_in, + seed=0, + negative_slope=negative_slope, + nonlinearity=nonlinearity) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/normal.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/normal.py new file mode 100644 index 0000000000000000000000000000000000000000..730c55ea6f1b8159e12158df6a608d92c77edcd1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/normal.py @@ -0,0 +1,99 @@ +# 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. + +from ...fluid.initializer import NormalInitializer +from ...fluid.initializer import TruncatedNormalInitializer + +__all__ = [] + + +class Normal(NormalInitializer): + """The Random Normal (Gaussian) distribution initializer. + + Args: + mean (float, optional): mean of the normal distribution. The default value is 0.0. + std (float, optional): standard deviation of the normal distribution. The default value is 1.0. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A parameter initialized by Random Normal (Gaussian) distribution. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.ones(shape=[3, 1, 2], dtype='float32') + weight_attr = paddle.framework.ParamAttr( + name="linear_weight", + initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0)) + bias_attr = paddle.framework.ParamAttr( + name="linear_bias", + initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0)) + linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr) + # linear.weight: [[ 2.1973135 -2.2697184] + # [-1.9104223 -1.0541488]] + # linear.bias: [ 0.7885926 -0.74719954] + + res = linear(data) + # res: [[[ 1.0754838 -4.071067 ]] + # [[ 1.0754838 -4.071067 ]] + # [[ 1.0754838 -4.071067 ]]] + """ + + def __init__(self, mean=0.0, std=1.0, name=None): + assert mean is not None, 'mean should not be None' + assert std is not None, 'std should not be None' + super(Normal, self).__init__(loc=mean, scale=std, seed=0) + + +class TruncatedNormal(TruncatedNormalInitializer): + """The truncated normal distribution (Gaussian distribution) initializer. + + Args: + mean (float, optional): Mean of the normal distribution. The default value is :math:`0.0`. + std (float, optional): Standard deviation of the normal distribution. The default value is :math:`1.0`. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A parameter initialized by truncated normal distribution (Gaussian distribution). + + Examples: + .. code-block:: python + + import paddle + + data = paddle.ones(shape=[3, 1, 2], dtype='float32') + weight_attr = paddle.framework.ParamAttr( + name="linear_weight", + initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0)) + bias_attr = paddle.framework.ParamAttr( + name="linear_bias", + initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0)) + linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr) + # linear.weight: [[-1.0981836 1.4140984] + # [ 3.1390522 -2.8266568]] + # linear.bias: [-2.1546738 -1.6570673] + + res = linear(data) + # res: [[[-0.11380529 -3.0696259 ]] + # [[-0.11380529 -3.0696259 ]] + # [[-0.11380529 -3.0696259 ]] + """ + + def __init__(self, mean=0.0, std=1.0, name=None): + assert mean is not None, 'mean should not be None' + assert std is not None, 'std should not be None' + super(TruncatedNormal, self).__init__(loc=mean, scale=std, seed=0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/orthogonal.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..63e0152e22b4a1c09a79b7515c5e384a387694c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/orthogonal.py @@ -0,0 +1,234 @@ +# Copyright (c) 2021 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. + +from ...fluid.initializer import Initializer +from ...fluid.data_feeder import check_variable_and_dtype +from ...fluid import framework +from ...tensor import diag, transpose, sign, qr, reshape +from paddle.utils import unique_name +from ...fluid.dygraph import no_grad +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +class Orthogonal(Initializer): + """The orthogonal initializer. The initialized tensor is (semi) orthogonal. + + It's only applied to Tensor whose dimension is greater than or equal to 2. + + For the Tensor whose dimension is greater than 2, the 0 dimension is seen as ``rows`` , + and the >=1 dimension are flattened as ``cols`` . + + Which can be describe as: + + .. code-block:: text + + rows = shape[0] + cols = shape[1]·shape[2]···shape[N] + + if rows < cols: + The rows are orthogonal vectors + elif rows > cols: + The columns are orthogonal vectors + else rows = cols: + Both rows and columns are orthogonal vectors + + Args: + gain(float, optional): The multiplication coefficient for initialized tensor. Default: 1.0. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A parameter initialized by orthogonal initialized. + + Examples: + .. code-block:: python + + import paddle + + weight_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Orthogonal()) + linear = paddle.nn.Linear(10, 15, weight_attr=weight_attr) + # linear.weight: X * X' = I + + linear = paddle.nn.Linear(15, 10, weight_attr=weight_attr) + # linear.weight: X' * X = I + """ + + def __init__(self, gain=1.0, name=None): + assert gain is not None, 'gain should not be None' + super(Orthogonal, self).__init__() + self._gain = gain + + def __call__(self, var, block=None): + """Initialize the input tensor with orthogonal initializer. + + Args: + var(Tensor): Tensor that needs to be initialized. + block(Block, optional): The block in which initialization ops + should be added. Used in static graph only, default None. + + Returns: + The last initialization op, it contain 8 ops in orthogonal initializer. + """ + block = self._check_block(block) + assert isinstance(var, framework.Parameter) + assert isinstance(block, framework.Block) + # 'qr' op only support float32/float64 now + check_variable_and_dtype(var, "Out", ["float32", "float64"], + "Orthogonal") + + self._seed = block.program.random_seed + + shape = var.shape + assert len( + shape + ) >= 2, "Only Tensor with 2 or more dimensions can be initialized by Orthogonal" + + row = shape[0] + col = 1 + for i in shape[1:]: + col *= i + + flatten_shape = [max(row, col), min(row, col)] + + if framework.in_dygraph_mode(): + with no_grad(): + place = framework._current_expected_place() + normal_var = _C_ops.gaussian_random(flatten_shape, 0.0, 1.0, + self._seed, var.dtype, + place) + q, r = _C_ops.qr(normal_var, 'reduced') + + r_diag = _C_ops.diag(r, 0, 0) + + r_sign = _C_ops.sign(r_diag) + + q = _C_ops.multiply(q, r_sign) + + if row < col: + q = _C_ops.transpose(q, [1, 0]) + + q = _C_ops.reshape(q, var.shape) + + tmp = _C_ops.scale(q, self._gain, 0.0, True) + + tmp._share_underline_tensor_to(var) + + return None + + normal_var = block.create_var(name=unique_name.generate('.'.join( + ['gaussian_random', 'tmp'])), + dtype=var.dtype, + persistable=False, + stop_gradient=True) + block.append_op(type='gaussian_random', + inputs={}, + outputs={'Out': normal_var}, + attrs={ + 'mean': 0.0, + 'std': 1.0, + 'shape': flatten_shape, + 'seed': self._seed, + 'dtype': var.dtype + }, + stop_gradient=True) + + q = block.create_var(name=unique_name.generate('.'.join( + ['qr', 'q', 'tmp'])), + dtype=normal_var.dtype, + persistable=False, + stop_gradient=True) + r = block.create_var(name=unique_name.generate('.'.join( + ['qr', 'r', 'tmp'])), + dtype=normal_var.dtype, + persistable=False, + stop_gradient=True) + block.append_op(type='qr', + inputs={'X': [normal_var]}, + outputs={ + 'Q': q, + 'R': r, + }, + attrs={'mode': 'reduced'}, + stop_gradient=True) + + r_diag = block.create_var(name=unique_name.generate('.'.join( + ['diag', 'tmp'])), + dtype=r.dtype, + persistable=False, + stop_gradient=True) + block.append_op(type='diag_v2', + inputs={'X': r}, + outputs={'Out': r_diag}, + attrs={ + 'offset': 0, + 'padding_value': 0 + }, + stop_gradient=True) + + r_sign = r_diag + block.append_op(type='sign', + inputs={'X': [r_diag]}, + outputs={'Out': r_sign}, + stop_gradient=True) + + block.append_op(type='elementwise_mul', + inputs={ + 'X': q, + 'Y': r_sign + }, + outputs={'Out': q}, + attrs={}, + stop_gradient=True) + + x_shape = block.create_var(name=unique_name.generate('.'.join( + ['transpose', 'shape', 'tmp'])), + dtype=q.dtype, + persistable=False, + stop_gradient=True) + if row < col: + q_transpose = block.create_var(name=unique_name.generate('.'.join( + ['transpose', 'tmp'])), + dtype=q.dtype, + persistable=False, + stop_gradient=True) + block.append_op(type='transpose2', + inputs={'X': q}, + outputs={ + 'Out': q_transpose, + 'XShape': x_shape + }, + attrs={'axis': [1, 0]}, + stop_gradient=True) + q = q_transpose + + block.append_op(type='reshape2', + inputs={'X': q}, + outputs={ + 'Out': q, + "XShape": x_shape + }, + attrs={'shape': var.shape}, + stop_gradient=True) + + op = block.append_op(type='scale', + inputs={'X': q}, + outputs={'Out': var}, + attrs={ + 'scale': self._gain, + 'bias': 0.0 + }) + + return op diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/uniform.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/uniform.py new file mode 100644 index 0000000000000000000000000000000000000000..707d3d03ecc13128c169b6c871608075be4c5fc3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/uniform.py @@ -0,0 +1,63 @@ +# 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. + +from ...fluid.initializer import UniformInitializer + +__all__ = [] + + +class Uniform(UniformInitializer): + """The uniform distribution initializer. + + Args: + low (float, optional): Lower boundary of the uniform distribution. The default value is :math:`-1.0`. + high (float, optional): Upper boundary of the uniform distribution. The default value is :math:`1.0`. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A parameter initialized by uniform distribution. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.ones(shape=[3, 1, 2], dtype='float32') + weight_attr = paddle.framework.ParamAttr( + name="linear_weight", + initializer=paddle.nn.initializer.Uniform(low=-0.5, high=0.5)) + bias_attr = paddle.framework.ParamAttr( + name="linear_bias", + initializer=paddle.nn.initializer.Uniform(low=-0.5, high=0.5)) + linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr) + # linear.weight: [[-0.46245047 0.05260676] + # [ 0.38054508 0.29169726]] + # linear.bias: [-0.2734719 0.23939109] + + res = linear(data) + # res: [[[-0.3553773 0.5836951]] + # [[-0.3553773 0.5836951]] + # [[-0.3553773 0.5836951]]] + """ + + def __init__(self, low=-1.0, high=1.0, name=None): + assert low is not None, 'low should not be None' + assert high is not None, 'high should not be None' + assert high >= low, 'high should greater or equal than low' + super(Uniform, self).__init__(low=low, + high=high, + seed=0, + diag_num=0, + diag_step=0, + diag_val=1.0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/xavier.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/xavier.py new file mode 100644 index 0000000000000000000000000000000000000000..2c6d60a6bb86be6a5d08d3807800d6f8182dc889 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/initializer/xavier.py @@ -0,0 +1,124 @@ +# 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. + +from ...fluid.initializer import XavierInitializer + +__all__ = [] + + +class XavierNormal(XavierInitializer): + r""" + This class implements the Xavier weight initializer from the paper + `Understanding the difficulty of training deep feedforward neural + networks `_ + by Xavier Glorot and Yoshua Bengio, using a normal distribution whose mean is :math:`0` and standard deviation is + + .. math:: + + \sqrt{\frac{2.0}{fan\_in + fan\_out}}. + + + Args: + fan_in (float, optional): fan_in for Xavier initialization, which is + inferred from the Tensor. The default value is None. + fan_out (float, optional): fan_out for Xavier initialization, which is + inferred from the Tensor. The default value is None. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A parameter initialized by Xavier weight, using a normal distribution. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.ones(shape=[3, 1, 2], dtype='float32') + weight_attr = paddle.framework.ParamAttr( + name="linear_weight", + initializer=paddle.nn.initializer.XavierNormal()) + bias_attr = paddle.framework.ParamAttr( + name="linear_bias", + initializer=paddle.nn.initializer.XavierNormal()) + linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr) + # inear.weight: [[ 0.06910077 -0.18103665] + # [-0.02546741 -1.0402188 ]] + # linear.bias: [-0.5012929 0.12418364] + + res = linear(data) + # res: [[[-0.4576595 -1.0970719]] + # [[-0.4576595 -1.0970719]] + # [[-0.4576595 -1.0970719]]] + """ + + def __init__(self, fan_in=None, fan_out=None, name=None): + super(XavierNormal, self).__init__(uniform=False, + fan_in=fan_in, + fan_out=fan_out, + seed=0) + + +class XavierUniform(XavierInitializer): + r""" + This class implements the Xavier weight initializer from the paper + `Understanding the difficulty of training deep feedforward neural + networks `_ + by Xavier Glorot and Yoshua Bengio. + + This initializer is designed to keep the scale of the gradients + approximately same in all the layers. In case of Uniform distribution, + the range is :math:`[-x,x]`, where + + .. math:: + + x = \sqrt{\frac{6.0}{fan\_in + fan\_out}}. + + Args: + fan_in (float, optional): fan_in for Xavier initialization, which is + inferred from the Tensor. The default value is None. + fan_out (float, optional): fan_out for Xavier initialization, which is + inferred from the Tensor. The default value is None. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A parameter initialized by Xavier weight, using a uniform distribution. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.ones(shape=[3, 1, 2], dtype='float32') + weight_attr = paddle.framework.ParamAttr( + name="linear_weight", + initializer=paddle.nn.initializer.XavierUniform()) + bias_attr = paddle.framework.ParamAttr( + name="linear_bias", + initializer=paddle.nn.initializer.XavierUniform()) + linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr) + # linear.weight: [[-0.04229349 -1.1248565 ] + # [-0.10789523 -0.5938053 ]] + # linear.bias: [ 1.1983747 -0.40201235] + + res = linear(data) + # res: [[[ 1.0481861 -2.1206741]] + # [[ 1.0481861 -2.1206741]] + # [[ 1.0481861 -2.1206741]]] + """ + + def __init__(self, fan_in=None, fan_out=None, name=None): + super(XavierUniform, self).__init__(uniform=True, + fan_in=fan_in, + fan_out=fan_out, + seed=0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45cb652332b3ad8929d453e5c6a51d31b7ee72be --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/__init__.py @@ -0,0 +1,101 @@ +# 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. + +# TODO: define activation functions of neural network + +from . import rnn # noqa: F401 +from . import transformer # noqa: F401 +from . import container # noqa: F401 + +from .activation import CELU # noqa: F401 +from .activation import PReLU # noqa: F401 +from .activation import ReLU # noqa: F401 +from .activation import ReLU6 # noqa: F401 +from .activation import LeakyReLU # noqa: F401 +from .activation import Sigmoid # noqa: F401 +from .activation import Softmax # noqa: F401 +from .activation import LogSoftmax # noqa: F401 +from .activation import RReLU # noqa: F401 +from .activation import Softmax2D # noqa: F401 +from .common import Bilinear # noqa: F401 +from .common import Pad1D # noqa: F401 +from .common import Pad2D # noqa: F401 +from .common import ZeroPad2D # noqa: F401 +from .common import Pad3D # noqa: F401 +from .common import CosineSimilarity # noqa: F401 +from .common import Embedding # noqa: F401 +from .common import Linear # noqa: F401 +from .common import Identity # noqa: F401 +from .common import Flatten # noqa: F401 +from .common import Upsample # noqa: F401 +from .common import Dropout # noqa: F401 +from .common import Dropout2D # noqa: F401 +from .common import Dropout3D # noqa: F401 +from .common import AlphaDropout # noqa: F401 +from .common import Upsample # noqa: F401 +from .common import UpsamplingBilinear2D # noqa: F401 +from .common import UpsamplingNearest2D # noqa: F401 +from .common import Fold +from .pooling import AvgPool1D # noqa: F401 +from .pooling import AvgPool2D # noqa: F401 +from .pooling import AvgPool3D # noqa: F401 +from .pooling import MaxPool1D # noqa: F401 +from .pooling import MaxPool2D # noqa: F401 +from .pooling import MaxPool3D # noqa: F401 +from .pooling import AdaptiveAvgPool1D # noqa: F401 +from .pooling import AdaptiveAvgPool2D # noqa: F401 +from .pooling import AdaptiveAvgPool3D # noqa: F401 +from .pooling import AdaptiveMaxPool1D # noqa: F401 +from .pooling import AdaptiveMaxPool2D # noqa: F401 +from .pooling import AdaptiveMaxPool3D # noqa: F401 +from .pooling import MaxUnPool1D # noqa: F401 +from .pooling import MaxUnPool2D # noqa: F401 +from .pooling import MaxUnPool3D # noqa: F401 +from .conv import Conv1D # noqa: F401 +from .conv import Conv2D # noqa: F401 +from .conv import Conv3D # noqa: F401 +from .conv import Conv1DTranspose # noqa: F401 +from .conv import Conv2DTranspose # noqa: F401 +from .conv import Conv3DTranspose # noqa: F401 +from .loss import BCEWithLogitsLoss # noqa: F401 +from .loss import CrossEntropyLoss # noqa: F401 +from .loss import MSELoss # noqa: F401 +from .loss import L1Loss # noqa: F401 +from .loss import NLLLoss # noqa: F401 +from .loss import BCELoss # noqa: F401 +from .loss import KLDivLoss # noqa: F401 +from .loss import MarginRankingLoss # noqa: F401 +from .loss import MultiLabelSoftMarginLoss +from .loss import CTCLoss # noqa: F401 +from .loss import SmoothL1Loss # noqa: F401 +from .loss import HingeEmbeddingLoss # noqa: F401 +from .loss import TripletMarginWithDistanceLoss +from .loss import TripletMarginLoss +from .loss import SoftMarginLoss +from .norm import BatchNorm1D # noqa: F401 +from .norm import BatchNorm2D # noqa: F401 +from .norm import BatchNorm3D # noqa: F401 +from .norm import SyncBatchNorm # noqa: F401 +from .norm import GroupNorm # noqa: F401 +from .norm import LayerNorm # noqa: F401 +from .norm import SpectralNorm # noqa: F401 +from .norm import LocalResponseNorm # noqa: F401 + +from .vision import PixelShuffle # noqa: F401 +from .vision import PixelUnshuffle # noqa: F401 +from .vision import ChannelShuffle # noqa: F401 +from .distance import PairwiseDistance # noqa: F401 +from .container import LayerDict # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/activation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..6736a9a6128627319ab248ccccbdc348b13a4e14 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/activation.py @@ -0,0 +1,1505 @@ +# 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. + +# TODO: define activation functions of neural network + +from ...framework import ParamAttr +from ..initializer import Constant +from paddle.framework import get_default_dtype +from .. import functional as F +from paddle.nn import Layer + +__all__ = [] + + +class CELU(Layer): + r""" + CELU Activation. + + .. math:: + + CELU(x) = max(0, x) + min(0, \alpha * (e^{x/\alpha}-1)) + + Parameters: + alpha (float, optional): The 'alpha' value of the CELU formulation. Default is 1.0. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1. ,6.], [1., 15.6]]) + m = paddle.nn.CELU(0.2) + out = m(x) + # [[-0.19865242, 6. ], + # [ 1. , 15.60000038]] + """ + + def __init__(self, alpha=1.0, name=None): + super(CELU, self).__init__() + self._alpha = alpha + self._name = name + + def forward(self, x): + return F.celu(x, self._alpha, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'alpha={}{}'.format(self._alpha, name_str) + + +class ELU(Layer): + r""" + ELU Activation. + + .. math:: + + ELU(x)= + \left\{ + \begin{array}{lcl} + x,& &\text{if } \ x > 0 \\ + alpha * (e^{x} - 1),& &\text{if } \ x <= 0 + \end{array} + \right. + + Parameters: + alpha (float, optional): The 'alpha' value of the ELU formulation. Default is 1.0. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1. ,6.], [1., 15.6]]) + m = paddle.nn.ELU(0.2) + out = m(x) + # [[-0.12642411 6. ] + # [ 1. 15.6 ]] + """ + + def __init__(self, alpha=1.0, name=None): + super(ELU, self).__init__() + self._alpha = alpha + self._name = name + + def forward(self, x): + return F.elu(x, self._alpha, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'alpha={}{}'.format(self._alpha, name_str) + + +class GELU(Layer): + r""" + GELU Activation. + + If approximate is True + + .. math:: + + GELU(x) = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3}))) + + else + + .. math:: + + GELU(x) = 0.5 * x * (1 + erf(\frac{x}{\sqrt{2}})) + + Parameters: + approximate (bool, optional): Wether to enable approximation. Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1, 0.5],[1, 1.5]]) + + m = paddle.nn.GELU() + out = m(x) # [-0.158655 0.345731 0.841345 1.39979] + + m = paddle.nn.GELU(True) + out = m(x) # [-0.158808 0.345714 0.841192 1.39957] + """ + + def __init__(self, approximate=False, name=None): + super(GELU, self).__init__() + self._approximate = approximate + self._name = name + + def forward(self, x): + return F.gelu(x, self._approximate, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'approximate={}{}'.format(self._approximate, name_str) + + +class Hardshrink(Layer): + r""" + Hardshrink Activation + + .. math:: + + hardshrink(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x > threshold \\ + x, & & if \ x < -threshold \\ + 0, & & if \ others + \end{array} + \right. + + Parameters: + threshold (float, optional): The value of threshold for hardthrink. Default is 0.5 + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-1, 0.3, 2.5]) + m = paddle.nn.Hardshrink() + out = m(x) # [-1., 0., 2.5] + """ + + def __init__(self, threshold=0.5, name=None): + super(Hardshrink, self).__init__() + self._threshold = threshold + self._name = name + + def forward(self, x): + return F.hardshrink(x, self._threshold, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'threshold={}{}'.format(self._threshold, name_str) + + +class Hardswish(Layer): + r""" + Hardswish activation. Create a callable object of `Hardswish`. Hardswish + is proposed in MobileNetV3, and performs better in computational stability + and efficiency compared to swish function. For more details please refer + to: https://arxiv.org/pdf/1905.02244.pdf + + .. math:: + + Hardswish(x)= + \left\{ + \begin{array}{cll} + 0 &, & \text{if } x \leq -3 \\ + x &, & \text{if } x \geq 3 \\ + \frac{x(x+3)}{6} &, & \text{otherwise} + \end{array} + \right. + + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-4., 5., 1.]) + m = paddle.nn.Hardswish() + out = m(x) # [0., 5., 0.666667] + """ + + def __init__(self, name=None): + super(Hardswish, self).__init__() + self._name = name + + def forward(self, x): + return F.hardswish(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Tanh(Layer): + r""" + Tanh Activation. + + .. math:: + Tanh(x) = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}} + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + m = paddle.nn.Tanh() + out = m(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.37994894, -0.19737533, 0.09966800, 0.29131261]) + """ + + def __init__(self, name=None): + super(Tanh, self).__init__() + self._name = name + + def forward(self, x): + return F.tanh(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Hardtanh(Layer): + r""" + Hardtanh Activation. Create a callable object of `Hardtanh`. + + .. math:: + + Hardtanh(x)= + \left\{ + \begin{array}{cll} + max,& & \text{if } x > max \\ + min,& & \text{if } x < min \\ + x,& & \text{otherwise} + \end{array} + \right. + + + Parameters: + min (float, optional): The value of min for Hardtanh. Default is -1. + max (float, optional): The value of max for Hardtanh. Default is 1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-1.5, 0.3, 2.5]) + m = paddle.nn.Hardtanh() + out = m(x) # [-1., 0.3, 1.] + """ + + def __init__(self, min=-1.0, max=1.0, name=None): + super(Hardtanh, self).__init__() + self._min = min + self._max = max + self._name = name + + def forward(self, x): + return F.hardtanh(x, self._min, self._max, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'min={}, max={}{}'.format(self._min, self._max, name_str) + + +class PReLU(Layer): + """ + PReLU Activation. + + .. math:: + + PReLU(x) = max(0, x) + weight * min(0, x) + + Parameters: + num_parameters (int, optional): Number of `weight` to learn. The supported values are: + 1 - a single parameter `alpha` is used for all input channels; + Number of channels - a separate `alpha` is used for each input channel. + Default is 1. + init (float, optional): Init value of learnable `weight`. Default is 0.25. + weight_attr(ParamAttr, optional): The parameter attribute for the learnable `weight`. + Default is None. For more information, please refer to :ref:`api_paddle_ParamAttr`. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + data_format(str, optional): Data format that specifies the layout of input. + It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW". + + Shape: + - input: Tensor with any shape. Default dtype is float32. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + paddle.set_default_dtype("float64") + + data = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0], + [ 3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[ 1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [ 6.0, 7.0, 8.0, 9.0]]]]) + + m = paddle.nn.PReLU(1, 0.25) + out = m(data) + print(out) + # [[[[-0.5 , 3. , -1. , 5. ], + # [ 3. , -1. , 5. , -1.5 ], + # [-1.75, -2. , 8. , 9. ]], + # [[ 1. , -0.5 , -0.75, 4. ], + # [-1.25, 6. , 7. , -2. ], + # [ 6. , 7. , 8. , 9. ]]]] + """ + + def __init__( + self, + num_parameters=1, + init=0.25, + weight_attr=None, + data_format="NCHW", + name=None, + ): + super(PReLU, self).__init__() + self._num_parameters = num_parameters + self._init = init + self._weight_attr = weight_attr + self._name = name + self._data_format = data_format + + self._weight = self.create_parameter( + attr=self._weight_attr, + shape=[self._num_parameters], + dtype=get_default_dtype(), + is_bias=False, + default_initializer=Constant(self._init), + ) + + def forward(self, x): + return F.prelu(x, self._weight, data_format=self._data_format) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'num_parameters={}, data_format={}, init={}, dtype={}{}'.format( + self._num_parameters, + self._data_format, + self._init, + self._dtype, + name_str, + ) + + +class RReLU(Layer): + r""" + RReLU activation layer. + + Applies the randomized leaky rectified liner unit function to improve generalization performance, + as described in the paper: + `Empirical Evaluation of Rectified Activations in Convolutional Network `_ + + During training, randomly samples the negative slope for activation values as described below: + + .. math:: + + RReLU(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + a * x, & & otherwise \\ + \end{array} + \right. + + where :math:`x` is the input tensor, + :math:`a` is randomly sampled from uniform distribution in range (:math:`lower`, :math:`upper`), + + In the test phase, the negative slope will take the average value of :math:`lower` and :math:`upper`: + + .. math:: + + RReLU(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + (lower + upper) * 0.5 * x, & & otherwise \\ + \end{array} + \right. + + where :math:`x` is the input tensor, + :math:`lower` and :math:`upper` are the bounds of uniform distribution. + + Parameters: + lower (float, optional): The lower bound of uniform distribution. Default: 0.125. + upper (float, optional): The upper bound of uniform distribution. Default: 0.333. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. Default dtype is float32. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + input_tensor = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0], + [ 3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[ 1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [ 6.0, 7.0, 8.0, 9.0]]]], dtype='float32') + + rrelu_layer = paddle.nn.RReLU(0.1, 0.3) + out = rrelu_layer(input_tensor) + print(out) + #[[[[-0.20000899 3. -0.88108218 5. ] + # [ 3. -0.55175185 5. -1.07761011] + # [-1.06806871 -1.98962009 8. 9. ]] + # [[ 1. -0.52382672 -0.65515128 4. ] + # [-1.37663394 6. 7. -2.34657836] + # [ 6. 7. 8. 9. ]]]] + """ + + def __init__(self, lower=1.0 / 8.0, upper=1.0 / 3.0, name=None): + super(RReLU, self).__init__() + self._lower = lower + self._upper = upper + self._name = name + + def forward(self, x): + return F.rrelu( + x, lower=self._lower, upper=self._upper, training=self.training + ) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'lower={}, upper={}, training={}, dtype={}{}'.format( + self._lower, self._upper, self.training, self._dtype, name_str + ) + + +class ReLU(Layer): + """ + ReLU Activation. + + .. math:: + + ReLU(x) = max(x, 0) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-2., 0., 1.]) + m = paddle.nn.ReLU() + out = m(x) + print(out) + # [0., 0., 1.] + """ + + def __init__(self, name=None): + super(ReLU, self).__init__() + self._name = name + + def forward(self, x): + return F.relu(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class ReLU6(Layer): + """ + ReLU6 Activation + + .. math:: + + ReLU6(x) = min(max(0,x), 6) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-1., 0.3, 6.5]) + m = paddle.nn.ReLU6() + out = m(x) + print(out) + # [0, 0.3, 6] + """ + + def __init__(self, name=None): + super(ReLU6, self).__init__() + self._name = name + + def forward(self, x): + return F.relu6(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class SELU(Layer): + r""" + SELU Activation + + .. math:: + + SELU(x)= scale * + \left\{ + \begin{array}{lcl} + x,& &\text{if } \ x > 0 \\ + alpha * e^{x} - alpha,& &\text{if } \ x <= 0 + \end{array} + \right. + + Parameters: + scale (float, optional): The value of scale(must be greater than 1.0) for SELU. Default is 1.0507009873554804934193349852946 + alpha (float, optional): The value of alpha(must be no less than zero) for SELU. Default is 1.6732632423543772848170429916717 + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0.0, 1.0],[2.0, 3.0]]) + m = paddle.nn.SELU() + out = m(x) + print(out) + # [[0, 1.050701],[2.101402, 3.152103]] + """ + + def __init__( + self, + scale=1.0507009873554804934193349852946, + alpha=1.6732632423543772848170429916717, + name=None, + ): + super(SELU, self).__init__() + self._scale = scale + self._alpha = alpha + self._name = name + + def forward(self, x): + return F.selu(x, self._scale, self._alpha, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'scale={:.16f}, alpha={:.16f}{}'.format( + self._scale, self._alpha, name_str + ) + + +class LeakyReLU(Layer): + r""" + Leaky ReLU Activation. Create a callable object of `LeakyReLU` to calculate + the `LeakyReLU` of input `x`. + + .. math:: + + LeakyReLU(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + negative\_slope * x, & & otherwise \\ + \end{array} + \right. + + + Parameters: + negative_slope (float, optional): Slope of the activation function at + :math:`x < 0` . Default is 0.01. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + m = paddle.nn.LeakyReLU() + x = paddle.to_tensor([-2.0, 0, 1]) + out = m(x) # [-0.02, 0., 1.] + """ + + def __init__(self, negative_slope=0.01, name=None): + super(LeakyReLU, self).__init__() + self._negative_slope = negative_slope + self._name = name + + def forward(self, x): + return F.leaky_relu(x, self._negative_slope, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'negative_slope={}{}'.format(self._negative_slope, name_str) + + +class Sigmoid(Layer): + r""" + this interface is used to construct a callable object of the ``Sigmoid`` class. This layer calcluate the `sigmoid` of input x. + + .. math:: + + sigmoid(x) = \frac{1}{1 + e^{-x}} + + Parameters: + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Shape: + x: N-D tensor, available dtype is float16, float32, float64. + + Returns: + A callable object of Sigmoid. + + Examples: + + .. code-block:: python + + import paddle + + m = paddle.nn.Sigmoid() + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = m(x) # [0.7310586, 0.880797, 0.95257413, 0.98201376] + """ + + def __init__(self, name=None): + super(Sigmoid, self).__init__() + self.name = name + + def forward(self, x): + return F.sigmoid(x, self.name) + + def extra_repr(self): + name_str = 'name={}'.format(self.name) if self.name else '' + return name_str + + +class Hardsigmoid(Layer): + r""" + ``Hardsigmoid`` Activiation Layers, Construct a callable object of + the ``Hardsigmoid`` class. This layer calcluate the `hardsigmoid` of input x. + + A 3-part piecewise linear approximation of sigmoid(https://arxiv.org/abs/1603.00391), + which is much faster than sigmoid. + + .. math:: + + Hardsigmoid(x)= + \left\{ + \begin{array}{rcl} + 0, & & \text{if } \ x \leq -3 \\ + 1, & & \text{if } \ x \geq 3 \\ + x/6 + 1/2, & & \text{otherwise} + \end{array} + \right. + + Parameters: + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + x: N-D tensor, available dtype is float32, float64. + + Returns: + A callable object of Hardsigmoid. + + Examples: + + .. code-block:: python + + import paddle + + m = paddle.nn.Hardsigmoid() + x = paddle.to_tensor([-4., 5., 1.]) + out = m(x) # [0., 1, 0.666667] + """ + + def __init__(self, name=None): + super(Hardsigmoid, self).__init__() + self.name = name + + def forward(self, x): + return F.hardsigmoid(x, name=self.name) + + def extra_repr(self): + name_str = 'name={}'.format(self.name) if self.name else '' + return name_str + + +class Softplus(Layer): + r""" + Softplus Activation + + .. math:: + softplus(x)=\begin{cases} + \frac{1}{\beta} * \log(1 + e^{\beta * x}),&x\leqslant\frac{\varepsilon}{\beta};\\ + x,&x>\frac{\varepsilon}{\beta}. + \end{cases} + + Parameters: + beta (float, optional): The value of :math:`\beta` for Softplus. Default is 1 + threshold (float, optional): The value of :math:`\varepsilon` for Softplus. Default is 20 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3], dtype='float32') + m = paddle.nn.Softplus() + out = m(x) # [0.513015, 0.598139, 0.744397, 0.854355] + """ + + def __init__(self, beta=1, threshold=20, name=None): + super(Softplus, self).__init__() + self._beta = beta + self._threshold = threshold + self._name = name + + def forward(self, x): + return F.softplus(x, self._beta, self._threshold, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'beta={}, threshold={}{}'.format( + self._beta, self._threshold, name_str + ) + + +class Softshrink(Layer): + r""" + Softshrink Activation + + .. math:: + + Softshrink(x)= + \left\{ + \begin{array}{rcl} + x - threshold,& & \text{if } x > threshold \\ + x + threshold,& & \text{if } x < -threshold \\ + 0,& & \text{otherwise} + \end{array} + \right. + + + Parameters: + threshold (float, optional): The value of threshold(must be no less than zero) for softplus. Default is 0.5 + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.9, -0.2, 0.1, 0.8]) + m = paddle.nn.Softshrink() + out = m(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.39999998, 0. , 0. , 0.30000001]) + """ + + def __init__(self, threshold=0.5, name=None): + super(Softshrink, self).__init__() + self._threshold = threshold + self._name = name + + def forward(self, x): + return F.softshrink(x, self._threshold, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'threshold={}{}'.format(self._threshold, name_str) + + +class Softsign(Layer): + r""" + Softsign Activation + + .. math:: + + Softsign(x) = \frac{x}{1 + |x|} + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + m = paddle.nn.Softsign() + out = m(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.28571430, -0.16666666, 0.09090909, 0.23076925]) + """ + + def __init__(self, name=None): + super(Softsign, self).__init__() + self._name = name + + def forward(self, x): + return F.softsign(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Swish(Layer): + r""" + Swish Activation. + + .. math:: + + Swish(x) = \frac{x}{1 + e^{-x}} + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-2., 0., 1.]) + m = paddle.nn.Swish() + out = m(x) + print(out) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.23840584, 0. , 0.73105854]) + """ + + def __init__(self, name=None): + super(Swish, self).__init__() + self._name = name + + def forward(self, x): + return F.swish(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Mish(Layer): + r""" + Mish Activation. + + .. math:: + + softplus(x) = \begin{cases} + x, \text{if } x > \text{threshold} \\ + \ln(1 + e^{x}), \text{otherwise} + \end{cases} + + Mish(x) = x * \tanh(softplus(x)) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-5., 0., 5.]) + m = paddle.nn.Mish() + out = m(x) # [-0.03357624, 0., 4.99955208] + + """ + + def __init__(self, name=None): + super(Mish, self).__init__() + self._name = name + + def forward(self, x): + return F.mish(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Tanhshrink(Layer): + """ + Tanhshrink Activation + + .. math:: + + Tanhshrink(x) = x - tanh(x) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + m = paddle.nn.Tanhshrink() + out = m(x) + print(out) + # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-0.02005106, -0.00262468, 0.00033200, 0.00868741]) + """ + + def __init__(self, name=None): + super(Tanhshrink, self).__init__() + self._name = name + + def forward(self, x): + return F.tanhshrink(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class ThresholdedReLU(Layer): + r""" + Thresholded ReLU Activation + + .. math:: + + ThresholdedReLU(x) = + \left\{ + \begin{array}{rl} + x,& \text{if } \ x > threshold \\ + 0,& \text{otherwise} + \end{array} + \right. + + + Parameters: + threshold (float, optional): The value of threshold for ThresholdedReLU. Default is 1.0 + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2., 0., 1.]) + m = paddle.nn.ThresholdedReLU() + out = m(x) + print(out) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2., 0., 0.]) + """ + + def __init__(self, threshold=1.0, name=None): + super(ThresholdedReLU, self).__init__() + self._threshold = threshold + self._name = name + + def forward(self, x): + return F.thresholded_relu(x, self._threshold, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'threshold={}{}'.format(self._threshold, name_str) + + +class Silu(Layer): + r""" + Silu Activation + + .. math:: + + silu(x) = \frac{x}{1 + \mathrm{e}^{-x}} + + Where :math:`x` is the input Tensor. + + Parameters: + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + m = paddle.nn.Silu() + out = m(x) # [ 0.731059, 1.761594, 2.857722, 3.928055 ] + """ + + def __init__(self, name=None): + super(Silu, self).__init__() + self._name = name + + def forward(self, x): + return F.silu(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class LogSigmoid(Layer): + r""" + LogSigmoid Activation. + + .. math:: + + LogSigmoid(x) = log \frac{1}{1 + e^{-x}} + + Parameters: + x (Tensor): The input Tensor with data type float32, or float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + m = paddle.nn.LogSigmoid() + out = m(x) # [-0.313262 -0.126928 -0.0485874 -0.0181499] + """ + + def __init__(self, name=None): + super(LogSigmoid, self).__init__() + self._name = name + + def forward(self, x): + return F.log_sigmoid(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Softmax(Layer): + r""" + Softmax Activation. + + This operator implements the softmax layer. The calculation process is as follows: + + 1. The dimension :attr:`axis` of ``x`` will be permuted to the last. + + 2. Then ``x`` will be logically flattened to a 2-D matrix. The matrix's second + dimension(row length) is the same as the dimension :attr:`axis` of ``x``, + and the first dimension(column length) is the product of all other dimensions + of ``x``. For each row of the matrix, the softmax operator squashes the + K-dimensional(K is the width of the matrix, which is also the size of ``x``'s + dimension :attr:`axis`) vector of arbitrary real values to a K-dimensional + vector of real values in the range [0, 1] that add up to 1. + + 3. After the softmax operation is completed, the inverse operations of steps 1 and 2 + are performed to restore the two-dimensional matrix to the same dimension as the ``x`` . + + It computes the exponential of the given dimension and the sum of exponential + values of all the other dimensions in the K-dimensional vector input. + Then the ratio of the exponential of the given dimension and the sum of + exponential values of all the other dimensions is the output of the softmax + operator. + + For each row :math:`i` and each column :math:`j` in the matrix, we have: + + .. math:: + + Softmax[i, j] = \frac{\exp(x[i, j])}{\sum_j(exp(x[i, j])} + + Example: + + .. code-block:: text + + Case 1: + Input: + x.shape = [2, 3, 4] + x.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + + Attrs: + axis = -1 + + Output: + out.shape = [2, 3, 4] + out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.07232949, 0.19661193, 0.19661193, 0.53444665]], + [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] + + Case 2: + Input: + x.shape = [2, 3, 4] + x.data = [[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]] + Attrs: + axis = 1 + + Output: + out.shape = [2, 3, 4] + out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783], + [0.01786798, 0.01786798, 0.04661262, 0.04661262], + [0.97555875, 0.97555875, 0.93623955, 0.93623955]], + [[0.00490169, 0.00490169, 0.00490169, 0.00490169], + [0.26762315, 0.26762315, 0.26762315, 0.26762315], + [0.72747516, 0.72747516, 0.72747516, 0.72747516]]] + + Parameters: + axis (int, optional): The axis along which to perform log_softmax + calculations. It should be in range [-D, D), where D is the + dimensions of ``x`` . If ``axis`` < 0, it works the same way as + :math:`axis + D` . Default is -1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0], + [3.0, 4.0, 5.0, 6.0], + [7.0, 8.0, 8.0, 9.0]], + [[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [6.0, 7.0, 8.0, 9.0]]], dtype='float32') + m = paddle.nn.Softmax() + out = m(x) + # [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.07232949, 0.19661193, 0.19661193, 0.53444665]], + # [[0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426], + # [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]] + """ + + def __init__(self, axis=-1, name=None): + super(Softmax, self).__init__() + self._axis = axis + self._dtype = None + self._name = name + + def forward(self, x): + return F.softmax(x, self._axis, self._dtype, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'axis={}{}'.format(self._axis, name_str) + + +class LogSoftmax(Layer): + r""" + This operator implements the log_softmax layer. The calculation process is as follows: + + .. math:: + + \begin{array} {rcl} + Out[i, j] &= &log(softmax(x)) \\ + &= &log(\frac{\exp(X[i, j])}{\sum_j(\exp(X[i, j])}) + \end{array} + + Parameters: + axis (int, optional): The axis along which to perform log_softmax + calculations. It should be in range [-D, D), where D is the + dimensions of the input Tensor . If ``axis`` < 0, it works the + same way as :math:`axis + D` . Default is -1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Tensor with any shape. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = [[[-2.0, 3.0, -4.0, 5.0], + [3.0, -4.0, 5.0, -6.0], + [-7.0, -8.0, 8.0, 9.0]], + [[1.0, -2.0, -3.0, 4.0], + [-5.0, 6.0, 7.0, -8.0], + [6.0, 7.0, 8.0, 9.0]]] + m = paddle.nn.LogSoftmax() + x = paddle.to_tensor(x) + out = m(x) + # [[[ -7.1278396 -2.1278396 -9.127839 -0.12783948] + # [ -2.1270514 -9.127051 -0.12705144 -11.127051 ] + # [-16.313261 -17.313261 -1.3132617 -0.31326184]] + # [[ -3.0518122 -6.051812 -7.051812 -0.051812 ] + # [-12.313267 -1.3132664 -0.3132665 -15.313267 ] + # [ -3.4401896 -2.4401896 -1.4401896 -0.44018966]]] + """ + + def __init__(self, axis=-1, name=None): + super(LogSoftmax, self).__init__() + self._axis = axis + self._name = name + + def forward(self, x): + return F.log_softmax(x, self._axis) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'axis={}{}'.format(self._axis, name_str) + + +class Maxout(Layer): + r""" + Maxout Activation. Create a callable object of `Maxout`. + + Assumed the input shape is (N, Ci, H, W). + The output shape is (N, Co, H, W). + Then Co = Ci/groups and the operator formula is as follows: + + .. math:: + + \begin{array}{l} + &out_{si+j} = \max_{k} x_{gsi + sk + j} \\ + &g = groups \\ + &s = \frac{input.size}{num\_channels} \\ + &0 \le i < \frac{num\_channels}{groups} \\ + &0 \le j < s \\ + &0 \le k < groups + \end{array} + + Parameters: + groups (int, optional): The groups number of maxout. `groups` specifies the + index of channel dimension where maxout will be performed. This must be + a factor of number of features. Default is 1. + axis (int, optional): The axis along which to perform maxout calculations. + It should be 1 when data format is NCHW, be -1 or 3 when data format + is NHWC. If ``axis`` < 0, it works the same way as :math:`axis + D` , + where D is the dimensions of ``x`` . Default is 1. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: :math:`(N, C_{in}, H_{in}, W_{in})` + - output: :math:`(N, C_{out}, H_{out}, W_{out})` + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([1, 2, 3, 4]) + # [[[[0.5002636 0.22272532 0.17402348 0.2874594 ] + # [0.95313174 0.6228939 0.7129065 0.7087491 ] + # [0.02879342 0.88725346 0.61093384 0.38833922]] + # [[0.5231306 0.03807496 0.91661984 0.15602879] + # [0.666127 0.616567 0.30741522 0.24044901] + # [0.7142536 0.7351477 0.31588817 0.23782359]]]] + m = paddle.nn.Maxout(groups=2) + out = m(x) + # [[[[0.5231306 0.22272532 0.91661984 0.2874594 ] + # [0.95313174 0.6228939 0.7129065 0.7087491 ] + # [0.7142536 0.88725346 0.61093384 0.38833922]]]] + """ + + def __init__(self, groups, axis=1, name=None): + super(Maxout, self).__init__() + self._groups = groups + self._axis = axis + self._name = name + + def forward(self, x): + return F.maxout(x, self._groups, self._axis, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'groups={}, axis={}{}'.format(self._groups, self._axis, name_str) + + +class Softmax2D(Layer): + r""" + + Softmax2D Activation. + Given a Tensor with shape (B, C, H, W) or (C, H, W), it will apply Softmax to each location (C, h_i, w_j). + The sum of result in each location (C, H_i, W_j) will be one. + + Shape: + - Input: :math:`(B, C, H, W)` or :math:`(C, H, W)` + - Output: :math:`(B, C, H, W)` or :math:`(C, H, W)` (same as input) + + Returns: + A Tensor of the same shape and dtype as input with value in range [0, 1]. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([1, 2, 3, 4]) + # [[[[0.42496058 0.1172187 0.14664008 0.8151267 ] + # [0.24430142 0.42052492 0.60372984 0.79307914] + # [0.4539401 0.90458065 0.10235776 0.62009853]] + + # [[0.11731581 0.16053623 0.05667042 0.91876775] + # [0.9413854 0.30770817 0.6788164 0.9543593 ] + # [0.4145064 0.75909156 0.11598814 0.73599935]]]] + m = paddle.nn.Softmax2D() + out = m(x) + # [[[[0.5763103 0.48917228 0.5224772 0.4741129 ] + # [0.3324591 0.5281743 0.48123717 0.45976716] + # [0.5098571 0.5363083 0.49659243 0.4710572 ]] + + # [[0.42368975 0.51082766 0.47752273 0.5258871 ] + # [0.66754097 0.47182566 0.5187628 0.5402329 ] + # [0.49014282 0.46369177 0.50340754 0.5289428 ]]]] + + """ + + def __init__(self, name=None): + super(Softmax2D, self).__init__() + self._dtype = None + self._name = name + + def forward(self, x): + assert ( + x.ndim == 3 or x.ndim == 4 + ), "Softmax2D requires a 3D or 4D tensor as input. Received: {}D.".format( + x.ndim + ) + return F.softmax(x, axis=-3, dtype=self._dtype, name=self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/common.py new file mode 100644 index 0000000000000000000000000000000000000000..45c08bf2b4d10e7e2a2da5d39ef05f2d18af9d40 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/common.py @@ -0,0 +1,1707 @@ +# 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. + +# TODO: define the common classes to build a neural network +import paddle +from ...fluid.dygraph import Flatten # noqa: F401 +from .. import functional as F +from ...fluid.framework import _dygraph_tracer +from paddle.nn import Layer +from paddle import in_dynamic_mode + +__all__ = [] + + +def _npairs(x, n): + if isinstance(x, (paddle.Tensor, list, tuple)): + return x + x = [x] * (n * 2) + return x + + +class Identity(Layer): + r""" + + A placeholder identity operator that is argument-insensitive. For each input :math:`X` , + the output :math:`Out` is: + + .. math:: + + Out = X + + Parameters: + args: any argument (unused) + kwargs: any keyword argument (unused) + + Shape: + - input: Multi-dimentional tensor with shape :math:`[batch\_size, n1, n2, ...]` . + - output: Multi-dimentional tensor with shape :math:`[batch\_size, n1, n2, ...]` . + + Examples: + .. code-block:: python + + import paddle + + input_tensor = paddle.randn(shape=[3, 2]) + layer = paddle.nn.Identity() + out = layer(input_tensor) + # input_tensor: [[-0.32342386 -1.200079 ] + # [ 0.7979031 -0.90978354] + # [ 0.40597573 1.8095392 ]] + # out: [[-0.32342386 -1.200079 ] + # [ 0.7979031 -0.90978354] + # [ 0.40597573 1.8095392 ]] + + + """ + + def __init__(self, *args, **kwargs): + super(Identity, self).__init__() + + def forward(self, input): + return input + + +class Linear(Layer): + r""" + + Fully-connected linear transformation layer. For each input :math:`X` , + the equation is: + + .. math:: + + Out = XW + b + + where :math:`W` is the weight and :math:`b` is the bias. + + Linear layer takes only one multi-dimensional tensor as input with the + shape :math:`[batch\_size, *, in\_features]` , where :math:`*` means any + number of additional dimensions. It multiplies input tensor with the weight + (a 2-D tensor of shape :math:`[in\_features, out\_features]` ) and produces + an output tensor of shape :math:`[batch\_size, *, out\_features]` . + If :math:`bias\_attr` is not False, the bias (a 1-D tensor of + shape :math:`[out\_features]` ) will be created and added to the output. + + Parameters: + in_features (int): The number of input units. + out_features (int): The number of output units. + weight_attr (ParamAttr, optional): The attribute for the learnable + weight of this layer. The default value is None and the weight will be + initialized to zero. For detailed information, please refer to + paddle.ParamAttr. + bias_attr (ParamAttr|bool, optional): The attribute for the learnable bias + of this layer. If it is set to False, no bias will be added to the output. + If it is set to None or one kind of ParamAttr, a bias parameter will + be created according to ParamAttr. For detailed information, please refer + to paddle.ParamAttr. The default value is None and the bias will be + initialized to zero. + name (str, optional): Normally there is no need for user to set this parameter. + For detailed information, please refer to :ref:`api_guide_Name` . + + Attribute: + **weight** (Parameter): the learnable weight of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + - input: Multi-dimentional tensor with shape :math:`[batch\_size, *, in\_features]` . + - output: Multi-dimentional tensor with shape :math:`[batch\_size, *, out\_features]` . + + Examples: + .. code-block:: python + + import paddle + + # Define the linear layer. + weight_attr = paddle.ParamAttr( + name="weight", + initializer=paddle.nn.initializer.Constant(value=0.5)) + bias_attr = paddle.ParamAttr( + name="bias", + initializer=paddle.nn.initializer.Constant(value=1.0)) + linear = paddle.nn.Linear(2, 4, weight_attr=weight_attr, bias_attr=bias_attr) + # linear.weight: [[0.5 0.5 0.5 0.5] + # [0.5 0.5 0.5 0.5]] + # linear.bias: [1. 1. 1. 1.] + + x = paddle.randn((3, 2), dtype="float32") + # x: [[-0.32342386 -1.200079 ] + # [ 0.7979031 -0.90978354] + # [ 0.40597573 1.8095392 ]] + y = linear(x) + # y: [[0.23824859 0.23824859 0.23824859 0.23824859] + # [0.9440598 0.9440598 0.9440598 0.9440598 ] + # [2.1077576 2.1077576 2.1077576 2.1077576 ]] + """ + + def __init__( + self, + in_features, + out_features, + weight_attr=None, + bias_attr=None, + name=None, + ): + super(Linear, self).__init__() + self._dtype = self._helper.get_default_dtype() + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self.weight = self.create_parameter( + shape=[in_features, out_features], + attr=self._weight_attr, + dtype=self._dtype, + is_bias=False, + ) + self.bias = self.create_parameter( + shape=[out_features], + attr=self._bias_attr, + dtype=self._dtype, + is_bias=True, + ) + self.name = name + + def forward(self, input): + out = F.linear( + x=input, weight=self.weight, bias=self.bias, name=self.name + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'in_features={}, out_features={}, dtype={}{}'.format( + self.weight.shape[0], self.weight.shape[1], self._dtype, name_str + ) + + +class Upsample(Layer): + """ + This op resizes a batch of images. + + The input must be a 3-D Tensor of the shape (num_batches, channels, in_w) + or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape + (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels), + Where in_w is width of the input tensor, in_h is the height of the input tensor, + in_d is the depth of the intput tensor. + and the resizing only applies on the three dimensions(depth, height and width). + + Supporting resample methods: + 'linear' : Linear interpolation + 'bilinear' : Bilinear interpolation + 'trilinear' : Trilinear interpolation + 'nearest' : Nearest neighbor interpolation + 'bicubic' : Bicubic interpolation + + Linear interpolation is the method of using a line connecting two known quantities + to determine the value of an unknown quantity between the two known quantities. + + Nearest neighbor interpolation is to perform nearest neighbor interpolation + in both the 3rd dimension(in height direction) and the 4th dimension(in width + direction) on input tensor. + + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + Bicubic interpolation is an extension of cubic interpolation for interpolating + data points on a two-dimensional regular grid. The interpolated surface is + smoother than corresponding surfaces obtained by bilinear interpolation or + nearest-neighbor interpolation. + + Trilinear interpolation is an extension of linear interpolation for + interpolating functions of three variables (e.g. D-direction, + H-direction and W-direction in this op) on a rectilinear 3D grid. + The linear interpolation is performed on three directions. + align_corners and align_mode are optional parameters,the calculation method + of interpolation can be selected by them. + + Area interpolation is to perform area interpolation + in both the 3rd dimension(in height direction) , the 4th dimension(in width + direction) and the 5th dimension(in depth direction) on input tensor. Set to + area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or + `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`. + + Example: + + .. code-block:: text + + For scale_factor: + if align_corners = True && out_size > 1 : + scale_factor = (in_size-1.0)/(out_size-1.0) + else: + scale_factor = float(in_size/out_size) + + Linear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,W_in) + output: (N,C,W_out) where: + W_out = W_{in} * scale_{factor} + + Nearest neighbor interpolation: + if: + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = floor (H_{in} * scale_{factor}) + W_out = floor (W_{in} * scale_{factor}) + else: + align_corners = True + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = round(H_{in} * scale_{factor}) + W_out = round(W_{in} * scale_{factor}) + + Bilinear interpolation: + if: + align_corners = False , align_mode = 0 + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + Bicubic interpolation: + if: + align_corners = False + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + + else: + input : (N,C,H_in,W_in) + output: (N,C,H_out,W_out) where: + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + Trilinear interpolation: + if: + align_corners = False , align_mode = 0 + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = (D_{in}+0.5) * scale_{factor} - 0.5 + H_out = (H_{in}+0.5) * scale_{factor} - 0.5 + W_out = (W_{in}+0.5) * scale_{factor} - 0.5 + else: + input : (N,C,D_in,H_in,W_in) + output: (N,C,D_out,H_out,W_out) where: + D_out = D_{in} * scale_{factor} + H_out = H_{in} * scale_{factor} + W_out = W_{in} * scale_{factor} + + https://en.wikipedia.org/wiki/Linear_interpolation. + For details of linear interpolation, please refer to Wikipedia: + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation. + + For details of bicubic interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bicubic_interpolation + + For details of trilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Trilinear_interpolation. + + Parameters: + x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + size (list|tuple|Tensor|None): Output shape of image resize + layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w) + when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor. + Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1]. + If a Tensor , its dimensions size should be a 1. + scale_factor (float|Tensor|list|tuple|None): The multiplier for the input height or width. At + least one of :attr:`size` or :attr:`scale_factor` must be set. + And :attr:`size` has a higher priority than :attr:`scale_factor`. Has to match input size if it is either a list or a tuple or a Tensor. + Default: None. + mode (str): The resample method. It supports 'linear', 'nearst', 'bilinear', + 'bicubic' and 'trilinear' currently. Default: 'nearest' + align_corners(bool) : An optional bool, If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the + corner pixels. + Default: False + align_mode(int) : An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above, + it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for + src_idx = scale_factor*dst_index. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + Returns: + A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels), + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels). + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand([2,3,6,10], dtype="float32") + upsample_out = paddle.nn.Upsample(size=[12,12]) + + output = upsample_out(x=input) + print(output.shape) + # [2, 3, 12, 12] + + """ + + def __init__( + self, + size=None, + scale_factor=None, + mode='nearest', + align_corners=False, + align_mode=0, + data_format='NCHW', + name=None, + ): + super(Upsample, self).__init__() + self.size = size + self.scale_factor = scale_factor + self.mode = mode.lower() + self.align_corners = align_corners + self.align_mode = align_mode + self.data_format = data_format + self.name = name + + def forward(self, x): + out = F.interpolate( + x, + size=self.size, + scale_factor=self.scale_factor, + mode=self.mode, + align_corners=self.align_corners, + align_mode=self.align_mode, + data_format=self.data_format, + name=self.name, + ) + + return out + + def extra_repr(self): + if self.scale_factor is not None: + main_str = 'scale_factor={}'.format(self.scale_factor) + else: + main_str = 'size={}'.format(self.size) + name_str = ', name={}'.format(self.name) if self.name else '' + return '{}, mode={}, align_corners={}, align_mode={}, data_format={}{}'.format( + main_str, + self.mode, + self.align_corners, + self.align_mode, + self.data_format, + name_str, + ) + + +class UpsamplingNearest2D(Layer): + """ + This op upsamples a batch of images, using nearest neighbours' pixel values. + The input must be a 4-D Tensor of the shape (num_batches, channels, in_h, in_w), + where in_w is width of the input tensor, in_h is the height of the input tensor. + And the upsampling only applies on the two dimensions(height and width). + Nearest neighbor interpolation is to perform nearest neighbor interpolation + in both the 3rd dimension(in height direction) and the 4th dimension(in width + direction) on input tensor. + + For details of nearest neighbor interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation. + + Parameters: + x (Tensor): 4-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + size (list|tuple|Tensor|None): Output shape of image resize + layer, the shape is (out_h, out_w) when input is a 4-D Tensor. + Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1]. + If a Tensor , its dimensions size should be a 1. + scale_factor (float|int|list|tuple|Tensor|None): The multiplier for the input height or width. At + least one of :attr:`size` or :attr:`scale_factor` must be set. + And :attr:`size` has a higher priority than :attr:`scale_factor`. + Has to match input size if it is either a list or a tuple or a Tensor. + Default: None. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + Returns: + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_data = paddle.rand(shape=(2,3,6,10)).astype("float32") + upsample_out = paddle.nn.UpsamplingNearest2D(size=[12,12]) + input = paddle.to_tensor(input_data) + output = upsample_out(x=input) + print(output.shape) + # [2L, 3L, 12L, 12L] + """ + + def __init__( + self, size=None, scale_factor=None, data_format='NCHW', name=None + ): + super(UpsamplingNearest2D, self).__init__() + self.size = size + self.scale_factor = scale_factor + self.data_format = data_format + self.name = name + + def forward(self, x): + out = F.interpolate( + x, + size=self.size, + scale_factor=self.scale_factor, + mode='nearest', + align_corners=False, + align_mode=0, + data_format=self.data_format, + name=self.name, + ) + + return out + + def extra_repr(self): + if self.scale_factor is not None: + main_str = 'scale_factor={}'.format(self.scale_factor) + else: + main_str = 'size={}'.format(self.size) + name_str = ', name={}'.format(self.name) if self.name else '' + return '{}, data_format={}{}'.format( + main_str, self.data_format, name_str + ) + + +class UpsamplingBilinear2D(Layer): + """ + This op upsamples a batch of images, using bilinear' pixel values. + The input must be a 4-D Tensor of the shape (num_batches, channels, in_h, in_w), + where in_w is width of the input tensor, in_h is the height of the input tensor. + And the upsampling only applies on the two dimensions(height and width). + Bilinear interpolation is an extension of linear interpolation for + interpolating functions of two variables (e.g. H-direction and + W-direction in this op) on a rectilinear 2D grid. The key idea is + to perform linear interpolation first in one direction, and then + again in the other direction. + + For details of bilinear interpolation, please refer to Wikipedia: + https://en.wikipedia.org/wiki/Bilinear_interpolation. + + Parameters: + x (Tensor): 4-D Tensor, its data type is float32, float64, or uint8, + its data format is specified by :attr:`data_format`. + size (list|tuple|Tensor|None): Output shape of image resize + layer, the shape is (out_h, out_w) when input is a 4-D Tensor. + Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1]. + If a Tensor , its dimensions size should be a 1. + scale_factor (float|int|list|tuple|Tensor|None): The multiplier for the input height or width. At + least one of :attr:`size` or :attr:`scale_factor` must be set. + And :attr:`size` has a higher priority than :attr:`scale_factor`. + Has to match input size if it is either a list or a tuple or a Tensor. + Default: None. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, + `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored + in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + Returns: + A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels), + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_data = paddle.rand(shape=(2,3,6,10)).astype("float32") + upsample_out = paddle.nn.UpsamplingBilinear2D(size=[12,12]) + input = paddle.to_tensor(input_data) + output = upsample_out(x=input) + print(output.shape) + # [2L, 3L, 12L, 12L] + """ + + def __init__( + self, size=None, scale_factor=None, data_format='NCHW', name=None + ): + super(UpsamplingBilinear2D, self).__init__() + self.size = size + self.scale_factor = scale_factor + self.data_format = data_format + self.name = name + + def forward(self, x): + out = F.interpolate( + x, + size=self.size, + scale_factor=self.scale_factor, + mode='bilinear', + align_corners=True, + align_mode=0, + data_format=self.data_format, + name=self.name, + ) + + return out + + def extra_repr(self): + if self.scale_factor is not None: + main_str = 'scale_factor={}'.format(self.scale_factor) + else: + main_str = 'size={}'.format(self.size) + name_str = ', name={}'.format(self.name) if self.name else '' + return '{}, data_format={}{}'.format( + main_str, self.data_format, name_str + ) + + +class Bilinear(Layer): + r""" + + This layer performs bilinear on two inputs. + + .. math:: + + out_{i} = x1 * W_{i} * {x2^\mathrm{T}}, i=0,1,...,outfeatures-1 + + out = out + b + + In this formula: + - :math:`x1`: the first input contains in1_features elements, shape is [batch_size, in1_features]. + - :math:`x2`: the second input contains in2_features elements, shape is [batch_size, in2_features]. + - :math:`W_{i}`: the i-th learned weight, shape is [in1_features, in2_features], and learned weight's shape is [out_features, in1_features, in2_features]. + - :math:`out_{i}`: the i-th element of out, shape is [batch_size], and out's shape is [batch_size, out_features]. + - :math:`b`: the learned bias, shape is [1, out_features]. + - :math:`x2^\mathrm{T}`: the transpose of :math:`x2`. + + Parameters: + in1_features (int): The dimension of each first input(`x1`). + in2_features (int): The dimension of each second input(`x2`). + out_features (int): The dimension of output of this layer. + weight_attr (ParamAttr, optional): The parameter attribute for the learnable w, parameters/weights of + this layer. The default value is None. + bias_attr (ParamAttr, optional): The parameter attribute for the bias + of this layer. If it is set to False, no bias will be added to the output units. + If it is set to None, the bias is initialized zero. The default value is None. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None. + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Returns: + Tensor: A 2-D Tensor of shape [batch_size, out_features]. + + Examples: + .. code-block:: python + + import paddle + + layer1 = paddle.rand((5, 5)).astype('float32') + layer2 = paddle.rand((5, 4)).astype('float32') + bilinear = paddle.nn.Bilinear( + in1_features=5, in2_features=4, out_features=1000) + result = bilinear(layer1,layer2) # result shape [5, 1000] + + """ + + def __init__( + self, + in1_features, + in2_features, + out_features, + weight_attr=None, + bias_attr=None, + name=None, + ): + super(Bilinear, self).__init__() + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self._name = name + self._in1_features = in1_features + self._in2_features = in2_features + self._out_features = out_features + self._dtype = self._helper.get_default_dtype() + + weight_shape = [ + self._out_features, + self._in1_features, + self._in2_features, + ] + self.weight = self.create_parameter( + attr=self._weight_attr, + shape=weight_shape, + dtype=self._dtype, + is_bias=False, + ) + bias_shape = [1, self._out_features] + self.bias = self.create_parameter( + attr=self._bias_attr, + shape=bias_shape, + dtype=self._dtype, + is_bias=True, + ) + + def forward(self, x1, x2): + return F.bilinear(x1, x2, self.weight, self.bias, self._name) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'in1_features={}, in2_features={}, out_features={}, dtype={}{}'.format( + self._in1_features, + self._in2_features, + self._out_features, + self._dtype, + name_str, + ) + + +class Dropout(Layer): + """ + Dropout is a regularization technique for reducing overfitting by preventing + neuron co-adaption during training as described in the paper: + `Improving neural networks by preventing co-adaptation of feature detectors `_ + The dropout operator randomly sets the outputs of some units to zero, while upscale others + according to the given dropout probability. + + See ``paddle.nn.functional.dropout`` for more details. + + In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled. + + Parameters: + p (float|int): Probability of setting units to zero. Default: 0.5 + axis (int|list|tuple): The axis along which the dropout is performed. Default None. + mode(str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'] + + 1. upscale_in_train(default), upscale the output at training time + + - train: out = input * mask / ( 1.0 - p ) + - inference: out = input + + 2. downscale_in_infer, downscale the output at inference + + - train: out = input * mask + - inference: out = input * (1.0 - p) + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: N-D tensor. + - output: N-D tensor, the same shape as input. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1,2,3], [4,5,6]], dtype="float32") + m = paddle.nn.Dropout(p=0.5) + + y_train = m(x) + print(y_train) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[2., 0., 6.], + # [0., 0., 0.]]) + + m.eval() # switch the model to test phase + y_test = m(x) + print(y_test) + # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1., 2., 3.], + # [4., 5., 6.]]) + """ + + def __init__(self, p=0.5, axis=None, mode="upscale_in_train", name=None): + super(Dropout, self).__init__() + + self.p = p + self.axis = axis + self.mode = mode + self.name = name + + def forward(self, input): + out = F.dropout( + input, + p=self.p, + axis=self.axis, + training=self.training, + mode=self.mode, + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'p={}, axis={}, mode={}{}'.format( + self.p, self.axis, self.mode, name_str + ) + + +class Dropout2D(Layer): + """ + Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` , + a channel is a 2D feature map with the shape `HW`). Each channel will be zeroed out independently + on every forward call with probability `p` using samples from a Bernoulli distribution. + Dropout2D will help promote independence between feature maps as described in the paper: + `Efficient Object Localization Using Convolutional Networks `_ + + See ``paddle.nn.functional.dropout2d`` for more details. + + In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled. + + Parameters: + p (float, optional): Probability of setting units to zero. Default: 0.5 + data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC`. The default is `NCHW`. When it is `NCHW`, the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: 4-D tensor. + - output: 4-D tensor, the same shape as input. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([2, 2, 1, 3], dtype="float32") + print(x) + # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[0.10052059, 0.93890846, 0.45351565]], + # [[0.47507706, 0.45021373, 0.11331241]]], + + # [[[0.53358698, 0.97375143, 0.34997326]], + # [[0.24758087, 0.52628899, 0.17970420]]]]) + + m = paddle.nn.Dropout2D(p=0.5) + y_train = m(x) + print(y_train) + # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[0. , 0. , 0. ]], + # [[0.95015413, 0.90042746, 0.22662482]]], + + # [[[1.06717396, 1.94750285, 0.69994652]], + # [[0. , 0. , 0. ]]]]) + + m.eval() # switch the model to test phase + y_test = m(x) + print(y_test) + # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[0.10052059, 0.93890846, 0.45351565]], + # [[0.47507706, 0.45021373, 0.11331241]]], + + # [[[0.53358698, 0.97375143, 0.34997326]], + # [[0.24758087, 0.52628899, 0.17970420]]]]) + """ + + def __init__(self, p=0.5, data_format='NCHW', name=None): + super(Dropout2D, self).__init__() + + self.p = p + self.data_format = data_format + self.name = name + + def forward(self, input): + out = F.dropout2d( + input, + p=self.p, + training=self.training, + data_format=self.data_format, + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'p={}, data_format={}{}'.format( + self.p, self.data_format, name_str + ) + + +class Dropout3D(Layer): + """ + Randomly zero out entire channels (in the batched input 5d tensor with the shape `NCDHW` , + a channel is a 3D feature map with the shape `DHW` ). Each channel will be zeroed out independently + on every forward call with probability `p` using samples from a Bernoulli distribution. + Dropout3D will help promote independence between feature maps as described in the paper: + `Efficient Object Localization Using Convolutional Networks `_ + + See ``paddle.nn.functional.dropout3d`` for more details. + + In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled. + + Parameters: + p (float | int): Probability of setting units to zero. Default: 0.5 + data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCDHW` or `NDHWC`. The default is `NCDHW`. When it is `NCDHW`, the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: 5-D tensor. + - output: 5-D tensor, the same shape as input. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(24, dtype="float32").reshape((1, 2, 2, 2, 3)) + print(x) + # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[[0. , 1. , 2. ], + # [3. , 4. , 5. ]], + # [[6. , 7. , 8. ], + # [9. , 10., 11.]]], + + # [[[12., 13., 14.], + # [15., 16., 17.]], + # [[18., 19., 20.], + # [21., 22., 23.]]]]]) + + m = paddle.nn.Dropout3D(p=0.5) + y_train = m(x) + print(y_train) + # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[[0. , 2. , 4. ], + # [6. , 8. , 10.]], + # [[12., 14., 16.], + # [18., 20., 22.]]], + + # [[[0. , 0. , 0. ], + # [0. , 0. , 0. ]], + # [[0. , 0. , 0. ], + # [0. , 0. , 0. ]]]]]) + + m.eval() # switch the model to test phase + y_test = m(x) + print(y_test) + # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[[[0. , 1. , 2. ], + # [3. , 4. , 5. ]], + # [[6. , 7. , 8. ], + # [9. , 10., 11.]]], + + # [[[12., 13., 14.], + # [15., 16., 17.]], + # [[18., 19., 20.], + # [21., 22., 23.]]]]]) + """ + + def __init__(self, p=0.5, data_format='NCDHW', name=None): + super(Dropout3D, self).__init__() + + self.p = p + self.data_format = data_format + self.name = name + + def forward(self, input): + out = F.dropout3d( + input, + p=self.p, + training=self.training, + data_format=self.data_format, + name=self.name, + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'p={}, data_format={}{}'.format( + self.p, self.data_format, name_str + ) + + +class AlphaDropout(Layer): + """ + Alpha Dropout is a type of Dropout that maintains the self-normalizing property. For an input with + zero mean and unit standard deviation, the output of Alpha Dropout maintains the original mean and + standard deviation of the input. Alpha Dropout fits well to SELU activate function by randomly setting + activations to the negative saturation value. + + For more information, please refer to: + `Self-Normalizing Neural Networks `_ + + In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled. + + Parameters: + p (float | int): Probability of setting units to zero. Default: 0.5 + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: N-D tensor. + - output: N-D tensor, the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1, 1], [-1, 1]], dtype="float32") + m = paddle.nn.AlphaDropout(p=0.5) + y_train = m(x) + print(y_train) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[-0.77919382, 1.66559887], + # [-0.77919382, -0.77919382]]) + + m.eval() # switch the model to test phase + y_test = m(x) + print(y_test) + # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[-1., 1.], + # [-1., 1.]]) + """ + + def __init__(self, p=0.5, name=None): + super(AlphaDropout, self).__init__() + self.p = p + self.name = name + + def forward(self, input): + out = F.alpha_dropout( + input, p=self.p, training=self.training, name=self.name + ) + return out + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'p={}{}'.format(self.p, name_str) + + +class Pad1D(Layer): + """ + This interface is used to construct a callable object of the ``Pad1D`` class. + Pad tensor according to 'pad', 'mode' and 'value'. + If mode is 'reflect', pad[0] and pad[1] must be no greater than width-1. + + Parameters: + padding (Tensor|list[int]|int): The padding size with data type int. If is int, use the + same padding in both dimensions. Else [len(padding)/2] dimensions + of input will be padded. The pad has the form (pad_left, pad_right). + mode (str, optional): Four modes: 'constant' (default), 'reflect', 'replicate', 'circular'. Default is 'constant'. + + - 'constant' mode, uses a constant value to pad the input tensor. + - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + - 'replicate' mode, uses input boundaries to pad the input tensor. + - 'circular' mode, uses circular input to pad the input tensor. + + value (float, optional): The value to fill the padded areas. Default is :math:`0.0`。 + data_format (str, optional): An string from: "NCL", "NLC". Specify the data format of the input data. + Default is "NCL" + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_shape = (1, 2, 3) + pad = [1, 2] + mode = "constant" + data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1 + my_pad = nn.Pad1D(padding=pad, mode=mode) + result = my_pad(data) + print(result) + # [[[0. 1. 2. 3. 0. 0.] + # [0. 4. 5. 6. 0. 0.]]] + """ + + def __init__( + self, padding, mode='constant', value=0.0, data_format="NCL", name=None + ): + super(Pad1D, self).__init__() + self._pad = _npairs(padding, 1) + self._mode = mode + self._value = value + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.pad( + x, + pad=self._pad, + mode=self._mode, + value=self._value, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'padding={}, mode={}, value={}, data_format={}{}'.format( + self._pad, self._mode, self._value, self._data_format, name_str + ) + + +class Pad2D(Layer): + """ + This interface is used to construct a callable object of the ``Pad2D`` class. + Pad tensor according to 'pad', 'mode' and 'value'. + If mode is 'reflect', pad[0] and pad[1] must be no greater + than width-1. The height dimension has the same condition. + + Parameters: + padding (Tensor|list[int]|int): The padding size with data type int. If is int, use the + same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded. + The pad has the form (pad_left, pad_right, pad_top, pad_bottom). + mode (str, optional): Four modes: 'constant' (default), 'reflect', 'replicate', 'circular'. Default is 'constant'. + + - 'constant' mode, uses a constant value to pad the input tensor. + - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + - 'replicate' mode, uses input boundaries to pad the input tensor. + - 'circular' mode, uses circular input to pad the input tensor. + + value (float, optional): The value to fill the padded areas. Default is :math:`0.0`。 + data_format (str, optional): An string from: "NCHW", "NHWC". Specify the data format of the input data. + Default is "NCHW"。 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_shape = (1, 1, 2, 3) + pad = [1, 0, 1, 2] + mode = "constant" + data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1 + my_pad = nn.Pad2D(padding=pad, mode=mode) + result = my_pad(data) + print(result) + # [[[[0. 0. 0. 0.] + # [0. 1. 2. 3.] + # [0. 4. 5. 6.] + # [0. 0. 0. 0.] + # [0. 0. 0. 0.]]]] + """ + + def __init__( + self, padding, mode='constant', value=0.0, data_format="NCHW", name=None + ): + super(Pad2D, self).__init__() + self._pad = _npairs(padding, 2) + self._mode = mode + self._value = value + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.pad( + x, + pad=self._pad, + mode=self._mode, + value=self._value, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'padding={}, mode={}, value={}, data_format={}{}'.format( + self._pad, self._mode, self._value, self._data_format, name_str + ) + + +class ZeroPad2D(Layer): + """ + This interface is used to construct a callable object of the ``ZeroPad2D`` class. + Pads the input tensor boundaries with zero. + + Parameters: + padding (Tensor | List[int] | int): The padding size with data type int. If is int, use the + same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded. + The pad has the form (pad_left, pad_right, pad_top, pad_bottom). + data_format (str): An string from: "NCHW", "NHWC". Specify the data format of the input data. + Default is "NCHW" + name (str, optional) : The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - x(Tensor): The input tensor of zeropad2d operator, which is a 4-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of zeropad2d operator, which is a 4-D tensor. + The data type is same as input x. + + Examples: + Examples are as follows. + + .. code-block:: python + + import paddle + import paddle.nn as nn + import numpy as np + + input_shape = (1, 1, 2, 3) + pad = [1, 0, 1, 2] + data = paddle.arange(np.prod(input_shape), dtype="float32").reshape(input_shape) + 1 + + my_pad = nn.ZeroPad2D(padding=pad) + result = my_pad(data) + + print(result) + # [[[[0. 0. 0. 0.] + # [0. 1. 2. 3.] + # [0. 4. 5. 6.] + # [0. 0. 0. 0.] + # [0. 0. 0. 0.]]]] + """ + + def __init__(self, padding, data_format="NCHW", name=None): + super(ZeroPad2D, self).__init__() + self._pad = _npairs(padding, 2) + self._mode = 'constant' + self._value = 0.0 + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.pad( + x, + pad=self._pad, + mode=self._mode, + value=self._value, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'padding={}, data_format={}{}'.format( + self._pad, self._data_format, name_str + ) + + +class Pad3D(Layer): + """ + This interface is used to construct a callable object of the ``Pad3D`` class. + Pad tensor according to 'pad', 'mode' and 'value'. + If mode is 'reflect', pad[0] and pad[1] must be no greater + than width-1. The height and depth dimension has the same condition. + + Parameters: + padding (Tensor|list[int]|int): The padding size with data type int. If is int, use the + same padding in all dimensions. Else [len(padding)/2] dimensions + of input will be padded. The pad has the form (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back). + mode (str, optional): Four modes: 'constant' (default), 'reflect', 'replicate', 'circular'. Default is 'constant'. + + - 'constant' mode, uses a constant value to pad the input tensor. + - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + - 'replicate' mode, uses input boundaries to pad the input tensor. + - 'circular' mode, uses circular input to pad the input tensor. + + value (float, optional): The value to fill the padded areas. Default is :math:`0.0`。 + data_format (str, optional): An string from: "NCDHW", "NDHWC". Specify the data format of the input data. + Default is "NCDHW"。 + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input_shape = (1, 1, 1, 2, 3) + pad = [1, 0, 1, 2, 0, 0] + mode = "constant" + data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1 + my_pad = nn.Pad3D(padding=pad, mode=mode) + result = my_pad(data) + print(result) + # [[[[[0. 0. 0. 0.] + # [0. 1. 2. 3.] + # [0. 4. 5. 6.] + # [0. 0. 0. 0.] + # [0. 0. 0. 0.]]]]] + """ + + def __init__( + self, + padding, + mode='constant', + value=0.0, + data_format="NCDHW", + name=None, + ): + super(Pad3D, self).__init__() + self._pad = _npairs(padding, 3) + self._mode = mode + self._value = value + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.pad( + x, + pad=self._pad, + mode=self._mode, + value=self._value, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self._name) if self._name else '' + return 'padding={}, mode={}, value={}, data_format={}{}'.format( + self._pad, self._mode, self._value, self._data_format, name_str + ) + + +class CosineSimilarity(Layer): + """ + This interface is used to compute cosine similarity between x1 and x2 along axis. + + Parameters: + axis (int): Dimension of vectors to compute cosine similarity. Default is 1. + eps(float): Small value to avoid division by zero. Default is 1e-8. + Returns: + None + + Examples: + .. code-block:: text + + Case 0: + x1 = [[0.8024077 0.9927354 0.27238318 0.8344984 ] + [0.48949873 0.5797396 0.65444374 0.66510963] + [0.1031398 0.9614342 0.08365563 0.6796464 ] + [0.10760343 0.7461209 0.7726148 0.5801006 ]] + x2 = [[0.62913156 0.1536727 0.9847992 0.04591406] + [0.9098952 0.15715368 0.8671125 0.3156102 ] + [0.4427798 0.54136837 0.5276275 0.32394758] + [0.3769419 0.8535014 0.48041078 0.9256797 ]] + axis = 1 + eps = 1e-8 + Out: [0.5275037 0.8368967 0.75037485 0.9245899] + + Code Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + x1 = paddle.to_tensor([[1., 2., 3.], + [2., 3., 4.]], dtype="float32") + x2 = paddle.to_tensor([[8., 3., 3.], + [2., 3., 4.]], dtype="float32") + + cos_sim_func = nn.CosineSimilarity(axis=0) + result = cos_sim_func(x1, x2) + print(result) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.65079135, 0.98058069, 1. ]) + """ + + def __init__(self, axis=1, eps=1e-8): + super(CosineSimilarity, self).__init__() + self._axis = axis + self._eps = eps + + def forward(self, x1, x2): + return F.cosine_similarity(x1, x2, axis=self._axis, eps=self._eps) + + def extra_repr(self): + return 'axis={_axis}, eps={_eps}'.format(**self.__dict__) + + +class Embedding(Layer): + r""" + + Embedding Layer, used to construct a callable object of the ``Embedding`` class. + For specific usage, refer to code examples. It implements the function of the Embedding Layer. + This layer is used to lookup embeddings vector of ids provided by :attr:`x` . + It automatically constructs a 2D embedding matrix based on the + input :attr:`num_embeddings` and :attr:`embedding_dim`. + + The shape of output Tensor is generated by appending an emb_size dimension to the + last dimension of the input Tensor shape. + + Note: + The id in :attr:`x` must satisfy :math:`0 =< id < num_embeddings` , + otherwise the program will throw an exception and exit. + + .. code-block:: text + + Case 1: + + x is a Tensor. padding_idx = -1 + x.data = [[1, 3], [2, 4], [4, 127] + x.shape = [3, 2] + Given size = [128, 16] + output is a Tensor: + out.shape = [3, 2, 16] + out.data = [[[0.129435295, 0.244512452, ..., 0.436322452], + [0.345421456, 0.524563927, ..., 0.144534654]], + + [[0.345249859, 0.124939536, ..., 0.194353745], + [0.945345345, 0.435394634, ..., 0.435345365]], + + [[0.945345345, 0.435394634, ..., 0.435345365], + [0.0, 0.0, ..., 0.0 ]]] # padding data + The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127 + It will pad all-zero data when ids is 127. + + Parameters: + num_embeddings (int): Just one element which indicate the size + of the dictionary of embeddings. + embedding_dim (int): Just one element which indicate the size of each embedding vector respectively. + padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-num_embeddings, num_embeddings). + If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted + to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup + encounters :math:`padding\_idx` in id. And the padding data will not be updated while training. + If set None, it makes no effect to output. Default: None. + sparse(bool, optional): The flag indicating whether to use sparse update. This parameter only + affects the performance of the backwards gradient update. It is recommended to set + True because sparse update is faster. But some optimizer does not support sparse update, + such as :ref:`api_paddle_optimizer_adadelta_Adadelta` , :ref:`api_paddle_optimizer_adamax_Adamax` , :ref:`api_paddle_optimizer_lamb_Lamb`. + In these case, sparse must be False. Default: False. + weight_attr(ParamAttr, optional): To specify the weight parameter property. Default: None, which means the + default weight parameter property is used. See usage for details in :ref:`api_ParamAttr` . In addition, + user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter. + The local word vector needs to be transformed into numpy format, and the shape of local word + vector should be consistent with :attr:`num_embeddings` . Then :ref:`api_initializer_NumpyArrayInitializer` + is used to load custom or pre-trained word vectors. See code example for details. + name(str|None, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Attribute: + **weight** (Parameter): the learnable weights of this layer. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[0], [1], [3]], dtype="int64", stop_gradient=False) + embedding = paddle.nn.Embedding(4, 3, sparse=True) + + w0 = paddle.to_tensor([[0., 0., 0.], + [1., 1., 1.], + [2., 2., 2.], + [3., 3., 3.]], dtype="float32") + embedding.weight.set_value(w0) + print(embedding.weight) + # Tensor(shape=[4, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[0., 0., 0.], + # [1., 1., 1.], + # [2., 2., 2.], + # [3., 3., 3.]]) + + adam = paddle.optimizer.Adam(parameters=[embedding.weight], learning_rate=0.01) + adam.clear_grad() + + + out = embedding(x) + print(out) + # Tensor(shape=[3, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[0., 0., 0.]], + # [[1., 1., 1.]], + # [[3., 3., 3.]]]) + + out.backward() + adam.step() + + """ + + def __init__( + self, + num_embeddings, + embedding_dim, + padding_idx=None, + sparse=False, + weight_attr=None, + name=None, + ): + super(Embedding, self).__init__() + self._num_embeddings = num_embeddings + self._embedding_dim = embedding_dim + self._sparse = sparse + self._is_distributed = False + self._padding_idx = padding_idx + + if self._num_embeddings <= 0: + raise ValueError("num_embeddings must be gather than 0") + + if self._embedding_dim <= 0: + raise ValueError("embedding_dim must be gather than 0") + + padding_idx = ( + -1 + if padding_idx is None + else padding_idx + if padding_idx >= 0 + else (num_embeddings + padding_idx) + ) + + if padding_idx >= num_embeddings or padding_idx < -num_embeddings: + raise ValueError( + "padding_idx must be within [-{}, {})".format( + num_embeddings, num_embeddings + ) + ) + + self._dtype = self._helper.get_default_dtype() + self._size = [self._num_embeddings, self._embedding_dim] + + self._weight_attr = weight_attr + self._remote_prefetch = False + self._name = name + self.weight = self.create_parameter( + attr=self._weight_attr, + shape=self._size, + dtype=self._dtype, + is_bias=False, + ) + + if in_dynamic_mode() and padding_idx != -1: + with paddle.no_grad(): + self.weight[padding_idx] = 0.0 + + def forward(self, x): + return F.embedding( + x, + weight=self.weight, + padding_idx=self._padding_idx, + sparse=self._sparse, + name=self._name, + ) + + def extra_repr(self): + main_str = '{_num_embeddings}, {_embedding_dim}' + if self._padding_idx is not None: + main_str += ', padding_idx={_padding_idx}' + main_str += ', sparse={_sparse}' + if self._name is not None: + main_str += ', name={_name}' + return main_str.format(**self.__dict__) + + +class Unfold(Layer): + """ + This op returns a col buffer of sliding local blocks of input x, also known + as im2col for batched 2D image tensors. For each block under the convolution filter, + all element will be rearranged as a column. While the convolution filter sliding over + the input feature map, a series of such columns will be formed. + + For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout] + can be calculated as following. + + See ``paddle.nn.functional.unfold`` for more details. + + + Parameters: + kernel_sizes(int|list): The size of convolution kernel, should be [k_h, k_w] + or an integer k treated as [k, k]. + strides(int|list): The strides, should be [stride_h, stride_w] + or an integer stride treated as [sride, stride]. + For default, strides will be [1, 1]. + paddings(int|list): The paddings of each dimension, should be + [padding_top, padding_left, padding_bottom, padding_right] + or [padding_h, padding_w] or an integer padding. + If [padding_h, padding_w] was given, it will expanded to + [padding_h, padding_w, padding_h, padding_w]. If an integer + padding was given, [padding, padding, padding, padding] will + be used. For default, paddings will be [0, 0, 0, 0] + dilations(int|list): the dilations of convolution kernel, should be + [dilation_h, dilation_w], or an integer dilation treated as + [dilation, dilation]. For default, it will be [1, 1]. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + x = paddle.randn((100,3,224,224)) + unfold = nn.Unfold(kernel_sizes=[3, 3]) + result = unfold(x) + print(result) + """ + + def __init__( + self, kernel_sizes, dilations=1, paddings=0, strides=1, name=None + ): + super(Unfold, self).__init__() + + self.kernel_sizes = kernel_sizes + self.dilations = dilations + self.paddings = paddings + self.strides = strides + self.name = name + + def forward(self, input): + return F.unfold( + input, + kernel_sizes=self.kernel_sizes, + strides=self.strides, + paddings=self.paddings, + dilations=self.dilations, + name=self.name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'kernel_size={}, dilation={}, padding={}, stride={}{}'.format( + self.kernel_sizes, + self.dilations, + self.paddings, + self.strides, + name_str, + ) + + +class Fold(Layer): + r""" + + Combines an array of sliding local blocks into a large containing + tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each + combined value in the resulting large tensor by summing all values from all containing blocks. + + + For each input :math:`x` with shape [N, C_in , L], the output shape [N, C_out, H_out, W_out] + can be calculated as following. + + .. math:: + + H_{out} &= output\_size[0] \\ + W_{out} &= output\_size[1] \\ + C_{out} &= \frac{C_{in}}{kernel\_sizes[0]\times kernel\_sizes[1]} \\ + + Parameters: + output_sizes(list): The size of output size, should be [output_size_h, output_size_w] + or an interger o treated as [o, o]. + kernel_sizes(int|list|tuple): The size of convolution kernel, should be [k_h, k_w] + or an integer k treated as [k, k]. + strides(int|list|tuple, optional): The strides, should be [stride_h, stride_w] + or an integer stride treated as [sride, stride]. + For default, strides will be [1, 1]. + paddings(int|list|tuple, optional): The paddings of each dimension, should be + [padding_top, padding_left, padding_bottom, padding_right] + or [padding_h, padding_w] or an integer padding. + If [padding_h, padding_w] was given, it will expanded to + [padding_h, padding_w, padding_h, padding_w]. If an integer + padding was given, [padding, padding, padding, padding] will + be used. For default, paddings will be [0, 0, 0, 0] + dilations(int|list|tuple, optional): the dilations of convolution kernel, should be + [dilation_h, dilation_w], or an integer dilation treated as + [dilation, dilation]. For default, it will be [1, 1]. + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + + Returns: + The tensor formed by combining a group of sliding local blocks + The output shape is [N, Cout, H, W] as decriabled above. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + x = paddle.randn([2,3*2*2,12]) + fold = nn.Fold(output_sizes=[4, 5], kernel_sizes=2) + y = fold(x) + # y.shape = [2,3,4,5] + """ + + def __init__( + self, + output_sizes, + kernel_sizes, + dilations=1, + paddings=0, + strides=1, + name=None, + ): + super(Fold, self).__init__() + + self.output_sizes = output_sizes + self.kernel_sizes = kernel_sizes + self.dilations = dilations + self.paddings = paddings + self.strides = strides + self.name = name + + def forward(self, input): + return F.fold( + input, + output_sizes=self.output_sizes, + kernel_sizes=self.kernel_sizes, + strides=self.strides, + paddings=self.paddings, + dilations=self.dilations, + name=self.name, + ) + + def extra_repr(self): + name_str = ', name={}'.format(self.name) if self.name else '' + return 'kernel_size={}, dilation={}, padding={}, stride={}{}'.format( + self.kernel_sizes, + self.dilations, + self.paddings, + self.strides, + name_str, + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/container.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/container.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1bf6bc5657e7da2d8f0193a6639a40ede4e749 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/container.py @@ -0,0 +1,293 @@ +# Copyright (c) 2021 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. + +from collections import OrderedDict +from .. import Layer +from collections.abc import Iterable, Mapping + +__all__ = [] + + +class LayerDict(Layer): + """ + LayerDict holds sublayers in the ordered dictionary, and sublayers it contains are properly registered. + Holded sublayers can be accessed like a regular ordered python dictionary. + + Parameters: + sublayers (LayerDict|OrderedDict|list[(key,Layer)...], optional): iterable of key/value pairs, the type of value is 'paddle.nn.Layer' . + + Examplex: + .. code-block:: python + + import paddle + import numpy as np + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layers_dict = paddle.nn.LayerDict(sublayers=sublayers) + + l = layers_dict['conv1d'] + + for k in layers_dict: + l = layers_dict[k] + + len(layers_dict) + #3 + + del layers_dict['conv2d'] + len(layers_dict) + #2 + + conv1d = layers_dict.pop('conv1d') + len(layers_dict) + #1 + + layers_dict.clear() + len(layers_dict) + #0 + + """ + + def __init__(self, sublayers=None): + super(LayerDict, self).__init__() + if sublayers is not None: + self.update(sublayers) + + def __getitem__(self, key): + return self._sub_layers[key] + + def __setitem__(self, key, sublayer): + return self.add_sublayer(key, sublayer) + + def __delitem__(self, key): + del self._sub_layers[key] + + def __len__(self): + return len(self._sub_layers) + + def __iter__(self): + return iter(self._sub_layers) + + def __contains__(self, key): + return key in self._sub_layers + + def clear(self): + """ + Clear all the sublayers in the LayerDict. + + Parameters: + None. + + Examplex: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + len(layer_dict) + #3 + + layer_dict.clear() + len(layer_dict) + #0 + + """ + self._sub_layers.clear() + + def pop(self, key): + """ + Remove the key from the LayerDict and return the layer of the key. + + Parameters: + key (str): the key to be removed. + + Examples: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + len(layer_dict) + #3 + + layer_dict.pop('conv2d') + len(layer_dict) + #2 + + """ + v = self[key] + del self[key] + return v + + def keys(self): + """ + Return the iterable of the keys in LayerDict. + + Parameters: + None. + + Examples: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + for k in layer_dict.keys(): + print(k) + + #conv1d + #conv2d + #conv3d + + """ + return self._sub_layers.keys() + + def items(self): + """ + Return the iterable of the key/value pairs in LayerDict. + + Parameters: + None. + + Examples: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + for k, v in layer_dict.items(): + print(k, ":", v) + + #conv1d : Conv1D(3, 2, kernel_size=[3], data_format=NCL) + #conv2d : Conv2D(3, 2, kernel_size=[3, 3], data_format=NCHW) + #conv3d : Conv3D(4, 6, kernel_size=[3, 3, 3], data_format=NCDHW) + + """ + return self._sub_layers.items() + + def values(self): + """ + Return the iterable of the values in LayerDict. + + Parameters: + None. + + Examples: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + for v in layer_dict.values(): + print(v) + + #Conv1D(3, 2, kernel_size=[3], data_format=NCL) + #Conv2D(3, 2, kernel_size=[3, 3], data_format=NCHW) + #Conv3D(4, 6, kernel_size=[3, 3, 3], data_format=NCDHW) + + """ + return self._sub_layers.values() + + def update(self, sublayers): + """ + Update the key/values pairs in sublayers to the LayerDict, overwriting the existing keys. + + Parameters: + sublayers (LayerDict|OrderedDict|list[(key,Layer)...]): iterable of key/value pairs, the type of value is 'paddle.nn.Layer' . + + Examples: + .. code-block:: python + + import paddle + from collections import OrderedDict + + sublayers = OrderedDict([ + ('conv1d', paddle.nn.Conv1D(3, 2, 3)), + ('conv2d', paddle.nn.Conv2D(3, 2, 3)), + ('conv3d', paddle.nn.Conv3D(4, 6, (3, 3, 3))), + ]) + + new_sublayers = OrderedDict([ + ('relu', paddle.nn.ReLU()), + ('conv2d', paddle.nn.Conv2D(4, 2, 4)), + ]) + layer_dict = paddle.nn.LayerDict(sublayers=sublayers) + + layer_dict.update(new_sublayers) + + for k, v in layer_dict.items(): + print(k, ":", v) + #conv1d : Conv1D(3, 2, kernel_size=[3], data_format=NCL) + #conv2d : Conv2D(4, 2, kernel_size=[4, 4], data_format=NCHW) + #conv3d : Conv3D(4, 6, kernel_size=[3, 3, 3], data_format=NCDHW) + #relu : ReLU() + + """ + + assert isinstance( + sublayers, Iterable + ), "The type of sublayers is not iterable of key/value pairs, the type of sublayers is " + type( + sublayers).__name__ + + if isinstance(sublayers, (OrderedDict, LayerDict, Mapping)): + for key, layer in sublayers.items(): + self.add_sublayer(key, layer) + else: + # handle this format [(key1, layer1), (key2, layer2)...] + for i, kv in enumerate(sublayers): + if len(kv) != 2: + raise ValueError("The length of the " + str(i) + + "'s element in sublayers is " + + str(len(kv)) + ", which must be 2.") + self.add_sublayer(kv[0], kv[1]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/conv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..08056508f9170b6bdefbac0813c5dc123683f124 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/conv.py @@ -0,0 +1,1233 @@ +# 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. + +# TODO: define classes of convolutional neural network + +import numpy as np + +from paddle import get_flags +from ...device import get_cudnn_version +from .. import Layer +from ..initializer import Normal +from .. import functional as F +from ...fluid.layers import utils +from ..functional.conv import _update_padding_nd +from ...device import is_compiled_with_cuda +from ...device import is_compiled_with_rocm + +__all__ = [] + + +def _get_default_param_initializer(num_channels, filter_size): + filter_elem_num = num_channels * np.prod(filter_size) + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std) + + +def _reverse_repeat_list(t, n): + """Reverse the order of `t` and repeat each element for `n` times. + This can be used to translate padding arg used by Conv and Pooling modules + to the ones used by `F.pad`. + """ + return list(x for x in reversed(t) for _ in range(n)) + + +class _ConvNd(Layer): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + transposed, + dims, + stride=1, + padding=0, + padding_mode='zeros', + output_padding=0, + dilation=1, + groups=1, + weight_attr=None, + bias_attr=None, + data_format="NCHW", + ): + super(_ConvNd, self).__init__() + assert ( + weight_attr is not False + ), "weight_attr should not be False in Conv." + self._param_attr = weight_attr + self._bias_attr = bias_attr + self._groups = groups + self._in_channels = in_channels + self._out_channels = out_channels + self._data_format = data_format + + valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'} + if padding_mode not in valid_padding_modes: + raise ValueError( + "padding_mode must be one of {}, but got padding_mode='{}'".format( + valid_padding_modes, padding_mode + ) + ) + + if padding_mode in { + 'reflect', + 'replicate', + 'circular', + } and not isinstance(padding, int): + raise TypeError( + "when padding_mode in ['reflect', 'replicate', 'circular'], type of padding must be int" + ) + + valid_format = {'NHWC', 'NCHW', 'NDHWC', 'NCDHW', 'NLC', 'NCL'} + if data_format not in valid_format: + raise ValueError( + "data_format must be one of {}, but got data_format='{}'".format( + valid_format, data_format + ) + ) + + channel_last = ( + (data_format == "NHWC") + or (data_format == "NDHWC") + or (data_format == "NLC") + ) + if channel_last: + self._channel_dim = len(data_format) - 1 + else: + self._channel_dim = 1 + + self._stride = utils.convert_to_list(stride, dims, 'stride') + self._dilation = utils.convert_to_list(dilation, dims, 'dilation') + self._kernel_size = utils.convert_to_list( + kernel_size, dims, 'kernel_size' + ) + self._padding = padding + self._padding_mode = padding_mode + self.output_padding = output_padding + if dims != 1: + self._updated_padding, self._padding_algorithm = _update_padding_nd( + padding, channel_last, dims + ) + + if transposed: + filter_shape = [ + self._in_channels, + out_channels // groups, + ] + self._kernel_size + else: + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups.") + + if padding_mode in {'reflect', 'replicate', 'circular'}: + _paired_padding = utils.convert_to_list( + padding, dims, 'padding' + ) + self._reversed_padding_repeated_twice = _reverse_repeat_list( + _paired_padding, 2 + ) + + ( + self._updated_padding, + self._padding_algorithm, + ) = _update_padding_nd(0, channel_last, dims) + + filter_shape = [ + out_channels, + in_channels // groups, + ] + self._kernel_size + + def _get_default_param_initializer(): + if transposed: + return None + filter_elem_num = np.prod(self._kernel_size) * self._in_channels + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std) + + self.weight = self.create_parameter( + shape=filter_shape, + attr=self._param_attr, + default_initializer=_get_default_param_initializer(), + ) + self.bias = self.create_parameter( + attr=self._bias_attr, shape=[self._out_channels], is_bias=True + ) + + cudnn_version = get_cudnn_version() + + self._use_cudnn = ( + True + if (is_compiled_with_cuda() and cudnn_version is not None) + else False + ) + + self._op_type = "conv" + str(dims) + 'd' + if self._op_type == 'conv2d' and ( + in_channels == groups + and in_channels != 1 + and out_channels % in_channels == 0 + ): + self._op_type = 'depthwise_conv2d' + if is_compiled_with_rocm(): + self._use_cudnn = True + else: + self._use_cudnn = False + + if ( + is_compiled_with_cuda() + and get_flags("FLAGS_conv2d_disable_cudnn")[ + "FLAGS_conv2d_disable_cudnn" + ] + ): + self._use_cudnn = False + + def extra_repr(self): + main_str = '{_in_channels}, {_out_channels}, kernel_size={_kernel_size}' + if self._stride != [1] * len(self._stride): + main_str += ', stride={_stride}' + if self._padding != 0: + main_str += ', padding={_padding}' + if self._padding_mode != 'zeros': + main_str += ', padding_mode={_padding_mode}' + if self.output_padding != 0: + main_str += ', output_padding={output_padding}' + if self._dilation != [1] * len(self._dilation): + main_str += ', dilation={_dilation}' + if self._groups != 1: + main_str += ', groups={_groups}' + main_str += ', data_format={_data_format}' + return main_str.format(**self.__dict__) + + +class Conv1D(_ConvNd): + r""" + This interface is used to construct a callable object of the ``Conv1D`` class. + For more details, refer to code examples. + The convolution1D layer calculates the output based on the input, filter + and stride, padding, dilation, groups parameters. Input and + Output are in NCL format or NLC format, where N is batch size, C is the number of + the feature map, L is the length of the feature map. + Filter's shape is [MCK] , where M is the number of output feature map, + C is the number of input feature map, K is the size of the kernel. + If the groups is greater than 1, C will equal the number of input feature map divided by the groups. + If bias attribution and activation type are provided, bias is added to the + output of the convolution, and the corresponding activation function is + applied to the final result. + + For each input :math:`X` , the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a ``Tensor`` with 'NCL' format or 'NLC' format. + * :math:`W`: Filter value, a ``Tensor`` with shape [MCK] . + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, L_{in})` + + Kernel shape: :math:`(C_{out}, C_{in}, K)` + + - Output: + + Output shape: :math:`(N, C_{out}, L_{out})` + + Where + + .. math:: + + L_{out}&= \frac{(L_{in} + 2 * padding - (dilation * (L_f - 1) + 1))}{stride} + 1 \\ + + Parameters: + in_channels(int): The number of channels in the input image. + out_channels(int): The number of filter. It is as same as the output + feature map. + kernel_size (int|tuple|list): The filter size. If kernel_size is a tuple/list, + it must contain one integer, (kernel_size). + stride (int|tuple|list, optional): The stride size. If stride is a tuple/list, it must + contain one integer, (stride_size). Default: 1. + padding(int|str|tuple|list, optional): The size of zeros to be padded. It must be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means the feature map is zero paded by size of `padding` on both sides. + 3. a list[int] or tuple[int] whose length is 1, which means the feature map is zero paded by size of `padding[0]` on both sides. + The default value is 0. + dilation (int|tuple|list, optional): The dilation size. If dilation is a tuple/list, it must + contain one integer, (dilation_size). Default: 1. + groups (int, optional): The groups number of the conv2d Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: 1. + padding_mode(str, optional): Four modes: 'zeros', 'reflect', 'replicate', 'circular'. + When in 'zeros' mode, this op uses zeros to pad the input tensor. + When in 'reflect' mode, uses reflection of the input boundaries to pad the input tensor. + When in 'replicate' mode, uses input boundaries to pad the input tensor. + When in 'circular' mode, uses circular input to pad the input tensor. + Default is 'zeros'. + weight_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter) + of conv1d. If it is set to None or one attribute of ParamAttr, conv1d + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with :math:`Normal(0.0, std)`, + and the :math:`std` is :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv1d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv1d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + + Attribute: + + **weight** (Parameter): the learnable weights of filter of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Shape: + - x: 3-D tensor with shape: (batch, in_channels, length) or (batch, length, in_channels). + - weight: 3-D tensor with shape: (out_channels, in_channels, kernel_size) + - bias: 1-D tensor with shape: (out_channels) + - output: 3-D tensor with same shape as input x. + + Examples: + .. code-block:: python + + import paddle + from paddle.nn import Conv1D + + x = paddle.to_tensor([[[4, 8, 1, 9], + [7, 2, 0, 9], + [6, 9, 2, 6]]], dtype="float32") + w = paddle.to_tensor([[[9, 3, 4], + [0, 0, 7], + [2, 5, 6]], + [[0, 3, 4], + [2, 9, 7], + [5, 6, 8]]], dtype="float32") + + conv = Conv1D(3, 2, 3) + conv.weight.set_value(w) + y = conv(x) + print(y) + # Tensor(shape=[1, 2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[133., 238.], + # [160., 211.]]]) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + padding_mode='zeros', + weight_attr=None, + bias_attr=None, + data_format="NCL", + ): + super(Conv1D, self).__init__( + in_channels, + out_channels, + kernel_size, + False, + 1, + stride=stride, + padding=padding, + padding_mode=padding_mode, + dilation=dilation, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x): + padding = 0 + if self._padding_mode != "zeros": + x = F.pad( + x, + self._reversed_padding_repeated_twice, + mode=self._padding_mode, + data_format=self._data_format, + ) + else: + padding = self._padding + + out = F.conv1d( + x, + self.weight, + bias=self.bias, + padding=padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + data_format=self._data_format, + ) + return out + + +class Conv1DTranspose(_ConvNd): + r""" + This interface is used to construct a callable object of the ``Conv1DTranspose`` class. + For more details, refer to code examples. + The 1-D convolution transpose layer calculates the output based on the input, + filter, and dilation, stride, padding. Input(Input) and output(Output) + are in 'NCL' format or 'NLC' where N is batch size, C is the number of channels, + L is the length of the feature. The details of convolution transpose + layer, please refer to the following explanation and references + `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a 3-D Tensor with 'NCL' format or 'NLC' format. + * :math:`W`: Kernel value, a 3-D Tensor with 'MCK' format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, a 3-D Tensor with data format 'NCL' of 'NLC', the shape of :math:`Out` and :math:`X` may be different. + + Example: + + - Input: + + Input shape: :math:`(N, C_{in}, L_{in})` + + Filter shape: :math:`(C_{in}, C_{out}, L_f)` + + - Output: + + Output shape: :math:`(N, C_{out}, L_{out})` + + Where + + .. math:: + + L^\prime_{out} &= (L_{in} - 1) * stride - pad_top - pad_bottom + dilation * (L_f - 1) + 1 \\\\ + L_{out} &\in [ L^\prime_{out}, L^\prime_{out} + stride ] + + Note: + The conv1d_transpose can be seen as the backward of the conv1d. For conv1d, + when stride > 1, conv1d maps multiple input shape to the same output shape, + so for conv1d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`L_{out} = L^\prime_{out}`; + else, the :math:`L_{out}` of the output size must between :math:`L^\prime_{out}` + and :math:`L^\prime_{out} + stride`. + + Args: + in_channels(int): The number of channels in the input image. + out_channels(int): The number of the filter. It is as same as the output + feature map. + kernel_size(int|tuple|list, optional): The filter size. If kernel_size is a tuple/list, + it must contain one integers, (kernel_size). None if + use output size to calculate kernel_size. Default: None. kernel_size and + output_size should not be None at the same time. + stride(int|tuple|list, optional): The stride size. It means the stride in transposed convolution. + If stride is a tuple/list, it must contain one integer, (stride_size). + Default: stride = 1. + padding(int|list|str|tuple, optional): The padding size. The padding argument effectively adds + `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a + string, either 'VALID' or 'SAME' supported, which is the padding algorithm. + If `padding` is a tuple or list, it could be in two forms: + `[pad]` or `[pad_left, pad_right]`. Default: padding = 0. + output_padding(int|list|tuple, optional): The count of zeros to be added to tail of each dimension. + If it is a tuple/list, it must contain one integer. Default: 0. + groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: groups = 1. + bias(bool, optional): Whether to use bias. Default: True. + dilation(int|tuple|list, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a tuple/list, it must contain one integer, (dilation_size). + Default: dilation = 1. + weight_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv1d_transpose. If it is set to None or one attribute of ParamAttr, conv1d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv1d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv1d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + + Attribute: + **weight** (Parameter): the learnable weights of filters of this layer. + **bias** (Parameter or None): the learnable bias of this layer. + + Shape: + + - x(Tensor): 3-D tensor with shape (batch, in_channels, length) when data_format is "NCL" or shape (batch, length, in_channels) when data_format is "NLC". + - weight(Tensor): 3-D tensor with shape (in_channels, out_channels, kernel_length). + - bias(Tensor): 1-D tensor with shape (out_channels). + - output_size(int|tuple|list, optional): The output image size. If output size is a tuple/list, it must contain one integer, (feature_length). None if use kernel_size, padding, output_padding and stride to calculate output_size. If output_size and kernel_size are specified at the same time, They should follow the formula above. Default: None. output_size and kernel_size should not be None at the same time. + - output(Tensor): 3-D tensor with same shape as input x. + + Examples: + .. code-block:: python + + import paddle + from paddle.nn import Conv1DTranspose + + # shape: (1, 2, 4) + x = paddle.to_tensor([[[4, 0, 9, 7], + [8, 0, 9, 2]]], dtype="float32") + # shape: (2, 1, 2) + w = paddle.to_tensor([[[7, 0]], + [[4, 2]]], dtype="float32") + + conv = Conv1DTranspose(2, 1, 2) + conv.weight.set_value(w) + y = conv(x) + print(y) + # Tensor(shape=[1, 1, 5], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[60., 16., 99., 75., 4. ]]]) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + groups=1, + dilation=1, + weight_attr=None, + bias_attr=None, + data_format="NCL", + ): + super(Conv1DTranspose, self).__init__( + in_channels, + out_channels, + kernel_size, + True, + 1, + stride=stride, + padding=padding, + dilation=dilation, + output_padding=output_padding, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x, output_size=None): + out = F.conv1d_transpose( + x, + self.weight, + bias=self.bias, + output_size=output_size, + output_padding=self.output_padding, + padding=self._padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + data_format=self._data_format, + ) + return out + + +class Conv2D(_ConvNd): + r""" + This interface is used to construct a callable object of the ``Conv2D`` class. + For more details, refer to code examples. + The convolution2D layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input and + Output are in NCHW format, where N is batch size, C is the number of + the feature map, H is the height of the feature map, and W is the width of the feature map. + Filter's shape is [MCHW] , where M is the number of output feature map, + C is the number of input feature map, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input feature map divided by the groups. + Please refer to UFLDL's `convolution + `_ + for more details. + If bias attribution and activation type are provided, bias is added to the + output of the convolution, and the corresponding activation function is + applied to the final result. + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a ``Tensor`` with NCHW format. + * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] . + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Parameters: + in_channels(int): The number of input channels in the input image. + out_channels(int): The number of output channels produced by the convolution. + kernel_size(int|list|tuple, optional): The size of the convolving kernel. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain three integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. The default value is 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1. + padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv2d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCHW" or "NHWC". Default: "NCHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filter of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, C_{in}, H_{in}, W_{in})` + + - weight: :math:`(C_{out}, C_{in}, K_{h}, K_{w})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1 + + W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1 + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + paddle.disable_static() + + x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.) + + conv = nn.Conv2D(4, 6, (3, 3)) + y_var = conv(x_var) + y_np = y_var.numpy() + print(y_np.shape) + # (2, 6, 6, 6) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + padding_mode='zeros', + weight_attr=None, + bias_attr=None, + data_format="NCHW", + ): + super(Conv2D, self).__init__( + in_channels, + out_channels, + kernel_size, + False, + 2, + stride=stride, + padding=padding, + padding_mode=padding_mode, + dilation=dilation, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x): + if self._padding_mode != 'zeros': + x = F.pad( + x, + self._reversed_padding_repeated_twice, + mode=self._padding_mode, + data_format=self._data_format, + ) + + out = F.conv._conv_nd( + x, + self.weight, + bias=self.bias, + stride=self._stride, + padding=self._updated_padding, + padding_algorithm=self._padding_algorithm, + dilation=self._dilation, + groups=self._groups, + data_format=self._data_format, + channel_dim=self._channel_dim, + op_type=self._op_type, + use_cudnn=self._use_cudnn, + ) + return out + + +class Conv2DTranspose(_ConvNd): + r""" + This interface is used to construct a callable object of the ``Conv2DTranspose`` class. + For more details, refer to code examples. + The convolution2D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input and output + are in NCHW format. Where N is batch size, C is the number of feature map, + H is the height of the feature map, and W is the width of the feature map. + Filter's shape is [CMHW] , where C is the number of input feature map, + M is the number of output feature map, H is the height of the filter, + and W is the width of the filter. If the groups is greater than 1, + C will equal the number of input feature map divided by the groups. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + The details of convolution transpose layer, please refer to the following explanation and references + `conv2dtranspose `_ . + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + Where: + + * :math:`X`: Input value, a ``Tensor`` with NCHW format. + * :math:`W`: Filter value, a ``Tensor`` with shape [CMHW] . + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Parameters: + in_channels(int): The number of channels in the input image. + out_channels(int): The number of channels produced by the convolution. + kernel_size(int|list|tuple): The kernel size. If kernel_size is a list/tuple, + it must contain two integers, (kernel_size_H, kernel_size_W). + Otherwise, the kernel will be a square. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` on both sides + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + output_padding(int|list|tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: 1. + groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + Default: 1. + weight_attr(ParamAttr, optional): The parameter attribute for learnable weights(Parameter) + of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. Default: None. + bias_attr(ParamAttr|bool, optional): The attribute for the bias of conv2d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCHW" or "NHWC". Default: "NCHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter or None): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, C_{in}, H_{in}, W_{in})` + + - weight: :math:`(C_{in}, C_{out}, K_{h}, K_{w})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H^\prime_{out} &= (H_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (kernel\_size[0] - 1) + 1 + + W^\prime_{out} &= (W_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (kernel\_size[1] - 1) + 1 + + H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] ) + + W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] ) + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + paddle.disable_static() + + x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.) + + conv = nn.Conv2DTranspose(4, 6, (3, 3)) + y_var = conv(x_var) + y_np = y_var.numpy() + print(y_np.shape) + # (2, 6, 10, 10) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + dilation=1, + groups=1, + weight_attr=None, + bias_attr=None, + data_format="NCHW", + ): + super(Conv2DTranspose, self).__init__( + in_channels, + out_channels, + kernel_size, + True, + 2, + stride=stride, + padding=padding, + dilation=dilation, + output_padding=output_padding, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x, output_size=None): + if output_size is None: + output_padding = self.output_padding + else: + output_padding = 0 + + out = F.conv2d_transpose( + x, + self.weight, + bias=self.bias, + padding=self._padding, + output_padding=output_padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + output_size=output_size, + data_format=self._data_format, + ) + return out + + +class Conv3D(_ConvNd): + r""" + **Convlution3d Layer** + The convolution3d layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional tensors with a shape of + :math:`[N, C, D, H, W]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. Convlution3D is similar with Convlution2D + but adds one dimension(depth). If bias attribution and activation type are + provided, bias is added to the output of the convolution, and the + corresponding activation function is applied to the final result. + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Parameters: + in_channels(int): The number of input channels in the input image. + out_channels(int): The number of output channels produced by the convolution. + kernel_size(int|list|tuple, optional): The size of the convolving kernel. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain three integers, (stride_D, stride_H, stride_W). Otherwise, the + stride_D = stride_H = stride_W = stride. The default value is 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1. + padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d. If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCDHW" or "NDHWC". Default: "NCDHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + - weight: :math:`(C_{out}, C_{in}, K_{d}, K_{h}, K_{w})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1 + + H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1 + + W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (kernel\_size[2] - 1) + 1))}{strides[2]} + 1 + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + paddle.disable_static() + + x_var = paddle.uniform((2, 4, 8, 8, 8), dtype='float32', min=-1., max=1.) + + conv = nn.Conv3D(4, 6, (3, 3, 3)) + y_var = conv(x_var) + y_np = y_var.numpy() + print(y_np.shape) + # (2, 6, 6, 6, 6) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + padding_mode='zeros', + weight_attr=None, + bias_attr=None, + data_format="NCDHW", + ): + super(Conv3D, self).__init__( + in_channels, + out_channels, + kernel_size, + False, + 3, + stride=stride, + padding=padding, + padding_mode=padding_mode, + dilation=dilation, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x): + if self._padding_mode != 'zeros': + x = F.pad( + x, + self._reversed_padding_repeated_twice, + mode=self._padding_mode, + data_format=self._data_format, + ) + + out = F.conv._conv_nd( + x, + self.weight, + bias=self.bias, + stride=self._stride, + padding=self._updated_padding, + padding_algorithm=self._padding_algorithm, + dilation=self._dilation, + groups=self._groups, + data_format=self._data_format, + channel_dim=self._channel_dim, + op_type=self._op_type, + use_cudnn=self._use_cudnn, + ) + return out + + +class Conv3DTranspose(_ConvNd): + r""" + **Convlution3D transpose layer** + The convolution3D transpose layer calculates the output based on the input, + filter, and dilations, strides, paddings. Input(Input) and output(Output) + are in NCDHW format. Where N is batch size, C is the number of channels, + D is the depth of the feature, H is the height of the feature, and W + is the width of the feature. Parameters(dilations, strides, paddings) are + two elements. These two elements represent height and width, respectively. + The details of convolution transpose layer, please refer to the following + explanation and references `therein `_. + If bias attribution and activation type are provided, bias is added to + the output of the convolution, and the corresponding activation function + is applied to the final result. + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW format. + * :math:`W`: Filter value, a tensor with CMDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`\\sigma`: Activation function. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + **Note**: + + The conv3d_transpose can be seen as the backward of the conv3d. For conv3d, + when stride > 1, conv3d maps multiple input shape to the same output shape, + so for conv3d_transpose, when stride > 1, input shape maps multiple output shape. + If output_size is None, :math:`H_{out} = H^\prime_{out}, :math:`H_{out} = \ + H^\prime_{out}, W_{out} = W^\prime_{out}`; else, the :math:`D_{out}` of the output + size must between :math:`D^\prime_{out}` and :math:`D^\prime_{out} + strides[0]`, + the :math:`H_{out}` of the output size must between :math:`H^\prime_{out}` + and :math:`H^\prime_{out} + strides[1]`, and the :math:`W_{out}` of the output size must + between :math:`W^\prime_{out}` and :math:`W^\prime_{out} + strides[2]`, + conv3d_transpose can compute the kernel size automatically. + + Parameters: + in_channels(int): The number of channels in the input image. + out_channels(int): The number of channels produced by the convolution. + kernel_size(int|list|tuple): The kernel size. If kernel_size is a list/tuple, + it must contain three integers, (kernel_size_D, kernel_size_H, kernel_size_W). + Otherwise, the kernel will be a square. + stride(int|list|tuple, optional): The stride size. It means the stride in transposed convolution. + If stride is a list/tuple, it must contain three integers, (stride_depth, stride_height, + stride_width). Otherwise, stride_depth = stride_height = stride_width = stride. + The default value is 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + output_padding(int|list|tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D transpose layer. Inspired by + grouped convolution in Alex Krizhevsky's Deep CNN paper, in which + when group=2, the first half of the filters is only connected to the + first half of the input channels, while the second half of the + filters is only connected to the second half of the input channels. + The default value is 1. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d_transpose + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCDHW" or "NDHWC". Default: "NCDHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` + + - weight: :math:`(C_{in}, C_{out}, K_{d}, K_{h}, K_{w})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (kernel\_size[0] - 1) + 1 + + H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (kernel\_size[1] - 1) + 1 + + W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (kernel\_size[2] - 1) + 1 + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + paddle.disable_static() + + x_var = paddle.uniform((2, 4, 8, 8, 8), dtype='float32', min=-1., max=1.) + + conv = nn.Conv3DTranspose(4, 6, (3, 3, 3)) + y_var = conv(x_var) + y_np = y_var.numpy() + print(y_np.shape) + # (2, 6, 10, 10, 10) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + output_padding=0, + dilation=1, + groups=1, + weight_attr=None, + bias_attr=None, + data_format="NCDHW", + ): + super(Conv3DTranspose, self).__init__( + in_channels, + out_channels, + kernel_size, + True, + 3, + stride=stride, + padding=padding, + dilation=dilation, + output_padding=output_padding, + groups=groups, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + def forward(self, x, output_size=None): + if output_size is None: + output_padding = self.output_padding + else: + output_padding = 0 + + out = F.conv3d_transpose( + x, + self.weight, + bias=self.bias, + padding=self._padding, + output_padding=output_padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + output_size=output_size, + data_format=self._data_format, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/distance.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/distance.py new file mode 100644 index 0000000000000000000000000000000000000000..98381b471d6f346e53913bb554ec1ef8e3dbe7b4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/distance.py @@ -0,0 +1,83 @@ +# Copyright (c) 2022 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. + +from .. import Layer +from .. import functional as F + +__all__ = [] + + +class PairwiseDistance(Layer): + r""" + + It computes the pairwise distance between two vectors. The + distance is calculated by p-oreder norm: + + .. math:: + + \Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}. + + Parameters: + p (float, optional): The order of norm. Default: :math:`2.0`. + epsilon (float, optional): Add small value to avoid division by zero. + Default: :math:`1e-6`. + keepdim (bool, optional): Whether to reserve the reduced dimension + in the output Tensor. The result tensor is one dimension less than + the result of ``|x-y|`` unless :attr:`keepdim` is True. Default: False. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + + Shape: + - x: :math:`[N, D]` or :math:`[D]`, where :math:`N` is batch size, :math:`D` + is the dimension of the data. Available data type is float32, float64. + - y: :math:`[N, D]` or :math:`[D]`, y have the same dtype as x. + - output: The same dtype as input tensor. + - If :attr:`keepdim` is True, the output shape is :math:`[N, 1]` or :math:`[1]`, + depending on whether the input has data shaped as :math:`[N, D]`. + - If :attr:`keepdim` is False, the output shape is :math:`[N]` or :math:`[]`, + depending on whether the input has data shaped as :math:`[N, D]`. + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([[1., 3.], [3., 5.]], dtype=paddle.float64) + y = paddle.to_tensor([[5., 6.], [7., 8.]], dtype=paddle.float64) + dist = paddle.nn.PairwiseDistance() + distance = dist(x, y) + print(distance.numpy()) # [5. 5.] + + """ + + def __init__(self, p=2., epsilon=1e-6, keepdim=False, name=None): + super(PairwiseDistance, self).__init__() + self.p = p + self.epsilon = epsilon + self.keepdim = keepdim + self.name = name + + def forward(self, x, y): + + return F.pairwise_distance(x, y, self.p, self.epsilon, self.keepdim, + self.name) + + def extra_repr(self): + main_str = 'p={p}' + if self.epsilon != 1e-6: + main_str += ', epsilon={epsilon}' + if self.keepdim != False: + main_str += ', keepdim={keepdim}' + if self.name != None: + main_str += ', name={name}' + return main_str.format(**self.__dict__) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..51706ee336f6852bde004fbe93c20460b72cb96a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/loss.py @@ -0,0 +1,1771 @@ +# -*- coding: utf-8 -* +# 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. + +# TODO: define loss functions of neural network +import numpy as np +import paddle.fluid as fluid +import paddle +from .. import functional as F +from paddle.fluid.framework import ( + _varbase_creator, + in_dygraph_mode, + _in_legacy_dygraph, +) +from .. import Layer +from paddle import in_dynamic_mode + +__all__ = [] + + +class BCEWithLogitsLoss(Layer): + r""" + + This operator combines the sigmoid layer and the :ref:`api_paddle_nn_BCELoss` layer. + Also, we can see it as the combine of ``sigmoid_cross_entropy_with_logits`` + layer and some reduce operations. + + This measures the element-wise probability error in classification tasks + in which each class is independent. + This can be thought of as predicting labels for a data-point, where labels + are not mutually exclusive. For example, a news article can be about + politics, technology or sports at the same time or none of these. + + First this operator calculate loss function as follows: + + .. math:: + Out = -Labels * \log(\sigma(Logit)) - (1 - Labels) * \log(1 - \sigma(Logit)) + + We know that :math:`\sigma(Logit) = \frac{1}{1 + e^{-Logit}}`. By substituting this we get: + + .. math:: + Out = Logit - Logit * Labels + \log(1 + e^{-Logit}) + + For stability and to prevent overflow of :math:`e^{-Logit}` when Logit < 0, + we reformulate the loss as follows: + + .. math:: + Out = \max(Logit, 0) - Logit * Labels + \log(1 + e^{-\|Logit\|}) + + Then, if ``weight`` or ``pos_weight`` is not None, this operator multiply the + weight tensor on the loss `Out`. The ``weight`` tensor will attach different + weight on every items in the batch. The ``pos_weight`` will attach different + weight on the positive label of each class. + + Finally, this operator applies reduce operation on the loss. + If :attr:`reduction` set to ``'none'``, the operator will return the original loss `Out`. + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is :math:`Out = MEAN(Out)`. + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is :math:`Out = SUM(Out)`. + + Note that the target labels ``label`` should be numbers between 0 and 1. + + Args: + weight (Tensor, optional): A manual rescaling weight given to the loss of each + batch element. If given, it has to be a 1D Tensor whose size is `[N, ]`, + The data type is float32, float64. Default is ``'None'``. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + pos_weight (Tensor, optional): A weight of positive examples. Must be a vector + with length equal to the number of classes. The data type is float32, float64. + Default is ``'None'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shapes: + - logit (Tensor): The input predications tensor. 2-D tensor with shape: [N, `*`], + N is batch_size, `*` means number of additional dimensions. The ``logit`` + is usually the output of Linear layer. Available dtype is float32, float64. + - label (Tensor): The target labels tensor. 2-D tensor with the same shape as + ``logit``. The target labels which values should be numbers between 0 and 1. + Available dtype is float32, float64. + - output (Tensor): If ``reduction`` is ``'none'``, the shape of output is + same as ``logit`` , else the shape of output is scalar. + + Returns: + A callable object of BCEWithLogitsLoss. + + Examples: + .. code-block:: python + + import paddle + logit = paddle.to_tensor([5.0, 1.0, 3.0], dtype="float32") + label = paddle.to_tensor([1.0, 0.0, 1.0], dtype="float32") + bce_logit_loss = paddle.nn.BCEWithLogitsLoss() + output = bce_logit_loss(logit, label) + print(output.numpy()) # [0.45618808] + + """ + + def __init__( + self, weight=None, reduction='mean', pos_weight=None, name=None + ): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in BCEWithLogitsLoss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + + super(BCEWithLogitsLoss, self).__init__() + self.weight = weight + self.reduction = reduction + self.pos_weight = pos_weight + self.name = name + + def forward(self, logit, label): + out = paddle.nn.functional.binary_cross_entropy_with_logits( + logit, + label, + self.weight, + self.reduction, + self.pos_weight, + self.name, + ) + return out + + +class CrossEntropyLoss(Layer): + r""" + + By default, this operator implements the cross entropy loss function with softmax. This function + combines the calculation of the softmax operation and the cross entropy loss function + to provide a more numerically stable computing. + + This operator will calculate the cross entropy loss function without softmax when use_softmax=False. + + By default, this operator will calculate the mean of the result, and you can also affect + the default behavior by using the reduction parameter. Please refer to the part of + parameters for details. + + This operator can be used to calculate the softmax cross entropy loss with soft and hard labels. + Where, the hard labels mean the actual label value, 0, 1, 2, etc. And the soft labels + mean the probability of the actual label, 0.6, 0.8, 0.2, etc. + + The calculation of this operator includes the following two steps. + + - **I.softmax cross entropy** + + 1. Hard label (each sample can only be assigned into one category) + + 1.1. when use_softmax=True + + .. math:: + \\loss_j=-\text{logits}_{label_j}+\log\left(\sum_{i=0}^{C}\exp(\text{logits}_i)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories. + + 1.2. when use_softmax=False + + .. math:: + \\loss_j=-\log\left({P}_{label_j}\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories, P is input(the output of softmax). + + + 2. Soft label (each sample is assigned to multiple categories with a certain probability, and the probability sum is 1). + + 2.1. when use_softmax=True + + .. math:: + \\loss_j=-\sum_{i=0}^{C}\text{label}_i\left(\text{logits}_i-\log\left(\sum_{i=0}^{C}\exp(\text{logits}_i)\right)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories. + + 2.2. when use_softmax=False + + .. math:: + \\loss_j=-\sum_{j=0}^{C}\left({label}_j*\log\left({P}_{label_j}\right)\right) , j = 1,...,N + + where, N is the number of samples and C is the number of categories, P is input(the output of softmax). + + + + - **II.Weight and reduction processing** + + 1. Weight + + If the ``weight`` parameter is ``None`` , go to the next step directly. + + If the ``weight`` parameter is not ``None`` , the cross entropy of each sample is weighted by weight + according to soft_label = False or True as follows. + + 1.1. Hard labels (soft_label = False) + + .. math:: + \\loss_j=loss_j*weight[label_j] + + + 1.2. Soft labels (soft_label = True) + + .. math:: + \\loss_j=loss_j*\sum_{i}\left(weight[label_i]*logits_i\right) + + 2. reduction + + 2.1 if the ``reduction`` parameter is ``none`` + + Return the previous result directly + + 2.2 if the ``reduction`` parameter is ``sum`` + + Return the sum of the previous results + + .. math:: + \\loss=\sum_{j}loss_j + + 2.3 if the ``reduction`` parameter is ``mean`` , it will be processed according to + the ``weight`` parameter as follows. + + 2.3.1. If the ``weight`` parameter is ``None`` + + Return the average value of the previous results + + .. math:: + \\loss=\sum_{j}loss_j/N + + where, N is the number of samples and C is the number of categories. + + 2.3.2. If the 'weight' parameter is not 'None', the weighted average value of the previous result will be returned + + 1. Hard labels (soft_label = False) + + .. math:: + \\loss=\sum_{j}loss_j/\sum_{j}weight[label_j] + + 2. Soft labels (soft_label = True) + + .. math:: + \\loss=\sum_{j}loss_j/\sum_{j}\left(\sum_{i}weight[label_i]\right) + + + Parameters: + weight (Tensor, optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size C and the data type is float32, float64. + Default is ``'None'`` . + ignore_index (int64, optional): Specifies a target value that is ignored + and does not contribute to the loss. A negative value means that no label + value needs to be ignored. Only valid when soft_label = False. + Default is ``-100`` . + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`size_average` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + soft_label (bool, optional): Indicate whether label is soft. + If soft_label=False, the label is hard. If soft_label=True, the label is soft. + Default is ``False``. + axis (int, optional): The index of dimension to perform softmax calculations. + It should be in range :math:`[-1, rank - 1]`, where :math:`rank` is the number + of dimensions of input :attr:`input`. + Default is ``-1`` . + use_softmax (bool, optional): Indicate whether compute softmax before cross_entropy. + Default is ``True``. + name (str, optional): The name of the operator. Default is ``None`` . + For more information, please refer to :ref:`api_guide_Name` . + + + Shape: + - **input** (Tensor), the data type is float32, float64. Shape is + :math:`[N_1, N_2, ..., N_k, C]`, where C is number of classes , ``k >= 1`` . + Note: + + 1. when use_softmax=True, it expects unscaled logits. This operator should not be used with the + output of softmax operator, which will produce incorrect results. + + 2. when use_softmax=False, it expects the output of softmax operator. + + - **label** (Tensor) + + 1. If soft_label=False, the shape is + :math:`[N_1, N_2, ..., N_k]` or :math:`[N_1, N_2, ..., N_k, 1]`, k >= 1. + the data type is int32, int64, float32, float64, where each value is [0, C-1]. + + 2. If soft_label=True, the shape and data type should be same with ``input`` , + and the sum of the labels for each sample should be 1. + + - **output** (Tensor), Return the softmax cross_entropy loss of ``input`` and ``label``. + The data type is the same as input. + If :attr:`reduction` is ``'mean'`` or ``'sum'`` , the dimension of return value is ``1``. + If :attr:`reduction` is ``'none'``: + + 1. If soft_label = False, the dimension of return value is the same with ``label`` . + + 2. if soft_label = True, the dimension of return value is :math:`[N_1, N_2, ..., N_k, 1]` . + + Examples: + + .. code-block:: python + + # hard labels + import paddle + paddle.seed(99999) + N=100 + C=200 + reduction='mean' + input = paddle.rand([N, C], dtype='float64') + label = paddle.randint(0, C, shape=[N], dtype='int64') + weight = paddle.rand([C], dtype='float64') + + cross_entropy_loss = paddle.nn.loss.CrossEntropyLoss( + weight=weight, reduction=reduction) + dy_ret = cross_entropy_loss( + input, + label) + print(dy_ret.numpy()) #[5.41993642] + + .. code-block:: python + + # soft labels + import paddle + paddle.seed(99999) + axis = -1 + ignore_index = -100 + N = 4 + C = 3 + shape = [N, C] + reduction='mean' + weight = None + logits = paddle.uniform(shape, dtype='float64', min=0.1, max=1.0) + labels = paddle.uniform(shape, dtype='float64', min=0.1, max=1.0) + labels /= paddle.sum(labels, axis=axis, keepdim=True) + paddle_loss_mean = paddle.nn.functional.cross_entropy( + logits, + labels, + soft_label=True, + axis=axis, + weight=weight, + reduction=reduction) + print(paddle_loss_mean.numpy()) #[1.12908343] + + """ + + def __init__( + self, + weight=None, + ignore_index=-100, + reduction='mean', + soft_label=False, + axis=-1, + use_softmax=True, + name=None, + ): + super(CrossEntropyLoss, self).__init__() + self.weight = weight + self.reduction = reduction + self.ignore_index = ignore_index + self.soft_label = soft_label + self.axis = axis + self.use_softmax = use_softmax + self.name = name + + def forward(self, input, label): + ret = paddle.nn.functional.cross_entropy( + input, + label, + weight=self.weight, + ignore_index=self.ignore_index, + reduction=self.reduction, + soft_label=self.soft_label, + axis=self.axis, + use_softmax=self.use_softmax, + name=self.name, + ) + + return ret + + +class HSigmoidLoss(Layer): + """ + Hierarchical Sigmoid Layer. + + The hierarchical sigmoid organizes the classes into a complete binary tree to reduce the computational complexity + and speed up the model training, especially the training of language model. + Each leaf node of the complete binary tree represents a class(word) and each non-leaf node acts as a binary classifier. + For each class(word), there's a unique path from root to itself, hsigmoid calculate the cost for each non-leaf node on + the path, and sum them to get a total cost. + Comparing to softmax, the OP can reduce the computational complexity from :math:`O(N)` to :math:`O(logN)`, where :math:`N` + represents the number of classes or the size of word dict. + + The OP supports default tree and custom tree. For the default tree, you can refer to `Hierarchical Probabilistic Neural + Network Language Model _`. For the custom + tree, you need to set :attr:`is_custom` to True, and do the following steps (take the language model as an example): + + 1. Using a custom word dict to build a binary tree, each leaf node should be an word in the word dict. + 2. Creating a dict map word_id -> path that from the word to the root node, we call it path_table. + 3. Creating a dict map word_id -> code of path that from the word to the root node, we call it path_code. + Code means the label of each binary classifier, 1 indicate true, 0 indicate false. + 4. Now, each word should has its path and code along the path, you can pass a batch of path and code related + to the same batch of inputs. + + Parameters: + feature_size (int): The number of features. + num_classes (int): The number of classes or the size of word dict, must be greater than 2. + If the default tree is used (:attr:`is_custom` is set to False), :attr:`num_classes` + should not be None. If the custom tree is used (:attr:`is_custom` is set to True), + :attr:`num_classes` should be the number of non-leaf nodes, which indicates the num of + classes using by the binary classifier. + weight_attr (ParamAttr, optional): The parameter attribute for the learnable weights + of hsigmoid. If it is set to None or one attribute of ParamAttr, hsigmoid will create a + ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is + initialized with Xavier. Default is None. + bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of hsigmoid. If it + is set to False, no bias will be added. If it is set to None or one attribute of ParamAttr, + hsigmoid will create a ParamAttr as bias_attr. If the Initializer of the bias_attr is not + set, the bias is initialized zero. Default is None. + is_custom (bool, optional): Whether use custom binary tree. If it's True, `path_table` and + `path_code` should be passed to its forward method, otherwise `path_table` and `path_code` + should not be passed to its forward method. Default is False. + is_sparse (bool, optional): Whether use sparse updating instead of dense updating, if it's True, + the gradient of weight and input will be sparse. Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + input (Tensor): The input tensor. The shapes is [N, D], where N is batch size and D is feature size. It's data type should be float32, float64. + label (Tensor): It's shapes is [N, 1]. It's data type should be int64. + output (Tensor): The HSigmoid Loss of ``input`` and ``label``. Shape is [N, 1] + + Examples: + .. code-block:: python + + import paddle + paddle.set_device('cpu') + + input = paddle.uniform([4, 3]) + # [[0.56194401 -0.22450298 -0.10741806] # random + # [0.36136317 0.23556745 0.88748658] # random + # [0.18151939 0.80947340 -0.31078976] # random + # [0.68886101 -0.14239830 -0.41297770]] # random + label = paddle.to_tensor([0, 1, 4, 5]) + m = paddle.nn.HSigmoidLoss(3, 5) + out = m(input, label) + # [[2.42524505] + # [1.74917245] + # [3.14571381] + # [2.34564662]] + """ + + def __init__( + self, + feature_size, + num_classes, + weight_attr=None, + bias_attr=None, + is_custom=False, + is_sparse=False, + name=None, + ): + super(HSigmoidLoss, self).__init__() + if (num_classes < 2) and (not is_custom): + raise ValueError( + "num_classes must not be less than 2 with default tree" + ) + + if (not is_custom) and (is_sparse): + print("Sparse mode should not be used without custom tree") + is_sparse = False + + self._feature_size = feature_size + self._num_classes = num_classes + self._is_custom = is_custom + self._is_sparse = is_sparse + + self._weight_attr = weight_attr + self._bias_attr = bias_attr + + self._name = name + self._dtype = paddle.get_default_dtype() + + remote_prefetch = is_sparse + print( + "With sparse mode, if your models has only" + " small parameter prefetch may cause speed down" + ) + + C = self._num_classes if is_custom else self._num_classes - 1 + self.weight = self.create_parameter( + [C, self._feature_size], + attr=self._weight_attr, + is_bias=False, + dtype=self._dtype, + ) + self.bias = self.create_parameter( + [C, 1], attr=self._bias_attr, is_bias=True, dtype=self._dtype + ) + + def forward(self, input, label, path_table=None, path_code=None): + out = F.hsigmoid_loss( + input, + label, + self._num_classes, + self.weight, + self.bias, + path_table=path_table, + path_code=path_code, + is_sparse=self._is_sparse, + name=self._name, + ) + return out + + +class MSELoss(Layer): + r""" + **Mean Square Error Loss** + Computes the mean square error (squared L2 norm) of given input and label. + + If :attr:`reduction` is set to ``'none'``, loss is calculated as: + + .. math:: + Out = (input - label)^2 + + If :attr:`reduction` is set to ``'mean'``, loss is calculated as: + + .. math:: + Out = \operatorname{mean}((input - label)^2) + + If :attr:`reduction` is set to ``'sum'``, loss is calculated as: + + .. math:: + Out = \operatorname{sum}((input - label)^2) + + where `input` and `label` are `float32` tensors of same shape. + + Parameters: + reduction (string, optional): The reduction method for the output, + could be 'none' | 'mean' | 'sum'. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned. + If :attr:`size_average` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + + Shape: + input (Tensor): Input tensor, the data type is float32 or float64 + label (Tensor): Label tensor, the data type is float32 or float64 + output (Tensor): output tensor storing the MSE loss of input and label, the data type is same as input. + + Examples: + .. code-block:: python + + import paddle + + mse_loss = paddle.nn.loss.MSELoss() + input = paddle.to_tensor([1.5]) + label = paddle.to_tensor([1.7]) + output = mse_loss(input, label) + print(output) + # [0.04000002] + """ + + def __init__(self, reduction='mean'): + super(MSELoss, self).__init__() + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'MSELoss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + self.reduction = reduction + + def forward(self, input, label): + if not in_dynamic_mode(): + fluid.data_feeder.check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'MSELoss' + ) + fluid.data_feeder.check_variable_and_dtype( + label, 'label', ['float32', 'float64'], 'MSELoss' + ) + + if in_dygraph_mode(): + square_out = paddle._C_ops.square(paddle.subtract(input, label)) + else: + square_out = paddle.square(paddle.subtract(input, label)) + if self.reduction == 'none': + return square_out + + reduce_op = 'reduce_mean' + if self.reduction == 'sum': + reduce_op = 'reduce_sum' + + return getattr(fluid.layers, reduce_op)(square_out) + + +class L1Loss(Layer): + r""" + + Construct a callable object of the ``L1Loss`` class. + The L1Loss layer calculates the L1 Loss of ``input`` and ``label`` as follows. + + If `reduction` set to ``'none'``, the loss is: + + .. math:: + Out = \lvert input - label\rvert + + If `reduction` set to ``'mean'``, the loss is: + + .. math:: + Out = MEAN(\lvert input - label\rvert) + + If `reduction` set to ``'sum'``, the loss is: + + .. math:: + Out = SUM(\lvert input - label\rvert) + + + Parameters: + reduction (str, optional): Indicate the reduction to apply to the loss, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'none'``, the unreduced loss is returned; + If `reduction` is ``'mean'``, the reduced mean loss is returned. + If `reduction` is ``'sum'``, the reduced sum loss is returned. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input (Tensor): The input tensor. The shapes is ``[N, *]``, where N is batch size and `*` means any number of additional dimensions. It's data type should be float32, float64, int32, int64. + - label (Tensor): label. The shapes is ``[N, *]``, same shape as ``input`` . It's data type should be float32, float64, int32, int64. + - output (Tensor): The L1 Loss of ``input`` and ``label``. + If `reduction` is ``'none'``, the shape of output loss is ``[N, *]``, the same as ``input`` . + If `reduction` is ``'mean'`` or ``'sum'``, the shape of output loss is [1]. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1.5, 0.8], [0.2, 1.3]]) + label = paddle.to_tensor([[1.7, 1], [0.4, 0.5]]) + + l1_loss = paddle.nn.L1Loss() + output = l1_loss(input, label) + print(output.numpy()) + # [0.35] + + l1_loss = paddle.nn.L1Loss(reduction='sum') + output = l1_loss(input, label) + print(output.numpy()) + # [1.4] + + l1_loss = paddle.nn.L1Loss(reduction='none') + output = l1_loss(input, label) + print(output) + # [[0.20000005 0.19999999] + # [0.2 0.79999995]] + + """ + + def __init__(self, reduction='mean', name=None): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in L1Loss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + super(L1Loss, self).__init__() + self.reduction = reduction + self.name = name + + def forward(self, input, label): + return paddle.nn.functional.l1_loss( + input, label, self.reduction, name=self.name + ) + + +class BCELoss(Layer): + """ + + This interface is used to construct a callable object of the ``BCELoss`` class. + The BCELoss layer measures the binary_cross_entropy loss between input predictions ``input`` + and target labels ``label`` . The binary_cross_entropy loss can be described as: + + If :attr:`weight` is set, the loss is: + + .. math:: + Out = -1 * weight * (label * log(input) + (1 - label) * log(1 - input)) + + If :attr:`weight` is None, the loss is: + + .. math:: + Out = -1 * (label * log(input) + (1 - label) * log(1 - input)) + + If :attr:`reduction` set to ``'none'``, the interface will return the original loss `Out`. + + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is: + + .. math:: + Out = MEAN(Out) + + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is: + + .. math:: + Out = SUM(Out) + + Note that the input predictions ``input`` always be the output of sigmoid, and the target labels ``label`` + should be numbers between 0 and 1. + + Parameters: + weight (Tensor, optional): A manual rescaling weight given to the loss of each + batch element. If given, has to be a Tensor of size nbatch and the data type + is float32, float64. Default is ``'None'``. + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input (Tensor): 2-D tensor with shape: ``[N, *]``, N is batch_size, `*` means + number of additional dimensions. The input ``input`` should always + be the output of sigmod. Available dtype is float32, float64. + - label (Tensor): 2-D tensor with the same shape as ``input``. The target + labels which values should be numbers between 0 and 1. Available + dtype is float32, float64. + - output (Tensor): If ``reduction`` is ``'none'``, the shape of output is + same as ``input`` , else the shape of output is scalar. + + Returns: + A callable object of BCELoss. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([0.5, 0.6, 0.7]) + label = paddle.to_tensor([1.0, 0.0, 1.0]) + bce_loss = paddle.nn.BCELoss() + output = bce_loss(input, label) + print(output) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.65537101]) + + """ + + def __init__(self, weight=None, reduction='mean', name=None): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in bce_loss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + + super(BCELoss, self).__init__() + self.weight = weight + self.reduction = reduction + self.name = name + + def forward(self, input, label): + out = paddle.nn.functional.binary_cross_entropy( + input, label, self.weight, self.reduction, self.name + ) + return out + + +class NLLLoss(Layer): + r""" + + This class accepts input and target label and returns negative log likelihood + cross error. It is useful to train a classification problem with C classes. + + The input for the loss is expected to contain log-probabilities of + each classes. It has to be a Tensor of size either (batch_size, C) or + (batch_size, C, d1, d2, ..., dK) with K >= 1 for the K-dimensional case. + The label for the loss should be a class index in the range [0, C-1] + where C is the number of classes. If ignore_index is specified, the + specified target value does not contribute to the input gradient. + + If the optional argument `weight` is provided, it should be a 1D Tensor + assigning weight to each of the classed. This is particularly useful + when you have an unbalanced training set. + + The loss is calculated as follows. + The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as: + + .. math:: + + \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad + l_n = - w_{y_n} x_{n,y_n}, \quad + w_{c} = \text{weight}[c] \cdot \mathbb{1}\{c \not= \text{ignore_index}\}, + + where :math:`N` is the batch size. If :attr:`reduction` is not ``'none'`` + (default ``'mean'``), then + + .. math:: + + \ell(x, y) = + \left\{ + \begin{array}{lcl} + \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n}} l_n, & + \text{if reduction} = \text{'mean';}\\ + \sum_{n=1}^N l_n, & + \text{if reduction} = \text{'sum'.} + \end{array} + \right. + + Parameters: + weight (Tensor, optional): Weight tensor, a manual rescaling weight given + to each class. If given, it has to be a 1D Tensor whose size is `[C, ]`. Otherwise, + it treated as if having all ones. the data type is + float32, float64, Default is ``'None'``. + ignore_index (int, optional): Specifies a target value that is ignored + and does not contribute to the input gradient. + reduction (str, optional): Indicate how to average the loss, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'mean'``, the reduced mean loss is returned; + if `reduction` is ``'sum'``, the reduced sum loss is returned; + if `reduction` is ``'none'``, no reduction will be apllied. + Default is ``'mean'``. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Shape: + - input (Tensor): Input tensor, the shape is :math:`[N, C]`, `C` is the number of classes. + But in K-dimension situation, the shape is :math:`[N, C, d_1, d_2, ..., d_K]`. + The data type is float32, float64. + - label (Tensor): Label tensor, the shape is :math:`[N,]` or :math:`[N, d_1, d_2, ..., d_K]`. + The data type is int64. + - output (Tensor): the `negative log likelihood loss` between input `x` and `label`. + If `reduction` is `'none'`, the shape is `[N, *]`. + If `reduction` is `'sum'` or `'mean'`, the shape is `[1]`. + + Examples: + .. code-block:: python + + import paddle + + nll_loss = paddle.nn.loss.NLLLoss() + log_softmax = paddle.nn.LogSoftmax(axis=1) + + input = paddle.to_tensor([[0.88103855, 0.9908683 , 0.6226845 ], + [0.53331435, 0.07999352, 0.8549948 ], + [0.25879037, 0.39530203, 0.698465 ], + [0.73427284, 0.63575995, 0.18827209], + [0.05689114, 0.0862954 , 0.6325046 ]], "float32") + log_out = log_softmax(input) + label = paddle.to_tensor([0, 2, 1, 1, 0], "int64") + result = nll_loss(log_out, label) + print(result) # Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=True, [1.07202101]) + + """ + + def __init__( + self, weight=None, ignore_index=-100, reduction='mean', name=None + ): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in nll_loss should be 'sum', 'mean' or " + "'none', but received %s, which is not allowed." % reduction + ) + super(NLLLoss, self).__init__() + self._weight = weight + self._ignore_index = ignore_index + self._reduction = reduction + self._name = name + + def forward(self, input, label): + return F.nll_loss( + input, + label, + weight=self._weight, + ignore_index=self._ignore_index, + reduction=self._reduction, + name=self._name, + ) + + +class KLDivLoss(Layer): + r""" + + Generate a callable object of 'KLDivLoss' to calculate the + Kullback-Leibler divergence loss between Input(X) and + Input(Target). Notes that Input(X) is the log-probability + and Input(Target) is the probability. + + KL divergence loss is calculated as follows: + + $$l(x, y) = y * (\log(y) - x)$$ + + Parameters: + reduction (Tensor): Indicate how to average the loss, + the candicates are ``'none'`` | ``'batchmean'`` | ``'mean'`` | ``'sum'``. + If `reduction` is ``'mean'``, the reduced mean loss is returned; + If `reduction` is ``'batchmean'``, the sum loss divided by batch size is returned; + if `reduction` is ``'sum'``, the reduced sum loss is returned; + if `reduction` is ``'none'``, no reduction will be apllied. + Default is ``'mean'``. + + Shape: + - input (Tensor): ``(N, *)``, where ``*`` means, any number of additional dimensions. + - label (Tensor): ``(N, *)``, same shape as input. + - output (Tensor): tensor with shape: [1] by default. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + shape = (5, 20) + x = paddle.uniform(shape, min=-10, max=10).astype('float32') + target = paddle.uniform(shape, min=-10, max=10).astype('float32') + + # 'batchmean' reduction, loss shape will be [1] + kldiv_criterion = nn.KLDivLoss(reduction='batchmean') + pred_loss = kldiv_criterion(x, target) + # shape=[1] + + # 'mean' reduction, loss shape will be [1] + kldiv_criterion = nn.KLDivLoss(reduction='mean') + pred_loss = kldiv_criterion(x, target) + # shape=[1] + + # 'sum' reduction, loss shape will be [1] + kldiv_criterion = nn.KLDivLoss(reduction='sum') + pred_loss = kldiv_criterion(x, target) + # shape=[1] + + # 'none' reduction, loss shape is same with X shape + kldiv_criterion = nn.KLDivLoss(reduction='none') + pred_loss = kldiv_criterion(x, target) + # shape=[5, 20] + + """ + + def __init__(self, reduction='mean'): + super(KLDivLoss, self).__init__() + self.reduction = reduction + + def forward(self, input, label): + out = F.kl_div(input, label, self.reduction) + return out + + +class MarginRankingLoss(Layer): + r""" + + This interface is used to construct a callable object of the ``MarginRankingLoss`` class. + The MarginRankingLoss layer calculates the margin rank loss between the input, other and label + , use the math function as follows. + + .. math:: + margin\_rank\_loss = max(0, -label * (input - other) + margin) + + If :attr:`reduction` set to ``'mean'``, the reduced mean loss is: + + .. math:: + Out = MEAN(margin\_rank\_loss) + + If :attr:`reduction` set to ``'sum'``, the reduced sum loss is: + + .. math:: + Out = SUM(margin\_rank\_loss) + + If :attr:`reduction` set to ``'none'``, just return the origin ``margin_rank_loss``. + + Parameters: + margin (float, optional): The margin value to add, default value is 0; + reduction (str, optional): Indicate the reduction to apply to the loss, the candicates are ``'none'``, ``'mean'``, ``'sum'``.If :attr:`reduction` is ``'none'``, the unreduced loss is returned; If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned. If :attr:`reduction` is ``'sum'``, the reduced sum loss is returned. Default is ``'mean'``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + + input: N-D Tensor, the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + + other: N-D Tensor, `other` have the same shape and dtype as `input`. + + label: N-D Tensor, label have the same shape and dtype as `input`. + + output: If :attr:`reduction` is ``'mean'`` or ``'sum'`` , the out shape is :math:`[1]`, otherwise the shape is the same as `input` .The same dtype as input tensor. + + Returns: + A callable object of MarginRankingLoss. + + Examples: + + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1, 2], [3, 4]], dtype="float32") + other = paddle.to_tensor([[2, 1], [2, 4]], dtype="float32") + label = paddle.to_tensor([[1, -1], [-1, -1]], dtype="float32") + margin_rank_loss = paddle.nn.MarginRankingLoss() + loss = margin_rank_loss(input, other, label) + + print(loss) + # [0.75] + """ + + def __init__(self, margin=0.0, reduction='mean', name=None): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in MarginRankingLoss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + super(MarginRankingLoss, self).__init__() + self.margin = margin + self.reduction = reduction + self.name = name + + def forward(self, input, other, label): + out = paddle.nn.functional.margin_ranking_loss( + input, other, label, self.margin, self.reduction, self.name + ) + return out + + +class CTCLoss(Layer): + """ + + An operator integrating the open source Warp-CTC library (https://github.com/baidu-research/warp-ctc) + to compute Connectionist Temporal Classification (CTC) loss. + It can be aliased as softmax with CTC, since a native softmax activation + is interated to the Warp-CTC library to normalize values for each row of the input tensor. + + Parameters: + blank (int, optional): The blank label index of Connectionist Temporal Classification (CTC) loss, which is in the half-opened interval [0, num_classes + 1). The data type must be int32. Default is 0. + reduction (string, optional): Indicate how to average the loss, the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. If :attr:`reduction` is ``'mean'``, the output loss will be divided by the label_lengths, and then return the mean of quotient; If :attr:`reduction` is ``'sum'``, return the sum of loss; If :attr:`reduction` is ``'none'``, no reduction will be applied. Default is ``'mean'``. + + Shape: + log_probs (Tensor): The unscaled probability sequence with padding, which is a 3-D Tensor. The tensor shape is [max_logit_length, batch_size, num_classes + 1], where max_logit_length is the longest length of input logit sequence. The data type should be float32 or float64. + labels (Tensor): The ground truth sequence with padding, which must be a 3-D Tensor. The tensor shape is [batch_size, max_label_length], where max_label_length is the longest length of label sequence. The data type must be int32. + input_lengths (Tensor): The length for each input sequence, it should have shape [batch_size] and dtype int64. + label_lengths (Tensor): The length for each label sequence, it should have shape [batch_size] and dtype int64. + norm_by_times (bool, default false) – Whether to normalize the gradients by the number of time-step, which is also the sequence’s length. There is no need to normalize the gradients if reduction mode is 'mean'. + + Returns: + Tensor, The Connectionist Temporal Classification (CTC) loss between ``log_probs`` and ``labels``. If attr:`reduction` is ``'none'``, the shape of loss is [batch_size], otherwise, the shape of loss is [1]. Data type is the same as ``log_probs``. + + Examples: + + .. code-block:: python + + # declarative mode + import paddle + + # length of the longest logit sequence + max_seq_length = 4 + #length of the longest label sequence + max_label_length = 3 + # number of logit sequences + batch_size = 2 + # class num + class_num = 3 + + log_probs = paddle.to_tensor([[[4.17021990e-01, 7.20324516e-01, 1.14374816e-04], + [3.02332580e-01, 1.46755889e-01, 9.23385918e-02]], + + [[1.86260208e-01, 3.45560730e-01, 3.96767467e-01], + [5.38816750e-01, 4.19194520e-01, 6.85219526e-01]], + + [[2.04452246e-01, 8.78117442e-01, 2.73875929e-02], + [6.70467496e-01, 4.17304814e-01, 5.58689833e-01]], + + [[1.40386939e-01, 1.98101491e-01, 8.00744593e-01], + [9.68261600e-01, 3.13424170e-01, 6.92322612e-01]], + + [[8.76389146e-01, 8.94606650e-01, 8.50442126e-02], + [3.90547849e-02, 1.69830427e-01, 8.78142476e-01]]], dtype="float32") + labels = paddle.to_tensor([[1, 2, 2], + [1, 2, 2]], dtype="int32") + input_lengths = paddle.to_tensor([5, 5], dtype="int64") + label_lengths = paddle.to_tensor([3, 3], dtype="int64") + + loss = paddle.nn.CTCLoss(blank=0, reduction='none')(log_probs, labels, + input_lengths, + label_lengths) + print(loss) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [3.91798496, 2.90765190]) + + loss = paddle.nn.CTCLoss(blank=0, reduction='mean')(log_probs, labels, + input_lengths, + label_lengths) + print(loss) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.13760614]) + """ + + def __init__(self, blank=0, reduction='mean'): + super(CTCLoss, self).__init__() + self.blank = blank + self.reduction = reduction + + def forward( + self, + log_probs, + labels, + input_lengths, + label_lengths, + norm_by_times=False, + ): + return paddle.nn.functional.ctc_loss( + log_probs, + labels, + input_lengths, + label_lengths, + self.blank, + self.reduction, + norm_by_times=norm_by_times, + ) + + +class SmoothL1Loss(Layer): + r""" + This operator calculates smooth_l1_loss. Creates a criterion that uses a squared + term if the absolute element-wise error falls below 1 and an L1 term otherwise. + In some cases it can prevent exploding gradients and it is more robust and less + sensitivity to outliers. Also known as the Huber loss: + + .. math:: + + loss(x, y) = \frac{1}{n}\sum_{i}z_i + + where :math:`z_i` is given by: + + .. math:: + + \mathop{z_i} = \left\{\begin{array}{rcl} + 0.5(x_i - y_i)^2 & & {if |x_i - y_i| < \delta} \\ + \delta * |x_i - y_i| - 0.5 * \delta^2 & & {otherwise} + \end{array} \right. + + Parameters: + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the reduced sum loss is returned. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned. + Default is ``'mean'``. + delta (float, optional): Specifies the hyperparameter :math:`\delta` to be used. + The value determines how large the errors need to be to use L1. Errors + smaller than delta are minimized with L2. Parameter is ignored for + negative/zero values. Default value is :math:`1.0`. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Call Parameters: + + input (Tensor): Input tensor, the data type is float32 or float64. Shape is (N, C), + where C is number of classes, and if shape is more than 2D, + this is (N, C, D1, D2,..., Dk), k >= 1. + + label (Tensor): Label tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + Returns: + Tensor, The tensor storing the smooth_l1_loss of input and label. + + Examples: + .. code-block:: python + + import paddle + input = paddle.rand([3, 3]).astype("float32") + label = paddle.rand([3, 3]).astype("float32") + loss = paddle.nn.SmoothL1Loss() + output = loss(input, label) + print(output) + # [0.049606] + """ + + def __init__(self, reduction='mean', delta=1.0, name=None): + super(SmoothL1Loss, self).__init__() + self.reduction = reduction + self.delta = delta + self.name = name + + def forward(self, input, label): + return F.smooth_l1_loss( + input, + label, + reduction=self.reduction, + delta=self.delta, + name=self.name, + ) + + +class MultiLabelSoftMarginLoss(Layer): + r"""Creates a criterion that optimizes a multi-class multi-classification + hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) + and output :math:`y` (which is a 2D `Tensor` of target class indices). + For each sample in the mini-batch: + + .. math:: + \text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)} + + where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`, \ + :math:`y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}`, \ + :math:`0 \leq y[j] \leq \text{x.size}(0)-1`, \ + and :math:`i \neq y[j]` for all :math:`i` and :math:`j`. + :math:`y` and :math:`x` must have the same size. + + Parameters: + weight (Tensor,optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size C and the data type is float32, float64. + Default is ``'None'`` . + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Call parameters: + input (Tensor): Input tensor, the data type is float32 or float64. Shape is (N, C), where C is number of classes, and if shape is more than 2D, this is (N, C, D1, D2,..., Dk), k >= 1. + label (Tensor): Label tensor containing 1 or -1, the data type is float32 or float64. The shape of label is the same as the shape of input. + + Shape: + input: N-D Tensor, the shape is [N, \*], N is batch size and `\*` means number of classes, available dtype is float32, float64. The sum operationoperates over all the elements. + label: N-D Tensor, same shape as the input. + output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the input. + + Returns: + A callable object of MultiLabelSoftMarginLoss. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input = paddle.to_tensor([[1, -2, 3], [0, -1, 2], [1, 0, 1]], dtype=paddle.float32) + label = paddle.to_tensor([[-1, 1, -1], [1, 1, 1], [1, -1, 1]], dtype=paddle.float32) + + multi_label_soft_margin_loss = nn.MultiLabelSoftMarginLoss(reduction='none') + loss = multi_label_soft_margin_loss(input, label) + print(loss) + # Tensor([3.49625897, 0.71111226, 0.43989015]) + + multi_label_soft_margin_loss = nn.MultiLabelSoftMarginLoss(reduction='mean') + loss = multi_label_soft_margin_loss(input, label) + print(loss) + # Tensor([1.54908717]) + """ + + def __init__(self, weight=None, reduction="mean", name=None): + super(MultiLabelSoftMarginLoss, self).__init__() + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "'reduction' in 'MultiLabelSoftMarginloss' should be 'sum', 'mean' or 'none', " + "but received {}.".format(reduction) + ) + self.weight = weight + self.reduction = reduction + self.name = name + + def forward(self, input, label): + return F.multi_label_soft_margin_loss( + input, + label, + weight=self.weight, + reduction=self.reduction, + name=self.name, + ) + + +class HingeEmbeddingLoss(Layer): + r""" + Create a callable object of `HingeEmbeddingLoss` to calculates hinge_embedding_loss. Measures the loss given an input tensor :math:`x` and a labels tensor :math:`y`(containing 1 or -1). + This is usually used for measuring whether two inputs are similar or dissimilar, e.g. using the L1 pairwise distance as :math:`x`, + and is typically used for learning nonlinear embeddings or semi-supervised learning. + + The loss function for :math:`n`-th sample in the mini-batch is + + .. math:: + l_n = \begin{cases} + x_n, & \text{if}\; y_n = 1,\\ + \max \{0, \Delta - x_n\}, & \text{if}\; y_n = -1, + \end{cases} + + and the total loss functions is + + .. math:: + \ell(x, y) = \begin{cases} + \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\ + \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.} + \end{cases} + + where :math:`L = \{l_1,\dots,l_N\}^\top`. + + Parameters: + + margin (float, optional): Specifies the hyperparameter margin to be used. + The value determines how large the input need to be to calculate in + hinge_embedding_loss. When label is -1, Input smaller than margin are minimized with hinge_embedding_loss. + Default = 1.0 + reduction (str, optional): Indicate how to average the loss by batch_size, + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Call Parameters: + + input (Tensor): Input tensor, the data type is float32 or float64. Shape is (N, C), where C is number of classes, and if shape is more than 2D, this is (N, C, D1, D2,..., Dk), k >= 1. + + label (Tensor): Label tensor containing 1 or -1, the data type is float32 or float64. The shape of label is the same as the shape of input. + + Shape: + + input: N-D Tensor, the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. The sum operationoperates over all the elements. + + label: N-D Tensor, same shape as the input. + + output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the input. + + Returns: + + Tensor, The tensor variable storing the hinge_embedding_loss of input and label. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + input = paddle.to_tensor([[1, -2, 3], [0, -1, 2], [1, 0, 1]], dtype=paddle.float32) + # label elements in {1., -1.} + label = paddle.to_tensor([[-1, 1, -1], [1, 1, 1], [1, -1, 1]], dtype=paddle.float32) + + hinge_embedding_loss = nn.HingeEmbeddingLoss(margin=1.0, reduction='none') + loss = hinge_embedding_loss(input, label) + print(loss) + # Tensor([[0., -2., 0.], + # [0., -1., 2.], + # [1., 1., 1.]]) + + hinge_embedding_loss = nn.HingeEmbeddingLoss(margin=1.0, reduction='mean') + loss = hinge_embedding_loss(input, label) + print(loss) + # Tensor([0.22222222]) + """ + + def __init__(self, margin=1.0, reduction="mean", name=None): + super(HingeEmbeddingLoss, self).__init__() + self.margin = margin + self.reduction = reduction + self.name = name + + def forward(self, input, label): + return F.hinge_embedding_loss( + input, + label, + reduction=self.reduction, + margin=self.margin, + name=self.name, + ) + + +class CosineEmbeddingLoss(Layer): + r""" + This interface is used to construct a callable object of the ``CosineEmbeddingLoss`` class. + The CosineEmbeddingLoss layer measures the cosine_embedding loss between input predictions ``input1``, ``input2`` + and target labels ``label`` with values 1 or 0. This is used for measuring whether two inputs are similar or + dissimilar and is typically used for learning nonlinear embeddings or semi-supervised learning. + The cosine embedding loss can be described as: + + If label = 1, then the loss value can be calculated as follow: + + .. math:: + Out = 1 - cos(input1, input2) + + If label = -1, then the loss value can be calculated as follow: + + .. math:: + Out = max(0, cos(input1, input2)) - margin + + The operator cos can be described as follow: + .. math:: + cos(x1, x2) = \frac{x1 \cdot{} x2}{\Vert x1 \Vert_2 * \Vert x2 \Vert_2} + + Parameters: + margin (float, optional): Should be a number from :math:`-1` to :math:`1`, + :math:`0` to :math:`0.5` is suggested. If :attr:`margin` is missing, the + default value is :math:`0`. + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, + ``'mean'``: the sum of the output will be divided by the number of + elements in the output, ``'sum'``: the output will be summed. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + input1 (Tensor): tensor with shape: [N, M] or [M], 'N' means batch size, 'M' means the length of input array. + Available dtypes are float32, float64. + input2 (Tensor): tensor with shape: [N, M] or [M], 'N' means batch size, 'M' means the length of input array. + Available dtypes are float32, float64. + label (Tensor): tensor with shape: [N] or [1]. The target labels values should be -1 or 1. + Available dtypes are int32, int64, float32, float64. + output (Tensor): Tensor, the cosine embedding Loss of Tensor ``input1`` ``input2`` and ``label``. + If `reduction` is ``'none'``, the shape of output loss is [N], the same as ``input`` . + If `reduction` is ``'mean'`` or ``'sum'``, the shape of output loss is [1]. + + Examples: + .. code-block:: python + + import paddle + + input1 = paddle.to_tensor([[1.6, 1.2, -0.5], [3.2, 2.6, -5.8]], 'float32') + input2 = paddle.to_tensor([[0.5, 0.5, -1.8], [2.3, -1.4, 1.1]], 'float32') + label = paddle.to_tensor([1, -1], 'int64') + + cosine_embedding_loss = paddle.nn.CosineEmbeddingLoss(margin=0.5, reduction='mean') + output = cosine_embedding_loss(input1, input2, label) + print(output) # [0.21155193] + + cosine_embedding_loss = paddle.nn.CosineEmbeddingLoss(margin=0.5, reduction='sum') + output = cosine_embedding_loss(input1, input2, label) + print(output) # [0.42310387] + + cosine_embedding_loss = paddle.nn.CosineEmbeddingLoss(margin=0.5, reduction='none') + output = cosine_embedding_loss(input1, input2, label) + print(output) # [0.42310387, 0. ] + + """ + + def __init__(self, margin=0, reduction='mean', name=None): + if margin > 1 or margin < -1: + raise ValueError( + "The value of 'margin' should be in the interval of [-1, 1], but received %f, which is not allowed." + % margin + ) + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' should be 'sum', 'mean' or " + "'none', but received %s, which is not allowed." % reduction + ) + super(CosineEmbeddingLoss, self).__init__() + self.margin = margin + self.reduction = reduction + self.name = name + + def forward(self, input1, input2, label): + return F.cosine_embedding_loss( + input1, + input2, + label, + margin=self.margin, + reduction=self.reduction, + name=self.name, + ) + + +class TripletMarginWithDistanceLoss(Layer): + r""" + Creates a criterion that measures the triplet loss given an input + tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`. + This is used for measuring a relative similarity between samples. A triplet + is composed by `input`, `positive` and `negative` (i.e., `input`, `positive examples` and `negative + examples` respectively). The shapes of all input tensors should be + :math:`(N, D)`. + + The loss function for each sample in the mini-batch is: + + .. math:: + L(input, pos, neg) = \max \{d(input_i, pos_i) - d(input_i, neg_i) + {\rm margin}, 0\} + + where the default `distance_function` + + .. math:: + d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_2 + + or user can define their own distance function. `margin` is a nonnegative margin representing the minimum difference + between the positive and negative distances that is required for the loss to be 0. If `swap` is true, it will compare distance of (input, negative) with + distance of (negative, positive) and change it to the smaller one. For more details see http://www.bmva.org/bmvc/2016/papers/paper119/paper119.pdf. + + Parameters: + distance_function (Callable, Optional): Quantifies the distance between two tensors. if not specified, 2 norm functions will be used. + + margin (float, Optional):Default: :math:`1`.A nonnegative margin representing the minimum difference + between the positive and negative distances required for the loss to be 0. Larger + margins penalize cases where the negative examples are not distant enough from the + anchors, relative to the positives. + + swap (bool, Optional):The distance swap changes the negative distance to the swap distance (distance between positive samples + and negative samples) if swap distance smaller than negative distance. Default: ``False``. + + reduction (str, Optional):Indicate how to average the loss by batch_size. + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shapes: + input (Tensor):Input tensor, the data type is float32 or float64. + the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + + positive (Tensor):Positive tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + negative (Tensor):Negative tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + output(Tensor): The tensor variable storing the triplet_margin_with_distance_loss of input and positive and negative. + + Return: + A callable object of TripletMarginWithDistanceLoss + + Examples: + .. code-block:: python + + import paddle + from paddle.nn import TripletMarginWithDistanceLoss + + input = paddle.to_tensor([[1, 5, 3], [0, 3, 2], [1, 4, 1]], dtype=paddle.float32) + positive= paddle.to_tensor([[5, 1, 2], [3, 2, 1], [3, -1, 1]], dtype=paddle.float32) + negative = paddle.to_tensor([[2, 1, -3], [1, 1, -1], [4, -2, 1]], dtype=paddle.float32) + triplet_margin_with_distance_loss = TripletMarginWithDistanceLoss(reduction='none') + loss = triplet_margin_with_distance_loss(input, positive, negative,) + print(loss) + # Tensor([0. , 0.57496738, 0. ]) + + triplet_margin_with_distance_loss = TripletMarginWithDistanceLoss(reduction='mean') + loss = triplet_margin_with_distance_loss(input, positive, negative,) + print(loss) + # Tensor([0.19165580]) + + """ + + def __init__( + self, + distance_function=None, + margin=1.0, + swap=False, + reduction: str = 'mean', + name=None, + ): + super(TripletMarginWithDistanceLoss, self).__init__() + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in TripletMarginWithDistanceLoss " + "should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + self.margin = margin + self.swap = swap + self.reduction = reduction + self.distance_function = distance_function + self.name = name + + def forward(self, input, positive, negative): + return F.triplet_margin_with_distance_loss( + input, + positive, + negative, + margin=self.margin, + swap=self.swap, + reduction=self.reduction, + name=self.name, + ) + + +class TripletMarginLoss(Layer): + r""" + Creates a criterion that measures the triplet loss given an input + tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`. + This is used for measuring a relative similarity between samples. A triplet + is composed by `input`, `positive` and `negative` (i.e., `input`, `positive examples` and `negative + examples` respectively). The shapes of all input tensors should be + :math:`(N, *)`. + + The loss function for each sample in the mini-batch is: + + .. math:: + L(input, pos, neg) = \max \{d(input_i, pos_i) - d(input_i, neg_i) + {\rm margin}, 0\} + + + where + + .. math:: + d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p + + Parameters: + margin (float, Optional):Default: :math:`1`. + + p (int, Optional):The norm degree for pairwise distance. Default: :math:`2`. + + epsilon (float, Optional):Add small value to avoid division by zero, + default value is 1e-6. + + swap (bool, Optional):The distance swap change the negative distance to the distance between + positive sample and negative sample. For more details, see `Learning shallow convolutional feature descriptors with triplet losses`. + Default: ``False``. + + reduction (str, Optional):Indicate how to average the loss by batch_size. + the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default: ``'mean'`` + + name (str,Optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Call Parameters: + input (Tensor):Input tensor, the data type is float32 or float64. + the shape is [N, \*], N is batch size and `\*` means any number of additional dimensions, available dtype is float32, float64. + + positive (Tensor):Positive tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + negative (Tensor):Negative tensor, the data type is float32 or float64. + The shape of label is the same as the shape of input. + + Returns: + Tensor. The tensor variable storing the triplet_margin_loss of input and positive and negative. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1, 5, 3], [0, 3, 2], [1, 4, 1]], dtype=paddle.float32) + positive= paddle.to_tensor([[5, 1, 2], [3, 2, 1], [3, -1, 1]], dtype=paddle.float32) + negative = paddle.to_tensor([[2, 1, -3], [1, 1, -1], [4, -2, 1]], dtype=paddle.float32) + triplet_margin_loss = paddle.nn.TripletMarginLoss(reduction='none') + loss = triplet_margin_loss(input, positive, negative) + print(loss) + # Tensor([0. , 0.57496738, 0. ]) + + triplet_margin_loss = paddle.nn.TripletMarginLoss(margin=1.0, swap=True, reduction='mean', ) + loss = triplet_margin_loss(input, positive, negative,) + print(loss) + # Tensor([0.19165580]) + + """ + + def __init__( + self, + margin=1.0, + p=2.0, + epsilon=1e-6, + swap=False, + reduction='mean', + name=None, + ): + super(TripletMarginLoss, self).__init__() + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in TripletMarginLoss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + self.margin = margin + self.p = p + self.epsilon = epsilon + self.swap = swap + self.reduction = reduction + self.name = name + + def forward(self, input, positive, negative): + return F.triplet_margin_loss( + input, + positive, + negative, + margin=self.margin, + p=self.p, + epsilon=self.epsilon, + swap=self.swap, + reduction=self.reduction, + name=self.name, + ) + + +class SoftMarginLoss(Layer): + r""" + + Creates a criterion that measures a two-class soft margin loss between input predictions ``input`` + and target labels ``label`` . It can be described as: + + .. math:: + Out = log(1 + exp((-label * input))) + + Parameters: + + reduction (str, optional): Indicate how to average the loss by batch_size, + the candidates are ``'none'`` | ``'mean'`` | ``'sum'``. + If :attr:`reduction` is ``'none'``, the unreduced loss is returned; + If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; + If :attr:`reduction` is ``'sum'``, the summed loss is returned. + Default is ``'mean'``. + + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shapes: + - Input (Tensor): The input tensor with shape: ``[N, *]``, + N is batch_size, `*` means any number of additional dimensions. The ``input`` ranges from -inf to inf + Available dtype is float32, float64. + - Label (Tensor): The target labels tensor with the same shape as + ``input``. The target labels which values should be numbers -1 or 1. + Available dtype is int32, int64, float32, float64. + - Output (Tensor): If ``reduction`` is ``'none'``, the shape of output is + same as ``input`` , else the shape of output is [1]. + + Returns: + A callable object of SoftMarginLoss. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[0.5, 0.6, 0.7],[0.3, 0.5, 0.2]], 'float32') + label = paddle.to_tensor([[1.0, -1.0, 1.0],[-1.0, 1.0, 1.0]], 'float32') + soft_margin_loss = paddle.nn.SoftMarginLoss() + output = soft_margin_loss(input, label) + print(output) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.64022040]) + + input_np = paddle.uniform(shape=(5, 5), min=0.1, max=0.8, dtype="float64") + label_np = paddle.randint(high=2, shape=(5, 5), dtype="int64") + label_np[label_np==0]=-1 + input = paddle.to_tensor(input_np) + label = paddle.to_tensor(label_np) + soft_margin_loss = paddle.nn.SoftMarginLoss(reduction='none') + output = soft_margin_loss(input, label) + print(output) + # Tensor(shape=[5, 5], dtype=float64, place=Place(gpu:0), stop_gradient=True, + # [[0.61739663, 0.51405668, 1.09346100, 0.42385561, 0.91602303], + # [0.76997038, 1.01977148, 0.98971722, 1.13976032, 0.88152088], + # [0.55476735, 1.10505384, 0.89923519, 0.45018155, 1.06587511], + # [0.37998142, 0.48067240, 0.47791212, 0.55664053, 0.98581399], + # [0.78571653, 0.59319711, 0.39701841, 0.76172109, 0.83781742]]) + + """ + + def __init__(self, reduction='mean', name=None): + if reduction not in ['sum', 'mean', 'none']: + raise ValueError( + "The value of 'reduction' in SoftMarginLoss should be 'sum', 'mean' or 'none', but " + "received %s, which is not allowed." % reduction + ) + + super(SoftMarginLoss, self).__init__() + self.reduction = reduction + self.name = name + + def forward(self, input, label): + out = paddle.nn.functional.soft_margin_loss( + input, label, self.reduction, self.name + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/norm.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..d359f576dd6a9adf3166f14289e6d633bd647aa9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/norm.py @@ -0,0 +1,1415 @@ +# 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. + +# +# 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. + +# TODO: define normalization api + +import six + +from ...fluid.dygraph import BatchNorm # noqa: F401 +from ...fluid.dygraph import SpectralNorm # noqa: F401 + +from ...framework import get_default_dtype, set_default_dtype, _non_static_mode + +from ..initializer import Constant +from ...framework import ParamAttr +from ...fluid.data_feeder import check_variable_and_dtype, check_type +from ...fluid import dygraph_utils + +from ..functional import batch_norm, layer_norm, instance_norm + +import numpy as np +import numbers +import warnings +from ...framework import no_grad +from .. import functional as F +from paddle import _C_ops, _legacy_C_ops +from .. import Layer +from paddle import in_dynamic_mode +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph + +__all__ = [] + + +class _InstanceNormBase(Layer): + """ + This class is based class for InstanceNorm1D, 2d, 3d. + + See InstaceNorm1D, InstanceNorm2D or InstanceNorm3D for more details. + """ + + def __init__( + self, + num_features, + epsilon=1e-5, + momentum=0.9, + weight_attr=None, + bias_attr=None, + data_format="NCHW", + name=None, + ): + super(_InstanceNormBase, self).__init__() + + if weight_attr == False or bias_attr == False: + assert ( + weight_attr == bias_attr + ), "weight_attr and bias_attr must be set to Fasle at the same time in InstanceNorm" + self._epsilon = epsilon + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self._num_features = num_features + + if weight_attr != False and bias_attr != False: + self.scale = self.create_parameter( + attr=self._weight_attr, + shape=[num_features], + default_initializer=Constant(1.0), + is_bias=False, + ) + self.bias = self.create_parameter( + attr=self._bias_attr, + shape=[num_features], + default_initializer=Constant(0.0), + is_bias=True, + ) + else: + self.scale = None + self.bias = None + + def _check_input_dim(self, input): + raise NotImplementedError("InstanceNorm Base error") + + def forward(self, input): + self._check_input_dim(input) + + return instance_norm( + input, weight=self.scale, bias=self.bias, eps=self._epsilon + ) + + def extra_repr(self): + return 'num_features={}, epsilon={}'.format( + self._num_features, self._epsilon + ) + + +class InstanceNorm1D(_InstanceNormBase): + r""" + Create a callable object of `InstanceNorm1D`. Applies Instance Normalization over a 3D input (a mini-batch of 1D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization . + + DataLayout: NCL `[batch, in_channels, length]` + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\ + \ mean\ of\ one\ feature\ map\ in\ mini-batch \\ + \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \ + \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\ + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + +Where `H` means height of feature map, `W` means width of feature map. + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr. + If the Initializer of the weight_attr is not set, the parameter is initialized + one. If it is set to False, will not create weight_attr. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm. + If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + If it is set to False, will not create bias_attr. Default: None. + data_format(str, optional): Specify the input data format, may be "NC", "NCL". Default "NCL". + name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + + Shape: + - x: 2-D or 3-D tensor with shape: (batch, num_features) or (batch, num_features, length). + - output: 3-D tensor with same shape as input x. + + Returns: + None. + + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 3)) + instance_norm = paddle.nn.InstanceNorm1D(2) + instance_norm_out = instance_norm(x) + + print(instance_norm_out) + + """ + + def _check_input_dim(self, input): + if len(input.shape) != 2 and len(input.shape) != 3: + raise ValueError( + 'expected 2D or 3D input (got {}D input)'.format( + len(input.shape) + ) + ) + + +class InstanceNorm2D(_InstanceNormBase): + r""" + Create a callable object of `InstanceNorm2D`. Applies Instance Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization . + + DataLayout: NCHW `[batch, in_channels, in_height, in_width]` + + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\ + \ mean\ of\ one\ feature\ map\ in\ mini-batch \\ + \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \ + \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\ + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + +Where `H` means height of feature map, `W` means width of feature map. + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr. + If the Initializer of the weight_attr is not set, the parameter is initialized + one. If it is set to False, will not create weight_attr. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm. + If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + If it is set to False, will not create bias_attr. Default: None. + data_format(str, optional): Specify the input data format, could be "NCHW". Default: NCHW. + name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 4-D tensor with shape: (batch, num_features, height, weight). + - output: 4-D tensor with same shape as input x. + + Returns: + None. + + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 2, 3)) + instance_norm = paddle.nn.InstanceNorm2D(2) + instance_norm_out = instance_norm(x) + + print(instance_norm_out) + """ + + def _check_input_dim(self, input): + if len(input.shape) != 4: + raise ValueError( + 'expected 4D input (got {}D input)'.format(len(input.shape)) + ) + + +class InstanceNorm3D(_InstanceNormBase): + r""" + Create a callable object of `InstanceNorm3D`. Applies Instance Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization . + + DataLayout: NCHW `[batch, in_channels, D, in_height, in_width]` + + + :math:`input` is the input features over a mini-batch. + + .. math:: + + \mu_{\beta} &\gets \frac{1}{HW} \sum_{i=1}^{HW} x_i \qquad &//\ + \ mean\ of\ one\ feature\ map\ in\ mini-batch \\ + \sigma_{\beta}^{2} &\gets \frac{1}{HW} \sum_{i=1}^{HW}(x_i - \ + \mu_{\beta})^2 \qquad &//\ variance\ of\ one\ feature\ map\ in\ mini-batch \\ + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + +Where `H` means height of feature map, `W` means width of feature map. + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): A value added to the denominator for + numerical stability. Default is 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of instance_norm. If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as weight_attr, the name of scale can be set in ParamAttr. + If the Initializer of the weight_attr is not set, the parameter is initialized + one. If it is set to False, will not create weight_attr. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of instance_norm. + If it is set to None or one attribute of ParamAttr, instance_norm + will create ParamAttr as bias_attr, the name of bias can be set in ParamAttr. + If the Initializer of the bias_attr is not set, the bias is initialized zero. + If it is set to False, will not create bias_attr. Default: None. + data_format(str, optional): Specify the input data format, could be "NCDHW". Default: NCDHW. + name(str, optional): Name for the InstanceNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 5-D tensor with shape: (batch, num_features, dims, height, weight). + - output: 5-D tensor with same shape as input x. + + Returns: + None. + + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 2, 2, 3)) + instance_norm = paddle.nn.InstanceNorm3D(2) + instance_norm_out = instance_norm(x) + + print(instance_norm_out.numpy) + """ + + def _check_input_dim(self, input): + if len(input.shape) != 5: + raise ValueError( + 'expected 5D input (got {}D input)'.format(len(input.shape)) + ) + + +class GroupNorm(Layer): + """ + + This interface is used to construct a callable object of the ``GroupNorm`` class. + For more details, refer to code examples. + It implements the function of the Group Normalization Layer. + Refer to `Group Normalization `_ . + + Parameters: + num_groups(int): The number of groups that divided from channels. + num_channels(int): The number of channels of input. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable + scale :math:`g`. If it is set to False, no scale will be added to the output units. + If it is set to None, the bias is initialized one. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable + bias :math:`b`. If it is set to False, no bias will be added to the output units. + If it is set to None, the bias is initialized zero. Default: None. + data_format(str, optional): Specify the input data format. Only NCHW is supported. Default: NCHW. + name(str, optional): Name for the GroupNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: Tensor with shape: attr:`(batch, num_features, *)`. + - output: The same shape as input x. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(48, dtype="float32").reshape((2, 6, 2, 2)) + group_norm = paddle.nn.GroupNorm(num_channels=6, num_groups=6) + group_norm_out = group_norm(x) + + print(group_norm_out) + """ + + def __init__( + self, + num_groups, + num_channels, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCHW', + name=None, + ): + super(GroupNorm, self).__init__() + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self._epsilon = epsilon + self._num_channels = num_channels + self._num_groups = num_groups + if data_format != 'NCHW': + raise ValueError("unsupported data layout:" + data_format) + + param_shape = [self._num_channels] + + if weight_attr == False: + self.weight = self.create_parameter( + attr=None, shape=param_shape, default_initializer=Constant(1.0) + ) + self.weight.stop_gradient = True + else: + self.weight = self.create_parameter( + attr=self._weight_attr, + shape=param_shape, + default_initializer=Constant(1.0), + ) + self.weight.stop_gradient = ( + self._weight_attr != None + and self._weight_attr.learning_rate == 0.0 + ) + + if bias_attr == False: + self.bias = self.create_parameter( + attr=None, + shape=param_shape, + default_initializer=Constant(0.0), + is_bias=True, + ) + self.bias.stop_gradient = True + else: + self.bias = self.create_parameter( + attr=self._bias_attr, shape=param_shape, is_bias=True + ) + self.bias.stop_gradient = ( + self._bias_attr != None and self._bias_attr.learning_rate == 0.0 + ) + + def forward(self, input): + mean_out = self._helper.create_variable_for_type_inference( + dtype=input.dtype, stop_gradient=True + ) + variance_out = self._helper.create_variable_for_type_inference( + dtype=input.dtype, stop_gradient=True + ) + + if in_dygraph_mode(): + pre_act = _C_ops.group_norm( + input, + self.weight, + self.bias, + self._epsilon, + self._num_groups, + "NCHW", + ) + + return dygraph_utils._append_activation_in_dygraph( + pre_act, act=None + ) + + elif _in_legacy_dygraph(): + pre_act, _, _ = _legacy_C_ops.group_norm( + input, + self.weight, + self.bias, + mean_out, + variance_out, + 'epsilon', + self._epsilon, + 'groups', + self._num_groups, + ) + return dygraph_utils._append_activation_in_dygraph( + pre_act, act=None + ) + + inputs = {'X': input} + if self.bias is not None: + inputs['Bias'] = self.bias + if self.weight is not None: + inputs['Scale'] = self.weight + + # create output + group_norm_out = self._helper.create_variable_for_type_inference( + dtype=input.dtype + ) + + self._helper.append_op( + type="group_norm", + inputs=inputs, + outputs={ + "Y": group_norm_out, + "Mean": mean_out, + "Variance": variance_out, + }, + attrs={"epsilon": self._epsilon, "groups": self._num_groups}, + ) + + return self._helper.append_activation(group_norm_out, None) + + def extra_repr(self): + return 'num_groups={}, num_channels={}, epsilon={}'.format( + self._num_groups, self._num_channels, self._epsilon + ) + + +class LayerNorm(Layer): + r""" + Construct a callable object of the ``LayerNorm`` class. + For more details, refer to code examples. + It implements the function of the Layer Normalization Layer and can be applied to mini-batch input data. + Refer to `Layer Normalization `_ + + The formula is as follows: + + .. math:: + + \mu & = \frac{1}{H}\sum_{i=1}^{H} x_i + + \sigma & = \sqrt{\frac{1}{H}\sum_{i=1}^{H}{(x_i - \mu)^2} + \epsilon} + + y & = f(\frac{g}{\sigma}(x - \mu) + b) + + - :math:`x`: the vector representation of the summed inputs to the neurons in that layer. + - :math:`H`: the number of hidden units in a layers + - :math:`\epsilon`: the small value added to the variance to prevent division by zero. + - :math:`g`: the trainable scale parameter. + - :math:`b`: the trainable bias parameter. + + Parameters: + normalized_shape(int|list|tuple): Input shape from an expected input of + size :math:`[*, normalized_shape[0], normalized_shape[1], ..., normalized_shape[-1]]`. + If it is a single integer, this module will normalize over the last dimension + which is expected to be of that specific size. + epsilon(float, optional): The small value added to the variance to prevent + division by zero. Default: 1e-05. + weight_attr(ParamAttr|bool, optional): The parameter attribute for the learnable + gain :math:`g`. If False, weight is None. If is None, a default :code:`ParamAttr` would be added as scale. The + :attr:`param_attr` is initialized as 1 if it is added. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the learnable + bias :math:`b`. If is False, bias is None. If is None, a default :code:`ParamAttr` would be added as bias. The + :attr:`bias_attr` is initialized as 0 if it is added. Default: None. + name(str, optional): Name for the LayerNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 2-D, 3-D, 4-D or 5-D tensor. + - output: same shape as input x. + + Returns: + None + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand((2, 2, 2, 3)) + layer_norm = paddle.nn.LayerNorm(x.shape[1:]) + layer_norm_out = layer_norm(x) + + print(layer_norm_out) + """ + + def __init__( + self, + normalized_shape, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + name=None, + ): + super(LayerNorm, self).__init__() + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = [normalized_shape] + + self._normalized_shape = list(normalized_shape) + self._epsilon = epsilon + self._weight_attr = weight_attr + self._bias_attr = bias_attr + param_shape = [np.prod(self._normalized_shape)] + + if weight_attr is False: + self.weight = None + else: + self.weight = self.create_parameter( + attr=self._weight_attr, + shape=param_shape, + default_initializer=Constant(1.0), + ) + + if bias_attr is False: + self.bias = None + else: + self.bias = self.create_parameter( + attr=self._bias_attr, shape=param_shape, is_bias=True + ) + + def forward(self, input): + return layer_norm( + input, + normalized_shape=self._normalized_shape, + weight=self.weight, + bias=self.bias, + epsilon=self._epsilon, + ) + + def extra_repr(self): + return 'normalized_shape={}, epsilon={}'.format( + self._normalized_shape, self._epsilon + ) + + +class _BatchNormBase(Layer): + """ + BatchNorm base . + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCHW', + use_global_stats=None, + name=None, + ): + super(_BatchNormBase, self).__init__() + self._num_features = num_features + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self._use_global_stats = use_global_stats + + if get_default_dtype() == 'float16': + self._dtype = 'float32' + else: + self._dtype = get_default_dtype() + + param_shape = [num_features] + + # create parameter + if weight_attr == False: + self.weight = self.create_parameter( + attr=None, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(1.0), + ) + self.weight.stop_gradient = True + else: + self.weight = self.create_parameter( + attr=self._weight_attr, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(1.0), + ) + self.weight.stop_gradient = ( + self._weight_attr != None + and self._weight_attr.learning_rate == 0.0 + ) + + if bias_attr == False: + self.bias = self.create_parameter( + attr=None, + shape=param_shape, + dtype=self._dtype, + default_initializer=Constant(0.0), + is_bias=True, + ) + self.bias.stop_gradient = True + else: + self.bias = self.create_parameter( + attr=self._bias_attr, + shape=param_shape, + dtype=self._dtype, + is_bias=True, + ) + self.bias.stop_gradient = ( + self._bias_attr != None and self._bias_attr.learning_rate == 0.0 + ) + + moving_mean_name = None + moving_variance_name = None + + if name is not None: + moving_mean_name = name + "_mean" + moving_variance_name = name + "_variance" + + self._mean = self.create_parameter( + dtype=self._dtype, + attr=ParamAttr( + name=moving_mean_name, + initializer=Constant(0.0), + trainable=False, + do_model_average=True, + ), + shape=param_shape, + ) + self._mean.stop_gradient = True + + self._variance = self.create_parameter( + dtype=self._dtype, + attr=ParamAttr( + name=moving_variance_name, + initializer=Constant(1.0), + trainable=False, + do_model_average=True, + ), + shape=param_shape, + ) + self._variance.stop_gradient = True + + self._data_format = data_format + self._in_place = False + self._momentum = momentum + self._epsilon = epsilon + self._fuse_with_relu = False + self._name = name + + def _check_input_dim(self, input): + raise NotImplementedError("BatchNorm Base error") + + def _check_data_format(self, input): + raise NotImplementedError("BatchNorm Base data format error") + + def forward(self, input): + + self._check_data_format(self._data_format) + + self._check_input_dim(input) + + if self.training: + warnings.warn( + "When training, we now always track global mean and variance." + ) + + return batch_norm( + input, + self._mean, + self._variance, + weight=self.weight, + bias=self.bias, + training=self.training, + momentum=self._momentum, + epsilon=self._epsilon, + data_format=self._data_format, + use_global_stats=self._use_global_stats, + ) + + def extra_repr(self): + main_str = 'num_features={}, momentum={}, epsilon={}'.format( + self._num_features, self._momentum, self._epsilon + ) + if self._data_format != 'NCHW': + main_str += ', data_format={}'.format(self._data_format) + if self._name is not None: + main_str += ', name={}'.format(self._name) + return main_str + + +class BatchNorm1D(_BatchNormBase): + r""" + Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . + + When use_global_stats = False, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + When use_global_stats = True, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch. + They are global or running statistics (moving_mean and moving_variance). It usually got from the + pre-trained model. Calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The normalization function formula is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable proportional parameter + - :math:`\beta` : trainable deviation parameter + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. + data_format(str, optional): Specify the input data format, may be "NC", "NCL" or "NLC". Default "NCL". + use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None. + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 2-D or 3-D tensor with shape: (batch, num_features) or (batch, num_features, length) when data_format is "NC" or "NCL", + (batch, length, num_features) when data_format is "NLC". + - output: 3-D tensor with same shape as input x. + + Returns: + None. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand((2, 1, 3)) + batch_norm = paddle.nn.BatchNorm1D(1) + batch_norm_out = batch_norm(x) + + print(batch_norm_out) + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCL', + use_global_stats=None, + name=None, + ): + super(BatchNorm1D, self).__init__( + num_features, + momentum, + epsilon, + weight_attr, + bias_attr, + data_format, + use_global_stats, + name, + ) + + def _check_data_format(self, input): + if input == 'NCHW' or input == 'NC' or input == 'NCL': + self._data_format = 'NCHW' + elif input == "NHWC" or input == 'NLC': + self._data_format = "NHWC" + else: + raise ValueError( + 'expected NC , NCL, NLC or None for data_format input' + ) + + def _check_input_dim(self, input): + if len(input.shape) != 2 and len(input.shape) != 3: + raise ValueError( + 'expected 2D or 3D input (got {}D input)'.format( + len(input.shape) + ) + ) + + +class BatchNorm2D(_BatchNormBase): + r""" + Applies Batch Normalization over a 4D input (a mini-batch of 2D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . + + When use_global_stats = False, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &// + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + When use_global_stats = True, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch. + They are global or running statistics (moving_mean and moving_variance). It usually got from the + pre-trained model. Calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The normalization function formula is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable proportional parameter + - :math:`\beta` : trainable deviation parameter + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. + data_format(str, optional): Specify the input data format, the data format can be "NCHW" or "NHWC". Default: NCHW. + use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None. + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 4-D tensor with shape: (batch, num_features, height, weight) when data_format is "NCHW", + or (batch, height, weight, num_features) when data_format is "NHWC". + - output: 4-D tensor with same shape as input x. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand((2, 1, 2, 3)) + batch_norm = paddle.nn.BatchNorm2D(1) + batch_norm_out = batch_norm(x) + + print(batch_norm_out) + """ + + def _check_data_format(self, input): + if input == 'NCHW': + self._data_format = input + elif input == "NHWC": + self._data_format = input + else: + raise ValueError('expected NCHW or NHWC for data_format input') + + def _check_input_dim(self, input): + if len(input.shape) != 4: + raise ValueError( + 'expected 4D input (got {}D input)'.format(len(input.shape)) + ) + + +class BatchNorm3D(_BatchNormBase): + r""" + Applies Batch Normalization over a 5D input (a mini-batch of 3D inputswith additional channel dimension) as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . + + When use_global_stats = False, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + When use_global_stats = True, the :math:`\\mu_{\\beta}` + and :math:`\\sigma_{\\beta}^{2}` are not the statistics of one mini-batch. + They are global or running statistics (moving_mean and moving_variance). It usually got from the + pre-trained model. Calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The normalization function formula is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable proportional parameter + - :math:`\beta` : trainable deviation parameter + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the weight_attr is not set, the parameter is initialized with ones. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. + data_format(str, optional): Specify the input data format, the data format can be "NCDHW" or "NDHWC. Default: NCDHW. + use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None. + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: 5-D tensor with shape: (batch, num_features, dims, height, weight) when data_format is "NCDHW", + or (batch, dims, height, weight, num_features) when data_format is "NDHWC". + - output: 5-D tensor with same shape as input x. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand((2, 1, 2, 2, 3)) + batch_norm = paddle.nn.BatchNorm3D(1) + batch_norm_out = batch_norm(x) + + print(batch_norm_out) + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCDHW', + use_global_stats=None, + name=None, + ): + super(BatchNorm3D, self).__init__( + num_features, + momentum, + epsilon, + weight_attr, + bias_attr, + data_format, + use_global_stats, + name, + ) + + def _check_data_format(self, input): + if input == 'NCHW' or input == 'NCDHW': + self._data_format = 'NCHW' + elif input == "NHWC" or input == "NDHWC": + self._data_format = 'NHWC' + else: + raise ValueError( + 'expected NCDHW, NDHWC or None for data_format input' + ) + + def _check_input_dim(self, input): + if len(input.shape) != 5: + raise ValueError( + 'expected 5D input (got {}D input)'.format(len(input.shape)) + ) + + +class SyncBatchNorm(_BatchNormBase): + r""" + + This interface is used to construct a callable object of the ``SyncBatchNorm`` class. + It implements the function of the Cross-GPU Synchronized Batch Normalization Layer, and can + be used as a normalizer function for other operations, such as conv2d and fully connected + operations. + The data is normalized by the mean and variance of the channel based on whole mini-batch + , which including data in all gpus. + Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing + Internal Covariate Shift `_ + for more details. + + When model in training mode, the :math:`\\mu_{\\beta}` + and :math:`\\sigma_{\\beta}^{2}` are the statistics of whole mini-batch data in all gpus. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + - :math:`x` : whole mini-batch data in all gpus + - :math:`m` : the size of the whole mini-batch data + + When model in evaluation mode, the :math:`\\mu_{\\beta}` + and :math:`\sigma_{\beta}^{2}` are global statistics (moving_mean and moving_variance, + which usually got from the pre-trained model). Global statistics calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The formula of normalization is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable scale parameter vector + - :math:`\beta` : trainable shift parameter vector + + Note: + If you want to use container to pack your model and has :ref:`api_paddle_nn_SyncBatchNorm` in the + evaluation phase, please use :ref:`api_paddle_nn_LayerList` or :ref:`api_paddle_nn_Sequential` instead of + :ref:`api_paddle_hub_list` to pack the model. + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of this layer. If it is set to None or one attribute of ParamAttr, this layerr + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with ones. If it is set to False, + this layer will not have trainable scale parameter. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of this layer. + If it is set to None or one attribute of ParamAttr, this layer + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. If it is set to False, this layer will not + have trainable bias parameter. Default: None. + + Shapes: + - input: Tensor that the dimension from 2 to 5. + - output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + # required: gpu + + import paddle + import paddle.nn as nn + + x = paddle.to_tensor([[[[0.3, 0.4], [0.3, 0.07]], [[0.83, 0.37], [0.18, 0.93]]]]).astype('float32') + + if paddle.is_compiled_with_cuda(): + sync_batch_norm = nn.SyncBatchNorm(2) + hidden1 = sync_batch_norm(x) + print(hidden1) + # Tensor(shape=[1, 2, 2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [[[[ 0.26824948, 1.09363246], + # [ 0.26824948, -1.63013160]], + + # [[ 0.80956620, -0.66528702], + # [-1.27446556, 1.13018656]]]]) + + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCHW', + name=None, + ): + super(SyncBatchNorm, self).__init__( + num_features, + momentum, + epsilon, + weight_attr, + bias_attr, + data_format, + None, + name, + ) + + def _check_data_format(self): + if self._data_format in ['NCHW', 'NCDHW', 'NC', 'NCL']: + self._data_format = 'NCHW' + elif self._data_format in ["NHWC", "NDHWC", 'NLC']: + self._data_format = 'NHWC' + else: + raise ValueError( + 'expected \'NCDHW\', \'NDHWC\', \'NCL\', \'NLC\', \'NC\', \'NCHW\', \'NHWC\' for data_format' + ) + + def forward(self, x): + self._check_data_format() + # create output + # mean and mean_out share the same memory + mean_out = self._mean + # variance and variance out share the same memory + variance_out = self._variance + + ### train mode: use mini-batch stats, eval mode: use global stats + ### use_global_stats only support False in sync_batch_norm + if in_dygraph_mode(): + sync_batch_norm_out, _, _, _, _, _ = _C_ops.sync_batch_norm_( + x, + self.weight, + self.bias, + self._mean, + self._variance, + self._momentum, + self._epsilon, + self._data_format, + not self.training, + False, + False, + False, + ) + return sync_batch_norm_out + + elif in_dynamic_mode(): + attrs = ( + "momentum", + self._momentum, + "epsilon", + self._epsilon, + "is_test", + not self.training, + "data_layout", + self._data_format, + "use_mkldnn", + False, + "fuse_with_relu", + False, + "use_global_stats", + False, + 'trainable_statistics', + False, + ) + sync_batch_norm_out, _, _, _, _, _ = _legacy_C_ops.sync_batch_norm( + x, + self.weight, + self.bias, + self._mean, + self._variance, + mean_out, + variance_out, + *attrs + ) + return sync_batch_norm_out + + check_variable_and_dtype( + x, 'input', ['float16', 'float32', 'float64'], 'SyncBatchNorm' + ) + + attrs = { + "momentum": self._momentum, + "epsilon": self._epsilon, + "is_test": not self.training, + "data_layout": self._data_format, + "use_mkldnn": False, + "fuse_with_relu": False, + "use_global_stats": False, + "trainable_statistics": False, + } + + inputs = { + "X": [x], + "Scale": [self.weight], + "Bias": [self.bias], + "Mean": [self._mean], + "Variance": [self._variance], + } + + saved_mean = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True + ) + saved_variance = self._helper.create_variable_for_type_inference( + dtype=self._dtype, stop_gradient=True + ) + sync_batch_norm_out = self._helper.create_variable_for_type_inference( + self._dtype + ) + + outputs = { + "Y": [sync_batch_norm_out], + "MeanOut": [mean_out], + "VarianceOut": [variance_out], + "SavedMean": [saved_mean], + "SavedVariance": [saved_variance], + } + + self._helper.append_op( + type="sync_batch_norm", inputs=inputs, outputs=outputs, attrs=attrs + ) + return sync_batch_norm_out + + @classmethod + def convert_sync_batchnorm(cls, layer): + """ + Helper function to convert :class: `paddle.nn.BatchNorm*d` layers in the model to :class: `paddle.nn.SyncBatchNorm` layers. + + Parameters: + layer(paddle.nn.Layer): model containing one or more `BatchNorm*d` layers. + + Returns: + The original model with converted SyncBatchNorm layers. If BatchNorm*d layer in the model, use SyncBatchNorm layer instead. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + model = nn.Sequential(nn.Conv2D(3, 5, 3), nn.BatchNorm2D(5)) + sync_model = nn.SyncBatchNorm.convert_sync_batchnorm(model) + + """ + layer_output = layer + if isinstance(layer, _BatchNormBase): + if ( + layer._weight_attr != None + and not isinstance(layer._weight_attr, bool) + and layer._weight_attr.name != None + ): + layer._weight_attr.name = layer._weight_attr.name + '_sync' + if ( + layer._bias_attr != None + and not isinstance(layer._bias_attr, bool) + and layer._bias_attr.name != None + ): + layer._bias_attr.name = layer._bias_attr.name + '_sync' + + layer_output = SyncBatchNorm( + layer._num_features, + layer._momentum, + layer._epsilon, + layer._weight_attr, + layer._bias_attr, + layer._data_format, + layer._name, + ) + + if layer._weight_attr != False and layer._bias_attr != False: + with no_grad(): + layer_output.weight = layer.weight + layer_output.bias = layer.bias + layer_output._mean = layer._mean + layer_output._variance = layer._variance + + for name, sublayer in layer.named_children(): + layer_output.add_sublayer( + name, cls.convert_sync_batchnorm(sublayer) + ) + del layer + return layer_output + + +class LocalResponseNorm(Layer): + """ + Local Response Normalization performs a type of "lateral inhibition" by normalizing over local input regions. + For more information, please refer to `ImageNet Classification with Deep Convolutional Neural Networks `_ + + See more details in :ref:`api_paddle_nn_functional_local_response_norm` . + + Parameters: + size (int): The number of channels to sum over. + alpha (float, optional): The scaling parameter, positive. Default:1e-4 + beta (float, optional): The exponent, positive. Default:0.75 + k (float, optional): An offset, positive. Default: 1.0 + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: + If input is 3-D Tensor, the string could be `"NCL"` or `"NLC"` . When it is `"NCL"`, + the data is stored in the order of: `[batch_size, input_channels, feature_length]`. + If input is 4-D Tensor, the string could be `"NCHW"`, `"NHWC"`. When it is `"NCHW"`, + the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. + If input is 5-D Tensor, the string could be `"NCDHW"`, `"NDHWC"` . When it is `"NCDHW"`, + the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. + name (str, optional): Name for the operation (optional, default is None). For more information, + please refer to :ref:`api_guide_Name`. + + Shape: + - input: 3-D/4-D/5-D tensor. + - output: 3-D/4-D/5-D tensor, the same shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand(shape=(3, 3, 112, 112), dtype="float32") + m = paddle.nn.LocalResponseNorm(size=5) + y = m(x) + print(y.shape) # [3, 3, 112, 112] + """ + + def __init__( + self, + size, + alpha=0.0001, + beta=0.75, + k=1.0, + data_format="NCHW", + name=None, + ): + super(LocalResponseNorm, self).__init__() + self.size = size + self.alpha = alpha + self.beta = beta + self.k = k + self.data_format = data_format + self.name = name + + def forward(self, input): + out = F.local_response_norm( + input, + self.size, + self.alpha, + self.beta, + self.k, + self.data_format, + self.name, + ) + return out + + def extra_repr(self): + main_str = 'size={}, alpha={}, beta={}, k={}'.format( + self.size, self.alpha, self.beta, self.k + ) + if self.data_format != 'NCHW': + main_str += ', data_format={}'.format(self.data_format) + if self.name is not None: + main_str += ', name={}'.format(self.name) + return main_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/pooling.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..75580342b392c2c7e64800af02b325480fcace6b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/pooling.py @@ -0,0 +1,1381 @@ +# 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. + +from ...fluid.layer_helper import LayerHelper +from .. import functional as F +from .. import Layer + +__all__ = [] + + +class AvgPool1D(Layer): + r""" + This operation applies a 1D average pooling over an input signal composed + of several input planes, based on the input, output_size, return_mask parameters. + Input(X) and output(Out) are in NCL format, where N is batch + size, C is the number of channels, L is the length of the feature. + The output tensor shape will be [N, C, output_size]. + + The output value of the layer with input size (N, C, L), + output (N, C, :math:`L_{out}`) and kernel_size ksize can be precisely described as + For average pool1d: + + .. math:: + + Output(N_i, C_i, l) = \frac{Input[N_i, C_i, stride \times l:stride \times l+k]}{ksize} + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain an integer. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain an integer. Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. + 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + exclusive(bool, optional): Whether to exclude padding points in average pooling mode, default is `True`. + ceil_mode(bool, optional): ${ceil_mode_comment}Whether to use the ceil function to calculate output height + and width. If it is set to False, the floor function will be used. The default value is False. + name(str, optional): For eed to detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no nset and None by default. + + Shape: + - x(Tensor): The input tensor of avg pool1d operator, which is a 3-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of avg pool1d operator, which is a 3-D tensor. + The data type is same as input x. + + Returns: + A callable object of AvgPool1D. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1) + AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0) + pool_out = AvgPool1D(data) + # pool_out shape: [1, 3, 16] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + exclusive=True, + ceil_mode=False, + name=None, + ): + super(AvgPool1D, self).__init__() + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.ceil_mode = ceil_mode + self.exclusive = exclusive + self.name = name + + def forward(self, x): + out = F.avg_pool1d( + x, + self.kernel_size, + self.stride, + self.padding, + self.exclusive, + self.ceil_mode, + self.name, + ) + return out + + def extra_repr(self): + return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class AvgPool2D(Layer): + r""" + This operation applies 2D average pooling over input features based on the input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NCHW format, where N is batch size, C is the number of channels, + H is the height of the feature, and W is the width of the feature. + + Example: + Input: + X shape: :math:`(N, C, :math:`H_{in}`, :math:`W_{in}`)` + Attr: + kernel_size: ksize + + Output: + Out shape: :math:`(N, C, :math:`H_{out}`, :math:`W_{out}`)` + + .. math:: + + Output(N_i, C_j, h, w) = \frac{\sum_{m=0}^{ksize[0]-1} \sum_{n=0}^{ksize[1]-1} + Input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)}{ksize[0] * ksize[1]} + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (pool_size_Height, pool_size_Width). + Otherwise, the pool kernel size will be a square of an int. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain two integers, (pool_stride_Height, pool_stride_Width). + Otherwise, the pool stride size will be a square of an int. + Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode(bool, optional): When True, will use `ceil` instead of `floor` to compute the output shape. + exclusive(bool, optional): Whether to exclude padding points in average pooling + mode, default is `true`. + divisor_override(float, optional): If specified, it will be used as divisor, otherwise kernel_size will be + used. Default None. + data_format(str, optional): The data format of the input and output data. An optional string from: `"NCHW"`, + `"NDHW"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + Shape: + - x(Tensor): The input tensor of avg pool2d operator, which is a 4-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of avg pool2d operator, which is a 4-D tensor. + The data type is same as input x. + + Returns: + A callable object of AvgPool2D. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + # max pool2d + input = paddle.uniform([1, 3, 32, 32], dtype="float32", min=-1, max=1) + AvgPool2D = nn.AvgPool2D(kernel_size=2, + stride=2, padding=0) + output = AvgPool2D(input) + # output.shape [1, 3, 16, 16] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + ceil_mode=False, + exclusive=True, + divisor_override=None, + data_format="NCHW", + name=None, + ): + super(AvgPool2D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.ceil_mode = ceil_mode + self.exclusive = exclusive + self.divisor = divisor_override + self.data_format = data_format + self.name = name + + def forward(self, x): + return F.avg_pool2d( + x, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + ceil_mode=self.ceil_mode, + exclusive=self.exclusive, + divisor_override=self.divisor, + data_format=self.data_format, + name=self.name, + ) + + def extra_repr(self): + return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class AvgPool3D(Layer): + """ + + This operation applies 3D max pooling over input features based on the input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NCDHW format, where N is batch size, C is the number of channels, + H is the height of the feature, D is the depth of the feature, and W is the width of the feature. + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If pool kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode(bool, optional): ${ceil_mode_comment} + exclusive(bool, optional): Whether to exclude padding points in average pooling mode, default is True. + divisor_override(int|float, optional): if specified, it will be used as divisor, otherwise kernel_size will + be used. Default None. + data_format(str, optional): The data format of the input and output data. An optional string from: `"NCDHW"`, + `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A callable object of AvgPool3D. + + Shape: + - x(Tensor): The input tensor of avg pool3d operator, which is a 5-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of avg pool3d operator, which is a 5-D tensor. + The data type is same as input x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + # avg pool3d + input = paddle.uniform([1, 2, 3, 32, 32], dtype="float32", min=-1, max=1) + AvgPool3D = nn.AvgPool3D(kernel_size=2, + stride=2, padding=0) + output = AvgPool3D(input) + # output.shape [1, 2, 3, 16, 16] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + ceil_mode=False, + exclusive=True, + divisor_override=None, + data_format="NCDHW", + name=None, + ): + super(AvgPool3D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.ceil_mode = ceil_mode + self.exclusive = exclusive + self.divisor = divisor_override + self.data_format = data_format + self.name = name + + def forward(self, x): + return F.avg_pool3d( + x, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + ceil_mode=self.ceil_mode, + exclusive=self.exclusive, + divisor_override=self.divisor, + data_format=self.data_format, + name=self.name, + ) + + def extra_repr(self): + return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class MaxPool1D(Layer): + """ + This operation applies 1D max pooling over input signal + composed of several input planes based on the input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NCL format, where N is batch size, C is the number of channels, + L is the length of the feature. + + The output value of the layer with input size (N, C, L), + output (N, C, L_{out}) and kernel_size k can be precisely described as + For average pool1d: + + .. math:: + + Output(N_i, C_i, l) = max(Input[N_i, C_i, stride \times l:stride \times l+k]) + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain an integer. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain an integer. Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An integer, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. + 4. A list[int] or tuple(int) whose length is 2, It has the form [pad_before, pad_after]. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or(0,0). + The default value is 0. + return_mask(bool, optional): Whether return the max indices along with the outputs. default is `False`. + ceil_mode(bool, optional): Whether to use the ceil function to calculate output height and width. + False is the default. If it is set to False, the floor function will be used. Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + Returns: + A callable object of MaxPool1D. + + Shape: + - x(Tensor): The input tensor of max pool1d operator, which is a 3-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of max pool1d operator, which is a 3-D tensor. + The data type is same as input x. + + Examples: + + .. code-block:: python + + import paddle + import paddle.nn as nn + + data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1) + MaxPool1D = nn.MaxPool1D(kernel_size=2, stride=2, padding=0) + pool_out = MaxPool1D(data) + # pool_out shape: [1, 3, 16] + + MaxPool1D = nn.MaxPool1D(kernel_size=2, stride=2, padding=0, return_mask=True) + pool_out, indices = MaxPool1D(data) + # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + name=None, + ): + super(MaxPool1D, self).__init__() + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.ceil_mode = ceil_mode + self.return_mask = return_mask + self.name = name + + def forward(self, input): + out = F.max_pool1d( + input, + self.kernel_size, + self.stride, + self.padding, + self.return_mask, + self.ceil_mode, + self.name, + ) + return out + + def extra_repr(self): + return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class MaxPool2D(Layer): + r""" + This operation applies 2D max pooling over input feature based on the input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NCHW format, where N is batch size, C is the number of channels, + H is the height of the feature, and W is the width of the feature. + + Example: + - Input: + X shape: :math:`(N, C, H_{in}, W_{in})` + - Attr: + kernel_size: ksize + + - Output: + Out shape: :math:`(N, C, H_{out}, W_{out})` + + .. math:: + + Output(N_i, C_j, h, w) = \max_{m=0, \ldots, ksize[0] -1} \max_{n=0, \ldots, ksize[1]-1} + Input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n) + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two integers, (pool_size_Height, pool_size_Width). + Otherwise, the pool kernel size will be a square of an int. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain two integers, (pool_stride_Height, pool_stride_Width). + Otherwise, the pool stride size will be a square of an int. + Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is \4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode(bool, optional): when True, will use `ceil` instead of `floor` to compute the output shape + return_mask(bool, optional): Whether to return the max indices along with the outputs. + data_format(str, optional): The data format of the input and output data. An optional string from: `"NCHW"`, `"NDHW"`. + The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_height, input_width]`. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + Returns: + A callable object of MaxPool2D. + + Shape: + - x(Tensor): The input tensor of max pool2d operator, which is a 4-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of max pool2d operator, which is a 4-D tensor. + The data type is same as input x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + # max pool2d + input = paddle.uniform([1, 3, 32, 32], dtype="float32", min=-1, max=1) + MaxPool2D = nn.MaxPool2D(kernel_size=2, + stride=2, padding=0) + output = MaxPool2D(input) + # output.shape [1, 3, 16, 16] + + # for return_mask=True + MaxPool2D = nn.MaxPool2D(kernel_size=2, stride=2, padding=0, return_mask=True) + output, max_indices = MaxPool2D(input) + # output.shape [1, 3, 16, 16], max_indices.shape [1, 3, 16, 16], + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + data_format="NCHW", + name=None, + ): + super(MaxPool2D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.return_mask = return_mask + self.ceil_mode = ceil_mode + self.data_format = data_format + self.name = name + + def forward(self, x): + return F.max_pool2d( + x, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + return_mask=self.return_mask, + ceil_mode=self.ceil_mode, + data_format=self.data_format, + name=self.name, + ) + + def extra_repr(self): + return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class MaxPool3D(Layer): + """ + This operation applies 3D max pooling over input features based on the input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NCDHW format, where N is batch size, C is the number of channels, + H is the height of the feature, D is the depth of the feature, and W is the width of the feature. + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If the kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is \6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode(bool, optional): ${ceil_mode_comment} + return_mask(bool, optional): Whether to return the max indices along with the outputs. + data_format(str, optional): The data format of the input and output data. An optional string from: `"NCDHW"`, + `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + + Returns: + A callable object of MaxPool3D. + + Shape: + - x(Tensor): The input tensor of max pool3d operator, which is a 5-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of max pool3d operator, which is a 5-D tensor. + The data type is same as input x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + # max pool3d + input = paddle.uniform([1, 2, 3, 32, 32], dtype="float32", min=-1, max=1) + MaxPool3D = nn.MaxPool3D(kernel_size=2, + stride=2, padding=0) + output = MaxPool3D(input) + # output.shape [1, 2, 3, 16, 16] + + # for return_mask=True + MaxPool3D = nn.MaxPool3D(kernel_size=2, stride=2, padding=0, return_mask=True) + output, max_indices = MaxPool3D(input) + # output.shape [1, 2, 3, 16, 16], max_indices.shape [1, 2, 3, 16, 16], + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + data_format="NCDHW", + name=None, + ): + super(MaxPool3D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.return_mask = return_mask + self.ceil_mode = ceil_mode + self.data_format = data_format + self.name = name + + def forward(self, x): + return F.max_pool3d( + x, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + return_mask=self.return_mask, + ceil_mode=self.ceil_mode, + data_format=self.data_format, + name=self.name, + ) + + def extra_repr(self): + return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) + + +class AdaptiveAvgPool1D(Layer): + r""" + + A 1D adaptive average pooling over an input signal composed + of several input planes, based on :attr:`output_size`. + Input and output are in NCL format, where N is batch + size, C is the number of channels and L is the length of the feature. + The shape of output will be :math:`[N, C, output\_size]`. + + The formulation for average adaptive pool1d is + + .. math:: + + lstart &= \lfloor i * L_{in} / L_{out}\rfloor, + + lend &= \lceil(i + 1) * L_{in} / L_{out}\rceil, + + Output(i) &= \frac{\sum Input[lstart:lend]}{lend - lstart}. + + Parameters: + output_size(int): The target output size. Its data type must be int. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A callable object for computing 1D adaptive average pooling. + + Examples: + .. code-block:: python + + # average adaptive pool1d + # suppose input data in shape of [N, C, L], `output_size` is m or [m], + # output shape is [N, C, m], adaptive pool divide L dimension + # of input data into m grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # lstart = floor(i * L / m) + # lend = ceil((i + 1) * L / m) + # output[:, :, i] = sum(input[:, :, lstart: lend])/(lend - lstart) + # + import paddle + import paddle.nn as nn + + data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1) + AdaptiveAvgPool1D = nn.AdaptiveAvgPool1D(output_size=16) + pool_out = AdaptiveAvgPool1D(data) + # pool_out shape: [1, 3, 16] + """ + + def __init__(self, output_size, name=None): + super(AdaptiveAvgPool1D, self).__init__() + self.output_size = output_size + self.name = name + + def forward(self, input): + return F.adaptive_avg_pool1d(input, self.output_size, self.name) + + def extra_repr(self): + return 'output_size={}'.format(self.output_size) + + +class AdaptiveAvgPool2D(Layer): + r""" + + This operation applies 2D adaptive avg pooling on input tensor. The h and w dimensions + of the output tensor are determined by the parameter output_size. + + For avg adaptive pool2d: + + .. math:: + + hstart &= floor(i * H_{in} / H_{out}) + + hend &= ceil((i + 1) * H_{in} / H_{out}) + + wstart &= floor(j * W_{in} / W_{out}) + + wend &= ceil((j + 1) * W_{in} / W_{out}) + + Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)} + + + Parameters: + output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain two element, (H, W). H and W can be either a int, or None which means + the size will be the same as that of the input. + data_format(str, optional): The data format of the input and output data. An optional string + from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in + the order of: [batch_size, input_channels, input_height, input_width]. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + Shape: + - x(Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of adaptive avg pool2d operator, which is a 4-D tensor. + The data type is same as input x. + + Returns: + A callable object of AdaptiveAvgPool2D. + + Examples: + .. code-block:: python + + # adaptive avg pool2d + # suppose input data in shape of [N, C, H, W], `output_size` is [m, n], + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive avg pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + + x = paddle.rand([2, 3, 32, 32]) + + adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=3) + pool_out = adaptive_avg_pool(x = x) + # pool_out.shape is [2, 3, 3, 3] + """ + + def __init__(self, output_size, data_format="NCHW", name=None): + super(AdaptiveAvgPool2D, self).__init__() + self._output_size = output_size + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.adaptive_avg_pool2d( + x, + output_size=self._output_size, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + return 'output_size={}'.format(self._output_size) + + +class AdaptiveAvgPool3D(Layer): + r""" + + This operation applies 3D adaptive avg pooling on input tensor. The h and w dimensions + of the output tensor are determined by the parameter output_size. + + For avg adaptive pool3d: + + .. math:: + + dstart &= floor(i * D_{in} / D_{out}) + + dend &= ceil((i + 1) * D_{in} / D_{out}) + + hstart &= floor(j * H_{in} / H_{out}) + + hend &= ceil((j + 1) * H_{in} / H_{out}) + + wstart &= floor(k * W_{in} / W_{out}) + + wend &= ceil((k + 1) * W_{in} / W_{out}) + + Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]} + {(dend - dstart) * (hend - hstart) * (wend - wstart)} + + + Parameters: + output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means + the size will be the same as that of the input. + data_format(str, optional): The data format of the input and output data. An optional string + from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in + the order of: [batch_size, input_channels, input_depth, input_height, input_width]. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + Shape: + - x(Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor. + The data type can be float32, float64\. + - output(Tensor): The output tensor of adaptive avg pool3d operator, which is a 5-D tensor. + The data type is same as input x. + + Returns: + A callable object of AdaptiveAvgPool3D. + + Examples: + .. code-block:: python + + # adaptive avg pool3d + # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n], + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into l * m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive avg pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(j * H / m) + # hend = ceil((j + 1) * H / m) + # wstart = floor(k * W / n) + # wend = ceil((k + 1) * W / n) + # output[:, :, i, j, k] = + # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) + import paddle + + x = paddle.rand([2, 3, 8, 32, 32]) + + adaptive_avg_pool = paddle.nn.AdaptiveAvgPool3D(output_size=3) + pool_out = adaptive_avg_pool(x = x) + # pool_out = [2, 3, 3, 3, 3] + """ + + def __init__(self, output_size, data_format="NCDHW", name=None): + super(AdaptiveAvgPool3D, self).__init__() + self._output_size = output_size + self._data_format = data_format + self._name = name + + def forward(self, x): + return F.adaptive_avg_pool3d( + x, + output_size=self._output_size, + data_format=self._data_format, + name=self._name, + ) + + def extra_repr(self): + return 'output_size={}'.format(self._output_size) + + +class AdaptiveMaxPool1D(Layer): + """ + + This operation applies a 1D adaptive max pooling over an input signal composed + of several input planes, based on the input, output_size, return_mask parameters. + Input(X) and output(Out) are in NCL format, where N is batch + size, C is the number of channels, L is the length of the feature. + The output tensor shape will be [N, C, output_size]. + + For max adaptive pool1d: + + .. math:: + + lstart &= floor(i * L_{in} / L_{out}) + + lend &= ceil((i + 1) * L_{in} / L_{out}) + + Output(i) &= max(Input[lstart:lend]) + + Parameters: + output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, + it must contain one int. + return_mask(bool, optional): If true, the index of max pooling point will be returned along + with outputs. It cannot be set in average pooling type. Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + Returns: + A callable object of AdaptiveMaxPool1D. + + Shape: + - x(Tensor): The input tensor of adaptive max pool1d operator, which is a 3-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of adaptive max pool1d operator, which is a 3-D tensor. + The data type is same as input x. + + Examples: + .. code-block:: python + + # max adaptive pool1d + # suppose input data in shape of [N, C, L], `output_size` is m or [m], + # output shape is [N, C, m], adaptive pool divide L dimension + # of input data into m grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # lstart = floor(i * L / m) + # lend = ceil((i + 1) * L / m) + # output[:, :, i] = max(input[:, :, lstart: lend]) + # + import paddle + import paddle.nn as nn + + data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1) + AdaptiveMaxPool1D = nn.AdaptiveMaxPool1D(output_size=16) + pool_out = AdaptiveMaxPool1D(data) + # pool_out shape: [1, 3, 16] + + # for return_mask = true + AdaptiveMaxPool1D = nn.AdaptiveMaxPool1D(output_size=16, return_mask=True) + pool_out, indices = AdaptiveMaxPool1D(data) + # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16] + + """ + + def __init__(self, output_size, return_mask=False, name=None): + super(AdaptiveMaxPool1D, self).__init__() + self.output_size = output_size + self.return_mask = return_mask + self.name = name + + def forward(self, input): + return F.adaptive_max_pool1d( + input, self.output_size, self.return_mask, self.name + ) + + def extra_repr(self): + return 'output_size={}, return_mask={}'.format( + self.output_size, self.return_mask + ) + + +class AdaptiveMaxPool2D(Layer): + """ + This operation applies 2D adaptive max pooling on input tensor. The h and w dimensions + of the output tensor are determined by the parameter output_size. The difference between adaptive pooling and + pooling is adaptive one focus on the output size. + + For adaptive max pool2d: + + .. math:: + + hstart &= floor(i * H_{in} / H_{out}) + + hend &= ceil((i + 1) * H_{in} / H_{out}) + + wstart &= floor(j * W_{in} / W_{out}) + + wend &= ceil((j + 1) * W_{in} / W_{out}) + + Output(i ,j) &= max(Input[hstart:hend, wstart:wend]) + + Parameters: + output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain + two element, (H, W). H and W can be either a int, or None which means the size will be the same as that of + the input. + return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs. + It cannot be set in average pooling type. Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + Shape: + - x(Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of adaptive max pool2d operator, which is a 4-D tensor. + The data type is same as input x. + + Returns: + A callable object of AdaptiveMaxPool2D. + Examples: + .. code-block:: python + + # adaptive max pool2d + # suppose input data in shape of [N, C, H, W], `output_size` is [m, n], + # output shape is [N, C, m, n], adaptive pool divide H and W dimensions + # of input data into m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(m): + # for j in range(n): + # hstart = floor(i * H / m) + # hend = ceil((i + 1) * H / m) + # wstart = floor(i * W / n) + # wend = ceil((i + 1) * W / n) + # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend]) + # + import paddle + + x = paddle.rand([2, 3, 32, 32]) + + adaptive_max_pool = paddle.nn.AdaptiveMaxPool2D(output_size=3, return_mask=True) + pool_out, indices = adaptive_max_pool(x = x) + """ + + def __init__(self, output_size, return_mask=False, name=None): + super(AdaptiveMaxPool2D, self).__init__() + self._output_size = output_size + self._return_mask = return_mask + self._name = name + + def forward(self, x): + return F.adaptive_max_pool2d( + x, + output_size=self._output_size, + return_mask=self._return_mask, + name=self._name, + ) + + def extra_repr(self): + return 'output_size={}, return_mask={}'.format( + self._output_size, self._return_mask + ) + + +class AdaptiveMaxPool3D(Layer): + """ + This operation applies 3D adaptive max pooling on input tensor. The h and w dimensions of the output tensor are + determined by the parameter output_size. The difference between adaptive pooling and pooling is adaptive one focus + on the output size. + + For adaptive max pool3d: + + .. math:: + + dstart &= floor(i * D_{in} / D_{out}) + + dend &= ceil((i + 1) * D_{in} / D_{out}) + + hstart &= floor(j * H_{in} / H_{out}) + + hend &= ceil((j + 1) * H_{in} / H_{out}) + + wstart &= floor(k * W_{in} / W_{out}) + + wend &= ceil((k + 1) * W_{in} / W_{out}) + + Output(i ,j, k) &= max(Input[dstart:dend, hstart:hend, wstart:wend]) + + Parameters: + output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain + three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as + that of the input. + return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs. + Default False. + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + Shape: + - x(Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of adaptive max pool3d operator, which is a 5-D tensor. + The data type is same as input x. + + Returns: + A callable object of AdaptiveMaxPool3D. + Examples: + .. code-block:: python + + # adaptive max pool3d + # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n], + # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions + # of input data into l * m * n grids averagely and performs poolings in each + # grid to get output. + # adaptive max pool performs calculations as follow: + # + # for i in range(l): + # for j in range(m): + # for k in range(n): + # dstart = floor(i * D / l) + # dend = ceil((i + 1) * D / l) + # hstart = floor(j * H / m) + # hend = ceil((j + 1) * H / m) + # wstart = floor(k * W / n) + # wend = ceil((k + 1) * W / n) + # output[:, :, i, j, k] = + # max(input[:, :, dstart:dend, hstart: hend, wstart: wend]) + import paddle + + x = paddle.rand([2, 3, 8, 32, 32]) + pool = paddle.nn.AdaptiveMaxPool3D(output_size=4) + out = pool(x) + # out shape: [2, 3, 4, 4, 4] + pool = paddle.nn.AdaptiveMaxPool3D(output_size=3, return_mask=True) + out, indices = pool(x) + # out shape: [2, 3, 4, 4, 4], indices shape: [2, 3, 4, 4, 4] + + """ + + def __init__(self, output_size, return_mask=False, name=None): + super(AdaptiveMaxPool3D, self).__init__() + self._output_size = output_size + self._return_mask = return_mask + self._name = name + + def forward(self, x): + return F.adaptive_max_pool3d( + x, + output_size=self._output_size, + return_mask=self._return_mask, + name=self._name, + ) + + def extra_repr(self): + return 'output_size={}, return_mask={}'.format( + self._output_size, self._return_mask + ) + + +class MaxUnPool1D(Layer): + r""" + This API implements max unpooling 1d opereation. + + `max_unpool1d` accepts the output of `max_pool1d` as input, + including the indices of the maximum value and calculate the partial inverse. + All non-maximum values ​​are set to zero. + + - Input: :math:`(N, C, L_{in})` + - Output: :math:`(N, C, L_{out})`, where + + .. math:: + L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size + + or as given by :attr:`output_size` in the call operator. + + Parameters: + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, stride, padding). + data_format (string): The data format of the input and output data. + The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of: + `[batch_size, input_channels, input_length]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + + Returns: + A callable object of MaxUnPool1D. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1, 3, 16]) + pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 3, 8], indices shape: [1, 3, 8] + Unpool1D = paddle.nn.MaxUnPool1D(kernel_size=2, padding=0) + unpool_out = Unpool1D(pool_out, indices) + # unpool_out shape: [1, 3, 16] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + data_format="NCL", + output_size=None, + name=None, + ): + super(MaxUnPool1D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.data_format = data_format + self.output_size = output_size + self.name = name + + def forward(self, x, indices): + return F.max_unpool1d( + x, + indices, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + data_format=self.data_format, + output_size=self.output_size, + name=self.name, + ) + + def extra_repr(self): + return 'output_size={}'.format(self.output_size) + + +class MaxUnPool2D(Layer): + r""" + This API implements max unpooling 2d opereation. + + 'max_unpool2d' accepts the output of 'max_unpool2d' as input + Including the indices of the maximum value and calculating the partial inverse + All non-maximum values ​​are set to zero. + + + Parameters: + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + kernel_size (int|tuple): Size of the max unpooling window. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, padding). + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + + - Input: :math:`(N, C, H_{in}, W_{in})` + - Output: :math:`(N, C, H_{out}, W_{out})`, where + + .. math:: + H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]} + + .. math:: + W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]} + + or as given by :attr:`output_size` in the call operator + + Returns: + A callable object of MaxUnPool2D. + + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1,1,6,6]) + pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 1, 3, 3], indices shape: [1, 1, 3, 3] + Unpool2D = paddle.nn.MaxUnPool2D(kernel_size=2, padding=0) + unpool_out = Unpool2D(pool_out, indices) + # unpool_out shape: [1, 1, 6, 6] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + data_format="NCHW", + output_size=None, + name=None, + ): + super(MaxUnPool2D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.data_format = data_format + self.output_size = output_size + self.name = name + + def forward(self, x, indices): + return F.max_unpool2d( + x, + indices, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + data_format=self.data_format, + output_size=self.output_size, + name=self.name, + ) + + def extra_repr(self): + return 'output_size={}'.format(self.output_size) + + +class MaxUnPool3D(Layer): + r""" + This API implements max unpooling 3d opereation. + + `max_unpool3d` accepts the output of `max_pool3d` as input, + including the indices of the maximum value and calculate the partial inverse. + All non-maximum values ​​are set to zero. + + - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where + + .. math:: + D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0] + + .. math:: + H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1] + + .. math:: + W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2] + + or as given by :attr:`output_size` in the call operator + + + Parameters: + kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list, + it must contain an integer. + stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list, + it must contain an integer. + padding (int | tuple): Padding that was added to the input. + output_size(list|tuple, optional): The target output size. If output_size is not specified, + the actual output shape will be automatically calculated by (input_shape, + kernel_size, stride, padding). + data_format (string): The data format of the input and output data. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + + Returns: + A callable object of MaxUnPool3D. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + data = paddle.rand(shape=[1, 1, 4, 4, 6]) + pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True) + # pool_out shape: [1, 1, 2, 2, 3], indices shape: [1, 1, 2, 2, 3] + Unpool3D = paddle.nn.MaxUnPool3D(kernel_size=2, padding=0) + unpool_out = Unpool3D(pool_out, indices) + # unpool_out shape: [1, 1, 4, 4, 6] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + data_format="NCDHW", + output_size=None, + name=None, + ): + super(MaxUnPool3D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.data_format = data_format + self.output_size = output_size + self.name = name + + def forward(self, x, indices): + return F.max_unpool3d( + x, + indices, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + data_format=self.data_format, + output_size=self.output_size, + name=self.name, + ) + + def extra_repr(self): + return 'output_size={}'.format(self.output_size) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/rnn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..fc85dfe1a1a67297fc5da465b9defd6ffdb780e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/rnn.py @@ -0,0 +1,1444 @@ +# 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. + +import copy +import collections +import itertools +import six +import math +import sys +import warnings +from functools import partial, reduce + +import numpy as np +import paddle +import paddle.fluid as fluid +from paddle import framework +from paddle.device import get_device, get_cudnn_version +from paddle.nn import functional as F +from paddle.nn import initializer as I +from paddle.nn import Layer, LayerList +from paddle.fluid.layers import utils +from paddle.fluid.layers.utils import map_structure, flatten, pack_sequence_as +from paddle.fluid.data_feeder import convert_dtype +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from paddle.fluid.framework import in_dygraph_mode +from paddle.framework import core +from paddle.static import default_startup_program +from paddle.static import program_guard +try: + from collections.abc import Sequence +except: + from collections import Sequence + +__all__ = [] + + +def split_states(states, bidirectional=False, state_components=1): + r""" + Split states of RNN network into possibly nested list or tuple of + states of each RNN cells of the RNN network. + + Parameters: + states (Tensor|tuple|list): the concatenated states for RNN network. + When `state_components` is 1, states in a Tensor with shape + `(L*D, N, C)` where `L` is the number of layers of the RNN + network, `D` is the number of directions of the RNN network(1 + for unidirectional RNNs and 2 for bidirectional RNNs), `N` is + the batch size of the input to the RNN network, `C` is the + hidden size of the RNN network. + + When `state_components` is larger than 1, `states` is a tuple of + `state_components` Tensors that meet the requirements described + above. + + For SimpleRNNs and GRUs, `state_components` is 1, and for LSTMs, + `state_components` is 2. + bidirectional (bool): whether the state is of a bidirectional RNN + network. Defaults to False. + state_components (int): the number of the components of the states. see + `states` above. Defaults to 1. + + Returns: + A nested list or tuple of RNN cell states. + If `bidirectional` is True, it can be indexed twice to get an RNN + cell state. The first index indicates the layer, the second index + indicates the direction. + If `bidirectional` is False, it can be indexed once to get an RNN + cell state. The index indicates the layer. + Note that if `state_components` is larger than 1, an RNN cell state + can be indexed one more time to get a tensor of shape(N, C), where + `N` is the batch size of the input to the RNN cell, and `C` is the + hidden size of the RNN cell. + """ + if state_components == 1: + states = paddle.unstack(states) + if not bidirectional: + return states + else: + return list(zip(states[::2], states[1::2])) + else: + assert len(states) == state_components + states = tuple([paddle.unstack(item) for item in states]) + if not bidirectional: + return list(zip(*states)) + else: + states = list(zip(*states)) + return list(zip(states[::2], states[1::2])) + + +def concat_states(states, bidirectional=False, state_components=1): + r""" + Concatenate a possibly nested list or tuple of RNN cell states into a + compact form. + + Parameters: + states (list|tuple): a possibly nested list or tuple of RNN cell + states. + If `bidirectional` is True, it can be indexed twice to get an + RNN cell state. The first index indicates the layer, the second + index indicates the direction. + If `bidirectional` is False, it can be indexed once to get an RNN + cell state. The index indicates the layer. + Note that if `state_components` is larger than 1, an RNN cell + state can be indexed one more time to get a tensor of shape(N, C), + where `N` is the batch size of the input to the RNN cell, and + `C` is the hidden size of the RNN cell. + bidirectional (bool): whether the state is of a bidirectional RNN + network. Defaults to False. + state_components (int): the number of the components of the states. see + `states` above. Defaults to 1. + + Returns: + Concatenated states for RNN network. + When `state_components` is 1, states in a Tensor with shape + `(L\*D, N, C)` where `L` is the number of layers of the RNN + network, `D` is the number of directions of the RNN network(1 for + unidirectional RNNs and 2 for bidirectional RNNs), `N` is the batch + size of the input to the RNN network, `C` is the hidden size of the + RNN network. + + """ + if state_components == 1: + return paddle.stack(flatten(states)) + else: + states = flatten(states) + componnets = [] + for i in range(state_components): + componnets.append(states[i::state_components]) + return tuple([paddle.stack(item) for item in componnets]) + + +class RNNCellBase(Layer): + r""" + RNNCellBase is the base class for abstraction representing the calculations + mapping the input and state to the output and new state. It is suitable to + and mostly used in RNN. + """ + + def get_initial_states(self, + batch_ref, + shape=None, + dtype=None, + init_value=0., + batch_dim_idx=0): + r""" + Generate initialized states according to provided shape, data type and + value. + + Parameters: + batch_ref (Tensor): A tensor, which shape would be used to + determine the batch size, which is used to generate initial + states. For `batch_ref`'s shape d, `d[batch_dim_idx]` is + treated as batch size. + shape (list|tuple, optional): A (possibly nested structure of) shape[s], + where a shape is a list/tuple of integer. `-1` (for batch size) + will be automatically prepended if a shape does not starts with + it. If None, property `state_shape` will be used. Defaults to + None. + dtype (str|list|tuple, optional): A (possibly nested structure of) + data type[s]. The structure must be same as that of `shape`, + except when all tensors' in states has the same data type, a + single data type can be used. If None and property `cell.state_shape` + is not available, current default floating type of paddle is + used. Defaults to None. + init_value (float, optional): A float value used to initialize states. + Defaults to 0. + batch_dim_idx (int, optional): An integer indicating which + dimension of the of `batch_ref` represents batch. Defaults to 0. + + Returns: + init_states (Tensor|tuple|list): tensor of the provided shape and + dtype, or list of tensors that each satisfies the requirements, + packed in the same structure as `shape` and `type` does. + """ + # TODO: use inputs and batch_size + batch_ref = flatten(batch_ref)[0] + + def _is_shape_sequence(seq): + if sys.version_info < (3, ): + integer_types = ( + int, + long, + ) + else: + integer_types = (int, ) + """For shape, list/tuple of integer is the finest-grained objection""" + if (isinstance(seq, list) or isinstance(seq, tuple)): + if reduce(lambda flag, x: isinstance(x, integer_types) and flag, + seq, True): + return False + # TODO: Add check for the illegal + if isinstance(seq, dict): + return True + return (isinstance(seq, Sequence) + and not isinstance(seq, six.string_types)) + + class Shape(object): + + def __init__(self, shape): + self.shape = shape if shape[0] == -1 else ([-1] + list(shape)) + + # nested structure of shapes + states_shapes = self.state_shape if shape is None else shape + is_sequence_ori = utils.is_sequence + utils.is_sequence = _is_shape_sequence + states_shapes = map_structure(lambda shape: Shape(shape), states_shapes) + utils.is_sequence = is_sequence_ori + + # nested structure of dtypes + try: + states_dtypes = self.state_dtype if dtype is None else dtype + except NotImplementedError: + states_dtypes = framework.get_default_dtype() + if len(flatten(states_dtypes)) == 1: + dtype = flatten(states_dtypes)[0] + states_dtypes = map_structure(lambda shape: dtype, states_shapes) + + init_states = map_structure( + lambda shape, dtype: paddle.fluid.layers. + fill_constant_batch_size_like(input=batch_ref, + shape=shape.shape, + dtype=dtype, + value=init_value, + input_dim_idx=batch_dim_idx), + states_shapes, states_dtypes) + return init_states + + @property + def state_shape(self): + r""" + Abstract method (property). + Used to initialize states. + A (possiblely nested structure of) shape[s], where a shape is a + list/tuple of integers (-1 for batch size would be automatically + inserted into a shape if shape is not started with it). + Not necessary to be implemented if states are not initialized by + `get_initial_states` or the `shape` argument is provided when using + `get_initial_states`. + """ + raise NotImplementedError( + "Please add implementaion for `state_shape` in the used cell.") + + @property + def state_dtype(self): + r""" + Abstract method (property). + Used to initialize states. + A (possiblely nested structure of) data types[s]. The structure must be + same as that of `shape`, except when all tensors' in states has the same + data type, a signle data type can be used. + Not necessary to be implemented if states are not initialized + by `get_initial_states` or the `dtype` argument is provided when using + `get_initial_states`. + """ + raise NotImplementedError( + "Please add implementaion for `state_dtype` in the used cell.") + + +class SimpleRNNCell(RNNCellBase): + r""" + Elman RNN (SimpleRNN) cell. Given the inputs and previous states, it + computes the outputs and updates states. + + The formula used is as follows: + + .. math:: + h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh}) + + y_{t} & = h_{t} + + where :math:`act` is for :attr:`activation`. + + Please refer to `Finding Structure in Time + `_ for more details. + + Parameters: + input_size (int): The input size. + hidden_size (int): The hidden size. + activation (str, optional): The activation in the SimpleRNN cell. + It can be `tanh` or `relu`. Defaults to `tanh`. + weight_ih_attr (ParamAttr, optional): The parameter attribute for + :math:`weight_ih`. Default: None. + weight_hh_attr(ParamAttr, optional): The parameter attribute for + :math:`weight_hh`. Default: None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + :math:`bias_ih`. Default: None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + :math:`bias_hh`. Default: None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Variables: + - **weight_ih** (Parameter): shape (hidden_size, input_size), input to hidden weight, corresponding to :math:`W_{ih}` in the formula. + - **weight_hh** (Parameter): shape (hidden_size, hidden_size), hidden to hidden weight, corresponding to :math:`W_{hh}` in the formula. + - **bias_ih** (Parameter): shape (hidden_size, ), input to hidden bias, corresponding to :math:`b_{ih}` in the formula. + - **bias_hh** (Parameter): shape (hidden_size, ), hidden to hidden bias, corresponding to :math:`b_{hh}` in the formula. + + Inputs: + - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_{t}` in the formula. + - **states** (Tensor, optional): shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}` in the formula. When states is None, zero state is used. Defaults to None. + + Returns: + - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula. + - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula. + + Notes: + All the weights and bias are initialized with `Uniform(-std, std)` by default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn((4, 16)) + prev_h = paddle.randn((4, 32)) + + cell = paddle.nn.SimpleRNNCell(16, 32) + y, h = cell(x, prev_h) + print(y.shape) + + #[4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + activation="tanh", + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + super(SimpleRNNCell, self).__init__() + if hidden_size <= 0: + raise ValueError( + "hidden_size of {} must be greater than 0, but now equals to {}" + .format(self.__class__.__name__, hidden_size)) + std = 1.0 / math.sqrt(hidden_size) + self.weight_ih = self.create_parameter( + (hidden_size, input_size), + weight_ih_attr, + default_initializer=I.Uniform(-std, std)) + self.weight_hh = self.create_parameter( + (hidden_size, hidden_size), + weight_hh_attr, + default_initializer=I.Uniform(-std, std)) + self.bias_ih = self.create_parameter( + (hidden_size, ), + bias_ih_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + self.bias_hh = self.create_parameter( + (hidden_size, ), + bias_hh_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + + self.input_size = input_size + self.hidden_size = hidden_size + if activation not in ["tanh", "relu"]: + raise ValueError( + "activation for SimpleRNNCell should be tanh or relu, " + "but get {}".format(activation)) + self.activation = activation + self._activation_fn = paddle.tanh \ + if activation == "tanh" \ + else F.relu + + def forward(self, inputs, states=None): + if states is None: + states = self.get_initial_states(inputs, self.state_shape) + pre_h = states + i2h = paddle.matmul(inputs, self.weight_ih, transpose_y=True) + if self.bias_ih is not None: + i2h += self.bias_ih + h2h = paddle.matmul(pre_h, self.weight_hh, transpose_y=True) + if self.bias_hh is not None: + h2h += self.bias_hh + h = self._activation_fn(i2h + h2h) + return h, h + + @property + def state_shape(self): + return (self.hidden_size, ) + + def extra_repr(self): + s = '{input_size}, {hidden_size}' + if self.activation != "tanh": + s += ', activation={activation}' + return s.format(**self.__dict__) + + +class LSTMCell(RNNCellBase): + r""" + Long-Short Term Memory(LSTM) RNN cell. Given the inputs and previous states, + it computes the outputs and updates states. + + The formula used is as follows: + + .. math:: + i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi}) + + f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf}) + + o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho}) + + \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg}) + + c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t} + + h_{t} & = o_{t} * \tanh(c_{t}) + + y_{t} & = h_{t} + + where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise + multiplication operator. + + Please refer to `An Empirical Exploration of Recurrent Network Architectures + `_ for more details. + + Parameters: + input_size (int): The input size. + hidden_size (int): The hidden size. + weight_ih_attr(ParamAttr, optional): The parameter attribute for + `weight_ih`. Default: None. + weight_hh_attr(ParamAttr, optional): The parameter attribute for + `weight_hh`. Default: None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + `bias_ih`. Default: None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + `bias_hh`. Default: None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Variables: + - **weight_ih** (Parameter): shape (4 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ii}, W_{if}, W_{ig}, W_{io}` in the formula. + - **weight_hh** (Parameter): shape (4 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hi}, W_{hf}, W_{hg}, W_{ho}` in the formula. + - **bias_ih** (Parameter): shape (4 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ii}, b_{if}, b_{ig}, b_{io}` in the formula. + - **bias_hh** (Parameter): shape (4 * hidden_size, ), hidden to hidden bias, swhich corresponds to the concatenation of :math:`b_{hi}, b_{hf}, b_{hg}, b_{ho}` in the formula. + + Inputs: + - **inputs** (Tensor): shape `[batch_size, input_size]`, the input, corresponding to :math:`x_t` in the formula. + - **states** (list|tuple, optional): a list/tuple of two tensors, each of shape `[batch_size, hidden_size]`, the previous hidden state, corresponding to :math:`h_{t-1}, c_{t-1}` in the formula. When states is None, zero state is used. Defaults to None. + + Returns: + - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula. + - **states** (tuple): a tuple of two tensors, each of shape `[batch_size, hidden_size]`, the new hidden states, corresponding to :math:`h_{t}, c_{t}` in the formula. + + Notes: + All the weights and bias are initialized with `Uniform(-std, std)` by + default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more + information about parameter initialization, please refer to :ref:`api_fluid_ParamAttr`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn((4, 16)) + prev_h = paddle.randn((4, 32)) + prev_c = paddle.randn((4, 32)) + + cell = paddle.nn.LSTMCell(16, 32) + y, (h, c) = cell(x, (prev_h, prev_c)) + + print(y.shape) + print(h.shape) + print(c.shape) + + #[4,32] + #[4,32] + #[4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + super(LSTMCell, self).__init__() + if hidden_size <= 0: + raise ValueError( + "hidden_size of {} must be greater than 0, but now equals to {}" + .format(self.__class__.__name__, hidden_size)) + std = 1.0 / math.sqrt(hidden_size) + self.weight_ih = self.create_parameter( + (4 * hidden_size, input_size), + weight_ih_attr, + default_initializer=I.Uniform(-std, std)) + self.weight_hh = self.create_parameter( + (4 * hidden_size, hidden_size), + weight_hh_attr, + default_initializer=I.Uniform(-std, std)) + self.bias_ih = self.create_parameter( + (4 * hidden_size, ), + bias_ih_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + self.bias_hh = self.create_parameter( + (4 * hidden_size, ), + bias_hh_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + + self.hidden_size = hidden_size + self.input_size = input_size + self._gate_activation = F.sigmoid + self._activation = paddle.tanh + + def forward(self, inputs, states=None): + if states is None: + states = self.get_initial_states(inputs, self.state_shape) + pre_hidden, pre_cell = states + gates = paddle.matmul(inputs, self.weight_ih, transpose_y=True) + if self.bias_ih is not None: + gates = gates + self.bias_ih + gates += paddle.matmul(pre_hidden, self.weight_hh, transpose_y=True) + if self.bias_hh is not None: + gates = gates + self.bias_hh + + chunked_gates = paddle.split(gates, num_or_sections=4, axis=-1) + + i = self._gate_activation(chunked_gates[0]) + f = self._gate_activation(chunked_gates[1]) + o = self._gate_activation(chunked_gates[3]) + c = f * pre_cell + i * self._activation(chunked_gates[2]) + h = o * self._activation(c) + + return h, (h, c) + + @property + def state_shape(self): + r""" + The `state_shape` of LSTMCell is a tuple with two shapes: + `((hidden_size, ), (hidden_size,))`. (-1 for batch size would be + automatically inserted into shape). These two shapes correspond + to :math:`h_{t-1}` and :math:`c_{t-1}` separately. + """ + return ((self.hidden_size, ), (self.hidden_size, )) + + def extra_repr(self): + return '{input_size}, {hidden_size}'.format(**self.__dict__) + + +class GRUCell(RNNCellBase): + r""" + Gated Recurrent Unit (GRU) RNN cell. Given the inputs and previous states, + it computes the outputs and updates states. + + The formula for GRU used is as follows: + + .. math:: + + r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr}) + + z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz}) + + \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc})) + + h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t} + + y_{t} & = h_{t} + + where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise + multiplication operator. + + Please refer to `An Empirical Exploration of Recurrent Network Architectures + `_ for more details. + + Parameters: + input_size (int): The input size. + hidden_size (int): The hidden size. + weight_ih_attr(ParamAttr, optional): The parameter attribute for + `weight_ih`. Default: None. + weight_hh_attr(ParamAttr, optional): The parameter attribute for + `weight_hh`. Default: None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + `bias_ih`. Default: None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + `bias_hh`. Default: None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Variables: + - **weight_ih** (Parameter): shape (3 * hidden_size, input_size), input to hidden weight, which corresponds to the concatenation of :math:`W_{ir}, W_{iz}, W_{ic}` in the formula. + - **weight_hh** (Parameter): shape (3 * hidden_size, hidden_size), hidden to hidden weight, which corresponds to the concatenation of :math:`W_{hr}, W_{hz}, W_{hc}` in the formula. + - **bias_ih** (Parameter): shape (3 * hidden_size, ), input to hidden bias, which corresponds to the concatenation of :math:`b_{ir}, b_{iz}, b_{ic}` in the formula. + - **bias_hh** (Parameter): shape (3 * hidden_size, ), hidden to hidden bias, swhich corresponds to the concatenation of :math:`b_{hr}, b_{hz}, b_{hc}` in the formula. + + Inputs: + - **inputs** (Tensor): A tensor with shape `[batch_size, input_size]`, corresponding to :math:`x_t` in the formula. + - **states** (Tensor): A tensor with shape `[batch_size, hidden_size]`, corresponding to :math:`h_{t-1}` in the formula. + + Returns: + - **outputs** (Tensor): shape `[batch_size, hidden_size]`, the output, corresponding to :math:`h_{t}` in the formula. + - **states** (Tensor): shape `[batch_size, hidden_size]`, the new hidden state, corresponding to :math:`h_{t}` in the formula. + + Notes: + All the weights and bias are initialized with `Uniform(-std, std)` by + default. Where std = :math:`\frac{1}{\sqrt{hidden\_size}}`. For more + information about parameter initialization, please refer to s:ref:`api_fluid_ParamAttr`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn((4, 16)) + prev_h = paddle.randn((4, 32)) + + cell = paddle.nn.GRUCell(16, 32) + y, h = cell(x, prev_h) + + print(y.shape) + print(h.shape) + + #[4,32] + #[4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + super(GRUCell, self).__init__() + if hidden_size <= 0: + raise ValueError( + "hidden_size of {} must be greater than 0, but now equals to {}" + .format(self.__class__.__name__, hidden_size)) + std = 1.0 / math.sqrt(hidden_size) + self.weight_ih = self.create_parameter( + (3 * hidden_size, input_size), + weight_ih_attr, + default_initializer=I.Uniform(-std, std)) + self.weight_hh = self.create_parameter( + (3 * hidden_size, hidden_size), + weight_hh_attr, + default_initializer=I.Uniform(-std, std)) + self.bias_ih = self.create_parameter( + (3 * hidden_size, ), + bias_ih_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + self.bias_hh = self.create_parameter( + (3 * hidden_size, ), + bias_hh_attr, + is_bias=True, + default_initializer=I.Uniform(-std, std)) + + self.hidden_size = hidden_size + self.input_size = input_size + self._gate_activation = F.sigmoid + self._activation = paddle.tanh + + def forward(self, inputs, states=None): + if states is None: + states = self.get_initial_states(inputs, self.state_shape) + + pre_hidden = states + x_gates = paddle.matmul(inputs, self.weight_ih, transpose_y=True) + if self.bias_ih is not None: + x_gates = x_gates + self.bias_ih + h_gates = paddle.matmul(pre_hidden, self.weight_hh, transpose_y=True) + if self.bias_hh is not None: + h_gates = h_gates + self.bias_hh + + x_r, x_z, x_c = paddle.split(x_gates, num_or_sections=3, axis=1) + h_r, h_z, h_c = paddle.split(h_gates, num_or_sections=3, axis=1) + + r = self._gate_activation(x_r + h_r) + z = self._gate_activation(x_z + h_z) + c = self._activation(x_c + r * h_c) # apply reset gate after mm + h = (pre_hidden - c) * z + c + + return h, h + + @property + def state_shape(self): + r""" + The `state_shape` of GRUCell is a shape `[hidden_size]` (-1 for batch + size would be automatically inserted into shape). The shape corresponds + to the shape of :math:`h_{t-1}`. + """ + return (self.hidden_size, ) + + def extra_repr(self): + return '{input_size}, {hidden_size}'.format(**self.__dict__) + + +class RNN(Layer): + r""" + Wrapper for RNN, which creates a recurrent neural network with an RNN cell. + It performs :code:`cell.forward()` repeatedly until reaches to the maximum + length of `inputs`. + + Parameters: + cell(RNNCellBase): An instance of `RNNCellBase`. + is_reverse (bool, optional): Indicate whether to calculate in the reverse + order of input sequences. Defaults to False. + time_major (bool): Whether the first dimension of the input means the + time steps. Defaults to False. + + Inputs: + - **inputs** (Tensor): A (possibly nested structure of) tensor[s]. The input sequences. If time major is False, the shape is `[batch_size, time_steps, input_size]`. If time major is True, the shape is `[time_steps, batch_size, input_size]` where `input_size` is the input size of the cell. + - **initial_states** (Tensor|list|tuple, optional): Tensor of a possibly nested structure of tensors, representing the initial state for the rnn cell. If not provided, `cell.get_initial_states` would be called to produce the initial states. Defaults to None. + - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None.If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings. + - **kwargs**: Additional keyword arguments to pass to `forward` of the cell. + + Returns: + - **outputs** (Tensor|list|tuple): the output sequences. If `time_major` is True, the shape is `[time_steps, batch_size, hidden_size]`, else `[batch_size, time_steps, hidden_size]`. + - **final_states** (Tensor|list|tuple): final states of the cell. Tensor or a possibly nested structure of tensors which has the same structure with intial state. Each tensor in final states has the same shape and dtype as the corresponding tensor in initial states. + + Notes: + This class is a low level API for wrapping rnn cell into a RNN network. + Users should take care of the state of the cell. If `initial_states` is + passed to the `forward` method, make sure that it satisfies the + requirements of the cell. + + Examples: + + .. code-block:: python + + import paddle + + inputs = paddle.rand((4, 23, 16)) + prev_h = paddle.randn((4, 32)) + + cell = paddle.nn.SimpleRNNCell(16, 32) + rnn = paddle.nn.RNN(cell) + outputs, final_states = rnn(inputs, prev_h) + + print(outputs.shape) + print(final_states.shape) + + #[4,23,32] + #[4,32] + + """ + + def __init__(self, cell, is_reverse=False, time_major=False): + super(RNN, self).__init__() + self.cell = cell + if not hasattr(self.cell, "call"): + # for non-dygraph mode, `rnn` api uses cell.call + self.cell.call = self.cell.forward + self.is_reverse = is_reverse + self.time_major = time_major + + def forward(self, + inputs, + initial_states=None, + sequence_length=None, + **kwargs): + final_outputs, final_states = paddle.fluid.layers.rnn( + self.cell, + inputs, + initial_states=initial_states, + sequence_length=sequence_length, + time_major=self.time_major, + is_reverse=self.is_reverse, + **kwargs) + return final_outputs, final_states + + +class BiRNN(Layer): + r""" + Wrapper for bidirectional RNN, which builds a bidiretional RNN given the + forward rnn cell and backward rnn cell. A BiRNN applies forward RNN and + backward RNN with coresponding cells separately and concats the outputs + along the last axis. + + Parameters: + cell_fw (RNNCellBase): A RNNCellBase instance used for forward RNN. + cell_bw (RNNCellBase): A RNNCellBase instance used for backward RNN. + time_major (bool): Whether the first dimension of the input means the + time steps. Defaults to False. + + Inputs: + - **inputs** (Tensor): the input sequences of both RNN. If time_major is True, the shape of is `[time_steps, batch_size, input_size]`, else the shape is `[batch_size, time_steps, input_size]`, where input_size is the input size of both cells. + - **initial_states** (list|tuple, optional): A tuple/list of the initial states of the forward cell and backward cell. Defaults to None. If not provided, `cell.get_initial_states` would be called to produce the initial states for each cell. Defaults to None. + - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings. + - **kwargs**: Additional keyword arguments. Arguments passed to `forward` for each cell. + + Outputs: + - **outputs** (Tensor): the outputs of the bidirectional RNN. It is the concatenation of the outputs from the forward RNN and backward RNN along the last axis. If time major is True, the shape is `[time_steps, batch_size, size]`, else the shape is `[batch_size, time_steps, size]`, where size is `cell_fw.hidden_size + cell_bw.hidden_size`. + - **final_states** (tuple): A tuple of the final states of the forward cell and backward cell. + + Notes: + This class is a low level API for wrapping rnn cells into a BiRNN + network. Users should take care of the states of the cells. + If `initial_states` is passed to the `forward` method, make sure that + it satisfies the requirements of the cells. + + Examples: + + .. code-block:: python + + import paddle + + cell_fw = paddle.nn.LSTMCell(16, 32) + cell_bw = paddle.nn.LSTMCell(16, 32) + rnn = paddle.nn.BiRNN(cell_fw, cell_bw) + + inputs = paddle.rand((2, 23, 16)) + outputs, final_states = rnn(inputs) + + print(outputs.shape) + print(final_states[0][0].shape,len(final_states),len(final_states[0])) + + #[4,23,64] + #[2,32] 2 2 + + """ + + def __init__(self, cell_fw, cell_bw, time_major=False): + super(BiRNN, self).__init__() + self.cell_fw = cell_fw + self.cell_bw = cell_bw + if cell_fw.input_size != cell_bw.input_size: + raise ValueError("input size of forward cell({}) does not equals" + "that of backward cell({})".format( + cell_fw.input_size, cell_bw.input_size)) + for cell in [self.cell_fw, self.cell_bw]: + if not hasattr(cell, "call"): + # for non-dygraph mode, `rnn` api uses cell.call + cell.call = cell.forward + self.time_major = time_major + + def forward(self, + inputs, + initial_states=None, + sequence_length=None, + **kwargs): + if isinstance(initial_states, (list, tuple)): + assert len(initial_states) == 2, \ + "length of initial_states should be 2 when it is a list/tuple" + + outputs, final_states = paddle.fluid.layers.birnn( + self.cell_fw, self.cell_bw, inputs, initial_states, sequence_length, + self.time_major, **kwargs) + return outputs, final_states + + +class RNNBase(LayerList): + r""" + RNNBase class for RNN networks. It provides `forward`, `flatten_parameters` + and other common methods for SimpleRNN, LSTM and GRU. + """ + + def __init__(self, + mode, + input_size, + hidden_size, + num_layers=1, + direction="forward", + time_major=False, + dropout=0., + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None): + super(RNNBase, self).__init__() + bidirectional_list = ["bidirectional", "bidirect"] + self.mode = mode + self.input_size = input_size + self.hidden_size = hidden_size + self.dropout = dropout + self.num_directions = 2 if direction in bidirectional_list else 1 + self.time_major = time_major + self.num_layers = num_layers + self.state_components = 2 if mode == "LSTM" else 1 + + kwargs = { + "weight_ih_attr": weight_ih_attr, + "weight_hh_attr": weight_hh_attr, + "bias_ih_attr": bias_ih_attr, + "bias_hh_attr": bias_hh_attr + } + + if mode == "LSTM": + rnn_cls = LSTMCell + elif mode == "GRU": + rnn_cls = GRUCell + else: + rnn_cls = SimpleRNNCell + kwargs["activation"] = self.activation + + if direction in ["forward"]: + is_reverse = False + cell = rnn_cls(input_size, hidden_size, **kwargs) + self.append(RNN(cell, is_reverse, time_major)) + for i in range(1, num_layers): + cell = rnn_cls(hidden_size, hidden_size, **kwargs) + self.append(RNN(cell, is_reverse, time_major)) + elif direction in bidirectional_list: + cell_fw = rnn_cls(input_size, hidden_size, **kwargs) + cell_bw = rnn_cls(input_size, hidden_size, **kwargs) + self.append(BiRNN(cell_fw, cell_bw, time_major)) + for i in range(1, num_layers): + cell_fw = rnn_cls(2 * hidden_size, hidden_size, **kwargs) + cell_bw = rnn_cls(2 * hidden_size, hidden_size, **kwargs) + self.append(BiRNN(cell_fw, cell_bw, time_major)) + else: + raise ValueError( + "direction should be forward or bidirect (or bidirectional), " + "received direction = {}".format(direction)) + + self.could_use_cudnn = True + self.could_use_cudnn &= len(self.parameters()) == num_layers * 4 * ( + 2 if direction in bidirectional_list else 1) + + # Expose params as RNN's attribute, which can make it compatible when + # replacing small ops composed rnn with cpp rnn kernel. + # Moreover, `jit.to_static` assumes params are added by current layer + # and wouldn't include sublayer's params in current layer, which also + # requires these params are added to current layer for `jit.save`. + param_names = [] + for layer in range(self.num_layers): + for direction in range(self.num_directions): + suffix = '_reverse' if direction == 1 else '' + param_names.extend(['weight_ih_l{}{}', 'weight_hh_l{}{}']) + if bias_ih_attr != False: param_names.append('bias_ih_l{}{}') + if bias_hh_attr != False: param_names.append('bias_hh_l{}{}') + param_names = [x.format(layer, suffix) for x in param_names] + for name, param in zip(param_names, self.parameters()): + setattr(self, name, param) + + self.flatten_parameters() + + def flatten_parameters(self): + """ + Resets parameter data pointer to address in continuous memory block for + cudnn usage. + """ + if self.could_use_cudnn: + # layer.parameters() is depth first and ordered + # for i in layer: for j in direct: w_ih, w_hh, b_ih, b_hh + # need to reorganize to cudnn param layout: + # all bias following all weights + params = self.parameters(include_sublayers=False) + shape = [np.prod(param.shape) for param in params] + self._all_weights = [None] * len(params) + for i, param in enumerate(params): + offset = 0 if i % 4 < 2 else (2 * self.num_layers * + self.num_directions) + layer_idx = i // 4 + self._all_weights[offset + layer_idx * 2 + i % 2] = param + # Wrap using a list to avoid registed into params and saving, maybe + # need a better way to handle this later. Use `create_parameter` to + # add both to main_program and startup_program for static-graph. + # Use Constant initializer to avoid make effect on random generator. + self._flat_weight = [ + self.create_parameter(shape=[np.sum(shape)], + dtype=params[0].dtype, + default_initializer=I.Constant(0.0)) + ] + # dropout state may also can be hided and avoid saving + # should dropout state be persistable for static-graph + self._dropout_state = self.create_variable( + dtype=core.VarDesc.VarType.UINT8) + if in_dynamic_mode(): + with paddle.no_grad(): + _legacy_C_ops.coalesce_tensor(self._all_weights, + self._all_weights, + self._flat_weight[0], + "copy_data", True, + "use_align", False, "dtype", + params[0].dtype) + return + # for static-graph, append coalesce_tensor into startup program + with program_guard(default_startup_program(), + default_startup_program()): + with paddle.no_grad(): + self._helper.append_op(type="coalesce_tensor", + inputs={"Input": self._all_weights}, + outputs={ + "Output": self._all_weights, + "FusedOutput": self._flat_weight + }, + attrs={ + "copy_data": True, + "use_align": False, + "dtype": params[0].dtype + }) + + def _cudnn_impl(self, inputs, initial_states, sequence_length): + if not self.time_major: + inputs = paddle.tensor.transpose(inputs, [1, 0, 2]) + + if in_dynamic_mode(): + _, _, out, state = _legacy_C_ops.rnn( + inputs, initial_states, self._all_weights, sequence_length, + self._dropout_state, self.state_components, 'dropout_prob', + self.dropout, 'is_bidirec', self.num_directions == 2, + 'input_size', self.input_size, 'hidden_size', self.hidden_size, + 'num_layers', self.num_layers, 'mode', self.mode, 'is_test', + not self.training) + else: + out = self._helper.create_variable_for_type_inference(inputs.dtype) + state = [ + self._helper.create_variable_for_type_inference(inputs.dtype) + for i in range(self.state_components) + ] + reserve = self._helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.UINT8, stop_gradient=True) + + inputs = { + 'Input': inputs, + 'WeightList': self._all_weights, + 'PreState': initial_states, + 'SequenceLength': sequence_length + } + attrs = { + 'dropout_prob': self.dropout, + 'is_bidirec': self.num_directions == 2, + 'input_size': self.input_size, + 'hidden_size': self.hidden_size, + 'num_layers': self.num_layers, + 'mode': self.mode, + 'is_test': not self.training + } + + outputs = { + 'Out': out, + 'State': state, + 'Reserve': reserve, + 'DropoutState': self._dropout_state, + } + + self._helper.append_op(type="rnn", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + out = paddle.tensor.transpose(out, + [1, 0, 2]) if not self.time_major else out + return out, tuple(state) if len(state) > 1 else state[0] + + def forward(self, inputs, initial_states=None, sequence_length=None): + batch_index = 1 if self.time_major else 0 + dtype = inputs.dtype + if initial_states is None: + state_shape = (self.num_layers * self.num_directions, -1, + self.hidden_size) + initial_states = tuple([ + paddle.fluid.layers.fill_constant_batch_size_like( + inputs, state_shape, dtype, 0, batch_index, 1) + for _ in range(self.state_components) + ]) + else: + initial_states = [initial_states] if isinstance( + initial_states, paddle.static.Variable) else initial_states + + if self.could_use_cudnn and (not paddle.device.is_compiled_with_rocm() + or sequence_length is None): + # Add CPU kernel and dispatch in backend later + return self._cudnn_impl(inputs, initial_states, sequence_length) + + states = split_states(initial_states, self.num_directions == 2, + self.state_components) + final_states = [] + + for i, rnn_layer in enumerate(self): + if i > 0: + inputs = F.dropout(inputs, + self.dropout, + training=self.training, + mode="upscale_in_train") + outputs, final_state = rnn_layer(inputs, states[i], sequence_length) + final_states.append(final_state) + inputs = outputs + + final_states = concat_states(final_states, self.num_directions == 2, + self.state_components) + return outputs, final_states + + def extra_repr(self): + main_str = '{input_size}, {hidden_size}' + if self.num_layers != 1: + main_str += ', num_layers={num_layers}' + if self.time_major != False: + main_str += ', time_major={time_major}' + if self.dropout != 0: + main_str += ', dropout={dropout}' + return main_str.format(**self.__dict__) + + +class SimpleRNN(RNNBase): + r""" + Multilayer Elman network(SimpleRNN). It takes input sequences and initial + states as inputs, and returns the output sequences and the final states. + + Each layer inside the SimpleRNN maps the input sequences and initial states + to the output sequences and final states in the following manner: at each + step, it takes step inputs(:math:`x_{t}`) and previous + states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`) + and new states(:math:`h_{t}`). + + .. math:: + + h_{t} & = act(W_{ih}x_{t} + b_{ih} + W_{hh}h_{t-1} + b_{hh}) + + y_{t} & = h_{t} + + where :math:`act` is for :attr:`activation`. + + Using key word arguments to construct is recommended. + + Parameters: + input_size (int): The input size of :math:`x` for the first layer's cell. + hidden_size (int): The hidden size of :math:`h` for each layer's cell. + num_layers (int, optional): Number of recurrent layers. Defaults to 1. + direction (str, optional): The direction of the network. It can be "forward" + or "bidirect"(or "bidirectional"). When "bidirect", the way to merge + outputs of forward and backward is concatenating. Defaults to "forward". + time_major (bool, optional): Whether the first dimension of the input + means the time steps. If time_major is True, the shape of Tensor is + [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size]. + Defaults to False. `time_steps` means the length of input sequence. + dropout (float, optional): The droput probability. Dropout is applied + to the input of each layer except for the first layer. The range of + dropout from 0 to 1. Defaults to 0. + activation (str, optional): The activation in each SimpleRNN cell. It can be + `tanh` or `relu`. Defaults to `tanh`. + weight_ih_attr (ParamAttr, optional): The parameter attribute for + `weight_ih` of each cell. Defaults to None. + weight_hh_attr (ParamAttr, optional): The parameter attribute for + `weight_hh` of each cell. Defaults to None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + `bias_ih` of each cells. Defaults to None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + `bias_hh` of each cells. Defaults to None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Inputs: + - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence. + - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used. + - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whose time step index are not less than the valid length are treated as paddings. + + Returns: + + - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence. + + - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1. + + Variables: + - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`. + - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`. + - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`. + - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`. + + Examples: + + .. code-block:: python + + import paddle + + rnn = paddle.nn.SimpleRNN(16, 32, 2) + + x = paddle.randn((4, 23, 16)) + prev_h = paddle.randn((2, 4, 32)) + y, h = rnn(x, prev_h) + + print(y.shape) + print(h.shape) + + #[4,23,32] + #[2,4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + num_layers=1, + direction="forward", + time_major=False, + dropout=0., + activation="tanh", + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + if activation == "tanh": + mode = "RNN_TANH" + elif activation == "relu": + mode = "RNN_RELU" + else: + raise ValueError("Unknown activation '{}'".format(activation)) + self.activation = activation + super(SimpleRNN, + self).__init__(mode, input_size, hidden_size, num_layers, + direction, time_major, dropout, weight_ih_attr, + weight_hh_attr, bias_ih_attr, bias_hh_attr) + + +class LSTM(RNNBase): + r""" + Multilayer LSTM. It takes a sequence and an initial state as inputs, and + returns the output sequences and the final states. + + Each layer inside the LSTM maps the input sequences and initial states + to the output sequences and final states in the following manner: at each + step, it takes step inputs(:math:`x_{t}`) and previous + states(:math:`h_{t-1}, c_{t-1}`) as inputs, and returns step + outputs(:math:`y_{t}`) and new states(:math:`h_{t}, c_{t}`). + + .. math:: + + i_{t} & = \sigma(W_{ii}x_{t} + b_{ii} + W_{hi}h_{t-1} + b_{hi}) + + f_{t} & = \sigma(W_{if}x_{t} + b_{if} + W_{hf}h_{t-1} + b_{hf}) + + o_{t} & = \sigma(W_{io}x_{t} + b_{io} + W_{ho}h_{t-1} + b_{ho}) + + \widetilde{c}_{t} & = \tanh (W_{ig}x_{t} + b_{ig} + W_{hg}h_{t-1} + b_{hg}) + + c_{t} & = f_{t} * c_{t-1} + i_{t} * \widetilde{c}_{t} + + h_{t} & = o_{t} * \tanh(c_{t}) + + y_{t} & = h_{t} + + where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise + multiplication operator. + + Using key word arguments to construct is recommended. + + Parameters: + input_size (int): The input size of :math:`x` for the first layer's cell. + hidden_size (int): The hidden size of :math:`h` for each layer's cell. + num_layers (int, optional): Number of recurrent layers. Defaults to 1. + direction (str, optional): The direction of the network. It can be "forward" + or "bidirect"(or "bidirectional"). When "bidirect", the way to merge + outputs of forward and backward is concatenating. Defaults to "forward". + time_major (bool, optional): Whether the first dimension of the input + means the time steps. If time_major is True, the shape of Tensor is + [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size]. + Defaults to False. `time_steps` means the length of input sequence. + dropout (float, optional): The droput probability. Dropout is applied + to the input of each layer except for the first layer. The range of + dropout from 0 to 1. Defaults to 0. + weight_ih_attr (ParamAttr, optional): The parameter attribute for + `weight_ih` of each cell. Default: None. + weight_hh_attr (ParamAttr, optional): The parameter attribute for + `weight_hh` of each cell. Default: None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + `bias_ih` of each cells. Default: None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + `bias_hh` of each cells. Default: None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Inputs: + - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence. + - **initial_states** (list|tuple, optional): the initial state, a list/tuple of (h, c), the shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used. + - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whos time step index are not less than the valid length are treated as paddings. + + Returns: + + - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, If `time_major` is False, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence. + + - **final_states** (tuple): the final state, a tuple of two tensors, h and c. The shape of each is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1. + + Variables: + - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`. + - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`. + - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`. + - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, swith shape `[hidden_size]`. + + Examples: + + .. code-block:: python + + import paddle + + rnn = paddle.nn.LSTM(16, 32, 2) + + x = paddle.randn((4, 23, 16)) + prev_h = paddle.randn((2, 4, 32)) + prev_c = paddle.randn((2, 4, 32)) + y, (h, c) = rnn(x, (prev_h, prev_c)) + + print(y.shape) + print(h.shape) + print(c.shape) + + #[4,23,32] + #[2,4,32] + #[2,4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + num_layers=1, + direction="forward", + time_major=False, + dropout=0., + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + super(LSTM, + self).__init__("LSTM", input_size, hidden_size, num_layers, + direction, time_major, dropout, weight_ih_attr, + weight_hh_attr, bias_ih_attr, bias_hh_attr) + + +class GRU(RNNBase): + r""" + Multilayer GRU. It takes input sequencse and initial states as inputs, and + returns the output sequences and the final states. + + Each layer inside the GRU maps the input sequences and initial states + to the output sequences and final states in the following manner: at each + step, it takes step inputs(:math:`x_{t}`) and previous + states(:math:`h_{t-1}`) as inputs, and returns step outputs(:math:`y_{t}`) + and new states(:math:`h_{t}`). + + .. math:: + + r_{t} & = \sigma(W_{ir}x_{t} + b_{ir} + W_{hr}h_{t-1} + b_{hr}) + + z_{t} & = \sigma(W_{iz}x_{t} + b_{iz} + W_{hz}h_{t-1} + b_{hz}) + + \widetilde{h}_{t} & = \tanh(W_{ic}x_{t} + b_{ic} + r_{t} * (W_{hc}h_{t-1} + b_{hc})) + + h_{t} & = z_{t} * h_{t-1} + (1 - z_{t}) * \widetilde{h}_{t} + + y_{t} & = h_{t} + + where :math:`\sigma` is the sigmoid fucntion, and * is the elemetwise + multiplication operator. + + Using key word arguments to construct is recommended. + + Parameters: + input_size (int): The input size of :math:`x` for the first layer's cell. + hidden_size (int): The hidden size of :math:`h` for each layer's cell. + num_layers (int, optional): Number of recurrent layers. Defaults to 1. + direction (str, optional): The direction of the network. It can be "forward" + or "bidirect"(or "bidirectional"). When "bidirect", the way to merge + outputs of forward and backward is concatenating. Defaults to "forward". + time_major (bool, optional): Whether the first dimension of the input + means the time steps. If time_major is True, the shape of Tensor is + [time_steps,batch_size,input_size], otherwise [batch_size, time_steps,input_size]. + Defaults to False. `time_steps` means the length of input sequence. + dropout (float, optional): The droput probability. Dropout is applied + to the input of each layer except for the first layer. The range of + dropout from 0 to 1. Defaults to 0. + weight_ih_attr (ParamAttr, optional): The parameter attribute for + `weight_ih` of each cell. Default: None. + weight_hh_attr (ParamAttr, optional): The parameter attribute for + `weight_hh` of each cell. Default: None. + bias_ih_attr (ParamAttr, optional): The parameter attribute for the + `bias_ih` of each cells. Default: None. + bias_hh_attr (ParamAttr, optional): The parameter attribute for the + `bias_hh` of each cells. Default: None. + name (str, optional): Name for the operation (optional, default is + None). For more information, please refer to :ref:`api_guide_Name`. + + Inputs: + - **inputs** (Tensor): the input sequence. If `time_major` is True, the shape is `[time_steps, batch_size, input_size]`, else, the shape is `[batch_size, time_steps, input_size]`. `time_steps` means the length of the input sequence. + - **initial_states** (Tensor, optional): the initial state. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. If initial_state is not given, zero initial states are used. Defaults to None. + - **sequence_length** (Tensor, optional): shape `[batch_size]`, dtype: int64 or int32. The valid lengths of input sequences. Defaults to None. If `sequence_length` is not None, the inputs are treated as padded sequences. In each input sequence, elements whos time step index are not less than the valid length are treated as paddings. + + Returns: + + - **outputs** (Tensor): the output sequence. If `time_major` is True, the shape is `[time_steps, batch_size, num_directions * hidden_size]`, else, the shape is `[batch_size, time_steps, num_directions * hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" else 1. `time_steps` means the length of the output sequence. + + - **final_states** (Tensor): final states. The shape is `[num_layers * num_directions, batch_size, hidden_size]`. Note that `num_directions` is 2 if direction is "bidirectional" (the index of forward states are 0, 2, 4, 6... and the index of backward states are 1, 3, 5, 7...), else 1. + + Variables: + - **weight_ih_l[k]**: the learnable input-hidden weights of the k-th layer. If `k = 0`, the shape is `[hidden_size, input_size]`. Otherwise, the shape is `[hidden_size, num_directions * hidden_size]`. + - **weight_hh_l[k]**: the learnable hidden-hidden weights of the k-th layer, with shape `[hidden_size, hidden_size]`. + - **bias_ih_l[k]**: the learnable input-hidden bias of the k-th layer, with shape `[hidden_size]`. + - **bias_hh_l[k]**: the learnable hidden-hidden bias of the k-th layer, with shape `[hidden_size]`. + + Examples: + + .. code-block:: python + + import paddle + + rnn = paddle.nn.GRU(16, 32, 2) + + x = paddle.randn((4, 23, 16)) + prev_h = paddle.randn((2, 4, 32)) + y, h = rnn(x, prev_h) + + print(y.shape) + print(h.shape) + + #[4,23,32] + #[2,4,32] + + """ + + def __init__(self, + input_size, + hidden_size, + num_layers=1, + direction="forward", + time_major=False, + dropout=0., + weight_ih_attr=None, + weight_hh_attr=None, + bias_ih_attr=None, + bias_hh_attr=None, + name=None): + super(GRU, + self).__init__("GRU", input_size, hidden_size, num_layers, + direction, time_major, dropout, weight_ih_attr, + weight_hh_attr, bias_ih_attr, bias_hh_attr) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..75f8bac75bc94a2dbd31b1c57e87aac0b3a91f54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/transformer.py @@ -0,0 +1,1402 @@ +# 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. + +# TODO: define the classes of Transformer neural network + +import copy +import collections +import numpy as np + +import paddle +from .common import Linear, Dropout +from .norm import LayerNorm +from .. import functional as F +from ... import tensor +from ...fluid import layers +from .. import Layer, LayerList +from ...framework import ParamAttr +from paddle.fluid.data_feeder import convert_dtype + +__all__ = [] + + +def _convert_param_attr_to_list(param_attr, n): + """ + If `param_attr` is a list or tuple, convert every element in it to a + ParamAttr instance. Otherwise, repeat `param_attr` `n` times to + construct a list, and rename every one by appending a increasing index + suffix to avoid having same names when `param_attr` contains a name. + + Parameters: + param_attr (list|tuple|ParamAttr): A list, tuple or something can be + converted to a ParamAttr instance by `ParamAttr._to_attr`. + n (int): The times to repeat to construct a list when `param_attr` + is not a list or tuple. + + Returns: + list: A list composed of each including cell's `param_attr`. + """ + if isinstance(param_attr, (list, tuple)): + assert len(param_attr) == n, ( + "length of param_attr should be %d when it is a list/tuple" % n) + param_attrs = [] + for attr in param_attr: + if isinstance(attr, bool): + if attr: + param_attrs.append(ParamAttr._to_attr(None)) + else: + param_attrs.append(False) + else: + param_attrs.append(ParamAttr._to_attr(attr)) + # param_attrs = [ParamAttr._to_attr(attr) for attr in param_attr] + elif isinstance(param_attr, bool): + param_attrs = [] + if param_attr: + param_attrs = [ParamAttr._to_attr(None) for i in range(n)] + else: + param_attrs = [False] * n + else: + param_attrs = [] + attr = ParamAttr._to_attr(param_attr) + for i in range(n): + attr_i = copy.deepcopy(attr) + if attr.name: + attr_i.name = attr_i.name + "_" + str(i) + param_attrs.append(attr_i) + return param_attrs + + +def _convert_attention_mask(attn_mask, dtype): + """ + Convert the attention mask to the target dtype we expect. + + Parameters: + attn_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + dtype (VarType): The target type of `attn_mask` we expect. + + Returns: + Tensor: A Tensor with shape same as input `attn_mask`, with data type `dtype`. + """ + if attn_mask is not None and attn_mask.dtype != dtype: + attn_mask_dtype = convert_dtype(attn_mask.dtype) + if attn_mask_dtype == 'bool' or 'int' in attn_mask_dtype: + attn_mask = (paddle.cast(attn_mask, dtype) - 1.0) * 1e9 + else: + attn_mask = paddle.cast(attn_mask, dtype) + return attn_mask + + +class MultiHeadAttention(Layer): + """ + Attention mapps queries and a set of key-value pairs to outputs, and + Multi-Head Attention performs multiple parallel attention to jointly attending + to information from different representation subspaces. + + Please refer to `Attention Is All You Need `_ + for more details. + + Parameters: + embed_dim (int): The expected feature size in the input and output. + num_heads (int): The number of heads in multi-head attention. + dropout (float, optional): The dropout probability used on attention + weights to drop some attention targets. 0 for no dropout. Default 0 + kdim (int, optional): The feature size in key. If None, assumed equal to + `embed_dim`. Default None. + vdim (int, optional): The feature size in value. If None, assumed equal to + `embed_dim`. Default None. + need_weights (bool, optional): Indicate whether to return the attention + weights. Default False. + weight_attr(ParamAttr, optional): To specify the weight parameter property. + Default: None, which means the default weight parameter property is used. + See usage for details in :code:`ParamAttr` . + bias_attr (ParamAttr|bool, optional): To specify the bias parameter property. + Default: None, which means the default bias parameter property is used. + If it is set to False, this layer will not have trainable bias parameter. + See usage for details in :code:`ParamAttr` . + + Examples: + + .. code-block:: python + + import paddle + + # encoder input: [batch_size, sequence_length, d_model] + query = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, num_heads, query_len, query_len] + attn_mask = paddle.rand((2, 2, 4, 4)) + multi_head_attn = paddle.nn.MultiHeadAttention(128, 2) + output = multi_head_attn(query, None, None, attn_mask=attn_mask) # [2, 4, 128] + """ + + Cache = collections.namedtuple("Cache", ["k", "v"]) + StaticCache = collections.namedtuple("StaticCache", ["k", "v"]) + + def __init__(self, + embed_dim, + num_heads, + dropout=0., + kdim=None, + vdim=None, + need_weights=False, + weight_attr=None, + bias_attr=None): + super(MultiHeadAttention, self).__init__() + + assert embed_dim > 0, ("Expected embed_dim to be greater than 0, " + "but received {}".format(embed_dim)) + assert num_heads > 0, ("Expected num_heads to be greater than 0, " + "but received {}".format(num_heads)) + + self.embed_dim = embed_dim + self.kdim = kdim if kdim is not None else embed_dim + self.vdim = vdim if vdim is not None else embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.need_weights = need_weights + + self.head_dim = embed_dim // num_heads + assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" + + self.q_proj = Linear(embed_dim, + embed_dim, + weight_attr, + bias_attr=bias_attr) + self.k_proj = Linear(self.kdim, + embed_dim, + weight_attr, + bias_attr=bias_attr) + self.v_proj = Linear(self.vdim, + embed_dim, + weight_attr, + bias_attr=bias_attr) + self.out_proj = Linear(embed_dim, + embed_dim, + weight_attr, + bias_attr=bias_attr) + + def _prepare_qkv(self, query, key, value, cache=None): + r""" + Prapares linear projected queries, keys and values for usage of subsequnt + multiple parallel attention. If `cache` is not None, using cached results + to reduce redundant calculations. + + Parameters: + query (Tensor): The queries for multi-head attention. It is a + tensor with shape `[batch_size, query_length, embed_dim]`. The + data type should be float32 or float64. + key (Tensor): The keys for multi-head attention. It is + a tensor with shape `[batch_size, key_length, kdim]`. The + data type should be float32 or float64. If None, use `query` as + `key`. + value (Tensor): The values for multi-head attention. It + is a tensor with shape `[batch_size, value_length, vdim]`. + The data type should be float32 or float64. If None, use `query` as + `value`. + cache (MultiHeadAttention.Cache|MultiHeadAttention.StaticCache, optional): + It is a namedtuple with `k` and `v` as fields, and stores tensors + shaped `[batch_size, num_heads, length, embed_dim]` which are results + of linear projection, reshape and transpose calculations in + MultiHeadAttention. If is an instance of `Cache`, `k` and `v` + fields reserve intermediate results of previous positions, which + mostly used for decoder self attention. If it is an instance of + `StaticCache`, `key` and `value` args would be ignored, `k` and + `v` fields would be used as calculated results on `key` and + `value`, which mostly used for decoder-encoder cross attention. + It is only used for inference and should be None for training. + Default None. + + Returns: + tuple: A tuple including linear projected keys and values. These two \ + tensors have shapes `[batch_size, n_head, sequence_length, d_key]` \ + and `[batch_size, n_head, sequence_length, d_value]` separately, \ + and their data types are same as inputs. + """ + q = self.q_proj(query) + q = tensor.reshape(x=q, shape=[0, 0, self.num_heads, self.head_dim]) + q = tensor.transpose(x=q, perm=[0, 2, 1, 3]) + + if isinstance(cache, self.StaticCache): + # for encoder-decoder attention in inference and has cached + k, v = cache.k, cache.v + else: + k, v = self.compute_kv(key, value) + + if isinstance(cache, self.Cache): + # for decoder self-attention in inference + k = tensor.concat([cache.k, k], axis=2) + v = tensor.concat([cache.v, v], axis=2) + cache = self.Cache(k, v) + + return (q, k, v) if cache is None else (q, k, v, cache) + + def compute_kv(self, key, value): + r""" + Applies linear projection on input keys and values, then splits heads + (reshape and transpose) to get keys and values from different representation + subspaces. The results are used as key-values pairs for subsequent multiple + parallel attention. + + It is part of calculations in multi-head attention, and is provided as + a method to pre-compute and prefetch these results, thus we can use them + to construct cache for inference. + + Parameters: + key (Tensor): The keys for multi-head attention. It is a tensor + with shape `[batch_size, sequence_length, kdim]`. The data type + should be float32 or float64. + value (Tensor): The values for multi-head attention. It is a tensor + with shape `[batch_size, sequence_length, vdim]`. The data type + should be float32 or float64. + + Returns: + tuple: A tuple including transformed keys and values. Their shapes \ + both are `[batch_size, num_heads, sequence_length, embed_dim // num_heads]`, \ + and their data types are same as inputs. + """ + k = self.k_proj(key) + v = self.v_proj(value) + k = tensor.reshape(x=k, shape=[0, 0, self.num_heads, self.head_dim]) + k = tensor.transpose(x=k, perm=[0, 2, 1, 3]) + v = tensor.reshape(x=v, shape=[0, 0, self.num_heads, self.head_dim]) + v = tensor.transpose(x=v, perm=[0, 2, 1, 3]) + return k, v + + def gen_cache(self, key, value=None, type=Cache): + """ + Generates cache for `forward` usage in inference accroding to arguments. + The generated cache is an instance of `MultiHeadAttention.Cache` or an + instance of `MultiHeadAttention.StaticCache`. + + `Cache` or `StaticCache` is namedtuple with `k` and `v` as fields, + and it stores tensors shaped `[batch_size, num_heads, length, embed_dim]` + which are results of linear projection, reshape and transpose calculations + in MultiHeadAttention. + + If the generated cache is an instance of `Cache`, `k` and `v` fields + reserve intermediate result tensors of previous positions, and the tensors + are incremental among decoding steps, which mostly are used for decoder + decoder self attention. + + If the generated cache is an instance of `StaticCache`, `k` and `v` fields + would be used as calculated result tensors on keys an values in `forward`, + and the tensors keep unchanged among decoding steps, which are mostly used + for decoder-encoder cross attention. + + The cache is generated as follows: + + 1. If `type` is `StaticCache`, apply `compute_kv(key, value)` and use the + results to create an instance of `StaticCache`. + + 2. If `type` is `Cache` and `value` is None, generate empty tensors shaped + `[batch_size, num_heads, 0, embed_dim // num_heads]` and use the results + to create an instance of `Cache`, where `batch_size` is from the first + dimension of `key`. + + 3. If `type` is `Cache` and `value` is not None, use `key`, `value` to create + an instance of `Cache`. + + Parameters: + key (Tensor): The keys for multi-head attention. It is + a tensor with shape `[batch_size, key_length, kdim]`. The + data type should be float32 or float64. If `value` is None, + it is only for batch size and data type reference. + value (Tensor, optional): The values for multi-head attention. It + is a tensor with shape `[batch_size, value_length, vdim]`. + The data type should be float32 or float64. If None, `key` is only + for batch size reference. Default None. + type (type): It should be `MultiHeadAttention.StaticCache` or + `MultiHeadAttention.Cache` to indicate the cache type to generate. + + Returns: + namedtuple: an instance of `Cache` or `StaticCache` accordingly. + """ + if type == MultiHeadAttention.StaticCache: # static_kv + k, v = self.compute_kv(key, value) + return self.StaticCache(k, v) + elif value is None: # incremental_state + k = layers.fill_constant_batch_size_like( + input=key, + shape=[-1, self.num_heads, 0, self.head_dim], + dtype=key.dtype, + value=0) + v = layers.fill_constant_batch_size_like( + input=key, + shape=[-1, self.num_heads, 0, self.head_dim], + dtype=key.dtype, + value=0) + return self.Cache(k, v) + else: + # incremental_state with initial value, mainly for usage like UniLM + return self.Cache(key, value) + + def forward(self, query, key=None, value=None, attn_mask=None, cache=None): + r""" + Applies multi-head attention to map queries and a set of key-value pairs + to outputs. + + Parameters: + query (Tensor): The queries for multi-head attention. It is a + tensor with shape `[batch_size, query_length, embed_dim]`. The + data type should be float32 or float64. + key (Tensor, optional): The keys for multi-head attention. It is + a tensor with shape `[batch_size, key_length, kdim]`. The + data type should be float32 or float64. If None, use `query` as + `key`. Default None. + value (Tensor, optional): The values for multi-head attention. It + is a tensor with shape `[batch_size, value_length, vdim]`. + The data type should be float32 or float64. If None, use `query` as + `value`. Default None. + attn_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (MultiHeadAttention.Cache|MultiHeadAttention.StaticCache, optional): + It is a namedtuple with `k` and `v` as fields, and stores tensors + shaped `[batch_size, num_heads, length, embed_dim]` which are results + of linear projection, reshape and transpose calculations in + MultiHeadAttention. If it is an instance of `Cache`, `k` and `v` + fields reserve intermediate results of previous positions, which + mostly used for decoder self attention. If it is an instance of + `StaticCache`, `key` and `value` args would be ignored, `k` and + `v` fields would be used as calculated results on `key` and + `value`, which mostly used for decoder-encoder cross attention. + It is only used for inference and should be None for training. + Default None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `query`, representing attention output. Or a tuple if \ + `need_weights` is True or `cache` is not None. If `need_weights` \ + is True, except for attention output, the tuple also includes \ + the attention weights tensor shaped `[batch_size, num_heads, query_length, key_length]`. \ + If `cache` is not None, the tuple then includes the new cache \ + having the same type as `cache`, and if it is `StaticCache`, it \ + is same as the input `cache`, if it is `Cache`, the new cache \ + reserves tensors concatanating raw tensors with intermediate \ + results of current query. + """ + key = query if key is None else key + value = query if value is None else value + # compute q ,k ,v + if cache is None: + q, k, v = self._prepare_qkv(query, key, value, cache) + else: + q, k, v, cache = self._prepare_qkv(query, key, value, cache) + + # scale dot product attention + product = paddle.matmul(x=q * (self.head_dim**-0.5), + y=k, + transpose_y=True) + if attn_mask is not None: + # Support bool or int mask + attn_mask = _convert_attention_mask(attn_mask, product.dtype) + product = product + attn_mask + weights = F.softmax(product) + if self.dropout: + weights = F.dropout(weights, + self.dropout, + training=self.training, + mode="upscale_in_train") + + out = tensor.matmul(weights, v) + + # combine heads + out = tensor.transpose(out, perm=[0, 2, 1, 3]) + out = tensor.reshape(x=out, shape=[0, 0, out.shape[2] * out.shape[3]]) + + # project to output + out = self.out_proj(out) + + outs = [out] + if self.need_weights: + outs.append(weights) + if cache is not None: + outs.append(cache) + return out if len(outs) == 1 else tuple(outs) + + +class TransformerEncoderLayer(Layer): + """ + TransformerEncoderLayer is composed of two sub-layers which are self (multi-head) + attention and feedforward network. Before and after each sub-layer, pre-process + and post-precess would be applied on the input and output accordingly. If + `normalize_before` is True, pre-process is layer normalization and post-precess + includes dropout, residual connection. Otherwise, no pre-process and post-precess + includes dropout, residual connection, layer normalization. + + Parameters: + d_model (int): The expected feature size in the input and output. + nhead (int): The number of heads in multi-head attention(MHA). + dim_feedforward (int): The hidden layer size in the feedforward network(FFN). + dropout (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.1 + activation (str, optional): The activation function in the feedforward + network. Default relu. + attn_dropout (float, optional): The dropout probability used + in MHA to drop some attention target. If None, use the value of + `dropout`. Default None + act_dropout (float, optional): The dropout probability used after FFN + activition. If None, use the value of `dropout`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default False + weight_attr(ParamAttr|list|tuple, optional): To specify the weight parameter property. + If it is a list/tuple, `weight_attr[0]` would be used as `weight_attr` for + MHA, and `weight_attr[1]` would be used as `weight_attr` for linear in FFN. + Otherwise, MHA and FFN both use it as `weight_attr` to create parameters. + Default: None, which means the default weight parameter property is used. + See usage for details in :code:`ParamAttr` . + bias_attr (ParamAttr|list|tuple|bool, optional): To specify the bias parameter property. + If it is a list/tuple, `bias_attr[0]` would be used as `bias_attr` for + MHA, and `bias_attr[1]` would be used as `bias_attr` for linear in FFN. + Otherwise, MHA and FFN both use it as `bias_attr` to create parameters. + The `False` value means the corresponding layer would not have trainable + bias parameter. See usage for details in :code:`ParamAttr` . Default: None, + which means the default bias parameter property is used. + + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import TransformerEncoderLayer + + # encoder input: [batch_size, src_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, n_head, src_len, src_len] + attn_mask = paddle.rand((2, 2, 4, 4)) + encoder_layer = TransformerEncoderLayer(128, 2, 512) + enc_output = encoder_layer(enc_input, attn_mask) # [2, 4, 128] + """ + + def __init__(self, + d_model, + nhead, + dim_feedforward, + dropout=0.1, + activation="relu", + attn_dropout=None, + act_dropout=None, + normalize_before=False, + weight_attr=None, + bias_attr=None): + self._config = locals() + self._config.pop("self") + self._config.pop("__class__", None) # py3 + + super(TransformerEncoderLayer, self).__init__() + + assert d_model > 0, ("Expected d_model to be greater than 0, " + "but received {}".format(d_model)) + assert nhead > 0, ("Expected nhead to be greater than 0, " + "but received {}".format(nhead)) + assert dim_feedforward > 0, ( + "Expected dim_feedforward to be greater than 0, " + "but received {}".format(dim_feedforward)) + + attn_dropout = dropout if attn_dropout is None else attn_dropout + act_dropout = dropout if act_dropout is None else act_dropout + self.normalize_before = normalize_before + + weight_attrs = _convert_param_attr_to_list(weight_attr, 2) + bias_attrs = _convert_param_attr_to_list(bias_attr, 2) + + self.self_attn = MultiHeadAttention(d_model, + nhead, + dropout=attn_dropout, + weight_attr=weight_attrs[0], + bias_attr=bias_attrs[0]) + self.linear1 = Linear(d_model, + dim_feedforward, + weight_attrs[1], + bias_attr=bias_attrs[1]) + self.dropout = Dropout(act_dropout, mode="upscale_in_train") + self.linear2 = Linear(dim_feedforward, + d_model, + weight_attrs[1], + bias_attr=bias_attrs[1]) + self.norm1 = LayerNorm(d_model) + self.norm2 = LayerNorm(d_model) + self.dropout1 = Dropout(dropout, mode="upscale_in_train") + self.dropout2 = Dropout(dropout, mode="upscale_in_train") + self.activation = getattr(F, activation) + + def forward(self, src, src_mask=None, cache=None): + r""" + Applies a Transformer encoder layer on the input. + + Parameters: + src (Tensor): The input of Transformer encoder layer. It is + a tensor with shape `[batch_size, sequence_length, d_model]`. + The data type should be float32 or float64. + src_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (Tensor, optional): It is an instance of `MultiHeadAttention.Cache`. + See `TransformerEncoderLayer.gen_cache` for more details. It is + only used for inference and should be None for training. Default + None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `enc_input`, representing the output of Transformer encoder \ + layer. Or a tuple if `cache` is not None, except for encoder \ + layer output, the tuple includes the new cache which is same \ + as input `cache` argument but `incremental_cache` has an \ + incremental length. See `MultiHeadAttention.gen_cache` and \ + `MultiHeadAttention.forward` for more details. + """ + src_mask = _convert_attention_mask(src_mask, src.dtype) + + residual = src + if self.normalize_before: + src = self.norm1(src) + # Add cache for encoder for the usage like UniLM + if cache is None: + src = self.self_attn(src, src, src, src_mask) + else: + src, incremental_cache = self.self_attn(src, src, src, src_mask, + cache) + + src = residual + self.dropout1(src) + if not self.normalize_before: + src = self.norm1(src) + + residual = src + if self.normalize_before: + src = self.norm2(src) + src = self.linear2(self.dropout(self.activation(self.linear1(src)))) + src = residual + self.dropout2(src) + if not self.normalize_before: + src = self.norm2(src) + return src if cache is None else (src, incremental_cache) + + def gen_cache(self, src): + r""" + Generates cache for `forward` usage. The generated cache is an + instance of `MultiHeadAttention.Cache`. + + Parameters: + src (Tensor): The input of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data + type should be float32 or float64. + + Returns: + incremental_cache: It is an instance of `MultiHeadAttention.Cache` \ + produced by `self_attn.gen_cache`, it reserves two tensors + shaped `[batch_size, nhead, 0, d_model // nhead]`. See \ + `MultiHeadAttention.gen_cache` and `MultiHeadAttention.forward` \ + for more details. + """ + incremental_cache = self.self_attn.gen_cache(src, + type=self.self_attn.Cache) + return incremental_cache + + +class TransformerEncoder(Layer): + """ + TransformerEncoder is a stack of N encoder layers. + + Parameters: + encoder_layer (Layer): an instance of the `TransformerEncoderLayer`. It + would be used as the first layer, and the other layers would be created + according to the configurations of it. + num_layers (int): The number of encoder layers to be stacked. + norm (LayerNorm, optional): the layer normalization component. If provided, + apply layer normalization on the output of last encoder layer. + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import TransformerEncoderLayer, TransformerEncoder + + # encoder input: [batch_size, src_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # self attention mask: [batch_size, n_head, src_len, src_len] + attn_mask = paddle.rand((2, 2, 4, 4)) + encoder_layer = TransformerEncoderLayer(128, 2, 512) + encoder = TransformerEncoder(encoder_layer, 2) + enc_output = encoder(enc_input, attn_mask) # [2, 4, 128] + """ + + def __init__(self, encoder_layer, num_layers, norm=None): + super(TransformerEncoder, self).__init__() + self.layers = LayerList([ + (encoder_layer if i == 0 else type(encoder_layer)( + **encoder_layer._config)) for i in range(num_layers) + ]) + self.num_layers = num_layers + self.norm = norm + + def forward(self, src, src_mask=None, cache=None): + r""" + Applies a stack of N Transformer encoder layers on inputs. If `norm` is + provided, also applies layer normalization on the output of last encoder + layer. + + Parameters: + src (Tensor): The input of Transformer encoder. It is a tensor + with shape `[batch_size, sequence_length, d_model]`. The data + type should be float32 or float64. + src_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (list, optional): It is a list, and each element in the list + is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. + See `TransformerEncoder.gen_cache` for more details. It is only + used for inference and should be None for training. Default None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `src`, representing the output of Transformer encoder. \ + Or a tuple if `cache` is not None, except for encoder output, \ + the tuple includes the new cache which is same as input `cache` \ + argument but `incremental_cache` in it has an incremental length. \ + See `MultiHeadAttention.gen_cache` and `MultiHeadAttention.forward` \ + for more details. + """ + src_mask = _convert_attention_mask(src_mask, src.dtype) + + output = src + new_caches = [] + for i, mod in enumerate(self.layers): + if cache is None: + output = mod(output, src_mask=src_mask) + else: + output, new_cache = mod(output, + src_mask=src_mask, + cache=cache[i]) + new_caches.append(new_cache) + + if self.norm is not None: + output = self.norm(output) + + return output if cache is None else (output, new_caches) + + def gen_cache(self, src): + r""" + Generates cache for `forward` usage. The generated cache is a list, and + each element in it is `incremental_cache` produced by + `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` + for more details. + + Parameters: + src (Tensor): The input of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + + Returns: + list: It is a list, and each element in the list is `incremental_cache` + produced by `TransformerEncoderLayer.gen_cache`. See + `TransformerEncoderLayer.gen_cache` for more details. + """ + cache = [layer.gen_cache(src) for layer in self.layers] + return cache + + +class TransformerDecoderLayer(Layer): + """ + TransformerDecoderLayer is composed of three sub-layers which are decoder + self (multi-head) attention, decoder-encoder cross attention and feedforward + network. Before and after each sub-layer, pre-process and post-precess would + be applied on the input and output accordingly. If `normalize_before` is True, + pre-process is layer normalization and post-precess includes dropout, residual + connection. Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. + + Parameters: + d_model (int): The expected feature size in the input and output. + nhead (int): The number of heads in multi-head attention(MHA). + dim_feedforward (int): The hidden layer size in the feedforward network(FFN). + dropout (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.1 + activation (str, optional): The activation function in the feedforward + network. Default relu. + attn_dropout (float, optional): The dropout probability used + in MHA to drop some attention target. If None, use the value of + `dropout`. Default None + act_dropout (float, optional): The dropout probability used after FFN + activition. If None, use the value of `dropout`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default False + weight_attr(ParamAttr|list|tuple, optional): To specify the weight parameter property. + If it is a list/tuple, `weight_attr[0]` would be used as `weight_attr` for + self attention, `weight_attr[1]` would be used as `weight_attr` for + cross attention, and `weight_attr[2]` would be used as `weight_attr` + for linear in FFN. Otherwise, the three sub-layers all uses it as + `weight_attr` to create parameters. Default: None, which means the + default weight parameter property is used. See usage for details + in :ref:`api_paddle_fluid_param_attr_ParamAttr` . + bias_attr (ParamAttr|list|tuple|bool, optional): To specify the bias parameter property. + If it is a list/tuple, `bias_attr[0]` would be used as `bias_attr` for + self attention, `bias_attr[1]` would be used as `bias_attr` for + cross attention, and `bias_attr[2]` would be used as `bias_attr` + for linear in FFN. Otherwise, the three sub-layers all uses it as + `bias_attr` to create parameters. The `False` value means the + corresponding layer would not have trainable bias parameter. See + usage for details in :code:`ParamAttr` . Default: None,which means + the default bias parameter property is used. + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import TransformerDecoderLayer + + # decoder input: [batch_size, tgt_len, d_model] + dec_input = paddle.rand((2, 4, 128)) + # encoder output: [batch_size, src_len, d_model] + enc_output = paddle.rand((2, 6, 128)) + # self attention mask: [batch_size, n_head, tgt_len, tgt_len] + self_attn_mask = paddle.rand((2, 2, 4, 4)) + # cross attention mask: [batch_size, n_head, tgt_len, src_len] + cross_attn_mask = paddle.rand((2, 2, 4, 6)) + decoder_layer = TransformerDecoderLayer(128, 2, 512) + output = decoder_layer(dec_input, + enc_output, + self_attn_mask, + cross_attn_mask) # [2, 4, 128] + """ + + def __init__(self, + d_model, + nhead, + dim_feedforward, + dropout=0.1, + activation="relu", + attn_dropout=None, + act_dropout=None, + normalize_before=False, + weight_attr=None, + bias_attr=None): + self._config = locals() + self._config.pop("self") + self._config.pop("__class__", None) # py3 + + super(TransformerDecoderLayer, self).__init__() + + assert d_model > 0, ("Expected d_model to be greater than 0, " + "but received {}".format(d_model)) + assert nhead > 0, ("Expected nhead to be greater than 0, " + "but received {}".format(nhead)) + assert dim_feedforward > 0, ( + "Expected dim_feedforward to be greater than 0, " + "but received {}".format(dim_feedforward)) + + attn_dropout = dropout if attn_dropout is None else attn_dropout + act_dropout = dropout if act_dropout is None else act_dropout + self.normalize_before = normalize_before + + weight_attrs = _convert_param_attr_to_list(weight_attr, 3) + bias_attrs = _convert_param_attr_to_list(bias_attr, 3) + + self.self_attn = MultiHeadAttention(d_model, + nhead, + dropout=attn_dropout, + weight_attr=weight_attrs[0], + bias_attr=bias_attrs[0]) + self.cross_attn = MultiHeadAttention(d_model, + nhead, + dropout=attn_dropout, + weight_attr=weight_attrs[1], + bias_attr=bias_attrs[1]) + self.linear1 = Linear(d_model, + dim_feedforward, + weight_attrs[2], + bias_attr=bias_attrs[2]) + self.dropout = Dropout(act_dropout, mode="upscale_in_train") + self.linear2 = Linear(dim_feedforward, + d_model, + weight_attrs[2], + bias_attr=bias_attrs[2]) + self.norm1 = LayerNorm(d_model) + self.norm2 = LayerNorm(d_model) + self.norm3 = LayerNorm(d_model) + self.dropout1 = Dropout(dropout, mode="upscale_in_train") + self.dropout2 = Dropout(dropout, mode="upscale_in_train") + self.dropout3 = Dropout(dropout, mode="upscale_in_train") + self.activation = getattr(F, activation) + + def forward(self, tgt, memory, tgt_mask=None, memory_mask=None, cache=None): + r""" + Applies a Transformer decoder layer on the input. + + Parameters: + tgt (Tensor): The input of Transformer decoder layer. It is a tensor + with shape `[batch_size, target_length, d_model]`. The data type + should be float32 or float64. + memory (Tensor): The output of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + tgt_mask (Tensor, optional): A tensor used in self attention + to prevents attention to some unwanted positions, usually the + the subsequent positions. It is a tensor with shape broadcasted + to `[batch_size, n_head, target_length, target_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + memory_mask (Tensor, optional): A tensor used in decoder-encoder + cross attention to prevents attention to some unwanted positions, + usually the paddings. It is a tensor with shape broadcasted to + `[batch_size, n_head, target_length, source_length]`. When the + data type is bool, the unwanted positions have `False` values + and the others have `True` values. When the data type is int, + the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (tuple, optional): It is a tuple( :code:`(incremental_cache, static_cache)` ), + `incremental_cache` is an instance of `MultiHeadAttention.Cache`, + `static_cache` is an instance of `MultiHeadAttention.StaticCache. + See `TransformerDecoderLayer.gen_cache` for more details. It is + only used for inference and should be None for training. Default + None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `tgt`, representing the output of Transformer decoder layer. \ + Or a tuple if `cache` is not None, except for decoder layer output, \ + the tuple includes the new cache which is same as input `cache` \ + argument but `incremental_cache` in it has an incremental length. \ + See `MultiHeadAttention.gen_cache` and `MultiHeadAttention.forward` \ + for more details. + """ + tgt_mask = _convert_attention_mask(tgt_mask, tgt.dtype) + memory_mask = _convert_attention_mask(memory_mask, memory.dtype) + + residual = tgt + if self.normalize_before: + tgt = self.norm1(tgt) + if cache is None: + tgt = self.self_attn(tgt, tgt, tgt, tgt_mask, None) + else: + tgt, incremental_cache = self.self_attn(tgt, tgt, tgt, tgt_mask, + cache[0]) + tgt = residual + self.dropout1(tgt) + if not self.normalize_before: + tgt = self.norm1(tgt) + + residual = tgt + if self.normalize_before: + tgt = self.norm2(tgt) + if cache is None: + tgt = self.cross_attn(tgt, memory, memory, memory_mask, None) + else: + tgt, static_cache = self.cross_attn(tgt, memory, memory, + memory_mask, cache[1]) + tgt = residual + self.dropout2(tgt) + if not self.normalize_before: + tgt = self.norm2(tgt) + + residual = tgt + if self.normalize_before: + tgt = self.norm3(tgt) + tgt = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) + tgt = residual + self.dropout3(tgt) + if not self.normalize_before: + tgt = self.norm3(tgt) + return tgt if cache is None else (tgt, (incremental_cache, + static_cache)) + + def gen_cache(self, memory): + r""" + Generates cache for `forward` usage. The generated cache is a tuple + composed of an instance of `MultiHeadAttention.Cache` and an instance + of `MultiHeadAttention.StaticCache`. + + Parameters: + memory (Tensor): The output of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + + Returns: + tuple: It is a tuple( :code:`(incremental_cache, static_cache)` ). \ + `incremental_cache` is an instance of `MultiHeadAttention.Cache` \ + produced by `self_attn.gen_cache(memory, MultiHeadAttention.Cache)`, \ + it reserves two tensors shaped `[batch_size, nhead, 0, d_model // nhead]`. \ + `static_cache` is an instance of `MultiHeadAttention.StaticCache` \ + produced by `cross_attn.gen_cache(memory, MultiHeadAttention.StaticCache)`, \ + it reserves two tensors shaped `[batch_size, nhead, source_length, d_model // nhead]`. + See `MultiHeadAttention.gen_cache` and `MultiHeadAttention.forward` \ + for more details. + """ + incremental_cache = self.self_attn.gen_cache(memory, + type=self.self_attn.Cache) + static_cache = self.cross_attn.gen_cache( + memory, memory, type=self.cross_attn.StaticCache) + return incremental_cache, static_cache + + +class TransformerDecoder(Layer): + """ + TransformerDecoder is a stack of N decoder layers. + + Parameters: + decoder_layer (Layer): an instance of the `TransformerDecoderLayer`. It + would be used as the first layer, and the other layers would be created + according to the configurations of it. + num_layers (int): The number of decoder layers to be stacked. + norm (LayerNorm, optional): the layer normalization component. If provided, + apply layer normalization on the output of last encoder layer. + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import TransformerDecoderLayer, TransformerDecoder + + # decoder input: [batch_size, tgt_len, d_model] + dec_input = paddle.rand((2, 4, 128)) + # encoder output: [batch_size, src_len, d_model] + enc_output = paddle.rand((2, 6, 128)) + # self attention mask: [batch_size, n_head, tgt_len, tgt_len] + self_attn_mask = paddle.rand((2, 2, 4, 4)) + # cross attention mask: [batch_size, n_head, tgt_len, src_len] + cross_attn_mask = paddle.rand((2, 2, 4, 6)) + decoder_layer = TransformerDecoderLayer(128, 2, 512) + decoder = TransformerDecoder(decoder_layer, 2) + output = decoder(dec_input, + enc_output, + self_attn_mask, + cross_attn_mask) # [2, 4, 128] + """ + + def __init__(self, decoder_layer, num_layers, norm=None): + super(TransformerDecoder, self).__init__() + self.layers = LayerList([ + (decoder_layer if i == 0 else type(decoder_layer)( + **decoder_layer._config)) for i in range(num_layers) + ]) + self.num_layers = num_layers + self.norm = norm + + def forward(self, tgt, memory, tgt_mask=None, memory_mask=None, cache=None): + r""" + Applies a stack of N Transformer decoder layers on inputs. If `norm` is + provided, also applies layer normalization on the output of last decoder + layer. + + Parameters: + tgt (Tensor): The input of Transformer decoder. It is a tensor + with shape `[batch_size, target_length, d_model]`. The data type + should be float32 or float64. + memory (Tensor): The output of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + tgt_mask (Tensor, optional): A tensor used in self attention + to prevents attention to some unwanted positions, usually the + the subsequent positions. It is a tensor with shape broadcasted + to `[batch_size, n_head, target_length, target_length]`. When + the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + memory_mask (Tensor, optional): A tensor used in decoder-encoder + cross attention to prevents attention to some unwanted positions, + usually the paddings. It is a tensor with shape broadcasted to + `[batch_size, n_head, target_length, source_length]`. When the + data type is bool, the unwanted positions have `False` values + and the others have `True` values. When the data type is int, + the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + cache (list, optional): It is a list, and each element in the list + is a tuple( :code:`(incremental_cache, static_cache)` ). See + `TransformerDecoder.gen_cache` for more details. It is only + used for inference and should be None for training. Default None. + + Returns: + Tensor|tuple: It is a tensor that has the same shape and data type \ + as `tgt`, representing the output of Transformer decoder. \ + Or a tuple if `cache` is not None, except for decoder output, \ + the tuple includes the new cache which is same as input `cache` \ + argument but `incremental_cache` in it has an incremental length. \ + See `MultiHeadAttention.gen_cache` and `MultiHeadAttention.forward` \ + for more details. + """ + tgt_mask = _convert_attention_mask(tgt_mask, tgt.dtype) + memory_mask = _convert_attention_mask(memory_mask, memory.dtype) + + output = tgt + new_caches = [] + for i, mod in enumerate(self.layers): + if cache is None: + output = mod(output, + memory, + tgt_mask=tgt_mask, + memory_mask=memory_mask, + cache=None) + else: + output, new_cache = mod(output, + memory, + tgt_mask=tgt_mask, + memory_mask=memory_mask, + cache=cache[i]) + new_caches.append(new_cache) + + if self.norm is not None: + output = self.norm(output) + + return output if cache is None else (output, new_caches) + + def gen_cache(self, memory, do_zip=False): + r""" + Generates cache for `forward` usage. The generated cache is a list, and + each element in it is a tuple( :code:`(incremental_cache, static_cache)` ) + produced by `TransformerDecoderLayer.gen_cache`. See `TransformerDecoderLayer.gen_cache` + for more details. If `do_zip` is True, apply `zip` on these tuples to get + a list with two elements. + + + Parameters: + memory (Tensor): The output of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + do_zip (bool, optional): Indicate whether to apply `zip` on the tuples. + If True, return a list with two elements. Default False + + Returns: + list: It is a list, and each element in the list is a tuple produced \ + by `TransformerDecoderLayer.gen_cache(memory)`. See `TransformerDecoderLayer.gen_cache` \ + for more details. If `do_zip` is True, apply `zip` on these tuples \ + and return a list with two elements. + """ + cache = [layer.gen_cache(memory) for layer in self.layers] + if do_zip: + cache = list(zip(*cache)) + return cache + + +class Transformer(Layer): + """ + A Transformer model composed of an instance of `TransformerEncoder` and an + instance of `TransformerDecoder`. While the embedding layer and output layer + are not included. + + Please refer to `Attention is all you need `_ , + and see `TransformerEncoder` and `TransformerDecoder` for more details. + + Users can configurate the model architecture with corresponding parameters. + Note the usage of `normalize_before` representing where to apply layer + normalization (in pre-process or post-precess of multi-head attention or FFN), + and some transformer like models are different on this, such as + `BERT `_ and `GPT2 `_ . + The default architecture here places layer normalization in post-process and + applies another layer normalization on the output of last encoder/decoder layer. + + Parameters: + d_model (int, optional): The expected feature size in the encoder/decoder input + and output. Default 512 + nhead (int, optional): The number of heads in multi-head attention(MHA). Default 8 + num_encoder_layers (int, optional): The number of layers in encoder. Default 6 + num_decoder_layers (int, optional): The number of layers in decoder. Default 6 + dim_feedforward (int, optional): The hidden layer size in the feedforward network(FFN). Default 2048 + dropout (float, optional): The dropout probability used in pre-process + and post-precess of MHA and FFN sub-layer. Default 0.1 + activation (str, optional): The activation function in the feedforward + network. Default relu. + attn_dropout (float, optional): The dropout probability used + in MHA to drop some attention target. If None, use the value of + `dropout`. Default None + act_dropout (float, optional): The dropout probability used after FFN + activition. If None, use the value of `dropout`. Default None + normalize_before (bool, optional): Indicate whether to put layer normalization + into preprocessing of MHA and FFN sub-layers. If True, pre-process is layer + normalization and post-precess includes dropout, residual connection. + Otherwise, no pre-process and post-precess includes dropout, residual + connection, layer normalization. Default False + weight_attr(ParamAttr|list|tuple, optional): To specify the weight parameter property. + If it is a list/tuple, the length of `weight_attr` could be 1, 2 or 3. If it is 3, + `weight_attr[0]` would be used as `weight_attr` for self attention, `weight_attr[1]` + would be used as `weight_attr` for cross attention of `TransformerDecoder`, + and `weight_attr[2]` would be used as `weight_attr` for linear in FFN. + If it is 2, `weight_attr[0]` would be used as `weight_attr` both for self attention + and cross attntion and `weight_attr[1]` would be used as `weight_attr` for + linear in FFN. If it is 1, `weight_attr[0]` would be used as `weight_attr` + for self attention, cross attention and linear in FFN. Otherwise, + the three sub-layers all uses it as `weight_attr` to create parameters. + Default: None, which means the default weight parameter property is used. + See usage for details + in :code:`ParamAttr` . + bias_attr (ParamAttr|list|tuple|bool, optional): To specify the bias parameter property. + If it is a list/tuple, the length of `bias_attr` could be 1, 2 or 3. If it is 3, + `bias_attr[0]` would be used as `bias_attr` for self attention, `bias_attr[1]` + would be used as `bias_attr` for cross attention of `TransformerDecoder`, + and `bias_attr[2]` would be used as `bias_attr` for linear in FFN. + If it is 2, `bias_attr[0]` would be used as `bias_attr` both for self attention + and cross attntion and `bias_attr[1]` would be used as `bias_attr` for + linear in FFN. If it is 1, `bias_attr[0]` would be used as `bias_attr` + for self attention, cross attention and linear in FFN. Otherwise, + the three sub-layers all uses it as `bias_attr` to create parameters. + The `False` value means the corresponding layer would not have trainable + bias parameter. See usage for details in :code:`ParamAttr` . + Default: None,which means the default bias parameter property is used. + custom_encoder (Layer, optional): If custom encoder is provided, use it as the encoder. + Default None + custom_decoder (Layer, optional): If custom decoder is provided, use it as the decoder. + Default None + + Examples: + + .. code-block:: python + + import paddle + from paddle.nn import Transformer + + # src: [batch_size, tgt_len, d_model] + enc_input = paddle.rand((2, 4, 128)) + # tgt: [batch_size, src_len, d_model] + dec_input = paddle.rand((2, 6, 128)) + # src_mask: [batch_size, n_head, src_len, src_len] + enc_self_attn_mask = paddle.rand((2, 2, 4, 4)) + # tgt_mask: [batch_size, n_head, tgt_len, tgt_len] + dec_self_attn_mask = paddle.rand((2, 2, 6, 6)) + # memory_mask: [batch_size, n_head, tgt_len, src_len] + cross_attn_mask = paddle.rand((2, 2, 6, 4)) + transformer = Transformer(128, 2, 4, 4, 512) + output = transformer(enc_input, + dec_input, + enc_self_attn_mask, + dec_self_attn_mask, + cross_attn_mask) # [2, 6, 128] + """ + + def __init__(self, + d_model=512, + nhead=8, + num_encoder_layers=6, + num_decoder_layers=6, + dim_feedforward=2048, + dropout=0.1, + activation="relu", + attn_dropout=None, + act_dropout=None, + normalize_before=False, + weight_attr=None, + bias_attr=None, + custom_encoder=None, + custom_decoder=None): + super(Transformer, self).__init__() + + assert d_model > 0, ("Expected d_model to be greater than 0, " + "but received {}".format(d_model)) + assert nhead > 0, ("Expected nhead to be greater than 0, " + "but received {}".format(nhead)) + assert dim_feedforward > 0, ( + "Expected dim_feedforward to be greater than 0, " + "but received {}".format(dim_feedforward)) + + if isinstance(bias_attr, (list, tuple)): + if len(bias_attr) == 1: + encoder_bias_attr = [bias_attr[0]] * 2 + decoder_bias_attr = [bias_attr[0]] * 3 + elif len(bias_attr) == 2: + encoder_bias_attr = bias_attr + decoder_bias_attr = [bias_attr[0], bias_attr[0], bias_attr[-1]] + elif len(bias_attr) == 3: + encoder_bias_attr = [bias_attr[0], bias_attr[-1]] + decoder_bias_attr = bias_attr + else: + assert False, ( + "length of bias_attr should be 1 or 2 or 3 when it is a list/tuple" + ) + else: + encoder_bias_attr = bias_attr + decoder_bias_attr = bias_attr + + if isinstance(weight_attr, (list, tuple)): + if len(weight_attr) == 1: + encoder_weight_attr = [weight_attr[0]] * 2 + decoder_weight_attr = [weight_attr[0]] * 3 + elif len(weight_attr) == 2: + encoder_weight_attr = weight_attr + decoder_weight_attr = [ + weight_attr[0], weight_attr[0], weight_attr[-1] + ] + elif len(weight_attr) == 3: + encoder_weight_attr = [weight_attr[0], weight_attr[-1]] + decoder_weight_attr = weight_attr + else: + assert False, ( + "length of weight_attr should be 1 or 2 or 3 when it is a list/tuple" + ) + else: + encoder_weight_attr = weight_attr + decoder_weight_attr = weight_attr + + if custom_encoder is not None: + self.encoder = custom_encoder + else: + encoder_layer = TransformerEncoderLayer( + d_model, nhead, dim_feedforward, dropout, activation, + attn_dropout, act_dropout, normalize_before, + encoder_weight_attr, encoder_bias_attr) + encoder_norm = LayerNorm(d_model) + self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, + encoder_norm) + + if custom_decoder is not None: + self.decoder = custom_decoder + else: + decoder_layer = TransformerDecoderLayer( + d_model, nhead, dim_feedforward, dropout, activation, + attn_dropout, act_dropout, normalize_before, + decoder_weight_attr, decoder_bias_attr) + decoder_norm = LayerNorm(d_model) + self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, + decoder_norm) + + self.d_model = d_model + self.nhead = nhead + + def forward(self, src, tgt, src_mask=None, tgt_mask=None, memory_mask=None): + r""" + Applies a Transformer model on the inputs. + + Parameters: + src (Tensor): The input of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + tgt (Tensor): The input of Transformer decoder. It is a tensor + with shape `[batch_size, target_length, d_model]`. The data type + should be float32 or float64. + memory (Tensor): The output of Transformer encoder. It is a tensor + with shape `[batch_size, source_length, d_model]`. The data type + should be float32 or float64. + src_mask (Tensor, optional): A tensor used in multi-head attention + to prevents attention to some unwanted positions, usually the + paddings or the subsequent positions. It is a tensor with shape + broadcasted to `[batch_size, n_head, sequence_length, sequence_length]`. + When the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + tgt_mask (Tensor, optional): A tensor used in self attention + to prevents attention to some unwanted positions, usually the + the subsequent positions. It is a tensor with shape broadcasted + to `[batch_size, n_head, target_length, target_length]`. When + the data type is bool, the unwanted positions have `False` + values and the others have `True` values. When the data type is + int, the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + memory_mask (Tensor, optional): A tensor used in decoder-encoder + cross attention to prevents attention to some unwanted positions, + usually the paddings. It is a tensor with shape broadcasted to + `[batch_size, n_head, target_length, source_length]`. When the + data type is bool, the unwanted positions have `False` values + and the others have `True` values. When the data type is int, + the unwanted positions have 0 values and the others have 1 + values. When the data type is float, the unwanted positions have + `-INF` values and the others have 0 values. It can be None when + nothing wanted or needed to be prevented attention to. Default None. + + Returns: + Tensor: It is a tensor that has the same shape and data type \ + as `tgt`, representing the output of Transformer decoder. + """ + src_mask = _convert_attention_mask(src_mask, src.dtype) + memory = self.encoder(src, src_mask=src_mask) + + tgt_mask = _convert_attention_mask(tgt_mask, tgt.dtype) + memory_mask = _convert_attention_mask(memory_mask, memory.dtype) + output = self.decoder(tgt, + memory, + tgt_mask=tgt_mask, + memory_mask=memory_mask) + return output + + def generate_square_subsequent_mask(self, length): + """ + Generate a square mask for the sequence. The mask ensures that the + predictions for position i can depend only on the known outputs at + positions less than i. + + Parameters: + length (int|Tensor): The length of sequence. + + Returns: + Tensor: Generated square mask according to the given length. + + Examples: + .. code-block:: python + + import paddle + from paddle.nn.layer.transformer import Transformer + length = 5 + d_model, n_head, dim_feedforward = 8, 4, 64 + transformer_paddle = Transformer( + d_model, n_head, dim_feedforward=dim_feedforward) + mask = transformer_paddle.generate_square_subsequent_mask(length) + print(mask) + + # [[ 0. -inf -inf -inf -inf] + # [ 0. 0. -inf -inf -inf] + # [ 0. 0. 0. -inf -inf] + # [ 0. 0. 0. 0. -inf] + # [ 0. 0. 0. 0. 0.]] + + """ + return paddle.tensor.triu( + paddle.full(shape=[length, length], + fill_value=-np.inf, + dtype=paddle.get_default_dtype()), 1) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/vision.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..e338e89dadaf4079db2dc27c8df64666ee995f8c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/layer/vision.py @@ -0,0 +1,222 @@ +# 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. + +# TODO: define specitial functions used in computer vision task + +from .. import Layer +from .. import functional + +__all__ = [] + + +class PixelShuffle(Layer): + """ + + PixelShuffle Layer + + Rearranges elements in a tensor of shape :math:`[N, C, H, W]` + to a tensor of shape :math:`[N, C/upscale_factor^2, H*upscale_factor, W \times upscale_factor]`, + or from shape :math:`[N, H, W, C]` to :math:`[N, H \times upscale_factor, W \times upscale_factor, C/upscale_factor^2]`. + This is useful for implementing efficient sub-pixel convolution + with a stride of 1/upscale_factor. + Please refer to the paper: `Real-Time Single Image and Video Super-Resolution + Using an Efficient Sub-Pixel Convolutional Neural Network `_ . + by Shi et. al (2016) for more details. + + Parameters: + + upscale_factor(int): factor to increase spatial resolution. + data_format (str, optional): The data format of the input and output data. An optional string from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - x: 4-D tensor with shape of :math:`(N, C, H, W)` or :math:`(N, H, W, C)`. + - out: 4-D tensor with shape of :math:`(N, C/upscale_factor^2, H \times upscale_factor, W \times upscale_factor)` or :math:`(N, H \times upscale_factor, W \times upscale_factor, C/upscale_factor^2)`. + + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + x = paddle.randn(shape=[2,9,4,4]) + pixel_shuffle = nn.PixelShuffle(3) + out_var = pixel_shuffle(x) + out = out_var.numpy() + print(out.shape) + # (2, 1, 12, 12) + + """ + + def __init__(self, upscale_factor, data_format="NCHW", name=None): + super(PixelShuffle, self).__init__() + + if not isinstance(upscale_factor, int): + raise TypeError("upscale factor must be int type") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError("Data format should be 'NCHW' or 'NHWC'." + "But recevie data format: {}".format(data_format)) + + self._upscale_factor = upscale_factor + self._data_format = data_format + self._name = name + + def forward(self, x): + return functional.pixel_shuffle(x, self._upscale_factor, + self._data_format, self._name) + + def extra_repr(self): + main_str = 'upscale_factor={}'.format(self._upscale_factor) + if self._data_format != 'NCHW': + main_str += ', data_format={}'.format(self._data_format) + if self._name is not None: + main_str += ', name={}'.format(self._name) + return main_str + + +class PixelUnshuffle(Layer): + """ + Rearranges elements in a tensor of shape :math:`[N, C, H, W]` + to a tensor of shape :math:`[N, r^2C, H/r, W/r]`, or from shape + :math:`[N, H, W, C]` to :math:`[N, H/r, W/r, r^2C]`, where :math:`r` is the + downscale factor. This operation is the reversion of PixelShuffle operation. + Please refer to the paper: `Real-Time Single Image and Video Super-Resolution + Using an Efficient Sub-Pixel Convolutional Neural Network `_ . + by Shi et. al (2016) for more details. + + Parameters: + downscale_factor (int): Factor to decrease spatial resolution. + data_format (str, optional): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - **x**: 4-D tensor with shape of :math:`[N, C, H, W]` or :math:`[N, C, H, W]`. + - **out**: 4-D tensor with shape of :math:`[N, r^2C, H/r, W/r]` or :math:`[N, H/r, W/r, r^2C]`, where :math:`r` is :attr:`downscale_factor`. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + + x = paddle.randn([2, 1, 12, 12]) + pixel_unshuffle = nn.PixelUnshuffle(3) + out = pixel_unshuffle(x) + print(out.shape) + # [2, 9, 4, 4] + + """ + + def __init__(self, downscale_factor, data_format="NCHW", name=None): + super(PixelUnshuffle, self).__init__() + + if not isinstance(downscale_factor, int): + raise TypeError("Downscale factor must be int type") + + if downscale_factor <= 0: + raise ValueError("Downscale factor must be positive") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError("Data format should be 'NCHW' or 'NHWC'." + "But recevie data format: {}".format(data_format)) + + self._downscale_factor = downscale_factor + self._data_format = data_format + self._name = name + + def forward(self, x): + return functional.pixel_unshuffle(x, self._downscale_factor, + self._data_format, self._name) + + def extra_repr(self): + main_str = 'downscale_factor={}'.format(self._downscale_factor) + if self._data_format != 'NCHW': + main_str += ', data_format={}'.format(self._data_format) + if self._name is not None: + main_str += ', name={}'.format(self._name) + return main_str + + +class ChannelShuffle(Layer): + """ + This operator divides channels in a tensor of shape [N, C, H, W] or [N, H, W, C] into g groups, + getting a tensor with the shape of [N, g, C/g, H, W] or [N, H, W, g, C/g], and transposes them + as [N, C/g, g, H, W] or [N, H, W, g, C/g], then rearranges them to original tensor shape. This + operation can improve the interaction between channels, using features efficiently. Please + refer to the paper: `ShuffleNet: An Extremely Efficient + Convolutional Neural Network for Mobile Devices `_ . + by Zhang et. al (2017) for more details. + + Parameters: + groups (int): Number of groups to divide channels in. + data_format (str): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width]. + name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - **x**: 4-D tensor with shape of [N, C, H, W] or [N, H, W, C]. + - **out**: 4-D tensor with shape and dtype same as x. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + x = paddle.arange(0, 0.6, 0.1, 'float32') + x = paddle.reshape(x, [1, 6, 1, 1]) + # [[[[0. ]], + # [[0.10000000]], + # [[0.20000000]], + # [[0.30000001]], + # [[0.40000001]], + # [[0.50000000]]]] + channel_shuffle = nn.ChannelShuffle(3) + y = channel_shuffle(x) + # [[[[0. ]], + # [[0.20000000]], + # [[0.40000001]], + # [[0.10000000]], + # [[0.30000001]], + # [[0.50000000]]]] + """ + + def __init__(self, groups, data_format="NCHW", name=None): + super(ChannelShuffle, self).__init__() + + if not isinstance(groups, int): + raise TypeError("groups must be int type") + + if groups <= 0: + raise ValueError("groups must be positive") + + if data_format not in ["NCHW", "NHWC"]: + raise ValueError("Data format should be 'NCHW' or 'NHWC'." + "But recevie data format: {}".format(data_format)) + + self._groups = groups + self._data_format = data_format + self._name = name + + def forward(self, x): + return functional.channel_shuffle(x, self._groups, self._data_format, + self._name) + + def extra_repr(self): + main_str = 'groups={}'.format(self._groups) + if self._data_format != 'NCHW': + main_str += ', data_format={}'.format(self._data_format) + if self._name is not None: + main_str += ', name={}'.format(self._name) + return main_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8973761ab6944389ecf99684282609021e7ce2b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/__init__.py @@ -0,0 +1,26 @@ +# Copyright (c) 2021 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. + +from .functional_layers import FloatFunctionalLayer # noqa: F401 +from .functional_layers import add # noqa: F401 +from .functional_layers import subtract # noqa: F401 +from .functional_layers import multiply # noqa: F401 +from .functional_layers import divide # noqa: F401 +from .functional_layers import reshape # noqa: F401 +from .functional_layers import transpose # noqa: F401 +from .functional_layers import concat # noqa: F401 +from .functional_layers import flatten # noqa: F401 +from .quant_layers import QuantStub # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/functional_layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/functional_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1eb5f4fb3c190cb71992312d02f19599d92a1f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/functional_layers.py @@ -0,0 +1,96 @@ +# Copyright (c) 2021 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. + +from ...tensor import math, manipulation +from .. import Layer + +__all__ = [] + + +class FloatFunctionalLayer(Layer): + + def __init__(self): + super(FloatFunctionalLayer, self).__init__() + + +class add(FloatFunctionalLayer): + + def __init__(self): + super(add, self).__init__() + + def forward(self, x, y, name=None): + return math.add(x, y, name) + + +class subtract(FloatFunctionalLayer): + + def __init__(self): + super(subtract, self).__init__() + + def forward(self, x, y, name=None): + return math.subtract(x, y, name) + + +class multiply(FloatFunctionalLayer): + + def __init__(self): + super(multiply, self).__init__() + + def forward(self, x, y, name=None): + return math.multiply(x, y, name) + + +class divide(FloatFunctionalLayer): + + def __init__(self): + super(divide, self).__init__() + + def forward(self, x, y, name=None): + return math.divide(x, y, name) + + +class reshape(FloatFunctionalLayer): + + def __init__(self): + super(reshape, self).__init__() + + def forward(self, x, shape, name=None): + return manipulation.reshape(x, shape, name) + + +class transpose(FloatFunctionalLayer): + + def __init__(self): + super(transpose, self).__init__() + + def forward(self, x, perm, name=None): + return manipulation.transpose(x, perm, name) + + +class concat(FloatFunctionalLayer): + + def __init__(self): + super(concat, self).__init__() + + def forward(self, x, axis=0, name=None): + return manipulation.concat(x, axis, name) + + +class flatten(FloatFunctionalLayer): + + def __init__(self): + super(flatten, self).__init__() + + def forward(self, x, start_axis=0, stop_axis=-1, name=None): + return manipulation.flatten(x, start_axis, stop_axis, name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/quant_layers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/quant_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..72bad0d44a8c38759d7ba2113a5cd991aeebe036 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/quant/quant_layers.py @@ -0,0 +1,959 @@ +# 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. + +import paddle +from paddle.framework import core +from paddle.fluid import dygraph_utils +from paddle.utils import unique_name +from paddle.framework import ParamAttr +from paddle.fluid.framework import _varbase_creator +from paddle.nn.initializer import Constant +from paddle.fluid.data_feeder import check_variable_and_dtype +from paddle.nn import functional as F +import logging +from paddle.fluid.log_helper import get_logger +from paddle import _C_ops, _legacy_C_ops +from paddle import in_dynamic_mode +from paddle.nn import Layer + +__all__ = [ + 'FakeQuantAbsMax', + 'FakeQuantMovingAverageAbsMax', + 'FakeQuantChannelWiseAbsMax', + 'QuantizedConv2D', + 'QuantizedConv2DTranspose', + 'QuantizedLinear', + 'MovingAverageAbsMaxScale', + 'MAOutputScaleLayer', + 'FakeQuantMAOutputScaleLayer', + 'QuantStub', + 'QuantizedRowParallelLinear', + 'QuantizedColumnParallelLinear', +] + +_logger = get_logger(__name__, + logging.INFO, + fmt='%(asctime)s-%(levelname)s: %(message)s') + + +class FakeQuantAbsMax(Layer): + r""" + FakeQuantAbsMax layer does the abs_max quant and then dequant. + Its computational formula is described as below: + + :math:`scale = max(abs(X))` + :math:`range = 2^{bit\_length - 1} - 1` + :math:`Out = round(X / scale * range) * scale / range` + """ + + def __init__(self, + name=None, + quant_bits=8, + dtype='float32', + quant_on_weight=False, + reduce_type=None): + super(FakeQuantAbsMax, self).__init__() + self._quant_bits = quant_bits + self._name = name + self._reduce_type = reduce_type + scale_prefix = "{}.scale".format( + name) if name else 'quant_dequant.scale' + self._scale_name = unique_name.generate(scale_prefix) + if quant_on_weight: + scale_attr = ParamAttr(name=self._scale_name, + initializer=Constant(0.001), + trainable=False) + self._scale = self.create_parameter(shape=[1], + attr=scale_attr, + dtype=self._dtype) + self._scale.stop_gradient = True + else: + self._scale = None + + def forward(self, input): + if in_dynamic_mode(): + attrs = ('bit_length', self._quant_bits) + quant_out = _varbase_creator(type=input.type, + name="{}.quantized.dequantized".format( + input.name), + shape=input.shape, + dtype=input.dtype, + persistable=False) + out_scale = self._scale + if self._reduce_type == "max": + paddle.distributed.all_reduce( + out_scale, op=paddle.distributed.ReduceOp.MAX) + + if not out_scale: + out_scale = _varbase_creator( + type=core.VarDesc.VarType.LOD_TENSOR, + name=self._scale_name, + shape=[1], + dtype=self._dtype, + persistable=False) + out_scale.stop_gradient = True + out, _, = _legacy_C_ops.fake_quantize_dequantize_abs_max( + input, quant_out, out_scale, *attrs) + return out + + check_variable_and_dtype(input, 'input', ['float32'], "FakeQuantAbsMax") + attrs = {'bit_length': self._quant_bits} + inputs = {"X": [input]} + quant_out = self._helper.create_variable( + name="{}.quantized.dequantized".format(input.name), + dtype=input.dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + out_scale = self._scale + if not out_scale: + out_scale = self._helper.create_variable( + name=self._scale_name, + dtype=self._dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + outputs = {"Out": [quant_out], "OutScale": [out_scale]} + + self._helper.append_op(type="fake_quantize_dequantize_abs_max", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return quant_out + + +class FakeQuantMovingAverageAbsMax(Layer): + r""" + FakeQuantMovingAverageAbsMax layer does the moving_average_abs_max quant and then dequant. + Its computational formula is described as below: + + :math:`scale = (moving\_rate*accum+max(abs(x)))/(moving\_rate*state+1)` + :math:`range = 2^{bit\_length - 1} - 1` + :math:`Out = round(X / scale * range) * scale / range` + """ + + def __init__(self, + name=None, + moving_rate=0.9, + quant_bits=8, + dtype='float32', + reduce_type=None): + super(FakeQuantMovingAverageAbsMax, self).__init__() + self._moving_rate = moving_rate + self._quant_bits = quant_bits + self._reduce_type = reduce_type + scale_prefix = "{}.scale".format( + name) if name else 'quant_dequant.scale' + scale_attr = ParamAttr(name=unique_name.generate(scale_prefix), + initializer=Constant(0.001), + trainable=False) + self._scale = self.create_parameter(shape=[1], + attr=scale_attr, + dtype=dtype) + self._scale.stop_gradient = True + + state_prefix = "{}.state".format( + name) if name else 'quant_dequant.state' + state_attr = ParamAttr(name=unique_name.generate(state_prefix), + initializer=Constant(1), + trainable=False) + self._state = self.create_parameter(shape=[1], + attr=state_attr, + dtype=dtype) + self._state.stop_gradient = True + + accum_prefix = "{}.accum".format( + name) if name else 'quant_dequant.accum' + accum_attr = ParamAttr(name=unique_name.generate(accum_prefix), + initializer=Constant(1), + trainable=False) + self._accum = self.create_parameter(shape=[1], + attr=accum_attr, + dtype=dtype) + self._accum.stop_gradient = True + + def forward(self, input): + if in_dynamic_mode(): + attrs = ('moving_rate', self._moving_rate, 'bit_length', + self._quant_bits, 'is_test', not self.training) + quant_out = _varbase_creator(type=input.type, + name="{}.quantized.dequantized".format( + input.name), + shape=input.shape, + dtype=input.dtype, + persistable=False) + if self._reduce_type == "max": + paddle.distributed.all_reduce( + self._scale, op=paddle.distributed.ReduceOp.MAX) + + state = self._state if self.training else None + accum = self._accum if self.training else None + + out, _, _, _ = _legacy_C_ops.fake_quantize_dequantize_moving_average_abs_max( + input, self._scale, accum, state, quant_out, self._scale, state, + accum, *attrs) + + return out + + check_variable_and_dtype(input, 'input', ['float32'], + "FakeQuantMovingAverageAbsMax") + attrs = { + 'moving_rate': self._moving_rate, + 'bit_length': self._quant_bits, + 'is_test': not self.training + } + inputs = {"X": [input], "InScale": [self._scale]} + quant_out = self._helper.create_variable( + name="{}.quantized.dequantized".format(input.name), + dtype=input.dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + outputs = {"Out": [quant_out], "OutScale": [self._scale]} + + if self.training: + inputs['InState'] = [self._state] + inputs['InAccum'] = [self._accum] + outputs['OutState'] = [self._state] + outputs['OutAccum'] = [self._accum] + + self._helper.append_op( + type="fake_quantize_dequantize_moving_average_abs_max", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return quant_out + + +class FakeQuantChannelWiseAbsMax(Layer): + + def __init__(self, + name=None, + channel_num=None, + quant_bits=8, + quant_axis=0, + dtype='float32', + quant_on_weight=False, + reduce_type=None): + assert quant_on_weight == True, "Channel_wise only can be used on weight quantization." + super(FakeQuantChannelWiseAbsMax, self).__init__() + self._quant_bits = quant_bits + self._quant_axis = quant_axis + self._dtype = dtype + self._name = name + self._channel_num = channel_num + self._reduce_type = reduce_type + scale_prefix = "{}.scale".format( + name) if name else 'quant_dequant.scale' + self._scale_name = unique_name.generate(scale_prefix) + if quant_on_weight: + scale_attr = ParamAttr(name=self._scale_name, + initializer=Constant(0.0), + trainable=False) + self._scale = self.create_parameter(shape=[self._channel_num], + attr=scale_attr, + dtype=self._dtype) + self._scale.stop_gradient = True + else: + self._scale = None + + def forward(self, input): + if in_dynamic_mode(): + attrs = ('bit_length', self._quant_bits, 'quant_axis', + self._quant_axis) + quant_out = _varbase_creator(type=input.type, + name="{}.quantized.dequantized".format( + input.name), + shape=input.shape, + dtype=input.dtype, + persistable=False) + + out_scale = self._scale + if self._reduce_type == "max": + paddle.distributed.all_reduce( + out_scale, op=paddle.distributed.ReduceOp.MAX) + if out_scale is None: + out_scale = _varbase_creator( + type=core.VarDesc.VarType.LOD_TENSOR, + name=self._scale_name, + shape=[self._channel_num], + dtype=self._dtype, + persistable=False) + out_scale.stop_gradient = True + + out, _, = _legacy_C_ops.fake_channel_wise_quantize_dequantize_abs_max( + input, quant_out, out_scale, *attrs) + return out + + check_variable_and_dtype(input, 'input', ['float32'], + "FakeQuantChannelWiseAbsMax") + attrs = {'bit_length': self._quant_bits, 'quant_axis': self._quant_axis} + inputs = {"X": [input]} + quant_out = self._helper.create_variable( + name="{}.quantized.dequantized".format(input.name), + dtype=input.dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + out_scale = self._scale + if not out_scale: + out_scale = self._helper.create_variable( + name=self._scale_name, + dtype=self._dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=True) + outputs = {"Out": [quant_out], "OutScale": [out_scale]} + + self._helper.append_op( + type="fake_channel_wise_quantize_dequantize_abs_max", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return quant_out + + +class MovingAverageAbsMaxScale(Layer): + + def __init__(self, + name=None, + moving_rate=0.9, + dtype='float32', + reduce_type=None): + r""" + MovingAverageMaxScale layer is used to calculating the output quantization + scale of Layer. Its computational formula is described as below: + + :math:`scale = (moving\_rate*accum+max(abs(x)))/(moving\_rate*state+1)` + :math:`Out = X` + """ + super(MovingAverageAbsMaxScale, self).__init__() + self._moving_rate = moving_rate + self._reduce_type = reduce_type + scale_prefix = '{}.scale'.format(name) if name else 'outscale.scale' + scale_name = unique_name.generate(scale_prefix) + scale_attr = ParamAttr(name=scale_name, + initializer=Constant(0), + trainable=False) + self._scale = self.create_parameter(shape=[1], + attr=scale_attr, + dtype=dtype) + self._scale.stop_gradient = True + + state_prefix = "{}.state".format(name) if name else 'outscale.state' + state_attr = ParamAttr(name=unique_name.generate(state_prefix), + initializer=Constant(0), + trainable=False) + self._state = self.create_parameter(shape=[1], + attr=state_attr, + dtype=dtype) + self._state.stop_gradient = True + + accum_prefix = "{}.accum".format(name) if name else 'outscale.accum' + accum_attr = ParamAttr(name=unique_name.generate(accum_prefix), + initializer=Constant(0), + trainable=False) + self._accum = self.create_parameter(shape=[1], + attr=accum_attr, + dtype=dtype) + self._accum.stop_gradient = True + + def forward(self, input): + if in_dynamic_mode(): + attrs = ('moving_rate', self._moving_rate, 'is_test', + not self.training) + + quant_out = _varbase_creator(type=input.type, + name="{}.tmp".format(input.name), + shape=input.shape, + dtype=input.dtype, + persistable=False) + if self._reduce_type == "max": + paddle.distributed.all_reduce( + self._scale, op=paddle.distributed.ReduceOp.MAX) + + state = self._state if self.training else None + accum = self._accum if self.training else None + + out, _, _, _ = _legacy_C_ops.moving_average_abs_max_scale( + input, accum, state, quant_out, self._scale, state, accum, + *attrs) + return out + + check_variable_and_dtype(input, 'input', ['float32', 'float64'], + 'MovingAverageAbsMaxScale') + + attrs = {'moving_rate': self._moving_rate, 'is_test': not self.training} + inputs = {"X": [input]} + quant_out = self._helper.create_variable( + name="{}.tmp".format(input.name), + dtype=input.dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + persistable=False, + stop_gradient=False) + outputs = {"Out": [quant_out], "OutScale": [self._scale]} + + if self.training: + inputs['InState'] = [self._state] + inputs['InAccum'] = [self._accum] + outputs['OutState'] = [self._state] + outputs['OutAccum'] = [self._accum] + + self._helper.append_op(type="moving_average_abs_max_scale", + inputs=inputs, + outputs=outputs, + attrs=attrs) + + return quant_out + + +QuantStub = MovingAverageAbsMaxScale + + +class QuantizedConv2D(Layer): + """ + The computational logic of QuantizedConv2D is the same with Conv2D. + The only difference is that its inputs are all fake quantized. + """ + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_quantize_type='abs_max', + activation_quantize_type='abs_max', + weight_pre_layer=None, + act_pre_layer=None, + weight_quant_layer=None, + act_quant_layer=None): + super(QuantizedConv2D, self).__init__() + # For Conv2D + self._groups = getattr(layer, '_groups') + self._stride = getattr(layer, '_stride') + self._padding = getattr(layer, '_padding') + self._padding_mode = getattr(layer, '_padding_mode') + if self._padding_mode != 'zeros': + self._reversed_padding_repeated_twice = getattr( + layer, '_reversed_padding_repeated_twice') + self._dilation = getattr(layer, '_dilation') + self._data_format = getattr(layer, '_data_format') + self.weight = getattr(layer, 'weight') + self.bias = getattr(layer, 'bias') + + # For FakeQuant + self._conv2d_quant_axis = 0 + if weight_quant_layer is not None: + self._fake_quant_weight = weight_quant_layer() + else: + self._fake_quant_weight = _get_fake_quant_type( + weight_quantize_type, + name=self.weight.name, + moving_rate=moving_rate, + quant_bits=weight_bits, + dtype=self._dtype, + quant_on_weight=True, + channel_num=self.weight.shape[self._conv2d_quant_axis], + quant_axis=self._conv2d_quant_axis) + if act_quant_layer is not None: + self._fake_quant_input = act_quant_layer() + else: + self._fake_quant_input = _get_fake_quant_type( + activation_quantize_type, + name=layer.full_name(), + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False) + + self._act_preprocess = act_pre_layer( + ) if act_pre_layer is not None else None + self._weight_preprocess = weight_pre_layer( + ) if weight_pre_layer is not None else None + + def forward(self, input): + if self._act_preprocess is not None: + input = self._act_preprocess(input) + quant_input = self._fake_quant_input(input) + + weight = self.weight + if self._weight_preprocess is not None: + weight = self._weight_preprocess(self.weight) + quant_weight = self._fake_quant_weight(weight) + + if self._padding_mode != 'zeros': + quant_input = F.pad(quant_input, + self._reversed_padding_repeated_twice, + mode=self._padding_mode, + data_format=self._data_format) + self._padding = 0 + + return F.conv2d(quant_input, + quant_weight, + bias=self.bias, + padding=self._padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + data_format=self._data_format) + + +class QuantizedConv2DTranspose(Layer): + """ + + The computational logic of QuantizedConv2DTranspose is the same with Conv2DTranspose. + The only difference is that its inputs are all fake quantized. + + Examples: + .. code-block:: python + + import paddle + import paddle.nn as nn + from paddle.nn.quant.quant_layers import QuantizedConv2DTranspose + + x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.) + conv = nn.Conv2DTranspose(4, 6, (3, 3)) + conv_quantized = QuantizedConv2DTranspose(conv) + y_quantized = conv_quantized(x_var) + y_var = conv(x_var) + y_quantized_np = y_quantized.numpy() + y_np = y_var.numpy() + print(y_np.shape, y_quantized_np.shape) + # (2, 6, 10, 10), (2, 6, 10, 10) + + """ + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_quantize_type='abs_max', + activation_quantize_type='abs_max', + weight_pre_layer=None, + act_pre_layer=None, + weight_quant_layer=None, + act_quant_layer=None): + r""" + Constructor. + + The arguments are the same as ImperativeQuantAware. + """ + super(QuantizedConv2DTranspose, self).__init__() + # For Conv2DTranspose + self._groups = getattr(layer, '_groups') + self._stride = getattr(layer, '_stride') + self._padding = getattr(layer, '_padding') + self._output_padding = getattr(layer, 'output_padding') + self._dilation = getattr(layer, '_dilation') + self._data_format = getattr(layer, '_data_format') + self.weight = getattr(layer, 'weight') + self.bias = getattr(layer, 'bias') + # For FakeQuant + self._conv2d_transpose_quant_axis = 1 + if weight_quant_layer is not None: + self._fake_quant_weight = weight_quant_layer() + else: + self._fake_quant_weight = _get_fake_quant_type( + weight_quantize_type, + name=self.weight.name, + moving_rate=moving_rate, + quant_bits=weight_bits, + dtype=self._dtype, + quant_on_weight=True, + channel_num=self.weight.shape[ + self._conv2d_transpose_quant_axis], + quant_axis=self._conv2d_transpose_quant_axis) + if act_quant_layer is not None: + self._fake_quant_input = act_quant_layer() + else: + self._fake_quant_input = _get_fake_quant_type( + activation_quantize_type, + name=layer.full_name(), + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False) + + self._act_preprocess = act_pre_layer( + ) if act_pre_layer is not None else None + self._weight_preprocess = weight_pre_layer( + ) if weight_pre_layer is not None else None + + def forward(self, input, output_size=None): + if self._act_preprocess is not None: + input = self._act_preprocess(input) + quant_input = self._fake_quant_input(input) + + weight = self.weight + if self._weight_preprocess is not None: + weight = self._weight_preprocess(self.weight) + quant_weight = self._fake_quant_weight(weight) + + if output_size is None: + output_padding = self._output_padding + else: + output_padding = 0 + + return F.conv2d_transpose(quant_input, + quant_weight, + bias=self.bias, + padding=self._padding, + output_padding=output_padding, + stride=self._stride, + dilation=self._dilation, + groups=self._groups, + output_size=output_size, + data_format=self._data_format) + + +class QuantizedLinear(Layer): + """ + The computational logic of QuantizedLinear is the same with Linear. + The only difference is that its inputs are all fake quantized. + """ + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_quantize_type='abs_max', + activation_quantize_type='abs_max', + weight_pre_layer=None, + act_pre_layer=None, + weight_quant_layer=None, + act_quant_layer=None): + super(QuantizedLinear, self).__init__() + # For Linear + self.weight = getattr(layer, 'weight') + self.bias = getattr(layer, 'bias') + self.name = getattr(layer, 'name') + # For FakeQuant + self._linear_quant_axis = 1 + + if weight_quant_layer is not None: + self._fake_quant_weight = weight_quant_layer() + else: + self._fake_quant_weight = _get_fake_quant_type( + weight_quantize_type, + name=self.weight.name, + moving_rate=moving_rate, + quant_bits=weight_bits, + dtype=self._dtype, + quant_on_weight=True, + channel_num=self.weight.shape[self._linear_quant_axis], + quant_axis=self._linear_quant_axis) + + if act_quant_layer is not None: + self._fake_quant_input = act_quant_layer() + else: + self._fake_quant_input = _get_fake_quant_type( + activation_quantize_type, + name=layer.full_name(), + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False) + + self._act_preprocess = act_pre_layer( + ) if act_pre_layer is not None else None + self._weight_preprocess = weight_pre_layer( + ) if weight_pre_layer is not None else None + + def forward(self, input): + if self._act_preprocess is not None: + input = self._act_preprocess(input) + quant_input = self._fake_quant_input(input) + + weight = self.weight + if self._weight_preprocess is not None: + weight = self._weight_preprocess(self.weight) + quant_weight = self._fake_quant_weight(weight) + + out = F.linear(x=quant_input, + weight=quant_weight, + bias=self.bias, + name=self.name) + return out + + +class QuantizedColumnParallelLinear(Layer): + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_quantize_type='abs_max', + activation_quantize_type='abs_max', + weight_pre_layer=None, + act_pre_layer=None, + weight_quant_layer=None, + act_quant_layer=None): + super(QuantizedColumnParallelLinear, self).__init__() + ''' + + ''' + assert weight_quant_layer is None, "When quantizing ColumnParallelLinear, weight_quant_layer should be None." + assert act_quant_layer is None, "When quantizing ColumnParallelLinear, act_quant_layer should be None." + + self.weight = getattr(layer, 'weight') + self.bias = getattr(layer, 'bias') + self.name = getattr(layer, '_name') + # For FakeQuant + self._linear_quant_axis = 1 + + self.is_mp = getattr(layer, 'is_mp') + self.model_parallel_group = getattr(layer, 'model_parallel_group') + self.gather_output = getattr(layer, 'gather_output') + + self._fake_quant_weight = _get_fake_quant_type( + weight_quantize_type, + name=self.weight.name, + moving_rate=moving_rate, + quant_bits=weight_bits, + dtype=self._dtype, + quant_on_weight=True, + channel_num=self.weight.shape[self._linear_quant_axis], + quant_axis=self._linear_quant_axis, + reduce_type='max' + if paddle.distributed.get_world_size() > 1 else None) + + self._fake_quant_input = _get_fake_quant_type( + activation_quantize_type, + name=layer.full_name(), + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False, + reduce_type=None) + + self._act_preprocess = act_pre_layer( + ) if act_pre_layer is not None else None + self._weight_preprocess = weight_pre_layer( + ) if weight_pre_layer is not None else None + + def forward(self, input): + if self.is_mp: + input_parallel = paddle.distributed.collective._c_identity( + input, group=self.model_parallel_group) + else: + input_parallel = input + + if self._act_preprocess is not None: + input_parallel = self._act_preprocess(input_parallel) + quant_input = self._fake_quant_input(input_parallel) + + weight = self.weight + if self._weight_preprocess is not None: + weight = self._weight_preprocess(self.weight) + quant_weight = self._fake_quant_weight(weight) + + output_parallel = F.linear(x=quant_input, + weight=quant_weight, + bias=self.bias, + name=self.name) + + if self.gather_output and self.is_mp: + output = paddle.distributed.collective._c_concat( + output_parallel, group=self.model_parallel_group) + else: + output = output_parallel + return output + + +class QuantizedRowParallelLinear(Layer): + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + weight_quantize_type='abs_max', + activation_quantize_type='abs_max', + weight_pre_layer=None, + act_pre_layer=None, + weight_quant_layer=None, + act_quant_layer=None): + super(QuantizedRowParallelLinear, self).__init__() + assert weight_quant_layer is None, "When quantizing RowParallelLinear, weight_quant_layer cannot defined by yourself." + assert act_quant_layer is None, "When quantizing RowParallelLinear, act_quant_layer cannot defined by yourself." + + # For Linear + self.weight = getattr(layer, 'weight') + self.bias = getattr(layer, 'bias') + self.name = getattr(layer, '_name') + # For FakeQuant + self._linear_quant_axis = 1 + + self.input_is_parallel = getattr(layer, 'input_is_parallel') + self.is_mp = getattr(layer, 'is_mp') + self.model_parallel_group = getattr(layer, 'model_parallel_group') + + self._fake_quant_weight = _get_fake_quant_type( + weight_quantize_type, + name=self.weight.name, + moving_rate=moving_rate, + quant_bits=weight_bits, + dtype=self._dtype, + quant_on_weight=True, + channel_num=self.weight.shape[self._linear_quant_axis], + quant_axis=self._linear_quant_axis, + reduce_type='max' + if paddle.distributed.get_world_size() > 1 else None) + + self._fake_quant_input = _get_fake_quant_type( + activation_quantize_type, + name=layer.full_name(), + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False, + reduce_type='max' + if paddle.distributed.get_world_size() > 1 else None) + + self._act_preprocess = act_pre_layer( + ) if act_pre_layer is not None else None + self._weight_preprocess = weight_pre_layer( + ) if weight_pre_layer is not None else None + + def forward(self, input): + if self.input_is_parallel or (not self.is_mp): + input_parallel = input + else: + # split last dim + input_parallel = paddle.distributed.collective._c_split( + input, group=self.model_parallel_group) + + if self._act_preprocess is not None: + input_parallel = self._act_preprocess(input_parallel) + quant_input = self._fake_quant_input(input_parallel) + + weight = self.weight + if self._weight_preprocess is not None: + weight = self._weight_preprocess(self.weight) + quant_weight = self._fake_quant_weight(weight) + + output_parallel = F.linear(x=quant_input, + weight=quant_weight, + name=self.name) + if self.is_mp: + output_ = paddle.distributed.collective._mp_allreduce( + output_parallel, + group=self.model_parallel_group, + use_calc_stream=True, + use_model_parallel=True) + else: + output_ = output_parallel + output = output_ + self.bias if self.bias is not None else output_ + return output + + +class MAOutputScaleLayer(Layer): + """ + Add MovingAverageMaxScale layer to the behind of the input layer. + Calculate the scale (moving average abs max) for the output of the input layer. + """ + + def __init__(self, + layer=None, + moving_rate=0.9, + name=None, + dtype='float32', + reduce_type=None): + r""" + Construct + """ + super(MAOutputScaleLayer, self).__init__() + self._layer = layer + if name is None: + name = layer.full_name() + self._ma_output_scale = \ + MovingAverageAbsMaxScale(name, moving_rate, dtype, reduce_type) + + def forward(self, *inputs, **kwargs): + out = self._layer(*inputs, **kwargs) + # TODO (jc): support the ops of several outputs + if (isinstance(out, list) or isinstance(out, tuple) + or isinstance(out, dict)): + return out + else: + return self._ma_output_scale(out) + + +class FakeQuantMAOutputScaleLayer(Layer): + """ + Add FakeQuantMovingAverageAbsMax layer to the behind of the input layer. + """ + + def __init__(self, + layer, + weight_bits=8, + activation_bits=8, + moving_rate=0.9, + name=None, + reduce_type=None, + *args, + **kwargs): + + super(FakeQuantMAOutputScaleLayer, self).__init__() + self._layer = layer + self._fake_quant_output = _get_fake_quant_type( + 'moving_average_abs_max', + name=layer.full_name() if name is None else name, + moving_rate=moving_rate, + quant_bits=activation_bits, + dtype=self._dtype, + quant_on_weight=False, + reduce_type=reduce_type) + + def forward(self, *inputs, **kwargs): + out = self._layer(*inputs, **kwargs) + # TODO (jc): support the ops of several outputs + if (isinstance(out, list) or isinstance(out, tuple)) and len(out) > 1: + return out + else: + return self._fake_quant_output(out) + + +def _get_fake_quant_type(quant_type, **kwargs): + call_args = { + "name": kwargs.get("name", None), + "quant_bits": kwargs.get("quant_bits", 8), + "dtype": kwargs.get("dtype", "float32"), + "reduce_type": kwargs.get("reduce_type", None) + } + + if quant_type == 'abs_max': + call_args["quant_on_weight"] = kwargs.get("quant_on_weight", False) + elif quant_type == 'moving_average_abs_max': + call_args["moving_rate"] = kwargs.get("moving_rate", 0.9) + elif quant_type == 'channel_wise_abs_max': + call_args["quant_on_weight"] = kwargs.get("quant_on_weight", False) + call_args["channel_num"] = kwargs.get("channel_num", None) + call_args["quant_axis"] = kwargs.get("quant_axis", 0) + assert call_args["channel_num"] is not None, ( + "You need to input channel_num" + "when you use channel_wise_abs_max strategy.") + fake_quant_map = { + 'abs_max': FakeQuantAbsMax, + 'moving_average_abs_max': FakeQuantMovingAverageAbsMax, + 'channel_wise_abs_max': FakeQuantChannelWiseAbsMax + } + + return fake_quant_map[quant_type](**call_args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5afdaa8d8489662e25e1eeb16bfe18f3ef8c1ac9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/__init__.py @@ -0,0 +1,22 @@ +# 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. + +from .spectral_norm_hook import spectral_norm +from .weight_norm_hook import weight_norm, remove_weight_norm # noqa: F401 +from .transform_parameters import parameters_to_vector, vector_to_parameters, _stride_column # noqa: F401 + +__all__ = [ #noqa + 'weight_norm', 'remove_weight_norm', 'spectral_norm', + 'parameters_to_vector', 'vector_to_parameters' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/spectral_norm_hook.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/spectral_norm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9abf46fff1a1f794b3b7caec094312f9a6fdbe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/spectral_norm_hook.py @@ -0,0 +1,218 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +import numpy as np + +import paddle +from ..layer.conv import Conv1DTranspose, Conv2DTranspose, Conv3DTranspose +from ..layer.common import Linear +from .. import functional as F + +__all__ = [] + + +def normal_(x, mean=0.0, std=1.0): + temp_value = paddle.normal(mean, std, shape=x.shape) + x.set_value(temp_value) + return x + + +class SpectralNorm(object): + def __init__(self, name='weight', n_power_iterations=1, dim=0, eps=1e-12): + self.name = name + self.dim = dim + if n_power_iterations <= 0: + raise ValueError( + 'Expected n_power_iterations to be positive, but ' + 'got n_power_iterations={}'.format(n_power_iterations) + ) + self.n_power_iterations = n_power_iterations + self.eps = eps + + def reshape_weight_to_matrix(self, weight): + weight_mat = weight + if self.dim != 0: + # transpose dim to front + weight_mat = weight_mat.transpose( + [self.dim] + + [d for d in range(weight_mat.dim()) if d != self.dim] + ) + + height = weight_mat.shape[0] + + return weight_mat.reshape([height, -1]) + + def compute_weight(self, layer, do_power_iteration): + weight = getattr(layer, self.name + '_orig') + u = getattr(layer, self.name + '_u') + v = getattr(layer, self.name + '_v') + weight_mat = self.reshape_weight_to_matrix(weight) + + if do_power_iteration: + with paddle.no_grad(): + for _ in range(self.n_power_iterations): + v.set_value( + F.normalize( + paddle.matmul( + weight_mat, + u, + transpose_x=True, + transpose_y=False, + ), + axis=0, + epsilon=self.eps, + ) + ) + + u.set_value( + F.normalize( + paddle.matmul(weight_mat, v), + axis=0, + epsilon=self.eps, + ) + ) + if self.n_power_iterations > 0: + u = u.clone() + v = v.clone() + + sigma = paddle.dot(u, paddle.mv(weight_mat, v)) + weight = weight / sigma + return weight + + def __call__(self, layer, inputs): + setattr( + layer, + self.name, + self.compute_weight(layer, do_power_iteration=layer.training), + ) + + @staticmethod + def apply(layer, name, n_power_iterations, dim, eps): + for k, hook in layer._forward_pre_hooks.items(): + if isinstance(hook, SpectralNorm) and hook.name == name: + raise RuntimeError( + "Cannot register two spectral_norm hooks on " + "the same parameter {}".format(name) + ) + + fn = SpectralNorm(name, n_power_iterations, dim, eps) + weight = layer._parameters[name] + + with paddle.no_grad(): + weight_mat = fn.reshape_weight_to_matrix(weight) + h, w = weight_mat.shape + + # randomly initialize u and v + u = layer.create_parameter([h]) + u = normal_(u, 0.0, 1.0) + v = layer.create_parameter([w]) + v = normal_(v, 0.0, 1.0) + u = F.normalize(u, axis=0, epsilon=fn.eps) + v = F.normalize(v, axis=0, epsilon=fn.eps) + + # delete fn.name form parameters, otherwise you can not set attribute + del layer._parameters[fn.name] + layer.add_parameter(fn.name + "_orig", weight) + # still need to assign weight back as fn.name because all sorts of + # things may assume that it exists, e.g., when initializing weights. + # However, we can't directly assign as it could be an Parameter and + # gets added as a parameter. Instead, we register weight * 1.0 as a plain + # attribute. + setattr(layer, fn.name, weight * 1.0) + layer.register_buffer(fn.name + "_u", u) + layer.register_buffer(fn.name + "_v", v) + layer.register_forward_pre_hook(fn) + return fn + + +def spectral_norm( + layer, name='weight', n_power_iterations=1, eps=1e-12, dim=None +): + r""" + Applies spectral normalization to a parameter according to the + following Calculation: + + Step 1: + Generate vector U in shape of [H], and V in shape of [W]. + While H is the :attr:`dim` th dimension of the input weights, + and W is the product result of remaining dimensions. + + Step 2: + :attr:`n_power_iterations` should be a positive integer, do following + calculations with U and V for :attr:`power_iters` rounds. + + .. math:: + + \mathbf{v} := \frac{\mathbf{W}^{T} \mathbf{u}}{\|\mathbf{W}^{T} \mathbf{u}\|_2} + + \mathbf{u} := \frac{\mathbf{W} \mathbf{v}}{\|\mathbf{W} \mathbf{v}\|_2} + + Step 3: + Calculate :math:`\sigma(\mathbf{W})` and normalize weight values. + + .. math:: + + \sigma(\mathbf{W}) = \mathbf{u}^{T} \mathbf{W} \mathbf{v} + + \mathbf{W} = \frac{\mathbf{W}}{\sigma(\mathbf{W})} + + + Refer to `Spectral Normalization `_ . + + Parameters: + layer(Layer): Layer of paddle, which has weight. + name(str, optional): Name of the weight parameter. Default: 'weight'. + n_power_iterations(int, optional): The number of power iterations to calculate spectral norm. Default: 1. + eps(float, optional): The epsilon for numerical stability in calculating norms. Default: 1e-12. + dim(int, optional): The index of dimension which should be permuted to the first before reshaping Input(Weight) to matrix, it should be set as 0 if Input(Weight) is the weight of fc layer, and should be set as 1 if Input(Weight) is the weight of conv layer. Default: None. + + Returns: + Layer, the original layer with the spectral norm hook. + + Examples: + .. code-block:: python + + from paddle.nn import Conv2D + from paddle.nn.utils import spectral_norm + + conv = Conv2D(3, 1, 3) + sn_conv = spectral_norm(conv) + print(sn_conv) + # Conv2D(3, 1, kernel_size=[3, 3], data_format=NCHW) + print(sn_conv.weight) + # Tensor(shape=[1, 3, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [[[[-0.21090528, 0.18563725, -0.14127982], + # [-0.02310637, 0.03197737, 0.34353802], + # [-0.17117859, 0.33152047, -0.28408015]], + # + # [[-0.13336606, -0.01862637, 0.06959272], + # [-0.02236020, -0.27091628, -0.24532901], + # [ 0.27254242, 0.15516677, 0.09036587]], + # + # [[ 0.30169338, -0.28146112, -0.11768346], + # [-0.45765871, -0.12504843, -0.17482486], + # [-0.36866254, -0.19969313, 0.08783543]]]]) + + """ + + if dim is None: + if isinstance( + layer, (Conv1DTranspose, Conv2DTranspose, Conv3DTranspose, Linear) + ): + dim = 1 + else: + dim = 0 + SpectralNorm.apply(layer, name, n_power_iterations, dim, eps) + return layer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/transform_parameters.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/transform_parameters.py new file mode 100644 index 0000000000000000000000000000000000000000..44b870a9a4744bd20087e7e5bce9dce990c2df17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/transform_parameters.py @@ -0,0 +1,175 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from functools import reduce + +import paddle +from paddle.fluid.framework import dygraph_only, _dygraph_tracer, _varbase_creator, in_dygraph_mode +from paddle import _C_ops, _legacy_C_ops + + +#input==output, inplace strategy of reshape has no cost almostly +def _inplace_reshape_dygraph(x, shape): + x_shape = _varbase_creator(dtype='int64') + if in_dygraph_mode(): + with paddle.fluid.dygraph.no_grad(): + tmp_out = _C_ops.reshape(x, shape) + tmp_out._share_underline_tensor_to(x) + else: + _dygraph_tracer().trace_op(type="reshape2", + inputs={'X': x}, + outputs={ + 'Out': x, + 'XShape': x_shape + }, + attrs={'shape': shape}, + stop_gradient=True) + + +@dygraph_only +def _stride_column(param): + """ + A tool function. Permute date of parameter as a 'columns' stride. Now, it only support 2-D parameter. + + Args: + param(Tensor]): The param that will be strided according to 'columns'. + + Examples: + .. code-block:: python + + import paddle + paddle.seed(100) + + linear = paddle.nn.Linear(2, 3) + print(linear.weight) + # [[-0.31485492, -1.02896988, 0.45741916], + # [-0.65525872, -1.04643178, 1.07262802]] + + paddle.nn.utils.stride_column(linear.weight) + print(linear.weight) + # [[-0.31485492, 0.45741916, -1.04643178], + # [-1.02896988, -0.65525872, 1.07262802]] + + """ + assert len(param.shape) == 2 + shape = [param.shape[1], param.shape[0]] + with paddle.fluid.dygraph.no_grad(): + reshape_var = paddle.reshape(param, shape) + transpose_var = paddle.transpose(reshape_var, [1, 0]) + transpose_var._share_underline_tensor_to(param) + + +@dygraph_only +def parameters_to_vector(parameters, name=None): + """ + Flatten parameters to a 1-D Tensor. + + Args: + parameters(Iterable[Tensor]): Iterable Tensors that are trainable parameters of a Layer. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A 1-D Tensor, which represents the parameters of a Layer. + + + Examples: + .. code-block:: python + + import paddle + linear = paddle.nn.Linear(10, 15) + + paddle.nn.utils.parameters_to_vector(linear.parameters()) + # 1-D Tensor: [165] + + """ + dtype = parameters[0].dtype + origin_shapes = [] + for param in parameters: + origin_shapes.append(param.shape) + _inplace_reshape_dygraph(param, [-1]) + + out = _varbase_creator(dtype=dtype) + if in_dygraph_mode(): + with paddle.fluid.dygraph.no_grad(): + tmp = _C_ops.concat(parameters, 0) + tmp._share_underline_tensor_to(out) + else: + _dygraph_tracer().trace_op(type='concat', + inputs={'X': parameters}, + outputs={'Out': [out]}, + attrs={'axis': 0}, + stop_gradient=True) + for i, param in enumerate(parameters): + _inplace_reshape_dygraph(param, origin_shapes[i]) + return out + + +@dygraph_only +def vector_to_parameters(vec, parameters, name=None): + """ + Transform a 1-D Tensor to the input ``parameters`` . + + Args: + vec (Tensor): A 1-D Tensor, which will be sliced and copied to the input ``parameters`` . + parameters (Iterable[Tensor]): Iterable Tensors that are trainable parameters of a Layer. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Examples: + .. code-block:: python + + import paddle + weight_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(3.)) + linear1 = paddle.nn.Linear(10, 15, weight_attr) + + vec = paddle.nn.utils.parameters_to_vector(linear1.parameters()) + + linear2 = paddle.nn.Linear(10, 15) + # copy weight of linear1 to linear2 + paddle.nn.utils.vector_to_parameters(vec, linear2.parameters()) + # weight: Tensor(shape=[10, 15], dtype=float32, place=CUDAPlace(0), stop_gradient=False, + # [[3. , ..., 3. ], + # [..., ..., ...], + # [3. , ..., 3. ]]) + """ + origin_shapes = [] + sections = [] + for param in parameters: + shape = param.shape + origin_shapes.append(shape) + numel = reduce(lambda x, y: x * y, shape) + sections.append(numel) + + if len(sections) == 1: + sections.append(0) + + if in_dygraph_mode(): + with paddle.fluid.dygraph.no_grad(): + res = _C_ops.split(vec, sections, 0) + for i in range(0, len(parameters)): + res[i]._share_underline_tensor_to(parameters[i]) + else: + _dygraph_tracer().trace_op(type='split', + inputs={'X': [vec]}, + outputs={'Out': parameters}, + attrs={ + 'axis': 0, + 'sections': sections + }, + stop_gradient=True) + + for i, param in enumerate(parameters): + _inplace_reshape_dygraph(param, origin_shapes[i]) + return diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/weight_norm_hook.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/weight_norm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..55e2d408ffaeadb618986aa6b921ff5eb478c8a7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/nn/utils/weight_norm_hook.py @@ -0,0 +1,246 @@ +# 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. +import paddle +import numpy as np +from ... import fluid +from ...fluid import dygraph +from ...fluid import layers as F +from ...fluid.layer_helper import LayerHelper +from ...fluid.data_feeder import check_variable_and_dtype +from ...framework import in_dygraph_mode +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def l2_norm(x, axis, epsilon=1e-12, name=None): + if len(x.shape) == 1: + axis = 0 + + if in_dygraph_mode(): + out, norm = _C_ops.norm(x, 1 if axis is None else axis, epsilon, False) + return paddle.squeeze(norm, axis=[axis]) + + check_variable_and_dtype(x, "X", ("float32", "float64"), "norm") + + helper = LayerHelper("l2_normalize", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + norm = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="norm", + inputs={"X": x}, + outputs={"Out": out, "Norm": norm}, + attrs={ + "axis": 1 if axis is None else axis, + "epsilon": epsilon, + }, + ) + return paddle.squeeze(norm, axis=[axis]) + + +def norm_except_dim(p, dim): + shape = p.shape + ndims = len(shape) + if dim == -1: + return paddle.sqrt(paddle.sum(paddle.square(p)) + 1e-12) + elif dim == 0: + p_matrix = paddle.reshape(p, (shape[0], -1)) + return l2_norm(p_matrix, axis=1) + elif dim == ndims - 1: + p_matrix = paddle.reshape(p, (-1, shape[-1])) + return l2_norm(p_matrix, axis=0) + else: + perm = list(range(ndims)) + perm[0] = dim + perm[dim] = 0 + p_transposed = paddle.transpose(p, perm) + return norm_except_dim(p_transposed, 0) + + +def _weight_norm(v, g, dim): + shape = v.shape + ndims = len(shape) + + if dim == -1: + v_normalized = v / (paddle.sqrt(paddle.sum(paddle.square(v))) + 1e-12) + elif dim == 0: + p_matrix = paddle.reshape(v, (shape[0], -1)) + v_normalized = F.l2_normalize(p_matrix, axis=1) + v_normalized = paddle.reshape(v_normalized, shape) + elif dim == ndims - 1: + p_matrix = paddle.reshape(v, (-1, shape[-1])) + v_normalized = F.l2_normalize(p_matrix, axis=0) + v_normalized = paddle.reshape(v_normalized, shape) + else: + perm = list(range(ndims)) + perm[0] = dim + perm[dim] = 0 + p_transposed = paddle.transpose(v, perm) + transposed_shape = p_transposed.shape + p_matrix = paddle.reshape(p_transposed, (p_transposed.shape[0], -1)) + v_normalized = F.l2_normalize(p_matrix, axis=1) + v_normalized = paddle.reshape(v_normalized, transposed_shape) + v_normalized = paddle.transpose(v_normalized, perm) + weight = F.elementwise_mul( + v_normalized, g, axis=dim if dim is not None else -1 + ) + return weight + + +class WeightNorm(object): + def __init__(self, name, dim): + if dim is None: + dim = -1 + self.name = name + self.dim = dim + + def compute_weight(self, layer): + g = getattr(layer, self.name + '_g') + v = getattr(layer, self.name + '_v') + return _weight_norm(v, g, self.dim) + + @staticmethod + def apply(layer, name, dim): + for k, hook in layer._forward_pre_hooks.items(): + if isinstance(hook, WeightNorm) and hook.name == name: + raise RuntimeError( + "Cannot register two weight_norm hooks on " + "the same parameter {}".format(name) + ) + + if dim is None: + dim = -1 + + # support dim is negative numeber, (dim = -1) == (dim = None) + weight_dim = len(layer._parameters[name].shape) + assert ( + dim < weight_dim and dim >= -1 * weight_dim + ), "dim must set between [-R, R), R means the dimension of weight." + if dim != -1: + dim = (dim + weight_dim) % weight_dim + + fn = WeightNorm(name, dim) + + w = getattr(layer, name) + del layer._parameters[name] + + g_var = norm_except_dim(w, dim) + v = layer.create_parameter(w.shape, dtype=w.dtype) + layer.add_parameter(name + "_v", v) + g = layer.create_parameter(g_var.shape, dtype=g_var.dtype) + layer.add_parameter(name + '_g', g) + with paddle.no_grad(): + paddle.assign(w, v) + paddle.assign(g_var, g) + setattr(layer, name, fn.compute_weight(layer)) + + layer.register_forward_pre_hook(fn) + return fn + + def remove(self, layer): + w_var = self.compute_weight(layer) + delattr(layer, self.name) + del layer._parameters[self.name + '_g'] + del layer._parameters[self.name + '_v'] + w = layer.create_parameter(w_var.shape, dtype=w_var.dtype) + layer.add_parameter(self.name, w) + with paddle.no_grad(): + paddle.assign(w_var, w) + + def __call__(self, layer, inputs): + setattr(layer, self.name, self.compute_weight(layer)) + + +def weight_norm(layer, name='weight', dim=0): + r""" + Applies weight normalization to a parameter according to the + following formula: + + .. math:: + + \mathbf{w} = g \dfrac{v}{\|v\|} + + Weight normalization is a reparameterization of the weight vectors in a neural network that + decouples the magnitude of those weight vectors from their direction. Weight normalization + replaces the parameter specified by `name`(eg: 'weight') with two parameters: one parameter + specifying the magnitude (eg: 'weight_g') and one parameter specifying the direction + (eg: 'weight_v'). Weight normalization has been implemented as discussed in this paper: + `Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks + `_. + + Parameters: + layer(Layer): Layer of paddle, which has weight. + name(str, optional): Name of the weight parameter. Default: 'weight'. + dim(int, optional): Dimension over which to compute the norm. Dim is a non-negative number + which is less than the rank of weight Tensor. For Example, dim can be chosen from 0, + 1, 2, 3 for convolution whose weight shape is [cout, cin, kh, kw] and rank is 4. + If dim is set to None, meaning that all elements will be normalized. Default: 0. + + Returns: + Origin layer with weight norm hook. + + Examples: + .. code-block:: python + + from paddle.nn import Conv2D + from paddle.nn.utils import weight_norm + + conv = Conv2D(3, 5, 3) + wn = weight_norm(conv) + print(conv.weight_g.shape) + # [5] + print(conv.weight_v.shape) + # [5, 3, 3, 3] + """ + WeightNorm.apply(layer, name, dim) + return layer + + +def remove_weight_norm(layer, name='weight'): + """ + remove weight normalization from layer. + + Parameters: + layer(Layer): Layer of paddle, which has weight. + name(str, optional): Name of the weight parameter. Default: 'weight'. + + Returns: + Layer, the origin layer without weight norm + + Examples: + .. code-block:: python + + import paddle + from paddle.nn import Conv2D + from paddle.nn.utils import weight_norm, remove_weight_norm + + conv = Conv2D(3, 5, 3) + wn = weight_norm(conv) + print(conv.weight_g) + # Parameter containing: + # Tensor(shape=[5], dtype=float32, place=Place(gpu:0), stop_gradient=False, + # [0., 0., 0., 0., 0.]) + # Conv2D(3, 5, kernel_size=[3, 3], data_format=NCHW) + + remove_weight_norm(conv) + # print(conv.weight_g) + # AttributeError: 'Conv2D' object has no attribute 'weight_g' + """ + for k, hook in layer._forward_pre_hooks.items(): + if isinstance(hook, WeightNorm) and hook.name == name: + hook.remove(layer) + del layer._forward_pre_hooks[k] + return layer + + raise ValueError("weight_norm of '{}' not found in {}".format(name, layer)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8853e78bf3d808108d540496f1d7d9e1d09121c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/__init__.py @@ -0,0 +1,17 @@ +# 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. + +from .export import export # noqa: F401 + +__all__ = ['export'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/export.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/export.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7a9299f5a5265aa3ed8f25c46e36e2e78929ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/onnx/export.py @@ -0,0 +1,106 @@ +# 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. + +import os +from paddle.utils import try_import + +__all__ = [] + + +def export(layer, path, input_spec=None, opset_version=9, **configs): + """ + Export Layer to ONNX format, which can use for inference via onnxruntime or other backends. + For more details, Please refer to `paddle2onnx `_ . + + Args: + layer (Layer): The Layer to be exported. + path (str): The path prefix to export model. The format is ``dirname/file_prefix`` or ``file_prefix`` , + and the exported ONNX file suffix is ``.onnx`` . + input_spec (list[InputSpec|Tensor], optional): Describes the input of the exported model's forward + method, which can be described by InputSpec or example Tensor. If None, all input variables of + the original Layer's forward method would be the inputs of the exported ``ONNX`` model. Default: None. + opset_version(int, optional): Opset version of exported ONNX model. + Now, stable supported opset version include 9, 10, 11. Default: 9. + **configs (dict, optional): Other export configuration options for compatibility. We do not + recommend using these configurations, they may be removed in the future. If not necessary, + DO NOT use them. Default None. + The following options are currently supported: + (1) output_spec (list[Tensor]): Selects the output targets of the exported model. + By default, all return variables of original Layer's forward method are kept as the + output of the exported model. If the provided ``output_spec`` list is not all output variables, + the exported model will be pruned according to the given ``output_spec`` list. + Returns: + None + Examples: + .. code-block:: python + + import paddle + + class LinearNet(paddle.nn.Layer): + def __init__(self): + super(LinearNet, self).__init__() + self._linear = paddle.nn.Linear(128, 10) + + def forward(self, x): + return self._linear(x) + + # Export model with 'InputSpec' to support dynamic input shape. + def export_linear_net(): + model = LinearNet() + x_spec = paddle.static.InputSpec(shape=[None, 128], dtype='float32') + paddle.onnx.export(model, 'linear_net', input_spec=[x_spec]) + + export_linear_net() + + class Logic(paddle.nn.Layer): + def __init__(self): + super(Logic, self).__init__() + + def forward(self, x, y, z): + if z: + return x + else: + return y + + # Export model with 'Tensor' to support pruned model by set 'output_spec'. + def export_logic(): + model = Logic() + x = paddle.to_tensor([1]) + y = paddle.to_tensor([2]) + # Static and run model. + paddle.jit.to_static(model) + out = model(x, y, z=True) + paddle.onnx.export(model, 'pruned', input_spec=[x], output_spec=[out]) + + export_logic() + """ + + p2o = try_import('paddle2onnx') + + file_prefix = os.path.basename(path) + if file_prefix == "": + raise ValueError( + "The input path MUST be format of dirname/file_prefix " + "[dirname\\file_prefix in Windows system], but " + "the file_prefix is empty in received path: {}".format(path) + ) + save_file = path + '.onnx' + + p2o.dygraph2onnx( + layer, + save_file, + input_spec=input_spec, + opset_version=opset_version, + **configs + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd75fd4906ea51cbdf18d534b750b7eddad49425 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/__init__.py @@ -0,0 +1,30 @@ +# 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. + +from .optimizer import Optimizer # noqa: F401 +from .adagrad import Adagrad # noqa: F401 +from .adam import Adam # noqa: F401 +from .adamw import AdamW # noqa: F401 +from .adamax import Adamax # noqa: F401 +from .rmsprop import RMSProp # noqa: F401 +from .adadelta import Adadelta # noqa: F401 +from .sgd import SGD # noqa: F401 +from .momentum import Momentum # noqa: F401 +from .lamb import Lamb # noqa: F401 +from . import lr # noqa: F401 + +__all__ = [ #noqa + 'Optimizer', 'Adagrad', 'Adam', 'AdamW', 'Adamax', 'RMSProp', 'Adadelta', + 'SGD', 'Momentum', 'Lamb' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adadelta.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9c5bac75e87e9943c325234b9ab4f0530ec80f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adadelta.py @@ -0,0 +1,202 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, name_scope +from ..framework import in_dygraph_mode +from paddle import _C_ops, _legacy_C_ops +from ..fluid.dygraph import no_grad + +__all__ = [] + + +class Adadelta(Optimizer): + r""" + **Notes: This API does not support sparse parameter optimization.** + + Adadelta Optimizer. Please refer to this for details: + `ADADELTA: AN ADAPTIVE LEARNING RATE METHOD `_. + + The update is done as follows: + + .. math:: + + E(g_t^2) &= \rho * E(g_{t-1}^2) + (1-\rho) * g^2 + + learning\_rate &= \sqrt{ ( E(dx_{t-1}^2) + \epsilon ) / ( E(g_t^2) + \epsilon ) } + + E(dx_t^2) &= \rho * E(dx_{t-1}^2) + (1-\rho) * (-g*learning\_rate)^2 + + Args: + learning_rate (float|Tensor|LearningRateDecay, optional): The learning rate used to update ``Parameter``. + It can be a float value, a ``Tensor`` with a float type or a LearningRateDecay. The default value is 0.001. + epsilon (float): a small float number for numeric stability. Default 1.0e-6. + rho (float): a floating point value indicating the decay rate. Default 0.95. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1) + linear = paddle.nn.Linear(10, 10) + out = linear(inp) + loss = paddle.mean(out) + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + adadelta = paddle.optimizer.Adadelta(learning_rate=0.1, parameters=linear.parameters(), weight_decay=0.01) + back = out.backward() + adadelta.step() + adadelta.clear_grad() + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + adadelta = paddle.optimizer.Adadelta( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1, + }], + weight_decay=0.01) + out.backward() + adadelta.step() + adadelta.clear_grad() + + """ + + _avg_squared_grad_acc_str = "_avg_squared_grad" + _avg_squared_update_acc_str = "_avg_squared_update" + + def __init__( + self, + learning_rate=0.001, + epsilon=1.0e-6, + rho=0.95, + parameters=None, + weight_decay=None, + grad_clip=None, + name=None, + ): + if learning_rate is None: + raise ValueError("learning_rate is not set.") + if epsilon is None: + raise ValueError("epsilon is not set.") + if rho is None: + raise ValueError("rho is not set.") + super(Adadelta, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name, + ) + self.type = "adadelta" + self._epsilon = epsilon + self._rho = rho + self._default_dict = { + 'epsilon': epsilon, + 'rho': rho, + } + + def _create_accumulators(self, block, parameters): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + if isinstance(parameters, dict): + parameters = parameters.get('params') + + for p in parameters: + self._add_accumulator(self._avg_squared_grad_acc_str, p) + self._add_accumulator(self._avg_squared_update_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + avg_squared_grad_acc = self._get_accumulator( + self._avg_squared_grad_acc_str, param_and_grad[0] + ) + avg_squared_update_acc = self._get_accumulator( + self._avg_squared_update_acc_str, param_and_grad[0] + ) + + if in_dygraph_mode(): + with no_grad(): + _C_ops.adadelta_( + param_and_grad[0], + param_and_grad[1], + avg_squared_grad_acc, + avg_squared_update_acc, + self._rho, + self._epsilon, + ) + return None + + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + # Create the adadelta optimizer op + adadelta_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "AvgSquaredGrad": avg_squared_grad_acc, + "AvgSquaredUpdate": avg_squared_update_acc, + }, + outputs={ + "ParamOut": param_and_grad[0], + "AvgSquaredGradOut": avg_squared_grad_acc, + "AvgSquaredUpdateOut": avg_squared_update_acc, + }, + attrs={"epsilon": self._epsilon, "rho": self._rho}, + stop_gradient=True, + ) + + return adadelta_op + + def _update_param_group(self, parameters): + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self._rho = parameters.get('rho', self._default_dict['rho']) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adagrad.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adagrad.py new file mode 100644 index 0000000000000000000000000000000000000000..634e73ccf3d6d2b303630e36b88cb5e7623022bd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adagrad.py @@ -0,0 +1,182 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable + +__all__ = [] + + +class Adagrad(Optimizer): + r""" + The Adaptive Gradient optimizer (Adagrad for short) use an optimization described + in paper: `Adaptive Subgradient Methods for Online Learning and + Stochastic Optimization `_. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + moment\_out &= moment + grad * grad + + param\_out &= param - \frac{learning\_rate * grad}{\sqrt{moment\_out} + \epsilon} + + + The original paper does not have the ``epsilon`` attribute. It is added here + in our implementation as also proposed `Per-parameter adaptive learning rate + methods `_ + for numerical stability to avoid the division by zero error. + + Args: + learning_rate (float|Tensor): The learning rate used to update ``Parameter``. + It can be a float value or a ``Variable`` with a float type. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-06. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_paddle_fluid_param_attr_aramAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies, + ClipGradByGlobalNorm, ClipGradByNorm and ClipGradByValue. Default None, + meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + initial_accumulator_value (float, optional): Initial value for moment accumulator. + The default value is 0.0. + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.rand(shape=[10, 10]) + linear = paddle.nn.Linear(10, 10) + out = linear(inp) + loss = paddle.mean(out) + adagrad = paddle.optimizer.Adagrad(learning_rate=0.1, + parameters=linear.parameters()) + out.backward() + adagrad.step() + adagrad.clear_grad() + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + adagrad = paddle.optimizer.Adagrad( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1, + }], + weight_decay=0.01) + out.backward() + adagrad.step() + adagrad.clear_grad() + + """ + _moment_acc_str = "moment" + + def __init__( + self, + learning_rate, + epsilon=1.0e-6, + parameters=None, + weight_decay=None, + grad_clip=None, + name=None, + initial_accumulator_value=0.0, + ): + assert learning_rate is not None + assert epsilon is not None + super(Adagrad, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name, + ) + self.type = "adagrad" + self._epsilon = epsilon + self.initial_accumulator_value = initial_accumulator_value + self._default_dict = { + 'epsilon': epsilon, + 'initial_accumulator_value': initial_accumulator_value, + } + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + for p in parameters: + self._add_accumulator( + self._moment_acc_str, + p, + fill_value=self.initial_accumulator_value, + ) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + moment_acc = self._get_accumulator( + self._moment_acc_str, param_and_grad[0] + ) + # Create the adagrad optimizer op + adagrad_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Moment": moment_acc, + "LearningRate": self._create_param_lr(param_and_grad), + }, + outputs={"ParamOut": param_and_grad[0], "MomentOut": moment_acc}, + attrs={"epsilon": self._epsilon}, + stop_gradient=True, + ) + + return adagrad_op + + def _update_param_group(self, parameters): + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self.initial_accumulator_value = parameters.get( + 'initial_accumulator_value', + self._default_dict['initial_accumulator_value'], + ) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adam.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adam.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bd964bf14cb004fd9c5f75edcb2962c97f81f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adam.py @@ -0,0 +1,821 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, _in_legacy_dygraph, in_dygraph_mode +from ..fluid import layers +from ..fluid import unique_name +from ..fluid.layer_helper import LayerHelper +import warnings +from ..fluid.dygraph import base as imperative_base +from collections import defaultdict +import numpy as np +import time + +import paddle +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +class Adam(Optimizer): + r""" + The Adam optimizer uses an optimization described at the end + of section 2 of `Adam paper `_ , + it can dynamically adjusts the learning rate of each parameter using + the 1st moment estimates and the 2nd moment estimates of the gradient. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + t & = t + 1 + + moment\_1\_out & = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad + + moment\_2\_out & = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad + + learning\_rate & = learning\_rate * \ + \frac{\sqrt{1 - {\beta}_2^t}}{1 - {\beta}_1^t} + + param\_out & = param - learning\_rate * \frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + + Related paper: `Adam: A Method for Stochastic Optimization `_ + + Args: + learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``. + It can be a float value or a LRScheduler. The default value is 0.001. + beta1 (float|Tensor, optional): The exponential decay rate for the 1st moment estimates. + It should be a float number or a Tensor with shape [1] and data type as float32. + The default value is 0.9. + beta2 (float|Tensor, optional): The exponential decay rate for the 2nd moment estimates. + It should be a float number or a Tensor with shape [1] and data type as float32. + The default value is 0.999. + epsilon (float|Tensor, optional): A small float value for numerical stability. + It should be a float number or a Tensor with shape [1] and data type as float32. + The default value is 1e-08. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators. + The accumulators are updated at every step. Every element of the two moving-average + is updated in both dense mode and sparse mode. If the size of parameter is very large, + then the update may be very slow. The lazy mode only update the element that has + gradient in current mini-batch, so it will be much more faster. But this mode has + different semantics with the original Adam algorithm and may lead to different result. + The default value is False. + multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false. + use_multi_tensor (bool, optional): Whether to use multi-tensor strategy to update all parameters at once . Default is false. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + Examples: + .. code-block:: python + + import paddle + + linear = paddle.nn.Linear(10, 10) + inp = paddle.rand([10,10], dtype="float32") + out = linear(inp) + loss = paddle.mean(out) + adam = paddle.optimizer.Adam(learning_rate=0.1, + parameters=linear.parameters()) + out.backward() + adam.step() + adam.clear_grad() + + .. code-block:: python + + # Adam with beta1/beta2 as Tensor and weight_decay as float + import paddle + + linear = paddle.nn.Linear(10, 10) + inp = paddle.rand([10,10], dtype="float32") + out = linear(inp) + loss = paddle.mean(out) + + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + + adam = paddle.optimizer.Adam(learning_rate=0.1, + parameters=linear.parameters(), + beta1=beta1, + beta2=beta2, + weight_decay=0.01) + out.backward() + adam.step() + adam.clear_grad() + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + adam = paddle.optimizer.Adam( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1, + 'beta1': 0.8 + }], + weight_decay=0.01, + beta1=0.9) + out.backward() + adam.step() + adam.clear_grad() + + """ + _moment1_acc_str = "moment1" + _moment2_acc_str = "moment2" + _beta1_pow_acc_str = "beta1_pow_acc" + _beta2_pow_acc_str = "beta2_pow_acc" + + def __init__( + self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + parameters=None, + weight_decay=None, + grad_clip=None, + lazy_mode=False, + multi_precision=False, + use_multi_tensor=False, + name=None, + ): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + if not isinstance(beta1, Variable): + if not 0 <= beta1 < 1: + raise ValueError( + "Invaild value of beta1, expect beta1 in [0,1)." + ) + if not isinstance(beta2, Variable): + if not 0 <= beta2 < 1: + raise ValueError( + "Invaild value of beta2, expect beta2 in [0,1)." + ) + if not isinstance(epsilon, Variable): + if not 0 <= epsilon: + raise ValueError( + "Invaild value of epsilon, expect epsilon >= 0." + ) + super(Adam, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name, + ) + self.type = "adam" + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._lazy_mode = lazy_mode + self._multi_precision = multi_precision + self._master_weights = {} + self._default_dict = { + 'beta1': beta1, + 'beta2': beta2, + 'epsilon': epsilon, + 'lazy_mode': lazy_mode, + } + + self._use_multi_tensor = use_multi_tensor + if self._use_multi_tensor: + self._param_dict = self._create_multi_tensor_dict() + self._moment1_dict = self._create_multi_tensor_dict() + self._moment2_dict = self._create_multi_tensor_dict() + self._beta1_pow_acc_dict = self._create_multi_tensor_dict() + self._beta2_pow_acc_dict = self._create_multi_tensor_dict() + self._master_weight_dict = self._create_multi_tensor_dict() + self._master_weight_dict['FP32_LODTensor'] = None + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var( + name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True, + ) + block = self.helper.startup_program.global_block() + block.append_op( + type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32, + }, + ) + self._master_weights[param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = ( + self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + ) + target_param = ( + self._master_weights[param.name] if find_master else param + ) + target_name = target_param.name + if ( + name not in self._accumulators + or target_name not in self._accumulators[name] + ): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name + ) + ) + return self._accumulators[name][target_name] + + def _add_moments_pows(self, p): + acc_dtype = p.dtype + if ( + acc_dtype == core.VarDesc.VarType.FP16 + or acc_dtype == core.VarDesc.VarType.BF16 + ): + acc_dtype = core.VarDesc.VarType.FP32 + self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype) + self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype) + self._add_accumulator( + name=self._beta1_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.9 + if isinstance(self._beta1, Variable) + else self._beta1, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, + device='cpu', + ) + self._add_accumulator( + name=self._beta2_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.999 + if isinstance(self._beta2, Variable) + else self._beta2, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, + device='cpu', + ) + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first and second moments + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_moments_pows(master_p) + continue + if ( + p.dtype == core.VarDesc.VarType.FP16 + and not self._multi_precision + ): + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Adam optimizer." + ) + self._add_moments_pows(p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + moment1 = self._get_accumulator( + self._moment1_acc_str, param_and_grad[0] + ) + moment2 = self._get_accumulator( + self._moment2_acc_str, param_and_grad[0] + ) + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param_and_grad[0] + ) + beta2_pow_acc = self._get_accumulator( + self._beta2_pow_acc_str, param_and_grad[0] + ) + find_master = ( + self._multi_precision + and param_and_grad[0].dtype == core.VarDesc.VarType.FP16 + ) + master_weight = ( + self._master_weights[param_and_grad[0].name] + if find_master + else None + ) + lr = self._create_param_lr(param_and_grad) + # create the adam optimize op + + if framework.in_dygraph_mode(): + found_inf = self._get_auxiliary_var('found_inf') + + _beta1 = ( + self._beta1 + if not isinstance(self._beta1, Variable) + else self._beta1.numpy().item(0) + ) + _beta2 = ( + self._beta2 + if not isinstance(self._beta2, Variable) + else self._beta2.numpy().item(0) + ) + + _, _, _, _, _, _ = _C_ops.adam_( + param_and_grad[0], + param_and_grad[1], + lr, + moment1, + moment2, + beta1_pow_acc, + beta2_pow_acc, + master_weight, + found_inf, + _beta1, + _beta2, + self._epsilon, + self._lazy_mode, + 1000, + find_master, + False, + ) + + return None + + if framework._in_legacy_dygraph(): + + _beta1 = ( + self._beta1 + if not isinstance(self._beta1, Variable) + else self._beta1.numpy().item(0) + ) + _beta2 = ( + self._beta2 + if not isinstance(self._beta2, Variable) + else self._beta2.numpy().item(0) + ) + _, _, _, _, _, _ = _legacy_C_ops.adam( + param_and_grad[0], + param_and_grad[1], + lr, + moment1, + moment2, + beta1_pow_acc, + beta2_pow_acc, + master_weight, + param_and_grad[0], + moment1, + moment2, + beta1_pow_acc, + beta2_pow_acc, + master_weight, + 'epsilon', + self._epsilon, + 'lazy_mode', + self._lazy_mode, + 'min_row_size_to_use_multithread', + 1000, + 'beta1', + _beta1, + 'beta2', + _beta2, + 'multi_precision', + find_master, + ) + + return None + + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "LearningRate": [lr], + "Moment1": [moment1], + "Moment2": [moment2], + "Beta1Pow": [beta1_pow_acc], + "Beta2Pow": [beta2_pow_acc], + } + outputs = { + "ParamOut": [param_and_grad[0]], + "Moment1Out": [moment1], + "Moment2Out": [moment2], + "Beta1PowOut": [beta1_pow_acc], + "Beta2PowOut": [beta2_pow_acc], + } + attrs = { + "lazy_mode": self._lazy_mode, + "min_row_size_to_use_multithread": 1000, + "multi_precision": find_master, + } + + if isinstance(self._beta1, Variable): + inputs['Beta1Tensor'] = self._beta1 + else: + attrs['beta1'] = self._beta1 + if isinstance(self._beta2, Variable): + inputs['Beta2Tensor'] = self._beta2 + else: + attrs['beta2'] = self._beta2 + if isinstance(self._epsilon, Variable): + inputs['EpsilonTensor'] = self._epsilon + else: + attrs['epsilon'] = self._epsilon + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + adam_op = block.append_op( + type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True, + ) + + return adam_op + + @imperative_base.no_grad + @framework.dygraph_only + def step(self): + """ + Execute the optimizer and update parameters once. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + a = paddle.rand([2,13], dtype="float32") + linear = paddle.nn.Linear(13, 5) + # This can be any optimizer supported by dygraph. + adam = paddle.optimizer.Adam(learning_rate = 0.01, + parameters = linear.parameters()) + out = linear(a) + out.backward() + adam.step() + adam.clear_grad() + """ + if not isinstance(self._parameter_list[0], dict): + params_grads = [] + for param in self._parameter_list: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + if in_dygraph_mode(): + if ( + hasattr(grad_var, "is_selected_rows") + and grad_var.is_selected_rows() + and self.regularization is not None + ): + raise RuntimeError( + "Adam don't support weight_decay with sparse parameters, please set it to None." + ) + else: + if ( + hasattr(grad_var, "_is_sparse") + and grad_var._is_sparse() + and self.regularization is not None + ): + raise RuntimeError( + "Adam don't support weight_decay with sparse parameters, please set it to None." + ) + params_grads.append((param, grad_var)) + + optimize_ops = self._apply_optimize( + loss=None, + startup_program=None, + params_grads=params_grads, + param_group_idx=0, + ) + else: + # optimize parameters in groups + for idx, param_group in enumerate(self._param_groups): + params_grads = defaultdict(lambda: list()) + for param in param_group['params']: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + params_grads['params'].append((param, grad_var)) + params_grads.update( + {k: v for k, v in param_group.items() if k != 'params'} + ) + self._apply_optimize( + loss=None, + startup_program=None, + params_grads=params_grads, + param_group_idx=idx, + ) + + def _multi_tensor_init(self, target_block, parameters, param_group_idx): + """ + All parameters used for optimizer (such as: parameters, master_weight, velocity_acc for momentum) calculations are grouped into a python list by data type (float16, float32). + This function will be overridden in the corresponding optimizer file. + Args: + target_block: the block in which the loss tensor is present + parameters: list of parameter tensors for the optimizer + """ + self._create_accumulators(target_block, parameters) + for param in parameters: + moment1 = self._get_accumulator(self._moment1_acc_str, param) + moment2 = self._get_accumulator(self._moment2_acc_str, param) + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param + ) + beta2_pow_acc = self._get_accumulator( + self._beta2_pow_acc_str, param + ) + + if param.dtype == paddle.float32: + self._param_dict['FP32_LODTensor'][param_group_idx].append( + param + ) + self._moment1_dict['FP32_LODTensor'][param_group_idx].append( + moment1 + ) + self._moment2_dict['FP32_LODTensor'][param_group_idx].append( + moment2 + ) + self._beta1_pow_acc_dict['FP32_LODTensor'][ + param_group_idx + ].append(beta1_pow_acc) + self._beta2_pow_acc_dict['FP32_LODTensor'][ + param_group_idx + ].append(beta2_pow_acc) + elif param.dtype == paddle.float16: + self._param_dict['FP16_LODTensor'][param_group_idx].append( + param + ) + self._moment1_dict['FP16_LODTensor'][param_group_idx].append( + moment1 + ) + self._moment2_dict['FP16_LODTensor'][param_group_idx].append( + moment2 + ) + self._beta1_pow_acc_dict['FP16_LODTensor'][ + param_group_idx + ].append(beta1_pow_acc) + self._beta2_pow_acc_dict['FP16_LODTensor'][ + param_group_idx + ].append(beta2_pow_acc) + if self._multi_precision: + self._master_weight_dict['FP16_LODTensor'][ + param_group_idx + ].append(self._master_weights[param.name]) + else: + self._master_weight_dict['FP16_LODTensor'] = None + else: + raise ValueError( + "Now multi_tensor_momentum only support fp32 and fp16 parameters and grad is LOD_TENSOR." + ) + + def _append_optimize_multi_tensor_op( + self, + target_block, + parameters_and_grads, + param_group_idx, + ): + """ + For Multi Tensor, append optimize merged_operator to block. + """ + assert isinstance(target_block, framework.Block) + + grad_dict = {'FP32_LODTensor': [], 'FP16_LODTensor': []} + lr_dict = {'FP32_LODTensor': [], 'FP16_LODTensor': []} + + if isinstance(parameters_and_grads, list): + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + if ( + param_and_grad[0].dtype == paddle.float32 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP32_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP32_LODTensor'].append(lr) + elif ( + param_and_grad[0].dtype == paddle.float16 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP16_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP16_LODTensor'].append(lr) + else: + for param_and_grad in parameters_and_grads['params']: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + param_grad_dict = dict() + param_grad_dict['params'] = param_and_grad + param_grad_dict.update( + { + k: v + for k, v in parameters_and_grads.items() + if k != 'params' + } + ) + param_and_grad = self._update_param_group(param_grad_dict) + if ( + param_and_grad[0].dtype == paddle.float32 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP32_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP32_LODTensor'].append(lr) + elif ( + param_and_grad[0].dtype == paddle.float16 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP16_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP16_LODTensor'].append(lr) + + multi_tensor_list = ['FP32_LODTensor', 'FP16_LODTensor'] + for key in multi_tensor_list: + if len(self._param_dict[key][param_group_idx]) > 0: + find_master = self._multi_precision and key == 'FP16_LODTensor' + + _beta1 = ( + self._beta1 + if not isinstance(self._beta1, Variable) + else self._beta1.numpy().item(0) + ) + _beta2 = ( + self._beta2 + if not isinstance(self._beta2, Variable) + else self._beta2.numpy().item(0) + ) + + if framework._non_static_mode(): + master_weight = self._master_weight_dict[key] + master_weight = ( + master_weight[param_group_idx] + if master_weight is not None + else None + ) + if in_dygraph_mode(): + + _, _, _, _, _, _ = _C_ops.merged_adam_( + self._param_dict[key][param_group_idx], + grad_dict[key], + lr_dict[key], + self._moment1_dict[key][param_group_idx], + self._moment2_dict[key][param_group_idx], + self._beta1_pow_acc_dict[key][param_group_idx], + self._beta2_pow_acc_dict[key][param_group_idx], + master_weight, + _beta1, + _beta2, + self._epsilon, + find_master, + False, + ) + else: + _, _, _, _, _, _ = _legacy_C_ops.merged_adam( + self._param_dict[key][param_group_idx], + grad_dict[key], + lr_dict[key], + self._moment1_dict[key][param_group_idx], + self._moment2_dict[key][param_group_idx], + self._beta1_pow_acc_dict[key][param_group_idx], + self._beta2_pow_acc_dict[key][param_group_idx], + master_weight, + self._param_dict[key][param_group_idx], + self._moment1_dict[key][param_group_idx], + self._moment2_dict[key][param_group_idx], + self._beta1_pow_acc_dict[key][param_group_idx], + self._beta2_pow_acc_dict[key][param_group_idx], + master_weight, + 'epsilon', + self._epsilon, + 'beta1', + _beta1, + 'beta2', + _beta2, + 'multi_precision', + find_master, + ) + else: + inputs = { + "Param": self._param_dict[key][param_group_idx], + "Grad": grad_dict[key], + "LearningRate": lr_dict[key], + "Moment1": self._moment1_dict[key][param_group_idx], + "Moment2": self._moment2_dict[key][param_group_idx], + "Beta1Pow": self._beta1_pow_acc_dict[key][ + param_group_idx + ], + "Beta2Pow": self._beta2_pow_acc_dict[key][ + param_group_idx + ], + } + outputs = { + "ParamOut": self._param_dict[key][param_group_idx], + "Moment1Out": self._moment1_dict[key][param_group_idx], + "Moment2Out": self._moment2_dict[key][param_group_idx], + "Beta1PowOut": self._beta1_pow_acc_dict[key][ + param_group_idx + ], + "Beta2PowOut": self._beta2_pow_acc_dict[key][ + param_group_idx + ], + } + attrs = { + "epsilon": self._epsilon, + "beta1": _beta1, + "beta2": _beta2, + } + if find_master: + inputs["MasterParam"] = self._master_weight_dict[key][ + param_group_idx + ] + outputs["MasterParamOut"] = self._master_weight_dict[ + key + ][param_group_idx] + attrs["multi_precision"] = find_master + target_block.append_op( + type="merged_adam", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True, + ) + return None + + def _update_param_group(self, parameters): + self._beta1 = parameters.get('beta1', self._default_dict['beta1']) + self._beta2 = parameters.get('beta2', self._default_dict['beta2']) + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self._lazy_mode = parameters.get( + 'lazy_mode', self._default_dict['lazy_mode'] + ) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamax.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamax.py new file mode 100644 index 0000000000000000000000000000000000000000..e3959fa67d7ecac7d5a2b3f803036862f1087e00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamax.py @@ -0,0 +1,328 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, name_scope +from paddle import _C_ops, _legacy_C_ops +from ..fluid.dygraph import no_grad + +__all__ = [] + + +class Adamax(Optimizer): + r""" + The Adamax optimizer is implemented based on the Adamax Optimization + in Section 7 of `Adam paper `_. + The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm, + which makes the learning rate update algorithm more stable and simple. + + The parameter ``param_out`` update rule with gradient ``grad``: + + .. math:: + + t & = t + 1 + + moment\_out & = {\beta}_1 * moment + (1 - {\beta}_1) * grad + + inf\_norm\_out & = max({\beta}_2 * inf\_norm + \epsilon, |grad|) + + learning\_rate & = \frac{learning\_rate}{1 - {\beta}_1^t} + + param\_out & = param - learning\_rate * \frac{moment\_out}{inf\_norm\_out} + + Related paper: `Adam: A Method for Stochastic Optimization `_ + + The original paper does not have an ``epsilon`` attribute, + it is added here for numerical stability to prevent the division by 0 error. + + Args: + learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``. + It can be a float value or a LRScheduler. The default value is 0.001. + beta1 (float, optional): The exponential decay rate for the 1st moment estimates. + The default value is 0.9. + beta2 (float, optional): The exponential decay rate for the 2nd moment estimates. + The default value is 0.999. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-08. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + **Notes**: + **Currently, Adamax doesn't support sparse parameter optimization.** + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1) + linear = paddle.nn.Linear(10, 10) + inp = paddle.to_tensor(inp) + out = linear(inp) + loss = paddle.mean(out) + + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + + adam = paddle.optimizer.Adamax(learning_rate=0.1, + parameters=linear.parameters(), + beta1=beta1, + beta2=beta2, + weight_decay=0.01) + out.backward() + adam.step() + adam.clear_grad() + + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + adam = paddle.optimizer.Adamax( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1, + 'beta1': 0.8 + }], + weight_decay=0.01, + beta1=0.9) + out.backward() + adam.step() + adam.clear_grad() + """ + _moment_acc_str = "moment" + _inf_norm_acc_str = "inf_norm" + _beta1_pow_acc_str = "beta1_pow_acc" + + def __init__( + self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + parameters=None, + weight_decay=None, + grad_clip=None, + name=None, + ): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + if not 0 <= beta1 < 1: + raise ValueError("Invaild value of beta1, expect beta1 in [0,1).") + if not 0 <= beta2 < 1: + raise ValueError("Invaild value of beta2, expect beta2 in [0,1).") + if not 0 <= epsilon: + raise ValueError("Invaild value of epsilon, expect epsilon >= 0.") + super(Adamax, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name, + ) + self.type = "adamax" + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._default_dict = { + 'beta1': beta1, + 'beta2': beta2, + 'epsilon': epsilon, + } + + def _create_accumulators(self, block, parameters): + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first moment and infinity norm + for p in parameters: + self._add_accumulator(self._moment_acc_str, p) + self._add_accumulator(self._inf_norm_acc_str, p) + self._add_accumulator( + name=self._beta1_pow_acc_str, + param=p, + fill_value=self._beta1, + shape=[1], + ) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + moment = self._get_accumulator(self._moment_acc_str, param_and_grad[0]) + inf_norm = self._get_accumulator( + self._inf_norm_acc_str, param_and_grad[0] + ) + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param_and_grad[0] + ) + + if framework.in_dygraph_mode(): + _C_ops.adamax_( + param_and_grad[0], + param_and_grad[1], + self._create_param_lr(param_and_grad), + moment, + inf_norm, + beta1_pow_acc, + self._beta1, + self._beta2, + self._epsilon, + ) + elif framework._in_legacy_dygraph(): + _legacy_C_ops.adamax( + param_and_grad[0], + param_and_grad[1], + self._create_param_lr(param_and_grad), + moment, + inf_norm, + beta1_pow_acc, + param_and_grad[0], + moment, + inf_norm, + "beta1", + self._beta1, + "beta2", + self._beta2, + "epsilon", + self._epsilon, + ) + else: + # create the adamax optimize op + adamax_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": self._create_param_lr(param_and_grad), + "Moment": moment, + "InfNorm": inf_norm, + "Beta1Pow": beta1_pow_acc, + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": moment, + "InfNormOut": inf_norm, + }, + attrs={ + "beta1": self._beta1, + "beta2": self._beta2, + "epsilon": self._epsilon, + }, + stop_gradient=True, + ) + + return adamax_op + + def _finish_update(self, block, parameters_and_grads): + """Update Beta1 Power accumulator""" + assert isinstance(block, framework.Block) + if isinstance(parameters_and_grads, list): + for param, grad in parameters_and_grads: + if grad is None or param.stop_gradient is True: + continue + if framework.in_dygraph_mode(): + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param + ) + with no_grad(): + tmp = _C_ops.scale( + beta1_pow_acc, self._beta1, 0.0, True + ) + beta1_pow_acc.copy_(tmp, False) + continue + with param.block.program._optimized_guard( + [param, grad] + ), name_scope('adamax'): + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param + ) + block.append_op( + type="scale", + inputs={"X": beta1_pow_acc}, + outputs={"Out": beta1_pow_acc}, + attrs={"scale": self._beta1}, + stop_gradient=True, + ) + else: + for param, grad in parameters_and_grads['params']: + if grad is None or param.stop_gradient is True: + continue + if framework.in_dygraph_mode(): + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param + ) + self._beta1 = parameters_and_grads.get( + 'beta1', self._default_dict['beta1'] + ) + with no_grad(): + tmp = _C_ops.scale( + beta1_pow_acc, self._beta1, 0.0, True + ) + beta1_pow_acc.copy_(tmp, False) + continue + + with param.block.program._optimized_guard( + [param, grad] + ), name_scope('adamax'): + beta1_pow_acc = self._get_accumulator( + self._beta1_pow_acc_str, param + ) + self._beta1 = parameters_and_grads.get( + 'beta1', self._default_dict['beta1'] + ) + block.append_op( + type="scale", + inputs={"X": beta1_pow_acc}, + outputs={"Out": beta1_pow_acc}, + attrs={"scale": self._beta1}, + stop_gradient=True, + ) + + def _update_param_group(self, parameters): + self._beta1 = parameters.get('beta1', self._default_dict['beta1']) + self._beta2 = parameters.get('beta2', self._default_dict['beta2']) + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamw.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamw.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe23c84a2a9179a5fcbb32f7f72d9956350263b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/adamw.py @@ -0,0 +1,622 @@ +# Copyright (c) 2021 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. + +import warnings +from collections import defaultdict +from .optimizer import Optimizer +from .lr import LRScheduler +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, Parameter +from ..fluid import unique_name +from ..fluid import layers +from ..fluid.layer_helper import LayerHelper +from ..fluid.clip import GradientClipBase +from ..fluid.dygraph import base as imperative_base +from collections.abc import Callable +from .. import _C_ops, _legacy_C_ops +import paddle + +__all__ = [] + + +class AdamW(Optimizer): + r""" + The AdamW optimizer is implemented based on the AdamW Optimization + in paper `DECOUPLED WEIGHT DECAY REGULARIZATION `_. + it can resolves the problem of L2 regularization failure in the Adam optimizer. + + .. math:: + + t & = t + 1 + + moment\_1\_out & = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad + + moemnt\_2\_out & = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad + + learning\_rate & = learning\_rate * + \frac{\sqrt{1 - {\beta}_2^t}}{1 - {beta}_1^t} + + param\_out & = param - learning\_rate * (\frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + \lambda * param) + + + Args: + learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``. + It can be a float value or a LRScheduler. The default value is 0.001. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + beta1 (float|Tensor, optional): The exponential decay rate for the 1st moment estimates. + It should be a float number or a Tensor with shape [1] and data type as float32. + The default value is 0.9. + beta2 (float|Tensor, optional): The exponential decay rate for the 2nd moment estimates. + It should be a float number or a Tensor with shape [1] and data type as float32. + The default value is 0.999. + epsilon (float, optional): A small float value for numerical stability. + The default value is 1e-08. + weight_decay (float|Tensor, optional): The weight decay coefficient, it can be float or Tensor. The default value is 0.01. + lr_ratio (function|None, optional): If it is not None, + the learning rate will be updated with layerwise learning rate ratio. + Otherwise, the learning rate is the original. + Default: None. + apply_decay_param_fun (function|None, optional): If it is not None, + only tensors that makes apply_decay_param_fun(Tensor.name)==True + will be updated with weight decay. It only works when we want to specify tensors. + Default: None. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators. + The accumulators are updated at every step. Every element of the two moving-average + is updated in both dense mode and sparse mode. If the size of parameter is very large, + then the update may be very slow. The lazy mode only update the element that has + gradient in current mini-batch, so it will be much more faster. But this mode has + different semantics with the original Adam algorithm and may lead to different result. + The default value is False. + multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + **Notes**: + **Currently, AdamW doesn't support sparse parameter optimization.** + + Examples: + .. code-block:: python + + import paddle + + linear = paddle.nn.Linear(10, 10) + inp = paddle.rand([10,10], dtype="float32") + out = linear(inp) + loss = paddle.mean(out) + + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + + opt = paddle.optimizer.AdamW(learning_rate=0.1, + parameters=linear.parameters(), + beta1=beta1, + beta2=beta2, + weight_decay=0.01) + out.backward() + opt.step() + opt.clear_grad() + + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + opt = paddle.optimizer.AdamW( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1, + 'beta1': 0.8 + }], + weight_decay=0.01, + beta1=0.9) + out.backward() + opt.step() + opt.clear_grad() + + """ + + _moment1_acc_str = "moment1" + _moment2_acc_str = "moment2" + _beta1_pow_acc_str = "beta1_pow_acc" + _beta2_pow_acc_str = "beta2_pow_acc" + + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + parameters=None, + weight_decay=0.01, + lr_ratio=None, + apply_decay_param_fun=None, + grad_clip=None, + lazy_mode=False, + multi_precision=False, + name=None): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + if not 0 <= beta1 < 1: + raise ValueError("Invaild value of beta1, expect beta1 in [0,1).") + if not 0 <= beta2 < 1: + raise ValueError("Invaild value of beta2, expect beta2 in [0,1).") + if not 0 <= epsilon: + raise ValueError("Invaild value of epsilon, expect epsilon >= 0.") + if not isinstance(weight_decay, float) and \ + not isinstance(weight_decay, framework.Variable): + raise TypeError("weight_decay should be float or Tensor.") + if lr_ratio is not None: + assert isinstance(lr_ratio, Callable) + if not core.is_compiled_with_cuda(): + raise NotImplementedError( + "'lr_ratio' is unimplemented in CPU, XPU and NPU") + + if parameters is not None: + # paddle.Tensor is also iterable, so here we don't check whether + # the input is iterable, if the input is paddle.Tensor, the + # list(paddle.Tensor) will be a error value + if isinstance(parameters, (paddle.Tensor, core.eager.Tensor)): + raise TypeError( + "`parameters` argument given to the optimizer should be " + "an iterable of paddle Tensors, but got argument type is `{}`." + .format(type(parameters))) + if isinstance(parameters, dict): + raise TypeError( + "`parameters` argument should not get dict type, " + "if parameter groups is needed, please set `parameters`" + " as list of dict") + self._parameter_list = list(parameters) + else: + self._parameter_list = None + + self._name = name + if framework._non_static_mode(): + if self._parameter_list is None: + raise AttributeError( + "parameters argument given to the Optimizer should not be None in dygraph mode." + ) + + if not isinstance(learning_rate, (float, LRScheduler)): + raise TypeError( + "learning rate should be float or LRScheduler, got %s here" % + type(learning_rate)) + if grad_clip is not None: + if not isinstance(grad_clip, GradientClipBase): + raise TypeError( + "'grad_clip' should be an instance of GradientClipBase's derived class" + ) + + self._dtype = None + # Infer the dtype form parameter + if self._parameter_list: + if isinstance(self._parameter_list[0], dict): + for param_group in self._parameter_list: + assert 'params' in param_group, \ + 'params should be set in parameters if parameter groups are optimized in different options' + self._dtype = self._parameter_list[0]['params'][0].dtype + else: + self._dtype = self._parameter_list[0].dtype + + # each program should have a independent learning rate + # program -> tensor(learning_rate) + self._learning_rate_map = dict() + # Dictionary of accumulators. Some optimizer subclasses need to + # allocate and manage extra tensors associated with the parameters + # to train. These tensors are called accumulators. + # {accum_name : { paramter_name : accumulator_for_parameter, ...}, ...} + self._accumulators = defaultdict(lambda: dict()) + self.helper = None + self._opti_name_list = [] + self._accumulators_holder = {} + self._param_device_map = dict() + self.clear_gradients = self.clear_grad + + self.type = "adamw" + self._learning_rate = learning_rate + self._params_name = set() + self._apply_decay_param_fun = apply_decay_param_fun + self._weight_decay = weight_decay + self._grad_clip = grad_clip + self._lr_ratio = lr_ratio + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._lazy_mode = lazy_mode + self._multi_precision = multi_precision + self._master_weights = {} + + self._default_dict = { + 'weight_decay': weight_decay, + 'beta1': beta1, + 'beta2': beta2, + 'epsilon': epsilon, + 'lazy_mode': lazy_mode, + 'grad_clip': grad_clip + } + + self._param_groups = [] + if self._parameter_list and isinstance(self._parameter_list[0], dict): + for param_group in self._parameter_list: + self._add_param_group(param_group.copy()) + else: + self._param_groups = self._parameter_list + + self._use_multi_tensor = None + self.regularization = None + self._auxiliary_vars = {} + + def _set_auxiliary_var(self, key, val): + self._auxiliary_vars[key] = val + + def _get_auxiliary_var(self, key): + if key in self._auxiliary_vars: + return self._auxiliary_vars[key] + else: + return None + + def _add_param_group(self, param_group): + """ + Add a param group to parameter_list. + + Args: + param_group (dict): The group of Tensors to be optimzed with + different optimization options. + """ + params = param_group['params'] + if isinstance(params, Parameter): + param_group['params'] = [params] + elif isinstance(params, set): + raise TypeError( + "optimizer parameters should be in ordered collections," + "but received set, please use list instead.") + else: + param_group['params'] = list(params) + + # Update optimization options for each groups + for k, v in self._default_dict.items(): + param_group.setdefault(k, v) + + param_set = set() + for group in self._param_groups: + param_set.update(set(group['params'])) + + if not param_set.isdisjoint(set(param_group['params'])): + raise ValueError( + "some parameters appear in more than one parameter group") + + for param in param_group['params']: + param.optimize_attr['learning_rate'] = param_group.get( + 'learning_rate', 1.) + + self._param_groups.append(param_group) + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + target_param = self._master_weights[ + param.name] if find_master else param + target_name = target_param.name + if (name not in self._accumulators + or target_name not in self._accumulators[name]): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name)) + return self._accumulators[name][target_name] + + def _add_moments_pows(self, p): + acc_dtype = p.dtype + if acc_dtype == core.VarDesc.VarType.FP16: + acc_dtype = core.VarDesc.VarType.FP32 + self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype) + self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype) + self._add_accumulator( + name=self._beta1_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.9 if isinstance(self._beta1, Variable) \ + else self._beta1, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + self._add_accumulator( + name=self._beta2_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.999 if isinstance(self._beta2, Variable) \ + else self._beta2, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first and second moments + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_moments_pows(master_p) + continue + if p.dtype == core.VarDesc.VarType.FP16 and not self._multi_precision: + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Adam optimizer." + ) + self._add_moments_pows(p) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + param, grad = param_and_grad + + # Whether we should do weight decay for the parameter. + with_decay = True + if self._apply_decay_param_fun is not None \ + and not self._apply_decay_param_fun(param.name): + with_decay = False + + moment1 = self._get_accumulator(self._moment1_acc_str, + param_and_grad[0]) + moment2 = self._get_accumulator(self._moment2_acc_str, + param_and_grad[0]) + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param_and_grad[0]) + beta2_pow_acc = self._get_accumulator(self._beta2_pow_acc_str, + param_and_grad[0]) + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + master_weight = (self._master_weights[param_and_grad[0].name] + if find_master else None) + lr = self._create_param_lr(param_and_grad) + + # create the adamw optimize op + if framework._non_static_mode(): + lr_ratio_ = 1. if self._lr_ratio is None else self._lr_ratio( + param_and_grad[0]) + + _beta1 = self._beta1 if not isinstance( + self._beta1, Variable) else self._beta1.numpy().item(0) + _beta2 = self._beta2 if not isinstance( + self._beta2, Variable) else self._beta2.numpy().item(0) + + if framework.in_dygraph_mode(): + found_inf = self._get_auxiliary_var('found_inf') + _, _, _, _, _, _ = _C_ops.adamw_( + param_and_grad[0], param_and_grad[1], lr, moment1, moment2, + beta1_pow_acc, beta2_pow_acc, master_weight, found_inf, + _beta1, _beta2, self._epsilon, lr_ratio_, + self._weight_decay, with_decay, self._lazy_mode, 1000, + find_master, False) + else: + _, _, _, _, _, _ = _legacy_C_ops.adamw( + param_and_grad[0], param_and_grad[1], lr, moment1, moment2, + beta1_pow_acc, beta2_pow_acc, master_weight, + param_and_grad[0], moment1, moment2, beta1_pow_acc, + beta2_pow_acc, master_weight, 'epsilon', self._epsilon, + 'lazy_mode', self._lazy_mode, + 'min_row_size_to_use_multithread', 1000, 'beta1', _beta1, + 'beta2', _beta2, "with_decay", with_decay, 'coeff', + self._weight_decay, 'multi_precision', find_master, + 'lr_ratio', lr_ratio_) + return None + + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "LearningRate": [lr], + "Moment1": [moment1], + "Moment2": [moment2], + "Beta1Pow": [beta1_pow_acc], + "Beta2Pow": [beta2_pow_acc], + } + + # Pass found_inf to adamw, to skip update for not only param, but also momentum and beta_pow + found_inf = self._get_auxiliary_var('found_inf') + + if found_inf: + inputs['SkipUpdate'] = found_inf + + outputs = { + "ParamOut": [param_and_grad[0]], + "Moment1Out": [moment1], + "Moment2Out": [moment2], + "Beta1PowOut": [beta1_pow_acc], + "Beta2PowOut": [beta2_pow_acc], + } + attrs = { + "lazy_mode": + self._lazy_mode, + "min_row_size_to_use_multithread": + 1000, + "multi_precision": + find_master, + "with_decay": + with_decay, + "coeff": + self._weight_decay, + "lr_ratio": + 1. if self._lr_ratio is None else self._lr_ratio(param_and_grad[0]) + } + + if isinstance(self._beta1, Variable): + inputs['Beta1Tensor'] = self._beta1 + else: + attrs['beta1'] = self._beta1 + if isinstance(self._beta2, Variable): + inputs['Beta2Tensor'] = self._beta2 + else: + attrs['beta2'] = self._beta2 + if isinstance(self._epsilon, Variable): + inputs['EpsilonTensor'] = self._epsilon + else: + attrs['epsilon'] = self._epsilon + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + adamw_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return adamw_op + + def __str__(self): + return " ".join(["Weight Decay, params:", ",".join(self._params_name)]) + + @imperative_base.no_grad + @framework.dygraph_only + def step(self): + """ + Execute the optimizer and update parameters once. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + a = paddle.rand([2,13], dtype="float32") + linear = paddle.nn.Linear(13, 5) + # This can be any optimizer supported by dygraph. + opt = paddle.optimizer.AdamW(learning_rate = 0.01, + parameters = linear.parameters()) + out = linear(a) + out.backward() + opt.step() + opt.clear_grad() + """ + if not isinstance(self._parameter_list[0], dict): + params_grads = [] + for param in self._parameter_list: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + if framework.in_dygraph_mode(): + if hasattr(grad_var, "is_selected_rows" + ) and grad_var.is_selected_rows( + ) and self.regularization is not None: + raise RuntimeError( + "AdamW don't support weight_decay with sparse parameters, please set it to None." + ) + else: + if hasattr( + grad_var, "_is_sparse") and grad_var._is_sparse( + ) and self.regularization is not None: + raise RuntimeError( + "AdamW don't support weight_decay with sparse parameters, please set it to None." + ) + params_grads.append((param, grad_var)) + + optimize_ops = self._apply_optimize(loss=None, + startup_program=None, + params_grads=params_grads) + else: + # optimize parameters in groups + for param_group in self._param_groups: + params_grads = defaultdict(lambda: list()) + for param in param_group['params']: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + if framework.in_dygraph_mode(): + if hasattr(grad_var, "is_selected_rows" + ) and grad_var.is_selected_rows( + ) and self.regularization is not None: + raise RuntimeError( + "AdamW don't support weight_decay with sparse parameters, please set it to None." + ) + else: + if hasattr(grad_var, + "_is_sparse") and grad_var._is_sparse( + ) and self.regularization is not None: + raise RuntimeError( + "AdamW don't support weight_decay with sparse parameters, please set it to None." + ) + params_grads['params'].append((param, grad_var)) + params_grads.update( + {k: v + for k, v in param_group.items() if k != 'params'}) + self._apply_optimize(loss=None, + startup_program=None, + params_grads=params_grads) + + def _update_param_group(self, parameters): + self._beta1 = parameters.get('beta1', self._default_dict['beta1']) + self._beta2 = parameters.get('beta2', self._default_dict['beta2']) + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self._lazy_mode = parameters.get('lazy_mode', + self._default_dict['lazy_mode']) + self._weight_decay = parameters.get('weight_decay', + self._default_dict['weight_decay']) + parameters = parameters.get('params') + + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lamb.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lamb.py new file mode 100644 index 0000000000000000000000000000000000000000..cbdf91ed2bfbb86db54fc645fa05a8c169ec6a3b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lamb.py @@ -0,0 +1,338 @@ +# Copyright (c) 2022 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable +from ..fluid import layers +from ..fluid import unique_name +from ..fluid.layer_helper import LayerHelper +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.executor import global_scope +import paddle + +__all__ = [] + + +class Lamb(Optimizer): + r""" + LAMB (Layer-wise Adaptive Moments optimizer for Batching training) Optimizer. + + LAMB Optimizer is designed to scale up the batch size of training without losing + accuracy, which supports adaptive element-wise updating and accurate layer-wise + correction. For more information, please refer to `Large Batch Optimization for + Deep Learning: Training BERT in 76 minutes `_ . + + The updating of parameters follows: + + .. math:: + + m_t &= \beta_1 m_{t - 1}+ (1 - \beta_1)g_t + + v_t &= \beta_2 v_{t - 1} + (1 - \beta_2)g_t^2 + + m_t &= \frac{m_t}{\beta_1^t} + + v_t &= \frac{v_t}{\beta_2^t} + + r_t &= \frac{m_t}{\sqrt{v_t}+\epsilon} + + w_t &= w_{t-1} -\eta_t \frac{\left \| w_{t-1}\right \|}{\left \| r_t + \lambda w_{t-1}\right \|} (r_t + \lambda w_{t-1}) + + + where :math:`m` is the 1st moment, and :math:`v` the 2nd moment, :math:`\\eta` the + learning rate, :math:`\\lambda` the LAMB weight decay rate. + + Args: + learning_rate (float|Variable, optional): the learning rate used to update parameters. \ + Can be a float value or a Variable with data type float32. Default 0.001. + lamb_weight_decay (float, optional): The LAMB weight decay rate. Default 0.01. Remind that weight_decay should be None. + beta1 (float, optional): The exponential decay rate for the 1st moment estimates. + Default 0.9. + beta2 (float, optional): The exponential decay rate for the 2nd moment estimates. + Default 0.999. + epsilon (float, optional): A small float value for numerical stability. Default 1e-6. + parameters (Iterable, optional): Iterable of ``Variable`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_paddle_fluid_clip_ClipGradByGlobalNorm` , :ref:`api_paddle_fluid_clip_ClipGradByNorm` , + :ref:`api_paddle_fluid_clip_ClipGradByValue` ). If you want better convergence, it is recommended + to use :ref:`api_paddle_fluid_clip_ClipGradByGlobalNorm` . Default None, meaning there is no gradient clipping. + name(str|None): For detailed information, please refer to + :ref:`api_guide_Name` . Usually name is no need to set and None by default. + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform(shape=[10, 10], dtype='float32', min=-0.1, max=0.1) + linear = paddle.nn.Linear(10, 10) + out = linear(inp) + loss = paddle.mean(out) + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.85], dtype="float32") + lamb = paddle.optimizer.Lamb(learning_rate=0.002, parameters=linear.parameters(), lamb_weight_decay=0.01) + back = out.backward() + lamb.step() + lamb.clear_grad() + + """ + _moment1_acc_str = "moment1" + _moment2_acc_str = "moment2" + _beta1_pow_acc_str = "beta1_pow_acc" + _beta2_pow_acc_str = "beta2_pow_acc" + + def __init__(self, + learning_rate=0.001, + lamb_weight_decay=0.01, + beta1=0.9, + beta2=0.999, + epsilon=1e-6, + parameters=None, + grad_clip=None, + exclude_from_weight_decay_fn=None, + multi_precision=False, + name=None): + assert learning_rate is not None + assert beta1 is not None + assert beta2 is not None + assert epsilon is not None + super(Lamb, self).__init__(learning_rate=learning_rate, + parameters=parameters, + weight_decay=None, + grad_clip=grad_clip, + name=name) + self.type = "lamb" + self._beta1 = beta1 + self._beta2 = beta2 + self._epsilon = epsilon + self._lamb_weight_decay = lamb_weight_decay + self._exclude_from_weight_decay_fn = exclude_from_weight_decay_fn + self._default_dict = { + 'beta1': beta1, + 'beta2': beta2, + 'epsilon': epsilon, + 'lamb_weight_decay': lamb_weight_decay, + 'exclude_from_weight_decay_fn': exclude_from_weight_decay_fn, + } + self._master_weights = {} + self._used_master_weights = {} + # TODO(zengjinle): expose API as soon as possible + self._multi_precision = multi_precision + + def _get_parameter(self, name, scope=None): + if scope is None: + scope = global_scope() + + p_t = scope.find_var(name).get_tensor() + + master_name = self._used_master_weights.get(name) + if master_name is not None: + master_p_t = scope.find_var(master_name).get_tensor() + assert master_p_t._dtype() != p_t._dtype() + assert master_p_t.shape() == p_t.shape() + else: + master_p_t = None + return p_t, master_p_t + + def _create_master_weight(self, param): + assert self._multi_precision + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first and second moments + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_moments_pows(master_p) + else: + self._add_moments_pows(p) + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + target_param = self._master_weights[ + param.name] if find_master else param + target_name = target_param.name + if (name not in self._accumulators + or target_name not in self._accumulators[name]): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name)) + return self._accumulators[name][target_name] + + def _add_moments_pows(self, p): + acc_dtype = p.dtype + if acc_dtype == core.VarDesc.VarType.FP16: + acc_dtype = core.VarDesc.VarType.FP32 + + self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype) + self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype) + self._add_accumulator( + name=self._beta1_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.9 if isinstance(self._beta1, Variable) \ + else self._beta1, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + self._add_accumulator( + name=self._beta2_pow_acc_str, + param=p, + dtype=acc_dtype, + fill_value=0.999 if isinstance(self._beta2, Variable) \ + else self._beta2, + shape=[1], + type=core.VarDesc.VarType.LOD_TENSOR, device='cpu') + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + block.program._use_lamb = True + + moment1 = self._get_accumulator(self._moment1_acc_str, + param_and_grad[0]) + moment2 = self._get_accumulator(self._moment2_acc_str, + param_and_grad[0]) + beta1_pow_acc = self._get_accumulator(self._beta1_pow_acc_str, + param_and_grad[0]) + beta2_pow_acc = self._get_accumulator(self._beta2_pow_acc_str, + param_and_grad[0]) + + if self._exclude_from_weight_decay_fn is not None \ + and self._exclude_from_weight_decay_fn(param_and_grad[0]): + weight_decay = 0.0 + else: + weight_decay = self._lamb_weight_decay + lr = self._create_param_lr(param_and_grad) + + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + p_name = param_and_grad[0].name + if find_master: + master_weight = self._master_weights[p_name] + self._used_master_weights[p_name] = master_weight.name + else: + master_weight = None + found_inf = self._get_auxiliary_var('found_inf') + + if framework.in_dygraph_mode(): + _C_ops.lamb_(param_and_grad[0], param_and_grad[1], lr, moment1, + moment2, beta1_pow_acc, beta2_pow_acc, master_weight, + found_inf, weight_decay, self._beta1, self._beta2, + self._epsilon, find_master) + return None + if framework._non_static_mode(): + _legacy_C_ops.lamb(param_and_grad[0], param_and_grad[1], lr, + moment1, moment2, beta1_pow_acc, beta2_pow_acc, + master_weight, param_and_grad[0], moment1, + moment2, beta1_pow_acc, beta2_pow_acc, + master_weight, 'beta1', self._beta1, 'beta2', + self._beta2, 'epsilon', self._epsilon, + 'weight_decay', weight_decay, 'multi_precision', + find_master) + return None + + # create the lamb optimize op + inputs = { + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": lr, + "Moment1": moment1, + "Moment2": moment2, + "Beta1Pow": beta1_pow_acc, + "Beta2Pow": beta2_pow_acc + } + outputs = { + "ParamOut": param_and_grad[0], + "Moment1Out": moment1, + "Moment2Out": moment2, + "Beta1PowOut": beta1_pow_acc, + "Beta2PowOut": beta2_pow_acc + } + attrs = { + "beta1": self._beta1, + "beta2": self._beta2, + "epsilon": self._epsilon, + "weight_decay": weight_decay, + "multi_precision": find_master, + } + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + if found_inf: + inputs["SkipUpdate"] = found_inf + + lamb_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return lamb_op + + def _update_param_group(self, parameters): + self._beta1 = parameters.get('beta1', self._default_dict['beta1']) + self._beta2 = parameters.get('beta2', self._default_dict['beta2']) + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self._lamb_weight_decay = parameters.get( + 'lamb_weight_decay', self._default_dict['lamb_weight_decay']) + self._exclude_from_weight_decay_fn = parameters.get( + 'exclude_from_weight_decay_fn', + self._default_dict['exclude_from_weight_decay_fn']) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lr.py new file mode 100644 index 0000000000000000000000000000000000000000..77a332cbdd997142258ef79b0ee4e2381cb00fd1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/lr.py @@ -0,0 +1,2124 @@ +# 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. + +import math +import numpy +import warnings +from paddle import Tensor +import paddle.fluid.core as core +from ..fluid.framework import _in_legacy_dygraph + +__all__ = [ # noqa + 'LRScheduler', + 'NoamDecay', + 'PiecewiseDecay', + 'NaturalExpDecay', + 'InverseTimeDecay', + 'PolynomialDecay', + 'LinearWarmup', + 'ExponentialDecay', + 'MultiStepDecay', + 'StepDecay', + 'LambdaDecay', + 'ReduceOnPlateau', + 'CosineAnnealingDecay', + 'MultiplicativeDecay', + 'OneCycleLR', + 'CyclicLR', +] + + +class LRScheduler(object): + """ + + LRScheduler Base class. Define the common interface of a learning rate scheduler. + + User can import it by ``from paddle.optimizer.lr import LRScheduler`` , + + then overload it for your subclass and have a custom implementation of ``get_lr()`` . + + Otherwise, an ``NotImplementedError`` exception will be thrown. + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + instance to schedule learning rate. + + Examples: + Here is an example of a simple ``StepDecay`` implementation. + + .. code-block:: python + + import paddle + from paddle.optimizer.lr import LRScheduler + + class StepDecay(LRScheduler): + def __init__(self, + learning_rate, + step_size, + gamma=0.1, + last_epoch=-1, + verbose=False): + if not isinstance(step_size, int): + raise TypeError( + "The type of 'step_size' must be 'int', but received %s." % + type(step_size)) + if gamma >= 1.0: + raise ValueError('gamma should be < 1.0.') + + self.step_size = step_size + self.gamma = gamma + super(StepDecay, self).__init__(learning_rate, last_epoch, verbose) + + def get_lr(self): + i = self.last_epoch // self.step_size + return self.base_lr * (self.gamma**i) + + """ + + def __init__(self, learning_rate=0.1, last_epoch=-1, verbose=False): + if not isinstance(learning_rate, (float, int)): + raise TypeError( + "The type of learning rate must be float, but received {}".format( + type(learning_rate) + ) + ) + self.base_lr = float(learning_rate) + self.last_lr = float(learning_rate) + self.last_epoch = last_epoch + self.verbose = verbose + self._var_name = None + + self.step() + + def __call__(self): + """ + Return lastest computed learning rate on current epoch. + """ + return self.last_lr + + def step(self, epoch=None): + """ + + ``step`` should be called after ``optimizer.step`` . It will update the learning rate in optimizer according to current ``epoch`` . + The new learning rate will take effect on next ``optimizer.step`` . + + Args: + epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1. + + Returns: + None + + """ + if epoch is None: + self.last_epoch += 1 + self.last_lr = self.get_lr() + else: + self.last_epoch = epoch + if hasattr(self, "_get_closed_form_lr"): + self.last_lr = self._get_closed_form_lr() + else: + self.last_lr = self.get_lr() + + if self.verbose: + print( + 'Epoch {}: {} set learning rate to {}.'.format( + self.last_epoch, self.__class__.__name__, self.last_lr + ) + ) + + def state_dict(self): + """ + + Returns the state of the scheduler as a :class:`dict`. + + It is a subset of ``self.__dict__`` . + """ + self.state_keys() + state_dict = {} + for key in self.keys: + if key not in self.__dict__: + continue + value = self.__dict__[key] + if isinstance(value, Tensor): + assert value.shape == [ + 1 + ], "shape of Tensor in state_dict must be [1] {}".format( + value.shape + ) + value = value.numpy()[0] + state_dict[key] = value + + return state_dict + + # For those subclass who overload LRScheduler, "last_epoch, last_lr" will be saved by default. + # (Note): you can change it for your subclass. + def state_keys(self): + """ + + For those subclass who overload ``LRScheduler`` (Base Class). Acquiescently, "last_epoch, last_lr" will be saved by ``self.keys = ['last_epoch', 'last_lr']`` . + + ``last_epoch`` is the current epoch num, and ``last_lr`` is the current learning rate. + + If you want to change the default behavior, you should have a custom implementation of ``_state_keys()`` to redefine ``self.keys`` . + + """ + self.keys = ['last_epoch', 'last_lr'] + + def set_state_dict(self, state_dict): + """ + + Loads the schedulers state. + """ + self.state_keys() + for key in self.keys: + if key in state_dict: + self.__dict__[key] = state_dict[key] + else: + raise RuntimeError( + "Please check whether state_dict is correct for optimizer. Can't find [ {} ] in state_dict".format( + key + ) + ) + if len(state_dict) > len(self.keys): + warnings.warn( + "There are some unused values in state_dict. Maybe the optimizer have different 'LearningRateDecay' when invoking state_dict and set_dict" + ) + + # alias for set_state_dict + set_dict = set_state_dict + + def get_lr(self): + """ + + For those subclass who overload ``LRScheduler`` (Base Class), User should have a custom implementation of ``get_lr()`` . + + Otherwise, an ``NotImplementedError`` exception will be thrown. + """ + # calculate by python float + raise NotImplementedError + + +class NoamDecay(LRScheduler): + r""" + + Applies Noam Decay to the initial learning rate. + + The algorithm can be described as following. + + .. math:: + + new\_learning\_rate = learning\_rate * d_{model}^{-0.5} * min(epoch^{-0.5}, epoch * warmup\_steps^{-1.5}) + + Please reference `attention is all you need `_ + + + Args: + d$_{model}$(int): The dimensionality of input and output feature vector of model. It is a python int number. + warmup_steps(int): The number of warmup steps. A super parameter. It is a python int number + learning_rate (float): The initial learning rate. It is a python float number. Default: 1.0. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``NoamDecay`` instance to schedule learning rate. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + """ + + def __init__( + self, + d_model, + warmup_steps, + learning_rate=1.0, + last_epoch=-1, + verbose=False, + ): + self.d_model = d_model + self.warmup_steps = warmup_steps + super(NoamDecay, self).__init__(learning_rate, last_epoch, verbose) + + def get_lr(self): + if self.last_epoch == 0: + a = 1 + else: + a = self.last_epoch**-0.5 + b = self.warmup_steps**-1.5 * self.last_epoch + return self.base_lr * (self.d_model**-0.5) * min(a, b) + + +class PiecewiseDecay(LRScheduler): + """ + + Piecewise learning rate scheduler. + + The algorithm can be described as the code below: + + .. code-block:: text + + boundaries = [100, 200] + values = [1.0, 0.5, 0.1] + if epoch < 100: + learning_rate = 1.0 + elif 100 <= global_step < 200: + learning_rate = 0.5 + else: + learning_rate = 0.1 + + Args: + boundaries(list|tuple): A list/tuple of steps numbers. The type of element in the list is python int. + values(list|tuple): A list/tuple of learning rate values that will be picked during different epoch boundaries. + The type of element in the list is python float. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``PiecewiseDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries=[3, 6, 9], values=[0.1, 0.2, 0.3, 0.4], verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries=[3, 6, 9], values=[0.1, 0.2, 0.3, 0.4], verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__(self, boundaries, values, last_epoch=-1, verbose=False): + self.boundaries = boundaries + self.values = values + super(PiecewiseDecay, self).__init__( + last_epoch=last_epoch, verbose=verbose + ) + + def get_lr(self): + for i in range(len(self.boundaries)): + if self.last_epoch < self.boundaries[i]: + return self.values[i] + return self.values[len(self.values) - 1] + + +class NaturalExpDecay(LRScheduler): + r""" + + Applies natural exponential decay to the initial learning rate. + + The algorithm can be described as following: + + .. math:: + + new\_learning\_rate = learning\_rate * e^{- gamma * epoch} + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + gamma (float, optional): A Ratio to update the learning rate, should greater than 0.0 to make learning rate decay. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``NaturalExpDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.NaturalExpDecay(learning_rate=0.5, gamma=0.1, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.NaturalExpDecay(learning_rate=0.5, gamma=0.1, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False): + assert ( + gamma > 0.0 + ), " 'gamma' must be a positive number so that the learning rate will decay." + self.gamma = gamma + super(NaturalExpDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + return self.base_lr * math.exp(-1 * self.gamma * self.last_epoch) + + +class InverseTimeDecay(LRScheduler): + r""" + + Applies inverse time decay to the initial learning rate. + + The algorithm can be described as following: + + .. math:: + + new\_learning\_rate = \frac{learning\_rate}{1 + gamma * epoch} + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be less than 1.0. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``InverseTimeDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.InverseTimeDecay(learning_rate=0.5, gamma=0.1, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.InverseTimeDecay(learning_rate=0.5, gamma=0.1, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + """ + + def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False): + self.gamma = gamma + super(InverseTimeDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + return self.base_lr / (1 + self.gamma * self.last_epoch) + + +class PolynomialDecay(LRScheduler): + r""" + + Applies polynomial decay to the initial learning rate. + + The algorithm can be described as following. + + If cycle is set to True, then: + + .. math:: + + decay\_steps & = decay\_steps * math.ceil(\frac{epoch}{decay\_steps}) + + new\_learning\_rate & = (learning\_rate-end\_lr)*(1-\frac{epoch}{decay\_steps})^{power}+end\_lr + + If cycle is set to False, then: + + .. math:: + + epoch & = min(epoch, decay\_steps) + + new\_learning\_rate & = (learning\_rate-end\_lr)*(1-\frac{epoch}{decay\_steps})^{power}+end\_lr + + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + decay_steps(int): The decay step size. It determines the decay cycle. It must be a positive integer. + end_lr(float, optional): The minimum final learning rate. Default: 0.0001. + power(float, optional): Power of polynomial, should greater than 0.0 to get learning rate decay. Default: 1.0. + cycle(bool, optional): Whether the learning rate rises again. If True, then the learning rate will rise when it decrease + to ``end_lr`` . If False, the learning rate is monotone decreasing. Default: False. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``PolynomialDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.PolynomialDecay(learning_rate=0.5, decay_steps=20, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.PolynomialDecay(learning_rate=0.5, decay_steps=20, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__( + self, + learning_rate, + decay_steps, + end_lr=0.0001, + power=1.0, + cycle=False, + last_epoch=-1, + verbose=False, + ): + assert decay_steps > 0 and isinstance( + decay_steps, int + ), " 'decay_steps' must be a positive integer." + self.decay_steps = decay_steps + self.end_lr = end_lr + assert ( + power > 0.0 + ), " 'power' must be greater than 0.0 so that the learning rate will decay." + self.power = power + self.cycle = cycle + super(PolynomialDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + tmp_epoch_num = self.last_epoch + tmp_decay_steps = self.decay_steps + if self.cycle: + div_res = math.ceil( + float(self.last_epoch) / float(self.decay_steps) + ) + + if self.last_epoch == 0: + div_res = 1 + tmp_decay_steps = self.decay_steps * div_res + else: + tmp_epoch_num = min(self.last_epoch, self.decay_steps) + + return (self.base_lr - self.end_lr) * ( + (1 - float(tmp_epoch_num) / float(tmp_decay_steps)) ** self.power + ) + self.end_lr + + +class LinearWarmup(LRScheduler): + r""" + + Linear learning rate warm up strategy. Update the learning rate preliminarily before the normal learning rate scheduler. + For more information, please refer to `Bag of Tricks for Image Classification with Convolutional Neural Networks `_ + + When epoch < warmup_steps, learning rate is updated as: + + .. math:: + + lr = start\_lr + (end\_lr - start\_lr) * \frac{epoch}{warmup\_steps} + + where start_lr is the initial learning rate, and end_lr is the final learning rate; + + When epoch >= warmup_steps, learning rate is updated as: + + .. math:: + + lr = learning_rate + + where ``learning_rate`` is float or any subclass of ``LRScheduler`` . + + Args: + learning_rate (float|LRScheduler): The learning rate after warm-up. It is a python float number or any subclass of ``LRScheduler`` . + warmup_steps (int): total steps of warm up. It must be a positive integer. + start_lr (float): Initial learning rate of warm up. + end_lr (float): Final learning rate of warm up. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``LinearWarmup`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.LinearWarmup( + learning_rate=0.5, warmup_steps=20, start_lr=0, end_lr=0.5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.LinearWarmup( + learning_rate=0.5, warmup_steps=20, start_lr=0, end_lr=0.5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__( + self, + learning_rate, + warmup_steps, + start_lr, + end_lr, + last_epoch=-1, + verbose=False, + ): + type_check = ( + isinstance(learning_rate, float) + or isinstance(learning_rate, int) + or isinstance(learning_rate, LRScheduler) + ) + if not type_check: + raise TypeError( + "the type of learning_rate should be [int, float or LRScheduler], the current type is {}".format( + learning_rate + ) + ) + self.learning_rate = learning_rate + assert warmup_steps > 0 and isinstance( + warmup_steps, int + ), " 'warmup_steps' must be a positive integer." + self.warmup_steps = warmup_steps + self.start_lr = start_lr + self.end_lr = end_lr + assert ( + end_lr > start_lr + ), "end_lr {} must be greater than start_lr {}".format(end_lr, start_lr) + super(LinearWarmup, self).__init__(start_lr, last_epoch, verbose) + + def state_dict(self): + """ + Returns the state of the LinearWarmup scheduler as a :class:`dict`. + + It is a subset of ``self.__dict__`` . + """ + state_dict = super(LinearWarmup, self).state_dict() + if isinstance(self.learning_rate, LRScheduler): + state_dict["LinearWarmup_LR"] = self.learning_rate.state_dict() + return state_dict + + def set_state_dict(self, state_dict): + """ + Loads state_dict for LinearWarmup scheduler. + """ + super(LinearWarmup, self).set_state_dict(state_dict) + if isinstance(self.learning_rate, LRScheduler): + self.learning_rate.set_state_dict(state_dict["LinearWarmup_LR"]) + + def get_lr(self): + if self.last_epoch < self.warmup_steps: + return (self.end_lr - self.start_lr) * float( + self.last_epoch + ) / float(self.warmup_steps) + self.start_lr + else: + if isinstance(self.learning_rate, LRScheduler): + self.learning_rate.step(self.last_epoch - self.warmup_steps) + return self.learning_rate() + + return self.learning_rate + + +class ExponentialDecay(LRScheduler): + r""" + + Update learning rate by `gamma` each epoch. + + The algorithm can be described as following. + + .. math:: + + new\_learning\_rate = last\_learning\_rate * gamma + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + gamma (float): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be in interval (0.0, 1.0). + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``ExponentialDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.ExponentialDecay(learning_rate=0.5, gamma=0.9, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.ExponentialDecay(learning_rate=0.5, gamma=0.9, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False): + assert ( + gamma > 0.0 and gamma < 1.0 + ), " 'gamma' must be in interval (0.0, 1.0) so that the learning rate will decay." + self.gamma = gamma + super(ExponentialDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + return self.base_lr * (self.gamma**self.last_epoch) + + +class MultiStepDecay(LRScheduler): + """ + Update the learning rate by ``gamma`` once ``epoch`` reaches one of the milestones. + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 + milestones = [30, 50] + gamma = 0.1 + if epoch < 30: + learning_rate = 0.5 + elif epoch < 50: + learning_rate = 0.05 + else: + learning_rate = 0.005 + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + milestones (tuple|list): List or tuple of each boundaries. Must be increasing. + gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be less than 1.0. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + + Returns: + ``MultiStepDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__( + self, learning_rate, milestones, gamma=0.1, last_epoch=-1, verbose=False + ): + if not isinstance(milestones, (tuple, list)): + raise TypeError( + "The type of 'milestones' in 'MultiStepDecay' must be 'tuple, list', but received %s." + % type(milestones) + ) + + if not all( + [ + milestones[i] < milestones[i + 1] + for i in range(len(milestones) - 1) + ] + ): + raise ValueError('The elements of milestones must be incremented') + if gamma >= 1.0: + raise ValueError('gamma should be < 1.0.') + + self.milestones = milestones + self.gamma = gamma + super(MultiStepDecay, self).__init__(learning_rate, last_epoch, verbose) + + def get_lr(self): + for i in range(len(self.milestones)): + if self.last_epoch < self.milestones[i]: + return self.base_lr * (self.gamma**i) + return self.base_lr * (self.gamma ** len(self.milestones)) + + +class StepDecay(LRScheduler): + """ + Update the learning rate of ``optimizer`` by ``gamma`` every ``step_size`` number of epoch. + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 + step_size = 30 + gamma = 0.1 + + learning_rate = 0.5 if epoch < 30 + learning_rate = 0.05 if 30 <= epoch < 60 + learning_rate = 0.005 if 60 <= epoch < 90 + ... + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + step_size (int): the interval to update. It must be a positive integer. + gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be less than 1.0. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``StepDecay`` instance to schedule learning rate. + + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=5, gamma=0.8, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=5, gamma=0.8, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__( + self, learning_rate, step_size, gamma=0.1, last_epoch=-1, verbose=False + ): + if not isinstance(step_size, int): + raise TypeError( + "The type of 'step_size' must be 'int', but received %s." + % type(step_size) + ) + if gamma >= 1.0: + raise ValueError('gamma should be < 1.0.') + + assert step_size > 0 and isinstance( + step_size, int + ), " 'step_size' must be a positive integer." + self.step_size = step_size + self.gamma = gamma + super(StepDecay, self).__init__(learning_rate, last_epoch, verbose) + + def get_lr(self): + i = self.last_epoch // self.step_size + return self.base_lr * (self.gamma**i) + + +class LambdaDecay(LRScheduler): + """ + Sets the learning rate of ``optimizer`` by function ``lr_lambda`` . ``lr_lambda`` is funciton which receives ``epoch`` . + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 # init learning_rate + lr_lambda = lambda epoch: 0.95 ** epoch + + learning_rate = 0.5 # epoch 0, 0.5*0.95**0 + learning_rate = 0.475 # epoch 1, 0.5*0.95**1 + learning_rate = 0.45125 # epoch 2, 0.5*0.95**2 + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + lr_lambda (function): A function which computes a factor by ``epoch`` , and then multiply the initial learning rate by this factor. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``LambdaDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.LambdaDecay(learning_rate=0.5, lr_lambda=lambda x:0.95**x, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.LambdaDecay(learning_rate=0.5, lr_lambda=lambda x:0.95**x, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + """ + + def __init__(self, learning_rate, lr_lambda, last_epoch=-1, verbose=False): + if not callable(lr_lambda): + raise TypeError( + "The type of 'lr_lambda' in 'LambdaDecay' must be 'function', but received %s." + % type(lr_lambda) + ) + + self.lr_lambda = lr_lambda + super(LambdaDecay, self).__init__(learning_rate, last_epoch, verbose) + + def get_lr(self): + return self.base_lr * self.lr_lambda(self.last_epoch) + + +class ReduceOnPlateau(LRScheduler): + """ + Reduce learning rate when ``metrics`` has stopped descending. Models often benefit from reducing the learning rate + by 2 to 10 times once model performance has no longer improvement. + + The ``metrics`` is the one which has been pass into ``step`` , it must be 1-D Tensor with shape [1]. When ``metrics`` + stop descending for a ``patience`` number of epochs, the learning rate will be reduced to ``learning_rate * factor`` . + (Specially, ``mode`` can also be set to ``'max`` , in this case, when ``metrics`` stop ascending for a ``patience`` + number of epochs, the learning rate will be reduced.) + + In addition, After each reduction, it will wait a ``cooldown`` number of epochs before resuming above operation. + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + mode (str, optional): ``'min'`` or ``'max'`` can be selected. Normally, it is ``'min'`` , which means that the + learning rate will reduce when ``loss`` stops descending. Specially, if it's set to ``'max'`` , the learning + rate will reduce when ``loss`` stops ascending. Default: ``'min'`` . + factor (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * factor`` . + It should be less than 1.0. Default: 0.1. + patience (int, optional): When ``loss`` doesn't improve for this number of epochs, learing rate will be reduced. + Default: 10. + threshold (float, optional): ``threshold`` and ``threshold_mode`` will determine the minimum change of ``loss`` . + This make tiny changes of ``loss`` will be ignored. Default: 1e-4. + threshold_mode (str, optional): ``'rel'`` or ``'abs'`` can be selected. In ``'rel'`` mode, the minimum change of ``loss`` + is ``last_loss * threshold`` , where ``last_loss`` is ``loss`` in last epoch. In ``'abs'`` mode, the minimum + change of ``loss`` is ``threshold`` . Default: ``'rel'`` . + cooldown (int, optional): The number of epochs to wait before resuming normal operation. Default: 0. + min_lr (float, optional): The lower bound of the learning rate after reduction. Default: 0. + epsilon (float, optional): Minimal decay applied to lr. If the difference between new and old lr is smaller than epsilon, + the update is ignored. Default: 1e-8. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False``. + + + Returns: + ``ReduceOnPlateau`` instance to schedule learning rate. + + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.ReduceOnPlateau(learning_rate=1.0, factor=0.5, patience=5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step(loss) # If you update learning rate each step + # scheduler.step(loss) # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.ReduceOnPlateau(learning_rate=1.0, factor=0.5, patience=5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step(out[0]) # If you update learning rate each step + # scheduler.step(out[0]) # If you update learning rate each epoch + + """ + + def __init__( + self, + learning_rate, + mode='min', + factor=0.1, + patience=10, + threshold=1e-4, + threshold_mode='rel', + cooldown=0, + min_lr=0, + epsilon=1e-8, + verbose=False, + ): + mode = mode.lower() + if mode not in ['min', 'max']: + raise ValueError('mode: ' + mode + ' is unknown!') + self.mode = mode + + if factor >= 1.0: + raise ValueError( + 'new_lr = origin_lr * gamma and gamma should be < 1.0.' + ) + self.factor = factor + + threshold_mode = threshold_mode.lower() + if threshold_mode not in ['rel', 'abs']: + raise ValueError( + 'threshold mode: ' + threshold_mode + ' is unknown!' + ) + self.threshold_mode = threshold_mode + if not isinstance(learning_rate, (float, int)): + raise TypeError( + "The type of 'learning_rate' in 'ReduceOnPlateau' must be 'float', but received %s." + % type(learning_rate) + ) + + self.patience = patience + self.threshold = threshold + self.threshold_mode = threshold_mode + self.cooldown = cooldown + self.min_lr = min_lr + self.epsilon = epsilon + + self.cooldown_counter = 0 + self.best = None + self.num_bad_epochs = 0 + + # Can not call Parent __init__, so implement here. + self.base_lr = float(learning_rate) + self.last_lr = float(learning_rate) + self.last_epoch = 0 + self.verbose = verbose + self._var_name = None + + # "cooldown_counter / best / num_bad_epochs / last_epoch / last_lr" will be stored. + def state_keys(self): + self.keys = [ + 'cooldown_counter', + 'best', + 'num_bad_epochs', + 'last_epoch', + 'last_lr', + ] + + def step(self, metrics, epoch=None): + """ + step should be called after `optimizer.step()` . It will update the learning rate in optimizer according to ``metrics`` . + The new learning rate will take effect on next epoch. + + Args: + metrics (Tensor|numpy.ndarray|float): Which will be monitored to determine whether the learning rate will reduce. + If it stop descending for a ``patience`` number of epochs, the learning rate will reduce. If it's 'Tensor' or + 'numpy.ndarray', its shape must be [1]. + epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1. + + Returns: + None + + Examples: + Please refer to the example of current LRScheduler. + """ + if epoch is None: + self.last_epoch = self.last_epoch + 1 + else: + self.last_epoch = epoch + + if not _in_legacy_dygraph(): + tmp = core.eager.Tensor + else: + # need to declarate explicitly + from paddle.framework import VarBase as Tensor + + tmp = Tensor + # loss must be float, numpy.ndarray or 1-D Tensor with shape [1] + if isinstance(metrics, (tmp, numpy.ndarray)): + assert len(metrics.shape) == 1 and metrics.shape[0] == 1, ( + "the metrics.shape " + "should be (1L,), but the current metrics.shape is {}. Maybe that " + "you should call paddle.mean to process it first.".format( + metrics.shape + ) + ) + elif not isinstance( + metrics, (int, float, numpy.float32, numpy.float64) + ): + raise TypeError( + "metrics must be 'int', 'float', 'np.float', 'numpy.ndarray' or 'paddle.Tensor', but receive {}".format( + type(metrics) + ) + ) + + if self.cooldown_counter > 0: + self.cooldown_counter -= 1 + else: + if self.best is None or self._is_better(metrics, self.best): + self.best = metrics + self.num_bad_epochs = 0 + else: + self.num_bad_epochs += 1 + + if self.num_bad_epochs > self.patience: + self.cooldown_counter = self.cooldown + self.num_bad_epochs = 0 + new_lr = max(self.last_lr * self.factor, self.min_lr) + if self.last_lr - new_lr > self.epsilon: + self.last_lr = new_lr + if self.verbose: + print( + 'Epoch {}: {} set learning rate to {}.'.format( + self.last_epoch, + self.__class__.__name__, + self.last_lr, + ) + ) + + def _is_better(self, current, best): + if self.mode == 'min' and self.threshold_mode == 'rel': + return current < best - best * self.threshold + + elif self.mode == 'min' and self.threshold_mode == 'abs': + return current < best - self.threshold + + elif self.mode == 'max' and self.threshold_mode == 'rel': + return current > best + best * self.threshold + + else: + return current > best + self.threshold + + +class CosineAnnealingDecay(LRScheduler): + r""" + + Set the learning rate using a cosine annealing schedule, where :math:`\eta_{max}` is set to + the initial learning_rate. :math:`T_{cur}` is the number of epochs since the last restart in + SGDR. + + The algorithm can be described as following. + + .. math:: + + \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 + + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right), + & T_{cur} \neq (2k+1)T_{max}; + + \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min}) + \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right), + & T_{cur} = (2k+1)T_{max}. + + It has been proposed in `SGDR: Stochastic Gradient Descent with Warm Restarts `_. + Note that this only implements the cosine annealing part of SGDR, and not the restarts. + + Args: + learning_rate (float): The initial learning rate, that is :math:`\eta_{max}` . It can be set to python float or int number. + T_max (int): Maximum number of iterations. It is half of the decay cycle of learning rate. It must be a positive integer. + eta_min (float|int, optional): Minimum learning rate, that is :math:`\eta_{min}` . Default: 0. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``CosineAnnealingDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.CosineAnnealingDecay(learning_rate=0.5, T_max=10, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.CosineAnnealingDecay(learning_rate=0.5, T_max=10, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(20): + for batch_id in range(5): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + """ + + def __init__( + self, learning_rate, T_max, eta_min=0, last_epoch=-1, verbose=False + ): + if not isinstance(T_max, int): + raise TypeError( + "The type of 'T_max' in 'CosineAnnealingDecay' must be 'int', but received %s." + % type(T_max) + ) + if not isinstance(eta_min, (float, int)): + raise TypeError( + "The type of 'eta_min' in 'CosineAnnealingDecay' must be 'float, int', but received %s." + % type(eta_min) + ) + assert T_max > 0 and isinstance( + T_max, int + ), " 'T_max' must be a positive integer." + self.T_max = T_max + self.eta_min = float(eta_min) + super(CosineAnnealingDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + if self.last_epoch == 0: + return self.base_lr + elif (self.last_epoch - 1 - self.T_max) % (2 * self.T_max) == 0: + return ( + self.last_lr + + (self.base_lr - self.eta_min) + * (1 - math.cos(math.pi / self.T_max)) + / 2 + ) + + return (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / ( + 1 + math.cos(math.pi * (self.last_epoch - 1) / self.T_max) + ) * (self.last_lr - self.eta_min) + self.eta_min + + def _get_closed_form_lr(self): + return ( + self.eta_min + + (self.base_lr - self.eta_min) + * (1 + math.cos(math.pi * self.last_epoch / self.T_max)) + / 2 + ) + + +class MultiplicativeDecay(LRScheduler): + """ + Multiply the learning rate of ``optimizer`` by the factor given in function ``lr_lambda`` . + + The algorithm can be described as the code below. + + .. code-block:: text + + learning_rate = 0.5 # init learning_rate + lr_lambda = lambda epoch: 0.95 + + learning_rate = 0.5 # epoch 0, + learning_rate = 0.475 # epoch 1, 0.5*0.95 + learning_rate = 0.45125 # epoch 2, 0.475*0.95 + + Args: + learning_rate (float): The initial learning rate. It is a python float number. + lr_lambda (function): A function which computes a factor by ``epoch`` , and then multiply the last learning rate by this factor. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``MultiplicativeDecay`` instance to schedule learning rate. + + Examples: + + .. code-block:: python + + import paddle + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.MultiplicativeDecay(learning_rate=0.5, lr_lambda=lambda x:0.95, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(20): + for batch_id in range(5): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # If you update learning rate each step + # scheduler.step() # If you update learning rate each epoch + + """ + + def __init__(self, learning_rate, lr_lambda, last_epoch=-1, verbose=False): + if not callable(lr_lambda): + raise TypeError( + "The type of 'lr_lambda' in 'MultiplicativeDecay' must be 'function', but received %s." + % type(lr_lambda) + ) + + self.lr_lambda = lr_lambda + super(MultiplicativeDecay, self).__init__( + learning_rate, last_epoch, verbose + ) + + def get_lr(self): + cur_lr = self.base_lr + for epoch in range(1, self.last_epoch + 1): + cur_lr = cur_lr * self.lr_lambda(epoch) + return cur_lr + + +class OneCycleLR(LRScheduler): + r""" + + Sets the learning rate according to the one cycle learning rate scheduler. + The scheduler adjusts the learning rate from an initial learning rate to the maximum learning rate and then + from that maximum learning rate to the minimum learning rate, which is much less than the initial learning rate. + + It has been proposed in `Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates `_. + + Please note that the default behaviour of this scheduler follows the fastai implementation of one cycle, + which claims that “unpublished work has shown even better results by using only two phases”. + If you want the behaviour of this scheduler to be consistent with the paper, please set ``three_phase=True`` . + + Also note that you should update learning rate each step. + + Args: + max_learning_rate (float): The maximum learning rate. It is a python float number. Functionally, it defines the initial learning rate by ``divide_factor`` . + total_steps (int): Number of total training steps. + divide_factor (float, optional): Initial learning rate will be determined by initial_learning_rate = max_learning_rate / divide_factor. Default: 25. + end_learning_rate (float, optional): The minimum learning rate during training, it should be much less than initial learning rate. + phase_pct (float): The percentage of total steps which used to increasing learning rate. Default: 0.3. + anneal_strategy (str, optional): Strategy of adjusting learning rate.'cos' for cosine annealing, 'linear' for linear annealing. Default: 'cos'. + three_phase (bool, optional): Whether to use three phase. + + If ``True``: + + 1. The learning rate will first increase from initial learning rate to maximum learning rate. + 2. Then it will decrease to initial learning rate. Number of step in this phase is the same as the one in first phase. + 3. Finally, it will decrease to minimum learning rate which is much less than initial learning rate. + + If ``False``: + + 1. The learning rate will increase to maximum learning rate. + 2. Then it will directly decrease to minimum learning rate. + + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``OneCycleLR`` instance to schedule learning rate. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.OneCycleLR(max_learning_rate=1.0, total_steps=100, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(5): + for batch_id in range(20): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # You should update learning rate each step + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.OneCycleLR(max_learning_rate=1.0, total_steps=100, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(5): + for batch_id in range(20): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # You should update learning rate each step + + """ + + def __init__( + self, + max_learning_rate, + total_steps, + divide_factor=25.0, + end_learning_rate=0.0001, + phase_pct=0.3, + anneal_strategy='cos', + three_phase=False, + last_epoch=-1, + verbose=False, + ): + # Check type and value of max_learning_rate + if not isinstance(max_learning_rate, (float, int)): + raise TypeError( + "'max_learning_rate' must be 'float' or 'int', but received {}".format( + type(max_learning_rate) + ) + ) + if max_learning_rate < 0: + raise ValueError("'max_learning_rate' must be a positive integer.") + + # Check type and value of end_learning_rate + if not isinstance(end_learning_rate, (float, int)): + raise TypeError( + "'end_learning_rate' must be 'float' or 'int', but received {}".format( + type(end_learning_rate) + ) + ) + if end_learning_rate < 0: + raise ValueError("'end_learning_rate' must be a positive integer.") + + # Check type and value of total_steps + if not isinstance(total_steps, int): + raise TypeError( + "'total_step' must be 'int', but received {}".format( + type(total_steps) + ) + ) + if total_steps <= 0: + raise ValueError("'total_step' must be a positive integer.") + self.total_steps = total_steps + + # Check type and value of pac_start + if not isinstance(phase_pct, float): + raise TypeError( + "'phase_pct' must be 'float', but received {}".format( + type(phase_pct) + ) + ) + if phase_pct < 0 or phase_pct > 1: + raise ValueError( + "'phase_pct' must be between 0 and 1, but received {}".format( + phase_pct + ) + ) + + # Check type and value of divide_factor + if not isinstance(divide_factor, (float, int)): + raise TypeError( + "'divide_factor' must be 'float' or 'int', but received {}".format( + type(divide_factor) + ) + ) + + initial_lr = max_learning_rate / float(divide_factor) + min_lr = float(end_learning_rate) + + if three_phase: + if phase_pct >= 0.5: + raise ValueError( + "When three_phase is True, 'phase_pct' must be less than 0.5" + ) + # start step and end step of each phase. + self._step_config = [ + 0, + phase_pct * self.total_steps - 1, + 2 * phase_pct * self.total_steps - 2, + self.total_steps - 1, + self.total_steps - 1, # for the last step. + ] + # step size of each phase. + self._steps_size = [ + self._step_config[1] - self._step_config[0], + self._step_config[2] - self._step_config[1], + self._step_config[3] - self._step_config[2], + self._step_config[3] + - self._step_config[2], # for the last step. + ] + # start lr and end lr of each phase. + self._lr_config = [ + initial_lr, + max_learning_rate, + initial_lr, + min_lr, + ] + else: + self._step_config = [ + 0, + phase_pct * self.total_steps - 1, + self.total_steps - 1, + self.total_steps - 1, + ] + self._steps_size = [ + self._step_config[1] - self._step_config[0], + self._step_config[2] - self._step_config[1], + self._step_config[2] - self._step_config[1], + ] + self._lr_config = [initial_lr, max_learning_rate, min_lr] + + # Check anneal_strategy + if anneal_strategy == 'cos': + self.anneal_func = self._cos_annealing + elif anneal_strategy == 'linear': + self.anneal_func = self._linear_annealing + else: + raise ValueError( + "'anneal_strategy' must by one of 'cos' or 'linear', but received {}".format( + anneal_strategy + ) + ) + super(OneCycleLR, self).__init__(initial_lr, last_epoch, verbose) + + def _cos_annealing(self, start_lr, end_lr, pct): + cos_out = math.cos(math.pi * pct) + 1 + return end_lr + (start_lr - end_lr) / 2.0 * cos_out + + def _linear_annealing(self, start_lr, end_lr, pct): + return (end_lr - start_lr) * pct + start_lr + + def get_lr(self): + current_step = self.last_epoch + + if current_step > self.total_steps: + raise ValueError( + "Tried to step {} times. However the number of total steps is {}".format( + current_step, self.total_steps + ) + ) + + for (i, (end_step, step_size)) in enumerate( + zip(self._step_config[1:], self._steps_size) + ): + # i == len(self._lr_config) - 2 catch the last step, otherwise it will return None. + if current_step <= end_step or i == len(self._lr_config) - 2: + # self._step_config[i] means start step of a phase. + percentage = (current_step - self._step_config[i]) / step_size + return self.anneal_func( + self._lr_config[i], self._lr_config[i + 1], percentage + ) + + +class CyclicLR(LRScheduler): + r""" + Set the learning rate according to the cyclic learning rate (CLR) scheduler. + The scheduler regards the process of learning rate adjustment as one cycle after another. + It cycles the learning rate between two boundaries with a constant frequency. + The distance between the two boundaries can be scaled on a per-iteration or per-cycle basis. + + It has been proposed in `Cyclic Learning Rates for Training Neural Networks `_. + + According to the paper, the cyclic learning rate schedule has three build-in scale methods: + + * "triangular": A basic triangular cycle without any amplitude scaling. + * "triangular2": A basic triangular cycle that reduce initial amplitude by half each cycle. + * "exp_range": A cycle that scales initial amplitude by scale function which is defined as :math:`gamma^{iterations}` . + + The initial amplitude is defined as max_learning_rate - base_learning_rate. + Also note that you should update learning rate each step. + + Args: + base_learning_rate (float): Initial learning rate, which is the lower boundary in the cycle. The paper recommends + that set the base_learning_rate to 1/3 or 1/4 of max_learning_rate. + max_learning_rate (float): Maximum learning rate in the cycle. It defines the cycle amplitude as above. + Since there is some scaling operation during process of learning rate adjustment, + max_learning_rate may not actually be reached. + step_size_up (int): Number of training steps, which is used to increase learning rate in a cycle. + The step size of one cycle will be defined by step_size_up + step_size_down. According to the paper, step + size should be set as at least 3 or 4 times steps in one epoch. + step_size_down (int, optional): Number of training steps, which is used to decrease learning rate in a cycle. + If not specified, it's value will initialize to `` step_size_up `` . Default: None + mode (str, optional): one of 'triangular', 'triangular2' or 'exp_range'. + If scale_fn is specified, this argument will be ignored. Default: 'triangular' + exp_gamma (float): Constant in 'exp_range' scaling function: exp_gamma**iterations. Used only when mode = 'exp_range'. Default: 1.0 + scale_fn (function, optional): A custom scaling function, which is used to replace three build-in methods. + It should only have one argument. For all x >= 0, 0 <= scale_fn(x) <= 1. + If specified, then 'mode' will be ignored. Default: None + scale_mode (str, optional): One of 'cycle' or 'iterations'. Defines whether scale_fn is evaluated on cycle + number or cycle iterations (total iterations since start of training). Default: 'cycle' + last_epoch (int, optional): The index of last epoch. Can be set to restart training.Default: -1, means initial learning rate. + verbose: (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` . + + Returns: + ``CyclicLR`` instance to schedule learning rate. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + # train on default dynamic graph mode + linear = paddle.nn.Linear(10, 10) + scheduler = paddle.optimizer.lr.CyclicLR(base_learning_rate=0.5, max_learning_rate=1.0, step_size_up=15, step_size_down=5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters()) + for epoch in range(5): + for batch_id in range(20): + x = paddle.uniform([10, 10]) + out = linear(x) + loss = paddle.mean(out) + loss.backward() + sgd.step() + sgd.clear_gradients() + scheduler.step() # You should update learning rate each step + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 4, 5]) + y = paddle.static.data(name='y', shape=[None, 4, 5]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.CyclicLR(base_learning_rate=0.5, + max_learning_rate=1.0, step_size_up=15, step_size_down=5, verbose=True) + sgd = paddle.optimizer.SGD(learning_rate=scheduler) + sgd.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for epoch in range(5): + for batch_id in range(20): + out = exe.run( + main_prog, + feed={ + 'x': np.random.randn(3, 4, 5).astype('float32'), + 'y': np.random.randn(3, 4, 5).astype('float32') + }, + fetch_list=loss.name) + scheduler.step() # You should update learning rate each step + """ + + def __init__( + self, + base_learning_rate, + max_learning_rate, + step_size_up, + step_size_down=None, + mode='triangular', + exp_gamma=1.0, + scale_fn=None, + scale_mode='cycle', + last_epoch=-1, + verbose=False, + ): + # check type and value of max_learning_rate + if not isinstance(max_learning_rate, (float, int)): + raise TypeError( + "'max_learning_rate' must be 'float' or 'int', but received {}".format( + type(max_learning_rate) + ) + ) + if max_learning_rate < 0: + raise ValueError( + "'max_learning_rate' must be a positive integer, but received {}".format( + max_learning_rate + ) + ) + + # check type and value of step_size_up + if not isinstance(step_size_up, int): + raise TypeError( + "The type of 'step_size_up' must be int, but received {}".format( + type(step_size_up) + ) + ) + if step_size_up <= 0: + raise ValueError( + "'step_size_up' must be a positive integer, but received {}".format( + step_size_up + ) + ) + + # check type and value of step_size_down + if step_size_down is not None: + if not isinstance(step_size_down, int): + raise TypeError( + "The type of 'step_size_down' must be int, but received {}".format( + type(step_size_down) + ) + ) + if step_size_down <= 0: + raise ValueError( + "'step_size_down' must be a positive integer, but received {}".format( + step_size_down + ) + ) + + # check type of exp_gamma + if not isinstance(exp_gamma, float): + raise TypeError( + "The type of 'exp_gamma' must be float, but received {}".format( + type(exp_gamma) + ) + ) + + step_size_up = float(step_size_up) + step_size_down = ( + float(step_size_down) + if step_size_down is not None + else step_size_up + ) + + self.cycle_size = step_size_up + step_size_down + self.step_up_pct = step_size_up / self.cycle_size + self.max_lr = float(max_learning_rate) + self.amplitude = self.max_lr - base_learning_rate + + if ( + mode not in ['triangular', 'triangular2', 'exp_range'] + and scale_fn is None + ): + raise ValueError( + "'mode' is invalid and 'scale_fn' is not specified, make sure one of 'mode' or 'scale_fn' is valid" + ) + if scale_mode not in ['cycle', 'iterations']: + raise ValueError( + "'scale_mode' must be one of 'cycle' or 'iterations" + ) + + self.mode = mode + self.gamma = exp_gamma # only for exp_range mode + + if scale_fn is None: + if self.mode == 'triangular': + self.scale_fn = self._triangular_scale_fn + self.scale_mode = 'cycle' + elif self.mode == 'triangular2': + self.scale_fn = self._triangular2_scale_fn + self.scale_mode = 'cycle' + elif self.mode == 'exp_range': + self.scale_fn = self._exp_range_scale_fn + self.scale_mode = 'iterations' + else: + self.scale_fn = scale_fn + self.scale_mode = scale_mode + super().__init__(base_learning_rate, last_epoch, verbose) + + def _triangular_scale_fn(self, x): + return 1.0 + + def _triangular2_scale_fn(self, x): + return 1 / (2.0 ** (x - 1)) + + def _exp_range_scale_fn(self, x): + return self.gamma**x + + def get_lr(self): + iterations = self.last_epoch + + cycle = 1 + iterations // self.cycle_size + pct_per_cycle = 1.0 + iterations / self.cycle_size - cycle + + if pct_per_cycle <= self.step_up_pct: + scale_factor = pct_per_cycle / self.step_up_pct + else: + scale_factor = (1 - pct_per_cycle) / (1 - self.step_up_pct) + + base_height = self.amplitude * scale_factor + + lr = self.base_lr + base_height * self.scale_fn(eval(self.scale_mode)) + + return lr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/momentum.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/momentum.py new file mode 100644 index 0000000000000000000000000000000000000000..da70ca1303ab770fb75e99a506177387748ab84f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/momentum.py @@ -0,0 +1,663 @@ +# 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. + +import warnings + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, name_scope +from ..fluid.layer_helper import LayerHelper +from ..fluid import unique_name +from ..fluid import layers +import paddle.fluid as fluid +from paddle.fluid.regularizer import L2DecayRegularizer +from paddle import _C_ops, _legacy_C_ops +import paddle +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph + +__all__ = [] + + +class Momentum(Optimizer): + r""" + + Simple Momentum optimizer with velocity state + + This optimizer has a flag for Nestrov Momentum. + + The update equations are as follows: + + .. math:: + + & velocity = mu * velocity + gradient + + & if (use\_nesterov): + + &\quad param = param - (gradient + mu * velocity) * learning\_rate + + & else: + + &\quad param = param - learning\_rate * velocity + + Parameters: + + learning_rate (float|Tensor|LearningRateDecay, optional): The learning rate used to update ``Parameter``. + It can be a float value, a ``Tensor`` with a float type or a LearningRateDecay. The default value is 0.001. + momentum (float): Momentum factor. The default value is 0.9. + parameters (list|tuple, optional): List|Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false. + rescale_grad (float, optional): Multiply the gradient with `rescale_grad` before updating. \ + Often choose to be ``1.0/batch_size``. + use_multi_tensor (bool, optional): Whether to use multi-tensor strategy to update all parameters at once . Default is false. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1) + linear = paddle.nn.Linear(10, 10) + inp = paddle.to_tensor(inp) + out = linear(inp) + loss = paddle.mean(out) + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + momentum = paddle.optimizer.Momentum(learning_rate=0.1, parameters=linear.parameters(), weight_decay=0.01) + back = out.backward() + momentum.step() + momentum.clear_grad() + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + momentum = paddle.optimizer.Momentum( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1 + }], + weight_decay=0.01, + momentum=0.9) + out.backward() + momentum.step() + momentum.clear_grad() + + """ + _velocity_acc_str = "velocity" + + def __init__( + self, + learning_rate=0.001, + momentum=0.9, + parameters=None, + use_nesterov=False, + weight_decay=None, + grad_clip=None, + multi_precision=False, + rescale_grad=1.0, + use_multi_tensor=False, + name=None, + ): + if learning_rate is None: + raise ValueError("learning_rate is not set") + if momentum is None: + raise ValueError("momentum is not set") + + predicate = lambda regular: isinstance( + regular, (L2DecayRegularizer, float) + ) + if isinstance(parameters, list): + if isinstance(parameters[0], dict): + for param_group in parameters: + decay = ( + param_group['weight_decay'] + if 'weight_decay' in param_group + else weight_decay + ) + reg_method, reg_coeff = self._update_regularization(decay) + param_group['regularization_method'] = reg_method + param_group['regularization_coeff'] = reg_coeff + py_regular = None if predicate(decay) else decay + param_group['weight_decay'] = py_regular + + py_regular = None if predicate(weight_decay) else weight_decay + super(Momentum, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=py_regular, + grad_clip=grad_clip, + name=name, + ) + self.type = "momentum" + self._momentum = momentum + self._use_nesterov = bool(use_nesterov) + ( + self._regularization_method, + self._regularization_coeff, + ) = self._update_regularization(weight_decay) + self._multi_precision = multi_precision + self._rescale_grad = rescale_grad + self._master_weights = {} + + self._default_dict = { + 'momentum': momentum, + 'use_nesterov': use_nesterov, + 'rescale_grad': rescale_grad, + 'regularization_method': self._regularization_method, + 'regularization_coeff': self._regularization_coeff, + } + self._use_multi_tensor = use_multi_tensor + if self._use_multi_tensor: + self._param_dict = self._create_multi_tensor_dict() + self._velocity_dict = self._create_multi_tensor_dict() + self._master_weight_dict = self._create_multi_tensor_dict() + self._master_weight_dict['FP32_LODTensor'] = None + self._regularization_method_dict = self._create_multi_tensor_dict() + self._regularization_coeff_dict = self._create_multi_tensor_dict() + + def _update_regularization(self, weight_decay): + reg_method = "" + reg_coeff = 0.0 + + if isinstance(weight_decay, L2DecayRegularizer): + reg_method = "l2_decay" + reg_coeff = weight_decay._regularization_coeff + if isinstance(weight_decay, float): + reg_method = "l2_decay" + reg_coeff = weight_decay + return reg_method, reg_coeff + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var( + name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True, + ) + block = self.helper.startup_program.global_block() + block.append_op( + type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32, + }, + ) + self._master_weights[param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + + Args: + name: name of the accumulator + param: parameter variable for which accumulator is to be fetched + + Returns: + accumulator variable for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + find_master = ( + self._multi_precision and param.dtype == core.VarDesc.VarType.FP16 + ) + target_param = ( + self._master_weights[param.name] if find_master else param + ) + target_name = target_param.name + if ( + name not in self._accumulators + or target_name not in self._accumulators[name] + ): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, target_name + ) + ) + return self._accumulators[name][target_name] + + def _create_accumulators(self, block, parameters): + ''' + if framework._non_static_mode(): + return + ''' + assert isinstance(block, framework.Block) + + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + self._add_accumulator(self._velocity_acc_str, master_p) + continue + if ( + p.dtype == core.VarDesc.VarType.FP16 + and not self._multi_precision + ): + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Momentum optimizer." + ) + self._add_accumulator(self._velocity_acc_str, p) + + def _create_regularization_of_grad(self, param, grad, regularization=None): + """Create and add backward regularization Operators + + Function helper of append_regularization_ops. + """ + # If ParamAttr is set to L2Decay, we skip doing regularization here. And then we fused + # L2Decay with momentum which can refer to _append_optimize_op below. + if hasattr(param, 'regularizer') and isinstance( + param.regularizer, L2DecayRegularizer + ): + return grad + return super(Momentum, self)._create_regularization_of_grad( + param, grad, regularization + ) + + def _append_optimize_op(self, block, param_and_grad): + assert isinstance(block, framework.Block) + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + velocity_acc = self._get_accumulator( + self._velocity_acc_str, param_and_grad[0] + ) + lr = self._create_param_lr(param_and_grad) + + # For fusion of momentum and l2decay + param = param_and_grad[0] + regularization_method = self._regularization_method + regularization_coeff = self._regularization_coeff + if hasattr(param, 'regularizer'): + # we skip param's l2decay before, so fuse it with momentum here. + if isinstance(param.regularizer, L2DecayRegularizer): + regularization_method = "l2_decay" + regularization_coeff = param.regularizer._regularization_coeff + # the param's regularization has been done before, we avoid do l2decay in momentum. + elif param.regularizer is not None: + regularization_method = "" + regularization_coeff = 0.0 + + find_master = ( + self._multi_precision + and param_and_grad[0].dtype == core.VarDesc.VarType.FP16 + ) + master_weight = ( + self._master_weights[param_and_grad[0].name] + if find_master + else None + ) + + if _in_legacy_dygraph(): + if isinstance(param_and_grad, dict): + self._update_regularization(param_and_grad['weight_decay']) + _, _, _ = _legacy_C_ops.momentum( + param_and_grad[0], + param_and_grad[1], + velocity_acc, + lr, + master_weight, + param_and_grad[0], + velocity_acc, + master_weight, + 'mu', + self._momentum, + 'use_nesterov', + self._use_nesterov, + 'regularization_method', + regularization_method, + 'regularization_coeff', + regularization_coeff, + 'multi_precision', + find_master, + ) + return None + if in_dygraph_mode(): + if isinstance(param_and_grad, dict): + self._update_regularization(param_and_grad['weight_decay']) + return _C_ops.momentum_( + param_and_grad[0], + param_and_grad[1], + velocity_acc, + lr, + master_weight, + self._momentum, + self._use_nesterov, + regularization_method, + regularization_coeff, + find_master, + self._rescale_grad, + ) + + attrs = { + "mu": self._momentum, + "use_nesterov": self._use_nesterov, + "regularization_method": regularization_method, + "regularization_coeff": regularization_coeff, + "multi_precision": find_master, + "rescale_grad": self._rescale_grad, + } + + inputs = { + "Param": [param_and_grad[0]], + "Grad": [param_and_grad[1]], + "Velocity": [velocity_acc], + "LearningRate": [lr], + } + + outputs = { + "ParamOut": [param_and_grad[0]], + "VelocityOut": [velocity_acc], + } + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + # create the momentum optimize op + momentum_op = block.append_op( + type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True, + ) + + return momentum_op + + def _multi_tensor_init(self, target_block, parameters, param_group_idx): + """ + All parameters used for optimizer (such as: parameters, master_weight, velocity_acc for momentum) calculations are grouped into a python list by data type (float16, float32). + This function will be overridden in the corresponding optimizer file. + + Args: + target_block: the block in which the loss tensor is present + parameters: list of parameter tensors for the optimizer + """ + self._create_accumulators(target_block, parameters) + for param in parameters: + velocity_acc = self._get_accumulator(self._velocity_acc_str, param) + regularization_method = self._regularization_method + regularization_coeff = self._regularization_coeff + if hasattr(param, 'regularizer'): + # we skip param's l2decay before, so fuse it with momentum here. + if isinstance(param.regularizer, L2DecayRegularizer): + regularization_method = "l2_decay" + regularization_coeff = ( + param.regularizer._regularization_coeff + ) + elif param.regularizer is not None: + regularization_method = "" + regularization_coeff = 0.0 + if param.dtype == paddle.float32: + self._param_dict['FP32_LODTensor'][param_group_idx].append( + param + ) + self._velocity_dict['FP32_LODTensor'][param_group_idx].append( + velocity_acc + ) + # fp32 no master weight + self._regularization_method_dict['FP32_LODTensor'][ + param_group_idx + ].append(regularization_method) + self._regularization_coeff_dict['FP32_LODTensor'][ + param_group_idx + ].append(regularization_coeff) + elif param.dtype == paddle.float16: + self._param_dict['FP16_LODTensor'][param_group_idx].append( + param + ) + self._velocity_dict['FP16_LODTensor'][param_group_idx].append( + velocity_acc + ) + if self._multi_precision: + self._master_weight_dict['FP16_LODTensor'][ + param_group_idx + ].append(self._master_weights[param.name]) + else: + self._master_weight_dict['FP16_LODTensor'][ + param_group_idx + ] = None + self._regularization_method_dict['FP16_LODTensor'][ + param_group_idx + ].append(regularization_method) + self._regularization_coeff_dict['FP16_LODTensor'][ + param_group_idx + ].append(regularization_coeff) + else: + raise ValueError( + "Now multi_tensor_momentum only support fp32 and fp16 parameters and grad is LOD_TENSOR." + ) + + def _append_optimize_multi_tensor_op( + self, + target_block, + parameters_and_grads, + param_group_idx, + ): + """ + For Multi Tensor, append optimize merged_operator to block. + """ + assert isinstance(target_block, framework.Block) + + grad_dict = {'FP32_LODTensor': [], 'FP16_LODTensor': []} + lr_dict = {'FP32_LODTensor': [], 'FP16_LODTensor': []} + + if isinstance(parameters_and_grads, list): + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + if ( + param_and_grad[0].dtype == paddle.float32 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP32_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP32_LODTensor'].append(lr) + elif ( + param_and_grad[0].dtype == paddle.float16 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP16_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP16_LODTensor'].append(lr) + else: + for param_and_grad in parameters_and_grads['params']: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + param_grad_dict = dict() + param_grad_dict['params'] = param_and_grad + param_grad_dict.update( + { + k: v + for k, v in parameters_and_grads.items() + if k != 'params' + } + ) + param_and_grad = self._update_param_group(param_grad_dict) + if ( + param_and_grad[0].dtype == paddle.float32 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP32_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP32_LODTensor'].append(lr) + elif ( + param_and_grad[0].dtype == paddle.float16 + and param_and_grad[1].type + == core.VarDesc.VarType.LOD_TENSOR + ): + grad_dict['FP16_LODTensor'].append(param_and_grad[1]) + lr = self._create_param_lr(param_and_grad) + lr_dict['FP16_LODTensor'].append(lr) + + multi_tensor_list = ['FP32_LODTensor', 'FP16_LODTensor'] + for key in multi_tensor_list: + if len(self._param_dict[key][param_group_idx]) > 0: + find_master = self._multi_precision and key == 'FP16_LODTensor' + + master_weight = self._master_weight_dict[key] + master_weight = ( + master_weight[param_group_idx] + if master_weight is not None + else None + ) + + if framework._non_static_mode(): + if in_dygraph_mode(): + _, _, _ = _C_ops.merged_momentum_( + self._param_dict[key][param_group_idx], + grad_dict[key], + self._velocity_dict[key][param_group_idx], + lr_dict[key], + master_weight, + self._momentum, + self._use_nesterov, + self._regularization_method_dict[key][ + param_group_idx + ], + self._regularization_coeff_dict[key][ + param_group_idx + ], + find_master, + self._rescale_grad, + ) + else: + _, _, _ = _legacy_C_ops.merged_momentum( + self._param_dict[key][param_group_idx], + grad_dict[key], + self._velocity_dict[key][param_group_idx], + lr_dict[key], + master_weight, + self._param_dict[key][param_group_idx], + self._velocity_dict[key][param_group_idx], + master_weight, + 'mu', + self._momentum, + 'use_nesterov', + self._use_nesterov, + 'regularization_method', + self._regularization_method_dict[key][ + param_group_idx + ], + 'regularization_coeff', + self._regularization_coeff_dict[key][ + param_group_idx + ], + 'multi_precision', + find_master, + ) + else: + inputs = { + "Param": self._param_dict[key][param_group_idx], + "Grad": grad_dict[key], + "Velocity": self._velocity_dict[key][param_group_idx], + "LearningRate": lr_dict[key], + } + outputs = { + "ParamOut": self._param_dict[key][param_group_idx], + "VelocityOut": self._velocity_dict[key][ + param_group_idx + ], + } + attrs = { + "mu": self._momentum, + "use_nesterov": self._use_nesterov, + "regularization_method": self._regularization_method_dict[ + key + ][ + param_group_idx + ], + "regularization_coeff": self._regularization_coeff_dict[ + key + ][param_group_idx], + } + if find_master: + inputs["MasterParam"] = self._master_weight_dict[key][ + param_group_idx + ] + outputs["MasterParamOut"] = self._master_weight_dict[ + key + ][param_group_idx] + attrs["multi_precision"] = find_master + target_block.append_op( + type="merged_momentum", + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True, + ) + return None + + def _update_param_group(self, parameters): + self._momentum = parameters.get( + 'momentum', self._default_dict['momentum'] + ) + self._use_nesterov = parameters.get( + 'use_nesterov', self._default_dict['use_nesterov'] + ) + self._rescale_grad = parameters.get( + 'rescale_grad', self._default_dict['rescale_grad'] + ) + self._regularization_method = parameters.get( + 'regularization_method', self._default_dict['regularization_method'] + ) + self._regularization_coeff = parameters.get( + 'regularization_coeff', self._default_dict['regularization_coeff'] + ) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab61bb548731b6051d2f6caee97fc08c8a552cf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/optimizer.py @@ -0,0 +1,1536 @@ +# 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. + +from __future__ import print_function + +import numpy as np +import six +import logging +from collections import defaultdict + +import paddle +from paddle.fluid.distribute_lookup_table import find_distributed_lookup_table +from paddle.fluid.framework import ( + Program, + Variable, + name_scope, + default_main_program, + default_startup_program, + device_guard, +) + +from ..fluid import framework +from ..fluid import layers +from ..fluid import unique_name +from ..fluid.backward import ( + append_backward, + _some_in_set_, + _append_grad_suffix_, + _get_no_grad_set_name, +) +from ..fluid.clip import ( + GradientClipBase, + GradientClipByNorm, + error_clip_callback, + append_gradient_clip_ops, +) +from ..fluid.framework import program_guard, Parameter +from ..fluid.initializer import Constant +from ..fluid.layer_helper import LayerHelper +from ..fluid.layers import ops +from ..fluid.dygraph import base as imperative_base +from ..fluid.dygraph import no_grad +from paddle.fluid import core +from paddle.fluid.layers import tensor +from functools import reduce +from ..fluid.wrapped_decorator import signature_safe_contextmanager +from .. import compat as cpt +from .lr import LRScheduler +import copy +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import ( + _in_legacy_dygraph, + _in_eager_without_dygraph_check, + _current_expected_place, + in_dygraph_mode, +) + +__all__ = [] + + +@framework.static_only +def append_backward_new( + loss_list, + parameter_list=None, + no_grad_set=None, + callbacks=None, + checkpoints=None, + distop_context=None, +): + from paddle.incubate.autograd.primx import orig2prim, Transform + + program = default_main_program() + assert ( + program.num_blocks == 1 + ), "The append_backward_new interface is designed to process only one block." + block = program.current_block() + for el in loss_list: + assert ( + el.block == block + ), f'variable in loss_list should be in current block of main program' + + orig2prim(block) + ad = Transform(block) + if parameter_list is None: + parameter_list = program.global_block().all_parameters() + param_dot, loss_dot = ad.linearize(parameter_list, loss_list) + loss_bar, param_bar = ad.transpose(loss_dot, param_dot) + + # remove param_dot and their constructor ops + op_indexes = [] + for var in param_dot: + if var is not None: + op_index = block.ops.index(var.op) + assert op_index >= 0 + op_indexes.append(op_index) + + ad.erase_ops(sorted(op_indexes)) + ad.erase_dots(param_dot) + + if len(parameter_list) == 1: + params_and_grads = [(parameter_list, param_bar)] + else: + params_and_grads = [] + for i, param in enumerate(parameter_list): + params_and_grads.append((param, param_bar[i])) + return params_and_grads + + +class Optimizer(object): + r"""Optimizer Base class. + + Define the common interface of an optimizer. + User should not use this class directly, + but need to use one of it's implementation. + + Args: + learning_rate (float|LRScheduler): The learning rate used to update ``Parameter``. + It can be a float value or any subclass of ``LRScheduler`` . + parameters (list|tuple, optional): List/Tuple of ``Tensor`` names to update to minimize ``loss``. \ + This parameter is required in dygraph mode. And you can specify different options for \ + different parameter groups such as the learning rate, weight decay, etc, \ + then the parameters are list of dict. Note that the learning_rate in paramter groups \ + represents the scale of base learning_rate. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of \ + some derived class of ``GradientClipBase`` . There are three cliping strategies \ + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , \ + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name`. + The default value is None. + + Returns: + Base class for optimizer. + + Examples: + .. code-block:: python + + #Take the subclass adam as an example + import paddle + linear = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear(inp) + loss = paddle.mean(out) + adam = paddle.optimizer.Adam(learning_rate=0.1, + parameters=linear.parameters()) + loss.backward() + adam.step() + adam.clear_grad() + + #Take the subclass sgd as an example + #optimize parameters in linear_1 and linear2 in different options. + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + sgd = paddle.optimizer.SGD( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1 + }], + weight_decay=0.01) + loss.backward() + sgd.step() + sgd.clear_grad() + + """ + + @imperative_base.no_grad + def __init__( + self, + learning_rate, + parameters=None, + weight_decay=None, + grad_clip=None, + name=None, + ): + + if parameters is not None: + # paddle.Tensor is also iterable, so here we don't check whether + # the input is iterable, if the input is paddle.Tensor, the + # list(paddle.Tensor) will be a error value + if isinstance(parameters, (paddle.Tensor, core.eager.Tensor)): + raise TypeError( + "`parameters` argument given to the optimizer should be " + "an iterable of paddle Tensors, but got argument type is `{}`.".format( + type(parameters) + ) + ) + if isinstance(parameters, dict): + raise TypeError( + "`parameters` argument should not get dict type, " + "if parameter groups is needed, please set `parameters`" + " as list of dict" + ) + self._parameter_list = list(parameters) + else: + self._parameter_list = None + + self._name = name + if framework._non_static_mode(): + if self._parameter_list is None: + raise AttributeError( + "parameters argument given to the Optimizer should not be None in dygraph mode." + ) + if weight_decay is not None: + if not isinstance(self._parameter_list[0], dict): + for param in self._parameter_list: + if ( + hasattr(param, 'regularizer') + and param.regularizer is not None + ): + logging.info( + "If regularizer of a Parameter has been set by 'paddle.ParamAttr' or 'static.WeightNormParamAttr' already. " + "The weight_decay[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!" + % weight_decay.__str__() + ) + break + + if not isinstance(learning_rate, (float, LRScheduler)): + raise TypeError( + "learning rate should be float or LRScheduler, got %s here" + % type(learning_rate) + ) + if grad_clip is not None: + if not isinstance(grad_clip, GradientClipBase): + raise TypeError( + "'grad_clip' should be an instance of GradientClipBase's derived class" + ) + if isinstance(weight_decay, float): + from ..fluid.regularizer import L2Decay + + self.regularization = L2Decay(weight_decay) + else: + self.regularization = weight_decay + self._grad_clip = grad_clip + self._learning_rate = learning_rate + + self._dtype = None + # Infer the dtype form parameter + if self._parameter_list: + if isinstance(self._parameter_list[0], dict): + for param_group in self._parameter_list: + assert ( + 'params' in param_group + ), 'params should be set in parameters if parameter groups are optimized in different options' + self._dtype = self._parameter_list[0]['params'][0].dtype + else: + self._dtype = self._parameter_list[0].dtype + + # each program should have a independent learning rate + # program -> tensor(learning_rate) + self._learning_rate_map = dict() + # Dictionary of accumulators. Some optimizer subclasses need to + # allocate and manage extra tensors associated with the parameters + # to train. These tensors are called accumulators. + # {accum_name : { paramter_name : accumulator_for_parameter, ...}, ...} + self._accumulators = defaultdict(lambda: dict()) + self.helper = None + self._opti_name_list = [] + self._accumulators_holder = {} + self._param_device_map = dict() + self.clear_gradients = self.clear_grad + self._default_dict = { + 'weight_decay': self.regularization, + 'grad_clip': self._grad_clip, + } + + self._param_groups = [] + if self._parameter_list and isinstance(self._parameter_list[0], dict): + for param_group in self._parameter_list: + self._add_param_group(param_group.copy()) + else: + self._param_groups = self._parameter_list + + # NOTE: Multi Tensor: Pass in all parameters and gradients to the op kernel of the Optimizer at one time for updating for dygraph mode. + # Optimizer support list: [ paddle.optimizer.Momentum, paddle.optimizer.Adam]. + self._use_multi_tensor = None + + self._param_dict = self._create_multi_tensor_dict() + self._auxiliary_vars = {} + + def _set_auxiliary_var(self, key, val): + self._auxiliary_vars[key] = val + + def _create_multi_tensor_dict(self): + n = len(self._param_groups) if self._param_groups is not None else 1 + return { + 'FP32_LODTensor': [[] for _ in range(n)], + 'FP16_LODTensor': [[] for _ in range(n)], + } + + def _get_auxiliary_var(self, key): + return self._auxiliary_vars.get(key, None) + + @framework.dygraph_only + def state_dict(self): + ''' + Get state dict information from optimizer. It contain all the tensor used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be include in state dict. + If the optimizer never be called(minimize function), the state_dict is empty. + + Args: + None + + Returns: + state_dict(dict) : dict contains all the Tensor used by optimizer + + Examples: + .. code-block:: python + + import paddle + emb = paddle.nn.Embedding(10, 10) + + adam = paddle.optimizer.Adam(0.001, parameters=emb.parameters()) + state_dict = adam.state_dict() + + ''' + state_dict = {} + for k, v in self._accumulators.items(): + for para_name, var_tmp in v.items(): + state_dict[var_tmp.name] = var_tmp + # if has master weight and then save master weight + if hasattr(self, "_master_weights"): + if len(self._master_weights) != 0: + state_dict["master_weights"] = self._master_weights + # global step if use lr decay + if isinstance(self._learning_rate, LRScheduler): + state_dict["LR_Scheduler"] = self._learning_rate.state_dict() + return state_dict + + @framework.dygraph_only + def set_state_dict(self, state_dict): + ''' + Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LRScheduler have been used, global_step will be changed. + + Args: + state_dict(dict) : Dict contains all the Tensor needed by optimizer + Return: + None + + Examples: + .. code-block:: python + + import paddle + + emb = paddle.nn.Embedding(10, 10) + + layer_state_dict = emb.state_dict() + paddle.save(layer_state_dict, "emb.pdparams") + + scheduler = paddle.optimizer.lr.NoamDecay( + d_model=0.01, warmup_steps=100, verbose=True) + adam = paddle.optimizer.Adam( + learning_rate=scheduler, + parameters=emb.parameters()) + opt_state_dict = adam.state_dict() + paddle.save(opt_state_dict, "adam.pdopt") + + opti_state_dict = paddle.load("adam.pdopt") + adam.set_state_dict(opti_state_dict) + + ''' + if isinstance(self._learning_rate, LRScheduler): + self._learning_rate.set_state_dict(state_dict["LR_Scheduler"]) + + # NOTE: exclude learning rate scheduler's state from + # _accumulators_holder. + state_dict = state_dict.copy() + if "LR_Scheduler" in state_dict: + state_dict.pop("LR_Scheduler") + if "master_weights" in state_dict: + if hasattr(self, "_master_weights"): + self._master_weights = state_dict["master_weights"] + state_dict.pop("master_weights") + self._accumulators_holder = state_dict + for k, v in self._accumulators.items(): + for para_name, var_tmp in v.items(): + assert ( + var_tmp.name in state_dict + ), "optimizer Tensor {} not found".format(var_tmp.name) + var = var_tmp.value() + tensor = var.get_tensor() + model_np = np.array(tensor) + + load_para = state_dict[var_tmp.name] + + if isinstance(load_para, Variable): + load_para_np = load_para.numpy() + elif isinstance(load_para, core.VarBase): + load_para_np = load_para.numpy() + elif isinstance(load_para, np.ndarray): + load_para_np = load_para + else: + raise RuntimeError( + "State dict type {} not supprt".format( + str(type(load_para)) + ) + ) + + assert ( + model_np.shape == load_para_np.shape + ), "Parameter shape not match, Dygraph Parameter [ {} ] need tensor with shape {} but load tensor with shape {}".format( + model_np.name, model_np.shape, load_para_np.shape + ) + + assert ( + model_np.dtype == load_para_np.dtype + ), "Parameter dtype not match, Dygraph Parameter [ {} ] need tensor with dtype {} but load tensor with dtype {}".format( + model_np.name, model_np.dtype, load_para_np.dtype + ) + + tensor.set(load_para_np, framework._current_expected_place()) + + def get_opti_var_name_list(self): + return self._opti_name_list + + def _create_global_learning_rate(self): + # lr var can't be float16, for pure fp16 training, should extra handle the dtype for lr + _lr_dtype = ( + paddle.get_default_dtype() if self._dtype is None else self._dtype + ) + _lr_dtype = ( + paddle.float32 + if ( + paddle.get_default_dtype() != "float16" + and _lr_dtype == paddle.float16 + ) + else _lr_dtype + ) + if isinstance(self._learning_rate, LRScheduler): + lr_var = self._global_learning_rate() + # only create global lr_var once + if not isinstance(lr_var, framework.Variable): + lr_name = unique_name.generate('learning_rate') + self._learning_rate._var_name = lr_name + lr_var = self.helper.create_global_variable( + name=lr_name, + shape=[1], + persistable=True, + stop_gradient=True, + dtype=_lr_dtype, + ) + main_prog = framework.default_main_program() + main_prog.lr_sheduler = self._learning_rate + main_prog.lr_var = lr_var + + self._learning_rate_map[ + framework.default_main_program() + ] = lr_var + + lr_value = float(self._learning_rate()) + self.helper.set_variable_initializer( + lr_var, initializer=Constant(value=lr_value) + ) + elif isinstance(self._learning_rate, float): + # only create global lr_var once + lr = self._global_learning_rate() + if isinstance(lr, framework.Variable): + return + else: + self._learning_rate_map[ + framework.default_main_program() + ] = layers.create_global_var( + name=unique_name.generate("learning_rate"), + shape=[1], + value=float(self._learning_rate), + dtype=_lr_dtype, + persistable=True, + ) + + @framework.dygraph_only + def set_lr(self, value): + """ + :api_attr: imperative + + Set the value of the learning rate manually in the optimizer. If the optimizer use LRScheduler, + this API cannot be invoked, because it will lead to conflict. + + Args: + value (float): the value of learning rate + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + linear = paddle.nn.Linear(10, 10) + + adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters()) + + # set learning rate manually by python float value + lr_list = [0.2, 0.3, 0.4, 0.5, 0.6] + for i in range(5): + adam.set_lr(lr_list[i]) + lr = adam.get_lr() + print("current lr is {}".format(lr)) + # Print: + # current lr is 0.2 + # current lr is 0.3 + # current lr is 0.4 + # current lr is 0.5 + # current lr is 0.6 + + """ + if not isinstance(value, (int, float)): + raise TypeError( + "The type of 'value' in optimizer.set_lr must be float, but received %s." + % (type(value)) + ) + if isinstance(self._learning_rate, LRScheduler): + raise RuntimeError( + "optimizer's learning rate can't be LRScheduler when invoke this API, because this will lead to conflict." + ) + self._learning_rate = float(value) + current_lr = self._global_learning_rate() + if current_lr is not None: + if in_dygraph_mode(): + place = _current_expected_place() + _C_ops.full_( + current_lr, + list(current_lr.shape), + float(value), + current_lr.dtype, + place, + ) + + elif _in_legacy_dygraph(): + _legacy_C_ops.fill_constant( + current_lr, + 'value', + float(value), + 'dtype', + current_lr.dtype, + 'shape', + list(current_lr.shape), + ) + else: + global_block = framework.default_main_program().global_block() + global_block.append_op( + type='fill_constant', + outputs={'Out': [current_lr]}, + attrs={ + 'dtype': current_lr.dtype, + 'shape': list(current_lr.shape), + 'value': float(value), + }, + stop_gradient=True, + ) + + def get_lr(self): + """ + Get current learning rate of optimizer. + If 'LRScheduler' is not used, the return value is all the same. + If 'LRScheduler' is used, the return value is the current scheduled learing rete. + + Returns: + float: The current learning rate of optimizer. + + Examples: + .. code-block:: python + + # train on default dynamic graph mode + import paddle + import numpy as np + emb = paddle.nn.Embedding(10, 3) + + ## example1: LRScheduler is not used, return the same value is all the same + adam = paddle.optimizer.Adam(0.01, parameters = emb.parameters()) + for batch in range(10): + input = paddle.randint(low=0, high=5, shape=[5]) + out = emb(input) + out.backward() + print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.01 + adam.step() + + ## example2: StepDecay is used, return the scheduled learning rate + scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1) + adam = paddle.optimizer.Adam(scheduler, parameters = emb.parameters()) + for batch in range(10): + input = paddle.randint(low=0, high=5, shape=[5]) + out = emb(input) + out.backward() + print("Learning rate of step{}: {}".format(batch, adam.get_lr())) # 0.5->0.05... + adam.step() + scheduler.step() + + # train on static graph mode + paddle.enable_static() + main_prog = paddle.static.Program() + start_prog = paddle.static.Program() + with paddle.static.program_guard(main_prog, start_prog): + x = paddle.static.data(name='x', shape=[None, 10]) + z = paddle.static.nn.fc(x, 100) + loss = paddle.mean(z) + scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=2, gamma=0.1) + adam = paddle.optimizer.Adam(learning_rate=scheduler) + adam.minimize(loss) + + exe = paddle.static.Executor() + exe.run(start_prog) + for batch in range(10): + print("Learning rate of step{}: {}", adam.get_lr()) # 0.5->0.05->0.005... + out = exe.run(main_prog, feed={'x': np.random.randn(3, 10).astype('float32')}) + scheduler.step() + + """ + if isinstance(self._learning_rate, float): + return self._learning_rate + else: + return self._learning_rate() + + def _global_learning_rate(self, program=None): + """ + get global decayed learning rate + :return: + """ + if program is None: + program = framework.default_main_program() + return self._learning_rate_map.get(program, None) + + def _append_optimize_op(self, block, param_and_grad): + """append optimize operator to block and return all the added optimize_op""" + raise NotImplementedError( + "Class \"Optimizer\" connot be used directly as an optimizer, please use its subclasses such as \"Adam\"" + ) + + def _create_param_lr(self, param_and_grad): + # create learning rate tensor for every parameter + param = param_and_grad[0] + if hasattr(param, 'optimize_attr'): + param_lr = param.optimize_attr['learning_rate'] + if type(param_lr) == Variable: + return param_lr + else: + if param_lr == 1.0: + return self._global_learning_rate() + else: + with default_main_program()._lr_schedule_guard( + is_with_opt=True + ), framework.name_scope('scale_with_param_lr'): + return self._global_learning_rate() * param_lr + else: + return self._global_learning_rate() + + def _create_accumulators(self, block, parameters): + """Create all accumulators needed by the parameters + + Args: + block: the block in which the loss tensor is present + parameters: list of parameter tensors for the optimizer + """ + pass + + def _finish_update(self, block, parameters_and_grads): + """Finish any custom updates needed + before completing an optimization step + + Args: + block: the block in which the loss tensor is present + parameters: list of parameter tensors for the optimizer + + Returns: + None + """ + pass + + def _add_accumulator( + self, + name, + param, + dtype=None, + fill_value=0.0, + shape=None, + type=None, + device=None, + ): + """Utility function to add an accumulator for a parameter + + Args: + block: the block in which the loss tensor is present + name: name of the accumulator + param: parameter tensor for which accumulator is to be added + dtype: data type of the accumulator tensor + fill_value: value to initialize the accumulator tensor + """ + if self._name is not None: + name = self._name + "_" + name + if ( + name in self._accumulators + and param.name in self._accumulators[name] + ): + if framework._non_static_mode(): + return self._accumulators[name][param.name] + raise Exception( + "Accumulator {} already exists for parameter {}".format( + name, param.name + ) + ) + if shape == None: + shape = param.shape + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_" + name + var_name = unique_name.generate(var_name) + self._opti_name_list.append(var_name) + + var = self.helper.create_global_variable( + name=var_name, + persistable=True, + dtype=dtype or param.dtype, + type=core.VarDesc.VarType.LOD_TENSOR + if framework._in_eager_without_dygraph_check() + else (param.type if type is None else type), + shape=shape, + belong_to_optimizer=True, + ) + if device is None: + device = self._get_device_for_param(param.name) + with device_guard(device): + self.helper.set_variable_initializer( + var, initializer=Constant(value=float(fill_value)) + ) + + if framework._non_static_mode(): + if len(self._accumulators_holder) > 0: + assert ( + var_name in self._accumulators_holder + ), "Optimizer set error, {} should in state dict".format( + var_name + ) + var.set_value(self._accumulators_holder[var_name]) + + self._accumulators[name][param.name] = var + return var + + def _get_accumulator(self, name, param): + """Utility function to fetch an accumulator for a parameter + + Args: + name: name of the accumulator + param: parameter tensor for which accumulator is to be fetched + + Returns: + accumulator tensor for the parameter + """ + if self._name is not None: + name = self._name + "_" + name + if ( + name not in self._accumulators + or param.name not in self._accumulators[name] + ): + raise Exception( + "Accumulator {} does not exist for parameter {}".format( + name, param.name + ) + ) + return self._accumulators[name][param.name] + + def _update_param_device_map(self, parameters_and_grads, target_block): + for param_and_grad in parameters_and_grads: + if param_and_grad[0].stop_gradient is False: + param_name = param_and_grad[0].name + ops = target_block.ops + device_attr_name = ( + core.op_proto_and_checker_maker.kOpDeviceAttrName() + ) + for op in ops: + input_arg_names = op.input_arg_names + if param_name in input_arg_names: + self._param_device_map[param_name] = op.attr( + device_attr_name + ) + break + + def _get_device_for_param(self, param_name): + device = None + if param_name in self._param_device_map: + device = self._param_device_map[param_name] + return device + + def _create_optimization_pass( + self, parameters_and_grads, param_group_idx=0 + ): + """Add optimization operators to update gradients to tensors. + + Args: + parameters_and_grads(list(tuple(Tensor, Tensor))): + a list of (tensor, gradient) pair to update. + + Returns: + return_op_list: a list of operators that will complete one step of + optimization. This will include parameter update ops, global step + update ops and any other custom ops required by subclasses to manage + their internal state. + """ + # This is a default implementation of create_optimization_pass that + # can be shared by most optimizers. This implementation assumes that + # the subclass will implement the _append_optimize_op method and the + # _initialize_tensors method. The subclass can extend the + # _create_accumulators method if it needs to create accumulators + # for parameters and extend _finish_update method to add custom ops. + + # Allways called under program_guard use global block as loss block + # But if current block is in control flow, append optimize op in the + # grad block of current block + + global_block = framework.default_main_program().global_block() + target_block = global_block + current_block = framework.default_main_program().current_block() + if current_block.idx != global_block.idx: + assert ( + current_block.backward_block_idx != -1 + ), "current block is not global_block, but it doesn't have backward block." + target_block = framework.default_main_program().blocks[ + current_block.backward_block_idx + ] + + start = len(target_block.ops) + self.helper = LayerHelper(self.__class__.__name__) + + self._create_global_learning_rate() + + # NOTE: Multi Tensor support [ Momentum, Adam ] for dygraph mode + if self._use_multi_tensor and self.__class__.__name__ in [ + 'Momentum', + 'Adam', + ]: + if ( + len(self._param_dict['FP32_LODTensor'][param_group_idx]) == 0 + and len(self._param_dict['FP16_LODTensor'][param_group_idx]) + == 0 + ): + if isinstance(parameters_and_grads, list): + assert param_group_idx == 0 + self._multi_tensor_init( + target_block, + [ + p[0] + for p in parameters_and_grads + if not p[0].stop_gradient + ], + param_group_idx, + ) + else: + self._update_param_group(parameters_and_grads) + self._multi_tensor_init( + target_block, + [ + p[0] + for p in parameters_and_grads['params'] + if not p[0].stop_gradient + ], + param_group_idx, + ) + if framework._non_static_mode(): + self._append_optimize_multi_tensor_op( + target_block, + parameters_and_grads, + param_group_idx=param_group_idx, + ) + else: + self._update_param_device_map( + parameters_and_grads, target_block + ) + # NOTE: Multi Tensor requires all parameters to be in the same device and program. + # param_grad_list = [p_0,g_0,p_1,g_1,....] + param_grad_list = [] + for param_and_grad in parameters_and_grads: + if ( + not param_and_grad[0].stop_gradient + and param_and_grad[1] is not None + ): + param_grad_list.append(param_and_grad[0]) + param_grad_list.append(param_and_grad[1]) + with param_grad_list[0].block.program._optimized_guard( + param_grad_list + ), name_scope("optimizer"): + device = self._get_device_for_param(param_grad_list[0].name) + with device_guard(device): + self._append_optimize_multi_tensor_op( + target_block, + parameters_and_grads, + param_group_idx=param_group_idx, + ) + else: + if not framework._non_static_mode(): + params_grads_device_map = ( + parameters_and_grads['params'] + if isinstance(parameters_and_grads, dict) + else parameters_and_grads + ) + self._update_param_device_map( + params_grads_device_map, target_block + ) + + if isinstance(parameters_and_grads, list): + self._create_accumulators( + target_block, + [ + p[0] + for p in parameters_and_grads + if not p[0].stop_gradient + ], + ) + else: + params_acc_dict = parameters_and_grads.copy() + params_acc_dict['params'] = [ + p[0] + for p in params_acc_dict['params'] + if not p[0].stop_gradient + ] + self._create_accumulators(target_block, params_acc_dict) + + if framework._non_static_mode(): + if isinstance(parameters_and_grads, list): + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + self._append_optimize_op( + target_block, param_and_grad + ) + else: + for param_and_grad in parameters_and_grads['params']: + if param_and_grad[1] is None: + continue + if param_and_grad[0].stop_gradient is False: + param_grad_dict = dict() + param_grad_dict['params'] = param_and_grad + param_grad_dict.update( + { + k: v + for k, v in parameters_and_grads.items() + if k != 'params' + } + ) + self._append_optimize_op( + target_block, param_grad_dict + ) + else: + for param_and_grad in parameters_and_grads: + if param_and_grad[1] is None: + continue + with param_and_grad[0].block.program._optimized_guard( + param_and_grad + ), name_scope("optimizer"): + if param_and_grad[0].stop_gradient is False: + device = self._get_device_for_param( + param_and_grad[0].name + ) + with device_guard(device): + optimize_op = self._append_optimize_op( + target_block, param_and_grad + ) + + # Get custom finish ops for subclasses + # FIXME: Need to fix this once we figure out how to handle dependencies + self._finish_update(target_block, parameters_and_grads) + + end = len(target_block.ops) + return target_block._slice_ops(start, end) + + def _append_dgc_ops(self, param_and_grad): + pass + + def backward( + self, + loss, + startup_program=None, + parameters=None, + no_grad_set=None, + callbacks=None, + ): + """ + The first part of ``minimize``, do auto-diff to append backward operations for + the current program. + + Args: + loss (Tensor): ``loss`` tensor to run optimizations. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameters``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't need + to be updated. The default value is None. + callbacks (list, optional): list of callable objects to run when appending backward + operator for one parameter. The default value is None. + + Return: + list: list of (param, grad) tensor pairs, param is ``Parameter``, + grad is the gradient value corresponding to the parameter. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(26, dtype="float32").reshape([2, 13]) + + linear = paddle.nn.Linear(13, 5) + # This can be any optimizer supported by dygraph. + adam = paddle.optimizer.Adam(learning_rate = 0.01, + parameters = linear.parameters()) + out = linear(x) + out.backward() + adam.step() + adam.clear_grad() + """ + act_no_grad_set = None + if framework._non_static_mode(): + pass + else: + act_no_grad_set = self._get_no_grad_set(loss, no_grad_set) + + # Infer dtype by loss if None + if self._dtype is None: + self._dtype = loss.dtype + + if framework._non_static_mode(): + parameter_list = parameters if parameters else self._parameter_list + + params_grads = [] + for param in parameter_list: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + # create gradient tensor + grad_var = param._grad_ivar() + params_grads.append((param, grad_var)) + else: + if callbacks is None: + callbacks = [error_clip_callback] + else: + assert isinstance(callbacks, list) + program = loss.block.program + assert len(loss.shape) == 1 and loss.shape[0] == 1, ( + "The loss.shape should be (1L,), but the current loss.shape is {}. " + "Maybe that you should call paddle.mean to process the current loss.".format( + loss.shape + ) + ) + parameter_list = parameters if parameters else self._parameter_list + with program_guard(program, startup_program): + from paddle.incubate.autograd.utils import prim_enabled + + if prim_enabled(): + params_grads = append_backward_new( + [loss], parameter_list, act_no_grad_set, callbacks + ) + else: + params_grads = append_backward( + loss, parameter_list, act_no_grad_set, callbacks + ) + # Note: since we can't use all_reduce_op now, + # dgc_op should be the last op of one grad. + self._append_dgc_ops(params_grads) + return params_grads + + def apply_gradients(self, params_grads): + """ + Second part of `minimize`, appending optimization operators for + given `params_grads` pairs. + + Args: + params_grads (list): list of (param, grad) pair to do optimization. + + Returns: + list: A list of operators appended to the current program. + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1) + linear = paddle.nn.Linear(10, 10) + out = linear(inp) + loss = paddle.mean(out) + optimizer = paddle.optimizer.Adam(learning_rate=0.1, + parameters=linear.parameters()) + params_grads = optimizer.backward(loss) + optimizer.apply_gradients(params_grads) + + """ + + params_grads = sorted(params_grads, key=lambda x: x[0].name) + + # 'optimizer(grad_clip)' or 'set_gradient_clip' + if self._grad_clip is not None: + params_grads = self._grad_clip(params_grads) + else: + + params_grads = append_gradient_clip_ops(params_grads) + + # Add regularization if any + params_grads = self.append_regularization_ops( + params_grads, self.regularization + ) + + optimize_ops = self._create_optimization_pass(params_grads) + return optimize_ops + + def _apply_optimize( + self, loss, startup_program, params_grads, param_group_idx=0 + ): + """ + Second part of `minimize`, appending optimization operators for + given `params_grads` pairs. + Args: + loss (Tensor): loss tensor to run optimizations. + startup_program (Program): startup_program for initializing parameters + in `parameters`. + params_grads (list): list of (param, grad) pair to do optimization. + Returns: + list: A list of operators appended to the current program. + """ + if framework._non_static_mode(): + with program_guard( + framework.default_main_program(), + framework.default_startup_program(), + ): + if isinstance(params_grads, list): + if self._grad_clip is not None: + params_grads = self._grad_clip(params_grads) + params_grads = self.append_regularization_ops( + params_grads, self.regularization + ) + else: + grad_clip = params_grads['grad_clip'] + if grad_clip is not None: + params_grads['params'] = grad_clip( + params_grads['params'] + ) + + params_grads['params'] = self.append_regularization_ops( + params_grads['params'], self.regularization + ) + optimize_ops = self._create_optimization_pass( + params_grads, param_group_idx=param_group_idx + ) + else: + assert param_group_idx == 0 + program = loss.block.program + with program_guard(program, startup_program): + optimize_ops = self.apply_gradients(params_grads) + return optimize_ops + + def _create_regularization_of_grad(self, param, grad, regularization=None): + """Create and add backward regularization Operators + + Function helper of append_regularization_ops. + """ + # If no gradient or no regularization is specified, then we don't need to do anything + if grad is None or ( + ( + not hasattr(param, 'regularizer') + or (hasattr(param, 'regularizer') and param.regularizer is None) + ) + and regularization is None + ): + return grad + regularization_term = None + if hasattr(param, 'regularizer') and param.regularizer is not None: + # Add variable for regularization term in grad block + regularization_term = param.regularizer(param, grad, grad.block) + elif regularization is not None: + regularization_term = regularization(param, grad, grad.block) + + assert regularization_term is not None + + if framework.in_dygraph_mode(): + return _C_ops.add_n([grad, regularization_term]) + elif framework._in_legacy_dygraph(): + return _legacy_C_ops.sum([grad, regularization_term]) + + new_grad = grad + if grad.type == core.VarDesc.VarType.SELECTED_ROWS: + # FIXME(zcd): If the grad is SELECTED_ROWS, after regularization, + # the grad's type and name will be changed. But the gradient's name + # is used in ParallelExecutor Reduce mode, so I add a flag for + # the new_grad here. + new_grad = grad.block.create_var( + name=grad.name + core.kNewGradSuffix(), + dtype=param.dtype, + shape=param.shape, + lod_level=param.lod_level, + type=core.VarDesc.VarType.LOD_TENSOR, + ) + + inputs = {"X": [grad, regularization_term]} + outputs = {"Out": [new_grad]} + grad.block.append_op(type='sum', inputs=inputs, outputs=outputs) + + return new_grad + + def append_regularization_ops( + self, parameters_and_grads, regularization=None + ): + r"""Create and add backward regularization Operators + + Creates and adds backward regularization operators in the BlockDesc. + This will add gradients of the regularizer function to the gradients + of the parameters and return these modified gradients. This is the + same as implementing weight decay in optimizers for regularization. + + Args: + parameters_and_grads: A list of (parameters, gradients) pairs + that need to be regularized. + regularization: A global regularizer. If the parameter is not + set. It will be applied with regularizer. + + Returns: + list[(Variable, Variable)]: list of (parameters, gradients) \ + pair with the regularized gradient + + Raises: + Exception: Unknown regularization type + """ + params_and_grads = [] + if framework._non_static_mode(): + for param, grad in parameters_and_grads: + new_grad = self._create_regularization_of_grad( + param, grad, regularization + ) + params_and_grads.append((param, new_grad)) + else: + repeate_regularizer = False + with framework.name_scope('regularization'): + for param, grad in parameters_and_grads: + if ( + not repeate_regularizer + and param.regularizer is not None + and regularization is not None + ): + repeate_regularizer = True + logging.info( + "If regularizer of a Parameter has been set by 'fluid.ParamAttr' or 'fluid.WeightNormParamAttr' already. " + "The Regularization[%s] in Optimizer will not take effect, and it will only be applied to other Parameters!" + % regularization.__str__() + ) + with param.block.program._optimized_guard([param, grad]): + new_grad = self._create_regularization_of_grad( + param, grad, regularization + ) + params_and_grads.append((param, new_grad)) + return params_and_grads + + def _get_no_grad_set(self, loss, no_grad_set=None): + no_grad_set = _get_no_grad_set_name(no_grad_set) + parameters = loss.block.program.global_block().all_parameters() + param_no_trainable = set( + [param.name for param in parameters if param.stop_gradient is True] + ) + # If the parameter is no trainable, it should not have a gradient. + no_grad_set.update(param_no_trainable) + + return no_grad_set + + @framework.dygraph_only + def clear_grad(self, set_to_zero=True): + """ + Clear the gradients of all optimized parameters for model. + + If not, new gradient will accumulat on previous gradient. + + There are two method to clear grad: set_to_zero or delete grad. + + Args: + set_to_zero (bool, optional): If set grads to zero or not, default is True. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + a = paddle.arange(26, dtype="float32").reshape([2, 13]) + linear = paddle.nn.Linear(13, 5) + # This can be any optimizer supported by dygraph. + adam = paddle.optimizer.Adam(learning_rate = 0.01, + parameters = linear.parameters()) + out = linear(a) + out.backward() + adam.step() + adam.clear_grad() + + """ + param_list = [] + if self._parameter_list is None or not isinstance( + self._parameter_list[0], dict + ): + for p in self._parameter_list: + if not p.stop_gradient: + param_list.append(p) + else: + for param_group in self._param_groups: + for p in param_group['params']: + if not p.stop_gradient: + param_list.append(p) + + if _in_eager_without_dygraph_check(): + for p in param_list: + p.clear_gradient(set_to_zero) + else: + core.clear_gradients(param_list, set_to_zero) + + @imperative_base.no_grad + def minimize( + self, loss, startup_program=None, parameters=None, no_grad_set=None + ): + """ + Add operations to minimize ``loss`` by updating ``parameters``. + + Args: + loss (Tensor): A ``Tensor`` containing the value to minimize. + startup_program (Program, optional): :ref:`api_fluid_Program` for + initializing parameters in ``parameters``. The default value + is None, at this time :ref:`api_fluid_default_startup_program` will be used. + parameters (list, optional): List of ``Tensor`` or ``Tensor.name`` to update + to minimize ``loss``. The default value is None, at this time all parameters + will be updated. + no_grad_set (set, optional): Set of ``Tensor`` or ``Tensor.name`` that don't need + to be updated. The default value is None. + + Returns: + tuple: tuple (optimize_ops, params_grads), A list of operators appended + by minimize and a list of (param, grad) tensor pairs, param is + ``Parameter``, grad is the gradient value corresponding to the parameter. + In static graph mode, the returned tuple can be passed to ``fetch_list`` in ``Executor.run()`` to + indicate program pruning. If so, the program will be pruned by ``feed`` and + ``fetch_list`` before run, see details in ``Executor``. + + Examples: + .. code-block:: python + + import paddle + linear = paddle.nn.Linear(10, 10) + input = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear(input) + loss = paddle.mean(out) + + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + + adam = paddle.optimizer.Adam(learning_rate=0.1, + parameters=linear.parameters(), + weight_decay=0.01) + loss.backward() + adam.minimize(loss) + adam.clear_grad() + + """ + assert isinstance(loss, Variable), "The loss should be an Tensor." + + parameter_list = parameters if parameters else self._parameter_list + + params_grads = self.backward( + loss, + startup_program=startup_program, + parameters=parameter_list, + no_grad_set=no_grad_set, + ) + + optimize_ops = self._apply_optimize( + loss, startup_program=startup_program, params_grads=params_grads + ) + + return optimize_ops, params_grads + + @imperative_base.no_grad + @framework.dygraph_only + def step(self): + """ + Execute the optimizer and update parameters once. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + a = paddle.arange(26, dtype="float32").reshape([2, 13]) + linear = paddle.nn.Linear(13, 5) + # This can be any optimizer supported by dygraph. + adam = paddle.optimizer.Adam(learning_rate = 0.01, + parameters = linear.parameters()) + out = linear(a) + out.backward() + adam.step() + adam.clear_grad() + """ + + if not isinstance(self._param_groups[0], dict): + params_grads = [] + for param in self._param_groups: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + params_grads.append((param, grad_var)) + + self._apply_optimize( + loss=None, + startup_program=None, + params_grads=params_grads, + param_group_idx=0, + ) + + else: + # optimize parameters in groups + for idx, param_group in enumerate(self._param_groups): + params_grads = defaultdict(lambda: list()) + for param in param_group['params']: + if param.stop_gradient: + continue + if param._grad_ivar() is not None: + grad_var = param._grad_ivar() + params_grads['params'].append((param, grad_var)) + params_grads.update( + {k: v for k, v in param_group.items() if k != 'params'} + ) + self._apply_optimize( + loss=None, + startup_program=None, + params_grads=params_grads, + param_group_idx=idx, + ) + + def _add_param_group(self, param_group): + """ + Add a param group to parameter_list. + + Args: + param_group (dict): The group of Tensors to be optimzed with + different optimization options. + """ + params = param_group['params'] + if isinstance(params, Parameter): + param_group['params'] = [params] + elif isinstance(params, set): + raise TypeError( + "optimizer parameters should be in ordered collections," + "but received set, please use list instead." + ) + else: + param_group['params'] = list(params) + + # Update optimization options for each groups + for k, v in self._default_dict.items(): + param_group.setdefault(k, v) + + param_set = set() + for group in self._param_groups: + param_set.update(set(group['params'])) + + if not param_set.isdisjoint(set(param_group['params'])): + raise ValueError( + "some parameters appear in more than one parameter group" + ) + + for param in param_group['params']: + weight_decay = param_group['weight_decay'] + if isinstance(weight_decay, float): + from ..fluid.regularizer import L2Decay + + regularization = L2Decay(weight_decay) + else: + regularization = weight_decay + param.regularizer = regularization + param.optimize_attr['learning_rate'] = param_group.get( + 'learning_rate', 1.0 + ) + + self._param_groups.append(param_group) + + def _update_param_group(self, parameters): + """ + Update the param group with new entry + Args: + parameters (dict): The extra group of Tensors to be optimzed with + different optimization options. Only used in child class. + """ + pass + + @framework.dygraph_only + def _multi_tensor_init(self, target_block, parameters, param_group_idx): + """ + All parameters used for optimizer (such as: parameters, master_weight, velocity_acc for momentum) calculations are grouped into a python list by data type (float16, float32). + This function will be overridden in the corresponding optimizer file. + + Args: + target_block: the block in which the loss tensor is present + parameters: list of parameter tensors for the optimizer + """ + pass + + @framework.dygraph_only + def _append_optimize_multi_tensor_op( + self, target_block, parameters_and_grads, param_group_idx + ): + """ + For Multi Tensor, append optimize merged_operator to block. + """ + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/rmsprop.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/rmsprop.py new file mode 100644 index 0000000000000000000000000000000000000000..10532c8f62846b2ddfdb1212274d2494ccf9ffc0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/rmsprop.py @@ -0,0 +1,258 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable + +__all__ = [] + + +class RMSProp(Optimizer): + r""" + Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning + rate method. The original slides proposed RMSProp: Slide 29 of + http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf . + + The original equation is as follows: + + .. math:: + + r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2 + + w & = w - \frac{\eta} {\sqrt{r(w,t) + \epsilon}} \nabla Q_{i}(w) + + The first equation calculates moving average of the squared gradient for + each weight. Then dividing the gradient by :math:`sqrt{v(w,t)}`. + + In some cases, adding a momentum term :math: `\\beta` is beneficial. + In our implementation, Nesterov momentum is used: + + .. math:: + + r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2 + + v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) + + \epsilon}} \nabla Q_{i}(w) + + w & = w - v(w, t) + + if centered is True: + + .. math:: + + r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2 + + g(w, t) & = \rho g(w, t-1) + (1 - \rho)\nabla Q_{i}(w) + + v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) - (g(w, t))^2 + + \epsilon}} \nabla Q_{i}(w) + + w & = w - v(w, t) + + where, :math:`\rho` is a hyperparameter and typical values are 0.9, 0.95 + and so on. :math:`\beta` is the momentum term. :math:`\epsilon` is a + smoothing term to avoid division by zero, usually set somewhere in range + from 1e-4 to 1e-8. + + + Parameters: + learning_rate (float|LRScheduler): The learning rate used to update ``Parameter``. + It can be a float value or a LRScheduler. + rho(float, optional): rho is :math:`\rho` in equation, default is 0.95. + epsilon(float, optional): :math:`\epsilon` in equation is smoothing term to + avoid division by zero, default is 1e-6. + momentum(float, optional): :math:`\beta` in equation is the momentum term, + default is 0.0. + centered(bool, optional): If True, gradients are normalized by the estimated variance of + the gradient; if False, by the uncentered second moment. Setting this to + True may help with training, but is slightly more expensive in terms of + computation and memory. Defaults to False. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. + This parameter is required in dygraph mode. And you can specify different options for + different parameter groups such as the learning rate, weight decay, etc, + then the parameters are list of dict. Note that the learning_rate in paramter groups + represents the scale of base learning_rate. + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, + the regularization setting here in optimizer will be ignored for this parameter. + Otherwise, the regularization setting here in optimizer will take effect. + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): This parameter is used by developers to print debugging information. + For details, please refer to :ref:`api_guide_Name`. Default is None. + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.rand([10,10], dtype="float32") + linear = paddle.nn.Linear(10, 10) + out = linear(inp) + loss = paddle.mean(out) + + rmsprop = paddle.optimizer.RMSProp(learning_rate=0.1, + parameters=linear.parameters(), + weight_decay=0.01) + out.backward() + rmsprop.step() + rmsprop.clear_grad() + + #Note that the learning_rate of linear_2 is 0.01. + linear_1 = paddle.nn.Linear(10, 10) + linear_2 = paddle.nn.Linear(10, 10) + inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) + out = linear_1(inp) + out = linear_2(out) + loss = paddle.mean(out) + rmsprop = paddle.optimizer.RMSProp( + learning_rate=0.1, + parameters=[{ + 'params': linear_1.parameters() + }, { + 'params': linear_2.parameters(), + 'weight_decay': 0.001, + 'learning_rate': 0.1 + }], + weight_decay=0.01) + out.backward() + rmsprop.step() + rmsprop.clear_grad() + """ + + _momentum_acc_str = "momentum" + _mean_square_acc_str = "mean_square" + _mean_grad_acc_str = "mean_grad" + + def __init__( + self, + learning_rate, + rho=0.95, + epsilon=1.0e-6, + momentum=0.0, + centered=False, + parameters=None, + weight_decay=None, + grad_clip=None, + name=None, + ): + if learning_rate is None: + raise ValueError("learning_rate is not set.") + if rho is None: + raise ValueError("rho is not set.") + if epsilon is None: + raise ValueError("epsilon is not set.") + if momentum is None: + raise ValueError("momentum is not set.") + if not 0.0 <= epsilon: + raise ValueError("Invalid value of epsilon, expect epsilon >= 0.") + if not 0.0 <= momentum: + raise ValueError("Invalid value of momentum, expect momentum >= 0.") + if not 0.0 <= rho: + raise ValueError("Invalid value of rho, expect rho >= 0.") + + super(RMSProp, self).__init__( + learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name, + ) + + self.type = "rmsprop" + self._rho = rho + self._epsilon = epsilon + self._momentum = momentum + self._centered = centered + self._default_dict = { + 'rho': rho, + 'epsilon': epsilon, + 'momentum': momentum, + 'centered': centered, + } + + def _create_accumulators(self, block, parameters): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + if isinstance(parameters, dict): + parameters = parameters.get('params') + + for p in parameters: + self._add_accumulator(self._momentum_acc_str, p) + self._add_accumulator(self._mean_square_acc_str, p) + self._add_accumulator(self._mean_grad_acc_str, p) + + def _append_optimize_op(self, block, param_and_grad): + if not isinstance(block, framework.Block): + raise TypeError("block is not instance of framework.Block.") + + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + momentum_acc = self._get_accumulator( + self._momentum_acc_str, param_and_grad[0] + ) + mean_square_acc = self._get_accumulator( + self._mean_square_acc_str, param_and_grad[0] + ) + mean_grad_acc = self._get_accumulator( + self._mean_grad_acc_str, param_and_grad[0] + ) + rmsprop_op = block.append_op( + type=self.type, + inputs={ + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "Moment": momentum_acc, + "MeanSquare": mean_square_acc, + "MeanGrad": mean_grad_acc, + "LearningRate": self._create_param_lr(param_and_grad), + }, + outputs={ + "ParamOut": param_and_grad[0], + "MomentOut": momentum_acc, + "MeanSquareOut": mean_square_acc, + "MeanGradOut": mean_grad_acc, + }, + attrs={ + "epsilon": self._epsilon, + "decay": self._rho, + "momentum": self._momentum, + "centered": self._centered, + }, + stop_gradient=True, + ) + + return rmsprop_op + + def _update_param_group(self, parameters): + self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) + self._rho = parameters.get('rho', self._default_dict['rho']) + self._momentum = parameters.get( + 'momentum', self._default_dict['momentum'] + ) + self._centered = parameters.get( + 'centered', self._default_dict['centered'] + ) + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/sgd.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5b9f4c4f14512677621b8348afe42a1d1bc03f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/optimizer/sgd.py @@ -0,0 +1,180 @@ +# 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. + +from .optimizer import Optimizer +from ..fluid import core +from ..fluid import framework +from ..fluid.framework import Variable, name_scope +from ..fluid.dygraph import no_grad +from paddle import _C_ops, _legacy_C_ops +import warnings +from ..fluid.layer_helper import LayerHelper +from ..fluid import unique_name +from ..fluid import layers +from ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode + +__all__ = [] + + +class SGD(Optimizer): + r""" + Optimizer of the stochastic gradient descent algorithm. + + .. math:: + + param\_out = param - learning\_rate * grad + + Parameters: + learning_rate (float|Tensor|LearningRateDecay, optional): The learning rate used to update ``Parameter``. + It can be a float value, a ``Tensor`` with a float type or a LearningRateDecay. The default value is 0.001. + parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \ + This parameter is required in dygraph mode. \ + The default value is None in static mode, at this time all parameters will be updated. + weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \ + It canbe a float value as coeff of L2 regularization or \ + :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`. + If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \ + the regularization setting here in optimizer will be ignored for this parameter. \ + Otherwise, the regularization setting here in optimizer will take effect. \ + Default None, meaning there is no regularization. + grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of + some derived class of ``GradientClipBase`` . There are three cliping strategies + ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , + :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name` . + + Examples: + .. code-block:: python + + import paddle + + inp = paddle.uniform(min=-0.1, max=0.1, shape=[10, 10], dtype='float32') + linear = paddle.nn.Linear(10, 10) + inp = paddle.to_tensor(inp) + out = linear(inp) + loss = paddle.mean(out) + sgd = paddle.optimizer.SGD(learning_rate=0.1, parameters=linear.parameters(), weight_decay=0.01) + out.backward() + sgd.step() + sgd.clear_grad() + + """ + + def __init__(self, + learning_rate=0.001, + parameters=None, + weight_decay=None, + grad_clip=None, + multi_precision=False, + name=None): + if learning_rate is None: + raise ValueError("learning_rate is not set") + super(SGD, self).__init__(learning_rate=learning_rate, + parameters=parameters, + weight_decay=weight_decay, + grad_clip=grad_clip, + name=name) + self.type = "sgd" + self._multi_precision = multi_precision + self._master_weights = {} + + def _create_master_weight(self, param): + if param.name in self._master_weights: + var = self._master_weights[param.name] + else: + assert isinstance(self.helper, LayerHelper) + + var_name = param.name + "_fp32_master" + var_name = unique_name.generate(var_name) + var = layers.create_global_var(name=var_name, + shape=param.shape, + value=0, + dtype='float32', + persistable=True) + block = self.helper.startup_program.global_block() + block.append_op(type="cast", + inputs={"X": [param]}, + outputs={"Out": [var]}, + attrs={ + "in_dtype": param.dtype, + "out_dtype": core.VarDesc.VarType.FP32 + }) + self._master_weights[param.name] = var + return var + + def _create_accumulators(self, block, parameters): + assert isinstance(block, framework.Block) + if isinstance(parameters, dict): + parameters = self._update_param_group(parameters) + + # Create accumulator tensors for first and second moments + for p in parameters: + if self._multi_precision and p.dtype == core.VarDesc.VarType.FP16: + master_p = self._create_master_weight(p) + continue + if p.dtype == core.VarDesc.VarType.FP16 and not self._multi_precision: + warnings.warn( + "Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence." + "Consider using multi_precision=True option of the Adam optimizer." + ) + + @no_grad + def _append_optimize_op(self, block, param_and_grad): + if isinstance(param_and_grad, dict): + param_and_grad = self._update_param_group(param_and_grad) + + find_master = self._multi_precision and param_and_grad[ + 0].dtype == core.VarDesc.VarType.FP16 + master_weight = (self._master_weights[param_and_grad[0].name] + if find_master else None) + + lr = self._create_param_lr(param_and_grad) + if in_dygraph_mode(): + _C_ops.sgd_(param_and_grad[0], lr, param_and_grad[1], master_weight, + find_master) + return None + if _in_legacy_dygraph(): + _legacy_C_ops.sgd(param_and_grad[0], lr, param_and_grad[1], + master_weight, param_and_grad[0], master_weight) + return None + + assert isinstance(block, framework.Block) + # create the optimize op + inputs = { + "Param": param_and_grad[0], + "Grad": param_and_grad[1], + "LearningRate": lr + } + + outputs = {"ParamOut": param_and_grad[0]} + + attrs = {"multi_precision": find_master} + + if find_master: + inputs["MasterParam"] = master_weight + outputs["MasterParamOut"] = master_weight + + sgd_op = block.append_op(type=self.type, + inputs=inputs, + outputs=outputs, + attrs=attrs, + stop_gradient=True) + + return sgd_op + + def _update_param_group(self, parameters): + parameters = parameters.get('params') + return parameters diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76108cf2953f8313adfbec3e0958876ab52e8372 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2022 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. + +from .profiler import ProfilerState, ProfilerTarget +from .profiler import make_scheduler, export_chrome_tracing, export_protobuf +from .profiler import Profiler +from .profiler import SummaryView +from .profiler import TracerEventType +from .utils import RecordEvent, load_profiler_result +from .profiler_statistic import SortedKeys + +__all__ = [ + 'ProfilerState', 'ProfilerTarget', 'make_scheduler', + 'export_chrome_tracing', 'export_protobuf', 'Profiler', 'RecordEvent', + 'load_profiler_result', 'SortedKeys', 'SummaryView' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..03cfb3a9a42231f639c022aebaebcb5c07fc1b93 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler.py @@ -0,0 +1,957 @@ +# Copyright (c) 2022 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. + +import os +import socket +import datetime +from enum import Enum +from typing import Any, Callable, Iterable, Optional, Union +from warnings import warn +import importlib +import json + +import paddle +from paddle.fluid.core import ( + _Profiler, + _ProfilerResult, + ProfilerOptions, + TracerEventType, + enable_memory_recorder, + enable_input_shape_recorder, + disable_memory_recorder, + disable_input_shape_recorder, +) + +from .utils import RecordEvent, wrap_optimizers +from .profiler_statistic import StatisticData, _build_table, SortedKeys +from paddle.profiler import utils +from .timer import benchmark + + +class SummaryView(Enum): + r""" + SummaryView define the summary view of different contents. + + - **SummaryView.DeviceView** : The device summary view. + + - **SummaryView.OverView** : The overview summary view. + + - **SummaryView.ModelView** : The model summary view. + + - **SummaryView.DistributedView** : The distributed summary view. + + - **SummaryView.KernelView** : The kernel summary view. + + - **SummaryView.OperatorView** : The operator summary view. + + - **SummaryView.MemoryView** : The memory summary view. + + - **SummaryView.MemoryManipulationView** : The meomory manipulation summary view. + + - **SummaryView.UDFView** : The user defined summary view. + """ + DeviceView = 0 + OverView = 1 + ModelView = 2 + DistributedView = 3 + KernelView = 4 + OperatorView = 5 + MemoryView = 6 + MemoryManipulationView = 7 + UDFView = 8 + + +class ProfilerState(Enum): + r""" + ProfilerState is used to present the state of :ref:`Profiler ` . + + The meaning of each ProfilerState is as following + + - **ProfilerState.CLOSED** : The profiler is closed, and no profiling data will be recorded. + + - **ProfilerState.READY** : The profiler is open, but the data will not be recorded. This state is used for reducing overhead influence when profiler starts. + + - **ProfilerState.RECORD** : The profiler is open, and the data will be recorded. + + - **ProfilerState.RECORD_AND_RETURN** : The profiler is open, and this state stands for the last batch of "RECORD" state in current profiling period. The collected data will be returned in this state. + """ + CLOSED = 0 + READY = 1 + RECORD = 2 + RECORD_AND_RETURN = 3 # the last step of RECORD + + +class ProfilerTarget(Enum): + r""" + ProfilerTarget is used to specify target device for :ref:`profiling ` . Only CPU, GPU and MLU are supported currently. + + The meaning of each ProfilerState is as following + + - **ProfilerTarget.CPU** : Profile events on CPU. + + - **ProfilerTarget.GPU** : Profile events on GPU. + + - **ProfilerTarget.MLU** : Profile events on MLU. + """ + CPU = 0 + GPU = 1 + MLU = 2 + CUSTOM_DEVICE = 3 + + +def make_scheduler( + *, + closed: int, + ready: int, + record: int, + repeat: int = 0, + skip_first: int = 0 +) -> Callable: + r""" + Return a scheduler function, which scheduler the :ref:`state ` according to the setting. + The state transform confirms to: + + .. code-block:: text + + (CLOSED) (CLOSED) (CLOSED) (READY) (RECORD,last RETURN) (CLOSED) + START -> skip_first -> closed -> ready -> record -> END + | | + | | (if has_repeated < repeat) + - - - - - - - - - - - - + Note that repeat <= 0 means the cycle will continue until the profiler exits. + + Args: + closed(int): The number of steps in state ProfilerState.CLOSED. + ready(int): The number of steps in state ProfilerState.READY. + record(int): The number of steps in state ProfilerState.RECORD, and the state in last step will be set as ProfilerState.RECORD_AND_RETURN. + repeat(int, optional): The number of cycles to repeat above state transform. Default value is 0, which means it will repeat this cycle until profiler exits. + skip_first(int, optional): The number of first steps to drop, not participate in the state transform, and at ProfilerState.CLOSED state. Default value is 0. + + Returns: + A scheduler function, conforms to above state transform setting. The function will takes one parameter `step_num`, and returns corresponding ProfilerState. + + Examples: + 1. profiling range [2, 5]. + + Assume batch 0: closed, batch 1: ready, batch [2, 5] record. + + .. code-block:: python + :name: code-example1 + + import paddle.profiler as profiler + profiler.make_scheduler(closed=1, ready=1, record=4, repeat=1) + + + 2. profiling range [3,6], [9,12], [15,18]. + + Assume batch 0: skiped, batch 1: closed, batch 2: ready, batch [3,6]: record, repeat. + + .. code-block:: python + :name: code-example2 + + import paddle.profiler as profiler + profiler.make_scheduler(closed=1, ready=1, record=4, skip_first=1) + """ + + def getScheduleState(step: int) -> ProfilerState: + assert step >= 0 + if step < skip_first: # within skip_first, just skip + return ProfilerState.CLOSED + step = step - skip_first + period_steps = closed + ready + record + has_repeated = step // period_steps + if ( + repeat > 0 and has_repeated >= repeat + ): # the period has repeated repeat times, return CLOSED state + return ProfilerState.CLOSED + mod_step = step % period_steps + if mod_step < closed: + return ProfilerState.CLOSED + elif mod_step >= closed and mod_step < closed + ready: + return ProfilerState.READY + else: + if mod_step < period_steps - 1: + return ProfilerState.RECORD + else: + return ProfilerState.RECORD_AND_RETURN + + assert ( + closed >= 0 + and ready >= 0 + and record > 0 + and repeat >= 0 + and skip_first >= 0 + ), "Invalid profiler scheduler arguments" + if ready == 0: + warn( + "Profiler will record data after enabling profiler immediately, \ + some data collected at the beginning of profiling may be 'noisy' because of overhead." + ) + return getScheduleState + + +def _default_state_scheduler(step: int): + r""" + A default state scheduler, keep recording from the beginning of the profiler until ending. + """ + return ProfilerState.RECORD + + +def export_chrome_tracing( + dir_name: str, worker_name: Optional[str] = None +) -> Callable: + r""" + Return a callable, used for outputing tracing data to chrome tracing format file. + The output file will be saved in directory ``dir_name``, and file name will be set as `worker_name`. + if `worker_name` is not set, the default name is `[hostname]_[pid]`. + + Args: + dir_name(str): Directory to save profiling data. + worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`. + + Returns: + A callable, which takes a Profiler object as parameter and calls its export method to save data to chrome tracing format file. + + Examples: + The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler ` . + + .. code-block:: python + + # required: gpu + import paddle.profiler as profiler + with profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 10), + on_trace_ready=profiler.export_protobuf('./log')) as p: + for iter in range(10): + #train() + p.step() + """ + if not os.path.exists(dir_name): + try: + os.makedirs(dir_name, exist_ok=True) + except Exception: + raise RuntimeError( + "Can not create directory '{}' for saving profiling results.".format( + dir_name + ) + ) + + def handle_fn(prof): + nonlocal worker_name + if not worker_name: + worker_name = "host_{}pid_{}".format( + socket.gethostname(), str(os.getpid()) + ) + now = datetime.datetime.now() + filename = '{}_time_{}.paddle_trace.json'.format( + worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f') + ) + prof.export(os.path.join(dir_name, filename), "json") + + return handle_fn + + +def export_protobuf( + dir_name: str, worker_name: Optional[str] = None +) -> Callable: + r""" + Return a callable, used for outputing tracing data to protobuf file. + The output file will be saved in directory ``dir_name``, and file name will be set as ``worker_name``. + if ``worker_name`` is not set, the default name is `[hostname]_[pid]`. + + Args: + dir_name(str): Directory to save profiling data. + worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`. + + Returns: + A callable, which takes a Profiler object as parameter and calls its export method to save data to protobuf file. + + Examples: + The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler ` . + + .. code-block:: python + + # required: gpu + import paddle.profiler as profiler + with profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 10), + on_trace_ready = profiler.export_protobuf('./log')) as p: + for iter in range(10): + #train() + p.step() + """ + if not os.path.exists(dir_name): + try: + os.makedirs(dir_name, exist_ok=True) + except Exception: + raise RuntimeError( + "Can not create directory '{}' for saving profiling results.".format( + dir_name + ) + ) + + def handle_fn(prof): + nonlocal worker_name + if not worker_name: + worker_name = "host_{}pid_{}".format( + socket.gethostname(), str(os.getpid()) + ) + now = datetime.datetime.now() + filename = '{}_time_{}.paddle_trace.pb'.format( + worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f') + ) + prof.export(os.path.join(dir_name, filename), "pb") + + return handle_fn + + +def _get_supported_targets() -> Iterable[ProfilerTarget]: + r""" + Get the current supported profiler target in the system. + """ + if _Profiler.is_cupti_supported(): + return [ + ProfilerTarget.CPU, + ProfilerTarget.GPU, + ProfilerTarget.CUSTOM_DEVICE, + ] + if _Profiler.is_cnpapi_supported(): + return [ + ProfilerTarget.CPU, + ProfilerTarget.MLU, + ProfilerTarget.CUSTOM_DEVICE, + ] + return [ProfilerTarget.CPU, ProfilerTarget.CUSTOM_DEVICE] + + +class Profiler: + r""" + Profiler context manager, user interface to manage profiling process to start, stop, export profiling data and print summary table. + + Args: + targets (list, optional): specify target devices to profile, and all existing and supported devices will be chosen by default. Currently supported values, :ref:`ProfilerTarget.CPU ` , :ref:`ProfilerTarget.GPU ` and :ref:`ProfilerTarget.MLU ` . + scheduler (Callable|tuple, optional): If it is a callable object, it takes a step number as parameter and return the corresponding :ref:`ProfilerState `. This callable object can be generated by :ref:`make_scheduler ` function. + If not provided (None), the default scheduler will keep tracing until the profiler exits. If it is a tuple, it has two values start_batch and end_batch, + which means profiling range [start_batch, end_batch). + on_trace_ready (Callable, optional): Callable object, serves as callback function, and takes the Profiler object as parameter, which provides a way for users to do post-processing. + This callable object will be called when ``scheduler`` returns ``ProfilerState.RECORD_AND_RETURN``. The default value is :ref:`export_chrome_tracing `. + timer_only (bool, optional): If it is True, the cost of Dataloader and every step of the model will be count without profiling. Otherwise, the model will + be timed and profiled. Default: False. + record_shapes (bool, optional): If it is True, collect op's input shape information. Default: False. + profile_memory (bool, optional): If it is True, collect tensor memory allocation and release information. Default: False. + + Examples: + 1. profiling range [2, 5). + + .. code-block:: python + :name: code-example1 + + # required: gpu + import paddle.profiler as profiler + with profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (2, 5), + on_trace_ready = profiler.export_chrome_tracing('./log')) as p: + for iter in range(10): + #train() + p.step() + + 2. profiling range [2,4], [7, 9], [11,13]. + + .. code-block:: python + :name: code-example2 + + # required: gpu + import paddle.profiler as profiler + with profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = profiler.make_scheduler(closed=1, ready=1, record=3, repeat=3), + on_trace_ready = profiler.export_chrome_tracing('./log')) as p: + for iter in range(10): + #train() + p.step() + + 3. Use profiler without context manager, and use default parameters. + + .. code-block:: python + :name: code-example3 + + # required: gpu + import paddle.profiler as profiler + p = profiler.Profiler() + p.start() + for iter in range(10): + #train() + p.step() + p.stop() + p.summary() + + 4. Use profiler to get throughput and cost of the model. + + .. code-block:: python + :name: code-example-timer1 + + import paddle + import paddle.profiler as profiler + + class RandomDataset(paddle.io.Dataset): + def __init__(self, num_samples): + self.num_samples = num_samples + + def __getitem__(self, idx): + image = paddle.rand(shape=[100], dtype='float32') + label = paddle.randint(0, 10, shape=[1], dtype='int64') + return image, label + + def __len__(self): + return self.num_samples + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + self.fc = paddle.nn.Linear(100, 10) + + def forward(self, image, label=None): + return self.fc(image) + + dataset = RandomDataset(20 * 4) + simple_net = SimpleNet() + opt = paddle.optimizer.SGD(learning_rate=1e-3, parameters=simple_net.parameters()) + BATCH_SIZE = 4 + loader = paddle.io.DataLoader( + dataset, + batch_size=BATCH_SIZE) + p = profiler.Profiler(timer_only=True) + p.start() + for i, (image, label) in enumerate(loader()): + out = simple_net(image) + loss = paddle.nn.functional.cross_entropy(out, label) + avg_loss = paddle.mean(loss) + avg_loss.backward() + opt.minimize(avg_loss) + simple_net.clear_gradients() + p.step(num_samples=BATCH_SIZE) + if i % 10 == 0: + step_info = p.step_info(unit='images') + print("Iter {}: {}".format(i, step_info)) + # The average statistics for 10 steps between the last and this call will be + # printed when the "step_info" is called at 10 iteration intervals. + # The values you get may be different from the following. + # Iter 0: reader_cost: 0.51946 s batch_cost: 0.66077 s ips: 6.054 images/s + # Iter 10: reader_cost: 0.00014 s batch_cost: 0.00441 s ips: 907.009 images/s + p.stop() + # The performance summary will be automatically printed when the "stop" is called. + # Reader Ratio: 2.658% + # Time Unit: s, IPS Unit: images/s + # | | avg | max | min | + # | reader_cost | 0.00011 | 0.00013 | 0.00007 | + # | batch_cost | 0.00405 | 0.00434 | 0.00326 | + # | ips | 1086.42904 | 1227.30604 | 959.92796 | + """ + + def __init__( + self, + *, + targets: Optional[Iterable[ProfilerTarget]] = None, + scheduler: Union[Callable[[int], ProfilerState], tuple, None] = None, + on_trace_ready: Optional[Callable[..., Any]] = None, + record_shapes: Optional[bool] = False, + profile_memory=False, + timer_only: Optional[bool] = False, + emit_nvtx: Optional[bool] = False, + custom_device_types: Optional[list] = [] + ): + supported_targets = _get_supported_targets() + if targets: + self.targets = set(targets) + for target in targets: + if target not in supported_targets: + self.targets.remove(target) + warn( + "Profiling {} is not supported in current context.".format( + target + ) + ) + else: + self.targets = supported_targets + profileoption = ProfilerOptions() + if ProfilerTarget.CPU in self.targets: + profileoption.trace_switch |= 1 + if ProfilerTarget.GPU in self.targets: + profileoption.trace_switch |= 1 << 1 + if ProfilerTarget.MLU in self.targets: + profileoption.trace_switch |= 1 << 2 + if ProfilerTarget.CUSTOM_DEVICE in self.targets: + profileoption.trace_switch |= 1 << 3 + if not custom_device_types: + custom_device_types = paddle.device.get_all_custom_device_type() + wrap_optimizers() + self.profiler = _Profiler.create(profileoption, custom_device_types) + if callable(scheduler): + self.scheduler = scheduler + elif isinstance(scheduler, (tuple, list)): + assert len(scheduler) == 2 and scheduler[1] > scheduler[0] + start_batch, end_batch = scheduler + start_batch = max(start_batch, 0) + if start_batch >= 1: + self.scheduler = make_scheduler( + closed=max(start_batch - 1, 0), + ready=1, + record=(end_batch - start_batch), + repeat=1, + ) + else: + self.scheduler = make_scheduler( + closed=0, + ready=0, + record=(end_batch - start_batch), + repeat=1, + ) + else: + self.scheduler = _default_state_scheduler + + if on_trace_ready == None: + self.on_trace_ready = export_chrome_tracing('./profiler_log/') + else: + self.on_trace_ready = on_trace_ready + self.step_num = 0 + self.previous_state = ProfilerState.CLOSED + self.current_state = self.scheduler(self.step_num) + self.record_event = None + self.profiler_result = None + self.timer_only = timer_only + self.record_shapes = record_shapes + self.profile_memory = profile_memory + self.emit_nvtx = emit_nvtx + + def __enter__(self): + self.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.stop() + + def start(self): + r''' + Start profiler and enter the first profiler step(0). + State transformed from CLOSED to self.current_state and trigger corresponding action. + + Examples: + .. code-block:: python + :name: code-example4 + + # required: gpu + import paddle.profiler as profiler + prof = profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (1, 9), + on_trace_ready = profiler.export_chrome_tracing('./log')) + prof.start() + for iter in range(10): + #train() + prof.step() + prof.stop() + + ''' + # Timing only without profiling. + benchmark().begin() + if not self.timer_only or self.emit_nvtx: + utils._is_profiler_used = True + if self.timer_only: + return + if self.record_shapes: + enable_input_shape_recorder() + if self.profile_memory: + enable_memory_recorder() + # CLOSED -> self.current_state + if self.current_state == ProfilerState.READY: + self.profiler.prepare() + elif self.current_state == ProfilerState.RECORD: + self.profiler.prepare() + self.profiler.start() + elif self.current_state == ProfilerState.RECORD_AND_RETURN: + self.profiler.prepare() + self.profiler.start() + self.record_event = RecordEvent( + name="ProfileStep#{}".format(self.step_num), + event_type=TracerEventType.ProfileStep, + ) + self.record_event.begin() + + def stop(self): + r''' + Stop profiler and State transformed from self.current_state to CLOSED. + Trigger corresponding action and post-process profiler result using self.on_trace_ready if result exists. + + Examples: + .. code-block:: python + :name: code-example5 + + # required: gpu + import paddle.profiler as profiler + prof = profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (1, 7), + on_trace_ready = profiler.export_chrome_tracing('./log')) + prof.start() + for iter in range(10): + #train() + prof.step() + prof.stop() + ''' + benchmark().end() + if self.timer_only: + return + if self.record_shapes: + disable_input_shape_recorder() + if self.profile_memory: + disable_memory_recorder() + # self.current_state -> CLOSED + # In this situation, RECORD state is regarded as RECORD_AND_RETURN. + if self.record_event: + self.record_event.end() + self.record_event = None + if self.current_state == ProfilerState.READY: + warn( + "Inproper Profiler state transform: READY->CLOSED, profiler will start and stop without saving data" + ) + self.profiler.start() + self.profiler.stop() + if ( + self.current_state == ProfilerState.RECORD + or self.current_state == ProfilerState.RECORD_AND_RETURN + ): + self.profiler_result = self.profiler.stop() + if self.on_trace_ready: + self.on_trace_ready(self) + utils._is_profiler_used = False + + def step(self, num_samples: Optional[int] = None): + r""" + Signals the profiler that the next profiling step has started. + Get the new ProfilerState and trigger corresponding action. + + Args: + num_samples (int|None, optional): Specifies the batch size of every step of the model + that is used to compute throughput when `timer_only` is True. Default: None. + + Examples: + .. code-block:: python + :name: code-example6 + + # required: gpu + import paddle.profiler as profiler + prof = profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 7), + on_trace_ready = profiler.export_chrome_tracing('./log')) + + prof.start() + for iter in range(10): + #train() + prof.step() + prof.stop() + """ + benchmark().step(num_samples) + if self.timer_only: + return + if self.record_event: + self.record_event.end() + self.record_event = None + self.previous_state = self.current_state + self.step_num += 1 + self.current_state = self.scheduler(self.step_num) + self._trigger_action() + self.record_event = RecordEvent( + name="ProfileStep#{}".format(self.step_num), + event_type=TracerEventType.ProfileStep, + ) + self.record_event.begin() + + def step_info(self, unit=None): + r""" + Get statistics for current step. If the function is called at certain iteration + intervals, the result is the average of all steps between the previous call and + this call. Statistics are as follows: + + 1. reader_cost: the cost of loading data measured in seconds. + + 2. batch_cost: the cost of step measured in seconds. + + 3. ips(Instance Per Second): the throughput of the model measured in `samples/s` + or others depends on the `unit`. When `num_samples` of `step()` is None, it is + measured in `steps/s`. + + Args: + unit (string, optional): The unit of input data is only used When `num_samples` + of `step()` is specified as a number. For example, when it is `images`, the unit + of throughput is `images/s`. Default: None, the unit of throughput is `samples/s`. + + Returns: + string: A string representing the statistic. + + Examples: + .. code-block:: python + :name: code-example-timer2 + + import paddle.profiler as profiler + prof = profiler.Profiler(timer_only=True) + prof.start() + for iter in range(20): + #train() + prof.step() + if iter % 10 == 0: + print("Iter {}: {}".format(iter, prof.step_info())) + # The example does not call the DataLoader, so there is no "reader_cost". + # Iter 0: batch_cost: 0.00001 s ips: 86216.623 steps/s + # Iter 10: batch_cost: 0.00001 s ips: 103645.034 steps/s + prof.stop() + # Time Unit: s, IPS Unit: steps/s + # | | avg | max | min | + # | batch_cost | 0.00000 | 0.00002 | 0.00000 | + # | ips | 267846.19437 | 712030.38727 | 45134.16662 | + """ + if unit is None: + unit = 'samples' + return benchmark().step_info(unit) + + def _trigger_action(self): + if self.previous_state == ProfilerState.CLOSED: + if self.current_state == ProfilerState.READY: # CLOSED -> READY + self.profiler.prepare() + if self.current_state == ProfilerState.RECORD: # CLOSED -> RECORD + self.profiler.prepare() + self.profiler.start() + if ( + self.current_state == ProfilerState.RECORD_AND_RETURN + ): # CLOSED -> RECORD_AND_RETURN + self.profiler.prepare() + self.profiler.start() + + elif self.previous_state == ProfilerState.READY: + if self.current_state == ProfilerState.CLOSED: # READY -> CLOSED + warn( + "Improper schedule: READY->CLOSED, profiler will start and stop without saving data" + ) + self.profiler.start() + self.profiler.stop() + if self.current_state == ProfilerState.RECORD: # READY -> RECORD + self.profiler.start() + if ( + self.current_state == ProfilerState.RECORD_AND_RETURN + ): # READY -> RECORD_AND_RETURN + self.profiler.start() + + elif self.previous_state == ProfilerState.RECORD: + if self.current_state == ProfilerState.CLOSED: # RECORD -> CLOSED + warn( + "Improper schedule: RECORD->CLOSED, profiler will not saving data" + ) + self.profiler.stop() + + if self.current_state == ProfilerState.READY: # RECORD -> READY + warn( + "Improper schedule: RECORD->READY, profiler will stop and re-prepare" + ) + self.profiler.stop() + self.profiler.prepare() + if ( + self.current_state == ProfilerState.RECORD_AND_RETURN + ): # RECORD -> RECORD_AND_RETURN + pass + + else: + assert self.previous_state == ProfilerState.RECORD_AND_RETURN + if ( + self.current_state == ProfilerState.CLOSED + ): # RECORD_AND_RETURN -> CLOSED + self.profiler_result = self.profiler.stop() + if ( + self.current_state == ProfilerState.READY + ): # RECORD_AND_RETURN -> READY + self.profiler_result = self.profiler.stop() + self.profiler.prepare() + if ( + self.current_state == ProfilerState.RECORD + ): # RECORD_AND_RETURN -> RECORD + self.profiler_result = self.profiler.stop() + self.profiler.prepare() + self.profiler.start() + if ( + self.current_state == ProfilerState.RECORD_AND_RETURN + ): # RECORD_AND_RETURN -> RECORD_AND_RETURN + self.profiler_result = self.profiler.stop() + self.profiler.prepare() + self.profiler.start() + if self.on_trace_ready: + self.on_trace_ready(self) + + def export(self, path="", format="json"): + r""" + Exports the tracing data to file. + + Args: + path(str): file path of the output. + format(str, optional): output format, can be chosen from ['json', 'pb'], 'json' for chrome tracing and 'pb' for protobuf, default value is 'json'. + + + Examples: + .. code-block:: python + :name: code-example7 + + # required: gpu + import paddle.profiler as profiler + prof = profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 7)) + prof.start() + for iter in range(10): + #train() + prof.step() + prof.stop() + prof.export(path="./profiler_data.json", format="json") + """ + if self.profiler_result: + self.profiler_result.save(path, format) + + def summary( + self, + sorted_by=SortedKeys.CPUTotal, + op_detail=True, + thread_sep=False, + time_unit='ms', + views=None, + ): + r""" + Print the Summary table. Currently support overview, model, distributed, operator, memory manipulation and userdefined summary. + + Args: + sorted_by( :ref:`SortedKeys ` , optional): how to rank the op table items, default value is SortedKeys.CPUTotal. + op_detail(bool, optional): expand each operator detail information, default value is True. + thread_sep(bool, optional): print op table each thread, default value is False. + time_unit(str, optional): time unit for display, can be chosen form ['s', 'ms', 'us', 'ns'], default value is 'ms'. + views(SummaryView|list[SummaryView], optional): summary tables to print, default to None means all views to be printed. + + Examples: + .. code-block:: python + :name: code-example8 + + # required: gpu + import paddle.profiler as profiler + prof = profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 7), + on_trace_ready = profiler.export_chrome_tracing('./log')) + prof.start() + for iter in range(10): + #train() + prof.step() + prof.stop() + prof.summary(sorted_by=profiler.SortedKeys.CPUTotal, op_detail=True, thread_sep=False, time_unit='ms') + """ + if isinstance(views, SummaryView): + views = [views] + + if self.profiler_result: + statistic_data = StatisticData( + self.profiler_result.get_data(), + self.profiler_result.get_extra_info(), + ) + print( + _build_table( + statistic_data, + sorted_by=sorted_by, + op_detail=op_detail, + thread_sep=thread_sep, + time_unit=time_unit, + views=views, + ) + ) + + +def get_profiler(config_path): + try: + with open(config_path, 'r') as filehandle: + config_dict = json.load(filehandle) + except Exception as e: + print('Load config file for profiler error: {}'.format(e)) + print('Use default parameters instead.') + return Profiler() + translated_config_dict = {} + if "targets" in config_dict: + try: + translated_config_dict['targets'] = [] + for target in config_dict['targets']: + if target.lower() == "cpu": + translated_config_dict['targets'].append(ProfilerTarget.CPU) + elif target.lower() == 'gpu': + translated_config_dict['targets'].append(ProfilerTarget.GPU) + except: + print('Set targets parameter error, use default parameter instead.') + translated_config_dict['targets'] = None + if "scheduler" in config_dict: + try: + if isinstance(config_dict['scheduler'], dict): + for key, value in config_dict['scheduler'].items(): + module_path = value['module'] + use_direct = value['use_direct'] + module = importlib.import_module(module_path) + method = getattr(module, key) + if not use_direct: + translated_config_dict['scheduler'] = method( + *value['args'], **value['kwargs'] + ) + else: + translated_config_dict['scheduler'] = method + else: + translated_config_dict['scheduler'] = [ + config_dict['scheduler'][0], + config_dict['scheduler'][1], + ] + + except: + print( + 'Set scheduler parameter error, use default parameter instead.' + ) + translated_config_dict['scheduler'] = None + if "on_trace_ready" in config_dict: + try: + if isinstance(config_dict['on_trace_ready'], dict): + for key, value in config_dict['on_trace_ready'].items(): + module_path = value['module'] + use_direct = value['use_direct'] + module = importlib.import_module(module_path) + method = getattr(module, key) + if not use_direct: + translated_config_dict['on_trace_ready'] = method( + *value['args'], **value['kwargs'] + ) + else: + translated_config_dict['on_trace_ready'] = method + except: + print( + 'Set on_trace_ready parameter error, use default parameter instead.' + ) + translated_config_dict['on_trace_ready'] = None + if "timer_only" in config_dict: + if isinstance(config_dict['timer_only'], bool): + translated_config_dict['timer_only'] = config_dict['timer_only'] + else: + print( + 'Set timer_only parameter error, use default parameter instead.' + ) + + return Profiler(**translated_config_dict) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler_statistic.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler_statistic.py new file mode 100644 index 0000000000000000000000000000000000000000..d4788c58fe144e1e46cee283c1c246e416dadff1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/profiler_statistic.py @@ -0,0 +1,1693 @@ +# Copyright (c) 2022 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. +import collections +from enum import Enum +import re + +from paddle.fluid.core import TracerEventType, TracerMemEventType + +from .statistic_helper import * + +_AllTracerEventType = [ + TracerEventType.Operator, TracerEventType.Dataloader, + TracerEventType.ProfileStep, TracerEventType.CudaRuntime, + TracerEventType.Kernel, TracerEventType.Memcpy, TracerEventType.Memset, + TracerEventType.UserDefined, TracerEventType.OperatorInner, + TracerEventType.Forward, TracerEventType.Backward, + TracerEventType.Optimization, TracerEventType.Communication, + TracerEventType.PythonOp, TracerEventType.PythonUserDefined +] + +_CommunicationOpName = ['allreduce', 'broadcast', 'rpc'] + + +class SortedKeys(Enum): + r""" + SortedKeys is used to specify how to sort items when printing :ref:`summary ` table. + + The meaning of each SortedKeys is as following + + - **SortedKeys.CPUTotal** : Sorted by CPU total time. + + - **SortedKeys.CPUAvg** : Sorted by CPU average time. + + - **SortedKeys.CPUMax** : Sorted by CPU max time. + + - **SortedKeys.CPUMin** : Sorted by CPU min time. + + - **SortedKeys.GPUTotal** : Sorted by GPU total time. + + - **SortedKeys.GPUAvg** : Sorted by GPU average time. + + - **SortedKeys.GPUMax** : Sorted by GPU max time. + + - **SortedKeys.GPUMin** : Sorted by GPU min time. + """ + CPUTotal = 0 + CPUAvg = 1 + CPUMax = 2 + CPUMin = 3 + GPUTotal = 4 + GPUAvg = 5 + GPUMax = 6 + GPUMin = 7 + + +class HostStatisticNode: + r''' + Wrap original node for calculating statistic metrics. + ''' + + def __init__(self, hostnode): + self.hostnode = hostnode + self.children_node = [] + self.runtime_node = [] + self.cpu_time = 0 + self.self_cpu_time = 0 + self.gpu_time = 0 # kernel time + self.self_gpu_time = 0 + self.general_gpu_time = 0 # besides kernel, include time of gpu events like memcpy and memset + self.self_general_gpu_time = 0 + + def cal_statistic(self): + for child in self.children_node: + child.cal_statistic() + for rt in self.runtime_node: + rt.cal_statistic() + self.cpu_time = self.hostnode.end_ns - self.hostnode.start_ns + self.self_cpu_time = self.cpu_time + for child in self.children_node: + self.gpu_time += child.gpu_time + self.general_gpu_time += child.general_gpu_time + self.self_cpu_time -= (child.end_ns - child.start_ns) + for rt in self.runtime_node: + self.self_cpu_time -= (rt.end_ns - rt.start_ns) + self.gpu_time += rt.gpu_time + self.self_gpu_time += rt.gpu_time + self.general_gpu_time += rt.general_gpu_time + self.self_general_gpu_time += rt.general_gpu_time + for device in self.hostnode.device_node: + if device.type == TracerEventType.Kernel: + self.gpu_time += (device.end_ns - device.start_ns) + self.self_gpu_time += (device.end_ns - device.start_ns) + self.general_gpu_time += (device.end_ns - device.start_ns) + self.self_general_gpu_time += (device.end_ns - device.start_ns) + + @property + def end_ns(self): + return self.hostnode.end_ns + + @property + def start_ns(self): + return self.hostnode.start_ns + + def __getattr__(self, name): + return getattr(self.hostnode, name) + + +def traverse_tree(nodetrees): + results = collections.defaultdict(list) + for thread_id, rootnode in nodetrees.items(): + stack = [] + stack.append(rootnode) + threadlist = results[thread_id] + while stack: + current_node = stack.pop() + threadlist.append(current_node) + for childnode in current_node.children_node: + stack.append(childnode) + return results + + +def get_device_nodes(hostnode): + ''' + Get all device nodes called in the time range of hostnode. + ''' + stack = [] + device_nodes = [] + stack.append(hostnode) + while stack: + current_node = stack.pop() + for childnode in current_node.children_node: + stack.append(childnode) + for runtimenode in current_node.runtime_node: + for devicenode in runtimenode.device_node: + device_nodes.append(devicenode) + return device_nodes + + +def wrap_tree(nodetrees): + ''' + Using HostStatisticNode to wrap original profiler result tree, and calculate node statistic metrics. + ''' + node_statistic_tree = {} + results = collections.defaultdict(list) + newresults = collections.defaultdict(list) + for thread_id, rootnode in nodetrees.items(): + stack = [] + stack.append(rootnode) + root_statistic_node = HostStatisticNode(rootnode) + newstack = [] + newstack.append(root_statistic_node) + node_statistic_tree[thread_id] = root_statistic_node + threadlist = results[thread_id] + newthreadlist = newresults[thread_id] + while stack: + current_node = stack.pop() + threadlist.append(current_node) + current_statistic_node = newstack.pop() + newthreadlist.append(current_statistic_node) + for childnode in current_node.children_node: + stack.append(childnode) + child_statistic_node = HostStatisticNode(childnode) + current_statistic_node.children_node.append( + child_statistic_node) + newstack.append(child_statistic_node) + for runtimenode in current_node.runtime_node: + runtime_statistic_node = HostStatisticNode(runtimenode) + current_statistic_node.runtime_node.append( + runtime_statistic_node) + # recursive calculate node statistic values + for thread_id, root_statistic_node in node_statistic_tree.items(): + root_statistic_node.cal_statistic() + + return node_statistic_tree, newresults + + +class TimeRangeSummary: + r""" + Analyse time ranges for each TracerEventType, and summarize the time. + """ + + def __init__(self): + self.CPUTimeRange = collections.defaultdict(list) + self.GPUTimeRange = collections.defaultdict( + lambda: collections.defaultdict( + list)) # GPU events should be divided into different devices + self.CPUTimeRangeSum = collections.defaultdict(int) + self.GPUTimeRangeSum = collections.defaultdict( + lambda: collections.defaultdict(int)) + self.call_times = collections.defaultdict(int) + + def parse(self, nodetrees): + r""" + Analysis node trees in profiler result, and get time range for different tracer event type. + """ + thread2hostnodes = traverse_tree(nodetrees) + for threadid, hostnodes in thread2hostnodes.items(): + CPUTimeRange = collections.defaultdict(list) + GPUTimeRange = collections.defaultdict( + lambda: collections.defaultdict(lambda: collections.defaultdict( + list))) # device_id/type/stream_id + for hostnode in hostnodes[1:]: #skip root node + CPUTimeRange[hostnode.type].append( + (hostnode.start_ns, hostnode.end_ns)) + self.call_times[hostnode.type] += 1 + for runtimenode in hostnode.runtime_node: + CPUTimeRange[runtimenode.type].append( + (runtimenode.start_ns, runtimenode.end_ns)) + self.call_times[runtimenode.type] += 1 + for devicenode in runtimenode.device_node: + GPUTimeRange[devicenode.device_id][devicenode.type][ + devicenode.stream_id].append( + (devicenode.start_ns, devicenode.end_ns)) + self.call_times[devicenode.type] += 1 + + for event_type, time_ranges in CPUTimeRange.items(): + time_ranges = merge_self_ranges(time_ranges, is_sorted=False) + self.CPUTimeRange[event_type] = merge_ranges( + self.CPUTimeRange[event_type], time_ranges, is_sorted=True) + for device_id, device_time_ranges in GPUTimeRange.items(): + for event_type, event_time_ranges in device_time_ranges.items(): + for stream_id, time_ranges in event_time_ranges.items(): + time_ranges = merge_self_ranges(time_ranges, + is_sorted=False) + self.GPUTimeRange[device_id][event_type] = merge_ranges( + self.GPUTimeRange[device_id][event_type], + time_ranges, + is_sorted=True) + + for event_type, time_ranges in self.CPUTimeRange.items(): + self.CPUTimeRangeSum[event_type] = sum_ranges(time_ranges) + for device_id, device_time_ranges in self.GPUTimeRange.items(): + for event_type, time_ranges in device_time_ranges.items(): + self.GPUTimeRangeSum[device_id][event_type] = sum_ranges( + time_ranges) + + def get_gpu_devices(self): + return self.GPUTimeRange.keys() + + def get_gpu_range_sum(self, device_id, event_type): + return self.GPUTimeRangeSum[device_id][event_type] + + def get_cpu_range_sum(self, event_type): + return self.CPUTimeRangeSum[event_type] + + +class DistributedSummary: + r""" + Analysis communication and computation time range, and their overlap. + The computation time is all kernel except kernels for communication like nccl. + """ + + def __init__(self): + self.cpu_communication_range = [] + self.gpu_communication_range = [] + self.communication_range = [] + self.computation_range = [] + self.overlap_range = [] + self.cpu_calls = 0 + self.gpu_calls = 0 + + def parse(self, nodetrees): + ''' + Collect all communication and computation time ranges. + ''' + thread2hostnodes = traverse_tree(nodetrees) + for threadid, hostnodes in thread2hostnodes.items(): + for hostnode in hostnodes[1:]: #skip root node + # case 1: TracerEventType is Communication + if hostnode.type == TracerEventType.Communication: + self.cpu_communication_range.append( + (hostnode.start_ns, hostnode.end_ns)) + device_nodes = get_device_nodes(hostnode) + for device_node in device_nodes: + if device_node.type == TracerEventType.Kernel: + self.gpu_communication_range.append( + (device_node.start_ns, device_node.end_ns)) + + #case 2: TracerEventType is Operator but is communication op + elif hostnode.type == TracerEventType.Operator and any([ + name in hostnode.name.lower() + for name in _CommunicationOpName + ]): + self.cpu_communication_range.append( + (hostnode.start_ns, hostnode.end_ns)) + device_nodes = get_device_nodes(hostnode) + for device_node in device_nodes: + if device_node.type == TracerEventType.Kernel: + self.gpu_communication_range.append( + (device_node.start_ns, device_node.end_ns)) + + #case 3: Others, filter kernels named with nccl + else: + for runtimenode in hostnode.runtime_node: + for devicenode in runtimenode.device_node: + if devicenode.type == TracerEventType.Kernel: + if 'nccl' in devicenode.name.lower(): + self.gpu_communication_range.append( + (devicenode.start_ns, + devicenode.end_ns)) + else: + self.computation_range.append( + (devicenode.start_ns, + devicenode.end_ns)) + self.cpu_calls = len(set(self.cpu_communication_range)) + self.gpu_calls = len(set(self.gpu_communication_range)) + self.cpu_communication_range = merge_self_ranges( + self.cpu_communication_range, is_sorted=False) + self.gpu_communication_range = merge_self_ranges( + self.gpu_communication_range, is_sorted=False) + self.communication_range = merge_ranges(self.cpu_communication_range, + self.gpu_communication_range, + is_sorted=True) + self.computation_range = merge_self_ranges(self.computation_range, + is_sorted=False) + self.overlap_range = intersection_ranges(self.communication_range, + self.computation_range, + is_sorted=True) + + +class EventSummary: + r""" + Analyse operator event in profiling data, correlate with its device event. + """ + + class DeviceItem: + + def __init__(self, name): + self.name = name + self.call = 0 + self.gpu_time = 0 + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_item(self, node): + self.call += 1 + self.add_gpu_time(node.end_ns - node.start_ns) + + class OperatorItem: + + def __init__(self, name): + self.name = name + self.call = 0 + self.cpu_time = 0 + self.gpu_time = 0 + self.max_cpu_time = 0 + self.min_cpu_time = float('inf') + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.devices = {} + self.operator_inners = {} + self.general_gpu_time = 0 + self.min_general_gpu_time = float('inf') + self.max_general_gpu_time = 0 + + @property + def avg_cpu_time(self): + return self.cpu_time / self.call + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + @property + def avg_general_gpu_time(self): + return self.general_gpu_time / self.call + + def add_cpu_time(self, time): + if time > self.max_cpu_time: + self.max_cpu_time = time + if time < self.min_cpu_time: + self.min_cpu_time = time + self.cpu_time += time + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_general_gpu_time(self, time): + if time > self.max_general_gpu_time: + self.max_general_gpu_time = time + if time < self.min_general_gpu_time: + self.min_general_gpu_time = time + self.general_gpu_time += time + + def add_call(self): + self.call += 1 + + def add_item(self, node): + self.add_call() + self.add_cpu_time(node.cpu_time) + self.add_gpu_time(node.gpu_time) + self.add_general_gpu_time(node.general_gpu_time) + for child in node.children_node: + if child.type != TracerEventType.Operator: + if child.name not in self.operator_inners: + self.operator_inners[ + child.name] = EventSummary.OperatorItem(child.name) + self.operator_inners[child.name].add_item(child) + + for runtimenode in node.runtime_node: + for devicenode in runtimenode.device_node: + name = devicenode.name + if name not in self.devices: + self.devices[name] = EventSummary.DeviceItem(name) + self.devices[name].add_item(devicenode) + + class GeneralItem: + + def __init__(self, name): + self.name = name + self.call = 0 + self.cpu_time = 0 + self.max_cpu_time = 0 + self.min_cpu_time = float('inf') + self.gpu_time = 0 + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.general_gpu_time = 0 + self.min_general_gpu_time = float('inf') + self.max_general_gpu_time = 0 + + @property + def avg_cpu_time(self): + return self.cpu_time / self.call + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + @property + def avg_general_gpu_time(self): + return self.general_gpu_time / self.call + + def add_cpu_time(self, time): + if time > self.max_cpu_time: + self.max_cpu_time = time + if time < self.min_cpu_time: + self.min_cpu_time = time + self.cpu_time += time + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_general_gpu_time(self, time): + if time > self.max_general_gpu_time: + self.max_general_gpu_time = time + if time < self.min_general_gpu_time: + self.min_general_gpu_time = time + self.general_gpu_time += time + + def add_call(self): + self.call += 1 + + def add_item(self, node): + self.add_call() + self.add_cpu_time(node.cpu_time) + self.add_gpu_time(node.gpu_time) + self.add_general_gpu_time(node.general_gpu_time) + + def __init__(self): + self.items = {} # for operator summary + self.thread_items = collections.defaultdict( + dict) # for operator summary + self.userdefined_items = {} # for userdefined summary + self.userdefined_thread_items = collections.defaultdict( + dict) # for userdefined summary + self.model_perspective_items = {} # for model summary + self.memory_manipulation_items = {} # for memory manipulation summary + self.kernel_items = {} # for kernel summary + + def parse(self, nodetrees): + r""" + Analysis operator event in the nodetress. + """ + node_statistic_trees, thread2host_statistic_nodes = wrap_tree(nodetrees) + for threadid, host_statistic_nodes in thread2host_statistic_nodes.items( + ): + for host_statistic_node in host_statistic_nodes[ + 1:]: #skip root node + if host_statistic_node.type == TracerEventType.Operator: + self.add_operator_item(host_statistic_node) + if host_statistic_node.type == TracerEventType.UserDefined\ + or host_statistic_node.type == TracerEventType.PythonUserDefined: + if 'memcpy' in host_statistic_node.name.lower() or 'memorycopy' in host_statistic_node.name.lower()\ + or 'memset' in host_statistic_node.name.lower(): + self.add_memory_manipulation_item(host_statistic_node) + else: + if host_statistic_node.type == TracerEventType.PythonUserDefined: + self.add_userdefined_item(host_statistic_node) + self.add_kernel_item(host_statistic_nodes[0]) + + for threadid, root_statistic_node in node_statistic_trees.items(): + deque = collections.deque() + deque.append(root_statistic_node) + while deque: + current_node = deque.popleft() + for child in current_node.children_node: + if child.type == TracerEventType.Forward or child.type == TracerEventType.Dataloader\ + or child.type == TracerEventType.Backward or child.type == TracerEventType.Optimization: + self.add_model_perspective_item( + child) #find first model perspective node + else: + if child.type == TracerEventType.ProfileStep: + self.add_model_perspective_item(child) + deque.append(child) + + def add_operator_item(self, operator_node): + if operator_node.name not in self.items: + self.items[operator_node.name] = EventSummary.OperatorItem( + operator_node.name) + + self.items[operator_node.name].add_item(operator_node) + + if operator_node.name not in self.thread_items[operator_node.thread_id]: + self.thread_items[operator_node.thread_id][ + operator_node.name] = EventSummary.OperatorItem( + operator_node.name) + self.thread_items[operator_node.thread_id][operator_node.name].add_item( + operator_node) + + def add_userdefined_item(self, userdefined_node): + if userdefined_node.name not in self.userdefined_items: + self.userdefined_items[ + userdefined_node.name] = EventSummary.GeneralItem( + userdefined_node.name) + + self.userdefined_items[userdefined_node.name].add_item(userdefined_node) + + if userdefined_node.name not in self.userdefined_thread_items[ + userdefined_node.thread_id]: + self.userdefined_thread_items[userdefined_node.thread_id][ + userdefined_node.name] = EventSummary.GeneralItem( + userdefined_node.name) + self.userdefined_thread_items[userdefined_node.thread_id][ + userdefined_node.name].add_item(userdefined_node) + + def add_memory_manipulation_item(self, memory_manipulation_node): + if memory_manipulation_node.name not in self.memory_manipulation_items: + self.memory_manipulation_items[ + memory_manipulation_node.name] = EventSummary.GeneralItem( + memory_manipulation_node.name) + self.memory_manipulation_items[memory_manipulation_node.name].add_item( + memory_manipulation_node) + + def add_model_perspective_item(self, model_perspective_node): + if model_perspective_node.type == TracerEventType.Forward: + name = 'Forward' + elif model_perspective_node.type == TracerEventType.Backward: + name = 'Backward' + elif model_perspective_node.type == TracerEventType.Optimization: + name = 'Optimization' + elif model_perspective_node.type == TracerEventType.Dataloader: + name = 'Dataloader' + elif model_perspective_node.type == TracerEventType.ProfileStep: + name = 'ProfileStep' + else: + return + if name not in self.model_perspective_items: + self.model_perspective_items[name] = EventSummary.GeneralItem(name) + self.model_perspective_items[name].add_item(model_perspective_node) + + def add_kernel_item(self, root_node): + device_nodes = get_device_nodes(root_node) + for device_node in device_nodes: + if device_node.type == TracerEventType.Kernel: + name = device_node.name + if name not in self.kernel_items: + self.kernel_items[name] = EventSummary.DeviceItem(name) + self.kernel_items[name].add_item(device_node) + + +class MemorySummary: + r""" + Analyse memory events in profiling data. + """ + + class MemoryItem: + + def __init__(self, event_name, place, memory_type='Allocated'): + self.event_name = event_name + self.place = place + self.allocation_count = 0 + self.free_count = 0 + self.allocation_size = 0 + self.free_size = 0 + self.increase_size = 0 + self.memory_type = memory_type + + def add_memory_record(self, size, allocation_type): + if allocation_type == TracerMemEventType.Allocate or allocation_type == TracerMemEventType.ReservedAllocate: + self.allocation_count += 1 + self.allocation_size += size + + elif allocation_type == TracerMemEventType.Free or allocation_type == TracerMemEventType.ReservedFree: + self.free_count += 1 + self.free_size -= size # size is sign(-) when free. + + else: + print("No corresponding type.") + self.increase_size = self.allocation_size - self.free_size + + def __init__(self): + self.allocated_items = collections.defaultdict( + dict) # for memory summary, device type: event + self.reserved_items = collections.defaultdict( + dict) # for memory summary, device type: event + self.peak_allocation_values = collections.defaultdict(int) + self.peak_reserved_values = collections.defaultdict(int) + + def _analyse_node_memory(self, event_name, node): + for memnode in node.mem_node: # self mem node + if memnode.type == TracerMemEventType.Allocate or memnode.type == TracerMemEventType.Free: + if event_name not in self.allocated_items[memnode.place]: + self.allocated_items[ + memnode.place][event_name] = MemorySummary.MemoryItem( + event_name, memnode.place, 'Allocated') + self.allocated_items[ + memnode.place][event_name].add_memory_record( + memnode.increase_bytes, memnode.type) + elif memnode.type == TracerMemEventType.ReservedAllocate or memnode.type == TracerMemEventType.ReservedFree: + if event_name not in self.reserved_items[memnode.place]: + self.reserved_items[ + memnode.place][event_name] = MemorySummary.MemoryItem( + event_name, memnode.place, 'Reserved') + self.reserved_items[ + memnode.place][event_name].add_memory_record( + memnode.increase_bytes, memnode.type) + self.peak_allocation_values[memnode.place] = max( + self.peak_allocation_values[memnode.place], + memnode.peak_allocated) + self.peak_reserved_values[memnode.place] = max( + self.peak_reserved_values[memnode.place], memnode.peak_reserved) + + def parse(self, nodetrees): + r""" + Analyse memory event in the nodetress. + """ + thread2hostnodes = traverse_tree(nodetrees) + for threadid, host_nodes in thread2hostnodes.items(): + for host_node in host_nodes[1:]: #skip root node + if host_node.type == TracerEventType.OperatorInner: + continue + if host_node.type == TracerEventType.Operator: + for child in host_node.children_node: + self._analyse_node_memory(host_node.name, child) + self._analyse_node_memory(host_node.name, host_node) + + +class StatisticData: + r""" + Hold all analysed results. + """ + + def __init__(self, node_trees, extra_info): + self.node_trees = node_trees + self.extra_info = extra_info + self.time_range_summary = TimeRangeSummary() + self.event_summary = EventSummary() + self.distributed_summary = DistributedSummary() + self.memory_summary = MemorySummary() + self.time_range_summary.parse(node_trees) + self.event_summary.parse(node_trees) + self.distributed_summary.parse(node_trees) + self.memory_summary.parse(node_trees) + + +def _build_table(statistic_data, + sorted_by=SortedKeys.CPUTotal, + op_detail=True, + thread_sep=False, + time_unit='ms', + row_limit=100, + max_src_column_width=75, + views=None): + + from .profiler import SummaryView + """Prints a summary of events.""" + # format table row + SPACING_SIZE = 2 + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + + def add_column(padding, text_dir='<'): + row_format_list[0] += '{: ' + text_dir + str(padding) + '}' + ( + ' ' * SPACING_SIZE) + header_sep_list[0] += '-' * padding + (' ' * SPACING_SIZE) + line_length_list[0] += padding + SPACING_SIZE + + def add_title(padding, text): + left_length = padding - len(text) + half = left_length // 2 + return '-' * half + text + '-' * (left_length - half) + + result = [] + + def append(s): + result.append(s) + result.append('\n') + + def format_time(time, unit='ms', indent=0): + r""" + Transform time in ns to time in unit. + """ + if time == float('inf'): + return '-' + else: + result = float(time) + if unit == 's': + result /= 1e9 + elif unit == 'ms': + result /= 1e6 + elif unit == 'us': + result /= 1e3 + return '{}{:.2f}'.format(' ' * indent, result) + + def format_ratio(ratio, indent=0): + r""" + Transform ratio within [0, 1] to percentage presentation. + """ + return '{}{:.2f}'.format(' ' * indent, ratio * 100) + + total_time = statistic_data.time_range_summary.get_cpu_range_sum( + TracerEventType.ProfileStep) + + if views is None or SummaryView.DeviceView in views: + + ###### Print Device Summary ###### + headers = ['Device', 'Utilization (%)'] + name_column_width = 30 + DEFAULT_COLUMN_WIDTH = 20 + add_column(name_column_width) + for _ in headers[1:]: + add_column(DEFAULT_COLUMN_WIDTH) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + + append(add_title(line_length, "Device Summary")) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + row_values = [ + 'CPU(Process)', + format_ratio( + float(statistic_data.extra_info['Process Cpu Utilization'])) + ] + append(row_format.format(*row_values)) + row_values = [ + 'CPU(System)', + format_ratio( + float(statistic_data.extra_info['System Cpu Utilization'])) + ] + append(row_format.format(*row_values)) + for gpu_name in statistic_data.time_range_summary.get_gpu_devices(): + gpu_time = float( + statistic_data.time_range_summary.get_gpu_range_sum( + gpu_name, TracerEventType.Kernel)) + utilization = gpu_time / total_time + row_values = ['GPU{}'.format(gpu_name), format_ratio(utilization)] + append(row_format.format(*row_values)) + + append(header_sep) + append( + "Note:\nCPU(Process) Utilization = Current process CPU time over all cpu cores / elapsed time, so max utilization can be reached 100% * number of cpu cores.\n" + "CPU(System) Utilization = All processes CPU time over all cpu cores(busy time) / (busy time + idle time).\n" + "GPU Utilization = Current process GPU time / elapsed time.") + append('-' * line_length) + append('') + append('') + + if total_time == 0: + return ''.join(result) + + if views is None or SummaryView.OverView in views: + ###### Print Overview Summary ###### + headers = ['Event Type', 'Calls', 'CPU Time', 'Ratio (%)'] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + + DEFAULT_COLUMN_WIDTH = 25 + for _ in headers: + add_column(DEFAULT_COLUMN_WIDTH) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Overview Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + cpu_type_time = collections.defaultdict(int) + gpu_type_time = collections.defaultdict(int) + cpu_call_times = collections.defaultdict(int) + gpu_call_times = collections.defaultdict(int) + cpu_call_times.update(statistic_data.time_range_summary.call_times) + gpu_call_times.update(statistic_data.time_range_summary.call_times) + + for event_type, value in statistic_data.time_range_summary.CPUTimeRangeSum.items( + ): + if event_type != TracerEventType.Communication: + cpu_type_time[event_type] = value + if statistic_data.distributed_summary.cpu_communication_range: + cpu_type_time[TracerEventType.Communication] = sum_ranges( + statistic_data.distributed_summary.cpu_communication_range) + cpu_call_times[ + TracerEventType. + Communication] = statistic_data.distributed_summary.cpu_calls + + for event_type in [ + TracerEventType.Dataloader, TracerEventType.Forward, + TracerEventType.Backward, TracerEventType.Optimization + ]: + event_type_name = str(event_type).split('.')[1] + if event_type in cpu_call_times and event_type_name in statistic_data.event_summary.model_perspective_items: + cpu_call_times[ + event_type] = statistic_data.event_summary.model_perspective_items[ + event_type_name].call + cpu_type_time[ + event_type] = statistic_data.event_summary.model_perspective_items[ + event_type_name].cpu_time + + gpu_time_range = collections.defaultdict(list) + for device_id, device_time_ranges in statistic_data.time_range_summary.GPUTimeRange.items( + ): + for event_type, time_range in device_time_ranges.items(): + gpu_time_range[event_type] = merge_ranges( + gpu_time_range[event_type], time_range, is_sorted=True) + for event_type, time_range in gpu_time_range.items(): + gpu_type_time[event_type] = sum_ranges(time_range) + if statistic_data.distributed_summary.gpu_communication_range: + gpu_type_time[TracerEventType.Communication] = sum_ranges( + statistic_data.distributed_summary.gpu_communication_range) + gpu_call_times[ + TracerEventType. + Communication] = statistic_data.distributed_summary.gpu_calls + + sorted_items = sorted(cpu_type_time.items(), + key=lambda x: x[1], + reverse=True) + event_type, time = sorted_items[0] + row_values = [ + '{}'.format(str(event_type).split('.')[1]), + cpu_call_times[event_type], + format_time(time, unit=time_unit), + format_ratio(float(time) / total_time) + ] + append(row_format.format(*row_values)) + for event_type, time in sorted_items[1:]: + row_values = [ + ' {}'.format(str(event_type).split('.')[1]), + cpu_call_times[event_type], + format_time(time, unit=time_unit), + format_ratio(float(time) / total_time) + ] + append(row_format.format(*row_values)) + append(header_sep) + headers = ['', 'Calls', 'GPU Time', 'Ratio (%)'] + append(row_format.format(*headers)) + append(header_sep) + for event_type, time in gpu_type_time.items(): + row_values = [ + ' {}'.format(str(event_type).split('.')[1]), + gpu_call_times[event_type], + format_time(time, unit=time_unit), + format_ratio(float(time) / total_time) + ] + append(row_format.format(*row_values)) + + append(header_sep) + append( + "Note:\nIn this table, We sum up all collected events in terms of event type.\n" + "The time of events collected on host are presented as CPU Time, and as GPU Time if on device.\n" + "Events with different types may overlap or inclusion, e.g. Operator includes OperatorInner, so the sum of ratios is not 100%.\n" + "The time of events in the same type with overlap will not calculate twice, and all time is summed after merged.\n" + "Example:\n" + "Thread 1:\n" + " Operator: |___________| |__________|\n" + "Thread 2:\n" + " Operator: |____________| |___|\n" + "After merged:\n" + " Result: |______________| |__________|\n") + append('-' * line_length) + append('') + append('') + + if views is None or SummaryView.ModelView in views: + + ###### Print Model Summary Report ###### + model_perspective_items = statistic_data.event_summary.model_perspective_items + if len(model_perspective_items) > 1: + all_row_values = [] + accmulation_time = 0 + gpu_accmulation_time = 0 + gpu_total_time = statistic_data.event_summary.model_perspective_items[ + 'ProfileStep'].gpu_time + for name in [ + 'ProfileStep', 'Dataloader', 'Forward', 'Backward', + 'Optimization' + ]: + if name in model_perspective_items: + item = model_perspective_items[name] + if gpu_total_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(item.gpu_time) / gpu_total_time + name = '{}'.format( + name) if 'ProfileStep' in name else ' {}'.format(name) + row_values = [ + '{}'.format(name), item.call, + '{} / {} / {} / {} / {}'.format( + format_time(item.cpu_time, unit=time_unit), + format_time(item.avg_cpu_time, unit=time_unit), + format_time(item.max_cpu_time, unit=time_unit), + format_time(item.min_cpu_time, unit=time_unit), + format_ratio(float(item.cpu_time) / total_time)), + '{} / {} / {} / {} / {}'.format( + format_time(item.gpu_time, unit=time_unit), + format_time(item.avg_gpu_time, unit=time_unit), + format_time(item.max_gpu_time, unit=time_unit), + format_time(item.min_gpu_time, unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + if 'ProfileStep' not in name: + accmulation_time += item.cpu_time + gpu_accmulation_time += item.gpu_time + + other_time = total_time - accmulation_time + other_gpu_time = gpu_total_time - gpu_accmulation_time + if gpu_total_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(other_gpu_time) / gpu_total_time + row_values = [ + ' Others', '-', '{} / - / - / - / {}'.format( + format_time(other_time, unit=time_unit), + format_ratio(float(other_time) / total_time)), + '{} / - / - / - / {}'.format( + format_time(other_gpu_time, unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + # Calculate the column width + calltime_width = 6 + cpu_data_description_width = 40 + gpu_data_description_width = 40 + for row_values in all_row_values: + if isinstance(row_values[1], + int) and len(str(row_values[1])) > calltime_width: + calltime_width = len(str(row_values[1])) + if len(row_values[2]) > cpu_data_description_width: + cpu_data_description_width = len(row_values[2]) + if len(row_values[3]) > gpu_data_description_width: + gpu_data_description_width = len(row_values[3]) + headers = [ + 'Name', 'Calls', 'CPU Total / Avg / Max / Min / Ratio(%)', + 'GPU Total / Avg / Max / Min / Ratio(%)' + ] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + name_column_width = 15 + add_column(name_column_width) + add_column(calltime_width) + add_column(cpu_data_description_width) + add_column(gpu_data_description_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Model Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for row_values in all_row_values: + append(row_format.format(*row_values)) + append(header_sep) + append( + "Note:\nIn this table, GPU time is the sum of all device(GPU) events called in the phase.\n" + "Unlike overview summary, if two device(GPU) events execute on different streams with overlap time, we sum them directly here.\n" + ) + append('-' * line_length) + append('') + append('') + + if views is None or SummaryView.DistributedView in views: + + ###### Print Distribution Summary Report ###### + if statistic_data.distributed_summary.communication_range: + headers = [ + 'Name', + 'Total Time', + 'Ratio (%)', + ] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + + DEFAULT_COLUMN_WIDTH = 25 + for _ in headers: + add_column(DEFAULT_COLUMN_WIDTH) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Distribution Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + communication_time = sum_ranges( + statistic_data.distributed_summary.communication_range) + computation_time = sum_ranges( + statistic_data.distributed_summary.computation_range) + overlap_time = sum_ranges( + statistic_data.distributed_summary.overlap_range) + row_values = [ + 'ProfileStep', + format_time(total_time, unit=time_unit), + format_ratio(float(total_time) / total_time) + ] + append(row_format.format(*row_values)) + row_values = [ + ' Communication', + format_time(communication_time, unit=time_unit), + format_ratio(float(communication_time) / total_time) + ] + append(row_format.format(*row_values)) + + row_values = [ + ' Computation', + format_time(computation_time, unit=time_unit), + format_ratio(float(computation_time) / total_time) + ] + append(row_format.format(*row_values)) + + row_values = [ + ' Overlap', + format_time(overlap_time, unit=time_unit), + format_ratio(float(overlap_time) / total_time) + ] + append(row_format.format(*row_values)) + append(header_sep) + append( + "Note:\nCommunication time: Communication Event time, Communication Op time and its kernel time on gpu.\n" + "Computation time: Kernel time, except kernels belong to communication(nccl kernels).\n" + "Overlap time: Communication time intersects with computation time.\n" + "Example:\n" + "Communication:\n" + " CPU: |_________________|\n" + " GPU: |______________|\n" + " Total: |_________________| |______________|\n" + "Computation time(Kernel):\n" + " GPU: |________________|\n" + "Overlap time: |___________|\n") + append('-' * line_length) + append('') + append('') + + if views is None or SummaryView.OperatorView in views: + + ###### Print Operator Summary Report ###### + if statistic_data.event_summary.items: + all_row_values = [] + name_column_width = 52 + if thread_sep == True: + thread_items = statistic_data.event_summary.thread_items + else: + thread_items = { + 'All threads merged': statistic_data.event_summary.items + } + for thread_id, items in thread_items.items(): + all_row_values.append("Thread: {}".format(thread_id)) + if sorted_by == SortedKeys.CPUTotal: + sorted_items = sorted(items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUAvg: + sorted_items = sorted(items.items(), + key=lambda x: x[1].avg_cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUMax: + sorted_items = sorted(items.items(), + key=lambda x: x[1].max_cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUMin: + sorted_items = sorted(items.items(), + key=lambda x: x[1].min_cpu_time) + elif sorted_by == SortedKeys.GPUTotal: + sorted_items = sorted(items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUAvg: + sorted_items = sorted( + items.items(), + key=lambda x: x[1].avg_general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMax: + sorted_items = sorted( + items.items(), + key=lambda x: x[1].max_general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMin: + sorted_items = sorted( + items.items(), key=lambda x: x[1].min_general_gpu_time) + total_op_cpu_time = 0 + total_op_gpu_time = 0 + + for name, item in sorted_items: + total_op_cpu_time += item.cpu_time + total_op_gpu_time += item.general_gpu_time + + for name, item in sorted_items: + if total_op_cpu_time == 0: + cpu_ratio = 0 + else: + cpu_ratio = float(item.cpu_time) / total_op_cpu_time + if total_op_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float( + item.general_gpu_time) / total_op_gpu_time + row_values = [ + name, item.call, '{} / {} / {} / {} / {}'.format( + format_time(item.cpu_time, unit=time_unit), + format_time(item.avg_cpu_time, unit=time_unit), + format_time(item.max_cpu_time, unit=time_unit), + format_time(item.min_cpu_time, unit=time_unit), + format_ratio(cpu_ratio)), + '{} / {} / {} / {} / {}'.format( + format_time(item.general_gpu_time, unit=time_unit), + format_time(item.avg_general_gpu_time, + unit=time_unit), + format_time(item.max_general_gpu_time, + unit=time_unit), + format_time(item.min_general_gpu_time, + unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + if op_detail: + for innerop_name, innerop_node in item.operator_inners.items( + ): + if item.cpu_time == 0: + cpu_ratio = 0 + else: + cpu_ratio = float( + innerop_node.cpu_time) / item.cpu_time + if item.general_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(innerop_node.general_gpu_time + ) / item.general_gpu_time + if len(innerop_name) + 2 > name_column_width: + innerop_name = innerop_name[:name_column_width - + 5] + innerop_name += "..." + row_values = [ + ' {}'.format(innerop_name), innerop_node.call, + '{} / {} / {} / {} / {}'.format( + format_time(innerop_node.cpu_time, + unit=time_unit), + format_time(innerop_node.avg_cpu_time, + unit=time_unit), + format_time(innerop_node.max_cpu_time, + unit=time_unit), + format_time(innerop_node.min_cpu_time, + unit=time_unit), + format_ratio(cpu_ratio)), + '{} / {} / {} / {} / {}'.format( + format_time(innerop_node.general_gpu_time, + unit=time_unit), + format_time( + innerop_node.avg_general_gpu_time, + unit=time_unit), + format_time( + innerop_node.max_general_gpu_time, + unit=time_unit), + format_time( + innerop_node.min_general_gpu_time, + unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + for device_node_name, device_node in innerop_node.devices.items( + ): + if innerop_node.general_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float( + device_node.gpu_time + ) / innerop_node.general_gpu_time + if len(device_node_name + ) + 4 > name_column_width: + device_node_name = device_node_name[: + name_column_width + - 7] + device_node_name += "..." + row_values = [ + ' {}'.format(device_node_name), + device_node.call, '- / - / - / - / -', + '{} / {} / {} / {} / {}'.format( + format_time(device_node.gpu_time, + unit=time_unit), + format_time(device_node.avg_gpu_time, + unit=time_unit), + format_time(device_node.max_gpu_time, + unit=time_unit), + format_time(device_node.min_gpu_time, + unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + for device_node_name, device_node in item.devices.items( + ): + if item.general_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(device_node.gpu_time + ) / item.general_gpu_time + if len(device_node_name) + 2 > name_column_width: + device_node_name = device_node_name[: + name_column_width + - 5] + device_node_name += "..." + row_values = [ + ' {}'.format(device_node_name), + device_node.call, '- / - / - / - / -', + '{} / {} / {} / {} / {}'.format( + format_time(device_node.gpu_time, + unit=time_unit), + format_time(device_node.avg_gpu_time, + unit=time_unit), + format_time(device_node.max_gpu_time, + unit=time_unit), + format_time(device_node.min_gpu_time, + unit=time_unit), + format_ratio(gpu_ratio)) + ] + all_row_values.append(row_values) + # Calculate the column width + calltime_width = 6 + cpu_data_description_width = 40 + gpu_data_description_width = 40 + for row_values in all_row_values: + if isinstance(row_values, str): + continue + if isinstance(row_values[1], + int) and len(str(row_values[1])) > calltime_width: + calltime_width = len(str(row_values[1])) + if len(row_values[2]) > cpu_data_description_width: + cpu_data_description_width = len(row_values[2]) + if len(row_values[3]) > gpu_data_description_width: + gpu_data_description_width = len(row_values[3]) + headers = [ + 'Name', 'Calls', 'CPU Total / Avg / Max / Min / Ratio(%)', + 'GPU Total / Avg / Max / Min / Ratio(%)' + ] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + add_column(name_column_width) + add_column(calltime_width) + add_column(cpu_data_description_width) + add_column(gpu_data_description_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Operator Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for row_values in all_row_values: + if isinstance(row_values, str): + append(add_title(line_length, row_values)) + else: + append(row_format.format(*row_values)) + append(header_sep) + append('') + append('') + + if views is None or SummaryView.KernelView in views: + + ###### Print Kernel Summary Report ###### + if statistic_data.event_summary.kernel_items: + all_row_values = [] + kernel_items = statistic_data.event_summary.kernel_items + if sorted_by == SortedKeys.GPUAvg: + sorted_items = sorted(kernel_items.items(), + key=lambda x: x[1].avg_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMax: + sorted_items = sorted(kernel_items.items(), + key=lambda x: x[1].max_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMin: + sorted_items = sorted(kernel_items.items(), + key=lambda x: x[1].min_gpu_time) + else: + sorted_items = sorted(kernel_items.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + + total_kernel_gpu_time = 0 + for name, item in sorted_items: + total_kernel_gpu_time += item.gpu_time + for name, item in sorted_items: + if total_kernel_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(item.gpu_time) / total_kernel_gpu_time + row_values = [ + name, + item.call, + '{} / {} / {} / {} / {}'.format( + format_time(item.gpu_time, unit=time_unit), + format_time(item.avg_gpu_time, unit=time_unit), + format_time(item.max_gpu_time, unit=time_unit), + format_time(item.min_gpu_time, unit=time_unit), + format_ratio(gpu_ratio)), + ] + all_row_values.append(row_values) + + headers = [ + 'Name', 'Calls', 'GPU Total / Avg / Max / Min / Ratio(%)' + ] + # Calculate the column width + name_column_width = 90 + calltime_width = 6 + gpu_data_description_width = 40 + for row_values in all_row_values: + if isinstance(row_values[1], + int) and len(str(row_values[1])) > calltime_width: + calltime_width = len(str(row_values[1])) + if len(row_values[2]) > gpu_data_description_width: + gpu_data_description_width = len(row_values[2]) + + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + add_column(name_column_width) + add_column(calltime_width) + add_column(gpu_data_description_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Kernel Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + kernel_name_pattern = re.compile('(.+?)(<.*>)(\(.*\))') + for row_values in all_row_values: + match = kernel_name_pattern.match(row_values[0]) + if match: + name = match.group(1) + match.group(2) + else: + name = row_values[0] + if len(name) > name_column_width: + row_values[0] = name[:name_column_width - 3] + '...' + else: + row_values[0] = name + append(row_format.format(*row_values)) + append(header_sep) + append('') + append('') + + if views is None or SummaryView.MemoryManipulationView in views: + + ###### Print Memory Manipulation Summary Report ###### + if statistic_data.event_summary.memory_manipulation_items: + all_row_values = [] + memory_manipulation_items = statistic_data.event_summary.memory_manipulation_items + gpu_total_time = statistic_data.event_summary.model_perspective_items[ + 'ProfileStep'].general_gpu_time + for name, item in memory_manipulation_items.items(): + if gpu_total_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float(item.general_gpu_time) / gpu_total_time + row_values = [ + name, + item.call, + '{} / {} / {} / {} / {}'.format( + format_time(item.cpu_time, unit=time_unit), + format_time(item.avg_cpu_time, unit=time_unit), + format_time(item.max_cpu_time, unit=time_unit), + format_time(item.min_cpu_time, unit=time_unit), + format_ratio(float(item.cpu_time) / total_time)), + '{} / {} / {} / {} / {}'.format( + format_time(item.general_gpu_time, unit=time_unit), + format_time(item.avg_general_gpu_time, unit=time_unit), + format_time(item.max_general_gpu_time, unit=time_unit), + format_time(item.min_general_gpu_time, unit=time_unit), + format_ratio(gpu_ratio)), + ] + all_row_values.append(row_values) + + headers = [ + 'Name', 'Calls', 'CPU Total / Avg / Max / Min / Ratio(%)', + 'GPU Total / Avg / Max / Min / Ratio(%)' + ] + # Calculate the column width + name_column_width = 0 + calltime_width = 6 + cpu_data_description_width = 40 + gpu_data_description_width = 40 + for row_values in all_row_values: + if len(row_values[0]) > name_column_width: + name_column_width = len(row_values[0]) + if isinstance(row_values[1], + int) and len(str(row_values[1])) > calltime_width: + calltime_width = len(str(row_values[1])) + if len(row_values[2]) > cpu_data_description_width: + cpu_data_description_width = len(row_values[2]) + if len(row_values[3]) > gpu_data_description_width: + gpu_data_description_width = len(row_values[3]) + + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + add_column(name_column_width) + add_column(calltime_width) + add_column(cpu_data_description_width) + add_column(gpu_data_description_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Memory Manipulation Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for row_values in all_row_values: + append(row_format.format(*row_values)) + append(header_sep) + append('') + append('') + + if views is None or SummaryView.UDFView in views: + + ###### Print UserDefined Summary Report ###### + if statistic_data.event_summary.userdefined_items: + all_row_values = [] + gpu_total_time = statistic_data.event_summary.model_perspective_items[ + 'ProfileStep'].general_gpu_time + if thread_sep == True: + userdefined_thread_items = statistic_data.event_summary.userdefined_thread_items + else: + userdefined_thread_items = { + 'All threads merged': + statistic_data.event_summary.userdefined_items + } + for thread_id, items in userdefined_thread_items.items(): + all_row_values.append("Thread: {}".format(thread_id)) + if sorted_by == SortedKeys.CPUTotal: + sorted_items = sorted(items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUAvg: + sorted_items = sorted(items.items(), + key=lambda x: x[1].avg_cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUMax: + sorted_items = sorted(items.items(), + key=lambda x: x[1].max_cpu_time, + reverse=True) + elif sorted_by == SortedKeys.CPUMin: + sorted_items = sorted(items.items(), + key=lambda x: x[1].min_cpu_time) + elif sorted_by == SortedKeys.GPUTotal: + sorted_items = sorted(items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUAvg: + sorted_items = sorted( + items.items(), + key=lambda x: x[1].avg_general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMax: + sorted_items = sorted( + items.items(), + key=lambda x: x[1].max_general_gpu_time, + reverse=True) + elif sorted_by == SortedKeys.GPUMin: + sorted_items = sorted( + items.items(), key=lambda x: x[1].min_general_gpu_time) + + for name, item in sorted_items: + if gpu_total_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float( + item.general_gpu_time) / gpu_total_time + row_values = [ + name, + item.call, + '{} / {} / {} / {} / {}'.format( + format_time(item.cpu_time, unit=time_unit), + format_time(item.avg_cpu_time, unit=time_unit), + format_time(item.max_cpu_time, unit=time_unit), + format_time(item.min_cpu_time, unit=time_unit), + format_ratio(float(item.cpu_time) / total_time)), + '{} / {} / {} / {} / {}'.format( + format_time(item.general_gpu_time, unit=time_unit), + format_time(item.avg_general_gpu_time, + unit=time_unit), + format_time(item.max_general_gpu_time, + unit=time_unit), + format_time(item.min_general_gpu_time, + unit=time_unit), + format_ratio(gpu_ratio)), + ] + all_row_values.append(row_values) + + # Calculate the column width + name_column_width = 0 + calltime_width = 6 + cpu_data_description_width = 40 + gpu_data_description_width = 40 + for row_values in all_row_values: + if isinstance(row_values, str): + continue + if len(row_values[0]) > name_column_width: + name_column_width = len(row_values[0]) + if isinstance(row_values[1], + int) and len(str(row_values[1])) > calltime_width: + calltime_width = len(str(row_values[1])) + if len(row_values[2]) > cpu_data_description_width: + cpu_data_description_width = len(row_values[2]) + if len(row_values[3]) > gpu_data_description_width: + gpu_data_description_width = len(row_values[3]) + + headers = [ + 'Name', 'Calls', 'CPU Total / Avg / Max / Min / Ratio(%)', + 'GPU Total / Avg / Max / Min / Ratio(%)' + ] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + + add_column(name_column_width) + add_column(calltime_width) + add_column(cpu_data_description_width) + add_column(gpu_data_description_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "UserDefined Summary")) + append('Time unit: {}'.format(time_unit)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for row_values in all_row_values: + if isinstance(row_values, str): + append(add_title(line_length, row_values)) + else: + append(row_format.format(*row_values)) + append('') + append('') + + if views is None or SummaryView.MemoryView in views: + + ###### Print Memory Summary Report ###### + if statistic_data.memory_summary.allocated_items or statistic_data.memory_summary.reserved_items: + for device_type, memory_events in statistic_data.memory_summary.allocated_items.items( + ): + all_row_values = [] + sorted_items = sorted(memory_events.items(), + key=lambda x: x[1].increase_size, + reverse=True) + + for event_name, item in sorted_items: + row_values = [ + event_name, item.memory_type, item.allocation_count, + item.free_count, item.allocation_size, item.free_size, + item.increase_size + ] + all_row_values.append(row_values) + + sorted_reserved_items = sorted( + statistic_data.memory_summary.reserved_items[device_type]. + items(), + key=lambda x: x[1].increase_size, + reverse=True) + for event_name, item in sorted_reserved_items: + row_values = [ + event_name, item.memory_type, item.allocation_count, + item.free_count, item.allocation_size, item.free_size, + item.increase_size + ] + all_row_values.append(row_values) + + # Calculate the column width + headers = [ + 'Name', 'Type', 'Allocation Count', 'Free Count', + 'Allocation Size', 'Free Size', 'Increased Size' + ] + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + name_column_width = 50 + number_column_width = 15 + add_column(name_column_width) + add_column(12) + add_column(number_column_width) + add_column(number_column_width) + add_column(number_column_width) + add_column(number_column_width) + add_column(number_column_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append( + add_title(line_length, + "Memory Summary - {}".format(device_type))) + append('Peak Allocated Memory: {}'.format( + statistic_data.memory_summary. + peak_allocation_values[device_type])) + append('Peak Reserved Memory: {}'.format( + statistic_data.memory_summary. + peak_reserved_values[device_type])) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for row_values in all_row_values: + if isinstance(row_values, str): + append(add_title(line_length, row_values)) + else: + append(row_format.format(*row_values)) + append('') + append('') + + return ''.join(result) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/statistic_helper.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/statistic_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..358f2a09b926415a00a3bc38d168885fc03bc6be --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/statistic_helper.py @@ -0,0 +1,226 @@ +# Copyright (c) 2022 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. +import collections + + +def sum_ranges(ranges): + result = 0 + for time_range in ranges: + result += (time_range[1] - time_range[0]) + return result + + +def merge_self_ranges(src_ranges, is_sorted=False): + merged_ranges = [] + if len(src_ranges) > 0: + if not is_sorted: + src_ranges.sort(key=lambda x: x[0]) + cur_indx = 0 + merged_ranges.append((src_ranges[cur_indx][0], src_ranges[cur_indx][1])) + for cur_indx in range(1, len(src_ranges)): + if src_ranges[cur_indx][1] > merged_ranges[-1][1]: + if src_ranges[cur_indx][0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], + src_ranges[cur_indx][1]) + else: + merged_ranges.append( + (src_ranges[cur_indx][0], src_ranges[cur_indx][1])) + return merged_ranges + + +def merge_ranges(range_list1, range_list2, is_sorted=False): + merged_ranges = [] + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + len1 = len(range_list1) + len2 = len(range_list2) + if len1 == 0 and len2 == 0: + return merged_ranges + elif len1 == 0: + return range_list2 + elif len2 == 0: + return range_list1 + else: + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + if range1[0] < range2[0]: + merged_ranges.append(range1) + indx1 += 1 + else: + merged_ranges.append(range2) + indx2 += 1 + while indx1 < len1 and indx2 < len2: + range1 = range_list1[indx1] + range2 = range_list2[indx2] + if range1[0] < range2[0]: + if range1[1] > merged_ranges[-1][1]: + if range1[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range1[1]) + else: + merged_ranges.append((range1[0], range1[1])) + indx1 += 1 + else: + indx1 += 1 + else: + if range2[1] > merged_ranges[-1][1]: + if range2[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range2[1]) + else: + merged_ranges.append((range2[0], range2[1])) + indx2 += 1 + else: + indx2 += 1 + + while indx1 < len1: + range1 = range_list1[indx1] + if range1[1] > merged_ranges[-1][1]: + if range1[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range1[1]) + else: + merged_ranges.append((range1[0], range1[1])) + indx1 += 1 + else: + indx1 += 1 + while indx2 < len2: + range2 = range_list2[indx2] + if range2[1] > merged_ranges[-1][1]: + if range2[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range2[1]) + else: + merged_ranges.append((range2[0], range2[1])) + indx2 += 1 + else: + indx2 += 1 + return merged_ranges + + +def intersection_ranges(range_list1, range_list2, is_sorted=False): + result_range = [] + if len(range_list1) == 0 or len(range_list2) == 0: + return result_range + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + + len1 = len(range_list1) + len2 = len(range_list2) + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + while indx1 < len1 and indx2 < len2: + if range2[1] <= range1[0]: + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] <= range1[0] and range2[1] < range1[1]: + assert (range2[1] > range1[0]) + result_range.append((range1[0], range2[1])) + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] <= range1[0]: + assert (range2[1] >= range1[1]) + result_range.append(range1) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + + elif range2[1] < range1[1]: + assert (range2[0] > range1[0]) + result_range.append(range2) + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] < range1[1]: + assert (range2[1] >= range1[1]) + result_range.append((range2[0], range1[1])) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + + else: + assert (range2[0] >= range1[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + return result_range + + +def subtract_ranges(range_list1, range_list2, is_sorted=False): + result_range = [] + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + if len(range_list1) == 0: + return result_range + if len(range_list2) == 0: + return range_list1 + + len1 = len(range_list1) + len2 = len(range_list2) + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + + while indx1 < len(range_list1): + if indx2 == len(range_list2): + result_range.append(range1) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + elif range2[1] <= range1[0]: + indx2 += 1 + if indx2 != len2: + range2 = range_list2[indx2] + elif range2[0] <= range1[0] and range2[1] < range1[1]: + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 != len2: + range2 = range_list2[indx2] + elif range2[0] <= range1[0]: + assert (range2[1] >= range1[1]) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 != len1: + range1 = range_list1[indx1] + elif range2[0] < range1[1]: + assert (range2[0] > range1[0]) + result_range.append((range1[0], range2[0])) + range1 = (range2[0], range1[1]) + else: + assert (range2[0] >= range1[1]) + result_range.append(range1) + indx1 += 1 + if indx1 != len1: + range1 = range_list1[indx1] + return result_range diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/timer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..35689feb56c82cebb5165dab061207086526cd30 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/timer.py @@ -0,0 +1,412 @@ +# Copyright (c) 2022 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. + +import timeit +import logging +from collections import OrderedDict + + +class Stack(object): + """ + The stack in a Last-In/First-Out (LIFO) manner. New element is added at + the end and an element is removed from that end. + """ + + def __init__(self): + self.items = [] + + def push(self, item): + self.items.append(item) + + def pop(self): + return self.items.pop() + + def is_empty(self): + return len(self.items) == 0 + + def peek(self): + if not self.is_empty(): + return self.items[len(self.items) - 1] + else: + return None + + +class Event(object): + """ + A Event is used to record the cost of every step and the cost of + the total steps except skipped steps. + """ + + def __init__(self): + self.reader_cost_averager = TimeAverager() + self.batch_cost_averager = TimeAverager() + self.total_samples = 0 + self.total_iters = 0 + self.skip_iter = 10 + self.reader_records = dict(max=0, min=float('inf'), total=0) + self.batch_records = dict(max=0, min=float('inf'), total=0) + self.speed_records = dict(max=0, min=float('inf')) + self.reader = None + self.need_record = True + # The speed mode depends on the setting of num_samples, there + # are 2 modes: steps/s(num_samples=None) or samples/s. + self.speed_mode = 'samples/s' + # The speed unit depends on the unit of samples that is + # specified in step_info and only works in this speed_mode="samples/s". + self.speed_unit = 'samples/s' + + def reset(self): + self.reader_cost_averager.reset() + self.batch_cost_averager.reset() + + def record_reader(self, usetime): + self.reader_cost_averager.record(usetime) + if self.total_iters >= self.skip_iter: + self._update_records(usetime, self.reader_records) + + def record_batch(self, usetime, num_samples=None): + if num_samples is None: + self.speed_mode = "steps/s" + self.speed_unit = "steps/s" + self.batch_cost_averager.record(usetime, num_samples) + self.total_iters += 1 + + if self.total_iters >= self.skip_iter: + self._update_records(usetime, self.batch_records) + if self.speed_mode == "samples/s": + current_speed = float(num_samples) / usetime + self.total_samples += num_samples + else: + current_speed = 1.0 / usetime # steps/s + self._update_records(current_speed, self.speed_records) + + def _update_records(self, current_record, records): + if current_record > records['max']: + records['max'] = current_record + elif current_record < records['min']: + records['min'] = current_record + if 'total' in records.keys(): + records['total'] += current_record + + def reader_average(self): + return self.reader_cost_averager.get_average() + + def batch_average(self): + return self.batch_cost_averager.get_average() + + def speed_average(self): + if self.speed_mode == "samples/s": + return self.batch_cost_averager.get_ips_average() + else: + return self.batch_cost_averager.get_step_average() + + def get_summary(self): + if self.total_iters <= self.skip_iter: + return {} + + reader_avg = 0 + batch_avg = 0 + speed_avg = 0 + + self.total_iters -= self.skip_iter + reader_avg = self.reader_records['total'] / float(self.total_iters) + batch_avg = self.batch_records['total'] / float(self.total_iters) + if self.speed_mode == "samples/s": + speed_avg = float(self.total_samples) / self.batch_records['total'] + else: + speed_avg = float(self.total_iters) / self.batch_records['total'] + + reader_summary = dict(max=self.reader_records['max'], + min=self.reader_records['min'], + avg=reader_avg) + batch_summary = dict(max=self.batch_records['max'], + min=self.batch_records['min'], + avg=batch_avg) + ips_summary = dict(max=self.speed_records['max'], + min=self.speed_records['min'], + avg=speed_avg) + reader_ratio = (reader_avg / batch_avg) * 100 + summary = dict(reader_summary=reader_summary, + batch_summary=batch_summary, + ips_summary=ips_summary, + reader_ratio=reader_ratio) + + return summary + + +class Hook(object): + """ + As the base class. All types of hooks should inherit from it. + """ + + def begin(self, benchmark): + pass + + def end(self, benchmark): + pass + + def before_reader(self, benchmark): + pass + + def after_reader(self, benchmark): + pass + + def after_step(self, benchmark): + pass + + +class TimerHook(Hook): + """ + A hook for recording real-time performance and the summary + performance of total steps. + """ + + def __init__(self): + self.start_time = timeit.default_timer() + self.start_reader = timeit.default_timer() + + def begin(self, benchmark): + """ + Create the event for timing and initialize the start time of a step. + This function will be called in `Profiler.start()`. + """ + + benchmark.events.push(Event()) + benchmark.current_event = benchmark.events.peek() + self.start_time = timeit.default_timer() + + def before_reader(self, benchmark): + """ + Initialize the start time of the dataloader. This function will be + called at the beginning of `next` method in `_DataLoaderIterMultiProcess` or + `_DataLoaderIterSingleProcess`. + + """ + + self.start_reader = timeit.default_timer() + + def after_reader(self, benchmark): + """ + Record the cost of dataloader for the current step. Since the skipped steps + are 10, it will update the maximum, minimum and the total time from the step + 11 to the current step. This function will be called at the end of `next` + method in `_DataLoaderIterMultiProcess` or `_DataLoaderIterSingleProcess`. + + """ + + reader_cost = timeit.default_timer() - self.start_reader + if (benchmark.current_event is None) or ( + not benchmark.current_event.need_record) or (reader_cost == 0): + return + benchmark.current_event.record_reader(reader_cost) + + def after_step(self, benchmark): + """ + Record the cost for the current step. It will contain the cost of the loading + data if there is a dataloader. Similar to `after_reader`, it will also update + the maximum, minimum and the total time from the step 11 to the current step + as well as the maximum and minimum speed of the model. This function will + be called in `Profiler.step()`. + + """ + + if (benchmark.current_event is + None) or (not benchmark.current_event.need_record): + return + batch_cost = timeit.default_timer() - self.start_time + benchmark.current_event.record_batch(batch_cost, benchmark.num_samples) + self.start_time = timeit.default_timer() + + def end(self, benchmark): + """ + Print the performance summary of the model and pop the current event + from the events stack. Since there may be nested timing events, such + as evaluation in the training process, the current event needs to be + update to the event at the top of the stack. + + """ + + if benchmark.events.is_empty(): + return + self._print_summary(benchmark) + benchmark.events.pop() + benchmark.current_event = benchmark.events.peek() + self.start_time = timeit.default_timer() + + def _print_summary(self, benchmark): + summary = benchmark.current_event.get_summary() + if not summary: + return + print('Perf Summary'.center(100, '=')) + if summary['reader_ratio'] != 0: + print('Reader Ratio: ' + '%.3f' % (summary['reader_ratio']) + '%') + print('Time Unit: s, IPS Unit: %s' % + (benchmark.current_event.speed_unit)) + print('|', ''.center(15), '|', 'avg'.center(15), '|', 'max'.center(15), + '|', 'min'.center(15), '|') + # if DataLoader is not called, reader_summary is unnecessary. + if summary['reader_summary']['avg'] != 0: + self._print_stats('reader_cost', summary['reader_summary']) + self._print_stats('batch_cost', summary['batch_summary']) + self._print_stats('ips', summary['ips_summary']) + + def _print_stats(self, item, message_dict): + avg_str = '%.5f' % (message_dict['avg']) + max_str = '%.5f' % (message_dict['max']) + min_str = '%.5f' % (message_dict['min']) + print('|', item.center(15), '|', avg_str.center(15), '|', + max_str.center(15), '|', min_str.center(15), '|') + + +class TimeAverager(object): + """ + Record the cost of every step and count the average. + """ + + def __init__(self): + self.reset() + + def reset(self): + self._total_iters = 0 + self._total_time = 0 + self._total_samples = 0 + + def record(self, usetime, num_samples=None): + self._total_iters += 1 + self._total_time += usetime + if num_samples: + self._total_samples += num_samples + + def get_average(self): + """ + Get the average cost of loading data or a step. + """ + + if self._total_iters == 0: + return 0 + return self._total_time / float(self._total_iters) + + def get_ips_average(self): + """ + Get the average throughput when speed mode is "samples/s". + """ + + if not self._total_samples or self._total_iters == 0: + return 0 + return float(self._total_samples) / self._total_time + + def get_step_average(self): + """ + Get the average speed when speed mode is "step/s". + """ + + if self._total_iters == 0: + return 0 + return float(self._total_iters) / self._total_time + + +class Benchmark(object): + """ + A tool for the statistics of model performance. The `before_reader` + and `after_reader` are called in the DataLoader to count the cost + of loading the data. The `begin`, `step` and `end` are called to + count the cost of a step or total steps. + """ + + def __init__(self): + self.num_samples = None + self.hooks = OrderedDict(timer_hook=TimerHook()) + self.current_event = None + self.events = Stack() + + def step(self, num_samples=None): + """ + Record the statistic for the current step. It will be called in + `Profiler.step()`. + """ + + self.num_samples = num_samples + self.after_step() + + def step_info(self, unit): + """ + It returns the statistic of the current step as a string. It contains + "reader_cost", "batch_cost" and "ips". + """ + + message = '' + reader_average = self.current_event.reader_average() + batch_average = self.current_event.batch_average() + if reader_average: + message += ' reader_cost: %.5f s' % (reader_average) + if batch_average: + if self.current_event.speed_mode == 'steps/s': + self.current_event.speed_unit = 'steps/s' + else: + self.current_event.speed_unit = unit + '/s' + message += ' %s: %.5f s' % ('batch_cost', batch_average) + speed_average = self.current_event.speed_average() + if speed_average: + message += ' ips: %.3f %s' % (speed_average, + self.current_event.speed_unit) + self.current_event.reset() + return message + + def begin(self): + for hook in self.hooks.values(): + hook.begin(self) + + def before_reader(self): + for hook in self.hooks.values(): + hook.before_reader(self) + + def after_reader(self): + for hook in self.hooks.values(): + hook.after_reader(self) + + def after_step(self): + for hook in self.hooks.values(): + hook.after_step(self) + + def end(self): + for hook in self.hooks.values(): + hook.end(self) + + def check_if_need_record(self, reader): + if self.current_event is None: + return + if self.current_event.need_record: + # set reader for the current event at the first iter + if self.current_event.reader is None: + self.current_event.reader = reader + elif self.current_event.reader.__dict__[ + '_dataset'] != reader.__dict__['_dataset']: + # enter a new task but not calling beign() to record it. + # we pause the timer until the end of new task, so that + # the cost of new task is not added to the current event. + # eg. start evaluation in the training task + self.current_event.need_record = False + else: + # when the new task exits, continue timing for the current event. + if self.current_event.reader.__dict__[ + '_dataset'] == reader.__dict__['_dataset']: + self.current_event.need_record = True + self.hooks['timer_hook'].start_time = timeit.default_timer() + + +_benchmark_ = Benchmark() + + +def benchmark(): + return _benchmark_ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..efe3975f1445246678aeed42c2cf7414e4dc188a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/profiler/utils.py @@ -0,0 +1,194 @@ +# Copyright (c) 2022 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. + +from typing import Any +from warnings import warn +import functools +from contextlib import ContextDecorator + +from paddle.fluid import core +from paddle.fluid.core import _RecordEvent, TracerEventType + +_is_profiler_used = False +_has_optimizer_wrapped = False + +_AllowedEventTypeList = [ + TracerEventType.Dataloader, + TracerEventType.ProfileStep, + TracerEventType.Forward, + TracerEventType.Backward, + TracerEventType.Optimization, + TracerEventType.PythonOp, + TracerEventType.PythonUserDefined, +] + + +class RecordEvent(ContextDecorator): + r""" + Interface for recording a time range by user defined. + + Args: + name (str): Name of the record event. + event_type (TracerEventType, optional): Optional, default value is + `TracerEventType.PythonUserDefined`. It is reserved for internal + purpose, and it is better not to specify this parameter. + + Examples: + .. code-block:: python + :name: code-example1 + + import paddle + import paddle.profiler as profiler + # method1: using context manager + with profiler.RecordEvent("record_add"): + data1 = paddle.randn(shape=[3]) + data2 = paddle.randn(shape=[3]) + result = data1 + data2 + # method2: call begin() and end() + record_event = profiler.RecordEvent("record_add") + record_event.begin() + data1 = paddle.randn(shape=[3]) + data2 = paddle.randn(shape=[3]) + result = data1 + data2 + record_event.end() + + **Note**: + RecordEvent will take effect only when :ref:`Profiler ` is on and at the state of `RECORD`. + """ + + def __init__( + self, + name: str, + event_type: TracerEventType = TracerEventType.PythonUserDefined, + ): + self.name = name + self.event_type = event_type + self.event = None + + def __enter__(self): + self.begin() + return self + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any): + self.end() + + def begin(self): + r""" + Record the time of beginning. + + Examples: + + .. code-block:: python + :name: code-example2 + + import paddle + import paddle.profiler as profiler + record_event = profiler.RecordEvent("record_sub") + record_event.begin() + data1 = paddle.randn(shape=[3]) + data2 = paddle.randn(shape=[3]) + result = data1 - data2 + record_event.end() + """ + if not _is_profiler_used: + return + if self.event_type not in _AllowedEventTypeList: + warn( + "Only TracerEvent Type in [{}, {}, {}, {}, {}, {},{}]\ + can be recorded.".format( + *_AllowedEventTypeList + ) + ) + self.event = None + else: + self.event = _RecordEvent(self.name, self.event_type) + + def end(self): + r''' + Record the time of ending. + + Examples: + + .. code-block:: python + :name: code-example3 + + import paddle + import paddle.profiler as profiler + record_event = profiler.RecordEvent("record_mul") + record_event.begin() + data1 = paddle.randn(shape=[3]) + data2 = paddle.randn(shape=[3]) + result = data1 * data2 + record_event.end() + ''' + if self.event: + self.event.end() + + +def load_profiler_result(filename: str): + r""" + Load dumped profiler data back to memory. + + Args: + filename(str): Name of the exported protobuf file of profiler data. + + Returns: + ``ProfilerResult`` object, which stores profiling data. + + Examples: + .. code-block:: python + + # required: gpu + import paddle.profiler as profiler + with profiler.Profiler( + targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU], + scheduler = (3, 10)) as p: + for iter in range(10): + #train() + p.step() + p.export('test_export_protobuf.pb', format='pb') + profiler_result = profiler.load_profiler_result('test_export_protobuf.pb') + """ + return core.load_profiler_result(filename) + + +def in_profiler_mode(): + return _is_profiler_used == True + + +def wrap_optimizers(): + def optimizer_warpper(func): + @functools.wraps(func) + def warpper(*args, **kwargs): + if in_profiler_mode(): + with RecordEvent( + 'Optimization Step', event_type=TracerEventType.Optimization + ): + return func(*args, **kwargs) + else: + return func(*args, **kwargs) + + return warpper + + global _has_optimizer_wrapped + if _has_optimizer_wrapped == True: + return + import paddle.optimizer as optimizer + + for classname in optimizer.__all__: + if classname != 'Optimizer': + classobject = getattr(optimizer, classname) + if getattr(classobject, 'step', None) != None: + classobject.step = optimizer_warpper(classobject.step) + _has_optimizer_wrapped = True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9002cd0676edaa2d959f673e5c80a061f6a41884 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/__init__.py @@ -0,0 +1,77 @@ +# 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. +r""" +At training and testing time, PaddlePaddle programs need to read data. To ease +the users' work to write data reading code, we define that + +- A *reader* is a function that reads data (from file, network, random number + generator, etc) and yields data items. +- A *reader creator* is a function that returns a reader function. +- A *reader decorator* is a function, which accepts one or more readers, and + returns a reader. +- A *batch reader* is a function that reads data (from *reader*, file, network, + random number generator, etc) and yields a batch of data items. + +##################### +Data Reader Interface +##################### + +Indeed, *data reader* doesn't have to be a function that reads and yields data +items. It can be any function with no parameter that creates a iterable +(anything can be used in :code:`for x in iterable`)\: + +.. code-block:: python + + iterable = data_reader() + +Element produced from the iterable should be a **single** entry of data, +**not** a mini batch. That entry of data could be a single item, or a tuple of +items. +Item should be of supported type (e.g., numpy array or list/tuple of float +or int). + +An example implementation for single item data reader creator: + +.. code-block:: python + + def reader_creator_random_image(width, height): + def reader(): + while True: + yield numpy.random.uniform(-1, 1, size=width*height) + return reader + +An example implementation for multiple item data reader creator: + +.. code-block:: python + + def reader_creator_random_image_and_label(width, height, label): + def reader(): + while True: + yield numpy.random.uniform(-1, 1, size=width*height), label + return reader + +""" + +from paddle.reader.decorator import map_readers # noqa: F401 +from paddle.reader.decorator import shuffle # noqa: F401 +from paddle.reader.decorator import xmap_readers # noqa: F401 +from paddle.reader.decorator import firstn # noqa: F401 +from paddle.reader.decorator import buffered # noqa: F401 +from paddle.reader.decorator import compose # noqa: F401 +from paddle.reader.decorator import cache # noqa: F401 +from paddle.reader.decorator import ComposeNotAligned # noqa: F401 +from paddle.reader.decorator import chain # noqa: F401 +from paddle.reader.decorator import multiprocess_reader # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/decorator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..20874215ddc268216cd44cbb04847abb6e92cb81 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/reader/decorator.py @@ -0,0 +1,697 @@ +# 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. + +from threading import Thread +import subprocess +import multiprocessing +import six +import sys +import warnings +import logging + +from six.moves.queue import Queue +from six.moves import zip_longest +from six.moves import map +from six.moves import zip +import itertools +import random +import zlib + +import paddle.compat as cpt +from paddle.fluid.reader import QUEUE_GET_TIMEOUT + +__all__ = [] + +# On macOS, the 'spawn' start method is now the default in Python3.8 multiprocessing, +# Paddle is currently unable to solve this, so forces the process to start using +# the 'fork' start method. +# +# TODO: This solution is not good, because the fork start method could lead to +# crashes of the subprocess. Figure out how to make 'spawn' work. +# +# For more details, please refer to +# https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods +# https://bugs.python.org/issue33725 +if sys.version_info >= (3, 8) and sys.platform == 'darwin': + fork_context = multiprocessing.get_context('fork') +else: + fork_context = multiprocessing + + +def cache(reader): + """ + Cache the reader data into memory. + + Be careful that this method may take long time to process, + and consume lots of memory. :code:`reader()` would only + call once. + + Args: + reader (generator): a reader object which yields + data each time. + + Returns: + generator: a decorated reader object which yields data from cached memory. + + Examples: + .. code-block:: python + + import paddle + + def reader(): + for i in range(3): + yield i + + # All data is cached into memory + cached_reader = paddle.io.cache(reader) + + # Output: 0 1 2 + for i in cached_reader(): + print(i) + """ + all_data = tuple(reader()) + + def __impl__(): + for item in all_data: + yield item + + return __impl__ + + +def map_readers(func, *readers): + """ + Creates a data reader that outputs return value of function using + output of each data reader as arguments. + + If input readers output the following data entries: 2 3, + and the input func is mul(x, y), + the output of the resulted reader will be 6. + + + Args: + func: a function to read data and compute result, the output of this function + will be set as the output of the resulted data reader. + readers (Reader|list of Reader): list of readers whose outputs will be used as arguments of func. + + Returns: + the resulted data reader (Reader) + + Examples: + + .. code-block:: python + + import paddle.reader + d = {"h": 0, "i": 1} + def func(x): + return d[x] + def reader(): + yield "h" + yield "i" + map_reader_result = paddle.reader.map_readers(func, reader) + """ + + def reader(): + rs = [] + for r in readers: + rs.append(r()) + for e in map(func, *rs): + yield e + + return reader + + +def shuffle(reader, buf_size): + """ + paddle.fluid.io.shuffle ( :ref:`api_fluid_io_shuffle` ) is recommended to use, + and paddle.reader.shuffle is an alias. + + This API creates a decorated reader that outputs the shuffled data. + + The output data from the origin reader will be saved into a buffer, + and then shuffle the data. The size of buffer is determined by argument buf_size. + + Args: + reader(callable): the original reader whose data will be shuffled. + buf_size(int): the size of shuffled buffer. + + Returns: + callable: a decorated reader. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + def reader(): + for i in range(5): + yield i + shuffled_reader = fluid.io.shuffle(reader, 3) + for e in shuffled_reader(): + print(e) + # outputs are 0~4 unordered arrangement + """ + + def data_reader(): + buf = [] + for e in reader(): + buf.append(e) + if len(buf) >= buf_size: + random.shuffle(buf) + for b in buf: + yield b + buf = [] + + if len(buf) > 0: + random.shuffle(buf) + for b in buf: + yield b + + return data_reader + + +def chain(*readers): + """ + Use the input data readers to create a chained data reader. The new created reader + chains the outputs of input readers together as its output, and it do not change + the format of the outputs. + + **Note**: + ``paddle.reader.chain`` is the alias of ``paddle.fluid.io.chain``, and + ``paddle.fluid.io.chain`` is recommended to use. + + For example, if three input readers' outputs are as follows: + [0, 0, 0], + [10, 10, 10], + [20, 20, 20]. + The chained reader will output: + [0, 0, 0], [10, 10, 10], [20, 20, 20]. + + Args: + readers(list): input data readers. + + Returns: + callable: the new chained data reader. + + Examples: + .. code-block:: python + + import paddle + + def reader_creator_3(start): + def reader(): + for i in range(start, start + 3): + yield [i, i, i] + return reader + + c = paddle.reader.chain(reader_creator_3(0), reader_creator_3(10), reader_creator_3(20)) + for e in c(): + print(e) + # Output: + # [0, 0, 0] + # [1, 1, 1] + # [2, 2, 2] + # [10, 10, 10] + # [11, 11, 11] + # [12, 12, 12] + # [20, 20, 20] + # [21, 21, 21] + # [22, 22, 22] + + """ + + def reader(): + rs = [] + for r in readers: + rs.append(r()) + + for e in itertools.chain(*rs): + yield e + + return reader + + +class ComposeNotAligned(ValueError): + pass + + +def compose(*readers, **kwargs): + """ + Creates a data reader whose output is the combination of input readers. + + If input readers output following data entries: + (1, 2) 3 (4, 5) + The composed reader will output: + (1, 2, 3, 4, 5) + + Args: + readers (Reader|list of Reader): readers that will be composed together. + check_alignment(bool, optional): Indicates whether the input readers are checked for + alignment. If True, whether input readers are aligned + correctly will be checked, else alignment will not be checkout and trailing outputs + will be discarded. Defaults to True. + + Returns: + the new data reader (Reader). + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + def reader_creator_10(dur): + def reader(): + for i in range(10): + yield i + return reader + reader = fluid.io.compose(reader_creator_10(0), reader_creator_10(0)) + """ + check_alignment = kwargs.pop('check_alignment', True) + + def make_tuple(x): + if isinstance(x, tuple): + return x + else: + return (x,) + + def reader(): + rs = [] + for r in readers: + rs.append(r()) + if not check_alignment: + for outputs in zip(*rs): + yield sum(list(map(make_tuple, outputs)), ()) + else: + for outputs in zip_longest(*rs): + for o in outputs: + if o is None: + # None will be not be present if compose is aligned + raise ComposeNotAligned( + "outputs of readers are not aligned." + ) + yield sum(list(map(make_tuple, outputs)), ()) + + return reader + + +def buffered(reader, size): + """ + Creates a buffered data reader. + + The buffered data reader will read and save data entries into a + buffer. Reading from the buffered data reader will proceed as long + as the buffer is not empty. + + Args: + reader(generator): the data reader to read from. + size(int): max buffer size. + + Returns: + generator: the buffered data reader. + + Examples: + .. code-block:: python + + import paddle + + def reader(): + for i in range(3): + yield i + + # Create a buffered reader, and the buffer size is 2. + buffered_reader = paddle.io.buffered(reader, 2) + + # Output: 0 1 2 + for i in buffered_reader(): + print(i) + """ + + class EndSignal: + pass + + end = EndSignal() + + def read_worker(r, q): + for d in r: + q.put(d) + q.put(end) + + def data_reader(): + r = reader() + q = Queue(maxsize=size) + t = Thread( + target=read_worker, + args=( + r, + q, + ), + ) + t.daemon = True + t.start() + e = q.get() + while e != end: + yield e + e = q.get() + + return data_reader + + +def firstn(reader, n): + """ + paddle.fluid.io.firstn ( :ref:`api_fluid_io_firstn` ) is recommended to use, + and paddle.reader.firstn is an alias. + + This API creates a decorated reader, and limits the max number of + samples that reader could return. + + Args: + reader(callable): the input reader. + n(int): the max number of samples in the reader. + + Returns: + callable: the decorated reader. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + def reader(): + for i in range(100): + yield i + firstn_reader = fluid.io.firstn(reader, 5) + for e in firstn_reader(): + print(e) + # the outputs are: 0 1 2 3 4 + """ + + # TODO(yuyang18): Check if just drop the reader, could clean the opened + # resource or not? + + def firstn_reader(): + for i, item in enumerate(reader()): + if i == n: + break + yield item + + return firstn_reader + + +class XmapEndSignal: + pass + + +def xmap_readers(mapper, reader, process_num, buffer_size, order=False): + """ + Use multi-threads to map samples from reader by a mapper defined by user. + + Args: + mapper (callable): a function to map the data from reader. + reader (callable): a data reader which yields the data. + process_num (int): thread number to handle original sample. + buffer_size (int): size of the queue to read data in. + order (bool): whether to keep the data order from original reader. + Default False. + + Returns: + callable: a decorated reader with data mapping. + """ + end = XmapEndSignal() + + # define a worker to read samples from reader to in_queue + def read_worker(reader, in_queue): + for i in reader(): + in_queue.put(i) + in_queue.put(end) + + # define a worker to read samples from reader to in_queue with order flag + def order_read_worker(reader, in_queue): + in_order = 0 + for i in reader(): + in_queue.put((in_order, i)) + in_order += 1 + in_queue.put(end) + + # define a worker to handle samples from in_queue by mapper + # and put mapped samples into out_queue + def handle_worker(in_queue, out_queue, mapper): + sample = in_queue.get() + while not isinstance(sample, XmapEndSignal): + r = mapper(sample) + out_queue.put(r) + sample = in_queue.get() + in_queue.put(end) + out_queue.put(end) + + # define a worker to handle samples from in_queue by mapper + # and put mapped samples into out_queue by order + def order_handle_worker(in_queue, out_queue, mapper, out_order): + ins = in_queue.get() + while not isinstance(ins, XmapEndSignal): + order, sample = ins + r = mapper(sample) + while order != out_order[0]: + pass + out_queue.put(r) + out_order[0] += 1 + ins = in_queue.get() + in_queue.put(end) + out_queue.put(end) + + def xreader(): + in_queue = Queue(buffer_size) + out_queue = Queue(buffer_size) + out_order = [0] + # start a read worker in a thread + target = order_read_worker if order else read_worker + t = Thread(target=target, args=(reader, in_queue)) + t.daemon = True + t.start() + # start several handle_workers + target = order_handle_worker if order else handle_worker + args = ( + (in_queue, out_queue, mapper, out_order) + if order + else (in_queue, out_queue, mapper) + ) + workers = [] + for i in range(process_num): + worker = Thread(target=target, args=args) + worker.daemon = True + workers.append(worker) + for w in workers: + w.start() + + sample = out_queue.get() + while not isinstance(sample, XmapEndSignal): + yield sample + sample = out_queue.get() + finish = 1 + while finish < process_num: + sample = out_queue.get() + if isinstance(sample, XmapEndSignal): + finish += 1 + else: + yield sample + + return xreader + + +def multiprocess_reader(readers, use_pipe=True, queue_size=1000): + """ + This API use python ``multiprocessing`` to read data from ``readers`` parallelly, + and then ``multiprocess.Queue`` or ``multiprocess.Pipe`` is used to merge + these data. A separate process will be created for each reader in the + ``readers`` list, please guarantee every reader can work independently + to avoid conflicts in parallel environment. + + + ``Multiprocess.Queue`` require the rw access right to /dev/shm, and it's not supported + in some platforms. + + Parameters: + readers (list( ``generator`` ) | tuple( ``generator`` )): a python ``generator`` list + used to read input data + use_pipe (bool, optional): control the inner API used to implement the multi-processing, + default True - use ``multiprocess.Pipe`` which is recommended + queue_size (int, optional): only useful when ``use_pipe`` is False - ``multiprocess.Queue`` + is used, default 1000. Increase this value can speed up the data reading, and more memory + will be consumed. + + Returns: + ``generator``: a new reader which can be run parallelly + + + Example: + + .. code-block:: python + + import paddle.fluid as fluid + from paddle.fluid.io import multiprocess_reader + import numpy as np + + sample_files = ['sample_file_1', 'sample_file_2'] + + def fake_input_files(): + with open(sample_files[0], 'w') as f: + np.savez(f, a=np.array([1, 2]), b=np.array([3, 4]), c=np.array([5, 6]), d=np.array([7, 8])) + with open(sample_files[1], 'w') as f: + np.savez(f, a=np.array([9, 10]), b=np.array([11, 12]), c=np.array([13, 14])) + + + def generate_reader(file_name): + # load data file + def _impl(): + data = np.load(file_name) + for item in sorted(data.files): + yield data[item], + return _impl + + if __name__ == '__main__': + # generate sample input files + fake_input_files() + + with fluid.program_guard(fluid.Program(), fluid.Program()): + place = fluid.CPUPlace() + # the 1st 2 is batch size + image = fluid.data(name='image', dtype='int64', shape=[2, 1, 2]) + fluid.layers.Print(image) + # print detailed tensor info of image variable + + reader = fluid.io.PyReader(feed_list=[image], capacity=2) + + decorated_reader = multiprocess_reader( + [generate_reader(sample_files[0]), generate_reader(sample_files[1])], False) + + reader.decorate_sample_generator(decorated_reader, batch_size=2, places=[place]) + + exe = fluid.Executor(place) + exe.run(fluid.default_startup_program()) + + for data in reader(): + res = exe.run(feed=data, fetch_list=[image]) + print(res[0]) + # print below content in this case + # [[[1 2]], [[3 4]]] + # [[[5 6]], [[7 8]]] + # [[[9 10]], [[11 12]]] + # [13,14] will be dropped + + """ + + if sys.platform == 'win32': + raise NotImplementedError( + "The multiprocess_reader method is not supported on windows." + ) + + # ujson is ultra fast json encoder and decoder written in pure C with bindings for Python 3.6+. + try: + import ujson as json + except Exception as e: + warnings.warn( + "The `ujson` module is not found, use the `json` module, `ujson` encodes and decodes faster, " + "you can install `ujson` through `pip install ujson`." + ) + import json + + assert ( + isinstance(readers, (list, tuple)) and len(readers) > 0 + ), "`readers` must be list or tuple." + + def _read_into_queue(reader, queue): + try: + for sample in reader(): + if sample is None: + raise ValueError("sample has None") + queue.put(sample) + queue.put(None) + except: + queue.put("") + six.reraise(*sys.exc_info()) + + def queue_reader(): + queue = fork_context.Queue(queue_size) + for reader in readers: + p = fork_context.Process( + target=_read_into_queue, args=(reader, queue) + ) + p.start() + + reader_num = len(readers) + finish_num = 0 + while finish_num < reader_num: + try: + sample = queue.get(timeout=QUEUE_GET_TIMEOUT) + except: + logging.error( + "multiprocess_reader failed to get data from the multiprocessing.Queue." + ) + six.reraise(*sys.exc_info()) + + if sample is None: + finish_num += 1 + elif sample == "": + raise ValueError( + "multiprocess_reader failed to put data into the multiprocessing.Queue." + ) + else: + yield sample + + def _read_into_pipe(reader, conn): + try: + for sample in reader(): + if sample is None: + raise ValueError("sample has None!") + conn.send(json.dumps(sample)) + conn.send(json.dumps(None)) + conn.close() + except: + conn.send(json.dumps("")) + conn.close() + six.reraise(*sys.exc_info()) + + def pipe_reader(): + conns = [] + for reader in readers: + parent_conn, child_conn = fork_context.Pipe() + conns.append(parent_conn) + p = fork_context.Process( + target=_read_into_pipe, args=(reader, child_conn) + ) + p.start() + + reader_num = len(readers) + finish_num = 0 + conn_to_remove = [] + while finish_num < reader_num: + for conn in conn_to_remove: + conns.remove(conn) + conn_to_remove = [] + for conn in conns: + sample = json.loads(conn.recv()) + if sample is None: + finish_num += 1 + conn.close() + conn_to_remove.append(conn) + elif sample == "": + conn.close() + conn_to_remove.append(conn) + raise ValueError( + "multiprocess_reader failed to send data into the multiprocessing.Pipe." + ) + else: + yield sample + + if use_pipe: + return pipe_reader + else: + return queue_reader diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/regularizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/regularizer.py new file mode 100644 index 0000000000000000000000000000000000000000..38060b8233fdbaf286876a0f9e408153b627e72f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/regularizer.py @@ -0,0 +1,140 @@ +# 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. + +__all__ = ['L1Decay', 'L2Decay'] + +import paddle.fluid as fluid + + +class L1Decay(fluid.regularizer.L1Decay): + r""" + Implement the L1 Weight Decay Regularization, which encourages the weights to be sparse. + + It can be set in :ref:`api_paddle_ParamAttr` or ``optimizer`` (such as :ref:`api_paddle_optimizer_Momentum` ). + When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in + ``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has + higher priority than ``optimizer`` , which means that for a trainable parameter, if regularizer is defined + in its ParamAttr, then the regularizer in Optimizer will be ignored. Otherwise the regularizer + in Optimizer will be used. + + In the implementation, the loss function of L1 Weight Decay Regularization is as follows: + + .. math:: + + loss = coeff * reduce\_sum(abs(x)) + + Args: + coeff(float, optional): regularization coeff. Default:0.0. + + Examples: + .. code-block:: python + + # Example1: set Regularizer in optimizer + import paddle + from paddle.regularizer import L1Decay + + linear = paddle.nn.Linear(10, 10) + inp = paddle.rand(shape=[10, 10], dtype="float32") + out = linear(inp) + loss = paddle.mean(out) + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + momentum = paddle.optimizer.Momentum( + learning_rate=0.1, + parameters=linear.parameters(), + weight_decay=L1Decay(0.0001)) + back = out.backward() + momentum.step() + momentum.clear_grad() + + # Example2: set Regularizer in parameters + # Set L1 regularization in parameters. + # Global regularizer does not take effect on my_conv2d for this case. + from paddle.nn import Conv2D + from paddle import ParamAttr + from paddle.regularizer import L2Decay + + my_conv2d = Conv2D( + in_channels=10, + out_channels=10, + kernel_size=1, + stride=1, + padding=0, + weight_attr=ParamAttr(regularizer=L2Decay(coeff=0.01)), + bias_attr=False) + """ + + def __init__(self, coeff=0.0): + super(L1Decay, self).__init__(coeff) + + +class L2Decay(fluid.regularizer.L2Decay): + r""" + Implement the L2 Weight Decay Regularization, which helps to prevent the model over-fitting. + + It can be set in :ref:`api_paddle_ParamAttr` or ``optimizer`` (such as :ref:`api_paddle_optimizer_Momentum` ). + When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in + ``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has + higher priority than ``optimizer`` , which means that for a trainable parameter, if regularizer is defined + in its ParamAttr, then the regularizer in Optimizer will be ignored. Otherwise the regularizer + in Optimizer will be used. + + In the implementation, the loss function of L2 Weight Decay Regularization is as follows: + + .. math:: + + loss = 0.5 * coeff * reduce\_sum(square(x)) + + Args: + regularization_coeff(float, optional): regularization coeff. Default:0.0 + + Examples: + .. code-block:: python + + # Example1: set Regularizer in optimizer + import paddle + from paddle.regularizer import L2Decay + linear = paddle.nn.Linear(10, 10) + inp = paddle.rand(shape=[10, 10], dtype="float32") + out = linear(inp) + loss = paddle.mean(out) + beta1 = paddle.to_tensor([0.9], dtype="float32") + beta2 = paddle.to_tensor([0.99], dtype="float32") + momentum = paddle.optimizer.Momentum( + learning_rate=0.1, + parameters=linear.parameters(), + weight_decay=L2Decay(0.0001)) + back = out.backward() + momentum.step() + momentum.clear_grad() + + # Example2: set Regularizer in parameters + # Set L2 regularization in parameters. + # Global regularizer does not take effect on my_conv2d for this case. + from paddle.nn import Conv2D + from paddle import ParamAttr + from paddle.regularizer import L2Decay + + my_conv2d = Conv2D( + in_channels=10, + out_channels=10, + kernel_size=1, + stride=1, + padding=0, + weight_attr=ParamAttr(regularizer=L2Decay(coeff=0.01)), + bias_attr=False) + """ + + def __init__(self, coeff=0.0): + super(L2Decay, self).__init__(coeff) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/signal.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/signal.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4de719a9c8ee97898ba28e66420c7f110a1df8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/signal.py @@ -0,0 +1,644 @@ +# Copyright (c) 2021 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. + +from typing import Optional + +import paddle + +from .tensor.attribute import is_complex, is_floating_point +from .fft import fft_r2c, fft_c2r, fft_c2c +from .fluid.data_feeder import check_variable_and_dtype +from .fluid.framework import _non_static_mode +from .fluid.layer_helper import LayerHelper +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph + +__all__ = [ + 'stft', + 'istft', +] + + +def frame(x, frame_length, hop_length, axis=-1, name=None): + """ + Slice the N-dimensional (where N >= 1) input into (overlapping) frames. + + Args: + x (Tensor): The input data which is a N-dimensional (where N >= 1) Tensor + with shape `[..., seq_length]` or `[seq_length, ...]`. + frame_length (int): Length of the frame and `0 < frame_length <= x.shape[axis]`. + hop_length (int): Number of steps to advance between adjacent frames + and `0 < hop_length`. + axis (int, optional): Specify the axis to operate on the input Tensors. Its + value should be 0(the first dimension) or -1(the last dimension). If not + specified, the last axis is used by default. + + Returns: + The output frames tensor with shape `[..., frame_length, num_frames]` if `axis==-1`, + otherwise `[num_frames, frame_length, ...]` where + + `num_framse = 1 + (x.shape[axis] - frame_length) // hop_length` + + Examples: + + .. code-block:: python + + import paddle + from paddle.signal import frame + + # 1D + x = paddle.arange(8) + y0 = frame(x, frame_length=4, hop_length=2, axis=-1) # [4, 3] + # [[0, 2, 4], + # [1, 3, 5], + # [2, 4, 6], + # [3, 5, 7]] + + y1 = frame(x, frame_length=4, hop_length=2, axis=0) # [3, 4] + # [[0, 1, 2, 3], + # [2, 3, 4, 5], + # [4, 5, 6, 7]] + + # 2D + x0 = paddle.arange(16).reshape([2, 8]) + y0 = frame(x0, frame_length=4, hop_length=2, axis=-1) # [2, 4, 3] + # [[[0, 2, 4], + # [1, 3, 5], + # [2, 4, 6], + # [3, 5, 7]], + # + # [[8 , 10, 12], + # [9 , 11, 13], + # [10, 12, 14], + # [11, 13, 15]]] + + x1 = paddle.arange(16).reshape([8, 2]) + y1 = frame(x1, frame_length=4, hop_length=2, axis=0) # [3, 4, 2] + # [[[0 , 1 ], + # [2 , 3 ], + # [4 , 5 ], + # [6 , 7 ]], + # + # [4 , 5 ], + # [6 , 7 ], + # [8 , 9 ], + # [10, 11]], + # + # [8 , 9 ], + # [10, 11], + # [12, 13], + # [14, 15]]] + + # > 2D + x0 = paddle.arange(32).reshape([2, 2, 8]) + y0 = frame(x0, frame_length=4, hop_length=2, axis=-1) # [2, 2, 4, 3] + + x1 = paddle.arange(32).reshape([8, 2, 2]) + y1 = frame(x1, frame_length=4, hop_length=2, axis=0) # [3, 4, 2, 2] + """ + if axis not in [0, -1]: + raise ValueError(f'Unexpected axis: {axis}. It should be 0 or -1.') + + if not isinstance(frame_length, int) or frame_length <= 0: + raise ValueError( + f'Unexpected frame_length: {frame_length}. It should be an positive integer.' + ) + + if not isinstance(hop_length, int) or hop_length <= 0: + raise ValueError( + f'Unexpected hop_length: {hop_length}. It should be an positive integer.' + ) + + if _non_static_mode(): + if frame_length > x.shape[axis]: + raise ValueError( + f'Attribute frame_length should be less equal than sequence length, ' + f'but got ({frame_length}) > ({x.shape[axis]}).' + ) + + op_type = 'frame' + + if in_dygraph_mode(): + return _C_ops.frame(x, frame_length, hop_length, axis) + + if _in_legacy_dygraph(): + attrs = ( + 'frame_length', + frame_length, + 'hop_length', + hop_length, + 'axis', + axis, + ) + op = getattr(_legacy_C_ops, op_type) + out = op(x, *attrs) + else: + check_variable_and_dtype( + x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], op_type + ) + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op( + type=op_type, + inputs={'X': x}, + attrs={ + 'frame_length': frame_length, + 'hop_length': hop_length, + 'axis': axis, + }, + outputs={'Out': out}, + ) + return out + + +def overlap_add(x, hop_length, axis=-1, name=None): + """ + Reconstructs a tensor consisted of overlap added sequences from input frames. + + Args: + x (Tensor): The input data which is a N-dimensional (where N >= 2) Tensor + with shape `[..., frame_length, num_frames]` or + `[num_frames, frame_length ...]`. + hop_length (int): Number of steps to advance between adjacent frames and + `0 < hop_length <= frame_length`. + axis (int, optional): Specify the axis to operate on the input Tensors. Its + value should be 0(the first dimension) or -1(the last dimension). If not + specified, the last axis is used by default. + + Returns: + The output frames tensor with shape `[..., seq_length]` if `axis==-1`, + otherwise `[seq_length, ...]` where + + `seq_length = (n_frames - 1) * hop_length + frame_length` + + Examples: + + .. code-block:: python + + import paddle + from paddle.signal import overlap_add + + # 2D + x0 = paddle.arange(16).reshape([8, 2]) + # [[0 , 1 ], + # [2 , 3 ], + # [4 , 5 ], + # [6 , 7 ], + # [8 , 9 ], + # [10, 11], + # [12, 13], + # [14, 15]] + y0 = overlap_add(x0, hop_length=2, axis=-1) # [10] + # [0 , 2 , 5 , 9 , 13, 17, 21, 25, 13, 15] + + x1 = paddle.arange(16).reshape([2, 8]) + # [[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ], + # [8 , 9 , 10, 11, 12, 13, 14, 15]] + y1 = overlap_add(x1, hop_length=2, axis=0) # [10] + # [0 , 1 , 10, 12, 14, 16, 18, 20, 14, 15] + + # > 2D + x0 = paddle.arange(32).reshape([2, 1, 8, 2]) + y0 = overlap_add(x0, hop_length=2, axis=-1) # [2, 1, 10] + + x1 = paddle.arange(32).reshape([2, 8, 1, 2]) + y1 = overlap_add(x1, hop_length=2, axis=0) # [10, 1, 2] + """ + if axis not in [0, -1]: + raise ValueError(f'Unexpected axis: {axis}. It should be 0 or -1.') + + if not isinstance(hop_length, int) or hop_length <= 0: + raise ValueError( + f'Unexpected hop_length: {hop_length}. It should be an positive integer.' + ) + + op_type = 'overlap_add' + + if in_dygraph_mode(): + out = _C_ops.overlap_add(x, hop_length, axis) + elif paddle.in_dynamic_mode(): + attrs = ('hop_length', hop_length, 'axis', axis) + op = getattr(_legacy_C_ops, op_type) + out = op(x, *attrs) + else: + check_variable_and_dtype( + x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], op_type + ) + helper = LayerHelper(op_type, **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op( + type=op_type, + inputs={'X': x}, + attrs={'hop_length': hop_length, 'axis': axis}, + outputs={'Out': out}, + ) + return out + + +def stft( + x, + n_fft, + hop_length=None, + win_length=None, + window=None, + center=True, + pad_mode='reflect', + normalized=False, + onesided=True, + name=None, +): + r""" + + Short-time Fourier transform (STFT). + + The STFT computes the discrete Fourier transforms (DFT) of short overlapping + windows of the input using this formula: + + .. math:: + X_t[\omega] = \sum_{n = 0}^{N-1}% + \text{window}[n]\ x[t \times H + n]\ % + e^{-{2 \pi j \omega n}/{N}} + + Where: + - :math:`t`: The :math:`t`-th input window. + + - :math:`\omega`: Frequency :math:`0 \leq \omega < \text{n\_fft}` for `onesided=False`, + or :math:`0 \leq \omega < \lfloor \text{n\_fft} / 2 \rfloor + 1` for `onesided=True`. + + - :math:`N`: Value of `n_fft`. + + - :math:`H`: Value of `hop_length`. + + Args: + x (Tensor): The input data which is a 1-dimensional or 2-dimensional Tensor with + shape `[..., seq_length]`. It can be a real-valued or a complex Tensor. + n_fft (int): The number of input samples to perform Fourier transform. + hop_length (int, optional): Number of steps to advance between adjacent windows + and `0 < hop_length`. Default: `None`(treated as equal to `n_fft//4`) + win_length (int, optional): The size of window. Default: `None`(treated as equal + to `n_fft`) + window (Tensor, optional): A 1-dimensional tensor of size `win_length`. It will + be center padded to length `n_fft` if `win_length < n_fft`. Default: `None`( + treated as a rectangle window with value equal to 1 of size `win_length`). + center (bool, optional): Whether to pad `x` to make that the + :math:`t \times hop\_length` at the center of :math:`t`-th frame. Default: `True`. + pad_mode (str, optional): Choose padding pattern when `center` is `True`. See + `paddle.nn.functional.pad` for all padding options. Default: `"reflect"` + normalized (bool, optional): Control whether to scale the output by `1/sqrt(n_fft)`. + Default: `False` + onesided (bool, optional): Control whether to return half of the Fourier transform + output that satisfies the conjugate symmetry condition when input is a real-valued + tensor. It can not be `True` if input is a complex tensor. Default: `True` + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + The complex STFT output tensor with shape `[..., n_fft//2 + 1, num_frames]` + (real-valued input and `onesided` is `True`) or `[..., n_fft, num_frames]` + (`onesided` is `False`) + + Examples: + .. code-block:: python + + import paddle + from paddle.signal import stft + + # real-valued input + x = paddle.randn([8, 48000], dtype=paddle.float64) + y1 = stft(x, n_fft=512) # [8, 257, 376] + y2 = stft(x, n_fft=512, onesided=False) # [8, 512, 376] + + # complex input + x = paddle.randn([8, 48000], dtype=paddle.float64) + \ + paddle.randn([8, 48000], dtype=paddle.float64)*1j # [8, 48000] complex128 + y1 = stft(x, n_fft=512, center=False, onesided=False) # [8, 512, 372] + + """ + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'complex64', 'complex128'], 'stft' + ) + + x_rank = len(x.shape) + assert x_rank in [ + 1, + 2, + ], f'x should be a 1D or 2D real tensor, but got rank of x is {x_rank}' + + if x_rank == 1: # (batch, seq_length) + x = x.unsqueeze(0) + + if hop_length is None: + hop_length = int(n_fft // 4) + + assert hop_length > 0, f'hop_length should be > 0, but got {hop_length}.' + + if win_length is None: + win_length = n_fft + + if _non_static_mode(): + assert ( + 0 < n_fft <= x.shape[-1] + ), f'n_fft should be in (0, seq_length({x.shape[-1]})], but got {n_fft}.' + + assert ( + 0 < win_length <= n_fft + ), f'win_length should be in (0, n_fft({n_fft})], but got {win_length}.' + + if window is not None: + assert ( + len(window.shape) == 1 and len(window) == win_length + ), f'expected a 1D window tensor of size equal to win_length({win_length}), but got window with shape {window.shape}.' + else: + window = paddle.ones(shape=(win_length,), dtype=x.dtype) + + if win_length < n_fft: + pad_left = (n_fft - win_length) // 2 + pad_right = n_fft - win_length - pad_left + window = paddle.nn.functional.pad( + window, pad=[pad_left, pad_right], mode='constant' + ) + + if center: + assert pad_mode in [ + 'constant', + 'reflect', + ], 'pad_mode should be "reflect" or "constant", but got "{}".'.format( + pad_mode + ) + + pad_length = n_fft // 2 + # FIXME: Input `x` can be a complex tensor but pad does not supprt complex input. + x = paddle.nn.functional.pad( + x.unsqueeze(-1), + pad=[pad_length, pad_length], + mode=pad_mode, + data_format="NLC", + ).squeeze(-1) + + x_frames = frame(x=x, frame_length=n_fft, hop_length=hop_length, axis=-1) + x_frames = x_frames.transpose( + perm=[0, 2, 1] + ) # switch n_fft to last dim, egs: (batch, num_frames, n_fft) + x_frames = paddle.multiply(x_frames, window) + + norm = 'ortho' if normalized else 'backward' + if is_complex(x_frames): + assert ( + not onesided + ), 'onesided should be False when input or window is a complex Tensor.' + + if not is_complex(x): + out = fft_r2c( + x=x_frames, + n=None, + axis=-1, + norm=norm, + forward=True, + onesided=onesided, + name=name, + ) + else: + out = fft_c2c( + x=x_frames, n=None, axis=-1, norm=norm, forward=True, name=name + ) + + out = out.transpose(perm=[0, 2, 1]) # (batch, n_fft, num_frames) + + if x_rank == 1: + out.squeeze_(0) + + return out + + +def istft( + x, + n_fft, + hop_length=None, + win_length=None, + window=None, + center=True, + normalized=False, + onesided=True, + length=None, + return_complex=False, + name=None, +): + r""" + Inverse short-time Fourier transform (ISTFT). + + Reconstruct time-domain signal from the giving complex input and window tensor when + nonzero overlap-add (NOLA) condition is met: + + .. math:: + \sum_{t = -\infty}^{\infty}% + \text{window}^2[n - t \times H]\ \neq \ 0, \ \text{for } all \ n + + Where: + - :math:`t`: The :math:`t`-th input window. + - :math:`N`: Value of `n_fft`. + - :math:`H`: Value of `hop_length`. + + Result of `istft` expected to be the inverse of `paddle.signal.stft`, but it is + not guaranteed to reconstruct a exactly realizible time-domain signal from a STFT + complex tensor which has been modified (via masking or otherwise). Therefore, `istft` + gives the [Griffin-Lim optimal estimate](https://ieeexplore.ieee.org/document/1164317) + (optimal in a least-squares sense) for the corresponding signal. + + Args: + x (Tensor): The input data which is a 2-dimensional or 3-dimensional **complesx** + Tensor with shape `[..., n_fft, num_frames]`. + n_fft (int): The size of Fourier transform. + hop_length (int, optional): Number of steps to advance between adjacent windows + from time-domain signal and `0 < hop_length < win_length`. Default: `None`( + treated as equal to `n_fft//4`) + win_length (int, optional): The size of window. Default: `None`(treated as equal + to `n_fft`) + window (Tensor, optional): A 1-dimensional tensor of size `win_length`. It will + be center padded to length `n_fft` if `win_length < n_fft`. It should be a + real-valued tensor if `return_complex` is False. Default: `None`(treated as + a rectangle window with value equal to 1 of size `win_length`). + center (bool, optional): It means that whether the time-domain signal has been + center padded. Default: `True`. + normalized (bool, optional): Control whether to scale the output by `1/sqrt(n_fft)`. + Default: `False` + onesided (bool, optional): It means that whether the input STFT tensor is a half + of the conjugate symmetry STFT tensor transformed from a real-valued signal + and `istft` will return a real-valued tensor when it is set to `True`. + Default: `True`. + length (int, optional): Specify the length of time-domain signal. Default: `None`( + treated as the whole length of signal). + return_complex (bool, optional): It means that whether the time-domain signal is + real-valued. If `return_complex` is set to `True`, `onesided` should be set to + `False` cause the output is complex. + name (str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A tensor of least squares estimation of the reconstructed signal(s) with shape + `[..., seq_length]` + + Examples: + .. code-block:: python + + import numpy as np + import paddle + from paddle.signal import stft, istft + + paddle.seed(0) + + # STFT + x = paddle.randn([8, 48000], dtype=paddle.float64) + y = stft(x, n_fft=512) # [8, 257, 376] + + # ISTFT + x_ = istft(y, n_fft=512) # [8, 48000] + + np.allclose(x, x_) # True + """ + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'istft') + + x_rank = len(x.shape) + assert x_rank in [ + 2, + 3, + ], 'x should be a 2D or 3D complex tensor, but got rank of x is {}'.format( + x_rank + ) + + if x_rank == 2: # (batch, n_fft, n_frames) + x = x.unsqueeze(0) + + if hop_length is None: + hop_length = int(n_fft // 4) + + if win_length is None: + win_length = n_fft + + # Assure no gaps between frames. + assert ( + 0 < hop_length <= win_length + ), 'hop_length should be in (0, win_length({})], but got {}.'.format( + win_length, hop_length + ) + + assert ( + 0 < win_length <= n_fft + ), 'win_length should be in (0, n_fft({})], but got {}.'.format( + n_fft, win_length + ) + + n_frames = x.shape[-1] + fft_size = x.shape[-2] + + if _non_static_mode(): + if onesided: + assert ( + fft_size == n_fft // 2 + 1 + ), 'fft_size should be equal to n_fft // 2 + 1({}) when onesided is True, but got {}.'.format( + n_fft // 2 + 1, fft_size + ) + else: + assert ( + fft_size == n_fft + ), 'fft_size should be equal to n_fft({}) when onesided is False, but got {}.'.format( + n_fft, fft_size + ) + + if window is not None: + assert ( + len(window.shape) == 1 and len(window) == win_length + ), 'expected a 1D window tensor of size equal to win_length({}), but got window with shape {}.'.format( + win_length, window.shape + ) + else: + window_dtype = ( + paddle.float32 + if x.dtype in [paddle.float32, paddle.complex64] + else paddle.float64 + ) + window = paddle.ones(shape=(win_length,), dtype=window_dtype) + + if win_length < n_fft: + pad_left = (n_fft - win_length) // 2 + pad_right = n_fft - win_length - pad_left + # FIXME: Input `window` can be a complex tensor but pad does not supprt complex input. + window = paddle.nn.functional.pad( + window, pad=[pad_left, pad_right], mode='constant' + ) + + x = x.transpose( + perm=[0, 2, 1] + ) # switch n_fft to last dim, egs: (batch, num_frames, n_fft) + norm = 'ortho' if normalized else 'backward' + + if return_complex: + assert ( + not onesided + ), 'onesided should be False when input(output of istft) or window is a complex Tensor.' + + out = fft_c2c(x=x, n=None, axis=-1, norm=norm, forward=False, name=None) + else: + assert not is_complex( + window + ), 'Data type of window should not be complex when return_complex is False.' + + if onesided is False: + x = x[:, :, : n_fft // 2 + 1] + out = fft_c2r(x=x, n=None, axis=-1, norm=norm, forward=False, name=None) + + out = paddle.multiply(out, window).transpose( + perm=[0, 2, 1] + ) # (batch, n_fft, num_frames) + out = overlap_add( + x=out, hop_length=hop_length, axis=-1 + ) # (batch, seq_length) + + window_envelop = overlap_add( + x=paddle.tile( + x=paddle.multiply(window, window).unsqueeze(0), + repeat_times=[n_frames, 1], + ).transpose( + perm=[1, 0] + ), # (n_fft, num_frames) + hop_length=hop_length, + axis=-1, + ) # (seq_length, ) + + if length is None: + if center: + out = out[:, (n_fft // 2) : -(n_fft // 2)] + window_envelop = window_envelop[(n_fft // 2) : -(n_fft // 2)] + else: + if center: + start = n_fft // 2 + else: + start = 0 + + out = out[:, start : start + length] + window_envelop = window_envelop[start : start + length] + + # Check whether the Nonzero Overlap Add (NOLA) constraint is met. + if _non_static_mode() and window_envelop.abs().min().item() < 1e-11: + raise ValueError( + 'Abort istft because Nonzero Overlap Add (NOLA) condition failed. For more information about NOLA constraint please see `scipy.signal.check_NOLA`(https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.check_NOLA.html).' + ) + + out = out / window_envelop + + if x_rank == 2: + out.squeeze_(0) + + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ca932ac46b6ada15d338b2018c2716a7a25efcb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/__init__.py @@ -0,0 +1,86 @@ +# Copyright (c) 2022 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. + +from .creation import sparse_coo_tensor +from .creation import sparse_csr_tensor + +from .unary import sin +from .unary import tan +from .unary import asin +from .unary import atan +from .unary import sinh +from .unary import tanh +from .unary import asinh +from .unary import atanh +from .unary import sqrt +from .unary import square +from .unary import log1p +from .unary import abs +from .unary import pow +from .unary import cast +from .unary import neg +from .unary import coalesce +from .unary import deg2rad +from .unary import rad2deg +from .unary import expm1 +from .unary import transpose +from .unary import reshape + +from .binary import mv +from .binary import matmul +from .binary import masked_matmul +from .binary import add +from .binary import divide +from .binary import multiply +from .binary import subtract +from .binary import is_same_shape + +from .multiary import addmm + +from . import nn + +__all__ = [ + 'sparse_coo_tensor', + 'sparse_csr_tensor', + 'sin', + 'tan', + 'asin', + 'atan', + 'sinh', + 'tanh', + 'asinh', + 'atanh', + 'sqrt', + 'square', + 'log1p', + 'abs', + 'pow', + 'cast', + 'neg', + 'deg2rad', + 'rad2deg', + 'expm1', + 'mv', + 'matmul', + 'masked_matmul', + 'addmm', + 'add', + 'subtract', + 'transpose', + 'multiply', + 'divide', + 'coalesce', + 'is_same_shape', + 'reshape', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/binary.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2a3af8ec83b0052b763cf4cb7eb67c5b813886 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/binary.py @@ -0,0 +1,443 @@ +# Copyright (c) 2022 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. + +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import dygraph_only, core +from paddle import in_dynamic_mode +from paddle.fluid.layer_helper import LayerHelper +from .unary import cast + +__all__ = [] + +_int_dtype_ = [ + core.VarDesc.VarType.UINT8, + core.VarDesc.VarType.INT8, + core.VarDesc.VarType.INT16, + core.VarDesc.VarType.INT32, + core.VarDesc.VarType.INT64, + core.VarDesc.VarType.BOOL, +] + + +@dygraph_only +def matmul(x, y, name=None): + """ + Note: + This API is only supported from ``CUDA 11.0`` . + + Applies matrix multiplication of two Tensors. + + The supported input/output Tensor layout are as follows: + + Note: + x[SparseCsrTensor] @ y[SparseCsrTensor] -> out[SparseCsrTensor] + x[SparseCsrTensor] @ y[DenseTensor] -> out[DenseTensor] + x[SparseCooTensor] @ y[SparseCooTensor] -> out[SparseCooTensor] + x[SparseCooTensor] @ y[DenseTensor] -> out[DenseTensor] + + It supports backward propagation. + + Dimensions `x` and `y` must be >= 2D. Automatic broadcasting of Tensor is not supported. + the shape of `x` should be `[*, M, K]` , and the shape of `y` should be `[*, K, N]` , where `*` + is zero or more batch dimensions. + + Args: + x (Tensor): The input tensor. It can be SparseCooTensor/SparseCsrTensor. The data type can be float32 or float64. + y (Tensor): The input tensor. It can be SparseCooTensor/SparseCsrTensor/DenseTensor. The data type can be float32 or float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Its layout is determined by that of `x` and `y` . + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + # csr @ dense -> dense + crows = [0, 1, 2, 3] + cols = [1, 2, 0] + values = [1., 2., 3.] + csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, [3, 3]) + # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 1, 2, 3], + # cols=[1, 2, 0], + # values=[1., 2., 3.]) + dense = paddle.ones([3, 2]) + out = paddle.sparse.matmul(csr, dense) + # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1., 1.], + # [2., 2.], + # [3., 3.]]) + + # coo @ dense -> dense + indices = [[0, 1, 2], [1, 2, 0]] + values = [1., 2., 3.] + coo = paddle.sparse.sparse_coo_tensor(indices, values, [3, 3]) + # Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # indices=[[0, 1, 2], + # [1, 2, 0]], + # values=[1., 2., 3.]) + dense = paddle.ones([3, 2]) + out = paddle.sparse.matmul(coo, dense) + # Tensor(shape=[3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[1., 1.], + # [2., 2.], + # [3., 3.]]) + """ + return _C_ops.sparse_matmul(x, y) + + +@dygraph_only +def masked_matmul(x, y, mask, name=None): + """ + Note: + This API is only supported from ``CUDA 11.3`` . + + Applies matrix multiplication of two Dense Tensors. + + The supported input/output Tensor layout are as follows: + + Note: + x[DenseTensor] @ y[DenseTensor] * mask[SparseCooTensor] -> out[SparseCooTensor] + x[DenseTensor] @ y[DenseTensor] * mask[SparseCsrTensor] -> out[SparseCsrTensor] + + It supports backward propagation. + + Dimensions `x` and `y` must be >= 2D. Automatic broadcasting of Tensor is not supported. + the shape of `x` should be `[*, M, K]` , and the shape of `y` should be `[*, K, N]` , and the shape of `mask` should be `[*, M, N]` , + where `*` is zero or more batch dimensions. + + Args: + x (Tensor): The input tensor. It is DenseTensor. The data type can be float32 or float64. + y (Tensor): The input tensor. It is DenseTensor. The data type can be float32 or float64. + mask (Tensor): The mask tensor, which can be SparseCooTensor/SparseCsrTensor. It specify sparse coordinates. The data type can be float32 or float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: SparseCoo or SparseCsr, which is determined by that of `mask` . + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + paddle.seed(100) + + # dense @ dense * csr_mask -> csr + crows = [0, 2, 3, 5] + cols = [1, 3, 2, 0, 1] + values = [1., 2., 3., 4., 5.] + dense_shape = [3, 4] + mask = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape) + # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 3, 5], + # cols=[1, 3, 2, 0, 1], + # values=[1., 2., 3., 4., 5.]) + + x = paddle.rand([3, 5]) + y = paddle.rand([5, 4]) + + out = paddle.sparse.masked_matmul(x, y, mask) + # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 3, 5], + # cols=[1, 3, 2, 0, 1], + # values=[0.98986477, 0.97800624, 1.14591956, 0.68561077, 0.94714981]) + + """ + return _C_ops.sparse_masked_matmul(x, y, mask) + + +@dygraph_only +def mv(x, vec, name=None): + """ + Note: + This API is only supported from ``CUDA 11.0`` . + + Applies matrix-vector product of Sparse Matrix 'x' and Dense vector 'vec' . + + The supported input/output Tensor layout are as follows: + + Note: + x[SparseCsrTensor] @ y[DenseTensor] -> out[SparseCsrTensor] + x[SparseCooTensor] @ y[DenseTensor] -> out[SparseCooTensor] + + It supports backward propagation. + + The shape of `x` should be `[M, N]` , and the shape of `y` should be `[N]` , + and the shape of `out` will be `[M]` . + + Args: + x (Tensor): The input 2D tensor. It must be SparseCooTensor/SparseCsrTensor. The data type can be float32 or float64. + y (Tensor): The input 1D tensor. It must be DenseTensor vector. The data type can be float32 or float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: 1D Tensor. + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + from paddle.fluid.framework import _test_eager_guard + paddle.seed(100) + + # csr @ dense -> dense + with _test_eager_guard(): + crows = [0, 2, 3, 5] + cols = [1, 3, 2, 0, 1] + values = [1., 2., 3., 4., 5.] + dense_shape = [3, 4] + csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape) + # Tensor(shape=[3, 4], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 3, 5], + # cols=[1, 3, 2, 0, 1], + # values=[1., 2., 3., 4., 5.]) + vec = paddle.randn([4]) + + out = paddle.sparse.mv(csr, vec) + # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [-3.85499096, -2.42975140, -1.75087738]) + + """ + return _C_ops.sparse_mv(x, vec) + + +def add(x, y, name=None): + """ + Add two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse + type(SparseCooTensor or SparseCsrTensor).If input is SparseCooTensor, x and y's sparse_dim should be identical. + The equation is: + + .. math:: + out = x + y + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: the result tensor. + + Examples: + + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + + x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32') + y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32') + sparse_x = x.to_sparse_csr() + sparse_y = y.to_sparse_csr() + sparse_z = paddle.sparse.add(sparse_x, sparse_y) + print(sparse_z.to_dense()) + + # [[ 0., -1., 0., 0.], + # [ 0., 2., -6., 0.], + # [ 6., 8., 4., 8.]] + + """ + if y.dtype != x.dtype: + y = cast(y, None, x.dtype) + + if in_dynamic_mode(): + return _C_ops.sparse_add(x, y) + else: + op_type = 'sparse_add' + inputs = {'x': x, 'y': y} + helper = LayerHelper(op_type) + out = helper.create_sparse_variable_for_type_inference(x.dtype) + helper.append_op( + type=op_type, inputs=inputs, outputs={'out': out}, attrs={} + ) + return out + + +@dygraph_only +def subtract(x, y, name=None): + """ + Subtract two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse + type(SparseCooTensor or SparseCsrTensor).If input is SparseCooTensor, x and y's sparse_dim should be identical. + The equation is: + + .. math:: + out = x - y + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: the result tensor. + + Examples: + + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + + x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32') + y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32') + sparse_x = x.to_sparse_csr() + sparse_y = y.to_sparse_csr() + sparse_z = paddle.sparse.subtract(sparse_x, sparse_y) + print(sparse_z.to_dense()) + + # [[ 0., -1., 0., 4.], + # [ 0., -2., 0., 0.], + # [ 2., 2., -4., -8.]] + + """ + if y.dtype != x.dtype: + y = _C_ops.sparse_cast(y, None, x.dtype) + return _C_ops.sparse_subtract(x, y) + + +@dygraph_only +def multiply(x, y, name=None): + """ + Multiply two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse + type(SparseCooTensor or SparseCsrTensor).If input is SparseCooTensor, x and y's sparse_dim should be identical. + The equation is: + + .. math:: + out = x * y + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: the result tensor. + + Examples: + + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + + x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32') + y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32') + sparse_x = x.to_sparse_csr() + sparse_y = y.to_sparse_csr() + sparse_z = paddle.sparse.multiply(sparse_x, sparse_y) + print(sparse_z.to_dense()) + + # [[ 0., 0., 0., -4.], + # [ 0., 0., 9., 0.], + # [ 8., 15., 0., 0.]] + + """ + if isinstance(y, (int, float)): + return _C_ops.sparse_scale(x, float(y), 0.0, True) + else: + if y.dtype != x.dtype: + y = _C_ops.sparse_cast(y, None, x.dtype) + return _C_ops.sparse_multiply(x, y) + + +@dygraph_only +def divide(x, y, name=None): + """ + Divide two sparse tensors element-wise. Input x and y's shape should be identical and have same sparse + type(SparseCooTensor or SparseCsrTensor).If input is SparseCooTensor, x and y's sparse_dim should be identical. + The equation is: + + .. math:: + out = x / y + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: the result tensor. + + Examples: + + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + + x = paddle.to_tensor([[0, -1, 0, 2], [0, 0, -3, 0], [4, 5, 0, 0]], 'float32') + y = paddle.to_tensor([[0, 0, 0, -2], [0, 2, -3, 0], [2, 3, 4, 8]], 'float32') + sparse_x = x.to_sparse_csr() + sparse_y = y.to_sparse_csr() + sparse_z = paddle.sparse.divide(sparse_x, sparse_y) + print(sparse_z.to_dense()) + + # [[ nan , -inf. , nan , -1. ], + # [ nan , 0. , 1. , nan ], + # [ 2. , 1.66666663, 0. , 0. ]] + + """ + if x.dtype in _int_dtype_: + x = _C_ops.sparse_cast(x, None, core.VarDesc.VarType.FP32) + + if isinstance(y, (int, float)): + return _C_ops.sparse_divide_scalar(x, float(y)) + else: + if y.dtype != x.dtype: + y = _C_ops.sparse_cast(y, None, x.dtype) + return _C_ops.sparse_divide(x, y) + + +@dygraph_only +def is_same_shape(x, y): + """ + Return the results of shape comparison between two Tensors, check whether x.shape equal to y.shape. + Any two type Tensor among DenseTensor/SparseCooTensor/SparseCsrTensor are supported. + + Args: + x (Tensor): The input tensor. It can be DenseTensor/SparseCooTensor/SparseCsrTensor. + y (Tensor): The input tensor. It can be DenseTensor/SparseCooTensor/SparseCsrTensor. + + Returns: + bool: True for same shape and False for different shape. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand([2, 3, 8]) + y = paddle.rand([2, 3, 8]) + y = y.to_sparse_csr() + z = paddle.rand([2, 5]) + + paddle.sparse.is_same_shape(x, y) + # True + paddle.sparse.is_same_shape(x, z) + # False + + """ + return x.is_same_shape(y) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/creation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/creation.py new file mode 100644 index 0000000000000000000000000000000000000000..6258f6e05a76c0af024d84b460f707bfc593677e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/creation.py @@ -0,0 +1,299 @@ +# Copyright (c) 2022 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. + +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import core, dygraph_only +from paddle.fluid.framework import _current_expected_place, _get_paddle_place +from paddle.tensor import to_tensor, max +from paddle.fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, + convert_dtype, +) +from paddle import in_dynamic_mode +from paddle.fluid.layer_helper import LayerHelper + +import numpy as np + +__all__ = [ + 'sparse_coo_tensor', + 'sparse_csr_tensor', +] + + +def _handle_dtype(data, dtype): + if dtype: + if convert_dtype(dtype) != convert_dtype(data.dtype): + return data.astype(convert_dtype(dtype)) + return data + + +def _infer_dense_shape(indices, values): + assert len(indices.shape) == 2 + lens = max(indices, axis=1) + lens = lens + 1 + lens = lens.numpy() + if len(values.shape) > 1: + lens = np.append(lens, values.shape[1:]) + return list(lens) + + +def _get_place(place): + place = _get_paddle_place(place) + if place is None: + place = _current_expected_place() + elif not isinstance( + place, (core.Place, core.CPUPlace, core.CUDAPinnedPlace, core.CUDAPlace) + ): + raise ValueError( + "'place' must be any of paddle.Place, paddle.CPUPlace, paddle.CUDAPinnedPlace, paddle.CUDAPlace" + ) + return place + + +def _check_indices_dtype(dtype): + if dtype not in [paddle.int8, paddle.int16, paddle.int32, paddle.int64]: + raise TypeError( + "the dtype of indices must be 'int8' or 'int16' or 'int32' or 'int64'" + ) + + +def sparse_coo_tensor( + indices, values, shape=None, dtype=None, place=None, stop_gradient=True +): + r""" + Constructs a sparse ``paddle.Tensor`` in coordinate format according to the indices + and values of the specified non-zero elements. + + Args: + indices(list|tuple|ndarray|Tensor): the indices of non-zero elements. + Can be a list, tuple, numpy\.ndarray, paddle\.Tensor. The indices must be 2-D. + values(list|tuple|ndarray|Tensor): Initial values for the tensor. + Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor. + shape(list|tuple, optional): The shape of the sparse tensor also represents the shape of + original dense tensor. If not provided the smallest shape will be inferred to + hold all elements. + dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' , + 'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8', + 'complex64' , 'complex128'. Default: None, infers dtype from ``data`` + except for python float number which gets dtype from ``get_default_type`` . + place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be + CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is + string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs. + stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True. + + Returns: + Tensor: A Tensor constructed from ``indices`` and ``values`` . + + Examples: + + .. code-block:: python + + import paddle + + indices = [[0, 1, 2], [1, 2, 0]] + values = [1.0, 2.0, 3.0] + dense_shape = [3, 3] + coo = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape) + # print(coo) + # Tensor(shape=[2, 3], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # indices=[[0, 1, 2], + # [1, 2, 0]], + # values=[1., 2., 3.]) + """ + + if in_dynamic_mode(): + place = _get_place(place) + + if not isinstance(indices, core.eager.Tensor): + indices = to_tensor( + indices, dtype=None, place=place, stop_gradient=True + ) + if not isinstance(values, core.eager.Tensor): + values = to_tensor(values, dtype, place, stop_gradient) + if len(indices.shape) != 2: + raise ValueError("'indices' must be 2-D.") + + nnz = indices.shape[1] + sparse_dim = indices.shape[0] + + _check_indices_dtype(indices.dtype) + + if nnz != values.shape[0]: + raise ValueError( + "the indices and values must have same number of non-zero, but get {} and {}".format( + nnz, values.shape[0] + ) + ) + + dense_dim = len(values.shape) - 1 + + if not indices.place._equals(place): + indices = indices._copy_to(place, False) + + if not values.place._equals(place): + values = values._copy_to(place, False) + values = _handle_dtype(values, dtype) + values.stop_gradient = stop_gradient + + min_shape = _infer_dense_shape(indices, values) + + if shape is None: + shape = min_shape + else: + if shape < min_shape: + raise ValueError( + "the minimun shape required is {}, but get {}".format( + min_shape, shape + ) + ) + if len(shape) != sparse_dim + dense_dim: + raise ValueError( + "the number of dimensions(len(shape) must be sparse_dim({}) + dense_dim({}), but get {}".format( + sparse_dim, dense_dim, len(shape) + ) + ) + + return _C_ops.sparse_sparse_coo_tensor(values, indices, shape) + + else: + op_type = 'sparse_sparse_coo_tensor' + inputs = {'values': values, 'indices': indices} + if shape[0] is None: + shape[0] = -1 + attrs = {'shape': shape} + helper = LayerHelper(op_type) + out = helper.create_sparse_variable_for_type_inference(dtype) + helper.append_op( + type=op_type, inputs=inputs, outputs={'out': out}, attrs=attrs + ) + return out + + +# TODO: need to support shape is None +@dygraph_only +def sparse_csr_tensor( + crows, cols, values, shape, dtype=None, place=None, stop_gradient=True +): + r""" + Constructs a sparse ``paddle.Tensor`` in CSR(Compressed Sparse Row) format according to the + ``crows``, ``cols`` and ``values``. + Currently, the crows and cols of each batch must be incrementd. + + Args: + crows(list|tuple|ndarray|Tensor): 1-D array, each element in the rows represents the + starting position of the first non-zero element of each row in values. + Can be a list, tuple, numpy\.ndarray, paddle\.Tensor. + cols(list|tuple|ndarray|Tensor): 1-D array, the column of non-zero elements. + Can be a list, tuple, numpy\.ndarray, paddle\.Tensor. + values(list|tuple|ndarray|Tensor): 1-D array, the non-zero elements. + Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor. + shape(list|tuple, optional): The shape of the sparse tensor also represents the shape of + original dense tensor. + hold all elements. + dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' , + 'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8', + 'complex64' , 'complex128'. Default: None, infers dtype from ``data`` + except for python float number which gets dtype from ``get_default_type`` . + place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be + CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is + string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs. + stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True. + + Returns: + Tensor: A Tensor constructed from ``crows``, ``cols`` and ``values`` . + + Examples: + + .. code-block:: python + + import paddle + + crows = [0, 2, 3, 5] + cols = [1, 3, 2, 0, 1] + values = [1, 2, 3, 4, 5] + dense_shape = [3, 4] + csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape) + # print(csr) + # Tensor(shape=[3, 4], dtype=paddle.int64, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 3, 5], + # cols=[1, 3, 2, 0, 1], + # values=[1, 2, 3, 4, 5]) + """ + + place = _get_place(place) + + if not isinstance(crows, core.eager.Tensor): + crows = to_tensor(crows, dtype=None, place=place, stop_gradient=True) + if not isinstance(cols, core.eager.Tensor): + cols = to_tensor(cols, dtype=None, place=place, stop_gradient=True) + if not isinstance(values, core.eager.Tensor): + values = to_tensor(values, dtype, place, stop_gradient) + + _check_indices_dtype(crows.dtype) + _check_indices_dtype(cols.dtype) + + if len(shape) != 2 and len(shape) != 3: + raise ValueError( + "SparseCsrTensor only support 2-D or 3-D matrix. but get shape {}".format( + shape + ) + ) + rows = shape[len(shape) - 2] + + if not crows.place._equals(place): + crows = crows._copy_to(place, False) + + if not cols.place._equals(place): + cols = cols._copy_to(place, False) + + if not values.place._equals(place): + values = values._copy_to(place, False) + values = _handle_dtype(values, dtype) + values.stop_gradient = stop_gradient + + if len(crows.shape) != 1 or len(cols.shape) != 1 or len(values.shape) != 1: + raise ValueError("The 'crows', 'cols' and 'values' must be 1-D.") + + if len(cols) != len(values): + raise ValueError("the length of cols must be same as length of values") + + if len(shape) == 2: + if crows.shape[0] != rows + 1: + raise ValueError( + "The length({}) of crows must be equal to the rows({})+1 of matrix.".format( + crows.shape[0], rows + ) + ) + if crows[0] != 0: + raise ValueError("the 0th value of crows must be 0") + + if crows[-1] != values.shape[0]: + raise ValueError( + "the last value of crows must be equal the number of non-zero" + ) + else: + if crows.shape[0] % (rows + 1) != 0: + raise ValueError( + "The length({}) of crows must be divisible the rows({})+1 of matrix.".format( + crows.shape[0], rows + ) + ) + # TODO(zkh2016): check whether the value in crows and cols is legal + + return core.eager.sparse_csr_tensor( + crows, cols, values, shape, stop_gradient + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/multiary.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/multiary.py new file mode 100644 index 0000000000000000000000000000000000000000..9874b8279135a47c06c195aaf23401af657025e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/multiary.py @@ -0,0 +1,82 @@ +# Copyright (c) 2022 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. + +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import dygraph_only + +__all__ = [] + + +@dygraph_only +def addmm(input, x, y, beta=1.0, alpha=1.0, name=None): + """ + Note: + This API is only supported from ``CUDA 11.0`` . + + Applies matrix multiplication for `x` and `y` , `input` is added to + the final result. The equation is: + + .. math:: + + Out = alpha * x * y + beta * input + + The supported input/output Tensor layout are as follows: + + Note: + input[SparseCsrTensor] + x[SparseCsrTensor] @ y[SparseCsrTensor] -> out[SparseCsrTensor] + input[DenseTensor] + x[SparseCsrTensor] @ y[DenseTensor] -> out[DenseTensor] + input[SparseCooTensor] + x[SparseCooTensor] @ y[SparseCooTensor] -> out[SparseCooTensor] + input[DenseTensor] + x[SparseCooTensor] @ y[DenseTensor] -> out[DenseTensor] + + It supports backward propagation. + + Dimensions `input` , `x` , `y` must be same and >= 2D. Automatic broadcasting of Tensor is not supported. + + Args: + input (Tensor): The input tensor. Shape is [*, M, N]. The data type can be float32 or float64. + x (Tensor): The input tensor. Shape is [*, M, K]. The data type can be float32 or float64. + y (Tensor): The input tensor. Shape is [*, K, N]. The data type can be float32 or float64. + beta (float, optional): Coefficient of `input` . Default: 1.0 + alpha (float, optional): Coefficient of `x * y` . Default: 1.0 + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Its layout is determined by that of `x` and `y` . dtype and shape is the same with `input` + + Examples: + + .. code-block:: python + + # required: gpu + import paddle + + # dense + csr @ dense -> dense + input = paddle.rand([3, 2]) + crows = [0, 1, 2, 3] + cols = [1, 2, 0] + values = [1., 2., 3.] + x = paddle.sparse.sparse_csr_tensor(crows, cols, values, [3, 3]) + y = paddle.rand([3, 2]) + out = paddle.sparse.addmm(input, x, y, 3.0, 2.0) + + # dense + coo @ dense -> dense + input = paddle.rand([3, 2]) + indices = [[0, 1, 2], [1, 2, 0]] + values = [1., 2., 3.] + x = paddle.sparse.sparse_coo_tensor(indices, values, [3, 3]) + y = paddle.rand([3, 2]) + out = paddle.sparse.addmm(input, x, y, 3.0, 2.0) + + """ + return _C_ops.sparse_addmm(input, x, y, alpha, beta) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4fa18877be4d1a1e19ba22f9bbdd48b8039e64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/__init__.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022 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. + +from . import functional + +from .layer.activation import ReLU +from .layer.norm import BatchNorm, SyncBatchNorm +from .layer.activation import Softmax +from .layer.activation import ReLU6 +from .layer.activation import LeakyReLU +from .layer.conv import Conv3D +from .layer.conv import SubmConv3D +from .layer.pooling import MaxPool3D + +__all__ = [ + 'ReLU', + 'ReLU6', + 'LeakyReLU', + 'Softmax', + 'BatchNorm', + 'SyncBatchNorm', + 'Conv3D', + 'SubmConv3D', + 'MaxPool3D', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3e8ff4ba503e3b4db2e4035c1ed45d477ca813c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/__init__.py @@ -0,0 +1,33 @@ +# Copyright (c) 2022 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. + +from .conv import conv3d # noqa: F401 +from .conv import subm_conv3d # noqa: F401 +from .transformer import attention # noqa: F401 +from .pooling import max_pool3d # noqa: F401 +from .activation import relu # noqa: F401 +from .activation import relu6 # noqa: F401 +from .activation import leaky_relu # noqa: F401 +from .activation import softmax # noqa: F401 + +__all__ = [ + 'conv3d', + 'subm_conv3d', + 'max_pool3d', + 'relu', + 'relu6', + 'leaky_relu', + 'softmax', + 'attention', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/activation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..8a7c671df178e577c005b3d9ef1863aa2d53ec79 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/activation.py @@ -0,0 +1,180 @@ +# Copyright (c) 2022 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. + +__all__ = [] + +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import dygraph_only +from paddle import in_dynamic_mode +from paddle.fluid.layer_helper import LayerHelper + + +def relu(x, name=None): + """ + sparse relu activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = max(x, 0) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.nn.functional.relu(sparse_x) + # [0., 0., 1.] + """ + if in_dynamic_mode(): + return _C_ops.sparse_relu(x) + else: + op_type = 'sparse_relu' + helper = LayerHelper(op_type) + out = helper.create_sparse_variable_for_type_inference(x.dtype) + helper.append_op(type=op_type, + inputs={'x': x}, + outputs={'out': out}, + attrs={}) + return out + + +@dygraph_only +def softmax(x, axis=-1, name=None): + """ + sparse softmax activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + Note: + Only support axis=-1 for SparseCsrTensor, which is faster when read data + by row (axis=-1). + + From the point of view of dense matrix, for each row :math:`i` and each column :math:`j` + in the matrix, we have: + + .. math:: + + softmax_ij = \frac{\exp(x_ij - max_j(x_ij))}{\sum_j(exp(x_ij - max_j(x_ij))} + + Parameters: + x (Tensor): The input tensor. It can be SparseCooTensor/SparseCsrTensor. The data type can be float32 or float64. + axis (int, optional): The axis along which to perform softmax calculations. Only support -1 for SparseCsrTensor. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: SparseCoo or SparseCsr, whose layout is the same with `x` . + + Examples: + .. code-block:: python + + import paddle + import numpy as np + paddle.seed(100) + + mask = np.random.rand(3, 4) < 0.5 + np_x = np.random.rand(3, 4) * mask + # [[0. 0. 0.96823406 0.19722934] + # [0.94373937 0. 0.02060066 0.71456372] + # [0. 0. 0. 0.98275049]] + + csr = paddle.to_tensor(np_x).to_sparse_csr() + # Tensor(shape=[3, 4], dtype=paddle.float64, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 5, 6], + # cols=[2, 3, 0, 2, 3, 3], + # values=[0.96823406, 0.19722934, 0.94373937, 0.02060066, 0.71456372, + # 0.98275049]) + + out = paddle.sparse.nn.functional.softmax(csr) + # Tensor(shape=[3, 4], dtype=paddle.float64, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 5, 6], + # cols=[2, 3, 0, 2, 3, 3], + # values=[0.68373820, 0.31626180, 0.45610887, 0.18119845, 0.36269269, + # 1. ]) + + """ + return _C_ops.sparse_softmax(x, axis) + + +@dygraph_only +def relu6(x, name=None): + """ + sparse relu6 activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + relu6(x) = min(max(0, x), 6) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 8.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.nn.functional.relu6(sparse_x) + """ + return _C_ops.sparse_relu6(x, 6.0) + + +@dygraph_only +def leaky_relu(x, negative_slope=0.01, name=None): + """ + sparse leaky_relu activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + leaky\_relu(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + negative\_slope * x, & & otherwise \\ + \end{array} + \right. + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + negative_slope (float, optional): Slope of the activation function at + :math:`x < 0` . Default is 0.01. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 5.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.nn.functional.leaky_relu(sparse_x, 0.5) + """ + return _C_ops.sparse_leaky_relu(x, negative_slope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/conv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d16f4683982cfadc484964651f958255362689 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/conv.py @@ -0,0 +1,334 @@ +# Copyright (c) 2022 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. + +__all__ = [] + +from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode +from paddle.fluid.layers.utils import convert_to_list +from paddle.fluid.layers.nn import elementwise_add +from ...creation import sparse_coo_tensor +from ...binary import add +from paddle.nn.functional.conv import _update_padding_nd +from paddle.fluid.layer_helper import LayerHelper + + +def _conv3d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + subm=False, + key=None, + data_format="NDHWC", + name=None, +): + assert groups == 1, "Currently, only support groups=1" + + dims = 3 + + # Currently, only support 'NDHWC' + if data_format not in ["NDHWC"]: + raise ValueError( + "Attr(data_format) should be 'NDHWC'. Received " + "Attr(data_format): {}.".format(data_format) + ) + if len(x.shape) != 5: + raise ValueError( + "Input x should be 5D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + + channel_last = data_format == "NDHWC" + channel_dim = -1 if channel_last else 1 + if len(x.shape) != 5: + raise ValueError( + "Input x should be 5D tensor, but received x with the shape of {}".format( + x.shape + ) + ) + num_channels = x.shape[channel_dim] + if num_channels < 0: + raise ValueError( + "The channel dimension of the input({}) should be defined. " + "Received: {}.".format(x.shape, num_channels) + ) + + padding, padding_algorithm = _update_padding_nd(padding, channel_last, dims) + stride = convert_to_list(stride, dims, 'stride') + dilation = convert_to_list(dilation, dims, 'dilation') + + if in_dynamic_mode(): + pre_bias = _C_ops.sparse_conv3d( + x, + weight, + padding, + dilation, + stride, + groups, + subm, + key if key is not None else "", + ) + if bias is not None: + return add(pre_bias, bias) + else: + return pre_bias + else: + inputs = {'x': x, 'kernel': weight} + attrs = { + 'paddings': padding, + 'dilations': dilation, + 'strides': stride, + 'groups': groups, + 'subm': subm, + 'key': key, + } + op_type = 'sparse_conv3d' + helper = LayerHelper(op_type, **locals()) + rulebook = helper.create_variable_for_type_inference( + dtype='int32', stop_gradient=True + ) + counter = helper.create_variable_for_type_inference( + dtype='int32', stop_gradient=True + ) + pre_bias = helper.create_sparse_variable_for_type_inference(x.dtype) + outputs = {"out": pre_bias, "rulebook": rulebook, "counter": counter} + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + if bias is not None: + return add(pre_bias, bias) + else: + return pre_bias + + +def conv3d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + data_format="NDHWC", + name=None, +): + r""" + + The sparse convolution3d functional calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional SparseCooTensors with a shape of + :math:`[N, D, H, W, C]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. If bias attribution is provided, + bias is added to the output of the convolution. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = \sigma (W \ast X + b) + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with MCDHW format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Args: + x (Tensor): The input is 5-D SparseCooTensor with shape [N, D, H, W, C], the data + type of input is float16 or float32 or float64. + weight (Tensor): The convolution kernel, a Tensor with shape [kD, kH, kW, C/g, M], + where M is the number of filters(output channels), g is the number of groups, + kD, kH, kW are the filter's depth, height and width respectively. + bias (Tensor, optional): The bias, a Tensor of shape [M]. + stride (int|list|tuple, optional): The stride size. It means the stride in convolution. If stride is a + list/tuple, it must contain three integers, (stride_depth, stride_height, stride_width). + Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple, optional): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NDHWC"`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|list|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. Currently, only support groups=1. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NDHWC"`. When it is `"NDHWC"`, the data is stored in the order of: + `[batch_size, input_depth, input_height, input_width, input_channels]`. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A SparseCooTensor representing the conv3d, whose data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]] + values = [[1], [2], [3], [4]] + indices = paddle.to_tensor(indices, dtype='int32') + values = paddle.to_tensor(values, dtype='float32') + dense_shape = [1, 1, 3, 4, 1] + sparse_x = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape, stop_gradient=True) + weight = paddle.randn((1, 3, 3, 1, 1), dtype='float32') + y = paddle.sparse.nn.functional.conv3d(sparse_x, weight) + print(y.shape) + # (1, 1, 1, 2, 1) + """ + return _conv3d( + x, + weight, + bias, + stride, + padding, + dilation, + groups, + False, + None, + data_format, + name, + ) + + +def subm_conv3d( + x, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + groups=1, + data_format="NDHWC", + key=None, + name=None, +): + r""" + + The sparse submanifold convolution3d functional calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional SparseCooTensors with a shape of + :math:`[N, D, H, W, C]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. If bias attribution is provided, + bias is added to the output of the convolution. + + For each input :math:`X`, the equation is: + + .. math:: + + Out = W \ast X + b + + In the above equation: + + * :math:`X`: Input value, a tensor with NCDHW or NDHWC format. + * :math:`W`: Filter value, a tensor with DHWCM format. + * :math:`\\ast`: Submanifold Convolution operation, refer to the paper: https://arxiv.org/abs/1706.01307. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Args: + x (Tensor): The input is 5-D SparseCooTensor with shape [N, D, H, W, C], the data + type of input is float16 or float32 or float64. + weight (Tensor): The convolution kernel, a Tensor with shape [kD, kH, kW, C/g, M], + where M is the number of filters(output channels), g is the number of groups, + kD, kH, kW are the filter's depth, height and width respectively. + bias (Tensor, optional): The bias, a Tensor of shape [M]. + stride (int|list|tuple, optional): The stride size. It means the stride in convolution. If stride is a + list/tuple, it must contain three integers, (stride_depth, stride_height, stride_width). + Otherwise, stride_depth = stride_height = stride_width = stride. Default: stride = 1. + padding (string|int|list|tuple): The padding size. It means the number of zero-paddings + on both sides for each dimension. If `padding` is a string, either 'VALID' or + 'SAME' which is the padding algorithm. If padding size is a tuple or list, + it could be in three forms: `[pad_depth, pad_height, pad_width]` or + `[pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right]`, + and when `data_format` is `"NCDHW"`, `padding` can be in the form + `[[0,0], [0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right]]`. + when `data_format` is `"NHWC"`, `padding` can be in the form + `[[0,0], [pad_depth_front, pad_depth_back], [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0,0]]`. + Default: padding = 0. + dilation (int|list|tuple, optional): The dilation size. It means the spacing between the kernel points. + If dilation is a list/tuple, it must contain three integers, (dilation_depth, dilation_height, + dilation_width). Otherwise, dilation_depth = dilation_height = dilation_width = dilation. + Default: dilation = 1. + groups (int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Currently, only support groups=1. + data_format (str, optional): Specify the data format of the input, and the data format of the output + will be consistent with that of the input. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NDHWC"`. When it is `"NDHWC"`, the data is stored in the order of: + `[batch_size, input_depth, input_height, input_width, input_channels]`. + key(str, optional): the key is used to save or use the same rulebook, + the definition and role of rulebook refers to + https://pdfs.semanticscholar.org/5125/a16039cabc6320c908a4764f32596e018ad3.pdf. The + default value is None. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + A SparseCooTensor representing the conv3d, whose data type is + the same with input. + + Examples: + .. code-block:: python + + import paddle + + indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]] + values = [[1], [2], [3], [4]] + indices = paddle.to_tensor(indices, dtype='int32') + values = paddle.to_tensor(values, dtype='float32') + dense_shape = [1, 1, 3, 4, 1] + sparse_x = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape, stop_gradient=True) + weight = paddle.randn((1, 3, 3, 1, 1), dtype='float32') + y = paddle.sparse.nn.functional.subm_conv3d(sparse_x, weight) + print(y.shape) + #(1, 1, 3, 4, 1) + """ + return _conv3d( + x, + weight, + bias, + stride, + padding, + dilation, + groups, + True, + key, + data_format, + name, + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/pooling.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..615a27d3df94e8e6f9b134883d0ba6ba11a06f8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/pooling.py @@ -0,0 +1,100 @@ +# Copyright (c) 2022 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. + +from paddle.fluid.layers import utils +from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode +from paddle.nn.functional.pooling import _update_padding_nd + +__all__ = [] + + +def max_pool3d( + x, + kernel_size, + stride=None, + padding=0, + ceil_mode=False, + data_format="NDHWC", + name=None, +): + """ + Implements sparse max pooling 3d operation. + See more details in :ref:`api_sparse_pooling_MaxPool3d` . + + Args: + x (Tensor): The input SparseCooTensor of pooling operator, which is a 5-D tensor with + shape [N, D, H, W, C]. The format of input tensor `"NDHWC"`, where N represents batch size, C represents the number of channels, D, H and W represent the depth, height and width of the feature respectively. + kernel_size (int|list|tuple): The pool kernel size. If the kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride (int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + padding (string|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode (bool, optional): ${ceil_mode_comment} + data_format (string, optional): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. + The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. Currently only support `"NDHWC"` . + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: The output tensor of pooling result. The data type is same as input tensor. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.randn((1, 4, 4, 4, 3)) + sparse_x = dense_x.to_sparse_coo(4) + kernel_sizes = [3, 3, 3] + paddings = [0, 0, 0] + strides = [1, 1, 1] + out = paddle.sparse.nn.functional.max_pool3d(sparse_x, kernel_sizes, stride=strides, padding=paddings) + #[1, 2, 2, 2, 3] + """ + + assert in_dynamic_mode(), "Currently, Sparse API only support dynamic mode" + assert ( + x.is_sparse_coo() + ), "Currently, sparse.relu only support the input of SparseCooTensor" + assert ( + data_format == 'NDHWC' + ), "Currently, sparse.max_pool3d only support data format of 'NDHWC'" + + kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') + if stride is None: + stride = kernel_size + else: + stride = utils.convert_to_list(stride, 3, 'pool_stride') + + channel_last = True + + padding, padding_algorithm = _update_padding_nd( + padding, 3, channel_last=channel_last, ceil_mode=ceil_mode + ) + + # TODO(zkh2016): remove the dependency on dilation from the backend + dilation = [1, 1, 1] + + return _C_ops.sparse_maxpool(x, kernel_size, padding, dilation, stride) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..d2fe100b7d904552819555d77beb1b9d7705e943 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/functional/transformer.py @@ -0,0 +1,93 @@ +# Copyright (c) 2022 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. + +__all__ = [] + +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import dygraph_only + + +@dygraph_only +def attention(query, + key, + value, + sparse_mask, + key_padding_mask=None, + attn_mask=None, + name=None): + """ + Note: + This API is only used from ``CUDA 11.7`` . + + SparseCsrTensor is used to store the intermediate result of Attention matrix + in Transformer module, which can reduce memory usage and improve performance. + ``sparse_mask`` express the sparse layout in CSR format. + The calculation equation is: + + .. math:: + + result = softmax(\frac{ Q * K^T }{\sqrt{d}}) * V + + where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module. + The shape of the three parameters are: `[batch_size, num_heads, seq_len, head_dim]`, and + ``d`` represents ``head_dim`` . + + Args: + query(DenseTensor): `query` in the Attention module. 4D Tensor with float32 or float64. + key(DenseTensor): `key` in the Attention module. 4D Tensor with float32 or float64. + value(DenseTensor): `value` in the Attention module. 4D Tensor with float32 or float64. + sparse_mask(SparseCsrTensor): The sparse layout in the Attention module. Its dense shape + is `[batch_size*num_heads, seq_len, seq_len]` . `nnz` of each batch must be the same. + dtype of `crows` and `cols` must be int64, dtype of `values` can be float32 or float64. + key_padding_mask(DenseTensor, optional): The key padding mask tensor in the Attention module. + 2D tensor with shape: [batch_size, seq_len]. dtype can be float32 or float64. Default: None. + attn_mask(DenseTensor, optional): The attention mask tensor in the Attention module. + 2D tensor with shape: [seq_len, seq_len]. dtype can be float32 or float64. Default: None. + name(str, optional): The default value is None. Normally there is no need for user + to set this property. For more information, please refer to + :ref:`api_guide_Name`. + + Returns: + 4D tensor with shape: [batch_size, num_heads, seq_len, head_dim]. dtype is same with input. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + batch_size = 16 + num_heads = 16 + seq_len = 512 + head_dim = 32 + + query = paddle.rand([batch_size, num_heads, seq_len, head_dim]) + key = paddle.rand([batch_size, num_heads, seq_len, head_dim]) + value = paddle.rand([batch_size, num_heads, seq_len, head_dim]) + + query.stop_gradient = False + key.stop_gradient = False + value.stop_gradient = False + + mask = paddle.nn.functional.dropout(paddle.ones([seq_len, seq_len])).expand([batch_size, num_heads, seq_len, seq_len]) + sp_mask = mask.reshape([-1, seq_len, seq_len]).to_sparse_csr() + + kp_mask = paddle.randint(0, 2, [batch_size, seq_len]) + attn_mask = paddle.randint(0, 2, [seq_len, seq_len]) + + output = paddle.sparse.nn.functional.attention(query, key, value, sp_mask, kp_mask, attn_mask) + output.backward() + """ + return _C_ops.sparse_fused_attention(query, key, value, sparse_mask, + key_padding_mask, attn_mask) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/activation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/activation.py new file mode 100644 index 0000000000000000000000000000000000000000..3e8e81ea0b11dcc5419b9d01b8592daf328aca7d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/activation.py @@ -0,0 +1,218 @@ +# Copyright (c) 2022 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. + +from .. import functional as F +from paddle.nn import Layer + +__all__ = [] + + +class ReLU(Layer): + """ + + Sparse ReLU Activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + ReLU(x) = max(x, 0) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Sparse Tensor with any shape. + - output: Sparse Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + relu = paddle.sparse.nn.ReLU() + out = relu(sparse_x) + # [0., 0., 1.] + + """ + + def __init__(self, name=None): + super(ReLU, self).__init__() + self._name = name + + def forward(self, x): + return F.relu(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class Softmax(Layer): + r""" + + Sparse Softmax Activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + Note: + Only support axis=-1 for SparseCsrTensor, which is faster when read data + by row (axis=-1). + + From the point of view of dense matrix, for each row :math:`i` and each column :math:`j` + in the matrix, we have: + + .. math:: + + softmax_ij = \frac{\exp(x_ij - max_j(x_ij))}{\sum_j(exp(x_ij - max_j(x_ij))} + + Parameters: + axis (int, optional): The axis along which to perform softmax calculations. Only support -1 for SparseCsrTensor. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: SparseCooTensor / SparseCsrTensor with any shape. + - output: Sparse Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + paddle.seed(100) + + mask = np.random.rand(3, 4) < 0.5 + np_x = np.random.rand(3, 4) * mask + # [[0. 0. 0.96823406 0.19722934] + # [0.94373937 0. 0.02060066 0.71456372] + # [0. 0. 0. 0.98275049]] + + csr = paddle.to_tensor(np_x).to_sparse_csr() + # Tensor(shape=[3, 4], dtype=paddle.float64, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 5, 6], + # cols=[2, 3, 0, 2, 3, 3], + # values=[0.96823406, 0.19722934, 0.94373937, 0.02060066, 0.71456372, + # 0.98275049]) + + softmax = paddle.sparse.nn.Softmax() + out = softmax(csr) + # Tensor(shape=[3, 4], dtype=paddle.float64, place=Place(gpu:0), stop_gradient=True, + # crows=[0, 2, 5, 6], + # cols=[2, 3, 0, 2, 3, 3], + # values=[0.68373820, 0.31626180, 0.45610887, 0.18119845, 0.36269269, + # 1. ]) + """ + + def __init__(self, axis=-1, name=None): + super(Softmax, self).__init__() + self._axis = axis + self._name = name + + def forward(self, x): + return F.softmax(x, self._axis, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class ReLU6(Layer): + """ + + Sparse ReLU6 Activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + ReLU(x) = min(max(0,x), 6) + + Parameters: + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Sparse Tensor with any shape. + - output: Sparse Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 8.]) + sparse_x = dense_x.to_sparse_coo(1) + relu6 = paddle.sparse.nn.ReLU6() + out = relu6(sparse_x) + + """ + + def __init__(self, name=None): + super(ReLU6, self).__init__() + self._name = name + + def forward(self, x): + return F.relu6(x, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str + + +class LeakyReLU(Layer): + r""" + + Sparse Leaky ReLU Activation, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + LeakyReLU(x)= + \left\{ + \begin{array}{rcl} + x, & & if \ x >= 0 \\ + negative\_slope * x, & & otherwise \\ + \end{array} + \right. + + Parameters: + negative_slope (float, optional): Slope of the activation function at + :math:`x < 0` . Default is 0.01. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Shape: + - input: Sparse Tensor with any shape. + - output: Sparse Tensor with the same shape as input. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 5.]) + sparse_x = dense_x.to_sparse_coo(1) + leaky_relu = paddle.sparse.nn.LeakyReLU(0.5) + out = leaky_relu(sparse_x) + + """ + + def __init__(self, negative_slope=0.01, name=None): + super(LeakyReLU, self).__init__() + self._negative_slope = negative_slope + self._name = name + + def forward(self, x): + return F.leaky_relu(x, self._negative_slope, self._name) + + def extra_repr(self): + name_str = 'name={}'.format(self._name) if self._name else '' + return name_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/conv.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..faf0f86f2d125d6e3a37a4acdfb0d4aac2fbab9a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/conv.py @@ -0,0 +1,405 @@ +# Copyright (c) 2022 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. + +import numpy as np +from .. import functional as F +from paddle.nn import Layer +from paddle.nn.initializer import Normal +from paddle.nn.functional.conv import _update_padding_nd +from paddle.fluid.layers import utils + +__all__ = [] + + +class _Conv3D(Layer): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + subm=False, + key=None, + padding_mode='zeros', + weight_attr=None, + bias_attr=None, + data_format="NDHWC", + ): + super(_Conv3D, self).__init__() + assert ( + weight_attr is not False + ), "weight_attr should not be False in Conv." + self._param_attr = weight_attr + self._bias_attr = bias_attr + self._groups = groups + self._in_channels = in_channels + self._out_channels = out_channels + self._data_format = data_format + self._subm = subm + self._key = key + + assert ( + padding_mode == 'zeros' + ), "Currently, only support padding_mode='zeros'" + assert groups == 1, "Currently, only support groups=1" + + valid_format = {'NDHWC'} + if data_format not in valid_format: + raise ValueError( + "data_format must be one of {}, but got data_format='{}'".format( + valid_format, data_format + ) + ) + + channel_last = data_format == "NDHWC" + + dims = 3 + self._stride = utils.convert_to_list(stride, dims, 'stride') + self._dilation = utils.convert_to_list(dilation, dims, 'dilation') + self._kernel_size = utils.convert_to_list( + kernel_size, dims, 'kernel_size' + ) + self._padding = padding + self._padding_mode = padding_mode + self._updated_padding, self._padding_algorithm = _update_padding_nd( + padding, channel_last, dims + ) + + # the sparse conv restricts the shape is [D, H, W, in_channels, out_channels] + filter_shape = self._kernel_size + [ + self._in_channels, + self._out_channels, + ] + + def _get_default_param_initializer(): + filter_elem_num = np.prod(self._kernel_size) * self._in_channels + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std) + + self.weight = self.create_parameter( + shape=filter_shape, + attr=self._param_attr, + default_initializer=_get_default_param_initializer(), + ) + self.bias = self.create_parameter( + attr=self._bias_attr, shape=[self._out_channels], is_bias=True + ) + + def forward(self, x): + out = F.conv._conv3d( + x, + self.weight, + bias=self.bias, + stride=self._stride, + padding=self._updated_padding, + dilation=self._dilation, + groups=self._groups, + subm=self._subm, + key=self._key, + data_format=self._data_format, + ) + return out + + def extra_repr(self): + main_str = '{_in_channels}, {_out_channels}, kernel_size={_kernel_size}' + if self._stride != [1] * len(self._stride): + main_str += ', stride={_stride}' + if self._padding != 0: + main_str += ', padding={_padding}' + if self._padding_mode != 'zeros': + main_str += ', padding_mode={_padding_mode}' + if self._dilation != [1] * len(self._dilation): + main_str += ', dilation={_dilation}' + if self._groups != 1: + main_str += ', groups={_groups}' + main_str += ', data_format={_data_format}' + return main_str.format(**self.__dict__) + + +class Conv3D(_Conv3D): + r""" + **Sparse Convlution3d Layer** + The Sparse convolution3d layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional SparseCooTensors with a shape of + :math:`[N, D, H, W, C]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. If bias attribution is provided, + bias is added to the output of the convolution. + For each input :math:`X`, the equation is: + + .. math:: + + Out = W \ast X + b + + In the above equation: + + * :math:`X`: Input value, a tensor with NDHWC format. + * :math:`W`: Filter value, a tensor with DHWCM format. + * :math:`\\ast`: Convolution operation. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Parameters: + in_channels(int): The number of input channels in the input image. + out_channels(int): The number of output channels produced by the convolution. + kernel_size(int|list|tuple, optional): The size of the convolving kernel. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain three integers, (stride_D, stride_H, stride_W). Otherwise, the + stride_D = stride_H = stride_W = stride. The default value is 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1, currently, only support groups=1. + padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Currently only support ``'zeros'``. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d. If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCDHW" or "NDHWC". Currently, only support "NCDHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, D_{in}, H_{in}, W_{in}, C_{in})` + + - weight: :math:`(K_{d}, K_{h}, K_{w}, C_{in}, C_{out})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, D_{out}, H_{out}, W_{out}, C_{out})` + + Where + + .. math:: + + D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1 + + H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1 + + W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (kernel\_size[2] - 1) + 1))}{strides[2]} + 1 + + Examples: + + .. code-block:: python + + import paddle + + indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]] + values = [[1], [2], [3], [4]] + indices = paddle.to_tensor(indices, dtype='int32') + values = paddle.to_tensor(values, dtype='float32') + dense_shape = [1, 1, 3, 4, 1] + sparse_x = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape, stop_gradient=True) + conv = paddle.sparse.nn.Conv3D(1, 1, (1, 3, 3)) + y = conv(sparse_x) + print(y.shape) + # (1, 1, 1, 2, 1) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + padding_mode='zeros', + weight_attr=None, + bias_attr=None, + data_format="NDHWC", + ): + super(Conv3D, self).__init__( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + subm=False, + key=None, + padding_mode=padding_mode, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) + + +class SubmConv3D(_Conv3D): + r""" + **Submanifold Sparse Convlution3d Layer** + The submanifold sparse convolution3d layer calculates the output based on the input, filter + and strides, paddings, dilations, groups parameters. Input(Input) and + Output(Output) are multidimensional SparseCooTensors with a shape of + :math:`[N, D, H, W, C]` . Where N is batch size, C is the number of + channels, D is the depth of the feature, H is the height of the feature, + and W is the width of the feature. If bias attribution is provided, + bias is added to the output of the convolution. + For each input :math:`X`, the equation is: + + .. math:: + + Out = W \ast X + b + + In the above equation: + + * :math:`X`: Input value, a tensor with NDHWC format. + * :math:`W`: Filter value, a tensor with DHWCM format. + * :math:`\\ast`: Submanifold Convolution operation, refer to the paper: https://arxiv.org/abs/1706.01307. + * :math:`b`: Bias value, a 1-D tensor with shape [M]. + * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different. + + Parameters: + in_channels(int): The number of input channels in the input image. + out_channels(int): The number of output channels produced by the convolution. + kernel_size(int|list|tuple, optional): The size of the convolving kernel. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain three integers, (stride_D, stride_H, stride_W). Otherwise, the + stride_D = stride_H = stride_W = stride. The default value is 1. + padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms. + 1. a string in ['valid', 'same']. + 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` + 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...]. + 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions. + 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0). + The default value is 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + groups(int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1. + padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Currently only support ``'zeros'``. + key(str, optional): the key is used to save or use the same rulebook, + the definition and role of rulebook refers to + https://pdfs.semanticscholar.org/5125/a16039cabc6320c908a4764f32596e018ad3.pdf. The + default value is None. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv3d. If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv3d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + data_format(str, optional): Data format that specifies the layout of input. + It can be "NCDHW" or "NDHWC". Currently, only support "NCDHW". + + Attribute: + + **weight** (Parameter): the learnable weights of filters of this layer. + + **bias** (Parameter): the learnable bias of this layer. + + Shape: + + - x: :math:`(N, D_{in}, H_{in}, W_{in}, C_{in})` + + - weight: :math:`(K_{d}, K_{h}, K_{w}, C_{in}, C_{out})` + + - bias: :math:`(C_{out})` + + - output: :math:`(N, D_{out}, H_{out}, W_{out}, C_{out})` + + Where + + .. math:: + + D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1 + + H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1 + + W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (kernel\_size[2] - 1) + 1))}{strides[2]} + 1 + + Examples: + + .. code-block:: python + + import paddle + + indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]] + values = [[1], [2], [3], [4]] + dense_shape = [1, 1, 3, 4, 1] + indices = paddle.to_tensor(indices, dtype='int32') + values = paddle.to_tensor(values, dtype='float32') + sparse_x = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape, stop_gradient=True) + subm_conv = paddle.sparse.nn.SubmConv3D(1, 1, (1, 3, 3)) + y = subm_conv(sparse_x) + print(y.shape) + # (1, 1, 3, 4, 1) + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + padding_mode='zeros', + key=None, + weight_attr=None, + bias_attr=None, + data_format="NDHWC", + ): + super(SubmConv3D, self).__init__( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + subm=True, + key=key, + padding_mode=padding_mode, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/norm.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..987e1835ecd0377d15501dab9a7dbe66b88b0dae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/norm.py @@ -0,0 +1,414 @@ +# Copyright (c) 2022 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. + +import paddle +import warnings +from paddle.nn.layer.norm import _BatchNormBase +from paddle.framework import no_grad +from paddle import _C_ops, in_dynamic_mode +from paddle.fluid.layer_helper import LayerHelper + + +class BatchNorm(paddle.nn.BatchNorm1D): + r""" + Applies Batch Normalization over a SparseCooTensor as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift . + + When use_global_stats = False, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are the statistics of one mini-batch. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + When use_global_stats = True, the :math:`\mu_{\beta}` + and :math:`\sigma_{\beta}^{2}` are not the statistics of one mini-batch. + They are global or running statistics (moving_mean and moving_variance). It usually got from the + pre-trained model. Calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The normalization function formula is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable proportional parameter + - :math:`\beta` : trainable deviation parameter + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of batch_norm. If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as weight_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the weight_attr is not set, the parameter is initialized with Xavier. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of batch_norm. + If it is set to None or one attribute of ParamAttr, batch_norm + will create ParamAttr as bias_attr. If it is set to Fasle, the weight is not learnable. + If the Initializer of the bias_attr is not set, the bias is initialized zero. Default: None. + data_format(str, optional): Specify the input data format, may be "NC", "NCL" or "NLC". Default "NCL". + use_global_stats(bool|None, optional): Whether to use global mean and variance. If set to False, use the statistics of one mini-batch, if set to True, use the global statistics, if set to None, use global statistics in the test phase and use the statistics of one mini-batch in the training phase. Default: None. + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shape: + - x: A SparseCooTensor with layout = 'NDHWC'. + - output: SparseCooTensor with same shape as input x. + + Returns: + None. + + + Examples: + .. code-block:: python + + import paddle + + paddle.seed(123) + channels = 3 + x_data = paddle.randn((1, 6, 6, 6, channels)).astype('float32') + dense_x = paddle.to_tensor(x_data) + sparse_x = dense_x.to_sparse_coo(4) + batch_norm = paddle.sparse.nn.BatchNorm(channels) + batch_norm_out = batch_norm(sparse_x) + print(batch_norm_out.shape) + # [1, 6, 6, 6, 3] + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NDHWC', + use_global_stats=None, + name=None, + ): + super(BatchNorm, self).__init__( + num_features, + momentum=momentum, + epsilon=epsilon, + weight_attr=weight_attr, + bias_attr=bias_attr, + data_format=data_format, + use_global_stats=use_global_stats, + name=name, + ) + + def _check_data_format(self, input): + if input != "NDHWC": + raise ValueError('sparse BatchNorm only support layout of "NDHWC"') + + def forward(self, input): + self._check_data_format(self._data_format) + + if self.training: + warnings.warn( + "When training, we now always track global mean and variance." + ) + + if self._use_global_stats == None: + self._use_global_stats = not self.training + trainable_statistics = False + else: + trainable_statistics = not self._use_global_stats + + data_format = 'NCHW' if self._data_format[1] == 'C' else 'NHWC' + + if in_dynamic_mode(): + batch_norm_out, _, _, _, _, _ = _C_ops.sparse_batch_norm_( + input, + self.weight, + self.bias, + self._mean, + self._variance, + self._momentum, + self._epsilon, + data_format, + not self.training, + self._use_global_stats, + trainable_statistics, + False, + ) + return batch_norm_out + else: + inputs = { + 'x': input, + 'scale': self.weight, + 'bias': self.bias, + 'mean': self._mean, + 'variance': self._variance, + } + attrs = { + 'momentum': self._momentum, + 'epsilon': self._epsilon, + 'data_layout': data_format, + 'is_test': not self.training, + 'use_global_stats': self._use_global_stats, + 'trainable_statistics': trainable_statistics, + 'fuse_with_relu': False, + } + op_type = 'sparse_batch_norm' + helper = LayerHelper(op_type) + dtype = input.dtype + mean_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + variance_out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + saved_mean = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + saved_variance = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + reserve_space = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=True + ) + out = helper.create_sparse_variable_for_type_inference(dtype) + outputs = { + "out": out, + "mean_out": mean_out, + "variance_out": variance_out, + "saved_mean": saved_mean, + "saved_variance": saved_variance, + "reserve_space": reserve_space, + } + + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + return out + + +class SyncBatchNorm(paddle.nn.SyncBatchNorm): + r""" + This interface is used to construct a callable object of the ``SyncBatchNorm`` class. + It implements the function of the Cross-GPU Synchronized Batch Normalization Layer, and can + be used as a normalizer function for other operations, such as conv2d and fully connected + operations. + The data is normalized by the mean and variance of the channel based on whole mini-batch + , which including data in all gpus. + Refer to `Batch Normalization: Accelerating Deep Network Training by Reducing + Internal Covariate Shift `_ + for more details. + + When model in training mode, the :math:`\\mu_{\\beta}` + and :math:`\\sigma_{\\beta}^{2}` are the statistics of whole mini-batch data in all gpus. + Calculated as follows: + + .. math:: + + \mu_{\beta} &\gets \frac{1}{m} \sum_{i=1}^{m} x_i \qquad &//\ + \ mini-batch\ mean \\ + \sigma_{\beta}^{2} &\gets \frac{1}{m} \sum_{i=1}^{m}(x_i - \ + \mu_{\beta})^2 \qquad &//\ mini-batch\ variance \\ + + - :math:`x` : whole mini-batch data in all gpus + - :math:`m` : the size of the whole mini-batch data + + When model in evaluation mode, the :math:`\\mu_{\\beta}` + and :math:`\sigma_{\beta}^{2}` are global statistics (moving_mean and moving_variance, + which usually got from the pre-trained model). Global statistics calculated as follows: + + .. math:: + moving\_mean = moving\_mean * momentum + \mu_{\beta} * (1. - momentum) \quad &// global \ mean \\ + moving\_variance = moving\_variance * momentum + \sigma_{\beta}^{2} * (1. - momentum) \quad &// global \ variance \\ + + The formula of normalization is as follows: + + .. math:: + + \hat{x_i} &\gets \frac{x_i - \mu_\beta} {\sqrt{\ + \sigma_{\beta}^{2} + \epsilon}} \qquad &//\ normalize \\ + y_i &\gets \gamma \hat{x_i} + \beta \qquad &//\ scale\ and\ shift + + - :math:`\epsilon` : add a smaller value to the variance to prevent division by zero + - :math:`\gamma` : trainable scale parameter vector + - :math:`\beta` : trainable shift parameter vector + + Note: + If you want to use container to pack your model and has ``SyncBatchNorm`` in the + evaluation phase, please use ``nn.LayerList`` or ``nn.Sequential`` instead of + ``list`` to pack the model. + + Parameters: + num_features(int): Indicate the number of channels of the input ``Tensor``. + epsilon(float, optional): The small value added to the variance to prevent division by zero. Default: 1e-5. + momentum(float, optional): The value used for the moving_mean and moving_var computation. Default: 0.9. + weight_attr(ParamAttr|bool, optional): The parameter attribute for Parameter `scale` + of this layer. If it is set to None or one attribute of ParamAttr, this layerr + will create ParamAttr as param_attr. If the Initializer of the param_attr + is not set, the parameter is initialized with Xavier. If it is set to False, + this layer will not have trainable scale parameter. Default: None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of this layer. + If it is set to None or one attribute of ParamAttr, this layer + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. If it is set to False, this layer will not + have trainable bias parameter. Default: None. + data_format(str, optional): Specify the input data format, may be "NCHW". Default "NCHW". + name(str, optional): Name for the BatchNorm, default is None. For more information, please refer to :ref:`api_guide_Name`.. + + Shapes: + input: Tensor that the dimension from 2 to 5. + + output: Tensor with the same shape as input. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + import paddle.sparse.nn as nn + + x = paddle.to_tensor([[[[0.3, 0.4], [0.3, 0.07]], [[0.83, 0.37], [0.18, 0.93]]]], dtype='float32') + x = x.to_sparse_coo(len(x.shape)-1) + + if paddle.is_compiled_with_cuda(): + sync_batch_norm = nn.SyncBatchNorm(2) + hidden1 = sync_batch_norm(x) + print(hidden1) + # Tensor(shape=[1, 2, 2, 2], dtype=paddle.float32, place=Place(gpu:0), stop_gradient=True, + # indices=[[0, 0, 0, 0], + # [0, 0, 1, 1], + # [0, 1, 0, 1]], + # values=[[-0.40730840, -0.13725480], + # [-0.40730840, -1.20299828], + # [ 1.69877410, -0.23414057], + # [-0.88415730, 1.57439375]]) + """ + + def __init__( + self, + num_features, + momentum=0.9, + epsilon=1e-05, + weight_attr=None, + bias_attr=None, + data_format='NCHW', + name=None, + ): + super(SyncBatchNorm, self).__init__( + num_features, + momentum, + epsilon, + weight_attr, + bias_attr, + data_format, + name, + ) + + def forward(self, x): + self._check_data_format() + sync_batch_norm_out, _, _, _, _, _ = _C_ops.sparse_sync_batch_norm_( + x, + self.weight, + self.bias, + self._mean, + self._variance, + self._momentum, + self._epsilon, + self._data_format, + not self.training, + False, + False, + False, + ) + return sync_batch_norm_out + + @classmethod + def convert_sync_batchnorm(cls, layer): + r""" + Helper function to convert :class: `paddle.sparse.nn.BatchNorm` layers in the model to :class: `paddle.sparse.nn.SyncBatchNorm` layers. + + Parameters: + layer(paddle.nn.Layer): model containing one or more `BatchNorm` layers. + + Returns: + The original model with converted SyncBatchNorm layers. If BatchNorm layer in the model, use SyncBatchNorm layer instead. + + Examples: + + .. code-block:: python + + import paddle + import paddle.sparse.nn as nn + + model = paddle.nn.Sequential(nn.Conv3D(3, 5, 3), nn.BatchNorm(5)) + sync_model = nn.SyncBatchNorm.convert_sync_batchnorm(model) + """ + + layer_output = layer + if isinstance(layer, _BatchNormBase): + if ( + layer._weight_attr != None + and not isinstance(layer._weight_attr, bool) + and layer._weight_attr.name != None + ): + layer._weight_attr.name = layer._weight_attr.name + '_sync' + if ( + layer._bias_attr != None + and not isinstance(layer._bias_attr, bool) + and layer._bias_attr.name != None + ): + layer._bias_attr.name = layer._bias_attr.name + '_sync' + + # convert sparse BatchNorm + if isinstance(layer, BatchNorm): + layer_output = SyncBatchNorm( + layer._num_features, + layer._momentum, + layer._epsilon, + layer._weight_attr, + layer._bias_attr, + layer._data_format, + layer._name, + ) + # convert dense BatchNorm + else: + layer_output = paddle.nn.SyncBatchNorm( + layer._num_features, + layer._momentum, + layer._epsilon, + layer._weight_attr, + layer._bias_attr, + layer._data_format, + layer._name, + ) + + if layer._weight_attr != False and layer._bias_attr != False: + with no_grad(): + layer_output.weight = layer.weight + layer_output.bias = layer.bias + layer_output._mean = layer._mean + layer_output._variance = layer._variance + + for name, sublayer in layer.named_children(): + layer_output.add_sublayer( + name, cls.convert_sync_batchnorm(sublayer) + ) + del layer + return layer_output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/pooling.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..340e7e5e1fce1c8598cb0bdf3ce84940390e3b08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/nn/layer/pooling.py @@ -0,0 +1,107 @@ +# Copyright (c) 2022 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. + +from paddle.nn import Layer +from .. import functional as F + + +class MaxPool3D(Layer): + """ + This operation applies 3D max pooling over input features based on the sparse input, + and kernel_size, stride, padding parameters. Input(X) and Output(Out) are + in NDHWC format, where N is batch size, C is the number of channels, + H is the height of the feature, D is the depth of the feature, and W is the width of the feature. + + Parameters: + kernel_size(int|list|tuple): The pool kernel size. If the kernel size + is a tuple or list, it must contain three integers, + (kernel_size_Depth, kernel_size_Height, kernel_size_Width). + Otherwise, the pool kernel size will be the cube of an int. + stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list, + it must contain three integers, [stride_Depth, stride_Height, stride_Width). + Otherwise, the pool stride size will be a cube of an int. + Default None, then stride will be equal to the kernel_size. + padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms. + 1. A string in ['valid', 'same']. + 2. An int, which means the feature map is zero padded by size of `padding` on every sides. + 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. + 4. A list[int] or tuple(int) whose length is \6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. + 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). + The default value is 0. + ceil_mode(bool, optional): ${ceil_mode_comment} + return_mask(bool, optional): Whether to return the max indices along with the outputs. + data_format(str, optional): The data format of the input and output data. An optional string from: `"NCDHW"`, + `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: + `[batch_size, input_channels, input_depth, input_height, input_width]`. Currently, only support "NDHWC". + name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. + Usually name is no need to set and None by default. + + + Returns: + A callable object of MaxPool3D. + + Shape: + - x(Tensor): The input SparseCooTensor of max pool3d operator, which is a 5-D tensor. + The data type can be float32, float64. + - output(Tensor): The output tensor of max pool3d operator, which is a 5-D tensor. + The data type is same as input x. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.randn((2, 3, 6, 6, 3)) + sparse_x = dense_x.to_sparse_coo(4) + max_pool3d = paddle.sparse.nn.MaxPool3D( + kernel_size=3, data_format='NDHWC') + out = max_pool3d(sparse_x) + #shape=[2, 1, 2, 2, 3] + + """ + + def __init__( + self, + kernel_size, + stride=None, + padding=0, + return_mask=False, + ceil_mode=False, + data_format="NDHWC", + name=None, + ): + super(MaxPool3D, self).__init__() + self.ksize = kernel_size + self.stride = stride + self.padding = padding + self.return_mask = return_mask + self.ceil_mode = ceil_mode + self.data_format = data_format + self.name = name + + def forward(self, x): + return F.max_pool3d( + x, + kernel_size=self.ksize, + stride=self.stride, + padding=self.padding, + ceil_mode=self.ceil_mode, + data_format=self.data_format, + name=self.name, + ) + + def extra_repr(self): + return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format( + **self.__dict__ + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/unary.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/unary.py new file mode 100644 index 0000000000000000000000000000000000000000..32825c32b3650b8cf6a8d0a6b034c4f3fe8eeb9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sparse/unary.py @@ -0,0 +1,702 @@ +# Copyright (c) 2022 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. + +import numpy as np + +from paddle import _C_ops, _legacy_C_ops +from paddle.fluid.framework import ( + dygraph_only, + core, + convert_np_dtype_to_dtype_, +) + +__all__ = [] + +_int_dtype_ = [ + core.VarDesc.VarType.UINT8, + core.VarDesc.VarType.INT8, + core.VarDesc.VarType.INT16, + core.VarDesc.VarType.INT32, + core.VarDesc.VarType.INT64, + core.VarDesc.VarType.BOOL, +] + + +@dygraph_only +def sin(x, name=None): + """ + Calculate elementwise sin of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = sin(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.sin(sparse_x) + + """ + return _C_ops.sparse_sin(x) + + +@dygraph_only +def tan(x, name=None): + """ + Calculate elementwise tan of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = tan(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.tan(sparse_x) + + """ + return _C_ops.sparse_tan(x) + + +@dygraph_only +def asin(x, name=None): + """ + Calculate elementwise asin of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = asin(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.asin(sparse_x) + + """ + return _C_ops.sparse_asin(x) + + +@dygraph_only +def transpose(x, perm, name=None): + """ + Changes the perm order of ``x`` without changing its data, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = transpose(x, perm) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + perm (list|tuple): Permute the input according to the data of perm. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A transposed Sparse Tensor with the same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([[-2., 0.], [1., 2.]]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.transpose(sparse_x, [1, 0]) + + """ + return _C_ops.sparse_transpose(x, perm) + + +@dygraph_only +def atan(x, name=None): + """ + Calculate elementwise atan of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = atan(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.atan(sparse_x) + + """ + return _C_ops.sparse_atan(x) + + +@dygraph_only +def sinh(x, name=None): + """ + Calculate elementwise sinh of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = sinh(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.sinh(sparse_x) + + """ + return _C_ops.sparse_sinh(x) + + +@dygraph_only +def asinh(x, name=None): + """ + Calculate elementwise asinh of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = asinh(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.asinh(sparse_x) + + """ + return _C_ops.sparse_asinh(x) + + +@dygraph_only +def atanh(x, name=None): + """ + Calculate elementwise atanh of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = atanh(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.atanh(sparse_x) + + """ + return _C_ops.sparse_atanh(x) + + +@dygraph_only +def tanh(x, name=None): + """ + Calculate elementwise tanh of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = tanh(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.tanh(sparse_x) + + """ + return _C_ops.sparse_tanh(x) + + +@dygraph_only +def square(x, name=None): + """ + Calculate elementwise square of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = square(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.square(sparse_x) + + """ + return _C_ops.sparse_square(x) + + +@dygraph_only +def sqrt(x, name=None): + """ + Calculate elementwise sqrt of SparseTensor, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = sqrt(x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.sqrt(sparse_x) + + """ + return _C_ops.sparse_sqrt(x) + + +@dygraph_only +def log1p(x, name=None): + """ + Calculate the natural log of (1+x), requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = ln(1+x) + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2, 0, 1], dtype='float32') + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.log1p(sparse_x) + + """ + return _C_ops.sparse_log1p(x) + + +@dygraph_only +def cast(x, index_dtype=None, value_dtype=None, name=None): + """ + cast non-zero-index of SparseTensor to `index_dtype`, non-zero-element of SparseTensor to + `value_dtype` , requiring x to be a SparseCooTensor or SparseCsrTensor. + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + index_dtype (np.dtype|str, optional): Data type of the index of SparseCooTensor, + or crows/cols of SparseCsrTensor. Can be uint8, int8, int16, int32, int64. + value_dtype (np.dtype|str, optional): Data type of the value of SparseCooTensor, + SparseCsrTensor. Can be bool, float16, float32, float64, int8, int32, int64, uint8. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2, 0, 1]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.cast(sparse_x, 'int32', 'float64') + + """ + if index_dtype and not isinstance(index_dtype, core.VarDesc.VarType): + index_dtype = convert_np_dtype_to_dtype_(index_dtype) + if value_dtype and not isinstance(value_dtype, core.VarDesc.VarType): + value_dtype = convert_np_dtype_to_dtype_(value_dtype) + return _C_ops.sparse_cast(x, index_dtype, value_dtype) + + +@dygraph_only +def pow(x, factor, name=None): + """ + Calculate elementwise pow of x, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = x^{factor} + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + factor (float|int): factor of pow. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2, 0, 3], dtype='float32') + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.pow(sparse_x, 2) + + """ + return _C_ops.sparse_pow(x, float(factor)) + + +@dygraph_only +def neg(x, name=None): + """ + Calculate elementwise negative of x, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = -x + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2, 0, 3], dtype='float32') + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.neg(sparse_x) + + """ + return _C_ops.sparse_scale(x, -1.0, 0.0, True) + + +@dygraph_only +def abs(x, name=None): + """ + Calculate elementwise absolute value of x, requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = |x| + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2, 0, 3], dtype='float32') + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.abs(sparse_x) + + """ + return _C_ops.sparse_abs(x) + + +@dygraph_only +def coalesce(x, name=None): + r""" + the coalesced operator include sorted and merge, after coalesced, the indices of x is sorted and unique. + + Parameters: + x (Tensor): the input SparseCooTensor. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: return the SparseCooTensor after coalesced. + + Examples: + .. code-block:: python + + import paddle + + indices = [[0, 0, 1], [1, 1, 2]] + values = [1.0, 2.0, 3.0] + sp_x = paddle.sparse.sparse_coo_tensor(indices, values) + sp_x = paddle.sparse.coalesce(sp_x) + print(sp_x.indices()) + #[[0, 1], [1, 2]] + print(sp_x.values()) + #[3.0, 3.0] + """ + return _C_ops.sparse_coalesce(x) + + +@dygraph_only +def rad2deg(x, name=None): + """ + Convert each of the elements of input x from angles in radians to degrees, + requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + rad2deg(x) = 180/ \pi * x + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([3.142, 0., -3.142]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.rad2deg(sparse_x) + + """ + if x.dtype in _int_dtype_: + x = _C_ops.sparse_cast(x, None, core.VarDesc.VarType.FP32) + return _C_ops.sparse_scale(x, 180.0 / np.pi, 0.0, True) + + +@dygraph_only +def deg2rad(x, name=None): + """ + Convert each of the elements of input x from degrees to angles in radians, + requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + deg2rad(x) = \pi * x / 180 + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-180, 0, 180]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.deg2rad(sparse_x) + + """ + if x.dtype in _int_dtype_: + x = _C_ops.sparse_cast(x, None, core.VarDesc.VarType.FP32) + return _C_ops.sparse_scale(x, np.pi / 180.0, 0.0, True) + + +@dygraph_only +def expm1(x, name=None): + """ + Calculate elementwise `exp(x)-1` , requiring x to be a SparseCooTensor or SparseCsrTensor. + + .. math:: + + out = exp(x) - 1 + + Parameters: + x (Tensor): The input Sparse Tensor with data type float32, float64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Sparse Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + dense_x = paddle.to_tensor([-2., 0., 1.]) + sparse_x = dense_x.to_sparse_coo(1) + out = paddle.sparse.expm1(sparse_x) + """ + return _C_ops.sparse_expm1(x) + + +@dygraph_only +def reshape(x, shape, name=None): + """ + Changes the shape of ``x`` without changing its value, requiring x to be a SparseCooTensor or SparseCsrTensor. + Currently this function can only reshape the sparse dims of ``x`` , but ``shape`` argument must be specified + as the shape of the reshaped tensor. + + Note that if x is a SparseCsrTensor, then len(shape) must be 2 or 3. + + There are some tricks when specifying the target shape. + + - 1. -1 means the value of this dimension is inferred from the total element number of x and remaining dimensions. Thus one and only one dimension can be set -1. + + - 2. 0 means the actual dimension value is going to be copied from the corresponding dimension of x. The indices of 0 in the target shape can not exceed the rank of x. + + Here are some examples to explain it. + + - 1. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [6, 8], the reshape operator will transform x into a 2-D tensor with shape [6, 8] and leaving x's data unchanged. + + - 2. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [2, 3, -1, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 3, 4, 2] and leaving x's data unchanged. In this case, one dimension of the target shape is set to -1, the value of this dimension is inferred from the total element number of x and remaining dimensions. + + - 3. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [-1, 0, 3, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 4, 3, 2] and leaving x's data unchanged. In this case, besides -1, 0 means the actual dimension value is going to be copied from the corresponding dimension of x. + + Args: + x (Tensor): The input sparse tensor with data type ``float32``, ``float64``, ``int32``, ``int64`` or ``bool``. + shape (list|tuple): Define the target shape. At most one dimension of the target shape can be -1. + The data type is ``int32``. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A reshaped Tensor with the same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x_shape = [6, 2, 3] + new_shape = [1, 0, 2, -1, 3] + format = "coo" + + dense_x = paddle.randint(-100, 100, x_shape) * paddle.randint(0, 2, x_shape) + + if format == "coo": + sp_x = dense_x.to_sparse_coo(len(x_shape)) + else: + sp_x = dense_x.to_sparse_csr() + sp_out = paddle.sparse.reshape(sp_x, new_shape) + + print(sp_out) + # the shape of sp_out is [1, 2, 2, 3, 3] + + """ + return _C_ops.sparse_reshape(x, shape) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44ab13360618a9d7d6139eddc0ff3ec6f5314993 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/__init__.py @@ -0,0 +1,90 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from . import amp # noqa: F401 +from . import sparsity # noqa: F401 +from . import nn # noqa: F401 +from .io import save_inference_model # noqa: F401 +from .io import load_inference_model # noqa: F401 +from .io import deserialize_persistables # noqa: F401 +from .io import serialize_persistables # noqa: F401 +from .io import deserialize_program # noqa: F401 +from .io import serialize_program # noqa: F401 +from .io import load_from_file # noqa: F401 +from .io import save_to_file # noqa: F401 +from .io import normalize_program # noqa: F401 +from ..fluid import Scope # noqa: F401 +from .input import data # noqa: F401 +from .input import InputSpec # noqa: F401 +from ..fluid.executor import Executor # noqa: F401 +from ..fluid.executor import global_scope # noqa: F401 +from ..fluid.executor import scope_guard # noqa: F401 +from ..fluid.backward import append_backward # noqa: F401 +from ..fluid.backward import gradients # noqa: F401 +from ..fluid.compiler import BuildStrategy # noqa: F401 +from ..fluid.compiler import CompiledProgram # noqa: F401 +from ..fluid.compiler import IpuCompiledProgram # noqa: F401 +from ..fluid.compiler import IpuStrategy # noqa: F401 +from ..fluid.compiler import ExecutionStrategy # noqa: F401 +from ..fluid.framework import default_main_program # noqa: F401 +from ..fluid.framework import default_startup_program # noqa: F401 +from ..fluid.framework import device_guard # noqa: F401 +from ..fluid.framework import Program # noqa: F401 +from ..fluid.framework import name_scope # noqa: F401 +from ..fluid.framework import program_guard # noqa: F401 +from ..fluid.framework import cpu_places # noqa: F401 +from ..fluid.framework import cuda_places # noqa: F401 +from ..fluid.framework import xpu_places # noqa: F401 +from ..fluid.framework import mlu_places # noqa: F401 +from ..fluid.framework import npu_places # noqa: F401 +from ..fluid.framework import Variable # noqa: F401 +from ..fluid.framework import ipu_shard_guard # noqa: F401 +from ..fluid.framework import set_ipu_shard # noqa: F401 +from ..fluid.layers.control_flow import Print # noqa: F401 +from ..fluid.layers.nn import py_func # noqa: F401 +from ..fluid.parallel_executor import ParallelExecutor # noqa: F401 +from ..fluid.param_attr import WeightNormParamAttr # noqa: F401 +from ..fluid.optimizer import ExponentialMovingAverage # noqa: F401 +from ..fluid.io import save # noqa: F401 +from ..fluid.io import load # noqa: F401 +from ..fluid.io import load_program_state # noqa: F401 +from ..fluid.io import set_program_state # noqa: F401 + +from ..fluid.io import load_vars # noqa: F401 +from ..fluid.io import save_vars # noqa: F401 +from ..fluid.io import batch # noqa: F401 + +from ..fluid.layers import create_parameter # noqa: F401 +from ..fluid.layers import create_global_var # noqa: F401 +from ..fluid.layers.metric_op import auc # noqa: F401 +from ..fluid.layers.metric_op import accuracy # noqa: F401 +from ..fluid.contrib.layers import ctr_metric_bundle # noqa: F401 +from ..fluid.layers import exponential_decay # noqa: F401 + +__all__ = [ #noqa + 'append_backward', 'gradients', 'Executor', 'global_scope', 'scope_guard', + 'BuildStrategy', 'CompiledProgram', 'ipu_shard_guard', 'IpuCompiledProgram', + 'IpuStrategy', 'Print', 'py_func', 'ExecutionStrategy', 'name_scope', + 'ParallelExecutor', 'program_guard', 'WeightNormParamAttr', + 'ExponentialMovingAverage', 'default_main_program', + 'default_startup_program', 'Program', 'data', 'InputSpec', 'save', 'load', + 'save_inference_model', 'load_inference_model', 'serialize_program', + 'serialize_persistables', 'save_to_file', 'deserialize_program', + 'deserialize_persistables', 'load_from_file', 'normalize_program', + 'load_program_state', 'set_program_state', 'cpu_places', 'cuda_places', + 'xpu_places', 'npu_places', 'mlu_places', 'Variable', 'create_global_var', + 'accuracy', 'auc', 'device_guard', 'create_parameter', 'set_ipu_shard', + 'ctr_metric_bundle', 'exponential_decay' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/amp/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/amp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ee3225057d0a581b7c0c2c98953d059c7f99e0b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/amp/__init__.py @@ -0,0 +1,21 @@ +# 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. + +from ...fluid.contrib.mixed_precision import decorate # noqa: F401 +from ...fluid.contrib.mixed_precision import CustomOpLists # noqa: F401 +from ...fluid.contrib.mixed_precision import AutoMixedPrecisionLists # noqa: F401 +from ...fluid.contrib.mixed_precision import fp16_guard # noqa: F401 +from ...fluid.contrib.mixed_precision import cast_model_to_fp16 # noqa: F401 +from ...fluid.contrib.mixed_precision import cast_parameters_to_fp16 # noqa: F401 +from ...fluid.contrib.mixed_precision import bf16 # noqa: F401 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/input.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/input.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8cf5ea67c9bfe8c8d2e5a0cd636929b92d35d8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/input.py @@ -0,0 +1,350 @@ +# 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. + +import six + +import paddle +from paddle.fluid import core, Variable +from paddle.fluid.layer_helper import LayerHelper +from paddle.fluid.data_feeder import check_type +from paddle.fluid.framework import convert_np_dtype_to_dtype_ +from paddle.fluid.framework import static_only + +__all__ = [] + + +@static_only +def data(name, shape, dtype=None, lod_level=0): + """ + **Data Layer** + + This function creates a variable on the global block. The global variable + can be accessed by all the following operators in the graph. The variable + is a placeholder that could be fed with input, such as Executor can feed + input into the variable. When `dtype` is None, the dtype + will get from the global dtype by `paddle.get_default_dtype()`. + + Args: + name (str): The name/alias of the variable, see :ref:`api_guide_Name` + for more details. + shape (list|tuple): List|Tuple of integers declaring the shape. You can + set "None" or -1 at a dimension to indicate the dimension can be of any + size. For example, it is useful to set changeable batch size as "None" or -1. + dtype (np.dtype|str, optional): The type of the data. Supported + dtype: bool, float16, float32, float64, int8, int16, int32, int64, + uint8. Default: None. When `dtype` is not set, the dtype will get + from the global dtype by `paddle.get_default_dtype()`. + lod_level (int, optional): The LoD level of the LoDTensor. Usually users + don't have to set this value. For more details about when and how to + use LoD level, see :ref:`user_guide_lod_tensor` . Default: 0. + + Returns: + Variable: The global variable that gives access to the data. + + Examples: + .. code-block:: python + + import numpy as np + import paddle + paddle.enable_static() + + # Creates a variable with fixed size [3, 2, 1] + # User can only feed data of the same shape to x + # the dtype is not set, so it will set "float32" by + # paddle.get_default_dtype(). You can use paddle.get_default_dtype() to + # change the global dtype + x = paddle.static.data(name='x', shape=[3, 2, 1]) + + # Creates a variable with changeable batch size -1. + # Users can feed data of any batch size into y, + # but size of each data sample has to be [2, 1] + y = paddle.static.data(name='y', shape=[-1, 2, 1], dtype='float32') + + z = x + y + + # In this example, we will feed x and y with np-ndarray "1" + # and fetch z, like implementing "1 + 1 = 2" in PaddlePaddle + feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32) + + exe = paddle.static.Executor(paddle.framework.CPUPlace()) + out = exe.run(paddle.static.default_main_program(), + feed={ + 'x': feed_data, + 'y': feed_data + }, + fetch_list=[z.name]) + + # np-ndarray of shape=[3, 2, 1], dtype=float32, whose elements are 2 + print(out) + + """ + helper = LayerHelper('data', **locals()) + check_type(name, 'name', (six.binary_type, six.text_type), 'data') + check_type(shape, 'shape', (list, tuple), 'data') + + shape = list(shape) + for i in six.moves.range(len(shape)): + if shape[i] is None: + shape[i] = -1 + + if dtype: + return helper.create_global_variable( + name=name, + shape=shape, + dtype=dtype, + type=core.VarDesc.VarType.LOD_TENSOR, + stop_gradient=True, + lod_level=lod_level, + is_data=True, + need_check_feed=True, + ) + else: + return helper.create_global_variable( + name=name, + shape=shape, + dtype=paddle.get_default_dtype(), + type=core.VarDesc.VarType.LOD_TENSOR, + stop_gradient=True, + lod_level=lod_level, + is_data=True, + need_check_feed=True, + ) + + +class InputSpec(object): + """ + InputSpec describes the signature information of the model input, such as ``shape`` , ``dtype`` , ``name`` . + + This interface is often used to specify input tensor information of models in high-level API. + It's also used to specify the tensor information for each input parameter of the forward function + decorated by `@paddle.jit.to_static`. + + Args: + shape (tuple(integers)|list[integers]): List|Tuple of integers + declaring the shape. You can set "None" or -1 at a dimension + to indicate the dimension can be of any size. For example, + it is useful to set changeable batch size as "None" or -1. + dtype (np.dtype|str, optional): The type of the data. Supported + dtype: bool, float16, float32, float64, int8, int16, int32, int64, + uint8. Default: float32. + name (str): The name/alias of the variable, see :ref:`api_guide_Name` + for more details. + + Examples: + .. code-block:: python + + from paddle.static import InputSpec + + input = InputSpec([None, 784], 'float32', 'x') + label = InputSpec([None, 1], 'int64', 'label') + + print(input) # InputSpec(shape=(-1, 784), dtype=paddle.float32, name=x) + print(label) # InputSpec(shape=(-1, 1), dtype=paddle.int64, name=label) + """ + + def __init__(self, shape, dtype='float32', name=None): + # replace `None` in shape with -1 + self.shape = self._verify(shape) + # convert dtype into united represention + if dtype is not None: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + self.dtype = dtype + self.name = name + + def _create_feed_layer(self): + return data(self.name, shape=self.shape, dtype=self.dtype) + + def __repr__(self): + return '{}(shape={}, dtype={}, name={})'.format( + type(self).__name__, self.shape, self.dtype, self.name + ) + + @classmethod + def from_tensor(cls, tensor, name=None): + """ + Generates a InputSpec based on the description of input tensor. + + Args: + tensor(Tensor): the source tensor to generate a InputSpec instance + + Returns: + A InputSpec instance generated from Tensor. + + Examples: + .. code-block:: python + + import paddle + from paddle.static import InputSpec + + paddle.disable_static() + + x = paddle.ones([2, 2], dtype="float32") + x_spec = InputSpec.from_tensor(x, name='x') + print(x_spec) # InputSpec(shape=(2, 2), dtype=paddle.float32, name=x) + + """ + if isinstance(tensor, (Variable, core.VarBase, core.eager.Tensor)): + return cls(tensor.shape, tensor.dtype, name or tensor.name) + else: + raise ValueError( + "Input `tensor` should be a Tensor, but received {}.".format( + type(tensor).__name__ + ) + ) + + @classmethod + def from_numpy(cls, ndarray, name=None): + """ + Generates a InputSpec based on the description of input np.ndarray. + + Args: + tensor(Tensor): the source numpy ndarray to generate a InputSpec instance + + Returns: + A InputSpec instance generated from Tensor. + + Examples: + .. code-block:: python + + import numpy as np + from paddle.static import InputSpec + + x = np.ones([2, 2], np.float32) + x_spec = InputSpec.from_numpy(x, name='x') + print(x_spec) # InputSpec(shape=(2, 2), dtype=paddle.float32, name=x) + + """ + return cls(ndarray.shape, ndarray.dtype, name) + + def batch(self, batch_size): + """ + Inserts `batch_size` in front of the `shape`. + + Args: + batch_size(int): the inserted integer value of batch size. + + Returns: + The original InputSpec instance by inserting `batch_size` in front of `shape`. + + Examples: + .. code-block:: python + + from paddle.static import InputSpec + + x_spec = InputSpec(shape=[64], dtype='float32', name='x') + x_spec.batch(4) + print(x_spec) # InputSpec(shape=(4, 64), dtype=paddle.float32, name=x) + + """ + if isinstance(batch_size, (list, tuple)): + if len(batch_size) != 1: + raise ValueError( + "Length of batch_size: {} shall be 1, but received {}.".format( + batch_size, len(batch_size) + ) + ) + batch_size = batch_size[1] + elif not isinstance(batch_size, six.integer_types): + raise TypeError( + "type(batch_size) shall be `int`, but received {}.".format( + type(batch_size).__name__ + ) + ) + + new_shape = [batch_size] + list(self.shape) + self.shape = tuple(new_shape) + + return self + + def unbatch(self): + """ + Removes the first element of `shape`. + + Returns: + The original InputSpec instance by removing the first element of `shape` . + + Examples: + .. code-block:: python + + from paddle.static import InputSpec + + x_spec = InputSpec(shape=[4, 64], dtype='float32', name='x') + x_spec.unbatch() + print(x_spec) # InputSpec(shape=(64,), dtype=paddle.float32, name=x) + + """ + if len(self.shape) == 0: + raise ValueError( + "Not support to unbatch a InputSpec when len(shape) == 0." + ) + + self.shape = self._verify(self.shape[1:]) + return self + + def _verify(self, shape): + """ + Verifies the input shape and modifies `None` into `-1`. + """ + if not isinstance(shape, (list, tuple)): + raise TypeError( + "Type of `shape` in InputSpec should be one of (tuple, list), but received {}.".format( + type(shape).__name__ + ) + ) + if len(shape) == 0: + raise ValueError( + "`shape` in InputSpec should contain at least 1 element, but received {}.".format( + shape + ) + ) + + for i, ele in enumerate(shape): + if ele is not None: + if not isinstance(ele, six.integer_types): + raise ValueError( + "shape[{}] should be an `int`, but received `{}`:{}.".format( + i, type(ele).__name__, ele + ) + ) + if ele is None or ele < -1: + shape[i] = -1 + + return tuple(shape) + + def __hash__(self): + # Note(Aurelius84): `name` is not considered as a field to compute hashkey. + # Because it's no need to generate a new program in following cases while using + # @paddle.jit.to_static. + # + # Case 1: + # foo(x_var) + # foo(y_var) + # x_var and y_var hold same shape and dtype, they should share a same program. + # + # + # Case 2: + # foo(x_var) + # foo(x_np) # x_np is a numpy.ndarray. + # x_var and x_np hold same shape and dtype, they should also share a same program. + return hash((tuple(self.shape), self.dtype)) + + def __eq__(self, other): + slots = ['shape', 'dtype', 'name'] + return type(self) is type(other) and all( + getattr(self, attr) == getattr(other, attr) for attr in slots + ) + + def __ne__(self, other): + return not self == other diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/io.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/io.py new file mode 100644 index 0000000000000000000000000000000000000000..b880da6abc59db4ff77b454b028e4387e2f7096a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/io.py @@ -0,0 +1,884 @@ +# Copyright (c) 2018 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. + +from __future__ import print_function + +import errno +import inspect +import logging +import os +import warnings +import six +import numpy as np + +import paddle +from paddle.fluid import ( + core, + Variable, + CompiledProgram, + default_main_program, + Program, + layers, + unique_name, + program_guard, +) +from paddle.fluid.io import prepend_feed_ops, append_fetch_ops +from paddle.fluid.framework import static_only, Parameter +from paddle.fluid.executor import Executor, global_scope +from paddle.fluid.log_helper import get_logger + +__all__ = [] + +_logger = get_logger( + __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s' +) + + +def _check_args(caller, args, supported_args=None, deprecated_args=None): + supported_args = [] if supported_args is None else supported_args + deprecated_args = [] if deprecated_args is None else deprecated_args + for arg in args: + if arg in deprecated_args: + raise ValueError( + "argument '{}' in function '{}' is deprecated, only {} are supported.".format( + arg, caller, supported_args + ) + ) + elif arg not in supported_args: + raise ValueError( + "function '{}' doesn't support argument '{}',\n only {} are supported.".format( + caller, arg, supported_args + ) + ) + + +def _check_vars(name, var_list): + if not isinstance(var_list, list): + var_list = [var_list] + if not var_list or not all([isinstance(var, Variable) for var in var_list]): + raise ValueError( + "'{}' should be a Variable or a list of Variable.".format(name) + ) + + +def _normalize_path_prefix(path_prefix): + """ + convert path_prefix to absolute path. + """ + if not isinstance(path_prefix, six.string_types): + raise ValueError("'path_prefix' should be a string.") + if path_prefix.endswith("/"): + raise ValueError("'path_prefix' should not be a directory") + path_prefix = os.path.normpath(path_prefix) + path_prefix = os.path.abspath(path_prefix) + return path_prefix + + +def _get_valid_program(program=None): + """ + return default main program if program is None. + """ + if program is None: + program = default_main_program() + elif isinstance(program, CompiledProgram): + program = program._program + if program is None: + raise TypeError( + "The type of input program is invalid, expected tyep is Program, but received None" + ) + warnings.warn( + "The input is a CompiledProgram, this is not recommended." + ) + if not isinstance(program, Program): + raise TypeError( + "The type of input program is invalid, expected type is fluid.Program, but received %s" + % type(program) + ) + return program + + +def _clone_var_in_block(block, var): + assert isinstance(var, Variable) + if var.desc.type() == core.VarDesc.VarType.LOD_TENSOR: + return block.create_var( + name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + lod_level=var.lod_level, + persistable=True, + ) + else: + return block.create_var( + name=var.name, + shape=var.shape, + dtype=var.dtype, + type=var.type, + persistable=True, + ) + + +def normalize_program(program, feed_vars, fetch_vars): + """ + :api_attr: Static Graph + + Normalize/Optimize a program according to feed_vars and fetch_vars. + + Args: + program(Program): Specify a program you want to optimize. + feed_vars(Variable | list[Variable]): Variables needed by inference. + fetch_vars(Variable | list[Variable]): Variables returned by inference. + + Returns: + Program: Normalized/Optimized program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # normalize main program. + program = paddle.static.default_main_program() + normalized_program = paddle.static.normalize_program(program, [image], [predict]) + + """ + if not isinstance(program, Program): + raise TypeError( + "program type must be `fluid.Program`, but received `%s`" + % type(program) + ) + if not isinstance(feed_vars, list): + feed_vars = [feed_vars] + if not all(isinstance(v, Variable) for v in feed_vars): + raise TypeError( + "feed_vars type must be a Variable or a list of Variable." + ) + if not isinstance(fetch_vars, list): + fetch_vars = [fetch_vars] + if not all(isinstance(v, Variable) for v in fetch_vars): + raise TypeError( + "fetch_vars type must be a Variable or a list of Variable." + ) + + # remind users to set auc_states to 0 if auc op were found. + for op in program.global_block().ops: + # clear device of Op + device_attr_name = core.op_proto_and_checker_maker.kOpDeviceAttrName() + op._set_attr(device_attr_name, "") + if op.type == 'auc': + warnings.warn( + "Be sure that you have set auc states to 0 " + "before saving inference model." + ) + break + + # fix the bug that the activation op's output as target will be pruned. + # will affect the inference performance. + # TODO(Superjomn) add an IR pass to remove 1-scale op. + with program_guard(program): + uniq_fetch_vars = [] + for i, var in enumerate(fetch_vars): + if var.dtype != paddle.bool: + var = layers.scale( + var, 1.0, name="save_infer_model/scale_{}".format(i) + ) + uniq_fetch_vars.append(var) + fetch_vars = uniq_fetch_vars + + # serialize program + copy_program = program.clone() + global_block = copy_program.global_block() + remove_op_idx = [] + for i, op in enumerate(global_block.ops): + op.desc.set_is_target(False) + if op.type == "feed" or op.type == "fetch": + remove_op_idx.append(i) + for idx in remove_op_idx[::-1]: + global_block._remove_op(idx) + copy_program.desc.flush() + + feed_var_names = [var.name for var in feed_vars] + copy_program = copy_program._prune_with_input( + feeded_var_names=feed_var_names, targets=fetch_vars + ) + copy_program = copy_program._inference_optimize(prune_read_op=True) + fetch_var_names = [var.name for var in fetch_vars] + prepend_feed_ops(copy_program, feed_var_names) + append_fetch_ops(copy_program, fetch_var_names) + copy_program.desc._set_version() + return copy_program + + +def is_persistable(var): + """ + Check whether the given variable is persistable. + + Args: + var(Variable): The variable to be checked. + + Returns: + bool: True if the given `var` is persistable + False if not. + + Examples: + .. code-block:: python + + import paddle + import paddle.fluid as fluid + + paddle.enable_static() + param = fluid.default_main_program().global_block().var('fc.b') + res = fluid.io.is_persistable(param) + """ + if ( + var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH + or var.desc.type() == core.VarDesc.VarType.FETCH_LIST + or var.desc.type() == core.VarDesc.VarType.READER + ): + return False + return var.persistable + + +@static_only +def serialize_program(feed_vars, fetch_vars, **kwargs): + """ + :api_attr: Static Graph + + Serialize default main program according to feed_vars and fetch_vars. + + Args: + feed_vars(Variable | list[Variable]): Variables needed by inference. + fetch_vars(Variable | list[Variable]): Variables returned by inference. + kwargs: Supported keys including 'program'.Attention please, kwargs is used for backward compatibility mainly. + - program(Program): specify a program if you don't want to use default main program. + + Returns: + bytes: serialized program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # serialize the default main program to bytes. + serialized_program = paddle.static.serialize_program([image], [predict]) + + # deserialize bytes to program + deserialized_program = paddle.static.deserialize_program(serialized_program) + + """ + # verify feed_vars + _check_vars('feed_vars', feed_vars) + # verify fetch_vars + _check_vars('fetch_vars', fetch_vars) + + program = _get_valid_program(kwargs.get('program', None)) + program = normalize_program(program, feed_vars, fetch_vars) + return _serialize_program(program) + + +def _serialize_program(program): + """ + serialize given program to bytes. + """ + return program.desc.serialize_to_string() + + +@static_only +def serialize_persistables(feed_vars, fetch_vars, executor, **kwargs): + """ + :api_attr: Static Graph + + Serialize parameters using given executor and default main program according to feed_vars and fetch_vars. + + Args: + feed_vars(Variable | list[Variable]): Variables needed by inference. + fetch_vars(Variable | list[Variable]): Variables returned by inference. + kwargs: Supported keys including 'program'.Attention please, kwargs is used for backward compatibility mainly. + - program(Program): specify a program if you don't want to use default main program. + + Returns: + bytes: serialized program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # serialize parameters to bytes. + serialized_params = paddle.static.serialize_persistables([image], [predict], exe) + + # deserialize bytes to parameters. + main_program = paddle.static.default_main_program() + deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe) + + """ + # verify feed_vars + _check_vars('feed_vars', feed_vars) + # verify fetch_vars + _check_vars('fetch_vars', fetch_vars) + + program = _get_valid_program(kwargs.get('program', None)) + program = normalize_program(program, feed_vars, fetch_vars) + return _serialize_persistables(program, executor) + + +def _serialize_persistables(program, executor): + """ + Serialize parameters using given program and executor. + """ + vars_ = list(filter(is_persistable, program.list_vars())) + # warn if no variable found in model + if len(vars_) == 0: + warnings.warn( + "no variable in your model, please ensure there are any " + "variables in your model to save" + ) + return None + # create a new program and clone persitable vars to it + save_program = Program() + save_block = save_program.global_block() + save_var_map = {} + for var in vars_: + if var.type != core.VarDesc.VarType.RAW: + var_copy = _clone_var_in_block(save_block, var) + save_var_map[var_copy.name] = var + + # create in_vars and out_var, then append a save_combine op to save_program + in_vars = [] + for name in sorted(save_var_map.keys()): + in_vars.append(save_var_map[name]) + + out_var_name = unique_name.generate("out_var") + out_var = save_block.create_var( + type=core.VarDesc.VarType.RAW, name=out_var_name + ) + out_var.desc.set_persistable(True) + save_block.append_op( + type='save_combine', + inputs={'X': in_vars}, + outputs={'Y': out_var}, + attrs={'file_path': '', 'save_to_memory': True}, + ) + # run save_program to save vars + # NOTE(zhiqiu): save op will add variable kLookupTablePath to save_program.desc, + # which leads to diff between save_program and its desc. Call _sync_with_cpp + # to keep consistency. + save_program._sync_with_cpp() + executor.run(save_program) + # return serialized bytes in out_var + return global_scope().find_var(out_var_name).get_bytes() + + +def save_to_file(path, content): + """ + Save content to given path. + Args: + path(str): Path to write content to. + content(bytes): Content to write. + Returns: + None + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + path_prefix = "./infer_model" + # 用户自定义网络,此处用 softmax 回归为例。 + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + loss = paddle.nn.functional.cross_entropy(predict, label) + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + # 序列化参数 + serialized_params = paddle.static.serialize_persistables([image], [predict], exe) + # 将序列化之后的参数保存到文件 + params_path = path_prefix + ".params" + paddle.static.save_to_file(params_path, serialized_params) + """ + + if not isinstance(content, bytes): + raise ValueError("'content' type should be bytes.") + with open(path, "wb") as f: + f.write(content) + + +@static_only +def save_inference_model( + path_prefix, feed_vars, fetch_vars, executor, **kwargs +): + """ + Save current model and its parameters to given path. i.e. + Given path_prefix = "/path/to/modelname", after invoking + save_inference_model(path_prefix, feed_vars, fetch_vars, executor), + you will find two files named modelname.pdmodel and modelname.pdiparams + under "/path/to", which represent your model and parameters respectively. + + Args: + path_prefix(str): Directory path to save model + model name without suffix. + feed_vars(Variable | list[Variable]): Variables needed by inference. + fetch_vars(Variable | list[Variable]): Variables returned by inference. + executor(Executor): The executor that saves the inference model. You can refer + to :ref:`api_guide_executor_en` for more details. + kwargs: Supported keys including 'program' and "clip_extra". Attention please, kwargs is used for backward compatibility mainly. + + - program(Program): specify a program if you don't want to use default main program. + + - clip_extra(bool): the flag indicating whether to clip extra information for every operator. Default: True. + + Returns: + None + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # Feed data and train process + + # Save inference model. Note we don't save label and loss in this example + paddle.static.save_inference_model(path_prefix, [image], [predict], exe) + + # In this example, the save_inference_mode inference will prune the default + # main program according to the network's input node (img) and output node(predict). + # The pruned inference program is going to be saved in file "./infer_model.pdmodel" + # and parameters are going to be saved in file "./infer_model.pdiparams". + + """ + + # check path_prefix, set model_path and params_path + path_prefix = _normalize_path_prefix(path_prefix) + try: + # mkdir may conflict if pserver and trainer are running on the same machine + dirname = os.path.dirname(path_prefix) + os.makedirs(dirname) + except OSError as e: + if e.errno != errno.EEXIST: + raise + model_path = path_prefix + ".pdmodel" + params_path = path_prefix + ".pdiparams" + if os.path.isdir(model_path): + raise ValueError("'{}' is an existing directory.".format(model_path)) + if os.path.isdir(params_path): + raise ValueError("'{}' is an existing directory.".format(params_path)) + + # verify feed_vars + _check_vars('feed_vars', feed_vars) + # verify fetch_vars + _check_vars('fetch_vars', fetch_vars) + + program = _get_valid_program(kwargs.get('program', None)) + clip_extra = kwargs.get('clip_extra', True) + program = normalize_program(program, feed_vars, fetch_vars) + # serialize and save program + program_bytes = _serialize_program( + program._remove_training_info(clip_extra=clip_extra) + ) + save_to_file(model_path, program_bytes) + # serialize and save params + params_bytes = _serialize_persistables(program, executor) + # program may not contain any parameter and just compute operation + if params_bytes is not None: + save_to_file(params_path, params_bytes) + + +@static_only +def deserialize_program(data): + """ + :api_attr: Static Graph + + Deserialize given data to a program. + + Args: + data(bytes): serialized program. + + Returns: + Program: deserialized program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # serialize the default main program to bytes. + serialized_program = paddle.static.serialize_program([image], [predict]) + + # deserialize bytes to program + deserialized_program = paddle.static.deserialize_program(serialized_program) + + """ + program = Program.parse_from_string(data) + if not core._is_program_version_supported(program._version()): + raise ValueError( + "Unsupported program version: %d\n" % program._version() + ) + return program + + +@static_only +def deserialize_persistables(program, data, executor): + """ + :api_attr: Static Graph + + Deserialize given data to parameters according to given program and executor. + + Args: + program(Program): program that contains parameter names (to deserialize). + data(bytes): serialized parameters. + executor(Executor): executor used to run load op. + + Returns: + Program: deserialized program. + + Examples: + .. code-block:: python + + import paddle + + paddle.enable_static() + + path_prefix = "./infer_model" + + # User defined network, here a softmax regession example + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + + loss = paddle.nn.functional.cross_entropy(predict, label) + + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + + # serialize parameters to bytes. + serialized_params = paddle.static.serialize_persistables([image], [predict], exe) + + # deserialize bytes to parameters. + main_program = paddle.static.default_main_program() + deserialized_params = paddle.static.deserialize_persistables(main_program, serialized_params, exe) + + + """ + if not isinstance(program, Program): + raise TypeError( + "program type must be `fluid.Program`, but received `%s`" + % type(program) + ) + # load params to a tmp program + load_program = Program() + load_block = load_program.global_block() + vars_ = list(filter(is_persistable, program.list_vars())) + + origin_shape_map = {} + load_var_map = {} + check_vars = [] + sparse_vars = [] + for var in vars_: + assert isinstance(var, Variable) + if var.type == core.VarDesc.VarType.RAW: + continue + if isinstance(var, Parameter): + origin_shape_map[var.name] = tuple(var.desc.get_shape()) + if var.type == core.VarDesc.VarType.SELECTED_ROWS: + sparse_vars.append(var) + continue + var_copy = _clone_var_in_block(load_block, var) + check_vars.append(var) + load_var_map[var_copy.name] = var_copy + + if data is None: + assert ( + len(origin_shape_map) == 0 + ), "Required 'data' shall be not None if program contains parameter, but received 'data' is None." + return + + # append load_combine op to load parameters, + load_var_list = [] + for name in sorted(load_var_map.keys()): + load_var_list.append(load_var_map[name]) + load_block.append_op( + type='load_combine', + inputs={}, + outputs={"Out": load_var_list}, + # if load from memory, file_path is data + attrs={'file_path': data, 'model_from_memory': True}, + ) + executor.run(load_program) + # check var shape + for var in check_vars: + if not isinstance(var, Parameter): + continue + var_tmp = paddle.fluid.global_scope().find_var(var.name) + assert var_tmp != None, "can't not find var: " + var.name + new_shape = (np.array(var_tmp.get_tensor())).shape + assert var.name in origin_shape_map, var.name + " MUST in var list." + origin_shape = origin_shape_map.get(var.name) + if new_shape != origin_shape: + raise RuntimeError( + "Shape mismatch, program needs a parameter with shape ({}), " + "but the loaded parameter ('{}') has a shape of ({}).".format( + origin_shape, var.name, new_shape + ) + ) + + +def load_from_file(path): + """ + Load file in binary mode. + Args: + path(str): Path of an existed file. + Returns: + bytes: Content of file. + + Examples: + + .. code-block:: python + + import paddle + paddle.enable_static() + path_prefix = "./infer_model" + # 用户自定义网络,此处用 softmax 回归为例。 + image = paddle.static.data(name='img', shape=[None, 28, 28], dtype='float32') + label = paddle.static.data(name='label', shape=[None, 1], dtype='int64') + predict = paddle.static.nn.fc(image, 10, activation='softmax') + loss = paddle.nn.functional.cross_entropy(predict, label) + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(paddle.static.default_startup_program()) + # 序列化参数 + serialized_params = paddle.static.serialize_persistables([image], [predict], exe) + # 将序列化之后的参数保存到文件 + params_path = path_prefix + ".params" + paddle.static.save_to_file(params_path, serialized_params) + # 从文件加载序列化之后的参数 + serialized_params_copy = paddle.static.load_from_file(params_path) + """ + with open(path, 'rb') as f: + data = f.read() + return data + + +@static_only +def load_inference_model(path_prefix, executor, **kwargs): + """ + :api_attr: Static Graph + + Load inference model from a given path. By this API, you can get the model + structure(Inference Program) and model parameters. + + Args: + path_prefix(str | None): One of the following: + - Directory path to save model + model name without suffix. + - Set to None when reading the model from memory. + executor(Executor): The executor to run for loading inference model. + See :ref:`api_guide_executor_en` for more details about it. + kwargs: Supported keys including 'model_filename', 'params_filename'.Attention please, kwargs is used for backward compatibility mainly. + - model_filename(str): specify model_filename if you don't want to use default name. + - params_filename(str): specify params_filename if you don't want to use default name. + + Returns: + list: The return of this API is a list with three elements: + (program, feed_target_names, fetch_targets). The `program` is a + ``Program`` (refer to :ref:`api_guide_Program_en`), which is used for inference. + The `feed_target_names` is a list of ``str``, which contains names of variables + that need to feed data in the inference program. The `fetch_targets` is a list of + ``Variable`` (refer to :ref:`api_guide_Program_en`). It contains variables from which + we can get inference results. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + + paddle.enable_static() + + # Build the model + startup_prog = paddle.static.default_startup_program() + main_prog = paddle.static.default_main_program() + with paddle.static.program_guard(main_prog, startup_prog): + image = paddle.static.data(name="img", shape=[64, 784]) + w = paddle.create_parameter(shape=[784, 200], dtype='float32') + b = paddle.create_parameter(shape=[200], dtype='float32') + hidden_w = paddle.matmul(x=image, y=w) + hidden_b = paddle.add(hidden_w, b) + exe = paddle.static.Executor(paddle.CPUPlace()) + exe.run(startup_prog) + + # Save the inference model + path_prefix = "./infer_model" + paddle.static.save_inference_model(path_prefix, [image], [hidden_b], exe) + + [inference_program, feed_target_names, fetch_targets] = ( + paddle.static.load_inference_model(path_prefix, exe)) + tensor_img = np.array(np.random.random((64, 784)), dtype=np.float32) + results = exe.run(inference_program, + feed={feed_target_names[0]: tensor_img}, + fetch_list=fetch_targets) + + # In this example, the inference program was saved in file + # "./infer_model.pdmodel" and parameters were saved in file + # " ./infer_model.pdiparams". + # By the inference program, feed_target_names and + # fetch_targets, we can use an executor to run the inference + # program to get the inference result. + """ + # check kwargs + supported_args = ('model_filename', 'params_filename') + deprecated_args = ('pserver_endpoints',) + caller = inspect.currentframe().f_code.co_name + _check_args(caller, kwargs, supported_args, deprecated_args) + + # load from memory + if path_prefix is None: + _logger.warning("Load inference model from memory is deprecated.") + model_filename = kwargs.get('model_filename', None) + params_filename = kwargs.get('params_filename', None) + if params_filename is None: + raise ValueError( + "params_filename cannot be None when path_prefix is None." + ) + load_dirname = '' + program_bytes = model_filename + params_bytes = params_filename + # load from file + else: + # check and norm path_prefix + path_prefix = _normalize_path_prefix(path_prefix) + + # set model_path and params_path in new way, + # path_prefix represents a file path without suffix in this case. + if not kwargs: + model_path = path_prefix + ".pdmodel" + params_path = path_prefix + ".pdiparams" + # set model_path and params_path in old way for compatible, + # path_prefix represents a directory path. + else: + model_filename = kwargs.get('model_filename', None) + params_filename = kwargs.get('params_filename', None) + # set model_path + if model_filename is None: + model_path = os.path.join(path_prefix, "__model__") + else: + model_path = os.path.join( + path_prefix, model_filename + ".pdmodel" + ) + if not os.path.exists(model_path): + model_path = os.path.join(path_prefix, model_filename) + # set params_path + if params_filename is None: + params_path = os.path.join(path_prefix, "") + else: + params_path = os.path.join( + path_prefix, params_filename + ".pdiparams" + ) + if not os.path.exists(params_path): + params_path = os.path.join(path_prefix, params_filename) + _logger.warning( + "The old way to load inference model is deprecated." + " model path: {}, params path: {}".format( + model_path, params_path + ) + ) + program_bytes = load_from_file(model_path) + load_dirname = os.path.dirname(params_path) + params_filename = os.path.basename(params_path) + # load params data + params_path = os.path.join(load_dirname, params_filename) + params_bytes = None + if os.path.exists(params_path): + params_bytes = load_from_file(params_path) + + # deserialize bytes to program + program = deserialize_program(program_bytes) + # deserialize bytes to params + deserialize_persistables(program, params_bytes, executor) + + feed_target_names = program.desc.get_feed_target_names() + fetch_target_names = program.desc.get_fetch_target_names() + fetch_targets = [ + program.global_block().var(name) for name in fetch_target_names + ] + + return [program, feed_target_names, fetch_targets] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41f8c99b52644896846e960eff7f550b45863e61 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/__init__.py @@ -0,0 +1,104 @@ +# 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. + +from .common import fc # noqa: F401 +from .common import deform_conv2d # noqa: F401 + +from ...fluid.layers import batch_norm # noqa: F401 +from ...fluid.layers import bilinear_tensor_product # noqa: F401 +from ...fluid.layers import case # noqa: F401 +from ...fluid.layers import cond # noqa: F401 +from ...fluid.layers import conv2d # noqa: F401 +from ...fluid.layers import conv2d_transpose # noqa: F401 +from ...fluid.layers import conv3d # noqa: F401 +from ...fluid.layers import conv3d_transpose # noqa: F401 +from ...fluid.layers import create_parameter # noqa: F401 +from ...fluid.layers import crf_decoding # noqa: F401 +from ...fluid.layers import data_norm # noqa: F401 +from ...fluid.layers import group_norm # noqa: F401 +from ...fluid.layers import instance_norm # noqa: F401 +from ...fluid.layers import layer_norm # noqa: F401 +from ...fluid.layers import multi_box_head # noqa: F401 +from ...fluid.layers import nce # noqa: F401 +from ...fluid.layers import prelu # noqa: F401 +from ...fluid.layers import py_func # noqa: F401 +from ...fluid.layers import row_conv # noqa: F401 +from ...fluid.layers import spectral_norm # noqa: F401 +from ...fluid.layers import switch_case # noqa: F401 +from ...fluid.layers import while_loop # noqa: F401 + +from ...fluid.input import embedding # noqa: F401 +from ...fluid.contrib.layers import sparse_embedding # noqa: F401 +from ...fluid.layers import continuous_value_model # noqa: F401 +from ...fluid.layers import StaticRNN # noqa: F401 + +from ...fluid.layers.sequence_lod import sequence_conv # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_softmax # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_pool # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_concat # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_first_step # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_last_step # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_slice # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_expand # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_expand_as # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_pad # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_unpad # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_reshape # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_scatter # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_enumerate # noqa: F401 +from ...fluid.layers.sequence_lod import sequence_reverse # noqa: F401 + +__all__ = [ #noqa + 'fc', + 'batch_norm', + 'embedding', + 'bilinear_tensor_product', + 'case', + 'cond', + 'conv2d', + 'conv2d_transpose', + 'conv3d', + 'conv3d_transpose', + 'crf_decoding', + 'data_norm', + 'deform_conv2d', + 'group_norm', + 'instance_norm', + 'layer_norm', + 'multi_box_head', + 'nce', + 'prelu', + 'py_func', + 'row_conv', + 'spectral_norm', + 'switch_case', + 'while_loop', + 'sparse_embedding', + 'sequence_conv', + 'sequence_softmax', + 'sequence_pool', + 'sequence_concat', + 'sequence_first_step', + 'sequence_last_step', + 'sequence_slice', + 'sequence_expand', + 'sequence_expand_as', + 'sequence_pad', + 'sequence_unpad', + 'sequence_reshape', + 'sequence_scatter', + 'sequence_enumerate', + 'sequence_reverse', + 'StaticRNN', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/common.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/common.py new file mode 100644 index 0000000000000000000000000000000000000000..98c5e81a2e8e063243cc994cefcdbff1da09fc1c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/nn/common.py @@ -0,0 +1,346 @@ +# 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. + +import paddle +from paddle.fluid.framework import static_only + +__all__ = [] + + +@static_only +def fc( + x, + size, + num_flatten_dims=1, + weight_attr=None, + bias_attr=None, + activation=None, + name=None, +): + r""" + + Fully-Connected layer can take a tensor or a list of tensor as its inputs. + It creates a 2-D weight tensor for each input tensor, which represents its + weight matrix from each input unit to each output unit. The fully connected + layer multiplies each input tensor with its corresponding weight to produce + an output tensor with shape :math:`[batch\_size, *, size]` , where :math:`*` + means any number of additional dimensions. If a list of tensor is given, + the results of multiple output tensors with shape :math:`[batch\_size, *, size]` + will be summed up. If :attr:`bias_attr` is not False, a 1-D bias tensor will + be created and added to the output. Finally, if :attr:`activation` is not None, + it will be applied to the output as well. + + For a single input tensor :math:`X` , the equation is: + + .. math:: + + Out = Act({XW + b}) + + For a list of input tensor, the equation is: + + .. math:: + + Out = Act({\sum_{i=0}^{N-1}X_iW_i + b}) + + where: + + * :math:`N`: The number of the input tensors. :math:`N` equals to :math:`len(X)` if :math:`X` is list of tensor. + * :math:`X_i`: The i-th input tensor. + * :math:`W_i`: The i-th weight matrix corresponding i-th input tensor. + * :math:`b`: The bias created by this layer (if needed). + * :math:`Act`: The activation function. + * :math:`Out`: The output tensor. + + .. code-block:: text + + # Case 1, input is a single tensor: + x.data = [[[0.1, 0.2], + [0.3, 0.4]]] + x.shape = (1, 2, 2) # 1 is batch_size + + out = paddle.static.nn.fc(x=x, size=1, num_flatten_dims=2) + + # Get the output: + out.data = [[0.83234344], [0.34936576]] + out.shape = (1, 2, 1) + + # Case 2, input is a list of tensor: + x0.data = [[[0.1, 0.2], + [0.3, 0.4]]] + x0.shape = (1, 2, 2) # 1 is batch_size + + x1.data = [[[0.1, 0.2, 0.3]]] + x1.shape = (1, 1, 3) + + out = paddle.static.nn.fc(x=[x0, x1], size=2) + + # Get the output: + out.data = [[0.18669507, 0.1893476]] + out.shape = (1, 2) + + Args: + x (Tensor|list[Tensor]|tuple[Tensor]): A tensor or a list/tuple of tensors. The number of dimensions + of each tensor is at least 2. The data type should be float16, float32 or float64. + size (int): The number of output units in this layer, which also means the feature + size of output tensor. + num_flatten_dims (int, optional): The fc layer can accept an input tensor with more than + two dimensions. If this happens, the multi-dimensional tensor will first be flattened + into a 2-D matrix. The parameter :attr:`num_flatten_dims` determines how the input + tensor is flattened: the first :math:`num\_flatten\_dims` (inclusive, index starts from 1) + dimensions will be flatten to form the first dimension of the final matrix (height of + the matrix), and the rest :math:`rank(x) - num\_flatten\_dims` dimensions are + flattened to form the second dimension of the final matrix (width of the matrix). + For example, assuming that :attr:`x` is a 5-dimensional tensor with a shape + :math:`[2, 3, 4, 5, 6]` , and :attr:`num_flatten_dims` = 3. + Then, the flattened matrix will have a shape :math:`[2 * 3 * 4, 5 * 6] = [24, 30]` . + Default: 1. + weight_attr (ParamAttr, optional): The attribute for the learnable weight. + The default value is None, and the weight will be initialized to zero. + For detailed information, please refer to :attr:`paddle.ParamAttr`. + Warning, if x is a list of tensor, weight_attr should also be a list of same length. + bias_attr (ParamAttr|bool, optional): The attribute of the learnable bias. + If it is set to False, no bias will be added to the output. + If it is set to None or one kind of ParamAttr, a bias parameter will + be created according to ParamAttr. For detailed information, please refer + to :attr:`paddle.ParamAttr`. The default value is None and the bias will be + initialized to zero. + activation (str, optional): Activation to be applied to the output of + this layer, such as tanh, softmax, sigmoid, relu. For more information, + please refer to :ref:`api_guide_activations_en` . Default: None. + name (str, optional): The default value is None. Normally there is no need for user to set + it. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor, its shape is :math:`[batch\_size, *, size]` , and the data type is same with input. + + Examples: + .. code-block:: python + + import paddle + paddle.enable_static() + + # When input is a single tensor + x = paddle.static.data(name="x", shape=[1, 2, 2], dtype="float32") + # x: [[[0.1 0.2] + # [0.3 0.4]]] + out = paddle.static.nn.fc( + x=x, + size=1, + num_flatten_dims=2, + weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)), + bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0))) + # out: [[[1.15] + # [1.35]]] + + # When input is multiple tensors + x0 = paddle.static.data(name="x0", shape=[1, 2, 2], dtype="float32") + # x0: [[[0.1 0.2] + # [0.3 0.4]]] + x1 = paddle.static.data(name="x1", shape=[1, 1, 3], dtype="float32") + # x1: [[[0.1 0.2 0.3]]] + out = paddle.static.nn.fc( + x=[x0, x1], + size=2, + weight_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=0.5)), + bias_attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0))) + # out: [[1.8 1.8]] + """ + return paddle.fluid.layers.fc( + input=x, + size=size, + num_flatten_dims=num_flatten_dims, + param_attr=weight_attr, + bias_attr=bias_attr, + act=activation, + name=name, + ) + + +@static_only +def deform_conv2d( + x, + offset, + mask, + num_filters, + filter_size, + stride=1, + padding=0, + dilation=1, + groups=1, + deformable_groups=1, + im2col_step=1, + weight_attr=None, + bias_attr=None, + name=None, +): + r""" + + Compute 2-D deformable convolution on 4-D input. + Given input image x, output feature map y, the deformable convolution operation can be expressed as follow: + + + Deformable Convolution v2: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k} + + Deformable Convolution v1: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)} + + Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location, + Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results + `_ and `Deformable Convolutional Networks `_. + + Example: + - Input: + + X shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + Filter shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + Offset shape: :math:`(N, 2 * deformable\_groups * H_f * H_w, H_{in}, W_{in})` + + Mask shape: :math:`(N, deformable\_groups * H_f * H_w, H_{in}, W_{in})` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Args: + x (Tensor): The input image with [N, C, H, W] format. A Tensor with type + float32, float64. + offset (Tensor): The input coordinate offset of deformable convolution layer. + A Tensor with type float32, float64. + mask (Tensor, Optional): The input mask of deformable convolution layer. + A Tensor with type float32, float64. It should be None when you use + deformable convolution v1. + num_filters(int): The number of filter. It is as same as the output + image channel. + filter_size (int|list|tuple): The filter size. If filter_size is a list/tuple, + it must contain two integers, (filter_size_H, filter_size_W). + Otherwise, the filter will be a square. + stride (int|list|tuple, Optional): The stride size. If stride is a list/tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: stride = 1. + padding (int|list|tuple, Optional): The padding size. If padding is a list/tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: padding = 0. + dilation (int|list|tuple, Optional): The dilation size. If dilation is a list/tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: dilation = 1. + groups (int, Optional): The groups number of the deformable conv layer. According to + grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + deformable_groups (int, Optional): The number of deformable group partitions. + Default: deformable_groups = 1. + im2col_step (int, Optional): Maximum number of images per im2col computation; + The total batch size should be devisable by this value or smaller + than this value; if you face out of memory problem, you can try + to use a smaller value here. + Default: im2col_step = 1. + weight_attr (ParamAttr, Optional): The parameter attribute for learnable parameters/weights + of deformable conv. If it is set to None or one attribute of ParamAttr, + deformable conv will create ParamAttr as weight_attr. + If the Initializer of the weight_attr is not set, the parameter is + initialized with :math:`Normal(0.0, std)`, and the + :math:`std` is :math:`(\\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None. + bias_attr (ParamAttr|bool, Optional): The parameter attribute for the bias of + deformable conv layer. If it is set to False, no bias will be added + to the output units. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. Default: None. + name(str, Optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + Returns: + Tensor: The tensor storing the deformable convolution \ + result. A Tensor with type float32, float64. + + Examples: + .. code-block:: python + + #deformable conv v2: + + import paddle + paddle.enable_static() + + C_in, H_in, W_in = 3, 32, 32 + filter_size, deformable_groups = 3, 1 + data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') + offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + mask = paddle.static.data(name='mask', shape=[None, deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + out = paddle.static.nn.deform_conv2d(x=data, offset=offset, mask=mask, + num_filters=2, filter_size=filter_size, padding=1) + + #deformable conv v1: + + import paddle + paddle.enable_static() + + C_in, H_in, W_in = 3, 32, 32 + filter_size, deformable_groups = 3, 1 + data = paddle.static.data(name='data', shape=[None, C_in, H_in, W_in], dtype='float32') + offset = paddle.static.data(name='offset', shape=[None, 2*deformable_groups*filter_size**2, H_in, W_in], dtype='float32') + out = paddle.static.nn.deform_conv2d(x=data, offset=offset, mask=None, + num_filters=2, filter_size=filter_size, padding=1) + """ + + if mask is None: + return paddle.fluid.layers.deformable_conv( + input=x, + offset=offset, + mask=mask, + num_filters=num_filters, + filter_size=filter_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + deformable_groups=deformable_groups, + im2col_step=im2col_step, + param_attr=weight_attr, + bias_attr=bias_attr, + modulated=False, + name=name, + ) + else: + return paddle.fluid.layers.deformable_conv( + input=x, + offset=offset, + mask=mask, + num_filters=num_filters, + filter_size=filter_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + deformable_groups=deformable_groups, + im2col_step=im2col_step, + param_attr=weight_attr, + bias_attr=bias_attr, + modulated=True, + name=name, + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/sparsity/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/sparsity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3166b19a099defb54499a63d510758bd6bf95c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/static/sparsity/__init__.py @@ -0,0 +1,32 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright (c) 2021 NVIDIA Corporation. 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. + +from ...fluid.contrib.sparsity import calculate_density #noqa: F401 +from ...fluid.contrib.sparsity import decorate #noqa: F401 +from ...fluid.contrib.sparsity import prune_model #noqa: F401 +from ...fluid.contrib.sparsity import reset_excluded_layers #noqa: F401 +from ...fluid.contrib.sparsity import add_supported_layer #noqa: F401 +from ...fluid.contrib import sparsity #noqa: F401 + + +def set_excluded_layers(main_program, param_names): + sparsity.set_excluded_layers(param_names=param_names, + main_program=main_program) + + +__all__ = [ #noqa + 'calculate_density', 'decorate', 'prune_model', 'set_excluded_layers', + 'reset_excluded_layers', 'add_supported_layer' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sysconfig.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce327c76961ad2febc020ed1a2595b7aad459a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/sysconfig.py @@ -0,0 +1,51 @@ +# 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. + +import os + +__all__ = ['get_include', 'get_lib'] + + +def get_include(): + """ + Get the directory containing the PaddlePaddle C++ header files. + Returns: + The directory as string. + + Examples: + .. code-block:: python + + import paddle + include_dir = paddle.sysconfig.get_include() + + """ + import paddle + return os.path.join(os.path.dirname(paddle.__file__), 'include') + + +def get_lib(): + """ + Get the directory containing the libpaddle_framework. + Returns: + The directory as string. + + Examples: + .. code-block:: python + + import paddle + include_dir = paddle.sysconfig.get_lib() + + """ + import paddle + return os.path.join(os.path.dirname(paddle.__file__), 'libs') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58dfa26cfe377e95cf98a4ca36c0742d7e03ee12 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/__init__.py @@ -0,0 +1,526 @@ +# 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. + +from .attribute import is_complex # noqa: F401 +from .attribute import is_integer # noqa: F401 +from .attribute import rank # noqa: F401 +from .attribute import shape # noqa: F401 +from .attribute import real # noqa: F401 +from .attribute import imag # noqa: F401 +from .attribute import is_floating_point # noqa: F401 +from .creation import to_tensor # noqa: F401 +from .creation import diag # noqa: F401 +from .creation import diagflat # noqa: F401 +from .creation import eye # noqa: F401 +from .creation import linspace # noqa: F401 +from .creation import ones # noqa: F401 +from .creation import ones_like # noqa: F401 +from .creation import zeros # noqa: F401 +from .creation import zeros_like # noqa: F401 +from .creation import arange # noqa: F401 +from .creation import full # noqa: F401 +from .creation import full_like # noqa: F401 +from .creation import triu # noqa: F401 +from .creation import tril # noqa: F401 +from .creation import meshgrid # noqa: F401 +from .creation import empty # noqa: F401 +from .creation import empty_like # noqa: F401 +from .creation import complex # noqa: F401 +from .linalg import matmul # noqa: F401 +from .linalg import dot # noqa: F401 +from .linalg import cov # noqa: F401 +from .linalg import corrcoef # noqa: F401 +from .linalg import norm # noqa: F401 +from .linalg import cond # noqa: F401 +from .linalg import transpose # noqa: F401 +from .linalg import lstsq # noqa: F401 +from .linalg import dist # noqa: F401 +from .linalg import t # noqa: F401 +from .linalg import cross # noqa: F401 +from .linalg import cholesky # noqa: F401 +from .linalg import bmm # noqa: F401 +from .linalg import histogram # noqa: F401 +from .linalg import bincount # noqa: F401 +from .linalg import mv # noqa: F401 +from .linalg import eig # noqa: F401 +from .linalg import matrix_power # noqa: F401 +from .linalg import qr # noqa: F401 +from .linalg import eigvals # noqa: F401 +from .linalg import multi_dot # noqa: F401 +from .linalg import svd # noqa: F401 +from .linalg import eigvalsh # noqa: F401 +from .linalg import eigh # noqa: F401 +from .linalg import pinv # noqa: F401 +from .linalg import solve # noqa: F401 +from .linalg import cholesky_solve # noqa: F401 +from .linalg import lu # noqa: F401 +from .linalg import lu_unpack # noqa: F401 +from .logic import equal # noqa: F401 +from .logic import greater_equal # noqa: F401 +from .logic import greater_than # noqa: F401 +from .logic import is_empty # noqa: F401 +from .logic import less_equal # noqa: F401 +from .logic import less_than # noqa: F401 +from .logic import logical_and # noqa: F401 +from .logic import logical_not # noqa: F401 +from .logic import logical_or # noqa: F401 +from .logic import logical_xor # noqa: F401 +from .logic import bitwise_and # noqa: F401 +from .logic import bitwise_or # noqa: F401 +from .logic import bitwise_xor # noqa: F401 +from .logic import bitwise_not # noqa: F401 +from .logic import not_equal # noqa: F401 +from .logic import allclose # noqa: F401 +from .logic import isclose # noqa: F401 +from .logic import equal_all # noqa: F401 +from .logic import is_tensor # noqa: F401 +from .manipulation import cast # noqa: F401 +from .manipulation import concat # noqa: F401 +from .manipulation import expand # noqa: F401 +from .manipulation import broadcast_to # noqa: F401 +from .manipulation import broadcast_tensors # noqa: F401 +from .manipulation import expand_as # noqa: F401 +from .manipulation import tile # noqa: F401 +from .manipulation import flatten # noqa: F401 +from .manipulation import flatten_ # noqa: F401 +from .manipulation import gather # noqa: F401 +from .manipulation import gather_nd # noqa: F401 +from .manipulation import reshape # noqa: F401 +from .manipulation import reshape_ # noqa: F401 +from .manipulation import flip as reverse # noqa: F401 +from .manipulation import scatter # noqa: F401 +from .manipulation import scatter_ # noqa: F401 +from .manipulation import scatter_nd_add # noqa: F401 +from .manipulation import scatter_nd # noqa: F401 +from .manipulation import shard_index # noqa: F401 +from .manipulation import slice # noqa: F401 +from .manipulation import split # noqa: F401 +from .manipulation import squeeze # noqa: F401 +from .manipulation import squeeze_ # noqa: F401 +from .manipulation import stack # noqa: F401 +from .manipulation import strided_slice # noqa: F401 +from .manipulation import unique # noqa: F401 +from .manipulation import unique_consecutive # noqa: F401 +from .manipulation import unsqueeze # noqa: F401 +from .manipulation import unsqueeze_ # noqa: F401 +from .manipulation import unstack # noqa: F401 +from .manipulation import flip # noqa: F401 +from .manipulation import rot90 # noqa: F401 +from .manipulation import unbind # noqa: F401 +from .manipulation import roll # noqa: F401 +from .manipulation import chunk # noqa: F401 +from .manipulation import tensordot # noqa: F401 +from .manipulation import as_complex # noqa: F401 +from .manipulation import take_along_axis # noqa: F401 +from .manipulation import put_along_axis # noqa: F401 +from .manipulation import put_along_axis_ # noqa: F401 +from .manipulation import as_real # noqa: F401 +from .manipulation import moveaxis # noqa: F401 +from .manipulation import repeat_interleave # noqa: F401 +from .manipulation import index_add # noqa: F401 +from .manipulation import index_add_ # noqa: F401 +from .math import abs # noqa: F401 +from .math import acos # noqa: F401 +from .math import asin # noqa: F401 +from .math import atan # noqa: F401 +from .math import ceil # noqa: F401 +from .math import ceil_ # noqa: F401 +from .math import cos # noqa: F401 +from .math import tan # noqa: F401 +from .math import cosh # noqa: F401 +from .math import cumsum # noqa: F401 +from .math import cumprod # noqa: F401 +from .math import logcumsumexp # noqa: F401 +from .math import logit # noqa: F401 +from .math import exp # noqa: F401 +from .math import exp_ # noqa: F401 +from .math import expm1 # noqa: F401 +from .math import floor # noqa: F401 +from .math import floor_ # noqa: F401 +from .math import increment # noqa: F401 +from .math import log # noqa: F401 +from .math import multiplex # noqa: F401 +from .math import pow # noqa: F401 +from .math import reciprocal # noqa: F401 +from .math import reciprocal_ # noqa: F401 +from .math import round # noqa: F401 +from .math import round_ # noqa: F401 +from .math import rsqrt # noqa: F401 +from .math import rsqrt_ # noqa: F401 +from .math import scale # noqa: F401 +from .math import scale_ # noqa: F401 +from .math import sign # noqa: F401 +from .math import sin # noqa: F401 +from .math import sinh # noqa: F401 +from .math import sqrt # noqa: F401 +from .math import sqrt_ # noqa: F401 +from .math import square # noqa: F401 +from .math import stanh # noqa: F401 +from .math import sum # noqa: F401 +from .math import nansum # noqa: F401 +from .math import nanmean # noqa: F401 +from .math import count_nonzero # noqa: F401 +from .math import tanh # noqa: F401 +from .math import tanh_ # noqa: F401 +from .math import add_n # noqa: F401 +from .math import max # noqa: F401 +from .math import amax # noqa: F401 +from .math import maximum # noqa: F401 +from .math import min # noqa: F401 +from .math import amin # noqa: F401 +from .math import minimum # noqa: F401 +from .math import mm # noqa: F401 +from .math import divide # noqa: F401 +from .math import floor_divide # noqa: F401 +from .math import remainder # noqa: F401 +from .math import remainder_ # noqa: F401 +from .math import mod # noqa: F401 +from .math import floor_mod # noqa: F401 +from .math import multiply # noqa: F401 +from .math import add # noqa: F401 +from .math import add_ # noqa: F401 +from .math import subtract # noqa: F401 +from .math import subtract_ # noqa: F401 +from .math import atan2 # noqa: F401 +from .math import logsumexp # noqa: F401 +from .math import inverse # noqa: F401 +from .math import log2 # noqa: F401 +from .math import log10 # noqa: F401 +from .math import log1p # noqa: F401 +from .math import erf # noqa: F401 +from .math import addmm # noqa: F401 +from .math import clip # noqa: F401 +from .math import clip_ # noqa: F401 +from .math import trace # noqa: F401 +from .math import kron # noqa: F401 +from .math import isfinite # noqa: F401 +from .math import isinf # noqa: F401 +from .math import isnan # noqa: F401 +from .math import prod # noqa: F401 +from .math import all # noqa: F401 +from .math import any # noqa: F401 +from .math import broadcast_shape # noqa: F401 +from .math import conj # noqa: F401 +from .math import trunc # noqa: F401 +from .math import digamma # noqa: F401 +from .math import neg # noqa: F401 +from .math import lgamma # noqa: F401 +from .math import diagonal # noqa: F401 +from .math import acosh # noqa: F401 +from .math import asinh # noqa: F401 +from .math import atanh # noqa: F401 +from .math import lerp # noqa: F401 +from .math import lerp_ # noqa: F401 +from .math import erfinv # noqa: F401 +from .math import erfinv_ # noqa: F401 +from .math import rad2deg # noqa: F401 +from .math import deg2rad # noqa: F401 +from .math import gcd # noqa: F401 +from .math import lcm # noqa: F401 +from .math import diff # noqa: F401 +from .math import angle # noqa: F401 +from .math import fmax # noqa: F401 +from .math import fmin # noqa: F401 +from .math import inner # noqa: F401 +from .math import outer # noqa: F401 +from .math import heaviside # noqa: F401 +from .math import frac # noqa: F401 +from .math import sgn # noqa: F401 +from .math import take # noqa: F401 + +from .random import multinomial # noqa: F401 +from .random import standard_normal # noqa: F401 +from .random import normal # noqa: F401 +from .random import uniform # noqa: F401 +from .random import uniform_ # noqa: F401 +from .random import randn # noqa: F401 +from .random import rand # noqa: F401 +from .random import randint # noqa: F401 +from .random import randint_like # noqa: F401 +from .random import randperm # noqa: F401 +from .random import poisson # noqa: F401 +from .random import exponential_ # noqa: F401 +from .search import argmax # noqa: F401 +from .search import argmin # noqa: F401 +from .search import argsort # noqa: F401 +from .search import searchsorted # noqa: F401 +from .search import bucketize # noqa: F401 +from .search import topk # noqa: F401 +from .search import where # noqa: F401 +from .search import index_select # noqa: F401 +from .search import nonzero # noqa: F401 +from .search import sort # noqa: F401 +from .search import index_sample # noqa: F401 +from .search import masked_select # noqa: F401 +from .search import kthvalue # noqa: F401 +from .search import mode # noqa: F401 + +from .stat import mean # noqa: F401 +from .stat import std # noqa: F401 +from .stat import var # noqa: F401 +from .stat import numel # noqa: F401 +from .stat import median # noqa: F401 +from .stat import nanmedian # noqa: F401 +from .stat import quantile # noqa: F401 +from .stat import nanquantile # noqa: F401 + +from .to_string import set_printoptions # noqa: F401 + +from .array import array_length # noqa: F401 +from .array import array_read # noqa: F401 +from .array import array_write # noqa: F401 +from .array import create_array # noqa: F401 + +from .einsum import einsum # noqa: F401 + +# this list used in math_op_patch.py for _binary_creator_ +tensor_method_func = [ # noqa + 'matmul', + 'dot', + 'cov', + 'corrcoef', + 'norm', + 'cond', + 'transpose', + 'lstsq', + 'dist', + 't', + 'cross', + 'cholesky', + 'bmm', + 'histogram', + 'bincount', + 'mv', + 'matrix_power', + 'qr', + 'eigvals', + 'eigvalsh', + 'abs', + 'acos', + 'all', + 'any', + 'asin', + 'atan', + 'ceil', + 'ceil_', + 'cos', + 'cosh', + 'cumsum', + 'cumprod', + 'logcumsumexp', + 'logit', + 'exp', + 'exp_', + 'floor', + 'floor_', + 'increment', + 'log', + 'log2', + 'log10', + 'logsumexp', + 'multiplex', + 'pow', + 'prod', + 'reciprocal', + 'reciprocal_', + 'round', + 'round_', + 'rsqrt', + 'rsqrt_', + 'scale', + 'scale_', + 'sign', + 'sin', + 'sinh', + 'sqrt', + 'sqrt_', + 'square', + 'stanh', + 'sum', + 'nansum', + 'nanmean', + 'count_nonzero', + 'tanh', + 'tanh_', + 'add_n', + 'max', + 'amax', + 'maximum', + 'min', + 'amin', + 'minimum', + 'fmax', + 'fmin', + 'mm', + 'inner', + 'outer', + 'divide', + 'floor_divide', + 'remainder', + 'remainder_', + 'mod', + 'floor_mod', + 'multiply', + 'add', + 'add_', + 'subtract', + 'subtract_', + 'atan', + 'logsumexp', + 'inverse', + 'log1p', + 'erf', + 'addmm', + 'clip', + 'clip_', + 'trace', + 'kron', + 'kthvalue', + 'isfinite', + 'isinf', + 'isnan', + 'broadcast_shape', + 'conj', + 'neg', + 'lgamma', + 'equal', + 'equal_all', + 'greater_equal', + 'greater_than', + 'is_empty', + 'less_equal', + 'less_than', + 'logical_and', + 'logical_not', + 'logical_or', + 'logical_xor', + 'not_equal', + 'allclose', + 'isclose', + 'is_tensor', + 'cast', + 'concat', + 'expand', + 'broadcast_to', + 'expand_as', + 'flatten', + 'flatten_', + 'gather', + 'gather_nd', + 'reshape', + 'reshape_', + 'reverse', + 'scatter', + 'scatter_', + 'scatter_nd_add', + 'scatter_nd', + 'shard_index', + 'slice', + 'split', + 'chunk', + 'tensordot', + 'squeeze', + 'squeeze_', + 'stack', + 'strided_slice', + 'transpose', + 'unique', + 'unique_consecutive', + 'unsqueeze', + 'unsqueeze_', + 'unstack', + 'flip', + 'rot90', + 'unbind', + 'roll', + 'tile', + 'argmax', + 'argmin', + 'argsort', + 'masked_select', + 'topk', + 'where', + 'index_select', + 'nonzero', + 'sort', + 'index_sample', + 'mean', + 'std', + 'var', + 'numel', + 'median', + 'nanmedian', + 'quantile', + 'nanquantile', + 'is_complex', + 'is_integer', + 'rank', + 'shape', + 'real', + 'imag', + 'is_floating_point', + 'digamma', + 'diagonal', + 'trunc', + 'frac', + 'bitwise_and', + 'bitwise_or', + 'bitwise_xor', + 'bitwise_not', + 'broadcast_tensors', + 'eig', + 'uniform_', + 'multi_dot', + 'solve', + 'cholesky_solve', + 'triangular_solve', + 'asinh', + 'atanh', + 'acosh', + 'lu', + 'lu_unpack', + 'as_complex', + 'as_real', + 'rad2deg', + 'deg2rad', + 'gcd', + 'lcm', + 'diff', + "mode", + 'lerp', + 'lerp_', + 'erfinv', + 'erfinv_', + 'angle', + 'moveaxis', + 'repeat_interleave', + 'take_along_axis', + 'put_along_axis', + 'put_along_axis_', + 'exponential_', + 'heaviside', + 'index_add', + "index_add_", + 'take', + 'bucketize', + 'sgn', +] + +# this list used in math_op_patch.py for magic_method bind +magic_method_func = [ + ('__and__', 'bitwise_and'), + ('__or__', 'bitwise_or'), + ('__xor__', 'bitwise_xor'), + ('__invert__', 'bitwise_not'), +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/array.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/array.py new file mode 100644 index 0000000000000000000000000000000000000000..02da6926a3f5f98b8cee209d291bcf096adf8c54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/array.py @@ -0,0 +1,274 @@ +# 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. + +# Define functions about array. + +import paddle +from ..static import Variable +from ..framework import LayerHelper, core, _non_static_mode +from ..fluid.data_feeder import check_type +from ..fluid.data_feeder import check_variable_and_dtype + +__all__ = [] + + +def array_length(array): + """ + This OP is used to get the length of the input array. + + Args: + array (list|Tensor): The input array that will be used to compute the length. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor whose VarType is LOD_TENSOR_ARRAY. + + Returns: + Tensor: 1-D Tensor with shape [1], which is the length of array. + + Examples: + .. code-block:: python + + import paddle + + arr = paddle.tensor.create_array(dtype='float32') + x = paddle.full(shape=[3, 3], fill_value=5, dtype="float32") + i = paddle.zeros(shape=[1], dtype="int32") + + arr = paddle.tensor.array_write(x, i, array=arr) + + arr_len = paddle.tensor.array_length(arr) + print(arr_len) # 1 + """ + if _non_static_mode(): + assert isinstance( + array, + list), "The 'array' in array_write must be a list in dygraph mode" + return len(array) + + if not isinstance( + array, + Variable) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "array should be tensor array vairable in array_length Op") + + helper = LayerHelper('array_length', **locals()) + tmp = helper.create_variable_for_type_inference(dtype='int64') + tmp.stop_gradient = True + helper.append_op(type='lod_array_length', + inputs={'X': [array]}, + outputs={'Out': [tmp]}) + return tmp + + +def array_read(array, i): + """ + This OP is used to read data at the specified position from the input array. + + Case: + + .. code-block:: text + + Input: + The shape of first three tensors are [1], and that of the last one is [1,2]: + array = ([0.6], [0.1], [0.3], [0.4, 0.2]) + And: + i = [3] + + Output: + output = [0.4, 0.2] + + Args: + array (list|Tensor): The input array. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor whose ``VarType`` is ``LOD_TENSOR_ARRAY``. + i (Tensor): 1-D Tensor, whose shape is [1] and dtype is int64. It represents the + specified read position of ``array``. + + Returns: + Tensor: A Tensor that is read at the specified position of ``array``. + + Examples: + .. code-block:: python + + import paddle + + arr = paddle.tensor.create_array(dtype="float32") + x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32") + i = paddle.zeros(shape=[1], dtype="int32") + + arr = paddle.tensor.array_write(x, i, array=arr) + + item = paddle.tensor.array_read(arr, i) + print(item) # [[5., 5., 5.]] + """ + if _non_static_mode(): + assert isinstance( + array, + list), "The 'array' in array_read must be list in dygraph mode" + assert isinstance( + i, Variable + ), "The index 'i' in array_read must be Variable in dygraph mode" + assert i.shape == [ + 1 + ], "The shape of index 'i' should be [1] in dygraph mode" + i = i.numpy().item(0) + return array[i] + + check_variable_and_dtype(i, 'i', ['int64'], 'array_read') + helper = LayerHelper('array_read', **locals()) + if not isinstance( + array, + Variable) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError("array should be tensor array vairable") + out = helper.create_variable_for_type_inference(dtype=array.dtype) + helper.append_op(type='read_from_array', + inputs={ + 'X': [array], + 'I': [i] + }, + outputs={'Out': [out]}) + return out + + +def array_write(x, i, array=None): + """ + This OP writes the input ``x`` into the i-th position of the ``array`` returns the modified array. + If ``array`` is none, a new array will be created and returned. + + Args: + x (Tensor): The input data to be written into array. It's multi-dimensional + Tensor or LoDTensor. Data type: float32, float64, int32, int64 and bool. + i (Tensor): 1-D Tensor with shape [1], which represents the position into which + ``x`` is written. + array (list|Tensor, optional): The array into which ``x`` is written. The default value is None, + when a new array will be created and returned as a result. In dynamic mode, ``array`` is a Python list. + But in static mode, array is a Tensor whose ``VarType`` is ``LOD_TENSOR_ARRAY``. + + Returns: + list|Tensor: The input ``array`` after ``x`` is written into. + + Examples: + .. code-block:: python + + import paddle + + arr = paddle.tensor.create_array(dtype="float32") + x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32") + i = paddle.zeros(shape=[1], dtype="int32") + + arr = paddle.tensor.array_write(x, i, array=arr) + + item = paddle.tensor.array_read(arr, i) + print(item) # [[5., 5., 5.]] + """ + if _non_static_mode(): + assert isinstance( + x, Variable + ), "The input data 'x' in array_write must be Variable in dygraph mode" + assert isinstance( + i, Variable + ), "The index 'i' in array_write must be Variable in dygraph mode" + assert i.shape == [ + 1 + ], "The shape of index 'i' should be [1] in dygraph mode" + i = i.numpy().item(0) + if array is None: + array = create_array(x.dtype) + assert isinstance( + array, + list), "The 'array' in array_write must be a list in dygraph mode" + assert i <= len( + array + ), "The index 'i' should not be greater than the length of 'array' in dygraph mode" + if i < len(array): + array[i] = x + else: + array.append(x) + return array + + check_variable_and_dtype(i, 'i', ['int64'], 'array_write') + check_type(x, 'x', (Variable), 'array_write') + helper = LayerHelper('array_write', **locals()) + if array is not None: + if not isinstance( + array, Variable + ) or array.type != core.VarDesc.VarType.LOD_TENSOR_ARRAY: + raise TypeError( + "array should be tensor array vairable in array_write Op") + if array is None: + array = helper.create_variable( + name="{0}.out".format(helper.name), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=x.dtype) + helper.append_op(type='write_to_array', + inputs={ + 'X': [x], + 'I': [i] + }, + outputs={'Out': [array]}) + return array + + +def create_array(dtype, initialized_list=None): + """ + This OP creates an array. It is used as the input of :ref:`api_paddle_tensor_array_array_read` and + :ref:`api_paddle_tensor_array_array_write`. + + Args: + dtype (str): The data type of the elements in the array. Support data type: float32, float64, int32, int64 and bool. + initialized_list(list): Used to initialize as default value for created array. + All values in initialized list should be a Tensor. + + Returns: + list|Tensor: An empty array. In dynamic mode, ``array`` is a Python list. But in static mode, array is a Tensor + whose ``VarType`` is ``LOD_TENSOR_ARRAY``. + + Examples: + .. code-block:: python + + import paddle + + arr = paddle.tensor.create_array(dtype="float32") + x = paddle.full(shape=[1, 3], fill_value=5, dtype="float32") + i = paddle.zeros(shape=[1], dtype="int32") + + arr = paddle.tensor.array_write(x, i, array=arr) + + item = paddle.tensor.array_read(arr, i) + print(item) # [[5., 5., 5.]] + + """ + array = [] + if initialized_list is not None: + if not isinstance(initialized_list, (list, tuple)): + raise TypeError( + "Require type(initialized_list) should be list/tuple, but received {}" + .format(type(initialized_list))) + array = list(initialized_list) + + # NOTE: Only support plain list like [x, y,...], not support nested list in static mode. + for val in array: + if not isinstance(val, Variable): + raise TypeError( + "All values in `initialized_list` should be Variable, but recevied {}." + .format(type(val))) + + if _non_static_mode(): + return array + + helper = LayerHelper("array", **locals()) + tensor_array = helper.create_variable( + name="{0}.out".format(helper.name), + type=core.VarDesc.VarType.LOD_TENSOR_ARRAY, + dtype=dtype) + + for val in array: + array_write(x=val, i=array_length(tensor_array), array=tensor_array) + + return tensor_array diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/attribute.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..f575092153b41bc964d43b4ee1b60cc90d0e63b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/attribute.py @@ -0,0 +1,335 @@ +# 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. + +from __future__ import print_function + +from ..framework import core, _non_static_mode +from ..framework import LayerHelper +from ..fluid.data_feeder import check_variable_and_dtype +from ..fluid.data_feeder import check_type + +from .creation import assign +from .creation import _complex_to_real_dtype + +# TODO: define functions to get tensor attributes +import paddle +from paddle import _C_ops, _legacy_C_ops +from ..static import Variable +from ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode + +import numpy as np + +__all__ = [] + + +def rank(input): + """ + + Returns the number of dimensions for a tensor, which is a 0-D int32 Tensor. + + Args: + input (Tensor): The input Tensor with shape of :math:`[N_1, N_2, ..., N_k]`, the data type is arbitrary. + + Returns: + Tensor, the output data type is int32.: The 0-D tensor with the dimensions of the input Tensor. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand((3, 100, 100)) + rank = paddle.rank(input) + print(rank) + # 3 + """ + check_type(input, 'input', (Variable), 'input') + ndims = len(input.shape) + out = assign(np.array(ndims, 'int32')) + + return out + + +def shape(input): + """ + :alias_main: paddle.shape + :alias: paddle.shape,paddle.tensor.shape,paddle.tensor.attribute.shape + :old_api: paddle.fluid.layers.shape + + **Shape Layer** + + Get the shape of the input. + + .. code-block:: text + + Case1: + Given N-D Tensor: + input = [ [1, 2, 3, 4], [5, 6, 7, 8] ] + + Then: + input.shape = [2, 4] + + Case2: + Given SelectedRows: + input.rows = [0, 4, 19] + input.height = 20 + input.value = [ [1, 2], [3, 4], [5, 6] ] # inner tensor + Then: + input.shape = [3, 2] + + Args: + input (Variable): The input can be N-D Tensor or SelectedRows with data type bool, float16, float32, float64, int32, int64. + If input variable is type of SelectedRows, returns the shape of it's inner tensor. + + Returns: + Variable (Tensor): The shape of the input variable. + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + import numpy as np + import paddle + paddle.enable_static() + + inputs = fluid.data(name="x", shape=[3, 100, 100], dtype="float32") + output = fluid.layers.shape(inputs) + + exe = fluid.Executor(fluid.CPUPlace()) + exe.run(fluid.default_startup_program()) + + img = np.ones((3, 100, 100)).astype(np.float32) + + res = exe.run(fluid.default_main_program(), feed={'x':img}, fetch_list=[output]) + print(res) # [array([ 3, 100, 100], dtype=int32)] + """ + if in_dygraph_mode(): + out = _C_ops.shape(input) + out.stop_gradient = True + return out + if _in_legacy_dygraph(): + out = _legacy_C_ops.shape(input) + out.stop_gradient = True + return out + + check_variable_and_dtype(input, 'input', [ + 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'complex64', + 'complex128' + ], 'shape') + helper = LayerHelper('shape', **locals()) + out = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op(type='shape', + inputs={'Input': input}, + outputs={'Out': out}, + stop_gradient=True) + + return out + + +def is_complex(x): + """Return whether x is a tensor of complex data type(complex64 or complex128). + + Args: + x (Tensor): The input tensor. + + Returns: + bool: True if the data type of the input is complex data type, otherwise false. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1 + 2j, 3 + 4j]) + print(paddle.is_complex(x)) + # True + + x = paddle.to_tensor([1.1, 1.2]) + print(paddle.is_complex(x)) + # False + + x = paddle.to_tensor([1, 2, 3]) + print(paddle.is_complex(x)) + # False + """ + if not isinstance(x, (paddle.Tensor, paddle.static.Variable)): + raise TypeError("Expected Tensor, but received type of x: {}".format( + type(x))) + dtype = x.dtype + is_complex_dtype = (dtype == core.VarDesc.VarType.COMPLEX64 + or dtype == core.VarDesc.VarType.COMPLEX128) + return is_complex_dtype + + +def is_floating_point(x): + """ + Returns whether the dtype of `x` is one of paddle.float64, paddle.float32, paddle.float16, and paddle.bfloat16. + + Args: + x (Tensor): The input tensor. + + Returns: + bool: True if the dtype of `x` is floating type, otherwise false. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(1., 5., dtype='float32') + y = paddle.arange(1, 5, dtype='int32') + print(paddle.is_floating_point(x)) + # True + print(paddle.is_floating_point(y)) + # False + """ + if not isinstance(x, (paddle.Tensor, paddle.static.Variable)): + raise TypeError("Expected Tensor, but received type of x: {}".format( + type(x))) + dtype = x.dtype + is_fp_dtype = (dtype == core.VarDesc.VarType.FP32 + or dtype == core.VarDesc.VarType.FP64 + or dtype == core.VarDesc.VarType.FP16 + or dtype == core.VarDesc.VarType.BF16) + return is_fp_dtype + + +def is_integer(x): + """Return whether x is a tensor of integeral data type. + + Args: + x (Tensor): The input tensor. + + Returns: + bool: True if the data type of the input is integer data type, otherwise false. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1 + 2j, 3 + 4j]) + print(paddle.is_integer(x)) + # False + + x = paddle.to_tensor([1.1, 1.2]) + print(paddle.is_integer(x)) + # False + + x = paddle.to_tensor([1, 2, 3]) + print(paddle.is_integer(x)) + # True + """ + if not isinstance(x, (paddle.Tensor, paddle.static.Variable)): + raise TypeError("Expected Tensor, but received type of x: {}".format( + type(x))) + dtype = x.dtype + is_int_dtype = (dtype == core.VarDesc.VarType.UINT8 + or dtype == core.VarDesc.VarType.INT8 + or dtype == core.VarDesc.VarType.INT16 + or dtype == core.VarDesc.VarType.INT32 + or dtype == core.VarDesc.VarType.INT64) + return is_int_dtype + + +def real(x, name=None): + """ + Returns a new Tensor containing real values of the input Tensor. + + Args: + x (Tensor): the input Tensor, its data type could be complex64 or complex128. + name (str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: a Tensor containing real values of the input Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor( + [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]]) + # Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[(1+6j), (2+5j), (3+4j)], + # [(4+3j), (5+2j), (6+1j)]]) + + real_res = paddle.real(x) + # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[1., 2., 3.], + # [4., 5., 6.]]) + + real_t = x.real() + # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[1., 2., 3.], + # [4., 5., 6.]]) + """ + if in_dygraph_mode(): + return _C_ops.real(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.real(x) + + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'real') + helper = LayerHelper('real', **locals()) + out = helper.create_variable_for_type_inference( + dtype=_complex_to_real_dtype(helper.input_dtype())) + helper.append_op(type='real', inputs={'X': x}, outputs={'Out': out}) + return out + + +def imag(x, name=None): + """ + Returns a new tensor containing imaginary values of input tensor. + + Args: + x (Tensor): the input tensor, its data type could be complex64 or complex128. + name (str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: a tensor containing imaginary values of the input tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor( + [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]]) + # Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[(1+6j), (2+5j), (3+4j)], + # [(4+3j), (5+2j), (6+1j)]]) + + imag_res = paddle.imag(x) + # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[6., 5., 4.], + # [3., 2., 1.]]) + + imag_t = x.imag() + # Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[6., 5., 4.], + # [3., 2., 1.]]) + """ + if in_dygraph_mode(): + return _C_ops.imag(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.imag(x) + + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'imag') + helper = LayerHelper('imag', **locals()) + out = helper.create_variable_for_type_inference( + dtype=_complex_to_real_dtype(helper.input_dtype())) + helper.append_op(type='imag', inputs={'X': x}, outputs={'Out': out}) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/creation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/creation.py new file mode 100644 index 0000000000000000000000000000000000000000..82a016ce64da7afd1ddc11ee20fe2893fbdc7bbb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/creation.py @@ -0,0 +1,2196 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function +import numpy as np +import math +import re +from paddle.common_ops_import import fill_constant +from ..fluid.layers import utils +from ..static import Variable, device_guard +from ..framework import _current_expected_place, _get_paddle_place +from ..framework import dygraph_only +from ..framework import core +from ..framework import in_dygraph_mode, _non_static_mode +from ..framework import LayerHelper +from ..fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, + convert_dtype, +) +from ..framework import ( + convert_np_dtype_to_dtype_, + _varbase_creator, + OpProtoHolder, +) + +# TODO: define functions to get create a tensor +import paddle +from paddle import _C_ops, _legacy_C_ops +from ..fluid.framework import ( + _in_legacy_dygraph, + _in_eager_without_dygraph_check, +) +import warnings + +__all__ = [] + + +def _complex_to_real_dtype(dtype): + if dtype == core.VarDesc.VarType.COMPLEX64: + return core.VarDesc.VarType.FP32 + elif dtype == core.VarDesc.VarType.COMPLEX128: + return core.VarDesc.VarType.FP64 + else: + return dtype + + +def _real_to_complex_dtype(dtype): + if dtype == core.VarDesc.VarType.FP32: + return core.VarDesc.VarType.COMPLEX64 + elif dtype == core.VarDesc.VarType.FP64: + return core.VarDesc.VarType.COMPLEX128 + else: + return dtype + + +def linspace(start, stop, num, dtype=None, name=None): + r""" + Return fixed number of evenly spaced values within a given interval. + + Args: + start(int|float|Tensor): The input :attr:`start` is start variable of range. It is a scalar, \ + or a Tensor of shape [1] with input data type int32, int64, float32 or float64. + stop(int|float|Tensor): The input :attr:`stop` is start variable of range. It is a scalar, \ + or a Tensor of shape [1] with input data type int32, int64, float32 or float64. + num(int|Tensor): The input :attr:`num` is given num of the sequence. It is an int scalar, \ + or a Tensor of shape [1] with data type int32. + dtype(np.dtype|str, optional): The data type of output tensor, it could be + int32, int64, float32 and float64. Default: if None, the data type is float32. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: the output data type will be float32, float64. The 1-D tensor with fixed number of evenly spaced values, \ + the data shape of this tensor is :math:`[num]` . If the :attr:`num` is set 1, the output tensor just has \ + the value with input :attr:`start`. + + Examples: + .. code-block:: python + + import paddle + data = paddle.linspace(0, 10, 5, 'float32') # [0.0, 2.5, 5.0, 7.5, 10.0] + data = paddle.linspace(0, 10, 1, 'float32') # [0.0] + + """ + if dtype is None: + dtype = 'float32' + tensor_num = num + tensor_start = start + tensor_stop = stop + if not isinstance(num, Variable): + check_type(num, 'num', (int), 'linspace') + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if not isinstance(start, Variable): + with device_guard("cpu"): + tensor_start = fill_constant([1], dtype, start, force_cpu=True) + if not isinstance(stop, Variable): + with device_guard("cpu"): + tensor_stop = fill_constant([1], dtype, stop, force_cpu=True) + if not isinstance(num, Variable): + with device_guard("cpu"): + tensor_num = fill_constant([1], 'int32', num, force_cpu=True) + if in_dygraph_mode(): + return _C_ops.linspace( + tensor_start, + tensor_stop, + tensor_num, + dtype, + _current_expected_place(), + ) + if _in_legacy_dygraph(): + return _legacy_C_ops.linspace( + tensor_start, tensor_stop, tensor_num, 'dtype', dtype + ) + + helper = LayerHelper("linspace", **locals()) + + start_dtype = convert_dtype(tensor_start.dtype) + stop_dtype = convert_dtype(tensor_stop.dtype) + out_dtype = convert_dtype(dtype) + if isinstance(start, Variable): + check_dtype( + start.dtype, + 'start', + ['float32', 'float64', 'int32', 'int64'], + 'linspace', + ) + else: + check_type(start, 'start', (int, float), 'linspace') + + if isinstance(stop, Variable): + check_dtype( + stop.dtype, + 'stop', + ['float32', 'float64', 'int32', 'int64'], + 'linspace', + ) + else: + check_type(stop, 'stop', (int, float), 'linspace') + if isinstance(num, Variable): + check_dtype(num.dtype, 'num', ['int32'], 'linspace') + check_dtype( + dtype, 'dtype', ['int32', 'int64', 'float32', 'float64'], 'linspace' + ) + if ( + (stop_dtype == "float64" or start_dtype == "float64") + and out_dtype in ["float32", "int32"] + ) or ( + (stop_dtype == "int64" or start_dtype == "int64") + and out_dtype == "int32" + ): + raise ValueError( + "The dtype of start/stop is {}/{} but the attr(dtype) of linspace is {}, " + "which may cause data type overflows. Please reset attr(dtype) of linspace.".format( + start_dtype, stop_dtype, dtype + ) + ) + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='linspace', + inputs={'Start': tensor_start, 'Stop': tensor_stop, 'Num': tensor_num}, + attrs={'dtype': dtype}, + outputs={'Out': [out]}, + ) + if isinstance(num, int): + out.desc.set_shape((num,)) + return out + + +def logspace(start, stop, num, base=10.0, dtype=None, name=None): + r""" + Return fixed number of logarithmical-evenly spaced values within the interval \ + :math:`[base^{start}, base^{stop}]`. + + Notes: + This API does not compute the gradient. + + Args: + start(int|float|Tensor): The input :attr:`start` is exponent of first entry in \ + the sequence. It is a scalar, or a Tensor of shape [1] with input data \ + type int32, int64, float32 or float64. + stop(int|float|Tensor): The input :attr:`stop` is exponent of last entry in the \ + sequence. It is a scalar, or a Tensor of shape [1] with input data \ + type int32, int64, float32 or float64. + num(int|Tensor): The input :attr:`num` is given number of items in the sequence. \ + It is an int scalar, or a Tensor of shape [1] with data type int32. + base(int|float|Tensor): The input :attr:`base` is base of the logarithm function. \ + It is a scalar, or a Tensor of shape [1] with input data type int32, int64, \ + float32 or float64. + dtype(np.dtype|str, optional): The data type of output tensor, it could be \ + int32, int64, float32 or float64. Default: if None, the data type is float32. \ + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: The output data type will be float32, float64. The 1-D tensor with \ + fixed number of logarithmical-evenly spaced values, the data shape of this \ + tensor is :math:`[num]`. If the :attr:`num` is set 1, the output tensor \ + just has the value with exponential of :attr:`start` with base :attr:`base`. + + Examples: + .. code-block:: python + + import paddle + data = paddle.logspace(0, 10, 5, 2, 'float32') + # [1. , 5.65685415 , 32. , 181.01933289, 1024. ] + data = paddle.logspace(0, 10, 1, 2, 'float32') + # [1.] + """ + if dtype is None: + dtype = 'float32' + tensor_num = num + tensor_start = start + tensor_stop = stop + tensor_base = base + if not isinstance(num, Variable): + check_type(num, 'num', (int), 'logspace') + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if not isinstance(start, Variable): + with device_guard("cpu"): + tensor_start = fill_constant([1], dtype, start) + if not isinstance(stop, Variable): + with device_guard("cpu"): + tensor_stop = fill_constant([1], dtype, stop) + if not isinstance(num, Variable): + with device_guard("cpu"): + tensor_num = fill_constant([1], 'int32', num) + if not isinstance(base, Variable): + with device_guard("cpu"): + tensor_base = fill_constant([1], dtype, base) + if _non_static_mode(): + return _legacy_C_ops.logspace( + tensor_start, tensor_stop, tensor_num, tensor_base, 'dtype', dtype + ) + + helper = LayerHelper("logspace", **locals()) + + start_dtype = convert_dtype(tensor_start.dtype) + stop_dtype = convert_dtype(tensor_stop.dtype) + base_dtype = convert_dtype(tensor_base.dtype) + out_dtype = convert_dtype(dtype) + if isinstance(start, Variable): + check_dtype( + start.dtype, + 'start', + ['float32', 'float64', 'int32', 'int64'], + 'logspace', + ) + else: + check_type(start, 'start', (int, float), 'logspace') + + if isinstance(stop, Variable): + check_dtype( + stop.dtype, + 'stop', + ['float32', 'float64', 'int32', 'int64'], + 'logspace', + ) + else: + check_type(stop, 'stop', (int, float), 'logspace') + + if isinstance(num, Variable): + check_dtype(num.dtype, 'num', ['int32'], 'logspace') + + if isinstance(base, Variable): + check_dtype( + base.dtype, + 'base', + ['float32', 'float64', 'int32', 'int64'], + 'logspace', + ) + else: + check_type(base, 'base', (int, float), 'logspace') + + check_dtype( + dtype, 'dtype', ['int32', 'int64', 'float32', 'float64'], 'logspace' + ) + if ( + ( + stop_dtype == "float64" + or start_dtype == "float64" + or base_dtype == "float64" + ) + and out_dtype in ["float32", "int32"] + ) or ( + ( + stop_dtype == "int64" + or start_dtype == "int64" + or base_dtype == "int64" + ) + and out_dtype == "int32" + ): + raise ValueError( + "The dtype of start/stop/base is {}/{}/{} but the attr(dtype) of logspace is {}, " + "which may cause data type overflows. Please reset attr(dtype) of logspace.".format( + start_dtype, stop_dtype, base_dtype, dtype + ) + ) + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='logspace', + inputs={ + 'Start': tensor_start, + 'Stop': tensor_stop, + 'Num': tensor_num, + 'Base': tensor_base, + }, + attrs={'dtype': dtype}, + outputs={'Out': [out]}, + ) + if isinstance(num, int): + out.desc.set_shape((num,)) + return out + + +def _to_tensor_non_static(data, dtype=None, place=None, stop_gradient=True): + + if not isinstance(data, np.ndarray): + + def _handle_dtype(data, dtype): + if dtype: + if convert_dtype(dtype) != convert_dtype(data.dtype): + return data.astype(convert_dtype(dtype)) + return data + + if np.isscalar(data) and not isinstance(data, str): + data = np.array([data]) + elif isinstance(data, (list, tuple)): + data = np.array(data) + if data.dtype == np.object_: + raise ValueError( + "\n\tFaild to convert input data to a regular ndarray :\n\t - Usually " + "this means the input data contains nested lists with different lengths. " + ) + elif isinstance(data, paddle.Tensor) and not in_dygraph_mode(): + data = data._copy_to(place, False) + data = _handle_dtype(data, dtype) + data.stop_gradient = stop_gradient + return data + elif isinstance(data, core.eager.Tensor) and in_dygraph_mode(): + data = data._copy_to(place, False) + data = _handle_dtype(data, dtype) + data.stop_gradient = stop_gradient + return data + elif isinstance(data, (core.LoDTensor, core.Tensor)): + # should't expose it to users, just for internal use. + # convert core.Tensor/core.LoDTensor to VarBase first + # Currenly, there is no copy when places are same + if in_dygraph_mode(): + data = core.eager.Tensor(data) + else: + data = paddle.Tensor(data) + if not data.place._equals(place): + data = data._copy_to(place, False) + data = _handle_dtype(data, dtype) + data.stop_gradient = stop_gradient + return data + else: + raise TypeError( + "Can't constructs a 'paddle.Tensor' with data type {}, data type must be scalar|list|tuple|np.ndarray|paddle.Tensor".format( + type(data) + ) + ) + if not dtype: + if data.dtype in [ + 'float16', + 'float32', + 'float64', + 'complex64', + 'complex128', + ]: + default_type = paddle.get_default_dtype() + if np.iscomplexobj(data): + default_type = ( + 'complex64' + if default_type in ['float16', 'float32'] + else 'complex128' + ) + data = data.astype(default_type) + # Windows default type is 'int32', while Linux/Mac is 'int64'. Unify they. + if data.dtype in ['int32']: + default_type = "int64" + data = data.astype(default_type) + + if dtype and convert_dtype(dtype) != data.dtype: + data = data.astype(convert_dtype(dtype)) + + if _in_eager_without_dygraph_check() and isinstance(data, np.ndarray): + return core.eager.Tensor( + value=data, + place=place, + persistable=False, + zero_copy=False, + name=None, + stop_gradient=stop_gradient, + ) + else: + return paddle.Tensor( + value=data, + place=place, + persistable=False, + zero_copy=False, + stop_gradient=stop_gradient, + ) + + +def _to_tensor_static(data, dtype=None, stop_gradient=None): + + if isinstance(data, Variable) and (dtype is None or dtype == data.dtype): + output = data + else: + + if not isinstance(data, np.ndarray): + if np.isscalar(data) and not isinstance(data, str): + data = np.array([data]) + elif isinstance(data, (list, tuple)): + data = np.array(data) + + if ( + isinstance(data, np.ndarray) + and not dtype + and data.dtype != 'object' + ): + if data.dtype in ['float16', 'float32', 'float64']: + data = data.astype(paddle.get_default_dtype()) + elif data.dtype in ['int32']: + data = data.astype('int64') + + if dtype: + target_dtype = dtype + elif hasattr(data, 'dtype') and data.dtype != 'object': + target_dtype = data.dtype + else: + target_dtype = paddle.get_default_dtype() + + target_dtype = convert_dtype(target_dtype) + + if ( + isinstance(data, np.ndarray) + and len(data.shape) > 0 + and any(isinstance(x, Variable) for x in data) + ): + if not all( + [x.shape == (1,) for x in data if isinstance(x, Variable)] + ): + raise TypeError( + "Unsupport paddle.to_tensor([Variable, Variable...]) with non-scalar variable." + ) + to_stack_list = [None] * data.shape[0] + for idx, d in enumerate(data): + to_stack_list[idx] = _to_tensor_static(d, dtype, stop_gradient) + data = paddle.stack(to_stack_list) + data = paddle.squeeze(data, -1) + + if not isinstance(data, Variable): + output = assign(data) + else: + output = data + if convert_dtype(output.dtype) != target_dtype: + output = paddle.cast(output, target_dtype) + + output.stop_gradient = stop_gradient + + return output + + +def to_tensor(data, dtype=None, place=None, stop_gradient=True): + r""" + Constructs a ``paddle.Tensor`` from ``data`` , + which can be scalar, tuple, list, numpy\.ndarray, paddle\.Tensor. + + If the ``data`` is already a Tensor, copy will be performed and return a new tensor. + If you only want to change stop_gradient property, please call ``Tensor.stop_gradient = stop_gradient`` directly. + + Args: + data(scalar|tuple|list|ndarray|Tensor): Initial data for the tensor. + Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor. + dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' , + 'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8', + 'complex64' , 'complex128'. Default: None, infers dtype from ``data`` + except for python float number which gets dtype from ``get_default_type`` . + place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be + CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is + string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs. + stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True. + + Returns: + Tensor: A Tensor constructed from ``data`` . + + Examples: + + .. code-block:: python + + import paddle + + type(paddle.to_tensor(1)) + # + + paddle.to_tensor(1) + # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True, + # [1]) + + x = paddle.to_tensor(1, stop_gradient=False) + print(x) + # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=False, + # [1]) + + paddle.to_tensor(x) # A new tensor will be created with default stop_gradient=True + # Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True, + # [1]) + + paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False) + # Tensor(shape=[2, 2], dtype=float32, place=CPUPlace, stop_gradient=False, + # [[0.10000000, 0.20000000], + # [0.30000001, 0.40000001]]) + + type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')) + # + + paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64') + # Tensor(shape=[2, 2], dtype=complex64, place=CPUPlace, stop_gradient=True, + # [[(1+1j), (2+0j)], + # [(3+2j), (4+0j)]]) + """ + place = _get_paddle_place(place) + if place is None: + place = _current_expected_place() + + if _non_static_mode(): + return _to_tensor_non_static(data, dtype, place, stop_gradient) + + # call assign for static graph + else: + re_exp = re.compile(r'[(](.+?)[)]', re.S) + place_str = re.findall(re_exp, str(place))[0] + + with paddle.static.device_guard(place_str): + return _to_tensor_static(data, dtype, stop_gradient) + + +def full_like(x, fill_value, dtype=None, name=None): + """ + + This function creates a tensor filled with ``fill_value`` which has identical shape of ``x`` and ``dtype``. + If the ``dtype`` is None, the data type of Tensor is same with ``x``. + + Args: + x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64. + fill_value(bool|float|int): The value to fill the tensor with. Note: this value shouldn't exceed the range of the output data type. + dtype(np.dtype|str, optional): The data type of output. The data type can be one + of bool, float16, float32, float64, int32, int64. The default value is None, which means the output + data type is the same as input. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Tensor which is created according to ``x``, ``fill_value`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.full(shape=[2, 3], fill_value=0.0, dtype='float32', name='input') + output = paddle.full_like(input, 2.0) + # [[2. 2. 2.] + # [2. 2. 2.]] + """ + + if dtype is None: + dtype = x.dtype + else: + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + return _C_ops.full_like(x, fill_value, dtype, x.place) + + if _in_legacy_dygraph(): + return _legacy_C_ops.fill_any_like( + x, 'value', fill_value, 'dtype', dtype + ) + + helper = LayerHelper("full_like", **locals()) + check_variable_and_dtype( + x, + 'x', + ['bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64'], + 'full_like', + ) + check_dtype( + dtype, + 'dtype', + ['bool', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64'], + 'full_like/zeros_like/ones_like', + ) + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='fill_any_like', + inputs={'X': [x]}, + attrs={'value': fill_value, "dtype": dtype}, + outputs={'Out': [out]}, + ) + out.stop_gradient = True + return out + + +def ones(shape, dtype=None, name=None): + """ + Create a Tensor of specified :attr:`shape` and :attr:`dtype` and fill it with 1. + + Args: + shape (tuple|list|Tensor): Shape of the Tensor to be created, the data type of shape should be int32 or int64. + dtype (np.dtype|str, optional): Data type of output Tensor, it should be one of + bool, float16, float32, float64, int32 and int64. If it is set to None, the data type will be float32. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements are 1. + + Examples: + .. code-block:: python + + import paddle + + # default dtype for ones OP + data1 = paddle.ones(shape=[3, 2]) + # [[1. 1.] + # [1. 1.] + # [1. 1.]] + + data2 = paddle.ones(shape=[2, 2], dtype='int32') + # [[1 1] + # [1 1]] + + # shape is a Tensor + shape = paddle.full(shape=[2], dtype='int32', fill_value=2) + data3 = paddle.ones(shape=shape, dtype='int32') + # [[1 1] + # [1 1]] + """ + if dtype is None: + dtype = 'float32' + return fill_constant(value=1.0, shape=shape, dtype=dtype, name=name) + + +def ones_like(x, dtype=None, name=None): + """ + Returns a Tensor filled with the value 1, with the same shape and + data type (use ``dtype`` if ``dtype`` is not None) as ``x``. + + Args: + x(Tensor): The input tensor which specifies shape and dtype. The + dtype of ``x`` can be bool, float16, float32, float64, int32, int64. + dtype(str|np.dtype, optional): The data type of the + output tensor. Supported data types: bool, float16, float32, float64, + int32, int64. If ``dtype`` is None, the data type is the same as ``x``. + Default is None. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor filled with the value 1, with the same shape and + data type (use ``dtype`` if ``dtype`` is not None) as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1,2,3]) + out1 = paddle.ones_like(x) # [1., 1., 1.] + out2 = paddle.ones_like(x, dtype='int32') # [1, 1, 1] + + """ + return full_like(x=x, fill_value=1, dtype=dtype, name=name) + + +def zeros(shape, dtype=None, name=None): + """ + Creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. + + Args: + shape(tuple|list|Tensor): Shape of the Tensor to be created, the data type of ``shape`` is int32 or int64. + dtype(np.dtype|str, optional): Data type of output Tensor, it supports + bool, float16, float32, float64, int32 and int64. Default: if None, the date type is float32. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.zeros(shape=[3, 2], dtype='float32') + # [[0. 0.] + # [0. 0.] + # [0. 0.]] + data = paddle.zeros(shape=[2, 2]) + # [[0. 0.] + # [0. 0.]] + + # shape is a Tensor + shape = paddle.full(shape=[2], dtype='int32', fill_value=2) + data3 = paddle.zeros(shape=shape, dtype='int32') + # [[0 0] + # [0 0]] + """ + if dtype is None: + dtype = 'float32' + return fill_constant(value=0.0, shape=shape, dtype=dtype, name=name) + + +def zeros_like(x, dtype=None, name=None): + """ + Returns a Tensor filled with the value 0, with the same shape and + data type (use ``dtype`` if ``dtype`` is not None) as ``x``. + + Args: + x(Tensor): The input tensor which specifies shape and dtype. The + dtype of ``x`` can be bool, float16, float32, float64, int32, int64. + dtype(str|np.dtype, optional): The data type of the + output tensor. Supported data types: bool, float16, float32, float64, + int32, int64. If ``dtype`` is None, the data type is the same as ``x``. + Default is None. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor filled with the value 0, with the same shape and + data type (use ``dtype`` if ``dtype`` is not None) as ``x``. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + out1 = paddle.zeros_like(x) # [0., 0., 0.] + out2 = paddle.zeros_like(x, dtype='int32') # [0, 0, 0] + + """ + return full_like(x=x, fill_value=0, dtype=dtype, name=name) + + +def eye(num_rows, num_columns=None, dtype=None, name=None): + """ + + This function constructs 2-D Tensor with ones on the diagonal and zeros elsewhere. + + Args: + num_rows(int): the number of rows in each batch Tensor. + num_columns(int, optional): the number of columns in each batch Tensor. + If None, default: num_rows. + dtype(np.dtype|str, optional): The data type of the returned Tensor. + It should be int32, int64, float16, float32, float64. Default: if None, the data type + is float32. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: An identity Tensor or LoDTensor of shape [num_rows, num_columns]. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.eye(3, dtype='int32') + # [[1 0 0] + # [0 1 0] + # [0 0 1]] + data = paddle.eye(2, 3, dtype='int32') + # [[1 0 0] + # [0 1 0]] + """ + + def _check_attr(attr, message): + if isinstance(attr, ((Variable, core.VarBase, core.eager.Tensor))): + assert len(attr.shape) == 1 and attr.shape[0] in [1, -1] + elif not isinstance(attr, int) or attr < 0: + raise TypeError("{} should be a non-negative int.".format(message)) + + _check_attr(num_rows, "num_rows") + + if dtype is None: + dtype = 'float32' + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + if num_columns is not None: + _check_attr(num_columns, "num_columns") + else: + num_columns = num_rows + + if _non_static_mode(): + if in_dygraph_mode(): + out = _C_ops.eye( + num_rows, num_columns, dtype, _current_expected_place() + ) + elif _in_legacy_dygraph(): + out = _legacy_C_ops.eye( + 'dtype', dtype, 'num_rows', num_rows, 'num_columns', num_columns + ) + + else: + helper = LayerHelper("eye", **locals()) + check_dtype( + dtype, + 'dtype', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'eye', + ) + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op( + type='eye', + inputs={}, + outputs={'Out': [out]}, + attrs={ + 'num_rows': num_rows, + 'num_columns': num_columns, + 'dtype': dtype, + }, + stop_gradient=True, + ) + + out.stop_gradient = True + return out + + +def full(shape, fill_value, dtype=None, name=None): + """ + + Return a Tensor with the ``fill_value`` which size is same as ``shape``. + + Args: + shape(list|tuple|Tensor): Shape of the Tensor to be created. + The data type is ``int32`` or ``int64`` . If ``shape`` is a list or tuple, + the elements of it should be integers or Tensors with shape [1]. + If ``shape`` is an Tensor, it should be an 1-D Tensor. + fill_value(bool|float|int|Tensor): The constant value + used to initialize the Tensor to be created. If ``fill_value`` is an Tensor, it must be an 1-D Tensor. + dtype(np.dtype|str, optional): Data type of the output Tensor + which can be float16, float32, float64, int32, int64, if dytpe is `None`, the data + type of created Tensor is `float32`. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Tensor which is created according to ``shape``, ``fill_value`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + data1 = paddle.full(shape=[2,1], fill_value=0, dtype='int64') + #[[0] + # [0]] + + # attr shape is a list which contains Tensor. + positive_2 = paddle.full([1], 2, "int32") + data3 = paddle.full(shape=[1, positive_2], dtype='float32', fill_value=1.5) + # [[1.5 1.5]] + + # attr shape is a Tensor. + shape = paddle.full([2], 2, "int32") + data4 = paddle.full(shape=shape, dtype='bool', fill_value=True) + # [[True True] + # [True True]] + + # attr fill_value is a Tensor. + val = paddle.full([1], 2.0, "float32") + data5 = paddle.full(shape=[2,1], fill_value=val, dtype='float32') + # [[2.0] + # [2.0]] + """ + + if dtype is None: + dtype = 'float32' + + return fill_constant(shape=shape, dtype=dtype, value=fill_value, name=name) + + +def arange(start=0, end=None, step=1, dtype=None, name=None): + """ + Returns a 1-D Tensor with spaced values within a given interval. + + Values are generated into the half-open interval [``start``, ``end``) with + the ``step``. (the interval including ``start`` but excluding ``end``). + + If ``dtype`` is float32 or float64, we advise adding a small epsilon to + ``end`` to avoid floating point rounding errors when comparing against ``end``. + + Parameters: + start(float|int|Tensor): Start of interval. The interval includes this + value. If ``end`` is None, the half-open interval is [0, ``start``). + If ``start`` is a Tensor, it is a 1-D Tensor with shape [1], with + data type int32, int64, float32, float64. Default is 0. + end(float|int|Tensor, optional): End of interval. The interval does not + include this value. If ``end`` is a Tensor, it is a 1-D Tensor with + shape [1], with data type int32, int64, float32, float64. If ``end`` + is None, the half-open interval is [0, ``start``). Default is None. + step(float|int|Tensor, optional): Spacing between values. For any out, + it is the istance between two adjacent values, out[i+1] - out[i]. + If ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with + data type int32, int64, float32, float64. Default is 1. + dtype(str|np.dtype, optional): The data type of the + output tensor. Supported data types: int32, int64, float32, float64. + If ``dytpe`` is None, the data type is float32. Default is None. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A 1-D Tensor with values from the interval [``start``, ``end``) + taken with common difference ``step`` beginning from ``start``. Its + data type is set by ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + out1 = paddle.arange(5) + # [0, 1, 2, 3, 4] + + out2 = paddle.arange(3, 9, 2.0) + # [3, 5, 7] + + # use 4.999 instead of 5.0 to avoid floating point rounding errors + out3 = paddle.arange(4.999, dtype='float32') + # [0., 1., 2., 3., 4.] + + start_var = paddle.to_tensor([3]) + out4 = paddle.arange(start_var, 7) + # [3, 4, 5, 6] + + """ + if dtype is None: + dtype = 'int64' + if end is None: + end = start + start = 0 + + out_shape = None + if ( + not isinstance(start, Variable) + and not isinstance(end, Variable) + and not isinstance(step, Variable) + ): + out_shape = [int(math.ceil((end - start) / step))] + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if not isinstance(start, Variable): + with device_guard("cpu"): + start = fill_constant([1], dtype, start, force_cpu=True) + elif start.dtype != dtype: + start = paddle.cast(start, dtype) + + if not isinstance(end, Variable): + with device_guard("cpu"): + end = fill_constant([1], dtype, end, force_cpu=True) + elif end.dtype != dtype: + end = paddle.cast(end, dtype) + + if not isinstance(step, Variable): + with device_guard("cpu"): + step = fill_constant([1], dtype, step, force_cpu=True) + elif step.dtype != dtype: + step = paddle.cast(step, dtype) + + if in_dygraph_mode(): + return _C_ops.arange(start, end, step, dtype, _current_expected_place()) + + if _in_legacy_dygraph(): + out = _legacy_C_ops.range(start, end, step) + out.stop_gradient = True + return out + + check_dtype( + dtype, 'dtype', ['float32', 'float64', 'int32', 'int64'], 'range/arange' + ) + helper = LayerHelper('range', **locals()) + out = helper.create_variable_for_type_inference(dtype, shape=out_shape) + helper.append_op( + type='range', + inputs={'Start': start, 'End': end, 'Step': step}, + outputs={'Out': out}, + ) + out.stop_gradient = True + if out_shape is not None: + out.desc.set_shape(out_shape) + return out + + +def _tril_triu_op(helper): + """Base op of tril_op and triu_op""" + op_type = helper.layer_type + x = helper.kwargs.get('x', None) + + assert x is not None, 'x cannot be None in {}'.format(op_type) + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], + op_type, + ) + if len(x.shape) < 2: + raise ValueError("x shape in {} must be at least 2-D".format(op_type)) + diagonal = helper.kwargs.get('diagonal', 0) + if not isinstance(diagonal, (int,)): + raise TypeError("diagonal in {} must be a python Int".format(op_type)) + name = helper.kwargs.get('name', None) + + if name is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + out = helper.create_variable( + name=name, dtype=x.dtype, persistable=False + ) + + helper.append_op( + type="tril_triu", + inputs={"X": x}, + attrs={ + "diagonal": diagonal, + "lower": True if op_type == 'tril' else False, + }, + outputs={"Out": out}, + ) + + return out + + +def tril(x, diagonal=0, name=None): + r""" + Returns the lower triangular part of a matrix (2-D tensor) or batch + of matrices :attr:`x`, the other elements of the result tensor are set + to 0. The lower triangular part of the matrix is defined as the elements + on and below the diagonal. + + Args: + x (Tensor): The input x which is a Tensor. + Support data types: ``bool``, ``float64``, ``float32``, ``int32``, ``int64``. + diagonal (int, optional): The diagonal to consider, default value is 0. + If :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\{(i, i)\}` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Results of lower triangular operation by the specified diagonal of input tensor x, + it's data type is the same as x's Tensor. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.arange(1, 13, dtype="int64").reshape([3,-1]) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 2 , 3 , 4 ], + # [5 , 6 , 7 , 8 ], + # [9 , 10, 11, 12]]) + + tril1 = paddle.tril(data) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 0 , 0 , 0 ], + # [5 , 6 , 0 , 0 ], + # [9 , 10, 11, 0 ]]) + + # example 2, positive diagonal value + tril2 = paddle.tril(data, diagonal=2) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 2 , 3 , 0 ], + # [5 , 6 , 7 , 8 ], + # [9 , 10, 11, 12]]) + + # example 3, negative diagonal value + tril3 = paddle.tril(data, diagonal=-1) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0 , 0 , 0 , 0 ], + # [5 , 0 , 0 , 0 ], + # [9 , 10, 0 , 0 ]]) + """ + if in_dygraph_mode(): + return _C_ops.tril_triu(x, diagonal, True) + + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, 'tril_triu') + return op(x, 'diagonal', diagonal, "lower", True) + + return _tril_triu_op(LayerHelper('tril', **locals())) + + +def triu(x, diagonal=0, name=None): + r""" + Return the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`x`, the other elements of the result tensor are set to 0. + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + Args: + x (Tensor): The input x which is a Tensor. + Support data types: ``float64``, ``float32``, ``int32``, ``int64``. + diagonal (int, optional): The diagonal to consider, default value is 0. + If :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\{(i, i)\}` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Results of upper triangular operation by the specified diagonal of input tensor x, + it's data type is the same as x's Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(1, 13, dtype="int64").reshape([3,-1]) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 2 , 3 , 4 ], + # [5 , 6 , 7 , 8 ], + # [9 , 10, 11, 12]]) + + # example 1, default diagonal + triu1 = paddle.tensor.triu(x) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 2 , 3 , 4 ], + # [0 , 6 , 7 , 8 ], + # [0 , 0 , 11, 12]]) + + # example 2, positive diagonal value + triu2 = paddle.tensor.triu(x, diagonal=2) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 0, 3, 4], + # [0, 0, 0, 8], + # [0, 0, 0, 0]]) + + # example 3, negative diagonal value + triu3 = paddle.tensor.triu(x, diagonal=-1) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1 , 2 , 3 , 4 ], + # [5 , 6 , 7 , 8 ], + # [0 , 10, 11, 12]]) + + """ + if in_dygraph_mode(): + return _C_ops.tril_triu(x, diagonal, False) + + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, 'tril_triu') + return op(x, 'diagonal', diagonal, "lower", False) + + return _tril_triu_op(LayerHelper('triu', **locals())) + + +def meshgrid(*args, **kwargs): + """ + + Takes a list of N tensors as input :attr:`*args`, each of which is 1-dimensional vector, and creates N-dimensional grids. + + Args: + *args(Tensor|list of Tensor) : tensors (tuple(list) of tensor): the shapes of input k tensors are (N1,), + (N2,),..., (Nk,). Support data types: ``float64``, ``float32``, ``int32``, ``int64``. + **kwargs (optional): Currently, only accept name in **kwargs + The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: k tensors. The shape of each tensor is (N1, N2, ..., Nk) + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randint(low=0, high=100, shape=[100]) + y = paddle.randint(low=0, high=100, shape=[200]) + + grid_x, grid_y = paddle.meshgrid(x, y) + + print(grid_x.shape) + print(grid_y.shape) + + #the shape of res_1 is (100, 200) + #the shape of res_2 is (100, 200) + + """ + + if len(args) == 1 and isinstance(args[0], (list, tuple)): + args = args[0] + if _in_legacy_dygraph(): + num = len(args) + out = _legacy_C_ops.meshgrid(list(args), num) + return out + if in_dygraph_mode(): + return _C_ops.meshgrid(list(args)) + + name = kwargs.get("name", None) + helper = LayerHelper('meshgrid', **locals()) + + if not isinstance(args, (list, tuple)): + raise TypeError("The type of input args in meshgrid should be list.") + + for id, input_ in enumerate(args): + check_dtype( + input_.dtype, + 'create data type', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'meshgrid', + ) + + num = len(args) + out = [ + helper.create_variable_for_type_inference(dtype=args[i].dtype) + for i in range(num) + ] + helper.append_op( + type='meshgrid', inputs={'X': list(args)}, outputs={'Out': out} + ) + + return out + + +def diagflat(x, offset=0, name=None): + """ + If ``x`` is a vector (1-D tensor), a 2-D square tensor with the elements of ``x`` as the diagonal is returned. + + If ``x`` is a tensor (more than 1-D), a 2-D square tensor with the elements of flattened ``x`` as the diagonal is returned. + + The argument ``offset`` controls the diagonal offset. + + + If ``offset`` = 0, it is the main diagonal. + + If ``offset`` > 0, it is superdiagonal. + + If ``offset`` < 0, it is subdiagonal. + + Args: + x (Tensor): The input tensor. It can be any shape. Its data type should be float32, float64, int32, int64. + offset (int, optional): The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal. Default: 0 (main diagonal). + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, a square matrix. The output data type is the same as input data type. + + Examples: + .. code-block:: python + :name: code-example-1 + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.diagflat(x) + print(y) + # Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 0, 0], + # [0, 2, 0], + # [0, 0, 3]]) + + y = paddle.diagflat(x, offset=1) + print(y) + # Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 1, 0, 0], + # [0, 0, 2, 0], + # [0, 0, 0, 3], + # [0, 0, 0, 0]]) + + y = paddle.diagflat(x, offset=-1) + print(y) + # Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 0, 0, 0], + # [1, 0, 0, 0], + # [0, 2, 0, 0], + # [0, 0, 3, 0]]) + + .. code-block:: python + :name: code-example-2 + + import paddle + + x = paddle.to_tensor([[1, 2], [3, 4]]) + y = paddle.diagflat(x) + print(y) + # Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 0, 0, 0], + # [0, 2, 0, 0], + # [0, 0, 3, 0], + # [0, 0, 0, 4]]) + + y = paddle.diagflat(x, offset=1) + print(y) + # Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 1, 0, 0, 0], + # [0, 0, 2, 0, 0], + # [0, 0, 0, 3, 0], + # [0, 0, 0, 0, 4], + # [0, 0, 0, 0, 0]]) + + y = paddle.diagflat(x, offset=-1) + print(y) + # Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 0, 0, 0, 0], + # [1, 0, 0, 0, 0], + # [0, 2, 0, 0, 0], + # [0, 0, 3, 0, 0], + # [0, 0, 0, 4, 0]]) + """ + padding_value = 0 + if in_dygraph_mode(): + if len(x.shape) == 1: + return _C_ops.diag(x, offset, padding_value) + else: + y = _C_ops.flatten(x, 0, -1) + return _C_ops.diag(y, offset, padding_value) + + if _in_legacy_dygraph(): + if len(x.shape) == 1: + return _legacy_C_ops.diag_v2( + x, "offset", offset, "padding_value", padding_value + ) + else: + y, _ = _legacy_C_ops.flatten_contiguous_range( + x, "start_axis", 0, "stop_axis", -1 + ) + return _legacy_C_ops.diag_v2( + y, "offset", offset, "padding_value", padding_value + ) + + check_type(x, 'x', (Variable), 'diagflat') + check_dtype( + x.dtype, 'x', ['float32', 'float64', 'int32', 'int64'], 'diagflat' + ) + check_type(offset, 'offset', (int), 'diagflat') + + helper = LayerHelper("diagflat", **locals()) + out1 = helper.create_variable_for_type_inference(dtype=x.dtype) + out1_shape = helper.create_variable_for_type_inference(x.dtype) + out2 = helper.create_variable_for_type_inference(dtype=x.dtype) + + if len(x.shape) == 1: + helper.append_op( + type='diag_v2', + inputs={'X': x}, + outputs={'Out': out2}, + attrs={'offset': offset, 'padding_value': padding_value}, + ) + else: + helper.append_op( + type='flatten_contiguous_range', + inputs={'X': x}, + outputs={'Out': out1, 'XShape': out1_shape}, + attrs={'start_axis': 0, 'stop_axis': -1}, + ) + out1.stop_gradient = True + + helper.append_op( + type='diag_v2', + inputs={'X': out1}, + outputs={'Out': out2}, + attrs={'offset': offset, 'padding_value': padding_value}, + ) + out2.stop_gradient = True + return out2 + + +def diag(x, offset=0, padding_value=0, name=None): + """ + If ``x`` is a vector (1-D tensor), a 2-D square tensor with the elements of ``x`` as the diagonal is returned. + + If ``x`` is a matrix (2-D tensor), a 1-D tensor with the diagonal elements of ``x`` is returned. + + The argument ``offset`` controls the diagonal offset: + + If ``offset`` = 0, it is the main diagonal. + + If ``offset`` > 0, it is superdiagonal. + + If ``offset`` < 0, it is subdiagonal. + + Args: + x (Tensor): The input tensor. Its shape is either 1-D or 2-D. Its data type should be float32, float64, int32, int64. + offset (int, optional): The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal. + padding_value (int|float, optional): Use this value to fill the area outside the specified diagonal band. Only takes effect when the input is a 1-D Tensor. The default value is 0. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, a square matrix or a vector. The output data type is the same as input data type. + + Examples: + .. code-block:: python + :name: code-example-1 + + import paddle + + paddle.disable_static() + x = paddle.to_tensor([1, 2, 3]) + y = paddle.diag(x) + print(y) + # Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 0, 0], + # [0, 2, 0], + # [0, 0, 3]]) + + y = paddle.diag(x, offset=1) + print(y) + # Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0, 1, 0, 0], + # [0, 0, 2, 0], + # [0, 0, 0, 3], + # [0, 0, 0, 0]]) + + y = paddle.diag(x, padding_value=6) + print(y) + # Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 6, 6], + # [6, 2, 6], + # [6, 6, 3]]) + + .. code-block:: python + :name: code-example-2 + + import paddle + + paddle.disable_static() + x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) + y = paddle.diag(x) + print(y) + # Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [1, 5]) + + y = paddle.diag(x, offset=1) + print(y) + # Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [2, 6]) + + y = paddle.diag(x, offset=-1) + print(y) + # Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True, + # [4]) + """ + if in_dygraph_mode(): + return _C_ops.diag(x, offset, padding_value) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.diag_v2( + x, "offset", offset, "padding_value", padding_value + ) + else: + check_type(x, 'x', (Variable), 'diag_v2') + check_dtype( + x.dtype, + 'x', + ['float32', 'float64', 'int32', 'int64'], + 'diag_v2', + ) + check_type(offset, 'offset', (int), 'diag_v2') + check_type(padding_value, 'padding_value', (int, float), 'diag_v2') + if len(x.shape) != 1 and len(x.shape) != 2: + raise ValueError( + "The dimension of input x must be either 1 or 2, but received {}".format( + len(x.shape) + ) + ) + + helper = LayerHelper("diag_v2", **locals()) + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='diag_v2', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'offset': offset, 'padding_value': padding_value}, + ) + + out.stop_gradient = True + return out + + +def empty(shape, dtype=None, name=None): + """ + Returns a Tensor with uninitialized data which size is same as ``shape``. + + Args: + shape(list|tuple|Tensor): Shape of the Tensor to be created. + The data type of dimension of shape is ``int32`` or ``int64`` . If ``shape`` is a list or tuple, + the elements of it should be integers or Tensors with shape [1]. + If ``shape`` is an Tensor, it should be an 1-D Tensor. + dtype(np.dtype|str, optional): Data type of the output Tensor + which can be bool, float16, float32, float64, int32, int64, if dytpe is `None`, the data + type of created Tensor use global default dtype (see ``get_default_dtype`` + for details). + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Tensor which is created according to ``shape`` and ``dtype``, and is uninitialized. + + Examples: + .. code-block:: python + + import paddle + + paddle.set_device("cpu") # and use cpu device + + # example 1: argument ``shape`` is a list which doesn't contain Tensor. + data1 = paddle.empty(shape=[2, 3], dtype='float32') + print(data1) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[0.00000000, 0. , 0.00000000], + # [0. , 0.29652897, 0.09356152]]) # uninitialized + + # example 2: argument ``shape`` is a Tensor, the data type must be int64 or int32. + shape_data = paddle.to_tensor([2, 3]).astype('int32') + data2 = paddle.empty(shape=shape_data, dtype='float32') + print(data2) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[-0.50543123, -0.09872390, -0.92634487], + # [-0.51007903, -0.02454148, 1.29315734]]) # uninitialized + + # example 3: argument ``shape`` is a list which contains Tensor. + dim2 = paddle.to_tensor([3]).astype('int32') + data3 = paddle.empty(shape=[2, dim2], dtype='float32') + print(data3) + # Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[ 0.00000000, 0. , -0.92634487], + # [-0.51007903, -0.02454148, 1.29315734]]) # uninitialized + """ + + if dtype is None: + dtype = paddle.get_default_dtype() + + dtype = convert_dtype(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + out = _C_ops.empty( + shape, convert_np_dtype_to_dtype_(dtype), _current_expected_place() + ) + out.stop_gradient = True + return out + + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + out = _legacy_C_ops.empty( + 'shape', shape, 'dtype', convert_np_dtype_to_dtype_(dtype) + ) + out.stop_gradient = True + return out + + helper = LayerHelper("empty", **locals()) + inputs = {} + + check_dtype( + dtype, + 'dtype', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'empty', + ) + check_type(shape, 'shape', (Variable, list, tuple), 'empty') + + if isinstance(shape, Variable): + check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'empty') + + attrs = {} + utils.get_shape_tensor_inputs( + inputs=inputs, attrs=attrs, shape=shape, op_type='empty' + ) + + out = helper.create_variable_for_type_inference(dtype=dtype) + attrs['dtype'] = convert_np_dtype_to_dtype_(dtype) + helper.append_op( + type='empty', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs, + stop_gradient=True, + ) + out.stop_gradient = True + return out + + +def empty_like(x, dtype=None, name=None): + """ + Returns a Tensor with uninitialized data which has identical shape of ``x`` and ``dtype``. + If the ``dtype`` is None, the data type of Tensor is same with ``x``. + + Args: + x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64. + dtype(np.dtype|str, optional): The data type of output. The data type can be one + of bool, float16, float32, float64, int32, int64. The default value is None, which means the output + data type is the same as input. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: Tensor which is created according to ``x`` and ``dtype``, and is uninitialized. + + Examples: + .. code-block:: python + + import paddle + + paddle.set_device("cpu") # and use cpu device + + x = paddle.randn([2, 3], 'float32') + output = paddle.empty_like(x) + #[[1.8491974e+20 1.8037303e+28 1.7443726e+28] # uninitialized + # [4.9640171e+28 3.0186127e+32 5.6715899e-11]] # uninitialized + """ + + if dtype is None: + dtype = x.dtype + dtype = convert_dtype(dtype) + + if in_dygraph_mode(): + out = _C_ops.empty( + x.shape, + convert_np_dtype_to_dtype_(dtype), + _current_expected_place(), + ) + out.stop_gradient = True + return out + + if _in_legacy_dygraph(): + out = _legacy_C_ops.empty( + 'shape', x.shape, 'dtype', convert_np_dtype_to_dtype_(dtype) + ) + out.stop_gradient = True + return out + + helper = LayerHelper("empty_like", **locals()) + check_variable_and_dtype( + x, + 'x', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'empty_like', + ) + check_dtype( + dtype, + 'dtype', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'empty_like', + ) + out = helper.create_variable_for_type_inference(dtype=dtype) + + inputs = {} + attrs = {} + attrs['dtype'] = convert_np_dtype_to_dtype_(dtype) + shape = paddle.shape(x) + utils.get_shape_tensor_inputs( + inputs=inputs, attrs=attrs, shape=shape, op_type='empty_like' + ) + + helper.append_op( + type='empty', + inputs=inputs, + outputs={'Out': [out]}, + attrs=attrs, + stop_gradient=True, + ) + out.stop_gradient = True + return out + + +def assign(x, output=None): + """ + + Copy value of the :attr:`x` to the :attr:`output`. + + Parameters: + x (Tensor|np.ndarray|list|tuple|scalar): A Tensor, numpy ndarray, tuple/list of scalar, + or scalar. Its data type can be float16, float32, float64, int32, int64 or bool. Note: the float64 data will be converted to float32 because of current platform protobuf + data limitation. + output (Tensor, optional): A Tensor. If :attr:`output` is None, a new Tensor will be created as :attr:`output`. Default: None. + + Returns: + Tensor: A Tensor with the same shape, data type and value as :attr:`x`. + + Examples: + .. code-block:: python + + import paddle + import numpy as np + data = paddle.full(shape=[3, 2], fill_value=2.5, dtype='float64') # [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + array = np.array([[1, 1], + [3, 4], + [1, 3]]).astype(np.int64) + result1 = paddle.zeros(shape=[3, 3], dtype='float32') + paddle.assign(array, result1) # result1 = [[1, 1], [3 4], [1, 3]] + result2 = paddle.assign(data) # result2 = [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + result3 = paddle.assign(np.array([[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]], dtype='float32')) # result3 = [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + """ + input = x + helper = LayerHelper('assign', **locals()) + check_type( + input, + 'input', + (Variable, np.ndarray, list, tuple, float, int, bool), + 'assign', + ) + is_inplace = True if output is not None else False + + if np.isscalar(input) and not isinstance(input, str): + input = np.array([input]) + elif isinstance(input, (list, tuple)): + input = np.array(input) + # NOTE(Aurelius84): Why we judge core.VarBase? + # In case of @to_static, a VarBase can be as input of `assign`, + # but _non_static_mode()==False under @to_static, which means + # isinstance(VarBase, Variable) == False. It will cause return None + # after this api. + if isinstance(input, (Variable, core.VarBase, core.eager.Tensor)): + if in_dygraph_mode(): + if output is None: + output = _C_ops.assign(input) + else: + _C_ops.assign_out_(input, output) + elif _in_legacy_dygraph(): + if output is None: + output = core.VarBase() + _legacy_C_ops.assign(input, output) + else: + check_dtype( + input.dtype, + 'input', + [ + 'float16', + 'uint16', + 'float32', + 'float64', + 'int32', + 'int64', + 'uint8', + 'bool', + ], + 'assign', + '(When the type of input in assign is Variable.)', + ) + if output is None: + output = helper.create_variable_for_type_inference( + dtype=input.dtype + ) + helper.append_op( + type='assign', inputs={'X': [input]}, outputs={'Out': [output]} + ) + elif isinstance(input, np.ndarray): + # We now support the form of [var, VAR...] if the Var.shape=[1,] + if len(input.shape) > 0 and any(isinstance(x, Variable) for x in input): + # We only deal with the case where the list is nested one level, convert all scalars into variables, and then use stack to process. It is necessary to ensure the consistency of types. + if not all( + [ + x.shape == (1,) + for x in input + if isinstance(x, (Variable, core.eager.Tensor)) + ] + ): + raise TypeError( + "Unsupport paddle.assign([Variable, Variable...]) with non-scalar variable." + ) + + def convert_scalar(x): + if not isinstance(x, (Variable, core.eager.Tensor)): + return assign(x) + return x + + to_stack_list = list(map(convert_scalar, input)) + ret = paddle.stack(to_stack_list) + ret = paddle.squeeze(ret, -1) + return ret + + if input.dtype == 'object': + """may be this form [[Var], [Var], [3], [4]], we reject them.""" + raise TypeError( + "The type of received input == `object`, it is not supported to convert to tensor, such as [[Var], [Var], [3], [4]]" + ) + + dtype = convert_np_dtype_to_dtype_(input.dtype) + if dtype == core.VarDesc.VarType.FP64: + # Setting FP64 numpy data is not supported in Paddle, so we + # use FP32 here + warnings.warn( + "paddle.assign doesn't support float64 input now due " + "to current platform protobuf data limitation, we convert " + "it to float32" + ) + dtype = core.VarDesc.VarType.FP32 + if dtype == core.VarDesc.VarType.BOOL: + value_name = "bool_values" + values = [int(v) for v in input.flat] + elif dtype == core.VarDesc.VarType.FP32: + value_name = "fp32_values" + values = [float(v) for v in input.flat] + elif dtype == core.VarDesc.VarType.INT32: + value_name = "int32_values" + values = [int(v) for v in input.flat] + elif dtype == core.VarDesc.VarType.INT64: + value_name = "int64_values" + values = [int(v) for v in input.flat] + else: + raise TypeError( + "When the type of 'input' in assign is numpy.ndarray, " + "the data type of 'input' must be bool, float32, int32 or int64, but " + "received %s." % convert_dtype(dtype) + ) + if input.size > 1024 * 1024: + raise ValueError( + "The size of input is too big. Please consider " + "saving it to file and 'load_op' to load it" + ) + if in_dygraph_mode(): + if output is None: + output = zeros(list(input.shape), dtype) + _C_ops.assign_value_( + output, + list(input.shape), + dtype, + values, + _current_expected_place(), + ) + elif _in_legacy_dygraph(): + if output is None: + output = core.VarBase() + _legacy_C_ops.assign_value( + output, + 'shape', + list(input.shape), + 'dtype', + dtype, + value_name, + values, + ) + else: + if output is None: + output = helper.create_variable_for_type_inference( + dtype=input.dtype + ) + helper.append_op( + type='assign_value', + outputs={'Out': [output]}, + attrs={ + 'dtype': dtype, + 'shape': list(input.shape), + value_name: values, + }, + ) + + if is_inplace and _in_legacy_dygraph(): + output._bump_inplace_version() + + return output + + +def clone(x, name=None): + """ + Returns a copy of input Tensor. It will always have a Tensor copy. + + In addition, This function is derivable, so gradients will flow back from the output to input. + + Parameters: + x (Tensor): The input Tensor. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, A Tensor copied from ``input``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.ones([2]) + x.stop_gradient = False + clone_x = paddle.clone(x) + + y = clone_x**3 + y.backward() + print(clone_x.grad) # [3] + print(x.grad) # [3] + """ + return x.clone() + + +# NOTE(zhiqiu): not public +def _memcpy(input, place=None, output=None): + """ + + The OP copies the :attr:`input` to the :attr:`output`. + NOTE: currently, only support CUDAPlace <-> CUDAPinnedPlace or NPUPlace <-> CPUPlace. + + Parameters: + input (Tensor): A tensor. Its data type supports float16, float32, float64, int32, int64, and bool. + device (Place): Target place for the output. + output (Tensor, optional): A tensor. If :attr:`output` is None, a new tensor will + be created as :attr:`output`. Default: None. + + Returns: + Tensor, A tensor with the same shape, data type and value as :attr:`input`. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.full(shape=[3, 2], fill_value=2.5, dtype='float64') # [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + result = paddle._memcpy(data, place=paddle.CPUPlace()) # result2 = [[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]] + """ + helper = LayerHelper('memcpy', **locals()) + check_type(input, 'input', (Variable), 'memcpy') + + if isinstance(input, (Variable, core.VarBase)): + check_dtype( + input.dtype, + 'input', + [ + 'float16', + 'uint16', + 'float32', + 'float64', + 'int32', + 'int64', + 'uint8', + 'bool', + ], + 'memcpy', + '(When the type of input in memcpy is Variable.)', + ) + if output is None: + output = helper.create_variable_for_type_inference(dtype=input.dtype) + + dst_place_type = -1 + if place is None: + dst_place_type = -1 + else: + p = core.Place() + p.set_place(place) + if p.is_cpu_place(): + dst_place_type = 0 + elif p.is_gpu_place(): + dst_place_type = 1 + elif p.is_cuda_pinned_place(): + dst_place_type = 2 + elif p.is_xpu_place(): + dst_place_type = 3 + elif p.is_npu_place(): + dst_place_type = 4 + + attrs = {'dst_place_type': dst_place_type} + helper.append_op( + type='memcpy', + inputs={'X': [input]}, + outputs={'Out': [output]}, + attrs=attrs, + ) + return output + + +def complex(real, imag, name=None): + """Return a compelx tensor given the real and image component. + + Args: + real (Tensor): The real component. The data type should be 'float32' or 'float64'. + imag (Tensor): The image component. The data type should be the same as ``real``. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: The output tensor. The data type is 'complex64' or 'complex128', with the same precision as ``real`` and ``imag``. + + **Note**: + ``paddle.complex`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(2, dtype=paddle.float32).unsqueeze(-1) + y = paddle.arange(3, dtype=paddle.float32) + z = paddle.complex(x, y) + print(z) + # Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True, + # [[0j , 1j , 2j ], + # [(1+0j), (1+1j), (1+2j)]]) + """ + if in_dygraph_mode(): + return _C_ops.complex(real, imag) + + if paddle.in_dynamic_mode(): + return paddle._legacy_C_ops.complex(real, imag) + + check_variable_and_dtype(real, 'real', ['float32', 'float64'], 'complex') + check_variable_and_dtype(imag, 'imag', ['float32', 'float64'], 'complex') + + op_type = "complex" + helper = LayerHelper(op_type, **locals()) + inputs = {"X": real, "Y": imag} + out = helper.create_variable_for_type_inference( + dtype=_real_to_complex_dtype(real.dtype) + ) + outputs = {"Out": out} + attrs = {} + helper.append_op(type=op_type, inputs=inputs, attrs=attrs, outputs=outputs) + return out + + +def tril_indices(row, col, offset=0, dtype='int64'): + """ + Return the indices of the lower triangular part of the 2-D matrix + whose row and col is knowed.Indices are ordered based on row and then columns. + The lower triangular part of the matrix is defined as the elements on + and below the diagonal. + + Args: + row (int): The input x which is a int number describe the number of row of the matrix. + col (int): The input x which is a int number describe the number of col of the matrix. + offset (int, optional): The offset to consider, default value is 0. + + - If offset = 0, all elements on and below the main diagonal are retained. + - If offset > 0, include just as many diagonals above the main diagonal. + - If offset < 0, excludes just as many diagonals below the main diagonal. + + dtype (int, optional): the data type of the output tensor, can be int32, int64. + + Returns: + Tensor: Results of the indices of lower triangular part of a row * col matrix, + where the first row contains row coordinates of and the second row contains column coordinates. + + Examples: + .. code-block:: python + + import paddle + + # example 1, default offset value + data1 = paddle.tril_indices(4,4,0) + print(data1) + # [[0, 1, 1, 2, 2, 2, 3, 3, 3, 3], + # [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]] + + # example 2, positive offset value + data2 = paddle.tril_indices(4,4,2) + print(data2) + # [[0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3], + # [0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]] + + # example 3, negative offset value + data3 = paddle.tril_indices(4,4,-1) + print(data3) + # [[ 1, 2, 2, 3, 3, 3], + # [ 0, 0, 1, 0, 1, 2]] + """ + if not isinstance(row, int) or row < 0: + raise TypeError("row should be a non-negative int") + + if col is not None: + if not isinstance(col, int) or col < 0: + raise TypeError("col should be a non-negative int") + else: + col = row + + if not isinstance(offset, int): + raise TypeError("offset should be a int") + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + out = _C_ops.tril_indices( + row, col, offset, dtype, _current_expected_place() + ) + return out + + if _in_legacy_dygraph(): + out = _legacy_C_ops.tril_indices( + 'rows', row, 'cols', col, 'offset', offset, "dtype", dtype + ) + return out + + else: + helper = LayerHelper("tril_indices", **locals()) + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='tril_indices', + inputs={}, + outputs={'out': [out]}, + attrs={'rows': row, 'cols': col, 'offset': offset, 'dtype': dtype}, + ) + return out + + +def triu_indices(row, col=None, offset=0, dtype='int64'): + """ + Return the indices of the upper triangular part of the 2-D matrix + whose row and col is known. Indices are ordered based on row and then columns. + The upper triangular part of the matrix is defined as the elements on + and above the diagonal. + + Args: + row (int): The input x which is a int number describe the number of row of the matrix. + col (int, optional): The input x which is a int number describe the number of col of the matrix. + default value for col is None, then it will be set equal to row, indicting a square matix. + offset (int, optional): The offset to consider, default value is 0. + + - If offset = 0, all elements on and above the main diagonal are retained. + - If offset > 0, include just as few diagonals above the main diagonal. + - If offset < 0, excludes just as few diagonals below the main diagonal. + + dtype (str|np.dtype|paddle.dtype, optional): the data type of the output tensor, + can be int32, int64, default value is int64. + Returns: + Tensor: Results of the indices of upper triangular part of a row * col matrix, + where the first row contains row coordinates of and the second row contains column coordinates. + + Examples: + .. code-block:: python + + import paddle + # example 1, default offset value + data1 = paddle.triu_indices(4,4,0) + print(data1) + # [[0, 0, 0, 0, 1, 1, 1, 2, 2, 3], + # [0, 1, 2, 3, 1, 2, 3, 2, 3, 3]] + # example 2, positive offset value + data2 = paddle.triu_indices(4,4,2) + print(data2) + # [[0, 0, 1], + # [2, 3, 3]] + # example 3, negative offset value + data3 = paddle.triu_indices(4,4,-1) + print(data3) + # [[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3], + # [0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 2, 3]] + """ + if not isinstance(row, int) or row < 0: + raise TypeError("row should be a non-negative int") + + if col is not None: + if not isinstance(col, int) or col < 0: + raise TypeError("col should be a non-negative int") + else: + col = row + + if not isinstance(offset, int): + raise TypeError("offset should be a int") + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + out = _C_ops.triu_indices( + row, col, offset, dtype, _current_expected_place() + ) + return out + + if _in_legacy_dygraph(): + out = _legacy_C_ops.triu_indices( + 'row', row, 'col', col, 'offset', offset, "dtype", dtype + ) + return out + + else: + helper = LayerHelper("triu_indices", **locals()) + + out = helper.create_variable_for_type_inference(dtype=dtype) + + helper.append_op( + type='triu_indices', + inputs={}, + outputs={'out': [out]}, + attrs={'row': row, 'col': col, 'offset': offset, 'dtype': dtype}, + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/einsum.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffd461c633c5cf44c55d2231f6722ebeb498bd2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/einsum.py @@ -0,0 +1,1100 @@ +# Copyright (c) 2021 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. + +import itertools +import numpy as np +import re + +from .linalg import dot, matmul, transpose +from .manipulation import squeeze, unsqueeze, reshape +from .math import multiply +from .math import sum as paddle_sum +from ..fluid.framework import _in_legacy_dygraph +from paddle import _C_ops, _legacy_C_ops +from ..fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..fluid.layer_helper import LayerHelper +from ..fluid.framework import ( + _non_static_mode, + in_dygraph_mode, + _in_legacy_dygraph, +) +import collections +import string +import opt_einsum + +from paddle.common_ops_import import dygraph_only + +__all__ = [] + + +def parse_op_labels(labelstr, operand): + ''' + Parse labels for an input operand. + + Parameters + ---------- + labelstr: + the input label string + operand: + the input operand + + Returns + ------- + the input operand's full label string in which all anonymous dimensions are + labeled in dots. + ''' + # Sanity checks + for c in labelstr.replace('.', ''): + assert ( + c.isalpha() + ), f"Invalid equation: {c} is not a valid label, which should be letters." + + assert ( + labelstr.replace('...', '', 1).find('.') == -1 + ), f"Invalid equation: `.` is found outside of an ellipsis." + + # Check shape. Note, in Paddle a tensor rank is always nonzero + ndims = len(operand.shape) + assert ndims > 0 + + full_labelstr = labelstr.replace('...', '.' * (ndims - len(labelstr) + 3)) + + assert ( + len(full_labelstr) == ndims + ), f"Invalid equation: the label string '{labelstr}' misses dimensions." + + return full_labelstr + + +def parse_labels(labelstr, operands): + ''' + Parse label strings for all input operands. + + Parameters + ---------- + labelstr: + The equation's label string + operands: + The input operands + + Returns + ------- + list of full label strings for all input operands + ''' + + nop_labels = labelstr.split(',') + assert len(nop_labels) == len(operands), ( + f"Invalid equation: the number of operands is {len(operands)}, " + f"but found {len(nop_labels)} segments in the label equation." + ) + + return list(map(parse_op_labels, nop_labels, operands)) + + +def validate_rhs(rhs, input_labels, n_bcast_dims): + ''' + Check whether the equation's right hand side is valid + ''' + # Sanity check. + if n_bcast_dims > 0: + assert ( + '...' in rhs + ), f"Invalid equation: missing ellipsis in output labels." + + rhs = rhs.replace('...', '') + rhs_set = set(rhs) + + # Hidden assumption: availble labels don't include '.' + assert '.' not in input_labels + + # Verify that output labels all come from the set of input labels + non_input_labels = rhs_set.difference(input_labels) + assert not non_input_labels, ( + f"Invalid equation: " + f"output label {sorted(non_input_labels)} not used by any input." + ) + # Verify that output labels are not duplicate + assert len(rhs) == len( + rhs_set + ), f"Invalid equation: duplicate output labels are found." + + +def build_view(in_labels, out_labels): + ''' + Build an inverse map of dimension indices. Three conditions must hold for + the result to be meaningful. + First, no duplicate letter labels in each label string. + Second, the number of dots in dimout_labels >= that in in_labels. + Third, dots are contiguous in each label string. + + Parameters + ---------- + in_labels: + The dimension labels to map to + out_labels: + The dimension labels to map from + + Returns + ------- + The inverse map from out_labels to in_labels. The length of the inverse map equals that of + out_labels. -1 is filled if there's no matching intput dimension for a specific label. + + Examples + -------- + in_labels = 'ij..', out_labels = '..ji' + inv_map = [2, 3, 1, 0] + in_labels = 'ij..', out_labels = '..kji' + inv_map = [2, 3, -1, 1, 0] + ''' + + inv_map = [-1] * len(out_labels) + + # First build the broadcast dimension mapping + # Find the broadcast index range in out_labels + r = re.search(r'\.+', out_labels) + if r: + start, end = r.start(), r.end() + s = re.search(r'\.+', in_labels) + # fill the broadcast dimension indices from right to left. + if s: + for ax, dim in zip( + range(start, end)[::-1], range(s.start(), s.end())[::-1] + ): + inv_map[ax] = dim + + # Now work on non-broadcast dimensions + if r: + it = itertools.chain(range(start), range(end, len(out_labels))) + else: + it = iter(range(len(out_labels))) + + for i in it: + inv_map[i] = in_labels.find(out_labels[i]) + + return inv_map + + +def build_global_view(nop_labels, rhs, n_bcast_dims): + ''' + Build the global view, which is a layout of all dimension labels + plus an index table that maps from the layout to the dimensions + in each operand. In the global view, the dimensions are arranged + such that output ones are put on the left and contraction ones + are put on the right. + + Parameters + ---------- + nop_labels: + The input full label strings of all input operands + rhs: + The equation right hand side + n_bcast_dims: + The maxium number of broadcast dimensions + + Returns + ------- + A tuple of g_labels, g_view, g_nout, g_count + g_labels: + the layout of all labels in a string + g_view: + the index table + g_nout: + the number of output dimensions + g_count: + the counter array for dimension contractions + ''' + # Put all labels in alphabetical order + concat = sorted(''.join(nop_labels).replace('.', '')) + labels, count = [], [] + for a, b in zip(['.'] + concat, concat): + if a != b: + labels.append(b) + count.append(1) + else: + count[-1] += 1 + + if rhs != None: + validate_rhs(rhs, labels, n_bcast_dims) + g_labels_out = rhs.replace('...', '.' * n_bcast_dims) + else: + g_labels_out = '.' * n_bcast_dims + ''.join( + l for l, c in zip(labels, count) if c == 1 + ) + + for i in range(len(count))[::-1]: + if labels[i] in g_labels_out: + labels.pop(i) + count.pop(i) + + g_labels_sum = ''.join(labels) + g_labels = g_labels_out + g_labels_sum + g_view = list(map(lambda i: build_view(i, g_labels), nop_labels)) + g_nout = len(g_labels_out) + g_count = count + + return g_labels, g_view, g_nout, g_count + + +def build_global_shape(g_view, g_labels, op_shapes): + ''' + The global shape is the shape of all dimensions rearranged and broadcasting + to the global view. It's a reference data structure for einsum planning. + + Parameters + ---------- + g_view: + the global view + op_shapes: + the shapes of the all operands + + Returns + ------- + g_shape: + the global shape vector + g_masks: + list of shape masks for each operand. A dimension's shape mask is a boolean + indicating whether its size > 1, in other words, it's not squeezable + ''' + view_shapes = [] + g_masks = [] + + for view, op_shape in zip(g_view, op_shapes): + view_shapes.append([op_shape[dim] if dim > -1 else 1 for dim in view]) + + g_shape = [set(sizes_per_ax) - {1} for sizes_per_ax in zip(*view_shapes)] + + non_bcastable = [ax for ax, sizes in enumerate(g_shape) if len(sizes) > 1] + + assert not non_bcastable, ( + f"Invalid operands: label {g_labels[non_bcastable[0]]} " + f"corresponds to non-broadcastable dimensions." + ) + + g_shape = [sizes.pop() if len(sizes) > 0 else 1 for sizes in g_shape] + + g_masks = [ + [s > 1 or s == -1 for s in view_shape] for view_shape in view_shapes + ] + + return g_shape, g_masks + + +def has_duplicated_labels(labels): + ''' + Returns True if there is any duplicate label. + ''' + labels = labels.replace('.', '') + return len(labels) > len(set(labels)) + + +def diagonalize(labels, operand): + ''' + Merges dimensions with duplicate labels. + + For those dimensions with duplicate labels, merge them into one dimension + which represents the diagonal elements. This requires the dimensions with + duplicate labels are equal sized. + + Examples + -------- + 'ijj...i' would be merged into 'ij...' + ''' + assert not has_duplicated_labels( + labels + ), f'Duplicate labels are not supported.' + + return labels, operand + + +def plan_reduce(plan, op, reduce_dims, keepdim): + ''' + Add reduce to the plan + ''' + varname = f'op{op}' + + f = lambda var, dims: paddle_sum(var, dims, keepdim=keepdim) + step = f, [varname], varname, reduce_dims + plan.add_step(step) + + +def plan_scalar_prod(plan, op1, op2): + varnames = [f'op{op1}', f'op{op2}'] + f = lambda var1, var2: paddle_sum(var1) * var2 + # f = lambda var1, var2: var1 * var2 + step = f, varnames, varnames[1] + plan.add_step(step) + + +def plan_matmul(plan, g_view, op1, op2, g_supports, g_shape, I, J1, J2, K): + ''' + plan matmul + ''' + # Transpose and re-shape op1 and op2 in I, J1, K and I, J2, K + # Then apply matmul(x, y, transpose_x=False, tranpose_y=True) + var1, var2 = f'op{op1}', f'op{op2}' + + op1_view, op2_view = [g_view[op] for op in (op1, op2)] + + I1 = [idx for idx in I if op1_view[idx] >= 0] + I2 = [idx for idx in I if op2_view[idx] >= 0] + op1_view = np.array(op1_view) + op1_dims = op1_view[I1 + J1 + K] + + op2_view = np.array(op2_view) + op2_dims = op2_view[I2 + J2 + K] + + op1_mask, op2_mask = [g_supports[op] for op in (op1, op2)] + op1_vshape = np.array([s if m else 1 for s, m in zip(g_shape, op1_mask)]) + op2_vshape = np.array([s if m else 1 for s, m in zip(g_shape, op2_mask)]) + vshape = np.maximum(op1_vshape, op2_vshape) + + i1, i2, j1, j2, k = map(len, (I1, I2, J1, J2, K)) + + if any(op1_dims != np.arange(len(op1_dims))): + # print(f'perm1: {perm1}') + step = transpose, [var1], var1, list(op1_dims) + plan.add_step(step) + + if any(op2_dims != np.arange(len(op2_dims))): + # print(f'perm2: {perm2}') + step = transpose, [var2], var2, list(op2_dims) + plan.add_step(step) + + # Check if conditions hold for turnning the operation into a matmul + if ( + j1 + j2 > 0 + and k > 0 + and -1 not in np.concatenate((op1_vshape, op2_vshape)) + ): + op1_shape = ( + list(op1_vshape[I]) + + [np.prod(op1_vshape[J1])] + + [np.prod(op1_vshape[K])] + ) + op2_shape = ( + list(op2_vshape[I]) + + [np.prod(op2_vshape[J2])] + + [np.prod(op2_vshape[K])] + ) + + # Merge J dims and K dims by reshaping + step = reshape, [var1], var1, op1_shape + plan.add_step(step) + step = reshape, [var2], var2, op2_shape + plan.add_step(step) + + # Matmul + step = matmul, [var1, var2], var2, False, True + plan.add_step(step) + + # Reshape back + shape = list(vshape[I + J1 + J2]) + step = reshape, [var2], var2, shape + plan.add_step(step) + + elif j1 == j2 == k == 1: + # Can still do matmul even unknown shapes are present + step = matmul, [var1, var2], var2, False, True + plan.add_step(step) + + # In the rest cases we opt for ops other than matmul + else: + # unsqueeze operands include J1...J2... dimensions + if j2: + fill = list(range(i1 + j1, i1 + j1 + j2)) + step = unsqueeze, [var1], var1, fill + plan.add_step(step) + if j1: + fill = list(range(i2, i2 + j1)) + step = unsqueeze, [var2], var2, fill + plan.add_step(step) + # In case of no dimensions to contract, do an elementwise multiply + if k == 0: + # make broadcast + step = multiply, [var1, var2], var2 + plan.add_step(step) + # Contract and no join, turn into a dot + elif j1 + j2 == 0 and k == 1: + step = unsqueeze, [var1], var1, [-2] + plan.add_step(step) + step = unsqueeze, [var2], var2, [-1] + plan.add_step(step) + step = matmul, [var1, var2], var2 + plan.add_step(step) + step = squeeze, [var2], var2, [-1, -2] + plan.add_step(step) + elif j1 + j2 == 0 and not -1 in np.concatenate( + (op1_vshape[K], op2_vshape[K]) + ): + assert all(op1_vshape[K] == op2_vshape[K]) + step = ( + reshape, + [var1], + var1, + list(op1_vshape[I]) + [1] + [np.prod(op1_vshape[K])], + ) + plan.add_step(step) + step = ( + reshape, + [var2], + var2, + list(op2_vshape[I]) + [1] + [np.prod(op2_vshape[K])], + ) + plan.add_step(step) + step = matmul, [var1, var2], var2, False, True + plan.add_step(step) + step = squeeze, [var2], var2, [-1, -2] + plan.add_step(step) + else: + step = multiply, [var1, var2], var2 + plan.add_step(step) + reduce_dims = list(range(-k, 0)) + plan_reduce(plan, op2, reduce_dims, keepdim=False) + + # Wrap up, updating auxiliary data + # Updating g_mask for I and J axes + for ax in I + J1 + J2: + op2_mask[ax] = vshape[ax] > 1 or vshape[ax] == -1 + + for ax in K: + op2_mask[ax] = False + + for ax in range(len(op2_view)): + op2_view[ax] = -1 + dim = 0 + for ax in I + J1 + J2: + op2_view[ax], dim = dim, dim + 1 + + g_view[op2] = list(op2_view) + + +def plan_summation( + plan, g_view, op1, op2, g_supports, g_shape, g_count, n_bcast +): + ''' + Plan various kinds of summation + ''' + op1_view, op2_view = g_view[op1], g_view[op2] + op1_mask, op2_mask = g_supports[op1], g_supports[op2] + + ndim = len(op1_view) + nout = ndim - len(g_count) + + count = [0] * nout + g_count + + I, K, J1, J2 = list(range(n_bcast)), [], [], [] + + for ax, dim1, dim2 in zip( + range(n_bcast, ndim), op1_view[n_bcast:], op2_view[n_bcast:] + ): + + if (dim1 != -1) != (dim2 != -1): + if dim1 != -1: + J1.append(ax) + else: + J2.append(ax) + elif dim1 != -1: + fold = int(op1_mask[ax]) + int(op2_mask[ax]) + if ax >= nout and fold == count[ax]: + # Ready to fold the dimensions + K.append(ax) + count[ax] -= fold + else: + I.append(ax) + count[ax] -= max(fold - 1, 0) + + # Update g_count + g_count[:] = count[nout:] + + # Now it's OK to merge the K dims as the same shape holds + # print(f'I: {I} J1: {J1} J2: {J2} K: {K}') + plan_matmul(plan, g_view, op1, op2, g_supports, g_shape, I, J1, J2, K) + + +def rearrange(axes): + perm, fill = [], [] + for ax, dim in enumerate(axes): + if dim < 0: + fill.append(ax) + else: + perm.append(dim) + # Trivial permutation returns [] + if all(i == dim for i, dim in enumerate(perm)): + perm = [] + + return perm, fill + + +def plan_broadcast(plan, operands, nop_axes): + ''' + Plan broadcast across + ''' + nop = len(operands) + varnames = [f'op{i}' for i in range(nop)] + + for i, op_axes in zip(range(nop), nop_axes): + # Re-arrange the dimesions according to the global layout + perm, fill = rearrange(op_axes) + var = varnames[i] + if perm: + step = transpose, [var], var, perm + plan.add_step(step) + if fill: + step = unsqueeze, [var], var, fill + plan.add_step(step) + + def f(*args): + expr = ' * '.join(varnames) + return eval(expr, dict(zip(varnames, args))) + + step = f, varnames, None + plan.add_step(step) + + +class Plan: + def __init__(self): + self.env = {} + self.steps = [] + + def add_step(self, step): + self.steps.append(step) + + def get_var(self, varname): + return self.env[varname] if varname in self.env else None + + def set_var(self, varname, var): + self.env[varname] = var + + def show(self): + res = None + for f, in_varnames, out_varname, *args in self.steps: + print(repr((out_varname, f, *in_varnames, *args))) + return res + + def execute(self): + res = None + for f, in_varnames, out_varname, *args in self.steps: + res = f(*map(self.get_var, in_varnames), *args) + if out_varname: + self.set_var(out_varname, res) + return res + + +def plan_einsum(operands, g_view, g_shape, g_supports, g_count, n_bcast): + ''' + Plans the actual execution steps. + Results + ------- + the execution plan + ''' + nop = len(operands) + ndim = len(g_view[0]) + nout = ndim - len(g_count) + + # Initialize a plan with an environment + plan = Plan() + op_names = [f'op{i}' for i in range(nop)] + list(map(plan.set_var, op_names, operands)) + + # In case no dimensions to combine, do broadcast straight across + if not g_count: + plan_broadcast(plan, operands, g_view) + return plan + + # Down count degenerate contraction dimensions. + for view, support in zip(g_view, g_supports): + # To collect the down count number, we use a type casting trick + down_count = [ + int((d + 1) and (not s)) + for d, s in zip(view[nout:], support[nout:]) + ] + for i, count in enumerate(down_count): + g_count[i] -= count + + # Reduce any dimension for which g_support is set and g_count == 1 + for i, view, mask in zip(range(nop), g_view, g_supports): + to_reduce = [] + for dim, masked, count in zip(view[nout:], mask[nout:], g_count): + to_reduce.append(dim if (masked and count == 1) else -1) + + reduce_dims = list(filter(lambda x: x > -1, to_reduce)) + if reduce_dims: + plan_reduce(plan, i, reduce_dims, keepdim=True) + + # Unset mask and decrease g_count for the reduced dimensions + for i, d in enumerate(to_reduce): + ax = i + nout + mask[ax] = mask[ax] and (d == -1) + g_count[i] -= 0 if d == -1 else 1 + + # Plan the summations over the operand sequence + for i in range(nop): + # plan a single step + + if i == 0: + continue + + # We'd like to arrange the dimensions in the following way: + # [I... J... K...] + # [I... J... K...] + # where + # I... are aligned and not to be combined immediately + # J... are not aligned and not to be combined immediately + # K... are aligned and should be immediately combined + # At this point the non-trivial broadcast dimensinos in K are already reduced + # and removed. That means all K dimensions are aligned and their sizes are not 1. + # We then inspect the layout of I,J,K plus the above observation to make + # specializatoin decisions. The current strategy is set as follows: + # (1) if I... J... K... are all empty, it's multiplying a scalar + # (2) if K... are empty, better use a broadcast + # (3) if I... J... empty and K... not empty, a vector-vector multiply (or a dot) + # (4) Elsewise, either I... or J... not empty, and K... not empty, use a general matmul + + # Resolve the summation kind: dot, matmul or * + if not any(g_supports[i - 1]): + # op1 is a one element tensor. + plan_scalar_prod(plan, i - 1, i) + else: + plan_summation( + plan, g_view, i - 1, i, g_supports, g_shape, g_count, n_bcast + ) + + # for ax, dim in enumerate(g_view[nop-1][:nout]): + # assert dim == ax + assert all(not masked for masked in g_supports[nop - 1][nout:]) + + view = g_view[-1] + if any(ax != dim for ax, dim in enumerate(view[:nout])): + perm = [dim for dim in view if dim >= 0] + if sorted(perm) != perm: + varname = f'op{nop-1}' + step = transpose, [varname], varname, perm + plan.add_step(step) + dim = 0 + unsqueeze_dims = [] + for ax, d in enumerate(view): + if d != -1: + view[ax], dim = dim, dim + 1 + for ax, d in enumerate(view[:nout]): + if d == -1: + unsqueeze_dims.append(ax) + if unsqueeze_dims: + varname = f'op{nop-1}' + step = unsqueeze, [varname], varname, unsqueeze_dims + plan.add_step(step) + + squeeze_dims = [dim for dim in view[nout:] if dim != -1] + if squeeze_dims: + # plan_reduce(plan, nop-1, reduce_dims, keepdim=False) + varname = f'op{nop-1}' + step = squeeze, [varname], varname, squeeze_dims + plan.add_step(step) + + return plan + + +def preprocess(equation, *operands): + """ + check equation / raise error, default right labels generation + """ + equation = equation.replace(" ", "") + nop = len(operands) + assert nop > 0, ( + "Required at least one operand in Einsum API, but received %s " % nop + ) + + # Part the equation to left hand side and right hand side + lhs, *rhs = equation.lower().split('->') + assert len(rhs) < 2, "Invalid equation: multiple `->` were found." + + labels = parse_labels(lhs, operands) + # Note, we distinguish between 'ij->' and 'ij' by setting rhs to '' and None + rhs = rhs[0] if rhs else None + if rhs is None: + rhs = rhs_inference(lhs) + + assert len(lhs.split(',')) == len(operands), ( + f"Invalid equation: the number of operands is {len(operands)}, " + f"but found {len(lhs.split(','))} segments in the label equation." + ) + + assert not ( + '...' in lhs and '...' not in rhs + ), f'Invalid equation: missing ellipsis in output labels.' + + assert not ( + len(list(filter(has_duplicated_labels, lhs.split(',')))) > 0 + ), f'Duplicate labels are not supported.' + + assert not has_duplicated_labels( + rhs + ), f'Invalid equation: duplicate output labels are found.' + + return lhs, rhs, labels + + +def parse_fake_shape(equation, operands, labels): + """ + + this shape is just used for operands planning. may differ with the original shape. + for example: + ... is replaced by 1 + -1 is replaced by 1 + Results + ------- + list of shape + + """ + shaped = collections.namedtuple('shaped', ['shape']) + + def fake_shape(label, op): + assert len(op.shape) == len(label), ( + "length of shape and length of label must be the same, but received %d != %d" + % (len(op.shape), len(label)) + ) + fakes = [s for i, (l, s) in enumerate(zip(label, op.shape)) if l != '.'] + fakes = list(map(abs, fakes)) # make -1 -> 1 + if '.' in label: + fakes.insert(label.index('.'), 1) + return shaped(fakes) + + out = list(map(fake_shape, labels, operands)) + return out + + +def rhs_inference(lhs): + def is_free(key): + return cnt.get(key) == 1 and key not in ['.', ','] + + cnt = collections.Counter(lhs) + rhs = "..." if '...' in lhs else "" + rhs = rhs + "".join(filter(is_free, sorted(cnt.elements()))) + return rhs + + +def gen_equation_for_opteinsum(lhs, rhs): + """ + 1. gen rhs if rhs is None + 2. '...' -> 'A' + """ + + def get_used_label(counter): + used = set(counter.elements()) + for c in string.ascii_lowercase: + if c not in used: + return c + raise ValueError( + "You have used all `a` - `z`, there can't find a unused for einsum optimization" + ) + + cnt = collections.Counter(lhs) + broadcast_label = get_used_label(cnt) + if rhs is None: + rhs = rhs_inference(lhs) + lhs = lhs.replace("...", broadcast_label) + rhs = rhs.replace("...", broadcast_label) + return lhs + "->" + rhs, broadcast_label + + +def einsum_v2(equation, *operands): + """ + einsum v2 implementation. + 1. Implement C++ EinsumOp. + 2. V2 create the EinsumOp to calculate, so just a little verifty work in python. + 3. V2 use opt_einsum.contract_path to optimize the multivariable einsum. + """ + n_op = len(operands) + lhs, rhs, labels = preprocess(equation, *operands) + + if n_op <= 2: + return gen_einsum_op(lhs + '->' + rhs, *operands) + + shapes = parse_fake_shape(lhs, operands, labels) + opt_equation, broadcast_label = gen_equation_for_opteinsum(lhs, rhs) + _, cons = opt_einsum.contract_path(opt_equation, *shapes, einsum_call=True) + var_list = list(operands) + for path in cons: + (a, b), _, eq, *__ = path + assert ( + a > b + ), "Assume the first var_idx is smaller than the second_idx. opt_einsum can guarantee it." + var_s = [var_list.pop(a), var_list.pop(b)] + eq = eq.replace(broadcast_label, "...") + var_list.append(gen_einsum_op(eq, *var_s)) + assert ( + len(var_list) == 1 + ), "There must be one elements in list, but received %d." % len(var_list) + return var_list[0] + + +def gen_einsum_op(equation, *operands): + """ + EinsumOp Python Interface: + """ + assert len(operands) <= 2, "Only support two operands in EinsumOp." + if in_dygraph_mode(): + return _C_ops.einsum(operands, equation)[0] + + if _in_legacy_dygraph(): + # dygraph + return _legacy_C_ops.einsum( + operands, len(operands), len(operands), 'equation', equation + )[0] + + for inp in operands: + check_variable_and_dtype(inp, 'dtype', ['float32', 'float64'], 'einsum') + check_type(equation, 'equation', str, 'einsum') + helper = LayerHelper('einsum', **locals()) + out = helper.create_variable_for_type_inference(dtype=operands[0].dtype) + attrs = dict() + attrs['equation'] = equation + caches = [ + helper.create_variable_for_type_inference(dtype=operands[0].dtype) + for i in range(len(operands)) + ] + xshape = [ + helper.create_variable_for_type_inference(dtype=operands[0].dtype) + for i in range(len(operands)) + ] + helper.append_op( + type='einsum', + inputs={'Operands': operands}, + outputs={'Out': out, "InnerCache": caches, "XShape": xshape}, + attrs=attrs, + ) + return out + + +def einsum(equation, *operands): + r""" + + einsum(equation, *operands) + + The current version of this API should be used in dygraph only mode. + + Einsum offers a tensor operation API which allows using the Einstein summation + convention or Einstain notation. It takes as input one or multiple tensors and + produces as output one tensor. + + Einsum is able to perform a variety of tensor operations. Following lists a few: + + - for single operand + - trace + - diagonal + - transpose + - sum + - for double operands + - dot + - outer + - broadcasting and elementwise multiply + - matrix multiply + - batched matrix multiply + - for many operads + - broadcasting multiply + - chained matrix multiply + + **The summation notation** + + - The tensor dimensions are labeled using uncased English letters. E.g., `ijk` + relates to a three dimensional tensor whose dimensions are labeled i, j, and k. + - The equation is `,` separated into terms, each being a distinct input's + dimension label string. + - Ellipsis `...` enables broadcasting by automatically converting the unlabeled + dimensions into broadcasting dimensions. + - Singular labels are called free labels, duplicate are dummy labels. Dummy labeled + dimensions will be reduced and removed in the output. + - Output labels can be explicitly specified on the right hand side of `->` or omitted. In the latter case, the output labels will be inferred from the input labels. + - Inference of output labels + - Broadcasting label `...`, if present, is put on the leftmost position. + - Free labels are reordered alphabetically and put after `...`. + - On explicit output labels + - If broadcasting is enabled, then `...` must be present. + - The output labels can be an empty, an indication to output as a scalar + the sum over the original output. + - Non-input labels are invalid. + - Duplicate labels are invalid. + - For any dummy label which is present for the output, it's promoted to + a free label. + - For any free label which is not present for the output, it's lowered to + a dummy label. + + - Examples + - '...ij, ...jk', where i and k are free labels, j is dummy. The output label + string is '...ik' + - 'ij -> i', where i is a free label and j is a dummy label. + - '...ij, ...jk -> ...ijk', where i, j and k are all free labels. + - '...ij, ...jk -> ij', an invalid equation since `...` is not present for + the output. + + **The summation rule** + + The summation procedure can be outlined as follows, although the actual steps taken + may vary significantly due to implementation specific optimization. + + - Step 1: preparation for broadcasting, that is, transposing and unsqueezing + the input operands to have each resulting dimension identically labeled across + all the input operands. + - Step 2: broadcasting multiply all the resulting operands from step 1. + - Step 3: reducing dummy labeled dimensions. + - Step 4: transposing the result tensor to match the output labels. + + **On trace and diagonal** + + The trace and diagonal are planned yet unimplemented features. + + Args: + equation (`str`): + The summation terms using the Einstein summation notation. + operands (`list|Tensor`): + The input tensors over which to compute the Einstein summation. The number of + operands should equal the number of input terms in the equation. + + Returns: + result (`Tensor`), the result tensor. + + Examples: + .. code-block:: python + + import paddle + paddle.seed(102) + x = paddle.rand([4]) + y = paddle.rand([5]) + + # sum + print(paddle.einsum('i->', x)) + # Tensor(shape=[], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # 1.95791852) + + # dot + print(paddle.einsum('i,i->', x, x)) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [1.45936954]) + + # outer + print(paddle.einsum("i,j->ij", x, y)) + # Tensor(shape=[4, 5], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.00079869, 0.00120950, 0.00136844, 0.00187187, 0.00192194], + # [0.23455200, 0.35519385, 0.40186870, 0.54970956, 0.56441545], + # [0.11773264, 0.17828843, 0.20171674, 0.27592498, 0.28330654], + # [0.32897076, 0.49817693, 0.56364071, 0.77099484, 0.79162055]]) + + A = paddle.rand([2, 3, 2]) + B = paddle.rand([2, 2, 3]) + + # transpose + print(paddle.einsum('ijk->kji', A)) + # Tensor(shape=[2, 3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[0.95649719, 0.49684682], + # [0.80071914, 0.46258664], + # [0.49814570, 0.33383518]], + # + # [[0.07637714, 0.29374704], + # [0.51470858, 0.51907635], + # [0.99066722, 0.55802226]]]) + + # batch matrix multiplication + print(paddle.einsum('ijk, ikl->ijl', A,B)) + # Tensor(shape=[2, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[0.32172769, 0.50617385, 0.41394392], + # [0.51736701, 0.49921003, 0.38730967], + # [0.69078457, 0.42282537, 0.30161136]], + # + # [[0.32043904, 0.18164253, 0.27810261], + # [0.50226176, 0.24512935, 0.39881429], + # [0.51476848, 0.23367381, 0.39229113]]]) + + # Ellipsis transpose + print(paddle.einsum('...jk->...kj', A)) + # Tensor(shape=[2, 2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[0.95649719, 0.80071914, 0.49814570], + # [0.07637714, 0.51470858, 0.99066722]], + # + # [[0.49684682, 0.46258664, 0.33383518], + # [0.29374704, 0.51907635, 0.55802226]]]) + + # Ellipsis batch matrix multiplication + print(paddle.einsum('...jk, ...kl->...jl', A,B)) + # Tensor(shape=[2, 3, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[0.32172769, 0.50617385, 0.41394392], + # [0.51736701, 0.49921003, 0.38730967], + # [0.69078457, 0.42282537, 0.30161136]], + # + # [[0.32043904, 0.18164253, 0.27810261], + # [0.50226176, 0.24512935, 0.39881429], + # [0.51476848, 0.23367381, 0.39229113]]]) + + """ + import os + + if int(os.environ.get('FLAGS_new_einsum', "1")): + return einsum_v2(equation, *operands) + + nop = len(operands) + assert nop > 0, "At least one operand is expected." + + # Part the equation to left hand side and right hand side + lhs, *rhs = equation.lower().replace(' ', '').split('->') + assert len(rhs) < 2, "Invalid equation: multiple `->` were found." + + # Note, we distinguish between 'ij->' and 'ij' by setting rhs to '' and None + rhs = rhs[0] if rhs else None + + # Parse labels for each operand and count the number of occurrences for each alphabet label + nop_labels = parse_labels(lhs, operands) + + # Diagonalize the operands which have duplicate labels + nop_labels, operands = list(zip(*map(diagonalize, nop_labels, operands))) + + # To handle broadcasting, we should first know how many dimensions are there + # We need to use that number to generate output labels + # e.g. 1 for ['ij', 'i.', '.k'] + n_bcast_dims = max(map(lambda s: s.count('.'), nop_labels)) + + # Build the data structures for planning. It's helpful to think of all the operands + # broadcasting together from a global view. In this view, dimensions from multiple + # operands are mapped to the same position if they are labeled uniquely. Broadcasting + # dimensions are mapped to adjacent positions with the right bound fixed. Subject to + # each operand, the map is injective but for all operands the map is on-to. + # g_labels: + # The labels of the global view + # g_view: + # Includes a list of maps from each operand's dimensions to the global view's dimensions + # which we refer to as ax or axes in the code to distinguish from operand's dims + # g_shape: + # The shape of the global view. The size of each dimension is what the aligned dimensions + # should broadcast to + # g_nout: + # Number of output axes + # g_supports + # Booleans indicating each operand's non-trivial dimensions + # g_count + # Counting how many non-trivial dimensions remain for each ax + + g_labels, g_view, g_nout, g_count = build_global_view( + nop_labels, rhs, n_bcast_dims + ) + g_shape, g_supports = build_global_shape( + g_view, g_labels, [op.shape for op in operands] + ) + + # Now we're ready to build up an execution plan + args = operands, g_view, g_shape, g_supports, g_count, n_bcast_dims + plan = plan_einsum(*args) + result = plan.execute() + + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/layer_function_generator.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/layer_function_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c32c3254b78a5fcfb9b20906fa2d5e038b4888 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/layer_function_generator.py @@ -0,0 +1,393 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function +import re +import functools +import warnings +import string + +from six.moves import cStringIO +from ..static import Variable +from ..fluid.proto import framework_pb2 +from ..framework import OpProtoHolder, core, convert_np_dtype_to_dtype_, _non_static_mode, in_dygraph_mode, _in_legacy_dygraph +from ..framework import LayerHelper +from ..fluid.data_feeder import check_variable_and_dtype +import paddle +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def _convert_(name): + """ + Formatting. + + Args: + name: The name/alias + + This function takes in a name and converts it to a standard format of + group1_group2. Where as per the regular expression, group1 can have + alphabets and numbers and group2 has capital alphabets. + + """ + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + + +def _type_to_str_(tp): + return framework_pb2.AttrType.Name(tp) + + +_two_dollar_pattern_ = re.compile(r"\$\$([^\$]+)\$\$") +_single_dollar_pattern_ = re.compile(r"\$([^\$]+)\$") +_two_bang_pattern_ = re.compile(r"!!([^!]+)!!") + + +def escape_math(text): + #return _two_bang_pattern_.sub( + # r'$$\1$$', + # _single_dollar_pattern_.sub(r':math:\n`\1`', + # _two_dollar_pattern_.sub(r"!!\1!!", text))) + return _two_dollar_pattern_.sub(r':math:`\1`', text) + + +def _generate_doc_string_(op_proto, + additional_args_lines=None, + skip_attrs_set=None): + """ + Generate docstring by OpProto + + Args: + op_proto (framework_pb2.OpProto): a protobuf message typed OpProto + + Returns: + str: the document string + """ + + if not isinstance(op_proto, framework_pb2.OpProto): + raise TypeError("OpProto should be `framework_pb2.OpProto`") + + buf = cStringIO() + buf.write(escape_math(op_proto.comment)) + buf.write('\nArgs:\n') + for each_input in op_proto.inputs: + line_begin = ' {0}'.format(_convert_(each_input.name)) + buf.write(line_begin) + buf.write(" (Tensor): ") + buf.write(escape_math(each_input.comment)) + if each_input.duplicable: + buf.write(" Duplicatable.") + if each_input.dispensable: + buf.write(" Optional.") + buf.write('\n') + + skip_attrs = OpProtoHolder.generated_op_attr_names() + # attr use_mkldnn and is_test also should not be visible to users. + skip_attrs.add("use_mkldnn") + skip_attrs.add("is_test") + skip_attrs.add("use_cudnn") + + if skip_attrs_set: + for t in skip_attrs_set: + skip_attrs.add(t) + + for each_attr in op_proto.attrs: + if each_attr.name in skip_attrs: + continue + buf.write(' ') + buf.write(each_attr.name) + buf.write(' (') + buf.write(_type_to_str_(each_attr.type)) + buf.write('): ') + buf.write(escape_math(each_attr.comment)) + buf.write('\n') + + if additional_args_lines is not None: + for line in additional_args_lines: + line = line.strip() + buf.write(' ') + buf.write(line) + buf.write('\n') + + if len(op_proto.outputs) != 0: + buf.write('\nReturns:\n') + buf.write(' ') + for each_opt in op_proto.outputs: + if not each_opt.intermediate: + break + buf.write(_convert_(each_opt.name)) + buf.write(' (Tensor): ') + buf.write(escape_math(each_opt.comment)) + + return buf.getvalue() + + +def generate_layer_fn(op_type): + """Register the Python layer for an Operator. + + Args: + op_type: The name of the operator to be created. + + This function takes in the operator type (sigmoid, mean , average etc) and + creates the operator functionality. + + """ + op_proto = OpProtoHolder.instance().get_op_proto(op_type) + not_intermediate_outputs = \ + [output for output in op_proto.outputs if not output.intermediate] + intermediate_outputs = \ + [output for output in op_proto.outputs if output.intermediate] + + if len(not_intermediate_outputs) != 1: + raise ValueError("Only one non intermediate output operator can be", + "automatically generated. {0}".format(op_type)) + + if not_intermediate_outputs[0].duplicable: + raise ValueError( + "Only non duplicable op can be automatically generated.") + + for output in intermediate_outputs: + if output.duplicable: + raise ValueError("The op can be automatically generated only when ", + "all intermediate ops are not duplicable.") + + o_name = not_intermediate_outputs[0].name + intermediate_output_names = [output.name for output in intermediate_outputs] + + def infer_and_check_dtype(op_proto, *args, **kwargs): + """ + This function performs the sanity check for dtype and + instance type. + """ + dtype = None + for ipt in op_proto.inputs: + name = _convert_(ipt.name) + val = kwargs.pop(name, []) + if not isinstance(val, list) and not isinstance(val, tuple): + val = [val] + if len(val) == 0: + if len(args) == 0: + continue + val = [args[0]] + args = args[1:] + + for each in val: + if not isinstance(each, Variable): + raise ValueError( + "input of {0} must be variable".format(op_type)) + + if dtype is None: + dtype = each.dtype + elif dtype != each.dtype: + raise ValueError( + "operator {0} must input same dtype. {1} vs {2}".format( + op_type, dtype, each.dtype)) + + if dtype is None: + arg_dtype = kwargs.get("dtype") + if arg_dtype: + if not isinstance(arg_dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(arg_dtype) + else: + dtype = arg_dtype + else: + dtype = core.VarDesc.VarType.FP32 + return dtype + + def func(*args, **kwargs): + helper = LayerHelper(op_type, **kwargs) + + dtype = infer_and_check_dtype(op_proto, *args, **kwargs) + + inputs = dict() + for ipt in op_proto.inputs: + name = _convert_(ipt.name) + val = kwargs.pop(name, []) + if not isinstance(val, list) and not isinstance(val, tuple): + val = [val] + if len(val) == 0 and len(args) != 0: + val = args[0] + args = args[1:] + inputs[ipt.name] = val + + outputs = dict() + out = kwargs.pop(_convert_(o_name), []) + if out: + out_var = out[0] if (isinstance(out, list) + or isinstance(out, tuple)) else out + else: + out_var = helper.create_variable_for_type_inference(dtype=dtype) + outputs[o_name] = [out_var] + for name in intermediate_output_names: + outputs[name] = [ + helper.create_variable_for_type_inference(dtype=dtype) + ] + helper.append_op(type=op_type, + inputs=inputs, + outputs=outputs, + attrs=kwargs) + return helper.append_activation(out_var) + + func.__name__ = op_type + func.__doc__ = _generate_doc_string_(op_proto) + return func + + +def generate_activation_fn(op_type): + """Register the Python layer for an Operator without Attribute. + + Args: + op_type: The name of the operator to be created. + + This function takes in the operator type (sigmoid, exp , tanh etc) and + creates the operator functionality. + + """ + op_proto = OpProtoHolder.instance().get_op_proto(op_type) + + def func(x, name=None): + if in_dygraph_mode() and hasattr(_C_ops, op_type): + op = getattr(_C_ops, op_type) + return op(x) + # TODO(dev): Because some ops' yaml has not been migrated. + # Replace it with _in_legacy_dygraph while all yaml work is done. + if _non_static_mode(): + op = getattr(_legacy_C_ops, op_type) + return op(x) + + if op_type not in ["abs", "exp", "square"]: + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], + op_type) + else: + # abs exp square ops support dtype(int32, int64, float16, float32, float64) + check_variable_and_dtype(x, 'x', [ + 'int32', 'int64', 'float16', 'float32', 'float64', 'complex64', + 'complex128' + ], op_type) + + helper = LayerHelper(op_type, **locals()) + + output = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type=op_type, inputs={"X": x}, outputs={"Out": output}) + return output + + func.__name__ = op_type + func.__doc__ = _generate_doc_string_( + op_proto, + additional_args_lines=[ + "name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`." + ]) + return func + + +def generate_inplace_fn(inplace_op_type): + """Register the Python layer for an Inplace Operator without Attribute. + + Args: + inplace_op_type: The name of the inplace operator to be created. + + This function takes in the inplace operator type (exp_ , ceil_ etc) and + creates the operator functionality. + """ + origin_op_type = inplace_op_type[:-1] + + def func(x, name=None): + if in_dygraph_mode() and hasattr(_C_ops, inplace_op_type): + op = getattr(_C_ops, inplace_op_type) + return op(x) + if _non_static_mode(): + op = getattr(_legacy_C_ops, inplace_op_type) + return op(x) + warnings.warn( + "In static mode, {}() is the same as {}() and does not perform inplace operation." + .format(inplace_op_type, origin_op_type)) + return generate_activation_fn(origin_op_type)(x, name) + + func.__name__ = inplace_op_type + func.__doc__ = """ +Inplace version of ``{0}`` API, the output Tensor will be inplaced with input ``x``. +Please refer to :ref:`api_fluid_layers_{1}`. +""".format(origin_op_type, origin_op_type) + + return func + + +def templatedoc(op_type=None): + """ + Decorator of layer function. It will use the docstring from the layer + function as the template. The template arguments are: + + * ${comment}: The operator comment written in CPP. + * ${{name}_comment}: The comment of ${name} written with AddAttr, AddOutput, + and AddInput. The ${name} is Python snake style. i.e., xxx_xxx. + * ${{name}_type}: The type of ${name}. + + Returns: + Decorated function. + """ + + def trim_ending_dot(msg): + return msg.rstrip('.') + + def __impl__(func): + if op_type is None: + op_type_name = func.__name__ + else: + op_type_name = op_type + op_proto = OpProtoHolder.instance().get_op_proto(op_type_name) + tmpl = string.Template(func.__doc__) + + comment_lines = op_proto.comment.split("\n") + comment = "" + for line in comment_lines: + line = line.strip() + if len(line) != 0: + comment += escape_math(line) + comment += " " + elif len(comment) != 0: + comment += "\n \n " + + args = {"comment": trim_ending_dot(comment)} + for each_input in op_proto.inputs: + input_name = _convert_(each_input.name) + args["{0}_comment".format(input_name)] = trim_ending_dot( + each_input.comment) + args["{0}_type".format(input_name)] = "Variable" + for each_attr in op_proto.attrs: + input_name = _convert_(each_attr.name) + args["{0}_comment".format(input_name)] = trim_ending_dot( + each_attr.comment) + args["{0}_type".format(input_name)] = _type_to_str_(each_attr.type) + + for each_opt in op_proto.outputs: + output_name = _convert_(each_opt.name) + args["{0}_comment".format(output_name)] = trim_ending_dot( + each_opt.comment) + args["{0}_type".format(output_name)] = "Variable" + func.__doc__ = tmpl.substitute(args) + return func + + return __impl__ + + +def add_sample_code(func, sample_code): + """ + Append sample code for dynamically generated functions. + + Args: + func: The function of the function to be append sample code to. + sample_code: sample code session in rst format. + """ + func.__doc__ = func.__doc__ + sample_code diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/linalg.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..132129ae628bc212c0e0b77fbb41d11cb052e285 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/linalg.py @@ -0,0 +1,3543 @@ +# 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. + +import numpy as np +from ..framework import LayerHelper +from ..framework import ( + _varbase_creator, + _dygraph_tracer, + in_dygraph_mode, + _non_static_mode, +) +from ..fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..static import Variable +from ..fluid.framework import _in_legacy_dygraph +from .manipulation import cast +from .math import multiply, add +from .logic import logical_not +from .creation import full + +import paddle +import warnings +from paddle.common_ops_import import core +from paddle.common_ops_import import VarDesc +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + +# Consistent with kDefaultDim from C++ Backend +K_DEFAULT_DIM = 9 + + +def transpose(x, perm, name=None): + """ + Permute the data dimensions of `input` according to `perm`. + + The `i`-th dimension of the returned tensor will correspond to the + perm[i]-th dimension of `input`. + + Args: + x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32. + perm (list|tuple): Permute the input according to the data of perm. + name (str): The name of this layer. It is optional. + + Returns: + Tensor: A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64. + + For Example: + + .. code-block:: text + + x = [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] + [[13 14 15 16] [17 18 19 20] [21 22 23 24]]] + shape(x) = [2,3,4] + + # Example 1 + perm0 = [1,0,2] + y_perm0 = [[[ 1 2 3 4] [13 14 15 16]] + [[ 5 6 7 8] [17 18 19 20]] + [[ 9 10 11 12] [21 22 23 24]]] + shape(y_perm0) = [3,2,4] + + # Example 2 + perm1 = [2,1,0] + y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]] + [[ 2 14] [ 6 18] [10 22]] + [[ 3 15] [ 7 19] [11 23]] + [[ 4 16] [ 8 20] [12 24]]] + shape(y_perm1) = [4,3,2] + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn([2, 3, 4]) + x_transposed = paddle.transpose(x, perm=[1, 0, 2]) + print(x_transposed.shape) + # [3L, 2L, 4L] + + """ + if in_dygraph_mode(): + return _C_ops.transpose(x, perm) + else: + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.transpose2(x, 'axis', perm) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'transpose', + ) + check_type(perm, 'perm', (list, tuple), 'transpose') + if isinstance(perm, tuple): + perm = list(perm) + if len(perm) != len(x.shape): + raise ValueError( + "Input(perm) is the permutation of dimensions of Input(x), " + "its length should be equal to dimensions of Input(x), " + "but received dimension of Input(x) is %s, " + "the length of Input(perm) is %s." % (len(x.shape), len(perm)) + ) + for idx, dim in enumerate(perm): + if dim >= len(x.shape): + raise ValueError( + "Each element in Input(perm) should be less than Input(x)'s dimension, " + "but %d-th element in Input(perm) is %d which exceeds Input(x)'s " + "dimension %d." % (idx, perm[idx], len(x.shape)) + ) + + helper = LayerHelper('transpose', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='transpose2', + inputs={'X': [x]}, + outputs={'Out': [out], 'XShape': [x_shape]}, + attrs={'axis': perm}, + ) + return out + + +def matmul(x, y, transpose_x=False, transpose_y=False, name=None): + """ + Applies matrix multiplication to two tensors. `matmul` follows + the complete broadcast rules, + and its behavior is consistent with `np.matmul`. + + Currently, the input tensors' number of dimensions can be any, `matmul` can be used to + achieve the `dot`, `matmul` and `batchmatmul`. + + The actual behavior depends on the shapes of :math:`x`, :math:`y` and the + flag values of :attr:`transpose_x`, :attr:`transpose_y`. Specifically: + + - If a transpose flag is specified, the last two dimensions of the tensor + are transposed. If the tensor is ndim-1 of shape, the transpose is invalid. If the tensor + is ndim-1 of shape :math:`[D]`, then for :math:`x` it is treated as :math:`[1, D]`, whereas + for :math:`y` it is the opposite: It is treated as :math:`[D, 1]`. + + The multiplication behavior depends on the dimensions of `x` and `y`. Specifically: + + - If both tensors are 1-dimensional, the dot product result is obtained. + + - If both tensors are 2-dimensional, the matrix-matrix product is obtained. + + - If the `x` is 1-dimensional and the `y` is 2-dimensional, + a `1` is prepended to its dimension in order to conduct the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + + - If the `x` is 2-dimensional and `y` is 1-dimensional, + the matrix-vector product is obtained. + + - If both arguments are at least 1-dimensional and at least one argument + is N-dimensional (where N > 2), then a batched matrix multiply is obtained. + If the first argument is 1-dimensional, a 1 is prepended to its dimension + in order to conduct the batched matrix multiply and removed after. + If the second argument is 1-dimensional, a 1 is appended to its + dimension for the purpose of the batched matrix multiple and removed after. + The non-matrix (exclude the last two dimensions) dimensions are + broadcasted according the broadcast rule. + For example, if input is a (j, 1, n, m) tensor and the other is a (k, m, p) tensor, + out will be a (j, k, n, p) tensor. + + Args: + x (Tensor): The input tensor which is a Tensor. + y (Tensor): The input tensor which is a Tensor. + transpose_x (bool): Whether to transpose :math:`x` before multiplication. + transpose_y (bool): Whether to transpose :math:`y` before multiplication. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + + Returns: + Tensor: The output Tensor. + + Examples: + + .. code-block:: python + + import paddle + + # vector * vector + x = paddle.rand([10]) + y = paddle.rand([10]) + z = paddle.matmul(x, y) + print(z.shape) + # [1] + + # matrix * vector + x = paddle.rand([10, 5]) + y = paddle.rand([5]) + z = paddle.matmul(x, y) + print(z.shape) + # [10] + + # batched matrix * broadcasted vector + x = paddle.rand([10, 5, 2]) + y = paddle.rand([2]) + z = paddle.matmul(x, y) + print(z.shape) + # [10, 5] + + # batched matrix * batched matrix + x = paddle.rand([10, 5, 2]) + y = paddle.rand([10, 2, 5]) + z = paddle.matmul(x, y) + print(z.shape) + # [10, 5, 5] + + # batched matrix * broadcasted matrix + x = paddle.rand([10, 1, 5, 2]) + y = paddle.rand([1, 3, 2, 5]) + z = paddle.matmul(x, y) + print(z.shape) + # [10, 3, 5, 5] + + """ + if in_dygraph_mode(): + return _C_ops.matmul(x, y, transpose_x, transpose_y) + + if _in_legacy_dygraph(): + op_type = 'matmul_v2' + op = getattr(_legacy_C_ops, op_type) + return op(x, y, 'trans_x', transpose_x, 'trans_y', transpose_y) + + attrs = { + 'trans_x': transpose_x, + 'trans_y': transpose_y, + } + + def __check_input(x, y): + var_names = {'x': x, 'y': y} + for name, val in var_names.items(): + check_variable_and_dtype( + val, + name, + ['float16', 'float32', 'float64', 'complex64', 'complex128'], + 'matmul', + ) + + __check_input(x, y) + + helper = LayerHelper('matmul_v2', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='matmul_v2', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + +def norm(x, p='fro', axis=None, keepdim=False, name=None): + """ + + Returns the matrix norm (Frobenius) or vector norm (the 1-norm, the Euclidean + or 2-norm, and in general the p-norm for p > 0) of a given tensor. + + Note: + This norm API is different from `numpy.linalg.norm`. + This api supports high-order input tensors (rank >= 3), and certain axis need to be pointed out to calculate the norm. + But `numpy.linalg.norm` only supports 1-D vector or 2-D matrix as input tensor. + For p-order matrix norm, this api actually treats matrix as a flattened vector to calculate the vector norm, NOT REAL MATRIX NORM. + + Args: + x (Tensor): The input tensor could be N-D tensor, and the input data + type could be float32 or float64. + p (float|string, optional): Order of the norm. Supported values are `fro`, `0`, `1`, `2`, + `inf`, `-inf` and any positive real number yielding the corresponding p-norm. Not supported: ord < 0 and nuclear norm. + Default value is `fro`. + axis (int|list|tuple, optional): The axis on which to apply norm operation. If axis is int + or list(int)/tuple(int) with only one element, the vector norm is computed over the axis. + If `axis < 0`, the dimension to norm operation is rank(input) + axis. + If axis is a list(int)/tuple(int) with two elements, the matrix norm is computed over the axis. + Default value is `None`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have fewer dimension + than the :attr:`input` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: results of norm operation on the specified axis of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(24, dtype="float32").reshape([2, 3, 4]) - 12 + # x: Tensor(shape=[2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[[-12., -11., -10., -9. ], + # [-8. , -7. , -6. , -5. ], + # [-4. , -3. , -2. , -1. ]], + + # [[ 0. , 1. , 2. , 3. ], + # [ 4. , 5. , 6. , 7. ], + # [ 8. , 9. , 10., 11.]]]) + + # compute frobenius norm along last two dimensions. + out_fro = paddle.linalg.norm(x, p='fro', axis=[0,1]) + # out_fro: Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [17.43559647, 16.91153526, 16.73320007, 16.91153526]) + + # compute 2-order vector norm along last dimension. + out_pnorm = paddle.linalg.norm(x, p=2, axis=-1) + # out_pnorm: Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[21.11871147, 13.19090557, 5.47722578 ], + # [3.74165750 , 11.22497177, 19.13112640]]) + + # compute 2-order norm along [0,1] dimension. + out_pnorm = paddle.linalg.norm(x, p=2, axis=[0,1]) + # out_pnorm: Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [17.43559647, 16.91153526, 16.73320007, 16.91153526]) + + # compute inf-order norm + out_pnorm = paddle.linalg.norm(x, p=float("inf")) + # out_pnorm = Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True, + # [12.]) + + out_pnorm = paddle.linalg.norm(x, p=float("inf"), axis=0) + # out_pnorm: Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[12., 11., 10., 9. ], + # [8. , 7. , 6. , 7. ], + # [8. , 9. , 10., 11.]]) + + # compute -inf-order norm + out_pnorm = paddle.linalg.norm(x, p=-float("inf")) + # out_pnorm: Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True, + # [0.]) + + out_pnorm = paddle.linalg.norm(x, p=-float("inf"), axis=0) + # out_pnorm: Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[0., 1., 2., 3.], + # [4., 5., 6., 5.], + # [4., 3., 2., 1.]]) + """ + + def frobenius_norm(input, dim=None, keepdim=False, name=None): + """ + The frobenius norm OP is to calculate the frobenius norm of certain two dimensions of Tensor `input`. + Args: + input (Variable): Tensor, data type float32, float64. + dim (list, optional): None for last two dimensions. + keepdim (bool, optional): Whether keep the dimensions as the `input`, Default False. + """ + if dim is not None and not (isinstance(dim, list) and len(dim) == 2): + raise ValueError( + "The dim of frobenius norm op should be None or two elements list!" + ) + + if in_dygraph_mode(): + if dim is None: + return _C_ops.frobenius_norm(input, [], keepdim, True) + return _C_ops.frobenius_norm(input, dim, keepdim, False) + if _in_legacy_dygraph(): + if dim is None: + return _legacy_C_ops.frobenius_norm( + input, 'keep_dim', keepdim, 'reduce_all', True + ) + return _legacy_C_ops.frobenius_norm( + input, 'dim', dim, 'keep_dim', keepdim, 'reduce_all', False + ) + attrs = {'dim': dim, 'keep_dim': keepdim, 'reduce_all': False} + if dim is None: + attrs['reduce_all'] = True + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'frobenius_norm' + ) + + helper = LayerHelper('frobenius_norm', **locals()) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + + helper.append_op( + type='frobenius_norm', + inputs={'X': input}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + def vector_norm( + input, porder=None, axis=None, keepdim=False, asvector=False, name=None + ): + """ + Calculate the p-order vector norm for certain dimension of Tensor `input`. + Args: + input (Variable): Tensor, data type float32, float64. + porder (float, optional): None for porder=2.0. + axis (int, optional): None for last dimension. + keepdim (bool, optional): Whether keep the dimensions as the `input`, Default False. + """ + if in_dygraph_mode(): + if axis is None: + axis = -1 + return _C_ops.p_norm(input, porder, axis, 1e-12, keepdim, asvector) + + if _in_legacy_dygraph(): + if axis is None: + axis = -1 + return _legacy_C_ops.p_norm( + input, + 'porder', + porder, + 'axis', + axis, + 'keepdim', + keepdim, + 'asvector', + asvector, + ) + + if porder is not None: + check_type(porder, 'porder', (float, int), 'p_norm') + if axis is not None: + check_type(axis, 'axis', (int), 'p_norm') + check_variable_and_dtype( + input, 'input', ['float32', 'float64'], 'p_norm' + ) + + attrs = { + 'axis': axis if axis is not None else -1, + 'porder': float(porder) if porder is not None else 2.0, + 'keepdim': keepdim, + 'asvector': asvector, + 'epsilon': 1e-12, + } + helper = LayerHelper('p_norm', **locals()) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + + helper.append_op( + type='p_norm', + inputs={'X': input}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + def inf_norm( + input, porder=None, axis=axis, keepdim=False, asvector=False, name=None + ): + if in_dygraph_mode(): + out = _C_ops.abs(input) + reduce_all = ( + True + if axis == None or axis == [] or asvector == True + else False + ) + axis = axis if axis != None and axis != [] else [0] + if reduce_all: + assert (axis == []) or (axis is None) + if porder == np.float64('inf'): + return _C_ops.max(out, axis, keepdim) + else: + return _C_ops.min(out, axis, keepdim) + + helper = LayerHelper('inf_norm', **locals()) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + helper.append_op(type='abs', inputs={'X': input}, outputs={'Out': out}) + reduce_out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + + reduce_all = ( + True if axis == None or axis == [] or asvector == True else False + ) + axis = axis if axis != None and axis != [] else [0] + + reduce_type = ( + 'reduce_max' if porder == np.float64('inf') else 'reduce_min' + ) + helper.append_op( + type=reduce_type, + inputs={'X': out}, + outputs={'Out': reduce_out}, + attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all}, + ) + + return reduce_out + + def p_matrix_norm(input, porder=1.0, axis=axis, keepdim=False, name=None): + """ + NOTE: + This function actually treats the matrix as flattened vector to calculate vector norm instead of matrix norm. + """ + if in_dygraph_mode(): + abs_out = _C_ops.abs(input) + pow_out = _C_ops.pow(abs_out, porder) + sum_out = _C_ops.sum(pow_out, axis, None, keepdim) + out = _C_ops.pow(sum_out, float(1.0 / porder)) + return out + + block = LayerHelper('norm', **locals()) + out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + abs_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + block.append_op( + type='abs', inputs={'X': input}, outputs={'Out': abs_out} + ) + pow_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + + block.append_op( + type='pow', + inputs={'X': abs_out}, + outputs={'Out': pow_out}, + attrs={'factor': porder}, + ) + sum_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + block.append_op( + type='reduce_sum', + inputs={'X': pow_out}, + outputs={'Out': sum_out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': True if axis is None else False, + }, + ) + block.append_op( + type='pow', + inputs={'X': sum_out}, + outputs={'Out': out}, + attrs={'factor': float(1.0 / porder)}, + ) + return out + + if axis is None and p is not None: + if isinstance(p, str): + if p == "fro": + return frobenius_norm(x, dim=axis, keepdim=keepdim, name=name) + else: + raise ValueError( + "only valid string values are 'fro', found {}".format(p) + ) + elif isinstance(p, (int, float)): + return vector_norm( + x, + porder=p, + axis=axis, + keepdim=keepdim, + asvector=True, + name=name, + ) + else: + raise ValueError( + "only valid p type is string or float, found {}".format(type(p)) + ) + + if isinstance(axis, tuple): + axis = list(axis) + if isinstance(axis, list) and len(axis) == 1: + axis = axis[0] + + # calculate vector norm, where axis is int or list with only one integer + if isinstance(axis, int): + if isinstance(p, str): + if p == "fro": + return vector_norm( + x, + porder=2, + axis=axis, + keepdim=keepdim, + asvector=False, + name=name, + ) + + else: + raise ValueError( + "only valid string values are 'fro', found {}".format(p) + ) + elif isinstance(p, (int, float)): + return vector_norm( + x, + axis=axis, + porder=p, + keepdim=keepdim, + asvector=False, + name=name, + ) + else: + raise ValueError( + "unspport p for p-order vector norm. except float, found {}".format( + p + ) + ) + # calculate matrix norm, where axis is list with two integers + elif isinstance(axis, list) and len(axis) == 2: + if p == "fro": + return frobenius_norm(x, dim=axis, keepdim=keepdim, name=name) + elif p == np.inf or p == -np.inf: + return inf_norm(x, porder=p, axis=axis, keepdim=keepdim, name=name) + elif p == 0: + raise ValueError( + "just suport axis type int or list (length of list <=1) if p = 0, found {}".format( + axis + ) + ) + else: + return p_matrix_norm( + x, porder=p, axis=axis, keepdim=keepdim, name=name + ) + else: + raise ValueError( + "except axis type int or list (length of list <=2), found {}".format( + axis + ) + ) + + +def dist(x, y, p=2, name=None): + r""" + + This OP returns the p-norm of (x - y). It is not a norm in a strict sense, only as a measure + of distance. The shapes of x and y must be broadcastable. The definition is as follows, for + details, please refer to the `numpy's broadcasting `_: + + - Each input has at least one dimension. + - Match the two input dimensions from back to front, the dimension sizes must either be equal, one of them is 1, or one of them does not exist. + + Where, z = x - y, the shapes of x and y are broadcastable, then the shape of z can be + obtained as follows: + + 1. If the number of dimensions of x and y are not equal, prepend 1 to the dimensions of the + tensor with fewer dimensions. + + For example, The shape of x is [8, 1, 6, 1], the shape of y is [7, 1, 5], prepend 1 to the + dimension of y. + + x (4-D Tensor): 8 x 1 x 6 x 1 + + y (4-D Tensor): 1 x 7 x 1 x 5 + + 2. Determine the size of each dimension of the output z: choose the maximum value from the + two input dimensions. + + z (4-D Tensor): 8 x 7 x 6 x 5 + + If the number of dimensions of the two inputs are the same, the size of the output can be + directly determined in step 2. When p takes different values, the norm formula is as follows: + + When p = 0, defining $0^0=0$, the zero-norm of z is simply the number of non-zero elements of z. + + .. math:: + + ||z||_{0}=\lim_{p \\rightarrow 0}\sum_{i=1}^{m}|z_i|^{p} + + When p = inf, the inf-norm of z is the maximum element of the absolute value of z. + + .. math:: + + ||z||_\infty=\max_i |z_i| + + When p = -inf, the negative-inf-norm of z is the minimum element of the absolute value of z. + + .. math:: + + ||z||_{-\infty}=\min_i |z_i| + + Otherwise, the p-norm of z follows the formula, + + .. math:: + + ||z||_{p}=(\sum_{i=1}^{m}|z_i|^p)^{\\frac{1}{p}} + + Args: + x (Tensor): 1-D to 6-D Tensor, its data type is float32 or float64. + y (Tensor): 1-D to 6-D Tensor, its data type is float32 or float64. + p (float, optional): The norm to be computed, its data type is float32 or float64. Default: 2. + + Returns: + Tensor: Tensor that is the p-norm of (x - y). + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[3, 3],[3, 3]], dtype="float32") + y = paddle.to_tensor([[3, 3],[3, 1]], dtype="float32") + out = paddle.dist(x, y, 0) + print(out) # out = [1.] + + out = paddle.dist(x, y, 2) + print(out) # out = [2.] + + out = paddle.dist(x, y, float("inf")) + print(out) # out = [2.] + + out = paddle.dist(x, y, float("-inf")) + print(out) # out = [0.] + """ + if in_dygraph_mode(): + return _C_ops.dist(x, y, p) + + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'dist') + check_variable_and_dtype(y, 'dtype', ['float32', 'float64'], 'dist') + check_type(p, 'p', (float, int), 'dist') + helper = LayerHelper("dist", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + + inputs = {"X": [x], "Y": [y]} + outputs = {'Out': [out]} + attrs = {"p": float(p)} + helper.append_op( + type='dist', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +def cond(x, p=None, name=None): + """ + + Computes the condition number of a matrix or batches of matrices with respect to a matrix norm ``p``. + + Args: + x (Tensor): The input tensor could be tensor of shape ``(*, m, n)`` where ``*`` is zero or more batch dimensions + for ``p`` in ``(2, -2)``, or of shape ``(*, n, n)`` where every matrix is invertible for any supported ``p``. + And the input data type could be ``float32`` or ``float64``. + p (float|string, optional): Order of the norm. Supported values are `fro`, `nuc`, `1`, `-1`, `2`, `-2`, + `inf`, `-inf`. Default value is `None`, meaning that the order of the norm is `2`. + name (str, optional): The default value is `None`. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: computing results of condition number, its data type is the same as input Tensor ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1., 0, -1], [0, 1, 0], [1, 0, 1]]) + + # compute conditional number when p is None + out = paddle.linalg.cond(x) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.41421342]) + + # compute conditional number when order of the norm is 'fro' + out_fro = paddle.linalg.cond(x, p='fro') + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [3.16227770]) + + # compute conditional number when order of the norm is 'nuc' + out_nuc = paddle.linalg.cond(x, p='nuc') + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [9.24263859]) + + # compute conditional number when order of the norm is 1 + out_1 = paddle.linalg.cond(x, p=1) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2.]) + + # compute conditional number when order of the norm is -1 + out_minus_1 = paddle.linalg.cond(x, p=-1) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.]) + + # compute conditional number when order of the norm is 2 + out_2 = paddle.linalg.cond(x, p=2) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.41421342]) + + # compute conditional number when order of the norm is -1 + out_minus_2 = paddle.linalg.cond(x, p=-2) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [0.70710683]) + + # compute conditional number when order of the norm is inf + out_inf = paddle.linalg.cond(x, p=float("inf")) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [2.]) + + # compute conditional number when order of the norm is -inf + out_minus_inf = paddle.linalg.cond(x, p=-float("inf")) + # Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [1.]) + + a = paddle.randn([2, 4, 4]) + # Tensor(shape=[2, 4, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[-0.06784091, -0.07095790, 1.31792855, -0.58959651], + # [ 0.20818676, -0.85640615, -0.89998871, -1.47439921], + # [-0.49132481, 0.42250812, -0.77383220, -2.19794774], + # [-0.33551720, -1.70003879, -1.09795380, -0.63737559]], + + # [[ 1.12026262, -0.16119350, -1.21157813, 2.74383283], + # [-0.15999718, 0.18798758, -0.69392562, 1.35720372], + # [-0.53013402, -2.26304483, 1.40843511, -1.02288902], + # [ 0.69533503, 2.05261683, -0.02251151, -1.43127477]]]) + + a_cond_fro = paddle.linalg.cond(a, p='fro') + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [8.86691189 , 75.23817444]) + + b = paddle.randn([2, 3, 4]) + # Tensor(shape=[2, 3, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[-0.43754861, 1.80796063, -0.78729683, -1.82264030], + # [-0.27670753, 0.06620564, 0.29072434, -0.31155765], + # [ 0.34123746, -0.05444612, 0.05001324, -1.46877074]], + + # [[-0.64331555, -1.51103854, -1.26277697, -0.68024760], + # [ 2.59375715, -1.06665540, 0.96575671, -0.73330832], + # [-0.47064447, -0.23945692, -0.95150250, -1.07125998]]]) + b_cond_2 = paddle.linalg.cond(b, p=2) + # Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [6.64228773, 3.89068866]) + + """ + + def mat_norm(input, porder=1.0, axis=None): + """ + NOTE: + Calculate the matrix norm of a square matrix or batches of square matrices, + when porder is in (1, -1, inf, -inf) + """ + reduce_all = True if axis is None or axis == [] else False + axis = axis if axis != None and axis != [] else [0] + keepdim = False + + if in_dygraph_mode(): + abs_out = _C_ops.abs(input) + sum_out = _C_ops.sum(abs_out, axis, None, keepdim) + + if porder == 1 or porder == np.inf: + return _C_ops.max(sum_out, [-1], keepdim) + if porder == -1 or porder == -np.inf: + return _C_ops.min(sum_out, [-1], keepdim) + + elif _in_legacy_dygraph(): + abs_out = _legacy_C_ops.abs(input) + sum_out = _legacy_C_ops.reduce_sum( + abs_out, + 'dim', + axis, + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + if porder == 1 or porder == np.inf: + return _legacy_C_ops.reduce_max( + sum_out, + 'dim', + [-1], + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + if porder == -1 or porder == -np.inf: + return _legacy_C_ops.reduce_min( + sum_out, + 'dim', + [-1], + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + else: + block = LayerHelper('norm', **locals()) + abs_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + sum_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + block.append_op( + type='abs', inputs={'X': input}, outputs={'Out': abs_out} + ) + block.append_op( + type='reduce_sum', + inputs={'X': abs_out}, + outputs={'Out': sum_out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all, + }, + ) + if porder == 1 or porder == np.inf: + block.append_op( + type='reduce_max', + inputs={'X': sum_out}, + outputs={'Out': out}, + attrs={ + 'dim': [-1], + 'keep_dim': keepdim, + 'reduce_all': reduce_all, + }, + ) + if porder == -1 or porder == -np.inf: + block.append_op( + type='reduce_min', + inputs={'X': sum_out}, + outputs={'Out': out}, + attrs={ + 'dim': [-1], + 'keep_dim': keepdim, + 'reduce_all': reduce_all, + }, + ) + return out + + def fro_norm(input, porder=2, axis=[-1]): + """ + NOTE: + Calculate the frobenius norm of a square matrix or batches of square matrices. + """ + reduce_all = True if axis is None or axis == [] else False + keepdim = False + + if in_dygraph_mode(): + pow_out = _C_ops.pow(input, porder) + sum_out_1 = _C_ops.sum(pow_out, axis, None, keepdim) + sum_out_2 = _C_ops.sum(sum_out_1, axis, None, keepdim) + return _C_ops.pow(sum_out_2, float(1.0 / porder)) + elif paddle.in_dynamic_mode(): + pow_out = _legacy_C_ops.pow(input, 'factor', porder) + sum_out_1 = _legacy_C_ops.reduce_sum( + pow_out, + 'dim', + axis, + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + sum_out_2 = _legacy_C_ops.reduce_sum( + sum_out_1, + 'dim', + axis, + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + return _legacy_C_ops.pow(sum_out_2, 'factor', float(1.0 / porder)) + + block = LayerHelper('norm', **locals()) + pow_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + sum_out_1 = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + sum_out_2 = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + block.append_op( + type='pow', + inputs={'X': input}, + outputs={'Out': pow_out}, + attrs={'factor': porder}, + ) + block.append_op( + type='reduce_sum', + inputs={'X': pow_out}, + outputs={'Out': sum_out_1}, + attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all}, + ) + block.append_op( + type='reduce_sum', + inputs={'X': sum_out_1}, + outputs={'Out': sum_out_2}, + attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all}, + ) + block.append_op( + type='pow', + inputs={'X': sum_out_2}, + outputs={'Out': out}, + attrs={'factor': float(1.0 / porder)}, + ) + return out + + def svd_norm(input, porder, axis=[-1]): + """ + NOTE: + Calculate the matrix norm, which is related to singular values, of a matrix + or batches of matrices, including nuclear norm, 2-norm and (-2)-norm. + """ + reduce_all = True if axis is None or axis == [] else False + keepdim = False + + u, s, vh = svd(input, full_matrices=False) + + if _non_static_mode(): + if porder == "nuc": + if in_dygraph_mode(): + return _C_ops.sum(s, axis, None, keepdim) + else: + return _legacy_C_ops.reduce_sum( + s, + 'dim', + axis, + 'keepdim', + keepdim, + 'reduce_all', + reduce_all, + ) + if in_dygraph_mode(): + max_out = _C_ops.max(s, axis, keepdim) + min_out = _C_ops.min(s, axis, keepdim) + if porder == 2: + return _C_ops.divide(max_out, min_out) + if porder == -2: + return _C_ops.divide(min_out, max_out) + + else: + max_out = _legacy_C_ops.reduce_max( + s, 'dim', axis, 'keepdim', keepdim, 'reduce_all', reduce_all + ) + min_out = _legacy_C_ops.reduce_min( + s, 'dim', axis, 'keepdim', keepdim, 'reduce_all', reduce_all + ) + if porder == 2: + return _legacy_C_ops.elementwise_div( + max_out, min_out, 'aixs', axis, 'use_mkldnn', False + ) + if porder == -2: + return _legacy_C_ops.elementwise_div( + min_out, max_out, 'aixs', axis, 'use_mkldnn', False + ) + + block = LayerHelper('norm', **locals()) + out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + if porder == "nuc": + block.append_op( + type='reduce_sum', + inputs={'X': s}, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all, + }, + ) + return out + max_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + min_out = block.create_variable_for_type_inference( + dtype=block.input_dtype() + ) + block.append_op( + type='reduce_max', + inputs={'X': s}, + outputs={'Out': max_out}, + attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all}, + ) + block.append_op( + type='reduce_min', + inputs={'X': s}, + outputs={'Out': min_out}, + attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all}, + ) + if porder == 2: + block.append_op( + type='elementwise_div', + inputs={'X': max_out, 'Y': min_out}, + outputs={'Out': out}, + attrs={'aixs': axis, 'use_mkldnn': False}, + ) + return out + if porder == -2: + block.append_op( + type='elementwise_div', + inputs={'X': min_out, 'Y': max_out}, + outputs={'Out': out}, + attrs={'aixs': axis, 'use_mkldnn': False}, + ) + return out + + def empty_tensor(input, shape): + if paddle.in_dynamic_mode(): + return input.reshape(shape) + raise ValueError("only support x is nonempty tensor in static mode") + + x_shape = list(x.shape) + if not len(x_shape) >= 2: + raise ValueError( + "input should be a matrix or batches of matrices, " + + "but the dimention of received input is {}".format(len(x_shape)) + ) + if p == None: + p = 2 + x_size = 0 if (0 in x_shape) else 1 + if p in ("fro", "nuc", 1, -1, np.inf, -np.inf): + if x_shape[len(x_shape) - 1] == x_shape[len(x_shape) - 2]: + if x_size == 0: + return empty_tensor(x, x_shape[:-2]) + x_inv = x.inverse() + if p == "fro": + return fro_norm(x) * fro_norm(x_inv) + if p == "nuc": + return svd_norm(x, p) * svd_norm(x_inv, p) + if p in (1, -1): + return mat_norm(x, porder=p, axis=[-2]) * mat_norm( + x_inv, porder=p, axis=[-2] + ) + if p in (np.inf, -np.inf): + return mat_norm(x, porder=p, axis=[-1]) * mat_norm( + x_inv, porder=p, axis=[-1] + ) + else: + raise ValueError( + "only support p is {} when input is a ".format(p) + + "square matrix or batches of square matrices" + ) + elif p in (2, -2): + if x_size == 0: + return empty_tensor(x, x_shape[:-2]) + return svd_norm(x, porder=p) + else: + raise ValueError( + "unsupported {} for p, only supporting ('fro', 'nuc', ".format(p) + + "1, -1, 2, -2, inf, -inf) or none" + ) + + +def dot(x, y, name=None): + """ + This operator calculates inner product for vectors. + + Note: + Support 1-d and 2-d Tensor. When it is 2d, the first dimension of this matrix + is the batch dimension, which means that the vectors of multiple batches are dotted. + + Parameters: + x(Tensor): 1-D or 2-D ``Tensor``. Its dtype should be ``float32``, ``float64``, ``int32``, ``int64`` + y(Tensor): 1-D or 2-D ``Tensor``. Its dtype soulde be ``float32``, ``float64``, ``int32``, ``int64`` + name(str, optional): Name of the output. Default is None. It's used to print debug info for developers. Details: :ref:`api_guide_Name` + + Returns: + Tensor: the calculated result Tensor. + + Examples: + + .. code-block:: python + + import paddle + + # 1-D Tensor * 1-D Tensor + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([4, 5, 6]) + z = paddle.dot(x, y) + print(z) # [32] + + # 2-D Tensor * 2-D Tensor + x = paddle.to_tensor([[1, 2, 3], [2, 4, 6]]) + y = paddle.to_tensor([[4, 5, 6], [4, 5, 6]]) + z = paddle.dot(x, y) + print(z) # [[32], [64]] + + """ + if in_dygraph_mode(): + return _C_ops.dot(x, y) + if _in_legacy_dygraph(): + return _legacy_C_ops.dot(x, y) + + op_type = 'dot' + + assert x is not None, 'x cannot be None in {}'.format(op_type) + assert y is not None, 'y cannot be None in {}'.format(op_type) + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], op_type + ) + check_variable_and_dtype( + y, 'y', ['float32', 'float64', 'int32', 'int64'], op_type + ) + + helper = LayerHelper(op_type, **locals()) + if name is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + out = helper.create_variable( + name=name, dtype=x.dtype, persistable=False + ) + helper.append_op( + type="dot", inputs={'X': x, 'Y': y}, attrs={}, outputs={"Out": out} + ) + return out + + +def cov(x, rowvar=True, ddof=True, fweights=None, aweights=None, name=None): + """ + Estimate the covariance matrix of the input variables, given data and weights. + + A covariance matrix is a square matrix, indicate the covariance of each pair variables in the input matrix. + For example, for an N-dimensional samples X=[x1,x2,…xN]T, then the covariance matrix + element Cij is the covariance of xi and xj. The element Cii is the variance of xi itself. + + Parameters: + x(Tensor): A N-D(N<=2) Tensor containing multiple variables and observations. By default, each row of x represents a variable. Also see rowvar below. + rowvar(Bool, optional): If rowvar is True (default), then each row represents a variable, with observations in the columns. Default: True + ddof(Bool, optional): If ddof=True will return the unbiased estimate, and ddof=False will return the simple average. Default: True + fweights(Tensor, optional): 1-D Tensor of integer frequency weights; The number of times each observation vector should be repeated. Default: None + aweights(Tensor, optional): 1-D Tensor of observation vector weights. How important of the observation vector, larger data means this element is more important. Default: None + name(str, optional): Name of the output. Default is None. It's used to print debug info for developers. Details: :ref:`api_guide_Name` + + Returns: + Tensor: The covariance matrix Tensor of the variables. + + Examples: + + .. code-block:: python + + import paddle + + xt = paddle.rand((3,4)) + paddle.linalg.cov(xt) + + ''' + Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + [[0.07918842, 0.06127326, 0.01493049], + [0.06127326, 0.06166256, 0.00302668], + [0.01493049, 0.00302668, 0.01632146]]) + ''' + """ + op_type = 'cov' + if len(x.shape) > 2 or len(x.shape) < 1: + raise ValueError( + "Input(x) only support N-D (1<=N<=2) tensor in cov, but received " + "length of Input(input) is %s." % len(x.shape) + ) + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'cov') + nx = x + if len(x.shape) == 1: + nx = x.reshape((1, -1)) + if not rowvar and nx.shape[0] != 1: + nx = nx.t() + w = None + observation_num = nx.shape[1] + if fweights is not None: + w = fweights.astype(nx.dtype) + if len(w.shape) > 1: + raise ValueError( + "Input(fweights) only support N-D (N<=1) tensor in cov, but received " + "shape of Input(input) is %s." % len(fweights.shape) + ) + if fweights.shape[0] != observation_num: + raise ValueError( + "The number of Input(fweights) should equal to x's dim[1]: {}, but received " + "size of Input(fweights) is {}.".format( + observation_num, fweights.shape[0] + ) + ) + if fweights.min() < 0: + raise ValueError( + "The value of Input(fweights) cannot be negtive, but received " + "min of Input(fweights) is {}.".format(fweights.min()) + ) + if not paddle.all(fweights == paddle.round(fweights.astype('float64'))): + raise ValueError("Input(fweights) must be integer ") + + if aweights is not None: + aw = aweights.astype(nx.dtype) + if len(aw.shape) > 1: + raise ValueError( + "Input(aweights) only support N-D (N<=1) tensor in cov, but received " + "length of Input(input) is %s." % len(aweights.shape) + ) + check_variable_and_dtype( + aweights, 'dtype', ['float32', 'float64'], 'cov' + ) + if aweights.shape[0] != observation_num: + raise ValueError( + "The number of Input(aweights) should equal to x's dim[1]: {}, but received " + "size of Input(aweights) is {}.".format( + observation_num, aweights.shape[0] + ) + ) + if aweights.min() < 0: + raise ValueError( + "The value of Input(aweights) cannot be negtive, but received " + "min of Input(aweights) is {}.".format(aweights.min()) + ) + if w is not None: + w = w * aw + else: + w = aw + + w_sum = paddle.to_tensor(observation_num, dtype=nx.dtype) + if fweights is not None or aweights is not None: + w_sum = w.sum() + if w_sum.item() == 0: + raise ValueError("The sum of weights is zero, can't be normalized.") + + if w is not None: + nx_w = nx * w + avg = (nx_w).sum(axis=1) / w_sum + else: + avg = nx.sum(axis=1) / w_sum + nx_w = nx + + if w is not None and aweights is not None and ddof == True: + norm_factor = w_sum - (w * aweights).sum() / w_sum + else: + norm_factor = w_sum - ddof + if norm_factor <= 0: + norm_factor = paddle.to_tensor(0, dtype=nx.dtype) + nx = nx - avg.unsqueeze(1) + xxt = paddle.mm(nx, nx_w.t().conj()) + cov = paddle.divide(xxt, norm_factor).squeeze() + return cov + + +def t(input, name=None): + """ + Transpose <=2-D tensor. + 0-D and 1-D tensors are returned as it is and 2-D tensor is equal to + the paddle.transpose function which perm dimensions set 0 and 1. + + Args: + input (Tensor): The input Tensor. It is a N-D (N<=2) Tensor of data types float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + Returns: + Tensor: A transposed n-D Tensor, with data type being float16, float32, float64, int32, int64. + + Examples: + + .. code-block:: python + :name: code-example + import paddle + + # Example 1 (0-D tensor) + x = paddle.to_tensor([0.79]) + paddle.t(x) # [0.79] + + # Example 2 (1-D tensor) + x = paddle.to_tensor([0.79, 0.84, 0.32]) + paddle.t(x) # [0.79000002, 0.83999997, 0.31999999] + paddle.t(x).shape # [3] + + # Example 3 (2-D tensor) + x = paddle.to_tensor([[0.79, 0.84, 0.32], + [0.64, 0.14, 0.57]]) + x.shape # [2, 3] + paddle.t(x) + # [[0.79000002, 0.63999999], + # [0.83999997, 0.14000000], + # [0.31999999, 0.56999999]] + paddle.t(x).shape # [3, 2] + + """ + if len(input.shape) > 2: + raise ValueError( + "Input(input) only support N-D (N<=2) tensor, but received " + "length of Input(input) is %s. Perhaps you can use paddle." + "tensor.transpose() instead." % len(input.shape) + ) + if in_dygraph_mode(): + if len(input.shape) == 1: + return input + # 2-D tensor + perm = [1, 0] + out = _C_ops.transpose(input, perm) + return out + + if _in_legacy_dygraph(): + if len(input.shape) == 1: + return input + # 2-D tensor + perm = [1, 0] + out, _ = _legacy_C_ops.transpose2(input, 'axis', perm) + return out + + check_variable_and_dtype( + input, + 'input', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'transpose', + ) + + helper = LayerHelper('t', **locals()) + out = helper.create_variable_for_type_inference(input.dtype) + input_shape = helper.create_variable_for_type_inference(input.dtype) + if len(input.shape) == 1: + out = input + else: + helper.append_op( + type='transpose2', + inputs={'X': [input]}, + outputs={'Out': [out], 'XShape': [input_shape]}, + attrs={'axis': [1, 0]}, + ) + return out + + +def cross(x, y, axis=9, name=None): + """ + Computes the cross product between two tensors along an axis. + + Inputs must have the same shape, and the length of their axes should be equal to 3. + If `axis` is not given, it defaults to the first axis found with the length 3. + + Args: + x (Tensor): The first input tensor. + y (Tensor): The second input tensor. + axis (int, optional): The axis along which to compute the cross product. It defaults to be 9 which indicates using the first axis found with the length 3. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. A Tensor with same data type as `x`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 1.0, 1.0], + [2.0, 2.0, 2.0], + [3.0, 3.0, 3.0]]) + y = paddle.to_tensor([[1.0, 1.0, 1.0], + [1.0, 1.0, 1.0], + [1.0, 1.0, 1.0]]) + + z1 = paddle.cross(x, y) + # [[-1. -1. -1.] + # [ 2. 2. 2.] + # [-1. -1. -1.]] + + z2 = paddle.cross(x, y, axis=1) + # [[0. 0. 0.] + # [0. 0. 0.] + # [0. 0. 0.]] + """ + if in_dygraph_mode(): + axis = K_DEFAULT_DIM if axis is None else axis + return _C_ops.cross(x, y, axis) + else: + if _in_legacy_dygraph(): + if axis is not None: + return _legacy_C_ops.cross(x, y, 'dim', axis) + else: + return _legacy_C_ops.cross(x, y) + else: + helper = LayerHelper("cross", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + attrs = dict() + attrs['dim'] = axis + + helper.append_op( + type='cross', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs=attrs, + ) + return out + + +def cholesky(x, upper=False, name=None): + r""" + Computes the Cholesky decomposition of one symmetric positive-definite + matrix or batches of symmetric positive-definite matrice. + + If `upper` is `True`, the decomposition has the form :math:`A = U^{T}U` , + and the returned matrix :math:`U` is upper-triangular. Otherwise, the + decomposition has the form :math:`A = LL^{T}` , and the returned matrix + :math:`L` is lower-triangular. + + Args: + x (Tensor): The input tensor. Its shape should be `[*, M, M]`, + where * is zero or more batch dimensions, and matrices on the + inner-most 2 dimensions all should be symmetric positive-definite. + Its data type should be float32 or float64. + upper (bool): The flag indicating whether to return upper or lower + triangular matrices. Default: False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, A Tensor with same shape and data type as `x`. It represents + triangular matrices generated by Cholesky decomposition. + + Examples: + .. code-block:: python + + import paddle + + a = paddle.rand([3, 3], dtype="float32") + a_t = paddle.transpose(a, [1, 0]) + x = paddle.matmul(a, a_t) + 1e-03 + + out = paddle.linalg.cholesky(x, upper=False) + print(out) + """ + if in_dygraph_mode(): + return _C_ops.cholesky(x, upper) + + if _in_legacy_dygraph(): + return _legacy_C_ops.cholesky(x, "upper", upper) + + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'cholesky') + check_type(upper, 'upper', bool, 'cholesky') + helper = LayerHelper('cholesky', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='cholesky', + inputs={'X': [x]}, + outputs={'Out': out}, + attrs={'upper': upper}, + ) + return out + + +def matrix_rank(x, tol=None, hermitian=False, name=None): + r""" + Computes the rank of a matrix. + + The rank of a matrix is the number of singular values that are greater than the specified `tol` threshold when hermitian=False, + or the number of eigenvalues in absolute value that are greater than the specified `tol` threshold when hermitian=True. + + Args: + x (Tensor): The input tensor. Its shape should be `[..., m, n]`, where `...` is zero or more batch dimensions. If `x` is a batch + of matrices then the output has the same batch dimensions. The data type of `x` should be float32 or float64. + tol (float,Tensor,optional): the tolerance value. Default: None. If `tol` is not specified, and `sigma` is the largest + singular value (or eigenvalues in absolute value), and `eps` is the epsilon value for the dtype of `x`, then `tol` is computed + with formula `tol=sigma * max(m,n) * eps`. Note that if `x` is a batch of matrices, `tol` is computed this way for every batch. + hermitian (bool,optional): indicates whether `x` is Hermitian. Default: False. When hermitian=True, `x` is assumed to be Hermitian, + enabling a more efficient method for finding eigenvalues, but `x` is not checked inside the function. Instead, We just use + the lower triangular of the matrix to compute. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Rank of tensor x. + + Examples: + .. code-block:: python + + import paddle + + a = paddle.eye(10) + b = paddle.linalg.matrix_rank(a) + print(b) + # b = [10] + + c = paddle.ones(shape=[3, 4, 5, 5]) + d = paddle.linalg.matrix_rank(c, tol=0.01, hermitian=True) + print(d) + # d = [[1, 1, 1, 1], + # [1, 1, 1, 1], + # [1, 1, 1, 1]] + + """ + if in_dygraph_mode(): + if isinstance(tol, Variable): + if tol.dtype != x.dtype: + tol_tensor = cast(tol, x.dtype) + else: + tol_tensor = tol + use_default_tol = False + return _C_ops.matrix_rank_tol( + x, tol_tensor, use_default_tol, hermitian + ) + + if tol is None: + tol_attr = 0.0 + use_default_tol = True + else: + tol_attr = float(tol) + use_default_tol = False + return _C_ops.matrix_rank(x, tol_attr, use_default_tol, hermitian) + + if _in_legacy_dygraph(): + if tol is None: + tol_tensor = None + tol_attr = 0.0 + use_default_tol = True + elif isinstance(tol, Variable): + if tol.dtype != x.dtype: + tol_tensor = cast(tol, x.dtype) + else: + tol_tensor = tol + tol_attr = 0.0 + use_default_tol = False + else: + tol_tensor = None + tol_attr = float(tol) + use_default_tol = False + return _legacy_C_ops.matrix_rank( + x, + tol_tensor, + "tol", + tol_attr, + 'hermitian', + hermitian, + 'use_default_tol', + use_default_tol, + ) + + inputs = {} + attrs = {} + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'matrix_rank') + inputs['X'] = x + if tol is None: + attrs['use_default_tol'] = True + elif isinstance(tol, Variable): + attrs['use_default_tol'] = False + if tol.dtype != x.dtype: + inputs['TolTensor'] = cast(tol, x.dtype) + else: + inputs['TolTensor'] = tol + else: + check_type(tol, 'tol', float, 'matrix_rank') + attrs['use_default_tol'] = False + attrs['tol'] = tol + check_type(hermitian, 'hermitian', bool, 'matrix_rank') + attrs['hermitian'] = hermitian + + helper = LayerHelper('matrix_rank', **locals()) + out = helper.create_variable_for_type_inference(dtype='int32') + helper.append_op( + type='matrix_rank', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +def bmm(x, y, name=None): + """ + Applies batched matrix multiplication to two tensors. + + Both of the two input tensors must be three-dementional and share the same batch size. + + if x is a (b, m, k) tensor, y is a (b, k, n) tensor, the output will be a (b, m, n) tensor. + + Args: + x (Tensor): The input Tensor. + y (Tensor): The input Tensor. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + + Returns: + Tensor: The product Tensor. + + Examples: + .. code-block:: python + + import paddle + + # In imperative mode: + # size x: (2, 2, 3) and y: (2, 3, 2) + x = paddle.to_tensor([[[1.0, 1.0, 1.0], + [2.0, 2.0, 2.0]], + [[3.0, 3.0, 3.0], + [4.0, 4.0, 4.0]]]) + y = paddle.to_tensor([[[1.0, 1.0],[2.0, 2.0],[3.0, 3.0]], + [[4.0, 4.0],[5.0, 5.0],[6.0, 6.0]]]) + out = paddle.bmm(x, y) + # Tensor(shape=[2, 2, 2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[[6. , 6. ], + # [12., 12.]], + + # [[45., 45.], + # [60., 60.]]]) + + """ + x_shape = x.shape + y_shape = y.shape + if not len(x_shape) == len(y_shape) == 3: + raise ValueError( + "x and y should be 3-dimensional. But received x's dimention: {}, y's dimention: {}".format( + x_shape, y_shape + ) + ) + if x_shape[2] != y_shape[1]: + raise ValueError( + "x's width must be equal with y's height. But received x's shape: {}, y's shape: {}".format( + x_shape, y_shape + ) + ) + if x_shape[0] != y_shape[0]: + raise ValueError( + "x's batch (shape[0]) must be equal with y's batch (shape[0]). But received x's shape: {}, y's shape: {}".format( + x_shape, y_shape + ) + ) + + if in_dygraph_mode(): + return _C_ops.bmm(x, y) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.bmm(x, y) + + helper = LayerHelper('bmm', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='bmm', inputs={'X': x, 'Y': y}, outputs={'Out': out}) + return out + + +def histogram(input, bins=100, min=0, max=0, name=None): + """ + Computes the histogram of a tensor. The elements are sorted into equal width bins between min and max. + If min and max are both zero, the minimum and maximum values of the data are used. + + Args: + input (Tensor): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` . The data type of the input Tensor + should be float32, float64, int32, int64. + bins (int, optional): number of histogram bins. + min (int, optional): lower end of the range (inclusive). + max (int, optional): upper end of the range (inclusive). + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: data type is int64, shape is (nbins,). + + Examples: + .. code-block:: python + + import paddle + + inputs = paddle.to_tensor([1, 2, 1]) + result = paddle.histogram(inputs, bins=4, min=0, max=3) + print(result) # [0, 2, 1, 0] + """ + if in_dygraph_mode(): + return _C_ops.histogram(input, bins, min, max) + + if _in_legacy_dygraph(): + return _legacy_C_ops.histogram( + input, "bins", bins, "min", min, "max", max + ) + + helper = LayerHelper('histogram', **locals()) + check_variable_and_dtype( + input, 'X', ['int32', 'int64', 'float32', 'float64'], 'histogram' + ) + out = helper.create_variable_for_type_inference(VarDesc.VarType.INT64) + helper.append_op( + type='histogram', + inputs={'X': input}, + outputs={'Out': out}, + attrs={'bins': bins, 'min': min, 'max': max}, + ) + return out + + +def bincount(x, weights=None, minlength=0, name=None): + """ + Computes frequency of each value in the input tensor. + + Args: + x (Tensor): A Tensor with non-negative integer. Should be 1-D tensor. + weights (Tensor, optional): Weight for each value in the input tensor. Should have the same shape as input. Default is None. + minlength (int, optional): Minimum number of bins. Should be non-negative integer. Default is 0. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The tensor of frequency. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 1, 4, 5]) + result1 = paddle.bincount(x) + print(result1) # [0, 2, 1, 0, 1, 1] + + w = paddle.to_tensor([2.1, 0.4, 0.1, 0.5, 0.5]) + result2 = paddle.bincount(x, weights=w) + print(result2) # [0., 2.19999981, 0.40000001, 0., 0.50000000, 0.50000000] + """ + if x.dtype not in [paddle.int32, paddle.int64]: + raise TypeError("Elements in Input(x) should all be integers") + + if _non_static_mode(): + return _legacy_C_ops.bincount(x, weights, "minlength", minlength) + + helper = LayerHelper('bincount', **locals()) + + check_variable_and_dtype(x, 'X', ['int32', 'int64'], 'bincount') + + if weights is not None: + check_variable_and_dtype( + weights, + 'Weights', + ['int32', 'int64', 'float32', 'float64'], + 'bincount', + ) + out = helper.create_variable_for_type_inference(dtype=weights.dtype) + else: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='bincount', + inputs={'X': x, 'Weights': weights}, + outputs={'Out': out}, + attrs={'minlength': minlength}, + ) + return out + + +def mv(x, vec, name=None): + """ + Performs a matrix-vector product of the matrix x and the vector vec. + + Args: + x (Tensor): A tensor with shape :math:`[M, N]` , The data type of the input Tensor x + should be one of float32, float64. + vec (Tensor): A tensor with shape :math:`[N]` , The data type of the input Tensor x + should be one of float32, float64. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The tensor which is producted by x and vec. + + Examples: + .. code-block:: python + + # x: [M, N], vec: [N] + # paddle.mv(x, vec) # out: [M] + + import paddle + + x = paddle.to_tensor([[2, 1, 3], [3, 0, 1]]).astype("float64") + vec = paddle.to_tensor([3, 5, 1]).astype("float64") + out = paddle.mv(x, vec) + print(out) + # Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True, + # [14., 10.]) + """ + if in_dygraph_mode(): + return _C_ops.mv(x, vec) + else: + if _in_legacy_dygraph(): + out = _legacy_C_ops.mv(x, vec) + return out + else: + + def __check_input(x, vec): + var_names = {'x': x, 'vec': vec} + for name, val in var_names.items(): + check_variable_and_dtype( + val, name, ['float32', 'float64'], 'mv' + ) + x_shape = list(x.shape) + vec_shape = list(vec.shape) + if len(x_shape) != 2: + raise ValueError( + "x should be 2-dimensional. But received x's dimention: {}".format( + x_shape + ) + ) + if len(vec_shape) != 1: + raise ValueError( + "vec should be 1-dimensional. But received vec's dimention: {}".format( + vec_shape + ) + ) + + __check_input(x, vec) + + helper = LayerHelper('mv', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='mv', inputs={'X': x, 'Vec': vec}, outputs={'Out': out} + ) + return out + + +def det(x, name=None): + """ + + Calculates determinant value of a square matrix or batches of square matrices. + + Args: + x (Tensor): the input matrix of size `(n, n)` or the + batch of matrices of size `(*, n, n)` where `*` is one or more + batch dimensions. + name(str, optional): Name of the output. Default is None. It's used + to print debug info for developers. Details: :ref:`api_guide_Name` + + Returns: + Tensor, the determinant value of a square matrix or batches of square matrices. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randn([3,3,3]) + + A = paddle.linalg.det(x) + + print(A) + + # [ 0.02547996, 2.52317095, -6.15900707]) + + + """ + if in_dygraph_mode(): + return _C_ops.det(x) + + if _in_legacy_dygraph(): + return _legacy_C_ops.determinant(x) + + check_dtype(x.dtype, 'Input', ['float32', 'float64'], 'det') + + input_shape = list(x.shape) + assert len(input_shape) >= 2, ( + "The x must be at least 2-dimensional, " + "but received Input x's dimensional: %s.\n" % len(input_shape) + ) + + assert ( + input_shape[-1] == input_shape[-2] + ), "Expect squared input," "but received %s by %s matrix.\n" % ( + input_shape[-2], + input_shape[-1], + ) + helper = LayerHelper('determinant', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='determinant', inputs={'Input': [x]}, outputs={'Out': [out]} + ) + return out + + +def slogdet(x, name=None): + """ + + Calculates the sign and natural logarithm of the absolute value of a square matrix's or batches square matrices' determinant. + The determinant can be computed with ``sign * exp`` (logabsdet) + + Supports input of float, double + + Note that for matrices that have zero determinant, this returns ``(0, -inf)`` + + Args: + x (Tensor): the batch of matrices of size :math:`(*, n, n)` + where math:`*` is one or more batch dimensions. + + Returns: + y (Tensor), A tensor containing the sign of the determinant and the natural logarithm + of the absolute value of determinant, respectively. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.randn([3,3,3]) + + A = paddle.linalg.slogdet(x) + + print(A) + + # [[ 1. , 1. , -1. ], + # [-0.98610914, -0.43010661, -0.10872950]]) + + """ + if in_dygraph_mode(): + return _C_ops.slogdet(x) + + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.slogdeterminant(x) + + check_dtype(x.dtype, 'Input', ['float32', 'float64'], 'slogdet') + + input_shape = list(x.shape) + assert len(input_shape) >= 2, ( + "The x must be at least 2-dimensional, " + "but received Input x's dimensional: %s.\n" % len(input_shape) + ) + + assert ( + input_shape[-1] == input_shape[-2] + ), "Expect squared input," "but received %s by %s matrix.\n" % ( + input_shape[-2], + input_shape[-1], + ) + helper = LayerHelper('slogdeterminant', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='slogdeterminant', inputs={'Input': [x]}, outputs={'Out': [out]} + ) + return out + + +def svd(x, full_matrices=False, name=None): + r""" + Computes the singular value decomposition of one matrix or a batch of regular matrices. + + Let :math:`X` be the input matrix or a batch of input matrices, the output should satisfies: + + .. math:: + X = U * diag(S) * VT + + Args: + x (Tensor): The input tensor. Its shape should be `[..., N, M]`, + where `...` is zero or more batch dimensions. N and M can be arbitraty + positive number. Note that if x is sigular matrices, the grad is numerical + instable. The data type of x should be float32 or float64. + full_matrices (bool): A flag to control the behavor of svd. + If full_matrices = True, svd op will compute full U and V matrics, + which means shape of U is `[..., N, N]`, shape of V is `[..., M, M]`. K = min(M, N). + If full_matrices = False, svd op will use a economic method to store U and V. + which means shape of U is `[..., N, K]`, shape of V is `[..., M, K]`. K = min(M, N). + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tuple of 3 tensors: (U, S, VH). VH is the conjugate transpose of V. S is the singlar value vectors of matrics with shape `[..., K]` + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0], [1.0, 3.0], [4.0, 6.0]]).astype('float64') + x = x.reshape([3, 2]) + u, s, vh = paddle.linalg.svd(x) + print (u) + #U = [[ 0.27364809, -0.21695147 ], + # [ 0.37892198, -0.87112408 ], + # [ 0.8840446 , 0.44053933 ]] + + print (s) + #S = [8.14753743, 0.78589688] + print (vh) + #VT= [[ 0.51411221, 0.85772294], + # [ 0.85772294, -0.51411221]] + + # one can verify : U * S * VT == X + # U * UH == I + # V * VH == I + """ + if in_dygraph_mode(): + return _C_ops.svd(x, full_matrices) + if _in_legacy_dygraph(): + return _legacy_C_ops.svd(x, 'full_matrices', full_matrices) + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'svd') + check_type(full_matrices, 'full_matrices', bool, 'svd') + helper = LayerHelper('svd', **locals()) + u = helper.create_variable_for_type_inference(dtype=x.dtype) + vh = helper.create_variable_for_type_inference(dtype=x.dtype) + s = helper.create_variable_for_type_inference(dtype=x.dtype) + attrs = dict() + attrs['full_matrices'] = full_matrices + helper.append_op( + type='svd', + inputs={'X': [x]}, + outputs={'U': u, 'VH': vh, 'S': s}, + attrs=attrs, + ) + return u, s, vh + + +def matrix_power(x, n, name=None): + r""" + + Computes the n-th power of a square matrix or a batch of square matrices. + + Let :math:`X` be a sqaure matrix or a batch of square matrices, :math:`n` be + an exponent, the equation should be: + + .. math:: + Out = X ^ {n} + + Specifically, + + - If `n > 0`, it returns the matrix or a batch of matrices raised to the power of `n`. + + - If `n = 0`, it returns the identity matrix or a batch of identity matrices. + + - If `n < 0`, it returns the inverse of each matrix (if invertible) raised to the power of `abs(n)`. + + Args: + x (Tensor): A square matrix or a batch of square matrices to be raised + to power `n`. Its shape should be `[*, M, M]`, where `*` is zero or + more batch dimensions. Its data type should be float32 or float64. + n (int): The exponent. It can be any positive, negative integer or zero. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - Tensor, The n-th power of the matrix (or the batch of matrices) `x`. Its + data type should be the same as that of `x`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2, 3], + [1, 4, 9], + [1, 8, 27]], dtype='float64') + print(paddle.linalg.matrix_power(x, 2)) + # [[6. , 34. , 102.], + # [14. , 90. , 282.], + # [36. , 250., 804.]] + + print(paddle.linalg.matrix_power(x, 0)) + # [[1., 0., 0.], + # [0., 1., 0.], + # [0., 0., 1.]] + + print(paddle.linalg.matrix_power(x, -2)) + # [[ 12.91666667, -12.75000000, 2.83333333 ], + # [-7.66666667 , 8. , -1.83333333 ], + # [ 1.80555556 , -1.91666667 , 0.44444444 ]] + """ + if in_dygraph_mode(): + return _C_ops.matrix_power(x, n) + + if _in_legacy_dygraph(): + return _legacy_C_ops.matrix_power(x, "n", n) + + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'matrix_power') + check_type(n, 'n', int, 'matrix_power') + helper = LayerHelper('matrix_power', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='matrix_power', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'n': n}, + ) + return out + + +def qr(x, mode="reduced", name=None): + r""" + Computes the QR decomposition of one matrix or batches of matrice (backward is unsupported now). + + Args: + x (Tensor): The input tensor. Its shape should be `[..., M, N]`, + where ... is zero or more batch dimensions. M and N can be arbitrary + positive number. The data type of x should be float32 or float64. + mode (str, optional): A flag to control the behavior of qr, the default is "reduced". + Suppose x's shape is `[..., M, N]` and denoting `K = min(M, N)`: + If mode = "reduced", qr op will return reduced Q and R matrices, + which means Q's shape is `[..., M, K]` and R's shape is `[..., K, N]`. + If mode = "complete", qr op will return complete Q and R matrices, + which means Q's shape is `[..., M, M]` and R's shape is `[..., M, N]`. + If mode = "r", qr op will only return reduced R matrix, which means + R's shape is `[..., K, N]`. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + If mode = "reduced" or mode = "complete", qr will return a two tensor-tuple, which represents Q and R. + If mode = "r", qr will return a tensor which represents R. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64') + q, r = paddle.linalg.qr(x) + print (q) + print (r) + + # Q = [[-0.16903085, 0.89708523], + # [-0.50709255, 0.27602622], + # [-0.84515425, -0.34503278]]) + + # R = [[-5.91607978, -7.43735744], + # [ 0. , 0.82807867]]) + + # one can verify : X = Q * R ; + """ + if in_dygraph_mode(): + q, r = _C_ops.qr(x, mode) + if mode == "r": + return r + else: + return q, r + if _in_legacy_dygraph(): + q, r = _legacy_C_ops.qr(x, 'mode', mode) + if mode == "r": + return r + else: + return q, r + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'qr') + check_type(mode, 'mode', str, 'qr') + helper = LayerHelper('qr', **locals()) + q = helper.create_variable_for_type_inference(dtype=x.dtype) + r = helper.create_variable_for_type_inference(dtype=x.dtype) + attrs = dict() + attrs['mode'] = mode + helper.append_op( + type='qr', inputs={'X': [x]}, outputs={'Q': q, 'R': r}, attrs=attrs + ) + if mode == "r": + return r + else: + return q, r + + +def lu(x, pivot=True, get_infos=False, name=None): + r""" + Computes the LU factorization of an N-D(N>=2) matrix x. + + Returns the LU factorization(inplace x) and Pivots. low triangular matrix L and + upper triangular matrix U are combined to a single LU matrix. + + Pivoting is done if pivot is set to True. + P mat can be get by pivots: + + .. code-block:: text + ones = eye(rows) #eye matrix of rank rows + for i in range(cols): + swap(ones[i], ones[pivots[i]]) + return ones + + Args: + + X (Tensor): the tensor to factor of N-dimensions(N>=2). + + pivot (bool, optional): controls whether pivoting is done. Default: True. + + get_infos (bool, optional): if set to True, returns an info IntTensor. Default: False. + + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + factorization (Tensor), LU matrix, the factorization of input X. + + pivots (IntTensor), the pivots of size(∗(N-2), min(m,n)). `pivots` stores all the + intermediate transpositions of rows. The final permutation `perm` could be + reconstructed by this, details refer to upper example. + + infos (IntTensor, optional), if `get_infos` is `True`, this is a tensor of size (∗(N-2)) + where non-zero values indicate whether factorization for the matrix or each minibatch + has succeeded or failed. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64') + lu,p,info = paddle.linalg.lu(x, get_infos=True) + + # >>> lu: + # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[5. , 6. ], + # [0.20000000, 0.80000000], + # [0.60000000, 0.50000000]]) + # >>> p + # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True, + # [3, 3]) + # >>> info + # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True, + # 0) + + P,L,U = paddle.linalg.lu_unpack(lu,p) + + # >>> P + # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[0., 1., 0.], + # [0., 0., 1.], + # [1., 0., 0.]]), + # >>> L + # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[1. , 0. ], + # [0.20000000, 1. ], + # [0.60000000, 0.50000000]]), + # >>> U + # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[5. , 6. ], + # [0. , 0.80000000]])) + + + # one can verify : X = P @ L @ U ; + """ + + if in_dygraph_mode(): + lu, p, info = _C_ops.lu(x, pivot) + elif paddle.in_dynamic_mode(): + lu, p, info = _legacy_C_ops.lu(x, 'pivot', pivot) + else: + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'lu') + helper = LayerHelper('lu', **locals()) + lu = helper.create_variable_for_type_inference(dtype=x.dtype) + p = helper.create_variable_for_type_inference(dtype='int') + info = helper.create_variable_for_type_inference(dtype='int') + attrs = dict() + attrs['pivot'] = pivot + helper.append_op( + type='lu', + inputs={'X': x}, + outputs={'Out': lu, 'Pivots': p, 'Infos': info}, + attrs=attrs, + ) + if get_infos: + return lu, p, info + else: + return lu, p + + +def lu_unpack(x, y, unpack_ludata=True, unpack_pivots=True, name=None): + r""" + Unpack L U and P to single matrix tensor . + unpack L and U matrix from LU, unpack permutation matrix P from Pivtos . + + P mat can be get by pivots: + + .. code-block:: text + ones = eye(rows) #eye matrix of rank rows + for i in range(cols): + swap(ones[i], ones[pivots[i]]) + + + Args: + x (Tensor): The LU tensor get from paddle.linalg.lu, which is combined by L and U. + + y (Tensor): Pivots get from paddle.linalg.lu. + + unpack_ludata (bool,optional): whether to unpack L and U from x. Default: True. + + unpack_pivots (bool, optional): whether to unpack permutation matrix P from Pivtos. Default: True. + + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + P (Tensor), Permutation matrix P of lu factorization. + + L (Tensor), The lower triangular matrix tensor of lu factorization. + + U (Tensor), The upper triangular matrix tensor of lu factorization. + + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64') + lu,p,info = paddle.linalg.lu(x, get_infos=True) + + # >>> lu: + # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[5. , 6. ], + # [0.20000000, 0.80000000], + # [0.60000000, 0.50000000]]) + # >>> p + # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True, + # [3, 3]) + # >>> info + # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True, + # 0) + + P,L,U = paddle.linalg.lu_unpack(lu,p) + + # >>> P + # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[0., 1., 0.], + # [0., 0., 1.], + # [1., 0., 0.]]), + # >>> L + # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[1. , 0. ], + # [0.20000000, 1. ], + # [0.60000000, 0.50000000]]), + # >>> U + # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, + # [[5. , 6. ], + # [0. , 0.80000000]])) + + # one can verify : X = P @ L @ U ; + """ + + if in_dygraph_mode(): + P, L, U = _C_ops.lu_unpack(x, y, unpack_ludata, unpack_pivots) + return P, L, U + + if paddle.in_dynamic_mode(): + P, L, U = _legacy_C_ops.lu_unpack( + x, y, 'unpack_ludata', unpack_ludata, 'unpack_pivots', unpack_pivots + ) + return P, L, U + + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'lu_unpack') + helper = LayerHelper('lu_unpack', **locals()) + p = helper.create_variable_for_type_inference(dtype=x.dtype) + l = helper.create_variable_for_type_inference(dtype=x.dtype) + u = helper.create_variable_for_type_inference(dtype=x.dtype) + + attrs = dict() + attrs['unpack_ludata'] = unpack_ludata + attrs['unpack_pivots'] = unpack_pivots + helper.append_op( + type='lu_unpack', + inputs={'X': x, 'Pivots': y}, + outputs={'Pmat': p, 'L': l, 'U': u}, + attrs=attrs, + ) + return p, l, u + + +def eig(x, name=None): + """ + Performs the eigenvalue decomposition of a square matrix or a batch of square matrices. + + Note: + - If the matrix is a Hermitian or a real symmetric matrix, please use :ref:`paddle.linalg.eigh` instead, which is much faster. + - If only eigenvalues is needed, please use :ref:`paddle.linalg.eigvals` instead. + - If the matrix is of any shape, please use :ref:`paddle.linalg.svd`. + - This API is only supported on CPU device. + - The output datatype is always complex for both real and complex input. + + Args: + x (Tensor): A tensor with shape math:`[*, N, N]`, The data type of the x should be one of ``float32``, + ``float64``, ``compplex64`` or ``complex128``. + name (str, optional): The default value is `None`. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Eigenvalues(Tensors): A tensor with shape math:`[*, N]` refers to the eigen values. + Eigenvectors(Tensors): A tensor with shape math:`[*, N, N]` refers to the eigen vectors. + + Examples: + .. code-block:: python + + import paddle + + paddle.device.set_device("cpu") + + x = paddle.to_tensor([[1.6707249, 7.2249975, 6.5045543], + [9.956216, 8.749598, 6.066444 ], + [4.4251957, 1.7983172, 0.370647 ]]) + w, v = paddle.linalg.eig(x) + print(v) + # Tensor(shape=[3, 3], dtype=complex128, place=CPUPlace, stop_gradient=False, + # [[(-0.5061363550800655+0j) , (-0.7971760990842826+0j) , + # (0.18518077798279986+0j)], + # [(-0.8308237755993192+0j) , (0.3463813401919749+0j) , + # (-0.6837005269141947+0j) ], + # [(-0.23142567697893396+0j), (0.4944999840400175+0j) , + # (0.7058765252952796+0j) ]]) + + print(w) + # Tensor(shape=[3], dtype=complex128, place=CPUPlace, stop_gradient=False, + # [ (16.50471283351188+0j) , (-5.5034820550763515+0j) , + # (-0.21026087843552282+0j)]) + """ + if in_dygraph_mode(): + return _C_ops.eig(x) + elif paddle.in_dynamic_mode(): + w, v = _legacy_C_ops.eig(x) + return w, v + + check_variable_and_dtype( + x, 'X', ['float32', 'float64', 'complex64', 'complex128'], 'eig' + ) + helper = LayerHelper('eig', **locals()) + + w = helper.create_variable_for_type_inference(x.dtype) + v = helper.create_variable_for_type_inference(x.dtype) + + inputs = {'X': x} + outputs = {'Eigenvalues': w, 'Eigenvectors': v} + helper.append_op(type='eig', inputs=inputs, outputs=outputs) + + return w, v + + +def eigvals(x, name=None): + """ + Compute the eigenvalues of one or more general matrices. + + Warning: + The gradient kernel of this operator does not yet developed. + If you need back propagation through this operator, please replace it with paddle.linalg.eig. + + Args: + x (Tensor): A square matrix or a batch of square matrices whose eigenvalues will be computed. + Its shape should be `[*, M, M]`, where `*` is zero or more batch dimensions. + Its data type should be float32, float64, complex64, or complex128. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, A tensor containing the unsorted eigenvalues which has the same batch + dimensions with `x`. The eigenvalues are complex-valued even when `x` is real. + + Examples: + .. code-block:: python + + import paddle + + paddle.set_device("cpu") + paddle.seed(1234) + + x = paddle.rand(shape=[3, 3], dtype='float64') + # [[0.02773777, 0.93004224, 0.06911496], + # [0.24831591, 0.45733623, 0.07717843], + # [0.48016702, 0.14235102, 0.42620817]]) + + print(paddle.linalg.eigvals(x)) + # [(-0.27078833542132674+0j), (0.29962280156230725+0j), (0.8824477020120244+0j)] #complex128 + """ + + check_variable_and_dtype( + x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'eigvals' + ) + + x_shape = list(x.shape) + if len(x_shape) < 2: + raise ValueError( + "The dimension of Input(x) should be at least 2, but received x's dimention = {}, x's shape = {}".format( + len(x_shape), x_shape + ) + ) + + if x_shape[-1] != x_shape[-2]: + raise ValueError( + "The last two dimensions of Input(x) should be equal, but received x's shape = {}".format( + x_shape + ) + ) + + if in_dygraph_mode(): + return _C_ops.eigvals(x) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.eigvals(x) + + helper = LayerHelper('eigvals', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='eigvals', inputs={'X': x}, outputs={'Out': out}) + return out + + +def multi_dot(x, name=None): + """ + Multi_dot is an operator that calculates multiple matrix multiplications. + + Supports inputs of float16(only GPU support), float32 and float64 dtypes. This function does not + support batched inputs. + + The input tensor in [x] must be 2-D except for the first and last can be 1-D. + If the first tensor is a 1-D vector of shape(n, ) it is treated as row vector + of shape(1, n), similarly if the last tensor is a 1D vector of shape(n, ), it + is treated as a column vector of shape(n, 1). + + If the first and last tensor are 2-D matrix, then the output is also 2-D matrix, + otherwise the output is a 1-D vector. + + Multi_dot will select the lowest cost multiplication order for calculation. The + cost of multiplying two matrices with shapes (a, b) and (b, c) is a * b * c. + Given matrices A, B, C with shapes (20, 5), (5, 100), (100, 10) respectively, + we can calculate the cost of different multiplication orders as follows: + - Cost((AB)C) = 20x5x100 + 20x100x10 = 30000 + - Cost(A(BC)) = 5x100x10 + 20x5x10 = 6000 + + In this case, multiplying B and C first, then multiply A, which is 5 times faster + than sequential calculation. + + Args: + x ([Tensor]): The input tensors which is a list Tensor. + name(str|None): A name for this layer(optional). If set None, the layer + will be named automatically. + + Returns: + Tensor: The output Tensor. + + + Examples: + + .. code-block:: python + + import paddle + # A * B + A = paddle.rand([3, 4]) + B = paddle.rand([4, 5]) + out = paddle.linalg.multi_dot([A, B]) + print(out.shape) + # [3, 5] + # A * B * C + A = paddle.rand([10, 5]) + B = paddle.rand([5, 8]) + C = paddle.rand([8, 7]) + out = paddle.linalg.multi_dot([A, B, C]) + print(out.shape) + # [10, 7] + """ + if _in_legacy_dygraph(): + return _legacy_C_ops.multi_dot(x) + if in_dygraph_mode(): + return _C_ops.multi_dot(x) + + check_type(x, 'x', (list, tuple), 'multi_dot') + for id, item in enumerate(x): + check_variable_and_dtype( + item, + 'x[' + str(id) + ']', + ['float16', 'float32', 'float64'], + 'multi_dot', + ) + if item.dtype != x[0].dtype: + raise TypeError( + "All the Tensors in the input must have the same data type." + ) + + helper = LayerHelper('multi_dot', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='multi_dot', inputs={"X": x}, outputs={"Out": out}) + return out + + +def eigh(x, UPLO='L', name=None): + """ + Compute the eigenvalues and eigenvectors of a + complex Hermitian (conjugate symmetric) or a real symmetric matrix. + + Args: + x (Tensor): A tensor with shape :math:`[*, N, N]` , The data type of the input Tensor x + should be one of float32, float64, complex64, complex128. + UPLO(str, optional): (string, default 'L'), 'L' represents the lower triangular matrix, + "'U' represents the upper triangular matrix.". + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + - out_value(Tensor): A Tensor with shape [*, N] and data type of float32 and float64. + The eigenvalues of eigh op. + - out_vector(Tensor): A Tensor with shape [*, N, N] and data type of float32,float64, + complex64 and complex128. The eigenvectors of eigh op. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, -2j], [2j, 5]]) + out_value, out_vector = paddle.linalg.eigh(x, UPLO='L') + print(out_value) + #[0.17157288, 5.82842712] + print(out_vector) + #[(-0.9238795325112867+0j), (-0.3826834323650898+0j)], + #[ 0.3826834323650898j , -0.9238795325112867j ]] + + """ + if in_dygraph_mode(): + return _C_ops.eigh(x, UPLO) + + if _in_legacy_dygraph(): + return _legacy_C_ops.eigh(x, 'UPLO', UPLO) + + def __check_input(x, UPLO): + x_shape = list(x.shape) + if len(x.shape) < 2: + raise ValueError( + "Input(input) only support >=2 tensor, but received " + "length of Input(input) is %s." % len(x.shape) + ) + if x_shape[-1] != x_shape[-2]: + raise ValueError( + "The input matrix must be batches of square matrices. But received x's dimention: {}".format( + x_shape + ) + ) + if UPLO != 'L' and UPLO != 'U': + raise ValueError( + "UPLO must be L or U. But received UPLO is: {}".format(UPLO) + ) + + __check_input(x, UPLO) + + helper = LayerHelper('eigh', **locals()) + check_variable_and_dtype( + x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'eigh' + ) + + out_value = helper.create_variable_for_type_inference(dtype=x.dtype) + out_vector = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='eigh', + inputs={'X': x}, + outputs={'Eigenvalues': out_value, 'Eigenvectors': out_vector}, + attrs={'UPLO': UPLO}, + ) + return out_value, out_vector + + +def pinv(x, rcond=1e-15, hermitian=False, name=None): + r""" + Calculate pseudo inverse via SVD(singular value decomposition) + of one matrix or batches of regular matrix. + + .. math:: + + if hermitian == False: + x = u * s * vt (SVD) + out = v * 1/s * ut + else: + x = u * s * ut (eigh) + out = u * 1/s * u.conj().transpose(-2,-1) + + If x is hermitian or symmetric matrix, svd will be replaced with eigh. + + Args: + x(Tensor): The input tensor. Its shape should be (*, m, n) + where * is zero or more batch dimensions. m and n can be + arbitraty positive number. The data type of x should be + float32 or float64 or complex64 or complex128. When data + type is complex64 or cpmplex128, hermitian should be set + True. + + rcond(Tensor, optional): the tolerance value to determine + when is a singular value zero. Default:1e-15. + + hermitian(bool, optional): indicates whether x is Hermitian + if complex or symmetric if real. Default: False. + + name(str|None): A name for this layer(optional). If set None, + the layer will be named automatically. + + Returns: + Tensor: The tensor with same data type with x. it represents + pseudo inverse of x. Its shape should be (*, n, m). + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(15).reshape((3, 5)).astype('float64') + input = paddle.to_tensor(x) + out = paddle.linalg.pinv(input) + print(input) + print(out) + + # input: + # [[0. , 1. , 2. , 3. , 4. ], + # [5. , 6. , 7. , 8. , 9. ], + # [10., 11., 12., 13., 14.]] + + # out: + # [[-0.22666667, -0.06666667, 0.09333333], + # [-0.12333333, -0.03333333, 0.05666667], + # [-0.02000000, 0.00000000, 0.02000000], + # [ 0.08333333, 0.03333333, -0.01666667], + # [ 0.18666667, 0.06666667, -0.05333333]] + + # one can verify : x * out * x = x ; + # or out * x * out = x ; + """ + if in_dygraph_mode(): + if not hermitian: + # combine svd and matmul op + u, s, vt = _C_ops.svd(x, False) + max_singular_val = _C_ops.max(s, [-1], True) + rcond = paddle.to_tensor(rcond, dtype=x.dtype) + cutoff = rcond * max_singular_val + y = float('inf') + y = paddle.to_tensor(y, dtype=x.dtype) + + condition = s > cutoff + cond_int = cast(condition, s.dtype) + cond_not_int = cast(logical_not(condition), s.dtype) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + st = _C_ops.unsqueeze(singular, [-2]) + + dims = list(range(len(vt.shape))) + perm = dims[:-2] + [dims[-1]] + [dims[-2]] + v = _C_ops.transpose(vt, perm) + + out_1 = v * st + out_2 = _C_ops.matmul(out_1, u, False, True) + return out_2 + else: + # combine eigh and matmul op + s, u = _C_ops.eigh(x, 'UPLO') + s_abs = paddle.abs(s) + max_singular_val = _C_ops.max(s_abs, [-1], True) + rcond = paddle.to_tensor(rcond, dtype=s.dtype) + cutoff = rcond * max_singular_val + y = float('inf') + y = paddle.to_tensor(y, dtype=s.dtype) + + condition = s_abs > cutoff + cond_int = cast(condition, s.dtype) + cond_not_int = cast(logical_not(condition), s.dtype) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + st = _C_ops.unsqueeze(singular, [-2]) + + out_1 = u * st + u_conj = _C_ops.conj(u) + out_2 = _C_ops.matmul(out_1, u_conj, False, True) + return out_2 + + if _in_legacy_dygraph(): + if not hermitian: + # combine svd and matmul op + u, s, vt = _legacy_C_ops.svd(x, 'full_matrices', False) + max_singular_val = _legacy_C_ops.reduce_max( + s, 'dim', [-1], 'keep_dim', True, 'reduce_all', False + ) + rcond = paddle.to_tensor(rcond, dtype=x.dtype) + cutoff = rcond * max_singular_val + y = float('inf') + y = paddle.to_tensor(y, dtype=x.dtype) + + condition = s > cutoff + cond_int = cast(condition, s.dtype) + cond_not_int = cast(logical_not(condition), s.dtype) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + st, _ = _legacy_C_ops.unsqueeze2(singular, 'axes', [-2]) + + dims = list(range(len(vt.shape))) + perm = dims[:-2] + [dims[-1]] + [dims[-2]] + v, _ = _legacy_C_ops.transpose2(vt, 'axis', perm) + + out_1 = v * st + if in_dygraph_mode(): + out_2 = _C_ops.matmul(out_1, u, False, True) + else: + out_2 = _legacy_C_ops.matmul_v2( + out_1, u, 'trans_x', False, 'trans_y', True + ) + return out_2 + else: + # combine eigh and matmul op + s, u = _legacy_C_ops.eigh(x, 'UPLO', 'L') + s_abs = paddle.abs(s) + max_singular_val = _legacy_C_ops.reduce_max( + s_abs, 'dim', [-1], 'keep_dim', True, 'reduce_all', False + ) + rcond = paddle.to_tensor(rcond, dtype=s.dtype) + cutoff = rcond * max_singular_val + y = float('inf') + y = paddle.to_tensor(y, dtype=s.dtype) + + condition = s_abs > cutoff + cond_int = cast(condition, s.dtype) + cond_not_int = cast(logical_not(condition), s.dtype) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + st, _ = _legacy_C_ops.unsqueeze2(singular, 'axes', [-2]) + + out_1 = u * st + u_conj = _legacy_C_ops.conj(u) + if in_dygraph_mode(): + out_2 = _C_ops.matmul(out_1, u_conj, False, True) + else: + out_2 = _legacy_C_ops.matmul_v2( + out_1, u_conj, 'trans_x', False, 'trans_y', True + ) + return out_2 + else: + if not hermitian: + helper = LayerHelper('pinv', **locals()) + dtype = x.dtype + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pinv') + + u = helper.create_variable_for_type_inference(dtype) + s = helper.create_variable_for_type_inference(dtype) + vt = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='svd', + inputs={'X': [x]}, + outputs={'U': u, 'VH': vt, 'S': s}, + attrs={'full_matrices': False}, + ) + + max_singular_val = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='reduce_max', + inputs={'X': s}, + outputs={'Out': max_singular_val}, + attrs={'dim': [-1], 'keep_dim': True, 'reduce_all': False}, + ) + + rcond = full(shape=[1], fill_value=rcond, dtype=dtype) + cutoff = rcond * max_singular_val + y = float('inf') + y = full(shape=[1], fill_value=y, dtype=dtype) + + condition = s > cutoff + cond_int = cast(condition, dtype) + cond_not_int = cast(logical_not(condition), dtype) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + + st = helper.create_variable_for_type_inference(dtype=dtype) + st_shape = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op( + type='unsqueeze2', + inputs={'X': singular}, + attrs={'axes': [-2]}, + outputs={'Out': st, 'XShape': st_shape}, + ) + + dims = list(range(len(vt.shape))) + perm = dims[:-2] + [dims[-1]] + [dims[-2]] + v = helper.create_variable_for_type_inference(dtype) + v_shape = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='transpose2', + inputs={'X': [vt]}, + outputs={'Out': [v], 'XShape': [v_shape]}, + attrs={'axis': perm}, + ) + + out_1 = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='elementwise_mul', + inputs={'X': v, 'Y': st}, + outputs={'Out': out_1}, + attrs={'axis': -1, 'use_mkldnn': False}, + ) + out_1 = helper.append_activation(out_1) + + out_2 = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='matmul_v2', + inputs={'X': out_1, 'Y': u}, + outputs={'Out': out_2}, + attrs={'trans_x': False, 'trans_y': True}, + ) + return out_2 + else: + helper = LayerHelper('pinv', **locals()) + dtype = x.dtype + check_variable_and_dtype( + x, + 'dtype', + ['float32', 'float64', 'complex64', 'complex128'], + 'pinv', + ) + + if dtype == paddle.complex128: + s_type = 'float64' + elif dtype == paddle.complex64: + s_type = 'float32' + else: + s_type = dtype + + u = helper.create_variable_for_type_inference(dtype) + s = helper.create_variable_for_type_inference(s_type) + helper.append_op( + type='eigh', + inputs={'X': x}, + outputs={'Eigenvalues': s, 'Eigenvectors': u}, + attrs={'UPLO': 'L'}, + ) + s_abs = helper.create_variable_for_type_inference(s_type) + helper.append_op( + type='abs', inputs={'X': s}, outputs={'Out': s_abs} + ) + max_singular_val = helper.create_variable_for_type_inference(s_type) + helper.append_op( + type='reduce_max', + inputs={'X': s_abs}, + outputs={'Out': max_singular_val}, + attrs={'dim': [-1], 'keep_dim': True, 'reduce_all': False}, + ) + + rcond = full(shape=[1], fill_value=rcond, dtype=s_type) + cutoff = rcond * max_singular_val + y = float('inf') + y = full(shape=[1], fill_value=y, dtype=s_type) + + condition = s_abs > cutoff + cond_int = cast(condition, s_type) + cond_not_int = cast(logical_not(condition), s_type) + out1 = multiply(1 / s, cond_int) + out2 = multiply(1 / y, cond_not_int) + singular = add(out1, out2) + + st = helper.create_variable_for_type_inference(dtype=s_type) + st_shape = helper.create_variable_for_type_inference(dtype=s_type) + helper.append_op( + type='unsqueeze2', + inputs={'X': singular}, + attrs={'axes': [-2]}, + outputs={'Out': st, 'XShape': st_shape}, + ) + + out_1 = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='elementwise_mul', + inputs={'X': u, 'Y': st}, + outputs={'Out': out_1}, + attrs={'axis': -1, 'use_mkldnn': False}, + ) + out_1 = helper.append_activation(out_1) + + u_conj = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='conj', inputs={'X': u}, outputs={'Out': [u_conj]} + ) + + out_2 = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='matmul_v2', + inputs={'X': out_1, 'Y': u_conj}, + outputs={'Out': out_2}, + attrs={'trans_x': False, 'trans_y': True}, + ) + return out_2 + + +def solve(x, y, name=None): + r""" + + Computes the solution of a square system of linear equations with a unique solution for input 'X' and 'Y'. + Let :math:`X` be a sqaure matrix or a batch of square matrices, :math:`Y` be + a vector/matrix or a batch of vectors/matrices, the equation should be: + + .. math:: + Out = X^-1 * Y + + Specifically, this system of linear equations has one solution if and only if input 'X' is invertible. + + Args: + x (Tensor): A square matrix or a batch of square matrices. Its shape should be ``[*, M, M]``, where ``*`` is zero or + more batch dimensions. Its data type should be float32 or float64. + y (Tensor): A vector/matrix or a batch of vectors/matrices. Its shape should be ``[*, M, K]``, where ``*`` is zero or + more batch dimensions. Its data type should be float32 or float64. + name(str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The solution of a square system of linear equations with a unique solution for input 'x' and 'y'. + Its data type should be the same as that of `x`. + + Examples: + + .. code-block:: python + + # a square system of linear equations: + # 2*X0 + X1 = 9 + # X0 + 2*X1 = 8 + + import paddle + + x = paddle.to_tensor([[3, 1],[1, 2]], dtype="float64") + y = paddle.to_tensor([9, 8], dtype="float64") + out = paddle.linalg.solve(x, y) + + print(out) + # [2., 3.]) + """ + if in_dygraph_mode(): + return _C_ops.solve(x, y) + + if _in_legacy_dygraph(): + return _legacy_C_ops.solve(x, y) + + inputs = {"X": [x], "Y": [y]} + helper = LayerHelper("solve", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'solve') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'solve') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="solve", inputs={"X": x, "Y": y}, outputs={"Out": out} + ) + return out + + +def triangular_solve( + x, y, upper=True, transpose=False, unitriangular=False, name=None +): + r""" + Computes the solution of a system of equations with a triangular coefficient matrix `x` and + multiple right-hand sides `y` . + + Input `x` and `y` is 2D matrices or batches of 2D matrices. If the inputs are batches, the outputs + is also batches. + + Args: + x (Tensor): The input triangular coefficient matrix. Its shape should be `[*, M, M]`, where `*` is zero or + more batch dimensions. Its data type should be float32 or float64. + y (Tensor): Multiple right-hand sides of system of equations. Its shape should be `[*, M, K]`, where `*` is + zero or more batch dimensions. Its data type should be float32 or float64. + upper (bool, optional): Whether to solve the upper-triangular system of equations (default) or the lower-triangular + system of equations. Default: True. + transpose (bool, optional): whether `x` should be transposed before calculation. Default: False. + unitriangular (bool, optional): whether `x` is unit triangular. If True, the diagonal elements of `x` are assumed + to be 1 and not referenced from `x` . Default: False. + name(str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The solution of the system of equations. Its data type should be the same as that of `x`. + + Examples: + .. code-block:: python + + # a square system of linear equations: + # x1 + x2 + x3 = 0 + # 2*x2 + x3 = -9 + # -x3 = 5 + + import paddle + + x = paddle.to_tensor([[1, 1, 1], + [0, 2, 1], + [0, 0,-1]], dtype="float64") + y = paddle.to_tensor([[0], [-9], [5]], dtype="float64") + out = paddle.linalg.triangular_solve(x, y, upper=True) + + print(out) + # [7, -2, -5] + """ + if in_dygraph_mode(): + return _C_ops.triangular_solve(x, y, upper, transpose, unitriangular) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.triangular_solve( + x, + y, + 'upper', + upper, + 'transpose', + transpose, + 'unitriangular', + unitriangular, + ) + + inputs = {"X": [x], "Y": [y]} + helper = LayerHelper("triangular_solve", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'triangular_solve') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'triangular_solve') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='triangular_solve', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs={ + 'upper': upper, + 'transpose': transpose, + 'unitriangular': unitriangular, + }, + ) + return out + + +def cholesky_solve(x, y, upper=False, name=None): + r""" + Solves a linear system of equations A @ X = B, given A's Cholesky factor matrix u and matrix B. + + Input `x` and `y` is 2D matrices or batches of 2D matrices. If the inputs are batches, the outputs + is also batches. + + Args: + x (Tensor): The input matrix which is upper or lower triangular Cholesky factor of square matrix A. Its shape should be `[*, M, M]`, where `*` is zero or + more batch dimensions. Its data type should be float32 or float64. + y (Tensor): Multiple right-hand sides of system of equations. Its shape should be `[*, M, K]`, where `*` is + zero or more batch dimensions. Its data type should be float32 or float64. + upper (bool, optional): whether to consider the Cholesky factor as a lower or upper triangular matrix. Default: False. + name(str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The solution of the system of equations. Its data type is the same as that of `x`. + + Examples: + .. code-block:: python + + import paddle + + u = paddle.to_tensor([[1, 1, 1], + [0, 2, 1], + [0, 0,-1]], dtype="float64") + b = paddle.to_tensor([[0], [-9], [5]], dtype="float64") + out = paddle.linalg.cholesky_solve(b, u, upper=True) + + print(out) + # [-2.5, -7, 9.5] + """ + if in_dygraph_mode(): + return _C_ops.cholesky_solve(x, y, upper) + + if _in_legacy_dygraph(): + return _legacy_C_ops.cholesky_solve(x, y, 'upper', upper) + + helper = LayerHelper("cholesky_solve", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'cholesky_solve') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'cholesky_solve') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='cholesky_solve', + inputs={'X': x, 'Y': y}, + outputs={'Out': out}, + attrs={'upper': upper}, + ) + return out + + +def eigvalsh(x, UPLO='L', name=None): + """ + Computes the eigenvalues of a + complex Hermitian (conjugate symmetric) or a real symmetric matrix. + + Args: + x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x + should be one of float32, float64, complex64, complex128. + UPLO(str, optional): Lower triangular part of a (‘L’, default) or the upper triangular part (‘U’). + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The tensor eigenvalues in ascending order. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, -2j], [2j, 5]]) + out_value = paddle.eigvalsh(x, UPLO='L') + print(out_value) + # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [0.17157286, 5.82842731]) + """ + if in_dygraph_mode(): + values, _ = _C_ops.eigvalsh(x, UPLO, x.stop_gradient) + return values + + elif paddle.in_dynamic_mode(): + is_test = x.stop_gradient + values, _ = _legacy_C_ops.eigvalsh(x, 'UPLO', UPLO, 'is_test', is_test) + return values + + def __check_input(x, UPLO): + x_shape = list(x.shape) + if len(x.shape) < 2: + raise ValueError( + "Input(input) only support >=2 tensor, but received " + "length of Input(input) is %s." % len(x.shape) + ) + if x_shape[-1] != x_shape[-2]: + raise ValueError( + "The input matrix must be batches of square matrices. But received x's dimention: {}".format( + x_shape + ) + ) + if UPLO != 'L' and UPLO != 'U': + raise ValueError( + "UPLO must be L or U. But received UPLO is: {}".format(UPLO) + ) + + __check_input(x, UPLO) + + helper = LayerHelper('eigvalsh', **locals()) + check_variable_and_dtype( + x, + 'dtype', + ['float32', 'float64', 'complex64', 'complex128'], + 'eigvalsh', + ) + + out_value = helper.create_variable_for_type_inference(dtype=x.dtype) + out_vector = helper.create_variable_for_type_inference(dtype=x.dtype) + + is_test = x.stop_gradient + helper.append_op( + type='eigvalsh', + inputs={'X': x}, + outputs={'Eigenvalues': out_value, 'Eigenvectors': out_vector}, + attrs={'UPLO': UPLO, 'is_test': is_test}, + ) + return out_value + + +def lstsq(x, y, rcond=None, driver=None, name=None): + """ + Computes a solution to + the least squares problem of a system of linear equations. + + Args: + x (Tensor): A tensor with shape ``(*, M, N)`` , the data type of the input Tensor ``x`` + should be one of float32, float64. + y (Tensor): A tensor with shape ``(*, M, K)`` , the data type of the input Tensor ``y`` + should be one of float32, float64. + rcond(float, optional): The default value is None. A float pointing number used to determine + the effective rank of ``x``. If ``rcond`` is None, it will be set to max(M, N) times the + machine precision of x_dtype. + driver(str, optional): The default value is None. The name of LAPACK method to be used. For + CPU inputs the valid values are ‘gels’, ‘gelsy’, ‘gelsd, ‘gelss’. For CUDA input, the only + valid driver is ‘gels’. If ``driver`` is None, ‘gelsy’ is used for CPU inputs and ‘gels’ + for CUDA inputs. + name(str, optional): The default value is None. Normally there is no need for user to set + this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tuple: A tuple of 4 Tensors which is (``solution``, ``residuals``, ``rank``, ``singular_values``). + ``solution`` is a tensor with shape ``(*, N, K)``, meaning the least squares solution. ``residuals`` + is a tensor with shape ``(*, K)``, meaning the squared residuals of the solutions, which is computed + when M > N and every matrix in ``x`` is full-rank, otherwise return an empty tensor. ``rank`` is a tensor + with shape ``(*)``, meaning the ranks of the matrices in ``x``, which is computed when ``driver`` in + (‘gelsy’, ‘gelsd’, ‘gelss’), otherwise return an empty tensor. ``singular_values`` is a tensor with + shape ``(*, min(M, N))``, meaning singular values of the matrices in ``x``, which is computed when + ``driver`` in (‘gelsd’, ‘gelss’), otherwise return an empty tensor. + + Examples: + .. code-block:: python + + import paddle + + paddle.set_device("cpu") + x = paddle.to_tensor([[1, 3], [3, 2], [5, 6.]]) + y = paddle.to_tensor([[3, 4, 6], [5, 3, 4], [1, 2, 1.]]) + results = paddle.linalg.lstsq(x, y, driver="gelsd") + print(results[0]) + # [[ 0.78350395, -0.22165027, -0.62371236], + # [-0.11340097, 0.78866047, 1.14948535]] + print(results[1]) + # [19.81443405, 10.43814468, 30.56185532]) + print(results[2]) + # 2 + print(results[3]) + # [9.03455734, 1.54167950] + + x = paddle.to_tensor([[10, 2, 3], [3, 10, 5], [5, 6, 12.]]) + y = paddle.to_tensor([[4, 2, 9], [2, 0, 3], [2, 5, 3.]]) + results = paddle.linalg.lstsq(x, y, driver="gels") + print(results[0]) + # [[ 0.39386186, 0.10230173, 0.93606132], + # [ 0.10741687, -0.29028133, 0.11892585], + # [-0.05115091, 0.51918161, -0.19948854]] + print(results[1]) + # [] + """ + device = paddle.get_device() + if device == "cpu": + if driver not in (None, "gels", "gelss", "gelsd", "gelsy"): + raise ValueError( + "Only support valid driver is 'gels', 'gelss', 'gelsd', 'gelsy' or None for CPU inputs. But got {}".format( + driver + ) + ) + driver = "gelsy" if driver is None else driver + elif "gpu" in device: + if driver not in (None, "gels"): + raise ValueError( + "Only support valid driver is 'gels' or None for CUDA inputs. But got {}".format( + driver + ) + ) + driver = "gels" if driver is None else driver + else: + raise RuntimeError("Only support lstsq api for CPU or CUDA device.") + + if x.dtype == y.dtype and x.dtype in (paddle.float32, paddle.float64): + pass + else: + raise ValueError( + "Only support x and y have the same dtype such as 'float32' and 'float64'." + ) + + if rcond is None: + if x.dtype == paddle.float32: + rcond = 1e-7 * max(x.shape[-2], x.shape[-1]) + elif x.dtype == paddle.float64: + rcond = 1e-15 * max(x.shape[-2], x.shape[-1]) + + if _non_static_mode(): + if in_dygraph_mode(): + solution, residuals, rank, singular_values = _C_ops.lstsq( + x, y, rcond, driver + ) + else: + solution, residuals, rank, singular_values = _legacy_C_ops.lstsq( + x, y, 'rcond', rcond, 'driver', driver + ) + + if driver == "gels": + rank = paddle.empty(shape=[0], dtype=paddle.int32) + singular_values = paddle.empty(shape=[0], dtype=x.dtype) + elif driver == "gelsy": + singular_values = paddle.empty(shape=[0], dtype=x.dtype) + + return solution, residuals, rank, singular_values + + helper = LayerHelper('lstsq', **locals()) + check_variable_and_dtype( + x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'lstsq' + ) + check_variable_and_dtype( + y, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'lstsq' + ) + + solution = helper.create_variable_for_type_inference(dtype=x.dtype) + residuals = helper.create_variable_for_type_inference(dtype=x.dtype) + rank = helper.create_variable_for_type_inference(dtype=paddle.int32) + singular_values = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='lstsq', + inputs={'X': x, 'Y': y}, + outputs={ + 'Solution': solution, + 'Residuals': residuals, + 'Rank': rank, + 'SingularValues': singular_values, + }, + attrs={'rcond': rcond, 'driver': driver}, + ) + + if driver == "gels": + rank = paddle.static.data(name='rank', shape=[0]) + singular_values = paddle.static.data(name='singular_values', shape=[0]) + elif driver == "gelsy": + singular_values = paddle.static.data(name='singular_values', shape=[0]) + + return solution, residuals, rank, singular_values + + +def corrcoef(x, rowvar=True, name=None): + """ + + A correlation coefficient matrix indicate the correlation of each pair variables in the input matrix. + For example, for an N-dimensional samples X=[x1,x2,…xN]T, then the correlation coefficient matrix + element Rij is the correlation of xi and xj. The element Rii is the covariance of xi itself. + + The relationship between the correlation coefficient matrix `R` and the + covariance matrix `C`, is + + .. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } + + The values of `R` are between -1 and 1. + + Parameters: + + x(Tensor): A N-D(N<=2) Tensor containing multiple variables and observations. By default, each row of x represents a variable. Also see rowvar below. + rowvar(Bool, optional): If rowvar is True (default), then each row represents a variable, with observations in the columns. Default: True. + name(str, optional): Name of the output. Default is None. It's used to print debug info for developers. Details: :ref:`api_guide_Name`. + + Returns: + + The correlation coefficient matrix of the variables. + + Examples: + .. code-block:: python + + import paddle + + xt = paddle.rand((3,4)) + print(paddle.linalg.corrcoef(xt)) + + # Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[ 1. , -0.73702252, 0.66228950], + # [-0.73702258, 1. , -0.77104872], + # [ 0.66228974, -0.77104825, 1. ]]) + + """ + if len(x.shape) > 2 or len(x.shape) < 1: + raise ValueError( + "Input(x) only support N-D (1<=N<=2) tensor in corrcoef, but received " + "length of Input(input) is %s." % len(x.shape) + ) + check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'corrcoef') + + c = cov(x, rowvar) + if c.ndim == 0: + # scalar covariance + # nan if incorrect value (nan, inf, 0), 1 otherwise + return c / c + + d = paddle.diag(c) + + if paddle.is_complex(d): + d = d.real() + stddev = paddle.sqrt(d) + c /= stddev[:, None] + c /= stddev[None, :] + + # Clip to [-1, 1]. This does not guarantee + if paddle.is_complex(c): + return paddle.complex( + paddle.clip(c.real(), -1, 1), paddle.clip(c.imag(), -1, 1) + ) + else: + c = paddle.clip(c, -1, 1) + + return c diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/logic.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/logic.py new file mode 100644 index 0000000000000000000000000000000000000000..c998c198d49216b33aab9dfd911655ba1d5c9e01 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/logic.py @@ -0,0 +1,1028 @@ +# 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. + +import paddle +from ..fluid.data_feeder import check_type, check_variable_and_dtype +from .layer_function_generator import templatedoc +from ..static import Variable + +# TODO: define logic functions of a tensor +from ..fluid.framework import _in_eager_mode_ + +if _in_eager_mode_: + Tensor = paddle.fluid.framework.core.eager.Tensor +else: + from ..framework import VarBase as Tensor + +from ..framework import in_dygraph_mode, _non_static_mode +from ..framework import LayerHelper +from ..fluid.framework import _in_legacy_dygraph + +# TODO: define logic functions of a tensor +from paddle import _C_ops, _legacy_C_ops +from paddle.tensor.creation import full + +__all__ = [] + + +def _logical_op(op_name, x, y, out=None, name=None, binary_op=True): + if in_dygraph_mode(): + op = getattr(_C_ops, op_name) + if binary_op: + return op(x, y) + else: + return op(x) + elif _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, op_name) + if binary_op: + return op(x, y) + else: + return op(x) + check_variable_and_dtype( + x, + "x", + ["bool", "int8", "int16", "int32", "int64", "float32", "float64"], + op_name, + ) + if y is not None: + check_variable_and_dtype( + y, + "y", + ["bool", "int8", "int16", "int32", "int64", "float32", "float64"], + op_name, + ) + if out is not None: + check_type(out, "out", Variable, op_name) + + helper = LayerHelper(op_name, **locals()) + + if binary_op and x.dtype != y.dtype: + raise ValueError( + "(InvalidArgument) The DataType of %s Op's Variable must be consistent, but received %s and %s." + % (op_name, x.dtype, y.dtype) + ) + + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if binary_op: + helper.append_op( + type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out} + ) + else: + helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out}) + + return out + + +def logical_and(x, y, out=None, name=None): + r""" + + ``logical_and`` operator computes element-wise logical AND on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = x \&\& y + + Note: + ``paddle.logical_and`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True]) + y = paddle.to_tensor([True, False, True, False]) + res = paddle.logical_and(x, y) + print(res) # [True False True False] + """ + if in_dygraph_mode(): + return _C_ops.logical_and(x, y) + + return _logical_op( + op_name="logical_and", x=x, y=y, name=name, out=out, binary_op=True + ) + + +def logical_or(x, y, out=None, name=None): + """ + + ``logical_or`` operator computes element-wise logical OR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = x || y + + Note: + ``paddle.logical_or`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Variable`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True, False], dtype="bool").reshape([2, 1]) + y = paddle.to_tensor([True, False, True, False], dtype="bool").reshape([2, 2]) + res = paddle.logical_or(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=bool, place=Place(cpu), stop_gradient=True, + # [[True , True ], + # [True , False]]) + """ + if in_dygraph_mode(): + return _C_ops.logical_or(x, y) + return _logical_op( + op_name="logical_or", x=x, y=y, name=name, out=out, binary_op=True + ) + + +def logical_xor(x, y, out=None, name=None): + r""" + + ``logical_xor`` operator computes element-wise logical XOR on ``x`` and ``y``, and returns ``out``. ``out`` is N-dim boolean ``Tensor``. + Each element of ``out`` is calculated by + + .. math:: + + out = (x || y) \&\& !(x \&\& y) + + Note: + ``paddle.logical_xor`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + y (Tensor): the input tensor, it's data type should be one of bool, int8, int16, in32, in64, float32, float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor`` will be created to save the output. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True, False], dtype="bool").reshape([2, 1]) + y = paddle.to_tensor([True, False, True, False], dtype="bool").reshape([2, 2]) + res = paddle.logical_xor(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=bool, place=Place(cpu), stop_gradient=True, + # [[False, True ], + # [True , False]]) + """ + if in_dygraph_mode(): + return _C_ops.logical_xor(x, y) + + return _logical_op( + op_name="logical_xor", x=x, y=y, name=name, out=out, binary_op=True + ) + + +@templatedoc() +def logical_not(x, out=None, name=None): + """ + + ``logical_not`` operator computes element-wise logical NOT on ``x``, and returns ``out``. ``out`` is N-dim boolean ``Variable``. + Each element of ``out`` is calculated by + + .. math:: + + out = !x + + Args: + x(Tensor): Operand of logical_not operator. Must be a Tensor of type bool, int8, int16, in32, in64, float32, or float64. + out(Tensor): The ``Tensor`` that specifies the output of the operator, which can be any ``Tensor`` that has been created in the program. The default value is None, and a new ``Tensor` will be created to save the output. + name(str|None): The default value is None. Normally there is no need for users to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([True, False, True, False]) + res = paddle.logical_not(x) + print(res) # [False True False True] + """ + if in_dygraph_mode(): + return _C_ops.logical_not(x) + return _logical_op( + op_name="logical_not", x=x, y=None, name=name, out=out, binary_op=False + ) + + +def is_empty(x, name=None): + """ + + Test whether a Tensor is empty. + + Args: + x (Tensor): The Tensor to be tested. + name (str, optional): The default value is ``None`` . Normally users + don't have to set this parameter. For more information, + please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: A bool scalar Tensor. True if 'x' is an empty Tensor. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand(shape=[4, 32, 32], dtype='float32') + res = paddle.is_empty(x=input) + print("res:", res) + # ('res:', Tensor: eager_tmp_1 + # - place: CPUPlace + # - shape: [1] + # - layout: NCHW + # - dtype: bool + # - data: [0]) + + """ + if in_dygraph_mode(): + return _C_ops.is_empty(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.is_empty(x) + + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'is_empty' + ) + check_type(name, "name", (str, type(None)), "is_empty") + + helper = LayerHelper("is_empty", **locals()) + cond = helper.create_variable_for_type_inference(dtype='bool') + cond.stop_gradient = True + helper.append_op( + type='is_empty', inputs={'X': [x]}, outputs={'Out': [cond]} + ) + return cond + + +def equal_all(x, y, name=None): + """ + Returns the truth value of :math:`x == y`. True if two inputs have the same elements, False otherwise. + + Note: + The output has no gradient. + + Args: + x(Tensor): Tensor, data type is bool, float32, float64, int32, int64. + y(Tensor): Tensor, data type is bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: output Tensor, data type is bool, value is [False] or [True]. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 2, 3]) + z = paddle.to_tensor([1, 4, 3]) + result1 = paddle.equal_all(x, y) + print(result1) # result1 = [True ] + result2 = paddle.equal_all(x, z) + print(result2) # result2 = [False ] + """ + if in_dygraph_mode(): + return _C_ops.equal_all(x, y) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.equal_all(x, y) + + helper = LayerHelper("equal_all", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + helper.append_op( + type='equal_all', inputs={'X': [x], 'Y': [y]}, outputs={'Out': [out]} + ) + return out + + +@templatedoc() +def allclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None): + """ + ${comment} + + Args: + x(Tensor): ${input_comment}. + y(Tensor): ${other_comment}. + rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` . + atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` . + equal_nan(equalnantype, optional): ${equal_nan_comment}. + name (str, optional): Name for the operation. For more information, please + refer to :ref:`api_guide_Name`. Default: None. + + Returns: + Tensor: ${out_comment}. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([10000., 1e-07]) + y = paddle.to_tensor([10000.1, 1e-08]) + result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=False, name="ignore_nan") + # [False] + + result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=True, name="equal_nan") + # [False] + + x = paddle.to_tensor([1.0, float('nan')]) + y = paddle.to_tensor([1.0, float('nan')]) + result1 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=False, name="ignore_nan") + # [False] + + result2 = paddle.allclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=True, name="equal_nan") + # [True] + """ + + if in_dygraph_mode(): + # NOTE(dev): Pass tol as Tensor to fix precision loss problem, because + # C++ backend will cast it into float32 if passing float from python. + as_tensor = lambda x: paddle.to_tensor( + [x], dtype='float64', place='cpu' + ) + return _C_ops.allclose( + x, y, as_tensor(rtol), as_tensor(atol), equal_nan + ) + if _in_legacy_dygraph(): + return _legacy_C_ops.allclose( + x, y, 'rtol', str(rtol), 'atol', str(atol), 'equal_nan', equal_nan + ) + check_variable_and_dtype(x, "input", ['float32', 'float64'], 'allclose') + check_variable_and_dtype(y, "input", ['float32', 'float64'], 'allclose') + check_type(rtol, 'rtol', float, 'allclose') + check_type(atol, 'atol', float, 'allclose') + check_type(equal_nan, 'equal_nan', bool, 'allclose') + + helper = LayerHelper("allclose", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + + inputs = {'Input': x, 'Other': y} + outputs = {'Out': out} + attrs = {'rtol': str(rtol), 'atol': str(atol), 'equal_nan': equal_nan} + helper.append_op( + type='allclose', inputs=inputs, outputs=outputs, attrs=attrs + ) + + return out + + +@templatedoc() +def equal(x, y, name=None): + """ + + This layer returns the truth value of :math:`x == y` elementwise. + + Note: + The output has no gradient. + + Args: + x(Tensor): Tensor, data type is bool, float32, float64, int32, int64. + y(Tensor): Tensor, data type is bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: output Tensor, it's shape is the same as the input's Tensor, + and the data type is bool. The result of this op is stop_gradient. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.equal(x, y) + print(result1) # result1 = [True False False] + """ + if not isinstance(y, (int, bool, float, Variable)): + raise TypeError( + "Type of input args must be float, bool, int or Tensor, but received type {}".format( + type(y) + ) + ) + if not isinstance(y, Variable): + y = full(shape=[1], dtype=x.dtype, fill_value=y) + + if in_dygraph_mode(): + default_axis = -1 + return _C_ops.equal(x, y, default_axis) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.equal(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "equal", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "equal", + ) + helper = LayerHelper("equal", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +@templatedoc() +def greater_equal(x, y, name=None): + """ + Returns the truth value of :math:`x >= y` elementwise, which is equivalent function to the overloaded operator `>=`. + + Note: + The output has no gradient. + + Args: + x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + Returns: + Tensor: The output shape is same as input :attr:`x`. The output data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.greater_equal(x, y) + print(result1) # result1 = [True False True] + """ + if in_dygraph_mode(): + default_axis = -1 + return _C_ops.greater_equal(x, y, default_axis) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.greater_equal(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "greater_equal", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "greater_equal", + ) + helper = LayerHelper("greater_equal", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='greater_equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +@templatedoc() +def greater_than(x, y, name=None): + """ + Returns the truth value of :math:`x > y` elementwise, which is equivalent function to the overloaded operator `>`. + + Note: + The output has no gradient. + + Args: + x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + Returns: + Tensor: The output shape is same as input :attr:`x`. The output data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.greater_than(x, y) + print(result1) # result1 = [False False True] + """ + if in_dygraph_mode(): + return _C_ops.greater_than(x, y, -1) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.greater_than(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "greater_than", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "greater_than", + ) + helper = LayerHelper("greater_than", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='greater_than', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +@templatedoc() +def less_equal(x, y, name=None): + """ + Returns the truth value of :math:`x <= y` elementwise, which is equivalent function to the overloaded operator `<=`. + + Note: + The output has no gradient. + + Args: + x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output shape is same as input :attr:`x`. The output data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.less_equal(x, y) + print(result1) # result1 = [True True False] + """ + if in_dygraph_mode(): + axis = -1 + return _C_ops.less_equal(x, y, axis) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.less_equal(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "less_equal", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "less_equal", + ) + helper = LayerHelper("less_equal", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='less_equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +@templatedoc() +def less_than(x, y, name=None): + """ + Returns the truth value of :math:`x < y` elementwise, which is equivalent function to the overloaded operator `<`. + + Note: + The output has no gradient. + + Args: + x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output shape is same as input :attr:`x`. The output data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.less_than(x, y) + print(result1) # result1 = [False True False] + """ + if in_dygraph_mode(): + default_axis = -1 + return _C_ops.less_than(x, y, default_axis) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.less_than(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "less_than", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "less_than", + ) + helper = LayerHelper("less_than", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='less_than', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +@templatedoc() +def not_equal(x, y, name=None): + """ + Returns the truth value of :math:`x != y` elementwise, which is equivalent function to the overloaded operator `!=`. + + Note: + The output has no gradient. + + Args: + x(Tensor): First input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + y(Tensor): Second input to compare which is N-D tensor. The input data type should be bool, float32, float64, int32, int64. + name(str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output shape is same as input :attr:`x`. The output data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3]) + y = paddle.to_tensor([1, 3, 2]) + result1 = paddle.not_equal(x, y) + print(result1) # result1 = [False True True] + """ + if in_dygraph_mode(): + axis = -1 + return _C_ops.not_equal(x, y, axis) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.not_equal(x, y) + else: + check_variable_and_dtype( + x, + "x", + ["bool", "float32", "float64", "int32", "int64"], + "not_equal", + ) + check_variable_and_dtype( + y, + "y", + ["bool", "float32", "float64", "int32", "int64"], + "not_equal", + ) + helper = LayerHelper("not_equal", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + out.stop_gradient = True + + helper.append_op( + type='not_equal', + inputs={'X': [x], 'Y': [y]}, + outputs={'Out': [out]}, + ) + return out + + +def is_tensor(x): + """ + + Tests whether input object is a paddle.Tensor. + + Args: + x (object): Object to test. + + Returns: + A boolean value. True if ``x`` is a paddle.Tensor, otherwise False. + + Examples: + .. code-block:: python + + import paddle + + input1 = paddle.rand(shape=[2, 3, 5], dtype='float32') + check = paddle.is_tensor(input1) + print(check) #True + + input3 = [1, 4] + check = paddle.is_tensor(input3) + print(check) #False + + """ + return isinstance(x, (Tensor, paddle.fluid.core.eager.Tensor)) + + +def _bitwise_op(op_name, x, y, out=None, name=None, binary_op=True): + if in_dygraph_mode(): + op = getattr(_C_ops, op_name) + if binary_op: + return op(x, y) + else: + return op(x) + elif _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, op_name) + if binary_op: + return op(x, y) + else: + return op(x) + + check_variable_and_dtype( + x, "x", ["bool", "uint8", "int8", "int16", "int32", "int64"], op_name + ) + if y is not None: + check_variable_and_dtype( + y, + "y", + ["bool", "uint8", "int8", "int16", "int32", "int64"], + op_name, + ) + if out is not None: + check_type(out, "out", Variable, op_name) + + helper = LayerHelper(op_name, **locals()) + if binary_op: + assert x.dtype == y.dtype + + if out is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + if binary_op: + helper.append_op( + type=op_name, inputs={"X": x, "Y": y}, outputs={"Out": out} + ) + else: + helper.append_op(type=op_name, inputs={"X": x}, outputs={"Out": out}) + + return out + + +@templatedoc() +def bitwise_and(x, y, out=None, name=None): + """ + ${comment} + + Args: + x (Tensor): ${x_comment} + y (Tensor): ${y_comment} + out(Tensor): ${out_comment} + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([-5, -1, 1]) + y = paddle.to_tensor([4, 2, -3]) + res = paddle.bitwise_and(x, y) + print(res) # [0, 2, 1] + """ + if in_dygraph_mode() and out is None: + return _C_ops.bitwise_and(x, y) + return _bitwise_op( + op_name="bitwise_and", x=x, y=y, name=name, out=out, binary_op=True + ) + + +@templatedoc() +def bitwise_or(x, y, out=None, name=None): + """ + ${comment} + + Args: + x (Tensor): ${x_comment} + y (Tensor): ${y_comment} + out(Tensor): ${out_comment} + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([-5, -1, 1]) + y = paddle.to_tensor([4, 2, -3]) + res = paddle.bitwise_or(x, y) + print(res) # [-1, -1, -3] + """ + if in_dygraph_mode() and out is None: + return _C_ops.bitwise_or(x, y) + + return _bitwise_op( + op_name="bitwise_or", x=x, y=y, name=name, out=out, binary_op=True + ) + + +@templatedoc() +def bitwise_xor(x, y, out=None, name=None): + """ + ${comment} + + Args: + x (Tensor): ${x_comment} + y (Tensor): ${y_comment} + out(Tensor): ${out_comment} + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([-5, -1, 1]) + y = paddle.to_tensor([4, 2, -3]) + res = paddle.bitwise_xor(x, y) + print(res) # [-1, -3, -4] + """ + if in_dygraph_mode() and out is None: + return _C_ops.bitwise_xor(x, y) + return _bitwise_op( + op_name="bitwise_xor", x=x, y=y, name=name, out=out, binary_op=True + ) + + +@templatedoc() +def bitwise_not(x, out=None, name=None): + """ + ${comment} + + Args: + x(Tensor): ${x_comment} + out(Tensor): ${out_comment} + + Returns: + Tensor: ${out_comment} + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([-5, -1, 1]) + res = paddle.bitwise_not(x) + print(res) # [4, 0, -2] + """ + if in_dygraph_mode() and out is None: + return _C_ops.bitwise_not(x) + + return _bitwise_op( + op_name="bitwise_not", x=x, y=None, name=name, out=out, binary_op=False + ) + + +@templatedoc() +def isclose(x, y, rtol=1e-05, atol=1e-08, equal_nan=False, name=None): + """ + ${comment} + + Args: + x(Tensor): ${input_comment}. + y(Tensor): ${other_comment}. + rtol(rtoltype, optional): The relative tolerance. Default: :math:`1e-5` . + atol(atoltype, optional): The absolute tolerance. Default: :math:`1e-8` . + equal_nan(equalnantype, optional): ${equal_nan_comment}. + name (str, optional): Name for the operation. For more information, please + refer to :ref:`api_guide_Name`. Default: None. + + Returns: + Tensor: ${out_comment}. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([10000., 1e-07]) + y = paddle.to_tensor([10000.1, 1e-08]) + result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=False, name="ignore_nan") + # [True, False] + result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=True, name="equal_nan") + # [True, False] + + x = paddle.to_tensor([1.0, float('nan')]) + y = paddle.to_tensor([1.0, float('nan')]) + result1 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=False, name="ignore_nan") + # [True, False] + result2 = paddle.isclose(x, y, rtol=1e-05, atol=1e-08, + equal_nan=True, name="equal_nan") + # [True, True] + """ + + if in_dygraph_mode(): + # NOTE(dev): Pass tol as Tensor to fix precision loss problem, because + # C++ backend will cast it into float32 if passing float from python. + as_tensor = lambda x: paddle.to_tensor( + [x], dtype='float64', place='cpu' + ) + return _C_ops.isclose(x, y, as_tensor(rtol), as_tensor(atol), equal_nan) + if _in_legacy_dygraph(): + return _legacy_C_ops.isclose( + x, y, 'rtol', str(rtol), 'atol', str(atol), 'equal_nan', equal_nan + ) + + check_variable_and_dtype(x, "input", ['float32', 'float64'], 'isclose') + check_variable_and_dtype(y, "input", ['float32', 'float64'], 'isclose') + check_type(rtol, 'rtol', float, 'isclose') + check_type(atol, 'atol', float, 'isclose') + check_type(equal_nan, 'equal_nan', bool, 'isclose') + + helper = LayerHelper("isclose", **locals()) + out = helper.create_variable_for_type_inference(dtype='bool') + + inputs = {'Input': x, 'Other': y} + outputs = {'Out': out} + attrs = {'rtol': str(rtol), 'atol': str(atol), 'equal_nan': equal_nan} + helper.append_op( + type='isclose', inputs=inputs, outputs=outputs, attrs=attrs + ) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/manipulation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/manipulation.py new file mode 100644 index 0000000000000000000000000000000000000000..f987e8b89cf2549996cdcf09f374808086dc4224 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/manipulation.py @@ -0,0 +1,4852 @@ +# 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. + +from __future__ import print_function +from collections import Counter + +from ..static import Variable, device_guard +from ..framework import core, in_dygraph_mode +from ..fluid.framework import ( + _in_legacy_dygraph, + _in_eager_without_dygraph_check, + _non_static_mode, +) +from ..framework import LayerHelper +from ..framework import OpProtoHolder, convert_np_dtype_to_dtype_, dygraph_only +from ..fluid.data_feeder import ( + convert_dtype, + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..fluid.layers import utils +import numpy as np + +# TODO: define functions to manipulate a tensor +from ..fluid.layers.nn import _elementwise_op_in_dygraph +from ..fluid.dygraph.inplace_utils import inplace_apis_in_dygraph_only +import paddle +from paddle import _C_ops, _legacy_C_ops +from ..common_ops_import import dygraph_utils, fill_constant, _varbase_creator +import warnings +from .creation import zeros +from .creation import _complex_to_real_dtype +from .creation import _real_to_complex_dtype + +__all__ = [] + + +def cast(x, dtype): + """ + + This OP takes in the Tensor :attr:`x` with :attr:`x.dtype` and casts it + to the output with :attr:`dtype`. It's meaningless if the output dtype + equals the input dtype, but it's fine if you do so. + + Args: + x (Tensor): An input N-D Tensor with data type bool, float16, + float32, float64, int32, int64, uint8. + dtype (np.dtype|str): Data type of the output: + bool, float16, float32, float64, int8, int32, int64, uint8. + + Returns: + Tensor: A Tensor with the same shape as input's. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 4], 'float64') + y = paddle.cast(x, 'uint8') + """ + if in_dygraph_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + return _C_ops.cast(x, dtype) + + if _non_static_mode(): + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + out = _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int16', + 'int32', + 'int64', + 'uint8', + 'uint16', + ], + 'cast', + ) + check_dtype( + dtype, + 'dtype', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int8', + 'int16', + 'int32', + 'int64', + 'uint8', + 'uint16', + ], + 'cast', + ) + + helper = LayerHelper('cast', **locals()) + out = helper.create_variable_for_type_inference( + dtype=dtype, stop_gradient=x.stop_gradient + ) + helper.append_op( + type='cast', + inputs={'X': [x]}, + outputs={'Out': [out]}, + attrs={'in_dtype': x.dtype, 'out_dtype': out.dtype}, + ) + return out + + +def slice(input, axes, starts, ends): + """ + This operator produces a slice of ``input`` along multiple axes. Similar to numpy: + https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html + Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and + end dimension for each axis in the list of axes and Slice uses this information + to slice the input data tensor. If a negative value is passed to + ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the + axis :math:`i-1` (here 0 is the initial position). + If the value passed to ``starts`` or ``ends`` is greater than n + (the number of elements in this dimension), it represents n. + For slicing to the end of a dimension with unknown size, it is recommended + to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` and ``ends``. + Following examples will explain how slice works: + + .. code-block:: text + + Case1: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [1, 0] + ends = [2, 3] + Then: + result = [ [5, 6, 7], ] + + Case2: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [-1, 1000] # -1 denotes the reverse 0th position of dimension 0. + Then: + result = [ [2, 3, 4], ] # result = data[0:1, 1:4] + + Args: + input (Tensor): A ``Tensor`` . The data type is ``float16``, ``float32``, ``float64``, ``int32`` or ``int64``. + axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to . + starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``starts`` is an Tensor, it should be an 1-D Tensor. + It represents starting indices of corresponding axis in ``axes``. + ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``ends`` is an Tensor, it should be an 1-D Tensor . + It represents ending indices of corresponding axis in ``axes``. + + Returns: + Tensor: A ``Tensor``. The data type is same as ``input``. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand(shape=[4, 5, 6], dtype='float32') + # example 1: + # attr starts is a list which doesn't contain tensor. + axes = [0, 1, 2] + starts = [-3, 0, 2] + ends = [3, 2, 4] + sliced_1 = paddle.slice(input, axes=axes, starts=starts, ends=ends) + # sliced_1 is input[0:3, 0:2, 2:4]. + + # example 2: + # attr starts is a list which contain tensor. + minus_3 = paddle.full([1], -3, "int32") + sliced_2 = paddle.slice(input, axes=axes, starts=[minus_3, 0, 2], ends=ends) + # sliced_2 is input[0:3, 0:2, 2:4]. + """ + if in_dygraph_mode(): + attrs = () + starts_tensor = None + ends_tensor = None + + if isinstance(axes, (list, tuple)): + axes = list(axes) + if len(axes) == 0: + raise ValueError( + "Input axes should not be an empty list/tuple." + ) + for i in range(len(axes)): + if axes[i] < 0: + axes[i] = max(0, axes[i] + len(input.shape)) + else: + axes[i] = min(len(input.shape) - 1, axes[i]) + + else: + raise ValueError( + "Input axes must be a python list or tuple, but reveived {}".format( + type(axes) + ) + ) + + infer_flags = list(1 for i in range(len(axes))) + + tmp_tensor_type = core.eager.Tensor + + if isinstance(starts, (list, tuple)): + starts = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in starts + ] + elif isinstance(starts, tmp_tensor_type): + tensor_t = starts.numpy() + starts = [ele for ele in tensor_t] + infer_flags = list(-1 for i in range(len(axes))) + + if isinstance(ends, (list, tuple)): + ends = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in ends + ] + elif isinstance(ends, tmp_tensor_type): + tensor_t = ends.numpy() + ends = [ele for ele in tensor_t] + infer_flags = list(-1 for i in range(len(axes))) + + return _C_ops.slice(input, axes, starts, ends, infer_flags, []) + else: + if _in_legacy_dygraph(): + attrs = () + starts_tensor = None + ends_tensor = None + + if isinstance(axes, (list, tuple)): + axes = list(axes) + if len(axes) == 0: + raise ValueError( + "Input axes should not be an empty list/tuple." + ) + for i in range(len(axes)): + if axes[i] < 0: + axes[i] = max(0, axes[i] + len(input.shape)) + else: + axes[i] = min(len(input.shape) - 1, axes[i]) + + else: + raise ValueError( + "Input axes must be a python list or tuple, but reveived {}".format( + type(axes) + ) + ) + + infer_flags = list(1 for i in range(len(axes))) + + tmp_tensor_type = Variable + + if isinstance(starts, (list, tuple)): + starts = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in starts + ] + attrs += ('starts', starts) + elif isinstance(starts, tmp_tensor_type): + starts_tensor = starts + starts.stop_gradient = True + infer_flags = list(-1 for i in range(len(axes))) + + if isinstance(ends, (list, tuple)): + ends = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in ends + ] + attrs += ('ends', ends) + elif isinstance(ends, tmp_tensor_type): + ends_tensor = ends + ends_tensor.stop_gradient = True + infer_flags = list(-1 for i in range(len(axes))) + + return _legacy_C_ops.slice( + input, + starts_tensor, + ends_tensor, + None, + None, + 'axes', + axes, + 'infer_flags', + infer_flags, + *attrs, + ) + + if not isinstance(starts, (list, tuple, Variable)): + raise ValueError( + "Input starts must be an Variable, python list or tuple." + ) + if not isinstance(ends, (list, tuple, Variable)): + raise ValueError( + "Input ends must be an Variable, python list or tuple." + ) + + helper = LayerHelper('slice', **locals()) + + inputs = {'Input': input} + attrs = {'axes': axes} + infer_flags = list(1 for i in range(len(axes))) + + # starts + if isinstance(starts, Variable): + starts.stop_gradient = True + inputs['StartsTensor'] = starts + infer_flags = list(-1 for i in range(len(axes))) + elif isinstance(starts, (list, tuple)): + attrs['starts'] = [] + if utils._contain_var(starts): + inputs['StartsTensorList'] = utils._convert_to_tensor_list(starts) + for i, dim in enumerate(starts): + if isinstance(dim, Variable): + attrs['starts'].append(-1) + infer_flags[i] = -1 + else: + attrs['starts'].append(dim) + else: + attrs['starts'] = starts + + # ends + if isinstance(ends, Variable): + ends.stop_gradient = True + inputs['EndsTensor'] = ends + infer_flags = list(-1 for i in range(len(axes))) + elif isinstance(ends, (list, tuple)): + attrs['ends'] = [] + if utils._contain_var(ends): + inputs['EndsTensorList'] = utils._convert_to_tensor_list(ends) + for i, dim in enumerate(ends): + if isinstance(dim, Variable): + attrs['ends'].append(-1) + infer_flags[i] = -1 + else: + attrs['ends'].append(dim) + else: + attrs['ends'] = ends + + # infer_flags + attrs['infer_flags'] = infer_flags + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('input') + ) + helper.append_op( + type='slice', inputs=inputs, attrs=attrs, outputs={'Out': out} + ) + + return out + + +def transpose(x, perm, name=None): + """ + Permute the data dimensions of `input` according to `perm`. + + The `i`-th dimension of the returned tensor will correspond to the + perm[i]-th dimension of `input`. + + Args: + x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, float32, float64, int32. + perm (list|tuple): Permute the input according to the data of perm. + name (str): The name of this layer. It is optional. + + Returns: + Tensor: A transposed n-D Tensor, with data type being bool, float32, float64, int32, int64. + + For Example: + + .. code-block:: text + + x = [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] + [[13 14 15 16] [17 18 19 20] [21 22 23 24]]] + shape(x) = [2,3,4] + + # Example 1 + perm0 = [1,0,2] + y_perm0 = [[[ 1 2 3 4] [13 14 15 16]] + [[ 5 6 7 8] [17 18 19 20]] + [[ 9 10 11 12] [21 22 23 24]]] + shape(y_perm0) = [3,2,4] + + # Example 2 + perm1 = [2,1,0] + y_perm1 = [[[ 1 13] [ 5 17] [ 9 21]] + [[ 2 14] [ 6 18] [10 22]] + [[ 3 15] [ 7 19] [11 23]] + [[ 4 16] [ 8 20] [12 24]]] + shape(y_perm1) = [4,3,2] + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn([2, 3, 4]) + x_transposed = paddle.transpose(x, perm=[1, 0, 2]) + print(x_transposed.shape) + # [3L, 2L, 4L] + + """ + if in_dygraph_mode(): + return _C_ops.transpose(x, perm) + else: + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.transpose2(x, 'axis', perm) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'transpose', + ) + check_type(perm, 'perm', (list, tuple), 'transpose') + if isinstance(perm, tuple): + perm = list(perm) + if len(perm) != len(x.shape): + raise ValueError( + "Input(perm) is the permutation of dimensions of Input(x), " + "its length should be equal to dimensions of Input(x), " + "but received dimension of Input(x) is %s, " + "the length of Input(perm) is %s." % (len(x.shape), len(perm)) + ) + for idx, dim in enumerate(perm): + if dim >= len(x.shape): + raise ValueError( + "Each element in Input(perm) should be less than Input(x)'s dimension, " + "but %d-th element in Input(perm) is %d which exceeds Input(x)'s " + "dimension %d." % (idx, perm[idx], len(x.shape)) + ) + + helper = LayerHelper('transpose', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='transpose2', + inputs={'X': [x]}, + outputs={'Out': [out], 'XShape': [x_shape]}, + attrs={'axis': perm}, + ) + return out + + +def unstack(x, axis=0, num=None): + """ + :alias_main: paddle.unstack + :alias: paddle.unstack,paddle.tensor.unstack,paddle.tensor.manipulation.unstack + :old_api: paddle.fluid.layers.unstack + + **UnStack Layer** + + This layer unstacks input Tensor :code:`x` into several Tensors along :code:`axis`. + + If :code:`axis` < 0, it would be replaced with :code:`axis+rank(x)`. + If :code:`num` is None, it would be inferred from :code:`x.shape[axis]`, + and if :code:`x.shape[axis]` <= 0 or is unknown, :code:`ValueError` is + raised. + + Args: + x (Tensor): Input Tensor. It is a N-D Tensors of data types float32, float64, int32, int64. + axis (int): The axis along which the input is unstacked. + num (int|None): The number of output variables. + + Returns: + list(Tensor): The unstacked Tensors list. The list elements are N-D Tensors of data types float32, float64, int32, int64. + + Examples: + .. code-block:: python + + import paddle + x = paddle.ones(name='x', shape=[2, 3, 5], dtype='float32') # create a tensor with shape=[2, 3, 5] + y = paddle.unstack(x, axis=1) # unstack with second axis, which results 3 tensors with shape=[2, 5] + + """ + if in_dygraph_mode(): + if num == None: + num = x.shape[axis] + if num == 0: + return [] + return _C_ops.unstack(x, axis, num) + + if _non_static_mode(): + if num == None: + num = x.shape[axis] + if num == 0: + return [] + return _legacy_C_ops.unstack(x, num, 'axis', int(axis), 'num', num) + + helper = LayerHelper('unstack', **locals()) + if num is None: + if axis is None or x.shape[axis] <= 0: + raise ValueError('unknown unstack number') + else: + num = x.shape[axis] + + outs = [] + for _ in range(num): + outs.append(helper.create_variable_for_type_inference(x.dtype)) + + helper.append_op( + type='unstack', + inputs={'X': [x]}, + outputs={'Y': outs}, + attrs={'axis': axis, 'num': num}, + ) + return outs + + +def shard_index(input, index_num, nshards, shard_id, ignore_value=-1): + """ + Reset the values of `input` according to the shard it beloning to. + Every value in `input` must be a non-negative integer, and + the parameter `index_num` represents the integer above the maximum + value of `input`. Thus, all values in `input` must be in the range + [0, index_num) and each value can be regarded as the offset to the beginning + of the range. The range is further split into multiple shards. Specifically, + we first compute the `shard_size` according to the following formula, + which represents the number of integers each shard can hold. So for the + i'th shard, it can hold values in the range [i*shard_size, (i+1)*shard_size). + :: + + shard_size = (index_num + nshards - 1) // nshards + + For each value `v` in `input`, we reset it to a new value according to the + following formula: + :: + + v = v - shard_id * shard_size if shard_id * shard_size <= v < (shard_id+1) * shard_size else ignore_value + + That is, the value `v` is set to the new offset within the range represented by the shard `shard_id` + if it in the range. Otherwise, we reset it to be `ignore_value`. + + Args: + input (Tensor): Input tensor with data type int64 or int32. It's last dimension must be 1. + index_num (int): An integer represents the integer above the maximum value of `input`. + nshards (int): The number of shards. + shard_id (int): The index of the current shard. + ignore_value (int): An integer value out of sharded index range. + + Returns: + Tensor. + + Examples: + .. code-block:: python + + import paddle + label = paddle.to_tensor([[16], [1]], "int64") + shard_label = paddle.shard_index(input=label, + index_num=20, + nshards=2, + shard_id=0) + print(shard_label) + # [[-1], [1]] + """ + if in_dygraph_mode(): + return _C_ops.shard_index( + input, index_num, nshards, shard_id, ignore_value + ) + + check_variable_and_dtype(input, 'input', ['int64', 'int32'], 'shard_index') + op_type = 'shard_index' + helper = LayerHelper(op_type, **locals()) + if shard_id < 0 or shard_id >= nshards: + raise ValueError( + 'The shard_id(%d) should be in [0, %d)' % (shard_id, nshards) + ) + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type=op_type, + inputs={'X': [input]}, + outputs={'Out': out}, + attrs={ + 'index_num': index_num, + 'nshards': nshards, + 'shard_id': shard_id, + 'ignore_value': ignore_value, + }, + stop_gradient=True, + ) + return out + + +def crop(x, shape=None, offsets=None, name=None): + """ + Crop input into output, as specified by offsets and shape. + + .. code-block:: text + + * Case 1 (input is a 2-D Tensor): + Input: + X.shape = [3, 5] + X.data = [[0, 1, 2, 0, 0], + [0, 3, 4, 0, 0], + [0, 0, 0, 0, 0]] + Parameters: + shape = [2, 2] + offsets = [0, 1] + Output: + Out.shape = [2, 2] + Out.data = [[1, 2], + [3, 4]] + * Case 2 (input is a 3-D Tensor): + Input: + 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]]] + Parameters: + shape = [2, 2, -1] + offsets = [0, 0, 1] + Output: + Out.shape = [2, 2, 3] + Out.data = [[[1, 2, 3], + [5, 6, 7]], + [[3, 4, 5], + [6, 7, 8]]] + + Parameters: + x (Tensor): 1-D to 6-D Tensor, the data type is float32, float64, int32 or int64. + shape (list|tuple|Tensor, optional): The output shape is specified + by `shape`. Its data type is int32. If a list/tuple, it's length must be + the same as the dimension size of `x`. If a Tensor, it should be a 1-D Tensor. + When it is a list, each element can be an integer or a Tensor of shape: [1]. + If Variable contained, it is suitable for the case that the shape may + be changed each iteration. + offsets (list|tuple|Variable, optional): Specifies the cropping + offsets at each dimension. Its data type is int32. If a list/tuple, it's length + must be the same as the dimension size of `x`. If a Tensor, it should be a 1-D + Tensor. When it is a list, each element can be an integer or a Tensor of shape: [1]. + If Variable contained, it is suitable for the case that the offsets may be changed + each iteration. Default: None, the offsets are 0 at each dimension. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The cropped Tensor has same data type with `x`. + + Examples: + + .. code-block:: python + + import paddle + x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + # x.shape = [3, 3] + # x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + + # shape can be a 1-D Tensor or list or tuple. + shape = paddle.to_tensor([2, 2], dtype='int32') + # shape = [2, 2] + # shape = (2, 2) + out = paddle.crop(x, shape) + # out.shape = [2, 2] + # out = [[1,2], [4,5]] + + # offsets can be a 1-D Tensor or list or tuple. + offsets = paddle.to_tensor([0, 1], dtype='int32') + # offsets = [1, 0] + # offsets = (1, 1) + out = paddle.crop(x, shape, offsets) + # out.shape = [2, 2] + # if offsets = [0, 0], out = [[1,2], [4,5]] + # if offsets = [0, 1], out = [[2,3], [5,6]] + # if offsets = [1, 0], out = [[4,5], [7,8]] + # if offsets = [1, 1], out = [[5,6], [8,9]] + + """ + + helper = LayerHelper('crop_tensor', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'crop_tensor' + ) + check_type(shape, 'shape', (list, tuple, Variable), 'crop_tensor') + check_type( + offsets, 'offsets', (list, tuple, Variable, type(None)), 'crop_tensor' + ) + + if offsets is None: + offsets = [0] * len(x.shape) + + if in_dygraph_mode(): + return _C_ops.crop_tensor(x, shape, offsets) + + out = helper.create_variable_for_type_inference(x.dtype) + ipts = {'X': x} + attrs = {} + + def _attr_shape_check(shape_val): + if not isinstance(shape_val, int): + raise TypeError( + "Attr(shape)'s dtype of Op(crop_tensor) should be int32, but received: %s." + % type(shape_val) + ) + if shape_val == 0: + raise ValueError( + "Attr(shape) of Op(crop_tensor) should not be zero, but received: %s." + % str(shape_val) + ) + if shape_val < -1: + raise ValueError( + "When the element in Attr(shape) of Op(crop_tensor) is negative, only -1 is supported, but received: %s." + % str(shape_val) + ) + + def _attr_offsets_check(offset_val): + if not isinstance(offset_val, int): + raise TypeError( + "Attr(offsets)'s dtype of Op(crop_tensor) should be int32, but received: %s." + % type(offset_val) + ) + if offset_val < 0: + raise ValueError( + "Attr(offsets) of Op(crop_tensor) should be greater or equal to zero, but received: %s." + % str(offset_val) + ) + + if isinstance(offsets, Variable): + offsets.stop_gradient = True + ipts['Offsets'] = offsets + attrs['offsets'] = [-1] * len(x.shape) + elif utils._contain_var(offsets): + new_offsets_tensor = [] + offsets_attr = [] + for dim in offsets: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_offsets_tensor.append(dim) + offsets_attr.append(-1) + else: + _attr_offsets_check(dim) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) + new_offsets_tensor.append(temp_out) + offsets_attr.append(dim) + ipts['OffsetsTensor'] = new_offsets_tensor + attrs['offsets'] = offsets_attr + else: + for offset in offsets: + _attr_offsets_check(offset) + attrs['offsets'] = offsets + + if isinstance(shape, Variable): + shape.stop_gradient = True + ipts['Shape'] = shape + elif utils._contain_var(shape): + new_shape_tensor = [] + shape_attr = [] + for dim_size in shape: + if isinstance(dim_size, Variable): + dim_size.stop_gradient = True + new_shape_tensor.append(dim_size) + shape_attr.append(0) + else: + _attr_shape_check(dim_size) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant( + [1], 'int32', dim_size, force_cpu=True, out=temp_out + ) + new_shape_tensor.append(temp_out) + shape_attr.append(dim_size) + ipts['ShapeTensor'] = new_shape_tensor + attrs['shape'] = shape_attr + else: + for dim_size in shape: + _attr_shape_check(dim_size) + attrs['shape'] = shape + + helper.append_op( + type='crop_tensor', + inputs=ipts, + outputs={'Out': out}, + attrs=None if len(attrs) == 0 else attrs, + ) + return out + + +@dygraph_only +def fill_(x, value): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + This function fill the Tensor with value inplace. + + Args: + x (Tensor): ``x`` is the Tensor we want to filled data inplace + value (Scale): ``value`` is the value to be filled in x + + Returns: + x(Tensor): Tensor x filled with value inplace + + Examples: + .. code-block:: python + + import paddle + + tensor = paddle.to_tensor([0, 1, 2, 3, 4]) + + tensor.fill_(0) + print(tensor.tolist()) #[0, 0, 0, 0, 0] + + """ + if not isinstance(value, (float, int)): + raise TypeError( + "The type of 'value' must be int or float, but received %s." + % (type(value)) + ) + if in_dygraph_mode(): + return _C_ops.fill_(x, value) + else: + return _legacy_C_ops.fill_any_( + x, "value_float", float(value), "value_int", int(value) + ) + + +@dygraph_only +def zero_(x): + """ + **Notes**: + **This API is ONLY available in Dygraph mode** + + This function fill the Tensor with zero inplace. + + Args: + x (Tensor): ``x`` is the Tensor we want to filled with zero inplace + + Returns: + x (Tensor): Tensor x filled with zero inplace + + Examples: + .. code-block:: python + + import paddle + + tensor = paddle.to_tensor([0, 1, 2, 3, 4]) + + tensor.zero_() + print(tensor.tolist()) #[0, 0, 0, 0, 0] + + """ + if in_dygraph_mode(): + return _C_ops.fill_(x, 0.0) + else: + return _legacy_C_ops.fill_any_( + x, "value_float", 0.0, "value_int", int(0) + ) + + +@dygraph_only +def fill_diagonal_(x, value, offset=0, wrap=False, name=None): + """ + Note: + This API is ONLY available in Dygraph mode. + + This function fill the value into the x Tensor's diagonal inplace. + + Args: + x(Tensor): ``x`` is the original Tensor + value(Scale): ``value`` is the value to filled in x + offset(int,optional): the offset to the main diagonal. Default: 0 (main diagonal). + wrap(bool,optional): the diagonal 'wrapped' after N columns for tall matrices. + name(str,optional): Name for the operation (optional, default is None) + + Returns: + Tensor: Tensor with diagonal filled with value. + + Examples: + .. code-block:: python + import paddle + x = paddle.ones((4, 3)) * 2 + x.fill_diagonal_(1.0) + print(x.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]] + """ + + helper = LayerHelper("fill_diagonal_", **locals()) + check_type(x, 'X', (Variable), 'fill_diagonal_') + dtype = helper.input_dtype('x') + check_dtype( + dtype, + 'X', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'fill_diagonal_', + ) + check_type(value, 'value', (bool, int, float), 'fill_diagonal_') + check_type(wrap, 'wrap', (bool), 'fill_diagonal_') + + inshape = x.shape + inshapeset = set(inshape) + assert len(inshape) >= 2, 'Tensor dims should >= 2 in fill_diagonal_ API' + if len(inshape) > 2: + assert ( + len(inshapeset) == 1 + ), 'Tensor dims should be equal while input dims > 2 in fill_diagonal_ API' + if in_dygraph_mode(): + if len(inshape) == 2: + return _C_ops.fill_diagonal_(x, value, offset, wrap) + return _C_ops.fill_diagonal_(x, value, offset, True) + + if len(inshape) == 2: + return _legacy_C_ops.fill_diagonal_( + x, 'value', value, 'offset', offset, 'wrap', wrap + ) + return _legacy_C_ops.fill_diagonal_( + x, 'value', value, 'offset', offset, 'wrap', True + ) + + +def _fill_diagonal_tensor_impl(x, y, offset=0, dim1=0, dim2=1, inplace=False): + inshape = x.shape + assert dim1 < len(inshape) and dim1 >= -len( + inshape + ), 'dim1 should between [-rank,rank) in fill_diagonal_tensor_' + assert dim2 < len(inshape) and dim2 >= -len( + inshape + ), 'dim2 should between [-rank,rank) in fill_diagonal_tensor_' + assert len(inshape) >= 2, 'Tensor dims should >= 2 in fill_diagonal_tensor_' + dim1 %= len(inshape) + dim2 %= len(inshape) + + predshape = [] + for i in range(len(inshape)): + if i != dim1 and i != dim2: + predshape.append(inshape[i]) + diaglen = min( + min(inshape[dim1], inshape[dim1] + offset), + min(inshape[dim2], inshape[dim2] - offset), + ) + predshape.append(diaglen) + assert tuple(predshape) == tuple( + y.shape + ), "the y shape should be {}".format(predshape) + if len(y.shape) == 1: + y = y.reshape([1, -1]) + + if inplace: + if in_dygraph_mode(): + return _C_ops.fill_diagonal_tensor_(x, y, offset, dim1, dim2) + else: + return _legacy_C_ops.fill_diagonal_tensor_( + x, y, 'offset', offset, 'dim1', dim1, 'dim2', dim2 + ) + if in_dygraph_mode(): + return _C_ops.fill_diagonal_tensor(x, y, offset, dim1, dim2) + else: + return _legacy_C_ops.fill_diagonal_tensor( + x, y, 'offset', offset, 'dim1', dim1, 'dim2', dim2 + ) + + +def fill_diagonal_tensor_(x, y, offset=0, dim1=0, dim2=1, name=None): + """ + Note: + This API is ONLY available in Dygraph mode. + + This function fill the source Tensor y into the x Tensor's diagonal inplace. + + Args: + x (Tensor): ``x`` is the original Tensor + y (Tensor): ``y`` is the Tensor to filled in x + dim1 (int,optional): first dimension with respect to which to fill diagonal. Default: 0. + dim2 (int,optional): second dimension with respect to which to fill diagonal. Default: 1. + offset (int,optional): the offset to the main diagonal. Default: 0 (main diagonal). + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Tensor with diagonal filled with y. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.ones((4, 3)) * 2 + y = paddle.ones((3,)) + x.fill_diagonal_tensor_(y) + print(x.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]] + + """ + return _fill_diagonal_tensor_impl( + x, y, offset=offset, dim1=dim1, dim2=dim2, inplace=True + ) + + +def fill_diagonal_tensor(x, y, offset=0, dim1=0, dim2=1, name=None): + """ + This function fill the source Tensor y into the x Tensor's diagonal. + + Args: + x (Tensor): ``x`` is the original Tensor + y (Tensor): ``y`` is the Tensor to filled in x + dim1 (int,optional): first dimension with respect to which to fill diagonal. Default: 0. + dim2 (int,optional): second dimension with respect to which to fill diagonal. Default: 1. + offset (int,optional): the offset to the main diagonal. Default: 0 (main diagonal). + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Tensor with diagonal filled with y. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.ones((4, 3)) * 2 + y = paddle.ones((3,)) + nx = x.fill_diagonal_tensor(y) + print(nx.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]] + + """ + return _fill_diagonal_tensor_impl( + x, y, offset=offset, dim1=dim1, dim2=dim2, inplace=False + ) + + +@dygraph_only +def tolist(x): + """ + Note: + This API is ONLY available in Dygraph mode. + + This function translate the paddle.Tensor to python list. + + Args: + x (Tensor): ``x`` is the Tensor we want to translate to list. + + Returns: + list: A list that contain the same value of current Tensor. + + + Examples: + .. code-block:: python + + import paddle + + t = paddle.to_tensor([0,1,2,3,4]) + expectlist = t.tolist() + print(expectlist) #[0, 1, 2, 3, 4] + + expectlist = paddle.tolist(t) + print(expectlist) #[0, 1, 2, 3, 4] + + """ + return x.numpy().tolist() + + +def concat(x, axis=0, name=None): + """ + + Concatenates the input along the axis. + + Args: + x (list|tuple): ``x`` is a Tensor list or Tensor tuple which is with data type bool, float16, + float32, float64, int32, int64, int8, uint8. All the Tensors in ``x`` must have same data type. + axis (int|Tensor, optional): Specify the axis to operate on the input Tensors. + It's a scalar with data type int or a Tensor with shape [1] and data type int32 + or int64. The effective range is [-R, R), where R is Rank(x). When ``axis < 0``, + it works the same way as ``axis+R``. Default is 0. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor with the same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor([[1, 2, 3], + [4, 5, 6]]) + x2 = paddle.to_tensor([[11, 12, 13], + [14, 15, 16]]) + x3 = paddle.to_tensor([[21, 22], + [23, 24]]) + zero = paddle.full(shape=[1], dtype='int32', fill_value=0) + # When the axis is negative, the real axis is (axis + Rank(x)) + # As follow, axis is -1, Rank(x) is 2, the real axis is 1 + out1 = paddle.concat(x=[x1, x2, x3], axis=-1) + out2 = paddle.concat(x=[x1, x2], axis=0) + out3 = paddle.concat(x=[x1, x2], axis=zero) + # out1 + # [[ 1 2 3 11 12 13 21 22] + # [ 4 5 6 14 15 16 23 24]] + # out2 out3 + # [[ 1 2 3] + # [ 4 5 6] + # [11 12 13] + # [14 15 16]] + """ + input = x + if in_dygraph_mode(): + if isinstance(axis, Variable): + axis = axis.numpy() + axis = axis.item(0) + if not isinstance(input, Variable): + input = [t for t in input if t.shape.count(0) == 0] + return _C_ops.concat(input, axis) + + if _in_legacy_dygraph(): + if isinstance(axis, Variable): + axis = axis.numpy() + axis = axis.item(0) + if not isinstance(input, Variable): + input = [t for t in input if t.shape.count(0) == 0] + out = _varbase_creator() + _legacy_C_ops.concat(input, out, 'axis', axis) + return out + + check_type(input, 'input', (list, tuple, Variable), 'concat') + if not isinstance(input, Variable): + for id, x in enumerate(input): + check_variable_and_dtype( + x, + 'input[' + str(id) + ']', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'int8', + 'unit8', + ], + 'concat', + ) + if x.dtype != input[0].dtype: + raise TypeError( + "All the Tensors in the input must have the same data type." + ) + else: + input = [input] + check_type(axis, 'axis', (int, Variable), 'concat') + + if isinstance(axis, Variable): + check_dtype( + axis.dtype, + 'axis', + ['int32', 'int64'], + 'concat', + "The data type of axis must be int32 or int64 when axis is a Tensor", + ) + + helper = LayerHelper('concat', **locals()) + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + + if input[0].desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + # NOTE(liym27): Don't remove this if branch! + # This feature is supported for Dynamic-to-Static, because after transformed, the type of inputs[0] + # is LOD_TENSOR_ARRAY in some scenarios. And this feature can be used in static mode. + + assert len(input) == 1, ( + "If the elements of 'input' in concat are Variable(LoDTensorArray), " + "number of the elements must be 1, but received %s." % len(input) + ) + out_index = helper.create_variable_for_type_inference(dtype="int32") + helper.append_op( + type='tensor_array_to_tensor', + inputs={'X': input[0]}, + outputs={'Out': [out], 'OutIndex': [out_index]}, + attrs={'axis': axis, 'use_stack': False}, + ) + else: + inputs = {'X': input} + attrs = {} + if isinstance(axis, Variable): + axis.stop_gradient = True + inputs['AxisTensor'] = axis + else: + attrs['axis'] = axis + + helper.append_op( + type='concat', inputs=inputs, outputs={'Out': [out]}, attrs=attrs + ) + return out + + +def broadcast_tensors(input, name=None): + """ + This OP broadcast a list of tensors following broadcast semantics + + Note: + If you want know more about broadcasting, please refer to `Introduction to Tensor`_ . + + .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor + + Args: + input (list|tuple): ``input`` is a Tensor list or Tensor tuple which is with data type bool, + float16, float32, float64, int32, int64. All the Tensors in ``input`` must have same data type. + Currently we only support tensors with rank no greater than 5. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + list(Tensor): The list of broadcasted tensors following the same order as ``input``. + + Examples: + .. code-block:: python + + import paddle + x1 = paddle.rand([1, 2, 3, 4]).astype('float32') + x2 = paddle.rand([1, 2, 1, 4]).astype('float32') + x3 = paddle.rand([1, 1, 3, 1]).astype('float32') + out1, out2, out3 = paddle.broadcast_tensors(input=[x1, x2, x3]) + # out1, out2, out3: tensors broadcasted from x1, x2, x3 with shape [1,2,3,4] + """ + + num_inputs = len(input) + if paddle.framework.in_dygraph_mode(): + return _C_ops.broadcast_tensors(input) + if paddle.framework._non_static_mode(): + return _legacy_C_ops.broadcast_tensors(input, num_inputs) + + check_type(input, 'input', (list, tuple), 'broadcast_tensors') + if num_inputs < 1: + raise TypeError( + "At least 1 tensor is needed to perform broadcast_tensors" + ) + + # Check input types + for id, x in enumerate(input): + check_variable_and_dtype( + x, + 'input[' + str(id) + ']', + ['bool', 'float32', 'float64', 'int32', 'int64'], + 'broadcast_tensors', + ) + if x.dtype != input[0].dtype: + raise TypeError( + "All the Tensors in the input must have the same data type." + ) + + # Check bcast semantics + output_shape_r_last_tensor_index = [] + output_shape_r = [] + + # Use while loop due to weird behaviour of "range()" + j = 0 + while j < len(input): + tensor = input[j] + shape = list(reversed(tensor.shape)) + + i = 0 + while i < len(shape): + if len(output_shape_r) <= i: + output_shape_r.append(shape[i]) + output_shape_r_last_tensor_index.append(j) + else: + invalid = ( + output_shape_r[i] != shape[i] + and output_shape_r[i] != 1 + and shape[i] != 1 + ) + if invalid: + last_index = output_shape_r_last_tensor_index[i] + raise TypeError( + "Input tensors to broadcast_tensors does not follow bcast semantics" + "Tensor {last_index} conflicts with Tensor {j} in reversed dimension {i}" + ) + if output_shape_r[i] <= shape[i]: + output_shape_r[i] = shape[i] + output_shape_r_last_tensor_index[i] = j + i += 1 # while i < len(shape) + j += 1 # while j < len(input) + + helper = LayerHelper('broadcast_tensors', **locals()) + i = 0 + out = [] + while i < num_inputs: + out.append( + helper.create_variable_for_type_inference( + dtype=helper.input_dtype() + ) + ) + i += 1 + + inputs = {'X': input} + helper.append_op( + type='broadcast_tensors', inputs=inputs, outputs={'Out': out}, attrs={} + ) + + return out + + +def flip(x, axis, name=None): + """ + Reverse the order of a n-D tensor along given axis in axis. + + Args: + x (Tensor): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` . The data type of the input Tensor x + should be float32, float64, int32, int64, bool. + axis (list|tuple|int): The axis(axes) to flip on. Negative indices for indexing from the end are accepted. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Tensor or LoDTensor calculated by flip layer. The data type is same with input x. + + Examples: + .. code-block:: python + + import paddle + + image_shape=(3, 2, 2) + img = paddle.arange(image_shape[0] * image_shape[1] * image_shape[2]).reshape(image_shape) + tmp = paddle.flip(img, [0,1]) + print(tmp) # [[[10,11],[8, 9]], [[6, 7],[4, 5]], [[2, 3],[0, 1]]] + + out = paddle.flip(tmp,-1) + print(out) # [[[11,10],[9, 8]], [[7, 6],[5, 4]], [[3, 2],[1, 0]]] + """ + if isinstance(axis, int): + axis = [axis] + + if in_dygraph_mode(): + return _C_ops.flip(x, axis) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.flip(x, "axis", axis) + + helper = LayerHelper("flip", **locals()) + check_type(x, 'X', (Variable), 'flip') + dtype = helper.input_dtype('x') + check_dtype( + dtype, + 'X', + ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], + 'flip', + ) + check_type(axis, 'axis', (list, tuple), 'flip') + if name is None: + out = helper.create_variable_for_type_inference(dtype) + else: + out = helper.create_variable(name=name, dtype=dtype, persistable=False) + + helper.append_op( + type="flip", inputs={"X": x}, outputs={"Out": out}, attrs={"axis": axis} + ) + return out + + +def rot90(x, k=1, axes=[0, 1], name=None): + """ + Rotate a n-D tensor by 90 degrees. The rotation direction and times are specified by axes and the absolute value of k. Rotation direction is from axes[0] towards axes[1] if k > 0, and from axes[1] towards axes[0] for k < 0. + + Args: + x (Tensor): The input Tensor(or LoDTensor). The data type of the input Tensor x + should be float16, float32, float64, int32, int64, bool. float16 is only supported on gpu. + k (int, optional): Direction and number of times to rotate, default value: 1. + axes (list|tuple, optional): Axes to rotate, dimension must be 2. default value: [0, 1]. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: Tensor or LoDTensor calculated by rot90 layer. The data type is same with input x. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.arange(4) + data = paddle.reshape(data, (2, 2)) + print(data) + #[[0, 1], + # [2, 3]] + + y = paddle.rot90(data, 1, [0, 1]) + print(y) + #[[1, 3], + # [0, 2]] + + y= paddle.rot90(data, -1, [0, 1]) + print(y) + #[[2, 0], + # [3, 1]] + + data2 = paddle.arange(8) + data2 = paddle.reshape(data2, (2,2,2)) + print(data2) + #[[[0, 1], + # [2, 3]], + # [[4, 5], + # [6, 7]]] + + y = paddle.rot90(data2, 1, [1, 2]) + print(y) + #[[[1, 3], + # [0, 2]], + # [[5, 7], + # [4, 6]]] + """ + + helper = LayerHelper("rot90", **locals()) + check_type(x, 'X', (Variable), 'rot90') + dtype = helper.input_dtype('x') + check_dtype( + dtype, + 'X', + ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], + 'rot90', + ) + check_type(axes, 'axes', (list, tuple), 'rot90') + + input_total_dims = len(x.shape) + total_rot_dims = len(axes) + if total_rot_dims != 2: + raise ValueError( + "expected total rotation axes == 2, but got axes = {}".format( + total_rot_dims + ) + ) + if input_total_dims < 2: + raise ValueError( + "expected total dims >= 2, but got total dims = {}".format( + input_total_dims + ) + ) + + if not (axes[0] != axes[1] and abs(axes[0] - axes[1]) != input_total_dims): + raise ValueError( + "expected rotation axes to be different, but got axis0 = {}, and axis1 = {}".format( + axes[0], axes[1] + ) + ) + + if not (axes[0] < input_total_dims and axes[0] >= -input_total_dims): + raise ValueError( + "Rotation axis0 out of range, axis0 = {}".format(axes[0]) + ) + if not (axes[1] < input_total_dims and axes[1] >= -input_total_dims): + raise ValueError( + "Rotation axis1 out of range, axis1 = {}".format(axes[1]) + ) + + k %= 4 + if k == 0: + return x + if k == 2: + return flip(flip(x, axes[0]), axes[1]) + + axes_list = list(range(0, input_total_dims)) + (axes_list[axes[0]], axes_list[axes[1]]) = ( + axes_list[axes[1]], + axes_list[axes[0]], + ) + if k == 1: + return transpose(flip(x, axes[1]), axes_list) + else: + # k == 3 + return flip(transpose(x, axes_list), axes[1]) + + +def flatten(x, start_axis=0, stop_axis=-1, name=None): + r""" + Flattens a contiguous range of axes in a tensor according to start_axis and stop_axis. + + Note: + The output Tensor will share data with origin Tensor and doesn't have a Tensor copy in ``dygraph`` mode. + If you want to use the Tensor copy version, please use `Tensor.clone` like ``flatten_clone_x = x.flatten().clone()``. + + For Example: + + .. code-block:: text + + Case 1: + + Given + X.shape = (3, 100, 100, 4) + + and + start_axis = 1 + end_axis = 2 + + We get: + Out.shape = (3, 1000 * 100, 2) + + Case 2: + + Given + X.shape = (3, 100, 100, 4) + + and + start_axis = 0 + stop_axis = -1 + + We get: + Out.shape = (3 * 100 * 100 * 4) + + Args: + x (Tensor): A tensor of number of dimentions >= axis. A tensor with data type float32, + float64, int8, int32, int64, uint8. + start_axis (int): the start axis to flatten + stop_axis (int): the stop axis to flatten + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A tensor with the contents of the input tensor, with input \ + axes flattened by indicated start axis and end axis. \ + A Tensor with data type same as input x. + + Examples: + + .. code-block:: python + + import paddle + + image_shape=(2, 3, 4, 4) + + x = paddle.arange(end=image_shape[0] * image_shape[1] * image_shape[2] * image_shape[3]) + img = paddle.reshape(x, image_shape) + + out = paddle.flatten(img, start_axis=1, stop_axis=2) + # out shape is [2, 12, 4] + + # out shares data with img in dygraph mode + img[0, 0, 0, 0] = -1 + print(out[0, 0, 0]) # [-1] + """ + if not (isinstance(x, Variable)): + raise ValueError("The input x should be a Tensor") + + if not paddle.in_dynamic_mode(): + check_variable_and_dtype( + x, + 'x', + ['float32', 'float64', 'int8', 'int16', 'int32', 'int64', 'uint8'], + 'flatten', + ) + + x_dim = len(x.shape) + if ( + not (isinstance(start_axis, int)) + or (start_axis > x_dim - 1) + or start_axis < -x_dim + ): + raise ValueError( + "The start_axis should be a int, and in range [-rank(x), rank(x))" + ) + if ( + not (isinstance(stop_axis, int)) + or (stop_axis > x_dim - 1) + or stop_axis < -x_dim + ): + raise ValueError( + "The stop_axis should be a int, and in range [-rank(x), rank(x))" + ) + if start_axis < 0: + start_axis = start_axis + x_dim + if stop_axis < 0: + stop_axis = stop_axis + x_dim + if start_axis > stop_axis: + raise ValueError("The stop_axis should be larger than stat_axis") + + if in_dygraph_mode(): + return _C_ops.flatten(x, start_axis, stop_axis) + + if _in_legacy_dygraph(): + dy_out, _ = _legacy_C_ops.flatten_contiguous_range( + x, 'start_axis', start_axis, 'stop_axis', stop_axis + ) + return dy_out + + helper = LayerHelper('flatten', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='flatten_contiguous_range', + inputs={"X": x}, + outputs={'Out': out, 'XShape': x_shape}, + attrs={"start_axis": start_axis, "stop_axis": stop_axis}, + ) + return out + + +@inplace_apis_in_dygraph_only +def flatten_(x, start_axis=0, stop_axis=-1, name=None): + """ + Inplace version of ``flatten`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_flatten`. + """ + if not (isinstance(x, Variable)): + raise ValueError("The input x should be a Tensor") + + x_dim = len(x.shape) + if ( + not (isinstance(start_axis, int)) + or (start_axis > x_dim - 1) + or start_axis < -x_dim + ): + raise ValueError( + "The start_axis should be a int, and in range [-rank(x), rank(x))" + ) + if ( + not (isinstance(stop_axis, int)) + or (stop_axis > x_dim - 1) + or stop_axis < -x_dim + ): + raise ValueError( + "The stop_axis should be a int, and in range [-rank(x), rank(x))" + ) + if start_axis < 0: + start_axis = start_axis + x_dim + if stop_axis < 0: + stop_axis = stop_axis + x_dim + if start_axis > stop_axis: + raise ValueError("The stop_axis should be larger than stat_axis") + + if in_dygraph_mode(): + return _C_ops.flatten_(x, start_axis, stop_axis) + + if _in_legacy_dygraph(): + dy_out, _ = _legacy_C_ops.flatten_contiguous_range_( + x, 'start_axis', start_axis, 'stop_axis', stop_axis + ) + return dy_out + + +def roll(x, shifts, axis=None, name=None): + """ + Roll the `x` tensor along the given axis(axes). With specific 'shifts', Elements that + roll beyond the last position are re-introduced at the first according to 'shifts'. + If a axis is not specified, + the tensor will be flattened before rolling and then restored to the original shape. + + Args: + x (Tensor): The x tensor as input. + shifts (int|list|tuple): The number of places by which the elements + of the `x` tensor are shifted. + axis (int|list|tuple, optional): axis(axes) along which to roll. Default: None + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + + Returns: + Tensor: A Tensor with same data type as `x`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0], + [4.0, 5.0, 6.0], + [7.0, 8.0, 9.0]]) + out_z1 = paddle.roll(x, shifts=1) + print(out_z1) + #[[9. 1. 2.] + # [3. 4. 5.] + # [6. 7. 8.]] + out_z2 = paddle.roll(x, shifts=1, axis=0) + print(out_z2) + #[[7. 8. 9.] + # [1. 2. 3.] + # [4. 5. 6.]] + out_z3 = paddle.roll(x, shifts=1, axis=1) + print(out_z3) + #[[3. 1. 2.] + # [6. 4. 5.] + # [9. 7. 8.]] + """ + origin_shape = x.shape + if type(shifts) == int: + shifts = [shifts] + if type(axis) == int: + axis = [axis] + + len_origin_shape = len(origin_shape) + if axis is not None: + for i in range(len(axis)): + if axis[i] >= len_origin_shape or axis[i] < -len_origin_shape: + raise ValueError( + "axis is out of range, it should be in range [{}, {}), but received {}".format( + -len_origin_shape, len_origin_shape, axis + ) + ) + else: + axis = [] + + if in_dygraph_mode(): + return _C_ops.roll(x, shifts, axis) + + if _in_legacy_dygraph(): + return _legacy_C_ops.roll(x, 'axis', axis, 'shifts', shifts) + + helper = LayerHelper("roll", **locals()) + check_type(axis, 'axis', (list, tuple), 'roll') + + out = helper.create_variable_for_type_inference(x.dtype) + + if isinstance(shifts, Variable): + helper.append_op( + type='roll', + inputs={'X': x, "ShiftsTensor": shifts}, + outputs={'Out': out}, + attrs={'axis': axis}, + ) + else: + check_type(shifts, 'shifts', (list, tuple), 'roll') + helper.append_op( + type='roll', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'axis': axis, 'shifts': shifts}, + ) + return out + + +def stack(x, axis=0, name=None): + """ + Stacks all the input tensors ``x`` along ``axis`` dimemsion. + All tensors must be of the same shape and same dtype. + + For example, given N tensors of shape [A, B], if ``axis == 0``, the shape of stacked + tensor is [N, A, B]; if ``axis == 1``, the shape of stacked + tensor is [A, N, B], etc. + + + .. code-block:: text + + Case 1: + + Input: + x[0].shape = [1, 2] + x[0].data = [ [1.0 , 2.0 ] ] + x[1].shape = [1, 2] + x[1].data = [ [3.0 , 4.0 ] ] + x[2].shape = [1, 2] + x[2].data = [ [5.0 , 6.0 ] ] + + Attrs: + axis = 0 + + Output: + Out.dims = [3, 1, 2] + Out.data =[ [ [1.0, 2.0] ], + [ [3.0, 4.0] ], + [ [5.0, 6.0] ] ] + + + Case 2: + + Input: + x[0].shape = [1, 2] + x[0].data = [ [1.0 , 2.0 ] ] + x[1].shape = [1, 2] + x[1].data = [ [3.0 , 4.0 ] ] + x[2].shape = [1, 2] + x[2].data = [ [5.0 , 6.0 ] ] + + + Attrs: + axis = 1 or axis = -2 # If axis = -2, axis = axis+ndim(x[0])+1 = -2+2+1 = 1. + + Output: + Out.shape = [1, 3, 2] + Out.data =[ [ [1.0, 2.0] + [3.0, 4.0] + [5.0, 6.0] ] ] + + Args: + x (list[Tensor]|tuple[Tensor]): Input ``x`` can be a ``list`` or ``tuple`` of tensors, the Tensors in ``x`` + must be of the same shape and dtype. Supported data types: float32, float64, int32, int64. + axis (int, optional): The axis along which all inputs are stacked. ``axis`` range is ``[-(R+1), R+1)``, + where ``R`` is the number of dimensions of the first input tensor ``x[0]``. + If ``axis < 0``, ``axis = axis+R+1``. The default value of axis is 0. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The stacked tensor with same data type as input. + + Example: + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor([[1.0, 2.0]]) + x2 = paddle.to_tensor([[3.0, 4.0]]) + x3 = paddle.to_tensor([[5.0, 6.0]]) + + out = paddle.stack([x1, x2, x3], axis=0) + print(out.shape) # [3, 1, 2] + print(out) + # [[[1., 2.]], + # [[3., 4.]], + # [[5., 6.]]] + + out = paddle.stack([x1, x2, x3], axis=-2) + print(out.shape) # [1, 3, 2] + print(out) + # [[[1., 2.], + # [3., 4.], + # [5., 6.]]] + """ + axis = 0 if axis is None else axis + + if in_dygraph_mode(): + return _C_ops.stack(x, axis) + + if _in_legacy_dygraph(): + return _legacy_C_ops.stack(x, 'axis', axis) + + if not isinstance(x, list) and not isinstance(x, tuple): + # NOTE:(zhiqiu) Only support Variable as input if the Variable is a LOD_TENSOR_ARRAY create by create_array, array_write, array_read, etc. + # In that case, Variable is array of tensors indeed. + if ( + isinstance(x, Variable) + and x.desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY + ): + x = [x] + else: + raise TypeError( + "The type of '%s' in %s must be %s, but received %s" + % ( + 'x', + 'stack', + 'list[Tensor], tuple[Tensor] or TensorArray', + type(x), + ) + ) + + helper = LayerHelper('stack', **locals()) + + out = helper.create_variable_for_type_inference(x[0].dtype) + if x[0].desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY: + assert len(x) == 1, ( + "If the elements of 'x' in stack are Variable(LoDTensorArray), " + "number of the elements must be 1, but received %s." % len(x) + ) + out_index = helper.create_variable_for_type_inference(dtype="int32") + + for i in x: + check_variable_and_dtype( + i, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'stack', + ) + + helper.append_op( + type='tensor_array_to_tensor', + inputs={'X': x[0]}, + outputs={'Out': [out], 'OutIndex': [out_index]}, + attrs={'axis': axis, 'use_stack': True}, + ) + else: + helper.append_op( + type='stack', + inputs={'X': x}, + outputs={'Y': out}, + attrs={'axis': axis}, + ) + + return out + + +def split(x, num_or_sections, axis=0, name=None): + """ + Split the input tensor into multiple sub-Tensors. + + Args: + x (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, uint8, int8, int32 or int64. + num_or_sections (int|list|tuple): If ``num_or_sections`` is an int, then ``num_or_sections`` + indicates the number of equal sized sub-Tensors that the ``x`` will be divided into. + If ``num_or_sections`` is a list or tuple, the length of it indicates the number of + sub-Tensors and the elements in it indicate the sizes of sub-Tensors' dimension orderly. + The length of the list must not be larger than the ``x`` 's size of specified ``axis``. + axis (int|Tensor, optional): The axis along which to split, it can be a scalar with type + ``int`` or a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``. + If :math::`axis < 0`, the axis to split along is :math:`rank(x) + axis`. Default is 0. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + Returns: + list(Tensor): The list of segmented Tensors. + + Example: + .. code-block:: python + + import paddle + + # x is a Tensor of shape [3, 9, 5] + x = paddle.rand([3, 9, 5]) + + out0, out1, out2 = paddle.split(x, num_or_sections=3, axis=1) + print(out0.shape) # [3, 3, 5] + print(out1.shape) # [3, 3, 5] + print(out2.shape) # [3, 3, 5] + + out0, out1, out2 = paddle.split(x, num_or_sections=[2, 3, 4], axis=1) + print(out0.shape) # [3, 2, 5] + print(out1.shape) # [3, 3, 5] + print(out2.shape) # [3, 4, 5] + + out0, out1, out2 = paddle.split(x, num_or_sections=[2, 3, -1], axis=1) + print(out0.shape) # [3, 2, 5] + print(out1.shape) # [3, 3, 5] + print(out2.shape) # [3, 4, 5] + + # axis is negative, the real axis is (rank(x) + axis)=1 + out0, out1, out2 = paddle.split(x, num_or_sections=3, axis=-2) + print(out0.shape) # [3, 3, 5] + print(out1.shape) # [3, 3, 5] + print(out2.shape) # [3, 3, 5] + """ + input = x + dim = axis + if _non_static_mode(): + num = None + attrs = () + + if isinstance(dim, Variable): + dim = dim.numpy() + dim = dim.item(0) + assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" + dim = (len(input.shape) + dim) if dim < 0 else dim + attrs += ('axis', dim) + + if isinstance(num_or_sections, int): + num = num_or_sections + attrs += ('num', num_or_sections) + elif isinstance(num_or_sections, (list, tuple)): + num = len(num_or_sections) + if utils._contain_var(num_or_sections): + for index, item in enumerate(num_or_sections): + if isinstance(item, Variable): + num_or_sections[index] = num_or_sections[index].numpy()[ + 0 + ] + attrs += ('sections', list(num_or_sections)) + else: + attrs += ('sections', list(num_or_sections)) + else: + raise TypeError( + "The type of 'num_or_sections' in split must be int, list or tuple in imperative mode, but " + "received %s." % (type(num_or_sections)) + ) + if in_dygraph_mode(): + if isinstance(num_or_sections, int): + return _C_ops.split_with_num(input, num_or_sections, dim) + else: + return _C_ops.split(input, num_or_sections, dim) + elif _in_legacy_dygraph(): + out = [_varbase_creator() for n in range(num)] + _legacy_C_ops.split(input, out, *attrs) + return out + + check_variable_and_dtype( + input, + 'input', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'uint8', + 'int8', + ], + 'split', + ) + check_type(num_or_sections, 'num_or_sections', (list, int, tuple), 'split') + check_type(dim, 'dim', (int, Variable), 'split') + if isinstance(dim, Variable): + check_dtype(dim.dtype, 'dim', ['int32', 'int64'], 'split') + + helper = LayerHelper('split', **locals()) + + input_shape = input.shape + inputs = {'X': input} + attrs = {'num': num_or_sections if isinstance(num_or_sections, int) else 0} + + def _get_SectionsTensorList(one_list): + tensor_list = [] + unk_dim_idx = -1 + for idx, dim_size in enumerate(one_list): + if isinstance(dim_size, Variable): + dim_size.stop_gradient = True + tensor_list.append(dim_size) + else: + assert isinstance(dim_size, int) + if dim_size == -1: + assert unk_dim_idx == -1, ( + "Only one value of 'num_or_section' in split can " + "be -1. But received num_or_section[%d] is also -1." + % idx + ) + unk_dim_idx = idx + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant( + [1], 'int32', dim_size, force_cpu=True, out=temp_out + ) + tensor_list.append(temp_out) + return tensor_list + + if isinstance(dim, Variable): + dim.stop_gradient = True + inputs['AxisTensor'] = dim + else: + assert len(input.shape) + dim >= 0, "(rank(x) + axis) must >= 0" + dim = (len(input_shape) + dim) if dim < 0 else dim + attrs['axis'] = dim + + if isinstance(num_or_sections, int): + assert num_or_sections > 1, 'num_or_sections must be more than 1.' + if isinstance(dim, int) and input_shape[dim] > 0: + assert input_shape[dim] % num_or_sections == 0, ( + "The input's size along the split dimension " + "must be evenly divisible by Attr(num_or_sections). " + "But %d is not evenly divisible by %d. " + % (num_or_sections, input_shape[dim]) + ) + num = num_or_sections + else: + if isinstance(dim, int) and input_shape[dim] > 0: + assert ( + len(num_or_sections) <= input_shape[dim] + ), 'len(num_or_sections) must not be more than input.shape[dim].' + num = len(num_or_sections) + attrs['sections'] = list( + map( + lambda ele: -1 if isinstance(ele, Variable) else ele, + num_or_sections, + ) + ) + if utils._contain_var(num_or_sections): + inputs['SectionsTensorList'] = _get_SectionsTensorList( + num_or_sections + ) + + outs = [ + helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + for i in range(num) + ] + helper.append_op( + type='split', inputs=inputs, outputs={'Out': outs}, attrs=attrs + ) + return outs + + +def squeeze(x, axis=None, name=None): + """ + Squeeze the dimension(s) of size 1 of input tensor x's shape. + + Note that the output Tensor will share data with origin Tensor and doesn't have a + Tensor copy in ``dygraph`` mode. If you want to use the Tensor copy version, + please use `Tensor.clone` like ``squeeze_clone_x = x.squeeze().clone()``. + + If axis is provided, it will remove the dimension(s) by given axis that of size 1. + If the dimension of given axis is not of size 1, the dimension remain unchanged. + If axis is not provided, all dims equal of size 1 will be removed. + + .. code-block:: text + + Case1: + + Input: + x.shape = [1, 3, 1, 5] # If axis is not provided, all dims equal of size 1 will be removed. + axis = None + Output: + out.shape = [3, 5] + + Case2: + + Input: + x.shape = [1, 3, 1, 5] # If axis is provided, it will remove the dimension(s) by given axis that of size 1. + axis = 0 + Output: + out.shape = [3, 1, 5] + + Case4: + + Input: + x.shape = [1, 3, 1, 5] # If the dimension of one given axis (3) is not of size 1, the dimension remain unchanged. + axis = [0, 2, 3] + Output: + out.shape = [3, 5] + + Case4: + + Input: + x.shape = [1, 3, 1, 5] # If axis is negative, axis = axis + ndim (number of dimensions in x). + axis = [-2] + Output: + out.shape = [1, 3, 5] + + Args: + x (Tensor): The input Tensor. Supported data type: float32, float64, bool, int8, int32, int64. + axis (int|list|tuple, optional): An integer or list/tuple of integers, indicating the dimensions to be squeezed. Default is None. + The range of axis is :math:`[-ndim(x), ndim(x))`. + If axis is negative, :math:`axis = axis + ndim(x)`. + If axis is None, all the dimensions of x of size 1 will be removed. + name (str, optional): Please refer to :ref:`api_guide_Name`, Default None. + + Returns: + Tensor: Squeezed Tensor with the same data type as input Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([5, 1, 10]) + output = paddle.squeeze(x, axis=1) + + print(x.shape) # [5, 1, 10] + print(output.shape) # [5, 10] + + # output shares data with x in dygraph mode + x[0, 0, 0] = 10. + print(output[0, 0]) # [10.] + + """ + if axis is None: + axis = [] + elif isinstance(axis, int): + axis = [axis] + elif isinstance(axis, tuple): + axis = list(axis) + + input = x + axes = axis + if in_dygraph_mode(): + return _C_ops.squeeze(input, axes) + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.squeeze2(input, 'axes', axes) + return out + + helper = LayerHelper("squeeze", **locals()) + check_variable_and_dtype( + input, + 'input', + [ + 'float16', + 'float32', + 'float64', + 'bool', + 'int8', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'squeeze', + ) + + check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'squeeze') + attrs = {} + if isinstance(axes, Variable): + axes.stop_gradient = True + attrs["axes"] = axes + elif isinstance(axes, (list, tuple)): + if utils._contain_var(axes): + attrs["axes"] = utils._convert_to_tensor_list(axes) + else: + attrs["axes"] = axes + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type="squeeze2", + inputs={"X": input}, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return out + + +@inplace_apis_in_dygraph_only +def squeeze_(x, axis=None, name=None): + """ + Inplace version of ``squeeze`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_paddle_tensor_squeeze`. + """ + if axis is None: + axis = [] + elif isinstance(axis, int): + axis = [axis] + elif isinstance(axis, tuple): + axis = list(axis) + + input = x + axes = axis + if in_dygraph_mode(): + return _C_ops.squeeze_(input, axes) + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.squeeze2_(input, 'axes', axes) + return out + + +def unique_consecutive( + x, + return_inverse=False, + return_counts=False, + axis=None, + dtype="int64", + name=None, +): + r""" + Eliminates all but the first element from every consecutive group of equivalent elements. + + Note: + This function is different from :func:`paddle.unique` in the sense that this function + only eliminates consecutive duplicate values. This semantics is similar to `std::unique` in C++. + + Args: + x(Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + return_inverse(bool, optional): If True, also return the indices for where elements in + the original input ended up in the returned unique consecutive tensor. Default is False. + return_counts(bool, optional): If True, also return the counts for each unique consecutive element. + Default is False. + axis(int, optional): The axis to apply unique consecutive. If None, the input will be flattened. + Default is None. + dtype(np.dtype|str, optional): The data type `inverse` tensor: int32 or int64. + Default: int64. + name(str, optional): Name for the operation. For more information, please refer to + :ref:`api_guide_Name`. Default is None. + + Returns: + tuple: (out, inverse, counts). `out` is the unique consecutive tensor for `x`. `inverse` is provided only if `return_inverse` is True. `counts` is provided only if `return_counts` is True. + + Example: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 1, 2, 2, 3, 1, 1, 2]) + output = paddle.unique_consecutive(x) # + print(output) + # Tensor(shape=[5], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [1, 2, 3, 1, 2]) + + _, inverse, counts = paddle.unique_consecutive(x, return_inverse=True, return_counts=True) + print(inverse) + # Tensor(shape=[8], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [0, 0, 1, 1, 2, 3, 3, 4]) + print(counts) + # Tensor(shape=[5], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [2, 2, 1, 2, 1]) + + x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3], [2, 1, 3]]) + output = paddle.unique_consecutive(x, axis=0) # + print(output) + # Tensor(shape=[3, 3], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [[2, 1, 3], + # [3, 0, 1], + # [2, 1, 3]]) + + x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3], [2, 1, 3]]) + output = paddle.unique_consecutive(x, axis=0) # + print(output) + # Tensor(shape=[3, 3], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [[2, 1, 3], + # [3, 0, 1], + # [2, 1, 3]]) + """ + + if axis is None: + axis = [] + else: + axis = [axis] + attr_dtype = convert_np_dtype_to_dtype_(dtype) + if in_dygraph_mode(): + out, inverse, counts = _C_ops.unique_consecutive( + x, return_inverse, return_counts, axis, attr_dtype + ) + outs = [out] + if return_inverse: + outs.append(inverse) + if return_counts: + outs.append(counts) + if len(outs) == 1: + return outs[0] + return tuple(outs) + elif paddle.in_dynamic_mode(): + out, inverse, counts = _legacy_C_ops.unique_consecutive( + x, + 'dtype', + attr_dtype, + 'return_inverse', + return_inverse, + 'return_counts', + return_counts, + 'axis', + axis, + ) + outs = [out] + if return_inverse: + outs.append(inverse) + if return_counts: + outs.append(counts) + if len(outs) == 1: + return outs[0] + return tuple(outs) + check_variable_and_dtype( + x, + "input", + ['float32', 'float64', 'int32', 'int64'], + 'unique_consecutive', + ) + check_type(return_inverse, 'return_inverse', bool, 'unique_consecutive') + check_type(return_counts, 'return_counts', bool, 'unique_consecutive') + check_dtype(dtype, 'dtype', ['int32', 'int64'], 'unique_consecutive') + if len(axis) != 0: + check_type(axis[0], 'axis', int, 'unique_consecutive') + helper = LayerHelper('unique_consecutive', **locals()) + attrs = { + 'dtype': attr_dtype, + "return_inverse": return_inverse, + "return_counts": return_counts, + "axis": axis, + } + out = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + inverse = helper.create_variable_for_type_inference( + dtype=attr_dtype, stop_gradient=True + ) + counts = helper.create_variable_for_type_inference( + dtype=attr_dtype, stop_gradient=True + ) + outputs = {"Out": out, "Index": inverse, "Counts": counts} + outs = [out] + if return_inverse: + outs.append(inverse) + if return_counts: + outs.append(counts) + helper.append_op( + type="unique_consecutive", inputs={"X": x}, attrs=attrs, outputs=outputs + ) + if len(outs) == 1: + return outs[0] + return tuple(outs) + + +def unique( + x, + return_index=False, + return_inverse=False, + return_counts=False, + axis=None, + dtype="int64", + name=None, +): + r""" + Returns the unique elements of `x` in ascending order. + + Args: + x(Tensor): The input tensor, it's data type should be float32, float64, int32, int64. + return_index(bool, optional): If True, also return the indices of the input tensor that + result in the unique Tensor. + return_inverse(bool, optional): If True, also return the indices for where elements in + the original input ended up in the returned unique tensor. + return_counts(bool, optional): If True, also return the counts for each unique element. + axis(int, optional): The axis to apply unique. If None, the input will be flattened. + Default: None. + dtype(np.dtype|str, optional): The date type of `indices` or `inverse` tensor: int32 or int64. + Default: int64. + name(str, optional): Name for the operation. For more information, please refer to + :ref:`api_guide_Name`. Default: None. + + Returns: + tuple (out, indices, inverse, counts). `out` is the unique tensor for `x`. `indices` is \ + provided only if `return_index` is True. `inverse` is provided only if `return_inverse` \ + is True. `counts` is provided only if `return_counts` is True. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 3, 1, 5, 3]) + unique = paddle.unique(x) + np_unique = unique.numpy() # [1 2 3 5] + _, indices, inverse, counts = paddle.unique(x, return_index=True, return_inverse=True, return_counts=True) + print(indices) + # Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [3, 0, 1, 4]) + print(inverse) + # Tensor(shape=[6], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [1, 2, 2, 0, 3, 2]) + print(counts) + # Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [1, 1, 3, 1]) + + x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3]]) + unique = paddle.unique(x) + print(unique) + # Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [0, 1, 2, 3]) + + unique = paddle.unique(x, axis=0) + print(unique) + # Tensor(shape=[2, 3], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [[2, 1, 3], + # [3, 0, 1]]) + """ + if axis is None: + axis = [] + else: + axis = [axis] + attr_dtype = convert_np_dtype_to_dtype_(dtype) + if _non_static_mode(): + if in_dygraph_mode(): + out, indices, inverse, counts = _C_ops.unique( + x, return_index, return_inverse, return_counts, axis, attr_dtype + ) + if _in_legacy_dygraph(): + out, inverse, indices, counts = _legacy_C_ops.unique( + x, + 'dtype', + attr_dtype, + 'return_index', + return_index, + 'return_inverse', + return_inverse, + 'return_counts', + return_counts, + 'axis', + axis, + "is_sorted", + True, + ) + outs = [out] + if return_index: + outs.append(indices) + if return_inverse: + outs.append(inverse) + if return_counts: + outs.append(counts) + + if len(outs) == 1: + return outs[0] + + return tuple(outs) + + check_variable_and_dtype( + x, "input", ['float32', 'float64', 'int32', 'int64'], 'unique' + ) + check_type(return_index, 'return_index', bool, 'unique') + check_type(return_inverse, 'return_inverse', bool, 'unique') + check_type(return_counts, 'return_counts', bool, 'unique') + check_dtype(dtype, 'dtype', ['int32', 'int64'], 'unique') + if len(axis) != 0: + check_type(axis[0], 'axis', int, 'unique') + + helper = LayerHelper('unique', **locals()) + attrs = { + 'dtype': attr_dtype, + "return_index": return_index, + "return_inverse": return_inverse, + "return_counts": return_counts, + "axis": axis, + "is_sorted": True, + } + out = helper.create_variable_for_type_inference( + dtype=x.dtype, stop_gradient=True + ) + indices = helper.create_variable_for_type_inference( + dtype=attr_dtype, stop_gradient=True + ) + inverse = helper.create_variable_for_type_inference( + dtype=attr_dtype, stop_gradient=True + ) + counts = helper.create_variable_for_type_inference( + dtype=attr_dtype, stop_gradient=True + ) + outputs = { + "Out": out, + "Indices": indices, + "Index": inverse, + "Counts": counts, + } + outs = [out] + if return_index: + outs.append(indices) + if return_inverse: + outs.append(inverse) + if return_counts: + outs.append(counts) + + helper.append_op( + type="unique", inputs={"X": x}, attrs=attrs, outputs=outputs + ) + + if len(outs) == 1: + return outs[0] + + return tuple(outs) + + +def unsqueeze(x, axis, name=None): + """ + Insert single-dimensional entries to the shape of input Tensor ``x``. Takes one + required argument axis, a dimension or list of dimensions that will be inserted. + Dimension indices in axis are as seen in the output tensor. + + Note that the output Tensor will share data with origin Tensor and doesn't have a + Tensor copy in ``dygraph`` mode. If you want to use the Tensor copy version, + please use `Tensor.clone` like ``unsqueeze_clone_x = x.unsqueeze(-1).clone()``. + + Args: + x (Tensor): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64. + axis (int|list|tuple|Tensor): Indicates the dimensions to be inserted. The data type is ``int32`` . + If ``axis`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. + If ``axis`` is a Tensor, it should be an 1-D Tensor . + If ``axis`` is negative, ``axis = axis + ndim(x) + 1``. + name (str|None): Name for this layer. Please refer to :ref:`api_guide_Name`, Default None. + + Returns: + Tensor: Unsqueezed Tensor with the same data type as input Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([5, 10]) + print(x.shape) # [5, 10] + + out1 = paddle.unsqueeze(x, axis=0) + print(out1.shape) # [1, 5, 10] + + out2 = paddle.unsqueeze(x, axis=[0, 2]) + print(out2.shape) # [1, 5, 1, 10] + + axis = paddle.to_tensor([0, 1, 2]) + out3 = paddle.unsqueeze(x, axis=axis) + print(out3.shape) # [1, 1, 1, 5, 10] + + # out1, out2, out3 share data with x in dygraph mode + x[0, 0] = 10. + print(out1[0, 0, 0]) # [10.] + print(out2[0, 0, 0, 0]) # [10.] + print(out3[0, 0, 0, 0, 0]) # [10.] + + """ + input = x + axes = axis + if _non_static_mode(): + if isinstance(axes, int): + axes = [axes] + elif isinstance(axes, Variable): + axes = axes.numpy().tolist() + elif isinstance(axes, (list, tuple)): + axes = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in axes + ] + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.unsqueeze2(input, 'axes', axes) + return out + return _C_ops.unsqueeze(input, axes) + + check_type(axes, 'axis/axes', (int, list, tuple, Variable), 'unsqueeze') + check_variable_and_dtype( + input, + 'input', + [ + 'float16', + 'float32', + 'float64', + 'bool', + 'int8', + 'int16', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'unsqueeze', + ) + helper = LayerHelper("unsqueeze2", **locals()) + inputs = {"X": input} + attrs = {} + + if isinstance(axes, int): + axes = [axes] + if isinstance(axes, Variable): + axes.stop_gradient = True + inputs["AxesTensor"] = axes + elif isinstance(axes, (list, tuple)): + if utils._contain_var(axes): + inputs["AxesTensorList"] = utils._convert_to_tensor_list(axes) + else: + attrs["axes"] = axes + + out = helper.create_variable_for_type_inference(dtype=input.dtype) + x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type="unsqueeze2", + inputs=inputs, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return out + + +@inplace_apis_in_dygraph_only +def unsqueeze_(x, axis, name=None): + """ + Inplace version of ``unsqueeze`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_paddle_tensor_unsqueeze`. + """ + input = x + axes = axis + if isinstance(axes, int): + axes = [axes] + elif isinstance(axes, Variable): + axes = axes.numpy().tolist() + elif isinstance(axes, (list, tuple)): + axes = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in axes + ] + if in_dygraph_mode(): + return _C_ops.unsqueeze_(input, axes) + out, _ = _legacy_C_ops.unsqueeze2_(input, 'axes', axes) + return out + + +def gather(x, index, axis=None, name=None): + """ + Output is obtained by gathering entries of ``axis`` + of ``x`` indexed by ``index`` and concatenate them together. + + .. code-block:: text + + + Given: + + x = [[1, 2], + [3, 4], + [5, 6]] + + index = [1, 2] + axis=[0] + + Then: + + out = [[3, 4], + [5, 6]] + + Args: + x (Tensor): The source input tensor with rank>=1. Supported data type is + int32, int64, float32, float64 and uint8 (only for CPU), + float16 (only for GPU). + index (Tensor): The index input tensor with rank=1. Data type is int32 or int64. + axis (Tensor|int, optional): The axis of input to be gathered, it's can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the ``axis`` is 0. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + output (Tensor): The output is a tensor with the same rank as ``x``. + + Examples: + + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[1,2],[3,4],[5,6]]) + index = paddle.to_tensor([0,1]) + output = paddle.gather(input, index, axis=0) + # expected output: [[1,2],[3,4]] + """ + if axis is None: + axis = 0 + + if in_dygraph_mode(): + return _C_ops.gather(x, index, axis) + if _in_legacy_dygraph(): + axis = axis.item() if isinstance(axis, paddle.Tensor) else axis + return _legacy_C_ops.gather( + x, index, None, "axis", axis, "overwrite", False + ) + + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64', 'int16', 'int32', 'int64', 'uint8'], + 'gather', + ) + check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather') + + if isinstance(axis, Variable): + check_variable_and_dtype(axis, 'axis', ['int32', 'int64'], 'gather') + + helper = LayerHelper('gather', **locals()) + dtype = helper.input_dtype('x') + out = helper.create_variable_for_type_inference(dtype) + if not isinstance(axis, Variable): + helper.append_op( + type="gather", + inputs={"X": x, "Index": index}, + attrs={'axis': axis, 'overwrite': False}, + outputs={"Out": out}, + ) + else: + helper.append_op( + type="gather", + inputs={"X": x, "Index": index, "Axis": axis}, + attrs={"overwrite": False}, + outputs={"Out": out}, + ) + + return out + + +def unbind(input, axis=0): + """ + + Removes a tensor dimension, then split the input tensor into multiple sub-Tensors. + + Args: + input (Tensor): The input variable which is an N-D Tensor, data type being float32, float64, int32 or int64. + axis (int32|int64, optional): A scalar with type ``int32|int64`` shape [1]. The dimension along which to unbind. + If :math:`axis < 0`, the dimension to unbind along is :math:`rank(input) + axis`. Default is 0. + Returns: + list(Tensor): The list of segmented Tensor variables. + + Example: + .. code-block:: python + + import paddle + + # input is a Tensor which shape is [3, 4, 5] + input = paddle.rand([3, 4, 5]) + + [x0, x1, x2] = paddle.unbind(input, axis=0) + # x0.shape [4, 5] + # x1.shape [4, 5] + # x2.shape [4, 5] + + [x0, x1, x2, x3] = paddle.unbind(input, axis=1) + # x0.shape [3, 5] + # x1.shape [3, 5] + # x2.shape [3, 5] + # x3.shape [3, 5] + """ + if in_dygraph_mode(): + return _C_ops.unbind(input, axis) + + if not isinstance(axis, (int)): + raise TypeError( + "The type of 'axis' must be int, but received %s." % (type(axis)) + ) + if isinstance(axis, np.generic): + axis = np.asscalar(axis) + input_shape = input.shape + axis_ = axis if axis >= 0 else len(input_shape) + axis + num = input_shape[axis_] + if _in_legacy_dygraph(): + return _legacy_C_ops.unbind(input, num, 'axis', axis) + + helper = LayerHelper("unbind", **locals()) + check_type(input, 'input', (Variable), 'unbind') + dtype = helper.input_dtype() + check_dtype( + dtype, 'unbind', ['float32', 'float64', 'int32', 'int64'], 'unbind' + ) + outs = [ + helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + for i in range(num) + ] + helper.append_op( + type="unbind", + inputs={"X": input}, + outputs={"Out": outs}, + attrs={"axis": axis}, + ) + return outs + + +def scatter(x, index, updates, overwrite=True, name=None): + """ + **Scatter Layer** + Output is obtained by updating the input on selected indices based on updates. + + .. code-block:: python + + import numpy as np + #input: + x = np.array([[1, 1], [2, 2], [3, 3]]) + index = np.array([2, 1, 0, 1]) + # shape of updates should be the same as x + # shape of updates with dim > 1 should be the same as input + updates = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) + overwrite = False + # calculation: + if not overwrite: + for i in range(len(index)): + x[index[i]] = np.zeros((2)) + for i in range(len(index)): + if (overwrite): + x[index[i]] = updates[i] + else: + x[index[i]] += updates[i] + # output: + out = np.array([[3, 3], [6, 6], [1, 1]]) + out.shape # [3, 2] + + **NOTICE**: The order in which updates are applied is nondeterministic, + so the output will be nondeterministic if index contains duplicates. + + Args: + x (Tensor): The input N-D Tensor with ndim>=1. Data type can be float32, float64. + index (Tensor): The index 1-D Tensor. Data type can be int32, int64. The length of index cannot exceed updates's length, and the value in index cannot exceed input's length. + updates (Tensor): update input with updates parameter based on index. shape should be the same as input, and dim value with dim > 1 should be the same as input. + overwrite (bool): The mode that updating the output when there are same indices. + + If True, use the overwrite mode to update the output of the same index, + if False, use the accumulate mode to update the output of the same index.Default value is True. + + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: The output is a Tensor with the same shape as x. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 1], [2, 2], [3, 3]], dtype='float32') + index = paddle.to_tensor([2, 1, 0, 1], dtype='int64') + updates = paddle.to_tensor([[1, 1], [2, 2], [3, 3], [4, 4]], dtype='float32') + + output1 = paddle.scatter(x, index, updates, overwrite=False) + # [[3., 3.], + # [6., 6.], + # [1., 1.]] + + output2 = paddle.scatter(x, index, updates, overwrite=True) + # CPU device: + # [[3., 3.], + # [4., 4.], + # [1., 1.]] + # GPU device maybe have two results because of the repeated numbers in index + # result 1: + # [[3., 3.], + # [4., 4.], + # [1., 1.]] + # result 2: + # [[3., 3.], + # [2., 2.], + # [1., 1.]] + """ + if in_dygraph_mode(): + return _C_ops.scatter(x, index, updates, overwrite) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.scatter( + x, index, updates, 'overwrite', overwrite + ) + else: + check_variable_and_dtype( + x, + 'dtype', + ['float32', 'float64', 'float16', 'int32', 'int64'], + 'scatter', + ) + check_type(overwrite, 'overwrite', bool, 'scatter') + helper = LayerHelper('scatter', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type="scatter", + inputs={"X": x, "Ids": index, "Updates": updates}, + attrs={'overwrite': overwrite}, + outputs={"Out": out}, + ) + return out + + +@inplace_apis_in_dygraph_only +def scatter_(x, index, updates, overwrite=True, name=None): + """ + Inplace version of ``scatter`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_paddle_tensor_scatter`. + """ + if in_dygraph_mode(): + return _C_ops.scatter_(x, index, updates, overwrite) + return _legacy_C_ops.scatter_(x, index, updates, 'overwrite', overwrite) + + +def scatter_nd_add(x, index, updates, name=None): + r""" + + Output is obtained by applying sparse addition to a single value + or slice in a Tensor. + + :attr:`x` is a Tensor with ndim :math:`R` + and :attr:`index` is a Tensor with ndim :math:`K` . Thus, :attr:`index` + has shape :math:`[i_0, i_1, ..., i_{K-2}, Q]` where :math:`Q \leq R` . :attr:`updates` + is a Tensor with ndim :math:`K - 1 + R - Q` and its + shape is :math:`index.shape[:-1] + x.shape[index.shape[-1]:]` . + + According to the :math:`[i_0, i_1, ..., i_{K-2}]` of :attr:`index` , + add the corresponding :attr:`updates` slice to the :attr:`x` slice + which is obtained by the last one dimension of :attr:`index` . + + .. code-block:: text + + Given: + + * Case 1: + x = [0, 1, 2, 3, 4, 5] + index = [[1], [2], [3], [1]] + updates = [9, 10, 11, 12] + + we get: + + output = [0, 22, 12, 14, 4, 5] + + * Case 2: + x = [[65, 17], [-14, -25]] + index = [[], []] + updates = [[[-1, -2], [1, 2]], + [[3, 4], [-3, -4]]] + x.shape = (2, 2) + index.shape = (2, 0) + updates.shape = (2, 2, 2) + + we get: + + output = [[67, 19], [-16, -27]] + + Args: + x (Tensor): The x input. Its dtype should be int32, int64, float32, float64. + index (Tensor): The index input with ndim > 1 and index.shape[-1] <= x.ndim. + Its dtype should be int32 or int64 as it is used as indexes. + updates (Tensor): The updated value of scatter_nd_add op, and it must have the same dtype + as x. It must have the shape index.shape[:-1] + x.shape[index.shape[-1]:]. + name (str|None): The output tensor name. If set None, the layer will be named automatically. + + Returns: + output (Tensor): The output is a tensor with the same shape and dtype as x. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand(shape=[3, 5, 9, 10], dtype='float32') + updates = paddle.rand(shape=[3, 9, 10], dtype='float32') + index = paddle.to_tensor([[1, 1], + [0, 1], + [1, 3]], dtype='int64') + + output = paddle.scatter_nd_add(x, index, updates) + print(output.shape) + # [3, 5, 9, 10] + """ + if in_dygraph_mode(): + return _C_ops.scatter_nd_add(x, index, updates) + else: + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, 'scatter_nd_add') + return op(x, index, updates) + else: + if x.dtype != updates.dtype: + raise ValueError("x and updates must have same data type.") + + helper = LayerHelper('scatter_nd_add', **locals()) + dtype = helper.input_dtype(input_param_name='x') + output = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="scatter_nd_add", + inputs={"X": x, "Index": index, "Updates": updates}, + outputs={"Out": output}, + ) + return output + + +def scatter_nd(index, updates, shape, name=None): + """ + **Scatter_nd Layer** + + Output is obtained by scattering the :attr:`updates` in a new tensor according + to :attr:`index` . This op is similar to :code:`scatter_nd_add`, except the + tensor of :attr:`shape` is zero-initialized. Correspondingly, :code:`scatter_nd(index, updates, shape)` + is equal to :code:`scatter_nd_add(paddle.zeros(shape, updates.dtype), index, updates)` . + If :attr:`index` has repeated elements, then the corresponding updates are accumulated. + Because of the numerical approximation issues, the different order of repeated elements + in :attr:`index` may cause different results. The specific calculation method can be + seen :code:`scatter_nd_add` . This op is the inverse of the :code:`gather_nd` op. + + Args: + index (Tensor): The index input with ndim > 1 and index.shape[-1] <= len(shape). + Its dtype should be int32 or int64 as it is used as indexes. + updates (Tensor): The updated value of scatter_nd op. Its dtype should be float32, float64. + It must have the shape index.shape[:-1] + shape[index.shape[-1]:] + shape(tuple|list): Shape of output tensor. + name (str|None): The output Tensor name. If set None, the layer will be named automatically. + + Returns: + output (Tensor): The output is a tensor with the same type as :attr:`updates` . + + Examples: + + .. code-block:: python + + import paddle + + index = paddle.to_tensor([[1, 1], + [0, 1], + [1, 3]], dtype="int64") + updates = paddle.rand(shape=[3, 9, 10], dtype='float32') + shape = [3, 5, 9, 10] + + output = paddle.scatter_nd(index, updates, shape) + """ + return scatter_nd_add(zeros(shape, updates.dtype), index, updates, name) + + +def chunk(x, chunks, axis=0, name=None): + """ + Split the input tensor into multiple sub-Tensors. + + Args: + x (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64. + chunks(int): The number of tensor to be split along the certain axis. + axis (int|Tensor, optional): The axis along which to split, it can be a scalar with type + ``int`` or a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``. + If :math::`axis < 0`, the axis to split along is :math:`rank(x) + axis`. Default is 0. + name (str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + Returns: + list(Tensor): The list of segmented Tensors. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([3, 9, 5]) + + out0, out1, out2 = paddle.chunk(x, chunks=3, axis=1) + # out0.shape [3, 3, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 3, 5] + + + # axis is negative, the real axis is (rank(x) + axis) which real + # value is 1. + out0, out1, out2 = paddle.chunk(x, chunks=3, axis=-2) + # out0.shape [3, 3, 5] + # out1.shape [3, 3, 5] + # out2.shape [3, 3, 5] + """ + check_type(chunks, 'chunks', (int), 'chunk') + return split(x, num_or_sections=chunks, axis=axis, name=name) + + +def tile(x, repeat_times, name=None): + """ + + Construct a new Tensor by repeating ``x`` the number of times given by ``repeat_times``. + After tiling, the value of the i'th dimension of the output is equal to ``x.shape[i]*repeat_times[i]``. + + Both the number of dimensions of ``x`` and the number of elements in ``repeat_times`` should be less than or equal to 6. + + Args: + x (Tensor): The input tensor, its data type should be bool, float32, float64, int32 or int64. + repeat_times (list|tuple|Tensor): The number of repeating times. If repeat_times is a list or tuple, all its elements + should be integers or 1-D Tensors with the data type int32. If repeat_times is a Tensor, it should be an 1-D Tensor with the data type int32. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. The data type is the same as ``x``. The size of the i-th dimension is equal to ``x[i] * repeat_times[i]``. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.to_tensor([1, 2, 3], dtype='int32') + out = paddle.tile(data, repeat_times=[2, 1]) + print(out) + # Tensor(shape=[2, 3], dtype=int32, place=Place(gpu:0), stop_gradient=True, + # [[1, 2, 3], + # [1, 2, 3]]) + + out = paddle.tile(data, repeat_times=(2, 2)) + print(out) + # Tensor(shape=[2, 6], dtype=int32, place=Place(gpu:0), stop_gradient=True, + # [[1, 2, 3, 1, 2, 3], + # [1, 2, 3, 1, 2, 3]]) + + repeat_times = paddle.to_tensor([1, 2], dtype='int32') + out = paddle.tile(data, repeat_times=repeat_times) + print(out) + # Tensor(shape=[1, 6], dtype=int32, place=Place(gpu:0), stop_gradient=True, + # [[1, 2, 3, 1, 2, 3]]) + """ + if in_dygraph_mode(): + if isinstance(repeat_times, core.eager.Tensor): + assert ( + repeat_times.ndim == 1 + ), "Only support ndim == 1 while repeat_times is a Tensor." + repeat_times = repeat_times.numpy().tolist() + + return _C_ops.tile(x, repeat_times) + + if _in_legacy_dygraph(): + return _legacy_C_ops.tile(x, 'repeat_times', repeat_times) + + check_type(repeat_times, 'repeat_times', (list, tuple, Variable), 'tile') + if isinstance(repeat_times, Variable): + assert ( + len(repeat_times.shape) == 1 + ), 'repeat_times must be an 1-D Tensor.' + else: + for elem in repeat_times: + if isinstance(elem, Variable): + assert ( + len(elem.shape) == 1 + ), 'Elements in repeat_times must be 1-D Tensors or integers.' + else: + type_tuple = (int, np.int32, np.int64) + assert isinstance( + elem, type_tuple + ), 'Elements in repeat_times must be 1-D Tensors or integers.' + + check_variable_and_dtype( + x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'tile' + ) + if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False: + raise ValueError( + "When the date type is bool for the input 'x' of tile op, you " + "must set its stop_gradient to be True by " + "some_var.stop_gradient == True supporting some_var is the input." + ) + + helper = LayerHelper('tile', **locals()) + + inputs = {"X": [x]} + attrs = {} + + def get_attr_repeat_times(list_repeat_times): + attrs_repeat_times = [] + for idx, times in enumerate(list_repeat_times): + if isinstance(times, Variable): + attrs_repeat_times.append(-1) + else: + attrs_repeat_times.append(times) + assert ( + times > 0 + ), "All elements in repeat_times must be positive for tile." + return attrs_repeat_times + + if isinstance(repeat_times, Variable): + repeat_times.stop_gradient = True + inputs['RepeatTimes'] = repeat_times + attrs['repeat_times'] = [-1] + elif isinstance(repeat_times, (list, tuple)): + attrs['repeat_times'] = get_attr_repeat_times(repeat_times) + if utils._contain_var(repeat_times): + inputs['repeat_times_tensor'] = utils._convert_to_tensor_list( + repeat_times + ) + + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='tile', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +def expand_as(x, y, name=None): + """ + + Expand the input tensor ``x`` to the same shape as the input tensor ``y``. + + Both the number of dimensions of ``x`` and ``y`` must be less than or equal to 6, and the number of dimensions of ``y`` must be greather than or equal to that of ``x``. The dimension to expand must have a value of 1. + + Args: + x (Tensor): The input tensor, its data type is bool, float32, float64, int32 or int64. + y (Tensor): The input tensor that gives the shape to expand to. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor: A Tensor with the same shape as ``y``. The data type is the same as ``x``. + + Examples: + .. code-block:: python + + import paddle + + data_x = paddle.to_tensor([1, 2, 3], 'int32') + data_y = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], 'int32') + out = paddle.expand_as(data_x, data_y) + print(out) + # Tensor(shape=[2, 3], dtype=int32, place=Place(gpu:0), stop_gradient=True, + # [[1, 2, 3], + # [1, 2, 3]]) + """ + if in_dygraph_mode(): + return _C_ops.expand_as(x, None, y.shape) + + if _non_static_mode(): + return _legacy_C_ops.expand_as_v2(x, 'target_shape', y.shape) + + check_variable_and_dtype( + x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'expand_as' + ) + check_type(y, 'y', Variable, 'expand_as') + + if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False: + raise ValueError( + "When the data type of input 'x' for expand_as is bool, " + "you must set its stop_gradient to be False by " + "some_var.stop_gradient = True, supporting " + "some_var as the input 'x'." + ) + inputs = {"X": [x], "Y": [y]} + + helper = LayerHelper('expand_as', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='expand_as_v2', + inputs=inputs, + attrs={'target_shape': y.shape}, + outputs={'Out': out}, + ) + return out + + +def broadcast_to(x, shape, name=None): + """ + + Broadcast the input tensor to a given shape. + + Both the number of dimensions of ``x`` and the number of elements in ``shape`` should be less than or equal to 6. The dimension to broadcast to must have a value 1. + + + Args: + x (Tensor): The input tensor, its data type is bool, float32, float64, int32 or int64. + shape (list|tuple|Tensor): The result shape after broadcasting. The data type is int32. If shape is a list or tuple, all its elements + should be integers or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. + The value -1 in shape means keeping the corresponding dimension unchanged. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + Returns: + N-D Tensor: A Tensor with the given shape. The data type is the same as ``x``. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.to_tensor([1, 2, 3], dtype='int32') + out = paddle.broadcast_to(data, shape=[2, 3]) + print(out) + # [[1, 2, 3], [1, 2, 3]] + """ + if in_dygraph_mode(): + return _C_ops.expand(x, shape) + if _in_legacy_dygraph(): + return _legacy_C_ops.expand_v2(x, 'shape', shape) + + if isinstance(shape, Variable): + assert len(shape.shape) == 1, 'shape must be an 1-D Tensor.' + else: + for elem in shape: + if isinstance(elem, Variable): + assert ( + len(elem.shape) == 1 + ), 'Elements in shape must be 1-D Tensors or integers.' + else: + type_tuple = (int, np.int32, np.int64) + assert isinstance( + elem, type_tuple + ), 'Elements in shape must be 1-D Tensors or integers.' + + check_variable_and_dtype( + x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'broadcast_to' + ) + check_type(shape, 'shape', (list, tuple, Variable), 'broadcast_to') + if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False: + raise ValueError( + "When the data type of input 'x' for broadcast_to is bool, " + "you must set its stop_gradient to be False by " + "some_var.stop_gradient = True, supporting " + "some_var as the input." + ) + + inputs = {"X": [x]} + attrs = {} + + helper = LayerHelper('expand', **locals()) + + def get_attr_expand_shape(list_expand_shape): + attrs_expand_shape = [] + for idx, shape in enumerate(list_expand_shape): + if isinstance(shape, Variable): + attrs_expand_shape.append(-1) + else: + attrs_expand_shape.append(shape) + assert ( + shape > 0 or shape == -1 + ), "All elements in shape of broadcast_to must be positive or -1." + return attrs_expand_shape + + if isinstance(shape, Variable): + shape.stop_gradient = True + inputs['Shape'] = shape + elif isinstance(shape, (list, tuple)): + attrs['shape'] = get_attr_expand_shape(shape) + if utils._contain_var(shape): + inputs['expand_shapes_tensor'] = utils._convert_to_tensor_list( + shape + ) + + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='expand_v2', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +def expand(x, shape, name=None): + """ + + Expand the input tensor to a given shape. + + Both the number of dimensions of ``x`` and the number of elements in ``shape`` should be less than or equal to 6. And the number of dimensions of ``x`` should be less than the number of elements in ``shape``. The dimension to expand must have a value 1. + + + Args: + x (Tensor): The input Tensor, its data type is bool, float32, float64, int32 or int64. + shape (list|tuple|Tensor): The result shape after expanding. The data type is int32. If shape is a list or tuple, all its elements + should be integers or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. + The value -1 in shape means keeping the corresponding dimension unchanged. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` . + + Returns: + N-D Tensor: A Tensor with the given shape. The data type is the same as ``x``. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.to_tensor([1, 2, 3], dtype='int32') + out = paddle.expand(data, shape=[2, 3]) + print(out) + # [[1, 2, 3], [1, 2, 3]] + """ + if in_dygraph_mode(): + return _C_ops.expand(x, shape) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.expand_v2(x, 'shape', shape) + + if isinstance(shape, Variable): + assert len(shape.shape) == 1, 'shape must be an 1-D Tensor.' + else: + for elem in shape: + if isinstance(elem, Variable): + assert ( + len(elem.shape) == 1 + ), 'Elements in shape must be 1-D Tensors or integers.' + else: + type_tuple = (int, np.int32, np.int64) + assert isinstance( + elem, type_tuple + ), 'Elements in shape must be 1-D Tensors or integers.' + + check_variable_and_dtype( + x, + 'x', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'expand', + ) + check_type(shape, 'shape', (list, tuple, Variable), 'expand') + if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False: + raise ValueError( + "When the data type of input 'x' for expand is bool, " + "you must set its stop_gradient to be False by " + "some_var.stop_gradient = True, supporting " + "some_var as the input." + ) + + inputs = {"X": [x]} + attrs = {} + + helper = LayerHelper('expand', **locals()) + + def get_attr_expand_shape(list_expand_shape): + attrs_expand_shape = [] + for idx, shape in enumerate(list_expand_shape): + if isinstance(shape, Variable): + attrs_expand_shape.append(-2) + else: + attrs_expand_shape.append(shape) + assert ( + shape > 0 or shape == -1 + ), "All elements in shape of expand must be positive or -1." + return attrs_expand_shape + + if isinstance(shape, Variable): + shape.stop_gradient = True + inputs['Shape'] = shape + elif isinstance(shape, (list, tuple)): + attrs['shape'] = get_attr_expand_shape(shape) + if utils._contain_var(shape): + inputs['expand_shapes_tensor'] = utils._convert_to_tensor_list( + shape + ) + + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='expand_v2', inputs=inputs, outputs={'Out': out}, attrs=attrs + ) + return out + + +def reshape(x, shape, name=None): + """ + Changes the shape of ``x`` without changing its data. + + Note that the output Tensor will share data with origin Tensor and doesn't + have a Tensor copy in ``dygraph`` mode. + If you want to use the Tensor copy version, please use `Tensor.clone` like + ``reshape_clone_x = x.reshape([-1]).clone()``. + + Some tricks exist when specifying the target shape. + + - 1. -1 means the value of this dimension is inferred from the total element number of x and remaining dimensions. Thus one and only one dimension can be set -1. + + - 2. 0 means the actual dimension value is going to be copied from the corresponding dimension of x. The index of 0s in shape can not exceed the dimension of x. + + Here are some examples to explain it. + + - 1. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [6, 8], the reshape operator will transform x into a 2-D tensor with shape [6, 8] and leaving x's data unchanged. + + - 2. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape specified is [2, 3, -1, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 3, 4, 2] and leaving x's data unchanged. In this case, one dimension of the target shape is set to -1, the value of this dimension is inferred from the total element number of x and remaining dimensions. + + - 3. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape is [-1, 0, 3, 2], the reshape operator will transform x into a 4-D tensor with shape [2, 4, 3, 2] and leaving x's data unchanged. In this case, besides -1, 0 means the actual dimension value is going to be copied from the corresponding dimension of x. + + Args: + x (Tensor): An N-D Tensor. The data type is ``float32``, ``float64``, ``int32``, ``int64`` or ``bool`` + shape (list|tuple|Tensor): Define the target shape. At most one dimension of the target shape can be -1. + The data type is ``int32`` . If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. + If ``shape`` is an Tensor, it should be an 1-D Tensor . + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A reshaped Tensor with the same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([2, 4, 6], dtype="float32") + positive_four = paddle.full([1], 4, "int32") + + out = paddle.reshape(x, [-1, 0, 3, 2]) + print(out) + # the shape is [2,4,3,2]. + + out = paddle.reshape(x, shape=[positive_four, 12]) + print(out) + # the shape of out_2 is [4, 12]. + + shape_tensor = paddle.to_tensor([8, 6], dtype=paddle.int32) + out = paddle.reshape(x, shape=shape_tensor) + print(out.shape) + # the shape is [8, 6]. + # out shares data with x in dygraph mode + x[0, 0, 0] = 10. + print(out[0, 0]) + # the value is [10.] + + """ + actual_shape = None + act = None + inplace = False + + if in_dygraph_mode(): + tmp_tensor_type = core.eager.Tensor + # TODO(zhiqiu): enable inplace in dygraph mode. + if inplace: + warnings.warn( + "Inplace on reshape is not allowed and will be discarded in dygraph mode currently." + ) + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in shape + ] + out = _C_ops.reshape(x, shape) + elif isinstance(shape, tmp_tensor_type): + shape.stop_gradient = True + out = _C_ops.reshape(x, shape) + else: + raise ValueError( + "shape must be an instance of `list`, `tuple` or `Variable`," + " got '{}.'".format(type(shape)) + ) + + return dygraph_utils._append_activation_in_dygraph(out, act) + else: + if _in_legacy_dygraph(): + tmp_tensor_type = Variable + if inplace: + warnings.warn( + "Inplace on reshape is not allowed and will be discarded in dygraph mode currently." + ) + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in shape + ] + out, _ = _legacy_C_ops.reshape2(x, None, 'shape', shape) + elif isinstance(shape, tmp_tensor_type): + shape.stop_gradient = True + out, _ = _legacy_C_ops.reshape2(x, shape) + else: + raise ValueError( + "shape must be an instance of `list`, `tuple` or `Variable`," + " got '{}.'".format(type(shape)) + ) + + return dygraph_utils._append_activation_in_dygraph(out, act) + + check_variable_and_dtype( + x, + 'x', + [ + 'float16', + 'float32', + 'float64', + 'int16', + 'int32', + 'int64', + 'bool', + 'uint16', + ], + 'reshape', + ) + check_type(shape, 'shape', (list, tuple, Variable), 'reshape') + check_type(actual_shape, 'actual_shape', (Variable, type(None)), 'reshape') + + helper = LayerHelper("reshape2", **locals()) + + def get_attr_shape(list_shape): + unk_dim_idx = -1 + attrs_shape = [] + for dim_idx, dim_size in enumerate(list_shape): + if isinstance(dim_size, Variable): + attrs_shape.append(-1) + else: + attrs_shape.append(dim_size) + if dim_size == -1: + assert unk_dim_idx == -1, ( + "Only one dimension value of 'shape' in reshape can " + "be -1. But received shape[%d] is also -1.\n" + "\n\t# N = x.shape()[2]\t\t# N is an int. " + "(NOT recommend under @to_static)\n\tN = paddle.shape(x)[2]\t\t" + "# N is a Tensor. (Recommend)\n\tz = paddle.reshape([N, -1, 4])" + "\t# z.shape is [-1, -1, 4]\n\n" + " If your target shape in Reshape represents dynamic shape, " + "please turn it into a Tensor under @to_static. See above example for details." + % dim_idx + ) + unk_dim_idx = dim_idx + elif dim_size == 0: + assert dim_idx < len(x.shape), ( + "The index of 0 in `shape` must be less than " + "the input tensor X's dimensions. " + "But received shape[%d] = 0, X's dimensions = %d." + % (dim_idx, len(x.shape)) + ) + else: + assert dim_size > 0, ( + "Each dimension value of 'shape' in reshape must not " + "be negative except one unknown dimension. " + "But received shape[%d] = %s." + % (dim_idx, str(dim_size)) + ) + return attrs_shape + + inputs = {"X": x} + attrs = {} + if isinstance(shape, Variable): + shape.stop_gradient = True + inputs["Shape"] = shape + elif isinstance(shape, (list, tuple)): + assert len(shape) > 0, ( + "The size of 'shape' in reshape can't be zero, " + "but received %s." % len(shape) + ) + attrs["shape"] = get_attr_shape(shape) + if utils._contain_var(shape): + inputs['ShapeTensor'] = utils._convert_to_tensor_list(shape) + elif isinstance(actual_shape, Variable): + actual_shape.stop_gradient = True + inputs["Shape"] = actual_shape + + out = ( + x + if inplace + else helper.create_variable_for_type_inference(dtype=x.dtype) + ) + x_shape = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="reshape2", + inputs=inputs, + attrs=attrs, + outputs={"Out": out, "XShape": x_shape}, + ) + + return helper.append_activation(out) + + +@inplace_apis_in_dygraph_only +def reshape_(x, shape, name=None): + """ + Inplace version of ``reshape`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_paddle_tensor_reshape`. + """ + if in_dygraph_mode(): + tmp_tensor_type = core.eager.Tensor + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) + if isinstance(item, tmp_tensor_type) + else item + for item in shape + ] + out = _C_ops.reshape_(x, shape) + elif isinstance(shape, tmp_tensor_type): + shape.stop_gradient = True + out = _C_ops.reshape_(x, shape) + else: + raise ValueError( + "shape must be an instance of `list`, `tuple` or `Variable`," + " got '{}.'".format(type(shape)) + ) + + return out + else: + if isinstance(shape, (list, tuple)): + shape = [ + item.numpy().item(0) if isinstance(item, Variable) else item + for item in shape + ] + out, _ = _legacy_C_ops.reshape2_(x, None, 'shape', shape) + return out + elif isinstance(shape, Variable): + shape.stop_gradient = True + # NOTE(pangyoki): Cannot support the case where the shape Tensor + # is negative. In the infer_shape stage, the input's dim will + # be changed to a negative number. + # Thus, convert Shape Tensor to list firstly and then call + # reshape inplace op. + shape_list = shape.numpy().tolist() + out, _ = _legacy_C_ops.reshape2_(x, None, 'shape', shape_list) + return out + + +def gather_nd(x, index, name=None): + """ + + This function is actually a high-dimensional extension of :code:`gather` + and supports for simultaneous indexing by multiple axes. :attr:`index` is a + K-dimensional integer tensor, which is regarded as a (K-1)-dimensional + tensor of :attr:`index` into :attr:`input`, where each element defines + a slice of params: + + .. math:: + + output[(i_0, ..., i_{K-2})] = input[index[(i_0, ..., i_{K-2})]] + + Obviously, :code:`index.shape[-1] <= input.rank` . And, the output tensor has + shape :code:`index.shape[:-1] + input.shape[index.shape[-1]:]` . + + .. code-block:: text + + Given: + 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) + + * Case 1: + index = [[1]] + + gather_nd(x, index) + = [x[1, :, :]] + = [[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23]] + + * Case 2: + index = [[0,2]] + + gather_nd(x, index) + = [x[0, 2, :]] + = [8, 9, 10, 11] + + * Case 3: + index = [[1, 2, 3]] + + gather_nd(x, index) + = [x[1, 2, 3]] + = [23] + + Args: + x (Tensor): The input Tensor which it's data type should be bool, float32, float64, int32, int64. + index (Tensor): The index input with rank > 1, index.shape[-1] <= input.rank. + Its dtype should be int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + output (Tensor): A tensor with the shape index.shape[:-1] + input.shape[index.shape[-1]:] + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[[1, 2], [3, 4], [5, 6]], + [[7, 8], [9, 10], [11, 12]]]) + index = paddle.to_tensor([[0, 1]]) + + output = paddle.gather_nd(x, index) #[[3, 4]] + + """ + if in_dygraph_mode(): + return _C_ops.gather_nd(x, index) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.gather_nd(x, index) + check_variable_and_dtype( + x, + 'x', + ['bool', 'float32', 'float64', 'int16', 'int32', 'int64'], + 'gather_np', + ) + check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather_np') + helper = LayerHelper('gather_nd', **locals()) + dtype = helper.input_dtype() + output = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="gather_nd", + inputs={"X": x, "Index": index}, + outputs={"Out": output}, + ) + return output + + +def strided_slice(x, axes, starts, ends, strides, name=None): + """ + This operator produces a slice of ``x`` along multiple axes. Similar to numpy: + https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html + Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and + end dimension for each axis in the list of axes and Slice uses this information + to slice the input data tensor. If a negative value is passed to + ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the + axis :math:`i-1` th(here 0 is the initial position). The ``strides`` represents steps of + slicing and if the ``strides`` is negative, slice operation is in the opposite direction. + If the value passed to ``starts`` or ``ends`` is greater than n + (the number of elements in this dimension), it represents n. + For slicing to the end of a dimension with unknown size, it is recommended + to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` , ``ends`` and ``strides``. + Following examples will explain how strided_slice works: + + .. code-block:: text + + Case1: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [1, 0] + ends = [2, 3] + strides = [1, 1] + Then: + result = [ [5, 6, 7], ] + + Case2: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [2, 0] + strides = [1, -1] + Then: + result = [ [8, 7, 6], ] + Case3: + Given: + data = [ [1, 2, 3, 4], [5, 6, 7, 8], ] + axes = [0, 1] + starts = [0, 1] + ends = [-1, 1000] + strides = [1, 3] + Then: + result = [ [2], ] + + Args: + x (Tensor): An N-D ``Tensor``. The data type is ``bool``, ``float16``, ``float32``, ``float64``, ``int32`` or ``int64``. + axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to. + It's optional. If it is not provides, it will be treated as :math:`[0,1,...,len(starts)-1]`. + starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``starts`` is an Tensor, it should be an 1-D Tensor. It represents starting indices of corresponding axis in ``axes``. + ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``ends`` is an Tensor, it should be an 1-D Tensor . It represents ending indices of corresponding axis in ``axes``. + strides (list|tuple|Tensor): The data type is ``int32`` . If ``strides`` is a list or tuple, the elements of + it should be integers or Tensors with shape [1]. If ``strides`` is an Tensor, it should be an 1-D Tensor . It represents slice step of corresponding axis in ``axes``. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Returns: + Tensor: A ``Tensor`` with the same dimension as ``x``. The data type is same as ``x``. + + Examples: + .. code-block:: python + + import paddle + x = paddle.zeros(shape=[3,4,5,6], dtype="float32") + # example 1: + # attr starts is a list which doesn't contain Tensor. + axes = [1, 2, 3] + starts = [-3, 0, 2] + ends = [3, 2, 4] + strides_1 = [1, 1, 1] + strides_2 = [1, 1, 2] + sliced_1 = paddle.strided_slice(x, axes=axes, starts=starts, ends=ends, strides=strides_1) + # sliced_1 is x[:, 1:3:1, 0:2:1, 2:4:1]. + # example 2: + # attr starts is a list which contain tensor Tensor. + minus_3 = paddle.full(shape=[1], fill_value=-3, dtype='int32') + sliced_2 = paddle.strided_slice(x, axes=axes, starts=[minus_3, 0, 2], ends=ends, strides=strides_2) + # sliced_2 is x[:, 1:3:1, 0:2:1, 2:4:2]. + """ + if in_dygraph_mode(): + return _C_ops.strided_slice(x, axes, starts, ends, strides) + + helper = LayerHelper('strided_slice', **locals()) + + check_variable_and_dtype( + x, + 'x', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'strided_slice', + ) + check_type(axes, 'axes', (list, tuple), 'strided_slice') + check_type(starts, 'starts', (list, tuple, Variable), 'strided_slice') + check_type(ends, 'ends', (list, tuple, Variable), 'strided_slice') + check_type(strides, 'strides', (list, tuple, Variable), 'strided_slice') + + def check_list_elements_dtype(list_input, input_name): + if isinstance(list_input, Variable): + check_dtype( + list_input.dtype, input_name, ['int32'], 'strided_slice' + ) + else: + for i, var in enumerate(list_input): + var_name = input_name + '[' + str(i) + ']' + if isinstance(var, Variable): + check_dtype(var.dtype, var_name, ['int32'], 'strided_slice') + + check_list_elements_dtype(axes, 'axes') + check_list_elements_dtype(starts, 'starts') + check_list_elements_dtype(ends, 'ends') + check_list_elements_dtype(strides, 'strides') + + def get_new_list_tensor(old_list): + new_list_tensor = [] + for dim in old_list: + if isinstance(dim, Variable): + dim.stop_gradient = True + new_list_tensor.append(dim) + else: + assert isinstance(dim, int) + temp_out = helper.create_variable_for_type_inference('int32') + fill_constant([1], 'int32', dim, force_cpu=True, out=temp_out) + new_list_tensor.append(temp_out) + return new_list_tensor + + inputs = {'Input': x} + attrs = {'axes': axes} + infer_flags = list(1 for i in range(len(axes))) + + if _in_legacy_dygraph(): + inputs = {'Input': x} + attrs = { + 'axes': axes, + 'starts': starts, + 'ends': ends, + 'strides': strides, + 'infer_flags': infer_flags, + } + else: + # starts + if isinstance(starts, Variable): + starts.stop_gradient = True + inputs['StartsTensor'] = starts + elif isinstance(starts, (list, tuple)): + attrs['starts'] = [] + if utils._contain_var(starts): + inputs['StartsTensorList'] = get_new_list_tensor(starts) + for i, dim in enumerate(starts): + if isinstance(dim, Variable): + attrs['starts'].append(-1) + infer_flags[i] = -1 + else: + attrs['starts'].append(dim) + else: + attrs['starts'] = starts + + # ends + if isinstance(ends, Variable): + ends.stop_gradient = True + inputs['EndsTensor'] = ends + elif isinstance(ends, (list, tuple)): + attrs['ends'] = [] + if utils._contain_var(ends): + inputs['EndsTensorList'] = get_new_list_tensor(ends) + for i, dim in enumerate(ends): + if isinstance(dim, Variable): + attrs['ends'].append(-1) + infer_flags[i] = -1 + else: + attrs['ends'].append(dim) + else: + attrs['ends'] = ends + + # strides + if isinstance(strides, Variable): + strides.stop_gradient = True + inputs['StridesTensor'] = strides + elif isinstance(strides, (list, tuple)): + attrs['strides'] = [] + if utils._contain_var(strides): + inputs['StridesTensorList'] = get_new_list_tensor(strides) + for i, dim in enumerate(strides): + if isinstance(dim, Variable): + attrs['strides'].append(-1) + infer_flags[i] = -1 + else: + attrs['strides'].append(dim) + else: + attrs['strides'] = strides + attrs['infer_flags'] = infer_flags + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('x') + ) + helper.append_op( + type='strided_slice', inputs=inputs, attrs=attrs, outputs={'Out': out} + ) + + return out + + +def tensordot(x, y, axes=2, name=None): + r""" + This function computes a contraction, which sum the product of elements from two tensors along the given axes. + + Args: + x (Tensor): The left tensor for contraction with data type ``float32`` or ``float64``. + y (Tensor): The right tensor for contraction with the same data type as ``x``. + axes (int|tuple|list|Tensor, optional): The axes to contract for ``x`` and ``y``, defaulted to integer ``2``. + + 1. It could be a non-negative integer ``n``, + in which the function will sum over the last ``n`` axes of ``x`` and the first ``n`` axes of ``y`` in order. + + 2. It could be a 1-d tuple or list with data type ``int``, in which ``x`` and ``y`` will be contracted along the same given axes. + For example, ``axes`` =[0, 1] applies contraction along the first two axes for ``x`` and the first two axes for ``y``. + + 3. It could be a tuple or list containing one or two 1-d tuple|list|Tensor with data type ``int``. + When containing one tuple|list|Tensor, the data in tuple|list|Tensor specified the same axes for ``x`` and ``y`` to contract. + When containing two tuple|list|Tensor, the first will be applied to ``x`` and the second to ``y``. + When containing more than two tuple|list|Tensor, only the first two axis sequences will be used while the others will be ignored. + + 4. It could be a tensor, in which the ``axes`` tensor will be translated to a python list + and applied the same rules described above to determine the contraction axes. + Note that the ``axes`` with Tensor type is ONLY available in Dygraph mode. + name(str, optional): The default value is None. Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` . + + Return: + Output (Tensor): The contraction result with the same data type as ``x`` and ``y``. + In general, :math:`output.ndim = x.ndim + y.ndim - 2 \times n_{axes}`, where :math:`n_{axes}` denotes the number of axes to be contracted. + + NOTES: + 1. This function supports tensor broadcast, + the size in the corresponding dimensions of ``x`` and ``y`` should be equal, or applies to the broadcast rules. + 2. This function also supports axes expansion, + when the two given axis sequences for ``x`` and ``y`` are of different lengths, + the shorter sequence will expand the same axes as the longer one at the end. + For example, if ``axes`` =[[0, 1, 2, 3], [1, 0]], + the axis sequence for ``x`` is [0, 1, 2, 3], + while the corresponding axis sequences for ``y`` will be expanded from [1, 0] to [1, 0, 2, 3]. + + Examples: + .. code-block:: python + + import paddle + + data_type = 'float64' + + # For two 2-d tensor x and y, the case axes=0 is equivalent to outer product. + # Note that tensordot supports empty axis sequence, so all the axes=0, axes=[], axes=[[]], and axes=[[],[]] are equivalent cases. + x = paddle.arange(4, dtype=data_type).reshape([2, 2]) + y = paddle.arange(4, dtype=data_type).reshape([2, 2]) + z = paddle.tensordot(x, y, axes=0) + # z = [[[[0., 0.], + # [0., 0.]], + # + # [[0., 1.], + # [2., 3.]]], + # + # + # [[[0., 2.], + # [4., 6.]], + # + # [[0., 3.], + # [6., 9.]]]] + + + # For two 1-d tensor x and y, the case axes=1 is equivalent to inner product. + x = paddle.arange(10, dtype=data_type) + y = paddle.arange(10, dtype=data_type) + z1 = paddle.tensordot(x, y, axes=1) + z2 = paddle.dot(x, y) + # z1 = z2 = [285.] + + + # For two 2-d tensor x and y, the case axes=1 is equivalent to matrix multiplication. + x = paddle.arange(6, dtype=data_type).reshape([2, 3]) + y = paddle.arange(12, dtype=data_type).reshape([3, 4]) + z1 = paddle.tensordot(x, y, axes=1) + z2 = paddle.matmul(x, y) + # z1 = z2 = [[20., 23., 26., 29.], + # [56., 68., 80., 92.]] + + + # When axes is a 1-d int list, x and y will be contracted along the same given axes. + # Note that axes=[1, 2] is equivalent to axes=[[1, 2]], axes=[[1, 2], []], axes=[[1, 2], [1]], and axes=[[1, 2], [1, 2]]. + x = paddle.arange(24, dtype=data_type).reshape([2, 3, 4]) + y = paddle.arange(36, dtype=data_type).reshape([3, 3, 4]) + z = paddle.tensordot(x, y, axes=[1, 2]) + # z = [[506. , 1298., 2090.], + # [1298., 3818., 6338.]] + + + # When axes is a list containing two 1-d int list, the first will be applied to x and the second to y. + x = paddle.arange(60, dtype=data_type).reshape([3, 4, 5]) + y = paddle.arange(24, dtype=data_type).reshape([4, 3, 2]) + z = paddle.tensordot(x, y, axes=([1, 0], [0, 1])) + # z = [[4400., 4730.], + # [4532., 4874.], + # [4664., 5018.], + # [4796., 5162.], + # [4928., 5306.]] + + + # Thanks to the support of axes expansion, axes=[[0, 1, 3, 4], [1, 0, 3, 4]] can be abbreviated as axes= [[0, 1, 3, 4], [1, 0]]. + x = paddle.arange(720, dtype=data_type).reshape([2, 3, 4, 5, 6]) + y = paddle.arange(720, dtype=data_type).reshape([3, 2, 4, 5, 6]) + z = paddle.tensordot(x, y, axes=[[0, 1, 3, 4], [1, 0]]) + # z = [[23217330., 24915630., 26613930., 28312230.], + # [24915630., 26775930., 28636230., 30496530.], + # [26613930., 28636230., 30658530., 32680830.], + # [28312230., 30496530., 32680830., 34865130.]] + """ + op_type = 'tensordot' + input_dtype = ['float32', 'float64'] + + check_variable_and_dtype(x, 'x', input_dtype, op_type) + check_variable_and_dtype(y, 'y', input_dtype, op_type) + check_type(axes, 'axes', (int, tuple, list, Variable), op_type) + + def _var_to_list(var): + if paddle.in_dynamic_mode(): + return tolist(var) + raise TypeError( + "The 'axes' with type 'Tensor' in " + + op_type + + " is not available in static graph mode, " + "please convert its type to int|Tuple|List, or use dynamic graph mode." + ) + + axes_x = [] + axes_y = [] + if np.issubdtype(type(axes), np.integer): + assert axes >= 0, ( + "The 'axes' in " + + op_type + + f" should not be negative, but received axes={axes}." + ) + axes_x = range(x.ndim - axes, x.ndim) + axes_y = range(axes) + else: + if isinstance(axes, Variable): + axes = _var_to_list(axes) + + if not axes or np.issubdtype(type(axes[0]), np.integer): + axes_x = axes + else: + axes_x = axes[0] + if len(axes) > 1: + axes_y = axes[1] + + if isinstance(axes_x, Variable): + axes_x = _var_to_list(axes_x) + if isinstance(axes_y, Variable): + axes_y = _var_to_list(axes_y) + + axes_x, axes_y = list(axes_x), list(axes_y) + len_axes_x, len_axes_y = len(axes_x), len(axes_y) + if len_axes_x < len_axes_y: + axes_x.extend(axes_y[len_axes_x:]) + elif len_axes_y < len_axes_x: + axes_y.extend(axes_x[len_axes_y:]) + + shape_x, shape_y = list(x.shape), list(y.shape) + need_contracted_dim_x = np.zeros((x.ndim), dtype=bool) + need_contracted_dim_y = np.zeros((y.ndim), dtype=bool) + contraction_size = 1 + for i in range(len(axes_x)): + dim_x, dim_y = axes_x[i], axes_y[i] + sx, sy = shape_x[dim_x], shape_y[dim_y] + if sx == 1: + shape_y[dim_y] = 1 + y = y.sum(dim_y).reshape(shape_y) + elif sy == 1: + shape_x[dim_x] = 1 + x = x.sum(dim_x).reshape(shape_x) + else: + assert sx == sy, ( + "The dimensional size for 'x' and 'y' in " + + op_type + + f" should match each other, but 'x' has size {sx} in dim {dim_x} while 'y' has size {sy} in dim {dim_y}." + ) + + need_contracted_dim_x[dim_x] = True + need_contracted_dim_y[dim_y] = True + contraction_size *= shape_x[dim_x] + + perm_x = [] + perm_y = [] + shape_out = [] + not_contraction_size_x = 1 + not_contraction_size_y = 1 + for i in range(x.ndim): + if not need_contracted_dim_x[i]: + perm_x.append(i) + shape_out.append(shape_x[i]) + not_contraction_size_x *= shape_x[i] + perm_x.extend(axes_x) + perm_y.extend(axes_y) + for i in range(y.ndim): + if not need_contracted_dim_y[i]: + perm_y.append(i) + shape_out.append(shape_y[i]) + not_contraction_size_y *= shape_y[i] + + if not shape_out: + shape_out = [1] + + x = x.transpose(perm=perm_x).reshape( + [not_contraction_size_x, contraction_size] + ) + y = y.transpose(perm=perm_y).reshape( + [contraction_size, not_contraction_size_y] + ) + out = x.matmul(y).reshape(shape_out) + return out + + +def as_complex(x, name=None): + """Transform a real tensor to a complex tensor. + + The data type of the input tensor is 'float32' or 'float64', and the data + type of the returned tensor is 'complex64' or 'complex128', respectively. + + The shape of the input tensor is ``(* ,2)``, (``*`` means arbitary shape), i.e. + the size of the last axis shoule be 2, which represent the real and imag part + of a complex number. The shape of the returned tensor is ``(*,)``. + + Args: + x (Tensor): The input tensor. Data type is 'float32' or 'float64'. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output. Data type is 'complex64' or 'complex128', with the same precision as the input. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2]) + y = paddle.as_complex(x) + print(y) + + # Tensor(shape=[2, 3], dtype=complex64, place=Place(gpu:0), stop_gradient=True, + # [[1j , (2+3j) , (4+5j) ], + # [(6+7j) , (8+9j) , (10+11j)]]) + """ + if in_dygraph_mode(): + return _C_ops.as_complex(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.as_complex(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'as_complex') + op_type = "as_complex" + helper = LayerHelper(op_type, **locals()) + inputs = {"X": x} + out = helper.create_variable_for_type_inference( + dtype=_real_to_complex_dtype(x.dtype) + ) + outputs = {"Out": out} + attrs = {} + helper.append_op(type=op_type, inputs=inputs, attrs=attrs, outputs=outputs) + return out + + +def as_real(x, name=None): + """Transform a complex tensor to a real tensor. + + The data type of the input tensor is 'complex64' or 'complex128', and the data + type of the returned tensor is 'float32' or 'float64', respectively. + + When the shape of the input tensor is ``(*, )``, (``*`` means arbitary shape), + the shape of the output tensor is ``(*, 2)``, i.e. the shape of the output is + the shape of the input appended by an extra ``2``. + + Args: + x (Tensor): The input tensor. Data type is 'complex64' or 'complex128'. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output. Data type is 'float32' or 'float64', with the same precision as the input. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2]) + y = paddle.as_complex(x) + z = paddle.as_real(y) + print(z) + + # Tensor(shape=[2, 3, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[0. , 1. ], + # [2. , 3. ], + # [4. , 5. ]], + + # [[6. , 7. ], + # [8. , 9. ], + # [10., 11.]]]) + """ + if in_dygraph_mode(): + return _C_ops.as_real(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.as_real(x) + + check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'as_real') + op_type = "as_real" + helper = LayerHelper(op_type, **locals()) + inputs = {"X": x} + out = helper.create_variable_for_type_inference( + dtype=_complex_to_real_dtype(x.dtype) + ) + outputs = {"Out": out} + helper.append_op(type=op_type, inputs=inputs, outputs=outputs) + return out + + +def repeat_interleave(x, repeats, axis=None, name=None): + """ + + Returns a new tensor which repeats the ``x`` tensor along dimension ``axis`` using + the entries in ``repeats`` which is a int or a Tensor. + + Args: + x (Tensor): The input Tensor to be operated. The data of ``x`` can be one of float32, float64, int32, int64. + repeats (Tensor or int): The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis. + axis (int, optional): The dimension in which we manipulate. Default: None, the output tensor is flatten. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor with same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) + repeats = paddle.to_tensor([3, 2, 1], dtype='int32') + + paddle.repeat_interleave(x, repeats, 1) + # [[1, 1, 1, 2, 2, 3], + # [4, 4, 4, 5, 5, 6]] + + paddle.repeat_interleave(x, 2, 0) + # [[1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6]] + + paddle.repeat_interleave(x, 2, None) + # [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + """ + + if axis is None: + x = paddle.flatten(x) + axis = 0 + + if in_dygraph_mode(): + if isinstance(repeats, Variable): + return _C_ops.repeat_interleave_with_tensor_index(x, repeats, axis) + return _C_ops.repeat_interleave(x, repeats, axis) + + helper = LayerHelper("repeat_interleave", **locals()) + check_variable_and_dtype( + x, + 'x', + ['float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.manipulation.repeat_interleave', + ) + + out = helper.create_variable_for_type_inference(x.dtype) + + helper.append_op( + type='repeat_interleave', + inputs={ + 'X': x, + 'RepeatsTensor': repeats if isinstance(repeats, Variable) else None, + }, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'Repeats': repeats if isinstance(repeats, int) else 0, + }, + ) + return out + + +def moveaxis(x, source, destination, name=None): + """ + Move the axis of tensor from ``source`` position to ``destination`` position. + + Other axis that have not been moved remain their original order. + + Args: + x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, int32, int64, float32, float64, complex64, complex128. + source(int|tuple|list): ``source`` position of axis that will be moved. Each element must be unique and integer. + destination(int|tuple|list(int)): ``destination`` position of axis that has been moved. Each element must be unique and integer. + name(str, optional): The default value is None. Normally there is no need for user to set this + property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A new tensor whose axis have been moved. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.ones([3, 2, 4]) + paddle.moveaxis(x, [0, 1], [1, 2]).shape + # [4, 3, 2] + + x = paddle.ones([2, 3]) + paddle.moveaxis(x, 0, 1).shape # equivalent to paddle.t(x) + # [3, 2] + """ + src = [source] if isinstance(source, int) else source + dst = [destination] if isinstance(destination, int) else destination + + assert len(src) == len( + dst + ), "'source' must have the same number with 'destination'" + + count = Counter(src).most_common(1) + if count[0][1] > 1: + raise ValueError("Each elemment of 'source' must be unique!") + count = Counter(dst).most_common(1) + if count[0][1] > 1: + raise ValueError("Each elemment of 'destination' must be unique!") + + ndim = len(x.shape) + + # perm is the new order after move axis + perm = list(range(ndim)) + src_dims = list(range(ndim)) + dst_dims = list(range(ndim)) + + for i, axis in enumerate(zip(src, dst)): + assert isinstance( + axis[0], int + ), "Each elemment of 'source' must be integer." + if axis[0] < 0: + assert ( + axis[0] >= -ndim + ), "'source' must be in the range of [-{0}, {0})".format(ndim) + src[i] += ndim + else: + assert ( + axis[0] < ndim + ), "'source' must be in the range of [-{0}, {0})".format(ndim) + + assert isinstance( + axis[1], int + ), "Each elemment of 'source' must be integer." + if axis[1] < 0: + assert ( + axis[1] >= -ndim + ), "'source' must be in the range of [-{0}, {0})".format(ndim) + dst[i] += ndim + else: + assert ( + axis[1] < ndim + ), "'source' must be in the range of [-{0}, {0})".format(ndim) + perm[dst[i]] = src[i] + src_dims.remove(src[i]) + dst_dims.remove(dst[i]) + + for i in range(len(src_dims)): + perm[dst_dims[i]] = src_dims[i] + + if in_dygraph_mode(): + out = _C_ops.transpose(x, perm) + return out + + if _in_legacy_dygraph(): + out, _ = _legacy_C_ops.transpose2(x, 'axis', perm) + return out + + check_variable_and_dtype( + x, + 'x', + [ + 'bool', + 'float16', + 'float32', + 'float64', + 'int32', + 'int64', + 'complex64', + 'complex128', + ], + 'moveaxis', + ) + + helper = LayerHelper('moveaxis', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + x_shape = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='transpose2', + inputs={'X': [x]}, + outputs={'Out': [out], 'XShape': [x_shape]}, + attrs={'axis': perm}, + ) + return out + + +def non_negative_axis(arr, axis): + ndim = len(arr.shape) + if axis >= 0: + assert ( + axis < ndim + ), "'axis' must be in the range of [-{0}, {0})".format(ndim) + else: + assert ( + axis >= -ndim + ), "'axis' must be in the range of [-{0}, {0})".format(ndim) + axis += ndim + + return axis + + +def infer_broadcast_shape(arr, indices, axis): + # This function is used in take/put_along_axis + broadcast_shape_list = list(arr.shape) + broadcast_shape_list[axis] = list(indices.shape)[axis] + broadcast_shape = tuple(broadcast_shape_list) + for i in range(len(arr.shape)): + if arr.shape[i] < indices.shape[i]: + # if indices matrix has larger size than arr matrix, do not broadcast. + return None + return broadcast_shape + + +def take_along_axis(arr, indices, axis): + """ + Take values from the input array by given indices matrix along the designated axis. + + Args: + arr (Tensor) : The input Tensor. Supported data types are float32 and float64. + indices (Tensor) : Indices to take along each 1d slice of arr. This must match the dimension of arr, + and need to broadcast against arr. Supported data type are int and int64. + axis (int) : The axis to take 1d slices along. + + Returns: + Tensor: The indexed element, same dtype with arr + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7,8,9]]) + index = paddle.to_tensor([[0]]) + axis = 0 + result = paddle.take_along_axis(x, index, axis) + print(result) + # [[1, 2, 3]] + """ + if len(arr.shape) != len(indices.shape): + raise ValueError( + "`indices` and `arr` must have the same number of dimensions!" + ) + axis = non_negative_axis(arr, axis) + broadcast_shape = infer_broadcast_shape(arr, indices, axis) + if not broadcast_shape: + # if indices matrix have larger size than arr, arr should broadcast into indices shape. + broadcast_shape = indices.shape + if _non_static_mode(): + indices = paddle.broadcast_to(indices, broadcast_shape) + broadcast_shape_list = list(broadcast_shape) + broadcast_shape_list[axis] = list(arr.shape)[axis] + broadcast_shape = tuple(broadcast_shape_list) + arr = paddle.broadcast_to(arr, broadcast_shape) + if not _in_legacy_dygraph(): + return _C_ops.take_along_axis(arr, indices, axis) + return _legacy_C_ops.take_along_axis(arr, indices, 'Axis', axis) + check_variable_and_dtype( + arr, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'], + 'take_along_axis', + ) + check_variable_and_dtype( + indices, 'index', ['int32', 'int64'], 'take_along_axis' + ) + indices = paddle.broadcast_to(indices, broadcast_shape) + broadcast_shape_list = list(broadcast_shape) + broadcast_shape_list[axis] = list(arr.shape)[axis] + broadcast_shape = tuple(broadcast_shape_list) + arr = paddle.broadcast_to(arr, broadcast_shape) + helper = LayerHelper('take_along_axis', **locals()) + dtype = helper.input_dtype() + result = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="take_along_axis", + inputs={"Input": arr, "Index": indices}, + attrs={"Axis": axis}, + outputs={"Result": result}, + ) + return result + + +def put_along_axis(arr, indices, values, axis, reduce='assign'): + """ + Put values into the destination array by given indices matrix along the designated axis. + + Args: + arr (Tensor) : The Destination Tensor. Supported data types are float32 and float64. + indices (Tensor) : Indices to put along each 1d slice of arr. This must match the dimension of arr, + and need to broadcast against arr. Supported data type are int and int64. + axis (int) : The axis to put 1d slices along. + reduce (str, optional): The reduce operation, default is 'assign', support 'add', 'assign', 'mul' and 'multiply'. + + Returns: + Tensor: The indexed element, same dtype with arr + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[10, 30, 20], [60, 40, 50]]) + index = paddle.to_tensor([[0]]) + value = 99 + axis = 0 + result = paddle.put_along_axis(x, index, value, axis) + print(result) + # [[99, 99, 99], + # [60, 40, 50]] + + """ + if len(arr.shape) != len(indices.shape): + raise ValueError( + "`indices` and `arr` must have the same number of dimensions!" + ) + axis = non_negative_axis(arr, axis) + broadcast_shape = infer_broadcast_shape(arr, indices, axis) + if _non_static_mode(): + values = ( + paddle.to_tensor(values) + if not isinstance(values, paddle.Tensor) + else values + ) + if broadcast_shape: + indices = paddle.broadcast_to(indices, broadcast_shape) + values = paddle.broadcast_to(values, indices.shape) + if in_dygraph_mode(): + return _C_ops.put_along_axis(arr, indices, values, axis, reduce) + return _legacy_C_ops.put_along_axis( + arr, indices, values, "Axis", axis, "Reduce", reduce + ) + + check_variable_and_dtype( + arr, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'], + 'put_along_axis', + ) + check_variable_and_dtype( + indices, 'index', ['int32', 'int64'], 'put_along_axis' + ) + if broadcast_shape: + indices = paddle.broadcast_to(indices, broadcast_shape) + values = paddle.broadcast_to(values, indices.shape) + helper = LayerHelper('put_along_axis', **locals()) + dtype = helper.input_dtype() + result = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="put_along_axis", + inputs={"Input": arr, "Index": indices, "Value": values}, + attrs={"Axis": axis, "Reduce": reduce}, + outputs={"Result": result}, + ) + return result + + +@inplace_apis_in_dygraph_only +def put_along_axis_(arr, indices, values, axis, reduce='assign'): + r""" + Inplace version of ``put_along_axis`` API, the output Tensor will be inplaced with input ``arr``. + Please refer to :ref:`api_tensor_put_along_axis`. + """ + if len(arr.shape) != len(indices.shape): + raise ValueError( + "`indices` and `arr` must have the same number of dimensions!" + ) + axis = non_negative_axis(arr, axis) + broadcast_shape = infer_broadcast_shape(arr, indices, axis) + values = ( + paddle.to_tensor(values) + if not isinstance(values, paddle.Tensor) + else values + ) + if broadcast_shape: + indices = paddle.broadcast_to(indices, broadcast_shape) + values = paddle.broadcast_to(values, indices.shape) + if in_dygraph_mode(): + return _C_ops.put_along_axis_(arr, indices, values, axis, reduce) + return _legacy_C_ops.put_along_axis_( + arr, indices, values, "Axis", axis, "Reduce", reduce + ) + + +def _index_add_params_check(x, index, input_axis, add_value): + dims = len(x.shape) + add_value_dims = len(add_value.shape) + + if input_axis >= 0: + axis = input_axis + else: + axis = input_axis + dims + + check_axis = axis + if check_axis >= dims or check_axis < -dims: + raise ValueError("Axis should be in range [-rank(x), rank(x)).") + + if isinstance(index, Variable): + if index.dtype not in [paddle.int64, paddle.int32]: + raise TypeError("The index dtype should be int32 or int64.") + if len(index.shape) != 1: + raise ValueError("The index should be a 1-D Tensor.") + + if dims != add_value_dims: + raise ValueError( + "The add_value does not support broadcast now. It must have the same dimension as x." + ) + for i in range(dims): + if i != axis and x.shape[i] != add_value.shape[i]: + raise ValueError( + "The add_value.shape[i] should be equal to x.shape[i] when i != axis." + ) + + +def index_add(x, index, axis, value, name=None): + """ + Adds the elements of the input tensor with value tensor by selecting the indices in the order given in index. + + Args: + x (Tensor) : The Destination Tensor. Supported data types are int32, int64, float16, float32, float64. + index (Tensor): The 1-D Tensor containing the indices to index. + The data type of ``index`` must be int32 or int64. + axis (int): The dimension in which we index. + value (Tensor): The tensor used to add the elements along the target axis. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: same dimention and dtype with x. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + input_tensor = paddle.to_tensor(paddle.ones((3, 3)), dtype="float32") + index = paddle.to_tensor([0, 2], dtype="int32") + value = paddle.to_tensor([[1, 1, 1], [1, 1, 1]], dtype="float32") + outplace_res = paddle.index_add(input_tensor, index, 0, value) + print(outplace_res) + # Tensor(shape=[3, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[2., 2., 2.], + # [1., 1., 1.], + # [2., 2., 2.]]) + """ + _index_add_params_check(x, index, axis, value) + + if in_dygraph_mode(): + return _C_ops.index_add(x, index, value, axis) + + helper = LayerHelper("index_add", **locals()) + check_variable_and_dtype( + x, + 'x', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.manipulation.index_add', + ) + check_variable_and_dtype( + index, + 'index', + ['int32', 'int64'], + 'paddle.tensor.manipulation.index_add', + ) + check_variable_and_dtype( + value, + 'add_value', + ['float16', 'float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.manipulation.index_add', + ) + + out = helper.create_variable_for_type_inference(x.dtype) + + helper.append_op( + type='index_add', + inputs={ + 'X': x, + 'Index': index, + 'AddValue': value, + }, + outputs={'Out': out}, + attrs={'axis': axis}, + ) + return out + + +@inplace_apis_in_dygraph_only +def index_add_(x, index, axis, value, name=None): + """ + Inplace version of ``index_add`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_paddle_tensor_index_add`. + + Examples: + .. code-block:: python + + # required: gpu + import paddle + + input_tensor = paddle.to_tensor(paddle.ones((3, 3)), dtype="float32") + index = paddle.to_tensor([0, 2], dtype="int32") + value = paddle.to_tensor([[1, 1], [1, 1], [1, 1]], dtype="float32") + inplace_res = paddle.index_add_(input_tensor, index, 1, value) + print(inplace_res) + # Tensor(shape=[3, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[2., 1., 2.], + # [2., 1., 2.], + # [2., 1., 2.]]) + """ + + _index_add_params_check(x, index, axis, value) + return _C_ops.index_add_(x, index, value, axis) + + +# TODO(dev): We need avoid implementing it by this way. +__METHODS = { + 'fill_': fill_, + 'zero_': zero_, + 'fill_diagonal_': fill_diagonal_, + 'fill_diagonal_tensor_': fill_diagonal_tensor_, + "fill_diagonal_tensor": fill_diagonal_tensor, + 'tolist': tolist, +} +for name, func in __METHODS.items(): + setattr(core.VarBase, name, func) + setattr(core.eager.Tensor, name, func) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/math.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/math.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5523c47a0337a24fe96ee78f2c9982541b9352 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/math.py @@ -0,0 +1,4936 @@ +# 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. +""" +math functions +""" +from __future__ import print_function +import numpy as np + +from paddle.common_ops_import import VarDesc +from paddle.common_ops_import import dygraph_only +from paddle.common_ops_import import OpProtoHolder +from paddle.common_ops_import import templatedoc +from paddle.common_ops_import import dygraph_utils + +from .manipulation import cast +from .creation import _complex_to_real_dtype +from .layer_function_generator import ( + _generate_doc_string_, + generate_activation_fn, + generate_layer_fn, +) + +import paddle +from ..static import Variable +from ..framework import ( + core, + in_dygraph_mode, + _non_static_mode, + LayerHelper, + _in_legacy_dygraph, +) +from ..fluid.framework import _in_legacy_dygraph +from ..framework import _varbase_creator, convert_np_dtype_to_dtype_ +from ..fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, + convert_dtype, +) +from ..fluid.dygraph.inplace_utils import inplace_apis_in_dygraph_only +from ..fluid.layers import utils + +# TODO: define math functions +# yapf: disable +from .ops import abs # noqa: F401 +from .ops import acos # noqa: F401 +from .ops import asin # noqa: F401 +from .ops import ceil # noqa: F401 +from .ops import ceil_ # noqa: F401 +from .ops import cos # noqa: F401 +from .ops import tan # noqa: F401 +from .ops import sinh # noqa: F401 +from .ops import cosh # noqa: F401 +from .ops import exp # noqa: F401 +from .ops import exp_ # noqa: F401 +from .ops import expm1 # noqa: F401 +from .ops import floor # noqa: F401 +from .ops import floor_ # noqa: F401 +from .ops import reciprocal # noqa: F401 +from .ops import reciprocal_ # noqa: F401 +from .ops import round # noqa: F401 +from .ops import round_ # noqa: F401 +from .ops import rsqrt # noqa: F401 +from .ops import rsqrt_ # noqa: F401 +from .ops import square # noqa: F401 +from .ops import atan # noqa: F401 +from .ops import erf # noqa: F401 +from .ops import sqrt # noqa: F401 +from .ops import sqrt_ # noqa: F401 +from .ops import sin # noqa: F401 +from .ops import asinh # noqa: F401 +from .ops import acosh # noqa: F401 +from .ops import atanh # noqa: F401 + + +from ..fluid.layers import elementwise_sub +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + +_supported_int_dtype_ = [ + VarDesc.VarType.UINT8, + VarDesc.VarType.INT8, + VarDesc.VarType.INT16, + VarDesc.VarType.INT32, + VarDesc.VarType.INT64, +] + +_supported_float_dtype_ = [ + VarDesc.VarType.FP32, + VarDesc.VarType.FP64, +] + + +def log(x, name=None): + r""" + Calculates the natural log of the given input Tensor, element-wise. + + .. math:: + + Out = \ln(x) + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` + + + Returns: + Tensor: The natural log of the input Tensor computed element-wise. + + Examples: + + .. code-block:: python + + import paddle + + x = [[2,3,4], [7,8,9]] + x = paddle.to_tensor(x, dtype='float32') + res = paddle.log(x) + # [[0.693147, 1.09861, 1.38629], [1.94591, 2.07944, 2.19722]] + """ + if in_dygraph_mode(): + return _C_ops.log(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.log(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], "log") + inputs = {'X': [x]} + helper = LayerHelper('log', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="log", inputs={"X": x}, outputs={"Out": out}) + return out + + +def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): + """ + Scale operator. + + Putting scale and bias to the input Tensor as following: + + ``bias_after_scale`` is True: + + .. math:: + Out=scale*X+bias + + ``bias_after_scale`` is False: + + .. math:: + Out=scale*(X+bias) + + Args: + x (Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8. + scale (float|Tensor): The scale factor of the input, it should be a float number or a Tensor with shape [1] and data type as float32. + bias (float): The bias to be put on the input. + bias_after_scale (bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances. + act (str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Output Tensor of scale operator, with shape and data type same as input. + + Examples: + .. code-block:: python + + # scale as a float32 number + import paddle + + data = paddle.randn(shape=[2,3], dtype='float32') + res = paddle.scale(data, scale=2.0, bias=1.0) + + .. code-block:: python + + # scale with parameter scale as a Tensor + import paddle + + data = paddle.randn(shape=[2, 3], dtype='float32') + factor = paddle.to_tensor([2], dtype='float32') + res = paddle.scale(data, scale=factor, bias=1.0) + + """ + + if in_dygraph_mode(): + out = _C_ops.scale(x, scale, float(bias), bias_after_scale) + return dygraph_utils._append_activation_in_dygraph(out, act) + elif _in_legacy_dygraph(): + _scale = scale.numpy().item(0) if isinstance(scale, Variable) else scale + out = _legacy_C_ops.scale(x, 'scale', + float(_scale), 'bias', + float(bias), 'bias_after_scale', bias_after_scale) + return dygraph_utils._append_activation_in_dygraph(out, act) + + check_variable_and_dtype(x, "x", [ + 'float16', 'uint16', 'float32', 'float64', 'int8', 'int16', 'int32', + 'int64', 'uint8' + ], "scale") + inputs = {'X': [x]} + attrs = { + 'bias': float(bias), + 'bias_after_scale': bias_after_scale, + } + if isinstance(scale, Variable): + inputs['ScaleTensor'] = [scale] + else: + attrs['scale'] = float(scale) + helper = LayerHelper('scale', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='scale', inputs=inputs, outputs={'Out': out}, attrs=attrs) + return helper.append_activation(out) + + +def stanh(x, scale_a=0.67, scale_b=1.7159, name=None): + r""" + + stanh activation. + + .. math:: + + out = b * \frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}} + + Parameters: + x (Tensor): The input Tensor with data type float32, float64. + scale_a (float, optional): The scale factor a of the input. Default is 0.67. + scale_b (float, optional): The scale factor b of the output. Default is 1.7159. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = paddle.stanh(x, scale_a=0.67, scale_b=1.72) # [1.00616539, 1.49927628, 1.65933108, 1.70390463] + + """ + + if _non_static_mode(): + return _legacy_C_ops.stanh(x, 'scale_a', scale_a, 'scale_b', scale_b) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'stanh') + + helper = LayerHelper('stanh', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='stanh', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'scale_a': scale_a, + 'scale_b': scale_b}) + return out + +def multiplex(inputs, index, name=None): + """ + + Based on the given index parameter, the OP selects a specific row from each input Tensor to construct the output Tensor. + + If the input of this OP contains :math:`m` Tensors, where :math:`I_{i}` means the i-th input Tensor, :math:`i` between :math:`[0,m)` . + + And :math:`O` means the output, where :math:`O[i]` means the i-th row of the output, then the output satisfies that :math:`O[i] = I_{index[i]}[i]` . + + For Example: + + .. code-block:: text + + Given: + + inputs = [[[0,0,3,4], [0,1,3,4], [0,2,4,4], [0,3,3,4]], + [[1,0,3,4], [1,1,7,8], [1,2,4,2], [1,3,3,4]], + [[2,0,3,4], [2,1,7,8], [2,2,4,2], [2,3,3,4]], + [[3,0,3,4], [3,1,7,8], [3,2,4,2], [3,3,3,4]]] + + index = [[3],[0],[1],[2]] + + out = [[3,0,3,4], # out[0] = inputs[index[0]][0] = inputs[3][0] = [3,0,3,4] + [0,1,3,4], # out[1] = inputs[index[1]][1] = inputs[0][1] = [0,1,3,4] + [1,2,4,2], # out[2] = inputs[index[2]][2] = inputs[1][2] = [1,2,4,2] + [2,3,3,4]] # out[3] = inputs[index[3]][3] = inputs[2][3] = [2,3,3,4] + + + Args: + inputs (list): The input Tensor list. The list elements are N-D Tensors of data types float32, float64, int32, int64. All input Tensor shapes should be the same and rank must be at least 2. + index (Tensor): Used to select some rows in the input Tensor to construct an index of the output Tensor. It is a 2-D Tensor with data type int32 or int64 and shape [M, 1], where M is the number of input Tensors. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Output of multiplex OP, with data type being float32, float64, int32, int64. + + Examples: + + .. code-block:: python + + import paddle + + img1 = paddle.to_tensor([[1, 2], [3, 4]], dtype=paddle.float32) + img2 = paddle.to_tensor([[5, 6], [7, 8]], dtype=paddle.float32) + inputs = [img1, img2] + index = paddle.to_tensor([[1], [0]], dtype=paddle.int32) + res = paddle.multiplex(inputs, index) + print(res) # Tensor([[5., 6.], [3., 4.]], dtype=float32) + + """ + if in_dygraph_mode(): + return _C_ops.multiplex(inputs, index) + elif _in_legacy_dygraph(): + return _legacy_C_ops.multiplex(index, inputs) + + helper = LayerHelper('multiplex', **locals()) + + check_type(inputs, 'inputs', (list), 'multiplex') + if len(inputs) < 2: + raise ValueError( + "inputs should be a list object with at least 2 elements.") + for id, x in enumerate(inputs): + check_variable_and_dtype(x, 'input[' + str(id) + ']', + ['float32', 'float64', 'int32', 'int64'], + 'multiplex') + check_variable_and_dtype(index, "index", ['int32', 'int64'], 'multiplex') + + out = helper.create_variable_for_type_inference(inputs[0].dtype) + helper.append_op( + type='multiplex', + inputs={'X': inputs, + 'Ids': index}, + outputs={'Out': [out]}) + return out + +@inplace_apis_in_dygraph_only +def scale_(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None): + """ + Inplace version of ``scale`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_scale`. + """ + if in_dygraph_mode(): + return _C_ops.scale_(x, scale, float(bias), bias_after_scale) + if _in_legacy_dygraph(): + _scale = scale.numpy().item(0) if isinstance(scale, Variable) else scale + return _legacy_C_ops.scale_(x, 'scale', + float(_scale), 'bias', + float(bias), 'bias_after_scale', bias_after_scale) + + +def pow(x, y, name=None): + """ + Compute the power of Tensor elements. The equation is: + + .. math:: + out = x^{y} + + Note: + ``paddle.pow`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + + Args: + x (Tensor): An N-D Tensor, the data type is float16, float32, float64, int32 or int64. + y (float|int|Tensor): If it is an N-D Tensor, its data type should be the same as `x`. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. Its dimension and data type are the same as `x`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 2, 3], dtype='float32') + + # example 1: y is a float or int + res = paddle.pow(x, 2) + print(res) + # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [1., 4., 9.]) + res = paddle.pow(x, 2.5) + print(res) + # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [1. , 5.65685415 , 15.58845711]) + + # example 2: y is a Tensor + y = paddle.to_tensor([2], dtype='float32') + res = paddle.pow(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [1., 4., 9.]) + + """ + # in dynamic graph mode + if in_dygraph_mode(): + if isinstance(y, (int, float)): + return _C_ops.pow(x, y) + elif isinstance(y, (paddle.Tensor, Variable)): + return _C_ops.elementwise_pow(x, y) + else: + raise TypeError('y must be scalar or tensor type, but received: %s '% (y.dtype)) + if _in_legacy_dygraph(): + if isinstance(y, (int, float)): + return _legacy_C_ops.pow(x, 'factor', y) + elif isinstance(y, (paddle.Tensor, Variable)): + return _elementwise_op_in_dygraph( + x, y, axis=-1, act=None, op_name='elementwise_pow') + else: + raise TypeError('y must be scalar or tensor type, but received: %s '% (y.dtype)) + # in static graph mode + if isinstance(y, (int, float)): + helper = LayerHelper('pow', **locals()) + inputs = {'X': x} + attrs = {'factor': y} + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs) + return out + elif isinstance(y, (paddle.Tensor, Variable)): + # TODO A potential speed improvement is supporting different types in C++ and removing the cast ops here + helper = LayerHelper('elementwise_pow', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + return _elementwise_op(LayerHelper('elementwise_pow', **locals())) + else: + raise TypeError('y must be scalar or tensor type, but received: %s '% (type(y))) + + +OP_NAMEMAPPING = { + 'elementwise_max': 'maximum', + 'elementwise_min': 'minimum', + 'elementwise_pow': 'elementwise_pow', + 'elementwise_floordiv': 'floor_divide', + 'elementwise_add': 'add', + 'elementwise_sub': 'subtract', + 'elementwise_mul': 'multiply', + 'elementwise_div': 'divide', + 'elementwise_mod': 'remainder', +} + +@dygraph_only +def _elementwise_op_in_dygraph(x, + y, + axis=-1, + act=None, + use_mkldnn=False, + op_name=None): + def is_inplace(op_name): + return op_name[-1] == "_" + + if op_name not in OP_NAMEMAPPING.keys() or axis != -1: + op = getattr(_legacy_C_ops, op_name) + out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) + else: + if in_dygraph_mode(): + op = getattr(_C_ops, OP_NAMEMAPPING[op_name] if not is_inplace(op_name) else op_name) + out = op(x, y) + + if _in_legacy_dygraph(): + op = getattr(_legacy_C_ops, op_name) + out = op(x, y, 'axis', axis, 'use_mkldnn', use_mkldnn) + + return dygraph_utils._append_activation_in_dygraph( + out, act, use_mkldnn=use_mkldnn) + +def _elementwise_op(helper): + op_type = helper.layer_type + original_op_type = helper.kwargs.get('original_op_type', op_type) + x = helper.kwargs.get('x', None) + y = helper.kwargs.get('y', None) + + out = helper.kwargs.get('out', None) + + assert x is not None, 'x cannot be None in {}'.format(original_op_type) + assert y is not None, 'y cannot be None in {}'.format(original_op_type) + check_variable_and_dtype( + x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], + original_op_type) + check_variable_and_dtype( + y, 'y', ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'], + original_op_type) + + axis = helper.kwargs.get('axis', -1) + use_mkldnn = helper.kwargs.get('use_mkldnn', False) + name = helper.kwargs.get('name', None) + + if out is None: + if name is None: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + else: + out = helper.create_variable(name=name, dtype=x.dtype, persistable=False) + + helper.append_op( + type=op_type, + inputs={'X': x, + 'Y': y}, + outputs={'Out': out}, + attrs={'axis': axis, + 'use_mkldnn': use_mkldnn}) + return helper.append_activation(out) + + +def add(x, y, name=None): + """ + Elementwise Add Operator. + Add two tensors element-wise + The equation is: + + .. math:: + + Out=X+Y + + $X$ the tensor of any dimension. + $Y$ the tensor whose dimensions must be less than or equal to the dimensions of $X$. + + There are two cases for this operator: + + 1. The shape of $Y$ is the same with $X$. + 2. The shape of $Y$ is a continuous subsequence of $X$. + + For case 2: + + 1. Broadcast $Y$ to match the shape of $X$, where axis is the start dimension index for broadcasting $Y$ onto $X$. + 2. If $axis$ is -1 (default), $axis$=rank($X$)−rank($Y$). + 3. The trailing dimensions of size 1 for $Y$ will be ignored for the consideration of subsequence, such as shape($Y$) = (2, 1) => (2). + + For example: + + .. code-block:: python + + shape(X) = (2, 3, 4, 5), shape(Y) = (,) + shape(X) = (2, 3, 4, 5), shape(Y) = (5,) + shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2 + shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1 + shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0 + shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0 + + Args: + x (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64. + y (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64. + name (string, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + N-D Tensor. A location into which the result is stored. It’s dimension equals with x. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 4], 'float64') + y = paddle.to_tensor([1, 5, 2], 'float64') + z = paddle.add(x, y) + print(z) # [3., 8., 6. ] + """ + + if in_dygraph_mode(): + return _C_ops.add( x, y) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.elementwise_add(x, y) + else: + return _elementwise_op(LayerHelper('elementwise_add', **locals())) + + +@inplace_apis_in_dygraph_only +def add_(x, y, name=None): + """ + Inplace version of ``add`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_add`. + """ + op_type = 'elementwise_add_' + axis = -1 + + out_shape = broadcast_shape(x.shape, y.shape) + if out_shape != x.shape: + raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) + + if in_dygraph_mode(): + return _C_ops.add_(x, y) + else: + out = _elementwise_op_in_dygraph( + x, y, axis=axis, op_name=op_type) + return out + + +def subtract(x, y, name=None): + """ + Substract two tensors element-wise. The equation is: + + .. math:: + out = x - y + + Note: + ``paddle.subtract`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [7, 8]]) + y = paddle.to_tensor([[5, 6], [3, 4]]) + res = paddle.subtract(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[-4, -4], + # [ 4, 4]]) + + x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) + y = paddle.to_tensor([1, 0, 4]) + res = paddle.subtract(x, y) + print(res) + # Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[[ 0, 2, -1], + # [ 0, 2, -1]]]) + + x = paddle.to_tensor([2, float('nan'), 5], dtype='float32') + y = paddle.to_tensor([1, 4, float('nan')], dtype='float32') + res = paddle.subtract(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [1. , nan, nan]) + + x = paddle.to_tensor([5, float('inf'), -float('inf')], dtype='float64') + y = paddle.to_tensor([1, 4, 5], dtype='float64') + res = paddle.subtract(x, y) + print(res) + # Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True, + # [ 4. , inf., -inf.]) + """ + op_type = 'elementwise_sub' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.subtract(x, y) + else: + if _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + else: + return _elementwise_op(LayerHelper(op_type, **locals())) + + +@inplace_apis_in_dygraph_only +def subtract_(x, y, name=None): + """ + Inplace version of ``subtract`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_subtract`. + """ + axis = -1 + act = None + + out_shape = broadcast_shape(x.shape, y.shape) + if out_shape != x.shape: + raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) + + if in_dygraph_mode(): + return _C_ops.subtract_(x, y) + else: + out = _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name='elementwise_sub_') + return out + + +def divide(x, y, name=None): + """ + Divide two tensors element-wise. The equation is: + + .. math:: + out = x / y + + Note: + ``paddle.divide`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 4], dtype='float64') + y = paddle.to_tensor([1, 5, 2], dtype='float64') + z = paddle.divide(x, y) + print(z) # [2., 0.6, 2.] + + """ + op_type = 'elementwise_div' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.divide( x, y) + else: + if _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + else: + return _elementwise_op(LayerHelper(op_type, **locals())) + + +def floor_divide(x, y, name=None): + """ + Floor divide two tensors element-wise. The equation is: + + .. math:: + out = x // y + + Note: + ``paddle.floor_divide`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be int32, int64. + y (Tensor): the input tensor, it's data type should be int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. It's dimension equals with $x$. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 8, 7]) + y = paddle.to_tensor([1, 5, 3, 3]) + z = paddle.floor_divide(x, y) + print(z) # [2, 0, 2, 2] + + """ + op_type = 'elementwise_floordiv' + axis = -1 + if in_dygraph_mode(): + return _C_ops.floor_divide(x, y) + elif _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, op_name=op_type) + + return _elementwise_op(LayerHelper(op_type, **locals())) + + +def remainder(x, y, name=None): + r""" + Mod two tensors element-wise. The equation is: + + .. math:: + + out = x \% y + + Note: + ``paddle.remainder`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([2, 3, 8, 7]) + y = paddle.to_tensor([1, 5, 3, 3]) + z = paddle.remainder(x, y) + print(z) # [0, 3, 2, 1] + + """ + op_type = 'elementwise_mod' + axis = -1 + + if in_dygraph_mode(): + return _C_ops.remainder(x, y) + elif _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, op_name=op_type) + + return _elementwise_op(LayerHelper(op_type, **locals())) + + +@inplace_apis_in_dygraph_only +def remainder_(x, y, name=None): + r""" + Inplace version of ``remainder`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_remainder`. + """ + op_type = 'elementwise_mod_' + axis = -1 + + out_shape = broadcast_shape(x.shape, y.shape) + if out_shape != x.shape: + raise ValueError( + "The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format( + out_shape, x.shape)) + + return _elementwise_op_in_dygraph(x, y, axis=axis, op_name=op_type) + + +mod = remainder # noqa: F841 +floor_mod = remainder # noqa: F841 + + +def multiply(x, y, name=None): + """ + multiply two tensors element-wise. The equation is: + + .. math:: + out = x * y + + Note: + ``paddle.multiply`` supports broadcasting. If you would like to know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool. + y (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [3, 4]]) + y = paddle.to_tensor([[5, 6], [7, 8]]) + res = paddle.multiply(x, y) + print(res) # [[5, 12], [21, 32]] + + x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) + y = paddle.to_tensor([2]) + res = paddle.multiply(x, y) + print(res) # [[[2, 4, 6], [2, 4, 6]]] + + """ + op_type = 'elementwise_mul' + act = None + axis = -1 + + if in_dygraph_mode(): + return _C_ops.multiply(x, y) + else: + if _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + else: + if x.dtype != y.dtype: + raise TypeError( + 'Input tensors must be same type, but received type of x: %s, type of y: %s ' + % (x.dtype, y.dtype)) + + return _elementwise_op(LayerHelper(op_type, **locals())) + +def maximum(x, y, name=None): + """ + Compare two tensors and returns a new tensor containing the element-wise maxima. The equation is: + + .. math:: + out = max(x, y) + + Note: + ``paddle.maximum`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [7, 8]]) + y = paddle.to_tensor([[3, 4], [5, 6]]) + res = paddle.maximum(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[3, 4], + # [7, 8]]) + + x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + y = paddle.to_tensor([3, 0, 4]) + res = paddle.maximum(x, y) + print(res) + # Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[3, 2, 4], + # [3, 2, 4]]) + + x = paddle.to_tensor([2, 3, 5], dtype='float32') + y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32') + res = paddle.maximum(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [2. , nan, nan]) + + x = paddle.to_tensor([5, 3, float("inf")], dtype='float32') + y = paddle.to_tensor([1, -float("inf"), 5], dtype='float32') + res = paddle.maximum(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [5. , 3. , inf.]) + """ + op_type = 'elementwise_max' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.maximum(x, y) + elif _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + return _elementwise_op(LayerHelper(op_type, **locals())) + +def minimum(x, y, name=None): + """ + Compare two tensors and return a new tensor containing the element-wise minima. The equation is: + + .. math:: + out = min(x, y) + + Note: + ``paddle.minimum`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [7, 8]]) + y = paddle.to_tensor([[3, 4], [5, 6]]) + res = paddle.minimum(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 2], + # [5, 6]]) + + x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) + y = paddle.to_tensor([3, 0, 4]) + res = paddle.minimum(x, y) + print(res) + # Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[[1, 0, 3], + # [1, 0, 3]]]) + + x = paddle.to_tensor([2, 3, 5], dtype='float32') + y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32') + res = paddle.minimum(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [1. , nan, nan]) + + x = paddle.to_tensor([5, 3, float("inf")], dtype='float64') + y = paddle.to_tensor([1, -float("inf"), 5], dtype='float64') + res = paddle.minimum(x, y) + print(res) + # Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True, + # [ 1. , -inf., 5. ]) + """ + op_type = 'elementwise_min' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.minimum(x, y) + elif _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + return _elementwise_op(LayerHelper(op_type, **locals())) + +def fmax(x, y, name=None): + """ + Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the maximum value of the element. + If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. + The equation is: + + .. math:: + out = fmax(x, y) + + Note: + ``paddle.fmax`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [7, 8]]) + y = paddle.to_tensor([[3, 4], [5, 6]]) + res = paddle.fmax(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[3, 4], + # [7, 8]]) + + x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]]) + y = paddle.to_tensor([3, 0, 4]) + res = paddle.fmax(x, y) + print(res) + # Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[3, 2, 4], + # [3, 2, 4]]) + + x = paddle.to_tensor([2, 3, 5], dtype='float32') + y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32') + res = paddle.fmax(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [2., 3., 5.]) + + x = paddle.to_tensor([5, 3, float("inf")], dtype='float32') + y = paddle.to_tensor([1, -float("inf"), 5], dtype='float32') + res = paddle.fmax(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [5. , 3. , inf.]) + """ + op_type = 'elementwise_fmax' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.fmax(x, y, axis) + if _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + return _elementwise_op(LayerHelper(op_type, **locals())) + +def fmin(x, y, name=None): + """ + Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the minimum value of the element. + If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned. + The equation is: + + .. math:: + out = fmin(x, y) + + Note: + ``paddle.fmin`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` . + + Args: + x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 2], [7, 8]]) + y = paddle.to_tensor([[3, 4], [5, 6]]) + res = paddle.fmin(x, y) + print(res) + # Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[1, 2], + # [5, 6]]) + + x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]]) + y = paddle.to_tensor([3, 0, 4]) + res = paddle.fmin(x, y) + print(res) + # Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[[1, 0, 3], + # [1, 0, 3]]]) + + x = paddle.to_tensor([2, 3, 5], dtype='float32') + y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32') + res = paddle.fmin(x, y) + print(res) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [1., 3., 5.]) + + x = paddle.to_tensor([5, 3, float("inf")], dtype='float64') + y = paddle.to_tensor([1, -float("inf"), 5], dtype='float64') + res = paddle.fmin(x, y) + print(res) + # Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True, + # [ 1. , -inf., 5. ]) + """ + op_type = 'elementwise_fmin' + axis = -1 + act = None + if in_dygraph_mode(): + return _C_ops.fmin(x, y, axis) + if _in_legacy_dygraph(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + return _elementwise_op(LayerHelper(op_type, **locals())) + + +def sum(x, axis=None, dtype=None, keepdim=False, name=None): + """ + Computes the sum of tensor elements over the given dimension. + + Args: + x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64. + axis (int|list|tuple, optional): The dimensions along which the sum is performed. If + :attr:`None`, sum all elements of :attr:`x` and return a + Tensor with a single element, otherwise must be in the + range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, + the dimension to reduce is :math:`rank + axis[i]`. + dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype + of output is the same as input Tensor `x`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result Tensor will have one fewer dimension + than the :attr:`x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Results of summation operation on the specified axis of input Tensor `x`, + if `x.dtype='bool'`, `x.dtype='int32'`, it's data type is `'int64'`, + otherwise it's data type is the same as `x`. + + Examples: + .. code-block:: python + + import paddle + + # x is a Tensor with following elements: + # [[0.2, 0.3, 0.5, 0.9] + # [0.1, 0.2, 0.6, 0.7]] + # Each example is followed by the corresponding output tensor. + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]]) + out1 = paddle.sum(x) # [3.5] + out2 = paddle.sum(x, axis=0) # [0.3, 0.5, 1.1, 1.6] + out3 = paddle.sum(x, axis=-1) # [1.9, 1.6] + out4 = paddle.sum(x, axis=1, keepdim=True) # [[1.9], [1.6]] + + # y is a Tensor with shape [2, 2, 2] and elements as below: + # [[[1, 2], [3, 4]], + # [[5, 6], [7, 8]]] + # Each example is followed by the corresponding output tensor. + y = paddle.to_tensor([[[1, 2], [3, 4]], + [[5, 6], [7, 8]]]) + out5 = paddle.sum(y, axis=[1, 2]) # [10, 26] + out6 = paddle.sum(y, axis=[0, 1]) # [16, 20] + + # x is a Tensor with following elements: + # [[True, True, True, True] + # [False, False, False, False]] + # Each example is followed by the corresponding output tensor. + x = paddle.to_tensor([[True, True, True, True], + [False, False, False, False]]) + out7 = paddle.sum(x) # [4] + out8 = paddle.sum(x, axis=0) # [1, 1, 1, 1] + out9 = paddle.sum(x, axis=1) # [4, 0] + """ + if isinstance(axis, Variable): + reduce_all_flag = True if axis.shape[0] == len(x.shape) else False + else: + if axis is not None and not isinstance(axis, (list, tuple)): + axis = [axis] + + if not axis: + axis = [] + + if len(axis) == 0: + reduce_all_flag = True + else: + if len(axis) == len(x.shape): + reduce_all_flag = True + else: + reduce_all_flag = False + + dtype_flag = False + if dtype is not None: + dtype_flag = True + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + return _C_ops.sum(x, axis, dtype, keepdim) + + if not isinstance(axis, Variable): + axis = axis if axis != None and axis != [] and axis != () else [0] + if utils._contain_var(axis): + axis = utils._convert_to_tensor_list(axis) + + if _in_legacy_dygraph(): + if dtype_flag: + return _legacy_C_ops.reduce_sum(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all_flag, 'in_dtype', + x.dtype, 'out_dtype', dtype) + else: + return _legacy_C_ops.reduce_sum(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all_flag) + + attrs = { + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all_flag + } + + if dtype_flag: + attrs.update({ + 'in_dtype': x.dtype, + 'out_dtype': dtype + }) + + check_variable_and_dtype( + x, 'x', ['bool', 'float16', 'float32', 'float64', + 'int16', 'int32', 'int64', 'complex64', 'complex128', + u'bool', u'float16', u'float32', u'float64', + u'int32', u'int64', u'complex64', u'complex128'], 'sum') + + check_type(axis, 'axis', (int, list, tuple, type(None), Variable), 'sum') + + helper = LayerHelper('sum', **locals()) + if dtype_flag: + out = helper.create_variable_for_type_inference( + dtype=dtype) + else: + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='reduce_sum', + inputs={'X': x}, + outputs={'Out': out}, + attrs=attrs) + return out + + +def nansum(x, axis=None, dtype=None, keepdim=False, name=None): + """ + Computes the sum of tensor elements over the given axis, treating Not a Numbers (NaNs) as zero. + + Args: + x (Tensor): An N-D Tensor, the data type is float32, float64, int32 or int64. + axis (int|list|tuple, optional): The dimensions along which the nansum is performed. If + :attr:`None`, nansum all elements of :attr:`x` and return a + Tensor with a single element, otherwise must be in the + range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, + the dimension to reduce is :math:`rank + axis[i]`. + dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype + of output is the same as input Tensor `x`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result Tensor will have one fewer dimension + than the :attr:`x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Results of summation operation on the specified axis of input Tensor `x`, + + Examples: + .. code-block:: python + + import paddle + + # x is a Tensor with following elements: + # [[nan, 0.3, 0.5, 0.9] + # [0.1, 0.2, -nan, 0.7]] + # Each example is followed by the corresponding output tensor. + x = paddle.to_tensor([[float('nan'), 0.3, 0.5, 0.9], + [0.1, 0.2, float('-nan'), 0.7]],dtype="float32") + out1 = paddle.nansum(x) # [2.7] + out2 = paddle.nansum(x, axis=0) # [0.1, 0.5, 0.5, 1.6] + out3 = paddle.nansum(x, axis=-1) # [1.7, 1.0] + out4 = paddle.nansum(x, axis=1, keepdim=True) # [[1.7], [1.0]] + + # y is a Tensor with shape [2, 2, 2] and elements as below: + # [[[1, nan], [3, 4]], + # [[5, 6], [-nan, 8]]] + # Each example is followed by the corresponding output tensor. + y = paddle.to_tensor([[[1, float('nan')], [3, 4]], + [[5, 6], [float('-nan'), 8]]]) + out5 = paddle.nansum(y, axis=[1, 2]) # [8, 19] + out6 = paddle.nansum(y, axis=[0, 1]) # [9, 18] + """ + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'nansum') + check_type(axis, 'axis', (int, list, tuple, type(None)), 'nansum') + + zero_tensor = paddle.zeros_like(x) + tmp_tensor = paddle.where(isnan(x), zero_tensor, x) + return sum(tmp_tensor, axis, dtype, keepdim, name) + + +def nanmean(x, axis=None, keepdim=False, name=None): + r""" + Compute the arithmetic mean along the specified axis, ignoring NaNs. + + Args: + x (Tensor): The input Tensor with data type uint16, float16, float32, float64. + axis (int|list|tuple, optional):The axis along which to perform nanmean + calculations. ``axis`` should be int, list(int) or tuple(int). If + ``axis`` is a list/tuple of dimension(s), nanmean is calculated along + all element(s) of ``axis`` . ``axis`` or element(s) of ``axis`` + should be in range [-D, D), where D is the dimensions of ``x`` . If + ``axis`` or element(s) of ``axis`` is less than 0, it works the + same way as :math:`axis + D` . If ``axis`` is None, nanmean is + calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of arithmetic mean along ``axis`` of ``x``, with the same data + type as ``x``. + + Examples: + + .. code-block:: python + :name: code-example1 + + import paddle + # x is a 2-D Tensor: + x = paddle.to_tensor([[float('nan'), 0.3, 0.5, 0.9], + [0.1, 0.2, float('-nan'), 0.7]]) + out1 = paddle.nanmean(x) + # [0.44999996] + out2 = paddle.nanmean(x, axis=0) + # [0.1, 0.25, 0.5, 0.79999995] + out3 = paddle.nanmean(x, axis=0, keepdim=True) + # [[0.1, 0.25, 0.5, 0.79999995]] + out4 = paddle.nanmean(x, axis=1) + # [0.56666666 0.33333334] + out5 = paddle.nanmean(x, axis=1, keepdim=True) + # [[0.56666666] + # [0.33333334]] + + # y is a 3-D Tensor: + y = paddle.to_tensor([[[1, float('nan')], [3, 4]], + [[5, 6], [float('-nan'), 8]]]) + out6 = paddle.nanmean(y, axis=[1, 2]) + # [2.66666675, 6.33333349] + out7 = paddle.nanmean(y, axis=[0, 1]) + # [3., 6.] + """ + if isinstance(axis, int): + axis = [axis] + check_variable_and_dtype(x, 'x/input', + ['uint16', 'float16', 'float32', 'float64'], + 'nanmean' ) + if axis is not None: + check_type(axis, 'axis/dim', (int, list, tuple), 'nanmean') + + cnt = paddle.sum(~paddle.isnan(x), axis = axis,keepdim=keepdim) + return paddle.divide(paddle.nansum(x, axis=axis, keepdim=keepdim, name=name), cnt.astype(x.dtype)) + + +def count_nonzero(x, axis=None, keepdim=False, name=None): + r""" + Counts the number of non-zero values in the tensor x along the specified axis. + + Args: + x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64. + axis (int|list|tuple, optional): The dimensions along which the sum is performed. If + :attr:`None`, sum all elements of :attr:`x` and return a + Tensor with a single element, otherwise must be in the + range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, + the dimension to reduce is :math:`rank + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result Tensor will have one fewer dimension + than the :attr:`x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Results of count operation on the specified axis of input Tensor `x`, it's data type is `'int64'`. + + Examples: + + .. code-block:: python + + import paddle + # x is a 2-D Tensor: + x = paddle.to_tensor([[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]]) + out1 = paddle.count_nonzero(x) + # [3] + out2 = paddle.count_nonzero(x, axis=0) + # [0, 1, 2] + out3 = paddle.count_nonzero(x, axis=0, keepdim=True) + # [[0, 1, 2]] + out4 = paddle.count_nonzero(x, axis=1) + # [2, 1, 0] + out5 = paddle.count_nonzero(x, axis=1, keepdim=True) + #[[2], + # [1], + # [0]] + + # y is a 3-D Tensor: + y = paddle.to_tensor([[[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]], + [[0., 2.5, 2.6], [0., 0., 2.4], [2.1, 2.2, 2.3]]]) + out6 = paddle.count_nonzero(y, axis=[1, 2]) + # [3, 6] + out7 = paddle.count_nonzero(y, axis=[0, 1]) + # [1, 3, 5] + """ + + + if axis is not None: + if isinstance(axis, int): + axis = [axis] + dims = len(x.shape) + for i in range(len(axis)): + if not isinstance(axis[i], int) or not (axis[i] < dims and axis[i] >= -dims): + raise ValueError( + "Axis should be None, int, or a list, element should in range [-rank(x), rank(x))." + ) + + bool_tensor = paddle.cast(x, 'bool') + int_tensor = paddle.cast(bool_tensor, 'int64') + return paddle.sum(int_tensor, axis=axis, keepdim=keepdim, name=name) + + +@templatedoc(op_type="sum") +def add_n(inputs, name=None): + """ + Sum one or more Tensor of the input. + + For example: + + .. code-block:: text + + Case 1: + + Input: + input.shape = [2, 3] + input = [[1, 2, 3], + [4, 5, 6]] + + Output: + output.shape = [2, 3] + output = [[1, 2, 3], + [4, 5, 6]] + + Case 2: + + Input: + First input: + input1.shape = [2, 3] + Input1 = [[1, 2, 3], + [4, 5, 6]] + + The second input: + input2.shape = [2, 3] + input2 = [[7, 8, 9], + [10, 11, 12]] + + Output: + output.shape = [2, 3] + output = [[8, 10, 12], + [14, 16, 18]] + + Args: + inputs (Tensor|list[Tensor]|tuple[Tensor]): A Tensor or a list/tuple of Tensors. The shape and data type of the list/tuple elements should be consistent. + Input can be multi-dimensional Tensor, and data types can be: float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the sum of input :math:`inputs` , its shape and data types are consistent with :math:`inputs`. + + Examples: + .. code-block:: python + + import paddle + + input0 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32') + input1 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]], dtype='float32') + output = paddle.add_n([input0, input1]) + # [[8., 10., 12.], + # [14., 16., 18.]] + """ + if in_dygraph_mode(): + if isinstance(inputs, Variable): + inputs = [inputs] + return _C_ops.add_n(inputs) + if _in_legacy_dygraph(): + if isinstance(inputs, Variable): + inputs = [inputs] + return _legacy_C_ops.sum(inputs, 'use_mkldnn', False) + + helper = LayerHelper('add_n', **locals()) + check_type(inputs, 'inputs', (Variable, tuple, list), 'add_n') + if isinstance(inputs, list) or isinstance(inputs, tuple): + if len(inputs) > 0: + for input in inputs: + check_variable_and_dtype(input, "inputs", \ + ['float16', 'float32', 'float64', 'int32', 'int64'], 'add_n') + else: + check_variable_and_dtype(inputs, "inputs", \ + ['float16', 'float32', 'float64', 'int32', 'int64'], 'add_n') + + + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('inputs')) + helper.append_op( + type='sum', + inputs={'X': inputs}, + outputs={'Out': out}, + attrs={'use_mkldnn': False}) + + return out + + +def trunc(input, name=None): + ''' + This API is used to returns a new tensor with the truncated integer values of input. + + Args: + input (Tensor): The input tensor, it's data type should be int32, int64, float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output Tensor of trunc. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand([2,2],'float32') + print(input) + # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.02331470, 0.42374918], + # [0.79647720, 0.74970269]]) + + output = paddle.trunc(input) + print(output) + # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0., 0.], + # [0., 0.]])) + ''' + if in_dygraph_mode(): + return _C_ops.trunc(input) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.trunc(input) + else: + inputs = {"X": input} + attrs = {} + + helper = LayerHelper("trunc", **locals()) + check_variable_and_dtype(input, 'X', ['int32', 'int64', 'float32', 'float64'], 'trunc') + out = helper.create_variable_for_type_inference(dtype=input.dtype) + + helper.append_op( + type="trunc", inputs=inputs, attrs=attrs, outputs={"Out": out}) + return out + + + +def mm(input, mat2, name=None): + """ + + Applies matrix multiplication to two tensors. + + Currently, the input tensors' rank can be any, but when the rank of any + inputs is bigger than 3, this two inputs' rank should be equal. + + + Also note that if the raw tensor :math:`x` or :math:`mat2` is rank-1 and + nontransposed, the prepended or appended dimension :math:`1` will be + removed after matrix multiplication. + + Args: + input (Tensor): The input tensor which is a Tensor. + mat2 (Tensor): The input tensor which is a Tensor. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The product Tensor. + + :: + + * example 1: + + input: [B, ..., M, K], mat2: [B, ..., K, N] + out: [B, ..., M, N] + + * example 2: + + input: [B, M, K], mat2: [B, K, N] + out: [B, M, N] + + * example 3: + + input: [B, M, K], mat2: [K, N] + out: [B, M, N] + + * example 4: + + input: [M, K], mat2: [K, N] + out: [M, N] + + * example 5: + + input: [B, M, K], mat2: [K] + out: [B, M] + + * example 6: + + input: [K], mat2: [K] + out: [1] + + Examples: + .. code-block:: python + + import paddle + input = paddle.arange(1, 7).reshape((3, 2)).astype('float32') + mat2 = paddle.arange(1, 9).reshape((2, 4)).astype('float32') + out = paddle.mm(input, mat2) + print(out) + # [[11., 14., 17., 20.], + # [23., 30., 37., 44.], + # [35., 46., 57., 68.]]) + + + """ + if in_dygraph_mode(): + return _C_ops.matmul(input, mat2, False, False) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.matmul_v2(input, mat2) + + def __check_input(x, y): + var_names = {'x': x, 'y': y} + for name, val in var_names.items(): + check_variable_and_dtype(val, name, + ['float16', 'float32', 'float64'], 'mm') + x_shape = list(x.shape) + y_shape = list(y.shape) + if len(x_shape) == 1: + x_shape = [1] + x_shape + if len(y_shape) == 1: + y_shape = y_shape + [1] + + # check the inner 2 dimensions + if x_shape[-1] != y_shape[-2]: + if not ((x_shape[-1] == -1) or (y_shape[-2] == -1)): + raise ValueError( + "After performing an optional transpose, Input X's width should be " + "equal to Y's width for multiplication " + "prerequisites. But received X's shape: %s, Y's shape: %s\n" + % (x_shape, y_shape)) + + if len(y_shape) > 2 and len(x_shape) > 2: + for i, dim_x in enumerate(x_shape[:-2]): + # don't check neg shape + if dim_x < 0 or y_shape[i] < 0: + continue + if dim_x != y_shape[i]: + raise ValueError( + "When the matrix is larger than 2 dimensions, the higher " + "dimensional values of the two matrices need to be equal. " + "But received x_shape[%d] != y_shape[%d]. X's shape: %s, " + "Y's shape: %s.\n" % (i, i, x_shape, y_shape)) + + __check_input(input, mat2) + + helper = LayerHelper('mm', **locals()) + out = helper.create_variable_for_type_inference(dtype=input.dtype) + helper.append_op( + type='matmul_v2', inputs={'X': input, + 'Y': mat2}, outputs={'Out': out}) + return out + + +def addmm(input, x, y, beta=1.0, alpha=1.0, name=None): + """ + **addmm** + + Perform matrix multiplication for input $x$ and $y$. + $input$ is added to the final result. + The equation is: + + .. math:: + Out = alpha * x * y + beta * input + + $Input$, $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $input$. + + Args: + input (Tensor): The input Tensor to be added to the final result. + x (Tensor): The first input Tensor for matrix multiplication. + y (Tensor): The second input Tensor for matrix multiplication. + beta (float, optional): Coefficient of $input$, default is 1. + alpha (float, optional): Coefficient of $x*y$, default is 1. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output Tensor of addmm. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.ones([2,2]) + y = paddle.ones([2,2]) + input = paddle.ones([2,2]) + + out = paddle.addmm( input=input, x=x, y=y, beta=0.5, alpha=5.0 ) + + print(out) + # [[10.5 10.5] + # [10.5 10.5]] + """ + input_shape = input.shape + x_shape = x.shape + y_shape = y.shape + if not len(x_shape) == len(y_shape) == 2: + raise ValueError("The dimention of x, y should be 2 but receive x's shape: {}, y's shape: {}".format(x_shape, y_shape)) + if x_shape[1] != y_shape[0]: + raise ValueError("The input Variable x's width must be equal with Variable y' height. But received x's shape = {}, y's shape = {}.".format(x_shape, y_shape)) + if len(input_shape) == 2: + if input_shape[0] != x_shape[0]: + if input_shape[0] != 1: + raise ValueError( "When x's dimension[0] is not equal with input's dimension[0], input's dimension[0] must be 1 but got {}".format(input_shape[0])) + if input_shape[1] != y_shape[1] and input_shape[1] != 1: + raise ValueError( "When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {}".format(input_shape[1])) + if input_shape[1] != y_shape[1]: + if input_shape[1] != 1: + raise ValueError( "When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {}".format(input_shape[1])) + elif len(input_shape) == 1: + if input_shape[0] not in (y_shape[1], 1): + raise ValueError("The input's shape: {} is not broadcastable with [x.shape[0], y.shape[1]]: [{},{}]".format(input_shape, x_shape[0], y_shape[1])) + else: + raise ValueError("The dimention of input should be 2 or 1 but receive input's shape: {}".format(input_shape)) + + + + if in_dygraph_mode(): + return _C_ops.addmm( input, x, y, alpha, beta) + else: + if _in_legacy_dygraph(): + out = _legacy_C_ops.addmm(input, x, y, "Alpha", alpha, "Beta", beta) + return out + else: + inputs = {'Input': input, "X": x, "Y": y} + attrs = {'Alpha': alpha, 'Beta': beta} + + helper = LayerHelper("addmm", **locals()) + check_variable_and_dtype(input, 'Input', ['float32', 'float64'], 'addmm') + check_variable_and_dtype(x, 'X', ['float32', 'float64'], 'addmm') + check_variable_and_dtype(y, 'Y', ['float32', 'float64'], 'addmm') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="addmm", inputs=inputs, attrs=attrs, outputs={"Out": out}) + return out + +def renorm(x, p, axis, max_norm): + """ + **renorm** + + This operator is used to calculate the p-norm along the axis, + suppose the input-shape on axis dimension has the value of T, then + the tensor is split into T parts, the p-norm should be calculated for each + part, if the p-norm for part i is larger than max-norm, then each element + in part i should be re-normalized at the same scale so that part-i' p-norm equals + max-norm exactly, otherwise part-i stays unchanged. + + Args: + x (Tensor): The input Tensor + p (float): The power of the norm operation. + axis (int): the dimension to slice the tensor. + max-norm (float): the maximal norm limit. + + Returns: + Tensor: the renorm Tensor. + + Examples: + .. code-block:: python + + import paddle + input = [[[2.0,2,-2],[3,0.3,3]],[[2,-8,2],[3.1,3.7,3]]] + x = paddle.to_tensor(input,dtype='float32') + y = paddle.renorm(x, 1.0, 2, 2.05) + print(y) + # [[[ 0.40594056, 0.29285714, -0.41000000], + # [ 0.60891086, 0.04392857, 0.61500001]], + # [[ 0.40594056, -1.17142856, 0.41000000], + # [ 0.62920785, 0.54178572, 0.61500001]]]) + + """ + input_shape = x.shape + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'renorm') + if not axis < len(input_shape): + raise ValueError("the axis:{} should be less then the shape's size {}:{}".format(axis,len(input_shape),input_shape)) + if not axis >=0: + if not axis >= -1 * len(input_shape): + raise ValueError("the axis:{} should not be less than -1 * length of input_shape:{}".format(axis,-1 * len(input_shape))) + axis = axis + len(input_shape) + if in_dygraph_mode(): + out = _C_ops.renorm(x, p, axis, max_norm) + return out + elif _in_legacy_dygraph(): + out = _legacy_C_ops.renorm(x, 'p',p, 'axis',axis, 'max_norm', max_norm) + return out + + inputs = {'X': x} + attrs = {'p': p, 'axis': axis, 'max_norm':max_norm} + + helper = LayerHelper("renorm", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type="renorm", inputs=inputs, attrs=attrs, outputs={"Out": out}) + return out + + + +def inner(x, y, name=None): + """ + + Inner product of two input Tensor. + + Ordinary inner product for 1-D Tensors, in higher dimensions a sum product over the last axes. + + Args: + x (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match y's. + y (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match x's. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The inner-product Tensor, the output shape is x.shape[:-1] + y.shape[:-1]. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(1, 7).reshape((2, 3)).astype('float32') + y = paddle.arange(1, 10).reshape((3, 3)).astype('float32') + out = paddle.inner(x, y) + print(out) + # ([[14, 32, 50], + # [32, 77, 122]]) + + + """ + if x.size == 1 or y.size == 1: + return multiply(x, y) + else: + xshape = x.shape + yshape = y.shape + dstshape = list(xshape[:-1])+list(yshape[:-1]) + if len(dstshape)==0: + dstshape = [1] + nx = x.reshape((-1, xshape[-1])) + ny = y.reshape((-1, yshape[-1])) + + if in_dygraph_mode(): + return _C_ops.matmul(nx, ny.T, False, False).reshape(dstshape) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.matmul_v2(nx, ny.T).reshape(dstshape) + + def __check_input(x, y): + var_names = {'x': x, 'y': y} + for name, val in var_names.items(): + check_variable_and_dtype(val, name, + ['float16', 'float32', 'float64'], 'inner') + x_shape = list(xshape) + y_shape = list(yshape) + + # check the inner 2 dimensions + if x_shape[-1] != y_shape[-1]: + if not ((x_shape[-1] == -1) or (y_shape[-1] == -1)): + raise ValueError( + "After performing an optional transpose, Input X's last dim should be " + "equal to Y's last dim for multiplication " + "prerequisites. But received X's shape: %s, Y's shape: %s\n" + % (x_shape, y_shape)) + + __check_input(nx, ny) + + helper = LayerHelper('inner', **locals()) + out = helper.create_variable_for_type_inference(dtype=nx.dtype) + helper.append_op( + type='matmul_v2', inputs={'X': nx, + 'Y': ny.T}, outputs={'Out': out}) + return out.reshape(dstshape) + + +def outer(x, y, name=None): + """ + + Outer product of two Tensors. + + Input is flattened if not already 1-dimensional. + + Args: + x (Tensor): An N-D Tensor or a Scalar Tensor. + y (Tensor): An N-D Tensor or a Scalar Tensor. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The outer-product Tensor. + + Examples: + .. code-block:: python + + import paddle + x = paddle.arange(1, 4).astype('float32') + y = paddle.arange(1, 6).astype('float32') + out = paddle.outer(x, y) + print(out) + # ([[1, 2, 3, 4, 5], + # [2, 4, 6, 8, 10], + # [3, 6, 9, 12, 15]]) + + + """ + nx = x.reshape((-1, 1)) + ny = y.reshape((1, -1)) + + if in_dygraph_mode(): + return _C_ops.matmul(nx, ny, False, False) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.matmul_v2(nx, ny) + + def __check_input(x, y): + var_names = {'x': x, 'y': y} + for name, val in var_names.items(): + check_variable_and_dtype(val, name, + ['float16', 'float32', 'float64'], 'inner') + + __check_input(nx, ny) + + helper = LayerHelper('outer', **locals()) + out = helper.create_variable_for_type_inference(dtype=nx.dtype) + helper.append_op( + type='matmul_v2', inputs={'X': nx, + 'Y': ny}, outputs={'Out': out}) + return out + + +def logsumexp(x, axis=None, keepdim=False, name=None): + r""" + Calculates the log of the sum of exponentials of ``x`` along ``axis`` . + + .. math:: + logsumexp(x) = \log\sum exp(x) + + Args: + x (Tensor): The input Tensor with data type float32 or float64, which + have no more than 4 dimensions. + axis (int|list|tuple, optional): The axis along which to perform + logsumexp calculations. ``axis`` should be int, list(int) or + tuple(int). If ``axis`` is a list/tuple of dimension(s), logsumexp + is calculated along all element(s) of ``axis`` . ``axis`` or + element(s) of ``axis`` should be in range [-D, D), where D is the + dimensions of ``x`` . If ``axis`` or element(s) of ``axis`` is + less than 0, it works the same way as :math:`axis + D` . If + ``axis`` is None, logsumexp is calculated along all elements of + ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keep_dim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of logsumexp along ``axis`` of ``x``, with the same data + type as ``x``. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[-1.5, 0., 2.], [3., 1.2, -2.4]]) + out1 = paddle.logsumexp(x) # [3.4691226] + out2 = paddle.logsumexp(x, 1) # [2.15317821, 3.15684602] + + """ + if isinstance(axis, int): + axis = [axis] + reduce_all = True if axis is None \ + or len(axis)==0 \ + or len(axis) == len(x.shape) else False + if axis is None or len(axis) == 0: + axis = [0] + + if in_dygraph_mode(): + if reduce_all: + axis = range(len(x.shape)) + return _C_ops.logsumexp(x, axis, keepdim, reduce_all) + if _in_legacy_dygraph(): + return _legacy_C_ops.logsumexp(x, 'axis', axis, 'keepdim', keepdim, 'reduce_all', reduce_all) + + check_variable_and_dtype(x, 'x', + ['float32', 'float64'], + 'logsumexp') + + helper = LayerHelper('logsumexp', **locals()) + attrs = {'axis': axis, 'keepdim': keepdim, 'reduce_all':reduce_all} + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='logsumexp', inputs={'X': x}, outputs={'Out': out}, attrs=attrs) + return out + + +def inverse(x, name=None): + """ + Takes the inverse of the square matrix. A square matrix is a matrix with + the same number of rows and columns. The input can be a square matrix + (2-D Tensor) or batches of square matrices. + + Args: + x (Tensor): The input tensor. The last two + dimensions should be equal. When the number of dimensions is + greater than 2, it is treated as batches of square matrix. The data + type can be float32 and float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor holds the inverse of x. The shape and data type + is the same as x. + + Examples: + .. code-block:: python + + import paddle + + mat = paddle.to_tensor([[2, 0], [0, 2]], dtype='float32') + inv = paddle.inverse(mat) + print(inv) # [[0.5, 0], [0, 0.5]] + + """ + if in_dygraph_mode(): + return _C_ops.inverse(x) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.inverse(x) + + def _check_input(x): + check_variable_and_dtype(x, 'x', + ['float32', 'float64'], 'inverse') + if len(x.shape) < 2: + raise ValueError( + "The input of inverse is expected to be a Tensor whose number " + "of dimensions is no less than 2. But reviced: %d, " + "x's shape: %s." % (len(x.shape), x.shape)) + _check_input(x) + helper = LayerHelper('inverse', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='inverse', inputs={'Input': [x] }, outputs={'Output': [out]}) + return out + +def _get_reduce_axis(axis): + """ + Internal function for max, min, amax and amin. + It computes the attribute reduce_all value based on axis. + """ + if axis is not None and not isinstance(axis, list): + if isinstance(axis, tuple): + axis = list(axis) + elif isinstance(axis, int): + axis= [axis] + else: + raise TypeError( + "The type of axis must be int, list or tuple, but received {}".format(type(axis))) + reduce_all = True if axis == None or axis == [] else False + if axis == None: + axis = [] + return reduce_all, axis + +def _get_reduce_axis_with_tensor(axis): + if isinstance(axis, Variable): + return False, axis + return _get_reduce_axis(axis) + +def _get_reduce_all_value(axis): + """ + Internal function for max, min, amax and amin. + It computes the attribute reduce_all value based on axis. + """ + if axis is not None and not isinstance(axis, list): + if isinstance(axis, tuple): + axis = list(axis) + elif isinstance(axis, int): + axis= [axis] + else: + raise TypeError( + "The type of axis must be int, list or tuple, but received {}".format(type(axis))) + + reduce_all = True if axis == None or axis == [] else False + axis = axis if axis != None and axis != [] else [0] + return reduce_all, axis + +def max(x, axis=None, keepdim=False, name=None): + """ + + Computes the maximum of tensor elements over the given axis. + + Note: + The difference between max and amax is: If there are multiple maximum elements, + amax evenly distributes gradient between these equal values, + while max propagates gradient to all of them. + + + Args: + x (Tensor): A tensor, the data type is float32, float64, int32, int64. + axis (int|list|tuple, optional): The axis along which the maximum is computed. + If :attr:`None`, compute the maximum over all elements of + `x` and return a Tensor with a single element, + otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`. + If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the `x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of maximum on the specified axis of input tensor, + it's data type is the same as `x`. + + Examples: + .. code-block:: python + + import paddle + + # data_x is a Tensor with shape [2, 4] + # the axis is a int element + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]], + dtype='float64', stop_gradient=False) + result1 = paddle.max(x) + result1.backward() + print(result1, x.grad) + #[0.9], [[0., 0., 0., 1.], [0., 0., 0., 0.]] + + x.clear_grad() + result2 = paddle.max(x, axis=0) + result2.backward() + print(result2, x.grad) + #[0.2, 0.3, 0.6, 0.9], [[1., 1., 0., 1.], [0., 0., 1., 0.]] + + x.clear_grad() + result3 = paddle.max(x, axis=-1) + result3.backward() + print(result3, x.grad) + #[0.9, 0.7], [[0., 0., 0., 1.], [0., 0., 0., 1.]] + + x.clear_grad() + result4 = paddle.max(x, axis=1, keepdim=True) + result4.backward() + print(result4, x.grad) + #[[0.9], [0.7]], [[0., 0., 0., 1.], [0., 0., 0., 1.]] + + # data_y is a Tensor with shape [2, 2, 2] + # the axis is list + y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], + [[5.0, 6.0], [7.0, 8.0]]], + dtype='float64', stop_gradient=False) + result5 = paddle.max(y, axis=[1, 2]) + result5.backward() + print(result5, y.grad) + #[4., 8.], [[[0., 0.], [0., 1.]], [[0., 0.], [0., 1.]]] + + y.clear_grad() + result6 = paddle.max(y, axis=[0, 1]) + result6.backward() + print(result6, y.grad) + #[7., 8.], [[[0., 0.], [0., 0.]], [[0., 0.], [1., 1.]]] + """ + + reduce_all, axis = _get_reduce_axis_with_tensor(axis) + if in_dygraph_mode(): + return _C_ops.max(x, axis, keepdim) + if _in_legacy_dygraph(): + return _legacy_C_ops.reduce_max(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all) + + helper = LayerHelper('max', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'max') + if not isinstance(axis, Variable) and utils._contain_var(axis): + axis = utils._convert_to_tensor_list(axis) + + out = helper.create_variable_for_type_inference( + dtype=x.dtype) + helper.append_op( + type='reduce_max', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all + }) + return out + +def min(x, axis=None, keepdim=False, name=None): + """ + + Computes the minimum of tensor elements over the given axis + + Note: + The difference between min and amin is: If there are multiple minimum elements, + amin evenly distributes gradient between these equal values, + while min propagates gradient to all of them. + + Args: + x (Tensor): A tensor, the data type is float32, float64, int32, int64. + axis (int|list|tuple, optional): The axis along which the minimum is computed. + If :attr:`None`, compute the minimum over all elements of + `x` and return a Tensor with a single element, + otherwise must be in the range :math:`[-x.ndim, x.ndim)`. + If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the `x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of minimum on the specified axis of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle + + # data_x is a Tensor with shape [2, 4] + # the axis is a int element + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]], + dtype='float64', stop_gradient=False) + result1 = paddle.min(x) + result1.backward() + print(result1, x.grad) + #[0.1], [[0., 0., 0., 0.], [1., 0., 0., 0.]] + + x.clear_grad() + result2 = paddle.min(x, axis=0) + result2.backward() + print(result2, x.grad) + #[0.1, 0.2, 0.5, 0.7], [[0., 0., 1., 0.], [1., 1., 0., 1.]] + + x.clear_grad() + result3 = paddle.min(x, axis=-1) + result3.backward() + print(result3, x.grad) + #[0.2, 0.1], [[1., 0., 0., 0.], [1., 0., 0., 0.]] + + x.clear_grad() + result4 = paddle.min(x, axis=1, keepdim=True) + result4.backward() + print(result4, x.grad) + #[[0.2], [0.1]], [[1., 0., 0., 0.], [1., 0., 0., 0.]] + + # data_y is a Tensor with shape [2, 2, 2] + # the axis is list + y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], + [[5.0, 6.0], [7.0, 8.0]]], + dtype='float64', stop_gradient=False) + result5 = paddle.min(y, axis=[1, 2]) + result5.backward() + print(result5, y.grad) + #[1., 5.], [[[1., 0.], [0., 0.]], [[1., 0.], [0., 0.]]] + + y.clear_grad() + result6 = paddle.min(y, axis=[0, 1]) + result6.backward() + print(result6, y.grad) + #[1., 2.], [[[1., 1.], [0., 0.]], [[0., 0.], [0., 0.]]] + """ + + reduce_all, axis = _get_reduce_axis_with_tensor(axis) + if in_dygraph_mode(): + return _C_ops.min(x, axis, keepdim) + + if _in_legacy_dygraph(): + return _legacy_C_ops.reduce_min(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all) + + helper = LayerHelper('min', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'min') + if not isinstance(axis, Variable) and utils._contain_var(axis): + axis = utils._convert_to_tensor_list(axis) + + out = helper.create_variable_for_type_inference( + dtype=x.dtype) + helper.append_op( + type='reduce_min', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all + }) + return out + +def amax(x, axis=None, keepdim=False, name=None): + """ + Computes the maximum of tensor elements over the given axis. + + Note: + The difference between max and amax is: If there are multiple maximum elements, + amax evenly distributes gradient between these equal values, + while max propagates gradient to all of them. + + Args: + x (Tensor): A tensor, the data type is float32, float64, int32, int64, + the dimension is no more than 4. + axis (int|list|tuple, optional): The axis along which the maximum is computed. + If :attr:`None`, compute the maximum over all elements of + `x` and return a Tensor with a single element, + otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`. + If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the `x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of maximum on the specified axis of input tensor, + it's data type is the same as `x`. + + Examples: + .. code-block:: python + + import paddle + # data_x is a Tensor with shape [2, 4] with multiple maximum elements + # the axis is a int element + + x = paddle.to_tensor([[0.1, 0.9, 0.9, 0.9], + [0.9, 0.9, 0.6, 0.7]], + dtype='float64', stop_gradient=False) + # There are 5 maximum elements: + # 1) amax evenly distributes gradient between these equal values, + # thus the corresponding gradients are 1/5=0.2; + # 2) while max propagates gradient to all of them, + # thus the corresponding gradient are 1. + result1 = paddle.amax(x) + result1.backward() + print(result1, x.grad) + #[0.9], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]] + + x.clear_grad() + result1_max = paddle.max(x) + result1_max.backward() + print(result1_max, x.grad) + #[0.9], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]] + + ############################### + + x.clear_grad() + result2 = paddle.amax(x, axis=0) + result2.backward() + print(result2, x.grad) + #[0.9, 0.9, 0.9, 0.9], [[0., 0.5, 1., 1.], [1., 0.5, 0., 0.]] + + x.clear_grad() + result3 = paddle.amax(x, axis=-1) + result3.backward() + print(result3, x.grad) + #[0.9, 0.9], [[0., 0.3333, 0.3333, 0.3333], [0.5, 0.5, 0., 0.]] + + x.clear_grad() + result4 = paddle.amax(x, axis=1, keepdim=True) + result4.backward() + print(result4, x.grad) + #[[0.9], [0.9]], [[0., 0.3333, 0.3333, 0.3333.], [0.5, 0.5, 0., 0.]] + + # data_y is a Tensor with shape [2, 2, 2] + # the axis is list + y = paddle.to_tensor([[[0.1, 0.9], [0.9, 0.9]], + [[0.9, 0.9], [0.6, 0.7]]], + dtype='float64', stop_gradient=False) + result5 = paddle.amax(y, axis=[1, 2]) + result5.backward() + print(result5, y.grad) + #[0.9., 0.9], [[[0., 0.3333], [0.3333, 0.3333]], [[0.5, 0.5], [0., 1.]]] + + y.clear_grad() + result6 = paddle.amax(y, axis=[0, 1]) + result6.backward() + print(result6, y.grad) + #[0.9., 0.9], [[[0., 0.3333], [0.5, 0.3333]], [[0.5, 0.3333], [1., 1.]]] + """ + + reduce_all, axis = _get_reduce_axis(axis) + if in_dygraph_mode(): + return _C_ops.amax(x, axis, keepdim) + if _in_legacy_dygraph(): + return _legacy_C_ops.reduce_amax(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) + + helper = LayerHelper('amax', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amax') + + out = helper.create_variable_for_type_inference( + dtype=x.dtype) + helper.append_op( + type='reduce_amax', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all + }) + return out + +def amin(x, axis=None, keepdim=False, name=None): + """ + + Computes the minimum of tensor elements over the given axis + + Note: + The difference between min and amin is: If there are multiple minimum elements, + amin evenly distributes gradient between these equal values, + while min propagates gradient to all of them. + + Args: + x (Tensor): A tensor, the data type is float32, float64, int32, int64, + the dimension is no more than 4. + axis (int|list|tuple, optional): The axis along which the minimum is computed. + If :attr:`None`, compute the minimum over all elements of + `x` and return a Tensor with a single element, + otherwise must be in the range :math:`[-x.ndim, x.ndim)`. + If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result tensor will have one fewer dimension + than the `x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of minimum on the specified axis of input tensor, + it's data type is the same as input's Tensor. + + Examples: + .. code-block:: python + + import paddle + # data_x is a Tensor with shape [2, 4] with multiple minimum elements + # the axis is a int element + + x = paddle.to_tensor([[0.2, 0.1, 0.1, 0.1], + [0.1, 0.1, 0.6, 0.7]], + dtype='float64', stop_gradient=False) + # There are 5 minimum elements: + # 1) amin evenly distributes gradient between these equal values, + # thus the corresponding gradients are 1/5=0.2; + # 2) while min propagates gradient to all of them, + # thus the corresponding gradient are 1. + result1 = paddle.amin(x) + result1.backward() + print(result1, x.grad) + #[0.1], [[0., 0.2, 0.2, 0.2], [0.2, 0.2, 0., 0.]] + + x.clear_grad() + result1_min = paddle.min(x) + result1_min.backward() + print(result1_min, x.grad) + #[0.1], [[0., 1.0, 1.0, 1.0], [1.0, 1.0, 0., 0.]] + + ############################### + + x.clear_grad() + result2 = paddle.amin(x, axis=0) + result2.backward() + print(result2, x.grad) + #[0.1, 0.1, 0.1, 0.1], [[0., 0.5, 1., 1.], [1., 0.5, 0., 0.]] + + x.clear_grad() + result3 = paddle.amin(x, axis=-1) + result3.backward() + print(result3, x.grad) + #[0.1, 0.1], [[0., 0.3333, 0.3333, 0.3333], [0.5, 0.5, 0., 0.]] + + x.clear_grad() + result4 = paddle.amin(x, axis=1, keepdim=True) + result4.backward() + print(result4, x.grad) + #[[0.1], [0.1]], [[0., 0.3333, 0.3333, 0.3333.], [0.5, 0.5, 0., 0.]] + + # data_y is a Tensor with shape [2, 2, 2] + # the axis is list + y = paddle.to_tensor([[[0.2, 0.1], [0.1, 0.1]], + [[0.1, 0.1], [0.6, 0.7]]], + dtype='float64', stop_gradient=False) + result5 = paddle.amin(y, axis=[1, 2]) + result5.backward() + print(result5, y.grad) + #[0.1., 0.1], [[[0., 0.3333], [0.3333, 0.3333]], [[0.5, 0.5], [0., 1.]]] + + y.clear_grad() + result6 = paddle.amin(y, axis=[0, 1]) + result6.backward() + print(result6, y.grad) + #[0.1., 0.1], [[[0., 0.3333], [0.5, 0.3333]], [[0.5, 0.3333], [1., 1.]]] + """ + + reduce_all, axis = _get_reduce_axis( axis ) + if in_dygraph_mode(): + return _C_ops.amin(x, axis, keepdim) + elif _in_legacy_dygraph(): + return _legacy_C_ops.reduce_amin(x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all) + helper = LayerHelper('amin', **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amin') + + out = helper.create_variable_for_type_inference( + dtype=x.dtype) + helper.append_op( + type='reduce_amin', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'dim': axis, + 'keep_dim': keepdim, + 'reduce_all': reduce_all + }) + return out + +def log1p(x, name=None): + r""" + Calculates the natural log of the given input tensor, element-wise. + + .. math:: + Out = \ln(x+1) + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the natural log of the input Tensor computed element-wise. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.to_tensor([[0], [1]], dtype='float32') + res = paddle.log1p(data) + # [[0.], [0.6931472]] + """ + + if in_dygraph_mode(): + return _C_ops.log1p(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.log1p(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], "log1p") + inputs = {'X': [x]} + helper = LayerHelper('log1p', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="log1p", inputs={"X": x}, outputs={"Out": out}) + return out + +def log2(x, name=None): + r""" + Calculates the log to the base 2 of the given input tensor, element-wise. + + .. math:: + + Out = \log_2x + + Args: + x (Tensor): Input tensor must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + + Returns: + Tensor: The log to the base 2 of the input Tensor computed element-wise. + + Examples: + + .. code-block:: python + + import paddle + + # example 1: x is a float + x_i = paddle.to_tensor([[1.0], [2.0]]) + res = paddle.log2(x_i) # [[0.], [1.0]] + + # example 2: x is float32 + x_i = paddle.full(shape=[1], fill_value=2, dtype='float32') + paddle.to_tensor(x_i) + res = paddle.log2(x_i) + print(res) # [1.0] + + # example 3: x is float64 + x_i = paddle.full(shape=[1], fill_value=2, dtype='float64') + paddle.to_tensor(x_i) + res = paddle.log2(x_i) + print(res) # [1.0] + """ + if in_dygraph_mode(): + return _C_ops.log2(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.log2(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], "log2") + inputs = {'X': [x]} + helper = LayerHelper('log2', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="log2", inputs={"X": x}, outputs={"Out": out}) + return out + + +def log10(x, name=None): + r""" + Calculates the log to the base 10 of the given input tensor, element-wise. + + .. math:: + + Out = \log_10_x + + Args: + x (Tensor): Input tensor must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + + Returns: + Tensor: The log to the base 10 of the input Tensor computed element-wise. + + Examples: + + .. code-block:: python + + import paddle + + # example 1: x is a float + x_i = paddle.to_tensor([[1.0], [10.0]]) + res = paddle.log10(x_i) # [[0.], [1.0]] + + # example 2: x is float32 + x_i = paddle.full(shape=[1], fill_value=10, dtype='float32') + paddle.to_tensor(x_i) + res = paddle.log10(x_i) + print(res) # [1.0] + + # example 3: x is float64 + x_i = paddle.full(shape=[1], fill_value=10, dtype='float64') + paddle.to_tensor(x_i) + res = paddle.log10(x_i) + print(res) # [1.0] + """ + if in_dygraph_mode(): + return _C_ops.log10(x) + if _in_legacy_dygraph(): + return _legacy_C_ops.log10(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], "log10") + inputs = {'X': [x]} + helper = LayerHelper('log10', **locals()) + dtype = helper.input_dtype(input_param_name='x') + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="log10", inputs={"X": x}, outputs={"Out": out}) + return out + + +def clip(x, min=None, max=None, name=None): + """ + This operator clip all elements in input into the range [ min, max ] and return + a resulting tensor as the following equation: + + .. math:: + + Out = MIN(MAX(x, min), max) + + Args: + x (Tensor): An N-D Tensor with data type float32, float64, int32 or int64. + min (float|int|Tensor, optional): The lower bound with type ``float`` , ``int`` or a ``Tensor`` + with shape [1] and type ``int32``, ``float32``, ``float64``. + max (float|int|Tensor, optional): The upper bound with type ``float``, ``int`` or a ``Tensor`` + with shape [1] and type ``int32``, ``float32``, ``float64``. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor with the same data type and data shape as input. + + Examples: + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor([[1.2, 3.5], [4.5, 6.4]], 'float32') + out1 = paddle.clip(x1, min=3.5, max=5.0) + out2 = paddle.clip(x1, min=2.5) + print(out1) + # [[3.5, 3.5] + # [4.5, 5.0]] + print(out2) + # [[2.5, 3.5] + # [[4.5, 6.4] + """ + + x_dtype = str(x.dtype) + if x_dtype == 'paddle.int32': + min_ = np.iinfo(np.int32).min + max_ = np.iinfo(np.int32).max - 2**7 + elif x_dtype == 'paddle.int64': + min_ = np.iinfo(np.int64).min + max_ = np.iinfo(np.int64).max - 2**39 + else: + min_ = float(np.finfo(np.float32).min) + max_ = float(np.finfo(np.float32).max) + + if in_dygraph_mode(): + if isinstance(min, Variable): + min = min.numpy().item(0) + if isinstance(max, Variable): + max = max.numpy().item(0) + min = min_ if min is None else min + max = max_ if max is None else max + return _C_ops.clip(x, min, max) + + if _in_legacy_dygraph(): + if isinstance(min, Variable): + min = min.numpy().item(0) + if isinstance(max, Variable): + max = max.numpy().item(0) + min = min_ if min is None else min + max = max_ if max is None else max + return _legacy_C_ops.clip(x, "min", min, "max", max) + + if min is not None: + check_type(min, 'min', (float, int, Variable), 'clip') + if isinstance(min, Variable): + check_dtype(min.dtype, 'min', ['float32', 'float64', 'int32'], + 'clip', '(When the type of min in clip is Variable.)') + if max is not None: + check_type(max, 'max', (float, int, Variable), 'clip') + if isinstance(max, Variable): + check_dtype(max.dtype, 'max', ['float32', 'float64', 'int32'], + 'clip', '(When the type of max in clip is Variable.)') + + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], 'clip') + + inputs = {'X': x} + attrs = {'min': min_, 'max': max_} + + if isinstance(min, Variable): + min.stop_gradient = True + inputs['Min'] = min + elif min is not None: + attrs['min'] = min + + if isinstance(max, Variable): + max.stop_gradient = True + inputs['Max'] = max + elif max is not None: + attrs['max'] = max + + helper = LayerHelper('clip', **locals()) + output = helper.create_variable_for_type_inference( + dtype=helper.input_dtype('x')) + helper.append_op( + type='clip', inputs=inputs, outputs={'Out': [output]}, attrs=attrs) + + return output + + +@inplace_apis_in_dygraph_only +def clip_(x, min=None, max=None, name=None): + """ + Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_clip`. + """ + fmin = float(np.finfo(np.float32).min) + fmax = float(np.finfo(np.float32).max) + if isinstance(min, Variable): + min = min.numpy().item(0) + if isinstance(max, Variable): + max = max.numpy().item(0) + min = fmin if min is None else min + max = fmax if max is None else max + + if in_dygraph_mode(): + return _C_ops.clip_(x, min, max) + + if _in_legacy_dygraph(): + return _legacy_C_ops.clip_(x, "min", min, "max", max) + + + +def trace(x, offset=0, axis1=0, axis2=1, name=None): + """ + + Computes the sum along diagonals of the input tensor x. + + If ``x`` is 2D, returns the sum of diagonal. + + If ``x`` has larger dimensions, then returns an tensor of diagonals sum, diagonals be taken from + the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axes + of the input tensor x. + + The argument ``offset`` determines where diagonals are taken from input tensor x: + + - If offset = 0, it is the main diagonal. + - If offset > 0, it is above the main diagonal. + - If offset < 0, it is below the main diagonal. + - Note that if offset is out of input's shape indicated by axis1 and axis2, 0 will be returned. + + Args: + x (Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be float32, float64, int32, int64. + offset (int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals). + axis1 (int, optional): The first axis with respect to take diagonal. Default: 0. + axis2 (int, optional): The second axis with respect to take diagonal. Default: 1. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: the output data type is the same as input data type. + + Examples: + .. code-block:: python + + import paddle + + case1 = paddle.randn([2, 3]) + case2 = paddle.randn([3, 10, 10]) + case3 = paddle.randn([3, 10, 5, 10]) + data1 = paddle.trace(case1) # data1.shape = [1] + data2 = paddle.trace(case2, offset=1, axis1=1, axis2=2) # data2.shape = [3] + data3 = paddle.trace(case3, offset=-3, axis1=1, axis2=-1) # data2.shape = [3, 5] + """ + def __check_input(x, offset, axis1, axis2): + check_dtype(x.dtype, 'Input', + ['int32', 'int64', 'float16', 'float32', 'float64'], + 'trace') + + input_shape = list(x.shape) + assert len(input_shape) >= 2, \ + "The x must be at least 2-dimensional, " \ + "But received Input x's dimensional: %s.\n" % \ + len(input_shape) + + axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1 + axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2 + + assert ((0 <= axis1_) and (axis1_ < len(input_shape))), \ + "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ + % (-(len(input_shape)), len(input_shape) - 1, axis1) + + assert ((0 <= axis2_) and (axis2_ < len(input_shape))), \ + "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ + % (-(len(input_shape)), len(input_shape) - 1, axis2) + + + assert axis1_ != axis2_, \ + "axis1 and axis2 cannot be the same axis." \ + "But received axis1 = %d, axis2 = %d\n"%(axis1, axis2) + + if in_dygraph_mode(): + return _C_ops.trace( x, offset, axis1, axis2 ) + + if _in_legacy_dygraph(): + return _legacy_C_ops.trace(x, 'offset', offset, 'axis1', axis1, 'axis2', axis2) + + __check_input(x, offset, axis1, axis2) + + helper = LayerHelper('trace', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='trace', + inputs={'Input': [x]}, + attrs={'offset': offset, + 'axis1': axis1, + 'axis2': axis2}, + outputs={'Out': [out]}) + return out + +def diagonal(x, offset=0, axis1=0, axis2=1, name=None): + """ + This OP computes the diagonals of the input tensor x. + + If ``x`` is 2D, returns the diagonal. + If ``x`` has larger dimensions, diagonals be taken from the 2D planes specified by axis1 and axis2. + By default, the 2D planes formed by the first and second axis of the input tensor x. + + The argument ``offset`` determines where diagonals are taken from input tensor x: + + - If offset = 0, it is the main diagonal. + - If offset > 0, it is above the main diagonal. + - If offset < 0, it is below the main diagonal. + + Args: + x (Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be bool, int32, int64, float16, float32, float64. + offset (int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals). + axis1 (int, optional): The first axis with respect to take diagonal. Default: 0. + axis2 (int, optional): The second axis with respect to take diagonal. Default: 1. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: a partial view of input tensor in specify two dimensions, the output data type is the same as input data type. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([2,2,3],'float32') + print(x) + # Tensor(shape=[2, 2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[0.45661032, 0.03751532, 0.90191704], + # [0.43760979, 0.86177313, 0.65221709]], + + # [[0.17020577, 0.00259554, 0.28954273], + # [0.51795638, 0.27325270, 0.18117726]]]) + + out1 = paddle.diagonal(x) + print(out1) + #Tensor(shape=[3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.45661032, 0.51795638], + # [0.03751532, 0.27325270], + # [0.90191704, 0.18117726]]) + + out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1) + print(out2) + #Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.45661032, 0.86177313], + # [0.17020577, 0.27325270]]) + + out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1) + print(out3) + #Tensor(shape=[3, 1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.43760979], + # [0.86177313], + # [0.65221709]]) + + out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2) + print(out4) + #Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.45661032, 0.86177313], + # [0.17020577, 0.27325270]]) + + """ + if in_dygraph_mode(): + return _C_ops.diagonal(x, offset, axis1, axis2) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.diagonal(x, 'offset', offset, 'axis1', axis1, 'axis2', axis2) + + def __check_input(x, offset, axis1, axis2): + check_dtype(x.dtype, 'Input', + ['bool', 'int32', 'int64', 'float16', 'float32', 'float64'], + 'diagonal') + + input_shape = list(x.shape) + assert len(input_shape) >= 2, \ + "The x must be at least 2-dimensional, " \ + "But received Input x's dimensional: %s.\n" % \ + len(input_shape) + + axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1 + axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2 + + assert axis1_ < len(input_shape), \ + "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ + % (-(len(input_shape)), len(input_shape) - 1, axis1) + + assert axis2_ < len(input_shape), \ + "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n" \ + % (-(len(input_shape)), len(input_shape) - 1, axis2) + + assert axis1_ != axis2_, \ + "axis1 and axis2 cannot be the same axis." \ + "But received axis1 = %d, axis2 = %d\n"%(axis1, axis2) + + __check_input(x, offset, axis1, axis2) + helper = LayerHelper('diagonal', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op( + type='diagonal', + inputs={'Input': [x]}, + attrs={'offset': offset, + 'axis1': axis1, + 'axis2': axis2}, + outputs={'Out': [out]}) + return out + + +@templatedoc(op_type="kron") +def kron(x, y, name=None): + """ + + ${comment} + + Args: + x (Tensor): the fist operand of kron op, data type: float16, float32, float64, int32 or int64. + y (Tensor): the second operand of kron op, data type: float16, float32, float64, int32 or int64. Its data type should be the same with x. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output of kron, data type: float16, float32, float64, int32 or int64. Its data is the same with x. + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([[1, 2], [3, 4]], dtype='int64') + y = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='int64') + out = paddle.kron(x, y) + print(out) + # [[1, 2, 3, 2, 4, 6], + # [ 4, 5, 6, 8, 10, 12], + # [ 7, 8, 9, 14, 16, 18], + # [ 3, 6, 9, 4, 8, 12], + # [12, 15, 18, 16, 20, 24], + # [21, 24, 27, 28, 32, 36]]) + """ + if _in_legacy_dygraph(): + return _legacy_C_ops.kron(x, y) + if in_dygraph_mode(): + return _C_ops.kron(x, y) + helper = LayerHelper('kron', **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'kron') + check_variable_and_dtype(y, 'y', ['float16', 'float32', 'float64', 'int32', 'int64'], 'kron') + + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type="kron", inputs={"X": x, "Y": y}, outputs={"Out": out}) + return out + + +def cumsum(x, axis=None, dtype=None, name=None): + """ + The cumulative sum of the elements along a given axis. + + Note: + The first element of the result is the same as the first element of the input. + + Args: + x (Tensor): The input tensor needed to be cumsumed. + axis (int, optional): The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array. + dtype (str, optional): The data type of the output tensor, can be float32, float64, int32, int64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the result of cumsum operator. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.arange(12) + data = paddle.reshape(data, (3, 4)) + + y = paddle.cumsum(data) + # [ 0 1 3 6 10 15 21 28 36 45 55 66] + + y = paddle.cumsum(data, axis=0) + # [[ 0 1 2 3] + # [ 4 6 8 10] + # [12 15 18 21]] + + y = paddle.cumsum(data, axis=-1) + # [[ 0 1 3 6] + # [ 4 9 15 22] + # [ 8 17 27 38]] + + y = paddle.cumsum(data, dtype='float64') + print(y.dtype) + # paddle.float64 + """ + if axis is None: + flatten = True + else: + flatten = False + if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype): + x = cast(x, dtype) + + if in_dygraph_mode(): + if axis is None: axis = -1 + return _C_ops.cumsum(x, axis, flatten, False, False) + if _in_legacy_dygraph(): + if axis is None: + return _legacy_C_ops.cumsum(x, 'flatten', flatten) + else: + return _legacy_C_ops.cumsum(x, 'axis', axis, 'flatten', flatten) + + check_type(x, 'x', (Variable), 'cumsum') + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + _cum_sum_ = generate_layer_fn('cumsum') + return _cum_sum_(**kwargs) + + +def logcumsumexp(x, axis=None, dtype=None, name=None): + r""" + The logarithm of the cumulative summation of the exponentiation of the elements along a given axis. + + For summation index j given by `axis` and other indices i, the result is + + .. math:: + + logcumsumexp(x)_{ij} = log \sum_{i=0}^{j}exp(x_{ij}) + + Note: + The first element of the result is the same as the first element of the input. + + Args: + x (Tensor): The input tensor. + axis (int, optional): The dimension to do the operation along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array. + dtype (str, optional): The data type of the output tensor, can be float32, float64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the result of logcumsumexp operator. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.arange(12, dtype='float64') + data = paddle.reshape(data, (3, 4)) + + y = paddle.logcumsumexp(data) + # [ 0. 1.3132617 2.4076061 3.4401898 4.4519143 5.4561934 + # 6.4577627 7.4583397 8.458551 9.45863 10.458658 11.458669 ] + + y = paddle.logcumsumexp(data, axis=0) + # [[ 0. 1. 2. 3. ] + # [ 4.01815 5.01815 6.01815 7.01815 ] + # [ 8.018479 9.018479 10.018479 11.018479]] + + y = paddle.logcumsumexp(data, axis=-1) + # [[ 0. 1.3132617 2.4076061 3.4401898] + # [ 4. 5.3132615 6.407606 7.44019 ] + # [ 8. 9.313262 10.407606 11.440189 ]] + + y = paddle.logcumsumexp(data, dtype='float64') + print(y.dtype) + # paddle.float64 + """ + if axis is None: + flatten = True + else: + flatten = False + if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype): + x = cast(x, dtype) + + if in_dygraph_mode(): + if axis is None: axis = -1 + return _C_ops.logcumsumexp(x, axis, flatten, False, False) + if _in_legacy_dygraph(): + if axis is None: + return _legacy_C_ops.logcumsumexp(x, 'flatten', flatten) + else: + return _legacy_C_ops.logcumsumexp(x, 'axis', axis, 'flatten', flatten) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], "logcumsumexp") + + helper = LayerHelper('logcumsumexp', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='logcumsumexp', inputs={'X': x}, outputs={'Out': out}, attrs={'axis': axis, 'flatten': flatten}) + return out + + +def cumprod(x, dim=None, dtype=None, name=None): + """ + Compute the cumulative product of the input tensor x along a given dimension dim. + + Note: + The first element of the result is the same as the first element of the input. + + Args: + x (Tensor): the input tensor need to be cumproded. + dim (int): the dimension along which the input tensor will be accumulated. It need to be in the range of [-x.rank, x.rank), where x.rank means the dimensions of the input tensor x and -1 means the last dimension. + dtype (str, optional): The data type of the output tensor, can be float32, float64, int32, int64, complex64, complex128. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the result of cumprod operator. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.arange(12) + data = paddle.reshape(data, (3, 4)) + # [[ 0 1 2 3 ] + # [ 4 5 6 7 ] + # [ 8 9 10 11]] + + y = paddle.cumprod(data, dim=0) + # [[ 0 1 2 3] + # [ 0 5 12 21] + # [ 0 45 120 231]] + + y = paddle.cumprod(data, dim=-1) + # [[ 0 0 0 0] + # [ 4 20 120 840] + # [ 8 72 720 7920]] + + y = paddle.cumprod(data, dim=1, dtype='float64') + # [[ 0. 0. 0. 0.] + # [ 4. 20. 120. 840.] + # [ 8. 72. 720. 7920.]] + + print(y.dtype) + # paddle.float64 + + """ + + if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype): + x = cast(x, dtype) + + if in_dygraph_mode(): + return _C_ops.cumprod(x, dim) + if _in_legacy_dygraph(): + return _legacy_C_ops.cumprod(x, 'dim', dim) + + check_variable_and_dtype(x, "x", ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'], 'cumprod') + check_type(dim, 'dim', int, 'cumprod') + + helper = LayerHelper('cumprod', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='cumprod', inputs={'X': x}, outputs={'Out': out}, attrs={'dim': dim}) + return out + +def isfinite(x, name=None): + """ + + Return whether every element of input tensor is finite number or not. + + Args: + x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + `Tensor`, the bool result which shows every element of `x` whether it is finite number or not. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) + out = paddle.isfinite(x) + print(out) # [False True True False True False False] + """ + if in_dygraph_mode(): + return _C_ops.isfinite( x ) + if _in_legacy_dygraph(): + return _legacy_C_ops.isfinite_v2(x) + helper = LayerHelper("isfinite_v2", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isfinite') + out = helper.create_variable_for_type_inference('bool') + helper.append_op(type="isfinite_v2", inputs={"X": x}, outputs={"Out": out}) + return out + +def isinf(x, name=None): + """ + + Return whether every element of input tensor is `+/-INF` or not. + + Args: + x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + `Tensor`, the bool result which shows every element of `x` whether it is `+/-INF` or not. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) + out = paddle.isinf(x) + print(out) # [ True False False True False False False] + """ + if in_dygraph_mode(): + return _C_ops.isinf( x ) + if _in_legacy_dygraph(): + return _legacy_C_ops.isinf_v2(x) + helper = LayerHelper("isinf_v2", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isinf') + out = helper.create_variable_for_type_inference(dtype='bool') + helper.append_op(type="isinf_v2", inputs={"X": x}, outputs={"Out": out}) + return out + +def isnan(x, name=None): + """ + + Return whether every element of input tensor is `NaN` or not. + + Args: + x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + `Tensor`, the bool result which shows every element of `x` whether it is `NaN` or not. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')]) + out = paddle.isnan(x) + print(out) # [False False False False False True True] + """ + if in_dygraph_mode(): + return _C_ops.isnan( x ) + + if _in_legacy_dygraph(): + return _legacy_C_ops.isnan_v2(x) + helper = LayerHelper("isnan_v2", **locals()) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64'], 'isnan') + out = helper.create_variable_for_type_inference(dtype='bool') + helper.append_op(type="isnan_v2", inputs={"X": x}, outputs={"Out": out}) + return out + + +def prod(x, axis=None, keepdim=False, dtype=None, name=None): + """ + Compute the product of tensor elements over the given axis. + + Args: + x (Tensor): The input tensor, its data type should be float32, float64, int32, int64. + axis (int|list|tuple, optional): The axis along which the product is computed. If :attr:`None`, + multiply all elements of `x` and return a Tensor with a single element, + otherwise must be in the range :math:`[-x.ndim, x.ndim)`. If :math:`axis[i]<0`, + the axis to reduce is :math:`x.ndim + axis[i]`. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result + tensor will have one fewer dimension than the input unless `keepdim` is true. Default is False. + dtype (str|np.dtype, optional): The desired date type of returned tensor, can be float32, float64, + int32, int64. If specified, the input tensor is casted to dtype before operator performed. + This is very useful for avoiding data type overflows. The default value is None, the dtype + of output is the same as input Tensor `x`. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, result of product on the specified dim of input tensor. + + Examples: + .. code-block:: python + + import paddle + + # the axis is a int element + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]]) + out1 = paddle.prod(x) + # [0.0002268] + + out2 = paddle.prod(x, -1) + # [0.027 0.0084] + + out3 = paddle.prod(x, 0) + # [0.02 0.06 0.3 0.63] + + out4 = paddle.prod(x, 0, keepdim=True) + # [[0.02 0.06 0.3 0.63]] + + out5 = paddle.prod(x, 0, dtype='int64') + # [0 0 0 0] + + # the axis is list + y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]], + [[5.0, 6.0], [7.0, 8.0]]]) + out6 = paddle.prod(y, [0, 1]) + # [105. 384.] + + out7 = paddle.prod(y, (1, 2)) + # [ 24. 1680.] + + """ + if dtype is not None: + check_dtype(dtype, 'dtype', ['float32', 'float64', 'int32', 'int64'], 'prod') + if x.dtype != convert_np_dtype_to_dtype_(dtype): + x = cast(x, dtype) + + dim = axis + if isinstance(dim, Variable): + reduce_all = True if axis.shape[0] == len(x.shape) else False + else: + if dim is not None and not isinstance(dim, list): + if isinstance(dim, tuple): + dim = list(dim) + elif isinstance(dim, int): + dim = [dim] + else: + raise TypeError( + "The type of axis must be int, list or tuple, but received {}". + format(type(dim))) + + reduce_all = True if dim is None or len(dim) == 0 or len(dim) == len(x.shape) else False + if dim is None or len(dim) == 0: + dim = [0] + + if in_dygraph_mode(): + return _C_ops.reduce_prod(x, dim, keepdim, reduce_all) + if _in_legacy_dygraph(): + return _legacy_C_ops.reduce_prod( + x, 'dim', dim, 'keep_dim', keepdim, 'reduce_all', reduce_all) + + helper = LayerHelper('reduce_prod', **locals()) + check_variable_and_dtype( + x, 'x/input', ['float32', 'float64', 'int32', 'int64'], 'reduce_prod') + out = helper.create_variable_for_type_inference(dtype=helper.input_dtype()) + if not isinstance(dim, Variable) and utils._contain_var(dim): + dim = utils._convert_to_tensor_list(dim) + helper.append_op( + type='reduce_prod', + inputs={'X': x}, + outputs={'Out': out}, + attrs={ + 'dim': dim, + 'keep_dim': keepdim, + 'reduce_all': reduce_all + }) + return out + + +def sign(x, name=None): + """ + Returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero. + + Args: + x (Tensor): The input tensor. The data type can be float16, float32 or float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output sign tensor with identical shape and data type to the input :attr:`x`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([3.0, 0.0, -2.0, 1.7], dtype='float32') + out = paddle.sign(x=x) + print(out) # [1.0, 0.0, -1.0, 1.0] + """ + if in_dygraph_mode(): + return _C_ops.sign(x) + + if _in_legacy_dygraph(): + return _legacy_C_ops.sign(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'sign') + helper = LayerHelper("sign", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type='sign', inputs={'X': [x]}, outputs={'Out': [out]}) + + return out + + +def tanh(x, name=None): + r""" + Tanh Activation Operator. + + .. math:: + out = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}} + + Args: + x (Tensor): Input of Tanh operator, an N-D Tensor, with data type float32, float64 or float16. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Output of Tanh operator, a Tensor with same data type and shape as input. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.tanh(x) + print(out) + # [-0.37994896 -0.19737532 0.09966799 0.29131261] + """ + if in_dygraph_mode(): + return _C_ops.tanh( x ) + + if _in_legacy_dygraph(): + return _legacy_C_ops.tanh(x) + + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'tanh') + check_type(x, 'x', (Variable), 'tanh') + helper = LayerHelper('tanh', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='tanh', inputs={'X': x}, outputs={'Out': out}) + return out + +@inplace_apis_in_dygraph_only +def tanh_(x, name=None): + r""" + Inplace version of ``tanh`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_tanh`. + """ + if in_dygraph_mode(): + return _C_ops.tanh_( x ) + return _legacy_C_ops.tanh_(x) + + +def increment(x, value=1.0, name=None): + """ + The API is usually used for control flow to increment the data of :attr:`x` by an amount :attr:`value`. + Notice that the number of elements in :attr:`x` must be equal to 1. + + Args: + x (Tensor): A tensor that must always contain only one element, its data type supports float32, float64, int32 and int64. + value (float, optional): The amount to increment the data of :attr:`x`. Default: 1.0. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the elementwise-incremented tensor with the same shape and data type as :attr:`x`. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.zeros(shape=[1], dtype='float32') + counter = paddle.increment(data) + # [1.] + + """ + if in_dygraph_mode(): + return _C_ops.increment_(x, value) + + if _in_legacy_dygraph(): + return _legacy_C_ops.increment(x, 'step', value) + + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'increment') + helper = LayerHelper("increment", **locals()) + helper.append_op( + type='increment', + inputs={'X': [x]}, + outputs={'Out': [x]}, + attrs={'step': float(value)}) + return x + + +def all(x, axis=None, keepdim=False, name=None): + """ + Computes the ``logical and`` of tensor elements over the given dimension. + + Args: + x (Tensor): An N-D Tensor, the input data type should be `bool`. + axis (int|list|tuple, optional): The dimensions along which the ``logical and`` is compute. If + :attr:`None`, and all elements of :attr:`x` and return a + Tensor with a single element, otherwise must be in the + range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, + the dimension to reduce is :math:`rank + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result Tensor will have one fewer dimension + than the :attr:`x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Results the ``logical and`` on the specified axis of input Tensor `x`, it's data type is bool. + + Examples: + .. code-block:: python + + import paddle + + # x is a bool Tensor with following elements: + # [[True, False] + # [True, True]] + x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32') + print(x) + x = paddle.cast(x, 'bool') + + # out1 should be [False] + out1 = paddle.all(x) # [False] + print(out1) + + # out2 should be [True, False] + out2 = paddle.all(x, axis=0) # [True, False] + print(out2) + + # keepdim=False, out3 should be [False, True], out.shape should be (2,) + out3 = paddle.all(x, axis=-1) # [False, True] + print(out3) + + # keepdim=True, out4 should be [[False], [True]], out.shape should be (2,1) + out4 = paddle.all(x, axis=1, keepdim=True) # [[False], [True]] + print(out4) + + """ + if axis is not None and not isinstance(axis, (list, tuple)): + axis = [axis] + + if not axis: + reduce_all_flag = True + else: + if len(axis) == len(x.shape): + reduce_all_flag = True + else: + reduce_all_flag = False + + if in_dygraph_mode(): + if reduce_all_flag: + axis = range(len(x.shape)) + return _C_ops.all(x, axis, keepdim) + + if _in_legacy_dygraph(): + axis = axis if axis != None and axis != [] else [0] + return _legacy_C_ops.reduce_all(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all_flag) + + attrs = { + 'dim': axis if axis != None and axis != [] and axis != () else [0], + 'keep_dim': keepdim, + 'reduce_all': reduce_all_flag + } + check_variable_and_dtype(x, 'x', ['bool'], 'all') + + + check_type(axis, 'axis', (int, list, tuple, type(None)), 'all') + + helper = LayerHelper('all', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='reduce_all', + inputs={'X': x}, + outputs={'Out': out}, + attrs=attrs) + return out + + +def any(x, axis=None, keepdim=False, name=None): + """ + Computes the ``logical or`` of tensor elements over the given dimension, and return the result. + + Args: + x (Tensor): An N-D Tensor, the input data type should be `bool`. + axis (int|list|tuple, optional): The dimensions along which the ``logical or`` is compute. If + :attr:`None`, and all elements of :attr:`x` and return a + Tensor with a single element, otherwise must be in the + range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`, + the dimension to reduce is :math:`rank + axis[i]`. + keepdim (bool, optional): Whether to reserve the reduced dimension in the + output Tensor. The result Tensor will have one fewer dimension + than the :attr:`x` unless :attr:`keepdim` is true, default + value is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: Results the ``logical or`` on the specified axis of input Tensor `x`, it's data type is bool. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32') + x = paddle.assign(x) + print(x) + x = paddle.cast(x, 'bool') + # x is a bool Tensor with following elements: + # [[True, False] + # [True, True]] + + # out1 should be [True] + out1 = paddle.any(x) # [True] + print(out1) + + # out2 should be [True, True] + out2 = paddle.any(x, axis=0) # [True, True] + print(out2) + + # keepdim=False, out3 should be [True, True], out.shape should be (2,) + out3 = paddle.any(x, axis=-1) # [True, True] + print(out3) + + # keepdim=True, result should be [[True], [True]], out.shape should be (2,1) + out4 = paddle.any(x, axis=1, keepdim=True) # [[True], [True]] + print(out4) + + """ + if axis is not None and not isinstance(axis, (list, tuple)): + axis = [axis] + + if not axis: + reduce_all_flag = True + else: + if len(axis) == len(x.shape): + reduce_all_flag = True + else: + reduce_all_flag = False + + if in_dygraph_mode(): + if reduce_all_flag: + axis = range(len(x.shape)) + return _C_ops.any(x, axis, keepdim) + + if _in_legacy_dygraph(): + axis = axis if axis != None and axis != [] else [0] + return _legacy_C_ops.reduce_any(x, 'dim', axis, 'keep_dim', keepdim, + 'reduce_all', reduce_all_flag) + + attrs = { + 'dim': axis if axis != None and axis != [] and axis != () else [0], + 'keep_dim': keepdim, + 'reduce_all': reduce_all_flag + } + + check_variable_and_dtype(x, 'x', ['bool'], 'any') + + + check_type(axis, 'axis', (int, list, tuple, type(None)), 'any') + + helper = LayerHelper('any', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='reduce_any', + inputs={'X': x}, + outputs={'Out': out}, + attrs=attrs) + return out + +def broadcast_shape(x_shape, y_shape): + """ + The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape, please refer to :ref:`user_guide_broadcasting` for more details. + + Args: + x_shape (list[int]|tuple[int]): A shape of tensor. + y_shape (list[int]|tuple[int]): A shape of tensor. + + + Returns: + list[int], the result shape. + + Examples: + .. code-block:: python + + import paddle + + shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1]) + # [2, 3, 3] + + # shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1]) + # ValueError (terminated with error message). + + """ + + return core.broadcast_shape(x_shape, y_shape) + +def conj(x, name=None): + r""" + This function computes the conjugate of the Tensor elementwisely. + + Args: + x (Tensor): The input Tensor which hold the complex numbers. + Optional data types are: complex64, complex128, float32, float64, int32 or int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): The conjugate of input. The shape and data type is the same with input. If the elements of tensor is real type such as float32, float64, int32 or int64, the out is the same with input. + + Examples: + .. code-block:: python + + import paddle + + data=paddle.to_tensor([[1+1j, 2+2j, 3+3j], [4+4j, 5+5j, 6+6j]]) + #Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[(1+1j), (2+2j), (3+3j)], + # [(4+4j), (5+5j), (6+6j)]]) + + conj_data=paddle.conj(data) + #Tensor(shape=[2, 3], dtype=complex64, place=CUDAPlace(0), stop_gradient=True, + # [[(1-1j), (2-2j), (3-3j)], + # [(4-4j), (5-5j), (6-6j)]]) + + """ + if in_dygraph_mode(): + return _C_ops.conj(x) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.conj(x) + + check_variable_and_dtype(x, "x", ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'], 'conj') + + helper = LayerHelper('conj', **locals()) + out = helper.create_variable_for_type_inference( + dtype=helper.input_dtype()) + + helper.append_op(type='conj', inputs={'X': x}, outputs={'Out': [out]}) + return out + +def digamma(x, name=None): + r""" + Calculates the digamma of the given input tensor, element-wise. + + .. math:: + Out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) } + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + Returns: + Tensor, the digamma of the input Tensor, the shape and data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + data = paddle.to_tensor([[1, 1.5], [0, -2.2]], dtype='float32') + res = paddle.digamma(data) + print(res) + # Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[-0.57721591, 0.03648996], + # [ nan , 5.32286835]]) + """ + + if in_dygraph_mode(): + return _C_ops.digamma(x) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.digamma(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'digamma') + helper = LayerHelper('digamma', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='digamma', inputs={'X': x}, outputs={'Out': out}) + return out + +def lgamma(x, name=None): + r""" + Calculates the lgamma of the given input tensor, element-wise. + + This operator performs elementwise lgamma for input $X$. + :math:`out = log\Gamma(x)` + + + Args: + x (Tensor): Input Tensor. Must be one of the following types: float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, the lgamma of the input Tensor, the shape and data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.lgamma(x) + print(out) + # [1.31452441, 1.76149750, 2.25271273, 1.09579802] + """ + if in_dygraph_mode(): + return _C_ops.lgamma(x) + elif _in_legacy_dygraph(): + return _legacy_C_ops.lgamma(x) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'lgamma') + helper = LayerHelper('lgamma', **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op(type='lgamma', inputs={'X': x}, outputs={'Out': out}) + return out + + +def neg(x, name=None): + """ + This function computes the negative of the Tensor elementwisely. + + Args: + x (Tensor): Input of neg operator, an N-D Tensor, with data type float32, float64, int8, int16, int32, or int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): The negative of input Tensor. The shape and data type are the same with input Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.neg(x) + print(out) + # [0.4 0.2 -0.1 -0.3] + """ + + return scale(x, scale=-1.0, bias=0.0, bias_after_scale=True, act=None, name=name) + +def atan2(x, y, name=None): + r""" + Element-wise arctangent of x/y with consideration of the quadrant. + + Equation: + .. math:: + + atan2(x,y)=\left\{\begin{matrix} + & tan^{-1}(\frac{x}{y}) & y > 0 \\ + & tan^{-1}(\frac{x}{y}) + \pi & x>=0, y < 0 \\ + & tan^{-1}(\frac{x}{y}) - \pi & x<0, y < 0 \\ + & +\frac{\pi}{2} & x>0, y = 0 \\ + & -\frac{\pi}{2} & x<0, y = 0 \\ + &\text{undefined} & x=0, y = 0 + \end{matrix}\right. + + Args: + x (Tensor): An N-D Tensor, the data type is int32, int64, float16, float32, float64. + y (Tensor): An N-D Tensor, must have the same type as `x`. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float64 when the input data type is int). + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-1, +1, +1, -1]).astype('float32') + #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [-1, 1, 1, -1]) + + y = paddle.to_tensor([-1, -1, +1, +1]).astype('float32') + #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [-1, -1, 1, 1]) + + out = paddle.atan2(x, y) + #Tensor(shape=[4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [-2.35619450, 2.35619450, 0.78539819, -0.78539819]) + + """ + + if in_dygraph_mode(): + return _C_ops.atan2( x, y) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.atan2(x, y) + else: + check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float16', 'float32', 'float64'], 'atan2') + check_variable_and_dtype(y, 'y', ['int32', 'int64', 'float16', 'float32', 'float64'], 'atan2') + + helper = LayerHelper('atan2', **locals()) + inputs = {'X1' : x, 'X2' : y} + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type='atan2', inputs=inputs, outputs={'Out': out}) + return out + +def logit(x, eps=None, name=None): + r""" + This function generates a new tensor with the logit of the elements of input x. x is clamped to [eps, 1-eps] when eps is not zero. When eps is zero and x < 0 or x > 1, the function will yields NaN. + + .. math:: + + logit(x) = ln(\frac{x}{1 - x}) + + where + + .. math:: + + x_i= + \left\{\begin{array}{rcl} + x_i & &\text{if } eps == Default \\ + eps & &\text{if } x_i < eps \\ + x_i & &\text{if } eps <= x_i <= 1-eps \\ + 1-eps & &\text{if } x_i > 1-eps + \end{array}\right. + + Args: + x (Tensor): The input Tensor with data type float32, float64. + eps (float, optional): the epsilon for input clamp bound. Default is None. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out(Tensor): A Tensor with the same data type and shape as ``x`` . + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.2635, 0.0106, 0.2780, 0.2097, 0.8095]) + out1 = paddle.logit(x) + print(out1) + # [-1.0277, -4.5365, -0.9544, -1.3269, 1.4468] + + """ + + if eps == None: + eps = 0.0 + if _in_legacy_dygraph(): + return _legacy_C_ops.logit(x, 'eps', eps) + if in_dygraph_mode(): + return _C_ops.logit(x, eps) + check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'], 'logit') + helper = LayerHelper("logit", **locals()) + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='logit', + inputs={'X': x}, + outputs={'Out': out}, + attrs={'eps': eps}) + return out + +def lerp(x, y, weight, name=None): + r""" + Does a linear interpolation between x and y based on weight. + + Equation: + .. math:: + + lerp(x, y, weight) = x + weight * (y - x). + + Args: + x (Tensor): An N-D Tensor with starting points, the data type is float32, float64. + y (Tensor): An N-D Tensor with ending points, the data type is float32, float64. + weight (float|Tensor): The weight for the interpolation formula. When weight is Tensor, the data type is float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the shape and data type is the same with input. + + Example: + .. code-block:: python + + import paddle + + x = paddle.arange(1., 5., dtype='float32') + y = paddle.empty([4], dtype='float32') + y.fill_(10.) + out = paddle.lerp(x, y, 0.5) + # out: [5.5, 6., 6.5, 7.] + + """ + if in_dygraph_mode(): + check_type(weight, 'weight', (float, paddle.Tensor, Variable), 'lerp') + if isinstance(weight, float): + weight = paddle.to_tensor(weight, dtype=x.dtype) + + return _C_ops.lerp( x, y, weight) + if _in_legacy_dygraph(): + if isinstance(weight, float): + weight = paddle.to_tensor(weight, dtype=x.dtype) + return _legacy_C_ops.lerp(x, y, weight) + + if isinstance(weight, float): + weight = paddle.full(shape=[1], fill_value=weight, dtype=x.dtype) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'lerp') + check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'lerp') + check_variable_and_dtype(weight, 'weight', ['float32', 'float64'], 'lerp') + + helper = LayerHelper('lerp', **locals()) + inputs = {'X': x, 'Y': y, 'Weight': weight} + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='lerp', inputs=inputs, outputs={'Out': out}) + return out + +@inplace_apis_in_dygraph_only +def lerp_(x, y, weight, name=None): + r""" + Inplace version of ``lerp`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_lerp`. + """ + out_shape = broadcast_shape(x.shape, y.shape) + check_type(weight, 'weight', (float, paddle.Tensor, Variable), 'lerp') + if isinstance(weight, float): + weight = paddle.to_tensor([weight], dtype=x.dtype) + elif isinstance(weight, (paddle.Tensor, Variable)): + out_shape = broadcast_shape(out_shape, weight.shape) + if out_shape != x.shape: + raise ValueError("The shape of broadcast output {} is different from that of inplace tensor {} in the Inplace operation.".format(out_shape, x.shape)) + if in_dygraph_mode(): + return _C_ops.lerp_( x, y, weight) + return _legacy_C_ops.lerp_(x, y, weight) + +def erfinv(x, name=None): + r""" + The inverse error function of x. Please refer to :ref:`api_paddle_erf` + + .. math:: + + erfinv(erf(x)) = x. + + Args: + x (Tensor): An N-D Tensor, the data type is float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor), an N-D Tensor, the shape and data type is the same with input. + + Example: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0, 0.5, -1.], dtype="float32") + out = paddle.erfinv(x) + # out: [0, 0.4769, -inf] + + """ + if in_dygraph_mode(): + return _C_ops.erfinv( x ) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'erfinv') + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.erfinv(x) + + helper = LayerHelper('erfinv', **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='erfinv', inputs={'X': x}, outputs={'Out': out}) + return out + +@inplace_apis_in_dygraph_only +def erfinv_(x, name=None): + r""" + Inplace version of ``erfinv`` API, the output Tensor will be inplaced with input ``x``. + Please refer to :ref:`api_tensor_erfinv`. + """ + check_type(x, 'x', (paddle.Tensor, Variable), 'erfinv') + if in_dygraph_mode(): + return _C_ops.erfinv_( x ) + return _legacy_C_ops.erfinv_(x) + +def rad2deg(x, name=None): + r""" + Convert each of the elements of input x from angles in radians to degrees. + + Equation: + .. math:: + + rad2deg(x)=180/ \pi * x + + Args: + x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int). + + Examples: + .. code-block:: python + + import paddle + import math + + x1 = paddle.to_tensor([3.142, -3.142, 6.283, -6.283, 1.570, -1.570]) + result1 = paddle.rad2deg(x1) + print(result1) + # Tensor(shape=[6], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [180.02334595, -180.02334595, 359.98937988, -359.98937988, + # 9.95437622 , -89.95437622]) + + x2 = paddle.to_tensor(math.pi/2) + result2 = paddle.rad2deg(x2) + print(result2) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [90.]) + + x3 = paddle.to_tensor(1) + result3 = paddle.rad2deg(x3) + print(result3) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [57.29578018]) + """ + rad2deg_scale = 180 / np.pi + if in_dygraph_mode(): + if convert_dtype(x.dtype) in ['int32', 'int64']: + x = cast(x, dtype="float32") + return _C_ops.scale(x, rad2deg_scale, 0.0, True) + elif paddle.in_dynamic_mode(): + if convert_dtype(x.dtype) in ['int32', 'int64']: + x = cast(x, dtype="float32") + return _legacy_C_ops.scale(x, 'scale', rad2deg_scale) + else: + check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float32', 'float64'], 'rad2deg') + helper = LayerHelper('rad2deg', **locals()) + out_cast = x + if convert_dtype(x.dtype) in ['int32', 'int64']: + out_cast = helper.create_variable_for_type_inference(dtype=paddle.float32) + helper.append_op( + type='cast', inputs={'X':x}, outputs={'Out': out_cast}, attrs={'in_dtype': x.dtype,'out_dtype': paddle.float32}) + out = helper.create_variable_for_type_inference(dtype=out_cast.dtype) + helper.append_op( + type='scale', inputs={'X':out_cast}, outputs={'Out': out}, attrs={'scale': rad2deg_scale}) + return out + +def deg2rad(x, name=None): + r""" + Convert each of the elements of input x from degrees to angles in radians. + .. math:: + + deg2rad(x)=\pi * x / 180 + + Args: + x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int). + + Examples: + .. code-block:: python + + import paddle + x1 = paddle.to_tensor([180.0, -180.0, 360.0, -360.0, 90.0, -90.0]) + result1 = paddle.deg2rad(x1) + print(result1) + # Tensor(shape=[6], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [3.14159274, -3.14159274, 6.28318548, -6.28318548, 1.57079637, + # -1.57079637]) + + x2 = paddle.to_tensor(180) + result2 = paddle.deg2rad(x2) + print(result2) + # Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [3.14159274]) + """ + deg2rad_scale = np.pi / 180.0 + if in_dygraph_mode(): + if convert_dtype(x.dtype) in ['int32', 'int64']: + x = cast(x, dtype="float32") + return _C_ops.scale(x, deg2rad_scale, 0.0, True) + elif paddle.in_dynamic_mode(): + if convert_dtype(x.dtype) in ['int32', 'int64']: + x = cast(x, dtype="float32") + return _legacy_C_ops.scale(x, 'scale', deg2rad_scale) + else: + check_variable_and_dtype(x, 'x', ['int32', 'int64', 'float32', 'float64'], 'deg2rad') + helper = LayerHelper('deg2rad', **locals()) + out_cast = x + if convert_dtype(x.dtype) in ['int32', 'int64']: + out_cast = helper.create_variable_for_type_inference(dtype=paddle.float32) + helper.append_op( + type='cast', inputs={'X':x}, outputs={'Out': out_cast}, attrs={'in_dtype': x.dtype,'out_dtype': paddle.float32}) + out = helper.create_variable_for_type_inference(dtype=out_cast.dtype) + helper.append_op( + type='scale', inputs={'X':out_cast}, outputs={'Out': out}, attrs={'scale': deg2rad_scale}) + return out + +def gcd(x, y, name=None): + """ + Computes the element-wise greatest common divisor (GCD) of input |x| and |y|. + Both x and y must have integer types. + + Note: + gcd(0,0)=0, gcd(0, y)=|y| + + If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output). + + Args: + x (Tensor): An N-D Tensor, the data type is int32,int64. + y (Tensor): An N-D Tensor, the data type is int32,int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor(12) + x2 = paddle.to_tensor(20) + paddle.gcd(x1, x2) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [4]) + + x3 = paddle.arange(6) + paddle.gcd(x3, x2) + # Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [20, 1 , 2 , 1 , 4 , 5]) + + x4 = paddle.to_tensor(0) + paddle.gcd(x4, x2) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [20]) + + paddle.gcd(x4, x4) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [0]) + + x5 = paddle.to_tensor(-20) + paddle.gcd(x1, x5) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [4]) + """ + shape = paddle.broadcast_shape(x.shape, y.shape) + x = paddle.broadcast_to(x, shape) + y = paddle.broadcast_to(y, shape) + x = paddle.abs(x) + y = paddle.abs(y) + + def _gcd_cond_fn(x, y): + return paddle.any(y != 0) + + def _gcd_body_fn(x, y): + # paddle.mod will raise an error when any element of y is 0. To avoid + # that, we change those zeros to ones. Their values don't matter because + # they won't be used. + y_not_equal_0 = (y != 0) + y_safe = paddle.where(y_not_equal_0, y, paddle.ones(y.shape, y.dtype)) + x, y = (paddle.where(y_not_equal_0, y, x), + paddle.where(y_not_equal_0, paddle.mod(x, y_safe),paddle.zeros(y.shape, y.dtype))) + return (paddle.where(x < y, y, x), paddle.where(x < y, x, y)) + + if paddle.in_dynamic_mode(): + while _gcd_cond_fn(x, y): + x, y = _gcd_body_fn(x, y) + + return x + else: + check_variable_and_dtype(x, 'x', ['int32', 'int64'], 'gcd') + check_variable_and_dtype(y, 'y', ['int32', 'int64'], 'gcd') + out, _ = paddle.static.nn.while_loop(_gcd_cond_fn, _gcd_body_fn, [x, y]) + return out + +def lcm(x, y, name=None): + """ + Computes the element-wise least common multiple (LCM) of input |x| and |y|. + Both x and y must have integer types. + + Note: + lcm(0,0)=0, lcm(0, y)=0 + + If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output). + + Args: + x (Tensor): An N-D Tensor, the data type is int32,int64. + y (Tensor): An N-D Tensor, the data type is int32,int64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + out (Tensor): An N-D Tensor, the data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor(12) + x2 = paddle.to_tensor(20) + paddle.lcm(x1, x2) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [60]) + + x3 = paddle.arange(6) + paddle.lcm(x3, x2) + # Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [0, 20, 20, 60, 20, 20]) + + x4 = paddle.to_tensor(0) + paddle.lcm(x4, x2) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [0]) + + paddle.lcm(x4, x4) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [0]) + + x5 = paddle.to_tensor(-20) + paddle.lcm(x1, x5) + # Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [60]) + """ + d = paddle.gcd(x, y) + # paddle.mod will raise an error when any element of y is 0. To avoid + # that, we change those zeros to ones. Their values don't matter because + # they won't be used. + d_equal_0 = paddle.equal(d, 0) + d_safe = paddle.where(d_equal_0, paddle.ones(d.shape, d.dtype), d) + out = paddle.where(d_equal_0, paddle.zeros(d.shape, d.dtype), paddle.abs(x * y) // d_safe) + return out + +def diff(x, n=1, axis=-1, prepend=None, append=None, name=None): + r""" + Computes the n-th forward difference along the given axis. + The first-order differences is computed by using the following formula: + + .. math:: + + out[i] = x[i+1] - x[i] + + Higher-order differences are computed by using paddle.diff() recursively. + Only n=1 is currently supported. + + Args: + x (Tensor): The input tensor to compute the forward difference on + n (int, optional): The number of times to recursively compute the difference. + Only support n=1. Default:1 + axis (int, optional): The axis to compute the difference along. Default:-1 + prepend (Tensor, optional): The tensor to prepend to input along axis before computing the difference. + It's dimensions must be equivalent to that of x, + and its shapes must match x's shape except on axis. + append (Tensor, optional): The tensor to append to input along axis before computing the difference, + It's dimensions must be equivalent to that of x, + and its shapes must match x's shape except on axis. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output tensor with same dtype with x. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1, 4, 5, 2]) + out = paddle.diff(x) + print(out) + # out: + # [3, 1, -3] + + y = paddle.to_tensor([7, 9]) + out = paddle.diff(x, append=y) + print(out) + # out: + # [3, 1, -3, 5, 2] + + z = paddle.to_tensor([[1, 2, 3], [4, 5, 6]]) + out = paddle.diff(z, axis=0) + print(out) + # out: + # [[3, 3, 3]] + out = paddle.diff(z, axis=1) + print(out) + # out: + # [[1, 1], [1, 1]] + """ + + if axis < 0: + axis = axis + len(x.shape) + if axis > len(x.shape): + axis = len(x.shape) + if axis < 0: + axis = 0 + dtype = x.dtype + axes = [axis] + infer_flags = list(1 for i in range(len(axes))) + if in_dygraph_mode(): + has_pend = False + input_list = [] + if prepend is not None and append is not None: + input_list = [prepend, x, append] + has_pend = True + elif prepend is not None: + input_list = [prepend, x] + has_pend = True + elif append is not None: + input_list = [x, append] + has_pend = True + if has_pend: + new_input = _C_ops.concat(input_list, axis) + else: + new_input = x + + attrs_1 = () + attrs_2 = () + + dim_len = new_input.shape[axis] + + starts_1 = [0] + attrs_1 += ('starts', starts_1) + ends_1 = [dim_len - 1] + attrs_1 += ('ends', ends_1) + input_front = _C_ops.slice(new_input, axes, starts_1, ends_1, infer_flags, + []) + starts_2 = [1] + attrs_2 += ('starts', starts_2) + ends_2 = [dim_len] + attrs_2 += ('ends', ends_2) + input_back = _C_ops.slice(new_input, axes, starts_2, ends_2, infer_flags, + []) + + if x.dtype == paddle.bool: + return _C_ops.logical_xor(input_back, input_front) + else: + return _C_ops.subtract(input_back, input_front) + elif _in_legacy_dygraph(): + has_pend = False + input_list = [] + if prepend is not None and append is not None: + input_list = [prepend, x, append] + has_pend = True + elif prepend is not None: + input_list = [prepend, x] + has_pend = True + elif append is not None: + input_list = [x, append] + has_pend = True + if has_pend: + new_input = _varbase_creator() + _legacy_C_ops.concat(input_list, new_input, 'axis', axis) + else: + new_input = x + + attrs_1 = () + attrs_2 = () + + dim_len = new_input.shape[axis] + + starts_1 = [0] + attrs_1 += ('starts', starts_1) + ends_1 = [dim_len - 1] + attrs_1 += ('ends', ends_1) + input_front = _legacy_C_ops.slice(new_input, None, None, None, None, 'axes', axes, \ + 'infer_flags', infer_flags, *attrs_1) + starts_2 = [1] + attrs_2 += ('starts', starts_2) + ends_2 = [dim_len] + attrs_2 += ('ends', ends_2) + input_back = _legacy_C_ops.slice(new_input, None, None, None, None, 'axes', axes, \ + 'infer_flags', infer_flags, *attrs_2) + + if x.dtype == paddle.bool: + return _legacy_C_ops.logical_xor(input_back, input_front) + else: + return elementwise_sub(input_back, input_front, axis=axis) + else: + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'bool', 'int32', 'int64'], 'diff') + check_type(axis, 'axis', (int), 'diff') + helper = LayerHelper('diff', **locals()) + has_pend = False + input_list = [] + if prepend is not None and append is not None: + input_list = [prepend, x, append] + has_pend = True + elif prepend is not None: + input_list = [prepend, x] + has_pend = True + elif append is not None: + input_list = [x, append] + has_pend = True + + if has_pend: + new_input = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='concat', inputs={'X': input_list}, outputs={'Out': [new_input]}, attrs={'axis': axis} + ) + else: + new_input = x + + dim_len = new_input.shape[axis] + attrs_1 = {'axes': axes} + starts_1 = [0] + ends_1 = [dim_len - 1] + attrs_1['starts'] = starts_1 + attrs_1['ends'] = ends_1 + input_front = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='slice', inputs={'Input': new_input}, attrs=attrs_1, outputs={'Out': input_front} + ) + attrs_2 = {'axes': axes} + starts_2 = [1] + ends_2 = [dim_len] + attrs_2['starts'] = starts_2 + attrs_2['ends'] = ends_2 + input_back = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='slice', inputs={'Input': new_input}, attrs=attrs_2, outputs={'Out': input_back} + ) + + if dtype == paddle.bool: + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='logical_xor', inputs={"X": input_back, "Y": input_front}, outputs={"Out": out} + ) + else: + out = elementwise_sub(input_back, input_front, axis=axis) + + return out + +def angle(x, name=None): + r""" + Element-wise angle of complex numbers. For non-negative real numbers, the angle is 0 while + for negative real numbers, the angle is :math:`\pi`. + + Equation: + .. math:: + + angle(x)=arctan2(x.imag, x.real) + + Args: + x (Tensor): An N-D Tensor, the data type is complex64, complex128, or float32, float64 . + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: An N-D Tensor of real data type with the same precision as that of x's data type. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-2, -1, 0, 1]).unsqueeze(-1).astype('float32') + y = paddle.to_tensor([-2, -1, 0, 1]).astype('float32') + z = x + 1j * y + print(z) + # Tensor(shape=[4, 4], dtype=complex64, place=Place(cpu), stop_gradient=True, + # [[(-2-2j), (-2-1j), (-2+0j), (-2+1j)], + # [(-1-2j), (-1-1j), (-1+0j), (-1+1j)], + # [-2j , -1j , 0j , 1j ], + # [ (1-2j), (1-1j), (1+0j), (1+1j)]]) + + theta = paddle.angle(z) + print(theta) + # Tensor(shape=[4, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[-2.35619450, -2.67794514, 3.14159274, 2.67794514], + # [-2.03444386, -2.35619450, 3.14159274, 2.35619450], + # [-1.57079637, -1.57079637, 0. , 1.57079637], + # [-1.10714877, -0.78539819, 0. , 0.78539819]]) + """ + + if in_dygraph_mode(): + return _C_ops.angle(x) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.angle(x) + + check_variable_and_dtype(x, 'x', + ['float32', 'float64', 'complex64', 'complex128'], 'angle') + op_type = "angle" + helper = LayerHelper(op_type, **locals()) + inputs = {"X": x} + out = helper.create_variable_for_type_inference( + dtype=_complex_to_real_dtype(x.dtype)) + outputs = {"Out": out} + helper.append_op(type=op_type, inputs=inputs, outputs=outputs) + return out + +def heaviside(x, y, name=None): + r""" + Computes the Heaviside step function determined by corresponding element in y for each element in x. The equation is + + .. math:: + 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`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`. + + Args: + x (Tensor): The input tensor of Heaviside step function, it's data type should be float16, float32, float64, int32 or int64. + y (Tensor): The tensor that determines a Heaviside step function, it's data type should be float16, float32, float64, int32 or int64. + name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + N-D Tensor. A location into which the result is stored. If x and y have different shapes and are broadcastable, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([-0.5, 0, 0.5]) + y = paddle.to_tensor([0.1]) + paddle.heaviside(x, y) + # [0. , 0.10000000, 1. ] + x = paddle.to_tensor([[-0.5, 0, 0.5], [-0.5, 0.5, 0]]) + y = paddle.to_tensor([0.1, 0.2, 0.3]) + paddle.heaviside(x, y) + # [[0. , 0.20000000, 1. ], + # [0. , 1. , 0.30000001]] + """ + op_type = 'elementwise_heaviside' + axis = -1 + act = None + if _non_static_mode(): + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + return _elementwise_op(LayerHelper(op_type, **locals())) + +def frac(x, name=None): + """ + This API is used to return the fractional portion of each element in input. + + Args: + x (Tensor): The input tensor, which data type should be int32, int64, float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The output Tensor of frac. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.to_tensor([[12.22000003, -1.02999997], + [-0.54999995, 0.66000003]]) + output = paddle.frac(input) + print(output) + # Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[ 0.22000003, -0.02999997], + # [-0.54999995, 0.66000003]]) + """ + op_type = 'elementwise_sub' + axis = -1 + act = None + if x.dtype not in [paddle.int32, paddle.int64, paddle.float32, paddle.float64]: + raise TypeError( + "The data type of input must be one of ['int32', 'int64', 'float32', 'float64'], but got {}".format(x.dtype)) + if in_dygraph_mode(): + y = _C_ops.trunc(x) + return _C_ops.subtract(x, y) + else: + if _in_legacy_dygraph(): + y = _legacy_C_ops.trunc(x) + return _elementwise_op_in_dygraph( + x, y, axis=axis, act=act, op_name=op_type) + else: + inputs = {"X": x} + attrs = {} + + helper = LayerHelper("trunc", **locals()) + check_variable_and_dtype(x, "X", ['int32', 'int64', 'float32', 'float64'], 'trunc') + y = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op( + type="trunc", inputs=inputs, attrs=attrs, outputs={"Out": y}) + return _elementwise_op(LayerHelper(op_type, **locals())) + +def sgn(x, name=None): + """ + For complex tensor, this API returns a new tensor whose elements have the same angles as the corresponding + elements of input and absolute values of one. + For other float dtype tensor, + this API returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero, same as paddle.sign. + + Args: + x (Tensor): The input tensor, which data type should be float16, float32, float64, complex64, complex128. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A sign Tensor for real input, or normalized Tensor for complex input, shape and data type are same as input. + + Examples: + .. code-block:: Python + + import paddle + + x = paddle.to_tensor([[3 + 4j, 7 - 24j, 0, 1 + 2j], [6 + 8j, 3, 0, -2]]) + print(paddle.sgn(x)) + #[[0.6+0.8j 0.28-0.96j 0.+0.j 0.4472136+0.8944272j] + # [0.6+0.8j 1.+0.j 0.+0.j -1.+0.j]] + + """ + if x.dtype not in [paddle.float16, paddle.float32, paddle.float64, paddle.complex64, paddle.complex128]: + raise TypeError( + "The data type of input must be one of ['float16', 'float32', 'float64', 'complex64', 'complex128'], but got {}" + .format(x.dtype)) + if paddle.is_complex(x): + expand_x = paddle.as_real(x) + x_abs = paddle.abs(x) + x_abs = paddle.unsqueeze(x_abs, axis=-1) + output = expand_x / x_abs + zeros = paddle.zeros_like(output) + output = paddle.where(paddle.isnan(output), zeros, output) + + return paddle.as_complex(output) + else: + return paddle.sign(x) + +def take(x, index, mode='raise', name=None): + """ + Returns a new tensor with the elements of input tensor x at the given index. + The input tensor is treated as if it were viewed as a 1-D tensor. + The result takes the same shape as the index. + + Args: + x (Tensor): An N-D Tensor, its data type should be int32, int64, float32, float64. + index (Tensor): An N-D Tensor, its data type should be int32, int64. + mode (str, optional): Specifies how out-of-bounds index will behave. the candicates are ``'raise'``, ``'wrap'`` and ``'clip'``. + + - ``'raise'``: raise an error (default); + - ``'wrap'``: wrap around; + - ``'clip'``: clip to the range. ``'clip'`` mode means that all indices that are too large are replaced by the index that addresses the last element. Note that this disables indexing with negative numbers. + + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, Tensor with the same shape as index, the data type is the same with input. + + Examples: + .. code-block:: python + + import paddle + + x_int = paddle.arange(0, 12).reshape([3, 4]) + x_float = x_int.astype(paddle.float64) + + idx_pos = paddle.arange(4, 10).reshape([2, 3]) # positive index + idx_neg = paddle.arange(-2, 4).reshape([2, 3]) # negative index + idx_err = paddle.arange(-2, 13).reshape([3, 5]) # index out of range + + paddle.take(x_int, idx_pos) + # Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[4, 5, 6], + # [7, 8, 9]]) + + paddle.take(x_int, idx_neg) + # Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[10, 11, 0 ], + # [1 , 2 , 3 ]]) + + paddle.take(x_float, idx_pos) + # Tensor(shape=[2, 3], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[4., 5., 6.], + # [7., 8., 9.]]) + + x_int.take(idx_pos) + # Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[4, 5, 6], + # [7, 8, 9]]) + + paddle.take(x_int, idx_err, mode='wrap') + # Tensor(shape=[3, 5], dtype=int32, place=Place(cpu), stop_gradient=True, + # [[10, 11, 0 , 1 , 2 ], + # [3 , 4 , 5 , 6 , 7 ], + # [8 , 9 , 10, 11, 0 ]]) + + paddle.take(x_int, idx_err, mode='clip') + # Tensor(shape=[3, 5], dtype=int32, place=Place(cpu), stop_gradient=True, + # [[0 , 0 , 0 , 1 , 2 ], + # [3 , 4 , 5 , 6 , 7 ], + # [8 , 9 , 10, 11, 11]]) + + """ + if mode not in ['raise', 'wrap', 'clip']: + raise ValueError( + "'mode' in 'take' should be 'raise', 'wrap', 'clip', but received {}.".format(mode)) + + if paddle.in_dynamic_mode(): + if not isinstance(index, (paddle.Tensor, Variable)): + raise TypeError( + "The type of 'index' must be Tensor, but got {}".format(type(index))) + if index.dtype not in [paddle.int32, paddle.int64]: + raise TypeError( + "The data type of 'index' must be one of ['int32', 'int64'], but got {}".format( + index.dtype)) + + else: + check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'take') + + input_1d = x.flatten() + index_1d = index.flatten() + max_index = input_1d.shape[-1] + + if mode == 'raise': + # This processing enables 'take' to handle negative indexes within the correct range. + index_1d = paddle.where(index_1d < 0, index_1d + max_index, index_1d) + elif mode == 'wrap': + # The out of range indices are constrained by taking the remainder. + index_1d = paddle.where(index_1d < 0, + index_1d % max_index, index_1d) + index_1d = paddle.where(index_1d >= max_index, + index_1d % max_index, index_1d) + elif mode == 'clip': + # 'clip' mode disables indexing with negative numbers. + index_1d = clip(index_1d, 0, max_index - 1) + + out = input_1d.index_select(index_1d).reshape(index.shape) + + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f056bda6157f2f0c73c8fb84af0ae2bebf674f8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/ops.py @@ -0,0 +1,610 @@ +# Copyright (c) 2022 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. + +from __future__ import print_function +import os +from .layer_function_generator import ( + generate_layer_fn, + generate_activation_fn, + generate_inplace_fn, + add_sample_code, +) +from ..framework import core +from ..framework import convert_np_dtype_to_dtype_ +from ..static import Variable +from ..fluid.data_feeder import ( + convert_dtype, + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..fluid.framework import in_dygraph_mode +from .. import _C_ops, _legacy_C_ops + +__deprecated_func_name__ = { + 'tanh_shrink': 'tanhshrink', + 'logsigmoid': 'log_sigmoid', +} + +__activations_noattr__ = [ + 'sigmoid', + 'silu', + 'logsigmoid', + 'tanh_shrink', + 'softplus', + 'softsign', + 'tanh', +] + +__unary_func__ = [ + 'exp', + 'expm1', + 'atan', + 'sqrt', + 'rsqrt', + 'abs', + 'ceil', + 'floor', + 'cos', + 'tan', + 'acos', + 'sin', + 'sinh', + 'asin', + 'cosh', + 'round', + 'reciprocal', + 'square', + 'acosh', + 'asinh', + 'atanh', +] + +__inplace_unary_func__ = [ + 'exp_', + 'sqrt_', + 'rsqrt_', + 'ceil_', + 'floor_', + 'round_', + 'reciprocal_', +] + +__all__ = [] + +# It is a hot fix in some unittest using: +# fluid.layers.scale(x=x, scale=10.0, out=out_var) +# e.g.: test_program_code.py, test_dist_train.py +globals()['_scale'] = generate_layer_fn('scale') + +globals()['_elementwise_div'] = generate_layer_fn('elementwise_div') + +for _OP in set(__activations_noattr__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_activation_fn(_OP) + globals()[_OP] = _func + +for _OP in set(__unary_func__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_activation_fn(_OP) + globals()[_OP] = _func + +for _OP in set(__inplace_unary_func__): + _new_OP = _OP + if _OP in __deprecated_func_name__: + _new_OP = __deprecated_func_name__[_OP] + _func = generate_inplace_fn(_OP) + globals()[_OP] = _func + +add_sample_code( + globals()["sigmoid"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.sigmoid(x) + print(out) + # [0.40131234 0.450166 0.52497919 0.57444252] + +""", +) + +add_sample_code( + globals()["silu"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0]) + out = F.silu(x) + print(out) + # [ 0.7310586 1.7615942 2.8577224, 3.9280552 ] + +""", +) + +add_sample_code( + globals()["logsigmoid"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.log_sigmoid(x) + print(out) + # [-0.91301525 -0.79813887 -0.64439666 -0.55435524] + +""", +) + +add_sample_code( + globals()["exp"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.exp(x) + print(out) + # [0.67032005 0.81873075 1.10517092 1.34985881] + +""", +) + +add_sample_code( + globals()["expm1"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.expm1(x) + print(out) + # [-0.32967997, -0.18126924, 0.10517092, 0.34985882] + +""", +) + +add_sample_code( + globals()["tanh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.tanh(x) + print(out) + # [-0.37994896 -0.19737532 0.09966799 0.29131261] + +""", +) + +add_sample_code( + globals()["atan"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.atan(x) + print(out) + # [-0.38050638 -0.19739556 0.09966865 0.29145679] + +""", +) + +add_sample_code( + globals()["tanh_shrink"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.tanhshrink(x) + print(out) + # [-0.020051, -0.00262468, 0.000332005, 0.00868739] + +""", +) + +add_sample_code( + globals()["sqrt"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4]) + out = paddle.sqrt(x) + print(out) + # [0.31622777 0.4472136 0.54772256 0.63245553] + +""", +) + +add_sample_code( + globals()["rsqrt"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.1, 0.2, 0.3, 0.4]) + out = paddle.rsqrt(x) + print(out) + # [3.16227766 2.23606798 1.82574186 1.58113883] + +""", +) + +add_sample_code( + globals()["abs"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.abs(x) + print(out) + # [0.4 0.2 0.1 0.3] + +""", +) + +add_sample_code( + globals()["ceil"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.ceil(x) + print(out) + # [-0. -0. 1. 1.] + +""", +) + +add_sample_code( + globals()["floor"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.floor(x) + print(out) + # [-1. -1. 0. 0.] + +""", +) + +add_sample_code( + globals()["cos"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.cos(x) + print(out) + # [0.92106099 0.98006658 0.99500417 0.95533649] + +""", +) + +add_sample_code( + globals()["tan"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.tan(x) + print(out) + # [-0.42279324, -0.20271005, 0.10033467, 0.30933627] + +""", +) + +add_sample_code( + globals()["acos"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.acos(x) + print(out) + # [1.98231317 1.77215425 1.47062891 1.26610367] + +""", +) + +add_sample_code( + globals()["sin"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.sin(x) + print(out) + # [-0.38941834 -0.19866933 0.09983342 0.29552021] + +""", +) + +add_sample_code( + globals()["asin"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.asin(x) + print(out) + # [-0.41151685 -0.20135792 0.10016742 0.30469265] + +""", +) + +add_sample_code( + globals()["cosh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.cosh(x) + print(out) + # [1.08107237 1.02006676 1.00500417 1.04533851] + +""", +) + +add_sample_code( + globals()["sinh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.sinh(x) + print(out) + # [-0.41075233 -0.201336 0.10016675 0.30452029] + +""", +) + +add_sample_code( + globals()["asinh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.asinh(x) + print(out) + # [-0.39003533, -0.19869010, 0.09983408, 0.29567307] + +""", +) + +add_sample_code( + globals()["acosh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([1., 3., 4., 5.]) + out = paddle.acosh(x) + print(out) + # [0. , 1.76274729, 2.06343699, 2.29243159] + +""", +) + +add_sample_code( + globals()["atanh"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.atanh(x) + print(out) + # [-0.42364895, -0.20273256, 0.10033535, 0.30951962] + +""", +) + +add_sample_code( + globals()["round"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.5, -0.2, 0.6, 1.5]) + out = paddle.round(x) + print(out) + # [-1. -0. 1. 2.] + +""", +) + +add_sample_code( + globals()["reciprocal"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.reciprocal(x) + print(out) + # [-2.5 -5. 10. 3.33333333] + +""", +) + +add_sample_code( + globals()["square"], + r""" +Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.square(x) + print(out) + # [0.16 0.04 0.01 0.09] + +""", +) + +add_sample_code( + globals()["softplus"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.softplus(x) + print(out) + # [0.513015, 0.598139, 0.744397, 0.854355] + +""", +) + +add_sample_code( + globals()["softsign"], + r""" +Examples: + .. code-block:: python + + import paddle + import paddle.nn.functional as F + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = F.softsign(x) + print(out) + # [-0.285714, -0.166667, 0.0909091, 0.230769] + +""", +) + +_erf_ = generate_layer_fn('erf') + + +def erf(x, name=None): + if in_dygraph_mode(): + return _C_ops.erf(x) + + locals_var = locals().copy() + kwargs = dict() + for name, val in locals_var.items(): + if val is not None: + kwargs[name] = val + return _erf_(**kwargs) + + +erf.__doc__ = r""" +:strong:`Erf Operator` +For more details, see `Error function `_. + +Equation: + .. math:: + out = \frac{2}{\sqrt{\pi}} \int_{0}^{x}e^{- \eta^{2}}d\eta + +Args: + + x (Tensor): The input tensor, it's data type should be float32, float64. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + +Returns: + + Tensor: The output of Erf, dtype: float32 or float64, the same as the input, shape: the same as the input. + +Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3]) + out = paddle.erf(x) + print(out) + # [-0.42839236 -0.22270259 0.11246292 0.32862676] +""" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/random.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/random.py new file mode 100644 index 0000000000000000000000000000000000000000..25c825cda34fdac6a59ad1f1a3841b6085e8d046 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/random.py @@ -0,0 +1,1071 @@ +# 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. + +# TODO: define random functions + +from ..framework import core +from ..framework import convert_np_dtype_to_dtype_, dygraph_only +from ..framework import LayerHelper +from ..fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype, check_shape +from ..fluid.layers import utils +import paddle +from paddle import _C_ops, _legacy_C_ops +from paddle.static import Variable +from paddle.fluid.framework import in_dygraph_mode, _in_legacy_dygraph, _current_expected_place + +__all__ = [] + + +def bernoulli(x, name=None): + """ + + For each element :math:`x_i` in input ``x``, take a sample from the Bernoulli distribution, also called two-point distribution, with success probability :math:`x_i`. The Bernoulli distribution with success probability :math:`x_i` is a discrete probability distribution with probability mass function + + .. math:: + p(y)=\\begin{cases} + x_i,&y=1\\\\ + 1-x_i,&y=0 + \end{cases}. + + Args: + x (Tensor): The input Tensor, it's data type should be float32, float64. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor filled samples from Bernoulli distribution, whose shape and dtype are same as ``x``. + + Examples: + .. code-block:: python + + import paddle + + paddle.set_device('cpu') # on CPU device + paddle.seed(100) + + x = paddle.rand([2,3]) + print(x) + # [[0.55355281, 0.20714243, 0.01162981], + # [0.51577556, 0.36369765, 0.26091650]] + + out = paddle.bernoulli(x) + print(out) + # [[1., 0., 1.], + # [0., 1., 0.]] + + """ + + if in_dygraph_mode(): + return _C_ops.bernoulli(x) + + if _in_legacy_dygraph(): + return _legacy_C_ops.bernoulli(x) + + check_variable_and_dtype(x, "x", ["float32", "float64"], "bernoulli") + + helper = LayerHelper("randint", **locals()) + out = helper.create_variable_for_type_inference( + dtype=x.dtype) # maybe set out to int32 ? + helper.append_op(type='bernoulli', + inputs={"X": x}, + outputs={'Out': out}, + attrs={}) + out.stop_gradient = True + return out + + +def poisson(x, name=None): + r""" + Returns a tensor filled with random number from a Poisson Distribution. + + .. math:: + + out_i \sim Poisson (lambda = x_i) + + Args: + x(Tensor): A tensor with rate parameter of poisson Distribution. The data type + should be float32, float64. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: A Tensor filled with random number with the same shape and dtype as ``x``. + + Examples: + .. code-block:: python + + import paddle + paddle.set_device('cpu') + paddle.seed(100) + + x = paddle.uniform([2,3], min=1.0, max=5.0) + out = paddle.poisson(x) + #[[2., 5., 0.], + # [5., 1., 3.]] + + """ + if in_dygraph_mode(): + return _C_ops.poisson(x) + + if paddle.in_dynamic_mode(): + return _legacy_C_ops.poisson(x) + + check_variable_and_dtype(x, "x", ["float32", "float64"], "poisson") + + helper = LayerHelper("poisson", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='poisson', + inputs={'X': x}, + outputs={'Out': out}, + attrs={}) + return out + + +def multinomial(x, num_samples=1, replacement=False, name=None): + """ + Returns a Tensor filled with random values sampled from a Multinomical + distribution. The input ``x`` is a tensor with probabilities for generating the + random number. Each element in ``x`` should be larger or equal to 0, but not all + 0. ``replacement`` indicates whether it is a replaceable sample. If ``replacement`` + is True, a category can be sampled more than once. + + Args: + x(Tensor): A tensor with probabilities for generating the random number. The data type + should be float32, float64. + num_samples(int, optional): Number of samples, default is 1. + replacement(bool, optional): Whether it is a replaceable sample, default is False. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: A Tensor filled with sampled category index after ``num_samples`` times samples. + + Examples: + .. code-block:: python + + import paddle + + paddle.seed(100) # on CPU device + x = paddle.rand([2,4]) + print(x) + # [[0.5535528 0.20714243 0.01162981 0.51577556] + # [0.36369765 0.2609165 0.18905126 0.5621971 ]] + + paddle.seed(200) # on CPU device + out1 = paddle.multinomial(x, num_samples=5, replacement=True) + print(out1) + # [[3 3 0 0 0] + # [3 3 3 1 0]] + + # out2 = paddle.multinomial(x, num_samples=5) + # InvalidArgumentError: When replacement is False, number of samples + # should be less than non-zero categories + + paddle.seed(300) # on CPU device + out3 = paddle.multinomial(x, num_samples=3) + print(out3) + # [[3 0 1] + # [3 1 0]] + + """ + + assert core.is_compiled_with_rocm() == False, ( + "multinomial op is not supported on ROCM yet.") + + if in_dygraph_mode(): + return _C_ops.multinomial(x, num_samples, replacement) + + if _in_legacy_dygraph(): + return _legacy_C_ops.multinomial(x, 'num_samples', num_samples, + 'replacement', replacement) + + check_variable_and_dtype(x, "x", ["float32", "float64"], "multinomial") + + helper = LayerHelper("multinomial", **locals()) + out = helper.create_variable_for_type_inference( + dtype=convert_np_dtype_to_dtype_('int64')) + helper.append_op(type='multinomial', + inputs={"X": x}, + outputs={'Out': out}, + attrs={ + 'num_samples': num_samples, + 'replacement': replacement + }) + out.stop_gradient = True + return out + + +def gaussian(shape, mean=0.0, std=1.0, dtype=None, name=None): + """ + Returns a Tensor filled with random values sampled from a Gaussian + distribution, with ``shape`` and ``dtype``. + + Args: + shape (list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + mean (float|int, optional): Mean of the output tensor, default is 0.0. + std (float|int, optional): Standard deviation of the output tensor, default + is 1.0. + seed (int, optional): Random seed of generator. + dtype (str|np.dtype, optional): The data type of the output Tensor. + Supported data types: float32, float64. + Default is None, use global default dtype (see ``get_default_dtype`` + for details). + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a Gaussian + distribution, with ``shape`` and ``dtype``. + """ + op_type_for_check = 'gaussian/standard_normal/randn/normal' + seed = 0 + + if dtype is None: + dtype = paddle.framework.get_default_dtype() + if dtype not in ['float32', 'float64']: + raise TypeError( + "{} only supports [float32, float64], but the default dtype is {}" + .format(op_type_for_check, dtype)) + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + place = _current_expected_place() + return _C_ops.gaussian_random(shape, float(mean), float(std), seed, + dtype, place) + + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + return _legacy_C_ops.gaussian_random('shape', shape, + 'mean', float(mean), 'std', + float(std), 'seed', seed, 'dtype', + dtype) + + check_shape(shape, op_type_for_check) + check_dtype(dtype, 'dtype', ['float32', 'float64'], op_type_for_check) + + inputs = {} + attrs = { + 'mean': mean, + 'std': std, + 'seed': seed, + 'dtype': dtype, + 'use_mkldnn': False + } + utils.get_shape_tensor_inputs(inputs=inputs, + attrs=attrs, + shape=shape, + op_type=op_type_for_check) + + helper = LayerHelper('gaussian', **locals()) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type='gaussian_random', + inputs=inputs, + outputs={'Out': out}, + attrs=attrs) + out.stop_gradient = True + return out + + +def standard_normal(shape, dtype=None, name=None): + """ + Returns a Tensor filled with random values sampled from a standard + normal distribution with mean 0 and standard deviation 1, with ``shape`` + and ``dtype``. + + Args: + shape (list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + dtype (str|np.dtype, optional): The data type of the output Tensor. + Supported data types: float32, float64. + Default is None, use global default dtype (see ``get_default_dtype`` + for details). + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a standard + normal distribution with mean 0 and standard deviation 1, with + ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + # example 1: attr shape is a list which doesn't contain Tensor. + out1 = paddle.standard_normal(shape=[2, 3]) + # [[-2.923464 , 0.11934398, -0.51249987], # random + # [ 0.39632758, 0.08177969, 0.2692008 ]] # random + + # example 2: attr shape is a list which contains Tensor. + dim1 = paddle.to_tensor([2], 'int64') + dim2 = paddle.to_tensor([3], 'int32') + out2 = paddle.standard_normal(shape=[dim1, dim2, 2]) + # [[[-2.8852394 , -0.25898588], # random + # [-0.47420555, 0.17683524], # random + # [-0.7989969 , 0.00754541]], # random + # [[ 0.85201347, 0.32320443], # random + # [ 1.1399018 , 0.48336947], # random + # [ 0.8086993 , 0.6868893 ]]] # random + + # example 3: attr shape is a Tensor, the data type must be int64 or int32. + shape_tensor = paddle.to_tensor([2, 3]) + out3 = paddle.standard_normal(shape_tensor) + # [[-2.878077 , 0.17099959, 0.05111201] # random + # [-0.3761474, -1.044801 , 1.1870178 ]] # random + + """ + return gaussian(shape=shape, mean=0.0, std=1.0, dtype=dtype, name=name) + + +def randn(shape, dtype=None, name=None): + """ + Returns a Tensor filled with random values sampled from a standard + normal distribution with mean 0 and standard deviation 1, with ``shape`` + and ``dtype``. + + Args: + shape (list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + dtype (str|np.dtype, optional): The data type of the output Tensor. + Supported data types: float32, float64. + Default is None, use global default dtype (see ``get_default_dtype`` + for details). + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a standard + normal distribution with mean 0 and standard deviation 1, with + ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + # example 1: attr shape is a list which doesn't contain Tensor. + out1 = paddle.randn(shape=[2, 3]) + # [[-2.923464 , 0.11934398, -0.51249987], # random + # [ 0.39632758, 0.08177969, 0.2692008 ]] # random + + # example 2: attr shape is a list which contains Tensor. + dim1 = paddle.to_tensor([2], 'int64') + dim2 = paddle.to_tensor([3], 'int32') + out2 = paddle.randn(shape=[dim1, dim2, 2]) + # [[[-2.8852394 , -0.25898588], # random + # [-0.47420555, 0.17683524], # random + # [-0.7989969 , 0.00754541]], # random + # [[ 0.85201347, 0.32320443], # random + # [ 1.1399018 , 0.48336947], # random + # [ 0.8086993 , 0.6868893 ]]] # random + + # example 3: attr shape is a Tensor, the data type must be int64 or int32. + shape_tensor = paddle.to_tensor([2, 3]) + out3 = paddle.randn(shape_tensor) + # [[-2.878077 , 0.17099959, 0.05111201] # random + # [-0.3761474, -1.044801 , 1.1870178 ]] # random + """ + return standard_normal(shape, dtype, name) + + +def normal(mean=0.0, std=1.0, shape=None, name=None): + """ + Returns a Tensor filled with random values sampled from a normal + distribution with ``mean`` and ``std`` (standard deviation) . + + If ``mean`` is a Tensor, the output Tensor has the same shape and data type as ``mean``. + If ``mean`` is not a Tensor and ``std`` is a Tensor, the output Tensor has the same shape and data type as ``std``. + If ``mean`` and ``std`` are not a Tensor, the output Tensor has the same shape as ``shape``, with data type float32. + + If ``mean`` and ``std`` are Tensor, the num of elements of ``mean`` and ``std`` should be the same. + + Args: + mean (float|Tensor, optional): The mean of the output Tensor's normal distribution. + If ``mean`` is float, all elements of the output Tensor shared the same mean. + If ``mean`` is a Tensor(data type supports float32, float64), it has per-element means. + Default is 0.0 + std (float|Tensor, optional): The standard deviation of the output Tensor's normal distribution. + If ``std`` is float, all elements of the output Tensor shared the same standard deviation. + If ``std`` is a Tensor(data type supports float32, float64), it has per-element standard deviations. + Defaule is 1.0 + shape (list|tuple|Tensor, optional): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). If ``mean`` or ``std`` is a Tensor, the shape of the output + Tensor is the same as ``mean`` or ``std`` , attr ``shape`` is ignored. + Default is None + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + A Tensor filled with random values sampled from a normal distribution with ``mean`` and ``std`` . + + Examples: + .. code-block:: python + + import paddle + + out1 = paddle.normal(shape=[2, 3]) + # [[ 0.17501129 0.32364586 1.561118 ] # random + # [-1.7232178 1.1545963 -0.76156676]] # random + + mean_tensor = paddle.to_tensor([1.0, 2.0, 3.0]) + out2 = paddle.normal(mean=mean_tensor) + # [ 0.18644847 -1.19434458 3.93694787] # random + + std_tensor = paddle.to_tensor([1.0, 2.0, 3.0]) + out3 = paddle.normal(mean=mean_tensor, std=std_tensor) + # [1.00780561 3.78457445 5.81058198] # random + + """ + if not paddle.in_dynamic_mode(): + check_type(mean, 'mean', (int, float, Variable), 'normal') + check_type(std, 'std', (int, float, Variable), 'normal') + if isinstance(mean, Variable): + check_dtype( + mean.dtype, 'mean', ['float32', 'float64'], 'normal', + "If mean is Tensor, it's data type only support float32, float64." + ) + if isinstance(std, Variable): + check_dtype( + std.dtype, 'std', ['float32', 'float64'], 'normal', + "If std is Tensor, it's data type only support float32, float64." + ) + if shape is not None: + check_shape(shape, 'normal') + + if isinstance(mean, Variable): + if isinstance(std, Variable): + if std.dtype != mean.dtype: + std = paddle.cast(std, mean.dtype) + mean_shape = paddle.shape(mean) + std = paddle.reshape(std, mean_shape) + else: + std = float(std) + out = standard_normal(paddle.shape(mean), mean.dtype, name) + elif isinstance(std, Variable): + mean = float(mean) + out = standard_normal(paddle.shape(std), std.dtype, name) + else: + return gaussian(shape=shape, mean=mean, std=std, name=name) + + out = out * std + mean + if not paddle.in_dynamic_mode(): + out.stop_grediant = True + return out + + +def uniform(shape, dtype=None, min=-1.0, max=1.0, seed=0, name=None): + """ + Returns a Tensor filled with random values sampled from a uniform + distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. + + Examples: + + .. code-block:: text + + Input: + shape = [1, 2] + Output: + result=[[0.8505902, 0.8397286]] + + Args: + shape(list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + dtype(str|np.dtype, optional): The data type of the output Tensor. + Supported data types: float32, float64. + Default is None, use global default dtype (see ``get_default_dtype`` + for details). + min(float|int, optional): The lower bound on the range of random values + to generate, ``min`` is included in the range. Default is -1.0. + max(float|int, optional): The upper bound on the range of random values + to generate, ``max`` is excluded in the range. Default is 1.0. + seed(int, optional): Random seed used for generating samples. If seed is 0, + it will use the seed of the global default generator (which can be set by paddle.seed). + Note that if seed is not 0, this operator will always generate the same random numbers every + time. Default is 0. + name(str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a uniform + distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + :name: code-example1 + + import paddle + + # example 1: + # attr shape is a list which doesn't contain Tensor. + out1 = paddle.uniform(shape=[3, 4]) + # [[ 0.84524226, 0.6921872, 0.56528175, 0.71690357], # random + # [-0.34646994, -0.45116323, -0.09902662, -0.11397249], # random + # [ 0.433519, 0.39483607, -0.8660099, 0.83664286]] # random + + # example 2: + # attr shape is a list which contains Tensor. + dim1 = paddle.to_tensor([2], 'int64') + dim2 = paddle.to_tensor([3], 'int32') + out2 = paddle.uniform(shape=[dim1, dim2]) + # [[-0.9951253, 0.30757582, 0.9899647 ], # random + # [ 0.5864527, 0.6607096, -0.8886161]] # random + + # example 3: + # attr shape is a Tensor, the data type must be int64 or int32. + shape_tensor = paddle.to_tensor([2, 3]) + out3 = paddle.uniform(shape_tensor) + # [[-0.8517412, -0.4006908, 0.2551912 ], # random + # [ 0.3364414, 0.36278176, -0.16085452]] # random + """ + if dtype is None: + dtype = paddle.framework.get_default_dtype() + if dtype not in ['float32', 'float64']: + raise TypeError( + "uniform/rand only supports [float32, float64], but the default dtype is {}" + .format(dtype)) + + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + return _C_ops.uniform_random(shape, dtype, float(min), float(max), seed, + _current_expected_place()) + + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + return _legacy_C_ops.uniform_random('shape', + shape, 'min', float(min), 'max', + float(max), 'seed', seed, 'dtype', + dtype) + + check_type(shape, 'shape', (list, tuple, Variable), 'uniform/rand') + check_dtype(dtype, 'dtype', ('float32', 'float64'), 'uniform/rand') + check_type(min, 'min', (float, int, Variable), 'uniform/rand') + check_type(max, 'max', (float, int, Variable), 'uniform/rand') + + inputs = dict() + attrs = {'seed': seed, 'min': min, 'max': max, 'dtype': dtype} + utils.get_shape_tensor_inputs(inputs=inputs, + attrs=attrs, + shape=shape, + op_type='uniform/rand') + + helper = LayerHelper("uniform", **locals()) + out = helper.create_variable_for_type_inference(dtype) + helper.append_op(type="uniform_random", + inputs=inputs, + attrs=attrs, + outputs={"Out": out}) + out.stop_gradient = True + return out + + +@dygraph_only +def uniform_(x, min=-1.0, max=1.0, seed=0, name=None): + """ + This is the inplace version of OP ``uniform``, which returns a Tensor filled + with random values sampled from a uniform distribution. The output Tensor will + be inplaced with input ``x``. Please refer to :ref:`api_tensor_uniform`. + + Args: + x(Tensor): The input tensor to be filled with random values. + min(float|int, optional): The lower bound on the range of random values + to generate, ``min`` is included in the range. Default is -1.0. + max(float|int, optional): The upper bound on the range of random values + to generate, ``max`` is excluded in the range. Default is 1.0. + seed(int, optional): Random seed used for generating samples. If seed is 0, + it will use the seed of the global default generator (which can be set by paddle.seed). + Note that if seed is not 0, this operator will always generate the same random numbers every + time. Default is 0. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: The input tensor x filled with random values sampled from a uniform + distribution in the range [``min``, ``max``). + Examples: + .. code-block:: python + + import paddle + # example: + x = paddle.ones(shape=[3, 4]) + x.uniform_() + print(x) + # [[ 0.84524226, 0.6921872, 0.56528175, 0.71690357], # random + # [-0.34646994, -0.45116323, -0.09902662, -0.11397249], # random + # [ 0.433519, 0.39483607, -0.8660099, 0.83664286]] # random + """ + if in_dygraph_mode(): + return _C_ops.uniform_random_inplace_(x, min, max, seed, 0, 0, 1.0) + else: + return _legacy_C_ops.uniform_random_inplace_(x, 'min', min, 'max', max, + 'seed', seed) + + +def randint(low=0, high=None, shape=[1], dtype=None, name=None): + """ + Returns a Tensor filled with random integers from a discrete uniform + distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``. + If ``high`` is None (the default), the range is [0, ``low``). + + Args: + low (int, optional): The lower bound on the range of random values to generate. + The ``low`` is included in the range. If ``high`` is None, the + range is [0, ``low``). Default is 0. + high (int, optional): The upper bound on the range of random values to + generate, the ``high`` is excluded in the range. Default is None + (see above for behavior if high = None). Default is None. + shape (list|tuple|Tensor, optional): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). Default is [1]. + dtype (str|np.dtype, optional): The data type of the + output tensor. Supported data types: int32, int64. If ``dytpe`` + is None, the data type is int64. Default is None. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random integers from a discrete uniform + distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + # example 1: + # attr shape is a list which doesn't contain Tensor. + out1 = paddle.randint(low=-5, high=5, shape=[3]) + # [0, -3, 2] # random + + # example 2: + # attr shape is a list which contains Tensor. + dim1 = paddle.to_tensor([2], 'int64') + dim2 = paddle.to_tensor([3], 'int32') + out2 = paddle.randint(low=-5, high=5, shape=[dim1, dim2]) + # [[0, -1, -3], # random + # [4, -2, 0]] # random + + # example 3: + # attr shape is a Tensor + shape_tensor = paddle.to_tensor(3) + out3 = paddle.randint(low=-5, high=5, shape=shape_tensor) + # [-2, 2, 3] # random + + # example 4: + # data type is int32 + out4 = paddle.randint(low=-5, high=5, shape=[3], dtype='int32') + # [-5, 4, -4] # random + + # example 5: + # Input only one parameter + # low=0, high=10, shape=[1], dtype='int64' + out5 = paddle.randint(10) + # [7] # random + + """ + if high is None: + if low <= 0: + raise ValueError( + "If high is None, low must be greater than 0, but received low = {0}." + .format(low)) + high = low + low = 0 + if dtype is None: + dtype = 'int64' + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + shape = utils.convert_shape_to_list(shape) + place = _current_expected_place() + return _C_ops.randint(low, high, shape, dtype, place) + if _in_legacy_dygraph(): + shape = utils.convert_shape_to_list(shape) + return _legacy_C_ops.randint('shape', shape, 'low', low, 'high', high, + 'seed', 0, 'dtype', dtype) + + check_shape(shape, 'randint') + check_dtype(dtype, 'dtype', ['int32', 'int64'], 'randint') + if low >= high: + raise ValueError( + "randint's low must less then high, but received low = {0}, " + "high = {1}".format(low, high)) + + inputs = dict() + attrs = {'low': low, 'high': high, 'seed': 0, 'dtype': dtype} + utils.get_shape_tensor_inputs(inputs=inputs, + attrs=attrs, + shape=shape, + op_type='randint') + + helper = LayerHelper("randint", **locals()) + out = helper.create_variable_for_type_inference(dtype=dtype) + helper.append_op(type='randint', + inputs=inputs, + outputs={'Out': out}, + attrs=attrs) + out.stop_gradient = True + return out + + +def randint_like(x, low=0, high=None, dtype=None, name=None): + """ + Returns a Tensor filled with random integers from a discrete uniform + distribution in the range [``low``, ``high``), with the same shape as ``x``. + (use ``dtype`` if ``dtype`` is not None) + If ``high`` is None (the default), the range is [0, ``low``). + + Args: + x (Tensor): The input tensor which specifies shape. The dtype of ``x`` + can be bool, int32, int64, float16, float32, float64. + low (int): The lower bound on the range of random values to generate. + The ``low`` is included in the range. If ``high`` is None, the + range is [0, ``low``). Default is 0. + high (int, optional): The upper bound on the range of random values to + generate, the ``high`` is excluded in the range. Default is None + (see above for behavior if high = None). Default is None. + dtype (str|np.dtype, optional): The data type of the + output tensor. Supported data types: bool, int32, int64, float16, + float32, float64. If ``dytpe`` is None, the data type is the + same as x's data type. Default is None. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random integers from a discrete uniform + distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + # example 1: + # dtype is None and the dtype of x is float16 + x = paddle.zeros((1,2)).astype("float16") + out1 = paddle.randint_like(x, low=-5, high=5) + print(out1) + print(out1.dtype) + # [[0, -3]] # random + # paddle.float16 + + # example 2: + # dtype is None and the dtype of x is float32 + x = paddle.zeros((1,2)).astype("float32") + out2 = paddle.randint_like(x, low=-5, high=5) + print(out2) + print(out2.dtype) + # [[0, -3]] # random + # paddle.float32 + + # example 3: + # dtype is None and the dtype of x is float64 + x = paddle.zeros((1,2)).astype("float64") + out3 = paddle.randint_like(x, low=-5, high=5) + print(out3) + print(out3.dtype) + # [[0, -3]] # random + # paddle.float64 + + # example 4: + # dtype is None and the dtype of x is int32 + x = paddle.zeros((1,2)).astype("int32") + out4 = paddle.randint_like(x, low=-5, high=5) + print(out4) + print(out4.dtype) + # [[0, -3]] # random + # paddle.int32 + + # example 5: + # dtype is None and the dtype of x is int64 + x = paddle.zeros((1,2)).astype("int64") + out5 = paddle.randint_like(x, low=-5, high=5) + print(out5) + print(out5.dtype) + # [[0, -3]] # random + # paddle.int64 + + # example 6: + # dtype is float64 and the dtype of x is float32 + x = paddle.zeros((1,2)).astype("float32") + out6 = paddle.randint_like(x, low=-5, high=5, dtype="float64") + print(out6) + print(out6.dtype) + # [[0, -1]] # random + # paddle.float64 + + # example 7: + # dtype is bool and the dtype of x is float32 + x = paddle.zeros((1,2)).astype("float32") + out7 = paddle.randint_like(x, low=-5, high=5, dtype="bool") + print(out7) + print(out7.dtype) + # [[0, -1]] # random + # paddle.bool + + # example 8: + # dtype is int32 and the dtype of x is float32 + x = paddle.zeros((1,2)).astype("float32") + out8 = paddle.randint_like(x, low=-5, high=5, dtype="int32") + print(out8) + print(out8.dtype) + # [[0, -1]] # random + # paddle.int32 + + # example 9: + # dtype is int64 and the dtype of x is float32 + x = paddle.zeros((1,2)).astype("float32") + out9 = paddle.randint_like(x, low=-5, high=5, dtype="int64") + print(out9) + print(out9.dtype) + # [[0, -1]] # random + # paddle.int64 + + # example 10: + # dtype is int64 and the dtype of x is bool + x = paddle.zeros((1,2)).astype("bool") + out10 = paddle.randint_like(x, low=-5, high=5, dtype="int64") + print(out10) + print(out10.dtype) + # [[0, -1]] # random + # paddle.int64 + + """ + if high is None: + if low <= 0: + raise ValueError( + "If high is None, low must be greater than 0, but received low = {0}." + .format(low)) + high = low + low = 0 + if dtype is None: + dtype = x.dtype + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + shape = paddle.shape(x) + + if low >= high: + raise ValueError( + "randint_like's low must less then high, but received low = {0}, " + "high = {1}".format(low, high)) + + if paddle.in_dynamic_mode(): + shape = utils.convert_shape_to_list(shape) + out = _legacy_C_ops.randint('shape', shape, 'low', low, 'high', high, + 'seed', 0, 'dtype', + core.VarDesc.VarType.INT64) + out = paddle.cast(out, dtype) + return out + + check_shape(shape, 'randint_like') + check_dtype(dtype, 'dtype', + ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'], + 'randint_like') + + inputs = {"ShapeTensor": shape} + attrs = { + 'low': low, + 'high': high, + 'seed': 0, + 'dtype': core.VarDesc.VarType.INT64 + } + + helper = LayerHelper("randint", **locals()) + out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.INT64) + helper.append_op(type='randint', + inputs=inputs, + outputs={'Out': out}, + attrs=attrs) + out.stop_gradient = True + out = paddle.cast(out, dtype) + return out + + +def randperm(n, dtype="int64", name=None): + """ + Returns a 1-D Tensor filled with random permutation values from 0 + to n-1, with ``dtype``. + + Args: + n (int): The upper bound (exclusive), and it should be greater than 0. + dtype (str|np.dtype, optional): The data type of + the output Tensor. Supported data types: int32, int64, float32, + float64. Default is int64. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A 1-D Tensor filled with random permutation values from 0 + to n-1, with ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + out1 = paddle.randperm(5) + # [4, 1, 2, 3, 0] # random + + out2 = paddle.randperm(7, 'int32') + # [1, 6, 2, 0, 4, 3, 5] # random + + """ + if not isinstance(dtype, core.VarDesc.VarType): + dtype = convert_np_dtype_to_dtype_(dtype) + + if in_dygraph_mode(): + return _C_ops.randperm(n, dtype, _current_expected_place()) + if _in_legacy_dygraph(): + return _legacy_C_ops.randperm('n', n, 'seed', 0, 'dtype', dtype) + + if n < 1: + raise ValueError("The input n should be greater than 0 in randperm op.") + check_dtype(dtype, 'dtype', ['int64', 'int32', 'float32', 'float64'], + 'randperm') + + helper = LayerHelper("randperm", **locals()) + out = helper.create_variable_for_type_inference(dtype) + attrs = {'n': n, 'dtype': dtype, 'seed': 0} + helper.append_op(type='randperm', + inputs={}, + outputs={'Out': out}, + attrs=attrs) + out.stop_gradient = True + return out + + +def rand(shape, dtype=None, name=None): + """ + Returns a Tensor filled with random values sampled from a uniform + distribution in the range [0, 1), with ``shape`` and ``dtype``. + + Args: + shape (list|tuple|Tensor): The shape of the output Tensor. If ``shape`` + is a list or tuple, the elements of it should be integers or Tensors + (with the shape [1], and the data type int32 or int64). If ``shape`` + is a Tensor, it should be a 1-D Tensor(with the data type int32 or + int64). + dtype (str|np.dtype, optional): The data type of the output Tensor. + Supported data types: float32, float64. + Default is None, use global default dtype (see ``get_default_dtype`` + for details). + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + Tensor: A Tensor filled with random values sampled from a uniform + distribution in the range [0, 1), with ``shape`` and ``dtype``. + + Examples: + .. code-block:: python + + import paddle + + # example 1: attr shape is a list which doesn't contain Tensor. + out1 = paddle.rand(shape=[2, 3]) + # [[0.451152 , 0.55825245, 0.403311 ], # random + # [0.22550228, 0.22106001, 0.7877319 ]] # random + + # example 2: attr shape is a list which contains Tensor. + dim1 = paddle.to_tensor([2], 'int64') + dim2 = paddle.to_tensor([3], 'int32') + out2 = paddle.rand(shape=[dim1, dim2, 2]) + # [[[0.8879919 , 0.25788337], # random + # [0.28826773, 0.9712097 ], # random + # [0.26438272, 0.01796806]], # random + # [[0.33633623, 0.28654453], # random + # [0.79109055, 0.7305809 ], # random + # [0.870881 , 0.2984597 ]]] # random + + # example 3: attr shape is a Tensor, the data type must be int64 or int32. + shape_tensor = paddle.to_tensor([2, 3]) + out3 = paddle.rand(shape_tensor) + # [[0.22920267, 0.841956 , 0.05981819], # random + # [0.4836288 , 0.24573246, 0.7516129 ]] # random + + """ + return uniform(shape, dtype, min=0.0, max=1.0, name=name) + + +def exponential_(x, lam=1.0, name=None): + r""" + This inplace OP fill input Tensor ``x`` with random number from a Exponential Distribution. + + ``lam`` is :math:`\lambda` parameter of Exponential Distribution. + + .. math:: + + f(x) = \lambda e^{-\lambda x} + + Args: + x(Tensor): Input tensor. The data type should be float32, float64. + lam(float, optional): :math:`\lambda` parameter of Exponential Distribution. Default, 1.0. + name(str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: Input Tensor ``x``. + + Examples: + .. code-block:: python + + import paddle + paddle.set_device('cpu') + paddle.seed(100) + + x = paddle.empty([2,3]) + x.exponential_() + # [[0.80643415, 0.23211166, 0.01169797], + # [0.72520673, 0.45208144, 0.30234432]] + + """ + if in_dygraph_mode(): + return _C_ops.exponential_(x, lam) + elif paddle.in_dynamic_mode(): + return _legacy_C_ops.exponential_(x, "lambda", lam) + + check_variable_and_dtype(x, "x", ["float32", "float64"], "exponential") + + helper = LayerHelper("exponential", **locals()) + helper.append_op(type='exponential', + inputs={"X": x}, + outputs={'Out': x}, + attrs={"lambda": lam}) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/search.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/search.py new file mode 100644 index 0000000000000000000000000000000000000000..e4458048edc6bb39d32349f86aab20cbc3e9e68c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/search.py @@ -0,0 +1,1108 @@ +# Copyright (c) 2022 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. +from __future__ import print_function +import numpy as np +import paddle +from ..framework import LayerHelper +from ..fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype +from ..fluid import layers +from ..framework import core, in_dygraph_mode, _non_static_mode +from ..fluid.framework import _in_legacy_dygraph +from paddle.common_ops_import import convert_np_dtype_to_dtype_ +from paddle.common_ops_import import Variable +from paddle.common_ops_import import VarDesc +from paddle import _C_ops, _legacy_C_ops +from .logic import logical_not + +# TODO: define searching & indexing functions of a tensor +# from ..fluid.layers import has_inf #DEFINE_ALIAS +# from ..fluid.layers import has_nan #DEFINE_ALIAS + +__all__ = [] + + +def argsort(x, axis=-1, descending=False, name=None): + """ + Sorts the input along the given axis, and returns the corresponding index tensor for the sorted output values. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True. + + Args: + x(Tensor): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is Rank(x). when axis<0, it works the same way + as axis+R. Default is -1. + descending(bool, optional) : Descending is a flag, if set to true, + algorithm will sort by descending order, else sort by + ascending order. Default is false. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: sorted indices(with the same shape as ``x`` + and with data type int64). + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[[5,8,9,5], + [0,0,1,7], + [6,9,2,4]], + [[5,2,4,2], + [4,7,7,9], + [1,7,0,6]]], + dtype='float32') + out1 = paddle.argsort(x, axis=-1) + out2 = paddle.argsort(x, axis=0) + out3 = paddle.argsort(x, axis=1) + + print(out1) + #[[[0 3 1 2] + # [0 1 2 3] + # [2 3 0 1]] + # [[1 3 2 0] + # [0 1 2 3] + # [2 0 3 1]]] + + print(out2) + #[[[0 1 1 1] + # [0 0 0 0] + # [1 1 1 0]] + # [[1 0 0 0] + # [1 1 1 1] + # [0 0 0 1]]] + + print(out3) + #[[[1 1 1 2] + # [0 0 2 0] + # [2 2 0 1]] + # [[2 0 2 0] + # [1 1 0 2] + # [0 2 1 1]]] + """ + if in_dygraph_mode(): + _, ids = _C_ops.argsort(x, axis, descending) + return ids + + if _in_legacy_dygraph(): + _, ids = _legacy_C_ops.argsort(x, 'axis', axis, 'descending', + descending) + return ids + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int16', 'int32', 'int64', 'uint8'], + 'argsort') + + helper = LayerHelper("argsort", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype, + stop_gradient=True) + ids = helper.create_variable_for_type_inference(VarDesc.VarType.INT64, + stop_gradient=True) + helper.append_op(type='argsort', + inputs={'X': x}, + outputs={ + 'Out': out, + 'Indices': ids + }, + attrs={ + 'axis': axis, + 'descending': descending + }) + return ids + + +def argmax(x, axis=None, keepdim=False, dtype="int64", name=None): + """ + Computes the indices of the max elements of the input tensor's + element along the provided axis. + + Args: + x(Tensor): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is x.ndim. when axis < 0, it works the same way + as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index. + keepdim(bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False. + dtype(str|np.dtype, optional): Data type of the output tensor which can + be int32, int64. The default value is ``int64`` , and it will + return the int64 indices. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, return the tensor of int32 if set :attr:`dtype` is int32, otherwise return the tensor of int64. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[5,8,9,5], + [0,0,1,7], + [6,9,2,4]]) + out1 = paddle.argmax(x) + print(out1) # 2 + out2 = paddle.argmax(x, axis=0) + print(out2) + # [2, 2, 0, 1] + out3 = paddle.argmax(x, axis=-1) + print(out3) + # [2, 3, 1] + out4 = paddle.argmax(x, axis=0, keepdim=True) + print(out4) + # [[2, 2, 0, 1]] + """ + if axis is not None and not isinstance(axis, (int, Variable)): + raise TypeError( + "The type of 'axis' must be int or Tensor or None in argmax, but received %s." + % (type(axis))) + + if dtype is None: + raise ValueError( + "the value of 'dtype' in argmax could not be None, but received None" + ) + + var_dtype = convert_np_dtype_to_dtype_(dtype) + flatten = False + if axis is None: + flatten = True + axis = 0 + + if in_dygraph_mode(): + return _C_ops.argmax(x, axis, keepdim, flatten, var_dtype) + if _in_legacy_dygraph(): + out = _legacy_C_ops.arg_max(x, 'axis', axis, 'dtype', var_dtype, + 'keepdims', keepdim, 'flatten', flatten) + return out + + helper = LayerHelper("argmax", **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int16', 'int32', 'int64', 'uint8'], + 'paddle.argmax') + check_dtype(var_dtype, 'dtype', ['int32', 'int64'], 'argmin') + attrs = {} + out = helper.create_variable_for_type_inference(var_dtype) + attrs['keepdims'] = keepdim + attrs['axis'] = axis + attrs['flatten'] = flatten + attrs['dtype'] = var_dtype + helper.append_op(type='arg_max', + inputs={'X': x}, + outputs={'Out': [out]}, + attrs=attrs) + out.stop_gradient = True + return out + + +def argmin(x, axis=None, keepdim=False, dtype="int64", name=None): + """ + Computes the indices of the min elements of the input tensor's + element along the provided axis. + + Args: + x(Tensor): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is x.ndim. when axis < 0, it works the same way + as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index. + keepdim(bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False. + dtype(str, optional): Data type of the output tensor which can + be int32, int64. The default value is 'int64', and it will + return the int64 indices. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor, return the tensor of `int32` if set :attr:`dtype` is `int32`, otherwise return the tensor of `int64`. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[5,8,9,5], + [0,0,1,7], + [6,9,2,4]]) + out1 = paddle.argmin(x) + print(out1) # 4 + out2 = paddle.argmin(x, axis=0) + print(out2) + # [1, 1, 1, 2] + out3 = paddle.argmin(x, axis=-1) + print(out3) + # [0, 0, 2] + out4 = paddle.argmin(x, axis=0, keepdim=True) + print(out4) + # [[1, 1, 1, 2]] + """ + if axis is not None and not isinstance(axis, (int, Variable)): + raise TypeError( + "The type of 'axis' must be int or Tensor or None in argmin, but received %s." + % (type(axis))) + + if dtype is None: + raise ValueError( + "the value of 'dtype' in argmin could not be None, but received None" + ) + + var_dtype = convert_np_dtype_to_dtype_(dtype) + flatten = False + if axis is None: + flatten = True + axis = 0 + + if in_dygraph_mode(): + return _C_ops.argmin(x, axis, keepdim, flatten, var_dtype) + if _in_legacy_dygraph(): + out = _legacy_C_ops.arg_min(x, 'axis', axis, 'dtype', var_dtype, + 'keepdims', keepdim, 'flatten', flatten) + return out + + helper = LayerHelper("argmin", **locals()) + check_variable_and_dtype( + x, 'x', ['float32', 'float64', 'int16', 'int32', 'int64', 'uint8'], + 'paddle.argmin') + check_dtype(var_dtype, 'dtype', ['int32', 'int64'], 'argmin') + out = helper.create_variable_for_type_inference(var_dtype) + attrs = {} + attrs['keepdims'] = keepdim + attrs['axis'] = axis + attrs['flatten'] = flatten + attrs['dtype'] = var_dtype + helper.append_op(type='arg_min', + inputs={'X': x}, + outputs={'Out': [out]}, + attrs=attrs) + out.stop_gradient = True + return out + + +def index_select(x, index, axis=0, name=None): + """ + + Returns a new tensor which indexes the ``input`` tensor along dimension ``axis`` using + the entries in ``index`` which is a Tensor. The returned tensor has the same number + of dimensions as the original ``x`` tensor. The dim-th dimension has the same + size as the length of ``index``; other dimensions have the same size as in the ``x`` tensor. + + Args: + x (Tensor): The input Tensor to be operated. The data of ``x`` can be one of float32, float64, int32, int64. + index (Tensor): The 1-D Tensor containing the indices to index. The data type of ``index`` must be int32 or int64. + axis (int, optional): The dimension in which we index. Default: if None, the ``axis`` is 0. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor with same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0]]) + index = paddle.to_tensor([0, 1, 1], dtype='int32') + out_z1 = paddle.index_select(x=x, index=index) + #[[1. 2. 3. 4.] + # [5. 6. 7. 8.] + # [5. 6. 7. 8.]] + out_z2 = paddle.index_select(x=x, index=index, axis=1) + #[[ 1. 2. 2.] + # [ 5. 6. 6.] + # [ 9. 10. 10.]] + """ + + if in_dygraph_mode(): + return _C_ops.index_select(x, index, axis) + + if _in_legacy_dygraph(): + return _legacy_C_ops.index_select(x, index, 'dim', axis) + + helper = LayerHelper("index_select", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.search.index_select') + check_variable_and_dtype(index, 'index', ['int32', 'int64'], + 'paddle.tensor.search.index_select') + + out = helper.create_variable_for_type_inference(x.dtype) + + helper.append_op(type='index_select', + inputs={ + 'X': x, + 'Index': index + }, + outputs={'Out': out}, + attrs={'dim': axis}) + return out + + +def nonzero(x, as_tuple=False): + """ + Return a tensor containing the indices of all non-zero elements of the `input` + tensor. If as_tuple is True, return a tuple of 1-D tensors, one for each dimension + in `input`, each containing the indices (in that dimension) of all non-zero elements + of `input`. Given a n-Dimensional `input` tensor with shape [x_1, x_2, ..., x_n], If + as_tuple is False, we can get a output tensor with shape [z, n], where `z` is the + number of all non-zero elements in the `input` tensor. If as_tuple is True, we can get + a 1-D tensor tuple of length `n`, and the shape of each 1-D tensor is [z, 1]. + + Args: + x (Tensor): The input tensor variable. + as_tuple (bool): Return type, Tensor or tuple of Tensor. + + Returns: + Tensor. The data type is int64. + + Examples: + + .. code-block:: python + + import paddle + + x1 = paddle.to_tensor([[1.0, 0.0, 0.0], + [0.0, 2.0, 0.0], + [0.0, 0.0, 3.0]]) + x2 = paddle.to_tensor([0.0, 1.0, 0.0, 3.0]) + out_z1 = paddle.nonzero(x1) + print(out_z1) + #[[0 0] + # [1 1] + # [2 2]] + out_z1_tuple = paddle.nonzero(x1, as_tuple=True) + for out in out_z1_tuple: + print(out) + #[[0] + # [1] + # [2]] + #[[0] + # [1] + # [2]] + out_z2 = paddle.nonzero(x2) + print(out_z2) + #[[1] + # [3]] + out_z2_tuple = paddle.nonzero(x2, as_tuple=True) + for out in out_z2_tuple: + print(out) + #[[1] + # [3]] + + """ + list_out = [] + shape = x.shape + rank = len(shape) + + if in_dygraph_mode(): + outs = _C_ops.where_index(x) + elif paddle.in_dynamic_mode(): + outs = _legacy_C_ops.where_index(x) + else: + helper = LayerHelper("where_index", **locals()) + + outs = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.INT64) + + helper.append_op(type='where_index', + inputs={'Condition': x}, + outputs={'Out': [outs]}) + + if not as_tuple: + return outs + elif rank == 1: + return tuple([outs]) + else: + for i in range(rank): + list_out.append( + paddle.slice(outs, axes=[1], starts=[i], ends=[i + 1])) + return tuple(list_out) + + +def sort(x, axis=-1, descending=False, name=None): + """ + + Sorts the input along the given axis, and returns the sorted output tensor. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True. + + Args: + x(Tensor): An input N-D Tensor with type float32, float64, int16, + int32, int64, uint8. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is Rank(x). when axis<0, it works the same way + as axis+R. Default is -1. + descending(bool, optional) : Descending is a flag, if set to true, + algorithm will sort by descending order, else sort by + ascending order. Default is false. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: sorted tensor(with the same shape and data type as ``x``). + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[[5,8,9,5], + [0,0,1,7], + [6,9,2,4]], + [[5,2,4,2], + [4,7,7,9], + [1,7,0,6]]], + dtype='float32') + out1 = paddle.sort(x=x, axis=-1) + out2 = paddle.sort(x=x, axis=0) + out3 = paddle.sort(x=x, axis=1) + print(out1) + #[[[5. 5. 8. 9.] + # [0. 0. 1. 7.] + # [2. 4. 6. 9.]] + # [[2. 2. 4. 5.] + # [4. 7. 7. 9.] + # [0. 1. 6. 7.]]] + print(out2) + #[[[5. 2. 4. 2.] + # [0. 0. 1. 7.] + # [1. 7. 0. 4.]] + # [[5. 8. 9. 5.] + # [4. 7. 7. 9.] + # [6. 9. 2. 6.]]] + print(out3) + #[[[0. 0. 1. 4.] + # [5. 8. 2. 5.] + # [6. 9. 9. 7.]] + # [[1. 2. 0. 2.] + # [4. 7. 4. 6.] + # [5. 7. 7. 9.]]] + """ + if in_dygraph_mode(): + outs, _ = _C_ops.argsort(x, axis, descending) + return outs + + if _in_legacy_dygraph(): + outs, _ = _legacy_C_ops.argsort(x, 'axis', axis, 'descending', + descending) + return outs + helper = LayerHelper("sort", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype, + stop_gradient=False) + ids = helper.create_variable_for_type_inference(VarDesc.VarType.INT64, + stop_gradient=True) + helper.append_op(type='argsort', + inputs={'X': x}, + outputs={ + 'Out': out, + 'Indices': ids + }, + attrs={ + 'axis': axis, + 'descending': descending + }) + return out + + +def mode(x, axis=-1, keepdim=False, name=None): + """ + Used to find values and indices of the modes at the optional axis. + + Args: + x(Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is x.ndim. when axis < 0, it works the same way + as axis + R. Default is -1. + keepdim(bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64. + + Examples: + + .. code-block:: python + + import paddle + + tensor = paddle.to_tensor([[[1,2,2],[2,3,3]],[[0,5,5],[9,9,0]]], dtype=paddle.float32) + res = paddle.mode(tensor, 2) + print(res) + # (Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[2., 3.], + # [5., 9.]]), Tensor(shape=[2, 2], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [[1, 1], + # [1, 0]])) + + """ + if in_dygraph_mode(): + return _C_ops.mode(x, axis, keepdim) + if _in_legacy_dygraph(): + return _legacy_C_ops.mode(x, "axis", axis, "keepdim", keepdim) + + helper = LayerHelper("mode", **locals()) + inputs = {"X": [x]} + attrs = {} + attrs['axis'] = axis + attrs['keepdim'] = keepdim + + values = helper.create_variable_for_type_inference(dtype=x.dtype) + indices = helper.create_variable_for_type_inference(dtype="int64") + + helper.append_op(type="mode", + inputs=inputs, + outputs={ + "Out": [values], + "Indices": [indices] + }, + attrs=attrs) + indices.stop_gradient = True + return values, indices + + +def where(condition, x=None, y=None, name=None): + r""" + Return a Tensor of elements selected from either :attr:`x` or :attr:`y` according to corresponding elements of :attr:`condition`. Concretely, + + .. math:: + + out_i = + \begin{cases} + x_i, & \text{if} \ condition_i \ \text{is} \ True \\ + y_i, & \text{if} \ condition_i \ \text{is} \ False \\ + \end{cases}. + + Notes: + ``numpy.where(condition)`` is identical to ``paddle.nonzero(condition, as_tuple=True)``, please refer to :ref:`api_tensor_search_nonzero`. + + Args: + condition (Tensor): The condition to choose x or y. When True (nonzero), yield x, otherwise yield y. + x (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is True with data type of float32, float64, int32 or int64. Either both or neither of x and y should be given. + y (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is False with data type of float32, float64, int32 or int64. Either both or neither of x and y should be given. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor: A Tensor with the same shape as :attr:`condition` and same data type as :attr:`x` and :attr:`y`. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([0.9383, 0.1983, 3.2, 1.2]) + y = paddle.to_tensor([1.0, 1.0, 1.0, 1.0]) + + out = paddle.where(x>1, x, y) + print(out) + #out: [1.0, 1.0, 3.2, 1.2] + + out = paddle.where(x>1) + print(out) + #out: (Tensor(shape=[2, 1], dtype=int64, place=CPUPlace, stop_gradient=True, + # [[2], + # [3]]),) + """ + if np.isscalar(x): + x = paddle.full([1], x, np.array([x]).dtype.name) + + if np.isscalar(y): + y = paddle.full([1], y, np.array([y]).dtype.name) + + if x is None and y is None: + return nonzero(condition, as_tuple=True) + + if x is None or y is None: + raise ValueError("either both or neither of x and y should be given") + + if not paddle.in_dynamic_mode(): + check_variable_and_dtype(condition, 'condition', ['bool'], 'where') + check_variable_and_dtype(x, 'x', + ['float32', 'float64', 'int32', 'int64'], + 'where') + check_variable_and_dtype(y, 'y', + ['float32', 'float64', 'int32', 'int64'], + 'where') + + condition_shape = list(condition.shape) + x_shape = list(x.shape) + y_shape = list(y.shape) + + if x_shape == y_shape and condition_shape == x_shape: + broadcast_condition = condition + broadcast_x = x + broadcast_y = y + else: + zeros_like_x = paddle.zeros_like(x) + zeros_like_y = paddle.zeros_like(y) + zeros_like_condition = paddle.zeros_like(condition) + zeros_like_condition = paddle.cast(zeros_like_condition, x.dtype) + cast_cond = paddle.cast(condition, x.dtype) + + broadcast_zeros = paddle.add(zeros_like_x, zeros_like_y) + broadcast_zeros = paddle.add(broadcast_zeros, zeros_like_condition) + broadcast_x = paddle.add(x, broadcast_zeros) + broadcast_y = paddle.add(y, broadcast_zeros) + broadcast_condition = paddle.add(cast_cond, broadcast_zeros) + broadcast_condition = paddle.cast(broadcast_condition, 'bool') + + if in_dygraph_mode(): + return _C_ops.where(broadcast_condition, broadcast_x, broadcast_y) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.where(broadcast_condition, broadcast_x, + broadcast_y) + else: + helper = LayerHelper("where", **locals()) + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type='where', + inputs={ + 'Condition': broadcast_condition, + 'X': broadcast_x, + 'Y': broadcast_y + }, + outputs={'Out': [out]}) + + return out + + +def index_sample(x, index): + """ + **IndexSample Layer** + + IndexSample OP returns the element of the specified location of X, + and the location is specified by Index. + + .. code-block:: text + + + Given: + + X = [[1, 2, 3, 4, 5], + [6, 7, 8, 9, 10]] + + Index = [[0, 1, 3], + [0, 2, 4]] + + Then: + + Out = [[1, 2, 4], + [6, 8, 10]] + + Args: + x (Tensor): The source input tensor with 2-D shape. Supported data type is + int32, int64, float32, float64. + index (Tensor): The index input tensor with 2-D shape, first dimension should be same with X. + Data type is int32 or int64. + + Returns: + output (Tensor): The output is a tensor with the same shape as index. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0]], dtype='float32') + index = paddle.to_tensor([[0, 1, 2], + [1, 2, 3], + [0, 0, 0]], dtype='int32') + target = paddle.to_tensor([[100, 200, 300, 400], + [500, 600, 700, 800], + [900, 1000, 1100, 1200]], dtype='int32') + out_z1 = paddle.index_sample(x, index) + print(out_z1) + #[[1. 2. 3.] + # [6. 7. 8.] + # [9. 9. 9.]] + + # Use the index of the maximum value by topk op + # get the value of the element of the corresponding index in other tensors + top_value, top_index = paddle.topk(x, k=2) + out_z2 = paddle.index_sample(target, top_index) + print(top_value) + #[[ 4. 3.] + # [ 8. 7.] + # [12. 11.]] + + print(top_index) + #[[3 2] + # [3 2] + # [3 2]] + + print(out_z2) + #[[ 400 300] + # [ 800 700] + # [1200 1100]] + + """ + if in_dygraph_mode(): + return _C_ops.index_sample(x, index) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.index_sample(x, index) + else: + helper = LayerHelper("index_sample", **locals()) + check_variable_and_dtype(x, 'x', + ['float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.search.index_sample') + check_variable_and_dtype(index, 'index', ['int32', 'int64'], + 'paddle.tensor.search.index_sample') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + + helper.append_op(type='index_sample', + inputs={ + 'X': x, + 'Index': index + }, + outputs={'Out': out}) + return out + + +def masked_select(x, mask, name=None): + """ + Returns a new 1-D tensor which indexes the input tensor according to the ``mask`` + which is a tensor with data type of bool. + + Args: + x (Tensor): The input Tensor, the data type can be int32, int64, float32, float64. + mask (Tensor): The Tensor containing the binary mask to index with, it's data type is bool. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + A 1-D Tensor which is the same data type as ``x``. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0]]) + mask = paddle.to_tensor([[True, False, False, False], + [True, True, False, False], + [True, False, False, False]]) + out = paddle.masked_select(x, mask) + #[1.0 5.0 6.0 9.0] + """ + + if in_dygraph_mode(): + return _C_ops.masked_select(x, mask) + + if _in_legacy_dygraph(): + return _legacy_C_ops.masked_select(x, mask) + + helper = LayerHelper("masked_select", **locals()) + check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'], + 'paddle.tensor.search.mask_select') + check_variable_and_dtype(mask, 'mask', ['bool'], + 'paddle.tensor.search.masked_select') + out = helper.create_variable_for_type_inference(dtype=x.dtype) + helper.append_op(type='masked_select', + inputs={ + 'X': x, + 'Mask': mask + }, + outputs={'Y': out}) + return out + + +def topk(x, k, axis=None, largest=True, sorted=True, name=None): + """ + Return values and indices of the k largest or smallest at the optional axis. + If the input is a 1-D Tensor, finds the k largest or smallest values and indices. + If the input is a Tensor with higher rank, this operator computes the top k values and indices along the :attr:`axis`. + + Args: + x(Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64. + k(int, Tensor): The number of top elements to look for along the axis. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is x.ndim. when axis < 0, it works the same way + as axis + R. Default is -1. + largest(bool, optional) : largest is a flag, if set to true, + algorithm will sort by descending order, otherwise sort by + ascending order. Default is True. + sorted(bool, optional): controls whether to return the elements in sorted order, default value is True. In gpu device, it always return the sorted value. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64. + + Examples: + + .. code-block:: python + + import paddle + + data_1 = paddle.to_tensor([1, 4, 5, 7]) + value_1, indices_1 = paddle.topk(data_1, k=1) + print(value_1) # [7] + print(indices_1) # [3] + + data_2 = paddle.to_tensor([[1, 4, 5, 7], [2, 6, 2, 5]]) + value_2, indices_2 = paddle.topk(data_2, k=1) + print(value_2) # [[7], [6]] + print(indices_2) # [[3], [1]] + + value_3, indices_3 = paddle.topk(data_2, k=1, axis=-1) + print(value_3) # [[7], [6]] + print(indices_3) # [[3], [1]] + + value_4, indices_4 = paddle.topk(data_2, k=1, axis=0) + print(value_4) # [[2, 6, 5, 7]] + print(indices_4) # [[1, 1, 0, 0]] + + + """ + + if in_dygraph_mode(): + if axis == None: + axis = -1 + out, indices = _C_ops.top_k(x, k, axis, largest, sorted) + return out, indices + + if _non_static_mode(): + if axis is None: + out, indices = _legacy_C_ops.top_k_v2(x, 'k', int(k), 'largest', + largest, 'sorted', sorted) + else: + out, indices = _legacy_C_ops.top_k_v2(x, 'k', int(k), 'axis', axis, + 'largest', largest, 'sorted', + sorted) + return out, indices + + helper = LayerHelper("top_k_v2", **locals()) + inputs = {"X": [x]} + attrs = {} + if isinstance(k, Variable): + inputs['K'] = [k] + else: + attrs = {'k': k} + attrs['largest'] = largest + attrs['sorted'] = sorted + if axis is not None: + attrs['axis'] = axis + + values = helper.create_variable_for_type_inference(dtype=x.dtype) + indices = helper.create_variable_for_type_inference(dtype="int64") + + helper.append_op(type="top_k_v2", + inputs=inputs, + outputs={ + "Out": [values], + "Indices": [indices] + }, + attrs=attrs) + indices.stop_gradient = True + return values, indices + + +def bucketize(x, sorted_sequence, out_int32=False, right=False, name=None): + """ + This API is used to find the index of the corresponding 1D tensor `sorted_sequence` in the innermost dimension based on the given `x`. + + Args: + x(Tensor): An input N-D tensor value with type int32, int64, float32, float64. + sorted_sequence(Tensor): An input 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension. + out_int32(bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64. + right(bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `x`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension. + The default value is False and it shows the lower bounds. + name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor(the same sizes of the `x`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64. + + Examples: + + .. code-block:: python + + import paddle + + sorted_sequence = paddle.to_tensor([2, 4, 8, 16], dtype='int32') + x = paddle.to_tensor([[0, 8, 4, 16], [-1, 2, 8, 4]], dtype='int32') + out1 = paddle.bucketize(x, sorted_sequence) + print(out1) + # Tensor(shape=[2, 4], dtype=int64, place=CPUPlace, stop_gradient=True, + # [[0, 2, 1, 3], + # [0, 0, 2, 1]]) + out2 = paddle.bucketize(x, sorted_sequence, right=True) + print(out2) + # Tensor(shape=[2, 4], dtype=int64, place=CPUPlace, stop_gradient=True, + # [[0, 3, 2, 4], + # [0, 1, 3, 2]]) + out3 = x.bucketize(sorted_sequence) + print(out3) + # Tensor(shape=[2, 4], dtype=int64, place=CPUPlace, stop_gradient=True, + # [[0, 2, 1, 3], + # [0, 0, 2, 1]]) + out4 = x.bucketize(sorted_sequence, right=True) + print(out4) + # Tensor(shape=[2, 4], dtype=int64, place=CPUPlace, stop_gradient=True, + # [[0, 3, 2, 4], + # [0, 1, 3, 2]]) + + """ + check_variable_and_dtype(sorted_sequence, 'SortedSequence', + ['float32', 'float64', 'int32', 'int64'], + 'paddle.searchsorted') + if sorted_sequence.dim() != 1: + raise ValueError( + f"sorted_sequence tensor must be 1 dimension, but got dim {sorted_sequence.dim()}" + ) + return searchsorted(sorted_sequence, x, out_int32, right, name) + + +def searchsorted(sorted_sequence, + values, + out_int32=False, + right=False, + name=None): + """ + Find the index of the corresponding `sorted_sequence` in the innermost dimension based on the given `values`. + + Args: + sorted_sequence(Tensor): An input N-D or 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension. + values(Tensor): An input N-D tensor value with type int32, int64, float32, float64. + out_int32(bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64. + right(bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `values`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension. + The default value is False and it shows the lower bounds. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + Tensor(the same sizes of the `values`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64. + + Examples: + + .. code-block:: python + + import paddle + + sorted_sequence = paddle.to_tensor([[1, 3, 5, 7, 9, 11], + [2, 4, 6, 8, 10, 12]], dtype='int32') + values = paddle.to_tensor([[3, 6, 9, 10], [3, 6, 9, 10]], dtype='int32') + out1 = paddle.searchsorted(sorted_sequence, values) + print(out1) + # Tensor(shape=[2, 4], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [[1, 3, 4, 5], + # [1, 2, 4, 4]]) + out2 = paddle.searchsorted(sorted_sequence, values, right=True) + print(out2) + # Tensor(shape=[2, 4], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [[2, 3, 5, 5], + # [1, 3, 4, 5]]) + sorted_sequence_1d = paddle.to_tensor([1, 3, 5, 7, 9, 11, 13]) + out3 = paddle.searchsorted(sorted_sequence_1d, values) + print(out3) + # Tensor(shape=[2, 4], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [[1, 3, 4, 5], + # [1, 3, 4, 5]]) + + """ + if in_dygraph_mode(): + return _C_ops.searchsorted(sorted_sequence, values, out_int32, right) + + if _in_legacy_dygraph(): + return _legacy_C_ops.searchsorted(sorted_sequence, values, "out_int32", + out_int32, "right", right) + + check_variable_and_dtype(sorted_sequence, 'SortedSequence', + ['float32', 'float64', 'int32', 'int64'], + 'paddle.searchsorted') + check_variable_and_dtype(values, 'Values', + ['float32', 'float64', 'int32', 'int64'], + 'paddle.searchsorted') + + helper = LayerHelper('searchsorted', **locals()) + out_type = 'int32' if out_int32 else 'int64' + out = helper.create_variable_for_type_inference(dtype=out_type) + helper.append_op(type='searchsorted', + inputs={ + 'SortedSequence': sorted_sequence, + "Values": values + }, + outputs={'Out': out}, + attrs={ + "out_int32": out_int32, + "right": right + }) + + return out + + +def kthvalue(x, k, axis=None, keepdim=False, name=None): + """ + Find values and indices of the k-th smallest at the axis. + + Args: + x(Tensor): A N-D Tensor with type float32, float64, int32, int64. + k(int): The k for the k-th smallest number to look for along the axis. + axis(int, optional): Axis to compute indices along. The effective range + is [-R, R), where R is x.ndim. when axis < 0, it works the same way + as axis + R. The default is None. And if the axis is None, it will computed as -1 by default. + keepdim(bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimentions is one fewer than x since the axis is squeezed. Default is False. + name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None. + + Returns: + tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.randn((2,3,2)) + # Tensor(shape=[2, 3, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[[ 0.22954939, -0.01296274], + # [ 1.17135799, -0.34493217], + # [-0.19550551, -0.17573971]], + # + # [[ 0.15104349, -0.93965352], + # [ 0.14745511, 0.98209465], + # [ 0.10732264, -0.55859774]]]) + y = paddle.kthvalue(x, 2, 1) + # (Tensor(shape=[2, 2], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[ 0.22954939, -0.17573971], + # [ 0.14745511, -0.55859774]]), Tensor(shape=[2, 2], dtype=int64, place=CUDAPlace(0), stop_gradient=True, + # [[0, 2], + # [1, 2]])) + """ + if _non_static_mode(): + if axis is not None: + if _in_legacy_dygraph(): + return _legacy_C_ops.kthvalue(x, 'k', k, "axis", axis, + "keepdim", keepdim) + return _C_ops.kthvalue(x, k, axis, keepdim) + else: + if _in_legacy_dygraph(): + return _legacy_C_ops.kthvalue(x, 'k', k, "keepdim", keepdim) + return _C_ops.kthvalue(x, k, -1, keepdim) + + helper = LayerHelper("kthvalue", **locals()) + inputs = {"X": [x]} + attrs = {'k': k} + if axis is not None: + attrs['axis'] = axis + values = helper.create_variable_for_type_inference(dtype=x.dtype) + indices = helper.create_variable_for_type_inference(dtype="int64") + + helper.append_op(type="kthvalue", + inputs=inputs, + outputs={ + "Out": [values], + "Indices": [indices] + }, + attrs=attrs) + indices.stop_gradient = True + return values, indices diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/stat.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4fd2c2a4b4689ac0c2d5ed289bca605f3797ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/stat.py @@ -0,0 +1,727 @@ +# 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. + +# TODO: define statistical functions of a tensor + +import numpy as np +from ..static import Variable +from ..framework import LayerHelper +from ..framework import core +from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode +from .search import where +from ..fluid.data_feeder import ( + convert_dtype, + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..fluid.layers import utils +import paddle +from paddle import _C_ops, _legacy_C_ops + +__all__ = [] + + +def mean(x, axis=None, keepdim=False, name=None): + """ + Computes the mean of the input tensor's elements along ``axis``. + + Args: + x (Tensor): The input Tensor with data type float32, float64. + axis (int|list|tuple, optional): The axis along which to perform mean + calculations. ``axis`` should be int, list(int) or tuple(int). If + ``axis`` is a list/tuple of dimension(s), mean is calculated along + all element(s) of ``axis`` . ``axis`` or element(s) of ``axis`` + should be in range [-D, D), where D is the dimensions of ``x`` . If + ``axis`` or element(s) of ``axis`` is less than 0, it works the + same way as :math:`axis + D` . If ``axis`` is None, mean is + calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of average along ``axis`` of ``x``, with the same data + type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[[1., 2., 3., 4.], + [5., 6., 7., 8.], + [9., 10., 11., 12.]], + [[13., 14., 15., 16.], + [17., 18., 19., 20.], + [21., 22., 23., 24.]]]) + out1 = paddle.mean(x) + # [12.5] + out2 = paddle.mean(x, axis=-1) + # [[ 2.5 6.5 10.5] + # [14.5 18.5 22.5]] + out3 = paddle.mean(x, axis=-1, keepdim=True) + # [[[ 2.5] + # [ 6.5] + # [10.5]] + # [[14.5] + # [18.5] + # [22.5]]] + out4 = paddle.mean(x, axis=[0, 2]) + # [ 8.5 12.5 16.5] + """ + + if isinstance(axis, Variable): + reduce_all = True if axis.shape[0] == len(x.shape) else False + else: + if isinstance(axis, int): + axis = [axis] + reduce_all = ( + True + if axis is None or len(axis) == 0 or len(axis) == len(x.shape) + else False + ) + if axis is None or len(axis) == 0: + axis = [0] + + if in_dygraph_mode(): + if reduce_all: + axis = list(range(len(x.shape))) + return _C_ops.mean(x, axis, keepdim) + if _in_legacy_dygraph(): + return _legacy_C_ops.reduce_mean( + x, 'dim', axis, 'keep_dim', keepdim, 'reduce_all', reduce_all + ) + + check_variable_and_dtype( + x, + 'x/input', + ['uint16', 'float16', 'float32', 'float64'], + 'mean/reduce_mean', + ) + check_type( + axis, 'axis/dim', (int, list, tuple, Variable), 'mean/reduce_mean' + ) + if isinstance(axis, (list, tuple)): + for item in axis: + check_type( + item, + 'elements of axis/dim', + (int, Variable), + 'mean/reduce_mean', + ) + + helper = LayerHelper('mean', **locals()) + + if not isinstance(axis, Variable) and utils._contain_var(axis): + axis = utils._convert_to_tensor_list(axis) + attrs = {'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all} + out = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='reduce_mean', inputs={'X': x}, outputs={'Out': out}, attrs=attrs + ) + return out + + +def var(x, axis=None, unbiased=True, keepdim=False, name=None): + """ + Computes the variance of ``x`` along ``axis`` . + + Args: + x (Tensor): The input Tensor with data type float32, float64. + axis (int|list|tuple, optional): The axis along which to perform variance calculations. ``axis`` should be int, list(int) or tuple(int). + + - If ``axis`` is a list/tuple of dimension(s), variance is calculated along all element(s) of ``axis`` . ``axis`` or element(s) of ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + - If ``axis`` or element(s) of ``axis`` is less than 0, it works the same way as :math:`axis + D` . + - If ``axis`` is None, variance is calculated over all elements of ``x``. Default is None. + + unbiased (bool, optional): Whether to use the unbiased estimation. If ``unbiased`` is True, the divisor used in the computation is :math:`N - 1`, where :math:`N` represents the number of elements along ``axis`` , otherwise the divisor is :math:`N`. Default is True. + keep_dim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result tensor will have one fewer dimension than the input unless keep_dim is true. Default is False. + name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of variance along ``axis`` of ``x``, with the same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0], [1.0, 4.0, 5.0]]) + out1 = paddle.var(x) + # [2.66666667] + out2 = paddle.var(x, axis=1) + # [1. 4.33333333] + """ + if not paddle.in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'var') + + u = mean(x, axis, True, name) + out = paddle.sum((x - u) ** 2, axis, keepdim=keepdim, name=name) + + dtype = x.dtype + n = paddle.cast(paddle.numel(x), paddle.int64) / paddle.cast( + paddle.numel(out), paddle.int64 + ) + n = n.astype(dtype) + if unbiased: + one_const = paddle.ones([1], x.dtype) + n = where(n > one_const, n - 1.0, one_const) + out /= n + return out + + +def std(x, axis=None, unbiased=True, keepdim=False, name=None): + """ + Computes the standard-deviation of ``x`` along ``axis`` . + + Args: + x (Tensor): The input Tensor with data type float32, float64. + axis (int|list|tuple, optional): The axis along which to perform + standard-deviation calculations. ``axis`` should be int, list(int) + or tuple(int). If ``axis`` is a list/tuple of dimension(s), + standard-deviation is calculated along all element(s) of ``axis`` . + ``axis`` or element(s) of ``axis`` should be in range [-D, D), + where D is the dimensions of ``x`` . If ``axis`` or element(s) of + ``axis`` is less than 0, it works the same way as :math:`axis + D` . + If ``axis`` is None, standard-deviation is calculated over all + elements of ``x``. Default is None. + unbiased (bool, optional): Whether to use the unbiased estimation. If + ``unbiased`` is True, the standard-deviation is calculated via the + unbiased estimator. If ``unbiased`` is True, the divisor used in + the computation is :math:`N - 1`, where :math:`N` represents the + number of elements along ``axis`` , otherwise the divisor is + :math:`N`. Default is True. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of standard-deviation along ``axis`` of ``x``, with the + same data type as ``x``. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor([[1.0, 2.0, 3.0], [1.0, 4.0, 5.0]]) + out1 = paddle.std(x) + # [1.63299316] + out2 = paddle.std(x, axis=1) + # [1. 2.081666] + """ + if not paddle.in_dynamic_mode(): + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'std') + + out = var(**locals()) + return paddle.sqrt(out) + + +def numel(x, name=None): + """ + Returns the number of elements for a tensor, which is a int64 Tensor with shape [1] in static mode + or a scalar value in imperative mode. + + Args: + x (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor: The number of elements for the input Tensor. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.full(shape=[4, 5, 7], fill_value=0, dtype='int32') + numel = paddle.numel(x) # 140 + + + """ + if in_dygraph_mode(): + return _C_ops.size(x) + elif _in_legacy_dygraph(): + return _legacy_C_ops.size(x) + + if not isinstance(x, Variable): + raise TypeError("x must be a Tensor in numel") + helper = LayerHelper('numel', **locals()) + out = helper.create_variable_for_type_inference( + dtype=core.VarDesc.VarType.INT64 + ) + helper.append_op(type='size', inputs={'Input': x}, outputs={'Out': out}) + return out + + +def nanmedian(x, axis=None, keepdim=True, name=None): + r""" + Compute the median along the specified axis, while ignoring NaNs. + + If the valid count of elements is a even number, + the average value of both elements in the middle is calculated as the median. + + Args: + x (Tensor): The input Tensor, it's data type can be int32, int64, float16, float32, float64. + axis (None|int|list|tuple, optional): + The axis along which to perform median calculations ``axis`` should be int or list of int. + ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` is less than 0, it works the same way as :math:`axis + D`. + If ``axis`` is None, median is calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is True. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of median along ``axis`` of ``x``. The output dtype is the same as `x`. + + Examples: + .. code-block:: python + + import paddle + x = paddle.to_tensor([[float('nan'), 2. , 3. ], [0. , 1. , 2. ]]) + + y1 = x.nanmedian() + # y1 is [[2.]] + + y2 = x.nanmedian(0) + # y2 is [[0., 1.5, 2.5]] + + y3 = x.nanmedian(0, keepdim=False) + # y3 is [0., 1.5, 2.5] + + y4 = x.nanmedian((0, 1)) + # y4 is [[2.]] + """ + if not isinstance(x, Variable): + raise TypeError("In median, the input x should be a Tensor.") + + if isinstance(axis, (list, tuple)) and len(axis) == 0: + raise ValueError("Axis list should not be empty.") + + dims = len(x.shape) + if axis is None: + axis = [] + elif isinstance(axis, tuple): + axis = list(axis) + elif isinstance(axis, int): + axis = [axis] + + if not isinstance(axis, list): + raise ValueError( + "Axis should be None, int, or a list, element should in range [-rank(x), rank(x))." + ) + + for i in range(len(axis)): + if not isinstance(axis[i], int) or not ( + axis[i] < dims and axis[i] >= -dims + ): + raise ValueError( + "Axis should be None, int, or a list, element should in range [-rank(x), rank(x))." + ) + if axis[i] < 0: + axis[i] += dims + + if len(axis) != len(set(axis)): + raise ValueError("Axis has duplicated elements.") + + if _in_legacy_dygraph(): + median_index, out = _legacy_C_ops.nanmedian( + x, 'axis', axis, 'keepdim', keepdim + ) + return out + + check_variable_and_dtype( + x, 'X', ['int32', 'int64', 'float16', 'float32', 'float64'], 'nanmedian' + ) + + helper = LayerHelper('nanmedian', **locals()) + attrs = {'axis': axis, 'keepdim': keepdim} + out = helper.create_variable_for_type_inference(x.dtype) + medians = helper.create_variable_for_type_inference(x.dtype) + helper.append_op( + type='nanmedian', + inputs={'X': x}, + outputs={'Out': out, 'MedianIndex': medians}, + attrs=attrs, + ) + return out + + +def median(x, axis=None, keepdim=False, name=None): + """ + Compute the median along the specified axis. + + Args: + x (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64. + axis (int, optional): The axis along which to perform median calculations ``axis`` should be int. + ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` is less than 0, it works the same way as :math:`axis + D`. + If ``axis`` is None, median is calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of median along ``axis`` of ``x``. If data type of ``x`` is float64, data type of results will be float64, otherwise data type will be float32. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.arange(12).reshape([3, 4]) + # Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True, + # [[0 , 1 , 2 , 3 ], + # [4 , 5 , 6 , 7 ], + # [8 , 9 , 10, 11]]) + + y1 = paddle.median(x) + # Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True, + # [5.50000000]) + + y2 = paddle.median(x, axis=0) + # Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [4., 5., 6., 7.]) + + y3 = paddle.median(x, axis=1) + # Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True, + # [1.50000000, 5.50000000, 9.50000000]) + + y4 = paddle.median(x, axis=0, keepdim=True) + # Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[4., 5., 6., 7.]]) + + """ + if not isinstance(x, Variable): + raise TypeError("In median, the input x should be a Tensor.") + is_flatten = axis is None + dims = len(x.shape) + if is_flatten: + x = paddle.flatten(x) + axis = 0 + else: + if not isinstance(axis, int) or not (axis < dims and axis >= -dims): + raise ValueError( + "In median, axis should be none or an integer in range [-rank(x), rank(x))." + ) + if axis < 0: + axis += dims + sz = x.shape[axis] + kth = sz >> 1 + tensor_topk, idx = paddle.topk(x, kth + 1, axis=axis, largest=False) + dtype = 'float64' if x.dtype == core.VarDesc.VarType.FP64 else 'float32' + if sz & 1 == 0: + out_tensor = paddle.slice( + tensor_topk, axes=[axis], starts=[kth - 1], ends=[kth] + ) + paddle.slice(tensor_topk, axes=[axis], starts=[kth], ends=[kth + 1]) + out_tensor = paddle.cast(out_tensor, dtype=dtype) / 2 + else: + out_tensor = paddle.cast( + paddle.slice( + tensor_topk, axes=[axis], starts=[kth], ends=[kth + 1] + ), + dtype=dtype, + ) + out_tensor = out_tensor + paddle.sum( + paddle.cast(paddle.isnan(x), dtype=dtype) * x, axis=axis, keepdim=True + ) + if not keepdim or is_flatten: + if not is_flatten: + newshape = x.shape[:axis] + x.shape[axis + 1 :] + elif not keepdim: + newshape = [1] + else: + newshape = [1] * dims + else: + newshape = out_tensor.shape + out_tensor = out_tensor.reshape(newshape, name=name) + return out_tensor + + +def _compute_quantile(x, q, axis=None, keepdim=False, ignore_nan=False): + """ + Compute the quantile of the input along the specified axis. + + Args: + x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64. + q (int|float|list): The q for calculate quantile, which should be in range [0, 1]. If q is a list, + each q will be calculated and the first dimension of output is same to the number of ``q`` . + axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int. + ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` is less than 0, it works the same way as :math:`axis + D`. + If ``axis`` is a list, quantile is calculated over all elements of given axises. + If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + ignore_nan: (bool, optional): Whether to ignore NaN of input Tensor. + If ``ignore_nan`` is True, it will calculate nanquantile. + Otherwise it will calculate quantile. Default is False. + + Returns: + Tensor, results of quantile along ``axis`` of ``x``. + In order to obtain higher precision, data type of results will be float64. + """ + # Validate x + if not isinstance(x, Variable): + raise TypeError("input x should be a Tensor.") + + # Validate q + if isinstance(q, (int, float)): + q = [q] + elif isinstance(q, (list, tuple)): + if len(q) <= 0: + raise ValueError("q should not be empty") + else: + raise TypeError("Type of q should be int, float, list or tuple.") + + # Validate axis + dims = len(x.shape) + out_shape = list(x.shape) + if axis is None: + x = paddle.flatten(x) + axis = 0 + out_shape = [1] * dims + else: + if isinstance(axis, list): + if len(axis) <= 0: + raise ValueError("axis should not be empty") + axis_src, axis_dst = [], [] + for axis_single in axis: + if not isinstance(axis_single, int) or not ( + axis_single < dims and axis_single >= -dims + ): + raise ValueError( + "Axis should be None, int, or a list, element should in range [-rank(x), rank(x))." + ) + if axis_single < 0: + axis_single = axis_single + dims + axis_src.append(axis_single) + out_shape[axis_single] = 1 + axis_dst = list(range(-len(axis), 0)) + x = paddle.moveaxis(x, axis_src, axis_dst) + x = paddle.flatten(x, axis_dst[0], axis_dst[-1]) + axis = axis_dst[0] + else: + if not isinstance(axis, int) or not (axis < dims and axis >= -dims): + raise ValueError( + "Axis should be None, int, or a list, element should in range [-rank(x), rank(x))." + ) + if axis < 0: + axis += dims + out_shape[axis] = 1 + + mask = x.isnan() + valid_counts = mask.logical_not().sum( + axis=axis, keepdim=True, dtype='float64' + ) + + indices = [] + + for q_num in q: + if q_num < 0 or q_num > 1: + raise ValueError("q should be in range [0, 1]") + if paddle.in_dynamic_mode(): + q_num = paddle.to_tensor(q_num, dtype='float64') + if ignore_nan: + indices.append(q_num * (valid_counts - 1)) + else: + # TODO: Use paddle.index_fill instead of where + index = q_num * (valid_counts - 1) + last_index = x.shape[axis] - 1 + nums = paddle.full_like(index, fill_value=last_index) + index = paddle.where(mask.any(axis=axis, keepdim=True), nums, index) + indices.append(index) + + sorted_tensor = paddle.sort(x, axis) + + outputs = [] + + # TODO(chenjianye): replace the for-loop to directly take elements. + for index in indices: + indices_below = paddle.floor(index).astype(paddle.int32) + indices_upper = paddle.ceil(index).astype(paddle.int32) + tensor_upper = paddle.take_along_axis( + sorted_tensor, indices_upper, axis=axis + ) + tensor_below = paddle.take_along_axis( + sorted_tensor, indices_below, axis=axis + ) + weights = index - indices_below.astype('float64') + out = paddle.lerp( + tensor_below.astype('float64'), + tensor_upper.astype('float64'), + weights, + ) + if not keepdim: + out = paddle.squeeze(out, axis=axis) + else: + out = out.reshape(out_shape) + outputs.append(out) + + if len(q) > 1: + outputs = paddle.stack(outputs, 0) + else: + outputs = outputs[0] + + return outputs + + +def quantile(x, q, axis=None, keepdim=False): + """ + Compute the quantile of the input along the specified axis. + If any values in a reduced row are NaN, then the quantiles for that reduction will be NaN. + + Args: + x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64. + q (int|float|list): The q for calculate quantile, which should be in range [0, 1]. If q is a list, + each q will be calculated and the first dimension of output is same to the number of ``q`` . + axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int. + ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` is less than 0, it works the same way as :math:`axis + D`. + If ``axis`` is a list, quantile is calculated over all elements of given axises. + If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of quantile along ``axis`` of ``x``. + In order to obtain higher precision, data type of results will be float64. + + Examples: + .. code-block:: python + + import paddle + + y = paddle.arange(0, 8 ,dtype="float32").reshape([4, 2]) + # Tensor(shape=[4, 2], dtype=float32, place=Place(cpu), stop_gradient=True, + # [[0., 1.], + # [2., 3.], + # [4., 5.], + # [6., 7.]]) + + y1 = paddle.quantile(y, q=0.5, axis=[0, 1]) + # Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=True, + # 3.50000000) + + y2 = paddle.quantile(y, q=0.5, axis=1) + # Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=True, + # [0.50000000, 2.50000000, 4.50000000, 6.50000000]) + + y3 = paddle.quantile(y, q=[0.3, 0.5], axis=0) + # Tensor(shape=[2, 2], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[1.80000000, 2.80000000], + # [3. , 4. ]]) + + y[0,0] = float("nan") + y4 = paddle.quantile(y, q=0.8, axis=1, keepdim=True) + # Tensor(shape=[4, 1], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[nan ], + # [2.80000000], + # [4.80000000], + # [6.80000000]]) + + """ + return _compute_quantile(x, q, axis=axis, keepdim=keepdim, ignore_nan=False) + + +def nanquantile(x, q, axis=None, keepdim=False): + """ + Compute the quantile of the input as if NaN values in input did not exist. + If all values in a reduced row are NaN, then the quantiles for that reduction will be NaN. + + Args: + x (Tensor): The input Tensor, it's data type can be float32, float64, int32, int64. + q (int|float|list): The q for calculate quantile, which should be in range [0, 1]. If q is a list, + each q will be calculated and the first dimension of output is same to the number of ``q`` . + axis (int|list, optional): The axis along which to calculate quantile. ``axis`` should be int or list of int. + ``axis`` should be in range [-D, D), where D is the dimensions of ``x`` . + If ``axis`` is less than 0, it works the same way as :math:`axis + D`. + If ``axis`` is a list, quantile is calculated over all elements of given axises. + If ``axis`` is None, quantile is calculated over all elements of ``x``. Default is None. + keepdim (bool, optional): Whether to reserve the reduced dimension(s) + in the output Tensor. If ``keepdim`` is True, the dimensions of + the output Tensor is the same as ``x`` except in the reduced + dimensions(it is of size 1 in this case). Otherwise, the shape of + the output Tensor is squeezed in ``axis`` . Default is False. + name (str, optional): Name for the operation (optional, default is None). + For more information, please refer to :ref:`api_guide_Name`. + + Returns: + Tensor, results of quantile along ``axis`` of ``x``. + In order to obtain higher precision, data type of results will be float64. + + Examples: + .. code-block:: python + + import paddle + + x = paddle.to_tensor( + [[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]], + dtype="float32") + x[0,0] = float("nan") + + y1 = paddle.nanquantile(x, q=0.5, axis=[0, 1]) + # Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=True, + # 5.) + + y2 = paddle.nanquantile(x, q=0.5, axis=1) + # Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True, + # [2.50000000, 7. ]) + + y3 = paddle.nanquantile(x, q=[0.3, 0.5], axis=0) + # Tensor(shape=[2, 5], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[5. , 2.50000000, 3.50000000, 4.50000000, 5.50000000], + # [5. , 3.50000000, 4.50000000, 5.50000000, 6.50000000]]) + + y4 = paddle.nanquantile(x, q=0.8, axis=1, keepdim=True) + # Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[3.40000000], + # [8.20000000]]) + + nan = paddle.full(shape=[2, 3], fill_value=float("nan")) + y5 = paddle.nanquantile(nan, q=0.8, axis=1, keepdim=True) + # Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=True, + # [[nan], + # [nan]]) + + """ + return _compute_quantile(x, q, axis=axis, keepdim=keepdim, ignore_nan=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/tensor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1696351609083581565cf78b1890bce7c511a3eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/tensor.py @@ -0,0 +1,15 @@ +# 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. + +# TODO: define the basic tensor classes diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/to_string.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/to_string.py new file mode 100644 index 0000000000000000000000000000000000000000..fb21c793f428dc20d9949eedc2f735ed949646bd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/tensor/to_string.py @@ -0,0 +1,357 @@ +# 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. + +import paddle +import numpy as np +from ..framework import core +from paddle.fluid.data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype + +__all__ = [] + + +class PrintOptions(object): + precision = 8 + threshold = 1000 + edgeitems = 3 + linewidth = 80 + sci_mode = False + + +DEFAULT_PRINT_OPTIONS = PrintOptions() + + +def set_printoptions(precision=None, + threshold=None, + edgeitems=None, + sci_mode=None, + linewidth=None): + """Set the printing options for Tensor. + + Args: + precision (int, optional): Number of digits of the floating number, default 8. + threshold (int, optional): Total number of elements printed, default 1000. + edgeitems (int, optional): Number of elements in summary at the beginning and ending of each dimension, default 3. + sci_mode (bool, optional): Format the floating number with scientific notation or not, default False. + linewidth (int, optional): Number of characters each line, default 80. + + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + + paddle.seed(10) + a = paddle.rand([10, 20]) + paddle.set_printoptions(4, 100, 3) + print(a) + + ''' + Tensor(shape=[10, 20], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + [[0.0002, 0.8503, 0.0135, ..., 0.9508, 0.2621, 0.6661], + [0.9710, 0.2605, 0.9950, ..., 0.4427, 0.9241, 0.9363], + [0.0948, 0.3226, 0.9955, ..., 0.1198, 0.0889, 0.9231], + ..., + [0.7206, 0.0941, 0.5292, ..., 0.4856, 0.1379, 0.0351], + [0.1745, 0.5621, 0.3602, ..., 0.2998, 0.4011, 0.1764], + [0.0728, 0.7786, 0.0314, ..., 0.2583, 0.1654, 0.0637]]) + ''' + """ + kwargs = {} + + if precision is not None: + check_type(precision, 'precision', (int), 'set_printoptions') + DEFAULT_PRINT_OPTIONS.precision = precision + kwargs['precision'] = precision + if threshold is not None: + check_type(threshold, 'threshold', (int), 'set_printoptions') + DEFAULT_PRINT_OPTIONS.threshold = threshold + kwargs['threshold'] = threshold + if edgeitems is not None: + check_type(edgeitems, 'edgeitems', (int), 'set_printoptions') + DEFAULT_PRINT_OPTIONS.edgeitems = edgeitems + kwargs['edgeitems'] = edgeitems + if linewidth is not None: + check_type(linewidth, 'linewidth', (int), 'set_printoptions') + DEFAULT_PRINT_OPTIONS.linewidth = linewidth + kwargs['linewidth'] = linewidth + if sci_mode is not None: + check_type(sci_mode, 'sci_mode', (bool), 'set_printoptions') + DEFAULT_PRINT_OPTIONS.sci_mode = sci_mode + kwargs['sci_mode'] = sci_mode + core.set_printoptions(**kwargs) + + +def _to_summary(var): + edgeitems = DEFAULT_PRINT_OPTIONS.edgeitems + + # Handle tensor of shape contains 0, like [0, 2], [3, 0, 3] + if np.prod(var.shape) == 0: + return np.array([]) + + if len(var.shape) == 0: + return var + elif len(var.shape) == 1: + if var.shape[0] > 2 * edgeitems: + return np.concatenate([var[:edgeitems], var[(-1 * edgeitems):]]) + else: + return var + else: + # recursively handle all dimensions + if var.shape[0] > 2 * edgeitems: + begin = [x for x in var[:edgeitems]] + end = [x for x in var[(-1 * edgeitems):]] + return np.stack([_to_summary(x) for x in (begin + end)]) + else: + return np.stack([_to_summary(x) for x in var]) + + +def _format_item(np_var, max_width=0, signed=False): + if np_var.dtype == np.float32 or np_var.dtype == np.float64 or np_var.dtype == np.float16: + if DEFAULT_PRINT_OPTIONS.sci_mode: + item_str = '{{:.{}e}}'.format( + DEFAULT_PRINT_OPTIONS.precision).format(np_var) + elif np.ceil(np_var) == np_var: + item_str = '{:.0f}.'.format(np_var) + else: + item_str = '{{:.{}f}}'.format( + DEFAULT_PRINT_OPTIONS.precision).format(np_var) + else: + item_str = '{}'.format(np_var) + + if max_width > len(item_str): + if signed: # handle sign character for tenosr with negative item + if np_var < 0: + return item_str.ljust(max_width) + else: + return ' ' + item_str.ljust(max_width - 1) + else: + return item_str.ljust(max_width) + else: # used for _get_max_width + return item_str + + +def _get_max_width(var): + # return max_width for a scalar + max_width = 0 + signed = False + for item in list(var.flatten()): + if (not signed) and (item < 0): + signed = True + item_str = _format_item(item) + max_width = max(max_width, len(item_str)) + + return max_width, signed + + +def _format_tensor(var, summary, indent=0, max_width=0, signed=False): + """ + Format a tensor + + Args: + var(Tensor): The tensor to be formatted. + summary(bool): Do summary or not. If true, some elements will not be printed, and be replaced with "...". + indent(int): The indent of each line. + max_width(int): The max width of each elements in var. + signed(bool): Print +/- or not. + """ + edgeitems = DEFAULT_PRINT_OPTIONS.edgeitems + linewidth = DEFAULT_PRINT_OPTIONS.linewidth + + if len(var.shape) == 0: + # currently, shape = [], i.e., scaler tensor is not supported. + # If it is supported, it should be formatted like this. + return _format_item(var, max_width, signed) + elif len(var.shape) == 1: + item_length = max_width + 2 + items_per_line = (linewidth - indent) // item_length + items_per_line = max(1, items_per_line) + + if summary and var.shape[0] > 2 * edgeitems: + items = [ + _format_item(item, max_width, signed) + for item in list(var)[:edgeitems] + ] + ['...'] + [ + _format_item(item, max_width, signed) + for item in list(var)[(-1 * edgeitems):] + ] + else: + items = [ + _format_item(item, max_width, signed) for item in list(var) + ] + lines = [ + items[i:i + items_per_line] + for i in range(0, len(items), items_per_line) + ] + s = (',\n' + ' ' * (indent + 1)).join( + [', '.join(line) for line in lines]) + return '[' + s + ']' + else: + # recursively handle all dimensions + if summary and var.shape[0] > 2 * edgeitems: + vars = [ + _format_tensor(x, summary, indent + 1, max_width, signed) + for x in var[:edgeitems] + ] + ['...'] + [ + _format_tensor(x, summary, indent + 1, max_width, signed) + for x in var[(-1 * edgeitems):] + ] + else: + vars = [ + _format_tensor(x, summary, indent + 1, max_width, signed) + for x in var + ] + + return '[' + (',' + '\n' * (len(var.shape) - 1) + ' ' * + (indent + 1)).join(vars) + ']' + + +def to_string(var, prefix='Tensor'): + indent = len(prefix) + 1 + + dtype = convert_dtype(var.dtype) + if var.dtype == core.VarDesc.VarType.BF16: + dtype = 'bfloat16' + + _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient},\n{indent}{data})" + + tensor = var.value().get_tensor() + if not tensor._is_initialized(): + return "Tensor(Not initialized)" + + if var.dtype == core.VarDesc.VarType.BF16: + var = var.astype('float32') + np_var = var.numpy() + + if len(var.shape) == 0: + size = 0 + else: + size = 1 + for dim in var.shape: + size *= dim + + summary = False + if size > DEFAULT_PRINT_OPTIONS.threshold: + summary = True + + max_width, signed = _get_max_width(_to_summary(np_var)) + + data = _format_tensor(np_var, + summary, + indent=indent, + max_width=max_width, + signed=signed) + + return _template.format(prefix=prefix, + shape=var.shape, + dtype=dtype, + place=var._place_str, + stop_gradient=var.stop_gradient, + indent=' ' * indent, + data=data) + + +def _format_dense_tensor(tensor, indent): + if tensor.dtype == core.VarDesc.VarType.BF16: + tensor = tensor.astype('float32') + + np_tensor = tensor.numpy() + + if len(tensor.shape) == 0: + size = 0 + else: + size = 1 + for dim in tensor.shape: + size *= dim + + sumary = False + if size > DEFAULT_PRINT_OPTIONS.threshold: + sumary = True + + max_width, signed = _get_max_width(_to_summary(np_tensor)) + + data = _format_tensor(np_tensor, + sumary, + indent=indent, + max_width=max_width, + signed=signed) + return data + + +def sparse_tensor_to_string(tensor, prefix='Tensor'): + indent = len(prefix) + 1 + if tensor.is_sparse_coo(): + _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient}, \n{indent}{indices}, \n{indent}{values})" + indices_tensor = tensor.indices() + values_tensor = tensor.values() + indices_data = 'indices=' + _format_dense_tensor( + indices_tensor, indent + len('indices=')) + values_data = 'values=' + _format_dense_tensor(values_tensor, + indent + len('values=')) + return _template.format(prefix=prefix, + shape=tensor.shape, + dtype=tensor.dtype, + place=tensor._place_str, + stop_gradient=tensor.stop_gradient, + indent=' ' * indent, + indices=indices_data, + values=values_data) + else: + _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient}, \n{indent}{crows}, \n{indent}{cols}, \n{indent}{values})" + crows_tensor = tensor.crows() + cols_tensor = tensor.cols() + elements_tensor = tensor.values() + crows_data = 'crows=' + _format_dense_tensor(crows_tensor, + indent + len('crows=')) + cols_data = 'cols=' + _format_dense_tensor(cols_tensor, + indent + len('cols=')) + values_data = 'values=' + _format_dense_tensor(elements_tensor, + indent + len('values=')) + + return _template.format(prefix=prefix, + shape=tensor.shape, + dtype=tensor.dtype, + place=tensor._place_str, + stop_gradient=tensor.stop_gradient, + indent=' ' * indent, + crows=crows_data, + cols=cols_data, + values=values_data) + + +def tensor_to_string(tensor, prefix='Tensor'): + indent = len(prefix) + 1 + + dtype = convert_dtype(tensor.dtype) + if tensor.dtype == core.VarDesc.VarType.BF16: + dtype = 'bfloat16' + + _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient},\n{indent}{data})" + + if tensor.is_sparse(): + return sparse_tensor_to_string(tensor, prefix) + + if not tensor._is_dense_tensor_hold_allocation(): + return "Tensor(Not initialized)" + else: + data = _format_dense_tensor(tensor, indent) + return _template.format(prefix=prefix, + shape=tensor.shape, + dtype=dtype, + place=tensor._place_str, + stop_gradient=tensor.stop_gradient, + indent=' ' * indent, + data=data) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5775a24785804743a811ffa54d23bb1452f2a2eb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/__init__.py @@ -0,0 +1,27 @@ +# 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. + +from .viterbi_decode import ViterbiDecoder, viterbi_decode +from .datasets import Conll05st # noqa: F401 +from .datasets import Imdb # noqa: F401 +from .datasets import Imikolov # noqa: F401 +from .datasets import Movielens # noqa: F401 +from .datasets import UCIHousing # noqa: F401 +from .datasets import WMT14 # noqa: F401 +from .datasets import WMT16 # noqa: F401 + +__all__ = [ #noqa + 'Conll05st', 'Imdb', 'Imikolov', 'Movielens', 'UCIHousing', 'WMT14', + 'WMT16', 'ViterbiDecoder', 'viterbi_decode' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..118917049928bf2f191d49bedc9c3bee5095004b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/__init__.py @@ -0,0 +1,23 @@ +# 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. + +from .conll05 import Conll05st # noqa: F401 +from .imdb import Imdb # noqa: F401 +from .imikolov import Imikolov # noqa: F401 +from .movielens import Movielens # noqa: F401 +from .uci_housing import UCIHousing # noqa: F401 +from .wmt14 import WMT14 # noqa: F401 +from .wmt16 import WMT16 # noqa: F401 + +__all__ = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/conll05.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/conll05.py new file mode 100644 index 0000000000000000000000000000000000000000..09f54d674fd936ce2d08dd331fb064925996a241 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/conll05.py @@ -0,0 +1,325 @@ +# 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. + +from __future__ import print_function + +import gzip +import tarfile +import numpy as np +import six +from six.moves import cPickle as pickle + +from paddle.io import Dataset +import paddle.compat as cpt +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +DATA_URL = 'http://paddlemodels.bj.bcebos.com/conll05st/conll05st-tests.tar.gz' +DATA_MD5 = '387719152ae52d60422c016e92a742fc' +WORDDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FwordDict.txt' +WORDDICT_MD5 = 'ea7fb7d4c75cc6254716f0177a506baa' +VERBDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FverbDict.txt' +VERBDICT_MD5 = '0d2977293bbb6cbefab5b0f97db1e77c' +TRGDICT_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2FtargetDict.txt' +TRGDICT_MD5 = 'd8c7f03ceb5fc2e5a0fa7503a4353751' +EMB_URL = 'http://paddlemodels.bj.bcebos.com/conll05st%2Femb' +EMB_MD5 = 'bf436eb0faa1f6f9103017f8be57cdb7' + +UNK_IDX = 0 + + +class Conll05st(Dataset): + """ + Implementation of `Conll05st `_ + test dataset. + + Note: only support download test dataset automatically for that + only test dataset of Conll05st is public. + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + word_dict_file(str): path to word dictionary file, can be set None if + :attr:`download` is True. Default None + verb_dict_file(str): path to verb dictionary file, can be set None if + :attr:`download` is True. Default None + target_dict_file(str): path to target dictionary file, can be set None if + :attr:`download` is True. Default None + emb_file(str): path to embedding dictionary file, only used for + :code:`get_embedding` can be set None if :attr:`download` is + True. Default None + download(bool): whether to download dataset automatically if + :attr:`data_file` :attr:`word_dict_file` :attr:`verb_dict_file` + :attr:`target_dict_file` is not set. Default True + + Returns: + Dataset: instance of conll05st dataset + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import Conll05st + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, pred_idx, mark, label): + return paddle.sum(pred_idx), paddle.sum(mark), paddle.sum(label) + + + conll05st = Conll05st() + + for i in range(10): + pred_idx, mark, label= conll05st[i][-3:] + pred_idx = paddle.to_tensor(pred_idx) + mark = paddle.to_tensor(mark) + label = paddle.to_tensor(label) + + model = SimpleNet() + pred_idx, mark, label= model(pred_idx, mark, label) + print(pred_idx.numpy(), mark.numpy(), label.numpy()) + + """ + + def __init__(self, + data_file=None, + word_dict_file=None, + verb_dict_file=None, + target_dict_file=None, + emb_file=None, + download=True): + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, DATA_URL, + DATA_MD5, 'conll05st', + download) + + self.word_dict_file = word_dict_file + if self.word_dict_file is None: + assert download, "word_dict_file is not set and downloading automatically is disabled" + self.word_dict_file = _check_exists_and_download( + word_dict_file, WORDDICT_URL, WORDDICT_MD5, 'conll05st', + download) + + self.verb_dict_file = verb_dict_file + if self.verb_dict_file is None: + assert download, "verb_dict_file is not set and downloading automatically is disabled" + self.verb_dict_file = _check_exists_and_download( + verb_dict_file, VERBDICT_URL, VERBDICT_MD5, 'conll05st', + download) + + self.target_dict_file = target_dict_file + if self.target_dict_file is None: + assert download, "target_dict_file is not set and downloading automatically is disabled" + self.target_dict_file = _check_exists_and_download( + target_dict_file, TRGDICT_URL, TRGDICT_MD5, 'conll05st', + download) + + self.emb_file = emb_file + if self.emb_file is None: + assert download, "emb_file is not set and downloading automatically is disabled" + self.emb_file = _check_exists_and_download(emb_file, EMB_URL, + EMB_MD5, 'conll05st', + download) + + self.word_dict = self._load_dict(self.word_dict_file) + self.predicate_dict = self._load_dict(self.verb_dict_file) + self.label_dict = self._load_label_dict(self.target_dict_file) + + # read dataset into memory + self._load_anno() + + def _load_label_dict(self, filename): + d = dict() + tag_dict = set() + with open(filename, 'r') as f: + for i, line in enumerate(f): + line = line.strip() + if line.startswith("B-"): + tag_dict.add(line[2:]) + elif line.startswith("I-"): + tag_dict.add(line[2:]) + index = 0 + for tag in tag_dict: + d["B-" + tag] = index + index += 1 + d["I-" + tag] = index + index += 1 + d["O"] = index + return d + + def _load_dict(self, filename): + d = dict() + with open(filename, 'r') as f: + for i, line in enumerate(f): + d[line.strip()] = i + return d + + def _load_anno(self): + tf = tarfile.open(self.data_file) + wf = tf.extractfile( + "conll05st-release/test.wsj/words/test.wsj.words.gz") + pf = tf.extractfile( + "conll05st-release/test.wsj/props/test.wsj.props.gz") + self.sentences = [] + self.predicates = [] + self.labels = [] + with gzip.GzipFile(fileobj=wf) as words_file, gzip.GzipFile( + fileobj=pf) as props_file: + sentences = [] + labels = [] + one_seg = [] + for word, label in zip(words_file, props_file): + word = cpt.to_text(word.strip()) + label = cpt.to_text(label.strip().split()) + + if len(label) == 0: # end of sentence + for i in range(len(one_seg[0])): + a_kind_lable = [x[i] for x in one_seg] + labels.append(a_kind_lable) + + if len(labels) >= 1: + verb_list = [] + for x in labels[0]: + if x != '-': + verb_list.append(x) + + for i, lbl in enumerate(labels[1:]): + cur_tag = 'O' + is_in_bracket = False + lbl_seq = [] + verb_word = '' + for l in lbl: + if l == '*' and is_in_bracket == False: + lbl_seq.append('O') + elif l == '*' and is_in_bracket == True: + lbl_seq.append('I-' + cur_tag) + elif l == '*)': + lbl_seq.append('I-' + cur_tag) + is_in_bracket = False + elif l.find('(') != -1 and l.find(')') != -1: + cur_tag = l[1:l.find('*')] + lbl_seq.append('B-' + cur_tag) + is_in_bracket = False + elif l.find('(') != -1 and l.find(')') == -1: + cur_tag = l[1:l.find('*')] + lbl_seq.append('B-' + cur_tag) + is_in_bracket = True + else: + raise RuntimeError('Unexpected label: %s' % + l) + + self.sentences.append(sentences) + self.predicates.append(verb_list[i]) + self.labels.append(lbl_seq) + + sentences = [] + labels = [] + one_seg = [] + else: + sentences.append(word) + one_seg.append(label) + + pf.close() + wf.close() + tf.close() + + def __getitem__(self, idx): + sentence = self.sentences[idx] + predicate = self.predicates[idx] + labels = self.labels[idx] + + sen_len = len(sentence) + + verb_index = labels.index('B-V') + mark = [0] * len(labels) + if verb_index > 0: + mark[verb_index - 1] = 1 + ctx_n1 = sentence[verb_index - 1] + else: + ctx_n1 = 'bos' + + if verb_index > 1: + mark[verb_index - 2] = 1 + ctx_n2 = sentence[verb_index - 2] + else: + ctx_n2 = 'bos' + + mark[verb_index] = 1 + ctx_0 = sentence[verb_index] + + if verb_index < len(labels) - 1: + mark[verb_index + 1] = 1 + ctx_p1 = sentence[verb_index + 1] + else: + ctx_p1 = 'eos' + + if verb_index < len(labels) - 2: + mark[verb_index + 2] = 1 + ctx_p2 = sentence[verb_index + 2] + else: + ctx_p2 = 'eos' + + word_idx = [self.word_dict.get(w, UNK_IDX) for w in sentence] + + ctx_n2_idx = [self.word_dict.get(ctx_n2, UNK_IDX)] * sen_len + ctx_n1_idx = [self.word_dict.get(ctx_n1, UNK_IDX)] * sen_len + ctx_0_idx = [self.word_dict.get(ctx_0, UNK_IDX)] * sen_len + ctx_p1_idx = [self.word_dict.get(ctx_p1, UNK_IDX)] * sen_len + ctx_p2_idx = [self.word_dict.get(ctx_p2, UNK_IDX)] * sen_len + + pred_idx = [self.predicate_dict.get(predicate)] * sen_len + label_idx = [self.label_dict.get(w) for w in labels] + + return (np.array(word_idx), np.array(ctx_n2_idx), np.array(ctx_n1_idx), + np.array(ctx_0_idx), np.array(ctx_p1_idx), np.array(ctx_p2_idx), + np.array(pred_idx), np.array(mark), np.array(label_idx)) + + def __len__(self): + return len(self.sentences) + + def get_dict(self): + """ + Get the word, verb and label dictionary of Wikipedia corpus. + + Examples: + + .. code-block:: python + + from paddle.text.datasets import Conll05st + + conll05st = Conll05st() + word_dict, predicate_dict, label_dict = conll05st.get_dict() + """ + return self.word_dict, self.predicate_dict, self.label_dict + + def get_embedding(self): + """ + Get the embedding dictionary file. + + Examples: + + .. code-block:: python + + from paddle.text.datasets import Conll05st + + conll05st = Conll05st() + emb_file = conll05st.get_embedding() + """ + return self.emb_file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imdb.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imdb.py new file mode 100644 index 0000000000000000000000000000000000000000..dc100795accff08286078c9814e24554c9d595d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imdb.py @@ -0,0 +1,144 @@ +# 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. + +from __future__ import print_function + +import re +import six +import string +import tarfile +import numpy as np +import collections + +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +URL = 'https://dataset.bj.bcebos.com/imdb%2FaclImdb_v1.tar.gz' +MD5 = '7c2ac02c03563afcf9b574c7e56c153a' + + +class Imdb(Dataset): + """ + Implementation of `IMDB `_ dataset. + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + mode(str): 'train' 'test' mode. Default 'train'. + cutoff(int): cutoff number for building word dictionary. Default 150. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: instance of IMDB dataset + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import Imdb + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, doc, label): + return paddle.sum(doc), label + + + imdb = Imdb(mode='train') + + for i in range(10): + doc, label = imdb[i] + doc = paddle.to_tensor(doc) + label = paddle.to_tensor(label) + + model = SimpleNet() + image, label = model(doc, label) + print(doc.numpy().shape, label.numpy().shape) + + """ + + def __init__(self, data_file=None, mode='train', cutoff=150, download=True): + assert mode.lower() in ['train', 'test'], \ + "mode should be 'train', 'test', but got {}".format(mode) + self.mode = mode.lower() + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, URL, MD5, + 'imdb', download) + + # Build a word dictionary from the corpus + self.word_idx = self._build_work_dict(cutoff) + + # read dataset into memory + self._load_anno() + + def _build_work_dict(self, cutoff): + word_freq = collections.defaultdict(int) + pattern = re.compile(r"aclImdb/((train)|(test))/((pos)|(neg))/.*\.txt$") + for doc in self._tokenize(pattern): + for word in doc: + word_freq[word] += 1 + + # Not sure if we should prune less-frequent words here. + word_freq = [x for x in six.iteritems(word_freq) if x[1] > cutoff] + + dictionary = sorted(word_freq, key=lambda x: (-x[1], x[0])) + words, _ = list(zip(*dictionary)) + word_idx = dict(list(zip(words, six.moves.range(len(words))))) + word_idx[''] = len(words) + return word_idx + + def _tokenize(self, pattern): + data = [] + with tarfile.open(self.data_file) as tarf: + tf = tarf.next() + while tf != None: + if bool(pattern.match(tf.name)): + # newline and punctuations removal and ad-hoc tokenization. + data.append( + tarf.extractfile(tf).read().rstrip( + six.b("\n\r")).translate( + None, + six.b(string.punctuation)).lower().split()) + tf = tarf.next() + + return data + + def _load_anno(self): + pos_pattern = re.compile(r"aclImdb/{}/pos/.*\.txt$".format(self.mode)) + neg_pattern = re.compile(r"aclImdb/{}/neg/.*\.txt$".format(self.mode)) + + UNK = self.word_idx[''] + + self.docs = [] + self.labels = [] + for doc in self._tokenize(pos_pattern): + self.docs.append([self.word_idx.get(w, UNK) for w in doc]) + self.labels.append(0) + for doc in self._tokenize(neg_pattern): + self.docs.append([self.word_idx.get(w, UNK) for w in doc]) + self.labels.append(1) + + def __getitem__(self, idx): + return (np.array(self.docs[idx]), np.array([self.labels[idx]])) + + def __len__(self): + return len(self.docs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imikolov.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imikolov.py new file mode 100644 index 0000000000000000000000000000000000000000..9c84669d6b8d8d05ccb77dbd7a3188ed923d5dd5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/imikolov.py @@ -0,0 +1,170 @@ +# 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. + +from __future__ import print_function + +import six +import tarfile +import numpy as np +import collections + +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +URL = 'https://dataset.bj.bcebos.com/imikolov%2Fsimple-examples.tgz' +MD5 = '30177ea32e27c525793142b6bf2c8e2d' + + +class Imikolov(Dataset): + """ + Implementation of imikolov dataset. + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + data_type(str): 'NGRAM' or 'SEQ'. Default 'NGRAM'. + window_size(int): sliding window size for 'NGRAM' data. Default -1. + mode(str): 'train' 'test' mode. Default 'train'. + min_word_freq(int): minimal word frequence for building word dictionary. Default 50. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: instance of imikolov dataset + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import Imikolov + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, src, trg): + return paddle.sum(src), paddle.sum(trg) + + + imikolov = Imikolov(mode='train', data_type='SEQ', window_size=2) + + for i in range(10): + src, trg = imikolov[i] + src = paddle.to_tensor(src) + trg = paddle.to_tensor(trg) + + model = SimpleNet() + src, trg = model(src, trg) + print(src.numpy().shape, trg.numpy().shape) + + """ + + def __init__(self, + data_file=None, + data_type='NGRAM', + window_size=-1, + mode='train', + min_word_freq=50, + download=True): + assert data_type.upper() in ['NGRAM', 'SEQ'], \ + "data type should be 'NGRAM', 'SEQ', but got {}".format(data_type) + self.data_type = data_type.upper() + + assert mode.lower() in ['train', 'test'], \ + "mode should be 'train', 'test', but got {}".format(mode) + self.mode = mode.lower() + + self.window_size = window_size + self.min_word_freq = min_word_freq + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically disabled" + self.data_file = _check_exists_and_download(data_file, URL, MD5, + 'imikolov', download) + + # Build a word dictionary from the corpus + self.word_idx = self._build_work_dict(min_word_freq) + + # read dataset into memory + self._load_anno() + + def word_count(self, f, word_freq=None): + if word_freq is None: + word_freq = collections.defaultdict(int) + + for l in f: + for w in l.strip().split(): + word_freq[w] += 1 + word_freq[''] += 1 + word_freq[''] += 1 + + return word_freq + + def _build_work_dict(self, cutoff): + train_filename = './simple-examples/data/ptb.train.txt' + test_filename = './simple-examples/data/ptb.valid.txt' + with tarfile.open(self.data_file) as tf: + trainf = tf.extractfile(train_filename) + testf = tf.extractfile(test_filename) + word_freq = self.word_count(testf, self.word_count(trainf)) + if '' in word_freq: + # remove for now, since we will set it as last index + del word_freq[''] + + word_freq = [ + x for x in six.iteritems(word_freq) if x[1] > self.min_word_freq + ] + + word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0])) + words, _ = list(zip(*word_freq_sorted)) + word_idx = dict(list(zip(words, six.moves.range(len(words))))) + word_idx[''] = len(words) + + return word_idx + + def _load_anno(self): + self.data = [] + with tarfile.open(self.data_file) as tf: + filename = './simple-examples/data/ptb.{}.txt'.format(self.mode) + f = tf.extractfile(filename) + + UNK = self.word_idx[''] + for l in f: + if self.data_type == 'NGRAM': + assert self.window_size > -1, 'Invalid gram length' + l = [''] + l.strip().split() + [''] + if len(l) >= self.window_size: + l = [self.word_idx.get(w, UNK) for w in l] + for i in six.moves.range(self.window_size, len(l) + 1): + self.data.append(tuple(l[i - self.window_size:i])) + elif self.data_type == 'SEQ': + l = l.strip().split() + l = [self.word_idx.get(w, UNK) for w in l] + src_seq = [self.word_idx['']] + l + trg_seq = l + [self.word_idx['']] + if self.window_size > 0 and len(src_seq) > self.window_size: + continue + self.data.append((src_seq, trg_seq)) + else: + assert False, 'Unknow data type' + + def __getitem__(self, idx): + return tuple([np.array(d) for d in self.data[idx]]) + + def __len__(self): + return len(self.data) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/movielens.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/movielens.py new file mode 100644 index 0000000000000000000000000000000000000000..94ebf6b594d662108f18017afb88408a58639441 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/movielens.py @@ -0,0 +1,220 @@ +# 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. + +from __future__ import print_function + +import numpy as np +import zipfile +import re +import random +import functools +import six + +import paddle +from paddle.io import Dataset +import paddle.compat as cpt +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +age_table = [1, 18, 25, 35, 45, 50, 56] + +URL = 'https://dataset.bj.bcebos.com/movielens%2Fml-1m.zip' +MD5 = 'c4d9eecfca2ab87c1945afe126590906' + + +class MovieInfo(object): + """ + Movie id, title and categories information are stored in MovieInfo. + """ + + def __init__(self, index, categories, title): + self.index = int(index) + self.categories = categories + self.title = title + + def value(self, categories_dict, movie_title_dict): + """ + Get information from a movie. + """ + return [[self.index], [categories_dict[c] for c in self.categories], + [movie_title_dict[w.lower()] for w in self.title.split()]] + + def __str__(self): + return "" % ( + self.index, self.title, self.categories) + + def __repr__(self): + return self.__str__() + + +class UserInfo(object): + """ + User id, gender, age, and job information are stored in UserInfo. + """ + + def __init__(self, index, gender, age, job_id): + self.index = int(index) + self.is_male = gender == 'M' + self.age = age_table.index(int(age)) + self.job_id = int(job_id) + + def value(self): + """ + Get information from a user. + """ + return [[self.index], [0 if self.is_male else 1], [self.age], + [self.job_id]] + + def __str__(self): + return "" % ( + self.index, "M" if self.is_male else "F", age_table[self.age], + self.job_id) + + def __repr__(self): + return str(self) + + +class Movielens(Dataset): + """ + Implementation of `Movielens 1-M `_ dataset. + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + mode(str): 'train' or 'test' mode. Default 'train'. + test_ratio(float): split ratio for test sample. Default 0.1. + rand_seed(int): random seed. Default 0. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: instance of Movielens 1-M dataset + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import Movielens + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, category, title, rating): + return paddle.sum(category), paddle.sum(title), paddle.sum(rating) + + + movielens = Movielens(mode='train') + + for i in range(10): + category, title, rating = movielens[i][-3:] + category = paddle.to_tensor(category) + title = paddle.to_tensor(title) + rating = paddle.to_tensor(rating) + + model = SimpleNet() + category, title, rating = model(category, title, rating) + print(category.numpy().shape, title.numpy().shape, rating.numpy().shape) + + """ + + def __init__(self, + data_file=None, + mode='train', + test_ratio=0.1, + rand_seed=0, + download=True): + assert mode.lower() in ['train', 'test'], \ + "mode should be 'train', 'test', but got {}".format(mode) + self.mode = mode.lower() + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, URL, MD5, + 'sentiment', download) + + self.test_ratio = test_ratio + self.rand_seed = rand_seed + + np.random.seed(rand_seed) + self._load_meta_info() + self._load_data() + + def _load_meta_info(self): + pattern = re.compile(r'^(.*)\((\d+)\)$') + self.movie_info = dict() + self.movie_title_dict = dict() + self.categories_dict = dict() + self.user_info = dict() + with zipfile.ZipFile(self.data_file) as package: + for info in package.infolist(): + assert isinstance(info, zipfile.ZipInfo) + title_word_set = set() + categories_set = set() + with package.open('ml-1m/movies.dat') as movie_file: + for i, line in enumerate(movie_file): + line = cpt.to_text(line, encoding='latin') + movie_id, title, categories = line.strip().split('::') + categories = categories.split('|') + for c in categories: + categories_set.add(c) + title = pattern.match(title).group(1) + self.movie_info[int(movie_id)] = MovieInfo( + index=movie_id, categories=categories, title=title) + for w in title.split(): + title_word_set.add(w.lower()) + + for i, w in enumerate(title_word_set): + self.movie_title_dict[w] = i + + for i, c in enumerate(categories_set): + self.categories_dict[c] = i + + with package.open('ml-1m/users.dat') as user_file: + for line in user_file: + line = cpt.to_text(line, encoding='latin') + uid, gender, age, job, _ = line.strip().split("::") + self.user_info[int(uid)] = UserInfo(index=uid, + gender=gender, + age=age, + job_id=job) + + def _load_data(self): + self.data = [] + is_test = self.mode == 'test' + with zipfile.ZipFile(self.data_file) as package: + with package.open('ml-1m/ratings.dat') as rating: + for line in rating: + line = cpt.to_text(line, encoding='latin') + if (np.random.random() < self.test_ratio) == is_test: + uid, mov_id, rating, _ = line.strip().split("::") + uid = int(uid) + mov_id = int(mov_id) + rating = float(rating) * 2 - 5.0 + + mov = self.movie_info[mov_id] + usr = self.user_info[uid] + self.data.append(usr.value() + \ + mov.value(self.categories_dict, self.movie_title_dict) + \ + [[rating]]) + + def __getitem__(self, idx): + data = self.data[idx] + return tuple([np.array(d) for d in data]) + + def __len__(self): + return len(self.data) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/uci_housing.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/uci_housing.py new file mode 100644 index 0000000000000000000000000000000000000000..c283aeaf733aa79d65443a11f79e44fc13148c01 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/uci_housing.py @@ -0,0 +1,113 @@ +# 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. + +from __future__ import print_function + +import six +import numpy as np + +import paddle +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +URL = 'http://paddlemodels.bj.bcebos.com/uci_housing/housing.data' +MD5 = 'd4accdce7a25600298819f8e28e8d593' +feature_names = [ + 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', + 'PTRATIO', 'B', 'LSTAT' +] + + +class UCIHousing(Dataset): + """ + Implementation of `UCI housing `_ + dataset + + Args: + data_file(str): path to data file, can be set None if + :attr:`download` is True. Default None + mode(str): 'train' or 'test' mode. Default 'train'. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: instance of UCI housing dataset. + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import UCIHousing + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, feature, target): + return paddle.sum(feature), target + + paddle.disable_static() + + uci_housing = UCIHousing(mode='train') + + for i in range(10): + feature, target = uci_housing[i] + feature = paddle.to_tensor(feature) + target = paddle.to_tensor(target) + + model = SimpleNet() + feature, target = model(feature, target) + print(feature.numpy().shape, target.numpy()) + + """ + + def __init__(self, data_file=None, mode='train', download=True): + assert mode.lower() in ['train', 'test'], \ + "mode should be 'train' or 'test', but got {}".format(mode) + self.mode = mode.lower() + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, URL, MD5, + 'uci_housing', download) + + # read dataset into memory + self._load_data() + + self.dtype = paddle.get_default_dtype() + + def _load_data(self, feature_num=14, ratio=0.8): + data = np.fromfile(self.data_file, sep=' ') + data = data.reshape(data.shape[0] // feature_num, feature_num) + maximums, minimums, avgs = data.max(axis=0), data.min( + axis=0), data.sum(axis=0) / data.shape[0] + for i in six.moves.range(feature_num - 1): + data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i]) + offset = int(data.shape[0] * ratio) + if self.mode == 'train': + self.data = data[:offset] + elif self.mode == 'test': + self.data = data[offset:] + + def __getitem__(self, idx): + data = self.data[idx] + return np.array(data[:-1]).astype(self.dtype), \ + np.array(data[-1:]).astype(self.dtype) + + def __len__(self): + return len(self.data) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt14.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt14.py new file mode 100644 index 0000000000000000000000000000000000000000..133c304a02a51d0d6f82a73f9611071025f8f170 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt14.py @@ -0,0 +1,201 @@ +# 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. + +from __future__ import print_function + +import tarfile +import numpy as np +import gzip +import six + +from paddle.io import Dataset +import paddle.compat as cpt +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +URL_DEV_TEST = ('http://www-lium.univ-lemans.fr/~schwenk/' + 'cslm_joint_paper/data/dev+test.tgz') +MD5_DEV_TEST = '7d7897317ddd8ba0ae5c5fa7248d3ff5' +# this is a small set of data for test. The original data is too large and +# will be add later. +URL_TRAIN = ('http://paddlemodels.bj.bcebos.com/wmt/wmt14.tgz') +MD5_TRAIN = '0791583d57d5beb693b9414c5b36798c' + +START = "" +END = "" +UNK = "" +UNK_IDX = 2 + + +class WMT14(Dataset): + """ + Implementation of `WMT14 `_ test dataset. + The original WMT14 dataset is too large and a small set of data for set is + provided. This module will download dataset from + http://paddlemodels.bj.bcebos.com/wmt/wmt14.tgz . + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + mode(str): 'train', 'test' or 'gen'. Default 'train' + dict_size(int): word dictionary size. Default -1. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: Instance of WMT14 dataset + - src_ids (np.array) - The sequence of token ids of source language. + - trg_ids (np.array) - The sequence of token ids of target language. + - trg_ids_next (np.array) - The next sequence of token ids of target language. + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import WMT14 + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, src_ids, trg_ids, trg_ids_next): + return paddle.sum(src_ids), paddle.sum(trg_ids), paddle.sum(trg_ids_next) + + wmt14 = WMT14(mode='train', dict_size=50) + + for i in range(10): + src_ids, trg_ids, trg_ids_next = wmt14[i] + src_ids = paddle.to_tensor(src_ids) + trg_ids = paddle.to_tensor(trg_ids) + trg_ids_next = paddle.to_tensor(trg_ids_next) + + model = SimpleNet() + src_ids, trg_ids, trg_ids_next = model(src_ids, trg_ids, trg_ids_next) + print(src_ids.numpy(), trg_ids.numpy(), trg_ids_next.numpy()) + + """ + + def __init__(self, + data_file=None, + mode='train', + dict_size=-1, + download=True): + assert mode.lower() in ['train', 'test', 'gen'], \ + "mode should be 'train', 'test' or 'gen', but got {}".format(mode) + self.mode = mode.lower() + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, URL_TRAIN, + MD5_TRAIN, 'wmt14', + download) + + # read dataset into memory + assert dict_size > 0, "dict_size should be set as positive number" + self.dict_size = dict_size + self._load_data() + + def _load_data(self): + + def __to_dict(fd, size): + out_dict = dict() + for line_count, line in enumerate(fd): + if line_count < size: + out_dict[cpt.to_text(line.strip())] = line_count + else: + break + return out_dict + + self.src_ids = [] + self.trg_ids = [] + self.trg_ids_next = [] + with tarfile.open(self.data_file, mode='r') as f: + names = [ + each_item.name for each_item in f + if each_item.name.endswith("src.dict") + ] + assert len(names) == 1 + self.src_dict = __to_dict(f.extractfile(names[0]), self.dict_size) + names = [ + each_item.name for each_item in f + if each_item.name.endswith("trg.dict") + ] + assert len(names) == 1 + self.trg_dict = __to_dict(f.extractfile(names[0]), self.dict_size) + + file_name = "{}/{}".format(self.mode, self.mode) + names = [ + each_item.name for each_item in f + if each_item.name.endswith(file_name) + ] + for name in names: + for line in f.extractfile(name): + line = cpt.to_text(line) + line_split = line.strip().split('\t') + if len(line_split) != 2: + continue + src_seq = line_split[0] # one source sequence + src_words = src_seq.split() + src_ids = [ + self.src_dict.get(w, UNK_IDX) + for w in [START] + src_words + [END] + ] + + trg_seq = line_split[1] # one target sequence + trg_words = trg_seq.split() + trg_ids = [self.trg_dict.get(w, UNK_IDX) for w in trg_words] + + # remove sequence whose length > 80 in training mode + if len(src_ids) > 80 or len(trg_ids) > 80: + continue + trg_ids_next = trg_ids + [self.trg_dict[END]] + trg_ids = [self.trg_dict[START]] + trg_ids + + self.src_ids.append(src_ids) + self.trg_ids.append(trg_ids) + self.trg_ids_next.append(trg_ids_next) + + def __getitem__(self, idx): + return (np.array(self.src_ids[idx]), np.array(self.trg_ids[idx]), + np.array(self.trg_ids_next[idx])) + + def __len__(self): + return len(self.src_ids) + + def get_dict(self, reverse=False): + """ + Get the source and target dictionary. + + Args: + reverse (bool): wether to reverse key and value in dictionary, + i.e. key: value to value: key. + + Returns: + Two dictionaries, the source and target dictionary. + + Examples: + + .. code-block:: python + + from paddle.text.datasets import WMT14 + wmt14 = WMT14(mode='train', dict_size=50) + src_dict, trg_dict = wmt14.get_dict() + """ + src_dict, trg_dict = self.src_dict, self.trg_dict + if reverse: + src_dict = {v: k for k, v in six.iteritems(src_dict)} + trg_dict = {v: k for k, v in six.iteritems(trg_dict)} + return src_dict, trg_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt16.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt16.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2245ae4fed50af755d8ffa731a0f939ba9f7db --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/datasets/wmt16.py @@ -0,0 +1,258 @@ +# 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. +""" +""" + +from __future__ import print_function + +import os +import six +import tarfile +import numpy as np +from collections import defaultdict + +import paddle +from paddle.io import Dataset +import paddle.compat as cpt +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +DATA_URL = ("http://paddlemodels.bj.bcebos.com/wmt/wmt16.tar.gz") +DATA_MD5 = "0c38be43600334966403524a40dcd81e" + +TOTAL_EN_WORDS = 11250 +TOTAL_DE_WORDS = 19220 + +START_MARK = "" +END_MARK = "" +UNK_MARK = "" + + +class WMT16(Dataset): + """ + Implementation of `WMT16 `_ test dataset. + ACL2016 Multimodal Machine Translation. Please see this website for more + details: http://www.statmt.org/wmt16/multimodal-task.html#task1 + + If you use the dataset created for your task, please cite the following paper: + Multi30K: Multilingual English-German Image Descriptions. + + .. code-block:: text + + @article{elliott-EtAl:2016:VL16, + author = {{Elliott}, D. and {Frank}, S. and {Sima"an}, K. and {Specia}, L.}, + title = {Multi30K: Multilingual English-German Image Descriptions}, + booktitle = {Proceedings of the 6th Workshop on Vision and Language}, + year = {2016}, + pages = {70--74}, + year = 2016 + } + + Args: + data_file(str): path to data tar file, can be set None if + :attr:`download` is True. Default None + mode(str): 'train', 'test' or 'val'. Default 'train' + src_dict_size(int): word dictionary size for source language word. Default -1. + trg_dict_size(int): word dictionary size for target language word. Default -1. + lang(str): source language, 'en' or 'de'. Default 'en'. + download(bool): whether to download dataset automatically if + :attr:`data_file` is not set. Default True + + Returns: + Dataset: Instance of WMT16 dataset. The instance of dataset has 3 fields: + - src_ids (np.array) - The sequence of token ids of source language. + - trg_ids (np.array) - The sequence of token ids of target language. + - trg_ids_next (np.array) - The next sequence of token ids of target language. + + Examples: + + .. code-block:: python + + import paddle + from paddle.text.datasets import WMT16 + + class SimpleNet(paddle.nn.Layer): + def __init__(self): + super(SimpleNet, self).__init__() + + def forward(self, src_ids, trg_ids, trg_ids_next): + return paddle.sum(src_ids), paddle.sum(trg_ids), paddle.sum(trg_ids_next) + + paddle.disable_static() + + wmt16 = WMT16(mode='train', src_dict_size=50, trg_dict_size=50) + + for i in range(10): + src_ids, trg_ids, trg_ids_next = wmt16[i] + src_ids = paddle.to_tensor(src_ids) + trg_ids = paddle.to_tensor(trg_ids) + trg_ids_next = paddle.to_tensor(trg_ids_next) + + model = SimpleNet() + src_ids, trg_ids, trg_ids_next = model(src_ids, trg_ids, trg_ids_next) + print(src_ids.numpy(), trg_ids.numpy(), trg_ids_next.numpy()) + + """ + + def __init__(self, + data_file=None, + mode='train', + src_dict_size=-1, + trg_dict_size=-1, + lang='en', + download=True): + assert mode.lower() in ['train', 'test', 'val'], \ + "mode should be 'train', 'test' or 'val', but got {}".format(mode) + self.mode = mode.lower() + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, DATA_URL, + DATA_MD5, 'wmt16', + download) + + self.lang = lang + assert src_dict_size > 0, "dict_size should be set as positive number" + assert trg_dict_size > 0, "dict_size should be set as positive number" + self.src_dict_size = min( + src_dict_size, (TOTAL_EN_WORDS if lang == "en" else TOTAL_DE_WORDS)) + self.trg_dict_size = min( + trg_dict_size, (TOTAL_DE_WORDS if lang == "en" else TOTAL_EN_WORDS)) + + # load source and target word dict + self.src_dict = self._load_dict(lang, src_dict_size) + self.trg_dict = self._load_dict("de" if lang == "en" else "en", + trg_dict_size) + + # load data + self.data = self._load_data() + + def _load_dict(self, lang, dict_size, reverse=False): + dict_path = os.path.join(paddle.dataset.common.DATA_HOME, + "wmt16/%s_%d.dict" % (lang, dict_size)) + dict_found = False + if os.path.exists(dict_path): + with open(dict_path, "rb") as d: + dict_found = len(d.readlines()) == dict_size + if not dict_found: + self._build_dict(dict_path, dict_size, lang) + + word_dict = {} + with open(dict_path, "rb") as fdict: + for idx, line in enumerate(fdict): + if reverse: + word_dict[idx] = cpt.to_text(line.strip()) + else: + word_dict[cpt.to_text(line.strip())] = idx + return word_dict + + def _build_dict(self, dict_path, dict_size, lang): + word_dict = defaultdict(int) + with tarfile.open(self.data_file, mode="r") as f: + for line in f.extractfile("wmt16/train"): + line = cpt.to_text(line) + line_split = line.strip().split("\t") + if len(line_split) != 2: continue + sen = line_split[0] if self.lang == "en" else line_split[1] + for w in sen.split(): + word_dict[w] += 1 + + with open(dict_path, "wb") as fout: + fout.write( + cpt.to_bytes("%s\n%s\n%s\n" % (START_MARK, END_MARK, UNK_MARK))) + for idx, word in enumerate( + sorted(six.iteritems(word_dict), + key=lambda x: x[1], + reverse=True)): + if idx + 3 == dict_size: break + fout.write(cpt.to_bytes(word[0])) + fout.write(cpt.to_bytes('\n')) + + def _load_data(self): + # the index for start mark, end mark, and unk are the same in source + # language and target language. Here uses the source language + # dictionary to determine their indices. + start_id = self.src_dict[START_MARK] + end_id = self.src_dict[END_MARK] + unk_id = self.src_dict[UNK_MARK] + + src_col = 0 if self.lang == "en" else 1 + trg_col = 1 - src_col + + self.src_ids = [] + self.trg_ids = [] + self.trg_ids_next = [] + with tarfile.open(self.data_file, mode="r") as f: + for line in f.extractfile("wmt16/{}".format(self.mode)): + line = cpt.to_text(line) + line_split = line.strip().split("\t") + if len(line_split) != 2: + continue + src_words = line_split[src_col].split() + src_ids = [start_id] + [ + self.src_dict.get(w, unk_id) for w in src_words + ] + [end_id] + + trg_words = line_split[trg_col].split() + trg_ids = [self.trg_dict.get(w, unk_id) for w in trg_words] + + trg_ids_next = trg_ids + [end_id] + trg_ids = [start_id] + trg_ids + + self.src_ids.append(src_ids) + self.trg_ids.append(trg_ids) + self.trg_ids_next.append(trg_ids_next) + + def __getitem__(self, idx): + return (np.array(self.src_ids[idx]), np.array(self.trg_ids[idx]), + np.array(self.trg_ids_next[idx])) + + def __len__(self): + return len(self.src_ids) + + def get_dict(self, lang, reverse=False): + """ + return the word dictionary for the specified language. + + Args: + lang(string): A string indicating which language is the source + language. Available options are: "en" for English + and "de" for Germany. + reverse(bool): If reverse is set to False, the returned python + dictionary will use word as key and use index as value. + If reverse is set to True, the returned python + dictionary will use index as key and word as value. + + Returns: + dict: The word dictionary for the specific language. + + Examples: + + .. code-block:: python + + from paddle.text.datasets import WMT16 + wmt16 = WMT16(mode='train', src_dict_size=50, trg_dict_size=50) + en_dict = wmt16.get_dict('en') + + """ + dict_size = self.src_dict_size if lang == self.lang else self.trg_dict_size + + dict_path = os.path.join(paddle.dataset.common.DATA_HOME, + "wmt16/%s_%d.dict" % (lang, dict_size)) + assert os.path.exists(dict_path), "Word dictionary does not exist. " + "Please invoke paddle.dataset.wmt16.train/test/validation first " + "to build the dictionary." + return self._load_dict(lang, dict_size) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/viterbi_decode.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/viterbi_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c81b9c8e6283e89a765299b89dc41844f6d37f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/text/viterbi_decode.py @@ -0,0 +1,138 @@ +# Copyright (c) 2021 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. + +from ..nn import Layer +from ..fluid.framework import core, _non_static_mode, in_dygraph_mode +from ..fluid.layer_helper import LayerHelper +from ..fluid.data_feeder import check_variable_and_dtype, check_type +from paddle import _C_ops, _legacy_C_ops + +__all__ = ['viterbi_decode', 'ViterbiDecoder'] + + +def viterbi_decode(potentials, + transition_params, + lengths, + include_bos_eos_tag=True, + name=None): + """ + Decode the highest scoring sequence of tags computed by transitions and potentials and get the viterbi path. + + Args: + potentials (Tensor): The input tensor of unary emission. This is a 3-D + tensor with shape of [batch_size, sequence_length, num_tags]. The data type is float32 or float64. + transition_params (Tensor): The input tensor of transition matrix. This is a 2-D + tensor with shape of [num_tags, num_tags]. The data type is float32 or float64. + lengths (Tensor): The input tensor of length of each sequence. This is a 1-D tensor with shape of [batch_size]. The data type is int64. + include_bos_eos_tag (`bool`, optional): If set to True, the last row and the last column of transitions will be considered + as start tag, the second to last row and the second to last column of transitions will be considered as stop tag. Defaults to ``True``. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + scores(Tensor): The output tensor containing the score for the Viterbi sequence. The shape is [batch_size] + and the data type is float32 or float64. + paths(Tensor): The output tensor containing the highest scoring tag indices. The shape is [batch_size, sequence_length] + and the data type is int64. + + Example: + .. code-block:: python + + import paddle + paddle.seed(102) + batch_size, seq_len, num_tags = 2, 4, 3 + emission = paddle.rand((batch_size, seq_len, num_tags), dtype='float32') + length = paddle.randint(1, seq_len + 1, [batch_size]) + tags = paddle.randint(0, num_tags, [batch_size, seq_len]) + transition = paddle.rand((num_tags, num_tags), dtype='float32') + scores, path = paddle.text.viterbi_decode(emission, transition, length, False) # scores: [3.37089300, 1.56825531], path: [[1, 0, 0], [1, 1, 0]] + """ + if in_dygraph_mode(): + return _C_ops.viterbi_decode(potentials, transition_params, lengths, + include_bos_eos_tag) + + if _non_static_mode(): + return _legacy_C_ops.viterbi_decode(potentials, transition_params, + lengths, 'include_bos_eos_tag', + include_bos_eos_tag) + check_variable_and_dtype(potentials, 'input', ['float32', 'float64'], + 'viterbi_decode') + check_variable_and_dtype(transition_params, 'transitions', + ['float32', 'float64'], 'viterbi_decode') + check_variable_and_dtype(lengths, 'length', 'int64', 'viterbi_decode') + check_type(include_bos_eos_tag, 'include_tag', bool, 'viterbi_decode') + helper = LayerHelper('viterbi_decode', **locals()) + attrs = {'include_bos_eos_tag': include_bos_eos_tag} + scores = helper.create_variable_for_type_inference(potentials.dtype) + path = helper.create_variable_for_type_inference('int64') + helper.append_op(type='viterbi_decode', + inputs={ + 'Input': potentials, + 'Transition': transition_params, + 'Length': lengths + }, + outputs={ + 'Scores': scores, + 'Path': path + }, + attrs=attrs) + return scores, path + + +class ViterbiDecoder(Layer): + """ + Decode the highest scoring sequence of tags computed by transitions and potentials and get the viterbi path. + + Args: + transitions (`Tensor`): The transition matrix. Its dtype is float32 and has a shape of `[num_tags, num_tags]`. + include_bos_eos_tag (`bool`, optional): If set to True, the last row and the last column of transitions will be considered + as start tag, the second to last row and the second to last column of transitions will be considered as stop tag. Defaults to ``True``. + name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Shape: + potentials (Tensor): The input tensor of unary emission. This is a 3-D tensor with shape of + [batch_size, sequence_length, num_tags]. The data type is float32 or float64. + lengths (Tensor): The input tensor of length of each sequence. This is a 1-D tensor with shape of + [batch_size]. The data type is int64. + + Returns: + scores(Tensor): The output tensor containing the score for the Viterbi sequence. The shape is [batch_size] + and the data type is float32 or float64. + paths(Tensor): The output tensor containing the highest scoring tag indices. The shape is [batch_size, sequence_length] + and the data type is int64. + + Example: + .. code-block:: python + + import paddle + paddle.seed(102) + batch_size, seq_len, num_tags = 2, 4, 3 + emission = paddle.rand((batch_size, seq_len, num_tags), dtype='float32') + length = paddle.randint(1, seq_len + 1, [batch_size]) + tags = paddle.randint(0, num_tags, [batch_size, seq_len]) + transition = paddle.rand((num_tags, num_tags), dtype='float32') + decoder = paddle.text.ViterbiDecoder(transition, include_bos_eos_tag=False) + scores, path = decoder(emission, length) # scores: [3.37089300, 1.56825531], path: [[1, 0, 0], [1, 1, 0]] + """ + + def __init__(self, transitions, include_bos_eos_tag=True, name=None): + super(ViterbiDecoder, self).__init__() + self.transitions = transitions + self.include_bos_eos_tag = include_bos_eos_tag + self.name = name + + def forward(self, potentials, lengths): + return viterbi_decode(potentials, self.transitions, lengths, + self.include_bos_eos_tag, self.name) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6994fd139b647af272e0d75a3937bed79ae717c6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/__init__.py @@ -0,0 +1,33 @@ +# 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. + +from . import gast +from .profiler import ProfilerOptions # noqa: F401 +from .profiler import Profiler # noqa: F401 +from .profiler import get_profiler # noqa: F401 +from .deprecated import deprecated # noqa: F401 +from .lazy_import import try_import # noqa: F401 +from .op_version import OpLastCheckpointChecker # noqa: F401 +from .install_check import run_check # noqa: F401 +from . import unique_name # noqa: F401 +from ..fluid.framework import require_version # noqa: F401 + +from . import download # noqa: F401 +from . import image_util # noqa: F401 +from . import cpp_extension # noqa: F401 +from . import dlpack + +__all__ = [ #noqa + 'deprecated', 'run_check', 'require_version', 'try_import' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..843f78d5c803a5f9dedc00865c7eaa5ad6c5fd6a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2021 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. + +from .cpp_extension import CUDAExtension # noqa: F401 +from .cpp_extension import CppExtension # noqa: F401 +from .cpp_extension import BuildExtension # noqa: F401 +from .cpp_extension import load # noqa: F401 +from .cpp_extension import setup # noqa: F401 + +from .extension_utils import parse_op_info # noqa: F401 +from .extension_utils import get_build_directory # noqa: F401 +from .extension_utils import load_op_meta_info_and_register_op # noqa: F401 + +__all__ = [ #noqa + 'CppExtension', 'CUDAExtension', 'load', 'setup', 'get_build_directory' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/cpp_extension.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/cpp_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..a8821e7a03e0f8c8c39676926e20de33900cea3b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/cpp_extension.py @@ -0,0 +1,949 @@ +# Copyright (c) 2021 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. + +import os +import six +import copy +import re + +import setuptools +from setuptools.command.easy_install import easy_install +from setuptools.command.build_ext import build_ext +from distutils.command.build import build + +from .extension_utils import ( + find_cuda_home, + find_rocm_home, + normalize_extension_kwargs, + add_compile_flag, + run_cmd, +) +from .extension_utils import ( + is_cuda_file, + prepare_unix_cudaflags, + prepare_win_cudaflags, +) +from .extension_utils import ( + _import_module_from_library, + _write_setup_file, + _jit_compile, +) +from .extension_utils import ( + check_abi_compatibility, + log_v, + CustomOpInfo, + parse_op_name_from, +) +from .extension_utils import ( + clean_object_if_change_cflags, + _reset_so_rpath, + _get_fluid_path, +) +from .extension_utils import ( + bootstrap_context, + get_build_directory, + add_std_without_repeat, +) + +from .extension_utils import ( + IS_WINDOWS, + OS_NAME, + MSVC_COMPILE_FLAGS, + MSVC_COMPILE_FLAGS, +) +from .extension_utils import CLANG_COMPILE_FLAGS, CLANG_LINK_FLAGS + +from ...fluid import core + +# Note(zhouwei): On windows, it will export function 'PyInit_[name]' by default, +# The solution is: 1.User add function PyInit_[name] 2. set not to export +# refer to https://stackoverflow.com/questions/34689210/error-exporting-symbol-when-building-python-c-extension-in-windows +if IS_WINDOWS and six.PY3: + from distutils.command.build_ext import build_ext as _du_build_ext + from unittest.mock import Mock + + _du_build_ext.get_export_symbols = Mock(return_value=None) + +CUDA_HOME = find_cuda_home() +if core.is_compiled_with_rocm(): + ROCM_HOME = find_rocm_home() + CUDA_HOME = ROCM_HOME + + +def setup(**attr): + """ + The interface is used to config the process of compiling customized operators, + mainly includes how to compile shared library, automatically generate python API + and install it into site-package. It supports using customized operators directly with + ``import`` statement. + + It encapsulates the python built-in ``setuptools.setup`` function and keeps arguments + and usage same as the native interface. Meanwhile, it hiddens Paddle inner framework + concepts, such as necessary compiling flags, included paths of head files, and linking + flags. It also will automatically search and valid local environment and versions of + ``cc(Linux)`` , ``cl.exe(Windows)`` and ``nvcc`` , then compiles customized operators + supporting CPU or GPU device according to the specified Extension type. + + Moreover, `ABI compatibility `_ + will be checked to ensure that compiler version from ``cc(Linux)`` , ``cl.exe(Windows)`` + on local machine is compatible with pre-installed Paddle whl in python site-packages. + + For Linux, GCC version will be checked . For example if Paddle with CUDA 10.1 is built with GCC 8.2, + then the version of user's local machine should satisfy GCC >= 8.2. + For Windows, Visual Studio version will be checked, and it should be greater than or equal to that of + PaddlePaddle (Visual Studio 2017). + If the above conditions are not met, the corresponding warning will be printed, and a fatal error may + occur because of ABI compatibility. + + Note: + + 1. Currently we support Linux, MacOS and Windows platfrom. + 2. On Linux platform, we recommend to use GCC 8.2 as soft linking condidate of ``/usr/bin/cc`` . + Then, Use ``which cc`` to ensure location of ``cc`` and using ``cc --version`` to ensure linking + GCC version. + 3. On Windows platform, we recommend to install `` Visual Studio`` (>=2017). + + + Compared with Just-In-Time ``load`` interface, it only compiles once by executing + ``python setup.py install`` . Then customized operators API will be available everywhere + after importing it. + + A simple example of ``setup.py`` as followed: + + .. code-block:: text + + # setup.py + + # Case 1: Compiling customized operators supporting CPU and GPU devices + from paddle.utils.cpp_extension import CUDAExtension, setup + + setup( + name='custom_op', # name of package used by "import" + ext_modules=CUDAExtension( + sources=['relu_op.cc', 'relu_op.cu', 'tanh_op.cc', 'tanh_op.cu'] # Support for compilation of multiple OPs + ) + ) + + # Case 2: Compiling customized operators supporting only CPU device + from paddle.utils.cpp_extension import CppExtension, setup + + setup( + name='custom_op', # name of package used by "import" + ext_modules=CppExtension( + sources=['relu_op.cc', 'tanh_op.cc'] # Support for compilation of multiple OPs + ) + ) + + + Applying compilation and installation by executing ``python setup.py install`` under source files directory. + Then we can use the layer api as followed: + + .. code-block:: text + + import paddle + from custom_op import relu, tanh + + x = paddle.randn([4, 10], dtype='float32') + relu_out = relu(x) + tanh_out = tanh(x) + + + Args: + name(str): Specify the name of shared library file and installed python package. + ext_modules(Extension): Specify the Extension instance including customized operator source files, compiling flags et.al. + If only compile operator supporting CPU device, please use ``CppExtension`` ; If compile operator + supporting CPU and GPU devices, please use ``CUDAExtension`` . + include_dirs(list[str], optional): Specify the extra include directories to search head files. The interface will automatically add + ``site-package/paddle/include`` . Please add the corresponding directory path if including third-party + head files. Default is None. + extra_compile_args(list[str] | dict, optional): Specify the extra compiling flags such as ``-O3`` . If set ``list[str]`` , all these flags + will be applied for ``cc`` and ``nvcc`` compiler. It support specify flags only applied ``cc`` or ``nvcc`` + compiler using dict type with ``{'cxx': [...], 'nvcc': [...]}`` . Default is None. + **attr(dict, optional): Specify other arguments same as ``setuptools.setup`` . + + Returns: + None + + """ + cmdclass = attr.get('cmdclass', {}) + assert isinstance(cmdclass, dict) + # if not specific cmdclass in setup, add it automatically. + if 'build_ext' not in cmdclass: + cmdclass['build_ext'] = BuildExtension.with_options( + no_python_abi_suffix=True + ) + attr['cmdclass'] = cmdclass + + error_msg = """ + Required to specific `name` argument in paddle.utils.cpp_extension.setup. + It's used as `import XXX` when you want install and import your custom operators.\n + For Example: + # setup.py file + from paddle.utils.cpp_extension import CUDAExtension, setup + setup(name='custom_module', + ext_modules=CUDAExtension( + sources=['relu_op.cc', 'relu_op.cu']) + + # After running `python setup.py install` + from custom_module import relu + """ + # name argument is required + if 'name' not in attr: + raise ValueError(error_msg) + + assert not attr['name'].endswith( + 'module' + ), "Please don't use 'module' as suffix in `name` argument, " + "it will be stripped in setuptools.bdist_egg and cause import error." + + ext_modules = attr.get('ext_modules', []) + if not isinstance(ext_modules, list): + ext_modules = [ext_modules] + assert ( + len(ext_modules) == 1 + ), "Required only one Extension, but received {}. If you want to compile multi operators, you can include all necessary source files in one Extension.".format( + len(ext_modules) + ) + # replace Extension.name with attr['name] to keep consistant with Package name. + for ext_module in ext_modules: + ext_module.name = attr['name'] + + attr['ext_modules'] = ext_modules + + # Add rename .so hook in easy_install + assert 'easy_install' not in cmdclass + cmdclass['easy_install'] = EasyInstallCommand + + # Note(Aurelius84): Add rename build_base directory hook in build command. + # To avoid using same build directory that will lead to remove the directory + # by mistake while parallelling execute setup.py, for example on CI. + assert 'build' not in cmdclass + build_base = os.path.join('build', attr['name']) + cmdclass['build'] = BuildCommand.with_options(build_base=build_base) + + # Always set zip_safe=False to make compatible in PY2 and PY3 + # See http://peak.telecommunity.com/DevCenter/setuptools#setting-the-zip-safe-flag + attr['zip_safe'] = False + + # switch `write_stub` to inject paddle api in .egg + with bootstrap_context(): + setuptools.setup(**attr) + + +def CppExtension(sources, *args, **kwargs): + """ + The interface is used to config source files of customized operators and complies + Op Kernel only supporting CPU device. Please use ``CUDAExtension`` if you want to + compile Op Kernel that supports both CPU and GPU devices. + + It further encapsulates python built-in ``setuptools.Extension`` .The arguments and + usage are same as the native interface, except for no need to explicitly specify + ``name`` . + + **A simple example:** + + .. code-block:: text + + # setup.py + + # Compiling customized operators supporting only CPU device + from paddle.utils.cpp_extension import CppExtension, setup + + setup( + name='custom_op', + ext_modules=CppExtension(sources=['relu_op.cc']) + ) + + + Note: + It is mainly used in ``setup`` and the nama of built shared library keeps same + as ``name`` argument specified in ``setup`` interface. + + + Args: + sources(list[str]): Specify the C++/CUDA source files of customized operators. + *args(list[options], optional): Specify other arguments same as ``setuptools.Extension`` . + **kwargs(dict[option], optional): Specify other arguments same as ``setuptools.Extension`` . + + Returns: + setuptools.Extension: An instance of ``setuptools.Extension`` + """ + kwargs = normalize_extension_kwargs(kwargs, use_cuda=False) + # Note(Aurelius84): While using `setup` and `jit`, the Extension `name` will + # be replaced as `setup.name` to keep consistant with package. Because we allow + # users can not specific name in Extension. + # See `paddle.utils.cpp_extension.setup` for details. + name = kwargs.get('name', None) + if name is None: + name = _generate_extension_name(sources) + + return setuptools.Extension(name, sources, *args, **kwargs) + + +def CUDAExtension(sources, *args, **kwargs): + """ + The interface is used to config source files of customized operators and complies + Op Kernel supporting both CPU and GPU devices. Please use ``CppExtension`` if you want to + compile Op Kernel that supports only CPU device. + + It further encapsulates python built-in ``setuptools.Extension`` .The arguments and + usage are same as the native interface, except for no need to explicitly specify + ``name`` . + + **A simple example:** + + .. code-block:: text + + # setup.py + + # Compiling customized operators supporting CPU and GPU devices + from paddle.utils.cpp_extension import CUDAExtension, setup + + setup( + name='custom_op', + ext_modules=CUDAExtension( + sources=['relu_op.cc', 'relu_op.cu'] + ) + ) + + + Note: + It is mainly used in ``setup`` and the nama of built shared library keeps same + as ``name`` argument specified in ``setup`` interface. + + + Args: + sources(list[str]): Specify the C++/CUDA source files of customized operators. + *args(list[options], optional): Specify other arguments same as ``setuptools.Extension`` . + **kwargs(dict[option], optional): Specify other arguments same as ``setuptools.Extension`` . + + Returns: + setuptools.Extension: An instance of setuptools.Extension. + """ + kwargs = normalize_extension_kwargs(kwargs, use_cuda=True) + # Note(Aurelius84): While using `setup` and `jit`, the Extension `name` will + # be replaced as `setup.name` to keep consistant with package. Because we allow + # users can not specific name in Extension. + # See `paddle.utils.cpp_extension.setup` for details. + name = kwargs.get('name', None) + if name is None: + name = _generate_extension_name(sources) + + return setuptools.Extension(name, sources, *args, **kwargs) + + +def _generate_extension_name(sources): + """ + Generate extension name by source files. + """ + assert len(sources) > 0, "source files is empty" + file_prefix = [] + for source in sources: + source = os.path.basename(source) + filename, _ = os.path.splitext(source) + # Use list to generate same order. + if filename not in file_prefix: + file_prefix.append(filename) + + return '_'.join(file_prefix) + + +class BuildExtension(build_ext, object): + """ + Inherited from setuptools.command.build_ext to customize how to apply + compilation process with share library. + """ + + @classmethod + def with_options(cls, **options): + """ + Returns a BuildExtension subclass containing use-defined options. + """ + + class cls_with_options(cls): + def __init__(self, *args, **kwargs): + kwargs.update(options) + cls.__init__(self, *args, **kwargs) + + return cls_with_options + + def __init__(self, *args, **kwargs): + """ + Attributes is initialized with following oreder: + + 1. super(self).__init__() + 2. initialize_options(self) + 3. the reset of current __init__() + 4. finalize_options(self) + + So, it is recommended to set attribute value in `finalize_options`. + """ + super(BuildExtension, self).__init__(*args, **kwargs) + self.no_python_abi_suffix = kwargs.get("no_python_abi_suffix", True) + self.output_dir = kwargs.get("output_dir", None) + # whether containing cuda source file in Extensions + self.contain_cuda_file = False + + def initialize_options(self): + super(BuildExtension, self).initialize_options() + + def finalize_options(self): + super(BuildExtension, self).finalize_options() + # NOTE(Aurelius84): Set location of compiled shared library. + # Carefully to modify this because `setup.py build/install` + # and `load` interface rely on this attribute. + if self.output_dir is not None: + self.build_lib = self.output_dir + + def build_extensions(self): + if OS_NAME.startswith("darwin"): + self._valid_clang_compiler() + + self._check_abi() + + # Note(Aurelius84): If already compiling source before, we should check whether + # cflags have changed and delete the built shared library to re-compile the source + # even though source file content keep unchanged. + so_name = self.get_ext_fullpath(self.extensions[0].name) + clean_object_if_change_cflags( + os.path.abspath(so_name), self.extensions[0] + ) + + # Consider .cu, .cu.cc as valid source extensions. + self.compiler.src_extensions += ['.cu', '.cu.cc'] + # Save the original _compile method for later. + if self.compiler.compiler_type == 'msvc': + self.compiler._cpp_extensions += ['.cu', '.cuh'] + original_compile = self.compiler.compile + original_spawn = self.compiler.spawn + else: + original_compile = self.compiler._compile + + def unix_custom_single_compiler( + obj, src, ext, cc_args, extra_postargs, pp_opts + ): + """ + Monkey patch machanism to replace inner compiler to custom complie process on Unix platform. + """ + # use abspath to ensure no warning and don't remove deecopy because modify params + # with dict type is dangerous. + src = os.path.abspath(src) + cflags = copy.deepcopy(extra_postargs) + try: + original_compiler = self.compiler.compiler_so + # nvcc or hipcc compile CUDA source + if is_cuda_file(src): + if core.is_compiled_with_rocm(): + assert ( + ROCM_HOME is not None + ), "Not found ROCM runtime, \ + please use `export ROCM_PATH= XXX` to specify it." + + hipcc_cmd = os.path.join(ROCM_HOME, 'bin', 'hipcc') + self.compiler.set_executable('compiler_so', hipcc_cmd) + # {'nvcc': {}, 'cxx: {}} + if isinstance(cflags, dict): + cflags = cflags['hipcc'] + else: + assert ( + CUDA_HOME is not None + ), "Not found CUDA runtime, \ + please use `export CUDA_HOME= XXX` to specify it." + + nvcc_cmd = os.path.join(CUDA_HOME, 'bin', 'nvcc') + self.compiler.set_executable('compiler_so', nvcc_cmd) + # {'nvcc': {}, 'cxx: {}} + if isinstance(cflags, dict): + cflags = cflags['nvcc'] + + cflags = prepare_unix_cudaflags(cflags) + # cxx compile Cpp source + elif isinstance(cflags, dict): + cflags = cflags['cxx'] + + # Note(qili93): HIP require some additional flags for CMAKE_C_FLAGS + if core.is_compiled_with_rocm(): + cflags.append('-D__HIP_PLATFORM_HCC__') + cflags.append('-D__HIP_NO_HALF_CONVERSIONS__=1') + cflags.append( + '-DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_SYSTEM_HIP' + ) + + # NOTE(Aurelius84): Since Paddle 2.0, we require gcc version > 5.x, + # so we add this flag to ensure the symbol names from user compiled + # shared library have same ABI suffix with libpaddle.so. + # See https://stackoverflow.com/questions/34571583/understanding-gcc-5s-glibcxx-use-cxx11-abi-or-the-new-abi + add_compile_flag(cflags, ['-D_GLIBCXX_USE_CXX11_ABI=1']) + # Append this macor only when jointly compiling .cc with .cu + if not is_cuda_file(src) and self.contain_cuda_file: + if core.is_compiled_with_rocm(): + cflags.append('-DPADDLE_WITH_HIP') + else: + cflags.append('-DPADDLE_WITH_CUDA') + + add_std_without_repeat( + cflags, self.compiler.compiler_type, use_std14=True + ) + original_compile(obj, src, ext, cc_args, cflags, pp_opts) + finally: + # restore original_compiler + self.compiler.set_executable('compiler_so', original_compiler) + + def win_custom_single_compiler( + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + + self.cflags = copy.deepcopy(extra_postargs) + extra_postargs = None + + def win_custom_spawn(cmd): + # Using regex to modify compile options + compile_options = self.compiler.compile_options + for i in range(len(cmd)): + if re.search('/MD', cmd[i]) is not None: + cmd[i] = '/MT' + if re.search('/W[1-4]', cmd[i]) is not None: + cmd[i] = '/W0' + + # Using regex to match src, obj and include files + src_regex = re.compile('/T(p|c)(.*)') + src_list = [ + m.group(2) + for m in (src_regex.match(elem) for elem in cmd) + if m + ] + + obj_regex = re.compile('/Fo(.*)') + obj_list = [ + m.group(1) + for m in (obj_regex.match(elem) for elem in cmd) + if m + ] + + include_regex = re.compile(r'((\-|\/)I.*)') + include_list = [ + m.group(1) + for m in (include_regex.match(elem) for elem in cmd) + if m + ] + + assert len(src_list) == 1 and len(obj_list) == 1 + src = src_list[0] + obj = obj_list[0] + if is_cuda_file(src): + assert ( + CUDA_HOME is not None + ), "Not found CUDA runtime, \ + please use `export CUDA_HOME= XXX` to specify it." + + nvcc_cmd = os.path.join(CUDA_HOME, 'bin', 'nvcc') + if isinstance(self.cflags, dict): + cflags = self.cflags['nvcc'] + elif isinstance(self.cflags, list): + cflags = self.cflags + else: + cflags = [] + + cflags = prepare_win_cudaflags(cflags) + ['--use-local-env'] + for flag in MSVC_COMPILE_FLAGS: + cflags = ['-Xcompiler', flag] + cflags + cmd = ( + [nvcc_cmd, '-c', src, '-o', obj] + include_list + cflags + ) + elif isinstance(self.cflags, dict): + cflags = MSVC_COMPILE_FLAGS + self.cflags['cxx'] + cmd += cflags + elif isinstance(self.cflags, list): + cflags = MSVC_COMPILE_FLAGS + self.cflags + cmd += cflags + # Append this macor only when jointly compiling .cc with .cu + if not is_cuda_file(src) and self.contain_cuda_file: + cmd.append('-DPADDLE_WITH_CUDA') + + return original_spawn(cmd) + + try: + self.compiler.spawn = win_custom_spawn + return original_compile( + sources, + output_dir, + macros, + include_dirs, + debug, + extra_preargs, + extra_postargs, + depends, + ) + finally: + self.compiler.spawn = original_spawn + + def object_filenames_with_cuda(origina_func, build_directory): + """ + Decorated the function to add customized naming machanism. + Originally, both .cc/.cu will have .o object output that will + bring file override problem. Use .cu.o as CUDA object suffix. + """ + + def wrapper(source_filenames, strip_dir=0, output_dir=''): + try: + objects = origina_func( + source_filenames, strip_dir, output_dir + ) + for i, source in enumerate(source_filenames): + # modify xx.o -> xx.cu.o/xx.cu.obj + if is_cuda_file(source): + old_obj = objects[i] + if self.compiler.compiler_type == 'msvc': + objects[i] = old_obj[:-3] + 'cu.obj' + else: + objects[i] = old_obj[:-1] + 'cu.o' + # if user set build_directory, output objects there. + if build_directory is not None: + objects = [ + os.path.join(build_directory, os.path.basename(obj)) + for obj in objects + ] + # ensure to use abspath + objects = [os.path.abspath(obj) for obj in objects] + finally: + self.compiler.object_filenames = origina_func + + return objects + + return wrapper + + # customized compile process + if self.compiler.compiler_type == 'msvc': + self.compiler.compile = win_custom_single_compiler + else: + self.compiler._compile = unix_custom_single_compiler + + self.compiler.object_filenames = object_filenames_with_cuda( + self.compiler.object_filenames, self.build_lib + ) + self._record_op_info() + + print("Compiling user custom op, it will cost a few seconds.....") + build_ext.build_extensions(self) + + # Reset runtime library path on MacOS platform + so_path = self.get_ext_fullpath(self.extensions[0]._full_name) + _reset_so_rpath(so_path) + + def get_ext_filename(self, fullname): + # for example: custommed_extension.cpython-37m-x86_64-linux-gnu.so + ext_name = super(BuildExtension, self).get_ext_filename(fullname) + split_str = '.' + name_items = ext_name.split(split_str) + if self.no_python_abi_suffix and six.PY3: + assert ( + len(name_items) > 2 + ), "Expected len(name_items) > 2, but received {}".format( + len(name_items) + ) + name_items.pop(-2) + ext_name = split_str.join(name_items) + + # custommed_extension.dylib + if OS_NAME.startswith('darwin'): + name_items[-1] = 'dylib' + ext_name = split_str.join(name_items) + return ext_name + + def _valid_clang_compiler(self): + """ + Make sure to use Clang as compiler on Mac platform + """ + compiler_infos = ['clang'] + CLANG_COMPILE_FLAGS + linker_infos = ['clang'] + CLANG_LINK_FLAGS + self.compiler.set_executables( + compiler=compiler_infos, + compiler_so=compiler_infos, + compiler_cxx=['clang'], + linker_exe=['clang'], + linker_so=linker_infos, + ) + + def _check_abi(self): + """ + Check ABI Compatibility. + """ + if hasattr(self.compiler, 'compiler_cxx'): + compiler = self.compiler.compiler_cxx[0] + elif IS_WINDOWS: + compiler = os.environ.get('CXX', 'cl') + else: + compiler = os.environ.get('CXX', 'c++') + + check_abi_compatibility(compiler) + # Warn user if VC env is activated but `DISTUTILS_USE_SDK` is not set. + if ( + IS_WINDOWS + and 'VSCMD_ARG_TGT_ARCH' in os.environ + and 'DISTUTILS_USE_SDK' not in os.environ + ): + msg = ( + 'It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.' + 'This may lead to multiple activations of the VC env.' + 'Please run `set DISTUTILS_USE_SDK=1` and try again.' + ) + raise UserWarning(msg) + + def _record_op_info(self): + """ + Record custom op information. + """ + # parse shared library abs path + outputs = self.get_outputs() + assert len(outputs) == 1 + # multi operators built into same one .so file + so_path = os.path.abspath(outputs[0]) + so_name = os.path.basename(so_path) + + for i, extension in enumerate(self.extensions): + sources = [os.path.abspath(s) for s in extension.sources] + if not self.contain_cuda_file: + self.contain_cuda_file = any([is_cuda_file(s) for s in sources]) + op_names = parse_op_name_from(sources) + + for op_name in op_names: + CustomOpInfo.instance().add( + op_name, so_name=so_name, so_path=so_path + ) + + +class EasyInstallCommand(easy_install, object): + """ + Extend easy_intall Command to control the behavior of naming shared library + file. + + NOTE(Aurelius84): This is a hook subclass inherited Command used to rename shared + library file after extracting egg-info into site-packages. + """ + + def __init__(self, *args, **kwargs): + super(EasyInstallCommand, self).__init__(*args, **kwargs) + + # NOTE(Aurelius84): Add args and kwargs to make compatible with PY2/PY3 + def run(self, *args, **kwargs): + super(EasyInstallCommand, self).run(*args, **kwargs) + # NOTE: To avoid failing import .so file instead of + # python file because they have same name, we rename + # .so shared library to another name. + for egg_file in self.outputs: + filename, ext = os.path.splitext(egg_file) + will_rename = False + if OS_NAME.startswith('linux') and ext == '.so': + will_rename = True + elif OS_NAME.startswith('darwin') and ext == '.dylib': + will_rename = True + elif IS_WINDOWS and ext == '.pyd': + will_rename = True + + if will_rename: + new_so_path = filename + "_pd_" + ext + if not os.path.exists(new_so_path): + os.rename(r'%s' % egg_file, r'%s' % new_so_path) + assert os.path.exists(new_so_path) + + +class BuildCommand(build, object): + """ + Extend build Command to control the behavior of specifying `build_base` root directory. + + NOTE(Aurelius84): This is a hook subclass inherited Command used to specify customized + build_base directory. + """ + + @classmethod + def with_options(cls, **options): + """ + Returns a BuildCommand subclass containing use-defined options. + """ + + class cls_with_options(cls): + def __init__(self, *args, **kwargs): + kwargs.update(options) + cls.__init__(self, *args, **kwargs) + + return cls_with_options + + def __init__(self, *args, **kwargs): + # Note: shall put before super() + self._specified_build_base = kwargs.get('build_base', None) + + super(BuildCommand, self).__init__(*args, **kwargs) + + def initialize_options(self): + """ + build_base is root directory for all sub-command, such as + build_lib, build_temp. See `distutils.command.build` for details. + """ + super(BuildCommand, self).initialize_options() + if self._specified_build_base is not None: + self.build_base = self._specified_build_base + + +def load( + name, + sources, + extra_cxx_cflags=None, + extra_cuda_cflags=None, + extra_ldflags=None, + extra_include_paths=None, + build_directory=None, + verbose=False, +): + """ + An Interface to automatically compile C++/CUDA source files Just-In-Time + and return callable python function as other Paddle layers API. It will + append user defined custom operators in background while building models. + + It will perform compiling, linking, Python API generation and module loading + processes under a individual subprocess. It does not require CMake or Ninja + environment. On Linux platform, it requires GCC compiler whose version is + greater than 5.4 and it should be soft linked to ``/usr/bin/cc`` . On Windows + platform, it requires Visual Studio whose version is greater than 2017. + On MacOS, clang++ is requited. In addition, if compiling Operators supporting + GPU device, please make sure ``nvcc`` compiler is installed in local environment. + + Moreover, `ABI compatibility `_ + will be checked to ensure that compiler version from ``cc(Linux)`` , ``cl.exe(Windows)`` + on local machine is compatible with pre-installed Paddle whl in python site-packages. + + For Linux, GCC version will be checked . For example if Paddle with CUDA 10.1 is built with GCC 8.2, + then the version of user's local machine should satisfy GCC >= 8.2. + For Windows, Visual Studio version will be checked, and it should be greater than or equal to that of + PaddlePaddle (Visual Studio 2017). + If the above conditions are not met, the corresponding warning will be printed, and a fatal error may + occur because of ABI compatibility. + + Compared with ``setup`` interface, it doesn't need extra ``setup.py`` and excute + ``python setup.py install`` command. The interface contains all compiling and installing + process underground. + + Note: + + 1. Currently we support Linux, MacOS and Windows platfrom. + 2. On Linux platform, we recommend to use GCC 8.2 as soft linking condidate of ``/usr/bin/cc`` . + Then, Use ``which cc`` to ensure location of ``cc`` and using ``cc --version`` to ensure linking + GCC version. + 3. On Windows platform, we recommend to install `` Visual Studio`` (>=2017). + + + **A simple example:** + + .. code-block:: text + + import paddle + from paddle.utils.cpp_extension import load + + custom_op_module = load( + name="op_shared_libary_name", # name of shared library + sources=['relu_op.cc', 'relu_op.cu'], # source files of customized op + extra_cxx_cflags=['-g', '-w'], # optional, specify extra flags to compile .cc/.cpp file + extra_cuda_cflags=['-O2'], # optional, specify extra flags to compile .cu file + verbose=True # optional, specify to output log information + ) + + x = paddle.randn([4, 10], dtype='float32') + out = custom_op_module.relu(x) + + + Args: + name(str): Specify the name of generated shared library file name, not including ``.so`` and ``.dll`` suffix. + sources(list[str]): Specify source files name of customized operators. Supporting ``.cc`` , ``.cpp`` for CPP file + and ``.cu`` for CUDA file. + extra_cxx_cflags(list[str], optional): Specify additional flags used to compile CPP files. By default + all basic and framework related flags have been included. + extra_cuda_cflags(list[str], optional): Specify additional flags used to compile CUDA files. By default + all basic and framework related flags have been included. + See `Cuda Compiler Driver NVCC `_ + for details. Default is None. + extra_ldflags(list[str], optional): Specify additional flags used to link shared library. See + `GCC Link Options `_ for details. + Default is None. + extra_include_paths(list[str], optional): Specify additional include path used to search header files. By default + all basic headers are included implicitly from ``site-package/paddle/include`` . + Default is None. + build_directory(str, optional): Specify root directory path to put shared library file. If set None, + it will use ``PADDLE_EXTENSION_DIR`` from os.environ. Use + ``paddle.utils.cpp_extension.get_build_directory()`` to see the location. Default is None. + verbose(bool, optional): whether to verbose compiled log information. Default is False + + Returns: + Module: A callable python module contains all CustomOp Layer APIs. + + """ + + if build_directory is None: + build_directory = get_build_directory(verbose) + + # ensure to use abs path + build_directory = os.path.abspath(build_directory) + + log_v("build_directory: {}".format(build_directory), verbose) + + file_path = os.path.join(build_directory, "{}_setup.py".format(name)) + sources = [os.path.abspath(source) for source in sources] + + if extra_cxx_cflags is None: + extra_cxx_cflags = [] + if extra_cuda_cflags is None: + extra_cuda_cflags = [] + assert isinstance( + extra_cxx_cflags, list + ), "Required type(extra_cxx_cflags) == list[str], but received {}".format( + extra_cxx_cflags + ) + assert isinstance( + extra_cuda_cflags, list + ), "Required type(extra_cuda_cflags) == list[str], but received {}".format( + extra_cuda_cflags + ) + + log_v( + "additional extra_cxx_cflags: [{}], extra_cuda_cflags: [{}]".format( + ' '.join(extra_cxx_cflags), ' '.join(extra_cuda_cflags) + ), + verbose, + ) + + # write setup.py file and compile it + build_base_dir = os.path.join(build_directory, name) + + _write_setup_file( + name, + sources, + file_path, + build_base_dir, + extra_include_paths, + extra_cxx_cflags, + extra_cuda_cflags, + extra_ldflags, + verbose, + ) + _jit_compile(file_path, verbose) + + # import as callable python api + custom_op_api = _import_module_from_library(name, build_base_dir, verbose) + + return custom_op_api diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/extension_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/extension_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..693a47f3f86da6aa5bfc7b4bbbc9ca5f0bb687a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/cpp_extension/extension_utils.py @@ -0,0 +1,1238 @@ +# Copyright (c) 2021 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. + +import os +import re +import sys +import json +import glob +import atexit +import hashlib +import logging +import collections +import textwrap +import warnings +import subprocess +import threading + +from importlib import machinery +from contextlib import contextmanager +from setuptools.command import bdist_egg + +try: + from subprocess import DEVNULL # py3 +except ImportError: + DEVNULL = open(os.devnull, 'wb') + +from ...fluid import core +from ...fluid.framework import OpProtoHolder +from ...sysconfig import get_include, get_lib + +logger = logging.getLogger("utils.cpp_extension") +logger.setLevel(logging.INFO) +formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s') +ch = logging.StreamHandler() +ch.setFormatter(formatter) +logger.addHandler(ch) + +OS_NAME = sys.platform +IS_WINDOWS = OS_NAME.startswith('win') + +MSVC_COMPILE_FLAGS = [ + '/MT', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018', + '/wd4190', '/EHsc', '/w', '/DGOOGLE_GLOG_DLL_DECL', + '/DBOOST_HAS_STATIC_ASSERT', '/DNDEBUG', '/DPADDLE_USE_DSO' +] +CLANG_COMPILE_FLAGS = [ + '-fno-common', '-dynamic', '-DNDEBUG', '-g', '-fwrapv', '-O3', '-arch', + 'x86_64' +] +CLANG_LINK_FLAGS = [ + '-dynamiclib', '-undefined', 'dynamic_lookup', '-arch', 'x86_64' +] + +MSVC_LINK_FLAGS = ['/MACHINE:X64'] + +if core.is_compiled_with_rocm(): + COMMON_HIPCC_FLAGS = [ + '-DPADDLE_WITH_HIP', '-DEIGEN_USE_GPU', '-DEIGEN_USE_HIP' + ] +else: + COMMON_NVCC_FLAGS = ['-DPADDLE_WITH_CUDA', '-DEIGEN_USE_GPU'] + +GCC_MINI_VERSION = (5, 4, 0) +MSVC_MINI_VERSION = (19, 0, 24215) +# Give warning if using wrong compiler +WRONG_COMPILER_WARNING = ''' + ************************************* + * Compiler Compatibility WARNING * + ************************************* + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +Found that your compiler ({user_compiler}) is not compatible with the compiler +built Paddle for this platform, which is {paddle_compiler} on {platform}. Please +use {paddle_compiler} to compile your custom op. Or you may compile Paddle from +source using {user_compiler}, and then also use it compile your custom op. + +See https://www.paddlepaddle.org.cn/documentation/docs/zh/install/compile/fromsource.html +for help with compiling Paddle from source. + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +''' +# Give warning if used compiler version is incompatible +ABI_INCOMPATIBILITY_WARNING = ''' + ********************************** + * ABI Compatibility WARNING * + ********************************** + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +Found that your compiler ({user_compiler} == {version}) may be ABI-incompatible with pre-installed Paddle! +Please use compiler that is ABI-compatible with GCC >= 5.4 (Recommended 8.2). + +See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html for ABI Compatibility +information + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +''' + +DEFAULT_OP_ATTR_NAMES = [ + core.op_proto_and_checker_maker.kOpRoleAttrName(), + core.op_proto_and_checker_maker.kOpRoleVarAttrName(), + core.op_proto_and_checker_maker.kOpNameScopeAttrName(), + core.op_proto_and_checker_maker.kOpCreationCallstackAttrName(), + core.op_proto_and_checker_maker.kOpDeviceAttrName(), + core.op_proto_and_checker_maker.kOpWithQuantAttrName() +] + + +@contextmanager +def bootstrap_context(): + """ + Context to manage how to write `__bootstrap__` code in .egg + """ + origin_write_stub = bdist_egg.write_stub + bdist_egg.write_stub = custom_write_stub + yield + + bdist_egg.write_stub = origin_write_stub + + +def load_op_meta_info_and_register_op(lib_filename): + core.load_op_meta_info_and_register_op(lib_filename) + return OpProtoHolder.instance().update_op_proto() + + +def custom_write_stub(resource, pyfile): + """ + Customized write_stub function to allow us to inject generated python + api codes into egg python file. + """ + _stub_template = textwrap.dedent(""" + import os + import sys + import types + import paddle + + cur_dir = os.path.dirname(os.path.abspath(__file__)) + so_path = os.path.join(cur_dir, "{resource}") + + def inject_ext_module(module_name, api_names): + if module_name in sys.modules: + return sys.modules[module_name] + + new_module = types.ModuleType(module_name) + for api_name in api_names: + setattr(new_module, api_name, eval(api_name)) + + return new_module + + def __bootstrap__(): + assert os.path.exists(so_path) + + # load custom op shared library with abs path + new_custom_ops = paddle.utils.cpp_extension.load_op_meta_info_and_register_op(so_path) + m = inject_ext_module(__name__, new_custom_ops) + + __bootstrap__() + + {custom_api} + + """).lstrip() + + # Parse registerring op information + _, op_info = CustomOpInfo.instance().last() + so_path = op_info.so_path + + new_custom_ops = load_op_meta_info_and_register_op(so_path) + assert len( + new_custom_ops + ) > 0, "Required at least one custom operators, but received len(custom_op) = %d" % len( + new_custom_ops) + + # NOTE: To avoid importing .so file instead of python file because they have same name, + # we rename .so shared library to another name, see EasyInstallCommand. + filename, ext = os.path.splitext(resource) + resource = filename + "_pd_" + ext + + api_content = [] + for op_name in new_custom_ops: + api_content.append(_custom_api_content(op_name)) + + with open(pyfile, 'w') as f: + f.write( + _stub_template.format(resource=resource, + custom_api='\n\n'.join(api_content))) + + +OpInfo = collections.namedtuple('OpInfo', ['so_name', 'so_path']) + + +class CustomOpInfo: + """ + A global Singleton map to record all compiled custom ops information. + """ + + @classmethod + def instance(cls): + if not hasattr(cls, '_instance'): + cls._instance = cls() + return cls._instance + + def __init__(self): + assert not hasattr( + self.__class__, + '_instance'), 'Please use `instance()` to get CustomOpInfo object!' + # NOTE(Aurelius84): Use OrderedDict to save more order information + self.op_info_map = collections.OrderedDict() + + def add(self, op_name, so_name, so_path=None): + self.op_info_map[op_name] = OpInfo(so_name, so_path) + + def last(self): + """ + Return the lastest insert custom op info. + """ + assert len(self.op_info_map) > 0 + return next(reversed(self.op_info_map.items())) + + +VersionFields = collections.namedtuple('VersionFields', [ + 'sources', + 'extra_compile_args', + 'extra_link_args', + 'library_dirs', + 'runtime_library_dirs', + 'include_dirs', + 'define_macros', + 'undef_macros', +]) + + +class VersionManager: + + def __init__(self, version_field): + self.version_field = version_field + self.version = self.hasher(version_field) + + def hasher(self, version_field): + from paddle.fluid.layers.utils import flatten + + md5 = hashlib.md5() + for field in version_field._fields: + elem = getattr(version_field, field) + if not elem: continue + if isinstance(elem, (list, tuple, dict)): + flat_elem = flatten(elem) + md5 = combine_hash(md5, tuple(flat_elem)) + else: + raise RuntimeError( + "Support types with list, tuple and dict, but received {} with {}." + .format(type(elem), elem)) + + return md5.hexdigest() + + @property + def details(self): + return self.version_field._asdict() + + +def combine_hash(md5, value): + """ + Return new hash value. + DO NOT use `hash()` because it doesn't generate stable value between different process. + See https://stackoverflow.com/questions/27522626/hash-function-in-python-3-3-returns-different-results-between-sessions + """ + md5.update(repr(value).encode()) + return md5 + + +def clean_object_if_change_cflags(so_path, extension): + """ + If already compiling source before, we should check whether cflags + have changed and delete the built object to re-compile the source + even though source file content keeps unchanaged. + """ + + def serialize(path, version_info): + assert isinstance(version_info, dict) + with open(path, 'w') as f: + f.write(json.dumps(version_info, indent=4, sort_keys=True)) + + def deserialize(path): + assert os.path.exists(path) + with open(path, 'r') as f: + content = f.read() + return json.loads(content) + + # version file + VERSION_FILE = "version.txt" + base_dir = os.path.dirname(so_path) + so_name = os.path.basename(so_path) + version_file = os.path.join(base_dir, VERSION_FILE) + + # version info + args = [getattr(extension, field, None) for field in VersionFields._fields] + version_field = VersionFields._make(args) + versioner = VersionManager(version_field) + + if os.path.exists(so_path) and os.path.exists(version_file): + old_version_info = deserialize(version_file) + so_version = old_version_info.get(so_name, None) + # delete shared library file if version is changed to re-compile it. + if so_version is not None and so_version != versioner.version: + log_v( + "Re-Compiling {}, because specified cflags have been changed. New signature {} has been saved into {}." + .format(so_name, versioner.version, version_file)) + os.remove(so_path) + # update new version information + new_version_info = versioner.details + new_version_info[so_name] = versioner.version + serialize(version_file, new_version_info) + else: + # If compile at first time, save compiling detail information for debug. + if not os.path.exists(base_dir): + os.makedirs(base_dir) + details = versioner.details + details[so_name] = versioner.version + serialize(version_file, details) + + +def prepare_unix_cudaflags(cflags): + """ + Prepare all necessary compiled flags for nvcc compiling CUDA files. + """ + if core.is_compiled_with_rocm(): + cflags = COMMON_HIPCC_FLAGS + ['-Xcompiler', '-fPIC' + ] + cflags + get_rocm_arch_flags(cflags) + else: + cflags = COMMON_NVCC_FLAGS + [ + '-ccbin', 'cc', '-Xcompiler', '-fPIC', '--expt-relaxed-constexpr', + '-DNVCC' + ] + cflags + get_cuda_arch_flags(cflags) + + return cflags + + +def prepare_win_cudaflags(cflags): + """ + Prepare all necessary compiled flags for nvcc compiling CUDA files. + """ + cflags = COMMON_NVCC_FLAGS + ['-w'] + cflags + get_cuda_arch_flags(cflags) + + return cflags + + +def add_std_without_repeat(cflags, compiler_type, use_std14=False): + """ + Append -std=c++11/14 in cflags if without specific it before. + """ + cpp_flag_prefix = '/std:' if compiler_type == 'msvc' else '-std=' + if not any(cpp_flag_prefix in flag for flag in cflags): + suffix = 'c++14' if use_std14 else 'c++11' + cpp_flag = cpp_flag_prefix + suffix + cflags.append(cpp_flag) + + +def get_cuda_arch_flags(cflags): + """ + For an arch, say "6.1", the added compile flag will be + ``-gencode=arch=compute_61,code=sm_61``. + For an added "+PTX", an additional + ``-gencode=arch=compute_xx,code=compute_xx`` is added. + """ + # TODO(Aurelius84): + return [] + + +def get_rocm_arch_flags(cflags): + """ + For ROCm platform, amdgpu target should be added for HIPCC. + """ + cflags = cflags + ['-fno-gpu-rdc', '-amdgpu-target=gfx906'] + return cflags + + +def _get_fluid_path(): + """ + Return installed fluid dir path. + """ + import paddle + return os.path.join(os.path.dirname(paddle.__file__), 'fluid') + + +def _get_core_name(): + """ + Return pybind DSO module name. + """ + import paddle + ext_name = '.pyd' if IS_WINDOWS else '.so' + return 'libpaddle' + ext_name + + +def _get_lib_core_path(): + """ + Return real path of libcore_(no)avx.dylib on MacOS. + """ + raw_core_name = _get_core_name() + lib_core_name = "lib{}.dylib".format(raw_core_name[:-3]) + return os.path.join(_get_fluid_path(), lib_core_name) + + +def _get_dll_core_path(): + """ + Return real path of libcore_(no)avx.dylib on Windows. + """ + raw_core_name = _get_core_name() + dll_core_name = "libpaddle.dll" + return os.path.join(_get_fluid_path(), dll_core_name) + + +def _reset_so_rpath(so_path): + """ + NOTE(Aurelius84): Runtime path of libpaddle.so is modified into `@loader_path/../libs` + in setup.py.in. While loading custom op, `@loader_path` is the dirname of custom op + instead of `paddle/fluid`. So we modify `@loader_path` from custom dylib into `@rpath` + to ensure dynamic loader find it correctly. + + Moreover, we will add `-rpath site-packages/paddle/fluid` while linking the dylib so + that we don't need to set `LD_LIBRARY_PATH` any more. + """ + assert os.path.exists(so_path) + if OS_NAME.startswith("darwin"): + origin_runtime_path = "@loader_path/../libs/" + rpath = "@rpath/{}".format(_get_core_name()) + cmd = 'install_name_tool -change {} {} {}'.format( + origin_runtime_path, rpath, so_path) + + run_cmd(cmd) + + +def _get_include_dirs_when_compiling(compile_dir): + """ + Get all include directories when compiling the PaddlePaddle + source code. + """ + include_dirs_file = 'includes.txt' + path = os.path.abspath(compile_dir) + include_dirs_file = os.path.join(path, include_dirs_file) + assert os.path.isfile(include_dirs_file), "File {} does not exist".format( + include_dirs_file) + with open(include_dirs_file, 'r') as f: + include_dirs = [line.strip() for line in f.readlines() if line.strip()] + + extra_dirs = ['paddle/fluid/platform'] + all_include_dirs = list(include_dirs) + for extra_dir in extra_dirs: + for include_dir in include_dirs: + d = os.path.join(include_dir, extra_dir) + if os.path.isdir(d): + all_include_dirs.append(d) + all_include_dirs.append(path) + all_include_dirs.sort() + return all_include_dirs + + +def normalize_extension_kwargs(kwargs, use_cuda=False): + """ + Normalize include_dirs, library_dir and other attributes in kwargs. + """ + assert isinstance(kwargs, dict) + compile_include_dirs = [] + # NOTE: the "_compile_dir" argument is not public to users. It is only + # reserved for internal usage. We do not guarantee that this argument + # is always valid in the future release versions. + compile_dir = kwargs.get("_compile_dir", None) + if compile_dir: + compile_include_dirs = _get_include_dirs_when_compiling(compile_dir) + + # append necessary include dir path of paddle + include_dirs = list(kwargs.get('include_dirs', [])) + include_dirs.extend(compile_include_dirs) + include_dirs.extend(find_paddle_includes(use_cuda)) + + kwargs['include_dirs'] = include_dirs + + # append necessary lib path of paddle + library_dirs = kwargs.get('library_dirs', []) + library_dirs.extend(find_paddle_libraries(use_cuda)) + kwargs['library_dirs'] = library_dirs + + # append compile flags and check settings of compiler + extra_compile_args = kwargs.get('extra_compile_args', []) + if isinstance(extra_compile_args, dict): + for compiler in ['cxx', 'nvcc']: + if compiler not in extra_compile_args: + extra_compile_args[compiler] = [] + + if IS_WINDOWS: + # TODO(zhouwei): may append compile flags in future + pass + # append link flags + extra_link_args = kwargs.get('extra_link_args', []) + extra_link_args.extend(MSVC_LINK_FLAGS) + lib_core_name = create_sym_link_if_not_exist() + extra_link_args.append('{}'.format(lib_core_name)) + if use_cuda: + extra_link_args.extend(['cudadevrt.lib', 'cudart_static.lib']) + kwargs['extra_link_args'] = extra_link_args + + else: + ########################### Linux Platform ########################### + extra_link_args = kwargs.get('extra_link_args', []) + # On Linux, GCC support '-l:xxx.so' to specify the library name + # without `lib` prefix. + if OS_NAME.startswith('linux'): + extra_link_args.append('-l:{}'.format(_get_core_name())) + ########################### MacOS Platform ########################### + else: + # See _reset_so_rpath for details. + extra_link_args.append('-Wl,-rpath,{}'.format(_get_fluid_path())) + # On MacOS, ld don't support `-l:xx`, so we create a + # liblibpaddle.dylib symbol link. + lib_core_name = create_sym_link_if_not_exist() + extra_link_args.append('-l{}'.format(lib_core_name)) + ########################### -- END -- ########################### + + add_compile_flag(extra_compile_args, ['-w']) # disable warning + + if use_cuda: + if core.is_compiled_with_rocm(): + extra_link_args.append('-lamdhip64') + else: + extra_link_args.append('-lcudart') + + kwargs['extra_link_args'] = extra_link_args + + # add runtime library dirs + runtime_library_dirs = kwargs.get('runtime_library_dirs', []) + runtime_library_dirs.extend(find_paddle_libraries(use_cuda)) + kwargs['runtime_library_dirs'] = runtime_library_dirs + + if compile_dir is None: + # Add this compile option to isolate fluid headers + add_compile_flag(extra_compile_args, ['-DPADDLE_WITH_CUSTOM_KERNEL']) + kwargs['extra_compile_args'] = extra_compile_args + + kwargs['language'] = 'c++' + return kwargs + + +def create_sym_link_if_not_exist(): + """ + Create soft symbol link of `libpaddle.so` + """ + assert OS_NAME.startswith('darwin') or IS_WINDOWS + + raw_core_name = _get_core_name() + core_path = os.path.join(_get_fluid_path(), raw_core_name) + if IS_WINDOWS: + new_dll_core_path = _get_dll_core_path() + # create symbol link on windows + if not os.path.exists(new_dll_core_path): + try: + os.symlink(core_path, new_dll_core_path) + except Exception: + warnings.warn( + "Failed to create soft symbol link for {}.\n You can run prompt as administrator and execute the " + "following command manually: `mklink {} {}`. Now it will create hard link for {} trickly." + .format(raw_core_name, new_dll_core_path, core_path, + raw_core_name)) + run_cmd('mklink /H {} {}'.format(new_dll_core_path, core_path)) + # libpaddle with lib suffix + assert os.path.exists(new_dll_core_path) + return raw_core_name[:-4] + ".lib" + + else: + new_lib_core_path = _get_lib_core_path() + # create symbol link on mac + if not os.path.exists(new_lib_core_path): + try: + os.symlink(core_path, new_lib_core_path) + assert os.path.exists(new_lib_core_path) + except Exception: + raise RuntimeError( + "Failed to create soft symbol link for {}.\n Please execute the following command manually: `ln -s {} {}`" + .format(raw_core_name, core_path, new_lib_core_path)) + + # libpaddle without suffix + return raw_core_name[:-3] + + +def find_cuda_home(): + """ + Use heuristic method to find cuda path + """ + # step 1. find in $CUDA_HOME or $CUDA_PATH + cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH') + + # step 2. find path by `which nvcc` + if cuda_home is None: + which_cmd = 'where' if IS_WINDOWS else 'which' + try: + with open(os.devnull, 'w') as devnull: + nvcc_path = subprocess.check_output([which_cmd, 'nvcc'], + stderr=devnull) + nvcc_path = nvcc_path.decode() + # Multi CUDA, select the first + nvcc_path = nvcc_path.split('\r\n')[0] + + # for example: /usr/local/cuda/bin/nvcc + cuda_home = os.path.dirname(os.path.dirname(nvcc_path)) + except: + if IS_WINDOWS: + # search from default NVIDIA GPU path + candidate_paths = glob.glob( + 'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*.*' + ) + if len(candidate_paths) > 0: + cuda_home = candidate_paths[0] + else: + cuda_home = "/usr/local/cuda" + # step 3. check whether path is valid + if cuda_home and not os.path.exists( + cuda_home) and core.is_compiled_with_cuda(): + cuda_home = None + + return cuda_home + + +def find_rocm_home(): + """ + Use heuristic method to find rocm path + """ + # step 1. find in $ROCM_HOME or $ROCM_PATH + rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH') + + # step 2. find path by `which nvcc` + if rocm_home is None: + which_cmd = 'where' if IS_WINDOWS else 'which' + try: + with open(os.devnull, 'w') as devnull: + hipcc_path = subprocess.check_output([which_cmd, 'hipcc'], + stderr=devnull) + hipcc_path = hipcc_path.decode() + hipcc_path = hipcc_path.rstrip('\r\n') + + # for example: /opt/rocm/bin/hipcc + rocm_home = os.path.dirname(os.path.dirname(hipcc_path)) + except: + rocm_home = "/opt/rocm" + # step 3. check whether path is valid + if rocm_home and not os.path.exists( + rocm_home) and core.is_compiled_with_rocm(): + rocm_home = None + + return rocm_home + + +def find_cuda_includes(): + """ + Use heuristic method to find cuda include path + """ + cuda_home = find_cuda_home() + if cuda_home is None: + raise ValueError( + "Not found CUDA runtime, please use `export CUDA_HOME=XXX` to specific it." + ) + + return [os.path.join(cuda_home, 'include')] + + +def find_rocm_includes(): + """ + Use heuristic method to find rocm include path + """ + rocm_home = find_rocm_home() + if rocm_home is None: + raise ValueError( + "Not found ROCM runtime, please use `export ROCM_PATH= XXX` to specific it." + ) + + return [os.path.join(rocm_home, 'include')] + + +def find_paddle_includes(use_cuda=False): + """ + Return Paddle necessary include dir path. + """ + # pythonXX/site-packages/paddle/include + paddle_include_dir = get_include() + third_party_dir = os.path.join(paddle_include_dir, 'third_party') + include_dirs = [paddle_include_dir, third_party_dir] + + if use_cuda: + if core.is_compiled_with_rocm(): + rocm_include_dir = find_rocm_includes() + include_dirs.extend(rocm_include_dir) + else: + cuda_include_dir = find_cuda_includes() + include_dirs.extend(cuda_include_dir) + + if OS_NAME.startswith('darwin'): + # NOTE(Aurelius84): Ensure to find std v1 headers correctly. + std_v1_includes = find_clang_cpp_include() + if std_v1_includes is not None and os.path.exists(std_v1_includes): + include_dirs.append(std_v1_includes) + + return include_dirs + + +def find_clang_cpp_include(compiler='clang'): + std_v1_includes = None + try: + compiler_version = subprocess.check_output([compiler, "--version"]) + compiler_version = compiler_version.decode() + infos = compiler_version.split("\n") + for info in infos: + if "InstalledDir" in info: + v1_path = info.split(':')[-1].strip() + if v1_path and os.path.exists(v1_path): + std_v1_includes = os.path.join(os.path.dirname(v1_path), + 'include/c++/v1') + except Exception: + # Just raise warnings because the include dir is not required. + warnings.warn( + "Failed to search `include/c++/v1/` include dirs. Don't worry because it's not required." + ) + return std_v1_includes + + +def find_cuda_libraries(): + """ + Use heuristic method to find cuda static lib path + """ + cuda_home = find_cuda_home() + if cuda_home is None: + raise ValueError( + "Not found CUDA runtime, please use `export CUDA_HOME=XXX` to specific it." + ) + if IS_WINDOWS: + cuda_lib_dir = [os.path.join(cuda_home, 'lib', 'x64')] + else: + cuda_lib_dir = [os.path.join(cuda_home, 'lib64')] + + return cuda_lib_dir + + +def find_rocm_libraries(): + """ + Use heuristic method to find rocm dynamic lib path + """ + rocm_home = find_rocm_home() + if rocm_home is None: + raise ValueError( + "Not found ROCM runtime, please use `export ROCM_PATH=XXX` to specific it." + ) + rocm_lib_dir = [os.path.join(rocm_home, 'lib')] + + return rocm_lib_dir + + +def find_paddle_libraries(use_cuda=False): + """ + Return Paddle necessary library dir path. + """ + # pythonXX/site-packages/paddle/libs + paddle_lib_dirs = [get_lib()] + + if use_cuda: + if core.is_compiled_with_rocm(): + rocm_lib_dir = find_rocm_libraries() + paddle_lib_dirs.extend(rocm_lib_dir) + else: + cuda_lib_dir = find_cuda_libraries() + paddle_lib_dirs.extend(cuda_lib_dir) + + # add `paddle/fluid` to search `libpaddle.so` + paddle_lib_dirs.append(_get_fluid_path()) + + return paddle_lib_dirs + + +def add_compile_flag(extra_compile_args, flags): + assert isinstance(flags, list) + if isinstance(extra_compile_args, dict): + for args in extra_compile_args.values(): + args.extend(flags) + else: + extra_compile_args.extend(flags) + + +def is_cuda_file(path): + + cuda_suffix = set(['.cu']) + items = os.path.splitext(path) + assert len(items) > 1 + return items[-1] in cuda_suffix + + +def get_build_directory(verbose=False): + """ + Return paddle extension root directory to put shared library. It could be specified by + ``export PADDLE_EXTENSION_DIR=XXX`` . If not set, ``~/.cache/paddle_extension`` will be used + by default. + + Returns: + The root directory of compiling customized operators. + + Examples: + + .. code-block:: python + + from paddle.utils.cpp_extension import get_build_directory + + build_dir = get_build_directory() + print(build_dir) + + """ + root_extensions_directory = os.environ.get('PADDLE_EXTENSION_DIR') + if root_extensions_directory is None: + dir_name = "paddle_extensions" + root_extensions_directory = os.path.join(os.path.expanduser('~/.cache'), + dir_name) + if IS_WINDOWS: + root_extensions_directory = os.path.normpath( + root_extensions_directory) + + log_v( + "$PADDLE_EXTENSION_DIR is not set, using path: {} by default.". + format(root_extensions_directory), verbose) + + if not os.path.exists(root_extensions_directory): + os.makedirs(root_extensions_directory) + + return root_extensions_directory + + +def parse_op_info(op_name): + """ + Parse input names and outpus detail information from registered custom op + from OpInfoMap. + """ + if op_name not in OpProtoHolder.instance().op_proto_map: + raise ValueError( + "Please load {} shared library file firstly by `paddle.utils.cpp_extension.load_op_meta_info_and_register_op(...)`" + .format(op_name)) + op_proto = OpProtoHolder.instance().get_op_proto(op_name) + + in_names = [x.name for x in op_proto.inputs] + out_names = [x.name for x in op_proto.outputs] + attr_names = [ + x.name for x in op_proto.attrs if x.name not in DEFAULT_OP_ATTR_NAMES + ] + + return in_names, out_names, attr_names + + +def _import_module_from_library(module_name, build_directory, verbose=False): + """ + Load shared library and import it as callable python module. + """ + if IS_WINDOWS: + dynamic_suffix = '.pyd' + elif OS_NAME.startswith('darwin'): + dynamic_suffix = '.dylib' + else: + dynamic_suffix = '.so' + ext_path = os.path.join(build_directory, module_name + dynamic_suffix) + if not os.path.exists(ext_path): + raise FileNotFoundError( + "Extension path: {} does not exist.".format(ext_path)) + + # load custom op_info and kernels from .so shared library + log_v('loading shared library from: {}'.format(ext_path), verbose) + op_names = load_op_meta_info_and_register_op(ext_path) + + # generate Python api in ext_path + return _generate_python_module(module_name, op_names, build_directory, + verbose) + + +def _generate_python_module(module_name, + op_names, + build_directory, + verbose=False): + """ + Automatically generate python file to allow import or load into as module + """ + + def remove_if_exit(filepath): + if os.path.exists(filepath): + os.remove(filepath) + + # NOTE: Use unique id as suffix to avoid write same file at same time in + # both multi-thread and multi-process. + thread_id = str(threading.currentThread().ident) + api_file = os.path.join(build_directory, + module_name + '_' + thread_id + '.py') + log_v("generate api file: {}".format(api_file), verbose) + + # delete the temp file before exit python process + atexit.register(lambda: remove_if_exit(api_file)) + + # write into .py file with RWLockc + api_content = [_custom_api_content(op_name) for op_name in op_names] + with open(api_file, 'w') as f: + f.write('\n\n'.join(api_content)) + + # load module + custom_module = _load_module_from_file(api_file, module_name, verbose) + return custom_module + + +def _custom_api_content(op_name): + params_str, ins_str, attrs_str, outs_str, in_names, attrs_names = _get_api_inputs_str( + op_name) + lower_in_names = [p.split("@")[0].lower() for p in in_names] + API_TEMPLATE = textwrap.dedent(""" + import paddle.fluid.core as core + from paddle.fluid.core import VarBase, CustomOpKernelContext + from paddle.fluid.framework import _non_static_mode, _dygraph_tracer, _in_legacy_dygraph, in_dygraph_mode + from paddle.fluid.layer_helper import LayerHelper + + def {op_name}({inputs}): + # prepare inputs and outputs + ins = {ins} + attrs = {attrs} + outs = {{}} + out_names = {out_names} + + # The output variable's dtype use default value 'float32', + # and the actual dtype of output variable will be inferred in runtime. + if in_dygraph_mode(): + ctx = CustomOpKernelContext() + for i in {in_names}: + ctx.add_inputs(i) + for j in {attr_names}: + ctx.add_attr(j) + for out_name in out_names: + outs[out_name] = core.eager.Tensor() + ctx.add_outputs(outs[out_name]) + core.eager._run_custom_op(ctx, "{op_name}", True) + else: + if _in_legacy_dygraph(): + for out_name in out_names: + outs[out_name] = VarBase() + _dygraph_tracer().trace_op(type="{op_name}", inputs=ins, outputs=outs, attrs=attrs) + else: + helper = LayerHelper("{op_name}", **locals()) + for out_name in out_names: + outs[out_name] = helper.create_variable(dtype='float32') + + helper.append_op(type="{op_name}", inputs=ins, outputs=outs, attrs=attrs) + + res = [outs[out_name] for out_name in out_names] + + return res[0] if len(res)==1 else res + """).lstrip() + + # generate python api file + api_content = API_TEMPLATE.format( + op_name=op_name, + inputs=params_str, + ins=ins_str, + attrs=attrs_str, + # "[x, y, z]"" + in_names="[" + ",".join(lower_in_names) + "]", + attr_names="[" + ",".join(attrs_names) + "]", + out_names=outs_str) + + return api_content + + +def _load_module_from_file(api_file_path, module_name, verbose=False): + """ + Load module from python file. + """ + if not os.path.exists(api_file_path): + raise FileNotFoundError( + "File : {} does not exist.".format(api_file_path)) + + # Unique readable module name to place custom api. + log_v('import module from file: {}'.format(api_file_path), verbose) + ext_name = "_paddle_cpp_extension_" + module_name + + # load module with RWLock + loader = machinery.SourceFileLoader(ext_name, api_file_path) + module = loader.load_module() + + return module + + +def _get_api_inputs_str(op_name): + """ + Returns string of api parameters and inputs dict. + """ + in_names, out_names, attr_names = parse_op_info(op_name) + # e.g: x, y, z + param_names = in_names + attr_names + # NOTE(chenweihang): we add suffix `@VECTOR` for std::vector input, + # but the string contains `@` cannot used as argument name, so we split + # input name by `@`, and only use first substr as argument + params_str = ','.join([p.split("@")[0].lower() for p in param_names]) + # e.g: {'X': x, 'Y': y, 'Z': z} + ins_str = "{%s}" % ','.join([ + "'{}' : {}".format(in_name, + in_name.split("@")[0].lower()) + for in_name in in_names + ]) + # e.g: {'num': n} + attrs_str = "{%s}" % ",".join([ + "'{}' : {}".format(attr_name, + attr_name.split("@")[0].lower()) + for attr_name in attr_names + ]) + # e.g: ['Out', 'Index'] + outs_str = "[%s]" % ','.join(["'{}'".format(name) for name in out_names]) + return params_str, ins_str, attrs_str, outs_str, in_names, attr_names + + +def _write_setup_file(name, + sources, + file_path, + build_dir, + include_dirs, + extra_cxx_cflags, + extra_cuda_cflags, + link_args, + verbose=False): + """ + Automatically generate setup.py and write it into build directory. + """ + template = textwrap.dedent(""" + import os + from paddle.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension, setup + from paddle.utils.cpp_extension import get_build_directory + + + setup( + name='{name}', + ext_modules=[ + {prefix}Extension( + sources={sources}, + include_dirs={include_dirs}, + extra_compile_args={{'cxx':{extra_cxx_cflags}, 'nvcc':{extra_cuda_cflags}}}, + extra_link_args={extra_link_args})], + cmdclass={{"build_ext" : BuildExtension.with_options( + output_dir=r'{build_dir}', + no_python_abi_suffix=True) + }})""").lstrip() + + with_cuda = False + if any([is_cuda_file(source) for source in sources]): + with_cuda = True + log_v("with_cuda: {}".format(with_cuda), verbose) + + content = template.format(name=name, + prefix='CUDA' if with_cuda else 'Cpp', + sources=list2str(sources), + include_dirs=list2str(include_dirs), + extra_cxx_cflags=list2str(extra_cxx_cflags), + extra_cuda_cflags=list2str(extra_cuda_cflags), + extra_link_args=list2str(link_args), + build_dir=build_dir) + + log_v('write setup.py into {}'.format(file_path), verbose) + with open(file_path, 'w') as f: + f.write(content) + + +def list2str(args): + """ + Convert list[str] into string. For example: ['x', 'y'] -> "['x', 'y']" + """ + if args is None: return '[]' + assert isinstance(args, (list, tuple)) + args = ["{}".format(arg) for arg in args] + return repr(args) + + +def _jit_compile(file_path, verbose=False): + """ + Build shared library in subprocess + """ + ext_dir = os.path.dirname(file_path) + setup_file = os.path.basename(file_path) + + # Using interpreter same with current process. + interpreter = sys.executable + + try: + py_version = subprocess.check_output([interpreter, '-V']) + py_version = py_version.decode() + log_v( + "Using Python interpreter: {}, version: {}".format( + interpreter, py_version.strip()), verbose) + except Exception: + _, error, _ = sys.exc_info() + raise RuntimeError( + 'Failed to check Python interpreter with `{}`, errors: {}'.format( + interpreter, error)) + + if IS_WINDOWS: + compile_cmd = 'cd /d {} && {} {} build'.format(ext_dir, interpreter, + setup_file) + else: + compile_cmd = 'cd {} && {} {} build'.format(ext_dir, interpreter, + setup_file) + + print("Compiling user custom op, it will cost a few seconds.....") + run_cmd(compile_cmd, verbose) + + +def parse_op_name_from(sources): + """ + Parse registerring custom op name from sources. + """ + + def regex(content): + pattern = re.compile(r'PD_BUILD_OP\(([^,\)]+)\)') + content = re.sub(r'\s|\t|\n', '', content) + op_name = pattern.findall(content) + op_name = set([re.sub('_grad', '', name) for name in op_name]) + + return op_name + + op_names = set() + for source in sources: + with open(source, 'r') as f: + content = f.read() + op_names |= regex(content) + + return list(op_names) + + +def run_cmd(command, verbose=False): + """ + Execute command with subprocess. + """ + # logging + log_v("execute command: {}".format(command), verbose) + + # execute command + try: + if verbose: + return subprocess.check_call(command, + shell=True, + stderr=subprocess.STDOUT) + else: + return subprocess.check_call(command, shell=True, stdout=DEVNULL) + except Exception: + _, error, _ = sys.exc_info() + raise RuntimeError("Failed to run command: {}, errors: {}".format( + compile, error)) + + +def check_abi_compatibility(compiler, verbose=False): + """ + Check whether GCC version on user local machine is compatible with Paddle in + site-packages. + """ + if os.environ.get('PADDLE_SKIP_CHECK_ABI') in ['True', 'true', '1']: + return True + + if not IS_WINDOWS: + cmd_out = subprocess.check_output(['which', compiler], + stderr=subprocess.STDOUT) + compiler_path = os.path.realpath(cmd_out.decode()).strip() + # if not found any suitable compiler, raise warning + if not any(name in compiler_path + for name in _expected_compiler_current_platform()): + warnings.warn( + WRONG_COMPILER_WARNING.format( + user_compiler=compiler, + paddle_compiler=_expected_compiler_current_platform()[0], + platform=OS_NAME)) + return False + + version = (0, 0, 0) + # clang++ have no ABI compatibility problem + if OS_NAME.startswith('darwin'): + return True + try: + if OS_NAME.startswith('linux'): + mini_required_version = GCC_MINI_VERSION + version_info = subprocess.check_output( + [compiler, '-dumpfullversion', '-dumpversion']) + version_info = version_info.decode() + version = version_info.strip().split('.') + elif IS_WINDOWS: + mini_required_version = MSVC_MINI_VERSION + compiler_info = subprocess.check_output(compiler, + stderr=subprocess.STDOUT) + try: + compiler_info = compiler_info.decode('UTF-8') + except UnicodeDecodeError: + compiler_info = compiler_info.decode('gbk') + match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.strip()) + if match is not None: + version = match.groups() + except Exception: + # check compiler version failed + _, error, _ = sys.exc_info() + warnings.warn('Failed to check compiler version for {}: {}'.format( + compiler, error)) + return False + + # check version compatibility + assert len(version) == 3 + if tuple(map(int, version)) >= mini_required_version: + return True + warnings.warn( + ABI_INCOMPATIBILITY_WARNING.format(user_compiler=compiler, + version='.'.join(version))) + return False + + +def _expected_compiler_current_platform(): + """ + Returns supported compiler string on current platform + """ + if OS_NAME.startswith('darwin'): + expect_compilers = ['clang', 'clang++'] + elif OS_NAME.startswith('linux'): + expect_compilers = ['gcc', 'g++', 'gnu-c++', 'gnu-cc'] + elif IS_WINDOWS: + expect_compilers = ['cl'] + return expect_compilers + + +def log_v(info, verbose=True): + """ + Print log information on stdout. + """ + if verbose: + logger.info(info) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/deprecated.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..5d4a899693691736a7c6673923d92e505fffb4d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/deprecated.py @@ -0,0 +1,120 @@ +# Copyright (c) 2018 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. +""" +decorator to deprecate a function or class +""" + +import warnings +import functools +import paddle +import sys + +__all__ = [] + +# NOTE(zhiqiu): Since python 3.2, DeprecationWarning is ignored by default, +# and since python 3.7, it is once again shown by default when triggered directly by code in __main__. +# See details: https://docs.python.org/3/library/warnings.html#default-warning-filter +# The following line set DeprecationWarning to show once, which is expected to work in python 3.2 -> 3.6 +# However, doing this could introduce one samll side effect, i.e., the DeprecationWarning which is not issued by @deprecated. +# The side effect is acceptable, and we will find better way to do this if we could. +warnings.simplefilter('default', DeprecationWarning) + + +def deprecated(update_to="", since="", reason="", level=0): + """Decorate a function to signify its deprecation. + + This function wraps a method that will soon be removed and does two things: + - The docstring of the API will be modified to include a notice + about deprecation." + - Raises a :class:`~exceptions.DeprecatedWarning` when old API is called. + + Args: + since(str, optional): The version at which the decorated method is considered deprecated. + update_to(str, optional): The new API users should use. + reason(str, optional): The reason why the API is deprecated. + level(int, optional): The deprecated warning log level. It must be + an Integer and must be one of 0, 1, 2. + If `level == 0`, the warning message will not be showed. + If `level == 1`, the warning message will be showed normally. + If `level == 2`, it will raise `RuntimeError`. + + Returns: + decorator: decorated function or class. + """ + + def decorator(func): + # TODO(zhiqiu): temporally disable the warnings + return func + """construct warning message, and return a decorated function or class.""" + assert isinstance(update_to, str), 'type of "update_to" must be str.' + assert isinstance(since, str), 'type of "since" must be str.' + assert isinstance(reason, str), 'type of "reason" must be str.' + assert isinstance(level, int) and level >= 0 and level < 3, ( + 'type of "level" must be int and must be one of 0, 1, 2. But ' + 'received: {}.'.format(level)) + + _since = since.strip() + _update_to = update_to.strip() + _reason = reason.strip() + + msg = 'API "{}.{}" is deprecated'.format(func.__module__, func.__name__) + + if len(_since) > 0: + msg += " since {}".format(_since) + msg += ", and will be removed in future versions." + if len(_update_to) > 0: + assert _update_to.startswith( + "paddle." + ), 'Argument update_to must start with "paddle.", your value is "{}"'.format( + update_to) + msg += ' Please use "{}" instead.'.format(_update_to) + if len(_reason) > 0: + msg += "\nreason: {}".format(_reason) + if func.__doc__: + func.__doc__ = ('\n\nWarning: ' + msg + '\n') + func.__doc__ + + if level == 0: + return func + + @functools.wraps(func) + def wrapper(*args, **kwargs): + """deprecated warning should be fired in 3 circumstances: + 1. current version is develop version, i.e. "0.0.0", because we assume develop version is always the latest version. + 2. since version is empty, in this case, API is deprecated in all versions. + 3. current version is newer than since version. + """ + + if level == 2: + raise RuntimeError('API "{}.{}" has been deprecated.'.format( + func.__module__, func.__name__)) + + warningmsg = "\033[93m\nWarning:\n%s \033[0m" % (msg) + # ensure ANSI escape sequences print correctly in cmd and powershell + if sys.platform.lower() == 'win32': + warningmsg = "\nWarning:\n%s " % (msg) + + v_current = [int(i) for i in paddle.__version__.split(".")] + v_current += [0] * (4 - len(v_current)) + v_since = [int(i) for i in _since.split(".")] + v_since += [0] * (4 - len(v_since)) + if paddle.__version__ == "0.0.0" or _since == "" or v_current >= v_since: + warnings.warn(warningmsg, + category=DeprecationWarning, + stacklevel=2) + + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/dlpack.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/dlpack.py new file mode 100644 index 0000000000000000000000000000000000000000..1ece08daa27274f5d4b70f9c39464aaab38f5a62 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/dlpack.py @@ -0,0 +1,102 @@ +# Copyright (c) 2021 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. + +import paddle +from ..fluid.core import LoDTensor +from ..fluid.framework import _non_static_mode +from ..fluid.data_feeder import check_type, check_dtype, convert_dtype + +__all__ = [ + 'to_dlpack', + 'from_dlpack', +] + + +def to_dlpack(x): + """ + Encodes a tensor to DLPack. + + Args: + x (Tensor): The input tensor, and the data type can be `bool`, `float16`, `float32`, + `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `complex64`, + `complex128`. + + Returns: + dltensor, and the data type is PyCapsule. + + Examples: + .. code-block:: python + + import paddle + # x is a tensor with shape [2, 4] + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]]) + dlpack = paddle.utils.dlpack.to_dlpack(x) + print(dlpack) + # + """ + + if _non_static_mode(): + if not isinstance(x, (paddle.Tensor, paddle.fluid.core.eager.Tensor)): + raise TypeError( + "The type of 'x' in to_dlpack must be paddle.Tensor," + " but received {}.".format(type(x))) + + return x.value().get_tensor()._to_dlpack() + + check_type(x, 'x', (LoDTensor), 'to_dlpack') + return x._to_dlpack() + + +def from_dlpack(dlpack): + """ + Decodes a DLPack to a tensor. + + Args: + dlpack (PyCapsule): a PyCapsule object with the dltensor. + + Returns: + out (Tensor): a tensor decoded from DLPack. One thing to be noted, if we get + an input dltensor with data type as `bool`, we return the decoded + tensor as `uint8`. + + Examples: + .. code-block:: python + + import paddle + # x is a tensor with shape [2, 4] + x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9], + [0.1, 0.2, 0.6, 0.7]]) + dlpack = paddle.utils.dlpack.to_dlpack(x) + x = paddle.utils.dlpack.from_dlpack(dlpack) + print(x) + # Tensor(shape=[2, 4], dtype=float32, place=CUDAPlace(0), stop_gradient=True, + # [[0.20000000, 0.30000001, 0.50000000, 0.89999998], + # [0.10000000, 0.20000000, 0.60000002, 0.69999999]]) + """ + + t = type(dlpack) + dlpack_flag = (t.__module__ == 'builtins' and t.__name__ == 'PyCapsule') + if not dlpack_flag: + raise TypeError( + "The type of 'dlpack' in from_dlpack must be PyCapsule object," + " but received {}.".format(type(dlpack))) + + if _non_static_mode(): + out = paddle.fluid.core.from_dlpack(dlpack) + out = paddle.to_tensor(out) + return out + + out = paddle.fluid.core.from_dlpack(dlpack) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/download.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/download.py new file mode 100644 index 0000000000000000000000000000000000000000..234aac860b62a34699a61703f76e1cc66dd06c79 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/download.py @@ -0,0 +1,381 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +import os.path as osp +import shutil +import requests +import subprocess +import hashlib +import tarfile +import zipfile +import time +from collections import OrderedDict + +try: + from tqdm import tqdm +except: + + class tqdm(object): + + def __init__(self, total=None): + self.total = total + self.n = 0 + + def update(self, n): + self.n += n + if self.total is None: + sys.stderr.write("\r{0:.1f} bytes".format(self.n)) + else: + sys.stderr.write("\r{0:.1f}%".format(100 * self.n / + float(self.total))) + sys.stderr.flush() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + sys.stderr.write('\n') + + +import logging + +logger = logging.getLogger(__name__) + +__all__ = ['get_weights_path_from_url'] + +WEIGHTS_HOME = osp.expanduser("~/.cache/paddle/hapi/weights") + +DOWNLOAD_RETRY_LIMIT = 3 + + +def is_url(path): + """ + Whether path is URL. + Args: + path (string): URL string or not. + """ + return path.startswith('http://') or path.startswith('https://') + + +def get_weights_path_from_url(url, md5sum=None): + """Get weights path from WEIGHT_HOME, if not exists, + download it from url. + + Args: + url (str): download url + md5sum (str): md5 sum of download package + + Returns: + str: a local path to save downloaded weights. + + Examples: + .. code-block:: python + + from paddle.utils.download import get_weights_path_from_url + + resnet18_pretrained_weight_url = 'https://paddle-hapi.bj.bcebos.com/models/resnet18.pdparams' + local_weight_path = get_weights_path_from_url(resnet18_pretrained_weight_url) + + """ + path = get_path_from_url(url, WEIGHTS_HOME, md5sum) + return path + + +def _map_path(url, root_dir): + # parse path after download under root_dir + fname = osp.split(url)[-1] + fpath = fname + return osp.join(root_dir, fpath) + + +def _get_unique_endpoints(trainer_endpoints): + # Sorting is to avoid different environmental variables for each card + trainer_endpoints.sort() + ips = set() + unique_endpoints = set() + for endpoint in trainer_endpoints: + ip = endpoint.split(":")[0] + if ip in ips: + continue + ips.add(ip) + unique_endpoints.add(endpoint) + logger.info("unique_endpoints {}".format(unique_endpoints)) + return unique_endpoints + + +def get_path_from_url(url, + root_dir, + md5sum=None, + check_exist=True, + decompress=True, + method='get'): + """ Download from given url to root_dir. + if file or directory specified by url is exists under + root_dir, return the path directly, otherwise download + from url and decompress it, return the path. + + Args: + url (str): download url + root_dir (str): root dir for downloading, it should be + WEIGHTS_HOME or DATASET_HOME + md5sum (str): md5 sum of download package + decompress (bool): decompress zip or tar file. Default is `True` + method (str): which download method to use. Support `wget` and `get`. Default is `get`. + + Returns: + str: a local path to save downloaded models & weights & datasets. + """ + + from paddle.fluid.dygraph.parallel import ParallelEnv + + assert is_url(url), "downloading from {} not a url".format(url) + # parse path after download to decompress under root_dir + fullpath = _map_path(url, root_dir) + # Mainly used to solve the problem of downloading data from different + # machines in the case of multiple machines. Different ips will download + # data, and the same ip will only download data once. + unique_endpoints = _get_unique_endpoints(ParallelEnv().trainer_endpoints[:]) + if osp.exists(fullpath) and check_exist and _md5check(fullpath, md5sum): + logger.info("Found {}".format(fullpath)) + else: + if ParallelEnv().current_endpoint in unique_endpoints: + fullpath = _download(url, root_dir, md5sum, method=method) + else: + while not os.path.exists(fullpath): + time.sleep(1) + + if ParallelEnv().current_endpoint in unique_endpoints: + if decompress and (tarfile.is_tarfile(fullpath) + or zipfile.is_zipfile(fullpath)): + fullpath = _decompress(fullpath) + + return fullpath + + +def _get_download(url, fullname): + # using requests.get method + fname = osp.basename(fullname) + try: + req = requests.get(url, stream=True) + except Exception as e: # requests.exceptions.ConnectionError + logger.info("Downloading {} from {} failed with exception {}".format( + fname, url, str(e))) + return False + + if req.status_code != 200: + raise RuntimeError("Downloading from {} failed with code " + "{}!".format(url, req.status_code)) + + # For protecting download interupted, download to + # tmp_fullname firstly, move tmp_fullname to fullname + # after download finished + tmp_fullname = fullname + "_tmp" + total_size = req.headers.get('content-length') + with open(tmp_fullname, 'wb') as f: + if total_size: + with tqdm(total=(int(total_size) + 1023) // 1024) as pbar: + for chunk in req.iter_content(chunk_size=1024): + f.write(chunk) + pbar.update(1) + else: + for chunk in req.iter_content(chunk_size=1024): + if chunk: + f.write(chunk) + shutil.move(tmp_fullname, fullname) + + return fullname + + +def _wget_download(url, fullname): + # using wget to download url + tmp_fullname = fullname + "_tmp" + # –user-agent + command = 'wget -O {} -t {} {}'.format(tmp_fullname, DOWNLOAD_RETRY_LIMIT, + url) + subprc = subprocess.Popen(command, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + _ = subprc.communicate() + + if subprc.returncode != 0: + raise RuntimeError( + '{} failed. Please make sure `wget` is installed or {} exists'. + format(command, url)) + + shutil.move(tmp_fullname, fullname) + + return fullname + + +_download_methods = { + 'get': _get_download, + 'wget': _wget_download, +} + + +def _download(url, path, md5sum=None, method='get'): + """ + Download from url, save to path. + + url (str): download url + path (str): download to given path + md5sum (str): md5 sum of download package + method (str): which download method to use. Support `wget` and `get`. Default is `get`. + + """ + assert method in _download_methods, 'make sure `{}` implemented'.format( + method) + + if not osp.exists(path): + os.makedirs(path) + + fname = osp.split(url)[-1] + fullname = osp.join(path, fname) + retry_cnt = 0 + + logger.info("Downloading {} from {}".format(fname, url)) + while not (osp.exists(fullname) and _md5check(fullname, md5sum)): + if retry_cnt < DOWNLOAD_RETRY_LIMIT: + retry_cnt += 1 + else: + raise RuntimeError("Download from {} failed. " + "Retry limit reached".format(url)) + + if not _download_methods[method](url, fullname): + time.sleep(1) + continue + + return fullname + + +def _md5check(fullname, md5sum=None): + if md5sum is None: + return True + + logger.info("File {} md5 checking...".format(fullname)) + md5 = hashlib.md5() + with open(fullname, 'rb') as f: + for chunk in iter(lambda: f.read(4096), b""): + md5.update(chunk) + calc_md5sum = md5.hexdigest() + + if calc_md5sum != md5sum: + logger.info("File {} md5 check failed, {}(calc) != " + "{}(base)".format(fullname, calc_md5sum, md5sum)) + return False + return True + + +def _decompress(fname): + """ + Decompress for zip and tar file + """ + logger.info("Decompressing {}...".format(fname)) + + # For protecting decompressing interupted, + # decompress to fpath_tmp directory firstly, if decompress + # successed, move decompress files to fpath and delete + # fpath_tmp and remove download compress file. + + if tarfile.is_tarfile(fname): + uncompressed_path = _uncompress_file_tar(fname) + elif zipfile.is_zipfile(fname): + uncompressed_path = _uncompress_file_zip(fname) + else: + raise TypeError("Unsupport compress file type {}".format(fname)) + + return uncompressed_path + + +def _uncompress_file_zip(filepath): + with zipfile.ZipFile(filepath, 'r') as files: + file_list = files.namelist() + + file_dir = os.path.dirname(filepath) + + if _is_a_single_file(file_list): + rootpath = file_list[0] + uncompressed_path = os.path.join(file_dir, rootpath) + files.extractall(file_dir) + + elif _is_a_single_dir(file_list): + # `strip(os.sep)` to remove `os.sep` in the tail of path + rootpath = os.path.splitext(file_list[0].strip(os.sep))[0].split( + os.sep)[-1] + uncompressed_path = os.path.join(file_dir, rootpath) + + files.extractall(file_dir) + else: + rootpath = os.path.splitext(filepath)[0].split(os.sep)[-1] + uncompressed_path = os.path.join(file_dir, rootpath) + if not os.path.exists(uncompressed_path): + os.makedirs(uncompressed_path) + files.extractall(os.path.join(file_dir, rootpath)) + + return uncompressed_path + + +def _uncompress_file_tar(filepath, mode="r:*"): + with tarfile.open(filepath, mode) as files: + file_list = files.getnames() + + file_dir = os.path.dirname(filepath) + + if _is_a_single_file(file_list): + rootpath = file_list[0] + uncompressed_path = os.path.join(file_dir, rootpath) + files.extractall(file_dir) + elif _is_a_single_dir(file_list): + rootpath = os.path.splitext(file_list[0].strip(os.sep))[0].split( + os.sep)[-1] + uncompressed_path = os.path.join(file_dir, rootpath) + files.extractall(file_dir) + else: + rootpath = os.path.splitext(filepath)[0].split(os.sep)[-1] + uncompressed_path = os.path.join(file_dir, rootpath) + if not os.path.exists(uncompressed_path): + os.makedirs(uncompressed_path) + + files.extractall(os.path.join(file_dir, rootpath)) + + return uncompressed_path + + +def _is_a_single_file(file_list): + if len(file_list) == 1 and file_list[0].find(os.sep) < 0: + return True + return False + + +def _is_a_single_dir(file_list): + new_file_list = [] + for file_path in file_list: + if '/' in file_path: + file_path = file_path.replace('/', os.sep) + elif '\\' in file_path: + file_path = file_path.replace('\\', os.sep) + new_file_list.append(file_path) + + file_name = new_file_list[0].split(os.sep)[0] + for i in range(1, len(new_file_list)): + if file_name != new_file_list[i].split(os.sep)[0]: + return False + return True diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcbf5abb81b26c10f619674bd895453ec37bd04 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/__init__.py @@ -0,0 +1,33 @@ +# Copyright (c) 2016, Serge Guelton +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# Neither the name of HPCProject, Serge Guelton nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# NOTE(paddle-dev): We introduce third-party library Gast as unified AST +# representation. See https://github.com/serge-sans-paille/gast for details. + +from .gast import * +from ast import NodeVisitor, NodeTransformer, iter_fields, dump diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/ast3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/ast3.py new file mode 100644 index 0000000000000000000000000000000000000000..4696c1ba497491a9a926b5b5b9750a9b6e704b5d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/ast3.py @@ -0,0 +1,467 @@ +# Copyright (c) 2016, Serge Guelton +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# Neither the name of HPCProject, Serge Guelton nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# NOTE(paddle-dev): We introduce third-party library Gast as unified AST +# representation. See https://github.com/serge-sans-paille/gast for details. + +from .astn import AstToGAst, GAstToAst +from . import gast +import ast +import sys + + +class Ast3ToGAst(AstToGAst): + if sys.version_info.minor < 9: + + def visit_ExtSlice(self, node): + new_node = gast.Tuple(self._visit(node.dims), gast.Load()) + gast.copy_location(new_node, node) + return new_node + + def visit_Index(self, node): + return self._visit(node.value) + + if sys.version_info.minor < 8: + + def visit_Module(self, node): + new_node = gast.Module( + self._visit(node.body), + [] # type_ignores + ) + return new_node + + def visit_Num(self, node): + new_node = gast.Constant( + node.n, + None, + ) + gast.copy_location(new_node, node) + return new_node + + def visit_Ellipsis(self, node): + new_node = gast.Constant( + Ellipsis, + None, + ) + gast.copy_location(new_node, node) + new_node.end_lineno = new_node.end_col_offset = None + return new_node + + def visit_Str(self, node): + new_node = gast.Constant( + node.s, + None, + ) + gast.copy_location(new_node, node) + return new_node + + def visit_Bytes(self, node): + new_node = gast.Constant( + node.s, + None, + ) + gast.copy_location(new_node, node) + return new_node + + def visit_FunctionDef(self, node): + new_node = gast.FunctionDef( + self._visit(node.name), + self._visit(node.args), + self._visit(node.body), + self._visit(node.decorator_list), + self._visit(node.returns), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_AsyncFunctionDef(self, node): + new_node = gast.AsyncFunctionDef( + self._visit(node.name), + self._visit(node.args), + self._visit(node.body), + self._visit(node.decorator_list), + self._visit(node.returns), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_For(self, node): + new_node = gast.For( + self._visit(node.target), + self._visit(node.iter), + self._visit(node.body), + self._visit(node.orelse), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_AsyncFor(self, node): + new_node = gast.AsyncFor( + self._visit(node.target), + self._visit(node.iter), + self._visit(node.body), + self._visit(node.orelse), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_With(self, node): + new_node = gast.With( + self._visit(node.items), + self._visit(node.body), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_AsyncWith(self, node): + new_node = gast.AsyncWith( + self._visit(node.items), + self._visit(node.body), + None, # type_comment + ) + gast.copy_location(new_node, node) + return new_node + + def visit_Call(self, node): + if sys.version_info.minor < 5: + if node.starargs: + star = gast.Starred(self._visit(node.starargs), gast.Load()) + gast.copy_location(star, node) + starred = [star] + else: + starred = [] + + if node.kwargs: + kw = gast.keyword(None, self._visit(node.kwargs)) + gast.copy_location(kw, node.kwargs) + kwargs = [kw] + else: + kwargs = [] + else: + starred = kwargs = [] + + new_node = gast.Call( + self._visit(node.func), + self._visit(node.args) + starred, + self._visit(node.keywords) + kwargs, + ) + gast.copy_location(new_node, node) + return new_node + + def visit_NameConstant(self, node): + if node.value is None: + new_node = gast.Constant(None, None) + elif node.value is True: + new_node = gast.Constant(True, None) + elif node.value is False: + new_node = gast.Constant(False, None) + gast.copy_location(new_node, node) + return new_node + + def visit_arguments(self, node): + new_node = gast.arguments( + self._visit(node.args), + [], # posonlyargs + self._visit(node.vararg), + self._visit(node.kwonlyargs), + self._visit(node.kw_defaults), + self._visit(node.kwarg), + self._visit(node.defaults), + ) + gast.copy_location(new_node, node) + return new_node + + def visit_Name(self, node): + new_node = gast.Name( + self._visit(node.id), + self._visit(node.ctx), + None, + None, + ) + ast.copy_location(new_node, node) + return new_node + + def visit_arg(self, node): + if sys.version_info.minor < 8: + extra_args = [None] + else: + extra_args = [self._visit(node.type_comment)] + + new_node = gast.Name( + self._visit(node.arg), + gast.Param(), + self._visit(node.annotation), + *extra_args # type_comment + ) + ast.copy_location(new_node, node) + return new_node + + def visit_ExceptHandler(self, node): + if node.name: + new_node = gast.ExceptHandler( + self._visit(node.type), + gast.Name(node.name, gast.Store(), None, None), + self._visit(node.body)) + ast.copy_location(new_node, node) + return new_node + else: + return self.generic_visit(node) + + if sys.version_info.minor < 6: + + def visit_comprehension(self, node): + new_node = gast.comprehension( + target=self._visit(node.target), + iter=self._visit(node.iter), + ifs=self._visit(node.ifs), + is_async=0, + ) + return ast.copy_location(new_node, node) + + +class GAstToAst3(GAstToAst): + if sys.version_info.minor < 9: + + def visit_Subscript(self, node): + + def adjust_slice(s): + if isinstance(s, ast.Slice): + return s + else: + return ast.Index(s) + + if isinstance(node.slice, gast.Tuple): + if any(isinstance(elt, gast.slice) for elt in node.slice.elts): + new_slice = ast.ExtSlice( + [adjust_slice(x) for x in self._visit(node.slice.elts)]) + else: + value = ast.Tuple(self._visit(node.slice.elts), ast.Load()) + ast.copy_location(value, node.slice) + new_slice = ast.Index(value) + else: + new_slice = adjust_slice(self._visit(node.slice)) + ast.copy_location(new_slice, node.slice) + + new_node = ast.Subscript( + self._visit(node.value), + new_slice, + self._visit(node.ctx), + ) + ast.copy_location(new_node, node) + return new_node + + if sys.version_info.minor < 8: + + def visit_Module(self, node): + new_node = ast.Module(self._visit(node.body)) + return new_node + + def visit_Constant(self, node): + if node.value is None: + new_node = ast.NameConstant(node.value) + elif node.value is Ellipsis: + new_node = ast.Ellipsis() + elif isinstance(node.value, bool): + new_node = ast.NameConstant(node.value) + elif isinstance(node.value, (int, float, complex)): + new_node = ast.Num(node.value) + elif isinstance(node.value, str): + new_node = ast.Str(node.value) + else: + new_node = ast.Bytes(node.value) + ast.copy_location(new_node, node) + return new_node + + def _make_arg(self, node): + if node is None: + return None + + if sys.version_info.minor < 8: + extra_args = tuple() + else: + extra_args = self._visit(node.type_comment), + + new_node = ast.arg(self._visit(node.id), self._visit(node.annotation), + *extra_args) + return ast.copy_location(new_node, node) + + def visit_Name(self, node): + new_node = ast.Name( + self._visit(node.id), + self._visit(node.ctx), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_ExceptHandler(self, node): + if node.name: + new_node = ast.ExceptHandler(self._visit(node.type), node.name.id, + self._visit(node.body)) + return ast.copy_location(new_node, node) + else: + return self.generic_visit(node) + + if sys.version_info.minor < 5: + + def visit_Call(self, node): + if node.args and isinstance(node.args[-1], gast.Starred): + args = node.args[:-1] + starargs = node.args[-1].value + else: + args = node.args + starargs = None + + if node.keywords and node.keywords[-1].arg is None: + keywords = node.keywords[:-1] + kwargs = node.keywords[-1].value + else: + keywords = node.keywords + kwargs = None + + new_node = ast.Call( + self._visit(node.func), + self._visit(args), + self._visit(keywords), + self._visit(starargs), + self._visit(kwargs), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_ClassDef(self, node): + self.generic_visit(node) + new_node = ast.ClassDef( + name=self._visit(node.name), + bases=self._visit(node.bases), + keywords=self._visit(node.keywords), + body=self._visit(node.body), + decorator_list=self._visit(node.decorator_list), + starargs=None, + kwargs=None, + ) + return ast.copy_location(new_node, node) + + elif sys.version_info.minor < 8: + + def visit_FunctionDef(self, node): + new_node = ast.FunctionDef( + self._visit(node.name), + self._visit(node.args), + self._visit(node.body), + self._visit(node.decorator_list), + self._visit(node.returns), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_AsyncFunctionDef(self, node): + new_node = ast.AsyncFunctionDef( + self._visit(node.name), + self._visit(node.args), + self._visit(node.body), + self._visit(node.decorator_list), + self._visit(node.returns), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_For(self, node): + new_node = ast.For( + self._visit(node.target), + self._visit(node.iter), + self._visit(node.body), + self._visit(node.orelse), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_AsyncFor(self, node): + new_node = ast.AsyncFor( + self._visit(node.target), + self._visit(node.iter), + self._visit(node.body), + self._visit(node.orelse), + None, # type_comment + ) + ast.copy_location(new_node, node) + return new_node + + def visit_With(self, node): + new_node = ast.With( + self._visit(node.items), + self._visit(node.body), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_AsyncWith(self, node): + new_node = ast.AsyncWith( + self._visit(node.items), + self._visit(node.body), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_Call(self, node): + new_node = ast.Call( + self._visit(node.func), + self._visit(node.args), + self._visit(node.keywords), + ) + ast.copy_location(new_node, node) + return new_node + + def visit_arguments(self, node): + extra_args = [ + self._make_arg(node.vararg), + [self._make_arg(n) for n in node.kwonlyargs], + self._visit(node.kw_defaults), + self._make_arg(node.kwarg), + self._visit(node.defaults), + ] + if sys.version_info.minor >= 8: + new_node = ast.arguments( + [self._make_arg(arg) for arg in node.posonlyargs], + [self._make_arg(n) for n in node.args], *extra_args) + else: + new_node = ast.arguments([self._make_arg(n) for n in node.args], + *extra_args) + return new_node + + +def ast_to_gast(node): + return Ast3ToGAst().visit(node) + + +def gast_to_ast(node): + return GAstToAst3().visit(node) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/astn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/astn.py new file mode 100644 index 0000000000000000000000000000000000000000..eb45bd4e4500a6e5a0e54b1ceb7e3b797d2c68f6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/astn.py @@ -0,0 +1,66 @@ +# Copyright (c) 2016, Serge Guelton +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# Neither the name of HPCProject, Serge Guelton nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# NOTE(paddle-dev): We introduce third-party library Gast as unified AST +# representation. See https://github.com/serge-sans-paille/gast for details. + +import ast +from . import gast + + +def _generate_translators(to): + + class Translator(ast.NodeTransformer): + + def _visit(self, node): + if isinstance(node, list): + return [self._visit(n) for n in node] + elif isinstance(node, ast.AST): + return self.visit(node) + else: + return node + + def generic_visit(self, node): + cls = type(node).__name__ + # handle nodes that are not part of the AST + if not hasattr(to, cls): + return + new_node = getattr(to, cls)() + for field in node._fields: + setattr(new_node, field, self._visit(getattr(node, field))) + for attr in getattr(node, '_attributes'): + if hasattr(node, attr): + setattr(new_node, attr, getattr(node, attr)) + return new_node + + return Translator + + +AstToGAst = _generate_translators(gast) + +GAstToAst = _generate_translators(ast) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/gast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/gast.py new file mode 100644 index 0000000000000000000000000000000000000000..1248434fe3533124cea74bc5b2a9c78567467595 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/gast/gast.py @@ -0,0 +1,698 @@ +# Copyright (c) 2016, Serge Guelton +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. + +# Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# Neither the name of HPCProject, Serge Guelton nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# NOTE(paddle-dev): We introduce third-party library Gast as unified AST +# representation. See https://github.com/serge-sans-paille/gast for details. + +import sys as _sys +import ast as _ast +from ast import boolop, cmpop, excepthandler, expr, expr_context, operator +from ast import slice, stmt, unaryop, mod, AST +from ast import iter_child_nodes, walk + +try: + from ast import TypeIgnore +except ImportError: + + class TypeIgnore(AST): + pass + + +def _make_node(Name, Fields, Attributes, Bases): + + def create_node(self, *args, **kwargs): + nbparam = len(args) + len(kwargs) + assert nbparam in (0, len(Fields)), \ + "Bad argument number for {}: {}, expecting {}".\ + format(Name, nbparam, len(Fields)) + self._fields = Fields + self._attributes = Attributes + for argname, argval in zip(self._fields, args): + setattr(self, argname, argval) + for argname, argval in kwargs.items(): + assert argname in Fields, \ + "Invalid Keyword argument for {}: {}".format(Name, argname) + setattr(self, argname, argval) + + setattr(_sys.modules[__name__], Name, + type(Name, Bases, {'__init__': create_node})) + + +_nodes = ( + # mod + ('Module', (('body', 'type_ignores'), (), (mod, ))), + ('Interactive', (('body', ), (), (mod, ))), + ('Expression', (('body', ), (), (mod, ))), + ('FunctionType', (('argtypes', 'returns'), (), (mod, ))), + ('Suite', (('body', ), (), (mod, ))), + + # stmt + ('FunctionDef', (('name', 'args', 'body', 'decorator_list', 'returns', + 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('AsyncFunctionDef', (('name', 'args', 'body', 'decorator_list', 'returns', + 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('ClassDef', (( + 'name', + 'bases', + 'keywords', + 'body', + 'decorator_list', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Return', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Delete', (('targets', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Assign', (( + 'targets', + 'value', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('AugAssign', (( + 'target', + 'op', + 'value', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('AnnAssign', (( + 'target', + 'annotation', + 'value', + 'simple', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Print', (( + 'dest', + 'values', + 'nl', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('For', (('target', 'iter', 'body', 'orelse', 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('AsyncFor', (('target', 'iter', 'body', 'orelse', 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('While', (( + 'test', + 'body', + 'orelse', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('If', (( + 'test', + 'body', + 'orelse', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('With', (('items', 'body', 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('AsyncWith', (('items', 'body', 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Raise', (( + 'exc', + 'cause', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Try', (( + 'body', + 'handlers', + 'orelse', + 'finalbody', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Assert', (( + 'test', + 'msg', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Import', (('names', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('ImportFrom', (( + 'module', + 'names', + 'level', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Exec', (( + 'body', + 'globals', + 'locals', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Global', (('names', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Nonlocal', (('names', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Expr', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Pass', ((), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Break', ((), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + ('Continue', ((), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (stmt, ))), + + # expr + ('BoolOp', (( + 'op', + 'values', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('BinOp', (( + 'left', + 'op', + 'right', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('UnaryOp', (( + 'op', + 'operand', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Lambda', (( + 'args', + 'body', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('IfExp', (( + 'test', + 'body', + 'orelse', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Dict', (( + 'keys', + 'values', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Set', (('elts', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('ListComp', (( + 'elt', + 'generators', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('SetComp', (( + 'elt', + 'generators', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('DictComp', (( + 'key', + 'value', + 'generators', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('GeneratorExp', (( + 'elt', + 'generators', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Await', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Yield', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('YieldFrom', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Compare', (( + 'left', + 'ops', + 'comparators', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Call', (( + 'func', + 'args', + 'keywords', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Repr', (('value', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('FormattedValue', (( + 'value', + 'conversion', + 'format_spec', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('JoinedStr', (('values', ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Constant', (('value', 'kind'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Attribute', (( + 'value', + 'attr', + 'ctx', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Subscript', (( + 'value', + 'slice', + 'ctx', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Starred', (( + 'value', + 'ctx', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Name', (('id', 'ctx', 'annotation', 'type_comment'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('List', (( + 'elts', + 'ctx', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + ('Tuple', (( + 'elts', + 'ctx', + ), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (expr, ))), + + # expr_context + ('Load', ((), (), (expr_context, ))), + ('Store', ((), (), (expr_context, ))), + ('Del', ((), (), (expr_context, ))), + ('AugLoad', ((), (), (expr_context, ))), + ('AugStore', ((), (), (expr_context, ))), + ('Param', ((), (), (expr_context, ))), + + # slice + ('Slice', (('lower', 'upper', 'step'), ( + 'lineno', + 'col_offset', + 'end_lineno', + 'end_col_offset', + ), (slice, ))), + + # boolop + ('And', ((), (), (boolop, ))), + ('Or', ((), (), (boolop, ))), + + # operator + ('Add', ((), (), (operator, ))), + ('Sub', ((), (), (operator, ))), + ('Mult', ((), (), (operator, ))), + ('MatMult', ((), (), (operator, ))), + ('Div', ((), (), (operator, ))), + ('Mod', ((), (), (operator, ))), + ('Pow', ((), (), (operator, ))), + ('LShift', ((), (), (operator, ))), + ('RShift', ((), (), (operator, ))), + ('BitOr', ((), (), (operator, ))), + ('BitXor', ((), (), (operator, ))), + ('BitAnd', ((), (), (operator, ))), + ('FloorDiv', ((), (), (operator, ))), + + # unaryop + ('Invert', ((), (), ( + unaryop, + AST, + ))), + ('Not', ((), (), ( + unaryop, + AST, + ))), + ('UAdd', ((), (), ( + unaryop, + AST, + ))), + ('USub', ((), (), ( + unaryop, + AST, + ))), + + # cmpop + ('Eq', ((), (), (cmpop, ))), + ('NotEq', ((), (), (cmpop, ))), + ('Lt', ((), (), (cmpop, ))), + ('LtE', ((), (), (cmpop, ))), + ('Gt', ((), (), (cmpop, ))), + ('GtE', ((), (), (cmpop, ))), + ('Is', ((), (), (cmpop, ))), + ('IsNot', ((), (), (cmpop, ))), + ('In', ((), (), (cmpop, ))), + ('NotIn', ((), (), (cmpop, ))), + + # comprehension + ('comprehension', (('target', 'iter', 'ifs', 'is_async'), (), (AST, ))), + + # excepthandler + ('ExceptHandler', (('type', 'name', 'body'), + ('lineno', 'col_offset', 'end_lineno', + 'end_col_offset'), (excepthandler, ))), + + # arguments + ('arguments', (('args', 'posonlyargs', 'vararg', 'kwonlyargs', + 'kw_defaults', 'kwarg', 'defaults'), (), (AST, ))), + + # keyword + ('keyword', (('arg', 'value'), ('lineno', 'col_offset', 'end_lineno', + 'end_col_offset'), (AST, ))), + + # alias + ('alias', (('name', 'asname'), (), (AST, ))), + + # withitem + ('withitem', (('context_expr', 'optional_vars'), (), (AST, ))), + + # type_ignore + ('type_ignore', ((), ('lineno', 'tag'), (TypeIgnore, ))), +) + +for name, descr in _nodes: + _make_node(name, *descr) + +py_version = _sys.version_info.major +if py_version != 3: + raise RuntimeError( + 'Required Python version >= 3, but received Python version == {}'. + format(py_version)) + +from .ast3 import ast_to_gast, gast_to_ast + + +def parse(*args, **kwargs): + return ast_to_gast(_ast.parse(*args, **kwargs)) + + +def literal_eval(node_or_string): + if isinstance(node_or_string, AST): + node_or_string = gast_to_ast(node_or_string) + return _ast.literal_eval(node_or_string) + + +def get_docstring(node, clean=True): + if not isinstance(node, (FunctionDef, ClassDef, Module)): + raise TypeError("%r can't have docstrings" % node.__class__.__name__) + if node.body and isinstance(node.body[0], Expr) and \ + isinstance(node.body[0].value, Constant): + if clean: + import inspect + holder = node.body[0].value + return inspect.cleandoc(getattr(holder, holder._fields[0])) + return node.body[0].value.s + + +# the following are directly imported from python3.8's Lib/ast.py # + + +def copy_location(new_node, old_node): + """ + Copy source location (`lineno`, `col_offset`, `end_lineno`, and + `end_col_offset` attributes) from *old_node* to *new_node* if possible, + and return *new_node*. + """ + for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset': + if attr in old_node._attributes and attr in new_node._attributes \ + and hasattr(old_node, attr): + setattr(new_node, attr, getattr(old_node, attr)) + return new_node + + +def fix_missing_locations(node): + """ + When you compile a node tree with compile(), the compiler expects lineno + and col_offset attributes for every node that supports them. This is + rather tedious to fill in for generated nodes, so this helper adds these + attributes recursively where not already set, by setting them to the values + of the parent node. It works recursively starting at *node*. + """ + + def _fix(node, lineno, col_offset, end_lineno, end_col_offset): + if 'lineno' in node._attributes: + if not hasattr(node, 'lineno'): + node.lineno = lineno + else: + lineno = node.lineno + if 'end_lineno' in node._attributes: + if not hasattr(node, 'end_lineno'): + node.end_lineno = end_lineno + else: + end_lineno = node.end_lineno + if 'col_offset' in node._attributes: + if not hasattr(node, 'col_offset'): + node.col_offset = col_offset + else: + col_offset = node.col_offset + if 'end_col_offset' in node._attributes: + if not hasattr(node, 'end_col_offset'): + node.end_col_offset = end_col_offset + else: + end_col_offset = node.end_col_offset + for child in iter_child_nodes(node): + _fix(child, lineno, col_offset, end_lineno, end_col_offset) + + _fix(node, 1, 0, 1, 0) + return node + + +def increment_lineno(node, n=1): + """ + Increment the line number and end line number of each node in the tree + starting at *node* by *n*. This is useful to "move code" to a different + location in a file. + """ + for child in walk(node): + if 'lineno' in child._attributes: + child.lineno = (getattr(child, 'lineno', 0) or 0) + n + if 'end_lineno' in child._attributes: + child.end_lineno = (getattr(child, 'end_lineno', 0) or 0) + n + return node diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/image_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/image_util.py new file mode 100644 index 0000000000000000000000000000000000000000..9c93d44eeecb03a4d7c76b85510cf542191139f7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/image_util.py @@ -0,0 +1,226 @@ +# 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. + +import numpy as np +from PIL import Image +from six.moves import cStringIO as StringIO + +__all__ = [] + + +def resize_image(img, target_size): + """ + Resize an image so that the shorter edge has length target_size. + img: the input image to be resized. + target_size: the target resized image size. + """ + percent = (target_size / float(min(img.size[0], img.size[1]))) + resized_size = int(round(img.size[0] * percent)), int( + round(img.size[1] * percent)) + img = img.resize(resized_size, Image.ANTIALIAS) + return img + + +def flip(im): + """ + Return the flipped image. + Flip an image along the horizontal direction. + im: input image, (K x H x W) ndarrays + """ + if len(im.shape) == 3: + return im[:, :, ::-1] + else: + return im[:, ::-1] + + +def crop_img(im, inner_size, color=True, test=True): + """ + Return cropped image. + The size of the cropped image is inner_size * inner_size. + im: (K x H x W) ndarrays + inner_size: the cropped image size. + color: whether it is color image. + test: whether in test mode. + If False, does random cropping and flipping. + If True, crop the center of images. + """ + if color: + height, width = max(inner_size, + im.shape[1]), max(inner_size, im.shape[2]) + padded_im = np.zeros((3, height, width)) + startY = (height - im.shape[1]) / 2 + startX = (width - im.shape[2]) / 2 + endY, endX = startY + im.shape[1], startX + im.shape[2] + padded_im[:, startY:endY, startX:endX] = im + else: + im = im.astype('float32') + height, width = max(inner_size, + im.shape[0]), max(inner_size, im.shape[1]) + padded_im = np.zeros((height, width)) + startY = (height - im.shape[0]) / 2 + startX = (width - im.shape[1]) / 2 + endY, endX = startY + im.shape[0], startX + im.shape[1] + padded_im[startY:endY, startX:endX] = im + if test: + startY = (height - inner_size) / 2 + startX = (width - inner_size) / 2 + else: + startY = np.random.randint(0, height - inner_size + 1) + startX = np.random.randint(0, width - inner_size + 1) + endY, endX = startY + inner_size, startX + inner_size + if color: + pic = padded_im[:, startY:endY, startX:endX] + else: + pic = padded_im[startY:endY, startX:endX] + if (not test) and (np.random.randint(2) == 0): + pic = flip(pic) + return pic + + +def decode_jpeg(jpeg_string): + np_array = np.array(Image.open(StringIO(jpeg_string))) + if len(np_array.shape) == 3: + np_array = np.transpose(np_array, (2, 0, 1)) + return np_array + + +def preprocess_img(im, img_mean, crop_size, is_train, color=True): + """ + Does data augmentation for images. + If is_train is false, cropping the center region from the image. + If is_train is true, randomly crop a region from the image, + and random does flipping. + im: (K x H x W) ndarrays + """ + im = im.astype('float32') + test = not is_train + pic = crop_img(im, crop_size, color, test) + pic -= img_mean + return pic.flatten() + + +def load_meta(meta_path, mean_img_size, crop_size, color=True): + """ + Return the loaded meta file. + Load the meta image, which is the mean of the images in the dataset. + The mean image is subtracted from every input image so that the expected mean + of each input image is zero. + """ + mean = np.load(meta_path)['data_mean'] + border = (mean_img_size - crop_size) / 2 + if color: + assert (mean_img_size * mean_img_size * 3 == mean.shape[0]) + mean = mean.reshape(3, mean_img_size, mean_img_size) + mean = mean[:, border:border + crop_size, + border:border + crop_size].astype('float32') + else: + assert (mean_img_size * mean_img_size == mean.shape[0]) + mean = mean.reshape(mean_img_size, mean_img_size) + mean = mean[border:border + crop_size, + border:border + crop_size].astype('float32') + return mean + + +def load_image(img_path, is_color=True): + """ + Load image and return. + img_path: image path. + is_color: is color image or not. + """ + img = Image.open(img_path) + img.load() + return img + + +def oversample(img, crop_dims): + """ + image : iterable of (H x W x K) ndarrays + crop_dims: (height, width) tuple for the crops. + Returned data contains ten crops of input image, namely, + four corner patches and the center patch as well as their + horizontal reflections. + """ + # Dimensions and center. + im_shape = np.array(img[0].shape) + crop_dims = np.array(crop_dims) + im_center = im_shape[:2] / 2.0 + + # Make crop coordinates + h_indices = (0, im_shape[0] - crop_dims[0]) + w_indices = (0, im_shape[1] - crop_dims[1]) + crops_ix = np.empty((5, 4), dtype=int) + curr = 0 + for i in h_indices: + for j in w_indices: + crops_ix[curr] = (i, j, i + crop_dims[0], j + crop_dims[1]) + curr += 1 + crops_ix[4] = np.tile(im_center, (1, 2)) + np.concatenate( + [-crop_dims / 2.0, crop_dims / 2.0]) + crops_ix = np.tile(crops_ix, (2, 1)) + + # Extract crops + crops = np.empty((10 * len(img), crop_dims[0], crop_dims[1], im_shape[-1]), + dtype=np.float32) + ix = 0 + for im in img: + for crop in crops_ix: + crops[ix] = im[crop[0]:crop[2], crop[1]:crop[3], :] + ix += 1 + crops[ix - 5:ix] = crops[ix - 5:ix, :, ::-1, :] # flip for mirrors + return crops + + +class ImageTransformer: + + def __init__(self, + transpose=None, + channel_swap=None, + mean=None, + is_color=True): + self.is_color = is_color + self.set_transpose(transpose) + self.set_channel_swap(channel_swap) + self.set_mean(mean) + + def set_transpose(self, order): + if order is not None: + if self.is_color: + assert 3 == len(order) + self.transpose = order + + def set_channel_swap(self, order): + if order is not None: + if self.is_color: + assert 3 == len(order) + self.channel_swap = order + + def set_mean(self, mean): + if mean is not None: + # mean value, may be one value per channel + if mean.ndim == 1: + mean = mean[:, np.newaxis, np.newaxis] + else: + # elementwise mean + if self.is_color: + assert len(mean.shape) == 3 + self.mean = mean + + def transformer(self, data): + if self.transpose is not None: + data = data.transpose(self.transpose) + if self.channel_swap is not None: + data = data[self.channel_swap, :, :] + if self.mean is not None: + data -= self.mean + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/install_check.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/install_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f0636e9a1016640d6b063b0243c3a53481afc2ea --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/install_check.py @@ -0,0 +1,292 @@ +# 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. + +from __future__ import absolute_import + +import os +import logging +import numpy as np + +import paddle + +__all__ = [] + + +def _simple_network(): + """ + Define a simple network composed by a single linear layer. + """ + input = paddle.static.data(name="input", + shape=[None, 2, 2], + dtype="float32") + weight = paddle.create_parameter( + shape=[2, 3], + dtype="float32", + attr=paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(0.1))) + bias = paddle.create_parameter(shape=[3], dtype="float32") + linear_out = paddle.nn.functional.linear(x=input, weight=weight, bias=bias) + out = paddle.tensor.sum(linear_out) + return input, out, weight + + +def _prepare_data(device_count): + """ + Prepare feeding data for simple network. The shape is [device_count, 2, 2]. + + Args: + device_count (int): The number of devices. + """ + # Prepare the feeding data. + np_input_single = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + if device_count == 1: + return np_input_single.reshape(device_count, 2, 2) + else: + input_list = [] + for i in range(device_count): + input_list.append(np_input_single) + np_input_muti = np.array(input_list) + np_input_muti = np_input_muti.reshape(device_count, 2, 2) + return np_input_muti + + +def _is_cuda_available(): + """ + Check whether CUDA is avaiable. + """ + try: + assert len(paddle.static.cuda_places()) > 0 + return True + except Exception as e: + logging.warning( + "You are using GPU version PaddlePaddle, but there is no GPU " + "detected on your machine. Maybe CUDA devices is not set properly." + "\n Original Error is {}".format(e)) + return False + + +def _is_npu_available(): + """ + Check whether NPU is avaiable. + """ + try: + assert len(paddle.static.npu_places()) > 0 + return True + except Exception as e: + logging.warning( + "You are using NPU version PaddlePaddle, but there is no NPU " + "detected on your machine. Maybe NPU devices is not set properly." + "\n Original Error is {}".format(e)) + return False + + +def _is_xpu_available(): + """ + Check whether XPU is avaiable. + """ + try: + assert len(paddle.static.xpu_places()) > 0 + return True + except Exception as e: + logging.warning( + "You are using XPU version PaddlePaddle, but there is no XPU " + "detected on your machine. Maybe XPU devices is not set properly." + "\n Original Error is {}".format(e)) + return False + + +def _run_dygraph_single(use_cuda, use_xpu, use_npu): + """ + Testing the simple network in dygraph mode using one CPU/GPU/XPU/NPU. + + Args: + use_cuda (bool): Whether running with CUDA. + use_xpu (bool): Whether running with XPU. + use_npu (bool): Whether running with NPU. + """ + paddle.disable_static() + if use_cuda: + paddle.set_device('gpu') + elif use_xpu: + paddle.set_device('xpu') + elif use_npu: + paddle.set_device('npu') + else: + paddle.set_device('cpu') + weight_attr = paddle.ParamAttr( + name="weight", initializer=paddle.nn.initializer.Constant(value=0.5)) + bias_attr = paddle.ParamAttr( + name="bias", initializer=paddle.nn.initializer.Constant(value=1.0)) + linear = paddle.nn.Linear(2, + 4, + weight_attr=weight_attr, + bias_attr=bias_attr) + input_np = _prepare_data(1) + input_tensor = paddle.to_tensor(input_np) + linear_out = linear(input_tensor) + out = paddle.tensor.sum(linear_out) + out.backward() + opt = paddle.optimizer.Adam(learning_rate=0.001, + parameters=linear.parameters()) + opt.step() + + +def _run_static_single(use_cuda, use_xpu, use_npu): + """ + Testing the simple network with executor running directly, using one CPU/GPU/XPU/NPU. + + Args: + use_cuda (bool): Whether running with CUDA. + use_xpu (bool): Whether running with XPU. + use_npu (bool): Whether running with NPU. + """ + paddle.enable_static() + with paddle.static.scope_guard(paddle.static.Scope()): + train_prog = paddle.static.Program() + startup_prog = paddle.static.Program() + startup_prog.random_seed = 1 + with paddle.static.program_guard(train_prog, startup_prog): + input, out, weight = _simple_network() + param_grads = paddle.static.append_backward( + out, parameter_list=[weight.name])[0] + + if use_cuda: + place = paddle.CUDAPlace(0) + elif use_xpu: + place = paddle.XPUPlace(0) + elif use_npu: + place = paddle.NPUPlace(0) + else: + place = paddle.CPUPlace() + + exe = paddle.static.Executor(place) + exe.run(startup_prog) + exe.run(train_prog, + feed={input.name: _prepare_data(1)}, + fetch_list=[out.name, param_grads[1].name]) + paddle.disable_static() + + +def _run_static_parallel(use_cuda, use_xpu, use_npu, device_list): + """ + Testing the simple network in data parallel mode, using multiple CPU/GPU. + + Args: + use_cuda (bool): Whether running with CUDA. + use_xpu (bool): Whether running with XPU. + use_npu (bool): Whether running with NPU. + device_list (int): The specified devices. + """ + paddle.enable_static() + with paddle.static.scope_guard(paddle.static.Scope()): + train_prog = paddle.static.Program() + startup_prog = paddle.static.Program() + with paddle.static.program_guard(train_prog, startup_prog): + input, out, _ = _simple_network() + loss = paddle.tensor.mean(out) + loss.persistable = True + paddle.optimizer.SGD(learning_rate=0.01).minimize(loss) + + compiled_prog = paddle.static.CompiledProgram( + train_prog).with_data_parallel(loss_name=loss.name, + places=device_list) + + if use_cuda: + place = paddle.CUDAPlace(0) + elif use_xpu: + place = paddle.XPUPlace(0) + compiled_prog = train_prog + elif use_npu: + place = paddle.NPUPlace(0) + compiled_prog = train_prog + else: + place = paddle.CPUPlace() + + exe = paddle.static.Executor(place) + exe.run(startup_prog) + exe.run(compiled_prog, + feed={input.name: _prepare_data(len(device_list))}, + fetch_list=[loss.name]) + paddle.disable_static() + + +def run_check(): + """ + Check whether PaddlePaddle is installed correctly and running successfully + on your system. + + Examples: + .. code-block:: python + + import paddle + + paddle.utils.run_check() + # Running verify PaddlePaddle program ... + # W1010 07:21:14.972093 8321 device_context.cc:338] Please NOTE: device: 0, CUDA Capability: 70, Driver API Version: 11.0, Runtime API Version: 10.1 + # W1010 07:21:14.979770 8321 device_context.cc:346] device: 0, cuDNN Version: 7.6. + # PaddlePaddle works well on 1 GPU. + # PaddlePaddle works well on 8 GPUs. + # PaddlePaddle is installed successfully! Let's start deep learning with PaddlePaddle now. + """ + + print("Running verify PaddlePaddle program ... ") + + use_cuda = False + use_xpu = False + use_npu = False + + if paddle.is_compiled_with_cuda(): + use_cuda = _is_cuda_available() + elif paddle.is_compiled_with_xpu(): + use_xpu = _is_xpu_available() + elif paddle.is_compiled_with_npu(): + use_npu = _is_npu_available() + + if use_cuda: + device_str = "GPU" + device_list = paddle.static.cuda_places() + elif use_xpu: + device_str = "XPU" + device_list = paddle.static.xpu_places() + elif use_npu: + device_str = "NPU" + device_list = paddle.static.npu_places() + else: + device_str = "CPU" + device_list = paddle.static.cpu_places(device_count=2) + device_count = len(device_list) + + _run_static_single(use_cuda, use_xpu, use_npu) + _run_dygraph_single(use_cuda, use_xpu, use_npu) + print("PaddlePaddle works well on 1 {}.".format(device_str)) + + try: + _run_static_parallel(use_cuda, use_xpu, use_npu, device_list) + print("PaddlePaddle works well on {} {}s.".format( + device_count, device_str)) + print( + "PaddlePaddle is installed successfully! Let's start deep learning with PaddlePaddle now." + ) + except Exception as e: + logging.warning( + "PaddlePaddle meets some problem with {} {}s. This may be caused by:" + "\n 1. There is not enough GPUs visible on your system" + "\n 2. Some GPUs are occupied by other process now" + "\n 3. NVIDIA-NCCL2 is not installed correctly on your system. Please follow instruction on https://github.com/NVIDIA/nccl-tests " + "\n to test your NCCL, or reinstall it following https://docs.nvidia.com/deeplearning/sdk/nccl-install-guide/index.html" + .format(device_count, device_str)) + + logging.warning("\n Original Error is: {}".format(e)) + print("PaddlePaddle is installed successfully ONLY for single {}! " + "Let's start deep learning with PaddlePaddle now.".format( + device_str)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/lazy_import.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/lazy_import.py new file mode 100644 index 0000000000000000000000000000000000000000..d9146422819f8aa2262fca89cf9e0dd673695b96 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/lazy_import.py @@ -0,0 +1,40 @@ +# Copyright (c) 2018 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. +"""Lazy imports for heavy dependencies.""" + +import importlib + +__all__ = [] + + +def try_import(module_name): + """Try importing a module, with an informative error message on failure.""" + install_name = module_name + + if module_name.find('.') > -1: + install_name = module_name.split('.')[0] + + if module_name == 'cv2': + install_name = 'opencv-python' + + try: + mod = importlib.import_module(module_name) + return mod + except ImportError: + err_msg = ( + "Failed importing {}. This likely means that some paddle modules " + "require additional dependencies that have to be " + "manually installed (usually with `pip install {}`). ").format( + module_name, install_name) + raise ImportError(err_msg) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/op_version.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/op_version.py new file mode 100644 index 0000000000000000000000000000000000000000..575e5f40772eb08ea2c79d4ac73d7d04c5f9cfbf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/op_version.py @@ -0,0 +1,72 @@ +# 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. + +from ..fluid import core + +__all__ = [] + + +def Singleton(cls): + _instance = {} + + def _singleton(*args, **kargs): + if cls not in _instance: + _instance[cls] = cls(*args, **kargs) + return _instance[cls] + + return _singleton + + +class OpUpdateInfoHelper(object): + + def __init__(self, info): + self._info = info + + def verify_key_value(self, name=''): + result = False + key_funcs = { + core.OpAttrInfo: 'name', + core.OpInputOutputInfo: 'name', + } + if name == '': + result = True + elif type(self._info) in key_funcs: + if getattr(self._info, key_funcs[type(self._info)])() == name: + result = True + return result + + +@Singleton +class OpLastCheckpointChecker(object): + + def __init__(self): + self.raw_version_map = core.get_op_version_map() + self.checkpoints_map = {} + self._construct_map() + + def _construct_map(self): + for op_name in self.raw_version_map: + last_checkpoint = self.raw_version_map[op_name].checkpoints()[-1] + infos = last_checkpoint.version_desc().infos() + self.checkpoints_map[op_name] = infos + + def filter_updates(self, op_name, type=core.OpUpdateType.kInvalid, key=''): + updates = [] + if op_name in self.checkpoints_map: + for update in self.checkpoints_map[op_name]: + if (update.type() == type) or (type + == core.OpUpdateType.kInvalid): + if OpUpdateInfoHelper(update.info()).verify_key_value(key): + updates.append(update.info()) + return updates diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..8c37e825689a605e84b932860c126171aaf7a653 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/profiler.py @@ -0,0 +1,176 @@ +# 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. + +from __future__ import print_function + +import sys +import warnings + +from ..fluid import core +from ..fluid.profiler import cuda_profiler # noqa: F401 +from ..fluid.profiler import start_profiler +from ..fluid.profiler import profiler # noqa: F401 +from ..fluid.profiler import stop_profiler +from ..fluid.profiler import reset_profiler +from .deprecated import deprecated + +__all__ = [ # noqa + 'Profiler', + 'get_profiler', + 'ProfilerOptions', + 'cuda_profiler', + 'start_profiler', + 'profiler', + 'stop_profiler', + 'reset_profiler', +] + + +@deprecated( + since="2.4.2", + update_to="paddle.profiler.Profiler", + level=1, + reason="Please use new profiler tool, this profiler tool is no longer maintained.", +) +class ProfilerOptions(object): + def __init__(self, options=None): + self.options = { + 'state': 'All', + 'sorted_key': 'default', + 'tracer_level': 'Default', + 'batch_range': [0, sys.maxsize], + 'output_thread_detail': False, + 'profile_path': 'none', + 'timeline_path': 'none', + 'op_summary_path': 'none', + } + if options is not None: + for key in self.options.keys(): + if options.get(key, None) is not None: + self.options[key] = options[key] + + # function to set one specified option + def with_state(self, state): + self.options['state'] = state + return self + + def __getitem__(self, name): + if self.options.get(name, None) is None: + raise ValueError( + "ProfilerOptions does not have an option named %s." % name + ) + else: + if ( + isinstance(self.options[name], str) + and self.options[name] == 'none' + ): + return None + else: + return self.options[name] + + +_current_profiler = None + + +@deprecated( + since="2.4.2", + update_to="paddle.profiler.Profiler", + level=1, + reason="Please use new profiler tool, this profiler tool is no longer maintained.", +) +class Profiler(object): + def __init__(self, enabled=True, options=None): + if options is not None: + self.profiler_options = options + else: + self.profiler_options = ProfilerOptions() + self.batch_id = 0 + self.enabled = enabled + + def __enter__(self): + # record current profiler + global _current_profiler + self.previous_profiler = _current_profiler + _current_profiler = self + + if self.enabled: + if self.profiler_options['batch_range'][0] == 0: + self.start() + return self + + def __exit__(self, exception_type, exception_value, traceback): + global _current_profiler + _current_profiler = self.previous_profiler + + if self.enabled: + self.stop() + + def start(self): + if self.enabled: + try: + start_profiler( + state=self.profiler_options['state'], + tracer_option=self.profiler_options['tracer_level'], + ) + except Exception as e: + warnings.warn( + "Profiler is not enabled becuase following exception:\n{}".format( + e + ) + ) + + def stop(self): + if self.enabled: + try: + stop_profiler( + sorted_key=self.profiler_options['sorted_key'], + profile_path=self.profiler_options['profile_path'], + ) + except Exception as e: + warnings.warn( + "Profiler is not disabled becuase following exception:\n{}".format( + e + ) + ) + + def reset(self): + if self.enabled and core.is_profiler_enabled(): + reset_profiler() + + def record_step(self, change_profiler_status=True): + if not self.enabled: + return + self.batch_id = self.batch_id + 1 + if change_profiler_status: + if self.batch_id == self.profiler_options['batch_range'][0]: + if core.is_profiler_enabled(): + self.reset() + else: + self.start() + + if self.batch_id == self.profiler_options['batch_range'][1]: + self.stop() + + +@deprecated( + since="2.4.2", + update_to="paddle.profiler.Profiler", + level=1, + reason="Please use new profiler tool, this profiler tool is no longer maintained.", +) +def get_profiler(): + global _current_profiler + if _current_profiler is None: + _current_profiler = Profiler() + return _current_profiler diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/unique_name.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/unique_name.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d487c933d767d4f1dca9642d5346bf97b7fe06 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/utils/unique_name.py @@ -0,0 +1,21 @@ +# Copyright (c) 2021 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. + +from ..fluid.unique_name import generate # noqa: F401 +from ..fluid.unique_name import switch # noqa: F401 +from ..fluid.unique_name import guard # noqa: F401 + +__all__ = [ #noqa + 'generate', 'switch', 'guard' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/version/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/version/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1aa2e18402830a163317540cec9517cf695987d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/version/__init__.py @@ -0,0 +1,104 @@ +# THIS FILE IS GENERATED FROM PADDLEPADDLE SETUP.PY +# +full_version = '2.4.2' +major = '2' +minor = '4' +patch = '2' +rc = '0' +cuda_version = 'False' +cudnn_version = 'False' +istaged = True +commit = '0e92adceae06b6b7463f2dc7790ffb0601730009' +with_mkl = 'ON' + +__all__ = ['cuda', 'cudnn', 'show'] + +def show(): + """Get the version of paddle if `paddle` package if tagged. Otherwise, output the corresponding commit id. + + Returns: + If paddle package is not tagged, the commit-id of paddle will be output. + Otherwise, the following information will be output. + + full_version: version of paddle + + major: the major version of paddle + + minor: the minor version of paddle + + patch: the patch level version of paddle + + rc: whether it's rc version + + cuda: the cuda version of package. It will return `False` if CPU version paddle package is installed + + cudnn: the cudnn version of package. It will return `False` if CPU version paddle package is installed + + Examples: + .. code-block:: python + + import paddle + + # Case 1: paddle is tagged with 2.2.0 + paddle.version.show() + # full_version: 2.2.0 + # major: 2 + # minor: 2 + # patch: 0 + # rc: 0 + # cuda: '10.2' + # cudnn: '7.6.5' + + # Case 2: paddle is not tagged + paddle.version.show() + # commit: cfa357e984bfd2ffa16820e354020529df434f7d + # cuda: '10.2' + # cudnn: '7.6.5' + """ + if istaged: + print('full_version:', full_version) + print('major:', major) + print('minor:', minor) + print('patch:', patch) + print('rc:', rc) + else: + print('commit:', commit) + print('cuda:', cuda_version) + print('cudnn:', cudnn_version) + +def mkl(): + return with_mkl + +def cuda(): + """Get cuda version of paddle package. + + Returns: + string: Return the version information of cuda. If paddle package is CPU version, it will return False. + + Examples: + .. code-block:: python + + import paddle + + paddle.version.cuda() + # '10.2' + + """ + return cuda_version + +def cudnn(): + """Get cudnn version of paddle package. + + Returns: + string: Return the version information of cudnn. If paddle package is CPU version, it will return False. + + Examples: + .. code-block:: python + + import paddle + + paddle.version.cudnn() + # '7.6.5' + + """ + return cudnn_version diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f0052537e251fb5beed4c650d9ab95de6fcf95e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/__init__.py @@ -0,0 +1,117 @@ +# 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. +import paddle +import paddle.nn as nn +from . import models # noqa: F401 +from . import transforms # noqa: F401 +from . import datasets # noqa: F401 +from . import ops # noqa: F401 +from .image import set_image_backend # noqa: F401 +from .image import get_image_backend # noqa: F401 +from .image import image_load # noqa: F401 +from .datasets import DatasetFolder # noqa: F401 +from .datasets import ImageFolder # noqa: F401 +from .datasets import MNIST # noqa: F401 +from .datasets import FashionMNIST # noqa: F401 +from .datasets import Flowers # noqa: F401 +from .datasets import Cifar10 # noqa: F401 +from .datasets import Cifar100 # noqa: F401 +from .datasets import VOC2012 # noqa: F401 +from .models import ResNet # noqa: F401 +from .models import resnet18 # noqa: F401 +from .models import resnet34 # noqa: F401 +from .models import resnet50 # noqa: F401 +from .models import resnet101 # noqa: F401 +from .models import resnet152 # noqa: F401 +from .models import resnext50_32x4d # noqa: F401 +from .models import resnext50_64x4d # noqa: F401 +from .models import resnext101_32x4d # noqa: F401 +from .models import resnext101_64x4d # noqa: F401 +from .models import resnext152_32x4d # noqa: F401 +from .models import resnext152_64x4d # noqa: F401 +from .models import wide_resnet50_2 # noqa: F401 +from .models import wide_resnet101_2 # noqa: F401 +from .models import MobileNetV1 # noqa: F401 +from .models import mobilenet_v1 # noqa: F401 +from .models import MobileNetV2 # noqa: F401 +from .models import mobilenet_v2 # noqa: F401 +from .models import MobileNetV3Small # noqa: F401 +from .models import MobileNetV3Large # noqa: F401 +from .models import mobilenet_v3_small # noqa: F401 +from .models import mobilenet_v3_large # noqa: F401 +from .models import SqueezeNet # noqa: F401 +from .models import squeezenet1_0 # noqa: F401 +from .models import squeezenet1_1 # noqa: F401 +from .models import VGG # noqa: F401 +from .models import vgg11 # noqa: F401 +from .models import vgg13 # noqa: F401 +from .models import vgg16 # noqa: F401 +from .models import vgg19 # noqa: F401 +from .models import LeNet # noqa: F401 +from .models import DenseNet # noqa: F401 +from .models import densenet121 # noqa: F401 +from .models import densenet161 # noqa: F401 +from .models import densenet169 # noqa: F401 +from .models import densenet201 # noqa: F401 +from .models import densenet264 # noqa: F401 +from .models import AlexNet # noqa: F401 +from .models import alexnet # noqa: F401 +from .models import InceptionV3 # noqa: F401 +from .models import inception_v3 # noqa: F401 +from .models import GoogLeNet # noqa: F401 +from .models import googlenet # noqa: F401 +from .models import ShuffleNetV2 # noqa: F401 +from .models import shufflenet_v2_x0_25 # noqa: F401 +from .models import shufflenet_v2_x0_33 # noqa: F401 +from .models import shufflenet_v2_x0_5 # noqa: F401 +from .models import shufflenet_v2_x1_0 # noqa: F401 +from .models import shufflenet_v2_x1_5 # noqa: F401 +from .models import shufflenet_v2_x2_0 # noqa: F401 +from .models import shufflenet_v2_swish # noqa: F401 +from .transforms import BaseTransform # noqa: F401 +from .transforms import Compose # noqa: F401 +from .transforms import Resize # noqa: F401 +from .transforms import RandomResizedCrop # noqa: F401 +from .transforms import CenterCrop # noqa: F401 +from .transforms import RandomHorizontalFlip # noqa: F401 +from .transforms import RandomVerticalFlip # noqa: F401 +from .transforms import Transpose # noqa: F401 +from .transforms import Normalize # noqa: F401 +from .transforms import BrightnessTransform # noqa: F401 +from .transforms import SaturationTransform # noqa: F401 +from .transforms import ContrastTransform # noqa: F401 +from .transforms import HueTransform # noqa: F401 +from .transforms import ColorJitter # noqa: F401 +from .transforms import RandomCrop # noqa: F401 +from .transforms import Pad # noqa: F401 +from .transforms import RandomRotation # noqa: F401 +from .transforms import Grayscale # noqa: F401 +from .transforms import ToTensor # noqa: F401 +from .transforms import to_tensor # noqa: F401 +from .transforms import hflip # noqa: F401 +from .transforms import vflip # noqa: F401 +from .transforms import resize # noqa: F401 +from .transforms import pad # noqa: F401 +from .transforms import rotate # noqa: F401 +from .transforms import to_grayscale # noqa: F401 +from .transforms import crop # noqa: F401 +from .transforms import center_crop # noqa: F401 +from .transforms import adjust_brightness # noqa: F401 +from .transforms import adjust_contrast # noqa: F401 +from .transforms import adjust_hue # noqa: F401 +from .transforms import normalize # noqa: F401 + +__all__ = [ #noqa + 'set_image_backend', 'get_image_backend', 'image_load' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10666b7c7194acd54c97ee3eae13e9d83152b465 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/__init__.py @@ -0,0 +1,27 @@ +# 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. + +from .folder import DatasetFolder # noqa: F401 +from .folder import ImageFolder # noqa: F401 +from .mnist import MNIST # noqa: F401 +from .mnist import FashionMNIST # noqa: F401 +from .flowers import Flowers # noqa: F401 +from .cifar import Cifar10 # noqa: F401 +from .cifar import Cifar100 # noqa: F401 +from .voc2012 import VOC2012 # noqa: F401 + +__all__ = [ #noqa + 'DatasetFolder', 'ImageFolder', 'MNIST', 'FashionMNIST', 'Flowers', + 'Cifar10', 'Cifar100', 'VOC2012' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/cifar.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..b274ab42a23f0a17ad1e642c55331104844d9911 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/cifar.py @@ -0,0 +1,274 @@ +# 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. + +from __future__ import print_function + +import tarfile +import numpy as np +import six +from PIL import Image +from six.moves import cPickle as pickle + +import paddle +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +URL_PREFIX = 'https://dataset.bj.bcebos.com/cifar/' +CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz' +CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a' +CIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz' +CIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85' + +MODE_FLAG_MAP = { + 'train10': 'data_batch', + 'test10': 'test_batch', + 'train100': 'train', + 'test100': 'test', +} + + +class Cifar10(Dataset): + """ + Implementation of `Cifar-10 `_ + dataset, which has 10 categories. + + Args: + data_file (str, optional): Path to data file, can be set None if + :attr:`download` is True. Default None, default data path: ~/.cache/paddle/dataset/cifar + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): transform to perform on image, None for no transform. Default: None. + download (bool, optional): download dataset automatically if :attr:`data_file` is None. Default True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of Cifar10 dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import Cifar10 + + + cifar10 = Cifar10() + print(len(cifar10)) + # 50000 + + for i in range(5): # only show first 5 images + img, label = cifar10[i] + # do something with img and label + print(type(img), img.size, label) + # (32, 32) 6 + + + transform = T.Compose( + [ + T.Resize(64), + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + cifar10_test = Cifar10( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(cifar10_test)) + # 10000 + + for img, label in itertools.islice(iter(cifar10_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape, label) + # [3, 64, 64] 3 + """ + + def __init__( + self, + data_file=None, + mode='train', + transform=None, + download=True, + backend=None, + ): + assert mode.lower() in [ + 'train', + 'test', + ], "mode.lower() should be 'train' or 'test', but got {}".format(mode) + self.mode = mode.lower() + + if backend is None: + backend = paddle.vision.get_image_backend() + if backend not in ['pil', 'cv2']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2'], but got {}".format( + backend + ) + ) + self.backend = backend + + self._init_url_md5_flag() + + self.data_file = data_file + if self.data_file is None: + assert ( + download + ), "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download( + data_file, self.data_url, self.data_md5, 'cifar', download + ) + + self.transform = transform + + # read dataset into memory + self._load_data() + + self.dtype = paddle.get_default_dtype() + + def _init_url_md5_flag(self): + self.data_url = CIFAR10_URL + self.data_md5 = CIFAR10_MD5 + self.flag = MODE_FLAG_MAP[self.mode + '10'] + + def _load_data(self): + self.data = [] + with tarfile.open(self.data_file, mode='r') as f: + names = ( + each_item.name for each_item in f if self.flag in each_item.name + ) + + names = sorted(list(names)) + + for name in names: + batch = pickle.load(f.extractfile(name), encoding='bytes') + + data = batch[six.b('data')] + labels = batch.get( + six.b('labels'), batch.get(six.b('fine_labels'), None) + ) + assert labels is not None + for sample, label in six.moves.zip(data, labels): + self.data.append((sample, label)) + + def __getitem__(self, idx): + image, label = self.data[idx] + image = np.reshape(image, [3, 32, 32]) + image = image.transpose([1, 2, 0]) + + if self.backend == 'pil': + image = Image.fromarray(image.astype('uint8')) + if self.transform is not None: + image = self.transform(image) + + if self.backend == 'pil': + return image, np.array(label).astype('int64') + + return image.astype(self.dtype), np.array(label).astype('int64') + + def __len__(self): + return len(self.data) + + +class Cifar100(Cifar10): + """ + Implementation of `Cifar-100 `_ + dataset, which has 100 categories. + + Args: + data_file (str, optional): path to data file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/cifar + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): transform to perform on image, None for no transform. Default: None. + download (bool, optional): download dataset automatically if :attr:`data_file` is None. Default True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of Cifar100 dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import Cifar100 + + + cifar100 = Cifar100() + print(len(cifar100)) + # 50000 + + for i in range(5): # only show first 5 images + img, label = cifar100[i] + # do something with img and label + print(type(img), img.size, label) + # (32, 32) 19 + + + transform = T.Compose( + [ + T.Resize(64), + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + cifar100_test = Cifar100( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(cifar100_test)) + # 10000 + + for img, label in itertools.islice(iter(cifar100_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape, label) + # [3, 64, 64] 49 + """ + + def __init__( + self, + data_file=None, + mode='train', + transform=None, + download=True, + backend=None, + ): + super(Cifar100, self).__init__( + data_file, mode, transform, download, backend + ) + + def _init_url_md5_flag(self): + self.data_url = CIFAR100_URL + self.data_md5 = CIFAR100_MD5 + self.flag = MODE_FLAG_MAP[self.mode + '100'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/flowers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/flowers.py new file mode 100644 index 0000000000000000000000000000000000000000..722f52acf69423db52e7c2c73edcb03afde0c683 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/flowers.py @@ -0,0 +1,182 @@ +# 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. + +from __future__ import print_function + +import os +import io +import tarfile +import numpy as np +from PIL import Image + +import paddle +from paddle.io import Dataset +from paddle.utils import try_import +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +DATA_URL = 'http://paddlemodels.bj.bcebos.com/flowers/102flowers.tgz' +LABEL_URL = 'http://paddlemodels.bj.bcebos.com/flowers/imagelabels.mat' +SETID_URL = 'http://paddlemodels.bj.bcebos.com/flowers/setid.mat' +DATA_MD5 = '52808999861908f626f3c1f4e79d11fa' +LABEL_MD5 = 'e0620be6f572b9609742df49c70aed4d' +SETID_MD5 = 'a5357ecc9cb78c4bef273ce3793fc85c' + +# In official 'readme', tstid is the flag of test data +# and trnid is the flag of train data. But test data is more than train data. +# So we exchange the train data and test data. +MODE_FLAG_MAP = {'train': 'tstid', 'test': 'trnid', 'valid': 'valid'} + + +class Flowers(Dataset): + """ + Implementation of `Flowers102 `_ + dataset. + + Args: + data_file (str, optional): Path to data file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/. + label_file (str, optional): Path to label file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/. + setid_file (str, optional): Path to subset index file, can be set + None if :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/flowers/. + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): transform to perform on image, None for no transform. Default: None. + download (bool, optional): download dataset automatically if :attr:`data_file` is None. Default: True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of Flowers dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import Flowers + + + flowers = Flowers() + print(len(flowers)) + # 6149 + + for i in range(5): # only show first 5 images + img, label = flowers[i] + # do something with img and label + print(type(img), img.size, label) + # (523, 500) [1] + + + transform = T.Compose( + [ + T.Resize(64), + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + flowers_test = Flowers( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(flowers_test)) + # 1020 + + for img, label in itertools.islice(iter(flowers_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape, label) + # [3, 64, 96] [1] + """ + + def __init__(self, + data_file=None, + label_file=None, + setid_file=None, + mode='train', + transform=None, + download=True, + backend=None): + assert mode.lower() in ['train', 'valid', 'test'], \ + "mode should be 'train', 'valid' or 'test', but got {}".format(mode) + + if backend is None: + backend = paddle.vision.get_image_backend() + if backend not in ['pil', 'cv2']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2'], but got {}".format( + backend)) + self.backend = backend + + flag = MODE_FLAG_MAP[mode.lower()] + + if not data_file: + assert download, "data_file is not set and downloading automatically is disabled" + data_file = _check_exists_and_download(data_file, DATA_URL, + DATA_MD5, 'flowers', + download) + + if not label_file: + assert download, "label_file is not set and downloading automatically is disabled" + label_file = _check_exists_and_download(label_file, LABEL_URL, + LABEL_MD5, 'flowers', + download) + + if not setid_file: + assert download, "setid_file is not set and downloading automatically is disabled" + setid_file = _check_exists_and_download(setid_file, SETID_URL, + SETID_MD5, 'flowers', + download) + + self.transform = transform + + data_tar = tarfile.open(data_file) + self.data_path = data_file.replace(".tgz", "/") + if not os.path.exists(self.data_path): + os.mkdir(self.data_path) + data_tar.extractall(self.data_path) + + scio = try_import('scipy.io') + self.labels = scio.loadmat(label_file)['labels'][0] + self.indexes = scio.loadmat(setid_file)[flag][0] + + def __getitem__(self, idx): + index = self.indexes[idx] + label = np.array([self.labels[index - 1]]) + img_name = "jpg/image_%05d.jpg" % index + image = os.path.join(self.data_path, img_name) + if self.backend == 'pil': + image = Image.open(image) + elif self.backend == 'cv2': + image = np.array(Image.open(image)) + + if self.transform is not None: + image = self.transform(image) + + if self.backend == 'pil': + return image, label.astype('int64') + + return image.astype(paddle.get_default_dtype()), label.astype('int64') + + def __len__(self): + return len(self.indexes) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/folder.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/folder.py new file mode 100644 index 0000000000000000000000000000000000000000..0d874765729ab7b2f9b5bcba585588f25012800e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/folder.py @@ -0,0 +1,467 @@ +# 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. + +import os +import sys +from PIL import Image + +import paddle +from paddle.io import Dataset +from paddle.utils import try_import + +__all__ = [] + + +def has_valid_extension(filename, extensions): + """Checks if a file is a vilid extension. + + Args: + filename (str): path to a file + extensions (list[str]|tuple[str]): extensions to consider + + Returns: + bool: True if the filename ends with one of given extensions + """ + assert isinstance(extensions, + (list, tuple)), ("`extensions` must be list or tuple.") + extensions = tuple([x.lower() for x in extensions]) + return filename.lower().endswith(extensions) + + +def make_dataset(dir, class_to_idx, extensions, is_valid_file=None): + images = [] + dir = os.path.expanduser(dir) + + if extensions is not None: + + def is_valid_file(x): + return has_valid_extension(x, extensions) + + for target in sorted(class_to_idx.keys()): + d = os.path.join(dir, target) + if not os.path.isdir(d): + continue + for root, _, fnames in sorted(os.walk(d, followlinks=True)): + for fname in sorted(fnames): + path = os.path.join(root, fname) + if is_valid_file(path): + item = (path, class_to_idx[target]) + images.append(item) + + return images + + +class DatasetFolder(Dataset): + """A generic data loader where the samples are arranged in this way: + + .. code-block:: text + + root/class_a/1.ext + root/class_a/2.ext + root/class_a/3.ext + + root/class_b/123.ext + root/class_b/456.ext + root/class_b/789.ext + + Args: + root (str): Root directory path. + loader (Callable, optional): A function to load a sample given its path. Default: None. + extensions (list[str]|tuple[str], optional): A list of allowed extensions. + Both :attr:`extensions` and :attr:`is_valid_file` should not be passed. + If this value is not set, the default is to use ('.jpg', '.jpeg', '.png', + '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None. + transform (Callable, optional): A function/transform that takes in + a sample and returns a transformed version. Default: None. + is_valid_file (Callable, optional): A function that takes path of a file + and check if the file is a valid file. Both :attr:`extensions` and + :attr:`is_valid_file` should not be passed. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of DatasetFolder. + + Attributes: + classes (list[str]): List of the class names. + class_to_idx (dict[str, int]): Dict with items (class_name, class_index). + samples (list[tuple[str, int]]): List of (sample_path, class_index) tuples. + targets (list[int]): The class_index value for each image in the dataset. + + Example: + + .. code-block:: python + + import shutil + import tempfile + import cv2 + import numpy as np + import paddle.vision.transforms as T + from pathlib import Path + from paddle.vision.datasets import DatasetFolder + + + def make_fake_file(img_path: str): + if img_path.endswith((".jpg", ".png", ".jpeg")): + fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8) + cv2.imwrite(img_path, fake_img) + elif img_path.endswith(".txt"): + with open(img_path, "w") as f: + f.write("This is a fake file.") + + def make_directory(root, directory_hierarchy, file_maker=make_fake_file): + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + for subpath in directory_hierarchy: + if isinstance(subpath, str): + filepath = root / subpath + file_maker(str(filepath)) + else: + dirname = list(subpath.keys())[0] + make_directory(root / dirname, subpath[dirname]) + + directory_hirerarchy = [ + {"class_0": [ + "abc.jpg", + "def.png"]}, + {"class_1": [ + "ghi.jpeg", + "jkl.png", + {"mno": [ + "pqr.jpeg", + "stu.jpg"]}]}, + "this_will_be_ignored.txt", + ] + + # You can replace this with any directory to explore the structure + # of generated data. e.g. fake_data_dir = "./temp_dir" + fake_data_dir = tempfile.mkdtemp() + make_directory(fake_data_dir, directory_hirerarchy) + data_folder_1 = DatasetFolder(fake_data_dir) + print(data_folder_1.classes) + # ['class_0', 'class_1'] + print(data_folder_1.class_to_idx) + # {'class_0': 0, 'class_1': 1} + print(data_folder_1.samples) + # [('./temp_dir/class_0/abc.jpg', 0), ('./temp_dir/class_0/def.png', 0), + # ('./temp_dir/class_1/ghi.jpeg', 1), ('./temp_dir/class_1/jkl.png', 1), + # ('./temp_dir/class_1/mno/pqr.jpeg', 1), ('./temp_dir/class_1/mno/stu.jpg', 1)] + print(data_folder_1.targets) + # [0, 0, 1, 1, 1, 1] + print(len(data_folder_1)) + # 6 + + for i in range(len(data_folder_1)): + img, label = data_folder_1[i] + # do something with img and label + print(type(img), img.size, label) + # (32, 32) 0 + + + transform = T.Compose( + [ + T.Resize(64), + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + data_folder_2 = DatasetFolder( + fake_data_dir, + loader=lambda x: cv2.imread(x), # load image with OpenCV + extensions=(".jpg",), # only load *.jpg files + transform=transform, # apply transform to every image + ) + + print([img_path for img_path, label in data_folder_2.samples]) + # ['./temp_dir/class_0/abc.jpg', './temp_dir/class_1/mno/stu.jpg'] + print(len(data_folder_2)) + # 2 + + for img, label in iter(data_folder_2): + # do something with img and label + print(type(img), img.shape, label) + # [3, 64, 64] 0 + + shutil.rmtree(fake_data_dir) + """ + + def __init__(self, + root, + loader=None, + extensions=None, + transform=None, + is_valid_file=None): + self.root = root + self.transform = transform + if extensions is None: + extensions = IMG_EXTENSIONS + classes, class_to_idx = self._find_classes(self.root) + samples = make_dataset(self.root, class_to_idx, extensions, + is_valid_file) + if len(samples) == 0: + raise (RuntimeError("Found 0 directories in subfolders of: " + + self.root + "\n" + "Supported extensions are: " + + ",".join(extensions))) + + self.loader = default_loader if loader is None else loader + self.extensions = extensions + + self.classes = classes + self.class_to_idx = class_to_idx + self.samples = samples + self.targets = [s[1] for s in samples] + + self.dtype = paddle.get_default_dtype() + + def _find_classes(self, dir): + """ + Finds the class folders in a dataset. + + Args: + dir (string): Root directory path. + + Returns: + tuple: (classes, class_to_idx) where classes are relative to (dir), + and class_to_idx is a dictionary. + + """ + if sys.version_info >= (3, 5): + # Faster and available in Python 3.5 and above + classes = [d.name for d in os.scandir(dir) if d.is_dir()] + else: + classes = [ + d for d in os.listdir(dir) + if os.path.isdir(os.path.join(dir, d)) + ] + classes.sort() + class_to_idx = {classes[i]: i for i in range(len(classes))} + return classes, class_to_idx + + def __getitem__(self, index): + """ + Args: + index (int): Index + + Returns: + tuple: (sample, target) where target is class_index of the target class. + """ + path, target = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + + return sample, target + + def __len__(self): + return len(self.samples) + + +IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', + '.tiff', '.webp') + + +def pil_loader(path): + with open(path, 'rb') as f: + img = Image.open(f) + return img.convert('RGB') + + +def cv2_loader(path): + cv2 = try_import('cv2') + return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB) + + +def default_loader(path): + from paddle.vision import get_image_backend + if get_image_backend() == 'cv2': + return cv2_loader(path) + else: + return pil_loader(path) + + +class ImageFolder(Dataset): + """A generic data loader where the samples are arranged in this way: + + .. code-block:: text + + root/1.ext + root/2.ext + root/sub_dir/3.ext + + Args: + root (str): Root directory path. + loader (Callable, optional): A function to load a sample given its path. Default: None. + extensions (list[str]|tuple[str], optional): A list of allowed extensions. + Both :attr:`extensions` and :attr:`is_valid_file` should not be passed. + If this value is not set, the default is to use ('.jpg', '.jpeg', '.png', + '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'). Default: None. + transform (Callable, optional): A function/transform that takes in + a sample and returns a transformed version. Default: None. + is_valid_file (Callable, optional): A function that takes path of a file + and check if the file is a valid file. Both :attr:`extensions` and + :attr:`is_valid_file` should not be passed. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of ImageFolder. + + Attributes: + samples (list[str]): List of sample path. + + Example: + + .. code-block:: python + + import shutil + import tempfile + import cv2 + import numpy as np + import paddle.vision.transforms as T + from pathlib import Path + from paddle.vision.datasets import ImageFolder + + + def make_fake_file(img_path: str): + if img_path.endswith((".jpg", ".png", ".jpeg")): + fake_img = np.random.randint(0, 256, (32, 32, 3), dtype=np.uint8) + cv2.imwrite(img_path, fake_img) + elif img_path.endswith(".txt"): + with open(img_path, "w") as f: + f.write("This is a fake file.") + + def make_directory(root, directory_hierarchy, file_maker=make_fake_file): + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + for subpath in directory_hierarchy: + if isinstance(subpath, str): + filepath = root / subpath + file_maker(str(filepath)) + else: + dirname = list(subpath.keys())[0] + make_directory(root / dirname, subpath[dirname]) + + directory_hirerarchy = [ + "abc.jpg", + "def.png", + {"ghi": [ + "jkl.jpeg", + {"mno": [ + "pqr.jpg"]}]}, + "this_will_be_ignored.txt", + ] + + # You can replace this with any directory to explore the structure + # of generated data. e.g. fake_data_dir = "./temp_dir" + fake_data_dir = tempfile.mkdtemp() + make_directory(fake_data_dir, directory_hirerarchy) + image_folder_1 = ImageFolder(fake_data_dir) + print(image_folder_1.samples) + # ['./temp_dir/abc.jpg', './temp_dir/def.png', + # './temp_dir/ghi/jkl.jpeg', './temp_dir/ghi/mno/pqr.jpg'] + print(len(image_folder_1)) + # 4 + + for i in range(len(image_folder_1)): + (img,) = image_folder_1[i] + # do something with img + print(type(img), img.size) + # (32, 32) + + + transform = T.Compose( + [ + T.Resize(64), + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + image_folder_2 = ImageFolder( + fake_data_dir, + loader=lambda x: cv2.imread(x), # load image with OpenCV + extensions=(".jpg",), # only load *.jpg files + transform=transform, # apply transform to every image + ) + + print(image_folder_2.samples) + # ['./temp_dir/abc.jpg', './temp_dir/ghi/mno/pqr.jpg'] + print(len(image_folder_2)) + # 2 + + for (img,) in iter(image_folder_2): + # do something with img + print(type(img), img.shape) + # [3, 64, 64] + + shutil.rmtree(fake_data_dir) + """ + + def __init__(self, + root, + loader=None, + extensions=None, + transform=None, + is_valid_file=None): + self.root = root + if extensions is None: + extensions = IMG_EXTENSIONS + + samples = [] + path = os.path.expanduser(root) + + if extensions is not None: + + def is_valid_file(x): + return has_valid_extension(x, extensions) + + for root, _, fnames in sorted(os.walk(path, followlinks=True)): + for fname in sorted(fnames): + f = os.path.join(root, fname) + if is_valid_file(f): + samples.append(f) + + if len(samples) == 0: + raise (RuntimeError("Found 0 files in subfolders of: " + self.root + + "\n" + "Supported extensions are: " + + ",".join(extensions))) + + self.loader = default_loader if loader is None else loader + self.extensions = extensions + self.samples = samples + self.transform = transform + + def __getitem__(self, index): + """ + Args: + index (int): Index + + Returns: + sample of specific index. + """ + path = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + return [sample] + + def __len__(self): + return len(self.samples) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/mnist.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..34049ed2f72b59b1a6b0503b2778f0fe57a9f012 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/mnist.py @@ -0,0 +1,286 @@ +# 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. + +from __future__ import print_function + +import os +import gzip +import struct +import numpy as np +from PIL import Image + +import paddle +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + + +class MNIST(Dataset): + """ + Implementation of `MNIST `_ dataset. + + Args: + image_path (str, optional): Path to image file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist. + label_path (str, optional): Path to label file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist. + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): Transform to perform on image, None for no transform. Default: None. + download (bool, optional): Download dataset automatically if + :attr:`image_path` :attr:`label_path` is not set. Default: True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of MNIST dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import MNIST + + + mnist = MNIST() + print(len(mnist)) + # 60000 + + for i in range(5): # only show first 5 images + img, label = mnist[i] + # do something with img and label + print(type(img), img.size, label) + # (28, 28) [5] + + + transform = T.Compose( + [ + T.ToTensor(), + T.Normalize( + mean=[127.5], + std=[127.5], + ), + ] + ) + + mnist_test = MNIST( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(mnist_test)) + # 10000 + + for img, label in itertools.islice(iter(mnist_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape, label) + # [1, 28, 28] [7] + """ + NAME = 'mnist' + URL_PREFIX = 'https://dataset.bj.bcebos.com/mnist/' + TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz' + TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3' + TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz' + TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c' + TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz' + TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873' + TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz' + TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432' + + def __init__(self, + image_path=None, + label_path=None, + mode='train', + transform=None, + download=True, + backend=None): + assert mode.lower() in ['train', 'test'], \ + "mode should be 'train' or 'test', but got {}".format(mode) + + if backend is None: + backend = paddle.vision.get_image_backend() + if backend not in ['pil', 'cv2']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2'], but got {}".format( + backend)) + self.backend = backend + + self.mode = mode.lower() + self.image_path = image_path + if self.image_path is None: + assert download, "image_path is not set and downloading automatically is disabled" + image_url = self.TRAIN_IMAGE_URL if mode == 'train' else self.TEST_IMAGE_URL + image_md5 = self.TRAIN_IMAGE_MD5 if mode == 'train' else self.TEST_IMAGE_MD5 + self.image_path = _check_exists_and_download( + image_path, image_url, image_md5, self.NAME, download) + + self.label_path = label_path + if self.label_path is None: + assert download, "label_path is not set and downloading automatically is disabled" + label_url = self.TRAIN_LABEL_URL if self.mode == 'train' else self.TEST_LABEL_URL + label_md5 = self.TRAIN_LABEL_MD5 if self.mode == 'train' else self.TEST_LABEL_MD5 + self.label_path = _check_exists_and_download( + label_path, label_url, label_md5, self.NAME, download) + + self.transform = transform + + # read dataset into memory + self._parse_dataset() + + self.dtype = paddle.get_default_dtype() + + def _parse_dataset(self, buffer_size=100): + self.images = [] + self.labels = [] + with gzip.GzipFile(self.image_path, 'rb') as image_file: + img_buf = image_file.read() + with gzip.GzipFile(self.label_path, 'rb') as label_file: + lab_buf = label_file.read() + + step_label = 0 + offset_img = 0 + # read from Big-endian + # get file info from magic byte + # image file : 16B + magic_byte_img = '>IIII' + magic_img, image_num, rows, cols = struct.unpack_from( + magic_byte_img, img_buf, offset_img) + offset_img += struct.calcsize(magic_byte_img) + + offset_lab = 0 + # label file : 8B + magic_byte_lab = '>II' + magic_lab, label_num = struct.unpack_from( + magic_byte_lab, lab_buf, offset_lab) + offset_lab += struct.calcsize(magic_byte_lab) + + while True: + if step_label >= label_num: + break + fmt_label = '>' + str(buffer_size) + 'B' + labels = struct.unpack_from(fmt_label, lab_buf, offset_lab) + offset_lab += struct.calcsize(fmt_label) + step_label += buffer_size + + fmt_images = '>' + str(buffer_size * rows * cols) + 'B' + images_temp = struct.unpack_from(fmt_images, img_buf, + offset_img) + images = np.reshape( + images_temp, + (buffer_size, rows * cols)).astype('float32') + offset_img += struct.calcsize(fmt_images) + + for i in range(buffer_size): + self.images.append(images[i, :]) + self.labels.append( + np.array([labels[i]]).astype('int64')) + + def __getitem__(self, idx): + image, label = self.images[idx], self.labels[idx] + image = np.reshape(image, [28, 28]) + + if self.backend == 'pil': + image = Image.fromarray(image.astype('uint8'), mode='L') + + if self.transform is not None: + image = self.transform(image) + + if self.backend == 'pil': + return image, label.astype('int64') + + return image.astype(self.dtype), label.astype('int64') + + def __len__(self): + return len(self.labels) + + +class FashionMNIST(MNIST): + """ + Implementation of `Fashion-MNIST `_ dataset. + + Args: + image_path (str, optional): Path to image file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist. + label_path (str, optional): Path to label file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist. + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): Transform to perform on image, None for no transform. Default: None. + download (bool, optional): Whether to download dataset automatically if + :attr:`image_path` :attr:`label_path` is not set. Default: True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of FashionMNIST dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import FashionMNIST + + + fashion_mnist = FashionMNIST() + print(len(fashion_mnist)) + # 60000 + + for i in range(5): # only show first 5 images + img, label = fashion_mnist[i] + # do something with img and label + print(type(img), img.size, label) + # (28, 28) [9] + + + transform = T.Compose( + [ + T.ToTensor(), + T.Normalize( + mean=[127.5], + std=[127.5], + ), + ] + ) + + fashion_mnist_test = FashionMNIST( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(fashion_mnist_test)) + # 10000 + + for img, label in itertools.islice(iter(fashion_mnist_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape, label) + # [1, 28, 28] [9] + """ + + NAME = 'fashion-mnist' + URL_PREFIX = 'https://dataset.bj.bcebos.com/fashion_mnist/' + TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz' + TEST_IMAGE_MD5 = 'bef4ecab320f06d8554ea6380940ec79' + TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz' + TEST_LABEL_MD5 = 'bb300cfdad3c16e7a12a480ee83cd310' + TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz' + TRAIN_IMAGE_MD5 = '8d4fb7e6c68d591d4c3dfef9ec88bf0d' + TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz' + TRAIN_LABEL_MD5 = '25c81989df183df01b3e8a0aad5dffbe' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/voc2012.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/voc2012.py new file mode 100644 index 0000000000000000000000000000000000000000..2d65b16550bad1c9d7b8ac2cba56009c74a81bd8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/datasets/voc2012.py @@ -0,0 +1,184 @@ +# 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. + +from __future__ import print_function + +import io +import tarfile +import numpy as np +from PIL import Image + +import paddle +from paddle.io import Dataset +from paddle.dataset.common import _check_exists_and_download + +__all__ = [] + +VOC_URL = 'https://dataset.bj.bcebos.com/voc/VOCtrainval_11-May-2012.tar' + +VOC_MD5 = '6cd6e144f989b92b3379bac3b3de84fd' +SET_FILE = 'VOCdevkit/VOC2012/ImageSets/Segmentation/{}.txt' +DATA_FILE = 'VOCdevkit/VOC2012/JPEGImages/{}.jpg' +LABEL_FILE = 'VOCdevkit/VOC2012/SegmentationClass/{}.png' + +CACHE_DIR = 'voc2012' + +MODE_FLAG_MAP = {'train': 'trainval', 'test': 'train', 'valid': "val"} + + +class VOC2012(Dataset): + """ + Implementation of `VOC2012 `_ dataset. + + Args: + data_file (str, optional): Path to data file, can be set None if + :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/voc2012. + mode (str, optional): Either train or test mode. Default 'train'. + transform (Callable, optional): Transform to perform on image, None for no transform. Default: None. + download (bool, optional): Download dataset automatically if :attr:`data_file` is None. Default: True. + backend (str, optional): Specifies which type of image to be returned: + PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}. + If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend `, + default backend is 'pil'. Default: None. + + Returns: + :ref:`api_paddle_io_Dataset`. An instance of VOC2012 dataset. + + Examples: + + .. code-block:: python + + import itertools + import paddle.vision.transforms as T + from paddle.vision.datasets import VOC2012 + + + voc2012 = VOC2012() + print(len(voc2012)) + # 2913 + + for i in range(5): # only show first 5 images + img, label = voc2012[i] + # do something with img and label + print(type(img), img.size) + # (500, 281) + print(type(label), label.size) + # (500, 281) + + + transform = T.Compose( + [ + T.ToTensor(), + T.Normalize( + mean=[0.5, 0.5, 0.5], + std=[0.5, 0.5, 0.5], + to_rgb=True, + ), + ] + ) + + voc2012_test = VOC2012( + mode="test", + transform=transform, # apply transform to every image + backend="cv2", # use OpenCV as image transform backend + ) + print(len(voc2012_test)) + # 1464 + + for img, label in itertools.islice(iter(voc2012_test), 5): # only show first 5 images + # do something with img and label + print(type(img), img.shape) + # [3, 281, 500] + print(type(label), label.shape) + # (281, 500) + """ + + def __init__(self, + data_file=None, + mode='train', + transform=None, + download=True, + backend=None): + assert mode.lower() in ['train', 'valid', 'test'], \ + "mode should be 'train', 'valid' or 'test', but got {}".format(mode) + + if backend is None: + backend = paddle.vision.get_image_backend() + if backend not in ['pil', 'cv2']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2'], but got {}".format( + backend)) + self.backend = backend + + self.flag = MODE_FLAG_MAP[mode.lower()] + + self.data_file = data_file + if self.data_file is None: + assert download, "data_file is not set and downloading automatically is disabled" + self.data_file = _check_exists_and_download(data_file, VOC_URL, + VOC_MD5, CACHE_DIR, + download) + self.transform = transform + + # read dataset into memory + self._load_anno() + + self.dtype = paddle.get_default_dtype() + + def _load_anno(self): + self.name2mem = {} + self.data_tar = tarfile.open(self.data_file) + for ele in self.data_tar.getmembers(): + self.name2mem[ele.name] = ele + + set_file = SET_FILE.format(self.flag) + sets = self.data_tar.extractfile(self.name2mem[set_file]) + + self.data = [] + self.labels = [] + + for line in sets: + line = line.strip() + data = DATA_FILE.format(line.decode('utf-8')) + label = LABEL_FILE.format(line.decode('utf-8')) + self.data.append(data) + self.labels.append(label) + + def __getitem__(self, idx): + data_file = self.data[idx] + label_file = self.labels[idx] + + data = self.data_tar.extractfile(self.name2mem[data_file]).read() + label = self.data_tar.extractfile(self.name2mem[label_file]).read() + data = Image.open(io.BytesIO(data)) + label = Image.open(io.BytesIO(label)) + + if self.backend == 'cv2': + data = np.array(data) + label = np.array(label) + + if self.transform is not None: + data = self.transform(data) + + if self.backend == 'cv2': + return data.astype(self.dtype), label.astype(self.dtype) + + return data, label + + def __len__(self): + return len(self.data) + + def __del__(self): + if self.data_tar: + self.data_tar.close() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/image.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/image.py new file mode 100644 index 0000000000000000000000000000000000000000..755c8bcc9cc322166454ad6959383f3610690b76 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/image.py @@ -0,0 +1,162 @@ +# 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. + +from PIL import Image +from paddle.utils import try_import + +__all__ = [] + +_image_backend = 'pil' + + +def set_image_backend(backend): + """ + Specifies the backend used to load images in class ``paddle.vision.datasets.ImageFolder`` + and ``paddle.vision.datasets.DatasetFolder`` . Now support backends are pillow and opencv. + If backend not set, will use 'pil' as default. + + Args: + backend (str): Name of the image load backend, should be one of {'pil', 'cv2'}. + + Examples: + + .. code-block:: python + + import os + import shutil + import tempfile + import numpy as np + from PIL import Image + + from paddle.vision import DatasetFolder + from paddle.vision import set_image_backend + + set_image_backend('pil') + + def make_fake_dir(): + data_dir = tempfile.mkdtemp() + + for i in range(2): + sub_dir = os.path.join(data_dir, 'class_' + str(i)) + if not os.path.exists(sub_dir): + os.makedirs(sub_dir) + for j in range(2): + fake_img = Image.fromarray((np.random.random((32, 32, 3)) * 255).astype('uint8')) + fake_img.save(os.path.join(sub_dir, str(j) + '.png')) + return data_dir + + temp_dir = make_fake_dir() + + pil_data_folder = DatasetFolder(temp_dir) + + for items in pil_data_folder: + break + + # should get PIL.Image.Image + print(type(items[0])) + + # use opencv as backend + # set_image_backend('cv2') + + # cv2_data_folder = DatasetFolder(temp_dir) + + # for items in cv2_data_folder: + # break + + # should get numpy.ndarray + # print(type(items[0])) + + shutil.rmtree(temp_dir) + """ + global _image_backend + if backend not in ['pil', 'cv2', 'tensor']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2', 'tensor'], but got {}". + format(backend)) + _image_backend = backend + + +def get_image_backend(): + """ + Gets the name of the package used to load images + + Returns: + str: backend of image load. + + Examples: + + .. code-block:: python + + from paddle.vision import get_image_backend + + backend = get_image_backend() + print(backend) + + """ + return _image_backend + + +def image_load(path, backend=None): + """Load an image. + + Args: + path (str): Path of the image. + backend (str, optional): The image decoding backend type. Options are + `cv2`, `pil`, `None`. If backend is None, the global _imread_backend + specified by ``paddle.vision.set_image_backend`` will be used. Default: None. + + Returns: + PIL.Image or np.array: Loaded image. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision import image_load, set_image_backend + + fake_img = Image.fromarray((np.random.random((32, 32, 3)) * 255).astype('uint8')) + + path = 'temp.png' + fake_img.save(path) + + set_image_backend('pil') + + pil_img = image_load(path).convert('RGB') + + # should be PIL.Image.Image + print(type(pil_img)) + + # use opencv as backend + # set_image_backend('cv2') + + # np_img = image_load(path) + # # should get numpy.ndarray + # print(type(np_img)) + + """ + + if backend is None: + backend = _image_backend + if backend not in ['pil', 'cv2', 'tensor']: + raise ValueError( + "Expected backend are one of ['pil', 'cv2', 'tensor'], but got {}". + format(backend)) + + if backend == 'pil': + return Image.open(path) + elif backend == 'cv2': + cv2 = try_import('cv2') + return cv2.imread(path) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72bb6ee8e8d5b5d7e018be37802da538f38bc88d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/__init__.py @@ -0,0 +1,81 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +from .resnet import ResNet # noqa: F401 +from .resnet import resnet18 # noqa: F401 +from .resnet import resnet34 # noqa: F401 +from .resnet import resnet50 # noqa: F401 +from .resnet import resnet101 # noqa: F401 +from .resnet import resnet152 # noqa: F401 +from .resnet import resnext50_32x4d # noqa: F401 +from .resnet import resnext50_64x4d # noqa: F401 +from .resnet import resnext101_32x4d # noqa: F401 +from .resnet import resnext101_64x4d # noqa: F401 +from .resnet import resnext152_32x4d # noqa: F401 +from .resnet import resnext152_64x4d # noqa: F401 +from .resnet import wide_resnet50_2 # noqa: F401 +from .resnet import wide_resnet101_2 # noqa: F401 +from .mobilenetv1 import MobileNetV1 # noqa: F401 +from .mobilenetv1 import mobilenet_v1 # noqa: F401 +from .mobilenetv2 import MobileNetV2 # noqa: F401 +from .mobilenetv2 import mobilenet_v2 # noqa: F401 +from .mobilenetv3 import MobileNetV3Small # noqa: F401 +from .mobilenetv3 import MobileNetV3Large # noqa: F401 +from .mobilenetv3 import mobilenet_v3_small # noqa: F401 +from .mobilenetv3 import mobilenet_v3_large # noqa: F401 +from .vgg import VGG # noqa: F401 +from .vgg import vgg11 # noqa: F401 +from .vgg import vgg13 # noqa: F401 +from .vgg import vgg16 # noqa: F401 +from .vgg import vgg19 # noqa: F401 +from .lenet import LeNet # noqa: F401 +from .densenet import DenseNet # noqa: F401 +from .densenet import densenet121 # noqa: F401 +from .densenet import densenet161 # noqa: F401 +from .densenet import densenet169 # noqa: F401 +from .densenet import densenet201 # noqa: F401 +from .densenet import densenet264 # noqa: F401 +from .alexnet import AlexNet # noqa: F401 +from .alexnet import alexnet # noqa: F401 +from .inceptionv3 import InceptionV3 # noqa: F401 +from .inceptionv3 import inception_v3 # noqa: F401 +from .squeezenet import SqueezeNet # noqa: F401 +from .squeezenet import squeezenet1_0 # noqa: F401 +from .squeezenet import squeezenet1_1 # noqa: F401 +from .googlenet import GoogLeNet # noqa: F401 +from .googlenet import googlenet # noqa: F401 +from .shufflenetv2 import ShuffleNetV2 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x0_25 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x0_33 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x0_5 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x1_0 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x1_5 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_x2_0 # noqa: F401 +from .shufflenetv2 import shufflenet_v2_swish # noqa: F401 + +__all__ = [ #noqa + 'ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', + 'resnext50_32x4d', 'resnext50_64x4d', 'resnext101_32x4d', + 'resnext101_64x4d', 'resnext152_32x4d', 'resnext152_64x4d', + 'wide_resnet50_2', 'wide_resnet101_2', 'VGG', 'vgg11', 'vgg13', 'vgg16', + 'vgg19', 'MobileNetV1', 'mobilenet_v1', 'MobileNetV2', 'mobilenet_v2', + 'MobileNetV3Small', 'MobileNetV3Large', 'mobilenet_v3_small', + 'mobilenet_v3_large', 'LeNet', 'DenseNet', 'densenet121', 'densenet161', + 'densenet169', 'densenet201', 'densenet264', 'AlexNet', 'alexnet', + 'InceptionV3', 'inception_v3', 'SqueezeNet', 'squeezenet1_0', + 'squeezenet1_1', 'GoogLeNet', 'googlenet', 'ShuffleNetV2', + 'shufflenet_v2_x0_25', 'shufflenet_v2_x0_33', 'shufflenet_v2_x0_5', + 'shufflenet_v2_x1_0', 'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0', + 'shufflenet_v2_swish' +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/alexnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/alexnet.py new file mode 100644 index 0000000000000000000000000000000000000000..b24afac253fe0c482acfa4dc81a5b57073d22988 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/alexnet.py @@ -0,0 +1,218 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + +from paddle.nn import Linear, Dropout, ReLU +from paddle.nn import Conv2D, MaxPool2D +from paddle.nn.initializer import Uniform +from paddle.fluid.param_attr import ParamAttr +from paddle.utils.download import get_weights_path_from_url + +model_urls = { + "alexnet": ( + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/AlexNet_pretrained.pdparams", + "7f0f9f737132e02732d75a1459d98a43", + ) +} + +__all__ = [] + + +class ConvPoolLayer(nn.Layer): + + def __init__(self, + input_channels, + output_channels, + filter_size, + stride, + padding, + stdv, + groups=1, + act=None): + super(ConvPoolLayer, self).__init__() + + self.relu = ReLU() if act == "relu" else None + + self._conv = Conv2D( + in_channels=input_channels, + out_channels=output_channels, + kernel_size=filter_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + self._pool = MaxPool2D(kernel_size=3, stride=2, padding=0) + + def forward(self, inputs): + x = self._conv(inputs) + if self.relu is not None: + x = self.relu(x) + x = self._pool(x) + return x + + +class AlexNet(nn.Layer): + """AlexNet model from + `"ImageNet Classification with Deep Convolutional Neural Networks" + `_. + + Args: + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of AlexNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import AlexNet + + alexnet = AlexNet() + + x = paddle.rand([1, 3, 224, 224]) + out = alexnet(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, num_classes=1000): + super(AlexNet, self).__init__() + self.num_classes = num_classes + stdv = 1.0 / math.sqrt(3 * 11 * 11) + self._conv1 = ConvPoolLayer(3, 64, 11, 4, 2, stdv, act="relu") + stdv = 1.0 / math.sqrt(64 * 5 * 5) + self._conv2 = ConvPoolLayer(64, 192, 5, 1, 2, stdv, act="relu") + stdv = 1.0 / math.sqrt(192 * 3 * 3) + self._conv3 = Conv2D( + 192, + 384, + 3, + stride=1, + padding=1, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + stdv = 1.0 / math.sqrt(384 * 3 * 3) + self._conv4 = Conv2D( + 384, + 256, + 3, + stride=1, + padding=1, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + stdv = 1.0 / math.sqrt(256 * 3 * 3) + self._conv5 = ConvPoolLayer(256, 256, 3, 1, 1, stdv, act="relu") + + if self.num_classes > 0: + stdv = 1.0 / math.sqrt(256 * 6 * 6) + self._drop1 = Dropout(p=0.5, mode="downscale_in_infer") + self._fc6 = Linear( + in_features=256 * 6 * 6, + out_features=4096, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + + self._drop2 = Dropout(p=0.5, mode="downscale_in_infer") + self._fc7 = Linear( + in_features=4096, + out_features=4096, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + self._fc8 = Linear( + in_features=4096, + out_features=num_classes, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv))) + + def forward(self, inputs): + x = self._conv1(inputs) + x = self._conv2(x) + x = self._conv3(x) + x = F.relu(x) + x = self._conv4(x) + x = F.relu(x) + x = self._conv5(x) + + if self.num_classes > 0: + x = paddle.flatten(x, start_axis=1, stop_axis=-1) + x = self._drop1(x) + x = self._fc6(x) + x = F.relu(x) + x = self._drop2(x) + x = self._fc7(x) + x = F.relu(x) + x = self._fc8(x) + + return x + + +def _alexnet(arch, pretrained, **kwargs): + model = AlexNet(**kwargs) + + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.load_dict(param) + + return model + + +def alexnet(pretrained=False, **kwargs): + """AlexNet model from + `"ImageNet Classification with Deep Convolutional Neural Networks" + `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`AlexNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of AlexNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import alexnet + + # build model + model = alexnet() + + # build model and load imagenet pretrained weight + # model = alexnet(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _alexnet('alexnet', pretrained, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/densenet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..5580b97a3a8e582a00a11e1d0f882f70f7b81cd7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/densenet.py @@ -0,0 +1,475 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +import paddle +import paddle.nn as nn +from paddle.nn import Conv2D, BatchNorm, Linear, Dropout +from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D +from paddle.nn.initializer import Uniform +from paddle.fluid.param_attr import ParamAttr +from paddle.utils.download import get_weights_path_from_url + +__all__ = [] + +model_urls = { + 'densenet121': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet121_pretrained.pdparams', + 'db1b239ed80a905290fd8b01d3af08e4'), + 'densenet161': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet161_pretrained.pdparams', + '62158869cb315098bd25ddbfd308a853'), + 'densenet169': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet169_pretrained.pdparams', + '82cc7c635c3f19098c748850efb2d796'), + 'densenet201': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet201_pretrained.pdparams', + '16ca29565a7712329cf9e36e02caaf58'), + 'densenet264': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet264_pretrained.pdparams', + '3270ce516b85370bba88cfdd9f60bff4'), +} + + +class BNACConvLayer(nn.Layer): + + def __init__(self, + num_channels, + num_filters, + filter_size, + stride=1, + pad=0, + groups=1, + act="relu"): + super(BNACConvLayer, self).__init__() + self._batch_norm = BatchNorm(num_channels, act=act) + + self._conv = Conv2D(in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=pad, + groups=groups, + weight_attr=ParamAttr(), + bias_attr=False) + + def forward(self, input): + y = self._batch_norm(input) + y = self._conv(y) + return y + + +class DenseLayer(nn.Layer): + + def __init__(self, num_channels, growth_rate, bn_size, dropout): + super(DenseLayer, self).__init__() + self.dropout = dropout + + self.bn_ac_func1 = BNACConvLayer(num_channels=num_channels, + num_filters=bn_size * growth_rate, + filter_size=1, + pad=0, + stride=1) + + self.bn_ac_func2 = BNACConvLayer(num_channels=bn_size * growth_rate, + num_filters=growth_rate, + filter_size=3, + pad=1, + stride=1) + + if dropout: + self.dropout_func = Dropout(p=dropout, mode="downscale_in_infer") + + def forward(self, input): + conv = self.bn_ac_func1(input) + conv = self.bn_ac_func2(conv) + if self.dropout: + conv = self.dropout_func(conv) + conv = paddle.concat([input, conv], axis=1) + return conv + + +class DenseBlock(nn.Layer): + + def __init__(self, + num_channels, + num_layers, + bn_size, + growth_rate, + dropout, + name=None): + super(DenseBlock, self).__init__() + self.dropout = dropout + self.dense_layer_func = [] + + pre_channel = num_channels + for layer in range(num_layers): + self.dense_layer_func.append( + self.add_sublayer( + "{}_{}".format(name, layer + 1), + DenseLayer(num_channels=pre_channel, + growth_rate=growth_rate, + bn_size=bn_size, + dropout=dropout))) + pre_channel = pre_channel + growth_rate + + def forward(self, input): + conv = input + for func in self.dense_layer_func: + conv = func(conv) + return conv + + +class TransitionLayer(nn.Layer): + + def __init__(self, num_channels, num_output_features): + super(TransitionLayer, self).__init__() + + self.conv_ac_func = BNACConvLayer(num_channels=num_channels, + num_filters=num_output_features, + filter_size=1, + pad=0, + stride=1) + + self.pool2d_avg = AvgPool2D(kernel_size=2, stride=2, padding=0) + + def forward(self, input): + y = self.conv_ac_func(input) + y = self.pool2d_avg(y) + return y + + +class ConvBNLayer(nn.Layer): + + def __init__(self, + num_channels, + num_filters, + filter_size, + stride=1, + pad=0, + groups=1, + act="relu"): + super(ConvBNLayer, self).__init__() + + self._conv = Conv2D(in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=pad, + groups=groups, + weight_attr=ParamAttr(), + bias_attr=False) + self._batch_norm = BatchNorm(num_filters, act=act) + + def forward(self, input): + y = self._conv(input) + y = self._batch_norm(y) + return y + + +class DenseNet(nn.Layer): + """DenseNet model from + `"Densely Connected Convolutional Networks" `_. + + Args: + layers (int, optional): Layers of DenseNet. Default: 121. + bn_size (int, optional): Expansion of growth rate in the middle layer. Default: 4. + dropout (float, optional): Dropout rate. Default: :math:`0.0`. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import DenseNet + + # build model + densenet = DenseNet() + + x = paddle.rand([1, 3, 224, 224]) + out = densenet(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, + layers=121, + bn_size=4, + dropout=0., + num_classes=1000, + with_pool=True): + super(DenseNet, self).__init__() + self.num_classes = num_classes + self.with_pool = with_pool + supported_layers = [121, 161, 169, 201, 264] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + densenet_spec = { + 121: (64, 32, [6, 12, 24, 16]), + 161: (96, 48, [6, 12, 36, 24]), + 169: (64, 32, [6, 12, 32, 32]), + 201: (64, 32, [6, 12, 48, 32]), + 264: (64, 32, [6, 12, 64, 48]) + } + num_init_features, growth_rate, block_config = densenet_spec[layers] + + self.conv1_func = ConvBNLayer(num_channels=3, + num_filters=num_init_features, + filter_size=7, + stride=2, + pad=3, + act='relu') + self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1) + self.block_config = block_config + self.dense_block_func_list = [] + self.transition_func_list = [] + pre_num_channels = num_init_features + num_features = num_init_features + for i, num_layers in enumerate(block_config): + self.dense_block_func_list.append( + self.add_sublayer( + "db_conv_{}".format(i + 2), + DenseBlock(num_channels=pre_num_channels, + num_layers=num_layers, + bn_size=bn_size, + growth_rate=growth_rate, + dropout=dropout, + name='conv' + str(i + 2)))) + + num_features = num_features + num_layers * growth_rate + pre_num_channels = num_features + + if i != len(block_config) - 1: + self.transition_func_list.append( + self.add_sublayer( + "tr_conv{}_blk".format(i + 2), + TransitionLayer(num_channels=pre_num_channels, + num_output_features=num_features // 2))) + pre_num_channels = num_features // 2 + num_features = num_features // 2 + + self.batch_norm = BatchNorm(num_features, act="relu") + if self.with_pool: + self.pool2d_avg = AdaptiveAvgPool2D(1) + + if self.num_classes > 0: + stdv = 1.0 / math.sqrt(num_features * 1.0) + self.out = Linear( + num_features, + num_classes, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr()) + + def forward(self, input): + conv = self.conv1_func(input) + conv = self.pool2d_max(conv) + + for i, num_layers in enumerate(self.block_config): + conv = self.dense_block_func_list[i](conv) + if i != len(self.block_config) - 1: + conv = self.transition_func_list[i](conv) + + conv = self.batch_norm(conv) + + if self.with_pool: + y = self.pool2d_avg(conv) + + if self.num_classes > 0: + y = paddle.flatten(y, start_axis=1, stop_axis=-1) + y = self.out(y) + + return y + + +def _densenet(arch, layers, pretrained, **kwargs): + model = DenseNet(layers=layers, **kwargs) + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + + return model + + +def densenet121(pretrained=False, **kwargs): + """DenseNet 121-layer model from + `"Densely Connected Convolutional Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet 121-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import densenet121 + + # build model + model = densenet121() + + # build model and load imagenet pretrained weight + # model = densenet121(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _densenet('densenet121', 121, pretrained, **kwargs) + + +def densenet161(pretrained=False, **kwargs): + """DenseNet 161-layer model from + `"Densely Connected Convolutional Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet 161-layer model. + + Examples: + .. code-block:: python + + from paddle.vision.models import densenet161 + + # build model + model = densenet161() + + # build model and load imagenet pretrained weight + # model = densenet161(pretrained=True) + """ + return _densenet('densenet161', 161, pretrained, **kwargs) + + +def densenet169(pretrained=False, **kwargs): + """DenseNet 169-layer model from + `"Densely Connected Convolutional Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet 169-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import densenet169 + + # build model + model = densenet169() + + # build model and load imagenet pretrained weight + # model = densenet169(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _densenet('densenet169', 169, pretrained, **kwargs) + + +def densenet201(pretrained=False, **kwargs): + """DenseNet 201-layer model from + `"Densely Connected Convolutional Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet 201-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import densenet201 + + # build model + model = densenet201() + + # build model and load imagenet pretrained weight + # model = densenet201(pretrained=True) + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _densenet('densenet201', 201, pretrained, **kwargs) + + +def densenet264(pretrained=False, **kwargs): + """DenseNet 264-layer model from + `"Densely Connected Convolutional Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`DenseNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of DenseNet 264-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import densenet264 + + # build model + model = densenet264() + + # build model and load imagenet pretrained weight + # model = densenet264(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _densenet('densenet264', 264, pretrained, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/googlenet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/googlenet.py new file mode 100644 index 0000000000000000000000000000000000000000..b5fc9ae4ab245c237afc63859f697e311f49da39 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/googlenet.py @@ -0,0 +1,266 @@ +# Copyright (c) 2021 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. + +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + +from paddle.nn import Conv2D, Linear, Dropout +from paddle.nn import MaxPool2D, AvgPool2D, AdaptiveAvgPool2D +from paddle.nn.initializer import Uniform +from paddle.fluid.param_attr import ParamAttr +from paddle.utils.download import get_weights_path_from_url + +__all__ = [] + +model_urls = { + "googlenet": + ("https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/GoogLeNet_pretrained.pdparams", + "80c06f038e905c53ab32c40eca6e26ae") +} + + +def xavier(channels, filter_size): + stdv = (3.0 / (filter_size**2 * channels))**0.5 + param_attr = ParamAttr(initializer=Uniform(-stdv, stdv)) + return param_attr + + +class ConvLayer(nn.Layer): + + def __init__(self, + num_channels, + num_filters, + filter_size, + stride=1, + groups=1): + super(ConvLayer, self).__init__() + + self._conv = Conv2D(in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=(filter_size - 1) // 2, + groups=groups, + bias_attr=False) + + def forward(self, inputs): + y = self._conv(inputs) + return y + + +class Inception(nn.Layer): + + def __init__(self, input_channels, output_channels, filter1, filter3R, + filter3, filter5R, filter5, proj): + super(Inception, self).__init__() + + self._conv1 = ConvLayer(input_channels, filter1, 1) + self._conv3r = ConvLayer(input_channels, filter3R, 1) + self._conv3 = ConvLayer(filter3R, filter3, 3) + self._conv5r = ConvLayer(input_channels, filter5R, 1) + self._conv5 = ConvLayer(filter5R, filter5, 5) + self._pool = MaxPool2D(kernel_size=3, stride=1, padding=1) + + self._convprj = ConvLayer(input_channels, proj, 1) + + def forward(self, inputs): + conv1 = self._conv1(inputs) + + conv3r = self._conv3r(inputs) + conv3 = self._conv3(conv3r) + + conv5r = self._conv5r(inputs) + conv5 = self._conv5(conv5r) + + pool = self._pool(inputs) + convprj = self._convprj(pool) + + cat = paddle.concat([conv1, conv3, conv5, convprj], axis=1) + cat = F.relu(cat) + return cat + + +class GoogLeNet(nn.Layer): + """GoogLeNet (Inception v1) model architecture from + `"Going Deeper with Convolutions" `_. + + Args: + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of GoogLeNet (Inception v1) model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import GoogLeNet + + # build model + model = GoogLeNet() + + x = paddle.rand([1, 3, 224, 224]) + out, out1, out2 = model(x) + + print(out.shape, out1.shape, out2.shape) + # [1, 1000] [1, 1000] [1, 1000] + """ + + def __init__(self, num_classes=1000, with_pool=True): + super(GoogLeNet, self).__init__() + self.num_classes = num_classes + self.with_pool = with_pool + + self._conv = ConvLayer(3, 64, 7, 2) + self._pool = MaxPool2D(kernel_size=3, stride=2) + self._conv_1 = ConvLayer(64, 64, 1) + self._conv_2 = ConvLayer(64, 192, 3) + + self._ince3a = Inception(192, 192, 64, 96, 128, 16, 32, 32) + self._ince3b = Inception(256, 256, 128, 128, 192, 32, 96, 64) + + self._ince4a = Inception(480, 480, 192, 96, 208, 16, 48, 64) + self._ince4b = Inception(512, 512, 160, 112, 224, 24, 64, 64) + self._ince4c = Inception(512, 512, 128, 128, 256, 24, 64, 64) + self._ince4d = Inception(512, 512, 112, 144, 288, 32, 64, 64) + self._ince4e = Inception(528, 528, 256, 160, 320, 32, 128, 128) + + self._ince5a = Inception(832, 832, 256, 160, 320, 32, 128, 128) + self._ince5b = Inception(832, 832, 384, 192, 384, 48, 128, 128) + + if with_pool: + # out + self._pool_5 = AdaptiveAvgPool2D(1) + # out1 + self._pool_o1 = AvgPool2D(kernel_size=5, stride=3) + # out2 + self._pool_o2 = AvgPool2D(kernel_size=5, stride=3) + + if num_classes > 0: + # out + self._drop = Dropout(p=0.4, mode="downscale_in_infer") + self._fc_out = Linear(1024, + num_classes, + weight_attr=xavier(1024, 1)) + + # out1 + self._conv_o1 = ConvLayer(512, 128, 1) + self._fc_o1 = Linear(1152, 1024, weight_attr=xavier(2048, 1)) + self._drop_o1 = Dropout(p=0.7, mode="downscale_in_infer") + self._out1 = Linear(1024, num_classes, weight_attr=xavier(1024, 1)) + + # out2 + self._conv_o2 = ConvLayer(528, 128, 1) + self._fc_o2 = Linear(1152, 1024, weight_attr=xavier(2048, 1)) + self._drop_o2 = Dropout(p=0.7, mode="downscale_in_infer") + self._out2 = Linear(1024, num_classes, weight_attr=xavier(1024, 1)) + + def forward(self, inputs): + x = self._conv(inputs) + x = self._pool(x) + x = self._conv_1(x) + x = self._conv_2(x) + x = self._pool(x) + + x = self._ince3a(x) + x = self._ince3b(x) + x = self._pool(x) + + ince4a = self._ince4a(x) + x = self._ince4b(ince4a) + x = self._ince4c(x) + ince4d = self._ince4d(x) + x = self._ince4e(ince4d) + x = self._pool(x) + + x = self._ince5a(x) + ince5b = self._ince5b(x) + + out, out1, out2 = ince5b, ince4a, ince4d + + if self.with_pool: + out = self._pool_5(out) + out1 = self._pool_o1(out1) + out2 = self._pool_o2(out2) + + if self.num_classes > 0: + out = self._drop(out) + out = paddle.squeeze(out, axis=[2, 3]) + out = self._fc_out(out) + + out1 = self._conv_o1(out1) + out1 = paddle.flatten(out1, start_axis=1, stop_axis=-1) + out1 = self._fc_o1(out1) + out1 = F.relu(out1) + out1 = self._drop_o1(out1) + out1 = self._out1(out1) + + out2 = self._conv_o2(out2) + out2 = paddle.flatten(out2, start_axis=1, stop_axis=-1) + out2 = self._fc_o2(out2) + out2 = self._drop_o2(out2) + out2 = self._out2(out2) + + return [out, out1, out2] + + +def googlenet(pretrained=False, **kwargs): + """GoogLeNet (Inception v1) model architecture from + `"Going Deeper with Convolutions" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`GoogLeNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of GoogLeNet (Inception v1) model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import googlenet + + # build model + model = googlenet() + + # build model and load imagenet pretrained weight + # model = googlenet(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out, out1, out2 = model(x) + + print(out.shape, out1.shape, out2.shape) + # [1, 1000] [1, 1000] [1, 1000] + """ + model = GoogLeNet(**kwargs) + arch = "googlenet" + if pretrained: + assert ( + arch in model_urls + ), "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/inceptionv3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/inceptionv3.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a06de3d85e7b07cfc3d0ec60e19f9e9a5e7594 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/inceptionv3.py @@ -0,0 +1,552 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +import paddle.nn as nn +from paddle.nn import Linear, Dropout +from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D +from paddle.nn.initializer import Uniform +from paddle.fluid.param_attr import ParamAttr + +from paddle.utils.download import get_weights_path_from_url +from ..ops import ConvNormActivation + +__all__ = [] + +model_urls = { + "inception_v3": + ("https://paddle-hapi.bj.bcebos.com/models/inception_v3.pdparams", + "649a4547c3243e8b59c656f41fe330b8") +} + + +class InceptionStem(nn.Layer): + + def __init__(self): + super().__init__() + self.conv_1a_3x3 = ConvNormActivation(in_channels=3, + out_channels=32, + kernel_size=3, + stride=2, + padding=0, + activation_layer=nn.ReLU) + self.conv_2a_3x3 = ConvNormActivation(in_channels=32, + out_channels=32, + kernel_size=3, + stride=1, + padding=0, + activation_layer=nn.ReLU) + self.conv_2b_3x3 = ConvNormActivation(in_channels=32, + out_channels=64, + kernel_size=3, + padding=1, + activation_layer=nn.ReLU) + + self.max_pool = MaxPool2D(kernel_size=3, stride=2, padding=0) + self.conv_3b_1x1 = ConvNormActivation(in_channels=64, + out_channels=80, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.conv_4a_3x3 = ConvNormActivation(in_channels=80, + out_channels=192, + kernel_size=3, + padding=0, + activation_layer=nn.ReLU) + + def forward(self, x): + x = self.conv_1a_3x3(x) + x = self.conv_2a_3x3(x) + x = self.conv_2b_3x3(x) + x = self.max_pool(x) + x = self.conv_3b_1x1(x) + x = self.conv_4a_3x3(x) + x = self.max_pool(x) + return x + + +class InceptionA(nn.Layer): + + def __init__(self, num_channels, pool_features): + super().__init__() + self.branch1x1 = ConvNormActivation(in_channels=num_channels, + out_channels=64, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + + self.branch5x5_1 = ConvNormActivation(in_channels=num_channels, + out_channels=48, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch5x5_2 = ConvNormActivation(in_channels=48, + out_channels=64, + kernel_size=5, + padding=2, + activation_layer=nn.ReLU) + + self.branch3x3dbl_1 = ConvNormActivation(in_channels=num_channels, + out_channels=64, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3dbl_2 = ConvNormActivation(in_channels=64, + out_channels=96, + kernel_size=3, + padding=1, + activation_layer=nn.ReLU) + self.branch3x3dbl_3 = ConvNormActivation(in_channels=96, + out_channels=96, + kernel_size=3, + padding=1, + activation_layer=nn.ReLU) + + self.branch_pool = AvgPool2D(kernel_size=3, + stride=1, + padding=1, + exclusive=False) + self.branch_pool_conv = ConvNormActivation(in_channels=num_channels, + out_channels=pool_features, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + + def forward(self, x): + branch1x1 = self.branch1x1(x) + branch5x5 = self.branch5x5_1(x) + branch5x5 = self.branch5x5_2(branch5x5) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = self.branch_pool(x) + branch_pool = self.branch_pool_conv(branch_pool) + x = paddle.concat([branch1x1, branch5x5, branch3x3dbl, branch_pool], + axis=1) + return x + + +class InceptionB(nn.Layer): + + def __init__(self, num_channels): + super().__init__() + self.branch3x3 = ConvNormActivation(in_channels=num_channels, + out_channels=384, + kernel_size=3, + stride=2, + padding=0, + activation_layer=nn.ReLU) + + self.branch3x3dbl_1 = ConvNormActivation(in_channels=num_channels, + out_channels=64, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3dbl_2 = ConvNormActivation(in_channels=64, + out_channels=96, + kernel_size=3, + padding=1, + activation_layer=nn.ReLU) + self.branch3x3dbl_3 = ConvNormActivation(in_channels=96, + out_channels=96, + kernel_size=3, + stride=2, + padding=0, + activation_layer=nn.ReLU) + + self.branch_pool = MaxPool2D(kernel_size=3, stride=2) + + def forward(self, x): + branch3x3 = self.branch3x3(x) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = self.branch_pool(x) + + x = paddle.concat([branch3x3, branch3x3dbl, branch_pool], axis=1) + + return x + + +class InceptionC(nn.Layer): + + def __init__(self, num_channels, channels_7x7): + super().__init__() + self.branch1x1 = ConvNormActivation(in_channels=num_channels, + out_channels=192, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + + self.branch7x7_1 = ConvNormActivation(in_channels=num_channels, + out_channels=channels_7x7, + kernel_size=1, + stride=1, + padding=0, + activation_layer=nn.ReLU) + self.branch7x7_2 = ConvNormActivation(in_channels=channels_7x7, + out_channels=channels_7x7, + kernel_size=(1, 7), + stride=1, + padding=(0, 3), + activation_layer=nn.ReLU) + self.branch7x7_3 = ConvNormActivation(in_channels=channels_7x7, + out_channels=192, + kernel_size=(7, 1), + stride=1, + padding=(3, 0), + activation_layer=nn.ReLU) + + self.branch7x7dbl_1 = ConvNormActivation(in_channels=num_channels, + out_channels=channels_7x7, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch7x7dbl_2 = ConvNormActivation(in_channels=channels_7x7, + out_channels=channels_7x7, + kernel_size=(7, 1), + padding=(3, 0), + activation_layer=nn.ReLU) + self.branch7x7dbl_3 = ConvNormActivation(in_channels=channels_7x7, + out_channels=channels_7x7, + kernel_size=(1, 7), + padding=(0, 3), + activation_layer=nn.ReLU) + self.branch7x7dbl_4 = ConvNormActivation(in_channels=channels_7x7, + out_channels=channels_7x7, + kernel_size=(7, 1), + padding=(3, 0), + activation_layer=nn.ReLU) + self.branch7x7dbl_5 = ConvNormActivation(in_channels=channels_7x7, + out_channels=192, + kernel_size=(1, 7), + padding=(0, 3), + activation_layer=nn.ReLU) + + self.branch_pool = AvgPool2D(kernel_size=3, + stride=1, + padding=1, + exclusive=False) + self.branch_pool_conv = ConvNormActivation(in_channels=num_channels, + out_channels=192, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + + def forward(self, x): + branch1x1 = self.branch1x1(x) + + branch7x7 = self.branch7x7_1(x) + branch7x7 = self.branch7x7_2(branch7x7) + branch7x7 = self.branch7x7_3(branch7x7) + + branch7x7dbl = self.branch7x7dbl_1(x) + branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) + + branch_pool = self.branch_pool(x) + branch_pool = self.branch_pool_conv(branch_pool) + + x = paddle.concat([branch1x1, branch7x7, branch7x7dbl, branch_pool], + axis=1) + + return x + + +class InceptionD(nn.Layer): + + def __init__(self, num_channels): + super().__init__() + self.branch3x3_1 = ConvNormActivation(in_channels=num_channels, + out_channels=192, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3_2 = ConvNormActivation(in_channels=192, + out_channels=320, + kernel_size=3, + stride=2, + padding=0, + activation_layer=nn.ReLU) + + self.branch7x7x3_1 = ConvNormActivation(in_channels=num_channels, + out_channels=192, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch7x7x3_2 = ConvNormActivation(in_channels=192, + out_channels=192, + kernel_size=(1, 7), + padding=(0, 3), + activation_layer=nn.ReLU) + self.branch7x7x3_3 = ConvNormActivation(in_channels=192, + out_channels=192, + kernel_size=(7, 1), + padding=(3, 0), + activation_layer=nn.ReLU) + self.branch7x7x3_4 = ConvNormActivation(in_channels=192, + out_channels=192, + kernel_size=3, + stride=2, + padding=0, + activation_layer=nn.ReLU) + + self.branch_pool = MaxPool2D(kernel_size=3, stride=2) + + def forward(self, x): + branch3x3 = self.branch3x3_1(x) + branch3x3 = self.branch3x3_2(branch3x3) + + branch7x7x3 = self.branch7x7x3_1(x) + branch7x7x3 = self.branch7x7x3_2(branch7x7x3) + branch7x7x3 = self.branch7x7x3_3(branch7x7x3) + branch7x7x3 = self.branch7x7x3_4(branch7x7x3) + + branch_pool = self.branch_pool(x) + + x = paddle.concat([branch3x3, branch7x7x3, branch_pool], axis=1) + return x + + +class InceptionE(nn.Layer): + + def __init__(self, num_channels): + super().__init__() + self.branch1x1 = ConvNormActivation(in_channels=num_channels, + out_channels=320, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3_1 = ConvNormActivation(in_channels=num_channels, + out_channels=384, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3_2a = ConvNormActivation(in_channels=384, + out_channels=384, + kernel_size=(1, 3), + padding=(0, 1), + activation_layer=nn.ReLU) + self.branch3x3_2b = ConvNormActivation(in_channels=384, + out_channels=384, + kernel_size=(3, 1), + padding=(1, 0), + activation_layer=nn.ReLU) + + self.branch3x3dbl_1 = ConvNormActivation(in_channels=num_channels, + out_channels=448, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + self.branch3x3dbl_2 = ConvNormActivation(in_channels=448, + out_channels=384, + kernel_size=3, + padding=1, + activation_layer=nn.ReLU) + self.branch3x3dbl_3a = ConvNormActivation(in_channels=384, + out_channels=384, + kernel_size=(1, 3), + padding=(0, 1), + activation_layer=nn.ReLU) + self.branch3x3dbl_3b = ConvNormActivation(in_channels=384, + out_channels=384, + kernel_size=(3, 1), + padding=(1, 0), + activation_layer=nn.ReLU) + + self.branch_pool = AvgPool2D(kernel_size=3, + stride=1, + padding=1, + exclusive=False) + self.branch_pool_conv = ConvNormActivation(in_channels=num_channels, + out_channels=192, + kernel_size=1, + padding=0, + activation_layer=nn.ReLU) + + def forward(self, x): + branch1x1 = self.branch1x1(x) + + branch3x3 = self.branch3x3_1(x) + branch3x3 = [ + self.branch3x3_2a(branch3x3), + self.branch3x3_2b(branch3x3), + ] + branch3x3 = paddle.concat(branch3x3, axis=1) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = [ + self.branch3x3dbl_3a(branch3x3dbl), + self.branch3x3dbl_3b(branch3x3dbl), + ] + branch3x3dbl = paddle.concat(branch3x3dbl, axis=1) + + branch_pool = self.branch_pool(x) + branch_pool = self.branch_pool_conv(branch_pool) + + x = paddle.concat([branch1x1, branch3x3, branch3x3dbl, branch_pool], + axis=1) + return x + + +class InceptionV3(nn.Layer): + """Inception v3 model from + `"Rethinking the Inception Architecture for Computer Vision" `_. + + Args: + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of Inception v3 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import InceptionV3 + + inception_v3 = InceptionV3() + + x = paddle.rand([1, 3, 299, 299]) + out = inception_v3(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, num_classes=1000, with_pool=True): + super().__init__() + self.num_classes = num_classes + self.with_pool = with_pool + self.layers_config = { + "inception_a": [[192, 256, 288], [32, 64, 64]], + "inception_b": [288], + "inception_c": [[768, 768, 768, 768], [128, 160, 160, 192]], + "inception_d": [768], + "inception_e": [1280, 2048] + } + + inception_a_list = self.layers_config["inception_a"] + inception_c_list = self.layers_config["inception_c"] + inception_b_list = self.layers_config["inception_b"] + inception_d_list = self.layers_config["inception_d"] + inception_e_list = self.layers_config["inception_e"] + + self.inception_stem = InceptionStem() + + self.inception_block_list = nn.LayerList() + for i in range(len(inception_a_list[0])): + inception_a = InceptionA(inception_a_list[0][i], + inception_a_list[1][i]) + self.inception_block_list.append(inception_a) + + for i in range(len(inception_b_list)): + inception_b = InceptionB(inception_b_list[i]) + self.inception_block_list.append(inception_b) + + for i in range(len(inception_c_list[0])): + inception_c = InceptionC(inception_c_list[0][i], + inception_c_list[1][i]) + self.inception_block_list.append(inception_c) + + for i in range(len(inception_d_list)): + inception_d = InceptionD(inception_d_list[i]) + self.inception_block_list.append(inception_d) + + for i in range(len(inception_e_list)): + inception_e = InceptionE(inception_e_list[i]) + self.inception_block_list.append(inception_e) + + if with_pool: + self.avg_pool = AdaptiveAvgPool2D(1) + + if num_classes > 0: + self.dropout = Dropout(p=0.2, mode="downscale_in_infer") + stdv = 1.0 / math.sqrt(2048 * 1.0) + self.fc = Linear( + 2048, + num_classes, + weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)), + bias_attr=ParamAttr()) + + def forward(self, x): + x = self.inception_stem(x) + for inception_block in self.inception_block_list: + x = inception_block(x) + + if self.with_pool: + x = self.avg_pool(x) + + if self.num_classes > 0: + x = paddle.reshape(x, shape=[-1, 2048]) + x = self.dropout(x) + x = self.fc(x) + return x + + +def inception_v3(pretrained=False, **kwargs): + """Inception v3 model from + `"Rethinking the Inception Architecture for Computer Vision" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`InceptionV3 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of Inception v3 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import inception_v3 + + # build model + model = inception_v3() + + # build model and load imagenet pretrained weight + # model = inception_v3(pretrained=True) + + x = paddle.rand([1, 3, 299, 299]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model = InceptionV3(**kwargs) + arch = "inception_v3" + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/lenet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/lenet.py new file mode 100644 index 0000000000000000000000000000000000000000..1d446569a660715ad60f6154cbd1172d6ca27059 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/lenet.py @@ -0,0 +1,65 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +import paddle +import paddle.nn as nn + +__all__ = [] + + +class LeNet(nn.Layer): + """LeNet model from + `"Gradient-based learning applied to document recognition" `_. + + Args: + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 10. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of LeNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import LeNet + + model = LeNet() + + x = paddle.rand([1, 1, 28, 28]) + out = model(x) + + print(out.shape) + # [1, 10] + """ + + def __init__(self, num_classes=10): + super(LeNet, self).__init__() + self.num_classes = num_classes + self.features = nn.Sequential(nn.Conv2D(1, 6, 3, stride=1, padding=1), + nn.ReLU(), nn.MaxPool2D(2, 2), + nn.Conv2D(6, 16, 5, stride=1, padding=0), + nn.ReLU(), nn.MaxPool2D(2, 2)) + + if num_classes > 0: + self.fc = nn.Sequential(nn.Linear(400, 120), nn.Linear(120, 84), + nn.Linear(84, num_classes)) + + def forward(self, inputs): + x = self.features(inputs) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv1.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv1.py new file mode 100644 index 0000000000000000000000000000000000000000..6359fcffcdfad92b8adeade2521953e38ae0e44c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv1.py @@ -0,0 +1,260 @@ +# 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. + +import paddle +import paddle.nn as nn + +from paddle.utils.download import get_weights_path_from_url +from ..ops import ConvNormActivation + +__all__ = [] + +model_urls = { + 'mobilenetv1_1.0': + ('https://paddle-hapi.bj.bcebos.com/models/mobilenetv1_1.0.pdparams', + '3033ab1975b1670bef51545feb65fc45') +} + + +class DepthwiseSeparable(nn.Layer): + + def __init__(self, in_channels, out_channels1, out_channels2, num_groups, + stride, scale): + super(DepthwiseSeparable, self).__init__() + + self._depthwise_conv = ConvNormActivation(in_channels, + int(out_channels1 * scale), + kernel_size=3, + stride=stride, + padding=1, + groups=int(num_groups * + scale)) + + self._pointwise_conv = ConvNormActivation(int(out_channels1 * scale), + int(out_channels2 * scale), + kernel_size=1, + stride=1, + padding=0) + + def forward(self, x): + x = self._depthwise_conv(x) + x = self._pointwise_conv(x) + return x + + +class MobileNetV1(nn.Layer): + """MobileNetV1 model from + `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" `_. + + Args: + scale (float, optional): Scale of channels in each layer. Default: 1.0. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV1 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import MobileNetV1 + + model = MobileNetV1() + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, scale=1.0, num_classes=1000, with_pool=True): + super(MobileNetV1, self).__init__() + self.scale = scale + self.dwsl = [] + self.num_classes = num_classes + self.with_pool = with_pool + + self.conv1 = ConvNormActivation(in_channels=3, + out_channels=int(32 * scale), + kernel_size=3, + stride=2, + padding=1) + + dws21 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 32 * scale), + out_channels1=32, + out_channels2=64, + num_groups=32, + stride=1, + scale=scale), + name="conv2_1") + self.dwsl.append(dws21) + + dws22 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 64 * scale), + out_channels1=64, + out_channels2=128, + num_groups=64, + stride=2, + scale=scale), + name="conv2_2") + self.dwsl.append(dws22) + + dws31 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 128 * scale), + out_channels1=128, + out_channels2=128, + num_groups=128, + stride=1, + scale=scale), + name="conv3_1") + self.dwsl.append(dws31) + + dws32 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 128 * scale), + out_channels1=128, + out_channels2=256, + num_groups=128, + stride=2, + scale=scale), + name="conv3_2") + self.dwsl.append(dws32) + + dws41 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 256 * scale), + out_channels1=256, + out_channels2=256, + num_groups=256, + stride=1, + scale=scale), + name="conv4_1") + self.dwsl.append(dws41) + + dws42 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 256 * scale), + out_channels1=256, + out_channels2=512, + num_groups=256, + stride=2, + scale=scale), + name="conv4_2") + self.dwsl.append(dws42) + + for i in range(5): + tmp = self.add_sublayer(sublayer=DepthwiseSeparable( + in_channels=int(512 * scale), + out_channels1=512, + out_channels2=512, + num_groups=512, + stride=1, + scale=scale), + name="conv5_" + str(i + 1)) + self.dwsl.append(tmp) + + dws56 = self.add_sublayer(sublayer=DepthwiseSeparable( + in_channels=int(512 * scale), + out_channels1=512, + out_channels2=1024, + num_groups=512, + stride=2, + scale=scale), + name="conv5_6") + self.dwsl.append(dws56) + + dws6 = self.add_sublayer(sublayer=DepthwiseSeparable(in_channels=int( + 1024 * scale), + out_channels1=1024, + out_channels2=1024, + num_groups=1024, + stride=1, + scale=scale), + name="conv6") + self.dwsl.append(dws6) + + if with_pool: + self.pool2d_avg = nn.AdaptiveAvgPool2D(1) + + if num_classes > 0: + self.fc = nn.Linear(int(1024 * scale), num_classes) + + def forward(self, x): + x = self.conv1(x) + for dws in self.dwsl: + x = dws(x) + + if self.with_pool: + x = self.pool2d_avg(x) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x) + return x + + +def _mobilenet(arch, pretrained=False, **kwargs): + model = MobileNetV1(**kwargs) + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.load_dict(param) + + return model + + +def mobilenet_v1(pretrained=False, scale=1.0, **kwargs): + """MobileNetV1 from + `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + scale (float, optional): Scale of channels in each layer. Default: 1.0. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`MobileNetV1 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV1 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import mobilenet_v1 + + # build model + model = mobilenet_v1() + + # build model and load imagenet pretrained weight + # model = mobilenet_v1(pretrained=True) + + # build mobilenet v1 with scale=0.5 + model_scale = mobilenet_v1(scale=0.5) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model = _mobilenet('mobilenetv1_' + str(scale), + pretrained, + scale=scale, + **kwargs) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..88fa8ebf6e693c8ff88793c14be01c11ae45dd02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv2.py @@ -0,0 +1,224 @@ +# Copyright (c) 2022 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. + +import paddle +import paddle.nn as nn +from paddle.utils.download import get_weights_path_from_url + +from .utils import _make_divisible +from ..ops import ConvNormActivation + +__all__ = [] + +model_urls = { + 'mobilenetv2_1.0': + ('https://paddle-hapi.bj.bcebos.com/models/mobilenet_v2_x1.0.pdparams', + '0340af0a901346c8d46f4529882fb63d') +} + + +class InvertedResidual(nn.Layer): + + def __init__(self, + inp, + oup, + stride, + expand_ratio, + norm_layer=nn.BatchNorm2D): + super(InvertedResidual, self).__init__() + self.stride = stride + assert stride in [1, 2] + + hidden_dim = int(round(inp * expand_ratio)) + self.use_res_connect = self.stride == 1 and inp == oup + + layers = [] + if expand_ratio != 1: + layers.append( + ConvNormActivation(inp, + hidden_dim, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.ReLU6)) + layers.extend([ + ConvNormActivation(hidden_dim, + hidden_dim, + stride=stride, + groups=hidden_dim, + norm_layer=norm_layer, + activation_layer=nn.ReLU6), + nn.Conv2D(hidden_dim, oup, 1, 1, 0, bias_attr=False), + norm_layer(oup), + ]) + self.conv = nn.Sequential(*layers) + + def forward(self, x): + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + +class MobileNetV2(nn.Layer): + """MobileNetV2 model from + `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" `_. + + Args: + scale (float, optional): Scale of channels in each layer. Default: 1.0. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV2 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import MobileNetV2 + + model = MobileNetV2() + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, scale=1.0, num_classes=1000, with_pool=True): + super(MobileNetV2, self).__init__() + self.num_classes = num_classes + self.with_pool = with_pool + input_channel = 32 + last_channel = 1280 + + block = InvertedResidual + round_nearest = 8 + norm_layer = nn.BatchNorm2D + inverted_residual_setting = [ + [1, 16, 1, 1], + [6, 24, 2, 2], + [6, 32, 3, 2], + [6, 64, 4, 2], + [6, 96, 3, 1], + [6, 160, 3, 2], + [6, 320, 1, 1], + ] + + input_channel = _make_divisible(input_channel * scale, round_nearest) + self.last_channel = _make_divisible(last_channel * max(1.0, scale), + round_nearest) + features = [ + ConvNormActivation(3, + input_channel, + stride=2, + norm_layer=norm_layer, + activation_layer=nn.ReLU6) + ] + + for t, c, n, s in inverted_residual_setting: + output_channel = _make_divisible(c * scale, round_nearest) + for i in range(n): + stride = s if i == 0 else 1 + features.append( + block(input_channel, + output_channel, + stride, + expand_ratio=t, + norm_layer=norm_layer)) + input_channel = output_channel + + features.append( + ConvNormActivation(input_channel, + self.last_channel, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.ReLU6)) + + self.features = nn.Sequential(*features) + + if with_pool: + self.pool2d_avg = nn.AdaptiveAvgPool2D(1) + + if self.num_classes > 0: + self.classifier = nn.Sequential( + nn.Dropout(0.2), nn.Linear(self.last_channel, num_classes)) + + def forward(self, x): + x = self.features(x) + + if self.with_pool: + x = self.pool2d_avg(x) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.classifier(x) + return x + + +def _mobilenet(arch, pretrained=False, **kwargs): + model = MobileNetV2(**kwargs) + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.load_dict(param) + + return model + + +def mobilenet_v2(pretrained=False, scale=1.0, **kwargs): + """MobileNetV2 from + `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + scale (float, optional): Scale of channels in each layer. Default: 1.0. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`MobileNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV2 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import mobilenet_v2 + + # build model + model = mobilenet_v2() + + # build model and load imagenet pretrained weight + # model = mobilenet_v2(pretrained=True) + + # build mobilenet v2 with scale=0.5 + model = mobilenet_v2(scale=0.5) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model = _mobilenet('mobilenetv2_' + str(scale), + pretrained, + scale=scale, + **kwargs) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv3.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3c8520ec6c80e1db9bc8cd454c7066acbbf875 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/mobilenetv3.py @@ -0,0 +1,464 @@ +# Copyright (c) 2022 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +from paddle.utils.download import get_weights_path_from_url +from functools import partial + +from .utils import _make_divisible +from ..ops import ConvNormActivation + +__all__ = [] + +model_urls = { + "mobilenet_v3_small_x1.0": + ("https://paddle-hapi.bj.bcebos.com/models/mobilenet_v3_small_x1.0.pdparams", + "34fe0e7c1f8b00b2b056ad6788d0590c"), + "mobilenet_v3_large_x1.0": + ("https://paddle-hapi.bj.bcebos.com/models/mobilenet_v3_large_x1.0.pdparams", + "118db5792b4e183b925d8e8e334db3df"), +} + + +class SqueezeExcitation(nn.Layer): + """ + This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507 (see Fig. 1). + Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in eq. 3. + This code is based on the torchvision code with modifications. + You can also see at https://github.com/pytorch/vision/blob/main/torchvision/ops/misc.py#L127 + Args: + input_channels (int): Number of channels in the input image + squeeze_channels (int): Number of squeeze channels + activation (Callable[..., paddle.nn.Layer], optional): ``delta`` activation. Default: ``paddle.nn.ReLU`` + scale_activation (Callable[..., paddle.nn.Layer]): ``sigma`` activation. Default: ``paddle.nn.Sigmoid`` + """ + + def __init__(self, + input_channels, + squeeze_channels, + activation=nn.ReLU, + scale_activation=nn.Sigmoid): + super().__init__() + self.avgpool = nn.AdaptiveAvgPool2D(1) + self.fc1 = nn.Conv2D(input_channels, squeeze_channels, 1) + self.fc2 = nn.Conv2D(squeeze_channels, input_channels, 1) + self.activation = activation() + self.scale_activation = scale_activation() + + def _scale(self, input): + scale = self.avgpool(input) + scale = self.fc1(scale) + scale = self.activation(scale) + scale = self.fc2(scale) + return self.scale_activation(scale) + + def forward(self, input): + scale = self._scale(input) + return scale * input + + +class InvertedResidualConfig: + + def __init__(self, + in_channels, + kernel, + expanded_channels, + out_channels, + use_se, + activation, + stride, + scale=1.0): + self.in_channels = self.adjust_channels(in_channels, scale=scale) + self.kernel = kernel + self.expanded_channels = self.adjust_channels(expanded_channels, + scale=scale) + self.out_channels = self.adjust_channels(out_channels, scale=scale) + self.use_se = use_se + if activation is None: + self.activation_layer = None + elif activation == "relu": + self.activation_layer = nn.ReLU + elif activation == "hardswish": + self.activation_layer = nn.Hardswish + else: + raise RuntimeError( + "The activation function is not supported: {}".format( + activation)) + self.stride = stride + + @staticmethod + def adjust_channels(channels, scale=1.0): + return _make_divisible(channels * scale, 8) + + +class InvertedResidual(nn.Layer): + + def __init__(self, in_channels, expanded_channels, out_channels, + filter_size, stride, use_se, activation_layer, norm_layer): + super().__init__() + self.use_res_connect = stride == 1 and in_channels == out_channels + self.use_se = use_se + self.expand = in_channels != expanded_channels + + if self.expand: + self.expand_conv = ConvNormActivation( + in_channels=in_channels, + out_channels=expanded_channels, + kernel_size=1, + stride=1, + padding=0, + norm_layer=norm_layer, + activation_layer=activation_layer) + + self.bottleneck_conv = ConvNormActivation( + in_channels=expanded_channels, + out_channels=expanded_channels, + kernel_size=filter_size, + stride=stride, + padding=int((filter_size - 1) // 2), + groups=expanded_channels, + norm_layer=norm_layer, + activation_layer=activation_layer) + + if self.use_se: + self.mid_se = SqueezeExcitation(expanded_channels, + _make_divisible(expanded_channels // + 4), + scale_activation=nn.Hardsigmoid) + + self.linear_conv = ConvNormActivation(in_channels=expanded_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + norm_layer=norm_layer, + activation_layer=None) + + def forward(self, x): + identity = x + if self.expand: + x = self.expand_conv(x) + x = self.bottleneck_conv(x) + if self.use_se: + x = self.mid_se(x) + x = self.linear_conv(x) + if self.use_res_connect: + x = paddle.add(identity, x) + return x + + +class MobileNetV3(nn.Layer): + """MobileNetV3 model from + `"Searching for MobileNetV3" `_. + + Args: + config (list[InvertedResidualConfig]): MobileNetV3 depthwise blocks config. + last_channel (int): The number of channels on the penultimate layer. + scale (float, optional): Scale of channels in each layer. Default: 1.0. + num_classes (int, optional): Output dim of last fc layer. If num_classes <=0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + """ + + def __init__(self, + config, + last_channel, + scale=1.0, + num_classes=1000, + with_pool=True): + super().__init__() + + self.config = config + self.scale = scale + self.last_channel = last_channel + self.num_classes = num_classes + self.with_pool = with_pool + self.firstconv_in_channels = config[0].in_channels + self.lastconv_in_channels = config[-1].in_channels + self.lastconv_out_channels = self.lastconv_in_channels * 6 + norm_layer = partial(nn.BatchNorm2D, epsilon=0.001, momentum=0.99) + + self.conv = ConvNormActivation(in_channels=3, + out_channels=self.firstconv_in_channels, + kernel_size=3, + stride=2, + padding=1, + groups=1, + activation_layer=nn.Hardswish, + norm_layer=norm_layer) + + self.blocks = nn.Sequential(*[ + InvertedResidual(in_channels=cfg.in_channels, + expanded_channels=cfg.expanded_channels, + out_channels=cfg.out_channels, + filter_size=cfg.kernel, + stride=cfg.stride, + use_se=cfg.use_se, + activation_layer=cfg.activation_layer, + norm_layer=norm_layer) for cfg in self.config + ]) + + self.lastconv = ConvNormActivation( + in_channels=self.lastconv_in_channels, + out_channels=self.lastconv_out_channels, + kernel_size=1, + stride=1, + padding=0, + groups=1, + norm_layer=norm_layer, + activation_layer=nn.Hardswish) + + if with_pool: + self.avgpool = nn.AdaptiveAvgPool2D(1) + + if num_classes > 0: + self.classifier = nn.Sequential( + nn.Linear(self.lastconv_out_channels, self.last_channel), + nn.Hardswish(), nn.Dropout(p=0.2), + nn.Linear(self.last_channel, num_classes)) + + def forward(self, x): + x = self.conv(x) + x = self.blocks(x) + x = self.lastconv(x) + + if self.with_pool: + x = self.avgpool(x) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.classifier(x) + + return x + + +class MobileNetV3Small(MobileNetV3): + """MobileNetV3 Small architecture model from + `"Searching for MobileNetV3" `_. + + Args: + scale (float, optional): Scale of channels in each layer. Default: 1.0. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV3 Small architecture model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import MobileNetV3Small + + # build model + model = MobileNetV3Small(scale=1.0) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, scale=1.0, num_classes=1000, with_pool=True): + config = [ + InvertedResidualConfig(16, 3, 16, 16, True, "relu", 2, scale), + InvertedResidualConfig(16, 3, 72, 24, False, "relu", 2, scale), + InvertedResidualConfig(24, 3, 88, 24, False, "relu", 1, scale), + InvertedResidualConfig(24, 5, 96, 40, True, "hardswish", 2, scale), + InvertedResidualConfig(40, 5, 240, 40, True, "hardswish", 1, scale), + InvertedResidualConfig(40, 5, 240, 40, True, "hardswish", 1, scale), + InvertedResidualConfig(40, 5, 120, 48, True, "hardswish", 1, scale), + InvertedResidualConfig(48, 5, 144, 48, True, "hardswish", 1, scale), + InvertedResidualConfig(48, 5, 288, 96, True, "hardswish", 2, scale), + InvertedResidualConfig(96, 5, 576, 96, True, "hardswish", 1, scale), + InvertedResidualConfig(96, 5, 576, 96, True, "hardswish", 1, scale), + ] + last_channel = _make_divisible(1024 * scale, 8) + super().__init__(config, + last_channel=last_channel, + scale=scale, + with_pool=with_pool, + num_classes=num_classes) + + +class MobileNetV3Large(MobileNetV3): + """MobileNetV3 Large architecture model from + `"Searching for MobileNetV3" `_. + + Args: + scale (float, optional): Scale of channels in each layer. Default: 1.0. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV3 Large architecture model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import MobileNetV3Large + + # build model + model = MobileNetV3Large(scale=1.0) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, scale=1.0, num_classes=1000, with_pool=True): + config = [ + InvertedResidualConfig(16, 3, 16, 16, False, "relu", 1, scale), + InvertedResidualConfig(16, 3, 64, 24, False, "relu", 2, scale), + InvertedResidualConfig(24, 3, 72, 24, False, "relu", 1, scale), + InvertedResidualConfig(24, 5, 72, 40, True, "relu", 2, scale), + InvertedResidualConfig(40, 5, 120, 40, True, "relu", 1, scale), + InvertedResidualConfig(40, 5, 120, 40, True, "relu", 1, scale), + InvertedResidualConfig(40, 3, 240, 80, False, "hardswish", 2, + scale), + InvertedResidualConfig(80, 3, 200, 80, False, "hardswish", 1, + scale), + InvertedResidualConfig(80, 3, 184, 80, False, "hardswish", 1, + scale), + InvertedResidualConfig(80, 3, 184, 80, False, "hardswish", 1, + scale), + InvertedResidualConfig(80, 3, 480, 112, True, "hardswish", 1, + scale), + InvertedResidualConfig(112, 3, 672, 112, True, "hardswish", 1, + scale), + InvertedResidualConfig(112, 5, 672, 160, True, "hardswish", 2, + scale), + InvertedResidualConfig(160, 5, 960, 160, True, "hardswish", 1, + scale), + InvertedResidualConfig(160, 5, 960, 160, True, "hardswish", 1, + scale), + ] + last_channel = _make_divisible(1280 * scale, 8) + super().__init__(config, + last_channel=last_channel, + scale=scale, + with_pool=with_pool, + num_classes=num_classes) + + +def _mobilenet_v3(arch, pretrained=False, scale=1.0, **kwargs): + if arch == "mobilenet_v3_large": + model = MobileNetV3Large(scale=scale, **kwargs) + else: + model = MobileNetV3Small(scale=scale, **kwargs) + if pretrained: + arch = "{}_x{}".format(arch, scale) + assert ( + arch in model_urls + ), "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + return model + + +def mobilenet_v3_small(pretrained=False, scale=1.0, **kwargs): + """MobileNetV3 Small architecture model from + `"Searching for MobileNetV3" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + scale (float, optional): Scale of channels in each layer. Default: 1.0. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`MobileNetV3Small `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV3 Small architecture model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import mobilenet_v3_small + + # build model + model = mobilenet_v3_small() + + # build model and load imagenet pretrained weight + # model = mobilenet_v3_small(pretrained=True) + + # build mobilenet v3 small model with scale=0.5 + model = mobilenet_v3_small(scale=0.5) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model = _mobilenet_v3("mobilenet_v3_small", + scale=scale, + pretrained=pretrained, + **kwargs) + return model + + +def mobilenet_v3_large(pretrained=False, scale=1.0, **kwargs): + """MobileNetV3 Large architecture model from + `"Searching for MobileNetV3" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + scale (float, optional): Scale of channels in each layer. Default: 1.0. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`MobileNetV3Large `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of MobileNetV3 Large architecture model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import mobilenet_v3_large + + # build model + model = mobilenet_v3_large() + + # build model and load imagenet pretrained weight + # model = mobilenet_v3_large(pretrained=True) + + # build mobilenet v3 large model with scale=0.5 + model = mobilenet_v3_large(scale=0.5) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model = _mobilenet_v3("mobilenet_v3_large", + scale=scale, + pretrained=pretrained, + **kwargs) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/resnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf479c0572376ac58b956481cde512eba1db81a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/resnet.py @@ -0,0 +1,775 @@ +# 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. + +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn + +from paddle.utils.download import get_weights_path_from_url + +__all__ = [] + +model_urls = { + 'resnet18': ('https://paddle-hapi.bj.bcebos.com/models/resnet18.pdparams', + 'cf548f46534aa3560945be4b95cd11c4'), + 'resnet34': ('https://paddle-hapi.bj.bcebos.com/models/resnet34.pdparams', + '8d2275cf8706028345f78ac0e1d31969'), + 'resnet50': ('https://paddle-hapi.bj.bcebos.com/models/resnet50.pdparams', + 'ca6f485ee1ab0492d38f323885b0ad80'), + 'resnet101': ('https://paddle-hapi.bj.bcebos.com/models/resnet101.pdparams', + '02f35f034ca3858e1e54d4036443c92d'), + 'resnet152': ('https://paddle-hapi.bj.bcebos.com/models/resnet152.pdparams', + '7ad16a2f1e7333859ff986138630fd7a'), + 'resnext50_32x4d': + ('https://paddle-hapi.bj.bcebos.com/models/resnext50_32x4d.pdparams', + 'dc47483169be7d6f018fcbb7baf8775d'), + "resnext50_64x4d": + ('https://paddle-hapi.bj.bcebos.com/models/resnext50_64x4d.pdparams', + '063d4b483e12b06388529450ad7576db'), + 'resnext101_32x4d': + ('https://paddle-hapi.bj.bcebos.com/models/resnext101_32x4d.pdparams', + '967b090039f9de2c8d06fe994fb9095f'), + 'resnext101_64x4d': + ('https://paddle-hapi.bj.bcebos.com/models/resnext101_64x4d.pdparams', + '98e04e7ca616a066699230d769d03008'), + 'resnext152_32x4d': + ('https://paddle-hapi.bj.bcebos.com/models/resnext152_32x4d.pdparams', + '18ff0beee21f2efc99c4b31786107121'), + 'resnext152_64x4d': + ('https://paddle-hapi.bj.bcebos.com/models/resnext152_64x4d.pdparams', + '77c4af00ca42c405fa7f841841959379'), + 'wide_resnet50_2': + ('https://paddle-hapi.bj.bcebos.com/models/wide_resnet50_2.pdparams', + '0282f804d73debdab289bd9fea3fa6dc'), + 'wide_resnet101_2': + ('https://paddle-hapi.bj.bcebos.com/models/wide_resnet101_2.pdparams', + 'd4360a2d23657f059216f5d5a1a9ac93'), +} + + +class BasicBlock(nn.Layer): + expansion = 1 + + def __init__(self, + inplanes, + planes, + stride=1, + downsample=None, + groups=1, + base_width=64, + dilation=1, + norm_layer=None): + super(BasicBlock, self).__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2D + + if dilation > 1: + raise NotImplementedError( + "Dilation > 1 not supported in BasicBlock") + + self.conv1 = nn.Conv2D(inplanes, + planes, + 3, + padding=1, + stride=stride, + bias_attr=False) + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU() + self.conv2 = nn.Conv2D(planes, planes, 3, padding=1, bias_attr=False) + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class BottleneckBlock(nn.Layer): + + expansion = 4 + + def __init__(self, + inplanes, + planes, + stride=1, + downsample=None, + groups=1, + base_width=64, + dilation=1, + norm_layer=None): + super(BottleneckBlock, self).__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2D + width = int(planes * (base_width / 64.)) * groups + + self.conv1 = nn.Conv2D(inplanes, width, 1, bias_attr=False) + self.bn1 = norm_layer(width) + + self.conv2 = nn.Conv2D(width, + width, + 3, + padding=dilation, + stride=stride, + groups=groups, + dilation=dilation, + bias_attr=False) + self.bn2 = norm_layer(width) + + self.conv3 = nn.Conv2D(width, + planes * self.expansion, + 1, + bias_attr=False) + self.bn3 = norm_layer(planes * self.expansion) + self.relu = nn.ReLU() + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class ResNet(nn.Layer): + """ResNet model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + Block (BasicBlock|BottleneckBlock): Block module of model. + depth (int, optional): Layers of ResNet, Default: 50. + width (int, optional): Base width per convolution group for each convolution block, Default: 64. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + groups (int, optional): Number of groups for each convolution block, Default: 1. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import ResNet + from paddle.vision.models.resnet import BottleneckBlock, BasicBlock + + # build ResNet with 18 layers + resnet18 = ResNet(BasicBlock, 18) + + # build ResNet with 50 layers + resnet50 = ResNet(BottleneckBlock, 50) + + # build Wide ResNet model + wide_resnet50_2 = ResNet(BottleneckBlock, 50, width=64*2) + + # build ResNeXt model + resnext50_32x4d = ResNet(BottleneckBlock, 50, width=4, groups=32) + + x = paddle.rand([1, 3, 224, 224]) + out = resnet18(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, + block, + depth=50, + width=64, + num_classes=1000, + with_pool=True, + groups=1): + super(ResNet, self).__init__() + layer_cfg = { + 18: [2, 2, 2, 2], + 34: [3, 4, 6, 3], + 50: [3, 4, 6, 3], + 101: [3, 4, 23, 3], + 152: [3, 8, 36, 3] + } + layers = layer_cfg[depth] + self.groups = groups + self.base_width = width + self.num_classes = num_classes + self.with_pool = with_pool + self._norm_layer = nn.BatchNorm2D + + self.inplanes = 64 + self.dilation = 1 + + self.conv1 = nn.Conv2D(3, + self.inplanes, + kernel_size=7, + stride=2, + padding=3, + bias_attr=False) + self.bn1 = self._norm_layer(self.inplanes) + self.relu = nn.ReLU() + self.maxpool = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2) + self.layer4 = self._make_layer(block, 512, layers[3], stride=2) + if with_pool: + self.avgpool = nn.AdaptiveAvgPool2D((1, 1)) + + if num_classes > 0: + self.fc = nn.Linear(512 * block.expansion, num_classes) + + def _make_layer(self, block, planes, blocks, stride=1, dilate=False): + norm_layer = self._norm_layer + downsample = None + previous_dilation = self.dilation + if dilate: + self.dilation *= stride + stride = 1 + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2D(self.inplanes, + planes * block.expansion, + 1, + stride=stride, + bias_attr=False), + norm_layer(planes * block.expansion), + ) + + layers = [] + layers.append( + block(self.inplanes, planes, stride, downsample, self.groups, + self.base_width, previous_dilation, norm_layer)) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append( + block(self.inplanes, + planes, + groups=self.groups, + base_width=self.base_width, + norm_layer=norm_layer)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + if self.with_pool: + x = self.avgpool(x) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.fc(x) + + return x + + +def _resnet(arch, Block, depth, pretrained, **kwargs): + model = ResNet(Block, depth, **kwargs) + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + + return model + + +def resnet18(pretrained=False, **kwargs): + """ResNet 18-layer model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet 18-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnet18 + + # build model + model = resnet18() + + # build model and load imagenet pretrained weight + # model = resnet18(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _resnet('resnet18', BasicBlock, 18, pretrained, **kwargs) + + +def resnet34(pretrained=False, **kwargs): + """ResNet 34-layer model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet 34-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnet34 + + # build model + model = resnet34() + + # build model and load imagenet pretrained weight + # model = resnet34(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _resnet('resnet34', BasicBlock, 34, pretrained, **kwargs) + + +def resnet50(pretrained=False, **kwargs): + """ResNet 50-layer model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet 50-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnet50 + + # build model + model = resnet50() + + # build model and load imagenet pretrained weight + # model = resnet50(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _resnet('resnet50', BottleneckBlock, 50, pretrained, **kwargs) + + +def resnet101(pretrained=False, **kwargs): + """ResNet 101-layer model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet 101-layer. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnet101 + + # build model + model = resnet101() + + # build model and load imagenet pretrained weight + # model = resnet101(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _resnet('resnet101', BottleneckBlock, 101, pretrained, **kwargs) + + +def resnet152(pretrained=False, **kwargs): + """ResNet 152-layer model from + `"Deep Residual Learning for Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNet 152-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnet152 + + # build model + model = resnet152() + + # build model and load imagenet pretrained weight + # model = resnet152(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _resnet('resnet152', BottleneckBlock, 152, pretrained, **kwargs) + + +def resnext50_32x4d(pretrained=False, **kwargs): + """ResNeXt-50 32x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-50 32x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext50_32x4d + + # build model + model = resnext50_32x4d() + + # build model and load imagenet pretrained weight + # model = resnext50_32x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 32 + kwargs['width'] = 4 + return _resnet('resnext50_32x4d', BottleneckBlock, 50, pretrained, **kwargs) + + +def resnext50_64x4d(pretrained=False, **kwargs): + """ResNeXt-50 64x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-50 64x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext50_64x4d + + # build model + model = resnext50_64x4d() + + # build model and load imagenet pretrained weight + # model = resnext50_64x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 64 + kwargs['width'] = 4 + return _resnet('resnext50_64x4d', BottleneckBlock, 50, pretrained, **kwargs) + + +def resnext101_32x4d(pretrained=False, **kwargs): + """ResNeXt-101 32x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-101 32x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext101_32x4d + + # build model + model = resnext101_32x4d() + + # build model and load imagenet pretrained weight + # model = resnext101_32x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 32 + kwargs['width'] = 4 + return _resnet('resnext101_32x4d', BottleneckBlock, 101, pretrained, + **kwargs) + + +def resnext101_64x4d(pretrained=False, **kwargs): + """ResNeXt-101 64x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-101 64x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext101_64x4d + + # build model + model = resnext101_64x4d() + + # build model and load imagenet pretrained weight + # model = resnext101_64x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 64 + kwargs['width'] = 4 + return _resnet('resnext101_64x4d', BottleneckBlock, 101, pretrained, + **kwargs) + + +def resnext152_32x4d(pretrained=False, **kwargs): + """ResNeXt-152 32x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-152 32x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext152_32x4d + + # build model + model = resnext152_32x4d() + + # build model and load imagenet pretrained weight + # model = resnext152_32x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 32 + kwargs['width'] = 4 + return _resnet('resnext152_32x4d', BottleneckBlock, 152, pretrained, + **kwargs) + + +def resnext152_64x4d(pretrained=False, **kwargs): + """ResNeXt-152 64x4d model from + `"Aggregated Residual Transformations for Deep Neural Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ResNeXt-152 64x4d model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import resnext152_64x4d + + # build model + model = resnext152_64x4d() + + # build model and load imagenet pretrained weight + # model = resnext152_64x4d(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['groups'] = 64 + kwargs['width'] = 4 + return _resnet('resnext152_64x4d', BottleneckBlock, 152, pretrained, + **kwargs) + + +def wide_resnet50_2(pretrained=False, **kwargs): + """Wide ResNet-50-2 model from + `"Wide Residual Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of Wide ResNet-50-2 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import wide_resnet50_2 + + # build model + model = wide_resnet50_2() + + # build model and load imagenet pretrained weight + # model = wide_resnet50_2(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['width'] = 64 * 2 + return _resnet('wide_resnet50_2', BottleneckBlock, 50, pretrained, **kwargs) + + +def wide_resnet101_2(pretrained=False, **kwargs): + """Wide ResNet-101-2 model from + `"Wide Residual Networks" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ResNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of Wide ResNet-101-2 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import wide_resnet101_2 + + # build model + model = wide_resnet101_2() + + # build model and load imagenet pretrained weight + # model = wide_resnet101_2(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + kwargs['width'] = 64 * 2 + return _resnet('wide_resnet101_2', BottleneckBlock, 101, pretrained, + **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/shufflenetv2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..900a1928304ae492bdc4d11fda6c66a929f9f1b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/shufflenetv2.py @@ -0,0 +1,569 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +from paddle.nn import AdaptiveAvgPool2D, Linear, MaxPool2D +from paddle.utils.download import get_weights_path_from_url + +from ..ops import ConvNormActivation + +__all__ = [] + +model_urls = { + "shufflenet_v2_x0_25": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_25.pdparams", + "1e509b4c140eeb096bb16e214796d03b", + ), + "shufflenet_v2_x0_33": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_33.pdparams", + "3d7b3ab0eaa5c0927ff1026d31b729bd", + ), + "shufflenet_v2_x0_5": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_5.pdparams", + "5e5cee182a7793c4e4c73949b1a71bd4", + ), + "shufflenet_v2_x1_0": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x1_0.pdparams", + "122d42478b9e81eb49f8a9ede327b1a4", + ), + "shufflenet_v2_x1_5": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x1_5.pdparams", + "faced5827380d73531d0ee027c67826d", + ), + "shufflenet_v2_x2_0": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x2_0.pdparams", + "cd3dddcd8305e7bcd8ad14d1c69a5784", + ), + "shufflenet_v2_swish": ( + "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_swish.pdparams", + "adde0aa3b023e5b0c94a68be1c394b84", + ), +} + + +def create_activation_layer(act): + if act == "swish": + return nn.Swish + elif act == "relu": + return nn.ReLU + elif act is None: + return None + else: + raise RuntimeError( + "The activation function is not supported: {}".format(act)) + + +def channel_shuffle(x, groups): + batch_size, num_channels, height, width = x.shape[0:4] + channels_per_group = num_channels // groups + + # reshape + x = paddle.reshape( + x, shape=[batch_size, groups, channels_per_group, height, width]) + + # transpose + x = paddle.transpose(x, perm=[0, 2, 1, 3, 4]) + + # flatten + x = paddle.reshape(x, shape=[batch_size, num_channels, height, width]) + return x + + +class InvertedResidual(nn.Layer): + + def __init__(self, + in_channels, + out_channels, + stride, + activation_layer=nn.ReLU): + super(InvertedResidual, self).__init__() + self._conv_pw = ConvNormActivation(in_channels=in_channels // 2, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + groups=1, + activation_layer=activation_layer) + self._conv_dw = ConvNormActivation(in_channels=out_channels // 2, + out_channels=out_channels // 2, + kernel_size=3, + stride=stride, + padding=1, + groups=out_channels // 2, + activation_layer=None) + self._conv_linear = ConvNormActivation( + in_channels=out_channels // 2, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + groups=1, + activation_layer=activation_layer) + + def forward(self, inputs): + x1, x2 = paddle.split( + inputs, + num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2], + axis=1) + x2 = self._conv_pw(x2) + x2 = self._conv_dw(x2) + x2 = self._conv_linear(x2) + out = paddle.concat([x1, x2], axis=1) + return channel_shuffle(out, 2) + + +class InvertedResidualDS(nn.Layer): + + def __init__(self, + in_channels, + out_channels, + stride, + activation_layer=nn.ReLU): + super(InvertedResidualDS, self).__init__() + + # branch1 + self._conv_dw_1 = ConvNormActivation(in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + stride=stride, + padding=1, + groups=in_channels, + activation_layer=None) + self._conv_linear_1 = ConvNormActivation( + in_channels=in_channels, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + groups=1, + activation_layer=activation_layer) + # branch2 + self._conv_pw_2 = ConvNormActivation(in_channels=in_channels, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + groups=1, + activation_layer=activation_layer) + self._conv_dw_2 = ConvNormActivation(in_channels=out_channels // 2, + out_channels=out_channels // 2, + kernel_size=3, + stride=stride, + padding=1, + groups=out_channels // 2, + activation_layer=None) + self._conv_linear_2 = ConvNormActivation( + in_channels=out_channels // 2, + out_channels=out_channels // 2, + kernel_size=1, + stride=1, + padding=0, + groups=1, + activation_layer=activation_layer) + + def forward(self, inputs): + x1 = self._conv_dw_1(inputs) + x1 = self._conv_linear_1(x1) + x2 = self._conv_pw_2(inputs) + x2 = self._conv_dw_2(x2) + x2 = self._conv_linear_2(x2) + out = paddle.concat([x1, x2], axis=1) + + return channel_shuffle(out, 2) + + +class ShuffleNetV2(nn.Layer): + """ShuffleNetV2 model from + `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" `_. + + Args: + scale (float, optional): Scale of output channels. Default: True. + act (str, optional): Activation function of neural network. Default: "relu". + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import ShuffleNetV2 + + shufflenet_v2_swish = ShuffleNetV2(scale=1.0, act="swish") + x = paddle.rand([1, 3, 224, 224]) + out = shufflenet_v2_swish(x) + print(out.shape) + # [1, 1000] + """ + + def __init__(self, scale=1.0, act="relu", num_classes=1000, with_pool=True): + super(ShuffleNetV2, self).__init__() + self.scale = scale + self.num_classes = num_classes + self.with_pool = with_pool + stage_repeats = [4, 8, 4] + activation_layer = create_activation_layer(act) + + if scale == 0.25: + stage_out_channels = [-1, 24, 24, 48, 96, 512] + elif scale == 0.33: + stage_out_channels = [-1, 24, 32, 64, 128, 512] + elif scale == 0.5: + stage_out_channels = [-1, 24, 48, 96, 192, 1024] + elif scale == 1.0: + stage_out_channels = [-1, 24, 116, 232, 464, 1024] + elif scale == 1.5: + stage_out_channels = [-1, 24, 176, 352, 704, 1024] + elif scale == 2.0: + stage_out_channels = [-1, 24, 224, 488, 976, 2048] + else: + raise NotImplementedError("This scale size:[" + str(scale) + + "] is not implemented!") + # 1. conv1 + self._conv1 = ConvNormActivation(in_channels=3, + out_channels=stage_out_channels[1], + kernel_size=3, + stride=2, + padding=1, + activation_layer=activation_layer) + self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1) + + # 2. bottleneck sequences + self._block_list = [] + for stage_id, num_repeat in enumerate(stage_repeats): + for i in range(num_repeat): + if i == 0: + block = self.add_sublayer(sublayer=InvertedResidualDS( + in_channels=stage_out_channels[stage_id + 1], + out_channels=stage_out_channels[stage_id + 2], + stride=2, + activation_layer=activation_layer), + name=str(stage_id + 2) + "_" + + str(i + 1)) + else: + block = self.add_sublayer(sublayer=InvertedResidual( + in_channels=stage_out_channels[stage_id + 2], + out_channels=stage_out_channels[stage_id + 2], + stride=1, + activation_layer=activation_layer), + name=str(stage_id + 2) + "_" + + str(i + 1)) + self._block_list.append(block) + # 3. last_conv + self._last_conv = ConvNormActivation( + in_channels=stage_out_channels[-2], + out_channels=stage_out_channels[-1], + kernel_size=1, + stride=1, + padding=0, + activation_layer=activation_layer) + # 4. pool + if with_pool: + self._pool2d_avg = AdaptiveAvgPool2D(1) + + # 5. fc + if num_classes > 0: + self._out_c = stage_out_channels[-1] + self._fc = Linear(stage_out_channels[-1], num_classes) + + def forward(self, inputs): + x = self._conv1(inputs) + x = self._max_pool(x) + for inv in self._block_list: + x = inv(x) + x = self._last_conv(x) + + if self.with_pool: + x = self._pool2d_avg(x) + + if self.num_classes > 0: + x = paddle.flatten(x, start_axis=1, stop_axis=-1) + x = self._fc(x) + return x + + +def _shufflenet_v2(arch, pretrained=False, **kwargs): + model = ShuffleNetV2(**kwargs) + if pretrained: + assert ( + arch in model_urls + ), "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.set_dict(param) + return model + + +def shufflenet_v2_x0_25(pretrained=False, **kwargs): + """ShuffleNetV2 with 0.25x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.25x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x0_25 + + # build model + model = shufflenet_v2_x0_25() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x0_25(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x0_25", + scale=0.25, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_x0_33(pretrained=False, **kwargs): + """ShuffleNetV2 with 0.33x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.33x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x0_33 + + # build model + model = shufflenet_v2_x0_33() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x0_33(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x0_33", + scale=0.33, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_x0_5(pretrained=False, **kwargs): + """ShuffleNetV2 with 0.5x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.5x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x0_5 + + # build model + model = shufflenet_v2_x0_5() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x0_5(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x0_5", + scale=0.5, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_x1_0(pretrained=False, **kwargs): + """ShuffleNetV2 with 1.0x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 1.0x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x1_0 + + # build model + model = shufflenet_v2_x1_0() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x1_0(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x1_0", + scale=1.0, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_x1_5(pretrained=False, **kwargs): + """ShuffleNetV2 with 1.5x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 1.5x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x1_5 + + # build model + model = shufflenet_v2_x1_5() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x1_5(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x1_5", + scale=1.5, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_x2_0(pretrained=False, **kwargs): + """ShuffleNetV2 with 2.0x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 2.0x output channels. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_x2_0 + + # build model + model = shufflenet_v2_x2_0() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_x2_0(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_x2_0", + scale=2.0, + pretrained=pretrained, + **kwargs) + + +def shufflenet_v2_swish(pretrained=False, **kwargs): + """ShuffleNetV2 with swish activation function, as described in + `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with swish activation function. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import shufflenet_v2_swish + + # build model + model = shufflenet_v2_swish() + + # build model and load imagenet pretrained weight + # model = shufflenet_v2_swish(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _shufflenet_v2("shufflenet_v2_swish", + scale=1.0, + act="swish", + pretrained=pretrained, + **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/squeezenet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/squeezenet.py new file mode 100644 index 0000000000000000000000000000000000000000..997d50dca70cf9a049faa0db3ed1d678e8bb8b6f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/squeezenet.py @@ -0,0 +1,277 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + +from paddle.nn import Conv2D, Dropout +from paddle.nn import AdaptiveAvgPool2D, MaxPool2D +from paddle.fluid.param_attr import ParamAttr +from paddle.utils.download import get_weights_path_from_url + +__all__ = [] + +model_urls = { + 'squeezenet1_0': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/SqueezeNet1_0_pretrained.pdparams', + '30b95af60a2178f03cf9b66cd77e1db1'), + 'squeezenet1_1': + ('https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/SqueezeNet1_1_pretrained.pdparams', + 'a11250d3a1f91d7131fd095ebbf09eee'), +} + + +class MakeFireConv(nn.Layer): + + def __init__(self, input_channels, output_channels, filter_size, padding=0): + super(MakeFireConv, self).__init__() + self._conv = Conv2D(input_channels, + output_channels, + filter_size, + padding=padding, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + + def forward(self, x): + x = self._conv(x) + x = F.relu(x) + return x + + +class MakeFire(nn.Layer): + + def __init__(self, input_channels, squeeze_channels, expand1x1_channels, + expand3x3_channels): + super(MakeFire, self).__init__() + self._conv = MakeFireConv(input_channels, squeeze_channels, 1) + self._conv_path1 = MakeFireConv(squeeze_channels, expand1x1_channels, 1) + self._conv_path2 = MakeFireConv(squeeze_channels, + expand3x3_channels, + 3, + padding=1) + + def forward(self, inputs): + x = self._conv(inputs) + x1 = self._conv_path1(x) + x2 = self._conv_path2(x) + return paddle.concat([x1, x2], axis=1) + + +class SqueezeNet(nn.Layer): + """SqueezeNet model from + `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" + `_. + + Args: + version (str): Version of SqueezeNet, which can be "1.0" or "1.1". + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of SqueezeNet model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import SqueezeNet + + # build v1.0 model + model = SqueezeNet(version='1.0') + + # build v1.1 model + # model = SqueezeNet(version='1.1') + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, version, num_classes=1000, with_pool=True): + super(SqueezeNet, self).__init__() + self.version = version + self.num_classes = num_classes + self.with_pool = with_pool + + supported_versions = ['1.0', '1.1'] + assert version in supported_versions, \ + "supported versions are {} but input version is {}".format( + supported_versions, version) + + if self.version == "1.0": + self._conv = Conv2D(3, + 96, + 7, + stride=2, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + self._pool = MaxPool2D(kernel_size=3, stride=2, padding=0) + self._conv1 = MakeFire(96, 16, 64, 64) + self._conv2 = MakeFire(128, 16, 64, 64) + self._conv3 = MakeFire(128, 32, 128, 128) + self._conv4 = MakeFire(256, 32, 128, 128) + self._conv5 = MakeFire(256, 48, 192, 192) + self._conv6 = MakeFire(384, 48, 192, 192) + self._conv7 = MakeFire(384, 64, 256, 256) + self._conv8 = MakeFire(512, 64, 256, 256) + else: + self._conv = Conv2D(3, + 64, + 3, + stride=2, + padding=1, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + self._pool = MaxPool2D(kernel_size=3, stride=2, padding=0) + self._conv1 = MakeFire(64, 16, 64, 64) + self._conv2 = MakeFire(128, 16, 64, 64) + self._conv3 = MakeFire(128, 32, 128, 128) + self._conv4 = MakeFire(256, 32, 128, 128) + self._conv5 = MakeFire(256, 48, 192, 192) + self._conv6 = MakeFire(384, 48, 192, 192) + self._conv7 = MakeFire(384, 64, 256, 256) + self._conv8 = MakeFire(512, 64, 256, 256) + + self._drop = Dropout(p=0.5, mode="downscale_in_infer") + self._conv9 = Conv2D(512, + num_classes, + 1, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + self._avg_pool = AdaptiveAvgPool2D(1) + + def forward(self, inputs): + x = self._conv(inputs) + x = F.relu(x) + x = self._pool(x) + if self.version == "1.0": + x = self._conv1(x) + x = self._conv2(x) + x = self._conv3(x) + x = self._pool(x) + x = self._conv4(x) + x = self._conv5(x) + x = self._conv6(x) + x = self._conv7(x) + x = self._pool(x) + x = self._conv8(x) + else: + x = self._conv1(x) + x = self._conv2(x) + x = self._pool(x) + x = self._conv3(x) + x = self._conv4(x) + x = self._pool(x) + x = self._conv5(x) + x = self._conv6(x) + x = self._conv7(x) + x = self._conv8(x) + if self.num_classes > 0: + x = self._drop(x) + x = self._conv9(x) + if self.with_pool: + x = F.relu(x) + x = self._avg_pool(x) + x = paddle.squeeze(x, axis=[2, 3]) + + return x + + +def _squeezenet(arch, version, pretrained, **kwargs): + model = SqueezeNet(version, **kwargs) + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + param = paddle.load(weight_path) + model.set_dict(param) + + return model + + +def squeezenet1_0(pretrained=False, **kwargs): + """SqueezeNet v1.0 model from + `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" + `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`SqueezeNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of SqueezeNet v1.0 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import squeezenet1_0 + + # build model + model = squeezenet1_0() + + # build model and load imagenet pretrained weight + # model = squeezenet1_0(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _squeezenet('squeezenet1_0', '1.0', pretrained, **kwargs) + + +def squeezenet1_1(pretrained=False, **kwargs): + """SqueezeNet v1.1 model from + `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" + `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`SqueezeNet `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of SqueezeNet v1.1 model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import squeezenet1_1 + + # build model + model = squeezenet1_1() + + # build model and load imagenet pretrained weight + # model = squeezenet1_1(pretrained=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + return _squeezenet('squeezenet1_1', '1.1', pretrained, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f61d0d601a44f5b47b5f36a1488a736f28df298c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/utils.py @@ -0,0 +1,32 @@ +# Copyright (c) 2022 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. + + +def _make_divisible(v, divisor=8, min_value=None): + """ + This function ensures that all layers have a channel number that is divisible by divisor + You can also see at https://github.com/keras-team/keras/blob/8ecef127f70db723c158dbe9ed3268b3d610ab55/keras/applications/mobilenet_v2.py#L505 + + Args: + divisor (int): The divisor for number of channels. Default: 8. + min_value (int, optional): The minimum value of number of channels, if it is None, + the default is divisor. Default: None. + """ + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + # Make sure that round down does not go down by more than 10%. + if new_v < 0.9 * v: + new_v += divisor + return new_v diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/vgg.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/vgg.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb0ea260058114db07a1620576164608d6aa886 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/models/vgg.py @@ -0,0 +1,287 @@ +# 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. + +import paddle +import paddle.nn as nn + +from paddle.utils.download import get_weights_path_from_url + +__all__ = [] + +model_urls = { + 'vgg16': ('https://paddle-hapi.bj.bcebos.com/models/vgg16.pdparams', + '89bbffc0f87d260be9b8cdc169c991c4'), + 'vgg19': ('https://paddle-hapi.bj.bcebos.com/models/vgg19.pdparams', + '23b18bb13d8894f60f54e642be79a0dd') +} + + +class VGG(nn.Layer): + """VGG model from + `"Very Deep Convolutional Networks For Large-Scale Image Recognition" `_. + + Args: + features (nn.Layer): Vgg features create by function make_layers. + num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer + will not be defined. Default: 1000. + with_pool (bool, optional): Use pool before the last three fc layer or not. Default: True. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of VGG model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import VGG + from paddle.vision.models.vgg import make_layers + + vgg11_cfg = [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'] + + features = make_layers(vgg11_cfg) + + vgg11 = VGG(features) + + x = paddle.rand([1, 3, 224, 224]) + out = vgg11(x) + + print(out.shape) + # [1, 1000] + """ + + def __init__(self, features, num_classes=1000, with_pool=True): + super(VGG, self).__init__() + self.features = features + self.num_classes = num_classes + self.with_pool = with_pool + + if with_pool: + self.avgpool = nn.AdaptiveAvgPool2D((7, 7)) + + if num_classes > 0: + self.classifier = nn.Sequential( + nn.Linear(512 * 7 * 7, 4096), + nn.ReLU(), + nn.Dropout(), + nn.Linear(4096, 4096), + nn.ReLU(), + nn.Dropout(), + nn.Linear(4096, num_classes), + ) + + def forward(self, x): + x = self.features(x) + + if self.with_pool: + x = self.avgpool(x) + + if self.num_classes > 0: + x = paddle.flatten(x, 1) + x = self.classifier(x) + + return x + + +def make_layers(cfg, batch_norm=False): + layers = [] + in_channels = 3 + for v in cfg: + if v == 'M': + layers += [nn.MaxPool2D(kernel_size=2, stride=2)] + else: + conv2d = nn.Conv2D(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, nn.BatchNorm2D(v), nn.ReLU()] + else: + layers += [conv2d, nn.ReLU()] + in_channels = v + return nn.Sequential(*layers) + + +cfgs = { + 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'B': + [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], + 'D': [ + 64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, + 512, 512, 'M' + ], + 'E': [ + 64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, + 'M', 512, 512, 512, 512, 'M' + ], +} + + +def _vgg(arch, cfg, batch_norm, pretrained, **kwargs): + model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs) + + if pretrained: + assert arch in model_urls, "{} model do not have a pretrained model now, you should set pretrained=False".format( + arch) + weight_path = get_weights_path_from_url(model_urls[arch][0], + model_urls[arch][1]) + + param = paddle.load(weight_path) + model.load_dict(param) + + return model + + +def vgg11(pretrained=False, batch_norm=False, **kwargs): + """VGG 11-layer model from + `"Very Deep Convolutional Networks For Large-Scale Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of VGG 11-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import vgg11 + + # build model + model = vgg11() + + # build vgg11 model with batch_norm + model = vgg11(batch_norm=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model_name = 'vgg11' + if batch_norm: + model_name += ('_bn') + return _vgg(model_name, 'A', batch_norm, pretrained, **kwargs) + + +def vgg13(pretrained=False, batch_norm=False, **kwargs): + """VGG 13-layer model from + `"Very Deep Convolutional Networks For Large-Scale Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + batch_norm (bool): If True, returns a model with batch_norm layer. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of VGG 13-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import vgg13 + + # build model + model = vgg13() + + # build vgg13 model with batch_norm + model = vgg13(batch_norm=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model_name = 'vgg13' + if batch_norm: + model_name += ('_bn') + return _vgg(model_name, 'B', batch_norm, pretrained, **kwargs) + + +def vgg16(pretrained=False, batch_norm=False, **kwargs): + """VGG 16-layer model from + `"Very Deep Convolutional Networks For Large-Scale Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of VGG 16-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import vgg16 + + # build model + model = vgg16() + + # build vgg16 model with batch_norm + model = vgg16(batch_norm=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model_name = 'vgg16' + if batch_norm: + model_name += ('_bn') + return _vgg(model_name, 'D', batch_norm, pretrained, **kwargs) + + +def vgg19(pretrained=False, batch_norm=False, **kwargs): + """VGG 19-layer model from + `"Very Deep Convolutional Networks For Large-Scale Image Recognition" `_. + + Args: + pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained + on ImageNet. Default: False. + batch_norm (bool, optional): If True, returns a model with batch_norm layer. Default: False. + **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`VGG `. + + Returns: + :ref:`api_paddle_nn_Layer`. An instance of VGG 19-layer model. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.models import vgg19 + + # build model + model = vgg19() + + # build vgg19 model with batch_norm + model = vgg19(batch_norm=True) + + x = paddle.rand([1, 3, 224, 224]) + out = model(x) + + print(out.shape) + # [1, 1000] + """ + model_name = 'vgg19' + if batch_norm: + model_name += ('_bn') + return _vgg(model_name, 'E', batch_norm, pretrained, **kwargs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9adda41eebfa92c6b53759743d2e656dfdd8831f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/ops.py @@ -0,0 +1,2602 @@ +# 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. + +import numpy as np +from ..fluid.layer_helper import LayerHelper +from ..fluid.data_feeder import ( + check_variable_and_dtype, + check_type, + check_dtype, +) +from ..fluid import core, layers +from ..fluid.layers import nn, utils +from ..nn import Layer, Conv2D, Sequential, ReLU, BatchNorm2D +from ..fluid.initializer import Normal +from ..fluid.framework import ( + Variable, + _non_static_mode, + in_dygraph_mode, + _in_legacy_dygraph, +) +from paddle.common_ops_import import * +from paddle import _C_ops, _legacy_C_ops + +__all__ = [ # noqa + 'yolo_loss', + 'yolo_box', + 'prior_box', + 'box_coder', + 'deform_conv2d', + 'DeformConv2D', + 'distribute_fpn_proposals', + 'generate_proposals', + 'read_file', + 'decode_jpeg', + 'roi_pool', + 'RoIPool', + 'psroi_pool', + 'PSRoIPool', + 'roi_align', + 'RoIAlign', + 'nms', + 'matrix_nms', +] + + +def yolo_loss( + x, + gt_box, + gt_label, + anchors, + anchor_mask, + class_num, + ignore_thresh, + downsample_ratio, + gt_score=None, + use_label_smooth=True, + name=None, + scale_x_y=1.0, +): + r""" + + This operator generates YOLOv3 loss based on given predict result and ground + truth boxes. + + The output of previous network is in shape [N, C, H, W], while H and W + should be the same, H and W specify the grid size, each grid point predict + given number bounding boxes, this given number, which following will be represented as S, + is specified by the number of anchor clusters in each scale. In the second dimension(the channel + dimension), C should be equal to S * (class_num + 5), class_num is the object + category number of source dataset(such as 80 in coco dataset), so in the + second(channel) dimension, apart from 4 box location coordinates x, y, w, h, + also includes confidence score of the box and class one-hot key of each anchor box. + + Assume the 4 location coordinates are :math:`t_x, t_y, t_w, t_h`, the box predictions + should be as follows: + + $$ + b_x = \\sigma(t_x) + c_x + $$ + $$ + b_y = \\sigma(t_y) + c_y + $$ + $$ + b_w = p_w e^{t_w} + $$ + $$ + b_h = p_h e^{t_h} + $$ + + In the equation above, :math:`c_x, c_y` is the left top corner of current grid + and :math:`p_w, p_h` is specified by anchors. + + As for confidence score, it is the logistic regression value of IoU between + anchor boxes and ground truth boxes, the score of the anchor box which has + the max IoU should be 1, and if the anchor box has IoU bigger than ignore + thresh, the confidence score loss of this anchor box will be ignored. + + Therefore, the YOLOv3 loss consists of three major parts: box location loss, + objectness loss and classification loss. The L1 loss is used for + box coordinates (w, h), sigmoid cross entropy loss is used for box + coordinates (x, y), objectness loss and classification loss. + + Each groud truth box finds a best matching anchor box in all anchors. + Prediction of this anchor box will incur all three parts of losses, and + prediction of anchor boxes with no GT box matched will only incur objectness + loss. + + In order to trade off box coordinate losses between big boxes and small + boxes, box coordinate losses will be mutiplied by scale weight, which is + calculated as follows. + + $$ + weight_{box} = 2.0 - t_w * t_h + $$ + + Final loss will be represented as follows. + + $$ + loss = (loss_{xy} + loss_{wh}) * weight_{box} + loss_{conf} + loss_{class} + $$ + + While :attr:`use_label_smooth` is set to be :attr:`True`, the classification + target will be smoothed when calculating classification loss, target of + positive samples will be smoothed to :math:`1.0 - 1.0 / class\_num` and target of + negetive samples will be smoothed to :math:`1.0 / class\_num`. + + While :attr:`gt_score` is given, which means the mixup score of ground truth + boxes, all losses incured by a ground truth box will be multiplied by its + mixup score. + + Args: + x (Tensor): The input tensor of YOLOv3 loss operator, This is a 4-D + tensor with shape of [N, C, H, W]. H and W should be same, + and the second dimension(C) stores box locations, confidence + score and classification one-hot keys of each anchor box. + The data type is float32 or float64. + gt_box (Tensor): groud truth boxes, should be in shape of [N, B, 4], + in the third dimension, x, y, w, h should be stored. + x,y is the center coordinate of boxes, w, h are the + width and height, x, y, w, h should be divided by + input image height to scale to [0, 1]. + N is the batch number and B is the max box number in + an image.The data type is float32 or float64. + gt_label (Tensor): class id of ground truth boxes, should be in shape + of [N, B].The data type is int32. + anchors (list|tuple): The anchor width and height, it will be parsed + pair by pair. + anchor_mask (list|tuple): The mask index of anchors used in current + YOLOv3 loss calculation. + class_num (int): The number of classes. + ignore_thresh (float): The ignore threshold to ignore confidence loss. + downsample_ratio (int): The downsample ratio from network input to YOLOv3 + loss input, so 32, 16, 8 should be set for the + first, second, and thrid YOLOv3 loss operators. + name (string): The default value is None. Normally there is no need + for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + gt_score (Tensor): mixup score of ground truth boxes, should be in shape + of [N, B]. Default None. + use_label_smooth (bool): Whether to use label smooth. Default True. + scale_x_y (float): Scale the center point of decoded bounding box. + Default 1.0 + + Returns: + Tensor: A 1-D tensor with shape [N], the value of yolov3 loss + + Examples: + .. code-block:: python + + import paddle + + x = paddle.rand([2, 14, 8, 8]).astype('float32') + gt_box = paddle.rand([2, 10, 4]).astype('float32') + gt_label = paddle.rand([2, 10]).astype('int32') + + + loss = paddle.vision.ops.yolo_loss(x, + gt_box=gt_box, + gt_label=gt_label, + anchors=[10, 13, 16, 30], + anchor_mask=[0, 1], + class_num=2, + ignore_thresh=0.7, + downsample_ratio=8, + use_label_smooth=True, + scale_x_y=1.) + """ + + if in_dygraph_mode(): + loss, _, _ = _C_ops.yolov3_loss( + x, + gt_box, + gt_label, + gt_score, + anchors, + anchor_mask, + class_num, + ignore_thresh, + downsample_ratio, + use_label_smooth, + scale_x_y, + ) + return loss + + if _non_static_mode(): + loss, _, _ = _legacy_C_ops.yolov3_loss( + x, + gt_box, + gt_label, + gt_score, + 'anchors', + anchors, + 'anchor_mask', + anchor_mask, + 'class_num', + class_num, + 'ignore_thresh', + ignore_thresh, + 'downsample_ratio', + downsample_ratio, + 'use_label_smooth', + use_label_smooth, + 'scale_x_y', + scale_x_y, + ) + return loss + + helper = LayerHelper('yolov3_loss', **locals()) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'yolo_loss') + check_variable_and_dtype( + gt_box, 'gt_box', ['float32', 'float64'], 'yolo_loss' + ) + check_variable_and_dtype(gt_label, 'gt_label', 'int32', 'yolo_loss') + check_type(anchors, 'anchors', (list, tuple), 'yolo_loss') + check_type(anchor_mask, 'anchor_mask', (list, tuple), 'yolo_loss') + check_type(class_num, 'class_num', int, 'yolo_loss') + check_type(ignore_thresh, 'ignore_thresh', float, 'yolo_loss') + check_type(use_label_smooth, 'use_label_smooth', bool, 'yolo_loss') + + loss = helper.create_variable_for_type_inference(dtype=x.dtype) + + objectness_mask = helper.create_variable_for_type_inference(dtype='int32') + gt_match_mask = helper.create_variable_for_type_inference(dtype='int32') + + inputs = { + "X": x, + "GTBox": gt_box, + "GTLabel": gt_label, + } + if gt_score is not None: + inputs["GTScore"] = gt_score + + attrs = { + "anchors": anchors, + "anchor_mask": anchor_mask, + "class_num": class_num, + "ignore_thresh": ignore_thresh, + "downsample_ratio": downsample_ratio, + "use_label_smooth": use_label_smooth, + "scale_x_y": scale_x_y, + } + + helper.append_op( + type='yolov3_loss', + inputs=inputs, + outputs={ + 'Loss': loss, + 'ObjectnessMask': objectness_mask, + 'GTMatchMask': gt_match_mask, + }, + attrs=attrs, + ) + return loss + + +def yolo_box( + x, + img_size, + anchors, + class_num, + conf_thresh, + downsample_ratio, + clip_bbox=True, + name=None, + scale_x_y=1.0, + iou_aware=False, + iou_aware_factor=0.5, +): + r""" + + This operator generates YOLO detection boxes from output of YOLOv3 network. + + The output of previous network is in shape [N, C, H, W], while H and W + should be the same, H and W specify the grid size, each grid point predict + given number boxes, this given number, which following will be represented as S, + is specified by the number of anchors. In the second dimension(the channel + dimension), C should be equal to S * (5 + class_num) if :attr:`iou_aware` is false, + otherwise C should be equal to S * (6 + class_num). class_num is the object + category number of source dataset(such as 80 in coco dataset), so the + second(channel) dimension, apart from 4 box location coordinates x, y, w, h, + also includes confidence score of the box and class one-hot key of each anchor + box. + + Assume the 4 location coordinates are :math:`t_x, t_y, t_w, t_h`, the box + predictions should be as follows: + + $$ + b_x = \\sigma(t_x) + c_x + $$ + $$ + b_y = \\sigma(t_y) + c_y + $$ + $$ + b_w = p_w e^{t_w} + $$ + $$ + b_h = p_h e^{t_h} + $$ + + in the equation above, :math:`c_x, c_y` is the left top corner of current grid + and :math:`p_w, p_h` is specified by anchors. + + The logistic regression value of the 5th channel of each anchor prediction boxes + represents the confidence score of each prediction box, and the logistic + regression value of the last :attr:`class_num` channels of each anchor prediction + boxes represents the classifcation scores. Boxes with confidence scores less than + :attr:`conf_thresh` should be ignored, and box final scores is the product of + confidence scores and classification scores. + + $$ + score_{pred} = score_{conf} * score_{class} + $$ + + where the confidence scores follow the formula bellow + + .. math:: + + score_{conf} = \begin{case} + obj, \text{if } iou_aware == flase \\ + obj^{1 - iou_aware_factor} * iou^{iou_aware_factor}, \text{otherwise} + \end{case} + + Args: + x (Tensor): The input tensor of YoloBox operator is a 4-D tensor with + shape of [N, C, H, W]. The second dimension(C) stores box + locations, confidence score and classification one-hot keys + of each anchor box. Generally, X should be the output of + YOLOv3 network. The data type is float32 or float64. + img_size (Tensor): The image size tensor of YoloBox operator, This is a + 2-D tensor with shape of [N, 2]. This tensor holds + height and width of each input image used for resizing + output box in input image scale. The data type is int32. + anchors (list|tuple): The anchor width and height, it will be parsed pair + by pair. + class_num (int): The number of classes. + conf_thresh (float): The confidence scores threshold of detection boxes. + Boxes with confidence scores under threshold should + be ignored. + downsample_ratio (int): The downsample ratio from network input to + :attr:`yolo_box` operator input, so 32, 16, 8 + should be set for the first, second, and thrid + :attr:`yolo_box` layer. + clip_bbox (bool): Whether clip output bonding box in :attr:`img_size` + boundary. Default true. + scale_x_y (float): Scale the center point of decoded bounding box. + Default 1.0 + name (string): The default value is None. Normally there is no need + for user to set this property. For more information, + please refer to :ref:`api_guide_Name` + iou_aware (bool): Whether use iou aware. Default false + iou_aware_factor (float): iou aware factor. Default 0.5 + + Returns: + Tensor: A 3-D tensor with shape [N, M, 4], the coordinates of boxes, + and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification + scores of boxes. + + Examples: + + .. code-block:: python + + import paddle + + x = paddle.rand([2, 14, 8, 8]).astype('float32') + img_size = paddle.ones((2, 2)).astype('int32') + + boxes, scores = paddle.vision.ops.yolo_box(x, + img_size=img_size, + anchors=[10, 13, 16, 30], + class_num=2, + conf_thresh=0.01, + downsample_ratio=8, + clip_bbox=True, + scale_x_y=1.) + """ + if in_dygraph_mode(): + boxes, scores = _C_ops.yolo_box( + x, + img_size, + anchors, + class_num, + conf_thresh, + downsample_ratio, + clip_bbox, + scale_x_y, + iou_aware, + iou_aware_factor, + ) + return boxes, scores + + if _non_static_mode(): + boxes, scores = _legacy_C_ops.yolo_box( + x, + img_size, + 'anchors', + anchors, + 'class_num', + class_num, + 'conf_thresh', + conf_thresh, + 'downsample_ratio', + downsample_ratio, + 'clip_bbox', + clip_bbox, + 'scale_x_y', + scale_x_y, + 'iou_aware', + iou_aware, + 'iou_aware_factor', + iou_aware_factor, + ) + return boxes, scores + + helper = LayerHelper('yolo_box', **locals()) + + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'yolo_box') + check_variable_and_dtype(img_size, 'img_size', 'int32', 'yolo_box') + check_type(anchors, 'anchors', (list, tuple), 'yolo_box') + check_type(conf_thresh, 'conf_thresh', float, 'yolo_box') + + boxes = helper.create_variable_for_type_inference(dtype=x.dtype) + scores = helper.create_variable_for_type_inference(dtype=x.dtype) + + attrs = { + "anchors": anchors, + "class_num": class_num, + "conf_thresh": conf_thresh, + "downsample_ratio": downsample_ratio, + "clip_bbox": clip_bbox, + "scale_x_y": scale_x_y, + "iou_aware": iou_aware, + "iou_aware_factor": iou_aware_factor, + } + + helper.append_op( + type='yolo_box', + inputs={ + "X": x, + "ImgSize": img_size, + }, + outputs={ + 'Boxes': boxes, + 'Scores': scores, + }, + attrs=attrs, + ) + return boxes, scores + + +def prior_box( + input, + image, + min_sizes, + max_sizes=None, + aspect_ratios=[1.0], + variance=[0.1, 0.1, 0.2, 0.2], + flip=False, + clip=False, + steps=[0.0, 0.0], + offset=0.5, + min_max_aspect_ratios_order=False, + name=None, +): + r""" + + This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm. + + Each position of the input produce N prior boxes, N is determined by + the count of min_sizes, max_sizes and aspect_ratios, The size of the + box is in range(min_size, max_size) interval, which is generated in + sequence according to the aspect_ratios. + + Args: + input (Tensor): 4-D tensor(NCHW), the data type should be float32 or float64. + image (Tensor): 4-D tensor(NCHW), the input image data of PriorBoxOp, + the data type should be float32 or float64. + min_sizes (list|tuple|float): the min sizes of generated prior boxes. + max_sizes (list|tuple|None, optional): the max sizes of generated prior boxes. + Default: None. + aspect_ratios (list|tuple|float, optional): the aspect ratios of generated + prior boxes. Default: [1.]. + variance (list|tuple, optional): the variances to be encoded in prior boxes. + Default:[0.1, 0.1, 0.2, 0.2]. + flip (bool): Whether to flip aspect ratios. Default:False. + clip (bool): Whether to clip out-of-boundary boxes. Default: False. + steps (list|tuple, optional): Prior boxes steps across width and height, If + steps[0] equals to 0.0 or steps[1] equals to 0.0, the prior boxes steps across + height or weight of the input will be automatically calculated. + Default: [0., 0.] + offset (float, optional)): Prior boxes center offset. Default: 0.5 + min_max_aspect_ratios_order (bool, optional): If set True, the output prior box is + in order of [min, max, aspect_ratios], which is consistent with + Caffe. Please note, this order affects the weights order of + convolution layer followed by and does not affect the final + detection results. Default: False. + name (str, optional): The default value is None. Normally there is no need for + user to set this property. For more information, please refer to :ref:`api_guide_Name` + + Returns: + Tensor: the output prior boxes and the expanded variances of PriorBox. + The prior boxes is a 4-D tensor, the layout is [H, W, num_priors, 4], + num_priors is the total box count of each position of input. + The expanded variances is a 4-D tensor, same shape as the prior boxes. + + Examples: + .. code-block:: python + + import paddle + + input = paddle.rand((1, 3, 6, 9), dtype=paddle.float32) + image = paddle.rand((1, 3, 9, 12), dtype=paddle.float32) + + box, var = paddle.vision.ops.prior_box( + input=input, + image=image, + min_sizes=[2.0, 4.0], + clip=True, + flip=True) + + """ + helper = LayerHelper("prior_box", **locals()) + dtype = helper.input_dtype() + check_variable_and_dtype( + input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box' + ) + + def _is_list_or_tuple_(data): + return isinstance(data, list) or isinstance(data, tuple) + + if not _is_list_or_tuple_(min_sizes): + min_sizes = [min_sizes] + if not _is_list_or_tuple_(aspect_ratios): + aspect_ratios = [aspect_ratios] + if not _is_list_or_tuple_(steps): + steps = [steps] + if not len(steps) == 2: + raise ValueError('steps should be (step_w, step_h)') + + min_sizes = list(map(float, min_sizes)) + aspect_ratios = list(map(float, aspect_ratios)) + steps = list(map(float, steps)) + + cur_max_sizes = None + if max_sizes is not None and len(max_sizes) > 0 and max_sizes[0] > 0: + if not _is_list_or_tuple_(max_sizes): + max_sizes = [max_sizes] + cur_max_sizes = max_sizes + + if in_dygraph_mode(): + step_w, step_h = steps + if max_sizes == None: + max_sizes = [] + box, var = _C_ops.prior_box( + input, + image, + min_sizes, + aspect_ratios, + variance, + max_sizes, + flip, + clip, + step_w, + step_h, + offset, + min_max_aspect_ratios_order, + ) + return box, var + + if _in_legacy_dygraph(): + attrs = ( + 'min_sizes', + min_sizes, + 'aspect_ratios', + aspect_ratios, + 'variances', + variance, + 'flip', + flip, + 'clip', + clip, + 'step_w', + steps[0], + 'step_h', + steps[1], + 'offset', + offset, + 'min_max_aspect_ratios_order', + min_max_aspect_ratios_order, + ) + if cur_max_sizes is not None: + attrs += ('max_sizes', cur_max_sizes) + box, var = _legacy_C_ops.prior_box(input, image, *attrs) + return box, var + else: + attrs = { + 'min_sizes': min_sizes, + 'aspect_ratios': aspect_ratios, + 'variances': variance, + 'flip': flip, + 'clip': clip, + 'step_w': steps[0], + 'step_h': steps[1], + 'offset': offset, + 'min_max_aspect_ratios_order': min_max_aspect_ratios_order, + } + if cur_max_sizes is not None: + attrs['max_sizes'] = cur_max_sizes + + box = helper.create_variable_for_type_inference(dtype) + var = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type="prior_box", + inputs={"Input": input, "Image": image}, + outputs={"Boxes": box, "Variances": var}, + attrs=attrs, + ) + box.stop_gradient = True + var.stop_gradient = True + return box, var + + +def box_coder( + prior_box, + prior_box_var, + target_box, + code_type="encode_center_size", + box_normalized=True, + axis=0, + name=None, +): + r""" + Encode/Decode the target bounding box with the priorbox information. + + The Encoding schema described below: + + .. math:: + + ox &= (tx - px) / pw / pxv + + oy &= (ty - py) / ph / pyv + + ow &= log(abs(tw / pw)) / pwv + + oh &= log(abs(th / ph)) / phv + + The Decoding schema described below: + + .. math:: + + ox &= (pw * pxv * tx * + px) - tw / 2 + + oy &= (ph * pyv * ty * + py) - th / 2 + + ow &= exp(pwv * tw) * pw + tw / 2 + + oh &= exp(phv * th) * ph + th / 2 + + where `tx`, `ty`, `tw`, `th` denote the target box's center coordinates, + width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote + the priorbox's (anchor) center coordinates, width and height. `pxv`, + `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`, + `ow`, `oh` denote the encoded/decoded coordinates, width and height. + During Box Decoding, two modes for broadcast are supported. Say target + box has shape [N, M, 4], and the shape of prior box can be [N, 4] or + [M, 4]. Then prior box will broadcast to target box along the + assigned axis. + + Args: + prior_box (Tensor): Box list prior_box is a 2-D Tensor with shape + [M, 4] holds M boxes and data type is float32 or float64. Each box + is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the + left top coordinate of the anchor box, if the input is image feature + map, they are close to the origin of the coordinate system. + [xmax, ymax] is the right bottom coordinate of the anchor box. + prior_box_var (List|Tensor|None): prior_box_var supports three types + of input. One is Tensor with shape [M, 4] which holds M group and + data type is float32 or float64. The second is list consist of + 4 elements shared by all boxes and data type is float32 or float64. + Other is None and not involved in calculation. + target_box (Tensor): This input can be a 2-D LoDTensor with shape + [N, 4] when code_type is 'encode_center_size'. This input also can + be a 3-D Tensor with shape [N, M, 4] when code_type is + 'decode_center_size'. Each box is represented as + [xmin, ymin, xmax, ymax]. The data type is float32 or float64. + code_type (str, optional): The code type used with the target box. It can be + `encode_center_size` or `decode_center_size`. `encode_center_size` + by default. + box_normalized (bool, optional): Whether treat the priorbox as a normalized box. + Set true by default. + axis (int, optional): Which axis in PriorBox to broadcast for box decode, + for example, if axis is 0 and TargetBox has shape [N, M, 4] and + PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4] + for decoding. It is only valid when code type is + `decode_center_size`. Set 0 by default. + name (str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + Tensor: output boxes, when code_type is 'encode_center_size', the + output tensor of box_coder_op with shape [N, M, 4] representing the + result of N target boxes encoded with M Prior boxes and variances. + When code_type is 'decode_center_size', N represents the batch size + and M represents the number of decoded boxes. + + Examples: + .. code-block:: python + + import paddle + + # For encode + prior_box_encode = paddle.rand((80, 4), dtype=paddle.float32) + prior_box_var_encode = paddle.rand((80, 4), dtype=paddle.float32) + target_box_encode = paddle.rand((20, 4), dtype=paddle.float32) + output_encode = paddle.vision.ops.box_coder( + prior_box=prior_box_encode, + prior_box_var=prior_box_var_encode, + target_box=target_box_encode, + code_type="encode_center_size") + + # For decode + prior_box_decode = paddle.rand((80, 4), dtype=paddle.float32) + prior_box_var_decode = paddle.rand((80, 4), dtype=paddle.float32) + target_box_decode = paddle.rand((20, 80, 4), dtype=paddle.float32) + output_decode = paddle.vision.ops.box_coder( + prior_box=prior_box_decode, + prior_box_var=prior_box_var_decode, + target_box=target_box_decode, + code_type="decode_center_size", + box_normalized=False) + + """ + check_variable_and_dtype( + prior_box, 'prior_box', ['float32', 'float64'], 'box_coder' + ) + check_variable_and_dtype( + target_box, 'target_box', ['float32', 'float64'], 'box_coder' + ) + + if in_dygraph_mode(): + if isinstance(prior_box_var, Variable): + output_box = _C_ops.box_coder( + prior_box, + prior_box_var, + target_box, + code_type, + box_normalized, + axis, + [], + ) + elif isinstance(prior_box_var, list): + output_box = _C_ops.box_coder( + prior_box, + None, + target_box, + code_type, + box_normalized, + axis, + prior_box_var, + ) + else: + raise TypeError("Input prior_box_var must be Variable or list") + return output_box + + if _in_legacy_dygraph(): + if isinstance(prior_box_var, Variable): + output_box = _legacy_C_ops.box_coder( + prior_box, + prior_box_var, + target_box, + "code_type", + code_type, + "box_normalized", + box_normalized, + "axis", + axis, + ) + elif isinstance(prior_box_var, list): + output_box = _legacy_C_ops.box_coder( + prior_box, + None, + target_box, + "code_type", + code_type, + "box_normalized", + box_normalized, + "axis", + axis, + "variance", + prior_box_var, + ) + else: + raise TypeError("Input prior_box_var must be Variable or list") + return output_box + else: + helper = LayerHelper("box_coder", **locals()) + + output_box = helper.create_variable_for_type_inference( + dtype=prior_box.dtype + ) + + inputs = {"PriorBox": prior_box, "TargetBox": target_box} + attrs = { + "code_type": code_type, + "box_normalized": box_normalized, + "axis": axis, + } + if isinstance(prior_box_var, Variable): + inputs['PriorBoxVar'] = prior_box_var + elif isinstance(prior_box_var, list): + attrs['variance'] = prior_box_var + else: + raise TypeError("Input prior_box_var must be Variable or list") + helper.append_op( + type="box_coder", + inputs=inputs, + attrs=attrs, + outputs={"OutputBox": output_box}, + ) + return output_box + + +def deform_conv2d( + x, + offset, + weight, + bias=None, + stride=1, + padding=0, + dilation=1, + deformable_groups=1, + groups=1, + mask=None, + name=None, +): + r""" + Compute 2-D deformable convolution on 4-D input. + Given input image x, output feature map y, the deformable convolution operation can be expressed as follow: + + + Deformable Convolution v2: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k} + + Deformable Convolution v1: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)} + + Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location, + Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results + `_ and `Deformable Convolutional Networks `_. + + Example: + - Input: + + x shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + weight shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + offset shape: :math:`(N, 2 * H_f * W_f, H_{out}, W_{out})` + + mask shape: :math:`(N, H_f * W_f, H_{out}, W_{out})` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \\frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\\\ + W_{out}&= \\frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + Args: + x (Tensor): The input image with [N, C, H, W] format. A Tensor with type + float32, float64. + offset (Tensor): The input coordinate offset of deformable convolution layer. + A Tensor with type float32, float64. + weight (Tensor): The convolution kernel with shape [M, C/g, kH, kW], where M is + the number of output channels, g is the number of groups, kH is the filter's + height, kW is the filter's width. + bias (Tensor, optional): The bias with shape [M,]. + stride (int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain two integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. Default: stride = 1. + padding (int|list|tuple, optional): The padding size. If padding is a list/tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: padding = 0. + dilation (int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain two integers, (dilation_H, dilation_W). Otherwise, the + dilation_H = dilation_W = dilation. Default: dilation = 1. + deformable_groups (int): The number of deformable group partitions. + Default: deformable_groups = 1. + groups (int, optonal): The groups number of the deformable conv layer. According to + grouped convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. Default: groups=1. + mask (Tensor, optional): The input mask of deformable convolution layer. + A Tensor with type float32, float64. It should be None when you use + deformable convolution v1. + name(str, optional): For details, please refer to :ref:`api_guide_Name`. + Generally, no setting is required. Default: None. + Returns: + Tensor: The tensor variable storing the deformable convolution \ + result. A Tensor with type float32, float64. + + Examples: + .. code-block:: python + + #deformable conv v2: + + import paddle + input = paddle.rand((8, 1, 28, 28)) + kh, kw = 3, 3 + weight = paddle.rand((16, 1, kh, kw)) + # offset shape should be [bs, 2 * kh * kw, out_h, out_w] + # mask shape should be [bs, hw * hw, out_h, out_w] + # In this case, for an input of 28, stride of 1 + # and kernel size of 3, without padding, the output size is 26 + offset = paddle.rand((8, 2 * kh * kw, 26, 26)) + mask = paddle.rand((8, kh * kw, 26, 26)) + out = paddle.vision.ops.deform_conv2d(input, offset, weight, mask=mask) + print(out.shape) + # returns + [8, 16, 26, 26] + + #deformable conv v1: + + import paddle + input = paddle.rand((8, 1, 28, 28)) + kh, kw = 3, 3 + weight = paddle.rand((16, 1, kh, kw)) + # offset shape should be [bs, 2 * kh * kw, out_h, out_w] + # In this case, for an input of 28, stride of 1 + # and kernel size of 3, without padding, the output size is 26 + offset = paddle.rand((8, 2 * kh * kw, 26, 26)) + out = paddle.vision.ops.deform_conv2d(input, offset, weight) + print(out.shape) + # returns + [8, 16, 26, 26] + """ + stride = utils.convert_to_list(stride, 2, 'stride') + padding = utils.convert_to_list(padding, 2, 'padding') + dilation = utils.convert_to_list(dilation, 2, 'dilation') + + use_deform_conv2d_v1 = True if mask is None else False + + if in_dygraph_mode(): + pre_bias = _C_ops.deformable_conv( + x, + offset, + weight, + mask, + stride, + padding, + dilation, + deformable_groups, + groups, + 1, + ) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=1) + else: + out = pre_bias + elif _in_legacy_dygraph(): + attrs = ( + 'strides', + stride, + 'paddings', + padding, + 'dilations', + dilation, + 'deformable_groups', + deformable_groups, + 'groups', + groups, + 'im2col_step', + 1, + ) + if use_deform_conv2d_v1: + op_type = 'deformable_conv_v1' + pre_bias = getattr(_legacy_C_ops, op_type)( + x, offset, weight, *attrs + ) + else: + op_type = 'deformable_conv' + pre_bias = getattr(_legacy_C_ops, op_type)( + x, offset, mask, weight, *attrs + ) + if bias is not None: + out = nn.elementwise_add(pre_bias, bias, axis=1) + else: + out = pre_bias + else: + check_variable_and_dtype( + x, "x", ['float32', 'float64'], 'deform_conv2d' + ) + check_variable_and_dtype( + offset, "offset", ['float32', 'float64'], 'deform_conv2d' + ) + + num_channels = x.shape[1] + + helper = LayerHelper('deformable_conv', **locals()) + dtype = helper.input_dtype() + + stride = utils.convert_to_list(stride, 2, 'stride') + padding = utils.convert_to_list(padding, 2, 'padding') + dilation = utils.convert_to_list(dilation, 2, 'dilation') + + pre_bias = helper.create_variable_for_type_inference(dtype) + + if use_deform_conv2d_v1: + op_type = 'deformable_conv_v1' + inputs = { + 'Input': x, + 'Filter': weight, + 'Offset': offset, + } + else: + op_type = 'deformable_conv' + inputs = { + 'Input': x, + 'Filter': weight, + 'Offset': offset, + 'Mask': mask, + } + + outputs = {"Output": pre_bias} + attrs = { + 'strides': stride, + 'paddings': padding, + 'dilations': dilation, + 'groups': groups, + 'deformable_groups': deformable_groups, + 'im2col_step': 1, + } + helper.append_op( + type=op_type, inputs=inputs, outputs=outputs, attrs=attrs + ) + + if bias is not None: + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='elementwise_add', + inputs={'X': [pre_bias], 'Y': [bias]}, + outputs={'Out': [out]}, + attrs={'axis': 1}, + ) + else: + out = pre_bias + return out + + +class DeformConv2D(Layer): + r""" + Compute 2-D deformable convolution on 4-D input. + Given input image x, output feature map y, the deformable convolution operation can be expressed as follow: + + + Deformable Convolution v2: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k) * \Delta m_k} + + Deformable Convolution v1: + + .. math:: + + y(p) = \sum_{k=1}^{K}{w_k * x(p + p_k + \Delta p_k)} + + Where :math:`\Delta p_k` and :math:`\Delta m_k` are the learnable offset and modulation scalar for the k-th location, + Which :math:`\Delta m_k` is one in deformable convolution v1. Please refer to `Deformable ConvNets v2: More Deformable, Better Results + `_ and `Deformable Convolutional Networks `_. + + Example: + - Input: + + x shape: :math:`(N, C_{in}, H_{in}, W_{in})` + + weight shape: :math:`(C_{out}, C_{in}, H_f, W_f)` + + offset shape: :math:`(N, 2 * H_f * W_f, H_{out}, W_{out})` + + mask shape: :math:`(N, H_f * W_f, H_{out}, W_{out})` + + - Output: + + Output shape: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (H_f - 1) + 1))}{strides[0]} + 1 \\ + W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (W_f - 1) + 1))}{strides[1]} + 1 + + + Parameters: + in_channels(int): The number of input channels in the input image. + out_channels(int): The number of output channels produced by the convolution. + kernel_size(int|list|tuple): The size of the convolving kernel. + stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must + contain three integers, (stride_H, stride_W). Otherwise, the + stride_H = stride_W = stride. The default value is 1. + padding (int|list|tuple, optional): The padding size. If padding is a list/tuple, it must + contain two integers, (padding_H, padding_W). Otherwise, the + padding_H = padding_W = padding. Default: padding = 0. + dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must + contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the + dilation_D = dilation_H = dilation_W = dilation. The default value is 1. + deformable_groups (int): The number of deformable group partitions. + Default: deformable_groups = 1. + groups(int, optional): The groups number of the Conv3D Layer. According to grouped + convolution in Alex Krizhevsky's Deep CNN paper: when group=2, + the first half of the filters is only connected to the first half + of the input channels, while the second half of the filters is only + connected to the second half of the input channels. The default value is 1. + weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights + of conv2d. If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as param_attr. If it is set to None, the parameter + is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is + :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None. + bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv2d. + If it is set to False, no bias will be added to the output units. + If it is set to None or one attribute of ParamAttr, conv2d + will create ParamAttr as bias_attr. If the Initializer of the bias_attr + is not set, the bias is initialized zero. The default value is None. + Attribute: + **weight** (Parameter): the learnable weights of filter of this layer. + **bias** (Parameter or None): the learnable bias of this layer. + Shape: + - x: :math:`(N, C_{in}, H_{in}, W_{in})` + - offset: :math:`(N, 2 * H_f * W_f, H_{out}, W_{out})` + - mask: :math:`(N, H_f * W_f, H_{out}, W_{out})` + - output: :math:`(N, C_{out}, H_{out}, W_{out})` + + Where + + .. math:: + + H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1 \\ + W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1 + + Examples: + .. code-block:: python + + #deformable conv v2: + + import paddle + input = paddle.rand((8, 1, 28, 28)) + kh, kw = 3, 3 + # offset shape should be [bs, 2 * kh * kw, out_h, out_w] + # mask shape should be [bs, hw * hw, out_h, out_w] + # In this case, for an input of 28, stride of 1 + # and kernel size of 3, without padding, the output size is 26 + offset = paddle.rand((8, 2 * kh * kw, 26, 26)) + mask = paddle.rand((8, kh * kw, 26, 26)) + deform_conv = paddle.vision.ops.DeformConv2D( + in_channels=1, + out_channels=16, + kernel_size=[kh, kw]) + out = deform_conv(input, offset, mask) + print(out.shape) + # returns + [8, 16, 26, 26] + + #deformable conv v1: + + import paddle + input = paddle.rand((8, 1, 28, 28)) + kh, kw = 3, 3 + # offset shape should be [bs, 2 * kh * kw, out_h, out_w] + # mask shape should be [bs, hw * hw, out_h, out_w] + # In this case, for an input of 28, stride of 1 + # and kernel size of 3, without padding, the output size is 26 + offset = paddle.rand((8, 2 * kh * kw, 26, 26)) + deform_conv = paddle.vision.ops.DeformConv2D( + in_channels=1, + out_channels=16, + kernel_size=[kh, kw]) + out = deform_conv(input, offset) + print(out.shape) + # returns + [8, 16, 26, 26] + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + deformable_groups=1, + groups=1, + weight_attr=None, + bias_attr=None, + ): + super(DeformConv2D, self).__init__() + assert ( + weight_attr is not False + ), "weight_attr should not be False in Conv." + self._weight_attr = weight_attr + self._bias_attr = bias_attr + self._deformable_groups = deformable_groups + self._groups = groups + self._in_channels = in_channels + self._out_channels = out_channels + self._channel_dim = 1 + + self._stride = utils.convert_to_list(stride, 2, 'stride') + self._dilation = utils.convert_to_list(dilation, 2, 'dilation') + self._kernel_size = utils.convert_to_list(kernel_size, 2, 'kernel_size') + + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups.") + + self._padding = utils.convert_to_list(padding, 2, 'padding') + + filter_shape = [out_channels, in_channels // groups] + self._kernel_size + + def _get_default_param_initializer(): + filter_elem_num = np.prod(self._kernel_size) * self._in_channels + std = (2.0 / filter_elem_num) ** 0.5 + return Normal(0.0, std, 0) + + self.weight = self.create_parameter( + shape=filter_shape, + attr=self._weight_attr, + default_initializer=_get_default_param_initializer(), + ) + self.bias = self.create_parameter( + attr=self._bias_attr, shape=[self._out_channels], is_bias=True + ) + + def forward(self, x, offset, mask=None): + out = deform_conv2d( + x=x, + offset=offset, + weight=self.weight, + bias=self.bias, + stride=self._stride, + padding=self._padding, + dilation=self._dilation, + deformable_groups=self._deformable_groups, + groups=self._groups, + mask=mask, + ) + return out + + +def distribute_fpn_proposals( + fpn_rois, + min_level, + max_level, + refer_level, + refer_scale, + pixel_offset=False, + rois_num=None, + name=None, +): + r""" + + In Feature Pyramid Networks (FPN) models, it is needed to distribute + all proposals into different FPN level, with respect to scale of the proposals, + the referring scale and the referring level. Besides, to restore the order of + proposals, we return an array which indicates the original index of rois + in current proposals. To compute FPN level for each roi, the formula is given as follows: + + .. math:: + roi\_scale &= \sqrt{BBoxArea(fpn\_roi)} \\ + level &= floor(\log(\frac{roi\_scale}{refer\_scale}) + refer\_level) + + where BBoxArea is a function to compute the area of each roi. + + Args: + fpn_rois (Tensor): The input fpn_rois. 2-D Tensor with shape [N, 4] and data type can be + float32 or float64. + min_level (int): The lowest level of FPN layer where the proposals come + from. + max_level (int): The highest level of FPN layer where the proposals + come from. + refer_level (int): The referring level of FPN layer with specified scale. + refer_scale (int): The referring scale of FPN layer with specified level. + pixel_offset (bool, optional): Whether there is pixel offset. If True, the offset of + image shape will be 1. 'False' by default. + rois_num (Tensor, optional): 1-D Tensor contains the number of RoIs in each image. + The shape is [B] and data type is int32. B is the number of images. + If rois_num not None, it will return a list of 1-D Tensor. Each element + is the output RoIs' number of each image on the corresponding level + and the shape is [B]. None by default. + name (str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + - multi_rois (List), The proposals in each FPN level. It is a list of 2-D Tensor with shape [M, 4], where M is + and data type is same as `fpn_rois` . The length is max_level-min_level+1. + - restore_ind (Tensor), The index used to restore the order of fpn_rois. It is a 2-D Tensor with shape [N, 1] + , where N is the number of total rois. The data type is int32. + - rois_num_per_level (List), A list of 1-D Tensor and each Tensor is + the RoIs' number in each image on the corresponding level. The shape + is [B] and data type of int32, where B is the number of images. + + Examples: + .. code-block:: python + + import paddle + + fpn_rois = paddle.rand((10, 4)) + rois_num = paddle.to_tensor([3, 1, 4, 2], dtype=paddle.int32) + + multi_rois, restore_ind, rois_num_per_level = paddle.vision.ops.distribute_fpn_proposals( + fpn_rois=fpn_rois, + min_level=2, + max_level=5, + refer_level=4, + refer_scale=224, + rois_num=rois_num) + + """ + num_lvl = max_level - min_level + 1 + + if in_dygraph_mode(): + assert ( + rois_num is not None + ), "rois_num should not be None in dygraph mode." + ( + multi_rois, + rois_num_per_level, + restore_ind, + ) = _C_ops.distribute_fpn_proposals( + fpn_rois, + rois_num, + min_level, + max_level, + refer_level, + refer_scale, + pixel_offset, + ) + return multi_rois, restore_ind, rois_num_per_level + + if _non_static_mode(): + assert ( + rois_num is not None + ), "rois_num should not be None in dygraph mode." + attrs = ( + 'min_level', + min_level, + 'max_level', + max_level, + 'refer_level', + refer_level, + 'refer_scale', + refer_scale, + 'pixel_offset', + pixel_offset, + ) + ( + multi_rois, + restore_ind, + rois_num_per_level, + ) = _legacy_C_ops.distribute_fpn_proposals( + fpn_rois, rois_num, num_lvl, num_lvl, *attrs + ) + return multi_rois, restore_ind, rois_num_per_level + + else: + check_variable_and_dtype( + fpn_rois, + 'fpn_rois', + ['float32', 'float64'], + 'distribute_fpn_proposals', + ) + helper = LayerHelper('distribute_fpn_proposals', **locals()) + dtype = helper.input_dtype('fpn_rois') + multi_rois = [ + helper.create_variable_for_type_inference(dtype) + for i in range(num_lvl) + ] + + restore_ind = helper.create_variable_for_type_inference(dtype='int32') + + inputs = {'FpnRois': fpn_rois} + outputs = { + 'MultiFpnRois': multi_rois, + 'RestoreIndex': restore_ind, + } + + if rois_num is not None: + inputs['RoisNum'] = rois_num + rois_num_per_level = [ + helper.create_variable_for_type_inference(dtype='int32') + for i in range(num_lvl) + ] + outputs['MultiLevelRoIsNum'] = rois_num_per_level + else: + rois_num_per_level = None + + helper.append_op( + type='distribute_fpn_proposals', + inputs=inputs, + outputs=outputs, + attrs={ + 'min_level': min_level, + 'max_level': max_level, + 'refer_level': refer_level, + 'refer_scale': refer_scale, + 'pixel_offset': pixel_offset, + }, + ) + return multi_rois, restore_ind, rois_num_per_level + + +def read_file(filename, name=None): + """ + Reads and outputs the bytes contents of a file as a uint8 Tensor + with one dimension. + + Args: + filename (str): Path of the file to be read. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + + Returns: + A uint8 tensor. + + Examples: + .. code-block:: python + + import cv2 + import paddle + + fake_img = (paddle.rand((400, 300, 3)).numpy() * 255).astype('uint8') + + cv2.imwrite('fake.jpg', fake_img) + + img_bytes = paddle.vision.ops.read_file('fake.jpg') + + print(img_bytes.shape) + # [142915] + """ + + if _non_static_mode(): + return _legacy_C_ops.read_file('filename', filename) + + inputs = dict() + attrs = {'filename': filename} + + helper = LayerHelper("read_file", **locals()) + out = helper.create_variable_for_type_inference('uint8') + helper.append_op( + type="read_file", inputs=inputs, attrs=attrs, outputs={"Out": out} + ) + + return out + + +def decode_jpeg(x, mode='unchanged', name=None): + """ + Decodes a JPEG image into a 3 dimensional RGB Tensor or 1 dimensional Gray Tensor. + Optionally converts the image to the desired format. + The values of the output tensor are uint8 between 0 and 255. + + Args: + x (Tensor): A one dimensional uint8 tensor containing the raw bytes + of the JPEG image. + mode (str): The read mode used for optionally converting the image. + Default: 'unchanged'. + name (str, optional): The default value is None. Normally there is no + need for user to set this property. For more information, please + refer to :ref:`api_guide_Name`. + Returns: + Tensor: A decoded image tensor with shape (imge_channels, image_height, image_width) + + Examples: + .. code-block:: python + + # required: gpu + import cv2 + import numpy as np + import paddle + + fake_img = (np.random.random( + (400, 300, 3)) * 255).astype('uint8') + + cv2.imwrite('fake.jpg', fake_img) + + img_bytes = paddle.vision.ops.read_file('fake.jpg') + img = paddle.vision.ops.decode_jpeg(img_bytes) + + print(img.shape) + """ + if _non_static_mode(): + return _legacy_C_ops.decode_jpeg(x, "mode", mode) + + inputs = {'X': x} + attrs = {"mode": mode} + + helper = LayerHelper("decode_jpeg", **locals()) + out = helper.create_variable_for_type_inference('uint8') + helper.append_op( + type="decode_jpeg", inputs=inputs, attrs=attrs, outputs={"Out": out} + ) + + return out + + +def psroi_pool(x, boxes, boxes_num, output_size, spatial_scale=1.0, name=None): + """ + Position sensitive region of interest pooling (also known as PSROIPooling) is to perform + position-sensitive average pooling on regions of interest specified by input. It performs + on inputs of nonuniform sizes to obtain fixed-size feature maps. + + PSROIPooling is proposed by R-FCN. Please refer to https://arxiv.org/abs/1605.06409 for more details. + + Args: + x (Tensor): Input features with shape (N, C, H, W). The data type can be float32 or float64. + boxes (Tensor): Box coordinates of ROIs (Regions of Interest) to pool over. It should be + a 2-D Tensor with shape (num_rois, 4). Given as [[x1, y1, x2, y2], ...], + (x1, y1) is the top left coordinates, and (x2, y2) is the bottom + right coordinates. + boxes_num (Tensor): The number of boxes contained in each picture in the batch. + output_size (int|Tuple(int, int)) The pooled output size(H, W), data type + is int32. If int, H and W are both equal to output_size. + spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their + input scale to the scale used when pooling. Default: 1.0 + name(str, optional): The default value is None. + Normally there is no need for user to set this property. + For more information, please refer to :ref:`api_guide_Name` + + Returns: + 4-D Tensor. The pooled ROIs with shape (num_rois, output_channels, pooled_h, pooled_w). + The output_channels equal to C / (pooled_h * pooled_w), where C is the channels of input. + + Examples: + .. code-block:: python + + import paddle + x = paddle.uniform([2, 490, 28, 28], dtype='float32') + boxes = paddle.to_tensor([[1, 5, 8, 10], [4, 2, 6, 7], [12, 12, 19, 21]], dtype='float32') + boxes_num = paddle.to_tensor([1, 2], dtype='int32') + pool_out = paddle.vision.ops.psroi_pool(x, boxes, boxes_num, 7, 1.0) + print(pool_out.shape) + # [3, 10, 7, 7] + """ + + check_type(output_size, 'output_size', (int, tuple, list), 'psroi_pool') + if isinstance(output_size, int): + output_size = (output_size, output_size) + pooled_height, pooled_width = output_size + assert len(x.shape) == 4, "Input features with shape should be (N, C, H, W)" + output_channels = int(x.shape[1] / (pooled_height * pooled_width)) + if in_dygraph_mode(): + return _C_ops.psroi_pool( + x, + boxes, + boxes_num, + pooled_height, + pooled_width, + output_channels, + spatial_scale, + ) + if _in_legacy_dygraph(): + return _legacy_C_ops.psroi_pool( + x, + boxes, + boxes_num, + "output_channels", + output_channels, + "spatial_scale", + spatial_scale, + "pooled_height", + pooled_height, + "pooled_width", + pooled_width, + ) + + helper = LayerHelper('psroi_pool', **locals()) + dtype = helper.input_dtype() + out = helper.create_variable_for_type_inference(dtype) + helper.append_op( + type='psroi_pool', + inputs={'X': x, 'ROIs': boxes}, + outputs={'Out': out}, + attrs={ + 'output_channels': output_channels, + 'spatial_scale': spatial_scale, + 'pooled_height': pooled_height, + 'pooled_width': pooled_width, + }, + ) + return out + + +class PSRoIPool(Layer): + """ + This interface is used to construct a callable object of the ``PSRoIPool`` class. Please + refer to :ref:`api_paddle_vision_ops_psroi_pool`. + + Args: + output_size (int|Tuple(int, int)) The pooled output size(H, W), data type + is int32. If int, H and W are both equal to output_size. + spatial_scale (float, optional): Multiplicative spatial scale factor to translate ROI coords from their + input scale to the scale used when pooling. Default: 1.0. + + Shape: + - x: 4-D Tensor with shape (N, C, H, W). + - boxes: 2-D Tensor with shape (num_rois, 4). + - boxes_num: 1-D Tensor. + - output: 4-D tensor with shape (num_rois, output_channels, pooled_h, pooled_w). + The output_channels equal to C / (pooled_h * pooled_w), where C is the channels of input. + + Returns: + None. + + Examples: + .. code-block:: python + + import paddle + + psroi_module = paddle.vision.ops.PSRoIPool(7, 1.0) + x = paddle.uniform([2, 490, 28, 28], dtype='float32') + boxes = paddle.to_tensor([[1, 5, 8, 10], [4, 2, 6, 7], [12, 12, 19, 21]], dtype='float32') + boxes_num = paddle.to_tensor([1, 2], dtype='int32') + pool_out = psroi_module(x, boxes, boxes_num) + print(pool_out.shape) # [3, 10, 7, 7] + """ + + def __init__(self, output_size, spatial_scale=1.0): + super(PSRoIPool, self).__init__() + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, x, boxes, boxes_num): + return psroi_pool( + x, boxes, boxes_num, self.output_size, self.spatial_scale + ) + + +def roi_pool(x, boxes, boxes_num, output_size, spatial_scale=1.0, name=None): + """ + This operator implements the roi_pooling layer. + Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). + The operator has three steps: 1. Dividing each region proposal into equal-sized sections with output_size(h, w) 2. Finding the largest value in each section 3. Copying these max values to the output buffer + For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn. + + Args: + x (Tensor): input feature, 4D-Tensor with the shape of [N,C,H,W], + where N is the batch size, C is the input channel, H is Height, W is weight. + The data type is float32 or float64. + boxes (Tensor): boxes (Regions of Interest) to pool over. + 2D-Tensor with the shape of [num_boxes,4]. + Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, + and (x2, y2) is the bottom right coordinates. + boxes_num (Tensor): the number of RoIs in each image, data type is int32. Default: None + output_size (int or tuple[int, int]): the pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. + spatial_scale (float, optional): multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 + name(str, optional): for detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. + + Returns: + pool_out (Tensor): the pooled feature, 4D-Tensor with the shape of [num_boxes, C, output_size[0], output_size[1]]. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.ops import roi_pool + + data = paddle.rand([1, 256, 32, 32]) + boxes = paddle.rand([3, 4]) + boxes[:, 2] += boxes[:, 0] + 3 + boxes[:, 3] += boxes[:, 1] + 4 + boxes_num = paddle.to_tensor([3]).astype('int32') + pool_out = roi_pool(data, boxes, boxes_num=boxes_num, output_size=3) + assert pool_out.shape == [3, 256, 3, 3], '' + """ + + check_type(output_size, 'output_size', (int, tuple), 'roi_pool') + if isinstance(output_size, int): + output_size = (output_size, output_size) + + pooled_height, pooled_width = output_size + if in_dygraph_mode(): + assert ( + boxes_num is not None + ), "boxes_num should not be None in dygraph mode." + return _C_ops.roi_pool( + x, boxes, boxes_num, pooled_height, pooled_width, spatial_scale + ) + if _in_legacy_dygraph(): + assert ( + boxes_num is not None + ), "boxes_num should not be None in dygraph mode." + pool_out, argmaxes = _legacy_C_ops.roi_pool( + x, + boxes, + boxes_num, + "pooled_height", + pooled_height, + "pooled_width", + pooled_width, + "spatial_scale", + spatial_scale, + ) + return pool_out + + else: + check_variable_and_dtype(x, 'x', ['float32'], 'roi_pool') + check_variable_and_dtype(boxes, 'boxes', ['float32'], 'roi_pool') + helper = LayerHelper('roi_pool', **locals()) + dtype = helper.input_dtype() + pool_out = helper.create_variable_for_type_inference(dtype) + argmaxes = helper.create_variable_for_type_inference(dtype='int32') + + inputs = { + "X": x, + "ROIs": boxes, + } + if boxes_num is not None: + inputs['RoisNum'] = boxes_num + helper.append_op( + type="roi_pool", + inputs=inputs, + outputs={"Out": pool_out, "Argmax": argmaxes}, + attrs={ + "pooled_height": pooled_height, + "pooled_width": pooled_width, + "spatial_scale": spatial_scale, + }, + ) + return pool_out + + +class RoIPool(Layer): + """ + This interface is used to construct a callable object of the `RoIPool` class. Please + refer to :ref:`api_paddle_vision_ops_roi_pool`. + + Args: + output_size (int or tuple[int, int]): the pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. + spatial_scale (float, optional): multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0. + + Returns: + pool_out (Tensor): the pooled feature, 4D-Tensor with the shape of [num_boxes, C, output_size[0], output_size[1]]. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.ops import RoIPool + + data = paddle.rand([1, 256, 32, 32]) + boxes = paddle.rand([3, 4]) + boxes[:, 2] += boxes[:, 0] + 3 + boxes[:, 3] += boxes[:, 1] + 4 + boxes_num = paddle.to_tensor([3]).astype('int32') + roi_pool = RoIPool(output_size=(4, 3)) + pool_out = roi_pool(data, boxes, boxes_num) + assert pool_out.shape == [3, 256, 4, 3], '' + """ + + def __init__(self, output_size, spatial_scale=1.0): + super(RoIPool, self).__init__() + self._output_size = output_size + self._spatial_scale = spatial_scale + + def forward(self, x, boxes, boxes_num): + return roi_pool( + x=x, + boxes=boxes, + boxes_num=boxes_num, + output_size=self._output_size, + spatial_scale=self._spatial_scale, + ) + + def extra_repr(self): + main_str = 'output_size={_output_size}, spatial_scale={_spatial_scale}' + return main_str.format(**self.__dict__) + + +def roi_align( + x, + boxes, + boxes_num, + output_size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True, + name=None, +): + """ + Implementing the roi_align layer. + Region of Interest (RoI) Align operator (also known as RoI Align) is to + perform bilinear interpolation on inputs of nonuniform sizes to obtain + fixed-size feature maps (e.g. 7*7), as described in Mask R-CNN. + + Dividing each region proposal into equal-sized sections with the pooled_width + and pooled_height. Location remains the origin result. + + In each ROI bin, the value of the four regularly sampled locations are + computed directly through bilinear interpolation. The output is the mean of + four locations. Thus avoid the misaligned problem. + + Args: + x (Tensor): Input feature, 4D-Tensor with the shape of [N,C,H,W], + where N is the batch size, C is the input channel, H is Height, + W is weight. The data type is float32 or float64. + boxes (Tensor): Boxes (RoIs, Regions of Interest) to pool over. It + should be a 2-D Tensor of shape (num_boxes, 4). The data type is + float32 or float64. Given as [[x1, y1, x2, y2], ...], (x1, y1) is + the top left coordinates, and (x2, y2) is the bottom right coordinates. + boxes_num (Tensor): The number of boxes contained in each picture in + the batch, the data type is int32. + output_size (int or Tuple[int, int]): The pooled output size(h, w), data + type is int32. If int, h and w are both equal to output_size. + spatial_scale (float32, optional): Multiplicative spatial scale factor to translate + ROI coords from their input scale to the scale used when pooling. + Default: 1.0. + sampling_ratio (int32, optional): number of sampling points in the interpolation + grid used to compute the output value of each pooled output bin. + If > 0, then exactly ``sampling_ratio x sampling_ratio`` sampling + points per bin are used. + If <= 0, then an adaptive number of grid points are used (computed + as ``ceil(roi_width / output_width)``, and likewise for height). + Default: -1. + aligned (bool, optional): If False, use the legacy implementation. If True, pixel + shift the box coordinates it by -0.5 for a better alignment with the + two neighboring pixel indices. This version is used in Detectron2. + Default: True. + name(str, optional): For detailed information, please refer to : + ref:`api_guide_Name`. Usually name is no need to set and None by + default. + + Returns: + The output of ROIAlignOp is a 4-D tensor with shape (num_boxes, + channels, pooled_h, pooled_w). The data type is float32 or float64. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.ops import roi_align + + data = paddle.rand([1, 256, 32, 32]) + boxes = paddle.rand([3, 4]) + boxes[:, 2] += boxes[:, 0] + 3 + boxes[:, 3] += boxes[:, 1] + 4 + boxes_num = paddle.to_tensor([3]).astype('int32') + align_out = roi_align(data, boxes, boxes_num, output_size=3) + assert align_out.shape == [3, 256, 3, 3] + """ + + check_type(output_size, 'output_size', (int, tuple), 'roi_align') + if isinstance(output_size, int): + output_size = (output_size, output_size) + + pooled_height, pooled_width = output_size + if in_dygraph_mode(): + assert ( + boxes_num is not None + ), "boxes_num should not be None in dygraph mode." + return _C_ops.roi_align( + x, + boxes, + boxes_num, + pooled_height, + pooled_width, + spatial_scale, + sampling_ratio, + aligned, + ) + if _in_legacy_dygraph(): + assert ( + boxes_num is not None + ), "boxes_num should not be None in dygraph mode." + align_out = _legacy_C_ops.roi_align( + x, + boxes, + boxes_num, + "pooled_height", + pooled_height, + "pooled_width", + pooled_width, + "spatial_scale", + spatial_scale, + "sampling_ratio", + sampling_ratio, + "aligned", + aligned, + ) + return align_out + + else: + check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'roi_align') + check_variable_and_dtype( + boxes, 'boxes', ['float32', 'float64'], 'roi_align' + ) + helper = LayerHelper('roi_align', **locals()) + dtype = helper.input_dtype() + align_out = helper.create_variable_for_type_inference(dtype) + inputs = { + "X": x, + "ROIs": boxes, + } + if boxes_num is not None: + inputs['RoisNum'] = boxes_num + helper.append_op( + type="roi_align", + inputs=inputs, + outputs={"Out": align_out}, + attrs={ + "pooled_height": pooled_height, + "pooled_width": pooled_width, + "spatial_scale": spatial_scale, + "sampling_ratio": sampling_ratio, + "aligned": aligned, + }, + ) + return align_out + + +class RoIAlign(Layer): + """ + This interface is used to construct a callable object of the `RoIAlign` class. + Please refer to :ref:`api_paddle_vision_ops_roi_align`. + + Args: + output_size (int or tuple[int, int]): The pooled output size(h, w), + data type is int32. If int, h and w are both equal to output_size. + spatial_scale (float32, optional): Multiplicative spatial scale factor + to translate ROI coords from their input scale to the scale used + when pooling. Default: 1.0 + + Returns: + The output of ROIAlign operator is a 4-D tensor with + shape (num_boxes, channels, pooled_h, pooled_w). + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.ops import RoIAlign + + data = paddle.rand([1, 256, 32, 32]) + boxes = paddle.rand([3, 4]) + boxes[:, 2] += boxes[:, 0] + 3 + boxes[:, 3] += boxes[:, 1] + 4 + boxes_num = paddle.to_tensor([3]).astype('int32') + roi_align = RoIAlign(output_size=(4, 3)) + align_out = roi_align(data, boxes, boxes_num) + assert align_out.shape == [3, 256, 4, 3] + """ + + def __init__(self, output_size, spatial_scale=1.0): + super(RoIAlign, self).__init__() + self._output_size = output_size + self._spatial_scale = spatial_scale + + def forward(self, x, boxes, boxes_num, aligned=True): + return roi_align( + x=x, + boxes=boxes, + boxes_num=boxes_num, + output_size=self._output_size, + spatial_scale=self._spatial_scale, + aligned=aligned, + ) + + +class ConvNormActivation(Sequential): + """ + Configurable block used for Convolution-Normalzation-Activation blocks. + This code is based on the torchvision code with modifications. + You can also see at https://github.com/pytorch/vision/blob/main/torchvision/ops/misc.py#L68 + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the Convolution-Normalzation-Activation block + kernel_size: (int|list|tuple, optional): Size of the convolving kernel. Default: 3 + stride (int|list|tuple, optional): Stride of the convolution. Default: 1 + padding (int|str|tuple|list, optional): Padding added to all four sides of the input. Default: None, + in wich case it will calculated as ``padding = (kernel_size - 1) // 2 * dilation`` + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + norm_layer (Callable[..., paddle.nn.Layer], optional): Norm layer that will be stacked on top of the convolutiuon layer. + If ``None`` this layer wont be used. Default: ``paddle.nn.BatchNorm2D`` + activation_layer (Callable[..., paddle.nn.Layer], optional): Activation function which will be stacked on top of the normalization + layer (if not ``None``), otherwise on top of the conv layer. If ``None`` this layer wont be used. Default: ``paddle.nn.ReLU`` + dilation (int): Spacing between kernel elements. Default: 1 + bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``. + """ + + def __init__( + self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=None, + groups=1, + norm_layer=BatchNorm2D, + activation_layer=ReLU, + dilation=1, + bias=None, + ): + if padding is None: + padding = (kernel_size - 1) // 2 * dilation + if bias is None: + bias = norm_layer is None + layers = [ + Conv2D( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation=dilation, + groups=groups, + bias_attr=bias, + ) + ] + if norm_layer is not None: + layers.append(norm_layer(out_channels)) + if activation_layer is not None: + layers.append(activation_layer()) + super().__init__(*layers) + + +def nms( + boxes, + iou_threshold=0.3, + scores=None, + category_idxs=None, + categories=None, + top_k=None, +): + r""" + This operator implements non-maximum suppression. Non-maximum suppression (NMS) + is used to select one bounding box out of many overlapping bounding boxes in object detection. + Boxes with IoU > iou_threshold will be considered as overlapping boxes, + just one with highest score can be kept. Here IoU is Intersection Over Union, + which can be computed by: + + .. math:: + + IoU = \frac{intersection\_area(box1, box2)}{union\_area(box1, box2)} + + If scores are provided, input boxes will be sorted by their scores firstly. + + If category_idxs and categories are provided, NMS will be performed with a batched style, + which means NMS will be applied to each category respectively and results of each category + will be concated and sorted by scores. + + If K is provided, only the first k elements will be returned. Otherwise, all box indices sorted by scores will be returned. + + Args: + boxes(Tensor): The input boxes data to be computed, it's a 2D-Tensor with + the shape of [num_boxes, 4]. The data type is float32 or float64. + Given as [[x1, y1, x2, y2], …], (x1, y1) is the top left coordinates, + and (x2, y2) is the bottom right coordinates. + Their relation should be ``0 <= x1 < x2 && 0 <= y1 < y2``. + iou_threshold(float32, optional): IoU threshold for determine overlapping boxes. Default value: 0.3. + scores(Tensor, optional): Scores corresponding to boxes, it's a 1D-Tensor with + shape of [num_boxes]. The data type is float32 or float64. Default: None. + category_idxs(Tensor, optional): Category indices corresponding to boxes. + it's a 1D-Tensor with shape of [num_boxes]. The data type is int64. Default: None. + categories(List, optional): A list of unique id of all categories. The data type is int64. Default: None. + top_k(int64, optional): The top K boxes who has higher score and kept by NMS preds to + consider. top_k should be smaller equal than num_boxes. Default: None. + + Returns: + Tensor: 1D-Tensor with the shape of [num_boxes]. Indices of boxes kept by NMS. + + Examples: + .. code-block:: python + + import paddle + + boxes = paddle.rand([4, 4]).astype('float32') + boxes[:, 2] = boxes[:, 0] + boxes[:, 2] + boxes[:, 3] = boxes[:, 1] + boxes[:, 3] + print(boxes) + # Tensor(shape=[4, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[0.64811575, 0.89756244, 0.86473107, 1.48552322], + # [0.48085716, 0.84799081, 0.54517937, 0.86396021], + # [0.62646860, 0.72901905, 1.17392159, 1.69691563], + # [0.89729202, 0.46281594, 1.88733089, 0.98588502]]) + + out = paddle.vision.ops.nms(boxes, 0.1) + print(out) + # Tensor(shape=[3], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [0, 1, 3]) + + scores = paddle.to_tensor([0.6, 0.7, 0.4, 0.233]) + + categories = [0, 1, 2, 3] + category_idxs = paddle.to_tensor([2, 0, 0, 3], dtype="int64") + + out = paddle.vision.ops.nms(boxes, + 0.1, + paddle.to_tensor(scores), + paddle.to_tensor(category_idxs), + categories, + 4) + print(out) + # Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True, + # [1, 0, 2, 3]) + """ + + def _nms(boxes, iou_threshold): + if in_dygraph_mode(): + return _C_ops.nms(boxes, iou_threshold) + + if _non_static_mode(): + return _legacy_C_ops.nms(boxes, 'iou_threshold', iou_threshold) + + helper = LayerHelper('nms', **locals()) + out = helper.create_variable_for_type_inference('int64') + helper.append_op( + type='nms', + inputs={'Boxes': boxes}, + outputs={'KeepBoxesIdxs': out}, + attrs={'iou_threshold': iou_threshold}, + ) + return out + + if scores is None: + return _nms(boxes, iou_threshold) + + import paddle + + if category_idxs is None: + sorted_global_indices = paddle.argsort(scores, descending=True) + sorted_keep_boxes_indices = _nms( + boxes[sorted_global_indices], iou_threshold + ) + return sorted_global_indices[sorted_keep_boxes_indices] + + if top_k is not None: + assert ( + top_k <= scores.shape[0] + ), "top_k should be smaller equal than the number of boxes" + assert ( + categories is not None + ), "if category_idxs is given, categories which is a list of unique id of all categories is necessary" + + mask = paddle.zeros_like(scores, dtype=paddle.int32) + + for category_id in categories: + cur_category_boxes_idxs = paddle.where(category_idxs == category_id)[0] + shape = cur_category_boxes_idxs.shape[0] + cur_category_boxes_idxs = paddle.reshape( + cur_category_boxes_idxs, [shape] + ) + if shape == 0: + continue + elif shape == 1: + mask[cur_category_boxes_idxs] = 1 + continue + cur_category_boxes = boxes[cur_category_boxes_idxs] + cur_category_scores = scores[cur_category_boxes_idxs] + cur_category_sorted_indices = paddle.argsort( + cur_category_scores, descending=True + ) + cur_category_sorted_boxes = cur_category_boxes[ + cur_category_sorted_indices + ] + + cur_category_keep_boxes_sub_idxs = cur_category_sorted_indices[ + _nms(cur_category_sorted_boxes, iou_threshold) + ] + + updates = paddle.ones_like( + cur_category_boxes_idxs[cur_category_keep_boxes_sub_idxs], + dtype=paddle.int32, + ) + mask = paddle.scatter( + mask, + cur_category_boxes_idxs[cur_category_keep_boxes_sub_idxs], + updates, + overwrite=True, + ) + keep_boxes_idxs = paddle.where(mask)[0] + shape = keep_boxes_idxs.shape[0] + keep_boxes_idxs = paddle.reshape(keep_boxes_idxs, [shape]) + sorted_sub_indices = paddle.argsort( + scores[keep_boxes_idxs], descending=True + ) + + if top_k is None: + return keep_boxes_idxs[sorted_sub_indices] + + if _non_static_mode(): + top_k = shape if shape < top_k else top_k + _, topk_sub_indices = paddle.topk(scores[keep_boxes_idxs], top_k) + return keep_boxes_idxs[topk_sub_indices] + + return keep_boxes_idxs[sorted_sub_indices][:top_k] + + +def generate_proposals( + scores, + bbox_deltas, + img_size, + anchors, + variances, + pre_nms_top_n=6000, + post_nms_top_n=1000, + nms_thresh=0.5, + min_size=0.1, + eta=1.0, + pixel_offset=False, + return_rois_num=False, + name=None, +): + """ + This operation proposes RoIs according to each box with their + probability to be a foreground object. And + the proposals of RPN output are calculated by anchors, bbox_deltas and scores. Final proposals + could be used to train detection net. + + For generating proposals, this operation performs following steps: + + 1. Transpose and resize scores and bbox_deltas in size of + (H * W * A, 1) and (H * W * A, 4) + 2. Calculate box locations as proposals candidates. + 3. Clip boxes to image + 4. Remove predicted boxes with small area. + 5. Apply non-maximum suppression (NMS) to get final proposals as output. + + Args: + scores (Tensor): A 4-D Tensor with shape [N, A, H, W] represents + the probability for each box to be an object. + N is batch size, A is number of anchors, H and W are height and + width of the feature map. The data type must be float32. + bbox_deltas (Tensor): A 4-D Tensor with shape [N, 4*A, H, W] + represents the difference between predicted box location and + anchor location. The data type must be float32. + img_size (Tensor): A 2-D Tensor with shape [N, 2] represents origin + image shape information for N batch, including height and width of the input sizes. + The data type can be float32 or float64. + anchors (Tensor): A 4-D Tensor represents the anchors with a layout + of [H, W, A, 4]. H and W are height and width of the feature map, + num_anchors is the box count of each position. Each anchor is + in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32. + variances (Tensor): A 4-D Tensor. The expanded variances of anchors with a layout of + [H, W, num_priors, 4]. Each variance is in + (xcenter, ycenter, w, h) format. The data type must be float32. + pre_nms_top_n (float, optional): Number of total bboxes to be kept per + image before NMS. `6000` by default. + post_nms_top_n (float, optional): Number of total bboxes to be kept per + image after NMS. `1000` by default. + nms_thresh (float, optional): Threshold in NMS. The data type must be float32. `0.5` by default. + min_size (float, optional): Remove predicted boxes with either height or + width less than this value. `0.1` by default. + eta(float, optional): Apply in adaptive NMS, only works if adaptive `threshold > 0.5`, + `adaptive_threshold = adaptive_threshold * eta` in each iteration. 1.0 by default. + pixel_offset (bool, optional): Whether there is pixel offset. If True, the offset of `img_size` will be 1. 'False' by default. + return_rois_num (bool, optional): Whether to return `rpn_rois_num` . When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's + num of each image in one batch. 'False' by default. + name(str, optional): For detailed information, please refer + to :ref:`api_guide_Name`. Usually name is no need to set and + None by default. + + Returns: + - rpn_rois (Tensor): The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``. + - rpn_roi_probs (Tensor): The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``. + - rpn_rois_num (Tensor): Rois's num of each image in one batch. 1-D Tensor with shape ``[B,]`` while ``B`` is the batch size. And its sum equals to RoIs number ``N`` . + + Examples: + .. code-block:: python + + import paddle + + scores = paddle.rand((2,4,5,5), dtype=paddle.float32) + bbox_deltas = paddle.rand((2, 16, 5, 5), dtype=paddle.float32) + img_size = paddle.to_tensor([[224.0, 224.0], [224.0, 224.0]]) + anchors = paddle.rand((2,5,4,4), dtype=paddle.float32) + variances = paddle.rand((2,5,10,4), dtype=paddle.float32) + rois, roi_probs, roi_nums = paddle.vision.ops.generate_proposals(scores, bbox_deltas, + img_size, anchors, variances, return_rois_num=True) + print(rois, roi_probs, roi_nums) + """ + + if in_dygraph_mode(): + assert ( + return_rois_num + ), "return_rois_num should be True in dygraph mode." + attrs = ( + pre_nms_top_n, + post_nms_top_n, + nms_thresh, + min_size, + eta, + pixel_offset, + ) + rpn_rois, rpn_roi_probs, rpn_rois_num = _C_ops.generate_proposals_v2( + scores, bbox_deltas, img_size, anchors, variances, *attrs + ) + + return rpn_rois, rpn_roi_probs, rpn_rois_num + elif _non_static_mode(): + assert ( + return_rois_num + ), "return_rois_num should be True in dygraph mode." + attrs = ( + 'pre_nms_topN', + pre_nms_top_n, + 'post_nms_topN', + post_nms_top_n, + 'nms_thresh', + nms_thresh, + 'min_size', + min_size, + 'eta', + eta, + 'pixel_offset', + pixel_offset, + ) + ( + rpn_rois, + rpn_roi_probs, + rpn_rois_num, + ) = _legacy_C_ops.generate_proposals_v2( + scores, bbox_deltas, img_size, anchors, variances, *attrs + ) + + return rpn_rois, rpn_roi_probs, rpn_rois_num + + helper = LayerHelper('generate_proposals_v2', **locals()) + + check_variable_and_dtype( + scores, 'scores', ['float32'], 'generate_proposals_v2' + ) + check_variable_and_dtype( + bbox_deltas, 'bbox_deltas', ['float32'], 'generate_proposals_v2' + ) + check_variable_and_dtype( + img_size, 'img_size', ['float32', 'float64'], 'generate_proposals_v2' + ) + check_variable_and_dtype( + anchors, 'anchors', ['float32'], 'generate_proposals_v2' + ) + check_variable_and_dtype( + variances, 'variances', ['float32'], 'generate_proposals_v2' + ) + + rpn_rois = helper.create_variable_for_type_inference( + dtype=bbox_deltas.dtype + ) + rpn_roi_probs = helper.create_variable_for_type_inference( + dtype=scores.dtype + ) + outputs = { + 'RpnRois': rpn_rois, + 'RpnRoiProbs': rpn_roi_probs, + } + if return_rois_num: + rpn_rois_num = helper.create_variable_for_type_inference(dtype='int32') + rpn_rois_num.stop_gradient = True + outputs['RpnRoisNum'] = rpn_rois_num + + helper.append_op( + type="generate_proposals_v2", + inputs={ + 'Scores': scores, + 'BboxDeltas': bbox_deltas, + 'ImShape': img_size, + 'Anchors': anchors, + 'Variances': variances, + }, + attrs={ + 'pre_nms_topN': pre_nms_top_n, + 'post_nms_topN': post_nms_top_n, + 'nms_thresh': nms_thresh, + 'min_size': min_size, + 'eta': eta, + 'pixel_offset': pixel_offset, + }, + outputs=outputs, + ) + rpn_rois.stop_gradient = True + rpn_roi_probs.stop_gradient = True + if not return_rois_num: + rpn_rois_num = None + + return rpn_rois, rpn_roi_probs, rpn_rois_num + + +def matrix_nms( + bboxes, + scores, + score_threshold, + post_threshold, + nms_top_k, + keep_top_k, + use_gaussian=False, + gaussian_sigma=2.0, + background_label=0, + normalized=True, + return_index=False, + return_rois_num=True, + name=None, +): + """ + + This operator does matrix non maximum suppression (NMS). + First selects a subset of candidate bounding boxes that have higher scores + than score_threshold (if provided), then the top k candidate is selected if + nms_top_k is larger than -1. Score of the remaining candidate are then + decayed according to the Matrix NMS scheme. + Aftern NMS step, at most keep_top_k number of total bboxes are to be kept + per image if keep_top_k is larger than -1. + + Args: + bboxes (Tensor): A 3-D Tensor with shape [N, M, 4] represents the + predicted locations of M bounding bboxes, + N is the batch size. Each bounding box has four + coordinate values and the layout is + [xmin, ymin, xmax, ymax], when box size equals to 4. + The data type is float32 or float64. + scores (Tensor): A 3-D Tensor with shape [N, C, M] + represents the predicted confidence predictions. + N is the batch size, C is the class number, M is + number of bounding boxes. For each category there + are total M scores which corresponding M bounding + boxes. Please note, M is equal to the 2nd dimension + of BBoxes. The data type is float32 or float64. + score_threshold (float): Threshold to filter out bounding boxes with + low confidence score. + post_threshold (float): Threshold to filter out bounding boxes with + low confidence score AFTER decaying. + nms_top_k (int): Maximum number of detections to be kept according to + the confidences after the filtering detections based + on score_threshold. + keep_top_k (int): Number of total bboxes to be kept per image after NMS + step. -1 means keeping all bboxes after NMS step. + use_gaussian (bool, optional): Use Gaussian as the decay function. Default: False + gaussian_sigma (float, optional): Sigma for Gaussian decay function. Default: 2.0 + background_label (int, optional): The index of background label, the background + label will be ignored. If set to -1, then all + categories will be considered. Default: 0 + normalized (bool, optional): Whether detections are normalized. Default: True + return_index(bool, optional): Whether return selected index. Default: False + return_rois_num(bool, optional): whether return rois_num. Default: True + name(str, optional): Name of the matrix nms op. Default: None. + Returns: + - A tuple with three Tensor, (Out, Index, RoisNum) if return_index is True, + otherwise, a tuple with two Tensor (Out, RoisNum) is returned. + - Out (Tensor), A 2-D Tensor with shape [No, 6] containing the + detection results. + Each row has 6 values, [label, confidence, xmin, ymin, xmax, ymax] + - Index (Tensor), A 2-D Tensor with shape [No, 1] containing the + selected indices, which are absolute values cross batches. + - rois_num (Tensor), A 1-D Tensor with shape [N] containing + the number of detected boxes in each image. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.ops import matrix_nms + + boxes = paddle.rand([4, 1, 4]) + boxes[..., 2] = boxes[..., 0] + boxes[..., 2] + boxes[..., 3] = boxes[..., 1] + boxes[..., 3] + scores = paddle.rand([4, 80, 1]) + out = matrix_nms(bboxes=boxes, scores=scores, background_label=0, + score_threshold=0.5, post_threshold=0.1, + nms_top_k=400, keep_top_k=200, normalized=False) + + """ + check_variable_and_dtype( + bboxes, 'BBoxes', ['float32', 'float64'], 'matrix_nms' + ) + check_variable_and_dtype( + scores, 'Scores', ['float32', 'float64'], 'matrix_nms' + ) + check_type(score_threshold, 'score_threshold', float, 'matrix_nms') + check_type(post_threshold, 'post_threshold', float, 'matrix_nms') + check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms') + check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms') + check_type(normalized, 'normalized', bool, 'matrix_nms') + check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms') + check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms') + check_type(background_label, 'background_label', int, 'matrix_nms') + + if in_dygraph_mode(): + out, index, rois_num = _C_ops.matrix_nms( + bboxes, + scores, + score_threshold, + nms_top_k, + keep_top_k, + post_threshold, + use_gaussian, + gaussian_sigma, + background_label, + normalized, + ) + if not return_index: + index = None + if not return_rois_num: + rois_num = None + return out, rois_num, index + elif _in_legacy_dygraph(): + attrs = ( + 'background_label', + background_label, + 'score_threshold', + score_threshold, + 'post_threshold', + post_threshold, + 'nms_top_k', + nms_top_k, + 'gaussian_sigma', + gaussian_sigma, + 'use_gaussian', + use_gaussian, + 'keep_top_k', + keep_top_k, + 'normalized', + normalized, + ) + out, index, rois_num = _legacy_C_ops.matrix_nms(bboxes, scores, *attrs) + if not return_index: + index = None + if not return_rois_num: + rois_num = None + return out, rois_num, index + else: + helper = LayerHelper('matrix_nms', **locals()) + output = helper.create_variable_for_type_inference(dtype=bboxes.dtype) + index = helper.create_variable_for_type_inference(dtype='int32') + outputs = {'Out': output, 'Index': index} + if return_rois_num: + rois_num = helper.create_variable_for_type_inference(dtype='int32') + outputs['RoisNum'] = rois_num + + helper.append_op( + type="matrix_nms", + inputs={'BBoxes': bboxes, 'Scores': scores}, + attrs={ + 'background_label': background_label, + 'score_threshold': score_threshold, + 'post_threshold': post_threshold, + 'nms_top_k': nms_top_k, + 'gaussian_sigma': gaussian_sigma, + 'use_gaussian': use_gaussian, + 'keep_top_k': keep_top_k, + 'normalized': normalized, + }, + outputs=outputs, + ) + output.stop_gradient = True + + if not return_index: + index = None + if not return_rois_num: + rois_num = None + return output, rois_num, index diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d615598bf2bccb2b00d4d08ead2285a64ba7e092 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/__init__.py @@ -0,0 +1,93 @@ +# 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. + +from .transforms import BaseTransform # noqa: F401 +from .transforms import Compose # noqa: F401 +from .transforms import Resize # noqa: F401 +from .transforms import RandomResizedCrop # noqa: F401 +from .transforms import CenterCrop # noqa: F401 +from .transforms import RandomHorizontalFlip # noqa: F401 +from .transforms import RandomVerticalFlip # noqa: F401 +from .transforms import Transpose # noqa: F401 +from .transforms import Normalize # noqa: F401 +from .transforms import BrightnessTransform # noqa: F401 +from .transforms import SaturationTransform # noqa: F401 +from .transforms import ContrastTransform # noqa: F401 +from .transforms import HueTransform # noqa: F401 +from .transforms import ColorJitter # noqa: F401 +from .transforms import RandomCrop # noqa: F401 +from .transforms import Pad # noqa: F401 +from .transforms import RandomAffine # noqa: F401 +from .transforms import RandomRotation # noqa: F401 +from .transforms import RandomPerspective # noqa: F401 +from .transforms import Grayscale # noqa: F401 +from .transforms import ToTensor # noqa: F401 +from .transforms import RandomErasing # noqa: F401 +from .functional import to_tensor # noqa: F401 +from .functional import hflip # noqa: F401 +from .functional import vflip # noqa: F401 +from .functional import resize # noqa: F401 +from .functional import pad # noqa: F401 +from .functional import affine # noqa: F401 +from .functional import rotate # noqa: F401 +from .functional import perspective # noqa: F401 +from .functional import to_grayscale # noqa: F401 +from .functional import crop # noqa: F401 +from .functional import center_crop # noqa: F401 +from .functional import adjust_brightness # noqa: F401 +from .functional import adjust_contrast # noqa: F401 +from .functional import adjust_hue # noqa: F401 +from .functional import normalize # noqa: F401 +from .functional import erase # noqa: F401 + +__all__ = [ #noqa + 'BaseTransform', + 'Compose', + 'Resize', + 'RandomResizedCrop', + 'CenterCrop', + 'RandomHorizontalFlip', + 'RandomVerticalFlip', + 'Transpose', + 'Normalize', + 'BrightnessTransform', + 'SaturationTransform', + 'ContrastTransform', + 'HueTransform', + 'ColorJitter', + 'RandomCrop', + 'Pad', + 'RandomAffine', + 'RandomRotation', + 'RandomPerspective', + 'Grayscale', + 'ToTensor', + 'RandomErasing', + 'to_tensor', + 'hflip', + 'vflip', + 'resize', + 'pad', + 'affine', + 'rotate', + 'perspective', + 'to_grayscale', + 'crop', + 'center_crop', + 'adjust_brightness', + 'adjust_contrast', + 'adjust_hue', + 'normalize', + 'erase', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc160b0c0e07ae8e38d02ec282c12b33ed540a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional.py @@ -0,0 +1,1005 @@ +# 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. + +from __future__ import division + +import sys +import math +import numbers +import warnings +import collections + +import numpy as np +from PIL import Image +from numpy import sin, cos, tan +import paddle + +from . import functional_pil as F_pil +from . import functional_cv2 as F_cv2 +from . import functional_tensor as F_t + +__all__ = [] + + +def _is_pil_image(img): + return isinstance(img, Image.Image) + + +def _is_tensor_image(img): + return isinstance(img, paddle.Tensor) + + +def _is_numpy_image(img): + return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) + + +def to_tensor(pic, data_format='CHW'): + """Converts a ``PIL.Image`` or ``numpy.ndarray`` to paddle.Tensor. + + See ``ToTensor`` for more details. + + Args: + pic (PIL.Image|np.ndarray): Image to be converted to tensor. + data_format (str, optional): Data format of output tensor, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + Tensor: Converted image. Data type is same as input img. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + tensor = F.to_tensor(fake_img) + print(tensor.shape) + + """ + if not (_is_pil_image(pic) or _is_numpy_image(pic) + or _is_tensor_image(pic)): + raise TypeError( + 'pic should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(pic))) + + if _is_pil_image(pic): + return F_pil.to_tensor(pic, data_format) + elif _is_numpy_image(pic): + return F_cv2.to_tensor(pic, data_format) + else: + return pic if data_format.lower() == 'chw' else pic.transpose((1, 2, 0)) + + +def resize(img, size, interpolation='bilinear'): + """ + Resizes the image to given size + + Args: + input (PIL.Image|np.ndarray): Image to be resized. + size (int|list|tuple): Target size of input data, with (height, width) shape. + interpolation (int|str, optional): Interpolation method. when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC, + - "box": Image.BOX, + - "lanczos": Image.LANCZOS, + - "hamming": Image.HAMMING + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "area": cv2.INTER_AREA, + - "bicubic": cv2.INTER_CUBIC, + - "lanczos": cv2.INTER_LANCZOS4 + + Returns: + PIL.Image or np.array: Resized image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + converted_img = F.resize(fake_img, 224) + print(converted_img.size) + # (262, 224) + + converted_img = F.resize(fake_img, (200, 150)) + print(converted_img.size) + # (150, 200) + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.resize(img, size, interpolation) + elif _is_tensor_image(img): + return F_t.resize(img, size, interpolation) + else: + return F_cv2.resize(img, size, interpolation) + + +def pad(img, padding, fill=0, padding_mode='constant'): + """ + Pads the given PIL.Image or numpy.array on all sides with specified padding mode and fill value. + + Args: + img (PIL.Image|np.array): Image to be padded. + padding (int|list|tuple): Padding on each border. If a single int is provided this + is used to pad all borders. If list/tuple of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a list/tuple of length 4 is provided + this is the padding for the left, top, right and bottom borders + respectively. + fill (float, optional): Pixel fill value for constant fill. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. Default: 0. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value on the edge of the image + + - reflect: pads with reflection of image (without repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image (repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + PIL.Image or np.array: Padded image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + padded_img = F.pad(fake_img, padding=1) + print(padded_img.size) + + padded_img = F.pad(fake_img, padding=(2, 1)) + print(padded_img.size) + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.pad(img, padding, fill, padding_mode) + elif _is_tensor_image(img): + return F_t.pad(img, padding, fill, padding_mode) + else: + return F_cv2.pad(img, padding, fill, padding_mode) + + +def crop(img, top, left, height, width): + """Crops the given Image. + + Args: + img (PIL.Image|np.array): Image to be cropped. (0,0) denotes the top left + corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + + Returns: + PIL.Image or np.array: Cropped image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + cropped_img = F.crop(fake_img, 56, 150, 200, 100) + print(cropped_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.crop(img, top, left, height, width) + elif _is_tensor_image(img): + return F_t.crop(img, top, left, height, width) + else: + return F_cv2.crop(img, top, left, height, width) + + +def center_crop(img, output_size): + """Crops the given Image and resize it to desired size. + + Args: + img (PIL.Image|np.array): Image to be cropped. (0,0) denotes the top left corner of the image. + output_size (sequence or int): (height, width) of the crop box. If int, + it is used for both directions + + Returns: + PIL.Image or np.array: Cropped image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + cropped_img = F.center_crop(fake_img, (150, 100)) + print(cropped_img.size) + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.center_crop(img, output_size) + elif _is_tensor_image(img): + return F_t.center_crop(img, output_size) + else: + return F_cv2.center_crop(img, output_size) + + +def hflip(img): + """Horizontally flips the given Image or np.array. + + Args: + img (PIL.Image|np.array): Image to be flipped. + + Returns: + PIL.Image or np.array: Horizontall flipped image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + flpped_img = F.hflip(fake_img) + print(flpped_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.hflip(img) + elif _is_tensor_image(img): + return F_t.hflip(img) + else: + return F_cv2.hflip(img) + + +def vflip(img): + """Vertically flips the given Image or np.array. + + Args: + img (PIL.Image|np.array): Image to be flipped. + + Returns: + PIL.Image or np.array: Vertically flipped image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + flpped_img = F.vflip(fake_img) + print(flpped_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.vflip(img) + elif _is_tensor_image(img): + return F_t.vflip(img) + else: + return F_cv2.vflip(img) + + +def adjust_brightness(img, brightness_factor): + """Adjusts brightness of an Image. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be adjusted. + brightness_factor (float): How much to adjust the brightness. Can be + any non negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + PIL.Image|np.array|paddle.Tensor: Brightness adjusted image. + + Examples: + .. code-block:: python + :name: code-example1 + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + print(fake_img.size) # (300, 256) + print(fake_img.load()[1,1]) # (95, 127, 202) + converted_img = F.adjust_brightness(fake_img, 0.5) + print(converted_img.size) # (300, 256) + print(converted_img.load()[1,1]) # (47, 63, 101) + + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.adjust_brightness(img, brightness_factor) + elif _is_numpy_image(img): + return F_cv2.adjust_brightness(img, brightness_factor) + else: + return F_t.adjust_brightness(img, brightness_factor) + + +def adjust_contrast(img, contrast_factor): + """Adjusts contrast of an Image. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be adjusted. + contrast_factor (float): How much to adjust the contrast. Can be any + non negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + PIL.Image|np.array|paddle.Tensor: Contrast adjusted image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + converted_img = F.adjust_contrast(fake_img, 0.4) + print(converted_img.size) + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.adjust_contrast(img, contrast_factor) + elif _is_numpy_image(img): + return F_cv2.adjust_contrast(img, contrast_factor) + else: + return F_t.adjust_contrast(img, contrast_factor) + + +def adjust_saturation(img, saturation_factor): + """Adjusts color saturation of an image. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be adjusted. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + PIL.Image|np.array|paddle.Tensor: Saturation adjusted image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + converted_img = F.adjust_saturation(fake_img, 0.4) + print(converted_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.adjust_saturation(img, saturation_factor) + elif _is_numpy_image(img): + return F_cv2.adjust_saturation(img, saturation_factor) + else: + return F_t.adjust_saturation(img, saturation_factor) + + +def adjust_hue(img, hue_factor): + """Adjusts hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be adjusted. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + PIL.Image|np.array|paddle.Tensor: Hue adjusted image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + converted_img = F.adjust_hue(fake_img, 0.4) + print(converted_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.adjust_hue(img, hue_factor) + elif _is_numpy_image(img): + return F_cv2.adjust_hue(img, hue_factor) + else: + return F_t.adjust_hue(img, hue_factor) + + +def _get_affine_matrix(center, angle, translate, scale, shear): + # Affine matrix is : M = T * C * RotateScaleShear * C^-1 + # Ihe inverse one is : M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1 + rot = math.radians(angle) + sx = math.radians(shear[0]) + sy = math.radians(shear[1]) + + # Rotate and Shear without scaling + a = math.cos(rot - sy) / math.cos(sy) + b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot) + c = math.sin(rot - sy) / math.cos(sy) + d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot) + + # Center Translation + cx, cy = center + tx, ty = translate + + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + matrix = [d, -b, 0.0, -c, a, 0.0] + matrix = [x / scale for x in matrix] + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty) + matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty) + # Apply center translation: C * RSS^-1 * C^-1 * T^-1 + matrix[2] += cx + matrix[5] += cy + + return matrix + + +def affine(img, + angle, + translate, + scale, + shear, + interpolation="nearest", + fill=0, + center=None): + """Apply affine transformation on the image. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be affined. + angle (int|float): The angle of the random rotation in clockwise order. + translate (list[float]): Maximum absolute fraction for horizontal and vertical translations. + scale (float): Scale factor for the image, scale should be positive. + shear (list[float]): Shear angle values which are parallel to the x-axis and y-axis in clockwise order. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST + according the backend. + When use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + When use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + center (2-tuple, optional): Optional center of rotation, (x, y). + Origin is the upper left corner. + Default is the center of the image. + + Returns: + PIL.Image|np.array|paddle.Tensor: Affine Transformed image. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.transforms import functional as F + + fake_img = paddle.randn((3, 256, 300)).astype(paddle.float32) + + affined_img = F.affine(fake_img, 45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 10]) + print(affined_img.shape) + """ + + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if not isinstance(translate, (list, tuple)): + raise TypeError("Argument translate should be a sequence") + + if len(translate) != 2: + raise ValueError("Argument translate should be a sequence of length 2") + + if scale <= 0.0: + raise ValueError("Argument scale should be positive") + + if not isinstance(shear, (numbers.Number, (list, tuple))): + raise TypeError( + "Shear should be either a single value or a sequence of two values") + + if not isinstance(interpolation, str): + raise TypeError("Argument interpolation should be a string") + + if isinstance(angle, int): + angle = float(angle) + + if isinstance(translate, tuple): + translate = list(translate) + + if isinstance(shear, numbers.Number): + shear = [shear, 0.0] + + if isinstance(shear, tuple): + shear = list(shear) + + if len(shear) == 1: + shear = [shear[0], shear[0]] + + if len(shear) != 2: + raise ValueError( + f"Shear should be a sequence containing two values. Got {shear}") + + if center is not None and not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + + if _is_pil_image(img): + width, height = img.size + # center = (width * 0.5 + 0.5, height * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of F_t.affine + if center is None: + center = [width * 0.5, height * 0.5] + matrix = _get_affine_matrix(center, angle, translate, scale, shear) + return F_pil.affine(img, matrix, interpolation, fill) + + if _is_numpy_image(img): + # get affine_matrix in F_cv2.affine() using cv2's functions + width, height = img.shape[0:2] + # center = (width * 0.5 + 0.5, height * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of F_t.affine + if center is None: + center = (width * 0.5, height * 0.5) + return F_cv2.affine(img, angle, translate, scale, shear, interpolation, + fill, center) + + if _is_tensor_image(img): + center_f = [0.0, 0.0] + if center is not None: + height, width = img.shape[-1], img.shape[-2] + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [ + 1.0 * (c - s * 0.5) for c, s in zip(center, [width, height]) + ] + translate_f = [1.0 * t for t in translate] + matrix = _get_affine_matrix(center_f, angle, translate_f, scale, shear) + return F_t.affine(img, matrix, interpolation, fill) + + +def rotate(img, + angle, + interpolation="nearest", + expand=False, + center=None, + fill=0): + """Rotates the image by angle. + + + Args: + img (PIL.Image|np.array): Image to be rotated. + angle (float or int): In degrees degrees counter clockwise order. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST + according the backend. when use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (2-list|2-tuple, optional): Optional center of rotation. + Origin is the upper left corner. + Default is the center of the image. + fill (3-list|3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + + Returns: + PIL.Image or np.array: Rotated image. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + rotated_img = F.rotate(fake_img, 90) + print(rotated_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if isinstance(center, list): + center = tuple(center) + if isinstance(fill, list): + fill = tuple(fill) + + if _is_pil_image(img): + return F_pil.rotate(img, angle, interpolation, expand, center, fill) + elif _is_tensor_image(img): + return F_t.rotate(img, angle, interpolation, expand, center, fill) + else: + return F_cv2.rotate(img, angle, interpolation, expand, center, fill) + + +def _get_perspective_coeffs(startpoints, endpoints): + """ + get coefficients (a, b, c, d, e, f, g, h) of the perspective transforms. + + In Perspective Transform each pixel (x, y) in the original image gets transformed as, + (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) ) + + Args: + startpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the original image, + endpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the transformed image. + + Returns: + output (list): octuple (a, b, c, d, e, f, g, h) for transforming each pixel. + """ + a_matrix = np.zeros((2 * len(startpoints), 8)) + + for i, (p1, p2) in enumerate(zip(endpoints, startpoints)): + a_matrix[2 * i, :] = [ + p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1] + ] + a_matrix[2 * i + 1, :] = [ + 0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1] + ] + + b_matrix = np.array(startpoints).reshape([8]) + res = np.linalg.lstsq(a_matrix, b_matrix)[0] + + output = list(res) + return output + + +def perspective(img, startpoints, endpoints, interpolation='nearest', fill=0): + """Perform perspective transform of the given image. + + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be transformed. + startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. + endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST + according the backend. + When use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + When use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + Returns: + PIL.Image|np.array|paddle.Tensor: transformed Image. + + Examples: + .. code-block:: python + + import paddle + from paddle.vision.transforms import functional as F + + fake_img = paddle.randn((3, 256, 300)).astype(paddle.float32) + + startpoints = [[0, 0], [33, 0], [33, 25], [0, 25]] + endpoints = [[3, 2], [32, 3], [30, 24], [2, 25]] + + perspectived_img = F.perspective(fake_img, startpoints, endpoints) + print(perspectived_img.shape) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + coeffs = _get_perspective_coeffs(startpoints, endpoints) + return F_pil.perspective(img, coeffs, interpolation, fill) + elif _is_tensor_image(img): + coeffs = _get_perspective_coeffs(startpoints, endpoints) + return F_t.perspective(img, coeffs, interpolation, fill) + else: + return F_cv2.perspective(img, startpoints, endpoints, interpolation, + fill) + + +def to_grayscale(img, num_output_channels=1): + """Converts image to grayscale version of image. + + Args: + img (PIL.Image|np.array): Image to be converted to grayscale. + + Returns: + PIL.Image or np.array: Grayscale version of the image. + if num_output_channels = 1 : returned image is single channel + + if num_output_channels = 3 : returned image is 3 channel with r = g = b + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + gray_img = F.to_grayscale(fake_img) + print(gray_img.size) + + """ + if not (_is_pil_image(img) or _is_numpy_image(img) + or _is_tensor_image(img)): + raise TypeError( + 'img should be PIL Image or Tensor Image or ndarray with dim=[2 or 3]. Got {}' + .format(type(img))) + + if _is_pil_image(img): + return F_pil.to_grayscale(img, num_output_channels) + elif _is_tensor_image(img): + return F_t.to_grayscale(img, num_output_channels) + else: + return F_cv2.to_grayscale(img, num_output_channels) + + +def normalize(img, mean, std, data_format='CHW', to_rgb=False): + """Normalizes a tensor or image with mean and standard deviation. + + Args: + img (PIL.Image|np.array|paddle.Tensor): input data to be normalized. + mean (list|tuple): Sequence of means for each channel. + std (list|tuple): Sequence of standard deviations for each channel. + data_format (str, optional): Data format of input img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + to_rgb (bool, optional): Whether to convert to rgb. If input is tensor, + this option will be igored. Default: False. + + Returns: + np.ndarray or Tensor: Normalized mage. Data format is same as input img. + + Examples: + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import functional as F + + fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') + + fake_img = Image.fromarray(fake_img) + + mean = [127.5, 127.5, 127.5] + std = [127.5, 127.5, 127.5] + + normalized_img = F.normalize(fake_img, mean, std, data_format='HWC') + print(normalized_img.max(), normalized_img.min()) + + """ + + if _is_tensor_image(img): + return F_t.normalize(img, mean, std, data_format) + else: + if _is_pil_image(img): + img = np.array(img).astype(np.float32) + + return F_cv2.normalize(img, mean, std, data_format, to_rgb) + + +def erase(img, i, j, h, w, v, inplace=False): + """Erase the pixels of selected area in input image with given value. + + Args: + img (paddle.Tensor | np.array | PIL.Image): input Tensor image. + For Tensor input, the shape should be (C, H, W). For np.array input, + the shape should be (H, W, C). + i (int): y coordinate of the top-left point of erased region. + j (int): x coordinate of the top-left point of erased region. + h (int): Height of the erased region. + w (int): Width of the erased region. + v (paddle.Tensor | np.array): value used to replace the pixels in erased region. It + should be np.array when img is np.array or PIL.Image. + inplace (bool, optional): Whether this transform is inplace. Default: False. + + Returns: + paddle.Tensor | np.array | PIL.Image: Erased image. The type is same with input image. + + Examples: + .. code-block:: python + + import paddle + + fake_img = paddle.randn((3, 2, 4)).astype(paddle.float32) + print(fake_img) + + #Tensor(shape=[3, 2, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[ 0.02169025, -0.97859967, -1.39175487, -1.07478464], + # [ 0.20654772, 1.74624777, 0.32268861, -0.13857445]], + # + # [[-0.14993843, 1.10793507, -0.40056887, -1.94395220], + # [ 0.41686651, 0.44551995, -0.09356714, -0.60898107]], + # + # [[-0.24998808, -1.47699273, -0.88838995, 0.42629015], + # [ 0.56948012, -0.96200180, 0.53355658, 3.20450878]]]) + + values = paddle.zeros((1,1,1), dtype=paddle.float32) + result = paddle.vision.transforms.erase(fake_img, 0, 1, 1, 2, values) + + print(result) + + #Tensor(shape=[3, 2, 4], dtype=float32, place=Place(gpu:0), stop_gradient=True, + # [[[ 0.02169025, 0. , 0. , -1.07478464], + # [ 0.20654772, 1.74624777, 0.32268861, -0.13857445]], + # + # [[-0.14993843, 0. , 0. , -1.94395220], + # [ 0.41686651, 0.44551995, -0.09356714, -0.60898107]], + # + # [[-0.24998808, 0. , 0. , 0.42629015], + # [ 0.56948012, -0.96200180, 0.53355658, 3.20450878]]]) + + """ + if _is_tensor_image(img): + return F_t.erase(img, i, j, h, w, v, inplace=inplace) + elif _is_pil_image(img): + return F_pil.erase(img, i, j, h, w, v, inplace=inplace) + else: + return F_cv2.erase(img, i, j, h, w, v, inplace=inplace) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_cv2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_cv2.py new file mode 100644 index 0000000000000000000000000000000000000000..df31add6f77db99625ef8e526d202b9d2e5981c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_cv2.py @@ -0,0 +1,710 @@ +# 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. + +from __future__ import division + +import sys +import math +import numbers +import warnings +import collections + +import numpy as np +from numpy import sin, cos, tan + +import paddle +from paddle.utils import try_import + +if sys.version_info < (3, 3): + Sequence = collections.Sequence + Iterable = collections.Iterable +else: + Sequence = collections.abc.Sequence + Iterable = collections.abc.Iterable + +__all__ = [] + + +def to_tensor(pic, data_format='CHW'): + """Converts a ``numpy.ndarray`` to paddle.Tensor. + + See ``ToTensor`` for more details. + + Args: + pic (np.ndarray): Image to be converted to tensor. + data_format (str, optional): Data format of output tensor, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + Tensor: Converted image. + + """ + + if data_format not in ['CHW', 'HWC']: + raise ValueError( + 'data_format should be CHW or HWC. Got {}'.format(data_format)) + + if pic.ndim == 2: + pic = pic[:, :, None] + + if data_format == 'CHW': + img = paddle.to_tensor(pic.transpose((2, 0, 1))) + else: + img = paddle.to_tensor(pic) + + if paddle.fluid.data_feeder.convert_dtype(img.dtype) == 'uint8': + return paddle.cast(img, np.float32) / 255. + else: + return img + + +def resize(img, size, interpolation='bilinear'): + """ + Resizes the image to given size + + Args: + input (np.ndarray): Image to be resized. + size (int|list|tuple): Target size of input data, with (height, width) shape. + interpolation (int|str, optional): Interpolation method. when use cv2 backend, + support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "area": cv2.INTER_AREA, + - "bicubic": cv2.INTER_CUBIC, + - "lanczos": cv2.INTER_LANCZOS4 + + Returns: + np.array: Resized image. + + """ + cv2 = try_import('cv2') + _cv2_interp_from_str = { + 'nearest': cv2.INTER_NEAREST, + 'bilinear': cv2.INTER_LINEAR, + 'area': cv2.INTER_AREA, + 'bicubic': cv2.INTER_CUBIC, + 'lanczos': cv2.INTER_LANCZOS4 + } + + if not (isinstance(size, int) or + (isinstance(size, Iterable) and len(size) == 2)): + raise TypeError('Got inappropriate size arg: {}'.format(size)) + + h, w = img.shape[:2] + + if isinstance(size, int): + if (w <= h and w == size) or (h <= w and h == size): + return img + if w < h: + ow = size + oh = int(size * h / w) + output = cv2.resize( + img, + dsize=(ow, oh), + interpolation=_cv2_interp_from_str[interpolation]) + else: + oh = size + ow = int(size * w / h) + output = cv2.resize( + img, + dsize=(ow, oh), + interpolation=_cv2_interp_from_str[interpolation]) + else: + output = cv2.resize(img, + dsize=(size[1], size[0]), + interpolation=_cv2_interp_from_str[interpolation]) + if len(img.shape) == 3 and img.shape[2] == 1: + return output[:, :, np.newaxis] + else: + return output + + +def pad(img, padding, fill=0, padding_mode='constant'): + """ + Pads the given numpy.array on all sides with specified padding mode and fill value. + + Args: + img (np.array): Image to be padded. + padding (int|list|tuple): Padding on each border. If a single int is provided this + is used to pad all borders. If list/tuple of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a list/tuple of length 4 is provided + this is the padding for the left, top, right and bottom borders + respectively. + fill (float, optional): Pixel fill value for constant fill. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. Default: 0. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value on the edge of the image + + - reflect: pads with reflection of image (without repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image (repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + np.array: Padded image. + + """ + cv2 = try_import('cv2') + _cv2_pad_from_str = { + 'constant': cv2.BORDER_CONSTANT, + 'edge': cv2.BORDER_REPLICATE, + 'reflect': cv2.BORDER_REFLECT_101, + 'symmetric': cv2.BORDER_REFLECT + } + + if not isinstance(padding, (numbers.Number, list, tuple)): + raise TypeError('Got inappropriate padding arg') + if not isinstance(fill, (numbers.Number, str, list, tuple)): + raise TypeError('Got inappropriate fill arg') + if not isinstance(padding_mode, str): + raise TypeError('Got inappropriate padding_mode arg') + + if isinstance(padding, Sequence) and len(padding) not in [2, 4]: + raise ValueError( + "Padding must be an int or a 2, or 4 element tuple, not a " + + "{} element tuple".format(len(padding))) + + assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \ + 'Padding mode should be either constant, edge, reflect or symmetric' + + if isinstance(padding, list): + padding = tuple(padding) + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + if isinstance(padding, Sequence) and len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + if isinstance(padding, Sequence) and len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.copyMakeBorder(img, + top=pad_top, + bottom=pad_bottom, + left=pad_left, + right=pad_right, + borderType=_cv2_pad_from_str[padding_mode], + value=fill)[:, :, np.newaxis] + else: + return cv2.copyMakeBorder(img, + top=pad_top, + bottom=pad_bottom, + left=pad_left, + right=pad_right, + borderType=_cv2_pad_from_str[padding_mode], + value=fill) + + +def crop(img, top, left, height, width): + """Crops the given image. + + Args: + img (np.array): Image to be cropped. (0,0) denotes the top left + corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + + Returns: + np.array: Cropped image. + + """ + + return img[top:top + height, left:left + width, :] + + +def center_crop(img, output_size): + """Crops the given image and resize it to desired size. + + Args: + img (np.array): Image to be cropped. (0,0) denotes the top left corner of the image. + output_size (sequence or int): (height, width) of the crop box. If int, + it is used for both directions + backend (str, optional): The image proccess backend type. Options are `pil`, `cv2`. Default: 'pil'. + + Returns: + np.array: Cropped image. + + """ + + if isinstance(output_size, numbers.Number): + output_size = (int(output_size), int(output_size)) + + h, w = img.shape[0:2] + th, tw = output_size + i = int(round((h - th) / 2.)) + j = int(round((w - tw) / 2.)) + return crop(img, i, j, th, tw) + + +def hflip(img): + """Horizontally flips the given image. + + Args: + img (np.array): Image to be flipped. + + Returns: + np.array: Horizontall flipped image. + + """ + cv2 = try_import('cv2') + + return cv2.flip(img, 1) + + +def vflip(img): + """Vertically flips the given np.array. + + Args: + img (np.array): Image to be flipped. + + Returns: + np.array: Vertically flipped image. + + """ + cv2 = try_import('cv2') + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.flip(img, 0)[:, :, np.newaxis] + else: + return cv2.flip(img, 0) + + +def adjust_brightness(img, brightness_factor): + """Adjusts brightness of an image. + + Args: + img (np.array): Image to be adjusted. + brightness_factor (float): How much to adjust the brightness. Can be + any non negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + np.array: Brightness adjusted image. + + """ + cv2 = try_import('cv2') + + table = np.array([i * brightness_factor + for i in range(0, 256)]).clip(0, 255).astype('uint8') + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.LUT(img, table)[:, :, np.newaxis] + else: + return cv2.LUT(img, table) + + +def adjust_contrast(img, contrast_factor): + """Adjusts contrast of an image. + + Args: + img (np.array): Image to be adjusted. + contrast_factor (float): How much to adjust the contrast. Can be any + non negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + np.array: Contrast adjusted image. + + """ + cv2 = try_import('cv2') + + table = np.array([(i - 74) * contrast_factor + 74 + for i in range(0, 256)]).clip(0, 255).astype('uint8') + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.LUT(img, table)[:, :, np.newaxis] + else: + return cv2.LUT(img, table) + + +def adjust_saturation(img, saturation_factor): + """Adjusts color saturation of an image. + + Args: + img (np.array): Image to be adjusted. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + np.array: Saturation adjusted image. + + """ + cv2 = try_import('cv2') + + dtype = img.dtype + img = img.astype(np.float32) + alpha = np.random.uniform(max(0, 1 - saturation_factor), + 1 + saturation_factor) + gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + gray_img = gray_img[..., np.newaxis] + img = img * alpha + gray_img * (1 - alpha) + return img.clip(0, 255).astype(dtype) + + +def adjust_hue(img, hue_factor): + """Adjusts hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + Args: + img (np.array): Image to be adjusted. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + np.array: Hue adjusted image. + + """ + cv2 = try_import('cv2') + + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError( + 'hue_factor:{} is not in [-0.5, 0.5].'.format(hue_factor)) + + dtype = img.dtype + img = img.astype(np.uint8) + hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV_FULL) + h, s, v = cv2.split(hsv_img) + + alpha = np.random.uniform(hue_factor, hue_factor) + h = h.astype(np.uint8) + # uint8 addition take cares of rotation across boundaries + with np.errstate(over="ignore"): + h += np.uint8(alpha * 255) + hsv_img = cv2.merge([h, s, v]) + return cv2.cvtColor(hsv_img, cv2.COLOR_HSV2BGR_FULL).astype(dtype) + + +def affine(img, + angle, + translate, + scale, + shear, + interpolation='nearest', + fill=0, + center=None): + """Affine the image by matrix. + + Args: + img (PIL.Image): Image to be affined. + translate (sequence or int): horizontal and vertical translations + scale (float): overall scale ratio + shear (sequence or float): shear angle value in degrees between -180 to 180, clockwise direction. + If a sequence is specified, the first value corresponds to a shear parallel to the x axis, while + the second value corresponds to a shear parallel to the y axis. + interpolation (int|str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to cv2.INTER_NEAREST. + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (3-tuple or int): RGB pixel fill value for area outside the affined image. + If int, it is used for all channels respectively. + center (sequence, optional): Optional center of rotation. Origin is the upper left corner. + Default is the center of the image. + + Returns: + np.array: Affined image. + + """ + cv2 = try_import('cv2') + _cv2_interp_from_str = { + 'nearest': cv2.INTER_NEAREST, + 'bilinear': cv2.INTER_LINEAR, + 'area': cv2.INTER_AREA, + 'bicubic': cv2.INTER_CUBIC, + 'lanczos': cv2.INTER_LANCZOS4 + } + + h, w = img.shape[0:2] + + if isinstance(fill, int): + fill = tuple([fill] * 3) + + if center is None: + center = (w / 2.0, h / 2.0) + + M = np.ones([2, 3]) + # Rotate and Scale + R = cv2.getRotationMatrix2D(angle=angle, center=center, scale=scale) + + # Shear + sx = math.tan(shear[0] * math.pi / 180) + sy = math.tan(shear[1] * math.pi / 180) + M[0] = R[0] + sy * R[1] + M[1] = R[1] + sx * R[0] + + # Translation + tx, ty = translate + M[0, 2] = tx + M[1, 2] = ty + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.warpAffine(img, + M, + dsize=(w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill)[:, :, np.newaxis] + else: + return cv2.warpAffine(img, + M, + dsize=(w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill) + + +def rotate(img, + angle, + interpolation='nearest', + expand=False, + center=None, + fill=0): + """Rotates the image by angle. + + Args: + img (np.array): Image to be rotated. + angle (float or int): In degrees degrees counter clockwise order. + interpolation (int|str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to cv2.INTER_NEAREST. + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (2-tuple, optional): Optional center of rotation. + Origin is the upper left corner. + Default is the center of the image. + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + np.array: Rotated image. + + """ + cv2 = try_import('cv2') + _cv2_interp_from_str = { + 'nearest': cv2.INTER_NEAREST, + 'bilinear': cv2.INTER_LINEAR, + 'area': cv2.INTER_AREA, + 'bicubic': cv2.INTER_CUBIC, + 'lanczos': cv2.INTER_LANCZOS4 + } + + h, w = img.shape[0:2] + if center is None: + center = (w / 2.0, h / 2.0) + M = cv2.getRotationMatrix2D(center, angle, 1) + + if expand: + + def transform(x, y, matrix): + (a, b, c, d, e, f) = matrix + return a * x + b * y + c, d * x + e * y + f + + # calculate output size + xx = [] + yy = [] + + angle = -math.radians(angle) + expand_matrix = [ + round(math.cos(angle), 15), + round(math.sin(angle), 15), + 0.0, + round(-math.sin(angle), 15), + round(math.cos(angle), 15), + 0.0, + ] + + post_trans = (0, 0) + expand_matrix[2], expand_matrix[5] = transform( + -center[0] - post_trans[0], -center[1] - post_trans[1], + expand_matrix) + expand_matrix[2] += center[0] + expand_matrix[5] += center[1] + + for x, y in ((0, 0), (w, 0), (w, h), (0, h)): + x, y = transform(x, y, expand_matrix) + xx.append(x) + yy.append(y) + nw = math.ceil(max(xx)) - math.floor(min(xx)) + nh = math.ceil(max(yy)) - math.floor(min(yy)) + + M[0, 2] += (nw - w) * 0.5 + M[1, 2] += (nh - h) * 0.5 + + w, h = int(nw), int(nh) + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.warpAffine(img, + M, (w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill)[:, :, np.newaxis] + else: + return cv2.warpAffine(img, + M, (w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill) + + +def perspective(img, startpoints, endpoints, interpolation='nearest', fill=0): + """Perspective the image. + + Args: + img (np.array): Image to be perspectived. + startpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the original image, + endpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the transformed image. + interpolation (int|str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to cv2.INTER_NEAREST. + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + np.array: Perspectived image. + + """ + cv2 = try_import('cv2') + _cv2_interp_from_str = { + 'nearest': cv2.INTER_NEAREST, + 'bilinear': cv2.INTER_LINEAR, + 'area': cv2.INTER_AREA, + 'bicubic': cv2.INTER_CUBIC, + 'lanczos': cv2.INTER_LANCZOS4 + } + h, w = img.shape[0:2] + + startpoints = np.array(startpoints, dtype="float32") + endpoints = np.array(endpoints, dtype="float32") + matrix = cv2.getPerspectiveTransform(startpoints, endpoints) + + if len(img.shape) == 3 and img.shape[2] == 1: + return cv2.warpPerspective(img, + matrix, + dsize=(w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill)[:, :, np.newaxis] + else: + return cv2.warpPerspective(img, + matrix, + dsize=(w, h), + flags=_cv2_interp_from_str[interpolation], + borderValue=fill) + + +def to_grayscale(img, num_output_channels=1): + """Converts image to grayscale version of image. + + Args: + img (np.array): Image to be converted to grayscale. + + Returns: + np.array: Grayscale version of the image. + if num_output_channels = 1 : returned image is single channel + + if num_output_channels = 3 : returned image is 3 channel with r = g = b + + """ + cv2 = try_import('cv2') + + if num_output_channels == 1: + img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis] + elif num_output_channels == 3: + # much faster than doing cvtColor to go back to gray + img = np.broadcast_to( + cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis], img.shape) + else: + raise ValueError('num_output_channels should be either 1 or 3') + + return img + + +def normalize(img, mean, std, data_format='CHW', to_rgb=False): + """Normalizes a ndarray imge or image with mean and standard deviation. + + Args: + img (np.array): input data to be normalized. + mean (list|tuple): Sequence of means for each channel. + std (list|tuple): Sequence of standard deviations for each channel. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + to_rgb (bool, optional): Whether to convert to rgb. Default: False. + + Returns: + np.array: Normalized mage. + + """ + + if data_format == 'CHW': + mean = np.float32(np.array(mean).reshape(-1, 1, 1)) + std = np.float32(np.array(std).reshape(-1, 1, 1)) + else: + mean = np.float32(np.array(mean).reshape(1, 1, -1)) + std = np.float32(np.array(std).reshape(1, 1, -1)) + if to_rgb: + # inplace + img = img[..., ::-1] + + img = (img - mean) / std + return img + + +def erase(img, i, j, h, w, v, inplace=False): + """Erase the pixels of selected area in input image array with given value. + + Args: + img (np.array): input image array, which shape is (H, W, C). + i (int): y coordinate of the top-left point of erased region. + j (int): x coordinate of the top-left point of erased region. + h (int): Height of the erased region. + w (int): Width of the erased region. + v (np.array): value used to replace the pixels in erased region. + inplace (bool, optional): Whether this transform is inplace. Default: False. + + Returns: + np.array: Erased image. + + """ + if not inplace: + img = img.copy() + + img[i:i + h, j:j + w, ...] = v + return img diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_pil.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_pil.py new file mode 100644 index 0000000000000000000000000000000000000000..50ed01f53e2d47f141f48b79e7a6b1d90da72c62 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_pil.py @@ -0,0 +1,558 @@ +# 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. + +from __future__ import division + +import sys +import math +import numbers +import warnings +import collections +from PIL import Image, ImageOps, ImageEnhance + +import numpy as np +from numpy import sin, cos, tan +import paddle + +if sys.version_info < (3, 3): + Sequence = collections.Sequence + Iterable = collections.Iterable +else: + Sequence = collections.abc.Sequence + Iterable = collections.abc.Iterable + +try: + # PIL version >= "9.1.0" + _pil_interp_from_str = { + 'nearest': Image.Resampling.NEAREST, + 'bilinear': Image.Resampling.BILINEAR, + 'bicubic': Image.Resampling.BICUBIC, + 'box': Image.Resampling.BOX, + 'lanczos': Image.Resampling.LANCZOS, + 'hamming': Image.Resampling.HAMMING + } +except: + _pil_interp_from_str = { + 'nearest': Image.NEAREST, + 'bilinear': Image.BILINEAR, + 'bicubic': Image.BICUBIC, + 'box': Image.BOX, + 'lanczos': Image.LANCZOS, + 'hamming': Image.HAMMING + } + +__all__ = [] + + +def to_tensor(pic, data_format='CHW'): + """Converts a ``PIL.Image`` to paddle.Tensor. + + See ``ToTensor`` for more details. + + Args: + pic (PIL.Image): Image to be converted to tensor. + data_format (str, optional): Data format of output tensor, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + Tensor: Converted image. + + """ + + if data_format not in ['CHW', 'HWC']: + raise ValueError( + 'data_format should be CHW or HWC. Got {}'.format(data_format)) + + # PIL Image + if pic.mode == 'I': + img = paddle.to_tensor(np.array(pic, np.int32, copy=False)) + elif pic.mode == 'I;16': + # cast and reshape not support int16 + img = paddle.to_tensor(np.array(pic, np.int32, copy=False)) + elif pic.mode == 'F': + img = paddle.to_tensor(np.array(pic, np.float32, copy=False)) + elif pic.mode == '1': + img = 255 * paddle.to_tensor(np.array(pic, np.uint8, copy=False)) + else: + img = paddle.to_tensor(np.array(pic, copy=False)) + + if pic.mode == 'YCbCr': + nchannel = 3 + elif pic.mode == 'I;16': + nchannel = 1 + else: + nchannel = len(pic.mode) + + dtype = paddle.fluid.data_feeder.convert_dtype(img.dtype) + if dtype == 'uint8': + img = paddle.cast(img, np.float32) / 255. + + img = img.reshape([pic.size[1], pic.size[0], nchannel]) + + if data_format == 'CHW': + img = img.transpose([2, 0, 1]) + + return img + + +def resize(img, size, interpolation='bilinear'): + """ + Resizes the image to given size + + Args: + input (PIL.Image): Image to be resized. + size (int|list|tuple): Target size of input data, with (height, width) shape. + interpolation (int|str, optional): Interpolation method. when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC, + - "box": Image.BOX, + - "lanczos": Image.LANCZOS, + - "hamming": Image.HAMMING + + Returns: + PIL.Image: Resized image. + + """ + + if not (isinstance(size, int) or + (isinstance(size, Iterable) and len(size) == 2)): + raise TypeError('Got inappropriate size arg: {}'.format(size)) + + if isinstance(size, int): + w, h = img.size + if (w <= h and w == size) or (h <= w and h == size): + return img + if w < h: + ow = size + oh = int(size * h / w) + return img.resize((ow, oh), _pil_interp_from_str[interpolation]) + else: + oh = size + ow = int(size * w / h) + return img.resize((ow, oh), _pil_interp_from_str[interpolation]) + else: + return img.resize(size[::-1], _pil_interp_from_str[interpolation]) + + +def pad(img, padding, fill=0, padding_mode='constant'): + """ + Pads the given PIL.Image on all sides with specified padding mode and fill value. + + Args: + img (PIL.Image): Image to be padded. + padding (int|list|tuple): Padding on each border. If a single int is provided this + is used to pad all borders. If list/tuple of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a list/tuple of length 4 is provided + this is the padding for the left, top, right and bottom borders + respectively. + fill (float, optional): Pixel fill value for constant fill. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. Default: 0. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value on the edge of the image + + - reflect: pads with reflection of image (without repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image (repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + PIL.Image: Padded image. + + """ + + if not isinstance(padding, (numbers.Number, list, tuple)): + raise TypeError('Got inappropriate padding arg') + if not isinstance(fill, (numbers.Number, str, list, tuple)): + raise TypeError('Got inappropriate fill arg') + if not isinstance(padding_mode, str): + raise TypeError('Got inappropriate padding_mode arg') + + if isinstance(padding, Sequence) and len(padding) not in [2, 4]: + raise ValueError( + "Padding must be an int or a 2, or 4 element tuple, not a " + + "{} element tuple".format(len(padding))) + + assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \ + 'Padding mode should be either constant, edge, reflect or symmetric' + + if isinstance(padding, list): + padding = tuple(padding) + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + if isinstance(padding, Sequence) and len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + if isinstance(padding, Sequence) and len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + if padding_mode == 'constant': + if img.mode == 'P': + palette = img.getpalette() + image = ImageOps.expand(img, border=padding, fill=fill) + image.putpalette(palette) + return image + + return ImageOps.expand(img, border=padding, fill=fill) + else: + if img.mode == 'P': + palette = img.getpalette() + img = np.asarray(img) + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), + padding_mode) + img = Image.fromarray(img) + img.putpalette(palette) + return img + + img = np.asarray(img) + # RGB image + if len(img.shape) == 3: + img = np.pad(img, + ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), + padding_mode) + # Grayscale image + if len(img.shape) == 2: + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), + padding_mode) + + return Image.fromarray(img) + + +def crop(img, top, left, height, width): + """Crops the given PIL Image. + + Args: + img (PIL.Image): Image to be cropped. (0,0) denotes the top left + corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + + Returns: + PIL.Image: Cropped image. + + """ + return img.crop((left, top, left + width, top + height)) + + +def center_crop(img, output_size): + """Crops the given PIL Image and resize it to desired size. + + Args: + img (PIL.Image): Image to be cropped. (0,0) denotes the top left corner of the image. + output_size (sequence or int): (height, width) of the crop box. If int, + it is used for both directions + backend (str, optional): The image proccess backend type. Options are `pil`, `cv2`. Default: 'pil'. + + Returns: + PIL.Image: Cropped image. + + """ + + if isinstance(output_size, numbers.Number): + output_size = (int(output_size), int(output_size)) + + image_width, image_height = img.size + crop_height, crop_width = output_size + crop_top = int(round((image_height - crop_height) / 2.)) + crop_left = int(round((image_width - crop_width) / 2.)) + return crop(img, crop_top, crop_left, crop_height, crop_width) + + +def hflip(img): + """Horizontally flips the given PIL Image. + + Args: + img (PIL.Image): Image to be flipped. + + Returns: + PIL.Image: Horizontall flipped image. + + """ + + return img.transpose(Image.FLIP_LEFT_RIGHT) + + +def vflip(img): + """Vertically flips the given PIL Image. + + Args: + img (PIL.Image): Image to be flipped. + + Returns: + PIL.Image: Vertically flipped image. + + """ + + return img.transpose(Image.FLIP_TOP_BOTTOM) + + +def adjust_brightness(img, brightness_factor): + """Adjusts brightness of an Image. + + Args: + img (PIL.Image): PIL Image to be adjusted. + brightness_factor (float): How much to adjust the brightness. Can be + any non negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + PIL.Image: Brightness adjusted image. + + """ + + enhancer = ImageEnhance.Brightness(img) + img = enhancer.enhance(brightness_factor) + return img + + +def adjust_contrast(img, contrast_factor): + """Adjusts contrast of an Image. + + Args: + img (PIL.Image): PIL Image to be adjusted. + contrast_factor (float): How much to adjust the contrast. Can be any + non negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + PIL.Image: Contrast adjusted image. + + """ + + enhancer = ImageEnhance.Contrast(img) + img = enhancer.enhance(contrast_factor) + return img + + +def adjust_saturation(img, saturation_factor): + """Adjusts color saturation of an image. + + Args: + img (PIL.Image): PIL Image to be adjusted. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + PIL.Image: Saturation adjusted image. + + """ + + enhancer = ImageEnhance.Color(img) + img = enhancer.enhance(saturation_factor) + return img + + +def adjust_hue(img, hue_factor): + """Adjusts hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + Args: + img (PIL.Image): PIL Image to be adjusted. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + PIL.Image: Hue adjusted image. + + """ + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError( + 'hue_factor:{} is not in [-0.5, 0.5].'.format(hue_factor)) + + input_mode = img.mode + if input_mode in {'L', '1', 'I', 'F'}: + return img + + h, s, v = img.convert('HSV').split() + + np_h = np.array(h, dtype=np.uint8) + # uint8 addition take cares of rotation across boundaries + with np.errstate(over='ignore'): + np_h += np.uint8(hue_factor * 255) + h = Image.fromarray(np_h, 'L') + + img = Image.merge('HSV', (h, s, v)).convert(input_mode) + return img + + +def affine(img, matrix, interpolation="nearest", fill=0): + """Affine the image by matrix. + + Args: + img (PIL.Image): Image to be affined. + matrix (float or int): Affine matrix. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST . when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + fill (3-tuple or int): RGB pixel fill value for area outside the affined image. + If int, it is used for all channels respectively. + + Returns: + PIL.Image: Affined image. + + """ + if isinstance(fill, int): + fill = tuple([fill] * 3) + + return img.transform(img.size, Image.AFFINE, matrix, + _pil_interp_from_str[interpolation], fill) + + +def rotate(img, + angle, + interpolation="nearest", + expand=False, + center=None, + fill=0): + """Rotates the image by angle. + + Args: + img (PIL.Image): Image to be rotated. + angle (float or int): In degrees degrees counter clockwise order. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST . when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (2-tuple, optional): Optional center of rotation. + Origin is the upper left corner. + Default is the center of the image. + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + PIL.Image: Rotated image. + + """ + + if isinstance(fill, int): + fill = tuple([fill] * 3) + + return img.rotate(angle, + _pil_interp_from_str[interpolation], + expand, + center, + fillcolor=fill) + + +def perspective(img, coeffs, interpolation="nearest", fill=0): + """Perspective the image. + + Args: + img (PIL.Image): Image to be perspectived. + coeffs (list[float]): coefficients (a, b, c, d, e, f, g, h) of the perspective transforms. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST . when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + PIL.Image: Perspectived image. + + """ + + if isinstance(fill, int): + fill = tuple([fill] * 3) + + return img.transform(img.size, Image.PERSPECTIVE, coeffs, + _pil_interp_from_str[interpolation], fill) + + +def to_grayscale(img, num_output_channels=1): + """Converts image to grayscale version of image. + + Args: + img (PIL.Image): Image to be converted to grayscale. + backend (str, optional): The image proccess backend type. Options are `pil`, + `cv2`. Default: 'pil'. + + Returns: + PIL.Image: Grayscale version of the image. + if num_output_channels = 1 : returned image is single channel + + if num_output_channels = 3 : returned image is 3 channel with r = g = b + + """ + + if num_output_channels == 1: + img = img.convert('L') + elif num_output_channels == 3: + img = img.convert('L') + np_img = np.array(img, dtype=np.uint8) + np_img = np.dstack([np_img, np_img, np_img]) + img = Image.fromarray(np_img, 'RGB') + else: + raise ValueError('num_output_channels should be either 1 or 3') + + return img + + +def erase(img, i, j, h, w, v, inplace=False): + """Erase the pixels of selected area in input image with given value. PIL format is + not support inplace. + + Args: + img (PIL.Image): input image, which shape is (C, H, W). + i (int): y coordinate of the top-left point of erased region. + j (int): x coordinate of the top-left point of erased region. + h (int): Height of the erased region. + w (int): Width of the erased region. + v (np.array): value used to replace the pixels in erased region. + inplace (bool, optional): Whether this transform is inplace. Default: False. + + Returns: + PIL.Image: Erased image. + + """ + np_img = np.array(img, dtype=np.uint8) + np_img[i:i + h, j:j + w, ...] = v + img = Image.fromarray(np_img, 'RGB') + return img diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_tensor.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf8253ec8b32ed1e6ff3990f533208f463f8189 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/functional_tensor.py @@ -0,0 +1,841 @@ +# 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. + +from __future__ import division + +import math +import numbers + +import paddle +import paddle.nn.functional as F + +import sys +import collections + +__all__ = [] + + +def _assert_image_tensor(img, data_format): + if not isinstance( + img, paddle.Tensor + ) or img.ndim < 3 or img.ndim > 4 or not data_format.lower() in ('chw', + 'hwc'): + raise RuntimeError( + 'not support [type={}, ndim={}, data_format={}] paddle image'. + format(type(img), img.ndim, data_format)) + + +def _get_image_h_axis(data_format): + if data_format.lower() == 'chw': + return -2 + elif data_format.lower() == 'hwc': + return -3 + + +def _get_image_w_axis(data_format): + if data_format.lower() == 'chw': + return -1 + elif data_format.lower() == 'hwc': + return -2 + + +def _get_image_c_axis(data_format): + if data_format.lower() == 'chw': + return -3 + elif data_format.lower() == 'hwc': + return -1 + + +def _get_image_n_axis(data_format): + if len(data_format) == 3: + return None + elif len(data_format) == 4: + return 0 + + +def _is_channel_last(data_format): + return _get_image_c_axis(data_format) == -1 + + +def _is_channel_first(data_format): + return _get_image_c_axis(data_format) == -3 + + +def _get_image_num_batches(img, data_format): + if _get_image_n_axis(data_format): + return img.shape[_get_image_n_axis(data_format)] + return None + + +def _get_image_num_channels(img, data_format): + return img.shape[_get_image_c_axis(data_format)] + + +def _get_image_size(img, data_format): + return img.shape[_get_image_w_axis(data_format)], img.shape[ + _get_image_h_axis(data_format)] + + +def _rgb_to_hsv(img): + """Convert a image Tensor from RGB to HSV. This implementation is based on Pillow ( + https://github.com/python-pillow/Pillow/blob/main/src/libImaging/Convert.c) + """ + maxc = img.max(axis=-3) + minc = img.min(axis=-3) + + is_equal = paddle.equal(maxc, minc) + one_divisor = paddle.ones_like(maxc) + c_delta = maxc - minc + # s is 0 when maxc == minc, set the divisor to 1 to avoid zero divide. + s = c_delta / paddle.where(is_equal, one_divisor, maxc) + + r, g, b = img.unbind(axis=-3) + c_delta_divisor = paddle.where(is_equal, one_divisor, c_delta) + # when maxc == minc, there is r == g == b, set the divisor to 1 to avoid zero divide. + rc = (maxc - r) / c_delta_divisor + gc = (maxc - g) / c_delta_divisor + bc = (maxc - b) / c_delta_divisor + + hr = (maxc == r).astype(maxc.dtype) * (bc - gc) + hg = ((maxc == g) & (maxc != r)).astype(maxc.dtype) * (rc - bc + 2.0) + hb = ((maxc != r) & (maxc != g)).astype(maxc.dtype) * (gc - rc + 4.0) + h = (hr + hg + hb) / 6.0 + 1.0 + h = h - h.trunc() + return paddle.stack([h, s, maxc], axis=-3) + + +def _hsv_to_rgb(img): + """Convert a image Tensor from HSV to RGB. + """ + h, s, v = img.unbind(axis=-3) + f = h * 6.0 + i = paddle.floor(f) + f = f - i + i = i.astype(paddle.int32) % 6 + + p = paddle.clip(v * (1.0 - s), 0.0, 1.0) + q = paddle.clip(v * (1.0 - s * f), 0.0, 1.0) + t = paddle.clip(v * (1.0 - s * (1.0 - f)), 0.0, 1.0) + + mask = paddle.equal(i.unsqueeze(axis=-3), + paddle.arange(6, dtype=i.dtype).reshape( + (-1, 1, 1))).astype(img.dtype) + matrix = paddle.stack([ + paddle.stack([v, q, p, p, t, v], axis=-3), + paddle.stack([t, v, v, q, p, p], axis=-3), + paddle.stack([p, p, t, v, v, q], axis=-3) + ], + axis=-4) + return paddle.einsum("...ijk, ...xijk -> ...xjk", mask, matrix) + + +def _blend_images(img1, img2, ratio): + max_value = 1.0 if paddle.is_floating_point(img1) else 255.0 + return paddle.lerp(img2, img1, + float(ratio)).clip(0, max_value).astype(img1.dtype) + + +def normalize(img, mean, std, data_format='CHW'): + """Normalizes a tensor image given mean and standard deviation. + + Args: + img (paddle.Tensor): input data to be normalized. + mean (list|tuple): Sequence of means for each channel. + std (list|tuple): Sequence of standard deviations for each channel. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + Tensor: Normalized mage. + + """ + _assert_image_tensor(img, data_format) + + mean = paddle.to_tensor(mean, place=img.place) + std = paddle.to_tensor(std, place=img.place) + + if _is_channel_first(data_format): + mean = mean.reshape([-1, 1, 1]) + std = std.reshape([-1, 1, 1]) + + return (img - mean) / std + + +def to_grayscale(img, num_output_channels=1, data_format='CHW'): + """Converts image to grayscale version of image. + + Args: + img (paddel.Tensor): Image to be converted to grayscale. + num_output_channels (int, optionl[1, 3]): + if num_output_channels = 1 : returned image is single channel + if num_output_channels = 3 : returned image is 3 channel + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + paddle.Tensor: Grayscale version of the image. + """ + _assert_image_tensor(img, data_format) + + if num_output_channels not in (1, 3): + raise ValueError('num_output_channels should be either 1 or 3') + + rgb_weights = paddle.to_tensor([0.2989, 0.5870, 0.1140], + place=img.place).astype(img.dtype) + + if _is_channel_first(data_format): + rgb_weights = rgb_weights.reshape((-1, 1, 1)) + + _c_index = _get_image_c_axis(data_format) + + img = (img * rgb_weights).sum(axis=_c_index, keepdim=True) + _shape = img.shape + _shape[_c_index] = num_output_channels + + return img.expand(_shape) + + +def _affine_grid(theta, w, h, ow, oh): + d = 0.5 + base_grid = paddle.ones((1, oh, ow, 3), dtype=theta.dtype) + + x_grid = paddle.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, ow) + base_grid[..., 0] = x_grid + y_grid = paddle.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, oh).unsqueeze_(-1) + base_grid[..., 1] = y_grid + + scaled_theta = theta.transpose( + (0, 2, 1)) / paddle.to_tensor([0.5 * w, 0.5 * h]) + output_grid = base_grid.reshape((1, oh * ow, 3)).bmm(scaled_theta) + + return output_grid.reshape((1, oh, ow, 2)) + + +def _grid_transform(img, grid, mode, fill): + if img.shape[0] > 1: + grid = grid.expand( + shape=[img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3]]) + + if fill is not None: + dummy = paddle.ones((img.shape[0], 1, img.shape[2], img.shape[3]), + dtype=img.dtype) + img = paddle.concat((img, dummy), axis=1) + + img = F.grid_sample(img, + grid, + mode=mode, + padding_mode="zeros", + align_corners=False) + + # Fill with required color + if fill is not None: + mask = img[:, -1:, :, :] # n 1 h w + img = img[:, :-1, :, :] # n c h w + mask = mask.expand_as(img) + len_fill = len(fill) if isinstance(fill, (tuple, list)) else 1 + fill_img = paddle.to_tensor(fill).reshape( + (1, len_fill, 1, 1)).expand_as(img) + + if mode == 'nearest': + mask = paddle.cast(mask < 0.5, img.dtype) + img = img * (1. - mask) + mask * fill_img + else: # 'bilinear' + img = img * mask + (1.0 - mask) * fill_img + + return img + + +def affine(img, matrix, interpolation="nearest", fill=None, data_format='CHW'): + """Affine to the image by matrix. + + Args: + img (paddle.Tensor): Image to be rotated. + matrix (float or int): Affine matrix. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set NEAREST . when use pil backend, + support method are as following: + - "nearest" + - "bilinear" + - "bicubic" + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + paddle.Tensor: Affined image. + + """ + ndim = len(img.shape) + if ndim == 3: + img = img.unsqueeze(0) + + img = img if data_format.lower() == 'chw' else img.transpose((0, 3, 1, 2)) + + matrix = paddle.to_tensor(matrix, place=img.place) + matrix = matrix.reshape((1, 2, 3)) + shape = img.shape + + grid = _affine_grid(matrix, + w=shape[-1], + h=shape[-2], + ow=shape[-1], + oh=shape[-2]) + + if isinstance(fill, int): + fill = tuple([fill] * 3) + + out = _grid_transform(img, grid, mode=interpolation, fill=fill) + + out = out if data_format.lower() == 'chw' else out.transpose((0, 2, 3, 1)) + out = out.squeeze(0) if ndim == 3 else out + + return out + + +def rotate(img, + angle, + interpolation='nearest', + expand=False, + center=None, + fill=None, + data_format='CHW'): + """Rotates the image by angle. + + Args: + img (paddle.Tensor): Image to be rotated. + angle (float or int): In degrees degrees counter clockwise order. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set NEAREST . when use pil backend, + support method are as following: + - "nearest" + - "bilinear" + - "bicubic" + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (2-tuple, optional): Optional center of rotation. + Origin is the upper left corner. + Default is the center of the image. + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + paddle.Tensor: Rotated image. + + """ + + angle = -angle % 360 + img = img.unsqueeze(0) + + # n, c, h, w = img.shape + w, h = _get_image_size(img, data_format=data_format) + + img = img if data_format.lower() == 'chw' else img.transpose((0, 3, 1, 2)) + + post_trans = [0, 0] + + if center is None: + rotn_center = [0, 0] + else: + rotn_center = [(p - s * 0.5) for p, s in zip(center, [w, h])] + + angle = math.radians(angle) + matrix = [ + math.cos(angle), + math.sin(angle), + 0.0, + -math.sin(angle), + math.cos(angle), + 0.0, + ] + + matrix[2] += matrix[0] * (-rotn_center[0] - post_trans[0]) + matrix[1] * ( + -rotn_center[1] - post_trans[1]) + matrix[5] += matrix[3] * (-rotn_center[0] - post_trans[0]) + matrix[4] * ( + -rotn_center[1] - post_trans[1]) + + matrix[2] += rotn_center[0] + matrix[5] += rotn_center[1] + + matrix = paddle.to_tensor(matrix, place=img.place) + matrix = matrix.reshape((1, 2, 3)) + + if expand: + # calculate output size + corners = paddle.to_tensor( + [[-0.5 * w, -0.5 * h, 1.0], [-0.5 * w, 0.5 * h, 1.0], + [0.5 * w, 0.5 * h, 1.0], [0.5 * w, -0.5 * h, 1.0]], + place=matrix.place).astype(matrix.dtype) + + _pos = corners.reshape((1, -1, 3)).bmm(matrix.transpose( + (0, 2, 1))).reshape((1, -1, 2)) + _min = _pos.min(axis=-2).floor() + _max = _pos.max(axis=-2).ceil() + + npos = _max - _min + nw = npos[0][0] + nh = npos[0][1] + + ow, oh = int(nw.numpy()[0]), int(nh.numpy()[0]) + + else: + ow, oh = w, h + + grid = _affine_grid(matrix, w, h, ow, oh) + + out = _grid_transform(img, grid, mode=interpolation, fill=fill) + + out = out if data_format.lower() == 'chw' else out.transpose((0, 2, 3, 1)) + + return out.squeeze(0) + + +def _perspective_grid(img, coeffs, ow, oh, dtype): + theta1 = coeffs[:6].reshape([1, 2, 3]) + tmp = paddle.tile(coeffs[6:].reshape([1, 2]), repeat_times=[2, 1]) + dummy = paddle.ones((2, 1), dtype=dtype) + theta2 = paddle.concat((tmp, dummy), axis=1).unsqueeze(0) + + d = 0.5 + base_grid = paddle.ones((1, oh, ow, 3), dtype=dtype) + + x_grid = paddle.linspace(d, ow * 1.0 + d - 1.0, ow) + base_grid[..., 0] = x_grid + y_grid = paddle.linspace(d, oh * 1.0 + d - 1.0, oh).unsqueeze_(-1) + base_grid[..., 1] = y_grid + + scaled_theta1 = theta1.transpose( + (0, 2, 1)) / paddle.to_tensor([0.5 * ow, 0.5 * oh]) + output_grid1 = base_grid.reshape((1, oh * ow, 3)).bmm(scaled_theta1) + output_grid2 = base_grid.reshape( + (1, oh * ow, 3)).bmm(theta2.transpose((0, 2, 1))) + + output_grid = output_grid1 / output_grid2 - 1.0 + return output_grid.reshape((1, oh, ow, 2)) + + +def perspective(img, + coeffs, + interpolation="nearest", + fill=None, + data_format='CHW'): + """Perspective the image. + + Args: + img (paddle.Tensor): Image to be rotated. + coeffs (list[float]): coefficients (a, b, c, d, e, f, g, h) of the perspective transforms. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set NEAREST. When use pil backend, + support method are as following: + - "nearest" + - "bilinear" + - "bicubic" + fill (3-tuple or int): RGB pixel fill value for area outside the rotated image. + If int, it is used for all channels respectively. + + Returns: + paddle.Tensor: Perspectived image. + + """ + + ndim = len(img.shape) + if ndim == 3: + img = img.unsqueeze(0) + + img = img if data_format.lower() == 'chw' else img.transpose((0, 3, 1, 2)) + ow, oh = img.shape[-1], img.shape[-2] + dtype = img.dtype if paddle.is_floating_point(img) else paddle.float32 + + coeffs = paddle.to_tensor(coeffs, place=img.place) + grid = _perspective_grid(img, coeffs, ow=ow, oh=oh, dtype=dtype) + out = _grid_transform(img, grid, mode=interpolation, fill=fill) + + out = out if data_format.lower() == 'chw' else out.transpose((0, 2, 3, 1)) + out = out.squeeze(0) if ndim == 3 else out + + return out + + +def vflip(img, data_format='CHW'): + """Vertically flips the given paddle tensor. + + Args: + img (paddle.Tensor): Image to be flipped. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + paddle.Tensor: Vertically flipped image. + + """ + _assert_image_tensor(img, data_format) + + h_axis = _get_image_h_axis(data_format) + + return img.flip(axis=[h_axis]) + + +def hflip(img, data_format='CHW'): + """Horizontally flips the given paddle.Tensor Image. + + Args: + img (paddle.Tensor): Image to be flipped. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + + Returns: + paddle.Tensor: Horizontall flipped image. + + """ + _assert_image_tensor(img, data_format) + + w_axis = _get_image_w_axis(data_format) + + return img.flip(axis=[w_axis]) + + +def crop(img, top, left, height, width, data_format='CHW'): + """Crops the given paddle.Tensor Image. + + Args: + img (paddle.Tensor): Image to be cropped. (0,0) denotes the top left + corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + Returns: + paddle.Tensor: Cropped image. + + """ + _assert_image_tensor(img, data_format) + + if _is_channel_first(data_format): + return img[:, top:top + height, left:left + width] + else: + return img[top:top + height, left:left + width, :] + + +def erase(img, i, j, h, w, v, inplace=False): + """Erase the pixels of selected area in input Tensor image with given value. + + Args: + img (paddle.Tensor): input Tensor image. + i (int): y coordinate of the top-left point of erased region. + j (int): x coordinate of the top-left point of erased region. + h (int): Height of the erased region. + w (int): Width of the erased region. + v (paddle.Tensor): value used to replace the pixels in erased region. + inplace (bool, optional): Whether this transform is inplace. Default: False. + + Returns: + paddle.Tensor: Erased image. + + """ + _assert_image_tensor(img, 'CHW') + if not inplace: + img = img.clone() + + img[..., i:i + h, j:j + w] = v + return img + + +def center_crop(img, output_size, data_format='CHW'): + """Crops the given paddle.Tensor Image and resize it to desired size. + + Args: + img (paddle.Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. + output_size (sequence or int): (height, width) of the crop box. If int, + it is used for both directions + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + Returns: + paddle.Tensor: Cropped image. + + """ + _assert_image_tensor(img, data_format) + + if isinstance(output_size, numbers.Number): + output_size = (int(output_size), int(output_size)) + + image_width, image_height = _get_image_size(img, data_format) + crop_height, crop_width = output_size + crop_top = int(round((image_height - crop_height) / 2.)) + crop_left = int(round((image_width - crop_width) / 2.)) + return crop(img, + crop_top, + crop_left, + crop_height, + crop_width, + data_format=data_format) + + +def pad(img, padding, fill=0, padding_mode='constant', data_format='CHW'): + """ + Pads the given paddle.Tensor on all sides with specified padding mode and fill value. + + Args: + img (paddle.Tensor): Image to be padded. + padding (int|list|tuple): Padding on each border. If a single int is provided this + is used to pad all borders. If tuple of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a tuple of length 4 is provided + this is the padding for the left, top, right and bottom borders + respectively. + fill (float, optional): Pixel fill value for constant fill. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. Default: 0. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value on the edge of the image + + - reflect: pads with reflection of image (without repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image (repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + paddle.Tensor: Padded image. + + """ + _assert_image_tensor(img, data_format) + + if not isinstance(padding, (numbers.Number, list, tuple)): + raise TypeError('Got inappropriate padding arg') + if not isinstance(fill, (numbers.Number, str, list, tuple)): + raise TypeError('Got inappropriate fill arg') + if not isinstance(padding_mode, str): + raise TypeError('Got inappropriate padding_mode arg') + + if isinstance(padding, (list, tuple)) and len(padding) not in [2, 4]: + raise ValueError( + "Padding must be an int or a 2, or 4 element tuple, not a " + + "{} element tuple".format(len(padding))) + + assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \ + 'Padding mode should be either constant, edge, reflect or symmetric' + + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + else: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + padding = [pad_left, pad_right, pad_top, pad_bottom] + + if padding_mode == 'edge': + padding_mode = 'replicate' + elif padding_mode == 'symmetric': + raise ValueError('Do not support symmetric mode') + + img = img.unsqueeze(0) + # 'constant', 'reflect', 'replicate', 'circular' + img = F.pad(img, + pad=padding, + mode=padding_mode, + value=float(fill), + data_format='N' + data_format) + + return img.squeeze(0) + + +def resize(img, size, interpolation='bilinear', data_format='CHW'): + """ + Resizes the image to given size + + Args: + input (paddle.Tensor): Image to be resized. + size (int|list|tuple): Target size of input data, with (height, width) shape. + interpolation (int|str, optional): Interpolation method. when use paddle backend, + support method are as following: + - "nearest" + - "bilinear" + - "bicubic" + - "trilinear" + - "area" + - "linear" + data_format (str, optional): paddle.Tensor format + - 'CHW' + - 'HWC' + Returns: + paddle.Tensor: Resized image. + + """ + _assert_image_tensor(img, data_format) + + if not (isinstance(size, int) or + (isinstance(size, (tuple, list)) and len(size) == 2)): + raise TypeError('Got inappropriate size arg: {}'.format(size)) + + if isinstance(size, int): + w, h = _get_image_size(img, data_format) + if (w <= h and w == size) or (h <= w and h == size): + return img + if w < h: + ow = size + oh = int(size * h / w) + else: + oh = size + ow = int(size * w / h) + else: + oh, ow = size + + img = img.unsqueeze(0) + img = F.interpolate(img, + size=(oh, ow), + mode=interpolation.lower(), + data_format='N' + data_format.upper()) + + return img.squeeze(0) + + +def adjust_brightness(img, brightness_factor): + """Adjusts brightness of an Image. + + Args: + img (paddle.Tensor): Image to be adjusted. + brightness_factor (float): How much to adjust the brightness. Can be + any non negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + paddle.Tensor: Brightness adjusted image. + + """ + _assert_image_tensor(img, 'CHW') + assert brightness_factor >= 0, "brightness_factor should be non-negative." + assert _get_image_num_channels( + img, 'CHW') in [1, 3], "channels of input should be either 1 or 3." + + extreme_target = paddle.zeros_like(img, img.dtype) + return _blend_images(img, extreme_target, brightness_factor) + + +def adjust_contrast(img, contrast_factor): + """Adjusts contrast of an image. + + Args: + img (paddle.Tensor): Image to be adjusted. + contrast_factor (float): How much to adjust the contrast. Can be any + non negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + paddle.Tensor: Contrast adjusted image. + + """ + _assert_image_tensor(img, 'chw') + assert contrast_factor >= 0, "contrast_factor should be non-negative." + + channels = _get_image_num_channels(img, 'CHW') + dtype = img.dtype if paddle.is_floating_point(img) else paddle.float32 + if channels == 1: + extreme_target = paddle.mean(img.astype(dtype), + axis=(-3, -2, -1), + keepdim=True) + elif channels == 3: + extreme_target = paddle.mean(to_grayscale(img).astype(dtype), + axis=(-3, -2, -1), + keepdim=True) + else: + raise ValueError("channels of input should be either 1 or 3.") + + return _blend_images(img, extreme_target, contrast_factor) + + +def adjust_saturation(img, saturation_factor): + """Adjusts color saturation of an image. + + Args: + img (paddle.Tensor): Image to be adjusted. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + paddle.Tensor: Saturation adjusted image. + + """ + _assert_image_tensor(img, 'CHW') + assert saturation_factor >= 0, "saturation_factor should be non-negative." + channels = _get_image_num_channels(img, 'CHW') + if channels == 1: + return img + elif channels == 3: + extreme_target = to_grayscale(img) + else: + raise ValueError("channels of input should be either 1 or 3.") + + return _blend_images(img, extreme_target, saturation_factor) + + +def adjust_hue(img, hue_factor): + """Adjusts hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + Args: + img (paddle.Tensor): Image to be adjusted. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + paddle.Tensor: Hue adjusted image. + + """ + _assert_image_tensor(img, 'CHW') + assert hue_factor >= -0.5 and hue_factor <= 0.5, "hue_factor should be in range [-0.5, 0.5]" + channels = _get_image_num_channels(img, 'CHW') + if channels == 1: + return img + elif channels == 3: + dtype = img.dtype + if dtype == paddle.uint8: + img = img.astype(paddle.float32) / 255.0 + + img_hsv = _rgb_to_hsv(img) + h, s, v = img_hsv.unbind(axis=-3) + h = (h + hue_factor) + h = h - h.floor() + img_adjusted = _hsv_to_rgb(paddle.stack([h, s, v], axis=-3)) + + if dtype == paddle.uint8: + img_adjusted = (img_adjusted * 255.0).astype(dtype) + else: + raise ValueError("channels of input should be either 1 or 3.") + + return img_adjusted diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/transforms.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..25cd2600ea0bbcd0327ff1caa43f71cfb5b155e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/paddle/vision/transforms/transforms.py @@ -0,0 +1,1871 @@ +# 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. + +from __future__ import division + +import math +import sys +import random + +import numpy as np +import numbers +import types +import collections +import warnings +import traceback + +import paddle +from paddle.utils import try_import +from . import functional as F + +if sys.version_info < (3, 3): + Sequence = collections.Sequence + Iterable = collections.Iterable +else: + Sequence = collections.abc.Sequence + Iterable = collections.abc.Iterable + +__all__ = [] + + +def _get_image_size(img): + if F._is_pil_image(img): + return img.size + elif F._is_numpy_image(img): + return img.shape[:2][::-1] + elif F._is_tensor_image(img): + if len(img.shape) == 3: + return img.shape[1:][::-1] # chw -> wh + elif len(img.shape) == 4: + return img.shape[2:][::-1] # nchw -> wh + else: + raise ValueError( + "The dim for input Tensor should be 3-D or 4-D, but received {}".format( + len(img.shape) + ) + ) + else: + raise TypeError("Unexpected type {}".format(type(img))) + + +def _check_input( + value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True +): + if isinstance(value, numbers.Number): + if value < 0: + raise ValueError( + "If {} is a single number, it must be non negative.".format( + name + ) + ) + value = [center - value, center + value] + if clip_first_on_zero: + value[0] = max(value[0], 0) + elif isinstance(value, (tuple, list)) and len(value) == 2: + if not bound[0] <= value[0] <= value[1] <= bound[1]: + raise ValueError( + "{} values should be between {}".format(name, bound) + ) + else: + raise TypeError( + "{} should be a single number or a list/tuple with lenght 2.".format( + name + ) + ) + + if value[0] == value[1] == center: + value = None + return value + + +class Compose(object): + """ + Composes several transforms together use for composing list of transforms + together for a dataset transform. + + Args: + transforms (list|tuple): List/Tuple of transforms to compose. + + Returns: + A compose object which is callable, __call__ for this Compose + object will call each given :attr:`transforms` sequencely. + + Examples: + + .. code-block:: python + + from paddle.vision.datasets import Flowers + from paddle.vision.transforms import Compose, ColorJitter, Resize + + transform = Compose([ColorJitter(), Resize(size=608)]) + flowers = Flowers(mode='test', transform=transform) + + for i in range(10): + sample = flowers[i] + print(sample[0].size, sample[1]) + + """ + + def __init__(self, transforms): + self.transforms = transforms + + def __call__(self, data): + for f in self.transforms: + try: + data = f(data) + except Exception as e: + stack_info = traceback.format_exc() + print( + "fail to perform transform [{}] with error: " + "{} and stack:\n{}".format(f, e, str(stack_info)) + ) + raise e + return data + + def __repr__(self): + format_string = self.__class__.__name__ + '(' + for t in self.transforms: + format_string += '\n' + format_string += ' {0}'.format(t) + format_string += '\n)' + return format_string + + +class BaseTransform(object): + """ + Base class of all transforms used in computer vision. + + calling logic: + + if keys is None: + _get_params -> _apply_image() + else: + _get_params -> _apply_*() for * in keys + + If you want to implement a self-defined transform method for image, + rewrite _apply_* method in subclass. + + Args: + keys (list[str]|tuple[str], optional): Input type. Input is a tuple contains different structures, + key is used to specify the type of input. For example, if your input + is image type, then the key can be None or ("image"). if your input + is (image, image) type, then the keys should be ("image", "image"). + if your input is (image, boxes), then the keys should be ("image", "boxes"). + + Current available strings & data type are describe below: + + - "image": input image, with shape of (H, W, C) + - "coords": coordinates, with shape of (N, 2) + - "boxes": bounding boxes, with shape of (N, 4), "xyxy" format, + + the 1st "xy" represents top left point of a box, + the 2nd "xy" represents right bottom point. + + - "mask": map used for segmentation, with shape of (H, W, 1) + + You can also customize your data types only if you implement the corresponding + _apply_*() methods, otherwise ``NotImplementedError`` will be raised. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + import paddle.vision.transforms.functional as F + from paddle.vision.transforms import BaseTransform + + def _get_image_size(img): + if F._is_pil_image(img): + return img.size + elif F._is_numpy_image(img): + return img.shape[:2][::-1] + else: + raise TypeError("Unexpected type {}".format(type(img))) + + class CustomRandomFlip(BaseTransform): + def __init__(self, prob=0.5, keys=None): + super(CustomRandomFlip, self).__init__(keys) + self.prob = prob + + def _get_params(self, inputs): + image = inputs[self.keys.index('image')] + params = {} + params['flip'] = np.random.random() < self.prob + params['size'] = _get_image_size(image) + return params + + def _apply_image(self, image): + if self.params['flip']: + return F.hflip(image) + return image + + # if you only want to transform image, do not need to rewrite this function + def _apply_coords(self, coords): + if self.params['flip']: + w = self.params['size'][0] + coords[:, 0] = w - coords[:, 0] + return coords + + # if you only want to transform image, do not need to rewrite this function + def _apply_boxes(self, boxes): + idxs = np.array([(0, 1), (2, 1), (0, 3), (2, 3)]).flatten() + coords = np.asarray(boxes).reshape(-1, 4)[:, idxs].reshape(-1, 2) + coords = self._apply_coords(coords).reshape((-1, 4, 2)) + minxy = coords.min(axis=1) + maxxy = coords.max(axis=1) + trans_boxes = np.concatenate((minxy, maxxy), axis=1) + return trans_boxes + + # if you only want to transform image, do not need to rewrite this function + def _apply_mask(self, mask): + if self.params['flip']: + return F.hflip(mask) + return mask + + # create fake inputs + fake_img = Image.fromarray((np.random.rand(400, 500, 3) * 255.).astype('uint8')) + fake_boxes = np.array([[2, 3, 200, 300], [50, 60, 80, 100]]) + fake_mask = fake_img.convert('L') + + # only transform for image: + flip_transform = CustomRandomFlip(1.0) + converted_img = flip_transform(fake_img) + + # transform for image, boxes and mask + flip_transform = CustomRandomFlip(1.0, keys=('image', 'boxes', 'mask')) + (converted_img, converted_boxes, converted_mask) = flip_transform((fake_img, fake_boxes, fake_mask)) + print('converted boxes', converted_boxes) + + """ + + def __init__(self, keys=None): + if keys is None: + keys = ("image",) + elif not isinstance(keys, Sequence): + raise ValueError( + "keys should be a sequence, but got keys={}".format(keys) + ) + for k in keys: + if self._get_apply(k) is None: + raise NotImplementedError( + "{} is unsupported data structure".format(k) + ) + self.keys = keys + + # storage some params get from function get_params() + self.params = None + + def _get_params(self, inputs): + pass + + def __call__(self, inputs): + """Apply transform on single input data""" + if not isinstance(inputs, tuple): + inputs = (inputs,) + + self.params = self._get_params(inputs) + + outputs = [] + for i in range(min(len(inputs), len(self.keys))): + apply_func = self._get_apply(self.keys[i]) + if apply_func is None: + outputs.append(inputs[i]) + else: + outputs.append(apply_func(inputs[i])) + if len(inputs) > len(self.keys): + outputs.extend(inputs[len(self.keys) :]) + + if len(outputs) == 1: + outputs = outputs[0] + else: + outputs = tuple(outputs) + return outputs + + def _get_apply(self, key): + return getattr(self, "_apply_{}".format(key), None) + + def _apply_image(self, image): + raise NotImplementedError + + def _apply_boxes(self, boxes): + raise NotImplementedError + + def _apply_mask(self, mask): + raise NotImplementedError + + +class ToTensor(BaseTransform): + """Convert a ``PIL.Image`` or ``numpy.ndarray`` to ``paddle.Tensor``. + + Converts a PIL.Image or numpy.ndarray (H x W x C) to a paddle.Tensor of shape (C x H x W). + + If input is a grayscale image (H x W), it will be converted to an image of shape (H x W x 1). + And the shape of output tensor will be (1 x H x W). + + If you want to keep the shape of output tensor as (H x W x C), you can set data_format = ``HWC`` . + + Converts a PIL.Image or numpy.ndarray in the range [0, 255] to a paddle.Tensor in the + range [0.0, 1.0] if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, + RGBA, CMYK, 1) or if the numpy.ndarray has dtype = np.uint8. + + In the other cases, tensors are returned without scaling. + + Args: + data_format (str, optional): Data format of output tensor, should be 'HWC' or + 'CHW'. Default: 'CHW'. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray): The input image with shape (H x W x C). + - output(np.ndarray): A tensor with shape (C x H x W) or (H x W x C) according option data_format. + + Returns: + A callable object of ToTensor. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + + import paddle.vision.transforms as T + import paddle.vision.transforms.functional as F + + fake_img = Image.fromarray((np.random.rand(4, 5, 3) * 255.).astype(np.uint8)) + + transform = T.ToTensor() + + tensor = transform(fake_img) + + print(tensor.shape) + # [3, 4, 5] + + print(tensor.dtype) + # paddle.float32 + """ + + def __init__(self, data_format='CHW', keys=None): + super(ToTensor, self).__init__(keys) + self.data_format = data_format + + def _apply_image(self, img): + """ + Args: + img (PIL.Image|np.ndarray): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + return F.to_tensor(img, self.data_format) + + +class Resize(BaseTransform): + """Resize the input Image to the given size. + + Args: + size (int|list|tuple): Desired output size. If size is a sequence like + (h, w), output size will be matched to this. If size is an int, + smaller edge of the image will be matched to this number. + i.e, if height > width, then image will be rescaled to + (size * height / width, size) + interpolation (int|str, optional): Interpolation method. Default: 'bilinear'. + when use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC, + - "box": Image.BOX, + - "lanczos": Image.LANCZOS, + - "hamming": Image.HAMMING + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "area": cv2.INTER_AREA, + - "bicubic": cv2.INTER_CUBIC, + - "lanczos": cv2.INTER_LANCZOS4 + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A resized image. + + Returns: + A callable object of Resize. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import Resize + + fake_img = Image.fromarray((np.random.rand(256, 300, 3) * 255.).astype(np.uint8)) + + transform = Resize(size=224) + converted_img = transform(fake_img) + print(converted_img.size) + # (262, 224) + + transform = Resize(size=(200,150)) + converted_img = transform(fake_img) + print(converted_img.size) + # (150, 200) + """ + + def __init__(self, size, interpolation='bilinear', keys=None): + super(Resize, self).__init__(keys) + assert isinstance(size, int) or ( + isinstance(size, Iterable) and len(size) == 2 + ) + self.size = size + self.interpolation = interpolation + + def _apply_image(self, img): + return F.resize(img, self.size, self.interpolation) + + +class RandomResizedCrop(BaseTransform): + """Crop the input data to random size and aspect ratio. + A crop of random size (default: of 0.08 to 1.0) of the original size and a random + aspect ratio (default: of 3/4 to 1.33) of the original aspect ratio is made. + After applying crop transfrom, the input data will be resized to given size. + + Args: + size (int|list|tuple): Target size of output image, with (height, width) shape. + scale (list|tuple): Scale range of the cropped image before resizing, relatively to the origin + image. Default: (0.08, 1.0) + ratio (list|tuple): Range of aspect ratio of the origin aspect ratio cropped. Default: (0.75, 1.33) + interpolation (int|str, optional): Interpolation method. Default: 'bilinear'. when use pil backend, + support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC, + - "box": Image.BOX, + - "lanczos": Image.LANCZOS, + - "hamming": Image.HAMMING + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "area": cv2.INTER_AREA, + - "bicubic": cv2.INTER_CUBIC, + - "lanczos": cv2.INTER_LANCZOS4 + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image. + + Returns: + A callable object of RandomResizedCrop. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import RandomResizedCrop + + transform = RandomResizedCrop(224) + + fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + + """ + + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4, 4.0 / 3), + interpolation='bilinear', + keys=None, + ): + super(RandomResizedCrop, self).__init__(keys) + if isinstance(size, int): + self.size = (size, size) + else: + self.size = size + assert scale[0] <= scale[1], "scale should be of kind (min, max)" + assert ratio[0] <= ratio[1], "ratio should be of kind (min, max)" + self.scale = scale + self.ratio = ratio + self.interpolation = interpolation + + def _get_param(self, image, attempts=10): + width, height = _get_image_size(image) + area = height * width + + for _ in range(attempts): + target_area = np.random.uniform(*self.scale) * area + log_ratio = tuple(math.log(x) for x in self.ratio) + aspect_ratio = math.exp(np.random.uniform(*log_ratio)) + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if 0 < w <= width and 0 < h <= height: + i = random.randint(0, height - h) + j = random.randint(0, width - w) + return i, j, h, w + + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(self.ratio): + w = width + h = int(round(w / min(self.ratio))) + elif in_ratio > max(self.ratio): + h = height + w = int(round(h * max(self.ratio))) + else: + # return whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + return i, j, h, w + + def _apply_image(self, img): + i, j, h, w = self._get_param(img) + + cropped_img = F.crop(img, i, j, h, w) + return F.resize(cropped_img, self.size, self.interpolation) + + +class CenterCrop(BaseTransform): + """Crops the given the input data at the center. + + Args: + size (int|list|tuple): Target size of output image, with (height, width) shape. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image. + + Returns: + A callable object of CenterCrop. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import CenterCrop + + transform = CenterCrop(224) + + fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + """ + + def __init__(self, size, keys=None): + super(CenterCrop, self).__init__(keys) + if isinstance(size, numbers.Number): + self.size = (int(size), int(size)) + else: + self.size = size + + def _apply_image(self, img): + return F.center_crop(img, self.size) + + +class RandomHorizontalFlip(BaseTransform): + """Horizontally flip the input data randomly with a given probability. + + Args: + prob (float, optional): Probability of the input data being flipped. Should be in [0, 1]. Default: 0.5 + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A horiziotal flipped image. + + Returns: + A callable object of RandomHorizontalFlip. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import RandomHorizontalFlip + + transform = RandomHorizontalFlip(0.5) + + fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + """ + + def __init__(self, prob=0.5, keys=None): + super(RandomHorizontalFlip, self).__init__(keys) + assert 0 <= prob <= 1, "probability must be between 0 and 1" + self.prob = prob + + def _apply_image(self, img): + if random.random() < self.prob: + return F.hflip(img) + return img + + +class RandomVerticalFlip(BaseTransform): + """Vertically flip the input data randomly with a given probability. + + Args: + prob (float, optional): Probability of the input data being flipped. Default: 0.5 + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A vertical flipped image. + + Returns: + A callable object of RandomVerticalFlip. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import RandomVerticalFlip + + transform = RandomVerticalFlip() + + fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + + """ + + def __init__(self, prob=0.5, keys=None): + super(RandomVerticalFlip, self).__init__(keys) + assert 0 <= prob <= 1, "probability must be between 0 and 1" + self.prob = prob + + def _apply_image(self, img): + if random.random() < self.prob: + return F.vflip(img) + return img + + +class Normalize(BaseTransform): + """Normalize the input data with mean and standard deviation. + Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, + this transform will normalize each channel of the input data. + ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` + + Args: + mean (int|float|list|tuple, optional): Sequence of means for each channel. + std (int|float|list|tuple, optional): Sequence of standard deviations for each channel. + data_format (str, optional): Data format of img, should be 'HWC' or + 'CHW'. Default: 'CHW'. + to_rgb (bool, optional): Whether to convert to rgb. Default: False. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A normalized array or tensor. + + Returns: + A callable object of Normalize. + + Examples: + + .. code-block:: python + :name: code-example + import paddle + from paddle.vision.transforms import Normalize + + normalize = Normalize(mean=[127.5, 127.5, 127.5], + std=[127.5, 127.5, 127.5], + data_format='HWC') + + fake_img = paddle.rand([300,320,3]).numpy() * 255. + + fake_img = normalize(fake_img) + print(fake_img.shape) + # (300, 320, 3) + print(fake_img.max(), fake_img.min()) + # 0.99999905 -0.999974 + + """ + + def __init__( + self, mean=0.0, std=1.0, data_format='CHW', to_rgb=False, keys=None + ): + super(Normalize, self).__init__(keys) + if isinstance(mean, numbers.Number): + mean = [mean, mean, mean] + + if isinstance(std, numbers.Number): + std = [std, std, std] + + self.mean = mean + self.std = std + self.data_format = data_format + self.to_rgb = to_rgb + + def _apply_image(self, img): + return F.normalize( + img, self.mean, self.std, self.data_format, self.to_rgb + ) + + +class Transpose(BaseTransform): + """Transpose input data to a target format. + For example, most transforms use HWC mode image, + while the Neural Network might use CHW mode input tensor. + output image will be an instance of numpy.ndarray. + + Args: + order (list|tuple, optional): Target order of input data. Default: (2, 0, 1). + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(np.ndarray|Paddle.Tensor): A transposed array or tensor. If input + is a PIL.Image, output will be converted to np.ndarray automatically. + + Returns: + A callable object of Transpose. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import Transpose + + transform = Transpose() + + fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.shape) + + """ + + def __init__(self, order=(2, 0, 1), keys=None): + super(Transpose, self).__init__(keys) + self.order = order + + def _apply_image(self, img): + if F._is_tensor_image(img): + return img.transpose(self.order) + + if F._is_pil_image(img): + img = np.asarray(img) + + if len(img.shape) == 2: + img = img[..., np.newaxis] + return img.transpose(self.order) + + +class BrightnessTransform(BaseTransform): + """Adjust brightness of the image. + + Args: + value (float): How much to adjust the brightness. Can be any + non negative number. 0 gives the original image + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in brghtness. + + Returns: + A callable object of BrightnessTransform. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import BrightnessTransform + + transform = BrightnessTransform(0.4) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + + """ + + def __init__(self, value, keys=None): + super(BrightnessTransform, self).__init__(keys) + self.value = _check_input(value, 'brightness') + + def _apply_image(self, img): + if self.value is None: + return img + + brightness_factor = random.uniform(self.value[0], self.value[1]) + return F.adjust_brightness(img, brightness_factor) + + +class ContrastTransform(BaseTransform): + """Adjust contrast of the image. + + Args: + value (float): How much to adjust the contrast. Can be any + non negative number. 0 gives the original image + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in contrast. + + Returns: + A callable object of ContrastTransform. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import ContrastTransform + + transform = ContrastTransform(0.4) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + + """ + + def __init__(self, value, keys=None): + super(ContrastTransform, self).__init__(keys) + if value < 0: + raise ValueError("contrast value should be non-negative") + self.value = _check_input(value, 'contrast') + + def _apply_image(self, img): + if self.value is None: + return img + + contrast_factor = random.uniform(self.value[0], self.value[1]) + return F.adjust_contrast(img, contrast_factor) + + +class SaturationTransform(BaseTransform): + """Adjust saturation of the image. + + Args: + value (float): How much to adjust the saturation. Can be any + non negative number. 0 gives the original image + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in saturation. + + Returns: + A callable object of SaturationTransform. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import SaturationTransform + + transform = SaturationTransform(0.4) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + + """ + + def __init__(self, value, keys=None): + super(SaturationTransform, self).__init__(keys) + self.value = _check_input(value, 'saturation') + + def _apply_image(self, img): + if self.value is None: + return img + + saturation_factor = random.uniform(self.value[0], self.value[1]) + return F.adjust_saturation(img, saturation_factor) + + +class HueTransform(BaseTransform): + """Adjust hue of the image. + + Args: + value (float): How much to adjust the hue. Can be any number + between 0 and 0.5, 0 gives the original image + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in hue. + + Returns: + A callable object of HueTransform. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import HueTransform + + transform = HueTransform(0.4) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + + """ + + def __init__(self, value, keys=None): + super(HueTransform, self).__init__(keys) + self.value = _check_input( + value, 'hue', center=0, bound=(-0.5, 0.5), clip_first_on_zero=False + ) + + def _apply_image(self, img): + if self.value is None: + return img + + hue_factor = random.uniform(self.value[0], self.value[1]) + return F.adjust_hue(img, hue_factor) + + +class ColorJitter(BaseTransform): + """Randomly change the brightness, contrast, saturation and hue of an image. + + Args: + brightness (float): How much to jitter brightness. + Chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. Should be non negative numbers. + contrast (float): How much to jitter contrast. + Chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. Should be non negative numbers. + saturation (float): How much to jitter saturation. + Chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. Should be non negative numbers. + hue (float): How much to jitter hue. + Chosen uniformly from [-hue, hue]. Should have 0<= hue <= 0.5. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A color jittered image. + + Returns: + A callable object of ColorJitter. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import ColorJitter + + transform = ColorJitter(0.4, 0.4, 0.4, 0.4) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + + """ + + def __init__( + self, brightness=0, contrast=0, saturation=0, hue=0, keys=None + ): + super(ColorJitter, self).__init__(keys) + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.hue = hue + + def _get_param(self, brightness, contrast, saturation, hue): + """Get a randomized transform to be applied on image. + + Arguments are same as that of __init__. + + Returns: + Transform which randomly adjusts brightness, contrast and + saturation in a random order. + """ + transforms = [] + + if brightness is not None: + transforms.append(BrightnessTransform(brightness, self.keys)) + + if contrast is not None: + transforms.append(ContrastTransform(contrast, self.keys)) + + if saturation is not None: + transforms.append(SaturationTransform(saturation, self.keys)) + + if hue is not None: + transforms.append(HueTransform(hue, self.keys)) + + random.shuffle(transforms) + transform = Compose(transforms) + + return transform + + def _apply_image(self, img): + """ + Args: + img (PIL Image): Input image. + + Returns: + PIL Image: Color jittered image. + """ + transform = self._get_param( + self.brightness, self.contrast, self.saturation, self.hue + ) + return transform(img) + + +class RandomCrop(BaseTransform): + """Crops the given CV Image at a random location. + + Args: + size (sequence|int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. + padding (int|sequence, optional): Optional padding on each border + of the image. If a sequence of length 4 is provided, it is used to pad left, + top, right, bottom borders respectively. Default: None, without padding. + pad_if_needed (boolean, optional): It will pad the image if smaller than the + desired size to avoid raising an exception. Default: False. + fill (float|tuple, optional): Pixel fill value for constant fill. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. Default: 0. + padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value on the edge of the image + + - reflect: pads with reflection of image (without repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image (repeating the last value on the edge) + + padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A random cropped image. + + Returns: + A callable object of RandomCrop. + + Examples: + + .. code-block:: python + :name: code-example1 + + import paddle + from paddle.vision.transforms import RandomCrop + transform = RandomCrop(224) + + fake_img = paddle.randint(0, 255, shape=(3, 324,300), dtype = 'int32') + print(fake_img.shape) # [3, 324, 300] + + crop_img = transform(fake_img) + print(crop_img.shape) # [3, 224, 224] + """ + + def __init__( + self, + size, + padding=None, + pad_if_needed=False, + fill=0, + padding_mode='constant', + keys=None, + ): + super(RandomCrop, self).__init__(keys) + if isinstance(size, numbers.Number): + self.size = (int(size), int(size)) + else: + self.size = size + self.padding = padding + self.pad_if_needed = pad_if_needed + self.fill = fill + self.padding_mode = padding_mode + + def _get_param(self, img, output_size): + """Get parameters for ``crop`` for a random crop. + + Args: + img (PIL Image): Image to be cropped. + output_size (tuple): Expected output size of the crop. + + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. + """ + w, h = _get_image_size(img) + th, tw = output_size + if w == tw and h == th: + return 0, 0, h, w + + i = random.randint(0, h - th) + j = random.randint(0, w - tw) + return i, j, th, tw + + def _apply_image(self, img): + """ + Args: + img (PIL Image): Image to be cropped. + + Returns: + PIL Image: Cropped image. + """ + if self.padding is not None: + img = F.pad(img, self.padding, self.fill, self.padding_mode) + + w, h = _get_image_size(img) + + # pad the width if needed + if self.pad_if_needed and w < self.size[1]: + img = F.pad( + img, (self.size[1] - w, 0), self.fill, self.padding_mode + ) + # pad the height if needed + if self.pad_if_needed and h < self.size[0]: + img = F.pad( + img, (0, self.size[0] - h), self.fill, self.padding_mode + ) + + i, j, h, w = self._get_param(img, self.size) + + return F.crop(img, i, j, h, w) + + +class Pad(BaseTransform): + """Pads the given CV Image on all sides with the given "pad" value. + + Args: + padding (int|list|tuple): Padding on each border. If a single int is provided this + is used to pad all borders. If list/tuple of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a list/tuple of length 4 is provided + this is the padding for the left, top, right and bottom borders + respectively. + fill (int|list|tuple): Pixel fill value for constant fill. Default is 0. If a list/tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. + ``constant`` means pads with a constant value, this value is specified with fill. + ``edge`` means pads with the last value at the edge of the image. + ``reflect`` means pads with reflection of image (without repeating the last value on the edge) + padding ``[1, 2, 3, 4]`` with 2 elements on both sides in reflect mode + will result in ``[3, 2, 1, 2, 3, 4, 3, 2]``. + ``symmetric`` menas pads with reflection of image (repeating the last value on the edge) + padding ``[1, 2, 3, 4]`` with 2 elements on both sides in symmetric mode + will result in ``[2, 1, 1, 2, 3, 4, 4, 3]``. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A paded image. + + Returns: + A callable object of Pad. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import Pad + + transform = Pad(2) + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + """ + + def __init__(self, padding, fill=0, padding_mode='constant', keys=None): + assert isinstance(padding, (numbers.Number, list, tuple)) + assert isinstance(fill, (numbers.Number, str, list, tuple)) + assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'] + + if isinstance(padding, list): + padding = tuple(padding) + if isinstance(fill, list): + fill = tuple(fill) + + if isinstance(padding, Sequence) and len(padding) not in [2, 4]: + raise ValueError( + "Padding must be an int or a 2, or 4 element tuple, not a " + + "{} element tuple".format(len(padding)) + ) + + super(Pad, self).__init__(keys) + self.padding = padding + self.fill = fill + self.padding_mode = padding_mode + + def _apply_image(self, img): + """ + Args: + img (PIL Image): Image to be padded. + + Returns: + PIL Image: Padded image. + """ + return F.pad(img, self.padding, self.fill, self.padding_mode) + + +def _check_sequence_input(x, name, req_sizes): + msg = ( + req_sizes[0] + if len(req_sizes) < 2 + else " or ".join([str(s) for s in req_sizes]) + ) + if not isinstance(x, Sequence): + raise TypeError(f"{name} should be a sequence of length {msg}.") + if len(x) not in req_sizes: + raise ValueError(f"{name} should be sequence of length {msg}.") + + +def _setup_angle(x, name, req_sizes=(2,)): + if isinstance(x, numbers.Number): + if x < 0: + raise ValueError( + f"If {name} is a single number, it must be positive." + ) + x = [-x, x] + else: + _check_sequence_input(x, name, req_sizes) + + return [float(d) for d in x] + + +class RandomAffine(BaseTransform): + """Random affine transformation of the image. + + Args: + degrees (int|float|tuple): The angle interval of the random rotation. + If set as a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees) in clockwise order. If set 0, will not rotate. + translate (tuple, optional): Maximum absolute fraction for horizontal and vertical translations. + For example translate=(a, b), then horizontal shift is randomly sampled in the range -img_width * a < dx < img_width * a + and vertical shift is randomly sampled in the range -img_height * b < dy < img_height * b. + Default is None, will not translate. + scale (tuple, optional): Scaling factor interval, e.g (a, b), then scale is randomly sampled from the range a <= scale <= b. + Default is None, will keep original scale and not scale. + shear (sequence or number, optional): Range of degrees to shear, ranges from -180 to 180 in clockwise order. + If set as a number, a shear parallel to the x axis in the range (-shear, +shear) will be applied. + Else if set as a sequence of 2 values a shear parallel to the x axis in the range (shear[0], shear[1]) will be applied. + Else if set as a sequence of 4 values, a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied. + Default is None, will not apply shear. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST + according the backend. + When use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + When use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + center (2-tuple, optional): Optional center of rotation, (x, y). + Origin is the upper left corner. + Default is the center of the image. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): An affined image. + + Returns: + A callable object of RandomAffine. + + Examples: + + .. code-block:: python + + import paddle + from paddle.vision.transforms import RandomAffine + + transform = RandomAffine([-90, 90], translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[-10, 10]) + + fake_img = paddle.randn((3, 256, 300)).astype(paddle.float32) + + fake_img = transform(fake_img) + print(fake_img.shape) + """ + + def __init__( + self, + degrees, + translate=None, + scale=None, + shear=None, + interpolation='nearest', + fill=0, + center=None, + keys=None, + ): + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + + super(RandomAffine, self).__init__(keys) + assert interpolation in ['nearest', 'bilinear', 'bicubic'] + self.interpolation = interpolation + + if translate is not None: + _check_sequence_input(translate, "translate", req_sizes=(2,)) + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError( + "translation values should be between 0 and 1" + ) + self.translate = translate + + if scale is not None: + _check_sequence_input(scale, "scale", req_sizes=(2,)) + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4)) + else: + self.shear = shear + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + self.fill = fill + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + self.center = center + + def _get_param( + self, img_size, degrees, translate=None, scale_ranges=None, shears=None + ): + """Get parameters for affine transformation + + Returns: + params to be passed to the affine transformation + """ + angle = random.uniform(degrees[0], degrees[1]) + + if translate is not None: + max_dx = float(translate[0] * img_size[0]) + max_dy = float(translate[1] * img_size[1]) + tx = int(random.uniform(-max_dx, max_dx)) + ty = int(random.uniform(-max_dy, max_dy)) + translations = (tx, ty) + else: + translations = (0, 0) + + if scale_ranges is not None: + scale = random.uniform(scale_ranges[0], scale_ranges[1]) + else: + scale = 1.0 + + shear_x, shear_y = 0.0, 0.0 + if shears is not None: + shear_x = random.uniform(shears[0], shears[1]) + if len(shears) == 4: + shear_y = random.uniform(shears[2], shears[3]) + shear = (shear_x, shear_y) + + return angle, translations, scale, shear + + def _apply_image(self, img): + """ + Args: + img (PIL.Image|np.array): Image to be affine transformed. + + Returns: + PIL.Image or np.array: Affine transformed image. + """ + + w, h = _get_image_size(img) + img_size = [w, h] + + ret = self._get_param( + img_size, self.degrees, self.translate, self.scale, self.shear + ) + + return F.affine( + img, + *ret, + interpolation=self.interpolation, + fill=self.fill, + center=self.center, + ) + + +class RandomRotation(BaseTransform): + """Rotates the image by angle. + + Args: + degrees (sequence or float or int): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees) clockwise order. + interpolation (str, optional): Interpolation method. If omitted, or if the + image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST + according the backend. when use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + when use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + expand (bool|optional): Optional expansion flag. Default: False. + If true, expands the output to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (2-tuple|optional): Optional center of rotation. + Origin is the upper left corner. + Default is the center of the image. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A rotated image. + + Returns: + A callable object of RandomRotation. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import RandomRotation + + transform = RandomRotation(90) + + fake_img = Image.fromarray((np.random.rand(200, 150, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(fake_img.size) + """ + + def __init__( + self, + degrees, + interpolation='nearest', + expand=False, + center=None, + fill=0, + keys=None, + ): + if isinstance(degrees, numbers.Number): + if degrees < 0: + raise ValueError( + "If degrees is a single number, it must be positive." + ) + self.degrees = (-degrees, degrees) + else: + if len(degrees) != 2: + raise ValueError( + "If degrees is a sequence, it must be of len 2." + ) + self.degrees = degrees + + super(RandomRotation, self).__init__(keys) + self.interpolation = interpolation + self.expand = expand + self.center = center + self.fill = fill + + def _get_param(self, degrees): + angle = random.uniform(degrees[0], degrees[1]) + + return angle + + def _apply_image(self, img): + """ + Args: + img (PIL.Image|np.array): Image to be rotated. + + Returns: + PIL.Image or np.array: Rotated image. + """ + + angle = self._get_param(self.degrees) + + return F.rotate( + img, angle, self.interpolation, self.expand, self.center, self.fill + ) + + +class RandomPerspective(BaseTransform): + """Random perspective transformation with a given probability. + + Args: + prob (float, optional): Probability of using transformation, ranges from + 0 to 1, default is 0.5. + distortion_scale (float, optional): Degree of distortion, ranges from + 0 to 1, default is 0.5. + interpolation (str, optional): Interpolation method. If omitted, or if + the image has only one channel, it is set to PIL.Image.NEAREST or + cv2.INTER_NEAREST. + When use pil backend, support method are as following: + - "nearest": Image.NEAREST, + - "bilinear": Image.BILINEAR, + - "bicubic": Image.BICUBIC + When use cv2 backend, support method are as following: + - "nearest": cv2.INTER_NEAREST, + - "bilinear": cv2.INTER_LINEAR, + - "bicubic": cv2.INTER_CUBIC + fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): A perspectived image. + + Returns: + A callable object of RandomPerspective. + + Examples: + + .. code-block:: python + + import paddle + from paddle.vision.transforms import RandomPerspective + + transform = RandomPerspective(prob=1.0, distortion_scale=0.9) + + fake_img = paddle.randn((3, 200, 150)).astype(paddle.float32) + + fake_img = transform(fake_img) + print(fake_img.shape) + """ + + def __init__( + self, + prob=0.5, + distortion_scale=0.5, + interpolation='nearest', + fill=0, + keys=None, + ): + super(RandomPerspective, self).__init__(keys) + assert 0 <= prob <= 1, "probability must be between 0 and 1" + assert ( + 0 <= distortion_scale <= 1 + ), "distortion_scale must be between 0 and 1" + assert interpolation in ['nearest', 'bilinear', 'bicubic'] + assert isinstance(fill, (numbers.Number, str, list, tuple)) + + self.prob = prob + self.distortion_scale = distortion_scale + self.interpolation = interpolation + self.fill = fill + + def get_params(self, width, height, distortion_scale): + """ + Returns: + startpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the original image, + endpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the transformed image. + """ + half_height = height // 2 + half_width = width // 2 + topleft = [ + int(random.uniform(0, int(distortion_scale * half_width) + 1)), + int(random.uniform(0, int(distortion_scale * half_height) + 1)), + ] + topright = [ + int( + random.uniform( + width - int(distortion_scale * half_width) - 1, width + ) + ), + int(random.uniform(0, int(distortion_scale * half_height) + 1)), + ] + botright = [ + int( + random.uniform( + width - int(distortion_scale * half_width) - 1, width + ) + ), + int( + random.uniform( + height - int(distortion_scale * half_height) - 1, height + ) + ), + ] + botleft = [ + int(random.uniform(0, int(distortion_scale * half_width) + 1)), + int( + random.uniform( + height - int(distortion_scale * half_height) - 1, height + ) + ), + ] + startpoints = [ + [0, 0], + [width - 1, 0], + [width - 1, height - 1], + [0, height - 1], + ] + endpoints = [topleft, topright, botright, botleft] + + return startpoints, endpoints + + def _apply_image(self, img): + """ + Args: + img (PIL.Image|np.array|paddle.Tensor): Image to be Perspectively transformed. + + Returns: + PIL.Image|np.array|paddle.Tensor: Perspectively transformed image. + """ + + width, height = _get_image_size(img) + + if random.random() < self.prob: + startpoints, endpoints = self.get_params( + width, height, self.distortion_scale + ) + return F.perspective( + img, startpoints, endpoints, self.interpolation, self.fill + ) + return img + + +class Grayscale(BaseTransform): + """Converts image to grayscale. + + Args: + num_output_channels (int): (1 or 3) number of channels desired for output image + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C). + - output(PIL.Image|np.ndarray|Paddle.Tensor): Grayscale version of the input image. + - If output_channels == 1 : returned image is single channel + - If output_channels == 3 : returned image is 3 channel with r == g == b + + Returns: + A callable object of Grayscale. + + Examples: + + .. code-block:: python + + import numpy as np + from PIL import Image + from paddle.vision.transforms import Grayscale + + transform = Grayscale() + + fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8)) + + fake_img = transform(fake_img) + print(np.array(fake_img).shape) + """ + + def __init__(self, num_output_channels=1, keys=None): + super(Grayscale, self).__init__(keys) + self.num_output_channels = num_output_channels + + def _apply_image(self, img): + """ + Args: + img (PIL Image): Image to be converted to grayscale. + + Returns: + PIL Image: Randomly grayscaled image. + """ + return F.to_grayscale(img, self.num_output_channels) + + +class RandomErasing(BaseTransform): + """Erase the pixels in a rectangle region selected randomly. + + Args: + prob (float, optional): Probability of the input data being erased. Default: 0.5. + scale (sequence, optional): The proportional range of the erased area to the input image. + Default: (0.02, 0.33). + ratio (sequence, optional): Aspect ratio range of the erased area. Default: (0.3, 3.3). + value (int|float|sequence|str, optional): The value each pixel in erased area will be replaced with. + If value is a single number, all pixels will be erased with this value. + If value is a sequence with length 3, the R, G, B channels will be ereased + respectively. If value is set to "random", each pixel will be erased with + random values. Default: 0. + inplace (bool, optional): Whether this transform is inplace. Default: False. + keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None. + + Shape: + - img(paddle.Tensor | np.array | PIL.Image): The input image. For Tensor input, the shape should be (C, H, W). + For np.array input, the shape should be (H, W, C). + - output(paddle.Tensor | np.array | PIL.Image): A random erased image. + + Returns: + A callable object of RandomErasing. + + Examples: + + .. code-block:: python + + import paddle + + fake_img = paddle.randn((3, 10, 10)).astype(paddle.float32) + transform = paddle.vision.transforms.RandomErasing() + result = transform(fake_img) + + print(result) + """ + + def __init__( + self, + prob=0.5, + scale=(0.02, 0.33), + ratio=(0.3, 3.3), + value=0, + inplace=False, + keys=None, + ): + super(RandomErasing, self).__init__(keys) + assert isinstance( + scale, (tuple, list) + ), "scale should be a tuple or list" + assert ( + scale[0] >= 0 and scale[1] <= 1 and scale[0] <= scale[1] + ), "scale should be of kind (min, max) and in range [0, 1]" + assert isinstance( + ratio, (tuple, list) + ), "ratio should be a tuple or list" + assert ( + ratio[0] >= 0 and ratio[0] <= ratio[1] + ), "ratio should be of kind (min, max)" + assert ( + prob >= 0 and prob <= 1 + ), "The probability should be in range [0, 1]" + assert isinstance( + value, (numbers.Number, str, tuple, list) + ), "value should be a number, tuple, list or str" + if isinstance(value, str) and value != "random": + raise ValueError("value must be 'random' when type is str") + + self.prob = prob + self.scale = scale + self.ratio = ratio + self.value = value + self.inplace = inplace + + def _get_param(self, img, scale, ratio, value): + """Get parameters for ``erase`` for a random erasing. + + Args: + img (paddle.Tensor | np.array | PIL.Image): Image to be erased. + scale (sequence, optional): The proportional range of the erased area to the input image. + ratio (sequence, optional): Aspect ratio range of the erased area. + value (sequence | None): The value each pixel in erased area will be replaced with. + If value is a sequence with length 3, the R, G, B channels will be ereased + respectively. If value is None, each pixel will be erased with random values. + + Returns: + tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erase. + """ + if F._is_pil_image(img): + shape = np.asarray(img).astype(np.uint8).shape + h, w, c = shape[-3], shape[-2], shape[-1] + elif F._is_numpy_image(img): + h, w, c = img.shape[-3], img.shape[-2], img.shape[-1] + elif F._is_tensor_image(img): + c, h, w = img.shape[-3], img.shape[-2], img.shape[-1] + + img_area = h * w + log_ratio = np.log(ratio) + for _ in range(10): + erase_area = np.random.uniform(*scale) * img_area + aspect_ratio = np.exp(np.random.uniform(*log_ratio)) + erase_h = int(round(np.sqrt(erase_area * aspect_ratio))) + erase_w = int(round(np.sqrt(erase_area / aspect_ratio))) + if erase_h >= h or erase_w >= w: + continue + if F._is_tensor_image(img): + if value is None: + v = paddle.normal(shape=[c, erase_h, erase_w]).astype( + img.dtype + ) + else: + v = paddle.to_tensor(value, dtype=img.dtype)[:, None, None] + else: + if value is None: + v = np.random.normal(size=[erase_h, erase_w, c]) * 255 + else: + v = np.array(value)[None, None, :] + top = np.random.randint(0, h - erase_h + 1) + left = np.random.randint(0, w - erase_w + 1) + + return top, left, erase_h, erase_w, v + + return 0, 0, h, w, img + + def _apply_image(self, img): + """ + Args: + img (paddle.Tensor | np.array | PIL.Image): Image to be Erased. + + Returns: + output (paddle.Tensor np.array | PIL.Image): A random erased image. + """ + + if random.random() < self.prob: + if isinstance(self.value, numbers.Number): + value = [self.value] + elif isinstance(self.value, str): + value = None + else: + value = self.value + if value is not None and not (len(value) == 1 or len(value) == 3): + raise ValueError( + "Value should be a single number or a sequence with length equals to image's channel." + ) + top, left, erase_h, erase_w, v = self._get_param( + img, self.scale, self.ratio, value + ) + return F.erase(img, top, left, erase_h, erase_w, v, self.inplace) + return img diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..d0c32e26092f6ea25771279418582a24ea449ab2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b602a346dbe4b0d45af287f25f05ead0f62daf44 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/__init__.py @@ -0,0 +1,110 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import os +import sys +import numpy as np +import skimage +import paddle +import signal +import random + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(os.path.abspath(os.path.join(__dir__, '../..'))) + +import copy +from paddle.io import Dataset, DataLoader, BatchSampler, DistributedBatchSampler +import paddle.distributed as dist + +from ppocr.data.imaug import transform, create_operators +from ppocr.data.simple_dataset import SimpleDataSet +from ppocr.data.lmdb_dataset import LMDBDataSet, LMDBDataSetSR +from ppocr.data.pgnet_dataset import PGDataSet +from ppocr.data.pubtab_dataset import PubTabDataSet + +__all__ = ['build_dataloader', 'transform', 'create_operators'] + + +def term_mp(sig_num, frame): + """ kill all child processes + """ + pid = os.getpid() + pgid = os.getpgid(os.getpid()) + print("main proc {} exit, kill process group " "{}".format(pid, pgid)) + os.killpg(pgid, signal.SIGKILL) + + +def build_dataloader(config, mode, device, logger, seed=None): + config = copy.deepcopy(config) + + support_dict = [ + 'SimpleDataSet', 'LMDBDataSet', 'PGDataSet', 'PubTabDataSet', + 'LMDBDataSetSR' + ] + module_name = config[mode]['dataset']['name'] + assert module_name in support_dict, Exception( + 'DataSet only support {}'.format(support_dict)) + assert mode in ['Train', 'Eval', 'Test' + ], "Mode should be Train, Eval or Test." + + dataset = eval(module_name)(config, mode, logger, seed) + loader_config = config[mode]['loader'] + batch_size = loader_config['batch_size_per_card'] + drop_last = loader_config['drop_last'] + shuffle = loader_config['shuffle'] + num_workers = loader_config['num_workers'] + if 'use_shared_memory' in loader_config.keys(): + use_shared_memory = loader_config['use_shared_memory'] + else: + use_shared_memory = True + + if mode == "Train": + # Distribute data to multiple cards + batch_sampler = DistributedBatchSampler( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last) + else: + # Distribute data to single card + batch_sampler = BatchSampler( + dataset=dataset, + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last) + + if 'collate_fn' in loader_config: + from . import collate_fn + collate_fn = getattr(collate_fn, loader_config['collate_fn'])() + else: + collate_fn = None + data_loader = DataLoader( + dataset=dataset, + batch_sampler=batch_sampler, + places=device, + num_workers=num_workers, + return_list=True, + use_shared_memory=use_shared_memory, + collate_fn=collate_fn) + + # support exit using ctrl+c + signal.signal(signal.SIGINT, term_mp) + signal.signal(signal.SIGTERM, term_mp) + + return data_loader diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/collate_fn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/collate_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..0da6060f042a0e60cdf211d8bc13aede32d5930a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/collate_fn.py @@ -0,0 +1,72 @@ +# Copyright (c) 2021 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. + +import paddle +import numbers +import numpy as np +from collections import defaultdict + + +class DictCollator(object): + """ + data batch + """ + + def __call__(self, batch): + # todo:support batch operators + data_dict = defaultdict(list) + to_tensor_keys = [] + for sample in batch: + for k, v in sample.items(): + if isinstance(v, (np.ndarray, paddle.Tensor, numbers.Number)): + if k not in to_tensor_keys: + to_tensor_keys.append(k) + data_dict[k].append(v) + for k in to_tensor_keys: + data_dict[k] = paddle.to_tensor(data_dict[k]) + return data_dict + + +class ListCollator(object): + """ + data batch + """ + + def __call__(self, batch): + # todo:support batch operators + data_dict = defaultdict(list) + to_tensor_idxs = [] + for sample in batch: + for idx, v in enumerate(sample): + if isinstance(v, (np.ndarray, paddle.Tensor, numbers.Number)): + if idx not in to_tensor_idxs: + to_tensor_idxs.append(idx) + data_dict[idx].append(v) + for idx in to_tensor_idxs: + data_dict[idx] = paddle.to_tensor(data_dict[idx]) + return list(data_dict.values()) + + +class SSLRotateCollate(object): + """ + bach: [ + [(4*3xH*W), (4,)] + [(4*3xH*W), (4,)] + ... + ] + """ + + def __call__(self, batch): + output = [np.concatenate(d, axis=0) for d in zip(*batch)] + return output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ColorJitter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ColorJitter.py new file mode 100644 index 0000000000000000000000000000000000000000..4b542abc8f9dc5af76529f9feb4bcb8b47b5f7d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ColorJitter.py @@ -0,0 +1,26 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +from paddle.vision.transforms import ColorJitter as pp_ColorJitter + +__all__ = ['ColorJitter'] + +class ColorJitter(object): + def __init__(self, brightness=0, contrast=0, saturation=0, hue=0,**kwargs): + self.aug = pp_ColorJitter(brightness, contrast, saturation, hue) + + def __call__(self, data): + image = data['image'] + image = self.aug(image) + data['image'] = image + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..102f48fcc19e59d9f8ffb0ad496f54cc64864f7d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/__init__.py @@ -0,0 +1,77 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from .iaa_augment import IaaAugment +from .make_border_map import MakeBorderMap +from .make_shrink_map import MakeShrinkMap +from .random_crop_data import EastRandomCropData, RandomCropImgMask +from .make_pse_gt import MakePseGt + + + +from .rec_img_aug import BaseDataAugmentation, RecAug, RecConAug, RecResizeImg, ClsResizeImg, \ + SRNRecResizeImg, GrayRecResizeImg, SARRecResizeImg, PRENResizeImg, \ + ABINetRecResizeImg, SVTRRecResizeImg, ABINetRecAug, VLRecResizeImg, SPINRecResizeImg, RobustScannerRecResizeImg +from .ssl_img_aug import SSLRotateResize +from .randaugment import RandAugment +from .copy_paste import CopyPaste +from .ColorJitter import ColorJitter +from .operators import * +from .label_ops import * + +from .east_process import * +from .sast_process import * +from .pg_process import * +from .table_ops import * + +from .vqa import * + +from .fce_aug import * +from .fce_targets import FCENetTargets + + +def transform(data, ops=None): + """ transform """ + if ops is None: + ops = [] + for op in ops: + data = op(data) + if data is None: + return None + return data + + +def create_operators(op_param_list, global_config=None): + """ + create operators based on the config + + Args: + params(list): a dict list, used to create some operators + """ + assert isinstance(op_param_list, list), ('operator config should be a list') + ops = [] + for operator in op_param_list: + assert isinstance(operator, + dict) and len(operator) == 1, "yaml format error" + op_name = list(operator)[0] + param = {} if operator[op_name] is None else operator[op_name] + if global_config is not None: + param.update(global_config) + op = eval(op_name)(**param) + ops.append(op) + return ops diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/abinet_aug.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/abinet_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..eefdc75d5a5c0ac3f7136bf22a2adb31129bd313 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/abinet_aug.py @@ -0,0 +1,407 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FangShancheng/ABINet/blob/main/transforms.py +""" +import math +import numbers +import random + +import cv2 +import numpy as np +from paddle.vision.transforms import Compose, ColorJitter + + +def sample_asym(magnitude, size=None): + return np.random.beta(1, 4, size) * magnitude + + +def sample_sym(magnitude, size=None): + return (np.random.beta(4, 4, size=size) - 0.5) * 2 * magnitude + + +def sample_uniform(low, high, size=None): + return np.random.uniform(low, high, size=size) + + +def get_interpolation(type='random'): + if type == 'random': + choice = [ + cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA + ] + interpolation = choice[random.randint(0, len(choice) - 1)] + elif type == 'nearest': + interpolation = cv2.INTER_NEAREST + elif type == 'linear': + interpolation = cv2.INTER_LINEAR + elif type == 'cubic': + interpolation = cv2.INTER_CUBIC + elif type == 'area': + interpolation = cv2.INTER_AREA + else: + raise TypeError( + 'Interpolation types only nearest, linear, cubic, area are supported!' + ) + return interpolation + + +class CVRandomRotation(object): + def __init__(self, degrees=15): + assert isinstance(degrees, + numbers.Number), "degree should be a single number." + assert degrees >= 0, "degree must be positive." + self.degrees = degrees + + @staticmethod + def get_params(degrees): + return sample_sym(degrees) + + def __call__(self, img): + angle = self.get_params(self.degrees) + src_h, src_w = img.shape[:2] + M = cv2.getRotationMatrix2D( + center=(src_w / 2, src_h / 2), angle=angle, scale=1.0) + abs_cos, abs_sin = abs(M[0, 0]), abs(M[0, 1]) + dst_w = int(src_h * abs_sin + src_w * abs_cos) + dst_h = int(src_h * abs_cos + src_w * abs_sin) + M[0, 2] += (dst_w - src_w) / 2 + M[1, 2] += (dst_h - src_h) / 2 + + flags = get_interpolation() + return cv2.warpAffine( + img, + M, (dst_w, dst_h), + flags=flags, + borderMode=cv2.BORDER_REPLICATE) + + +class CVRandomAffine(object): + def __init__(self, degrees, translate=None, scale=None, shear=None): + assert isinstance(degrees, + numbers.Number), "degree should be a single number." + assert degrees >= 0, "degree must be positive." + self.degrees = degrees + + if translate is not None: + assert isinstance(translate, (tuple, list)) and len(translate) == 2, \ + "translate should be a list or tuple and it must be of length 2." + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError( + "translation values should be between 0 and 1") + self.translate = translate + + if scale is not None: + assert isinstance(scale, (tuple, list)) and len(scale) == 2, \ + "scale should be a list or tuple and it must be of length 2." + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + if isinstance(shear, numbers.Number): + if shear < 0: + raise ValueError( + "If shear is a single number, it must be positive.") + self.shear = [shear] + else: + assert isinstance(shear, (tuple, list)) and (len(shear) == 2), \ + "shear should be a list or tuple and it must be of length 2." + self.shear = shear + else: + self.shear = shear + + def _get_inverse_affine_matrix(self, center, angle, translate, scale, + shear): + # https://github.com/pytorch/vision/blob/v0.4.0/torchvision/transforms/functional.py#L717 + from numpy import sin, cos, tan + + if isinstance(shear, numbers.Number): + shear = [shear, 0] + + if not isinstance(shear, (tuple, list)) and len(shear) == 2: + raise ValueError( + "Shear should be a single value or a tuple/list containing " + + "two values. Got {}".format(shear)) + + rot = math.radians(angle) + sx, sy = [math.radians(s) for s in shear] + + cx, cy = center + tx, ty = translate + + # RSS without scaling + a = cos(rot - sy) / cos(sy) + b = -cos(rot - sy) * tan(sx) / cos(sy) - sin(rot) + c = sin(rot - sy) / cos(sy) + d = -sin(rot - sy) * tan(sx) / cos(sy) + cos(rot) + + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + M = [d, -b, 0, -c, a, 0] + M = [x / scale for x in M] + + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + M[2] += M[0] * (-cx - tx) + M[1] * (-cy - ty) + M[5] += M[3] * (-cx - tx) + M[4] * (-cy - ty) + + # Apply center translation: C * RSS^-1 * C^-1 * T^-1 + M[2] += cx + M[5] += cy + return M + + @staticmethod + def get_params(degrees, translate, scale_ranges, shears, height): + angle = sample_sym(degrees) + if translate is not None: + max_dx = translate[0] * height + max_dy = translate[1] * height + translations = (np.round(sample_sym(max_dx)), + np.round(sample_sym(max_dy))) + else: + translations = (0, 0) + + if scale_ranges is not None: + scale = sample_uniform(scale_ranges[0], scale_ranges[1]) + else: + scale = 1.0 + + if shears is not None: + if len(shears) == 1: + shear = [sample_sym(shears[0]), 0.] + elif len(shears) == 2: + shear = [sample_sym(shears[0]), sample_sym(shears[1])] + else: + shear = 0.0 + + return angle, translations, scale, shear + + def __call__(self, img): + src_h, src_w = img.shape[:2] + angle, translate, scale, shear = self.get_params( + self.degrees, self.translate, self.scale, self.shear, src_h) + + M = self._get_inverse_affine_matrix((src_w / 2, src_h / 2), angle, + (0, 0), scale, shear) + M = np.array(M).reshape(2, 3) + + startpoints = [(0, 0), (src_w - 1, 0), (src_w - 1, src_h - 1), + (0, src_h - 1)] + project = lambda x, y, a, b, c: int(a * x + b * y + c) + endpoints = [(project(x, y, *M[0]), project(x, y, *M[1])) + for x, y in startpoints] + + rect = cv2.minAreaRect(np.array(endpoints)) + bbox = cv2.boxPoints(rect).astype(dtype=np.int) + max_x, max_y = bbox[:, 0].max(), bbox[:, 1].max() + min_x, min_y = bbox[:, 0].min(), bbox[:, 1].min() + + dst_w = int(max_x - min_x) + dst_h = int(max_y - min_y) + M[0, 2] += (dst_w - src_w) / 2 + M[1, 2] += (dst_h - src_h) / 2 + + # add translate + dst_w += int(abs(translate[0])) + dst_h += int(abs(translate[1])) + if translate[0] < 0: M[0, 2] += abs(translate[0]) + if translate[1] < 0: M[1, 2] += abs(translate[1]) + + flags = get_interpolation() + return cv2.warpAffine( + img, + M, (dst_w, dst_h), + flags=flags, + borderMode=cv2.BORDER_REPLICATE) + + +class CVRandomPerspective(object): + def __init__(self, distortion=0.5): + self.distortion = distortion + + def get_params(self, width, height, distortion): + offset_h = sample_asym( + distortion * height / 2, size=4).astype(dtype=np.int) + offset_w = sample_asym( + distortion * width / 2, size=4).astype(dtype=np.int) + topleft = (offset_w[0], offset_h[0]) + topright = (width - 1 - offset_w[1], offset_h[1]) + botright = (width - 1 - offset_w[2], height - 1 - offset_h[2]) + botleft = (offset_w[3], height - 1 - offset_h[3]) + + startpoints = [(0, 0), (width - 1, 0), (width - 1, height - 1), + (0, height - 1)] + endpoints = [topleft, topright, botright, botleft] + return np.array( + startpoints, dtype=np.float32), np.array( + endpoints, dtype=np.float32) + + def __call__(self, img): + height, width = img.shape[:2] + startpoints, endpoints = self.get_params(width, height, self.distortion) + M = cv2.getPerspectiveTransform(startpoints, endpoints) + + # TODO: more robust way to crop image + rect = cv2.minAreaRect(endpoints) + bbox = cv2.boxPoints(rect).astype(dtype=np.int) + max_x, max_y = bbox[:, 0].max(), bbox[:, 1].max() + min_x, min_y = bbox[:, 0].min(), bbox[:, 1].min() + min_x, min_y = max(min_x, 0), max(min_y, 0) + + flags = get_interpolation() + img = cv2.warpPerspective( + img, + M, (max_x, max_y), + flags=flags, + borderMode=cv2.BORDER_REPLICATE) + img = img[min_y:, min_x:] + return img + + +class CVRescale(object): + def __init__(self, factor=4, base_size=(128, 512)): + """ Define image scales using gaussian pyramid and rescale image to target scale. + + Args: + factor: the decayed factor from base size, factor=4 keeps target scale by default. + base_size: base size the build the bottom layer of pyramid + """ + if isinstance(factor, numbers.Number): + self.factor = round(sample_uniform(0, factor)) + elif isinstance(factor, (tuple, list)) and len(factor) == 2: + self.factor = round(sample_uniform(factor[0], factor[1])) + else: + raise Exception('factor must be number or list with length 2') + # assert factor is valid + self.base_h, self.base_w = base_size[:2] + + def __call__(self, img): + if self.factor == 0: return img + src_h, src_w = img.shape[:2] + cur_w, cur_h = self.base_w, self.base_h + scale_img = cv2.resize( + img, (cur_w, cur_h), interpolation=get_interpolation()) + for _ in range(self.factor): + scale_img = cv2.pyrDown(scale_img) + scale_img = cv2.resize( + scale_img, (src_w, src_h), interpolation=get_interpolation()) + return scale_img + + +class CVGaussianNoise(object): + def __init__(self, mean=0, var=20): + self.mean = mean + if isinstance(var, numbers.Number): + self.var = max(int(sample_asym(var)), 1) + elif isinstance(var, (tuple, list)) and len(var) == 2: + self.var = int(sample_uniform(var[0], var[1])) + else: + raise Exception('degree must be number or list with length 2') + + def __call__(self, img): + noise = np.random.normal(self.mean, self.var**0.5, img.shape) + img = np.clip(img + noise, 0, 255).astype(np.uint8) + return img + + +class CVMotionBlur(object): + def __init__(self, degrees=12, angle=90): + if isinstance(degrees, numbers.Number): + self.degree = max(int(sample_asym(degrees)), 1) + elif isinstance(degrees, (tuple, list)) and len(degrees) == 2: + self.degree = int(sample_uniform(degrees[0], degrees[1])) + else: + raise Exception('degree must be number or list with length 2') + self.angle = sample_uniform(-angle, angle) + + def __call__(self, img): + M = cv2.getRotationMatrix2D((self.degree // 2, self.degree // 2), + self.angle, 1) + motion_blur_kernel = np.zeros((self.degree, self.degree)) + motion_blur_kernel[self.degree // 2, :] = 1 + motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, + (self.degree, self.degree)) + motion_blur_kernel = motion_blur_kernel / self.degree + img = cv2.filter2D(img, -1, motion_blur_kernel) + img = np.clip(img, 0, 255).astype(np.uint8) + return img + + +class CVGeometry(object): + def __init__(self, + degrees=15, + translate=(0.3, 0.3), + scale=(0.5, 2.), + shear=(45, 15), + distortion=0.5, + p=0.5): + self.p = p + type_p = random.random() + if type_p < 0.33: + self.transforms = CVRandomRotation(degrees=degrees) + elif type_p < 0.66: + self.transforms = CVRandomAffine( + degrees=degrees, translate=translate, scale=scale, shear=shear) + else: + self.transforms = CVRandomPerspective(distortion=distortion) + + def __call__(self, img): + if random.random() < self.p: + return self.transforms(img) + else: + return img + + +class CVDeterioration(object): + def __init__(self, var, degrees, factor, p=0.5): + self.p = p + transforms = [] + if var is not None: + transforms.append(CVGaussianNoise(var=var)) + if degrees is not None: + transforms.append(CVMotionBlur(degrees=degrees)) + if factor is not None: + transforms.append(CVRescale(factor=factor)) + + random.shuffle(transforms) + transforms = Compose(transforms) + self.transforms = transforms + + def __call__(self, img): + if random.random() < self.p: + + return self.transforms(img) + else: + return img + + +class CVColorJitter(object): + def __init__(self, + brightness=0.5, + contrast=0.5, + saturation=0.5, + hue=0.1, + p=0.5): + self.p = p + self.transforms = ColorJitter( + brightness=brightness, + contrast=contrast, + saturation=saturation, + hue=hue) + + def __call__(self, img): + if random.random() < self.p: return self.transforms(img) + else: return img diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/copy_paste.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/copy_paste.py new file mode 100644 index 0000000000000000000000000000000000000000..79343da60fd40f8dc0ffe8927398b70cb751b532 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/copy_paste.py @@ -0,0 +1,174 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import copy +import cv2 +import random +import numpy as np +from PIL import Image +from shapely.geometry import Polygon + +from ppocr.data.imaug.iaa_augment import IaaAugment +from ppocr.data.imaug.random_crop_data import is_poly_outside_rect +from tools.infer.utility import get_rotate_crop_image + + +class CopyPaste(object): + def __init__(self, objects_paste_ratio=0.2, limit_paste=True, **kwargs): + self.ext_data_num = 1 + self.objects_paste_ratio = objects_paste_ratio + self.limit_paste = limit_paste + augmenter_args = [{'type': 'Resize', 'args': {'size': [0.5, 3]}}] + self.aug = IaaAugment(augmenter_args) + + def __call__(self, data): + point_num = data['polys'].shape[1] + src_img = data['image'] + src_polys = data['polys'].tolist() + src_texts = data['texts'] + src_ignores = data['ignore_tags'].tolist() + ext_data = data['ext_data'][0] + ext_image = ext_data['image'] + ext_polys = ext_data['polys'] + ext_texts = ext_data['texts'] + ext_ignores = ext_data['ignore_tags'] + + indexs = [i for i in range(len(ext_ignores)) if not ext_ignores[i]] + select_num = max( + 1, min(int(self.objects_paste_ratio * len(ext_polys)), 30)) + + random.shuffle(indexs) + select_idxs = indexs[:select_num] + select_polys = ext_polys[select_idxs] + select_ignores = ext_ignores[select_idxs] + + src_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2RGB) + ext_image = cv2.cvtColor(ext_image, cv2.COLOR_BGR2RGB) + src_img = Image.fromarray(src_img).convert('RGBA') + for idx, poly, tag in zip(select_idxs, select_polys, select_ignores): + box_img = get_rotate_crop_image(ext_image, poly) + + src_img, box = self.paste_img(src_img, box_img, src_polys) + if box is not None: + box = box.tolist() + for _ in range(len(box), point_num): + box.append(box[-1]) + src_polys.append(box) + src_texts.append(ext_texts[idx]) + src_ignores.append(tag) + src_img = cv2.cvtColor(np.array(src_img), cv2.COLOR_RGB2BGR) + h, w = src_img.shape[:2] + src_polys = np.array(src_polys) + src_polys[:, :, 0] = np.clip(src_polys[:, :, 0], 0, w) + src_polys[:, :, 1] = np.clip(src_polys[:, :, 1], 0, h) + data['image'] = src_img + data['polys'] = src_polys + data['texts'] = src_texts + data['ignore_tags'] = np.array(src_ignores) + return data + + def paste_img(self, src_img, box_img, src_polys): + box_img_pil = Image.fromarray(box_img).convert('RGBA') + src_w, src_h = src_img.size + box_w, box_h = box_img_pil.size + + angle = np.random.randint(0, 360) + box = np.array([[[0, 0], [box_w, 0], [box_w, box_h], [0, box_h]]]) + box = rotate_bbox(box_img, box, angle)[0] + box_img_pil = box_img_pil.rotate(angle, expand=1) + box_w, box_h = box_img_pil.width, box_img_pil.height + if src_w - box_w < 0 or src_h - box_h < 0: + return src_img, None + + paste_x, paste_y = self.select_coord(src_polys, box, src_w - box_w, + src_h - box_h) + if paste_x is None: + return src_img, None + box[:, 0] += paste_x + box[:, 1] += paste_y + r, g, b, A = box_img_pil.split() + src_img.paste(box_img_pil, (paste_x, paste_y), mask=A) + + return src_img, box + + def select_coord(self, src_polys, box, endx, endy): + if self.limit_paste: + xmin, ymin, xmax, ymax = box[:, 0].min(), box[:, 1].min( + ), box[:, 0].max(), box[:, 1].max() + for _ in range(50): + paste_x = random.randint(0, endx) + paste_y = random.randint(0, endy) + xmin1 = xmin + paste_x + xmax1 = xmax + paste_x + ymin1 = ymin + paste_y + ymax1 = ymax + paste_y + + num_poly_in_rect = 0 + for poly in src_polys: + if not is_poly_outside_rect(poly, xmin1, ymin1, + xmax1 - xmin1, ymax1 - ymin1): + num_poly_in_rect += 1 + break + if num_poly_in_rect == 0: + return paste_x, paste_y + return None, None + else: + paste_x = random.randint(0, endx) + paste_y = random.randint(0, endy) + return paste_x, paste_y + + +def get_union(pD, pG): + return Polygon(pD).union(Polygon(pG)).area + + +def get_intersection_over_union(pD, pG): + return get_intersection(pD, pG) / get_union(pD, pG) + + +def get_intersection(pD, pG): + return Polygon(pD).intersection(Polygon(pG)).area + + +def rotate_bbox(img, text_polys, angle, scale=1): + """ + from https://github.com/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/augment.py + Args: + img: np.ndarray + text_polys: np.ndarray N*4*2 + angle: int + scale: int + + Returns: + + """ + w = img.shape[1] + h = img.shape[0] + + rangle = np.deg2rad(angle) + nw = (abs(np.sin(rangle) * h) + abs(np.cos(rangle) * w)) + nh = (abs(np.cos(rangle) * h) + abs(np.sin(rangle) * w)) + rot_mat = cv2.getRotationMatrix2D((nw * 0.5, nh * 0.5), angle, scale) + rot_move = np.dot(rot_mat, np.array([(nw - w) * 0.5, (nh - h) * 0.5, 0])) + rot_mat[0, 2] += rot_move[0] + rot_mat[1, 2] += rot_move[1] + + # ---------------------- rotate box ---------------------- + rot_text_polys = list() + for bbox in text_polys: + point1 = np.dot(rot_mat, np.array([bbox[0, 0], bbox[0, 1], 1])) + point2 = np.dot(rot_mat, np.array([bbox[1, 0], bbox[1, 1], 1])) + point3 = np.dot(rot_mat, np.array([bbox[2, 0], bbox[2, 1], 1])) + point4 = np.dot(rot_mat, np.array([bbox[3, 0], bbox[3, 1], 1])) + rot_text_polys.append([point1, point2, point3, point4]) + return np.array(rot_text_polys, dtype=np.float32) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/east_process.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/east_process.py new file mode 100644 index 0000000000000000000000000000000000000000..df08adfa1516c59229e95af193c172dfcdd5af08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/east_process.py @@ -0,0 +1,436 @@ +#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +#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. +""" +This code is refered from: +https://github.com/songdejia/EAST/blob/master/data_utils.py +""" +import math +import cv2 +import numpy as np +import json +import sys +import os + +__all__ = ['EASTProcessTrain'] + + +class EASTProcessTrain(object): + def __init__(self, + image_shape=[512, 512], + background_ratio=0.125, + min_crop_side_ratio=0.1, + min_text_size=10, + **kwargs): + self.input_size = image_shape[1] + self.random_scale = np.array([0.5, 1, 2.0, 3.0]) + self.background_ratio = background_ratio + self.min_crop_side_ratio = min_crop_side_ratio + self.min_text_size = min_text_size + + def preprocess(self, im): + input_size = self.input_size + im_shape = im.shape + im_size_min = np.min(im_shape[0:2]) + im_size_max = np.max(im_shape[0:2]) + im_scale = float(input_size) / float(im_size_max) + im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale) + img_mean = [0.485, 0.456, 0.406] + img_std = [0.229, 0.224, 0.225] + # im = im[:, :, ::-1].astype(np.float32) + im = im / 255 + im -= img_mean + im /= img_std + new_h, new_w, _ = im.shape + im_padded = np.zeros((input_size, input_size, 3), dtype=np.float32) + im_padded[:new_h, :new_w, :] = im + im_padded = im_padded.transpose((2, 0, 1)) + im_padded = im_padded[np.newaxis, :] + return im_padded, im_scale + + def rotate_im_poly(self, im, text_polys): + """ + rotate image with 90 / 180 / 270 degre + """ + im_w, im_h = im.shape[1], im.shape[0] + dst_im = im.copy() + dst_polys = [] + rand_degree_ratio = np.random.rand() + rand_degree_cnt = 1 + if 0.333 < rand_degree_ratio < 0.666: + rand_degree_cnt = 2 + elif rand_degree_ratio > 0.666: + rand_degree_cnt = 3 + for i in range(rand_degree_cnt): + dst_im = np.rot90(dst_im) + rot_degree = -90 * rand_degree_cnt + rot_angle = rot_degree * math.pi / 180.0 + n_poly = text_polys.shape[0] + cx, cy = 0.5 * im_w, 0.5 * im_h + ncx, ncy = 0.5 * dst_im.shape[1], 0.5 * dst_im.shape[0] + for i in range(n_poly): + wordBB = text_polys[i] + poly = [] + for j in range(4): + sx, sy = wordBB[j][0], wordBB[j][1] + dx = math.cos(rot_angle) * (sx - cx)\ + - math.sin(rot_angle) * (sy - cy) + ncx + dy = math.sin(rot_angle) * (sx - cx)\ + + math.cos(rot_angle) * (sy - cy) + ncy + poly.append([dx, dy]) + dst_polys.append(poly) + dst_polys = np.array(dst_polys, dtype=np.float32) + return dst_im, dst_polys + + def polygon_area(self, poly): + """ + compute area of a polygon + :param poly: + :return: + """ + edge = [(poly[1][0] - poly[0][0]) * (poly[1][1] + poly[0][1]), + (poly[2][0] - poly[1][0]) * (poly[2][1] + poly[1][1]), + (poly[3][0] - poly[2][0]) * (poly[3][1] + poly[2][1]), + (poly[0][0] - poly[3][0]) * (poly[0][1] + poly[3][1])] + return np.sum(edge) / 2. + + def check_and_validate_polys(self, polys, tags, img_height, img_width): + """ + check so that the text poly is in the same direction, + and also filter some invalid polygons + :param polys: + :param tags: + :return: + """ + h, w = img_height, img_width + if polys.shape[0] == 0: + return polys + polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w - 1) + polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h - 1) + + validated_polys = [] + validated_tags = [] + for poly, tag in zip(polys, tags): + p_area = self.polygon_area(poly) + #invalid poly + if abs(p_area) < 1: + continue + if p_area > 0: + #'poly in wrong direction' + if not tag: + tag = True #reversed cases should be ignore + poly = poly[(0, 3, 2, 1), :] + validated_polys.append(poly) + validated_tags.append(tag) + return np.array(validated_polys), np.array(validated_tags) + + def draw_img_polys(self, img, polys): + if len(img.shape) == 4: + img = np.squeeze(img, axis=0) + if img.shape[0] == 3: + img = img.transpose((1, 2, 0)) + img[:, :, 2] += 123.68 + img[:, :, 1] += 116.78 + img[:, :, 0] += 103.94 + cv2.imwrite("tmp.jpg", img) + img = cv2.imread("tmp.jpg") + for box in polys: + box = box.astype(np.int32).reshape((-1, 1, 2)) + cv2.polylines(img, [box], True, color=(255, 255, 0), thickness=2) + import random + ino = random.randint(0, 100) + cv2.imwrite("tmp_%d.jpg" % ino, img) + return + + def shrink_poly(self, poly, r): + """ + fit a poly inside the origin poly, maybe bugs here... + used for generate the score map + :param poly: the text poly + :param r: r in the paper + :return: the shrinked poly + """ + # shrink ratio + R = 0.3 + # find the longer pair + dist0 = np.linalg.norm(poly[0] - poly[1]) + dist1 = np.linalg.norm(poly[2] - poly[3]) + dist2 = np.linalg.norm(poly[0] - poly[3]) + dist3 = np.linalg.norm(poly[1] - poly[2]) + if dist0 + dist1 > dist2 + dist3: + # first move (p0, p1), (p2, p3), then (p0, p3), (p1, p2) + ## p0, p1 + theta = np.arctan2((poly[1][1] - poly[0][1]), + (poly[1][0] - poly[0][0])) + poly[0][0] += R * r[0] * np.cos(theta) + poly[0][1] += R * r[0] * np.sin(theta) + poly[1][0] -= R * r[1] * np.cos(theta) + poly[1][1] -= R * r[1] * np.sin(theta) + ## p2, p3 + theta = np.arctan2((poly[2][1] - poly[3][1]), + (poly[2][0] - poly[3][0])) + poly[3][0] += R * r[3] * np.cos(theta) + poly[3][1] += R * r[3] * np.sin(theta) + poly[2][0] -= R * r[2] * np.cos(theta) + poly[2][1] -= R * r[2] * np.sin(theta) + ## p0, p3 + theta = np.arctan2((poly[3][0] - poly[0][0]), + (poly[3][1] - poly[0][1])) + poly[0][0] += R * r[0] * np.sin(theta) + poly[0][1] += R * r[0] * np.cos(theta) + poly[3][0] -= R * r[3] * np.sin(theta) + poly[3][1] -= R * r[3] * np.cos(theta) + ## p1, p2 + theta = np.arctan2((poly[2][0] - poly[1][0]), + (poly[2][1] - poly[1][1])) + poly[1][0] += R * r[1] * np.sin(theta) + poly[1][1] += R * r[1] * np.cos(theta) + poly[2][0] -= R * r[2] * np.sin(theta) + poly[2][1] -= R * r[2] * np.cos(theta) + else: + ## p0, p3 + # print poly + theta = np.arctan2((poly[3][0] - poly[0][0]), + (poly[3][1] - poly[0][1])) + poly[0][0] += R * r[0] * np.sin(theta) + poly[0][1] += R * r[0] * np.cos(theta) + poly[3][0] -= R * r[3] * np.sin(theta) + poly[3][1] -= R * r[3] * np.cos(theta) + ## p1, p2 + theta = np.arctan2((poly[2][0] - poly[1][0]), + (poly[2][1] - poly[1][1])) + poly[1][0] += R * r[1] * np.sin(theta) + poly[1][1] += R * r[1] * np.cos(theta) + poly[2][0] -= R * r[2] * np.sin(theta) + poly[2][1] -= R * r[2] * np.cos(theta) + ## p0, p1 + theta = np.arctan2((poly[1][1] - poly[0][1]), + (poly[1][0] - poly[0][0])) + poly[0][0] += R * r[0] * np.cos(theta) + poly[0][1] += R * r[0] * np.sin(theta) + poly[1][0] -= R * r[1] * np.cos(theta) + poly[1][1] -= R * r[1] * np.sin(theta) + ## p2, p3 + theta = np.arctan2((poly[2][1] - poly[3][1]), + (poly[2][0] - poly[3][0])) + poly[3][0] += R * r[3] * np.cos(theta) + poly[3][1] += R * r[3] * np.sin(theta) + poly[2][0] -= R * r[2] * np.cos(theta) + poly[2][1] -= R * r[2] * np.sin(theta) + return poly + + def generate_quad(self, im_size, polys, tags): + """ + Generate quadrangle. + """ + h, w = im_size + poly_mask = np.zeros((h, w), dtype=np.uint8) + score_map = np.zeros((h, w), dtype=np.uint8) + # (x1, y1, ..., x4, y4, short_edge_norm) + geo_map = np.zeros((h, w, 9), dtype=np.float32) + # mask used during traning, to ignore some hard areas + training_mask = np.ones((h, w), dtype=np.uint8) + for poly_idx, poly_tag in enumerate(zip(polys, tags)): + poly = poly_tag[0] + tag = poly_tag[1] + + r = [None, None, None, None] + for i in range(4): + dist1 = np.linalg.norm(poly[i] - poly[(i + 1) % 4]) + dist2 = np.linalg.norm(poly[i] - poly[(i - 1) % 4]) + r[i] = min(dist1, dist2) + # score map + shrinked_poly = self.shrink_poly( + poly.copy(), r).astype(np.int32)[np.newaxis, :, :] + cv2.fillPoly(score_map, shrinked_poly, 1) + cv2.fillPoly(poly_mask, shrinked_poly, poly_idx + 1) + # if the poly is too small, then ignore it during training + poly_h = min( + np.linalg.norm(poly[0] - poly[3]), + np.linalg.norm(poly[1] - poly[2])) + poly_w = min( + np.linalg.norm(poly[0] - poly[1]), + np.linalg.norm(poly[2] - poly[3])) + if min(poly_h, poly_w) < self.min_text_size: + cv2.fillPoly(training_mask, + poly.astype(np.int32)[np.newaxis, :, :], 0) + + if tag: + cv2.fillPoly(training_mask, + poly.astype(np.int32)[np.newaxis, :, :], 0) + + xy_in_poly = np.argwhere(poly_mask == (poly_idx + 1)) + # geo map. + y_in_poly = xy_in_poly[:, 0] + x_in_poly = xy_in_poly[:, 1] + poly[:, 0] = np.minimum(np.maximum(poly[:, 0], 0), w) + poly[:, 1] = np.minimum(np.maximum(poly[:, 1], 0), h) + for pno in range(4): + geo_channel_beg = pno * 2 + geo_map[y_in_poly, x_in_poly, geo_channel_beg] =\ + x_in_poly - poly[pno, 0] + geo_map[y_in_poly, x_in_poly, geo_channel_beg+1] =\ + y_in_poly - poly[pno, 1] + geo_map[y_in_poly, x_in_poly, 8] = \ + 1.0 / max(min(poly_h, poly_w), 1.0) + return score_map, geo_map, training_mask + + def crop_area(self, im, polys, tags, crop_background=False, max_tries=50): + """ + make random crop from the input image + :param im: + :param polys: + :param tags: + :param crop_background: + :param max_tries: + :return: + """ + h, w, _ = im.shape + pad_h = h // 10 + pad_w = w // 10 + h_array = np.zeros((h + pad_h * 2), dtype=np.int32) + w_array = np.zeros((w + pad_w * 2), dtype=np.int32) + for poly in polys: + poly = np.round(poly, decimals=0).astype(np.int32) + minx = np.min(poly[:, 0]) + maxx = np.max(poly[:, 0]) + w_array[minx + pad_w:maxx + pad_w] = 1 + miny = np.min(poly[:, 1]) + maxy = np.max(poly[:, 1]) + h_array[miny + pad_h:maxy + pad_h] = 1 + # ensure the cropped area not across a text + h_axis = np.where(h_array == 0)[0] + w_axis = np.where(w_array == 0)[0] + if len(h_axis) == 0 or len(w_axis) == 0: + return im, polys, tags + + for i in range(max_tries): + xx = np.random.choice(w_axis, size=2) + xmin = np.min(xx) - pad_w + xmax = np.max(xx) - pad_w + xmin = np.clip(xmin, 0, w - 1) + xmax = np.clip(xmax, 0, w - 1) + yy = np.random.choice(h_axis, size=2) + ymin = np.min(yy) - pad_h + ymax = np.max(yy) - pad_h + ymin = np.clip(ymin, 0, h - 1) + ymax = np.clip(ymax, 0, h - 1) + if xmax - xmin < self.min_crop_side_ratio * w or \ + ymax - ymin < self.min_crop_side_ratio * h: + # area too small + continue + if polys.shape[0] != 0: + poly_axis_in_area = (polys[:, :, 0] >= xmin)\ + & (polys[:, :, 0] <= xmax)\ + & (polys[:, :, 1] >= ymin)\ + & (polys[:, :, 1] <= ymax) + selected_polys = np.where( + np.sum(poly_axis_in_area, axis=1) == 4)[0] + else: + selected_polys = [] + + if len(selected_polys) == 0: + # no text in this area + if crop_background: + im = im[ymin:ymax + 1, xmin:xmax + 1, :] + polys = [] + tags = [] + return im, polys, tags + else: + continue + + im = im[ymin:ymax + 1, xmin:xmax + 1, :] + polys = polys[selected_polys] + tags = tags[selected_polys] + polys[:, :, 0] -= xmin + polys[:, :, 1] -= ymin + return im, polys, tags + return im, polys, tags + + def crop_background_infor(self, im, text_polys, text_tags): + im, text_polys, text_tags = self.crop_area( + im, text_polys, text_tags, crop_background=True) + + if len(text_polys) > 0: + return None + # pad and resize image + input_size = self.input_size + im, ratio = self.preprocess(im) + score_map = np.zeros((input_size, input_size), dtype=np.float32) + geo_map = np.zeros((input_size, input_size, 9), dtype=np.float32) + training_mask = np.ones((input_size, input_size), dtype=np.float32) + return im, score_map, geo_map, training_mask + + def crop_foreground_infor(self, im, text_polys, text_tags): + im, text_polys, text_tags = self.crop_area( + im, text_polys, text_tags, crop_background=False) + + if text_polys.shape[0] == 0: + return None + #continue for all ignore case + if np.sum((text_tags * 1.0)) >= text_tags.size: + return None + # pad and resize image + input_size = self.input_size + im, ratio = self.preprocess(im) + text_polys[:, :, 0] *= ratio + text_polys[:, :, 1] *= ratio + _, _, new_h, new_w = im.shape + # print(im.shape) + # self.draw_img_polys(im, text_polys) + score_map, geo_map, training_mask = self.generate_quad( + (new_h, new_w), text_polys, text_tags) + return im, score_map, geo_map, training_mask + + def __call__(self, data): + im = data['image'] + text_polys = data['polys'] + text_tags = data['ignore_tags'] + if im is None: + return None + if text_polys.shape[0] == 0: + return None + + #add rotate cases + if np.random.rand() < 0.5: + im, text_polys = self.rotate_im_poly(im, text_polys) + h, w, _ = im.shape + text_polys, text_tags = self.check_and_validate_polys(text_polys, + text_tags, h, w) + if text_polys.shape[0] == 0: + return None + + # random scale this image + rd_scale = np.random.choice(self.random_scale) + im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale) + text_polys *= rd_scale + if np.random.rand() < self.background_ratio: + outs = self.crop_background_infor(im, text_polys, text_tags) + else: + outs = self.crop_foreground_infor(im, text_polys, text_tags) + + if outs is None: + return None + im, score_map, geo_map, training_mask = outs + score_map = score_map[np.newaxis, ::4, ::4].astype(np.float32) + geo_map = np.swapaxes(geo_map, 1, 2) + geo_map = np.swapaxes(geo_map, 1, 0) + geo_map = geo_map[:, ::4, ::4].astype(np.float32) + training_mask = training_mask[np.newaxis, ::4, ::4] + training_mask = training_mask.astype(np.float32) + + data['image'] = im[0] + data['score_map'] = score_map + data['geo_map'] = geo_map + data['training_mask'] = training_mask + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_aug.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..66bafef13caaaa958c89f865bde04cb25f031329 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_aug.py @@ -0,0 +1,564 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/datasets/pipelines/transforms.py +""" +import numpy as np +from PIL import Image, ImageDraw +import cv2 +from shapely.geometry import Polygon +import math +from ppocr.utils.poly_nms import poly_intersection + + +class RandomScaling: + def __init__(self, size=800, scale=(3. / 4, 5. / 2), **kwargs): + """Random scale the image while keeping aspect. + + Args: + size (int) : Base size before scaling. + scale (tuple(float)) : The range of scaling. + """ + assert isinstance(size, int) + assert isinstance(scale, float) or isinstance(scale, tuple) + self.size = size + self.scale = scale if isinstance(scale, tuple) \ + else (1 - scale, 1 + scale) + + def __call__(self, data): + image = data['image'] + text_polys = data['polys'] + h, w, _ = image.shape + + aspect_ratio = np.random.uniform(min(self.scale), max(self.scale)) + scales = self.size * 1.0 / max(h, w) * aspect_ratio + scales = np.array([scales, scales]) + out_size = (int(h * scales[1]), int(w * scales[0])) + image = cv2.resize(image, out_size[::-1]) + + data['image'] = image + text_polys[:, :, 0::2] = text_polys[:, :, 0::2] * scales[1] + text_polys[:, :, 1::2] = text_polys[:, :, 1::2] * scales[0] + data['polys'] = text_polys + + return data + + +class RandomCropFlip: + def __init__(self, + pad_ratio=0.1, + crop_ratio=0.5, + iter_num=1, + min_area_ratio=0.2, + **kwargs): + """Random crop and flip a patch of the image. + + Args: + crop_ratio (float): The ratio of cropping. + iter_num (int): Number of operations. + min_area_ratio (float): Minimal area ratio between cropped patch + and original image. + """ + assert isinstance(crop_ratio, float) + assert isinstance(iter_num, int) + assert isinstance(min_area_ratio, float) + + self.pad_ratio = pad_ratio + self.epsilon = 1e-2 + self.crop_ratio = crop_ratio + self.iter_num = iter_num + self.min_area_ratio = min_area_ratio + + def __call__(self, results): + for i in range(self.iter_num): + results = self.random_crop_flip(results) + + return results + + def random_crop_flip(self, results): + image = results['image'] + polygons = results['polys'] + ignore_tags = results['ignore_tags'] + if len(polygons) == 0: + return results + + if np.random.random() >= self.crop_ratio: + return results + + h, w, _ = image.shape + area = h * w + pad_h = int(h * self.pad_ratio) + pad_w = int(w * self.pad_ratio) + h_axis, w_axis = self.generate_crop_target(image, polygons, pad_h, + pad_w) + if len(h_axis) == 0 or len(w_axis) == 0: + return results + + attempt = 0 + while attempt < 50: + attempt += 1 + polys_keep = [] + polys_new = [] + ignore_tags_keep = [] + ignore_tags_new = [] + xx = np.random.choice(w_axis, size=2) + xmin = np.min(xx) - pad_w + xmax = np.max(xx) - pad_w + xmin = np.clip(xmin, 0, w - 1) + xmax = np.clip(xmax, 0, w - 1) + yy = np.random.choice(h_axis, size=2) + ymin = np.min(yy) - pad_h + ymax = np.max(yy) - pad_h + ymin = np.clip(ymin, 0, h - 1) + ymax = np.clip(ymax, 0, h - 1) + if (xmax - xmin) * (ymax - ymin) < area * self.min_area_ratio: + # area too small + continue + + pts = np.stack([[xmin, xmax, xmax, xmin], + [ymin, ymin, ymax, ymax]]).T.astype(np.int32) + pp = Polygon(pts) + fail_flag = False + for polygon, ignore_tag in zip(polygons, ignore_tags): + ppi = Polygon(polygon.reshape(-1, 2)) + ppiou, _ = poly_intersection(ppi, pp, buffer=0) + if np.abs(ppiou - float(ppi.area)) > self.epsilon and \ + np.abs(ppiou) > self.epsilon: + fail_flag = True + break + elif np.abs(ppiou - float(ppi.area)) < self.epsilon: + polys_new.append(polygon) + ignore_tags_new.append(ignore_tag) + else: + polys_keep.append(polygon) + ignore_tags_keep.append(ignore_tag) + + if fail_flag: + continue + else: + break + + cropped = image[ymin:ymax, xmin:xmax, :] + select_type = np.random.randint(3) + if select_type == 0: + img = np.ascontiguousarray(cropped[:, ::-1]) + elif select_type == 1: + img = np.ascontiguousarray(cropped[::-1, :]) + else: + img = np.ascontiguousarray(cropped[::-1, ::-1]) + image[ymin:ymax, xmin:xmax, :] = img + results['img'] = image + + if len(polys_new) != 0: + height, width, _ = cropped.shape + if select_type == 0: + for idx, polygon in enumerate(polys_new): + poly = polygon.reshape(-1, 2) + poly[:, 0] = width - poly[:, 0] + 2 * xmin + polys_new[idx] = poly + elif select_type == 1: + for idx, polygon in enumerate(polys_new): + poly = polygon.reshape(-1, 2) + poly[:, 1] = height - poly[:, 1] + 2 * ymin + polys_new[idx] = poly + else: + for idx, polygon in enumerate(polys_new): + poly = polygon.reshape(-1, 2) + poly[:, 0] = width - poly[:, 0] + 2 * xmin + poly[:, 1] = height - poly[:, 1] + 2 * ymin + polys_new[idx] = poly + polygons = polys_keep + polys_new + ignore_tags = ignore_tags_keep + ignore_tags_new + results['polys'] = np.array(polygons) + results['ignore_tags'] = ignore_tags + + return results + + def generate_crop_target(self, image, all_polys, pad_h, pad_w): + """Generate crop target and make sure not to crop the polygon + instances. + + Args: + image (ndarray): The image waited to be crop. + all_polys (list[list[ndarray]]): All polygons including ground + truth polygons and ground truth ignored polygons. + pad_h (int): Padding length of height. + pad_w (int): Padding length of width. + Returns: + h_axis (ndarray): Vertical cropping range. + w_axis (ndarray): Horizontal cropping range. + """ + h, w, _ = image.shape + h_array = np.zeros((h + pad_h * 2), dtype=np.int32) + w_array = np.zeros((w + pad_w * 2), dtype=np.int32) + + text_polys = [] + for polygon in all_polys: + rect = cv2.minAreaRect(polygon.astype(np.int32).reshape(-1, 2)) + box = cv2.boxPoints(rect) + box = np.int0(box) + text_polys.append([box[0], box[1], box[2], box[3]]) + + polys = np.array(text_polys, dtype=np.int32) + for poly in polys: + poly = np.round(poly, decimals=0).astype(np.int32) + minx = np.min(poly[:, 0]) + maxx = np.max(poly[:, 0]) + w_array[minx + pad_w:maxx + pad_w] = 1 + miny = np.min(poly[:, 1]) + maxy = np.max(poly[:, 1]) + h_array[miny + pad_h:maxy + pad_h] = 1 + + h_axis = np.where(h_array == 0)[0] + w_axis = np.where(w_array == 0)[0] + return h_axis, w_axis + + +class RandomCropPolyInstances: + """Randomly crop images and make sure to contain at least one intact + instance.""" + + def __init__(self, crop_ratio=5.0 / 8.0, min_side_ratio=0.4, **kwargs): + super().__init__() + self.crop_ratio = crop_ratio + self.min_side_ratio = min_side_ratio + + def sample_valid_start_end(self, valid_array, min_len, max_start, min_end): + + assert isinstance(min_len, int) + assert len(valid_array) > min_len + + start_array = valid_array.copy() + max_start = min(len(start_array) - min_len, max_start) + start_array[max_start:] = 0 + start_array[0] = 1 + diff_array = np.hstack([0, start_array]) - np.hstack([start_array, 0]) + region_starts = np.where(diff_array < 0)[0] + region_ends = np.where(diff_array > 0)[0] + region_ind = np.random.randint(0, len(region_starts)) + start = np.random.randint(region_starts[region_ind], + region_ends[region_ind]) + + end_array = valid_array.copy() + min_end = max(start + min_len, min_end) + end_array[:min_end] = 0 + end_array[-1] = 1 + diff_array = np.hstack([0, end_array]) - np.hstack([end_array, 0]) + region_starts = np.where(diff_array < 0)[0] + region_ends = np.where(diff_array > 0)[0] + region_ind = np.random.randint(0, len(region_starts)) + end = np.random.randint(region_starts[region_ind], + region_ends[region_ind]) + return start, end + + def sample_crop_box(self, img_size, results): + """Generate crop box and make sure not to crop the polygon instances. + + Args: + img_size (tuple(int)): The image size (h, w). + results (dict): The results dict. + """ + + assert isinstance(img_size, tuple) + h, w = img_size[:2] + + key_masks = results['polys'] + + x_valid_array = np.ones(w, dtype=np.int32) + y_valid_array = np.ones(h, dtype=np.int32) + + selected_mask = key_masks[np.random.randint(0, len(key_masks))] + selected_mask = selected_mask.reshape((-1, 2)).astype(np.int32) + max_x_start = max(np.min(selected_mask[:, 0]) - 2, 0) + min_x_end = min(np.max(selected_mask[:, 0]) + 3, w - 1) + max_y_start = max(np.min(selected_mask[:, 1]) - 2, 0) + min_y_end = min(np.max(selected_mask[:, 1]) + 3, h - 1) + + for mask in key_masks: + mask = mask.reshape((-1, 2)).astype(np.int32) + clip_x = np.clip(mask[:, 0], 0, w - 1) + clip_y = np.clip(mask[:, 1], 0, h - 1) + min_x, max_x = np.min(clip_x), np.max(clip_x) + min_y, max_y = np.min(clip_y), np.max(clip_y) + + x_valid_array[min_x - 2:max_x + 3] = 0 + y_valid_array[min_y - 2:max_y + 3] = 0 + + min_w = int(w * self.min_side_ratio) + min_h = int(h * self.min_side_ratio) + + x1, x2 = self.sample_valid_start_end(x_valid_array, min_w, max_x_start, + min_x_end) + y1, y2 = self.sample_valid_start_end(y_valid_array, min_h, max_y_start, + min_y_end) + + return np.array([x1, y1, x2, y2]) + + def crop_img(self, img, bbox): + assert img.ndim == 3 + h, w, _ = img.shape + assert 0 <= bbox[1] < bbox[3] <= h + assert 0 <= bbox[0] < bbox[2] <= w + return img[bbox[1]:bbox[3], bbox[0]:bbox[2]] + + def __call__(self, results): + image = results['image'] + polygons = results['polys'] + ignore_tags = results['ignore_tags'] + if len(polygons) < 1: + return results + + if np.random.random_sample() < self.crop_ratio: + + crop_box = self.sample_crop_box(image.shape, results) + img = self.crop_img(image, crop_box) + results['image'] = img + # crop and filter masks + x1, y1, x2, y2 = crop_box + w = max(x2 - x1, 1) + h = max(y2 - y1, 1) + polygons[:, :, 0::2] = polygons[:, :, 0::2] - x1 + polygons[:, :, 1::2] = polygons[:, :, 1::2] - y1 + + valid_masks_list = [] + valid_tags_list = [] + for ind, polygon in enumerate(polygons): + if (polygon[:, ::2] > -4).all() and ( + polygon[:, ::2] < w + 4).all() and ( + polygon[:, 1::2] > -4).all() and ( + polygon[:, 1::2] < h + 4).all(): + polygon[:, ::2] = np.clip(polygon[:, ::2], 0, w) + polygon[:, 1::2] = np.clip(polygon[:, 1::2], 0, h) + valid_masks_list.append(polygon) + valid_tags_list.append(ignore_tags[ind]) + + results['polys'] = np.array(valid_masks_list) + results['ignore_tags'] = valid_tags_list + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + return repr_str + + +class RandomRotatePolyInstances: + def __init__(self, + rotate_ratio=0.5, + max_angle=10, + pad_with_fixed_color=False, + pad_value=(0, 0, 0), + **kwargs): + """Randomly rotate images and polygon masks. + + Args: + rotate_ratio (float): The ratio of samples to operate rotation. + max_angle (int): The maximum rotation angle. + pad_with_fixed_color (bool): The flag for whether to pad rotated + image with fixed value. If set to False, the rotated image will + be padded onto cropped image. + pad_value (tuple(int)): The color value for padding rotated image. + """ + self.rotate_ratio = rotate_ratio + self.max_angle = max_angle + self.pad_with_fixed_color = pad_with_fixed_color + self.pad_value = pad_value + + def rotate(self, center, points, theta, center_shift=(0, 0)): + # rotate points. + (center_x, center_y) = center + center_y = -center_y + x, y = points[:, ::2], points[:, 1::2] + y = -y + + theta = theta / 180 * math.pi + cos = math.cos(theta) + sin = math.sin(theta) + + x = (x - center_x) + y = (y - center_y) + + _x = center_x + x * cos - y * sin + center_shift[0] + _y = -(center_y + x * sin + y * cos) + center_shift[1] + + points[:, ::2], points[:, 1::2] = _x, _y + return points + + def cal_canvas_size(self, ori_size, degree): + assert isinstance(ori_size, tuple) + angle = degree * math.pi / 180.0 + h, w = ori_size[:2] + + cos = math.cos(angle) + sin = math.sin(angle) + canvas_h = int(w * math.fabs(sin) + h * math.fabs(cos)) + canvas_w = int(w * math.fabs(cos) + h * math.fabs(sin)) + + canvas_size = (canvas_h, canvas_w) + return canvas_size + + def sample_angle(self, max_angle): + angle = np.random.random_sample() * 2 * max_angle - max_angle + return angle + + def rotate_img(self, img, angle, canvas_size): + h, w = img.shape[:2] + rotation_matrix = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1) + rotation_matrix[0, 2] += int((canvas_size[1] - w) / 2) + rotation_matrix[1, 2] += int((canvas_size[0] - h) / 2) + + if self.pad_with_fixed_color: + target_img = cv2.warpAffine( + img, + rotation_matrix, (canvas_size[1], canvas_size[0]), + flags=cv2.INTER_NEAREST, + borderValue=self.pad_value) + else: + mask = np.zeros_like(img) + (h_ind, w_ind) = (np.random.randint(0, h * 7 // 8), + np.random.randint(0, w * 7 // 8)) + img_cut = img[h_ind:(h_ind + h // 9), w_ind:(w_ind + w // 9)] + img_cut = cv2.resize(img_cut, (canvas_size[1], canvas_size[0])) + + mask = cv2.warpAffine( + mask, + rotation_matrix, (canvas_size[1], canvas_size[0]), + borderValue=[1, 1, 1]) + target_img = cv2.warpAffine( + img, + rotation_matrix, (canvas_size[1], canvas_size[0]), + borderValue=[0, 0, 0]) + target_img = target_img + img_cut * mask + + return target_img + + def __call__(self, results): + if np.random.random_sample() < self.rotate_ratio: + image = results['image'] + polygons = results['polys'] + h, w = image.shape[:2] + + angle = self.sample_angle(self.max_angle) + canvas_size = self.cal_canvas_size((h, w), angle) + center_shift = (int((canvas_size[1] - w) / 2), int( + (canvas_size[0] - h) / 2)) + image = self.rotate_img(image, angle, canvas_size) + results['image'] = image + # rotate polygons + rotated_masks = [] + for mask in polygons: + rotated_mask = self.rotate((w / 2, h / 2), mask, angle, + center_shift) + rotated_masks.append(rotated_mask) + results['polys'] = np.array(rotated_masks) + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + return repr_str + + +class SquareResizePad: + def __init__(self, + target_size, + pad_ratio=0.6, + pad_with_fixed_color=False, + pad_value=(0, 0, 0), + **kwargs): + """Resize or pad images to be square shape. + + Args: + target_size (int): The target size of square shaped image. + pad_with_fixed_color (bool): The flag for whether to pad rotated + image with fixed value. If set to False, the rescales image will + be padded onto cropped image. + pad_value (tuple(int)): The color value for padding rotated image. + """ + assert isinstance(target_size, int) + assert isinstance(pad_ratio, float) + assert isinstance(pad_with_fixed_color, bool) + assert isinstance(pad_value, tuple) + + self.target_size = target_size + self.pad_ratio = pad_ratio + self.pad_with_fixed_color = pad_with_fixed_color + self.pad_value = pad_value + + def resize_img(self, img, keep_ratio=True): + h, w, _ = img.shape + if keep_ratio: + t_h = self.target_size if h >= w else int(h * self.target_size / w) + t_w = self.target_size if h <= w else int(w * self.target_size / h) + else: + t_h = t_w = self.target_size + img = cv2.resize(img, (t_w, t_h)) + return img, (t_h, t_w) + + def square_pad(self, img): + h, w = img.shape[:2] + if h == w: + return img, (0, 0) + pad_size = max(h, w) + if self.pad_with_fixed_color: + expand_img = np.ones((pad_size, pad_size, 3), dtype=np.uint8) + expand_img[:] = self.pad_value + else: + (h_ind, w_ind) = (np.random.randint(0, h * 7 // 8), + np.random.randint(0, w * 7 // 8)) + img_cut = img[h_ind:(h_ind + h // 9), w_ind:(w_ind + w // 9)] + expand_img = cv2.resize(img_cut, (pad_size, pad_size)) + if h > w: + y0, x0 = 0, (h - w) // 2 + else: + y0, x0 = (w - h) // 2, 0 + expand_img[y0:y0 + h, x0:x0 + w] = img + offset = (x0, y0) + + return expand_img, offset + + def square_pad_mask(self, points, offset): + x0, y0 = offset + pad_points = points.copy() + pad_points[::2] = pad_points[::2] + x0 + pad_points[1::2] = pad_points[1::2] + y0 + return pad_points + + def __call__(self, results): + image = results['image'] + polygons = results['polys'] + h, w = image.shape[:2] + + if np.random.random_sample() < self.pad_ratio: + image, out_size = self.resize_img(image, keep_ratio=True) + image, offset = self.square_pad(image) + else: + image, out_size = self.resize_img(image, keep_ratio=False) + offset = (0, 0) + results['image'] = image + try: + polygons[:, :, 0::2] = polygons[:, :, 0::2] * out_size[ + 1] / w + offset[0] + polygons[:, :, 1::2] = polygons[:, :, 1::2] * out_size[ + 0] / h + offset[1] + except: + pass + results['polys'] = polygons + + return results + + def __repr__(self): + repr_str = self.__class__.__name__ + return repr_str diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_targets.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..8c64276e26665d2779d35154bf9cd77edddad580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/fce_targets.py @@ -0,0 +1,666 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/datasets/pipelines/textdet_targets/fcenet_targets.py +""" + +import cv2 +import numpy as np +from numpy.fft import fft +from numpy.linalg import norm +import sys + +def vector_slope(vec): + assert len(vec) == 2 + return abs(vec[1] / (vec[0] + 1e-8)) + +class FCENetTargets: + """Generate the ground truth targets of FCENet: Fourier Contour Embedding + for Arbitrary-Shaped Text Detection. + + [https://arxiv.org/abs/2104.10442] + + Args: + fourier_degree (int): The maximum Fourier transform degree k. + resample_step (float): The step size for resampling the text center + line (TCL). It's better not to exceed half of the minimum width. + center_region_shrink_ratio (float): The shrink ratio of text center + region. + level_size_divisors (tuple(int)): The downsample ratio on each level. + level_proportion_range (tuple(tuple(int))): The range of text sizes + assigned to each level. + """ + + def __init__(self, + fourier_degree=5, + resample_step=4.0, + center_region_shrink_ratio=0.3, + level_size_divisors=(8, 16, 32), + level_proportion_range=((0, 0.25), (0.2, 0.65), (0.55, 1.0)), + orientation_thr=2.0, + **kwargs): + + super().__init__() + assert isinstance(level_size_divisors, tuple) + assert isinstance(level_proportion_range, tuple) + assert len(level_size_divisors) == len(level_proportion_range) + self.fourier_degree = fourier_degree + self.resample_step = resample_step + self.center_region_shrink_ratio = center_region_shrink_ratio + self.level_size_divisors = level_size_divisors + self.level_proportion_range = level_proportion_range + + self.orientation_thr = orientation_thr + + def vector_angle(self, vec1, vec2): + if vec1.ndim > 1: + unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8).reshape((-1, 1)) + else: + unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8) + if vec2.ndim > 1: + unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8).reshape((-1, 1)) + else: + unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8) + return np.arccos( + np.clip( + np.sum(unit_vec1 * unit_vec2, axis=-1), -1.0, 1.0)) + + def resample_line(self, line, n): + """Resample n points on a line. + + Args: + line (ndarray): The points composing a line. + n (int): The resampled points number. + + Returns: + resampled_line (ndarray): The points composing the resampled line. + """ + + assert line.ndim == 2 + assert line.shape[0] >= 2 + assert line.shape[1] == 2 + assert isinstance(n, int) + assert n > 0 + + length_list = [ + norm(line[i + 1] - line[i]) for i in range(len(line) - 1) + ] + total_length = sum(length_list) + length_cumsum = np.cumsum([0.0] + length_list) + delta_length = total_length / (float(n) + 1e-8) + + current_edge_ind = 0 + resampled_line = [line[0]] + + for i in range(1, n): + current_line_len = i * delta_length + + while current_edge_ind + 1 < len(length_cumsum) and current_line_len >= length_cumsum[current_edge_ind + 1]: + current_edge_ind += 1 + + current_edge_end_shift = current_line_len - length_cumsum[ + current_edge_ind] + + if current_edge_ind >= len(length_list): + break + end_shift_ratio = current_edge_end_shift / length_list[ + current_edge_ind] + current_point = line[current_edge_ind] + (line[current_edge_ind + 1] + - line[current_edge_ind] + ) * end_shift_ratio + resampled_line.append(current_point) + resampled_line.append(line[-1]) + resampled_line = np.array(resampled_line) + + return resampled_line + + def reorder_poly_edge(self, points): + """Get the respective points composing head edge, tail edge, top + sideline and bottom sideline. + + Args: + points (ndarray): The points composing a text polygon. + + Returns: + head_edge (ndarray): The two points composing the head edge of text + polygon. + tail_edge (ndarray): The two points composing the tail edge of text + polygon. + top_sideline (ndarray): The points composing top curved sideline of + text polygon. + bot_sideline (ndarray): The points composing bottom curved sideline + of text polygon. + """ + + assert points.ndim == 2 + assert points.shape[0] >= 4 + assert points.shape[1] == 2 + + head_inds, tail_inds = self.find_head_tail(points, self.orientation_thr) + head_edge, tail_edge = points[head_inds], points[tail_inds] + + pad_points = np.vstack([points, points]) + if tail_inds[1] < 1: + tail_inds[1] = len(points) + sideline1 = pad_points[head_inds[1]:tail_inds[1]] + sideline2 = pad_points[tail_inds[1]:(head_inds[1] + len(points))] + sideline_mean_shift = np.mean( + sideline1, axis=0) - np.mean( + sideline2, axis=0) + + if sideline_mean_shift[1] > 0: + top_sideline, bot_sideline = sideline2, sideline1 + else: + top_sideline, bot_sideline = sideline1, sideline2 + + return head_edge, tail_edge, top_sideline, bot_sideline + + def find_head_tail(self, points, orientation_thr): + """Find the head edge and tail edge of a text polygon. + + Args: + points (ndarray): The points composing a text polygon. + orientation_thr (float): The threshold for distinguishing between + head edge and tail edge among the horizontal and vertical edges + of a quadrangle. + + Returns: + head_inds (list): The indexes of two points composing head edge. + tail_inds (list): The indexes of two points composing tail edge. + """ + + assert points.ndim == 2 + assert points.shape[0] >= 4 + assert points.shape[1] == 2 + assert isinstance(orientation_thr, float) + + if len(points) > 4: + pad_points = np.vstack([points, points[0]]) + edge_vec = pad_points[1:] - pad_points[:-1] + + theta_sum = [] + adjacent_vec_theta = [] + for i, edge_vec1 in enumerate(edge_vec): + adjacent_ind = [x % len(edge_vec) for x in [i - 1, i + 1]] + adjacent_edge_vec = edge_vec[adjacent_ind] + temp_theta_sum = np.sum( + self.vector_angle(edge_vec1, adjacent_edge_vec)) + temp_adjacent_theta = self.vector_angle(adjacent_edge_vec[0], + adjacent_edge_vec[1]) + theta_sum.append(temp_theta_sum) + adjacent_vec_theta.append(temp_adjacent_theta) + theta_sum_score = np.array(theta_sum) / np.pi + adjacent_theta_score = np.array(adjacent_vec_theta) / np.pi + poly_center = np.mean(points, axis=0) + edge_dist = np.maximum( + norm( + pad_points[1:] - poly_center, axis=-1), + norm( + pad_points[:-1] - poly_center, axis=-1)) + dist_score = edge_dist / np.max(edge_dist) + position_score = np.zeros(len(edge_vec)) + score = 0.5 * theta_sum_score + 0.15 * adjacent_theta_score + score += 0.35 * dist_score + if len(points) % 2 == 0: + position_score[(len(score) // 2 - 1)] += 1 + position_score[-1] += 1 + score += 0.1 * position_score + pad_score = np.concatenate([score, score]) + score_matrix = np.zeros((len(score), len(score) - 3)) + x = np.arange(len(score) - 3) / float(len(score) - 4) + gaussian = 1. / (np.sqrt(2. * np.pi) * 0.5) * np.exp(-np.power( + (x - 0.5) / 0.5, 2.) / 2) + gaussian = gaussian / np.max(gaussian) + for i in range(len(score)): + score_matrix[i, :] = score[i] + pad_score[(i + 2):(i + len( + score) - 1)] * gaussian * 0.3 + + head_start, tail_increment = np.unravel_index(score_matrix.argmax(), + score_matrix.shape) + tail_start = (head_start + tail_increment + 2) % len(points) + head_end = (head_start + 1) % len(points) + tail_end = (tail_start + 1) % len(points) + + if head_end > tail_end: + head_start, tail_start = tail_start, head_start + head_end, tail_end = tail_end, head_end + head_inds = [head_start, head_end] + tail_inds = [tail_start, tail_end] + else: + if vector_slope(points[1] - points[0]) + vector_slope( + points[3] - points[2]) < vector_slope(points[ + 2] - points[1]) + vector_slope(points[0] - points[ + 3]): + horizontal_edge_inds = [[0, 1], [2, 3]] + vertical_edge_inds = [[3, 0], [1, 2]] + else: + horizontal_edge_inds = [[3, 0], [1, 2]] + vertical_edge_inds = [[0, 1], [2, 3]] + + vertical_len_sum = norm(points[vertical_edge_inds[0][0]] - points[ + vertical_edge_inds[0][1]]) + norm(points[vertical_edge_inds[1][ + 0]] - points[vertical_edge_inds[1][1]]) + horizontal_len_sum = norm(points[horizontal_edge_inds[0][ + 0]] - points[horizontal_edge_inds[0][1]]) + norm(points[ + horizontal_edge_inds[1][0]] - points[horizontal_edge_inds[1] + [1]]) + + if vertical_len_sum > horizontal_len_sum * orientation_thr: + head_inds = horizontal_edge_inds[0] + tail_inds = horizontal_edge_inds[1] + else: + head_inds = vertical_edge_inds[0] + tail_inds = vertical_edge_inds[1] + + return head_inds, tail_inds + + def resample_sidelines(self, sideline1, sideline2, resample_step): + """Resample two sidelines to be of the same points number according to + step size. + + Args: + sideline1 (ndarray): The points composing a sideline of a text + polygon. + sideline2 (ndarray): The points composing another sideline of a + text polygon. + resample_step (float): The resampled step size. + + Returns: + resampled_line1 (ndarray): The resampled line 1. + resampled_line2 (ndarray): The resampled line 2. + """ + + assert sideline1.ndim == sideline2.ndim == 2 + assert sideline1.shape[1] == sideline2.shape[1] == 2 + assert sideline1.shape[0] >= 2 + assert sideline2.shape[0] >= 2 + assert isinstance(resample_step, float) + + length1 = sum([ + norm(sideline1[i + 1] - sideline1[i]) + for i in range(len(sideline1) - 1) + ]) + length2 = sum([ + norm(sideline2[i + 1] - sideline2[i]) + for i in range(len(sideline2) - 1) + ]) + + total_length = (length1 + length2) / 2 + resample_point_num = max(int(float(total_length) / resample_step), 1) + + resampled_line1 = self.resample_line(sideline1, resample_point_num) + resampled_line2 = self.resample_line(sideline2, resample_point_num) + + return resampled_line1, resampled_line2 + + def generate_center_region_mask(self, img_size, text_polys): + """Generate text center region mask. + + Args: + img_size (tuple): The image size of (height, width). + text_polys (list[list[ndarray]]): The list of text polygons. + + Returns: + center_region_mask (ndarray): The text center region mask. + """ + + assert isinstance(img_size, tuple) + # assert check_argument.is_2dlist(text_polys) + + h, w = img_size + + center_region_mask = np.zeros((h, w), np.uint8) + + center_region_boxes = [] + for poly in text_polys: + # assert len(poly) == 1 + polygon_points = poly.reshape(-1, 2) + _, _, top_line, bot_line = self.reorder_poly_edge(polygon_points) + resampled_top_line, resampled_bot_line = self.resample_sidelines( + top_line, bot_line, self.resample_step) + resampled_bot_line = resampled_bot_line[::-1] + if len(resampled_top_line) != len(resampled_bot_line): + continue + center_line = (resampled_top_line + resampled_bot_line) / 2 + + line_head_shrink_len = norm(resampled_top_line[0] - + resampled_bot_line[0]) / 4.0 + line_tail_shrink_len = norm(resampled_top_line[-1] - + resampled_bot_line[-1]) / 4.0 + head_shrink_num = int(line_head_shrink_len // self.resample_step) + tail_shrink_num = int(line_tail_shrink_len // self.resample_step) + if len(center_line) > head_shrink_num + tail_shrink_num + 2: + center_line = center_line[head_shrink_num:len(center_line) - + tail_shrink_num] + resampled_top_line = resampled_top_line[head_shrink_num:len( + resampled_top_line) - tail_shrink_num] + resampled_bot_line = resampled_bot_line[head_shrink_num:len( + resampled_bot_line) - tail_shrink_num] + + for i in range(0, len(center_line) - 1): + tl = center_line[i] + (resampled_top_line[i] - center_line[i] + ) * self.center_region_shrink_ratio + tr = center_line[i + 1] + (resampled_top_line[i + 1] - + center_line[i + 1] + ) * self.center_region_shrink_ratio + br = center_line[i + 1] + (resampled_bot_line[i + 1] - + center_line[i + 1] + ) * self.center_region_shrink_ratio + bl = center_line[i] + (resampled_bot_line[i] - center_line[i] + ) * self.center_region_shrink_ratio + current_center_box = np.vstack([tl, tr, br, + bl]).astype(np.int32) + center_region_boxes.append(current_center_box) + + cv2.fillPoly(center_region_mask, center_region_boxes, 1) + return center_region_mask + + def resample_polygon(self, polygon, n=400): + """Resample one polygon with n points on its boundary. + + Args: + polygon (list[float]): The input polygon. + n (int): The number of resampled points. + Returns: + resampled_polygon (list[float]): The resampled polygon. + """ + length = [] + + for i in range(len(polygon)): + p1 = polygon[i] + if i == len(polygon) - 1: + p2 = polygon[0] + else: + p2 = polygon[i + 1] + length.append(((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5) + + total_length = sum(length) + n_on_each_line = (np.array(length) / (total_length + 1e-8)) * n + n_on_each_line = n_on_each_line.astype(np.int32) + new_polygon = [] + + for i in range(len(polygon)): + num = n_on_each_line[i] + p1 = polygon[i] + if i == len(polygon) - 1: + p2 = polygon[0] + else: + p2 = polygon[i + 1] + + if num == 0: + continue + + dxdy = (p2 - p1) / num + for j in range(num): + point = p1 + dxdy * j + new_polygon.append(point) + + return np.array(new_polygon) + + def normalize_polygon(self, polygon): + """Normalize one polygon so that its start point is at right most. + + Args: + polygon (list[float]): The origin polygon. + Returns: + new_polygon (lost[float]): The polygon with start point at right. + """ + temp_polygon = polygon - polygon.mean(axis=0) + x = np.abs(temp_polygon[:, 0]) + y = temp_polygon[:, 1] + index_x = np.argsort(x) + index_y = np.argmin(y[index_x[:8]]) + index = index_x[index_y] + new_polygon = np.concatenate([polygon[index:], polygon[:index]]) + return new_polygon + + def poly2fourier(self, polygon, fourier_degree): + """Perform Fourier transformation to generate Fourier coefficients ck + from polygon. + + Args: + polygon (ndarray): An input polygon. + fourier_degree (int): The maximum Fourier degree K. + Returns: + c (ndarray(complex)): Fourier coefficients. + """ + points = polygon[:, 0] + polygon[:, 1] * 1j + c_fft = fft(points) / len(points) + c = np.hstack((c_fft[-fourier_degree:], c_fft[:fourier_degree + 1])) + return c + + def clockwise(self, c, fourier_degree): + """Make sure the polygon reconstructed from Fourier coefficients c in + the clockwise direction. + + Args: + polygon (list[float]): The origin polygon. + Returns: + new_polygon (lost[float]): The polygon in clockwise point order. + """ + if np.abs(c[fourier_degree + 1]) > np.abs(c[fourier_degree - 1]): + return c + elif np.abs(c[fourier_degree + 1]) < np.abs(c[fourier_degree - 1]): + return c[::-1] + else: + if np.abs(c[fourier_degree + 2]) > np.abs(c[fourier_degree - 2]): + return c + else: + return c[::-1] + + def cal_fourier_signature(self, polygon, fourier_degree): + """Calculate Fourier signature from input polygon. + + Args: + polygon (ndarray): The input polygon. + fourier_degree (int): The maximum Fourier degree K. + Returns: + fourier_signature (ndarray): An array shaped (2k+1, 2) containing + real part and image part of 2k+1 Fourier coefficients. + """ + resampled_polygon = self.resample_polygon(polygon) + resampled_polygon = self.normalize_polygon(resampled_polygon) + + fourier_coeff = self.poly2fourier(resampled_polygon, fourier_degree) + fourier_coeff = self.clockwise(fourier_coeff, fourier_degree) + + real_part = np.real(fourier_coeff).reshape((-1, 1)) + image_part = np.imag(fourier_coeff).reshape((-1, 1)) + fourier_signature = np.hstack([real_part, image_part]) + + return fourier_signature + + def generate_fourier_maps(self, img_size, text_polys): + """Generate Fourier coefficient maps. + + Args: + img_size (tuple): The image size of (height, width). + text_polys (list[list[ndarray]]): The list of text polygons. + + Returns: + fourier_real_map (ndarray): The Fourier coefficient real part maps. + fourier_image_map (ndarray): The Fourier coefficient image part + maps. + """ + + assert isinstance(img_size, tuple) + + h, w = img_size + k = self.fourier_degree + real_map = np.zeros((k * 2 + 1, h, w), dtype=np.float32) + imag_map = np.zeros((k * 2 + 1, h, w), dtype=np.float32) + + for poly in text_polys: + mask = np.zeros((h, w), dtype=np.uint8) + polygon = np.array(poly).reshape((1, -1, 2)) + cv2.fillPoly(mask, polygon.astype(np.int32), 1) + fourier_coeff = self.cal_fourier_signature(polygon[0], k) + for i in range(-k, k + 1): + if i != 0: + real_map[i + k, :, :] = mask * fourier_coeff[i + k, 0] + ( + 1 - mask) * real_map[i + k, :, :] + imag_map[i + k, :, :] = mask * fourier_coeff[i + k, 1] + ( + 1 - mask) * imag_map[i + k, :, :] + else: + yx = np.argwhere(mask > 0.5) + k_ind = np.ones((len(yx)), dtype=np.int64) * k + y, x = yx[:, 0], yx[:, 1] + real_map[k_ind, y, x] = fourier_coeff[k, 0] - x + imag_map[k_ind, y, x] = fourier_coeff[k, 1] - y + + return real_map, imag_map + + def generate_text_region_mask(self, img_size, text_polys): + """Generate text center region mask and geometry attribute maps. + + Args: + img_size (tuple): The image size (height, width). + text_polys (list[list[ndarray]]): The list of text polygons. + + Returns: + text_region_mask (ndarray): The text region mask. + """ + + assert isinstance(img_size, tuple) + + h, w = img_size + text_region_mask = np.zeros((h, w), dtype=np.uint8) + + for poly in text_polys: + polygon = np.array(poly, dtype=np.int32).reshape((1, -1, 2)) + cv2.fillPoly(text_region_mask, polygon, 1) + + return text_region_mask + + def generate_effective_mask(self, mask_size: tuple, polygons_ignore): + """Generate effective mask by setting the ineffective regions to 0 and + effective regions to 1. + + Args: + mask_size (tuple): The mask size. + polygons_ignore (list[[ndarray]]: The list of ignored text + polygons. + + Returns: + mask (ndarray): The effective mask of (height, width). + """ + + mask = np.ones(mask_size, dtype=np.uint8) + + for poly in polygons_ignore: + instance = poly.reshape(-1, 2).astype(np.int32).reshape(1, -1, 2) + cv2.fillPoly(mask, instance, 0) + + return mask + + def generate_level_targets(self, img_size, text_polys, ignore_polys): + """Generate ground truth target on each level. + + Args: + img_size (list[int]): Shape of input image. + text_polys (list[list[ndarray]]): A list of ground truth polygons. + ignore_polys (list[list[ndarray]]): A list of ignored polygons. + Returns: + level_maps (list(ndarray)): A list of ground target on each level. + """ + h, w = img_size + lv_size_divs = self.level_size_divisors + lv_proportion_range = self.level_proportion_range + lv_text_polys = [[] for i in range(len(lv_size_divs))] + lv_ignore_polys = [[] for i in range(len(lv_size_divs))] + level_maps = [] + for poly in text_polys: + polygon = np.array(poly, dtype=np.int).reshape((1, -1, 2)) + _, _, box_w, box_h = cv2.boundingRect(polygon) + proportion = max(box_h, box_w) / (h + 1e-8) + + for ind, proportion_range in enumerate(lv_proportion_range): + if proportion_range[0] < proportion < proportion_range[1]: + lv_text_polys[ind].append(poly / lv_size_divs[ind]) + + for ignore_poly in ignore_polys: + polygon = np.array(ignore_poly, dtype=np.int).reshape((1, -1, 2)) + _, _, box_w, box_h = cv2.boundingRect(polygon) + proportion = max(box_h, box_w) / (h + 1e-8) + + for ind, proportion_range in enumerate(lv_proportion_range): + if proportion_range[0] < proportion < proportion_range[1]: + lv_ignore_polys[ind].append(ignore_poly / lv_size_divs[ind]) + + for ind, size_divisor in enumerate(lv_size_divs): + current_level_maps = [] + level_img_size = (h // size_divisor, w // size_divisor) + + text_region = self.generate_text_region_mask( + level_img_size, lv_text_polys[ind])[None] + current_level_maps.append(text_region) + + center_region = self.generate_center_region_mask( + level_img_size, lv_text_polys[ind])[None] + current_level_maps.append(center_region) + + effective_mask = self.generate_effective_mask( + level_img_size, lv_ignore_polys[ind])[None] + current_level_maps.append(effective_mask) + + fourier_real_map, fourier_image_maps = self.generate_fourier_maps( + level_img_size, lv_text_polys[ind]) + current_level_maps.append(fourier_real_map) + current_level_maps.append(fourier_image_maps) + + level_maps.append(np.concatenate(current_level_maps)) + + return level_maps + + def generate_targets(self, results): + """Generate the ground truth targets for FCENet. + + Args: + results (dict): The input result dictionary. + + Returns: + results (dict): The output result dictionary. + """ + + assert isinstance(results, dict) + image = results['image'] + polygons = results['polys'] + ignore_tags = results['ignore_tags'] + h, w, _ = image.shape + + polygon_masks = [] + polygon_masks_ignore = [] + for tag, polygon in zip(ignore_tags, polygons): + if tag is True: + polygon_masks_ignore.append(polygon) + else: + polygon_masks.append(polygon) + + level_maps = self.generate_level_targets((h, w), polygon_masks, + polygon_masks_ignore) + + mapping = { + 'p3_maps': level_maps[0], + 'p4_maps': level_maps[1], + 'p5_maps': level_maps[2] + } + for key, value in mapping.items(): + results[key] = value + + return results + + def __call__(self, results): + results = self.generate_targets(results) + return results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/iaa_augment.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/iaa_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..0aac7877c257f3e7532ca2806891775913d416b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/iaa_augment.py @@ -0,0 +1,105 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/iaa_augment.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import numpy as np +import imgaug +import imgaug.augmenters as iaa + + +class AugmenterBuilder(object): + def __init__(self): + pass + + def build(self, args, root=True): + if args is None or len(args) == 0: + return None + elif isinstance(args, list): + if root: + sequence = [self.build(value, root=False) for value in args] + return iaa.Sequential(sequence) + else: + return getattr(iaa, args[0])( + *[self.to_tuple_if_list(a) for a in args[1:]]) + elif isinstance(args, dict): + cls = getattr(iaa, args['type']) + return cls(**{ + k: self.to_tuple_if_list(v) + for k, v in args['args'].items() + }) + else: + raise RuntimeError('unknown augmenter arg: ' + str(args)) + + def to_tuple_if_list(self, obj): + if isinstance(obj, list): + return tuple(obj) + return obj + + +class IaaAugment(): + def __init__(self, augmenter_args=None, **kwargs): + if augmenter_args is None: + augmenter_args = [{ + 'type': 'Fliplr', + 'args': { + 'p': 0.5 + } + }, { + 'type': 'Affine', + 'args': { + 'rotate': [-10, 10] + } + }, { + 'type': 'Resize', + 'args': { + 'size': [0.5, 3] + } + }] + self.augmenter = AugmenterBuilder().build(augmenter_args) + + def __call__(self, data): + image = data['image'] + shape = image.shape + + if self.augmenter: + aug = self.augmenter.to_deterministic() + data['image'] = aug.augment_image(image) + data = self.may_augment_annotation(aug, data, shape) + return data + + def may_augment_annotation(self, aug, data, shape): + if aug is None: + return data + + line_polys = [] + for poly in data['polys']: + new_poly = self.may_augment_poly(aug, shape, poly) + line_polys.append(new_poly) + data['polys'] = np.array(line_polys) + return data + + def may_augment_poly(self, aug, img_shape, poly): + keypoints = [imgaug.Keypoint(p[0], p[1]) for p in poly] + keypoints = aug.augment_keypoints( + [imgaug.KeypointsOnImage( + keypoints, shape=img_shape)])[0].keypoints + poly = [(p.x, p.y) for p in keypoints] + return poly diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/label_ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/label_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..59cb9b8a253cf04244ebf83511ab412174487a53 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/label_ops.py @@ -0,0 +1,1397 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import copy +import numpy as np +import string +from shapely.geometry import LineString, Point, Polygon +import json +import copy +from random import sample + +from ppocr.utils.logging import get_logger +from ppocr.data.imaug.vqa.augment import order_by_tbyx + + +class ClsLabelEncode(object): + def __init__(self, label_list, **kwargs): + self.label_list = label_list + + def __call__(self, data): + label = data['label'] + if label not in self.label_list: + return None + label = self.label_list.index(label) + data['label'] = label + return data + + +class DetLabelEncode(object): + def __init__(self, **kwargs): + pass + + def __call__(self, data): + label = data['label'] + label = json.loads(label) + nBox = len(label) + boxes, txts, txt_tags = [], [], [] + for bno in range(0, nBox): + box = label[bno]['points'] + txt = label[bno]['transcription'] + boxes.append(box) + txts.append(txt) + if txt in ['*', '###']: + txt_tags.append(True) + else: + txt_tags.append(False) + if len(boxes) == 0: + return None + boxes = self.expand_points_num(boxes) + boxes = np.array(boxes, dtype=np.float32) + txt_tags = np.array(txt_tags, dtype=np.bool) + + data['polys'] = boxes + data['texts'] = txts + data['ignore_tags'] = txt_tags + return data + + def order_points_clockwise(self, pts): + rect = np.zeros((4, 2), dtype="float32") + s = pts.sum(axis=1) + rect[0] = pts[np.argmin(s)] + rect[2] = pts[np.argmax(s)] + tmp = np.delete(pts, (np.argmin(s), np.argmax(s)), axis=0) + diff = np.diff(np.array(tmp), axis=1) + rect[1] = tmp[np.argmin(diff)] + rect[3] = tmp[np.argmax(diff)] + return rect + + def expand_points_num(self, boxes): + max_points_num = 0 + for box in boxes: + if len(box) > max_points_num: + max_points_num = len(box) + ex_boxes = [] + for box in boxes: + ex_box = box + [box[-1]] * (max_points_num - len(box)) + ex_boxes.append(ex_box) + return ex_boxes + + +class BaseRecLabelEncode(object): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + lower=False): + + self.max_text_len = max_text_length + self.beg_str = "sos" + self.end_str = "eos" + self.lower = lower + + if character_dict_path is None: + logger = get_logger() + logger.warning( + "The character_dict_path is None, model can only recognize number and lower letters" + ) + self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz" + dict_character = list(self.character_str) + self.lower = True + else: + self.character_str = [] + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + self.character_str.append(line) + if use_space_char: + self.character_str.append(" ") + dict_character = list(self.character_str) + dict_character = self.add_special_char(dict_character) + self.dict = {} + for i, char in enumerate(dict_character): + self.dict[char] = i + self.character = dict_character + + def add_special_char(self, dict_character): + return dict_character + + def encode(self, text): + """convert text-label into text-index. + input: + text: text labels of each image. [batch_size] + + output: + text: concatenated text index for CTCLoss. + [sum(text_lengths)] = [text_index_0 + text_index_1 + ... + text_index_(n - 1)] + length: length of each text. [batch_size] + """ + if len(text) == 0 or len(text) > self.max_text_len: + return None + if self.lower: + text = text.lower() + text_list = [] + for char in text: + if char not in self.dict: + # logger = get_logger() + # logger.warning('{} is not in dict'.format(char)) + continue + text_list.append(self.dict[char]) + if len(text_list) == 0: + return None + return text_list + + +class CTCLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(CTCLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + data['length'] = np.array(len(text)) + text = text + [0] * (self.max_text_len - len(text)) + data['label'] = np.array(text) + + label = [0] * len(self.character) + for x in text: + label[x] += 1 + data['label_ace'] = np.array(label) + return data + + def add_special_char(self, dict_character): + dict_character = ['blank'] + dict_character + return dict_character + + +class E2ELabelEncodeTest(BaseRecLabelEncode): + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(E2ELabelEncodeTest, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def __call__(self, data): + import json + padnum = len(self.dict) + label = data['label'] + label = json.loads(label) + nBox = len(label) + boxes, txts, txt_tags = [], [], [] + for bno in range(0, nBox): + box = label[bno]['points'] + txt = label[bno]['transcription'] + boxes.append(box) + txts.append(txt) + if txt in ['*', '###']: + txt_tags.append(True) + else: + txt_tags.append(False) + boxes = np.array(boxes, dtype=np.float32) + txt_tags = np.array(txt_tags, dtype=np.bool) + data['polys'] = boxes + data['ignore_tags'] = txt_tags + temp_texts = [] + for text in txts: + text = text.lower() + text = self.encode(text) + if text is None: + return None + text = text + [padnum] * (self.max_text_len - len(text) + ) # use 36 to pad + temp_texts.append(text) + data['texts'] = np.array(temp_texts) + return data + + +class E2ELabelEncodeTrain(object): + def __init__(self, **kwargs): + pass + + def __call__(self, data): + import json + label = data['label'] + label = json.loads(label) + nBox = len(label) + boxes, txts, txt_tags = [], [], [] + for bno in range(0, nBox): + box = label[bno]['points'] + txt = label[bno]['transcription'] + boxes.append(box) + txts.append(txt) + if txt in ['*', '###']: + txt_tags.append(True) + else: + txt_tags.append(False) + boxes = np.array(boxes, dtype=np.float32) + txt_tags = np.array(txt_tags, dtype=np.bool) + + data['polys'] = boxes + data['texts'] = txts + data['ignore_tags'] = txt_tags + return data + + +class KieLabelEncode(object): + def __init__(self, + character_dict_path, + class_path, + norm=10, + directed=False, + **kwargs): + super(KieLabelEncode, self).__init__() + self.dict = dict({'': 0}) + self.label2classid_map = dict() + with open(character_dict_path, 'r', encoding='utf-8') as fr: + idx = 1 + for line in fr: + char = line.strip() + self.dict[char] = idx + idx += 1 + with open(class_path, "r") as fin: + lines = fin.readlines() + for idx, line in enumerate(lines): + line = line.strip("\n") + self.label2classid_map[line] = idx + self.norm = norm + self.directed = directed + + def compute_relation(self, boxes): + """Compute relation between every two boxes.""" + x1s, y1s = boxes[:, 0:1], boxes[:, 1:2] + x2s, y2s = boxes[:, 4:5], boxes[:, 5:6] + ws, hs = x2s - x1s + 1, np.maximum(y2s - y1s + 1, 1) + dxs = (x1s[:, 0][None] - x1s) / self.norm + dys = (y1s[:, 0][None] - y1s) / self.norm + xhhs, xwhs = hs[:, 0][None] / hs, ws[:, 0][None] / hs + whs = ws / hs + np.zeros_like(xhhs) + relations = np.stack([dxs, dys, whs, xhhs, xwhs], -1) + bboxes = np.concatenate([x1s, y1s, x2s, y2s], -1).astype(np.float32) + return relations, bboxes + + def pad_text_indices(self, text_inds): + """Pad text index to same length.""" + max_len = 300 + recoder_len = max([len(text_ind) for text_ind in text_inds]) + padded_text_inds = -np.ones((len(text_inds), max_len), np.int32) + for idx, text_ind in enumerate(text_inds): + padded_text_inds[idx, :len(text_ind)] = np.array(text_ind) + return padded_text_inds, recoder_len + + def list_to_numpy(self, ann_infos): + """Convert bboxes, relations, texts and labels to ndarray.""" + boxes, text_inds = ann_infos['points'], ann_infos['text_inds'] + boxes = np.array(boxes, np.int32) + relations, bboxes = self.compute_relation(boxes) + + labels = ann_infos.get('labels', None) + if labels is not None: + labels = np.array(labels, np.int32) + edges = ann_infos.get('edges', None) + if edges is not None: + labels = labels[:, None] + edges = np.array(edges) + edges = (edges[:, None] == edges[None, :]).astype(np.int32) + if self.directed: + edges = (edges & labels == 1).astype(np.int32) + np.fill_diagonal(edges, -1) + labels = np.concatenate([labels, edges], -1) + padded_text_inds, recoder_len = self.pad_text_indices(text_inds) + max_num = 300 + temp_bboxes = np.zeros([max_num, 4]) + h, _ = bboxes.shape + temp_bboxes[:h, :] = bboxes + + temp_relations = np.zeros([max_num, max_num, 5]) + temp_relations[:h, :h, :] = relations + + temp_padded_text_inds = np.zeros([max_num, max_num]) + temp_padded_text_inds[:h, :] = padded_text_inds + + temp_labels = np.zeros([max_num, max_num]) + temp_labels[:h, :h + 1] = labels + + tag = np.array([h, recoder_len]) + return dict( + image=ann_infos['image'], + points=temp_bboxes, + relations=temp_relations, + texts=temp_padded_text_inds, + labels=temp_labels, + tag=tag) + + def convert_canonical(self, points_x, points_y): + + assert len(points_x) == 4 + assert len(points_y) == 4 + + points = [Point(points_x[i], points_y[i]) for i in range(4)] + + polygon = Polygon([(p.x, p.y) for p in points]) + min_x, min_y, _, _ = polygon.bounds + points_to_lefttop = [ + LineString([points[i], Point(min_x, min_y)]) for i in range(4) + ] + distances = np.array([line.length for line in points_to_lefttop]) + sort_dist_idx = np.argsort(distances) + lefttop_idx = sort_dist_idx[0] + + if lefttop_idx == 0: + point_orders = [0, 1, 2, 3] + elif lefttop_idx == 1: + point_orders = [1, 2, 3, 0] + elif lefttop_idx == 2: + point_orders = [2, 3, 0, 1] + else: + point_orders = [3, 0, 1, 2] + + sorted_points_x = [points_x[i] for i in point_orders] + sorted_points_y = [points_y[j] for j in point_orders] + + return sorted_points_x, sorted_points_y + + def sort_vertex(self, points_x, points_y): + + assert len(points_x) == 4 + assert len(points_y) == 4 + + x = np.array(points_x) + y = np.array(points_y) + center_x = np.sum(x) * 0.25 + center_y = np.sum(y) * 0.25 + + x_arr = np.array(x - center_x) + y_arr = np.array(y - center_y) + + angle = np.arctan2(y_arr, x_arr) * 180.0 / np.pi + sort_idx = np.argsort(angle) + + sorted_points_x, sorted_points_y = [], [] + for i in range(4): + sorted_points_x.append(points_x[sort_idx[i]]) + sorted_points_y.append(points_y[sort_idx[i]]) + + return self.convert_canonical(sorted_points_x, sorted_points_y) + + def __call__(self, data): + import json + label = data['label'] + annotations = json.loads(label) + boxes, texts, text_inds, labels, edges = [], [], [], [], [] + for ann in annotations: + box = ann['points'] + x_list = [box[i][0] for i in range(4)] + y_list = [box[i][1] for i in range(4)] + sorted_x_list, sorted_y_list = self.sort_vertex(x_list, y_list) + sorted_box = [] + for x, y in zip(sorted_x_list, sorted_y_list): + sorted_box.append(x) + sorted_box.append(y) + boxes.append(sorted_box) + text = ann['transcription'] + texts.append(ann['transcription']) + text_ind = [self.dict[c] for c in text if c in self.dict] + text_inds.append(text_ind) + if 'label' in ann.keys(): + labels.append(self.label2classid_map[ann['label']]) + elif 'key_cls' in ann.keys(): + labels.append(ann['key_cls']) + else: + raise ValueError( + "Cannot found 'key_cls' in ann.keys(), please check your training annotation." + ) + edges.append(ann.get('edge', 0)) + ann_infos = dict( + image=data['image'], + points=boxes, + texts=texts, + text_inds=text_inds, + edges=edges, + labels=labels) + + return self.list_to_numpy(ann_infos) + + +class AttnLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(AttnLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def add_special_char(self, dict_character): + self.beg_str = "sos" + self.end_str = "eos" + dict_character = [self.beg_str] + dict_character + [self.end_str] + return dict_character + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len: + return None + data['length'] = np.array(len(text)) + text = [0] + text + [len(self.character) - 1] + [0] * (self.max_text_len + - len(text) - 2) + data['label'] = np.array(text) + return data + + def get_ignored_tokens(self): + beg_idx = self.get_beg_end_flag_idx("beg") + end_idx = self.get_beg_end_flag_idx("end") + return [beg_idx, end_idx] + + def get_beg_end_flag_idx(self, beg_or_end): + if beg_or_end == "beg": + idx = np.array(self.dict[self.beg_str]) + elif beg_or_end == "end": + idx = np.array(self.dict[self.end_str]) + else: + assert False, "Unsupport type %s in get_beg_end_flag_idx" \ + % beg_or_end + return idx + + +class SEEDLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(SEEDLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def add_special_char(self, dict_character): + self.padding = "padding" + self.end_str = "eos" + self.unknown = "unknown" + dict_character = dict_character + [ + self.end_str, self.padding, self.unknown + ] + return dict_character + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len: + return None + data['length'] = np.array(len(text)) + 1 # conclude eos + text = text + [len(self.character) - 3] + [len(self.character) - 2] * ( + self.max_text_len - len(text) - 1) + data['label'] = np.array(text) + return data + + +class SRNLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length=25, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(SRNLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def add_special_char(self, dict_character): + dict_character = dict_character + [self.beg_str, self.end_str] + return dict_character + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + char_num = len(self.character) + if text is None: + return None + if len(text) > self.max_text_len: + return None + data['length'] = np.array(len(text)) + text = text + [char_num - 1] * (self.max_text_len - len(text)) + data['label'] = np.array(text) + return data + + def get_ignored_tokens(self): + beg_idx = self.get_beg_end_flag_idx("beg") + end_idx = self.get_beg_end_flag_idx("end") + return [beg_idx, end_idx] + + def get_beg_end_flag_idx(self, beg_or_end): + if beg_or_end == "beg": + idx = np.array(self.dict[self.beg_str]) + elif beg_or_end == "end": + idx = np.array(self.dict[self.end_str]) + else: + assert False, "Unsupport type %s in get_beg_end_flag_idx" \ + % beg_or_end + return idx + + +class TableLabelEncode(AttnLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path, + replace_empty_cell_token=False, + merge_no_span_structure=False, + learn_empty_box=False, + loc_reg_num=4, + **kwargs): + self.max_text_len = max_text_length + self.lower = False + self.learn_empty_box = learn_empty_box + self.merge_no_span_structure = merge_no_span_structure + self.replace_empty_cell_token = replace_empty_cell_token + + dict_character = [] + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + dict_character.append(line) + + if self.merge_no_span_structure: + if "" not in dict_character: + dict_character.append("") + if "" in dict_character: + dict_character.remove("") + + dict_character = self.add_special_char(dict_character) + self.dict = {} + for i, char in enumerate(dict_character): + self.dict[char] = i + self.idx2char = {v: k for k, v in self.dict.items()} + + self.character = dict_character + self.loc_reg_num = loc_reg_num + self.pad_idx = self.dict[self.beg_str] + self.start_idx = self.dict[self.beg_str] + self.end_idx = self.dict[self.end_str] + + self.td_token = ['', '', ''] + self.empty_bbox_token_dict = { + "[]": '', + "[' ']": '', + "['', ' ', '']": '', + "['\\u2028', '\\u2028']": '', + "['', ' ', '']": '', + "['', '']": '', + "['', ' ', '']": '', + "['', '', '', '']": '', + "['', '', ' ', '', '']": '', + "['', '']": '', + "['', ' ', '\\u2028', ' ', '\\u2028', ' ', '']": + '', + } + + @property + def _max_text_len(self): + return self.max_text_len + 2 + + def __call__(self, data): + cells = data['cells'] + structure = data['structure'] + if self.merge_no_span_structure: + structure = self._merge_no_span_structure(structure) + if self.replace_empty_cell_token: + structure = self._replace_empty_cell_token(structure, cells) + # remove empty token and add " " to span token + new_structure = [] + for token in structure: + if token != '': + if 'span' in token and token[0] != ' ': + token = ' ' + token + new_structure.append(token) + # encode structure + structure = self.encode(new_structure) + if structure is None: + return None + + structure = [self.start_idx] + structure + [self.end_idx + ] # add sos abd eos + structure = structure + [self.pad_idx] * (self._max_text_len - + len(structure)) # pad + structure = np.array(structure) + data['structure'] = structure + + if len(structure) > self._max_text_len: + return None + + # encode box + bboxes = np.zeros( + (self._max_text_len, self.loc_reg_num), dtype=np.float32) + bbox_masks = np.zeros((self._max_text_len, 1), dtype=np.float32) + + bbox_idx = 0 + + for i, token in enumerate(structure): + if self.idx2char[token] in self.td_token: + if 'bbox' in cells[bbox_idx] and len(cells[bbox_idx][ + 'tokens']) > 0: + bbox = cells[bbox_idx]['bbox'].copy() + bbox = np.array(bbox, dtype=np.float32).reshape(-1) + bboxes[i] = bbox + bbox_masks[i] = 1.0 + if self.learn_empty_box: + bbox_masks[i] = 1.0 + bbox_idx += 1 + data['bboxes'] = bboxes + data['bbox_masks'] = bbox_masks + return data + + def _merge_no_span_structure(self, structure): + """ + This code is refer from: + https://github.com/JiaquanYe/TableMASTER-mmocr/blob/master/table_recognition/data_preprocess.py + """ + new_structure = [] + i = 0 + while i < len(structure): + token = structure[i] + if token == '': + token = '' + i += 1 + new_structure.append(token) + i += 1 + return new_structure + + def _replace_empty_cell_token(self, token_list, cells): + """ + This fun code is refer from: + https://github.com/JiaquanYe/TableMASTER-mmocr/blob/master/table_recognition/data_preprocess.py + """ + + bbox_idx = 0 + add_empty_bbox_token_list = [] + for token in token_list: + if token in ['', '']: + if 'bbox' not in cells[bbox_idx].keys(): + content = str(cells[bbox_idx]['tokens']) + token = self.empty_bbox_token_dict[content] + add_empty_bbox_token_list.append(token) + bbox_idx += 1 + else: + add_empty_bbox_token_list.append(token) + return add_empty_bbox_token_list + + +class TableMasterLabelEncode(TableLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path, + replace_empty_cell_token=False, + merge_no_span_structure=False, + learn_empty_box=False, + loc_reg_num=4, + **kwargs): + super(TableMasterLabelEncode, self).__init__( + max_text_length, character_dict_path, replace_empty_cell_token, + merge_no_span_structure, learn_empty_box, loc_reg_num, **kwargs) + self.pad_idx = self.dict[self.pad_str] + self.unknown_idx = self.dict[self.unknown_str] + + @property + def _max_text_len(self): + return self.max_text_len + + def add_special_char(self, dict_character): + self.beg_str = '' + self.end_str = '' + self.unknown_str = '' + self.pad_str = '' + dict_character = dict_character + dict_character = dict_character + [ + self.unknown_str, self.beg_str, self.end_str, self.pad_str + ] + return dict_character + + +class TableBoxEncode(object): + def __init__(self, in_box_format='xyxy', out_box_format='xyxy', **kwargs): + assert out_box_format in ['xywh', 'xyxy', 'xyxyxyxy'] + self.in_box_format = in_box_format + self.out_box_format = out_box_format + + def __call__(self, data): + img_height, img_width = data['image'].shape[:2] + bboxes = data['bboxes'] + if self.in_box_format != self.out_box_format: + if self.out_box_format == 'xywh': + if self.in_box_format == 'xyxyxyxy': + bboxes = self.xyxyxyxy2xywh(bboxes) + elif self.in_box_format == 'xyxy': + bboxes = self.xyxy2xywh(bboxes) + + bboxes[:, 0::2] /= img_width + bboxes[:, 1::2] /= img_height + data['bboxes'] = bboxes + return data + + def xyxyxyxy2xywh(self, boxes): + new_bboxes = np.zeros([len(bboxes), 4]) + new_bboxes[:, 0] = bboxes[:, 0::2].min() # x1 + new_bboxes[:, 1] = bboxes[:, 1::2].min() # y1 + new_bboxes[:, 2] = bboxes[:, 0::2].max() - new_bboxes[:, 0] # w + new_bboxes[:, 3] = bboxes[:, 1::2].max() - new_bboxes[:, 1] # h + return new_bboxes + + def xyxy2xywh(self, bboxes): + new_bboxes = np.empty_like(bboxes) + new_bboxes[:, 0] = (bboxes[:, 0] + bboxes[:, 2]) / 2 # x center + new_bboxes[:, 1] = (bboxes[:, 1] + bboxes[:, 3]) / 2 # y center + new_bboxes[:, 2] = bboxes[:, 2] - bboxes[:, 0] # width + new_bboxes[:, 3] = bboxes[:, 3] - bboxes[:, 1] # height + return new_bboxes + + +class SARLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(SARLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def add_special_char(self, dict_character): + beg_end_str = "" + unknown_str = "" + padding_str = "" + dict_character = dict_character + [unknown_str] + self.unknown_idx = len(dict_character) - 1 + dict_character = dict_character + [beg_end_str] + self.start_idx = len(dict_character) - 1 + self.end_idx = len(dict_character) - 1 + dict_character = dict_character + [padding_str] + self.padding_idx = len(dict_character) - 1 + + return dict_character + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len - 1: + return None + data['length'] = np.array(len(text)) + target = [self.start_idx] + text + [self.end_idx] + padded_text = [self.padding_idx for _ in range(self.max_text_len)] + + padded_text[:len(target)] = target + data['label'] = np.array(padded_text) + return data + + def get_ignored_tokens(self): + return [self.padding_idx] + + +class PRENLabelEncode(BaseRecLabelEncode): + def __init__(self, + max_text_length, + character_dict_path, + use_space_char=False, + **kwargs): + super(PRENLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def add_special_char(self, dict_character): + padding_str = '' # 0 + end_str = '' # 1 + unknown_str = '' # 2 + + dict_character = [padding_str, end_str, unknown_str] + dict_character + self.padding_idx = 0 + self.end_idx = 1 + self.unknown_idx = 2 + + return dict_character + + def encode(self, text): + if len(text) == 0 or len(text) >= self.max_text_len: + return None + if self.lower: + text = text.lower() + text_list = [] + for char in text: + if char not in self.dict: + text_list.append(self.unknown_idx) + else: + text_list.append(self.dict[char]) + text_list.append(self.end_idx) + if len(text_list) < self.max_text_len: + text_list += [self.padding_idx] * ( + self.max_text_len - len(text_list)) + return text_list + + def __call__(self, data): + text = data['label'] + encoded_text = self.encode(text) + if encoded_text is None: + return None + data['label'] = np.array(encoded_text) + return data + + +class VQATokenLabelEncode(object): + """ + Label encode for NLP VQA methods + """ + + def __init__(self, + class_path, + contains_re=False, + add_special_ids=False, + algorithm='LayoutXLM', + use_textline_bbox_info=True, + order_method=None, + infer_mode=False, + ocr_engine=None, + **kwargs): + super(VQATokenLabelEncode, self).__init__() + from paddlenlp.transformers import LayoutXLMTokenizer, LayoutLMTokenizer, LayoutLMv2Tokenizer + from ppocr.utils.utility import load_vqa_bio_label_maps + tokenizer_dict = { + 'LayoutXLM': { + 'class': LayoutXLMTokenizer, + 'pretrained_model': 'layoutxlm-base-uncased' + }, + 'LayoutLM': { + 'class': LayoutLMTokenizer, + 'pretrained_model': 'layoutlm-base-uncased' + }, + 'LayoutLMv2': { + 'class': LayoutLMv2Tokenizer, + 'pretrained_model': 'layoutlmv2-base-uncased' + } + } + self.contains_re = contains_re + tokenizer_config = tokenizer_dict[algorithm] + self.tokenizer = tokenizer_config['class'].from_pretrained( + tokenizer_config['pretrained_model']) + self.label2id_map, id2label_map = load_vqa_bio_label_maps(class_path) + self.add_special_ids = add_special_ids + self.infer_mode = infer_mode + self.ocr_engine = ocr_engine + self.use_textline_bbox_info = use_textline_bbox_info + self.order_method = order_method + assert self.order_method in [None, "tb-yx"] + + def split_bbox(self, bbox, text, tokenizer): + words = text.split() + token_bboxes = [] + curr_word_idx = 0 + x1, y1, x2, y2 = bbox + unit_w = (x2 - x1) / len(text) + for idx, word in enumerate(words): + curr_w = len(word) * unit_w + word_bbox = [x1, y1, x1 + curr_w, y2] + token_bboxes.extend([word_bbox] * len(tokenizer.tokenize(word))) + x1 += (len(word) + 1) * unit_w + return token_bboxes + + def filter_empty_contents(self, ocr_info): + """ + find out the empty texts and remove the links + """ + new_ocr_info = [] + empty_index = [] + for idx, info in enumerate(ocr_info): + if len(info["transcription"]) > 0: + new_ocr_info.append(copy.deepcopy(info)) + else: + empty_index.append(info["id"]) + + for idx, info in enumerate(new_ocr_info): + new_link = [] + for link in info["linking"]: + if link[0] in empty_index or link[1] in empty_index: + continue + new_link.append(link) + new_ocr_info[idx]["linking"] = new_link + return new_ocr_info + + def __call__(self, data): + # load bbox and label info + ocr_info = self._load_ocr_info(data) + + for idx in range(len(ocr_info)): + if "bbox" not in ocr_info[idx]: + ocr_info[idx]["bbox"] = self.trans_poly_to_bbox(ocr_info[idx][ + "points"]) + + if self.order_method == "tb-yx": + ocr_info = order_by_tbyx(ocr_info) + + # for re + train_re = self.contains_re and not self.infer_mode + if train_re: + ocr_info = self.filter_empty_contents(ocr_info) + + height, width, _ = data['image'].shape + + words_list = [] + bbox_list = [] + input_ids_list = [] + token_type_ids_list = [] + segment_offset_id = [] + gt_label_list = [] + + entities = [] + + if train_re: + relations = [] + id2label = {} + entity_id_to_index_map = {} + empty_entity = set() + + data['ocr_info'] = copy.deepcopy(ocr_info) + + for info in ocr_info: + text = info["transcription"] + if len(text) <= 0: + continue + if train_re: + # for re + if len(text) == 0: + empty_entity.add(info["id"]) + continue + id2label[info["id"]] = info["label"] + relations.extend([tuple(sorted(l)) for l in info["linking"]]) + # smooth_box + info["bbox"] = self.trans_poly_to_bbox(info["points"]) + + encode_res = self.tokenizer.encode( + text, + pad_to_max_seq_len=False, + return_attention_mask=True, + return_token_type_ids=True) + + if not self.add_special_ids: + # TODO: use tok.all_special_ids to remove + encode_res["input_ids"] = encode_res["input_ids"][1:-1] + encode_res["token_type_ids"] = encode_res["token_type_ids"][1: + -1] + encode_res["attention_mask"] = encode_res["attention_mask"][1: + -1] + + if self.use_textline_bbox_info: + bbox = [info["bbox"]] * len(encode_res["input_ids"]) + else: + bbox = self.split_bbox(info["bbox"], info["transcription"], + self.tokenizer) + if len(bbox) <= 0: + continue + bbox = self._smooth_box(bbox, height, width) + if self.add_special_ids: + bbox.insert(0, [0, 0, 0, 0]) + bbox.append([0, 0, 0, 0]) + + # parse label + if not self.infer_mode: + label = info['label'] + gt_label = self._parse_label(label, encode_res) + + # construct entities for re + if train_re: + if gt_label[0] != self.label2id_map["O"]: + entity_id_to_index_map[info["id"]] = len(entities) + label = label.upper() + entities.append({ + "start": len(input_ids_list), + "end": + len(input_ids_list) + len(encode_res["input_ids"]), + "label": label.upper(), + }) + else: + entities.append({ + "start": len(input_ids_list), + "end": len(input_ids_list) + len(encode_res["input_ids"]), + "label": 'O', + }) + input_ids_list.extend(encode_res["input_ids"]) + token_type_ids_list.extend(encode_res["token_type_ids"]) + bbox_list.extend(bbox) + words_list.append(text) + segment_offset_id.append(len(input_ids_list)) + if not self.infer_mode: + gt_label_list.extend(gt_label) + + data['input_ids'] = input_ids_list + data['token_type_ids'] = token_type_ids_list + data['bbox'] = bbox_list + data['attention_mask'] = [1] * len(input_ids_list) + data['labels'] = gt_label_list + data['segment_offset_id'] = segment_offset_id + data['tokenizer_params'] = dict( + padding_side=self.tokenizer.padding_side, + pad_token_type_id=self.tokenizer.pad_token_type_id, + pad_token_id=self.tokenizer.pad_token_id) + data['entities'] = entities + + if train_re: + data['relations'] = relations + data['id2label'] = id2label + data['empty_entity'] = empty_entity + data['entity_id_to_index_map'] = entity_id_to_index_map + return data + + def trans_poly_to_bbox(self, poly): + x1 = int(np.min([p[0] for p in poly])) + x2 = int(np.max([p[0] for p in poly])) + y1 = int(np.min([p[1] for p in poly])) + y2 = int(np.max([p[1] for p in poly])) + return [x1, y1, x2, y2] + + def _load_ocr_info(self, data): + if self.infer_mode: + ocr_result = self.ocr_engine.ocr(data['image'], cls=False) + ocr_info = [] + for res in ocr_result: + ocr_info.append({ + "transcription": res[1][0], + "bbox": self.trans_poly_to_bbox(res[0]), + "points": res[0], + }) + return ocr_info + else: + info = data['label'] + # read text info + info_dict = json.loads(info) + return info_dict + + def _smooth_box(self, bboxes, height, width): + bboxes = np.array(bboxes) + bboxes[:, 0] = bboxes[:, 0] * 1000 / width + bboxes[:, 2] = bboxes[:, 2] * 1000 / width + bboxes[:, 1] = bboxes[:, 1] * 1000 / height + bboxes[:, 3] = bboxes[:, 3] * 1000 / height + bboxes = bboxes.astype("int64").tolist() + return bboxes + + def _parse_label(self, label, encode_res): + gt_label = [] + if label.lower() in ["other", "others", "ignore"]: + gt_label.extend([0] * len(encode_res["input_ids"])) + else: + gt_label.append(self.label2id_map[("b-" + label).upper()]) + gt_label.extend([self.label2id_map[("i-" + label).upper()]] * + (len(encode_res["input_ids"]) - 1)) + return gt_label + + +class MultiLabelEncode(BaseRecLabelEncode): + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(MultiLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + self.ctc_encode = CTCLabelEncode(max_text_length, character_dict_path, + use_space_char, **kwargs) + self.sar_encode = SARLabelEncode(max_text_length, character_dict_path, + use_space_char, **kwargs) + + def __call__(self, data): + data_ctc = copy.deepcopy(data) + data_sar = copy.deepcopy(data) + data_out = dict() + data_out['img_path'] = data.get('img_path', None) + data_out['image'] = data['image'] + ctc = self.ctc_encode.__call__(data_ctc) + sar = self.sar_encode.__call__(data_sar) + if ctc is None or sar is None: + return None + data_out['label_ctc'] = ctc['label'] + data_out['label_sar'] = sar['label'] + data_out['length'] = ctc['length'] + return data_out + + +class NRTRLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + + super(NRTRLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len - 1: + return None + data['length'] = np.array(len(text)) + text.insert(0, 2) + text.append(3) + text = text + [0] * (self.max_text_len - len(text)) + data['label'] = np.array(text) + return data + + def add_special_char(self, dict_character): + dict_character = ['blank', '', '', ''] + dict_character + return dict_character + + +class ViTSTRLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + ignore_index=0, + **kwargs): + + super(ViTSTRLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + self.ignore_index = ignore_index + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len: + return None + data['length'] = np.array(len(text)) + text.insert(0, self.ignore_index) + text.append(1) + text = text + [self.ignore_index] * (self.max_text_len + 2 - len(text)) + data['label'] = np.array(text) + return data + + def add_special_char(self, dict_character): + dict_character = ['', ''] + dict_character + return dict_character + + +class ABINetLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + ignore_index=100, + **kwargs): + + super(ABINetLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + self.ignore_index = ignore_index + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) >= self.max_text_len: + return None + data['length'] = np.array(len(text)) + text.append(0) + text = text + [self.ignore_index] * (self.max_text_len + 1 - len(text)) + data['label'] = np.array(text) + return data + + def add_special_char(self, dict_character): + dict_character = [''] + dict_character + return dict_character + + +class SRLabelEncode(BaseRecLabelEncode): + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + **kwargs): + super(SRLabelEncode, self).__init__(max_text_length, + character_dict_path, use_space_char) + self.dic = {} + with open(character_dict_path, 'r') as fin: + for line in fin.readlines(): + line = line.strip() + character, sequence = line.split() + self.dic[character] = sequence + english_stroke_alphabet = '0123456789' + self.english_stroke_dict = {} + for index in range(len(english_stroke_alphabet)): + self.english_stroke_dict[english_stroke_alphabet[index]] = index + + def encode(self, label): + stroke_sequence = '' + for character in label: + if character not in self.dic: + continue + else: + stroke_sequence += self.dic[character] + stroke_sequence += '0' + label = stroke_sequence + + length = len(label) + + input_tensor = np.zeros(self.max_text_len).astype("int64") + for j in range(length - 1): + input_tensor[j + 1] = self.english_stroke_dict[label[j]] + + return length, input_tensor + + def __call__(self, data): + text = data['label'] + length, input_tensor = self.encode(text) + + data["length"] = length + data["input_tensor"] = input_tensor + if text is None: + return None + return data + + +class SPINLabelEncode(AttnLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + lower=True, + **kwargs): + super(SPINLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char) + self.lower = lower + + def add_special_char(self, dict_character): + self.beg_str = "sos" + self.end_str = "eos" + dict_character = [self.beg_str] + [self.end_str] + dict_character + return dict_character + + def __call__(self, data): + text = data['label'] + text = self.encode(text) + if text is None: + return None + if len(text) > self.max_text_len: + return None + data['length'] = np.array(len(text)) + target = [0] + text + [1] + padded_text = [0 for _ in range(self.max_text_len + 2)] + + padded_text[:len(target)] = target + data['label'] = np.array(padded_text) + return data + + +class VLLabelEncode(BaseRecLabelEncode): + """ Convert between text-label and text-index """ + + def __init__(self, + max_text_length, + character_dict_path=None, + use_space_char=False, + lower=True, + **kwargs): + super(VLLabelEncode, self).__init__( + max_text_length, character_dict_path, use_space_char, lower) + self.character = self.character[10:] + self.character[ + 1:10] + [self.character[0]] + self.dict = {} + for i, char in enumerate(self.character): + self.dict[char] = i + + def __call__(self, data): + text = data['label'] # original string + # generate occluded text + len_str = len(text) + if len_str <= 0: + return None + change_num = 1 + order = list(range(len_str)) + change_id = sample(order, change_num)[0] + label_sub = text[change_id] + if change_id == (len_str - 1): + label_res = text[:change_id] + elif change_id == 0: + label_res = text[1:] + else: + label_res = text[:change_id] + text[change_id + 1:] + + data['label_res'] = label_res # remaining string + data['label_sub'] = label_sub # occluded character + data['label_id'] = change_id # character index + # encode label + text = self.encode(text) + if text is None: + return None + text = [i + 1 for i in text] + data['length'] = np.array(len(text)) + text = text + [0] * (self.max_text_len - len(text)) + data['label'] = np.array(text) + label_res = self.encode(label_res) + label_sub = self.encode(label_sub) + if label_res is None: + label_res = [] + else: + label_res = [i + 1 for i in label_res] + if label_sub is None: + label_sub = [] + else: + label_sub = [i + 1 for i in label_sub] + data['length_res'] = np.array(len(label_res)) + data['length_sub'] = np.array(len(label_sub)) + label_res = label_res + [0] * (self.max_text_len - len(label_res)) + label_sub = label_sub + [0] * (self.max_text_len - len(label_sub)) + data['label_res'] = np.array(label_res) + data['label_sub'] = np.array(label_sub) + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_border_map.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_border_map.py new file mode 100644 index 0000000000000000000000000000000000000000..abab38368db2de84e54b060598fc509a65219296 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_border_map.py @@ -0,0 +1,173 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/make_border_map.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import numpy as np +import cv2 + +np.seterr(divide='ignore', invalid='ignore') +import pyclipper +from shapely.geometry import Polygon +import sys +import warnings + +warnings.simplefilter("ignore") + +__all__ = ['MakeBorderMap'] + + +class MakeBorderMap(object): + def __init__(self, + shrink_ratio=0.4, + thresh_min=0.3, + thresh_max=0.7, + **kwargs): + self.shrink_ratio = shrink_ratio + self.thresh_min = thresh_min + self.thresh_max = thresh_max + + def __call__(self, data): + + img = data['image'] + text_polys = data['polys'] + ignore_tags = data['ignore_tags'] + + canvas = np.zeros(img.shape[:2], dtype=np.float32) + mask = np.zeros(img.shape[:2], dtype=np.float32) + + for i in range(len(text_polys)): + if ignore_tags[i]: + continue + self.draw_border_map(text_polys[i], canvas, mask=mask) + canvas = canvas * (self.thresh_max - self.thresh_min) + self.thresh_min + + data['threshold_map'] = canvas + data['threshold_mask'] = mask + return data + + def draw_border_map(self, polygon, canvas, mask): + polygon = np.array(polygon) + assert polygon.ndim == 2 + assert polygon.shape[1] == 2 + + polygon_shape = Polygon(polygon) + if polygon_shape.area <= 0: + return + distance = polygon_shape.area * ( + 1 - np.power(self.shrink_ratio, 2)) / polygon_shape.length + subject = [tuple(l) for l in polygon] + padding = pyclipper.PyclipperOffset() + padding.AddPath(subject, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) + + padded_polygon = np.array(padding.Execute(distance)[0]) + cv2.fillPoly(mask, [padded_polygon.astype(np.int32)], 1.0) + + xmin = padded_polygon[:, 0].min() + xmax = padded_polygon[:, 0].max() + ymin = padded_polygon[:, 1].min() + ymax = padded_polygon[:, 1].max() + width = xmax - xmin + 1 + height = ymax - ymin + 1 + + polygon[:, 0] = polygon[:, 0] - xmin + polygon[:, 1] = polygon[:, 1] - ymin + + xs = np.broadcast_to( + np.linspace( + 0, width - 1, num=width).reshape(1, width), (height, width)) + ys = np.broadcast_to( + np.linspace( + 0, height - 1, num=height).reshape(height, 1), (height, width)) + + distance_map = np.zeros( + (polygon.shape[0], height, width), dtype=np.float32) + for i in range(polygon.shape[0]): + j = (i + 1) % polygon.shape[0] + absolute_distance = self._distance(xs, ys, polygon[i], polygon[j]) + distance_map[i] = np.clip(absolute_distance / distance, 0, 1) + distance_map = distance_map.min(axis=0) + + xmin_valid = min(max(0, xmin), canvas.shape[1] - 1) + xmax_valid = min(max(0, xmax), canvas.shape[1] - 1) + ymin_valid = min(max(0, ymin), canvas.shape[0] - 1) + ymax_valid = min(max(0, ymax), canvas.shape[0] - 1) + canvas[ymin_valid:ymax_valid + 1, xmin_valid:xmax_valid + 1] = np.fmax( + 1 - distance_map[ymin_valid - ymin:ymax_valid - ymax + height, + xmin_valid - xmin:xmax_valid - xmax + width], + canvas[ymin_valid:ymax_valid + 1, xmin_valid:xmax_valid + 1]) + + def _distance(self, xs, ys, point_1, point_2): + ''' + compute the distance from point to a line + ys: coordinates in the first axis + xs: coordinates in the second axis + point_1, point_2: (x, y), the end of the line + ''' + height, width = xs.shape[:2] + square_distance_1 = np.square(xs - point_1[0]) + np.square(ys - point_1[ + 1]) + square_distance_2 = np.square(xs - point_2[0]) + np.square(ys - point_2[ + 1]) + square_distance = np.square(point_1[0] - point_2[0]) + np.square( + point_1[1] - point_2[1]) + + cosin = (square_distance - square_distance_1 - square_distance_2) / ( + 2 * np.sqrt(square_distance_1 * square_distance_2)) + square_sin = 1 - np.square(cosin) + square_sin = np.nan_to_num(square_sin) + result = np.sqrt(square_distance_1 * square_distance_2 * square_sin / + square_distance) + + result[cosin < + 0] = np.sqrt(np.fmin(square_distance_1, square_distance_2))[cosin + < 0] + # self.extend_line(point_1, point_2, result) + return result + + def extend_line(self, point_1, point_2, result, shrink_ratio): + ex_point_1 = (int( + round(point_1[0] + (point_1[0] - point_2[0]) * (1 + shrink_ratio))), + int( + round(point_1[1] + (point_1[1] - point_2[1]) * ( + 1 + shrink_ratio)))) + cv2.line( + result, + tuple(ex_point_1), + tuple(point_1), + 4096.0, + 1, + lineType=cv2.LINE_AA, + shift=0) + ex_point_2 = (int( + round(point_2[0] + (point_2[0] - point_1[0]) * (1 + shrink_ratio))), + int( + round(point_2[1] + (point_2[1] - point_1[1]) * ( + 1 + shrink_ratio)))) + cv2.line( + result, + tuple(ex_point_2), + tuple(point_2), + 4096.0, + 1, + lineType=cv2.LINE_AA, + shift=0) + return ex_point_1, ex_point_2 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_pse_gt.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_pse_gt.py new file mode 100644 index 0000000000000000000000000000000000000000..255d076bde848d53f3b2fb04e80594872f4ae8c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_pse_gt.py @@ -0,0 +1,106 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import cv2 +import numpy as np +import pyclipper +from shapely.geometry import Polygon + +__all__ = ['MakePseGt'] + + +class MakePseGt(object): + def __init__(self, kernel_num=7, size=640, min_shrink_ratio=0.4, **kwargs): + self.kernel_num = kernel_num + self.min_shrink_ratio = min_shrink_ratio + self.size = size + + def __call__(self, data): + + image = data['image'] + text_polys = data['polys'] + ignore_tags = data['ignore_tags'] + + h, w, _ = image.shape + short_edge = min(h, w) + if short_edge < self.size: + # keep short_size >= self.size + scale = self.size / short_edge + image = cv2.resize(image, dsize=None, fx=scale, fy=scale) + text_polys *= scale + + gt_kernels = [] + for i in range(1, self.kernel_num + 1): + # s1->sn, from big to small + rate = 1.0 - (1.0 - self.min_shrink_ratio) / (self.kernel_num - 1 + ) * i + text_kernel, ignore_tags = self.generate_kernel( + image.shape[0:2], rate, text_polys, ignore_tags) + gt_kernels.append(text_kernel) + + training_mask = np.ones(image.shape[0:2], dtype='uint8') + for i in range(text_polys.shape[0]): + if ignore_tags[i]: + cv2.fillPoly(training_mask, + text_polys[i].astype(np.int32)[np.newaxis, :, :], + 0) + + gt_kernels = np.array(gt_kernels) + gt_kernels[gt_kernels > 0] = 1 + + data['image'] = image + data['polys'] = text_polys + data['gt_kernels'] = gt_kernels[0:] + data['gt_text'] = gt_kernels[0] + data['mask'] = training_mask.astype('float32') + return data + + def generate_kernel(self, + img_size, + shrink_ratio, + text_polys, + ignore_tags=None): + """ + Refer to part of the code: + https://github.com/open-mmlab/mmocr/blob/main/mmocr/datasets/pipelines/textdet_targets/base_textdet_targets.py + """ + + h, w = img_size + text_kernel = np.zeros((h, w), dtype=np.float32) + for i, poly in enumerate(text_polys): + polygon = Polygon(poly) + distance = polygon.area * (1 - shrink_ratio * shrink_ratio) / ( + polygon.length + 1e-6) + subject = [tuple(l) for l in poly] + pco = pyclipper.PyclipperOffset() + pco.AddPath(subject, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) + shrinked = np.array(pco.Execute(-distance)) + + if len(shrinked) == 0 or shrinked.size == 0: + if ignore_tags is not None: + ignore_tags[i] = True + continue + try: + shrinked = np.array(shrinked[0]).reshape(-1, 2) + except: + if ignore_tags is not None: + ignore_tags[i] = True + continue + cv2.fillPoly(text_kernel, [shrinked.astype(np.int32)], i + 1) + return text_kernel, ignore_tags diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_shrink_map.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_shrink_map.py new file mode 100644 index 0000000000000000000000000000000000000000..6c65c20e5621f91a5b1fba549b059c92923fca6f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/make_shrink_map.py @@ -0,0 +1,123 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/make_shrink_map.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import numpy as np +import cv2 +from shapely.geometry import Polygon +import pyclipper + +__all__ = ['MakeShrinkMap'] + + +class MakeShrinkMap(object): + r''' + Making binary mask from detection data with ICDAR format. + Typically following the process of class `MakeICDARData`. + ''' + + def __init__(self, min_text_size=8, shrink_ratio=0.4, **kwargs): + self.min_text_size = min_text_size + self.shrink_ratio = shrink_ratio + + def __call__(self, data): + image = data['image'] + text_polys = data['polys'] + ignore_tags = data['ignore_tags'] + + h, w = image.shape[:2] + text_polys, ignore_tags = self.validate_polygons(text_polys, + ignore_tags, h, w) + gt = np.zeros((h, w), dtype=np.float32) + mask = np.ones((h, w), dtype=np.float32) + for i in range(len(text_polys)): + polygon = text_polys[i] + height = max(polygon[:, 1]) - min(polygon[:, 1]) + width = max(polygon[:, 0]) - min(polygon[:, 0]) + if ignore_tags[i] or min(height, width) < self.min_text_size: + cv2.fillPoly(mask, + polygon.astype(np.int32)[np.newaxis, :, :], 0) + ignore_tags[i] = True + else: + polygon_shape = Polygon(polygon) + subject = [tuple(l) for l in polygon] + padding = pyclipper.PyclipperOffset() + padding.AddPath(subject, pyclipper.JT_ROUND, + pyclipper.ET_CLOSEDPOLYGON) + shrinked = [] + + # Increase the shrink ratio every time we get multiple polygon returned back + possible_ratios = np.arange(self.shrink_ratio, 1, + self.shrink_ratio) + np.append(possible_ratios, 1) + # print(possible_ratios) + for ratio in possible_ratios: + # print(f"Change shrink ratio to {ratio}") + distance = polygon_shape.area * ( + 1 - np.power(ratio, 2)) / polygon_shape.length + shrinked = padding.Execute(-distance) + if len(shrinked) == 1: + break + + if shrinked == []: + cv2.fillPoly(mask, + polygon.astype(np.int32)[np.newaxis, :, :], 0) + ignore_tags[i] = True + continue + + for each_shirnk in shrinked: + shirnk = np.array(each_shirnk).reshape(-1, 2) + cv2.fillPoly(gt, [shirnk.astype(np.int32)], 1) + + data['shrink_map'] = gt + data['shrink_mask'] = mask + return data + + def validate_polygons(self, polygons, ignore_tags, h, w): + ''' + polygons (numpy.array, required): of shape (num_instances, num_points, 2) + ''' + if len(polygons) == 0: + return polygons, ignore_tags + assert len(polygons) == len(ignore_tags) + for polygon in polygons: + polygon[:, 0] = np.clip(polygon[:, 0], 0, w - 1) + polygon[:, 1] = np.clip(polygon[:, 1], 0, h - 1) + + for i in range(len(polygons)): + area = self.polygon_area(polygons[i]) + if abs(area) < 1: + ignore_tags[i] = True + if area > 0: + polygons[i] = polygons[i][::-1, :] + return polygons, ignore_tags + + def polygon_area(self, polygon): + """ + compute polygon area + """ + area = 0 + q = polygon[-1] + for p in polygon: + area += p[0] * q[1] - p[1] * q[0] + q = p + return area / 2.0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/operators.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..5e84b1aac9c54d8a8283468af6826ca917ba0384 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/operators.py @@ -0,0 +1,500 @@ +""" +# 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. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import sys +import six +import cv2 +import numpy as np +import math +from PIL import Image + + +class DecodeImage(object): + """ decode image """ + + def __init__(self, + img_mode='RGB', + channel_first=False, + ignore_orientation=False, + **kwargs): + self.img_mode = img_mode + self.channel_first = channel_first + self.ignore_orientation = ignore_orientation + + def __call__(self, data): + img = data['image'] + if six.PY2: + assert type(img) is str and len( + img) > 0, "invalid input 'img' in DecodeImage" + else: + assert type(img) is bytes and len( + img) > 0, "invalid input 'img' in DecodeImage" + img = np.frombuffer(img, dtype='uint8') + if self.ignore_orientation: + img = cv2.imdecode(img, cv2.IMREAD_IGNORE_ORIENTATION | + cv2.IMREAD_COLOR) + else: + img = cv2.imdecode(img, 1) + if img is None: + return None + if self.img_mode == 'GRAY': + img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) + elif self.img_mode == 'RGB': + assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape) + img = img[:, :, ::-1] + + if self.channel_first: + img = img.transpose((2, 0, 1)) + + data['image'] = img + return data + + +class NormalizeImage(object): + """ normalize image such as substract mean, divide std + """ + + def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs): + if isinstance(scale, str): + scale = eval(scale) + self.scale = np.float32(scale if scale is not None else 1.0 / 255.0) + mean = mean if mean is not None else [0.485, 0.456, 0.406] + std = std if std is not None else [0.229, 0.224, 0.225] + + shape = (3, 1, 1) if order == 'chw' else (1, 1, 3) + self.mean = np.array(mean).reshape(shape).astype('float32') + self.std = np.array(std).reshape(shape).astype('float32') + + def __call__(self, data): + img = data['image'] + from PIL import Image + if isinstance(img, Image.Image): + img = np.array(img) + assert isinstance(img, + np.ndarray), "invalid input 'img' in NormalizeImage" + data['image'] = ( + img.astype('float32') * self.scale - self.mean) / self.std + return data + + +class ToCHWImage(object): + """ convert hwc image to chw image + """ + + def __init__(self, **kwargs): + pass + + def __call__(self, data): + img = data['image'] + from PIL import Image + if isinstance(img, Image.Image): + img = np.array(img) + data['image'] = img.transpose((2, 0, 1)) + return data + + +class Fasttext(object): + def __init__(self, path="None", **kwargs): + import fasttext + self.fast_model = fasttext.load_model(path) + + def __call__(self, data): + label = data['label'] + fast_label = self.fast_model[label] + data['fast_label'] = fast_label + return data + + +class KeepKeys(object): + def __init__(self, keep_keys, **kwargs): + self.keep_keys = keep_keys + + def __call__(self, data): + data_list = [] + for key in self.keep_keys: + data_list.append(data[key]) + return data_list + + +class Pad(object): + def __init__(self, size=None, size_div=32, **kwargs): + if size is not None and not isinstance(size, (int, list, tuple)): + raise TypeError("Type of target_size is invalid. Now is {}".format( + type(size))) + if isinstance(size, int): + size = [size, size] + self.size = size + self.size_div = size_div + + def __call__(self, data): + + img = data['image'] + img_h, img_w = img.shape[0], img.shape[1] + if self.size: + resize_h2, resize_w2 = self.size + assert ( + img_h < resize_h2 and img_w < resize_w2 + ), '(h, w) of target size should be greater than (img_h, img_w)' + else: + resize_h2 = max( + int(math.ceil(img.shape[0] / self.size_div) * self.size_div), + self.size_div) + resize_w2 = max( + int(math.ceil(img.shape[1] / self.size_div) * self.size_div), + self.size_div) + img = cv2.copyMakeBorder( + img, + 0, + resize_h2 - img_h, + 0, + resize_w2 - img_w, + cv2.BORDER_CONSTANT, + value=0) + data['image'] = img + return data + + +class Resize(object): + def __init__(self, size=(640, 640), **kwargs): + self.size = size + + def resize_image(self, img): + resize_h, resize_w = self.size + ori_h, ori_w = img.shape[:2] # (h, w, c) + ratio_h = float(resize_h) / ori_h + ratio_w = float(resize_w) / ori_w + img = cv2.resize(img, (int(resize_w), int(resize_h))) + return img, [ratio_h, ratio_w] + + def __call__(self, data): + img = data['image'] + if 'polys' in data: + text_polys = data['polys'] + + img_resize, [ratio_h, ratio_w] = self.resize_image(img) + if 'polys' in data: + new_boxes = [] + for box in text_polys: + new_box = [] + for cord in box: + new_box.append([cord[0] * ratio_w, cord[1] * ratio_h]) + new_boxes.append(new_box) + data['polys'] = np.array(new_boxes, dtype=np.float32) + data['image'] = img_resize + return data + + +class DetResizeForTest(object): + def __init__(self, **kwargs): + super(DetResizeForTest, self).__init__() + self.resize_type = 0 + self.keep_ratio = False + if 'image_shape' in kwargs: + self.image_shape = kwargs['image_shape'] + self.resize_type = 1 + if 'keep_ratio' in kwargs: + self.keep_ratio = kwargs['keep_ratio'] + elif 'limit_side_len' in kwargs: + self.limit_side_len = kwargs['limit_side_len'] + self.limit_type = kwargs.get('limit_type', 'min') + elif 'resize_long' in kwargs: + self.resize_type = 2 + self.resize_long = kwargs.get('resize_long', 960) + else: + self.limit_side_len = 736 + self.limit_type = 'min' + + def __call__(self, data): + img = data['image'] + src_h, src_w, _ = img.shape + if sum([src_h, src_w]) < 64: + img = self.image_padding(img) + + if self.resize_type == 0: + # img, shape = self.resize_image_type0(img) + img, [ratio_h, ratio_w] = self.resize_image_type0(img) + elif self.resize_type == 2: + img, [ratio_h, ratio_w] = self.resize_image_type2(img) + else: + # img, shape = self.resize_image_type1(img) + img, [ratio_h, ratio_w] = self.resize_image_type1(img) + data['image'] = img + data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w]) + return data + + def image_padding(self, im, value=0): + h, w, c = im.shape + im_pad = np.zeros((max(32, h), max(32, w), c), np.uint8) + value + im_pad[:h, :w, :] = im + return im_pad + + def resize_image_type1(self, img): + resize_h, resize_w = self.image_shape + ori_h, ori_w = img.shape[:2] # (h, w, c) + if self.keep_ratio is True: + resize_w = ori_w * resize_h / ori_h + N = math.ceil(resize_w / 32) + resize_w = N * 32 + ratio_h = float(resize_h) / ori_h + ratio_w = float(resize_w) / ori_w + img = cv2.resize(img, (int(resize_w), int(resize_h))) + # return img, np.array([ori_h, ori_w]) + return img, [ratio_h, ratio_w] + + def resize_image_type0(self, img): + """ + resize image to a size multiple of 32 which is required by the network + args: + img(array): array with shape [h, w, c] + return(tuple): + img, (ratio_h, ratio_w) + """ + limit_side_len = self.limit_side_len + h, w, c = img.shape + + # limit the max side + if self.limit_type == 'max': + if max(h, w) > limit_side_len: + if h > w: + ratio = float(limit_side_len) / h + else: + ratio = float(limit_side_len) / w + else: + ratio = 1. + elif self.limit_type == 'min': + if min(h, w) < limit_side_len: + if h < w: + ratio = float(limit_side_len) / h + else: + ratio = float(limit_side_len) / w + else: + ratio = 1. + elif self.limit_type == 'resize_long': + ratio = float(limit_side_len) / max(h, w) + else: + raise Exception('not support limit type, image ') + resize_h = int(h * ratio) + resize_w = int(w * ratio) + + resize_h = max(int(round(resize_h / 32) * 32), 32) + resize_w = max(int(round(resize_w / 32) * 32), 32) + + try: + if int(resize_w) <= 0 or int(resize_h) <= 0: + return None, (None, None) + img = cv2.resize(img, (int(resize_w), int(resize_h))) + except: + print(img.shape, resize_w, resize_h) + sys.exit(0) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + return img, [ratio_h, ratio_w] + + def resize_image_type2(self, img): + h, w, _ = img.shape + + resize_w = w + resize_h = h + + if resize_h > resize_w: + ratio = float(self.resize_long) / resize_h + else: + ratio = float(self.resize_long) / resize_w + + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + img = cv2.resize(img, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + + return img, [ratio_h, ratio_w] + + +class E2EResizeForTest(object): + def __init__(self, **kwargs): + super(E2EResizeForTest, self).__init__() + self.max_side_len = kwargs['max_side_len'] + self.valid_set = kwargs['valid_set'] + + def __call__(self, data): + img = data['image'] + src_h, src_w, _ = img.shape + if self.valid_set == 'totaltext': + im_resized, [ratio_h, ratio_w] = self.resize_image_for_totaltext( + img, max_side_len=self.max_side_len) + else: + im_resized, (ratio_h, ratio_w) = self.resize_image( + img, max_side_len=self.max_side_len) + data['image'] = im_resized + data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w]) + return data + + def resize_image_for_totaltext(self, im, max_side_len=512): + + h, w, _ = im.shape + resize_w = w + resize_h = h + ratio = 1.25 + if h * ratio > max_side_len: + ratio = float(max_side_len) / resize_h + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(im, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + return im, (ratio_h, ratio_w) + + def resize_image(self, im, max_side_len=512): + """ + resize image to a size multiple of max_stride which is required by the network + :param im: the resized image + :param max_side_len: limit of max image size to avoid out of memory in gpu + :return: the resized image and the resize ratio + """ + h, w, _ = im.shape + + resize_w = w + resize_h = h + + # Fix the longer side + if resize_h > resize_w: + ratio = float(max_side_len) / resize_h + else: + ratio = float(max_side_len) / resize_w + + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(im, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + + return im, (ratio_h, ratio_w) + + +class KieResize(object): + def __init__(self, **kwargs): + super(KieResize, self).__init__() + self.max_side, self.min_side = kwargs['img_scale'][0], kwargs[ + 'img_scale'][1] + + def __call__(self, data): + img = data['image'] + points = data['points'] + src_h, src_w, _ = img.shape + im_resized, scale_factor, [ratio_h, ratio_w + ], [new_h, new_w] = self.resize_image(img) + resize_points = self.resize_boxes(img, points, scale_factor) + data['ori_image'] = img + data['ori_boxes'] = points + data['points'] = resize_points + data['image'] = im_resized + data['shape'] = np.array([new_h, new_w]) + return data + + def resize_image(self, img): + norm_img = np.zeros([1024, 1024, 3], dtype='float32') + scale = [512, 1024] + h, w = img.shape[:2] + max_long_edge = max(scale) + max_short_edge = min(scale) + scale_factor = min(max_long_edge / max(h, w), + max_short_edge / min(h, w)) + resize_w, resize_h = int(w * float(scale_factor) + 0.5), int(h * float( + scale_factor) + 0.5) + max_stride = 32 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(img, (resize_w, resize_h)) + new_h, new_w = im.shape[:2] + w_scale = new_w / w + h_scale = new_h / h + scale_factor = np.array( + [w_scale, h_scale, w_scale, h_scale], dtype=np.float32) + norm_img[:new_h, :new_w, :] = im + return norm_img, scale_factor, [h_scale, w_scale], [new_h, new_w] + + def resize_boxes(self, im, points, scale_factor): + points = points * scale_factor + img_shape = im.shape[:2] + points[:, 0::2] = np.clip(points[:, 0::2], 0, img_shape[1]) + points[:, 1::2] = np.clip(points[:, 1::2], 0, img_shape[0]) + return points + + +class SRResize(object): + def __init__(self, + imgH=32, + imgW=128, + down_sample_scale=4, + keep_ratio=False, + min_ratio=1, + mask=False, + infer_mode=False, + **kwargs): + self.imgH = imgH + self.imgW = imgW + self.keep_ratio = keep_ratio + self.min_ratio = min_ratio + self.down_sample_scale = down_sample_scale + self.mask = mask + self.infer_mode = infer_mode + + def __call__(self, data): + imgH = self.imgH + imgW = self.imgW + images_lr = data["image_lr"] + transform2 = ResizeNormalize( + (imgW // self.down_sample_scale, imgH // self.down_sample_scale)) + images_lr = transform2(images_lr) + data["img_lr"] = images_lr + if self.infer_mode: + return data + + images_HR = data["image_hr"] + label_strs = data["label"] + transform = ResizeNormalize((imgW, imgH)) + images_HR = transform(images_HR) + data["img_hr"] = images_HR + return data + + +class ResizeNormalize(object): + def __init__(self, size, interpolation=Image.BICUBIC): + self.size = size + self.interpolation = interpolation + + def __call__(self, img): + img = img.resize(self.size, self.interpolation) + img_numpy = np.array(img).astype("float32") + img_numpy = img_numpy.transpose((2, 0, 1)) / 255 + return img_numpy diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/pg_process.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/pg_process.py new file mode 100644 index 0000000000000000000000000000000000000000..53031064c019ddce00c7546f898ac67a7f0459f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/pg_process.py @@ -0,0 +1,906 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +import cv2 +import numpy as np + +__all__ = ['PGProcessTrain'] + + +class PGProcessTrain(object): + def __init__(self, + character_dict_path, + max_text_length, + max_text_nums, + tcl_len, + batch_size=14, + min_crop_size=24, + min_text_size=4, + max_text_size=512, + **kwargs): + self.tcl_len = tcl_len + self.max_text_length = max_text_length + self.max_text_nums = max_text_nums + self.batch_size = batch_size + self.min_crop_size = min_crop_size + self.min_text_size = min_text_size + self.max_text_size = max_text_size + self.Lexicon_Table = self.get_dict(character_dict_path) + self.pad_num = len(self.Lexicon_Table) + self.img_id = 0 + + def get_dict(self, character_dict_path): + character_str = "" + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + character_str += line + dict_character = list(character_str) + return dict_character + + def quad_area(self, poly): + """ + compute area of a polygon + :param poly: + :return: + """ + edge = [(poly[1][0] - poly[0][0]) * (poly[1][1] + poly[0][1]), + (poly[2][0] - poly[1][0]) * (poly[2][1] + poly[1][1]), + (poly[3][0] - poly[2][0]) * (poly[3][1] + poly[2][1]), + (poly[0][0] - poly[3][0]) * (poly[0][1] + poly[3][1])] + return np.sum(edge) / 2. + + def gen_quad_from_poly(self, poly): + """ + Generate min area quad from poly. + """ + point_num = poly.shape[0] + min_area_quad = np.zeros((4, 2), dtype=np.float32) + rect = cv2.minAreaRect(poly.astype( + np.int32)) # (center (x,y), (width, height), angle of rotation) + box = np.array(cv2.boxPoints(rect)) + + first_point_idx = 0 + min_dist = 1e4 + for i in range(4): + dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \ + np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \ + np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \ + np.linalg.norm(box[(i + 3) % 4] - poly[-1]) + if dist < min_dist: + min_dist = dist + first_point_idx = i + for i in range(4): + min_area_quad[i] = box[(first_point_idx + i) % 4] + + return min_area_quad + + def check_and_validate_polys(self, polys, tags, im_size): + """ + check so that the text poly is in the same direction, + and also filter some invalid polygons + :param polys: + :param tags: + :return: + """ + (h, w) = im_size + if polys.shape[0] == 0: + return polys, np.array([]), np.array([]) + polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w - 1) + polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h - 1) + + validated_polys = [] + validated_tags = [] + hv_tags = [] + for poly, tag in zip(polys, tags): + quad = self.gen_quad_from_poly(poly) + p_area = self.quad_area(quad) + if abs(p_area) < 1: + print('invalid poly') + continue + if p_area > 0: + if tag == False: + print('poly in wrong direction') + tag = True # reversed cases should be ignore + poly = poly[(0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, + 1), :] + quad = quad[(0, 3, 2, 1), :] + + len_w = np.linalg.norm(quad[0] - quad[1]) + np.linalg.norm(quad[3] - + quad[2]) + len_h = np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - + quad[2]) + hv_tag = 1 + + if len_w * 2.0 < len_h: + hv_tag = 0 + + validated_polys.append(poly) + validated_tags.append(tag) + hv_tags.append(hv_tag) + return np.array(validated_polys), np.array(validated_tags), np.array( + hv_tags) + + def crop_area(self, + im, + polys, + tags, + hv_tags, + txts, + crop_background=False, + max_tries=25): + """ + make random crop from the input image + :param im: + :param polys: [b,4,2] + :param tags: + :param crop_background: + :param max_tries: 50 -> 25 + :return: + """ + h, w, _ = im.shape + pad_h = h // 10 + pad_w = w // 10 + h_array = np.zeros((h + pad_h * 2), dtype=np.int32) + w_array = np.zeros((w + pad_w * 2), dtype=np.int32) + for poly in polys: + poly = np.round(poly, decimals=0).astype(np.int32) + minx = np.min(poly[:, 0]) + maxx = np.max(poly[:, 0]) + w_array[minx + pad_w:maxx + pad_w] = 1 + miny = np.min(poly[:, 1]) + maxy = np.max(poly[:, 1]) + h_array[miny + pad_h:maxy + pad_h] = 1 + # ensure the cropped area not across a text + h_axis = np.where(h_array == 0)[0] + w_axis = np.where(w_array == 0)[0] + if len(h_axis) == 0 or len(w_axis) == 0: + return im, polys, tags, hv_tags, txts + for i in range(max_tries): + xx = np.random.choice(w_axis, size=2) + xmin = np.min(xx) - pad_w + xmax = np.max(xx) - pad_w + xmin = np.clip(xmin, 0, w - 1) + xmax = np.clip(xmax, 0, w - 1) + yy = np.random.choice(h_axis, size=2) + ymin = np.min(yy) - pad_h + ymax = np.max(yy) - pad_h + ymin = np.clip(ymin, 0, h - 1) + ymax = np.clip(ymax, 0, h - 1) + if xmax - xmin < self.min_crop_size or \ + ymax - ymin < self.min_crop_size: + continue + if polys.shape[0] != 0: + poly_axis_in_area = (polys[:, :, 0] >= xmin) & (polys[:, :, 0] <= xmax) \ + & (polys[:, :, 1] >= ymin) & (polys[:, :, 1] <= ymax) + selected_polys = np.where( + np.sum(poly_axis_in_area, axis=1) == 4)[0] + else: + selected_polys = [] + if len(selected_polys) == 0: + # no text in this area + if crop_background: + txts_tmp = [] + for selected_poly in selected_polys: + txts_tmp.append(txts[selected_poly]) + txts = txts_tmp + return im[ymin: ymax + 1, xmin: xmax + 1, :], \ + polys[selected_polys], tags[selected_polys], hv_tags[selected_polys], txts + else: + continue + im = im[ymin:ymax + 1, xmin:xmax + 1, :] + polys = polys[selected_polys] + tags = tags[selected_polys] + hv_tags = hv_tags[selected_polys] + txts_tmp = [] + for selected_poly in selected_polys: + txts_tmp.append(txts[selected_poly]) + txts = txts_tmp + polys[:, :, 0] -= xmin + polys[:, :, 1] -= ymin + return im, polys, tags, hv_tags, txts + + return im, polys, tags, hv_tags, txts + + def fit_and_gather_tcl_points_v2(self, + min_area_quad, + poly, + max_h, + max_w, + fixed_point_num=64, + img_id=0, + reference_height=3): + """ + Find the center point of poly as key_points, then fit and gather. + """ + key_point_xys = [] + point_num = poly.shape[0] + for idx in range(point_num // 2): + center_point = (poly[idx] + poly[point_num - 1 - idx]) / 2.0 + key_point_xys.append(center_point) + + tmp_image = np.zeros( + shape=( + max_h, + max_w, ), dtype='float32') + cv2.polylines(tmp_image, [np.array(key_point_xys).astype('int32')], + False, 1.0) + ys, xs = np.where(tmp_image > 0) + xy_text = np.array(list(zip(xs, ys)), dtype='float32') + + left_center_pt = ( + (min_area_quad[0] - min_area_quad[1]) / 2.0).reshape(1, 2) + right_center_pt = ( + (min_area_quad[1] - min_area_quad[2]) / 2.0).reshape(1, 2) + proj_unit_vec = (right_center_pt - left_center_pt) / ( + np.linalg.norm(right_center_pt - left_center_pt) + 1e-6) + proj_unit_vec_tile = np.tile(proj_unit_vec, + (xy_text.shape[0], 1)) # (n, 2) + left_center_pt_tile = np.tile(left_center_pt, + (xy_text.shape[0], 1)) # (n, 2) + xy_text_to_left_center = xy_text - left_center_pt_tile + proj_value = np.sum(xy_text_to_left_center * proj_unit_vec_tile, axis=1) + xy_text = xy_text[np.argsort(proj_value)] + + # convert to np and keep the num of point not greater then fixed_point_num + pos_info = np.array(xy_text).reshape(-1, 2)[:, ::-1] # xy-> yx + point_num = len(pos_info) + if point_num > fixed_point_num: + keep_ids = [ + int((point_num * 1.0 / fixed_point_num) * x) + for x in range(fixed_point_num) + ] + pos_info = pos_info[keep_ids, :] + + keep = int(min(len(pos_info), fixed_point_num)) + if np.random.rand() < 0.2 and reference_height >= 3: + dl = (np.random.rand(keep) - 0.5) * reference_height * 0.3 + random_float = np.array([1, 0]).reshape([1, 2]) * dl.reshape( + [keep, 1]) + pos_info += random_float + pos_info[:, 0] = np.clip(pos_info[:, 0], 0, max_h - 1) + pos_info[:, 1] = np.clip(pos_info[:, 1], 0, max_w - 1) + + # padding to fixed length + pos_l = np.zeros((self.tcl_len, 3), dtype=np.int32) + pos_l[:, 0] = np.ones((self.tcl_len, )) * img_id + pos_m = np.zeros((self.tcl_len, 1), dtype=np.float32) + pos_l[:keep, 1:] = np.round(pos_info).astype(np.int32) + pos_m[:keep] = 1.0 + return pos_l, pos_m + + def generate_direction_map(self, poly_quads, n_char, direction_map): + """ + """ + width_list = [] + height_list = [] + for quad in poly_quads: + quad_w = (np.linalg.norm(quad[0] - quad[1]) + + np.linalg.norm(quad[2] - quad[3])) / 2.0 + quad_h = (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[2] - quad[1])) / 2.0 + width_list.append(quad_w) + height_list.append(quad_h) + norm_width = max(sum(width_list) / n_char, 1.0) + average_height = max(sum(height_list) / len(height_list), 1.0) + k = 1 + for quad in poly_quads: + direct_vector_full = ( + (quad[1] + quad[2]) - (quad[0] + quad[3])) / 2.0 + direct_vector = direct_vector_full / ( + np.linalg.norm(direct_vector_full) + 1e-6) * norm_width + direction_label = tuple( + map(float, + [direct_vector[0], direct_vector[1], 1.0 / average_height])) + cv2.fillPoly(direction_map, + quad.round().astype(np.int32)[np.newaxis, :, :], + direction_label) + k += 1 + return direction_map + + def calculate_average_height(self, poly_quads): + """ + """ + height_list = [] + for quad in poly_quads: + quad_h = (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[2] - quad[1])) / 2.0 + height_list.append(quad_h) + average_height = max(sum(height_list) / len(height_list), 1.0) + return average_height + + def generate_tcl_ctc_label(self, + h, + w, + polys, + tags, + text_strs, + ds_ratio, + tcl_ratio=0.3, + shrink_ratio_of_width=0.15): + """ + Generate polygon. + """ + score_map_big = np.zeros( + ( + h, + w, ), dtype=np.float32) + h, w = int(h * ds_ratio), int(w * ds_ratio) + polys = polys * ds_ratio + + score_map = np.zeros( + ( + h, + w, ), dtype=np.float32) + score_label_map = np.zeros( + ( + h, + w, ), dtype=np.float32) + tbo_map = np.zeros((h, w, 5), dtype=np.float32) + training_mask = np.ones( + ( + h, + w, ), dtype=np.float32) + direction_map = np.ones((h, w, 3)) * np.array([0, 0, 1]).reshape( + [1, 1, 3]).astype(np.float32) + + label_idx = 0 + score_label_map_text_label_list = [] + pos_list, pos_mask, label_list = [], [], [] + for poly_idx, poly_tag in enumerate(zip(polys, tags)): + poly = poly_tag[0] + tag = poly_tag[1] + + # generate min_area_quad + min_area_quad, center_point = self.gen_min_area_quad_from_poly(poly) + min_area_quad_h = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[3]) + + np.linalg.norm(min_area_quad[1] - min_area_quad[2])) + min_area_quad_w = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[1]) + + np.linalg.norm(min_area_quad[2] - min_area_quad[3])) + + if min(min_area_quad_h, min_area_quad_w) < self.min_text_size * ds_ratio \ + or min(min_area_quad_h, min_area_quad_w) > self.max_text_size * ds_ratio: + continue + + if tag: + cv2.fillPoly(training_mask, + poly.astype(np.int32)[np.newaxis, :, :], 0.15) + else: + text_label = text_strs[poly_idx] + text_label = self.prepare_text_label(text_label, + self.Lexicon_Table) + + text_label_index_list = [[self.Lexicon_Table.index(c_)] + for c_ in text_label + if c_ in self.Lexicon_Table] + if len(text_label_index_list) < 1: + continue + + tcl_poly = self.poly2tcl(poly, tcl_ratio) + tcl_quads = self.poly2quads(tcl_poly) + poly_quads = self.poly2quads(poly) + + stcl_quads, quad_index = self.shrink_poly_along_width( + tcl_quads, + shrink_ratio_of_width=shrink_ratio_of_width, + expand_height_ratio=1.0 / tcl_ratio) + + cv2.fillPoly(score_map, + np.round(stcl_quads).astype(np.int32), 1.0) + cv2.fillPoly(score_map_big, + np.round(stcl_quads / ds_ratio).astype(np.int32), + 1.0) + + for idx, quad in enumerate(stcl_quads): + quad_mask = np.zeros((h, w), dtype=np.float32) + quad_mask = cv2.fillPoly( + quad_mask, + np.round(quad[np.newaxis, :, :]).astype(np.int32), 1.0) + tbo_map = self.gen_quad_tbo(poly_quads[quad_index[idx]], + quad_mask, tbo_map) + + # score label map and score_label_map_text_label_list for refine + if label_idx == 0: + text_pos_list_ = [[len(self.Lexicon_Table)], ] + score_label_map_text_label_list.append(text_pos_list_) + + label_idx += 1 + cv2.fillPoly(score_label_map, + np.round(poly_quads).astype(np.int32), label_idx) + score_label_map_text_label_list.append(text_label_index_list) + + # direction info, fix-me + n_char = len(text_label_index_list) + direction_map = self.generate_direction_map(poly_quads, n_char, + direction_map) + + # pos info + average_shrink_height = self.calculate_average_height( + stcl_quads) + pos_l, pos_m = self.fit_and_gather_tcl_points_v2( + min_area_quad, + poly, + max_h=h, + max_w=w, + fixed_point_num=64, + img_id=self.img_id, + reference_height=average_shrink_height) + + label_l = text_label_index_list + if len(text_label_index_list) < 2: + continue + + pos_list.append(pos_l) + pos_mask.append(pos_m) + label_list.append(label_l) + + # use big score_map for smooth tcl lines + score_map_big_resized = cv2.resize( + score_map_big, dsize=None, fx=ds_ratio, fy=ds_ratio) + score_map = np.array(score_map_big_resized > 1e-3, dtype='float32') + + return score_map, score_label_map, tbo_map, direction_map, training_mask, \ + pos_list, pos_mask, label_list, score_label_map_text_label_list + + def adjust_point(self, poly): + """ + adjust point order. + """ + point_num = poly.shape[0] + if point_num == 4: + len_1 = np.linalg.norm(poly[0] - poly[1]) + len_2 = np.linalg.norm(poly[1] - poly[2]) + len_3 = np.linalg.norm(poly[2] - poly[3]) + len_4 = np.linalg.norm(poly[3] - poly[0]) + + if (len_1 + len_3) * 1.5 < (len_2 + len_4): + poly = poly[[1, 2, 3, 0], :] + + elif point_num > 4: + vector_1 = poly[0] - poly[1] + vector_2 = poly[1] - poly[2] + cos_theta = np.dot(vector_1, vector_2) / ( + np.linalg.norm(vector_1) * np.linalg.norm(vector_2) + 1e-6) + theta = np.arccos(np.round(cos_theta, decimals=4)) + + if abs(theta) > (70 / 180 * math.pi): + index = list(range(1, point_num)) + [0] + poly = poly[np.array(index), :] + return poly + + def gen_min_area_quad_from_poly(self, poly): + """ + Generate min area quad from poly. + """ + point_num = poly.shape[0] + min_area_quad = np.zeros((4, 2), dtype=np.float32) + if point_num == 4: + min_area_quad = poly + center_point = np.sum(poly, axis=0) / 4 + else: + rect = cv2.minAreaRect(poly.astype( + np.int32)) # (center (x,y), (width, height), angle of rotation) + center_point = rect[0] + box = np.array(cv2.boxPoints(rect)) + + first_point_idx = 0 + min_dist = 1e4 + for i in range(4): + dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \ + np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \ + np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \ + np.linalg.norm(box[(i + 3) % 4] - poly[-1]) + if dist < min_dist: + min_dist = dist + first_point_idx = i + + for i in range(4): + min_area_quad[i] = box[(first_point_idx + i) % 4] + + return min_area_quad, center_point + + def shrink_quad_along_width(self, + quad, + begin_width_ratio=0., + end_width_ratio=1.): + """ + Generate shrink_quad_along_width. + """ + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + def shrink_poly_along_width(self, + quads, + shrink_ratio_of_width, + expand_height_ratio=1.0): + """ + shrink poly with given length. + """ + upper_edge_list = [] + + def get_cut_info(edge_len_list, cut_len): + for idx, edge_len in enumerate(edge_len_list): + cut_len -= edge_len + if cut_len <= 0.000001: + ratio = (cut_len + edge_len_list[idx]) / edge_len_list[idx] + return idx, ratio + + for quad in quads: + upper_edge_len = np.linalg.norm(quad[0] - quad[1]) + upper_edge_list.append(upper_edge_len) + + # length of left edge and right edge. + left_length = np.linalg.norm(quads[0][0] - quads[0][ + 3]) * expand_height_ratio + right_length = np.linalg.norm(quads[-1][1] - quads[-1][ + 2]) * expand_height_ratio + + shrink_length = min(left_length, right_length, + sum(upper_edge_list)) * shrink_ratio_of_width + # shrinking length + upper_len_left = shrink_length + upper_len_right = sum(upper_edge_list) - shrink_length + + left_idx, left_ratio = get_cut_info(upper_edge_list, upper_len_left) + left_quad = self.shrink_quad_along_width( + quads[left_idx], begin_width_ratio=left_ratio, end_width_ratio=1) + right_idx, right_ratio = get_cut_info(upper_edge_list, upper_len_right) + right_quad = self.shrink_quad_along_width( + quads[right_idx], begin_width_ratio=0, end_width_ratio=right_ratio) + + out_quad_list = [] + if left_idx == right_idx: + out_quad_list.append( + [left_quad[0], right_quad[1], right_quad[2], left_quad[3]]) + else: + out_quad_list.append(left_quad) + for idx in range(left_idx + 1, right_idx): + out_quad_list.append(quads[idx]) + out_quad_list.append(right_quad) + + return np.array(out_quad_list), list(range(left_idx, right_idx + 1)) + + def prepare_text_label(self, label_str, Lexicon_Table): + """ + Prepare text lablel by given Lexicon_Table. + """ + if len(Lexicon_Table) == 36: + return label_str.lower() + else: + return label_str + + def vector_angle(self, A, B): + """ + Calculate the angle between vector AB and x-axis positive direction. + """ + AB = np.array([B[1] - A[1], B[0] - A[0]]) + return np.arctan2(*AB) + + def theta_line_cross_point(self, theta, point): + """ + Calculate the line through given point and angle in ax + by + c =0 form. + """ + x, y = point + cos = np.cos(theta) + sin = np.sin(theta) + return [sin, -cos, cos * y - sin * x] + + def line_cross_two_point(self, A, B): + """ + Calculate the line through given point A and B in ax + by + c =0 form. + """ + angle = self.vector_angle(A, B) + return self.theta_line_cross_point(angle, A) + + def average_angle(self, poly): + """ + Calculate the average angle between left and right edge in given poly. + """ + p0, p1, p2, p3 = poly + angle30 = self.vector_angle(p3, p0) + angle21 = self.vector_angle(p2, p1) + return (angle30 + angle21) / 2 + + def line_cross_point(self, line1, line2): + """ + line1 and line2 in 0=ax+by+c form, compute the cross point of line1 and line2 + """ + a1, b1, c1 = line1 + a2, b2, c2 = line2 + d = a1 * b2 - a2 * b1 + + if d == 0: + print('Cross point does not exist') + return np.array([0, 0], dtype=np.float32) + else: + x = (b1 * c2 - b2 * c1) / d + y = (a2 * c1 - a1 * c2) / d + + return np.array([x, y], dtype=np.float32) + + def quad2tcl(self, poly, ratio): + """ + Generate center line by poly clock-wise point. (4, 2) + """ + ratio_pair = np.array( + [[0.5 - ratio / 2], [0.5 + ratio / 2]], dtype=np.float32) + p0_3 = poly[0] + (poly[3] - poly[0]) * ratio_pair + p1_2 = poly[1] + (poly[2] - poly[1]) * ratio_pair + return np.array([p0_3[0], p1_2[0], p1_2[1], p0_3[1]]) + + def poly2tcl(self, poly, ratio): + """ + Generate center line by poly clock-wise point. + """ + ratio_pair = np.array( + [[0.5 - ratio / 2], [0.5 + ratio / 2]], dtype=np.float32) + tcl_poly = np.zeros_like(poly) + point_num = poly.shape[0] + + for idx in range(point_num // 2): + point_pair = poly[idx] + (poly[point_num - 1 - idx] - poly[idx] + ) * ratio_pair + tcl_poly[idx] = point_pair[0] + tcl_poly[point_num - 1 - idx] = point_pair[1] + return tcl_poly + + def gen_quad_tbo(self, quad, tcl_mask, tbo_map): + """ + Generate tbo_map for give quad. + """ + # upper and lower line function: ax + by + c = 0; + up_line = self.line_cross_two_point(quad[0], quad[1]) + lower_line = self.line_cross_two_point(quad[3], quad[2]) + + quad_h = 0.5 * (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[1] - quad[2])) + quad_w = 0.5 * (np.linalg.norm(quad[0] - quad[1]) + + np.linalg.norm(quad[2] - quad[3])) + + # average angle of left and right line. + angle = self.average_angle(quad) + + xy_in_poly = np.argwhere(tcl_mask == 1) + for y, x in xy_in_poly: + point = (x, y) + line = self.theta_line_cross_point(angle, point) + cross_point_upper = self.line_cross_point(up_line, line) + cross_point_lower = self.line_cross_point(lower_line, line) + ##FIX, offset reverse + upper_offset_x, upper_offset_y = cross_point_upper - point + lower_offset_x, lower_offset_y = cross_point_lower - point + tbo_map[y, x, 0] = upper_offset_y + tbo_map[y, x, 1] = upper_offset_x + tbo_map[y, x, 2] = lower_offset_y + tbo_map[y, x, 3] = lower_offset_x + tbo_map[y, x, 4] = 1.0 / max(min(quad_h, quad_w), 1.0) * 2 + return tbo_map + + def poly2quads(self, poly): + """ + Split poly into quads. + """ + quad_list = [] + point_num = poly.shape[0] + + # point pair + point_pair_list = [] + for idx in range(point_num // 2): + point_pair = [poly[idx], poly[point_num - 1 - idx]] + point_pair_list.append(point_pair) + + quad_num = point_num // 2 - 1 + for idx in range(quad_num): + # reshape and adjust to clock-wise + quad_list.append((np.array(point_pair_list)[[idx, idx + 1]] + ).reshape(4, 2)[[0, 2, 3, 1]]) + + return np.array(quad_list) + + def rotate_im_poly(self, im, text_polys): + """ + rotate image with 90 / 180 / 270 degre + """ + im_w, im_h = im.shape[1], im.shape[0] + dst_im = im.copy() + dst_polys = [] + rand_degree_ratio = np.random.rand() + rand_degree_cnt = 1 + if rand_degree_ratio > 0.5: + rand_degree_cnt = 3 + for i in range(rand_degree_cnt): + dst_im = np.rot90(dst_im) + rot_degree = -90 * rand_degree_cnt + rot_angle = rot_degree * math.pi / 180.0 + n_poly = text_polys.shape[0] + cx, cy = 0.5 * im_w, 0.5 * im_h + ncx, ncy = 0.5 * dst_im.shape[1], 0.5 * dst_im.shape[0] + for i in range(n_poly): + wordBB = text_polys[i] + poly = [] + for j in range(4): # 16->4 + sx, sy = wordBB[j][0], wordBB[j][1] + dx = math.cos(rot_angle) * (sx - cx) - math.sin(rot_angle) * ( + sy - cy) + ncx + dy = math.sin(rot_angle) * (sx - cx) + math.cos(rot_angle) * ( + sy - cy) + ncy + poly.append([dx, dy]) + dst_polys.append(poly) + return dst_im, np.array(dst_polys, dtype=np.float32) + + def __call__(self, data): + input_size = 512 + im = data['image'] + text_polys = data['polys'] + text_tags = data['ignore_tags'] + text_strs = data['texts'] + h, w, _ = im.shape + text_polys, text_tags, hv_tags = self.check_and_validate_polys( + text_polys, text_tags, (h, w)) + if text_polys.shape[0] <= 0: + return None + # set aspect ratio and keep area fix + asp_scales = np.arange(1.0, 1.55, 0.1) + asp_scale = np.random.choice(asp_scales) + if np.random.rand() < 0.5: + asp_scale = 1.0 / asp_scale + asp_scale = math.sqrt(asp_scale) + + asp_wx = asp_scale + asp_hy = 1.0 / asp_scale + im = cv2.resize(im, dsize=None, fx=asp_wx, fy=asp_hy) + text_polys[:, :, 0] *= asp_wx + text_polys[:, :, 1] *= asp_hy + + h, w, _ = im.shape + if max(h, w) > 2048: + rd_scale = 2048.0 / max(h, w) + im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale) + text_polys *= rd_scale + h, w, _ = im.shape + if min(h, w) < 16: + return None + + # no background + im, text_polys, text_tags, hv_tags, text_strs = self.crop_area( + im, + text_polys, + text_tags, + hv_tags, + text_strs, + crop_background=False) + + if text_polys.shape[0] == 0: + return None + # # continue for all ignore case + if np.sum((text_tags * 1.0)) >= text_tags.size: + return None + new_h, new_w, _ = im.shape + if (new_h is None) or (new_w is None): + return None + # resize image + std_ratio = float(input_size) / max(new_w, new_h) + rand_scales = np.array( + [0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.0, 1.0, 1.0, 1.0]) + rz_scale = std_ratio * np.random.choice(rand_scales) + im = cv2.resize(im, dsize=None, fx=rz_scale, fy=rz_scale) + text_polys[:, :, 0] *= rz_scale + text_polys[:, :, 1] *= rz_scale + + # add gaussian blur + if np.random.rand() < 0.1 * 0.5: + ks = np.random.permutation(5)[0] + 1 + ks = int(ks / 2) * 2 + 1 + im = cv2.GaussianBlur(im, ksize=(ks, ks), sigmaX=0, sigmaY=0) + # add brighter + if np.random.rand() < 0.1 * 0.5: + im = im * (1.0 + np.random.rand() * 0.5) + im = np.clip(im, 0.0, 255.0) + # add darker + if np.random.rand() < 0.1 * 0.5: + im = im * (1.0 - np.random.rand() * 0.5) + im = np.clip(im, 0.0, 255.0) + + # Padding the im to [input_size, input_size] + new_h, new_w, _ = im.shape + if min(new_w, new_h) < input_size * 0.5: + return None + im_padded = np.ones((input_size, input_size, 3), dtype=np.float32) + im_padded[:, :, 2] = 0.485 * 255 + im_padded[:, :, 1] = 0.456 * 255 + im_padded[:, :, 0] = 0.406 * 255 + + # Random the start position + del_h = input_size - new_h + del_w = input_size - new_w + sh, sw = 0, 0 + if del_h > 1: + sh = int(np.random.rand() * del_h) + if del_w > 1: + sw = int(np.random.rand() * del_w) + + # Padding + im_padded[sh:sh + new_h, sw:sw + new_w, :] = im.copy() + text_polys[:, :, 0] += sw + text_polys[:, :, 1] += sh + + score_map, score_label_map, border_map, direction_map, training_mask, \ + pos_list, pos_mask, label_list, score_label_map_text_label = self.generate_tcl_ctc_label(input_size, + input_size, + text_polys, + text_tags, + text_strs, 0.25) + if len(label_list) <= 0: # eliminate negative samples + return None + pos_list_temp = np.zeros([64, 3]) + pos_mask_temp = np.zeros([64, 1]) + label_list_temp = np.zeros([self.max_text_length, 1]) + self.pad_num + + for i, label in enumerate(label_list): + n = len(label) + if n > self.max_text_length: + label_list[i] = label[:self.max_text_length] + continue + while n < self.max_text_length: + label.append([self.pad_num]) + n += 1 + + for i in range(len(label_list)): + label_list[i] = np.array(label_list[i]) + + if len(pos_list) <= 0 or len(pos_list) > self.max_text_nums: + return None + for __ in range(self.max_text_nums - len(pos_list), 0, -1): + pos_list.append(pos_list_temp) + pos_mask.append(pos_mask_temp) + label_list.append(label_list_temp) + + if self.img_id == self.batch_size - 1: + self.img_id = 0 + else: + self.img_id += 1 + + im_padded[:, :, 2] -= 0.485 * 255 + im_padded[:, :, 1] -= 0.456 * 255 + im_padded[:, :, 0] -= 0.406 * 255 + im_padded[:, :, 2] /= (255.0 * 0.229) + im_padded[:, :, 1] /= (255.0 * 0.224) + im_padded[:, :, 0] /= (255.0 * 0.225) + im_padded = im_padded.transpose((2, 0, 1)) + images = im_padded[::-1, :, :] + tcl_maps = score_map[np.newaxis, :, :] + tcl_label_maps = score_label_map[np.newaxis, :, :] + border_maps = border_map.transpose((2, 0, 1)) + direction_maps = direction_map.transpose((2, 0, 1)) + training_masks = training_mask[np.newaxis, :, :] + pos_list = np.array(pos_list) + pos_mask = np.array(pos_mask) + label_list = np.array(label_list) + data['images'] = images + data['tcl_maps'] = tcl_maps + data['tcl_label_maps'] = tcl_label_maps + data['border_maps'] = border_maps + data['direction_maps'] = direction_maps + data['training_masks'] = training_masks + data['label_list'] = label_list + data['pos_list'] = pos_list + data['pos_mask'] = pos_mask + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/randaugment.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/randaugment.py new file mode 100644 index 0000000000000000000000000000000000000000..56f114d2f665f9b326e96819ac3d606c87a6e142 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/randaugment.py @@ -0,0 +1,143 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from PIL import Image, ImageEnhance, ImageOps +import numpy as np +import random +import six + + +class RawRandAugment(object): + def __init__(self, + num_layers=2, + magnitude=5, + fillcolor=(128, 128, 128), + **kwargs): + self.num_layers = num_layers + self.magnitude = magnitude + self.max_level = 10 + + abso_level = self.magnitude / self.max_level + self.level_map = { + "shearX": 0.3 * abso_level, + "shearY": 0.3 * abso_level, + "translateX": 150.0 / 331 * abso_level, + "translateY": 150.0 / 331 * abso_level, + "rotate": 30 * abso_level, + "color": 0.9 * abso_level, + "posterize": int(4.0 * abso_level), + "solarize": 256.0 * abso_level, + "contrast": 0.9 * abso_level, + "sharpness": 0.9 * abso_level, + "brightness": 0.9 * abso_level, + "autocontrast": 0, + "equalize": 0, + "invert": 0 + } + + # from https://stackoverflow.com/questions/5252170/ + # specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand + def rotate_with_fill(img, magnitude): + rot = img.convert("RGBA").rotate(magnitude) + return Image.composite(rot, + Image.new("RGBA", rot.size, (128, ) * 4), + rot).convert(img.mode) + + rnd_ch_op = random.choice + + self.func = { + "shearX": lambda img, magnitude: img.transform( + img.size, + Image.AFFINE, + (1, magnitude * rnd_ch_op([-1, 1]), 0, 0, 1, 0), + Image.BICUBIC, + fillcolor=fillcolor), + "shearY": lambda img, magnitude: img.transform( + img.size, + Image.AFFINE, + (1, 0, 0, magnitude * rnd_ch_op([-1, 1]), 1, 0), + Image.BICUBIC, + fillcolor=fillcolor), + "translateX": lambda img, magnitude: img.transform( + img.size, + Image.AFFINE, + (1, 0, magnitude * img.size[0] * rnd_ch_op([-1, 1]), 0, 1, 0), + fillcolor=fillcolor), + "translateY": lambda img, magnitude: img.transform( + img.size, + Image.AFFINE, + (1, 0, 0, 0, 1, magnitude * img.size[1] * rnd_ch_op([-1, 1])), + fillcolor=fillcolor), + "rotate": lambda img, magnitude: rotate_with_fill(img, magnitude), + "color": lambda img, magnitude: ImageEnhance.Color(img).enhance( + 1 + magnitude * rnd_ch_op([-1, 1])), + "posterize": lambda img, magnitude: + ImageOps.posterize(img, magnitude), + "solarize": lambda img, magnitude: + ImageOps.solarize(img, magnitude), + "contrast": lambda img, magnitude: + ImageEnhance.Contrast(img).enhance( + 1 + magnitude * rnd_ch_op([-1, 1])), + "sharpness": lambda img, magnitude: + ImageEnhance.Sharpness(img).enhance( + 1 + magnitude * rnd_ch_op([-1, 1])), + "brightness": lambda img, magnitude: + ImageEnhance.Brightness(img).enhance( + 1 + magnitude * rnd_ch_op([-1, 1])), + "autocontrast": lambda img, magnitude: + ImageOps.autocontrast(img), + "equalize": lambda img, magnitude: ImageOps.equalize(img), + "invert": lambda img, magnitude: ImageOps.invert(img) + } + + def __call__(self, img): + avaiable_op_names = list(self.level_map.keys()) + for layer_num in range(self.num_layers): + op_name = np.random.choice(avaiable_op_names) + img = self.func[op_name](img, self.level_map[op_name]) + return img + + +class RandAugment(RawRandAugment): + """ RandAugment wrapper to auto fit different img types """ + + def __init__(self, prob=0.5, *args, **kwargs): + self.prob = prob + if six.PY2: + super(RandAugment, self).__init__(*args, **kwargs) + else: + super().__init__(*args, **kwargs) + + def __call__(self, data): + if np.random.rand() > self.prob: + return data + img = data['image'] + if not isinstance(img, Image.Image): + img = np.ascontiguousarray(img) + img = Image.fromarray(img) + + if six.PY2: + img = super(RandAugment, self).__call__(img) + else: + img = super().__call__(img) + + if isinstance(img, Image.Image): + img = np.asarray(img) + data['image'] = img + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/random_crop_data.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/random_crop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..64aa110de4e3df950ce21e6d657877081b0fdd13 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/random_crop_data.py @@ -0,0 +1,234 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/data_loader/modules/random_crop_data.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import numpy as np +import cv2 +import random + + +def is_poly_in_rect(poly, x, y, w, h): + poly = np.array(poly) + if poly[:, 0].min() < x or poly[:, 0].max() > x + w: + return False + if poly[:, 1].min() < y or poly[:, 1].max() > y + h: + return False + return True + + +def is_poly_outside_rect(poly, x, y, w, h): + poly = np.array(poly) + if poly[:, 0].max() < x or poly[:, 0].min() > x + w: + return True + if poly[:, 1].max() < y or poly[:, 1].min() > y + h: + return True + return False + + +def split_regions(axis): + regions = [] + min_axis = 0 + for i in range(1, axis.shape[0]): + if axis[i] != axis[i - 1] + 1: + region = axis[min_axis:i] + min_axis = i + regions.append(region) + return regions + + +def random_select(axis, max_size): + xx = np.random.choice(axis, size=2) + xmin = np.min(xx) + xmax = np.max(xx) + xmin = np.clip(xmin, 0, max_size - 1) + xmax = np.clip(xmax, 0, max_size - 1) + return xmin, xmax + + +def region_wise_random_select(regions, max_size): + selected_index = list(np.random.choice(len(regions), 2)) + selected_values = [] + for index in selected_index: + axis = regions[index] + xx = int(np.random.choice(axis, size=1)) + selected_values.append(xx) + xmin = min(selected_values) + xmax = max(selected_values) + return xmin, xmax + + +def crop_area(im, text_polys, min_crop_side_ratio, max_tries): + h, w, _ = im.shape + h_array = np.zeros(h, dtype=np.int32) + w_array = np.zeros(w, dtype=np.int32) + for points in text_polys: + points = np.round(points, decimals=0).astype(np.int32) + minx = np.min(points[:, 0]) + maxx = np.max(points[:, 0]) + w_array[minx:maxx] = 1 + miny = np.min(points[:, 1]) + maxy = np.max(points[:, 1]) + h_array[miny:maxy] = 1 + # ensure the cropped area not across a text + h_axis = np.where(h_array == 0)[0] + w_axis = np.where(w_array == 0)[0] + + if len(h_axis) == 0 or len(w_axis) == 0: + return 0, 0, w, h + + h_regions = split_regions(h_axis) + w_regions = split_regions(w_axis) + + for i in range(max_tries): + if len(w_regions) > 1: + xmin, xmax = region_wise_random_select(w_regions, w) + else: + xmin, xmax = random_select(w_axis, w) + if len(h_regions) > 1: + ymin, ymax = region_wise_random_select(h_regions, h) + else: + ymin, ymax = random_select(h_axis, h) + + if xmax - xmin < min_crop_side_ratio * w or ymax - ymin < min_crop_side_ratio * h: + # area too small + continue + num_poly_in_rect = 0 + for poly in text_polys: + if not is_poly_outside_rect(poly, xmin, ymin, xmax - xmin, + ymax - ymin): + num_poly_in_rect += 1 + break + + if num_poly_in_rect > 0: + return xmin, ymin, xmax - xmin, ymax - ymin + + return 0, 0, w, h + + +class EastRandomCropData(object): + def __init__(self, + size=(640, 640), + max_tries=10, + min_crop_side_ratio=0.1, + keep_ratio=True, + **kwargs): + self.size = size + self.max_tries = max_tries + self.min_crop_side_ratio = min_crop_side_ratio + self.keep_ratio = keep_ratio + + def __call__(self, data): + img = data['image'] + text_polys = data['polys'] + ignore_tags = data['ignore_tags'] + texts = data['texts'] + all_care_polys = [ + text_polys[i] for i, tag in enumerate(ignore_tags) if not tag + ] + # 计算crop区域 + crop_x, crop_y, crop_w, crop_h = crop_area( + img, all_care_polys, self.min_crop_side_ratio, self.max_tries) + # crop 图片 保持比例填充 + scale_w = self.size[0] / crop_w + scale_h = self.size[1] / crop_h + scale = min(scale_w, scale_h) + h = int(crop_h * scale) + w = int(crop_w * scale) + if self.keep_ratio: + padimg = np.zeros((self.size[1], self.size[0], img.shape[2]), + img.dtype) + padimg[:h, :w] = cv2.resize( + img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w], (w, h)) + img = padimg + else: + img = cv2.resize( + img[crop_y:crop_y + crop_h, crop_x:crop_x + crop_w], + tuple(self.size)) + # crop 文本框 + text_polys_crop = [] + ignore_tags_crop = [] + texts_crop = [] + for poly, text, tag in zip(text_polys, texts, ignore_tags): + poly = ((poly - (crop_x, crop_y)) * scale).tolist() + if not is_poly_outside_rect(poly, 0, 0, w, h): + text_polys_crop.append(poly) + ignore_tags_crop.append(tag) + texts_crop.append(text) + data['image'] = img + data['polys'] = np.array(text_polys_crop) + data['ignore_tags'] = ignore_tags_crop + data['texts'] = texts_crop + return data + + +class RandomCropImgMask(object): + def __init__(self, size, main_key, crop_keys, p=3 / 8, **kwargs): + self.size = size + self.main_key = main_key + self.crop_keys = crop_keys + self.p = p + + def __call__(self, data): + image = data['image'] + + h, w = image.shape[0:2] + th, tw = self.size + if w == tw and h == th: + return data + + mask = data[self.main_key] + if np.max(mask) > 0 and random.random() > self.p: + # make sure to crop the text region + tl = np.min(np.where(mask > 0), axis=1) - (th, tw) + tl[tl < 0] = 0 + br = np.max(np.where(mask > 0), axis=1) - (th, tw) + br[br < 0] = 0 + + br[0] = min(br[0], h - th) + br[1] = min(br[1], w - tw) + + i = random.randint(tl[0], br[0]) if tl[0] < br[0] else 0 + j = random.randint(tl[1], br[1]) if tl[1] < br[1] else 0 + else: + i = random.randint(0, h - th) if h - th > 0 else 0 + j = random.randint(0, w - tw) if w - tw > 0 else 0 + + # return i, j, th, tw + for k in data: + if k in self.crop_keys: + if len(data[k].shape) == 3: + if np.argmin(data[k].shape) == 0: + img = data[k][:, i:i + th, j:j + tw] + if img.shape[1] != img.shape[2]: + a = 1 + elif np.argmin(data[k].shape) == 2: + img = data[k][i:i + th, j:j + tw, :] + if img.shape[1] != img.shape[0]: + a = 1 + else: + img = data[k] + else: + img = data[k][i:i + th, j:j + tw] + if img.shape[0] != img.shape[1]: + a = 1 + data[k] = img + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/rec_img_aug.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/rec_img_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e0de8496559a40d42641a043848d5d43c98de1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/rec_img_aug.py @@ -0,0 +1,757 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +import cv2 +import numpy as np +import random +import copy +from PIL import Image +from .text_image_aug import tia_perspective, tia_stretch, tia_distort +from .abinet_aug import CVGeometry, CVDeterioration, CVColorJitter +from paddle.vision.transforms import Compose + + +class RecAug(object): + def __init__(self, + tia_prob=0.4, + crop_prob=0.4, + reverse_prob=0.4, + noise_prob=0.4, + jitter_prob=0.4, + blur_prob=0.4, + hsv_aug_prob=0.4, + **kwargs): + self.tia_prob = tia_prob + self.bda = BaseDataAugmentation(crop_prob, reverse_prob, noise_prob, + jitter_prob, blur_prob, hsv_aug_prob) + + def __call__(self, data): + img = data['image'] + h, w, _ = img.shape + + # tia + if random.random() <= self.tia_prob: + if h >= 20 and w >= 20: + img = tia_distort(img, random.randint(3, 6)) + img = tia_stretch(img, random.randint(3, 6)) + img = tia_perspective(img) + + # bda + data['image'] = img + data = self.bda(data) + return data + + +class BaseDataAugmentation(object): + def __init__(self, + crop_prob=0.4, + reverse_prob=0.4, + noise_prob=0.4, + jitter_prob=0.4, + blur_prob=0.4, + hsv_aug_prob=0.4, + **kwargs): + self.crop_prob = crop_prob + self.reverse_prob = reverse_prob + self.noise_prob = noise_prob + self.jitter_prob = jitter_prob + self.blur_prob = blur_prob + self.hsv_aug_prob = hsv_aug_prob + + def __call__(self, data): + img = data['image'] + h, w, _ = img.shape + + if random.random() <= self.crop_prob and h >= 20 and w >= 20: + img = get_crop(img) + + if random.random() <= self.blur_prob: + img = blur(img) + + if random.random() <= self.hsv_aug_prob: + img = hsv_aug(img) + + if random.random() <= self.jitter_prob: + img = jitter(img) + + if random.random() <= self.noise_prob: + img = add_gasuss_noise(img) + + if random.random() <= self.reverse_prob: + img = 255 - img + + data['image'] = img + return data + + +class ABINetRecAug(object): + def __init__(self, + geometry_p=0.5, + deterioration_p=0.25, + colorjitter_p=0.25, + **kwargs): + self.transforms = Compose([ + CVGeometry( + degrees=45, + translate=(0.0, 0.0), + scale=(0.5, 2.), + shear=(45, 15), + distortion=0.5, + p=geometry_p), CVDeterioration( + var=20, degrees=6, factor=4, p=deterioration_p), + CVColorJitter( + brightness=0.5, + contrast=0.5, + saturation=0.5, + hue=0.1, + p=colorjitter_p) + ]) + + def __call__(self, data): + img = data['image'] + img = self.transforms(img) + data['image'] = img + return data + + +class RecConAug(object): + def __init__(self, + prob=0.5, + image_shape=(32, 320, 3), + max_text_length=25, + ext_data_num=1, + **kwargs): + self.ext_data_num = ext_data_num + self.prob = prob + self.max_text_length = max_text_length + self.image_shape = image_shape + self.max_wh_ratio = self.image_shape[1] / self.image_shape[0] + + def merge_ext_data(self, data, ext_data): + ori_w = round(data['image'].shape[1] / data['image'].shape[0] * + self.image_shape[0]) + ext_w = round(ext_data['image'].shape[1] / ext_data['image'].shape[0] * + self.image_shape[0]) + data['image'] = cv2.resize(data['image'], (ori_w, self.image_shape[0])) + ext_data['image'] = cv2.resize(ext_data['image'], + (ext_w, self.image_shape[0])) + data['image'] = np.concatenate( + [data['image'], ext_data['image']], axis=1) + data["label"] += ext_data["label"] + return data + + def __call__(self, data): + rnd_num = random.random() + if rnd_num > self.prob: + return data + for idx, ext_data in enumerate(data["ext_data"]): + if len(data["label"]) + len(ext_data[ + "label"]) > self.max_text_length: + break + concat_ratio = data['image'].shape[1] / data['image'].shape[ + 0] + ext_data['image'].shape[1] / ext_data['image'].shape[0] + if concat_ratio > self.max_wh_ratio: + break + data = self.merge_ext_data(data, ext_data) + data.pop("ext_data") + return data + + +class ClsResizeImg(object): + def __init__(self, image_shape, **kwargs): + self.image_shape = image_shape + + def __call__(self, data): + img = data['image'] + norm_img, _ = resize_norm_img(img, self.image_shape) + data['image'] = norm_img + return data + + +class RecResizeImg(object): + def __init__(self, + image_shape, + infer_mode=False, + character_dict_path='./ppocr/utils/ppocr_keys_v1.txt', + padding=True, + **kwargs): + self.image_shape = image_shape + self.infer_mode = infer_mode + self.character_dict_path = character_dict_path + self.padding = padding + + def __call__(self, data): + img = data['image'] + if self.infer_mode and self.character_dict_path is not None: + norm_img, valid_ratio = resize_norm_img_chinese(img, + self.image_shape) + else: + norm_img, valid_ratio = resize_norm_img(img, self.image_shape, + self.padding) + data['image'] = norm_img + data['valid_ratio'] = valid_ratio + return data + + +class VLRecResizeImg(object): + def __init__(self, + image_shape, + infer_mode=False, + character_dict_path='./ppocr/utils/ppocr_keys_v1.txt', + padding=True, + **kwargs): + self.image_shape = image_shape + self.infer_mode = infer_mode + self.character_dict_path = character_dict_path + self.padding = padding + + def __call__(self, data): + img = data['image'] + + imgC, imgH, imgW = self.image_shape + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_w = imgW + resized_image = resized_image.astype('float32') + if self.image_shape[0] == 1: + resized_image = resized_image / 255 + norm_img = resized_image[np.newaxis, :] + else: + norm_img = resized_image.transpose((2, 0, 1)) / 255 + valid_ratio = min(1.0, float(resized_w / imgW)) + + data['image'] = norm_img + data['valid_ratio'] = valid_ratio + return data + + +class SRNRecResizeImg(object): + def __init__(self, image_shape, num_heads, max_text_length, **kwargs): + self.image_shape = image_shape + self.num_heads = num_heads + self.max_text_length = max_text_length + + def __call__(self, data): + img = data['image'] + norm_img = resize_norm_img_srn(img, self.image_shape) + data['image'] = norm_img + [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \ + srn_other_inputs(self.image_shape, self.num_heads, self.max_text_length) + + data['encoder_word_pos'] = encoder_word_pos + data['gsrm_word_pos'] = gsrm_word_pos + data['gsrm_slf_attn_bias1'] = gsrm_slf_attn_bias1 + data['gsrm_slf_attn_bias2'] = gsrm_slf_attn_bias2 + return data + + +class SARRecResizeImg(object): + def __init__(self, image_shape, width_downsample_ratio=0.25, **kwargs): + self.image_shape = image_shape + self.width_downsample_ratio = width_downsample_ratio + + def __call__(self, data): + img = data['image'] + norm_img, resize_shape, pad_shape, valid_ratio = resize_norm_img_sar( + img, self.image_shape, self.width_downsample_ratio) + data['image'] = norm_img + data['resized_shape'] = resize_shape + data['pad_shape'] = pad_shape + data['valid_ratio'] = valid_ratio + return data + + +class PRENResizeImg(object): + def __init__(self, image_shape, **kwargs): + """ + Accroding to original paper's realization, it's a hard resize method here. + So maybe you should optimize it to fit for your task better. + """ + self.dst_h, self.dst_w = image_shape + + def __call__(self, data): + img = data['image'] + resized_img = cv2.resize( + img, (self.dst_w, self.dst_h), interpolation=cv2.INTER_LINEAR) + resized_img = resized_img.transpose((2, 0, 1)) / 255 + resized_img -= 0.5 + resized_img /= 0.5 + data['image'] = resized_img.astype(np.float32) + return data + + +class SPINRecResizeImg(object): + def __init__(self, + image_shape, + interpolation=2, + mean=(127.5, 127.5, 127.5), + std=(127.5, 127.5, 127.5), + **kwargs): + self.image_shape = image_shape + + self.mean = np.array(mean, dtype=np.float32) + self.std = np.array(std, dtype=np.float32) + self.interpolation = interpolation + + def __call__(self, data): + img = data['image'] + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + # different interpolation type corresponding the OpenCV + if self.interpolation == 0: + interpolation = cv2.INTER_NEAREST + elif self.interpolation == 1: + interpolation = cv2.INTER_LINEAR + elif self.interpolation == 2: + interpolation = cv2.INTER_CUBIC + elif self.interpolation == 3: + interpolation = cv2.INTER_AREA + else: + raise Exception("Unsupported interpolation type !!!") + # Deal with the image error during image loading + if img is None: + return None + + img = cv2.resize(img, tuple(self.image_shape), interpolation) + img = np.array(img, np.float32) + img = np.expand_dims(img, -1) + img = img.transpose((2, 0, 1)) + # normalize the image + img = img.copy().astype(np.float32) + mean = np.float64(self.mean.reshape(1, -1)) + stdinv = 1 / np.float64(self.std.reshape(1, -1)) + img -= mean + img *= stdinv + data['image'] = img + return data + + +class GrayRecResizeImg(object): + def __init__(self, + image_shape, + resize_type, + inter_type='Image.ANTIALIAS', + scale=True, + padding=False, + **kwargs): + self.image_shape = image_shape + self.resize_type = resize_type + self.padding = padding + self.inter_type = eval(inter_type) + self.scale = scale + + def __call__(self, data): + img = data['image'] + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + image_shape = self.image_shape + if self.padding: + imgC, imgH, imgW = image_shape + # todo: change to 0 and modified image shape + h = img.shape[0] + w = img.shape[1] + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = cv2.resize(img, (resized_w, imgH)) + norm_img = np.expand_dims(resized_image, -1) + norm_img = norm_img.transpose((2, 0, 1)) + resized_image = norm_img.astype(np.float32) / 128. - 1. + padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + padding_im[:, :, 0:resized_w] = resized_image + data['image'] = padding_im + return data + if self.resize_type == 'PIL': + image_pil = Image.fromarray(np.uint8(img)) + img = image_pil.resize(self.image_shape, self.inter_type) + img = np.array(img) + if self.resize_type == 'OpenCV': + img = cv2.resize(img, self.image_shape) + norm_img = np.expand_dims(img, -1) + norm_img = norm_img.transpose((2, 0, 1)) + if self.scale: + data['image'] = norm_img.astype(np.float32) / 128. - 1. + else: + data['image'] = norm_img.astype(np.float32) / 255. + return data + + +class ABINetRecResizeImg(object): + def __init__(self, image_shape, **kwargs): + self.image_shape = image_shape + + def __call__(self, data): + img = data['image'] + norm_img, valid_ratio = resize_norm_img_abinet(img, self.image_shape) + data['image'] = norm_img + data['valid_ratio'] = valid_ratio + return data + + +class SVTRRecResizeImg(object): + def __init__(self, image_shape, padding=True, **kwargs): + self.image_shape = image_shape + self.padding = padding + + def __call__(self, data): + img = data['image'] + + norm_img, valid_ratio = resize_norm_img(img, self.image_shape, + self.padding) + data['image'] = norm_img + data['valid_ratio'] = valid_ratio + return data + +class RobustScannerRecResizeImg(object): + def __init__(self, image_shape, max_text_length, width_downsample_ratio=0.25, **kwargs): + self.image_shape = image_shape + self.width_downsample_ratio = width_downsample_ratio + self.max_text_length = max_text_length + + def __call__(self, data): + img = data['image'] + norm_img, resize_shape, pad_shape, valid_ratio = resize_norm_img_sar( + img, self.image_shape, self.width_downsample_ratio) + word_positons = np.array(range(0, self.max_text_length)).astype('int64') + data['image'] = norm_img + data['resized_shape'] = resize_shape + data['pad_shape'] = pad_shape + data['valid_ratio'] = valid_ratio + data['word_positons'] = word_positons + return data + +def resize_norm_img_sar(img, image_shape, width_downsample_ratio=0.25): + imgC, imgH, imgW_min, imgW_max = image_shape + h = img.shape[0] + w = img.shape[1] + valid_ratio = 1.0 + # make sure new_width is an integral multiple of width_divisor. + width_divisor = int(1 / width_downsample_ratio) + # resize + ratio = w / float(h) + resize_w = math.ceil(imgH * ratio) + if resize_w % width_divisor != 0: + resize_w = round(resize_w / width_divisor) * width_divisor + if imgW_min is not None: + resize_w = max(imgW_min, resize_w) + if imgW_max is not None: + valid_ratio = min(1.0, 1.0 * resize_w / imgW_max) + resize_w = min(imgW_max, resize_w) + resized_image = cv2.resize(img, (resize_w, imgH)) + resized_image = resized_image.astype('float32') + # norm + if image_shape[0] == 1: + resized_image = resized_image / 255 + resized_image = resized_image[np.newaxis, :] + else: + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + resize_shape = resized_image.shape + padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32) + padding_im[:, :, 0:resize_w] = resized_image + pad_shape = padding_im.shape + + return padding_im, resize_shape, pad_shape, valid_ratio + + +def resize_norm_img(img, image_shape, padding=True): + imgC, imgH, imgW = image_shape + h = img.shape[0] + w = img.shape[1] + if not padding: + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_w = imgW + else: + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = cv2.resize(img, (resized_w, imgH)) + resized_image = resized_image.astype('float32') + if image_shape[0] == 1: + resized_image = resized_image / 255 + resized_image = resized_image[np.newaxis, :] + else: + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + padding_im[:, :, 0:resized_w] = resized_image + valid_ratio = min(1.0, float(resized_w / imgW)) + return padding_im, valid_ratio + + +def resize_norm_img_chinese(img, image_shape): + imgC, imgH, imgW = image_shape + # todo: change to 0 and modified image shape + max_wh_ratio = imgW * 1.0 / imgH + h, w = img.shape[0], img.shape[1] + ratio = w * 1.0 / h + max_wh_ratio = max(max_wh_ratio, ratio) + imgW = int(imgH * max_wh_ratio) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = cv2.resize(img, (resized_w, imgH)) + resized_image = resized_image.astype('float32') + if image_shape[0] == 1: + resized_image = resized_image / 255 + resized_image = resized_image[np.newaxis, :] + else: + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + padding_im[:, :, 0:resized_w] = resized_image + valid_ratio = min(1.0, float(resized_w / imgW)) + return padding_im, valid_ratio + + +def resize_norm_img_srn(img, image_shape): + imgC, imgH, imgW = image_shape + + img_black = np.zeros((imgH, imgW)) + im_hei = img.shape[0] + im_wid = img.shape[1] + + if im_wid <= im_hei * 1: + img_new = cv2.resize(img, (imgH * 1, imgH)) + elif im_wid <= im_hei * 2: + img_new = cv2.resize(img, (imgH * 2, imgH)) + elif im_wid <= im_hei * 3: + img_new = cv2.resize(img, (imgH * 3, imgH)) + else: + img_new = cv2.resize(img, (imgW, imgH)) + + img_np = np.asarray(img_new) + img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY) + img_black[:, 0:img_np.shape[1]] = img_np + img_black = img_black[:, :, np.newaxis] + + row, col, c = img_black.shape + c = 1 + + return np.reshape(img_black, (c, row, col)).astype(np.float32) + + +def resize_norm_img_abinet(img, image_shape): + imgC, imgH, imgW = image_shape + + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_w = imgW + resized_image = resized_image.astype('float32') + resized_image = resized_image / 255. + + mean = np.array([0.485, 0.456, 0.406]) + std = np.array([0.229, 0.224, 0.225]) + resized_image = ( + resized_image - mean[None, None, ...]) / std[None, None, ...] + resized_image = resized_image.transpose((2, 0, 1)) + resized_image = resized_image.astype('float32') + + valid_ratio = min(1.0, float(resized_w / imgW)) + return resized_image, valid_ratio + + +def srn_other_inputs(image_shape, num_heads, max_text_length): + + imgC, imgH, imgW = image_shape + feature_dim = int((imgH / 8) * (imgW / 8)) + + encoder_word_pos = np.array(range(0, feature_dim)).reshape( + (feature_dim, 1)).astype('int64') + gsrm_word_pos = np.array(range(0, max_text_length)).reshape( + (max_text_length, 1)).astype('int64') + + gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length)) + gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape( + [1, max_text_length, max_text_length]) + gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1, + [num_heads, 1, 1]) * [-1e9] + + gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape( + [1, max_text_length, max_text_length]) + gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2, + [num_heads, 1, 1]) * [-1e9] + + return [ + encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, + gsrm_slf_attn_bias2 + ] + + +def flag(): + """ + flag + """ + return 1 if random.random() > 0.5000001 else -1 + + +def hsv_aug(img): + """ + cvtColor + """ + hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) + delta = 0.001 * random.random() * flag() + hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta) + new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) + return new_img + + +def blur(img): + """ + blur + """ + h, w, _ = img.shape + if h > 10 and w > 10: + return cv2.GaussianBlur(img, (5, 5), 1) + else: + return img + + +def jitter(img): + """ + jitter + """ + w, h, _ = img.shape + if h > 10 and w > 10: + thres = min(w, h) + s = int(random.random() * thres * 0.01) + src_img = img.copy() + for i in range(s): + img[i:, i:, :] = src_img[:w - i, :h - i, :] + return img + else: + return img + + +def add_gasuss_noise(image, mean=0, var=0.1): + """ + Gasuss noise + """ + + noise = np.random.normal(mean, var**0.5, image.shape) + out = image + 0.5 * noise + out = np.clip(out, 0, 255) + out = np.uint8(out) + return out + + +def get_crop(image): + """ + random crop + """ + h, w, _ = image.shape + top_min = 1 + top_max = 8 + top_crop = int(random.randint(top_min, top_max)) + top_crop = min(top_crop, h - 1) + crop_img = image.copy() + ratio = random.randint(0, 1) + if ratio: + crop_img = crop_img[top_crop:h, :, :] + else: + crop_img = crop_img[0:h - top_crop, :, :] + return crop_img + + +def rad(x): + """ + rad + """ + return x * np.pi / 180 + + +def get_warpR(config): + """ + get_warpR + """ + anglex, angley, anglez, fov, w, h, r = \ + config.anglex, config.angley, config.anglez, config.fov, config.w, config.h, config.r + if w > 69 and w < 112: + anglex = anglex * 1.5 + + z = np.sqrt(w**2 + h**2) / 2 / np.tan(rad(fov / 2)) + # Homogeneous coordinate transformation matrix + rx = np.array([[1, 0, 0, 0], + [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [ + 0, + -np.sin(rad(anglex)), + np.cos(rad(anglex)), + 0, + ], [0, 0, 0, 1]], np.float32) + ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0], + [0, 1, 0, 0], [ + -np.sin(rad(angley)), + 0, + np.cos(rad(angley)), + 0, + ], [0, 0, 0, 1]], np.float32) + rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0], + [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0], + [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) + r = rx.dot(ry).dot(rz) + # generate 4 points + pcenter = np.array([h / 2, w / 2, 0, 0], np.float32) + p1 = np.array([0, 0, 0, 0], np.float32) - pcenter + p2 = np.array([w, 0, 0, 0], np.float32) - pcenter + p3 = np.array([0, h, 0, 0], np.float32) - pcenter + p4 = np.array([w, h, 0, 0], np.float32) - pcenter + dst1 = r.dot(p1) + dst2 = r.dot(p2) + dst3 = r.dot(p3) + dst4 = r.dot(p4) + list_dst = np.array([dst1, dst2, dst3, dst4]) + org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32) + dst = np.zeros((4, 2), np.float32) + # Project onto the image plane + dst[:, 0] = list_dst[:, 0] * z / (z - list_dst[:, 2]) + pcenter[0] + dst[:, 1] = list_dst[:, 1] * z / (z - list_dst[:, 2]) + pcenter[1] + + warpR = cv2.getPerspectiveTransform(org, dst) + + dst1, dst2, dst3, dst4 = dst + r1 = int(min(dst1[1], dst2[1])) + r2 = int(max(dst3[1], dst4[1])) + c1 = int(min(dst1[0], dst3[0])) + c2 = int(max(dst2[0], dst4[0])) + + try: + ratio = min(1.0 * h / (r2 - r1), 1.0 * w / (c2 - c1)) + + dx = -c1 + dy = -r1 + T1 = np.float32([[1., 0, dx], [0, 1., dy], [0, 0, 1.0 / ratio]]) + ret = T1.dot(warpR) + except: + ratio = 1.0 + T1 = np.float32([[1., 0, 0], [0, 1., 0], [0, 0, 1.]]) + ret = T1 + return ret, (-r1, -c1), ratio, dst + + +def get_warpAffine(config): + """ + get_warpAffine + """ + anglez = config.anglez + rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0], + [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0]], np.float32) + return rz diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/sast_process.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/sast_process.py new file mode 100644 index 0000000000000000000000000000000000000000..08d03b194dcfab92ab59329857d4a1326531218e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/sast_process.py @@ -0,0 +1,777 @@ +#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +#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. +""" +This part code is refered from: +https://github.com/songdejia/EAST/blob/master/data_utils.py +""" +import math +import cv2 +import numpy as np +import json +import sys +import os + +__all__ = ['SASTProcessTrain'] + + +class SASTProcessTrain(object): + def __init__(self, + image_shape=[512, 512], + min_crop_size=24, + min_crop_side_ratio=0.3, + min_text_size=10, + max_text_size=512, + **kwargs): + self.input_size = image_shape[1] + self.min_crop_size = min_crop_size + self.min_crop_side_ratio = min_crop_side_ratio + self.min_text_size = min_text_size + self.max_text_size = max_text_size + + def quad_area(self, poly): + """ + compute area of a polygon + :param poly: + :return: + """ + edge = [(poly[1][0] - poly[0][0]) * (poly[1][1] + poly[0][1]), + (poly[2][0] - poly[1][0]) * (poly[2][1] + poly[1][1]), + (poly[3][0] - poly[2][0]) * (poly[3][1] + poly[2][1]), + (poly[0][0] - poly[3][0]) * (poly[0][1] + poly[3][1])] + return np.sum(edge) / 2. + + def gen_quad_from_poly(self, poly): + """ + Generate min area quad from poly. + """ + point_num = poly.shape[0] + min_area_quad = np.zeros((4, 2), dtype=np.float32) + if True: + rect = cv2.minAreaRect(poly.astype( + np.int32)) # (center (x,y), (width, height), angle of rotation) + center_point = rect[0] + box = np.array(cv2.boxPoints(rect)) + + first_point_idx = 0 + min_dist = 1e4 + for i in range(4): + dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \ + np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \ + np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \ + np.linalg.norm(box[(i + 3) % 4] - poly[-1]) + if dist < min_dist: + min_dist = dist + first_point_idx = i + for i in range(4): + min_area_quad[i] = box[(first_point_idx + i) % 4] + + return min_area_quad + + def check_and_validate_polys(self, polys, tags, xxx_todo_changeme): + """ + check so that the text poly is in the same direction, + and also filter some invalid polygons + :param polys: + :param tags: + :return: + """ + (h, w) = xxx_todo_changeme + if polys.shape[0] == 0: + return polys, np.array([]), np.array([]) + polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w - 1) + polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h - 1) + + validated_polys = [] + validated_tags = [] + hv_tags = [] + for poly, tag in zip(polys, tags): + quad = self.gen_quad_from_poly(poly) + p_area = self.quad_area(quad) + if abs(p_area) < 1: + print('invalid poly') + continue + if p_area > 0: + if tag == False: + print('poly in wrong direction') + tag = True # reversed cases should be ignore + poly = poly[(0, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, + 1), :] + quad = quad[(0, 3, 2, 1), :] + + len_w = np.linalg.norm(quad[0] - quad[1]) + np.linalg.norm(quad[3] - + quad[2]) + len_h = np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - + quad[2]) + hv_tag = 1 + + if len_w * 2.0 < len_h: + hv_tag = 0 + + validated_polys.append(poly) + validated_tags.append(tag) + hv_tags.append(hv_tag) + return np.array(validated_polys), np.array(validated_tags), np.array( + hv_tags) + + def crop_area(self, + im, + polys, + tags, + hv_tags, + crop_background=False, + max_tries=25): + """ + make random crop from the input image + :param im: + :param polys: + :param tags: + :param crop_background: + :param max_tries: 50 -> 25 + :return: + """ + h, w, _ = im.shape + pad_h = h // 10 + pad_w = w // 10 + h_array = np.zeros((h + pad_h * 2), dtype=np.int32) + w_array = np.zeros((w + pad_w * 2), dtype=np.int32) + for poly in polys: + poly = np.round(poly, decimals=0).astype(np.int32) + minx = np.min(poly[:, 0]) + maxx = np.max(poly[:, 0]) + w_array[minx + pad_w:maxx + pad_w] = 1 + miny = np.min(poly[:, 1]) + maxy = np.max(poly[:, 1]) + h_array[miny + pad_h:maxy + pad_h] = 1 + # ensure the cropped area not across a text + h_axis = np.where(h_array == 0)[0] + w_axis = np.where(w_array == 0)[0] + if len(h_axis) == 0 or len(w_axis) == 0: + return im, polys, tags, hv_tags + for i in range(max_tries): + xx = np.random.choice(w_axis, size=2) + xmin = np.min(xx) - pad_w + xmax = np.max(xx) - pad_w + xmin = np.clip(xmin, 0, w - 1) + xmax = np.clip(xmax, 0, w - 1) + yy = np.random.choice(h_axis, size=2) + ymin = np.min(yy) - pad_h + ymax = np.max(yy) - pad_h + ymin = np.clip(ymin, 0, h - 1) + ymax = np.clip(ymax, 0, h - 1) + # if xmax - xmin < ARGS.min_crop_side_ratio * w or \ + # ymax - ymin < ARGS.min_crop_side_ratio * h: + if xmax - xmin < self.min_crop_size or \ + ymax - ymin < self.min_crop_size: + # area too small + continue + if polys.shape[0] != 0: + poly_axis_in_area = (polys[:, :, 0] >= xmin) & (polys[:, :, 0] <= xmax) \ + & (polys[:, :, 1] >= ymin) & (polys[:, :, 1] <= ymax) + selected_polys = np.where( + np.sum(poly_axis_in_area, axis=1) == 4)[0] + else: + selected_polys = [] + if len(selected_polys) == 0: + # no text in this area + if crop_background: + return im[ymin : ymax + 1, xmin : xmax + 1, :], \ + polys[selected_polys], tags[selected_polys], hv_tags[selected_polys] + else: + continue + im = im[ymin:ymax + 1, xmin:xmax + 1, :] + polys = polys[selected_polys] + tags = tags[selected_polys] + hv_tags = hv_tags[selected_polys] + polys[:, :, 0] -= xmin + polys[:, :, 1] -= ymin + return im, polys, tags, hv_tags + + return im, polys, tags, hv_tags + + def generate_direction_map(self, poly_quads, direction_map): + """ + """ + width_list = [] + height_list = [] + for quad in poly_quads: + quad_w = (np.linalg.norm(quad[0] - quad[1]) + + np.linalg.norm(quad[2] - quad[3])) / 2.0 + quad_h = (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[2] - quad[1])) / 2.0 + width_list.append(quad_w) + height_list.append(quad_h) + norm_width = max(sum(width_list) / (len(width_list) + 1e-6), 1.0) + average_height = max(sum(height_list) / (len(height_list) + 1e-6), 1.0) + + for quad in poly_quads: + direct_vector_full = ( + (quad[1] + quad[2]) - (quad[0] + quad[3])) / 2.0 + direct_vector = direct_vector_full / ( + np.linalg.norm(direct_vector_full) + 1e-6) * norm_width + direction_label = tuple( + map(float, [ + direct_vector[0], direct_vector[1], 1.0 / (average_height + + 1e-6) + ])) + cv2.fillPoly(direction_map, + quad.round().astype(np.int32)[np.newaxis, :, :], + direction_label) + return direction_map + + def calculate_average_height(self, poly_quads): + """ + """ + height_list = [] + for quad in poly_quads: + quad_h = (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[2] - quad[1])) / 2.0 + height_list.append(quad_h) + average_height = max(sum(height_list) / len(height_list), 1.0) + return average_height + + def generate_tcl_label(self, + hw, + polys, + tags, + ds_ratio, + tcl_ratio=0.3, + shrink_ratio_of_width=0.15): + """ + Generate polygon. + """ + h, w = hw + h, w = int(h * ds_ratio), int(w * ds_ratio) + polys = polys * ds_ratio + + score_map = np.zeros( + ( + h, + w, ), dtype=np.float32) + tbo_map = np.zeros((h, w, 5), dtype=np.float32) + training_mask = np.ones( + ( + h, + w, ), dtype=np.float32) + direction_map = np.ones((h, w, 3)) * np.array([0, 0, 1]).reshape( + [1, 1, 3]).astype(np.float32) + + for poly_idx, poly_tag in enumerate(zip(polys, tags)): + poly = poly_tag[0] + tag = poly_tag[1] + + # generate min_area_quad + min_area_quad, center_point = self.gen_min_area_quad_from_poly(poly) + min_area_quad_h = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[3]) + + np.linalg.norm(min_area_quad[1] - min_area_quad[2])) + min_area_quad_w = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[1]) + + np.linalg.norm(min_area_quad[2] - min_area_quad[3])) + + if min(min_area_quad_h, min_area_quad_w) < self.min_text_size * ds_ratio \ + or min(min_area_quad_h, min_area_quad_w) > self.max_text_size * ds_ratio: + continue + + if tag: + # continue + cv2.fillPoly(training_mask, + poly.astype(np.int32)[np.newaxis, :, :], 0.15) + else: + tcl_poly = self.poly2tcl(poly, tcl_ratio) + tcl_quads = self.poly2quads(tcl_poly) + poly_quads = self.poly2quads(poly) + # stcl map + stcl_quads, quad_index = self.shrink_poly_along_width( + tcl_quads, + shrink_ratio_of_width=shrink_ratio_of_width, + expand_height_ratio=1.0 / tcl_ratio) + # generate tcl map + cv2.fillPoly(score_map, + np.round(stcl_quads).astype(np.int32), 1.0) + + # generate tbo map + for idx, quad in enumerate(stcl_quads): + quad_mask = np.zeros((h, w), dtype=np.float32) + quad_mask = cv2.fillPoly( + quad_mask, + np.round(quad[np.newaxis, :, :]).astype(np.int32), 1.0) + tbo_map = self.gen_quad_tbo(poly_quads[quad_index[idx]], + quad_mask, tbo_map) + return score_map, tbo_map, training_mask + + def generate_tvo_and_tco(self, + hw, + polys, + tags, + tcl_ratio=0.3, + ds_ratio=0.25): + """ + Generate tcl map, tvo map and tbo map. + """ + h, w = hw + h, w = int(h * ds_ratio), int(w * ds_ratio) + polys = polys * ds_ratio + poly_mask = np.zeros((h, w), dtype=np.float32) + + tvo_map = np.ones((9, h, w), dtype=np.float32) + tvo_map[0:-1:2] = np.tile(np.arange(0, w), (h, 1)) + tvo_map[1:-1:2] = np.tile(np.arange(0, w), (h, 1)).T + poly_tv_xy_map = np.zeros((8, h, w), dtype=np.float32) + + # tco map + tco_map = np.ones((3, h, w), dtype=np.float32) + tco_map[0] = np.tile(np.arange(0, w), (h, 1)) + tco_map[1] = np.tile(np.arange(0, w), (h, 1)).T + poly_tc_xy_map = np.zeros((2, h, w), dtype=np.float32) + + poly_short_edge_map = np.ones((h, w), dtype=np.float32) + + for poly, poly_tag in zip(polys, tags): + + if poly_tag == True: + continue + + # adjust point order for vertical poly + poly = self.adjust_point(poly) + + # generate min_area_quad + min_area_quad, center_point = self.gen_min_area_quad_from_poly(poly) + min_area_quad_h = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[3]) + + np.linalg.norm(min_area_quad[1] - min_area_quad[2])) + min_area_quad_w = 0.5 * ( + np.linalg.norm(min_area_quad[0] - min_area_quad[1]) + + np.linalg.norm(min_area_quad[2] - min_area_quad[3])) + + # generate tcl map and text, 128 * 128 + tcl_poly = self.poly2tcl(poly, tcl_ratio) + + # generate poly_tv_xy_map + for idx in range(4): + cv2.fillPoly( + poly_tv_xy_map[2 * idx], + np.round(tcl_poly[np.newaxis, :, :]).astype(np.int32), + float(min(max(min_area_quad[idx, 0], 0), w))) + cv2.fillPoly( + poly_tv_xy_map[2 * idx + 1], + np.round(tcl_poly[np.newaxis, :, :]).astype(np.int32), + float(min(max(min_area_quad[idx, 1], 0), h))) + + # generate poly_tc_xy_map + for idx in range(2): + cv2.fillPoly( + poly_tc_xy_map[idx], + np.round(tcl_poly[np.newaxis, :, :]).astype(np.int32), + float(center_point[idx])) + + # generate poly_short_edge_map + cv2.fillPoly( + poly_short_edge_map, + np.round(tcl_poly[np.newaxis, :, :]).astype(np.int32), + float(max(min(min_area_quad_h, min_area_quad_w), 1.0))) + + # generate poly_mask and training_mask + cv2.fillPoly(poly_mask, + np.round(tcl_poly[np.newaxis, :, :]).astype(np.int32), + 1) + + tvo_map *= poly_mask + tvo_map[:8] -= poly_tv_xy_map + tvo_map[-1] /= poly_short_edge_map + tvo_map = tvo_map.transpose((1, 2, 0)) + + tco_map *= poly_mask + tco_map[:2] -= poly_tc_xy_map + tco_map[-1] /= poly_short_edge_map + tco_map = tco_map.transpose((1, 2, 0)) + + return tvo_map, tco_map + + def adjust_point(self, poly): + """ + adjust point order. + """ + point_num = poly.shape[0] + if point_num == 4: + len_1 = np.linalg.norm(poly[0] - poly[1]) + len_2 = np.linalg.norm(poly[1] - poly[2]) + len_3 = np.linalg.norm(poly[2] - poly[3]) + len_4 = np.linalg.norm(poly[3] - poly[0]) + + if (len_1 + len_3) * 1.5 < (len_2 + len_4): + poly = poly[[1, 2, 3, 0], :] + + elif point_num > 4: + vector_1 = poly[0] - poly[1] + vector_2 = poly[1] - poly[2] + cos_theta = np.dot(vector_1, vector_2) / ( + np.linalg.norm(vector_1) * np.linalg.norm(vector_2) + 1e-6) + theta = np.arccos(np.round(cos_theta, decimals=4)) + + if abs(theta) > (70 / 180 * math.pi): + index = list(range(1, point_num)) + [0] + poly = poly[np.array(index), :] + return poly + + def gen_min_area_quad_from_poly(self, poly): + """ + Generate min area quad from poly. + """ + point_num = poly.shape[0] + min_area_quad = np.zeros((4, 2), dtype=np.float32) + if point_num == 4: + min_area_quad = poly + center_point = np.sum(poly, axis=0) / 4 + else: + rect = cv2.minAreaRect(poly.astype( + np.int32)) # (center (x,y), (width, height), angle of rotation) + center_point = rect[0] + box = np.array(cv2.boxPoints(rect)) + + first_point_idx = 0 + min_dist = 1e4 + for i in range(4): + dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \ + np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \ + np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \ + np.linalg.norm(box[(i + 3) % 4] - poly[-1]) + if dist < min_dist: + min_dist = dist + first_point_idx = i + + for i in range(4): + min_area_quad[i] = box[(first_point_idx + i) % 4] + + return min_area_quad, center_point + + def shrink_quad_along_width(self, + quad, + begin_width_ratio=0., + end_width_ratio=1.): + """ + Generate shrink_quad_along_width. + """ + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + def shrink_poly_along_width(self, + quads, + shrink_ratio_of_width, + expand_height_ratio=1.0): + """ + shrink poly with given length. + """ + upper_edge_list = [] + + def get_cut_info(edge_len_list, cut_len): + for idx, edge_len in enumerate(edge_len_list): + cut_len -= edge_len + if cut_len <= 0.000001: + ratio = (cut_len + edge_len_list[idx]) / edge_len_list[idx] + return idx, ratio + + for quad in quads: + upper_edge_len = np.linalg.norm(quad[0] - quad[1]) + upper_edge_list.append(upper_edge_len) + + # length of left edge and right edge. + left_length = np.linalg.norm(quads[0][0] - quads[0][ + 3]) * expand_height_ratio + right_length = np.linalg.norm(quads[-1][1] - quads[-1][ + 2]) * expand_height_ratio + + shrink_length = min(left_length, right_length, + sum(upper_edge_list)) * shrink_ratio_of_width + # shrinking length + upper_len_left = shrink_length + upper_len_right = sum(upper_edge_list) - shrink_length + + left_idx, left_ratio = get_cut_info(upper_edge_list, upper_len_left) + left_quad = self.shrink_quad_along_width( + quads[left_idx], begin_width_ratio=left_ratio, end_width_ratio=1) + right_idx, right_ratio = get_cut_info(upper_edge_list, upper_len_right) + right_quad = self.shrink_quad_along_width( + quads[right_idx], begin_width_ratio=0, end_width_ratio=right_ratio) + + out_quad_list = [] + if left_idx == right_idx: + out_quad_list.append( + [left_quad[0], right_quad[1], right_quad[2], left_quad[3]]) + else: + out_quad_list.append(left_quad) + for idx in range(left_idx + 1, right_idx): + out_quad_list.append(quads[idx]) + out_quad_list.append(right_quad) + + return np.array(out_quad_list), list(range(left_idx, right_idx + 1)) + + def vector_angle(self, A, B): + """ + Calculate the angle between vector AB and x-axis positive direction. + """ + AB = np.array([B[1] - A[1], B[0] - A[0]]) + return np.arctan2(*AB) + + def theta_line_cross_point(self, theta, point): + """ + Calculate the line through given point and angle in ax + by + c =0 form. + """ + x, y = point + cos = np.cos(theta) + sin = np.sin(theta) + return [sin, -cos, cos * y - sin * x] + + def line_cross_two_point(self, A, B): + """ + Calculate the line through given point A and B in ax + by + c =0 form. + """ + angle = self.vector_angle(A, B) + return self.theta_line_cross_point(angle, A) + + def average_angle(self, poly): + """ + Calculate the average angle between left and right edge in given poly. + """ + p0, p1, p2, p3 = poly + angle30 = self.vector_angle(p3, p0) + angle21 = self.vector_angle(p2, p1) + return (angle30 + angle21) / 2 + + def line_cross_point(self, line1, line2): + """ + line1 and line2 in 0=ax+by+c form, compute the cross point of line1 and line2 + """ + a1, b1, c1 = line1 + a2, b2, c2 = line2 + d = a1 * b2 - a2 * b1 + + if d == 0: + #print("line1", line1) + #print("line2", line2) + print('Cross point does not exist') + return np.array([0, 0], dtype=np.float32) + else: + x = (b1 * c2 - b2 * c1) / d + y = (a2 * c1 - a1 * c2) / d + + return np.array([x, y], dtype=np.float32) + + def quad2tcl(self, poly, ratio): + """ + Generate center line by poly clock-wise point. (4, 2) + """ + ratio_pair = np.array( + [[0.5 - ratio / 2], [0.5 + ratio / 2]], dtype=np.float32) + p0_3 = poly[0] + (poly[3] - poly[0]) * ratio_pair + p1_2 = poly[1] + (poly[2] - poly[1]) * ratio_pair + return np.array([p0_3[0], p1_2[0], p1_2[1], p0_3[1]]) + + def poly2tcl(self, poly, ratio): + """ + Generate center line by poly clock-wise point. + """ + ratio_pair = np.array( + [[0.5 - ratio / 2], [0.5 + ratio / 2]], dtype=np.float32) + tcl_poly = np.zeros_like(poly) + point_num = poly.shape[0] + + for idx in range(point_num // 2): + point_pair = poly[idx] + (poly[point_num - 1 - idx] - poly[idx] + ) * ratio_pair + tcl_poly[idx] = point_pair[0] + tcl_poly[point_num - 1 - idx] = point_pair[1] + return tcl_poly + + def gen_quad_tbo(self, quad, tcl_mask, tbo_map): + """ + Generate tbo_map for give quad. + """ + # upper and lower line function: ax + by + c = 0; + up_line = self.line_cross_two_point(quad[0], quad[1]) + lower_line = self.line_cross_two_point(quad[3], quad[2]) + + quad_h = 0.5 * (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[1] - quad[2])) + quad_w = 0.5 * (np.linalg.norm(quad[0] - quad[1]) + + np.linalg.norm(quad[2] - quad[3])) + + # average angle of left and right line. + angle = self.average_angle(quad) + + xy_in_poly = np.argwhere(tcl_mask == 1) + for y, x in xy_in_poly: + point = (x, y) + line = self.theta_line_cross_point(angle, point) + cross_point_upper = self.line_cross_point(up_line, line) + cross_point_lower = self.line_cross_point(lower_line, line) + ##FIX, offset reverse + upper_offset_x, upper_offset_y = cross_point_upper - point + lower_offset_x, lower_offset_y = cross_point_lower - point + tbo_map[y, x, 0] = upper_offset_y + tbo_map[y, x, 1] = upper_offset_x + tbo_map[y, x, 2] = lower_offset_y + tbo_map[y, x, 3] = lower_offset_x + tbo_map[y, x, 4] = 1.0 / max(min(quad_h, quad_w), 1.0) * 2 + return tbo_map + + def poly2quads(self, poly): + """ + Split poly into quads. + """ + quad_list = [] + point_num = poly.shape[0] + + # point pair + point_pair_list = [] + for idx in range(point_num // 2): + point_pair = [poly[idx], poly[point_num - 1 - idx]] + point_pair_list.append(point_pair) + + quad_num = point_num // 2 - 1 + for idx in range(quad_num): + # reshape and adjust to clock-wise + quad_list.append((np.array(point_pair_list)[[idx, idx + 1]] + ).reshape(4, 2)[[0, 2, 3, 1]]) + + return np.array(quad_list) + + def __call__(self, data): + im = data['image'] + text_polys = data['polys'] + text_tags = data['ignore_tags'] + if im is None: + return None + if text_polys.shape[0] == 0: + return None + + h, w, _ = im.shape + text_polys, text_tags, hv_tags = self.check_and_validate_polys( + text_polys, text_tags, (h, w)) + + if text_polys.shape[0] == 0: + return None + + #set aspect ratio and keep area fix + asp_scales = np.arange(1.0, 1.55, 0.1) + asp_scale = np.random.choice(asp_scales) + + if np.random.rand() < 0.5: + asp_scale = 1.0 / asp_scale + asp_scale = math.sqrt(asp_scale) + + asp_wx = asp_scale + asp_hy = 1.0 / asp_scale + im = cv2.resize(im, dsize=None, fx=asp_wx, fy=asp_hy) + text_polys[:, :, 0] *= asp_wx + text_polys[:, :, 1] *= asp_hy + + h, w, _ = im.shape + if max(h, w) > 2048: + rd_scale = 2048.0 / max(h, w) + im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale) + text_polys *= rd_scale + h, w, _ = im.shape + if min(h, w) < 16: + return None + + #no background + im, text_polys, text_tags, hv_tags = self.crop_area(im, \ + text_polys, text_tags, hv_tags, crop_background=False) + + if text_polys.shape[0] == 0: + return None + #continue for all ignore case + if np.sum((text_tags * 1.0)) >= text_tags.size: + return None + new_h, new_w, _ = im.shape + if (new_h is None) or (new_w is None): + return None + #resize image + std_ratio = float(self.input_size) / max(new_w, new_h) + rand_scales = np.array( + [0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.0, 1.0, 1.0, 1.0]) + rz_scale = std_ratio * np.random.choice(rand_scales) + im = cv2.resize(im, dsize=None, fx=rz_scale, fy=rz_scale) + text_polys[:, :, 0] *= rz_scale + text_polys[:, :, 1] *= rz_scale + + #add gaussian blur + if np.random.rand() < 0.1 * 0.5: + ks = np.random.permutation(5)[0] + 1 + ks = int(ks / 2) * 2 + 1 + im = cv2.GaussianBlur(im, ksize=(ks, ks), sigmaX=0, sigmaY=0) + #add brighter + if np.random.rand() < 0.1 * 0.5: + im = im * (1.0 + np.random.rand() * 0.5) + im = np.clip(im, 0.0, 255.0) + #add darker + if np.random.rand() < 0.1 * 0.5: + im = im * (1.0 - np.random.rand() * 0.5) + im = np.clip(im, 0.0, 255.0) + + # Padding the im to [input_size, input_size] + new_h, new_w, _ = im.shape + if min(new_w, new_h) < self.input_size * 0.5: + return None + + im_padded = np.ones( + (self.input_size, self.input_size, 3), dtype=np.float32) + im_padded[:, :, 2] = 0.485 * 255 + im_padded[:, :, 1] = 0.456 * 255 + im_padded[:, :, 0] = 0.406 * 255 + + # Random the start position + del_h = self.input_size - new_h + del_w = self.input_size - new_w + sh, sw = 0, 0 + if del_h > 1: + sh = int(np.random.rand() * del_h) + if del_w > 1: + sw = int(np.random.rand() * del_w) + + # Padding + im_padded[sh:sh + new_h, sw:sw + new_w, :] = im.copy() + text_polys[:, :, 0] += sw + text_polys[:, :, 1] += sh + + score_map, border_map, training_mask = self.generate_tcl_label( + (self.input_size, self.input_size), text_polys, text_tags, 0.25) + + # SAST head + tvo_map, tco_map = self.generate_tvo_and_tco( + (self.input_size, self.input_size), + text_polys, + text_tags, + tcl_ratio=0.3, + ds_ratio=0.25) + # print("test--------tvo_map shape:", tvo_map.shape) + + im_padded[:, :, 2] -= 0.485 * 255 + im_padded[:, :, 1] -= 0.456 * 255 + im_padded[:, :, 0] -= 0.406 * 255 + im_padded[:, :, 2] /= (255.0 * 0.229) + im_padded[:, :, 1] /= (255.0 * 0.224) + im_padded[:, :, 0] /= (255.0 * 0.225) + im_padded = im_padded.transpose((2, 0, 1)) + + data['image'] = im_padded[::-1, :, :] + data['score_map'] = score_map[np.newaxis, :, :] + data['border_map'] = border_map.transpose((2, 0, 1)) + data['training_mask'] = training_mask[np.newaxis, :, :] + data['tvo_map'] = tvo_map.transpose((2, 0, 1)) + data['tco_map'] = tco_map.transpose((2, 0, 1)) + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ssl_img_aug.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ssl_img_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ed6ac3e230ae85754bf40189c392c7e6e29b63 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/ssl_img_aug.py @@ -0,0 +1,60 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +import cv2 +import numpy as np +import random +from PIL import Image + +from .rec_img_aug import resize_norm_img + + +class SSLRotateResize(object): + def __init__(self, + image_shape, + padding=False, + select_all=True, + mode="train", + **kwargs): + self.image_shape = image_shape + self.padding = padding + self.select_all = select_all + self.mode = mode + + def __call__(self, data): + img = data["image"] + + data["image_r90"] = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) + data["image_r180"] = cv2.rotate(data["image_r90"], + cv2.ROTATE_90_CLOCKWISE) + data["image_r270"] = cv2.rotate(data["image_r180"], + cv2.ROTATE_90_CLOCKWISE) + + images = [] + for key in ["image", "image_r90", "image_r180", "image_r270"]: + images.append( + resize_norm_img( + data.pop(key), + image_shape=self.image_shape, + padding=self.padding)[0]) + data["image"] = np.stack(images, axis=0) + data["label"] = np.array(list(range(4))) + if not self.select_all: + data["image"] = data["image"][0::2] # just choose 0 and 180 + data["label"] = data["label"][0:2] # label needs to be continuous + if self.mode == "test": + data["image"] = data["image"][0] + data["label"] = data["label"][0] + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/table_ops.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/table_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c2fb2be6c80fdeb637717af2bbe122e1be999c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/table_ops.py @@ -0,0 +1,229 @@ +""" +# 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. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import sys +import six +import cv2 +import numpy as np + + +class GenTableMask(object): + """ gen table mask """ + + def __init__(self, shrink_h_max, shrink_w_max, mask_type=0, **kwargs): + self.shrink_h_max = 5 + self.shrink_w_max = 5 + self.mask_type = mask_type + + def projection(self, erosion, h, w, spilt_threshold=0): + # 水平投影 + projection_map = np.ones_like(erosion) + project_val_array = [0 for _ in range(0, h)] + + for j in range(0, h): + for i in range(0, w): + if erosion[j, i] == 255: + project_val_array[j] += 1 + # 根据数组,获取切割点 + start_idx = 0 # 记录进入字符区的索引 + end_idx = 0 # 记录进入空白区域的索引 + in_text = False # 是否遍历到了字符区内 + box_list = [] + for i in range(len(project_val_array)): + if in_text == False and project_val_array[ + i] > spilt_threshold: # 进入字符区了 + in_text = True + start_idx = i + elif project_val_array[ + i] <= spilt_threshold and in_text == True: # 进入空白区了 + end_idx = i + in_text = False + if end_idx - start_idx <= 2: + continue + box_list.append((start_idx, end_idx + 1)) + + if in_text: + box_list.append((start_idx, h - 1)) + # 绘制投影直方图 + for j in range(0, h): + for i in range(0, project_val_array[j]): + projection_map[j, i] = 0 + return box_list, projection_map + + def projection_cx(self, box_img): + box_gray_img = cv2.cvtColor(box_img, cv2.COLOR_BGR2GRAY) + h, w = box_gray_img.shape + # 灰度图片进行二值化处理 + ret, thresh1 = cv2.threshold(box_gray_img, 200, 255, + cv2.THRESH_BINARY_INV) + # 纵向腐蚀 + if h < w: + kernel = np.ones((2, 1), np.uint8) + erode = cv2.erode(thresh1, kernel, iterations=1) + else: + erode = thresh1 + # 水平膨胀 + kernel = np.ones((1, 5), np.uint8) + erosion = cv2.dilate(erode, kernel, iterations=1) + # 水平投影 + projection_map = np.ones_like(erosion) + project_val_array = [0 for _ in range(0, h)] + + for j in range(0, h): + for i in range(0, w): + if erosion[j, i] == 255: + project_val_array[j] += 1 + # 根据数组,获取切割点 + start_idx = 0 # 记录进入字符区的索引 + end_idx = 0 # 记录进入空白区域的索引 + in_text = False # 是否遍历到了字符区内 + box_list = [] + spilt_threshold = 0 + for i in range(len(project_val_array)): + if in_text == False and project_val_array[ + i] > spilt_threshold: # 进入字符区了 + in_text = True + start_idx = i + elif project_val_array[ + i] <= spilt_threshold and in_text == True: # 进入空白区了 + end_idx = i + in_text = False + if end_idx - start_idx <= 2: + continue + box_list.append((start_idx, end_idx + 1)) + + if in_text: + box_list.append((start_idx, h - 1)) + # 绘制投影直方图 + for j in range(0, h): + for i in range(0, project_val_array[j]): + projection_map[j, i] = 0 + split_bbox_list = [] + if len(box_list) > 1: + for i, (h_start, h_end) in enumerate(box_list): + if i == 0: + h_start = 0 + if i == len(box_list): + h_end = h + word_img = erosion[h_start:h_end + 1, :] + word_h, word_w = word_img.shape + w_split_list, w_projection_map = self.projection(word_img.T, + word_w, word_h) + w_start, w_end = w_split_list[0][0], w_split_list[-1][1] + if h_start > 0: + h_start -= 1 + h_end += 1 + word_img = box_img[h_start:h_end + 1:, w_start:w_end + 1, :] + split_bbox_list.append([w_start, h_start, w_end, h_end]) + else: + split_bbox_list.append([0, 0, w, h]) + return split_bbox_list + + def shrink_bbox(self, bbox): + left, top, right, bottom = bbox + sh_h = min(max(int((bottom - top) * 0.1), 1), self.shrink_h_max) + sh_w = min(max(int((right - left) * 0.1), 1), self.shrink_w_max) + left_new = left + sh_w + right_new = right - sh_w + top_new = top + sh_h + bottom_new = bottom - sh_h + if left_new >= right_new: + left_new = left + right_new = right + if top_new >= bottom_new: + top_new = top + bottom_new = bottom + return [left_new, top_new, right_new, bottom_new] + + def __call__(self, data): + img = data['image'] + cells = data['cells'] + height, width = img.shape[0:2] + if self.mask_type == 1: + mask_img = np.zeros((height, width), dtype=np.float32) + else: + mask_img = np.zeros((height, width, 3), dtype=np.float32) + cell_num = len(cells) + for cno in range(cell_num): + if "bbox" in cells[cno]: + bbox = cells[cno]['bbox'] + left, top, right, bottom = bbox + box_img = img[top:bottom, left:right, :].copy() + split_bbox_list = self.projection_cx(box_img) + for sno in range(len(split_bbox_list)): + split_bbox_list[sno][0] += left + split_bbox_list[sno][1] += top + split_bbox_list[sno][2] += left + split_bbox_list[sno][3] += top + + for sno in range(len(split_bbox_list)): + left, top, right, bottom = split_bbox_list[sno] + left, top, right, bottom = self.shrink_bbox( + [left, top, right, bottom]) + if self.mask_type == 1: + mask_img[top:bottom, left:right] = 1.0 + data['mask_img'] = mask_img + else: + mask_img[top:bottom, left:right, :] = (255, 255, 255) + data['image'] = mask_img + return data + + +class ResizeTableImage(object): + def __init__(self, max_len, resize_bboxes=False, infer_mode=False, + **kwargs): + super(ResizeTableImage, self).__init__() + self.max_len = max_len + self.resize_bboxes = resize_bboxes + self.infer_mode = infer_mode + + def __call__(self, data): + img = data['image'] + height, width = img.shape[0:2] + ratio = self.max_len / (max(height, width) * 1.0) + resize_h = int(height * ratio) + resize_w = int(width * ratio) + resize_img = cv2.resize(img, (resize_w, resize_h)) + if self.resize_bboxes and not self.infer_mode: + data['bboxes'] = data['bboxes'] * ratio + data['image'] = resize_img + data['src_img'] = img + data['shape'] = np.array([height, width, ratio, ratio]) + data['max_len'] = self.max_len + return data + + +class PaddingTableImage(object): + def __init__(self, size, **kwargs): + super(PaddingTableImage, self).__init__() + self.size = size + + def __call__(self, data): + img = data['image'] + pad_h, pad_w = self.size + padding_img = np.zeros((pad_h, pad_w, 3), dtype=np.float32) + height, width = img.shape[0:2] + padding_img[0:height, 0:width, :] = img.copy() + data['image'] = padding_img + shape = data['shape'].tolist() + shape.extend([pad_h, pad_w]) + data['shape'] = np.array(shape) + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bca262638efb00190aaf2b6328cd34a9e87ba131 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/__init__.py @@ -0,0 +1,17 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from .augment import tia_perspective, tia_distort, tia_stretch + +__all__ = ['tia_distort', 'tia_stretch', 'tia_perspective'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/augment.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/augment.py new file mode 100644 index 0000000000000000000000000000000000000000..2d15dd5f353c72a6cc3876481c423d81a8175c95 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/augment.py @@ -0,0 +1,120 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/RubanSeven/Text-Image-Augmentation-python/blob/master/augment.py +""" + +import numpy as np +from .warp_mls import WarpMLS + + +def tia_distort(src, segment=4): + img_h, img_w = src.shape[:2] + + cut = img_w // segment + thresh = cut // 3 + + src_pts = list() + dst_pts = list() + + src_pts.append([0, 0]) + src_pts.append([img_w, 0]) + src_pts.append([img_w, img_h]) + src_pts.append([0, img_h]) + + dst_pts.append([np.random.randint(thresh), np.random.randint(thresh)]) + dst_pts.append( + [img_w - np.random.randint(thresh), np.random.randint(thresh)]) + dst_pts.append( + [img_w - np.random.randint(thresh), img_h - np.random.randint(thresh)]) + dst_pts.append( + [np.random.randint(thresh), img_h - np.random.randint(thresh)]) + + half_thresh = thresh * 0.5 + + for cut_idx in np.arange(1, segment, 1): + src_pts.append([cut * cut_idx, 0]) + src_pts.append([cut * cut_idx, img_h]) + dst_pts.append([ + cut * cut_idx + np.random.randint(thresh) - half_thresh, + np.random.randint(thresh) - half_thresh + ]) + dst_pts.append([ + cut * cut_idx + np.random.randint(thresh) - half_thresh, + img_h + np.random.randint(thresh) - half_thresh + ]) + + trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h) + dst = trans.generate() + + return dst + + +def tia_stretch(src, segment=4): + img_h, img_w = src.shape[:2] + + cut = img_w // segment + thresh = cut * 4 // 5 + + src_pts = list() + dst_pts = list() + + src_pts.append([0, 0]) + src_pts.append([img_w, 0]) + src_pts.append([img_w, img_h]) + src_pts.append([0, img_h]) + + dst_pts.append([0, 0]) + dst_pts.append([img_w, 0]) + dst_pts.append([img_w, img_h]) + dst_pts.append([0, img_h]) + + half_thresh = thresh * 0.5 + + for cut_idx in np.arange(1, segment, 1): + move = np.random.randint(thresh) - half_thresh + src_pts.append([cut * cut_idx, 0]) + src_pts.append([cut * cut_idx, img_h]) + dst_pts.append([cut * cut_idx + move, 0]) + dst_pts.append([cut * cut_idx + move, img_h]) + + trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h) + dst = trans.generate() + + return dst + + +def tia_perspective(src): + img_h, img_w = src.shape[:2] + + thresh = img_h // 2 + + src_pts = list() + dst_pts = list() + + src_pts.append([0, 0]) + src_pts.append([img_w, 0]) + src_pts.append([img_w, img_h]) + src_pts.append([0, img_h]) + + dst_pts.append([0, np.random.randint(thresh)]) + dst_pts.append([img_w, np.random.randint(thresh)]) + dst_pts.append([img_w, img_h - np.random.randint(thresh)]) + dst_pts.append([0, img_h - np.random.randint(thresh)]) + + trans = WarpMLS(src, src_pts, dst_pts, img_w, img_h) + dst = trans.generate() + + return dst \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/warp_mls.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/warp_mls.py new file mode 100644 index 0000000000000000000000000000000000000000..75de11115cf9ba824a7cd62b8b880ea7f99e4cb2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/text_image_aug/warp_mls.py @@ -0,0 +1,168 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/RubanSeven/Text-Image-Augmentation-python/blob/master/warp_mls.py +""" + +import numpy as np + + +class WarpMLS: + def __init__(self, src, src_pts, dst_pts, dst_w, dst_h, trans_ratio=1.): + self.src = src + self.src_pts = src_pts + self.dst_pts = dst_pts + self.pt_count = len(self.dst_pts) + self.dst_w = dst_w + self.dst_h = dst_h + self.trans_ratio = trans_ratio + self.grid_size = 100 + self.rdx = np.zeros((self.dst_h, self.dst_w)) + self.rdy = np.zeros((self.dst_h, self.dst_w)) + + @staticmethod + def __bilinear_interp(x, y, v11, v12, v21, v22): + return (v11 * (1 - y) + v12 * y) * (1 - x) + (v21 * + (1 - y) + v22 * y) * x + + def generate(self): + self.calc_delta() + return self.gen_img() + + def calc_delta(self): + w = np.zeros(self.pt_count, dtype=np.float32) + + if self.pt_count < 2: + return + + i = 0 + while 1: + if self.dst_w <= i < self.dst_w + self.grid_size - 1: + i = self.dst_w - 1 + elif i >= self.dst_w: + break + + j = 0 + while 1: + if self.dst_h <= j < self.dst_h + self.grid_size - 1: + j = self.dst_h - 1 + elif j >= self.dst_h: + break + + sw = 0 + swp = np.zeros(2, dtype=np.float32) + swq = np.zeros(2, dtype=np.float32) + new_pt = np.zeros(2, dtype=np.float32) + cur_pt = np.array([i, j], dtype=np.float32) + + k = 0 + for k in range(self.pt_count): + if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]: + break + + w[k] = 1. / ( + (i - self.dst_pts[k][0]) * (i - self.dst_pts[k][0]) + + (j - self.dst_pts[k][1]) * (j - self.dst_pts[k][1])) + + sw += w[k] + swp = swp + w[k] * np.array(self.dst_pts[k]) + swq = swq + w[k] * np.array(self.src_pts[k]) + + if k == self.pt_count - 1: + pstar = 1 / sw * swp + qstar = 1 / sw * swq + + miu_s = 0 + for k in range(self.pt_count): + if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]: + continue + pt_i = self.dst_pts[k] - pstar + miu_s += w[k] * np.sum(pt_i * pt_i) + + cur_pt -= pstar + cur_pt_j = np.array([-cur_pt[1], cur_pt[0]]) + + for k in range(self.pt_count): + if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]: + continue + + pt_i = self.dst_pts[k] - pstar + pt_j = np.array([-pt_i[1], pt_i[0]]) + + tmp_pt = np.zeros(2, dtype=np.float32) + tmp_pt[0] = np.sum(pt_i * cur_pt) * self.src_pts[k][0] - \ + np.sum(pt_j * cur_pt) * self.src_pts[k][1] + tmp_pt[1] = -np.sum(pt_i * cur_pt_j) * self.src_pts[k][0] + \ + np.sum(pt_j * cur_pt_j) * self.src_pts[k][1] + tmp_pt *= (w[k] / miu_s) + new_pt += tmp_pt + + new_pt += qstar + else: + new_pt = self.src_pts[k] + + self.rdx[j, i] = new_pt[0] - i + self.rdy[j, i] = new_pt[1] - j + + j += self.grid_size + i += self.grid_size + + def gen_img(self): + src_h, src_w = self.src.shape[:2] + dst = np.zeros_like(self.src, dtype=np.float32) + + for i in np.arange(0, self.dst_h, self.grid_size): + for j in np.arange(0, self.dst_w, self.grid_size): + ni = i + self.grid_size + nj = j + self.grid_size + w = h = self.grid_size + if ni >= self.dst_h: + ni = self.dst_h - 1 + h = ni - i + 1 + if nj >= self.dst_w: + nj = self.dst_w - 1 + w = nj - j + 1 + + di = np.reshape(np.arange(h), (-1, 1)) + dj = np.reshape(np.arange(w), (1, -1)) + delta_x = self.__bilinear_interp( + di / h, dj / w, self.rdx[i, j], self.rdx[i, nj], + self.rdx[ni, j], self.rdx[ni, nj]) + delta_y = self.__bilinear_interp( + di / h, dj / w, self.rdy[i, j], self.rdy[i, nj], + self.rdy[ni, j], self.rdy[ni, nj]) + nx = j + dj + delta_x * self.trans_ratio + ny = i + di + delta_y * self.trans_ratio + nx = np.clip(nx, 0, src_w - 1) + ny = np.clip(ny, 0, src_h - 1) + nxi = np.array(np.floor(nx), dtype=np.int32) + nyi = np.array(np.floor(ny), dtype=np.int32) + nxi1 = np.array(np.ceil(nx), dtype=np.int32) + nyi1 = np.array(np.ceil(ny), dtype=np.int32) + + if len(self.src.shape) == 3: + x = np.tile(np.expand_dims(ny - nyi, axis=-1), (1, 1, 3)) + y = np.tile(np.expand_dims(nx - nxi, axis=-1), (1, 1, 3)) + else: + x = ny - nyi + y = nx - nxi + dst[i:i + h, j:j + w] = self.__bilinear_interp( + x, y, self.src[nyi, nxi], self.src[nyi, nxi1], + self.src[nyi1, nxi], self.src[nyi1, nxi1]) + + dst = np.clip(dst, 0, 255) + dst = np.array(dst, dtype=np.uint8) + + return dst diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34189bcefb17a0776bd62a19c58081286882b5a5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/__init__.py @@ -0,0 +1,22 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from .token import VQATokenPad, VQASerTokenChunk, VQAReTokenChunk, VQAReTokenRelation + +__all__ = [ + 'VQATokenPad', + 'VQASerTokenChunk', + 'VQAReTokenChunk', + 'VQAReTokenRelation', +] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/augment.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/augment.py new file mode 100644 index 0000000000000000000000000000000000000000..b95fcdf0f0baea481de59321a22dab283d99e693 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/augment.py @@ -0,0 +1,33 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import os +import sys +import numpy as np +import random +from copy import deepcopy + + +def order_by_tbyx(ocr_info): + res = sorted(ocr_info, key=lambda r: (r["bbox"][1], r["bbox"][0])) + for i in range(len(res) - 1): + for j in range(i, 0, -1): + if abs(res[j + 1]["bbox"][1] - res[j]["bbox"][1]) < 20 and \ + (res[j + 1]["bbox"][0] < res[j]["bbox"][0]): + tmp = deepcopy(res[j]) + res[j] = deepcopy(res[j + 1]) + res[j + 1] = deepcopy(tmp) + else: + break + return res diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c115661753cd031b16ec34697157e2fcdcf2dec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/__init__.py @@ -0,0 +1,17 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from .vqa_token_chunk import VQASerTokenChunk, VQAReTokenChunk +from .vqa_token_pad import VQATokenPad +from .vqa_token_relation import VQAReTokenRelation diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_chunk.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa949e688289b320c6a7c121c944708febe2c9d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_chunk.py @@ -0,0 +1,122 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from collections import defaultdict + + +class VQASerTokenChunk(object): + def __init__(self, max_seq_len=512, infer_mode=False, **kwargs): + self.max_seq_len = max_seq_len + self.infer_mode = infer_mode + + def __call__(self, data): + encoded_inputs_all = [] + seq_len = len(data['input_ids']) + for index in range(0, seq_len, self.max_seq_len): + chunk_beg = index + chunk_end = min(index + self.max_seq_len, seq_len) + encoded_inputs_example = {} + for key in data: + if key in [ + 'label', 'input_ids', 'labels', 'token_type_ids', + 'bbox', 'attention_mask' + ]: + if self.infer_mode and key == 'labels': + encoded_inputs_example[key] = data[key] + else: + encoded_inputs_example[key] = data[key][chunk_beg: + chunk_end] + else: + encoded_inputs_example[key] = data[key] + + encoded_inputs_all.append(encoded_inputs_example) + if len(encoded_inputs_all) == 0: + return None + return encoded_inputs_all[0] + + +class VQAReTokenChunk(object): + def __init__(self, + max_seq_len=512, + entities_labels=None, + infer_mode=False, + **kwargs): + self.max_seq_len = max_seq_len + self.entities_labels = { + 'HEADER': 0, + 'QUESTION': 1, + 'ANSWER': 2 + } if entities_labels is None else entities_labels + self.infer_mode = infer_mode + + def __call__(self, data): + # prepare data + entities = data.pop('entities') + relations = data.pop('relations') + encoded_inputs_all = [] + for index in range(0, len(data["input_ids"]), self.max_seq_len): + item = {} + for key in data: + if key in [ + 'label', 'input_ids', 'labels', 'token_type_ids', + 'bbox', 'attention_mask' + ]: + if self.infer_mode and key == 'labels': + item[key] = data[key] + else: + item[key] = data[key][index:index + self.max_seq_len] + else: + item[key] = data[key] + # select entity in current chunk + entities_in_this_span = [] + global_to_local_map = {} # + for entity_id, entity in enumerate(entities): + if (index <= entity["start"] < index + self.max_seq_len and + index <= entity["end"] < index + self.max_seq_len): + entity["start"] = entity["start"] - index + entity["end"] = entity["end"] - index + global_to_local_map[entity_id] = len(entities_in_this_span) + entities_in_this_span.append(entity) + + # select relations in current chunk + relations_in_this_span = [] + for relation in relations: + if (index <= relation["start_index"] < index + self.max_seq_len + and index <= relation["end_index"] < + index + self.max_seq_len): + relations_in_this_span.append({ + "head": global_to_local_map[relation["head"]], + "tail": global_to_local_map[relation["tail"]], + "start_index": relation["start_index"] - index, + "end_index": relation["end_index"] - index, + }) + item.update({ + "entities": self.reformat(entities_in_this_span), + "relations": self.reformat(relations_in_this_span), + }) + if len(item['entities']) > 0: + item['entities']['label'] = [ + self.entities_labels[x] for x in item['entities']['label'] + ] + encoded_inputs_all.append(item) + if len(encoded_inputs_all) == 0: + return None + return encoded_inputs_all[0] + + def reformat(self, data): + new_data = defaultdict(list) + for item in data: + for k, v in item.items(): + new_data[k].append(v) + return new_data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_pad.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5a20f95f0159e5c57072dd86eff0f25cf49eac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_pad.py @@ -0,0 +1,104 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import paddle +import numpy as np + + +class VQATokenPad(object): + def __init__(self, + max_seq_len=512, + pad_to_max_seq_len=True, + return_attention_mask=True, + return_token_type_ids=True, + truncation_strategy="longest_first", + return_overflowing_tokens=False, + return_special_tokens_mask=False, + infer_mode=False, + **kwargs): + self.max_seq_len = max_seq_len + self.pad_to_max_seq_len = max_seq_len + self.return_attention_mask = return_attention_mask + self.return_token_type_ids = return_token_type_ids + self.truncation_strategy = truncation_strategy + self.return_overflowing_tokens = return_overflowing_tokens + self.return_special_tokens_mask = return_special_tokens_mask + self.pad_token_label_id = paddle.nn.CrossEntropyLoss().ignore_index + self.infer_mode = infer_mode + + def __call__(self, data): + needs_to_be_padded = self.pad_to_max_seq_len and len(data[ + "input_ids"]) < self.max_seq_len + + if needs_to_be_padded: + if 'tokenizer_params' in data: + tokenizer_params = data.pop('tokenizer_params') + else: + tokenizer_params = dict( + padding_side='right', pad_token_type_id=0, pad_token_id=1) + + difference = self.max_seq_len - len(data["input_ids"]) + if tokenizer_params['padding_side'] == 'right': + if self.return_attention_mask: + data["attention_mask"] = [1] * len(data[ + "input_ids"]) + [0] * difference + if self.return_token_type_ids: + data["token_type_ids"] = ( + data["token_type_ids"] + + [tokenizer_params['pad_token_type_id']] * difference) + if self.return_special_tokens_mask: + data["special_tokens_mask"] = data[ + "special_tokens_mask"] + [1] * difference + data["input_ids"] = data["input_ids"] + [ + tokenizer_params['pad_token_id'] + ] * difference + if not self.infer_mode: + data["labels"] = data[ + "labels"] + [self.pad_token_label_id] * difference + data["bbox"] = data["bbox"] + [[0, 0, 0, 0]] * difference + elif tokenizer_params['padding_side'] == 'left': + if self.return_attention_mask: + data["attention_mask"] = [0] * difference + [ + 1 + ] * len(data["input_ids"]) + if self.return_token_type_ids: + data["token_type_ids"] = ( + [tokenizer_params['pad_token_type_id']] * difference + + data["token_type_ids"]) + if self.return_special_tokens_mask: + data["special_tokens_mask"] = [ + 1 + ] * difference + data["special_tokens_mask"] + data["input_ids"] = [tokenizer_params['pad_token_id'] + ] * difference + data["input_ids"] + if not self.infer_mode: + data["labels"] = [self.pad_token_label_id + ] * difference + data["labels"] + data["bbox"] = [[0, 0, 0, 0]] * difference + data["bbox"] + else: + if self.return_attention_mask: + data["attention_mask"] = [1] * len(data["input_ids"]) + + for key in data: + if key in [ + 'input_ids', 'labels', 'token_type_ids', 'bbox', + 'attention_mask' + ]: + if self.infer_mode: + if key != 'labels': + length = min(len(data[key]), self.max_seq_len) + data[key] = data[key][:length] + else: + continue + data[key] = np.array(data[key], dtype='int64') + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_relation.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_relation.py new file mode 100644 index 0000000000000000000000000000000000000000..293988ff85aecb39bac84b412f3466abecc6db4d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/imaug/vqa/token/vqa_token_relation.py @@ -0,0 +1,67 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + + +class VQAReTokenRelation(object): + def __init__(self, **kwargs): + pass + + def __call__(self, data): + """ + build relations + """ + entities = data['entities'] + relations = data['relations'] + id2label = data.pop('id2label') + empty_entity = data.pop('empty_entity') + entity_id_to_index_map = data.pop('entity_id_to_index_map') + + relations = list(set(relations)) + relations = [ + rel for rel in relations + if rel[0] not in empty_entity and rel[1] not in empty_entity + ] + kv_relations = [] + for rel in relations: + pair = [id2label[rel[0]], id2label[rel[1]]] + if pair == ["question", "answer"]: + kv_relations.append({ + "head": entity_id_to_index_map[rel[0]], + "tail": entity_id_to_index_map[rel[1]] + }) + elif pair == ["answer", "question"]: + kv_relations.append({ + "head": entity_id_to_index_map[rel[1]], + "tail": entity_id_to_index_map[rel[0]] + }) + else: + continue + relations = sorted( + [{ + "head": rel["head"], + "tail": rel["tail"], + "start_index": self.get_relation_span(rel, entities)[0], + "end_index": self.get_relation_span(rel, entities)[1], + } for rel in kv_relations], + key=lambda x: x["head"], ) + + data['relations'] = relations + return data + + def get_relation_span(self, rel, entities): + bound = [] + for entity_index in [rel["head"], rel["tail"]]: + bound.append(entities[entity_index]["start"]) + bound.append(entities[entity_index]["end"]) + return min(bound), max(bound) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/lmdb_dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/lmdb_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3a51cefec2f1da2c96cceb6482d8303aa136b78a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/lmdb_dataset.py @@ -0,0 +1,176 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import numpy as np +import os +from paddle.io import Dataset +import lmdb +import cv2 +import string +import six +from PIL import Image + +from .imaug import transform, create_operators + + +class LMDBDataSet(Dataset): + def __init__(self, config, mode, logger, seed=None): + super(LMDBDataSet, self).__init__() + + global_config = config['Global'] + dataset_config = config[mode]['dataset'] + loader_config = config[mode]['loader'] + batch_size = loader_config['batch_size_per_card'] + data_dir = dataset_config['data_dir'] + self.do_shuffle = loader_config['shuffle'] + + self.lmdb_sets = self.load_hierarchical_lmdb_dataset(data_dir) + logger.info("Initialize indexs of datasets:%s" % data_dir) + self.data_idx_order_list = self.dataset_traversal() + if self.do_shuffle: + np.random.shuffle(self.data_idx_order_list) + self.ops = create_operators(dataset_config['transforms'], global_config) + + ratio_list = dataset_config.get("ratio_list", [1.0]) + self.need_reset = True in [x < 1 for x in ratio_list] + + def load_hierarchical_lmdb_dataset(self, data_dir): + lmdb_sets = {} + dataset_idx = 0 + for dirpath, dirnames, filenames in os.walk(data_dir + '/'): + if not dirnames: + env = lmdb.open( + dirpath, + max_readers=32, + readonly=True, + lock=False, + readahead=False, + meminit=False) + txn = env.begin(write=False) + num_samples = int(txn.get('num-samples'.encode())) + lmdb_sets[dataset_idx] = {"dirpath":dirpath, "env":env, \ + "txn":txn, "num_samples":num_samples} + dataset_idx += 1 + return lmdb_sets + + def dataset_traversal(self): + lmdb_num = len(self.lmdb_sets) + total_sample_num = 0 + for lno in range(lmdb_num): + total_sample_num += self.lmdb_sets[lno]['num_samples'] + data_idx_order_list = np.zeros((total_sample_num, 2)) + beg_idx = 0 + for lno in range(lmdb_num): + tmp_sample_num = self.lmdb_sets[lno]['num_samples'] + end_idx = beg_idx + tmp_sample_num + data_idx_order_list[beg_idx:end_idx, 0] = lno + data_idx_order_list[beg_idx:end_idx, 1] \ + = list(range(tmp_sample_num)) + data_idx_order_list[beg_idx:end_idx, 1] += 1 + beg_idx = beg_idx + tmp_sample_num + return data_idx_order_list + + def get_img_data(self, value): + """get_img_data""" + if not value: + return None + imgdata = np.frombuffer(value, dtype='uint8') + if imgdata is None: + return None + imgori = cv2.imdecode(imgdata, 1) + if imgori is None: + return None + return imgori + + def get_lmdb_sample_info(self, txn, index): + label_key = 'label-%09d'.encode() % index + label = txn.get(label_key) + if label is None: + return None + label = label.decode('utf-8') + img_key = 'image-%09d'.encode() % index + imgbuf = txn.get(img_key) + return imgbuf, label + + def __getitem__(self, idx): + lmdb_idx, file_idx = self.data_idx_order_list[idx] + lmdb_idx = int(lmdb_idx) + file_idx = int(file_idx) + sample_info = self.get_lmdb_sample_info(self.lmdb_sets[lmdb_idx]['txn'], + file_idx) + if sample_info is None: + return self.__getitem__(np.random.randint(self.__len__())) + img, label = sample_info + data = {'image': img, 'label': label} + outs = transform(data, self.ops) + if outs is None: + return self.__getitem__(np.random.randint(self.__len__())) + return outs + + def __len__(self): + return self.data_idx_order_list.shape[0] + + +class LMDBDataSetSR(LMDBDataSet): + def buf2PIL(self, txn, key, type='RGB'): + imgbuf = txn.get(key) + buf = six.BytesIO() + buf.write(imgbuf) + buf.seek(0) + im = Image.open(buf).convert(type) + return im + + def str_filt(self, str_, voc_type): + alpha_dict = { + 'digit': string.digits, + 'lower': string.digits + string.ascii_lowercase, + 'upper': string.digits + string.ascii_letters, + 'all': string.digits + string.ascii_letters + string.punctuation + } + if voc_type == 'lower': + str_ = str_.lower() + for char in str_: + if char not in alpha_dict[voc_type]: + str_ = str_.replace(char, '') + return str_ + + def get_lmdb_sample_info(self, txn, index): + self.voc_type = 'upper' + self.max_len = 100 + self.test = False + label_key = b'label-%09d' % index + word = str(txn.get(label_key).decode()) + img_HR_key = b'image_hr-%09d' % index # 128*32 + img_lr_key = b'image_lr-%09d' % index # 64*16 + try: + img_HR = self.buf2PIL(txn, img_HR_key, 'RGB') + img_lr = self.buf2PIL(txn, img_lr_key, 'RGB') + except IOError or len(word) > self.max_len: + return self[index + 1] + label_str = self.str_filt(word, self.voc_type) + return img_HR, img_lr, label_str + + def __getitem__(self, idx): + lmdb_idx, file_idx = self.data_idx_order_list[idx] + lmdb_idx = int(lmdb_idx) + file_idx = int(file_idx) + sample_info = self.get_lmdb_sample_info(self.lmdb_sets[lmdb_idx]['txn'], + file_idx) + if sample_info is None: + return self.__getitem__(np.random.randint(self.__len__())) + img_HR, img_lr, label_str = sample_info + data = {'image_hr': img_HR, 'image_lr': img_lr, 'label': label_str} + outs = transform(data, self.ops) + if outs is None: + return self.__getitem__(np.random.randint(self.__len__())) + return outs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pgnet_dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pgnet_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6f80179c4eb971ace360edb5368f6a2acd5a6322 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pgnet_dataset.py @@ -0,0 +1,106 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import numpy as np +import os +from paddle.io import Dataset +from .imaug import transform, create_operators +import random + + +class PGDataSet(Dataset): + def __init__(self, config, mode, logger, seed=None): + super(PGDataSet, self).__init__() + + self.logger = logger + self.seed = seed + self.mode = mode + global_config = config['Global'] + dataset_config = config[mode]['dataset'] + loader_config = config[mode]['loader'] + + self.delimiter = dataset_config.get('delimiter', '\t') + label_file_list = dataset_config.pop('label_file_list') + data_source_num = len(label_file_list) + ratio_list = dataset_config.get("ratio_list", [1.0]) + if isinstance(ratio_list, (float, int)): + ratio_list = [float(ratio_list)] * int(data_source_num) + assert len( + ratio_list + ) == data_source_num, "The length of ratio_list should be the same as the file_list." + self.data_dir = dataset_config['data_dir'] + self.do_shuffle = loader_config['shuffle'] + + logger.info("Initialize indexs of datasets:%s" % label_file_list) + self.data_lines = self.get_image_info_list(label_file_list, ratio_list) + self.data_idx_order_list = list(range(len(self.data_lines))) + if mode.lower() == "train": + self.shuffle_data_random() + + self.ops = create_operators(dataset_config['transforms'], global_config) + + self.need_reset = True in [x < 1 for x in ratio_list] + + def shuffle_data_random(self): + if self.do_shuffle: + random.seed(self.seed) + random.shuffle(self.data_lines) + return + + def get_image_info_list(self, file_list, ratio_list): + if isinstance(file_list, str): + file_list = [file_list] + data_lines = [] + for idx, file in enumerate(file_list): + with open(file, "rb") as f: + lines = f.readlines() + if self.mode == "train" or ratio_list[idx] < 1.0: + random.seed(self.seed) + lines = random.sample(lines, + round(len(lines) * ratio_list[idx])) + data_lines.extend(lines) + return data_lines + + def __getitem__(self, idx): + file_idx = self.data_idx_order_list[idx] + data_line = self.data_lines[file_idx] + img_id = 0 + try: + data_line = data_line.decode('utf-8') + substr = data_line.strip("\n").split(self.delimiter) + file_name = substr[0] + label = substr[1] + img_path = os.path.join(self.data_dir, file_name) + if self.mode.lower() == 'eval': + try: + img_id = int(data_line.split(".")[0][7:]) + except: + img_id = 0 + data = {'img_path': img_path, 'label': label, 'img_id': img_id} + if not os.path.exists(img_path): + raise Exception("{} does not exist!".format(img_path)) + with open(data['img_path'], 'rb') as f: + img = f.read() + data['image'] = img + outs = transform(data, self.ops) + except Exception as e: + self.logger.error( + "When parsing line {}, error happened with msg: {}".format( + self.data_idx_order_list[idx], e)) + outs = None + if outs is None: + return self.__getitem__(np.random.randint(self.__len__())) + return outs + + def __len__(self): + return len(self.data_idx_order_list) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pubtab_dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pubtab_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..642d3eb1961cbf0e829e6fb122f38c6af99df1c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/pubtab_dataset.py @@ -0,0 +1,133 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import numpy as np +import os +import random +from paddle.io import Dataset +import json +from copy import deepcopy + +from .imaug import transform, create_operators + + +class PubTabDataSet(Dataset): + def __init__(self, config, mode, logger, seed=None): + super(PubTabDataSet, self).__init__() + self.logger = logger + + global_config = config['Global'] + dataset_config = config[mode]['dataset'] + loader_config = config[mode]['loader'] + + label_file_list = dataset_config.pop('label_file_list') + data_source_num = len(label_file_list) + ratio_list = dataset_config.get("ratio_list", [1.0]) + if isinstance(ratio_list, (float, int)): + ratio_list = [float(ratio_list)] * int(data_source_num) + + assert len( + ratio_list + ) == data_source_num, "The length of ratio_list should be the same as the file_list." + + self.data_dir = dataset_config['data_dir'] + self.do_shuffle = loader_config['shuffle'] + + self.seed = seed + self.mode = mode.lower() + logger.info("Initialize indexs of datasets:%s" % label_file_list) + self.data_lines = self.get_image_info_list(label_file_list, ratio_list) + # self.check(config['Global']['max_text_length']) + + if mode.lower() == "train" and self.do_shuffle: + self.shuffle_data_random() + self.ops = create_operators(dataset_config['transforms'], global_config) + self.need_reset = True in [x < 1 for x in ratio_list] + + def get_image_info_list(self, file_list, ratio_list): + if isinstance(file_list, str): + file_list = [file_list] + data_lines = [] + for idx, file in enumerate(file_list): + with open(file, "rb") as f: + lines = f.readlines() + if self.mode == "train" or ratio_list[idx] < 1.0: + random.seed(self.seed) + lines = random.sample(lines, + round(len(lines) * ratio_list[idx])) + data_lines.extend(lines) + return data_lines + + def check(self, max_text_length): + data_lines = [] + for line in self.data_lines: + data_line = line.decode('utf-8').strip("\n") + info = json.loads(data_line) + file_name = info['filename'] + cells = info['html']['cells'].copy() + structure = info['html']['structure']['tokens'].copy() + + img_path = os.path.join(self.data_dir, file_name) + if not os.path.exists(img_path): + self.logger.warning("{} does not exist!".format(img_path)) + continue + if len(structure) == 0 or len(structure) > max_text_length: + continue + # data = {'img_path': img_path, 'cells': cells, 'structure':structure,'file_name':file_name} + data_lines.append(line) + self.data_lines = data_lines + + def shuffle_data_random(self): + if self.do_shuffle: + random.seed(self.seed) + random.shuffle(self.data_lines) + return + + def __getitem__(self, idx): + try: + data_line = self.data_lines[idx] + data_line = data_line.decode('utf-8').strip("\n") + info = json.loads(data_line) + file_name = info['filename'] + cells = info['html']['cells'].copy() + structure = info['html']['structure']['tokens'].copy() + + img_path = os.path.join(self.data_dir, file_name) + if not os.path.exists(img_path): + raise Exception("{} does not exist!".format(img_path)) + data = { + 'img_path': img_path, + 'cells': cells, + 'structure': structure, + 'file_name': file_name + } + + with open(data['img_path'], 'rb') as f: + img = f.read() + data['image'] = img + outs = transform(data, self.ops) + except: + import traceback + err = traceback.format_exc() + self.logger.error( + "When parsing line {}, error happened with msg: {}".format( + data_line, err)) + outs = None + if outs is None: + rnd_idx = np.random.randint(self.__len__( + )) if self.mode == "train" else (idx + 1) % self.__len__() + return self.__getitem__(rnd_idx) + return outs + + def __len__(self): + return len(self.data_lines) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/simple_dataset.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/simple_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..402f1e38fed9e32722e2dd160f10f779028807a3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/data/simple_dataset.py @@ -0,0 +1,151 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import numpy as np +import os +import json +import random +import traceback +from paddle.io import Dataset +from .imaug import transform, create_operators + + +class SimpleDataSet(Dataset): + def __init__(self, config, mode, logger, seed=None): + super(SimpleDataSet, self).__init__() + self.logger = logger + self.mode = mode.lower() + + global_config = config['Global'] + dataset_config = config[mode]['dataset'] + loader_config = config[mode]['loader'] + + self.delimiter = dataset_config.get('delimiter', '\t') + label_file_list = dataset_config.pop('label_file_list') + data_source_num = len(label_file_list) + ratio_list = dataset_config.get("ratio_list", 1.0) + if isinstance(ratio_list, (float, int)): + ratio_list = [float(ratio_list)] * int(data_source_num) + + assert len( + ratio_list + ) == data_source_num, "The length of ratio_list should be the same as the file_list." + self.data_dir = dataset_config['data_dir'] + self.do_shuffle = loader_config['shuffle'] + self.seed = seed + logger.info("Initialize indexs of datasets:%s" % label_file_list) + self.data_lines = self.get_image_info_list(label_file_list, ratio_list) + self.data_idx_order_list = list(range(len(self.data_lines))) + if self.mode == "train" and self.do_shuffle: + self.shuffle_data_random() + self.ops = create_operators(dataset_config['transforms'], global_config) + self.ext_op_transform_idx = dataset_config.get("ext_op_transform_idx", + 2) + self.need_reset = True in [x < 1 for x in ratio_list] + + def get_image_info_list(self, file_list, ratio_list): + if isinstance(file_list, str): + file_list = [file_list] + data_lines = [] + for idx, file in enumerate(file_list): + with open(file, "rb") as f: + lines = f.readlines() + if self.mode == "train" or ratio_list[idx] < 1.0: + random.seed(self.seed) + lines = random.sample(lines, + round(len(lines) * ratio_list[idx])) + data_lines.extend(lines) + return data_lines + + def shuffle_data_random(self): + random.seed(self.seed) + random.shuffle(self.data_lines) + return + + def _try_parse_filename_list(self, file_name): + # multiple images -> one gt label + if len(file_name) > 0 and file_name[0] == "[": + try: + info = json.loads(file_name) + file_name = random.choice(info) + except: + pass + return file_name + + def get_ext_data(self): + ext_data_num = 0 + for op in self.ops: + if hasattr(op, 'ext_data_num'): + ext_data_num = getattr(op, 'ext_data_num') + break + load_data_ops = self.ops[:self.ext_op_transform_idx] + ext_data = [] + + while len(ext_data) < ext_data_num: + file_idx = self.data_idx_order_list[np.random.randint(self.__len__( + ))] + data_line = self.data_lines[file_idx] + data_line = data_line.decode('utf-8') + substr = data_line.strip("\n").split(self.delimiter) + file_name = substr[0] + file_name = self._try_parse_filename_list(file_name) + label = substr[1] + img_path = os.path.join(self.data_dir, file_name) + data = {'img_path': img_path, 'label': label} + if not os.path.exists(img_path): + continue + with open(data['img_path'], 'rb') as f: + img = f.read() + data['image'] = img + data = transform(data, load_data_ops) + + if data is None: + continue + if 'polys' in data.keys(): + if data['polys'].shape[1] != 4: + continue + ext_data.append(data) + return ext_data + + def __getitem__(self, idx): + file_idx = self.data_idx_order_list[idx] + data_line = self.data_lines[file_idx] + try: + data_line = data_line.decode('utf-8') + substr = data_line.strip("\n").split(self.delimiter) + file_name = substr[0] + file_name = self._try_parse_filename_list(file_name) + label = substr[1] + img_path = os.path.join(self.data_dir, file_name) + data = {'img_path': img_path, 'label': label} + if not os.path.exists(img_path): + raise Exception("{} does not exist!".format(img_path)) + with open(data['img_path'], 'rb') as f: + img = f.read() + data['image'] = img + data['ext_data'] = self.get_ext_data() + outs = transform(data, self.ops) + except: + self.logger.error( + "When parsing line {}, error happened with msg: {}".format( + data_line, traceback.format_exc())) + outs = None + if outs is None: + # during evaluation, we should fix the idx to get same results for many times of evaluation. + rnd_idx = np.random.randint(self.__len__( + )) if self.mode == "train" else (idx + 1) % self.__len__() + return self.__getitem__(rnd_idx) + return outs + + def __len__(self): + return len(self.data_idx_order_list) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..1a11778945c9d7b5f5519cd55473e8bf7790db2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/__init__.py @@ -0,0 +1,78 @@ +# 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. + +import copy +import paddle +import paddle.nn as nn + +# basic_loss +from .basic_loss import LossFromOutput + +# det loss +from .det_db_loss import DBLoss +from .det_east_loss import EASTLoss +from .det_sast_loss import SASTLoss +from .det_pse_loss import PSELoss +from .det_fce_loss import FCELoss + +# rec loss +from .rec_ctc_loss import CTCLoss +from .rec_att_loss import AttentionLoss +from .rec_srn_loss import SRNLoss +from .rec_ce_loss import CELoss +from .rec_sar_loss import SARLoss +from .rec_aster_loss import AsterLoss +from .rec_pren_loss import PRENLoss +from .rec_multi_loss import MultiLoss +from .rec_vl_loss import VLLoss +from .rec_spin_att_loss import SPINAttentionLoss + +# cls loss +from .cls_loss import ClsLoss + +# e2e loss +from .e2e_pg_loss import PGLoss +from .kie_sdmgr_loss import SDMGRLoss + +# basic loss function +from .basic_loss import DistanceLoss + +# combined loss function +from .combined_loss import CombinedLoss + +# table loss +from .table_att_loss import TableAttentionLoss, SLALoss +from .table_master_loss import TableMasterLoss +# vqa token loss +from .vqa_token_layoutlm_loss import VQASerTokenLayoutLMLoss + +# sr loss +from .stroke_focus_loss import StrokeFocusLoss + + +def build_loss(config): + support_dict = [ + 'DBLoss', 'PSELoss', 'EASTLoss', 'SASTLoss', 'FCELoss', 'CTCLoss', + 'ClsLoss', 'AttentionLoss', 'SRNLoss', 'PGLoss', 'CombinedLoss', + 'CELoss', 'TableAttentionLoss', 'SARLoss', 'AsterLoss', 'SDMGRLoss', + 'VQASerTokenLayoutLMLoss', 'LossFromOutput', 'PRENLoss', 'MultiLoss', + 'TableMasterLoss', 'SPINAttentionLoss', 'VLLoss', 'StrokeFocusLoss', + 'SLALoss' + ] + config = copy.deepcopy(config) + module_name = config.pop('name') + assert module_name in support_dict, Exception('loss only support {}'.format( + support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/ace_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/ace_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..915b99e6ec1d6cb4641d8032fa188c61006dfbb3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/ace_loss.py @@ -0,0 +1,52 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +# This code is refer from: https://github.com/viig99/LS-ACELoss + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn + + +class ACELoss(nn.Layer): + def __init__(self, **kwargs): + super().__init__() + self.loss_func = nn.CrossEntropyLoss( + weight=None, + ignore_index=0, + reduction='none', + soft_label=True, + axis=-1) + + def __call__(self, predicts, batch): + if isinstance(predicts, (list, tuple)): + predicts = predicts[-1] + + B, N = predicts.shape[:2] + div = paddle.to_tensor([N]).astype('float32') + + predicts = nn.functional.softmax(predicts, axis=-1) + aggregation_preds = paddle.sum(predicts, axis=1) + aggregation_preds = paddle.divide(aggregation_preds, div) + + length = batch[2].astype("float32") + batch = batch[3].astype("float32") + batch[:, 0] = paddle.subtract(div, length) + batch = paddle.divide(batch, div) + + loss = self.loss_func(aggregation_preds, batch) + return {"loss_ace": loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/basic_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/basic_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f0472ecd0cf3f443aeb474ca6dd5487111f8f0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/basic_loss.py @@ -0,0 +1,167 @@ +#copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + +from paddle.nn import L1Loss +from paddle.nn import MSELoss as L2Loss +from paddle.nn import SmoothL1Loss + + +class CELoss(nn.Layer): + def __init__(self, epsilon=None): + super().__init__() + if epsilon is not None and (epsilon <= 0 or epsilon >= 1): + epsilon = None + self.epsilon = epsilon + + def _labelsmoothing(self, target, class_num): + if target.shape[-1] != class_num: + one_hot_target = F.one_hot(target, class_num) + else: + one_hot_target = target + soft_target = F.label_smooth(one_hot_target, epsilon=self.epsilon) + soft_target = paddle.reshape(soft_target, shape=[-1, class_num]) + return soft_target + + def forward(self, x, label): + loss_dict = {} + if self.epsilon is not None: + class_num = x.shape[-1] + label = self._labelsmoothing(label, class_num) + x = -F.log_softmax(x, axis=-1) + loss = paddle.sum(x * label, axis=-1) + else: + if label.shape[-1] == x.shape[-1]: + label = F.softmax(label, axis=-1) + soft_label = True + else: + soft_label = False + loss = F.cross_entropy(x, label=label, soft_label=soft_label) + return loss + + +class KLJSLoss(object): + def __init__(self, mode='kl'): + assert mode in ['kl', 'js', 'KL', 'JS' + ], "mode can only be one of ['kl', 'KL', 'js', 'JS']" + self.mode = mode + + def __call__(self, p1, p2, reduction="mean", eps=1e-5): + + if self.mode.lower() == 'kl': + loss = paddle.multiply(p2, + paddle.log((p2 + eps) / (p1 + eps) + eps)) + loss += paddle.multiply( + p1, paddle.log((p1 + eps) / (p2 + eps) + eps)) + loss *= 0.5 + elif self.mode.lower() == "js": + loss = paddle.multiply( + p2, paddle.log((2 * p2 + eps) / (p1 + p2 + eps) + eps)) + loss += paddle.multiply( + p1, paddle.log((2 * p1 + eps) / (p1 + p2 + eps) + eps)) + loss *= 0.5 + else: + raise ValueError( + "The mode.lower() if KLJSLoss should be one of ['kl', 'js']") + + if reduction == "mean": + loss = paddle.mean(loss, axis=[1, 2]) + elif reduction == "none" or reduction is None: + return loss + else: + loss = paddle.sum(loss, axis=[1, 2]) + + return loss + + +class DMLLoss(nn.Layer): + """ + DMLLoss + """ + + def __init__(self, act=None, use_log=False): + super().__init__() + if act is not None: + assert act in ["softmax", "sigmoid"] + if act == "softmax": + self.act = nn.Softmax(axis=-1) + elif act == "sigmoid": + self.act = nn.Sigmoid() + else: + self.act = None + + self.use_log = use_log + self.jskl_loss = KLJSLoss(mode="kl") + + def _kldiv(self, x, target): + eps = 1.0e-10 + loss = target * (paddle.log(target + eps) - x) + # batch mean loss + loss = paddle.sum(loss) / loss.shape[0] + return loss + + def forward(self, out1, out2): + if self.act is not None: + out1 = self.act(out1) + 1e-10 + out2 = self.act(out2) + 1e-10 + if self.use_log: + # for recognition distillation, log is needed for feature map + log_out1 = paddle.log(out1) + log_out2 = paddle.log(out2) + loss = ( + self._kldiv(log_out1, out2) + self._kldiv(log_out2, out1)) / 2.0 + else: + # distillation log is not needed for detection + loss = self.jskl_loss(out1, out2) + return loss + + +class DistanceLoss(nn.Layer): + """ + DistanceLoss: + mode: loss mode + """ + + def __init__(self, mode="l2", **kargs): + super().__init__() + assert mode in ["l1", "l2", "smooth_l1"] + if mode == "l1": + self.loss_func = nn.L1Loss(**kargs) + elif mode == "l2": + self.loss_func = nn.MSELoss(**kargs) + elif mode == "smooth_l1": + self.loss_func = nn.SmoothL1Loss(**kargs) + + def forward(self, x, y): + return self.loss_func(x, y) + + +class LossFromOutput(nn.Layer): + def __init__(self, key='loss', reduction='none'): + super().__init__() + self.key = key + self.reduction = reduction + + def forward(self, predicts, batch): + loss = predicts + if self.key is not None and isinstance(predicts, dict): + loss = loss[self.key] + if self.reduction == 'mean': + loss = paddle.mean(loss) + elif self.reduction == 'sum': + loss = paddle.sum(loss) + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/center_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/center_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..f62b8af373ed065a2fedbfa182f9692d6decefda --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/center_loss.py @@ -0,0 +1,88 @@ +#copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +# This code is refer from: https://github.com/KaiyangZhou/pytorch-center-loss + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +import os +import pickle + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + + +class CenterLoss(nn.Layer): + """ + Reference: Wen et al. A Discriminative Feature Learning Approach for Deep Face Recognition. ECCV 2016. + """ + + def __init__(self, num_classes=6625, feat_dim=96, center_file_path=None): + super().__init__() + self.num_classes = num_classes + self.feat_dim = feat_dim + self.centers = paddle.randn( + shape=[self.num_classes, self.feat_dim]).astype("float64") + + if center_file_path is not None: + assert os.path.exists( + center_file_path + ), f"center path({center_file_path}) must exist when it is not None." + with open(center_file_path, 'rb') as f: + char_dict = pickle.load(f) + for key in char_dict.keys(): + self.centers[key] = paddle.to_tensor(char_dict[key]) + + def __call__(self, predicts, batch): + assert isinstance(predicts, (list, tuple)) + features, predicts = predicts + + feats_reshape = paddle.reshape( + features, [-1, features.shape[-1]]).astype("float64") + label = paddle.argmax(predicts, axis=2) + label = paddle.reshape(label, [label.shape[0] * label.shape[1]]) + + batch_size = feats_reshape.shape[0] + + #calc l2 distance between feats and centers + square_feat = paddle.sum(paddle.square(feats_reshape), + axis=1, + keepdim=True) + square_feat = paddle.expand(square_feat, [batch_size, self.num_classes]) + + square_center = paddle.sum(paddle.square(self.centers), + axis=1, + keepdim=True) + square_center = paddle.expand( + square_center, [self.num_classes, batch_size]).astype("float64") + square_center = paddle.transpose(square_center, [1, 0]) + + distmat = paddle.add(square_feat, square_center) + feat_dot_center = paddle.matmul(feats_reshape, + paddle.transpose(self.centers, [1, 0])) + distmat = distmat - 2.0 * feat_dot_center + + #generate the mask + classes = paddle.arange(self.num_classes).astype("int64") + label = paddle.expand( + paddle.unsqueeze(label, 1), (batch_size, self.num_classes)) + mask = paddle.equal( + paddle.expand(classes, [batch_size, self.num_classes]), + label).astype("float64") + dist = paddle.multiply(distmat, mask) + + loss = paddle.sum(paddle.clip(dist, min=1e-12, max=1e+12)) / batch_size + return {'loss_center': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/cls_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/cls_loss.py new file mode 100755 index 0000000000000000000000000000000000000000..abc5e5b72cb055716715345105b59089f0a96edc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/cls_loss.py @@ -0,0 +1,30 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn + + +class ClsLoss(nn.Layer): + def __init__(self, **kwargs): + super(ClsLoss, self).__init__() + self.loss_func = nn.CrossEntropyLoss(reduction='mean') + + def forward(self, predicts, batch): + label = batch[1].astype("int64") + loss = self.loss_func(input=predicts, label=label) + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/combined_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/combined_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..8d697d544b51899cdafeff94be2ecce067b907a2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/combined_loss.py @@ -0,0 +1,72 @@ +# 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. + +import paddle +import paddle.nn as nn + +from .rec_ctc_loss import CTCLoss +from .center_loss import CenterLoss +from .ace_loss import ACELoss +from .rec_sar_loss import SARLoss + +from .distillation_loss import DistillationCTCLoss +from .distillation_loss import DistillationSARLoss +from .distillation_loss import DistillationDMLLoss +from .distillation_loss import DistillationDistanceLoss, DistillationDBLoss, DistillationDilaDBLoss +from .distillation_loss import DistillationVQASerTokenLayoutLMLoss, DistillationSERDMLLoss +from .distillation_loss import DistillationLossFromOutput +from .distillation_loss import DistillationVQADistanceLoss + + +class CombinedLoss(nn.Layer): + """ + CombinedLoss: + a combionation of loss function + """ + + def __init__(self, loss_config_list=None): + super().__init__() + self.loss_func = [] + self.loss_weight = [] + assert isinstance(loss_config_list, list), ( + 'operator config should be a list') + for config in loss_config_list: + assert isinstance(config, + dict) and len(config) == 1, "yaml format error" + name = list(config)[0] + param = config[name] + assert "weight" in param, "weight must be in param, but param just contains {}".format( + param.keys()) + self.loss_weight.append(param.pop("weight")) + self.loss_func.append(eval(name)(**param)) + + def forward(self, input, batch, **kargs): + loss_dict = {} + loss_all = 0. + for idx, loss_func in enumerate(self.loss_func): + loss = loss_func(input, batch, **kargs) + if isinstance(loss, paddle.Tensor): + loss = {"loss_{}_{}".format(str(loss), idx): loss} + + weight = self.loss_weight[idx] + + loss = {key: loss[key] * weight for key in loss} + + if "loss" in loss: + loss_all += loss["loss"] + else: + loss_all += paddle.add_n(list(loss.values())) + loss_dict.update(loss) + loss_dict["loss"] = loss_all + return loss_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_basic_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_basic_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..61ea579b41d3cdf7831c168f563a1e3cd72463a0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_basic_loss.py @@ -0,0 +1,153 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/models/losses/basic_loss.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import paddle +from paddle import nn +import paddle.nn.functional as F + + +class BalanceLoss(nn.Layer): + def __init__(self, + balance_loss=True, + main_loss_type='DiceLoss', + negative_ratio=3, + return_origin=False, + eps=1e-6, + **kwargs): + """ + The BalanceLoss for Differentiable Binarization text detection + args: + balance_loss (bool): whether balance loss or not, default is True + main_loss_type (str): can only be one of ['CrossEntropy','DiceLoss', + 'Euclidean','BCELoss', 'MaskL1Loss'], default is 'DiceLoss'. + negative_ratio (int|float): float, default is 3. + return_origin (bool): whether return unbalanced loss or not, default is False. + eps (float): default is 1e-6. + """ + super(BalanceLoss, self).__init__() + self.balance_loss = balance_loss + self.main_loss_type = main_loss_type + self.negative_ratio = negative_ratio + self.return_origin = return_origin + self.eps = eps + + if self.main_loss_type == "CrossEntropy": + self.loss = nn.CrossEntropyLoss() + elif self.main_loss_type == "Euclidean": + self.loss = nn.MSELoss() + elif self.main_loss_type == "DiceLoss": + self.loss = DiceLoss(self.eps) + elif self.main_loss_type == "BCELoss": + self.loss = BCELoss(reduction='none') + elif self.main_loss_type == "MaskL1Loss": + self.loss = MaskL1Loss(self.eps) + else: + loss_type = [ + 'CrossEntropy', 'DiceLoss', 'Euclidean', 'BCELoss', 'MaskL1Loss' + ] + raise Exception( + "main_loss_type in BalanceLoss() can only be one of {}".format( + loss_type)) + + def forward(self, pred, gt, mask=None): + """ + The BalanceLoss for Differentiable Binarization text detection + args: + pred (variable): predicted feature maps. + gt (variable): ground truth feature maps. + mask (variable): masked maps. + return: (variable) balanced loss + """ + positive = gt * mask + negative = (1 - gt) * mask + + positive_count = int(positive.sum()) + negative_count = int( + min(negative.sum(), positive_count * self.negative_ratio)) + loss = self.loss(pred, gt, mask=mask) + + if not self.balance_loss: + return loss + + positive_loss = positive * loss + negative_loss = negative * loss + negative_loss = paddle.reshape(negative_loss, shape=[-1]) + if negative_count > 0: + sort_loss = negative_loss.sort(descending=True) + negative_loss = sort_loss[:negative_count] + # negative_loss, _ = paddle.topk(negative_loss, k=negative_count_int) + balance_loss = (positive_loss.sum() + negative_loss.sum()) / ( + positive_count + negative_count + self.eps) + else: + balance_loss = positive_loss.sum() / (positive_count + self.eps) + if self.return_origin: + return balance_loss, loss + + return balance_loss + + +class DiceLoss(nn.Layer): + def __init__(self, eps=1e-6): + super(DiceLoss, self).__init__() + self.eps = eps + + def forward(self, pred, gt, mask, weights=None): + """ + DiceLoss function. + """ + + assert pred.shape == gt.shape + assert pred.shape == mask.shape + if weights is not None: + assert weights.shape == mask.shape + mask = weights * mask + intersection = paddle.sum(pred * gt * mask) + + union = paddle.sum(pred * mask) + paddle.sum(gt * mask) + self.eps + loss = 1 - 2.0 * intersection / union + assert loss <= 1 + return loss + + +class MaskL1Loss(nn.Layer): + def __init__(self, eps=1e-6): + super(MaskL1Loss, self).__init__() + self.eps = eps + + def forward(self, pred, gt, mask): + """ + Mask L1 Loss + """ + loss = (paddle.abs(pred - gt) * mask).sum() / (mask.sum() + self.eps) + loss = paddle.mean(loss) + return loss + + +class BCELoss(nn.Layer): + def __init__(self, reduction='mean'): + super(BCELoss, self).__init__() + self.reduction = reduction + + def forward(self, input, label, mask=None, weight=None, name=None): + loss = F.binary_cross_entropy(input, label, reduction=self.reduction) + return loss diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_db_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_db_loss.py new file mode 100755 index 0000000000000000000000000000000000000000..708ffbdb47f349304e2bfd781a836e79348475f4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_db_loss.py @@ -0,0 +1,76 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/models/losses/DB_loss.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn + +from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss + + +class DBLoss(nn.Layer): + """ + Differentiable Binarization (DB) Loss Function + args: + param (dict): the super paramter for DB Loss + """ + + def __init__(self, + balance_loss=True, + main_loss_type='DiceLoss', + alpha=5, + beta=10, + ohem_ratio=3, + eps=1e-6, + **kwargs): + super(DBLoss, self).__init__() + self.alpha = alpha + self.beta = beta + self.dice_loss = DiceLoss(eps=eps) + self.l1_loss = MaskL1Loss(eps=eps) + self.bce_loss = BalanceLoss( + balance_loss=balance_loss, + main_loss_type=main_loss_type, + negative_ratio=ohem_ratio) + + def forward(self, predicts, labels): + predict_maps = predicts['maps'] + label_threshold_map, label_threshold_mask, label_shrink_map, label_shrink_mask = labels[ + 1:] + shrink_maps = predict_maps[:, 0, :, :] + threshold_maps = predict_maps[:, 1, :, :] + binary_maps = predict_maps[:, 2, :, :] + + loss_shrink_maps = self.bce_loss(shrink_maps, label_shrink_map, + label_shrink_mask) + loss_threshold_maps = self.l1_loss(threshold_maps, label_threshold_map, + label_threshold_mask) + loss_binary_maps = self.dice_loss(binary_maps, label_shrink_map, + label_shrink_mask) + loss_shrink_maps = self.alpha * loss_shrink_maps + loss_threshold_maps = self.beta * loss_threshold_maps + + loss_all = loss_shrink_maps + loss_threshold_maps \ + + loss_binary_maps + losses = {'loss': loss_all, \ + "loss_shrink_maps": loss_shrink_maps, \ + "loss_threshold_maps": loss_threshold_maps, \ + "loss_binary_maps": loss_binary_maps} + return losses diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_east_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_east_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf5372b72d49ebeb34c0ce127e7221d563a6c35 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_east_loss.py @@ -0,0 +1,63 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +from .det_basic_loss import DiceLoss + + +class EASTLoss(nn.Layer): + """ + """ + + def __init__(self, + eps=1e-6, + **kwargs): + super(EASTLoss, self).__init__() + self.dice_loss = DiceLoss(eps=eps) + + def forward(self, predicts, labels): + l_score, l_geo, l_mask = labels[1:] + f_score = predicts['f_score'] + f_geo = predicts['f_geo'] + + dice_loss = self.dice_loss(f_score, l_score, l_mask) + + #smoooth_l1_loss + channels = 8 + l_geo_split = paddle.split( + l_geo, num_or_sections=channels + 1, axis=1) + f_geo_split = paddle.split(f_geo, num_or_sections=channels, axis=1) + smooth_l1 = 0 + for i in range(0, channels): + geo_diff = l_geo_split[i] - f_geo_split[i] + abs_geo_diff = paddle.abs(geo_diff) + smooth_l1_sign = paddle.less_than(abs_geo_diff, l_score) + smooth_l1_sign = paddle.cast(smooth_l1_sign, dtype='float32') + in_loss = abs_geo_diff * abs_geo_diff * smooth_l1_sign + \ + (abs_geo_diff - 0.5) * (1.0 - smooth_l1_sign) + out_loss = l_geo_split[-1] / channels * in_loss * l_score + smooth_l1 += out_loss + smooth_l1_loss = paddle.mean(smooth_l1 * l_score) + + dice_loss = dice_loss * 0.01 + total_loss = dice_loss + smooth_l1_loss + losses = {"loss":total_loss, \ + "dice_loss":dice_loss,\ + "smooth_l1_loss":smooth_l1_loss} + return losses diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_fce_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_fce_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d7dfb5aa6c6b2ac7eaf03bcfb18b1b2859cbc521 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_fce_loss.py @@ -0,0 +1,227 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textdet/losses/fce_loss.py +""" + +import numpy as np +from paddle import nn +import paddle +import paddle.nn.functional as F +from functools import partial + + +def multi_apply(func, *args, **kwargs): + pfunc = partial(func, **kwargs) if kwargs else func + map_results = map(pfunc, *args) + return tuple(map(list, zip(*map_results))) + + +class FCELoss(nn.Layer): + """The class for implementing FCENet loss + FCENet(CVPR2021): Fourier Contour Embedding for Arbitrary-shaped + Text Detection + + [https://arxiv.org/abs/2104.10442] + + Args: + fourier_degree (int) : The maximum Fourier transform degree k. + num_sample (int) : The sampling points number of regression + loss. If it is too small, fcenet tends to be overfitting. + ohem_ratio (float): the negative/positive ratio in OHEM. + """ + + def __init__(self, fourier_degree, num_sample, ohem_ratio=3.): + super().__init__() + self.fourier_degree = fourier_degree + self.num_sample = num_sample + self.ohem_ratio = ohem_ratio + + def forward(self, preds, labels): + assert isinstance(preds, dict) + preds = preds['levels'] + + p3_maps, p4_maps, p5_maps = labels[1:] + assert p3_maps[0].shape[0] == 4 * self.fourier_degree + 5,\ + 'fourier degree not equal in FCEhead and FCEtarget' + + # to tensor + gts = [p3_maps, p4_maps, p5_maps] + for idx, maps in enumerate(gts): + gts[idx] = paddle.to_tensor(np.stack(maps)) + + losses = multi_apply(self.forward_single, preds, gts) + + loss_tr = paddle.to_tensor(0.).astype('float32') + loss_tcl = paddle.to_tensor(0.).astype('float32') + loss_reg_x = paddle.to_tensor(0.).astype('float32') + loss_reg_y = paddle.to_tensor(0.).astype('float32') + loss_all = paddle.to_tensor(0.).astype('float32') + + for idx, loss in enumerate(losses): + loss_all += sum(loss) + if idx == 0: + loss_tr += sum(loss) + elif idx == 1: + loss_tcl += sum(loss) + elif idx == 2: + loss_reg_x += sum(loss) + else: + loss_reg_y += sum(loss) + + results = dict( + loss=loss_all, + loss_text=loss_tr, + loss_center=loss_tcl, + loss_reg_x=loss_reg_x, + loss_reg_y=loss_reg_y, ) + return results + + def forward_single(self, pred, gt): + cls_pred = paddle.transpose(pred[0], (0, 2, 3, 1)) + reg_pred = paddle.transpose(pred[1], (0, 2, 3, 1)) + gt = paddle.transpose(gt, (0, 2, 3, 1)) + + k = 2 * self.fourier_degree + 1 + tr_pred = paddle.reshape(cls_pred[:, :, :, :2], (-1, 2)) + tcl_pred = paddle.reshape(cls_pred[:, :, :, 2:], (-1, 2)) + x_pred = paddle.reshape(reg_pred[:, :, :, 0:k], (-1, k)) + y_pred = paddle.reshape(reg_pred[:, :, :, k:2 * k], (-1, k)) + + tr_mask = gt[:, :, :, :1].reshape([-1]) + tcl_mask = gt[:, :, :, 1:2].reshape([-1]) + train_mask = gt[:, :, :, 2:3].reshape([-1]) + x_map = paddle.reshape(gt[:, :, :, 3:3 + k], (-1, k)) + y_map = paddle.reshape(gt[:, :, :, 3 + k:], (-1, k)) + + tr_train_mask = (train_mask * tr_mask).astype('bool') + tr_train_mask2 = paddle.concat( + [tr_train_mask.unsqueeze(1), tr_train_mask.unsqueeze(1)], axis=1) + # tr loss + loss_tr = self.ohem(tr_pred, tr_mask, train_mask) + # tcl loss + loss_tcl = paddle.to_tensor(0.).astype('float32') + tr_neg_mask = tr_train_mask.logical_not() + tr_neg_mask2 = paddle.concat( + [tr_neg_mask.unsqueeze(1), tr_neg_mask.unsqueeze(1)], axis=1) + if tr_train_mask.sum().item() > 0: + loss_tcl_pos = F.cross_entropy( + tcl_pred.masked_select(tr_train_mask2).reshape([-1, 2]), + tcl_mask.masked_select(tr_train_mask).astype('int64')) + loss_tcl_neg = F.cross_entropy( + tcl_pred.masked_select(tr_neg_mask2).reshape([-1, 2]), + tcl_mask.masked_select(tr_neg_mask).astype('int64')) + loss_tcl = loss_tcl_pos + 0.5 * loss_tcl_neg + + # regression loss + loss_reg_x = paddle.to_tensor(0.).astype('float32') + loss_reg_y = paddle.to_tensor(0.).astype('float32') + if tr_train_mask.sum().item() > 0: + weight = (tr_mask.masked_select(tr_train_mask.astype('bool')) + .astype('float32') + tcl_mask.masked_select( + tr_train_mask.astype('bool')).astype('float32')) / 2 + weight = weight.reshape([-1, 1]) + + ft_x, ft_y = self.fourier2poly(x_map, y_map) + ft_x_pre, ft_y_pre = self.fourier2poly(x_pred, y_pred) + + dim = ft_x.shape[1] + + tr_train_mask3 = paddle.concat( + [tr_train_mask.unsqueeze(1) for i in range(dim)], axis=1) + + loss_reg_x = paddle.mean(weight * F.smooth_l1_loss( + ft_x_pre.masked_select(tr_train_mask3).reshape([-1, dim]), + ft_x.masked_select(tr_train_mask3).reshape([-1, dim]), + reduction='none')) + loss_reg_y = paddle.mean(weight * F.smooth_l1_loss( + ft_y_pre.masked_select(tr_train_mask3).reshape([-1, dim]), + ft_y.masked_select(tr_train_mask3).reshape([-1, dim]), + reduction='none')) + + return loss_tr, loss_tcl, loss_reg_x, loss_reg_y + + def ohem(self, predict, target, train_mask): + + pos = (target * train_mask).astype('bool') + neg = ((1 - target) * train_mask).astype('bool') + + pos2 = paddle.concat([pos.unsqueeze(1), pos.unsqueeze(1)], axis=1) + neg2 = paddle.concat([neg.unsqueeze(1), neg.unsqueeze(1)], axis=1) + + n_pos = pos.astype('float32').sum() + + if n_pos.item() > 0: + loss_pos = F.cross_entropy( + predict.masked_select(pos2).reshape([-1, 2]), + target.masked_select(pos).astype('int64'), + reduction='sum') + loss_neg = F.cross_entropy( + predict.masked_select(neg2).reshape([-1, 2]), + target.masked_select(neg).astype('int64'), + reduction='none') + n_neg = min( + int(neg.astype('float32').sum().item()), + int(self.ohem_ratio * n_pos.astype('float32'))) + else: + loss_pos = paddle.to_tensor(0.) + loss_neg = F.cross_entropy( + predict.masked_select(neg2).reshape([-1, 2]), + target.masked_select(neg).astype('int64'), + reduction='none') + n_neg = 100 + if len(loss_neg) > n_neg: + loss_neg, _ = paddle.topk(loss_neg, n_neg) + + return (loss_pos + loss_neg.sum()) / (n_pos + n_neg).astype('float32') + + def fourier2poly(self, real_maps, imag_maps): + """Transform Fourier coefficient maps to polygon maps. + + Args: + real_maps (tensor): A map composed of the real parts of the + Fourier coefficients, whose shape is (-1, 2k+1) + imag_maps (tensor):A map composed of the imag parts of the + Fourier coefficients, whose shape is (-1, 2k+1) + + Returns + x_maps (tensor): A map composed of the x value of the polygon + represented by n sample points (xn, yn), whose shape is (-1, n) + y_maps (tensor): A map composed of the y value of the polygon + represented by n sample points (xn, yn), whose shape is (-1, n) + """ + + k_vect = paddle.arange( + -self.fourier_degree, self.fourier_degree + 1, + dtype='float32').reshape([-1, 1]) + i_vect = paddle.arange( + 0, self.num_sample, dtype='float32').reshape([1, -1]) + + transform_matrix = 2 * np.pi / self.num_sample * paddle.matmul(k_vect, + i_vect) + + x1 = paddle.einsum('ak, kn-> an', real_maps, + paddle.cos(transform_matrix)) + x2 = paddle.einsum('ak, kn-> an', imag_maps, + paddle.sin(transform_matrix)) + y1 = paddle.einsum('ak, kn-> an', real_maps, + paddle.sin(transform_matrix)) + y2 = paddle.einsum('ak, kn-> an', imag_maps, + paddle.cos(transform_matrix)) + + x_maps = x1 - x2 + y_maps = y1 + y2 + + return x_maps, y_maps diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_pse_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_pse_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..6b31343ed4d1687ee8ca44592fba0331b0b287dc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_pse_loss.py @@ -0,0 +1,149 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/head/psenet_head.py +""" + +import paddle +from paddle import nn +from paddle.nn import functional as F +import numpy as np +from ppocr.utils.iou import iou + + +class PSELoss(nn.Layer): + def __init__(self, + alpha, + ohem_ratio=3, + kernel_sample_mask='pred', + reduction='sum', + eps=1e-6, + **kwargs): + """Implement PSE Loss. + """ + super(PSELoss, self).__init__() + assert reduction in ['sum', 'mean', 'none'] + self.alpha = alpha + self.ohem_ratio = ohem_ratio + self.kernel_sample_mask = kernel_sample_mask + self.reduction = reduction + self.eps = eps + + def forward(self, outputs, labels): + predicts = outputs['maps'] + predicts = F.interpolate(predicts, scale_factor=4) + + texts = predicts[:, 0, :, :] + kernels = predicts[:, 1:, :, :] + gt_texts, gt_kernels, training_masks = labels[1:] + + # text loss + selected_masks = self.ohem_batch(texts, gt_texts, training_masks) + + loss_text = self.dice_loss(texts, gt_texts, selected_masks) + iou_text = iou((texts > 0).astype('int64'), + gt_texts, + training_masks, + reduce=False) + losses = dict(loss_text=loss_text, iou_text=iou_text) + + # kernel loss + loss_kernels = [] + if self.kernel_sample_mask == 'gt': + selected_masks = gt_texts * training_masks + elif self.kernel_sample_mask == 'pred': + selected_masks = ( + F.sigmoid(texts) > 0.5).astype('float32') * training_masks + + for i in range(kernels.shape[1]): + kernel_i = kernels[:, i, :, :] + gt_kernel_i = gt_kernels[:, i, :, :] + loss_kernel_i = self.dice_loss(kernel_i, gt_kernel_i, + selected_masks) + loss_kernels.append(loss_kernel_i) + loss_kernels = paddle.mean(paddle.stack(loss_kernels, axis=1), axis=1) + iou_kernel = iou((kernels[:, -1, :, :] > 0).astype('int64'), + gt_kernels[:, -1, :, :], + training_masks * gt_texts, + reduce=False) + losses.update(dict(loss_kernels=loss_kernels, iou_kernel=iou_kernel)) + loss = self.alpha * loss_text + (1 - self.alpha) * loss_kernels + losses['loss'] = loss + if self.reduction == 'sum': + losses = {x: paddle.sum(v) for x, v in losses.items()} + elif self.reduction == 'mean': + losses = {x: paddle.mean(v) for x, v in losses.items()} + return losses + + def dice_loss(self, input, target, mask): + input = F.sigmoid(input) + + input = input.reshape([input.shape[0], -1]) + target = target.reshape([target.shape[0], -1]) + mask = mask.reshape([mask.shape[0], -1]) + + input = input * mask + target = target * mask + + a = paddle.sum(input * target, 1) + b = paddle.sum(input * input, 1) + self.eps + c = paddle.sum(target * target, 1) + self.eps + d = (2 * a) / (b + c) + return 1 - d + + def ohem_single(self, score, gt_text, training_mask, ohem_ratio=3): + pos_num = int(paddle.sum((gt_text > 0.5).astype('float32'))) - int( + paddle.sum( + paddle.logical_and((gt_text > 0.5), (training_mask <= 0.5)) + .astype('float32'))) + + if pos_num == 0: + selected_mask = training_mask + selected_mask = selected_mask.reshape( + [1, selected_mask.shape[0], selected_mask.shape[1]]).astype( + 'float32') + return selected_mask + + neg_num = int(paddle.sum((gt_text <= 0.5).astype('float32'))) + neg_num = int(min(pos_num * ohem_ratio, neg_num)) + + if neg_num == 0: + selected_mask = training_mask + selected_mask = selected_mask.reshape( + [1, selected_mask.shape[0], selected_mask.shape[1]]).astype( + 'float32') + return selected_mask + + neg_score = paddle.masked_select(score, gt_text <= 0.5) + neg_score_sorted = paddle.sort(-neg_score) + threshold = -neg_score_sorted[neg_num - 1] + + selected_mask = paddle.logical_and( + paddle.logical_or((score >= threshold), (gt_text > 0.5)), + (training_mask > 0.5)) + selected_mask = selected_mask.reshape( + [1, selected_mask.shape[0], selected_mask.shape[1]]).astype( + 'float32') + return selected_mask + + def ohem_batch(self, scores, gt_texts, training_masks, ohem_ratio=3): + selected_masks = [] + for i in range(scores.shape[0]): + selected_masks.append( + self.ohem_single(scores[i, :, :], gt_texts[i, :, :], + training_masks[i, :, :], ohem_ratio)) + + selected_masks = paddle.concat(selected_masks, 0).astype('float32') + return selected_masks diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_sast_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_sast_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0c756bd4ebe4157ed397a6c2e9b7e94054b4e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/det_sast_loss.py @@ -0,0 +1,121 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +from .det_basic_loss import DiceLoss +import numpy as np + + +class SASTLoss(nn.Layer): + """ + """ + + def __init__(self, eps=1e-6, **kwargs): + super(SASTLoss, self).__init__() + self.dice_loss = DiceLoss(eps=eps) + + def forward(self, predicts, labels): + """ + tcl_pos: N x 128 x 3 + tcl_mask: N x 128 x 1 + tcl_label: N x X list or LoDTensor + """ + + f_score = predicts['f_score'] + f_border = predicts['f_border'] + f_tvo = predicts['f_tvo'] + f_tco = predicts['f_tco'] + + l_score, l_border, l_mask, l_tvo, l_tco = labels[1:] + + #score_loss + intersection = paddle.sum(f_score * l_score * l_mask) + union = paddle.sum(f_score * l_mask) + paddle.sum(l_score * l_mask) + score_loss = 1.0 - 2 * intersection / (union + 1e-5) + + #border loss + l_border_split, l_border_norm = paddle.split( + l_border, num_or_sections=[4, 1], axis=1) + f_border_split = f_border + border_ex_shape = l_border_norm.shape * np.array([1, 4, 1, 1]) + l_border_norm_split = paddle.expand( + x=l_border_norm, shape=border_ex_shape) + l_border_score = paddle.expand(x=l_score, shape=border_ex_shape) + l_border_mask = paddle.expand(x=l_mask, shape=border_ex_shape) + + border_diff = l_border_split - f_border_split + abs_border_diff = paddle.abs(border_diff) + border_sign = abs_border_diff < 1.0 + border_sign = paddle.cast(border_sign, dtype='float32') + border_sign.stop_gradient = True + border_in_loss = 0.5 * abs_border_diff * abs_border_diff * border_sign + \ + (abs_border_diff - 0.5) * (1.0 - border_sign) + border_out_loss = l_border_norm_split * border_in_loss + border_loss = paddle.sum(border_out_loss * l_border_score * l_border_mask) / \ + (paddle.sum(l_border_score * l_border_mask) + 1e-5) + + #tvo_loss + l_tvo_split, l_tvo_norm = paddle.split( + l_tvo, num_or_sections=[8, 1], axis=1) + f_tvo_split = f_tvo + tvo_ex_shape = l_tvo_norm.shape * np.array([1, 8, 1, 1]) + l_tvo_norm_split = paddle.expand(x=l_tvo_norm, shape=tvo_ex_shape) + l_tvo_score = paddle.expand(x=l_score, shape=tvo_ex_shape) + l_tvo_mask = paddle.expand(x=l_mask, shape=tvo_ex_shape) + # + tvo_geo_diff = l_tvo_split - f_tvo_split + abs_tvo_geo_diff = paddle.abs(tvo_geo_diff) + tvo_sign = abs_tvo_geo_diff < 1.0 + tvo_sign = paddle.cast(tvo_sign, dtype='float32') + tvo_sign.stop_gradient = True + tvo_in_loss = 0.5 * abs_tvo_geo_diff * abs_tvo_geo_diff * tvo_sign + \ + (abs_tvo_geo_diff - 0.5) * (1.0 - tvo_sign) + tvo_out_loss = l_tvo_norm_split * tvo_in_loss + tvo_loss = paddle.sum(tvo_out_loss * l_tvo_score * l_tvo_mask) / \ + (paddle.sum(l_tvo_score * l_tvo_mask) + 1e-5) + + #tco_loss + l_tco_split, l_tco_norm = paddle.split( + l_tco, num_or_sections=[2, 1], axis=1) + f_tco_split = f_tco + tco_ex_shape = l_tco_norm.shape * np.array([1, 2, 1, 1]) + l_tco_norm_split = paddle.expand(x=l_tco_norm, shape=tco_ex_shape) + l_tco_score = paddle.expand(x=l_score, shape=tco_ex_shape) + l_tco_mask = paddle.expand(x=l_mask, shape=tco_ex_shape) + + tco_geo_diff = l_tco_split - f_tco_split + abs_tco_geo_diff = paddle.abs(tco_geo_diff) + tco_sign = abs_tco_geo_diff < 1.0 + tco_sign = paddle.cast(tco_sign, dtype='float32') + tco_sign.stop_gradient = True + tco_in_loss = 0.5 * abs_tco_geo_diff * abs_tco_geo_diff * tco_sign + \ + (abs_tco_geo_diff - 0.5) * (1.0 - tco_sign) + tco_out_loss = l_tco_norm_split * tco_in_loss + tco_loss = paddle.sum(tco_out_loss * l_tco_score * l_tco_mask) / \ + (paddle.sum(l_tco_score * l_tco_mask) + 1e-5) + + # total loss + tvo_lw, tco_lw = 1.5, 1.5 + score_lw, border_lw = 1.0, 1.0 + total_loss = score_loss * score_lw + border_loss * border_lw + \ + tvo_loss * tvo_lw + tco_loss * tco_lw + + losses = {'loss':total_loss, "score_loss":score_loss,\ + "border_loss":border_loss, 'tvo_loss':tvo_loss, 'tco_loss':tco_loss} + return losses diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/distillation_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/distillation_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..87fed6235d73aef2695cd6db95662e615d52c94c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/distillation_loss.py @@ -0,0 +1,456 @@ +#copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +import paddle +import paddle.nn as nn +import numpy as np +import cv2 + +from .rec_ctc_loss import CTCLoss +from .rec_sar_loss import SARLoss +from .basic_loss import DMLLoss +from .basic_loss import DistanceLoss +from .basic_loss import LossFromOutput +from .det_db_loss import DBLoss +from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss +from .vqa_token_layoutlm_loss import VQASerTokenLayoutLMLoss + + +def _sum_loss(loss_dict): + if "loss" in loss_dict.keys(): + return loss_dict + else: + loss_dict["loss"] = 0. + for k, value in loss_dict.items(): + if k == "loss": + continue + else: + loss_dict["loss"] += value + return loss_dict + + +class DistillationDMLLoss(DMLLoss): + """ + """ + + def __init__(self, + model_name_pairs=[], + act=None, + use_log=False, + key=None, + multi_head=False, + dis_head='ctc', + maps_name=None, + name="dml"): + super().__init__(act=act, use_log=use_log) + assert isinstance(model_name_pairs, list) + self.key = key + self.multi_head = multi_head + self.dis_head = dis_head + self.model_name_pairs = self._check_model_name_pairs(model_name_pairs) + self.name = name + self.maps_name = self._check_maps_name(maps_name) + + def _check_model_name_pairs(self, model_name_pairs): + if not isinstance(model_name_pairs, list): + return [] + elif isinstance(model_name_pairs[0], list) and isinstance( + model_name_pairs[0][0], str): + return model_name_pairs + else: + return [model_name_pairs] + + def _check_maps_name(self, maps_name): + if maps_name is None: + return None + elif type(maps_name) == str: + return [maps_name] + elif type(maps_name) == list: + return [maps_name] + else: + return None + + def _slice_out(self, outs): + new_outs = {} + for k in self.maps_name: + if k == "thrink_maps": + new_outs[k] = outs[:, 0, :, :] + elif k == "threshold_maps": + new_outs[k] = outs[:, 1, :, :] + elif k == "binary_maps": + new_outs[k] = outs[:, 2, :, :] + else: + continue + return new_outs + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, pair in enumerate(self.model_name_pairs): + out1 = predicts[pair[0]] + out2 = predicts[pair[1]] + if self.key is not None: + out1 = out1[self.key] + out2 = out2[self.key] + + if self.maps_name is None: + if self.multi_head: + loss = super().forward(out1[self.dis_head], + out2[self.dis_head]) + else: + loss = super().forward(out1, out2) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}_{}_{}".format(key, pair[0], pair[1], + idx)] = loss[key] + else: + loss_dict["{}_{}".format(self.name, idx)] = loss + else: + outs1 = self._slice_out(out1) + outs2 = self._slice_out(out2) + for _c, k in enumerate(outs1.keys()): + loss = super().forward(outs1[k], outs2[k]) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}_{}_{}_{}".format(key, pair[ + 0], pair[1], self.maps_name, idx)] = loss[key] + else: + loss_dict["{}_{}_{}".format(self.name, self.maps_name[ + _c], idx)] = loss + + loss_dict = _sum_loss(loss_dict) + + return loss_dict + + +class DistillationCTCLoss(CTCLoss): + def __init__(self, + model_name_list=[], + key=None, + multi_head=False, + name="loss_ctc"): + super().__init__() + self.model_name_list = model_name_list + self.key = key + self.name = name + self.multi_head = multi_head + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, model_name in enumerate(self.model_name_list): + out = predicts[model_name] + if self.key is not None: + out = out[self.key] + if self.multi_head: + assert 'ctc' in out, 'multi head has multi out' + loss = super().forward(out['ctc'], batch[:2] + batch[3:]) + else: + loss = super().forward(out, batch) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}_{}".format(self.name, model_name, + idx)] = loss[key] + else: + loss_dict["{}_{}".format(self.name, model_name)] = loss + return loss_dict + + +class DistillationSARLoss(SARLoss): + def __init__(self, + model_name_list=[], + key=None, + multi_head=False, + name="loss_sar", + **kwargs): + ignore_index = kwargs.get('ignore_index', 92) + super().__init__(ignore_index=ignore_index) + self.model_name_list = model_name_list + self.key = key + self.name = name + self.multi_head = multi_head + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, model_name in enumerate(self.model_name_list): + out = predicts[model_name] + if self.key is not None: + out = out[self.key] + if self.multi_head: + assert 'sar' in out, 'multi head has multi out' + loss = super().forward(out['sar'], batch[:1] + batch[2:]) + else: + loss = super().forward(out, batch) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}_{}".format(self.name, model_name, + idx)] = loss[key] + else: + loss_dict["{}_{}".format(self.name, model_name)] = loss + return loss_dict + + +class DistillationDBLoss(DBLoss): + def __init__(self, + model_name_list=[], + balance_loss=True, + main_loss_type='DiceLoss', + alpha=5, + beta=10, + ohem_ratio=3, + eps=1e-6, + name="db", + **kwargs): + super().__init__() + self.model_name_list = model_name_list + self.name = name + self.key = None + + def forward(self, predicts, batch): + loss_dict = {} + for idx, model_name in enumerate(self.model_name_list): + out = predicts[model_name] + if self.key is not None: + out = out[self.key] + loss = super().forward(out, batch) + + if isinstance(loss, dict): + for key in loss.keys(): + if key == "loss": + continue + name = "{}_{}_{}".format(self.name, model_name, key) + loss_dict[name] = loss[key] + else: + loss_dict["{}_{}".format(self.name, model_name)] = loss + + loss_dict = _sum_loss(loss_dict) + return loss_dict + + +class DistillationDilaDBLoss(DBLoss): + def __init__(self, + model_name_pairs=[], + key=None, + balance_loss=True, + main_loss_type='DiceLoss', + alpha=5, + beta=10, + ohem_ratio=3, + eps=1e-6, + name="dila_dbloss"): + super().__init__() + self.model_name_pairs = model_name_pairs + self.name = name + self.key = key + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, pair in enumerate(self.model_name_pairs): + stu_outs = predicts[pair[0]] + tch_outs = predicts[pair[1]] + if self.key is not None: + stu_preds = stu_outs[self.key] + tch_preds = tch_outs[self.key] + + stu_shrink_maps = stu_preds[:, 0, :, :] + stu_binary_maps = stu_preds[:, 2, :, :] + + # dilation to teacher prediction + dilation_w = np.array([[1, 1], [1, 1]]) + th_shrink_maps = tch_preds[:, 0, :, :] + th_shrink_maps = th_shrink_maps.numpy() > 0.3 # thresh = 0.3 + dilate_maps = np.zeros_like(th_shrink_maps).astype(np.float32) + for i in range(th_shrink_maps.shape[0]): + dilate_maps[i] = cv2.dilate( + th_shrink_maps[i, :, :].astype(np.uint8), dilation_w) + th_shrink_maps = paddle.to_tensor(dilate_maps) + + label_threshold_map, label_threshold_mask, label_shrink_map, label_shrink_mask = batch[ + 1:] + + # calculate the shrink map loss + bce_loss = self.alpha * self.bce_loss( + stu_shrink_maps, th_shrink_maps, label_shrink_mask) + loss_binary_maps = self.dice_loss(stu_binary_maps, th_shrink_maps, + label_shrink_mask) + + # k = f"{self.name}_{pair[0]}_{pair[1]}" + k = "{}_{}_{}".format(self.name, pair[0], pair[1]) + loss_dict[k] = bce_loss + loss_binary_maps + + loss_dict = _sum_loss(loss_dict) + return loss_dict + + +class DistillationDistanceLoss(DistanceLoss): + """ + """ + + def __init__(self, + mode="l2", + model_name_pairs=[], + key=None, + name="loss_distance", + **kargs): + super().__init__(mode=mode, **kargs) + assert isinstance(model_name_pairs, list) + self.key = key + self.model_name_pairs = model_name_pairs + self.name = name + "_l2" + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, pair in enumerate(self.model_name_pairs): + out1 = predicts[pair[0]] + out2 = predicts[pair[1]] + if self.key is not None: + out1 = out1[self.key] + out2 = out2[self.key] + loss = super().forward(out1, out2) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}_{}".format(self.name, key, idx)] = loss[ + key] + else: + loss_dict["{}_{}_{}_{}".format(self.name, pair[0], pair[1], + idx)] = loss + return loss_dict + + +class DistillationVQASerTokenLayoutLMLoss(VQASerTokenLayoutLMLoss): + def __init__(self, + num_classes, + model_name_list=[], + key=None, + name="loss_ser"): + super().__init__(num_classes=num_classes) + self.model_name_list = model_name_list + self.key = key + self.name = name + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, model_name in enumerate(self.model_name_list): + out = predicts[model_name] + if self.key is not None: + out = out[self.key] + loss = super().forward(out, batch) + loss_dict["{}_{}".format(self.name, model_name)] = loss["loss"] + return loss_dict + + +class DistillationLossFromOutput(LossFromOutput): + def __init__(self, + reduction="none", + model_name_list=[], + dist_key=None, + key="loss", + name="loss_re"): + super().__init__(key=key, reduction=reduction) + self.model_name_list = model_name_list + self.name = name + self.dist_key = dist_key + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, model_name in enumerate(self.model_name_list): + out = predicts[model_name] + if self.dist_key is not None: + out = out[self.dist_key] + loss = super().forward(out, batch) + loss_dict["{}_{}".format(self.name, model_name)] = loss["loss"] + return loss_dict + + +class DistillationSERDMLLoss(DMLLoss): + """ + """ + + def __init__(self, + act="softmax", + use_log=True, + num_classes=7, + model_name_pairs=[], + key=None, + name="loss_dml_ser"): + super().__init__(act=act, use_log=use_log) + assert isinstance(model_name_pairs, list) + self.key = key + self.name = name + self.num_classes = num_classes + self.model_name_pairs = model_name_pairs + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, pair in enumerate(self.model_name_pairs): + out1 = predicts[pair[0]] + out2 = predicts[pair[1]] + if self.key is not None: + out1 = out1[self.key] + out2 = out2[self.key] + out1 = out1.reshape([-1, out1.shape[-1]]) + out2 = out2.reshape([-1, out2.shape[-1]]) + + attention_mask = batch[2] + if attention_mask is not None: + active_output = attention_mask.reshape([-1, ]) == 1 + out1 = out1[active_output] + out2 = out2[active_output] + + loss_dict["{}_{}".format(self.name, idx)] = super().forward(out1, + out2) + + return loss_dict + + +class DistillationVQADistanceLoss(DistanceLoss): + def __init__(self, + mode="l2", + model_name_pairs=[], + key=None, + name="loss_distance", + **kargs): + super().__init__(mode=mode, **kargs) + assert isinstance(model_name_pairs, list) + self.key = key + self.model_name_pairs = model_name_pairs + self.name = name + "_l2" + + def forward(self, predicts, batch): + loss_dict = dict() + for idx, pair in enumerate(self.model_name_pairs): + out1 = predicts[pair[0]] + out2 = predicts[pair[1]] + attention_mask = batch[2] + if self.key is not None: + out1 = out1[self.key] + out2 = out2[self.key] + if attention_mask is not None: + max_len = attention_mask.shape[-1] + out1 = out1[:, :max_len] + out2 = out2[:, :max_len] + out1 = out1.reshape([-1, out1.shape[-1]]) + out2 = out2.reshape([-1, out2.shape[-1]]) + if attention_mask is not None: + active_output = attention_mask.reshape([-1, ]) == 1 + out1 = out1[active_output] + out2 = out2[active_output] + + loss = super().forward(out1, out2) + if isinstance(loss, dict): + for key in loss: + loss_dict["{}_{}nohu_{}".format(self.name, key, + idx)] = loss[key] + else: + loss_dict["{}_{}_{}_{}".format(self.name, pair[0], pair[1], + idx)] = loss + return loss_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/e2e_pg_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/e2e_pg_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..10a8ed0aa907123b155976ba498426604f23c2b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/e2e_pg_loss.py @@ -0,0 +1,140 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +import paddle + +from .det_basic_loss import DiceLoss +from ppocr.utils.e2e_utils.extract_batchsize import pre_process + + +class PGLoss(nn.Layer): + def __init__(self, + tcl_bs, + max_text_length, + max_text_nums, + pad_num, + eps=1e-6, + **kwargs): + super(PGLoss, self).__init__() + self.tcl_bs = tcl_bs + self.max_text_nums = max_text_nums + self.max_text_length = max_text_length + self.pad_num = pad_num + self.dice_loss = DiceLoss(eps=eps) + + def border_loss(self, f_border, l_border, l_score, l_mask): + l_border_split, l_border_norm = paddle.tensor.split( + l_border, num_or_sections=[4, 1], axis=1) + f_border_split = f_border + b, c, h, w = l_border_norm.shape + l_border_norm_split = paddle.expand( + x=l_border_norm, shape=[b, 4 * c, h, w]) + b, c, h, w = l_score.shape + l_border_score = paddle.expand(x=l_score, shape=[b, 4 * c, h, w]) + b, c, h, w = l_mask.shape + l_border_mask = paddle.expand(x=l_mask, shape=[b, 4 * c, h, w]) + border_diff = l_border_split - f_border_split + abs_border_diff = paddle.abs(border_diff) + border_sign = abs_border_diff < 1.0 + border_sign = paddle.cast(border_sign, dtype='float32') + border_sign.stop_gradient = True + border_in_loss = 0.5 * abs_border_diff * abs_border_diff * border_sign + \ + (abs_border_diff - 0.5) * (1.0 - border_sign) + border_out_loss = l_border_norm_split * border_in_loss + border_loss = paddle.sum(border_out_loss * l_border_score * l_border_mask) / \ + (paddle.sum(l_border_score * l_border_mask) + 1e-5) + return border_loss + + def direction_loss(self, f_direction, l_direction, l_score, l_mask): + l_direction_split, l_direction_norm = paddle.tensor.split( + l_direction, num_or_sections=[2, 1], axis=1) + f_direction_split = f_direction + b, c, h, w = l_direction_norm.shape + l_direction_norm_split = paddle.expand( + x=l_direction_norm, shape=[b, 2 * c, h, w]) + b, c, h, w = l_score.shape + l_direction_score = paddle.expand(x=l_score, shape=[b, 2 * c, h, w]) + b, c, h, w = l_mask.shape + l_direction_mask = paddle.expand(x=l_mask, shape=[b, 2 * c, h, w]) + direction_diff = l_direction_split - f_direction_split + abs_direction_diff = paddle.abs(direction_diff) + direction_sign = abs_direction_diff < 1.0 + direction_sign = paddle.cast(direction_sign, dtype='float32') + direction_sign.stop_gradient = True + direction_in_loss = 0.5 * abs_direction_diff * abs_direction_diff * direction_sign + \ + (abs_direction_diff - 0.5) * (1.0 - direction_sign) + direction_out_loss = l_direction_norm_split * direction_in_loss + direction_loss = paddle.sum(direction_out_loss * l_direction_score * l_direction_mask) / \ + (paddle.sum(l_direction_score * l_direction_mask) + 1e-5) + return direction_loss + + def ctcloss(self, f_char, tcl_pos, tcl_mask, tcl_label, label_t): + f_char = paddle.transpose(f_char, [0, 2, 3, 1]) + tcl_pos = paddle.reshape(tcl_pos, [-1, 3]) + tcl_pos = paddle.cast(tcl_pos, dtype=int) + f_tcl_char = paddle.gather_nd(f_char, tcl_pos) + f_tcl_char = paddle.reshape(f_tcl_char, + [-1, 64, 37]) # len(Lexicon_Table)+1 + f_tcl_char_fg, f_tcl_char_bg = paddle.split(f_tcl_char, [36, 1], axis=2) + f_tcl_char_bg = f_tcl_char_bg * tcl_mask + (1.0 - tcl_mask) * 20.0 + b, c, l = tcl_mask.shape + tcl_mask_fg = paddle.expand(x=tcl_mask, shape=[b, c, 36 * l]) + tcl_mask_fg.stop_gradient = True + f_tcl_char_fg = f_tcl_char_fg * tcl_mask_fg + (1.0 - tcl_mask_fg) * ( + -20.0) + f_tcl_char_mask = paddle.concat([f_tcl_char_fg, f_tcl_char_bg], axis=2) + f_tcl_char_ld = paddle.transpose(f_tcl_char_mask, (1, 0, 2)) + N, B, _ = f_tcl_char_ld.shape + input_lengths = paddle.to_tensor([N] * B, dtype='int64') + cost = paddle.nn.functional.ctc_loss( + log_probs=f_tcl_char_ld, + labels=tcl_label, + input_lengths=input_lengths, + label_lengths=label_t, + blank=self.pad_num, + reduction='none') + cost = cost.mean() + return cost + + def forward(self, predicts, labels): + images, tcl_maps, tcl_label_maps, border_maps \ + , direction_maps, training_masks, label_list, pos_list, pos_mask = labels + # for all the batch_size + pos_list, pos_mask, label_list, label_t = pre_process( + label_list, pos_list, pos_mask, self.max_text_length, + self.max_text_nums, self.pad_num, self.tcl_bs) + + f_score, f_border, f_direction, f_char = predicts['f_score'], predicts['f_border'], predicts['f_direction'], \ + predicts['f_char'] + score_loss = self.dice_loss(f_score, tcl_maps, training_masks) + border_loss = self.border_loss(f_border, border_maps, tcl_maps, + training_masks) + direction_loss = self.direction_loss(f_direction, direction_maps, + tcl_maps, training_masks) + ctc_loss = self.ctcloss(f_char, pos_list, pos_mask, label_list, label_t) + loss_all = score_loss + border_loss + direction_loss + 5 * ctc_loss + + losses = { + 'loss': loss_all, + "score_loss": score_loss, + "border_loss": border_loss, + "direction_loss": direction_loss, + "ctc_loss": ctc_loss + } + return losses diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/kie_sdmgr_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/kie_sdmgr_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..745671f58da91c108624097faea72d55c1877f6b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/kie_sdmgr_loss.py @@ -0,0 +1,115 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +# reference from : https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/kie/losses/sdmgr_loss.py + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +import paddle + + +class SDMGRLoss(nn.Layer): + def __init__(self, node_weight=1.0, edge_weight=1.0, ignore=0): + super().__init__() + self.loss_node = nn.CrossEntropyLoss(ignore_index=ignore) + self.loss_edge = nn.CrossEntropyLoss(ignore_index=-1) + self.node_weight = node_weight + self.edge_weight = edge_weight + self.ignore = ignore + + def pre_process(self, gts, tag): + gts, tag = gts.numpy(), tag.numpy().tolist() + temp_gts = [] + batch = len(tag) + for i in range(batch): + num, recoder_len = tag[i][0], tag[i][1] + temp_gts.append( + paddle.to_tensor( + gts[i, :num, :num + 1], dtype='int64')) + return temp_gts + + def accuracy(self, pred, target, topk=1, thresh=None): + """Calculate accuracy according to the prediction and target. + + Args: + pred (torch.Tensor): The model prediction, shape (N, num_class) + target (torch.Tensor): The target of each prediction, shape (N, ) + topk (int | tuple[int], optional): If the predictions in ``topk`` + matches the target, the predictions will be regarded as + correct ones. Defaults to 1. + thresh (float, optional): If not None, predictions with scores under + this threshold are considered incorrect. Default to None. + + Returns: + float | tuple[float]: If the input ``topk`` is a single integer, + the function will return a single float as accuracy. If + ``topk`` is a tuple containing multiple integers, the + function will return a tuple containing accuracies of + each ``topk`` number. + """ + assert isinstance(topk, (int, tuple)) + if isinstance(topk, int): + topk = (topk, ) + return_single = True + else: + return_single = False + + maxk = max(topk) + if pred.shape[0] == 0: + accu = [pred.new_tensor(0.) for i in range(len(topk))] + return accu[0] if return_single else accu + pred_value, pred_label = paddle.topk(pred, maxk, axis=1) + pred_label = pred_label.transpose( + [1, 0]) # transpose to shape (maxk, N) + correct = paddle.equal(pred_label, + (target.reshape([1, -1]).expand_as(pred_label))) + res = [] + for k in topk: + correct_k = paddle.sum(correct[:k].reshape([-1]).astype('float32'), + axis=0, + keepdim=True) + res.append( + paddle.multiply(correct_k, + paddle.to_tensor(100.0 / pred.shape[0]))) + return res[0] if return_single else res + + def forward(self, pred, batch): + node_preds, edge_preds = pred + gts, tag = batch[4], batch[5] + gts = self.pre_process(gts, tag) + node_gts, edge_gts = [], [] + for gt in gts: + node_gts.append(gt[:, 0]) + edge_gts.append(gt[:, 1:].reshape([-1])) + node_gts = paddle.concat(node_gts) + edge_gts = paddle.concat(edge_gts) + + node_valids = paddle.nonzero(node_gts != self.ignore).reshape([-1]) + edge_valids = paddle.nonzero(edge_gts != -1).reshape([-1]) + loss_node = self.loss_node(node_preds, node_gts) + loss_edge = self.loss_edge(edge_preds, edge_gts) + loss = self.node_weight * loss_node + self.edge_weight * loss_edge + return dict( + loss=loss, + loss_node=loss_node, + loss_edge=loss_edge, + acc_node=self.accuracy( + paddle.gather(node_preds, node_valids), + paddle.gather(node_gts, node_valids)), + acc_edge=self.accuracy( + paddle.gather(edge_preds, edge_valids), + paddle.gather(edge_gts, edge_valids))) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_aster_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_aster_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..9927fbc043f2af146e51cbb9a549f1dffc980341 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_aster_loss.py @@ -0,0 +1,98 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class CosineEmbeddingLoss(nn.Layer): + def __init__(self, margin=0.): + super(CosineEmbeddingLoss, self).__init__() + self.margin = margin + self.epsilon = 1e-12 + + def forward(self, x1, x2, target): + similarity = paddle.sum(x1 * x2, axis=-1) / (paddle.norm( + x1, axis=-1) * paddle.norm( + x2, axis=-1) + self.epsilon) + one_list = paddle.full_like(target, fill_value=1) + out = paddle.mean( + paddle.where( + paddle.equal(target, one_list), 1. - similarity, + paddle.maximum( + paddle.zeros_like(similarity), similarity - self.margin))) + + return out + + +class AsterLoss(nn.Layer): + def __init__(self, + weight=None, + size_average=True, + ignore_index=-100, + sequence_normalize=False, + sample_normalize=True, + **kwargs): + super(AsterLoss, self).__init__() + self.weight = weight + self.size_average = size_average + self.ignore_index = ignore_index + self.sequence_normalize = sequence_normalize + self.sample_normalize = sample_normalize + self.loss_sem = CosineEmbeddingLoss() + self.is_cosin_loss = True + self.loss_func_rec = nn.CrossEntropyLoss(weight=None, reduction='none') + + def forward(self, predicts, batch): + targets = batch[1].astype("int64") + label_lengths = batch[2].astype('int64') + sem_target = batch[3].astype('float32') + embedding_vectors = predicts['embedding_vectors'] + rec_pred = predicts['rec_pred'] + + if not self.is_cosin_loss: + sem_loss = paddle.sum(self.loss_sem(embedding_vectors, sem_target)) + else: + label_target = paddle.ones([embedding_vectors.shape[0]]) + sem_loss = paddle.sum( + self.loss_sem(embedding_vectors, sem_target, label_target)) + + # rec loss + batch_size, def_max_length = targets.shape[0], targets.shape[1] + + mask = paddle.zeros([batch_size, def_max_length]) + for i in range(batch_size): + mask[i, :label_lengths[i]] = 1 + mask = paddle.cast(mask, "float32") + max_length = max(label_lengths) + assert max_length == rec_pred.shape[1] + targets = targets[:, :max_length] + mask = mask[:, :max_length] + rec_pred = paddle.reshape(rec_pred, [-1, rec_pred.shape[2]]) + input = nn.functional.log_softmax(rec_pred, axis=1) + targets = paddle.reshape(targets, [-1, 1]) + mask = paddle.reshape(mask, [-1, 1]) + output = -paddle.index_sample(input, index=targets) * mask + output = paddle.sum(output) + if self.sequence_normalize: + output = output / paddle.sum(mask) + if self.sample_normalize: + output = output / batch_size + + loss = output + sem_loss * 0.1 + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_att_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_att_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..6e2f67483c86a45f3aa1feb1e1fac1a5013bfb46 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_att_loss.py @@ -0,0 +1,39 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class AttentionLoss(nn.Layer): + def __init__(self, **kwargs): + super(AttentionLoss, self).__init__() + self.loss_func = nn.CrossEntropyLoss(weight=None, reduction='none') + + def forward(self, predicts, batch): + targets = batch[1].astype("int64") + label_lengths = batch[2].astype('int64') + batch_size, num_steps, num_classes = predicts.shape[0], predicts.shape[ + 1], predicts.shape[2] + assert len(targets.shape) == len(list(predicts.shape)) - 1, \ + "The target's shape and inputs's shape is [N, d] and [N, num_steps]" + + inputs = paddle.reshape(predicts, [-1, predicts.shape[-1]]) + targets = paddle.reshape(targets, [-1]) + + return {'loss': paddle.sum(self.loss_func(inputs, targets))} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ce_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ce_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..614384de863c15b106aef831f8e938b89dadc246 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ce_loss.py @@ -0,0 +1,66 @@ +import paddle +from paddle import nn +import paddle.nn.functional as F + + +class CELoss(nn.Layer): + def __init__(self, + smoothing=False, + with_all=False, + ignore_index=-1, + **kwargs): + super(CELoss, self).__init__() + if ignore_index >= 0: + self.loss_func = nn.CrossEntropyLoss( + reduction='mean', ignore_index=ignore_index) + else: + self.loss_func = nn.CrossEntropyLoss(reduction='mean') + self.smoothing = smoothing + self.with_all = with_all + + def forward(self, pred, batch): + + if isinstance(pred, dict): # for ABINet + loss = {} + loss_sum = [] + for name, logits in pred.items(): + if isinstance(logits, list): + logit_num = len(logits) + all_tgt = paddle.concat([batch[1]] * logit_num, 0) + all_logits = paddle.concat(logits, 0) + flt_logtis = all_logits.reshape([-1, all_logits.shape[2]]) + flt_tgt = all_tgt.reshape([-1]) + else: + flt_logtis = logits.reshape([-1, logits.shape[2]]) + flt_tgt = batch[1].reshape([-1]) + loss[name + '_loss'] = self.loss_func(flt_logtis, flt_tgt) + loss_sum.append(loss[name + '_loss']) + loss['loss'] = sum(loss_sum) + return loss + else: + if self.with_all: # for ViTSTR + tgt = batch[1] + pred = pred.reshape([-1, pred.shape[2]]) + tgt = tgt.reshape([-1]) + loss = self.loss_func(pred, tgt) + return {'loss': loss} + else: # for NRTR + max_len = batch[2].max() + tgt = batch[1][:, 1:2 + max_len] + pred = pred.reshape([-1, pred.shape[2]]) + tgt = tgt.reshape([-1]) + if self.smoothing: + eps = 0.1 + n_class = pred.shape[1] + one_hot = F.one_hot(tgt, pred.shape[1]) + one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / ( + n_class - 1) + log_prb = F.log_softmax(pred, axis=1) + non_pad_mask = paddle.not_equal( + tgt, paddle.zeros( + tgt.shape, dtype=tgt.dtype)) + loss = -(one_hot * log_prb).sum(axis=1) + loss = loss.masked_select(non_pad_mask).mean() + else: + loss = self.loss_func(pred, tgt) + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ctc_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ctc_loss.py new file mode 100755 index 0000000000000000000000000000000000000000..502fc8c5227460c1e299ae2a46d464d29ddbe374 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_ctc_loss.py @@ -0,0 +1,45 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class CTCLoss(nn.Layer): + def __init__(self, use_focal_loss=False, **kwargs): + super(CTCLoss, self).__init__() + self.loss_func = nn.CTCLoss(blank=0, reduction='none') + self.use_focal_loss = use_focal_loss + + def forward(self, predicts, batch): + if isinstance(predicts, (list, tuple)): + predicts = predicts[-1] + predicts = predicts.transpose((1, 0, 2)) + N, B, _ = predicts.shape + preds_lengths = paddle.to_tensor( + [N] * B, dtype='int64', place=paddle.CPUPlace()) + labels = batch[1].astype("int32") + label_lengths = batch[2].astype('int64') + loss = self.loss_func(predicts, labels, preds_lengths, label_lengths) + if self.use_focal_loss: + weight = paddle.exp(-loss) + weight = paddle.subtract(paddle.to_tensor([1.0]), weight) + weight = paddle.square(weight) + loss = paddle.multiply(loss, weight) + loss = loss.mean() + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_enhanced_ctc_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_enhanced_ctc_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..b57be6468e2ec75811442e7449525267e7d9e82e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_enhanced_ctc_loss.py @@ -0,0 +1,70 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +from .ace_loss import ACELoss +from .center_loss import CenterLoss +from .rec_ctc_loss import CTCLoss + + +class EnhancedCTCLoss(nn.Layer): + def __init__(self, + use_focal_loss=False, + use_ace_loss=False, + ace_loss_weight=0.1, + use_center_loss=False, + center_loss_weight=0.05, + num_classes=6625, + feat_dim=96, + init_center=False, + center_file_path=None, + **kwargs): + super(EnhancedCTCLoss, self).__init__() + self.ctc_loss_func = CTCLoss(use_focal_loss=use_focal_loss) + + self.use_ace_loss = False + if use_ace_loss: + self.use_ace_loss = use_ace_loss + self.ace_loss_func = ACELoss() + self.ace_loss_weight = ace_loss_weight + + self.use_center_loss = False + if use_center_loss: + self.use_center_loss = use_center_loss + self.center_loss_func = CenterLoss( + num_classes=num_classes, + feat_dim=feat_dim, + init_center=init_center, + center_file_path=center_file_path) + self.center_loss_weight = center_loss_weight + + def __call__(self, predicts, batch): + loss = self.ctc_loss_func(predicts, batch)["loss"] + + if self.use_center_loss: + center_loss = self.center_loss_func( + predicts, batch)["loss_center"] * self.center_loss_weight + loss = loss + center_loss + + if self.use_ace_loss: + ace_loss = self.ace_loss_func( + predicts, batch)["loss_ace"] * self.ace_loss_weight + loss = loss + ace_loss + + return {'enhanced_ctc_loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_multi_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_multi_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..09f007afe6303e83b9a6948df553ec0fca8b6b2d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_multi_loss.py @@ -0,0 +1,58 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + +from .rec_ctc_loss import CTCLoss +from .rec_sar_loss import SARLoss + + +class MultiLoss(nn.Layer): + def __init__(self, **kwargs): + super().__init__() + self.loss_funcs = {} + self.loss_list = kwargs.pop('loss_config_list') + self.weight_1 = kwargs.get('weight_1', 1.0) + self.weight_2 = kwargs.get('weight_2', 1.0) + self.gtc_loss = kwargs.get('gtc_loss', 'sar') + for loss_info in self.loss_list: + for name, param in loss_info.items(): + if param is not None: + kwargs.update(param) + loss = eval(name)(**kwargs) + self.loss_funcs[name] = loss + + def forward(self, predicts, batch): + self.total_loss = {} + total_loss = 0.0 + # batch [image, label_ctc, label_sar, length, valid_ratio] + for name, loss_func in self.loss_funcs.items(): + if name == 'CTCLoss': + loss = loss_func(predicts['ctc'], + batch[:2] + batch[3:])['loss'] * self.weight_1 + elif name == 'SARLoss': + loss = loss_func(predicts['sar'], + batch[:1] + batch[2:])['loss'] * self.weight_2 + else: + raise NotImplementedError( + '{} is not supported in MultiLoss yet'.format(name)) + self.total_loss[name] = loss + total_loss += loss + self.total_loss['loss'] = total_loss + return self.total_loss diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_pren_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_pren_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc53d29b2474eeb7897586d1bb7b8c6df2d400e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_pren_loss.py @@ -0,0 +1,30 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn + + +class PRENLoss(nn.Layer): + def __init__(self, **kwargs): + super(PRENLoss, self).__init__() + # note: 0 is padding idx + self.loss_func = nn.CrossEntropyLoss(reduction='mean', ignore_index=0) + + def forward(self, predicts, batch): + loss = self.loss_func(predicts, batch[1].astype('int64')) + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_sar_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_sar_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a4f83f03c08e4c4e6bab308aebc2daa8aa612400 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_sar_loss.py @@ -0,0 +1,29 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class SARLoss(nn.Layer): + def __init__(self, **kwargs): + super(SARLoss, self).__init__() + ignore_index = kwargs.get('ignore_index', 92) # 6626 + self.loss_func = paddle.nn.loss.CrossEntropyLoss( + reduction="mean", ignore_index=ignore_index) + + def forward(self, predicts, batch): + predict = predicts[:, : + -1, :] # ignore last index of outputs to be in same seq_len with targets + label = batch[1].astype( + "int64")[:, 1:] # ignore first index of target in loss calculation + batch_size, num_steps, num_classes = predict.shape[0], predict.shape[ + 1], predict.shape[2] + assert len(label.shape) == len(list(predict.shape)) - 1, \ + "The target's shape and inputs's shape is [N, d] and [N, num_steps]" + + inputs = paddle.reshape(predict, [-1, num_classes]) + targets = paddle.reshape(label, [-1]) + loss = self.loss_func(inputs, targets) + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_spin_att_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_spin_att_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..195780c7bfaf4aae5dd23bd72ace268bed9c1d4f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_spin_att_loss.py @@ -0,0 +1,45 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + +'''This code is refer from: +https://github.com/hikopensource/DAVAR-Lab-OCR +''' + +class SPINAttentionLoss(nn.Layer): + def __init__(self, reduction='mean', ignore_index=-100, **kwargs): + super(SPINAttentionLoss, self).__init__() + self.loss_func = nn.CrossEntropyLoss(weight=None, reduction=reduction, ignore_index=ignore_index) + + def forward(self, predicts, batch): + targets = batch[1].astype("int64") + targets = targets[:, 1:] # remove [eos] in label + + label_lengths = batch[2].astype('int64') + batch_size, num_steps, num_classes = predicts.shape[0], predicts.shape[ + 1], predicts.shape[2] + assert len(targets.shape) == len(list(predicts.shape)) - 1, \ + "The target's shape and inputs's shape is [N, d] and [N, num_steps]" + + inputs = paddle.reshape(predicts, [-1, predicts.shape[-1]]) + targets = paddle.reshape(targets, [-1]) + + return {'loss': self.loss_func(inputs, targets)} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_srn_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_srn_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5b65ebaf1ee135d1fefe8d93ddc3f77985b132 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_srn_loss.py @@ -0,0 +1,47 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class SRNLoss(nn.Layer): + def __init__(self, **kwargs): + super(SRNLoss, self).__init__() + self.loss_func = paddle.nn.loss.CrossEntropyLoss(reduction="sum") + + def forward(self, predicts, batch): + predict = predicts['predict'] + word_predict = predicts['word_out'] + gsrm_predict = predicts['gsrm_out'] + label = batch[1] + + casted_label = paddle.cast(x=label, dtype='int64') + casted_label = paddle.reshape(x=casted_label, shape=[-1, 1]) + + cost_word = self.loss_func(word_predict, label=casted_label) + cost_gsrm = self.loss_func(gsrm_predict, label=casted_label) + cost_vsfd = self.loss_func(predict, label=casted_label) + + cost_word = paddle.reshape(x=paddle.sum(cost_word), shape=[1]) + cost_gsrm = paddle.reshape(x=paddle.sum(cost_gsrm), shape=[1]) + cost_vsfd = paddle.reshape(x=paddle.sum(cost_vsfd), shape=[1]) + + sum_cost = cost_word * 3.0 + cost_vsfd + cost_gsrm * 0.15 + + return {'loss': sum_cost, 'word_loss': cost_word, 'img_loss': cost_vsfd} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_vl_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_vl_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd87c709bbf81d2fd83d721d49086256f2ab629 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/rec_vl_loss.py @@ -0,0 +1,70 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/wangyuxin87/VisionLAN +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + + +class VLLoss(nn.Layer): + def __init__(self, mode='LF_1', weight_res=0.5, weight_mas=0.5, **kwargs): + super(VLLoss, self).__init__() + self.loss_func = paddle.nn.loss.CrossEntropyLoss(reduction="mean") + assert mode in ['LF_1', 'LF_2', 'LA'] + self.mode = mode + self.weight_res = weight_res + self.weight_mas = weight_mas + + def flatten_label(self, target): + label_flatten = [] + label_length = [] + for i in range(0, target.shape[0]): + cur_label = target[i].tolist() + label_flatten += cur_label[:cur_label.index(0) + 1] + label_length.append(cur_label.index(0) + 1) + label_flatten = paddle.to_tensor(label_flatten, dtype='int64') + label_length = paddle.to_tensor(label_length, dtype='int32') + return (label_flatten, label_length) + + def _flatten(self, sources, lengths): + return paddle.concat([t[:l] for t, l in zip(sources, lengths)]) + + def forward(self, predicts, batch): + text_pre = predicts[0] + target = batch[1].astype('int64') + label_flatten, length = self.flatten_label(target) + text_pre = self._flatten(text_pre, length) + if self.mode == 'LF_1': + loss = self.loss_func(text_pre, label_flatten) + else: + text_rem = predicts[1] + text_mas = predicts[2] + target_res = batch[2].astype('int64') + target_sub = batch[3].astype('int64') + label_flatten_res, length_res = self.flatten_label(target_res) + label_flatten_sub, length_sub = self.flatten_label(target_sub) + text_rem = self._flatten(text_rem, length_res) + text_mas = self._flatten(text_mas, length_sub) + loss_ori = self.loss_func(text_pre, label_flatten) + loss_res = self.loss_func(text_rem, label_flatten_res) + loss_mas = self.loss_func(text_mas, label_flatten_sub) + loss = loss_ori + loss_res * self.weight_res + loss_mas * self.weight_mas + return {'loss': loss} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/stroke_focus_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/stroke_focus_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..002bbc34774cc80599015492762ca448f593df0f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/stroke_focus_loss.py @@ -0,0 +1,68 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/loss/stroke_focus_loss.py +""" +import cv2 +import sys +import time +import string +import random +import numpy as np +import paddle.nn as nn +import paddle + + +class StrokeFocusLoss(nn.Layer): + def __init__(self, character_dict_path=None, **kwargs): + super(StrokeFocusLoss, self).__init__(character_dict_path) + self.mse_loss = nn.MSELoss() + self.ce_loss = nn.CrossEntropyLoss() + self.l1_loss = nn.L1Loss() + self.english_stroke_alphabet = '0123456789' + self.english_stroke_dict = {} + for index in range(len(self.english_stroke_alphabet)): + self.english_stroke_dict[self.english_stroke_alphabet[ + index]] = index + + stroke_decompose_lines = open(character_dict_path, 'r').readlines() + self.dic = {} + for line in stroke_decompose_lines: + line = line.strip() + character, sequence = line.split() + self.dic[character] = sequence + + def forward(self, pred, data): + + sr_img = pred["sr_img"] + hr_img = pred["hr_img"] + + mse_loss = self.mse_loss(sr_img, hr_img) + word_attention_map_gt = pred["word_attention_map_gt"] + word_attention_map_pred = pred["word_attention_map_pred"] + + hr_pred = pred["hr_pred"] + sr_pred = pred["sr_pred"] + + attention_loss = paddle.nn.functional.l1_loss(word_attention_map_gt, + word_attention_map_pred) + + loss = (mse_loss + attention_loss * 50) * 100 + + return { + "mse_loss": mse_loss, + "attention_loss": attention_loss, + "loss": loss + } diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_att_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_att_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..f1771847b46b99d8cf2a3ae69e7e990ee02f26a5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_att_loss.py @@ -0,0 +1,93 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +from paddle.nn import functional as F + + +class TableAttentionLoss(nn.Layer): + def __init__(self, structure_weight, loc_weight, **kwargs): + super(TableAttentionLoss, self).__init__() + self.loss_func = nn.CrossEntropyLoss(weight=None, reduction='none') + self.structure_weight = structure_weight + self.loc_weight = loc_weight + + def forward(self, predicts, batch): + structure_probs = predicts['structure_probs'] + structure_targets = batch[1].astype("int64") + structure_targets = structure_targets[:, 1:] + structure_probs = paddle.reshape(structure_probs, + [-1, structure_probs.shape[-1]]) + structure_targets = paddle.reshape(structure_targets, [-1]) + structure_loss = self.loss_func(structure_probs, structure_targets) + + structure_loss = paddle.mean(structure_loss) * self.structure_weight + + loc_preds = predicts['loc_preds'] + loc_targets = batch[2].astype("float32") + loc_targets_mask = batch[3].astype("float32") + loc_targets = loc_targets[:, 1:, :] + loc_targets_mask = loc_targets_mask[:, 1:, :] + loc_loss = F.mse_loss(loc_preds * loc_targets_mask, + loc_targets) * self.loc_weight + + total_loss = structure_loss + loc_loss + return { + 'loss': total_loss, + "structure_loss": structure_loss, + "loc_loss": loc_loss + } + + +class SLALoss(nn.Layer): + def __init__(self, structure_weight, loc_weight, loc_loss='mse', **kwargs): + super(SLALoss, self).__init__() + self.loss_func = nn.CrossEntropyLoss(weight=None, reduction='mean') + self.structure_weight = structure_weight + self.loc_weight = loc_weight + self.loc_loss = loc_loss + self.eps = 1e-12 + + def forward(self, predicts, batch): + structure_probs = predicts['structure_probs'] + structure_targets = batch[1].astype("int64") + structure_targets = structure_targets[:, 1:] + + structure_loss = self.loss_func(structure_probs, structure_targets) + + structure_loss = paddle.mean(structure_loss) * self.structure_weight + + loc_preds = predicts['loc_preds'] + loc_targets = batch[2].astype("float32") + loc_targets_mask = batch[3].astype("float32") + loc_targets = loc_targets[:, 1:, :] + loc_targets_mask = loc_targets_mask[:, 1:, :] + + loc_loss = F.smooth_l1_loss( + loc_preds * loc_targets_mask, + loc_targets * loc_targets_mask, + reduction='sum') * self.loc_weight + + loc_loss = loc_loss / (loc_targets_mask.sum() + self.eps) + total_loss = structure_loss + loc_loss + return { + 'loss': total_loss, + "structure_loss": structure_loss, + "loc_loss": loc_loss + } diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_master_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_master_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..dca982dbd43e2c14f15503e1e98d6fe6c18878c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/table_master_loss.py @@ -0,0 +1,70 @@ +# Copyright (c) 2021 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. +""" +This code is refer from: +https://github.com/JiaquanYe/TableMASTER-mmocr/tree/master/mmocr/models/textrecog/losses +""" + +import paddle +from paddle import nn + + +class TableMasterLoss(nn.Layer): + def __init__(self, ignore_index=-1): + super(TableMasterLoss, self).__init__() + self.structure_loss = nn.CrossEntropyLoss( + ignore_index=ignore_index, reduction='mean') + self.box_loss = nn.L1Loss(reduction='sum') + self.eps = 1e-12 + + def forward(self, predicts, batch): + # structure_loss + structure_probs = predicts['structure_probs'] + structure_targets = batch[1] + structure_targets = structure_targets[:, 1:] + structure_probs = structure_probs.reshape( + [-1, structure_probs.shape[-1]]) + structure_targets = structure_targets.reshape([-1]) + + structure_loss = self.structure_loss(structure_probs, structure_targets) + structure_loss = structure_loss.mean() + losses = dict(structure_loss=structure_loss) + + # box loss + bboxes_preds = predicts['loc_preds'] + bboxes_targets = batch[2][:, 1:, :] + bbox_masks = batch[3][:, 1:] + # mask empty-bbox or non-bbox structure token's bbox. + + masked_bboxes_preds = bboxes_preds * bbox_masks + masked_bboxes_targets = bboxes_targets * bbox_masks + + # horizon loss (x and width) + horizon_sum_loss = self.box_loss(masked_bboxes_preds[:, :, 0::2], + masked_bboxes_targets[:, :, 0::2]) + horizon_loss = horizon_sum_loss / (bbox_masks.sum() + self.eps) + # vertical loss (y and height) + vertical_sum_loss = self.box_loss(masked_bboxes_preds[:, :, 1::2], + masked_bboxes_targets[:, :, 1::2]) + vertical_loss = vertical_sum_loss / (bbox_masks.sum() + self.eps) + + horizon_loss = horizon_loss.mean() + vertical_loss = vertical_loss.mean() + all_loss = structure_loss + horizon_loss + vertical_loss + losses.update({ + 'loss': all_loss, + 'horizon_bbox_loss': horizon_loss, + 'vertical_bbox_loss': vertical_loss + }) + return losses diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/vqa_token_layoutlm_loss.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/vqa_token_layoutlm_loss.py new file mode 100755 index 0000000000000000000000000000000000000000..5d564c0e26f8fea1359ba3aa489359873a033cb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/losses/vqa_token_layoutlm_loss.py @@ -0,0 +1,46 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +from ppocr.losses.basic_loss import DMLLoss + + +class VQASerTokenLayoutLMLoss(nn.Layer): + def __init__(self, num_classes, key=None): + super().__init__() + self.loss_class = nn.CrossEntropyLoss() + self.num_classes = num_classes + self.ignore_index = self.loss_class.ignore_index + self.key = key + + def forward(self, predicts, batch): + if isinstance(predicts, dict) and self.key is not None: + predicts = predicts[self.key] + labels = batch[5] + attention_mask = batch[2] + if attention_mask is not None: + active_loss = attention_mask.reshape([-1, ]) == 1 + active_output = predicts.reshape( + [-1, self.num_classes])[active_loss] + active_label = labels.reshape([-1, ])[active_loss] + loss = self.loss_class(active_output, active_label) + else: + loss = self.loss_class( + predicts.reshape([-1, self.num_classes]), + labels.reshape([-1, ])) + return {'loss': loss} \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..853647c06cf0519a0e049e14c16a0d3e26f9845b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/__init__.py @@ -0,0 +1,47 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import copy + +__all__ = ["build_metric"] + +from .det_metric import DetMetric, DetFCEMetric +from .rec_metric import RecMetric +from .cls_metric import ClsMetric +from .e2e_metric import E2EMetric +from .distillation_metric import DistillationMetric +from .table_metric import TableMetric +from .kie_metric import KIEMetric +from .vqa_token_ser_metric import VQASerTokenMetric +from .vqa_token_re_metric import VQAReTokenMetric +from .sr_metric import SRMetric + +def build_metric(config): + support_dict = [ + "DetMetric", "DetFCEMetric", "RecMetric", "ClsMetric", "E2EMetric", + "DistillationMetric", "TableMetric", 'KIEMetric', 'VQASerTokenMetric', + 'VQAReTokenMetric', 'SRMetric' + ] + + config = copy.deepcopy(config) + module_name = config.pop("name") + assert module_name in support_dict, Exception( + "metric only support {}".format(support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/cls_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/cls_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..6c077518ce205d4ec4d426aaedb8c0af880122ee --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/cls_metric.py @@ -0,0 +1,46 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + + +class ClsMetric(object): + def __init__(self, main_indicator='acc', **kwargs): + self.main_indicator = main_indicator + self.eps = 1e-5 + self.reset() + + def __call__(self, pred_label, *args, **kwargs): + preds, labels = pred_label + correct_num = 0 + all_num = 0 + for (pred, pred_conf), (target, _) in zip(preds, labels): + if pred == target: + correct_num += 1 + all_num += 1 + self.correct_num += correct_num + self.all_num += all_num + return {'acc': correct_num / (all_num + self.eps), } + + def get_metric(self): + """ + return metrics { + 'acc': 0 + } + """ + acc = self.correct_num / (self.all_num + self.eps) + self.reset() + return {'acc': acc} + + def reset(self): + self.correct_num = 0 + self.all_num = 0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/det_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/det_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..dca94c092790b121c46c4f1c0f0355391ef8dba9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/det_metric.py @@ -0,0 +1,154 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +__all__ = ['DetMetric', 'DetFCEMetric'] + +from .eval_det_iou import DetectionIoUEvaluator + + +class DetMetric(object): + def __init__(self, main_indicator='hmean', **kwargs): + self.evaluator = DetectionIoUEvaluator() + self.main_indicator = main_indicator + self.reset() + + def __call__(self, preds, batch, **kwargs): + ''' + batch: a list produced by dataloaders. + image: np.ndarray of shape (N, C, H, W). + ratio_list: np.ndarray of shape(N,2) + polygons: np.ndarray of shape (N, K, 4, 2), the polygons of objective regions. + ignore_tags: np.ndarray of shape (N, K), indicates whether a region is ignorable or not. + preds: a list of dict produced by post process + points: np.ndarray of shape (N, K, 4, 2), the polygons of objective regions. + ''' + gt_polyons_batch = batch[2] + ignore_tags_batch = batch[3] + for pred, gt_polyons, ignore_tags in zip(preds, gt_polyons_batch, + ignore_tags_batch): + # prepare gt + gt_info_list = [{ + 'points': gt_polyon, + 'text': '', + 'ignore': ignore_tag + } for gt_polyon, ignore_tag in zip(gt_polyons, ignore_tags)] + # prepare det + det_info_list = [{ + 'points': det_polyon, + 'text': '' + } for det_polyon in pred['points']] + result = self.evaluator.evaluate_image(gt_info_list, det_info_list) + self.results.append(result) + + def get_metric(self): + """ + return metrics { + 'precision': 0, + 'recall': 0, + 'hmean': 0 + } + """ + + metrics = self.evaluator.combine_results(self.results) + self.reset() + return metrics + + def reset(self): + self.results = [] # clear results + + +class DetFCEMetric(object): + def __init__(self, main_indicator='hmean', **kwargs): + self.evaluator = DetectionIoUEvaluator() + self.main_indicator = main_indicator + self.reset() + + def __call__(self, preds, batch, **kwargs): + ''' + batch: a list produced by dataloaders. + image: np.ndarray of shape (N, C, H, W). + ratio_list: np.ndarray of shape(N,2) + polygons: np.ndarray of shape (N, K, 4, 2), the polygons of objective regions. + ignore_tags: np.ndarray of shape (N, K), indicates whether a region is ignorable or not. + preds: a list of dict produced by post process + points: np.ndarray of shape (N, K, 4, 2), the polygons of objective regions. + ''' + gt_polyons_batch = batch[2] + ignore_tags_batch = batch[3] + + for pred, gt_polyons, ignore_tags in zip(preds, gt_polyons_batch, + ignore_tags_batch): + # prepare gt + gt_info_list = [{ + 'points': gt_polyon, + 'text': '', + 'ignore': ignore_tag + } for gt_polyon, ignore_tag in zip(gt_polyons, ignore_tags)] + # prepare det + det_info_list = [{ + 'points': det_polyon, + 'text': '', + 'score': score + } for det_polyon, score in zip(pred['points'], pred['scores'])] + + for score_thr in self.results.keys(): + det_info_list_thr = [ + det_info for det_info in det_info_list + if det_info['score'] >= score_thr + ] + result = self.evaluator.evaluate_image(gt_info_list, + det_info_list_thr) + self.results[score_thr].append(result) + + def get_metric(self): + """ + return metrics {'heman':0, + 'thr 0.3':'precision: 0 recall: 0 hmean: 0', + 'thr 0.4':'precision: 0 recall: 0 hmean: 0', + 'thr 0.5':'precision: 0 recall: 0 hmean: 0', + 'thr 0.6':'precision: 0 recall: 0 hmean: 0', + 'thr 0.7':'precision: 0 recall: 0 hmean: 0', + 'thr 0.8':'precision: 0 recall: 0 hmean: 0', + 'thr 0.9':'precision: 0 recall: 0 hmean: 0', + } + """ + metrics = {} + hmean = 0 + for score_thr in self.results.keys(): + metric = self.evaluator.combine_results(self.results[score_thr]) + # for key, value in metric.items(): + # metrics['{}_{}'.format(key, score_thr)] = value + metric_str = 'precision:{:.5f} recall:{:.5f} hmean:{:.5f}'.format( + metric['precision'], metric['recall'], metric['hmean']) + metrics['thr {}'.format(score_thr)] = metric_str + hmean = max(hmean, metric['hmean']) + metrics['hmean'] = hmean + + self.reset() + return metrics + + def reset(self): + self.results = { + 0.3: [], + 0.4: [], + 0.5: [], + 0.6: [], + 0.7: [], + 0.8: [], + 0.9: [] + } # clear results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/distillation_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/distillation_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..e2cbc4dc07c4e7b234ca964eb9fc0259dfab6ab4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/distillation_metric.py @@ -0,0 +1,75 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import importlib +import copy + +from .rec_metric import RecMetric +from .det_metric import DetMetric +from .e2e_metric import E2EMetric +from .cls_metric import ClsMetric +from .vqa_token_ser_metric import VQASerTokenMetric +from .vqa_token_re_metric import VQAReTokenMetric + + +class DistillationMetric(object): + def __init__(self, + key=None, + base_metric_name=None, + main_indicator=None, + **kwargs): + self.main_indicator = main_indicator + self.key = key + self.main_indicator = main_indicator + self.base_metric_name = base_metric_name + self.kwargs = kwargs + self.metrics = None + + def _init_metrcis(self, preds): + self.metrics = dict() + mod = importlib.import_module(__name__) + for key in preds: + self.metrics[key] = getattr(mod, self.base_metric_name)( + main_indicator=self.main_indicator, **self.kwargs) + self.metrics[key].reset() + + def __call__(self, preds, batch, **kwargs): + assert isinstance(preds, dict) + if self.metrics is None: + self._init_metrcis(preds) + output = dict() + for key in preds: + self.metrics[key].__call__(preds[key], batch, **kwargs) + + def get_metric(self): + """ + return metrics { + 'acc': 0, + 'norm_edit_dis': 0, + } + """ + output = dict() + for key in self.metrics: + metric = self.metrics[key].get_metric() + # main indicator + if key == self.key: + output.update(metric) + else: + for sub_key in metric: + output["{}_{}".format(key, sub_key)] = metric[sub_key] + return output + + def reset(self): + for key in self.metrics: + self.metrics[key].reset() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/e2e_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/e2e_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8ba3b222022099501e6bda48266ef51a40e9db --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/e2e_metric.py @@ -0,0 +1,86 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +__all__ = ['E2EMetric'] + +from ppocr.utils.e2e_metric.Deteval import get_socre_A, get_socre_B, combine_results +from ppocr.utils.e2e_utils.extract_textpoint_slow import get_dict + + +class E2EMetric(object): + def __init__(self, + mode, + gt_mat_dir, + character_dict_path, + main_indicator='f_score_e2e', + **kwargs): + self.mode = mode + self.gt_mat_dir = gt_mat_dir + self.label_list = get_dict(character_dict_path) + self.max_index = len(self.label_list) + self.main_indicator = main_indicator + self.reset() + + def __call__(self, preds, batch, **kwargs): + if self.mode == 'A': + gt_polyons_batch = batch[2] + temp_gt_strs_batch = batch[3][0] + ignore_tags_batch = batch[4] + gt_strs_batch = [] + + for temp_list in temp_gt_strs_batch: + t = "" + for index in temp_list: + if index < self.max_index: + t += self.label_list[index] + gt_strs_batch.append(t) + + for pred, gt_polyons, gt_strs, ignore_tags in zip( + [preds], gt_polyons_batch, [gt_strs_batch], ignore_tags_batch): + # prepare gt + gt_info_list = [{ + 'points': gt_polyon, + 'text': gt_str, + 'ignore': ignore_tag + } for gt_polyon, gt_str, ignore_tag in + zip(gt_polyons, gt_strs, ignore_tags)] + # prepare det + e2e_info_list = [{ + 'points': det_polyon, + 'texts': pred_str + } for det_polyon, pred_str in + zip(pred['points'], pred['texts'])] + + result = get_socre_A(gt_info_list, e2e_info_list) + self.results.append(result) + else: + img_id = batch[5][0] + e2e_info_list = [{ + 'points': det_polyon, + 'texts': pred_str + } for det_polyon, pred_str in zip(preds['points'], preds['texts'])] + result = get_socre_B(self.gt_mat_dir, img_id, e2e_info_list) + self.results.append(result) + + def get_metric(self): + metrics = combine_results(self.results) + self.reset() + return metrics + + def reset(self): + self.results = [] # clear results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/eval_det_iou.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/eval_det_iou.py new file mode 100644 index 0000000000000000000000000000000000000000..c144886b3f84a458a88931d6beb2153054eba7d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/eval_det_iou.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from collections import namedtuple +import numpy as np +from shapely.geometry import Polygon +""" +reference from : +https://github.com/MhLiao/DB/blob/3c32b808d4412680310d3d28eeb6a2d5bf1566c5/concern/icdar2015_eval/detection/iou.py#L8 +""" + + +class DetectionIoUEvaluator(object): + def __init__(self, iou_constraint=0.5, area_precision_constraint=0.5): + self.iou_constraint = iou_constraint + self.area_precision_constraint = area_precision_constraint + + def evaluate_image(self, gt, pred): + def get_union(pD, pG): + return Polygon(pD).union(Polygon(pG)).area + + def get_intersection_over_union(pD, pG): + return get_intersection(pD, pG) / get_union(pD, pG) + + def get_intersection(pD, pG): + return Polygon(pD).intersection(Polygon(pG)).area + + def compute_ap(confList, matchList, numGtCare): + correct = 0 + AP = 0 + if len(confList) > 0: + confList = np.array(confList) + matchList = np.array(matchList) + sorted_ind = np.argsort(-confList) + confList = confList[sorted_ind] + matchList = matchList[sorted_ind] + for n in range(len(confList)): + match = matchList[n] + if match: + correct += 1 + AP += float(correct) / (n + 1) + + if numGtCare > 0: + AP /= numGtCare + + return AP + + perSampleMetrics = {} + + matchedSum = 0 + + Rectangle = namedtuple('Rectangle', 'xmin ymin xmax ymax') + + numGlobalCareGt = 0 + numGlobalCareDet = 0 + + arrGlobalConfidences = [] + arrGlobalMatches = [] + + recall = 0 + precision = 0 + hmean = 0 + + detMatched = 0 + + iouMat = np.empty([1, 1]) + + gtPols = [] + detPols = [] + + gtPolPoints = [] + detPolPoints = [] + + # Array of Ground Truth Polygons' keys marked as don't Care + gtDontCarePolsNum = [] + # Array of Detected Polygons' matched with a don't Care GT + detDontCarePolsNum = [] + + pairs = [] + detMatchedNums = [] + + arrSampleConfidences = [] + arrSampleMatch = [] + + evaluationLog = "" + + for n in range(len(gt)): + points = gt[n]['points'] + dontCare = gt[n]['ignore'] + if not Polygon(points).is_valid: + continue + + gtPol = points + gtPols.append(gtPol) + gtPolPoints.append(points) + if dontCare: + gtDontCarePolsNum.append(len(gtPols) - 1) + + evaluationLog += "GT polygons: " + str(len(gtPols)) + ( + " (" + str(len(gtDontCarePolsNum)) + " don't care)\n" + if len(gtDontCarePolsNum) > 0 else "\n") + + for n in range(len(pred)): + points = pred[n]['points'] + if not Polygon(points).is_valid: + continue + + detPol = points + detPols.append(detPol) + detPolPoints.append(points) + if len(gtDontCarePolsNum) > 0: + for dontCarePol in gtDontCarePolsNum: + dontCarePol = gtPols[dontCarePol] + intersected_area = get_intersection(dontCarePol, detPol) + pdDimensions = Polygon(detPol).area + precision = 0 if pdDimensions == 0 else intersected_area / pdDimensions + if (precision > self.area_precision_constraint): + detDontCarePolsNum.append(len(detPols) - 1) + break + + evaluationLog += "DET polygons: " + str(len(detPols)) + ( + " (" + str(len(detDontCarePolsNum)) + " don't care)\n" + if len(detDontCarePolsNum) > 0 else "\n") + + if len(gtPols) > 0 and len(detPols) > 0: + # Calculate IoU and precision matrixs + outputShape = [len(gtPols), len(detPols)] + iouMat = np.empty(outputShape) + gtRectMat = np.zeros(len(gtPols), np.int8) + detRectMat = np.zeros(len(detPols), np.int8) + for gtNum in range(len(gtPols)): + for detNum in range(len(detPols)): + pG = gtPols[gtNum] + pD = detPols[detNum] + iouMat[gtNum, detNum] = get_intersection_over_union(pD, pG) + + for gtNum in range(len(gtPols)): + for detNum in range(len(detPols)): + if gtRectMat[gtNum] == 0 and detRectMat[ + detNum] == 0 and gtNum not in gtDontCarePolsNum and detNum not in detDontCarePolsNum: + if iouMat[gtNum, detNum] > self.iou_constraint: + gtRectMat[gtNum] = 1 + detRectMat[detNum] = 1 + detMatched += 1 + pairs.append({'gt': gtNum, 'det': detNum}) + detMatchedNums.append(detNum) + evaluationLog += "Match GT #" + \ + str(gtNum) + " with Det #" + str(detNum) + "\n" + + numGtCare = (len(gtPols) - len(gtDontCarePolsNum)) + numDetCare = (len(detPols) - len(detDontCarePolsNum)) + if numGtCare == 0: + recall = float(1) + precision = float(0) if numDetCare > 0 else float(1) + else: + recall = float(detMatched) / numGtCare + precision = 0 if numDetCare == 0 else float(detMatched) / numDetCare + + hmean = 0 if (precision + recall) == 0 else 2.0 * \ + precision * recall / (precision + recall) + + matchedSum += detMatched + numGlobalCareGt += numGtCare + numGlobalCareDet += numDetCare + + perSampleMetrics = { + 'gtCare': numGtCare, + 'detCare': numDetCare, + 'detMatched': detMatched, + } + return perSampleMetrics + + def combine_results(self, results): + numGlobalCareGt = 0 + numGlobalCareDet = 0 + matchedSum = 0 + for result in results: + numGlobalCareGt += result['gtCare'] + numGlobalCareDet += result['detCare'] + matchedSum += result['detMatched'] + + methodRecall = 0 if numGlobalCareGt == 0 else float( + matchedSum) / numGlobalCareGt + methodPrecision = 0 if numGlobalCareDet == 0 else float( + matchedSum) / numGlobalCareDet + methodHmean = 0 if methodRecall + methodPrecision == 0 else 2 * \ + methodRecall * methodPrecision / ( + methodRecall + methodPrecision) + methodMetrics = { + 'precision': methodPrecision, + 'recall': methodRecall, + 'hmean': methodHmean + } + + return methodMetrics + + +if __name__ == '__main__': + evaluator = DetectionIoUEvaluator() + gts = [[{ + 'points': [(0, 0), (1, 0), (1, 1), (0, 1)], + 'text': 1234, + 'ignore': False, + }, { + 'points': [(2, 2), (3, 2), (3, 3), (2, 3)], + 'text': 5678, + 'ignore': False, + }]] + preds = [[{ + 'points': [(0.1, 0.1), (1, 0), (1, 1), (0, 1)], + 'text': 123, + 'ignore': False, + }]] + results = [] + for gt, pred in zip(gts, preds): + results.append(evaluator.evaluate_image(gt, pred)) + metrics = evaluator.combine_results(results) + print(metrics) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/kie_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/kie_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..28ab22b807ffe4347ca95be5a44143539db4c97c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/kie_metric.py @@ -0,0 +1,71 @@ +# Copyright (c) 2021 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. +# The code is refer from: https://github.com/open-mmlab/mmocr/blob/main/mmocr/core/evaluation/kie_metric.py + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import paddle + +__all__ = ['KIEMetric'] + + +class KIEMetric(object): + def __init__(self, main_indicator='hmean', **kwargs): + self.main_indicator = main_indicator + self.reset() + self.node = [] + self.gt = [] + + def __call__(self, preds, batch, **kwargs): + nodes, _ = preds + gts, tag = batch[4].squeeze(0), batch[5].tolist()[0] + gts = gts[:tag[0], :1].reshape([-1]) + self.node.append(nodes.numpy()) + self.gt.append(gts) + # result = self.compute_f1_score(nodes, gts) + # self.results.append(result) + + def compute_f1_score(self, preds, gts): + ignores = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 25] + C = preds.shape[1] + classes = np.array(sorted(set(range(C)) - set(ignores))) + hist = np.bincount( + (gts * C).astype('int64') + preds.argmax(1), minlength=C + **2).reshape([C, C]).astype('float32') + diag = np.diag(hist) + recalls = diag / hist.sum(1).clip(min=1) + precisions = diag / hist.sum(0).clip(min=1) + f1 = 2 * recalls * precisions / (recalls + precisions).clip(min=1e-8) + return f1[classes] + + def combine_results(self, results): + node = np.concatenate(self.node, 0) + gts = np.concatenate(self.gt, 0) + results = self.compute_f1_score(node, gts) + data = {'hmean': results.mean()} + return data + + def get_metric(self): + + metrics = self.combine_results(self.results) + self.reset() + return metrics + + def reset(self): + self.results = [] # clear results + self.node = [] + self.gt = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/rec_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/rec_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..9863978116b1340fa809e8919a6a37d598d6bbdf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/rec_metric.py @@ -0,0 +1,76 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from rapidfuzz.distance import Levenshtein +import string + + + +class RecMetric(object): + def __init__(self, + main_indicator='acc', + is_filter=False, + ignore_space=True, + **kwargs): + self.main_indicator = main_indicator + self.is_filter = is_filter + self.ignore_space = ignore_space + self.eps = 1e-5 + self.reset() + + def _normalize_text(self, text): + text = ''.join( + filter(lambda x: x in (string.digits + string.ascii_letters), text)) + return text.lower() + + def __call__(self, pred_label, *args, **kwargs): + preds, labels = pred_label + correct_num = 0 + all_num = 0 + norm_edit_dis = 0.0 + for (pred, pred_conf), (target, _) in zip(preds, labels): + if self.ignore_space: + pred = pred.replace(" ", "") + target = target.replace(" ", "") + if self.is_filter: + pred = self._normalize_text(pred) + target = self._normalize_text(target) + norm_edit_dis += Levenshtein.normalized_distance(pred, target) + if pred == target: + correct_num += 1 + all_num += 1 + self.correct_num += correct_num + self.all_num += all_num + self.norm_edit_dis += norm_edit_dis + return { + 'acc': correct_num / (all_num + self.eps), + 'norm_edit_dis': 1 - norm_edit_dis / (all_num + self.eps) + } + + def get_metric(self): + """ + return metrics { + 'acc': 0, + 'norm_edit_dis': 0, + } + """ + acc = 1.0 * self.correct_num / (self.all_num + self.eps) + norm_edit_dis = 1 - self.norm_edit_dis / (self.all_num + self.eps) + self.reset() + return {'acc': acc, 'norm_edit_dis': norm_edit_dis} + + def reset(self): + self.correct_num = 0 + self.all_num = 0 + self.norm_edit_dis = 0 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/sr_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/sr_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..51c3ad66564e61abdd91432e6dc9ea1d8918583b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/sr_metric.py @@ -0,0 +1,155 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/utils/ssim_psnr.py +""" + +from math import exp + +import paddle +import paddle.nn.functional as F +import paddle.nn as nn +import string + + +class SSIM(nn.Layer): + def __init__(self, window_size=11, size_average=True): + super(SSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = 1 + self.window = self.create_window(window_size, self.channel) + + def gaussian(self, window_size, sigma): + gauss = paddle.to_tensor([ + exp(-(x - window_size // 2)**2 / float(2 * sigma**2)) + for x in range(window_size) + ]) + return gauss / gauss.sum() + + def create_window(self, window_size, channel): + _1D_window = self.gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).unsqueeze(0).unsqueeze(0) + window = _2D_window.expand([channel, 1, window_size, window_size]) + return window + + def _ssim(self, img1, img2, window, window_size, channel, + size_average=True): + mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel) + mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d( + img1 * img1, window, padding=window_size // 2, + groups=channel) - mu1_sq + sigma2_sq = F.conv2d( + img2 * img2, window, padding=window_size // 2, + groups=channel) - mu2_sq + sigma12 = F.conv2d( + img1 * img2, window, padding=window_size // 2, + groups=channel) - mu1_mu2 + + C1 = 0.01**2 + C2 = 0.03**2 + + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ( + (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) + + if size_average: + return ssim_map.mean() + else: + return ssim_map.mean([1, 2, 3]) + + def ssim(self, img1, img2, window_size=11, size_average=True): + (_, channel, _, _) = img1.shape + window = self.create_window(window_size, channel) + + return self._ssim(img1, img2, window, window_size, channel, + size_average) + + def forward(self, img1, img2): + (_, channel, _, _) = img1.shape + + if channel == self.channel and self.window.dtype == img1.dtype: + window = self.window + else: + window = self.create_window(self.window_size, channel) + + self.window = window + self.channel = channel + + return self._ssim(img1, img2, window, self.window_size, channel, + self.size_average) + + +class SRMetric(object): + def __init__(self, main_indicator='all', **kwargs): + self.main_indicator = main_indicator + self.eps = 1e-5 + self.psnr_result = [] + self.ssim_result = [] + self.calculate_ssim = SSIM() + self.reset() + + def reset(self): + self.correct_num = 0 + self.all_num = 0 + self.norm_edit_dis = 0 + self.psnr_result = [] + self.ssim_result = [] + + def calculate_psnr(self, img1, img2): + # img1 and img2 have range [0, 1] + mse = ((img1 * 255 - img2 * 255)**2).mean() + if mse == 0: + return float('inf') + return 20 * paddle.log10(255.0 / paddle.sqrt(mse)) + + def _normalize_text(self, text): + text = ''.join( + filter(lambda x: x in (string.digits + string.ascii_letters), text)) + return text.lower() + + def __call__(self, pred_label, *args, **kwargs): + metric = {} + images_sr = pred_label["sr_img"] + images_hr = pred_label["hr_img"] + psnr = self.calculate_psnr(images_sr, images_hr) + ssim = self.calculate_ssim(images_sr, images_hr) + self.psnr_result.append(psnr) + self.ssim_result.append(ssim) + + def get_metric(self): + """ + return metrics { + 'acc': 0, + 'norm_edit_dis': 0, + } + """ + self.psnr_avg = sum(self.psnr_result) / len(self.psnr_result) + self.psnr_avg = round(self.psnr_avg.item(), 6) + self.ssim_avg = sum(self.ssim_result) / len(self.ssim_result) + self.ssim_avg = round(self.ssim_avg.item(), 6) + + self.all_avg = self.psnr_avg + self.ssim_avg + + self.reset() + return { + 'psnr_avg': self.psnr_avg, + "ssim_avg": self.ssim_avg, + "all": self.all_avg + } diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/table_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/table_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b247efa672caacb9a9a09a8ef0da58e47367e4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/table_metric.py @@ -0,0 +1,156 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import numpy as np +from ppocr.metrics.det_metric import DetMetric + + +class TableStructureMetric(object): + def __init__(self, + main_indicator='acc', + eps=1e-6, + del_thead_tbody=False, + **kwargs): + self.main_indicator = main_indicator + self.eps = eps + self.del_thead_tbody = del_thead_tbody + self.reset() + + def __call__(self, pred_label, batch=None, *args, **kwargs): + preds, labels = pred_label + pred_structure_batch_list = preds['structure_batch_list'] + gt_structure_batch_list = labels['structure_batch_list'] + correct_num = 0 + all_num = 0 + for (pred, pred_conf), target in zip(pred_structure_batch_list, + gt_structure_batch_list): + pred_str = ''.join(pred) + target_str = ''.join(target) + if self.del_thead_tbody: + pred_str = pred_str.replace('', '').replace( + '', '').replace('', '').replace('', + '') + target_str = target_str.replace('', '').replace( + '', '').replace('', '').replace('', + '') + if pred_str == target_str: + correct_num += 1 + all_num += 1 + self.correct_num += correct_num + self.all_num += all_num + + def get_metric(self): + """ + return metrics { + 'acc': 0, + } + """ + acc = 1.0 * self.correct_num / (self.all_num + self.eps) + self.reset() + return {'acc': acc} + + def reset(self): + self.correct_num = 0 + self.all_num = 0 + self.len_acc_num = 0 + self.token_nums = 0 + self.anys_dict = dict() + + +class TableMetric(object): + def __init__(self, + main_indicator='acc', + compute_bbox_metric=False, + box_format='xyxy', + del_thead_tbody=False, + **kwargs): + """ + + @param sub_metrics: configs of sub_metric + @param main_matric: main_matric for save best_model + @param kwargs: + """ + self.structure_metric = TableStructureMetric( + del_thead_tbody=del_thead_tbody) + self.bbox_metric = DetMetric() if compute_bbox_metric else None + self.main_indicator = main_indicator + self.box_format = box_format + self.reset() + + def __call__(self, pred_label, batch=None, *args, **kwargs): + self.structure_metric(pred_label) + if self.bbox_metric is not None: + self.bbox_metric(*self.prepare_bbox_metric_input(pred_label)) + + def prepare_bbox_metric_input(self, pred_label): + pred_bbox_batch_list = [] + gt_ignore_tags_batch_list = [] + gt_bbox_batch_list = [] + preds, labels = pred_label + + batch_num = len(preds['bbox_batch_list']) + for batch_idx in range(batch_num): + # pred + pred_bbox_list = [ + self.format_box(pred_box) + for pred_box in preds['bbox_batch_list'][batch_idx] + ] + pred_bbox_batch_list.append({'points': pred_bbox_list}) + + # gt + gt_bbox_list = [] + gt_ignore_tags_list = [] + for gt_box in labels['bbox_batch_list'][batch_idx]: + gt_bbox_list.append(self.format_box(gt_box)) + gt_ignore_tags_list.append(0) + gt_bbox_batch_list.append(gt_bbox_list) + gt_ignore_tags_batch_list.append(gt_ignore_tags_list) + + return [ + pred_bbox_batch_list, + [0, 0, gt_bbox_batch_list, gt_ignore_tags_batch_list] + ] + + def get_metric(self): + structure_metric = self.structure_metric.get_metric() + if self.bbox_metric is None: + return structure_metric + bbox_metric = self.bbox_metric.get_metric() + if self.main_indicator == self.bbox_metric.main_indicator: + output = bbox_metric + for sub_key in structure_metric: + output["structure_metric_{}".format( + sub_key)] = structure_metric[sub_key] + else: + output = structure_metric + for sub_key in bbox_metric: + output["bbox_metric_{}".format(sub_key)] = bbox_metric[sub_key] + return output + + def reset(self): + self.structure_metric.reset() + if self.bbox_metric is not None: + self.bbox_metric.reset() + + def format_box(self, box): + if self.box_format == 'xyxy': + x1, y1, x2, y2 = box + box = [[x1, y1], [x2, y1], [x2, y2], [x1, y2]] + elif self.box_format == 'xywh': + x, y, w, h = box + x1, y1, x2, y2 = x - w // 2, y - h // 2, x + w // 2, y + h // 2 + box = [[x1, y1], [x2, y1], [x2, y2], [x1, y2]] + elif self.box_format == 'xyxyxyxy': + x1, y1, x2, y2, x3, y3, x4, y4 = box + box = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]] + return box diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_re_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_re_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..f84387d8beb729bcc4b420ceea24a5e9b2993c64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_re_metric.py @@ -0,0 +1,179 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import paddle + +__all__ = ['KIEMetric'] + + +class VQAReTokenMetric(object): + def __init__(self, main_indicator='hmean', **kwargs): + self.main_indicator = main_indicator + self.reset() + + def __call__(self, preds, batch, **kwargs): + pred_relations, relations, entities = preds + self.pred_relations_list.extend(pred_relations) + self.relations_list.extend(relations) + self.entities_list.extend(entities) + + def get_metric(self): + gt_relations = [] + for b in range(len(self.relations_list)): + rel_sent = [] + if "head" in self.relations_list[b]: + for head, tail in zip(self.relations_list[b]["head"], + self.relations_list[b]["tail"]): + rel = {} + rel["head_id"] = head + rel["head"] = ( + self.entities_list[b]["start"][rel["head_id"]], + self.entities_list[b]["end"][rel["head_id"]]) + rel["head_type"] = self.entities_list[b]["label"][rel[ + "head_id"]] + + rel["tail_id"] = tail + rel["tail"] = ( + self.entities_list[b]["start"][rel["tail_id"]], + self.entities_list[b]["end"][rel["tail_id"]]) + rel["tail_type"] = self.entities_list[b]["label"][rel[ + "tail_id"]] + + rel["type"] = 1 + rel_sent.append(rel) + gt_relations.append(rel_sent) + re_metrics = self.re_score( + self.pred_relations_list, gt_relations, mode="boundaries") + metrics = { + "precision": re_metrics["ALL"]["p"], + "recall": re_metrics["ALL"]["r"], + "hmean": re_metrics["ALL"]["f1"], + } + self.reset() + return metrics + + def reset(self): + self.pred_relations_list = [] + self.relations_list = [] + self.entities_list = [] + + def re_score(self, pred_relations, gt_relations, mode="strict"): + """Evaluate RE predictions + + Args: + pred_relations (list) : list of list of predicted relations (several relations in each sentence) + gt_relations (list) : list of list of ground truth relations + + rel = { "head": (start_idx (inclusive), end_idx (exclusive)), + "tail": (start_idx (inclusive), end_idx (exclusive)), + "head_type": ent_type, + "tail_type": ent_type, + "type": rel_type} + + vocab (Vocab) : dataset vocabulary + mode (str) : in 'strict' or 'boundaries'""" + + assert mode in ["strict", "boundaries"] + + relation_types = [v for v in [0, 1] if not v == 0] + scores = { + rel: { + "tp": 0, + "fp": 0, + "fn": 0 + } + for rel in relation_types + ["ALL"] + } + + # Count GT relations and Predicted relations + n_sents = len(gt_relations) + n_rels = sum([len([rel for rel in sent]) for sent in gt_relations]) + n_found = sum([len([rel for rel in sent]) for sent in pred_relations]) + + # Count TP, FP and FN per type + for pred_sent, gt_sent in zip(pred_relations, gt_relations): + for rel_type in relation_types: + # strict mode takes argument types into account + if mode == "strict": + pred_rels = {(rel["head"], rel["head_type"], rel["tail"], + rel["tail_type"]) + for rel in pred_sent + if rel["type"] == rel_type} + gt_rels = {(rel["head"], rel["head_type"], rel["tail"], + rel["tail_type"]) + for rel in gt_sent if rel["type"] == rel_type} + + # boundaries mode only takes argument spans into account + elif mode == "boundaries": + pred_rels = {(rel["head"], rel["tail"]) + for rel in pred_sent + if rel["type"] == rel_type} + gt_rels = {(rel["head"], rel["tail"]) + for rel in gt_sent if rel["type"] == rel_type} + + scores[rel_type]["tp"] += len(pred_rels & gt_rels) + scores[rel_type]["fp"] += len(pred_rels - gt_rels) + scores[rel_type]["fn"] += len(gt_rels - pred_rels) + + # Compute per entity Precision / Recall / F1 + for rel_type in scores.keys(): + if scores[rel_type]["tp"]: + scores[rel_type]["p"] = scores[rel_type]["tp"] / ( + scores[rel_type]["fp"] + scores[rel_type]["tp"]) + scores[rel_type]["r"] = scores[rel_type]["tp"] / ( + scores[rel_type]["fn"] + scores[rel_type]["tp"]) + else: + scores[rel_type]["p"], scores[rel_type]["r"] = 0, 0 + + if not scores[rel_type]["p"] + scores[rel_type]["r"] == 0: + scores[rel_type]["f1"] = ( + 2 * scores[rel_type]["p"] * scores[rel_type]["r"] / + (scores[rel_type]["p"] + scores[rel_type]["r"])) + else: + scores[rel_type]["f1"] = 0 + + # Compute micro F1 Scores + tp = sum([scores[rel_type]["tp"] for rel_type in relation_types]) + fp = sum([scores[rel_type]["fp"] for rel_type in relation_types]) + fn = sum([scores[rel_type]["fn"] for rel_type in relation_types]) + + if tp: + precision = tp / (tp + fp) + recall = tp / (tp + fn) + f1 = 2 * precision * recall / (precision + recall) + + else: + precision, recall, f1 = 0, 0, 0 + + scores["ALL"]["p"] = precision + scores["ALL"]["r"] = recall + scores["ALL"]["f1"] = f1 + scores["ALL"]["tp"] = tp + scores["ALL"]["fp"] = fp + scores["ALL"]["fn"] = fn + + # Compute Macro F1 Scores + scores["ALL"]["Macro_f1"] = np.mean( + [scores[ent_type]["f1"] for ent_type in relation_types]) + scores["ALL"]["Macro_p"] = np.mean( + [scores[ent_type]["p"] for ent_type in relation_types]) + scores["ALL"]["Macro_r"] = np.mean( + [scores[ent_type]["r"] for ent_type in relation_types]) + + return scores diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_ser_metric.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_ser_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..286d8addaf32ba8e4fa12751c6e270c853775bd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/metrics/vqa_token_ser_metric.py @@ -0,0 +1,47 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import paddle + +__all__ = ['KIEMetric'] + + +class VQASerTokenMetric(object): + def __init__(self, main_indicator='hmean', **kwargs): + self.main_indicator = main_indicator + self.reset() + + def __call__(self, preds, batch, **kwargs): + preds, labels = preds + self.pred_list.extend(preds) + self.gt_list.extend(labels) + + def get_metric(self): + from seqeval.metrics import f1_score, precision_score, recall_score + metrics = { + "precision": precision_score(self.gt_list, self.pred_list), + "recall": recall_score(self.gt_list, self.pred_list), + "hmean": f1_score(self.gt_list, self.pred_list), + } + self.reset() + return metrics + + def reset(self): + self.pred_list = [] + self.gt_list = [] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..1c955ef3abe9c38e816616cc9b5399c6832aa5f1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/__init__.py @@ -0,0 +1,68 @@ +# 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. + +import copy +import importlib + +from paddle.jit import to_static +from paddle.static import InputSpec + +from .base_model import BaseModel +from .distillation_model import DistillationModel + +__all__ = ["build_model", "apply_to_static"] + + +def build_model(config): + config = copy.deepcopy(config) + if not "name" in config: + arch = BaseModel(config) + else: + name = config.pop("name") + mod = importlib.import_module(__name__) + arch = getattr(mod, name)(config) + return arch + + +def apply_to_static(model, config, logger): + if config["Global"].get("to_static", False) is not True: + return model + assert "image_shape" in config[ + "Global"], "image_shape must be assigned for static training mode..." + supported_list = ["DB", "SVTR"] + if config["Architecture"]["algorithm"] in ["Distillation"]: + algo = list(config["Architecture"]["Models"].values())[0]["algorithm"] + else: + algo = config["Architecture"]["algorithm"] + assert algo in supported_list, f"algorithms that supports static training must in in {supported_list} but got {algo}" + + specs = [ + InputSpec( + [None] + config["Global"]["image_shape"], dtype='float32') + ] + + if algo == "SVTR": + specs.append([ + InputSpec( + [None, config["Global"]["max_text_length"]], + dtype='int64'), InputSpec( + [None, config["Global"]["max_text_length"]], dtype='int64'), + InputSpec( + [None], dtype='int64'), InputSpec( + [None], dtype='float64') + ]) + + model = to_static(model, input_spec=specs) + logger.info("Successfully to apply @to_static with specs: {}".format(specs)) + return model diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/base_model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5612d366ea9ccf3f45ab675fbaa374fd4fe5d773 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/base_model.py @@ -0,0 +1,118 @@ +# Copyright (c) 2021 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. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +from ppocr.modeling.transforms import build_transform +from ppocr.modeling.backbones import build_backbone +from ppocr.modeling.necks import build_neck +from ppocr.modeling.heads import build_head + +__all__ = ['BaseModel'] + + +class BaseModel(nn.Layer): + def __init__(self, config): + """ + the module for OCR. + args: + config (dict): the super parameters for module. + """ + super(BaseModel, self).__init__() + in_channels = config.get('in_channels', 3) + model_type = config['model_type'] + # build transfrom, + # for rec, transfrom can be TPS,None + # for det and cls, transfrom shoule to be None, + # if you make model differently, you can use transfrom in det and cls + if 'Transform' not in config or config['Transform'] is None: + self.use_transform = False + else: + self.use_transform = True + config['Transform']['in_channels'] = in_channels + self.transform = build_transform(config['Transform']) + in_channels = self.transform.out_channels + + # build backbone, backbone is need for del, rec and cls + if 'Backbone' not in config or config['Backbone'] is None: + self.use_backbone = False + else: + self.use_backbone = True + config["Backbone"]['in_channels'] = in_channels + self.backbone = build_backbone(config["Backbone"], model_type) + in_channels = self.backbone.out_channels + + # build neck + # for rec, neck can be cnn,rnn or reshape(None) + # for det, neck can be FPN, BIFPN and so on. + # for cls, neck should be none + if 'Neck' not in config or config['Neck'] is None: + self.use_neck = False + else: + self.use_neck = True + config['Neck']['in_channels'] = in_channels + self.neck = build_neck(config['Neck']) + in_channels = self.neck.out_channels + + # # build head, head is need for det, rec and cls + if 'Head' not in config or config['Head'] is None: + self.use_head = False + else: + self.use_head = True + config["Head"]['in_channels'] = in_channels + self.head = build_head(config["Head"]) + + self.return_all_feats = config.get("return_all_feats", False) + + def forward(self, x, data=None): + + y = dict() + if self.use_transform: + x = self.transform(x) + if self.use_backbone: + x = self.backbone(x) + if isinstance(x, dict): + y.update(x) + else: + y["backbone_out"] = x + final_name = "backbone_out" + if self.use_neck: + x = self.neck(x) + if isinstance(x, dict): + y.update(x) + else: + y["neck_out"] = x + final_name = "neck_out" + if self.use_head: + x = self.head(x, targets=data) + # for multi head, save ctc neck out for udml + if isinstance(x, dict) and 'ctc_neck' in x.keys(): + y["neck_out"] = x["ctc_neck"] + y["head_out"] = x + elif isinstance(x, dict): + y.update(x) + else: + y["head_out"] = x + final_name = "head_out" + if self.return_all_feats: + if self.training: + return y + elif isinstance(x, dict): + return x + else: + return {final_name: x} + else: + return x \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/distillation_model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/distillation_model.py new file mode 100644 index 0000000000000000000000000000000000000000..cce8fd311d4e847afda0fbb035743f0a10564c7d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/architectures/distillation_model.py @@ -0,0 +1,60 @@ +# Copyright (c) 2021 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. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +from ppocr.modeling.transforms import build_transform +from ppocr.modeling.backbones import build_backbone +from ppocr.modeling.necks import build_neck +from ppocr.modeling.heads import build_head +from .base_model import BaseModel +from ppocr.utils.save_load import load_pretrained_params + +__all__ = ['DistillationModel'] + + +class DistillationModel(nn.Layer): + def __init__(self, config): + """ + the module for OCR distillation. + args: + config (dict): the super parameters for module. + """ + super().__init__() + self.model_list = [] + self.model_name_list = [] + for key in config["Models"]: + model_config = config["Models"][key] + freeze_params = False + pretrained = None + if "freeze_params" in model_config: + freeze_params = model_config.pop("freeze_params") + if "pretrained" in model_config: + pretrained = model_config.pop("pretrained") + model = BaseModel(model_config) + if pretrained is not None: + load_pretrained_params(model, pretrained) + if freeze_params: + for param in model.parameters(): + param.trainable = False + self.model_list.append(self.add_sublayer(key, model)) + self.model_name_list.append(key) + + def forward(self, x, data=None): + result_dict = dict() + for idx, model_name in enumerate(self.model_name_list): + result_dict[model_name] = self.model_list[idx](x, data) + return result_dict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..6fdcc4a759e59027b1457d1e46757c64c4dcad9e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/__init__.py @@ -0,0 +1,72 @@ +# 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. + +__all__ = ["build_backbone"] + + +def build_backbone(config, model_type): + if model_type == "det" or model_type == "table": + from .det_mobilenet_v3 import MobileNetV3 + from .det_resnet import ResNet + from .det_resnet_vd import ResNet_vd + from .det_resnet_vd_sast import ResNet_SAST + from .det_pp_lcnet import PPLCNet + support_dict = [ + "MobileNetV3", "ResNet", "ResNet_vd", "ResNet_SAST", "PPLCNet" + ] + if model_type == "table": + from .table_master_resnet import TableResNetExtra + support_dict.append('TableResNetExtra') + elif model_type == "rec" or model_type == "cls": + from .rec_mobilenet_v3 import MobileNetV3 + from .rec_resnet_vd import ResNet + from .rec_resnet_fpn import ResNetFPN + from .rec_mv1_enhance import MobileNetV1Enhance + from .rec_nrtr_mtb import MTB + from .rec_resnet_31 import ResNet31 + from .rec_resnet_32 import ResNet32 + from .rec_resnet_45 import ResNet45 + from .rec_resnet_aster import ResNet_ASTER + from .rec_micronet import MicroNet + from .rec_efficientb3_pren import EfficientNetb3_PREN + from .rec_svtrnet import SVTRNet + from .rec_vitstr import ViTSTR + support_dict = [ + 'MobileNetV1Enhance', 'MobileNetV3', 'ResNet', 'ResNetFPN', 'MTB', + 'ResNet31', 'ResNet45', 'ResNet_ASTER', 'MicroNet', + 'EfficientNetb3_PREN', 'SVTRNet', 'ViTSTR', 'ResNet32' + ] + elif model_type == 'e2e': + from .e2e_resnet_vd_pg import ResNet + support_dict = ['ResNet'] + elif model_type == 'kie': + from .kie_unet_sdmgr import Kie_backbone + from .vqa_layoutlm import LayoutLMForSer, LayoutLMv2ForSer, LayoutLMv2ForRe, LayoutXLMForSer, LayoutXLMForRe + support_dict = [ + 'Kie_backbone', 'LayoutLMForSer', 'LayoutLMv2ForSer', + 'LayoutLMv2ForRe', 'LayoutXLMForSer', 'LayoutXLMForRe' + ] + elif model_type == 'table': + from .table_resnet_vd import ResNet + from .table_mobilenet_v3 import MobileNetV3 + support_dict = ['ResNet', 'MobileNetV3'] + else: + raise NotImplementedError + + module_name = config.pop('name') + assert module_name in support_dict, Exception( + "when model typs is {}, backbone only support {}".format(model_type, + support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_mobilenet_v3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_mobilenet_v3.py new file mode 100755 index 0000000000000000000000000000000000000000..05113ea8419aa302c952adfd74e9083055c35dca --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_mobilenet_v3.py @@ -0,0 +1,268 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + +__all__ = ['MobileNetV3'] + + +def make_divisible(v, divisor=8, min_value=None): + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + if new_v < 0.9 * v: + new_v += divisor + return new_v + + +class MobileNetV3(nn.Layer): + def __init__(self, + in_channels=3, + model_name='large', + scale=0.5, + disable_se=False, + **kwargs): + """ + the MobilenetV3 backbone network for detection module. + Args: + params(dict): the super parameters for build network + """ + super(MobileNetV3, self).__init__() + + self.disable_se = disable_se + + if model_name == "large": + cfg = [ + # k, exp, c, se, nl, s, + [3, 16, 16, False, 'relu', 1], + [3, 64, 24, False, 'relu', 2], + [3, 72, 24, False, 'relu', 1], + [5, 72, 40, True, 'relu', 2], + [5, 120, 40, True, 'relu', 1], + [5, 120, 40, True, 'relu', 1], + [3, 240, 80, False, 'hardswish', 2], + [3, 200, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 480, 112, True, 'hardswish', 1], + [3, 672, 112, True, 'hardswish', 1], + [5, 672, 160, True, 'hardswish', 2], + [5, 960, 160, True, 'hardswish', 1], + [5, 960, 160, True, 'hardswish', 1], + ] + cls_ch_squeeze = 960 + elif model_name == "small": + cfg = [ + # k, exp, c, se, nl, s, + [3, 16, 16, True, 'relu', 2], + [3, 72, 24, False, 'relu', 2], + [3, 88, 24, False, 'relu', 1], + [5, 96, 40, True, 'hardswish', 2], + [5, 240, 40, True, 'hardswish', 1], + [5, 240, 40, True, 'hardswish', 1], + [5, 120, 48, True, 'hardswish', 1], + [5, 144, 48, True, 'hardswish', 1], + [5, 288, 96, True, 'hardswish', 2], + [5, 576, 96, True, 'hardswish', 1], + [5, 576, 96, True, 'hardswish', 1], + ] + cls_ch_squeeze = 576 + else: + raise NotImplementedError("mode[" + model_name + + "_model] is not implemented!") + + supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25] + assert scale in supported_scale, \ + "supported scale are {} but input scale is {}".format(supported_scale, scale) + inplanes = 16 + # conv1 + self.conv = ConvBNLayer( + in_channels=in_channels, + out_channels=make_divisible(inplanes * scale), + kernel_size=3, + stride=2, + padding=1, + groups=1, + if_act=True, + act='hardswish') + + self.stages = [] + self.out_channels = [] + block_list = [] + i = 0 + inplanes = make_divisible(inplanes * scale) + for (k, exp, c, se, nl, s) in cfg: + se = se and not self.disable_se + start_idx = 2 if model_name == 'large' else 0 + if s == 2 and i > start_idx: + self.out_channels.append(inplanes) + self.stages.append(nn.Sequential(*block_list)) + block_list = [] + block_list.append( + ResidualUnit( + in_channels=inplanes, + mid_channels=make_divisible(scale * exp), + out_channels=make_divisible(scale * c), + kernel_size=k, + stride=s, + use_se=se, + act=nl)) + inplanes = make_divisible(scale * c) + i += 1 + block_list.append( + ConvBNLayer( + in_channels=inplanes, + out_channels=make_divisible(scale * cls_ch_squeeze), + kernel_size=1, + stride=1, + padding=0, + groups=1, + if_act=True, + act='hardswish')) + self.stages.append(nn.Sequential(*block_list)) + self.out_channels.append(make_divisible(scale * cls_ch_squeeze)) + for i, stage in enumerate(self.stages): + self.add_sublayer(sublayer=stage, name="stage{}".format(i)) + + def forward(self, x): + x = self.conv(x) + out_list = [] + for stage in self.stages: + x = stage(x) + out_list.append(x) + return out_list + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups=1, + if_act=True, + act=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + bias_attr=False) + + self.bn = nn.BatchNorm(num_channels=out_channels, act=None) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + if self.if_act: + if self.act == "relu": + x = F.relu(x) + elif self.act == "hardswish": + x = F.hardswish(x) + else: + print("The activation function({}) is selected incorrectly.". + format(self.act)) + exit() + return x + + +class ResidualUnit(nn.Layer): + def __init__(self, + in_channels, + mid_channels, + out_channels, + kernel_size, + stride, + use_se, + act=None): + super(ResidualUnit, self).__init__() + self.if_shortcut = stride == 1 and in_channels == out_channels + self.if_se = use_se + + self.expand_conv = ConvBNLayer( + in_channels=in_channels, + out_channels=mid_channels, + kernel_size=1, + stride=1, + padding=0, + if_act=True, + act=act) + self.bottleneck_conv = ConvBNLayer( + in_channels=mid_channels, + out_channels=mid_channels, + kernel_size=kernel_size, + stride=stride, + padding=int((kernel_size - 1) // 2), + groups=mid_channels, + if_act=True, + act=act) + if self.if_se: + self.mid_se = SEModule(mid_channels) + self.linear_conv = ConvBNLayer( + in_channels=mid_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + if_act=False, + act=None) + + def forward(self, inputs): + x = self.expand_conv(inputs) + x = self.bottleneck_conv(x) + if self.if_se: + x = self.mid_se(x) + x = self.linear_conv(x) + if self.if_shortcut: + x = paddle.add(inputs, x) + return x + + +class SEModule(nn.Layer): + def __init__(self, in_channels, reduction=4): + super(SEModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2D(1) + self.conv1 = nn.Conv2D( + in_channels=in_channels, + out_channels=in_channels // reduction, + kernel_size=1, + stride=1, + padding=0) + self.conv2 = nn.Conv2D( + in_channels=in_channels // reduction, + out_channels=in_channels, + kernel_size=1, + stride=1, + padding=0) + + def forward(self, inputs): + outputs = self.avg_pool(inputs) + outputs = self.conv1(outputs) + outputs = F.relu(outputs) + outputs = self.conv2(outputs) + outputs = F.hardsigmoid(outputs, slope=0.2, offset=0.5) + return inputs * outputs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_pp_lcnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_pp_lcnet.py new file mode 100644 index 0000000000000000000000000000000000000000..3f719e92bc67452b482e5b2053ee1a09540ffc0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_pp_lcnet.py @@ -0,0 +1,271 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import, division, print_function + +import os +import paddle +import paddle.nn as nn +from paddle import ParamAttr +from paddle.nn import AdaptiveAvgPool2D, BatchNorm, Conv2D, Dropout, Linear +from paddle.regularizer import L2Decay +from paddle.nn.initializer import KaimingNormal +from paddle.utils.download import get_path_from_url + +MODEL_URLS = { + "PPLCNet_x0.25": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_25_pretrained.pdparams", + "PPLCNet_x0.35": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_35_pretrained.pdparams", + "PPLCNet_x0.5": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_5_pretrained.pdparams", + "PPLCNet_x0.75": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_75_pretrained.pdparams", + "PPLCNet_x1.0": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x1_0_pretrained.pdparams", + "PPLCNet_x1.5": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x1_5_pretrained.pdparams", + "PPLCNet_x2.0": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x2_0_pretrained.pdparams", + "PPLCNet_x2.5": + "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x2_5_pretrained.pdparams" +} + +MODEL_STAGES_PATTERN = { + "PPLCNet": ["blocks2", "blocks3", "blocks4", "blocks5", "blocks6"] +} + +__all__ = list(MODEL_URLS.keys()) + +# Each element(list) represents a depthwise block, which is composed of k, in_c, out_c, s, use_se. +# k: kernel_size +# in_c: input channel number in depthwise block +# out_c: output channel number in depthwise block +# s: stride in depthwise block +# use_se: whether to use SE block + +NET_CONFIG = { + "blocks2": + # k, in_c, out_c, s, use_se + [[3, 16, 32, 1, False]], + "blocks3": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]], + "blocks4": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]], + "blocks5": + [[3, 128, 256, 2, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False], + [5, 256, 256, 1, False], [5, 256, 256, 1, False], [5, 256, 256, 1, False]], + "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True]] +} + + +def make_divisible(v, divisor=8, min_value=None): + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + if new_v < 0.9 * v: + new_v += divisor + return new_v + + +class ConvBNLayer(nn.Layer): + def __init__(self, + num_channels, + filter_size, + num_filters, + stride, + num_groups=1): + super().__init__() + + self.conv = Conv2D( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=(filter_size - 1) // 2, + groups=num_groups, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False) + + self.bn = BatchNorm( + num_filters, + param_attr=ParamAttr(regularizer=L2Decay(0.0)), + bias_attr=ParamAttr(regularizer=L2Decay(0.0))) + self.hardswish = nn.Hardswish() + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.hardswish(x) + return x + + +class DepthwiseSeparable(nn.Layer): + def __init__(self, + num_channels, + num_filters, + stride, + dw_size=3, + use_se=False): + super().__init__() + self.use_se = use_se + self.dw_conv = ConvBNLayer( + num_channels=num_channels, + num_filters=num_channels, + filter_size=dw_size, + stride=stride, + num_groups=num_channels) + if use_se: + self.se = SEModule(num_channels) + self.pw_conv = ConvBNLayer( + num_channels=num_channels, + filter_size=1, + num_filters=num_filters, + stride=1) + + def forward(self, x): + x = self.dw_conv(x) + if self.use_se: + x = self.se(x) + x = self.pw_conv(x) + return x + + +class SEModule(nn.Layer): + def __init__(self, channel, reduction=4): + super().__init__() + self.avg_pool = AdaptiveAvgPool2D(1) + self.conv1 = Conv2D( + in_channels=channel, + out_channels=channel // reduction, + kernel_size=1, + stride=1, + padding=0) + self.relu = nn.ReLU() + self.conv2 = Conv2D( + in_channels=channel // reduction, + out_channels=channel, + kernel_size=1, + stride=1, + padding=0) + self.hardsigmoid = nn.Hardsigmoid() + + def forward(self, x): + identity = x + x = self.avg_pool(x) + x = self.conv1(x) + x = self.relu(x) + x = self.conv2(x) + x = self.hardsigmoid(x) + x = paddle.multiply(x=identity, y=x) + return x + + +class PPLCNet(nn.Layer): + def __init__(self, + in_channels=3, + scale=1.0, + pretrained=False, + use_ssld=False): + super().__init__() + self.out_channels = [ + int(NET_CONFIG["blocks3"][-1][2] * scale), + int(NET_CONFIG["blocks4"][-1][2] * scale), + int(NET_CONFIG["blocks5"][-1][2] * scale), + int(NET_CONFIG["blocks6"][-1][2] * scale) + ] + self.scale = scale + + self.conv1 = ConvBNLayer( + num_channels=in_channels, + filter_size=3, + num_filters=make_divisible(16 * scale), + stride=2) + + self.blocks2 = nn.Sequential(* [ + DepthwiseSeparable( + num_channels=make_divisible(in_c * scale), + num_filters=make_divisible(out_c * scale), + dw_size=k, + stride=s, + use_se=se) + for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks2"]) + ]) + + self.blocks3 = nn.Sequential(* [ + DepthwiseSeparable( + num_channels=make_divisible(in_c * scale), + num_filters=make_divisible(out_c * scale), + dw_size=k, + stride=s, + use_se=se) + for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks3"]) + ]) + + self.blocks4 = nn.Sequential(* [ + DepthwiseSeparable( + num_channels=make_divisible(in_c * scale), + num_filters=make_divisible(out_c * scale), + dw_size=k, + stride=s, + use_se=se) + for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks4"]) + ]) + + self.blocks5 = nn.Sequential(* [ + DepthwiseSeparable( + num_channels=make_divisible(in_c * scale), + num_filters=make_divisible(out_c * scale), + dw_size=k, + stride=s, + use_se=se) + for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks5"]) + ]) + + self.blocks6 = nn.Sequential(* [ + DepthwiseSeparable( + num_channels=make_divisible(in_c * scale), + num_filters=make_divisible(out_c * scale), + dw_size=k, + stride=s, + use_se=se) + for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks6"]) + ]) + + if pretrained: + self._load_pretrained( + MODEL_URLS['PPLCNet_x{}'.format(scale)], use_ssld=use_ssld) + + def forward(self, x): + outs = [] + x = self.conv1(x) + x = self.blocks2(x) + x = self.blocks3(x) + outs.append(x) + x = self.blocks4(x) + outs.append(x) + x = self.blocks5(x) + outs.append(x) + x = self.blocks6(x) + outs.append(x) + return outs + + def _load_pretrained(self, pretrained_url, use_ssld=False): + if use_ssld: + pretrained_url = pretrained_url.replace("_pretrained", + "_ssld_pretrained") + print(pretrained_url) + local_weight_path = get_path_from_url( + pretrained_url, os.path.expanduser("~/.paddleclas/weights")) + param_state_dict = paddle.load(local_weight_path) + self.set_dict(param_state_dict) + return diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..87eef11cf0e33c24c0f539c8074b21f589345282 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet.py @@ -0,0 +1,236 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F +from paddle.nn import Conv2D, BatchNorm, Linear, Dropout +from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D +from paddle.nn.initializer import Uniform + +import math + +from paddle.vision.ops import DeformConv2D +from paddle.regularizer import L2Decay +from paddle.nn.initializer import Normal, Constant, XavierUniform +from .det_resnet_vd import DeformableConvV2, ConvBNLayer + + +class BottleneckBlock(nn.Layer): + def __init__(self, + num_channels, + num_filters, + stride, + shortcut=True, + is_dcn=False): + super(BottleneckBlock, self).__init__() + + self.conv0 = ConvBNLayer( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=1, + act="relu", ) + self.conv1 = ConvBNLayer( + in_channels=num_filters, + out_channels=num_filters, + kernel_size=3, + stride=stride, + act="relu", + is_dcn=is_dcn, + dcn_groups=1, ) + self.conv2 = ConvBNLayer( + in_channels=num_filters, + out_channels=num_filters * 4, + kernel_size=1, + act=None, ) + + if not shortcut: + self.short = ConvBNLayer( + in_channels=num_channels, + out_channels=num_filters * 4, + kernel_size=1, + stride=stride, ) + + self.shortcut = shortcut + + self._num_channels_out = num_filters * 4 + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + conv2 = self.conv2(conv1) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + + y = paddle.add(x=short, y=conv2) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__(self, + num_channels, + num_filters, + stride, + shortcut=True, + name=None): + super(BasicBlock, self).__init__() + self.stride = stride + self.conv0 = ConvBNLayer( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=3, + stride=stride, + act="relu") + self.conv1 = ConvBNLayer( + in_channels=num_filters, + out_channels=num_filters, + kernel_size=3, + act=None) + + if not shortcut: + self.short = ConvBNLayer( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=1, + stride=stride) + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv1) + y = F.relu(y) + return y + + +class ResNet(nn.Layer): + def __init__(self, + in_channels=3, + layers=50, + out_indices=None, + dcn_stage=None): + super(ResNet, self).__init__() + + self.layers = layers + self.input_image_channel = in_channels + + supported_layers = [18, 34, 50, 101, 152] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + + if layers == 18: + depth = [2, 2, 2, 2] + elif layers == 34 or layers == 50: + depth = [3, 4, 6, 3] + elif layers == 101: + depth = [3, 4, 23, 3] + elif layers == 152: + depth = [3, 8, 36, 3] + num_channels = [64, 256, 512, + 1024] if layers >= 50 else [64, 64, 128, 256] + num_filters = [64, 128, 256, 512] + + self.dcn_stage = dcn_stage if dcn_stage is not None else [ + False, False, False, False + ] + self.out_indices = out_indices if out_indices is not None else [ + 0, 1, 2, 3 + ] + + self.conv = ConvBNLayer( + in_channels=self.input_image_channel, + out_channels=64, + kernel_size=7, + stride=2, + act="relu", ) + self.pool2d_max = MaxPool2D( + kernel_size=3, + stride=2, + padding=1, ) + + self.stages = [] + self.out_channels = [] + if layers >= 50: + for block in range(len(depth)): + shortcut = False + block_list = [] + is_dcn = self.dcn_stage[block] + for i in range(depth[block]): + if layers in [101, 152] and block == 2: + if i == 0: + conv_name = "res" + str(block + 2) + "a" + else: + conv_name = "res" + str(block + 2) + "b" + str(i) + else: + conv_name = "res" + str(block + 2) + chr(97 + i) + bottleneck_block = self.add_sublayer( + conv_name, + BottleneckBlock( + num_channels=num_channels[block] + if i == 0 else num_filters[block] * 4, + num_filters=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + is_dcn=is_dcn)) + block_list.append(bottleneck_block) + shortcut = True + if block in self.out_indices: + self.out_channels.append(num_filters[block] * 4) + self.stages.append(nn.Sequential(*block_list)) + else: + for block in range(len(depth)): + shortcut = False + block_list = [] + for i in range(depth[block]): + conv_name = "res" + str(block + 2) + chr(97 + i) + basic_block = self.add_sublayer( + conv_name, + BasicBlock( + num_channels=num_channels[block] + if i == 0 else num_filters[block], + num_filters=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut)) + block_list.append(basic_block) + shortcut = True + if block in self.out_indices: + self.out_channels.append(num_filters[block]) + self.stages.append(nn.Sequential(*block_list)) + + def forward(self, inputs): + y = self.conv(inputs) + y = self.pool2d_max(y) + out = [] + for i, block in enumerate(self.stages): + y = block(y) + if i in self.out_indices: + out.append(y) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd.py new file mode 100644 index 0000000000000000000000000000000000000000..a421da0ab440e9b87c1c7efc7d2448f8f76ad205 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd.py @@ -0,0 +1,352 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +from paddle.vision.ops import DeformConv2D +from paddle.regularizer import L2Decay +from paddle.nn.initializer import Normal, Constant, XavierUniform + +__all__ = ["ResNet_vd", "ConvBNLayer", "DeformableConvV2"] + + +class DeformableConvV2(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride=1, + padding=0, + dilation=1, + groups=1, + weight_attr=None, + bias_attr=None, + lr_scale=1, + regularizer=None, + skip_quant=False, + dcn_bias_regularizer=L2Decay(0.), + dcn_bias_lr_scale=2.): + super(DeformableConvV2, self).__init__() + self.offset_channel = 2 * kernel_size**2 * groups + self.mask_channel = kernel_size**2 * groups + + if bias_attr: + # in FCOS-DCN head, specifically need learning_rate and regularizer + dcn_bias_attr = ParamAttr( + initializer=Constant(value=0), + regularizer=dcn_bias_regularizer, + learning_rate=dcn_bias_lr_scale) + else: + # in ResNet backbone, do not need bias + dcn_bias_attr = False + self.conv_dcn = DeformConv2D( + in_channels, + out_channels, + kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2 * dilation, + dilation=dilation, + deformable_groups=groups, + weight_attr=weight_attr, + bias_attr=dcn_bias_attr) + + if lr_scale == 1 and regularizer is None: + offset_bias_attr = ParamAttr(initializer=Constant(0.)) + else: + offset_bias_attr = ParamAttr( + initializer=Constant(0.), + learning_rate=lr_scale, + regularizer=regularizer) + self.conv_offset = nn.Conv2D( + in_channels, + groups * 3 * kernel_size**2, + kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + weight_attr=ParamAttr(initializer=Constant(0.0)), + bias_attr=offset_bias_attr) + if skip_quant: + self.conv_offset.skip_quant = True + + def forward(self, x): + offset_mask = self.conv_offset(x) + offset, mask = paddle.split( + offset_mask, + num_or_sections=[self.offset_channel, self.mask_channel], + axis=1) + mask = F.sigmoid(mask) + y = self.conv_dcn(x, offset, mask=mask) + return y + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + dcn_groups=1, + is_vd_mode=False, + act=None, + is_dcn=False): + super(ConvBNLayer, self).__init__() + + self.is_vd_mode = is_vd_mode + self._pool2d_avg = nn.AvgPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + if not is_dcn: + self._conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + bias_attr=False) + else: + self._conv = DeformableConvV2( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=dcn_groups, #groups, + bias_attr=False) + self._batch_norm = nn.BatchNorm(out_channels, act=act) + + def forward(self, inputs): + if self.is_vd_mode: + inputs = self._pool2d_avg(inputs) + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class BottleneckBlock(nn.Layer): + def __init__( + self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + is_dcn=False, ): + super(BottleneckBlock, self).__init__() + + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + act='relu') + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + is_dcn=is_dcn, + dcn_groups=2) + self.conv2 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels * 4, + kernel_size=1, + act=None) + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels * 4, + kernel_size=1, + stride=1, + is_vd_mode=False if if_first else True) + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + conv2 = self.conv2(conv1) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv2) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__( + self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, ): + super(BasicBlock, self).__init__() + self.stride = stride + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu') + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + act=None) + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + is_vd_mode=False if if_first else True) + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv1) + y = F.relu(y) + return y + + +class ResNet_vd(nn.Layer): + def __init__(self, + in_channels=3, + layers=50, + dcn_stage=None, + out_indices=None, + **kwargs): + super(ResNet_vd, self).__init__() + + self.layers = layers + supported_layers = [18, 34, 50, 101, 152, 200] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + + if layers == 18: + depth = [2, 2, 2, 2] + elif layers == 34 or layers == 50: + depth = [3, 4, 6, 3] + elif layers == 101: + depth = [3, 4, 23, 3] + elif layers == 152: + depth = [3, 8, 36, 3] + elif layers == 200: + depth = [3, 12, 48, 3] + num_channels = [64, 256, 512, + 1024] if layers >= 50 else [64, 64, 128, 256] + num_filters = [64, 128, 256, 512] + + self.dcn_stage = dcn_stage if dcn_stage is not None else [ + False, False, False, False + ] + self.out_indices = out_indices if out_indices is not None else [ + 0, 1, 2, 3 + ] + + self.conv1_1 = ConvBNLayer( + in_channels=in_channels, + out_channels=32, + kernel_size=3, + stride=2, + act='relu') + self.conv1_2 = ConvBNLayer( + in_channels=32, + out_channels=32, + kernel_size=3, + stride=1, + act='relu') + self.conv1_3 = ConvBNLayer( + in_channels=32, + out_channels=64, + kernel_size=3, + stride=1, + act='relu') + self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + + self.stages = [] + self.out_channels = [] + if layers >= 50: + for block in range(len(depth)): + block_list = [] + shortcut = False + is_dcn = self.dcn_stage[block] + for i in range(depth[block]): + bottleneck_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BottleneckBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block] * 4, + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0, + is_dcn=is_dcn)) + shortcut = True + block_list.append(bottleneck_block) + if block in self.out_indices: + self.out_channels.append(num_filters[block] * 4) + self.stages.append(nn.Sequential(*block_list)) + else: + for block in range(len(depth)): + block_list = [] + shortcut = False + for i in range(depth[block]): + basic_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BasicBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block], + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0)) + shortcut = True + block_list.append(basic_block) + if block in self.out_indices: + self.out_channels.append(num_filters[block]) + self.stages.append(nn.Sequential(*block_list)) + + def forward(self, inputs): + y = self.conv1_1(inputs) + y = self.conv1_2(y) + y = self.conv1_3(y) + y = self.pool2d_max(y) + out = [] + for i, block in enumerate(self.stages): + y = block(y) + if i in self.out_indices: + out.append(y) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd_sast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd_sast.py new file mode 100644 index 0000000000000000000000000000000000000000..c9376a8d56e9fa8eff5d2980f63b0b8b955efe88 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/det_resnet_vd_sast.py @@ -0,0 +1,285 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +__all__ = ["ResNet_SAST"] + + +class ConvBNLayer(nn.Layer): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + is_vd_mode=False, + act=None, + name=None, ): + super(ConvBNLayer, self).__init__() + + self.is_vd_mode = is_vd_mode + self._pool2d_avg = nn.AvgPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self._conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + "_weights"), + bias_attr=False) + if name == "conv1": + bn_name = "bn_" + name + else: + bn_name = "bn" + name[3:] + self._batch_norm = nn.BatchNorm( + out_channels, + act=act, + param_attr=ParamAttr(name=bn_name + '_scale'), + bias_attr=ParamAttr(bn_name + '_offset'), + moving_mean_name=bn_name + '_mean', + moving_variance_name=bn_name + '_variance') + + def forward(self, inputs): + if self.is_vd_mode: + inputs = self._pool2d_avg(inputs) + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class BottleneckBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BottleneckBlock, self).__init__() + + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2b") + self.conv2 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels * 4, + kernel_size=1, + act=None, + name=name + "_branch2c") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels * 4, + kernel_size=1, + stride=1, + is_vd_mode=False if if_first else True, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + conv2 = self.conv2(conv1) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv2) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BasicBlock, self).__init__() + self.stride = stride + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + act=None, + name=name + "_branch2b") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + is_vd_mode=False if if_first else True, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv1) + y = F.relu(y) + return y + + +class ResNet_SAST(nn.Layer): + def __init__(self, in_channels=3, layers=50, **kwargs): + super(ResNet_SAST, self).__init__() + + self.layers = layers + supported_layers = [18, 34, 50, 101, 152, 200] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + + if layers == 18: + depth = [2, 2, 2, 2] + elif layers == 34 or layers == 50: + # depth = [3, 4, 6, 3] + depth = [3, 4, 6, 3, 3] + elif layers == 101: + depth = [3, 4, 23, 3] + elif layers == 152: + depth = [3, 8, 36, 3] + elif layers == 200: + depth = [3, 12, 48, 3] + # num_channels = [64, 256, 512, + # 1024] if layers >= 50 else [64, 64, 128, 256] + # num_filters = [64, 128, 256, 512] + num_channels = [64, 256, 512, + 1024, 2048] if layers >= 50 else [64, 64, 128, 256] + num_filters = [64, 128, 256, 512, 512] + + self.conv1_1 = ConvBNLayer( + in_channels=in_channels, + out_channels=32, + kernel_size=3, + stride=2, + act='relu', + name="conv1_1") + self.conv1_2 = ConvBNLayer( + in_channels=32, + out_channels=32, + kernel_size=3, + stride=1, + act='relu', + name="conv1_2") + self.conv1_3 = ConvBNLayer( + in_channels=32, + out_channels=64, + kernel_size=3, + stride=1, + act='relu', + name="conv1_3") + self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + + self.stages = [] + self.out_channels = [3, 64] + if layers >= 50: + for block in range(len(depth)): + block_list = [] + shortcut = False + for i in range(depth[block]): + if layers in [101, 152] and block == 2: + if i == 0: + conv_name = "res" + str(block + 2) + "a" + else: + conv_name = "res" + str(block + 2) + "b" + str(i) + else: + conv_name = "res" + str(block + 2) + chr(97 + i) + bottleneck_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BottleneckBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block] * 4, + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + block_list.append(bottleneck_block) + self.out_channels.append(num_filters[block] * 4) + self.stages.append(nn.Sequential(*block_list)) + else: + for block in range(len(depth)): + block_list = [] + shortcut = False + for i in range(depth[block]): + conv_name = "res" + str(block + 2) + chr(97 + i) + basic_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BasicBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block], + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + block_list.append(basic_block) + self.out_channels.append(num_filters[block]) + self.stages.append(nn.Sequential(*block_list)) + + def forward(self, inputs): + out = [inputs] + y = self.conv1_1(inputs) + y = self.conv1_2(y) + y = self.conv1_3(y) + out.append(y) + y = self.pool2d_max(y) + for block in self.stages: + y = block(y) + out.append(y) + return out \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/e2e_resnet_vd_pg.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/e2e_resnet_vd_pg.py new file mode 100644 index 0000000000000000000000000000000000000000..97afd3460d03dc078b53064fb45b6fb6d3542df9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/e2e_resnet_vd_pg.py @@ -0,0 +1,265 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +__all__ = ["ResNet"] + + +class ConvBNLayer(nn.Layer): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + is_vd_mode=False, + act=None, + name=None, ): + super(ConvBNLayer, self).__init__() + + self.is_vd_mode = is_vd_mode + self._pool2d_avg = nn.AvgPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self._conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + "_weights"), + bias_attr=False) + if name == "conv1": + bn_name = "bn_" + name + else: + bn_name = "bn" + name[3:] + self._batch_norm = nn.BatchNorm( + out_channels, + act=act, + param_attr=ParamAttr(name=bn_name + '_scale'), + bias_attr=ParamAttr(bn_name + '_offset'), + moving_mean_name=bn_name + '_mean', + moving_variance_name=bn_name + '_variance') + + def forward(self, inputs): + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class BottleneckBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BottleneckBlock, self).__init__() + + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2b") + self.conv2 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels * 4, + kernel_size=1, + act=None, + name=name + "_branch2c") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels * 4, + kernel_size=1, + stride=stride, + is_vd_mode=False if if_first else True, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + conv2 = self.conv2(conv1) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv2) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BasicBlock, self).__init__() + self.stride = stride + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + act=None, + name=name + "_branch2b") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + is_vd_mode=False if if_first else True, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv1) + y = F.relu(y) + return y + + +class ResNet(nn.Layer): + def __init__(self, in_channels=3, layers=50, **kwargs): + super(ResNet, self).__init__() + + self.layers = layers + supported_layers = [18, 34, 50, 101, 152, 200] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + + if layers == 18: + depth = [2, 2, 2, 2] + elif layers == 34 or layers == 50: + # depth = [3, 4, 6, 3] + depth = [3, 4, 6, 3, 3] + elif layers == 101: + depth = [3, 4, 23, 3] + elif layers == 152: + depth = [3, 8, 36, 3] + elif layers == 200: + depth = [3, 12, 48, 3] + num_channels = [64, 256, 512, 1024, + 2048] if layers >= 50 else [64, 64, 128, 256] + num_filters = [64, 128, 256, 512, 512] + + self.conv1_1 = ConvBNLayer( + in_channels=in_channels, + out_channels=64, + kernel_size=7, + stride=2, + act='relu', + name="conv1_1") + self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + + self.stages = [] + self.out_channels = [3, 64] + # num_filters = [64, 128, 256, 512, 512] + if layers >= 50: + for block in range(len(depth)): + block_list = [] + shortcut = False + for i in range(depth[block]): + if layers in [101, 152] and block == 2: + if i == 0: + conv_name = "res" + str(block + 2) + "a" + else: + conv_name = "res" + str(block + 2) + "b" + str(i) + else: + conv_name = "res" + str(block + 2) + chr(97 + i) + bottleneck_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BottleneckBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block] * 4, + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + block_list.append(bottleneck_block) + self.out_channels.append(num_filters[block] * 4) + self.stages.append(nn.Sequential(*block_list)) + else: + for block in range(len(depth)): + block_list = [] + shortcut = False + for i in range(depth[block]): + conv_name = "res" + str(block + 2) + chr(97 + i) + basic_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BasicBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block], + out_channels=num_filters[block], + stride=2 if i == 0 and block != 0 else 1, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + block_list.append(basic_block) + self.out_channels.append(num_filters[block]) + self.stages.append(nn.Sequential(*block_list)) + + def forward(self, inputs): + out = [inputs] + y = self.conv1_1(inputs) + out.append(y) + y = self.pool2d_max(y) + for block in self.stages: + y = block(y) + out.append(y) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/kie_unet_sdmgr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/kie_unet_sdmgr.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1bd8030060b26acb9e60bd671a5b23d936347b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/kie_unet_sdmgr.py @@ -0,0 +1,181 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import numpy as np +import cv2 + +__all__ = ["Kie_backbone"] + + +class Encoder(nn.Layer): + def __init__(self, num_channels, num_filters): + super(Encoder, self).__init__() + self.conv1 = nn.Conv2D( + num_channels, + num_filters, + kernel_size=3, + stride=1, + padding=1, + bias_attr=False) + self.bn1 = nn.BatchNorm(num_filters, act='relu') + + self.conv2 = nn.Conv2D( + num_filters, + num_filters, + kernel_size=3, + stride=1, + padding=1, + bias_attr=False) + self.bn2 = nn.BatchNorm(num_filters, act='relu') + + self.pool = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + + def forward(self, inputs): + x = self.conv1(inputs) + x = self.bn1(x) + x = self.conv2(x) + x = self.bn2(x) + x_pooled = self.pool(x) + return x, x_pooled + + +class Decoder(nn.Layer): + def __init__(self, num_channels, num_filters): + super(Decoder, self).__init__() + + self.conv1 = nn.Conv2D( + num_channels, + num_filters, + kernel_size=3, + stride=1, + padding=1, + bias_attr=False) + self.bn1 = nn.BatchNorm(num_filters, act='relu') + + self.conv2 = nn.Conv2D( + num_filters, + num_filters, + kernel_size=3, + stride=1, + padding=1, + bias_attr=False) + self.bn2 = nn.BatchNorm(num_filters, act='relu') + + self.conv0 = nn.Conv2D( + num_channels, + num_filters, + kernel_size=1, + stride=1, + padding=0, + bias_attr=False) + self.bn0 = nn.BatchNorm(num_filters, act='relu') + + def forward(self, inputs_prev, inputs): + x = self.conv0(inputs) + x = self.bn0(x) + x = paddle.nn.functional.interpolate( + x, scale_factor=2, mode='bilinear', align_corners=False) + x = paddle.concat([inputs_prev, x], axis=1) + x = self.conv1(x) + x = self.bn1(x) + x = self.conv2(x) + x = self.bn2(x) + return x + + +class UNet(nn.Layer): + def __init__(self): + super(UNet, self).__init__() + self.down1 = Encoder(num_channels=3, num_filters=16) + self.down2 = Encoder(num_channels=16, num_filters=32) + self.down3 = Encoder(num_channels=32, num_filters=64) + self.down4 = Encoder(num_channels=64, num_filters=128) + self.down5 = Encoder(num_channels=128, num_filters=256) + + self.up1 = Decoder(32, 16) + self.up2 = Decoder(64, 32) + self.up3 = Decoder(128, 64) + self.up4 = Decoder(256, 128) + self.out_channels = 16 + + def forward(self, inputs): + x1, _ = self.down1(inputs) + _, x2 = self.down2(x1) + _, x3 = self.down3(x2) + _, x4 = self.down4(x3) + _, x5 = self.down5(x4) + + x = self.up4(x4, x5) + x = self.up3(x3, x) + x = self.up2(x2, x) + x = self.up1(x1, x) + return x + + +class Kie_backbone(nn.Layer): + def __init__(self, in_channels, **kwargs): + super(Kie_backbone, self).__init__() + self.out_channels = 16 + self.img_feat = UNet() + self.maxpool = nn.MaxPool2D(kernel_size=7) + + def bbox2roi(self, bbox_list): + rois_list = [] + rois_num = [] + for img_id, bboxes in enumerate(bbox_list): + rois_num.append(bboxes.shape[0]) + rois_list.append(bboxes) + rois = paddle.concat(rois_list, 0) + rois_num = paddle.to_tensor(rois_num, dtype='int32') + return rois, rois_num + + def pre_process(self, img, relations, texts, gt_bboxes, tag, img_size): + img, relations, texts, gt_bboxes, tag, img_size = img.numpy( + ), relations.numpy(), texts.numpy(), gt_bboxes.numpy(), tag.numpy( + ).tolist(), img_size.numpy() + temp_relations, temp_texts, temp_gt_bboxes = [], [], [] + h, w = int(np.max(img_size[:, 0])), int(np.max(img_size[:, 1])) + img = paddle.to_tensor(img[:, :, :h, :w]) + batch = len(tag) + for i in range(batch): + num, recoder_len = tag[i][0], tag[i][1] + temp_relations.append( + paddle.to_tensor( + relations[i, :num, :num, :], dtype='float32')) + temp_texts.append( + paddle.to_tensor( + texts[i, :num, :recoder_len], dtype='float32')) + temp_gt_bboxes.append( + paddle.to_tensor( + gt_bboxes[i, :num, ...], dtype='float32')) + return img, temp_relations, temp_texts, temp_gt_bboxes + + def forward(self, inputs): + img = inputs[0] + relations, texts, gt_bboxes, tag, img_size = inputs[1], inputs[ + 2], inputs[3], inputs[5], inputs[-1] + img, relations, texts, gt_bboxes = self.pre_process( + img, relations, texts, gt_bboxes, tag, img_size) + x = self.img_feat(img) + boxes, rois_num = self.bbox2roi(gt_bboxes) + feats = paddle.vision.ops.roi_align( + x, boxes, spatial_scale=1.0, output_size=7, boxes_num=rois_num) + feats = self.maxpool(feats).squeeze(-1).squeeze(-1) + return [relations, texts, feats] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_efficientb3_pren.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_efficientb3_pren.py new file mode 100644 index 0000000000000000000000000000000000000000..57eef178869fc7f5ff55b3548674c741fb4f3ead --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_efficientb3_pren.py @@ -0,0 +1,228 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +Code is refer from: +https://github.com/RuijieJ/pren/blob/main/Nets/EfficientNet.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +from collections import namedtuple +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + +__all__ = ['EfficientNetb3'] + + +class EffB3Params: + @staticmethod + def get_global_params(): + """ + The fllowing are efficientnetb3's arch superparams, but to fit for scene + text recognition task, the resolution(image_size) here is changed + from 300 to 64. + """ + GlobalParams = namedtuple('GlobalParams', [ + 'drop_connect_rate', 'width_coefficient', 'depth_coefficient', + 'depth_divisor', 'image_size' + ]) + global_params = GlobalParams( + drop_connect_rate=0.3, + width_coefficient=1.2, + depth_coefficient=1.4, + depth_divisor=8, + image_size=64) + return global_params + + @staticmethod + def get_block_params(): + BlockParams = namedtuple('BlockParams', [ + 'kernel_size', 'num_repeat', 'input_filters', 'output_filters', + 'expand_ratio', 'id_skip', 'se_ratio', 'stride' + ]) + block_params = [ + BlockParams(3, 1, 32, 16, 1, True, 0.25, 1), + BlockParams(3, 2, 16, 24, 6, True, 0.25, 2), + BlockParams(5, 2, 24, 40, 6, True, 0.25, 2), + BlockParams(3, 3, 40, 80, 6, True, 0.25, 2), + BlockParams(5, 3, 80, 112, 6, True, 0.25, 1), + BlockParams(5, 4, 112, 192, 6, True, 0.25, 2), + BlockParams(3, 1, 192, 320, 6, True, 0.25, 1) + ] + return block_params + + +class EffUtils: + @staticmethod + def round_filters(filters, global_params): + """Calculate and round number of filters based on depth multiplier.""" + multiplier = global_params.width_coefficient + if not multiplier: + return filters + divisor = global_params.depth_divisor + filters *= multiplier + new_filters = int(filters + divisor / 2) // divisor * divisor + if new_filters < 0.9 * filters: + new_filters += divisor + return int(new_filters) + + @staticmethod + def round_repeats(repeats, global_params): + """Round number of filters based on depth multiplier.""" + multiplier = global_params.depth_coefficient + if not multiplier: + return repeats + return int(math.ceil(multiplier * repeats)) + + +class ConvBlock(nn.Layer): + def __init__(self, block_params): + super(ConvBlock, self).__init__() + self.block_args = block_params + self.has_se = (self.block_args.se_ratio is not None) and \ + (0 < self.block_args.se_ratio <= 1) + self.id_skip = block_params.id_skip + + # expansion phase + self.input_filters = self.block_args.input_filters + output_filters = \ + self.block_args.input_filters * self.block_args.expand_ratio + if self.block_args.expand_ratio != 1: + self.expand_conv = nn.Conv2D( + self.input_filters, output_filters, 1, bias_attr=False) + self.bn0 = nn.BatchNorm(output_filters) + + # depthwise conv phase + k = self.block_args.kernel_size + s = self.block_args.stride + self.depthwise_conv = nn.Conv2D( + output_filters, + output_filters, + groups=output_filters, + kernel_size=k, + stride=s, + padding='same', + bias_attr=False) + self.bn1 = nn.BatchNorm(output_filters) + + # squeeze and excitation layer, if desired + if self.has_se: + num_squeezed_channels = max(1, + int(self.block_args.input_filters * + self.block_args.se_ratio)) + self.se_reduce = nn.Conv2D(output_filters, num_squeezed_channels, 1) + self.se_expand = nn.Conv2D(num_squeezed_channels, output_filters, 1) + + # output phase + self.final_oup = self.block_args.output_filters + self.project_conv = nn.Conv2D( + output_filters, self.final_oup, 1, bias_attr=False) + self.bn2 = nn.BatchNorm(self.final_oup) + self.swish = nn.Swish() + + def drop_connect(self, inputs, p, training): + if not training: + return inputs + + batch_size = inputs.shape[0] + keep_prob = 1 - p + random_tensor = keep_prob + random_tensor += paddle.rand([batch_size, 1, 1, 1], dtype=inputs.dtype) + random_tensor = paddle.to_tensor(random_tensor, place=inputs.place) + binary_tensor = paddle.floor(random_tensor) + output = inputs / keep_prob * binary_tensor + return output + + def forward(self, inputs, drop_connect_rate=None): + # expansion and depthwise conv + x = inputs + if self.block_args.expand_ratio != 1: + x = self.swish(self.bn0(self.expand_conv(inputs))) + x = self.swish(self.bn1(self.depthwise_conv(x))) + + # squeeze and excitation + if self.has_se: + x_squeezed = F.adaptive_avg_pool2d(x, 1) + x_squeezed = self.se_expand(self.swish(self.se_reduce(x_squeezed))) + x = F.sigmoid(x_squeezed) * x + x = self.bn2(self.project_conv(x)) + + # skip conntection and drop connect + if self.id_skip and self.block_args.stride == 1 and \ + self.input_filters == self.final_oup: + if drop_connect_rate: + x = self.drop_connect( + x, p=drop_connect_rate, training=self.training) + x = x + inputs + return x + + +class EfficientNetb3_PREN(nn.Layer): + def __init__(self, in_channels): + super(EfficientNetb3_PREN, self).__init__() + self.blocks_params = EffB3Params.get_block_params() + self.global_params = EffB3Params.get_global_params() + self.out_channels = [] + # stem + stem_channels = EffUtils.round_filters(32, self.global_params) + self.conv_stem = nn.Conv2D( + in_channels, stem_channels, 3, 2, padding='same', bias_attr=False) + self.bn0 = nn.BatchNorm(stem_channels) + + self.blocks = [] + # to extract three feature maps for fpn based on efficientnetb3 backbone + self.concerned_block_idxes = [7, 17, 25] + concerned_idx = 0 + for i, block_params in enumerate(self.blocks_params): + block_params = block_params._replace( + input_filters=EffUtils.round_filters(block_params.input_filters, + self.global_params), + output_filters=EffUtils.round_filters( + block_params.output_filters, self.global_params), + num_repeat=EffUtils.round_repeats(block_params.num_repeat, + self.global_params)) + self.blocks.append( + self.add_sublayer("{}-0".format(i), ConvBlock(block_params))) + concerned_idx += 1 + if concerned_idx in self.concerned_block_idxes: + self.out_channels.append(block_params.output_filters) + if block_params.num_repeat > 1: + block_params = block_params._replace( + input_filters=block_params.output_filters, stride=1) + for j in range(block_params.num_repeat - 1): + self.blocks.append( + self.add_sublayer('{}-{}'.format(i, j + 1), + ConvBlock(block_params))) + concerned_idx += 1 + if concerned_idx in self.concerned_block_idxes: + self.out_channels.append(block_params.output_filters) + + self.swish = nn.Swish() + + def forward(self, inputs): + outs = [] + + x = self.swish(self.bn0(self.conv_stem(inputs))) + for idx, block in enumerate(self.blocks): + drop_connect_rate = self.global_params.drop_connect_rate + if drop_connect_rate: + drop_connect_rate *= float(idx) / len(self.blocks) + x = block(x, drop_connect_rate=drop_connect_rate) + if idx in self.concerned_block_idxes: + outs.append(x) + return outs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_micronet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_micronet.py new file mode 100644 index 0000000000000000000000000000000000000000..b0ae5a14c3004f63d39dff32cc737a0d96155593 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_micronet.py @@ -0,0 +1,528 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/liyunsheng13/micronet/blob/main/backbone/micronet.py +https://github.com/liyunsheng13/micronet/blob/main/backbone/activation.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn + +from ppocr.modeling.backbones.det_mobilenet_v3 import make_divisible + +M0_cfgs = [ + # s, n, c, ks, c1, c2, g1, g2, c3, g3, g4, y1, y2, y3, r + [2, 1, 8, 3, 2, 2, 0, 4, 8, 2, 2, 2, 0, 1, 1], + [2, 1, 12, 3, 2, 2, 0, 8, 12, 4, 4, 2, 2, 1, 1], + [2, 1, 16, 5, 2, 2, 0, 12, 16, 4, 4, 2, 2, 1, 1], + [1, 1, 32, 5, 1, 4, 4, 4, 32, 4, 4, 2, 2, 1, 1], + [2, 1, 64, 5, 1, 4, 8, 8, 64, 8, 8, 2, 2, 1, 1], + [1, 1, 96, 3, 1, 4, 8, 8, 96, 8, 8, 2, 2, 1, 2], + [1, 1, 384, 3, 1, 4, 12, 12, 0, 0, 0, 2, 2, 1, 2], +] +M1_cfgs = [ + # s, n, c, ks, c1, c2, g1, g2, c3, g3, g4 + [2, 1, 8, 3, 2, 2, 0, 6, 8, 2, 2, 2, 0, 1, 1], + [2, 1, 16, 3, 2, 2, 0, 8, 16, 4, 4, 2, 2, 1, 1], + [2, 1, 16, 5, 2, 2, 0, 16, 16, 4, 4, 2, 2, 1, 1], + [1, 1, 32, 5, 1, 6, 4, 4, 32, 4, 4, 2, 2, 1, 1], + [2, 1, 64, 5, 1, 6, 8, 8, 64, 8, 8, 2, 2, 1, 1], + [1, 1, 96, 3, 1, 6, 8, 8, 96, 8, 8, 2, 2, 1, 2], + [1, 1, 576, 3, 1, 6, 12, 12, 0, 0, 0, 2, 2, 1, 2], +] +M2_cfgs = [ + # s, n, c, ks, c1, c2, g1, g2, c3, g3, g4 + [2, 1, 12, 3, 2, 2, 0, 8, 12, 4, 4, 2, 0, 1, 1], + [2, 1, 16, 3, 2, 2, 0, 12, 16, 4, 4, 2, 2, 1, 1], + [1, 1, 24, 3, 2, 2, 0, 16, 24, 4, 4, 2, 2, 1, 1], + [2, 1, 32, 5, 1, 6, 6, 6, 32, 4, 4, 2, 2, 1, 1], + [1, 1, 32, 5, 1, 6, 8, 8, 32, 4, 4, 2, 2, 1, 2], + [1, 1, 64, 5, 1, 6, 8, 8, 64, 8, 8, 2, 2, 1, 2], + [2, 1, 96, 5, 1, 6, 8, 8, 96, 8, 8, 2, 2, 1, 2], + [1, 1, 128, 3, 1, 6, 12, 12, 128, 8, 8, 2, 2, 1, 2], + [1, 1, 768, 3, 1, 6, 16, 16, 0, 0, 0, 2, 2, 1, 2], +] +M3_cfgs = [ + # s, n, c, ks, c1, c2, g1, g2, c3, g3, g4 + [2, 1, 16, 3, 2, 2, 0, 12, 16, 4, 4, 0, 2, 0, 1], + [2, 1, 24, 3, 2, 2, 0, 16, 24, 4, 4, 0, 2, 0, 1], + [1, 1, 24, 3, 2, 2, 0, 24, 24, 4, 4, 0, 2, 0, 1], + [2, 1, 32, 5, 1, 6, 6, 6, 32, 4, 4, 0, 2, 0, 1], + [1, 1, 32, 5, 1, 6, 8, 8, 32, 4, 4, 0, 2, 0, 2], + [1, 1, 64, 5, 1, 6, 8, 8, 48, 8, 8, 0, 2, 0, 2], + [1, 1, 80, 5, 1, 6, 8, 8, 80, 8, 8, 0, 2, 0, 2], + [1, 1, 80, 5, 1, 6, 10, 10, 80, 8, 8, 0, 2, 0, 2], + [1, 1, 120, 5, 1, 6, 10, 10, 120, 10, 10, 0, 2, 0, 2], + [1, 1, 120, 5, 1, 6, 12, 12, 120, 10, 10, 0, 2, 0, 2], + [1, 1, 144, 3, 1, 6, 12, 12, 144, 12, 12, 0, 2, 0, 2], + [1, 1, 432, 3, 1, 3, 12, 12, 0, 0, 0, 0, 2, 0, 2], +] + + +def get_micronet_config(mode): + return eval(mode + '_cfgs') + + +class MaxGroupPooling(nn.Layer): + def __init__(self, channel_per_group=2): + super(MaxGroupPooling, self).__init__() + self.channel_per_group = channel_per_group + + def forward(self, x): + if self.channel_per_group == 1: + return x + # max op + b, c, h, w = x.shape + + # reshape + y = paddle.reshape(x, [b, c // self.channel_per_group, -1, h, w]) + out = paddle.max(y, axis=2) + return out + + +class SpatialSepConvSF(nn.Layer): + def __init__(self, inp, oups, kernel_size, stride): + super(SpatialSepConvSF, self).__init__() + + oup1, oup2 = oups + self.conv = nn.Sequential( + nn.Conv2D( + inp, + oup1, (kernel_size, 1), (stride, 1), (kernel_size // 2, 0), + bias_attr=False, + groups=1), + nn.BatchNorm2D(oup1), + nn.Conv2D( + oup1, + oup1 * oup2, (1, kernel_size), (1, stride), + (0, kernel_size // 2), + bias_attr=False, + groups=oup1), + nn.BatchNorm2D(oup1 * oup2), + ChannelShuffle(oup1), ) + + def forward(self, x): + out = self.conv(x) + return out + + +class ChannelShuffle(nn.Layer): + def __init__(self, groups): + super(ChannelShuffle, self).__init__() + self.groups = groups + + def forward(self, x): + b, c, h, w = x.shape + + channels_per_group = c // self.groups + + # reshape + x = paddle.reshape(x, [b, self.groups, channels_per_group, h, w]) + + x = paddle.transpose(x, (0, 2, 1, 3, 4)) + out = paddle.reshape(x, [b, -1, h, w]) + + return out + + +class StemLayer(nn.Layer): + def __init__(self, inp, oup, stride, groups=(4, 4)): + super(StemLayer, self).__init__() + + g1, g2 = groups + self.stem = nn.Sequential( + SpatialSepConvSF(inp, groups, 3, stride), + MaxGroupPooling(2) if g1 * g2 == 2 * oup else nn.ReLU6()) + + def forward(self, x): + out = self.stem(x) + return out + + +class DepthSpatialSepConv(nn.Layer): + def __init__(self, inp, expand, kernel_size, stride): + super(DepthSpatialSepConv, self).__init__() + + exp1, exp2 = expand + + hidden_dim = inp * exp1 + oup = inp * exp1 * exp2 + + self.conv = nn.Sequential( + nn.Conv2D( + inp, + inp * exp1, (kernel_size, 1), (stride, 1), + (kernel_size // 2, 0), + bias_attr=False, + groups=inp), + nn.BatchNorm2D(inp * exp1), + nn.Conv2D( + hidden_dim, + oup, (1, kernel_size), + 1, (0, kernel_size // 2), + bias_attr=False, + groups=hidden_dim), + nn.BatchNorm2D(oup)) + + def forward(self, x): + x = self.conv(x) + return x + + +class GroupConv(nn.Layer): + def __init__(self, inp, oup, groups=2): + super(GroupConv, self).__init__() + self.inp = inp + self.oup = oup + self.groups = groups + self.conv = nn.Sequential( + nn.Conv2D( + inp, oup, 1, 1, 0, bias_attr=False, groups=self.groups[0]), + nn.BatchNorm2D(oup)) + + def forward(self, x): + x = self.conv(x) + return x + + +class DepthConv(nn.Layer): + def __init__(self, inp, oup, kernel_size, stride): + super(DepthConv, self).__init__() + self.conv = nn.Sequential( + nn.Conv2D( + inp, + oup, + kernel_size, + stride, + kernel_size // 2, + bias_attr=False, + groups=inp), + nn.BatchNorm2D(oup)) + + def forward(self, x): + out = self.conv(x) + return out + + +class DYShiftMax(nn.Layer): + def __init__(self, + inp, + oup, + reduction=4, + act_max=1.0, + act_relu=True, + init_a=[0.0, 0.0], + init_b=[0.0, 0.0], + relu_before_pool=False, + g=None, + expansion=False): + super(DYShiftMax, self).__init__() + self.oup = oup + self.act_max = act_max * 2 + self.act_relu = act_relu + self.avg_pool = nn.Sequential(nn.ReLU() if relu_before_pool == True else + nn.Sequential(), nn.AdaptiveAvgPool2D(1)) + + self.exp = 4 if act_relu else 2 + self.init_a = init_a + self.init_b = init_b + + # determine squeeze + squeeze = make_divisible(inp // reduction, 4) + if squeeze < 4: + squeeze = 4 + + self.fc = nn.Sequential( + nn.Linear(inp, squeeze), + nn.ReLU(), nn.Linear(squeeze, oup * self.exp), nn.Hardsigmoid()) + + if g is None: + g = 1 + self.g = g[1] + if self.g != 1 and expansion: + self.g = inp // self.g + + self.gc = inp // self.g + index = paddle.to_tensor([range(inp)]) + index = paddle.reshape(index, [1, inp, 1, 1]) + index = paddle.reshape(index, [1, self.g, self.gc, 1, 1]) + indexgs = paddle.split(index, [1, self.g - 1], axis=1) + indexgs = paddle.concat((indexgs[1], indexgs[0]), axis=1) + indexs = paddle.split(indexgs, [1, self.gc - 1], axis=2) + indexs = paddle.concat((indexs[1], indexs[0]), axis=2) + self.index = paddle.reshape(indexs, [inp]) + self.expansion = expansion + + def forward(self, x): + x_in = x + x_out = x + + b, c, _, _ = x_in.shape + y = self.avg_pool(x_in) + y = paddle.reshape(y, [b, c]) + y = self.fc(y) + y = paddle.reshape(y, [b, self.oup * self.exp, 1, 1]) + y = (y - 0.5) * self.act_max + + n2, c2, h2, w2 = x_out.shape + x2 = paddle.to_tensor(x_out.numpy()[:, self.index.numpy(), :, :]) + + if self.exp == 4: + temp = y.shape + a1, b1, a2, b2 = paddle.split(y, temp[1] // self.oup, axis=1) + + a1 = a1 + self.init_a[0] + a2 = a2 + self.init_a[1] + + b1 = b1 + self.init_b[0] + b2 = b2 + self.init_b[1] + + z1 = x_out * a1 + x2 * b1 + z2 = x_out * a2 + x2 * b2 + + out = paddle.maximum(z1, z2) + + elif self.exp == 2: + temp = y.shape + a1, b1 = paddle.split(y, temp[1] // self.oup, axis=1) + a1 = a1 + self.init_a[0] + b1 = b1 + self.init_b[0] + out = x_out * a1 + x2 * b1 + + return out + + +class DYMicroBlock(nn.Layer): + def __init__(self, + inp, + oup, + kernel_size=3, + stride=1, + ch_exp=(2, 2), + ch_per_group=4, + groups_1x1=(1, 1), + depthsep=True, + shuffle=False, + activation_cfg=None): + super(DYMicroBlock, self).__init__() + + self.identity = stride == 1 and inp == oup + + y1, y2, y3 = activation_cfg['dy'] + act_reduction = 8 * activation_cfg['ratio'] + init_a = activation_cfg['init_a'] + init_b = activation_cfg['init_b'] + + t1 = ch_exp + gs1 = ch_per_group + hidden_fft, g1, g2 = groups_1x1 + hidden_dim2 = inp * t1[0] * t1[1] + + if gs1[0] == 0: + self.layers = nn.Sequential( + DepthSpatialSepConv(inp, t1, kernel_size, stride), + DYShiftMax( + hidden_dim2, + hidden_dim2, + act_max=2.0, + act_relu=True if y2 == 2 else False, + init_a=init_a, + reduction=act_reduction, + init_b=init_b, + g=gs1, + expansion=False) if y2 > 0 else nn.ReLU6(), + ChannelShuffle(gs1[1]) if shuffle else nn.Sequential(), + ChannelShuffle(hidden_dim2 // 2) + if shuffle and y2 != 0 else nn.Sequential(), + GroupConv(hidden_dim2, oup, (g1, g2)), + DYShiftMax( + oup, + oup, + act_max=2.0, + act_relu=False, + init_a=[1.0, 0.0], + reduction=act_reduction // 2, + init_b=[0.0, 0.0], + g=(g1, g2), + expansion=False) if y3 > 0 else nn.Sequential(), + ChannelShuffle(g2) if shuffle else nn.Sequential(), + ChannelShuffle(oup // 2) + if shuffle and oup % 2 == 0 and y3 != 0 else nn.Sequential(), ) + elif g2 == 0: + self.layers = nn.Sequential( + GroupConv(inp, hidden_dim2, gs1), + DYShiftMax( + hidden_dim2, + hidden_dim2, + act_max=2.0, + act_relu=False, + init_a=[1.0, 0.0], + reduction=act_reduction, + init_b=[0.0, 0.0], + g=gs1, + expansion=False) if y3 > 0 else nn.Sequential(), ) + else: + self.layers = nn.Sequential( + GroupConv(inp, hidden_dim2, gs1), + DYShiftMax( + hidden_dim2, + hidden_dim2, + act_max=2.0, + act_relu=True if y1 == 2 else False, + init_a=init_a, + reduction=act_reduction, + init_b=init_b, + g=gs1, + expansion=False) if y1 > 0 else nn.ReLU6(), + ChannelShuffle(gs1[1]) if shuffle else nn.Sequential(), + DepthSpatialSepConv(hidden_dim2, (1, 1), kernel_size, stride) + if depthsep else + DepthConv(hidden_dim2, hidden_dim2, kernel_size, stride), + nn.Sequential(), + DYShiftMax( + hidden_dim2, + hidden_dim2, + act_max=2.0, + act_relu=True if y2 == 2 else False, + init_a=init_a, + reduction=act_reduction, + init_b=init_b, + g=gs1, + expansion=True) if y2 > 0 else nn.ReLU6(), + ChannelShuffle(hidden_dim2 // 4) + if shuffle and y1 != 0 and y2 != 0 else nn.Sequential() + if y1 == 0 and y2 == 0 else ChannelShuffle(hidden_dim2 // 2), + GroupConv(hidden_dim2, oup, (g1, g2)), + DYShiftMax( + oup, + oup, + act_max=2.0, + act_relu=False, + init_a=[1.0, 0.0], + reduction=act_reduction // 2 + if oup < hidden_dim2 else act_reduction, + init_b=[0.0, 0.0], + g=(g1, g2), + expansion=False) if y3 > 0 else nn.Sequential(), + ChannelShuffle(g2) if shuffle else nn.Sequential(), + ChannelShuffle(oup // 2) + if shuffle and y3 != 0 else nn.Sequential(), ) + + def forward(self, x): + identity = x + out = self.layers(x) + + if self.identity: + out = out + identity + + return out + + +class MicroNet(nn.Layer): + """ + the MicroNet backbone network for recognition module. + Args: + mode(str): {'M0', 'M1', 'M2', 'M3'} + Four models are proposed based on four different computational costs (4M, 6M, 12M, 21M MAdds) + Default: 'M3'. + """ + + def __init__(self, mode='M3', **kwargs): + super(MicroNet, self).__init__() + + self.cfgs = get_micronet_config(mode) + + activation_cfg = {} + if mode == 'M0': + input_channel = 4 + stem_groups = 2, 2 + out_ch = 384 + activation_cfg['init_a'] = 1.0, 1.0 + activation_cfg['init_b'] = 0.0, 0.0 + elif mode == 'M1': + input_channel = 6 + stem_groups = 3, 2 + out_ch = 576 + activation_cfg['init_a'] = 1.0, 1.0 + activation_cfg['init_b'] = 0.0, 0.0 + elif mode == 'M2': + input_channel = 8 + stem_groups = 4, 2 + out_ch = 768 + activation_cfg['init_a'] = 1.0, 1.0 + activation_cfg['init_b'] = 0.0, 0.0 + elif mode == 'M3': + input_channel = 12 + stem_groups = 4, 3 + out_ch = 432 + activation_cfg['init_a'] = 1.0, 0.5 + activation_cfg['init_b'] = 0.0, 0.5 + else: + raise NotImplementedError("mode[" + mode + + "_model] is not implemented!") + + layers = [StemLayer(3, input_channel, stride=2, groups=stem_groups)] + + for idx, val in enumerate(self.cfgs): + s, n, c, ks, c1, c2, g1, g2, c3, g3, g4, y1, y2, y3, r = val + + t1 = (c1, c2) + gs1 = (g1, g2) + gs2 = (c3, g3, g4) + activation_cfg['dy'] = [y1, y2, y3] + activation_cfg['ratio'] = r + + output_channel = c + layers.append( + DYMicroBlock( + input_channel, + output_channel, + kernel_size=ks, + stride=s, + ch_exp=t1, + ch_per_group=gs1, + groups_1x1=gs2, + depthsep=True, + shuffle=True, + activation_cfg=activation_cfg, )) + input_channel = output_channel + for i in range(1, n): + layers.append( + DYMicroBlock( + input_channel, + output_channel, + kernel_size=ks, + stride=1, + ch_exp=t1, + ch_per_group=gs1, + groups_1x1=gs2, + depthsep=True, + shuffle=True, + activation_cfg=activation_cfg, )) + input_channel = output_channel + self.features = nn.Sequential(*layers) + + self.pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + + self.out_channels = make_divisible(out_ch) + + def forward(self, x): + x = self.features(x) + x = self.pool(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mobilenet_v3.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mobilenet_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..917e000d94ea01ce0057e08c1f4839240561a368 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mobilenet_v3.py @@ -0,0 +1,138 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from paddle import nn + +from ppocr.modeling.backbones.det_mobilenet_v3 import ResidualUnit, ConvBNLayer, make_divisible + +__all__ = ['MobileNetV3'] + + +class MobileNetV3(nn.Layer): + def __init__(self, + in_channels=3, + model_name='small', + scale=0.5, + large_stride=None, + small_stride=None, + disable_se=False, + **kwargs): + super(MobileNetV3, self).__init__() + self.disable_se = disable_se + if small_stride is None: + small_stride = [2, 2, 2, 2] + if large_stride is None: + large_stride = [1, 2, 2, 2] + + assert isinstance(large_stride, list), "large_stride type must " \ + "be list but got {}".format(type(large_stride)) + assert isinstance(small_stride, list), "small_stride type must " \ + "be list but got {}".format(type(small_stride)) + assert len(large_stride) == 4, "large_stride length must be " \ + "4 but got {}".format(len(large_stride)) + assert len(small_stride) == 4, "small_stride length must be " \ + "4 but got {}".format(len(small_stride)) + + if model_name == "large": + cfg = [ + # k, exp, c, se, nl, s, + [3, 16, 16, False, 'relu', large_stride[0]], + [3, 64, 24, False, 'relu', (large_stride[1], 1)], + [3, 72, 24, False, 'relu', 1], + [5, 72, 40, True, 'relu', (large_stride[2], 1)], + [5, 120, 40, True, 'relu', 1], + [5, 120, 40, True, 'relu', 1], + [3, 240, 80, False, 'hardswish', 1], + [3, 200, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 184, 80, False, 'hardswish', 1], + [3, 480, 112, True, 'hardswish', 1], + [3, 672, 112, True, 'hardswish', 1], + [5, 672, 160, True, 'hardswish', (large_stride[3], 1)], + [5, 960, 160, True, 'hardswish', 1], + [5, 960, 160, True, 'hardswish', 1], + ] + cls_ch_squeeze = 960 + elif model_name == "small": + cfg = [ + # k, exp, c, se, nl, s, + [3, 16, 16, True, 'relu', (small_stride[0], 1)], + [3, 72, 24, False, 'relu', (small_stride[1], 1)], + [3, 88, 24, False, 'relu', 1], + [5, 96, 40, True, 'hardswish', (small_stride[2], 1)], + [5, 240, 40, True, 'hardswish', 1], + [5, 240, 40, True, 'hardswish', 1], + [5, 120, 48, True, 'hardswish', 1], + [5, 144, 48, True, 'hardswish', 1], + [5, 288, 96, True, 'hardswish', (small_stride[3], 1)], + [5, 576, 96, True, 'hardswish', 1], + [5, 576, 96, True, 'hardswish', 1], + ] + cls_ch_squeeze = 576 + else: + raise NotImplementedError("mode[" + model_name + + "_model] is not implemented!") + + supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25] + assert scale in supported_scale, \ + "supported scales are {} but input scale is {}".format(supported_scale, scale) + + inplanes = 16 + # conv1 + self.conv1 = ConvBNLayer( + in_channels=in_channels, + out_channels=make_divisible(inplanes * scale), + kernel_size=3, + stride=2, + padding=1, + groups=1, + if_act=True, + act='hardswish') + i = 0 + block_list = [] + inplanes = make_divisible(inplanes * scale) + for (k, exp, c, se, nl, s) in cfg: + se = se and not self.disable_se + block_list.append( + ResidualUnit( + in_channels=inplanes, + mid_channels=make_divisible(scale * exp), + out_channels=make_divisible(scale * c), + kernel_size=k, + stride=s, + use_se=se, + act=nl)) + inplanes = make_divisible(scale * c) + i += 1 + self.blocks = nn.Sequential(*block_list) + + self.conv2 = ConvBNLayer( + in_channels=inplanes, + out_channels=make_divisible(scale * cls_ch_squeeze), + kernel_size=1, + stride=1, + padding=0, + groups=1, + if_act=True, + act='hardswish') + + self.pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + self.out_channels = make_divisible(scale * cls_ch_squeeze) + + def forward(self, x): + x = self.conv1(x) + x = self.blocks(x) + x = self.conv2(x) + x = self.pool(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mv1_enhance.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mv1_enhance.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6af5e82cf13ac42d9a970787596a65986ade54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_mv1_enhance.py @@ -0,0 +1,256 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +# This code is refer from: https://github.com/PaddlePaddle/PaddleClas/blob/develop/ppcls/arch/backbone/legendary_models/pp_lcnet.py + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import numpy as np +import paddle +from paddle import ParamAttr, reshape, transpose +import paddle.nn as nn +import paddle.nn.functional as F +from paddle.nn import Conv2D, BatchNorm, Linear, Dropout +from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D +from paddle.nn.initializer import KaimingNormal +from paddle.regularizer import L2Decay +from paddle.nn.functional import hardswish, hardsigmoid + + +class ConvBNLayer(nn.Layer): + def __init__(self, + num_channels, + filter_size, + num_filters, + stride, + padding, + channels=None, + num_groups=1, + act='hard_swish'): + super(ConvBNLayer, self).__init__() + + self._conv = Conv2D( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=padding, + groups=num_groups, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False) + + self._batch_norm = BatchNorm( + num_filters, + act=act, + param_attr=ParamAttr(regularizer=L2Decay(0.0)), + bias_attr=ParamAttr(regularizer=L2Decay(0.0))) + + def forward(self, inputs): + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class DepthwiseSeparable(nn.Layer): + def __init__(self, + num_channels, + num_filters1, + num_filters2, + num_groups, + stride, + scale, + dw_size=3, + padding=1, + use_se=False): + super(DepthwiseSeparable, self).__init__() + self.use_se = use_se + self._depthwise_conv = ConvBNLayer( + num_channels=num_channels, + num_filters=int(num_filters1 * scale), + filter_size=dw_size, + stride=stride, + padding=padding, + num_groups=int(num_groups * scale)) + if use_se: + self._se = SEModule(int(num_filters1 * scale)) + self._pointwise_conv = ConvBNLayer( + num_channels=int(num_filters1 * scale), + filter_size=1, + num_filters=int(num_filters2 * scale), + stride=1, + padding=0) + + def forward(self, inputs): + y = self._depthwise_conv(inputs) + if self.use_se: + y = self._se(y) + y = self._pointwise_conv(y) + return y + + +class MobileNetV1Enhance(nn.Layer): + def __init__(self, + in_channels=3, + scale=0.5, + last_conv_stride=1, + last_pool_type='max', + **kwargs): + super().__init__() + self.scale = scale + self.block_list = [] + + self.conv1 = ConvBNLayer( + num_channels=3, + filter_size=3, + channels=3, + num_filters=int(32 * scale), + stride=2, + padding=1) + + conv2_1 = DepthwiseSeparable( + num_channels=int(32 * scale), + num_filters1=32, + num_filters2=64, + num_groups=32, + stride=1, + scale=scale) + self.block_list.append(conv2_1) + + conv2_2 = DepthwiseSeparable( + num_channels=int(64 * scale), + num_filters1=64, + num_filters2=128, + num_groups=64, + stride=1, + scale=scale) + self.block_list.append(conv2_2) + + conv3_1 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=128, + num_groups=128, + stride=1, + scale=scale) + self.block_list.append(conv3_1) + + conv3_2 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=256, + num_groups=128, + stride=(2, 1), + scale=scale) + self.block_list.append(conv3_2) + + conv4_1 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=256, + num_groups=256, + stride=1, + scale=scale) + self.block_list.append(conv4_1) + + conv4_2 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=512, + num_groups=256, + stride=(2, 1), + scale=scale) + self.block_list.append(conv4_2) + + for _ in range(5): + conv5 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=512, + num_groups=512, + stride=1, + dw_size=5, + padding=2, + scale=scale, + use_se=False) + self.block_list.append(conv5) + + conv5_6 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=1024, + num_groups=512, + stride=(2, 1), + dw_size=5, + padding=2, + scale=scale, + use_se=True) + self.block_list.append(conv5_6) + + conv6 = DepthwiseSeparable( + num_channels=int(1024 * scale), + num_filters1=1024, + num_filters2=1024, + num_groups=1024, + stride=last_conv_stride, + dw_size=5, + padding=2, + use_se=True, + scale=scale) + self.block_list.append(conv6) + + self.block_list = nn.Sequential(*self.block_list) + if last_pool_type == 'avg': + self.pool = nn.AvgPool2D(kernel_size=2, stride=2, padding=0) + else: + self.pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + self.out_channels = int(1024 * scale) + + def forward(self, inputs): + y = self.conv1(inputs) + y = self.block_list(y) + y = self.pool(y) + return y + + +class SEModule(nn.Layer): + def __init__(self, channel, reduction=4): + super(SEModule, self).__init__() + self.avg_pool = AdaptiveAvgPool2D(1) + self.conv1 = Conv2D( + in_channels=channel, + out_channels=channel // reduction, + kernel_size=1, + stride=1, + padding=0, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + self.conv2 = Conv2D( + in_channels=channel // reduction, + out_channels=channel, + kernel_size=1, + stride=1, + padding=0, + weight_attr=ParamAttr(), + bias_attr=ParamAttr()) + + def forward(self, inputs): + outputs = self.avg_pool(inputs) + outputs = self.conv1(outputs) + outputs = F.relu(outputs) + outputs = self.conv2(outputs) + outputs = hardsigmoid(outputs) + return paddle.multiply(x=inputs, y=outputs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_nrtr_mtb.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_nrtr_mtb.py new file mode 100644 index 0000000000000000000000000000000000000000..22e02a6371c3ff8b28fd88b5cfa1087309d551f8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_nrtr_mtb.py @@ -0,0 +1,48 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from paddle import nn +import paddle + + +class MTB(nn.Layer): + def __init__(self, cnn_num, in_channels): + super(MTB, self).__init__() + self.block = nn.Sequential() + self.out_channels = in_channels + self.cnn_num = cnn_num + if self.cnn_num == 2: + for i in range(self.cnn_num): + self.block.add_sublayer( + 'conv_{}'.format(i), + nn.Conv2D( + in_channels=in_channels + if i == 0 else 32 * (2**(i - 1)), + out_channels=32 * (2**i), + kernel_size=3, + stride=2, + padding=1)) + self.block.add_sublayer('relu_{}'.format(i), nn.ReLU()) + self.block.add_sublayer('bn_{}'.format(i), + nn.BatchNorm2D(32 * (2**i))) + + def forward(self, images): + x = self.block(images) + if self.cnn_num == 2: + # (b, w, h, c) + x = paddle.transpose(x, [0, 3, 2, 1]) + x_shape = paddle.shape(x) + x = paddle.reshape( + x, [x_shape[0], x_shape[1], x_shape[2] * x_shape[3]]) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_31.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_31.py new file mode 100644 index 0000000000000000000000000000000000000000..46dc374008b56a20dbd4be257775368e9cbbace4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_31.py @@ -0,0 +1,231 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/layers/conv_layer.py +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/backbones/resnet31_ocr.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F +import numpy as np + +__all__ = ["ResNet31"] + +def conv3x3(in_channel, out_channel, stride=1, conv_weight_attr=None): + return nn.Conv2D( + in_channel, + out_channel, + kernel_size=3, + stride=stride, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False) + + +class BasicBlock(nn.Layer): + expansion = 1 + + def __init__(self, in_channels, channels, stride=1, downsample=False, conv_weight_attr=None, bn_weight_attr=None): + super().__init__() + self.conv1 = conv3x3(in_channels, channels, stride, + conv_weight_attr=conv_weight_attr) + self.bn1 = nn.BatchNorm2D(channels, weight_attr=bn_weight_attr) + self.relu = nn.ReLU() + self.conv2 = conv3x3(channels, channels, + conv_weight_attr=conv_weight_attr) + self.bn2 = nn.BatchNorm2D(channels, weight_attr=bn_weight_attr) + self.downsample = downsample + if downsample: + self.downsample = nn.Sequential( + nn.Conv2D( + in_channels, + channels * self.expansion, + 1, + stride, + weight_attr=conv_weight_attr, + bias_attr=False), + nn.BatchNorm2D(channels * self.expansion, weight_attr=bn_weight_attr)) + else: + self.downsample = nn.Sequential() + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class ResNet31(nn.Layer): + ''' + Args: + in_channels (int): Number of channels of input image tensor. + layers (list[int]): List of BasicBlock number for each stage. + channels (list[int]): List of out_channels of Conv2d layer. + out_indices (None | Sequence[int]): Indices of output stages. + last_stage_pool (bool): If True, add `MaxPool2d` layer to last stage. + init_type (None | str): the config to control the initialization. + ''' + + def __init__(self, + in_channels=3, + layers=[1, 2, 5, 3], + channels=[64, 128, 256, 256, 512, 512, 512], + out_indices=None, + last_stage_pool=False, + init_type=None): + super(ResNet31, self).__init__() + assert isinstance(in_channels, int) + assert isinstance(last_stage_pool, bool) + + self.out_indices = out_indices + self.last_stage_pool = last_stage_pool + + conv_weight_attr = None + bn_weight_attr = None + + if init_type is not None: + support_dict = ['KaimingNormal'] + assert init_type in support_dict, Exception( + "resnet31 only support {}".format(support_dict)) + conv_weight_attr = nn.initializer.KaimingNormal() + bn_weight_attr = ParamAttr(initializer=nn.initializer.Uniform(), learning_rate=1) + + # conv 1 (Conv Conv) + self.conv1_1 = nn.Conv2D( + in_channels, channels[0], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn1_1 = nn.BatchNorm2D(channels[0], weight_attr=bn_weight_attr) + self.relu1_1 = nn.ReLU() + + self.conv1_2 = nn.Conv2D( + channels[0], channels[1], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn1_2 = nn.BatchNorm2D(channels[1], weight_attr=bn_weight_attr) + self.relu1_2 = nn.ReLU() + + # conv 2 (Max-pooling, Residual block, Conv) + self.pool2 = nn.MaxPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self.block2 = self._make_layer(channels[1], channels[2], layers[0], + conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr) + self.conv2 = nn.Conv2D( + channels[2], channels[2], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn2 = nn.BatchNorm2D(channels[2], weight_attr=bn_weight_attr) + self.relu2 = nn.ReLU() + + # conv 3 (Max-pooling, Residual block, Conv) + self.pool3 = nn.MaxPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self.block3 = self._make_layer(channels[2], channels[3], layers[1], + conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr) + self.conv3 = nn.Conv2D( + channels[3], channels[3], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn3 = nn.BatchNorm2D(channels[3], weight_attr=bn_weight_attr) + self.relu3 = nn.ReLU() + + # conv 4 (Max-pooling, Residual block, Conv) + self.pool4 = nn.MaxPool2D( + kernel_size=(2, 1), stride=(2, 1), padding=0, ceil_mode=True) + self.block4 = self._make_layer(channels[3], channels[4], layers[2], + conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr) + self.conv4 = nn.Conv2D( + channels[4], channels[4], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn4 = nn.BatchNorm2D(channels[4], weight_attr=bn_weight_attr) + self.relu4 = nn.ReLU() + + # conv 5 ((Max-pooling), Residual block, Conv) + self.pool5 = None + if self.last_stage_pool: + self.pool5 = nn.MaxPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self.block5 = self._make_layer(channels[4], channels[5], layers[3], + conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr) + self.conv5 = nn.Conv2D( + channels[5], channels[5], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr) + self.bn5 = nn.BatchNorm2D(channels[5], weight_attr=bn_weight_attr) + self.relu5 = nn.ReLU() + + self.out_channels = channels[-1] + + def _make_layer(self, input_channels, output_channels, blocks, conv_weight_attr=None, bn_weight_attr=None): + layers = [] + for _ in range(blocks): + downsample = None + if input_channels != output_channels: + downsample = nn.Sequential( + nn.Conv2D( + input_channels, + output_channels, + kernel_size=1, + stride=1, + weight_attr=conv_weight_attr, + bias_attr=False), + nn.BatchNorm2D(output_channels, weight_attr=bn_weight_attr)) + + layers.append( + BasicBlock( + input_channels, output_channels, downsample=downsample, + conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr)) + input_channels = output_channels + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1_1(x) + x = self.bn1_1(x) + x = self.relu1_1(x) + + x = self.conv1_2(x) + x = self.bn1_2(x) + x = self.relu1_2(x) + + outs = [] + for i in range(4): + layer_index = i + 2 + pool_layer = getattr(self, f'pool{layer_index}') + block_layer = getattr(self, f'block{layer_index}') + conv_layer = getattr(self, f'conv{layer_index}') + bn_layer = getattr(self, f'bn{layer_index}') + relu_layer = getattr(self, f'relu{layer_index}') + + if pool_layer is not None: + x = pool_layer(x) + x = block_layer(x) + x = conv_layer(x) + x = bn_layer(x) + x = relu_layer(x) + + outs.append(x) + + if self.out_indices is not None: + return tuple([outs[i] for i in self.out_indices]) + + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_32.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_32.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd19251a3ed43a472d49f03743ead1491aa86ac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_32.py @@ -0,0 +1,269 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/hikopensource/DAVAR-Lab-OCR/davarocr/davar_rcg/models/backbones/ResNet32.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle.nn as nn + +__all__ = ["ResNet32"] + +conv_weight_attr = nn.initializer.KaimingNormal() + +class ResNet32(nn.Layer): + """ + Feature Extractor is proposed in FAN Ref [1] + + Ref [1]: Focusing Attention: Towards Accurate Text Recognition in Neural Images ICCV-2017 + """ + + def __init__(self, in_channels, out_channels=512): + """ + + Args: + in_channels (int): input channel + output_channel (int): output channel + """ + super(ResNet32, self).__init__() + self.out_channels = out_channels + self.ConvNet = ResNet(in_channels, out_channels, BasicBlock, [1, 2, 5, 3]) + + def forward(self, inputs): + """ + Args: + inputs: input feature + + Returns: + output feature + + """ + return self.ConvNet(inputs) + +class BasicBlock(nn.Layer): + """Res-net Basic Block""" + expansion = 1 + + def __init__(self, inplanes, planes, + stride=1, downsample=None, + norm_type='BN', **kwargs): + """ + Args: + inplanes (int): input channel + planes (int): channels of the middle feature + stride (int): stride of the convolution + downsample (int): type of the down_sample + norm_type (str): type of the normalization + **kwargs (None): backup parameter + """ + super(BasicBlock, self).__init__() + self.conv1 = self._conv3x3(inplanes, planes) + self.bn1 = nn.BatchNorm2D(planes) + self.conv2 = self._conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2D(planes) + self.relu = nn.ReLU() + self.downsample = downsample + self.stride = stride + + def _conv3x3(self, in_planes, out_planes, stride=1): + """ + + Args: + in_planes (int): input channel + out_planes (int): channels of the middle feature + stride (int): stride of the convolution + Returns: + nn.Layer: Conv2D with kernel = 3 + + """ + + return nn.Conv2D(in_planes, out_planes, + kernel_size=3, stride=stride, + padding=1, weight_attr=conv_weight_attr, + bias_attr=False) + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + out += residual + out = self.relu(out) + + return out + +class ResNet(nn.Layer): + """Res-Net network structure""" + def __init__(self, input_channel, + output_channel, block, layers): + """ + + Args: + input_channel (int): input channel + output_channel (int): output channel + block (BasicBlock): convolution block + layers (list): layers of the block + """ + super(ResNet, self).__init__() + + self.output_channel_block = [int(output_channel / 4), + int(output_channel / 2), + output_channel, + output_channel] + + self.inplanes = int(output_channel / 8) + self.conv0_1 = nn.Conv2D(input_channel, int(output_channel / 16), + kernel_size=3, stride=1, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn0_1 = nn.BatchNorm2D(int(output_channel / 16)) + self.conv0_2 = nn.Conv2D(int(output_channel / 16), self.inplanes, + kernel_size=3, stride=1, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn0_2 = nn.BatchNorm2D(self.inplanes) + self.relu = nn.ReLU() + + self.maxpool1 = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + self.layer1 = self._make_layer(block, + self.output_channel_block[0], + layers[0]) + self.conv1 = nn.Conv2D(self.output_channel_block[0], + self.output_channel_block[0], + kernel_size=3, stride=1, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn1 = nn.BatchNorm2D(self.output_channel_block[0]) + + self.maxpool2 = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + self.layer2 = self._make_layer(block, + self.output_channel_block[1], + layers[1], stride=1) + self.conv2 = nn.Conv2D(self.output_channel_block[1], + self.output_channel_block[1], + kernel_size=3, stride=1, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False,) + self.bn2 = nn.BatchNorm2D(self.output_channel_block[1]) + + self.maxpool3 = nn.MaxPool2D(kernel_size=2, + stride=(2, 1), + padding=(0, 1)) + self.layer3 = self._make_layer(block, self.output_channel_block[2], + layers[2], stride=1) + self.conv3 = nn.Conv2D(self.output_channel_block[2], + self.output_channel_block[2], + kernel_size=3, stride=1, + padding=1, + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn3 = nn.BatchNorm2D(self.output_channel_block[2]) + + self.layer4 = self._make_layer(block, self.output_channel_block[3], + layers[3], stride=1) + self.conv4_1 = nn.Conv2D(self.output_channel_block[3], + self.output_channel_block[3], + kernel_size=2, stride=(2, 1), + padding=(0, 1), + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn4_1 = nn.BatchNorm2D(self.output_channel_block[3]) + self.conv4_2 = nn.Conv2D(self.output_channel_block[3], + self.output_channel_block[3], + kernel_size=2, stride=1, + padding=0, + weight_attr=conv_weight_attr, + bias_attr=False) + self.bn4_2 = nn.BatchNorm2D(self.output_channel_block[3]) + + def _make_layer(self, block, planes, blocks, stride=1): + """ + + Args: + block (block): convolution block + planes (int): input channels + blocks (list): layers of the block + stride (int): stride of the convolution + + Returns: + nn.Sequential: the combination of the convolution block + + """ + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2D(self.inplanes, planes * block.expansion, + kernel_size=1, stride=stride, + weight_attr=conv_weight_attr, + bias_attr=False), + nn.BatchNorm2D(planes * block.expansion), + ) + + layers = list() + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv0_1(x) + x = self.bn0_1(x) + x = self.relu(x) + x = self.conv0_2(x) + x = self.bn0_2(x) + x = self.relu(x) + + x = self.maxpool1(x) + x = self.layer1(x) + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + + x = self.maxpool2(x) + x = self.layer2(x) + x = self.conv2(x) + x = self.bn2(x) + x = self.relu(x) + + x = self.maxpool3(x) + x = self.layer3(x) + x = self.conv3(x) + x = self.bn3(x) + x = self.relu(x) + + x = self.layer4(x) + x = self.conv4_1(x) + x = self.bn4_1(x) + x = self.relu(x) + x = self.conv4_2(x) + x = self.bn4_2(x) + x = self.relu(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_45.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_45.py new file mode 100644 index 0000000000000000000000000000000000000000..083eb7f48811cf6887845f98bbeae315b727287d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_45.py @@ -0,0 +1,144 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FangShancheng/ABINet/tree/main/modules +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +from paddle.nn.initializer import KaimingNormal +import paddle.nn as nn +import paddle.nn.functional as F +import numpy as np +import math + +__all__ = ["ResNet45"] + + +def conv1x1(in_planes, out_planes, stride=1): + return nn.Conv2D( + in_planes, + out_planes, + kernel_size=1, + stride=1, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False) + + +def conv3x3(in_channel, out_channel, stride=1): + return nn.Conv2D( + in_channel, + out_channel, + kernel_size=3, + stride=stride, + padding=1, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False) + + +class BasicBlock(nn.Layer): + expansion = 1 + + def __init__(self, in_channels, channels, stride=1, downsample=None): + super().__init__() + self.conv1 = conv1x1(in_channels, channels) + self.bn1 = nn.BatchNorm2D(channels) + self.relu = nn.ReLU() + self.conv2 = conv3x3(channels, channels, stride) + self.bn2 = nn.BatchNorm2D(channels) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + out += residual + out = self.relu(out) + + return out + + +class ResNet45(nn.Layer): + def __init__(self, + in_channels=3, + block=BasicBlock, + layers=[3, 4, 6, 6, 3], + strides=[2, 1, 2, 1, 1]): + self.inplanes = 32 + super(ResNet45, self).__init__() + self.conv1 = nn.Conv2D( + in_channels, + 32, + kernel_size=3, + stride=1, + padding=1, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False) + self.bn1 = nn.BatchNorm2D(32) + self.relu = nn.ReLU() + + self.layer1 = self._make_layer(block, 32, layers[0], stride=strides[0]) + self.layer2 = self._make_layer(block, 64, layers[1], stride=strides[1]) + self.layer3 = self._make_layer(block, 128, layers[2], stride=strides[2]) + self.layer4 = self._make_layer(block, 256, layers[3], stride=strides[3]) + self.layer5 = self._make_layer(block, 512, layers[4], stride=strides[4]) + self.out_channels = 512 + + def _make_layer(self, block, planes, blocks, stride=1): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + # downsample = True + downsample = nn.Sequential( + nn.Conv2D( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + weight_attr=ParamAttr(initializer=KaimingNormal()), + bias_attr=False), + nn.BatchNorm2D(planes * block.expansion), ) + + layers = [] + layers.append(block(self.inplanes, planes, stride, downsample)) + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.layer5(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_aster.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_aster.py new file mode 100644 index 0000000000000000000000000000000000000000..782dc393ea3c8b67d68fb9f4b038afc85ffcad93 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_aster.py @@ -0,0 +1,143 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/resnet_aster.py +""" +import paddle +import paddle.nn as nn + +import sys +import math + + +def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" + return nn.Conv2D( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=1, + bias_attr=False) + + +def conv1x1(in_planes, out_planes, stride=1): + """1x1 convolution""" + return nn.Conv2D( + in_planes, out_planes, kernel_size=1, stride=stride, bias_attr=False) + + +def get_sinusoid_encoding(n_position, feat_dim, wave_length=10000): + # [n_position] + positions = paddle.arange(0, n_position) + # [feat_dim] + dim_range = paddle.arange(0, feat_dim) + dim_range = paddle.pow(wave_length, 2 * (dim_range // 2) / feat_dim) + # [n_position, feat_dim] + angles = paddle.unsqueeze( + positions, axis=1) / paddle.unsqueeze( + dim_range, axis=0) + angles = paddle.cast(angles, "float32") + angles[:, 0::2] = paddle.sin(angles[:, 0::2]) + angles[:, 1::2] = paddle.cos(angles[:, 1::2]) + return angles + + +class AsterBlock(nn.Layer): + def __init__(self, inplanes, planes, stride=1, downsample=None): + super(AsterBlock, self).__init__() + self.conv1 = conv1x1(inplanes, planes, stride) + self.bn1 = nn.BatchNorm2D(planes) + self.relu = nn.ReLU() + self.conv2 = conv3x3(planes, planes) + self.bn2 = nn.BatchNorm2D(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + residual = x + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + residual = self.downsample(x) + out += residual + out = self.relu(out) + return out + + +class ResNet_ASTER(nn.Layer): + """For aster or crnn""" + + def __init__(self, with_lstm=True, n_group=1, in_channels=3): + super(ResNet_ASTER, self).__init__() + self.with_lstm = with_lstm + self.n_group = n_group + + self.layer0 = nn.Sequential( + nn.Conv2D( + in_channels, + 32, + kernel_size=(3, 3), + stride=1, + padding=1, + bias_attr=False), + nn.BatchNorm2D(32), + nn.ReLU()) + + self.inplanes = 32 + self.layer1 = self._make_layer(32, 3, [2, 2]) # [16, 50] + self.layer2 = self._make_layer(64, 4, [2, 2]) # [8, 25] + self.layer3 = self._make_layer(128, 6, [2, 1]) # [4, 25] + self.layer4 = self._make_layer(256, 6, [2, 1]) # [2, 25] + self.layer5 = self._make_layer(512, 3, [2, 1]) # [1, 25] + + if with_lstm: + self.rnn = nn.LSTM(512, 256, direction="bidirect", num_layers=2) + self.out_channels = 2 * 256 + else: + self.out_channels = 512 + + def _make_layer(self, planes, blocks, stride): + downsample = None + if stride != [1, 1] or self.inplanes != planes: + downsample = nn.Sequential( + conv1x1(self.inplanes, planes, stride), nn.BatchNorm2D(planes)) + + layers = [] + layers.append(AsterBlock(self.inplanes, planes, stride, downsample)) + self.inplanes = planes + for _ in range(1, blocks): + layers.append(AsterBlock(self.inplanes, planes)) + return nn.Sequential(*layers) + + def forward(self, x): + x0 = self.layer0(x) + x1 = self.layer1(x0) + x2 = self.layer2(x1) + x3 = self.layer3(x2) + x4 = self.layer4(x3) + x5 = self.layer5(x4) + + cnn_feat = x5.squeeze(2) # [N, c, w] + cnn_feat = paddle.transpose(cnn_feat, perm=[0, 2, 1]) + if self.with_lstm: + rnn_feat, _ = self.rnn(cnn_feat) + return rnn_feat + else: + return cnn_feat \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..79efd6e41e231ecad99aa4d01a8226a8550bd1ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_fpn.py @@ -0,0 +1,306 @@ +#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +#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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import paddle +import numpy as np + +__all__ = ["ResNetFPN"] + + +class ResNetFPN(nn.Layer): + def __init__(self, in_channels=1, layers=50, **kwargs): + super(ResNetFPN, self).__init__() + supported_layers = { + 18: { + 'depth': [2, 2, 2, 2], + 'block_class': BasicBlock + }, + 34: { + 'depth': [3, 4, 6, 3], + 'block_class': BasicBlock + }, + 50: { + 'depth': [3, 4, 6, 3], + 'block_class': BottleneckBlock + }, + 101: { + 'depth': [3, 4, 23, 3], + 'block_class': BottleneckBlock + }, + 152: { + 'depth': [3, 8, 36, 3], + 'block_class': BottleneckBlock + } + } + stride_list = [(2, 2), (2, 2), (1, 1), (1, 1)] + num_filters = [64, 128, 256, 512] + self.depth = supported_layers[layers]['depth'] + self.F = [] + self.conv = ConvBNLayer( + in_channels=in_channels, + out_channels=64, + kernel_size=7, + stride=2, + act="relu", + name="conv1") + self.block_list = [] + in_ch = 64 + if layers >= 50: + for block in range(len(self.depth)): + for i in range(self.depth[block]): + if layers in [101, 152] and block == 2: + if i == 0: + conv_name = "res" + str(block + 2) + "a" + else: + conv_name = "res" + str(block + 2) + "b" + str(i) + else: + conv_name = "res" + str(block + 2) + chr(97 + i) + block_list = self.add_sublayer( + "bottleneckBlock_{}_{}".format(block, i), + BottleneckBlock( + in_channels=in_ch, + out_channels=num_filters[block], + stride=stride_list[block] if i == 0 else 1, + name=conv_name)) + in_ch = num_filters[block] * 4 + self.block_list.append(block_list) + self.F.append(block_list) + else: + for block in range(len(self.depth)): + for i in range(self.depth[block]): + conv_name = "res" + str(block + 2) + chr(97 + i) + if i == 0 and block != 0: + stride = (2, 1) + else: + stride = (1, 1) + basic_block = self.add_sublayer( + conv_name, + BasicBlock( + in_channels=in_ch, + out_channels=num_filters[block], + stride=stride_list[block] if i == 0 else 1, + is_first=block == i == 0, + name=conv_name)) + in_ch = basic_block.out_channels + self.block_list.append(basic_block) + out_ch_list = [in_ch // 4, in_ch // 2, in_ch] + self.base_block = [] + self.conv_trans = [] + self.bn_block = [] + for i in [-2, -3]: + in_channels = out_ch_list[i + 1] + out_ch_list[i] + + self.base_block.append( + self.add_sublayer( + "F_{}_base_block_0".format(i), + nn.Conv2D( + in_channels=in_channels, + out_channels=out_ch_list[i], + kernel_size=1, + weight_attr=ParamAttr(trainable=True), + bias_attr=ParamAttr(trainable=True)))) + self.base_block.append( + self.add_sublayer( + "F_{}_base_block_1".format(i), + nn.Conv2D( + in_channels=out_ch_list[i], + out_channels=out_ch_list[i], + kernel_size=3, + padding=1, + weight_attr=ParamAttr(trainable=True), + bias_attr=ParamAttr(trainable=True)))) + self.base_block.append( + self.add_sublayer( + "F_{}_base_block_2".format(i), + nn.BatchNorm( + num_channels=out_ch_list[i], + act="relu", + param_attr=ParamAttr(trainable=True), + bias_attr=ParamAttr(trainable=True)))) + self.base_block.append( + self.add_sublayer( + "F_{}_base_block_3".format(i), + nn.Conv2D( + in_channels=out_ch_list[i], + out_channels=512, + kernel_size=1, + bias_attr=ParamAttr(trainable=True), + weight_attr=ParamAttr(trainable=True)))) + self.out_channels = 512 + + def __call__(self, x): + x = self.conv(x) + fpn_list = [] + F = [] + for i in range(len(self.depth)): + fpn_list.append(np.sum(self.depth[:i + 1])) + + for i, block in enumerate(self.block_list): + x = block(x) + for number in fpn_list: + if i + 1 == number: + F.append(x) + base = F[-1] + + j = 0 + for i, block in enumerate(self.base_block): + if i % 3 == 0 and i < 6: + j = j + 1 + b, c, w, h = F[-j - 1].shape + if [w, h] == list(base.shape[2:]): + base = base + else: + base = self.conv_trans[j - 1](base) + base = self.bn_block[j - 1](base) + base = paddle.concat([base, F[-j - 1]], axis=1) + base = block(base) + return base + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=2 if stride == (1, 1) else kernel_size, + dilation=2 if stride == (1, 1) else 1, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + '.conv2d.output.1.w_0'), + bias_attr=False, ) + + if name == "conv1": + bn_name = "bn_" + name + else: + bn_name = "bn" + name[3:] + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name=name + '.output.1.w_0'), + bias_attr=ParamAttr(name=name + '.output.1.b_0'), + moving_mean_name=bn_name + "_mean", + moving_variance_name=bn_name + "_variance") + + def __call__(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class ShortCut(nn.Layer): + def __init__(self, in_channels, out_channels, stride, name, is_first=False): + super(ShortCut, self).__init__() + self.use_conv = True + + if in_channels != out_channels or stride != 1 or is_first == True: + if stride == (1, 1): + self.conv = ConvBNLayer( + in_channels, out_channels, 1, 1, name=name) + else: # stride==(2,2) + self.conv = ConvBNLayer( + in_channels, out_channels, 1, stride, name=name) + else: + self.use_conv = False + + def forward(self, x): + if self.use_conv: + x = self.conv(x) + return x + + +class BottleneckBlock(nn.Layer): + def __init__(self, in_channels, out_channels, stride, name): + super(BottleneckBlock, self).__init__() + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2b") + + self.conv2 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels * 4, + kernel_size=1, + act=None, + name=name + "_branch2c") + + self.short = ShortCut( + in_channels=in_channels, + out_channels=out_channels * 4, + stride=stride, + is_first=False, + name=name + "_branch1") + self.out_channels = out_channels * 4 + + def forward(self, x): + y = self.conv0(x) + y = self.conv1(y) + y = self.conv2(y) + y = y + self.short(x) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__(self, in_channels, out_channels, stride, name, is_first): + super(BasicBlock, self).__init__() + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + act='relu', + stride=stride, + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + act=None, + name=name + "_branch2b") + self.short = ShortCut( + in_channels=in_channels, + out_channels=out_channels, + stride=stride, + is_first=is_first, + name=name + "_branch1") + self.out_channels = out_channels + + def forward(self, x): + y = self.conv0(x) + y = self.conv1(y) + y = y + self.short(x) + return F.relu(y) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_vd.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_vd.py new file mode 100644 index 0000000000000000000000000000000000000000..0187deb96f111a2c2b545c7be42dba48c7352e17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_resnet_vd.py @@ -0,0 +1,286 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +__all__ = ["ResNet"] + + +class ConvBNLayer(nn.Layer): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + is_vd_mode=False, + act=None, + name=None, ): + super(ConvBNLayer, self).__init__() + + self.is_vd_mode = is_vd_mode + self._pool2d_avg = nn.AvgPool2D( + kernel_size=stride, stride=stride, padding=0, ceil_mode=True) + self._conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1 if is_vd_mode else stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + "_weights"), + bias_attr=False) + if name == "conv1": + bn_name = "bn_" + name + else: + bn_name = "bn" + name[3:] + self._batch_norm = nn.BatchNorm( + out_channels, + act=act, + param_attr=ParamAttr(name=bn_name + '_scale'), + bias_attr=ParamAttr(bn_name + '_offset'), + moving_mean_name=bn_name + '_mean', + moving_variance_name=bn_name + '_variance') + + def forward(self, inputs): + if self.is_vd_mode: + inputs = self._pool2d_avg(inputs) + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class BottleneckBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BottleneckBlock, self).__init__() + + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2b") + self.conv2 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels * 4, + kernel_size=1, + act=None, + name=name + "_branch2c") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels * 4, + kernel_size=1, + stride=stride, + is_vd_mode=not if_first and stride[0] != 1, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + + conv1 = self.conv1(y) + conv2 = self.conv2(conv1) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv2) + y = F.relu(y) + return y + + +class BasicBlock(nn.Layer): + def __init__(self, + in_channels, + out_channels, + stride, + shortcut=True, + if_first=False, + name=None): + super(BasicBlock, self).__init__() + self.stride = stride + self.conv0 = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + stride=stride, + act='relu', + name=name + "_branch2a") + self.conv1 = ConvBNLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + act=None, + name=name + "_branch2b") + + if not shortcut: + self.short = ConvBNLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=stride, + is_vd_mode=not if_first and stride[0] != 1, + name=name + "_branch1") + + self.shortcut = shortcut + + def forward(self, inputs): + y = self.conv0(inputs) + conv1 = self.conv1(y) + + if self.shortcut: + short = inputs + else: + short = self.short(inputs) + y = paddle.add(x=short, y=conv1) + y = F.relu(y) + return y + + +class ResNet(nn.Layer): + def __init__(self, in_channels=3, layers=50, **kwargs): + super(ResNet, self).__init__() + + self.layers = layers + supported_layers = [18, 34, 50, 101, 152, 200] + assert layers in supported_layers, \ + "supported layers are {} but input layer is {}".format( + supported_layers, layers) + + if layers == 18: + depth = [2, 2, 2, 2] + elif layers == 34 or layers == 50: + depth = [3, 4, 6, 3] + elif layers == 101: + depth = [3, 4, 23, 3] + elif layers == 152: + depth = [3, 8, 36, 3] + elif layers == 200: + depth = [3, 12, 48, 3] + num_channels = [64, 256, 512, + 1024] if layers >= 50 else [64, 64, 128, 256] + num_filters = [64, 128, 256, 512] + + self.conv1_1 = ConvBNLayer( + in_channels=in_channels, + out_channels=32, + kernel_size=3, + stride=1, + act='relu', + name="conv1_1") + self.conv1_2 = ConvBNLayer( + in_channels=32, + out_channels=32, + kernel_size=3, + stride=1, + act='relu', + name="conv1_2") + self.conv1_3 = ConvBNLayer( + in_channels=32, + out_channels=64, + kernel_size=3, + stride=1, + act='relu', + name="conv1_3") + self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1) + + self.block_list = [] + if layers >= 50: + for block in range(len(depth)): + shortcut = False + for i in range(depth[block]): + if layers in [101, 152, 200] and block == 2: + if i == 0: + conv_name = "res" + str(block + 2) + "a" + else: + conv_name = "res" + str(block + 2) + "b" + str(i) + else: + conv_name = "res" + str(block + 2) + chr(97 + i) + + if i == 0 and block != 0: + stride = (2, 1) + else: + stride = (1, 1) + bottleneck_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BottleneckBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block] * 4, + out_channels=num_filters[block], + stride=stride, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + self.block_list.append(bottleneck_block) + self.out_channels = num_filters[block] * 4 + else: + for block in range(len(depth)): + shortcut = False + for i in range(depth[block]): + conv_name = "res" + str(block + 2) + chr(97 + i) + if i == 0 and block != 0: + stride = (2, 1) + else: + stride = (1, 1) + + basic_block = self.add_sublayer( + 'bb_%d_%d' % (block, i), + BasicBlock( + in_channels=num_channels[block] + if i == 0 else num_filters[block], + out_channels=num_filters[block], + stride=stride, + shortcut=shortcut, + if_first=block == i == 0, + name=conv_name)) + shortcut = True + self.block_list.append(basic_block) + self.out_channels = num_filters[block] + self.out_pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + + def forward(self, inputs): + y = self.conv1_1(inputs) + y = self.conv1_2(y) + y = self.conv1_3(y) + y = self.pool2d_max(y) + for block in self.block_list: + y = block(y) + y = self.out_pool(y) + return y diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_svtrnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_svtrnet.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c07f4476929d49237c8e9a10713f881f5f556b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_svtrnet.py @@ -0,0 +1,592 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from paddle import ParamAttr +from paddle.nn.initializer import KaimingNormal +import numpy as np +import paddle +import paddle.nn as nn +from paddle.nn.initializer import TruncatedNormal, Constant, Normal + +trunc_normal_ = TruncatedNormal(std=.02) +normal_ = Normal +zeros_ = Constant(value=0.) +ones_ = Constant(value=1.) + + +def drop_path(x, drop_prob=0., training=False): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... + """ + if drop_prob == 0. or not training: + return x + keep_prob = paddle.to_tensor(1 - drop_prob) + shape = (paddle.shape(x)[0], ) + (1, ) * (x.ndim - 1) + random_tensor = keep_prob + paddle.rand(shape, dtype=x.dtype) + random_tensor = paddle.floor(random_tensor) # binarize + output = x.divide(keep_prob) * random_tensor + return output + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=0, + bias_attr=False, + groups=1, + act=nn.GELU): + super().__init__() + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=paddle.ParamAttr( + initializer=nn.initializer.KaimingUniform()), + bias_attr=bias_attr) + self.norm = nn.BatchNorm2D(out_channels) + self.act = act() + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + out = self.act(out) + return out + + +class DropPath(nn.Layer): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + +class Identity(nn.Layer): + def __init__(self): + super(Identity, self).__init__() + + def forward(self, input): + return input + + +class Mlp(nn.Layer): + def __init__(self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class ConvMixer(nn.Layer): + def __init__( + self, + dim, + num_heads=8, + HW=[8, 25], + local_k=[3, 3], ): + super().__init__() + self.HW = HW + self.dim = dim + self.local_mixer = nn.Conv2D( + dim, + dim, + local_k, + 1, [local_k[0] // 2, local_k[1] // 2], + groups=num_heads, + weight_attr=ParamAttr(initializer=KaimingNormal())) + + def forward(self, x): + h = self.HW[0] + w = self.HW[1] + x = x.transpose([0, 2, 1]).reshape([0, self.dim, h, w]) + x = self.local_mixer(x) + x = x.flatten(2).transpose([0, 2, 1]) + return x + + +class Attention(nn.Layer): + def __init__(self, + dim, + num_heads=8, + mixer='Global', + HW=None, + local_k=[7, 11], + qkv_bias=False, + qk_scale=None, + attn_drop=0., + proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias_attr=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.HW = HW + if HW is not None: + H = HW[0] + W = HW[1] + self.N = H * W + self.C = dim + if mixer == 'Local' and HW is not None: + hk = local_k[0] + wk = local_k[1] + mask = paddle.ones([H * W, H + hk - 1, W + wk - 1], dtype='float32') + for h in range(0, H): + for w in range(0, W): + mask[h * W + w, h:h + hk, w:w + wk] = 0. + mask_paddle = mask[:, hk // 2:H + hk // 2, wk // 2:W + wk // + 2].flatten(1) + mask_inf = paddle.full([H * W, H * W], '-inf', dtype='float32') + mask = paddle.where(mask_paddle < 1, mask_paddle, mask_inf) + self.mask = mask.unsqueeze([0, 1]) + self.mixer = mixer + + def forward(self, x): + if self.HW is not None: + N = self.N + C = self.C + else: + _, N, C = x.shape + qkv = self.qkv(x).reshape((0, N, 3, self.num_heads, C // + self.num_heads)).transpose((2, 0, 3, 1, 4)) + q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] + + attn = (q.matmul(k.transpose((0, 1, 3, 2)))) + if self.mixer == 'Local': + attn += self.mask + attn = nn.functional.softmax(attn, axis=-1) + attn = self.attn_drop(attn) + + x = (attn.matmul(v)).transpose((0, 2, 1, 3)).reshape((0, N, C)) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Layer): + def __init__(self, + dim, + num_heads, + mixer='Global', + local_mixer=[7, 11], + HW=None, + mlp_ratio=4., + qkv_bias=False, + qk_scale=None, + drop=0., + attn_drop=0., + drop_path=0., + act_layer=nn.GELU, + norm_layer='nn.LayerNorm', + epsilon=1e-6, + prenorm=True): + super().__init__() + if isinstance(norm_layer, str): + self.norm1 = eval(norm_layer)(dim, epsilon=epsilon) + else: + self.norm1 = norm_layer(dim) + if mixer == 'Global' or mixer == 'Local': + self.mixer = Attention( + dim, + num_heads=num_heads, + mixer=mixer, + HW=HW, + local_k=local_mixer, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop) + elif mixer == 'Conv': + self.mixer = ConvMixer( + dim, num_heads=num_heads, HW=HW, local_k=local_mixer) + else: + raise TypeError("The mixer must be one of [Global, Local, Conv]") + + self.drop_path = DropPath(drop_path) if drop_path > 0. else Identity() + if isinstance(norm_layer, str): + self.norm2 = eval(norm_layer)(dim, epsilon=epsilon) + else: + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp_ratio = mlp_ratio + self.mlp = Mlp(in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop) + self.prenorm = prenorm + + def forward(self, x): + if self.prenorm: + x = self.norm1(x + self.drop_path(self.mixer(x))) + x = self.norm2(x + self.drop_path(self.mlp(x))) + else: + x = x + self.drop_path(self.mixer(self.norm1(x))) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class PatchEmbed(nn.Layer): + """ Image to Patch Embedding + """ + + def __init__(self, + img_size=[32, 100], + in_channels=3, + embed_dim=768, + sub_num=2, + patch_size=[4, 4], + mode='pope'): + super().__init__() + num_patches = (img_size[1] // (2 ** sub_num)) * \ + (img_size[0] // (2 ** sub_num)) + self.img_size = img_size + self.num_patches = num_patches + self.embed_dim = embed_dim + self.norm = None + if mode == 'pope': + if sub_num == 2: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=None), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=None)) + if sub_num == 3: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 4, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=None), + ConvBNLayer( + in_channels=embed_dim // 4, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=None), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=None)) + elif mode == 'linear': + self.proj = nn.Conv2D( + 1, embed_dim, kernel_size=patch_size, stride=patch_size) + self.num_patches = img_size[0] // patch_size[0] * img_size[ + 1] // patch_size[1] + + def forward(self, x): + B, C, H, W = x.shape + assert H == self.img_size[0] and W == self.img_size[1], \ + f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).transpose((0, 2, 1)) + return x + + +class SubSample(nn.Layer): + def __init__(self, + in_channels, + out_channels, + types='Pool', + stride=[2, 1], + sub_norm='nn.LayerNorm', + act=None): + super().__init__() + self.types = types + if types == 'Pool': + self.avgpool = nn.AvgPool2D( + kernel_size=[3, 5], stride=stride, padding=[1, 2]) + self.maxpool = nn.MaxPool2D( + kernel_size=[3, 5], stride=stride, padding=[1, 2]) + self.proj = nn.Linear(in_channels, out_channels) + else: + self.conv = nn.Conv2D( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + weight_attr=ParamAttr(initializer=KaimingNormal())) + self.norm = eval(sub_norm)(out_channels) + if act is not None: + self.act = act() + else: + self.act = None + + def forward(self, x): + + if self.types == 'Pool': + x1 = self.avgpool(x) + x2 = self.maxpool(x) + x = (x1 + x2) * 0.5 + out = self.proj(x.flatten(2).transpose((0, 2, 1))) + else: + x = self.conv(x) + out = x.flatten(2).transpose((0, 2, 1)) + out = self.norm(out) + if self.act is not None: + out = self.act(out) + + return out + + +class SVTRNet(nn.Layer): + def __init__( + self, + img_size=[32, 100], + in_channels=3, + embed_dim=[64, 128, 256], + depth=[3, 6, 3], + num_heads=[2, 4, 8], + mixer=['Local'] * 6 + ['Global'] * + 6, # Local atten, Global atten, Conv + local_mixer=[[7, 11], [7, 11], [7, 11]], + patch_merging='Conv', # Conv, Pool, None + mlp_ratio=4, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + last_drop=0.1, + attn_drop_rate=0., + drop_path_rate=0.1, + norm_layer='nn.LayerNorm', + sub_norm='nn.LayerNorm', + epsilon=1e-6, + out_channels=192, + out_char_num=25, + block_unit='Block', + act='nn.GELU', + last_stage=True, + sub_num=2, + prenorm=True, + use_lenhead=False, + **kwargs): + super().__init__() + self.img_size = img_size + self.embed_dim = embed_dim + self.out_channels = out_channels + self.prenorm = prenorm + patch_merging = None if patch_merging != 'Conv' and patch_merging != 'Pool' else patch_merging + self.patch_embed = PatchEmbed( + img_size=img_size, + in_channels=in_channels, + embed_dim=embed_dim[0], + sub_num=sub_num) + num_patches = self.patch_embed.num_patches + self.HW = [img_size[0] // (2**sub_num), img_size[1] // (2**sub_num)] + self.pos_embed = self.create_parameter( + shape=[1, num_patches, embed_dim[0]], default_initializer=zeros_) + self.add_parameter("pos_embed", self.pos_embed) + self.pos_drop = nn.Dropout(p=drop_rate) + Block_unit = eval(block_unit) + + dpr = np.linspace(0, drop_path_rate, sum(depth)) + self.blocks1 = nn.LayerList([ + Block_unit( + dim=embed_dim[0], + num_heads=num_heads[0], + mixer=mixer[0:depth[0]][i], + HW=self.HW, + local_mixer=local_mixer[0], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[0:depth[0]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[0]) + ]) + if patch_merging is not None: + self.sub_sample1 = SubSample( + embed_dim[0], + embed_dim[1], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 2, self.HW[1]] + else: + HW = self.HW + self.patch_merging = patch_merging + self.blocks2 = nn.LayerList([ + Block_unit( + dim=embed_dim[1], + num_heads=num_heads[1], + mixer=mixer[depth[0]:depth[0] + depth[1]][i], + HW=HW, + local_mixer=local_mixer[1], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0]:depth[0] + depth[1]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[1]) + ]) + if patch_merging is not None: + self.sub_sample2 = SubSample( + embed_dim[1], + embed_dim[2], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 4, self.HW[1]] + else: + HW = self.HW + self.blocks3 = nn.LayerList([ + Block_unit( + dim=embed_dim[2], + num_heads=num_heads[2], + mixer=mixer[depth[0] + depth[1]:][i], + HW=HW, + local_mixer=local_mixer[2], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0] + depth[1]:][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[2]) + ]) + self.last_stage = last_stage + if last_stage: + self.avg_pool = nn.AdaptiveAvgPool2D([1, out_char_num]) + self.last_conv = nn.Conv2D( + in_channels=embed_dim[2], + out_channels=self.out_channels, + kernel_size=1, + stride=1, + padding=0, + bias_attr=False) + self.hardswish = nn.Hardswish() + self.dropout = nn.Dropout(p=last_drop, mode="downscale_in_infer") + if not prenorm: + self.norm = eval(norm_layer)(embed_dim[-1], epsilon=epsilon) + self.use_lenhead = use_lenhead + if use_lenhead: + self.len_conv = nn.Linear(embed_dim[2], self.out_channels) + self.hardswish_len = nn.Hardswish() + self.dropout_len = nn.Dropout( + p=last_drop, mode="downscale_in_infer") + + trunc_normal_(self.pos_embed) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight) + if isinstance(m, nn.Linear) and m.bias is not None: + zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + zeros_(m.bias) + ones_(m.weight) + + def forward_features(self, x): + x = self.patch_embed(x) + x = x + self.pos_embed + x = self.pos_drop(x) + for blk in self.blocks1: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample1( + x.transpose([0, 2, 1]).reshape( + [0, self.embed_dim[0], self.HW[0], self.HW[1]])) + for blk in self.blocks2: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample2( + x.transpose([0, 2, 1]).reshape( + [0, self.embed_dim[1], self.HW[0] // 2, self.HW[1]])) + for blk in self.blocks3: + x = blk(x) + if not self.prenorm: + x = self.norm(x) + return x + + def forward(self, x): + x = self.forward_features(x) + if self.use_lenhead: + len_x = self.len_conv(x.mean(1)) + len_x = self.dropout_len(self.hardswish_len(len_x)) + if self.last_stage: + if self.patch_merging is not None: + h = self.HW[0] // 4 + else: + h = self.HW[0] + x = self.avg_pool( + x.transpose([0, 2, 1]).reshape( + [0, self.embed_dim[2], h, self.HW[1]])) + x = self.last_conv(x) + x = self.hardswish(x) + x = self.dropout(x) + if self.use_lenhead: + return x, len_x + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_vitstr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_vitstr.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d7d5148a1120e6f97a321b4135c6780c0c5db2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/rec_vitstr.py @@ -0,0 +1,120 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/roatienza/deep-text-recognition-benchmark/blob/master/modules/vitstr.py +""" + +import numpy as np +import paddle +import paddle.nn as nn +from ppocr.modeling.backbones.rec_svtrnet import Block, PatchEmbed, zeros_, trunc_normal_, ones_ + +scale_dim_heads = {'tiny': [192, 3], 'small': [384, 6], 'base': [768, 12]} + + +class ViTSTR(nn.Layer): + def __init__(self, + img_size=[224, 224], + in_channels=1, + scale='tiny', + seqlen=27, + patch_size=[16, 16], + embed_dim=None, + depth=12, + num_heads=None, + mlp_ratio=4, + qkv_bias=True, + qk_scale=None, + drop_path_rate=0., + drop_rate=0., + attn_drop_rate=0., + norm_layer='nn.LayerNorm', + act_layer='nn.GELU', + epsilon=1e-6, + out_channels=None, + **kwargs): + super().__init__() + self.seqlen = seqlen + embed_dim = embed_dim if embed_dim is not None else scale_dim_heads[ + scale][0] + num_heads = num_heads if num_heads is not None else scale_dim_heads[ + scale][1] + out_channels = out_channels if out_channels is not None else embed_dim + self.patch_embed = PatchEmbed( + img_size=img_size, + in_channels=in_channels, + embed_dim=embed_dim, + patch_size=patch_size, + mode='linear') + num_patches = self.patch_embed.num_patches + + self.pos_embed = self.create_parameter( + shape=[1, num_patches + 1, embed_dim], default_initializer=zeros_) + self.add_parameter("pos_embed", self.pos_embed) + self.cls_token = self.create_parameter( + shape=[1, 1, embed_dim], default_initializer=zeros_) + self.add_parameter("cls_token", self.cls_token) + + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = np.linspace(0, drop_path_rate, depth) + self.blocks = nn.LayerList([ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=eval(act_layer), + epsilon=epsilon, + prenorm=False) for i in range(depth) + ]) + self.norm = eval(norm_layer)(embed_dim, epsilon=epsilon) + + self.out_channels = out_channels + + trunc_normal_(self.pos_embed) + trunc_normal_(self.cls_token) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight) + if isinstance(m, nn.Linear) and m.bias is not None: + zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + zeros_(m.bias) + ones_(m.weight) + + def forward_features(self, x): + B = x.shape[0] + x = self.patch_embed(x) + cls_tokens = paddle.tile(self.cls_token, repeat_times=[B, 1, 1]) + x = paddle.concat((cls_tokens, x), axis=1) + x = x + self.pos_embed + x = self.pos_drop(x) + for blk in self.blocks: + x = blk(x) + x = self.norm(x) + return x + + def forward(self, x): + x = self.forward_features(x) + x = x[:, :self.seqlen] + return x.transpose([0, 2, 1]).unsqueeze(2) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/table_master_resnet.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/table_master_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..dacf5ed26e5374b3c93c1a983be1d7b5b4c471fc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/table_master_resnet.py @@ -0,0 +1,369 @@ +# Copyright (c) 2022 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. +""" +This code is refer from: +https://github.com/JiaquanYe/TableMASTER-mmocr/blob/master/mmocr/models/textrecog/backbones/table_resnet_extra.py +""" + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + + +class BasicBlock(nn.Layer): + expansion = 1 + + def __init__(self, + inplanes, + planes, + stride=1, + downsample=None, + gcb_config=None): + super(BasicBlock, self).__init__() + self.conv1 = nn.Conv2D( + inplanes, + planes, + kernel_size=3, + stride=stride, + padding=1, + bias_attr=False) + self.bn1 = nn.BatchNorm2D(planes, momentum=0.9) + self.relu = nn.ReLU() + self.conv2 = nn.Conv2D( + planes, planes, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn2 = nn.BatchNorm2D(planes, momentum=0.9) + self.downsample = downsample + self.stride = stride + self.gcb_config = gcb_config + + if self.gcb_config is not None: + gcb_ratio = gcb_config['ratio'] + gcb_headers = gcb_config['headers'] + att_scale = gcb_config['att_scale'] + fusion_type = gcb_config['fusion_type'] + self.context_block = MultiAspectGCAttention( + inplanes=planes, + ratio=gcb_ratio, + headers=gcb_headers, + att_scale=att_scale, + fusion_type=fusion_type) + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.gcb_config is not None: + out = self.context_block(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +def get_gcb_config(gcb_config, layer): + if gcb_config is None or not gcb_config['layers'][layer]: + return None + else: + return gcb_config + + +class TableResNetExtra(nn.Layer): + def __init__(self, layers, in_channels=3, gcb_config=None): + assert len(layers) >= 4 + + super(TableResNetExtra, self).__init__() + self.inplanes = 128 + self.conv1 = nn.Conv2D( + in_channels, + 64, + kernel_size=3, + stride=1, + padding=1, + bias_attr=False) + self.bn1 = nn.BatchNorm2D(64) + self.relu1 = nn.ReLU() + + self.conv2 = nn.Conv2D( + 64, 128, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn2 = nn.BatchNorm2D(128) + self.relu2 = nn.ReLU() + + self.maxpool1 = nn.MaxPool2D(kernel_size=2, stride=2) + + self.layer1 = self._make_layer( + BasicBlock, + 256, + layers[0], + stride=1, + gcb_config=get_gcb_config(gcb_config, 0)) + + self.conv3 = nn.Conv2D( + 256, 256, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn3 = nn.BatchNorm2D(256) + self.relu3 = nn.ReLU() + + self.maxpool2 = nn.MaxPool2D(kernel_size=2, stride=2) + + self.layer2 = self._make_layer( + BasicBlock, + 256, + layers[1], + stride=1, + gcb_config=get_gcb_config(gcb_config, 1)) + + self.conv4 = nn.Conv2D( + 256, 256, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn4 = nn.BatchNorm2D(256) + self.relu4 = nn.ReLU() + + self.maxpool3 = nn.MaxPool2D(kernel_size=2, stride=2) + + self.layer3 = self._make_layer( + BasicBlock, + 512, + layers[2], + stride=1, + gcb_config=get_gcb_config(gcb_config, 2)) + + self.conv5 = nn.Conv2D( + 512, 512, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn5 = nn.BatchNorm2D(512) + self.relu5 = nn.ReLU() + + self.layer4 = self._make_layer( + BasicBlock, + 512, + layers[3], + stride=1, + gcb_config=get_gcb_config(gcb_config, 3)) + + self.conv6 = nn.Conv2D( + 512, 512, kernel_size=3, stride=1, padding=1, bias_attr=False) + self.bn6 = nn.BatchNorm2D(512) + self.relu6 = nn.ReLU() + + self.out_channels = [256, 256, 512] + + def _make_layer(self, block, planes, blocks, stride=1, gcb_config=None): + downsample = None + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + nn.Conv2D( + self.inplanes, + planes * block.expansion, + kernel_size=1, + stride=stride, + bias_attr=False), + nn.BatchNorm2D(planes * block.expansion), ) + + layers = [] + layers.append( + block( + self.inplanes, + planes, + stride, + downsample, + gcb_config=gcb_config)) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append(block(self.inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + f = [] + x = self.conv1(x) + + x = self.bn1(x) + x = self.relu1(x) + + x = self.conv2(x) + x = self.bn2(x) + x = self.relu2(x) + + x = self.maxpool1(x) + x = self.layer1(x) + + x = self.conv3(x) + x = self.bn3(x) + x = self.relu3(x) + f.append(x) + + x = self.maxpool2(x) + x = self.layer2(x) + + x = self.conv4(x) + x = self.bn4(x) + x = self.relu4(x) + f.append(x) + + x = self.maxpool3(x) + + x = self.layer3(x) + x = self.conv5(x) + x = self.bn5(x) + x = self.relu5(x) + + x = self.layer4(x) + x = self.conv6(x) + x = self.bn6(x) + x = self.relu6(x) + f.append(x) + return f + + +class MultiAspectGCAttention(nn.Layer): + def __init__(self, + inplanes, + ratio, + headers, + pooling_type='att', + att_scale=False, + fusion_type='channel_add'): + super(MultiAspectGCAttention, self).__init__() + assert pooling_type in ['avg', 'att'] + + assert fusion_type in ['channel_add', 'channel_mul', 'channel_concat'] + assert inplanes % headers == 0 and inplanes >= 8 # inplanes must be divided by headers evenly + + self.headers = headers + self.inplanes = inplanes + self.ratio = ratio + self.planes = int(inplanes * ratio) + self.pooling_type = pooling_type + self.fusion_type = fusion_type + self.att_scale = False + + self.single_header_inplanes = int(inplanes / headers) + + if pooling_type == 'att': + self.conv_mask = nn.Conv2D( + self.single_header_inplanes, 1, kernel_size=1) + self.softmax = nn.Softmax(axis=2) + else: + self.avg_pool = nn.AdaptiveAvgPool2D(1) + + if fusion_type == 'channel_add': + self.channel_add_conv = nn.Sequential( + nn.Conv2D( + self.inplanes, self.planes, kernel_size=1), + nn.LayerNorm([self.planes, 1, 1]), + nn.ReLU(), + nn.Conv2D( + self.planes, self.inplanes, kernel_size=1)) + elif fusion_type == 'channel_concat': + self.channel_concat_conv = nn.Sequential( + nn.Conv2D( + self.inplanes, self.planes, kernel_size=1), + nn.LayerNorm([self.planes, 1, 1]), + nn.ReLU(), + nn.Conv2D( + self.planes, self.inplanes, kernel_size=1)) + # for concat + self.cat_conv = nn.Conv2D( + 2 * self.inplanes, self.inplanes, kernel_size=1) + elif fusion_type == 'channel_mul': + self.channel_mul_conv = nn.Sequential( + nn.Conv2D( + self.inplanes, self.planes, kernel_size=1), + nn.LayerNorm([self.planes, 1, 1]), + nn.ReLU(), + nn.Conv2D( + self.planes, self.inplanes, kernel_size=1)) + + def spatial_pool(self, x): + batch, channel, height, width = x.shape + if self.pooling_type == 'att': + # [N*headers, C', H , W] C = headers * C' + x = x.reshape([ + batch * self.headers, self.single_header_inplanes, height, width + ]) + input_x = x + + # [N*headers, C', H * W] C = headers * C' + # input_x = input_x.view(batch, channel, height * width) + input_x = input_x.reshape([ + batch * self.headers, self.single_header_inplanes, + height * width + ]) + + # [N*headers, 1, C', H * W] + input_x = input_x.unsqueeze(1) + # [N*headers, 1, H, W] + context_mask = self.conv_mask(x) + # [N*headers, 1, H * W] + context_mask = context_mask.reshape( + [batch * self.headers, 1, height * width]) + + # scale variance + if self.att_scale and self.headers > 1: + context_mask = context_mask / paddle.sqrt( + self.single_header_inplanes) + + # [N*headers, 1, H * W] + context_mask = self.softmax(context_mask) + + # [N*headers, 1, H * W, 1] + context_mask = context_mask.unsqueeze(-1) + # [N*headers, 1, C', 1] = [N*headers, 1, C', H * W] * [N*headers, 1, H * W, 1] + context = paddle.matmul(input_x, context_mask) + + # [N, headers * C', 1, 1] + context = context.reshape( + [batch, self.headers * self.single_header_inplanes, 1, 1]) + else: + # [N, C, 1, 1] + context = self.avg_pool(x) + + return context + + def forward(self, x): + # [N, C, 1, 1] + context = self.spatial_pool(x) + + out = x + + if self.fusion_type == 'channel_mul': + # [N, C, 1, 1] + channel_mul_term = F.sigmoid(self.channel_mul_conv(context)) + out = out * channel_mul_term + elif self.fusion_type == 'channel_add': + # [N, C, 1, 1] + channel_add_term = self.channel_add_conv(context) + out = out + channel_add_term + else: + # [N, C, 1, 1] + channel_concat_term = self.channel_concat_conv(context) + + # use concat + _, C1, _, _ = channel_concat_term.shape + N, C2, H, W = out.shape + + out = paddle.concat( + [out, channel_concat_term.expand([-1, -1, H, W])], axis=1) + out = self.cat_conv(out) + out = F.layer_norm(out, [self.inplanes, H, W]) + out = F.relu(out) + + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/vqa_layoutlm.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/vqa_layoutlm.py new file mode 100644 index 0000000000000000000000000000000000000000..8e10ed7b48e9aff344b71e5a04970d1a5dab8a71 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/backbones/vqa_layoutlm.py @@ -0,0 +1,234 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +from paddle import nn + +from paddlenlp.transformers import LayoutXLMModel, LayoutXLMForTokenClassification, LayoutXLMForRelationExtraction +from paddlenlp.transformers import LayoutLMModel, LayoutLMForTokenClassification +from paddlenlp.transformers import LayoutLMv2Model, LayoutLMv2ForTokenClassification, LayoutLMv2ForRelationExtraction +from paddlenlp.transformers import AutoModel + +__all__ = ["LayoutXLMForSer", "LayoutLMForSer"] + +pretrained_model_dict = { + LayoutXLMModel: { + "base": "layoutxlm-base-uncased", + "vi": "vi-layoutxlm-base-uncased", + }, + LayoutLMModel: { + "base": "layoutlm-base-uncased", + }, + LayoutLMv2Model: { + "base": "layoutlmv2-base-uncased", + "vi": "vi-layoutlmv2-base-uncased", + }, +} + + +class NLPBaseModel(nn.Layer): + def __init__(self, + base_model_class, + model_class, + mode="base", + type="ser", + pretrained=True, + checkpoints=None, + **kwargs): + super(NLPBaseModel, self).__init__() + if checkpoints is not None: # load the trained model + self.model = model_class.from_pretrained(checkpoints) + else: # load the pretrained-model + pretrained_model_name = pretrained_model_dict[base_model_class][ + mode] + if pretrained is True: + base_model = base_model_class.from_pretrained( + pretrained_model_name) + else: + base_model = base_model_class.from_pretrained(pretrained) + if type == "ser": + self.model = model_class( + base_model, num_classes=kwargs["num_classes"], dropout=None) + else: + self.model = model_class(base_model, dropout=None) + self.out_channels = 1 + self.use_visual_backbone = True + + +class LayoutLMForSer(NLPBaseModel): + def __init__(self, + num_classes, + pretrained=True, + checkpoints=None, + mode="base", + **kwargs): + super(LayoutLMForSer, self).__init__( + LayoutLMModel, + LayoutLMForTokenClassification, + mode, + "ser", + pretrained, + checkpoints, + num_classes=num_classes, ) + self.use_visual_backbone = False + + def forward(self, x): + x = self.model( + input_ids=x[0], + bbox=x[1], + attention_mask=x[2], + token_type_ids=x[3], + position_ids=None, + output_hidden_states=False) + return x + + +class LayoutLMv2ForSer(NLPBaseModel): + def __init__(self, + num_classes, + pretrained=True, + checkpoints=None, + mode="base", + **kwargs): + super(LayoutLMv2ForSer, self).__init__( + LayoutLMv2Model, + LayoutLMv2ForTokenClassification, + mode, + "ser", + pretrained, + checkpoints, + num_classes=num_classes) + if hasattr(self.model.layoutlmv2, "use_visual_backbone" + ) and self.model.layoutlmv2.use_visual_backbone is False: + self.use_visual_backbone = False + + def forward(self, x): + if self.use_visual_backbone is True: + image = x[4] + else: + image = None + x = self.model( + input_ids=x[0], + bbox=x[1], + attention_mask=x[2], + token_type_ids=x[3], + image=image, + position_ids=None, + head_mask=None, + labels=None) + if self.training: + res = {"backbone_out": x[0]} + res.update(x[1]) + return res + else: + return x + + +class LayoutXLMForSer(NLPBaseModel): + def __init__(self, + num_classes, + pretrained=True, + checkpoints=None, + mode="base", + **kwargs): + super(LayoutXLMForSer, self).__init__( + LayoutXLMModel, + LayoutXLMForTokenClassification, + mode, + "ser", + pretrained, + checkpoints, + num_classes=num_classes) + if hasattr(self.model.layoutxlm, "use_visual_backbone" + ) and self.model.layoutxlm.use_visual_backbone is False: + self.use_visual_backbone = False + + def forward(self, x): + if self.use_visual_backbone is True: + image = x[4] + else: + image = None + x = self.model( + input_ids=x[0], + bbox=x[1], + attention_mask=x[2], + token_type_ids=x[3], + image=image, + position_ids=None, + head_mask=None, + labels=None) + if self.training: + res = {"backbone_out": x[0]} + res.update(x[1]) + return res + else: + return x + + +class LayoutLMv2ForRe(NLPBaseModel): + def __init__(self, pretrained=True, checkpoints=None, mode="base", + **kwargs): + super(LayoutLMv2ForRe, self).__init__( + LayoutLMv2Model, LayoutLMv2ForRelationExtraction, mode, "re", + pretrained, checkpoints) + if hasattr(self.model.layoutlmv2, "use_visual_backbone" + ) and self.model.layoutlmv2.use_visual_backbone is False: + self.use_visual_backbone = False + + def forward(self, x): + x = self.model( + input_ids=x[0], + bbox=x[1], + attention_mask=x[2], + token_type_ids=x[3], + image=x[4], + position_ids=None, + head_mask=None, + labels=None, + entities=x[5], + relations=x[6]) + return x + + +class LayoutXLMForRe(NLPBaseModel): + def __init__(self, pretrained=True, checkpoints=None, mode="base", + **kwargs): + super(LayoutXLMForRe, self).__init__( + LayoutXLMModel, LayoutXLMForRelationExtraction, mode, "re", + pretrained, checkpoints) + if hasattr(self.model.layoutxlm, "use_visual_backbone" + ) and self.model.layoutxlm.use_visual_backbone is False: + self.use_visual_backbone = False + + def forward(self, x): + if self.use_visual_backbone is True: + image = x[4] + else: + image = None + x = self.model( + input_ids=x[0], + bbox=x[1], + attention_mask=x[2], + token_type_ids=x[3], + image=image, + position_ids=None, + head_mask=None, + labels=None, + entities=x[5], + relations=x[6]) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..0feda6c6e062fa314d97b8949d8545ed3305c22e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/__init__.py @@ -0,0 +1,64 @@ +# 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. + +__all__ = ['build_head'] + + +def build_head(config): + # det head + from .det_db_head import DBHead + from .det_east_head import EASTHead + from .det_sast_head import SASTHead + from .det_pse_head import PSEHead + from .det_fce_head import FCEHead + from .e2e_pg_head import PGHead + + # rec head + from .rec_ctc_head import CTCHead + from .rec_att_head import AttentionHead + from .rec_srn_head import SRNHead + from .rec_nrtr_head import Transformer + from .rec_sar_head import SARHead + from .rec_aster_head import AsterHead + from .rec_pren_head import PRENHead + from .rec_multi_head import MultiHead + from .rec_spin_att_head import SPINAttentionHead + from .rec_abinet_head import ABINetHead + from .rec_robustscanner_head import RobustScannerHead + from .rec_visionlan_head import VLHead + + # cls head + from .cls_head import ClsHead + + #kie head + from .kie_sdmgr_head import SDMGRHead + + from .table_att_head import TableAttentionHead, SLAHead + from .table_master_head import TableMasterHead + + support_dict = [ + 'DBHead', 'PSEHead', 'FCEHead', 'EASTHead', 'SASTHead', 'CTCHead', + 'ClsHead', 'AttentionHead', 'SRNHead', 'PGHead', 'Transformer', + 'TableAttentionHead', 'SARHead', 'AsterHead', 'SDMGRHead', 'PRENHead', + 'MultiHead', 'ABINetHead', 'TableMasterHead', 'SPINAttentionHead', + 'VLHead', 'SLAHead', 'RobustScannerHead' + ] + + #table head + + module_name = config.pop('name') + assert module_name in support_dict, Exception('head only support {}'.format( + support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/cls_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/cls_head.py new file mode 100644 index 0000000000000000000000000000000000000000..91bfa615a8206b5ec0f993429ccae990a05d0b9b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/cls_head.py @@ -0,0 +1,52 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +import paddle.nn.functional as F + + +class ClsHead(nn.Layer): + """ + Class orientation + + Args: + + params(dict): super parameters for build Class network + """ + + def __init__(self, in_channels, class_dim, **kwargs): + super(ClsHead, self).__init__() + self.pool = nn.AdaptiveAvgPool2D(1) + stdv = 1.0 / math.sqrt(in_channels * 1.0) + self.fc = nn.Linear( + in_channels, + class_dim, + weight_attr=ParamAttr( + name="fc_0.w_0", + initializer=nn.initializer.Uniform(-stdv, stdv)), + bias_attr=ParamAttr(name="fc_0.b_0"), ) + + def forward(self, x, targets=None): + x = self.pool(x) + x = paddle.reshape(x, shape=[x.shape[0], x.shape[1]]) + x = self.fc(x) + if not self.training: + x = F.softmax(x, axis=1) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_db_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_db_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a686ae5ab0662ad31ddfd339bd1999c45c370cf0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_db_head.py @@ -0,0 +1,118 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +def get_bias_attr(k): + stdv = 1.0 / math.sqrt(k * 1.0) + initializer = paddle.nn.initializer.Uniform(-stdv, stdv) + bias_attr = ParamAttr(initializer=initializer) + return bias_attr + + +class Head(nn.Layer): + def __init__(self, in_channels, name_list, kernel_list=[3, 2, 2], **kwargs): + super(Head, self).__init__() + + self.conv1 = nn.Conv2D( + in_channels=in_channels, + out_channels=in_channels // 4, + kernel_size=kernel_list[0], + padding=int(kernel_list[0] // 2), + weight_attr=ParamAttr(), + bias_attr=False) + self.conv_bn1 = nn.BatchNorm( + num_channels=in_channels // 4, + param_attr=ParamAttr( + initializer=paddle.nn.initializer.Constant(value=1.0)), + bias_attr=ParamAttr( + initializer=paddle.nn.initializer.Constant(value=1e-4)), + act='relu') + self.conv2 = nn.Conv2DTranspose( + in_channels=in_channels // 4, + out_channels=in_channels // 4, + kernel_size=kernel_list[1], + stride=2, + weight_attr=ParamAttr( + initializer=paddle.nn.initializer.KaimingUniform()), + bias_attr=get_bias_attr(in_channels // 4)) + self.conv_bn2 = nn.BatchNorm( + num_channels=in_channels // 4, + param_attr=ParamAttr( + initializer=paddle.nn.initializer.Constant(value=1.0)), + bias_attr=ParamAttr( + initializer=paddle.nn.initializer.Constant(value=1e-4)), + act="relu") + self.conv3 = nn.Conv2DTranspose( + in_channels=in_channels // 4, + out_channels=1, + kernel_size=kernel_list[2], + stride=2, + weight_attr=ParamAttr( + initializer=paddle.nn.initializer.KaimingUniform()), + bias_attr=get_bias_attr(in_channels // 4), ) + + def forward(self, x): + x = self.conv1(x) + x = self.conv_bn1(x) + x = self.conv2(x) + x = self.conv_bn2(x) + x = self.conv3(x) + x = F.sigmoid(x) + return x + + +class DBHead(nn.Layer): + """ + Differentiable Binarization (DB) for text detection: + see https://arxiv.org/abs/1911.08947 + args: + params(dict): super parameters for build DB network + """ + + def __init__(self, in_channels, k=50, **kwargs): + super(DBHead, self).__init__() + self.k = k + binarize_name_list = [ + 'conv2d_56', 'batch_norm_47', 'conv2d_transpose_0', 'batch_norm_48', + 'conv2d_transpose_1', 'binarize' + ] + thresh_name_list = [ + 'conv2d_57', 'batch_norm_49', 'conv2d_transpose_2', 'batch_norm_50', + 'conv2d_transpose_3', 'thresh' + ] + self.binarize = Head(in_channels, binarize_name_list, **kwargs) + self.thresh = Head(in_channels, thresh_name_list, **kwargs) + + def step_function(self, x, y): + return paddle.reciprocal(1 + paddle.exp(-self.k * (x - y))) + + def forward(self, x, targets=None): + shrink_maps = self.binarize(x) + if not self.training: + return {'maps': shrink_maps} + + threshold_maps = self.thresh(x) + binary_maps = self.step_function(shrink_maps, threshold_maps) + y = paddle.concat([shrink_maps, threshold_maps, binary_maps], axis=1) + return {'maps': y} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_east_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_east_head.py new file mode 100644 index 0000000000000000000000000000000000000000..004eb5d7bb9a134d1a84f980e37e5336dc43a29a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_east_head.py @@ -0,0 +1,121 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups=1, + if_act=True, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class EASTHead(nn.Layer): + """ + """ + def __init__(self, in_channels, model_name, **kwargs): + super(EASTHead, self).__init__() + self.model_name = model_name + if self.model_name == "large": + num_outputs = [128, 64, 1, 8] + else: + num_outputs = [64, 32, 1, 8] + + self.det_conv1 = ConvBNLayer( + in_channels=in_channels, + out_channels=num_outputs[0], + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="det_head1") + self.det_conv2 = ConvBNLayer( + in_channels=num_outputs[0], + out_channels=num_outputs[1], + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="det_head2") + self.score_conv = ConvBNLayer( + in_channels=num_outputs[1], + out_channels=num_outputs[2], + kernel_size=1, + stride=1, + padding=0, + if_act=False, + act=None, + name="f_score") + self.geo_conv = ConvBNLayer( + in_channels=num_outputs[1], + out_channels=num_outputs[3], + kernel_size=1, + stride=1, + padding=0, + if_act=False, + act=None, + name="f_geo") + + def forward(self, x, targets=None): + f_det = self.det_conv1(x) + f_det = self.det_conv2(f_det) + f_score = self.score_conv(f_det) + f_score = F.sigmoid(f_score) + f_geo = self.geo_conv(f_det) + f_geo = (F.sigmoid(f_geo) - 0.5) * 2 * 800 + + pred = {'f_score': f_score, 'f_geo': f_geo} + return pred diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_fce_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_fce_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9503989f58f09a5137f1002f7b90d0942a97d1d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_fce_head.py @@ -0,0 +1,99 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textdet/dense_heads/fce_head.py +""" + +from paddle import nn +from paddle import ParamAttr +import paddle.nn.functional as F +from paddle.nn.initializer import Normal +import paddle +from functools import partial + + +def multi_apply(func, *args, **kwargs): + pfunc = partial(func, **kwargs) if kwargs else func + map_results = map(pfunc, *args) + return tuple(map(list, zip(*map_results))) + + +class FCEHead(nn.Layer): + """The class for implementing FCENet head. + FCENet(CVPR2021): Fourier Contour Embedding for Arbitrary-shaped Text + Detection. + + [https://arxiv.org/abs/2104.10442] + + Args: + in_channels (int): The number of input channels. + scales (list[int]) : The scale of each layer. + fourier_degree (int) : The maximum Fourier transform degree k. + """ + + def __init__(self, in_channels, fourier_degree=5): + super().__init__() + assert isinstance(in_channels, int) + + self.downsample_ratio = 1.0 + self.in_channels = in_channels + self.fourier_degree = fourier_degree + self.out_channels_cls = 4 + self.out_channels_reg = (2 * self.fourier_degree + 1) * 2 + + self.out_conv_cls = nn.Conv2D( + in_channels=self.in_channels, + out_channels=self.out_channels_cls, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr( + name='cls_weights', + initializer=Normal( + mean=0., std=0.01)), + bias_attr=True) + self.out_conv_reg = nn.Conv2D( + in_channels=self.in_channels, + out_channels=self.out_channels_reg, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr( + name='reg_weights', + initializer=Normal( + mean=0., std=0.01)), + bias_attr=True) + + def forward(self, feats, targets=None): + cls_res, reg_res = multi_apply(self.forward_single, feats) + level_num = len(cls_res) + outs = {} + if not self.training: + for i in range(level_num): + tr_pred = F.softmax(cls_res[i][:, 0:2, :, :], axis=1) + tcl_pred = F.softmax(cls_res[i][:, 2:, :, :], axis=1) + outs['level_{}'.format(i)] = paddle.concat( + [tr_pred, tcl_pred, reg_res[i]], axis=1) + else: + preds = [[cls_res[i], reg_res[i]] for i in range(level_num)] + outs['levels'] = preds + return outs + + def forward_single(self, x): + cls_predict = self.out_conv_cls(x) + reg_predict = self.out_conv_reg(x) + return cls_predict, reg_predict diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_pse_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_pse_head.py new file mode 100644 index 0000000000000000000000000000000000000000..32a5b48e190b7566411b19841b6aa14455b5d41d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_pse_head.py @@ -0,0 +1,37 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/head/psenet_head.py +""" + +from paddle import nn + + +class PSEHead(nn.Layer): + def __init__(self, in_channels, hidden_dim=256, out_channels=7, **kwargs): + super(PSEHead, self).__init__() + self.conv1 = nn.Conv2D( + in_channels, hidden_dim, kernel_size=3, stride=1, padding=1) + self.bn1 = nn.BatchNorm2D(hidden_dim) + self.relu1 = nn.ReLU() + + self.conv2 = nn.Conv2D( + hidden_dim, out_channels, kernel_size=1, stride=1, padding=0) + + def forward(self, x, **kwargs): + out = self.conv1(x) + out = self.relu1(self.bn1(out)) + out = self.conv2(out) + return {'maps': out} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_sast_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_sast_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7a88a2db6c29c8c4fa1ee94d27bd0701cdbc90f8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/det_sast_head.py @@ -0,0 +1,128 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + groups=1, + if_act=True, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class SAST_Header1(nn.Layer): + def __init__(self, in_channels, **kwargs): + super(SAST_Header1, self).__init__() + out_channels = [64, 64, 128] + self.score_conv = nn.Sequential( + ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_score1'), + ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_score2'), + ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_score3'), + ConvBNLayer(out_channels[2], 1, 3, 1, act=None, name='f_score4') + ) + self.border_conv = nn.Sequential( + ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_border1'), + ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_border2'), + ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_border3'), + ConvBNLayer(out_channels[2], 4, 3, 1, act=None, name='f_border4') + ) + + def forward(self, x): + f_score = self.score_conv(x) + f_score = F.sigmoid(f_score) + f_border = self.border_conv(x) + return f_score, f_border + + +class SAST_Header2(nn.Layer): + def __init__(self, in_channels, **kwargs): + super(SAST_Header2, self).__init__() + out_channels = [64, 64, 128] + self.tvo_conv = nn.Sequential( + ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_tvo1'), + ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_tvo2'), + ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_tvo3'), + ConvBNLayer(out_channels[2], 8, 3, 1, act=None, name='f_tvo4') + ) + self.tco_conv = nn.Sequential( + ConvBNLayer(in_channels, out_channels[0], 1, 1, act='relu', name='f_tco1'), + ConvBNLayer(out_channels[0], out_channels[1], 3, 1, act='relu', name='f_tco2'), + ConvBNLayer(out_channels[1], out_channels[2], 1, 1, act='relu', name='f_tco3'), + ConvBNLayer(out_channels[2], 2, 3, 1, act=None, name='f_tco4') + ) + + def forward(self, x): + f_tvo = self.tvo_conv(x) + f_tco = self.tco_conv(x) + return f_tvo, f_tco + + +class SASTHead(nn.Layer): + """ + """ + def __init__(self, in_channels, **kwargs): + super(SASTHead, self).__init__() + + self.head1 = SAST_Header1(in_channels) + self.head2 = SAST_Header2(in_channels) + + def forward(self, x, targets=None): + f_score, f_border = self.head1(x) + f_tvo, f_tco = self.head2(x) + + predicts = {} + predicts['f_score'] = f_score + predicts['f_border'] = f_border + predicts['f_tvo'] = f_tvo + predicts['f_tco'] = f_tco + return predicts \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/e2e_pg_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/e2e_pg_head.py new file mode 100644 index 0000000000000000000000000000000000000000..274e1cdac5172f45590c9f7d7b50522c74db6750 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/e2e_pg_head.py @@ -0,0 +1,253 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups=1, + if_act=True, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance", + use_global_stats=False) + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class PGHead(nn.Layer): + """ + """ + + def __init__(self, in_channels, **kwargs): + super(PGHead, self).__init__() + self.conv_f_score1 = ConvBNLayer( + in_channels=in_channels, + out_channels=64, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_score{}".format(1)) + self.conv_f_score2 = ConvBNLayer( + in_channels=64, + out_channels=64, + kernel_size=3, + stride=1, + padding=1, + act='relu', + name="conv_f_score{}".format(2)) + self.conv_f_score3 = ConvBNLayer( + in_channels=64, + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_score{}".format(3)) + + self.conv1 = nn.Conv2D( + in_channels=128, + out_channels=1, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr(name="conv_f_score{}".format(4)), + bias_attr=False) + + self.conv_f_boder1 = ConvBNLayer( + in_channels=in_channels, + out_channels=64, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_boder{}".format(1)) + self.conv_f_boder2 = ConvBNLayer( + in_channels=64, + out_channels=64, + kernel_size=3, + stride=1, + padding=1, + act='relu', + name="conv_f_boder{}".format(2)) + self.conv_f_boder3 = ConvBNLayer( + in_channels=64, + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_boder{}".format(3)) + self.conv2 = nn.Conv2D( + in_channels=128, + out_channels=4, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr(name="conv_f_boder{}".format(4)), + bias_attr=False) + self.conv_f_char1 = ConvBNLayer( + in_channels=in_channels, + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_char{}".format(1)) + self.conv_f_char2 = ConvBNLayer( + in_channels=128, + out_channels=128, + kernel_size=3, + stride=1, + padding=1, + act='relu', + name="conv_f_char{}".format(2)) + self.conv_f_char3 = ConvBNLayer( + in_channels=128, + out_channels=256, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_char{}".format(3)) + self.conv_f_char4 = ConvBNLayer( + in_channels=256, + out_channels=256, + kernel_size=3, + stride=1, + padding=1, + act='relu', + name="conv_f_char{}".format(4)) + self.conv_f_char5 = ConvBNLayer( + in_channels=256, + out_channels=256, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_char{}".format(5)) + self.conv3 = nn.Conv2D( + in_channels=256, + out_channels=37, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr(name="conv_f_char{}".format(6)), + bias_attr=False) + + self.conv_f_direc1 = ConvBNLayer( + in_channels=in_channels, + out_channels=64, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_direc{}".format(1)) + self.conv_f_direc2 = ConvBNLayer( + in_channels=64, + out_channels=64, + kernel_size=3, + stride=1, + padding=1, + act='relu', + name="conv_f_direc{}".format(2)) + self.conv_f_direc3 = ConvBNLayer( + in_channels=64, + out_channels=128, + kernel_size=1, + stride=1, + padding=0, + act='relu', + name="conv_f_direc{}".format(3)) + self.conv4 = nn.Conv2D( + in_channels=128, + out_channels=2, + kernel_size=3, + stride=1, + padding=1, + groups=1, + weight_attr=ParamAttr(name="conv_f_direc{}".format(4)), + bias_attr=False) + + def forward(self, x, targets=None): + f_score = self.conv_f_score1(x) + f_score = self.conv_f_score2(f_score) + f_score = self.conv_f_score3(f_score) + f_score = self.conv1(f_score) + f_score = F.sigmoid(f_score) + + # f_border + f_border = self.conv_f_boder1(x) + f_border = self.conv_f_boder2(f_border) + f_border = self.conv_f_boder3(f_border) + f_border = self.conv2(f_border) + + f_char = self.conv_f_char1(x) + f_char = self.conv_f_char2(f_char) + f_char = self.conv_f_char3(f_char) + f_char = self.conv_f_char4(f_char) + f_char = self.conv_f_char5(f_char) + f_char = self.conv3(f_char) + + f_direction = self.conv_f_direc1(x) + f_direction = self.conv_f_direc2(f_direction) + f_direction = self.conv_f_direc3(f_direction) + f_direction = self.conv4(f_direction) + + predicts = {} + predicts['f_score'] = f_score + predicts['f_border'] = f_border + predicts['f_char'] = f_char + predicts['f_direction'] = f_direction + return predicts diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/kie_sdmgr_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/kie_sdmgr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5f73fa7e5b182faa1456e069da79118d6f7068 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/kie_sdmgr_head.py @@ -0,0 +1,207 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +# reference from : https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/kie/heads/sdmgr_head.py + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class SDMGRHead(nn.Layer): + def __init__(self, + in_channels, + num_chars=92, + visual_dim=16, + fusion_dim=1024, + node_input=32, + node_embed=256, + edge_input=5, + edge_embed=256, + num_gnn=2, + num_classes=26, + bidirectional=False): + super().__init__() + + self.fusion = Block([visual_dim, node_embed], node_embed, fusion_dim) + self.node_embed = nn.Embedding(num_chars, node_input, 0) + hidden = node_embed // 2 if bidirectional else node_embed + self.rnn = nn.LSTM( + input_size=node_input, hidden_size=hidden, num_layers=1) + self.edge_embed = nn.Linear(edge_input, edge_embed) + self.gnn_layers = nn.LayerList( + [GNNLayer(node_embed, edge_embed) for _ in range(num_gnn)]) + self.node_cls = nn.Linear(node_embed, num_classes) + self.edge_cls = nn.Linear(edge_embed, 2) + + def forward(self, input, targets): + relations, texts, x = input + node_nums, char_nums = [], [] + for text in texts: + node_nums.append(text.shape[0]) + char_nums.append(paddle.sum((text > -1).astype(int), axis=-1)) + + max_num = max([char_num.max() for char_num in char_nums]) + all_nodes = paddle.concat([ + paddle.concat( + [text, paddle.zeros( + (text.shape[0], max_num - text.shape[1]))], -1) + for text in texts + ]) + temp = paddle.clip(all_nodes, min=0).astype(int) + embed_nodes = self.node_embed(temp) + rnn_nodes, _ = self.rnn(embed_nodes) + + b, h, w = rnn_nodes.shape + nodes = paddle.zeros([b, w]) + all_nums = paddle.concat(char_nums) + valid = paddle.nonzero((all_nums > 0).astype(int)) + temp_all_nums = ( + paddle.gather(all_nums, valid) - 1).unsqueeze(-1).unsqueeze(-1) + temp_all_nums = paddle.expand(temp_all_nums, [ + temp_all_nums.shape[0], temp_all_nums.shape[1], rnn_nodes.shape[-1] + ]) + temp_all_nodes = paddle.gather(rnn_nodes, valid) + N, C, A = temp_all_nodes.shape + one_hot = F.one_hot( + temp_all_nums[:, 0, :], num_classes=C).transpose([0, 2, 1]) + one_hot = paddle.multiply( + temp_all_nodes, one_hot.astype("float32")).sum(axis=1, keepdim=True) + t = one_hot.expand([N, 1, A]).squeeze(1) + nodes = paddle.scatter(nodes, valid.squeeze(1), t) + + if x is not None: + nodes = self.fusion([x, nodes]) + + all_edges = paddle.concat( + [rel.reshape([-1, rel.shape[-1]]) for rel in relations]) + embed_edges = self.edge_embed(all_edges.astype('float32')) + embed_edges = F.normalize(embed_edges) + + for gnn_layer in self.gnn_layers: + nodes, cat_nodes = gnn_layer(nodes, embed_edges, node_nums) + + node_cls, edge_cls = self.node_cls(nodes), self.edge_cls(cat_nodes) + return node_cls, edge_cls + + +class GNNLayer(nn.Layer): + def __init__(self, node_dim=256, edge_dim=256): + super().__init__() + self.in_fc = nn.Linear(node_dim * 2 + edge_dim, node_dim) + self.coef_fc = nn.Linear(node_dim, 1) + self.out_fc = nn.Linear(node_dim, node_dim) + self.relu = nn.ReLU() + + def forward(self, nodes, edges, nums): + start, cat_nodes = 0, [] + for num in nums: + sample_nodes = nodes[start:start + num] + cat_nodes.append( + paddle.concat([ + paddle.expand(sample_nodes.unsqueeze(1), [-1, num, -1]), + paddle.expand(sample_nodes.unsqueeze(0), [num, -1, -1]) + ], -1).reshape([num**2, -1])) + start += num + cat_nodes = paddle.concat([paddle.concat(cat_nodes), edges], -1) + cat_nodes = self.relu(self.in_fc(cat_nodes)) + coefs = self.coef_fc(cat_nodes) + + start, residuals = 0, [] + for num in nums: + residual = F.softmax( + -paddle.eye(num).unsqueeze(-1) * 1e9 + + coefs[start:start + num**2].reshape([num, num, -1]), 1) + residuals.append((residual * cat_nodes[start:start + num**2] + .reshape([num, num, -1])).sum(1)) + start += num**2 + + nodes += self.relu(self.out_fc(paddle.concat(residuals))) + return [nodes, cat_nodes] + + +class Block(nn.Layer): + def __init__(self, + input_dims, + output_dim, + mm_dim=1600, + chunks=20, + rank=15, + shared=False, + dropout_input=0., + dropout_pre_lin=0., + dropout_output=0., + pos_norm='before_cat'): + super().__init__() + self.rank = rank + self.dropout_input = dropout_input + self.dropout_pre_lin = dropout_pre_lin + self.dropout_output = dropout_output + assert (pos_norm in ['before_cat', 'after_cat']) + self.pos_norm = pos_norm + # Modules + self.linear0 = nn.Linear(input_dims[0], mm_dim) + self.linear1 = (self.linear0 + if shared else nn.Linear(input_dims[1], mm_dim)) + self.merge_linears0 = nn.LayerList() + self.merge_linears1 = nn.LayerList() + self.chunks = self.chunk_sizes(mm_dim, chunks) + for size in self.chunks: + ml0 = nn.Linear(size, size * rank) + self.merge_linears0.append(ml0) + ml1 = ml0 if shared else nn.Linear(size, size * rank) + self.merge_linears1.append(ml1) + self.linear_out = nn.Linear(mm_dim, output_dim) + + def forward(self, x): + x0 = self.linear0(x[0]) + x1 = self.linear1(x[1]) + bs = x1.shape[0] + if self.dropout_input > 0: + x0 = F.dropout(x0, p=self.dropout_input, training=self.training) + x1 = F.dropout(x1, p=self.dropout_input, training=self.training) + x0_chunks = paddle.split(x0, self.chunks, -1) + x1_chunks = paddle.split(x1, self.chunks, -1) + zs = [] + for x0_c, x1_c, m0, m1 in zip(x0_chunks, x1_chunks, self.merge_linears0, + self.merge_linears1): + m = m0(x0_c) * m1(x1_c) # bs x split_size*rank + m = m.reshape([bs, self.rank, -1]) + z = paddle.sum(m, 1) + if self.pos_norm == 'before_cat': + z = paddle.sqrt(F.relu(z)) - paddle.sqrt(F.relu(-z)) + z = F.normalize(z) + zs.append(z) + z = paddle.concat(zs, 1) + if self.pos_norm == 'after_cat': + z = paddle.sqrt(F.relu(z)) - paddle.sqrt(F.relu(-z)) + z = F.normalize(z) + + if self.dropout_pre_lin > 0: + z = F.dropout(z, p=self.dropout_pre_lin, training=self.training) + z = self.linear_out(z) + if self.dropout_output > 0: + z = F.dropout(z, p=self.dropout_output, training=self.training) + return z + + def chunk_sizes(self, dim, chunks): + split_size = (dim + chunks - 1) // chunks + sizes_list = [split_size] * chunks + sizes_list[-1] = sizes_list[-1] - (sum(sizes_list) - dim) + return sizes_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_abinet_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_abinet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2309ad65e6ebd32592df19eed0ce1fbd11cb9a81 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_abinet_head.py @@ -0,0 +1,297 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FangShancheng/ABINet/tree/main/modules +""" + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle.nn import LayerList +from ppocr.modeling.heads.rec_nrtr_head import TransformerBlock, PositionalEncoding + + +class BCNLanguage(nn.Layer): + def __init__(self, + d_model=512, + nhead=8, + num_layers=4, + dim_feedforward=2048, + dropout=0., + max_length=25, + detach=True, + num_classes=37): + super().__init__() + + self.d_model = d_model + self.detach = detach + self.max_length = max_length + 1 # additional stop token + self.proj = nn.Linear(num_classes, d_model, bias_attr=False) + self.token_encoder = PositionalEncoding( + dropout=0.1, dim=d_model, max_len=self.max_length) + self.pos_encoder = PositionalEncoding( + dropout=0, dim=d_model, max_len=self.max_length) + + self.decoder = nn.LayerList([ + TransformerBlock( + d_model=d_model, + nhead=nhead, + dim_feedforward=dim_feedforward, + attention_dropout_rate=dropout, + residual_dropout_rate=dropout, + with_self_attn=False, + with_cross_attn=True) for i in range(num_layers) + ]) + + self.cls = nn.Linear(d_model, num_classes) + + def forward(self, tokens, lengths): + """ + Args: + tokens: (B, N, C) where N is length, B is batch size and C is classes number + lengths: (B,) + """ + if self.detach: tokens = tokens.detach() + embed = self.proj(tokens) # (B, N, C) + embed = self.token_encoder(embed) # (B, N, C) + padding_mask = _get_mask(lengths, self.max_length) + zeros = paddle.zeros_like(embed) # (B, N, C) + qeury = self.pos_encoder(zeros) + for decoder_layer in self.decoder: + qeury = decoder_layer(qeury, embed, cross_mask=padding_mask) + output = qeury # (B, N, C) + + logits = self.cls(output) # (B, N, C) + + return output, logits + + +def encoder_layer(in_c, out_c, k=3, s=2, p=1): + return nn.Sequential( + nn.Conv2D(in_c, out_c, k, s, p), nn.BatchNorm2D(out_c), nn.ReLU()) + + +def decoder_layer(in_c, + out_c, + k=3, + s=1, + p=1, + mode='nearest', + scale_factor=None, + size=None): + align_corners = False if mode == 'nearest' else True + return nn.Sequential( + nn.Upsample( + size=size, + scale_factor=scale_factor, + mode=mode, + align_corners=align_corners), + nn.Conv2D(in_c, out_c, k, s, p), + nn.BatchNorm2D(out_c), + nn.ReLU()) + + +class PositionAttention(nn.Layer): + def __init__(self, + max_length, + in_channels=512, + num_channels=64, + h=8, + w=32, + mode='nearest', + **kwargs): + super().__init__() + self.max_length = max_length + self.k_encoder = nn.Sequential( + encoder_layer( + in_channels, num_channels, s=(1, 2)), + encoder_layer( + num_channels, num_channels, s=(2, 2)), + encoder_layer( + num_channels, num_channels, s=(2, 2)), + encoder_layer( + num_channels, num_channels, s=(2, 2))) + self.k_decoder = nn.Sequential( + decoder_layer( + num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer( + num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer( + num_channels, num_channels, scale_factor=2, mode=mode), + decoder_layer( + num_channels, in_channels, size=(h, w), mode=mode)) + + self.pos_encoder = PositionalEncoding( + dropout=0, dim=in_channels, max_len=max_length) + self.project = nn.Linear(in_channels, in_channels) + + def forward(self, x): + B, C, H, W = x.shape + k, v = x, x + + # calculate key vector + features = [] + for i in range(0, len(self.k_encoder)): + k = self.k_encoder[i](k) + features.append(k) + for i in range(0, len(self.k_decoder) - 1): + k = self.k_decoder[i](k) + # print(k.shape, features[len(self.k_decoder) - 2 - i].shape) + k = k + features[len(self.k_decoder) - 2 - i] + k = self.k_decoder[-1](k) + + # calculate query vector + # TODO q=f(q,k) + zeros = paddle.zeros( + (B, self.max_length, C), dtype=x.dtype) # (T, N, C) + q = self.pos_encoder(zeros) # (B, N, C) + q = self.project(q) # (B, N, C) + + # calculate attention + attn_scores = q @k.flatten(2) # (B, N, (H*W)) + attn_scores = attn_scores / (C**0.5) + attn_scores = F.softmax(attn_scores, axis=-1) + + v = v.flatten(2).transpose([0, 2, 1]) # (B, (H*W), C) + attn_vecs = attn_scores @v # (B, N, C) + + return attn_vecs, attn_scores.reshape([0, self.max_length, H, W]) + + +class ABINetHead(nn.Layer): + def __init__(self, + in_channels, + out_channels, + d_model=512, + nhead=8, + num_layers=3, + dim_feedforward=2048, + dropout=0.1, + max_length=25, + use_lang=False, + iter_size=1): + super().__init__() + self.max_length = max_length + 1 + self.pos_encoder = PositionalEncoding( + dropout=0.1, dim=d_model, max_len=8 * 32) + self.encoder = nn.LayerList([ + TransformerBlock( + d_model=d_model, + nhead=nhead, + dim_feedforward=dim_feedforward, + attention_dropout_rate=dropout, + residual_dropout_rate=dropout, + with_self_attn=True, + with_cross_attn=False) for i in range(num_layers) + ]) + self.decoder = PositionAttention( + max_length=max_length + 1, # additional stop token + mode='nearest', ) + self.out_channels = out_channels + self.cls = nn.Linear(d_model, self.out_channels) + self.use_lang = use_lang + if use_lang: + self.iter_size = iter_size + self.language = BCNLanguage( + d_model=d_model, + nhead=nhead, + num_layers=4, + dim_feedforward=dim_feedforward, + dropout=dropout, + max_length=max_length, + num_classes=self.out_channels) + # alignment + self.w_att_align = nn.Linear(2 * d_model, d_model) + self.cls_align = nn.Linear(d_model, self.out_channels) + + def forward(self, x, targets=None): + x = x.transpose([0, 2, 3, 1]) + _, H, W, C = x.shape + feature = x.flatten(1, 2) + feature = self.pos_encoder(feature) + for encoder_layer in self.encoder: + feature = encoder_layer(feature) + feature = feature.reshape([0, H, W, C]).transpose([0, 3, 1, 2]) + v_feature, attn_scores = self.decoder( + feature) # (B, N, C), (B, C, H, W) + vis_logits = self.cls(v_feature) # (B, N, C) + logits = vis_logits + vis_lengths = _get_length(vis_logits) + if self.use_lang: + align_logits = vis_logits + align_lengths = vis_lengths + all_l_res, all_a_res = [], [] + for i in range(self.iter_size): + tokens = F.softmax(align_logits, axis=-1) + lengths = align_lengths + lengths = paddle.clip( + lengths, 2, self.max_length) # TODO:move to langauge model + l_feature, l_logits = self.language(tokens, lengths) + + # alignment + all_l_res.append(l_logits) + fuse = paddle.concat((l_feature, v_feature), -1) + f_att = F.sigmoid(self.w_att_align(fuse)) + output = f_att * v_feature + (1 - f_att) * l_feature + align_logits = self.cls_align(output) # (B, N, C) + + align_lengths = _get_length(align_logits) + all_a_res.append(align_logits) + if self.training: + return { + 'align': all_a_res, + 'lang': all_l_res, + 'vision': vis_logits + } + else: + logits = align_logits + if self.training: + return logits + else: + return F.softmax(logits, -1) + + +def _get_length(logit): + """ Greed decoder to obtain length from logit""" + out = (logit.argmax(-1) == 0) + abn = out.any(-1) + out_int = out.cast('int32') + out = (out_int.cumsum(-1) == 1) & out + out = out.cast('int32') + out = out.argmax(-1) + out = out + 1 + len_seq = paddle.zeros_like(out) + logit.shape[1] + out = paddle.where(abn, out, len_seq) + return out + + +def _get_mask(length, max_length): + """Generate a square mask for the sequence. The masked positions are filled with float('-inf'). + Unmasked positions are filled with float(0.0). + """ + length = length.unsqueeze(-1) + B = paddle.shape(length)[0] + grid = paddle.arange(0, max_length).unsqueeze(0).tile([B, 1]) + zero_mask = paddle.zeros([B, max_length], dtype='float32') + inf_mask = paddle.full([B, max_length], '-inf', dtype='float32') + diag_mask = paddle.diag( + paddle.full( + [max_length], '-inf', dtype=paddle.float32), + offset=0, + name=None) + mask = paddle.where(grid >= length, inf_mask, zero_mask) + mask = mask.unsqueeze(1) + diag_mask + return mask.unsqueeze(1) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_aster_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_aster_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1febc320ea835db31d11bba2fe5f0b4ef0c1f7f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_aster_head.py @@ -0,0 +1,389 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/attention_recognition_head.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import sys + +import paddle +from paddle import nn +from paddle.nn import functional as F + + +class AsterHead(nn.Layer): + def __init__(self, + in_channels, + out_channels, + sDim, + attDim, + max_len_labels, + time_step=25, + beam_width=5, + **kwargs): + super(AsterHead, self).__init__() + self.num_classes = out_channels + self.in_planes = in_channels + self.sDim = sDim + self.attDim = attDim + self.max_len_labels = max_len_labels + self.decoder = AttentionRecognitionHead(in_channels, out_channels, sDim, + attDim, max_len_labels) + self.time_step = time_step + self.embeder = Embedding(self.time_step, in_channels) + self.beam_width = beam_width + self.eos = self.num_classes - 3 + + def forward(self, x, targets=None, embed=None): + return_dict = {} + embedding_vectors = self.embeder(x) + + if self.training: + rec_targets, rec_lengths, _ = targets + rec_pred = self.decoder([x, rec_targets, rec_lengths], + embedding_vectors) + return_dict['rec_pred'] = rec_pred + return_dict['embedding_vectors'] = embedding_vectors + else: + rec_pred, rec_pred_scores = self.decoder.beam_search( + x, self.beam_width, self.eos, embedding_vectors) + rec_pred_scores.stop_gradient = True + rec_pred.stop_gradient = True + return_dict['rec_pred'] = rec_pred + return_dict['rec_pred_scores'] = rec_pred_scores + return_dict['embedding_vectors'] = embedding_vectors + return return_dict + + +class Embedding(nn.Layer): + def __init__(self, in_timestep, in_planes, mid_dim=4096, embed_dim=300): + super(Embedding, self).__init__() + self.in_timestep = in_timestep + self.in_planes = in_planes + self.embed_dim = embed_dim + self.mid_dim = mid_dim + self.eEmbed = nn.Linear( + in_timestep * in_planes, + self.embed_dim) # Embed encoder output to a word-embedding like + + def forward(self, x): + x = paddle.reshape(x, [paddle.shape(x)[0], -1]) + x = self.eEmbed(x) + return x + + +class AttentionRecognitionHead(nn.Layer): + """ + input: [b x 16 x 64 x in_planes] + output: probability sequence: [b x T x num_classes] + """ + + def __init__(self, in_channels, out_channels, sDim, attDim, max_len_labels): + super(AttentionRecognitionHead, self).__init__() + self.num_classes = out_channels # this is the output classes. So it includes the . + self.in_planes = in_channels + self.sDim = sDim + self.attDim = attDim + self.max_len_labels = max_len_labels + + self.decoder = DecoderUnit( + sDim=sDim, xDim=in_channels, yDim=self.num_classes, attDim=attDim) + + def forward(self, x, embed): + x, targets, lengths = x + batch_size = paddle.shape(x)[0] + # Decoder + state = self.decoder.get_initial_state(embed) + outputs = [] + for i in range(max(lengths)): + if i == 0: + y_prev = paddle.full( + shape=[batch_size], fill_value=self.num_classes) + else: + + y_prev = targets[:, i - 1] + output, state = self.decoder(x, state, y_prev) + outputs.append(output) + outputs = paddle.concat([_.unsqueeze(1) for _ in outputs], 1) + return outputs + + def beam_search(self, x, beam_width, eos, embed): + def _inflate(tensor, times, dim): + repeat_dims = [1] * tensor.dim() + repeat_dims[dim] = times + output = paddle.tile(tensor, repeat_dims) + return output + + # https://github.com/IBM/pytorch-seq2seq/blob/fede87655ddce6c94b38886089e05321dc9802af/seq2seq/models/TopKDecoder.py + batch_size, l, d = paddle.shape(x) + x = paddle.tile( + paddle.transpose( + x.unsqueeze(1), perm=[1, 0, 2, 3]), [beam_width, 1, 1, 1]) + inflated_encoder_feats = paddle.reshape( + paddle.transpose( + x, perm=[1, 0, 2, 3]), [-1, l, d]) + + # Initialize the decoder + state = self.decoder.get_initial_state(embed, tile_times=beam_width) + + pos_index = paddle.reshape( + paddle.arange(batch_size) * beam_width, shape=[-1, 1]) + # Initialize the scores + + sequence_scores = paddle.full( + shape=[batch_size, beam_width], fill_value=-float('Inf')) + sequence_scores[:, 0] = 0.0 + sequence_scores = paddle.reshape( + sequence_scores, shape=[batch_size * beam_width, 1]) + + # Initialize the input vector + y_prev = paddle.full( + shape=[batch_size * beam_width], fill_value=self.num_classes) + + # Store decisions for backtracking + stored_scores = [] + stored_predecessors = [] + stored_emitted_symbols = [] + + for i in range(self.max_len_labels): + output, state = self.decoder(inflated_encoder_feats, state, y_prev) + state = paddle.unsqueeze(state, axis=0) + log_softmax_output = paddle.nn.functional.log_softmax( + output, axis=1) + + sequence_scores = _inflate(sequence_scores, self.num_classes, 1) + sequence_scores += log_softmax_output + scores, candidates = paddle.topk( + paddle.reshape(sequence_scores, [batch_size, -1]), + beam_width, + axis=1) + # Reshape input = (bk, 1) and sequence_scores = (bk, 1) + y_prev = paddle.reshape( + candidates % self.num_classes, shape=[batch_size, beam_width]) + y_prev = paddle.reshape(y_prev, shape=[batch_size * beam_width]) + sequence_scores = paddle.reshape( + scores, shape=[batch_size * beam_width, 1]) + + # Update fields for next timestep + pos_index = paddle.expand(pos_index, paddle.shape(candidates)) + + predecessors = paddle.cast( + candidates / self.num_classes + pos_index, dtype='int64') + predecessors = paddle.reshape( + predecessors, shape=[batch_size * beam_width, 1]) + state = paddle.index_select( + state, index=predecessors.squeeze(), axis=1) + + # Update sequence socres and erase scores for symbol so that they aren't expanded + stored_scores.append(sequence_scores.clone()) + y_prev = paddle.reshape(y_prev, shape=[-1, 1]) + + eos_prev = paddle.full(paddle.shape(y_prev), fill_value=eos) + mask = eos_prev == y_prev + mask = paddle.cast(mask, 'int64') + mask = paddle.nonzero(mask) + if len(mask) > 0: + sequence_scores[:] = -float('inf') + sequence_scores = paddle.to_tensor(sequence_scores) + + # Cache results for backtracking + stored_predecessors.append(predecessors) + y_prev = paddle.squeeze(y_prev) + stored_emitted_symbols.append(y_prev) + + # Do backtracking to return the optimal values + # ====== backtrak ======# + # Initialize return variables given different types + p = [] + + # Placeholder for lengths of top-k sequences + l = paddle.full([batch_size, beam_width], self.max_len_labels) + + # the last step output of the beams are not sorted + # thus they are sorted here + sorted_score, sorted_idx = paddle.topk( + paddle.reshape( + stored_scores[-1], shape=[batch_size, beam_width]), + beam_width) + + # initialize the sequence scores with the sorted last step beam scores + s = sorted_score.clone() + + batch_eos_found = paddle.zeros( + [batch_size], dtype='int32') # the number of EOS found + # in the backward loop below for each batch + t = self.max_len_labels - 1 + + # initialize the back pointer with the sorted order of the last step beams. + # add pos_index for indexing variable with b*k as the first dimension. + t_predecessors = paddle.reshape( + sorted_idx + pos_index.expand(paddle.shape(sorted_idx)), + shape=[batch_size * beam_width]) + + tmp_beam_width = beam_width + while t >= 0: + # Re-order the variables with the back pointer + current_symbol = paddle.index_select( + stored_emitted_symbols[t], index=t_predecessors, axis=0) + t_predecessors = paddle.index_select( + stored_predecessors[t].squeeze(), index=t_predecessors, axis=0) + eos_indices = stored_emitted_symbols[t] == eos + eos_indices = paddle.nonzero(eos_indices) + + stored_predecessors_t = stored_predecessors[t] + stored_emitted_symbols_t = stored_emitted_symbols[t] + stored_scores_t = stored_scores[t] + t_plus = t + 1 + + if eos_indices.dim() > 0: + for j in range(eos_indices.shape[0] - 1, -1, -1): + # Indices of the EOS symbol for both variables + # with b*k as the first dimension, and b, k for + # the first two dimensions + idx = eos_indices[j] + b_idx = int(idx[0] / tmp_beam_width) + # The indices of the replacing position + # according to the replacement strategy noted above + res_k_idx = tmp_beam_width - (batch_eos_found[b_idx] % + tmp_beam_width) - 1 + batch_eos_found[b_idx] += 1 + res_idx = b_idx * tmp_beam_width + res_k_idx + + # Replace the old information in return variables + # with the new ended sequence information + + t_predecessors[res_idx] = stored_predecessors_t[idx[0]] + current_symbol[res_idx] = stored_emitted_symbols_t[idx[0]] + s[b_idx, res_k_idx] = stored_scores_t[idx[0], 0] + l[b_idx][res_k_idx] = t_plus + + # record the back tracked results + p.append(current_symbol) + t -= 1 + + # Sort and re-order again as the added ended sequences may change + # the order (very unlikely) + s, re_sorted_idx = s.topk(beam_width) + + for b_idx in range(batch_size): + tmp_tensor = paddle.full_like(l[b_idx], 0) + for k_idx in re_sorted_idx[b_idx]: + tmp_tensor[k_idx] = l[b_idx][k_idx] + l[b_idx] = tmp_tensor + + re_sorted_idx = paddle.reshape( + re_sorted_idx + pos_index.expand(paddle.shape(re_sorted_idx)), + [batch_size * beam_width]) + + # Reverse the sequences and re-order at the same time + # It is reversed because the backtracking happens in reverse time order + reversed_p = p[::-1] + + q = [] + for step in reversed_p: + q.append( + paddle.reshape( + paddle.index_select(step, re_sorted_idx, 0), + shape=[batch_size, beam_width, -1])) + + q = paddle.concat(q, -1)[:, 0, :] + return q, paddle.ones_like(q) + + +class AttentionUnit(nn.Layer): + def __init__(self, sDim, xDim, attDim): + super(AttentionUnit, self).__init__() + + self.sDim = sDim + self.xDim = xDim + self.attDim = attDim + + self.sEmbed = nn.Linear(sDim, attDim) + self.xEmbed = nn.Linear(xDim, attDim) + self.wEmbed = nn.Linear(attDim, 1) + + def forward(self, x, sPrev): + batch_size, T, _ = x.shape # [b x T x xDim] + x = paddle.reshape(x, [-1, self.xDim]) # [(b x T) x xDim] + xProj = self.xEmbed(x) # [(b x T) x attDim] + xProj = paddle.reshape(xProj, [batch_size, T, -1]) # [b x T x attDim] + + sPrev = sPrev.squeeze(0) + sProj = self.sEmbed(sPrev) # [b x attDim] + sProj = paddle.unsqueeze(sProj, 1) # [b x 1 x attDim] + sProj = paddle.expand(sProj, + [batch_size, T, self.attDim]) # [b x T x attDim] + + sumTanh = paddle.tanh(sProj + xProj) + sumTanh = paddle.reshape(sumTanh, [-1, self.attDim]) + + vProj = self.wEmbed(sumTanh) # [(b x T) x 1] + vProj = paddle.reshape(vProj, [batch_size, T]) + alpha = F.softmax( + vProj, axis=1) # attention weights for each sample in the minibatch + return alpha + + +class DecoderUnit(nn.Layer): + def __init__(self, sDim, xDim, yDim, attDim): + super(DecoderUnit, self).__init__() + self.sDim = sDim + self.xDim = xDim + self.yDim = yDim + self.attDim = attDim + self.emdDim = attDim + + self.attention_unit = AttentionUnit(sDim, xDim, attDim) + self.tgt_embedding = nn.Embedding( + yDim + 1, self.emdDim, weight_attr=nn.initializer.Normal( + std=0.01)) # the last is used for + self.gru = nn.GRUCell(input_size=xDim + self.emdDim, hidden_size=sDim) + self.fc = nn.Linear( + sDim, + yDim, + weight_attr=nn.initializer.Normal(std=0.01), + bias_attr=nn.initializer.Constant(value=0)) + self.embed_fc = nn.Linear(300, self.sDim) + + def get_initial_state(self, embed, tile_times=1): + assert embed.shape[1] == 300 + state = self.embed_fc(embed) # N * sDim + if tile_times != 1: + state = state.unsqueeze(1) + trans_state = paddle.transpose(state, perm=[1, 0, 2]) + state = paddle.tile(trans_state, repeat_times=[tile_times, 1, 1]) + trans_state = paddle.transpose(state, perm=[1, 0, 2]) + state = paddle.reshape(trans_state, shape=[-1, self.sDim]) + state = state.unsqueeze(0) # 1 * N * sDim + return state + + def forward(self, x, sPrev, yPrev): + # x: feature sequence from the image decoder. + batch_size, T, _ = x.shape + alpha = self.attention_unit(x, sPrev) + context = paddle.squeeze(paddle.matmul(alpha.unsqueeze(1), x), axis=1) + yPrev = paddle.cast(yPrev, dtype="int64") + yProj = self.tgt_embedding(yPrev) + + concat_context = paddle.concat([yProj, context], 1) + sPrev = paddle.squeeze(sPrev, 0) + + output, state = self.gru(concat_context, sPrev) + output = paddle.squeeze(output, axis=1) + output = self.fc(output) + return output, state diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_att_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_att_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8b119fe08ac79a6b98a449bb117da018df2ff3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_att_head.py @@ -0,0 +1,202 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F +import numpy as np + + +class AttentionHead(nn.Layer): + def __init__(self, in_channels, out_channels, hidden_size, **kwargs): + super(AttentionHead, self).__init__() + self.input_size = in_channels + self.hidden_size = hidden_size + self.num_classes = out_channels + + self.attention_cell = AttentionGRUCell( + in_channels, hidden_size, out_channels, use_gru=False) + self.generator = nn.Linear(hidden_size, out_channels) + + def _char_to_onehot(self, input_char, onehot_dim): + input_ont_hot = F.one_hot(input_char, onehot_dim) + return input_ont_hot + + def forward(self, inputs, targets=None, batch_max_length=25): + batch_size = paddle.shape(inputs)[0] + num_steps = batch_max_length + + hidden = paddle.zeros((batch_size, self.hidden_size)) + output_hiddens = [] + + if targets is not None: + for i in range(num_steps): + char_onehots = self._char_to_onehot( + targets[:, i], onehot_dim=self.num_classes) + (outputs, hidden), alpha = self.attention_cell(hidden, inputs, + char_onehots) + output_hiddens.append(paddle.unsqueeze(outputs, axis=1)) + output = paddle.concat(output_hiddens, axis=1) + probs = self.generator(output) + else: + targets = paddle.zeros(shape=[batch_size], dtype="int32") + probs = None + char_onehots = None + outputs = None + alpha = None + + for i in range(num_steps): + char_onehots = self._char_to_onehot( + targets, onehot_dim=self.num_classes) + (outputs, hidden), alpha = self.attention_cell(hidden, inputs, + char_onehots) + probs_step = self.generator(outputs) + if probs is None: + probs = paddle.unsqueeze(probs_step, axis=1) + else: + probs = paddle.concat( + [probs, paddle.unsqueeze( + probs_step, axis=1)], axis=1) + next_input = probs_step.argmax(axis=1) + targets = next_input + if not self.training: + probs = paddle.nn.functional.softmax(probs, axis=2) + return probs + + +class AttentionGRUCell(nn.Layer): + def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False): + super(AttentionGRUCell, self).__init__() + self.i2h = nn.Linear(input_size, hidden_size, bias_attr=False) + self.h2h = nn.Linear(hidden_size, hidden_size) + self.score = nn.Linear(hidden_size, 1, bias_attr=False) + + self.rnn = nn.GRUCell( + input_size=input_size + num_embeddings, hidden_size=hidden_size) + + self.hidden_size = hidden_size + + def forward(self, prev_hidden, batch_H, char_onehots): + + batch_H_proj = self.i2h(batch_H) + prev_hidden_proj = paddle.unsqueeze(self.h2h(prev_hidden), axis=1) + + res = paddle.add(batch_H_proj, prev_hidden_proj) + res = paddle.tanh(res) + e = self.score(res) + + alpha = F.softmax(e, axis=1) + alpha = paddle.transpose(alpha, [0, 2, 1]) + context = paddle.squeeze(paddle.mm(alpha, batch_H), axis=1) + concat_context = paddle.concat([context, char_onehots], 1) + + cur_hidden = self.rnn(concat_context, prev_hidden) + + return cur_hidden, alpha + + +class AttentionLSTM(nn.Layer): + def __init__(self, in_channels, out_channels, hidden_size, **kwargs): + super(AttentionLSTM, self).__init__() + self.input_size = in_channels + self.hidden_size = hidden_size + self.num_classes = out_channels + + self.attention_cell = AttentionLSTMCell( + in_channels, hidden_size, out_channels, use_gru=False) + self.generator = nn.Linear(hidden_size, out_channels) + + def _char_to_onehot(self, input_char, onehot_dim): + input_ont_hot = F.one_hot(input_char, onehot_dim) + return input_ont_hot + + def forward(self, inputs, targets=None, batch_max_length=25): + batch_size = inputs.shape[0] + num_steps = batch_max_length + + hidden = (paddle.zeros((batch_size, self.hidden_size)), paddle.zeros( + (batch_size, self.hidden_size))) + output_hiddens = [] + + if targets is not None: + for i in range(num_steps): + # one-hot vectors for a i-th char + char_onehots = self._char_to_onehot( + targets[:, i], onehot_dim=self.num_classes) + hidden, alpha = self.attention_cell(hidden, inputs, + char_onehots) + + hidden = (hidden[1][0], hidden[1][1]) + output_hiddens.append(paddle.unsqueeze(hidden[0], axis=1)) + output = paddle.concat(output_hiddens, axis=1) + probs = self.generator(output) + + else: + targets = paddle.zeros(shape=[batch_size], dtype="int32") + probs = None + + for i in range(num_steps): + char_onehots = self._char_to_onehot( + targets, onehot_dim=self.num_classes) + hidden, alpha = self.attention_cell(hidden, inputs, + char_onehots) + probs_step = self.generator(hidden[0]) + hidden = (hidden[1][0], hidden[1][1]) + if probs is None: + probs = paddle.unsqueeze(probs_step, axis=1) + else: + probs = paddle.concat( + [probs, paddle.unsqueeze( + probs_step, axis=1)], axis=1) + + next_input = probs_step.argmax(axis=1) + + targets = next_input + + return probs + + +class AttentionLSTMCell(nn.Layer): + def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False): + super(AttentionLSTMCell, self).__init__() + self.i2h = nn.Linear(input_size, hidden_size, bias_attr=False) + self.h2h = nn.Linear(hidden_size, hidden_size) + self.score = nn.Linear(hidden_size, 1, bias_attr=False) + if not use_gru: + self.rnn = nn.LSTMCell( + input_size=input_size + num_embeddings, hidden_size=hidden_size) + else: + self.rnn = nn.GRUCell( + input_size=input_size + num_embeddings, hidden_size=hidden_size) + + self.hidden_size = hidden_size + + def forward(self, prev_hidden, batch_H, char_onehots): + batch_H_proj = self.i2h(batch_H) + prev_hidden_proj = paddle.unsqueeze(self.h2h(prev_hidden[0]), axis=1) + res = paddle.add(batch_H_proj, prev_hidden_proj) + res = paddle.tanh(res) + e = self.score(res) + + alpha = F.softmax(e, axis=1) + alpha = paddle.transpose(alpha, [0, 2, 1]) + context = paddle.squeeze(paddle.mm(alpha, batch_H), axis=1) + concat_context = paddle.concat([context, char_onehots], 1) + cur_hidden = self.rnn(concat_context, prev_hidden) + + return cur_hidden, alpha diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_ctc_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_ctc_head.py new file mode 100755 index 0000000000000000000000000000000000000000..6c1cf0659607186d54dfee6983b135f34d542446 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_ctc_head.py @@ -0,0 +1,87 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +import paddle +from paddle import ParamAttr, nn +from paddle.nn import functional as F + + +def get_para_bias_attr(l2_decay, k): + regularizer = paddle.regularizer.L2Decay(l2_decay) + stdv = 1.0 / math.sqrt(k * 1.0) + initializer = nn.initializer.Uniform(-stdv, stdv) + weight_attr = ParamAttr(regularizer=regularizer, initializer=initializer) + bias_attr = ParamAttr(regularizer=regularizer, initializer=initializer) + return [weight_attr, bias_attr] + + +class CTCHead(nn.Layer): + def __init__(self, + in_channels, + out_channels, + fc_decay=0.0004, + mid_channels=None, + return_feats=False, + **kwargs): + super(CTCHead, self).__init__() + if mid_channels is None: + weight_attr, bias_attr = get_para_bias_attr( + l2_decay=fc_decay, k=in_channels) + self.fc = nn.Linear( + in_channels, + out_channels, + weight_attr=weight_attr, + bias_attr=bias_attr) + else: + weight_attr1, bias_attr1 = get_para_bias_attr( + l2_decay=fc_decay, k=in_channels) + self.fc1 = nn.Linear( + in_channels, + mid_channels, + weight_attr=weight_attr1, + bias_attr=bias_attr1) + + weight_attr2, bias_attr2 = get_para_bias_attr( + l2_decay=fc_decay, k=mid_channels) + self.fc2 = nn.Linear( + mid_channels, + out_channels, + weight_attr=weight_attr2, + bias_attr=bias_attr2) + self.out_channels = out_channels + self.mid_channels = mid_channels + self.return_feats = return_feats + + def forward(self, x, targets=None): + if self.mid_channels is None: + predicts = self.fc(x) + else: + x = self.fc1(x) + predicts = self.fc2(x) + + if self.return_feats: + result = (x, predicts) + else: + result = predicts + if not self.training: + predicts = F.softmax(predicts, axis=2) + result = predicts + + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_multi_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_multi_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2f10e7bdf90025d3304128e720ce561c8bb269c1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_multi_head.py @@ -0,0 +1,73 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +from ppocr.modeling.necks.rnn import Im2Seq, EncoderWithRNN, EncoderWithFC, SequenceEncoder, EncoderWithSVTR +from .rec_ctc_head import CTCHead +from .rec_sar_head import SARHead + + +class MultiHead(nn.Layer): + def __init__(self, in_channels, out_channels_list, **kwargs): + super().__init__() + self.head_list = kwargs.pop('head_list') + self.gtc_head = 'sar' + assert len(self.head_list) >= 2 + for idx, head_name in enumerate(self.head_list): + name = list(head_name)[0] + if name == 'SARHead': + # sar head + sar_args = self.head_list[idx][name] + self.sar_head = eval(name)(in_channels=in_channels, \ + out_channels=out_channels_list['SARLabelDecode'], **sar_args) + elif name == 'CTCHead': + # ctc neck + self.encoder_reshape = Im2Seq(in_channels) + neck_args = self.head_list[idx][name]['Neck'] + encoder_type = neck_args.pop('name') + self.encoder = encoder_type + self.ctc_encoder = SequenceEncoder(in_channels=in_channels, \ + encoder_type=encoder_type, **neck_args) + # ctc head + head_args = self.head_list[idx][name]['Head'] + self.ctc_head = eval(name)(in_channels=self.ctc_encoder.out_channels, \ + out_channels=out_channels_list['CTCLabelDecode'], **head_args) + else: + raise NotImplementedError( + '{} is not supported in MultiHead yet'.format(name)) + + def forward(self, x, targets=None): + ctc_encoder = self.ctc_encoder(x) + ctc_out = self.ctc_head(ctc_encoder, targets) + head_out = dict() + head_out['ctc'] = ctc_out + head_out['ctc_neck'] = ctc_encoder + # eval mode + if not self.training: + return ctc_out + if self.gtc_head == 'sar': + sar_out = self.sar_head(x, targets[1:]) + head_out['sar'] = sar_out + return head_out + else: + return head_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_nrtr_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_nrtr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..bf9ef56145e6edfb15bd30235b4a62588396ba96 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_nrtr_head.py @@ -0,0 +1,677 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle.nn import LayerList +# from paddle.nn.initializer import XavierNormal as xavier_uniform_ +from paddle.nn import Dropout, Linear, LayerNorm +import numpy as np +from ppocr.modeling.backbones.rec_svtrnet import Mlp, zeros_, ones_ +from paddle.nn.initializer import XavierNormal as xavier_normal_ + + +class Transformer(nn.Layer): + """A transformer model. User is able to modify the attributes as needed. The architechture + is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, + Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and + Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information + Processing Systems, pages 6000-6010. + + Args: + d_model: the number of expected features in the encoder/decoder inputs (default=512). + nhead: the number of heads in the multiheadattention models (default=8). + num_encoder_layers: the number of sub-encoder-layers in the encoder (default=6). + num_decoder_layers: the number of sub-decoder-layers in the decoder (default=6). + dim_feedforward: the dimension of the feedforward network model (default=2048). + dropout: the dropout value (default=0.1). + custom_encoder: custom encoder (default=None). + custom_decoder: custom decoder (default=None). + """ + + def __init__(self, + d_model=512, + nhead=8, + num_encoder_layers=6, + beam_size=0, + num_decoder_layers=6, + max_len=25, + dim_feedforward=1024, + attention_dropout_rate=0.0, + residual_dropout_rate=0.1, + in_channels=0, + out_channels=0, + scale_embedding=True): + super(Transformer, self).__init__() + self.out_channels = out_channels + 1 + self.max_len = max_len + self.embedding = Embeddings( + d_model=d_model, + vocab=self.out_channels, + padding_idx=0, + scale_embedding=scale_embedding) + self.positional_encoding = PositionalEncoding( + dropout=residual_dropout_rate, dim=d_model) + + if num_encoder_layers > 0: + self.encoder = nn.LayerList([ + TransformerBlock( + d_model, + nhead, + dim_feedforward, + attention_dropout_rate, + residual_dropout_rate, + with_self_attn=True, + with_cross_attn=False) for i in range(num_encoder_layers) + ]) + else: + self.encoder = None + + self.decoder = nn.LayerList([ + TransformerBlock( + d_model, + nhead, + dim_feedforward, + attention_dropout_rate, + residual_dropout_rate, + with_self_attn=True, + with_cross_attn=True) for i in range(num_decoder_layers) + ]) + + self.beam_size = beam_size + self.d_model = d_model + self.nhead = nhead + self.tgt_word_prj = nn.Linear( + d_model, self.out_channels, bias_attr=False) + w0 = np.random.normal(0.0, d_model**-0.5, + (d_model, self.out_channels)).astype(np.float32) + self.tgt_word_prj.weight.set_value(w0) + self.apply(self._init_weights) + + def _init_weights(self, m): + + if isinstance(m, nn.Linear): + xavier_normal_(m.weight) + if m.bias is not None: + zeros_(m.bias) + + def forward_train(self, src, tgt): + tgt = tgt[:, :-1] + + tgt = self.embedding(tgt) + tgt = self.positional_encoding(tgt) + tgt_mask = self.generate_square_subsequent_mask(tgt.shape[1]) + + if self.encoder is not None: + src = self.positional_encoding(src) + for encoder_layer in self.encoder: + src = encoder_layer(src) + memory = src # B N C + else: + memory = src # B N C + for decoder_layer in self.decoder: + tgt = decoder_layer(tgt, memory, self_mask=tgt_mask) + output = tgt + logit = self.tgt_word_prj(output) + return logit + + def forward(self, src, targets=None): + """Take in and process masked source/target sequences. + Args: + src: the sequence to the encoder (required). + tgt: the sequence to the decoder (required). + Shape: + - src: :math:`(B, sN, C)`. + - tgt: :math:`(B, tN, C)`. + Examples: + >>> output = transformer_model(src, tgt) + """ + + if self.training: + max_len = targets[1].max() + tgt = targets[0][:, :2 + max_len] + return self.forward_train(src, tgt) + else: + if self.beam_size > 0: + return self.forward_beam(src) + else: + return self.forward_test(src) + + def forward_test(self, src): + + bs = paddle.shape(src)[0] + if self.encoder is not None: + src = self.positional_encoding(src) + for encoder_layer in self.encoder: + src = encoder_layer(src) + memory = src # B N C + else: + memory = src + dec_seq = paddle.full((bs, 1), 2, dtype=paddle.int64) + dec_prob = paddle.full((bs, 1), 1., dtype=paddle.float32) + for len_dec_seq in range(1, self.max_len): + dec_seq_embed = self.embedding(dec_seq) + dec_seq_embed = self.positional_encoding(dec_seq_embed) + tgt_mask = self.generate_square_subsequent_mask( + paddle.shape(dec_seq_embed)[1]) + tgt = dec_seq_embed + for decoder_layer in self.decoder: + tgt = decoder_layer(tgt, memory, self_mask=tgt_mask) + dec_output = tgt + dec_output = dec_output[:, -1, :] + word_prob = F.softmax(self.tgt_word_prj(dec_output), axis=-1) + preds_idx = paddle.argmax(word_prob, axis=-1) + if paddle.equal_all( + preds_idx, + paddle.full( + paddle.shape(preds_idx), 3, dtype='int64')): + break + preds_prob = paddle.max(word_prob, axis=-1) + dec_seq = paddle.concat( + [dec_seq, paddle.reshape(preds_idx, [-1, 1])], axis=1) + dec_prob = paddle.concat( + [dec_prob, paddle.reshape(preds_prob, [-1, 1])], axis=1) + return [dec_seq, dec_prob] + + def forward_beam(self, images): + """ Translation work in one batch """ + + def get_inst_idx_to_tensor_position_map(inst_idx_list): + """ Indicate the position of an instance in a tensor. """ + return { + inst_idx: tensor_position + for tensor_position, inst_idx in enumerate(inst_idx_list) + } + + def collect_active_part(beamed_tensor, curr_active_inst_idx, + n_prev_active_inst, n_bm): + """ Collect tensor parts associated to active instances. """ + + beamed_tensor_shape = paddle.shape(beamed_tensor) + n_curr_active_inst = len(curr_active_inst_idx) + new_shape = (n_curr_active_inst * n_bm, beamed_tensor_shape[1], + beamed_tensor_shape[2]) + + beamed_tensor = beamed_tensor.reshape([n_prev_active_inst, -1]) + beamed_tensor = beamed_tensor.index_select( + curr_active_inst_idx, axis=0) + beamed_tensor = beamed_tensor.reshape(new_shape) + + return beamed_tensor + + def collate_active_info(src_enc, inst_idx_to_position_map, + active_inst_idx_list): + # Sentences which are still active are collected, + # so the decoder will not run on completed sentences. + + n_prev_active_inst = len(inst_idx_to_position_map) + active_inst_idx = [ + inst_idx_to_position_map[k] for k in active_inst_idx_list + ] + active_inst_idx = paddle.to_tensor(active_inst_idx, dtype='int64') + active_src_enc = collect_active_part( + src_enc.transpose([1, 0, 2]), active_inst_idx, + n_prev_active_inst, n_bm).transpose([1, 0, 2]) + active_inst_idx_to_position_map = get_inst_idx_to_tensor_position_map( + active_inst_idx_list) + return active_src_enc, active_inst_idx_to_position_map + + def beam_decode_step(inst_dec_beams, len_dec_seq, enc_output, + inst_idx_to_position_map, n_bm): + """ Decode and update beam status, and then return active beam idx """ + + def prepare_beam_dec_seq(inst_dec_beams, len_dec_seq): + dec_partial_seq = [ + b.get_current_state() for b in inst_dec_beams if not b.done + ] + dec_partial_seq = paddle.stack(dec_partial_seq) + dec_partial_seq = dec_partial_seq.reshape([-1, len_dec_seq]) + return dec_partial_seq + + def predict_word(dec_seq, enc_output, n_active_inst, n_bm): + dec_seq = self.embedding(dec_seq) + dec_seq = self.positional_encoding(dec_seq) + tgt_mask = self.generate_square_subsequent_mask( + paddle.shape(dec_seq)[1]) + tgt = dec_seq + for decoder_layer in self.decoder: + tgt = decoder_layer(tgt, enc_output, self_mask=tgt_mask) + dec_output = tgt + dec_output = dec_output[:, + -1, :] # Pick the last step: (bh * bm) * d_h + word_prob = F.softmax(self.tgt_word_prj(dec_output), axis=1) + word_prob = paddle.reshape(word_prob, [n_active_inst, n_bm, -1]) + return word_prob + + def collect_active_inst_idx_list(inst_beams, word_prob, + inst_idx_to_position_map): + active_inst_idx_list = [] + for inst_idx, inst_position in inst_idx_to_position_map.items(): + is_inst_complete = inst_beams[inst_idx].advance(word_prob[ + inst_position]) + if not is_inst_complete: + active_inst_idx_list += [inst_idx] + + return active_inst_idx_list + + n_active_inst = len(inst_idx_to_position_map) + dec_seq = prepare_beam_dec_seq(inst_dec_beams, len_dec_seq) + word_prob = predict_word(dec_seq, enc_output, n_active_inst, n_bm) + # Update the beam with predicted word prob information and collect incomplete instances + active_inst_idx_list = collect_active_inst_idx_list( + inst_dec_beams, word_prob, inst_idx_to_position_map) + return active_inst_idx_list + + def collect_hypothesis_and_scores(inst_dec_beams, n_best): + all_hyp, all_scores = [], [] + for inst_idx in range(len(inst_dec_beams)): + scores, tail_idxs = inst_dec_beams[inst_idx].sort_scores() + all_scores += [scores[:n_best]] + hyps = [ + inst_dec_beams[inst_idx].get_hypothesis(i) + for i in tail_idxs[:n_best] + ] + all_hyp += [hyps] + return all_hyp, all_scores + + with paddle.no_grad(): + #-- Encode + if self.encoder is not None: + src = self.positional_encoding(images) + src_enc = self.encoder(src) + else: + src_enc = images + + n_bm = self.beam_size + src_shape = paddle.shape(src_enc) + inst_dec_beams = [Beam(n_bm) for _ in range(1)] + active_inst_idx_list = list(range(1)) + # Repeat data for beam search + src_enc = paddle.tile(src_enc, [1, n_bm, 1]) + inst_idx_to_position_map = get_inst_idx_to_tensor_position_map( + active_inst_idx_list) + # Decode + for len_dec_seq in range(1, self.max_len): + src_enc_copy = src_enc.clone() + active_inst_idx_list = beam_decode_step( + inst_dec_beams, len_dec_seq, src_enc_copy, + inst_idx_to_position_map, n_bm) + if not active_inst_idx_list: + break # all instances have finished their path to + src_enc, inst_idx_to_position_map = collate_active_info( + src_enc_copy, inst_idx_to_position_map, + active_inst_idx_list) + batch_hyp, batch_scores = collect_hypothesis_and_scores(inst_dec_beams, + 1) + result_hyp = [] + hyp_scores = [] + for bs_hyp, score in zip(batch_hyp, batch_scores): + l = len(bs_hyp[0]) + bs_hyp_pad = bs_hyp[0] + [3] * (25 - l) + result_hyp.append(bs_hyp_pad) + score = float(score) / l + hyp_score = [score for _ in range(25)] + hyp_scores.append(hyp_score) + return [ + paddle.to_tensor( + np.array(result_hyp), dtype=paddle.int64), + paddle.to_tensor(hyp_scores) + ] + + def generate_square_subsequent_mask(self, sz): + """Generate a square mask for the sequence. The masked positions are filled with float('-inf'). + Unmasked positions are filled with float(0.0). + """ + mask = paddle.zeros([sz, sz], dtype='float32') + mask_inf = paddle.triu( + paddle.full( + shape=[sz, sz], dtype='float32', fill_value='-inf'), + diagonal=1) + mask = mask + mask_inf + return mask.unsqueeze([0, 1]) + + +class MultiheadAttention(nn.Layer): + """Allows the model to jointly attend to information + from different representation subspaces. + See reference: Attention Is All You Need + + .. math:: + \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O + \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V) + + Args: + embed_dim: total dimension of the model + num_heads: parallel attention layers, or heads + + """ + + def __init__(self, embed_dim, num_heads, dropout=0., self_attn=False): + super(MultiheadAttention, self).__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + # self.dropout = dropout + self.head_dim = embed_dim // num_heads + assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" + self.scale = self.head_dim**-0.5 + self.self_attn = self_attn + if self_attn: + self.qkv = nn.Linear(embed_dim, embed_dim * 3) + else: + self.q = nn.Linear(embed_dim, embed_dim) + self.kv = nn.Linear(embed_dim, embed_dim * 2) + self.attn_drop = nn.Dropout(dropout) + self.out_proj = nn.Linear(embed_dim, embed_dim) + + def forward(self, query, key=None, attn_mask=None): + + qN = query.shape[1] + + if self.self_attn: + qkv = self.qkv(query).reshape( + (0, qN, 3, self.num_heads, self.head_dim)).transpose( + (2, 0, 3, 1, 4)) + q, k, v = qkv[0], qkv[1], qkv[2] + else: + kN = key.shape[1] + q = self.q(query).reshape( + [0, qN, self.num_heads, self.head_dim]).transpose([0, 2, 1, 3]) + kv = self.kv(key).reshape( + (0, kN, 2, self.num_heads, self.head_dim)).transpose( + (2, 0, 3, 1, 4)) + k, v = kv[0], kv[1] + + attn = (q.matmul(k.transpose((0, 1, 3, 2)))) * self.scale + + if attn_mask is not None: + attn += attn_mask + + attn = F.softmax(attn, axis=-1) + attn = self.attn_drop(attn) + + x = (attn.matmul(v)).transpose((0, 2, 1, 3)).reshape( + (0, qN, self.embed_dim)) + x = self.out_proj(x) + + return x + + +class TransformerBlock(nn.Layer): + def __init__(self, + d_model, + nhead, + dim_feedforward=2048, + attention_dropout_rate=0.0, + residual_dropout_rate=0.1, + with_self_attn=True, + with_cross_attn=False, + epsilon=1e-5): + super(TransformerBlock, self).__init__() + self.with_self_attn = with_self_attn + if with_self_attn: + self.self_attn = MultiheadAttention( + d_model, + nhead, + dropout=attention_dropout_rate, + self_attn=with_self_attn) + self.norm1 = LayerNorm(d_model, epsilon=epsilon) + self.dropout1 = Dropout(residual_dropout_rate) + self.with_cross_attn = with_cross_attn + if with_cross_attn: + self.cross_attn = MultiheadAttention( #for self_attn of encoder or cross_attn of decoder + d_model, + nhead, + dropout=attention_dropout_rate) + self.norm2 = LayerNorm(d_model, epsilon=epsilon) + self.dropout2 = Dropout(residual_dropout_rate) + + self.mlp = Mlp(in_features=d_model, + hidden_features=dim_feedforward, + act_layer=nn.ReLU, + drop=residual_dropout_rate) + + self.norm3 = LayerNorm(d_model, epsilon=epsilon) + + self.dropout3 = Dropout(residual_dropout_rate) + + def forward(self, tgt, memory=None, self_mask=None, cross_mask=None): + if self.with_self_attn: + tgt1 = self.self_attn(tgt, attn_mask=self_mask) + tgt = self.norm1(tgt + self.dropout1(tgt1)) + + if self.with_cross_attn: + tgt2 = self.cross_attn(tgt, key=memory, attn_mask=cross_mask) + tgt = self.norm2(tgt + self.dropout2(tgt2)) + tgt = self.norm3(tgt + self.dropout3(self.mlp(tgt))) + return tgt + + +class PositionalEncoding(nn.Layer): + """Inject some information about the relative or absolute position of the tokens + in the sequence. The positional encodings have the same dimension as + the embeddings, so that the two can be summed. Here, we use sine and cosine + functions of different frequencies. + .. math:: + \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) + \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) + \text{where pos is the word position and i is the embed idx) + Args: + d_model: the embed dim (required). + dropout: the dropout value (default=0.1). + max_len: the max. length of the incoming sequence (default=5000). + Examples: + >>> pos_encoder = PositionalEncoding(d_model) + """ + + def __init__(self, dropout, dim, max_len=5000): + super(PositionalEncoding, self).__init__() + self.dropout = nn.Dropout(p=dropout) + + pe = paddle.zeros([max_len, dim]) + position = paddle.arange(0, max_len, dtype=paddle.float32).unsqueeze(1) + div_term = paddle.exp( + paddle.arange(0, dim, 2).astype('float32') * + (-math.log(10000.0) / dim)) + pe[:, 0::2] = paddle.sin(position * div_term) + pe[:, 1::2] = paddle.cos(position * div_term) + pe = paddle.unsqueeze(pe, 0) + pe = paddle.transpose(pe, [1, 0, 2]) + self.register_buffer('pe', pe) + + def forward(self, x): + """Inputs of forward function + Args: + x: the sequence fed to the positional encoder model (required). + Shape: + x: [sequence length, batch size, embed dim] + output: [sequence length, batch size, embed dim] + Examples: + >>> output = pos_encoder(x) + """ + x = x.transpose([1, 0, 2]) + x = x + self.pe[:paddle.shape(x)[0], :] + return self.dropout(x).transpose([1, 0, 2]) + + +class PositionalEncoding_2d(nn.Layer): + """Inject some information about the relative or absolute position of the tokens + in the sequence. The positional encodings have the same dimension as + the embeddings, so that the two can be summed. Here, we use sine and cosine + functions of different frequencies. + .. math:: + \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) + \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) + \text{where pos is the word position and i is the embed idx) + Args: + d_model: the embed dim (required). + dropout: the dropout value (default=0.1). + max_len: the max. length of the incoming sequence (default=5000). + Examples: + >>> pos_encoder = PositionalEncoding(d_model) + """ + + def __init__(self, dropout, dim, max_len=5000): + super(PositionalEncoding_2d, self).__init__() + self.dropout = nn.Dropout(p=dropout) + + pe = paddle.zeros([max_len, dim]) + position = paddle.arange(0, max_len, dtype=paddle.float32).unsqueeze(1) + div_term = paddle.exp( + paddle.arange(0, dim, 2).astype('float32') * + (-math.log(10000.0) / dim)) + pe[:, 0::2] = paddle.sin(position * div_term) + pe[:, 1::2] = paddle.cos(position * div_term) + pe = paddle.transpose(paddle.unsqueeze(pe, 0), [1, 0, 2]) + self.register_buffer('pe', pe) + + self.avg_pool_1 = nn.AdaptiveAvgPool2D((1, 1)) + self.linear1 = nn.Linear(dim, dim) + self.linear1.weight.data.fill_(1.) + self.avg_pool_2 = nn.AdaptiveAvgPool2D((1, 1)) + self.linear2 = nn.Linear(dim, dim) + self.linear2.weight.data.fill_(1.) + + def forward(self, x): + """Inputs of forward function + Args: + x: the sequence fed to the positional encoder model (required). + Shape: + x: [sequence length, batch size, embed dim] + output: [sequence length, batch size, embed dim] + Examples: + >>> output = pos_encoder(x) + """ + w_pe = self.pe[:paddle.shape(x)[-1], :] + w1 = self.linear1(self.avg_pool_1(x).squeeze()).unsqueeze(0) + w_pe = w_pe * w1 + w_pe = paddle.transpose(w_pe, [1, 2, 0]) + w_pe = paddle.unsqueeze(w_pe, 2) + + h_pe = self.pe[:paddle.shape(x).shape[-2], :] + w2 = self.linear2(self.avg_pool_2(x).squeeze()).unsqueeze(0) + h_pe = h_pe * w2 + h_pe = paddle.transpose(h_pe, [1, 2, 0]) + h_pe = paddle.unsqueeze(h_pe, 3) + + x = x + w_pe + h_pe + x = paddle.transpose( + paddle.reshape(x, + [x.shape[0], x.shape[1], x.shape[2] * x.shape[3]]), + [2, 0, 1]) + + return self.dropout(x) + + +class Embeddings(nn.Layer): + def __init__(self, d_model, vocab, padding_idx=None, scale_embedding=True): + super(Embeddings, self).__init__() + self.embedding = nn.Embedding(vocab, d_model, padding_idx=padding_idx) + w0 = np.random.normal(0.0, d_model**-0.5, + (vocab, d_model)).astype(np.float32) + self.embedding.weight.set_value(w0) + self.d_model = d_model + self.scale_embedding = scale_embedding + + def forward(self, x): + if self.scale_embedding: + x = self.embedding(x) + return x * math.sqrt(self.d_model) + return self.embedding(x) + + +class Beam(): + """ Beam search """ + + def __init__(self, size, device=False): + + self.size = size + self._done = False + # The score for each translation on the beam. + self.scores = paddle.zeros((size, ), dtype=paddle.float32) + self.all_scores = [] + # The backpointers at each time-step. + self.prev_ks = [] + # The outputs at each time-step. + self.next_ys = [paddle.full((size, ), 0, dtype=paddle.int64)] + self.next_ys[0][0] = 2 + + def get_current_state(self): + "Get the outputs for the current timestep." + return self.get_tentative_hypothesis() + + def get_current_origin(self): + "Get the backpointers for the current timestep." + return self.prev_ks[-1] + + @property + def done(self): + return self._done + + def advance(self, word_prob): + "Update beam status and check if finished or not." + num_words = word_prob.shape[1] + + # Sum the previous scores. + if len(self.prev_ks) > 0: + beam_lk = word_prob + self.scores.unsqueeze(1).expand_as(word_prob) + else: + beam_lk = word_prob[0] + + flat_beam_lk = beam_lk.reshape([-1]) + best_scores, best_scores_id = flat_beam_lk.topk(self.size, 0, True, + True) # 1st sort + self.all_scores.append(self.scores) + self.scores = best_scores + # bestScoresId is flattened as a (beam x word) array, + # so we need to calculate which word and beam each score came from + prev_k = best_scores_id // num_words + self.prev_ks.append(prev_k) + self.next_ys.append(best_scores_id - prev_k * num_words) + # End condition is when top-of-beam is EOS. + if self.next_ys[-1][0] == 3: + self._done = True + self.all_scores.append(self.scores) + + return self._done + + def sort_scores(self): + "Sort the scores." + return self.scores, paddle.to_tensor( + [i for i in range(int(self.scores.shape[0]))], dtype='int32') + + def get_the_best_score_and_idx(self): + "Get the score of the best in the beam." + scores, ids = self.sort_scores() + return scores[1], ids[1] + + def get_tentative_hypothesis(self): + "Get the decoded sequence for the current timestep." + if len(self.next_ys) == 1: + dec_seq = self.next_ys[0].unsqueeze(1) + else: + _, keys = self.sort_scores() + hyps = [self.get_hypothesis(k) for k in keys] + hyps = [[2] + h for h in hyps] + dec_seq = paddle.to_tensor(hyps, dtype='int64') + return dec_seq + + def get_hypothesis(self, k): + """ Walk back to construct the full hypothesis. """ + hyp = [] + for j in range(len(self.prev_ks) - 1, -1, -1): + hyp.append(self.next_ys[j + 1][k]) + k = self.prev_ks[j][k] + return list(map(lambda x: x.item(), hyp[::-1])) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_pren_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_pren_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e4b3e9f82f60b7671e56ddfa02baff5e62f37b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_pren_head.py @@ -0,0 +1,34 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from paddle import nn +from paddle.nn import functional as F + + +class PRENHead(nn.Layer): + def __init__(self, in_channels, out_channels, **kwargs): + super(PRENHead, self).__init__() + self.linear = nn.Linear(in_channels, out_channels) + + def forward(self, x, targets=None): + predicts = self.linear(x) + + if not self.training: + predicts = F.softmax(predicts, axis=2) + + return predicts diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_robustscanner_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_robustscanner_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7956059ecfe01f27db364d3d748d6af24dad0aac --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_robustscanner_head.py @@ -0,0 +1,709 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/encoders/channel_reduction_encoder.py +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/decoders/robust_scanner_decoder.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + +class BaseDecoder(nn.Layer): + def __init__(self, **kwargs): + super().__init__() + + def forward_train(self, feat, out_enc, targets, img_metas): + raise NotImplementedError + + def forward_test(self, feat, out_enc, img_metas): + raise NotImplementedError + + def forward(self, + feat, + out_enc, + label=None, + valid_ratios=None, + word_positions=None, + train_mode=True): + self.train_mode = train_mode + + if train_mode: + return self.forward_train(feat, out_enc, label, valid_ratios, word_positions) + return self.forward_test(feat, out_enc, valid_ratios, word_positions) + +class ChannelReductionEncoder(nn.Layer): + """Change the channel number with a one by one convoluational layer. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + """ + + def __init__(self, + in_channels, + out_channels, + **kwargs): + super(ChannelReductionEncoder, self).__init__() + + self.layer = nn.Conv2D( + in_channels, out_channels, kernel_size=1, stride=1, padding=0, weight_attr=nn.initializer.XavierNormal()) + + def forward(self, feat): + """ + Args: + feat (Tensor): Image features with the shape of + :math:`(N, C_{in}, H, W)`. + + Returns: + Tensor: A tensor of shape :math:`(N, C_{out}, H, W)`. + """ + return self.layer(feat) + + +def masked_fill(x, mask, value): + y = paddle.full(x.shape, value, x.dtype) + return paddle.where(mask, y, x) + +class DotProductAttentionLayer(nn.Layer): + + def __init__(self, dim_model=None): + super().__init__() + + self.scale = dim_model**-0.5 if dim_model is not None else 1. + + def forward(self, query, key, value, h, w, valid_ratios=None): + query = paddle.transpose(query, (0, 2, 1)) + logits = paddle.matmul(query, key) * self.scale + n, c, t = logits.shape + # reshape to (n, c, h, w) + logits = paddle.reshape(logits, [n, c, h, w]) + if valid_ratios is not None: + # cal mask of attention weight + for i, valid_ratio in enumerate(valid_ratios): + valid_width = min(w, int(w * valid_ratio + 0.5)) + if valid_width < w: + logits[i, :, :, valid_width:] = float('-inf') + + # reshape to (n, c, h, w) + logits = paddle.reshape(logits, [n, c, t]) + weights = F.softmax(logits, axis=2) + value = paddle.transpose(value, (0, 2, 1)) + glimpse = paddle.matmul(weights, value) + glimpse = paddle.transpose(glimpse, (0, 2, 1)) + return glimpse + +class SequenceAttentionDecoder(BaseDecoder): + """Sequence attention decoder for RobustScanner. + + RobustScanner: `RobustScanner: Dynamically Enhancing Positional Clues for + Robust Text Recognition `_ + + Args: + num_classes (int): Number of output classes :math:`C`. + rnn_layers (int): Number of RNN layers. + dim_input (int): Dimension :math:`D_i` of input vector ``feat``. + dim_model (int): Dimension :math:`D_m` of the model. Should also be the + same as encoder output vector ``out_enc``. + max_seq_len (int): Maximum output sequence length :math:`T`. + start_idx (int): The index of ``. + mask (bool): Whether to mask input features according to + ``img_meta['valid_ratio']``. + padding_idx (int): The index of ``. + dropout (float): Dropout rate. + return_feature (bool): Return feature or logits as the result. + encode_value (bool): Whether to use the output of encoder ``out_enc`` + as `value` of attention layer. If False, the original feature + ``feat`` will be used. + + Warning: + This decoder will not predict the final class which is assumed to be + ``. Therefore, its output size is always :math:`C - 1`. `` + is also ignored by loss as specified in + :obj:`mmocr.models.textrecog.recognizer.EncodeDecodeRecognizer`. + """ + + def __init__(self, + num_classes=None, + rnn_layers=2, + dim_input=512, + dim_model=128, + max_seq_len=40, + start_idx=0, + mask=True, + padding_idx=None, + dropout=0, + return_feature=False, + encode_value=False): + super().__init__() + + self.num_classes = num_classes + self.dim_input = dim_input + self.dim_model = dim_model + self.return_feature = return_feature + self.encode_value = encode_value + self.max_seq_len = max_seq_len + self.start_idx = start_idx + self.mask = mask + + self.embedding = nn.Embedding( + self.num_classes, self.dim_model, padding_idx=padding_idx) + + self.sequence_layer = nn.LSTM( + input_size=dim_model, + hidden_size=dim_model, + num_layers=rnn_layers, + time_major=False, + dropout=dropout) + + self.attention_layer = DotProductAttentionLayer() + + self.prediction = None + if not self.return_feature: + pred_num_classes = num_classes - 1 + self.prediction = nn.Linear( + dim_model if encode_value else dim_input, pred_num_classes) + + def forward_train(self, feat, out_enc, targets, valid_ratios): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + targets (Tensor): a tensor of shape :math:`(N, T)`. Each element is the index of a + character. + valid_ratios (Tensor): valid length ratio of img. + Returns: + Tensor: A raw logit tensor of shape :math:`(N, T, C-1)` if + ``return_feature=False``. Otherwise it would be the hidden feature + before the prediction projection layer, whose shape is + :math:`(N, T, D_m)`. + """ + + tgt_embedding = self.embedding(targets) + + n, c_enc, h, w = out_enc.shape + assert c_enc == self.dim_model + _, c_feat, _, _ = feat.shape + assert c_feat == self.dim_input + _, len_q, c_q = tgt_embedding.shape + assert c_q == self.dim_model + assert len_q <= self.max_seq_len + + query, _ = self.sequence_layer(tgt_embedding) + query = paddle.transpose(query, (0, 2, 1)) + key = paddle.reshape(out_enc, [n, c_enc, h * w]) + if self.encode_value: + value = key + else: + value = paddle.reshape(feat, [n, c_feat, h * w]) + + attn_out = self.attention_layer(query, key, value, h, w, valid_ratios) + attn_out = paddle.transpose(attn_out, (0, 2, 1)) + + if self.return_feature: + return attn_out + + out = self.prediction(attn_out) + + return out + + def forward_test(self, feat, out_enc, valid_ratios): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + valid_ratios (Tensor): valid length ratio of img. + + Returns: + Tensor: The output logit sequence tensor of shape + :math:`(N, T, C-1)`. + """ + seq_len = self.max_seq_len + batch_size = feat.shape[0] + + decode_sequence = (paddle.ones((batch_size, seq_len), dtype='int64') * self.start_idx) + + outputs = [] + for i in range(seq_len): + step_out = self.forward_test_step(feat, out_enc, decode_sequence, + i, valid_ratios) + outputs.append(step_out) + max_idx = paddle.argmax(step_out, axis=1, keepdim=False) + if i < seq_len - 1: + decode_sequence[:, i + 1] = max_idx + + outputs = paddle.stack(outputs, 1) + + return outputs + + def forward_test_step(self, feat, out_enc, decode_sequence, current_step, + valid_ratios): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + decode_sequence (Tensor): Shape :math:`(N, T)`. The tensor that + stores history decoding result. + current_step (int): Current decoding step. + valid_ratios (Tensor): valid length ratio of img + + Returns: + Tensor: Shape :math:`(N, C-1)`. The logit tensor of predicted + tokens at current time step. + """ + + embed = self.embedding(decode_sequence) + + n, c_enc, h, w = out_enc.shape + assert c_enc == self.dim_model + _, c_feat, _, _ = feat.shape + assert c_feat == self.dim_input + _, _, c_q = embed.shape + assert c_q == self.dim_model + + query, _ = self.sequence_layer(embed) + query = paddle.transpose(query, (0, 2, 1)) + key = paddle.reshape(out_enc, [n, c_enc, h * w]) + if self.encode_value: + value = key + else: + value = paddle.reshape(feat, [n, c_feat, h * w]) + + # [n, c, l] + attn_out = self.attention_layer(query, key, value, h, w, valid_ratios) + out = attn_out[:, :, current_step] + + if self.return_feature: + return out + + out = self.prediction(out) + out = F.softmax(out, dim=-1) + + return out + + +class PositionAwareLayer(nn.Layer): + + def __init__(self, dim_model, rnn_layers=2): + super().__init__() + + self.dim_model = dim_model + + self.rnn = nn.LSTM( + input_size=dim_model, + hidden_size=dim_model, + num_layers=rnn_layers, + time_major=False) + + self.mixer = nn.Sequential( + nn.Conv2D( + dim_model, dim_model, kernel_size=3, stride=1, padding=1), + nn.ReLU(), + nn.Conv2D( + dim_model, dim_model, kernel_size=3, stride=1, padding=1)) + + def forward(self, img_feature): + n, c, h, w = img_feature.shape + rnn_input = paddle.transpose(img_feature, (0, 2, 3, 1)) + rnn_input = paddle.reshape(rnn_input, (n * h, w, c)) + rnn_output, _ = self.rnn(rnn_input) + rnn_output = paddle.reshape(rnn_output, (n, h, w, c)) + rnn_output = paddle.transpose(rnn_output, (0, 3, 1, 2)) + out = self.mixer(rnn_output) + return out + + +class PositionAttentionDecoder(BaseDecoder): + """Position attention decoder for RobustScanner. + + RobustScanner: `RobustScanner: Dynamically Enhancing Positional Clues for + Robust Text Recognition `_ + + Args: + num_classes (int): Number of output classes :math:`C`. + rnn_layers (int): Number of RNN layers. + dim_input (int): Dimension :math:`D_i` of input vector ``feat``. + dim_model (int): Dimension :math:`D_m` of the model. Should also be the + same as encoder output vector ``out_enc``. + max_seq_len (int): Maximum output sequence length :math:`T`. + mask (bool): Whether to mask input features according to + ``img_meta['valid_ratio']``. + return_feature (bool): Return feature or logits as the result. + encode_value (bool): Whether to use the output of encoder ``out_enc`` + as `value` of attention layer. If False, the original feature + ``feat`` will be used. + + Warning: + This decoder will not predict the final class which is assumed to be + ``. Therefore, its output size is always :math:`C - 1`. `` + is also ignored by loss + + """ + + def __init__(self, + num_classes=None, + rnn_layers=2, + dim_input=512, + dim_model=128, + max_seq_len=40, + mask=True, + return_feature=False, + encode_value=False): + super().__init__() + + self.num_classes = num_classes + self.dim_input = dim_input + self.dim_model = dim_model + self.max_seq_len = max_seq_len + self.return_feature = return_feature + self.encode_value = encode_value + self.mask = mask + + self.embedding = nn.Embedding(self.max_seq_len + 1, self.dim_model) + + self.position_aware_module = PositionAwareLayer( + self.dim_model, rnn_layers) + + self.attention_layer = DotProductAttentionLayer() + + self.prediction = None + if not self.return_feature: + pred_num_classes = num_classes - 1 + self.prediction = nn.Linear( + dim_model if encode_value else dim_input, pred_num_classes) + + def _get_position_index(self, length, batch_size): + position_index_list = [] + for i in range(batch_size): + position_index = paddle.arange(0, end=length, step=1, dtype='int64') + position_index_list.append(position_index) + batch_position_index = paddle.stack(position_index_list, axis=0) + return batch_position_index + + def forward_train(self, feat, out_enc, targets, valid_ratios, position_index): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + targets (dict): A dict with the key ``padded_targets``, a + tensor of shape :math:`(N, T)`. Each element is the index of a + character. + valid_ratios (Tensor): valid length ratio of img. + position_index (Tensor): The position of each word. + + Returns: + Tensor: A raw logit tensor of shape :math:`(N, T, C-1)` if + ``return_feature=False``. Otherwise it will be the hidden feature + before the prediction projection layer, whose shape is + :math:`(N, T, D_m)`. + """ + n, c_enc, h, w = out_enc.shape + assert c_enc == self.dim_model + _, c_feat, _, _ = feat.shape + assert c_feat == self.dim_input + _, len_q = targets.shape + assert len_q <= self.max_seq_len + + position_out_enc = self.position_aware_module(out_enc) + + query = self.embedding(position_index) + query = paddle.transpose(query, (0, 2, 1)) + key = paddle.reshape(position_out_enc, (n, c_enc, h * w)) + if self.encode_value: + value = paddle.reshape(out_enc,(n, c_enc, h * w)) + else: + value = paddle.reshape(feat,(n, c_feat, h * w)) + + attn_out = self.attention_layer(query, key, value, h, w, valid_ratios) + attn_out = paddle.transpose(attn_out, (0, 2, 1)) # [n, len_q, dim_v] + + if self.return_feature: + return attn_out + + return self.prediction(attn_out) + + def forward_test(self, feat, out_enc, valid_ratios, position_index): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + valid_ratios (Tensor): valid length ratio of img + position_index (Tensor): The position of each word. + + Returns: + Tensor: A raw logit tensor of shape :math:`(N, T, C-1)` if + ``return_feature=False``. Otherwise it would be the hidden feature + before the prediction projection layer, whose shape is + :math:`(N, T, D_m)`. + """ + n, c_enc, h, w = out_enc.shape + assert c_enc == self.dim_model + _, c_feat, _, _ = feat.shape + assert c_feat == self.dim_input + + position_out_enc = self.position_aware_module(out_enc) + + query = self.embedding(position_index) + query = paddle.transpose(query, (0, 2, 1)) + key = paddle.reshape(position_out_enc, (n, c_enc, h * w)) + if self.encode_value: + value = paddle.reshape(out_enc,(n, c_enc, h * w)) + else: + value = paddle.reshape(feat,(n, c_feat, h * w)) + + attn_out = self.attention_layer(query, key, value, h, w, valid_ratios) + attn_out = paddle.transpose(attn_out, (0, 2, 1)) # [n, len_q, dim_v] + + if self.return_feature: + return attn_out + + return self.prediction(attn_out) + +class RobustScannerFusionLayer(nn.Layer): + + def __init__(self, dim_model, dim=-1): + super(RobustScannerFusionLayer, self).__init__() + + self.dim_model = dim_model + self.dim = dim + self.linear_layer = nn.Linear(dim_model * 2, dim_model * 2) + + def forward(self, x0, x1): + assert x0.shape == x1.shape + fusion_input = paddle.concat([x0, x1], self.dim) + output = self.linear_layer(fusion_input) + output = F.glu(output, self.dim) + return output + +class RobustScannerDecoder(BaseDecoder): + """Decoder for RobustScanner. + + RobustScanner: `RobustScanner: Dynamically Enhancing Positional Clues for + Robust Text Recognition `_ + + Args: + num_classes (int): Number of output classes :math:`C`. + dim_input (int): Dimension :math:`D_i` of input vector ``feat``. + dim_model (int): Dimension :math:`D_m` of the model. Should also be the + same as encoder output vector ``out_enc``. + max_seq_len (int): Maximum output sequence length :math:`T`. + start_idx (int): The index of ``. + mask (bool): Whether to mask input features according to + ``img_meta['valid_ratio']``. + padding_idx (int): The index of ``. + encode_value (bool): Whether to use the output of encoder ``out_enc`` + as `value` of attention layer. If False, the original feature + ``feat`` will be used. + + Warning: + This decoder will not predict the final class which is assumed to be + ``. Therefore, its output size is always :math:`C - 1`. `` + is also ignored by loss as specified in + :obj:`mmocr.models.textrecog.recognizer.EncodeDecodeRecognizer`. + """ + + def __init__(self, + num_classes=None, + dim_input=512, + dim_model=128, + hybrid_decoder_rnn_layers=2, + hybrid_decoder_dropout=0, + position_decoder_rnn_layers=2, + max_seq_len=40, + start_idx=0, + mask=True, + padding_idx=None, + encode_value=False): + super().__init__() + self.num_classes = num_classes + self.dim_input = dim_input + self.dim_model = dim_model + self.max_seq_len = max_seq_len + self.encode_value = encode_value + self.start_idx = start_idx + self.padding_idx = padding_idx + self.mask = mask + + # init hybrid decoder + self.hybrid_decoder = SequenceAttentionDecoder( + num_classes=num_classes, + rnn_layers=hybrid_decoder_rnn_layers, + dim_input=dim_input, + dim_model=dim_model, + max_seq_len=max_seq_len, + start_idx=start_idx, + mask=mask, + padding_idx=padding_idx, + dropout=hybrid_decoder_dropout, + encode_value=encode_value, + return_feature=True + ) + + # init position decoder + self.position_decoder = PositionAttentionDecoder( + num_classes=num_classes, + rnn_layers=position_decoder_rnn_layers, + dim_input=dim_input, + dim_model=dim_model, + max_seq_len=max_seq_len, + mask=mask, + encode_value=encode_value, + return_feature=True + ) + + + self.fusion_module = RobustScannerFusionLayer( + self.dim_model if encode_value else dim_input) + + pred_num_classes = num_classes - 1 + self.prediction = nn.Linear(dim_model if encode_value else dim_input, + pred_num_classes) + + def forward_train(self, feat, out_enc, target, valid_ratios, word_positions): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + target (dict): A dict with the key ``padded_targets``, a + tensor of shape :math:`(N, T)`. Each element is the index of a + character. + valid_ratios (Tensor): + word_positions (Tensor): The position of each word. + + Returns: + Tensor: A raw logit tensor of shape :math:`(N, T, C-1)`. + """ + hybrid_glimpse = self.hybrid_decoder.forward_train( + feat, out_enc, target, valid_ratios) + position_glimpse = self.position_decoder.forward_train( + feat, out_enc, target, valid_ratios, word_positions) + + fusion_out = self.fusion_module(hybrid_glimpse, position_glimpse) + + out = self.prediction(fusion_out) + + return out + + def forward_test(self, feat, out_enc, valid_ratios, word_positions): + """ + Args: + feat (Tensor): Tensor of shape :math:`(N, D_i, H, W)`. + out_enc (Tensor): Encoder output of shape + :math:`(N, D_m, H, W)`. + valid_ratios (Tensor): + word_positions (Tensor): The position of each word. + Returns: + Tensor: The output logit sequence tensor of shape + :math:`(N, T, C-1)`. + """ + seq_len = self.max_seq_len + batch_size = feat.shape[0] + + decode_sequence = (paddle.ones((batch_size, seq_len), dtype='int64') * self.start_idx) + + position_glimpse = self.position_decoder.forward_test( + feat, out_enc, valid_ratios, word_positions) + + outputs = [] + for i in range(seq_len): + hybrid_glimpse_step = self.hybrid_decoder.forward_test_step( + feat, out_enc, decode_sequence, i, valid_ratios) + + fusion_out = self.fusion_module(hybrid_glimpse_step, + position_glimpse[:, i, :]) + + char_out = self.prediction(fusion_out) + char_out = F.softmax(char_out, -1) + outputs.append(char_out) + max_idx = paddle.argmax(char_out, axis=1, keepdim=False) + if i < seq_len - 1: + decode_sequence[:, i + 1] = max_idx + + outputs = paddle.stack(outputs, 1) + + return outputs + +class RobustScannerHead(nn.Layer): + def __init__(self, + out_channels, # 90 + unknown + start + padding + in_channels, + enc_outchannles=128, + hybrid_dec_rnn_layers=2, + hybrid_dec_dropout=0, + position_dec_rnn_layers=2, + start_idx=0, + max_text_length=40, + mask=True, + padding_idx=None, + encode_value=False, + **kwargs): + super(RobustScannerHead, self).__init__() + + # encoder module + self.encoder = ChannelReductionEncoder( + in_channels=in_channels, out_channels=enc_outchannles) + + # decoder module + self.decoder =RobustScannerDecoder( + num_classes=out_channels, + dim_input=in_channels, + dim_model=enc_outchannles, + hybrid_decoder_rnn_layers=hybrid_dec_rnn_layers, + hybrid_decoder_dropout=hybrid_dec_dropout, + position_decoder_rnn_layers=position_dec_rnn_layers, + max_seq_len=max_text_length, + start_idx=start_idx, + mask=mask, + padding_idx=padding_idx, + encode_value=encode_value) + + def forward(self, inputs, targets=None): + ''' + targets: [label, valid_ratio, word_positions] + ''' + out_enc = self.encoder(inputs) + valid_ratios = None + word_positions = targets[-1] + + if len(targets) > 1: + valid_ratios = targets[-2] + + if self.training: + label = targets[0] # label + label = paddle.to_tensor(label, dtype='int64') + final_out = self.decoder( + inputs, out_enc, label, valid_ratios, word_positions) + if not self.training: + final_out = self.decoder( + inputs, + out_enc, + label=None, + valid_ratios=valid_ratios, + word_positions=word_positions, + train_mode=False) + return final_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_sar_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_sar_head.py new file mode 100644 index 0000000000000000000000000000000000000000..5e64cae85afafc555f2519ed6dd3f05eafff7ea2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_sar_head.py @@ -0,0 +1,410 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/encoders/sar_encoder.py +https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/decoders/sar_decoder.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F + + +class SAREncoder(nn.Layer): + """ + Args: + enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. + enc_drop_rnn (float): Dropout probability of RNN layer in encoder. + enc_gru (bool): If True, use GRU, else LSTM in encoder. + d_model (int): Dim of channels from backbone. + d_enc (int): Dim of encoder RNN layer. + mask (bool): If True, mask padding in RNN sequence. + """ + + def __init__(self, + enc_bi_rnn=False, + enc_drop_rnn=0.1, + enc_gru=False, + d_model=512, + d_enc=512, + mask=True, + **kwargs): + super().__init__() + assert isinstance(enc_bi_rnn, bool) + assert isinstance(enc_drop_rnn, (int, float)) + assert 0 <= enc_drop_rnn < 1.0 + assert isinstance(enc_gru, bool) + assert isinstance(d_model, int) + assert isinstance(d_enc, int) + assert isinstance(mask, bool) + + self.enc_bi_rnn = enc_bi_rnn + self.enc_drop_rnn = enc_drop_rnn + self.mask = mask + + # LSTM Encoder + if enc_bi_rnn: + direction = 'bidirectional' + else: + direction = 'forward' + kwargs = dict( + input_size=d_model, + hidden_size=d_enc, + num_layers=2, + time_major=False, + dropout=enc_drop_rnn, + direction=direction) + if enc_gru: + self.rnn_encoder = nn.GRU(**kwargs) + else: + self.rnn_encoder = nn.LSTM(**kwargs) + + # global feature transformation + encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1) + self.linear = nn.Linear(encoder_rnn_out_size, encoder_rnn_out_size) + + def forward(self, feat, img_metas=None): + if img_metas is not None: + assert len(img_metas[0]) == paddle.shape(feat)[0] + + valid_ratios = None + if img_metas is not None and self.mask: + valid_ratios = img_metas[-1] + + h_feat = feat.shape[2] # bsz c h w + feat_v = F.max_pool2d( + feat, kernel_size=(h_feat, 1), stride=1, padding=0) + feat_v = feat_v.squeeze(2) # bsz * C * W + feat_v = paddle.transpose(feat_v, perm=[0, 2, 1]) # bsz * W * C + holistic_feat = self.rnn_encoder(feat_v)[0] # bsz * T * C + + if valid_ratios is not None: + valid_hf = [] + T = paddle.shape(holistic_feat)[1] + for i in range(paddle.shape(valid_ratios)[0]): + valid_step = paddle.minimum( + T, paddle.ceil(valid_ratios[i] * T).astype('int32')) - 1 + valid_hf.append(holistic_feat[i, valid_step, :]) + valid_hf = paddle.stack(valid_hf, axis=0) + else: + valid_hf = holistic_feat[:, -1, :] # bsz * C + holistic_feat = self.linear(valid_hf) # bsz * C + + return holistic_feat + + +class BaseDecoder(nn.Layer): + def __init__(self, **kwargs): + super().__init__() + + def forward_train(self, feat, out_enc, targets, img_metas): + raise NotImplementedError + + def forward_test(self, feat, out_enc, img_metas): + raise NotImplementedError + + def forward(self, + feat, + out_enc, + label=None, + img_metas=None, + train_mode=True): + self.train_mode = train_mode + + if train_mode: + return self.forward_train(feat, out_enc, label, img_metas) + return self.forward_test(feat, out_enc, img_metas) + + +class ParallelSARDecoder(BaseDecoder): + """ + Args: + out_channels (int): Output class number. + enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. + dec_bi_rnn (bool): If True, use bidirectional RNN in decoder. + dec_drop_rnn (float): Dropout of RNN layer in decoder. + dec_gru (bool): If True, use GRU, else LSTM in decoder. + d_model (int): Dim of channels from backbone. + d_enc (int): Dim of encoder RNN layer. + d_k (int): Dim of channels of attention module. + pred_dropout (float): Dropout probability of prediction layer. + max_seq_len (int): Maximum sequence length for decoding. + mask (bool): If True, mask padding in feature map. + start_idx (int): Index of start token. + padding_idx (int): Index of padding token. + pred_concat (bool): If True, concat glimpse feature from + attention with holistic feature and hidden state. + """ + + def __init__( + self, + out_channels, # 90 + unknown + start + padding + enc_bi_rnn=False, + dec_bi_rnn=False, + dec_drop_rnn=0.0, + dec_gru=False, + d_model=512, + d_enc=512, + d_k=64, + pred_dropout=0.1, + max_text_length=30, + mask=True, + pred_concat=True, + **kwargs): + super().__init__() + + self.num_classes = out_channels + self.enc_bi_rnn = enc_bi_rnn + self.d_k = d_k + self.start_idx = out_channels - 2 + self.padding_idx = out_channels - 1 + self.max_seq_len = max_text_length + self.mask = mask + self.pred_concat = pred_concat + + encoder_rnn_out_size = d_enc * (int(enc_bi_rnn) + 1) + decoder_rnn_out_size = encoder_rnn_out_size * (int(dec_bi_rnn) + 1) + + # 2D attention layer + self.conv1x1_1 = nn.Linear(decoder_rnn_out_size, d_k) + self.conv3x3_1 = nn.Conv2D( + d_model, d_k, kernel_size=3, stride=1, padding=1) + self.conv1x1_2 = nn.Linear(d_k, 1) + + # Decoder RNN layer + if dec_bi_rnn: + direction = 'bidirectional' + else: + direction = 'forward' + + kwargs = dict( + input_size=encoder_rnn_out_size, + hidden_size=encoder_rnn_out_size, + num_layers=2, + time_major=False, + dropout=dec_drop_rnn, + direction=direction) + if dec_gru: + self.rnn_decoder = nn.GRU(**kwargs) + else: + self.rnn_decoder = nn.LSTM(**kwargs) + + # Decoder input embedding + self.embedding = nn.Embedding( + self.num_classes, + encoder_rnn_out_size, + padding_idx=self.padding_idx) + + # Prediction layer + self.pred_dropout = nn.Dropout(pred_dropout) + pred_num_classes = self.num_classes - 1 + if pred_concat: + fc_in_channel = decoder_rnn_out_size + d_model + encoder_rnn_out_size + else: + fc_in_channel = d_model + self.prediction = nn.Linear(fc_in_channel, pred_num_classes) + + def _2d_attention(self, + decoder_input, + feat, + holistic_feat, + valid_ratios=None): + + y = self.rnn_decoder(decoder_input)[0] + # y: bsz * (seq_len + 1) * hidden_size + + attn_query = self.conv1x1_1(y) # bsz * (seq_len + 1) * attn_size + bsz, seq_len, attn_size = attn_query.shape + attn_query = paddle.unsqueeze(attn_query, axis=[3, 4]) + # (bsz, seq_len + 1, attn_size, 1, 1) + + attn_key = self.conv3x3_1(feat) + # bsz * attn_size * h * w + attn_key = attn_key.unsqueeze(1) + # bsz * 1 * attn_size * h * w + + attn_weight = paddle.tanh(paddle.add(attn_key, attn_query)) + + # bsz * (seq_len + 1) * attn_size * h * w + attn_weight = paddle.transpose(attn_weight, perm=[0, 1, 3, 4, 2]) + # bsz * (seq_len + 1) * h * w * attn_size + attn_weight = self.conv1x1_2(attn_weight) + # bsz * (seq_len + 1) * h * w * 1 + bsz, T, h, w, c = paddle.shape(attn_weight) + assert c == 1 + + if valid_ratios is not None: + # cal mask of attention weight + for i in range(paddle.shape(valid_ratios)[0]): + valid_width = paddle.minimum( + w, paddle.ceil(valid_ratios[i] * w).astype("int32")) + if valid_width < w: + attn_weight[i, :, :, valid_width:, :] = float('-inf') + + attn_weight = paddle.reshape(attn_weight, [bsz, T, -1]) + attn_weight = F.softmax(attn_weight, axis=-1) + + attn_weight = paddle.reshape(attn_weight, [bsz, T, h, w, c]) + attn_weight = paddle.transpose(attn_weight, perm=[0, 1, 4, 2, 3]) + # attn_weight: bsz * T * c * h * w + # feat: bsz * c * h * w + attn_feat = paddle.sum(paddle.multiply(feat.unsqueeze(1), attn_weight), + (3, 4), + keepdim=False) + # bsz * (seq_len + 1) * C + + # Linear transformation + if self.pred_concat: + hf_c = holistic_feat.shape[-1] + holistic_feat = paddle.expand( + holistic_feat, shape=[bsz, seq_len, hf_c]) + y = self.prediction(paddle.concat((y, attn_feat, holistic_feat), 2)) + else: + y = self.prediction(attn_feat) + # bsz * (seq_len + 1) * num_classes + if self.train_mode: + y = self.pred_dropout(y) + + return y + + def forward_train(self, feat, out_enc, label, img_metas): + ''' + img_metas: [label, valid_ratio] + ''' + if img_metas is not None: + assert paddle.shape(img_metas[0])[0] == paddle.shape(feat)[0] + + valid_ratios = None + if img_metas is not None and self.mask: + valid_ratios = img_metas[-1] + + lab_embedding = self.embedding(label) + # bsz * seq_len * emb_dim + out_enc = out_enc.unsqueeze(1) + # bsz * 1 * emb_dim + in_dec = paddle.concat((out_enc, lab_embedding), axis=1) + # bsz * (seq_len + 1) * C + out_dec = self._2d_attention( + in_dec, feat, out_enc, valid_ratios=valid_ratios) + + return out_dec[:, 1:, :] # bsz * seq_len * num_classes + + def forward_test(self, feat, out_enc, img_metas): + if img_metas is not None: + assert len(img_metas[0]) == feat.shape[0] + + valid_ratios = None + if img_metas is not None and self.mask: + valid_ratios = img_metas[-1] + + seq_len = self.max_seq_len + bsz = feat.shape[0] + start_token = paddle.full( + (bsz, ), fill_value=self.start_idx, dtype='int64') + # bsz + start_token = self.embedding(start_token) + # bsz * emb_dim + emb_dim = start_token.shape[1] + start_token = start_token.unsqueeze(1) + start_token = paddle.expand(start_token, shape=[bsz, seq_len, emb_dim]) + # bsz * seq_len * emb_dim + out_enc = out_enc.unsqueeze(1) + # bsz * 1 * emb_dim + decoder_input = paddle.concat((out_enc, start_token), axis=1) + # bsz * (seq_len + 1) * emb_dim + + outputs = [] + for i in range(1, seq_len + 1): + decoder_output = self._2d_attention( + decoder_input, feat, out_enc, valid_ratios=valid_ratios) + char_output = decoder_output[:, i, :] # bsz * num_classes + char_output = F.softmax(char_output, -1) + outputs.append(char_output) + max_idx = paddle.argmax(char_output, axis=1, keepdim=False) + char_embedding = self.embedding(max_idx) # bsz * emb_dim + if i < seq_len: + decoder_input[:, i + 1, :] = char_embedding + + outputs = paddle.stack(outputs, 1) # bsz * seq_len * num_classes + + return outputs + + +class SARHead(nn.Layer): + def __init__(self, + in_channels, + out_channels, + enc_dim=512, + max_text_length=30, + enc_bi_rnn=False, + enc_drop_rnn=0.1, + enc_gru=False, + dec_bi_rnn=False, + dec_drop_rnn=0.0, + dec_gru=False, + d_k=512, + pred_dropout=0.1, + pred_concat=True, + **kwargs): + super(SARHead, self).__init__() + + # encoder module + self.encoder = SAREncoder( + enc_bi_rnn=enc_bi_rnn, + enc_drop_rnn=enc_drop_rnn, + enc_gru=enc_gru, + d_model=in_channels, + d_enc=enc_dim) + + # decoder module + self.decoder = ParallelSARDecoder( + out_channels=out_channels, + enc_bi_rnn=enc_bi_rnn, + dec_bi_rnn=dec_bi_rnn, + dec_drop_rnn=dec_drop_rnn, + dec_gru=dec_gru, + d_model=in_channels, + d_enc=enc_dim, + d_k=d_k, + pred_dropout=pred_dropout, + max_text_length=max_text_length, + pred_concat=pred_concat) + + def forward(self, feat, targets=None): + ''' + img_metas: [label, valid_ratio] + ''' + holistic_feat = self.encoder(feat, targets) # bsz c + + if self.training: + label = targets[0] # label + final_out = self.decoder( + feat, holistic_feat, label, img_metas=targets) + else: + final_out = self.decoder( + feat, + holistic_feat, + label=None, + img_metas=targets, + train_mode=False) + # (bsz, seq_len, num_classes) + + return final_out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_spin_att_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_spin_att_head.py new file mode 100644 index 0000000000000000000000000000000000000000..86e35e4339d8e1006cfe43d6cf4f2f7d231082c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_spin_att_head.py @@ -0,0 +1,115 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +""" +This code is refer from: +https://github.com/hikopensource/DAVAR-Lab-OCR/davarocr/davar_rcg/models/sequence_heads/att_head.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F + + +class SPINAttentionHead(nn.Layer): + def __init__(self, in_channels, out_channels, hidden_size, **kwargs): + super(SPINAttentionHead, self).__init__() + self.input_size = in_channels + self.hidden_size = hidden_size + self.num_classes = out_channels + + self.attention_cell = AttentionLSTMCell( + in_channels, hidden_size, out_channels, use_gru=False) + self.generator = nn.Linear(hidden_size, out_channels) + + def _char_to_onehot(self, input_char, onehot_dim): + input_ont_hot = F.one_hot(input_char, onehot_dim) + return input_ont_hot + + def forward(self, inputs, targets=None, batch_max_length=25): + batch_size = paddle.shape(inputs)[0] + num_steps = batch_max_length + 1 # +1 for [sos] at end of sentence + + hidden = (paddle.zeros((batch_size, self.hidden_size)), + paddle.zeros((batch_size, self.hidden_size))) + output_hiddens = [] + if self.training: # for train + targets = targets[0] + for i in range(num_steps): + char_onehots = self._char_to_onehot( + targets[:, i], onehot_dim=self.num_classes) + (outputs, hidden), alpha = self.attention_cell(hidden, inputs, + char_onehots) + output_hiddens.append(paddle.unsqueeze(outputs, axis=1)) + output = paddle.concat(output_hiddens, axis=1) + probs = self.generator(output) + else: + targets = paddle.zeros(shape=[batch_size], dtype="int32") + probs = None + char_onehots = None + outputs = None + alpha = None + + for i in range(num_steps): + char_onehots = self._char_to_onehot( + targets, onehot_dim=self.num_classes) + (outputs, hidden), alpha = self.attention_cell(hidden, inputs, + char_onehots) + probs_step = self.generator(outputs) + if probs is None: + probs = paddle.unsqueeze(probs_step, axis=1) + else: + probs = paddle.concat( + [probs, paddle.unsqueeze( + probs_step, axis=1)], axis=1) + next_input = probs_step.argmax(axis=1) + targets = next_input + if not self.training: + probs = paddle.nn.functional.softmax(probs, axis=2) + return probs + + +class AttentionLSTMCell(nn.Layer): + def __init__(self, input_size, hidden_size, num_embeddings, use_gru=False): + super(AttentionLSTMCell, self).__init__() + self.i2h = nn.Linear(input_size, hidden_size, bias_attr=False) + self.h2h = nn.Linear(hidden_size, hidden_size) + self.score = nn.Linear(hidden_size, 1, bias_attr=False) + if not use_gru: + self.rnn = nn.LSTMCell( + input_size=input_size + num_embeddings, hidden_size=hidden_size) + else: + self.rnn = nn.GRUCell( + input_size=input_size + num_embeddings, hidden_size=hidden_size) + + self.hidden_size = hidden_size + + def forward(self, prev_hidden, batch_H, char_onehots): + batch_H_proj = self.i2h(batch_H) + prev_hidden_proj = paddle.unsqueeze(self.h2h(prev_hidden[0]), axis=1) + res = paddle.add(batch_H_proj, prev_hidden_proj) + res = paddle.tanh(res) + e = self.score(res) + + alpha = F.softmax(e, axis=1) + alpha = paddle.transpose(alpha, [0, 2, 1]) + context = paddle.squeeze(paddle.mm(alpha, batch_H), axis=1) + concat_context = paddle.concat([context, char_onehots], 1) + cur_hidden = self.rnn(concat_context, prev_hidden) + + return cur_hidden, alpha diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_srn_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_srn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1070d8cd648eb686c0a2e66df092b7dc6de29c42 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_srn_head.py @@ -0,0 +1,278 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np +from .self_attention import WrapEncoderForFeature +from .self_attention import WrapEncoder +from paddle.static import Program +from ppocr.modeling.backbones.rec_resnet_fpn import ResNetFPN + +from collections import OrderedDict +gradient_clip = 10 + + +class PVAM(nn.Layer): + def __init__(self, in_channels, char_num, max_text_length, num_heads, + num_encoder_tus, hidden_dims): + super(PVAM, self).__init__() + self.char_num = char_num + self.max_length = max_text_length + self.num_heads = num_heads + self.num_encoder_TUs = num_encoder_tus + self.hidden_dims = hidden_dims + # Transformer encoder + t = 256 + c = 512 + self.wrap_encoder_for_feature = WrapEncoderForFeature( + src_vocab_size=1, + max_length=t, + n_layer=self.num_encoder_TUs, + n_head=self.num_heads, + d_key=int(self.hidden_dims / self.num_heads), + d_value=int(self.hidden_dims / self.num_heads), + d_model=self.hidden_dims, + d_inner_hid=self.hidden_dims, + prepostprocess_dropout=0.1, + attention_dropout=0.1, + relu_dropout=0.1, + preprocess_cmd="n", + postprocess_cmd="da", + weight_sharing=True) + + # PVAM + self.flatten0 = paddle.nn.Flatten(start_axis=0, stop_axis=1) + self.fc0 = paddle.nn.Linear( + in_features=in_channels, + out_features=in_channels, ) + self.emb = paddle.nn.Embedding( + num_embeddings=self.max_length, embedding_dim=in_channels) + self.flatten1 = paddle.nn.Flatten(start_axis=0, stop_axis=2) + self.fc1 = paddle.nn.Linear( + in_features=in_channels, out_features=1, bias_attr=False) + + def forward(self, inputs, encoder_word_pos, gsrm_word_pos): + b, c, h, w = inputs.shape + conv_features = paddle.reshape(inputs, shape=[-1, c, h * w]) + conv_features = paddle.transpose(conv_features, perm=[0, 2, 1]) + # transformer encoder + b, t, c = conv_features.shape + + enc_inputs = [conv_features, encoder_word_pos, None] + word_features = self.wrap_encoder_for_feature(enc_inputs) + + # pvam + b, t, c = word_features.shape + word_features = self.fc0(word_features) + word_features_ = paddle.reshape(word_features, [-1, 1, t, c]) + word_features_ = paddle.tile(word_features_, [1, self.max_length, 1, 1]) + word_pos_feature = self.emb(gsrm_word_pos) + word_pos_feature_ = paddle.reshape(word_pos_feature, + [-1, self.max_length, 1, c]) + word_pos_feature_ = paddle.tile(word_pos_feature_, [1, 1, t, 1]) + y = word_pos_feature_ + word_features_ + y = F.tanh(y) + attention_weight = self.fc1(y) + attention_weight = paddle.reshape( + attention_weight, shape=[-1, self.max_length, t]) + attention_weight = F.softmax(attention_weight, axis=-1) + pvam_features = paddle.matmul(attention_weight, + word_features) #[b, max_length, c] + return pvam_features + + +class GSRM(nn.Layer): + def __init__(self, in_channels, char_num, max_text_length, num_heads, + num_encoder_tus, num_decoder_tus, hidden_dims): + super(GSRM, self).__init__() + self.char_num = char_num + self.max_length = max_text_length + self.num_heads = num_heads + self.num_encoder_TUs = num_encoder_tus + self.num_decoder_TUs = num_decoder_tus + self.hidden_dims = hidden_dims + + self.fc0 = paddle.nn.Linear( + in_features=in_channels, out_features=self.char_num) + self.wrap_encoder0 = WrapEncoder( + src_vocab_size=self.char_num + 1, + max_length=self.max_length, + n_layer=self.num_decoder_TUs, + n_head=self.num_heads, + d_key=int(self.hidden_dims / self.num_heads), + d_value=int(self.hidden_dims / self.num_heads), + d_model=self.hidden_dims, + d_inner_hid=self.hidden_dims, + prepostprocess_dropout=0.1, + attention_dropout=0.1, + relu_dropout=0.1, + preprocess_cmd="n", + postprocess_cmd="da", + weight_sharing=True) + + self.wrap_encoder1 = WrapEncoder( + src_vocab_size=self.char_num + 1, + max_length=self.max_length, + n_layer=self.num_decoder_TUs, + n_head=self.num_heads, + d_key=int(self.hidden_dims / self.num_heads), + d_value=int(self.hidden_dims / self.num_heads), + d_model=self.hidden_dims, + d_inner_hid=self.hidden_dims, + prepostprocess_dropout=0.1, + attention_dropout=0.1, + relu_dropout=0.1, + preprocess_cmd="n", + postprocess_cmd="da", + weight_sharing=True) + + self.mul = lambda x: paddle.matmul(x=x, + y=self.wrap_encoder0.prepare_decoder.emb0.weight, + transpose_y=True) + + def forward(self, inputs, gsrm_word_pos, gsrm_slf_attn_bias1, + gsrm_slf_attn_bias2): + # ===== GSRM Visual-to-semantic embedding block ===== + b, t, c = inputs.shape + pvam_features = paddle.reshape(inputs, [-1, c]) + word_out = self.fc0(pvam_features) + word_ids = paddle.argmax(F.softmax(word_out), axis=1) + word_ids = paddle.reshape(x=word_ids, shape=[-1, t, 1]) + + #===== GSRM Semantic reasoning block ===== + """ + This module is achieved through bi-transformers, + ngram_feature1 is the froward one, ngram_fetaure2 is the backward one + """ + pad_idx = self.char_num + + word1 = paddle.cast(word_ids, "float32") + word1 = F.pad(word1, [1, 0], value=1.0 * pad_idx, data_format="NLC") + word1 = paddle.cast(word1, "int64") + word1 = word1[:, :-1, :] + word2 = word_ids + + enc_inputs_1 = [word1, gsrm_word_pos, gsrm_slf_attn_bias1] + enc_inputs_2 = [word2, gsrm_word_pos, gsrm_slf_attn_bias2] + + gsrm_feature1 = self.wrap_encoder0(enc_inputs_1) + gsrm_feature2 = self.wrap_encoder1(enc_inputs_2) + + gsrm_feature2 = F.pad(gsrm_feature2, [0, 1], + value=0., + data_format="NLC") + gsrm_feature2 = gsrm_feature2[:, 1:, ] + gsrm_features = gsrm_feature1 + gsrm_feature2 + + gsrm_out = self.mul(gsrm_features) + + b, t, c = gsrm_out.shape + gsrm_out = paddle.reshape(gsrm_out, [-1, c]) + + return gsrm_features, word_out, gsrm_out + + +class VSFD(nn.Layer): + def __init__(self, in_channels=512, pvam_ch=512, char_num=38): + super(VSFD, self).__init__() + self.char_num = char_num + self.fc0 = paddle.nn.Linear( + in_features=in_channels * 2, out_features=pvam_ch) + self.fc1 = paddle.nn.Linear( + in_features=pvam_ch, out_features=self.char_num) + + def forward(self, pvam_feature, gsrm_feature): + b, t, c1 = pvam_feature.shape + b, t, c2 = gsrm_feature.shape + combine_feature_ = paddle.concat([pvam_feature, gsrm_feature], axis=2) + img_comb_feature_ = paddle.reshape( + combine_feature_, shape=[-1, c1 + c2]) + img_comb_feature_map = self.fc0(img_comb_feature_) + img_comb_feature_map = F.sigmoid(img_comb_feature_map) + img_comb_feature_map = paddle.reshape( + img_comb_feature_map, shape=[-1, t, c1]) + combine_feature = img_comb_feature_map * pvam_feature + ( + 1.0 - img_comb_feature_map) * gsrm_feature + img_comb_feature = paddle.reshape(combine_feature, shape=[-1, c1]) + + out = self.fc1(img_comb_feature) + return out + + +class SRNHead(nn.Layer): + def __init__(self, in_channels, out_channels, max_text_length, num_heads, + num_encoder_TUs, num_decoder_TUs, hidden_dims, **kwargs): + super(SRNHead, self).__init__() + self.char_num = out_channels + self.max_length = max_text_length + self.num_heads = num_heads + self.num_encoder_TUs = num_encoder_TUs + self.num_decoder_TUs = num_decoder_TUs + self.hidden_dims = hidden_dims + + self.pvam = PVAM( + in_channels=in_channels, + char_num=self.char_num, + max_text_length=self.max_length, + num_heads=self.num_heads, + num_encoder_tus=self.num_encoder_TUs, + hidden_dims=self.hidden_dims) + + self.gsrm = GSRM( + in_channels=in_channels, + char_num=self.char_num, + max_text_length=self.max_length, + num_heads=self.num_heads, + num_encoder_tus=self.num_encoder_TUs, + num_decoder_tus=self.num_decoder_TUs, + hidden_dims=self.hidden_dims) + self.vsfd = VSFD(in_channels=in_channels, char_num=self.char_num) + + self.gsrm.wrap_encoder1.prepare_decoder.emb0 = self.gsrm.wrap_encoder0.prepare_decoder.emb0 + + def forward(self, inputs, targets=None): + others = targets[-4:] + encoder_word_pos = others[0] + gsrm_word_pos = others[1] + gsrm_slf_attn_bias1 = others[2] + gsrm_slf_attn_bias2 = others[3] + + pvam_feature = self.pvam(inputs, encoder_word_pos, gsrm_word_pos) + + gsrm_feature, word_out, gsrm_out = self.gsrm( + pvam_feature, gsrm_word_pos, gsrm_slf_attn_bias1, + gsrm_slf_attn_bias2) + + final_out = self.vsfd(pvam_feature, gsrm_feature) + if not self.training: + final_out = F.softmax(final_out, axis=1) + + _, decoded_out = paddle.topk(final_out, k=1) + + predicts = OrderedDict([ + ('predict', final_out), + ('pvam_feature', pvam_feature), + ('decoded_out', decoded_out), + ('word_out', word_out), + ('gsrm_out', gsrm_out), + ]) + + return predicts diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_visionlan_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_visionlan_head.py new file mode 100644 index 0000000000000000000000000000000000000000..86054d9bbb12613e3119b4c0d72f4670344d773a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/rec_visionlan_head.py @@ -0,0 +1,468 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/wangyuxin87/VisionLAN +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import ParamAttr +import paddle.nn as nn +import paddle.nn.functional as F +from paddle.nn.initializer import Normal, XavierNormal +import numpy as np + + +class PositionalEncoding(nn.Layer): + def __init__(self, d_hid, n_position=200): + super(PositionalEncoding, self).__init__() + self.register_buffer( + 'pos_table', self._get_sinusoid_encoding_table(n_position, d_hid)) + + def _get_sinusoid_encoding_table(self, n_position, d_hid): + ''' Sinusoid position encoding table ''' + + def get_position_angle_vec(position): + return [ + position / np.power(10000, 2 * (hid_j // 2) / d_hid) + for hid_j in range(d_hid) + ] + + sinusoid_table = np.array( + [get_position_angle_vec(pos_i) for pos_i in range(n_position)]) + sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i + sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 + sinusoid_table = paddle.to_tensor(sinusoid_table, dtype='float32') + sinusoid_table = paddle.unsqueeze(sinusoid_table, axis=0) + return sinusoid_table + + def forward(self, x): + return x + self.pos_table[:, :x.shape[1]].clone().detach() + + +class ScaledDotProductAttention(nn.Layer): + "Scaled Dot-Product Attention" + + def __init__(self, temperature, attn_dropout=0.1): + super(ScaledDotProductAttention, self).__init__() + self.temperature = temperature + self.dropout = nn.Dropout(attn_dropout) + self.softmax = nn.Softmax(axis=2) + + def forward(self, q, k, v, mask=None): + k = paddle.transpose(k, perm=[0, 2, 1]) + attn = paddle.bmm(q, k) + attn = attn / self.temperature + if mask is not None: + attn = attn.masked_fill(mask, -1e9) + if mask.dim() == 3: + mask = paddle.unsqueeze(mask, axis=1) + elif mask.dim() == 2: + mask = paddle.unsqueeze(mask, axis=1) + mask = paddle.unsqueeze(mask, axis=1) + repeat_times = [ + attn.shape[1] // mask.shape[1], attn.shape[2] // mask.shape[2] + ] + mask = paddle.tile(mask, [1, repeat_times[0], repeat_times[1], 1]) + attn[mask == 0] = -1e9 + attn = self.softmax(attn) + attn = self.dropout(attn) + output = paddle.bmm(attn, v) + return output + + +class MultiHeadAttention(nn.Layer): + " Multi-Head Attention module" + + def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): + super(MultiHeadAttention, self).__init__() + self.n_head = n_head + self.d_k = d_k + self.d_v = d_v + self.w_qs = nn.Linear( + d_model, + n_head * d_k, + weight_attr=ParamAttr(initializer=Normal( + mean=0, std=np.sqrt(2.0 / (d_model + d_k))))) + self.w_ks = nn.Linear( + d_model, + n_head * d_k, + weight_attr=ParamAttr(initializer=Normal( + mean=0, std=np.sqrt(2.0 / (d_model + d_k))))) + self.w_vs = nn.Linear( + d_model, + n_head * d_v, + weight_attr=ParamAttr(initializer=Normal( + mean=0, std=np.sqrt(2.0 / (d_model + d_v))))) + + self.attention = ScaledDotProductAttention(temperature=np.power(d_k, + 0.5)) + self.layer_norm = nn.LayerNorm(d_model) + self.fc = nn.Linear( + n_head * d_v, + d_model, + weight_attr=ParamAttr(initializer=XavierNormal())) + self.dropout = nn.Dropout(dropout) + + def forward(self, q, k, v, mask=None): + d_k, d_v, n_head = self.d_k, self.d_v, self.n_head + sz_b, len_q, _ = q.shape + sz_b, len_k, _ = k.shape + sz_b, len_v, _ = v.shape + residual = q + + q = self.w_qs(q) + q = paddle.reshape( + q, shape=[-1, len_q, n_head, d_k]) # 4*21*512 ---- 4*21*8*64 + k = self.w_ks(k) + k = paddle.reshape(k, shape=[-1, len_k, n_head, d_k]) + v = self.w_vs(v) + v = paddle.reshape(v, shape=[-1, len_v, n_head, d_v]) + + q = paddle.transpose(q, perm=[2, 0, 1, 3]) + q = paddle.reshape(q, shape=[-1, len_q, d_k]) # (n*b) x lq x dk + k = paddle.transpose(k, perm=[2, 0, 1, 3]) + k = paddle.reshape(k, shape=[-1, len_k, d_k]) # (n*b) x lk x dk + v = paddle.transpose(v, perm=[2, 0, 1, 3]) + v = paddle.reshape(v, shape=[-1, len_v, d_v]) # (n*b) x lv x dv + + mask = paddle.tile( + mask, + [n_head, 1, 1]) if mask is not None else None # (n*b) x .. x .. + output = self.attention(q, k, v, mask=mask) + output = paddle.reshape(output, shape=[n_head, -1, len_q, d_v]) + output = paddle.transpose(output, perm=[1, 2, 0, 3]) + output = paddle.reshape( + output, shape=[-1, len_q, n_head * d_v]) # b x lq x (n*dv) + output = self.dropout(self.fc(output)) + output = self.layer_norm(output + residual) + return output + + +class PositionwiseFeedForward(nn.Layer): + def __init__(self, d_in, d_hid, dropout=0.1): + super(PositionwiseFeedForward, self).__init__() + self.w_1 = nn.Conv1D(d_in, d_hid, 1) # position-wise + self.w_2 = nn.Conv1D(d_hid, d_in, 1) # position-wise + self.layer_norm = nn.LayerNorm(d_in) + self.dropout = nn.Dropout(dropout) + + def forward(self, x): + residual = x + x = paddle.transpose(x, perm=[0, 2, 1]) + x = self.w_2(F.relu(self.w_1(x))) + x = paddle.transpose(x, perm=[0, 2, 1]) + x = self.dropout(x) + x = self.layer_norm(x + residual) + return x + + +class EncoderLayer(nn.Layer): + ''' Compose with two layers ''' + + def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1): + super(EncoderLayer, self).__init__() + self.slf_attn = MultiHeadAttention( + n_head, d_model, d_k, d_v, dropout=dropout) + self.pos_ffn = PositionwiseFeedForward( + d_model, d_inner, dropout=dropout) + + def forward(self, enc_input, slf_attn_mask=None): + enc_output = self.slf_attn( + enc_input, enc_input, enc_input, mask=slf_attn_mask) + enc_output = self.pos_ffn(enc_output) + return enc_output + + +class Transformer_Encoder(nn.Layer): + def __init__(self, + n_layers=2, + n_head=8, + d_word_vec=512, + d_k=64, + d_v=64, + d_model=512, + d_inner=2048, + dropout=0.1, + n_position=256): + super(Transformer_Encoder, self).__init__() + self.position_enc = PositionalEncoding( + d_word_vec, n_position=n_position) + self.dropout = nn.Dropout(p=dropout) + self.layer_stack = nn.LayerList([ + EncoderLayer( + d_model, d_inner, n_head, d_k, d_v, dropout=dropout) + for _ in range(n_layers) + ]) + self.layer_norm = nn.LayerNorm(d_model, epsilon=1e-6) + + def forward(self, enc_output, src_mask, return_attns=False): + enc_output = self.dropout( + self.position_enc(enc_output)) # position embeding + for enc_layer in self.layer_stack: + enc_output = enc_layer(enc_output, slf_attn_mask=src_mask) + enc_output = self.layer_norm(enc_output) + return enc_output + + +class PP_layer(nn.Layer): + def __init__(self, n_dim=512, N_max_character=25, n_position=256): + + super(PP_layer, self).__init__() + self.character_len = N_max_character + self.f0_embedding = nn.Embedding(N_max_character, n_dim) + self.w0 = nn.Linear(N_max_character, n_position) + self.wv = nn.Linear(n_dim, n_dim) + self.we = nn.Linear(n_dim, N_max_character) + self.active = nn.Tanh() + self.softmax = nn.Softmax(axis=2) + + def forward(self, enc_output): + # enc_output: b,256,512 + reading_order = paddle.arange(self.character_len, dtype='int64') + reading_order = reading_order.unsqueeze(0).expand( + [enc_output.shape[0], self.character_len]) # (S,) -> (B, S) + reading_order = self.f0_embedding(reading_order) # b,25,512 + + # calculate attention + reading_order = paddle.transpose(reading_order, perm=[0, 2, 1]) + t = self.w0(reading_order) # b,512,256 + t = self.active( + paddle.transpose( + t, perm=[0, 2, 1]) + self.wv(enc_output)) # b,256,512 + t = self.we(t) # b,256,25 + t = self.softmax(paddle.transpose(t, perm=[0, 2, 1])) # b,25,256 + g_output = paddle.bmm(t, enc_output) # b,25,512 + return g_output + + +class Prediction(nn.Layer): + def __init__(self, + n_dim=512, + n_position=256, + N_max_character=25, + n_class=37): + super(Prediction, self).__init__() + self.pp = PP_layer( + n_dim=n_dim, N_max_character=N_max_character, n_position=n_position) + self.pp_share = PP_layer( + n_dim=n_dim, N_max_character=N_max_character, n_position=n_position) + self.w_vrm = nn.Linear(n_dim, n_class) # output layer + self.w_share = nn.Linear(n_dim, n_class) # output layer + self.nclass = n_class + + def forward(self, cnn_feature, f_res, f_sub, train_mode=False, + use_mlm=True): + if train_mode: + if not use_mlm: + g_output = self.pp(cnn_feature) # b,25,512 + g_output = self.w_vrm(g_output) + f_res = 0 + f_sub = 0 + return g_output, f_res, f_sub + g_output = self.pp(cnn_feature) # b,25,512 + f_res = self.pp_share(f_res) + f_sub = self.pp_share(f_sub) + g_output = self.w_vrm(g_output) + f_res = self.w_share(f_res) + f_sub = self.w_share(f_sub) + return g_output, f_res, f_sub + else: + g_output = self.pp(cnn_feature) # b,25,512 + g_output = self.w_vrm(g_output) + return g_output + + +class MLM(nn.Layer): + "Architecture of MLM" + + def __init__(self, n_dim=512, n_position=256, max_text_length=25): + super(MLM, self).__init__() + self.MLM_SequenceModeling_mask = Transformer_Encoder( + n_layers=2, n_position=n_position) + self.MLM_SequenceModeling_WCL = Transformer_Encoder( + n_layers=1, n_position=n_position) + self.pos_embedding = nn.Embedding(max_text_length, n_dim) + self.w0_linear = nn.Linear(1, n_position) + self.wv = nn.Linear(n_dim, n_dim) + self.active = nn.Tanh() + self.we = nn.Linear(n_dim, 1) + self.sigmoid = nn.Sigmoid() + + def forward(self, x, label_pos): + # transformer unit for generating mask_c + feature_v_seq = self.MLM_SequenceModeling_mask(x, src_mask=None) + # position embedding layer + label_pos = paddle.to_tensor(label_pos, dtype='int64') + pos_emb = self.pos_embedding(label_pos) + pos_emb = self.w0_linear(paddle.unsqueeze(pos_emb, axis=2)) + pos_emb = paddle.transpose(pos_emb, perm=[0, 2, 1]) + # fusion position embedding with features V & generate mask_c + att_map_sub = self.active(pos_emb + self.wv(feature_v_seq)) + att_map_sub = self.we(att_map_sub) # b,256,1 + att_map_sub = paddle.transpose(att_map_sub, perm=[0, 2, 1]) + att_map_sub = self.sigmoid(att_map_sub) # b,1,256 + # WCL + ## generate inputs for WCL + att_map_sub = paddle.transpose(att_map_sub, perm=[0, 2, 1]) + f_res = x * (1 - att_map_sub) # second path with remaining string + f_sub = x * att_map_sub # first path with occluded character + ## transformer units in WCL + f_res = self.MLM_SequenceModeling_WCL(f_res, src_mask=None) + f_sub = self.MLM_SequenceModeling_WCL(f_sub, src_mask=None) + return f_res, f_sub, att_map_sub + + +def trans_1d_2d(x): + b, w_h, c = x.shape # b, 256, 512 + x = paddle.transpose(x, perm=[0, 2, 1]) + x = paddle.reshape(x, [-1, c, 32, 8]) + x = paddle.transpose(x, perm=[0, 1, 3, 2]) # [b, c, 8, 32] + return x + + +class MLM_VRM(nn.Layer): + """ + MLM+VRM, MLM is only used in training. + ratio controls the occluded number in a batch. + The pipeline of VisionLAN in testing is very concise with only a backbone + sequence modeling(transformer unit) + prediction layer(pp layer). + x: input image + label_pos: character index + training_step: LF or LA process + output + text_pre: prediction of VRM + test_rem: prediction of remaining string in MLM + text_mas: prediction of occluded character in MLM + mask_c_show: visualization of Mask_c + """ + + def __init__(self, + n_layers=3, + n_position=256, + n_dim=512, + max_text_length=25, + nclass=37): + super(MLM_VRM, self).__init__() + self.MLM = MLM(n_dim=n_dim, + n_position=n_position, + max_text_length=max_text_length) + self.SequenceModeling = Transformer_Encoder( + n_layers=n_layers, n_position=n_position) + self.Prediction = Prediction( + n_dim=n_dim, + n_position=n_position, + N_max_character=max_text_length + + 1, # N_max_character = 1 eos + 25 characters + n_class=nclass) + self.nclass = nclass + self.max_text_length = max_text_length + + def forward(self, x, label_pos, training_step, train_mode=False): + b, c, h, w = x.shape + nT = self.max_text_length + x = paddle.transpose(x, perm=[0, 1, 3, 2]) + x = paddle.reshape(x, [-1, c, h * w]) + x = paddle.transpose(x, perm=[0, 2, 1]) + if train_mode: + if training_step == 'LF_1': + f_res = 0 + f_sub = 0 + x = self.SequenceModeling(x, src_mask=None) + text_pre, test_rem, text_mas = self.Prediction( + x, f_res, f_sub, train_mode=True, use_mlm=False) + return text_pre, text_pre, text_pre, text_pre + elif training_step == 'LF_2': + # MLM + f_res, f_sub, mask_c = self.MLM(x, label_pos) + x = self.SequenceModeling(x, src_mask=None) + text_pre, test_rem, text_mas = self.Prediction( + x, f_res, f_sub, train_mode=True) + mask_c_show = trans_1d_2d(mask_c) + return text_pre, test_rem, text_mas, mask_c_show + elif training_step == 'LA': + # MLM + f_res, f_sub, mask_c = self.MLM(x, label_pos) + ## use the mask_c (1 for occluded character and 0 for remaining characters) to occlude input + ## ratio controls the occluded number in a batch + character_mask = paddle.zeros_like(mask_c) + + ratio = b // 2 + if ratio >= 1: + with paddle.no_grad(): + character_mask[0:ratio, :, :] = mask_c[0:ratio, :, :] + else: + character_mask = mask_c + x = x * (1 - character_mask) + # VRM + ## transformer unit for VRM + x = self.SequenceModeling(x, src_mask=None) + ## prediction layer for MLM and VSR + text_pre, test_rem, text_mas = self.Prediction( + x, f_res, f_sub, train_mode=True) + mask_c_show = trans_1d_2d(mask_c) + return text_pre, test_rem, text_mas, mask_c_show + else: + raise NotImplementedError + else: # VRM is only used in the testing stage + f_res = 0 + f_sub = 0 + contextual_feature = self.SequenceModeling(x, src_mask=None) + text_pre = self.Prediction( + contextual_feature, + f_res, + f_sub, + train_mode=False, + use_mlm=False) + text_pre = paddle.transpose( + text_pre, perm=[1, 0, 2]) # (26, b, 37)) + return text_pre, x + + +class VLHead(nn.Layer): + """ + Architecture of VisionLAN + """ + + def __init__(self, + in_channels, + out_channels=36, + n_layers=3, + n_position=256, + n_dim=512, + max_text_length=25, + training_step='LA'): + super(VLHead, self).__init__() + self.MLM_VRM = MLM_VRM( + n_layers=n_layers, + n_position=n_position, + n_dim=n_dim, + max_text_length=max_text_length, + nclass=out_channels + 1) + self.training_step = training_step + + def forward(self, feat, targets=None): + + if self.training: + label_pos = targets[-2] + text_pre, test_rem, text_mas, mask_map = self.MLM_VRM( + feat, label_pos, self.training_step, train_mode=True) + return text_pre, test_rem, text_mas, mask_map + else: + text_pre, x = self.MLM_VRM( + feat, targets, self.training_step, train_mode=False) + return text_pre, x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/self_attention.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/self_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4c65e3931ae74a0fde2a16694a69fdfa69b5ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/self_attention.py @@ -0,0 +1,405 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +import paddle +from paddle import ParamAttr, nn +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np +gradient_clip = 10 + + +class WrapEncoderForFeature(nn.Layer): + def __init__(self, + src_vocab_size, + max_length, + n_layer, + n_head, + d_key, + d_value, + d_model, + d_inner_hid, + prepostprocess_dropout, + attention_dropout, + relu_dropout, + preprocess_cmd, + postprocess_cmd, + weight_sharing, + bos_idx=0): + super(WrapEncoderForFeature, self).__init__() + + self.prepare_encoder = PrepareEncoder( + src_vocab_size, + d_model, + max_length, + prepostprocess_dropout, + bos_idx=bos_idx, + word_emb_param_name="src_word_emb_table") + self.encoder = Encoder(n_layer, n_head, d_key, d_value, d_model, + d_inner_hid, prepostprocess_dropout, + attention_dropout, relu_dropout, preprocess_cmd, + postprocess_cmd) + + def forward(self, enc_inputs): + conv_features, src_pos, src_slf_attn_bias = enc_inputs + enc_input = self.prepare_encoder(conv_features, src_pos) + enc_output = self.encoder(enc_input, src_slf_attn_bias) + return enc_output + + +class WrapEncoder(nn.Layer): + """ + embedder + encoder + """ + + def __init__(self, + src_vocab_size, + max_length, + n_layer, + n_head, + d_key, + d_value, + d_model, + d_inner_hid, + prepostprocess_dropout, + attention_dropout, + relu_dropout, + preprocess_cmd, + postprocess_cmd, + weight_sharing, + bos_idx=0): + super(WrapEncoder, self).__init__() + + self.prepare_decoder = PrepareDecoder( + src_vocab_size, + d_model, + max_length, + prepostprocess_dropout, + bos_idx=bos_idx) + self.encoder = Encoder(n_layer, n_head, d_key, d_value, d_model, + d_inner_hid, prepostprocess_dropout, + attention_dropout, relu_dropout, preprocess_cmd, + postprocess_cmd) + + def forward(self, enc_inputs): + src_word, src_pos, src_slf_attn_bias = enc_inputs + enc_input = self.prepare_decoder(src_word, src_pos) + enc_output = self.encoder(enc_input, src_slf_attn_bias) + return enc_output + + +class Encoder(nn.Layer): + """ + encoder + """ + + def __init__(self, + n_layer, + n_head, + d_key, + d_value, + d_model, + d_inner_hid, + prepostprocess_dropout, + attention_dropout, + relu_dropout, + preprocess_cmd="n", + postprocess_cmd="da"): + + super(Encoder, self).__init__() + + self.encoder_layers = list() + for i in range(n_layer): + self.encoder_layers.append( + self.add_sublayer( + "layer_%d" % i, + EncoderLayer(n_head, d_key, d_value, d_model, d_inner_hid, + prepostprocess_dropout, attention_dropout, + relu_dropout, preprocess_cmd, + postprocess_cmd))) + self.processer = PrePostProcessLayer(preprocess_cmd, d_model, + prepostprocess_dropout) + + def forward(self, enc_input, attn_bias): + for encoder_layer in self.encoder_layers: + enc_output = encoder_layer(enc_input, attn_bias) + enc_input = enc_output + enc_output = self.processer(enc_output) + return enc_output + + +class EncoderLayer(nn.Layer): + """ + EncoderLayer + """ + + def __init__(self, + n_head, + d_key, + d_value, + d_model, + d_inner_hid, + prepostprocess_dropout, + attention_dropout, + relu_dropout, + preprocess_cmd="n", + postprocess_cmd="da"): + + super(EncoderLayer, self).__init__() + self.preprocesser1 = PrePostProcessLayer(preprocess_cmd, d_model, + prepostprocess_dropout) + self.self_attn = MultiHeadAttention(d_key, d_value, d_model, n_head, + attention_dropout) + self.postprocesser1 = PrePostProcessLayer(postprocess_cmd, d_model, + prepostprocess_dropout) + + self.preprocesser2 = PrePostProcessLayer(preprocess_cmd, d_model, + prepostprocess_dropout) + self.ffn = FFN(d_inner_hid, d_model, relu_dropout) + self.postprocesser2 = PrePostProcessLayer(postprocess_cmd, d_model, + prepostprocess_dropout) + + def forward(self, enc_input, attn_bias): + attn_output = self.self_attn( + self.preprocesser1(enc_input), None, None, attn_bias) + attn_output = self.postprocesser1(attn_output, enc_input) + ffn_output = self.ffn(self.preprocesser2(attn_output)) + ffn_output = self.postprocesser2(ffn_output, attn_output) + return ffn_output + + +class MultiHeadAttention(nn.Layer): + """ + Multi-Head Attention + """ + + def __init__(self, d_key, d_value, d_model, n_head=1, dropout_rate=0.): + super(MultiHeadAttention, self).__init__() + self.n_head = n_head + self.d_key = d_key + self.d_value = d_value + self.d_model = d_model + self.dropout_rate = dropout_rate + self.q_fc = paddle.nn.Linear( + in_features=d_model, out_features=d_key * n_head, bias_attr=False) + self.k_fc = paddle.nn.Linear( + in_features=d_model, out_features=d_key * n_head, bias_attr=False) + self.v_fc = paddle.nn.Linear( + in_features=d_model, out_features=d_value * n_head, bias_attr=False) + self.proj_fc = paddle.nn.Linear( + in_features=d_value * n_head, out_features=d_model, bias_attr=False) + + def _prepare_qkv(self, queries, keys, values, cache=None): + if keys is None: # self-attention + keys, values = queries, queries + static_kv = False + else: # cross-attention + static_kv = True + + q = self.q_fc(queries) + q = paddle.reshape(x=q, shape=[0, 0, self.n_head, self.d_key]) + q = paddle.transpose(x=q, perm=[0, 2, 1, 3]) + + if cache is not None and static_kv and "static_k" in cache: + # for encoder-decoder attention in inference and has cached + k = cache["static_k"] + v = cache["static_v"] + else: + k = self.k_fc(keys) + v = self.v_fc(values) + k = paddle.reshape(x=k, shape=[0, 0, self.n_head, self.d_key]) + k = paddle.transpose(x=k, perm=[0, 2, 1, 3]) + v = paddle.reshape(x=v, shape=[0, 0, self.n_head, self.d_value]) + v = paddle.transpose(x=v, perm=[0, 2, 1, 3]) + + if cache is not None: + if static_kv and not "static_k" in cache: + # for encoder-decoder attention in inference and has not cached + cache["static_k"], cache["static_v"] = k, v + elif not static_kv: + # for decoder self-attention in inference + cache_k, cache_v = cache["k"], cache["v"] + k = paddle.concat([cache_k, k], axis=2) + v = paddle.concat([cache_v, v], axis=2) + cache["k"], cache["v"] = k, v + + return q, k, v + + def forward(self, queries, keys, values, attn_bias, cache=None): + # compute q ,k ,v + keys = queries if keys is None else keys + values = keys if values is None else values + q, k, v = self._prepare_qkv(queries, keys, values, cache) + + # scale dot product attention + product = paddle.matmul(x=q, y=k, transpose_y=True) + product = product * self.d_model**-0.5 + if attn_bias is not None: + product += attn_bias + weights = F.softmax(product) + if self.dropout_rate: + weights = F.dropout( + weights, p=self.dropout_rate, mode="downscale_in_infer") + out = paddle.matmul(weights, v) + + # combine heads + out = paddle.transpose(out, perm=[0, 2, 1, 3]) + out = paddle.reshape(x=out, shape=[0, 0, out.shape[2] * out.shape[3]]) + + # project to output + out = self.proj_fc(out) + + return out + + +class PrePostProcessLayer(nn.Layer): + """ + PrePostProcessLayer + """ + + def __init__(self, process_cmd, d_model, dropout_rate): + super(PrePostProcessLayer, self).__init__() + self.process_cmd = process_cmd + self.functors = [] + for cmd in self.process_cmd: + if cmd == "a": # add residual connection + self.functors.append(lambda x, y: x + y if y is not None else x) + elif cmd == "n": # add layer normalization + self.functors.append( + self.add_sublayer( + "layer_norm_%d" % len(self.sublayers()), + paddle.nn.LayerNorm( + normalized_shape=d_model, + weight_attr=paddle.ParamAttr( + initializer=paddle.nn.initializer.Constant(1.)), + bias_attr=paddle.ParamAttr( + initializer=paddle.nn.initializer.Constant(0.))))) + elif cmd == "d": # add dropout + self.functors.append(lambda x: F.dropout( + x, p=dropout_rate, mode="downscale_in_infer") + if dropout_rate else x) + + def forward(self, x, residual=None): + for i, cmd in enumerate(self.process_cmd): + if cmd == "a": + x = self.functors[i](x, residual) + else: + x = self.functors[i](x) + return x + + +class PrepareEncoder(nn.Layer): + def __init__(self, + src_vocab_size, + src_emb_dim, + src_max_len, + dropout_rate=0, + bos_idx=0, + word_emb_param_name=None, + pos_enc_param_name=None): + super(PrepareEncoder, self).__init__() + self.src_emb_dim = src_emb_dim + self.src_max_len = src_max_len + self.emb = paddle.nn.Embedding( + num_embeddings=self.src_max_len, embedding_dim=self.src_emb_dim) + self.dropout_rate = dropout_rate + + def forward(self, src_word, src_pos): + src_word_emb = src_word + src_word_emb = paddle.cast(src_word_emb, 'float32') + src_word_emb = paddle.scale(x=src_word_emb, scale=self.src_emb_dim**0.5) + src_pos = paddle.squeeze(src_pos, axis=-1) + src_pos_enc = self.emb(src_pos) + src_pos_enc.stop_gradient = True + enc_input = src_word_emb + src_pos_enc + if self.dropout_rate: + out = F.dropout( + x=enc_input, p=self.dropout_rate, mode="downscale_in_infer") + else: + out = enc_input + return out + + +class PrepareDecoder(nn.Layer): + def __init__(self, + src_vocab_size, + src_emb_dim, + src_max_len, + dropout_rate=0, + bos_idx=0, + word_emb_param_name=None, + pos_enc_param_name=None): + super(PrepareDecoder, self).__init__() + self.src_emb_dim = src_emb_dim + """ + self.emb0 = Embedding(num_embeddings=src_vocab_size, + embedding_dim=src_emb_dim) + """ + self.emb0 = paddle.nn.Embedding( + num_embeddings=src_vocab_size, + embedding_dim=self.src_emb_dim, + padding_idx=bos_idx, + weight_attr=paddle.ParamAttr( + name=word_emb_param_name, + initializer=nn.initializer.Normal(0., src_emb_dim**-0.5))) + self.emb1 = paddle.nn.Embedding( + num_embeddings=src_max_len, + embedding_dim=self.src_emb_dim, + weight_attr=paddle.ParamAttr(name=pos_enc_param_name)) + self.dropout_rate = dropout_rate + + def forward(self, src_word, src_pos): + src_word = paddle.cast(src_word, 'int64') + src_word = paddle.squeeze(src_word, axis=-1) + src_word_emb = self.emb0(src_word) + src_word_emb = paddle.scale(x=src_word_emb, scale=self.src_emb_dim**0.5) + src_pos = paddle.squeeze(src_pos, axis=-1) + src_pos_enc = self.emb1(src_pos) + src_pos_enc.stop_gradient = True + enc_input = src_word_emb + src_pos_enc + if self.dropout_rate: + out = F.dropout( + x=enc_input, p=self.dropout_rate, mode="downscale_in_infer") + else: + out = enc_input + return out + + +class FFN(nn.Layer): + """ + Feed-Forward Network + """ + + def __init__(self, d_inner_hid, d_model, dropout_rate): + super(FFN, self).__init__() + self.dropout_rate = dropout_rate + self.fc1 = paddle.nn.Linear( + in_features=d_model, out_features=d_inner_hid) + self.fc2 = paddle.nn.Linear( + in_features=d_inner_hid, out_features=d_model) + + def forward(self, x): + hidden = self.fc1(x) + hidden = F.relu(hidden) + if self.dropout_rate: + hidden = F.dropout( + hidden, p=self.dropout_rate, mode="downscale_in_infer") + out = self.fc2(hidden) + return out diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/sr_rensnet_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/sr_rensnet_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..a004a12663ac2061a329236c58e147a017c80ba6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/sr_rensnet_transformer.py @@ -0,0 +1,430 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/loss/transformer_english_decomposition.py +""" +import paddle +import paddle.nn as nn +import paddle.nn.functional as F +import math, copy +import numpy as np + +# stroke-level alphabet +alphabet = '0123456789' + + +def get_alphabet_len(): + return len(alphabet) + + +def subsequent_mask(size): + """Generate a square mask for the sequence. The masked positions are filled with float('-inf'). + Unmasked positions are filled with float(0.0). + """ + mask = paddle.ones([1, size, size], dtype='float32') + mask_inf = paddle.triu( + paddle.full( + shape=[1, size, size], dtype='float32', fill_value='-inf'), + diagonal=1) + mask = mask + mask_inf + padding_mask = paddle.equal(mask, paddle.to_tensor(1, dtype=mask.dtype)) + return padding_mask + + +def clones(module, N): + return nn.LayerList([copy.deepcopy(module) for _ in range(N)]) + + +def masked_fill(x, mask, value): + y = paddle.full(x.shape, value, x.dtype) + return paddle.where(mask, y, x) + + +def attention(query, key, value, mask=None, dropout=None, attention_map=None): + d_k = query.shape[-1] + scores = paddle.matmul(query, + paddle.transpose(key, [0, 1, 3, 2])) / math.sqrt(d_k) + + if mask is not None: + scores = masked_fill(scores, mask == 0, float('-inf')) + else: + pass + + p_attn = F.softmax(scores, axis=-1) + + if dropout is not None: + p_attn = dropout(p_attn) + return paddle.matmul(p_attn, value), p_attn + + +class MultiHeadedAttention(nn.Layer): + def __init__(self, h, d_model, dropout=0.1, compress_attention=False): + super(MultiHeadedAttention, self).__init__() + assert d_model % h == 0 + self.d_k = d_model // h + self.h = h + self.linears = clones(nn.Linear(d_model, d_model), 4) + self.attn = None + self.dropout = nn.Dropout(p=dropout, mode="downscale_in_infer") + self.compress_attention = compress_attention + self.compress_attention_linear = nn.Linear(h, 1) + + def forward(self, query, key, value, mask=None, attention_map=None): + if mask is not None: + mask = mask.unsqueeze(1) + nbatches = query.shape[0] + + query, key, value = \ + [paddle.transpose(l(x).reshape([nbatches, -1, self.h, self.d_k]), [0,2,1,3]) + for l, x in zip(self.linears, (query, key, value))] + + x, attention_map = attention( + query, + key, + value, + mask=mask, + dropout=self.dropout, + attention_map=attention_map) + + x = paddle.reshape( + paddle.transpose(x, [0, 2, 1, 3]), + [nbatches, -1, self.h * self.d_k]) + + return self.linears[-1](x), attention_map + + +class ResNet(nn.Layer): + def __init__(self, num_in, block, layers): + super(ResNet, self).__init__() + + self.conv1 = nn.Conv2D(num_in, 64, kernel_size=3, stride=1, padding=1) + self.bn1 = nn.BatchNorm2D(64, use_global_stats=True) + self.relu1 = nn.ReLU() + self.pool = nn.MaxPool2D((2, 2), (2, 2)) + + self.conv2 = nn.Conv2D(64, 128, kernel_size=3, stride=1, padding=1) + self.bn2 = nn.BatchNorm2D(128, use_global_stats=True) + self.relu2 = nn.ReLU() + + self.layer1_pool = nn.MaxPool2D((2, 2), (2, 2)) + self.layer1 = self._make_layer(block, 128, 256, layers[0]) + self.layer1_conv = nn.Conv2D(256, 256, 3, 1, 1) + self.layer1_bn = nn.BatchNorm2D(256, use_global_stats=True) + self.layer1_relu = nn.ReLU() + + self.layer2_pool = nn.MaxPool2D((2, 2), (2, 2)) + self.layer2 = self._make_layer(block, 256, 256, layers[1]) + self.layer2_conv = nn.Conv2D(256, 256, 3, 1, 1) + self.layer2_bn = nn.BatchNorm2D(256, use_global_stats=True) + self.layer2_relu = nn.ReLU() + + self.layer3_pool = nn.MaxPool2D((2, 2), (2, 2)) + self.layer3 = self._make_layer(block, 256, 512, layers[2]) + self.layer3_conv = nn.Conv2D(512, 512, 3, 1, 1) + self.layer3_bn = nn.BatchNorm2D(512, use_global_stats=True) + self.layer3_relu = nn.ReLU() + + self.layer4_pool = nn.MaxPool2D((2, 2), (2, 2)) + self.layer4 = self._make_layer(block, 512, 512, layers[3]) + self.layer4_conv2 = nn.Conv2D(512, 1024, 3, 1, 1) + self.layer4_conv2_bn = nn.BatchNorm2D(1024, use_global_stats=True) + self.layer4_conv2_relu = nn.ReLU() + + def _make_layer(self, block, inplanes, planes, blocks): + + if inplanes != planes: + downsample = nn.Sequential( + nn.Conv2D(inplanes, planes, 3, 1, 1), + nn.BatchNorm2D( + planes, use_global_stats=True), ) + else: + downsample = None + layers = [] + layers.append(block(inplanes, planes, downsample)) + for i in range(1, blocks): + layers.append(block(planes, planes, downsample=None)) + + return nn.Sequential(*layers) + + def forward(self, x): + x = self.conv1(x) + x = self.bn1(x) + x = self.relu1(x) + x = self.pool(x) + + x = self.conv2(x) + x = self.bn2(x) + x = self.relu2(x) + + x = self.layer1_pool(x) + x = self.layer1(x) + x = self.layer1_conv(x) + x = self.layer1_bn(x) + x = self.layer1_relu(x) + + x = self.layer2(x) + x = self.layer2_conv(x) + x = self.layer2_bn(x) + x = self.layer2_relu(x) + + x = self.layer3(x) + x = self.layer3_conv(x) + x = self.layer3_bn(x) + x = self.layer3_relu(x) + + x = self.layer4(x) + x = self.layer4_conv2(x) + x = self.layer4_conv2_bn(x) + x = self.layer4_conv2_relu(x) + + return x + + +class Bottleneck(nn.Layer): + def __init__(self, input_dim): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2D(input_dim, input_dim, 1) + self.bn1 = nn.BatchNorm2D(input_dim, use_global_stats=True) + self.relu = nn.ReLU() + + self.conv2 = nn.Conv2D(input_dim, input_dim, 3, 1, 1) + self.bn2 = nn.BatchNorm2D(input_dim, use_global_stats=True) + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + out += residual + out = self.relu(out) + + return out + + +class PositionalEncoding(nn.Layer): + "Implement the PE function." + + def __init__(self, dropout, dim, max_len=5000): + super(PositionalEncoding, self).__init__() + self.dropout = nn.Dropout(p=dropout, mode="downscale_in_infer") + + pe = paddle.zeros([max_len, dim]) + position = paddle.arange(0, max_len, dtype=paddle.float32).unsqueeze(1) + div_term = paddle.exp( + paddle.arange(0, dim, 2).astype('float32') * + (-math.log(10000.0) / dim)) + pe[:, 0::2] = paddle.sin(position * div_term) + pe[:, 1::2] = paddle.cos(position * div_term) + pe = paddle.unsqueeze(pe, 0) + self.register_buffer('pe', pe) + + def forward(self, x): + x = x + self.pe[:, :paddle.shape(x)[1]] + return self.dropout(x) + + +class PositionwiseFeedForward(nn.Layer): + "Implements FFN equation." + + def __init__(self, d_model, d_ff, dropout=0.1): + super(PositionwiseFeedForward, self).__init__() + self.w_1 = nn.Linear(d_model, d_ff) + self.w_2 = nn.Linear(d_ff, d_model) + self.dropout = nn.Dropout(dropout, mode="downscale_in_infer") + + def forward(self, x): + return self.w_2(self.dropout(F.relu(self.w_1(x)))) + + +class Generator(nn.Layer): + "Define standard linear + softmax generation step." + + def __init__(self, d_model, vocab): + super(Generator, self).__init__() + self.proj = nn.Linear(d_model, vocab) + self.relu = nn.ReLU() + + def forward(self, x): + out = self.proj(x) + return out + + +class Embeddings(nn.Layer): + def __init__(self, d_model, vocab): + super(Embeddings, self).__init__() + self.lut = nn.Embedding(vocab, d_model) + self.d_model = d_model + + def forward(self, x): + embed = self.lut(x) * math.sqrt(self.d_model) + return embed + + +class LayerNorm(nn.Layer): + "Construct a layernorm module (See citation for details)." + + def __init__(self, features, eps=1e-6): + super(LayerNorm, self).__init__() + self.a_2 = self.create_parameter( + shape=[features], + default_initializer=paddle.nn.initializer.Constant(1.0)) + self.b_2 = self.create_parameter( + shape=[features], + default_initializer=paddle.nn.initializer.Constant(0.0)) + self.eps = eps + + def forward(self, x): + mean = x.mean(-1, keepdim=True) + std = x.std(-1, keepdim=True) + return self.a_2 * (x - mean) / (std + self.eps) + self.b_2 + + +class Decoder(nn.Layer): + def __init__(self): + super(Decoder, self).__init__() + + self.mask_multihead = MultiHeadedAttention( + h=16, d_model=1024, dropout=0.1) + self.mul_layernorm1 = LayerNorm(1024) + + self.multihead = MultiHeadedAttention(h=16, d_model=1024, dropout=0.1) + self.mul_layernorm2 = LayerNorm(1024) + + self.pff = PositionwiseFeedForward(1024, 2048) + self.mul_layernorm3 = LayerNorm(1024) + + def forward(self, text, conv_feature, attention_map=None): + text_max_length = text.shape[1] + mask = subsequent_mask(text_max_length) + result = text + result = self.mul_layernorm1(result + self.mask_multihead( + text, text, text, mask=mask)[0]) + b, c, h, w = conv_feature.shape + conv_feature = paddle.transpose( + conv_feature.reshape([b, c, h * w]), [0, 2, 1]) + word_image_align, attention_map = self.multihead( + result, + conv_feature, + conv_feature, + mask=None, + attention_map=attention_map) + result = self.mul_layernorm2(result + word_image_align) + result = self.mul_layernorm3(result + self.pff(result)) + + return result, attention_map + + +class BasicBlock(nn.Layer): + def __init__(self, inplanes, planes, downsample): + super(BasicBlock, self).__init__() + self.conv1 = nn.Conv2D( + inplanes, planes, kernel_size=3, stride=1, padding=1) + self.bn1 = nn.BatchNorm2D(planes, use_global_stats=True) + self.relu = nn.ReLU() + self.conv2 = nn.Conv2D( + planes, planes, kernel_size=3, stride=1, padding=1) + self.bn2 = nn.BatchNorm2D(planes, use_global_stats=True) + self.downsample = downsample + + def forward(self, x): + residual = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample != None: + residual = self.downsample(residual) + + out += residual + out = self.relu(out) + + return out + + +class Encoder(nn.Layer): + def __init__(self): + super(Encoder, self).__init__() + self.cnn = ResNet(num_in=1, block=BasicBlock, layers=[1, 2, 5, 3]) + + def forward(self, input): + conv_result = self.cnn(input) + return conv_result + + +class Transformer(nn.Layer): + def __init__(self, in_channels=1): + super(Transformer, self).__init__() + + word_n_class = get_alphabet_len() + self.embedding_word_with_upperword = Embeddings(512, word_n_class) + self.pe = PositionalEncoding(dim=512, dropout=0.1, max_len=5000) + + self.encoder = Encoder() + self.decoder = Decoder() + self.generator_word_with_upperword = Generator(1024, word_n_class) + + for p in self.parameters(): + if p.dim() > 1: + nn.initializer.XavierNormal(p) + + def forward(self, image, text_length, text_input, attention_map=None): + if image.shape[1] == 3: + R = image[:, 0:1, :, :] + G = image[:, 1:2, :, :] + B = image[:, 2:3, :, :] + image = 0.299 * R + 0.587 * G + 0.114 * B + + conv_feature = self.encoder(image) # batch, 1024, 8, 32 + max_length = max(text_length) + text_input = text_input[:, :max_length] + + text_embedding = self.embedding_word_with_upperword( + text_input) # batch, text_max_length, 512 + postion_embedding = self.pe( + paddle.zeros(text_embedding.shape)) # batch, text_max_length, 512 + text_input_with_pe = paddle.concat([text_embedding, postion_embedding], + 2) # batch, text_max_length, 1024 + batch, seq_len, _ = text_input_with_pe.shape + + text_input_with_pe, word_attention_map = self.decoder( + text_input_with_pe, conv_feature) + + word_decoder_result = self.generator_word_with_upperword( + text_input_with_pe) + + if self.training: + total_length = paddle.sum(text_length) + probs_res = paddle.zeros([total_length, get_alphabet_len()]) + start = 0 + + for index, length in enumerate(text_length): + length = int(length.numpy()) + probs_res[start:start + length, :] = word_decoder_result[ + index, 0:0 + length, :] + + start = start + length + + return probs_res, word_attention_map, None + else: + return word_decoder_result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_att_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_att_head.py new file mode 100644 index 0000000000000000000000000000000000000000..00b434105bd9fe1f0d928c5f026dc5804b33fe23 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_att_head.py @@ -0,0 +1,263 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +import paddle.nn as nn +from paddle import ParamAttr +import paddle.nn.functional as F +import numpy as np + +from .rec_att_head import AttentionGRUCell + + +def get_para_bias_attr(l2_decay, k): + if l2_decay > 0: + regularizer = paddle.regularizer.L2Decay(l2_decay) + stdv = 1.0 / math.sqrt(k * 1.0) + initializer = nn.initializer.Uniform(-stdv, stdv) + else: + regularizer = None + initializer = None + weight_attr = ParamAttr(regularizer=regularizer, initializer=initializer) + bias_attr = ParamAttr(regularizer=regularizer, initializer=initializer) + return [weight_attr, bias_attr] + + +class TableAttentionHead(nn.Layer): + def __init__(self, + in_channels, + hidden_size, + loc_type, + in_max_len=488, + max_text_length=800, + out_channels=30, + loc_reg_num=4, + **kwargs): + super(TableAttentionHead, self).__init__() + self.input_size = in_channels[-1] + self.hidden_size = hidden_size + self.out_channels = out_channels + self.max_text_length = max_text_length + + self.structure_attention_cell = AttentionGRUCell( + self.input_size, hidden_size, self.out_channels, use_gru=False) + self.structure_generator = nn.Linear(hidden_size, self.out_channels) + self.loc_type = loc_type + self.in_max_len = in_max_len + + if self.loc_type == 1: + self.loc_generator = nn.Linear(hidden_size, 4) + else: + if self.in_max_len == 640: + self.loc_fea_trans = nn.Linear(400, self.max_text_length + 1) + elif self.in_max_len == 800: + self.loc_fea_trans = nn.Linear(625, self.max_text_length + 1) + else: + self.loc_fea_trans = nn.Linear(256, self.max_text_length + 1) + self.loc_generator = nn.Linear(self.input_size + hidden_size, + loc_reg_num) + + def _char_to_onehot(self, input_char, onehot_dim): + input_ont_hot = F.one_hot(input_char, onehot_dim) + return input_ont_hot + + def forward(self, inputs, targets=None): + # if and else branch are both needed when you want to assign a variable + # if you modify the var in just one branch, then the modification will not work. + fea = inputs[-1] + if len(fea.shape) == 3: + pass + else: + last_shape = int(np.prod(fea.shape[2:])) # gry added + fea = paddle.reshape(fea, [fea.shape[0], fea.shape[1], last_shape]) + fea = fea.transpose([0, 2, 1]) # (NTC)(batch, width, channels) + batch_size = fea.shape[0] + + hidden = paddle.zeros((batch_size, self.hidden_size)) + output_hiddens = [] + if self.training and targets is not None: + structure = targets[0] + for i in range(self.max_text_length + 1): + elem_onehots = self._char_to_onehot( + structure[:, i], onehot_dim=self.out_channels) + (outputs, hidden), alpha = self.structure_attention_cell( + hidden, fea, elem_onehots) + output_hiddens.append(paddle.unsqueeze(outputs, axis=1)) + output = paddle.concat(output_hiddens, axis=1) + structure_probs = self.structure_generator(output) + if self.loc_type == 1: + loc_preds = self.loc_generator(output) + loc_preds = F.sigmoid(loc_preds) + else: + loc_fea = fea.transpose([0, 2, 1]) + loc_fea = self.loc_fea_trans(loc_fea) + loc_fea = loc_fea.transpose([0, 2, 1]) + loc_concat = paddle.concat([output, loc_fea], axis=2) + loc_preds = self.loc_generator(loc_concat) + loc_preds = F.sigmoid(loc_preds) + else: + temp_elem = paddle.zeros(shape=[batch_size], dtype="int32") + structure_probs = None + loc_preds = None + elem_onehots = None + outputs = None + alpha = None + max_text_length = paddle.to_tensor(self.max_text_length) + i = 0 + while i < max_text_length + 1: + elem_onehots = self._char_to_onehot( + temp_elem, onehot_dim=self.out_channels) + (outputs, hidden), alpha = self.structure_attention_cell( + hidden, fea, elem_onehots) + output_hiddens.append(paddle.unsqueeze(outputs, axis=1)) + structure_probs_step = self.structure_generator(outputs) + temp_elem = structure_probs_step.argmax(axis=1, dtype="int32") + i += 1 + + output = paddle.concat(output_hiddens, axis=1) + structure_probs = self.structure_generator(output) + structure_probs = F.softmax(structure_probs) + if self.loc_type == 1: + loc_preds = self.loc_generator(output) + loc_preds = F.sigmoid(loc_preds) + else: + loc_fea = fea.transpose([0, 2, 1]) + loc_fea = self.loc_fea_trans(loc_fea) + loc_fea = loc_fea.transpose([0, 2, 1]) + loc_concat = paddle.concat([output, loc_fea], axis=2) + loc_preds = self.loc_generator(loc_concat) + loc_preds = F.sigmoid(loc_preds) + return {'structure_probs': structure_probs, 'loc_preds': loc_preds} + + +class SLAHead(nn.Layer): + def __init__(self, + in_channels, + hidden_size, + out_channels=30, + max_text_length=500, + loc_reg_num=4, + fc_decay=0.0, + **kwargs): + """ + @param in_channels: input shape + @param hidden_size: hidden_size for RNN and Embedding + @param out_channels: num_classes to rec + @param max_text_length: max text pred + """ + super().__init__() + in_channels = in_channels[-1] + self.hidden_size = hidden_size + self.max_text_length = max_text_length + self.emb = self._char_to_onehot + self.num_embeddings = out_channels + + # structure + self.structure_attention_cell = AttentionGRUCell( + in_channels, hidden_size, self.num_embeddings) + weight_attr, bias_attr = get_para_bias_attr( + l2_decay=fc_decay, k=hidden_size) + weight_attr1_1, bias_attr1_1 = get_para_bias_attr( + l2_decay=fc_decay, k=hidden_size) + weight_attr1_2, bias_attr1_2 = get_para_bias_attr( + l2_decay=fc_decay, k=hidden_size) + self.structure_generator = nn.Sequential( + nn.Linear( + self.hidden_size, + self.hidden_size, + weight_attr=weight_attr1_2, + bias_attr=bias_attr1_2), + nn.Linear( + hidden_size, + out_channels, + weight_attr=weight_attr, + bias_attr=bias_attr)) + # loc + weight_attr1, bias_attr1 = get_para_bias_attr( + l2_decay=fc_decay, k=self.hidden_size) + weight_attr2, bias_attr2 = get_para_bias_attr( + l2_decay=fc_decay, k=self.hidden_size) + self.loc_generator = nn.Sequential( + nn.Linear( + self.hidden_size, + self.hidden_size, + weight_attr=weight_attr1, + bias_attr=bias_attr1), + nn.Linear( + self.hidden_size, + loc_reg_num, + weight_attr=weight_attr2, + bias_attr=bias_attr2), + nn.Sigmoid()) + + def forward(self, inputs, targets=None): + fea = inputs[-1] + batch_size = fea.shape[0] + # reshape + fea = paddle.reshape(fea, [fea.shape[0], fea.shape[1], -1]) + fea = fea.transpose([0, 2, 1]) # (NTC)(batch, width, channels) + + hidden = paddle.zeros((batch_size, self.hidden_size)) + structure_preds = [] + loc_preds = [] + if self.training and targets is not None: + structure = targets[0] + for i in range(self.max_text_length + 1): + hidden, structure_step, loc_step = self._decode(structure[:, i], + fea, hidden) + structure_preds.append(structure_step) + loc_preds.append(loc_step) + else: + pre_chars = paddle.zeros(shape=[batch_size], dtype="int32") + max_text_length = paddle.to_tensor(self.max_text_length) + # for export + loc_step, structure_step = None, None + for i in range(max_text_length + 1): + hidden, structure_step, loc_step = self._decode(pre_chars, fea, + hidden) + pre_chars = structure_step.argmax(axis=1, dtype="int32") + structure_preds.append(structure_step) + loc_preds.append(loc_step) + structure_preds = paddle.stack(structure_preds, axis=1) + loc_preds = paddle.stack(loc_preds, axis=1) + if not self.training: + structure_preds = F.softmax(structure_preds) + return {'structure_probs': structure_preds, 'loc_preds': loc_preds} + + def _decode(self, pre_chars, features, hidden): + """ + Predict table label and coordinates for each step + @param pre_chars: Table label in previous step + @param features: + @param hidden: hidden status in previous step + @return: + """ + emb_feature = self.emb(pre_chars) + # output shape is b * self.hidden_size + (output, hidden), alpha = self.structure_attention_cell( + hidden, features, emb_feature) + + # structure + structure_step = self.structure_generator(output) + # loc + loc_step = self.loc_generator(output) + return hidden, structure_step, loc_step + + def _char_to_onehot(self, input_char): + input_ont_hot = F.one_hot(input_char, self.num_embeddings) + return input_ont_hot diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_master_head.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_master_head.py new file mode 100644 index 0000000000000000000000000000000000000000..486f9cbea13c15b0f3a6d608789163f18f678914 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/heads/table_master_head.py @@ -0,0 +1,281 @@ +# Copyright (c) 2021 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. +""" +This code is refer from: +https://github.com/JiaquanYe/TableMASTER-mmocr/blob/master/mmocr/models/textrecog/decoders/master_decoder.py +""" + +import copy +import math +import paddle +from paddle import nn +from paddle.nn import functional as F + + +class TableMasterHead(nn.Layer): + """ + Split to two transformer header at the last layer. + Cls_layer is used to structure token classification. + Bbox_layer is used to regress bbox coord. + """ + + def __init__(self, + in_channels, + out_channels=30, + headers=8, + d_ff=2048, + dropout=0, + max_text_length=500, + loc_reg_num=4, + **kwargs): + super(TableMasterHead, self).__init__() + hidden_size = in_channels[-1] + self.layers = clones( + DecoderLayer(headers, hidden_size, dropout, d_ff), 2) + self.cls_layer = clones( + DecoderLayer(headers, hidden_size, dropout, d_ff), 1) + self.bbox_layer = clones( + DecoderLayer(headers, hidden_size, dropout, d_ff), 1) + self.cls_fc = nn.Linear(hidden_size, out_channels) + self.bbox_fc = nn.Sequential( + # nn.Linear(hidden_size, hidden_size), + nn.Linear(hidden_size, loc_reg_num), + nn.Sigmoid()) + self.norm = nn.LayerNorm(hidden_size) + self.embedding = Embeddings(d_model=hidden_size, vocab=out_channels) + self.positional_encoding = PositionalEncoding(d_model=hidden_size) + + self.SOS = out_channels - 3 + self.PAD = out_channels - 1 + self.out_channels = out_channels + self.loc_reg_num = loc_reg_num + self.max_text_length = max_text_length + + def make_mask(self, tgt): + """ + Make mask for self attention. + :param src: [b, c, h, l_src] + :param tgt: [b, l_tgt] + :return: + """ + trg_pad_mask = (tgt != self.PAD).unsqueeze(1).unsqueeze(3) + + tgt_len = paddle.shape(tgt)[1] + trg_sub_mask = paddle.tril( + paddle.ones( + ([tgt_len, tgt_len]), dtype=paddle.float32)) + + tgt_mask = paddle.logical_and( + trg_pad_mask.astype(paddle.float32), trg_sub_mask) + return tgt_mask.astype(paddle.float32) + + def decode(self, input, feature, src_mask, tgt_mask): + # main process of transformer decoder. + x = self.embedding(input) # x: 1*x*512, feature: 1*3600,512 + x = self.positional_encoding(x) + + # origin transformer layers + for i, layer in enumerate(self.layers): + x = layer(x, feature, src_mask, tgt_mask) + + # cls head + for layer in self.cls_layer: + cls_x = layer(x, feature, src_mask, tgt_mask) + cls_x = self.norm(cls_x) + + # bbox head + for layer in self.bbox_layer: + bbox_x = layer(x, feature, src_mask, tgt_mask) + bbox_x = self.norm(bbox_x) + return self.cls_fc(cls_x), self.bbox_fc(bbox_x) + + def greedy_forward(self, SOS, feature): + input = SOS + output = paddle.zeros( + [input.shape[0], self.max_text_length + 1, self.out_channels]) + bbox_output = paddle.zeros( + [input.shape[0], self.max_text_length + 1, self.loc_reg_num]) + max_text_length = paddle.to_tensor(self.max_text_length) + for i in range(max_text_length + 1): + target_mask = self.make_mask(input) + out_step, bbox_output_step = self.decode(input, feature, None, + target_mask) + prob = F.softmax(out_step, axis=-1) + next_word = prob.argmax(axis=2, dtype="int64") + input = paddle.concat( + [input, next_word[:, -1].unsqueeze(-1)], axis=1) + if i == self.max_text_length: + output = out_step + bbox_output = bbox_output_step + return output, bbox_output + + def forward_train(self, out_enc, targets): + # x is token of label + # feat is feature after backbone before pe. + # out_enc is feature after pe. + padded_targets = targets[0] + src_mask = None + tgt_mask = self.make_mask(padded_targets[:, :-1]) + output, bbox_output = self.decode(padded_targets[:, :-1], out_enc, + src_mask, tgt_mask) + return {'structure_probs': output, 'loc_preds': bbox_output} + + def forward_test(self, out_enc): + batch_size = out_enc.shape[0] + SOS = paddle.zeros([batch_size, 1], dtype='int64') + self.SOS + output, bbox_output = self.greedy_forward(SOS, out_enc) + output = F.softmax(output) + return {'structure_probs': output, 'loc_preds': bbox_output} + + def forward(self, feat, targets=None): + feat = feat[-1] + b, c, h, w = feat.shape + feat = feat.reshape([b, c, h * w]) # flatten 2D feature map + feat = feat.transpose((0, 2, 1)) + out_enc = self.positional_encoding(feat) + if self.training: + return self.forward_train(out_enc, targets) + + return self.forward_test(out_enc) + + +class DecoderLayer(nn.Layer): + """ + Decoder is made of self attention, srouce attention and feed forward. + """ + + def __init__(self, headers, d_model, dropout, d_ff): + super(DecoderLayer, self).__init__() + self.self_attn = MultiHeadAttention(headers, d_model, dropout) + self.src_attn = MultiHeadAttention(headers, d_model, dropout) + self.feed_forward = FeedForward(d_model, d_ff, dropout) + self.sublayer = clones(SubLayerConnection(d_model, dropout), 3) + + def forward(self, x, feature, src_mask, tgt_mask): + x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask)) + x = self.sublayer[1]( + x, lambda x: self.src_attn(x, feature, feature, src_mask)) + return self.sublayer[2](x, self.feed_forward) + + +class MultiHeadAttention(nn.Layer): + def __init__(self, headers, d_model, dropout): + super(MultiHeadAttention, self).__init__() + + assert d_model % headers == 0 + self.d_k = int(d_model / headers) + self.headers = headers + self.linears = clones(nn.Linear(d_model, d_model), 4) + self.attn = None + self.dropout = nn.Dropout(dropout) + + def forward(self, query, key, value, mask=None): + B = query.shape[0] + + # 1) Do all the linear projections in batch from d_model => h x d_k + query, key, value = \ + [l(x).reshape([B, 0, self.headers, self.d_k]).transpose([0, 2, 1, 3]) + for l, x in zip(self.linears, (query, key, value))] + # 2) Apply attention on all the projected vectors in batch + x, self.attn = self_attention( + query, key, value, mask=mask, dropout=self.dropout) + x = x.transpose([0, 2, 1, 3]).reshape([B, 0, self.headers * self.d_k]) + return self.linears[-1](x) + + +class FeedForward(nn.Layer): + def __init__(self, d_model, d_ff, dropout): + super(FeedForward, self).__init__() + self.w_1 = nn.Linear(d_model, d_ff) + self.w_2 = nn.Linear(d_ff, d_model) + self.dropout = nn.Dropout(dropout) + + def forward(self, x): + return self.w_2(self.dropout(F.relu(self.w_1(x)))) + + +class SubLayerConnection(nn.Layer): + """ + A residual connection followed by a layer norm. + Note for code simplicity the norm is first as opposed to last. + """ + + def __init__(self, size, dropout): + super(SubLayerConnection, self).__init__() + self.norm = nn.LayerNorm(size) + self.dropout = nn.Dropout(dropout) + + def forward(self, x, sublayer): + return x + self.dropout(sublayer(self.norm(x))) + + +def masked_fill(x, mask, value): + mask = mask.astype(x.dtype) + return x * paddle.logical_not(mask).astype(x.dtype) + mask * value + + +def self_attention(query, key, value, mask=None, dropout=None): + """ + Compute 'Scale Dot Product Attention' + """ + d_k = value.shape[-1] + + score = paddle.matmul(query, key.transpose([0, 1, 3, 2]) / math.sqrt(d_k)) + if mask is not None: + # score = score.masked_fill(mask == 0, -1e9) # b, h, L, L + score = masked_fill(score, mask == 0, -6.55e4) # for fp16 + + p_attn = F.softmax(score, axis=-1) + + if dropout is not None: + p_attn = dropout(p_attn) + return paddle.matmul(p_attn, value), p_attn + + +def clones(module, N): + """ Produce N identical layers """ + return nn.LayerList([copy.deepcopy(module) for _ in range(N)]) + + +class Embeddings(nn.Layer): + def __init__(self, d_model, vocab): + super(Embeddings, self).__init__() + self.lut = nn.Embedding(vocab, d_model) + self.d_model = d_model + + def forward(self, *input): + x = input[0] + return self.lut(x) * math.sqrt(self.d_model) + + +class PositionalEncoding(nn.Layer): + """ Implement the PE function. """ + + def __init__(self, d_model, dropout=0., max_len=5000): + super(PositionalEncoding, self).__init__() + self.dropout = nn.Dropout(p=dropout) + + # Compute the positional encodings once in log space. + pe = paddle.zeros([max_len, d_model]) + position = paddle.arange(0, max_len).unsqueeze(1).astype('float32') + div_term = paddle.exp( + paddle.arange(0, d_model, 2) * -math.log(10000.0) / d_model) + pe[:, 0::2] = paddle.sin(position * div_term) + pe[:, 1::2] = paddle.cos(position * div_term) + pe = pe.unsqueeze(0) + self.register_buffer('pe', pe) + + def forward(self, feat, **kwargs): + feat = feat + self.pe[:, :paddle.shape(feat)[1]] # pe 1*5000*512 + return self.dropout(feat) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3ae2d6ef27821f592645a4ba945d3feeaa8cf8a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/__init__.py @@ -0,0 +1,38 @@ +# 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. + +__all__ = ['build_neck'] + + +def build_neck(config): + from .db_fpn import DBFPN, RSEFPN, LKPAN + from .east_fpn import EASTFPN + from .sast_fpn import SASTFPN + from .rnn import SequenceEncoder + from .pg_fpn import PGFPN + from .table_fpn import TableFPN + from .fpn import FPN + from .fce_fpn import FCEFPN + from .pren_fpn import PRENFPN + from .csp_pan import CSPPAN + support_dict = [ + 'FPN', 'FCEFPN', 'LKPAN', 'DBFPN', 'RSEFPN', 'EASTFPN', 'SASTFPN', + 'SequenceEncoder', 'PGFPN', 'TableFPN', 'PRENFPN', 'CSPPAN' + ] + + module_name = config.pop('name') + assert module_name in support_dict, Exception('neck only support {}'.format( + support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/csp_pan.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/csp_pan.py new file mode 100755 index 0000000000000000000000000000000000000000..f4f8547f7d80d25edfe66824aa4f104341ae29ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/csp_pan.py @@ -0,0 +1,324 @@ +# Copyright (c) 2021 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. + +# The code is based on: +# https://github.com/PaddlePaddle/PaddleDetection/blob/release%2F2.3/ppdet/modeling/necks/csp_pan.py + +import paddle +import paddle.nn as nn +import paddle.nn.functional as F +from paddle import ParamAttr + +__all__ = ['CSPPAN'] + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channel=96, + out_channel=96, + kernel_size=3, + stride=1, + groups=1, + act='leaky_relu'): + super(ConvBNLayer, self).__init__() + initializer = nn.initializer.KaimingUniform() + self.act = act + assert self.act in ['leaky_relu', "hard_swish"] + self.conv = nn.Conv2D( + in_channels=in_channel, + out_channels=out_channel, + kernel_size=kernel_size, + groups=groups, + padding=(kernel_size - 1) // 2, + stride=stride, + weight_attr=ParamAttr(initializer=initializer), + bias_attr=False) + self.bn = nn.BatchNorm2D(out_channel) + + def forward(self, x): + x = self.bn(self.conv(x)) + if self.act == "leaky_relu": + x = F.leaky_relu(x) + elif self.act == "hard_swish": + x = F.hardswish(x) + return x + + +class DPModule(nn.Layer): + """ + Depth-wise and point-wise module. + Args: + in_channel (int): The input channels of this Module. + out_channel (int): The output channels of this Module. + kernel_size (int): The conv2d kernel size of this Module. + stride (int): The conv2d's stride of this Module. + act (str): The activation function of this Module, + Now support `leaky_relu` and `hard_swish`. + """ + + def __init__(self, + in_channel=96, + out_channel=96, + kernel_size=3, + stride=1, + act='leaky_relu'): + super(DPModule, self).__init__() + initializer = nn.initializer.KaimingUniform() + self.act = act + self.dwconv = nn.Conv2D( + in_channels=in_channel, + out_channels=out_channel, + kernel_size=kernel_size, + groups=out_channel, + padding=(kernel_size - 1) // 2, + stride=stride, + weight_attr=ParamAttr(initializer=initializer), + bias_attr=False) + self.bn1 = nn.BatchNorm2D(out_channel) + self.pwconv = nn.Conv2D( + in_channels=out_channel, + out_channels=out_channel, + kernel_size=1, + groups=1, + padding=0, + weight_attr=ParamAttr(initializer=initializer), + bias_attr=False) + self.bn2 = nn.BatchNorm2D(out_channel) + + def act_func(self, x): + if self.act == "leaky_relu": + x = F.leaky_relu(x) + elif self.act == "hard_swish": + x = F.hardswish(x) + return x + + def forward(self, x): + x = self.act_func(self.bn1(self.dwconv(x))) + x = self.act_func(self.bn2(self.pwconv(x))) + return x + + +class DarknetBottleneck(nn.Layer): + """The basic bottleneck block used in Darknet. + Each Block consists of two ConvModules and the input is added to the + final output. Each ConvModule is composed of Conv, BN, and act. + The first convLayer has filter size of 1x1 and the second one has the + filter size of 3x3. + Args: + in_channels (int): The input channels of this Module. + out_channels (int): The output channels of this Module. + expansion (int): The kernel size of the convolution. Default: 0.5 + add_identity (bool): Whether to add identity to the out. + Default: True + use_depthwise (bool): Whether to use depthwise separable convolution. + Default: False + """ + + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + expansion=0.5, + add_identity=True, + use_depthwise=False, + act="leaky_relu"): + super(DarknetBottleneck, self).__init__() + hidden_channels = int(out_channels * expansion) + conv_func = DPModule if use_depthwise else ConvBNLayer + self.conv1 = ConvBNLayer( + in_channel=in_channels, + out_channel=hidden_channels, + kernel_size=1, + act=act) + self.conv2 = conv_func( + in_channel=hidden_channels, + out_channel=out_channels, + kernel_size=kernel_size, + stride=1, + act=act) + self.add_identity = \ + add_identity and in_channels == out_channels + + def forward(self, x): + identity = x + out = self.conv1(x) + out = self.conv2(out) + + if self.add_identity: + return out + identity + else: + return out + + +class CSPLayer(nn.Layer): + """Cross Stage Partial Layer. + Args: + in_channels (int): The input channels of the CSP layer. + out_channels (int): The output channels of the CSP layer. + expand_ratio (float): Ratio to adjust the number of channels of the + hidden layer. Default: 0.5 + num_blocks (int): Number of blocks. Default: 1 + add_identity (bool): Whether to add identity in blocks. + Default: True + use_depthwise (bool): Whether to depthwise separable convolution in + blocks. Default: False + """ + + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + expand_ratio=0.5, + num_blocks=1, + add_identity=True, + use_depthwise=False, + act="leaky_relu"): + super().__init__() + mid_channels = int(out_channels * expand_ratio) + self.main_conv = ConvBNLayer(in_channels, mid_channels, 1, act=act) + self.short_conv = ConvBNLayer(in_channels, mid_channels, 1, act=act) + self.final_conv = ConvBNLayer( + 2 * mid_channels, out_channels, 1, act=act) + + self.blocks = nn.Sequential(* [ + DarknetBottleneck( + mid_channels, + mid_channels, + kernel_size, + 1.0, + add_identity, + use_depthwise, + act=act) for _ in range(num_blocks) + ]) + + def forward(self, x): + x_short = self.short_conv(x) + + x_main = self.main_conv(x) + x_main = self.blocks(x_main) + + x_final = paddle.concat((x_main, x_short), axis=1) + return self.final_conv(x_final) + + +class Channel_T(nn.Layer): + def __init__(self, + in_channels=[116, 232, 464], + out_channels=96, + act="leaky_relu"): + super(Channel_T, self).__init__() + self.convs = nn.LayerList() + for i in range(len(in_channels)): + self.convs.append( + ConvBNLayer( + in_channels[i], out_channels, 1, act=act)) + + def forward(self, x): + outs = [self.convs[i](x[i]) for i in range(len(x))] + return outs + + +class CSPPAN(nn.Layer): + """Path Aggregation Network with CSP module. + Args: + in_channels (List[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale) + kernel_size (int): The conv2d kernel size of this Module. + num_csp_blocks (int): Number of bottlenecks in CSPLayer. Default: 1 + use_depthwise (bool): Whether to depthwise separable convolution in + blocks. Default: True + """ + + def __init__(self, + in_channels, + out_channels, + kernel_size=5, + num_csp_blocks=1, + use_depthwise=True, + act='hard_swish'): + super(CSPPAN, self).__init__() + self.in_channels = in_channels + self.out_channels = [out_channels] * len(in_channels) + conv_func = DPModule if use_depthwise else ConvBNLayer + + self.conv_t = Channel_T(in_channels, out_channels, act=act) + + # build top-down blocks + self.upsample = nn.Upsample(scale_factor=2, mode='nearest') + self.top_down_blocks = nn.LayerList() + for idx in range(len(in_channels) - 1, 0, -1): + self.top_down_blocks.append( + CSPLayer( + out_channels * 2, + out_channels, + kernel_size=kernel_size, + num_blocks=num_csp_blocks, + add_identity=False, + use_depthwise=use_depthwise, + act=act)) + + # build bottom-up blocks + self.downsamples = nn.LayerList() + self.bottom_up_blocks = nn.LayerList() + for idx in range(len(in_channels) - 1): + self.downsamples.append( + conv_func( + out_channels, + out_channels, + kernel_size=kernel_size, + stride=2, + act=act)) + self.bottom_up_blocks.append( + CSPLayer( + out_channels * 2, + out_channels, + kernel_size=kernel_size, + num_blocks=num_csp_blocks, + add_identity=False, + use_depthwise=use_depthwise, + act=act)) + + def forward(self, inputs): + """ + Args: + inputs (tuple[Tensor]): input features. + Returns: + tuple[Tensor]: CSPPAN features. + """ + assert len(inputs) == len(self.in_channels) + inputs = self.conv_t(inputs) + + # top-down path + inner_outs = [inputs[-1]] + for idx in range(len(self.in_channels) - 1, 0, -1): + feat_heigh = inner_outs[0] + feat_low = inputs[idx - 1] + upsample_feat = F.upsample( + feat_heigh, size=paddle.shape(feat_low)[2:4], mode="nearest") + + inner_out = self.top_down_blocks[len(self.in_channels) - 1 - idx]( + paddle.concat([upsample_feat, feat_low], 1)) + inner_outs.insert(0, inner_out) + + # bottom-up path + outs = [inner_outs[0]] + for idx in range(len(self.in_channels) - 1): + feat_low = outs[-1] + feat_height = inner_outs[idx + 1] + downsample_feat = self.downsamples[idx](feat_low) + out = self.bottom_up_blocks[idx](paddle.concat( + [downsample_feat, feat_height], 1)) + outs.append(out) + + return tuple(outs) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/db_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/db_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3f52a331db5daafab2a38c0a441edd44eb141d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/db_fpn.py @@ -0,0 +1,427 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../../..'))) + +from ppocr.modeling.backbones.det_mobilenet_v3 import SEModule + + +class DSConv(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + padding, + stride=1, + groups=None, + if_act=True, + act="relu", + **kwargs): + super(DSConv, self).__init__() + if groups == None: + groups = in_channels + self.if_act = if_act + self.act = act + self.conv1 = nn.Conv2D( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + bias_attr=False) + + self.bn1 = nn.BatchNorm(num_channels=in_channels, act=None) + + self.conv2 = nn.Conv2D( + in_channels=in_channels, + out_channels=int(in_channels * 4), + kernel_size=1, + stride=1, + bias_attr=False) + + self.bn2 = nn.BatchNorm(num_channels=int(in_channels * 4), act=None) + + self.conv3 = nn.Conv2D( + in_channels=int(in_channels * 4), + out_channels=out_channels, + kernel_size=1, + stride=1, + bias_attr=False) + self._c = [in_channels, out_channels] + if in_channels != out_channels: + self.conv_end = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + bias_attr=False) + + def forward(self, inputs): + + x = self.conv1(inputs) + x = self.bn1(x) + + x = self.conv2(x) + x = self.bn2(x) + if self.if_act: + if self.act == "relu": + x = F.relu(x) + elif self.act == "hardswish": + x = F.hardswish(x) + else: + print("The activation function({}) is selected incorrectly.". + format(self.act)) + exit() + + x = self.conv3(x) + if self._c[0] != self._c[1]: + x = x + self.conv_end(inputs) + return x + + +class DBFPN(nn.Layer): + def __init__(self, in_channels, out_channels, use_asf=False, **kwargs): + super(DBFPN, self).__init__() + self.out_channels = out_channels + self.use_asf = use_asf + weight_attr = paddle.nn.initializer.KaimingUniform() + + self.in2_conv = nn.Conv2D( + in_channels=in_channels[0], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in3_conv = nn.Conv2D( + in_channels=in_channels[1], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in4_conv = nn.Conv2D( + in_channels=in_channels[2], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in5_conv = nn.Conv2D( + in_channels=in_channels[3], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p5_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p4_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p3_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p2_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + + if self.use_asf is True: + self.asf = ASFBlock(self.out_channels, self.out_channels // 4) + + def forward(self, x): + c2, c3, c4, c5 = x + + in5 = self.in5_conv(c5) + in4 = self.in4_conv(c4) + in3 = self.in3_conv(c3) + in2 = self.in2_conv(c2) + + out4 = in4 + F.upsample( + in5, scale_factor=2, mode="nearest", align_mode=1) # 1/16 + out3 = in3 + F.upsample( + out4, scale_factor=2, mode="nearest", align_mode=1) # 1/8 + out2 = in2 + F.upsample( + out3, scale_factor=2, mode="nearest", align_mode=1) # 1/4 + + p5 = self.p5_conv(in5) + p4 = self.p4_conv(out4) + p3 = self.p3_conv(out3) + p2 = self.p2_conv(out2) + p5 = F.upsample(p5, scale_factor=8, mode="nearest", align_mode=1) + p4 = F.upsample(p4, scale_factor=4, mode="nearest", align_mode=1) + p3 = F.upsample(p3, scale_factor=2, mode="nearest", align_mode=1) + + fuse = paddle.concat([p5, p4, p3, p2], axis=1) + + if self.use_asf is True: + fuse = self.asf(fuse, [p5, p4, p3, p2]) + + return fuse + + +class RSELayer(nn.Layer): + def __init__(self, in_channels, out_channels, kernel_size, shortcut=True): + super(RSELayer, self).__init__() + weight_attr = paddle.nn.initializer.KaimingUniform() + self.out_channels = out_channels + self.in_conv = nn.Conv2D( + in_channels=in_channels, + out_channels=self.out_channels, + kernel_size=kernel_size, + padding=int(kernel_size // 2), + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.se_block = SEModule(self.out_channels) + self.shortcut = shortcut + + def forward(self, ins): + x = self.in_conv(ins) + if self.shortcut: + out = x + self.se_block(x) + else: + out = self.se_block(x) + return out + + +class RSEFPN(nn.Layer): + def __init__(self, in_channels, out_channels, shortcut=True, **kwargs): + super(RSEFPN, self).__init__() + self.out_channels = out_channels + self.ins_conv = nn.LayerList() + self.inp_conv = nn.LayerList() + + for i in range(len(in_channels)): + self.ins_conv.append( + RSELayer( + in_channels[i], + out_channels, + kernel_size=1, + shortcut=shortcut)) + self.inp_conv.append( + RSELayer( + out_channels, + out_channels // 4, + kernel_size=3, + shortcut=shortcut)) + + def forward(self, x): + c2, c3, c4, c5 = x + + in5 = self.ins_conv[3](c5) + in4 = self.ins_conv[2](c4) + in3 = self.ins_conv[1](c3) + in2 = self.ins_conv[0](c2) + + out4 = in4 + F.upsample( + in5, scale_factor=2, mode="nearest", align_mode=1) # 1/16 + out3 = in3 + F.upsample( + out4, scale_factor=2, mode="nearest", align_mode=1) # 1/8 + out2 = in2 + F.upsample( + out3, scale_factor=2, mode="nearest", align_mode=1) # 1/4 + + p5 = self.inp_conv[3](in5) + p4 = self.inp_conv[2](out4) + p3 = self.inp_conv[1](out3) + p2 = self.inp_conv[0](out2) + + p5 = F.upsample(p5, scale_factor=8, mode="nearest", align_mode=1) + p4 = F.upsample(p4, scale_factor=4, mode="nearest", align_mode=1) + p3 = F.upsample(p3, scale_factor=2, mode="nearest", align_mode=1) + + fuse = paddle.concat([p5, p4, p3, p2], axis=1) + return fuse + + +class LKPAN(nn.Layer): + def __init__(self, in_channels, out_channels, mode='large', **kwargs): + super(LKPAN, self).__init__() + self.out_channels = out_channels + weight_attr = paddle.nn.initializer.KaimingUniform() + + self.ins_conv = nn.LayerList() + self.inp_conv = nn.LayerList() + # pan head + self.pan_head_conv = nn.LayerList() + self.pan_lat_conv = nn.LayerList() + + if mode.lower() == 'lite': + p_layer = DSConv + elif mode.lower() == 'large': + p_layer = nn.Conv2D + else: + raise ValueError( + "mode can only be one of ['lite', 'large'], but received {}". + format(mode)) + + for i in range(len(in_channels)): + self.ins_conv.append( + nn.Conv2D( + in_channels=in_channels[i], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False)) + + self.inp_conv.append( + p_layer( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=9, + padding=4, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False)) + + if i > 0: + self.pan_head_conv.append( + nn.Conv2D( + in_channels=self.out_channels // 4, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + stride=2, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False)) + self.pan_lat_conv.append( + p_layer( + in_channels=self.out_channels // 4, + out_channels=self.out_channels // 4, + kernel_size=9, + padding=4, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False)) + + def forward(self, x): + c2, c3, c4, c5 = x + + in5 = self.ins_conv[3](c5) + in4 = self.ins_conv[2](c4) + in3 = self.ins_conv[1](c3) + in2 = self.ins_conv[0](c2) + + out4 = in4 + F.upsample( + in5, scale_factor=2, mode="nearest", align_mode=1) # 1/16 + out3 = in3 + F.upsample( + out4, scale_factor=2, mode="nearest", align_mode=1) # 1/8 + out2 = in2 + F.upsample( + out3, scale_factor=2, mode="nearest", align_mode=1) # 1/4 + + f5 = self.inp_conv[3](in5) + f4 = self.inp_conv[2](out4) + f3 = self.inp_conv[1](out3) + f2 = self.inp_conv[0](out2) + + pan3 = f3 + self.pan_head_conv[0](f2) + pan4 = f4 + self.pan_head_conv[1](pan3) + pan5 = f5 + self.pan_head_conv[2](pan4) + + p2 = self.pan_lat_conv[0](f2) + p3 = self.pan_lat_conv[1](pan3) + p4 = self.pan_lat_conv[2](pan4) + p5 = self.pan_lat_conv[3](pan5) + + p5 = F.upsample(p5, scale_factor=8, mode="nearest", align_mode=1) + p4 = F.upsample(p4, scale_factor=4, mode="nearest", align_mode=1) + p3 = F.upsample(p3, scale_factor=2, mode="nearest", align_mode=1) + + fuse = paddle.concat([p5, p4, p3, p2], axis=1) + return fuse + + +class ASFBlock(nn.Layer): + """ + This code is refered from: + https://github.com/MhLiao/DB/blob/master/decoders/feature_attention.py + """ + + def __init__(self, in_channels, inter_channels, out_features_num=4): + """ + Adaptive Scale Fusion (ASF) block of DBNet++ + Args: + in_channels: the number of channels in the input data + inter_channels: the number of middle channels + out_features_num: the number of fused stages + """ + super(ASFBlock, self).__init__() + weight_attr = paddle.nn.initializer.KaimingUniform() + self.in_channels = in_channels + self.inter_channels = inter_channels + self.out_features_num = out_features_num + self.conv = nn.Conv2D(in_channels, inter_channels, 3, padding=1) + + self.spatial_scale = nn.Sequential( + #Nx1xHxW + nn.Conv2D( + in_channels=1, + out_channels=1, + kernel_size=3, + bias_attr=False, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr)), + nn.ReLU(), + nn.Conv2D( + in_channels=1, + out_channels=1, + kernel_size=1, + bias_attr=False, + weight_attr=ParamAttr(initializer=weight_attr)), + nn.Sigmoid()) + + self.channel_scale = nn.Sequential( + nn.Conv2D( + in_channels=inter_channels, + out_channels=out_features_num, + kernel_size=1, + bias_attr=False, + weight_attr=ParamAttr(initializer=weight_attr)), + nn.Sigmoid()) + + def forward(self, fuse_features, features_list): + fuse_features = self.conv(fuse_features) + spatial_x = paddle.mean(fuse_features, axis=1, keepdim=True) + attention_scores = self.spatial_scale(spatial_x) + fuse_features + attention_scores = self.channel_scale(attention_scores) + assert len(features_list) == self.out_features_num + + out_list = [] + for i in range(self.out_features_num): + out_list.append(attention_scores[:, i:i + 1] * features_list[i]) + return paddle.concat(out_list, axis=1) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/east_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/east_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..120ff156cba2f7f8f8a562e76c82f1fac8584d4a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/east_fpn.py @@ -0,0 +1,188 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups=1, + if_act=True, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class DeConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups=1, + if_act=True, + act=None, + name=None): + super(DeConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.deconv = nn.Conv2DTranspose( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.deconv(x) + x = self.bn(x) + return x + + +class EASTFPN(nn.Layer): + def __init__(self, in_channels, model_name, **kwargs): + super(EASTFPN, self).__init__() + self.model_name = model_name + if self.model_name == "large": + self.out_channels = 128 + else: + self.out_channels = 64 + self.in_channels = in_channels[::-1] + self.h1_conv = ConvBNLayer( + in_channels=self.out_channels+self.in_channels[1], + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="unet_h_1") + self.h2_conv = ConvBNLayer( + in_channels=self.out_channels+self.in_channels[2], + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="unet_h_2") + self.h3_conv = ConvBNLayer( + in_channels=self.out_channels+self.in_channels[3], + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="unet_h_3") + self.g0_deconv = DeConvBNLayer( + in_channels=self.in_channels[0], + out_channels=self.out_channels, + kernel_size=4, + stride=2, + padding=1, + if_act=True, + act='relu', + name="unet_g_0") + self.g1_deconv = DeConvBNLayer( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=4, + stride=2, + padding=1, + if_act=True, + act='relu', + name="unet_g_1") + self.g2_deconv = DeConvBNLayer( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=4, + stride=2, + padding=1, + if_act=True, + act='relu', + name="unet_g_2") + self.g3_conv = ConvBNLayer( + in_channels=self.out_channels, + out_channels=self.out_channels, + kernel_size=3, + stride=1, + padding=1, + if_act=True, + act='relu', + name="unet_g_3") + + def forward(self, x): + f = x[::-1] + + h = f[0] + g = self.g0_deconv(h) + h = paddle.concat([g, f[1]], axis=1) + h = self.h1_conv(h) + g = self.g1_deconv(h) + h = paddle.concat([g, f[2]], axis=1) + h = self.h2_conv(h) + g = self.g2_deconv(h) + h = paddle.concat([g, f[3]], axis=1) + h = self.h3_conv(h) + g = self.g3_conv(h) + + return g \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fce_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fce_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..954e964e97d6061d9cc684ccac8a1b137d5d069c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fce_fpn.py @@ -0,0 +1,280 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.3/ppdet/modeling/necks/fpn.py +""" + +import paddle.nn as nn +import paddle.nn.functional as F +from paddle import ParamAttr +from paddle.nn.initializer import XavierUniform +from paddle.nn.initializer import Normal +from paddle.regularizer import L2Decay + +__all__ = ['FCEFPN'] + + +class ConvNormLayer(nn.Layer): + def __init__(self, + ch_in, + ch_out, + filter_size, + stride, + groups=1, + norm_type='bn', + norm_decay=0., + norm_groups=32, + lr_scale=1., + freeze_norm=False, + initializer=Normal( + mean=0., std=0.01)): + super(ConvNormLayer, self).__init__() + assert norm_type in ['bn', 'sync_bn', 'gn'] + + bias_attr = False + + self.conv = nn.Conv2D( + in_channels=ch_in, + out_channels=ch_out, + kernel_size=filter_size, + stride=stride, + padding=(filter_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr( + initializer=initializer, learning_rate=1.), + bias_attr=bias_attr) + + norm_lr = 0. if freeze_norm else 1. + param_attr = ParamAttr( + learning_rate=norm_lr, + regularizer=L2Decay(norm_decay) if norm_decay is not None else None) + bias_attr = ParamAttr( + learning_rate=norm_lr, + regularizer=L2Decay(norm_decay) if norm_decay is not None else None) + if norm_type == 'bn': + self.norm = nn.BatchNorm2D( + ch_out, weight_attr=param_attr, bias_attr=bias_attr) + elif norm_type == 'sync_bn': + self.norm = nn.SyncBatchNorm( + ch_out, weight_attr=param_attr, bias_attr=bias_attr) + elif norm_type == 'gn': + self.norm = nn.GroupNorm( + num_groups=norm_groups, + num_channels=ch_out, + weight_attr=param_attr, + bias_attr=bias_attr) + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + return out + + +class FCEFPN(nn.Layer): + """ + Feature Pyramid Network, see https://arxiv.org/abs/1612.03144 + Args: + in_channels (list[int]): input channels of each level which can be + derived from the output shape of backbone by from_config + out_channels (list[int]): output channel of each level + spatial_scales (list[float]): the spatial scales between input feature + maps and original input image which can be derived from the output + shape of backbone by from_config + has_extra_convs (bool): whether to add extra conv to the last level. + default False + extra_stage (int): the number of extra stages added to the last level. + default 1 + use_c5 (bool): Whether to use c5 as the input of extra stage, + otherwise p5 is used. default True + norm_type (string|None): The normalization type in FPN module. If + norm_type is None, norm will not be used after conv and if + norm_type is string, bn, gn, sync_bn are available. default None + norm_decay (float): weight decay for normalization layer weights. + default 0. + freeze_norm (bool): whether to freeze normalization layer. + default False + relu_before_extra_convs (bool): whether to add relu before extra convs. + default False + + """ + + def __init__(self, + in_channels, + out_channels, + spatial_scales=[0.25, 0.125, 0.0625, 0.03125], + has_extra_convs=False, + extra_stage=1, + use_c5=True, + norm_type=None, + norm_decay=0., + freeze_norm=False, + relu_before_extra_convs=True): + super(FCEFPN, self).__init__() + self.out_channels = out_channels + for s in range(extra_stage): + spatial_scales = spatial_scales + [spatial_scales[-1] / 2.] + self.spatial_scales = spatial_scales + self.has_extra_convs = has_extra_convs + self.extra_stage = extra_stage + self.use_c5 = use_c5 + self.relu_before_extra_convs = relu_before_extra_convs + self.norm_type = norm_type + self.norm_decay = norm_decay + self.freeze_norm = freeze_norm + + self.lateral_convs = [] + self.fpn_convs = [] + fan = out_channels * 3 * 3 + + # stage index 0,1,2,3 stands for res2,res3,res4,res5 on ResNet Backbone + # 0 <= st_stage < ed_stage <= 3 + st_stage = 4 - len(in_channels) + ed_stage = st_stage + len(in_channels) - 1 + for i in range(st_stage, ed_stage + 1): + if i == 3: + lateral_name = 'fpn_inner_res5_sum' + else: + lateral_name = 'fpn_inner_res{}_sum_lateral'.format(i + 2) + in_c = in_channels[i - st_stage] + if self.norm_type is not None: + lateral = self.add_sublayer( + lateral_name, + ConvNormLayer( + ch_in=in_c, + ch_out=out_channels, + filter_size=1, + stride=1, + norm_type=self.norm_type, + norm_decay=self.norm_decay, + freeze_norm=self.freeze_norm, + initializer=XavierUniform(fan_out=in_c))) + else: + lateral = self.add_sublayer( + lateral_name, + nn.Conv2D( + in_channels=in_c, + out_channels=out_channels, + kernel_size=1, + weight_attr=ParamAttr( + initializer=XavierUniform(fan_out=in_c)))) + self.lateral_convs.append(lateral) + + for i in range(st_stage, ed_stage + 1): + fpn_name = 'fpn_res{}_sum'.format(i + 2) + if self.norm_type is not None: + fpn_conv = self.add_sublayer( + fpn_name, + ConvNormLayer( + ch_in=out_channels, + ch_out=out_channels, + filter_size=3, + stride=1, + norm_type=self.norm_type, + norm_decay=self.norm_decay, + freeze_norm=self.freeze_norm, + initializer=XavierUniform(fan_out=fan))) + else: + fpn_conv = self.add_sublayer( + fpn_name, + nn.Conv2D( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + padding=1, + weight_attr=ParamAttr( + initializer=XavierUniform(fan_out=fan)))) + self.fpn_convs.append(fpn_conv) + + # add extra conv levels for RetinaNet(use_c5)/FCOS(use_p5) + if self.has_extra_convs: + for i in range(self.extra_stage): + lvl = ed_stage + 1 + i + if i == 0 and self.use_c5: + in_c = in_channels[-1] + else: + in_c = out_channels + extra_fpn_name = 'fpn_{}'.format(lvl + 2) + if self.norm_type is not None: + extra_fpn_conv = self.add_sublayer( + extra_fpn_name, + ConvNormLayer( + ch_in=in_c, + ch_out=out_channels, + filter_size=3, + stride=2, + norm_type=self.norm_type, + norm_decay=self.norm_decay, + freeze_norm=self.freeze_norm, + initializer=XavierUniform(fan_out=fan))) + else: + extra_fpn_conv = self.add_sublayer( + extra_fpn_name, + nn.Conv2D( + in_channels=in_c, + out_channels=out_channels, + kernel_size=3, + stride=2, + padding=1, + weight_attr=ParamAttr( + initializer=XavierUniform(fan_out=fan)))) + self.fpn_convs.append(extra_fpn_conv) + + @classmethod + def from_config(cls, cfg, input_shape): + return { + 'in_channels': [i.channels for i in input_shape], + 'spatial_scales': [1.0 / i.stride for i in input_shape], + } + + def forward(self, body_feats): + laterals = [] + num_levels = len(body_feats) + + for i in range(num_levels): + laterals.append(self.lateral_convs[i](body_feats[i])) + + for i in range(1, num_levels): + lvl = num_levels - i + upsample = F.interpolate( + laterals[lvl], + scale_factor=2., + mode='nearest', ) + laterals[lvl - 1] += upsample + + fpn_output = [] + for lvl in range(num_levels): + fpn_output.append(self.fpn_convs[lvl](laterals[lvl])) + + if self.extra_stage > 0: + # use max pool to get more levels on top of outputs (Faster R-CNN, Mask R-CNN) + if not self.has_extra_convs: + assert self.extra_stage == 1, 'extra_stage should be 1 if FPN has not extra convs' + fpn_output.append(F.max_pool2d(fpn_output[-1], 1, stride=2)) + # add extra conv levels for RetinaNet(use_c5)/FCOS(use_p5) + else: + if self.use_c5: + extra_source = body_feats[-1] + else: + extra_source = fpn_output[-1] + fpn_output.append(self.fpn_convs[num_levels](extra_source)) + + for i in range(1, self.extra_stage): + if self.relu_before_extra_convs: + fpn_output.append(self.fpn_convs[num_levels + i](F.relu( + fpn_output[-1]))) + else: + fpn_output.append(self.fpn_convs[num_levels + i]( + fpn_output[-1])) + return fpn_output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..48c85b1e53bd889bc887e8fedcd33b1b12cb734b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/fpn.py @@ -0,0 +1,138 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/neck/fpn.py +""" + +import paddle.nn as nn +import paddle +import math +import paddle.nn.functional as F + + +class Conv_BN_ReLU(nn.Layer): + def __init__(self, + in_planes, + out_planes, + kernel_size=1, + stride=1, + padding=0): + super(Conv_BN_ReLU, self).__init__() + self.conv = nn.Conv2D( + in_planes, + out_planes, + kernel_size=kernel_size, + stride=stride, + padding=padding, + bias_attr=False) + self.bn = nn.BatchNorm2D(out_planes, momentum=0.1) + self.relu = nn.ReLU() + + for m in self.sublayers(): + if isinstance(m, nn.Conv2D): + n = m._kernel_size[0] * m._kernel_size[1] * m._out_channels + m.weight = paddle.create_parameter( + shape=m.weight.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Normal( + 0, math.sqrt(2. / n))) + elif isinstance(m, nn.BatchNorm2D): + m.weight = paddle.create_parameter( + shape=m.weight.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Constant(1.0)) + m.bias = paddle.create_parameter( + shape=m.bias.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Constant(0.0)) + + def forward(self, x): + return self.relu(self.bn(self.conv(x))) + + +class FPN(nn.Layer): + def __init__(self, in_channels, out_channels): + super(FPN, self).__init__() + + # Top layer + self.toplayer_ = Conv_BN_ReLU( + in_channels[3], out_channels, kernel_size=1, stride=1, padding=0) + # Lateral layers + self.latlayer1_ = Conv_BN_ReLU( + in_channels[2], out_channels, kernel_size=1, stride=1, padding=0) + + self.latlayer2_ = Conv_BN_ReLU( + in_channels[1], out_channels, kernel_size=1, stride=1, padding=0) + + self.latlayer3_ = Conv_BN_ReLU( + in_channels[0], out_channels, kernel_size=1, stride=1, padding=0) + + # Smooth layers + self.smooth1_ = Conv_BN_ReLU( + out_channels, out_channels, kernel_size=3, stride=1, padding=1) + + self.smooth2_ = Conv_BN_ReLU( + out_channels, out_channels, kernel_size=3, stride=1, padding=1) + + self.smooth3_ = Conv_BN_ReLU( + out_channels, out_channels, kernel_size=3, stride=1, padding=1) + + self.out_channels = out_channels * 4 + for m in self.sublayers(): + if isinstance(m, nn.Conv2D): + n = m._kernel_size[0] * m._kernel_size[1] * m._out_channels + m.weight = paddle.create_parameter( + shape=m.weight.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Normal( + 0, math.sqrt(2. / n))) + elif isinstance(m, nn.BatchNorm2D): + m.weight = paddle.create_parameter( + shape=m.weight.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Constant(1.0)) + m.bias = paddle.create_parameter( + shape=m.bias.shape, + dtype='float32', + default_initializer=paddle.nn.initializer.Constant(0.0)) + + def _upsample(self, x, scale=1): + return F.upsample(x, scale_factor=scale, mode='bilinear') + + def _upsample_add(self, x, y, scale=1): + return F.upsample(x, scale_factor=scale, mode='bilinear') + y + + def forward(self, x): + f2, f3, f4, f5 = x + p5 = self.toplayer_(f5) + + f4 = self.latlayer1_(f4) + p4 = self._upsample_add(p5, f4, 2) + p4 = self.smooth1_(p4) + + f3 = self.latlayer2_(f3) + p3 = self._upsample_add(p4, f3, 2) + p3 = self.smooth2_(p3) + + f2 = self.latlayer3_(f2) + p2 = self._upsample_add(p3, f2, 2) + p2 = self.smooth3_(p2) + + p3 = self._upsample(p3, 2) + p4 = self._upsample(p4, 4) + p5 = self._upsample(p5, 8) + + fuse = paddle.concat([p2, p3, p4, p5], axis=1) + return fuse diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pg_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pg_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..3f64539f790b55bb1f95adc8d3c78b84ca2fccc5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pg_fpn.py @@ -0,0 +1,314 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + is_vd_mode=False, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + + self.is_vd_mode = is_vd_mode + self._pool2d_avg = nn.AvgPool2D( + kernel_size=2, stride=2, padding=0, ceil_mode=True) + self._conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + "_weights"), + bias_attr=False) + if name == "conv1": + bn_name = "bn_" + name + else: + bn_name = "bn" + name[3:] + self._batch_norm = nn.BatchNorm( + out_channels, + act=act, + param_attr=ParamAttr(name=bn_name + '_scale'), + bias_attr=ParamAttr(bn_name + '_offset'), + moving_mean_name=bn_name + '_mean', + moving_variance_name=bn_name + '_variance', + use_global_stats=False) + + def forward(self, inputs): + y = self._conv(inputs) + y = self._batch_norm(y) + return y + + +class DeConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size=4, + stride=2, + padding=1, + groups=1, + if_act=True, + act=None, + name=None): + super(DeConvBNLayer, self).__init__() + + self.if_act = if_act + self.act = act + self.deconv = nn.Conv2DTranspose( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance", + use_global_stats=False) + + def forward(self, x): + x = self.deconv(x) + x = self.bn(x) + return x + + +class PGFPN(nn.Layer): + def __init__(self, in_channels, **kwargs): + super(PGFPN, self).__init__() + num_inputs = [2048, 2048, 1024, 512, 256] + num_outputs = [256, 256, 192, 192, 128] + self.out_channels = 128 + self.conv_bn_layer_1 = ConvBNLayer( + in_channels=3, + out_channels=32, + kernel_size=3, + stride=1, + act=None, + name='FPN_d1') + self.conv_bn_layer_2 = ConvBNLayer( + in_channels=64, + out_channels=64, + kernel_size=3, + stride=1, + act=None, + name='FPN_d2') + self.conv_bn_layer_3 = ConvBNLayer( + in_channels=256, + out_channels=128, + kernel_size=3, + stride=1, + act=None, + name='FPN_d3') + self.conv_bn_layer_4 = ConvBNLayer( + in_channels=32, + out_channels=64, + kernel_size=3, + stride=2, + act=None, + name='FPN_d4') + self.conv_bn_layer_5 = ConvBNLayer( + in_channels=64, + out_channels=64, + kernel_size=3, + stride=1, + act='relu', + name='FPN_d5') + self.conv_bn_layer_6 = ConvBNLayer( + in_channels=64, + out_channels=128, + kernel_size=3, + stride=2, + act=None, + name='FPN_d6') + self.conv_bn_layer_7 = ConvBNLayer( + in_channels=128, + out_channels=128, + kernel_size=3, + stride=1, + act='relu', + name='FPN_d7') + self.conv_bn_layer_8 = ConvBNLayer( + in_channels=128, + out_channels=128, + kernel_size=1, + stride=1, + act=None, + name='FPN_d8') + + self.conv_h0 = ConvBNLayer( + in_channels=num_inputs[0], + out_channels=num_outputs[0], + kernel_size=1, + stride=1, + act=None, + name="conv_h{}".format(0)) + self.conv_h1 = ConvBNLayer( + in_channels=num_inputs[1], + out_channels=num_outputs[1], + kernel_size=1, + stride=1, + act=None, + name="conv_h{}".format(1)) + self.conv_h2 = ConvBNLayer( + in_channels=num_inputs[2], + out_channels=num_outputs[2], + kernel_size=1, + stride=1, + act=None, + name="conv_h{}".format(2)) + self.conv_h3 = ConvBNLayer( + in_channels=num_inputs[3], + out_channels=num_outputs[3], + kernel_size=1, + stride=1, + act=None, + name="conv_h{}".format(3)) + self.conv_h4 = ConvBNLayer( + in_channels=num_inputs[4], + out_channels=num_outputs[4], + kernel_size=1, + stride=1, + act=None, + name="conv_h{}".format(4)) + + self.dconv0 = DeConvBNLayer( + in_channels=num_outputs[0], + out_channels=num_outputs[0 + 1], + name="dconv_{}".format(0)) + self.dconv1 = DeConvBNLayer( + in_channels=num_outputs[1], + out_channels=num_outputs[1 + 1], + act=None, + name="dconv_{}".format(1)) + self.dconv2 = DeConvBNLayer( + in_channels=num_outputs[2], + out_channels=num_outputs[2 + 1], + act=None, + name="dconv_{}".format(2)) + self.dconv3 = DeConvBNLayer( + in_channels=num_outputs[3], + out_channels=num_outputs[3 + 1], + act=None, + name="dconv_{}".format(3)) + self.conv_g1 = ConvBNLayer( + in_channels=num_outputs[1], + out_channels=num_outputs[1], + kernel_size=3, + stride=1, + act='relu', + name="conv_g{}".format(1)) + self.conv_g2 = ConvBNLayer( + in_channels=num_outputs[2], + out_channels=num_outputs[2], + kernel_size=3, + stride=1, + act='relu', + name="conv_g{}".format(2)) + self.conv_g3 = ConvBNLayer( + in_channels=num_outputs[3], + out_channels=num_outputs[3], + kernel_size=3, + stride=1, + act='relu', + name="conv_g{}".format(3)) + self.conv_g4 = ConvBNLayer( + in_channels=num_outputs[4], + out_channels=num_outputs[4], + kernel_size=3, + stride=1, + act='relu', + name="conv_g{}".format(4)) + self.convf = ConvBNLayer( + in_channels=num_outputs[4], + out_channels=num_outputs[4], + kernel_size=1, + stride=1, + act=None, + name="conv_f{}".format(4)) + + def forward(self, x): + c0, c1, c2, c3, c4, c5, c6 = x + # FPN_Down_Fusion + f = [c0, c1, c2] + g = [None, None, None] + h = [None, None, None] + h[0] = self.conv_bn_layer_1(f[0]) + h[1] = self.conv_bn_layer_2(f[1]) + h[2] = self.conv_bn_layer_3(f[2]) + + g[0] = self.conv_bn_layer_4(h[0]) + g[1] = paddle.add(g[0], h[1]) + g[1] = F.relu(g[1]) + g[1] = self.conv_bn_layer_5(g[1]) + g[1] = self.conv_bn_layer_6(g[1]) + + g[2] = paddle.add(g[1], h[2]) + g[2] = F.relu(g[2]) + g[2] = self.conv_bn_layer_7(g[2]) + f_down = self.conv_bn_layer_8(g[2]) + + # FPN UP Fusion + f1 = [c6, c5, c4, c3, c2] + g = [None, None, None, None, None] + h = [None, None, None, None, None] + h[0] = self.conv_h0(f1[0]) + h[1] = self.conv_h1(f1[1]) + h[2] = self.conv_h2(f1[2]) + h[3] = self.conv_h3(f1[3]) + h[4] = self.conv_h4(f1[4]) + + g[0] = self.dconv0(h[0]) + g[1] = paddle.add(g[0], h[1]) + g[1] = F.relu(g[1]) + g[1] = self.conv_g1(g[1]) + g[1] = self.dconv1(g[1]) + + g[2] = paddle.add(g[1], h[2]) + g[2] = F.relu(g[2]) + g[2] = self.conv_g2(g[2]) + g[2] = self.dconv2(g[2]) + + g[3] = paddle.add(g[2], h[3]) + g[3] = F.relu(g[3]) + g[3] = self.conv_g3(g[3]) + g[3] = self.dconv3(g[3]) + + g[4] = paddle.add(x=g[3], y=h[4]) + g[4] = F.relu(g[4]) + g[4] = self.conv_g4(g[4]) + f_up = self.convf(g[4]) + f_common = paddle.add(f_down, f_up) + f_common = F.relu(f_common) + return f_common diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pren_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pren_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..afbdcea83d9a5a827d805a542b56e6be11b03389 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/pren_fpn.py @@ -0,0 +1,163 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +Code is refer from: +https://github.com/RuijieJ/pren/blob/main/Nets/Aggregation.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F + + +class PoolAggregate(nn.Layer): + def __init__(self, n_r, d_in, d_middle=None, d_out=None): + super(PoolAggregate, self).__init__() + if not d_middle: + d_middle = d_in + if not d_out: + d_out = d_in + + self.d_in = d_in + self.d_middle = d_middle + self.d_out = d_out + self.act = nn.Swish() + + self.n_r = n_r + self.aggs = self._build_aggs() + + def _build_aggs(self): + aggs = [] + for i in range(self.n_r): + aggs.append( + self.add_sublayer( + '{}'.format(i), + nn.Sequential( + ('conv1', nn.Conv2D( + self.d_in, self.d_middle, 3, 2, 1, bias_attr=False) + ), ('bn1', nn.BatchNorm(self.d_middle)), + ('act', self.act), ('conv2', nn.Conv2D( + self.d_middle, self.d_out, 3, 2, 1, bias_attr=False + )), ('bn2', nn.BatchNorm(self.d_out))))) + return aggs + + def forward(self, x): + b = x.shape[0] + outs = [] + for agg in self.aggs: + y = agg(x) + p = F.adaptive_avg_pool2d(y, 1) + outs.append(p.reshape((b, 1, self.d_out))) + out = paddle.concat(outs, 1) + return out + + +class WeightAggregate(nn.Layer): + def __init__(self, n_r, d_in, d_middle=None, d_out=None): + super(WeightAggregate, self).__init__() + if not d_middle: + d_middle = d_in + if not d_out: + d_out = d_in + + self.n_r = n_r + self.d_out = d_out + self.act = nn.Swish() + + self.conv_n = nn.Sequential( + ('conv1', nn.Conv2D( + d_in, d_in, 3, 1, 1, + bias_attr=False)), ('bn1', nn.BatchNorm(d_in)), + ('act1', self.act), ('conv2', nn.Conv2D( + d_in, n_r, 1, bias_attr=False)), ('bn2', nn.BatchNorm(n_r)), + ('act2', nn.Sigmoid())) + self.conv_d = nn.Sequential( + ('conv1', nn.Conv2D( + d_in, d_middle, 3, 1, 1, + bias_attr=False)), ('bn1', nn.BatchNorm(d_middle)), + ('act1', self.act), ('conv2', nn.Conv2D( + d_middle, d_out, 1, + bias_attr=False)), ('bn2', nn.BatchNorm(d_out))) + + def forward(self, x): + b, _, h, w = x.shape + + hmaps = self.conv_n(x) + fmaps = self.conv_d(x) + r = paddle.bmm( + hmaps.reshape((b, self.n_r, h * w)), + fmaps.reshape((b, self.d_out, h * w)).transpose((0, 2, 1))) + return r + + +class GCN(nn.Layer): + def __init__(self, d_in, n_in, d_out=None, n_out=None, dropout=0.1): + super(GCN, self).__init__() + if not d_out: + d_out = d_in + if not n_out: + n_out = d_in + + self.conv_n = nn.Conv1D(n_in, n_out, 1) + self.linear = nn.Linear(d_in, d_out) + self.dropout = nn.Dropout(dropout) + self.act = nn.Swish() + + def forward(self, x): + x = self.conv_n(x) + x = self.dropout(self.linear(x)) + return self.act(x) + + +class PRENFPN(nn.Layer): + def __init__(self, in_channels, n_r, d_model, max_len, dropout): + super(PRENFPN, self).__init__() + assert len(in_channels) == 3, "in_channels' length must be 3." + c1, c2, c3 = in_channels # the depths are from big to small + # build fpn + assert d_model % 3 == 0, "{} can't be divided by 3.".format(d_model) + self.agg_p1 = PoolAggregate(n_r, c1, d_out=d_model // 3) + self.agg_p2 = PoolAggregate(n_r, c2, d_out=d_model // 3) + self.agg_p3 = PoolAggregate(n_r, c3, d_out=d_model // 3) + + self.agg_w1 = WeightAggregate(n_r, c1, 4 * c1, d_model // 3) + self.agg_w2 = WeightAggregate(n_r, c2, 4 * c2, d_model // 3) + self.agg_w3 = WeightAggregate(n_r, c3, 4 * c3, d_model // 3) + + self.gcn_pool = GCN(d_model, n_r, d_model, max_len, dropout) + self.gcn_weight = GCN(d_model, n_r, d_model, max_len, dropout) + + self.out_channels = d_model + + def forward(self, inputs): + f3, f5, f7 = inputs + + rp1 = self.agg_p1(f3) + rp2 = self.agg_p2(f5) + rp3 = self.agg_p3(f7) + rp = paddle.concat([rp1, rp2, rp3], 2) # [b,nr,d] + + rw1 = self.agg_w1(f3) + rw2 = self.agg_w2(f5) + rw3 = self.agg_w3(f7) + rw = paddle.concat([rw1, rw2, rw3], 2) # [b,nr,d] + + y1 = self.gcn_pool(rp) + y2 = self.gcn_weight(rw) + y = 0.5 * (y1 + y2) + return y # [b,max_len,d] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/rnn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..33be9400b34cb535d260881748e179c3df106caa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/rnn.py @@ -0,0 +1,245 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn + +from ppocr.modeling.heads.rec_ctc_head import get_para_bias_attr +from ppocr.modeling.backbones.rec_svtrnet import Block, ConvBNLayer, trunc_normal_, zeros_, ones_ + + +class Im2Seq(nn.Layer): + def __init__(self, in_channels, **kwargs): + super().__init__() + self.out_channels = in_channels + + def forward(self, x): + B, C, H, W = x.shape + assert H == 1 + x = x.squeeze(axis=2) + x = x.transpose([0, 2, 1]) # (NTC)(batch, width, channels) + return x + + +class EncoderWithRNN(nn.Layer): + def __init__(self, in_channels, hidden_size): + super(EncoderWithRNN, self).__init__() + self.out_channels = hidden_size * 2 + self.lstm = nn.LSTM( + in_channels, hidden_size, direction='bidirectional', num_layers=2) + + def forward(self, x): + x, _ = self.lstm(x) + return x + +class BidirectionalLSTM(nn.Layer): + def __init__(self, input_size, + hidden_size, + output_size=None, + num_layers=1, + dropout=0, + direction=False, + time_major=False, + with_linear=False): + super(BidirectionalLSTM, self).__init__() + self.with_linear = with_linear + self.rnn = nn.LSTM(input_size, + hidden_size, + num_layers=num_layers, + dropout=dropout, + direction=direction, + time_major=time_major) + + # text recognition the specified structure LSTM with linear + if self.with_linear: + self.linear = nn.Linear(hidden_size * 2, output_size) + + def forward(self, input_feature): + recurrent, _ = self.rnn(input_feature) # batch_size x T x input_size -> batch_size x T x (2*hidden_size) + if self.with_linear: + output = self.linear(recurrent) # batch_size x T x output_size + return output + return recurrent + +class EncoderWithCascadeRNN(nn.Layer): + def __init__(self, in_channels, hidden_size, out_channels, num_layers=2, with_linear=False): + super(EncoderWithCascadeRNN, self).__init__() + self.out_channels = out_channels[-1] + self.encoder = nn.LayerList( + [BidirectionalLSTM( + in_channels if i == 0 else out_channels[i - 1], + hidden_size, + output_size=out_channels[i], + num_layers=1, + direction='bidirectional', + with_linear=with_linear) + for i in range(num_layers)] + ) + + + def forward(self, x): + for i, l in enumerate(self.encoder): + x = l(x) + return x + + +class EncoderWithFC(nn.Layer): + def __init__(self, in_channels, hidden_size): + super(EncoderWithFC, self).__init__() + self.out_channels = hidden_size + weight_attr, bias_attr = get_para_bias_attr( + l2_decay=0.00001, k=in_channels) + self.fc = nn.Linear( + in_channels, + hidden_size, + weight_attr=weight_attr, + bias_attr=bias_attr, + name='reduce_encoder_fea') + + def forward(self, x): + x = self.fc(x) + return x + + +class EncoderWithSVTR(nn.Layer): + def __init__( + self, + in_channels, + dims=64, # XS + depth=2, + hidden_dims=120, + use_guide=False, + num_heads=8, + qkv_bias=True, + mlp_ratio=2.0, + drop_rate=0.1, + attn_drop_rate=0.1, + drop_path=0., + qk_scale=None): + super(EncoderWithSVTR, self).__init__() + self.depth = depth + self.use_guide = use_guide + self.conv1 = ConvBNLayer( + in_channels, in_channels // 8, padding=1, act=nn.Swish) + self.conv2 = ConvBNLayer( + in_channels // 8, hidden_dims, kernel_size=1, act=nn.Swish) + + self.svtr_block = nn.LayerList([ + Block( + dim=hidden_dims, + num_heads=num_heads, + mixer='Global', + HW=None, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.Swish, + attn_drop=attn_drop_rate, + drop_path=drop_path, + norm_layer='nn.LayerNorm', + epsilon=1e-05, + prenorm=False) for i in range(depth) + ]) + self.norm = nn.LayerNorm(hidden_dims, epsilon=1e-6) + self.conv3 = ConvBNLayer( + hidden_dims, in_channels, kernel_size=1, act=nn.Swish) + # last conv-nxn, the input is concat of input tensor and conv3 output tensor + self.conv4 = ConvBNLayer( + 2 * in_channels, in_channels // 8, padding=1, act=nn.Swish) + + self.conv1x1 = ConvBNLayer( + in_channels // 8, dims, kernel_size=1, act=nn.Swish) + self.out_channels = dims + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight) + if isinstance(m, nn.Linear) and m.bias is not None: + zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + zeros_(m.bias) + ones_(m.weight) + + def forward(self, x): + # for use guide + if self.use_guide: + z = x.clone() + z.stop_gradient = True + else: + z = x + # for short cut + h = z + # reduce dim + z = self.conv1(z) + z = self.conv2(z) + # SVTR global block + B, C, H, W = z.shape + z = z.flatten(2).transpose([0, 2, 1]) + for blk in self.svtr_block: + z = blk(z) + z = self.norm(z) + # last stage + z = z.reshape([0, H, W, C]).transpose([0, 3, 1, 2]) + z = self.conv3(z) + z = paddle.concat((h, z), axis=1) + z = self.conv1x1(self.conv4(z)) + return z + + +class SequenceEncoder(nn.Layer): + def __init__(self, in_channels, encoder_type, hidden_size=48, **kwargs): + super(SequenceEncoder, self).__init__() + self.encoder_reshape = Im2Seq(in_channels) + self.out_channels = self.encoder_reshape.out_channels + self.encoder_type = encoder_type + if encoder_type == 'reshape': + self.only_reshape = True + else: + support_encoder_dict = { + 'reshape': Im2Seq, + 'fc': EncoderWithFC, + 'rnn': EncoderWithRNN, + 'svtr': EncoderWithSVTR, + 'cascadernn': EncoderWithCascadeRNN + } + assert encoder_type in support_encoder_dict, '{} must in {}'.format( + encoder_type, support_encoder_dict.keys()) + if encoder_type == "svtr": + self.encoder = support_encoder_dict[encoder_type]( + self.encoder_reshape.out_channels, **kwargs) + elif encoder_type == 'cascadernn': + self.encoder = support_encoder_dict[encoder_type]( + self.encoder_reshape.out_channels, hidden_size, **kwargs) + else: + self.encoder = support_encoder_dict[encoder_type]( + self.encoder_reshape.out_channels, hidden_size) + self.out_channels = self.encoder.out_channels + self.only_reshape = False + + def forward(self, x): + if self.encoder_type != 'svtr': + x = self.encoder_reshape(x) + if not self.only_reshape: + x = self.encoder(x) + return x + else: + x = self.encoder(x) + x = self.encoder_reshape(x) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/sast_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/sast_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6024590ac574f725fc6c519dd96ee4462276d6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/sast_fpn.py @@ -0,0 +1,284 @@ +# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + groups=1, + if_act=True, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class DeConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride, + groups=1, + if_act=True, + act=None, + name=None): + super(DeConvBNLayer, self).__init__() + self.if_act = if_act + self.act = act + self.deconv = nn.Conv2DTranspose( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + '_weights'), + bias_attr=False) + self.bn = nn.BatchNorm( + num_channels=out_channels, + act=act, + param_attr=ParamAttr(name="bn_" + name + "_scale"), + bias_attr=ParamAttr(name="bn_" + name + "_offset"), + moving_mean_name="bn_" + name + "_mean", + moving_variance_name="bn_" + name + "_variance") + + def forward(self, x): + x = self.deconv(x) + x = self.bn(x) + return x + + +class FPN_Up_Fusion(nn.Layer): + def __init__(self, in_channels): + super(FPN_Up_Fusion, self).__init__() + in_channels = in_channels[::-1] + out_channels = [256, 256, 192, 192, 128] + + self.h0_conv = ConvBNLayer(in_channels[0], out_channels[0], 1, 1, act=None, name='fpn_up_h0') + self.h1_conv = ConvBNLayer(in_channels[1], out_channels[1], 1, 1, act=None, name='fpn_up_h1') + self.h2_conv = ConvBNLayer(in_channels[2], out_channels[2], 1, 1, act=None, name='fpn_up_h2') + self.h3_conv = ConvBNLayer(in_channels[3], out_channels[3], 1, 1, act=None, name='fpn_up_h3') + self.h4_conv = ConvBNLayer(in_channels[4], out_channels[4], 1, 1, act=None, name='fpn_up_h4') + + self.g0_conv = DeConvBNLayer(out_channels[0], out_channels[1], 4, 2, act=None, name='fpn_up_g0') + + self.g1_conv = nn.Sequential( + ConvBNLayer(out_channels[1], out_channels[1], 3, 1, act='relu', name='fpn_up_g1_1'), + DeConvBNLayer(out_channels[1], out_channels[2], 4, 2, act=None, name='fpn_up_g1_2') + ) + self.g2_conv = nn.Sequential( + ConvBNLayer(out_channels[2], out_channels[2], 3, 1, act='relu', name='fpn_up_g2_1'), + DeConvBNLayer(out_channels[2], out_channels[3], 4, 2, act=None, name='fpn_up_g2_2') + ) + self.g3_conv = nn.Sequential( + ConvBNLayer(out_channels[3], out_channels[3], 3, 1, act='relu', name='fpn_up_g3_1'), + DeConvBNLayer(out_channels[3], out_channels[4], 4, 2, act=None, name='fpn_up_g3_2') + ) + + self.g4_conv = nn.Sequential( + ConvBNLayer(out_channels[4], out_channels[4], 3, 1, act='relu', name='fpn_up_fusion_1'), + ConvBNLayer(out_channels[4], out_channels[4], 1, 1, act=None, name='fpn_up_fusion_2') + ) + + def _add_relu(self, x1, x2): + x = paddle.add(x=x1, y=x2) + x = F.relu(x) + return x + + def forward(self, x): + f = x[2:][::-1] + h0 = self.h0_conv(f[0]) + h1 = self.h1_conv(f[1]) + h2 = self.h2_conv(f[2]) + h3 = self.h3_conv(f[3]) + h4 = self.h4_conv(f[4]) + + g0 = self.g0_conv(h0) + g1 = self._add_relu(g0, h1) + g1 = self.g1_conv(g1) + g2 = self.g2_conv(self._add_relu(g1, h2)) + g3 = self.g3_conv(self._add_relu(g2, h3)) + g4 = self.g4_conv(self._add_relu(g3, h4)) + + return g4 + + +class FPN_Down_Fusion(nn.Layer): + def __init__(self, in_channels): + super(FPN_Down_Fusion, self).__init__() + out_channels = [32, 64, 128] + + self.h0_conv = ConvBNLayer(in_channels[0], out_channels[0], 3, 1, act=None, name='fpn_down_h0') + self.h1_conv = ConvBNLayer(in_channels[1], out_channels[1], 3, 1, act=None, name='fpn_down_h1') + self.h2_conv = ConvBNLayer(in_channels[2], out_channels[2], 3, 1, act=None, name='fpn_down_h2') + + self.g0_conv = ConvBNLayer(out_channels[0], out_channels[1], 3, 2, act=None, name='fpn_down_g0') + + self.g1_conv = nn.Sequential( + ConvBNLayer(out_channels[1], out_channels[1], 3, 1, act='relu', name='fpn_down_g1_1'), + ConvBNLayer(out_channels[1], out_channels[2], 3, 2, act=None, name='fpn_down_g1_2') + ) + + self.g2_conv = nn.Sequential( + ConvBNLayer(out_channels[2], out_channels[2], 3, 1, act='relu', name='fpn_down_fusion_1'), + ConvBNLayer(out_channels[2], out_channels[2], 1, 1, act=None, name='fpn_down_fusion_2') + ) + + def forward(self, x): + f = x[:3] + h0 = self.h0_conv(f[0]) + h1 = self.h1_conv(f[1]) + h2 = self.h2_conv(f[2]) + g0 = self.g0_conv(h0) + g1 = paddle.add(x=g0, y=h1) + g1 = F.relu(g1) + g1 = self.g1_conv(g1) + g2 = paddle.add(x=g1, y=h2) + g2 = F.relu(g2) + g2 = self.g2_conv(g2) + return g2 + + +class Cross_Attention(nn.Layer): + def __init__(self, in_channels): + super(Cross_Attention, self).__init__() + self.theta_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_theta') + self.phi_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_phi') + self.g_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act='relu', name='f_g') + + self.fh_weight_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fh_weight') + self.fh_sc_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fh_sc') + + self.fv_weight_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fv_weight') + self.fv_sc_conv = ConvBNLayer(in_channels, in_channels, 1, 1, act=None, name='fv_sc') + + self.f_attn_conv = ConvBNLayer(in_channels * 2, in_channels, 1, 1, act='relu', name='f_attn') + + def _cal_fweight(self, f, shape): + f_theta, f_phi, f_g = f + #flatten + f_theta = paddle.transpose(f_theta, [0, 2, 3, 1]) + f_theta = paddle.reshape(f_theta, [shape[0] * shape[1], shape[2], 128]) + f_phi = paddle.transpose(f_phi, [0, 2, 3, 1]) + f_phi = paddle.reshape(f_phi, [shape[0] * shape[1], shape[2], 128]) + f_g = paddle.transpose(f_g, [0, 2, 3, 1]) + f_g = paddle.reshape(f_g, [shape[0] * shape[1], shape[2], 128]) + #correlation + f_attn = paddle.matmul(f_theta, paddle.transpose(f_phi, [0, 2, 1])) + #scale + f_attn = f_attn / (128**0.5) + f_attn = F.softmax(f_attn) + #weighted sum + f_weight = paddle.matmul(f_attn, f_g) + f_weight = paddle.reshape( + f_weight, [shape[0], shape[1], shape[2], 128]) + return f_weight + + def forward(self, f_common): + f_shape = paddle.shape(f_common) + # print('f_shape: ', f_shape) + + f_theta = self.theta_conv(f_common) + f_phi = self.phi_conv(f_common) + f_g = self.g_conv(f_common) + + ######## horizon ######## + fh_weight = self._cal_fweight([f_theta, f_phi, f_g], + [f_shape[0], f_shape[2], f_shape[3]]) + fh_weight = paddle.transpose(fh_weight, [0, 3, 1, 2]) + fh_weight = self.fh_weight_conv(fh_weight) + #short cut + fh_sc = self.fh_sc_conv(f_common) + f_h = F.relu(fh_weight + fh_sc) + + ######## vertical ######## + fv_theta = paddle.transpose(f_theta, [0, 1, 3, 2]) + fv_phi = paddle.transpose(f_phi, [0, 1, 3, 2]) + fv_g = paddle.transpose(f_g, [0, 1, 3, 2]) + fv_weight = self._cal_fweight([fv_theta, fv_phi, fv_g], + [f_shape[0], f_shape[3], f_shape[2]]) + fv_weight = paddle.transpose(fv_weight, [0, 3, 2, 1]) + fv_weight = self.fv_weight_conv(fv_weight) + #short cut + fv_sc = self.fv_sc_conv(f_common) + f_v = F.relu(fv_weight + fv_sc) + + ######## merge ######## + f_attn = paddle.concat([f_h, f_v], axis=1) + f_attn = self.f_attn_conv(f_attn) + return f_attn + + +class SASTFPN(nn.Layer): + def __init__(self, in_channels, with_cab=False, **kwargs): + super(SASTFPN, self).__init__() + self.in_channels = in_channels + self.with_cab = with_cab + self.FPN_Down_Fusion = FPN_Down_Fusion(self.in_channels) + self.FPN_Up_Fusion = FPN_Up_Fusion(self.in_channels) + self.out_channels = 128 + self.cross_attention = Cross_Attention(self.out_channels) + + def forward(self, x): + #down fpn + f_down = self.FPN_Down_Fusion(x) + + #up fpn + f_up = self.FPN_Up_Fusion(x) + + #fusion + f_common = paddle.add(x=f_down, y=f_up) + f_common = F.relu(f_common) + + if self.with_cab: + # print('enhence f_common with CAB.') + f_common = self.cross_attention(f_common) + + return f_common diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/table_fpn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/table_fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..734f15af65e4e15a7ddb4004954a61bfa1934246 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/necks/table_fpn.py @@ -0,0 +1,110 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import paddle +from paddle import nn +import paddle.nn.functional as F +from paddle import ParamAttr + + +class TableFPN(nn.Layer): + def __init__(self, in_channels, out_channels, **kwargs): + super(TableFPN, self).__init__() + self.out_channels = 512 + weight_attr = paddle.nn.initializer.KaimingUniform() + self.in2_conv = nn.Conv2D( + in_channels=in_channels[0], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in3_conv = nn.Conv2D( + in_channels=in_channels[1], + out_channels=self.out_channels, + kernel_size=1, + stride = 1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in4_conv = nn.Conv2D( + in_channels=in_channels[2], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.in5_conv = nn.Conv2D( + in_channels=in_channels[3], + out_channels=self.out_channels, + kernel_size=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p5_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p4_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p3_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.p2_conv = nn.Conv2D( + in_channels=self.out_channels, + out_channels=self.out_channels // 4, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), + bias_attr=False) + self.fuse_conv = nn.Conv2D( + in_channels=self.out_channels * 4, + out_channels=512, + kernel_size=3, + padding=1, + weight_attr=ParamAttr(initializer=weight_attr), bias_attr=False) + + def forward(self, x): + c2, c3, c4, c5 = x + + in5 = self.in5_conv(c5) + in4 = self.in4_conv(c4) + in3 = self.in3_conv(c3) + in2 = self.in2_conv(c2) + + out4 = in4 + F.upsample( + in5, size=in4.shape[2:4], mode="nearest", align_mode=1) # 1/16 + out3 = in3 + F.upsample( + out4, size=in3.shape[2:4], mode="nearest", align_mode=1) # 1/8 + out2 = in2 + F.upsample( + out3, size=in2.shape[2:4], mode="nearest", align_mode=1) # 1/4 + + p4 = F.upsample(out4, size=in5.shape[2:4], mode="nearest", align_mode=1) + p3 = F.upsample(out3, size=in5.shape[2:4], mode="nearest", align_mode=1) + p2 = F.upsample(out2, size=in5.shape[2:4], mode="nearest", align_mode=1) + fuse = paddle.concat([in5, p4, p3, p2], axis=1) + fuse_conv = self.fuse_conv(fuse) * 0.005 + return [c5 + fuse_conv] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..b22c60bb3d5e1933056d37bad208f4c311139c8e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/__init__.py @@ -0,0 +1,30 @@ +# 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. + +__all__ = ['build_transform'] + + +def build_transform(config): + from .tps import TPS + from .stn import STN_ON + from .tsrn import TSRN + from .gaspin_transformer import GA_SPIN_Transformer as GA_SPIN + + support_dict = ['TPS', 'STN_ON', 'GA_SPIN', 'TSRN'] + + module_name = config.pop('name') + assert module_name in support_dict, Exception( + 'transform only support {}'.format(support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/gaspin_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/gaspin_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..f4719eb2162a02141620586bcb6a849ae16f3b62 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/gaspin_transformer.py @@ -0,0 +1,284 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np +import functools +from .tps import GridGenerator + +'''This code is refer from: +https://github.com/hikopensource/DAVAR-Lab-OCR/davarocr/davar_rcg/models/transformations/gaspin_transformation.py +''' + +class SP_TransformerNetwork(nn.Layer): + """ + Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] + Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021. + """ + + def __init__(self, nc=1, default_type=5): + """ Based on SPIN + Args: + nc (int): number of input channels (usually in 1 or 3) + default_type (int): the complexity of transformation intensities (by default set to 6 as the paper) + """ + super(SP_TransformerNetwork, self).__init__() + self.power_list = self.cal_K(default_type) + self.sigmoid = nn.Sigmoid() + self.bn = nn.InstanceNorm2D(nc) + + def cal_K(self, k=5): + """ + + Args: + k (int): the complexity of transformation intensities (by default set to 6 as the paper) + + Returns: + List: the normalized intensity of each pixel in [0,1], denoted as \beta [1x(2K+1)] + + """ + from math import log + x = [] + if k != 0: + for i in range(1, k+1): + lower = round(log(1-(0.5/(k+1))*i)/log((0.5/(k+1))*i), 2) + upper = round(1/lower, 2) + x.append(lower) + x.append(upper) + x.append(1.00) + return x + + def forward(self, batch_I, weights, offsets, lambda_color=None): + """ + + Args: + batch_I (Tensor): batch of input images [batch_size x nc x I_height x I_width] + weights: + offsets: the predicted offset by AIN, a scalar + lambda_color: the learnable update gate \alpha in Equa. (5) as + g(x) = (1 - \alpha) \odot x + \alpha \odot x_{offsets} + + Returns: + Tensor: transformed images by SPN as Equa. (4) in Ref. [1] + [batch_size x I_channel_num x I_r_height x I_r_width] + + """ + batch_I = (batch_I + 1) * 0.5 + if offsets is not None: + batch_I = batch_I*(1-lambda_color) + offsets*lambda_color + batch_weight_params = paddle.unsqueeze(paddle.unsqueeze(weights, -1), -1) + batch_I_power = paddle.stack([batch_I.pow(p) for p in self.power_list], axis=1) + + batch_weight_sum = paddle.sum(batch_I_power * batch_weight_params, axis=1) + batch_weight_sum = self.bn(batch_weight_sum) + batch_weight_sum = self.sigmoid(batch_weight_sum) + batch_weight_sum = batch_weight_sum * 2 - 1 + return batch_weight_sum + +class GA_SPIN_Transformer(nn.Layer): + """ + Geometric-Absorbed SPIN Transformation (GA-SPIN) proposed in Ref. [1] + + + Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021. + """ + + def __init__(self, in_channels=1, + I_r_size=(32, 100), + offsets=False, + norm_type='BN', + default_type=6, + loc_lr=1, + stn=True): + """ + Args: + in_channels (int): channel of input features, + set it to 1 if the grayscale images and 3 if RGB input + I_r_size (tuple): size of rectified images (used in STN transformations) + offsets (bool): set it to False if use SPN w.o. AIN, + and set it to True if use SPIN (both with SPN and AIN) + norm_type (str): the normalization type of the module, + set it to 'BN' by default, 'IN' optionally + default_type (int): the K chromatic space, + set it to 3/5/6 depend on the complexity of transformation intensities + loc_lr (float): learning rate of location network + stn (bool): whther to use stn. + + """ + super(GA_SPIN_Transformer, self).__init__() + self.nc = in_channels + self.spt = True + self.offsets = offsets + self.stn = stn # set to True in GA-SPIN, while set it to False in SPIN + self.I_r_size = I_r_size + self.out_channels = in_channels + if norm_type == 'BN': + norm_layer = functools.partial(nn.BatchNorm2D, use_global_stats=True) + elif norm_type == 'IN': + norm_layer = functools.partial(nn.InstanceNorm2D, weight_attr=False, + use_global_stats=False) + else: + raise NotImplementedError('normalization layer [%s] is not found' % norm_type) + + if self.spt: + self.sp_net = SP_TransformerNetwork(in_channels, + default_type) + self.spt_convnet = nn.Sequential( + # 32*100 + nn.Conv2D(in_channels, 32, 3, 1, 1, bias_attr=False), + norm_layer(32), nn.ReLU(), + nn.MaxPool2D(kernel_size=2, stride=2), + # 16*50 + nn.Conv2D(32, 64, 3, 1, 1, bias_attr=False), + norm_layer(64), nn.ReLU(), + nn.MaxPool2D(kernel_size=2, stride=2), + # 8*25 + nn.Conv2D(64, 128, 3, 1, 1, bias_attr=False), + norm_layer(128), nn.ReLU(), + nn.MaxPool2D(kernel_size=2, stride=2), + # 4*12 + ) + self.stucture_fc1 = nn.Sequential( + nn.Conv2D(128, 256, 3, 1, 1, bias_attr=False), + norm_layer(256), nn.ReLU(), + nn.MaxPool2D(kernel_size=2, stride=2), + nn.Conv2D(256, 256, 3, 1, 1, bias_attr=False), + norm_layer(256), nn.ReLU(), # 2*6 + nn.MaxPool2D(kernel_size=2, stride=2), + nn.Conv2D(256, 512, 3, 1, 1, bias_attr=False), + norm_layer(512), nn.ReLU(), # 1*3 + nn.AdaptiveAvgPool2D(1), + nn.Flatten(1, -1), # batch_size x 512 + nn.Linear(512, 256, weight_attr=nn.initializer.Normal(0.001)), + nn.BatchNorm1D(256), nn.ReLU() + ) + self.out_weight = 2*default_type+1 + self.spt_length = 2*default_type+1 + if offsets: + self.out_weight += 1 + if self.stn: + self.F = 20 + self.out_weight += self.F * 2 + self.GridGenerator = GridGenerator(self.F*2, self.F) + + # self.out_weight*=nc + # Init structure_fc2 in LocalizationNetwork + initial_bias = self.init_spin(default_type*2) + initial_bias = initial_bias.reshape(-1) + param_attr = ParamAttr( + learning_rate=loc_lr, + initializer=nn.initializer.Assign(np.zeros([256, self.out_weight]))) + bias_attr = ParamAttr( + learning_rate=loc_lr, + initializer=nn.initializer.Assign(initial_bias)) + self.stucture_fc2 = nn.Linear(256, self.out_weight, + weight_attr=param_attr, + bias_attr=bias_attr) + self.sigmoid = nn.Sigmoid() + + if offsets: + self.offset_fc1 = nn.Sequential(nn.Conv2D(128, 16, + 3, 1, 1, + bias_attr=False), + norm_layer(16), + nn.ReLU(),) + self.offset_fc2 = nn.Conv2D(16, in_channels, + 3, 1, 1) + self.pool = nn.MaxPool2D(2, 2) + + def init_spin(self, nz): + """ + Args: + nz (int): number of paired \betas exponents, which means the value of K x 2 + + """ + init_id = [0.00]*nz+[5.00] + if self.offsets: + init_id += [-5.00] + # init_id *=3 + init = np.array(init_id) + + if self.stn: + F = self.F + ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2)) + ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2)) + ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2)) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0) + initial_bias = initial_bias.reshape(-1) + init = np.concatenate([init, initial_bias], axis=0) + return init + + def forward(self, x, return_weight=False): + """ + Args: + x (Tensor): input image batch + return_weight (bool): set to False by default, + if set to True return the predicted offsets of AIN, denoted as x_{offsets} + + Returns: + Tensor: rectified image [batch_size x I_channel_num x I_height x I_width], the same as the input size + """ + + if self.spt: + feat = self.spt_convnet(x) + fc1 = self.stucture_fc1(feat) + sp_weight_fusion = self.stucture_fc2(fc1) + sp_weight_fusion = sp_weight_fusion.reshape([x.shape[0], self.out_weight, 1]) + if self.offsets: # SPIN w. AIN + lambda_color = sp_weight_fusion[:, self.spt_length, 0] + lambda_color = self.sigmoid(lambda_color).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) + sp_weight = sp_weight_fusion[:, :self.spt_length, :] + offsets = self.pool(self.offset_fc2(self.offset_fc1(feat))) + + assert offsets.shape[2] == 2 # 2 + assert offsets.shape[3] == 6 # 16 + offsets = self.sigmoid(offsets) # v12 + + if return_weight: + return offsets + offsets = nn.functional.upsample(offsets, size=(x.shape[2], x.shape[3]), mode='bilinear') + + if self.stn: + batch_C_prime = sp_weight_fusion[:, (self.spt_length + 1):, :].reshape([x.shape[0], self.F, 2]) + build_P_prime = self.GridGenerator(batch_C_prime, self.I_r_size) + build_P_prime_reshape = build_P_prime.reshape([build_P_prime.shape[0], + self.I_r_size[0], + self.I_r_size[1], + 2]) + + else: # SPIN w.o. AIN + sp_weight = sp_weight_fusion[:, :self.spt_length, :] + lambda_color, offsets = None, None + + if self.stn: + batch_C_prime = sp_weight_fusion[:, self.spt_length:, :].reshape([x.shape[0], self.F, 2]) + build_P_prime = self.GridGenerator(batch_C_prime, self.I_r_size) + build_P_prime_reshape = build_P_prime.reshape([build_P_prime.shape[0], + self.I_r_size[0], + self.I_r_size[1], + 2]) + + x = self.sp_net(x, sp_weight, offsets, lambda_color) + if self.stn: + x = F.grid_sample(x=x, grid=build_P_prime_reshape, padding_mode='border') + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/stn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/stn.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2bdda050f217d8253740001901fbff4065782a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/stn.py @@ -0,0 +1,135 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/stn_head.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np + +from .tps_spatial_transformer import TPSSpatialTransformer + + +def conv3x3_block(in_channels, out_channels, stride=1): + n = 3 * 3 * out_channels + w = math.sqrt(2. / n) + conv_layer = nn.Conv2D( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + weight_attr=nn.initializer.Normal( + mean=0.0, std=w), + bias_attr=nn.initializer.Constant(0)) + block = nn.Sequential(conv_layer, nn.BatchNorm2D(out_channels), nn.ReLU()) + return block + + +class STN(nn.Layer): + def __init__(self, in_channels, num_ctrlpoints, activation='none'): + super(STN, self).__init__() + self.in_channels = in_channels + self.num_ctrlpoints = num_ctrlpoints + self.activation = activation + self.stn_convnet = nn.Sequential( + conv3x3_block(in_channels, 32), #32x64 + nn.MaxPool2D( + kernel_size=2, stride=2), + conv3x3_block(32, 64), #16x32 + nn.MaxPool2D( + kernel_size=2, stride=2), + conv3x3_block(64, 128), # 8*16 + nn.MaxPool2D( + kernel_size=2, stride=2), + conv3x3_block(128, 256), # 4*8 + nn.MaxPool2D( + kernel_size=2, stride=2), + conv3x3_block(256, 256), # 2*4, + nn.MaxPool2D( + kernel_size=2, stride=2), + conv3x3_block(256, 256)) # 1*2 + self.stn_fc1 = nn.Sequential( + nn.Linear( + 2 * 256, + 512, + weight_attr=nn.initializer.Normal(0, 0.001), + bias_attr=nn.initializer.Constant(0)), + nn.BatchNorm1D(512), + nn.ReLU()) + fc2_bias = self.init_stn() + self.stn_fc2 = nn.Linear( + 512, + num_ctrlpoints * 2, + weight_attr=nn.initializer.Constant(0.0), + bias_attr=nn.initializer.Assign(fc2_bias)) + + def init_stn(self): + margin = 0.01 + sampling_num_per_side = int(self.num_ctrlpoints / 2) + ctrl_pts_x = np.linspace(margin, 1. - margin, sampling_num_per_side) + ctrl_pts_y_top = np.ones(sampling_num_per_side) * margin + ctrl_pts_y_bottom = np.ones(sampling_num_per_side) * (1 - margin) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + ctrl_points = np.concatenate( + [ctrl_pts_top, ctrl_pts_bottom], axis=0).astype(np.float32) + if self.activation == 'none': + pass + elif self.activation == 'sigmoid': + ctrl_points = -np.log(1. / ctrl_points - 1.) + ctrl_points = paddle.to_tensor(ctrl_points) + fc2_bias = paddle.reshape( + ctrl_points, shape=[ctrl_points.shape[0] * ctrl_points.shape[1]]) + return fc2_bias + + def forward(self, x): + x = self.stn_convnet(x) + batch_size, _, h, w = x.shape + x = paddle.reshape(x, shape=(batch_size, -1)) + img_feat = self.stn_fc1(x) + x = self.stn_fc2(0.1 * img_feat) + if self.activation == 'sigmoid': + x = F.sigmoid(x) + x = paddle.reshape(x, shape=[-1, self.num_ctrlpoints, 2]) + return img_feat, x + + +class STN_ON(nn.Layer): + def __init__(self, in_channels, tps_inputsize, tps_outputsize, + num_control_points, tps_margins, stn_activation): + super(STN_ON, self).__init__() + self.tps = TPSSpatialTransformer( + output_image_size=tuple(tps_outputsize), + num_control_points=num_control_points, + margins=tuple(tps_margins)) + self.stn_head = STN(in_channels=in_channels, + num_ctrlpoints=num_control_points, + activation=stn_activation) + self.tps_inputsize = tps_inputsize + self.out_channels = in_channels + + def forward(self, image): + stn_input = paddle.nn.functional.interpolate( + image, self.tps_inputsize, mode="bilinear", align_corners=True) + stn_img_feat, ctrl_points = self.stn_head(stn_input) + x, _ = self.tps(image, ctrl_points) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps.py new file mode 100644 index 0000000000000000000000000000000000000000..9bdab0f85112b90d8da959dce4e258188a812052 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps.py @@ -0,0 +1,308 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/clovaai/deep-text-recognition-benchmark/blob/master/modules/transformation.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np + + +class ConvBNLayer(nn.Layer): + def __init__(self, + in_channels, + out_channels, + kernel_size, + stride=1, + groups=1, + act=None, + name=None): + super(ConvBNLayer, self).__init__() + self.conv = nn.Conv2D( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=(kernel_size - 1) // 2, + groups=groups, + weight_attr=ParamAttr(name=name + "_weights"), + bias_attr=False) + bn_name = "bn_" + name + self.bn = nn.BatchNorm( + out_channels, + act=act, + param_attr=ParamAttr(name=bn_name + '_scale'), + bias_attr=ParamAttr(bn_name + '_offset'), + moving_mean_name=bn_name + '_mean', + moving_variance_name=bn_name + '_variance') + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + return x + + +class LocalizationNetwork(nn.Layer): + def __init__(self, in_channels, num_fiducial, loc_lr, model_name): + super(LocalizationNetwork, self).__init__() + self.F = num_fiducial + F = num_fiducial + if model_name == "large": + num_filters_list = [64, 128, 256, 512] + fc_dim = 256 + else: + num_filters_list = [16, 32, 64, 128] + fc_dim = 64 + + self.block_list = [] + for fno in range(0, len(num_filters_list)): + num_filters = num_filters_list[fno] + name = "loc_conv%d" % fno + conv = self.add_sublayer( + name, + ConvBNLayer( + in_channels=in_channels, + out_channels=num_filters, + kernel_size=3, + act='relu', + name=name)) + self.block_list.append(conv) + if fno == len(num_filters_list) - 1: + pool = nn.AdaptiveAvgPool2D(1) + else: + pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0) + in_channels = num_filters + self.block_list.append(pool) + name = "loc_fc1" + stdv = 1.0 / math.sqrt(num_filters_list[-1] * 1.0) + self.fc1 = nn.Linear( + in_channels, + fc_dim, + weight_attr=ParamAttr( + learning_rate=loc_lr, + name=name + "_w", + initializer=nn.initializer.Uniform(-stdv, stdv)), + bias_attr=ParamAttr(name=name + '.b_0'), + name=name) + + # Init fc2 in LocalizationNetwork + initial_bias = self.get_initial_fiducials() + initial_bias = initial_bias.reshape(-1) + name = "loc_fc2" + param_attr = ParamAttr( + learning_rate=loc_lr, + initializer=nn.initializer.Assign(np.zeros([fc_dim, F * 2])), + name=name + "_w") + bias_attr = ParamAttr( + learning_rate=loc_lr, + initializer=nn.initializer.Assign(initial_bias), + name=name + "_b") + self.fc2 = nn.Linear( + fc_dim, + F * 2, + weight_attr=param_attr, + bias_attr=bias_attr, + name=name) + self.out_channels = F * 2 + + def forward(self, x): + """ + Estimating parameters of geometric transformation + Args: + image: input + Return: + batch_C_prime: the matrix of the geometric transformation + """ + B = x.shape[0] + i = 0 + for block in self.block_list: + x = block(x) + x = x.squeeze(axis=2).squeeze(axis=2) + x = self.fc1(x) + + x = F.relu(x) + x = self.fc2(x) + x = x.reshape(shape=[-1, self.F, 2]) + return x + + def get_initial_fiducials(self): + """ see RARE paper Fig. 6 (a) """ + F = self.F + ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2)) + ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2)) + ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2)) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0) + return initial_bias + + +class GridGenerator(nn.Layer): + def __init__(self, in_channels, num_fiducial): + super(GridGenerator, self).__init__() + self.eps = 1e-6 + self.F = num_fiducial + + name = "ex_fc" + initializer = nn.initializer.Constant(value=0.0) + param_attr = ParamAttr( + learning_rate=0.0, initializer=initializer, name=name + "_w") + bias_attr = ParamAttr( + learning_rate=0.0, initializer=initializer, name=name + "_b") + self.fc = nn.Linear( + in_channels, + 6, + weight_attr=param_attr, + bias_attr=bias_attr, + name=name) + + def forward(self, batch_C_prime, I_r_size): + """ + Generate the grid for the grid_sampler. + Args: + batch_C_prime: the matrix of the geometric transformation + I_r_size: the shape of the input image + Return: + batch_P_prime: the grid for the grid_sampler + """ + C = self.build_C_paddle() + P = self.build_P_paddle(I_r_size) + + inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).astype('float32') + P_hat_tensor = self.build_P_hat_paddle( + C, paddle.to_tensor(P)).astype('float32') + + inv_delta_C_tensor.stop_gradient = True + P_hat_tensor.stop_gradient = True + + batch_C_ex_part_tensor = self.get_expand_tensor(batch_C_prime) + + batch_C_ex_part_tensor.stop_gradient = True + + batch_C_prime_with_zeros = paddle.concat( + [batch_C_prime, batch_C_ex_part_tensor], axis=1) + batch_T = paddle.matmul(inv_delta_C_tensor, batch_C_prime_with_zeros) + batch_P_prime = paddle.matmul(P_hat_tensor, batch_T) + return batch_P_prime + + def build_C_paddle(self): + """ Return coordinates of fiducial points in I_r; C """ + F = self.F + ctrl_pts_x = paddle.linspace(-1.0, 1.0, int(F / 2), dtype='float64') + ctrl_pts_y_top = -1 * paddle.ones([int(F / 2)], dtype='float64') + ctrl_pts_y_bottom = paddle.ones([int(F / 2)], dtype='float64') + ctrl_pts_top = paddle.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = paddle.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + C = paddle.concat([ctrl_pts_top, ctrl_pts_bottom], axis=0) + return C # F x 2 + + def build_P_paddle(self, I_r_size): + I_r_height, I_r_width = I_r_size + I_r_grid_x = (paddle.arange( + -I_r_width, I_r_width, 2, dtype='float64') + 1.0 + ) / paddle.to_tensor(np.array([I_r_width])) + + I_r_grid_y = (paddle.arange( + -I_r_height, I_r_height, 2, dtype='float64') + 1.0 + ) / paddle.to_tensor(np.array([I_r_height])) + + # P: self.I_r_width x self.I_r_height x 2 + P = paddle.stack(paddle.meshgrid(I_r_grid_x, I_r_grid_y), axis=2) + P = paddle.transpose(P, perm=[1, 0, 2]) + # n (= self.I_r_width x self.I_r_height) x 2 + return P.reshape([-1, 2]) + + def build_inv_delta_C_paddle(self, C): + """ Return inv_delta_C which is needed to calculate T """ + F = self.F + hat_eye = paddle.eye(F, dtype='float64') # F x F + hat_C = paddle.norm( + C.reshape([1, F, 2]) - C.reshape([F, 1, 2]), axis=2) + hat_eye + hat_C = (hat_C**2) * paddle.log(hat_C) + delta_C = paddle.concat( # F+3 x F+3 + [ + paddle.concat( + [paddle.ones( + (F, 1), dtype='float64'), C, hat_C], axis=1), # F x F+3 + paddle.concat( + [ + paddle.zeros( + (2, 3), dtype='float64'), paddle.transpose( + C, perm=[1, 0]) + ], + axis=1), # 2 x F+3 + paddle.concat( + [ + paddle.zeros( + (1, 3), dtype='float64'), paddle.ones( + (1, F), dtype='float64') + ], + axis=1) # 1 x F+3 + ], + axis=0) + inv_delta_C = paddle.inverse(delta_C) + return inv_delta_C # F+3 x F+3 + + def build_P_hat_paddle(self, C, P): + F = self.F + eps = self.eps + n = P.shape[0] # n (= self.I_r_width x self.I_r_height) + # P_tile: n x 2 -> n x 1 x 2 -> n x F x 2 + P_tile = paddle.tile(paddle.unsqueeze(P, axis=1), (1, F, 1)) + C_tile = paddle.unsqueeze(C, axis=0) # 1 x F x 2 + P_diff = P_tile - C_tile # n x F x 2 + # rbf_norm: n x F + rbf_norm = paddle.norm(P_diff, p=2, axis=2, keepdim=False) + + # rbf: n x F + rbf = paddle.multiply( + paddle.square(rbf_norm), paddle.log(rbf_norm + eps)) + P_hat = paddle.concat( + [paddle.ones( + (n, 1), dtype='float64'), P, rbf], axis=1) + return P_hat # n x F+3 + + def get_expand_tensor(self, batch_C_prime): + B, H, C = batch_C_prime.shape + batch_C_prime = batch_C_prime.reshape([B, H * C]) + batch_C_ex_part_tensor = self.fc(batch_C_prime) + batch_C_ex_part_tensor = batch_C_ex_part_tensor.reshape([-1, 3, 2]) + return batch_C_ex_part_tensor + + +class TPS(nn.Layer): + def __init__(self, in_channels, num_fiducial, loc_lr, model_name): + super(TPS, self).__init__() + self.loc_net = LocalizationNetwork(in_channels, num_fiducial, loc_lr, + model_name) + self.grid_generator = GridGenerator(self.loc_net.out_channels, + num_fiducial) + self.out_channels = in_channels + + def forward(self, image): + image.stop_gradient = False + batch_C_prime = self.loc_net(image) + batch_P_prime = self.grid_generator(batch_C_prime, image.shape[2:]) + batch_P_prime = batch_P_prime.reshape( + [-1, image.shape[2], image.shape[3], 2]) + batch_I_r = F.grid_sample(x=image, grid=batch_P_prime) + return batch_I_r diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps_spatial_transformer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps_spatial_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ec2c848f192d766722f824962a7f8d0fed41f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tps_spatial_transformer.py @@ -0,0 +1,156 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/tps_spatial_transformer.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import paddle +from paddle import nn, ParamAttr +from paddle.nn import functional as F +import numpy as np +import itertools + + +def grid_sample(input, grid, canvas=None): + input.stop_gradient = False + output = F.grid_sample(input, grid) + if canvas is None: + return output + else: + input_mask = paddle.ones(shape=input.shape) + output_mask = F.grid_sample(input_mask, grid) + padded_output = output * output_mask + canvas * (1 - output_mask) + return padded_output + + +# phi(x1, x2) = r^2 * log(r), where r = ||x1 - x2||_2 +def compute_partial_repr(input_points, control_points): + N = input_points.shape[0] + M = control_points.shape[0] + pairwise_diff = paddle.reshape( + input_points, shape=[N, 1, 2]) - paddle.reshape( + control_points, shape=[1, M, 2]) + # original implementation, very slow + # pairwise_dist = torch.sum(pairwise_diff ** 2, dim = 2) # square of distance + pairwise_diff_square = pairwise_diff * pairwise_diff + pairwise_dist = pairwise_diff_square[:, :, 0] + pairwise_diff_square[:, :, + 1] + repr_matrix = 0.5 * pairwise_dist * paddle.log(pairwise_dist) + # fix numerical error for 0 * log(0), substitute all nan with 0 + mask = np.array(repr_matrix != repr_matrix) + repr_matrix[mask] = 0 + return repr_matrix + + +# output_ctrl_pts are specified, according to our task. +def build_output_control_points(num_control_points, margins): + margin_x, margin_y = margins + num_ctrl_pts_per_side = num_control_points // 2 + ctrl_pts_x = np.linspace(margin_x, 1.0 - margin_x, num_ctrl_pts_per_side) + ctrl_pts_y_top = np.ones(num_ctrl_pts_per_side) * margin_y + ctrl_pts_y_bottom = np.ones(num_ctrl_pts_per_side) * (1.0 - margin_y) + ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1) + ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1) + output_ctrl_pts_arr = np.concatenate( + [ctrl_pts_top, ctrl_pts_bottom], axis=0) + output_ctrl_pts = paddle.to_tensor(output_ctrl_pts_arr) + return output_ctrl_pts + + +class TPSSpatialTransformer(nn.Layer): + def __init__(self, + output_image_size=None, + num_control_points=None, + margins=None): + super(TPSSpatialTransformer, self).__init__() + self.output_image_size = output_image_size + self.num_control_points = num_control_points + self.margins = margins + + self.target_height, self.target_width = output_image_size + target_control_points = build_output_control_points(num_control_points, + margins) + N = num_control_points + + # create padded kernel matrix + forward_kernel = paddle.zeros(shape=[N + 3, N + 3]) + target_control_partial_repr = compute_partial_repr( + target_control_points, target_control_points) + target_control_partial_repr = paddle.cast(target_control_partial_repr, + forward_kernel.dtype) + forward_kernel[:N, :N] = target_control_partial_repr + forward_kernel[:N, -3] = 1 + forward_kernel[-3, :N] = 1 + target_control_points = paddle.cast(target_control_points, + forward_kernel.dtype) + forward_kernel[:N, -2:] = target_control_points + forward_kernel[-2:, :N] = paddle.transpose( + target_control_points, perm=[1, 0]) + # compute inverse matrix + inverse_kernel = paddle.inverse(forward_kernel) + + # create target cordinate matrix + HW = self.target_height * self.target_width + target_coordinate = list( + itertools.product( + range(self.target_height), range(self.target_width))) + target_coordinate = paddle.to_tensor(target_coordinate) # HW x 2 + Y, X = paddle.split( + target_coordinate, target_coordinate.shape[1], axis=1) + Y = Y / (self.target_height - 1) + X = X / (self.target_width - 1) + target_coordinate = paddle.concat( + [X, Y], axis=1) # convert from (y, x) to (x, y) + target_coordinate_partial_repr = compute_partial_repr( + target_coordinate, target_control_points) + target_coordinate_repr = paddle.concat( + [ + target_coordinate_partial_repr, paddle.ones(shape=[HW, 1]), + target_coordinate + ], + axis=1) + + # register precomputed matrices + self.inverse_kernel = inverse_kernel + self.padding_matrix = paddle.zeros(shape=[3, 2]) + self.target_coordinate_repr = target_coordinate_repr + self.target_control_points = target_control_points + + def forward(self, input, source_control_points): + assert source_control_points.ndimension() == 3 + assert source_control_points.shape[1] == self.num_control_points + assert source_control_points.shape[2] == 2 + batch_size = paddle.shape(source_control_points)[0] + + padding_matrix = paddle.expand( + self.padding_matrix, shape=[batch_size, 3, 2]) + Y = paddle.concat([source_control_points, padding_matrix], 1) + mapping_matrix = paddle.matmul(self.inverse_kernel, Y) + source_coordinate = paddle.matmul(self.target_coordinate_repr, + mapping_matrix) + + grid = paddle.reshape( + source_coordinate, + shape=[-1, self.target_height, self.target_width, 2]) + grid = paddle.clip(grid, 0, + 1) # the source_control_points may be out of [0, 1]. + # the input to grid_sample is normalized [-1, 1], but what we get is [0, 1] + grid = 2.0 * grid - 1.0 + output_maps = grid_sample(input, grid, canvas=None) + return output_maps, source_coordinate \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tsrn.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tsrn.py new file mode 100644 index 0000000000000000000000000000000000000000..31aa90ea4b5d5e8f071487899b72219f3e5b36f5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/modeling/transforms/tsrn.py @@ -0,0 +1,219 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/FudanVI/FudanOCR/blob/main/text-gestalt/model/tsrn.py +""" + +import math +import paddle +import paddle.nn.functional as F +from paddle import nn +from collections import OrderedDict +import sys +import numpy as np +import warnings +import math, copy +import cv2 + +warnings.filterwarnings("ignore") + +from .tps_spatial_transformer import TPSSpatialTransformer +from .stn import STN as STN_model +from ppocr.modeling.heads.sr_rensnet_transformer import Transformer + + +class TSRN(nn.Layer): + def __init__(self, + in_channels, + scale_factor=2, + width=128, + height=32, + STN=False, + srb_nums=5, + mask=False, + hidden_units=32, + infer_mode=False, + **kwargs): + super(TSRN, self).__init__() + in_planes = 3 + if mask: + in_planes = 4 + assert math.log(scale_factor, 2) % 1 == 0 + upsample_block_num = int(math.log(scale_factor, 2)) + self.block1 = nn.Sequential( + nn.Conv2D( + in_planes, 2 * hidden_units, kernel_size=9, padding=4), + nn.PReLU()) + self.srb_nums = srb_nums + for i in range(srb_nums): + setattr(self, 'block%d' % (i + 2), + RecurrentResidualBlock(2 * hidden_units)) + + setattr( + self, + 'block%d' % (srb_nums + 2), + nn.Sequential( + nn.Conv2D( + 2 * hidden_units, + 2 * hidden_units, + kernel_size=3, + padding=1), + nn.BatchNorm2D(2 * hidden_units))) + + block_ = [ + UpsampleBLock(2 * hidden_units, 2) + for _ in range(upsample_block_num) + ] + block_.append( + nn.Conv2D( + 2 * hidden_units, in_planes, kernel_size=9, padding=4)) + setattr(self, 'block%d' % (srb_nums + 3), nn.Sequential(*block_)) + self.tps_inputsize = [height // scale_factor, width // scale_factor] + tps_outputsize = [height // scale_factor, width // scale_factor] + num_control_points = 20 + tps_margins = [0.05, 0.05] + self.stn = STN + if self.stn: + self.tps = TPSSpatialTransformer( + output_image_size=tuple(tps_outputsize), + num_control_points=num_control_points, + margins=tuple(tps_margins)) + + self.stn_head = STN_model( + in_channels=in_planes, + num_ctrlpoints=num_control_points, + activation='none') + self.out_channels = in_channels + + self.r34_transformer = Transformer() + for param in self.r34_transformer.parameters(): + param.trainable = False + self.infer_mode = infer_mode + + def forward(self, x): + output = {} + if self.infer_mode: + output["lr_img"] = x + y = x + else: + output["lr_img"] = x[0] + output["hr_img"] = x[1] + y = x[0] + if self.stn and self.training: + _, ctrl_points_x = self.stn_head(y) + y, _ = self.tps(y, ctrl_points_x) + block = {'1': self.block1(y)} + for i in range(self.srb_nums + 1): + block[str(i + 2)] = getattr(self, + 'block%d' % (i + 2))(block[str(i + 1)]) + + block[str(self.srb_nums + 3)] = getattr(self, 'block%d' % (self.srb_nums + 3)) \ + ((block['1'] + block[str(self.srb_nums + 2)])) + + sr_img = paddle.tanh(block[str(self.srb_nums + 3)]) + + output["sr_img"] = sr_img + + if self.training: + hr_img = x[1] + length = x[2] + input_tensor = x[3] + + # add transformer + sr_pred, word_attention_map_pred, _ = self.r34_transformer( + sr_img, length, input_tensor) + + hr_pred, word_attention_map_gt, _ = self.r34_transformer( + hr_img, length, input_tensor) + + output["hr_img"] = hr_img + output["hr_pred"] = hr_pred + output["word_attention_map_gt"] = word_attention_map_gt + output["sr_pred"] = sr_pred + output["word_attention_map_pred"] = word_attention_map_pred + + return output + + +class RecurrentResidualBlock(nn.Layer): + def __init__(self, channels): + super(RecurrentResidualBlock, self).__init__() + self.conv1 = nn.Conv2D(channels, channels, kernel_size=3, padding=1) + self.bn1 = nn.BatchNorm2D(channels) + self.gru1 = GruBlock(channels, channels) + self.prelu = mish() + self.conv2 = nn.Conv2D(channels, channels, kernel_size=3, padding=1) + self.bn2 = nn.BatchNorm2D(channels) + self.gru2 = GruBlock(channels, channels) + + def forward(self, x): + residual = self.conv1(x) + residual = self.bn1(residual) + residual = self.prelu(residual) + residual = self.conv2(residual) + residual = self.bn2(residual) + residual = self.gru1(residual.transpose([0, 1, 3, 2])).transpose( + [0, 1, 3, 2]) + + return self.gru2(x + residual) + + +class UpsampleBLock(nn.Layer): + def __init__(self, in_channels, up_scale): + super(UpsampleBLock, self).__init__() + self.conv = nn.Conv2D( + in_channels, in_channels * up_scale**2, kernel_size=3, padding=1) + + self.pixel_shuffle = nn.PixelShuffle(up_scale) + self.prelu = mish() + + def forward(self, x): + x = self.conv(x) + x = self.pixel_shuffle(x) + x = self.prelu(x) + return x + + +class mish(nn.Layer): + def __init__(self, ): + super(mish, self).__init__() + self.activated = True + + def forward(self, x): + if self.activated: + x = x * (paddle.tanh(F.softplus(x))) + return x + + +class GruBlock(nn.Layer): + def __init__(self, in_channels, out_channels): + super(GruBlock, self).__init__() + assert out_channels % 2 == 0 + self.conv1 = nn.Conv2D( + in_channels, out_channels, kernel_size=1, padding=0) + self.gru = nn.GRU(out_channels, + out_channels // 2, + direction='bidirectional') + + def forward(self, x): + # x: b, c, w, h + x = self.conv1(x) + x = x.transpose([0, 2, 3, 1]) # b, w, h, c + batch_size, w, h, c = x.shape + x = x.reshape([-1, h, c]) # b*w, h, c + x, _ = self.gru(x) + x = x.reshape([-1, w, h, c]) + x = x.transpose([0, 3, 1, 2]) + return x diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6bd2ebb4a81427245dc10e446cd2da101d53bd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/__init__.py @@ -0,0 +1,62 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals +import copy +import paddle + +__all__ = ['build_optimizer'] + + +def build_lr_scheduler(lr_config, epochs, step_each_epoch): + from . import learning_rate + lr_config.update({'epochs': epochs, 'step_each_epoch': step_each_epoch}) + lr_name = lr_config.pop('name', 'Const') + lr = getattr(learning_rate, lr_name)(**lr_config)() + return lr + + +def build_optimizer(config, epochs, step_each_epoch, model): + from . import regularizer, optimizer + config = copy.deepcopy(config) + # step1 build lr + lr = build_lr_scheduler(config.pop('lr'), epochs, step_each_epoch) + + # step2 build regularization + if 'regularizer' in config and config['regularizer'] is not None: + reg_config = config.pop('regularizer') + reg_name = reg_config.pop('name') + if not hasattr(regularizer, reg_name): + reg_name += 'Decay' + reg = getattr(regularizer, reg_name)(**reg_config)() + elif 'weight_decay' in config: + reg = config.pop('weight_decay') + else: + reg = None + + # step3 build optimizer + optim_name = config.pop('name') + if 'clip_norm' in config: + clip_norm = config.pop('clip_norm') + grad_clip = paddle.nn.ClipGradByNorm(clip_norm=clip_norm) + else: + grad_clip = None + optim = getattr(optimizer, optim_name)(learning_rate=lr, + weight_decay=reg, + grad_clip=grad_clip, + **config) + return optim(model), lr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/learning_rate.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/learning_rate.py new file mode 100644 index 0000000000000000000000000000000000000000..7d45109b4857871f52764c64d6d32e5322fc7c57 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/learning_rate.py @@ -0,0 +1,388 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from paddle.optimizer import lr +from .lr_scheduler import CyclicalCosineDecay, OneCycleDecay + + +class Linear(object): + """ + Linear learning rate decay + Args: + lr (float): The initial learning rate. It is a python float number. + epochs(int): The decay step size. It determines the decay cycle. + end_lr(float, optional): The minimum final learning rate. Default: 0.0001. + power(float, optional): Power of polynomial. Default: 1.0. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + epochs, + step_each_epoch, + end_lr=0.0, + power=1.0, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(Linear, self).__init__() + self.learning_rate = learning_rate + self.epochs = epochs * step_each_epoch + self.end_lr = end_lr + self.power = power + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = lr.PolynomialDecay( + learning_rate=self.learning_rate, + decay_steps=self.epochs, + end_lr=self.end_lr, + power=self.power, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate + + +class Cosine(object): + """ + Cosine learning rate decay + lr = 0.05 * (math.cos(epoch * (math.pi / epochs)) + 1) + Args: + lr(float): initial learning rate + step_each_epoch(int): steps each epoch + epochs(int): total training epochs + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + step_each_epoch, + epochs, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(Cosine, self).__init__() + self.learning_rate = learning_rate + self.T_max = step_each_epoch * epochs + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = lr.CosineAnnealingDecay( + learning_rate=self.learning_rate, + T_max=self.T_max, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate + + +class Step(object): + """ + Piecewise learning rate decay + Args: + step_each_epoch(int): steps each epoch + learning_rate (float): The initial learning rate. It is a python float number. + step_size (int): the interval to update. + gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be less than 1.0. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + step_size, + step_each_epoch, + gamma, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(Step, self).__init__() + self.step_size = step_each_epoch * step_size + self.learning_rate = learning_rate + self.gamma = gamma + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = lr.StepDecay( + learning_rate=self.learning_rate, + step_size=self.step_size, + gamma=self.gamma, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate + + +class Piecewise(object): + """ + Piecewise learning rate decay + Args: + boundaries(list): A list of steps numbers. The type of element in the list is python int. + values(list): A list of learning rate values that will be picked during different epoch boundaries. + The type of element in the list is python float. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + step_each_epoch, + decay_epochs, + values, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(Piecewise, self).__init__() + self.boundaries = [step_each_epoch * e for e in decay_epochs] + self.values = values + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = lr.PiecewiseDecay( + boundaries=self.boundaries, + values=self.values, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.values[0], + last_epoch=self.last_epoch) + return learning_rate + + +class CyclicalCosine(object): + """ + Cyclical cosine learning rate decay + Args: + learning_rate(float): initial learning rate + step_each_epoch(int): steps each epoch + epochs(int): total training epochs + cycle(int): period of the cosine learning rate + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + step_each_epoch, + epochs, + cycle, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(CyclicalCosine, self).__init__() + self.learning_rate = learning_rate + self.T_max = step_each_epoch * epochs + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + self.cycle = round(cycle * step_each_epoch) + + def __call__(self): + learning_rate = CyclicalCosineDecay( + learning_rate=self.learning_rate, + T_max=self.T_max, + cycle=self.cycle, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate + + +class OneCycle(object): + """ + One Cycle learning rate decay + Args: + max_lr(float): Upper learning rate boundaries + epochs(int): total training epochs + step_each_epoch(int): steps each epoch + anneal_strategy(str): {‘cos’, ‘linear’} Specifies the annealing strategy: “cos” for cosine annealing, “linear” for linear annealing. + Default: ‘cos’ + three_phase(bool): If True, use a third phase of the schedule to annihilate the learning rate according to ‘final_div_factor’ + instead of modifying the second phase (the first two phases will be symmetrical about the step indicated by ‘pct_start’). + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + max_lr, + epochs, + step_each_epoch, + anneal_strategy='cos', + three_phase=False, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(OneCycle, self).__init__() + self.max_lr = max_lr + self.epochs = epochs + self.steps_per_epoch = step_each_epoch + self.anneal_strategy = anneal_strategy + self.three_phase = three_phase + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = OneCycleDecay( + max_lr=self.max_lr, + epochs=self.epochs, + steps_per_epoch=self.steps_per_epoch, + anneal_strategy=self.anneal_strategy, + three_phase=self.three_phase, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.max_lr, + last_epoch=self.last_epoch) + return learning_rate + + +class Const(object): + """ + Const learning rate decay + Args: + learning_rate(float): initial learning rate + step_each_epoch(int): steps each epoch + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + step_each_epoch, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(Const, self).__init__() + self.learning_rate = learning_rate + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = self.learning_rate + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate + + +class DecayLearningRate(object): + """ + DecayLearningRate learning rate decay + new_lr = (lr - end_lr) * (1 - epoch/decay_steps)**power + end_lr + Args: + learning_rate(float): initial learning rate + step_each_epoch(int): steps each epoch + epochs(int): total training epochs + factor(float): Power of polynomial, should greater than 0.0 to get learning rate decay. Default: 0.9 + end_lr(float): The minimum final learning rate. Default: 0.0. + """ + + def __init__(self, + learning_rate, + step_each_epoch, + epochs, + factor=0.9, + end_lr=0, + **kwargs): + super(DecayLearningRate, self).__init__() + self.learning_rate = learning_rate + self.epochs = epochs + 1 + self.factor = factor + self.end_lr = 0 + self.decay_steps = step_each_epoch * epochs + + def __call__(self): + learning_rate = lr.PolynomialDecay( + learning_rate=self.learning_rate, + decay_steps=self.decay_steps, + power=self.factor, + end_lr=self.end_lr) + return learning_rate + + +class MultiStepDecay(object): + """ + Piecewise learning rate decay + Args: + step_each_epoch(int): steps each epoch + learning_rate (float): The initial learning rate. It is a python float number. + step_size (int): the interval to update. + gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` . + It should be less than 1.0. Default: 0.1. + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + """ + + def __init__(self, + learning_rate, + milestones, + step_each_epoch, + gamma, + warmup_epoch=0, + last_epoch=-1, + **kwargs): + super(MultiStepDecay, self).__init__() + self.milestones = [step_each_epoch * e for e in milestones] + self.learning_rate = learning_rate + self.gamma = gamma + self.last_epoch = last_epoch + self.warmup_epoch = round(warmup_epoch * step_each_epoch) + + def __call__(self): + learning_rate = lr.MultiStepDecay( + learning_rate=self.learning_rate, + milestones=self.milestones, + gamma=self.gamma, + last_epoch=self.last_epoch) + if self.warmup_epoch > 0: + learning_rate = lr.LinearWarmup( + learning_rate=learning_rate, + warmup_steps=self.warmup_epoch, + start_lr=0.0, + end_lr=self.learning_rate, + last_epoch=self.last_epoch) + return learning_rate diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/lr_scheduler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..f62f1f3b0adbd8df0e03a66faa4565f2f7df28bc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/lr_scheduler.py @@ -0,0 +1,162 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import math +from paddle.optimizer.lr import LRScheduler + + +class CyclicalCosineDecay(LRScheduler): + def __init__(self, + learning_rate, + T_max, + cycle=1, + last_epoch=-1, + eta_min=0.0, + verbose=False): + """ + Cyclical cosine learning rate decay + A learning rate which can be referred in https://arxiv.org/pdf/2012.12645.pdf + Args: + learning rate(float): learning rate + T_max(int): maximum epoch num + cycle(int): period of the cosine decay + last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate. + eta_min(float): minimum learning rate during training + verbose(bool): whether to print learning rate for each epoch + """ + super(CyclicalCosineDecay, self).__init__(learning_rate, last_epoch, + verbose) + self.cycle = cycle + self.eta_min = eta_min + + def get_lr(self): + if self.last_epoch == 0: + return self.base_lr + reletive_epoch = self.last_epoch % self.cycle + lr = self.eta_min + 0.5 * (self.base_lr - self.eta_min) * \ + (1 + math.cos(math.pi * reletive_epoch / self.cycle)) + return lr + + +class OneCycleDecay(LRScheduler): + """ + One Cycle learning rate decay + A learning rate which can be referred in https://arxiv.org/abs/1708.07120 + Code refered in https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR + """ + + def __init__(self, + max_lr, + epochs=None, + steps_per_epoch=None, + pct_start=0.3, + anneal_strategy='cos', + div_factor=25., + final_div_factor=1e4, + three_phase=False, + last_epoch=-1, + verbose=False): + + # Validate total_steps + if epochs <= 0 or not isinstance(epochs, int): + raise ValueError( + "Expected positive integer epochs, but got {}".format(epochs)) + if steps_per_epoch <= 0 or not isinstance(steps_per_epoch, int): + raise ValueError( + "Expected positive integer steps_per_epoch, but got {}".format( + steps_per_epoch)) + self.total_steps = epochs * steps_per_epoch + + self.max_lr = max_lr + self.initial_lr = self.max_lr / div_factor + self.min_lr = self.initial_lr / final_div_factor + + if three_phase: + self._schedule_phases = [ + { + 'end_step': float(pct_start * self.total_steps) - 1, + 'start_lr': self.initial_lr, + 'end_lr': self.max_lr, + }, + { + 'end_step': float(2 * pct_start * self.total_steps) - 2, + 'start_lr': self.max_lr, + 'end_lr': self.initial_lr, + }, + { + 'end_step': self.total_steps - 1, + 'start_lr': self.initial_lr, + 'end_lr': self.min_lr, + }, + ] + else: + self._schedule_phases = [ + { + 'end_step': float(pct_start * self.total_steps) - 1, + 'start_lr': self.initial_lr, + 'end_lr': self.max_lr, + }, + { + 'end_step': self.total_steps - 1, + 'start_lr': self.max_lr, + 'end_lr': self.min_lr, + }, + ] + + # Validate pct_start + if pct_start < 0 or pct_start > 1 or not isinstance(pct_start, float): + raise ValueError( + "Expected float between 0 and 1 pct_start, but got {}".format( + pct_start)) + + # Validate anneal_strategy + if anneal_strategy not in ['cos', 'linear']: + raise ValueError( + "anneal_strategy must by one of 'cos' or 'linear', instead got {}". + format(anneal_strategy)) + elif anneal_strategy == 'cos': + self.anneal_func = self._annealing_cos + elif anneal_strategy == 'linear': + self.anneal_func = self._annealing_linear + + super(OneCycleDecay, self).__init__(max_lr, last_epoch, verbose) + + def _annealing_cos(self, start, end, pct): + "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." + cos_out = math.cos(math.pi * pct) + 1 + return end + (start - end) / 2.0 * cos_out + + def _annealing_linear(self, start, end, pct): + "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." + return (end - start) * pct + start + + def get_lr(self): + computed_lr = 0.0 + step_num = self.last_epoch + + if step_num > self.total_steps: + raise ValueError( + "Tried to step {} times. The specified number of total steps is {}" + .format(step_num + 1, self.total_steps)) + start_step = 0 + for i, phase in enumerate(self._schedule_phases): + end_step = phase['end_step'] + if step_num <= end_step or i == len(self._schedule_phases) - 1: + pct = (step_num - start_step) / (end_step - start_step) + computed_lr = self.anneal_func(phase['start_lr'], + phase['end_lr'], pct) + break + start_step = phase['end_step'] + + return computed_lr diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/optimizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..144f011c79ec2303b7fbc73ac078afe3ce92c255 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/optimizer.py @@ -0,0 +1,285 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +from paddle import optimizer as optim + + +class Momentum(object): + """ + Simple Momentum optimizer with velocity state. + Args: + learning_rate (float|Variable) - The learning rate used to update parameters. + Can be a float value or a Variable with one float value as data element. + momentum (float) - Momentum factor. + regularization (WeightDecayRegularizer, optional) - The strategy of regularization. + """ + + def __init__(self, + learning_rate, + momentum, + weight_decay=None, + grad_clip=None, + **args): + super(Momentum, self).__init__() + self.learning_rate = learning_rate + self.momentum = momentum + self.weight_decay = weight_decay + self.grad_clip = grad_clip + + def __call__(self, model): + train_params = [ + param for param in model.parameters() if param.trainable is True + ] + opt = optim.Momentum( + learning_rate=self.learning_rate, + momentum=self.momentum, + weight_decay=self.weight_decay, + grad_clip=self.grad_clip, + parameters=train_params) + return opt + + +class Adam(object): + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-08, + parameter_list=None, + weight_decay=None, + grad_clip=None, + name=None, + lazy_mode=False, + **kwargs): + self.learning_rate = learning_rate + self.beta1 = beta1 + self.beta2 = beta2 + self.epsilon = epsilon + self.parameter_list = parameter_list + self.learning_rate = learning_rate + self.weight_decay = weight_decay + self.grad_clip = grad_clip + self.name = name + self.lazy_mode = lazy_mode + self.group_lr = kwargs.get('group_lr', False) + self.training_step = kwargs.get('training_step', None) + + def __call__(self, model): + if self.group_lr: + if self.training_step == 'LF_2': + import paddle + if isinstance(model, paddle.fluid.dygraph.parallel. + DataParallel): # multi gpu + mlm = model._layers.head.MLM_VRM.MLM.parameters() + pre_mlm_pp = model._layers.head.MLM_VRM.Prediction.pp_share.parameters( + ) + pre_mlm_w = model._layers.head.MLM_VRM.Prediction.w_share.parameters( + ) + else: # single gpu + mlm = model.head.MLM_VRM.MLM.parameters() + pre_mlm_pp = model.head.MLM_VRM.Prediction.pp_share.parameters( + ) + pre_mlm_w = model.head.MLM_VRM.Prediction.w_share.parameters( + ) + + total = [] + for param in mlm: + total.append(id(param)) + for param in pre_mlm_pp: + total.append(id(param)) + for param in pre_mlm_w: + total.append(id(param)) + + group_base_params = [ + param for param in model.parameters() if id(param) in total + ] + group_small_params = [ + param for param in model.parameters() + if id(param) not in total + ] + train_params = [{ + 'params': group_base_params + }, { + 'params': group_small_params, + 'learning_rate': self.learning_rate.values[0] * 0.1 + }] + + else: + print( + 'group lr currently only support VisionLAN in LF_2 training step' + ) + train_params = [ + param for param in model.parameters() + if param.trainable is True + ] + else: + train_params = [ + param for param in model.parameters() if param.trainable is True + ] + + opt = optim.Adam( + learning_rate=self.learning_rate, + beta1=self.beta1, + beta2=self.beta2, + epsilon=self.epsilon, + weight_decay=self.weight_decay, + grad_clip=self.grad_clip, + name=self.name, + lazy_mode=self.lazy_mode, + parameters=train_params) + return opt + + +class RMSProp(object): + """ + Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning rate method. + Args: + learning_rate (float|Variable) - The learning rate used to update parameters. + Can be a float value or a Variable with one float value as data element. + momentum (float) - Momentum factor. + rho (float) - rho value in equation. + epsilon (float) - avoid division by zero, default is 1e-6. + regularization (WeightDecayRegularizer, optional) - The strategy of regularization. + """ + + def __init__(self, + learning_rate, + momentum=0.0, + rho=0.95, + epsilon=1e-6, + weight_decay=None, + grad_clip=None, + **args): + super(RMSProp, self).__init__() + self.learning_rate = learning_rate + self.momentum = momentum + self.rho = rho + self.epsilon = epsilon + self.weight_decay = weight_decay + self.grad_clip = grad_clip + + def __call__(self, model): + train_params = [ + param for param in model.parameters() if param.trainable is True + ] + opt = optim.RMSProp( + learning_rate=self.learning_rate, + momentum=self.momentum, + rho=self.rho, + epsilon=self.epsilon, + weight_decay=self.weight_decay, + grad_clip=self.grad_clip, + parameters=train_params) + return opt + + +class Adadelta(object): + def __init__(self, + learning_rate=0.001, + epsilon=1e-08, + rho=0.95, + parameter_list=None, + weight_decay=None, + grad_clip=None, + name=None, + **kwargs): + self.learning_rate = learning_rate + self.epsilon = epsilon + self.rho = rho + self.parameter_list = parameter_list + self.learning_rate = learning_rate + self.weight_decay = weight_decay + self.grad_clip = grad_clip + self.name = name + + def __call__(self, model): + train_params = [ + param for param in model.parameters() if param.trainable is True + ] + opt = optim.Adadelta( + learning_rate=self.learning_rate, + epsilon=self.epsilon, + rho=self.rho, + weight_decay=self.weight_decay, + grad_clip=self.grad_clip, + name=self.name, + parameters=train_params) + return opt + + +class AdamW(object): + def __init__(self, + learning_rate=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8, + weight_decay=0.01, + multi_precision=False, + grad_clip=None, + no_weight_decay_name=None, + one_dim_param_no_weight_decay=False, + name=None, + lazy_mode=False, + **args): + super().__init__() + self.learning_rate = learning_rate + self.beta1 = beta1 + self.beta2 = beta2 + self.epsilon = epsilon + self.grad_clip = grad_clip + self.weight_decay = 0.01 if weight_decay is None else weight_decay + self.grad_clip = grad_clip + self.name = name + self.lazy_mode = lazy_mode + self.multi_precision = multi_precision + self.no_weight_decay_name_list = no_weight_decay_name.split( + ) if no_weight_decay_name else [] + self.one_dim_param_no_weight_decay = one_dim_param_no_weight_decay + + def __call__(self, model): + parameters = [ + param for param in model.parameters() if param.trainable is True + ] + + self.no_weight_decay_param_name_list = [ + p.name for n, p in model.named_parameters() + if any(nd in n for nd in self.no_weight_decay_name_list) + ] + + if self.one_dim_param_no_weight_decay: + self.no_weight_decay_param_name_list += [ + p.name for n, p in model.named_parameters() if len(p.shape) == 1 + ] + + opt = optim.AdamW( + learning_rate=self.learning_rate, + beta1=self.beta1, + beta2=self.beta2, + epsilon=self.epsilon, + parameters=parameters, + weight_decay=self.weight_decay, + multi_precision=self.multi_precision, + grad_clip=self.grad_clip, + name=self.name, + lazy_mode=self.lazy_mode, + apply_decay_param_fun=self._apply_decay_param_fun) + return opt + + def _apply_decay_param_fun(self, name): + return name not in self.no_weight_decay_param_name_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/regularizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/regularizer.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce68f7139e21f9e3e1dcc155254b7a92b0e7270 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/optimizer/regularizer.py @@ -0,0 +1,51 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import paddle + + +class L1Decay(object): + """ + L1 Weight Decay Regularization, which encourages the weights to be sparse. + Args: + factor(float): regularization coeff. Default:0.0. + """ + + def __init__(self, factor=0.0): + super(L1Decay, self).__init__() + self.coeff = factor + + def __call__(self): + reg = paddle.regularizer.L1Decay(self.coeff) + return reg + + +class L2Decay(object): + """ + L2 Weight Decay Regularization, which helps to prevent the model over-fitting. + Args: + factor(float): regularization coeff. Default:0.0. + """ + + def __init__(self, factor=0.0): + super(L2Decay, self).__init__() + self.coeff = float(factor) + + def __call__(self): + return self.coeff \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f41a005f5b90e7edf11fad80b9b7eac89257160 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/__init__.py @@ -0,0 +1,67 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import copy + +__all__ = ['build_post_process'] + +from .db_postprocess import DBPostProcess, DistillationDBPostProcess +from .east_postprocess import EASTPostProcess +from .sast_postprocess import SASTPostProcess +from .fce_postprocess import FCEPostProcess +from .rec_postprocess import CTCLabelDecode, AttnLabelDecode, SRNLabelDecode, \ + DistillationCTCLabelDecode, NRTRLabelDecode, SARLabelDecode, \ + SEEDLabelDecode, PRENLabelDecode, ViTSTRLabelDecode, ABINetLabelDecode, \ + SPINLabelDecode, VLLabelDecode +from .cls_postprocess import ClsPostProcess +from .pg_postprocess import PGPostProcess +from .vqa_token_ser_layoutlm_postprocess import VQASerTokenLayoutLMPostProcess, DistillationSerPostProcess +from .vqa_token_re_layoutlm_postprocess import VQAReTokenLayoutLMPostProcess, DistillationRePostProcess +from .table_postprocess import TableMasterLabelDecode, TableLabelDecode +from .picodet_postprocess import PicoDetPostProcess + + +def build_post_process(config, global_config=None): + support_dict = [ + 'DBPostProcess', 'EASTPostProcess', 'SASTPostProcess', 'FCEPostProcess', + 'CTCLabelDecode', 'AttnLabelDecode', 'ClsPostProcess', 'SRNLabelDecode', + 'PGPostProcess', 'DistillationCTCLabelDecode', 'TableLabelDecode', + 'DistillationDBPostProcess', 'NRTRLabelDecode', 'SARLabelDecode', + 'SEEDLabelDecode', 'VQASerTokenLayoutLMPostProcess', + 'VQAReTokenLayoutLMPostProcess', 'PRENLabelDecode', + 'DistillationSARLabelDecode', 'ViTSTRLabelDecode', 'ABINetLabelDecode', + 'TableMasterLabelDecode', 'SPINLabelDecode', + 'DistillationSerPostProcess', 'DistillationRePostProcess', + 'VLLabelDecode', 'PicoDetPostProcess' + ] + + if config['name'] == 'PSEPostProcess': + from .pse_postprocess import PSEPostProcess + support_dict.append('PSEPostProcess') + + config = copy.deepcopy(config) + module_name = config.pop('name') + if module_name == "None": + return + if global_config is not None: + config.update(global_config) + assert module_name in support_dict, Exception( + 'post process only support {}'.format(support_dict)) + module_class = eval(module_name)(**config) + return module_class diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/cls_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/cls_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..9a27ba0831358564d99a6ec698a5019eae1c25f7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/cls_postprocess.py @@ -0,0 +1,42 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import paddle + + +class ClsPostProcess(object): + """ Convert between text-label and text-index """ + + def __init__(self, label_list=None, key=None, **kwargs): + super(ClsPostProcess, self).__init__() + self.label_list = label_list + self.key = key + + def __call__(self, preds, label=None, *args, **kwargs): + if self.key is not None: + preds = preds[self.key] + + label_list = self.label_list + if label_list is None: + label_list = {idx: idx for idx in range(preds.shape[-1])} + + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + + pred_idxs = preds.argmax(axis=1) + decode_out = [(label_list[idx], preds[i, idx]) + for i, idx in enumerate(pred_idxs)] + if label is None: + return decode_out + label = [(label_list[idx], 1.0) for idx in label] + return decode_out, label diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/db_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/db_postprocess.py new file mode 100755 index 0000000000000000000000000000000000000000..d89741b4f2d259350f8921a09a3105ab4f9cf568 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/db_postprocess.py @@ -0,0 +1,277 @@ +# 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. +""" +This code is refered from: +https://github.com/WenmuZhou/DBNet.pytorch/blob/master/post_processing/seg_detector_representer.py +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import cv2 +import paddle +from shapely.geometry import Polygon +import pyclipper + +np.int = np.int32 +np.float = np.float64 +np.bool = np.bool_ + +class DBPostProcess(object): + """ + The post process for Differentiable Binarization (DB). + """ + + def __init__(self, + thresh=0.3, + box_thresh=0.7, + max_candidates=1000, + unclip_ratio=2.0, + use_dilation=False, + score_mode="fast", + use_polygon=False, + **kwargs): + self.thresh = thresh + self.box_thresh = box_thresh + self.max_candidates = max_candidates + self.unclip_ratio = unclip_ratio + self.min_size = 3 + self.score_mode = score_mode + self.use_polygon = use_polygon + assert score_mode in [ + "slow", "fast" + ], "Score mode must be in [slow, fast] but got: {}".format(score_mode) + + self.dilation_kernel = None if not use_dilation else np.array( + [[1, 1], [1, 1]]) + + def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height): + ''' + _bitmap: single map with shape (1, H, W), + whose values are binarized as {0, 1} + ''' + + bitmap = _bitmap + height, width = bitmap.shape + + boxes = [] + scores = [] + + contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), + cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + + for contour in contours[:self.max_candidates]: + epsilon = 0.002 * cv2.arcLength(contour, True) + approx = cv2.approxPolyDP(contour, epsilon, True) + points = approx.reshape((-1, 2)) + if points.shape[0] < 4: + continue + + score = self.box_score_fast(pred, points.reshape(-1, 2)) + if self.box_thresh > score: + continue + + if points.shape[0] > 2: + box = self.unclip(points, self.unclip_ratio) + if len(box) > 1: + continue + else: + continue + box = box.reshape(-1, 2) + + _, sside = self.get_mini_boxes(box.reshape((-1, 1, 2))) + if sside < self.min_size + 2: + continue + + box = np.array(box) + box[:, 0] = np.clip( + np.round(box[:, 0] / width * dest_width), 0, dest_width) + box[:, 1] = np.clip( + np.round(box[:, 1] / height * dest_height), 0, dest_height) + boxes.append(box.tolist()) + scores.append(score) + return boxes, scores + + def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height): + ''' + _bitmap: single map with shape (1, H, W), + whose values are binarized as {0, 1} + ''' + + bitmap = _bitmap + height, width = bitmap.shape + + outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, + cv2.CHAIN_APPROX_SIMPLE) + if len(outs) == 3: + img, contours, _ = outs[0], outs[1], outs[2] + elif len(outs) == 2: + contours, _ = outs[0], outs[1] + + num_contours = min(len(contours), self.max_candidates) + + boxes = [] + scores = [] + for index in range(num_contours): + contour = contours[index] + points, sside = self.get_mini_boxes(contour) + if sside < self.min_size: + continue + points = np.array(points) + if self.score_mode == "fast": + score = self.box_score_fast(pred, points.reshape(-1, 2)) + else: + score = self.box_score_slow(pred, contour) + if self.box_thresh > score: + continue + + box = self.unclip(points, self.unclip_ratio).reshape(-1, 1, 2) + box, sside = self.get_mini_boxes(box) + if sside < self.min_size + 2: + continue + box = np.array(box) + + box[:, 0] = np.clip( + np.round(box[:, 0] / width * dest_width), 0, dest_width) + box[:, 1] = np.clip( + np.round(box[:, 1] / height * dest_height), 0, dest_height) + boxes.append(box.astype(np.int16)) + scores.append(score) + return np.array(boxes, dtype=np.int16), scores + + def unclip(self, box, unclip_ratio): + poly = Polygon(box) + distance = poly.area * unclip_ratio / poly.length + offset = pyclipper.PyclipperOffset() + offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) + expanded = np.array(offset.Execute(distance)) + return expanded + + def get_mini_boxes(self, contour): + bounding_box = cv2.minAreaRect(contour) + points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0]) + + index_1, index_2, index_3, index_4 = 0, 1, 2, 3 + if points[1][1] > points[0][1]: + index_1 = 0 + index_4 = 1 + else: + index_1 = 1 + index_4 = 0 + if points[3][1] > points[2][1]: + index_2 = 2 + index_3 = 3 + else: + index_2 = 3 + index_3 = 2 + + box = [ + points[index_1], points[index_2], points[index_3], points[index_4] + ] + return box, min(bounding_box[1]) + + def box_score_fast(self, bitmap, _box): + ''' + box_score_fast: use bbox mean score as the mean score + ''' + h, w = bitmap.shape[:2] + box = _box.copy() + xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1) + xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1) + ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1) + ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1) + + mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8) + box[:, 0] = box[:, 0] - xmin + box[:, 1] = box[:, 1] - ymin + cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1) + return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0] + + def box_score_slow(self, bitmap, contour): + ''' + box_score_slow: use polyon mean score as the mean score + ''' + h, w = bitmap.shape[:2] + contour = contour.copy() + contour = np.reshape(contour, (-1, 2)) + + xmin = np.clip(np.min(contour[:, 0]), 0, w - 1) + xmax = np.clip(np.max(contour[:, 0]), 0, w - 1) + ymin = np.clip(np.min(contour[:, 1]), 0, h - 1) + ymax = np.clip(np.max(contour[:, 1]), 0, h - 1) + + mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8) + + contour[:, 0] = contour[:, 0] - xmin + contour[:, 1] = contour[:, 1] - ymin + + cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1) + return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0] + + def __call__(self, outs_dict, shape_list): + pred = outs_dict['maps'] + if isinstance(pred, paddle.Tensor): + pred = pred.numpy() + pred = pred[:, 0, :, :] + segmentation = pred > self.thresh + + boxes_batch = [] + for batch_index in range(pred.shape[0]): + src_h, src_w, ratio_h, ratio_w = shape_list[batch_index] + if self.dilation_kernel is not None: + mask = cv2.dilate( + np.array(segmentation[batch_index]).astype(np.uint8), + self.dilation_kernel) + else: + mask = segmentation[batch_index] + if self.use_polygon is True: + boxes, scores = self.polygons_from_bitmap(pred[batch_index], + mask, src_w, src_h) + else: + boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask, + src_w, src_h) + + boxes_batch.append({'points': boxes}) + return boxes_batch + + +class DistillationDBPostProcess(object): + def __init__(self, + model_name=["student"], + key=None, + thresh=0.3, + box_thresh=0.6, + max_candidates=1000, + unclip_ratio=1.5, + use_dilation=False, + score_mode="fast", + use_polygon=False, + **kwargs): + self.model_name = model_name + self.key = key + self.post_process = DBPostProcess( + thresh=thresh, + box_thresh=box_thresh, + max_candidates=max_candidates, + unclip_ratio=unclip_ratio, + use_dilation=use_dilation, + score_mode=score_mode, + use_polygon=use_polygon) + + def __call__(self, predicts, shape_list): + results = {} + for k in self.model_name: + results[k] = self.post_process(predicts[k], shape_list=shape_list) + return results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/east_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/east_postprocess.py new file mode 100755 index 0000000000000000000000000000000000000000..c194c81c6911aac0f9210109c37b76b44532e9c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/east_postprocess.py @@ -0,0 +1,143 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +from .locality_aware_nms import nms_locality +import cv2 +import paddle + +import os +import sys + + +class EASTPostProcess(object): + """ + The post process for EAST. + """ + + def __init__(self, + score_thresh=0.8, + cover_thresh=0.1, + nms_thresh=0.2, + **kwargs): + + self.score_thresh = score_thresh + self.cover_thresh = cover_thresh + self.nms_thresh = nms_thresh + + def restore_rectangle_quad(self, origin, geometry): + """ + Restore rectangle from quadrangle. + """ + # quad + origin_concat = np.concatenate( + (origin, origin, origin, origin), axis=1) # (n, 8) + pred_quads = origin_concat - geometry + pred_quads = pred_quads.reshape((-1, 4, 2)) # (n, 4, 2) + return pred_quads + + def detect(self, + score_map, + geo_map, + score_thresh=0.8, + cover_thresh=0.1, + nms_thresh=0.2): + """ + restore text boxes from score map and geo map + """ + + score_map = score_map[0] + geo_map = np.swapaxes(geo_map, 1, 0) + geo_map = np.swapaxes(geo_map, 1, 2) + # filter the score map + xy_text = np.argwhere(score_map > score_thresh) + if len(xy_text) == 0: + return [] + # sort the text boxes via the y axis + xy_text = xy_text[np.argsort(xy_text[:, 0])] + #restore quad proposals + text_box_restored = self.restore_rectangle_quad( + xy_text[:, ::-1] * 4, geo_map[xy_text[:, 0], xy_text[:, 1], :]) + boxes = np.zeros((text_box_restored.shape[0], 9), dtype=np.float32) + boxes[:, :8] = text_box_restored.reshape((-1, 8)) + boxes[:, 8] = score_map[xy_text[:, 0], xy_text[:, 1]] + + try: + import lanms + boxes = lanms.merge_quadrangle_n9(boxes, nms_thresh) + except: + print( + 'you should install lanms by pip3 install lanms-nova to speed up nms_locality' + ) + boxes = nms_locality(boxes.astype(np.float64), nms_thresh) + if boxes.shape[0] == 0: + return [] + # Here we filter some low score boxes by the average score map, + # this is different from the orginal paper. + for i, box in enumerate(boxes): + mask = np.zeros_like(score_map, dtype=np.uint8) + cv2.fillPoly(mask, box[:8].reshape( + (-1, 4, 2)).astype(np.int32) // 4, 1) + boxes[i, 8] = cv2.mean(score_map, mask)[0] + boxes = boxes[boxes[:, 8] > cover_thresh] + return boxes + + def sort_poly(self, p): + """ + Sort polygons. + """ + min_axis = np.argmin(np.sum(p, axis=1)) + p = p[[min_axis, (min_axis + 1) % 4,\ + (min_axis + 2) % 4, (min_axis + 3) % 4]] + if abs(p[0, 0] - p[1, 0]) > abs(p[0, 1] - p[1, 1]): + return p + else: + return p[[0, 3, 2, 1]] + + def __call__(self, outs_dict, shape_list): + score_list = outs_dict['f_score'] + geo_list = outs_dict['f_geo'] + if isinstance(score_list, paddle.Tensor): + score_list = score_list.numpy() + geo_list = geo_list.numpy() + img_num = len(shape_list) + dt_boxes_list = [] + for ino in range(img_num): + score = score_list[ino] + geo = geo_list[ino] + boxes = self.detect( + score_map=score, + geo_map=geo, + score_thresh=self.score_thresh, + cover_thresh=self.cover_thresh, + nms_thresh=self.nms_thresh) + boxes_norm = [] + if len(boxes) > 0: + h, w = score.shape[1:] + src_h, src_w, ratio_h, ratio_w = shape_list[ino] + boxes = boxes[:, :8].reshape((-1, 4, 2)) + boxes[:, :, 0] /= ratio_w + boxes[:, :, 1] /= ratio_h + for i_box, box in enumerate(boxes): + box = self.sort_poly(box.astype(np.int32)) + if np.linalg.norm(box[0] - box[1]) < 5 \ + or np.linalg.norm(box[3] - box[0]) < 5: + continue + boxes_norm.append(box) + dt_boxes_list.append({'points': np.array(boxes_norm)}) + return dt_boxes_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/fce_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/fce_postprocess.py new file mode 100755 index 0000000000000000000000000000000000000000..8e0716f9f2f3a7cb585fa40a2e2a27aecb606a9b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/fce_postprocess.py @@ -0,0 +1,241 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/open-mmlab/mmocr/blob/v0.3.0/mmocr/models/textdet/postprocess/wrapper.py +""" + +import cv2 +import paddle +import numpy as np +from numpy.fft import ifft +from ppocr.utils.poly_nms import poly_nms, valid_boundary + + +def fill_hole(input_mask): + h, w = input_mask.shape + canvas = np.zeros((h + 2, w + 2), np.uint8) + canvas[1:h + 1, 1:w + 1] = input_mask.copy() + + mask = np.zeros((h + 4, w + 4), np.uint8) + + cv2.floodFill(canvas, mask, (0, 0), 1) + canvas = canvas[1:h + 1, 1:w + 1].astype(np.bool) + + return ~canvas | input_mask + + +def fourier2poly(fourier_coeff, num_reconstr_points=50): + """ Inverse Fourier transform + Args: + fourier_coeff (ndarray): Fourier coefficients shaped (n, 2k+1), + with n and k being candidates number and Fourier degree + respectively. + num_reconstr_points (int): Number of reconstructed polygon points. + Returns: + Polygons (ndarray): The reconstructed polygons shaped (n, n') + """ + + a = np.zeros((len(fourier_coeff), num_reconstr_points), dtype='complex') + k = (len(fourier_coeff[0]) - 1) // 2 + + a[:, 0:k + 1] = fourier_coeff[:, k:] + a[:, -k:] = fourier_coeff[:, :k] + + poly_complex = ifft(a) * num_reconstr_points + polygon = np.zeros((len(fourier_coeff), num_reconstr_points, 2)) + polygon[:, :, 0] = poly_complex.real + polygon[:, :, 1] = poly_complex.imag + return polygon.astype('int32').reshape((len(fourier_coeff), -1)) + + +class FCEPostProcess(object): + """ + The post process for FCENet. + """ + + def __init__(self, + scales, + fourier_degree=5, + num_reconstr_points=50, + decoding_type='fcenet', + score_thr=0.3, + nms_thr=0.1, + alpha=1.0, + beta=1.0, + box_type='poly', + **kwargs): + + self.scales = scales + self.fourier_degree = fourier_degree + self.num_reconstr_points = num_reconstr_points + self.decoding_type = decoding_type + self.score_thr = score_thr + self.nms_thr = nms_thr + self.alpha = alpha + self.beta = beta + self.box_type = box_type + + def __call__(self, preds, shape_list): + score_maps = [] + for key, value in preds.items(): + if isinstance(value, paddle.Tensor): + value = value.numpy() + cls_res = value[:, :4, :, :] + reg_res = value[:, 4:, :, :] + score_maps.append([cls_res, reg_res]) + + return self.get_boundary(score_maps, shape_list) + + def resize_boundary(self, boundaries, scale_factor): + """Rescale boundaries via scale_factor. + + Args: + boundaries (list[list[float]]): The boundary list. Each boundary + with size 2k+1 with k>=4. + scale_factor(ndarray): The scale factor of size (4,). + + Returns: + boundaries (list[list[float]]): The scaled boundaries. + """ + boxes = [] + scores = [] + for b in boundaries: + sz = len(b) + valid_boundary(b, True) + scores.append(b[-1]) + b = (np.array(b[:sz - 1]) * + (np.tile(scale_factor[:2], int( + (sz - 1) / 2)).reshape(1, sz - 1))).flatten().tolist() + boxes.append(np.array(b).reshape([-1, 2])) + + return np.array(boxes, dtype=np.float32), scores + + def get_boundary(self, score_maps, shape_list): + assert len(score_maps) == len(self.scales) + boundaries = [] + for idx, score_map in enumerate(score_maps): + scale = self.scales[idx] + boundaries = boundaries + self._get_boundary_single(score_map, + scale) + + # nms + boundaries = poly_nms(boundaries, self.nms_thr) + boundaries, scores = self.resize_boundary( + boundaries, (1 / shape_list[0, 2:]).tolist()[::-1]) + + boxes_batch = [dict(points=boundaries, scores=scores)] + return boxes_batch + + def _get_boundary_single(self, score_map, scale): + assert len(score_map) == 2 + assert score_map[1].shape[1] == 4 * self.fourier_degree + 2 + + return self.fcenet_decode( + preds=score_map, + fourier_degree=self.fourier_degree, + num_reconstr_points=self.num_reconstr_points, + scale=scale, + alpha=self.alpha, + beta=self.beta, + box_type=self.box_type, + score_thr=self.score_thr, + nms_thr=self.nms_thr) + + def fcenet_decode(self, + preds, + fourier_degree, + num_reconstr_points, + scale, + alpha=1.0, + beta=2.0, + box_type='poly', + score_thr=0.3, + nms_thr=0.1): + """Decoding predictions of FCENet to instances. + + Args: + preds (list(Tensor)): The head output tensors. + fourier_degree (int): The maximum Fourier transform degree k. + num_reconstr_points (int): The points number of the polygon + reconstructed from predicted Fourier coefficients. + scale (int): The down-sample scale of the prediction. + alpha (float) : The parameter to calculate final scores. Score_{final} + = (Score_{text region} ^ alpha) + * (Score_{text center region}^ beta) + beta (float) : The parameter to calculate final score. + box_type (str): Boundary encoding type 'poly' or 'quad'. + score_thr (float) : The threshold used to filter out the final + candidates. + nms_thr (float) : The threshold of nms. + + Returns: + boundaries (list[list[float]]): The instance boundary and confidence + list. + """ + assert isinstance(preds, list) + assert len(preds) == 2 + assert box_type in ['poly', 'quad'] + + cls_pred = preds[0][0] + tr_pred = cls_pred[0:2] + tcl_pred = cls_pred[2:] + + reg_pred = preds[1][0].transpose([1, 2, 0]) + x_pred = reg_pred[:, :, :2 * fourier_degree + 1] + y_pred = reg_pred[:, :, 2 * fourier_degree + 1:] + + score_pred = (tr_pred[1]**alpha) * (tcl_pred[1]**beta) + tr_pred_mask = (score_pred) > score_thr + tr_mask = fill_hole(tr_pred_mask) + + tr_contours, _ = cv2.findContours( + tr_mask.astype(np.uint8), cv2.RETR_TREE, + cv2.CHAIN_APPROX_SIMPLE) # opencv4 + + mask = np.zeros_like(tr_mask) + boundaries = [] + for cont in tr_contours: + deal_map = mask.copy().astype(np.int8) + cv2.drawContours(deal_map, [cont], -1, 1, -1) + + score_map = score_pred * deal_map + score_mask = score_map > 0 + xy_text = np.argwhere(score_mask) + dxy = xy_text[:, 1] + xy_text[:, 0] * 1j + + x, y = x_pred[score_mask], y_pred[score_mask] + c = x + y * 1j + c[:, fourier_degree] = c[:, fourier_degree] + dxy + c *= scale + + polygons = fourier2poly(c, num_reconstr_points) + score = score_map[score_mask].reshape(-1, 1) + polygons = poly_nms(np.hstack((polygons, score)).tolist(), nms_thr) + + boundaries = boundaries + polygons + + boundaries = poly_nms(boundaries, nms_thr) + + if box_type == 'quad': + new_boundaries = [] + for boundary in boundaries: + poly = np.array(boundary[:-1]).reshape(-1, 2).astype(np.float32) + score = boundary[-1] + points = cv2.boxPoints(cv2.minAreaRect(poly)) + points = np.int0(points) + new_boundaries.append(points.reshape(-1).tolist() + [score]) + boundaries = new_boundaries + + return boundaries diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/locality_aware_nms.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/locality_aware_nms.py new file mode 100644 index 0000000000000000000000000000000000000000..d305ef681882b4a393a73190bcbd20a65d1f0c15 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/locality_aware_nms.py @@ -0,0 +1,200 @@ +""" +Locality aware nms. +This code is refered from: https://github.com/songdejia/EAST/blob/master/locality_aware_nms.py +""" + +import numpy as np +from shapely.geometry import Polygon + + +def intersection(g, p): + """ + Intersection. + """ + g = Polygon(g[:8].reshape((4, 2))) + p = Polygon(p[:8].reshape((4, 2))) + g = g.buffer(0) + p = p.buffer(0) + if not g.is_valid or not p.is_valid: + return 0 + inter = Polygon(g).intersection(Polygon(p)).area + union = g.area + p.area - inter + if union == 0: + return 0 + else: + return inter / union + + +def intersection_iog(g, p): + """ + Intersection_iog. + """ + g = Polygon(g[:8].reshape((4, 2))) + p = Polygon(p[:8].reshape((4, 2))) + if not g.is_valid or not p.is_valid: + return 0 + inter = Polygon(g).intersection(Polygon(p)).area + #union = g.area + p.area - inter + union = p.area + if union == 0: + print("p_area is very small") + return 0 + else: + return inter / union + + +def weighted_merge(g, p): + """ + Weighted merge. + """ + g[:8] = (g[8] * g[:8] + p[8] * p[:8]) / (g[8] + p[8]) + g[8] = (g[8] + p[8]) + return g + + +def standard_nms(S, thres): + """ + Standard nms. + """ + order = np.argsort(S[:, 8])[::-1] + keep = [] + while order.size > 0: + i = order[0] + keep.append(i) + ovr = np.array([intersection(S[i], S[t]) for t in order[1:]]) + + inds = np.where(ovr <= thres)[0] + order = order[inds + 1] + + return S[keep] + + +def standard_nms_inds(S, thres): + """ + Standard nms, retun inds. + """ + order = np.argsort(S[:, 8])[::-1] + keep = [] + while order.size > 0: + i = order[0] + keep.append(i) + ovr = np.array([intersection(S[i], S[t]) for t in order[1:]]) + + inds = np.where(ovr <= thres)[0] + order = order[inds + 1] + + return keep + + +def nms(S, thres): + """ + nms. + """ + order = np.argsort(S[:, 8])[::-1] + keep = [] + while order.size > 0: + i = order[0] + keep.append(i) + ovr = np.array([intersection(S[i], S[t]) for t in order[1:]]) + + inds = np.where(ovr <= thres)[0] + order = order[inds + 1] + + return keep + + +def soft_nms(boxes_in, Nt_thres=0.3, threshold=0.8, sigma=0.5, method=2): + """ + soft_nms + :para boxes_in, N x 9 (coords + score) + :para threshould, eliminate cases min score(0.001) + :para Nt_thres, iou_threshi + :para sigma, gaussian weght + :method, linear or gaussian + """ + boxes = boxes_in.copy() + N = boxes.shape[0] + if N is None or N < 1: + return np.array([]) + pos, maxpos = 0, 0 + weight = 0.0 + inds = np.arange(N) + tbox, sbox = boxes[0].copy(), boxes[0].copy() + for i in range(N): + maxscore = boxes[i, 8] + maxpos = i + tbox = boxes[i].copy() + ti = inds[i] + pos = i + 1 + #get max box + while pos < N: + if maxscore < boxes[pos, 8]: + maxscore = boxes[pos, 8] + maxpos = pos + pos = pos + 1 + #add max box as a detection + boxes[i, :] = boxes[maxpos, :] + inds[i] = inds[maxpos] + #swap + boxes[maxpos, :] = tbox + inds[maxpos] = ti + tbox = boxes[i].copy() + pos = i + 1 + #NMS iteration + while pos < N: + sbox = boxes[pos].copy() + ts_iou_val = intersection(tbox, sbox) + if ts_iou_val > 0: + if method == 1: + if ts_iou_val > Nt_thres: + weight = 1 - ts_iou_val + else: + weight = 1 + elif method == 2: + weight = np.exp(-1.0 * ts_iou_val**2 / sigma) + else: + if ts_iou_val > Nt_thres: + weight = 0 + else: + weight = 1 + boxes[pos, 8] = weight * boxes[pos, 8] + #if box score falls below thresold, discard the box by + #swaping last box update N + if boxes[pos, 8] < threshold: + boxes[pos, :] = boxes[N - 1, :] + inds[pos] = inds[N - 1] + N = N - 1 + pos = pos - 1 + pos = pos + 1 + + return boxes[:N] + + +def nms_locality(polys, thres=0.3): + """ + locality aware nms of EAST + :param polys: a N*9 numpy array. first 8 coordinates, then prob + :return: boxes after nms + """ + S = [] + p = None + for g in polys: + if p is not None and intersection(g, p) > thres: + p = weighted_merge(g, p) + else: + if p is not None: + S.append(p) + p = g + if p is not None: + S.append(p) + + if len(S) == 0: + return np.array([]) + return standard_nms(np.array(S), thres) + + +if __name__ == '__main__': + # 343,350,448,135,474,143,369,359 + print( + Polygon(np.array([[343, 350], [448, 135], [474, 143], [369, 359]])) + .area) \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pg_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pg_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1455181fddb0adb5347406bb2eb3093ee6fb30 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pg_postprocess.py @@ -0,0 +1,52 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys + +__dir__ = os.path.dirname(__file__) +sys.path.append(__dir__) +sys.path.append(os.path.join(__dir__, '..')) +from ppocr.utils.e2e_utils.pgnet_pp_utils import PGNet_PostProcess + + +class PGPostProcess(object): + """ + The post process for PGNet. + """ + + def __init__(self, character_dict_path, valid_set, score_thresh, mode, + **kwargs): + self.character_dict_path = character_dict_path + self.valid_set = valid_set + self.score_thresh = score_thresh + self.mode = mode + + # c++ la-nms is faster, but only support python 3.5 + self.is_python35 = False + if sys.version_info.major == 3 and sys.version_info.minor == 5: + self.is_python35 = True + + def __call__(self, outs_dict, shape_list): + post = PGNet_PostProcess(self.character_dict_path, self.valid_set, + self.score_thresh, outs_dict, shape_list) + if self.mode == 'fast': + data = post.pg_postprocess_fast() + else: + data = post.pg_postprocess_slow() + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/picodet_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/picodet_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0aeb4387ea4778c1c6bec910262f1c4e136084 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/picodet_postprocess.py @@ -0,0 +1,250 @@ +# Copyright (c) 2021 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. + +import numpy as np +from scipy.special import softmax + + +def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200): + """ + Args: + box_scores (N, 5): boxes in corner-form and probabilities. + iou_threshold: intersection over union threshold. + top_k: keep top_k results. If k <= 0, keep all the results. + candidate_size: only consider the candidates with the highest scores. + Returns: + picked: a list of indexes of the kept boxes + """ + scores = box_scores[:, -1] + boxes = box_scores[:, :-1] + picked = [] + indexes = np.argsort(scores) + indexes = indexes[-candidate_size:] + while len(indexes) > 0: + current = indexes[-1] + picked.append(current) + if 0 < top_k == len(picked) or len(indexes) == 1: + break + current_box = boxes[current, :] + indexes = indexes[:-1] + rest_boxes = boxes[indexes, :] + iou = iou_of( + rest_boxes, + np.expand_dims( + current_box, axis=0), ) + indexes = indexes[iou <= iou_threshold] + + return box_scores[picked, :] + + +def iou_of(boxes0, boxes1, eps=1e-5): + """Return intersection-over-union (Jaccard index) of boxes. + Args: + boxes0 (N, 4): ground truth boxes. + boxes1 (N or 1, 4): predicted boxes. + eps: a small number to avoid 0 as denominator. + Returns: + iou (N): IoU values. + """ + overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2]) + overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:]) + + overlap_area = area_of(overlap_left_top, overlap_right_bottom) + area0 = area_of(boxes0[..., :2], boxes0[..., 2:]) + area1 = area_of(boxes1[..., :2], boxes1[..., 2:]) + return overlap_area / (area0 + area1 - overlap_area + eps) + + +def area_of(left_top, right_bottom): + """Compute the areas of rectangles given two corners. + Args: + left_top (N, 2): left top corner. + right_bottom (N, 2): right bottom corner. + Returns: + area (N): return the area. + """ + hw = np.clip(right_bottom - left_top, 0.0, None) + return hw[..., 0] * hw[..., 1] + + +class PicoDetPostProcess(object): + """ + Args: + input_shape (int): network input image size + ori_shape (int): ori image shape of before padding + scale_factor (float): scale factor of ori image + enable_mkldnn (bool): whether to open MKLDNN + """ + + def __init__(self, + layout_dict_path, + strides=[8, 16, 32, 64], + score_threshold=0.4, + nms_threshold=0.5, + nms_top_k=1000, + keep_top_k=100): + self.labels = self.load_layout_dict(layout_dict_path) + self.strides = strides + self.score_threshold = score_threshold + self.nms_threshold = nms_threshold + self.nms_top_k = nms_top_k + self.keep_top_k = keep_top_k + + def load_layout_dict(self, layout_dict_path): + with open(layout_dict_path, 'r', encoding='utf-8') as fp: + labels = fp.readlines() + return [label.strip('\n') for label in labels] + + def warp_boxes(self, boxes, ori_shape): + """Apply transform to boxes + """ + width, height = ori_shape[1], ori_shape[0] + n = len(boxes) + if n: + # warp points + xy = np.ones((n * 4, 3)) + xy[:, :2] = boxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape( + n * 4, 2) # x1y1, x2y2, x1y2, x2y1 + # xy = xy @ M.T # transform + xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8) # rescale + # create new boxes + x = xy[:, [0, 2, 4, 6]] + y = xy[:, [1, 3, 5, 7]] + xy = np.concatenate( + (x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T + # clip boxes + xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width) + xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height) + return xy.astype(np.float32) + else: + return boxes + + def img_info(self, ori_img, img): + origin_shape = ori_img.shape + resize_shape = img.shape + im_scale_y = resize_shape[2] / float(origin_shape[0]) + im_scale_x = resize_shape[3] / float(origin_shape[1]) + scale_factor = np.array([im_scale_y, im_scale_x], dtype=np.float32) + img_shape = np.array(img.shape[2:], dtype=np.float32) + + input_shape = np.array(img).astype('float32').shape[2:] + ori_shape = np.array((img_shape, )).astype('float32') + scale_factor = np.array((scale_factor, )).astype('float32') + return ori_shape, input_shape, scale_factor + + def __call__(self, ori_img, img, preds): + scores, raw_boxes = preds['boxes'], preds['boxes_num'] + batch_size = raw_boxes[0].shape[0] + reg_max = int(raw_boxes[0].shape[-1] / 4 - 1) + out_boxes_num = [] + out_boxes_list = [] + results = [] + ori_shape, input_shape, scale_factor = self.img_info(ori_img, img) + + for batch_id in range(batch_size): + # generate centers + decode_boxes = [] + select_scores = [] + for stride, box_distribute, score in zip(self.strides, raw_boxes, + scores): + box_distribute = box_distribute[batch_id] + score = score[batch_id] + # centers + fm_h = input_shape[0] / stride + fm_w = input_shape[1] / stride + h_range = np.arange(fm_h) + w_range = np.arange(fm_w) + ww, hh = np.meshgrid(w_range, h_range) + ct_row = (hh.flatten() + 0.5) * stride + ct_col = (ww.flatten() + 0.5) * stride + center = np.stack((ct_col, ct_row, ct_col, ct_row), axis=1) + + # box distribution to distance + reg_range = np.arange(reg_max + 1) + box_distance = box_distribute.reshape((-1, reg_max + 1)) + box_distance = softmax(box_distance, axis=1) + box_distance = box_distance * np.expand_dims(reg_range, axis=0) + box_distance = np.sum(box_distance, axis=1).reshape((-1, 4)) + box_distance = box_distance * stride + + # top K candidate + topk_idx = np.argsort(score.max(axis=1))[::-1] + topk_idx = topk_idx[:self.nms_top_k] + center = center[topk_idx] + score = score[topk_idx] + box_distance = box_distance[topk_idx] + + # decode box + decode_box = center + [-1, -1, 1, 1] * box_distance + + select_scores.append(score) + decode_boxes.append(decode_box) + + # nms + bboxes = np.concatenate(decode_boxes, axis=0) + confidences = np.concatenate(select_scores, axis=0) + picked_box_probs = [] + picked_labels = [] + for class_index in range(0, confidences.shape[1]): + probs = confidences[:, class_index] + mask = probs > self.score_threshold + probs = probs[mask] + if probs.shape[0] == 0: + continue + subset_boxes = bboxes[mask, :] + box_probs = np.concatenate( + [subset_boxes, probs.reshape(-1, 1)], axis=1) + box_probs = hard_nms( + box_probs, + iou_threshold=self.nms_threshold, + top_k=self.keep_top_k, ) + picked_box_probs.append(box_probs) + picked_labels.extend([class_index] * box_probs.shape[0]) + + if len(picked_box_probs) == 0: + out_boxes_list.append(np.empty((0, 4))) + out_boxes_num.append(0) + + else: + picked_box_probs = np.concatenate(picked_box_probs) + + # resize output boxes + picked_box_probs[:, :4] = self.warp_boxes( + picked_box_probs[:, :4], ori_shape[batch_id]) + im_scale = np.concatenate([ + scale_factor[batch_id][::-1], scale_factor[batch_id][::-1] + ]) + picked_box_probs[:, :4] /= im_scale + # clas score box + out_boxes_list.append( + np.concatenate( + [ + np.expand_dims( + np.array(picked_labels), + axis=-1), np.expand_dims( + picked_box_probs[:, 4], axis=-1), + picked_box_probs[:, :4] + ], + axis=1)) + out_boxes_num.append(len(picked_labels)) + + out_boxes_list = np.concatenate(out_boxes_list, axis=0) + out_boxes_num = np.asarray(out_boxes_num).astype(np.int32) + + for dt in out_boxes_list: + clsid, bbox, score = int(dt[0]), dt[2:], dt[1] + label = self.labels[clsid] + result = {'bbox': bbox, 'label': label} + results.append(result) + return results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..680473bf4b1863ac695dc8173778e59bd4fdacf9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) 2021 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. + +from .pse_postprocess import PSEPostProcess \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/README.md b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a19d5d1b6b1d8e6952eb054d74c6672ed10bc48 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/README.md @@ -0,0 +1,6 @@ +## 编译 +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/post_processing/pse +```python +python3 setup.py build_ext --inplace +``` diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1903a9149a7703ac7ae9a66273eca620e0d77272 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/__init__.py @@ -0,0 +1,29 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import sys +import os +import subprocess + +python_path = sys.executable + +ori_path = os.getcwd() +os.chdir('ppocr/postprocess/pse_postprocess/pse') +if subprocess.call( + '{} setup.py build_ext --inplace'.format(python_path), shell=True) != 0: + raise RuntimeError( + 'Cannot compile pse: {}, if your system is windows, you need to install all the default components of `desktop development using C++` in visual studio 2019+'. + format(os.path.dirname(os.path.realpath(__file__)))) +os.chdir(ori_path) + +from .pse import pse diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/pse.pyx b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/pse.pyx new file mode 100644 index 0000000000000000000000000000000000000000..b2be49e9471865c11b840207f922258e67a554b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/pse.pyx @@ -0,0 +1,70 @@ + +import numpy as np +import cv2 +cimport numpy as np +cimport cython +cimport libcpp +cimport libcpp.pair +cimport libcpp.queue +from libcpp.pair cimport * +from libcpp.queue cimport * + +@cython.boundscheck(False) +@cython.wraparound(False) +cdef np.ndarray[np.int32_t, ndim=2] _pse(np.ndarray[np.uint8_t, ndim=3] kernels, + np.ndarray[np.int32_t, ndim=2] label, + int kernel_num, + int label_num, + float min_area=0): + cdef np.ndarray[np.int32_t, ndim=2] pred + pred = np.zeros((label.shape[0], label.shape[1]), dtype=np.int32) + + for label_idx in range(1, label_num): + if np.sum(label == label_idx) < min_area: + label[label == label_idx] = 0 + + cdef libcpp.queue.queue[libcpp.pair.pair[np.int16_t,np.int16_t]] que = \ + queue[libcpp.pair.pair[np.int16_t,np.int16_t]]() + cdef libcpp.queue.queue[libcpp.pair.pair[np.int16_t,np.int16_t]] nxt_que = \ + queue[libcpp.pair.pair[np.int16_t,np.int16_t]]() + cdef np.int16_t* dx = [-1, 1, 0, 0] + cdef np.int16_t* dy = [0, 0, -1, 1] + cdef np.int16_t tmpx, tmpy + + points = np.array(np.where(label > 0)).transpose((1, 0)) + for point_idx in range(points.shape[0]): + tmpx, tmpy = points[point_idx, 0], points[point_idx, 1] + que.push(pair[np.int16_t,np.int16_t](tmpx, tmpy)) + pred[tmpx, tmpy] = label[tmpx, tmpy] + + cdef libcpp.pair.pair[np.int16_t,np.int16_t] cur + cdef int cur_label + for kernel_idx in range(kernel_num - 1, -1, -1): + while not que.empty(): + cur = que.front() + que.pop() + cur_label = pred[cur.first, cur.second] + + is_edge = True + for j in range(4): + tmpx = cur.first + dx[j] + tmpy = cur.second + dy[j] + if tmpx < 0 or tmpx >= label.shape[0] or tmpy < 0 or tmpy >= label.shape[1]: + continue + if kernels[kernel_idx, tmpx, tmpy] == 0 or pred[tmpx, tmpy] > 0: + continue + + que.push(pair[np.int16_t,np.int16_t](tmpx, tmpy)) + pred[tmpx, tmpy] = cur_label + is_edge = False + if is_edge: + nxt_que.push(cur) + + que, nxt_que = nxt_que, que + + return pred + +def pse(kernels, min_area): + kernel_num = kernels.shape[0] + label_num, label = cv2.connectedComponents(kernels[-1], connectivity=4) + return _pse(kernels[:-1], label, kernel_num, label_num, min_area) \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/setup.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..03746782af791938bff31c24e4a760f566c73b49 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse/setup.py @@ -0,0 +1,14 @@ +from distutils.core import setup, Extension +from Cython.Build import cythonize +import numpy + +setup(ext_modules=cythonize(Extension( + 'pse', + sources=['pse.pyx'], + language='c++', + include_dirs=[numpy.get_include()], + library_dirs=[], + libraries=[], + extra_compile_args=['-O3'], + extra_link_args=[] +))) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse_postprocess.py new file mode 100755 index 0000000000000000000000000000000000000000..962f3efe922c4a2656e0f44f478e1baf301a5542 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/pse_postprocess/pse_postprocess.py @@ -0,0 +1,120 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/head/psenet_head.py +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import cv2 +import paddle +from paddle.nn import functional as F + +from ppocr.postprocess.pse_postprocess.pse import pse + + +class PSEPostProcess(object): + """ + The post process for PSE. + """ + + def __init__(self, + thresh=0.5, + box_thresh=0.85, + min_area=16, + box_type='quad', + scale=4, + **kwargs): + assert box_type in ['quad', 'poly'], 'Only quad and poly is supported' + self.thresh = thresh + self.box_thresh = box_thresh + self.min_area = min_area + self.box_type = box_type + self.scale = scale + + def __call__(self, outs_dict, shape_list): + pred = outs_dict['maps'] + if not isinstance(pred, paddle.Tensor): + pred = paddle.to_tensor(pred) + pred = F.interpolate( + pred, scale_factor=4 // self.scale, mode='bilinear') + + score = F.sigmoid(pred[:, 0, :, :]) + + kernels = (pred > self.thresh).astype('float32') + text_mask = kernels[:, 0, :, :] + text_mask = paddle.unsqueeze(text_mask, axis=1) + + kernels[:, 0:, :, :] = kernels[:, 0:, :, :] * text_mask + + score = score.numpy() + kernels = kernels.numpy().astype(np.uint8) + + boxes_batch = [] + for batch_index in range(pred.shape[0]): + boxes, scores = self.boxes_from_bitmap(score[batch_index], + kernels[batch_index], + shape_list[batch_index]) + + boxes_batch.append({'points': boxes, 'scores': scores}) + return boxes_batch + + def boxes_from_bitmap(self, score, kernels, shape): + label = pse(kernels, self.min_area) + return self.generate_box(score, label, shape) + + def generate_box(self, score, label, shape): + src_h, src_w, ratio_h, ratio_w = shape + label_num = np.max(label) + 1 + + boxes = [] + scores = [] + for i in range(1, label_num): + ind = label == i + points = np.array(np.where(ind)).transpose((1, 0))[:, ::-1] + + if points.shape[0] < self.min_area: + label[ind] = 0 + continue + + score_i = np.mean(score[ind]) + if score_i < self.box_thresh: + label[ind] = 0 + continue + + if self.box_type == 'quad': + rect = cv2.minAreaRect(points) + bbox = cv2.boxPoints(rect) + elif self.box_type == 'poly': + box_height = np.max(points[:, 1]) + 10 + box_width = np.max(points[:, 0]) + 10 + + mask = np.zeros((box_height, box_width), np.uint8) + mask[points[:, 1], points[:, 0]] = 255 + + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_SIMPLE) + bbox = np.squeeze(contours[0], 1) + else: + raise NotImplementedError + + bbox[:, 0] = np.clip(np.round(bbox[:, 0] / ratio_w), 0, src_w) + bbox[:, 1] = np.clip(np.round(bbox[:, 1] / ratio_h), 0, src_h) + boxes.append(bbox) + scores.append(score_i) + return boxes, scores diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/rec_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/rec_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..99e7d0c90f24373c97247bcd407d30af2b48a430 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/rec_postprocess.py @@ -0,0 +1,814 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import numpy as np +import paddle +from paddle.nn import functional as F +import re + + +class BaseRecLabelDecode(object): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False): + self.beg_str = "sos" + self.end_str = "eos" + self.reverse = False + self.character_str = [] + if character_dict_path is None: + self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz" + dict_character = list(self.character_str) + else: + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + self.character_str.append(line) + if use_space_char: + self.character_str.append(" ") + dict_character = list(self.character_str) + if 'arabic' in character_dict_path: + self.reverse = True + + dict_character = self.add_special_char(dict_character) + self.dict = {} + for i, char in enumerate(dict_character): + self.dict[char] = i + self.character = dict_character + + def pred_reverse(self, pred): + pred_re = [] + c_current = '' + for c in pred: + if not bool(re.search('[a-zA-Z0-9 :*./%+-]', c)): + if c_current != '': + pred_re.append(c_current) + pred_re.append(c) + c_current = '' + else: + c_current += c + if c_current != '': + pred_re.append(c_current) + + return ''.join(pred_re[::-1]) + + def add_special_char(self, dict_character): + return dict_character + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + ignored_tokens = self.get_ignored_tokens() + batch_size = len(text_index) + for batch_idx in range(batch_size): + selection = np.ones(len(text_index[batch_idx]), dtype=bool) + if is_remove_duplicate: + selection[1:] = text_index[batch_idx][1:] != text_index[ + batch_idx][:-1] + for ignored_token in ignored_tokens: + selection &= text_index[batch_idx] != ignored_token + + char_list = [ + self.character[text_id] + for text_id in text_index[batch_idx][selection] + ] + if text_prob is not None: + conf_list = text_prob[batch_idx][selection] + else: + conf_list = [1] * len(selection) + if len(conf_list) == 0: + conf_list = [0] + + text = ''.join(char_list) + + if self.reverse: # for arabic rec + text = self.pred_reverse(text) + + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def get_ignored_tokens(self): + return [0] # for ctc blank + + +class CTCLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(CTCLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def __call__(self, preds, label=None, *args, **kwargs): + if isinstance(preds, tuple) or isinstance(preds, list): + preds = preds[-1] + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True) + if label is None: + return text + label = self.decode(label) + return text, label + + def add_special_char(self, dict_character): + dict_character = ['blank'] + dict_character + return dict_character + + +class DistillationCTCLabelDecode(CTCLabelDecode): + """ + Convert + Convert between text-label and text-index + """ + + def __init__(self, + character_dict_path=None, + use_space_char=False, + model_name=["student"], + key=None, + multi_head=False, + **kwargs): + super(DistillationCTCLabelDecode, self).__init__(character_dict_path, + use_space_char) + if not isinstance(model_name, list): + model_name = [model_name] + self.model_name = model_name + + self.key = key + self.multi_head = multi_head + + def __call__(self, preds, label=None, *args, **kwargs): + output = dict() + for name in self.model_name: + pred = preds[name] + if self.key is not None: + pred = pred[self.key] + if self.multi_head and isinstance(pred, dict): + pred = pred['ctc'] + output[name] = super().__call__(pred, label=label, *args, **kwargs) + return output + + +class AttnLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(AttnLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def add_special_char(self, dict_character): + self.beg_str = "sos" + self.end_str = "eos" + dict_character = dict_character + dict_character = [self.beg_str] + dict_character + [self.end_str] + return dict_character + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + ignored_tokens = self.get_ignored_tokens() + [beg_idx, end_idx] = self.get_ignored_tokens() + batch_size = len(text_index) + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + if text_index[batch_idx][idx] in ignored_tokens: + continue + if int(text_index[batch_idx][idx]) == int(end_idx): + break + if is_remove_duplicate: + # only for predict + if idx > 0 and text_index[batch_idx][idx - 1] == text_index[ + batch_idx][idx]: + continue + char_list.append(self.character[int(text_index[batch_idx][ + idx])]) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + text = ''.join(char_list) + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def __call__(self, preds, label=None, *args, **kwargs): + """ + text = self.decode(text) + if label is None: + return text + else: + label = self.decode(label, is_remove_duplicate=False) + return text, label + """ + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label, is_remove_duplicate=False) + return text, label + + def get_ignored_tokens(self): + beg_idx = self.get_beg_end_flag_idx("beg") + end_idx = self.get_beg_end_flag_idx("end") + return [beg_idx, end_idx] + + def get_beg_end_flag_idx(self, beg_or_end): + if beg_or_end == "beg": + idx = np.array(self.dict[self.beg_str]) + elif beg_or_end == "end": + idx = np.array(self.dict[self.end_str]) + else: + assert False, "unsupport type %s in get_beg_end_flag_idx" \ + % beg_or_end + return idx + + +class SEEDLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(SEEDLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def add_special_char(self, dict_character): + self.padding_str = "padding" + self.end_str = "eos" + self.unknown = "unknown" + dict_character = dict_character + [ + self.end_str, self.padding_str, self.unknown + ] + return dict_character + + def get_ignored_tokens(self): + end_idx = self.get_beg_end_flag_idx("eos") + return [end_idx] + + def get_beg_end_flag_idx(self, beg_or_end): + if beg_or_end == "sos": + idx = np.array(self.dict[self.beg_str]) + elif beg_or_end == "eos": + idx = np.array(self.dict[self.end_str]) + else: + assert False, "unsupport type %s in get_beg_end_flag_idx" % beg_or_end + return idx + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + [end_idx] = self.get_ignored_tokens() + batch_size = len(text_index) + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + if int(text_index[batch_idx][idx]) == int(end_idx): + break + if is_remove_duplicate: + # only for predict + if idx > 0 and text_index[batch_idx][idx - 1] == text_index[ + batch_idx][idx]: + continue + char_list.append(self.character[int(text_index[batch_idx][ + idx])]) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + text = ''.join(char_list) + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def __call__(self, preds, label=None, *args, **kwargs): + """ + text = self.decode(text) + if label is None: + return text + else: + label = self.decode(label, is_remove_duplicate=False) + return text, label + """ + tmp = {} + if isinstance(preds, list): + tmp["rec_pred"] = preds[1] + tmp["rec_pred_scores"] = preds[0] + preds = tmp + preds_idx = preds["rec_pred"] + if isinstance(preds_idx, paddle.Tensor): + preds_idx = preds_idx.numpy() + if "rec_pred_scores" in preds: + preds_idx = preds["rec_pred"] + preds_prob = preds["rec_pred_scores"] + else: + preds_idx = preds["rec_pred"].argmax(axis=2) + preds_prob = preds["rec_pred"].max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label, is_remove_duplicate=False) + return text, label + + +class SRNLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(SRNLabelDecode, self).__init__(character_dict_path, + use_space_char) + self.max_text_length = kwargs.get('max_text_length', 25) + + def __call__(self, preds, label=None, *args, **kwargs): + pred = preds['predict'] + char_num = len(self.character_str) + 2 + if isinstance(pred, paddle.Tensor): + pred = pred.numpy() + pred = np.reshape(pred, [-1, char_num]) + + preds_idx = np.argmax(pred, axis=1) + preds_prob = np.max(pred, axis=1) + + preds_idx = np.reshape(preds_idx, [-1, self.max_text_length]) + + preds_prob = np.reshape(preds_prob, [-1, self.max_text_length]) + + text = self.decode(preds_idx, preds_prob) + + if label is None: + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + return text + label = self.decode(label) + return text, label + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + ignored_tokens = self.get_ignored_tokens() + batch_size = len(text_index) + + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + if text_index[batch_idx][idx] in ignored_tokens: + continue + if is_remove_duplicate: + # only for predict + if idx > 0 and text_index[batch_idx][idx - 1] == text_index[ + batch_idx][idx]: + continue + char_list.append(self.character[int(text_index[batch_idx][ + idx])]) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + + text = ''.join(char_list) + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def add_special_char(self, dict_character): + dict_character = dict_character + [self.beg_str, self.end_str] + return dict_character + + def get_ignored_tokens(self): + beg_idx = self.get_beg_end_flag_idx("beg") + end_idx = self.get_beg_end_flag_idx("end") + return [beg_idx, end_idx] + + def get_beg_end_flag_idx(self, beg_or_end): + if beg_or_end == "beg": + idx = np.array(self.dict[self.beg_str]) + elif beg_or_end == "end": + idx = np.array(self.dict[self.end_str]) + else: + assert False, "unsupport type %s in get_beg_end_flag_idx" \ + % beg_or_end + return idx + + +class SARLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(SARLabelDecode, self).__init__(character_dict_path, + use_space_char) + + self.rm_symbol = kwargs.get('rm_symbol', False) + + def add_special_char(self, dict_character): + beg_end_str = "" + unknown_str = "" + padding_str = "" + dict_character = dict_character + [unknown_str] + self.unknown_idx = len(dict_character) - 1 + dict_character = dict_character + [beg_end_str] + self.start_idx = len(dict_character) - 1 + self.end_idx = len(dict_character) - 1 + dict_character = dict_character + [padding_str] + self.padding_idx = len(dict_character) - 1 + return dict_character + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + ignored_tokens = self.get_ignored_tokens() + + batch_size = len(text_index) + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + if text_index[batch_idx][idx] in ignored_tokens: + continue + if int(text_index[batch_idx][idx]) == int(self.end_idx): + if text_prob is None and idx == 0: + continue + else: + break + if is_remove_duplicate: + # only for predict + if idx > 0 and text_index[batch_idx][idx - 1] == text_index[ + batch_idx][idx]: + continue + char_list.append(self.character[int(text_index[batch_idx][ + idx])]) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + text = ''.join(char_list) + if self.rm_symbol: + comp = re.compile('[^A-Z^a-z^0-9^\u4e00-\u9fa5]') + text = text.lower() + text = comp.sub('', text) + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def __call__(self, preds, label=None, *args, **kwargs): + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + + if label is None: + return text + label = self.decode(label, is_remove_duplicate=False) + return text, label + + def get_ignored_tokens(self): + return [self.padding_idx] + + +class DistillationSARLabelDecode(SARLabelDecode): + """ + Convert + Convert between text-label and text-index + """ + + def __init__(self, + character_dict_path=None, + use_space_char=False, + model_name=["student"], + key=None, + multi_head=False, + **kwargs): + super(DistillationSARLabelDecode, self).__init__(character_dict_path, + use_space_char) + if not isinstance(model_name, list): + model_name = [model_name] + self.model_name = model_name + + self.key = key + self.multi_head = multi_head + + def __call__(self, preds, label=None, *args, **kwargs): + output = dict() + for name in self.model_name: + pred = preds[name] + if self.key is not None: + pred = pred[self.key] + if self.multi_head and isinstance(pred, dict): + pred = pred['sar'] + output[name] = super().__call__(pred, label=label, *args, **kwargs) + return output + + +class PRENLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(PRENLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def add_special_char(self, dict_character): + padding_str = '' # 0 + end_str = '' # 1 + unknown_str = '' # 2 + + dict_character = [padding_str, end_str, unknown_str] + dict_character + self.padding_idx = 0 + self.end_idx = 1 + self.unknown_idx = 2 + + return dict_character + + def decode(self, text_index, text_prob=None): + """ convert text-index into text-label. """ + result_list = [] + batch_size = len(text_index) + + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + if text_index[batch_idx][idx] == self.end_idx: + break + if text_index[batch_idx][idx] in \ + [self.padding_idx, self.unknown_idx]: + continue + char_list.append(self.character[int(text_index[batch_idx][ + idx])]) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + + text = ''.join(char_list) + if len(text) > 0: + result_list.append((text, np.mean(conf_list).tolist())) + else: + # here confidence of empty recog result is 1 + result_list.append(('', 1)) + return result_list + + def __call__(self, preds, label=None, *args, **kwargs): + preds = preds.numpy() + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob) + if label is None: + return text + label = self.decode(label) + return text, label + + +class NRTRLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=True, **kwargs): + super(NRTRLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def __call__(self, preds, label=None, *args, **kwargs): + + if len(preds) == 2: + preds_id = preds[0] + preds_prob = preds[1] + if isinstance(preds_id, paddle.Tensor): + preds_id = preds_id.numpy() + if isinstance(preds_prob, paddle.Tensor): + preds_prob = preds_prob.numpy() + if preds_id[0][0] == 2: + preds_idx = preds_id[:, 1:] + preds_prob = preds_prob[:, 1:] + else: + preds_idx = preds_id + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label[:, 1:]) + else: + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label[:, 1:]) + return text, label + + def add_special_char(self, dict_character): + dict_character = ['blank', '', '', ''] + dict_character + return dict_character + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + batch_size = len(text_index) + for batch_idx in range(batch_size): + char_list = [] + conf_list = [] + for idx in range(len(text_index[batch_idx])): + try: + char_idx = self.character[int(text_index[batch_idx][idx])] + except: + continue + if char_idx == '': # end + break + char_list.append(char_idx) + if text_prob is not None: + conf_list.append(text_prob[batch_idx][idx]) + else: + conf_list.append(1) + text = ''.join(char_list) + result_list.append((text.lower(), np.mean(conf_list).tolist())) + return result_list + + +class ViTSTRLabelDecode(NRTRLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(ViTSTRLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def __call__(self, preds, label=None, *args, **kwargs): + if isinstance(preds, paddle.Tensor): + preds = preds[:, 1:].numpy() + else: + preds = preds[:, 1:] + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label[:, 1:]) + return text, label + + def add_special_char(self, dict_character): + dict_character = ['', ''] + dict_character + return dict_character + + +class ABINetLabelDecode(NRTRLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(ABINetLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def __call__(self, preds, label=None, *args, **kwargs): + if isinstance(preds, dict): + preds = preds['align'][-1].numpy() + elif isinstance(preds, paddle.Tensor): + preds = preds.numpy() + else: + preds = preds + + preds_idx = preds.argmax(axis=2) + preds_prob = preds.max(axis=2) + text = self.decode(preds_idx, preds_prob, is_remove_duplicate=False) + if label is None: + return text + label = self.decode(label) + return text, label + + def add_special_char(self, dict_character): + dict_character = [''] + dict_character + return dict_character + + +class SPINLabelDecode(AttnLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(SPINLabelDecode, self).__init__(character_dict_path, + use_space_char) + + def add_special_char(self, dict_character): + self.beg_str = "sos" + self.end_str = "eos" + dict_character = dict_character + dict_character = [self.beg_str] + [self.end_str] + dict_character + return dict_character + + +class VLLabelDecode(BaseRecLabelDecode): + """ Convert between text-label and text-index """ + + def __init__(self, character_dict_path=None, use_space_char=False, + **kwargs): + super(VLLabelDecode, self).__init__(character_dict_path, use_space_char) + self.max_text_length = kwargs.get('max_text_length', 25) + self.nclass = len(self.character) + 1 + self.character = self.character[10:] + self.character[ + 1:10] + [self.character[0]] + + def decode(self, text_index, text_prob=None, is_remove_duplicate=False): + """ convert text-index into text-label. """ + result_list = [] + ignored_tokens = self.get_ignored_tokens() + batch_size = len(text_index) + for batch_idx in range(batch_size): + selection = np.ones(len(text_index[batch_idx]), dtype=bool) + if is_remove_duplicate: + selection[1:] = text_index[batch_idx][1:] != text_index[ + batch_idx][:-1] + for ignored_token in ignored_tokens: + selection &= text_index[batch_idx] != ignored_token + + char_list = [ + self.character[text_id - 1] + for text_id in text_index[batch_idx][selection] + ] + if text_prob is not None: + conf_list = text_prob[batch_idx][selection] + else: + conf_list = [1] * len(selection) + if len(conf_list) == 0: + conf_list = [0] + + text = ''.join(char_list) + result_list.append((text, np.mean(conf_list).tolist())) + return result_list + + def __call__(self, preds, label=None, length=None, *args, **kwargs): + if len(preds) == 2: # eval mode + text_pre, x = preds + b = text_pre.shape[1] + lenText = self.max_text_length + nsteps = self.max_text_length + + if not isinstance(text_pre, paddle.Tensor): + text_pre = paddle.to_tensor(text_pre, dtype='float32') + + out_res = paddle.zeros( + shape=[lenText, b, self.nclass], dtype=x.dtype) + out_length = paddle.zeros(shape=[b], dtype=x.dtype) + now_step = 0 + for _ in range(nsteps): + if 0 in out_length and now_step < nsteps: + tmp_result = text_pre[now_step, :, :] + out_res[now_step] = tmp_result + tmp_result = tmp_result.topk(1)[1].squeeze(axis=1) + for j in range(b): + if out_length[j] == 0 and tmp_result[j] == 0: + out_length[j] = now_step + 1 + now_step += 1 + for j in range(0, b): + if int(out_length[j]) == 0: + out_length[j] = nsteps + start = 0 + output = paddle.zeros( + shape=[int(out_length.sum()), self.nclass], dtype=x.dtype) + for i in range(0, b): + cur_length = int(out_length[i]) + output[start:start + cur_length] = out_res[0:cur_length, i, :] + start += cur_length + net_out = output + length = out_length + + else: # train mode + net_out = preds[0] + length = length + net_out = paddle.concat([t[:l] for t, l in zip(net_out, length)]) + text = [] + if not isinstance(net_out, paddle.Tensor): + net_out = paddle.to_tensor(net_out, dtype='float32') + net_out = F.softmax(net_out, axis=1) + for i in range(0, length.shape[0]): + preds_idx = net_out[int(length[:i].sum()):int(length[:i].sum( + ) + length[i])].topk(1)[1][:, 0].tolist() + preds_text = ''.join([ + self.character[idx - 1] + if idx > 0 and idx <= len(self.character) else '' + for idx in preds_idx + ]) + preds_prob = net_out[int(length[:i].sum()):int(length[:i].sum( + ) + length[i])].topk(1)[0][:, 0] + preds_prob = paddle.exp( + paddle.log(preds_prob).sum() / (preds_prob.shape[0] + 1e-6)) + text.append((preds_text, preds_prob.numpy()[0])) + if label is None: + return text + label = self.decode(label) + return text, label diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/sast_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/sast_postprocess.py new file mode 100755 index 0000000000000000000000000000000000000000..bee75c05b1a3ea59193d566f91378c96797f533b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/sast_postprocess.py @@ -0,0 +1,355 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys + +__dir__ = os.path.dirname(__file__) +sys.path.append(__dir__) +sys.path.append(os.path.join(__dir__, '..')) + +import numpy as np +from .locality_aware_nms import nms_locality +import paddle +import cv2 +import time + + +class SASTPostProcess(object): + """ + The post process for SAST. + """ + + def __init__(self, + score_thresh=0.5, + nms_thresh=0.2, + sample_pts_num=2, + shrink_ratio_of_width=0.3, + expand_scale=1.0, + tcl_map_thresh=0.5, + **kwargs): + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.sample_pts_num = sample_pts_num + self.shrink_ratio_of_width = shrink_ratio_of_width + self.expand_scale = expand_scale + self.tcl_map_thresh = tcl_map_thresh + + # c++ la-nms is faster, but only support python 3.5 + self.is_python35 = False + if sys.version_info.major == 3 and sys.version_info.minor == 5: + self.is_python35 = True + + def point_pair2poly(self, point_pair_list): + """ + Transfer vertical point_pairs into poly point in clockwise. + """ + # constract poly + point_num = len(point_pair_list) * 2 + point_list = [0] * point_num + for idx, point_pair in enumerate(point_pair_list): + point_list[idx] = point_pair[0] + point_list[point_num - 1 - idx] = point_pair[1] + return np.array(point_list).reshape(-1, 2) + + def shrink_quad_along_width(self, + quad, + begin_width_ratio=0., + end_width_ratio=1.): + """ + Generate shrink_quad_along_width. + """ + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + def expand_poly_along_width(self, poly, shrink_ratio_of_width=0.3): + """ + expand poly along width. + """ + point_num = poly.shape[0] + left_quad = np.array( + [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32) + left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \ + (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6) + left_quad_expand = self.shrink_quad_along_width(left_quad, left_ratio, + 1.0) + right_quad = np.array( + [ + poly[point_num // 2 - 2], poly[point_num // 2 - 1], + poly[point_num // 2], poly[point_num // 2 + 1] + ], + dtype=np.float32) + right_ratio = 1.0 + \ + shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \ + (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6) + right_quad_expand = self.shrink_quad_along_width(right_quad, 0.0, + right_ratio) + poly[0] = left_quad_expand[0] + poly[-1] = left_quad_expand[-1] + poly[point_num // 2 - 1] = right_quad_expand[1] + poly[point_num // 2] = right_quad_expand[2] + return poly + + def restore_quad(self, tcl_map, tcl_map_thresh, tvo_map): + """Restore quad.""" + xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh) + xy_text = xy_text[:, ::-1] # (n, 2) + + # Sort the text boxes via the y axis + xy_text = xy_text[np.argsort(xy_text[:, 1])] + + scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0] + scores = scores[:, np.newaxis] + + # Restore + point_num = int(tvo_map.shape[-1] / 2) + assert point_num == 4 + tvo_map = tvo_map[xy_text[:, 1], xy_text[:, 0], :] + xy_text_tile = np.tile(xy_text, (1, point_num)) # (n, point_num * 2) + quads = xy_text_tile - tvo_map + + return scores, quads, xy_text + + def quad_area(self, quad): + """ + compute area of a quad. + """ + edge = [(quad[1][0] - quad[0][0]) * (quad[1][1] + quad[0][1]), + (quad[2][0] - quad[1][0]) * (quad[2][1] + quad[1][1]), + (quad[3][0] - quad[2][0]) * (quad[3][1] + quad[2][1]), + (quad[0][0] - quad[3][0]) * (quad[0][1] + quad[3][1])] + return np.sum(edge) / 2. + + def nms(self, dets): + if self.is_python35: + import lanms + dets = lanms.merge_quadrangle_n9(dets, self.nms_thresh) + else: + dets = nms_locality(dets, self.nms_thresh) + return dets + + def cluster_by_quads_tco(self, tcl_map, tcl_map_thresh, quads, tco_map): + """ + Cluster pixels in tcl_map based on quads. + """ + instance_count = quads.shape[0] + 1 # contain background + instance_label_map = np.zeros(tcl_map.shape[:2], dtype=np.int32) + if instance_count == 1: + return instance_count, instance_label_map + + # predict text center + xy_text = np.argwhere(tcl_map[:, :, 0] > tcl_map_thresh) + n = xy_text.shape[0] + xy_text = xy_text[:, ::-1] # (n, 2) + tco = tco_map[xy_text[:, 1], xy_text[:, 0], :] # (n, 2) + pred_tc = xy_text - tco + + # get gt text center + m = quads.shape[0] + gt_tc = np.mean(quads, axis=1) # (m, 2) + + pred_tc_tile = np.tile(pred_tc[:, np.newaxis, :], + (1, m, 1)) # (n, m, 2) + gt_tc_tile = np.tile(gt_tc[np.newaxis, :, :], (n, 1, 1)) # (n, m, 2) + dist_mat = np.linalg.norm(pred_tc_tile - gt_tc_tile, axis=2) # (n, m) + xy_text_assign = np.argmin(dist_mat, axis=1) + 1 # (n,) + + instance_label_map[xy_text[:, 1], xy_text[:, 0]] = xy_text_assign + return instance_count, instance_label_map + + def estimate_sample_pts_num(self, quad, xy_text): + """ + Estimate sample points number. + """ + eh = (np.linalg.norm(quad[0] - quad[3]) + + np.linalg.norm(quad[1] - quad[2])) / 2.0 + ew = (np.linalg.norm(quad[0] - quad[1]) + + np.linalg.norm(quad[2] - quad[3])) / 2.0 + + dense_sample_pts_num = max(2, int(ew)) + dense_xy_center_line = xy_text[np.linspace( + 0, + xy_text.shape[0] - 1, + dense_sample_pts_num, + endpoint=True, + dtype=np.float32).astype(np.int32)] + + dense_xy_center_line_diff = dense_xy_center_line[ + 1:] - dense_xy_center_line[:-1] + estimate_arc_len = np.sum( + np.linalg.norm( + dense_xy_center_line_diff, axis=1)) + + sample_pts_num = max(2, int(estimate_arc_len / eh)) + return sample_pts_num + + def detect_sast(self, + tcl_map, + tvo_map, + tbo_map, + tco_map, + ratio_w, + ratio_h, + src_w, + src_h, + shrink_ratio_of_width=0.3, + tcl_map_thresh=0.5, + offset_expand=1.0, + out_strid=4.0): + """ + first resize the tcl_map, tvo_map and tbo_map to the input_size, then restore the polys + """ + # restore quad + scores, quads, xy_text = self.restore_quad(tcl_map, tcl_map_thresh, + tvo_map) + dets = np.hstack((quads, scores)).astype(np.float32, copy=False) + dets = self.nms(dets) + if dets.shape[0] == 0: + return [] + quads = dets[:, :-1].reshape(-1, 4, 2) + + # Compute quad area + quad_areas = [] + for quad in quads: + quad_areas.append(-self.quad_area(quad)) + + # instance segmentation + # instance_count, instance_label_map = cv2.connectedComponents(tcl_map.astype(np.uint8), connectivity=8) + instance_count, instance_label_map = self.cluster_by_quads_tco( + tcl_map, tcl_map_thresh, quads, tco_map) + + # restore single poly with tcl instance. + poly_list = [] + for instance_idx in range(1, instance_count): + xy_text = np.argwhere(instance_label_map == instance_idx)[:, ::-1] + quad = quads[instance_idx - 1] + q_area = quad_areas[instance_idx - 1] + if q_area < 5: + continue + + # + len1 = float(np.linalg.norm(quad[0] - quad[1])) + len2 = float(np.linalg.norm(quad[1] - quad[2])) + min_len = min(len1, len2) + if min_len < 3: + continue + + # filter small CC + if xy_text.shape[0] <= 0: + continue + + # filter low confidence instance + xy_text_scores = tcl_map[xy_text[:, 1], xy_text[:, 0], 0] + if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.1: + # if np.sum(xy_text_scores) / quad_areas[instance_idx - 1] < 0.05: + continue + + # sort xy_text + left_center_pt = np.array( + [[(quad[0, 0] + quad[-1, 0]) / 2.0, + (quad[0, 1] + quad[-1, 1]) / 2.0]]) # (1, 2) + right_center_pt = np.array( + [[(quad[1, 0] + quad[2, 0]) / 2.0, + (quad[1, 1] + quad[2, 1]) / 2.0]]) # (1, 2) + proj_unit_vec = (right_center_pt - left_center_pt) / \ + (np.linalg.norm(right_center_pt - left_center_pt) + 1e-6) + proj_value = np.sum(xy_text * proj_unit_vec, axis=1) + xy_text = xy_text[np.argsort(proj_value)] + + # Sample pts in tcl map + if self.sample_pts_num == 0: + sample_pts_num = self.estimate_sample_pts_num(quad, xy_text) + else: + sample_pts_num = self.sample_pts_num + xy_center_line = xy_text[np.linspace( + 0, + xy_text.shape[0] - 1, + sample_pts_num, + endpoint=True, + dtype=np.float32).astype(np.int32)] + + point_pair_list = [] + for x, y in xy_center_line: + # get corresponding offset + offset = tbo_map[y, x, :].reshape(2, 2) + if offset_expand != 1.0: + offset_length = np.linalg.norm( + offset, axis=1, keepdims=True) + expand_length = np.clip( + offset_length * (offset_expand - 1), + a_min=0.5, + a_max=3.0) + offset_detal = offset / offset_length * expand_length + offset = offset + offset_detal + # original point + ori_yx = np.array([y, x], dtype=np.float32) + point_pair = (ori_yx + offset)[:, ::-1] * out_strid / np.array( + [ratio_w, ratio_h]).reshape(-1, 2) + point_pair_list.append(point_pair) + + # ndarry: (x, 2), expand poly along width + detected_poly = self.point_pair2poly(point_pair_list) + detected_poly = self.expand_poly_along_width(detected_poly, + shrink_ratio_of_width) + detected_poly[:, 0] = np.clip( + detected_poly[:, 0], a_min=0, a_max=src_w) + detected_poly[:, 1] = np.clip( + detected_poly[:, 1], a_min=0, a_max=src_h) + poly_list.append(detected_poly) + + return poly_list + + def __call__(self, outs_dict, shape_list): + score_list = outs_dict['f_score'] + border_list = outs_dict['f_border'] + tvo_list = outs_dict['f_tvo'] + tco_list = outs_dict['f_tco'] + if isinstance(score_list, paddle.Tensor): + score_list = score_list.numpy() + border_list = border_list.numpy() + tvo_list = tvo_list.numpy() + tco_list = tco_list.numpy() + + img_num = len(shape_list) + poly_lists = [] + for ino in range(img_num): + p_score = score_list[ino].transpose((1, 2, 0)) + p_border = border_list[ino].transpose((1, 2, 0)) + p_tvo = tvo_list[ino].transpose((1, 2, 0)) + p_tco = tco_list[ino].transpose((1, 2, 0)) + src_h, src_w, ratio_h, ratio_w = shape_list[ino] + + poly_list = self.detect_sast( + p_score, + p_tvo, + p_border, + p_tco, + ratio_w, + ratio_h, + src_w, + src_h, + shrink_ratio_of_width=self.shrink_ratio_of_width, + tcl_map_thresh=self.tcl_map_thresh, + offset_expand=self.expand_scale) + poly_lists.append({'points': np.array(poly_list)}) + + return poly_lists diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/table_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/table_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..a47061f935e31b24fdb624df170f8abb38e01f40 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/table_postprocess.py @@ -0,0 +1,186 @@ +# Copyright (c) 2021 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. + +import numpy as np +import paddle + +from .rec_postprocess import AttnLabelDecode + + +class TableLabelDecode(AttnLabelDecode): + """ """ + + def __init__(self, + character_dict_path, + merge_no_span_structure=False, + **kwargs): + dict_character = [] + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + dict_character.append(line) + + if merge_no_span_structure: + if "" not in dict_character: + dict_character.append("") + if "" in dict_character: + dict_character.remove("") + + dict_character = self.add_special_char(dict_character) + self.dict = {} + for i, char in enumerate(dict_character): + self.dict[char] = i + self.character = dict_character + self.td_token = ['', ''] + + def __call__(self, preds, batch=None): + structure_probs = preds['structure_probs'] + bbox_preds = preds['loc_preds'] + if isinstance(structure_probs, paddle.Tensor): + structure_probs = structure_probs.numpy() + if isinstance(bbox_preds, paddle.Tensor): + bbox_preds = bbox_preds.numpy() + shape_list = batch[-1] + result = self.decode(structure_probs, bbox_preds, shape_list) + if len(batch) == 1: # only contains shape + return result + + label_decode_result = self.decode_label(batch) + return result, label_decode_result + + def decode(self, structure_probs, bbox_preds, shape_list): + """convert text-label into text-index. + """ + ignored_tokens = self.get_ignored_tokens() + end_idx = self.dict[self.end_str] + + structure_idx = structure_probs.argmax(axis=2) + structure_probs = structure_probs.max(axis=2) + + structure_batch_list = [] + bbox_batch_list = [] + batch_size = len(structure_idx) + for batch_idx in range(batch_size): + structure_list = [] + bbox_list = [] + score_list = [] + for idx in range(len(structure_idx[batch_idx])): + char_idx = int(structure_idx[batch_idx][idx]) + if idx > 0 and char_idx == end_idx: + break + if char_idx in ignored_tokens: + continue + text = self.character[char_idx] + if text in self.td_token: + bbox = bbox_preds[batch_idx, idx] + bbox = self._bbox_decode(bbox, shape_list[batch_idx]) + bbox_list.append(bbox) + structure_list.append(text) + score_list.append(structure_probs[batch_idx, idx]) + structure_batch_list.append([structure_list, np.mean(score_list)]) + bbox_batch_list.append(np.array(bbox_list)) + result = { + 'bbox_batch_list': bbox_batch_list, + 'structure_batch_list': structure_batch_list, + } + return result + + def decode_label(self, batch): + """convert text-label into text-index. + """ + structure_idx = batch[1] + gt_bbox_list = batch[2] + shape_list = batch[-1] + ignored_tokens = self.get_ignored_tokens() + end_idx = self.dict[self.end_str] + + structure_batch_list = [] + bbox_batch_list = [] + batch_size = len(structure_idx) + for batch_idx in range(batch_size): + structure_list = [] + bbox_list = [] + for idx in range(len(structure_idx[batch_idx])): + char_idx = int(structure_idx[batch_idx][idx]) + if idx > 0 and char_idx == end_idx: + break + if char_idx in ignored_tokens: + continue + structure_list.append(self.character[char_idx]) + + bbox = gt_bbox_list[batch_idx][idx] + if bbox.sum() != 0: + bbox = self._bbox_decode(bbox, shape_list[batch_idx]) + bbox_list.append(bbox) + structure_batch_list.append(structure_list) + bbox_batch_list.append(bbox_list) + result = { + 'bbox_batch_list': bbox_batch_list, + 'structure_batch_list': structure_batch_list, + } + return result + + def _bbox_decode(self, bbox, shape): + h, w, ratio_h, ratio_w, pad_h, pad_w = shape + bbox[0::2] *= w + bbox[1::2] *= h + return bbox + + +class TableMasterLabelDecode(TableLabelDecode): + """ """ + + def __init__(self, + character_dict_path, + box_shape='ori', + merge_no_span_structure=True, + **kwargs): + super(TableMasterLabelDecode, self).__init__(character_dict_path, + merge_no_span_structure) + self.box_shape = box_shape + assert box_shape in [ + 'ori', 'pad' + ], 'The shape used for box normalization must be ori or pad' + + def add_special_char(self, dict_character): + self.beg_str = '' + self.end_str = '' + self.unknown_str = '' + self.pad_str = '' + dict_character = dict_character + dict_character = dict_character + [ + self.unknown_str, self.beg_str, self.end_str, self.pad_str + ] + return dict_character + + def get_ignored_tokens(self): + pad_idx = self.dict[self.pad_str] + start_idx = self.dict[self.beg_str] + end_idx = self.dict[self.end_str] + unknown_idx = self.dict[self.unknown_str] + return [start_idx, end_idx, pad_idx, unknown_idx] + + def _bbox_decode(self, bbox, shape): + h, w, ratio_h, ratio_w, pad_h, pad_w = shape + if self.box_shape == 'pad': + h, w = pad_h, pad_w + bbox[0::2] *= w + bbox[1::2] *= h + bbox[0::2] /= ratio_w + bbox[1::2] /= ratio_h + x, y, w, h = bbox + x1, y1, x2, y2 = x - w // 2, y - h // 2, x + w // 2, y + h // 2 + bbox = np.array([x1, y1, x2, y2]) + return bbox diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_re_layoutlm_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_re_layoutlm_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..96c25d9aac01066f7a3841fe61aa7b0fe05041bd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_re_layoutlm_postprocess.py @@ -0,0 +1,73 @@ +# Copyright (c) 2021 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. +import paddle + + +class VQAReTokenLayoutLMPostProcess(object): + """ Convert between text-label and text-index """ + + def __init__(self, **kwargs): + super(VQAReTokenLayoutLMPostProcess, self).__init__() + + def __call__(self, preds, label=None, *args, **kwargs): + if label is not None: + return self._metric(preds, label) + else: + return self._infer(preds, *args, **kwargs) + + def _metric(self, preds, label): + return preds['pred_relations'], label[6], label[5] + + def _infer(self, preds, *args, **kwargs): + ser_results = kwargs['ser_results'] + entity_idx_dict_batch = kwargs['entity_idx_dict_batch'] + pred_relations = preds['pred_relations'] + + # merge relations and ocr info + results = [] + for pred_relation, ser_result, entity_idx_dict in zip( + pred_relations, ser_results, entity_idx_dict_batch): + result = [] + used_tail_id = [] + for relation in pred_relation: + if relation['tail_id'] in used_tail_id: + continue + used_tail_id.append(relation['tail_id']) + ocr_info_head = ser_result[entity_idx_dict[relation['head_id']]] + ocr_info_tail = ser_result[entity_idx_dict[relation['tail_id']]] + result.append((ocr_info_head, ocr_info_tail)) + results.append(result) + return results + + +class DistillationRePostProcess(VQAReTokenLayoutLMPostProcess): + """ + DistillationRePostProcess + """ + + def __init__(self, model_name=["Student"], key=None, **kwargs): + super().__init__(**kwargs) + if not isinstance(model_name, list): + model_name = [model_name] + self.model_name = model_name + self.key = key + + def __call__(self, preds, *args, **kwargs): + output = dict() + for name in self.model_name: + pred = preds[name] + if self.key is not None: + pred = pred[self.key] + output[name] = super().__call__(pred, *args, **kwargs) + return output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_ser_layoutlm_postprocess.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_ser_layoutlm_postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..5541da90a05d0137628f45f72b15fd61eba1e203 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/postprocess/vqa_token_ser_layoutlm_postprocess.py @@ -0,0 +1,117 @@ +# Copyright (c) 2021 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. +import numpy as np +import paddle +from ppocr.utils.utility import load_vqa_bio_label_maps + + +class VQASerTokenLayoutLMPostProcess(object): + """ Convert between text-label and text-index """ + + def __init__(self, class_path, **kwargs): + super(VQASerTokenLayoutLMPostProcess, self).__init__() + label2id_map, self.id2label_map = load_vqa_bio_label_maps(class_path) + + self.label2id_map_for_draw = dict() + for key in label2id_map: + if key.startswith("I-"): + self.label2id_map_for_draw[key] = label2id_map["B" + key[1:]] + else: + self.label2id_map_for_draw[key] = label2id_map[key] + + self.id2label_map_for_show = dict() + for key in self.label2id_map_for_draw: + val = self.label2id_map_for_draw[key] + if key == "O": + self.id2label_map_for_show[val] = key + if key.startswith("B-") or key.startswith("I-"): + self.id2label_map_for_show[val] = key[2:] + else: + self.id2label_map_for_show[val] = key + + def __call__(self, preds, batch=None, *args, **kwargs): + if isinstance(preds, tuple): + preds = preds[0] + if isinstance(preds, paddle.Tensor): + preds = preds.numpy() + + if batch is not None: + return self._metric(preds, batch[5]) + else: + return self._infer(preds, **kwargs) + + def _metric(self, preds, label): + pred_idxs = preds.argmax(axis=2) + decode_out_list = [[] for _ in range(pred_idxs.shape[0])] + label_decode_out_list = [[] for _ in range(pred_idxs.shape[0])] + + for i in range(pred_idxs.shape[0]): + for j in range(pred_idxs.shape[1]): + if label[i, j] != -100: + label_decode_out_list[i].append(self.id2label_map[label[i, + j]]) + decode_out_list[i].append(self.id2label_map[pred_idxs[i, + j]]) + return decode_out_list, label_decode_out_list + + def _infer(self, preds, segment_offset_ids, ocr_infos): + results = [] + + for pred, segment_offset_id, ocr_info in zip(preds, segment_offset_ids, + ocr_infos): + pred = np.argmax(pred, axis=1) + pred = [self.id2label_map[idx] for idx in pred] + + for idx in range(len(segment_offset_id)): + if idx == 0: + start_id = 0 + else: + start_id = segment_offset_id[idx - 1] + + end_id = segment_offset_id[idx] + + curr_pred = pred[start_id:end_id] + curr_pred = [self.label2id_map_for_draw[p] for p in curr_pred] + + if len(curr_pred) <= 0: + pred_id = 0 + else: + counts = np.bincount(curr_pred) + pred_id = np.argmax(counts) + ocr_info[idx]["pred_id"] = int(pred_id) + ocr_info[idx]["pred"] = self.id2label_map_for_show[int(pred_id)] + results.append(ocr_info) + return results + + +class DistillationSerPostProcess(VQASerTokenLayoutLMPostProcess): + """ + DistillationSerPostProcess + """ + + def __init__(self, class_path, model_name=["Student"], key=None, **kwargs): + super().__init__(class_path, **kwargs) + if not isinstance(model_name, list): + model_name = [model_name] + self.model_name = model_name + self.key = key + + def __call__(self, preds, batch=None, *args, **kwargs): + output = dict() + for name in self.model_name: + pred = preds[name] + if self.key is not None: + pred = pred[self.key] + output[name] = super().__call__(pred, batch=batch, *args, **kwargs) + return output diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/EN_symbol_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/EN_symbol_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..1aef43d6b842731a54cbe682ccda5c2dbfa694d9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/EN_symbol_dict.txt @@ -0,0 +1,94 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +: +; +< += +> +? +@ +[ +\ +] +^ +_ +` +{ +| +} +~ \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/__init__.py new file mode 100755 index 0000000000000000000000000000000000000000..abf198b97e6e818e1fbe59006f98492640bcee54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ar_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ar_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc6380293eb51754b3d82a4b20ce4bdc297d56ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ar_dict.txt @@ -0,0 +1,117 @@ +a +r +b +i +c +_ +m +g +/ +1 +0 +I +L +S +V +R +C +2 +v +l +6 +3 +9 +. +j +p +ا +ل +م +ر +ج +و +ح +ي +ة +5 +8 +7 +أ +ب +ض +4 +ك +س +ه +ث +ن +ط +ع +ت +غ +خ +ف +ئ +ز +إ +د +ص +ظ +ذ +ش +ى +ق +ؤ +آ +ء +s +e +n +w +t +u +z +d +A +N +G +h +o +E +T +H +O +B +y +F +U +J +X +W +P +Z +M +k +q +Y +Q +D +f +K +x +' +% +- +# +@ +! +& +$ +, +: +é +? ++ +É +( + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/arabic_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/arabic_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..916d421c53bad563dfd980c1b64dcce07a3c9d24 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/arabic_dict.txt @@ -0,0 +1,161 @@ +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +ء +آ +أ +ؤ +إ +ئ +ا +ب +ة +ت +ث +ج +ح +خ +د +ذ +ر +ز +س +ش +ص +ض +ط +ظ +ع +غ +ف +ق +ك +ل +م +ن +ه +و +ى +ي +ً +ٌ +ٍ +َ +ُ +ِ +ّ +ْ +ٓ +ٔ +ٰ +ٱ +ٹ +پ +چ +ڈ +ڑ +ژ +ک +ڭ +گ +ں +ھ +ۀ +ہ +ۂ +ۃ +ۆ +ۇ +ۈ +ۋ +ی +ې +ے +ۓ +ە +١ +٢ +٣ +٤ +٥ +٦ +٧ +٨ +٩ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/be_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/be_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8458baaf2f1b1da82dc56bd259ca6fb3e887b89 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/be_dict.txt @@ -0,0 +1,145 @@ +b +e +_ +i +m +g +/ +2 +0 +I +L +S +V +R +C +1 +v +a +l +6 +9 +4 +3 +. +j +p +п +а +з +б +у +г +н +ц +ь +8 +м +л +і +о +ў +ы +7 +5 +М +х +с +р +ф +я +е +д +ж +ю +ч +й +к +Д +в +Б +т +І +ш +ё +э +К +Л +Н +А +Ж +Г +В +П +З +Е +О +Р +С +У +Ё +Й +Т +Ч +Э +Ц +Ю +Ш +Ф +Х +Я +Ь +Ы +Ў +s +c +n +w +M +o +t +T +E +A +B +u +h +y +k +r +H +d +Y +O +U +F +f +x +D +G +N +K +P +z +J +X +W +Z +Q +% +- +q +@ +' +! +# +& +, +: +$ +( +? +é ++ +É + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/bg_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/bg_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..84713c373b5df1f59d51bd9c505721d8ec239b98 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/bg_dict.txt @@ -0,0 +1,140 @@ +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +А +Б +В +Г +Д +Е +Ж +З +И +Й +К +Л +М +Н +О +П +Р +С +Т +У +Ф +Х +Ц +Ч +Ш +Щ +Ъ +Ю +Я +а +б +в +г +д +е +ж +з +и +й +к +л +м +н +о +п +р +с +т +у +ф +х +ц +ч +ш +щ +ъ +ь +ю +я + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/chinese_cht_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/chinese_cht_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..cc1aa4724b9a6f0e15275bcf61c91c26b6550c3e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/chinese_cht_dict.txt @@ -0,0 +1,8421 @@ +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +\ +] +^ +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +| +} +~ +¥ +® +° +± +² +´ +· +» +É +Ë +Ó +× +Ü +à +á +ä +è +é +ì +í +ò +ó +÷ +ú +ü +ā +ē +ī +ō +ū +ǐ +ǒ +ɔ +ɡ +ʌ +ˋ +Λ +Ο +Φ +Ω +α +β +ε +θ +μ +π +З +И +Й +П +Я +г +— +‖ +‘ +’ +“ +” +• +… +‧ +′ +″ +※ +℃ +№ +™ +Ⅱ +Ⅲ +Ⅳ +← +↑ +→ +↓ +⇋ +∈ +∑ +√ +∞ +∣ +∧ +∩ +∫ +∶ +≈ +≠ +≤ +≥ +⊙ +⊥ +① +② +③ +④ +⑧ +⑴ +⑵ +⑶ +─ +│ +┅ +┌ +├ +█ +▎ +▏ +▕ +■ +□ +▪ +▲ +△ +▼ +◆ +◇ +○ +◎ +● +◥ +★ +☆ +❋ +❤ +  +、 +。 +〇 +〉 +《 +》 +「 +」 +『 +』 +【 +】 +〔 +〕 +〖 +〗 +の +サ +シ +ジ +マ +ㄱ +ㆍ +㎏ +㎡ +㐂 +㐱 +㙟 +㴪 +㸃 +䖝 +䝉 +䰾 +䲁 +一 +丁 +七 +丄 +丈 +三 +上 +下 +丌 +不 +与 +丏 +丐 +丑 +且 +丕 +世 +丘 +丙 +丞 +丟 +両 +並 +丨 +丫 +中 +丰 +串 +丶 +丸 +丹 +主 +丼 +丿 +乂 +乃 +久 +么 +之 +乍 +乎 +乏 +乒 +乓 +乖 +乗 +乘 +乙 +乚 +乜 +九 +乞 +也 +乩 +乭 +乳 +乸 +乹 +乾 +亀 +亂 +亅 +了 +予 +亊 +事 +二 +亍 +云 +互 +亓 +五 +井 +亘 +些 +亜 +亞 +亟 +亠 +亡 +亢 +交 +亥 +亦 +亨 +享 +京 +亭 +亮 +亰 +亳 +亶 +亹 +人 +亻 +什 +仁 +仂 +仃 +仄 +仇 +仉 +今 +介 +仍 +仏 +仔 +仕 +他 +仗 +付 +仙 +仛 +仝 +仞 +仟 +仡 +代 +令 +以 +仨 +仫 +仮 +仰 +仲 +仳 +仵 +件 +仺 +任 +仼 +份 +仿 +企 +伃 +伈 +伉 +伊 +伋 +伍 +伎 +伏 +伐 +休 +伕 +伙 +伝 +伢 +伯 +估 +伱 +伴 +伶 +伷 +伸 +伺 +似 +伽 +伾 +佀 +佁 +佃 +但 +佇 +佈 +佉 +佋 +位 +低 +住 +佐 +佑 +体 +佔 +何 +佗 +佘 +余 +佚 +佛 +作 +佝 +佞 +佟 +你 +佣 +佤 +佧 +佩 +佬 +佯 +佰 +佳 +併 +佶 +佹 +佺 +佼 +佾 +使 +侁 +侃 +侄 +侅 +來 +侈 +侊 +例 +侍 +侏 +侑 +侖 +侗 +侘 +侚 +供 +依 +侞 +価 +侮 +侯 +侵 +侶 +侷 +侹 +便 +俁 +係 +促 +俄 +俅 +俊 +俋 +俌 +俍 +俎 +俏 +俐 +俑 +俗 +俘 +俚 +俛 +保 +俞 +俟 +俠 +信 +俬 +修 +俯 +俱 +俳 +俴 +俵 +俶 +俸 +俺 +俽 +俾 +倆 +倈 +倉 +個 +倌 +倍 +們 +倒 +倓 +倔 +倖 +倗 +倘 +候 +倚 +倜 +倞 +借 +倡 +倢 +倣 +値 +倦 +倧 +倩 +倪 +倫 +倬 +倭 +倮 +倻 +值 +偁 +偃 +假 +偈 +偉 +偊 +偌 +偍 +偎 +偏 +偓 +偕 +做 +停 +健 +偪 +偲 +側 +偵 +偶 +偷 +偸 +偽 +傀 +傃 +傅 +傈 +傉 +傍 +傑 +傒 +傕 +傖 +傘 +備 +傜 +傢 +傣 +催 +傭 +傲 +傳 +債 +傷 +傻 +傾 +僅 +僉 +僊 +働 +像 +僑 +僔 +僕 +僖 +僙 +僚 +僜 +僡 +僧 +僩 +僭 +僮 +僰 +僱 +僳 +僴 +僵 +價 +僻 +儀 +儁 +儂 +億 +儆 +儇 +儈 +儉 +儋 +儐 +儒 +儔 +儕 +儘 +儚 +儞 +償 +儡 +儥 +儦 +優 +儫 +儱 +儲 +儷 +儺 +儻 +儼 +兀 +允 +元 +兄 +充 +兆 +先 +光 +克 +兌 +免 +児 +兒 +兔 +兕 +兗 +兜 +入 +內 +全 +兩 +兪 +八 +公 +六 +兮 +共 +兵 +其 +具 +典 +兼 +兿 +冀 +冂 +円 +冇 +冉 +冊 +再 +冏 +冑 +冒 +冕 +冖 +冗 +冚 +冠 +冢 +冤 +冥 +冧 +冨 +冪 +冫 +冬 +冮 +冰 +冴 +冶 +冷 +冼 +冽 +凃 +凄 +准 +凈 +凋 +凌 +凍 +凖 +凜 +凝 +凞 +几 +凡 +処 +凪 +凬 +凰 +凱 +凳 +凵 +凶 +凸 +凹 +出 +函 +刀 +刁 +刂 +刃 +刄 +分 +切 +刈 +刊 +刎 +刑 +划 +列 +初 +判 +別 +刦 +刧 +刨 +利 +刪 +刮 +到 +制 +刷 +券 +刺 +刻 +刼 +剁 +剃 +則 +削 +剋 +剌 +前 +剎 +剏 +剔 +剖 +剛 +剝 +剡 +剣 +剩 +剪 +剮 +副 +割 +創 +剿 +劃 +劄 +劇 +劈 +劉 +劊 +劌 +劍 +劑 +劔 +力 +功 +加 +劣 +助 +努 +劫 +劬 +劭 +劵 +効 +劼 +劾 +勁 +勃 +勅 +勇 +勉 +勐 +勑 +勒 +勔 +動 +勖 +勗 +勘 +務 +勛 +勝 +勞 +募 +勢 +勣 +勤 +勦 +勰 +勱 +勲 +勳 +勵 +勷 +勸 +勺 +勻 +勾 +勿 +匂 +匄 +包 +匆 +匈 +匋 +匍 +匏 +匐 +匕 +化 +北 +匙 +匚 +匝 +匠 +匡 +匣 +匪 +匯 +匱 +匸 +匹 +匾 +匿 +區 +十 +千 +卅 +升 +午 +卉 +半 +卋 +卍 +卐 +卑 +卒 +卓 +協 +南 +博 +卜 +卞 +卟 +占 +卡 +卣 +卦 +卧 +卩 +卬 +卮 +卯 +印 +危 +卲 +即 +卵 +卷 +卸 +卹 +卺 +卻 +卽 +卿 +厄 +厓 +厔 +厙 +厚 +厝 +原 +厥 +厭 +厰 +厲 +厴 +厶 +去 +參 +叄 +又 +叉 +及 +友 +反 +収 +叔 +叕 +取 +受 +叛 +叟 +叡 +叢 +口 +古 +句 +另 +叨 +叩 +只 +叫 +召 +叭 +叮 +可 +台 +叱 +史 +右 +叵 +司 +叻 +叼 +吁 +吃 +各 +吆 +合 +吉 +吊 +吋 +同 +名 +后 +吏 +吐 +向 +吒 +吔 +吖 +君 +吝 +吞 +吟 +吠 +吡 +吥 +否 +吧 +吩 +含 +吮 +吱 +吲 +吳 +吵 +吶 +吸 +吹 +吻 +吼 +吾 +呀 +呂 +呃 +呈 +呉 +告 +呋 +呎 +呢 +呤 +呦 +周 +呱 +味 +呵 +呷 +呸 +呼 +命 +呾 +咀 +咁 +咂 +咄 +咅 +咆 +咋 +和 +咎 +咑 +咒 +咔 +咕 +咖 +咗 +咘 +咚 +咟 +咤 +咥 +咧 +咨 +咩 +咪 +咫 +咬 +咭 +咯 +咱 +咲 +咳 +咸 +咻 +咼 +咽 +咾 +咿 +哀 +品 +哂 +哄 +哆 +哇 +哈 +哉 +哌 +哎 +哏 +哐 +哖 +哚 +哞 +員 +哥 +哦 +哨 +哩 +哪 +哭 +哮 +哱 +哲 +哺 +哼 +唃 +唄 +唆 +唇 +唉 +唏 +唐 +唑 +唔 +唘 +唧 +唫 +唬 +唭 +售 +唯 +唱 +唳 +唵 +唷 +唸 +唻 +唾 +啁 +啃 +啄 +商 +啉 +啊 +啍 +問 +啓 +啖 +啚 +啜 +啞 +啟 +啡 +啣 +啤 +啥 +啦 +啪 +啫 +啯 +啰 +啱 +啲 +啵 +啶 +啷 +啻 +啼 +啾 +喀 +喂 +喃 +善 +喆 +喇 +喈 +喉 +喊 +喋 +喏 +喔 +喘 +喙 +喚 +喜 +喝 +喢 +喦 +喧 +喪 +喫 +喬 +單 +喰 +喱 +喲 +喳 +喵 +喹 +喻 +喼 +嗄 +嗅 +嗆 +嗇 +嗊 +嗎 +嗑 +嗒 +嗓 +嗔 +嗖 +嗚 +嗜 +嗝 +嗞 +嗡 +嗢 +嗣 +嗦 +嗨 +嗩 +嗪 +嗮 +嗯 +嗲 +嗶 +嗹 +嗽 +嘀 +嘅 +嘆 +嘉 +嘌 +嘍 +嘎 +嘏 +嘔 +嘗 +嘚 +嘛 +嘜 +嘞 +嘟 +嘢 +嘣 +嘥 +嘧 +嘩 +嘬 +嘮 +嘯 +嘰 +嘲 +嘴 +嘶 +嘸 +嘹 +嘻 +嘿 +噁 +噌 +噍 +噏 +噓 +噗 +噝 +噠 +噢 +噤 +噥 +噦 +器 +噩 +噪 +噬 +噯 +噰 +噲 +噴 +噶 +噸 +噹 +噻 +嚇 +嚈 +嚎 +嚏 +嚐 +嚒 +嚓 +嚕 +嚗 +嚙 +嚞 +嚟 +嚤 +嚦 +嚧 +嚨 +嚩 +嚮 +嚳 +嚴 +嚶 +嚷 +嚼 +嚿 +囀 +囂 +囃 +囉 +囊 +囍 +囑 +囒 +囓 +囗 +囚 +四 +囝 +回 +因 +囡 +団 +囤 +囧 +囪 +囮 +囯 +困 +囲 +図 +囶 +囷 +囹 +固 +囿 +圂 +圃 +圄 +圈 +圉 +國 +圍 +圏 +園 +圓 +圖 +圗 +團 +圜 +土 +圧 +在 +圩 +圪 +圭 +圯 +地 +圳 +圻 +圾 +址 +均 +坊 +坋 +坌 +坍 +坎 +坐 +坑 +坖 +坡 +坣 +坤 +坦 +坨 +坩 +坪 +坫 +坬 +坭 +坮 +坯 +坳 +坵 +坶 +坷 +坻 +垂 +垃 +垈 +型 +垍 +垓 +垕 +垚 +垛 +垞 +垟 +垠 +垢 +垣 +垮 +垯 +垰 +垵 +垸 +垻 +垿 +埃 +埅 +埇 +埈 +埋 +埌 +城 +埏 +埒 +埔 +埕 +埗 +埜 +域 +埠 +埡 +埤 +埧 +埨 +埪 +埭 +埮 +埴 +埵 +執 +培 +基 +埻 +埼 +堀 +堂 +堃 +堅 +堆 +堇 +堈 +堉 +堊 +堍 +堖 +堝 +堡 +堤 +堦 +堪 +堮 +堯 +堰 +報 +場 +堵 +堷 +堺 +塀 +塅 +塆 +塊 +塋 +塌 +塍 +塏 +塑 +塔 +塗 +塘 +塙 +塜 +塞 +塡 +塢 +塤 +塨 +塩 +填 +塬 +塭 +塰 +塱 +塲 +塵 +塹 +塽 +塾 +墀 +境 +墅 +墉 +墊 +墎 +墓 +増 +墘 +墜 +增 +墟 +墡 +墣 +墨 +墩 +墫 +墬 +墮 +墱 +墳 +墺 +墼 +墾 +壁 +壄 +壆 +壇 +壋 +壌 +壎 +壐 +壑 +壓 +壔 +壕 +壘 +壙 +壞 +壟 +壠 +壢 +壤 +壩 +士 +壬 +壯 +壱 +壴 +壹 +壺 +壽 +夀 +夆 +変 +夊 +夋 +夌 +夏 +夔 +夕 +外 +夙 +多 +夜 +夠 +夢 +夤 +夥 +大 +天 +太 +夫 +夬 +夭 +央 +夯 +失 +夷 +夾 +奀 +奄 +奇 +奈 +奉 +奎 +奏 +奐 +契 +奓 +奔 +奕 +套 +奘 +奚 +奠 +奢 +奣 +奧 +奩 +奪 +奫 +奭 +奮 +女 +奴 +奶 +她 +好 +妀 +妁 +如 +妃 +妄 +妊 +妍 +妏 +妑 +妒 +妓 +妖 +妙 +妝 +妞 +妠 +妤 +妥 +妧 +妨 +妭 +妮 +妯 +妲 +妳 +妸 +妹 +妺 +妻 +妾 +姀 +姁 +姃 +姆 +姈 +姉 +姊 +始 +姌 +姍 +姐 +姑 +姒 +姓 +委 +姚 +姜 +姝 +姣 +姥 +姦 +姨 +姪 +姫 +姬 +姮 +姵 +姶 +姸 +姻 +姿 +威 +娃 +娉 +娋 +娌 +娍 +娎 +娑 +娖 +娘 +娛 +娜 +娟 +娠 +娣 +娥 +娩 +娫 +娳 +娶 +娸 +娼 +娽 +婀 +婁 +婆 +婉 +婊 +婑 +婕 +婚 +婢 +婦 +婧 +婪 +婭 +婯 +婷 +婺 +婻 +婼 +婿 +媃 +媄 +媊 +媐 +媒 +媓 +媖 +媗 +媚 +媛 +媜 +媞 +媧 +媭 +媯 +媲 +媳 +媺 +媼 +媽 +媾 +媿 +嫁 +嫂 +嫄 +嫈 +嫉 +嫌 +嫖 +嫘 +嫚 +嫡 +嫣 +嫦 +嫩 +嫪 +嫲 +嫳 +嫵 +嫺 +嫻 +嬅 +嬈 +嬉 +嬋 +嬌 +嬗 +嬛 +嬝 +嬡 +嬤 +嬨 +嬪 +嬬 +嬭 +嬰 +嬴 +嬸 +嬾 +嬿 +孀 +孃 +孆 +孋 +孌 +子 +孑 +孔 +孕 +孖 +字 +存 +孚 +孛 +孜 +孝 +孟 +孢 +季 +孤 +孩 +孫 +孬 +孮 +孰 +孳 +孵 +學 +孺 +孻 +孽 +孿 +宀 +它 +宅 +宇 +守 +安 +宋 +完 +宍 +宏 +宓 +宕 +宗 +官 +宙 +定 +宛 +宜 +実 +客 +宣 +室 +宥 +宦 +宧 +宮 +宰 +害 +宴 +宵 +家 +宸 +容 +宿 +寀 +寁 +寂 +寄 +寅 +密 +寇 +寈 +寊 +富 +寐 +寒 +寓 +寔 +寕 +寖 +寗 +寘 +寛 +寜 +寞 +察 +寡 +寢 +寤 +寥 +實 +寧 +寨 +審 +寫 +寬 +寮 +寯 +寰 +寳 +寵 +寶 +寸 +寺 +対 +封 +専 +尃 +射 +將 +專 +尉 +尊 +尋 +對 +導 +小 +尐 +少 +尓 +尕 +尖 +尗 +尙 +尚 +尢 +尤 +尨 +尪 +尬 +就 +尷 +尹 +尺 +尻 +尼 +尾 +尿 +局 +屁 +屄 +居 +屆 +屇 +屈 +屋 +屌 +屍 +屎 +屏 +屐 +屑 +屓 +展 +屚 +屜 +屠 +屢 +層 +履 +屬 +屭 +屯 +山 +屹 +屺 +屻 +岀 +岈 +岌 +岐 +岑 +岔 +岡 +岢 +岣 +岧 +岩 +岪 +岫 +岬 +岰 +岱 +岳 +岵 +岷 +岸 +岻 +峁 +峅 +峇 +峋 +峍 +峒 +峘 +峙 +峚 +峠 +峨 +峩 +峪 +峭 +峯 +峰 +峴 +島 +峻 +峼 +峽 +崁 +崆 +崇 +崈 +崋 +崍 +崎 +崐 +崑 +崒 +崔 +崖 +崗 +崘 +崙 +崚 +崛 +崞 +崟 +崠 +崢 +崤 +崧 +崩 +崬 +崮 +崱 +崴 +崵 +崶 +崽 +嵇 +嵊 +嵋 +嵌 +嵎 +嵐 +嵒 +嵕 +嵖 +嵗 +嵙 +嵛 +嵜 +嵨 +嵩 +嵬 +嵮 +嵯 +嵰 +嵴 +嵻 +嵿 +嶁 +嶂 +嶃 +嶄 +嶇 +嶋 +嶌 +嶍 +嶒 +嶔 +嶗 +嶝 +嶠 +嶢 +嶦 +嶧 +嶪 +嶬 +嶰 +嶲 +嶴 +嶷 +嶸 +嶺 +嶼 +嶽 +巂 +巄 +巆 +巋 +巌 +巍 +巎 +巑 +巒 +巔 +巖 +巘 +巛 +川 +州 +巡 +巢 +工 +左 +巧 +巨 +巫 +差 +巰 +己 +已 +巳 +巴 +巶 +巷 +巻 +巽 +巾 +巿 +市 +布 +帆 +希 +帑 +帔 +帕 +帖 +帘 +帙 +帚 +帛 +帝 +帡 +帢 +帥 +師 +席 +帯 +帰 +帳 +帶 +帷 +常 +帽 +幀 +幃 +幄 +幅 +幌 +幔 +幕 +幗 +幚 +幛 +幟 +幡 +幢 +幣 +幪 +幫 +干 +平 +年 +幵 +幷 +幸 +幹 +幺 +幻 +幼 +幽 +幾 +庀 +庁 +広 +庇 +床 +序 +底 +庖 +店 +庚 +府 +庠 +庢 +庥 +度 +座 +庫 +庭 +庲 +庵 +庶 +康 +庸 +庹 +庼 +庾 +廁 +廂 +廄 +廆 +廈 +廉 +廊 +廋 +廌 +廍 +廑 +廓 +廔 +廕 +廖 +廙 +廚 +廝 +廞 +廟 +廠 +廡 +廢 +廣 +廧 +廨 +廩 +廬 +廰 +廱 +廳 +延 +廷 +廸 +建 +廻 +廼 +廿 +弁 +弄 +弅 +弇 +弈 +弉 +弊 +弋 +弍 +式 +弐 +弒 +弓 +弔 +引 +弖 +弗 +弘 +弛 +弟 +弢 +弦 +弧 +弨 +弩 +弭 +弱 +張 +強 +弸 +弼 +弾 +彀 +彄 +彅 +彆 +彈 +彊 +彌 +彎 +彐 +彔 +彖 +彗 +彘 +彙 +彜 +彞 +彠 +彡 +形 +彣 +彤 +彥 +彧 +彩 +彪 +彫 +彬 +彭 +彰 +影 +彳 +彷 +役 +彼 +彿 +往 +征 +徂 +待 +徇 +很 +徉 +徊 +律 +後 +徐 +徑 +徒 +得 +徘 +徙 +徜 +從 +徠 +御 +徧 +徨 +復 +循 +徫 +徬 +徭 +微 +徳 +徴 +徵 +德 +徸 +徹 +徽 +心 +忄 +必 +忉 +忌 +忍 +忐 +忑 +忒 +志 +忘 +忙 +応 +忝 +忞 +忠 +快 +忬 +忯 +忱 +忳 +念 +忻 +忽 +忿 +怍 +怎 +怒 +怕 +怖 +怙 +怛 +思 +怠 +怡 +急 +怦 +性 +怨 +怪 +怯 +怵 +恁 +恂 +恃 +恆 +恊 +恍 +恐 +恕 +恙 +恢 +恣 +恤 +恥 +恨 +恩 +恪 +恬 +恭 +息 +恰 +恵 +恿 +悄 +悅 +悆 +悉 +悌 +悍 +悔 +悖 +悚 +悛 +悝 +悞 +悟 +悠 +患 +悧 +您 +悪 +悰 +悲 +悳 +悵 +悶 +悸 +悼 +情 +惆 +惇 +惑 +惔 +惕 +惘 +惚 +惜 +惟 +惠 +惡 +惣 +惦 +惰 +惱 +惲 +想 +惶 +惹 +惺 +愁 +愃 +愆 +愈 +愉 +愍 +意 +愐 +愒 +愔 +愕 +愚 +愛 +愜 +感 +愣 +愧 +愨 +愫 +愭 +愴 +愷 +愼 +愾 +愿 +慄 +慈 +態 +慌 +慎 +慕 +慘 +慚 +慜 +慟 +慢 +慣 +慥 +慧 +慨 +慮 +慰 +慳 +慵 +慶 +慷 +慾 +憂 +憊 +憋 +憍 +憎 +憐 +憑 +憓 +憕 +憙 +憚 +憤 +憧 +憨 +憩 +憫 +憬 +憲 +憶 +憺 +憻 +憾 +懂 +懃 +懇 +懈 +應 +懋 +懌 +懍 +懐 +懣 +懦 +懮 +懲 +懵 +懶 +懷 +懸 +懺 +懼 +懽 +懾 +懿 +戀 +戇 +戈 +戊 +戌 +戍 +戎 +成 +我 +戒 +戔 +戕 +或 +戙 +戚 +戛 +戟 +戡 +戢 +戥 +戦 +戩 +截 +戮 +戰 +戱 +戲 +戳 +戴 +戶 +戸 +戻 +戽 +戾 +房 +所 +扁 +扆 +扇 +扈 +扉 +手 +扌 +才 +扎 +扒 +打 +扔 +托 +扙 +扛 +扞 +扣 +扥 +扦 +扭 +扮 +扯 +扳 +扶 +批 +扼 +找 +承 +技 +抃 +抄 +抇 +抉 +把 +抑 +抒 +抓 +投 +抖 +抗 +折 +抦 +披 +抬 +抱 +抵 +抹 +抻 +押 +抽 +抿 +拂 +拆 +拇 +拈 +拉 +拋 +拌 +拍 +拎 +拏 +拐 +拒 +拓 +拔 +拖 +拗 +拘 +拙 +拚 +招 +拜 +拝 +拡 +括 +拭 +拮 +拯 +拱 +拳 +拴 +拷 +拺 +拼 +拽 +拾 +拿 +持 +指 +按 +挎 +挑 +挖 +挙 +挨 +挪 +挫 +振 +挲 +挵 +挹 +挺 +挻 +挾 +捂 +捆 +捉 +捌 +捍 +捎 +捏 +捐 +捒 +捕 +捜 +捦 +捧 +捨 +捩 +捫 +捭 +捱 +捲 +捶 +捷 +捺 +捻 +掀 +掂 +掃 +掄 +掇 +授 +掉 +掌 +掏 +掐 +排 +掖 +掘 +掙 +掛 +掞 +掟 +掠 +採 +探 +掣 +接 +控 +推 +掩 +措 +掬 +掰 +掾 +揀 +揄 +揆 +揉 +揍 +描 +提 +插 +揔 +揖 +揚 +換 +握 +揪 +揭 +揮 +援 +揸 +揺 +損 +搏 +搐 +搓 +搔 +搖 +搗 +搜 +搞 +搠 +搢 +搪 +搬 +搭 +搳 +搴 +搵 +搶 +搽 +搾 +摂 +摒 +摔 +摘 +摜 +摞 +摟 +摠 +摧 +摩 +摭 +摯 +摳 +摴 +摵 +摶 +摸 +摹 +摺 +摻 +摽 +撃 +撇 +撈 +撐 +撒 +撓 +撕 +撖 +撙 +撚 +撞 +撣 +撤 +撥 +撩 +撫 +撬 +播 +撮 +撰 +撲 +撳 +撻 +撼 +撾 +撿 +擀 +擁 +擂 +擅 +擇 +擊 +擋 +操 +擎 +擒 +擔 +擘 +據 +擠 +擢 +擥 +擦 +擬 +擯 +擰 +擱 +擲 +擴 +擷 +擺 +擼 +擾 +攀 +攏 +攔 +攖 +攘 +攜 +攝 +攞 +攢 +攣 +攤 +攪 +攫 +攬 +支 +攴 +攵 +收 +攷 +攸 +改 +攻 +攽 +放 +政 +故 +效 +敍 +敎 +敏 +救 +敔 +敕 +敖 +敗 +敘 +教 +敝 +敞 +敟 +敢 +散 +敦 +敫 +敬 +敭 +敲 +整 +敵 +敷 +數 +敻 +敾 +斂 +斃 +文 +斌 +斎 +斐 +斑 +斕 +斖 +斗 +料 +斛 +斜 +斝 +斟 +斡 +斤 +斥 +斧 +斬 +斯 +新 +斷 +方 +於 +施 +斿 +旁 +旂 +旃 +旄 +旅 +旉 +旋 +旌 +旎 +族 +旖 +旗 +旙 +旛 +旡 +既 +日 +旦 +旨 +早 +旬 +旭 +旱 +旲 +旳 +旺 +旻 +旼 +旽 +旾 +旿 +昀 +昂 +昃 +昆 +昇 +昉 +昊 +昌 +昍 +明 +昏 +昐 +易 +昔 +昕 +昚 +昛 +昜 +昝 +昞 +星 +映 +昡 +昣 +昤 +春 +昧 +昨 +昪 +昫 +昭 +是 +昰 +昱 +昴 +昵 +昶 +昺 +晁 +時 +晃 +晈 +晉 +晊 +晏 +晗 +晙 +晚 +晛 +晝 +晞 +晟 +晤 +晦 +晧 +晨 +晩 +晪 +晫 +晭 +普 +景 +晰 +晳 +晴 +晶 +晷 +晸 +智 +晾 +暃 +暄 +暅 +暇 +暈 +暉 +暊 +暌 +暎 +暏 +暐 +暑 +暕 +暖 +暗 +暘 +暝 +暟 +暠 +暢 +暦 +暨 +暫 +暮 +暱 +暲 +暴 +暸 +暹 +暻 +暾 +曄 +曅 +曆 +曇 +曉 +曌 +曔 +曖 +曙 +曜 +曝 +曠 +曦 +曧 +曨 +曩 +曬 +曮 +曰 +曲 +曳 +更 +曶 +曷 +書 +曹 +曺 +曼 +曽 +曾 +替 +最 +會 +月 +有 +朊 +朋 +服 +朏 +朐 +朓 +朔 +朕 +朖 +朗 +望 +朝 +期 +朦 +朧 +木 +未 +末 +本 +札 +朱 +朴 +朵 +朶 +朽 +朿 +杁 +杉 +杋 +杌 +李 +杏 +材 +村 +杓 +杖 +杙 +杜 +杞 +束 +杠 +杣 +杤 +杧 +杬 +杭 +杯 +東 +杲 +杳 +杴 +杵 +杷 +杻 +杼 +松 +板 +极 +枇 +枉 +枋 +枏 +析 +枕 +枖 +林 +枚 +枛 +果 +枝 +枠 +枡 +枯 +枰 +枱 +枲 +枳 +架 +枷 +枸 +枹 +枼 +柁 +柃 +柄 +柉 +柊 +柎 +柏 +某 +柑 +柒 +染 +柔 +柘 +柚 +柜 +柝 +柞 +柟 +查 +柩 +柬 +柯 +柰 +柱 +柳 +柴 +柵 +柶 +柷 +査 +柾 +柿 +栃 +栄 +栐 +栒 +栓 +栜 +栝 +栞 +校 +栢 +栨 +栩 +株 +栲 +栴 +核 +根 +栻 +格 +栽 +桀 +桁 +桂 +桃 +桄 +桅 +框 +案 +桉 +桌 +桎 +桐 +桑 +桓 +桔 +桕 +桖 +桙 +桜 +桝 +桫 +桱 +桲 +桴 +桶 +桷 +桼 +桿 +梀 +梁 +梂 +梃 +梅 +梆 +梉 +梏 +梓 +梔 +梗 +梘 +條 +梟 +梠 +梢 +梣 +梧 +梨 +梫 +梭 +梯 +械 +梱 +梳 +梵 +梶 +梽 +棄 +棆 +棉 +棋 +棍 +棐 +棒 +棓 +棕 +棖 +棗 +棘 +棚 +棛 +棟 +棠 +棡 +棣 +棧 +棨 +棩 +棪 +棫 +森 +棱 +棲 +棵 +棶 +棹 +棺 +棻 +棼 +棽 +椅 +椆 +椇 +椋 +植 +椎 +椏 +椒 +椙 +椥 +椪 +椰 +椲 +椴 +椵 +椹 +椽 +椿 +楂 +楊 +楓 +楔 +楗 +楙 +楚 +楝 +楞 +楠 +楡 +楢 +楣 +楤 +楦 +楧 +楨 +楫 +業 +楮 +楯 +楳 +極 +楷 +楸 +楹 +楽 +楿 +概 +榆 +榊 +榍 +榎 +榑 +榔 +榕 +榖 +榗 +榘 +榛 +榜 +榞 +榢 +榣 +榤 +榦 +榧 +榨 +榫 +榭 +榮 +榲 +榴 +榷 +榻 +榿 +槀 +槁 +槃 +槊 +構 +槌 +槍 +槎 +槐 +槓 +槔 +槗 +様 +槙 +槤 +槩 +槭 +槰 +槱 +槲 +槳 +槺 +槻 +槼 +槽 +槿 +樀 +樁 +樂 +樅 +樆 +樊 +樋 +樑 +樓 +樗 +樘 +標 +樞 +樟 +模 +樣 +樨 +権 +樫 +樵 +樸 +樹 +樺 +樻 +樽 +樾 +橄 +橇 +橈 +橋 +橐 +橒 +橓 +橘 +橙 +橚 +機 +橡 +橢 +橪 +橫 +橿 +檀 +檄 +檇 +檉 +檊 +檎 +檐 +檔 +檗 +檜 +檞 +檠 +檡 +檢 +檣 +檦 +檨 +檫 +檬 +檯 +檳 +檵 +檸 +檻 +檽 +櫂 +櫃 +櫆 +櫈 +櫓 +櫚 +櫛 +櫞 +櫟 +櫥 +櫨 +櫪 +櫱 +櫸 +櫻 +櫾 +櫿 +欄 +欉 +權 +欏 +欒 +欖 +欞 +欠 +次 +欣 +欥 +欲 +欸 +欹 +欺 +欽 +款 +歆 +歇 +歉 +歊 +歌 +歎 +歐 +歓 +歙 +歛 +歡 +止 +正 +此 +步 +武 +歧 +歩 +歪 +歲 +歳 +歴 +歷 +歸 +歹 +死 +歿 +殂 +殃 +殄 +殆 +殉 +殊 +殑 +殖 +殘 +殛 +殞 +殟 +殤 +殭 +殮 +殯 +殲 +殳 +段 +殷 +殺 +殻 +殼 +殿 +毀 +毅 +毆 +毉 +毋 +毌 +母 +毎 +每 +毐 +毒 +毓 +比 +毖 +毗 +毘 +毛 +毫 +毬 +毯 +毴 +毸 +毽 +毿 +氂 +氈 +氍 +氏 +氐 +民 +氓 +氖 +気 +氘 +氙 +氚 +氛 +氟 +氣 +氦 +氧 +氨 +氪 +氫 +氬 +氮 +氯 +氰 +水 +氵 +氷 +永 +氹 +氻 +氽 +氾 +汀 +汁 +求 +汊 +汎 +汐 +汕 +汗 +汛 +汜 +汝 +汞 +江 +池 +污 +汧 +汨 +汩 +汪 +汭 +汰 +汲 +汴 +汶 +決 +汽 +汾 +沁 +沂 +沃 +沄 +沅 +沆 +沇 +沈 +沉 +沌 +沍 +沏 +沐 +沒 +沓 +沔 +沖 +沘 +沙 +沚 +沛 +沜 +沢 +沨 +沫 +沭 +沮 +沯 +沱 +河 +沸 +油 +沺 +治 +沼 +沽 +沾 +沿 +況 +泂 +泄 +泆 +泇 +泉 +泊 +泌 +泐 +泓 +泔 +法 +泖 +泗 +泚 +泛 +泠 +泡 +波 +泣 +泥 +泩 +泫 +泮 +泯 +泰 +泱 +泳 +泵 +洄 +洋 +洌 +洎 +洗 +洙 +洛 +洞 +洢 +洣 +洤 +津 +洨 +洩 +洪 +洮 +洱 +洲 +洳 +洵 +洸 +洹 +洺 +活 +洽 +派 +流 +浄 +浙 +浚 +浛 +浜 +浞 +浟 +浠 +浡 +浣 +浤 +浥 +浦 +浩 +浪 +浮 +浯 +浴 +浵 +海 +浸 +浹 +涅 +涇 +消 +涉 +涌 +涎 +涑 +涓 +涔 +涕 +涙 +涪 +涫 +涮 +涯 +液 +涵 +涸 +涼 +涿 +淄 +淅 +淆 +淇 +淋 +淌 +淍 +淎 +淏 +淑 +淓 +淖 +淘 +淙 +淚 +淛 +淝 +淞 +淠 +淡 +淤 +淥 +淦 +淨 +淩 +淪 +淫 +淬 +淮 +淯 +淰 +深 +淳 +淵 +淶 +混 +淸 +淹 +淺 +添 +淼 +淽 +渃 +清 +済 +渉 +渋 +渕 +渙 +渚 +減 +渝 +渟 +渠 +渡 +渣 +渤 +渥 +渦 +渫 +測 +渭 +港 +渲 +渴 +游 +渺 +渼 +渽 +渾 +湃 +湄 +湉 +湊 +湍 +湓 +湔 +湖 +湘 +湛 +湜 +湞 +湟 +湣 +湥 +湧 +湫 +湮 +湯 +湳 +湴 +湼 +満 +溁 +溇 +溈 +溉 +溋 +溎 +溏 +源 +準 +溙 +溜 +溝 +溟 +溢 +溥 +溦 +溧 +溪 +溫 +溯 +溱 +溲 +溴 +溵 +溶 +溺 +溼 +滀 +滁 +滂 +滄 +滅 +滇 +滈 +滉 +滋 +滌 +滎 +滏 +滑 +滓 +滔 +滕 +滘 +滙 +滝 +滬 +滯 +滲 +滴 +滷 +滸 +滹 +滻 +滽 +滾 +滿 +漁 +漂 +漆 +漇 +漈 +漎 +漏 +漓 +演 +漕 +漚 +漠 +漢 +漣 +漩 +漪 +漫 +漬 +漯 +漱 +漲 +漳 +漴 +漵 +漷 +漸 +漼 +漾 +漿 +潁 +潑 +潔 +潘 +潛 +潞 +潟 +潢 +潤 +潭 +潮 +潯 +潰 +潲 +潺 +潼 +潽 +潾 +潿 +澀 +澁 +澂 +澄 +澆 +澇 +澈 +澉 +澋 +澌 +澍 +澎 +澔 +澗 +澠 +澡 +澣 +澤 +澥 +澧 +澪 +澮 +澯 +澱 +澳 +澶 +澹 +澻 +激 +濁 +濂 +濃 +濉 +濊 +濋 +濕 +濘 +濙 +濛 +濞 +濟 +濠 +濡 +濤 +濫 +濬 +濮 +濯 +濰 +濱 +濲 +濶 +濺 +濼 +濾 +瀁 +瀅 +瀆 +瀉 +瀍 +瀏 +瀑 +瀔 +瀕 +瀘 +瀚 +瀛 +瀝 +瀞 +瀟 +瀠 +瀣 +瀦 +瀧 +瀨 +瀬 +瀰 +瀲 +瀴 +瀶 +瀹 +瀾 +灃 +灊 +灌 +灑 +灘 +灝 +灞 +灡 +灣 +灤 +灧 +火 +灰 +灴 +灸 +灼 +災 +炁 +炅 +炆 +炊 +炎 +炒 +炔 +炕 +炘 +炙 +炟 +炣 +炤 +炫 +炬 +炭 +炮 +炯 +炱 +炲 +炳 +炷 +炸 +為 +炻 +烈 +烉 +烊 +烋 +烏 +烒 +烔 +烘 +烙 +烜 +烝 +烤 +烯 +烱 +烴 +烷 +烹 +烺 +烽 +焃 +焄 +焉 +焊 +焌 +焓 +焗 +焙 +焚 +焜 +焞 +無 +焦 +焯 +焰 +焱 +焴 +然 +焻 +焼 +焿 +煇 +煉 +煊 +煌 +煎 +煐 +煒 +煔 +煕 +煖 +煙 +煚 +煜 +煞 +煠 +煤 +煥 +煦 +照 +煨 +煩 +煬 +煮 +煲 +煳 +煵 +煶 +煸 +煽 +熄 +熅 +熇 +熈 +熊 +熏 +熒 +熔 +熖 +熗 +熘 +熙 +熜 +熟 +熠 +熤 +熥 +熨 +熬 +熯 +熱 +熲 +熳 +熵 +熹 +熺 +熼 +熾 +熿 +燁 +燃 +燄 +燈 +燉 +燊 +燎 +燏 +燐 +燒 +燔 +燕 +燘 +燙 +燚 +燜 +燝 +營 +燥 +燦 +燧 +燫 +燬 +燭 +燮 +燴 +燹 +燻 +燼 +燾 +燿 +爀 +爆 +爌 +爍 +爐 +爔 +爚 +爛 +爝 +爨 +爪 +爬 +爭 +爯 +爰 +爲 +爵 +父 +爸 +爹 +爺 +爻 +爽 +爾 +爿 +牁 +牂 +牆 +片 +版 +牌 +牒 +牕 +牖 +牘 +牙 +牛 +牝 +牟 +牠 +牡 +牢 +牧 +物 +牯 +牲 +特 +牻 +牼 +牽 +犀 +犁 +犂 +犇 +犍 +犎 +犖 +犛 +犢 +犧 +犨 +犬 +犯 +犰 +犴 +犽 +狀 +狂 +狄 +狍 +狎 +狐 +狒 +狓 +狗 +狙 +狛 +狟 +狠 +狡 +狦 +狨 +狩 +狳 +狶 +狷 +狸 +狹 +狻 +狼 +猁 +猄 +猇 +猊 +猗 +猙 +猛 +猜 +猝 +猞 +猢 +猥 +猨 +猩 +猳 +猴 +猶 +猷 +猺 +猻 +猾 +猿 +獁 +獃 +獄 +獅 +獇 +獎 +獏 +獐 +獒 +獠 +獢 +獣 +獨 +獬 +獮 +獯 +獰 +獲 +獴 +獵 +獷 +獸 +獺 +獻 +獼 +獾 +玀 +玄 +玆 +率 +玉 +王 +玎 +玏 +玓 +玕 +玖 +玗 +玘 +玙 +玟 +玠 +玡 +玢 +玥 +玧 +玨 +玩 +玫 +玭 +玲 +玳 +玶 +玷 +玹 +玻 +玾 +珀 +珂 +珅 +珈 +珉 +珊 +珌 +珍 +珎 +珏 +珖 +珙 +珝 +珞 +珠 +珡 +珣 +珤 +珥 +珦 +珧 +珩 +珪 +班 +珮 +珵 +珹 +珺 +珽 +現 +琁 +球 +琄 +琅 +理 +琇 +琉 +琊 +琍 +琎 +琚 +琛 +琡 +琢 +琤 +琥 +琦 +琨 +琪 +琬 +琮 +琯 +琰 +琱 +琳 +琴 +琵 +琶 +琹 +琺 +琿 +瑀 +瑁 +瑂 +瑄 +瑅 +瑆 +瑈 +瑊 +瑋 +瑑 +瑒 +瑕 +瑗 +瑙 +瑚 +瑛 +瑜 +瑝 +瑞 +瑟 +瑠 +瑢 +瑣 +瑤 +瑥 +瑧 +瑨 +瑩 +瑪 +瑭 +瑯 +瑰 +瑱 +瑳 +瑴 +瑺 +瑾 +璀 +璁 +璃 +璄 +璆 +璇 +璈 +璉 +璋 +璌 +璐 +璕 +璘 +璙 +璚 +璜 +璞 +璟 +璠 +璡 +璣 +璥 +璦 +璧 +璨 +璩 +璪 +璫 +璬 +璮 +環 +璱 +璵 +璸 +璹 +璽 +璿 +瓈 +瓊 +瓌 +瓏 +瓑 +瓔 +瓖 +瓘 +瓚 +瓛 +瓜 +瓞 +瓠 +瓢 +瓣 +瓤 +瓦 +瓮 +瓴 +瓶 +瓷 +瓿 +甂 +甄 +甌 +甍 +甑 +甕 +甘 +甙 +甚 +甜 +生 +甡 +產 +産 +甥 +甦 +用 +甩 +甪 +甫 +甬 +甯 +田 +由 +甲 +申 +男 +甸 +甹 +町 +甾 +畀 +畇 +畈 +畊 +畋 +界 +畎 +畏 +畐 +畑 +畔 +留 +畜 +畝 +畠 +畢 +略 +畦 +畧 +番 +畫 +畬 +畯 +異 +畲 +畳 +畵 +當 +畷 +畸 +畹 +畿 +疃 +疆 +疇 +疊 +疋 +疌 +疍 +疏 +疑 +疒 +疕 +疙 +疚 +疝 +疣 +疤 +疥 +疫 +疲 +疳 +疵 +疸 +疹 +疼 +疽 +疾 +痂 +病 +症 +痊 +痍 +痔 +痕 +痘 +痙 +痛 +痞 +痟 +痠 +痢 +痣 +痤 +痧 +痩 +痰 +痱 +痲 +痴 +痹 +痺 +痿 +瘀 +瘁 +瘊 +瘋 +瘍 +瘓 +瘙 +瘜 +瘞 +瘟 +瘠 +瘡 +瘢 +瘤 +瘦 +瘧 +瘩 +瘰 +瘴 +瘺 +癀 +療 +癆 +癇 +癌 +癒 +癖 +癘 +癜 +癟 +癡 +癢 +癤 +癥 +癩 +癬 +癭 +癮 +癯 +癰 +癱 +癲 +癸 +発 +登 +發 +白 +百 +皂 +的 +皆 +皇 +皈 +皋 +皎 +皐 +皓 +皖 +皙 +皚 +皛 +皝 +皞 +皮 +皰 +皴 +皷 +皸 +皺 +皿 +盂 +盃 +盅 +盆 +盈 +益 +盋 +盌 +盎 +盒 +盔 +盛 +盜 +盞 +盟 +盡 +監 +盤 +盥 +盦 +盧 +盨 +盩 +盪 +盫 +目 +盯 +盱 +盲 +直 +盷 +相 +盹 +盺 +盼 +盾 +眀 +省 +眉 +看 +県 +眙 +眛 +眜 +眞 +真 +眠 +眥 +眨 +眩 +眭 +眯 +眵 +眶 +眷 +眸 +眺 +眼 +眾 +着 +睇 +睛 +睜 +睞 +睡 +睢 +督 +睥 +睦 +睨 +睪 +睫 +睭 +睹 +睺 +睽 +睾 +睿 +瞄 +瞅 +瞋 +瞌 +瞎 +瞑 +瞓 +瞞 +瞢 +瞥 +瞧 +瞪 +瞫 +瞬 +瞭 +瞰 +瞳 +瞻 +瞼 +瞽 +瞿 +矇 +矍 +矗 +矚 +矛 +矜 +矞 +矢 +矣 +知 +矧 +矩 +短 +矮 +矯 +石 +矸 +矽 +砂 +砋 +砌 +砍 +砒 +研 +砝 +砢 +砥 +砦 +砧 +砩 +砫 +砭 +砮 +砯 +砰 +砲 +砳 +破 +砵 +砷 +砸 +砼 +硂 +硃 +硅 +硇 +硏 +硐 +硒 +硓 +硚 +硜 +硝 +硤 +硨 +硫 +硬 +硭 +硯 +硼 +碁 +碇 +碉 +碌 +碎 +碑 +碓 +碕 +碗 +碘 +碚 +碟 +碡 +碣 +碧 +碩 +碪 +碭 +碰 +碲 +碳 +碴 +碶 +碸 +確 +碻 +碼 +碽 +碾 +磁 +磅 +磊 +磋 +磐 +磔 +磕 +磘 +磙 +磚 +磜 +磡 +磨 +磪 +磬 +磯 +磱 +磲 +磵 +磷 +磺 +磻 +磾 +礁 +礄 +礎 +礐 +礑 +礒 +礙 +礠 +礦 +礪 +礫 +礬 +礮 +礱 +礴 +示 +礻 +礽 +社 +祀 +祁 +祂 +祆 +祇 +祈 +祉 +祋 +祏 +祐 +祓 +祕 +祖 +祗 +祙 +祚 +祛 +祜 +祝 +神 +祟 +祠 +祥 +祧 +票 +祭 +祹 +祺 +祼 +祿 +禁 +禃 +禇 +禍 +禎 +福 +禑 +禓 +禔 +禕 +禘 +禛 +禟 +禠 +禤 +禦 +禧 +禨 +禩 +禪 +禮 +禰 +禱 +禵 +禹 +禺 +禼 +禽 +禾 +禿 +秀 +私 +秈 +秉 +秋 +科 +秒 +秕 +秘 +租 +秠 +秣 +秤 +秦 +秧 +秩 +秭 +秳 +秸 +移 +稀 +稅 +稈 +稉 +程 +稍 +稑 +稔 +稗 +稘 +稙 +稚 +稜 +稞 +稟 +稠 +種 +稱 +稲 +稷 +稹 +稺 +稻 +稼 +稽 +稾 +稿 +穀 +穂 +穆 +穈 +穉 +穌 +積 +穎 +穗 +穟 +穠 +穡 +穢 +穣 +穩 +穫 +穰 +穴 +穵 +究 +穹 +空 +穿 +突 +窄 +窅 +窈 +窋 +窒 +窕 +窖 +窗 +窘 +窟 +窠 +窣 +窨 +窩 +窪 +窮 +窯 +窰 +窶 +窺 +窿 +竄 +竅 +竇 +竈 +竊 +立 +竑 +站 +竜 +竟 +章 +竣 +童 +竦 +竩 +竭 +端 +競 +竹 +竺 +竻 +竿 +笄 +笆 +笈 +笏 +笑 +笘 +笙 +笛 +笞 +笠 +笥 +符 +笨 +笩 +笪 +第 +笭 +笮 +笯 +笱 +笳 +笹 +筅 +筆 +等 +筊 +筋 +筌 +筍 +筏 +筐 +筒 +答 +策 +筘 +筠 +筥 +筦 +筧 +筬 +筭 +筱 +筲 +筳 +筵 +筶 +筷 +筻 +箆 +箇 +箋 +箍 +箏 +箐 +箑 +箒 +箔 +箕 +算 +箜 +管 +箬 +箭 +箱 +箴 +箸 +節 +篁 +範 +篆 +篇 +築 +篊 +篋 +篌 +篔 +篙 +篝 +篠 +篡 +篤 +篥 +篦 +篩 +篪 +篭 +篯 +篳 +篷 +簀 +簃 +簇 +簉 +簋 +簍 +簑 +簕 +簗 +簞 +簠 +簡 +簧 +簪 +簫 +簷 +簸 +簹 +簺 +簽 +簾 +簿 +籀 +籃 +籌 +籍 +籐 +籙 +籛 +籜 +籝 +籟 +籠 +籣 +籤 +籥 +籪 +籬 +籮 +籲 +米 +籽 +籾 +粄 +粉 +粍 +粑 +粒 +粕 +粗 +粘 +粟 +粢 +粥 +粦 +粧 +粩 +粱 +粲 +粳 +粵 +粹 +粼 +粽 +精 +粿 +糀 +糅 +糊 +糌 +糍 +糎 +糕 +糖 +糙 +糜 +糝 +糞 +糟 +糠 +糢 +糧 +糬 +糯 +糰 +糴 +糶 +糸 +糹 +糺 +系 +糾 +紀 +紂 +約 +紅 +紆 +紇 +紈 +紉 +紊 +紋 +納 +紐 +紑 +紓 +純 +紕 +紗 +紘 +紙 +級 +紛 +紜 +紝 +紞 +素 +紡 +索 +紫 +紮 +累 +細 +紱 +紲 +紳 +紵 +紹 +紺 +紿 +終 +絃 +組 +絆 +経 +絎 +結 +絕 +絛 +絜 +絞 +絡 +絢 +給 +絨 +絪 +絮 +統 +絲 +絳 +絵 +絶 +絹 +絺 +綁 +綃 +綈 +綉 +綎 +綏 +經 +綖 +継 +続 +綜 +綝 +綞 +綠 +綢 +綣 +綦 +綧 +綫 +綬 +維 +綮 +綰 +綱 +網 +綳 +綴 +綸 +綺 +綻 +綽 +綾 +綿 +緁 +緃 +緄 +緈 +緊 +緋 +総 +緑 +緒 +緖 +緘 +線 +緜 +緝 +緞 +締 +緡 +緣 +緤 +編 +緩 +緬 +緯 +緱 +緲 +練 +緹 +緻 +縂 +縄 +縈 +縉 +縊 +縕 +縛 +縝 +縞 +縠 +縡 +縣 +縤 +縫 +縮 +縯 +縱 +縴 +縵 +縷 +縹 +縻 +總 +績 +繁 +繃 +繆 +繇 +繒 +織 +繕 +繖 +繙 +繚 +繞 +繡 +繩 +繪 +繫 +繭 +繰 +繳 +繹 +繻 +繼 +繽 +繾 +纁 +纂 +纈 +續 +纍 +纏 +纓 +纔 +纕 +纖 +纘 +纛 +纜 +缐 +缶 +缸 +缺 +缽 +罃 +罄 +罅 +罈 +罉 +罌 +罍 +罐 +罔 +罕 +罘 +罟 +罡 +罨 +罩 +罪 +置 +罰 +罱 +署 +罳 +罵 +罶 +罷 +罹 +罽 +羂 +羅 +羆 +羈 +羊 +羋 +羌 +美 +羔 +羕 +羗 +羙 +羚 +羞 +羡 +羣 +群 +羥 +羧 +羨 +義 +羯 +羰 +羱 +羲 +羸 +羹 +羽 +羿 +翀 +翁 +翂 +翃 +翅 +翊 +翌 +翎 +翏 +習 +翔 +翕 +翙 +翜 +翟 +翠 +翡 +翥 +翦 +翩 +翬 +翮 +翰 +翱 +翳 +翹 +翻 +翼 +耀 +老 +考 +耄 +者 +耆 +而 +耍 +耎 +耐 +耑 +耒 +耔 +耕 +耗 +耘 +耙 +耜 +耦 +耨 +耬 +耳 +耵 +耶 +耷 +耽 +耿 +聃 +聆 +聊 +聒 +聖 +聘 +聚 +聞 +聟 +聨 +聯 +聰 +聱 +聲 +聳 +聴 +聶 +職 +聽 +聾 +聿 +肄 +肅 +肆 +肇 +肉 +肋 +肌 +肏 +肖 +肘 +肚 +肛 +肜 +肝 +肟 +股 +肢 +肥 +肩 +肪 +肫 +肯 +肱 +育 +肸 +肹 +肺 +肼 +肽 +胂 +胃 +胄 +胅 +胇 +胊 +背 +胍 +胎 +胖 +胗 +胙 +胚 +胛 +胝 +胞 +胡 +胤 +胥 +胬 +胭 +胰 +胱 +胳 +胴 +胸 +胺 +胼 +能 +脂 +脅 +脆 +脇 +脈 +脊 +脒 +脖 +脘 +脛 +脣 +脩 +脫 +脬 +脭 +脯 +脲 +脳 +脷 +脹 +脾 +腆 +腈 +腊 +腋 +腌 +腎 +腐 +腑 +腓 +腔 +腕 +腥 +腦 +腧 +腩 +腫 +腮 +腰 +腱 +腳 +腴 +腸 +腹 +腺 +腿 +膀 +膂 +膈 +膊 +膏 +膚 +膛 +膜 +膝 +膠 +膣 +膥 +膦 +膨 +膩 +膮 +膳 +膺 +膽 +膾 +膿 +臀 +臂 +臃 +臆 +臉 +臊 +臍 +臏 +臘 +臚 +臞 +臟 +臠 +臣 +臧 +臨 +自 +臭 +臯 +至 +致 +臺 +臻 +臼 +臾 +舂 +舅 +與 +興 +舉 +舊 +舌 +舍 +舎 +舒 +舔 +舖 +舘 +舛 +舜 +舞 +舟 +舢 +舥 +舨 +舩 +航 +舫 +般 +舲 +舵 +舶 +舷 +舸 +船 +舺 +艅 +艇 +艉 +艋 +艎 +艏 +艔 +艘 +艙 +艚 +艦 +艮 +良 +艱 +色 +艶 +艷 +艸 +艽 +艾 +艿 +芃 +芊 +芋 +芍 +芎 +芑 +芒 +芘 +芙 +芛 +芝 +芡 +芥 +芨 +芩 +芪 +芫 +芬 +芭 +芮 +芯 +花 +芳 +芴 +芷 +芸 +芹 +芻 +芽 +芾 +苄 +苅 +苑 +苒 +苓 +苔 +苕 +苗 +苛 +苜 +苝 +苞 +苟 +苡 +苣 +苤 +若 +苦 +苧 +苪 +苫 +苯 +英 +苳 +苴 +苷 +苺 +苻 +苼 +苾 +茀 +茁 +茂 +范 +茄 +茅 +茆 +茇 +茈 +茉 +茌 +茗 +茘 +茚 +茛 +茜 +茝 +茨 +茫 +茬 +茭 +茮 +茯 +茱 +茲 +茴 +茵 +茶 +茷 +茸 +茹 +茺 +茼 +荀 +荃 +荅 +荇 +草 +荊 +荎 +荏 +荒 +荔 +荖 +荘 +荳 +荷 +荸 +荻 +荼 +荽 +莆 +莉 +莊 +莎 +莒 +莓 +莕 +莖 +莘 +莙 +莛 +莜 +莞 +莠 +莢 +莧 +莨 +莩 +莪 +莫 +莽 +莿 +菀 +菁 +菅 +菇 +菈 +菉 +菊 +菌 +菍 +菏 +菑 +菓 +菔 +菖 +菘 +菜 +菝 +菟 +菠 +菡 +菥 +菩 +菪 +菫 +華 +菰 +菱 +菲 +菴 +菶 +菸 +菹 +菺 +菼 +菽 +菾 +萁 +萃 +萄 +萇 +萊 +萌 +萍 +萎 +萐 +萘 +萜 +萠 +萡 +萣 +萩 +萬 +萭 +萱 +萵 +萸 +萹 +萼 +落 +葃 +葆 +葉 +葊 +葎 +葑 +葒 +著 +葙 +葚 +葛 +葜 +葝 +葡 +董 +葦 +葩 +葫 +葬 +葭 +葯 +葰 +葳 +葵 +葶 +葷 +葺 +蒂 +蒄 +蒍 +蒎 +蒐 +蒓 +蒔 +蒗 +蒙 +蒜 +蒞 +蒟 +蒡 +蒢 +蒤 +蒧 +蒨 +蒭 +蒯 +蒲 +蒴 +蒸 +蒹 +蒺 +蒻 +蒼 +蒽 +蒾 +蒿 +蓀 +蓁 +蓂 +蓄 +蓆 +蓉 +蓋 +蓍 +蓑 +蓓 +蓖 +蓘 +蓚 +蓧 +蓨 +蓪 +蓬 +蓭 +蓮 +蓯 +蓳 +蓼 +蓽 +蓿 +蔆 +蔎 +蔑 +蔓 +蔔 +蔕 +蔗 +蔘 +蔚 +蔝 +蔞 +蔡 +蔣 +蔥 +蔦 +蔬 +蔭 +蔴 +蔵 +蔻 +蔽 +蕁 +蕃 +蕅 +蕈 +蕉 +蕊 +蕎 +蕑 +蕒 +蕖 +蕘 +蕙 +蕚 +蕟 +蕡 +蕢 +蕤 +蕨 +蕩 +蕪 +蕭 +蕷 +蕹 +蕺 +蕻 +蕾 +薀 +薄 +薆 +薇 +薈 +薊 +薌 +薏 +薐 +薑 +薔 +薗 +薘 +薙 +薛 +薜 +薞 +薟 +薡 +薦 +薨 +薩 +薪 +薫 +薬 +薯 +薰 +薲 +薷 +薸 +薹 +薺 +薾 +薿 +藁 +藉 +藍 +藎 +藏 +藐 +藔 +藕 +藜 +藝 +藟 +藤 +藥 +藦 +藨 +藩 +藪 +藶 +藸 +藹 +藺 +藻 +藿 +蘂 +蘄 +蘅 +蘆 +蘇 +蘊 +蘋 +蘐 +蘑 +蘓 +蘗 +蘘 +蘚 +蘞 +蘢 +蘧 +蘩 +蘭 +蘵 +蘶 +蘸 +蘼 +蘿 +虉 +虎 +虐 +虓 +虔 +處 +虖 +虛 +虜 +虞 +號 +虢 +虧 +虨 +虯 +虱 +虵 +虹 +虺 +虻 +蚆 +蚊 +蚋 +蚌 +蚍 +蚓 +蚖 +蚜 +蚝 +蚡 +蚢 +蚣 +蚤 +蚧 +蚨 +蚩 +蚪 +蚯 +蚱 +蚴 +蚵 +蚶 +蚺 +蚼 +蛀 +蛄 +蛇 +蛉 +蛋 +蛍 +蛐 +蛑 +蛔 +蛙 +蛛 +蛞 +蛟 +蛤 +蛭 +蛯 +蛸 +蛹 +蛺 +蛻 +蛾 +蜀 +蜂 +蜃 +蜆 +蜇 +蜈 +蜉 +蜊 +蜍 +蜑 +蜒 +蜓 +蜘 +蜚 +蜛 +蜜 +蜞 +蜢 +蜣 +蜥 +蜨 +蜮 +蜯 +蜱 +蜴 +蜷 +蜻 +蜾 +蜿 +蝀 +蝌 +蝍 +蝎 +蝓 +蝕 +蝗 +蝘 +蝙 +蝚 +蝟 +蝠 +蝣 +蝤 +蝦 +蝨 +蝮 +蝯 +蝰 +蝲 +蝴 +蝶 +蝸 +蝽 +螂 +螃 +螄 +螅 +螈 +螋 +融 +螐 +螔 +螞 +螟 +螠 +螢 +螣 +螥 +螫 +螭 +螯 +螳 +螶 +螺 +螻 +螽 +螾 +蟀 +蟄 +蟅 +蟆 +蟊 +蟋 +蟌 +蟎 +蟑 +蟒 +蟜 +蟠 +蟥 +蟪 +蟫 +蟬 +蟯 +蟲 +蟳 +蟴 +蟶 +蟹 +蟻 +蟾 +蠂 +蠃 +蠄 +蠅 +蠆 +蠊 +蠋 +蠍 +蠐 +蠑 +蠓 +蠔 +蠕 +蠖 +蠘 +蠙 +蠟 +蠡 +蠢 +蠣 +蠱 +蠲 +蠵 +蠶 +蠷 +蠹 +蠻 +血 +衂 +衆 +行 +衍 +衎 +術 +衕 +衖 +街 +衙 +衚 +衛 +衜 +衝 +衞 +衡 +衢 +衣 +表 +衩 +衫 +衰 +衲 +衷 +衽 +衾 +衿 +袁 +袂 +袈 +袋 +袍 +袓 +袖 +袛 +袞 +袤 +袪 +被 +袱 +袴 +袾 +裁 +裂 +裊 +裎 +裒 +裔 +裕 +裖 +裘 +裙 +補 +裝 +裟 +裡 +裨 +裬 +裱 +裳 +裴 +裵 +裸 +裹 +製 +裾 +裿 +褀 +褂 +複 +褌 +褍 +褎 +褐 +褒 +褓 +褔 +褘 +褙 +褚 +褞 +褥 +褧 +褪 +褫 +褭 +褲 +褶 +褸 +褻 +襄 +襌 +襖 +襞 +襟 +襠 +襤 +襦 +襪 +襯 +襲 +襴 +襶 +襻 +襾 +西 +要 +覃 +覆 +覇 +覈 +見 +覌 +規 +覓 +視 +覚 +覡 +覦 +覧 +親 +覬 +覲 +観 +覺 +覽 +覿 +觀 +角 +觔 +觙 +觚 +觜 +解 +觭 +觱 +觴 +觶 +觸 +觿 +言 +訁 +訂 +訃 +訇 +計 +訊 +訌 +討 +訏 +訐 +訒 +訓 +訔 +訕 +訖 +託 +記 +訛 +訝 +訟 +訣 +訥 +訪 +設 +許 +訴 +訶 +診 +註 +証 +訾 +詁 +詆 +詈 +詐 +詒 +詔 +評 +詛 +詞 +詠 +詡 +詢 +詣 +詥 +試 +詧 +詩 +詫 +詭 +詮 +詰 +話 +該 +詳 +詵 +詹 +詼 +誄 +誅 +誇 +誌 +認 +誒 +誓 +誕 +誘 +語 +誠 +誡 +誣 +誤 +誥 +誦 +誨 +說 +説 +読 +誰 +課 +誴 +誹 +誼 +誾 +調 +談 +請 +諍 +諏 +諒 +論 +諗 +諜 +諟 +諠 +諡 +諤 +諦 +諧 +諪 +諫 +諭 +諮 +諱 +諲 +諳 +諴 +諶 +諷 +諸 +諺 +諼 +諾 +謀 +謁 +謂 +謄 +謇 +謊 +謌 +謎 +謏 +謐 +謔 +謖 +謗 +謙 +謚 +講 +謜 +謝 +謠 +謢 +謤 +謨 +謩 +謫 +謬 +謳 +謹 +謾 +證 +譏 +譓 +譔 +識 +譙 +譚 +譜 +譞 +警 +譫 +譬 +譭 +譯 +議 +譲 +譳 +譴 +護 +譽 +譿 +讀 +讃 +變 +讌 +讎 +讓 +讖 +讙 +讚 +讜 +讞 +谷 +谿 +豁 +豆 +豇 +豈 +豉 +豊 +豌 +豎 +豐 +豔 +豕 +豚 +象 +豢 +豨 +豪 +豫 +豬 +豳 +豸 +豹 +豺 +豿 +貂 +貅 +貉 +貊 +貌 +貐 +貒 +貓 +貔 +貘 +貝 +貞 +負 +財 +貢 +貤 +貧 +貨 +販 +貪 +貫 +責 +貭 +貮 +貯 +貲 +貳 +貴 +貶 +買 +貸 +貺 +費 +貼 +貽 +貿 +賀 +賁 +賂 +賃 +賄 +資 +賈 +賊 +賑 +賒 +賓 +賔 +賕 +賚 +賜 +賞 +賠 +賡 +賢 +賣 +賤 +賦 +賨 +質 +賬 +賭 +賴 +賹 +賺 +賻 +購 +賽 +賾 +贄 +贅 +贇 +贈 +贊 +贌 +贍 +贏 +贓 +贔 +贖 +贛 +赤 +赦 +赧 +赫 +赬 +赭 +走 +赳 +赴 +起 +趁 +超 +越 +趐 +趕 +趖 +趙 +趟 +趣 +趨 +足 +趴 +趵 +趺 +趼 +趾 +跅 +跆 +跋 +跌 +跏 +跑 +跖 +跗 +跛 +距 +跟 +跡 +跣 +跤 +跨 +跩 +跪 +路 +跳 +踎 +踏 +踐 +踝 +踞 +踢 +踩 +踰 +踴 +踹 +踺 +蹂 +蹄 +蹇 +蹈 +蹉 +蹊 +蹋 +蹕 +蹙 +蹟 +蹠 +蹤 +蹦 +蹬 +蹭 +蹯 +蹲 +蹴 +蹶 +蹺 +蹻 +蹼 +躁 +躂 +躄 +躉 +躋 +躍 +躑 +躒 +躔 +躝 +躪 +身 +躬 +躰 +躲 +躺 +軀 +車 +軋 +軌 +軍 +軎 +軒 +軔 +軛 +軟 +転 +軫 +軲 +軸 +軹 +軺 +軻 +軼 +軽 +軾 +較 +輄 +輅 +載 +輋 +輒 +輓 +輔 +輕 +輛 +輝 +輞 +輟 +輥 +輦 +輩 +輪 +輬 +輭 +輯 +輶 +輸 +輻 +輾 +輿 +轀 +轂 +轄 +轅 +轆 +轉 +轍 +轎 +轘 +轝 +轟 +轤 +辛 +辜 +辟 +辣 +辦 +辧 +辨 +辭 +辮 +辯 +辰 +辱 +農 +辵 +辺 +辻 +込 +迂 +迄 +迅 +迎 +近 +返 +迢 +迤 +迥 +迦 +迪 +迫 +迭 +迮 +述 +迴 +迵 +迷 +迸 +迺 +追 +退 +送 +逃 +逄 +逅 +逆 +逈 +逋 +逌 +逍 +逎 +透 +逐 +逑 +途 +逕 +逖 +逗 +這 +通 +逛 +逝 +逞 +速 +造 +逢 +連 +逤 +逨 +逮 +逯 +進 +逴 +逵 +逸 +逹 +逺 +逼 +逾 +遁 +遂 +遄 +遇 +遊 +運 +遍 +過 +遏 +遐 +遒 +道 +達 +違 +遘 +遙 +遛 +遜 +遞 +遠 +遢 +遣 +遨 +適 +遭 +遮 +遯 +遲 +遴 +遵 +遶 +遷 +選 +遹 +遺 +遼 +避 +邀 +邁 +邂 +邃 +還 +邇 +邈 +邉 +邊 +邋 +邏 +邑 +邕 +邗 +邙 +邛 +邠 +邡 +邢 +那 +邦 +邨 +邪 +邯 +邰 +邱 +邲 +邳 +邴 +邵 +邸 +邽 +邾 +郁 +郃 +郄 +郅 +郇 +郊 +郋 +郎 +郗 +郛 +郜 +郝 +郞 +郟 +郡 +郢 +郤 +部 +郪 +郫 +郭 +郯 +郳 +郴 +郵 +郷 +都 +郾 +郿 +鄂 +鄃 +鄄 +鄆 +鄉 +鄋 +鄑 +鄒 +鄔 +鄖 +鄗 +鄘 +鄙 +鄚 +鄜 +鄞 +鄠 +鄢 +鄣 +鄤 +鄧 +鄩 +鄫 +鄭 +鄯 +鄰 +鄱 +鄲 +鄳 +鄴 +鄺 +酃 +酆 +酈 +酉 +酊 +酋 +酌 +配 +酎 +酏 +酐 +酒 +酔 +酗 +酚 +酞 +酡 +酢 +酣 +酥 +酩 +酪 +酬 +酮 +酯 +酰 +酴 +酵 +酶 +酷 +酸 +酺 +酼 +醁 +醂 +醃 +醅 +醇 +醉 +醋 +醌 +醍 +醐 +醒 +醚 +醛 +醜 +醞 +醢 +醣 +醪 +醫 +醬 +醮 +醯 +醴 +醺 +醾 +醿 +釀 +釁 +釆 +采 +釉 +釋 +里 +重 +野 +量 +釐 +金 +釒 +釓 +釔 +釕 +釗 +釘 +釙 +釚 +釜 +針 +釣 +釤 +釦 +釧 +釩 +釪 +釭 +釴 +釵 +釷 +釹 +釺 +鈀 +鈁 +鈄 +鈇 +鈈 +鈉 +鈊 +鈍 +鈏 +鈐 +鈑 +鈔 +鈕 +鈖 +鈞 +鈢 +鈣 +鈥 +鈦 +鈫 +鈮 +鈰 +鈳 +鈴 +鈷 +鈸 +鈹 +鈺 +鈾 +鈿 +鉀 +鉄 +鉅 +鉆 +鉈 +鉉 +鉋 +鉌 +鉍 +鉏 +鉑 +鉓 +鉗 +鉚 +鉛 +鉞 +鉟 +鉤 +鉦 +鉬 +鉭 +鉲 +鉶 +鉷 +鉸 +鉻 +鉾 +鉿 +銀 +銂 +銃 +銅 +銋 +銍 +銑 +銓 +銕 +銖 +銘 +銚 +銜 +銠 +銣 +銥 +銦 +銨 +銩 +銪 +銫 +銬 +銭 +銱 +銲 +銳 +銶 +銷 +銹 +銻 +銼 +銾 +鋁 +鋅 +鋆 +鋇 +鋌 +鋏 +鋐 +鋒 +鋕 +鋗 +鋙 +鋡 +鋤 +鋥 +鋦 +鋨 +鋪 +鋮 +鋯 +鋰 +鋱 +鋳 +鋶 +鋸 +鋹 +鋼 +錀 +錄 +錏 +錐 +錒 +錕 +錘 +錚 +錞 +錟 +錠 +錡 +錢 +錦 +錨 +錫 +錬 +錮 +錯 +錳 +錶 +錸 +錻 +鍀 +鍇 +鍈 +鍉 +鍊 +鍋 +鍍 +鍏 +鍔 +鍘 +鍛 +鍝 +鍟 +鍠 +鍥 +鍩 +鍬 +鍱 +鍳 +鍵 +鍶 +鍷 +鍺 +鍼 +鍾 +鎂 +鎅 +鎊 +鎌 +鎏 +鎓 +鎔 +鎖 +鎗 +鎘 +鎚 +鎛 +鎢 +鎣 +鎦 +鎧 +鎪 +鎬 +鎭 +鎮 +鎰 +鎳 +鎵 +鎻 +鏃 +鏇 +鏈 +鏊 +鏌 +鏐 +鏑 +鏓 +鏖 +鏗 +鏘 +鏜 +鏝 +鏞 +鏟 +鏡 +鏢 +鏤 +鏦 +鏳 +鏴 +鏵 +鏷 +鏻 +鏽 +鐃 +鐇 +鐈 +鐓 +鐔 +鐘 +鐙 +鐠 +鐡 +鐤 +鐦 +鐧 +鐫 +鐬 +鐭 +鐮 +鐲 +鐳 +鐵 +鐸 +鐺 +鐽 +鐿 +鑀 +鑁 +鑂 +鑄 +鑅 +鑊 +鑌 +鑑 +鑒 +鑛 +鑠 +鑣 +鑨 +鑪 +鑫 +鑭 +鑰 +鑲 +鑴 +鑷 +鑼 +鑽 +鑾 +鑿 +長 +門 +閂 +閃 +閆 +閉 +開 +閎 +閏 +閑 +閒 +間 +閔 +閘 +閜 +閞 +閟 +関 +閣 +閥 +閦 +閨 +閩 +閬 +閭 +閰 +閱 +閶 +閹 +閻 +閼 +閾 +閿 +闆 +闇 +闈 +闊 +闋 +闌 +闍 +闐 +闓 +闔 +闕 +闖 +闘 +關 +闞 +闡 +闢 +闥 +阜 +阝 +阡 +阪 +阭 +阮 +阯 +阱 +防 +阻 +阿 +陀 +陁 +陂 +附 +陋 +陌 +降 +限 +陔 +陘 +陛 +陜 +陝 +陞 +陟 +陡 +院 +陣 +除 +陪 +陬 +陰 +陲 +陳 +陵 +陶 +陷 +陸 +険 +陽 +隄 +隅 +隆 +隈 +隊 +隋 +隍 +階 +隔 +隕 +隗 +隘 +隙 +際 +障 +隣 +隧 +隨 +險 +隰 +隱 +隲 +隳 +隴 +隷 +隸 +隹 +隻 +隼 +雀 +雁 +雄 +雅 +集 +雇 +雉 +雋 +雌 +雍 +雎 +雑 +雒 +雕 +雖 +雙 +雛 +雜 +雝 +雞 +離 +難 +雨 +雩 +雪 +雫 +雯 +雱 +雲 +零 +雷 +雹 +電 +需 +霄 +霅 +霆 +震 +霈 +霉 +霊 +霍 +霎 +霏 +霑 +霓 +霖 +霙 +霜 +霞 +霤 +霧 +霨 +霰 +露 +霶 +霸 +霹 +霽 +霾 +靁 +靂 +靄 +靈 +靉 +靑 +青 +靖 +靚 +靛 +靜 +非 +靠 +靡 +面 +革 +靫 +靬 +靭 +靳 +靴 +靶 +靺 +靼 +鞅 +鞆 +鞋 +鞍 +鞏 +鞘 +鞞 +鞠 +鞣 +鞥 +鞦 +鞨 +鞭 +鞮 +鞴 +韁 +韃 +韆 +韋 +韌 +韑 +韓 +韙 +韜 +韞 +韠 +韡 +韭 +韮 +音 +韶 +韺 +韻 +韾 +響 +頁 +頂 +頃 +項 +順 +須 +頊 +頌 +頍 +頎 +頏 +預 +頑 +頒 +頓 +頔 +頗 +領 +頜 +頠 +頡 +頤 +頦 +頫 +頭 +頰 +頴 +頵 +頷 +頸 +頹 +頻 +頼 +顆 +題 +額 +顎 +顏 +顒 +顓 +顔 +顕 +顗 +願 +顙 +顛 +類 +顥 +顧 +顫 +顯 +顰 +顱 +顳 +顴 +風 +颮 +颯 +颱 +颶 +颺 +颼 +飄 +飆 +飈 +飛 +食 +飠 +飡 +飢 +飥 +飩 +飪 +飫 +飬 +飭 +飮 +飯 +飲 +飴 +飼 +飽 +飾 +餃 +餄 +餅 +餉 +養 +餌 +餎 +餐 +餒 +餓 +餗 +餘 +餚 +餛 +餞 +餠 +餡 +館 +餮 +餵 +餺 +餾 +餿 +饃 +饅 +饋 +饌 +饑 +饒 +饕 +饗 +饞 +饟 +饢 +首 +馗 +馘 +香 +馛 +馥 +馦 +馨 +馬 +馭 +馮 +馯 +馱 +馳 +馴 +馼 +駁 +駄 +駅 +駆 +駐 +駑 +駒 +駔 +駕 +駘 +駙 +駛 +駝 +駟 +駢 +駭 +駰 +駱 +駿 +騁 +騂 +騄 +騅 +騋 +騎 +騏 +験 +騖 +騙 +騤 +騨 +騫 +騭 +騮 +騰 +騶 +騷 +騾 +驁 +驃 +驄 +驅 +驊 +驌 +驍 +驎 +驒 +驕 +驗 +驚 +驛 +驟 +驢 +驤 +驥 +驩 +驪 +骨 +骯 +骰 +骶 +骷 +骸 +骼 +髀 +髂 +髎 +髏 +髑 +髒 +髓 +體 +高 +髙 +髡 +髦 +髪 +髭 +髮 +髯 +髲 +髷 +髹 +髻 +鬃 +鬄 +鬅 +鬆 +鬍 +鬚 +鬟 +鬢 +鬣 +鬥 +鬧 +鬨 +鬩 +鬪 +鬬 +鬮 +鬯 +鬱 +鬲 +鬹 +鬻 +鬼 +魁 +魂 +魃 +魄 +魅 +魈 +魋 +魍 +魎 +魏 +魔 +魕 +魘 +魚 +魛 +魞 +魟 +魣 +魨 +魩 +魮 +魯 +魴 +魷 +鮀 +鮁 +鮃 +鮄 +鮊 +鮋 +鮍 +鮐 +鮑 +鮒 +鮓 +鮗 +鮜 +鮟 +鮠 +鮡 +鮣 +鮨 +鮪 +鮫 +鮭 +鮮 +鮰 +鮸 +鮹 +鮻 +鯀 +鯁 +鯃 +鯇 +鯉 +鯊 +鯏 +鯒 +鯓 +鯔 +鯕 +鯖 +鯗 +鯙 +鯛 +鯡 +鯢 +鯤 +鯧 +鯨 +鯪 +鯭 +鯮 +鯰 +鯶 +鯷 +鯻 +鯽 +鯿 +鰂 +鰃 +鰆 +鰈 +鰉 +鰍 +鰏 +鰒 +鰓 +鰕 +鰗 +鰛 +鰜 +鰟 +鰣 +鰤 +鰧 +鰨 +鰩 +鰭 +鰮 +鰱 +鰲 +鰳 +鰶 +鰷 +鰹 +鰺 +鰻 +鰼 +鰾 +鱀 +鱂 +鱅 +鱇 +鱈 +鱉 +鱊 +鱒 +鱓 +鱔 +鱖 +鱗 +鱘 +鱚 +鱝 +鱟 +鱠 +鱣 +鱥 +鱧 +鱨 +鱬 +鱮 +鱰 +鱲 +鱵 +鱷 +鱸 +鱺 +鱻 +鳥 +鳧 +鳩 +鳯 +鳰 +鳳 +鳴 +鳶 +鳽 +鴆 +鴇 +鴉 +鴒 +鴓 +鴕 +鴗 +鴛 +鴝 +鴞 +鴟 +鴡 +鴣 +鴦 +鴨 +鴫 +鴯 +鴰 +鴴 +鴻 +鴿 +鵂 +鵄 +鵎 +鵐 +鵑 +鵒 +鵓 +鵙 +鵜 +鵝 +鵞 +鵟 +鵠 +鵡 +鵪 +鵬 +鵯 +鵰 +鵲 +鵵 +鵼 +鵾 +鶆 +鶇 +鶉 +鶏 +鶒 +鶓 +鶘 +鶚 +鶡 +鶥 +鶩 +鶬 +鶯 +鶲 +鶴 +鶹 +鶺 +鶻 +鶼 +鶿 +鷂 +鷄 +鷉 +鷎 +鷓 +鷗 +鷙 +鷚 +鷟 +鷥 +鷦 +鷫 +鷯 +鷲 +鷳 +鷸 +鷹 +鷺 +鸊 +鸌 +鸐 +鸑 +鸕 +鸘 +鸚 +鸛 +鸜 +鸝 +鸞 +鹮 +鹵 +鹹 +鹼 +鹽 +鹿 +麂 +麅 +麇 +麈 +麊 +麋 +麐 +麒 +麓 +麗 +麝 +麞 +麟 +麥 +麩 +麪 +麯 +麴 +麵 +麹 +麺 +麻 +麼 +麽 +麾 +麿 +黁 +黃 +黇 +黌 +黍 +黎 +黏 +黐 +黑 +黒 +黔 +默 +黙 +黛 +黜 +黝 +點 +黟 +黥 +黧 +黨 +黯 +黴 +黶 +黻 +黼 +黽 +黿 +鼂 +鼇 +鼈 +鼉 +鼎 +鼐 +鼒 +鼓 +鼕 +鼙 +鼠 +鼢 +鼩 +鼬 +鼯 +鼱 +鼴 +鼷 +鼻 +鼽 +鼾 +齊 +齋 +齒 +齕 +齡 +齣 +齦 +齧 +齲 +齶 +龍 +龎 +龐 +龑 +龔 +龕 +龜 +龝 +龠 +龢 +郎 +凉 +﹑ +﹗ +﹝ +﹞ +﹢ +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +A +B +C +D +E +F +G +H +I +K +L +M +N +O +P +R +S +T +U +V +W +Y +Z +[ +] +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +r +s +t +u +z +{ +| +} +~ +¥ +𣇉 + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/cyrillic_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/cyrillic_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b6f66494d5417e18bbd225719aa72690e09e126 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/cyrillic_dict.txt @@ -0,0 +1,163 @@ + +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +Ё +Є +І +Ј +Љ +Ў +А +Б +В +Г +Д +Е +Ж +З +И +Й +К +Л +М +Н +О +П +Р +С +Т +У +Ф +Х +Ц +Ч +Ш +Щ +Ъ +Ы +Ь +Э +Ю +Я +а +б +в +г +д +е +ж +з +и +й +к +л +м +н +о +п +р +с +т +у +ф +х +ц +ч +ш +щ +ъ +ы +ь +э +ю +я +ё +ђ +є +і +ј +љ +њ +ћ +ў +џ +Ґ +ґ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/devanagari_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/devanagari_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..f55923061bfd480b875bb3679d7a75a9157387a9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/devanagari_dict.txt @@ -0,0 +1,167 @@ + +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +ँ +ं +ः +अ +आ +इ +ई +उ +ऊ +ऋ +ए +ऐ +ऑ +ओ +औ +क +ख +ग +घ +ङ +च +छ +ज +झ +ञ +ट +ठ +ड +ढ +ण +त +थ +द +ध +न +ऩ +प +फ +ब +भ +म +य +र +ऱ +ल +ळ +व +श +ष +स +ह +़ +ा +ि +ी +ु +ू +ृ +ॅ +े +ै +ॉ +ो +ौ +् +॒ +क़ +ख़ +ग़ +ज़ +ड़ +ढ़ +फ़ +ॠ +। +० +१ +२ +३ +४ +५ +६ +७ +८ +९ +॰ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/en_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/en_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fbd99f46acca8391a5e86ae546c637399204506 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/en_dict.txt @@ -0,0 +1,63 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/fa_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/fa_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..2328fbd8374b3c551036a8521c1a70104925b5a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/fa_dict.txt @@ -0,0 +1,136 @@ +f +a +_ +i +m +g +/ +1 +3 +I +L +S +V +R +C +2 +0 +v +l +6 +8 +5 +. +j +p +و +د +ر +ك +ن +ش +ه +ا +4 +9 +ی +ج +ِ +7 +غ +ل +س +ز +ّ +ت +ک +گ +ي +م +ب +ف +چ +خ +ق +ژ +آ +ص +پ +َ +ع +ئ +ح +ٔ +ض +ُ +ذ +أ +ى +ط +ظ +ث +ة +ً +ء +ؤ +ْ +ۀ +إ +ٍ +ٌ +ٰ +ٓ +ٱ +s +c +e +n +w +N +E +W +Y +D +O +H +A +d +z +r +T +G +o +t +x +h +b +B +M +Z +u +P +F +y +q +U +K +k +J +Q +' +X +# +? +% +$ +, +: +& +! +- +( +É +@ +é ++ + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/french_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/french_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8f657db35bf0b74f779f38a9e3b9b47b007e3c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/french_dict.txt @@ -0,0 +1,136 @@ +f +e +n +c +h +_ +i +m +g +/ +r +v +a +l +t +w +o +d +6 +1 +. +p +B +u +2 +à +3 +R +y +4 +U +E +A +5 +P +O +S +T +D +7 +Z +8 +I +N +L +G +M +H +0 +J +K +- +9 +F +C +V +é +X +' +s +Q +: +è +x +b +Y +Œ +É +z +W +Ç +È +k +Ô +ô +€ +À +Ê +q +ù +° +ê +î +* + +j +" +, +â +% +û +ç +ü +? +! +; +ö +( +) +ï +º +ó +ø +å ++ +™ +á +Ë +< +² +Á +Î +& +@ +œ +ε +Ü +ë +[ +] +í +ò +Ö +ä +ß +« +» +ú +ñ +æ +µ +³ +Å +$ +# + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/german_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/german_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e121af21a1617dd970234ca98ae7072b0335332 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/german_dict.txt @@ -0,0 +1,143 @@ + +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; += +> +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +] +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +£ +§ +­ +° +´ +µ +· +º +¿ +Á +Ä +Å +É +Ï +Ô +Ö +Ü +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +í +ï +ñ +ò +ó +ô +ö +ø +ù +ú +û +ü +ō +Š +Ÿ +ʒ +β +δ +з +Ṡ +‘ +€ +© +ª +« +¬ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/hi_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/hi_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dfedb5ac483966de40caabe0e95118f88aa5a54 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/hi_dict.txt @@ -0,0 +1,162 @@ + +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +ँ +ं +ः +अ +आ +इ +ई +उ +ऊ +ऋ +ए +ऐ +ऑ +ओ +औ +क +ख +ग +घ +ङ +च +छ +ज +झ +ञ +ट +ठ +ड +ढ +ण +त +थ +द +ध +न +प +फ +ब +भ +म +य +र +ल +ळ +व +श +ष +स +ह +़ +ा +ि +ी +ु +ू +ृ +ॅ +े +ै +ॉ +ो +ौ +् +क़ +ख़ +ग़ +ज़ +ड़ +ढ़ +फ़ +० +१ +२ +३ +४ +५ +६ +७ +८ +९ +॰ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/it_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/it_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..e692c6d4335b4b8b2ed873d7923a69ed5e3d6c9a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/it_dict.txt @@ -0,0 +1,118 @@ +i +t +_ +m +g +/ +5 +I +L +S +V +R +C +2 +0 +1 +v +a +l +7 +8 +9 +6 +. +j +p + +e +r +o +d +s +n +3 +4 +P +u +c +A +- +, +" +z +h +f +b +q +ì +' +à +O +è +G +ù +é +ò +; +F +E +B +N +H +k +: +U +T +X +D +K +? +[ +M +­ +x +y +( +) +W +ö +º +w +] +Q +J ++ +ü +! +È +á +% += +» +ñ +Ö +Y +ä +í +Z +« +@ +ó +ø +ï +ú +ê +ç +Á +É +Å +ß +{ +} +& +` +û +î +# +$ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/japan_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/japan_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..339d4b89e5159a346636641a0814874faa59754a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/japan_dict.txt @@ -0,0 +1,4399 @@ +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +] +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +© +° +² +´ +½ +Á +Ä +Å +Ç +È +É +Í +Ó +Ö +× +Ü +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +í +ð +ñ +ò +ó +ô +õ +ö +ø +ú +û +ü +ý +ā +ă +ą +ć +Č +č +đ +ē +ė +ę +ğ +ī +ı +Ł +ł +ń +ň +ō +ř +Ş +ş +Š +š +ţ +ū +ż +Ž +ž +Ș +ș +ț +Δ +α +λ +μ +φ +Г +О +а +в +л +о +р +с +т +я +ồ +​ +— +― +’ +“ +” +… +℃ +→ +∇ +− +■ +☆ +  +、 +。 +々 +〆 +〈 +〉 +「 +」 +『 +』 +〔 +〕 +〜 +ぁ +あ +ぃ +い +う +ぇ +え +ぉ +お +か +が +き +ぎ +く +ぐ +け +げ +こ +ご +さ +ざ +し +じ +す +ず +せ +ぜ +そ +ぞ +た +だ +ち +ぢ +っ +つ +づ +て +で +と +ど +な +に +ぬ +ね +の +は +ば +ぱ +ひ +び +ぴ +ふ +ぶ +ぷ +へ +べ +ぺ +ほ +ぼ +ぽ +ま +み +む +め +も +ゃ +や +ゅ +ゆ +ょ +よ +ら +り +る +れ +ろ +わ +ゑ +を +ん +ゝ +ゞ +ァ +ア +ィ +イ +ゥ +ウ +ェ +エ +ォ +オ +カ +ガ +キ +ギ +ク +グ +ケ +ゲ +コ +ゴ +サ +ザ +シ +ジ +ス +ズ +セ +ゼ +ソ +ゾ +タ +ダ +チ +ヂ +ッ +ツ +ヅ +テ +デ +ト +ド +ナ +ニ +ヌ +ネ +ノ +ハ +バ +パ +ヒ +ビ +ピ +フ +ブ +プ +ヘ +ベ +ペ +ホ +ボ +ポ +マ +ミ +ム +メ +モ +ャ +ヤ +ュ +ユ +ョ +ヨ +ラ +リ +ル +レ +ロ +ワ +ヰ +ン +ヴ +ヵ +ヶ +・ +ー +㈱ +一 +丁 +七 +万 +丈 +三 +上 +下 +不 +与 +丑 +且 +世 +丘 +丙 +丞 +両 +並 +中 +串 +丸 +丹 +主 +丼 +丿 +乃 +久 +之 +乎 +乏 +乗 +乘 +乙 +九 +乞 +也 +乱 +乳 +乾 +亀 +了 +予 +争 +事 +二 +于 +互 +五 +井 +亘 +亙 +些 +亜 +亟 +亡 +交 +亥 +亦 +亨 +享 +京 +亭 +亮 +人 +什 +仁 +仇 +今 +介 +仍 +仏 +仔 +仕 +他 +仗 +付 +仙 +代 +令 +以 +仮 +仰 +仲 +件 +任 +企 +伊 +伍 +伎 +伏 +伐 +休 +会 +伝 +伯 +估 +伴 +伶 +伸 +伺 +似 +伽 +佃 +但 +位 +低 +住 +佐 +佑 +体 +何 +余 +佚 +佛 +作 +佩 +佳 +併 +佶 +使 +侈 +例 +侍 +侏 +侑 +侘 +供 +依 +侠 +価 +侮 +侯 +侵 +侶 +便 +係 +促 +俄 +俊 +俔 +俗 +俘 +保 +信 +俣 +俤 +修 +俯 +俳 +俵 +俸 +俺 +倉 +個 +倍 +倒 +候 +借 +倣 +値 +倫 +倭 +倶 +倹 +偃 +假 +偈 +偉 +偏 +偐 +偕 +停 +健 +側 +偵 +偶 +偽 +傀 +傅 +傍 +傑 +傘 +備 +催 +傭 +傲 +傳 +債 +傷 +傾 +僊 +働 +像 +僑 +僕 +僚 +僧 +僭 +僮 +儀 +億 +儇 +儒 +儛 +償 +儡 +優 +儲 +儺 +儼 +兀 +允 +元 +兄 +充 +兆 +先 +光 +克 +兌 +免 +兎 +児 +党 +兜 +入 +全 +八 +公 +六 +共 +兵 +其 +具 +典 +兼 +内 +円 +冊 +再 +冑 +冒 +冗 +写 +冠 +冤 +冥 +冨 +冬 +冲 +决 +冶 +冷 +准 +凉 +凋 +凌 +凍 +凛 +凝 +凞 +几 +凡 +処 +凪 +凰 +凱 +凶 +凸 +凹 +出 +函 +刀 +刃 +分 +切 +刈 +刊 +刎 +刑 +列 +初 +判 +別 +利 +刪 +到 +制 +刷 +券 +刹 +刺 +刻 +剃 +則 +削 +剋 +前 +剖 +剛 +剣 +剤 +剥 +剪 +副 +剰 +割 +創 +剽 +劇 +劉 +劔 +力 +功 +加 +劣 +助 +努 +劫 +劭 +励 +労 +効 +劾 +勃 +勅 +勇 +勉 +勒 +動 +勘 +務 +勝 +募 +勢 +勤 +勧 +勲 +勺 +勾 +勿 +匁 +匂 +包 +匏 +化 +北 +匙 +匝 +匠 +匡 +匣 +匯 +匲 +匹 +区 +医 +匿 +十 +千 +升 +午 +卉 +半 +卍 +卑 +卒 +卓 +協 +南 +単 +博 +卜 +占 +卦 +卯 +印 +危 +即 +却 +卵 +卸 +卿 +厄 +厚 +原 +厠 +厨 +厩 +厭 +厳 +去 +参 +又 +叉 +及 +友 +双 +反 +収 +叔 +取 +受 +叙 +叛 +叟 +叡 +叢 +口 +古 +句 +叩 +只 +叫 +召 +可 +台 +叱 +史 +右 +叶 +号 +司 +吃 +各 +合 +吉 +吊 +同 +名 +后 +吏 +吐 +向 +君 +吝 +吟 +吠 +否 +含 +吸 +吹 +吻 +吽 +吾 +呂 +呆 +呈 +呉 +告 +呑 +周 +呪 +呰 +味 +呼 +命 +咀 +咄 +咋 +和 +咒 +咫 +咲 +咳 +咸 +哀 +品 +哇 +哉 +員 +哨 +哩 +哭 +哲 +哺 +唄 +唆 +唇 +唐 +唖 +唯 +唱 +唳 +唸 +唾 +啄 +商 +問 +啓 +啼 +善 +喋 +喚 +喜 +喝 +喧 +喩 +喪 +喫 +喬 +單 +喰 +営 +嗅 +嗇 +嗔 +嗚 +嗜 +嗣 +嘆 +嘉 +嘗 +嘘 +嘩 +嘯 +嘱 +嘲 +嘴 +噂 +噌 +噛 +器 +噴 +噺 +嚆 +嚢 +囀 +囃 +囉 +囚 +四 +回 +因 +団 +困 +囲 +図 +固 +国 +圀 +圃 +國 +圏 +園 +圓 +團 +圜 +土 +圧 +在 +圭 +地 +址 +坂 +均 +坊 +坐 +坑 +坡 +坤 +坦 +坪 +垂 +型 +垢 +垣 +埃 +埋 +城 +埒 +埔 +域 +埠 +埴 +埵 +執 +培 +基 +埼 +堀 +堂 +堅 +堆 +堕 +堤 +堪 +堯 +堰 +報 +場 +堵 +堺 +塀 +塁 +塊 +塑 +塔 +塗 +塘 +塙 +塚 +塞 +塩 +填 +塵 +塾 +境 +墉 +墓 +増 +墜 +墟 +墨 +墳 +墺 +墻 +墾 +壁 +壇 +壊 +壌 +壕 +士 +壬 +壮 +声 +壱 +売 +壷 +壹 +壺 +壽 +変 +夏 +夕 +外 +夙 +多 +夜 +夢 +夥 +大 +天 +太 +夫 +夬 +夭 +央 +失 +夷 +夾 +奄 +奇 +奈 +奉 +奎 +奏 +契 +奔 +奕 +套 +奘 +奠 +奢 +奥 +奨 +奪 +奮 +女 +奴 +奸 +好 +如 +妃 +妄 +妊 +妍 +妓 +妖 +妙 +妥 +妨 +妬 +妲 +妹 +妻 +妾 +姉 +始 +姐 +姓 +委 +姚 +姜 +姞 +姥 +姦 +姨 +姪 +姫 +姶 +姻 +姿 +威 +娑 +娘 +娟 +娠 +娩 +娯 +娼 +婆 +婉 +婚 +婢 +婦 +婬 +婿 +媄 +媒 +媓 +媚 +媛 +媞 +媽 +嫁 +嫄 +嫉 +嫌 +嫐 +嫗 +嫡 +嬉 +嬌 +嬢 +嬪 +嬬 +嬾 +孁 +子 +孔 +字 +存 +孚 +孝 +孟 +季 +孤 +学 +孫 +孵 +學 +宅 +宇 +守 +安 +宋 +完 +宍 +宏 +宕 +宗 +官 +宙 +定 +宛 +宜 +宝 +実 +客 +宣 +室 +宥 +宮 +宰 +害 +宴 +宵 +家 +宸 +容 +宿 +寂 +寄 +寅 +密 +寇 +富 +寒 +寓 +寔 +寛 +寝 +察 +寡 +實 +寧 +審 +寮 +寵 +寶 +寸 +寺 +対 +寿 +封 +専 +射 +将 +尉 +尊 +尋 +對 +導 +小 +少 +尖 +尚 +尤 +尪 +尭 +就 +尹 +尺 +尻 +尼 +尽 +尾 +尿 +局 +居 +屈 +届 +屋 +屍 +屎 +屏 +屑 +屓 +展 +属 +屠 +層 +履 +屯 +山 +岐 +岑 +岡 +岩 +岫 +岬 +岳 +岷 +岸 +峠 +峡 +峨 +峯 +峰 +島 +峻 +崇 +崋 +崎 +崑 +崖 +崗 +崛 +崩 +嵌 +嵐 +嵩 +嵯 +嶂 +嶋 +嶠 +嶺 +嶼 +嶽 +巀 +巌 +巒 +巖 +川 +州 +巡 +巣 +工 +左 +巧 +巨 +巫 +差 +己 +巳 +巴 +巷 +巻 +巽 +巾 +市 +布 +帆 +希 +帖 +帚 +帛 +帝 +帥 +師 +席 +帯 +帰 +帳 +帷 +常 +帽 +幄 +幅 +幇 +幌 +幔 +幕 +幟 +幡 +幢 +幣 +干 +平 +年 +并 +幸 +幹 +幻 +幼 +幽 +幾 +庁 +広 +庄 +庇 +床 +序 +底 +庖 +店 +庚 +府 +度 +座 +庫 +庭 +庵 +庶 +康 +庸 +廂 +廃 +廉 +廊 +廓 +廟 +廠 +廣 +廬 +延 +廷 +建 +廻 +廼 +廿 +弁 +弄 +弉 +弊 +弌 +式 +弐 +弓 +弔 +引 +弖 +弗 +弘 +弛 +弟 +弥 +弦 +弧 +弱 +張 +強 +弼 +弾 +彈 +彊 +彌 +彎 +当 +彗 +彙 +彝 +形 +彦 +彩 +彫 +彬 +彭 +彰 +影 +彷 +役 +彼 +往 +征 +徂 +径 +待 +律 +後 +徐 +徑 +徒 +従 +得 +徠 +御 +徧 +徨 +復 +循 +徭 +微 +徳 +徴 +德 +徹 +徽 +心 +必 +忉 +忌 +忍 +志 +忘 +忙 +応 +忠 +快 +忯 +念 +忻 +忽 +忿 +怒 +怖 +思 +怠 +怡 +急 +性 +怨 +怪 +怯 +恂 +恋 +恐 +恒 +恕 +恣 +恤 +恥 +恨 +恩 +恬 +恭 +息 +恵 +悉 +悌 +悍 +悔 +悟 +悠 +患 +悦 +悩 +悪 +悲 +悼 +情 +惇 +惑 +惚 +惜 +惟 +惠 +惣 +惧 +惨 +惰 +想 +惹 +惺 +愈 +愉 +愍 +意 +愔 +愚 +愛 +感 +愷 +愿 +慈 +態 +慌 +慎 +慕 +慢 +慣 +慧 +慨 +慮 +慰 +慶 +憂 +憎 +憐 +憑 +憙 +憤 +憧 +憩 +憬 +憲 +憶 +憾 +懇 +應 +懌 +懐 +懲 +懸 +懺 +懽 +懿 +戈 +戊 +戌 +戎 +成 +我 +戒 +戔 +或 +戚 +戟 +戦 +截 +戮 +戯 +戴 +戸 +戻 +房 +所 +扁 +扇 +扈 +扉 +手 +才 +打 +払 +托 +扮 +扱 +扶 +批 +承 +技 +抄 +把 +抑 +抓 +投 +抗 +折 +抜 +択 +披 +抱 +抵 +抹 +押 +抽 +担 +拇 +拈 +拉 +拍 +拏 +拐 +拒 +拓 +拘 +拙 +招 +拝 +拠 +拡 +括 +拭 +拳 +拵 +拶 +拾 +拿 +持 +挂 +指 +按 +挑 +挙 +挟 +挨 +振 +挺 +挽 +挿 +捉 +捕 +捗 +捜 +捧 +捨 +据 +捺 +捻 +掃 +掄 +授 +掌 +排 +掖 +掘 +掛 +掟 +採 +探 +掣 +接 +控 +推 +掩 +措 +掬 +掲 +掴 +掻 +掾 +揃 +揄 +揆 +揉 +描 +提 +揖 +揚 +換 +握 +揮 +援 +揶 +揺 +損 +搦 +搬 +搭 +携 +搾 +摂 +摘 +摩 +摸 +摺 +撃 +撒 +撞 +撤 +撥 +撫 +播 +撮 +撰 +撲 +撹 +擁 +操 +擔 +擦 +擬 +擾 +攘 +攝 +攣 +支 +收 +改 +攻 +放 +政 +故 +敏 +救 +敗 +教 +敢 +散 +敦 +敬 +数 +整 +敵 +敷 +斂 +文 +斉 +斎 +斐 +斑 +斗 +料 +斜 +斟 +斤 +斥 +斧 +斬 +断 +斯 +新 +方 +於 +施 +旁 +旅 +旋 +旌 +族 +旗 +旛 +无 +旡 +既 +日 +旦 +旧 +旨 +早 +旬 +旭 +旺 +旻 +昂 +昆 +昇 +昉 +昌 +明 +昏 +易 +昔 +星 +映 +春 +昧 +昨 +昪 +昭 +是 +昵 +昼 +晁 +時 +晃 +晋 +晏 +晒 +晟 +晦 +晧 +晩 +普 +景 +晴 +晶 +智 +暁 +暇 +暈 +暉 +暑 +暖 +暗 +暘 +暢 +暦 +暫 +暮 +暲 +暴 +暹 +暾 +曄 +曇 +曉 +曖 +曙 +曜 +曝 +曠 +曰 +曲 +曳 +更 +書 +曹 +曼 +曽 +曾 +替 +最 +會 +月 +有 +朋 +服 +朏 +朔 +朕 +朗 +望 +朝 +期 +朧 +木 +未 +末 +本 +札 +朱 +朴 +机 +朽 +杁 +杉 +李 +杏 +材 +村 +杓 +杖 +杜 +杞 +束 +条 +杢 +杣 +来 +杭 +杮 +杯 +東 +杲 +杵 +杷 +杼 +松 +板 +枅 +枇 +析 +枓 +枕 +林 +枚 +果 +枝 +枠 +枡 +枢 +枯 +枳 +架 +柄 +柊 +柏 +某 +柑 +染 +柔 +柘 +柚 +柯 +柱 +柳 +柴 +柵 +査 +柾 +柿 +栂 +栃 +栄 +栖 +栗 +校 +株 +栲 +栴 +核 +根 +栻 +格 +栽 +桁 +桂 +桃 +框 +案 +桐 +桑 +桓 +桔 +桜 +桝 +桟 +桧 +桴 +桶 +桾 +梁 +梅 +梆 +梓 +梔 +梗 +梛 +條 +梟 +梢 +梧 +梨 +械 +梱 +梲 +梵 +梶 +棄 +棋 +棒 +棗 +棘 +棚 +棟 +棠 +森 +棲 +棹 +棺 +椀 +椅 +椋 +植 +椎 +椏 +椒 +椙 +検 +椥 +椹 +椿 +楊 +楓 +楕 +楚 +楞 +楠 +楡 +楢 +楨 +楪 +楫 +業 +楮 +楯 +楳 +極 +楷 +楼 +楽 +概 +榊 +榎 +榕 +榛 +榜 +榮 +榱 +榴 +槃 +槇 +槊 +構 +槌 +槍 +槐 +様 +槙 +槻 +槽 +槿 +樂 +樋 +樓 +樗 +標 +樟 +模 +権 +横 +樫 +樵 +樹 +樺 +樽 +橇 +橋 +橘 +機 +橿 +檀 +檄 +檎 +檐 +檗 +檜 +檣 +檥 +檬 +檮 +檸 +檻 +櫃 +櫓 +櫛 +櫟 +櫨 +櫻 +欄 +欅 +欠 +次 +欣 +欧 +欲 +欺 +欽 +款 +歌 +歎 +歓 +止 +正 +此 +武 +歩 +歪 +歯 +歳 +歴 +死 +殆 +殉 +殊 +残 +殖 +殯 +殴 +段 +殷 +殺 +殻 +殿 +毀 +毅 +母 +毎 +毒 +比 +毘 +毛 +毫 +毬 +氈 +氏 +民 +気 +水 +氷 +永 +氾 +汀 +汁 +求 +汎 +汐 +汗 +汚 +汝 +江 +池 +汪 +汰 +汲 +決 +汽 +沂 +沃 +沅 +沆 +沈 +沌 +沐 +沓 +沖 +沙 +没 +沢 +沱 +河 +沸 +油 +治 +沼 +沽 +沿 +況 +泉 +泊 +泌 +法 +泗 +泡 +波 +泣 +泥 +注 +泯 +泰 +泳 +洋 +洒 +洗 +洛 +洞 +津 +洩 +洪 +洲 +洸 +洹 +活 +洽 +派 +流 +浄 +浅 +浙 +浚 +浜 +浣 +浦 +浩 +浪 +浮 +浴 +海 +浸 +涅 +消 +涌 +涙 +涛 +涯 +液 +涵 +涼 +淀 +淄 +淆 +淇 +淋 +淑 +淘 +淡 +淤 +淨 +淫 +深 +淳 +淵 +混 +淹 +添 +清 +済 +渉 +渋 +渓 +渕 +渚 +減 +渟 +渠 +渡 +渤 +渥 +渦 +温 +渫 +測 +港 +游 +渾 +湊 +湖 +湘 +湛 +湧 +湫 +湯 +湾 +湿 +満 +源 +準 +溜 +溝 +溢 +溥 +溪 +溶 +溺 +滄 +滅 +滋 +滌 +滑 +滕 +滝 +滞 +滴 +滸 +滹 +滿 +漁 +漂 +漆 +漉 +漏 +漑 +演 +漕 +漠 +漢 +漣 +漫 +漬 +漱 +漸 +漿 +潅 +潔 +潙 +潜 +潟 +潤 +潭 +潮 +潰 +潴 +澁 +澂 +澄 +澎 +澗 +澤 +澪 +澱 +澳 +激 +濁 +濃 +濟 +濠 +濡 +濤 +濫 +濯 +濱 +濾 +瀉 +瀋 +瀑 +瀕 +瀞 +瀟 +瀧 +瀬 +瀾 +灌 +灑 +灘 +火 +灯 +灰 +灸 +災 +炉 +炊 +炎 +炒 +炭 +炮 +炷 +点 +為 +烈 +烏 +烙 +烝 +烹 +焔 +焙 +焚 +無 +焦 +然 +焼 +煇 +煉 +煌 +煎 +煕 +煙 +煤 +煥 +照 +煩 +煬 +煮 +煽 +熈 +熊 +熙 +熟 +熨 +熱 +熹 +熾 +燃 +燈 +燎 +燔 +燕 +燗 +燥 +燭 +燻 +爆 +爐 +爪 +爬 +爲 +爵 +父 +爺 +爼 +爽 +爾 +片 +版 +牌 +牒 +牘 +牙 +牛 +牝 +牟 +牡 +牢 +牧 +物 +牲 +特 +牽 +犂 +犠 +犬 +犯 +状 +狂 +狄 +狐 +狗 +狙 +狛 +狡 +狩 +独 +狭 +狷 +狸 +狼 +猊 +猛 +猟 +猥 +猨 +猩 +猪 +猫 +献 +猴 +猶 +猷 +猾 +猿 +獄 +獅 +獏 +獣 +獲 +玄 +玅 +率 +玉 +王 +玖 +玩 +玲 +珀 +珂 +珈 +珉 +珊 +珍 +珎 +珞 +珠 +珣 +珥 +珪 +班 +現 +球 +理 +琉 +琢 +琥 +琦 +琮 +琲 +琳 +琴 +琵 +琶 +瑁 +瑋 +瑙 +瑚 +瑛 +瑜 +瑞 +瑠 +瑤 +瑩 +瑪 +瑳 +瑾 +璃 +璋 +璜 +璞 +璧 +璨 +環 +璵 +璽 +璿 +瓊 +瓔 +瓜 +瓢 +瓦 +瓶 +甍 +甑 +甕 +甘 +甚 +甞 +生 +産 +甥 +用 +甫 +田 +由 +甲 +申 +男 +町 +画 +界 +畏 +畑 +畔 +留 +畜 +畝 +畠 +畢 +略 +番 +異 +畳 +當 +畷 +畸 +畺 +畿 +疆 +疇 +疋 +疎 +疏 +疑 +疫 +疱 +疲 +疹 +疼 +疾 +病 +症 +痒 +痔 +痕 +痘 +痙 +痛 +痢 +痩 +痴 +痺 +瘍 +瘡 +瘧 +療 +癇 +癌 +癒 +癖 +癡 +癪 +発 +登 +白 +百 +的 +皆 +皇 +皋 +皐 +皓 +皮 +皺 +皿 +盂 +盃 +盆 +盈 +益 +盒 +盗 +盛 +盞 +盟 +盡 +監 +盤 +盥 +盧 +目 +盲 +直 +相 +盾 +省 +眉 +看 +県 +眞 +真 +眠 +眷 +眺 +眼 +着 +睡 +督 +睦 +睨 +睿 +瞋 +瞑 +瞞 +瞬 +瞭 +瞰 +瞳 +瞻 +瞼 +瞿 +矍 +矛 +矜 +矢 +知 +矧 +矩 +短 +矮 +矯 +石 +砂 +砌 +研 +砕 +砥 +砦 +砧 +砲 +破 +砺 +硝 +硫 +硬 +硯 +碁 +碇 +碌 +碑 +碓 +碕 +碗 +碣 +碧 +碩 +確 +碾 +磁 +磐 +磔 +磧 +磨 +磬 +磯 +礁 +礎 +礒 +礙 +礫 +礬 +示 +礼 +社 +祀 +祁 +祇 +祈 +祉 +祐 +祓 +祕 +祖 +祗 +祚 +祝 +神 +祟 +祠 +祢 +祥 +票 +祭 +祷 +祺 +禁 +禄 +禅 +禊 +禍 +禎 +福 +禔 +禖 +禛 +禦 +禧 +禮 +禰 +禹 +禽 +禿 +秀 +私 +秋 +科 +秒 +秘 +租 +秤 +秦 +秩 +称 +移 +稀 +程 +税 +稔 +稗 +稙 +稚 +稜 +稠 +種 +稱 +稲 +稷 +稻 +稼 +稽 +稿 +穀 +穂 +穆 +積 +穎 +穏 +穗 +穜 +穢 +穣 +穫 +穴 +究 +空 +突 +窃 +窄 +窒 +窓 +窟 +窠 +窩 +窪 +窮 +窯 +竃 +竄 +竈 +立 +站 +竜 +竝 +竟 +章 +童 +竪 +竭 +端 +竴 +競 +竹 +竺 +竽 +竿 +笄 +笈 +笏 +笑 +笙 +笛 +笞 +笠 +笥 +符 +第 +笹 +筅 +筆 +筇 +筈 +等 +筋 +筌 +筍 +筏 +筐 +筑 +筒 +答 +策 +筝 +筥 +筧 +筬 +筮 +筯 +筰 +筵 +箆 +箇 +箋 +箏 +箒 +箔 +箕 +算 +箙 +箜 +管 +箪 +箭 +箱 +箸 +節 +篁 +範 +篆 +篇 +築 +篋 +篌 +篝 +篠 +篤 +篥 +篦 +篩 +篭 +篳 +篷 +簀 +簒 +簡 +簧 +簪 +簫 +簺 +簾 +簿 +籀 +籃 +籌 +籍 +籐 +籟 +籠 +籤 +籬 +米 +籾 +粂 +粉 +粋 +粒 +粕 +粗 +粘 +粛 +粟 +粥 +粧 +粮 +粳 +精 +糊 +糖 +糜 +糞 +糟 +糠 +糧 +糯 +糸 +糺 +系 +糾 +紀 +約 +紅 +紋 +納 +紐 +純 +紗 +紘 +紙 +級 +紛 +素 +紡 +索 +紫 +紬 +累 +細 +紳 +紵 +紹 +紺 +絁 +終 +絃 +組 +絅 +経 +結 +絖 +絞 +絡 +絣 +給 +統 +絲 +絵 +絶 +絹 +絽 +綏 +經 +継 +続 +綜 +綟 +綬 +維 +綱 +網 +綴 +綸 +綺 +綽 +綾 +綿 +緊 +緋 +総 +緑 +緒 +線 +締 +緥 +編 +緩 +緬 +緯 +練 +緻 +縁 +縄 +縅 +縒 +縛 +縞 +縢 +縣 +縦 +縫 +縮 +縹 +總 +績 +繁 +繊 +繋 +繍 +織 +繕 +繝 +繦 +繧 +繰 +繹 +繼 +纂 +纈 +纏 +纐 +纒 +纛 +缶 +罔 +罠 +罧 +罪 +置 +罰 +署 +罵 +罷 +罹 +羂 +羅 +羆 +羇 +羈 +羊 +羌 +美 +群 +羨 +義 +羯 +羲 +羹 +羽 +翁 +翅 +翌 +習 +翔 +翛 +翠 +翡 +翫 +翰 +翺 +翻 +翼 +耀 +老 +考 +者 +耆 +而 +耐 +耕 +耗 +耨 +耳 +耶 +耽 +聊 +聖 +聘 +聚 +聞 +聟 +聡 +聨 +聯 +聰 +聲 +聴 +職 +聾 +肄 +肆 +肇 +肉 +肋 +肌 +肖 +肘 +肛 +肝 +股 +肢 +肥 +肩 +肪 +肯 +肱 +育 +肴 +肺 +胃 +胆 +背 +胎 +胖 +胚 +胝 +胞 +胡 +胤 +胱 +胴 +胸 +能 +脂 +脅 +脆 +脇 +脈 +脊 +脚 +脛 +脩 +脱 +脳 +腋 +腎 +腐 +腑 +腔 +腕 +腫 +腰 +腱 +腸 +腹 +腺 +腿 +膀 +膏 +膚 +膜 +膝 +膠 +膣 +膨 +膩 +膳 +膵 +膾 +膿 +臂 +臆 +臈 +臍 +臓 +臘 +臚 +臣 +臥 +臨 +自 +臭 +至 +致 +臺 +臼 +舂 +舅 +與 +興 +舌 +舍 +舎 +舒 +舖 +舗 +舘 +舜 +舞 +舟 +舩 +航 +般 +舳 +舶 +船 +艇 +艘 +艦 +艮 +良 +色 +艶 +芋 +芒 +芙 +芝 +芥 +芦 +芬 +芭 +芯 +花 +芳 +芸 +芹 +芻 +芽 +芿 +苅 +苑 +苔 +苗 +苛 +苞 +苡 +若 +苦 +苧 +苫 +英 +苴 +苻 +茂 +范 +茄 +茅 +茎 +茗 +茘 +茜 +茨 +茲 +茵 +茶 +茸 +茹 +草 +荊 +荏 +荒 +荘 +荷 +荻 +荼 +莞 +莪 +莫 +莬 +莱 +莵 +莽 +菅 +菊 +菌 +菓 +菖 +菘 +菜 +菟 +菩 +菫 +華 +菱 +菴 +萄 +萊 +萌 +萍 +萎 +萠 +萩 +萬 +萱 +落 +葉 +著 +葛 +葡 +董 +葦 +葩 +葬 +葭 +葱 +葵 +葺 +蒋 +蒐 +蒔 +蒙 +蒟 +蒡 +蒲 +蒸 +蒻 +蒼 +蒿 +蓄 +蓆 +蓉 +蓋 +蓑 +蓬 +蓮 +蓼 +蔀 +蔑 +蔓 +蔚 +蔡 +蔦 +蔬 +蔭 +蔵 +蔽 +蕃 +蕉 +蕊 +蕎 +蕨 +蕩 +蕪 +蕭 +蕾 +薄 +薇 +薊 +薔 +薗 +薙 +薛 +薦 +薨 +薩 +薪 +薫 +薬 +薭 +薮 +藁 +藉 +藍 +藏 +藐 +藝 +藤 +藩 +藪 +藷 +藹 +藺 +藻 +蘂 +蘆 +蘇 +蘊 +蘭 +虎 +虐 +虔 +虚 +虜 +虞 +號 +虫 +虹 +虻 +蚊 +蚕 +蛇 +蛉 +蛍 +蛎 +蛙 +蛛 +蛟 +蛤 +蛭 +蛮 +蛸 +蛹 +蛾 +蜀 +蜂 +蜃 +蜆 +蜊 +蜘 +蜜 +蜷 +蜻 +蝉 +蝋 +蝕 +蝙 +蝠 +蝦 +蝶 +蝿 +螂 +融 +螣 +螺 +蟄 +蟇 +蟠 +蟷 +蟹 +蟻 +蠢 +蠣 +血 +衆 +行 +衍 +衒 +術 +街 +衙 +衛 +衝 +衞 +衡 +衢 +衣 +表 +衫 +衰 +衵 +衷 +衽 +衾 +衿 +袁 +袈 +袋 +袍 +袒 +袖 +袙 +袞 +袢 +被 +袰 +袱 +袴 +袷 +袿 +裁 +裂 +裃 +装 +裏 +裔 +裕 +裘 +裙 +補 +裟 +裡 +裲 +裳 +裴 +裸 +裹 +製 +裾 +褂 +褄 +複 +褌 +褐 +褒 +褥 +褪 +褶 +褻 +襄 +襖 +襞 +襟 +襠 +襦 +襪 +襲 +襴 +襷 +西 +要 +覆 +覇 +覈 +見 +規 +視 +覗 +覚 +覧 +親 +覲 +観 +覺 +觀 +角 +解 +触 +言 +訂 +計 +討 +訓 +託 +記 +訛 +訟 +訢 +訥 +訪 +設 +許 +訳 +訴 +訶 +診 +註 +証 +詐 +詔 +評 +詛 +詞 +詠 +詢 +詣 +試 +詩 +詫 +詮 +詰 +話 +該 +詳 +誄 +誅 +誇 +誉 +誌 +認 +誓 +誕 +誘 +語 +誠 +誡 +誣 +誤 +誥 +誦 +説 +読 +誰 +課 +誼 +誾 +調 +談 +請 +諌 +諍 +諏 +諒 +論 +諚 +諜 +諟 +諡 +諦 +諧 +諫 +諭 +諮 +諱 +諶 +諷 +諸 +諺 +諾 +謀 +謄 +謌 +謎 +謗 +謙 +謚 +講 +謝 +謡 +謫 +謬 +謹 +證 +識 +譚 +譛 +譜 +警 +譬 +譯 +議 +譲 +譴 +護 +讀 +讃 +讐 +讒 +谷 +谿 +豅 +豆 +豊 +豎 +豐 +豚 +象 +豪 +豫 +豹 +貌 +貝 +貞 +負 +財 +貢 +貧 +貨 +販 +貪 +貫 +責 +貯 +貰 +貴 +買 +貸 +費 +貼 +貿 +賀 +賁 +賂 +賃 +賄 +資 +賈 +賊 +賎 +賑 +賓 +賛 +賜 +賞 +賠 +賢 +賣 +賤 +賦 +質 +賭 +購 +賽 +贄 +贅 +贈 +贋 +贔 +贖 +赤 +赦 +走 +赴 +起 +超 +越 +趙 +趣 +足 +趺 +趾 +跋 +跏 +距 +跡 +跨 +跪 +路 +跳 +践 +踊 +踏 +踐 +踞 +踪 +踵 +蹄 +蹉 +蹊 +蹟 +蹲 +蹴 +躅 +躇 +躊 +躍 +躑 +躙 +躪 +身 +躬 +躯 +躰 +車 +軋 +軌 +軍 +軒 +軟 +転 +軸 +軻 +軽 +軾 +較 +載 +輌 +輔 +輜 +輝 +輦 +輩 +輪 +輯 +輸 +輿 +轄 +轍 +轟 +轢 +辛 +辞 +辟 +辥 +辦 +辨 +辰 +辱 +農 +辺 +辻 +込 +迂 +迅 +迎 +近 +返 +迢 +迦 +迪 +迫 +迭 +述 +迷 +迹 +追 +退 +送 +逃 +逅 +逆 +逍 +透 +逐 +逓 +途 +逕 +逗 +這 +通 +逝 +逞 +速 +造 +逢 +連 +逮 +週 +進 +逸 +逼 +遁 +遂 +遅 +遇 +遊 +運 +遍 +過 +遐 +道 +達 +違 +遙 +遜 +遠 +遡 +遣 +遥 +適 +遭 +遮 +遯 +遵 +遷 +選 +遺 +遼 +避 +邀 +邁 +邂 +邃 +還 +邇 +邉 +邊 +邑 +那 +邦 +邨 +邪 +邯 +邵 +邸 +郁 +郊 +郎 +郡 +郢 +部 +郭 +郴 +郵 +郷 +都 +鄂 +鄙 +鄭 +鄰 +鄲 +酉 +酋 +酌 +配 +酎 +酒 +酔 +酢 +酥 +酪 +酬 +酵 +酷 +酸 +醍 +醐 +醒 +醗 +醜 +醤 +醪 +醵 +醸 +采 +釈 +釉 +釋 +里 +重 +野 +量 +釐 +金 +釘 +釜 +針 +釣 +釧 +釿 +鈍 +鈎 +鈐 +鈔 +鈞 +鈦 +鈴 +鈷 +鈸 +鈿 +鉄 +鉇 +鉉 +鉋 +鉛 +鉢 +鉤 +鉦 +鉱 +鉾 +銀 +銃 +銅 +銈 +銑 +銕 +銘 +銚 +銜 +銭 +鋏 +鋒 +鋤 +鋭 +鋲 +鋳 +鋸 +鋺 +鋼 +錆 +錍 +錐 +錘 +錠 +錣 +錦 +錫 +錬 +錯 +録 +錵 +鍋 +鍍 +鍑 +鍔 +鍛 +鍬 +鍮 +鍵 +鍼 +鍾 +鎌 +鎖 +鎗 +鎚 +鎧 +鎬 +鎮 +鎰 +鎹 +鏃 +鏑 +鏡 +鐃 +鐇 +鐐 +鐔 +鐘 +鐙 +鐚 +鐡 +鐵 +鐸 +鑁 +鑊 +鑑 +鑒 +鑚 +鑠 +鑢 +鑰 +鑵 +鑷 +鑼 +鑽 +鑿 +長 +門 +閃 +閇 +閉 +開 +閏 +閑 +間 +閔 +閘 +関 +閣 +閤 +閥 +閦 +閨 +閬 +閲 +閻 +閼 +閾 +闇 +闍 +闔 +闕 +闘 +關 +闡 +闢 +闥 +阜 +阪 +阮 +阯 +防 +阻 +阿 +陀 +陂 +附 +陌 +降 +限 +陛 +陞 +院 +陣 +除 +陥 +陪 +陬 +陰 +陳 +陵 +陶 +陸 +険 +陽 +隅 +隆 +隈 +隊 +隋 +階 +随 +隔 +際 +障 +隠 +隣 +隧 +隷 +隻 +隼 +雀 +雁 +雄 +雅 +集 +雇 +雉 +雊 +雋 +雌 +雍 +雑 +雖 +雙 +雛 +離 +難 +雨 +雪 +雫 +雰 +雲 +零 +雷 +雹 +電 +需 +震 +霊 +霍 +霖 +霜 +霞 +霧 +霰 +露 +靈 +青 +靖 +静 +靜 +非 +面 +革 +靫 +靭 +靱 +靴 +靺 +鞁 +鞄 +鞆 +鞋 +鞍 +鞏 +鞘 +鞠 +鞨 +鞭 +韋 +韓 +韜 +韮 +音 +韶 +韻 +響 +頁 +頂 +頃 +項 +順 +須 +頌 +預 +頑 +頒 +頓 +領 +頚 +頬 +頭 +頴 +頸 +頻 +頼 +顆 +題 +額 +顎 +顔 +顕 +顗 +願 +顛 +類 +顧 +顯 +風 +飛 +食 +飢 +飩 +飫 +飯 +飲 +飴 +飼 +飽 +飾 +餃 +餅 +餉 +養 +餌 +餐 +餓 +餘 +餝 +餡 +館 +饂 +饅 +饉 +饋 +饌 +饒 +饗 +首 +馗 +香 +馨 +馬 +馳 +馴 +駄 +駅 +駆 +駈 +駐 +駒 +駕 +駝 +駿 +騁 +騎 +騏 +騒 +験 +騙 +騨 +騰 +驕 +驚 +驛 +驢 +骨 +骸 +髄 +體 +高 +髙 +髢 +髪 +髭 +髮 +髷 +髻 +鬘 +鬚 +鬢 +鬨 +鬯 +鬱 +鬼 +魁 +魂 +魄 +魅 +魏 +魔 +魚 +魯 +鮎 +鮑 +鮒 +鮪 +鮫 +鮭 +鮮 +鯉 +鯔 +鯖 +鯛 +鯨 +鯰 +鯱 +鰐 +鰒 +鰭 +鰯 +鰰 +鰹 +鰻 +鱈 +鱒 +鱗 +鱧 +鳥 +鳩 +鳰 +鳳 +鳴 +鳶 +鴈 +鴉 +鴎 +鴛 +鴟 +鴦 +鴨 +鴫 +鴻 +鵄 +鵜 +鵞 +鵡 +鵬 +鵲 +鵺 +鶉 +鶏 +鶯 +鶴 +鷄 +鷙 +鷲 +鷹 +鷺 +鸚 +鸞 +鹸 +鹽 +鹿 +麁 +麒 +麓 +麗 +麝 +麞 +麟 +麦 +麩 +麹 +麺 +麻 +麾 +麿 +黄 +黌 +黍 +黒 +黙 +黛 +黠 +鼈 +鼉 +鼎 +鼓 +鼠 +鼻 +齊 +齋 +齟 +齢 +齬 +龍 +龕 +龗 +! +# +% +& +( +) ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; += +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +R +S +T +U +V +W +X +Z +a +c +d +e +f +h +i +j +k +l +m +n +o +p +r +s +t +u +y +z +~ +・ + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ka_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ka_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..d506b691bd1a6c55299ad89a72cf3a69a2c879a9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ka_dict.txt @@ -0,0 +1,153 @@ +k +a +_ +i +m +g +/ +1 +2 +I +L +S +V +R +C +0 +v +l +6 +4 +8 +. +j +p +ಗ +ು +ಣ +ಪ +ಡ +ಿ +ಸ +ಲ +ಾ +ದ +್ +7 +5 +3 +ವ +ಷ +ಬ +ಹ +ೆ +9 +ಅ +ಳ +ನ +ರ +ಉ +ಕ +ಎ +ೇ +ಂ +ೈ +ೊ +ೀ +ಯ +ೋ +ತ +ಶ +ಭ +ಧ +ಚ +ಜ +ೂ +ಮ +ಒ +ೃ +ಥ +ಇ +ಟ +ಖ +ಆ +ಞ +ಫ +- +ಢ +ಊ +ಓ +ಐ +ಃ +ಘ +ಝ +ೌ +ಠ +ಛ +ಔ +ಏ +ಈ +ಋ +೨ +೦ +೧ +೮ +೯ +೪ +, +೫ +೭ +೩ +೬ +ಙ +s +c +e +n +w +o +u +t +d +E +A +T +B +Z +N +G +O +q +z +r +x +P +K +M +J +U +D +f +F +h +b +W +Y +y +H +X +Q +' +# +& +! +@ +$ +: +% +é +É +( +? ++ + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/kie_dict/xfund_class_list.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/kie_dict/xfund_class_list.txt new file mode 100644 index 0000000000000000000000000000000000000000..faded9f9b8f56bd258909bec9b8f1755aa688367 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/kie_dict/xfund_class_list.txt @@ -0,0 +1,4 @@ +OTHER +QUESTION +ANSWER +HEADER diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/korean_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/korean_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..a13899f14dfe3bfc25b34904390c7b1e4ed8674b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/korean_dict.txt @@ -0,0 +1,3688 @@ +! +" +# +$ +% +& +' +* ++ +- +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +\ +] +^ +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +| +} +~ +© +° +² +½ +Á +Ä +Å +Ç +É +Í +Î +Ó +Ö +× +Ü +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +ì +í +î +ï +ð +ñ +ò +ó +ô +õ +ö +ø +ú +û +ü +ý +ā +ă +ą +ć +Č +č +đ +ē +ė +ę +ě +ğ +ī +İ +ı +Ł +ł +ń +ň +ō +ř +Ş +ş +Š +š +ţ +ū +ź +ż +Ž +ž +Ș +ș +Α +Δ +α +λ +φ +Г +О +а +в +л +о +р +с +т +я +​ +’ +“ +” +→ +∇ +∼ +「 +」 +ア +カ +グ +ニ +ラ +ン +ㄱ +ㄴ +ㄷ +ㄸ +ㄹ +ㅂ +ㅅ +ㅆ +ㅇ +ㅈ +ㅊ +ㅋ +ㅌ +ㅎ +ㅓ +ㅜ +ㅣ +一 +丁 +七 +三 +上 +下 +不 +丑 +世 +丘 +丞 +中 +丸 +丹 +主 +乃 +久 +之 +乎 +乘 +九 +也 +乳 +乾 +事 +二 +云 +互 +五 +井 +亞 +亡 +交 +亥 +亨 +享 +京 +亭 +人 +仁 +今 +他 +仙 +代 +令 +以 +仰 +仲 +件 +任 +企 +伊 +伍 +伎 +伏 +伐 +休 +伯 +伴 +伸 +佃 +佈 +位 +低 +住 +佐 +何 +佛 +作 +使 +來 +供 +依 +侯 +侵 +侶 +便 +俗 +保 +俠 +信 +修 +俱 +俳 +倉 +個 +倍 +倒 +候 +借 +値 +倫 +倭 +假 +偈 +偉 +偏 +停 +偶 +傅 +傑 +傳 +傷 +傾 +像 +僞 +僥 +僧 +價 +儀 +儉 +儒 +優 +儼 +兀 +允 +元 +兆 +先 +光 +克 +兒 +入 +內 +全 +八 +公 +六 +共 +兵 +其 +具 +典 +兼 +再 +冠 +冥 +冶 +准 +凞 +凡 +凱 +出 +函 +刀 +分 +刊 +刑 +列 +初 +判 +別 +利 +到 +制 +券 +刺 +刻 +則 +前 +剛 +副 +創 +劃 +劑 +力 +功 +加 +劣 +助 +劫 +勇 +動 +務 +勝 +勢 +勳 +勸 +匈 +化 +北 +匠 +區 +十 +千 +午 +半 +卍 +卑 +卒 +卓 +南 +博 +卜 +占 +卦 +印 +危 +卵 +卷 +卽 +卿 +厄 +原 +厦 +去 +參 +又 +叉 +友 +反 +叔 +受 +口 +古 +句 +可 +台 +史 +右 +司 +各 +合 +吉 +同 +名 +后 +吏 +吐 +君 +吠 +吳 +呂 +告 +周 +味 +呵 +命 +和 +咳 +咸 +咽 +哀 +品 +哨 +哮 +哲 +唐 +唯 +唱 +商 +問 +啼 +善 +喆 +喉 +喜 +喩 +喪 +嘗 +器 +嚴 +囊 +四 +回 +因 +困 +固 +圈 +國 +圍 +園 +圓 +圖 +團 +土 +在 +地 +均 +坊 +坐 +坑 +坵 +型 +垢 +城 +域 +埴 +執 +培 +基 +堂 +堅 +堆 +堤 +堯 +報 +場 +塔 +塚 +塞 +塵 +境 +墜 +墟 +墨 +墳 +墾 +壁 +壇 +壓 +壤 +士 +壬 +壯 +壺 +壽 +夏 +夕 +外 +多 +夜 +夢 +大 +天 +太 +夫 +央 +失 +夷 +奄 +奇 +奉 +奎 +奏 +契 +奔 +奮 +女 +奴 +好 +如 +妄 +妊 +妖 +妙 +始 +姑 +姓 +姚 +姜 +威 +婆 +婚 +婦 +媒 +媚 +子 +孔 +字 +存 +孝 +孟 +季 +孤 +孫 +學 +孺 +宇 +守 +安 +宋 +宗 +官 +宙 +定 +客 +宣 +室 +宮 +害 +家 +容 +寂 +寃 +寄 +寅 +密 +寇 +富 +寒 +寓 +實 +審 +寫 +寬 +寶 +寸 +寺 +封 +將 +專 +尊 +對 +小 +少 +尙 +尹 +尼 +尿 +局 +居 +屈 +屋 +屍 +屎 +屛 +層 +屬 +山 +岐 +岡 +岩 +岳 +岸 +峙 +峰 +島 +峻 +峽 +崇 +崔 +崖 +崩 +嶋 +巖 +川 +州 +巢 +工 +左 +巧 +巨 +巫 +差 +己 +巷 +市 +布 +帝 +師 +帶 +常 +帽 +幕 +干 +平 +年 +幹 +幻 +幼 +幽 +庇 +序 +店 +府 +度 +座 +庫 +庭 +康 +廟 +廣 +廳 +延 +廷 +建 +廻 +弁 +式 +弑 +弓 +引 +弘 +弟 +弱 +張 +强 +弼 +彌 +彛 +形 +彬 +影 +役 +彼 +彿 +往 +征 +待 +律 +後 +徐 +徑 +得 +從 +循 +微 +德 +徹 +心 +必 +忌 +忍 +志 +忠 +思 +怡 +急 +性 +恐 +恒 +恨 +恩 +悅 +悖 +患 +悲 +情 +惑 +惟 +惠 +惡 +想 +惺 +愁 +意 +愚 +愛 +感 +愼 +慈 +態 +慕 +慣 +慧 +慾 +憂 +憤 +憺 +應 +懸 +戎 +成 +我 +戟 +戮 +戰 +戴 +戶 +房 +所 +手 +才 +打 +批 +承 +技 +抄 +把 +抗 +抱 +抽 +拇 +拓 +拘 +拙 +拜 +拾 +持 +指 +捌 +捨 +捿 +授 +掌 +排 +接 +推 +提 +揚 +揭 +援 +損 +搗 +摩 +播 +操 +擒 +擔 +擘 +據 +擧 +攘 +攝 +攬 +支 +改 +攻 +放 +政 +故 +敍 +敎 +救 +敗 +散 +敬 +整 +數 +文 +斗 +料 +斛 +斜 +斧 +斯 +新 +斷 +方 +於 +施 +旋 +族 +旗 +日 +旨 +早 +旱 +昌 +明 +易 +昔 +星 +春 +昧 +昭 +是 +時 +晉 +晋 +晩 +普 +景 +晴 +晶 +智 +暈 +暑 +暗 +暘 +曉 +曜 +曠 +曦 +曰 +曲 +書 +曹 +曼 +曾 +最 +會 +月 +有 +朋 +服 +望 +朝 +期 +木 +未 +末 +本 +朱 +朴 +李 +材 +村 +杖 +杜 +杞 +杭 +杯 +東 +松 +板 +林 +果 +枝 +枯 +枰 +枾 +柏 +柑 +柱 +栗 +校 +栢 +核 +根 +格 +桀 +桂 +案 +桎 +桑 +桓 +桔 +梁 +梏 +梓 +梗 +條 +梨 +梵 +棗 +棟 +森 +植 +椒 +楊 +楓 +楚 +業 +楮 +極 +榮 +槃 +槍 +樂 +樓 +樗 +樣 +樸 +樹 +樺 +樽 +橄 +橋 +橘 +機 +橡 +檀 +檎 +權 +欌 +欖 +次 +欲 +歌 +歐 +止 +正 +此 +步 +武 +歲 +歸 +死 +殖 +段 +殷 +殺 +殿 +毅 +母 +毒 +比 +毛 +氏 +民 +氣 +水 +永 +求 +汎 +汗 +江 +池 +沅 +沒 +沖 +沙 +沛 +河 +油 +治 +沼 +沿 +泉 +泊 +法 +泗 +泡 +波 +注 +泰 +洋 +洙 +洛 +洞 +津 +洲 +活 +派 +流 +浅 +浦 +浮 +浴 +海 +涅 +涇 +消 +涌 +液 +淑 +淡 +淨 +淫 +深 +淳 +淵 +淸 +渠 +渡 +游 +渾 +湖 +湯 +源 +溪 +溫 +溶 +滄 +滅 +滋 +滯 +滿 +漁 +漆 +漢 +漫 +漸 +潑 +潤 +潭 +澄 +澎 +澤 +澳 +澹 +濁 +濕 +濟 +濤 +濯 +瀋 +瀝 +灣 +火 +灰 +灸 +災 +炎 +炭 +点 +烈 +烏 +烙 +焚 +無 +焦 +然 +煌 +煎 +照 +煬 +煮 +熟 +熱 +燁 +燈 +燔 +燕 +燥 +燧 +燮 +爲 +爵 +父 +片 +版 +牌 +牛 +牝 +牟 +牡 +物 +特 +犧 +犬 +狀 +狗 +猥 +猩 +猪 +獨 +獵 +獸 +獻 +玄 +玉 +王 +玲 +珍 +珠 +珪 +班 +現 +球 +理 +琴 +瑞 +瑟 +瑪 +璃 +璋 +璽 +瓜 +瓦 +甑 +甘 +生 +産 +用 +甫 +田 +由 +甲 +申 +男 +界 +畏 +留 +畜 +畢 +略 +番 +異 +畵 +當 +畸 +疏 +疑 +疫 +疹 +疼 +病 +症 +痔 +痛 +痺 +瘀 +瘍 +瘡 +療 +癌 +癖 +登 +發 +白 +百 +的 +皆 +皇 +皮 +盂 +盆 +益 +盛 +盜 +盟 +盡 +盤 +盧 +目 +直 +相 +省 +看 +眞 +眼 +睡 +督 +瞋 +矢 +矣 +知 +短 +石 +破 +碍 +碑 +磁 +磨 +磬 +示 +社 +祇 +祖 +祝 +神 +祥 +祭 +祺 +禁 +禅 +禍 +福 +禦 +禪 +禮 +禹 +禽 +禾 +秀 +私 +秉 +秋 +科 +秘 +秤 +秦 +秩 +移 +稀 +稗 +種 +稱 +稷 +稼 +稽 +穀 +穆 +積 +空 +窮 +竅 +立 +章 +童 +竭 +端 +竹 +笑 +符 +第 +筆 +等 +筍 +答 +策 +箋 +箕 +管 +箱 +節 +篇 +簡 +米 +粉 +粘 +粥 +精 +糖 +糞 +系 +紀 +紂 +約 +紅 +紋 +純 +紙 +級 +素 +索 +紫 +紬 +累 +細 +紳 +終 +組 +結 +絡 +統 +絲 +絶 +絹 +經 +綠 +維 +綱 +網 +綸 +綽 +緖 +線 +緣 +緯 +縣 +縱 +總 +織 +繡 +繩 +繪 +繭 +纂 +續 +罕 +置 +罰 +羅 +羊 +美 +群 +義 +羽 +翁 +習 +翟 +老 +考 +者 +而 +耐 +耕 +耳 +聃 +聖 +聞 +聰 +聲 +職 +肇 +肉 +肖 +肝 +股 +肥 +育 +肺 +胃 +胎 +胚 +胞 +胡 +胥 +能 +脂 +脈 +脚 +脛 +脣 +脩 +脫 +脯 +脾 +腋 +腎 +腫 +腸 +腹 +膜 +膠 +膨 +膽 +臆 +臟 +臣 +臥 +臨 +自 +至 +致 +臺 +臼 +臾 +與 +興 +舊 +舌 +舍 +舒 +舜 +舟 +般 +船 +艦 +良 +色 +芋 +花 +芳 +芽 +苑 +苔 +苕 +苛 +苞 +若 +苦 +英 +茂 +茵 +茶 +茹 +荀 +荇 +草 +荒 +荷 +莊 +莫 +菊 +菌 +菜 +菩 +菫 +華 +菴 +菽 +萊 +萍 +萬 +落 +葉 +著 +葛 +董 +葬 +蒙 +蒜 +蒲 +蒸 +蒿 +蓮 +蔓 +蔘 +蔡 +蔬 +蕃 +蕉 +蕓 +薄 +薑 +薛 +薩 +薪 +薺 +藏 +藝 +藤 +藥 +藩 +藻 +蘆 +蘇 +蘊 +蘚 +蘭 +虎 +處 +虛 +虞 +虹 +蜀 +蜂 +蜜 +蝕 +蝶 +融 +蟬 +蟲 +蠶 +蠻 +血 +衆 +行 +術 +衛 +衡 +衣 +表 +袁 +裔 +裕 +裙 +補 +製 +複 +襄 +西 +要 +見 +視 +親 +覺 +觀 +角 +解 +言 +訂 +訊 +訓 +託 +記 +訣 +設 +診 +註 +評 +詩 +話 +詵 +誅 +誌 +認 +誕 +語 +誠 +誤 +誥 +誦 +說 +調 +談 +諍 +論 +諡 +諫 +諭 +諸 +謙 +講 +謝 +謠 +證 +識 +譚 +譜 +譯 +議 +護 +讀 +變 +谷 +豆 +豊 +豚 +象 +豪 +豫 +貝 +貞 +財 +貧 +貨 +貪 +貫 +貴 +貸 +費 +資 +賊 +賓 +賞 +賢 +賣 +賦 +質 +贍 +赤 +赫 +走 +起 +超 +越 +趙 +趣 +趨 +足 +趾 +跋 +跡 +路 +踏 +蹟 +身 +躬 +車 +軍 +軒 +軟 +載 +輓 +輕 +輪 +輯 +輸 +輻 +輿 +轅 +轉 +辨 +辭 +辯 +辰 +農 +近 +迦 +述 +追 +逆 +透 +逐 +通 +逝 +造 +逢 +連 +進 +逵 +遂 +遊 +運 +遍 +過 +道 +達 +遠 +遡 +適 +遷 +選 +遺 +遽 +還 +邊 +邑 +那 +邪 +郞 +郡 +部 +都 +鄒 +鄕 +鄭 +鄲 +配 +酒 +酸 +醉 +醫 +醯 +釋 +里 +重 +野 +量 +釐 +金 +針 +鈍 +鈴 +鉞 +銀 +銅 +銘 +鋼 +錄 +錢 +錦 +鎭 +鏡 +鐘 +鐵 +鑑 +鑛 +長 +門 +閃 +開 +間 +閔 +閣 +閥 +閭 +閻 +闕 +關 +阪 +防 +阿 +陀 +降 +限 +陝 +院 +陰 +陳 +陵 +陶 +陸 +陽 +隆 +隊 +隋 +階 +際 +障 +隣 +隨 +隱 +隷 +雀 +雄 +雅 +集 +雇 +雌 +雖 +雙 +雜 +離 +難 +雨 +雪 +雲 +電 +霜 +露 +靈 +靑 +靖 +靜 +非 +面 +革 +靴 +鞏 +韓 +音 +韶 +韻 +順 +須 +頊 +頌 +領 +頭 +顔 +願 +顚 +類 +顯 +風 +飛 +食 +飢 +飮 +飯 +飾 +養 +餓 +餘 +首 +香 +馨 +馬 +駒 +騫 +騷 +驕 +骨 +骸 +髓 +體 +高 +髥 +髮 +鬪 +鬱 +鬼 +魏 +魔 +魚 +魯 +鮮 +鰍 +鰐 +鳥 +鳧 +鳳 +鴨 +鵲 +鶴 +鷄 +鷹 +鹽 +鹿 +麗 +麥 +麻 +黃 +黑 +默 +點 +黨 +鼎 +齊 +齋 +齒 +龍 +龜 +가 +각 +간 +갇 +갈 +갉 +감 +갑 +값 +갓 +갔 +강 +갖 +갗 +같 +갚 +갛 +개 +객 +갠 +갤 +갬 +갭 +갯 +갰 +갱 +갸 +걀 +걔 +걘 +거 +걱 +건 +걷 +걸 +검 +겁 +것 +겄 +겅 +겆 +겉 +겊 +겋 +게 +겐 +겔 +겟 +겠 +겡 +겨 +격 +겪 +견 +결 +겸 +겹 +겻 +겼 +경 +곁 +계 +곕 +곗 +고 +곡 +곤 +곧 +골 +곪 +곬 +곯 +곰 +곱 +곳 +공 +곶 +과 +곽 +관 +괄 +괌 +광 +괘 +괜 +괭 +괴 +괸 +굉 +교 +구 +국 +군 +굳 +굴 +굵 +굶 +굼 +굽 +굿 +궁 +궂 +궈 +권 +궐 +궜 +궝 +궤 +귀 +귄 +귈 +귓 +규 +균 +귤 +그 +극 +근 +글 +긁 +금 +급 +긋 +긍 +기 +긴 +길 +김 +깁 +깃 +깅 +깊 +까 +깍 +깎 +깐 +깔 +깜 +깝 +깟 +깡 +깥 +깨 +깬 +깰 +깻 +깼 +깽 +꺄 +꺼 +꺽 +꺾 +껀 +껄 +껌 +껍 +껏 +껐 +껑 +께 +껴 +꼈 +꼍 +꼐 +꼬 +꼭 +꼴 +꼼 +꼽 +꼿 +꽁 +꽂 +꽃 +꽉 +꽝 +꽤 +꽥 +꾀 +꾜 +꾸 +꾹 +꾼 +꿀 +꿇 +꿈 +꿉 +꿋 +꿍 +꿎 +꿔 +꿨 +꿩 +꿰 +꿴 +뀄 +뀌 +뀐 +뀔 +뀜 +뀝 +끄 +끈 +끊 +끌 +끓 +끔 +끕 +끗 +끙 +끝 +끼 +끽 +낀 +낄 +낌 +낍 +낏 +낑 +나 +낙 +낚 +난 +낟 +날 +낡 +남 +납 +낫 +났 +낭 +낮 +낯 +낱 +낳 +내 +낵 +낸 +낼 +냄 +냅 +냇 +냈 +냉 +냐 +냔 +냘 +냥 +너 +넉 +넋 +넌 +널 +넓 +넘 +넙 +넛 +넜 +넝 +넣 +네 +넥 +넨 +넬 +넴 +넵 +넷 +넸 +넹 +녀 +녁 +년 +념 +녔 +녕 +녘 +녜 +노 +녹 +논 +놀 +놈 +놋 +농 +높 +놓 +놔 +놨 +뇌 +뇨 +뇩 +뇽 +누 +눅 +눈 +눌 +눔 +눕 +눗 +눠 +눴 +뉘 +뉜 +뉩 +뉴 +늄 +늅 +늉 +느 +늑 +는 +늘 +늙 +늠 +늡 +능 +늦 +늪 +늬 +니 +닉 +닌 +닐 +님 +닙 +닛 +닝 +닢 +다 +닥 +닦 +단 +닫 +달 +닭 +닮 +닯 +닳 +담 +답 +닷 +당 +닻 +닿 +대 +댁 +댄 +댈 +댐 +댑 +댓 +댔 +댕 +댜 +더 +덕 +덖 +던 +덜 +덟 +덤 +덥 +덧 +덩 +덫 +덮 +데 +덱 +덴 +델 +뎀 +뎃 +뎅 +뎌 +뎠 +뎨 +도 +독 +돈 +돋 +돌 +돔 +돕 +돗 +동 +돛 +돝 +돼 +됐 +되 +된 +될 +됨 +됩 +됴 +두 +둑 +둔 +둘 +둠 +둡 +둣 +둥 +둬 +뒀 +뒤 +뒬 +뒷 +뒹 +듀 +듈 +듐 +드 +득 +든 +듣 +들 +듦 +듬 +듭 +듯 +등 +듸 +디 +딕 +딘 +딛 +딜 +딤 +딥 +딧 +딨 +딩 +딪 +따 +딱 +딴 +딸 +땀 +땄 +땅 +때 +땐 +땔 +땜 +땝 +땠 +땡 +떠 +떡 +떤 +떨 +떫 +떰 +떱 +떳 +떴 +떵 +떻 +떼 +떽 +뗀 +뗄 +뗍 +뗏 +뗐 +뗑 +또 +똑 +똘 +똥 +뙤 +뚜 +뚝 +뚤 +뚫 +뚱 +뛰 +뛴 +뛸 +뜀 +뜁 +뜨 +뜩 +뜬 +뜯 +뜰 +뜸 +뜻 +띄 +띈 +띌 +띔 +띕 +띠 +띤 +띨 +띱 +띵 +라 +락 +란 +랄 +람 +랍 +랏 +랐 +랑 +랒 +랗 +래 +랙 +랜 +랠 +램 +랩 +랫 +랬 +랭 +랴 +략 +량 +러 +럭 +런 +럴 +럼 +럽 +럿 +렀 +렁 +렇 +레 +렉 +렌 +렐 +렘 +렙 +렛 +렝 +려 +력 +련 +렬 +렴 +렵 +렷 +렸 +령 +례 +로 +록 +론 +롤 +롬 +롭 +롯 +롱 +롸 +롹 +뢰 +뢴 +뢸 +룃 +료 +룐 +룡 +루 +룩 +룬 +룰 +룸 +룹 +룻 +룽 +뤄 +뤘 +뤼 +류 +륙 +륜 +률 +륨 +륭 +르 +륵 +른 +를 +름 +릅 +릇 +릉 +릎 +리 +릭 +린 +릴 +림 +립 +릿 +링 +마 +막 +만 +많 +맏 +말 +맑 +맘 +맙 +맛 +망 +맞 +맡 +맣 +매 +맥 +맨 +맬 +맴 +맵 +맷 +맸 +맹 +맺 +먀 +먁 +머 +먹 +먼 +멀 +멈 +멋 +멍 +멎 +메 +멕 +멘 +멜 +멤 +멥 +멧 +멩 +며 +멱 +면 +멸 +몄 +명 +몇 +모 +목 +몫 +몬 +몰 +몸 +몹 +못 +몽 +뫼 +묘 +무 +묵 +묶 +문 +묻 +물 +묽 +뭄 +뭅 +뭇 +뭉 +뭍 +뭏 +뭐 +뭔 +뭘 +뭡 +뭣 +뮈 +뮌 +뮐 +뮤 +뮬 +므 +믈 +믐 +미 +믹 +민 +믿 +밀 +밈 +밉 +밋 +밌 +밍 +및 +밑 +바 +박 +밖 +반 +받 +발 +밝 +밟 +밤 +밥 +밧 +방 +밭 +배 +백 +밴 +밸 +뱀 +뱁 +뱃 +뱄 +뱅 +뱉 +뱍 +뱐 +버 +벅 +번 +벌 +범 +법 +벗 +벙 +벚 +베 +벡 +벤 +벨 +벰 +벱 +벳 +벵 +벼 +벽 +변 +별 +볍 +볏 +볐 +병 +볕 +보 +복 +볶 +본 +볼 +봄 +봅 +봇 +봉 +봐 +봤 +뵈 +뵐 +뵙 +부 +북 +분 +붇 +불 +붉 +붐 +붓 +붕 +붙 +뷔 +뷰 +뷴 +뷸 +브 +븐 +블 +비 +빅 +빈 +빌 +빔 +빕 +빗 +빙 +빚 +빛 +빠 +빡 +빤 +빨 +빳 +빴 +빵 +빻 +빼 +빽 +뺀 +뺄 +뺌 +뺏 +뺐 +뺑 +뺨 +뻐 +뻑 +뻔 +뻗 +뻘 +뻣 +뻤 +뻥 +뻬 +뼈 +뼉 +뼘 +뽀 +뽈 +뽐 +뽑 +뽕 +뾰 +뿌 +뿍 +뿐 +뿔 +뿜 +쁘 +쁜 +쁠 +쁨 +삐 +삔 +삘 +사 +삭 +삯 +산 +살 +삵 +삶 +삼 +삽 +삿 +샀 +상 +샅 +새 +색 +샌 +샐 +샘 +샙 +샛 +샜 +생 +샤 +샨 +샬 +샴 +샵 +샷 +샹 +서 +석 +섞 +선 +섣 +설 +섬 +섭 +섯 +섰 +성 +섶 +세 +섹 +센 +셀 +셈 +셉 +셋 +셌 +셍 +셔 +션 +셜 +셨 +셰 +셴 +셸 +소 +속 +손 +솔 +솜 +솝 +솟 +송 +솥 +쇄 +쇠 +쇤 +쇳 +쇼 +숀 +숄 +숍 +수 +숙 +순 +숟 +술 +숨 +숩 +숫 +숭 +숯 +숱 +숲 +숴 +쉐 +쉘 +쉬 +쉭 +쉰 +쉴 +쉼 +쉽 +슈 +슐 +슘 +슛 +슝 +스 +슥 +슨 +슬 +슭 +슴 +습 +슷 +승 +시 +식 +신 +싣 +실 +싫 +심 +십 +싯 +싱 +싶 +싸 +싹 +싼 +쌀 +쌈 +쌉 +쌌 +쌍 +쌓 +쌔 +쌘 +쌩 +써 +썩 +썬 +썰 +썸 +썹 +썼 +썽 +쎄 +쎈 +쏘 +쏙 +쏜 +쏟 +쏠 +쏭 +쏴 +쐈 +쐐 +쐬 +쑤 +쑥 +쑨 +쒀 +쒔 +쓰 +쓱 +쓴 +쓸 +씀 +씁 +씌 +씨 +씩 +씬 +씰 +씸 +씹 +씻 +씽 +아 +악 +안 +앉 +않 +알 +앎 +앓 +암 +압 +앗 +았 +앙 +앞 +애 +액 +앤 +앨 +앰 +앱 +앳 +앴 +앵 +야 +약 +얀 +얄 +얇 +얌 +얍 +얏 +양 +얕 +얗 +얘 +얜 +어 +억 +언 +얹 +얻 +얼 +얽 +엄 +업 +없 +엇 +었 +엉 +엊 +엌 +엎 +에 +엑 +엔 +엘 +엠 +엡 +엣 +엥 +여 +역 +엮 +연 +열 +엷 +염 +엽 +엾 +엿 +였 +영 +옅 +옆 +옇 +예 +옌 +옐 +옙 +옛 +오 +옥 +온 +올 +옭 +옮 +옳 +옴 +옵 +옷 +옹 +옻 +와 +왁 +완 +왈 +왑 +왓 +왔 +왕 +왜 +왠 +왱 +외 +왼 +요 +욕 +욘 +욜 +욤 +용 +우 +욱 +운 +울 +움 +웁 +웃 +웅 +워 +웍 +원 +월 +웜 +웠 +웡 +웨 +웬 +웰 +웸 +웹 +위 +윅 +윈 +윌 +윔 +윗 +윙 +유 +육 +윤 +율 +윱 +윳 +융 +으 +윽 +은 +을 +읊 +음 +읍 +응 +의 +읜 +읠 +이 +익 +인 +일 +읽 +잃 +임 +입 +잇 +있 +잉 +잊 +잎 +자 +작 +잔 +잖 +잘 +잠 +잡 +잣 +잤 +장 +잦 +재 +잭 +잰 +잴 +잽 +잿 +쟀 +쟁 +쟈 +쟉 +쟤 +저 +적 +전 +절 +젊 +점 +접 +젓 +정 +젖 +제 +젝 +젠 +젤 +젬 +젭 +젯 +져 +젼 +졀 +졌 +졍 +조 +족 +존 +졸 +좀 +좁 +종 +좇 +좋 +좌 +좍 +좽 +죄 +죠 +죤 +주 +죽 +준 +줄 +줌 +줍 +줏 +중 +줘 +줬 +쥐 +쥔 +쥘 +쥬 +쥴 +즈 +즉 +즌 +즐 +즘 +즙 +증 +지 +직 +진 +짇 +질 +짊 +짐 +집 +짓 +징 +짖 +짙 +짚 +짜 +짝 +짠 +짢 +짤 +짧 +짬 +짭 +짰 +짱 +째 +짹 +짼 +쨀 +쨉 +쨋 +쨌 +쨍 +쩄 +쩌 +쩍 +쩐 +쩔 +쩜 +쩝 +쩡 +쩨 +쪄 +쪘 +쪼 +쪽 +쪾 +쫀 +쫄 +쫑 +쫓 +쫙 +쬐 +쭈 +쭉 +쭐 +쭙 +쯔 +쯤 +쯧 +찌 +찍 +찐 +찔 +찜 +찝 +찡 +찢 +찧 +차 +착 +찬 +찮 +찰 +참 +찹 +찻 +찼 +창 +찾 +채 +책 +챈 +챌 +챔 +챕 +챗 +챘 +챙 +챠 +챤 +처 +척 +천 +철 +첨 +첩 +첫 +청 +체 +첵 +첸 +첼 +쳄 +쳇 +쳉 +쳐 +쳔 +쳤 +초 +촉 +촌 +촘 +촛 +총 +촨 +촬 +최 +쵸 +추 +축 +춘 +출 +춤 +춥 +춧 +충 +춰 +췄 +췌 +취 +췬 +츄 +츠 +측 +츨 +츰 +층 +치 +칙 +친 +칠 +칡 +침 +칩 +칫 +칭 +카 +칵 +칸 +칼 +캄 +캅 +캇 +캉 +캐 +캔 +캘 +캠 +캡 +캣 +캤 +캥 +캬 +커 +컥 +컨 +컫 +컬 +컴 +컵 +컷 +컸 +컹 +케 +켄 +켈 +켐 +켓 +켕 +켜 +켠 +켤 +켭 +켯 +켰 +코 +콕 +콘 +콜 +콤 +콥 +콧 +콩 +콰 +콱 +콴 +콸 +쾅 +쾌 +쾡 +쾨 +쾰 +쿄 +쿠 +쿡 +쿤 +쿨 +쿰 +쿵 +쿼 +퀀 +퀄 +퀘 +퀭 +퀴 +퀵 +퀸 +퀼 +큐 +큘 +크 +큰 +클 +큼 +큽 +키 +킥 +킨 +킬 +킴 +킵 +킷 +킹 +타 +탁 +탄 +탈 +탉 +탐 +탑 +탓 +탔 +탕 +태 +택 +탠 +탤 +탬 +탭 +탯 +탰 +탱 +터 +턱 +턴 +털 +텀 +텁 +텃 +텄 +텅 +테 +텍 +텐 +텔 +템 +텝 +텡 +텨 +톈 +토 +톡 +톤 +톨 +톰 +톱 +톳 +통 +퇴 +툇 +투 +툭 +툰 +툴 +툼 +퉁 +퉈 +퉜 +튀 +튄 +튈 +튕 +튜 +튠 +튤 +튬 +트 +특 +튼 +튿 +틀 +틈 +틉 +틋 +틔 +티 +틱 +틴 +틸 +팀 +팁 +팅 +파 +팍 +팎 +판 +팔 +팜 +팝 +팟 +팠 +팡 +팥 +패 +팩 +팬 +팰 +팸 +팻 +팼 +팽 +퍼 +퍽 +펀 +펄 +펌 +펍 +펐 +펑 +페 +펙 +펜 +펠 +펨 +펩 +펫 +펭 +펴 +편 +펼 +폄 +폈 +평 +폐 +포 +폭 +폰 +폴 +폼 +폿 +퐁 +표 +푭 +푸 +푹 +푼 +풀 +품 +풋 +풍 +퓨 +퓬 +퓰 +퓸 +프 +픈 +플 +픔 +픕 +피 +픽 +핀 +필 +핌 +핍 +핏 +핑 +하 +학 +한 +할 +핥 +함 +합 +핫 +항 +해 +핵 +핸 +핼 +햄 +햅 +햇 +했 +행 +햐 +향 +헀 +허 +헉 +헌 +헐 +험 +헙 +헛 +헝 +헤 +헥 +헨 +헬 +헴 +헵 +헷 +헹 +혀 +혁 +현 +혈 +혐 +협 +혓 +혔 +형 +혜 +호 +혹 +혼 +홀 +홈 +홉 +홋 +홍 +홑 +화 +확 +환 +활 +홧 +황 +홰 +홱 +횃 +회 +획 +횝 +횟 +횡 +효 +후 +훅 +훈 +훌 +훑 +훔 +훗 +훤 +훨 +훼 +휄 +휑 +휘 +휙 +휜 +휠 +휩 +휭 +휴 +휼 +흄 +흉 +흐 +흑 +흔 +흘 +흙 +흠 +흡 +흣 +흥 +흩 +희 +흰 +흽 +히 +힉 +힌 +힐 +힘 +힙 +힝 +車 +滑 +金 +奈 +羅 +洛 +卵 +欄 +蘭 +郎 +來 +盧 +老 +魯 +綠 +鹿 +論 +雷 +樓 +縷 +凌 +樂 +不 +參 +葉 +沈 +若 +兩 +凉 +梁 +呂 +女 +廬 +麗 +黎 +曆 +歷 +戀 +蓮 +連 +列 +烈 +裂 +念 +獵 +靈 +領 +例 +禮 +醴 +惡 +尿 +料 +遼 +龍 +暈 +柳 +流 +類 +六 +陸 +倫 +律 +栗 +利 +李 +梨 +理 +離 +燐 +林 +臨 +立 +茶 +切 +宅 + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/latin_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/latin_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..e166bf33ecfbdc90ddb3d9743fded23306acabd5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/latin_dict.txt @@ -0,0 +1,185 @@ + +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +] +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +} +¡ +£ +§ +ª +« +­ +° +² +³ +´ +µ +· +º +» +¿ +À +Á + +Ä +Å +Ç +È +É +Ê +Ë +Ì +Í +Î +Ï +Ò +Ó +Ô +Õ +Ö +Ú +Ü +Ý +ß +à +á +â +ã +ä +å +æ +ç +è +é +ê +ë +ì +í +î +ï +ñ +ò +ó +ô +õ +ö +ø +ù +ú +û +ü +ý +ą +Ć +ć +Č +č +Đ +đ +ę +ı +Ł +ł +ō +Œ +œ +Š +š +Ÿ +Ž +ž +ʒ +β +δ +ε +з +Ṡ +‘ +€ +™ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_cdla_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_cdla_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..8be0f48600a88463d840fffe27eebd63629576ce --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_cdla_dict.txt @@ -0,0 +1,10 @@ +text +title +figure +figure_caption +table +table_caption +header +footer +reference +equation \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca6acf4eef8d4d5f9ba5a4ced4858a119a4ef983 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt @@ -0,0 +1,5 @@ +text +title +list +table +figure \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_table_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_table_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..faea15ea07d7d1a6f77dbd4287bb9fa87165cbb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/layout_dict/layout_table_dict.txt @@ -0,0 +1 @@ +table \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/mr_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/mr_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..283b1504ae344ed7db95050ddb9e3682126cc741 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/mr_dict.txt @@ -0,0 +1,153 @@ + +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +ँ +ं +ः +अ +आ +इ +ई +उ +ऊ +ए +ऐ +ऑ +ओ +औ +क +ख +ग +घ +च +छ +ज +झ +ञ +ट +ठ +ड +ढ +ण +त +थ +द +ध +न +प +फ +ब +भ +म +य +र +ऱ +ल +ळ +व +श +ष +स +ह +़ +ा +ि +ी +ु +ू +ृ +ॅ +े +ै +ॉ +ो +ौ +् +० +१ +२ +३ +४ +५ +६ +७ +८ +९ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ne_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ne_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a7df9537fc886c4de53ee68ab67b171b386780f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ne_dict.txt @@ -0,0 +1,153 @@ + +! +# +$ +% +& +' +( ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +_ +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +É +é +ः +अ +आ +इ +ई +उ +ऊ +ऋ +ए +ऐ +ओ +औ +क +ख +ग +घ +ङ +च +छ +ज +झ +ञ +ट +ठ +ड +ढ +ण +त +थ +द +ध +न +ऩ +प +फ +ब +भ +म +य +र +ऱ +ल +व +श +ष +स +ह +़ +ा +ि +ी +ु +ू +ृ +े +ै +ो +ौ +् +॒ +ॠ +। +० +१ +२ +३ +४ +५ +६ +७ +८ +९ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/oc_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/oc_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..e88af8bd85f4e01c43d08e5ba3ae6cadc5a465a4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/oc_dict.txt @@ -0,0 +1,96 @@ +o +c +_ +i +m +g +/ +2 +0 +I +L +S +V +R +C +1 +v +a +l +4 +3 +. +j +p +r +e +è +t +9 +7 +5 +8 +n +' +b +s +6 +q +u +á +d +ò +à +h +z +f +ï +í +A +ç +x +ó +é +P +O +Ò +ü +k +À +F +- +ú +­ +æ +Á +D +E +w +K +T +N +y +U +Z +G +B +J +H +M +W +Y +X +Q +% +$ +, +@ +& +! +: +( +# +? ++ +É + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/pu_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/pu_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..9500fae6e4976ea632bf579b533f82f176f3b7e7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/pu_dict.txt @@ -0,0 +1,130 @@ +p +u +_ +i +m +g +/ +8 +I +L +S +V +R +C +2 +0 +1 +v +a +l +6 +7 +4 +5 +. +j + +q +e +s +t +ã +o +x +9 +c +n +r +z +ç +õ +3 +A +U +d +º +ô +­ +, +E +; +ó +á +b +D +? +ú +ê +- +h +P +f +à +N +í +O +M +G +É +é +â +F +: +T +Á +" +Q +) +W +J +B +H +( +ö +% +Ö +« +w +K +y +! +k +] +' +Z ++ +Ç +Õ +Y +À +X +µ +» +ª +Í +ü +ä +´ +è +ñ +ß +ï +Ú +ë +Ô +Ï +Ó +[ +Ì +< + +ò +§ +³ +ø +å +# +$ +& +@ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rs_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rs_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..d1ce46d240841b8471cbb1209ee92864895c667c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rs_dict.txt @@ -0,0 +1,91 @@ +r +s +_ +i +m +g +/ +1 +I +L +S +V +R +C +2 +0 +v +a +l +7 +5 +8 +6 +. +j +p + +t +d +9 +3 +e +š +4 +k +u +ć +c +n +đ +o +z +č +b +ž +f +Z +T +h +M +F +O +Š +B +H +A +E +Đ +Ž +D +P +G +Č +K +U +N +J +Ć +w +y +W +x +Y +X +q +Q +# +& +$ +, +- +% +' +@ +! +: +? +( +É +é ++ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rsc_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rsc_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..95dd4636057e5b6dd8bd3a3dd6aacf19e790cffb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/rsc_dict.txt @@ -0,0 +1,134 @@ +r +s +c +_ +i +m +g +/ +5 +I +L +S +V +R +C +2 +0 +1 +v +a +l +9 +7 +8 +. +j +p +м +а +с +и +р +ћ +е +ш +3 +4 +о +г +н +з +в +л +6 +т +ж +у +к +п +њ +д +ч +С +ј +ф +ц +љ +х +О +И +А +б +Ш +К +ђ +џ +М +В +З +Д +Р +У +Н +Т +Б +? +П +Х +Ј +Ц +Г +Љ +Л +Ф +e +n +w +E +F +A +N +f +o +b +M +G +t +y +W +k +P +u +H +B +T +z +h +O +Y +d +U +K +D +x +X +J +Z +Q +q +' +- +@ +é +# +! +, +% +$ +: +& ++ +( +É + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ru_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ru_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b0cf3a8d6cd61ae395d1242dae3d42906029e2c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ru_dict.txt @@ -0,0 +1,125 @@ +к +в +а +з +и +у +р +о +н +я +х +п +л +ы +г +е +т +м +д +ж +ш +ь +с +ё +б +й +ч +ю +ц +щ +М +э +ф +А +ъ +С +Ф +Ю +В +К +Т +Н +О +Э +У +И +Г +Л +Р +Д +Б +Ш +П +З +Х +Е +Ж +Я +Ц +Ч +Й +Щ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/spin_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/spin_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ee8347fd9c85228a3cf46c810d4fc28ab05c492 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/spin_dict.txt @@ -0,0 +1,68 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +: +( +' +- +, +% +> +. +[ +? +) +" += +_ +* +] +; +& ++ +$ +@ +/ +| +! +< +# +` +{ +~ +\ +} +^ \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ta_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ta_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..19d81892c205627f296adbf8b20ea41aba2de5d0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ta_dict.txt @@ -0,0 +1,128 @@ +t +a +_ +i +m +g +/ +3 +I +L +S +V +R +C +2 +0 +1 +v +l +9 +7 +8 +. +j +p +ப +ூ +த +ம +ி +வ +ர +் +ந +ோ +ன +6 +ஆ +ற +ல +5 +ள +ா +ொ +ழ +ு +4 +ெ +ண +க +ட +ை +ே +ச +ய +ஒ +இ +அ +ங +உ +ீ +ஞ +எ +ஓ +ஃ +ஜ +ஷ +ஸ +ஏ +ஊ +ஹ +ஈ +ஐ +ௌ +ஔ +s +c +e +n +w +F +T +O +P +K +A +N +G +Y +E +M +H +U +B +o +b +D +d +r +W +u +y +f +X +k +q +h +J +z +Z +Q +x +- +' +$ +, +% +@ +é +! +# ++ +É +& +: +( +? + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ef028c786cbce6d1e25856c62986d757b31f93b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_dict.txt @@ -0,0 +1,277 @@ +← + +☆ +─ +α + + +⋅ +$ +ω +ψ +χ +( +υ +≥ +σ +, +ρ +ε +0 +■ +4 +8 +✗ +b +< +✓ +Ψ +Ω +€ +D +3 +Π +H +║ + +L +Φ +Χ +θ +P +κ +λ +μ +T +ξ +X +β +γ +δ +\ +ζ +η +` +d + +h +f +l +Θ +p +√ +t + +x +Β +Γ +Δ +| +ǂ +ɛ +j +̧ +➢ +⁡ +̌ +′ +« +△ +▲ +# +
+' +Ι ++ +¶ +/ +▼ +⇑ +□ +· +7 +▪ +; +? +➔ +∩ +C +÷ +G +⇒ +K + +O +S +С +W +Α +[ +○ +_ +● +‡ +c +z +g + +o + +〈 +〉 +s +⩽ +w +φ +ʹ +{ +» +∣ +̆ +e +ˆ +∈ +τ +◆ +ι +∅ +∆ +∙ +∘ +Ø +ß +✔ +∞ +∑ +− +× +◊ +∗ +∖ +˃ +˂ +∫ +" +i +& +π +↔ +* +∥ +æ +∧ +. +⁄ +ø +Q +∼ +6 +⁎ +: +★ +> +a +B +≈ +F +J +̄ +N +♯ +R +V + +― +Z +♣ +^ +¤ +¥ +§ + +¢ +£ +≦ +­ +≤ +‖ +Λ +© +n +↓ +→ +↑ +r +° +± +v + +♂ +k +♀ +~ +ᅟ +̇ +@ +” +♦ +ł +® +⊕ +„ +! + +% +⇓ +) +- +1 +5 +9 += +А +A +‰ +⋆ +Σ +E +◦ +I +※ +M +m +̨ +⩾ +† + +• +U +Y +
 +] +̸ +2 +‐ +– +‒ +̂ +— +̀ +́ +’ +‘ +⋮ +⋯ +̊ +“ +̈ +≧ +q +u +ı +y + +​ +̃ +} +ν diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_master_structure_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_master_structure_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..95ab2539a70aca4f695c53a38cdc1c3e164fcfb3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_master_structure_dict.txt @@ -0,0 +1,39 @@ + + + + + + + + + + + colspan="2" + colspan="3" + + + rowspan="2" + colspan="4" + colspan="6" + rowspan="3" + colspan="9" + colspan="10" + colspan="7" + rowspan="4" + rowspan="5" + rowspan="9" + colspan="8" + rowspan="8" + rowspan="6" + rowspan="7" + rowspan="10" + + + + + + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..8edb10b8817ad596af6c63b6b8fc5eb2349b7464 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict.txt @@ -0,0 +1,28 @@ + + + + + + + + + + colspan="2" + colspan="3" + rowspan="2" + colspan="4" + colspan="6" + rowspan="3" + colspan="9" + colspan="10" + colspan="7" + rowspan="4" + rowspan="5" + rowspan="9" + colspan="8" + rowspan="8" + rowspan="6" + rowspan="7" + rowspan="10" \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict_ch.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict_ch.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c59c0e9998a31f9d32f703625aa1c5ca7718c8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/table_structure_dict_ch.txt @@ -0,0 +1,48 @@ + + + + + + + + + + colspan="2" + colspan="3" + colspan="4" + colspan="5" + colspan="6" + colspan="7" + colspan="8" + colspan="9" + colspan="10" + colspan="11" + colspan="12" + colspan="13" + colspan="14" + colspan="15" + colspan="16" + colspan="17" + colspan="18" + colspan="19" + colspan="20" + rowspan="2" + rowspan="3" + rowspan="4" + rowspan="5" + rowspan="6" + rowspan="7" + rowspan="8" + rowspan="9" + rowspan="10" + rowspan="11" + rowspan="12" + rowspan="13" + rowspan="14" + rowspan="15" + rowspan="16" + rowspan="17" + rowspan="18" + rowspan="19" + rowspan="20" diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/te_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/te_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..83d74cc7e5f899ca43b23fa690d84d70bee535e3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/te_dict.txt @@ -0,0 +1,151 @@ +t +e +_ +i +m +g +/ +5 +I +L +S +V +R +C +2 +0 +1 +v +a +l +3 +4 +8 +9 +. +j +p +త +ె +ర +క +్ +ి +ం +చ +ే +ద +ు +7 +6 +ఉ +ా +మ +ట +ో +వ +ప +ల +శ +ఆ +య +ై +భ +' +ీ +గ +ూ +డ +ధ +హ +న +జ +స +[ +‌ +ష +అ +ణ +ఫ +బ +ఎ +; +ళ +థ +ొ +ఠ +ృ +ఒ +ఇ +ః +ఊ +ఖ +- +ఐ +ఘ +ౌ +ఏ +ఈ +ఛ +, +ఓ +ఞ +| +? +: +ఢ +" +( +” +! ++ +) +* += +& +“ +€ +] +£ +$ +s +c +n +w +k +J +G +u +d +r +E +o +h +y +b +f +B +M +O +T +N +D +P +A +F +x +W +Y +U +H +K +X +z +Z +Q +q +É +% +# +@ +é diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ug_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ug_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..77602f2cfd29d739478bc9e757bd82b71235554b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ug_dict.txt @@ -0,0 +1,114 @@ +u +g +_ +i +m +/ +1 +I +L +S +V +R +C +2 +0 +v +a +l +8 +5 +3 +6 +9 +. +j +p + +ق +ا +پ +ل +4 +7 +ئ +ى +ش +ت +ي +ك +د +ف +ر +و +ن +ب +ە +خ +ې +چ +ۇ +ز +س +م +ۋ +گ +ڭ +ۆ +ۈ +ج +غ +ھ +ژ +s +c +e +n +w +P +E +D +U +d +r +b +y +B +o +O +Y +N +T +k +t +h +A +H +F +z +W +K +G +M +f +Z +X +Q +J +x +q +- +! +% +# +? +: +$ +, +& +' +É +@ +é +( ++ diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/uk_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/uk_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..c5ffc0a53dbdf7af6d911097dffb8733d7d4eab1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/uk_dict.txt @@ -0,0 +1,142 @@ +u +k +_ +i +m +g +/ +1 +6 +I +L +S +V +R +C +2 +0 +v +a +l +7 +9 +. +j +p +в +і +д +п +о +н +с +т +ю +4 +5 +3 +а +и +м +е +р +ч +у +Б +з +л +к +8 +А +В +г +є +б +ь +х +ґ +ш +ц +ф +я +щ +ж +Г +Х +У +Т +Е +І +Н +П +З +Л +Ю +С +Д +М +К +Р +Ф +О +Ц +И +Я +Ч +Ш +Ж +Є +Ґ +Ь +s +c +e +n +w +A +P +r +E +t +o +h +d +y +M +G +N +F +B +T +D +U +O +W +Z +f +H +Y +b +K +z +x +Q +X +q +J +$ +- +' +# +& +% +? +: +! +, ++ +@ +( +é +É + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ur_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ur_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..c06786a83bc60039fa395d71e367bece1e80b11d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/ur_dict.txt @@ -0,0 +1,137 @@ +u +r +_ +i +m +g +/ +3 +I +L +S +V +R +C +2 +0 +1 +v +a +l +9 +7 +8 +. +j +p + +چ +ٹ +پ +ا +ئ +ی +ے +4 +6 +و +ل +ن +ڈ +ھ +ک +ت +ش +ف +ق +ر +د +5 +ب +ج +خ +ہ +س +ز +غ +ڑ +ں +آ +م +ؤ +ط +ص +ح +ع +گ +ث +ض +ذ +ۓ +ِ +ء +ظ +ً +ي +ُ +ۃ +أ +ٰ +ە +ژ +ۂ +ة +ّ +ك +ه +s +c +e +n +w +o +d +t +D +M +T +U +E +b +P +h +y +W +H +A +x +B +O +N +G +Y +Q +F +k +K +q +J +Z +f +z +X +' +@ +& +! +, +: +$ +- +# +? +% +é ++ +( +É diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/xi_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/xi_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..f195f1ea6ce90b09f5feecfc6c288eed423eeb8d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict/xi_dict.txt @@ -0,0 +1,110 @@ +x +i +_ +m +g +/ +1 +0 +I +L +S +V +R +C +2 +v +a +l +3 +6 +4 +5 +. +j +p + +Q +u +e +r +o +8 +7 +n +c +9 +t +b +é +q +d +ó +y +F +s +, +O +í +T +f +" +U +M +h +: +P +H +A +E +D +z +N +á +ñ +ú +% +; +è ++ +Y +- +B +G +( +) +¿ +? +w +¡ +! +X +É +K +k +Á +ü +Ú +« +» +J +' +ö +W +Z +º +Ö +­ +[ +] +Ç +ç +à +ä +û +ò +Í +ê +ô +ø +ª diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict90.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict90.txt new file mode 100644 index 0000000000000000000000000000000000000000..a945ae9c526e4faa68852eb3fb47d078a2f3f6ce --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/dict90.txt @@ -0,0 +1,90 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +: +; +< += +> +? +@ +[ +\ +] +_ +` +~ \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/Deteval.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/Deteval.py new file mode 100755 index 0000000000000000000000000000000000000000..45567a7dd2d82b6c583abd4a4eabef52974be081 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/Deteval.py @@ -0,0 +1,574 @@ +# Copyright (c) 2021 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. + +import numpy as np +import scipy.io as io +from ppocr.utils.e2e_metric.polygon_fast import iod, area_of_intersection, area + + +def get_socre_A(gt_dir, pred_dict): + allInputs = 1 + + def input_reading_mod(pred_dict): + """This helper reads input from txt files""" + det = [] + n = len(pred_dict) + for i in range(n): + points = pred_dict[i]['points'] + text = pred_dict[i]['texts'] + point = ",".join(map(str, points.reshape(-1, ))) + det.append([point, text]) + return det + + def gt_reading_mod(gt_dict): + """This helper reads groundtruths from mat files""" + gt = [] + n = len(gt_dict) + for i in range(n): + points = gt_dict[i]['points'].tolist() + h = len(points) + text = gt_dict[i]['text'] + xx = [ + np.array( + ['x:'], dtype=' 1): + gt_x = list(map(int, np.squeeze(gt[1]))) + gt_y = list(map(int, np.squeeze(gt[3]))) + for det_id, detection in enumerate(detections): + detection_orig = detection + detection = [float(x) for x in detection[0].split(',')] + detection = list(map(int, detection)) + det_x = detection[0::2] + det_y = detection[1::2] + det_gt_iou = iod(det_x, det_y, gt_x, gt_y) + if det_gt_iou > threshold: + detections[det_id] = [] + + detections[:] = [item for item in detections if item != []] + return detections + + def sigma_calculation(det_x, det_y, gt_x, gt_y): + """ + sigma = inter_area / gt_area + """ + return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / + area(gt_x, gt_y)), 2) + + def tau_calculation(det_x, det_y, gt_x, gt_y): + if area(det_x, det_y) == 0.0: + return 0 + return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / + area(det_x, det_y)), 2) + + ##############################Initialization################################### + # global_sigma = [] + # global_tau = [] + # global_pred_str = [] + # global_gt_str = [] + ############################################################################### + + for input_id in range(allInputs): + if (input_id != '.DS_Store') and (input_id != 'Pascal_result.txt') and ( + input_id != 'Pascal_result_curved.txt') and (input_id != 'Pascal_result_non_curved.txt') and ( + input_id != 'Deteval_result.txt') and (input_id != 'Deteval_result_curved.txt') \ + and (input_id != 'Deteval_result_non_curved.txt'): + detections = input_reading_mod(pred_dict) + groundtruths = gt_reading_mod(gt_dir) + detections = detection_filtering( + detections, + groundtruths) # filters detections overlapping with DC area + dc_id = [] + for i in range(len(groundtruths)): + if groundtruths[i][5] == '#': + dc_id.append(i) + cnt = 0 + for a in dc_id: + num = a - cnt + del groundtruths[num] + cnt += 1 + + local_sigma_table = np.zeros((len(groundtruths), len(detections))) + local_tau_table = np.zeros((len(groundtruths), len(detections))) + local_pred_str = {} + local_gt_str = {} + + for gt_id, gt in enumerate(groundtruths): + if len(detections) > 0: + for det_id, detection in enumerate(detections): + detection_orig = detection + detection = [float(x) for x in detection[0].split(',')] + detection = list(map(int, detection)) + pred_seq_str = detection_orig[1].strip() + det_x = detection[0::2] + det_y = detection[1::2] + gt_x = list(map(int, np.squeeze(gt[1]))) + gt_y = list(map(int, np.squeeze(gt[3]))) + gt_seq_str = str(gt[4].tolist()[0]) + + local_sigma_table[gt_id, det_id] = sigma_calculation( + det_x, det_y, gt_x, gt_y) + local_tau_table[gt_id, det_id] = tau_calculation( + det_x, det_y, gt_x, gt_y) + local_pred_str[det_id] = pred_seq_str + local_gt_str[gt_id] = gt_seq_str + + global_sigma = local_sigma_table + global_tau = local_tau_table + global_pred_str = local_pred_str + global_gt_str = local_gt_str + + single_data = {} + single_data['sigma'] = global_sigma + single_data['global_tau'] = global_tau + single_data['global_pred_str'] = global_pred_str + single_data['global_gt_str'] = global_gt_str + return single_data + + +def get_socre_B(gt_dir, img_id, pred_dict): + allInputs = 1 + + def input_reading_mod(pred_dict): + """This helper reads input from txt files""" + det = [] + n = len(pred_dict) + for i in range(n): + points = pred_dict[i]['points'] + text = pred_dict[i]['texts'] + point = ",".join(map(str, points.reshape(-1, ))) + det.append([point, text]) + return det + + def gt_reading_mod(gt_dir, gt_id): + gt = io.loadmat('%s/poly_gt_img%s.mat' % (gt_dir, gt_id)) + gt = gt['polygt'] + return gt + + def detection_filtering(detections, groundtruths, threshold=0.5): + for gt_id, gt in enumerate(groundtruths): + if (gt[5] == '#') and (gt[1].shape[1] > 1): + gt_x = list(map(int, np.squeeze(gt[1]))) + gt_y = list(map(int, np.squeeze(gt[3]))) + for det_id, detection in enumerate(detections): + detection_orig = detection + detection = [float(x) for x in detection[0].split(',')] + detection = list(map(int, detection)) + det_x = detection[0::2] + det_y = detection[1::2] + det_gt_iou = iod(det_x, det_y, gt_x, gt_y) + if det_gt_iou > threshold: + detections[det_id] = [] + + detections[:] = [item for item in detections if item != []] + return detections + + def sigma_calculation(det_x, det_y, gt_x, gt_y): + """ + sigma = inter_area / gt_area + """ + return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / + area(gt_x, gt_y)), 2) + + def tau_calculation(det_x, det_y, gt_x, gt_y): + if area(det_x, det_y) == 0.0: + return 0 + return np.round((area_of_intersection(det_x, det_y, gt_x, gt_y) / + area(det_x, det_y)), 2) + + ##############################Initialization################################### + # global_sigma = [] + # global_tau = [] + # global_pred_str = [] + # global_gt_str = [] + ############################################################################### + + for input_id in range(allInputs): + if (input_id != '.DS_Store') and (input_id != 'Pascal_result.txt') and ( + input_id != 'Pascal_result_curved.txt') and (input_id != 'Pascal_result_non_curved.txt') and ( + input_id != 'Deteval_result.txt') and (input_id != 'Deteval_result_curved.txt') \ + and (input_id != 'Deteval_result_non_curved.txt'): + detections = input_reading_mod(pred_dict) + groundtruths = gt_reading_mod(gt_dir, img_id).tolist() + detections = detection_filtering( + detections, + groundtruths) # filters detections overlapping with DC area + dc_id = [] + for i in range(len(groundtruths)): + if groundtruths[i][5] == '#': + dc_id.append(i) + cnt = 0 + for a in dc_id: + num = a - cnt + del groundtruths[num] + cnt += 1 + + local_sigma_table = np.zeros((len(groundtruths), len(detections))) + local_tau_table = np.zeros((len(groundtruths), len(detections))) + local_pred_str = {} + local_gt_str = {} + + for gt_id, gt in enumerate(groundtruths): + if len(detections) > 0: + for det_id, detection in enumerate(detections): + detection_orig = detection + detection = [float(x) for x in detection[0].split(',')] + detection = list(map(int, detection)) + pred_seq_str = detection_orig[1].strip() + det_x = detection[0::2] + det_y = detection[1::2] + gt_x = list(map(int, np.squeeze(gt[1]))) + gt_y = list(map(int, np.squeeze(gt[3]))) + gt_seq_str = str(gt[4].tolist()[0]) + + local_sigma_table[gt_id, det_id] = sigma_calculation( + det_x, det_y, gt_x, gt_y) + local_tau_table[gt_id, det_id] = tau_calculation( + det_x, det_y, gt_x, gt_y) + local_pred_str[det_id] = pred_seq_str + local_gt_str[gt_id] = gt_seq_str + + global_sigma = local_sigma_table + global_tau = local_tau_table + global_pred_str = local_pred_str + global_gt_str = local_gt_str + + single_data = {} + single_data['sigma'] = global_sigma + single_data['global_tau'] = global_tau + single_data['global_pred_str'] = global_pred_str + single_data['global_gt_str'] = global_gt_str + return single_data + + +def combine_results(all_data): + tr = 0.7 + tp = 0.6 + fsc_k = 0.8 + k = 2 + global_sigma = [] + global_tau = [] + global_pred_str = [] + global_gt_str = [] + for data in all_data: + global_sigma.append(data['sigma']) + global_tau.append(data['global_tau']) + global_pred_str.append(data['global_pred_str']) + global_gt_str.append(data['global_gt_str']) + + global_accumulative_recall = 0 + global_accumulative_precision = 0 + total_num_gt = 0 + total_num_det = 0 + hit_str_count = 0 + hit_count = 0 + + def one_to_one(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idy): + hit_str_num = 0 + for gt_id in range(num_gt): + gt_matching_qualified_sigma_candidates = np.where( + local_sigma_table[gt_id, :] > tr) + gt_matching_num_qualified_sigma_candidates = gt_matching_qualified_sigma_candidates[ + 0].shape[0] + gt_matching_qualified_tau_candidates = np.where( + local_tau_table[gt_id, :] > tp) + gt_matching_num_qualified_tau_candidates = gt_matching_qualified_tau_candidates[ + 0].shape[0] + + det_matching_qualified_sigma_candidates = np.where( + local_sigma_table[:, gt_matching_qualified_sigma_candidates[0]] + > tr) + det_matching_num_qualified_sigma_candidates = det_matching_qualified_sigma_candidates[ + 0].shape[0] + det_matching_qualified_tau_candidates = np.where( + local_tau_table[:, gt_matching_qualified_tau_candidates[0]] > + tp) + det_matching_num_qualified_tau_candidates = det_matching_qualified_tau_candidates[ + 0].shape[0] + + if (gt_matching_num_qualified_sigma_candidates == 1) and (gt_matching_num_qualified_tau_candidates == 1) and \ + (det_matching_num_qualified_sigma_candidates == 1) and ( + det_matching_num_qualified_tau_candidates == 1): + global_accumulative_recall = global_accumulative_recall + 1.0 + global_accumulative_precision = global_accumulative_precision + 1.0 + local_accumulative_recall = local_accumulative_recall + 1.0 + local_accumulative_precision = local_accumulative_precision + 1.0 + + gt_flag[0, gt_id] = 1 + matched_det_id = np.where(local_sigma_table[gt_id, :] > tr) + # recg start + gt_str_cur = global_gt_str[idy][gt_id] + pred_str_cur = global_pred_str[idy][matched_det_id[0].tolist()[ + 0]] + if pred_str_cur == gt_str_cur: + hit_str_num += 1 + else: + if pred_str_cur.lower() == gt_str_cur.lower(): + hit_str_num += 1 + # recg end + det_flag[0, matched_det_id] = 1 + return local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, gt_flag, det_flag, hit_str_num + + def one_to_many(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idy): + hit_str_num = 0 + for gt_id in range(num_gt): + # skip the following if the groundtruth was matched + if gt_flag[0, gt_id] > 0: + continue + + non_zero_in_sigma = np.where(local_sigma_table[gt_id, :] > 0) + num_non_zero_in_sigma = non_zero_in_sigma[0].shape[0] + + if num_non_zero_in_sigma >= k: + ####search for all detections that overlaps with this groundtruth + qualified_tau_candidates = np.where((local_tau_table[ + gt_id, :] >= tp) & (det_flag[0, :] == 0)) + num_qualified_tau_candidates = qualified_tau_candidates[ + 0].shape[0] + + if num_qualified_tau_candidates == 1: + if ((local_tau_table[gt_id, qualified_tau_candidates] >= tp) + and + (local_sigma_table[gt_id, qualified_tau_candidates] >= + tr)): + # became an one-to-one case + global_accumulative_recall = global_accumulative_recall + 1.0 + global_accumulative_precision = global_accumulative_precision + 1.0 + local_accumulative_recall = local_accumulative_recall + 1.0 + local_accumulative_precision = local_accumulative_precision + 1.0 + + gt_flag[0, gt_id] = 1 + det_flag[0, qualified_tau_candidates] = 1 + # recg start + gt_str_cur = global_gt_str[idy][gt_id] + pred_str_cur = global_pred_str[idy][ + qualified_tau_candidates[0].tolist()[0]] + if pred_str_cur == gt_str_cur: + hit_str_num += 1 + else: + if pred_str_cur.lower() == gt_str_cur.lower(): + hit_str_num += 1 + # recg end + elif (np.sum(local_sigma_table[gt_id, qualified_tau_candidates]) + >= tr): + gt_flag[0, gt_id] = 1 + det_flag[0, qualified_tau_candidates] = 1 + # recg start + gt_str_cur = global_gt_str[idy][gt_id] + pred_str_cur = global_pred_str[idy][ + qualified_tau_candidates[0].tolist()[0]] + if pred_str_cur == gt_str_cur: + hit_str_num += 1 + else: + if pred_str_cur.lower() == gt_str_cur.lower(): + hit_str_num += 1 + # recg end + + global_accumulative_recall = global_accumulative_recall + fsc_k + global_accumulative_precision = global_accumulative_precision + num_qualified_tau_candidates * fsc_k + + local_accumulative_recall = local_accumulative_recall + fsc_k + local_accumulative_precision = local_accumulative_precision + num_qualified_tau_candidates * fsc_k + + return local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, gt_flag, det_flag, hit_str_num + + def many_to_one(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idy): + hit_str_num = 0 + for det_id in range(num_det): + # skip the following if the detection was matched + if det_flag[0, det_id] > 0: + continue + + non_zero_in_tau = np.where(local_tau_table[:, det_id] > 0) + num_non_zero_in_tau = non_zero_in_tau[0].shape[0] + + if num_non_zero_in_tau >= k: + ####search for all detections that overlaps with this groundtruth + qualified_sigma_candidates = np.where(( + local_sigma_table[:, det_id] >= tp) & (gt_flag[0, :] == 0)) + num_qualified_sigma_candidates = qualified_sigma_candidates[ + 0].shape[0] + + if num_qualified_sigma_candidates == 1: + if ((local_tau_table[qualified_sigma_candidates, det_id] >= + tp) and + (local_sigma_table[qualified_sigma_candidates, det_id] + >= tr)): + # became an one-to-one case + global_accumulative_recall = global_accumulative_recall + 1.0 + global_accumulative_precision = global_accumulative_precision + 1.0 + local_accumulative_recall = local_accumulative_recall + 1.0 + local_accumulative_precision = local_accumulative_precision + 1.0 + + gt_flag[0, qualified_sigma_candidates] = 1 + det_flag[0, det_id] = 1 + # recg start + pred_str_cur = global_pred_str[idy][det_id] + gt_len = len(qualified_sigma_candidates[0]) + for idx in range(gt_len): + ele_gt_id = qualified_sigma_candidates[0].tolist()[ + idx] + if ele_gt_id not in global_gt_str[idy]: + continue + gt_str_cur = global_gt_str[idy][ele_gt_id] + if pred_str_cur == gt_str_cur: + hit_str_num += 1 + break + else: + if pred_str_cur.lower() == gt_str_cur.lower(): + hit_str_num += 1 + break + # recg end + elif (np.sum(local_tau_table[qualified_sigma_candidates, + det_id]) >= tp): + det_flag[0, det_id] = 1 + gt_flag[0, qualified_sigma_candidates] = 1 + # recg start + pred_str_cur = global_pred_str[idy][det_id] + gt_len = len(qualified_sigma_candidates[0]) + for idx in range(gt_len): + ele_gt_id = qualified_sigma_candidates[0].tolist()[idx] + if ele_gt_id not in global_gt_str[idy]: + continue + gt_str_cur = global_gt_str[idy][ele_gt_id] + if pred_str_cur == gt_str_cur: + hit_str_num += 1 + break + else: + if pred_str_cur.lower() == gt_str_cur.lower(): + hit_str_num += 1 + break + # recg end + + global_accumulative_recall = global_accumulative_recall + num_qualified_sigma_candidates * fsc_k + global_accumulative_precision = global_accumulative_precision + fsc_k + + local_accumulative_recall = local_accumulative_recall + num_qualified_sigma_candidates * fsc_k + local_accumulative_precision = local_accumulative_precision + fsc_k + return local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, gt_flag, det_flag, hit_str_num + + for idx in range(len(global_sigma)): + local_sigma_table = np.array(global_sigma[idx]) + local_tau_table = global_tau[idx] + + num_gt = local_sigma_table.shape[0] + num_det = local_sigma_table.shape[1] + + total_num_gt = total_num_gt + num_gt + total_num_det = total_num_det + num_det + + local_accumulative_recall = 0 + local_accumulative_precision = 0 + gt_flag = np.zeros((1, num_gt)) + det_flag = np.zeros((1, num_det)) + + #######first check for one-to-one case########## + local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, \ + gt_flag, det_flag, hit_str_num = one_to_one(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idx) + + hit_str_count += hit_str_num + #######then check for one-to-many case########## + local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, \ + gt_flag, det_flag, hit_str_num = one_to_many(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idx) + hit_str_count += hit_str_num + #######then check for many-to-one case########## + local_accumulative_recall, local_accumulative_precision, global_accumulative_recall, global_accumulative_precision, \ + gt_flag, det_flag, hit_str_num = many_to_one(local_sigma_table, local_tau_table, + local_accumulative_recall, local_accumulative_precision, + global_accumulative_recall, global_accumulative_precision, + gt_flag, det_flag, idx) + hit_str_count += hit_str_num + + try: + recall = global_accumulative_recall / total_num_gt + except ZeroDivisionError: + recall = 0 + + try: + precision = global_accumulative_precision / total_num_det + except ZeroDivisionError: + precision = 0 + + try: + f_score = 2 * precision * recall / (precision + recall) + except ZeroDivisionError: + f_score = 0 + + try: + seqerr = 1 - float(hit_str_count) / global_accumulative_recall + except ZeroDivisionError: + seqerr = 1 + + try: + recall_e2e = float(hit_str_count) / total_num_gt + except ZeroDivisionError: + recall_e2e = 0 + + try: + precision_e2e = float(hit_str_count) / total_num_det + except ZeroDivisionError: + precision_e2e = 0 + + try: + f_score_e2e = 2 * precision_e2e * recall_e2e / ( + precision_e2e + recall_e2e) + except ZeroDivisionError: + f_score_e2e = 0 + + final = { + 'total_num_gt': total_num_gt, + 'total_num_det': total_num_det, + 'global_accumulative_recall': global_accumulative_recall, + 'hit_str_count': hit_str_count, + 'recall': recall, + 'precision': precision, + 'f_score': f_score, + 'seqerr': seqerr, + 'recall_e2e': recall_e2e, + 'precision_e2e': precision_e2e, + 'f_score_e2e': f_score_e2e + } + return final diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/polygon_fast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/polygon_fast.py new file mode 100755 index 0000000000000000000000000000000000000000..81c9ad70675bb37a95968283b6dc6f42f709df27 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_metric/polygon_fast.py @@ -0,0 +1,83 @@ +# Copyright (c) 2021 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. +import numpy as np +from shapely.geometry import Polygon +""" +:param det_x: [1, N] Xs of detection's vertices +:param det_y: [1, N] Ys of detection's vertices +:param gt_x: [1, N] Xs of groundtruth's vertices +:param gt_y: [1, N] Ys of groundtruth's vertices + +############## +All the calculation of 'AREA' in this script is handled by: +1) First generating a binary mask with the polygon area filled up with 1's +2) Summing up all the 1's +""" + + +def area(x, y): + polygon = Polygon(np.stack([x, y], axis=1)) + return float(polygon.area) + + +def approx_area_of_intersection(det_x, det_y, gt_x, gt_y): + """ + This helper determine if both polygons are intersecting with each others with an approximation method. + Area of intersection represented by the minimum bounding rectangular [xmin, ymin, xmax, ymax] + """ + det_ymax = np.max(det_y) + det_xmax = np.max(det_x) + det_ymin = np.min(det_y) + det_xmin = np.min(det_x) + + gt_ymax = np.max(gt_y) + gt_xmax = np.max(gt_x) + gt_ymin = np.min(gt_y) + gt_xmin = np.min(gt_x) + + all_min_ymax = np.minimum(det_ymax, gt_ymax) + all_max_ymin = np.maximum(det_ymin, gt_ymin) + + intersect_heights = np.maximum(0.0, (all_min_ymax - all_max_ymin)) + + all_min_xmax = np.minimum(det_xmax, gt_xmax) + all_max_xmin = np.maximum(det_xmin, gt_xmin) + intersect_widths = np.maximum(0.0, (all_min_xmax - all_max_xmin)) + + return intersect_heights * intersect_widths + + +def area_of_intersection(det_x, det_y, gt_x, gt_y): + p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0) + p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0) + return float(p1.intersection(p2).area) + + +def area_of_union(det_x, det_y, gt_x, gt_y): + p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0) + p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0) + return float(p1.union(p2).area) + + +def iou(det_x, det_y, gt_x, gt_y): + return area_of_intersection(det_x, det_y, gt_x, gt_y) / ( + area_of_union(det_x, det_y, gt_x, gt_y) + 1.0) + + +def iod(det_x, det_y, gt_x, gt_y): + """ + This helper determine the fraction of intersection area over detection area + """ + return area_of_intersection(det_x, det_y, gt_x, gt_y) / ( + area(det_x, det_y) + 1.0) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_batchsize.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_batchsize.py new file mode 100644 index 0000000000000000000000000000000000000000..e99a833ea76a81e02d39b16fe1a01e22f15bf3a4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_batchsize.py @@ -0,0 +1,87 @@ +import paddle +import numpy as np +import copy + + +def org_tcl_rois(batch_size, pos_lists, pos_masks, label_lists, tcl_bs): + """ + """ + pos_lists_, pos_masks_, label_lists_ = [], [], [] + img_bs = batch_size + ngpu = int(batch_size / img_bs) + img_ids = np.array(pos_lists, dtype=np.int32)[:, 0, 0].copy() + pos_lists_split, pos_masks_split, label_lists_split = [], [], [] + for i in range(ngpu): + pos_lists_split.append([]) + pos_masks_split.append([]) + label_lists_split.append([]) + + for i in range(img_ids.shape[0]): + img_id = img_ids[i] + gpu_id = int(img_id / img_bs) + img_id = img_id % img_bs + pos_list = pos_lists[i].copy() + pos_list[:, 0] = img_id + pos_lists_split[gpu_id].append(pos_list) + pos_masks_split[gpu_id].append(pos_masks[i].copy()) + label_lists_split[gpu_id].append(copy.deepcopy(label_lists[i])) + # repeat or delete + for i in range(ngpu): + vp_len = len(pos_lists_split[i]) + if vp_len <= tcl_bs: + for j in range(0, tcl_bs - vp_len): + pos_list = pos_lists_split[i][j].copy() + pos_lists_split[i].append(pos_list) + pos_mask = pos_masks_split[i][j].copy() + pos_masks_split[i].append(pos_mask) + label_list = copy.deepcopy(label_lists_split[i][j]) + label_lists_split[i].append(label_list) + else: + for j in range(0, vp_len - tcl_bs): + c_len = len(pos_lists_split[i]) + pop_id = np.random.permutation(c_len)[0] + pos_lists_split[i].pop(pop_id) + pos_masks_split[i].pop(pop_id) + label_lists_split[i].pop(pop_id) + # merge + for i in range(ngpu): + pos_lists_.extend(pos_lists_split[i]) + pos_masks_.extend(pos_masks_split[i]) + label_lists_.extend(label_lists_split[i]) + return pos_lists_, pos_masks_, label_lists_ + + +def pre_process(label_list, pos_list, pos_mask, max_text_length, max_text_nums, + pad_num, tcl_bs): + label_list = label_list.numpy() + batch, _, _, _ = label_list.shape + pos_list = pos_list.numpy() + pos_mask = pos_mask.numpy() + pos_list_t = [] + pos_mask_t = [] + label_list_t = [] + for i in range(batch): + for j in range(max_text_nums): + if pos_mask[i, j].any(): + pos_list_t.append(pos_list[i][j]) + pos_mask_t.append(pos_mask[i][j]) + label_list_t.append(label_list[i][j]) + pos_list, pos_mask, label_list = org_tcl_rois(batch, pos_list_t, pos_mask_t, + label_list_t, tcl_bs) + label = [] + tt = [l.tolist() for l in label_list] + for i in range(tcl_bs): + k = 0 + for j in range(max_text_length): + if tt[i][j][0] != pad_num: + k += 1 + else: + break + label.append(k) + label = paddle.to_tensor(label) + label = paddle.cast(label, dtype='int64') + pos_list = paddle.to_tensor(pos_list) + pos_mask = paddle.to_tensor(pos_mask) + label_list = paddle.squeeze(paddle.to_tensor(label_list), axis=2) + label_list = paddle.cast(label_list, dtype='int32') + return pos_list, pos_mask, label_list, label diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_fast.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..787cd3017fafa6fc554bead0cc05b5bfe682df42 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_fast.py @@ -0,0 +1,457 @@ +# Copyright (c) 2021 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. +"""Contains various CTC decoders.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import cv2 +import math + +import numpy as np +from itertools import groupby +from skimage.morphology._skeletonize import thin + + +def get_dict(character_dict_path): + character_str = "" + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + character_str += line + dict_character = list(character_str) + return dict_character + + +def softmax(logits): + """ + logits: N x d + """ + max_value = np.max(logits, axis=1, keepdims=True) + exp = np.exp(logits - max_value) + exp_sum = np.sum(exp, axis=1, keepdims=True) + dist = exp / exp_sum + return dist + + +def get_keep_pos_idxs(labels, remove_blank=None): + """ + Remove duplicate and get pos idxs of keep items. + The value of keep_blank should be [None, 95]. + """ + duplicate_len_list = [] + keep_pos_idx_list = [] + keep_char_idx_list = [] + for k, v_ in groupby(labels): + current_len = len(list(v_)) + if k != remove_blank: + current_idx = int(sum(duplicate_len_list) + current_len // 2) + keep_pos_idx_list.append(current_idx) + keep_char_idx_list.append(k) + duplicate_len_list.append(current_len) + return keep_char_idx_list, keep_pos_idx_list + + +def remove_blank(labels, blank=0): + new_labels = [x for x in labels if x != blank] + return new_labels + + +def insert_blank(labels, blank=0): + new_labels = [blank] + for l in labels: + new_labels += [l, blank] + return new_labels + + +def ctc_greedy_decoder(probs_seq, blank=95, keep_blank_in_idxs=True): + """ + CTC greedy (best path) decoder. + """ + raw_str = np.argmax(np.array(probs_seq), axis=1) + remove_blank_in_pos = None if keep_blank_in_idxs else blank + dedup_str, keep_idx_list = get_keep_pos_idxs( + raw_str, remove_blank=remove_blank_in_pos) + dst_str = remove_blank(dedup_str, blank=blank) + return dst_str, keep_idx_list + + +def instance_ctc_greedy_decoder(gather_info, logits_map, pts_num=4): + _, _, C = logits_map.shape + ys, xs = zip(*gather_info) + logits_seq = logits_map[list(ys), list(xs)] + probs_seq = logits_seq + labels = np.argmax(probs_seq, axis=1) + dst_str = [k for k, v_ in groupby(labels) if k != C - 1] + detal = len(gather_info) // (pts_num - 1) + keep_idx_list = [0] + [detal * (i + 1) for i in range(pts_num - 2)] + [-1] + keep_gather_list = [gather_info[idx] for idx in keep_idx_list] + return dst_str, keep_gather_list + + +def ctc_decoder_for_image(gather_info_list, + logits_map, + Lexicon_Table, + pts_num=6): + """ + CTC decoder using multiple processes. + """ + decoder_str = [] + decoder_xys = [] + for gather_info in gather_info_list: + if len(gather_info) < pts_num: + continue + dst_str, xys_list = instance_ctc_greedy_decoder( + gather_info, logits_map, pts_num=pts_num) + dst_str_readable = ''.join([Lexicon_Table[idx] for idx in dst_str]) + if len(dst_str_readable) < 2: + continue + decoder_str.append(dst_str_readable) + decoder_xys.append(xys_list) + return decoder_str, decoder_xys + + +def sort_with_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + + def sort_part_with_direction(pos_list, point_direction): + pos_list = np.array(pos_list).reshape(-1, 2) + point_direction = np.array(point_direction).reshape(-1, 2) + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list[np.argsort(pos_proj_leng)].tolist() + sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist() + return sorted_list, sorted_direction + + pos_list = np.array(pos_list).reshape(-1, 2) + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + sorted_point, sorted_direction = sort_part_with_direction(pos_list, + point_direction) + + point_num = len(sorted_point) + if point_num >= 16: + middle_num = point_num // 2 + first_part_point = sorted_point[:middle_num] + first_point_direction = sorted_direction[:middle_num] + sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction( + first_part_point, first_point_direction) + + last_part_point = sorted_point[middle_num:] + last_point_direction = sorted_direction[middle_num:] + sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction( + last_part_point, last_point_direction) + sorted_point = sorted_fist_part_point + sorted_last_part_point + sorted_direction = sorted_fist_part_direction + sorted_last_part_direction + + return sorted_point, np.array(sorted_direction) + + +def add_id(pos_list, image_id=0): + """ + Add id for gather feature, for inference. + """ + new_list = [] + for item in pos_list: + new_list.append((image_id, item[0], item[1])) + return new_list + + +def sort_and_expand_with_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + h, w, _ = f_direction.shape + sorted_list, point_direction = sort_with_direction(pos_list, f_direction) + + point_num = len(sorted_list) + sub_direction_len = max(point_num // 3, 2) + left_direction = point_direction[:sub_direction_len, :] + right_dirction = point_direction[point_num - sub_direction_len:, :] + + left_average_direction = -np.mean(left_direction, axis=0, keepdims=True) + left_average_len = np.linalg.norm(left_average_direction) + left_start = np.array(sorted_list[0]) + left_step = left_average_direction / (left_average_len + 1e-6) + + right_average_direction = np.mean(right_dirction, axis=0, keepdims=True) + right_average_len = np.linalg.norm(right_average_direction) + right_step = right_average_direction / (right_average_len + 1e-6) + right_start = np.array(sorted_list[-1]) + + append_num = max( + int((left_average_len + right_average_len) / 2.0 * 0.15), 1) + left_list = [] + right_list = [] + for i in range(append_num): + ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ly < h and lx < w and (ly, lx) not in left_list: + left_list.append((ly, lx)) + ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ry < h and rx < w and (ry, rx) not in right_list: + right_list.append((ry, rx)) + + all_list = left_list[::-1] + sorted_list + right_list + return all_list + + +def sort_and_expand_with_direction_v2(pos_list, f_direction, binary_tcl_map): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + binary_tcl_map: h x w + """ + h, w, _ = f_direction.shape + sorted_list, point_direction = sort_with_direction(pos_list, f_direction) + + point_num = len(sorted_list) + sub_direction_len = max(point_num // 3, 2) + left_direction = point_direction[:sub_direction_len, :] + right_dirction = point_direction[point_num - sub_direction_len:, :] + + left_average_direction = -np.mean(left_direction, axis=0, keepdims=True) + left_average_len = np.linalg.norm(left_average_direction) + left_start = np.array(sorted_list[0]) + left_step = left_average_direction / (left_average_len + 1e-6) + + right_average_direction = np.mean(right_dirction, axis=0, keepdims=True) + right_average_len = np.linalg.norm(right_average_direction) + right_step = right_average_direction / (right_average_len + 1e-6) + right_start = np.array(sorted_list[-1]) + + append_num = max( + int((left_average_len + right_average_len) / 2.0 * 0.15), 1) + max_append_num = 2 * append_num + + left_list = [] + right_list = [] + for i in range(max_append_num): + ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ly < h and lx < w and (ly, lx) not in left_list: + if binary_tcl_map[ly, lx] > 0.5: + left_list.append((ly, lx)) + else: + break + + for i in range(max_append_num): + ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ry < h and rx < w and (ry, rx) not in right_list: + if binary_tcl_map[ry, rx] > 0.5: + right_list.append((ry, rx)) + else: + break + + all_list = left_list[::-1] + sorted_list + right_list + return all_list + + +def point_pair2poly(point_pair_list): + """ + Transfer vertical point_pairs into poly point in clockwise. + """ + point_num = len(point_pair_list) * 2 + point_list = [0] * point_num + for idx, point_pair in enumerate(point_pair_list): + point_list[idx] = point_pair[0] + point_list[point_num - 1 - idx] = point_pair[1] + return np.array(point_list).reshape(-1, 2) + + +def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.): + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + +def expand_poly_along_width(poly, shrink_ratio_of_width=0.3): + """ + expand poly along width. + """ + point_num = poly.shape[0] + left_quad = np.array( + [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32) + left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \ + (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6) + left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0) + right_quad = np.array( + [ + poly[point_num // 2 - 2], poly[point_num // 2 - 1], + poly[point_num // 2], poly[point_num // 2 + 1] + ], + dtype=np.float32) + right_ratio = 1.0 + shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \ + (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6) + right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio) + poly[0] = left_quad_expand[0] + poly[-1] = left_quad_expand[-1] + poly[point_num // 2 - 1] = right_quad_expand[1] + poly[point_num // 2] = right_quad_expand[2] + return poly + + +def restore_poly(instance_yxs_list, seq_strs, p_border, ratio_w, ratio_h, src_w, + src_h, valid_set): + poly_list = [] + keep_str_list = [] + for yx_center_line, keep_str in zip(instance_yxs_list, seq_strs): + if len(keep_str) < 2: + print('--> too short, {}'.format(keep_str)) + continue + + offset_expand = 1.0 + if valid_set == 'totaltext': + offset_expand = 1.2 + + point_pair_list = [] + for y, x in yx_center_line: + offset = p_border[:, y, x].reshape(2, 2) * offset_expand + ori_yx = np.array([y, x], dtype=np.float32) + point_pair = (ori_yx + offset)[:, ::-1] * 4.0 / np.array( + [ratio_w, ratio_h]).reshape(-1, 2) + point_pair_list.append(point_pair) + + detected_poly = point_pair2poly(point_pair_list) + detected_poly = expand_poly_along_width( + detected_poly, shrink_ratio_of_width=0.2) + detected_poly[:, 0] = np.clip(detected_poly[:, 0], a_min=0, a_max=src_w) + detected_poly[:, 1] = np.clip(detected_poly[:, 1], a_min=0, a_max=src_h) + + keep_str_list.append(keep_str) + if valid_set == 'partvgg': + middle_point = len(detected_poly) // 2 + detected_poly = detected_poly[ + [0, middle_point - 1, middle_point, -1], :] + poly_list.append(detected_poly) + elif valid_set == 'totaltext': + poly_list.append(detected_poly) + else: + print('--> Not supported format.') + exit(-1) + return poly_list, keep_str_list + + +def generate_pivot_list_fast(p_score, + p_char_maps, + f_direction, + Lexicon_Table, + score_thresh=0.5): + """ + return center point and end point of TCL instance; filter with the char maps; + """ + p_score = p_score[0] + f_direction = f_direction.transpose(1, 2, 0) + p_tcl_map = (p_score > score_thresh) * 1.0 + skeleton_map = thin(p_tcl_map.astype(np.uint8)) + instance_count, instance_label_map = cv2.connectedComponents( + skeleton_map.astype(np.uint8), connectivity=8) + + # get TCL Instance + all_pos_yxs = [] + if instance_count > 0: + for instance_id in range(1, instance_count): + pos_list = [] + ys, xs = np.where(instance_label_map == instance_id) + pos_list = list(zip(ys, xs)) + + if len(pos_list) < 3: + continue + + pos_list_sorted = sort_and_expand_with_direction_v2( + pos_list, f_direction, p_tcl_map) + all_pos_yxs.append(pos_list_sorted) + + p_char_maps = p_char_maps.transpose([1, 2, 0]) + decoded_str, keep_yxs_list = ctc_decoder_for_image( + all_pos_yxs, logits_map=p_char_maps, Lexicon_Table=Lexicon_Table) + return keep_yxs_list, decoded_str + + +def extract_main_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + pos_list = np.array(pos_list) + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] + point_direction = point_direction[:, ::-1] # x, y -> y, x + average_direction = np.mean(point_direction, axis=0, keepdims=True) + average_direction = average_direction / ( + np.linalg.norm(average_direction) + 1e-6) + return average_direction + + +def sort_by_direction_with_image_id_deprecated(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[id, y, x], [id, y, x], [id, y, x] ...] + """ + pos_list_full = np.array(pos_list).reshape(-1, 3) + pos_list = pos_list_full[:, 1:] + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist() + return sorted_list + + +def sort_by_direction_with_image_id(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + + def sort_part_with_direction(pos_list_full, point_direction): + pos_list_full = np.array(pos_list_full).reshape(-1, 3) + pos_list = pos_list_full[:, 1:] + point_direction = np.array(point_direction).reshape(-1, 2) + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist() + sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist() + return sorted_list, sorted_direction + + pos_list = np.array(pos_list).reshape(-1, 3) + point_direction = f_direction[pos_list[:, 1], pos_list[:, 2]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + sorted_point, sorted_direction = sort_part_with_direction(pos_list, + point_direction) + + point_num = len(sorted_point) + if point_num >= 16: + middle_num = point_num // 2 + first_part_point = sorted_point[:middle_num] + first_point_direction = sorted_direction[:middle_num] + sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction( + first_part_point, first_point_direction) + + last_part_point = sorted_point[middle_num:] + last_point_direction = sorted_direction[middle_num:] + sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction( + last_part_point, last_point_direction) + sorted_point = sorted_fist_part_point + sorted_last_part_point + sorted_direction = sorted_fist_part_direction + sorted_last_part_direction + + return sorted_point diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_slow.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_slow.py new file mode 100644 index 0000000000000000000000000000000000000000..ace46fba372e0b6ee27959076e1e855e77c4305c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/extract_textpoint_slow.py @@ -0,0 +1,592 @@ +# Copyright (c) 2021 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. +"""Contains various CTC decoders.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import cv2 +import math + +import numpy as np +from itertools import groupby +from skimage.morphology._skeletonize import thin + + +def get_dict(character_dict_path): + character_str = "" + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode('utf-8').strip("\n").strip("\r\n") + character_str += line + dict_character = list(character_str) + return dict_character + + +def point_pair2poly(point_pair_list): + """ + Transfer vertical point_pairs into poly point in clockwise. + """ + pair_length_list = [] + for point_pair in point_pair_list: + pair_length = np.linalg.norm(point_pair[0] - point_pair[1]) + pair_length_list.append(pair_length) + pair_length_list = np.array(pair_length_list) + pair_info = (pair_length_list.max(), pair_length_list.min(), + pair_length_list.mean()) + + point_num = len(point_pair_list) * 2 + point_list = [0] * point_num + for idx, point_pair in enumerate(point_pair_list): + point_list[idx] = point_pair[0] + point_list[point_num - 1 - idx] = point_pair[1] + return np.array(point_list).reshape(-1, 2), pair_info + + +def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.): + """ + Generate shrink_quad_along_width. + """ + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + +def expand_poly_along_width(poly, shrink_ratio_of_width=0.3): + """ + expand poly along width. + """ + point_num = poly.shape[0] + left_quad = np.array( + [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32) + left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \ + (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6) + left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0) + right_quad = np.array( + [ + poly[point_num // 2 - 2], poly[point_num // 2 - 1], + poly[point_num // 2], poly[point_num // 2 + 1] + ], + dtype=np.float32) + right_ratio = 1.0 + \ + shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \ + (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6) + right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio) + poly[0] = left_quad_expand[0] + poly[-1] = left_quad_expand[-1] + poly[point_num // 2 - 1] = right_quad_expand[1] + poly[point_num // 2] = right_quad_expand[2] + return poly + + +def softmax(logits): + """ + logits: N x d + """ + max_value = np.max(logits, axis=1, keepdims=True) + exp = np.exp(logits - max_value) + exp_sum = np.sum(exp, axis=1, keepdims=True) + dist = exp / exp_sum + return dist + + +def get_keep_pos_idxs(labels, remove_blank=None): + """ + Remove duplicate and get pos idxs of keep items. + The value of keep_blank should be [None, 95]. + """ + duplicate_len_list = [] + keep_pos_idx_list = [] + keep_char_idx_list = [] + for k, v_ in groupby(labels): + current_len = len(list(v_)) + if k != remove_blank: + current_idx = int(sum(duplicate_len_list) + current_len // 2) + keep_pos_idx_list.append(current_idx) + keep_char_idx_list.append(k) + duplicate_len_list.append(current_len) + return keep_char_idx_list, keep_pos_idx_list + + +def remove_blank(labels, blank=0): + new_labels = [x for x in labels if x != blank] + return new_labels + + +def insert_blank(labels, blank=0): + new_labels = [blank] + for l in labels: + new_labels += [l, blank] + return new_labels + + +def ctc_greedy_decoder(probs_seq, blank=95, keep_blank_in_idxs=True): + """ + CTC greedy (best path) decoder. + """ + raw_str = np.argmax(np.array(probs_seq), axis=1) + remove_blank_in_pos = None if keep_blank_in_idxs else blank + dedup_str, keep_idx_list = get_keep_pos_idxs( + raw_str, remove_blank=remove_blank_in_pos) + dst_str = remove_blank(dedup_str, blank=blank) + return dst_str, keep_idx_list + + +def instance_ctc_greedy_decoder(gather_info, + logits_map, + keep_blank_in_idxs=True): + """ + gather_info: [[x, y], [x, y] ...] + logits_map: H x W X (n_chars + 1) + """ + _, _, C = logits_map.shape + ys, xs = zip(*gather_info) + logits_seq = logits_map[list(ys), list(xs)] # n x 96 + probs_seq = softmax(logits_seq) + dst_str, keep_idx_list = ctc_greedy_decoder( + probs_seq, blank=C - 1, keep_blank_in_idxs=keep_blank_in_idxs) + keep_gather_list = [gather_info[idx] for idx in keep_idx_list] + return dst_str, keep_gather_list + + +def ctc_decoder_for_image(gather_info_list, logits_map, + keep_blank_in_idxs=True): + """ + CTC decoder using multiple processes. + """ + decoder_results = [] + for gather_info in gather_info_list: + res = instance_ctc_greedy_decoder( + gather_info, logits_map, keep_blank_in_idxs=keep_blank_in_idxs) + decoder_results.append(res) + return decoder_results + + +def sort_with_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + + def sort_part_with_direction(pos_list, point_direction): + pos_list = np.array(pos_list).reshape(-1, 2) + point_direction = np.array(point_direction).reshape(-1, 2) + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list[np.argsort(pos_proj_leng)].tolist() + sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist() + return sorted_list, sorted_direction + + pos_list = np.array(pos_list).reshape(-1, 2) + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + sorted_point, sorted_direction = sort_part_with_direction(pos_list, + point_direction) + + point_num = len(sorted_point) + if point_num >= 16: + middle_num = point_num // 2 + first_part_point = sorted_point[:middle_num] + first_point_direction = sorted_direction[:middle_num] + sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction( + first_part_point, first_point_direction) + + last_part_point = sorted_point[middle_num:] + last_point_direction = sorted_direction[middle_num:] + sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction( + last_part_point, last_point_direction) + sorted_point = sorted_fist_part_point + sorted_last_part_point + sorted_direction = sorted_fist_part_direction + sorted_last_part_direction + + return sorted_point, np.array(sorted_direction) + + +def add_id(pos_list, image_id=0): + """ + Add id for gather feature, for inference. + """ + new_list = [] + for item in pos_list: + new_list.append((image_id, item[0], item[1])) + return new_list + + +def sort_and_expand_with_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + h, w, _ = f_direction.shape + sorted_list, point_direction = sort_with_direction(pos_list, f_direction) + + # expand along + point_num = len(sorted_list) + sub_direction_len = max(point_num // 3, 2) + left_direction = point_direction[:sub_direction_len, :] + right_dirction = point_direction[point_num - sub_direction_len:, :] + + left_average_direction = -np.mean(left_direction, axis=0, keepdims=True) + left_average_len = np.linalg.norm(left_average_direction) + left_start = np.array(sorted_list[0]) + left_step = left_average_direction / (left_average_len + 1e-6) + + right_average_direction = np.mean(right_dirction, axis=0, keepdims=True) + right_average_len = np.linalg.norm(right_average_direction) + right_step = right_average_direction / (right_average_len + 1e-6) + right_start = np.array(sorted_list[-1]) + + append_num = max( + int((left_average_len + right_average_len) / 2.0 * 0.15), 1) + left_list = [] + right_list = [] + for i in range(append_num): + ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ly < h and lx < w and (ly, lx) not in left_list: + left_list.append((ly, lx)) + ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ry < h and rx < w and (ry, rx) not in right_list: + right_list.append((ry, rx)) + + all_list = left_list[::-1] + sorted_list + right_list + return all_list + + +def sort_and_expand_with_direction_v2(pos_list, f_direction, binary_tcl_map): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + binary_tcl_map: h x w + """ + h, w, _ = f_direction.shape + sorted_list, point_direction = sort_with_direction(pos_list, f_direction) + + # expand along + point_num = len(sorted_list) + sub_direction_len = max(point_num // 3, 2) + left_direction = point_direction[:sub_direction_len, :] + right_dirction = point_direction[point_num - sub_direction_len:, :] + + left_average_direction = -np.mean(left_direction, axis=0, keepdims=True) + left_average_len = np.linalg.norm(left_average_direction) + left_start = np.array(sorted_list[0]) + left_step = left_average_direction / (left_average_len + 1e-6) + + right_average_direction = np.mean(right_dirction, axis=0, keepdims=True) + right_average_len = np.linalg.norm(right_average_direction) + right_step = right_average_direction / (right_average_len + 1e-6) + right_start = np.array(sorted_list[-1]) + + append_num = max( + int((left_average_len + right_average_len) / 2.0 * 0.15), 1) + max_append_num = 2 * append_num + + left_list = [] + right_list = [] + for i in range(max_append_num): + ly, lx = np.round(left_start + left_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ly < h and lx < w and (ly, lx) not in left_list: + if binary_tcl_map[ly, lx] > 0.5: + left_list.append((ly, lx)) + else: + break + + for i in range(max_append_num): + ry, rx = np.round(right_start + right_step * (i + 1)).flatten().astype( + 'int32').tolist() + if ry < h and rx < w and (ry, rx) not in right_list: + if binary_tcl_map[ry, rx] > 0.5: + right_list.append((ry, rx)) + else: + break + + all_list = left_list[::-1] + sorted_list + right_list + return all_list + + +def generate_pivot_list_curved(p_score, + p_char_maps, + f_direction, + score_thresh=0.5, + is_expand=True, + is_backbone=False, + image_id=0): + """ + return center point and end point of TCL instance; filter with the char maps; + """ + p_score = p_score[0] + f_direction = f_direction.transpose(1, 2, 0) + p_tcl_map = (p_score > score_thresh) * 1.0 + skeleton_map = thin(p_tcl_map) + instance_count, instance_label_map = cv2.connectedComponents( + skeleton_map.astype(np.uint8), connectivity=8) + + # get TCL Instance + all_pos_yxs = [] + center_pos_yxs = [] + end_points_yxs = [] + instance_center_pos_yxs = [] + pred_strs = [] + if instance_count > 0: + for instance_id in range(1, instance_count): + pos_list = [] + ys, xs = np.where(instance_label_map == instance_id) + pos_list = list(zip(ys, xs)) + + ### FIX-ME, eliminate outlier + if len(pos_list) < 3: + continue + + if is_expand: + pos_list_sorted = sort_and_expand_with_direction_v2( + pos_list, f_direction, p_tcl_map) + else: + pos_list_sorted, _ = sort_with_direction(pos_list, f_direction) + all_pos_yxs.append(pos_list_sorted) + + # use decoder to filter backgroud points. + p_char_maps = p_char_maps.transpose([1, 2, 0]) + decode_res = ctc_decoder_for_image( + all_pos_yxs, logits_map=p_char_maps, keep_blank_in_idxs=True) + for decoded_str, keep_yxs_list in decode_res: + if is_backbone: + keep_yxs_list_with_id = add_id(keep_yxs_list, image_id=image_id) + instance_center_pos_yxs.append(keep_yxs_list_with_id) + pred_strs.append(decoded_str) + else: + end_points_yxs.extend((keep_yxs_list[0], keep_yxs_list[-1])) + center_pos_yxs.extend(keep_yxs_list) + + if is_backbone: + return pred_strs, instance_center_pos_yxs + else: + return center_pos_yxs, end_points_yxs + + +def generate_pivot_list_horizontal(p_score, + p_char_maps, + f_direction, + score_thresh=0.5, + is_backbone=False, + image_id=0): + """ + return center point and end point of TCL instance; filter with the char maps; + """ + p_score = p_score[0] + f_direction = f_direction.transpose(1, 2, 0) + p_tcl_map_bi = (p_score > score_thresh) * 1.0 + instance_count, instance_label_map = cv2.connectedComponents( + p_tcl_map_bi.astype(np.uint8), connectivity=8) + + # get TCL Instance + all_pos_yxs = [] + center_pos_yxs = [] + end_points_yxs = [] + instance_center_pos_yxs = [] + + if instance_count > 0: + for instance_id in range(1, instance_count): + pos_list = [] + ys, xs = np.where(instance_label_map == instance_id) + pos_list = list(zip(ys, xs)) + + ### FIX-ME, eliminate outlier + if len(pos_list) < 5: + continue + + # add rule here + main_direction = extract_main_direction(pos_list, + f_direction) # y x + reference_directin = np.array([0, 1]).reshape([-1, 2]) # y x + is_h_angle = abs(np.sum( + main_direction * reference_directin)) < math.cos(math.pi / 180 * + 70) + + point_yxs = np.array(pos_list) + max_y, max_x = np.max(point_yxs, axis=0) + min_y, min_x = np.min(point_yxs, axis=0) + is_h_len = (max_y - min_y) < 1.5 * (max_x - min_x) + + pos_list_final = [] + if is_h_len: + xs = np.unique(xs) + for x in xs: + ys = instance_label_map[:, x].copy().reshape((-1, )) + y = int(np.where(ys == instance_id)[0].mean()) + pos_list_final.append((y, x)) + else: + ys = np.unique(ys) + for y in ys: + xs = instance_label_map[y, :].copy().reshape((-1, )) + x = int(np.where(xs == instance_id)[0].mean()) + pos_list_final.append((y, x)) + + pos_list_sorted, _ = sort_with_direction(pos_list_final, + f_direction) + all_pos_yxs.append(pos_list_sorted) + + # use decoder to filter backgroud points. + p_char_maps = p_char_maps.transpose([1, 2, 0]) + decode_res = ctc_decoder_for_image( + all_pos_yxs, logits_map=p_char_maps, keep_blank_in_idxs=True) + for decoded_str, keep_yxs_list in decode_res: + if is_backbone: + keep_yxs_list_with_id = add_id(keep_yxs_list, image_id=image_id) + instance_center_pos_yxs.append(keep_yxs_list_with_id) + else: + end_points_yxs.extend((keep_yxs_list[0], keep_yxs_list[-1])) + center_pos_yxs.extend(keep_yxs_list) + + if is_backbone: + return instance_center_pos_yxs + else: + return center_pos_yxs, end_points_yxs + + +def generate_pivot_list_slow(p_score, + p_char_maps, + f_direction, + score_thresh=0.5, + is_backbone=False, + is_curved=True, + image_id=0): + """ + Warp all the function together. + """ + if is_curved: + return generate_pivot_list_curved( + p_score, + p_char_maps, + f_direction, + score_thresh=score_thresh, + is_expand=True, + is_backbone=is_backbone, + image_id=image_id) + else: + return generate_pivot_list_horizontal( + p_score, + p_char_maps, + f_direction, + score_thresh=score_thresh, + is_backbone=is_backbone, + image_id=image_id) + + +# for refine module +def extract_main_direction(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + pos_list = np.array(pos_list) + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] + point_direction = point_direction[:, ::-1] # x, y -> y, x + average_direction = np.mean(point_direction, axis=0, keepdims=True) + average_direction = average_direction / ( + np.linalg.norm(average_direction) + 1e-6) + return average_direction + + +def sort_by_direction_with_image_id_deprecated(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[id, y, x], [id, y, x], [id, y, x] ...] + """ + pos_list_full = np.array(pos_list).reshape(-1, 3) + pos_list = pos_list_full[:, 1:] + point_direction = f_direction[pos_list[:, 0], pos_list[:, 1]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist() + return sorted_list + + +def sort_by_direction_with_image_id(pos_list, f_direction): + """ + f_direction: h x w x 2 + pos_list: [[y, x], [y, x], [y, x] ...] + """ + + def sort_part_with_direction(pos_list_full, point_direction): + pos_list_full = np.array(pos_list_full).reshape(-1, 3) + pos_list = pos_list_full[:, 1:] + point_direction = np.array(point_direction).reshape(-1, 2) + average_direction = np.mean(point_direction, axis=0, keepdims=True) + pos_proj_leng = np.sum(pos_list * average_direction, axis=1) + sorted_list = pos_list_full[np.argsort(pos_proj_leng)].tolist() + sorted_direction = point_direction[np.argsort(pos_proj_leng)].tolist() + return sorted_list, sorted_direction + + pos_list = np.array(pos_list).reshape(-1, 3) + point_direction = f_direction[pos_list[:, 1], pos_list[:, 2]] # x, y + point_direction = point_direction[:, ::-1] # x, y -> y, x + sorted_point, sorted_direction = sort_part_with_direction(pos_list, + point_direction) + + point_num = len(sorted_point) + if point_num >= 16: + middle_num = point_num // 2 + first_part_point = sorted_point[:middle_num] + first_point_direction = sorted_direction[:middle_num] + sorted_fist_part_point, sorted_fist_part_direction = sort_part_with_direction( + first_part_point, first_point_direction) + + last_part_point = sorted_point[middle_num:] + last_point_direction = sorted_direction[middle_num:] + sorted_last_part_point, sorted_last_part_direction = sort_part_with_direction( + last_part_point, last_point_direction) + sorted_point = sorted_fist_part_point + sorted_last_part_point + sorted_direction = sorted_fist_part_direction + sorted_last_part_direction + + return sorted_point + + +def generate_pivot_list_tt_inference(p_score, + p_char_maps, + f_direction, + score_thresh=0.5, + is_backbone=False, + is_curved=True, + image_id=0): + """ + return center point and end point of TCL instance; filter with the char maps; + """ + p_score = p_score[0] + f_direction = f_direction.transpose(1, 2, 0) + p_tcl_map = (p_score > score_thresh) * 1.0 + skeleton_map = thin(p_tcl_map) + instance_count, instance_label_map = cv2.connectedComponents( + skeleton_map.astype(np.uint8), connectivity=8) + + # get TCL Instance + all_pos_yxs = [] + if instance_count > 0: + for instance_id in range(1, instance_count): + pos_list = [] + ys, xs = np.where(instance_label_map == instance_id) + pos_list = list(zip(ys, xs)) + ### FIX-ME, eliminate outlier + if len(pos_list) < 3: + continue + pos_list_sorted = sort_and_expand_with_direction_v2( + pos_list, f_direction, p_tcl_map) + pos_list_sorted_with_id = add_id(pos_list_sorted, image_id=image_id) + all_pos_yxs.append(pos_list_sorted_with_id) + return all_pos_yxs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/pgnet_pp_utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/pgnet_pp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a15503c0a88f735cc5f5eef924b0d022e5684eed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/pgnet_pp_utils.py @@ -0,0 +1,162 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +import paddle +import os +import sys + +__dir__ = os.path.dirname(__file__) +sys.path.append(__dir__) +sys.path.append(os.path.join(__dir__, '..')) +from extract_textpoint_slow import * +from extract_textpoint_fast import generate_pivot_list_fast, restore_poly + + +class PGNet_PostProcess(object): + # two different post-process + def __init__(self, character_dict_path, valid_set, score_thresh, outs_dict, + shape_list): + self.Lexicon_Table = get_dict(character_dict_path) + self.valid_set = valid_set + self.score_thresh = score_thresh + self.outs_dict = outs_dict + self.shape_list = shape_list + + def pg_postprocess_fast(self): + p_score = self.outs_dict['f_score'] + p_border = self.outs_dict['f_border'] + p_char = self.outs_dict['f_char'] + p_direction = self.outs_dict['f_direction'] + if isinstance(p_score, paddle.Tensor): + p_score = p_score[0].numpy() + p_border = p_border[0].numpy() + p_direction = p_direction[0].numpy() + p_char = p_char[0].numpy() + else: + p_score = p_score[0] + p_border = p_border[0] + p_direction = p_direction[0] + p_char = p_char[0] + + src_h, src_w, ratio_h, ratio_w = self.shape_list[0] + instance_yxs_list, seq_strs = generate_pivot_list_fast( + p_score, + p_char, + p_direction, + self.Lexicon_Table, + score_thresh=self.score_thresh) + poly_list, keep_str_list = restore_poly(instance_yxs_list, seq_strs, + p_border, ratio_w, ratio_h, + src_w, src_h, self.valid_set) + data = { + 'points': poly_list, + 'texts': keep_str_list, + } + return data + + def pg_postprocess_slow(self): + p_score = self.outs_dict['f_score'] + p_border = self.outs_dict['f_border'] + p_char = self.outs_dict['f_char'] + p_direction = self.outs_dict['f_direction'] + if isinstance(p_score, paddle.Tensor): + p_score = p_score[0].numpy() + p_border = p_border[0].numpy() + p_direction = p_direction[0].numpy() + p_char = p_char[0].numpy() + else: + p_score = p_score[0] + p_border = p_border[0] + p_direction = p_direction[0] + p_char = p_char[0] + src_h, src_w, ratio_h, ratio_w = self.shape_list[0] + is_curved = self.valid_set == "totaltext" + char_seq_idx_set, instance_yxs_list = generate_pivot_list_slow( + p_score, + p_char, + p_direction, + score_thresh=self.score_thresh, + is_backbone=True, + is_curved=is_curved) + seq_strs = [] + for char_idx_set in char_seq_idx_set: + pr_str = ''.join([self.Lexicon_Table[pos] for pos in char_idx_set]) + seq_strs.append(pr_str) + poly_list = [] + keep_str_list = [] + all_point_list = [] + all_point_pair_list = [] + for yx_center_line, keep_str in zip(instance_yxs_list, seq_strs): + if len(yx_center_line) == 1: + yx_center_line.append(yx_center_line[-1]) + + offset_expand = 1.0 + if self.valid_set == 'totaltext': + offset_expand = 1.2 + + point_pair_list = [] + for batch_id, y, x in yx_center_line: + offset = p_border[:, y, x].reshape(2, 2) + if offset_expand != 1.0: + offset_length = np.linalg.norm( + offset, axis=1, keepdims=True) + expand_length = np.clip( + offset_length * (offset_expand - 1), + a_min=0.5, + a_max=3.0) + offset_detal = offset / offset_length * expand_length + offset = offset + offset_detal + ori_yx = np.array([y, x], dtype=np.float32) + point_pair = (ori_yx + offset)[:, ::-1] * 4.0 / np.array( + [ratio_w, ratio_h]).reshape(-1, 2) + point_pair_list.append(point_pair) + + all_point_list.append([ + int(round(x * 4.0 / ratio_w)), + int(round(y * 4.0 / ratio_h)) + ]) + all_point_pair_list.append(point_pair.round().astype(np.int32) + .tolist()) + + detected_poly, pair_length_info = point_pair2poly(point_pair_list) + detected_poly = expand_poly_along_width( + detected_poly, shrink_ratio_of_width=0.2) + detected_poly[:, 0] = np.clip( + detected_poly[:, 0], a_min=0, a_max=src_w) + detected_poly[:, 1] = np.clip( + detected_poly[:, 1], a_min=0, a_max=src_h) + + if len(keep_str) < 2: + continue + + keep_str_list.append(keep_str) + detected_poly = np.round(detected_poly).astype('int32') + if self.valid_set == 'partvgg': + middle_point = len(detected_poly) // 2 + detected_poly = detected_poly[ + [0, middle_point - 1, middle_point, -1], :] + poly_list.append(detected_poly) + elif self.valid_set == 'totaltext': + poly_list.append(detected_poly) + else: + print('--> Not supported format.') + exit(-1) + data = { + 'points': poly_list, + 'texts': keep_str_list, + } + return data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/visual.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/visual.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e4fd0667dbf4a42dbc0fd9bf26e6fd91be0d82 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/e2e_utils/visual.py @@ -0,0 +1,162 @@ +# Copyright (c) 2021 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. +import numpy as np +import cv2 +import time + + +def resize_image(im, max_side_len=512): + """ + resize image to a size multiple of max_stride which is required by the network + :param im: the resized image + :param max_side_len: limit of max image size to avoid out of memory in gpu + :return: the resized image and the resize ratio + """ + h, w, _ = im.shape + + resize_w = w + resize_h = h + + if resize_h > resize_w: + ratio = float(max_side_len) / resize_h + else: + ratio = float(max_side_len) / resize_w + + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(im, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + + return im, (ratio_h, ratio_w) + + +def resize_image_min(im, max_side_len=512): + """ + """ + h, w, _ = im.shape + + resize_w = w + resize_h = h + + if resize_h < resize_w: + ratio = float(max_side_len) / resize_h + else: + ratio = float(max_side_len) / resize_w + + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(im, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + return im, (ratio_h, ratio_w) + + +def resize_image_for_totaltext(im, max_side_len=512): + """ + """ + h, w, _ = im.shape + + resize_w = w + resize_h = h + ratio = 1.25 + if h * ratio > max_side_len: + ratio = float(max_side_len) / resize_h + + resize_h = int(resize_h * ratio) + resize_w = int(resize_w * ratio) + + max_stride = 128 + resize_h = (resize_h + max_stride - 1) // max_stride * max_stride + resize_w = (resize_w + max_stride - 1) // max_stride * max_stride + im = cv2.resize(im, (int(resize_w), int(resize_h))) + ratio_h = resize_h / float(h) + ratio_w = resize_w / float(w) + return im, (ratio_h, ratio_w) + + +def point_pair2poly(point_pair_list): + """ + Transfer vertical point_pairs into poly point in clockwise. + """ + pair_length_list = [] + for point_pair in point_pair_list: + pair_length = np.linalg.norm(point_pair[0] - point_pair[1]) + pair_length_list.append(pair_length) + pair_length_list = np.array(pair_length_list) + pair_info = (pair_length_list.max(), pair_length_list.min(), + pair_length_list.mean()) + + point_num = len(point_pair_list) * 2 + point_list = [0] * point_num + for idx, point_pair in enumerate(point_pair_list): + point_list[idx] = point_pair[0] + point_list[point_num - 1 - idx] = point_pair[1] + return np.array(point_list).reshape(-1, 2), pair_info + + +def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.): + """ + Generate shrink_quad_along_width. + """ + ratio_pair = np.array( + [[begin_width_ratio], [end_width_ratio]], dtype=np.float32) + p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair + p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair + return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]]) + + +def expand_poly_along_width(poly, shrink_ratio_of_width=0.3): + """ + expand poly along width. + """ + point_num = poly.shape[0] + left_quad = np.array( + [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32) + left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \ + (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6) + left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0) + right_quad = np.array( + [ + poly[point_num // 2 - 2], poly[point_num // 2 - 1], + poly[point_num // 2], poly[point_num // 2 + 1] + ], + dtype=np.float32) + right_ratio = 1.0 + \ + shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \ + (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6) + right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio) + poly[0] = left_quad_expand[0] + poly[-1] = left_quad_expand[-1] + poly[point_num // 2 - 1] = right_quad_expand[1] + poly[point_num // 2] = right_quad_expand[2] + return poly + + +def norm2(x, axis=None): + if axis: + return np.sqrt(np.sum(x**2, axis=axis)) + return np.sqrt(np.sum(x**2)) + + +def cos(p1, p2): + return (p1 * p2).sum() / (norm2(p1) * norm2(p2)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/en_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/en_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..7677d31b9d3f08eef2823c2cf051beeab1f0470b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/en_dict.txt @@ -0,0 +1,95 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +@ +A +B +C +D +E +F +G +H +I +J +K +L +M +N +O +P +Q +R +S +T +U +V +W +X +Y +Z +[ +\ +] +^ +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +| +} +~ +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/gen_label.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/gen_label.py new file mode 100644 index 0000000000000000000000000000000000000000..fb78bd38bcfc1a59cac48a28bbb655ecb83bcb3f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/gen_label.py @@ -0,0 +1,81 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import os +import argparse +import json + + +def gen_rec_label(input_path, out_label): + with open(out_label, 'w') as out_file: + with open(input_path, 'r') as f: + for line in f.readlines(): + tmp = line.strip('\n').replace(" ", "").split(',') + img_path, label = tmp[0], tmp[1] + label = label.replace("\"", "") + out_file.write(img_path + '\t' + label + '\n') + + +def gen_det_label(root_path, input_dir, out_label): + with open(out_label, 'w') as out_file: + for label_file in os.listdir(input_dir): + img_path = root_path + label_file[3:-4] + ".jpg" + label = [] + with open( + os.path.join(input_dir, label_file), 'r', + encoding='utf-8-sig') as f: + for line in f.readlines(): + tmp = line.strip("\n\r").replace("\xef\xbb\xbf", + "").split(',') + points = tmp[:8] + s = [] + for i in range(0, len(points), 2): + b = points[i:i + 2] + b = [int(t) for t in b] + s.append(b) + result = {"transcription": tmp[8], "points": s} + label.append(result) + + out_file.write(img_path + '\t' + json.dumps( + label, ensure_ascii=False) + '\n') + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + '--mode', + type=str, + default="rec", + help='Generate rec_label or det_label, can be set rec or det') + parser.add_argument( + '--root_path', + type=str, + default=".", + help='The root directory of images.Only takes effect when mode=det ') + parser.add_argument( + '--input_path', + type=str, + default=".", + help='Input_label or input path to be converted') + parser.add_argument( + '--output_label', + type=str, + default="out_label.txt", + help='Output file name') + + args = parser.parse_args() + if args.mode == "rec": + print("Generate rec label") + gen_rec_label(args.input_path, args.output_label) + elif args.mode == "det": + gen_det_label(args.root_path, args.input_path, args.output_label) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ic15_dict.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ic15_dict.txt new file mode 100644 index 0000000000000000000000000000000000000000..474060366f8a2a00c108d5c743821c0a61867cd5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ic15_dict.txt @@ -0,0 +1,36 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/iou.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/iou.py new file mode 100644 index 0000000000000000000000000000000000000000..35459f5f053cde0a74f76c5652bfb723a48ca890 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/iou.py @@ -0,0 +1,54 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/whai362/PSENet/blob/python3/models/loss/iou.py +""" + +import paddle + +EPS = 1e-6 + + +def iou_single(a, b, mask, n_class): + valid = mask == 1 + a = a.masked_select(valid) + b = b.masked_select(valid) + miou = [] + for i in range(n_class): + if a.shape == [0] and a.shape == b.shape: + inter = paddle.to_tensor(0.0) + union = paddle.to_tensor(0.0) + else: + inter = ((a == i).logical_and(b == i)).astype('float32') + union = ((a == i).logical_or(b == i)).astype('float32') + miou.append(paddle.sum(inter) / (paddle.sum(union) + EPS)) + miou = sum(miou) / len(miou) + return miou + + +def iou(a, b, mask, n_class=2, reduce=True): + batch_size = a.shape[0] + + a = a.reshape([batch_size, -1]) + b = b.reshape([batch_size, -1]) + mask = mask.reshape([batch_size, -1]) + + iou = paddle.zeros((batch_size, ), dtype='float32') + for i in range(batch_size): + iou[i] = iou_single(a[i], b[i], mask[i], n_class) + + if reduce: + iou = paddle.mean(iou) + return iou diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e92f734e84b7e0278f8e7940ef3baf137c159e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/__init__.py @@ -0,0 +1,3 @@ +from .vdl_logger import VDLLogger +from .wandb_logger import WandbLogger +from .loggers import Loggers diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/base_logger.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/base_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7fc3593ba8e69fdd5bed386c7ae4ff0d459988 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/base_logger.py @@ -0,0 +1,15 @@ +import os +from abc import ABC, abstractmethod + +class BaseLogger(ABC): + def __init__(self, save_dir): + self.save_dir = save_dir + os.makedirs(self.save_dir, exist_ok=True) + + @abstractmethod + def log_metrics(self, metrics, prefix=None): + pass + + @abstractmethod + def close(self): + pass \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/loggers.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/loggers.py new file mode 100644 index 0000000000000000000000000000000000000000..260146620811c8e72da66e9f2c7bbcbaef90b90d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/loggers.py @@ -0,0 +1,18 @@ +from .wandb_logger import WandbLogger + +class Loggers(object): + def __init__(self, loggers): + super().__init__() + self.loggers = loggers + + def log_metrics(self, metrics, prefix=None, step=None): + for logger in self.loggers: + logger.log_metrics(metrics, prefix=prefix, step=step) + + def log_model(self, is_best, prefix, metadata=None): + for logger in self.loggers: + logger.log_model(is_best=is_best, prefix=prefix, metadata=metadata) + + def close(self): + for logger in self.loggers: + logger.close() \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/vdl_logger.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/vdl_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..c345f93235b239873f0ddcd49c8b1b8966877a03 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/vdl_logger.py @@ -0,0 +1,21 @@ +from .base_logger import BaseLogger +from visualdl import LogWriter + +class VDLLogger(BaseLogger): + def __init__(self, save_dir): + super().__init__(save_dir) + self.vdl_writer = LogWriter(logdir=save_dir) + + def log_metrics(self, metrics, prefix=None, step=None): + if not prefix: + prefix = "" + updated_metrics = {prefix + "/" + k: v for k, v in metrics.items()} + + for k, v in updated_metrics.items(): + self.vdl_writer.add_scalar(k, v, step) + + def log_model(self, is_best, prefix, metadata=None): + pass + + def close(self): + self.vdl_writer.close() \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/wandb_logger.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/wandb_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c6711696569e825638e0a27394071020b29cb5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/loggers/wandb_logger.py @@ -0,0 +1,78 @@ +import os +from .base_logger import BaseLogger + +class WandbLogger(BaseLogger): + def __init__(self, + project=None, + name=None, + id=None, + entity=None, + save_dir=None, + config=None, + **kwargs): + try: + import wandb + self.wandb = wandb + except ModuleNotFoundError: + raise ModuleNotFoundError( + "Please install wandb using `pip install wandb`" + ) + + self.project = project + self.name = name + self.id = id + self.save_dir = save_dir + self.config = config + self.kwargs = kwargs + self.entity = entity + self._run = None + self._wandb_init = dict( + project=self.project, + name=self.name, + id=self.id, + entity=self.entity, + dir=self.save_dir, + resume="allow" + ) + self._wandb_init.update(**kwargs) + + _ = self.run + + if self.config: + self.run.config.update(self.config) + + @property + def run(self): + if self._run is None: + if self.wandb.run is not None: + logger.info( + "There is a wandb run already in progress " + "and newly created instances of `WandbLogger` will reuse" + " this run. If this is not desired, call `wandb.finish()`" + "before instantiating `WandbLogger`." + ) + self._run = self.wandb.run + else: + self._run = self.wandb.init(**self._wandb_init) + return self._run + + def log_metrics(self, metrics, prefix=None, step=None): + if not prefix: + prefix = "" + updated_metrics = {prefix.lower() + "/" + k: v for k, v in metrics.items()} + + self.run.log(updated_metrics, step=step) + + def log_model(self, is_best, prefix, metadata=None): + model_path = os.path.join(self.save_dir, prefix + '.pdparams') + artifact = self.wandb.Artifact('model-{}'.format(self.run.id), type='model', metadata=metadata) + artifact.add_file(model_path, name="model_ckpt.pdparams") + + aliases = [prefix] + if is_best: + aliases.append("best") + + self.run.log_artifact(artifact, aliases=aliases) + + def close(self): + self.run.finish() \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/logging.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1eac8f351a4d30915d6f4ca863267cb73b9b1f19 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/logging.py @@ -0,0 +1,71 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +""" +This code is refer from: +https://github.com/WenmuZhou/PytorchOCR/blob/master/torchocr/utils/logging.py +""" + +import os +import sys +import logging +import functools +import paddle.distributed as dist + +logger_initialized = {} + + +@functools.lru_cache() +def get_logger(name='ppocr', log_file=None, log_level=logging.DEBUG): + """Initialize and get a logger by name. + If the logger has not been initialized, this method will initialize the + logger by adding one or two handlers, otherwise the initialized logger will + be directly returned. During initialization, a StreamHandler will always be + added. If `log_file` is specified a FileHandler will also be added. + Args: + name (str): Logger name. + log_file (str | None): The log filename. If specified, a FileHandler + will be added to the logger. + log_level (int): The logger level. Note that only the process of + rank 0 is affected, and other processes will set the level to + "Error" thus be silent most of the time. + Returns: + logging.Logger: The expected logger. + """ + logger = logging.getLogger(name) + if name in logger_initialized: + return logger + for logger_name in logger_initialized: + if name.startswith(logger_name): + return logger + + formatter = logging.Formatter( + '[%(asctime)s] %(name)s %(levelname)s: %(message)s', + datefmt="%Y/%m/%d %H:%M:%S") + + stream_handler = logging.StreamHandler(stream=sys.stdout) + stream_handler.setFormatter(formatter) + logger.addHandler(stream_handler) + if log_file is not None and dist.get_rank() == 0: + log_file_folder = os.path.split(log_file)[0] + os.makedirs(log_file_folder, exist_ok=True) + file_handler = logging.FileHandler(log_file, 'a') + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + if dist.get_rank() == 0: + logger.setLevel(log_level) + else: + logger.setLevel(logging.ERROR) + logger_initialized[name] = True + logger.propagate = False + return logger diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/network.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/network.py new file mode 100644 index 0000000000000000000000000000000000000000..080a5d160116cfdd3b255a883525281d97ee9cc9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/network.py @@ -0,0 +1,82 @@ +# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import os +import sys +import tarfile +import requests +from tqdm import tqdm + +from ppocr.utils.logging import get_logger + + +def download_with_progressbar(url, save_path): + logger = get_logger() + response = requests.get(url, stream=True) + if response.status_code == 200: + total_size_in_bytes = int(response.headers.get('content-length', 1)) + block_size = 1024 # 1 Kibibyte + progress_bar = tqdm( + total=total_size_in_bytes, unit='iB', unit_scale=True) + with open(save_path, 'wb') as file: + for data in response.iter_content(block_size): + progress_bar.update(len(data)) + file.write(data) + progress_bar.close() + else: + logger.error("Something went wrong while downloading models") + sys.exit(0) + + +def maybe_download(model_storage_directory, url): + # using custom model + tar_file_name_list = ['.pdiparams', '.pdiparams.info', '.pdmodel'] + if not os.path.exists( + os.path.join(model_storage_directory, 'inference.pdiparams') + ) or not os.path.exists( + os.path.join(model_storage_directory, 'inference.pdmodel')): + assert url.endswith('.tar'), 'Only supports tar compressed package' + tmp_path = os.path.join(model_storage_directory, url.split('/')[-1]) + print('download {} to {}'.format(url, tmp_path)) + os.makedirs(model_storage_directory, exist_ok=True) + download_with_progressbar(url, tmp_path) + with tarfile.open(tmp_path, 'r') as tarObj: + for member in tarObj.getmembers(): + filename = None + for tar_file_name in tar_file_name_list: + if member.name.endswith(tar_file_name): + filename = 'inference' + tar_file_name + if filename is None: + continue + file = tarObj.extractfile(member) + with open( + os.path.join(model_storage_directory, filename), + 'wb') as f: + f.write(file.read()) + os.remove(tmp_path) + + +def is_link(s): + return s is not None and s.startswith('http') + + +def confirm_model_dir_url(model_dir, default_model_dir, default_url): + url = default_url + if model_dir is None or is_link(model_dir): + if is_link(model_dir): + url = model_dir + file_name = url.split('/')[-1][:-4] + model_dir = default_model_dir + model_dir = os.path.join(model_dir, file_name) + return model_dir, url diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/poly_nms.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/poly_nms.py new file mode 100644 index 0000000000000000000000000000000000000000..9dcb3d2c2f7be2022529d5e54de357182f207cf5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/poly_nms.py @@ -0,0 +1,146 @@ +# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import numpy as np +from shapely.geometry import Polygon + + +def points2polygon(points): + """Convert k points to 1 polygon. + + Args: + points (ndarray or list): A ndarray or a list of shape (2k) + that indicates k points. + + Returns: + polygon (Polygon): A polygon object. + """ + if isinstance(points, list): + points = np.array(points) + + assert isinstance(points, np.ndarray) + assert (points.size % 2 == 0) and (points.size >= 8) + + point_mat = points.reshape([-1, 2]) + return Polygon(point_mat) + + +def poly_intersection(poly_det, poly_gt, buffer=0.0001): + """Calculate the intersection area between two polygon. + + Args: + poly_det (Polygon): A polygon predicted by detector. + poly_gt (Polygon): A gt polygon. + + Returns: + intersection_area (float): The intersection area between two polygons. + """ + assert isinstance(poly_det, Polygon) + assert isinstance(poly_gt, Polygon) + + if buffer == 0: + poly_inter = poly_det & poly_gt + else: + poly_inter = poly_det.buffer(buffer) & poly_gt.buffer(buffer) + return poly_inter.area, poly_inter + + +def poly_union(poly_det, poly_gt): + """Calculate the union area between two polygon. + + Args: + poly_det (Polygon): A polygon predicted by detector. + poly_gt (Polygon): A gt polygon. + + Returns: + union_area (float): The union area between two polygons. + """ + assert isinstance(poly_det, Polygon) + assert isinstance(poly_gt, Polygon) + + area_det = poly_det.area + area_gt = poly_gt.area + area_inters, _ = poly_intersection(poly_det, poly_gt) + return area_det + area_gt - area_inters + + +def valid_boundary(x, with_score=True): + num = len(x) + if num < 8: + return False + if num % 2 == 0 and (not with_score): + return True + if num % 2 == 1 and with_score: + return True + + return False + + +def boundary_iou(src, target): + """Calculate the IOU between two boundaries. + + Args: + src (list): Source boundary. + target (list): Target boundary. + + Returns: + iou (float): The iou between two boundaries. + """ + assert valid_boundary(src, False) + assert valid_boundary(target, False) + src_poly = points2polygon(src) + target_poly = points2polygon(target) + + return poly_iou(src_poly, target_poly) + + +def poly_iou(poly_det, poly_gt): + """Calculate the IOU between two polygons. + + Args: + poly_det (Polygon): A polygon predicted by detector. + poly_gt (Polygon): A gt polygon. + + Returns: + iou (float): The IOU between two polygons. + """ + assert isinstance(poly_det, Polygon) + assert isinstance(poly_gt, Polygon) + area_inters, _ = poly_intersection(poly_det, poly_gt) + area_union = poly_union(poly_det, poly_gt) + if area_union == 0: + return 0.0 + return area_inters / area_union + + +def poly_nms(polygons, threshold): + assert isinstance(polygons, list) + + polygons = np.array(sorted(polygons, key=lambda x: x[-1])) + + keep_poly = [] + index = [i for i in range(polygons.shape[0])] + + while len(index) > 0: + keep_poly.append(polygons[index[-1]].tolist()) + A = polygons[index[-1]][:-1] + index = np.delete(index, -1) + iou_list = np.zeros((len(index), )) + for i in range(len(index)): + B = polygons[index[i]][:-1] + iou_list[i] = boundary_iou(A, B) + remove_index = np.where(iou_list > threshold) + index = np.delete(index, remove_index) + + return keep_poly diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ppocr_keys_v1.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ppocr_keys_v1.txt new file mode 100644 index 0000000000000000000000000000000000000000..84b885d8352226e49b1d5d791b8f43a663e246aa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/ppocr_keys_v1.txt @@ -0,0 +1,6623 @@ +' +疗 +绚 +诚 +娇 +溜 +题 +贿 +者 +廖 +更 +纳 +加 +奉 +公 +一 +就 +汴 +计 +与 +路 +房 +原 +妇 +2 +0 +8 +- +7 +其 +> +: +] +, +, +骑 +刈 +全 +消 +昏 +傈 +安 +久 +钟 +嗅 +不 +影 +处 +驽 +蜿 +资 +关 +椤 +地 +瘸 +专 +问 +忖 +票 +嫉 +炎 +韵 +要 +月 +田 +节 +陂 +鄙 +捌 +备 +拳 +伺 +眼 +网 +盎 +大 +傍 +心 +东 +愉 +汇 +蹿 +科 +每 +业 +里 +航 +晏 +字 +平 +录 +先 +1 +3 +彤 +鲶 +产 +稍 +督 +腴 +有 +象 +岳 +注 +绍 +在 +泺 +文 +定 +核 +名 +水 +过 +理 +让 +偷 +率 +等 +这 +发 +” +为 +含 +肥 +酉 +相 +鄱 +七 +编 +猥 +锛 +日 +镀 +蒂 +掰 +倒 +辆 +栾 +栗 +综 +涩 +州 +雌 +滑 +馀 +了 +机 +块 +司 +宰 +甙 +兴 +矽 +抚 +保 +用 +沧 +秩 +如 +收 +息 +滥 +页 +疑 +埠 +! +! +姥 +异 +橹 +钇 +向 +下 +跄 +的 +椴 +沫 +国 +绥 +獠 +报 +开 +民 +蜇 +何 +分 +凇 +长 +讥 +藏 +掏 +施 +羽 +中 +讲 +派 +嘟 +人 +提 +浼 +间 +世 +而 +古 +多 +倪 +唇 +饯 +控 +庚 +首 +赛 +蜓 +味 +断 +制 +觉 +技 +替 +艰 +溢 +潮 +夕 +钺 +外 +摘 +枋 +动 +双 +单 +啮 +户 +枇 +确 +锦 +曜 +杜 +或 +能 +效 +霜 +盒 +然 +侗 +电 +晁 +放 +步 +鹃 +新 +杖 +蜂 +吒 +濂 +瞬 +评 +总 +隍 +对 +独 +合 +也 +是 +府 +青 +天 +诲 +墙 +组 +滴 +级 +邀 +帘 +示 +已 +时 +骸 +仄 +泅 +和 +遨 +店 +雇 +疫 +持 +巍 +踮 +境 +只 +亨 +目 +鉴 +崤 +闲 +体 +泄 +杂 +作 +般 +轰 +化 +解 +迂 +诿 +蛭 +璀 +腾 +告 +版 +服 +省 +师 +小 +规 +程 +线 +海 +办 +引 +二 +桧 +牌 +砺 +洄 +裴 +修 +图 +痫 +胡 +许 +犊 +事 +郛 +基 +柴 +呼 +食 +研 +奶 +律 +蛋 +因 +葆 +察 +戏 +褒 +戒 +再 +李 +骁 +工 +貂 +油 +鹅 +章 +啄 +休 +场 +给 +睡 +纷 +豆 +器 +捎 +说 +敏 +学 +会 +浒 +设 +诊 +格 +廓 +查 +来 +霓 +室 +溆 +¢ +诡 +寥 +焕 +舜 +柒 +狐 +回 +戟 +砾 +厄 +实 +翩 +尿 +五 +入 +径 +惭 +喹 +股 +宇 +篝 +| +; +美 +期 +云 +九 +祺 +扮 +靠 +锝 +槌 +系 +企 +酰 +阊 +暂 +蚕 +忻 +豁 +本 +羹 +执 +条 +钦 +H +獒 +限 +进 +季 +楦 +于 +芘 +玖 +铋 +茯 +未 +答 +粘 +括 +样 +精 +欠 +矢 +甥 +帷 +嵩 +扣 +令 +仔 +风 +皈 +行 +支 +部 +蓉 +刮 +站 +蜡 +救 +钊 +汗 +松 +嫌 +成 +可 +. +鹤 +院 +从 +交 +政 +怕 +活 +调 +球 +局 +验 +髌 +第 +韫 +谗 +串 +到 +圆 +年 +米 +/ +* +友 +忿 +检 +区 +看 +自 +敢 +刃 +个 +兹 +弄 +流 +留 +同 +没 +齿 +星 +聆 +轼 +湖 +什 +三 +建 +蛔 +儿 +椋 +汕 +震 +颧 +鲤 +跟 +力 +情 +璺 +铨 +陪 +务 +指 +族 +训 +滦 +鄣 +濮 +扒 +商 +箱 +十 +召 +慷 +辗 +所 +莞 +管 +护 +臭 +横 +硒 +嗓 +接 +侦 +六 +露 +党 +馋 +驾 +剖 +高 +侬 +妪 +幂 +猗 +绺 +骐 +央 +酐 +孝 +筝 +课 +徇 +缰 +门 +男 +西 +项 +句 +谙 +瞒 +秃 +篇 +教 +碲 +罚 +声 +呐 +景 +前 +富 +嘴 +鳌 +稀 +免 +朋 +啬 +睐 +去 +赈 +鱼 +住 +肩 +愕 +速 +旁 +波 +厅 +健 +茼 +厥 +鲟 +谅 +投 +攸 +炔 +数 +方 +击 +呋 +谈 +绩 +别 +愫 +僚 +躬 +鹧 +胪 +炳 +招 +喇 +膨 +泵 +蹦 +毛 +结 +5 +4 +谱 +识 +陕 +粽 +婚 +拟 +构 +且 +搜 +任 +潘 +比 +郢 +妨 +醪 +陀 +桔 +碘 +扎 +选 +哈 +骷 +楷 +亿 +明 +缆 +脯 +监 +睫 +逻 +婵 +共 +赴 +淝 +凡 +惦 +及 +达 +揖 +谩 +澹 +减 +焰 +蛹 +番 +祁 +柏 +员 +禄 +怡 +峤 +龙 +白 +叽 +生 +闯 +起 +细 +装 +谕 +竟 +聚 +钙 +上 +导 +渊 +按 +艾 +辘 +挡 +耒 +盹 +饪 +臀 +记 +邮 +蕙 +受 +各 +医 +搂 +普 +滇 +朗 +茸 +带 +翻 +酚 +( +光 +堤 +墟 +蔷 +万 +幻 +〓 +瑙 +辈 +昧 +盏 +亘 +蛀 +吉 +铰 +请 +子 +假 +闻 +税 +井 +诩 +哨 +嫂 +好 +面 +琐 +校 +馊 +鬣 +缂 +营 +访 +炖 +占 +农 +缀 +否 +经 +钚 +棵 +趟 +张 +亟 +吏 +茶 +谨 +捻 +论 +迸 +堂 +玉 +信 +吧 +瞠 +乡 +姬 +寺 +咬 +溏 +苄 +皿 +意 +赉 +宝 +尔 +钰 +艺 +特 +唳 +踉 +都 +荣 +倚 +登 +荐 +丧 +奇 +涵 +批 +炭 +近 +符 +傩 +感 +道 +着 +菊 +虹 +仲 +众 +懈 +濯 +颞 +眺 +南 +释 +北 +缝 +标 +既 +茗 +整 +撼 +迤 +贲 +挎 +耱 +拒 +某 +妍 +卫 +哇 +英 +矶 +藩 +治 +他 +元 +领 +膜 +遮 +穗 +蛾 +飞 +荒 +棺 +劫 +么 +市 +火 +温 +拈 +棚 +洼 +转 +果 +奕 +卸 +迪 +伸 +泳 +斗 +邡 +侄 +涨 +屯 +萋 +胭 +氡 +崮 +枞 +惧 +冒 +彩 +斜 +手 +豚 +随 +旭 +淑 +妞 +形 +菌 +吲 +沱 +争 +驯 +歹 +挟 +兆 +柱 +传 +至 +包 +内 +响 +临 +红 +功 +弩 +衡 +寂 +禁 +老 +棍 +耆 +渍 +织 +害 +氵 +渑 +布 +载 +靥 +嗬 +虽 +苹 +咨 +娄 +库 +雉 +榜 +帜 +嘲 +套 +瑚 +亲 +簸 +欧 +边 +6 +腿 +旮 +抛 +吹 +瞳 +得 +镓 +梗 +厨 +继 +漾 +愣 +憨 +士 +策 +窑 +抑 +躯 +襟 +脏 +参 +贸 +言 +干 +绸 +鳄 +穷 +藜 +音 +折 +详 +) +举 +悍 +甸 +癌 +黎 +谴 +死 +罩 +迁 +寒 +驷 +袖 +媒 +蒋 +掘 +模 +纠 +恣 +观 +祖 +蛆 +碍 +位 +稿 +主 +澧 +跌 +筏 +京 +锏 +帝 +贴 +证 +糠 +才 +黄 +鲸 +略 +炯 +饱 +四 +出 +园 +犀 +牧 +容 +汉 +杆 +浈 +汰 +瑷 +造 +虫 +瘩 +怪 +驴 +济 +应 +花 +沣 +谔 +夙 +旅 +价 +矿 +以 +考 +s +u +呦 +晒 +巡 +茅 +准 +肟 +瓴 +詹 +仟 +褂 +译 +桌 +混 +宁 +怦 +郑 +抿 +些 +余 +鄂 +饴 +攒 +珑 +群 +阖 +岔 +琨 +藓 +预 +环 +洮 +岌 +宀 +杲 +瀵 +最 +常 +囡 +周 +踊 +女 +鼓 +袭 +喉 +简 +范 +薯 +遐 +疏 +粱 +黜 +禧 +法 +箔 +斤 +遥 +汝 +奥 +直 +贞 +撑 +置 +绱 +集 +她 +馅 +逗 +钧 +橱 +魉 +[ +恙 +躁 +唤 +9 +旺 +膘 +待 +脾 +惫 +购 +吗 +依 +盲 +度 +瘿 +蠖 +俾 +之 +镗 +拇 +鲵 +厝 +簧 +续 +款 +展 +啃 +表 +剔 +品 +钻 +腭 +损 +清 +锶 +统 +涌 +寸 +滨 +贪 +链 +吠 +冈 +伎 +迥 +咏 +吁 +览 +防 +迅 +失 +汾 +阔 +逵 +绀 +蔑 +列 +川 +凭 +努 +熨 +揪 +利 +俱 +绉 +抢 +鸨 +我 +即 +责 +膦 +易 +毓 +鹊 +刹 +玷 +岿 +空 +嘞 +绊 +排 +术 +估 +锷 +违 +们 +苟 +铜 +播 +肘 +件 +烫 +审 +鲂 +广 +像 +铌 +惰 +铟 +巳 +胍 +鲍 +康 +憧 +色 +恢 +想 +拷 +尤 +疳 +知 +S +Y +F +D +A +峄 +裕 +帮 +握 +搔 +氐 +氘 +难 +墒 +沮 +雨 +叁 +缥 +悴 +藐 +湫 +娟 +苑 +稠 +颛 +簇 +后 +阕 +闭 +蕤 +缚 +怎 +佞 +码 +嘤 +蔡 +痊 +舱 +螯 +帕 +赫 +昵 +升 +烬 +岫 +、 +疵 +蜻 +髁 +蕨 +隶 +烛 +械 +丑 +盂 +梁 +强 +鲛 +由 +拘 +揉 +劭 +龟 +撤 +钩 +呕 +孛 +费 +妻 +漂 +求 +阑 +崖 +秤 +甘 +通 +深 +补 +赃 +坎 +床 +啪 +承 +吼 +量 +暇 +钼 +烨 +阂 +擎 +脱 +逮 +称 +P +神 +属 +矗 +华 +届 +狍 +葑 +汹 +育 +患 +窒 +蛰 +佼 +静 +槎 +运 +鳗 +庆 +逝 +曼 +疱 +克 +代 +官 +此 +麸 +耧 +蚌 +晟 +例 +础 +榛 +副 +测 +唰 +缢 +迹 +灬 +霁 +身 +岁 +赭 +扛 +又 +菡 +乜 +雾 +板 +读 +陷 +徉 +贯 +郁 +虑 +变 +钓 +菜 +圾 +现 +琢 +式 +乐 +维 +渔 +浜 +左 +吾 +脑 +钡 +警 +T +啵 +拴 +偌 +漱 +湿 +硕 +止 +骼 +魄 +积 +燥 +联 +踢 +玛 +则 +窿 +见 +振 +畿 +送 +班 +钽 +您 +赵 +刨 +印 +讨 +踝 +籍 +谡 +舌 +崧 +汽 +蔽 +沪 +酥 +绒 +怖 +财 +帖 +肱 +私 +莎 +勋 +羔 +霸 +励 +哼 +帐 +将 +帅 +渠 +纪 +婴 +娩 +岭 +厘 +滕 +吻 +伤 +坝 +冠 +戊 +隆 +瘁 +介 +涧 +物 +黍 +并 +姗 +奢 +蹑 +掣 +垸 +锴 +命 +箍 +捉 +病 +辖 +琰 +眭 +迩 +艘 +绌 +繁 +寅 +若 +毋 +思 +诉 +类 +诈 +燮 +轲 +酮 +狂 +重 +反 +职 +筱 +县 +委 +磕 +绣 +奖 +晋 +濉 +志 +徽 +肠 +呈 +獐 +坻 +口 +片 +碰 +几 +村 +柿 +劳 +料 +获 +亩 +惕 +晕 +厌 +号 +罢 +池 +正 +鏖 +煨 +家 +棕 +复 +尝 +懋 +蜥 +锅 +岛 +扰 +队 +坠 +瘾 +钬 +@ +卧 +疣 +镇 +譬 +冰 +彷 +频 +黯 +据 +垄 +采 +八 +缪 +瘫 +型 +熹 +砰 +楠 +襁 +箐 +但 +嘶 +绳 +啤 +拍 +盥 +穆 +傲 +洗 +盯 +塘 +怔 +筛 +丿 +台 +恒 +喂 +葛 +永 +¥ +烟 +酒 +桦 +书 +砂 +蚝 +缉 +态 +瀚 +袄 +圳 +轻 +蛛 +超 +榧 +遛 +姒 +奘 +铮 +右 +荽 +望 +偻 +卡 +丶 +氰 +附 +做 +革 +索 +戚 +坨 +桷 +唁 +垅 +榻 +岐 +偎 +坛 +莨 +山 +殊 +微 +骇 +陈 +爨 +推 +嗝 +驹 +澡 +藁 +呤 +卤 +嘻 +糅 +逛 +侵 +郓 +酌 +德 +摇 +※ +鬃 +被 +慨 +殡 +羸 +昌 +泡 +戛 +鞋 +河 +宪 +沿 +玲 +鲨 +翅 +哽 +源 +铅 +语 +照 +邯 +址 +荃 +佬 +顺 +鸳 +町 +霭 +睾 +瓢 +夸 +椁 +晓 +酿 +痈 +咔 +侏 +券 +噎 +湍 +签 +嚷 +离 +午 +尚 +社 +锤 +背 +孟 +使 +浪 +缦 +潍 +鞅 +军 +姹 +驶 +笑 +鳟 +鲁 +》 +孽 +钜 +绿 +洱 +礴 +焯 +椰 +颖 +囔 +乌 +孔 +巴 +互 +性 +椽 +哞 +聘 +昨 +早 +暮 +胶 +炀 +隧 +低 +彗 +昝 +铁 +呓 +氽 +藉 +喔 +癖 +瑗 +姨 +权 +胱 +韦 +堑 +蜜 +酋 +楝 +砝 +毁 +靓 +歙 +锲 +究 +屋 +喳 +骨 +辨 +碑 +武 +鸠 +宫 +辜 +烊 +适 +坡 +殃 +培 +佩 +供 +走 +蜈 +迟 +翼 +况 +姣 +凛 +浔 +吃 +飘 +债 +犟 +金 +促 +苛 +崇 +坂 +莳 +畔 +绂 +兵 +蠕 +斋 +根 +砍 +亢 +欢 +恬 +崔 +剁 +餐 +榫 +快 +扶 +‖ +濒 +缠 +鳜 +当 +彭 +驭 +浦 +篮 +昀 +锆 +秸 +钳 +弋 +娣 +瞑 +夷 +龛 +苫 +拱 +致 +% +嵊 +障 +隐 +弑 +初 +娓 +抉 +汩 +累 +蓖 +" +唬 +助 +苓 +昙 +押 +毙 +破 +城 +郧 +逢 +嚏 +獭 +瞻 +溱 +婿 +赊 +跨 +恼 +璧 +萃 +姻 +貉 +灵 +炉 +密 +氛 +陶 +砸 +谬 +衔 +点 +琛 +沛 +枳 +层 +岱 +诺 +脍 +榈 +埂 +征 +冷 +裁 +打 +蹴 +素 +瘘 +逞 +蛐 +聊 +激 +腱 +萘 +踵 +飒 +蓟 +吆 +取 +咙 +簋 +涓 +矩 +曝 +挺 +揣 +座 +你 +史 +舵 +焱 +尘 +苏 +笈 +脚 +溉 +榨 +诵 +樊 +邓 +焊 +义 +庶 +儋 +蟋 +蒲 +赦 +呷 +杞 +诠 +豪 +还 +试 +颓 +茉 +太 +除 +紫 +逃 +痴 +草 +充 +鳕 +珉 +祗 +墨 +渭 +烩 +蘸 +慕 +璇 +镶 +穴 +嵘 +恶 +骂 +险 +绋 +幕 +碉 +肺 +戳 +刘 +潞 +秣 +纾 +潜 +銮 +洛 +须 +罘 +销 +瘪 +汞 +兮 +屉 +r +林 +厕 +质 +探 +划 +狸 +殚 +善 +煊 +烹 +〒 +锈 +逯 +宸 +辍 +泱 +柚 +袍 +远 +蹋 +嶙 +绝 +峥 +娥 +缍 +雀 +徵 +认 +镱 +谷 += +贩 +勉 +撩 +鄯 +斐 +洋 +非 +祚 +泾 +诒 +饿 +撬 +威 +晷 +搭 +芍 +锥 +笺 +蓦 +候 +琊 +档 +礁 +沼 +卵 +荠 +忑 +朝 +凹 +瑞 +头 +仪 +弧 +孵 +畏 +铆 +突 +衲 +车 +浩 +气 +茂 +悖 +厢 +枕 +酝 +戴 +湾 +邹 +飚 +攘 +锂 +写 +宵 +翁 +岷 +无 +喜 +丈 +挑 +嗟 +绛 +殉 +议 +槽 +具 +醇 +淞 +笃 +郴 +阅 +饼 +底 +壕 +砚 +弈 +询 +缕 +庹 +翟 +零 +筷 +暨 +舟 +闺 +甯 +撞 +麂 +茌 +蔼 +很 +珲 +捕 +棠 +角 +阉 +媛 +娲 +诽 +剿 +尉 +爵 +睬 +韩 +诰 +匣 +危 +糍 +镯 +立 +浏 +阳 +少 +盆 +舔 +擘 +匪 +申 +尬 +铣 +旯 +抖 +赘 +瓯 +居 +ˇ +哮 +游 +锭 +茏 +歌 +坏 +甚 +秒 +舞 +沙 +仗 +劲 +潺 +阿 +燧 +郭 +嗖 +霏 +忠 +材 +奂 +耐 +跺 +砀 +输 +岖 +媳 +氟 +极 +摆 +灿 +今 +扔 +腻 +枝 +奎 +药 +熄 +吨 +话 +q +额 +慑 +嘌 +协 +喀 +壳 +埭 +视 +著 +於 +愧 +陲 +翌 +峁 +颅 +佛 +腹 +聋 +侯 +咎 +叟 +秀 +颇 +存 +较 +罪 +哄 +岗 +扫 +栏 +钾 +羌 +己 +璨 +枭 +霉 +煌 +涸 +衿 +键 +镝 +益 +岢 +奏 +连 +夯 +睿 +冥 +均 +糖 +狞 +蹊 +稻 +爸 +刿 +胥 +煜 +丽 +肿 +璃 +掸 +跚 +灾 +垂 +樾 +濑 +乎 +莲 +窄 +犹 +撮 +战 +馄 +软 +络 +显 +鸢 +胸 +宾 +妲 +恕 +埔 +蝌 +份 +遇 +巧 +瞟 +粒 +恰 +剥 +桡 +博 +讯 +凯 +堇 +阶 +滤 +卖 +斌 +骚 +彬 +兑 +磺 +樱 +舷 +两 +娱 +福 +仃 +差 +找 +桁 +÷ +净 +把 +阴 +污 +戬 +雷 +碓 +蕲 +楚 +罡 +焖 +抽 +妫 +咒 +仑 +闱 +尽 +邑 +菁 +爱 +贷 +沥 +鞑 +牡 +嗉 +崴 +骤 +塌 +嗦 +订 +拮 +滓 +捡 +锻 +次 +坪 +杩 +臃 +箬 +融 +珂 +鹗 +宗 +枚 +降 +鸬 +妯 +阄 +堰 +盐 +毅 +必 +杨 +崃 +俺 +甬 +状 +莘 +货 +耸 +菱 +腼 +铸 +唏 +痤 +孚 +澳 +懒 +溅 +翘 +疙 +杷 +淼 +缙 +骰 +喊 +悉 +砻 +坷 +艇 +赁 +界 +谤 +纣 +宴 +晃 +茹 +归 +饭 +梢 +铡 +街 +抄 +肼 +鬟 +苯 +颂 +撷 +戈 +炒 +咆 +茭 +瘙 +负 +仰 +客 +琉 +铢 +封 +卑 +珥 +椿 +镧 +窨 +鬲 +寿 +御 +袤 +铃 +萎 +砖 +餮 +脒 +裳 +肪 +孕 +嫣 +馗 +嵇 +恳 +氯 +江 +石 +褶 +冢 +祸 +阻 +狈 +羞 +银 +靳 +透 +咳 +叼 +敷 +芷 +啥 +它 +瓤 +兰 +痘 +懊 +逑 +肌 +往 +捺 +坊 +甩 +呻 +〃 +沦 +忘 +膻 +祟 +菅 +剧 +崆 +智 +坯 +臧 +霍 +墅 +攻 +眯 +倘 +拢 +骠 +铐 +庭 +岙 +瓠 +′ +缺 +泥 +迢 +捶 +? +? +郏 +喙 +掷 +沌 +纯 +秘 +种 +听 +绘 +固 +螨 +团 +香 +盗 +妒 +埚 +蓝 +拖 +旱 +荞 +铀 +血 +遏 +汲 +辰 +叩 +拽 +幅 +硬 +惶 +桀 +漠 +措 +泼 +唑 +齐 +肾 +念 +酱 +虚 +屁 +耶 +旗 +砦 +闵 +婉 +馆 +拭 +绅 +韧 +忏 +窝 +醋 +葺 +顾 +辞 +倜 +堆 +辋 +逆 +玟 +贱 +疾 +董 +惘 +倌 +锕 +淘 +嘀 +莽 +俭 +笏 +绑 +鲷 +杈 +择 +蟀 +粥 +嗯 +驰 +逾 +案 +谪 +褓 +胫 +哩 +昕 +颚 +鲢 +绠 +躺 +鹄 +崂 +儒 +俨 +丝 +尕 +泌 +啊 +萸 +彰 +幺 +吟 +骄 +苣 +弦 +脊 +瑰 +〈 +诛 +镁 +析 +闪 +剪 +侧 +哟 +框 +螃 +守 +嬗 +燕 +狭 +铈 +缮 +概 +迳 +痧 +鲲 +俯 +售 +笼 +痣 +扉 +挖 +满 +咋 +援 +邱 +扇 +歪 +便 +玑 +绦 +峡 +蛇 +叨 +〖 +泽 +胃 +斓 +喋 +怂 +坟 +猪 +该 +蚬 +炕 +弥 +赞 +棣 +晔 +娠 +挲 +狡 +创 +疖 +铕 +镭 +稷 +挫 +弭 +啾 +翔 +粉 +履 +苘 +哦 +楼 +秕 +铂 +土 +锣 +瘟 +挣 +栉 +习 +享 +桢 +袅 +磨 +桂 +谦 +延 +坚 +蔚 +噗 +署 +谟 +猬 +钎 +恐 +嬉 +雒 +倦 +衅 +亏 +璩 +睹 +刻 +殿 +王 +算 +雕 +麻 +丘 +柯 +骆 +丸 +塍 +谚 +添 +鲈 +垓 +桎 +蚯 +芥 +予 +飕 +镦 +谌 +窗 +醚 +菀 +亮 +搪 +莺 +蒿 +羁 +足 +J +真 +轶 +悬 +衷 +靛 +翊 +掩 +哒 +炅 +掐 +冼 +妮 +l +谐 +稚 +荆 +擒 +犯 +陵 +虏 +浓 +崽 +刍 +陌 +傻 +孜 +千 +靖 +演 +矜 +钕 +煽 +杰 +酗 +渗 +伞 +栋 +俗 +泫 +戍 +罕 +沾 +疽 +灏 +煦 +芬 +磴 +叱 +阱 +榉 +湃 +蜀 +叉 +醒 +彪 +租 +郡 +篷 +屎 +良 +垢 +隗 +弱 +陨 +峪 +砷 +掴 +颁 +胎 +雯 +绵 +贬 +沐 +撵 +隘 +篙 +暖 +曹 +陡 +栓 +填 +臼 +彦 +瓶 +琪 +潼 +哪 +鸡 +摩 +啦 +俟 +锋 +域 +耻 +蔫 +疯 +纹 +撇 +毒 +绶 +痛 +酯 +忍 +爪 +赳 +歆 +嘹 +辕 +烈 +册 +朴 +钱 +吮 +毯 +癜 +娃 +谀 +邵 +厮 +炽 +璞 +邃 +丐 +追 +词 +瓒 +忆 +轧 +芫 +谯 +喷 +弟 +半 +冕 +裙 +掖 +墉 +绮 +寝 +苔 +势 +顷 +褥 +切 +衮 +君 +佳 +嫒 +蚩 +霞 +佚 +洙 +逊 +镖 +暹 +唛 +& +殒 +顶 +碗 +獗 +轭 +铺 +蛊 +废 +恹 +汨 +崩 +珍 +那 +杵 +曲 +纺 +夏 +薰 +傀 +闳 +淬 +姘 +舀 +拧 +卷 +楂 +恍 +讪 +厩 +寮 +篪 +赓 +乘 +灭 +盅 +鞣 +沟 +慎 +挂 +饺 +鼾 +杳 +树 +缨 +丛 +絮 +娌 +臻 +嗳 +篡 +侩 +述 +衰 +矛 +圈 +蚜 +匕 +筹 +匿 +濞 +晨 +叶 +骋 +郝 +挚 +蚴 +滞 +增 +侍 +描 +瓣 +吖 +嫦 +蟒 +匾 +圣 +赌 +毡 +癞 +恺 +百 +曳 +需 +篓 +肮 +庖 +帏 +卿 +驿 +遗 +蹬 +鬓 +骡 +歉 +芎 +胳 +屐 +禽 +烦 +晌 +寄 +媾 +狄 +翡 +苒 +船 +廉 +终 +痞 +殇 +々 +畦 +饶 +改 +拆 +悻 +萄 +£ +瓿 +乃 +訾 +桅 +匮 +溧 +拥 +纱 +铍 +骗 +蕃 +龋 +缬 +父 +佐 +疚 +栎 +醍 +掳 +蓄 +x +惆 +颜 +鲆 +榆 +〔 +猎 +敌 +暴 +谥 +鲫 +贾 +罗 +玻 +缄 +扦 +芪 +癣 +落 +徒 +臾 +恿 +猩 +托 +邴 +肄 +牵 +春 +陛 +耀 +刊 +拓 +蓓 +邳 +堕 +寇 +枉 +淌 +啡 +湄 +兽 +酷 +萼 +碚 +濠 +萤 +夹 +旬 +戮 +梭 +琥 +椭 +昔 +勺 +蜊 +绐 +晚 +孺 +僵 +宣 +摄 +冽 +旨 +萌 +忙 +蚤 +眉 +噼 +蟑 +付 +契 +瓜 +悼 +颡 +壁 +曾 +窕 +颢 +澎 +仿 +俑 +浑 +嵌 +浣 +乍 +碌 +褪 +乱 +蔟 +隙 +玩 +剐 +葫 +箫 +纲 +围 +伐 +决 +伙 +漩 +瑟 +刑 +肓 +镳 +缓 +蹭 +氨 +皓 +典 +畲 +坍 +铑 +檐 +塑 +洞 +倬 +储 +胴 +淳 +戾 +吐 +灼 +惺 +妙 +毕 +珐 +缈 +虱 +盖 +羰 +鸿 +磅 +谓 +髅 +娴 +苴 +唷 +蚣 +霹 +抨 +贤 +唠 +犬 +誓 +逍 +庠 +逼 +麓 +籼 +釉 +呜 +碧 +秧 +氩 +摔 +霄 +穸 +纨 +辟 +妈 +映 +完 +牛 +缴 +嗷 +炊 +恩 +荔 +茆 +掉 +紊 +慌 +莓 +羟 +阙 +萁 +磐 +另 +蕹 +辱 +鳐 +湮 +吡 +吩 +唐 +睦 +垠 +舒 +圜 +冗 +瞿 +溺 +芾 +囱 +匠 +僳 +汐 +菩 +饬 +漓 +黑 +霰 +浸 +濡 +窥 +毂 +蒡 +兢 +驻 +鹉 +芮 +诙 +迫 +雳 +厂 +忐 +臆 +猴 +鸣 +蚪 +栈 +箕 +羡 +渐 +莆 +捍 +眈 +哓 +趴 +蹼 +埕 +嚣 +骛 +宏 +淄 +斑 +噜 +严 +瑛 +垃 +椎 +诱 +压 +庾 +绞 +焘 +廿 +抡 +迄 +棘 +夫 +纬 +锹 +眨 +瞌 +侠 +脐 +竞 +瀑 +孳 +骧 +遁 +姜 +颦 +荪 +滚 +萦 +伪 +逸 +粳 +爬 +锁 +矣 +役 +趣 +洒 +颔 +诏 +逐 +奸 +甭 +惠 +攀 +蹄 +泛 +尼 +拼 +阮 +鹰 +亚 +颈 +惑 +勒 +〉 +际 +肛 +爷 +刚 +钨 +丰 +养 +冶 +鲽 +辉 +蔻 +画 +覆 +皴 +妊 +麦 +返 +醉 +皂 +擀 +〗 +酶 +凑 +粹 +悟 +诀 +硖 +港 +卜 +z +杀 +涕 +± +舍 +铠 +抵 +弛 +段 +敝 +镐 +奠 +拂 +轴 +跛 +袱 +e +t +沉 +菇 +俎 +薪 +峦 +秭 +蟹 +历 +盟 +菠 +寡 +液 +肢 +喻 +染 +裱 +悱 +抱 +氙 +赤 +捅 +猛 +跑 +氮 +谣 +仁 +尺 +辊 +窍 +烙 +衍 +架 +擦 +倏 +璐 +瑁 +币 +楞 +胖 +夔 +趸 +邛 +惴 +饕 +虔 +蝎 +§ +哉 +贝 +宽 +辫 +炮 +扩 +饲 +籽 +魏 +菟 +锰 +伍 +猝 +末 +琳 +哚 +蛎 +邂 +呀 +姿 +鄞 +却 +歧 +仙 +恸 +椐 +森 +牒 +寤 +袒 +婆 +虢 +雅 +钉 +朵 +贼 +欲 +苞 +寰 +故 +龚 +坭 +嘘 +咫 +礼 +硷 +兀 +睢 +汶 +’ +铲 +烧 +绕 +诃 +浃 +钿 +哺 +柜 +讼 +颊 +璁 +腔 +洽 +咐 +脲 +簌 +筠 +镣 +玮 +鞠 +谁 +兼 +姆 +挥 +梯 +蝴 +谘 +漕 +刷 +躏 +宦 +弼 +b +垌 +劈 +麟 +莉 +揭 +笙 +渎 +仕 +嗤 +仓 +配 +怏 +抬 +错 +泯 +镊 +孰 +猿 +邪 +仍 +秋 +鼬 +壹 +歇 +吵 +炼 +< +尧 +射 +柬 +廷 +胧 +霾 +凳 +隋 +肚 +浮 +梦 +祥 +株 +堵 +退 +L +鹫 +跎 +凶 +毽 +荟 +炫 +栩 +玳 +甜 +沂 +鹿 +顽 +伯 +爹 +赔 +蛴 +徐 +匡 +欣 +狰 +缸 +雹 +蟆 +疤 +默 +沤 +啜 +痂 +衣 +禅 +w +i +h +辽 +葳 +黝 +钗 +停 +沽 +棒 +馨 +颌 +肉 +吴 +硫 +悯 +劾 +娈 +马 +啧 +吊 +悌 +镑 +峭 +帆 +瀣 +涉 +咸 +疸 +滋 +泣 +翦 +拙 +癸 +钥 +蜒 ++ +尾 +庄 +凝 +泉 +婢 +渴 +谊 +乞 +陆 +锉 +糊 +鸦 +淮 +I +B +N +晦 +弗 +乔 +庥 +葡 +尻 +席 +橡 +傣 +渣 +拿 +惩 +麋 +斛 +缃 +矮 +蛏 +岘 +鸽 +姐 +膏 +催 +奔 +镒 +喱 +蠡 +摧 +钯 +胤 +柠 +拐 +璋 +鸥 +卢 +荡 +倾 +^ +_ +珀 +逄 +萧 +塾 +掇 +贮 +笆 +聂 +圃 +冲 +嵬 +M +滔 +笕 +值 +炙 +偶 +蜱 +搐 +梆 +汪 +蔬 +腑 +鸯 +蹇 +敞 +绯 +仨 +祯 +谆 +梧 +糗 +鑫 +啸 +豺 +囹 +猾 +巢 +柄 +瀛 +筑 +踌 +沭 +暗 +苁 +鱿 +蹉 +脂 +蘖 +牢 +热 +木 +吸 +溃 +宠 +序 +泞 +偿 +拜 +檩 +厚 +朐 +毗 +螳 +吞 +媚 +朽 +担 +蝗 +橘 +畴 +祈 +糟 +盱 +隼 +郜 +惜 +珠 +裨 +铵 +焙 +琚 +唯 +咚 +噪 +骊 +丫 +滢 +勤 +棉 +呸 +咣 +淀 +隔 +蕾 +窈 +饨 +挨 +煅 +短 +匙 +粕 +镜 +赣 +撕 +墩 +酬 +馁 +豌 +颐 +抗 +酣 +氓 +佑 +搁 +哭 +递 +耷 +涡 +桃 +贻 +碣 +截 +瘦 +昭 +镌 +蔓 +氚 +甲 +猕 +蕴 +蓬 +散 +拾 +纛 +狼 +猷 +铎 +埋 +旖 +矾 +讳 +囊 +糜 +迈 +粟 +蚂 +紧 +鲳 +瘢 +栽 +稼 +羊 +锄 +斟 +睁 +桥 +瓮 +蹙 +祉 +醺 +鼻 +昱 +剃 +跳 +篱 +跷 +蒜 +翎 +宅 +晖 +嗑 +壑 +峻 +癫 +屏 +狠 +陋 +袜 +途 +憎 +祀 +莹 +滟 +佶 +溥 +臣 +约 +盛 +峰 +磁 +慵 +婪 +拦 +莅 +朕 +鹦 +粲 +裤 +哎 +疡 +嫖 +琵 +窟 +堪 +谛 +嘉 +儡 +鳝 +斩 +郾 +驸 +酊 +妄 +胜 +贺 +徙 +傅 +噌 +钢 +栅 +庇 +恋 +匝 +巯 +邈 +尸 +锚 +粗 +佟 +蛟 +薹 +纵 +蚊 +郅 +绢 +锐 +苗 +俞 +篆 +淆 +膀 +鲜 +煎 +诶 +秽 +寻 +涮 +刺 +怀 +噶 +巨 +褰 +魅 +灶 +灌 +桉 +藕 +谜 +舸 +薄 +搀 +恽 +借 +牯 +痉 +渥 +愿 +亓 +耘 +杠 +柩 +锔 +蚶 +钣 +珈 +喘 +蹒 +幽 +赐 +稗 +晤 +莱 +泔 +扯 +肯 +菪 +裆 +腩 +豉 +疆 +骜 +腐 +倭 +珏 +唔 +粮 +亡 +润 +慰 +伽 +橄 +玄 +誉 +醐 +胆 +龊 +粼 +塬 +陇 +彼 +削 +嗣 +绾 +芽 +妗 +垭 +瘴 +爽 +薏 +寨 +龈 +泠 +弹 +赢 +漪 +猫 +嘧 +涂 +恤 +圭 +茧 +烽 +屑 +痕 +巾 +赖 +荸 +凰 +腮 +畈 +亵 +蹲 +偃 +苇 +澜 +艮 +换 +骺 +烘 +苕 +梓 +颉 +肇 +哗 +悄 +氤 +涠 +葬 +屠 +鹭 +植 +竺 +佯 +诣 +鲇 +瘀 +鲅 +邦 +移 +滁 +冯 +耕 +癔 +戌 +茬 +沁 +巩 +悠 +湘 +洪 +痹 +锟 +循 +谋 +腕 +鳃 +钠 +捞 +焉 +迎 +碱 +伫 +急 +榷 +奈 +邝 +卯 +辄 +皲 +卟 +醛 +畹 +忧 +稳 +雄 +昼 +缩 +阈 +睑 +扌 +耗 +曦 +涅 +捏 +瞧 +邕 +淖 +漉 +铝 +耦 +禹 +湛 +喽 +莼 +琅 +诸 +苎 +纂 +硅 +始 +嗨 +傥 +燃 +臂 +赅 +嘈 +呆 +贵 +屹 +壮 +肋 +亍 +蚀 +卅 +豹 +腆 +邬 +迭 +浊 +} +童 +螂 +捐 +圩 +勐 +触 +寞 +汊 +壤 +荫 +膺 +渌 +芳 +懿 +遴 +螈 +泰 +蓼 +蛤 +茜 +舅 +枫 +朔 +膝 +眙 +避 +梅 +判 +鹜 +璜 +牍 +缅 +垫 +藻 +黔 +侥 +惚 +懂 +踩 +腰 +腈 +札 +丞 +唾 +慈 +顿 +摹 +荻 +琬 +~ +斧 +沈 +滂 +胁 +胀 +幄 +莜 +Z +匀 +鄄 +掌 +绰 +茎 +焚 +赋 +萱 +谑 +汁 +铒 +瞎 +夺 +蜗 +野 +娆 +冀 +弯 +篁 +懵 +灞 +隽 +芡 +脘 +俐 +辩 +芯 +掺 +喏 +膈 +蝈 +觐 +悚 +踹 +蔗 +熠 +鼠 +呵 +抓 +橼 +峨 +畜 +缔 +禾 +崭 +弃 +熊 +摒 +凸 +拗 +穹 +蒙 +抒 +祛 +劝 +闫 +扳 +阵 +醌 +踪 +喵 +侣 +搬 +仅 +荧 +赎 +蝾 +琦 +买 +婧 +瞄 +寓 +皎 +冻 +赝 +箩 +莫 +瞰 +郊 +笫 +姝 +筒 +枪 +遣 +煸 +袋 +舆 +痱 +涛 +母 +〇 +启 +践 +耙 +绲 +盘 +遂 +昊 +搞 +槿 +诬 +纰 +泓 +惨 +檬 +亻 +越 +C +o +憩 +熵 +祷 +钒 +暧 +塔 +阗 +胰 +咄 +娶 +魔 +琶 +钞 +邻 +扬 +杉 +殴 +咽 +弓 +〆 +髻 +】 +吭 +揽 +霆 +拄 +殖 +脆 +彻 +岩 +芝 +勃 +辣 +剌 +钝 +嘎 +甄 +佘 +皖 +伦 +授 +徕 +憔 +挪 +皇 +庞 +稔 +芜 +踏 +溴 +兖 +卒 +擢 +饥 +鳞 +煲 +‰ +账 +颗 +叻 +斯 +捧 +鳍 +琮 +讹 +蛙 +纽 +谭 +酸 +兔 +莒 +睇 +伟 +觑 +羲 +嗜 +宜 +褐 +旎 +辛 +卦 +诘 +筋 +鎏 +溪 +挛 +熔 +阜 +晰 +鳅 +丢 +奚 +灸 +呱 +献 +陉 +黛 +鸪 +甾 +萨 +疮 +拯 +洲 +疹 +辑 +叙 +恻 +谒 +允 +柔 +烂 +氏 +逅 +漆 +拎 +惋 +扈 +湟 +纭 +啕 +掬 +擞 +哥 +忽 +涤 +鸵 +靡 +郗 +瓷 +扁 +廊 +怨 +雏 +钮 +敦 +E +懦 +憋 +汀 +拚 +啉 +腌 +岸 +f +痼 +瞅 +尊 +咀 +眩 +飙 +忌 +仝 +迦 +熬 +毫 +胯 +篑 +茄 +腺 +凄 +舛 +碴 +锵 +诧 +羯 +後 +漏 +汤 +宓 +仞 +蚁 +壶 +谰 +皑 +铄 +棰 +罔 +辅 +晶 +苦 +牟 +闽 +\ +烃 +饮 +聿 +丙 +蛳 +朱 +煤 +涔 +鳖 +犁 +罐 +荼 +砒 +淦 +妤 +黏 +戎 +孑 +婕 +瑾 +戢 +钵 +枣 +捋 +砥 +衩 +狙 +桠 +稣 +阎 +肃 +梏 +诫 +孪 +昶 +婊 +衫 +嗔 +侃 +塞 +蜃 +樵 +峒 +貌 +屿 +欺 +缫 +阐 +栖 +诟 +珞 +荭 +吝 +萍 +嗽 +恂 +啻 +蜴 +磬 +峋 +俸 +豫 +谎 +徊 +镍 +韬 +魇 +晴 +U +囟 +猜 +蛮 +坐 +囿 +伴 +亭 +肝 +佗 +蝠 +妃 +胞 +滩 +榴 +氖 +垩 +苋 +砣 +扪 +馏 +姓 +轩 +厉 +夥 +侈 +禀 +垒 +岑 +赏 +钛 +辐 +痔 +披 +纸 +碳 +“ +坞 +蠓 +挤 +荥 +沅 +悔 +铧 +帼 +蒌 +蝇 +a +p +y +n +g +哀 +浆 +瑶 +凿 +桶 +馈 +皮 +奴 +苜 +佤 +伶 +晗 +铱 +炬 +优 +弊 +氢 +恃 +甫 +攥 +端 +锌 +灰 +稹 +炝 +曙 +邋 +亥 +眶 +碾 +拉 +萝 +绔 +捷 +浍 +腋 +姑 +菖 +凌 +涞 +麽 +锢 +桨 +潢 +绎 +镰 +殆 +锑 +渝 +铬 +困 +绽 +觎 +匈 +糙 +暑 +裹 +鸟 +盔 +肽 +迷 +綦 +『 +亳 +佝 +俘 +钴 +觇 +骥 +仆 +疝 +跪 +婶 +郯 +瀹 +唉 +脖 +踞 +针 +晾 +忒 +扼 +瞩 +叛 +椒 +疟 +嗡 +邗 +肆 +跆 +玫 +忡 +捣 +咧 +唆 +艄 +蘑 +潦 +笛 +阚 +沸 +泻 +掊 +菽 +贫 +斥 +髂 +孢 +镂 +赂 +麝 +鸾 +屡 +衬 +苷 +恪 +叠 +希 +粤 +爻 +喝 +茫 +惬 +郸 +绻 +庸 +撅 +碟 +宄 +妹 +膛 +叮 +饵 +崛 +嗲 +椅 +冤 +搅 +咕 +敛 +尹 +垦 +闷 +蝉 +霎 +勰 +败 +蓑 +泸 +肤 +鹌 +幌 +焦 +浠 +鞍 +刁 +舰 +乙 +竿 +裔 +。 +茵 +函 +伊 +兄 +丨 +娜 +匍 +謇 +莪 +宥 +似 +蝽 +翳 +酪 +翠 +粑 +薇 +祢 +骏 +赠 +叫 +Q +噤 +噻 +竖 +芗 +莠 +潭 +俊 +羿 +耜 +O +郫 +趁 +嗪 +囚 +蹶 +芒 +洁 +笋 +鹑 +敲 +硝 +啶 +堡 +渲 +揩 +』 +携 +宿 +遒 +颍 +扭 +棱 +割 +萜 +蔸 +葵 +琴 +捂 +饰 +衙 +耿 +掠 +募 +岂 +窖 +涟 +蔺 +瘤 +柞 +瞪 +怜 +匹 +距 +楔 +炜 +哆 +秦 +缎 +幼 +茁 +绪 +痨 +恨 +楸 +娅 +瓦 +桩 +雪 +嬴 +伏 +榔 +妥 +铿 +拌 +眠 +雍 +缇 +‘ +卓 +搓 +哌 +觞 +噩 +屈 +哧 +髓 +咦 +巅 +娑 +侑 +淫 +膳 +祝 +勾 +姊 +莴 +胄 +疃 +薛 +蜷 +胛 +巷 +芙 +芋 +熙 +闰 +勿 +窃 +狱 +剩 +钏 +幢 +陟 +铛 +慧 +靴 +耍 +k +浙 +浇 +飨 +惟 +绗 +祜 +澈 +啼 +咪 +磷 +摞 +诅 +郦 +抹 +跃 +壬 +吕 +肖 +琏 +颤 +尴 +剡 +抠 +凋 +赚 +泊 +津 +宕 +殷 +倔 +氲 +漫 +邺 +涎 +怠 +$ +垮 +荬 +遵 +俏 +叹 +噢 +饽 +蜘 +孙 +筵 +疼 +鞭 +羧 +牦 +箭 +潴 +c +眸 +祭 +髯 +啖 +坳 +愁 +芩 +驮 +倡 +巽 +穰 +沃 +胚 +怒 +凤 +槛 +剂 +趵 +嫁 +v +邢 +灯 +鄢 +桐 +睽 +檗 +锯 +槟 +婷 +嵋 +圻 +诗 +蕈 +颠 +遭 +痢 +芸 +怯 +馥 +竭 +锗 +徜 +恭 +遍 +籁 +剑 +嘱 +苡 +龄 +僧 +桑 +潸 +弘 +澶 +楹 +悲 +讫 +愤 +腥 +悸 +谍 +椹 +呢 +桓 +葭 +攫 +阀 +翰 +躲 +敖 +柑 +郎 +笨 +橇 +呃 +魁 +燎 +脓 +葩 +磋 +垛 +玺 +狮 +沓 +砜 +蕊 +锺 +罹 +蕉 +翱 +虐 +闾 +巫 +旦 +茱 +嬷 +枯 +鹏 +贡 +芹 +汛 +矫 +绁 +拣 +禺 +佃 +讣 +舫 +惯 +乳 +趋 +疲 +挽 +岚 +虾 +衾 +蠹 +蹂 +飓 +氦 +铖 +孩 +稞 +瑜 +壅 +掀 +勘 +妓 +畅 +髋 +W +庐 +牲 +蓿 +榕 +练 +垣 +唱 +邸 +菲 +昆 +婺 +穿 +绡 +麒 +蚱 +掂 +愚 +泷 +涪 +漳 +妩 +娉 +榄 +讷 +觅 +旧 +藤 +煮 +呛 +柳 +腓 +叭 +庵 +烷 +阡 +罂 +蜕 +擂 +猖 +咿 +媲 +脉 +【 +沏 +貅 +黠 +熏 +哲 +烁 +坦 +酵 +兜 +× +潇 +撒 +剽 +珩 +圹 +乾 +摸 +樟 +帽 +嗒 +襄 +魂 +轿 +憬 +锡 +〕 +喃 +皆 +咖 +隅 +脸 +残 +泮 +袂 +鹂 +珊 +囤 +捆 +咤 +误 +徨 +闹 +淙 +芊 +淋 +怆 +囗 +拨 +梳 +渤 +R +G +绨 +蚓 +婀 +幡 +狩 +麾 +谢 +唢 +裸 +旌 +伉 +纶 +裂 +驳 +砼 +咛 +澄 +樨 +蹈 +宙 +澍 +倍 +貔 +操 +勇 +蟠 +摈 +砧 +虬 +够 +缁 +悦 +藿 +撸 +艹 +摁 +淹 +豇 +虎 +榭 +ˉ +吱 +d +° +喧 +荀 +踱 +侮 +奋 +偕 +饷 +犍 +惮 +坑 +璎 +徘 +宛 +妆 +袈 +倩 +窦 +昂 +荏 +乖 +K +怅 +撰 +鳙 +牙 +袁 +酞 +X +痿 +琼 +闸 +雁 +趾 +荚 +虻 +涝 +《 +杏 +韭 +偈 +烤 +绫 +鞘 +卉 +症 +遢 +蓥 +诋 +杭 +荨 +匆 +竣 +簪 +辙 +敕 +虞 +丹 +缭 +咩 +黟 +m +淤 +瑕 +咂 +铉 +硼 +茨 +嶂 +痒 +畸 +敬 +涿 +粪 +窘 +熟 +叔 +嫔 +盾 +忱 +裘 +憾 +梵 +赡 +珙 +咯 +娘 +庙 +溯 +胺 +葱 +痪 +摊 +荷 +卞 +乒 +髦 +寐 +铭 +坩 +胗 +枷 +爆 +溟 +嚼 +羚 +砬 +轨 +惊 +挠 +罄 +竽 +菏 +氧 +浅 +楣 +盼 +枢 +炸 +阆 +杯 +谏 +噬 +淇 +渺 +俪 +秆 +墓 +泪 +跻 +砌 +痰 +垡 +渡 +耽 +釜 +讶 +鳎 +煞 +呗 +韶 +舶 +绷 +鹳 +缜 +旷 +铊 +皱 +龌 +檀 +霖 +奄 +槐 +艳 +蝶 +旋 +哝 +赶 +骞 +蚧 +腊 +盈 +丁 +` +蜚 +矸 +蝙 +睨 +嚓 +僻 +鬼 +醴 +夜 +彝 +磊 +笔 +拔 +栀 +糕 +厦 +邰 +纫 +逭 +纤 +眦 +膊 +馍 +躇 +烯 +蘼 +冬 +诤 +暄 +骶 +哑 +瘠 +」 +臊 +丕 +愈 +咱 +螺 +擅 +跋 +搏 +硪 +谄 +笠 +淡 +嘿 +骅 +谧 +鼎 +皋 +姚 +歼 +蠢 +驼 +耳 +胬 +挝 +涯 +狗 +蒽 +孓 +犷 +凉 +芦 +箴 +铤 +孤 +嘛 +坤 +V +茴 +朦 +挞 +尖 +橙 +诞 +搴 +碇 +洵 +浚 +帚 +蜍 +漯 +柘 +嚎 +讽 +芭 +荤 +咻 +祠 +秉 +跖 +埃 +吓 +糯 +眷 +馒 +惹 +娼 +鲑 +嫩 +讴 +轮 +瞥 +靶 +褚 +乏 +缤 +宋 +帧 +删 +驱 +碎 +扑 +俩 +俄 +偏 +涣 +竹 +噱 +皙 +佰 +渚 +唧 +斡 +# +镉 +刀 +崎 +筐 +佣 +夭 +贰 +肴 +峙 +哔 +艿 +匐 +牺 +镛 +缘 +仡 +嫡 +劣 +枸 +堀 +梨 +簿 +鸭 +蒸 +亦 +稽 +浴 +{ +衢 +束 +槲 +j +阁 +揍 +疥 +棋 +潋 +聪 +窜 +乓 +睛 +插 +冉 +阪 +苍 +搽 +「 +蟾 +螟 +幸 +仇 +樽 +撂 +慢 +跤 +幔 +俚 +淅 +覃 +觊 +溶 +妖 +帛 +侨 +曰 +妾 +泗 +· +: +瀘 +風 +Ë +( +) +∶ +紅 +紗 +瑭 +雲 +頭 +鶏 +財 +許 +• +¥ +樂 +焗 +麗 +— +; +滙 +東 +榮 +繪 +興 +… +門 +業 +π +楊 +國 +顧 +é +盤 +寳 +Λ +龍 +鳳 +島 +誌 +緣 +結 +銭 +萬 +勝 +祎 +璟 +優 +歡 +臨 +時 +購 += +★ +藍 +昇 +鐵 +觀 +勅 +農 +聲 +畫 +兿 +術 +發 +劉 +記 +專 +耑 +園 +書 +壴 +種 +Ο +● +褀 +號 +銀 +匯 +敟 +锘 +葉 +橪 +廣 +進 +蒄 +鑽 +阝 +祙 +貢 +鍋 +豊 +夬 +喆 +團 +閣 +開 +燁 +賓 +館 +酡 +沔 +順 ++ +硚 +劵 +饸 +陽 +車 +湓 +復 +萊 +氣 +軒 +華 +堃 +迮 +纟 +戶 +馬 +學 +裡 +電 +嶽 +獨 +マ +シ +サ +ジ +燘 +袪 +環 +❤ +臺 +灣 +専 +賣 +孖 +聖 +攝 +線 +▪ +α +傢 +俬 +夢 +達 +莊 +喬 +貝 +薩 +劍 +羅 +壓 +棛 +饦 +尃 +璈 +囍 +醫 +G +I +A +# +N +鷄 +髙 +嬰 +啓 +約 +隹 +潔 +賴 +藝 +~ +寶 +籣 +麺 +  +嶺 +√ +義 +網 +峩 +長 +∧ +魚 +機 +構 +② +鳯 +偉 +L +B +㙟 +畵 +鴿 +' +詩 +溝 +嚞 +屌 +藔 +佧 +玥 +蘭 +織 +1 +3 +9 +0 +7 +點 +砭 +鴨 +鋪 +銘 +廳 +弍 +‧ +創 +湯 +坶 +℃ +卩 +骝 +& +烜 +荘 +當 +潤 +扞 +係 +懷 +碶 +钅 +蚨 +讠 +☆ +叢 +爲 +埗 +涫 +塗 +→ +楽 +現 +鯨 +愛 +瑪 +鈺 +忄 +悶 +藥 +飾 +樓 +視 +孬 +ㆍ +燚 +苪 +師 +① +丼 +锽 +│ +韓 +標 +è +兒 +閏 +匋 +張 +漢 +Ü +髪 +會 +閑 +檔 +習 +裝 +の +峯 +菘 +輝 +И +雞 +釣 +億 +浐 +K +O +R +8 +H +E +P +T +W +D +S +C +M +F +姌 +饹 +» +晞 +廰 +ä +嵯 +鷹 +負 +飲 +絲 +冚 +楗 +澤 +綫 +區 +❋ +← +質 +靑 +揚 +③ +滬 +統 +産 +協 +﹑ +乸 +畐 +經 +運 +際 +洺 +岽 +為 +粵 +諾 +崋 +豐 +碁 +ɔ +V +2 +6 +齋 +誠 +訂 +´ +勑 +雙 +陳 +無 +í +泩 +媄 +夌 +刂 +i +c +t +o +r +a +嘢 +耄 +燴 +暃 +壽 +媽 +靈 +抻 +體 +唻 +É +冮 +甹 +鎮 +錦 +ʌ +蜛 +蠄 +尓 +駕 +戀 +飬 +逹 +倫 +貴 +極 +Я +Й +寬 +磚 +嶪 +郎 +職 +| +間 +n +d +剎 +伈 +課 +飛 +橋 +瘊 +№ +譜 +骓 +圗 +滘 +縣 +粿 +咅 +養 +濤 +彳 +® +% +Ⅱ +啰 +㴪 +見 +矞 +薬 +糁 +邨 +鲮 +顔 +罱 +З +選 +話 +贏 +氪 +俵 +競 +瑩 +繡 +枱 +β +綉 +á +獅 +爾 +™ +麵 +戋 +淩 +徳 +個 +劇 +場 +務 +簡 +寵 +h +實 +膠 +轱 +圖 +築 +嘣 +樹 +㸃 +營 +耵 +孫 +饃 +鄺 +飯 +麯 +遠 +輸 +坫 +孃 +乚 +閃 +鏢 +㎡ +題 +廠 +關 +↑ +爺 +將 +軍 +連 +篦 +覌 +參 +箸 +- +窠 +棽 +寕 +夀 +爰 +歐 +呙 +閥 +頡 +熱 +雎 +垟 +裟 +凬 +勁 +帑 +馕 +夆 +疌 +枼 +馮 +貨 +蒤 +樸 +彧 +旸 +靜 +龢 +暢 +㐱 +鳥 +珺 +鏡 +灡 +爭 +堷 +廚 +Ó +騰 +診 +┅ +蘇 +褔 +凱 +頂 +豕 +亞 +帥 +嘬 +⊥ +仺 +桖 +複 +饣 +絡 +穂 +顏 +棟 +納 +▏ +濟 +親 +設 +計 +攵 +埌 +烺 +ò +頤 +燦 +蓮 +撻 +節 +講 +濱 +濃 +娽 +洳 +朿 +燈 +鈴 +護 +膚 +铔 +過 +補 +Z +U +5 +4 +坋 +闿 +䖝 +餘 +缐 +铞 +貿 +铪 +桼 +趙 +鍊 +[ +㐂 +垚 +菓 +揸 +捲 +鐘 +滏 +𣇉 +爍 +輪 +燜 +鴻 +鮮 +動 +鹞 +鷗 +丄 +慶 +鉌 +翥 +飮 +腸 +⇋ +漁 +覺 +來 +熘 +昴 +翏 +鲱 +圧 +鄉 +萭 +頔 +爐 +嫚 +г +貭 +類 +聯 +幛 +輕 +訓 +鑒 +夋 +锨 +芃 +珣 +䝉 +扙 +嵐 +銷 +處 +ㄱ +語 +誘 +苝 +歸 +儀 +燒 +楿 +內 +粢 +葒 +奧 +麥 +礻 +滿 +蠔 +穵 +瞭 +態 +鱬 +榞 +硂 +鄭 +黃 +煙 +祐 +奓 +逺 +* +瑄 +獲 +聞 +薦 +讀 +這 +樣 +決 +問 +啟 +們 +執 +説 +轉 +單 +隨 +唘 +帶 +倉 +庫 +還 +贈 +尙 +皺 +■ +餅 +產 +○ +∈ +報 +狀 +楓 +賠 +琯 +嗮 +禮 +` +傳 +> +≤ +嗞 +Φ +≥ +換 +咭 +∣ +↓ +曬 +ε +応 +寫 +″ +終 +様 +純 +費 +療 +聨 +凍 +壐 +郵 +ü +黒 +∫ +製 +塊 +調 +軽 +確 +撃 +級 +馴 +Ⅲ +涇 +繹 +數 +碼 +證 +狒 +処 +劑 +< +晧 +賀 +衆 +] +櫥 +兩 +陰 +絶 +對 +鯉 +憶 +◎ +p +e +Y +蕒 +煖 +頓 +測 +試 +鼽 +僑 +碩 +妝 +帯 +≈ +鐡 +舖 +權 +喫 +倆 +ˋ +該 +悅 +ā +俫 +. +f +s +b +m +k +g +u +j +貼 +淨 +濕 +針 +適 +備 +l +/ +給 +謢 +強 +觸 +衛 +與 +⊙ +$ +緯 +變 +⑴ +⑵ +⑶ +㎏ +殺 +∩ +幚 +─ +價 +▲ +離 +ú +ó +飄 +烏 +関 +閟 +﹝ +﹞ +邏 +輯 +鍵 +驗 +訣 +導 +歷 +屆 +層 +▼ +儱 +錄 +熳 +ē +艦 +吋 +錶 +辧 +飼 +顯 +④ +禦 +販 +気 +対 +枰 +閩 +紀 +幹 +瞓 +貊 +淚 +△ +眞 +墊 +Ω +獻 +褲 +縫 +緑 +亜 +鉅 +餠 +{ +} +◆ +蘆 +薈 +█ +◇ +溫 +彈 +晳 +粧 +犸 +穩 +訊 +崬 +凖 +熥 +П +舊 +條 +紋 +圍 +Ⅳ +筆 +尷 +難 +雜 +錯 +綁 +識 +頰 +鎖 +艶 +□ +殁 +殼 +⑧ +├ +▕ +鵬 +ǐ +ō +ǒ +糝 +綱 +▎ +μ +盜 +饅 +醬 +籤 +蓋 +釀 +鹽 +據 +à +ɡ +辦 +◥ +彐 +┌ +婦 +獸 +鲩 +伱 +ī +蒟 +蒻 +齊 +袆 +腦 +寧 +凈 +妳 +煥 +詢 +偽 +謹 +啫 +鯽 +騷 +鱸 +損 +傷 +鎻 +髮 +買 +冏 +儥 +両 +﹢ +∞ +載 +喰 +z +羙 +悵 +燙 +曉 +員 +組 +徹 +艷 +痠 +鋼 +鼙 +縮 +細 +嚒 +爯 +≠ +維 +" +鱻 +壇 +厍 +帰 +浥 +犇 +薡 +軎 +² +應 +醜 +刪 +緻 +鶴 +賜 +噁 +軌 +尨 +镔 +鷺 +槗 +彌 +葚 +濛 +請 +溇 +緹 +賢 +訪 +獴 +瑅 +資 +縤 +陣 +蕟 +栢 +韻 +祼 +恁 +伢 +謝 +劃 +涑 +總 +衖 +踺 +砋 +凉 +籃 +駿 +苼 +瘋 +昽 +紡 +驊 +腎 +﹗ +響 +杋 +剛 +嚴 +禪 +歓 +槍 +傘 +檸 +檫 +炣 +勢 +鏜 +鎢 +銑 +尐 +減 +奪 +惡 +θ +僮 +婭 +臘 +ū +ì +殻 +鉄 +∑ +蛲 +焼 +緖 +續 +紹 +懮 \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/profiler.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e28bc6bea9ca912a0786d879a48ec0349e7698 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/profiler.py @@ -0,0 +1,110 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +import sys +import paddle + +# A global variable to record the number of calling times for profiler +# functions. It is used to specify the tracing range of training steps. +_profiler_step_id = 0 + +# A global variable to avoid parsing from string every time. +_profiler_options = None + + +class ProfilerOptions(object): + ''' + Use a string to initialize a ProfilerOptions. + The string should be in the format: "key1=value1;key2=value;key3=value3". + For example: + "profile_path=model.profile" + "batch_range=[50, 60]; profile_path=model.profile" + "batch_range=[50, 60]; tracer_option=OpDetail; profile_path=model.profile" + ProfilerOptions supports following key-value pair: + batch_range - a integer list, e.g. [100, 110]. + state - a string, the optional values are 'CPU', 'GPU' or 'All'. + sorted_key - a string, the optional values are 'calls', 'total', + 'max', 'min' or 'ave. + tracer_option - a string, the optional values are 'Default', 'OpDetail', + 'AllOpDetail'. + profile_path - a string, the path to save the serialized profile data, + which can be used to generate a timeline. + exit_on_finished - a boolean. + ''' + + def __init__(self, options_str): + assert isinstance(options_str, str) + + self._options = { + 'batch_range': [10, 20], + 'state': 'All', + 'sorted_key': 'total', + 'tracer_option': 'Default', + 'profile_path': '/tmp/profile', + 'exit_on_finished': True + } + self._parse_from_string(options_str) + + def _parse_from_string(self, options_str): + for kv in options_str.replace(' ', '').split(';'): + key, value = kv.split('=') + if key == 'batch_range': + value_list = value.replace('[', '').replace(']', '').split(',') + value_list = list(map(int, value_list)) + if len(value_list) >= 2 and value_list[0] >= 0 and value_list[ + 1] > value_list[0]: + self._options[key] = value_list + elif key == 'exit_on_finished': + self._options[key] = value.lower() in ("yes", "true", "t", "1") + elif key in [ + 'state', 'sorted_key', 'tracer_option', 'profile_path' + ]: + self._options[key] = value + + def __getitem__(self, name): + if self._options.get(name, None) is None: + raise ValueError( + "ProfilerOptions does not have an option named %s." % name) + return self._options[name] + + +def add_profiler_step(options_str=None): + ''' + Enable the operator-level timing using PaddlePaddle's profiler. + The profiler uses a independent variable to count the profiler steps. + One call of this function is treated as a profiler step. + + Args: + profiler_options - a string to initialize the ProfilerOptions. + Default is None, and the profiler is disabled. + ''' + if options_str is None: + return + + global _profiler_step_id + global _profiler_options + + if _profiler_options is None: + _profiler_options = ProfilerOptions(options_str) + + if _profiler_step_id == _profiler_options['batch_range'][0]: + paddle.utils.profiler.start_profiler( + _profiler_options['state'], _profiler_options['tracer_option']) + elif _profiler_step_id == _profiler_options['batch_range'][1]: + paddle.utils.profiler.stop_profiler(_profiler_options['sorted_key'], + _profiler_options['profile_path']) + if _profiler_options['exit_on_finished']: + sys.exit(0) + + _profiler_step_id += 1 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/save_load.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/save_load.py new file mode 100644 index 0000000000000000000000000000000000000000..aa65f290c0a5f4f13b3103fb4404815e2ae74a88 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/save_load.py @@ -0,0 +1,220 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. +# +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import errno +import os +import pickle +import six + +import paddle + +from ppocr.utils.logging import get_logger + +__all__ = ['load_model'] + + +def _mkdir_if_not_exist(path, logger): + """ + mkdir if not exists, ignore the exception when multiprocess mkdir together + """ + if not os.path.exists(path): + try: + os.makedirs(path) + except OSError as e: + if e.errno == errno.EEXIST and os.path.isdir(path): + logger.warning( + 'be happy if some process has already created {}'.format( + path)) + else: + raise OSError('Failed to mkdir {}'.format(path)) + + +def load_model(config, model, optimizer=None, model_type='det'): + """ + load model from checkpoint or pretrained_model + """ + logger = get_logger() + global_config = config['Global'] + checkpoints = global_config.get('checkpoints') + pretrained_model = global_config.get('pretrained_model') + best_model_dict = {} + is_float16 = False + is_nlp_model = model_type == 'kie' and config["Architecture"][ + "algorithm"] not in ["SDMGR"] + + if is_nlp_model is True: + # NOTE: for kie model dsitillation, resume training is not supported now + if config["Architecture"]["algorithm"] in ["Distillation"]: + return best_model_dict + checkpoints = config['Architecture']['Backbone']['checkpoints'] + # load kie method metric + if checkpoints: + if os.path.exists(os.path.join(checkpoints, 'metric.states')): + with open(os.path.join(checkpoints, 'metric.states'), + 'rb') as f: + states_dict = pickle.load(f) if six.PY2 else pickle.load( + f, encoding='latin1') + best_model_dict = states_dict.get('best_model_dict', {}) + if 'epoch' in states_dict: + best_model_dict['start_epoch'] = states_dict['epoch'] + 1 + logger.info("resume from {}".format(checkpoints)) + + if optimizer is not None: + if checkpoints[-1] in ['/', '\\']: + checkpoints = checkpoints[:-1] + if os.path.exists(checkpoints + '.pdopt'): + optim_dict = paddle.load(checkpoints + '.pdopt') + optimizer.set_state_dict(optim_dict) + else: + logger.warning( + "{}.pdopt is not exists, params of optimizer is not loaded". + format(checkpoints)) + + return best_model_dict + + if checkpoints: + if checkpoints.endswith('.pdparams'): + checkpoints = checkpoints.replace('.pdparams', '') + assert os.path.exists(checkpoints + ".pdparams"), \ + "The {}.pdparams does not exists!".format(checkpoints) + + # load params from trained model + params = paddle.load(checkpoints + '.pdparams') + state_dict = model.state_dict() + new_state_dict = {} + for key, value in state_dict.items(): + if key not in params: + logger.warning("{} not in loaded params {} !".format( + key, params.keys())) + continue + pre_value = params[key] + if pre_value.dtype == paddle.float16: + is_float16 = True + if pre_value.dtype != value.dtype: + pre_value = pre_value.astype(value.dtype) + if list(value.shape) == list(pre_value.shape): + new_state_dict[key] = pre_value + else: + logger.warning( + "The shape of model params {} {} not matched with loaded params shape {} !". + format(key, value.shape, pre_value.shape)) + model.set_state_dict(new_state_dict) + if is_float16: + logger.info( + "The parameter type is float16, which is converted to float32 when loading" + ) + if optimizer is not None: + if os.path.exists(checkpoints + '.pdopt'): + optim_dict = paddle.load(checkpoints + '.pdopt') + optimizer.set_state_dict(optim_dict) + else: + logger.warning( + "{}.pdopt is not exists, params of optimizer is not loaded". + format(checkpoints)) + + if os.path.exists(checkpoints + '.states'): + with open(checkpoints + '.states', 'rb') as f: + states_dict = pickle.load(f) if six.PY2 else pickle.load( + f, encoding='latin1') + best_model_dict = states_dict.get('best_model_dict', {}) + if 'epoch' in states_dict: + best_model_dict['start_epoch'] = states_dict['epoch'] + 1 + logger.info("resume from {}".format(checkpoints)) + elif pretrained_model: + is_float16 = load_pretrained_params(model, pretrained_model) + else: + logger.info('train from scratch') + best_model_dict['is_float16'] = is_float16 + return best_model_dict + + +def load_pretrained_params(model, path): + logger = get_logger() + if path.endswith('.pdparams'): + path = path.replace('.pdparams', '') + assert os.path.exists(path + ".pdparams"), \ + "The {}.pdparams does not exists!".format(path) + + params = paddle.load(path + '.pdparams') + + state_dict = model.state_dict() + + new_state_dict = {} + is_float16 = False + + for k1 in params.keys(): + + if k1 not in state_dict.keys(): + logger.warning("The pretrained params {} not in model".format(k1)) + else: + if params[k1].dtype == paddle.float16: + is_float16 = True + if params[k1].dtype != state_dict[k1].dtype: + params[k1] = params[k1].astype(state_dict[k1].dtype) + if list(state_dict[k1].shape) == list(params[k1].shape): + new_state_dict[k1] = params[k1] + else: + logger.warning( + "The shape of model params {} {} not matched with loaded params {} {} !". + format(k1, state_dict[k1].shape, k1, params[k1].shape)) + + model.set_state_dict(new_state_dict) + if is_float16: + logger.info( + "The parameter type is float16, which is converted to float32 when loading" + ) + logger.info("load pretrain successful from {}".format(path)) + return is_float16 + + +def save_model(model, + optimizer, + model_path, + logger, + config, + is_best=False, + prefix='ppocr', + **kwargs): + """ + save model to the target path + """ + _mkdir_if_not_exist(model_path, logger) + model_prefix = os.path.join(model_path, prefix) + paddle.save(optimizer.state_dict(), model_prefix + '.pdopt') + + is_nlp_model = config['Architecture']["model_type"] == 'kie' and config[ + "Architecture"]["algorithm"] not in ["SDMGR"] + if is_nlp_model is not True: + paddle.save(model.state_dict(), model_prefix + '.pdparams') + metric_prefix = model_prefix + else: # for kie system, we follow the save/load rules in NLP + if config['Global']['distributed']: + arch = model._layers + else: + arch = model + if config["Architecture"]["algorithm"] in ["Distillation"]: + arch = arch.Student + arch.backbone.model.save_pretrained(model_prefix) + metric_prefix = os.path.join(model_prefix, 'metric') + # save metric and config + with open(metric_prefix + '.states', 'wb') as f: + pickle.dump(kwargs, f, protocol=2) + if is_best: + logger.info('save best model is to {}'.format(model_prefix)) + else: + logger.info("save model in {}".format(model_prefix)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/stats.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/stats.py new file mode 100755 index 0000000000000000000000000000000000000000..179b0082f16133ac202c6f0dc120ec07c10fd18e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/stats.py @@ -0,0 +1,72 @@ +# 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. + +import collections +import numpy as np +import datetime + +__all__ = ['TrainingStats', 'Time'] + + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size): + self.deque = collections.deque(maxlen=window_size) + + def add_value(self, value): + self.deque.append(value) + + def get_median_value(self): + return np.median(self.deque) + + +def Time(): + return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') + + +class TrainingStats(object): + def __init__(self, window_size, stats_keys): + self.window_size = window_size + self.smoothed_losses_and_metrics = { + key: SmoothedValue(window_size) + for key in stats_keys + } + + def update(self, stats): + for k, v in stats.items(): + if k not in self.smoothed_losses_and_metrics: + self.smoothed_losses_and_metrics[k] = SmoothedValue( + self.window_size) + self.smoothed_losses_and_metrics[k].add_value(v) + + def get(self, extras=None): + stats = collections.OrderedDict() + if extras: + for k, v in extras.items(): + stats[k] = v + for k, v in self.smoothed_losses_and_metrics.items(): + stats[k] = round(v.get_median_value(), 6) + + return stats + + def log(self, extras=None): + d = self.get(extras) + strs = [] + for k, v in d.items(): + strs.append('{}: {:x<6f}'.format(k, v)) + strs = ', '.join(strs) + return strs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/utility.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/utility.py new file mode 100755 index 0000000000000000000000000000000000000000..18357c8e97bcea8ee321856a87146a4a7b901469 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/utility.py @@ -0,0 +1,150 @@ +# 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. + +import logging +import os +import imghdr +import cv2 +import random +import numpy as np +import paddle + + +def print_dict(d, logger, delimiter=0): + """ + Recursively visualize a dict and + indenting acrrording by the relationship of keys. + """ + for k, v in sorted(d.items()): + if isinstance(v, dict): + logger.info("{}{} : ".format(delimiter * " ", str(k))) + print_dict(v, logger, delimiter + 4) + elif isinstance(v, list) and len(v) >= 1 and isinstance(v[0], dict): + logger.info("{}{} : ".format(delimiter * " ", str(k))) + for value in v: + print_dict(value, logger, delimiter + 4) + else: + logger.info("{}{} : {}".format(delimiter * " ", k, v)) + + +def get_check_global_params(mode): + check_params = ['use_gpu', 'max_text_length', 'image_shape', \ + 'image_shape', 'character_type', 'loss_type'] + if mode == "train_eval": + check_params = check_params + [ \ + 'train_batch_size_per_card', 'test_batch_size_per_card'] + elif mode == "test": + check_params = check_params + ['test_batch_size_per_card'] + return check_params + + +def _check_image_file(path): + img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'pdf'} + return any([path.lower().endswith(e) for e in img_end]) + + +def get_image_file_list(img_file): + imgs_lists = [] + if img_file is None or not os.path.exists(img_file): + raise Exception("not found any img file in {}".format(img_file)) + + img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'pdf'} + if os.path.isfile(img_file) and _check_image_file(img_file): + imgs_lists.append(img_file) + elif os.path.isdir(img_file): + for single_file in os.listdir(img_file): + file_path = os.path.join(img_file, single_file) + if os.path.isfile(file_path) and _check_image_file(file_path): + imgs_lists.append(file_path) + if len(imgs_lists) == 0: + raise Exception("not found any img file in {}".format(img_file)) + imgs_lists = sorted(imgs_lists) + return imgs_lists + + +def check_and_read(img_path): + if os.path.basename(img_path)[-3:] in ['gif', 'GIF']: + gif = cv2.VideoCapture(img_path) + ret, frame = gif.read() + if not ret: + logger = logging.getLogger('ppocr') + logger.info("Cannot read {}. This gif image maybe corrupted.") + return None, False + if len(frame.shape) == 2 or frame.shape[-1] == 1: + frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB) + imgvalue = frame[:, :, ::-1] + return imgvalue, True, False + elif os.path.basename(img_path)[-3:] in ['pdf']: + import fitz + from PIL import Image + imgs = [] + with fitz.open(img_path) as pdf: + for pg in range(0, pdf.pageCount): + page = pdf[pg] + mat = fitz.Matrix(2, 2) + pm = page.getPixmap(matrix=mat, alpha=False) + + # if width or height > 2000 pixels, don't enlarge the image + if pm.width > 2000 or pm.height > 2000: + pm = page.getPixmap(matrix=fitz.Matrix(1, 1), alpha=False) + + img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples) + img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) + imgs.append(img) + return imgs, False, True + return None, False, False + + +def load_vqa_bio_label_maps(label_map_path): + with open(label_map_path, "r", encoding='utf-8') as fin: + lines = fin.readlines() + old_lines = [line.strip() for line in lines] + lines = ["O"] + for line in old_lines: + # "O" has already been in lines + if line.upper() in ["OTHER", "OTHERS", "IGNORE"]: + continue + lines.append(line) + labels = ["O"] + for line in lines[1:]: + labels.append("B-" + line) + labels.append("I-" + line) + label2id_map = {label.upper(): idx for idx, label in enumerate(labels)} + id2label_map = {idx: label.upper() for idx, label in enumerate(labels)} + return label2id_map, id2label_map + + +def set_seed(seed=1024): + random.seed(seed) + np.random.seed(seed) + paddle.seed(seed) + + +class AverageMeter: + def __init__(self): + self.reset() + + def reset(self): + """reset""" + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + """update""" + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/visual.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/visual.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd805ea6e76be37612a142102beab492bece941 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/ppocr/utils/visual.py @@ -0,0 +1,123 @@ +# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. +# +# 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. +import cv2 +import os +import numpy as np +from PIL import Image, ImageDraw, ImageFont + + +def draw_ser_results(image, + ocr_results, + font_path="doc/fonts/simfang.ttf", + font_size=14): + np.random.seed(2021) + color = (np.random.permutation(range(255)), + np.random.permutation(range(255)), + np.random.permutation(range(255))) + color_map = { + idx: (color[0][idx], color[1][idx], color[2][idx]) + for idx in range(1, 255) + } + if isinstance(image, np.ndarray): + image = Image.fromarray(image) + elif isinstance(image, str) and os.path.isfile(image): + image = Image.open(image).convert('RGB') + img_new = image.copy() + draw = ImageDraw.Draw(img_new) + + font = ImageFont.truetype(font_path, font_size, encoding="utf-8") + for ocr_info in ocr_results: + if ocr_info["pred_id"] not in color_map: + continue + color = color_map[ocr_info["pred_id"]] + text = "{}: {}".format(ocr_info["pred"], ocr_info["transcription"]) + + if "bbox" in ocr_info: + # draw with ocr engine + bbox = ocr_info["bbox"] + else: + # draw with ocr groundtruth + bbox = trans_poly_to_bbox(ocr_info["points"]) + draw_box_txt(bbox, text, draw, font, font_size, color) + + img_new = Image.blend(image, img_new, 0.5) + return np.array(img_new) + + +def draw_box_txt(bbox, text, draw, font, font_size, color): + # draw ocr results outline + bbox = ((bbox[0], bbox[1]), (bbox[2], bbox[3])) + draw.rectangle(bbox, fill=color) + + # draw ocr results + start_y = max(0, bbox[0][1] - font_size) + tw = font.getsize(text)[0] + draw.rectangle( + [(bbox[0][0] + 1, start_y), (bbox[0][0] + tw + 1, start_y + font_size)], + fill=(0, 0, 255)) + draw.text((bbox[0][0] + 1, start_y), text, fill=(255, 255, 255), font=font) + + +def trans_poly_to_bbox(poly): + x1 = np.min([p[0] for p in poly]) + x2 = np.max([p[0] for p in poly]) + y1 = np.min([p[1] for p in poly]) + y2 = np.max([p[1] for p in poly]) + return [x1, y1, x2, y2] + + +def draw_re_results(image, + result, + font_path="doc/fonts/simfang.ttf", + font_size=18): + np.random.seed(0) + if isinstance(image, np.ndarray): + image = Image.fromarray(image) + elif isinstance(image, str) and os.path.isfile(image): + image = Image.open(image).convert('RGB') + img_new = image.copy() + draw = ImageDraw.Draw(img_new) + + font = ImageFont.truetype(font_path, font_size, encoding="utf-8") + color_head = (0, 0, 255) + color_tail = (255, 0, 0) + color_line = (0, 255, 0) + + for ocr_info_head, ocr_info_tail in result: + draw_box_txt(ocr_info_head["bbox"], ocr_info_head["transcription"], + draw, font, font_size, color_head) + draw_box_txt(ocr_info_tail["bbox"], ocr_info_tail["transcription"], + draw, font, font_size, color_tail) + + center_head = ( + (ocr_info_head['bbox'][0] + ocr_info_head['bbox'][2]) // 2, + (ocr_info_head['bbox'][1] + ocr_info_head['bbox'][3]) // 2) + center_tail = ( + (ocr_info_tail['bbox'][0] + ocr_info_tail['bbox'][2]) // 2, + (ocr_info_tail['bbox'][1] + ocr_info_tail['bbox'][3]) // 2) + + draw.line([center_head, center_tail], fill=color_line, width=5) + + img_new = Image.blend(image, img_new, 0.5) + return np.array(img_new) + + +def draw_rectangle(img_path, boxes): + boxes = np.array(boxes) + img = cv2.imread(img_path) + img_show = img.copy() + for box in boxes.astype(int): + x1, y1, x2, y2 = box + cv2.rectangle(img_show, (x1, y1), (x2, y2), (255, 0, 0), 2) + return img_show \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/readme.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..0fb91ec5b04c33f64fe180bea83808e60726c6bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/readme.txt @@ -0,0 +1,15 @@ + +目标是把 paddlepaddle 的所有依赖都转移到本地,既是不再需要安装 paddlepaddle==2.4.2 这个特定版本的包 + +proxychains4 conda create -n ppstandalone python=3.10 pip -y && +conda activate ppstandalone + +/root/miniforge3/envs/ppstandalone/lib/python3.10/site-packages/paddle + move paddle form here + +rm -rf ~/miniforge3/envs/ppstandalone && +conda deactivate + # 转完以后删掉它 + +visualdl==2.5.3 + # protobuf-5.28.0 依赖在这里面 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2e544ec65e43747a68bbd77c3f7c5910c878a64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt @@ -0,0 +1,61 @@ +######### PaddleOCR_ali1k_det_rec_300epoch begin ######################## +astor==0.8.1 +attrdict==2.0.1 +babel==2.16.0 +bce-python-sdk==0.9.21 +blinker==1.8.2 +cachetools==5.5.0 +certifi==2024.8.30 +charset-normalizer==3.3.2 +click==8.1.7 +contourpy==1.3.0 +cssselect==1.2.0 +cssutils==2.11.1 +cycler==0.12.1 +Cython==3.0.11 +decorator==5.1.1 +et-xmlfile==1.1.0 +Flask==3.0.3 +flask-babel==4.0.0 +fonttools==4.53.1 +future==1.0.0 +idna==3.8 +imageio==2.35.1 +imgaug==0.4.0 +itsdangerous==2.2.0 +Jinja2==3.1.4 +kiwisolver==1.4.5 +lazy_loader==0.4 +lmdb==1.5.1 +lxml==5.3.0 +MarkupSafe==2.1.5 +matplotlib==3.9.2 +more-itertools==10.4.0 +networkx==3.3 +numpy==1.26.4 +opencv-contrib-python==4.10.0.84 +opencv-python==4.6.0.66 +openpyxl==3.1.5 +opt-einsum==3.3.0 +packaging==24.1 +pillow==10.4.0 +premailer==3.10.0 +psutil==6.0.0 +pyclipper==1.3.0.post5 +pycryptodome==3.20.0 +pyparsing==3.1.4 +python-dateutil==2.9.0.post0 +pytz==2024.1 +rapidfuzz==3.9.7 +rarfile==4.2 +requests==2.32.3 +scikit-image==0.24.0 +scipy==1.14.1 +shapely==2.0.6 +six==1.16.0 +tifffile==2024.8.30 +tqdm==4.66.5 +tzdata==2024.1 +urllib3==2.2.2 +Werkzeug==3.0.4 +######### PaddleOCR_ali1k_det_rec_300epoch end ######################## \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d56c9dbaa1304b160521da03c05db2352e341bf2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. +# +# 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. diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/convert_ppocr_label.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/convert_ppocr_label.py new file mode 100644 index 0000000000000000000000000000000000000000..c64b9ed168113879182262b609bea692fcb73165 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/convert_ppocr_label.py @@ -0,0 +1,100 @@ +# Copyright (c) 2022 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. +import numpy as np +import json +import os + + +def poly_to_string(poly): + if len(poly.shape) > 1: + poly = np.array(poly).flatten() + + string = "\t".join(str(i) for i in poly) + return string + + +def convert_label(label_dir, mode="gt", save_dir="./save_results/"): + if not os.path.exists(label_dir): + raise ValueError(f"The file {label_dir} does not exist!") + + assert label_dir != save_dir, "hahahhaha" + + label_file = open(label_dir, 'r') + data = label_file.readlines() + + gt_dict = {} + + for line in data: + try: + tmp = line.split('\t') + assert len(tmp) == 2, "" + except: + tmp = line.strip().split(' ') + + gt_lists = [] + + if tmp[0].split('/')[0] is not None: + img_path = tmp[0] + anno = json.loads(tmp[1]) + gt_collect = [] + for dic in anno: + #txt = dic['transcription'].replace(' ', '') # ignore blank + txt = dic['transcription'] + if 'score' in dic and float(dic['score']) < 0.5: + continue + if u'\u3000' in txt: txt = txt.replace(u'\u3000', u' ') + #while ' ' in txt: + # txt = txt.replace(' ', '') + poly = np.array(dic['points']).flatten() + if txt == "###": + txt_tag = 1 ## ignore 1 + else: + txt_tag = 0 + if mode == "gt": + gt_label = poly_to_string(poly) + "\t" + str( + txt_tag) + "\t" + txt + "\n" + else: + gt_label = poly_to_string(poly) + "\t" + txt + "\n" + + gt_lists.append(gt_label) + + gt_dict[img_path] = gt_lists + else: + continue + + if not os.path.exists(save_dir): + os.makedirs(save_dir) + + for img_name in gt_dict.keys(): + save_name = img_name.split("/")[-1] + save_file = os.path.join(save_dir, save_name + ".txt") + with open(save_file, "w") as f: + f.writelines(gt_dict[img_name]) + + print("The convert label saved in {}".format(save_dir)) + + +def parse_args(): + import argparse + parser = argparse.ArgumentParser(description="args") + parser.add_argument("--label_path", type=str, required=True) + parser.add_argument("--save_folder", type=str, required=True) + parser.add_argument("--mode", type=str, default=False) + args = parser.parse_args() + return args + + +if __name__ == "__main__": + args = parse_args() + convert_label(args.label_path, args.mode, args.save_folder) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/draw_html.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/draw_html.py new file mode 100644 index 0000000000000000000000000000000000000000..fcac8ad3bfb6f0d1fcc48ea026b0febe60a001c0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/draw_html.py @@ -0,0 +1,73 @@ +# Copyright (c) 2022 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. + +import os +import argparse + + +def str2bool(v): + return v.lower() in ("true", "t", "1") + + +def init_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--image_dir", type=str, default="") + parser.add_argument("--save_html_path", type=str, default="./default.html") + parser.add_argument("--width", type=int, default=640) + return parser + + +def parse_args(): + parser = init_args() + return parser.parse_args() + + +def draw_debug_img(args): + + html_path = args.save_html_path + + err_cnt = 0 + with open(html_path, 'w') as html: + html.write('\n\n') + html.write('\n') + html.write( + "" + ) + image_list = [] + path = args.image_dir + for i, filename in enumerate(sorted(os.listdir(path))): + if filename.endswith("txt"): continue + # The image path + base = "{}/{}".format(path, filename) + html.write("\n") + html.write(f'') + + html.write("\n") + html.write('\n') + html.write('
{filename}\n GT') + html.write(f'GT\n
\n') + html.write('\n\n') + print(f"The html file saved in {html_path}") + return + + +if __name__ == "__main__": + + args = parse_args() + + draw_debug_img(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/eval_end2end.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/eval_end2end.py new file mode 100644 index 0000000000000000000000000000000000000000..dd37940845b60d55291b40b8cd50d6afd5b91f94 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/eval_end2end.py @@ -0,0 +1,193 @@ +# Copyright (c) 2022 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. + +import os +import re +import sys +import shapely +from shapely.geometry import Polygon +import numpy as np +from collections import defaultdict +import operator +import editdistance + + +def strQ2B(ustring): + rstring = "" + for uchar in ustring: + inside_code = ord(uchar) + if inside_code == 12288: + inside_code = 32 + elif (inside_code >= 65281 and inside_code <= 65374): + inside_code -= 65248 + rstring += chr(inside_code) + return rstring + + +def polygon_from_str(polygon_points): + """ + Create a shapely polygon object from gt or dt line. + """ + polygon_points = np.array(polygon_points).reshape(4, 2) + polygon = Polygon(polygon_points).convex_hull + return polygon + + +def polygon_iou(poly1, poly2): + """ + Intersection over union between two shapely polygons. + """ + if not poly1.intersects( + poly2): # this test is fast and can accelerate calculation + iou = 0 + else: + try: + inter_area = poly1.intersection(poly2).area + union_area = poly1.area + poly2.area - inter_area + iou = float(inter_area) / union_area + except shapely.geos.TopologicalError: + # except Exception as e: + # print(e) + print('shapely.geos.TopologicalError occurred, iou set to 0') + iou = 0 + return iou + + +def ed(str1, str2): + return editdistance.eval(str1, str2) + + +def e2e_eval(gt_dir, res_dir, ignore_blank=False): + print('start testing...') + iou_thresh = 0.5 + val_names = os.listdir(gt_dir) + num_gt_chars = 0 + gt_count = 0 + dt_count = 0 + hit = 0 + ed_sum = 0 + + for i, val_name in enumerate(val_names): + with open(os.path.join(gt_dir, val_name), encoding='utf-8') as f: + gt_lines = [o.strip() for o in f.readlines()] + gts = [] + ignore_masks = [] + for line in gt_lines: + parts = line.strip().split('\t') + # ignore illegal data + if len(parts) < 9: + continue + assert (len(parts) < 11) + if len(parts) == 9: + gts.append(parts[:8] + ['']) + else: + gts.append(parts[:8] + [parts[-1]]) + + ignore_masks.append(parts[8]) + + val_path = os.path.join(res_dir, val_name) + if not os.path.exists(val_path): + dt_lines = [] + else: + with open(val_path, encoding='utf-8') as f: + dt_lines = [o.strip() for o in f.readlines()] + dts = [] + for line in dt_lines: + # print(line) + parts = line.strip().split("\t") + assert (len(parts) < 10), "line error: {}".format(line) + if len(parts) == 8: + dts.append(parts + ['']) + else: + dts.append(parts) + + dt_match = [False] * len(dts) + gt_match = [False] * len(gts) + all_ious = defaultdict(tuple) + for index_gt, gt in enumerate(gts): + gt_coors = [float(gt_coor) for gt_coor in gt[0:8]] + gt_poly = polygon_from_str(gt_coors) + for index_dt, dt in enumerate(dts): + dt_coors = [float(dt_coor) for dt_coor in dt[0:8]] + dt_poly = polygon_from_str(dt_coors) + iou = polygon_iou(dt_poly, gt_poly) + if iou >= iou_thresh: + all_ious[(index_gt, index_dt)] = iou + sorted_ious = sorted( + all_ious.items(), key=operator.itemgetter(1), reverse=True) + sorted_gt_dt_pairs = [item[0] for item in sorted_ious] + + # matched gt and dt + for gt_dt_pair in sorted_gt_dt_pairs: + index_gt, index_dt = gt_dt_pair + if gt_match[index_gt] == False and dt_match[index_dt] == False: + gt_match[index_gt] = True + dt_match[index_dt] = True + if ignore_blank: + gt_str = strQ2B(gts[index_gt][8]).replace(" ", "") + dt_str = strQ2B(dts[index_dt][8]).replace(" ", "") + else: + gt_str = strQ2B(gts[index_gt][8]) + dt_str = strQ2B(dts[index_dt][8]) + if ignore_masks[index_gt] == '0': + ed_sum += ed(gt_str, dt_str) + num_gt_chars += len(gt_str) + if gt_str == dt_str: + hit += 1 + gt_count += 1 + dt_count += 1 + + # unmatched dt + for tindex, dt_match_flag in enumerate(dt_match): + if dt_match_flag == False: + dt_str = dts[tindex][8] + gt_str = '' + ed_sum += ed(dt_str, gt_str) + dt_count += 1 + + # unmatched gt + for tindex, gt_match_flag in enumerate(gt_match): + if gt_match_flag == False and ignore_masks[tindex] == '0': + dt_str = '' + gt_str = gts[tindex][8] + ed_sum += ed(gt_str, dt_str) + num_gt_chars += len(gt_str) + gt_count += 1 + + eps = 1e-9 + print('hit, dt_count, gt_count', hit, dt_count, gt_count) + precision = hit / (dt_count + eps) + recall = hit / (gt_count + eps) + fmeasure = 2.0 * precision * recall / (precision + recall + eps) + avg_edit_dist_img = ed_sum / len(val_names) + avg_edit_dist_field = ed_sum / (gt_count + eps) + character_acc = 1 - ed_sum / (num_gt_chars + eps) + + print('character_acc: %.2f' % (character_acc * 100) + "%") + print('avg_edit_dist_field: %.2f' % (avg_edit_dist_field)) + print('avg_edit_dist_img: %.2f' % (avg_edit_dist_img)) + print('precision: %.2f' % (precision * 100) + "%") + print('recall: %.2f' % (recall * 100) + "%") + print('fmeasure: %.2f' % (fmeasure * 100) + "%") + + +if __name__ == '__main__': + # if len(sys.argv) != 3: + # print("python3 ocr_e2e_eval.py gt_dir res_dir") + # exit(-1) + # gt_folder = sys.argv[1] + # pred_folder = sys.argv[2] + gt_folder = sys.argv[1] + pred_folder = sys.argv[2] + e2e_eval(gt_folder, pred_folder) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/readme.md b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..636ee764aef35a551f729cce20c16357ddf4f495 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/end2end/readme.md @@ -0,0 +1,63 @@ + +# 简介 + +`tools/end2end`目录下存放了文本检测+文本识别pipeline串联预测的指标评测代码以及可视化工具。本节介绍文本检测+文本识别的端对端指标评估方式。 + + +## 端对端评测步骤 + +**步骤一:** + +运行`tools/infer/predict_system.py`,得到保存的结果: + +``` +python3 tools/infer/predict_system.py --det_model_dir=./ch_PP-OCRv2_det_infer/ --rec_model_dir=./ch_PP-OCRv2_rec_infer/ --image_dir=./datasets/img_dir/ --draw_img_save_dir=./ch_PP-OCRv2_results/ --is_visualize=True +``` + +文本检测识别可视化图默认保存在`./ch_PP-OCRv2_results/`目录下,预测结果默认保存在`./ch_PP-OCRv2_results/system_results.txt`中,格式如下: +``` +all-sum-510/00224225.jpg [{"transcription": "超赞", "points": [[8.0, 48.0], [157.0, 44.0], [159.0, 115.0], [10.0, 119.0]], "score": "0.99396634"}, {"transcription": "中", "points": [[202.0, 152.0], [230.0, 152.0], [230.0, 163.0], [202.0, 163.0]], "score": "0.09310734"}, {"transcription": "58.0m", "points": [[196.0, 192.0], [444.0, 192.0], [444.0, 240.0], [196.0, 240.0]], "score": "0.44041982"}, {"transcription": "汽配", "points": [[55.0, 263.0], [95.0, 263.0], [95.0, 281.0], [55.0, 281.0]], "score": "0.9986651"}, {"transcription": "成总店", "points": [[120.0, 262.0], [176.0, 262.0], [176.0, 283.0], [120.0, 283.0]], "score": "0.9929402"}, {"transcription": "K", "points": [[237.0, 286.0], [311.0, 286.0], [311.0, 345.0], [237.0, 345.0]], "score": "0.6074794"}, {"transcription": "88:-8", "points": [[203.0, 405.0], [477.0, 414.0], [475.0, 459.0], [201.0, 450.0]], "score": "0.7106863"}] +``` + + +**步骤二:** + +将步骤一保存的数据转换为端对端评测需要的数据格式: + +修改 `tools/end2end/convert_ppocr_label.py`中的代码,convert_label函数中设置输入标签路径,Mode,保存标签路径等,对预测数据的GTlabel和预测结果的label格式进行转换。 + +``` +python3 tools/end2end/convert_ppocr_label.py --mode=gt --label_path=path/to/label_txt --save_folder=save_gt_label + +python3 tools/end2end/convert_ppocr_label.py --mode=pred --label_path=path/to/pred_txt --save_folder=save_PPOCRV2_infer +``` + +得到如下结果: +``` +├── ./save_gt_label/ +├── ./save_PPOCRV2_infer/ +``` + +**步骤三:** + +执行端对端评测,运行`tools/eval_end2end.py`计算端对端指标,运行方式如下: + +``` +python3 tools/eval_end2end.py "gt_label_dir" "predict_label_dir" +``` + +比如: + +``` +python3 tools/eval_end2end.py ./save_gt_label/ ./save_PPOCRV2_infer/ +``` +将得到如下结果,fmeasure为主要关注的指标: +``` +hit, dt_count, gt_count 1557 2693 3283 +character_acc: 61.77% +avg_edit_dist_field: 3.08 +avg_edit_dist_img: 51.82 +precision: 57.82% +recall: 47.43% +fmeasure: 52.11% +``` diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/eval.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/eval.py new file mode 100755 index 0000000000000000000000000000000000000000..3d1d3813d33e251ec83a9729383fe772bc4cc225 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/eval.py @@ -0,0 +1,131 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, __dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +import paddle +from ppocr.data import build_dataloader +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.metrics import build_metric +from ppocr.utils.save_load import load_model +import tools.program as program + + +def main(): + global_config = config['Global'] + # build dataloader + valid_dataloader = build_dataloader(config, 'Eval', device, logger) + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + # for rec algorithm + if hasattr(post_process_class, 'character'): + char_num = len(getattr(post_process_class, 'character')) + if config['Architecture']["algorithm"] in ["Distillation", + ]: # distillation model + for key in config['Architecture']["Models"]: + if config['Architecture']['Models'][key]['Head'][ + 'name'] == 'MultiHead': # for multi head + out_channels_list = {} + if config['PostProcess'][ + 'name'] == 'DistillationSARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Models'][key]['Head'][ + 'out_channels_list'] = out_channels_list + else: + config['Architecture']["Models"][key]["Head"][ + 'out_channels'] = char_num + elif config['Architecture']['Head'][ + 'name'] == 'MultiHead': # for multi head + out_channels_list = {} + if config['PostProcess']['name'] == 'SARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Head'][ + 'out_channels_list'] = out_channels_list + else: # base rec model + config['Architecture']["Head"]['out_channels'] = char_num + + model = build_model(config['Architecture']) + extra_input_models = ["SRN", "NRTR", "SAR", "SEED", "SVTR", "VisionLAN", "RobustScanner"] + extra_input = False + if config['Architecture']['algorithm'] == 'Distillation': + for key in config['Architecture']["Models"]: + extra_input = extra_input or config['Architecture']['Models'][key][ + 'algorithm'] in extra_input_models + else: + extra_input = config['Architecture']['algorithm'] in extra_input_models + if "model_type" in config['Architecture'].keys(): + model_type = config['Architecture']['model_type'] + else: + model_type = None + + # build metric + eval_class = build_metric(config['Metric']) + # amp + use_amp = config["Global"].get("use_amp", False) + amp_level = config["Global"].get("amp_level", 'O2') + amp_custom_black_list = config['Global'].get('amp_custom_black_list',[]) + if use_amp: + AMP_RELATED_FLAGS_SETTING = { + 'FLAGS_cudnn_batchnorm_spatial_persistent': 1, + 'FLAGS_max_inplace_grad_add': 8, + } + paddle.fluid.set_flags(AMP_RELATED_FLAGS_SETTING) + scale_loss = config["Global"].get("scale_loss", 1.0) + use_dynamic_loss_scaling = config["Global"].get( + "use_dynamic_loss_scaling", False) + scaler = paddle.amp.GradScaler( + init_loss_scaling=scale_loss, + use_dynamic_loss_scaling=use_dynamic_loss_scaling) + if amp_level == "O2": + model = paddle.amp.decorate( + models=model, level=amp_level, master_weight=True) + else: + scaler = None + + best_model_dict = load_model( + config, model, model_type=config['Architecture']["model_type"]) + if len(best_model_dict): + logger.info('metric in ckpt ***************') + for k, v in best_model_dict.items(): + logger.info('{}:{}'.format(k, v)) + + # start eval + metric = program.eval(model, valid_dataloader, post_process_class, + eval_class, model_type, extra_input, scaler, amp_level, amp_custom_black_list) + logger.info('metric eval ***************') + for k, v in metric.items(): + logger.info('{}:{}'.format(k, v)) + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_center.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_center.py new file mode 100644 index 0000000000000000000000000000000000000000..30b9c33499b8d0c8044682c6a078e00f683c1d7c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_center.py @@ -0,0 +1,77 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +import pickle + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.append(os.path.abspath(os.path.join(__dir__, '..'))) + +from ppocr.data import build_dataloader +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import print_dict +import tools.program as program + + +def main(): + global_config = config['Global'] + # build dataloader + config['Eval']['dataset']['name'] = config['Train']['dataset']['name'] + config['Eval']['dataset']['data_dir'] = config['Train']['dataset'][ + 'data_dir'] + config['Eval']['dataset']['label_file_list'] = config['Train']['dataset'][ + 'label_file_list'] + eval_dataloader = build_dataloader(config, 'Eval', device, logger) + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + # for rec algorithm + if hasattr(post_process_class, 'character'): + char_num = len(getattr(post_process_class, 'character')) + config['Architecture']["Head"]['out_channels'] = char_num + + #set return_features = True + config['Architecture']["Head"]["return_feats"] = True + + model = build_model(config['Architecture']) + + best_model_dict = load_model(config, model) + if len(best_model_dict): + logger.info('metric in ckpt ***************') + for k, v in best_model_dict.items(): + logger.info('{}:{}'.format(k, v)) + + # get features from train data + char_center = program.get_center(model, eval_dataloader, post_process_class) + + #serialize to disk + with open("train_center.pkl", 'wb') as f: + pickle.dump(char_center, f) + return + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_model.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_model.py new file mode 100755 index 0000000000000000000000000000000000000000..4b91462a3b40bb6db73d0ad91d6b3cf96673f2a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/export_model.py @@ -0,0 +1,256 @@ +# 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. + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, ".."))) + +import argparse + +import paddle +from paddle.jit import to_static + +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.logging import get_logger +from tools.program import load_config, merge_config, ArgsParser + + +def export_single_model(model, + arch_config, + save_path, + logger, + input_shape=None, + quanter=None): + if arch_config["algorithm"] == "SRN": + max_text_length = arch_config["Head"]["max_text_length"] + other_shape = [ + paddle.static.InputSpec( + shape=[None, 1, 64, 256], dtype="float32"), [ + paddle.static.InputSpec( + shape=[None, 256, 1], + dtype="int64"), paddle.static.InputSpec( + shape=[None, max_text_length, 1], dtype="int64"), + paddle.static.InputSpec( + shape=[None, 8, max_text_length, max_text_length], + dtype="int64"), paddle.static.InputSpec( + shape=[None, 8, max_text_length, max_text_length], + dtype="int64") + ] + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "SAR": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 48, 160], dtype="float32"), + [paddle.static.InputSpec( + shape=[None], dtype="float32")] + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "SVTR": + if arch_config["Head"]["name"] == 'MultiHead': + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 48, -1], dtype="float32"), + ] + else: + other_shape = [ + paddle.static.InputSpec( + shape=[None] + input_shape, dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "PREN": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 64, 512], dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["model_type"] == "sr": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 16, 64], dtype="float32") + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "ViTSTR": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 1, 224, 224], dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "ABINet": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 32, 128], dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] in ["NRTR", "SPIN"]: + other_shape = [ + paddle.static.InputSpec( + shape=[None, 1, 32, 100], dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "VisionLAN": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 64, 256], dtype="float32"), + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "RobustScanner": + max_text_length = arch_config["Head"]["max_text_length"] + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 48, 160], dtype="float32"), [ + paddle.static.InputSpec( + shape=[None, ], dtype="float32"), + paddle.static.InputSpec( + shape=[None, max_text_length], dtype="int64") + ] + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] == "SEED": + other_shape = [ + paddle.static.InputSpec( + shape=[None, 3, 64, 256], dtype="float32") + ] + model = to_static(model, input_spec=other_shape) + elif arch_config["algorithm"] in ["LayoutLM", "LayoutLMv2", "LayoutXLM"]: + input_spec = [ + paddle.static.InputSpec( + shape=[None, 512], dtype="int64"), # input_ids + paddle.static.InputSpec( + shape=[None, 512, 4], dtype="int64"), # bbox + paddle.static.InputSpec( + shape=[None, 512], dtype="int64"), # attention_mask + paddle.static.InputSpec( + shape=[None, 512], dtype="int64"), # token_type_ids + paddle.static.InputSpec( + shape=[None, 3, 224, 224], dtype="int64"), # image + ] + if model.backbone.use_visual_backbone is False: + input_spec.pop(4) + model = to_static(model, input_spec=[input_spec]) + else: + infer_shape = [3, -1, -1] + if arch_config["model_type"] == "rec": + infer_shape = [3, 32, -1] # for rec model, H must be 32 + if "Transform" in arch_config and arch_config[ + "Transform"] is not None and arch_config["Transform"][ + "name"] == "TPS": + logger.info( + "When there is tps in the network, variable length input is not supported, and the input size needs to be the same as during training" + ) + infer_shape[-1] = 100 + elif arch_config["model_type"] == "table": + infer_shape = [3, 488, 488] + if arch_config["algorithm"] == "TableMaster": + infer_shape = [3, 480, 480] + if arch_config["algorithm"] == "SLANet": + infer_shape = [3, -1, -1] + model = to_static( + model, + input_spec=[ + paddle.static.InputSpec( + shape=[None] + infer_shape, dtype="float32") + ]) + + if quanter is None: + paddle.jit.save(model, save_path) + else: + quanter.save_quantized_model(model, save_path) + logger.info("inference model is saved to {}".format(save_path)) + return + + +def main(): + FLAGS = ArgsParser().parse_args() + config = load_config(FLAGS.config) + config = merge_config(config, FLAGS.opt) + logger = get_logger() + # build post process + + post_process_class = build_post_process(config["PostProcess"], + config["Global"]) + + # build model + # for rec algorithm + if hasattr(post_process_class, "character"): + char_num = len(getattr(post_process_class, "character")) + if config["Architecture"]["algorithm"] in ["Distillation", + ]: # distillation model + for key in config["Architecture"]["Models"]: + if config["Architecture"]["Models"][key]["Head"][ + "name"] == 'MultiHead': # multi head + out_channels_list = {} + if config['PostProcess'][ + 'name'] == 'DistillationSARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Models'][key]['Head'][ + 'out_channels_list'] = out_channels_list + else: + config["Architecture"]["Models"][key]["Head"][ + "out_channels"] = char_num + # just one final tensor needs to exported for inference + config["Architecture"]["Models"][key][ + "return_all_feats"] = False + elif config['Architecture']['Head'][ + 'name'] == 'MultiHead': # multi head + out_channels_list = {} + char_num = len(getattr(post_process_class, 'character')) + if config['PostProcess']['name'] == 'SARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Head'][ + 'out_channels_list'] = out_channels_list + else: # base rec model + config["Architecture"]["Head"]["out_channels"] = char_num + + # for sr algorithm + if config["Architecture"]["model_type"] == "sr": + config['Architecture']["Transform"]['infer_mode'] = True + model = build_model(config["Architecture"]) + load_model(config, model, model_type=config['Architecture']["model_type"]) + model.eval() + + save_path = config["Global"]["save_inference_dir"] + + arch_config = config["Architecture"] + + if arch_config["algorithm"] == "SVTR" and arch_config["Head"][ + "name"] != 'MultiHead': + input_shape = config["Eval"]["dataset"]["transforms"][-2][ + 'SVTRRecResizeImg']['image_shape'] + else: + input_shape = None + + if arch_config["algorithm"] in ["Distillation", ]: # distillation model + archs = list(arch_config["Models"].values()) + for idx, name in enumerate(model.model_name_list): + sub_model_save_path = os.path.join(save_path, name, "inference") + export_single_model(model.model_list[idx], archs[idx], + sub_model_save_path, logger) + else: + save_path = os.path.join(save_path, "inference") + export_single_model( + model, arch_config, save_path, logger, input_shape=input_shape) + + +if __name__ == "__main__": + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_cls.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_cls.py new file mode 100755 index 0000000000000000000000000000000000000000..d2b7108ca35666acfa53e785686fd7b9dfc21ed5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_cls.py @@ -0,0 +1,151 @@ +# 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. +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import copy +import numpy as np +import math +import time +import traceback + +import tools.infer.utility as utility +from ppocr.postprocess import build_post_process +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, check_and_read + +logger = get_logger() + + +class TextClassifier(object): + def __init__(self, args): + self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")] + self.cls_batch_num = args.cls_batch_num + self.cls_thresh = args.cls_thresh + postprocess_params = { + 'name': 'ClsPostProcess', + "label_list": args.label_list, + } + self.postprocess_op = build_post_process(postprocess_params) + self.predictor, self.input_tensor, self.output_tensors, _ = \ + utility.create_predictor(args, 'cls', logger) + self.use_onnx = args.use_onnx + + def resize_norm_img(self, img): + imgC, imgH, imgW = self.cls_image_shape + h = img.shape[0] + w = img.shape[1] + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = cv2.resize(img, (resized_w, imgH)) + resized_image = resized_image.astype('float32') + if self.cls_image_shape[0] == 1: + resized_image = resized_image / 255 + resized_image = resized_image[np.newaxis, :] + else: + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + padding_im[:, :, 0:resized_w] = resized_image + return padding_im + + def __call__(self, img_list): + img_list = copy.deepcopy(img_list) + img_num = len(img_list) + # Calculate the aspect ratio of all text bars + width_list = [] + for img in img_list: + width_list.append(img.shape[1] / float(img.shape[0])) + # Sorting can speed up the cls process + indices = np.argsort(np.array(width_list)) + + cls_res = [['', 0.0]] * img_num + batch_num = self.cls_batch_num + elapse = 0 + for beg_img_no in range(0, img_num, batch_num): + + end_img_no = min(img_num, beg_img_no + batch_num) + norm_img_batch = [] + max_wh_ratio = 0 + starttime = time.time() + for ino in range(beg_img_no, end_img_no): + h, w = img_list[indices[ino]].shape[0:2] + wh_ratio = w * 1.0 / h + max_wh_ratio = max(max_wh_ratio, wh_ratio) + for ino in range(beg_img_no, end_img_no): + norm_img = self.resize_norm_img(img_list[indices[ino]]) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + norm_img_batch = np.concatenate(norm_img_batch) + norm_img_batch = norm_img_batch.copy() + + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = norm_img_batch + outputs = self.predictor.run(self.output_tensors, input_dict) + prob_out = outputs[0] + else: + self.input_tensor.copy_from_cpu(norm_img_batch) + self.predictor.run() + prob_out = self.output_tensors[0].copy_to_cpu() + self.predictor.try_shrink_memory() + cls_result = self.postprocess_op(prob_out) + elapse += time.time() - starttime + for rno in range(len(cls_result)): + label, score = cls_result[rno] + cls_res[indices[beg_img_no + rno]] = [label, score] + if '180' in label and score > self.cls_thresh: + img_list[indices[beg_img_no + rno]] = cv2.rotate( + img_list[indices[beg_img_no + rno]], 1) + return img_list, cls_res, elapse + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + text_classifier = TextClassifier(args) + valid_image_file_list = [] + img_list = [] + for image_file in image_file_list: + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + valid_image_file_list.append(image_file) + img_list.append(img) + try: + img_list, cls_res, predict_time = text_classifier(img_list) + except Exception as E: + logger.info(traceback.format_exc()) + logger.info(E) + exit() + for ino in range(len(img_list)): + logger.info("Predicts of {}:{}".format(valid_image_file_list[ino], + cls_res[ino])) + + +if __name__ == "__main__": + main(utility.parse_args()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_det.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_det.py new file mode 100755 index 0000000000000000000000000000000000000000..9f5c480d3c55367a02eacb48bed6ae3d38282f05 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_det.py @@ -0,0 +1,320 @@ +# 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. +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import numpy as np +import time +import sys + +import tools.infer.utility as utility +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, check_and_read +from ppocr.data import create_operators, transform +from ppocr.postprocess import build_post_process +import json +logger = get_logger() + + +class TextDetector(object): + def __init__(self, args): + self.args = args + self.det_algorithm = args.det_algorithm + self.use_onnx = args.use_onnx + pre_process_list = [{ + 'DetResizeForTest': { + 'limit_side_len': args.det_limit_side_len, + 'limit_type': args.det_limit_type, + } + }, { + 'NormalizeImage': { + 'std': [0.229, 0.224, 0.225], + 'mean': [0.485, 0.456, 0.406], + 'scale': '1./255.', + 'order': 'hwc' + } + }, { + 'ToCHWImage': None + }, { + 'KeepKeys': { + 'keep_keys': ['image', 'shape'] + } + }] + postprocess_params = {} + if self.det_algorithm == "DB": + postprocess_params['name'] = 'DBPostProcess' + postprocess_params["thresh"] = args.det_db_thresh + postprocess_params["box_thresh"] = args.det_db_box_thresh + postprocess_params["max_candidates"] = 1000 + postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio + postprocess_params["use_dilation"] = args.use_dilation + postprocess_params["score_mode"] = args.det_db_score_mode + elif self.det_algorithm == "DB++": + postprocess_params['name'] = 'DBPostProcess' + postprocess_params["thresh"] = args.det_db_thresh + postprocess_params["box_thresh"] = args.det_db_box_thresh + postprocess_params["max_candidates"] = 1000 + postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio + postprocess_params["use_dilation"] = args.use_dilation + postprocess_params["score_mode"] = args.det_db_score_mode + pre_process_list[1] = { + 'NormalizeImage': { + 'std': [1.0, 1.0, 1.0], + 'mean': + [0.48109378172549, 0.45752457890196, 0.40787054090196], + 'scale': '1./255.', + 'order': 'hwc' + } + } + elif self.det_algorithm == "EAST": + postprocess_params['name'] = 'EASTPostProcess' + postprocess_params["score_thresh"] = args.det_east_score_thresh + postprocess_params["cover_thresh"] = args.det_east_cover_thresh + postprocess_params["nms_thresh"] = args.det_east_nms_thresh + elif self.det_algorithm == "SAST": + pre_process_list[0] = { + 'DetResizeForTest': { + 'resize_long': args.det_limit_side_len + } + } + postprocess_params['name'] = 'SASTPostProcess' + postprocess_params["score_thresh"] = args.det_sast_score_thresh + postprocess_params["nms_thresh"] = args.det_sast_nms_thresh + self.det_sast_polygon = args.det_sast_polygon + if self.det_sast_polygon: + postprocess_params["sample_pts_num"] = 6 + postprocess_params["expand_scale"] = 1.2 + postprocess_params["shrink_ratio_of_width"] = 0.2 + else: + postprocess_params["sample_pts_num"] = 2 + postprocess_params["expand_scale"] = 1.0 + postprocess_params["shrink_ratio_of_width"] = 0.3 + elif self.det_algorithm == "PSE": + postprocess_params['name'] = 'PSEPostProcess' + postprocess_params["thresh"] = args.det_pse_thresh + postprocess_params["box_thresh"] = args.det_pse_box_thresh + postprocess_params["min_area"] = args.det_pse_min_area + postprocess_params["box_type"] = args.det_pse_box_type + postprocess_params["scale"] = args.det_pse_scale + self.det_pse_box_type = args.det_pse_box_type + elif self.det_algorithm == "FCE": + pre_process_list[0] = { + 'DetResizeForTest': { + 'rescale_img': [1080, 736] + } + } + postprocess_params['name'] = 'FCEPostProcess' + postprocess_params["scales"] = args.scales + postprocess_params["alpha"] = args.alpha + postprocess_params["beta"] = args.beta + postprocess_params["fourier_degree"] = args.fourier_degree + postprocess_params["box_type"] = args.det_fce_box_type + else: + logger.info("unknown det_algorithm:{}".format(self.det_algorithm)) + sys.exit(0) + + self.preprocess_op = create_operators(pre_process_list) + self.postprocess_op = build_post_process(postprocess_params) + self.predictor, self.input_tensor, self.output_tensors, self.config = utility.create_predictor( + args, 'det', logger) + + if self.use_onnx: + img_h, img_w = self.input_tensor.shape[2:] + if img_h is not None and img_w is not None and img_h > 0 and img_w > 0: + pre_process_list[0] = { + 'DetResizeForTest': { + 'image_shape': [img_h, img_w] + } + } + self.preprocess_op = create_operators(pre_process_list) + + if args.benchmark: + import auto_log + pid = os.getpid() + gpu_id = utility.get_infer_gpuid() + self.autolog = auto_log.AutoLogger( + model_name="det", + model_precision=args.precision, + batch_size=1, + data_shape="dynamic", + save_path=None, + inference_config=self.config, + pids=pid, + process_name=None, + gpu_ids=gpu_id if args.use_gpu else None, + time_keys=[ + 'preprocess_time', 'inference_time', 'postprocess_time' + ], + warmup=2, + logger=logger) + + def order_points_clockwise(self, pts): + rect = np.zeros((4, 2), dtype="float32") + s = pts.sum(axis=1) + rect[0] = pts[np.argmin(s)] + rect[2] = pts[np.argmax(s)] + tmp = np.delete(pts, (np.argmin(s), np.argmax(s)), axis=0) + diff = np.diff(np.array(tmp), axis=1) + rect[1] = tmp[np.argmin(diff)] + rect[3] = tmp[np.argmax(diff)] + return rect + + def clip_det_res(self, points, img_height, img_width): + for pno in range(points.shape[0]): + points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1)) + points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1)) + return points + + def filter_tag_det_res(self, dt_boxes, image_shape): + img_height, img_width = image_shape[0:2] + dt_boxes_new = [] + for box in dt_boxes: + box = self.order_points_clockwise(box) + box = self.clip_det_res(box, img_height, img_width) + rect_width = int(np.linalg.norm(box[0] - box[1])) + rect_height = int(np.linalg.norm(box[0] - box[3])) + if rect_width <= 3 or rect_height <= 3: + continue + dt_boxes_new.append(box) + dt_boxes = np.array(dt_boxes_new) + return dt_boxes + + def filter_tag_det_res_only_clip(self, dt_boxes, image_shape): + img_height, img_width = image_shape[0:2] + dt_boxes_new = [] + for box in dt_boxes: + box = self.clip_det_res(box, img_height, img_width) + dt_boxes_new.append(box) + dt_boxes = np.array(dt_boxes_new) + return dt_boxes + + def __call__(self, img): + ori_im = img.copy() + data = {'image': img} + + st = time.time() + + if self.args.benchmark: + self.autolog.times.start() + + data = transform(data, self.preprocess_op) + img, shape_list = data + if img is None: + return None, 0 + img = np.expand_dims(img, axis=0) + shape_list = np.expand_dims(shape_list, axis=0) + img = img.copy() + + if self.args.benchmark: + self.autolog.times.stamp() + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = img + outputs = self.predictor.run(self.output_tensors, input_dict) + else: + self.input_tensor.copy_from_cpu(img) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if self.args.benchmark: + self.autolog.times.stamp() + + preds = {} + if self.det_algorithm == "EAST": + preds['f_geo'] = outputs[0] + preds['f_score'] = outputs[1] + elif self.det_algorithm == 'SAST': + preds['f_border'] = outputs[0] + preds['f_score'] = outputs[1] + preds['f_tco'] = outputs[2] + preds['f_tvo'] = outputs[3] + elif self.det_algorithm in ['DB', 'PSE', 'DB++']: + preds['maps'] = outputs[0] + elif self.det_algorithm == 'FCE': + for i, output in enumerate(outputs): + preds['level_{}'.format(i)] = output + else: + raise NotImplementedError + + #self.predictor.try_shrink_memory() + post_result = self.postprocess_op(preds, shape_list) + dt_boxes = post_result[0]['points'] + if (self.det_algorithm == "SAST" and self.det_sast_polygon) or ( + self.det_algorithm in ["PSE", "FCE"] and + self.postprocess_op.box_type == 'poly'): + dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape) + else: + dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape) + + if self.args.benchmark: + self.autolog.times.end(stamp=True) + et = time.time() + return dt_boxes, et - st + + +if __name__ == "__main__": + args = utility.parse_args() + image_file_list = get_image_file_list(args.image_dir) + text_detector = TextDetector(args) + count = 0 + total_time = 0 + draw_img_save = "./inference_results" + + if args.warmup: + img = np.random.uniform(0, 255, [640, 640, 3]).astype(np.uint8) + for i in range(2): + res = text_detector(img) + + if not os.path.exists(draw_img_save): + os.makedirs(draw_img_save) + save_results = [] + for image_file in image_file_list: + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + st = time.time() + dt_boxes, _ = text_detector(img) + elapse = time.time() - st + if count > 0: + total_time += elapse + count += 1 + save_pred = os.path.basename(image_file) + "\t" + str( + json.dumps([x.tolist() for x in dt_boxes])) + "\n" + save_results.append(save_pred) + logger.info(save_pred) + logger.info("The predict time of {}: {}".format(image_file, elapse)) + src_im = utility.draw_text_det_res(dt_boxes, image_file) + img_name_pure = os.path.split(image_file)[-1] + img_path = os.path.join(draw_img_save, + "det_res_{}".format(img_name_pure)) + cv2.imwrite(img_path, src_im) + logger.info("The visualized image saved in {}".format(img_path)) + + with open(os.path.join(draw_img_save, "det_results.txt"), 'w') as f: + f.writelines(save_results) + f.close() + if args.benchmark: + text_detector.autolog.report() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_e2e.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_e2e.py new file mode 100755 index 0000000000000000000000000000000000000000..de315d701c7172ded4d30e48e79abee367f42239 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_e2e.py @@ -0,0 +1,169 @@ +# 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. +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import numpy as np +import time +import sys + +import tools.infer.utility as utility +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, check_and_read +from ppocr.data import create_operators, transform +from ppocr.postprocess import build_post_process + +logger = get_logger() + + +class TextE2E(object): + def __init__(self, args): + self.args = args + self.e2e_algorithm = args.e2e_algorithm + self.use_onnx = args.use_onnx + pre_process_list = [{ + 'E2EResizeForTest': {} + }, { + 'NormalizeImage': { + 'std': [0.229, 0.224, 0.225], + 'mean': [0.485, 0.456, 0.406], + 'scale': '1./255.', + 'order': 'hwc' + } + }, { + 'ToCHWImage': None + }, { + 'KeepKeys': { + 'keep_keys': ['image', 'shape'] + } + }] + postprocess_params = {} + if self.e2e_algorithm == "PGNet": + pre_process_list[0] = { + 'E2EResizeForTest': { + 'max_side_len': args.e2e_limit_side_len, + 'valid_set': 'totaltext' + } + } + postprocess_params['name'] = 'PGPostProcess' + postprocess_params["score_thresh"] = args.e2e_pgnet_score_thresh + postprocess_params["character_dict_path"] = args.e2e_char_dict_path + postprocess_params["valid_set"] = args.e2e_pgnet_valid_set + postprocess_params["mode"] = args.e2e_pgnet_mode + else: + logger.info("unknown e2e_algorithm:{}".format(self.e2e_algorithm)) + sys.exit(0) + + self.preprocess_op = create_operators(pre_process_list) + self.postprocess_op = build_post_process(postprocess_params) + self.predictor, self.input_tensor, self.output_tensors, _ = utility.create_predictor( + args, 'e2e', logger) # paddle.jit.load(args.det_model_dir) + # self.predictor.eval() + + def clip_det_res(self, points, img_height, img_width): + for pno in range(points.shape[0]): + points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1)) + points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1)) + return points + + def filter_tag_det_res_only_clip(self, dt_boxes, image_shape): + img_height, img_width = image_shape[0:2] + dt_boxes_new = [] + for box in dt_boxes: + box = self.clip_det_res(box, img_height, img_width) + dt_boxes_new.append(box) + dt_boxes = np.array(dt_boxes_new) + return dt_boxes + + def __call__(self, img): + + ori_im = img.copy() + data = {'image': img} + data = transform(data, self.preprocess_op) + img, shape_list = data + if img is None: + return None, 0 + img = np.expand_dims(img, axis=0) + shape_list = np.expand_dims(shape_list, axis=0) + img = img.copy() + starttime = time.time() + + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = img + outputs = self.predictor.run(self.output_tensors, input_dict) + preds = {} + preds['f_border'] = outputs[0] + preds['f_char'] = outputs[1] + preds['f_direction'] = outputs[2] + preds['f_score'] = outputs[3] + else: + self.input_tensor.copy_from_cpu(img) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + + preds = {} + if self.e2e_algorithm == 'PGNet': + preds['f_border'] = outputs[0] + preds['f_char'] = outputs[1] + preds['f_direction'] = outputs[2] + preds['f_score'] = outputs[3] + else: + raise NotImplementedError + post_result = self.postprocess_op(preds, shape_list) + points, strs = post_result['points'], post_result['texts'] + dt_boxes = self.filter_tag_det_res_only_clip(points, ori_im.shape) + elapse = time.time() - starttime + return dt_boxes, strs, elapse + + +if __name__ == "__main__": + args = utility.parse_args() + image_file_list = get_image_file_list(args.image_dir) + text_detector = TextE2E(args) + count = 0 + total_time = 0 + draw_img_save = "./inference_results" + if not os.path.exists(draw_img_save): + os.makedirs(draw_img_save) + for image_file in image_file_list: + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + points, strs, elapse = text_detector(img) + if count > 0: + total_time += elapse + count += 1 + logger.info("Predict time of {}: {}".format(image_file, elapse)) + src_im = utility.draw_e2e_res(points, strs, image_file) + img_name_pure = os.path.split(image_file)[-1] + img_path = os.path.join(draw_img_save, + "e2e_res_{}".format(img_name_pure)) + cv2.imwrite(img_path, src_im) + logger.info("The visualized image saved in {}".format(img_path)) + if count > 1: + logger.info("Avg Time: {}".format(total_time / (count - 1))) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_rec.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_rec.py new file mode 100755 index 0000000000000000000000000000000000000000..5a7564e122c7173658c4cc2a57caef13276a304f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_rec.py @@ -0,0 +1,592 @@ +# 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. +import os +import sys +from PIL import Image +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import numpy as np +import math +import time +import traceback +import paddle + +import tools.infer.utility as utility +from ppocr.postprocess import build_post_process +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, check_and_read + +logger = get_logger() + + +class TextRecognizer(object): + def __init__(self, args): + self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")] + self.rec_batch_num = args.rec_batch_num + self.rec_algorithm = args.rec_algorithm + postprocess_params = { + 'name': 'CTCLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + if self.rec_algorithm == "SRN": + postprocess_params = { + 'name': 'SRNLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == "RARE": + postprocess_params = { + 'name': 'AttnLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == 'NRTR': + postprocess_params = { + 'name': 'NRTRLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == "SAR": + postprocess_params = { + 'name': 'SARLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == "VisionLAN": + postprocess_params = { + 'name': 'VLLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == 'ViTSTR': + postprocess_params = { + 'name': 'ViTSTRLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == 'ABINet': + postprocess_params = { + 'name': 'ABINetLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == "SPIN": + postprocess_params = { + 'name': 'SPINLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + elif self.rec_algorithm == "RobustScanner": + postprocess_params = { + 'name': 'SARLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char, + "rm_symbol": True + } + elif self.rec_algorithm == "SEED": + postprocess_params = { + 'name': 'SEEDLabelDecode', + "character_dict_path": args.rec_char_dict_path, + "use_space_char": args.use_space_char + } + self.postprocess_op = build_post_process(postprocess_params) + self.predictor, self.input_tensor, self.output_tensors, self.config = \ + utility.create_predictor(args, 'rec', logger) + self.benchmark = args.benchmark + self.use_onnx = args.use_onnx + if args.benchmark: + import auto_log + pid = os.getpid() + gpu_id = utility.get_infer_gpuid() + self.autolog = auto_log.AutoLogger( + model_name="rec", + model_precision=args.precision, + batch_size=args.rec_batch_num, + data_shape="dynamic", + save_path=None, #args.save_log_path, + inference_config=self.config, + pids=pid, + process_name=None, + gpu_ids=gpu_id if args.use_gpu else None, + time_keys=[ + 'preprocess_time', 'inference_time', 'postprocess_time' + ], + warmup=0, + logger=logger) + + def resize_norm_img(self, img, max_wh_ratio): + imgC, imgH, imgW = self.rec_image_shape + if self.rec_algorithm == 'NRTR' or self.rec_algorithm == 'ViTSTR': + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + # return padding_im + image_pil = Image.fromarray(np.uint8(img)) + if self.rec_algorithm == 'ViTSTR': + img = image_pil.resize([imgW, imgH], Image.BICUBIC) + else: + img = image_pil.resize([imgW, imgH], Image.ANTIALIAS) + img = np.array(img) + norm_img = np.expand_dims(img, -1) + norm_img = norm_img.transpose((2, 0, 1)) + if self.rec_algorithm == 'ViTSTR': + norm_img = norm_img.astype(np.float32) / 255. + else: + norm_img = norm_img.astype(np.float32) / 128. - 1. + return norm_img + + assert imgC == img.shape[2] + imgW = int((imgH * max_wh_ratio)) + if self.use_onnx: + w = self.input_tensor.shape[3:][0] + if w is not None and w > 0: + imgW = w + + h, w = img.shape[:2] + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + if self.rec_algorithm == 'RARE': + if resized_w > self.rec_image_shape[2]: + resized_w = self.rec_image_shape[2] + imgW = self.rec_image_shape[2] + + resized_image = cv2.resize(img, (resized_w, imgH)) + resized_image = resized_image.astype('float32') + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32) + padding_im[:, :, 0:resized_w] = resized_image + return padding_im + + def resize_norm_img_vl(self, img, image_shape): + + imgC, imgH, imgW = image_shape + img = img[:, :, ::-1] # bgr2rgb + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_image = resized_image.astype('float32') + resized_image = resized_image.transpose((2, 0, 1)) / 255 + return resized_image + + def resize_norm_img_srn(self, img, image_shape): + imgC, imgH, imgW = image_shape + + img_black = np.zeros((imgH, imgW)) + im_hei = img.shape[0] + im_wid = img.shape[1] + + if im_wid <= im_hei * 1: + img_new = cv2.resize(img, (imgH * 1, imgH)) + elif im_wid <= im_hei * 2: + img_new = cv2.resize(img, (imgH * 2, imgH)) + elif im_wid <= im_hei * 3: + img_new = cv2.resize(img, (imgH * 3, imgH)) + else: + img_new = cv2.resize(img, (imgW, imgH)) + + img_np = np.asarray(img_new) + img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY) + img_black[:, 0:img_np.shape[1]] = img_np + img_black = img_black[:, :, np.newaxis] + + row, col, c = img_black.shape + c = 1 + + return np.reshape(img_black, (c, row, col)).astype(np.float32) + + def srn_other_inputs(self, image_shape, num_heads, max_text_length): + + imgC, imgH, imgW = image_shape + feature_dim = int((imgH / 8) * (imgW / 8)) + + encoder_word_pos = np.array(range(0, feature_dim)).reshape( + (feature_dim, 1)).astype('int64') + gsrm_word_pos = np.array(range(0, max_text_length)).reshape( + (max_text_length, 1)).astype('int64') + + gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length)) + gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape( + [-1, 1, max_text_length, max_text_length]) + gsrm_slf_attn_bias1 = np.tile( + gsrm_slf_attn_bias1, + [1, num_heads, 1, 1]).astype('float32') * [-1e9] + + gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape( + [-1, 1, max_text_length, max_text_length]) + gsrm_slf_attn_bias2 = np.tile( + gsrm_slf_attn_bias2, + [1, num_heads, 1, 1]).astype('float32') * [-1e9] + + encoder_word_pos = encoder_word_pos[np.newaxis, :] + gsrm_word_pos = gsrm_word_pos[np.newaxis, :] + + return [ + encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, + gsrm_slf_attn_bias2 + ] + + def process_image_srn(self, img, image_shape, num_heads, max_text_length): + norm_img = self.resize_norm_img_srn(img, image_shape) + norm_img = norm_img[np.newaxis, :] + + [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \ + self.srn_other_inputs(image_shape, num_heads, max_text_length) + + gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32) + gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32) + encoder_word_pos = encoder_word_pos.astype(np.int64) + gsrm_word_pos = gsrm_word_pos.astype(np.int64) + + return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, + gsrm_slf_attn_bias2) + + def resize_norm_img_sar(self, img, image_shape, + width_downsample_ratio=0.25): + imgC, imgH, imgW_min, imgW_max = image_shape + h = img.shape[0] + w = img.shape[1] + valid_ratio = 1.0 + # make sure new_width is an integral multiple of width_divisor. + width_divisor = int(1 / width_downsample_ratio) + # resize + ratio = w / float(h) + resize_w = math.ceil(imgH * ratio) + if resize_w % width_divisor != 0: + resize_w = round(resize_w / width_divisor) * width_divisor + if imgW_min is not None: + resize_w = max(imgW_min, resize_w) + if imgW_max is not None: + valid_ratio = min(1.0, 1.0 * resize_w / imgW_max) + resize_w = min(imgW_max, resize_w) + resized_image = cv2.resize(img, (resize_w, imgH)) + resized_image = resized_image.astype('float32') + # norm + if image_shape[0] == 1: + resized_image = resized_image / 255 + resized_image = resized_image[np.newaxis, :] + else: + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + resize_shape = resized_image.shape + padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32) + padding_im[:, :, 0:resize_w] = resized_image + pad_shape = padding_im.shape + + return padding_im, resize_shape, pad_shape, valid_ratio + + def resize_norm_img_spin(self, img): + img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + # return padding_im + img = cv2.resize(img, tuple([100, 32]), cv2.INTER_CUBIC) + img = np.array(img, np.float32) + img = np.expand_dims(img, -1) + img = img.transpose((2, 0, 1)) + mean = [127.5] + std = [127.5] + mean = np.array(mean, dtype=np.float32) + std = np.array(std, dtype=np.float32) + mean = np.float32(mean.reshape(1, -1)) + stdinv = 1 / np.float32(std.reshape(1, -1)) + img -= mean + img *= stdinv + return img + + def resize_norm_img_svtr(self, img, image_shape): + + imgC, imgH, imgW = image_shape + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_image = resized_image.astype('float32') + resized_image = resized_image.transpose((2, 0, 1)) / 255 + resized_image -= 0.5 + resized_image /= 0.5 + return resized_image + + def resize_norm_img_abinet(self, img, image_shape): + + imgC, imgH, imgW = image_shape + + resized_image = cv2.resize( + img, (imgW, imgH), interpolation=cv2.INTER_LINEAR) + resized_image = resized_image.astype('float32') + resized_image = resized_image / 255. + + mean = np.array([0.485, 0.456, 0.406]) + std = np.array([0.229, 0.224, 0.225]) + resized_image = ( + resized_image - mean[None, None, ...]) / std[None, None, ...] + resized_image = resized_image.transpose((2, 0, 1)) + resized_image = resized_image.astype('float32') + + return resized_image + + def __call__(self, img_list): + img_num = len(img_list) + # Calculate the aspect ratio of all text bars + width_list = [] + for img in img_list: + width_list.append(img.shape[1] / float(img.shape[0])) + # Sorting can speed up the recognition process + indices = np.argsort(np.array(width_list)) + rec_res = [['', 0.0]] * img_num + batch_num = self.rec_batch_num + st = time.time() + if self.benchmark: + self.autolog.times.start() + for beg_img_no in range(0, img_num, batch_num): + end_img_no = min(img_num, beg_img_no + batch_num) + norm_img_batch = [] + if self.rec_algorithm == "SRN": + encoder_word_pos_list = [] + gsrm_word_pos_list = [] + gsrm_slf_attn_bias1_list = [] + gsrm_slf_attn_bias2_list = [] + if self.rec_algorithm == "SAR": + valid_ratios = [] + imgC, imgH, imgW = self.rec_image_shape[:3] + max_wh_ratio = imgW / imgH + # max_wh_ratio = 0 + for ino in range(beg_img_no, end_img_no): + h, w = img_list[indices[ino]].shape[0:2] + wh_ratio = w * 1.0 / h + max_wh_ratio = max(max_wh_ratio, wh_ratio) + for ino in range(beg_img_no, end_img_no): + if self.rec_algorithm == "SAR": + norm_img, _, _, valid_ratio = self.resize_norm_img_sar( + img_list[indices[ino]], self.rec_image_shape) + norm_img = norm_img[np.newaxis, :] + valid_ratio = np.expand_dims(valid_ratio, axis=0) + valid_ratios.append(valid_ratio) + norm_img_batch.append(norm_img) + elif self.rec_algorithm == "SRN": + norm_img = self.process_image_srn( + img_list[indices[ino]], self.rec_image_shape, 8, 25) + encoder_word_pos_list.append(norm_img[1]) + gsrm_word_pos_list.append(norm_img[2]) + gsrm_slf_attn_bias1_list.append(norm_img[3]) + gsrm_slf_attn_bias2_list.append(norm_img[4]) + norm_img_batch.append(norm_img[0]) + elif self.rec_algorithm == "SVTR": + norm_img = self.resize_norm_img_svtr(img_list[indices[ino]], + self.rec_image_shape) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + elif self.rec_algorithm == "VisionLAN": + norm_img = self.resize_norm_img_vl(img_list[indices[ino]], + self.rec_image_shape) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + elif self.rec_algorithm == 'SPIN': + norm_img = self.resize_norm_img_spin(img_list[indices[ino]]) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + elif self.rec_algorithm == "ABINet": + norm_img = self.resize_norm_img_abinet( + img_list[indices[ino]], self.rec_image_shape) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + elif self.rec_algorithm == "SEED": + norm_img = self.resize_norm_img_svtr(img_list[indices[ino]], + self.rec_image_shape) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + elif self.rec_algorithm == "RobustScanner": + norm_img, _, _, valid_ratio = self.resize_norm_img_sar( + img_list[indices[ino]], + self.rec_image_shape, + width_downsample_ratio=0.25) + norm_img = norm_img[np.newaxis, :] + valid_ratio = np.expand_dims(valid_ratio, axis=0) + valid_ratios = [] + valid_ratios.append(valid_ratio) + norm_img_batch.append(norm_img) + word_positions_list = [] + word_positions = np.array(range(0, 40)).astype('int64') + word_positions = np.expand_dims(word_positions, axis=0) + word_positions_list.append(word_positions) + else: + norm_img = self.resize_norm_img(img_list[indices[ino]], + max_wh_ratio) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + norm_img_batch = np.concatenate(norm_img_batch) + norm_img_batch = norm_img_batch.copy() + if self.benchmark: + self.autolog.times.stamp() + + if self.rec_algorithm == "SRN": + encoder_word_pos_list = np.concatenate(encoder_word_pos_list) + gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list) + gsrm_slf_attn_bias1_list = np.concatenate( + gsrm_slf_attn_bias1_list) + gsrm_slf_attn_bias2_list = np.concatenate( + gsrm_slf_attn_bias2_list) + + inputs = [ + norm_img_batch, + encoder_word_pos_list, + gsrm_word_pos_list, + gsrm_slf_attn_bias1_list, + gsrm_slf_attn_bias2_list, + ] + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = norm_img_batch + outputs = self.predictor.run(self.output_tensors, + input_dict) + preds = {"predict": outputs[2]} + else: + input_names = self.predictor.get_input_names() + for i in range(len(input_names)): + input_tensor = self.predictor.get_input_handle( + input_names[i]) + input_tensor.copy_from_cpu(inputs[i]) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if self.benchmark: + self.autolog.times.stamp() + preds = {"predict": outputs[2]} + elif self.rec_algorithm == "SAR": + valid_ratios = np.concatenate(valid_ratios) + inputs = [ + norm_img_batch, + np.array( + [valid_ratios], dtype=np.float32), + ] + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = norm_img_batch + outputs = self.predictor.run(self.output_tensors, + input_dict) + preds = outputs[0] + else: + input_names = self.predictor.get_input_names() + for i in range(len(input_names)): + input_tensor = self.predictor.get_input_handle( + input_names[i]) + input_tensor.copy_from_cpu(inputs[i]) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if self.benchmark: + self.autolog.times.stamp() + preds = outputs[0] + elif self.rec_algorithm == "RobustScanner": + valid_ratios = np.concatenate(valid_ratios) + word_positions_list = np.concatenate(word_positions_list) + inputs = [norm_img_batch, valid_ratios, word_positions_list] + + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = norm_img_batch + outputs = self.predictor.run(self.output_tensors, + input_dict) + preds = outputs[0] + else: + input_names = self.predictor.get_input_names() + for i in range(len(input_names)): + input_tensor = self.predictor.get_input_handle( + input_names[i]) + input_tensor.copy_from_cpu(inputs[i]) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if self.benchmark: + self.autolog.times.stamp() + preds = outputs[0] + else: + if self.use_onnx: + input_dict = {} + input_dict[self.input_tensor.name] = norm_img_batch + outputs = self.predictor.run(self.output_tensors, + input_dict) + preds = outputs[0] + else: + self.input_tensor.copy_from_cpu(norm_img_batch) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if self.benchmark: + self.autolog.times.stamp() + if len(outputs) != 1: + preds = outputs + else: + preds = outputs[0] + rec_result = self.postprocess_op(preds) + for rno in range(len(rec_result)): + rec_res[indices[beg_img_no + rno]] = rec_result[rno] + if self.benchmark: + self.autolog.times.end(stamp=True) + return rec_res, time.time() - st + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + text_recognizer = TextRecognizer(args) + valid_image_file_list = [] + img_list = [] + + logger.info( + "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', " + "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320" + ) + # warmup 2 times + if args.warmup: + img = np.random.uniform(0, 255, [48, 320, 3]).astype(np.uint8) + for i in range(2): + res = text_recognizer([img] * int(args.rec_batch_num)) + + for image_file in image_file_list: + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + valid_image_file_list.append(image_file) + img_list.append(img) + try: + rec_res, _ = text_recognizer(img_list) + + except Exception as E: + logger.info(traceback.format_exc()) + logger.info(E) + exit() + for ino in range(len(img_list)): + logger.info("Predicts of {}:{}".format(valid_image_file_list[ino], + rec_res[ino])) + if args.benchmark: + text_recognizer.autolog.report() + + +if __name__ == "__main__": + main(utility.parse_args()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_sr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_sr.py new file mode 100755 index 0000000000000000000000000000000000000000..ca99f6819f4b207ecc0f0d1383fe1d26d07fbf50 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_sr.py @@ -0,0 +1,155 @@ +# 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. +import os +import sys +from PIL import Image +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, __dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import numpy as np +import math +import time +import traceback +import paddle + +import tools.infer.utility as utility +from ppocr.postprocess import build_post_process +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, check_and_read + +logger = get_logger() + + +class TextSR(object): + def __init__(self, args): + self.sr_image_shape = [int(v) for v in args.sr_image_shape.split(",")] + self.sr_batch_num = args.sr_batch_num + + self.predictor, self.input_tensor, self.output_tensors, self.config = \ + utility.create_predictor(args, 'sr', logger) + self.benchmark = args.benchmark + if args.benchmark: + import auto_log + pid = os.getpid() + gpu_id = utility.get_infer_gpuid() + self.autolog = auto_log.AutoLogger( + model_name="sr", + model_precision=args.precision, + batch_size=args.sr_batch_num, + data_shape="dynamic", + save_path=None, #args.save_log_path, + inference_config=self.config, + pids=pid, + process_name=None, + gpu_ids=gpu_id if args.use_gpu else None, + time_keys=[ + 'preprocess_time', 'inference_time', 'postprocess_time' + ], + warmup=0, + logger=logger) + + def resize_norm_img(self, img): + imgC, imgH, imgW = self.sr_image_shape + img = img.resize((imgW // 2, imgH // 2), Image.BICUBIC) + img_numpy = np.array(img).astype("float32") + img_numpy = img_numpy.transpose((2, 0, 1)) / 255 + return img_numpy + + def __call__(self, img_list): + img_num = len(img_list) + batch_num = self.sr_batch_num + st = time.time() + st = time.time() + all_result = [] * img_num + if self.benchmark: + self.autolog.times.start() + for beg_img_no in range(0, img_num, batch_num): + end_img_no = min(img_num, beg_img_no + batch_num) + norm_img_batch = [] + imgC, imgH, imgW = self.sr_image_shape + for ino in range(beg_img_no, end_img_no): + norm_img = self.resize_norm_img(img_list[ino]) + norm_img = norm_img[np.newaxis, :] + norm_img_batch.append(norm_img) + + norm_img_batch = np.concatenate(norm_img_batch) + norm_img_batch = norm_img_batch.copy() + if self.benchmark: + self.autolog.times.stamp() + self.input_tensor.copy_from_cpu(norm_img_batch) + self.predictor.run() + outputs = [] + for output_tensor in self.output_tensors: + output = output_tensor.copy_to_cpu() + outputs.append(output) + if len(outputs) != 1: + preds = outputs + else: + preds = outputs[0] + all_result.append(outputs) + if self.benchmark: + self.autolog.times.end(stamp=True) + return all_result, time.time() - st + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + text_recognizer = TextSR(args) + valid_image_file_list = [] + img_list = [] + + # warmup 2 times + if args.warmup: + img = np.random.uniform(0, 255, [16, 64, 3]).astype(np.uint8) + for i in range(2): + res = text_recognizer([img] * int(args.sr_batch_num)) + + for image_file in image_file_list: + img, flag, _ = check_and_read(image_file) + if not flag: + img = Image.open(image_file).convert("RGB") + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + valid_image_file_list.append(image_file) + img_list.append(img) + try: + preds, _ = text_recognizer(img_list) + for beg_no in range(len(preds)): + sr_img = preds[beg_no][1] + lr_img = preds[beg_no][0] + for i in (range(sr_img.shape[0])): + fm_sr = (sr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8) + fm_lr = (lr_img[i] * 255).transpose(1, 2, 0).astype(np.uint8) + img_name_pure = os.path.split(valid_image_file_list[ + beg_no * args.sr_batch_num + i])[-1] + cv2.imwrite("infer_result/sr_{}".format(img_name_pure), + fm_sr[:, :, ::-1]) + logger.info("The visualized image saved in infer_result/sr_{}". + format(img_name_pure)) + + except Exception as E: + logger.info(traceback.format_exc()) + logger.info(E) + exit() + if args.benchmark: + text_recognizer.autolog.report() + + +if __name__ == "__main__": + main(utility.parse_args()) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_system.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_system.py new file mode 100755 index 0000000000000000000000000000000000000000..2290aa18ec2d4f56dfe3a3ac3da0f62eb3694bfe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/predict_system.py @@ -0,0 +1,272 @@ +# 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. +import os +import sys +import subprocess + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import copy +import numpy as np +import json +import time +import logging +from PIL import Image +import tools.infer.utility as utility +import tools.infer.predict_rec as predict_rec +import tools.infer.predict_det as predict_det +import tools.infer.predict_cls as predict_cls +from ppocr.utils.utility import get_image_file_list, check_and_read +from ppocr.utils.logging import get_logger +from tools.infer.utility import draw_ocr_box_txt, get_rotate_crop_image +logger = get_logger() + + +class TextSystem(object): + def __init__(self, args): + if not args.show_log: + logger.setLevel(logging.INFO) + + self.text_detector = predict_det.TextDetector(args) + self.text_recognizer = predict_rec.TextRecognizer(args) + self.use_angle_cls = args.use_angle_cls + self.drop_score = args.drop_score + if self.use_angle_cls: + self.text_classifier = predict_cls.TextClassifier(args) + + self.args = args + self.crop_image_res_index = 0 + + def draw_crop_rec_res(self, output_dir, img_crop_list, rec_res): + os.makedirs(output_dir, exist_ok=True) + bbox_num = len(img_crop_list) + for bno in range(bbox_num): + cv2.imwrite( + os.path.join(output_dir, + f"mg_crop_{bno+self.crop_image_res_index}.jpg"), + img_crop_list[bno]) + logger.debug(f"{bno}, {rec_res[bno]}") + self.crop_image_res_index += bbox_num + + def __call__(self, img, cls=True): + time_dict = {'det': 0, 'rec': 0, 'csl': 0, 'all': 0} + start = time.time() + ori_im = img.copy() + dt_boxes, elapse = self.text_detector(img) + time_dict['det'] = elapse + logger.debug("dt_boxes num : {}, elapse : {}".format( + len(dt_boxes), elapse)) + if dt_boxes is None: + return None, None + img_crop_list = [] + + dt_boxes = sorted_boxes(dt_boxes) + + for bno in range(len(dt_boxes)): + tmp_box = copy.deepcopy(dt_boxes[bno]) + img_crop = get_rotate_crop_image(ori_im, tmp_box) + img_crop_list.append(img_crop) + if self.use_angle_cls and cls: + img_crop_list, angle_list, elapse = self.text_classifier( + img_crop_list) + time_dict['cls'] = elapse + logger.debug("cls num : {}, elapse : {}".format( + len(img_crop_list), elapse)) + + rec_res, elapse = self.text_recognizer(img_crop_list) + time_dict['rec'] = elapse + logger.debug("rec_res num : {}, elapse : {}".format( + len(rec_res), elapse)) + if self.args.save_crop_res: + self.draw_crop_rec_res(self.args.crop_res_save_dir, img_crop_list, + rec_res) + filter_boxes, filter_rec_res = [], [] + for box, rec_result in zip(dt_boxes, rec_res): + text, score = rec_result + if score >= self.drop_score: + filter_boxes.append(box) + filter_rec_res.append(rec_result) + end = time.time() + time_dict['all'] = end - start + return filter_boxes, filter_rec_res, time_dict + + +def sorted_boxes(dt_boxes): + """ + Sort text boxes in order from top to bottom, left to right + args: + dt_boxes(array):detected text boxes with shape [4, 2] + return: + sorted boxes(array) with shape [4, 2] + """ + num_boxes = dt_boxes.shape[0] + sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0])) + _boxes = list(sorted_boxes) + + for i in range(num_boxes - 1): + for j in range(i, 0, -1): + if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \ + (_boxes[j + 1][0][0] < _boxes[j][0][0]): + tmp = _boxes[j] + _boxes[j] = _boxes[j + 1] + _boxes[j + 1] = tmp + else: + break + return _boxes + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + image_file_list = image_file_list[args.process_id::args.total_process_num] + text_sys = TextSystem(args) + is_visualize = True + font_path = args.vis_font_path + drop_score = args.drop_score + draw_img_save_dir = args.draw_img_save_dir + os.makedirs(draw_img_save_dir, exist_ok=True) + save_results = [] + + logger.info( + "In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', " + "if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320" + ) + + # warm up 10 times + if args.warmup: + img = np.random.uniform(0, 255, [640, 640, 3]).astype(np.uint8) + for i in range(10): + res = text_sys(img) + + total_time = 0 + cpu_mem, gpu_mem, gpu_util = 0, 0, 0 + _st = time.time() + count = 0 + for idx, image_file in enumerate(image_file_list): + + img, flag, _ = check_and_read(image_file) + if not flag: + img = cv2.imread(image_file) + if img is None: + logger.debug("error in loading image:{}".format(image_file)) + continue + starttime = time.time() + dt_boxes, rec_res, time_dict = text_sys(img) + elapse = time.time() - starttime + total_time += elapse + + logger.debug( + str(idx) + " Predict time of %s: %.3fs" % (image_file, elapse)) + for text, score in rec_res: + logger.debug("{}, {:.3f}".format(text, score)) + + res = [{ + "transcription": rec_res[idx][0], + "points": np.array(dt_boxes[idx]).astype(np.int32).tolist(), + } for idx in range(len(dt_boxes))] + save_pred = os.path.basename(image_file) + "\t" + json.dumps( + res, ensure_ascii=False) + "\n" + save_results.append(save_pred) + + if is_visualize: + image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + boxes = dt_boxes + txts = [rec_res[i][0] for i in range(len(rec_res))] + scores = [rec_res[i][1] for i in range(len(rec_res))] + + draw_img = draw_ocr_box_txt( + image, + boxes, + txts, + scores, + drop_score=drop_score, + font_path=font_path) + if flag: + image_file = image_file[:-3] + "png" + cv2.imwrite( + os.path.join(draw_img_save_dir, os.path.basename(image_file)), + draw_img[:, :, ::-1]) + logger.debug("The visualized image saved in {}".format( + os.path.join(draw_img_save_dir, os.path.basename(image_file)))) + + logger.info("The predict total time is {}".format(time.time() - _st)) + if args.benchmark: + text_sys.text_detector.autolog.report() + text_sys.text_recognizer.autolog.report() + + with open( + os.path.join(draw_img_save_dir, "system_results.txt"), + 'w', + encoding='utf-8') as f: + f.writelines(save_results) + + +if __name__ == "__main__": + + """ + python3 tools/infer/predict_system.py \ + --image_dir="train_data/det/test/25.jpg" \ + --det_algorithm="DB" \ + --det_model_dir="output/det_model" \ + --det_limit_side_len=960 \ + --det_db_unclip_ratio=3.5 \ + --rec_model_dir="output/rec_model/Student" \ + --rec_char_dict_path="train_data/keys.txt" \ + --use_gpu False \ + --enable_mkldnn=True + + """ + import sys + sys.argv.append( '--image_dir' ) + # sys.argv.append( 'train_data/det/test/12.jpg' ) + sys.argv.append( 'train_data/det/train/3.jpg' ) + sys.argv.append( '--det_algorithm' ) + sys.argv.append( 'DB' ) + sys.argv.append( '--det_model_dir' ) + sys.argv.append( 'output/det_model' ) + sys.argv.append( '--det_limit_side_len' ) + sys.argv.append( '960' ) + sys.argv.append( '--det_db_unclip_ratio' ) + sys.argv.append( '3.5' ) + sys.argv.append( '--rec_model_dir' ) + sys.argv.append( 'output/rec_model/Student' ) + sys.argv.append( '--rec_char_dict_path' ) + sys.argv.append( 'train_data/keys.txt' ) + sys.argv.append( '--use_gpu' ) + sys.argv.append( 'False' ) + sys.argv.append( '--enable_mkldnn' ) + sys.argv.append( 'True' ) + sys.argv.append( '--vis_font_path' ) + sys.argv.append( 'fonts/simfang.ttf' ) + + + args = utility.parse_args() + if args.use_mp: + p_list = [] + total_process_num = args.total_process_num + for process_id in range(total_process_num): + cmd = [sys.executable, "-u"] + sys.argv + [ + "--process_id={}".format(process_id), + "--use_mp={}".format(False) + ] + p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout) + p_list.append(p) + for p in p_list: + p.wait() + else: + main(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/utility.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/utility.py new file mode 100644 index 0000000000000000000000000000000000000000..d810764897347b29c7db2f531851f5aad42ea14b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer/utility.py @@ -0,0 +1,611 @@ +# 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. + +import argparse +import os +import sys +import platform +import cv2 +import numpy as np +import paddle +from PIL import Image, ImageDraw, ImageFont +import math +from paddle import inference +import time +from ppocr.utils.logging import get_logger + + +def str2bool(v): + return v.lower() in ("true", "t", "1") + + +def init_args(): + parser = argparse.ArgumentParser() + # params for prediction engine + parser.add_argument("--use_gpu", type=str2bool, default=True) + parser.add_argument("--use_xpu", type=str2bool, default=False) + parser.add_argument("--ir_optim", type=str2bool, default=True) + parser.add_argument("--use_tensorrt", type=str2bool, default=False) + parser.add_argument("--min_subgraph_size", type=int, default=15) + parser.add_argument("--shape_info_filename", type=str, default=None) + parser.add_argument("--precision", type=str, default="fp32") + parser.add_argument("--gpu_mem", type=int, default=500) + + # params for text detector + parser.add_argument("--image_dir", type=str) + parser.add_argument("--det_algorithm", type=str, default='DB') + parser.add_argument("--det_model_dir", type=str) + parser.add_argument("--det_limit_side_len", type=float, default=960) + parser.add_argument("--det_limit_type", type=str, default='max') + + # DB parmas + parser.add_argument("--det_db_thresh", type=float, default=0.3) + parser.add_argument("--det_db_box_thresh", type=float, default=0.6) + parser.add_argument("--det_db_unclip_ratio", type=float, default=1.5) + parser.add_argument("--max_batch_size", type=int, default=10) + parser.add_argument("--use_dilation", type=str2bool, default=False) + parser.add_argument("--det_db_score_mode", type=str, default="fast") + # EAST parmas + parser.add_argument("--det_east_score_thresh", type=float, default=0.8) + parser.add_argument("--det_east_cover_thresh", type=float, default=0.1) + parser.add_argument("--det_east_nms_thresh", type=float, default=0.2) + + # SAST parmas + parser.add_argument("--det_sast_score_thresh", type=float, default=0.5) + parser.add_argument("--det_sast_nms_thresh", type=float, default=0.2) + parser.add_argument("--det_sast_polygon", type=str2bool, default=False) + + # PSE parmas + parser.add_argument("--det_pse_thresh", type=float, default=0) + parser.add_argument("--det_pse_box_thresh", type=float, default=0.85) + parser.add_argument("--det_pse_min_area", type=float, default=16) + parser.add_argument("--det_pse_box_type", type=str, default='quad') + parser.add_argument("--det_pse_scale", type=int, default=1) + + # FCE parmas + parser.add_argument("--scales", type=list, default=[8, 16, 32]) + parser.add_argument("--alpha", type=float, default=1.0) + parser.add_argument("--beta", type=float, default=1.0) + parser.add_argument("--fourier_degree", type=int, default=5) + parser.add_argument("--det_fce_box_type", type=str, default='poly') + + # params for text recognizer + parser.add_argument("--rec_algorithm", type=str, default='SVTR_LCNet') + parser.add_argument("--rec_model_dir", type=str) + parser.add_argument("--rec_image_shape", type=str, default="3, 48, 320") + parser.add_argument("--rec_batch_num", type=int, default=6) + parser.add_argument("--max_text_length", type=int, default=25) + parser.add_argument( + "--rec_char_dict_path", + type=str, + default="./ppocr/utils/ppocr_keys_v1.txt") + parser.add_argument("--use_space_char", type=str2bool, default=True) + parser.add_argument( + "--vis_font_path", type=str, default="./doc/fonts/simfang.ttf") + parser.add_argument("--drop_score", type=float, default=0.5) + + # params for e2e + parser.add_argument("--e2e_algorithm", type=str, default='PGNet') + parser.add_argument("--e2e_model_dir", type=str) + parser.add_argument("--e2e_limit_side_len", type=float, default=768) + parser.add_argument("--e2e_limit_type", type=str, default='max') + + # PGNet parmas + parser.add_argument("--e2e_pgnet_score_thresh", type=float, default=0.5) + parser.add_argument( + "--e2e_char_dict_path", type=str, default="./ppocr/utils/ic15_dict.txt") + parser.add_argument("--e2e_pgnet_valid_set", type=str, default='totaltext') + parser.add_argument("--e2e_pgnet_mode", type=str, default='fast') + + # params for text classifier + parser.add_argument("--use_angle_cls", type=str2bool, default=False) + parser.add_argument("--cls_model_dir", type=str) + parser.add_argument("--cls_image_shape", type=str, default="3, 48, 192") + parser.add_argument("--label_list", type=list, default=['0', '180']) + parser.add_argument("--cls_batch_num", type=int, default=6) + parser.add_argument("--cls_thresh", type=float, default=0.9) + + parser.add_argument("--enable_mkldnn", type=str2bool, default=False) + parser.add_argument("--cpu_threads", type=int, default=10) + parser.add_argument("--use_pdserving", type=str2bool, default=False) + parser.add_argument("--warmup", type=str2bool, default=False) + + # SR parmas + parser.add_argument("--sr_model_dir", type=str) + parser.add_argument("--sr_image_shape", type=str, default="3, 32, 128") + parser.add_argument("--sr_batch_num", type=int, default=1) + + # + parser.add_argument( + "--draw_img_save_dir", type=str, default="./inference_results") + parser.add_argument("--save_crop_res", type=str2bool, default=False) + parser.add_argument("--crop_res_save_dir", type=str, default="./output") + + # multi-process + parser.add_argument("--use_mp", type=str2bool, default=False) + parser.add_argument("--total_process_num", type=int, default=1) + parser.add_argument("--process_id", type=int, default=0) + + parser.add_argument("--benchmark", type=str2bool, default=False) + parser.add_argument("--save_log_path", type=str, default="./log_output/") + + parser.add_argument("--show_log", type=str2bool, default=True) + parser.add_argument("--use_onnx", type=str2bool, default=False) + return parser + + +def parse_args( args=None ): + parser = init_args() + return parser.parse_args(args) + + +def create_predictor(args, mode, logger): + if mode == "det": + model_dir = args.det_model_dir + elif mode == 'cls': + model_dir = args.cls_model_dir + elif mode == 'rec': + model_dir = args.rec_model_dir + elif mode == 'table': + model_dir = args.table_model_dir + elif mode == 'ser': + model_dir = args.ser_model_dir + elif mode == "sr": + model_dir = args.sr_model_dir + elif mode == 'layout': + model_dir = args.layout_model_dir + else: + model_dir = args.e2e_model_dir + + if model_dir is None: + logger.info("not find {} model file path {}".format(mode, model_dir)) + sys.exit(0) + if args.use_onnx: + import onnxruntime as ort + model_file_path = model_dir + if not os.path.exists(model_file_path): + raise ValueError("not find model file path {}".format( + model_file_path)) + sess = ort.InferenceSession(model_file_path) + return sess, sess.get_inputs()[0], None, None + + else: + file_names = ['model', 'inference'] + for file_name in file_names: + model_file_path = '{}/{}.pdmodel'.format(model_dir, file_name) + params_file_path = '{}/{}.pdiparams'.format(model_dir, file_name) + if os.path.exists(model_file_path) and os.path.exists( + params_file_path): + break + if not os.path.exists(model_file_path): + raise ValueError( + "not find model.pdmodel or inference.pdmodel in {}".format( + model_dir)) + if not os.path.exists(params_file_path): + raise ValueError( + "not find model.pdiparams or inference.pdiparams in {}".format( + model_dir)) + + config = inference.Config(model_file_path, params_file_path) + + if hasattr(args, 'precision'): + if args.precision == "fp16" and args.use_tensorrt: + precision = inference.PrecisionType.Half + elif args.precision == "int8": + precision = inference.PrecisionType.Int8 + else: + precision = inference.PrecisionType.Float32 + else: + precision = inference.PrecisionType.Float32 + + if args.use_gpu: + gpu_id = get_infer_gpuid() + if gpu_id is None: + logger.warning( + "GPU is not found in current device by nvidia-smi. Please check your device or ignore it if run on jetson." + ) + config.enable_use_gpu(args.gpu_mem, 0) + if args.use_tensorrt: + config.enable_tensorrt_engine( + workspace_size=1 << 30, + precision_mode=precision, + max_batch_size=args.max_batch_size, + min_subgraph_size=args. + min_subgraph_size, # skip the minmum trt subgraph + use_calib_mode=False) + + # collect shape + if args.shape_info_filename is not None: + if not os.path.exists(args.shape_info_filename): + config.collect_shape_range_info( + args.shape_info_filename) + logger.info( + f"collect dynamic shape info into : {args.shape_info_filename}" + ) + else: + logger.info( + f"dynamic shape info file( {args.shape_info_filename} ) already exists, not need to generate again." + ) + config.enable_tuned_tensorrt_dynamic_shape( + args.shape_info_filename, True) + else: + logger.info( + f"when using tensorrt, dynamic shape is a suggested option, you can use '--shape_info_filename=shape.txt' for offline dygnamic shape tuning" + ) + + elif args.use_xpu: + config.enable_xpu(10 * 1024 * 1024) + else: + config.disable_gpu() + if args.enable_mkldnn: + # cache 10 different shapes for mkldnn to avoid memory leak + config.set_mkldnn_cache_capacity(10) + config.enable_mkldnn() + if args.precision == "fp16": + config.enable_mkldnn_bfloat16() + if hasattr(args, "cpu_threads"): + config.set_cpu_math_library_num_threads(args.cpu_threads) + else: + # default cpu threads as 10 + config.set_cpu_math_library_num_threads(10) + # enable memory optim + config.enable_memory_optim() + config.disable_glog_info() + config.delete_pass("conv_transpose_eltwiseadd_bn_fuse_pass") + config.delete_pass("matmul_transpose_reshape_fuse_pass") + if mode == 'table': + config.delete_pass("fc_fuse_pass") # not supported for table + config.switch_use_feed_fetch_ops(False) + config.switch_ir_optim(True) + + # create predictor + predictor = inference.create_predictor(config) + input_names = predictor.get_input_names() + if mode in ['ser', 're']: + input_tensor = [] + for name in input_names: + input_tensor.append(predictor.get_input_handle(name)) + else: + for name in input_names: + input_tensor = predictor.get_input_handle(name) + output_tensors = get_output_tensors(args, mode, predictor) + return predictor, input_tensor, output_tensors, config + + +def get_output_tensors(args, mode, predictor): + output_names = predictor.get_output_names() + output_tensors = [] + if mode == "rec" and args.rec_algorithm in ["CRNN", "SVTR_LCNet"]: + output_name = 'softmax_0.tmp_0' + if output_name in output_names: + return [predictor.get_output_handle(output_name)] + else: + for output_name in output_names: + output_tensor = predictor.get_output_handle(output_name) + output_tensors.append(output_tensor) + else: + for output_name in output_names: + output_tensor = predictor.get_output_handle(output_name) + output_tensors.append(output_tensor) + return output_tensors + + +def get_infer_gpuid(): + sysstr = platform.system() + if sysstr == "Windows": + return 0 + + if not paddle.fluid.core.is_compiled_with_rocm(): + cmd = "env | grep CUDA_VISIBLE_DEVICES" + else: + cmd = "env | grep HIP_VISIBLE_DEVICES" + env_cuda = os.popen(cmd).readlines() + if len(env_cuda) == 0: + return 0 + else: + gpu_id = env_cuda[0].strip().split("=")[1] + return int(gpu_id[0]) + + +def draw_e2e_res(dt_boxes, strs, img_path): + src_im = cv2.imread(img_path) + for box, str in zip(dt_boxes, strs): + box = box.astype(np.int32).reshape((-1, 1, 2)) + cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2) + cv2.putText( + src_im, + str, + org=(int(box[0, 0, 0]), int(box[0, 0, 1])), + fontFace=cv2.FONT_HERSHEY_COMPLEX, + fontScale=0.7, + color=(0, 255, 0), + thickness=1) + return src_im + + +def draw_text_det_res(dt_boxes, img_path): + src_im = cv2.imread(img_path) + for box in dt_boxes: + box = np.array(box).astype(np.int32).reshape(-1, 2) + cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2) + return src_im + + +def resize_img(img, input_size=600): + """ + resize img and limit the longest side of the image to input_size + """ + img = np.array(img) + im_shape = img.shape + im_size_max = np.max(im_shape[0:2]) + im_scale = float(input_size) / float(im_size_max) + img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale) + return img + + +def draw_ocr(image, + boxes, + txts=None, + scores=None, + drop_score=0.5, + font_path="./doc/fonts/simfang.ttf"): + """ + Visualize the results of OCR detection and recognition + args: + image(Image|array): RGB image + boxes(list): boxes with shape(N, 4, 2) + txts(list): the texts + scores(list): txxs corresponding scores + drop_score(float): only scores greater than drop_threshold will be visualized + font_path: the path of font which is used to draw text + return(array): + the visualized img + """ + if scores is None: + scores = [1] * len(boxes) + box_num = len(boxes) + for i in range(box_num): + if scores is not None and (scores[i] < drop_score or + math.isnan(scores[i])): + continue + box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64) + image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2) + if txts is not None: + img = np.array(resize_img(image, input_size=600)) + txt_img = text_visual( + txts, + scores, + img_h=img.shape[0], + img_w=600, + threshold=drop_score, + font_path=font_path) + img = np.concatenate([np.array(img), np.array(txt_img)], axis=1) + return img + return image + + +def draw_ocr_box_txt(image, + boxes, + txts, + scores=None, + drop_score=0.5, + font_path="./doc/simfang.ttf"): + h, w = image.height, image.width + img_left = image.copy() + img_right = Image.new('RGB', (w, h), (255, 255, 255)) + + import random + + random.seed(0) + draw_left = ImageDraw.Draw(img_left) + draw_right = ImageDraw.Draw(img_right) + for idx, (box, txt) in enumerate(zip(boxes, txts)): + if scores is not None and scores[idx] < drop_score: + continue + color = (random.randint(0, 255), random.randint(0, 255), + random.randint(0, 255)) + draw_left.polygon(box, fill=color) + draw_right.polygon( + [ + box[0][0], box[0][1], box[1][0], box[1][1], box[2][0], + box[2][1], box[3][0], box[3][1] + ], + outline=color) + box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][ + 1])**2) + box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][ + 1])**2) + if box_height > 2 * box_width: + font_size = max(int(box_width * 0.9), 10) + font = ImageFont.truetype(font_path, font_size, encoding="utf-8") + cur_y = box[0][1] + for c in txt: + char_size = font.getsize(c) + draw_right.text( + (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font) + cur_y += char_size[1] + else: + font_size = max(int(box_height * 0.8), 10) + font = ImageFont.truetype(font_path, font_size, encoding="utf-8") + draw_right.text( + [box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font) + img_left = Image.blend(image, img_left, 0.5) + img_show = Image.new('RGB', (w * 2, h), (255, 255, 255)) + img_show.paste(img_left, (0, 0, w, h)) + img_show.paste(img_right, (w, 0, w * 2, h)) + return np.array(img_show) + + +def str_count(s): + """ + Count the number of Chinese characters, + a single English character and a single number + equal to half the length of Chinese characters. + args: + s(string): the input of string + return(int): + the number of Chinese characters + """ + import string + count_zh = count_pu = 0 + s_len = len(s) + en_dg_count = 0 + for c in s: + if c in string.ascii_letters or c.isdigit() or c.isspace(): + en_dg_count += 1 + elif c.isalpha(): + count_zh += 1 + else: + count_pu += 1 + return s_len - math.ceil(en_dg_count / 2) + + +def text_visual(texts, + scores, + img_h=400, + img_w=600, + threshold=0., + font_path="./doc/simfang.ttf"): + """ + create new blank img and draw txt on it + args: + texts(list): the text will be draw + scores(list|None): corresponding score of each txt + img_h(int): the height of blank img + img_w(int): the width of blank img + font_path: the path of font which is used to draw text + return(array): + """ + if scores is not None: + assert len(texts) == len( + scores), "The number of txts and corresponding scores must match" + + def create_blank_img(): + blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255 + blank_img[:, img_w - 1:] = 0 + blank_img = Image.fromarray(blank_img).convert("RGB") + draw_txt = ImageDraw.Draw(blank_img) + return blank_img, draw_txt + + blank_img, draw_txt = create_blank_img() + + font_size = 20 + txt_color = (0, 0, 0) + font = ImageFont.truetype(font_path, font_size, encoding="utf-8") + + gap = font_size + 5 + txt_img_list = [] + count, index = 1, 0 + for idx, txt in enumerate(texts): + index += 1 + if scores[idx] < threshold or math.isnan(scores[idx]): + index -= 1 + continue + first_line = True + while str_count(txt) >= img_w // font_size - 4: + tmp = txt + txt = tmp[:img_w // font_size - 4] + if first_line: + new_txt = str(index) + ': ' + txt + first_line = False + else: + new_txt = ' ' + txt + draw_txt.text((0, gap * count), new_txt, txt_color, font=font) + txt = tmp[img_w // font_size - 4:] + if count >= img_h // gap - 1: + txt_img_list.append(np.array(blank_img)) + blank_img, draw_txt = create_blank_img() + count = 0 + count += 1 + if first_line: + new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx]) + else: + new_txt = " " + txt + " " + '%.3f' % (scores[idx]) + draw_txt.text((0, gap * count), new_txt, txt_color, font=font) + # whether add new blank img or not + if count >= img_h // gap - 1 and idx + 1 < len(texts): + txt_img_list.append(np.array(blank_img)) + blank_img, draw_txt = create_blank_img() + count = 0 + count += 1 + txt_img_list.append(np.array(blank_img)) + if len(txt_img_list) == 1: + blank_img = np.array(txt_img_list[0]) + else: + blank_img = np.concatenate(txt_img_list, axis=1) + return np.array(blank_img) + + +def base64_to_cv2(b64str): + import base64 + data = base64.b64decode(b64str.encode('utf8')) + data = np.frombuffer(data, np.uint8) + data = cv2.imdecode(data, cv2.IMREAD_COLOR) + return data + + +def draw_boxes(image, boxes, scores=None, drop_score=0.5): + if scores is None: + scores = [1] * len(boxes) + for (box, score) in zip(boxes, scores): + if score < drop_score: + continue + box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64) + image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2) + return image + + +def get_rotate_crop_image(img, points): + ''' + img_height, img_width = img.shape[0:2] + left = int(np.min(points[:, 0])) + right = int(np.max(points[:, 0])) + top = int(np.min(points[:, 1])) + bottom = int(np.max(points[:, 1])) + img_crop = img[top:bottom, left:right, :].copy() + points[:, 0] = points[:, 0] - left + points[:, 1] = points[:, 1] - top + ''' + assert len(points) == 4, "shape of points must be 4*2" + img_crop_width = int( + max( + np.linalg.norm(points[0] - points[1]), + np.linalg.norm(points[2] - points[3]))) + img_crop_height = int( + max( + np.linalg.norm(points[0] - points[3]), + np.linalg.norm(points[1] - points[2]))) + pts_std = np.float32([[0, 0], [img_crop_width, 0], + [img_crop_width, img_crop_height], + [0, img_crop_height]]) + M = cv2.getPerspectiveTransform(points, pts_std) + dst_img = cv2.warpPerspective( + img, + M, (img_crop_width, img_crop_height), + borderMode=cv2.BORDER_REPLICATE, + flags=cv2.INTER_CUBIC) + dst_img_height, dst_img_width = dst_img.shape[0:2] + if dst_img_height * 1.0 / dst_img_width >= 1.5: + dst_img = np.rot90(dst_img) + return dst_img + + +def check_gpu(use_gpu): + if use_gpu and not paddle.is_compiled_with_cuda(): + use_gpu = False + return use_gpu + + +if __name__ == '__main__': + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_cls.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_cls.py new file mode 100755 index 0000000000000000000000000000000000000000..7fd6b536fbe50fb1240d84ca3a5e87236940c0f5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_cls.py @@ -0,0 +1,85 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +import tools.program as program + + +def main(): + global_config = config['Global'] + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + model = build_model(config['Architecture']) + + load_model(config, model) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + continue + elif op_name == 'KeepKeys': + op[op_name]['keep_keys'] = ['image'] + elif op_name == "SSLRotateResize": + op[op_name]["mode"] = "test" + transforms.append(op) + global_config['infer_mode'] = True + ops = create_operators(transforms, global_config) + + model.eval() + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + with open(file, 'rb') as f: + img = f.read() + data = {'image': img} + batch = transform(data, ops) + + images = np.expand_dims(batch[0], axis=0) + images = paddle.to_tensor(images) + preds = model(images) + post_result = post_process_class(preds) + for rec_result in post_result: + logger.info('\t result: {}'.format(rec_result)) + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_det.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_det.py new file mode 100755 index 0000000000000000000000000000000000000000..f253e8f2876a5942538f18e93dfdada4391875b2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_det.py @@ -0,0 +1,134 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import json +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +import tools.program as program + + +def draw_det_res(dt_boxes, config, img, img_name, save_path): + if len(dt_boxes) > 0: + import cv2 + src_im = img + for box in dt_boxes: + box = np.array(box).astype(np.int32).reshape((-1, 1, 2)) + cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2) + if not os.path.exists(save_path): + os.makedirs(save_path) + save_path = os.path.join(save_path, os.path.basename(img_name)) + cv2.imwrite(save_path, src_im) + logger.info("The detected Image saved in {}".format(save_path)) + + +@paddle.no_grad() +def main(): + global_config = config['Global'] + + # build model + model = build_model(config['Architecture']) + + load_model(config, model) + # build post process + post_process_class = build_post_process(config['PostProcess']) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + continue + elif op_name == 'KeepKeys': + op[op_name]['keep_keys'] = ['image', 'shape'] + transforms.append(op) + + ops = create_operators(transforms, global_config) + + save_res_path = config['Global']['save_res_path'] + if not os.path.exists(os.path.dirname(save_res_path)): + os.makedirs(os.path.dirname(save_res_path)) + + model.eval() + with open(save_res_path, "wb") as fout: + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + with open(file, 'rb') as f: + img = f.read() + data = {'image': img} + batch = transform(data, ops) + + images = np.expand_dims(batch[0], axis=0) + shape_list = np.expand_dims(batch[1], axis=0) + images = paddle.to_tensor(images) + preds = model(images) + post_result = post_process_class(preds, shape_list) + + src_img = cv2.imread(file) + + dt_boxes_json = [] + # parser boxes if post_result is dict + if isinstance(post_result, dict): + det_box_json = {} + for k in post_result.keys(): + boxes = post_result[k][0]['points'] + dt_boxes_list = [] + for box in boxes: + tmp_json = {"transcription": ""} + tmp_json['points'] = np.array(box).tolist() + dt_boxes_list.append(tmp_json) + det_box_json[k] = dt_boxes_list + save_det_path = os.path.dirname(config['Global'][ + 'save_res_path']) + "/det_results_{}/".format(k) + draw_det_res(boxes, config, src_img, file, save_det_path) + else: + boxes = post_result[0]['points'] + dt_boxes_json = [] + # write result + for box in boxes: + tmp_json = {"transcription": ""} + tmp_json['points'] = np.array(box).tolist() + dt_boxes_json.append(tmp_json) + save_det_path = os.path.dirname(config['Global'][ + 'save_res_path']) + "/det_results/" + draw_det_res(boxes, config, src_img, file, save_det_path) + otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n" + fout.write(otstr.encode()) + + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_e2e.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_e2e.py new file mode 100755 index 0000000000000000000000000000000000000000..d3e6b28fca0a3ff32ea940747712d6c71aa290fd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_e2e.py @@ -0,0 +1,122 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import json +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +import tools.program as program + + +def draw_e2e_res(dt_boxes, strs, config, img, img_name): + if len(dt_boxes) > 0: + src_im = img + for box, str in zip(dt_boxes, strs): + box = box.astype(np.int32).reshape((-1, 1, 2)) + cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2) + cv2.putText( + src_im, + str, + org=(int(box[0, 0, 0]), int(box[0, 0, 1])), + fontFace=cv2.FONT_HERSHEY_COMPLEX, + fontScale=0.7, + color=(0, 255, 0), + thickness=1) + save_det_path = os.path.dirname(config['Global'][ + 'save_res_path']) + "/e2e_results/" + if not os.path.exists(save_det_path): + os.makedirs(save_det_path) + save_path = os.path.join(save_det_path, os.path.basename(img_name)) + cv2.imwrite(save_path, src_im) + logger.info("The e2e Image saved in {}".format(save_path)) + + +def main(): + global_config = config['Global'] + + # build model + model = build_model(config['Architecture']) + + load_model(config, model) + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + continue + elif op_name == 'KeepKeys': + op[op_name]['keep_keys'] = ['image', 'shape'] + transforms.append(op) + + ops = create_operators(transforms, global_config) + + save_res_path = config['Global']['save_res_path'] + if not os.path.exists(os.path.dirname(save_res_path)): + os.makedirs(os.path.dirname(save_res_path)) + + model.eval() + with open(save_res_path, "wb") as fout: + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + with open(file, 'rb') as f: + img = f.read() + data = {'image': img} + batch = transform(data, ops) + images = np.expand_dims(batch[0], axis=0) + shape_list = np.expand_dims(batch[1], axis=0) + images = paddle.to_tensor(images) + preds = model(images) + post_result = post_process_class(preds, shape_list) + points, strs = post_result['points'], post_result['texts'] + # write result + dt_boxes_json = [] + for poly, str in zip(points, strs): + tmp_json = {"transcription": str} + tmp_json['points'] = poly.tolist() + dt_boxes_json.append(tmp_json) + otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n" + fout.write(otstr.encode()) + src_img = cv2.imread(file) + draw_e2e_res(points, strs, config, src_img, file) + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie.py new file mode 100755 index 0000000000000000000000000000000000000000..9375434cc887b08dfa746420a6c73c58c6e04797 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie.py @@ -0,0 +1,176 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import paddle.nn.functional as F + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import cv2 +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.utils.save_load import load_model +import tools.program as program +import time + + +def read_class_list(filepath): + ret = {} + with open(filepath, "r") as f: + lines = f.readlines() + for idx, line in enumerate(lines): + ret[idx] = line.strip("\n") + return ret + + +def draw_kie_result(batch, node, idx_to_cls, count): + img = batch[6].copy() + boxes = batch[7] + h, w = img.shape[:2] + pred_img = np.ones((h, w * 2, 3), dtype=np.uint8) * 255 + max_value, max_idx = paddle.max(node, -1), paddle.argmax(node, -1) + node_pred_label = max_idx.numpy().tolist() + node_pred_score = max_value.numpy().tolist() + + for i, box in enumerate(boxes): + if i >= len(node_pred_label): + break + new_box = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], + [box[0], box[3]]] + Pts = np.array([new_box], np.int32) + cv2.polylines( + img, [Pts.reshape((-1, 1, 2))], + True, + color=(255, 255, 0), + thickness=1) + x_min = int(min([point[0] for point in new_box])) + y_min = int(min([point[1] for point in new_box])) + + pred_label = node_pred_label[i] + if pred_label in idx_to_cls: + pred_label = idx_to_cls[pred_label] + pred_score = '{:.2f}'.format(node_pred_score[i]) + text = pred_label + '(' + pred_score + ')' + cv2.putText(pred_img, text, (x_min * 2, y_min), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1) + vis_img = np.ones((h, w * 3, 3), dtype=np.uint8) * 255 + vis_img[:, :w] = img + vis_img[:, w:] = pred_img + save_kie_path = os.path.dirname(config['Global'][ + 'save_res_path']) + "/kie_results/" + if not os.path.exists(save_kie_path): + os.makedirs(save_kie_path) + save_path = os.path.join(save_kie_path, str(count) + ".png") + cv2.imwrite(save_path, vis_img) + logger.info("The Kie Image saved in {}".format(save_path)) + +def write_kie_result(fout, node, data): + """ + Write infer result to output file, sorted by the predict label of each line. + The format keeps the same as the input with additional score attribute. + """ + import json + label = data['label'] + annotations = json.loads(label) + max_value, max_idx = paddle.max(node, -1), paddle.argmax(node, -1) + node_pred_label = max_idx.numpy().tolist() + node_pred_score = max_value.numpy().tolist() + res = [] + for i, label in enumerate(node_pred_label): + pred_score = '{:.2f}'.format(node_pred_score[i]) + pred_res = { + 'label': label, + 'transcription': annotations[i]['transcription'], + 'score': pred_score, + 'points': annotations[i]['points'], + } + res.append(pred_res) + res.sort(key=lambda x: x['label']) + fout.writelines([json.dumps(res, ensure_ascii=False) + '\n']) + +def main(): + global_config = config['Global'] + + # build model + model = build_model(config['Architecture']) + load_model(config, model) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + transforms.append(op) + + data_dir = config['Eval']['dataset']['data_dir'] + + ops = create_operators(transforms, global_config) + + save_res_path = config['Global']['save_res_path'] + class_path = config['Global']['class_path'] + idx_to_cls = read_class_list(class_path) + os.makedirs(os.path.dirname(save_res_path), exist_ok=True) + + model.eval() + + warmup_times = 0 + count_t = [] + with open(save_res_path, "w") as fout: + with open(config['Global']['infer_img'], "rb") as f: + lines = f.readlines() + for index, data_line in enumerate(lines): + if index == 10: + warmup_t = time.time() + data_line = data_line.decode('utf-8') + substr = data_line.strip("\n").split("\t") + img_path, label = data_dir + "/" + substr[0], substr[1] + data = {'img_path': img_path, 'label': label} + with open(data['img_path'], 'rb') as f: + img = f.read() + data['image'] = img + st = time.time() + batch = transform(data, ops) + batch_pred = [0] * len(batch) + for i in range(len(batch)): + batch_pred[i] = paddle.to_tensor( + np.expand_dims( + batch[i], axis=0)) + st = time.time() + node, edge = model(batch_pred) + node = F.softmax(node, -1) + count_t.append(time.time() - st) + draw_kie_result(batch, node, idx_to_cls, index) + write_kie_result(fout, node, data) + fout.close() + logger.info("success!") + logger.info("It took {} s for predict {} images.".format( + np.sum(count_t), len(count_t))) + ips = len(count_t[warmup_times:]) / np.sum(count_t[warmup_times:]) + logger.info("The ips is {} images/s".format(ips)) + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser.py new file mode 100755 index 0000000000000000000000000000000000000000..2fc5749b9c10b9c89bc16e561fbe9c5ce58eb13c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser.py @@ -0,0 +1,157 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' +import cv2 +import json +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.visual import draw_ser_results +from ppocr.utils.utility import get_image_file_list, load_vqa_bio_label_maps +import tools.program as program + + +def to_tensor(data): + import numbers + from collections import defaultdict + data_dict = defaultdict(list) + to_tensor_idxs = [] + + for idx, v in enumerate(data): + if isinstance(v, (np.ndarray, paddle.Tensor, numbers.Number)): + if idx not in to_tensor_idxs: + to_tensor_idxs.append(idx) + data_dict[idx].append(v) + for idx in to_tensor_idxs: + data_dict[idx] = paddle.to_tensor(data_dict[idx]) + return list(data_dict.values()) + + +class SerPredictor(object): + def __init__(self, config): + global_config = config['Global'] + self.algorithm = config['Architecture']["algorithm"] + + # build post process + self.post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + self.model = build_model(config['Architecture']) + + load_model( + config, self.model, model_type=config['Architecture']["model_type"]) + + from paddleocr import PaddleOCR + + self.ocr_engine = PaddleOCR( + use_angle_cls=False, + show_log=False, + rec_model_dir=global_config.get("kie_rec_model_dir", None), + det_model_dir=global_config.get("kie_det_model_dir", None), + use_gpu=global_config['use_gpu']) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + op[op_name]['ocr_engine'] = self.ocr_engine + elif op_name == 'KeepKeys': + op[op_name]['keep_keys'] = [ + 'input_ids', 'bbox', 'attention_mask', 'token_type_ids', + 'image', 'labels', 'segment_offset_id', 'ocr_info', + 'entities' + ] + + transforms.append(op) + if config["Global"].get("infer_mode", None) is None: + global_config['infer_mode'] = True + self.ops = create_operators(config['Eval']['dataset']['transforms'], + global_config) + self.model.eval() + + def __call__(self, data): + with open(data["img_path"], 'rb') as f: + img = f.read() + data["image"] = img + batch = transform(data, self.ops) + batch = to_tensor(batch) + preds = self.model(batch) + + post_result = self.post_process_class( + preds, segment_offset_ids=batch[6], ocr_infos=batch[7]) + return post_result, batch + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + os.makedirs(config['Global']['save_res_path'], exist_ok=True) + + ser_engine = SerPredictor(config) + + if config["Global"].get("infer_mode", None) is False: + data_dir = config['Eval']['dataset']['data_dir'] + with open(config['Global']['infer_img'], "rb") as f: + infer_imgs = f.readlines() + else: + infer_imgs = get_image_file_list(config['Global']['infer_img']) + + with open( + os.path.join(config['Global']['save_res_path'], + "infer_results.txt"), + "w", + encoding='utf-8') as fout: + for idx, info in enumerate(infer_imgs): + if config["Global"].get("infer_mode", None) is False: + data_line = info.decode('utf-8') + substr = data_line.strip("\n").split("\t") + img_path = os.path.join(data_dir, substr[0]) + data = {'img_path': img_path, 'label': substr[1]} + else: + img_path = info + data = {'img_path': img_path} + + save_img_path = os.path.join( + config['Global']['save_res_path'], + os.path.splitext(os.path.basename(img_path))[0] + "_ser.jpg") + + result, _ = ser_engine(data) + result = result[0] + fout.write(img_path + "\t" + json.dumps( + { + "ocr_info": result, + }, ensure_ascii=False) + "\n") + img_res = draw_ser_results(img_path, result) + cv2.imwrite(save_img_path, img_res) + + logger.info("process: [{}/{}], save result to {}".format( + idx, len(infer_imgs), save_img_path)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser_re.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser_re.py new file mode 100755 index 0000000000000000000000000000000000000000..3ee696f28470a16205be628b3aeb586ef7a9c6a6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_kie_token_ser_re.py @@ -0,0 +1,213 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' +import cv2 +import json +import paddle +import paddle.distributed as dist + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.visual import draw_re_results +from ppocr.utils.logging import get_logger +from ppocr.utils.utility import get_image_file_list, load_vqa_bio_label_maps, print_dict +from tools.program import ArgsParser, load_config, merge_config +from tools.infer_kie_token_ser import SerPredictor + + +class ReArgsParser(ArgsParser): + def __init__(self): + super(ReArgsParser, self).__init__() + self.add_argument( + "-c_ser", "--config_ser", help="ser configuration file to use") + self.add_argument( + "-o_ser", + "--opt_ser", + nargs='+', + help="set ser configuration options ") + + def parse_args(self, argv=None): + args = super(ReArgsParser, self).parse_args(argv) + assert args.config_ser is not None, \ + "Please specify --config_ser=ser_configure_file_path." + args.opt_ser = self._parse_opt(args.opt_ser) + return args + + +def make_input(ser_inputs, ser_results): + entities_labels = {'HEADER': 0, 'QUESTION': 1, 'ANSWER': 2} + + entities = ser_inputs[8][0] + ser_results = ser_results[0] + assert len(entities) == len(ser_results) + + # entities + start = [] + end = [] + label = [] + entity_idx_dict = {} + for i, (res, entity) in enumerate(zip(ser_results, entities)): + if res['pred'] == 'O': + continue + entity_idx_dict[len(start)] = i + start.append(entity['start']) + end.append(entity['end']) + label.append(entities_labels[res['pred']]) + entities = dict(start=start, end=end, label=label) + + # relations + head = [] + tail = [] + for i in range(len(entities["label"])): + for j in range(len(entities["label"])): + if entities["label"][i] == 1 and entities["label"][j] == 2: + head.append(i) + tail.append(j) + + relations = dict(head=head, tail=tail) + + batch_size = ser_inputs[0].shape[0] + entities_batch = [] + relations_batch = [] + entity_idx_dict_batch = [] + for b in range(batch_size): + entities_batch.append(entities) + relations_batch.append(relations) + entity_idx_dict_batch.append(entity_idx_dict) + + ser_inputs[8] = entities_batch + ser_inputs.append(relations_batch) + # remove ocr_info segment_offset_id and label in ser input + ser_inputs.pop(7) + ser_inputs.pop(6) + ser_inputs.pop(5) + return ser_inputs, entity_idx_dict_batch + + +class SerRePredictor(object): + def __init__(self, config, ser_config): + global_config = config['Global'] + if "infer_mode" in global_config: + ser_config["Global"]["infer_mode"] = global_config["infer_mode"] + + self.ser_engine = SerPredictor(ser_config) + + # init re model + + # build post process + self.post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + self.model = build_model(config['Architecture']) + + load_model( + config, self.model, model_type=config['Architecture']["model_type"]) + + self.model.eval() + + def __call__(self, data): + ser_results, ser_inputs = self.ser_engine(data) + re_input, entity_idx_dict_batch = make_input(ser_inputs, ser_results) + preds = self.model(re_input) + post_result = self.post_process_class( + preds, + ser_results=ser_results, + entity_idx_dict_batch=entity_idx_dict_batch) + return post_result + + +def preprocess(): + FLAGS = ReArgsParser().parse_args() + config = load_config(FLAGS.config) + config = merge_config(config, FLAGS.opt) + + ser_config = load_config(FLAGS.config_ser) + ser_config = merge_config(ser_config, FLAGS.opt_ser) + + logger = get_logger() + + # check if set use_gpu=True in paddlepaddle cpu version + use_gpu = config['Global']['use_gpu'] + + device = 'gpu:{}'.format(dist.ParallelEnv().dev_id) if use_gpu else 'cpu' + device = paddle.set_device(device) + + logger.info('{} re config {}'.format('*' * 10, '*' * 10)) + print_dict(config, logger) + logger.info('\n') + logger.info('{} ser config {}'.format('*' * 10, '*' * 10)) + print_dict(ser_config, logger) + logger.info('train with paddle {} and device {}'.format(paddle.__version__, + device)) + return config, ser_config, device, logger + + +if __name__ == '__main__': + config, ser_config, device, logger = preprocess() + os.makedirs(config['Global']['save_res_path'], exist_ok=True) + + ser_re_engine = SerRePredictor(config, ser_config) + + if config["Global"].get("infer_mode", None) is False: + data_dir = config['Eval']['dataset']['data_dir'] + with open(config['Global']['infer_img'], "rb") as f: + infer_imgs = f.readlines() + else: + infer_imgs = get_image_file_list(config['Global']['infer_img']) + + with open( + os.path.join(config['Global']['save_res_path'], + "infer_results.txt"), + "w", + encoding='utf-8') as fout: + for idx, info in enumerate(infer_imgs): + if config["Global"].get("infer_mode", None) is False: + data_line = info.decode('utf-8') + substr = data_line.strip("\n").split("\t") + img_path = os.path.join(data_dir, substr[0]) + data = {'img_path': img_path, 'label': substr[1]} + else: + img_path = info + data = {'img_path': img_path} + + save_img_path = os.path.join( + config['Global']['save_res_path'], + os.path.splitext(os.path.basename(img_path))[0] + "_ser_re.jpg") + + result = ser_re_engine(data) + result = result[0] + fout.write(img_path + "\t" + json.dumps( + result, ensure_ascii=False) + "\n") + img_res = draw_re_results(img_path, result) + cv2.imwrite(save_img_path, img_res) + + logger.info("process: [{}/{}], save result to {}".format( + idx, len(infer_imgs), save_img_path)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_rec.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_rec.py new file mode 100755 index 0000000000000000000000000000000000000000..2d2e09a2840da1f73cac613bdd01090050729893 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_rec.py @@ -0,0 +1,176 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys +import json + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +import tools.program as program + + +def main(): + global_config = config['Global'] + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + if hasattr(post_process_class, 'character'): + char_num = len(getattr(post_process_class, 'character')) + if config['Architecture']["algorithm"] in ["Distillation", + ]: # distillation model + for key in config['Architecture']["Models"]: + if config['Architecture']['Models'][key]['Head'][ + 'name'] == 'MultiHead': # for multi head + out_channels_list = {} + if config['PostProcess'][ + 'name'] == 'DistillationSARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Models'][key]['Head'][ + 'out_channels_list'] = out_channels_list + else: + config['Architecture']["Models"][key]["Head"][ + 'out_channels'] = char_num + elif config['Architecture']['Head'][ + 'name'] == 'MultiHead': # for multi head loss + out_channels_list = {} + if config['PostProcess']['name'] == 'SARLabelDecode': + char_num = char_num - 2 + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Head'][ + 'out_channels_list'] = out_channels_list + else: # base rec model + config['Architecture']["Head"]['out_channels'] = char_num + model = build_model(config['Architecture']) + + load_model(config, model) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + continue + elif op_name in ['RecResizeImg']: + op[op_name]['infer_mode'] = True + elif op_name == 'KeepKeys': + if config['Architecture']['algorithm'] == "SRN": + op[op_name]['keep_keys'] = [ + 'image', 'encoder_word_pos', 'gsrm_word_pos', + 'gsrm_slf_attn_bias1', 'gsrm_slf_attn_bias2' + ] + elif config['Architecture']['algorithm'] == "SAR": + op[op_name]['keep_keys'] = ['image', 'valid_ratio'] + elif config['Architecture']['algorithm'] == "RobustScanner": + op[op_name][ + 'keep_keys'] = ['image', 'valid_ratio', 'word_positons'] + else: + op[op_name]['keep_keys'] = ['image'] + transforms.append(op) + global_config['infer_mode'] = True + ops = create_operators(transforms, global_config) + + save_res_path = config['Global'].get('save_res_path', + "./output/rec/predicts_rec.txt") + if not os.path.exists(os.path.dirname(save_res_path)): + os.makedirs(os.path.dirname(save_res_path)) + + model.eval() + + with open(save_res_path, "w") as fout: + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + with open(file, 'rb') as f: + img = f.read() + data = {'image': img} + batch = transform(data, ops) + if config['Architecture']['algorithm'] == "SRN": + encoder_word_pos_list = np.expand_dims(batch[1], axis=0) + gsrm_word_pos_list = np.expand_dims(batch[2], axis=0) + gsrm_slf_attn_bias1_list = np.expand_dims(batch[3], axis=0) + gsrm_slf_attn_bias2_list = np.expand_dims(batch[4], axis=0) + + others = [ + paddle.to_tensor(encoder_word_pos_list), + paddle.to_tensor(gsrm_word_pos_list), + paddle.to_tensor(gsrm_slf_attn_bias1_list), + paddle.to_tensor(gsrm_slf_attn_bias2_list) + ] + if config['Architecture']['algorithm'] == "SAR": + valid_ratio = np.expand_dims(batch[-1], axis=0) + img_metas = [paddle.to_tensor(valid_ratio)] + if config['Architecture']['algorithm'] == "RobustScanner": + valid_ratio = np.expand_dims(batch[1], axis=0) + word_positons = np.expand_dims(batch[2], axis=0) + img_metas = [ + paddle.to_tensor(valid_ratio), + paddle.to_tensor(word_positons), + ] + images = np.expand_dims(batch[0], axis=0) + images = paddle.to_tensor(images) + if config['Architecture']['algorithm'] == "SRN": + preds = model(images, others) + elif config['Architecture']['algorithm'] == "SAR": + preds = model(images, img_metas) + elif config['Architecture']['algorithm'] == "RobustScanner": + preds = model(images, img_metas) + else: + preds = model(images) + post_result = post_process_class(preds) + info = None + if isinstance(post_result, dict): + rec_info = dict() + for key in post_result: + if len(post_result[key][0]) >= 2: + rec_info[key] = { + "label": post_result[key][0][0], + "score": float(post_result[key][0][1]), + } + info = json.dumps(rec_info, ensure_ascii=False) + else: + if len(post_result[0]) >= 2: + info = post_result[0][0] + "\t" + str(post_result[0][1]) + + if info is not None: + logger.info("\t result: {}".format(info)) + fout.write(file + "\t" + info + "\n") + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_sr.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_sr.py new file mode 100755 index 0000000000000000000000000000000000000000..df4334f3427e57b9062dd819aa16c110fd771e8c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_sr.py @@ -0,0 +1,100 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys +import json +from PIL import Image +import cv2 + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, __dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import paddle + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +import tools.program as program + + +def main(): + global_config = config['Global'] + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # sr transform + config['Architecture']["Transform"]['infer_mode'] = True + + model = build_model(config['Architecture']) + + load_model(config, model) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Label' in op_name: + continue + elif op_name in ['SRResize']: + op[op_name]['infer_mode'] = True + elif op_name == 'KeepKeys': + op[op_name]['keep_keys'] = ['img_lr'] + transforms.append(op) + global_config['infer_mode'] = True + ops = create_operators(transforms, global_config) + + save_visual_path = config['Global'].get('save_visual', "infer_result/") + if not os.path.exists(os.path.dirname(save_visual_path)): + os.makedirs(os.path.dirname(save_visual_path)) + + model.eval() + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + img = Image.open(file).convert("RGB") + data = {'image_lr': img} + batch = transform(data, ops) + images = np.expand_dims(batch[0], axis=0) + images = paddle.to_tensor(images) + + preds = model(images) + sr_img = preds["sr_img"][0] + lr_img = preds["lr_img"][0] + fm_sr = (sr_img.numpy() * 255).transpose(1, 2, 0).astype(np.uint8) + fm_lr = (lr_img.numpy() * 255).transpose(1, 2, 0).astype(np.uint8) + img_name_pure = os.path.split(file)[-1] + cv2.imwrite("{}/sr_{}".format(save_visual_path, img_name_pure), + fm_sr[:, :, ::-1]) + logger.info("The visualized image saved in infer_result/sr_{}".format( + img_name_pure)) + + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_table.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6dde5d67d061f4d0593928759db34bb9b22cde0d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/infer_table.py @@ -0,0 +1,121 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +import os +import sys +import json + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +os.environ["FLAGS_allocator_strategy"] = 'auto_growth' + +import paddle +from paddle.jit import to_static + +from ppocr.data import create_operators, transform +from ppocr.modeling.architectures import build_model +from ppocr.postprocess import build_post_process +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import get_image_file_list +from ppocr.utils.visual import draw_rectangle +from tools.infer.utility import draw_boxes +import tools.program as program +import cv2 + + +@paddle.no_grad() +def main(config, device, logger, vdl_writer): + global_config = config['Global'] + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + if hasattr(post_process_class, 'character'): + config['Architecture']["Head"]['out_channels'] = len( + getattr(post_process_class, 'character')) + + model = build_model(config['Architecture']) + algorithm = config['Architecture']['algorithm'] + + load_model(config, model) + + # create data ops + transforms = [] + for op in config['Eval']['dataset']['transforms']: + op_name = list(op)[0] + if 'Encode' in op_name: + continue + if op_name == 'KeepKeys': + op[op_name]['keep_keys'] = ['image', 'shape'] + transforms.append(op) + + global_config['infer_mode'] = True + ops = create_operators(transforms, global_config) + + save_res_path = config['Global']['save_res_path'] + os.makedirs(save_res_path, exist_ok=True) + + model.eval() + with open( + os.path.join(save_res_path, 'infer.txt'), mode='w', + encoding='utf-8') as f_w: + for file in get_image_file_list(config['Global']['infer_img']): + logger.info("infer_img: {}".format(file)) + with open(file, 'rb') as f: + img = f.read() + data = {'image': img} + batch = transform(data, ops) + images = np.expand_dims(batch[0], axis=0) + shape_list = np.expand_dims(batch[1], axis=0) + + images = paddle.to_tensor(images) + preds = model(images) + post_result = post_process_class(preds, [shape_list]) + + structure_str_list = post_result['structure_batch_list'][0] + bbox_list = post_result['bbox_batch_list'][0] + structure_str_list = structure_str_list[0] + structure_str_list = [ + '', '', '' + ] + structure_str_list + ['
', '', ''] + bbox_list_str = json.dumps(bbox_list.tolist()) + + logger.info("result: {}, {}".format(structure_str_list, + bbox_list_str)) + f_w.write("result: {}, {}\n".format(structure_str_list, + bbox_list_str)) + + if len(bbox_list) > 0 and len(bbox_list[0]) == 4: + img = draw_rectangle(file, bbox_list) + else: + img = draw_boxes(cv2.imread(file), bbox_list) + cv2.imwrite( + os.path.join(save_res_path, os.path.basename(file)), img) + logger.info('save result to {}'.format(save_res_path)) + logger.info("success!") + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess() + main(config, device, logger, vdl_writer) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/program.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/program.py new file mode 100755 index 0000000000000000000000000000000000000000..16d3d4035af933cda01b422ea56e9e2895ec2b88 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/program.py @@ -0,0 +1,688 @@ +# Copyright (c) 2021 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys +import platform +import yaml +import time +import datetime +import paddle +import paddle.distributed as dist +from tqdm import tqdm +import cv2 +import numpy as np +from argparse import ArgumentParser, RawDescriptionHelpFormatter + +from ppocr.utils.stats import TrainingStats +from ppocr.utils.save_load import save_model +from ppocr.utils.utility import print_dict, AverageMeter +from ppocr.utils.logging import get_logger +from ppocr.utils.loggers import VDLLogger, WandbLogger, Loggers +from ppocr.utils import profiler +from ppocr.data import build_dataloader + + +class ArgsParser(ArgumentParser): + def __init__(self): + super(ArgsParser, self).__init__( + formatter_class=RawDescriptionHelpFormatter) + self.add_argument("-c", "--config", help="configuration file to use") + self.add_argument( + "-o", "--opt", nargs='+', help="set configuration options") + self.add_argument( + '-p', + '--profiler_options', + type=str, + default=None, + help='The option of profiler, which should be in format ' \ + '\"key1=value1;key2=value2;key3=value3\".' + ) + + def parse_args(self, argv=None): + args = super(ArgsParser, self).parse_args(argv) + assert args.config is not None, \ + "Please specify --config=configure_file_path." + args.opt = self._parse_opt(args.opt) + return args + + def _parse_opt(self, opts): + config = {} + if not opts: + return config + for s in opts: + s = s.strip() + k, v = s.split('=') + config[k] = yaml.load(v, Loader=yaml.Loader) + return config + + +def load_config(file_path): + """ + Load config from yml/yaml file. + Args: + file_path (str): Path of the config file to be loaded. + Returns: global config + """ + _, ext = os.path.splitext(file_path) + assert ext in ['.yml', '.yaml'], "only support yaml files for now" + config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader) + return config + + +def merge_config(config, opts): + """ + Merge config into global config. + Args: + config (dict): Config to be merged. + Returns: global config + """ + for key, value in opts.items(): + if "." not in key: + if isinstance(value, dict) and key in config: + config[key].update(value) + else: + config[key] = value + else: + sub_keys = key.split('.') + assert ( + sub_keys[0] in config + ), "the sub_keys can only be one of global_config: {}, but get: " \ + "{}, please check your running command".format( + config.keys(), sub_keys[0]) + cur = config[sub_keys[0]] + for idx, sub_key in enumerate(sub_keys[1:]): + if idx == len(sub_keys) - 2: + cur[sub_key] = value + else: + cur = cur[sub_key] + return config + + +def check_device(use_gpu, use_xpu=False): + """ + Log error and exit when set use_gpu=true in paddlepaddle + cpu version. + """ + err = "Config {} cannot be set as true while your paddle " \ + "is not compiled with {} ! \nPlease try: \n" \ + "\t1. Install paddlepaddle to run model on {} \n" \ + "\t2. Set {} as false in config file to run " \ + "model on CPU" + + try: + if use_gpu and use_xpu: + print("use_xpu and use_gpu can not both be ture.") + if use_gpu and not paddle.is_compiled_with_cuda(): + print(err.format("use_gpu", "cuda", "gpu", "use_gpu")) + sys.exit(1) + if use_xpu and not paddle.device.is_compiled_with_xpu(): + print(err.format("use_xpu", "xpu", "xpu", "use_xpu")) + sys.exit(1) + except Exception as e: + pass + + +def check_xpu(use_xpu): + """ + Log error and exit when set use_xpu=true in paddlepaddle + cpu/gpu version. + """ + err = "Config use_xpu cannot be set as true while you are " \ + "using paddlepaddle cpu/gpu version ! \nPlease try: \n" \ + "\t1. Install paddlepaddle-xpu to run model on XPU \n" \ + "\t2. Set use_xpu as false in config file to run " \ + "model on CPU/GPU" + + try: + if use_xpu and not paddle.is_compiled_with_xpu(): + print(err) + sys.exit(1) + except Exception as e: + pass + + +def to_float32(preds): + if isinstance(preds, dict): + for k in preds: + if isinstance(preds[k], dict) or isinstance(preds[k], list): + preds[k] = to_float32(preds[k]) + elif isinstance(preds[k], paddle.Tensor): + preds[k] = preds[k].astype(paddle.float32) + elif isinstance(preds, list): + for k in range(len(preds)): + if isinstance(preds[k], dict): + preds[k] = to_float32(preds[k]) + elif isinstance(preds[k], list): + preds[k] = to_float32(preds[k]) + elif isinstance(preds[k], paddle.Tensor): + preds[k] = preds[k].astype(paddle.float32) + elif isinstance(preds, paddle.Tensor): + preds = preds.astype(paddle.float32) + return preds + + +def train(config, + train_dataloader, + valid_dataloader, + device, + model, + loss_class, + optimizer, + lr_scheduler, + post_process_class, + eval_class, + pre_best_model_dict, + logger, + log_writer=None, + scaler=None, + amp_level='O2', + amp_custom_black_list=[]): + cal_metric_during_train = config['Global'].get('cal_metric_during_train', + False) + calc_epoch_interval = config['Global'].get('calc_epoch_interval', 1) + log_smooth_window = config['Global']['log_smooth_window'] + epoch_num = config['Global']['epoch_num'] + print_batch_step = config['Global']['print_batch_step'] + eval_batch_step = config['Global']['eval_batch_step'] + profiler_options = config['profiler_options'] + + global_step = 0 + if 'global_step' in pre_best_model_dict: + global_step = pre_best_model_dict['global_step'] + start_eval_step = 0 + if type(eval_batch_step) == list and len(eval_batch_step) >= 2: + start_eval_step = eval_batch_step[0] + eval_batch_step = eval_batch_step[1] + if len(valid_dataloader) == 0: + logger.info( + 'No Images in eval dataset, evaluation during training ' \ + 'will be disabled' + ) + start_eval_step = 1e111 + logger.info( + "During the training process, after the {}th iteration, " \ + "an evaluation is run every {} iterations". + format(start_eval_step, eval_batch_step)) + save_epoch_step = config['Global']['save_epoch_step'] + save_model_dir = config['Global']['save_model_dir'] + if not os.path.exists(save_model_dir): + os.makedirs(save_model_dir) + main_indicator = eval_class.main_indicator + best_model_dict = {main_indicator: 0} + best_model_dict.update(pre_best_model_dict) + train_stats = TrainingStats(log_smooth_window, ['lr']) + model_average = False + model.train() + + use_srn = config['Architecture']['algorithm'] == "SRN" + extra_input_models = [ + "SRN", "NRTR", "SAR", "SEED", "SVTR", "SPIN", "VisionLAN", + "RobustScanner" + ] + extra_input = False + if config['Architecture']['algorithm'] == 'Distillation': + for key in config['Architecture']["Models"]: + extra_input = extra_input or config['Architecture']['Models'][key][ + 'algorithm'] in extra_input_models + else: + extra_input = config['Architecture']['algorithm'] in extra_input_models + try: + model_type = config['Architecture']['model_type'] + except: + model_type = None + + algorithm = config['Architecture']['algorithm'] + + start_epoch = best_model_dict[ + 'start_epoch'] if 'start_epoch' in best_model_dict else 1 + + total_samples = 0 + train_reader_cost = 0.0 + train_batch_cost = 0.0 + reader_start = time.time() + eta_meter = AverageMeter() + + max_iter = len(train_dataloader) - 1 if platform.system( + ) == "Windows" else len(train_dataloader) + + for epoch in range(start_epoch, epoch_num + 1): + if train_dataloader.dataset.need_reset: + train_dataloader = build_dataloader( + config, 'Train', device, logger, seed=epoch) + max_iter = len(train_dataloader) - 1 if platform.system( + ) == "Windows" else len(train_dataloader) + + for idx, batch in enumerate(train_dataloader): + profiler.add_profiler_step(profiler_options) + train_reader_cost += time.time() - reader_start + if idx >= max_iter: + break + lr = optimizer.get_lr() + images = batch[0] + if use_srn: + model_average = True + # use amp + if scaler: + with paddle.amp.auto_cast(level=amp_level, custom_black_list=amp_custom_black_list): + if model_type == 'table' or extra_input: + preds = model(images, data=batch[1:]) + elif model_type in ["kie"]: + preds = model(batch) + else: + preds = model(images) + preds = to_float32(preds) + loss = loss_class(preds, batch) + avg_loss = loss['loss'] + scaled_avg_loss = scaler.scale(avg_loss) + scaled_avg_loss.backward() + scaler.minimize(optimizer, scaled_avg_loss) + else: + if model_type == 'table' or extra_input: + preds = model(images, data=batch[1:]) + elif model_type in ["kie", 'sr']: + preds = model(batch) + else: + preds = model(images) + loss = loss_class(preds, batch) + avg_loss = loss['loss'] + avg_loss.backward() + optimizer.step() + + optimizer.clear_grad() + + if cal_metric_during_train and epoch % calc_epoch_interval == 0: # only rec and cls need + batch = [item.numpy() for item in batch] + if model_type in ['kie', 'sr']: + eval_class(preds, batch) + elif model_type in ['table']: + post_result = post_process_class(preds, batch) + eval_class(post_result, batch) + else: + if config['Loss']['name'] in ['MultiLoss', 'MultiLoss_v2' + ]: # for multi head loss + post_result = post_process_class( + preds['ctc'], batch[1]) # for CTC head out + elif config['Loss']['name'] in ['VLLoss']: + post_result = post_process_class(preds, batch[1], + batch[-1]) + else: + post_result = post_process_class(preds, batch[1]) + eval_class(post_result, batch) + metric = eval_class.get_metric() + train_stats.update(metric) + + train_batch_time = time.time() - reader_start + train_batch_cost += train_batch_time + eta_meter.update(train_batch_time) + global_step += 1 + total_samples += len(images) + + if not isinstance(lr_scheduler, float): + lr_scheduler.step() + + # logger and visualdl + stats = {k: v.numpy().mean() for k, v in loss.items()} + stats['lr'] = lr + train_stats.update(stats) + + if log_writer is not None and dist.get_rank() == 0: + log_writer.log_metrics( + metrics=train_stats.get(), prefix="TRAIN", step=global_step) + + if dist.get_rank() == 0 and ( + (global_step > 0 and global_step % print_batch_step == 0) or + (idx >= len(train_dataloader) - 1)): + logs = train_stats.log() + + eta_sec = ((epoch_num + 1 - epoch) * \ + len(train_dataloader) - idx - 1) * eta_meter.avg + eta_sec_format = str(datetime.timedelta(seconds=int(eta_sec))) + strs = 'epoch: [{}/{}], global_step: {}, {}, avg_reader_cost: ' \ + '{:.5f} s, avg_batch_cost: {:.5f} s, avg_samples: {}, ' \ + 'ips: {:.5f} samples/s, eta: {}'.format( + epoch, epoch_num, global_step, logs, + train_reader_cost / print_batch_step, + train_batch_cost / print_batch_step, + total_samples / print_batch_step, + total_samples / train_batch_cost, eta_sec_format) + logger.info(strs) + + total_samples = 0 + train_reader_cost = 0.0 + train_batch_cost = 0.0 + # eval + if global_step > start_eval_step and \ + (global_step - start_eval_step) % eval_batch_step == 0 \ + and dist.get_rank() == 0: + if model_average: + Model_Average = paddle.incubate.optimizer.ModelAverage( + 0.15, + parameters=model.parameters(), + min_average_window=10000, + max_average_window=15625) + Model_Average.apply() + cur_metric = eval( + model, + valid_dataloader, + post_process_class, + eval_class, + model_type, + extra_input=extra_input, + scaler=scaler, + amp_level=amp_level, + amp_custom_black_list=amp_custom_black_list) + cur_metric_str = 'cur metric, {}'.format(', '.join( + ['{}: {}'.format(k, v) for k, v in cur_metric.items()])) + logger.info(cur_metric_str) + + # logger metric + if log_writer is not None: + log_writer.log_metrics( + metrics=cur_metric, prefix="EVAL", step=global_step) + + if cur_metric[main_indicator] >= best_model_dict[ + main_indicator]: + best_model_dict.update(cur_metric) + best_model_dict['best_epoch'] = epoch + save_model( + model, + optimizer, + save_model_dir, + logger, + config, + is_best=True, + prefix='best_accuracy', + best_model_dict=best_model_dict, + epoch=epoch, + global_step=global_step) + best_str = 'best metric, {}'.format(', '.join([ + '{}: {}'.format(k, v) for k, v in best_model_dict.items() + ])) + logger.info(best_str) + # logger best metric + if log_writer is not None: + log_writer.log_metrics( + metrics={ + "best_{}".format(main_indicator): + best_model_dict[main_indicator] + }, + prefix="EVAL", + step=global_step) + + log_writer.log_model( + is_best=True, + prefix="best_accuracy", + metadata=best_model_dict) + + reader_start = time.time() + if dist.get_rank() == 0: + save_model( + model, + optimizer, + save_model_dir, + logger, + config, + is_best=False, + prefix='latest', + best_model_dict=best_model_dict, + epoch=epoch, + global_step=global_step) + + if log_writer is not None: + log_writer.log_model(is_best=False, prefix="latest") + + if dist.get_rank() == 0 and epoch > 0 and epoch % save_epoch_step == 0: + save_model( + model, + optimizer, + save_model_dir, + logger, + config, + is_best=False, + prefix='iter_epoch_{}'.format(epoch), + best_model_dict=best_model_dict, + epoch=epoch, + global_step=global_step) + if log_writer is not None: + log_writer.log_model( + is_best=False, prefix='iter_epoch_{}'.format(epoch)) + + best_str = 'best metric, {}'.format(', '.join( + ['{}: {}'.format(k, v) for k, v in best_model_dict.items()])) + logger.info(best_str) + if dist.get_rank() == 0 and log_writer is not None: + log_writer.close() + return + + +def eval(model, + valid_dataloader, + post_process_class, + eval_class, + model_type=None, + extra_input=False, + scaler=None, + amp_level='O2', + amp_custom_black_list = []): + model.eval() + with paddle.no_grad(): + total_frame = 0.0 + total_time = 0.0 + pbar = tqdm( + total=len(valid_dataloader), + desc='eval model:', + position=0, + leave=True) + max_iter = len(valid_dataloader) - 1 if platform.system( + ) == "Windows" else len(valid_dataloader) + sum_images = 0 + for idx, batch in enumerate(valid_dataloader): + if idx >= max_iter: + break + images = batch[0] + start = time.time() + + # use amp + if scaler: + with paddle.amp.auto_cast(level=amp_level, custom_black_list=amp_custom_black_list): + if model_type == 'table' or extra_input: + preds = model(images, data=batch[1:]) + elif model_type in ["kie"]: + preds = model(batch) + elif model_type in ['sr']: + preds = model(batch) + sr_img = preds["sr_img"] + lr_img = preds["lr_img"] + else: + preds = model(images) + preds = to_float32(preds) + else: + if model_type == 'table' or extra_input: + preds = model(images, data=batch[1:]) + elif model_type in ["kie"]: + preds = model(batch) + elif model_type in ['sr']: + preds = model(batch) + sr_img = preds["sr_img"] + lr_img = preds["lr_img"] + else: + preds = model(images) + + batch_numpy = [] + for item in batch: + if isinstance(item, paddle.Tensor): + batch_numpy.append(item.numpy()) + else: + batch_numpy.append(item) + # Obtain usable results from post-processing methods + total_time += time.time() - start + # Evaluate the results of the current batch + if model_type in ['table', 'kie']: + if post_process_class is None: + eval_class(preds, batch_numpy) + else: + post_result = post_process_class(preds, batch_numpy) + eval_class(post_result, batch_numpy) + elif model_type in ['sr']: + eval_class(preds, batch_numpy) + else: + post_result = post_process_class(preds, batch_numpy[1]) + eval_class(post_result, batch_numpy) + + pbar.update(1) + total_frame += len(images) + sum_images += 1 + # Get final metric,eg. acc or hmean + metric = eval_class.get_metric() + + pbar.close() + model.train() + metric['fps'] = total_frame / total_time + return metric + + +def update_center(char_center, post_result, preds): + result, label = post_result + feats, logits = preds + logits = paddle.argmax(logits, axis=-1) + feats = feats.numpy() + logits = logits.numpy() + + for idx_sample in range(len(label)): + if result[idx_sample][0] == label[idx_sample][0]: + feat = feats[idx_sample] + logit = logits[idx_sample] + for idx_time in range(len(logit)): + index = logit[idx_time] + if index in char_center.keys(): + char_center[index][0] = ( + char_center[index][0] * char_center[index][1] + + feat[idx_time]) / (char_center[index][1] + 1) + char_center[index][1] += 1 + else: + char_center[index] = [feat[idx_time], 1] + return char_center + + +def get_center(model, eval_dataloader, post_process_class): + pbar = tqdm(total=len(eval_dataloader), desc='get center:') + max_iter = len(eval_dataloader) - 1 if platform.system( + ) == "Windows" else len(eval_dataloader) + char_center = dict() + for idx, batch in enumerate(eval_dataloader): + if idx >= max_iter: + break + images = batch[0] + start = time.time() + preds = model(images) + + batch = [item.numpy() for item in batch] + # Obtain usable results from post-processing methods + post_result = post_process_class(preds, batch[1]) + + #update char_center + char_center = update_center(char_center, post_result, preds) + pbar.update(1) + + pbar.close() + for key in char_center.keys(): + char_center[key] = char_center[key][0] + return char_center + + +def preprocess(is_train=False): + FLAGS = ArgsParser().parse_args() + profiler_options = FLAGS.profiler_options + config = load_config(FLAGS.config) + config = merge_config(config, FLAGS.opt) + profile_dic = {"profiler_options": FLAGS.profiler_options} + config = merge_config(config, profile_dic) + + if is_train: + # save_config + save_model_dir = config['Global']['save_model_dir'] + os.makedirs(save_model_dir, exist_ok=True) + with open(os.path.join(save_model_dir, 'config.yml'), 'w') as f: + yaml.dump( + dict(config), f, default_flow_style=False, sort_keys=False) + log_file = '{}/train.log'.format(save_model_dir) + else: + log_file = None + logger = get_logger(log_file=log_file) + + # check if set use_gpu=True in paddlepaddle cpu version + use_gpu = config['Global']['use_gpu'] + use_xpu = config['Global'].get('use_xpu', False) + + # check if set use_xpu=True in paddlepaddle cpu/gpu version + use_xpu = False + if 'use_xpu' in config['Global']: + use_xpu = config['Global']['use_xpu'] + check_xpu(use_xpu) + + alg = config['Architecture']['algorithm'] + assert alg in [ + 'EAST', 'DB', 'SAST', 'Rosetta', 'CRNN', 'STARNet', 'RARE', 'SRN', + 'CLS', 'PGNet', 'Distillation', 'NRTR', 'TableAttn', 'SAR', 'PSE', + 'SEED', 'SDMGR', 'LayoutXLM', 'LayoutLM', 'LayoutLMv2', 'PREN', 'FCE', + 'SVTR', 'ViTSTR', 'ABINet', 'DB++', 'TableMaster', 'SPIN', 'VisionLAN', + 'Gestalt', 'SLANet', 'RobustScanner' + ] + + if use_xpu: + device = 'xpu:{0}'.format(os.getenv('FLAGS_selected_xpus', 0)) + else: + device = 'gpu:{}'.format(dist.ParallelEnv() + .dev_id) if use_gpu else 'cpu' + check_device(use_gpu, use_xpu) + + device = paddle.set_device(device) + + config['Global']['distributed'] = dist.get_world_size() != 1 + + loggers = [] + + if 'use_visualdl' in config['Global'] and config['Global']['use_visualdl']: + save_model_dir = config['Global']['save_model_dir'] + vdl_writer_path = '{}/vdl/'.format(save_model_dir) + log_writer = VDLLogger(vdl_writer_path) + loggers.append(log_writer) + if ('use_wandb' in config['Global'] and + config['Global']['use_wandb']) or 'wandb' in config: + save_dir = config['Global']['save_model_dir'] + wandb_writer_path = "{}/wandb".format(save_dir) + if "wandb" in config: + wandb_params = config['wandb'] + else: + wandb_params = dict() + wandb_params.update({'save_dir': save_model_dir}) + log_writer = WandbLogger(**wandb_params, config=config) + loggers.append(log_writer) + else: + log_writer = None + print_dict(config, logger) + + if loggers: + log_writer = Loggers(loggers) + else: + log_writer = None + + logger.info('train with paddle {} and device {}'.format(paddle.__version__, + device)) + return config, device, logger, log_writer diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/test_hubserving.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/test_hubserving.py new file mode 100755 index 0000000000000000000000000000000000000000..ec17a9413e15b3ae92843990cfcbb05fc5f991a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/test_hubserving.py @@ -0,0 +1,157 @@ +# 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. +import os +import sys +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.append(os.path.abspath(os.path.join(__dir__, '..'))) + +from ppocr.utils.logging import get_logger +logger = get_logger() + +import cv2 +import numpy as np +import time +from PIL import Image +from ppocr.utils.utility import get_image_file_list +from tools.infer.utility import draw_ocr, draw_boxes, str2bool +from ppstructure.utility import draw_structure_result +from ppstructure.predict_system import to_excel + +import requests +import json +import base64 + + +def cv2_to_base64(image): + return base64.b64encode(image).decode('utf8') + + +def draw_server_result(image_file, res): + img = cv2.imread(image_file) + image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + if len(res) == 0: + return np.array(image) + keys = res[0].keys() + if 'text_region' not in keys: # for ocr_rec, draw function is invalid + logger.info("draw function is invalid for ocr_rec!") + return None + elif 'text' not in keys: # for ocr_det + logger.info("draw text boxes only!") + boxes = [] + for dno in range(len(res)): + boxes.append(res[dno]['text_region']) + boxes = np.array(boxes) + draw_img = draw_boxes(image, boxes) + return draw_img + else: # for ocr_system + logger.info("draw boxes and texts!") + boxes = [] + texts = [] + scores = [] + for dno in range(len(res)): + boxes.append(res[dno]['text_region']) + texts.append(res[dno]['text']) + scores.append(res[dno]['confidence']) + boxes = np.array(boxes) + scores = np.array(scores) + draw_img = draw_ocr( + image, boxes, texts, scores, draw_txt=True, drop_score=0.5) + return draw_img + + +def save_structure_res(res, save_folder, image_file): + img = cv2.imread(image_file) + excel_save_folder = os.path.join(save_folder, os.path.basename(image_file)) + os.makedirs(excel_save_folder, exist_ok=True) + # save res + with open( + os.path.join(excel_save_folder, 'res.txt'), 'w', + encoding='utf8') as f: + for region in res: + if region['type'] == 'Table': + excel_path = os.path.join(excel_save_folder, + '{}.xlsx'.format(region['bbox'])) + to_excel(region['res'], excel_path) + elif region['type'] == 'Figure': + x1, y1, x2, y2 = region['bbox'] + print(region['bbox']) + roi_img = img[y1:y2, x1:x2, :] + img_path = os.path.join(excel_save_folder, + '{}.jpg'.format(region['bbox'])) + cv2.imwrite(img_path, roi_img) + else: + for text_result in region['res']: + f.write('{}\n'.format(json.dumps(text_result))) + + +def main(args): + image_file_list = get_image_file_list(args.image_dir) + is_visualize = False + headers = {"Content-type": "application/json"} + cnt = 0 + total_time = 0 + for image_file in image_file_list: + img = open(image_file, 'rb').read() + if img is None: + logger.info("error in loading image:{}".format(image_file)) + continue + img_name = os.path.basename(image_file) + # seed http request + starttime = time.time() + data = {'images': [cv2_to_base64(img)]} + r = requests.post( + url=args.server_url, headers=headers, data=json.dumps(data)) + elapse = time.time() - starttime + total_time += elapse + logger.info("Predict time of %s: %.3fs" % (image_file, elapse)) + res = r.json()["results"][0] + logger.info(res) + + if args.visualize: + draw_img = None + if 'structure_table' in args.server_url: + to_excel(res['html'], './{}.xlsx'.format(img_name)) + elif 'structure_system' in args.server_url: + save_structure_res(res['regions'], args.output, image_file) + else: + draw_img = draw_server_result(image_file, res) + if draw_img is not None: + if not os.path.exists(args.output): + os.makedirs(args.output) + cv2.imwrite( + os.path.join(args.output, os.path.basename(image_file)), + draw_img[:, :, ::-1]) + logger.info("The visualized image saved in {}".format( + os.path.join(args.output, os.path.basename(image_file)))) + cnt += 1 + if cnt % 100 == 0: + logger.info("{} processed".format(cnt)) + logger.info("avg time cost: {}".format(float(total_time) / cnt)) + + +def parse_args(): + import argparse + parser = argparse.ArgumentParser(description="args for hub serving") + parser.add_argument("--server_url", type=str, required=True) + parser.add_argument("--image_dir", type=str, required=True) + parser.add_argument("--visualize", type=str2bool, default=False) + parser.add_argument("--output", type=str, default='./hubserving_result') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = parse_args() + main(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/train.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/train.py new file mode 100755 index 0000000000000000000000000000000000000000..d0f200189e34265b3c080ac9e25eb80d29c705b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/tools/train.py @@ -0,0 +1,203 @@ +# 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. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import os +import sys + +__dir__ = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(__dir__) +sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..'))) + +import yaml +import paddle +import paddle.distributed as dist + +from ppocr.data import build_dataloader +from ppocr.modeling.architectures import build_model +from ppocr.losses import build_loss +from ppocr.optimizer import build_optimizer +from ppocr.postprocess import build_post_process +from ppocr.metrics import build_metric +from ppocr.utils.save_load import load_model +from ppocr.utils.utility import set_seed +from ppocr.modeling.architectures import apply_to_static +import tools.program as program + +dist.get_world_size() + + +def main(config, device, logger, vdl_writer): + # init dist environment + if config['Global']['distributed']: + dist.init_parallel_env() + + global_config = config['Global'] + + # build dataloader + train_dataloader = build_dataloader(config, 'Train', device, logger) + if len(train_dataloader) == 0: + logger.error( + "No Images in train dataset, please ensure\n" + + "\t1. The images num in the train label_file_list should be larger than or equal with batch size.\n" + + + "\t2. The annotation file and path in the configuration file are provided normally." + ) + return + + if config['Eval']: + valid_dataloader = build_dataloader(config, 'Eval', device, logger) + else: + valid_dataloader = None + + # build post process + post_process_class = build_post_process(config['PostProcess'], + global_config) + + # build model + # for rec algorithm + if hasattr(post_process_class, 'character'): + char_num = len(getattr(post_process_class, 'character')) + if config['Architecture']["algorithm"] in ["Distillation", + ]: # distillation model + for key in config['Architecture']["Models"]: + if config['Architecture']['Models'][key]['Head'][ + 'name'] == 'MultiHead': # for multi head + if config['PostProcess'][ + 'name'] == 'DistillationSARLabelDecode': + char_num = char_num - 2 + # update SARLoss params + assert list(config['Loss']['loss_config_list'][-1].keys())[ + 0] == 'DistillationSARLoss' + config['Loss']['loss_config_list'][-1][ + 'DistillationSARLoss']['ignore_index'] = char_num + 1 + out_channels_list = {} + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Models'][key]['Head'][ + 'out_channels_list'] = out_channels_list + else: + config['Architecture']["Models"][key]["Head"][ + 'out_channels'] = char_num + elif config['Architecture']['Head'][ + 'name'] == 'MultiHead': # for multi head + if config['PostProcess']['name'] == 'SARLabelDecode': + char_num = char_num - 2 + # update SARLoss params + assert list(config['Loss']['loss_config_list'][1].keys())[ + 0] == 'SARLoss' + if config['Loss']['loss_config_list'][1]['SARLoss'] is None: + config['Loss']['loss_config_list'][1]['SARLoss'] = { + 'ignore_index': char_num + 1 + } + else: + config['Loss']['loss_config_list'][1]['SARLoss'][ + 'ignore_index'] = char_num + 1 + out_channels_list = {} + out_channels_list['CTCLabelDecode'] = char_num + out_channels_list['SARLabelDecode'] = char_num + 2 + config['Architecture']['Head'][ + 'out_channels_list'] = out_channels_list + else: # base rec model + config['Architecture']["Head"]['out_channels'] = char_num + + if config['PostProcess']['name'] == 'SARLabelDecode': # for SAR model + config['Loss']['ignore_index'] = char_num - 1 + + model = build_model(config['Architecture']) + use_sync_bn = config["Global"].get("use_sync_bn", False) + if use_sync_bn: + model = paddle.nn.SyncBatchNorm.convert_sync_batchnorm(model) + logger.info('convert_sync_batchnorm') + + model = apply_to_static(model, config, logger) + + # build loss + loss_class = build_loss(config['Loss']) + + # build optim + optimizer, lr_scheduler = build_optimizer( + config['Optimizer'], + epochs=config['Global']['epoch_num'], + step_each_epoch=len(train_dataloader), + model=model) + + # build metric + eval_class = build_metric(config['Metric']) + + logger.info('train dataloader has {} iters'.format(len(train_dataloader))) + if valid_dataloader is not None: + logger.info('valid dataloader has {} iters'.format( + len(valid_dataloader))) + + use_amp = config["Global"].get("use_amp", False) + amp_level = config["Global"].get("amp_level", 'O2') + amp_custom_black_list = config['Global'].get('amp_custom_black_list',[]) + if use_amp: + AMP_RELATED_FLAGS_SETTING = { + 'FLAGS_cudnn_batchnorm_spatial_persistent': 1, + 'FLAGS_max_inplace_grad_add': 8, + } + paddle.fluid.set_flags(AMP_RELATED_FLAGS_SETTING) + scale_loss = config["Global"].get("scale_loss", 1.0) + use_dynamic_loss_scaling = config["Global"].get( + "use_dynamic_loss_scaling", False) + scaler = paddle.amp.GradScaler( + init_loss_scaling=scale_loss, + use_dynamic_loss_scaling=use_dynamic_loss_scaling) + if amp_level == "O2": + model, optimizer = paddle.amp.decorate( + models=model, optimizers=optimizer, level=amp_level, master_weight=True) + else: + scaler = None + + # load pretrain model + pre_best_model_dict = load_model(config, model, optimizer, + config['Architecture']["model_type"]) + + if config['Global']['distributed']: + model = paddle.DataParallel(model) + # start train + program.train(config, train_dataloader, valid_dataloader, device, model, + loss_class, optimizer, lr_scheduler, post_process_class, + eval_class, pre_best_model_dict, logger, vdl_writer, scaler,amp_level, amp_custom_black_list) + + +def test_reader(config, device, logger): + loader = build_dataloader(config, 'Train', device, logger) + import time + starttime = time.time() + count = 0 + try: + for data in loader(): + count += 1 + if count % 1 == 0: + batch_time = time.time() - starttime + starttime = time.time() + logger.info("reader: {}, {}, {}".format( + count, len(data[0]), batch_time)) + except Exception as e: + logger.info(e) + logger.info("finish reader: {}, Success!".format(count)) + + +if __name__ == '__main__': + config, device, logger, vdl_writer = program.preprocess(is_train=True) + seed = config['Global']['seed'] if 'seed' in config['Global'] else 1024 + set_seed(seed) + main(config, device, logger, vdl_writer) + # test_reader(config, device, logger) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/test/12.jpg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/test/12.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7fc6f6befb60266160fdaa5d6cdb96d6911b3928 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/test/12.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c495c9e6bc6621522e9864bf6eaf602f11162fe5c711a1786c9ab1637203a414 +size 1406394 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4317eb58927ce4fea743c0b874ebf7c33c0312e5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15ff363a3a02f4103676c59fba036ade251b6cb3978c5511e93cc0c79cb3e219 +size 1915949 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/keys.txt b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/keys.txt new file mode 100644 index 0000000000000000000000000000000000000000..8d0326af0dd398ae623fb09d60116013d00721b1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/keys.txt @@ -0,0 +1,3015 @@ +1 +2 +4 +第 +一 +篇 +内 +科 +护 +理 +学 +常 +放 +射 +至 +左 +肩 +、 +臂 +侧 +达 +环 +指 +和 +小 +, +或 +咽 +颈 +背 +下 +颌 +部 +等 +。 +( +) +持 +续 +时 +间 +缓 +解 +方 +式 +: +疼 +痛 +3 +~ +5 +分 +钟 +很 +少 +超 +过 +休 +息 +舌 +含 +服 +硝 +酸 +甘 +油 +. +体 +征 +平 +般 +无 +异 +心 +绞 +发 +作 +表 +现 +血 +压 +升 +高 +率 +增 +快 +面 +色 +苍 +白 +情 +焦 +虑 +皮 +肤 +冷 +出 +汗 +有 +尖 +可 +四 +音 +暂 +性 +收 +缩 +期 +杂 +临 +床 +型 +稳 +定 +由 +于 +力 +活 +动 +其 +他 +加 +肌 +需 +氧 +量 +的 +因 +素 +诱 +在 +个 +月 +次 +数 +程 +度 +大 +致 +相 +同 +不 +目 +前 +上 +将 +劳 +以 +外 +缺 +胸 +统 +称 +为 +严 +重 +级 +根 +据 +拿 +管 +会 +I +受 +限 +制 +仅 +强 +长 +生 +Ⅱ +轻 +步 +走 +登 +楼 +梯 +饱 +餐 +后 +寒 +精 +神 +应 +激 +Ⅲ +明 +显 +行 +0 +m +层 +即 +Ⅳ +切 +均 +能 +引 +起 +适 +静 +也 +三 +辅 +助 +检 +查 +电 +图 +约 +半 +病 +人 +正 +陈 +旧 +梗 +死 +改 +变 +亦 +非 +特 +S +T +段 +波 +低 +倒 +置 +偶 +见 +抬 +运 +负 +荷 +试 +验 +态 +及 +连 +监 +测 +提 +已 +规 +项 +冠 +状 +脉 +造 +影 +选 +择 +使 +右 +主 +要 +支 +得 +到 +清 +楚 +各 +狭 +窄 +位 +并 +估 +计 +认 +腔 +直 +径 +减 +7 +% +响 +供 +具 +意 +义 +本 +确 +诊 +价 +值 +对 +治 +疗 +案 +判 +断 +预 +极 +成 +手 +阳 +中 +典 +≥ +V +核 +铊 +像 +所 +示 +灌 +注 +损 +流 +足 +消 +失 +区 +域 +如 +兼 +则 +; +- +9 +池 +室 +壁 +局 +障 +碍 +子 +除 +况 +还 +了 +代 +谢 +通 +与 +匹 +配 +析 +准 +评 +原 +两 +标 +急 +防 +再 +从 +而 +降 +立 +停 +止 +症 +药 +物 +较 +用 +效 +酯 +剂 +这 +类 +扩 +张 +循 +周 +围 +回 +容 +排 +脏 +耗 +① +片 +6 +g +研 +究 +证 +反 +复 +产 +耐 +又 +恢 +② +山 +梨 +每 +维 +喷 +雾 +吸 +入 +烦 +躁 +安 +剧 +烈 +者 +镇 +考 +吗 +啡 +十 +五 +章 +疾 +术 +信 +③ +带 +参 +观 +熟 +悉 +境 +仪 +呼 +机 +设 +备 +声 +便 +④ +导 +家 +属 +尽 +帮 +来 +自 +控 +感 +染 +口 +黏 +膜 +道 +是 +炎 +潜 +戒 +烟 +冬 +季 +保 +暖 +冒 +卫 +避 +免 +破 +积 +灶 +饮 +食 +营 +养 +鼓 +励 +进 +够 +热 +丰 +富 +脂 +胆 +固 +醇 +功 +欠 +佳 +钠 +盐 +摄 +经 +补 +充 +液 +源 +恶 +质 +给 +予 +蛋 +新 +鲜 +浆 +全 +纠 +贫 +瘤 +卧 +密 +察 +遵 +医 +嘱 +天 +抗 +凝 +洋 +地 +黄 +奎 +尼 +丁 +利 +尿 +氯 +化 +钾 +毒 +律 +伴 +糖 +采 +取 +措 +施 +绀 +先 +腹 +泻 +脱 +水 +警 +惕 +晕 +厥 +头 +颅 +伤 +脑 +易 +做 +好 +殊 +志 +种 +报 +告 +合 +处 +渗 +拔 +穿 +刺 +按 +沙 +袋 +迫 +肢 +栓 +形 +包 +括 +几 +系 +比 +袖 +接 +更 +且 +舒 +桡 +插 +宜 +k +P +a +H + +8 +/ +结 +识 +末 +梢 +格 +执 +菌 +操 +调 +零 +点 +空 +气 +肿 +胀 +落 +远 +端 +颜 +温 +⑤ +记 +录 +命 +房 +肺 +嵌 +客 +依 +畅 +折 +咳 +嗽 +呕 +吐 +抽 +搐 +⑥ +℃ +逐 +渐 +撤 +跳 +若 +多 +肽 +冰 +枕 +敷 +酒 +擦 +浴 +知 +阿 +司 +林 +l +留 +肠 +露 +湿 +搏 +唇 +甲 +毛 +细 +盈 +趾 +红 +润 +说 +组 +织 +良 +论 +央 +旦 +协 +寻 +找 +早 +善 +阻 +促 +儿 +A +i +r +w +y +B +e +t +h +n +建 +D +d +f +b +o +u +s +颤 +苏 +] +阶 +技 +抢 +救 +继 +器 +官 +衰 +竭 +《 +美 +国 +C +R +E +南 +》 +议 +童 +婴 +基 +础 +开 +工 +幅 +c +弹 +频 +“ +” +骤 +果 +单 +首 +双 +打 +法 +掌 +骨 +乳 +线 +抱 +拇 +深 +廓 +额 +举 +颏 +去 +泌 +患 +向 +仰 +淹 +溺 +迅 +速 +转 +俯 +托 +胃 +腰 +吹 +塞 +泡 +鼻 +牙 +关 +紧 +闭 +幼 +未 +必 +须 +初 +始 +J +但 +肘 +此 +粗 +路 +短 +挥 +稀 +释 +只 +才 +剑 +突 +针 +肾 +腺 +卡 +尚 +品 +丙 +溴 +苄 +铵 +扪 +肱 +股 +> +听 +窦 +瞳 +孔 +最 +述 +当 +绝 +弃 +昏 +迷 +任 +何 +散 +干 +完 +逆 +害 +故 +纯 +浓 +简 +院 +肛 +门 +洁 +镜 +肉 +摘 +渣 +粪 +隐 +喂 +姿 +势 +母 +亲 +身 +松 +弛 +汁 +坐 +怀 +哺 +弯 +住 +堵 +另 +别 +整 +吮 +吞 +奶 +呛 +溢 +夹 +旁 +剪 +刀 +吃 +靠 +拍 +然 +倡 +慢 +传 +肝 +否 +夜 +延 +聚 +之 +添 +膳 +睡 +眠 +泄 +软 +余 +凹 +陷 +摩 +瓶 +皲 +裂 +洗 +净 +暴 +燥 +涂 +羊 +罩 +仍 +渡 +元 +随 +着 +满 +育 +世 +界 +岁 +离 +二 +牛 +混 +授 +实 +承 +担 +替 +马 +酪 +块 +埃 +希 +肪 +颗 +粒 +乏 +酶 +亚 +麻 +矿 +尤 +磷 +氨 +钙 +β +某 +些 +敏 +疫 +脊 +透 +呈 +玻 +璃 +样 +蜘 +蛛 +网 +薄 +胞 +总 +× +° +L +培 +X +阴 +联 +屏 +N ++ +F +Z +M +巩 +抑 +粘 +泼 +溶 +疑 +疝 +惊 +光 +集 +齿 +垫 +咬 +坠 +跌 +兴 +奋 +椎 +喉 +衣 +领 +疮 +换 +布 +臀 +耳 +残 +瘫 +痪 +翻 +眼 +膏 +纱 +覆 +盖 +角 +日 +衡 +饲 +蔼 +贴 +柔 +务 +克 +健 +康 +教 +思 +想 +坚 +副 +户 +触 +遗 +被 +锻 +炼 +挛 +语 +智 +言 +训 +练 +女 +殖 +输 +卵 +巢 +囊 +宫 +缔 +厚 +穹 +窿 +紊 +乱 +碱 +妇 +盆 +求 +脓 +剖 +探 +瘀 +边 +隔 +争 +恐 +惧 +绪 +战 +拒 +讲 +冲 +裤 +棉 +孕 +褥 +宣 +播 +彻 +底 +弱 +迁 +抵 +胎 +盘 +雌 +伞 +锁 +峡 +纤 +节 +滑 +似 +腊 +互 +贯 +蔓 +骶 +韧 +硬 +疲 +七 +愉 +畸 +介 +绍 +习 +惯 +肥 +胖 +蓄 +范 +石 +风 +猝 +淀 +粉 +创 +年 +龄 +青 +春 +腿 +堆 +甚 +亡 +综 +匀 +紫 +条 +纹 +鉴 +男 +茎 +匿 +误 +往 +怕 +讥 +笑 +愿 +交 +卑 +怯 +孤 +独 +胰 +岛 +污 +游 +【 +】 +阑 +尾 +膀 +胱 +里 +困 +难 +膨 +史 +既 +溃 +疡 +近 +鸣 +移 +浊 +社 +危 +苦 +友 +济 +醉 +愈 +慰 +勇 +敢 +胜 +膈 +躯 +禁 +算 +概 +累 +就 +晨 +僵 +疹 +没 +灵 +萎 +腓 +斑 +狼 +蝶 +糜 +烂 +睑 +眶 +演 +泽 +丧 +械 +虽 +板 +件 +允 +许 +挤 +推 +荐 +击 +顺 +滴 +碳 +氢 +永 +久 +植 +腋 +沟 +戴 +帽 +冻 +呋 +米 +晚 +待 +威 +胁 +专 +痰 +⑦ +⑧ +妊 +娠 +蒂 +扭 +割 +著 +癌 +叩 +阵 +疸 +展 +坏 +列 +谱 +忧 +望 +牵 +涉 +灭 +念 +杀 +媒 +微 +繁 +芽 +孢 +真 +肮 +疽 +构 +蒸 +汽 +浸 +政 +批 +符 +事 +辐 +乙 +烷 +醛 +戊 +枝 +杆 +邻 +苯 +臭 +碘 +酊 +伏 +己 +酚 +假 +丝 +酵 +p +存 +奇 +痒 +宁 +豆 +附 +剥 +抓 +痕 +悬 +< +广 +霉 +唑 +咪 +氟 +顿 +忌 +搔 +煮 +沸 +烫 +娩 +鹅 +例 +侣 +退 +侵 +淡 +味 +浅 +瘙 +灼 +公 +共 +览 +序 +号 +象 +居 +民 +档 +辖 +籍 +资 +料 +栏 +众 +咨 +询 +办 +座 +群 +庭 +访 +视 +老 +筛 +督 +辨 +险 +校 += +该 +汇 +馈 +趋 +绘 +写 +送 +委 +员 +讨 +途 +夺 +秒 +握 +罹 +历 +场 +订 +县 +府 +照 +描 +扎 +索 +封 +睾 +淤 +丸 +吻 +顾 +八 +厌 +削 +歧 +链 +球 +蜡 +蒙 +蠕 +斯 +嗪 +稠 +粥 +蔬 +菜 +鱼 +决 +偿 +赶 +O +勺 +稍 +杯 +让 +囟 +窝 +葡 +萄 +六 +差 +Y +苷 +潴 +迟 +饥 +饿 +峰 +欲 +巨 +败 +K +樟 +丘 +叫 +弓 +嗜 +痉 +徐 +聋 +釉 +枢 +愤 +怒 +妥 +郁 +疏 +辛 +辣 +香 +胡 +椒 +葱 +蒜 +韭 +鸡 +普 +鲁 +龈 +终 +恼 +努 +陪 +幸 +福 +享 +憾 +获 +乐 +趣 +尊 +九 +剩 +熏 +职 +业 +我 +癜 +束 +噬 +寿 +占 +碰 +撞 +痊 +髓 +龙 +· +胶 +海 +绵 +填 +玩 +锐 +络 +修 +士 +文 +都 +Ⅰ +审 +省 +市 +火 +优 +贡 +献 +琳 +珀 +秀 +杰 +德 +伦 +哲 +忆 +践 +际 +诸 +金 +字 +塔 +拢 +腕 +震 +倾 +屈 +曲 +肋 +潮 +略 +笛 +划 +娱 +尘 +脸 +勉 +们 +扰 +沮 +树 +猫 +狗 +鸟 +宠 +悲 +拮 +哌 +滞 +茶 +胺 +铬 +齐 +晶 +拉 +勿 +凉 +窒 +畴 +益 +沉 +把 +G +P +Q +宽 +振 +喊 +摸 +拨 +伸 +垂 +捏 +v +忽 +映 +贮 +弥 +z +寄 +虫 +灰 +觉 +费 +哮 +喘 +泛 +咯 +壮 +勤 +叉 +详 +凡 +钳 +幕 +撕 +惹 +漠 +斜 +隆 +越 +皱 +醒 +哭 +逗 +东 +西 +弄 +脚 +陌 +遮 +挡 +喜 +憎 +模 +仿 +名 +爱 +妒 +看 +画 +令 +戏 +守 +瘢 +氮 +废 +酐 +痹 +倍 +滤 +矢 +拥 +跃 +钝 +糊 +廉 +扫 +磁 +晰 +巴 +英 +顽 +泮 +迎 +宾 +诞 +孩 +褐 +氏 +蓝 +份 +黑 +耻 +酮 +椭 +圆 +叶 +■ +脐 +觅 +御 +键 +羞 +愧 +惑 +扬 +惩 +罚 +疚 +赞 +俗 +什 +么 +纪 +秩 +书 +龋 +虚 +遭 +妨 +盂 +髂 +盲 +颇 +髋 +融 +缘 +岬 +棘 +翼 +横 +距 +纵 +屑 +褶 +咀 +嚼 +笔 +胚 +锥 +截 +问 +硫 +镁 +酰 +骼 +痫 +膝 +腱 +暗 +麦 +诉 +渴 +幻 +瘘 +烧 +丢 +木 +站 +浪 +权 +责 +策 +题 +拟 +团 +挑 +恰 +归 +纳 +递 +诺 +漏 +刻 +闷 +U +芯 +筒 +朝 +借 +签 +饭 +擅 +仔 +歇 +套 +启 +踝 +髁 +偏 +尺 +鹰 +嘴 +沿 +枪 +旋 +碎 +螺 +钉 +钢 +拆 +缝 +烤 +灯 +迹 +唯 +铺 +婚 +私 +氛 +丛 +淋 +鞘 +铁 +曾 +唐 +族 +猛 +悦 +挽 +洞 +瓣 +³ +装 +糙 +胛 +∶ +扣 +癫 +师 +请 +x +漓 +隙 +逸 +缚 +滋 +蕈 +啰 +狂 +谵 +妄 +眩 +洒 +农 +皂 +煤 +窑 +炉 +睛 +涩 +芫 +荽 +煎 +抹 +汤 +泪 +痂 +硼 +砂 +漱 +曝 +晒 +苗 +痘 +疱 +宿 +醚 +飞 +沫 +遍 +携 +泵 +悸 +樱 +桃 +痴 +呆 +舱 +杉 +铂 +嘧 +啶 +澈 +脆 +浑 +W +抉 +宏 +伟 +赋 +它 +答 +署 +纲 +霜 +铝 +亢 +痿 +扶 +绕 +酌 +返 +星 +倦 +怠 +追 +踪 +鼠 +霍 +艾 +禽 +犬 +革 +炭 +痢 +百 +猩 +梅 +钩 +疟 +腮 +版 +岗 +畜 +宰 +挂 +蚊 +帐 +驱 +柯 +酗 +卒 +迂 +盗 +矇 +野 +摇 +晃 +秘 +盛 +锰 +巡 +圈 +却 +逼 +嚏 +脾 +甾 +雄 +襞 +亮 +缬 +赖 +谷 +C +储 +锌 +铜 +硒 +琐 +嵴 +车 +轮 +碾 +轧 +腘 +贬 +商 +吖 +橡 +巾 +镊 +叠 +花 +遂 +遇 +筹 +闹 +懂 +贝 +坦 +洛 +尔 +α +莫 +噻 +袢 +塑 +那 +哚 +慎 +兰 +腌 +罐 +啤 +架 +腐 +蚀 +幽 +唾 +渍 +炸 +北 +京 +台 +掉 +箱 +姻 +载 +父 +夫 +赘 +桥 +鼾 +咖 +搬 +蚯 +蚓 +投 +忘 +读 +缄 +默 +偷 +窃 +穷 +嫉 +茨 +敌 +攻 +奈 +刚 +词 +句 +婉 +话 +劝 +绒 +拭 +裸 +催 +姓 +印 +燕 +谨 +喝 +沾 +雷 +藤 +浦 +肯 +憋 +聘 +财 +竞 +仁 +班 +株 +瘪 +衍 +炔 +醋 +羟 +伍 +⑨ +犹 +杏 +蜂 +蛇 +河 +豚 +癞 +蛤 +蟆 +闻 +M +涎 +涕 +氰 +袭 +腥 +夏 +饵 +绿 +j +旨 +址 +债 +瞻 +巧 +赤 +酱 +靡 +荚 +秋 +腭 +窘 +呻 +吟 +扇 +桑 +恒 +≤ +搭 +草 +古 +² +捷 +芥 +斥 +罕 +酷 +凶 +阙 +涤 +漂 +材 +絮 +垢 +锈 +毁 +卸 +摆 +篮 +筐 +碗 +皿 +轴 +摞 +纸 +槽 +纺 +编 +溯 +柜 +墙 +勒 +袜 +绷 +太 +逻 +辑 +云 +错 +叙 +矛 +盾 +违 +拗 +荒 +谬 +僻 +旺 +顶 +蹬 +B +衔 +她 +撑 +缠 +卷 +邓 +揉 +捧 +闪 +抚 +恋 +唤 +欢 +踢 +跑 +逃 +— +乎 +谈 +悄 +泣 +耽 +掩 +慌 +耍 +跟 +舞 +蹈 +矫 +鞣 +荨 +烹 +阈 +怖 +腻 +蛔 +钻 +栖 +溅 +拖 +队 +拐 +杖 +椅 +奠 +荧 +嘌 +呤 +姐 +妹 +枯 +稚 +癖 +绩 +瘦 +爽 +襟 +寸 +哀 +雏 +柱 +毳 +眉 +睫 +啼 +扑 +彩 +柏 +扁 +肃 +今 +付 +扼 +慧 +恪 +魄 +迭 +脒 +昔 +韦 +滥 +礼 +泳 +桶 +叮 +景 +毕 +盒 +诫 +忠 +诚 +伙 +刮 +店 +搓 +灸 +烘 +窗 +筋 +衬 +Q +烁 +濒 +浮 +楔 +谅 +矮 +祖 +乃 +漫 +哪 +T +畏 +靶 +* +U +库 +恍 +惚 +磺 +烯 +遥 +祛 +踏 +拳 +阅 +军 +佝 +偻 +涌 +泉 +穴 +撬 +咐 +枸 +橼 +铋 +潘 +啉 +瑞 +博 +饪 +俱 +阐 +沐 +焚 +镍 +锡 +砷 +鳞 +牢 +瓜 +枣 +菇 +罗 +帕 +蜕 +瘾 +椹 +欣 +鞍 +硅 +兜 +蹲 +候 +盏 +厂 +井 +暑 +勃 +剃 +骑 +澡 +汞 +桌 +筷 +陡 +刷 +挖 +摔 +泊 +裹 +召 +谊 +珍 +惜 +壶 +棕 +挫 +芬 +宗 +嗅 +炖 +煨 +泥 +羹 +午 +傍 +园 +奔 +藏 +毫 +[ +亿 +巯 +侏 +儒 +夭 +骺 +庚 +粟 +喹 +肟 +售 +沛 +蝼 +课 +堂 +拓 +泔 +钮 +晾 +拾 +翔 +… +犯 +萘 +萨 +昆 +飘 +劣 +燃 +肼 +杨 +万 +杠 +兆 +贲 +华 +嘈 +艺 +懒 +钡 +芳 +泰 +斗 +土 +壤 +城 +乡 +蚴 +壳 +窜 +村 +磨 +颁 +贻 +履 +纷 +吩 +甜 +瞬 +敲 +萌 +昨 +臻 +弧 +匍 +匐 +爬 +绳 +匙 +页 +Ⅵ +Ⅶ +Ⅷ +Ⅸ +Ⅴ +颞 +呃 +塌 +崩 +孟 +琥 +千 +鞋 +檗 +噁 +腾 +龛 +厘 +凸 +澄 +铃 +薯 +莨 +菪 +馏 +哈 +嘶 +哑 +钱 +票 +搅 +拌 +销 +掀 +憩 +街 +嘲 +脲 +框 +孪 +兄 +弟 +烛 +焰 +昂 +贵 +棒 +跖 +跛 +胫 +妻 +梦 +企 +誉 +q +购 +买 +轨 +蜷 +谓 +笼 +谋 +吲 +赢 +妆 +芹 +蘑 +挠 +伯 +荣 +弗 +赫 +兹 +晋 +揩 +蘸 +纽 +昼 +饼 +馒 +吊 +艳 +唱 +歌 +滚 +迈 +躲 +咿 +呀 +爸 +妈 +哥 +尴 +尬 +谦 +聆 +拘 +⑩ +奏 +A +涵 +孙 +彼 +谐 +杵 +粮 +祸 +柄 +川 +崎 +稽 +梭 +贺 +吠 +瞪 +搞 +赡 +噪 +爆 +蝇 +蟑 +螂 +武 +蕉 +庆 +橙 +奥 +戈 +惰 +卢 +尸 +痣 +墩 +丹 +蔽 +串 +珠 +匮 +陆 +跨 +钼 +惫 +逝 +邀 +蛲 +杜 +裆 +揭 +酬 +姆 +奖 +慑 +兑 +凭 +赏 +吡 +迄 +毗 +毯 +浇 +徒 +援 +姑 +佩 +辰 +梳 +垛 +哽 +噎 +扯 +挺 +哨 +熄 +螨 +虾 +蟹 +痔 +埋 +? +绎 +苹 +娃 +洽 +厉 +骂 +骄 +傲 +谎 +吧 +啪 +Ⅺ +Ⅹ +拽 +舍 +颠 +茄 +芸 +竖 +疖 +苔 +疣 +恳 +伊 +荡 +尝 +亨 +荤 +厕 +崔 +契 +忙 +娇 +嫩 +捆 +绑 +蜇 +羧 +抖 +臼 +册 +叹 +靴 +喃 +趴 +刹 +貌 +饰 +竟 +你 +哦 +舆 +仑 +戳 +豁 +熬 +咸 +崇 +拜 +羡 +慕 +掘 +拧 +忍 +抒 +擤 +芦 +猪 +颊 +磅 +秤 +屋 +鞭 +渠 +牌 +梁 +玉 +虹 +拄 +驼 +稿 +薪 +码 +译 +朋 +嗳 +阜 +沥 +佐 +银 +丈 +' +玫 +瑰 +垃 +圾 +旅 +赛 +橘 +铠 +陵 +脘 +锋 +胍 +芒 +棋 +锝 +骡 +柴 +钎 +锤 +嫌 +剔 +颧 +吼 +睁 +痈 +乘 +柳 +汉 +陶 +唠 +叨 +踞 +郭 +烬 +兽 +舔 +蚁 +番 +徙 +靛 +胭 +萝 +卜 +堪 +D +蝴 +瓦 +朵 +刃 +捻 +雨 +淆 +碟 +摁 +庄 +雅 +慷 +慨 +妙 +歉 +吉 +瑟 +砸 +掷 +榴 +搦 +蜜 +羽 +漩 +涡 +汀 +酞 +伪 +罪 +枷 +喧 +哗 +凌 +僚 +菱 +舟 +闸 +敞 +潺 +抠 +坡 +呶 +耸 +豌 +麸 +雪 +疳 +扮 +辈 +李 +捣 +挣 +欧 +黛 +晓 +辟 +筑 +艰 +鲍 +曼 +窥 +辞 +派 +岭 +菠 +笋 +榨 +寝 +扔 +捡 +攀 +蹦 +谣 +敬 +卖 +淫 +嫖 +娼 +港 +帆 +箭 +洲 +桂 +痤 +韵 +抄 +湛 +忱 +禾 +蚕 +鸽 +愚 +笨 +眦 +佛 +― +铅 +翌 +朗 +津 +朦 +胧 +髌 +雍 +猿 +喇 +叭 +螳 +踩 +芋 +蹄 +莲 +藕 +宝 +谁 +睹 +阂 +敛 +姬 +恙 +蚤 +搜 +涨 +猕 +猴 +芝 +仲 +裁 +睬 +踱 +怎 +磋 +祈 +倚 +灾 +钴 +阔 +旬 +姊 +焉 +拙 +呵 +莱 +搁 +γ +菊 +蓟 +仙 +睿 +宅 +馅 +歪 +毅 +冶 +榜 +堕 +殴 +漆 +菲 +驻 +詹 +卓 +聂 +弊 +¥ +簇 +蔗 +爪 +→ +喙 +牡 +蛎 +蚶 +宋 +镉 +捕 +狐 +兔 +蛙 +驶 +森 +癔 +俣 +墨 +躺 +琼 +缢 +吓 +掏 +竹 +恩 +讶 +跪 +凳 +君 +臣 +江 +堰 +兵 +圣 +豫 +铲 +肚 +& +奉 +辏 +屯 +± +捂 +虐 +蹒 +跚 +慈 +聪 +牺 +牲 +税 +渥 +盟 +驾 +瞒 +讳 +镰 +糠 +搪 +瓷 +怨 +怪 +恨 +乞 +寡 +噩 +馆 +眺 +漾 +啊 +呜 +屉 +招 +棍 +" +孝 +秃 +「 +簧 +衷 +蜿 +蜒 +伽 +壬 +鹿 +镯 +溏 +矽 +荠 +岩 +熊 +旷 +藻 +氩 +田 +讯 +刊 +鹤 +蓖 +镭 +锭 +邪 +腑 +辗 +铯 +鑫 +镶 +O +驮 +逊 +蹙 +咧 +乒 +乓 +郝 +熔 +寂 +庞 +唆 +骚 +蠢 +愁 +忡 +郊 +贪 +凯 +氡 +烃 +铀 +芘 +厅 +踊 +闲 +䓬 +癸 +氦 +氖 +槛 +绊 +曳 +伐 +吵 +厨 +逛 +贸 +皆 +睦 +掣 +隶 +踹 +喀 +鸦 +桐 +币 +R +挚 +萩 +襁 +褓 +炕 +湍 +纫 +颖 +悍 +遣 +倘 +苜 +蓿 +凋 +猜 +俩 +锦 +渊 +莪 +枚 +辱 +绌 +锯 +弦 +乌 +莓 +塘 \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/rec/test/1_crop_5.jpg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/rec/test/1_crop_5.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0fac6edacae7e349be4751ac54a0f60ee17840c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/rec/test/1_crop_5.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31a63e72c751f322f76b968d817cc1e531a8ea5e05fcb6456aaf1a719efaa662 +size 2998 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d81e3a0169c4b6d48f1991466c017e7de5ff284 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from __future__ import absolute_import + +import os + +from visualdl.writer.writer import LogWriter # noqa: F401 +from visualdl.reader.reader import LogReader # noqa: F401 +from visualdl.version import vdl_version as __version__ # noqa: F401 +from visualdl.utils.dir import init_vdl_config + +init_vdl_config() + +ROOT = os.path.dirname(__file__) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..591bb651ff541cf8a1668306ecadacc8b2af45e8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/__init__.py @@ -0,0 +1,47 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +components = { + "scalar": { + "enabled": False + }, + "image": { + "enabled": False + }, + "text": { + "enabled": False + }, + "embedding": { + "enabled": False + }, + "audio": { + "enabled": False + }, + "histogram": { + "enabled": False + }, + "graph": { + "enabled": False + }, + "pr_curve": { + "enabled": False + }, + "roc_curve": { + "enabled": False + }, + "meta_data": { + "enabled": False + } +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/base_component.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/base_component.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f7de9bc0af36e69b1efe3bba0ffeac46371f7e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/base_component.py @@ -0,0 +1,617 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import numpy as np +from PIL import Image + +from visualdl.proto.record_pb2 import Record + + +def scalars(main_tag, tag_scalar_dict, step, walltime=None): + """Package data to scalars + + Args: + main_tag (string): Data identifier + tag_scalar_dict (dict): A dict to provide multi-values with tags + step (int): Step of scalar + walltime (int): Wall time of scalar + + Return: + Package with format of record_pb2.Record + """ + for sub_tag, value in tag_scalar_dict.items(): + value = float(value) + yield Record(values=[ + Record.Value( + id=step, + tag=main_tag, + timestamp=walltime, + tag_value=Record.TagValue(tag=sub_tag, value=value)) + ]) + + +def scalar(tag, value, step, walltime=None): + """Package data to one scalar. + Args: + tag (string): Data identifier + value (float): Value of scalar + step (int): Step of scalar + walltime (int): Wall time of scalar + + Return: + Package with format of record_pb2.Record + """ + value = float(value) + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, value=value) + ]) + + +def meta_data(tag='meta_data_tag', display_name="", step=0, walltime=None): + """Package data to one meta_data. + + Meta data is info for one record file, include `display_name` etc. + + Args: + tag (string): Data identifier + display_name (string): Replace + step (int): Step of scalar + walltime (int): Wall time of scalar + + Return: + Package with format of record_pb2.Record + """ + meta = Record.MetaData(display_name=display_name) + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, meta_data=meta) + ]) + + +def imgarray2bytes(np_array): + """Convert image ndarray to bytes. + + Args: + np_array (np.ndarray): Array to converte. + + Returns: + Binary bytes of np_array. + """ + try: + import cv2 + + np_array = cv2.cvtColor(np_array, cv2.COLOR_BGR2RGB) + ret, buf = cv2.imencode(".png", np_array) + img_bin = Image.fromarray(np.uint8(buf)).tobytes("raw") + except ImportError: + import io + im = Image.fromarray(np_array) + with io.BytesIO() as fp: + im.save(fp, format='png') + img_bin = fp.getvalue() + return img_bin + + +def make_grid(I, ncols=8): # noqa: E741 + assert isinstance(I, + np.ndarray), 'plugin error, should pass numpy array here' + if I.shape[1] == 1: + I = np.concatenate([I, I, I], 1) # noqa: E741 + assert I.ndim == 4 and I.shape[1] == 3 or I.shape[1] == 4 + nimg = I.shape[0] + H = I.shape[2] + W = I.shape[3] + ncols = min(nimg, ncols) + nrows = int(np.ceil(float(nimg) / ncols)) + canvas = np.zeros((I.shape[1], H * nrows, W * ncols), dtype=I.dtype) + i = 0 + for y in range(nrows): + for x in range(ncols): + if i >= nimg: + break + canvas[:, y * H:(y + 1) * H, x * W:(x + 1) * W] = I[i] + i = i + 1 + return canvas + + +def convert_to_HWC(tensor, input_format): + """Convert `NCHW`, `HWC`, `HW` to `HWC` + + Args: + tensor (np.ndarray): Value of image + input_format (string): Format of image + + Return: + Image of format `HWC`. + """ + assert (len(set(input_format)) == len(input_format) + ), "You can not use the same dimension shordhand twice. \ + input_format: {}".format(input_format) + assert (len(tensor.shape) == len(input_format) + ), "size of input tensor and input format are different. \ + tensor shape: {}, input_format: {}".format(tensor.shape, input_format) + input_format = input_format.upper() + + if len(input_format) == 4: + index = [input_format.find(c) for c in 'NCHW'] + tensor_NCHW = tensor.transpose(index) + tensor_CHW = make_grid(tensor_NCHW) + return tensor_CHW.transpose(1, 2, 0) + + if len(input_format) == 3: + index = [input_format.find(c) for c in 'HWC'] + tensor_HWC = tensor.transpose(index) + if tensor_HWC.shape[2] == 1: + tensor_HWC = np.concatenate([tensor_HWC, tensor_HWC, tensor_HWC], + 2) + return tensor_HWC + + if len(input_format) == 2: + index = [input_format.find(c) for c in 'HW'] + tensor = tensor.transpose(index) + tensor = np.stack([tensor, tensor, tensor], 2) + return tensor + + +def denormalization(image_array): + """Renormalise ndarray matrix. + + Args: + image_array(np.ndarray): Value of image + + Return: + Matrix after renormalising. + """ + if image_array.max() <= 1 and image_array.min() >= 0: + image_array *= 255 + return image_array.astype(np.uint8) + + +def image(tag, image_array, step, walltime=None, dataformats="HWC"): + """Package data to one image. + + Args: + tag (string): Data identifier + image_array (np.ndarray): Value of image + step (int): Step of image + walltime (int): Wall time of image + dataformats (string): Format of image + + Return: + Package with format of record_pb2.Record + """ + image_array = denormalization(image_array) + image_array = convert_to_HWC(image_array, dataformats) + image_bytes = imgarray2bytes(image_array) + image = Record.Image(encoded_image_string=image_bytes) + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, image=image) + ]) + + +def embedding(tag, labels, hot_vectors, step, labels_meta=None, walltime=None): + """Package data to one embedding. + + Args: + tag (string): Data identifier + labels (list): A list of labels. + hot_vectors (np.array or list): A matrix which each row is + feature of labels. + step (int): Step of embeddings. + walltime (int): Wall time of embeddings. + + Return: + Package with format of record_pb2.Record + """ + embeddings = Record.Embeddings() + + if labels_meta: + embeddings.label_meta.extend(labels_meta) + + if isinstance(labels[0], list): + temp = [] + for index in range(len(labels[0])): + temp.append([label[index] for label in labels]) + labels = temp + for label, hot_vector in zip(labels, hot_vectors): + if not isinstance(label, list): + label = [label] + embeddings.embeddings.append( + Record.Embedding(label=label, vectors=hot_vector)) + + return Record(values=[ + Record.Value( + id=step, tag=tag, timestamp=walltime, embeddings=embeddings) + ]) + + +def audio(tag, audio_array, sample_rate, step, walltime): + """Package data to one audio. + + Args: + tag (string): Data identifier + audio_array (np.ndarray or list): audio represented by a np.array + sample_rate (int): Sample rate of audio + step (int): Step of audio + walltime (int): Wall time of audio + + Return: + Package with format of record_pb2.Record + """ + audio_array = audio_array.squeeze() + if abs(audio_array).max() > 1: + print('warning: audio amplitude out of range, auto clipped.') + audio_array = audio_array.clip(-1, 1) + assert (audio_array.ndim == 1), 'input tensor should be 1 dimensional.' + + audio_array = [int(32767.0 * x) for x in audio_array] + + import io + import wave + import struct + + fio = io.BytesIO() + wave_writer = wave.open(fio, 'wb') + wave_writer.setnchannels(1) + wave_writer.setsampwidth(2) + wave_writer.setframerate(sample_rate) + audio_enc = b'' + audio_enc += struct.pack("<" + "h" * len(audio_array), *audio_array) + wave_writer.writeframes(audio_enc) + wave_writer.close() + audio_string = fio.getvalue() + fio.close() + audio_data = Record.Audio( + sample_rate=sample_rate, + num_channels=1, + length_frames=len(audio_array), + encoded_audio_string=audio_string, + content_type='audio/wav') + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, audio=audio_data) + ]) + + +def text(tag, text_string, step, walltime=None): + """Package data to one image. + Args: + tag (string): Data identifier + text_string (string): Value of text + step (int): Step of text + walltime (int): Wall time of text + Return: + Package with format of record_pb2.Record + """ + _text = Record.Text(encoded_text_string=text_string) + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, text=_text) + ]) + + +def histogram(tag, hist, bin_edges, step, walltime): + """Package data to one histogram. + + Args: + tag (string): Data identifier + hist (np.ndarray or list): The values of the histogram + bin_edges (np.ndarray or list): The bin edges + step (int): Step of histogram + walltime (int): Wall time of histogram + + Return: + Package with format of record_pb2.Record + """ + histogram = Record.Histogram(hist=hist, bin_edges=bin_edges) + return Record(values=[ + Record.Value( + id=step, tag=tag, timestamp=walltime, histogram=histogram) + ]) + + +def hparam(name, hparam_dict, metric_list, walltime): + """Package data to one histogram. + + Args: + name (str): Name of hparam. + hparam_dict (dictionary): Each key-value pair in the dictionary is the + name of the hyper parameter and it's corresponding value. The type of the value + can be one of `bool`, `string`, `float`, `int`, or `None`. + metric_list (list): Name of all metrics. + walltime (int): Wall time of hparam. + + Return: + Package with format of record_pb2.Record + """ + + hm = Record.HParam() + hm.name = name + for k, v in hparam_dict.items(): + if v is None: + continue + hparamInfo = Record.HParam.HparamInfo() + hparamInfo.name = k + if isinstance(v, int): + hparamInfo.int_value = v + hm.hparamInfos.append(hparamInfo) + elif isinstance(v, float): + hparamInfo.float_value = v + hm.hparamInfos.append(hparamInfo) + elif isinstance(v, str): + hparamInfo.string_value = v + hm.hparamInfos.append(hparamInfo) + else: + print("The value of %s must be int, float or str, not %s" % + (k, str(type(v)))) + for metric in metric_list: + metricInfo = Record.HParam.HparamInfo() + metricInfo.name = metric + metricInfo.float_value = 0 + hm.metricInfos.append(metricInfo) + + return Record(values=[ + Record.Value(id=1, tag="hparam", timestamp=walltime, hparam=hm) + ]) + + +def compute_curve(labels, predictions, num_thresholds=None, weights=None): + """ Compute precision-recall curve data by labels and predictions. + + Args: + labels (np.ndarray or list): Binary labels for each element. + predictions (np.ndarray or list): The probability that an element be + classified as true. + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + """ + if isinstance(labels, list): + labels = np.array(labels) + if isinstance(predictions, list): + predictions = np.array(predictions) + _MINIMUM_COUNT = 1e-7 + + if weights is None: + weights = 1.0 + + bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1))) + float_labels = labels.astype(np.float) + histogram_range = (0, num_thresholds - 1) + tp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=float_labels * weights) + fp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=(1.0 - float_labels) * weights) + + # Obtain the reverse cumulative sum. + tp = np.cumsum(tp_buckets[::-1])[::-1] + fp = np.cumsum(fp_buckets[::-1])[::-1] + tn = fp[0] - fp + fn = tp[0] - tp + precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp) + recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn) + data = { + 'tp': tp.astype(int).tolist(), + 'fp': fp.astype(int).tolist(), + 'tn': tn.astype(int).tolist(), + 'fn': fn.astype(int).tolist(), + 'precision': precision.astype(float).tolist(), + 'recall': recall.astype(float).tolist() + } + return data + + +def pr_curve(tag, + labels, + predictions, + step, + walltime, + num_thresholds=127, + weights=None): + """Package data to one pr_curve. + + Args: + tag (string): Data identifier + labels (np.ndarray or list): Binary labels for each element. + predictions (np.ndarray or list): The probability that an element be + classified as true. + step (int): Step of pr_curve + walltime (int): Wall time of pr_curve + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + + Return: + Package with format of record_pb2.Record + """ + num_thresholds = min(num_thresholds, 127) + prcurve_map = compute_curve(labels, predictions, num_thresholds, weights) + + return pr_curve_raw( + tag=tag, + tp=prcurve_map['tp'], + fp=prcurve_map['fp'], + tn=prcurve_map['tn'], + fn=prcurve_map['fn'], + precision=prcurve_map['precision'], + recall=prcurve_map['recall'], + step=step, + walltime=walltime) + + +def pr_curve_raw(tag, tp, fp, tn, fn, precision, recall, step, walltime): + """Package raw data to one pr_curve. + + Args: + tag (string): Data identifier + tp (list): True Positive. + fp (list): False Positive. + tn (list): True Negative. + fn (list): False Negative. + precision (list): The fraction of retrieved documents that are relevant + to the query: + recall (list): The fraction of the relevant documents that are + successfully retrieved. + step (int): Step of pr_curve + walltime (int): Wall time of pr_curve + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + + Return: + Package with format of record_pb2.Record + """ + """ + if isinstance(tp, np.ndarray): + tp = tp.astype(int).tolist() + if isinstance(fp, np.ndarray): + fp = fp.astype(int).tolist() + if isinstance(tn, np.ndarray): + tn = tn.astype(int).tolist() + if isinstance(fn, np.ndarray): + fn = fn.astype(int).tolist() + if isinstance(precision, np.ndarray): + precision = precision.astype(int).tolist() + if isinstance(recall, np.ndarray): + recall = recall.astype(int).tolist() + """ + prcurve = Record.PRCurve( + TP=tp, FP=fp, TN=tn, FN=fn, precision=precision, recall=recall) + return Record(values=[ + Record.Value(id=step, tag=tag, timestamp=walltime, pr_curve=prcurve) + ]) + + +def compute_roc_curve(labels, predictions, num_thresholds=None, weights=None): + """ Compute ROC curve data by labels and predictions. + Args: + labels (numpy.ndarray or list): Binary labels for each element. + predictions (numpy.ndarray or list): The probability that an element be + classified as true. + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + """ + if isinstance(labels, list): + labels = np.array(labels) + if isinstance(predictions, list): + predictions = np.array(predictions) + _MINIMUM_COUNT = 1e-7 + + if weights is None: + weights = 1.0 + + bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1))) + float_labels = labels.astype(np.float) + histogram_range = (0, num_thresholds - 1) + tp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=float_labels * weights) + fp_buckets, _ = np.histogram( + bucket_indices, + bins=num_thresholds, + range=histogram_range, + weights=(1.0 - float_labels) * weights) + + # Obtain the reverse cumulative sum. + tp = np.cumsum(tp_buckets[::-1])[::-1] + fp = np.cumsum(fp_buckets[::-1])[::-1] + tn = fp[0] - fp + fn = tp[0] - tp + tpr = tp / np.maximum(_MINIMUM_COUNT, tn + fp) + fpr = fp / np.maximum(_MINIMUM_COUNT, tn + fp) + data = { + 'tp': tp.astype(int).tolist(), + 'fp': fp.astype(int).tolist(), + 'tn': tn.astype(int).tolist(), + 'fn': fn.astype(int).tolist(), + 'tpr': tpr.astype(float).tolist(), + 'fpr': fpr.astype(float).tolist() + } + return data + + +def roc_curve(tag, + labels, + predictions, + step, + walltime, + num_thresholds=127, + weights=None): + """Package data to one roc_curve. + Args: + tag (string): Data identifier + labels (numpy.ndarray or list): Binary labels for each element. + predictions (numpy.ndarray or list): The probability that an element be + classified as true. + step (int): Step of pr_curve + walltime (int): Wall time of pr_curve + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + Return: + Package with format of record_pb2.Record + """ + num_thresholds = min(num_thresholds, 127) + roc_curve_map = compute_roc_curve(labels, predictions, num_thresholds, + weights) + + return roc_curve_raw( + tag=tag, + tp=roc_curve_map['tp'], + fp=roc_curve_map['fp'], + tn=roc_curve_map['tn'], + fn=roc_curve_map['fn'], + tpr=roc_curve_map['tpr'], + fpr=roc_curve_map['fpr'], + step=step, + walltime=walltime) + + +def roc_curve_raw(tag, tp, fp, tn, fn, tpr, fpr, step, walltime): + """Package raw data to one roc_curve. + Args: + tag (string): Data identifier + tp (list): True Positive. + fp (list): False Positive. + tn (list): True Negative. + fn (list): False Negative. + tpr (list): true positive rate: + fpr (list): false positive rate. + step (int): Step of roc_curve + walltime (int): Wall time of roc_curve + num_thresholds (int): Number of thresholds used to draw the curve. + weights (float): Multiple of data to display on the curve. + Return: + Package with format of record_pb2.Record + """ + """ + if isinstance(tp, np.ndarray): + tp = tp.astype(int).tolist() + if isinstance(fp, np.ndarray): + fp = fp.astype(int).tolist() + if isinstance(tn, np.ndarray): + tn = tn.astype(int).tolist() + if isinstance(fn, np.ndarray): + fn = fn.astype(int).tolist() + if isinstance(tpr, np.ndarray): + tpr = tpr.astype(int).tolist() + if isinstance(fpr, np.ndarray): + fpr = fpr.astype(int).tolist() + """ + roc_curve = Record.ROC_Curve(TP=tp, FP=fp, TN=tn, FN=fn, tpr=tpr, fpr=fpr) + return Record(values=[ + Record.Value( + id=step, tag=tag, timestamp=walltime, roc_curve=roc_curve) + ]) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb89f7dc28021116195ccad1cc54e12e54c8a735 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from .exporter import translate_graph +from .graph_component import analyse_model +from .netron_graph import Model + +__all__ = ['translate_graph', 'analyse_model', 'Model'] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/exporter.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..541deed3775df9d272008ad4b588d9857d191630 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/exporter.py @@ -0,0 +1,36 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json +import os +import tempfile + +from .graph_component import analyse_model +from .utils import create_opname_scope +from .utils import print_model + + +def translate_graph(model, input_spec, verbose=True): + import paddle + with tempfile.TemporaryDirectory() as tmp: + model._full_name = '{}[{}]'.format(model.__class__.__name__, "model") + create_opname_scope(model) + model = paddle.jit.to_static(model, input_spec) + paddle.jit.save(model, os.path.join(tmp, 'temp')) + model_data = open(os.path.join(tmp, 'temp.pdmodel'), 'rb').read() + result = analyse_model(model_data) + if verbose: + print_model(result) + result = json.dumps(result, indent=2) + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/graph_component.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/graph_component.py new file mode 100644 index 0000000000000000000000000000000000000000..be71a12b361b6989841176ade5863c617e7291bf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/graph_component.py @@ -0,0 +1,363 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections +import os.path +import pathlib +import re + +_graph_version = '1.0.0' + + +def post_order_traverse(root, all_ops, post_order_results): + ''' + Traversal a tree in post order. + Args: + root: current node of the tree. + all_ops: used to index all nodes. + post_order_results(list): used to store traversal results in place. + ''' + for child in all_ops[root]['children_node']: + post_order_traverse(child, all_ops, post_order_results) + post_order_results.append(root) + return + + +def create_non_leaf_nodes(parent_node_name, child_node_name, all_ops, + general_children_dict): + ''' + Create a path from leaf to root, e.g. /a/b/c -> /a/b -> /a -> /. If node in path not exists, \ + create one and fill information. + Args: + parent_node_name: name of parent node + child_node_name: name of current node + all_ops: used to store and index all nodes. + general_children_dict: used to store all descendants for each non-leaf node. + ''' + if parent_node_name == '/' or parent_node_name == '': # root node + parent_node_name = '/' + if parent_node_name not in all_ops: + all_ops[parent_node_name] = {} + all_ops[parent_node_name]['children_node'] = set() + all_ops[parent_node_name]['name'] = parent_node_name + all_ops[parent_node_name]['show_name'] = os.path.dirname( + all_ops[child_node_name]['show_name']) + all_ops[parent_node_name]['attrs'] = {} + all_ops[parent_node_name]['input_nodes'] = set() + all_ops[parent_node_name]['output_nodes'] = set() + all_ops[parent_node_name]['type'] = os.path.basename( + all_ops[parent_node_name]['show_name']) + all_ops[parent_node_name]['input_vars'] = set() + all_ops[parent_node_name]['output_vars'] = set() + all_ops[parent_node_name]['parent_node'] = '' + all_ops[parent_node_name]['edge_input_nodes'] = [] + all_ops[parent_node_name]['edge_output_nodes'] = [] + all_ops[parent_node_name]['is_leaf_node'] = False + + all_ops[child_node_name]['parent_node'] = parent_node_name + all_ops[parent_node_name]['children_node'].add(child_node_name) + general_children_dict[parent_node_name].add(child_node_name) + general_children_dict[parent_node_name].update( + general_children_dict[child_node_name]) + if parent_node_name == '/': # root node + return + else: + create_non_leaf_nodes( + os.path.dirname(parent_node_name), parent_node_name, all_ops, + general_children_dict) + + +def construct_edges(var_name, all_ops, all_vars, all_edges): + ''' + Construct path edges from var's from_node to to_nodes. + Algorithm: + 1. Judge if src_node and dst_node have the same parent node, if yes, link them directly + and fill information in all_edges, return. + 2. Find the closest common ancestor, repeat link node and its parent until reach the common ancestor. + Every time construct a new edge, fill information in all_edges. + Args: + var_name: name of variable to process + all_ops: used to index all nodes. + all_vars: used to index all variables. + all_edges: used to store and index all edges + ''' + from_node = all_vars[var_name]['from_node'] + to_nodes = all_vars[var_name]['to_nodes'] + + def _construct_edge(src_node, dst_node): + if all_ops[src_node]['parent_node'] == all_ops[dst_node][ + 'parent_node']: + if (src_node, dst_node) not in all_edges: + all_edges[(src_node, dst_node)] = { + 'from_node': src_node, + 'to_node': dst_node, + 'vars': {var_name}, + 'label': '' + } + else: + all_edges[(src_node, dst_node)]['vars'].add(var_name) + else: + common_ancestor = os.path.commonpath([src_node, dst_node]) + common_ancestor = pathlib.Path(common_ancestor).as_posix( + ) # in windows, os.path.commonpath will return windows path, we should convert it to posix + src_base_node = src_node + while True: + parent_node = all_ops[src_base_node]['parent_node'] + if parent_node == common_ancestor: + break + if (src_base_node, parent_node) not in all_edges: + all_edges[(src_base_node, parent_node)] = { + 'from_node': src_base_node, + 'to_node': parent_node, + 'vars': {var_name}, + 'label': '' + } + else: + all_edges[(src_base_node, + parent_node)]['vars'].add(var_name) + src_base_node = parent_node + dst_base_node = dst_node + while True: + parent_node = all_ops[dst_base_node]['parent_node'] + if parent_node == common_ancestor: + break + if (parent_node, dst_base_node) not in all_edges: + all_edges[(parent_node, dst_base_node)] = { + 'from_node': parent_node, + 'to_node': dst_base_node, + 'vars': {var_name}, + 'label': '' + } + else: + all_edges[(parent_node, + dst_base_node)]['vars'].add(var_name) + dst_base_node = parent_node + if (src_base_node, dst_base_node) not in all_edges: + all_edges[(src_base_node, dst_base_node)] = { + 'from_node': src_base_node, + 'to_node': dst_base_node, + 'vars': {var_name}, + 'label': '' + } + else: + all_edges[(src_base_node, dst_base_node)]['vars'].add(var_name) + return + + if from_node and to_nodes: + for to_node in to_nodes: + if from_node == to_node: + continue + _construct_edge(from_node, to_node) + + +def analyse_model(model_pb): # noqa: C901 + try: + from paddle.framework import core + except Exception: + print("Paddlepaddle is required to use add_graph interface.\n\ + Please refer to \ + https://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/pip/linux-pip.html\ + to install paddlepaddle.") + + AttrType = core.AttrType + attr_type_name = { + AttrType.INT: "INT", + AttrType.INTS: "INTS", + AttrType.LONG: "LONG", + AttrType.LONGS: "LONGS", + AttrType.FLOAT: "FLOAT", + AttrType.FLOATS: "FLOATS", + AttrType.STRING: "STRING", + AttrType.STRINGS: "STRINGS", + AttrType.BOOL: "BOOL", + AttrType.BOOLS: "BOOLS", + AttrType.BLOCK: "BLOCK", + AttrType.BLOCKS: "BLOCKS" + } + ProgramDesc = core.ProgramDesc + from paddle.utils.unique_name import generate + program_desc = ProgramDesc(model_pb) + all_ops = {} + all_vars = {} + all_edges = {} + op_inputvars_dict = collections.defaultdict(list) + op_outputvars_dict = collections.defaultdict(list) + for i in range(program_desc.num_blocks()): + if i != 0: # We do not show sub block for clarity now + continue + block_desc = program_desc.block(i) + # vars info + for var_desc in block_desc.all_vars(): + try: + var_name = var_desc.name() + all_vars[var_name] = {} + all_vars[var_name]['name'] = var_name + all_vars[var_name]['shape'] = var_desc.shape() + all_vars[var_name]['type'] = str(var_desc.type()) + all_vars[var_name]['dtype'] = str(var_desc.dtype()) + all_vars[var_name]['value'] = [] + all_vars[var_name]['persistable'] = var_desc.persistable() + attr_dict = {} + for attr_name in var_desc.attr_names(): + attr_dict[attr_name] = var_desc.attr(attr_name) + all_vars[var_name]['attrs'] = attr_dict + all_vars[var_name]['from_node'] = '' + all_vars[var_name]['to_nodes'] = [] + + except Exception: + # feed, fetch var + var_name = var_desc.name() + all_vars[var_name] = {} + all_vars[var_name]['name'] = var_name + all_vars[var_name]['shape'] = '' + all_vars[var_name]['type'] = str(var_desc.type()) + all_vars[var_name]['dtype'] = '' + all_vars[var_name]['value'] = [] + all_vars[var_name]['persistable'] = var_desc.persistable() + attr_dict = {} + for attr_name in var_desc.attr_names(): + attr_dict[attr_name] = var_desc.attr(attr_name) + all_vars[var_name]['attrs'] = attr_dict + all_vars[var_name]['from_node'] = '' + all_vars[var_name]['to_nodes'] = [] + + for i in range(program_desc.num_blocks()): + if i != 0: # We do not show sub block for clarity now + continue + block_desc = program_desc.block(i) + # ops info + for j in range(block_desc.op_size()): + op_desc = block_desc.op(j) + op_name = op_desc.attr('op_namescope') + generate( + str(op_desc.type())) + all_ops[op_name] = {} + all_ops[op_name]['name'] = op_name + all_ops[op_name]['show_name'] = re.sub(r'\[(\w|\.)*\]', '', + op_name) + all_ops[op_name]['type'] = str(op_desc.type()) + all_ops[op_name]['input_vars'] = {} + all_ops[op_name]['is_leaf_node'] = True + for input_name, variable_list in op_desc.inputs().items(): + all_ops[op_name]['input_vars'][input_name] = variable_list + op_inputvars_dict[op_name].extend(variable_list) + # fill var 'to_nodes' + for variable_name in variable_list: + all_vars[variable_name]['to_nodes'].append(op_name) + all_ops[op_name]['output_vars'] = {} + for output_name, variable_list in op_desc.outputs().items(): + all_ops[op_name]['output_vars'][output_name] = variable_list + op_outputvars_dict[op_name].extend(variable_list) + # fill var 'from_node' + for variable_name in variable_list: + all_vars[variable_name]['from_node'] = op_name + + attr_dict = {} + attr_type_dict = {} + for attr_name in op_desc.attr_names(): + try: + if attr_name == 'sub_block': + continue + attr_dict[attr_name] = op_desc.attr(attr_name) + attr_type = op_desc.attr_type(attr_name) + attr_type_dict[attr_name] = attr_type_name[ + attr_type] if attr_type in attr_type_name else str( + attr_type).split('.')[1] + except Exception: + continue + all_ops[op_name]['attrs'] = attr_dict + all_ops[op_name]['attr_types'] = attr_type_dict + all_ops[op_name]['children_node'] = [] + all_ops[op_name]['input_nodes'] = [] + all_ops[op_name]['output_nodes'] = [] + all_ops[op_name]['edge_input_nodes'] = [] + all_ops[op_name]['edge_output_nodes'] = [] + + # second pass, create non-leaf nodes, fill 'parent_node', 'children_nodes' of nodes. + for variable_name in all_vars: + if all_vars[variable_name]['from_node'] == '': + continue + # some variable's input and output node are the same, we should prevent to show this situation as a cycle + from_node_name = all_vars[variable_name]['from_node'] + for to_node_name in all_vars[variable_name]['to_nodes']: + if to_node_name != from_node_name: + all_ops[from_node_name]['output_nodes'].append(to_node_name) + all_ops[to_node_name]['input_nodes'].append(from_node_name) + + general_children_dict = collections.defaultdict(set) + + all_op_names = list(all_ops.keys()) + for op_name in all_op_names: + create_non_leaf_nodes( + os.path.dirname(op_name), op_name, all_ops, general_children_dict) + + # fill all non-leaf node's 'output_nodes' 'input_nodes' 'output_vars' 'input_vars' + # post-order traverse tree + post_order_results = [] + + post_order_traverse('/', all_ops, post_order_results) + + for op_name in post_order_results: + op = all_ops[op_name] + op['children_node'] = list(op['children_node']) + + if op['children_node']: + for child_op in op['children_node']: + for input_node in all_ops[child_op]['input_nodes']: + if input_node in general_children_dict[op_name]: + continue + else: + op['input_nodes'].add(input_node) + for output_node in all_ops[child_op]['output_nodes']: + if output_node in general_children_dict[op_name]: + continue + else: + op['output_nodes'].add(output_node) + for input_var in op_inputvars_dict[child_op]: + if all_vars[input_var][ + 'from_node'] not in general_children_dict[op_name]: + op['input_vars'].add(input_var) + for output_var in op_outputvars_dict[child_op]: + for to_node_name in all_vars[output_var]['to_nodes']: + if to_node_name not in general_children_dict[op_name]: + op['output_vars'].add(output_var) + op['input_nodes'] = list(op['input_nodes']) + op['output_nodes'] = list(op['output_nodes']) + op_inputvars_dict[op_name] = list(op['input_vars']) + op_outputvars_dict[op_name] = list(op['output_vars']) + op['input_vars'] = {'X': list(op['input_vars'])} + op['output_vars'] = {'Y': list(op['output_vars'])} + + # Supplement edges and 'edge_input_nodes', 'edge_output_nodes' in op to help draw in frontend + for var_name in all_vars.keys(): + construct_edges(var_name, all_ops, all_vars, all_edges) + + for src_node, to_node in all_edges.keys(): + all_ops[src_node]['edge_output_nodes'].append(to_node) + all_ops[to_node]['edge_input_nodes'].append(src_node) + all_edges[(src_node, to_node)]['vars'] = list( + all_edges[(src_node, to_node)]['vars']) + if len(all_edges[(src_node, to_node)]['vars']) > 1: + all_edges[(src_node, to_node)]['label'] = str( + len(all_edges[(src_node, to_node)]['vars'])) + ' tensors' + elif len(all_edges[(src_node, to_node)]['vars']) == 1: + all_edges[(src_node, to_node)]['label'] = str( + all_vars[all_edges[(src_node, to_node)]['vars'][0]]['shape']) + + final_data = { + 'version': _graph_version, + 'nodes': list(all_ops.values()), + 'vars': list(all_vars.values()), + 'edges': list(all_edges.values()) + } + return final_data diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/netron_graph.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/netron_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..91a74ea5fe0b5ba50731208d795b736f16d6554c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/netron_graph.py @@ -0,0 +1,254 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from collections import defaultdict +from collections import deque + + +class Model: + def __init__(self, graph_data): + self.name = 'Paddle Graph' + self.version = graph_data['version'] + self.all_nodes = {node['name']: node for node in graph_data['nodes']} + self.all_vars = {var['name']: var for var in graph_data['vars']} + self.all_edges = {(edge['from_node'], edge['to_node']): edge + for edge in graph_data['edges']} + self.visible_maps = { + node['name']: (True if not node['children_node'] else False) + for node in graph_data['nodes'] + } + root_node = self.all_nodes['/'] + for child_name in root_node['children_node']: + self.visible_maps[child_name] = True + + def make_graph(self, refresh=False, expand_all=False): + if refresh is True: + self.visible_maps = { + node['name']: (True if not node['children_node'] else False) + for node in self.all_nodes.values() + } + root_node = self.all_nodes['/'] + for child_name in root_node['children_node']: + self.visible_maps[child_name] = True + if expand_all is True: + self.visible_maps = { + node['name']: (True if not node['children_node'] else False) + for node in self.all_nodes.values() + } + self.current_nodes = { + node_name: self.all_nodes[node_name] + for node_name in self.get_current_visible_nodes() + } + return Graph(self.current_nodes, self.all_vars) + + def get_all_leaf_nodes(self): + return Graph(self.all_nodes, self.all_vars) + + def get_current_visible_nodes(self): + # bfs traversal to get current visible nodes + # if one node is visible now, all its children nodes are invisible + current_visible_nodes = [] + travesal_queue = deque() + visited_map = defaultdict(bool) + travesal_queue.append('/') + visited_map['/'] = True + while travesal_queue: + current_name = travesal_queue.popleft() + current_node = self.all_nodes[current_name] + if self.visible_maps[current_name] is True: + current_visible_nodes.append(current_name) + else: + for child_name in current_node['children_node']: + if visited_map[child_name] is False: + travesal_queue.append(child_name) + visited_map[child_name] = True + return current_visible_nodes + + def adjust_visible(self, node_name, expand=True, keep_state=False): + if (expand): + if self.all_nodes[node_name]['is_leaf_node'] is True: + return + if keep_state: + self.visible_maps[node_name] = False + else: + self.visible_maps[node_name] = False + current_node = self.all_nodes[node_name] + for child_name in current_node['children_node']: + self.visible_maps[child_name] = True + else: + self.visible_maps[node_name] = True + + def adjust_search_node_visible(self, + node_name, + keep_state=False, + is_node=True): + if node_name is None: + return + node_names = [] + if is_node is False: + var = self.all_vars[node_name] + node_names.append(var['from_node']) + node_names.extend(var['to_nodes']) + else: + node_names.append(node_name) + for node_name in node_names: + topmost_parent = None + parent_node_name = self.all_nodes[node_name]['parent_node'] + while (parent_node_name != '/'): + if self.visible_maps[parent_node_name] is True: + topmost_parent = parent_node_name + parent_node_name = self.all_nodes[parent_node_name][ + 'parent_node'] + if topmost_parent is not None: + self.visible_maps[topmost_parent] = False + parent_node_name = self.all_nodes[node_name]['parent_node'] + if (keep_state): + self.visible_maps[node_name] = True + while (parent_node_name != topmost_parent): + self.visible_maps[parent_node_name] = False + parent_node_name = self.all_nodes[parent_node_name][ + 'parent_node'] + else: + for child_name in self.all_nodes[parent_node_name][ + 'children_node']: + self.visible_maps[child_name] = True + self.visible_maps[parent_node_name] = False + key_path_node_name = parent_node_name + while (parent_node_name != topmost_parent): + parent_node_name = self.all_nodes[parent_node_name][ + 'parent_node'] + for child_name in self.all_nodes[parent_node_name][ + 'children_node']: + if child_name != key_path_node_name: + self.visible_maps[child_name] = True + else: + self.visible_maps[child_name] = False + key_path_node_name = parent_node_name + + +class Graph(dict): + def __init__(self, nodes, all_vars): + self.nodes = [] + self.inputs = [] + self.outputs = [] + self.name = 'Paddle Graph' + output_idx = 0 + for op_node in nodes.values(): + if op_node['type'] == 'feed': + for key, value in op_node["output_vars"].items(): + self.inputs.append( + Parameter( + value[0], + [Argument(name, all_vars[name]) + for name in value])) + continue + if op_node['type'] == 'fetch': + for key, value in op_node["input_vars"].items(): + self.outputs.append( + Parameter( + 'Output{}'.format(output_idx), + [Argument(name, all_vars[name]) + for name in value])) + output_idx += 1 + continue + self.nodes.append(Node(op_node, all_vars)) + + super(Graph, self).__init__( + name=self.name, + nodes=self.nodes, + inputs=self.inputs, + outputs=self.outputs) + + +class Node(dict): + def __init__(self, node, all_vars): + self.name = node['name'] + self.show_name = node['show_name'] + self.type = node['type'] + self.attributes = [ + Attribute(key, value, node['attr_types'][key]) + for key, value in node['attrs'].items() + ] + self.inputs = [ + Parameter(key, [Argument(name, all_vars[name]) for name in value]) + for key, value in node["input_vars"].items() + ] + self.outputs = [ + Parameter(key, [Argument(name, all_vars[name]) for name in value]) + for key, value in node["output_vars"].items() + ] + self.chain = [] + self.visible = True + self.is_leaf = node['is_leaf_node'] + super(Node, self).__init__( + name=self.name, + type=self.type, + attributes=self.attributes, + inputs=self.inputs, + outputs=self.outputs, + chain=self.chain, + visible=self.visible, + is_leaf=self.is_leaf, + show_name=self.show_name) + + +class Attribute(dict): + def __init__(self, key, value, attr_type): + self.name = key + self.value = value + self.type = attr_type + self.visible = True if key not in [ + 'use_mkldnn', 'use_cudnn', 'op_callstack', 'op_role', + 'op_role_var', 'op_namescope', 'is_test' + ] else False + super(Attribute, self).__init__( + name=self.name, + value=self.value, + type=self.type, + visible=self.visible) + + +class Parameter(dict): + def __init__(self, name, args): + self.name = name + self.visible = True + self.arguments = args + super(Parameter, self).__init__( + name=self.name, visible=self.visible, arguments=self.arguments) + + +class Argument(dict): + def __init__(self, name, var): + self.name = name + self.type = TensorType(var['dtype'], var['shape']) + self.initializer = None if var['persistable'] is False else self.type + super(Argument, self).__init__( + name=self.name, type=self.type, initializer=self.initializer) + + +class TensorType(dict): + def __init__(self, datatype, shape): + self.dataType = datatype + self.shape = TensorShape(shape) + self.denotation = None + super(TensorType, self).__init__( + dataType=self.dataType, + shape=self.shape, + denotation=self.denotation) + + +class TensorShape(dict): + def __init__(self, dimensions): + self.dimensions = dimensions + super(TensorShape, self).__init__(dimensions=self.dimensions) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd33abdf0852b26851f762e7b0d7c6ac94ad595 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/graph/utils.py @@ -0,0 +1,107 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from collections import Counter +from collections import deque + +_name_scope_stack = deque() + + +def _opname_creation_prehook(layer, inputs): + from paddle.static import name_scope + global _name_scope_stack + _name_scope_stack.append(name_scope(layer.full_name())) + _name_scope_stack[-1].__enter__() + + +def _opname_creation_posthook(layer, inputs, outputs): + global _name_scope_stack + name_scope_manager = _name_scope_stack.pop() + name_scope_manager.__exit__(None, None, None) + + +def create_opname_scope(layer): + layer.register_forward_pre_hook(_opname_creation_prehook) + for name, sublayer in layer.named_children(): + sublayer._full_name = '{}[{}]'.format(sublayer.__class__.__name__, + name) + create_opname_scope(sublayer) + layer.register_forward_post_hook(_opname_creation_posthook) + + +def print_model(analyse_result): + ''' + Print some information about model for users, we count numbers of ops and layers. + ''' + result = [] + # statistics + op_counter = Counter() + layer_counter = Counter() + nodes = analyse_result['nodes'] + total_ops = 0 + total_layers = 0 + for node in nodes: + if node['name'] == '/': + continue + if not node['children_node']: + op_counter[node['type']] += 1 + total_ops += 1 + else: + layer_counter[node['type']] += 1 + total_layers += 1 + + SPACING_SIZE = 2 + row_format_list = [""] + header_sep_list = [""] + line_length_list = [-SPACING_SIZE] + + def add_title(padding, text): + left_length = padding - len(text) + half = left_length // 2 + return '-' * half + text + '-' * (left_length - half) + + def add_column(padding, text_dir='<'): + row_format_list[0] += '{: ' + text_dir + str(padding) + '}' + ( + ' ' * SPACING_SIZE) + header_sep_list[0] += '-' * padding + (' ' * SPACING_SIZE) + line_length_list[0] += padding + SPACING_SIZE + + def append(s): + result.append(s) + result.append('\n') + + headers = ['Name', 'Type', 'Count'] + column_width = 20 + for _ in headers: + add_column(column_width) + + row_format = row_format_list[0] + header_sep = header_sep_list[0] + line_length = line_length_list[0] + + # construct table string + append(add_title(line_length, "Graph Summary")) + append('total operators: {}\ttotal layers:{}'.format( + total_ops, total_layers)) + append(header_sep) + append(row_format.format(*headers)) + append(header_sep) + for op_type, count in op_counter.items(): + row_values = [op_type, 'operator', count] + append(row_format.format(*row_values)) + for layer_type, count in layer_counter.items(): + row_values = [layer_type, 'layer', count] + append(row_format.format(*row_values)) + append('-' * line_length) + print(''.join(result)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19f7b87ee86723af4d909e34a05647f7e40fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19f7b87ee86723af4d909e34a05647f7e40fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/client_app.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/client_app.py new file mode 100644 index 0000000000000000000000000000000000000000..76447abae7c033355c132493eae25db603544e1f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/client_app.py @@ -0,0 +1,799 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import gradio as gr +import numpy as np + +from .http_client_manager import get_metric_data +from .http_client_manager import HttpClientManager +from .http_client_manager import metrics_table_head +from .http_client_manager import metrics_table_head_en +from .visualizer import visualize_detection +from .visualizer import visualize_face_alignment +from .visualizer import visualize_face_detection +from .visualizer import visualize_headpose +from .visualizer import visualize_keypoint_detection +from .visualizer import visualize_matting +from .visualizer import visualize_ocr +from .visualizer import visualize_segmentation + +_http_manager = HttpClientManager() + +supported_tasks = { + 'detection': visualize_detection, + 'facedet': visualize_face_detection, + 'keypointdetection': visualize_keypoint_detection, + 'segmentation': visualize_segmentation, + 'matting': visualize_matting, + 'ocr': visualize_ocr, + 'facealignment': visualize_face_alignment, + 'headpose': visualize_headpose, + 'unspecified': lambda x: str(x) +} + + +def create_gradio_client_app(): # noqa:C901 + css = """ + .gradio-container { + font-family: 'IBM Plex Sans', sans-serif; + } + .gr-button { + color: white; + border-color: black; + background: black; + } + input[type='range'] { + accent-color: black; + } + .dark input[type='range'] { + accent-color: #dfdfdf; + } + #gallery { + min-height: 22rem; + margin-bottom: 15px; + margin-left: auto; + margin-right: auto; + border-bottom-right-radius: .5rem !important; + border-bottom-left-radius: .5rem !important; + } + #gallery>div>.h-full { + min-height: 20rem; + } + .details:hover { + text-decoration: underline; + } + .gr-button { + white-space: nowrap; + } + .gr-button:focus { + border-color: rgb(147 197 253 / var(--tw-border-opacity)); + outline: none; + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + --tw-border-opacity: 1; + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) \ + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color); + --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity)); + --tw-ring-opacity: .5; + } + .footer { + margin-bottom: 45px; + margin-top: 35px; + text-align: center; + border-bottom: 1px solid #e5e5e5; + } + .footer>p { + font-size: .8rem; + display: inline-block; + padding: 0 10px; + transform: translateY(10px); + background: white; + } + .dark .footer { + border-color: #303030; + } + .dark .footer>p { + background: #0b0f19; + } + .prompt h4{ + margin: 1.25em 0 .25em 0; + font-weight: bold; + font-size: 115%; + } + """ + + block = gr.Blocks(css=css) + + with block: + gr.HTML(""" +
+
+

+ FastDeploy Client +

+
+

+ The client is used for creating requests to fastdeploy server. +

+
+ """) + with gr.Group(): + with gr.Box(): + with gr.Column(): + with gr.Row(): + server_addr_text = gr.Textbox( + label="服务ip", + show_label=True, + max_lines=1, + placeholder="localhost", + ) + + server_http_port_text = gr.Textbox( + label="推理服务端口", + show_label=True, + max_lines=1, + placeholder="8000", + ) + + server_metric_port_text = gr.Textbox( + label="性能服务端口", + show_label=True, + max_lines=1, + placeholder="8002", + ) + with gr.Row(): + model_name_text = gr.Textbox( + label="模型名称", + show_label=True, + max_lines=1, + placeholder="yolov5", + ) + model_version_text = gr.Textbox( + label="模型版本", + show_label=True, + max_lines=1, + placeholder="1", + ) + + with gr.Box(): + with gr.Tab("组件形式"): + check_button = gr.Button("获取模型输入输出") + component_format_column = gr.Column(visible=False) + with component_format_column: + task_radio = gr.Radio( + choices=list(supported_tasks.keys()), + value='unspecified', + label='任务类型', + visible=True) + gr.Markdown("根据模型需要,挑选文本框或者图像框进行输入") + with gr.Row(): + with gr.Column(): + gr.Markdown("模型输入") + input_accordions = [] + input_name_texts = [] + input_images = [] + input_texts = [] + for i in range(6): + accordion = gr.Accordion( + "输入变量 {}".format(i), + open=True, + visible=False) + with accordion: + input_name_text = gr.Textbox( + label="变量名", interactive=False) + input_image = gr.Image(type='numpy') + input_text = gr.Textbox( + label="文本框", max_lines=1000) + input_accordions.append(accordion) + input_name_texts.append(input_name_text) + input_images.append(input_image) + input_texts.append(input_text) + + with gr.Column(): + gr.Markdown("模型输出") + output_accordions = [] + output_name_texts = [] + output_images = [] + output_texts = [] + for i in range(6): + accordion = gr.Accordion( + "输出变量 {}".format(i), + open=True, + visible=False) + with accordion: + output_name_text = gr.Textbox( + label="变量名", interactive=False) + output_text = gr.Textbox( + label="服务返回的原数据", + interactive=False, + show_label=True) + output_image = gr.Image( + interactive=False) + output_accordions.append(accordion) + output_name_texts.append(output_name_text) + output_images.append(output_image) + output_texts.append(output_text) + component_submit_button = gr.Button("提交请求") + with gr.Tab("原始形式"): + gr.Markdown("模型输入") + raw_payload_text = gr.Textbox( + label="负载数据", max_lines=10000) + with gr.Column(): + gr.Markdown("输出") + output_raw_text = gr.Textbox( + label="服务返回的原始数据", interactive=False) + raw_submit_button = gr.Button("提交请求") + + with gr.Box(): + with gr.Column(): + gr.Markdown("服务性能统计(每次提交请求会自动更新数据,您也可以手动点击更新)") + output_html_table = gr.HTML( + label="metrics", + interactive=False, + show_label=False, + value=metrics_table_head.format('', '')) + update_metric_button = gr.Button("更新统计数据") + + status_text = gr.Textbox( + label="status", + show_label=True, + max_lines=1, + interactive=False) + + lang_text = gr.Textbox( + label="lang", + show_label=False, + value='zh', + max_lines=1, + visible=False + ) # This text box is only used for divide zh and en page + + all_input_output_components = input_accordions + input_name_texts + input_images + \ + input_texts + output_accordions + output_name_texts + output_images + output_texts + + def get_input_output_name(server_ip, server_port, model_name, + model_version, lang_text): + try: + server_addr = server_ip + ':' + server_port + input_metas, output_metas = _http_manager.get_model_meta( + server_addr, model_name, model_version) + except Exception as e: + return {status_text: str(e)} + results = { + component: None + for component in all_input_output_components + } + results[component_format_column] = gr.update(visible=True) + for input_accordio in input_accordions: + results[input_accordio] = gr.update(visible=False) + for output_accordio in output_accordions: + results[output_accordio] = gr.update(visible=False) + results[status_text] = 'Get model inputs and outputs successfully.' + for i, input_meta in enumerate(input_metas): + results[input_accordions[i]] = gr.update(visible=True) + results[input_name_texts[i]] = input_meta['name'] + for i, output_meta in enumerate(output_metas): + results[output_accordions[i]] = gr.update(visible=True) + results[output_name_texts[i]] = output_meta['name'] + return results + + def component_inference(*args): + server_ip = args[0] + http_port = args[1] + metric_port = args[2] + model_name = args[3] + model_version = args[4] + names = args[5:5 + len(input_name_texts)] + images = args[5 + len(input_name_texts):5 + len(input_name_texts) + + len(input_images)] + texts = args[5 + len(input_name_texts) + len(input_images):5 + + len(input_name_texts) + len(input_images) + + len(input_texts)] + task_type = args[-1] + server_addr = server_ip + ':' + http_port + if server_ip and http_port and model_name and model_version: + inputs = {} + for i, input_name in enumerate(names): + if input_name: + if images[i] is not None: + inputs[input_name] = np.array([images[i]]) + if texts[i]: + inputs[input_name] = np.array( + [[texts[i].encode('utf-8')]], dtype=np.object_) + try: + infer_results = _http_manager.infer( + server_addr, model_name, model_version, inputs) + results = {status_text: 'Inference successfully.'} + for i, (output_name, + data) in enumerate(infer_results.items()): + results[output_name_texts[i]] = output_name + results[output_texts[i]] = str(data) + if task_type != 'unspecified': + try: + results[output_images[i]] = supported_tasks[ + task_type](images[0], data) + except Exception: + results[output_images[i]] = None + if metric_port: + html_table = get_metric_data(server_ip, metric_port, + 'zh') + results[output_html_table] = html_table + return results + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + else: + return { + status_text: + 'Please input server addr, model name and model version.' + } + + def raw_inference(*args): + server_ip = args[0] + http_port = args[1] + metric_port = args[2] + model_name = args[3] + model_version = args[4] + payload_text = args[5] + server_addr = server_ip + ':' + http_port + try: + result = _http_manager.raw_infer(server_addr, model_name, + model_version, payload_text) + results = { + status_text: 'Get response from server', + output_raw_text: result + } + if server_ip and metric_port: + html_table = get_metric_data(server_ip, metric_port, 'zh') + results[output_html_table] = html_table + return results + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + + def update_metric(server_ip, metrics_port, lang_text): + if server_ip and metrics_port: + try: + html_table = get_metric_data(server_ip, metrics_port, 'zh') + return { + output_html_table: html_table, + status_text: "Update metrics successfully." + } + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + else: + return { + status_text: 'Please input server ip and metrics_port.' + } + + check_button.click( + fn=get_input_output_name, + inputs=[ + server_addr_text, server_http_port_text, model_name_text, + model_version_text, lang_text + ], + outputs=[ + *all_input_output_components, check_button, + component_format_column, status_text + ]) + component_submit_button.click( + fn=component_inference, + inputs=[ + server_addr_text, server_http_port_text, + server_metric_port_text, model_name_text, model_version_text, + *input_name_texts, *input_images, *input_texts, task_radio + ], + outputs=[ + *output_name_texts, *output_images, *output_texts, status_text, + output_html_table + ]) + raw_submit_button.click( + fn=raw_inference, + inputs=[ + server_addr_text, server_http_port_text, + server_metric_port_text, model_name_text, model_version_text, + raw_payload_text + ], + outputs=[output_raw_text, status_text, output_html_table]) + update_metric_button.click( + fn=update_metric, + inputs=[server_addr_text, server_metric_port_text, lang_text], + outputs=[output_html_table, status_text]) + return block + + +def create_gradio_client_app_en(): # noqa:C901 + css = """ + .gradio-container { + font-family: 'IBM Plex Sans', sans-serif; + } + .gr-button { + color: white; + border-color: black; + background: black; + } + input[type='range'] { + accent-color: black; + } + .dark input[type='range'] { + accent-color: #dfdfdf; + } + #gallery { + min-height: 22rem; + margin-bottom: 15px; + margin-left: auto; + margin-right: auto; + border-bottom-right-radius: .5rem !important; + border-bottom-left-radius: .5rem !important; + } + #gallery>div>.h-full { + min-height: 20rem; + } + .details:hover { + text-decoration: underline; + } + .gr-button { + white-space: nowrap; + } + .gr-button:focus { + border-color: rgb(147 197 253 / var(--tw-border-opacity)); + outline: none; + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + --tw-border-opacity: 1; + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) \ + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color); + --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity)); + --tw-ring-opacity: .5; + } + .footer { + margin-bottom: 45px; + margin-top: 35px; + text-align: center; + border-bottom: 1px solid #e5e5e5; + } + .footer>p { + font-size: .8rem; + display: inline-block; + padding: 0 10px; + transform: translateY(10px); + background: white; + } + .dark .footer { + border-color: #303030; + } + .dark .footer>p { + background: #0b0f19; + } + .prompt h4{ + margin: 1.25em 0 .25em 0; + font-weight: bold; + font-size: 115%; + } + """ + + block = gr.Blocks(css=css) + + with block: + gr.HTML(""" +
+
+

+ FastDeploy Client +

+
+

+ The client is used for creating requests to fastdeploy server. +

+
+ """) + with gr.Group(): + with gr.Box(): + with gr.Column(): + with gr.Row(): + server_addr_text = gr.Textbox( + label="server ip", + show_label=True, + max_lines=1, + placeholder="localhost", + ) + + server_http_port_text = gr.Textbox( + label="server port", + show_label=True, + max_lines=1, + placeholder="8000", + ) + + server_metric_port_text = gr.Textbox( + label="metrics port", + show_label=True, + max_lines=1, + placeholder="8002", + ) + with gr.Row(): + model_name_text = gr.Textbox( + label="model name", + show_label=True, + max_lines=1, + placeholder="yolov5", + ) + model_version_text = gr.Textbox( + label="model version", + show_label=True, + max_lines=1, + placeholder="1", + ) + + with gr.Box(): + with gr.Tab("Component form"): + check_button = gr.Button("get model input and output") + component_format_column = gr.Column(visible=False) + with component_format_column: + task_radio = gr.Radio( + choices=list(supported_tasks.keys()), + value='unspecified', + label='task type', + visible=True) + gr.Markdown( + "Choose text or image component to input according to data type" + ) + with gr.Row(): + with gr.Column(): + gr.Markdown("Inputs") + input_accordions = [] + input_name_texts = [] + input_images = [] + input_texts = [] + for i in range(6): + accordion = gr.Accordion( + "variable {}".format(i), + open=True, + visible=False) + with accordion: + input_name_text = gr.Textbox( + label="variable name", + interactive=False) + input_image = gr.Image(type='numpy') + input_text = gr.Textbox( + label="text", max_lines=1000) + input_accordions.append(accordion) + input_name_texts.append(input_name_text) + input_images.append(input_image) + input_texts.append(input_text) + + with gr.Column(): + gr.Markdown("Outputs") + output_accordions = [] + output_name_texts = [] + output_images = [] + output_texts = [] + for i in range(6): + accordion = gr.Accordion( + "variable {}".format(i), + open=True, + visible=False) + with accordion: + output_name_text = gr.Textbox( + label="variable name", + interactive=False) + output_text = gr.Textbox( + label="text", + interactive=False, + show_label=True) + output_image = gr.Image( + interactive=False) + output_accordions.append(accordion) + output_name_texts.append(output_name_text) + output_images.append(output_image) + output_texts.append(output_text) + component_submit_button = gr.Button("submit request") + with gr.Tab("Original form"): + gr.Markdown("Request") + raw_payload_text = gr.Textbox( + label="request payload", max_lines=10000) + with gr.Column(): + gr.Markdown("Response") + output_raw_text = gr.Textbox( + label="raw response data", interactive=False) + raw_submit_button = gr.Button("submit request") + + with gr.Box(): + with gr.Column(): + gr.Markdown( + "Metrics(update automatically when submit request,or click update metrics button manually)" + ) + output_html_table = gr.HTML( + label="metrics", + interactive=False, + show_label=False, + value=metrics_table_head_en.format('', '')) + update_metric_button = gr.Button("update metrics") + + status_text = gr.Textbox( + label="status", + show_label=True, + max_lines=1, + interactive=False) + + lang_text = gr.Textbox( + label="lang", + show_label=False, + value='en', + max_lines=1, + visible=False + ) # This text box is only used for divide zh and en page + + all_input_output_components = input_accordions + input_name_texts + input_images + \ + input_texts + output_accordions + output_name_texts + output_images + output_texts + + def get_input_output_name(server_ip, server_port, model_name, + model_version, lang_text): + try: + server_addr = server_ip + ':' + server_port + input_metas, output_metas = _http_manager.get_model_meta( + server_addr, model_name, model_version) + except Exception as e: + return {status_text: str(e)} + results = { + component: None + for component in all_input_output_components + } + results[component_format_column] = gr.update(visible=True) + for input_accordio in input_accordions: + results[input_accordio] = gr.update(visible=False) + for output_accordio in output_accordions: + results[output_accordio] = gr.update(visible=False) + results[status_text] = 'Get model inputs and outputs successfully.' + for i, input_meta in enumerate(input_metas): + results[input_accordions[i]] = gr.update(visible=True) + results[input_name_texts[i]] = input_meta['name'] + for i, output_meta in enumerate(output_metas): + results[output_accordions[i]] = gr.update(visible=True) + results[output_name_texts[i]] = output_meta['name'] + return results + + def component_inference(*args): + server_ip = args[0] + http_port = args[1] + metric_port = args[2] + model_name = args[3] + model_version = args[4] + names = args[5:5 + len(input_name_texts)] + images = args[5 + len(input_name_texts):5 + len(input_name_texts) + + len(input_images)] + texts = args[5 + len(input_name_texts) + len(input_images):5 + + len(input_name_texts) + len(input_images) + + len(input_texts)] + task_type = args[-1] + server_addr = server_ip + ':' + http_port + if server_ip and http_port and model_name and model_version: + inputs = {} + for i, input_name in enumerate(names): + if input_name: + if images[i] is not None: + inputs[input_name] = np.array([images[i]]) + if texts[i]: + inputs[input_name] = np.array( + [[texts[i].encode('utf-8')]], dtype=np.object_) + try: + infer_results = _http_manager.infer( + server_addr, model_name, model_version, inputs) + results = {status_text: 'Inference successfully.'} + for i, (output_name, + data) in enumerate(infer_results.items()): + results[output_name_texts[i]] = output_name + results[output_texts[i]] = str(data) + if task_type != 'unspecified': + try: + results[output_images[i]] = supported_tasks[ + task_type](images[0], data) + except Exception: + results[output_images[i]] = None + if metric_port: + html_table = get_metric_data(server_ip, metric_port, + 'en') + results[output_html_table] = html_table + return results + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + else: + return { + status_text: + 'Please input server addr, model name and model version.' + } + + def raw_inference(*args): + server_ip = args[0] + http_port = args[1] + metric_port = args[2] + model_name = args[3] + model_version = args[4] + payload_text = args[5] + server_addr = server_ip + ':' + http_port + try: + result = _http_manager.raw_infer(server_addr, model_name, + model_version, payload_text) + results = { + status_text: 'Get response from server', + output_raw_text: result + } + if server_ip and metric_port: + html_table = get_metric_data(server_ip, metric_port, 'en') + results[output_html_table] = html_table + return results + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + + def update_metric(server_ip, metrics_port, lang_text): + if server_ip and metrics_port: + try: + html_table = get_metric_data(server_ip, metrics_port, 'en') + return { + output_html_table: html_table, + status_text: "Update metrics successfully." + } + except Exception as e: + return {status_text: 'Error: {}'.format(e)} + else: + return { + status_text: 'Please input server ip and metrics_port.' + } + + check_button.click( + fn=get_input_output_name, + inputs=[ + server_addr_text, server_http_port_text, model_name_text, + model_version_text, lang_text + ], + outputs=[ + *all_input_output_components, check_button, + component_format_column, status_text + ]) + component_submit_button.click( + fn=component_inference, + inputs=[ + server_addr_text, server_http_port_text, + server_metric_port_text, model_name_text, model_version_text, + *input_name_texts, *input_images, *input_texts, task_radio + ], + outputs=[ + *output_name_texts, *output_images, *output_texts, status_text, + output_html_table + ]) + raw_submit_button.click( + fn=raw_inference, + inputs=[ + server_addr_text, server_http_port_text, + server_metric_port_text, model_name_text, model_version_text, + raw_payload_text + ], + outputs=[output_raw_text, status_text, output_html_table]) + update_metric_button.click( + fn=update_metric, + inputs=[server_addr_text, server_metric_port_text, lang_text], + outputs=[output_html_table, status_text]) + return block diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/http_client_manager.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/http_client_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..47c419fe73db64d4516c88840b4786be7a6d4193 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/http_client_manager.py @@ -0,0 +1,351 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json +import re + +import numpy as np +import requests +import tritonclient.http as httpclient + + +def prepare_request(inputs_meta, inputs_data, outputs_meta): + ''' + inputs_meta: inputs meta information from model. name: info + inputs_data: users input data. name: data + ''' + # Set the input data + inputs = [] + for input_dict in inputs_meta: + input_name = input_dict['name'] + if input_name not in inputs_data: + raise RuntimeError( + 'Error: input name {} required for model not existed.'.format( + input_name)) + if input_dict['datatype'] == 'FP32': + inputs_data[input_name] = inputs_data[input_name].astype( + np.float32 + ) / 255 # image data returned by gradio is uint8, convert to fp32 + if len(input_dict['shape'] + ) == 3 and input_dict['shape'][0] == 3: # NCHW + inputs_data[input_name] = inputs_data[input_name][0].transpose( + 2, 0, 1) + elif len(input_dict['shape'] + ) == 4 and input_dict['shape'][1] == 3: # NCHW + inputs_data[input_name] = inputs_data[input_name].transpose( + 0, 3, 1, 2) + infer_input = httpclient.InferInput( + input_name, inputs_data[input_name].shape, input_dict['datatype']) + infer_input.set_data_from_numpy(inputs_data[input_name]) + inputs.append(infer_input) + outputs = [] + for output_dict in outputs_meta: + infer_output = httpclient.InferRequestedOutput(output_dict['name']) + outputs.append(infer_output) + return inputs, outputs + + +metrics_table_head = """ + + +
+ + + + + + + + + + + + + + + + + + + {} +
模型名称执行统计延迟统计
请求处理成功数请求处理失败数推理batch数推理样本数请求处理时间(ms)任务队列等待时间(ms)输入处理时间(ms)模型推理时间(ms)输出处理时间(ms)
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + {} +
GPU性能指标显存
利用率(%)功率(W)功率限制(W)耗电量(W)总量(GB)已使用(GB)
+
+""" + +metrics_table_head_en = """ + + +
+ + + + + + + + + + + + + + + + + + + {} +
Model nameExecution metricDelay metric
inference request successinference request failureinference countinference exec countinference request duration(ms)inference queue duration(ms)inference comput input duration(ms)inference compute infer duration +(ms)inference compute output duration(ms)
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + {} +
GPUPerformance metricMemory
utilization(%)power usage(W)power limit(W)energy consumption(W)total(GB)used(GB)
+
+""" + + +def get_metric_data(server_addr, metric_port, lang='zh'): # noqa:C901 + ''' + Get metrics data from fastdeploy server, and transform it into html table. + Args: + server_addr(str): fastdeployserver ip address + metric_port(int): fastdeployserver metrics port + Returns: + htmltable(str): html table to show metrics data + ''' + model_table = {} + gpu_table = {} + metric_column_name = { + "Model": { + "nv_inference_request_success", "nv_inference_request_failure", + "nv_inference_count", "nv_inference_exec_count", + "nv_inference_request_duration_us", + "nv_inference_queue_duration_us", + "nv_inference_compute_input_duration_us", + "nv_inference_compute_infer_duration_us", + "nv_inference_compute_output_duration_us" + }, + "GPU": { + "nv_gpu_power_usage", "nv_gpu_power_limit", + "nv_energy_consumption", "nv_gpu_utilization", + "nv_gpu_memory_total_bytes", "nv_gpu_memory_used_bytes" + }, + "CPU": { + "nv_cpu_utilization", "nv_cpu_memory_total_bytes", + "nv_cpu_memory_used_bytes" + } + } + try: + res = requests.get("http://{}:{}/metrics".format( + server_addr, metric_port)) + except Exception: + return metrics_table_head.format('', '') + metric_content = res.text + for content in metric_content.split('\n'): + if content.startswith('#'): + continue + else: + res = re.match(r'(\w+){(.*)} (\w+)', + content) # match output by server metrics interface + if not res: + continue + metric_name = res.group(1) + model = res.group(2) + value = res.group(3) + infos = {} + for info in model.split(','): + k, v = info.split('=') + v = v.strip('"') + infos[k] = v + if metric_name in [ + "nv_inference_request_duration_us", + "nv_inference_queue_duration_us", + "nv_inference_compute_input_duration_us", + "nv_inference_compute_infer_duration_us", + "nv_inference_compute_output_duration_us" + ]: + value = str(float(value) / 1000) + elif metric_name in [ + "nv_gpu_memory_total_bytes", "nv_gpu_memory_used_bytes" + ]: + value = str(float(value) / 1024 / 1024 / 1024) + for key, metric_names in metric_column_name.items(): + if metric_name in metric_names: + if key == 'Model': + model_name = infos['model'] + if model_name not in model_table: + model_table[model_name] = {} + model_table[model_name][metric_name] = value + elif key == 'GPU': + gpu_name = infos['gpu_uuid'] + if gpu_name not in gpu_table: + gpu_table[gpu_name] = {} + gpu_table[gpu_name][metric_name] = value + elif key == 'CPU': + pass + model_data_list = [] + gpu_data_list = [] + model_data_metric_names = [ + "nv_inference_request_success", "nv_inference_request_failure", + "nv_inference_exec_count", "nv_inference_count", + "nv_inference_request_duration_us", "nv_inference_queue_duration_us", + "nv_inference_compute_input_duration_us", + "nv_inference_compute_infer_duration_us", + "nv_inference_compute_output_duration_us" + ] + gpu_data_metric_names = [ + "nv_gpu_utilization", "nv_gpu_power_usage", "nv_gpu_power_limit", + "nv_energy_consumption", "nv_gpu_memory_total_bytes", + "nv_gpu_memory_used_bytes" + ] + for k, v in model_table.items(): + data = [] + data.append(k) + for data_metric in model_data_metric_names: + data.append(v[data_metric]) + model_data_list.append(data) + for k, v in gpu_table.items(): + data = [] + data.append(k) + for data_metric in gpu_data_metric_names: + data.append(v[data_metric]) + gpu_data_list.append(data) + model_data = '\n'.join([ + "" + '\n'.join(["" + item + "" + for item in data]) + "" + for data in model_data_list + ]) + gpu_data = '\n'.join([ + "" + '\n'.join(["" + item + "" + for item in data]) + "" + for data in gpu_data_list + ]) + if lang == 'en': + return metrics_table_head_en.format(model_data, gpu_data) + return metrics_table_head.format(model_data, gpu_data) + + +class HttpClientManager: + def __init__(self): + self.clients = {} # server url: httpclient + + def _create_client(self, server_url): + if server_url in self.clients: + return self.clients[server_url] + try: + fastdeploy_client = httpclient.InferenceServerClient(server_url) + self.clients[server_url] = fastdeploy_client + return fastdeploy_client + except Exception: + raise RuntimeError( + 'Can not connect to server {}, please check your ' + 'server address'.format(server_url)) + + def infer(self, server_url, model_name, model_version, inputs): + fastdeploy_client = self._create_client(server_url) + input_metadata, output_metadata = self.get_model_meta( + server_url, model_name, model_version) + inputs, outputs = prepare_request(input_metadata, inputs, + output_metadata) + response = fastdeploy_client.infer( + model_name, inputs, model_version=model_version, outputs=outputs) + + results = {} + for output in output_metadata: + result = response.as_numpy(output['name']) # datatype: numpy + if output['datatype'] == 'BYTES': # datatype: bytes + try: + value = result + if len(result.shape) == 1: + value = result[0] + elif len(result.shape) == 2: + value = result[0][0] + elif len(result.shape) == 3: + value = result[0][0][0] + result = json.loads(value) # datatype: json + except Exception: + pass + else: + result = result[0] + results[output['name']] = result + return results + + def raw_infer(self, server_url, model_name, model_version, raw_input): + url = 'http://{}/v2/models/{}/versions/{}/infer'.format( + server_url, model_name, model_version) + res = requests.post(url, data=json.dumps(json.loads(raw_input))) + return json.dumps(res.json()) + + def get_model_meta(self, server_url, model_name, model_version): + fastdeploy_client = self._create_client(server_url) + try: + model_metadata = fastdeploy_client.get_model_metadata( + model_name=model_name, model_version=model_version) + except Exception as e: + raise RuntimeError("Failed to retrieve the metadata: " + str(e)) + + input_metadata = model_metadata['inputs'] + output_metadata = model_metadata['outputs'] + return input_metadata, output_metadata diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/visualizer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c64a2427cfd6995c9ccaf4fea7ab0a0a75a72c41 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_client/visualizer.py @@ -0,0 +1,184 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import numpy as np + +__all__ = [ + 'visualize_detection', 'visualize_keypoint_detection', + 'visualize_face_detection', 'visualize_face_alignment', + 'visualize_segmentation', 'visualize_matting', 'visualize_ocr', + 'visualize_headpose' +] + + +def visualize_detection(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + boxes = np.array(data['boxes']) + scores = np.array(data['scores']) + label_ids = np.array(data['label_ids']) + masks = np.array(data['masks']) + contain_masks = data['contain_masks'] + detection_result = fd.C.vision.DetectionResult() + detection_result.boxes = boxes + detection_result.scores = scores + detection_result.label_ids = label_ids + detection_result.masks = masks + detection_result.contain_masks = contain_masks + result = fd.vision.vis_detection(image, detection_result) + return result + + +def visualize_keypoint_detection(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + keypoints = np.array(data['keypoints']) + scores = np.array(data['scores']) + num_joints = np.array(data['num_joints']) + + detection_result = fd.C.vision.KeyPointDetectionResult() + detection_result.keypoints = keypoints + detection_result.scores = scores + detection_result.num_joints = num_joints + + result = fd.vision.vis_keypoint_detection(image, detection_result) + return result + + +def visualize_face_detection(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + data = np.array(data['data']) + scores = np.array(data['scores']) + landmarks = np.array(data['landmarks']) + landmarks_per_face = data['landmarks_per_face'] + + detection_result = fd.C.vision.FaceDetectionResult() + detection_result.data = data + detection_result.scores = scores + detection_result.landmarks = landmarks + detection_result.landmarks_per_face = landmarks_per_face + + result = fd.vision.vis_face_detection(image, detection_result) + return result + + +def visualize_face_alignment(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + landmarks = np.array(data['landmarks']) + + facealignment_result = fd.C.vision.FaceAlignmentResult() + facealignment_result.landmarks = landmarks + + result = fd.vision.vis_face_alignment(image, facealignment_result) + return result + + +def visualize_segmentation(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + label_ids = np.array(data['label_ids']) + score_map = np.array(data['score_map']) + shape = np.array(data['shape']) + + segmentation_result = fd.C.vision.SegmentationResult() + segmentation_result.shape = shape + segmentation_result.score_map = score_map + segmentation_result.label_ids = label_ids + + result = fd.vision.vis_segmentation(image, segmentation_result) + return result + + +def visualize_matting(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + alpha = np.array(data['alpha']) + foreground = np.array(data['foreground']) + contain_foreground = data['contain_foreground'] + shape = np.array(data['shape']) + + matting_result = fd.C.vision.MattingResult() + matting_result.alpha = alpha + matting_result.foreground = foreground + matting_result.contain_foreground = contain_foreground + matting_result.shape = shape + + result = fd.vision.vis_matting(image, matting_result) + return result + + +def visualize_ocr(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + boxes = np.array(data['boxes']) + text = np.array(data['text']) + rec_scores = np.array(data['rec_scores']) + cls_scores = np.array(data['cls_scores']) + cls_labels = data['cls_labels'] + + ocr_result = fd.C.vision.OCRResult() + ocr_result.boxes = boxes + ocr_result.text = text + ocr_result.rec_scores = rec_scores + ocr_result.cls_scores = cls_scores + ocr_result.cls_labels = cls_labels + + result = fd.vision.vis_ppocr(image, ocr_result) + return result + + +def visualize_headpose(image, data): + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy") + euler_angles = np.array(data['euler_angles']) + + headpose_result = fd.C.vision.HeadPoseResult() + headpose_result.euler_angles = euler_angles + + result = fd.vision.vis_headpose(image, headpose_result) + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_lib.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..28934b3cd18360ca152a149a80117639b8e72501 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_lib.py @@ -0,0 +1,796 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import copy +import json +import os +import random +import re +import signal +import string +from collections import defaultdict +from subprocess import Popen +from subprocess import STDOUT + +import google.protobuf.json_format as json_format +import google.protobuf.text_format as text_format +import psutil +import requests + +from .proto.model_config_pb2 import ModelConfig +from visualdl.utils.dir import FASTDEPLOYSERVER_PATH + + +def pbtxt2json(content: str): + ''' + Convert protocol messages in text format to json format string. + ''' + message = text_format.Parse(content, ModelConfig()) + json_string = json_format.MessageToJson(message) + return json_string + + +def json2pbtxt(content: str): + ''' + Convert json format string to protocol messages in text format. + ''' + message = json_format.Parse(content, ModelConfig()) + text_proto = text_format.MessageToString(message) + return text_proto + + +def validate_data(model_config): + ''' + Validate data in model config, we should check empty value recieved from front end. + The easiest way to handle it is to drop empty value. + Args: + model_config: model config to be saved in config file + Return: + model config after filtering. + ''' + model_config_filtered = {} + for key, value in model_config.items(): + if value: + model_config_filtered[key] = value + return model_config_filtered + + +def analyse_config(cur_dir: str): + ''' + Analyse the model config in specified directory. + Return a json object to describe configuration. + ''' + all_model_configs = {} + all_model_versions = {} + parent_dir, sub_dirs, filenames = os.walk(cur_dir).send( + None) # models can only put directory in model repository, + # so we should only search depth 1 directories. + for model_dir_name in sub_dirs: + model_dir, model_sub_dirs, filenames = os.walk( + os.path.join(parent_dir, model_dir_name)).send(None) + model_name = os.path.basename(model_dir) + config_filenames = [] + for filename in filenames: + if '.pbtxt' in filename: + config_filenames.append( + filename + ) # filenames with extension .pbtxt are all config files + if config_filenames: + default_config_filename = config_filenames[0] + if 'config.pbtxt' in config_filenames: + default_config_filename = 'config.pbtxt' + config_filenames.remove(default_config_filename) + config_filenames.insert(0, default_config_filename) + else: + # if no config.pbtxt, we choose the first file in config_filenames list to create config.pbtxt + copy_config_file_to_default_config(model_dir, + default_config_filename) + default_config_filename = 'config.pbtxt' + config_filenames.insert(0, default_config_filename) + json_config = json.loads( + pbtxt2json( + open(os.path.join(model_dir, + default_config_filename)).read())) + json_config["config_filenames"] = config_filenames[ + 0] # add config_filenames to config data (frontend developer said he only wanted one filename, + # and to request config_filenames by get_config_filenames_for_one_model later) + all_model_configs[ + model_name] = json_config # store original config file content in json format + json_config[ + 'name'] = model_name # because name in config data may be different from model_name, + # model_name is model directory name actually, we should conform name with model_name. + else: + continue + for model_sub_dir in model_sub_dirs: + if re.match( + r'\d+', + model_sub_dir): # version directory consists of numbers + if model_name not in all_model_versions: + all_model_versions[model_name] = {} + if model_sub_dir not in all_model_versions[model_name]: + all_model_versions[model_name][model_sub_dir] = [] + for version_resource_file in os.listdir( + os.path.join(model_dir, model_sub_dir)): + all_model_versions[model_name][model_sub_dir].append( + version_resource_file) + if model_name not in all_model_versions: # if a model has config but no version directory, + # to convenient users, we create one + all_model_versions[model_name] = {} + os.mkdir(os.path.join(model_dir, '1')) + all_model_versions[model_name]['1'] = [] + + if not all_model_configs: + raise Exception( + 'The path you choose is not a valid model repository, please choose a valid path.' + ) + return all_model_configs, all_model_versions + + +def exchange_format_to_original_format(exchange_format): + ''' + Change config exchange format to original format. + ''' + ensembles = [] + models = [] + all_models = {} + if 'ensembles' in exchange_format: + ensembles = exchange_format['ensembles'] + if 'models' in exchange_format: + models = exchange_format['models'] + alls = ensembles + models + for model_config in alls: + # 1. add 'executionAccelerators' keyword + if 'optimization' in model_config: + optimization_config = model_config['optimization'] + del model_config['optimization'] + model_config['optimization'] = {} + model_config['optimization'][ + 'executionAccelerators'] = optimization_config + # 2. delete versions information + if 'versions' in model_config: + del model_config['versions'] + if 'config_filenames' in model_config: + del model_config['config_filenames'] + if 'platform' in model_config and model_config[ + 'platform'] == 'ensemble': # emsemble model + # 3. add 'ensembleScheduling' keyword + if 'step' in model_config: + step_configs = model_config['step'] + if 'ensembleScheduling' not in model_config: + model_config['ensembleScheduling'] = {} + model_config['ensembleScheduling']['step'] = step_configs + del model_config['step'] + # 4. remove two virtual models(feed, fetch), and + # "modelType", "inputModels", "outputModels", "inputVars", "outputVars" + remove_list = [] + for model_config_in_step in step_configs: + if model_config_in_step[ + 'modelName'] == 'feed' or model_config_in_step[ + 'modelName'] == 'fetch': + remove_list.append(model_config_in_step) + continue + del model_config_in_step['modelType'] + del model_config_in_step['inputModels'] + del model_config_in_step['outputModels'] + del model_config_in_step['inputVars'] + del model_config_in_step['outputVars'] + for remove_item in remove_list: + step_configs.remove(remove_item) + all_models[model_config['name']] = model_config + return all_models + + +def copy_config_file_to_default_config(model_dir, config_name): + json_config = json.loads( + pbtxt2json(open(os.path.join(model_dir, config_name)).read())) + model_name = os.path.basename(model_dir) + json_config['name'] = model_name + text_proto = json2pbtxt(json.dumps(json_config)) + with open(os.path.join(model_dir, 'config.pbtxt'), 'w') as f: + f.write(text_proto) + + +def original_format_to_exchange_format(original_format, version_info): + ''' + Change config original format to exchange format. + ''' + exchange_format = {} + exchange_format['ensembles'] = [] + exchange_format['models'] = [] + # 0. transform version info into component format in frontend + for model_name, version_filenames_dict in version_info.items(): + version_info_for_frontend = [] + for version_name, filenames in version_filenames_dict.items(): + version_filenames_dict_for_frontend = {} + version_filenames_dict_for_frontend['title'] = version_name + version_filenames_dict_for_frontend['key'] = version_name + version_filenames_dict_for_frontend['children'] = [] + for filename in filenames: + version_filenames_dict_for_frontend['children'].append({ + 'title': + filename, + 'key': + filename + }) + version_info_for_frontend.append( + version_filenames_dict_for_frontend) + version_info[model_name] = version_info_for_frontend + + for model_name, model_config in original_format.items(): + # 1. remove 'executionAccelerators' keyword + transformed_config = copy.deepcopy(model_config) + if 'optimization' in model_config: + if 'executionAccelerators' in model_config['optimization']: + transformed_optimization_config = model_config['optimization'][ + 'executionAccelerators'] + del transformed_config['optimization'] + transformed_config[ + 'optimization'] = transformed_optimization_config + # 2. add versions information + if model_name in version_info: + transformed_config['versions'] = version_info[model_name] + if 'platform' in model_config and model_config[ + 'platform'] == 'ensemble': # emsemble model + # 3. remove ensembleScheduling + if 'ensembleScheduling' in model_config: + if 'step' in model_config['ensembleScheduling']: + del transformed_config['ensembleScheduling'] + transformed_config['step'] = model_config[ + 'ensembleScheduling']['step'] + # 4. add two virtual models(feed, fetch), and + # "modelType", "inputModels", "outputModels", "inputVars", "outputVars" + for model_config_in_step in transformed_config['step']: + model_config_in_step['modelType'] = 'normal' + model_config_in_step['inputModels'] = [] + model_config_in_step['outputModels'] = [] + model_config_in_step['inputVars'] = [] + model_config_in_step['outputVars'] = [] + + transformed_config['step'].append({ + "modelName": "feed", + "modelType": "virtual", + "inputModels": [], + "outputModels": [], + "inputVars": [], + "outputVars": [] + }) + transformed_config['step'].append({ + "modelName": "fetch", + "modelType": "virtual", + "inputModels": [], + "outputModels": [], + "inputVars": [], + "outputVars": [] + }) + analyse_step_relationships(transformed_config['step'], + transformed_config['input'], + transformed_config['output']) + exchange_format['ensembles'].append(transformed_config) + elif 'backend' in model_config: # single model + exchange_format['models'].append(transformed_config) + return exchange_format + + +def analyse_step_relationships(step_config, inputs, outputs): # noqa: C901 + ''' + Analyse model relationships in ensemble step. And fill \ + "inputModels", "outputModels", "inputVars", "outputVars" in step_config. + step_config: step data in ensemble model config. + inputs: inputs in ensemble model config. + outputs: outputs in ensemble model config. + ''' + models_dict = {} + vars_dict = {} + for model_config_in_step in step_config: + models_dict[model_config_in_step['modelName']] = model_config_in_step + if model_config_in_step['modelType'] == 'virtual': + for var in inputs: + if var['name'] not in vars_dict: + vars_dict[var['name']] = {} + vars_dict[var['name']]['from_models'] = set() + vars_dict[var['name']]['to_models'] = set() + vars_dict[var['name']]['from_models'].add('feed') + for var in outputs: + if var['name'] not in vars_dict: + vars_dict[var['name']] = {} + vars_dict[var['name']]['from_models'] = set() + vars_dict[var['name']]['to_models'] = set() + vars_dict[var['name']]['to_models'].add('fetch') + else: + for var_placehold_name, var_name in model_config_in_step[ + 'inputMap'].items(): + if var_name not in vars_dict: + vars_dict[var_name] = {} + vars_dict[var_name]['from_models'] = set() + vars_dict[var_name]['to_models'] = set() + vars_dict[var_name]['to_models'].add( + model_config_in_step['modelName']) + + for var_placehold_name, var_name in model_config_in_step[ + 'outputMap'].items(): + if var_name not in vars_dict: + vars_dict[var_name] = {} + vars_dict[var_name]['from_models'] = set() + vars_dict[var_name]['to_models'] = set() + vars_dict[var_name]['from_models'].add( + model_config_in_step['modelName']) + for var_name, relationships in vars_dict.items(): + for from_model in relationships['from_models']: + models_dict[from_model]['outputVars'].append(var_name) + for var_to_model in relationships['to_models']: + if var_to_model not in models_dict[from_model]['outputModels']: + models_dict[from_model]['outputModels'].append( + var_to_model) + for to_model in relationships['to_models']: + models_dict[to_model]['inputVars'].append(var_name) + for var_from_model in relationships['from_models']: + if var_from_model not in models_dict[to_model]['inputModels']: + models_dict[to_model]['inputModels'].append(var_from_model) + calculate_layout_for_frontend(models_dict) + + +def get_config_filenames_for_one_model(cur_dir, name): + _, _, filenames = os.walk(os.path.join(cur_dir, name)).send(None) + config_filenames = [] + backup_config_filenames = [] + for filename in filenames: + if '.pbtxt' in filename and 'vdlbackup' not in filename: + config_filenames.append( + filename + ) # filenames with extension .pbtxt and not contain 'vdlbackup' are normal config files + elif '.pbtxt' in filename and 'vdlbackup' in filename: + backup_config_filenames.append( + filename + ) # filenames with extension .pbtxt and contain 'vdlbackup' are backup config files + config_filenames = sorted(config_filenames) + sorted( + backup_config_filenames) + return config_filenames + + +def get_config_for_one_model(cur_dir, name, config_filename): + all_model_configs = {} + all_model_versions = {} + filename = os.path.join(cur_dir, name, config_filename) + json_config = json.loads(pbtxt2json(open(filename).read())) + json_config[ + 'name'] = name # because name in config data may be different from model_name, + # model_name is model directory name actually, we should conform name with model_name. + json_config["config_filenames"] = config_filename + all_model_configs[ + name] = json_config # store original config file content in json format + all_model_versions[name] = {} + for model_sub_dir in os.listdir(os.path.join(cur_dir, name)): + if re.match(r'\d+', + model_sub_dir): # version directory consists of numbers + if model_sub_dir not in all_model_versions[name]: + all_model_versions[name][model_sub_dir] = [] + for version_resource_file in os.listdir( + os.path.join(cur_dir, name, model_sub_dir)): + all_model_versions[name][model_sub_dir].append( + version_resource_file) + model_config = original_format_to_exchange_format(all_model_configs, + all_model_versions) + if model_config['ensembles']: + return model_config['ensembles'][0] + elif model_config['models']: + return model_config['models'][0] + + +def calculate_layout_for_frontend(model_config_in_step): + ''' + Analyse model topology connections and prepare the positions for each model in layout. + Dynamic program algorithm: + depth(cur_node) = max([depth(prev_node) for prev_node in cur_node['inputModels']]) + Args: + model_config_in_step(dict): model config in ensemble models' step, indexed by model name. + Returns: + None. Results calculated will be saved in place. + ''' + path_depth = defaultdict(int) + + def depth_recursive(model): + if model['modelName'] == 'feed': + path_depth[model['modelName']] = 0 + return 0 + if path_depth[model['modelName']] != 0: + return path_depth[model['modelName']] + path_depth[model['modelName']] = max([ + depth_recursive(model_config_in_step[model_name]) for model_name in + model_config_in_step[model['modelName']]['inputModels'] + ]) + 1 + return path_depth[model['modelName']] + + depth_recursive(model_config_in_step['fetch']) + path_depth_tuple = [ + (k, v) + for k, v in sorted(path_depth.items(), key=lambda item: item[1]) + ] + cur_x = 0 + last_depth = -1 + for model_name, depth in path_depth_tuple: + if depth == last_depth: + model_config_in_step[model_name]['pos_y'] = depth + model_config_in_step[model_name]['pos_x'] = cur_x + cur_x += 1 + else: + cur_x = 0 + model_config_in_step[model_name]['pos_y'] = depth + model_config_in_step[model_name]['pos_x'] = cur_x + cur_x += 1 + last_depth = depth + return + + +def launch_process(kwargs: dict): + ''' + Launch a fastdeploy server according to specified arguments. + ''' + cmd = ['fastdeployserver'] + launch_env = os.environ.copy() + start_args = {} + for key, value in kwargs.items(): + if key == 'default_model_name': # Used to fill client model_name automatically + start_args[key] = value + continue + if key == 'server-name' or key == 'ensemble-img': # extra information + start_args[key] = value + continue + if key == 'gpus': + if value: + launch_env['CUDA_VISIBLE_DEVICES'] = value + start_args[key] = value + continue + cmd.append('--{}'.format(key)) + cmd.append('{}'.format(value)) + start_args[key] = value + if start_args['server-name'] and start_args['server-name'] in os.listdir( + FASTDEPLOYSERVER_PATH): + raise RuntimeError( + "Failed to launch server,server name {} has been used,please write a different server name." + .format(start_args['server-name'])) + all_model_configs, all_model_versions = analyse_config( + start_args['model-repository']) + model_repo_config = original_format_to_exchange_format( + all_model_configs, all_model_versions) + model_repo_config['ensemble-img'] = start_args['ensemble-img'] + logfilename = 'logfile-{}'.format(get_random_string(8)) + while os.path.exists(os.path.join(FASTDEPLOYSERVER_PATH, logfilename)): + logfilename = 'logfile-{}'.format(get_random_string(8)) + try: + p = Popen( + cmd, + stdout=open( + os.path.join(FASTDEPLOYSERVER_PATH, logfilename), + 'w', + buffering=1), + stderr=STDOUT, + universal_newlines=True, + env=launch_env) + except Exception: + raise RuntimeError( + "Failed to launch fastdeployserver,please check fastdeployserver is installed in environment." + ) + server_name = start_args['server-name'] if start_args[ + 'server-name'] else p.pid + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_name)), + 'w') as f: + # filename ${server_name} contain 4 lines: + # line1 : the real log filename ${logfilename} + # line2 : pid + # line3 : launch arguments + # line4 : model-repository configuration + f.write(logfilename + '\n' + str(p.pid) + '\n' + + json.dumps(start_args) + '\n' + json.dumps(model_repo_config)) + return p + + +def get_random_string(length): + # choose from all lowercase letter + letters = string.ascii_lowercase + result_str = ''.join([random.choice(letters) for i in range(length)]) + return result_str + + +def get_start_arguments(server_id): + ''' + Get the start arguments for fastdeployserver process. + Args: + server_id(str): fastdeployserver process name + Returns: + args(dict): launch arguments when start fastdeployserver process. + ''' + args = {} + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'r') as f: + arguments_json = f.read().split('\n')[2] + args = json.loads(arguments_json) + return args + + +def get_process_pid(server_id): + ''' + Get the process id for fastdeployserver process. + Args: + server_id(str): fastdeployserver process name + Returns: + pid(int): process id. + ''' + pid = None + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'r') as f: + pid = int(f.read().split('\n')[1]) + return pid + + +def get_process_logfile_name(server_id): + ''' + Get the process logfile name for fastdeployserver process. + Args: + server_id(str): fastdeployserver process name + Returns: + logfile(str): logfile name. + ''' + filename = None + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'r') as f: + filename = f.read().split('\n')[0] + return filename + + +def get_process_model_configuration(server_id): + ''' + Get the model repository configuration for fastdeployserver process. + Args: + server_id(str): fastdeployserver process name + Returns: + configuration(dict): model repository configuration + ''' + conf = {} + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'r') as f: + conf_json = f.read().split('\n')[3] + conf = json.loads(conf_json) + return conf + + +def get_process_output(server_id, length): + ''' + Get the standard output of a opened subprocess. + ''' + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + logfilename = get_process_logfile_name(server_id) + # delete file ${logfilename} if exists + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(logfilename))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, + '{}'.format(logfilename)), 'r') as f: + f.seek(length) + data = f.read() + return data + + +def mark_pid_for_dead_process(server_id): + ''' + Resource files for a dead server only deleted when user closes the server in frontend. + When user close the server, pid recorded in logfile will be killed. + In case a dead process id is reassigned for a new process, we should mark the pid recorded in logfile as outdated. + Here, we choose to replace the pid to -1 in logfile to denote the zombie process \ + which has been polled and becomes dead. + Args: + server_id(str): fastdeployserver process name + ''' + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'r') as f: + contents = f.read().split('\n') + contents[1] = '-1' # we replace pid to -1 + with open( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id)), + 'w') as f: + f.write('\n'.join(contents)) + + +def delete_files_for_process(server_id): + ''' + Delete logfile for fastdeployserver process. + Args: + server_id(str): fastdeployserver process name + ''' + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))): + logfilename = get_process_logfile_name(server_id) + # delete file ${logfilename} if exists + if os.path.exists( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(logfilename))): + os.remove( + os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(logfilename))) + os.remove(os.path.join(FASTDEPLOYSERVER_PATH, '{}'.format(server_id))) + + +def kill_process(process): + ''' + Stop a opened subprocess. + ''' + if type(process) == str: # server_id, use os.kill to terminate + pid = get_process_pid(process) + if pid == -1: # we use -1 to mark dead process + return + try: + os.kill(pid, signal.SIGKILL) + except Exception: + pass + else: + pid = process.pid + process.kill() + try: + process.wait(10) + except Exception: + pass + + +def get_alive_fastdeploy_servers(): + ''' + Search server names in `FASTDEPLOYSERVER_PATH`, if process is dead and log still exists due to \ + some unexpectable reasons, delete log file. + ''' + server_names = [ + name for name in os.listdir(FASTDEPLOYSERVER_PATH) + if 'logfile' not in name + ] + should_delete_servers = [] + for server_name in server_names: + if check_process_alive(server_name) is False: + delete_files_for_process(server_name) + should_delete_servers.append(server_name) + for server_name in should_delete_servers: + server_names.remove(server_name) + return server_names + + +def check_process_zombie(server_id): + ''' + Given a server id, check whether the process became zoombie and mark pid as -1. + Args: + server_id(str): fastdeployserver process name + Return: + status(bool): True if process became zoombie. + ''' + pid = get_process_pid(server_id) + if pid == -1: + return True + else: + return False + + +def check_process_alive(server_id): + ''' + Given a server id, check whether the process is alive or not. + Args: + server_id(str): fastdeployserver process name + Return: + status(bool): True if process is still alive. + ''' + pid = get_process_pid(server_id) + if pid is None: + return False + if pid == -1: # We use -1 to mark zombie process which has been dead process. + # Consider user wants to know the reason for dead process due to exception, + # we return True to let user in frontend can get the log for dead process. + return True + try: + os.kill(pid, 0) + except OSError: + return False + else: + if 'fastdeployserve' not in psutil.Process(pid).name( + ): # We should judge the pid is fastdeployserver process, in case pid has been reassigned. + # Note: I do not know why psutil.Process(pid).name() is fastdeployserve but not fastdeployserver. + return False + else: + return True + + +_metric_column_name = { + "Model": { + "nv_inference_request_success", "nv_inference_request_failure", + "nv_inference_count", "nv_inference_exec_count", + "nv_inference_request_duration_us", "nv_inference_queue_duration_us", + "nv_inference_compute_input_duration_us", + "nv_inference_compute_infer_duration_us", + "nv_inference_compute_output_duration_us" + }, + "GPU": { + "nv_gpu_power_usage", "nv_gpu_power_limit", "nv_energy_consumption", + "nv_gpu_utilization", "nv_gpu_memory_total_bytes", + "nv_gpu_memory_used_bytes" + }, + "CPU": { + "nv_cpu_utilization", "nv_cpu_memory_total_bytes", + "nv_cpu_memory_used_bytes" + } +} + + +def generate_metric_table(server_addr, server_port): # noqa:C901 + model_table = {} + gpu_table = {} + try: + res = requests.get("http://{}:{}/metrics".format( + server_addr, server_port)) + except Exception: + return None + metric_content = res.text + for content in metric_content.split('\n'): + if content.startswith('#'): + continue + else: + res = re.match(r'(\w+){(.*)} (\w+)', + content) # match output by server metrics interface + if not res: + continue + metric_name = res.group(1) + model = res.group(2) + value = res.group(3) + infos = {} + for info in model.split(','): + k, v = info.split('=') + v = v.strip('"') + infos[k] = v + if metric_name in [ + "nv_inference_request_duration_us", + "nv_inference_queue_duration_us", + "nv_inference_compute_input_duration_us", + "nv_inference_compute_infer_duration_us", + "nv_inference_compute_output_duration_us" + ]: + value = float(value) / 1000 + elif metric_name in [ + "nv_gpu_memory_total_bytes", "nv_gpu_memory_used_bytes" + ]: + value = float(value) / 1024 / 1024 / 1024 + for key, metric_names in _metric_column_name.items(): + if metric_name in metric_names: + if key == 'Model': + model_name = infos['model'] + if model_name not in model_table: + model_table[model_name] = {} + model_table[model_name][metric_name] = value + elif key == 'GPU': + gpu_name = infos['gpu_uuid'] + if gpu_name not in gpu_table: + gpu_table[gpu_name] = {} + gpu_table[gpu_name][metric_name] = value + elif key == 'CPU': + pass + results = {} + results['Model'] = model_table + results['GPU'] = gpu_table + return results diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b6280329e542a9e7b2aad2f540032fc40c409ec3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/fastdeploy_server.py @@ -0,0 +1,451 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import datetime +import json +import os +import re +import shutil +import socket +import time +from multiprocessing import Process +from pathlib import Path + +import requests + +from .fastdeploy_client.client_app import create_gradio_client_app +from .fastdeploy_client.client_app import create_gradio_client_app_en +from .fastdeploy_lib import analyse_config +from .fastdeploy_lib import check_process_zombie +from .fastdeploy_lib import copy_config_file_to_default_config +from .fastdeploy_lib import delete_files_for_process +from .fastdeploy_lib import exchange_format_to_original_format +from .fastdeploy_lib import generate_metric_table +from .fastdeploy_lib import get_alive_fastdeploy_servers +from .fastdeploy_lib import get_config_filenames_for_one_model +from .fastdeploy_lib import get_config_for_one_model +from .fastdeploy_lib import get_process_model_configuration +from .fastdeploy_lib import get_process_output +from .fastdeploy_lib import get_start_arguments +from .fastdeploy_lib import json2pbtxt +from .fastdeploy_lib import kill_process +from .fastdeploy_lib import launch_process +from .fastdeploy_lib import mark_pid_for_dead_process +from .fastdeploy_lib import original_format_to_exchange_format +from .fastdeploy_lib import validate_data +from visualdl.server.api import gen_result +from visualdl.server.api import result +from visualdl.utils.dir import FASTDEPLOYSERVER_PATH + + +class FastDeployServerApi(object): + def __init__(self): + self.root_dir = Path(os.getcwd()) + self.opened_servers = { + } # Use to store the opened server process pid and process itself + self.client_port = None # Chinese version + self.client_en_port = None # English version + + @result() + def get_directory(self, cur_dir): + if self.root_dir not in Path(os.path.abspath(cur_dir)).parents: + cur_dir = '.' + cur_dir, sub_dirs, filenames = os.walk(cur_dir).send(None) + if Path(self.root_dir) != Path(os.path.abspath(cur_dir)): + sub_dirs.append('..') + sub_dirs = sorted(sub_dirs) + directorys = { + 'parent_dir': + os.path.relpath(Path(os.path.abspath(cur_dir)), self.root_dir), + 'sub_dir': + sub_dirs + } + return directorys + + @result() + def get_config(self, cur_dir): + all_model_configs, all_model_versions = analyse_config(cur_dir) + return original_format_to_exchange_format(all_model_configs, + all_model_versions) + + @result() + def config_update(self, cur_dir, model_name, config, config_filename): + config = json.loads(config) + all_models = exchange_format_to_original_format(config) + model_dir = os.path.join(os.path.abspath(cur_dir), model_name) + filtered_config = validate_data(all_models[model_name]) + text_proto = json2pbtxt(json.dumps(filtered_config)) + # backup user's config data first, when data corrupted by front-end, we still can recovery data + # backup config filename: {original_name}_vdlbackup_{datetime}.pbtxt + # backup config can only used to restore config.pbtxt + if 'vdlbackup' in config_filename: + raise RuntimeError( + "Backup config file is not permitted to update.") + basename = os.path.splitext(config_filename)[0] + shutil.copy( + os.path.join(model_dir, config_filename), + os.path.join( + model_dir, '{}_vdlbackup_{}.pbtxt'.format( + basename, + datetime.datetime.now().isoformat()))) + with open(os.path.join(model_dir, config_filename), 'w') as f: + f.write(text_proto) + return + + @result() + def start_server(self, configs): + configs = json.loads(configs) + process = launch_process(configs) + if process.poll() is not None: + raise RuntimeError( + "Failed to launch fastdeployserver,please check fastdeployserver is installed in environment." + ) + server_name = configs['server-name'] if configs[ + 'server-name'] else str(process.pid) + self.opened_servers[server_name] = process + return server_name + + @result() + def stop_server(self, server_id): + if server_id in self.opened_servers: # check if server_id in self.opened_servers + kill_process(self.opened_servers[server_id]) + del self.opened_servers[server_id] + elif server_id in set( + os.listdir(FASTDEPLOYSERVER_PATH)): # check if server_id in + # FASTDEPLOYSERVER_PATH(may be launched by other vdl app instance by gunicorn) + kill_process(server_id) + delete_files_for_process(server_id) + self._poll_zombie_process() + + @result('text/plain') + def get_server_output(self, server_id, length): + length = int(length) + if server_id in self.opened_servers: # check if server_id in self.opened_servers + return get_process_output(server_id, length) + elif str(server_id) in set( + os.listdir(FASTDEPLOYSERVER_PATH)): # check if server_id in + # FASTDEPLOYSERVER_PATH(may be launched by other vdl app instance by gunicorn) + return get_process_output(server_id, length) + else: + return + + @result() + def get_server_metric(self, server_id): + args = get_start_arguments(server_id) + host = 'localhost' + port = args.get('metrics-port', 8002) + return generate_metric_table(host, port) + + @result() + def get_server_list(self): + return get_alive_fastdeploy_servers() + + @result() + def check_server_alive(self, server_id): + self._poll_zombie_process() + if check_process_zombie(server_id) is True: + raise RuntimeError( + "Server {} is down due to exception or killed,please check the reason according to the log, " + "then close this server.".format(server_id)) + return + + @result() + def get_server_config(self, server_id): + return get_process_model_configuration(server_id) + + @result() + def get_pretrain_model_list(self): + ''' + Get all available fastdeploy models from hub server. + ''' + res = requests.get( + 'http://paddlepaddle.org.cn/paddlehub/fastdeploy_listmodels') + result = res.json() + if result['status'] != 0: + raise RuntimeError( + "Failed to get pre-trained model list from hub server.") + else: + data = result['data'] + model_list = {} + for category, models in data.items(): + if category not in model_list: + model_list[category] = set() + for model in models: + model_list[category].add(model['name']) + # adapt data format for frontend + models_info = [] + for category, model_names in model_list.items(): + models_info.append({ + "value": category, + "label": category, + "children": [] + }) + for model_name in sorted(model_names): + models_info[-1]["children"].append({ + "value": model_name, + "label": model_name + }) + return models_info + + @result() + def download_pretrain_model(self, cur_dir, model_name, version, + pretrain_model_name): + version_resource_dir = os.path.join( + os.path.abspath(cur_dir), model_name, version) + try: + import fastdeploy as fd + except Exception: + raise RuntimeError( + "fastdeploy is required for visualizing results,please refer to " + "https://github.com/PaddlePaddle/FastDeploy to install fastdeploy" + ) + model_path = fd.download_model( + name=pretrain_model_name, path=version_resource_dir) + if model_path: + if '.onnx' in model_path: + shutil.move( + model_path, + os.path.join(os.path.dirname(model_path), 'model.onnx')) + else: + for filename in os.listdir(model_path): + if '.pdmodel' in filename or '.pdiparams' in filename: + shutil.move( + os.path.join(model_path, filename), + os.path.join( + os.path.dirname(model_path), 'model{}'.format( + os.path.splitext(filename)[1]))) + else: + shutil.move( + os.path.join(model_path, filename), + os.path.join( + os.path.dirname(model_path), filename)) + shutil.rmtree(model_path) + version_info_for_frontend = [] + for version_name in os.listdir(os.path.join(cur_dir, model_name)): + if re.match( + r'\d+', + version_name): # version directory consists of numbers + version_filenames_dict_for_frontend = {} + version_filenames_dict_for_frontend['title'] = version_name + version_filenames_dict_for_frontend['key'] = version_name + version_filenames_dict_for_frontend['children'] = [] + for filename in os.listdir( + os.path.join(cur_dir, model_name, version_name)): + version_filenames_dict_for_frontend['children'].append( + { + 'title': filename, + 'key': filename + }) + version_info_for_frontend.append( + version_filenames_dict_for_frontend) + return version_info_for_frontend + else: + raise RuntimeError( + "Failed to download pre-trained model {}.".format( + pretrain_model_name)) + + @result() + def get_config_for_model(self, cur_dir, name, config_filename): + return get_config_for_one_model(cur_dir, name, config_filename) + + @result() + def get_config_filenames_for_model(self, cur_dir, name): + return get_config_filenames_for_one_model(cur_dir, name) + + @result() + def delete_config_for_model(self, cur_dir, name, config_filename): + if self.root_dir not in Path( + os.path.abspath(cur_dir) + ).parents: # should prevent user remove files outside model-repository + raise RuntimeError( + 'Failed to delete config file, please check filepath.') + if os.path.exists(os.path.join(cur_dir, name, config_filename)): + os.remove(os.path.join(cur_dir, name, config_filename)) + return get_config_filenames_for_one_model(cur_dir, name) + + @result() + def set_default_config_for_model(self, cur_dir, name, config_filename): + model_dir = os.path.join(os.path.abspath(cur_dir), name) + # backup config.pbtxt to config_vdlbackup_{datetime}.pbtxt + if os.path.exists(os.path.join(model_dir, 'config.pbtxt')): + shutil.copy( + os.path.join(model_dir, 'config.pbtxt'), + os.path.join( + model_dir, 'config_vdlbackup_{}.pbtxt'.format( + datetime.datetime.now().isoformat()))) + if config_filename != 'config.pbtxt': + copy_config_file_to_default_config(model_dir, config_filename) + return + + @result() + def delete_resource_for_model(self, cur_dir, model_name, version, + resource_filename): + if self.root_dir not in Path( + os.path.abspath(cur_dir) + ).parents: # should prevent user remove files outside model-repository + raise RuntimeError( + 'Failed to delete resource file, please check filepath.') + resource_path = os.path.join( + os.path.abspath(cur_dir), model_name, version, resource_filename) + if os.path.exists(resource_path): + os.remove(resource_path) + version_info_for_frontend = [] + for version_name in os.listdir(os.path.join(cur_dir, model_name)): + if re.match(r'\d+', + version_name): # version directory consists of numbers + version_filenames_dict_for_frontend = {} + version_filenames_dict_for_frontend['title'] = version_name + version_filenames_dict_for_frontend['key'] = version_name + version_filenames_dict_for_frontend['children'] = [] + for filename in os.listdir( + os.path.join(cur_dir, model_name, version_name)): + version_filenames_dict_for_frontend['children'].append({ + 'title': + filename, + 'key': + filename + }) + version_info_for_frontend.append( + version_filenames_dict_for_frontend) + return version_info_for_frontend + + @result() + def rename_resource_for_model(self, cur_dir, model_name, version, + resource_filename, new_filename): + if self.root_dir not in Path( + os.path.abspath(cur_dir) + ).parents: # should prevent user remove files outside model-repository + raise RuntimeError( + 'Failed to rename resource file, please check filepath.') + resource_path = os.path.join( + os.path.abspath(cur_dir), model_name, version, resource_filename) + new_file_path = os.path.join( + os.path.abspath(cur_dir), model_name, version, new_filename) + if os.path.exists(resource_path): + shutil.move(resource_path, new_file_path) + version_info_for_frontend = [] + for version_name in os.listdir(os.path.join(cur_dir, model_name)): + if re.match(r'\d+', + version_name): # version directory consists of numbers + version_filenames_dict_for_frontend = {} + version_filenames_dict_for_frontend['title'] = version_name + version_filenames_dict_for_frontend['key'] = version_name + version_filenames_dict_for_frontend['children'] = [] + for filename in os.listdir( + os.path.join(cur_dir, model_name, version_name)): + version_filenames_dict_for_frontend['children'].append({ + 'title': + filename, + 'key': + filename + }) + version_info_for_frontend.append( + version_filenames_dict_for_frontend) + return version_info_for_frontend + + def create_fastdeploy_client(self, lang='zh'): + def get_free_tcp_port(): + tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + tcp.bind(('localhost', 0)) + addr, port = tcp.getsockname() + tcp.close() + return port + + def check_alive(client_port): + while True: + try: + requests.get('http://localhost:{}/'.format(client_port)) + break + except Exception: + time.sleep(1) + + if lang == 'en': + if self.client_en_port is None: + self.client_en_port = get_free_tcp_port() + app = create_gradio_client_app_en() + thread = Process( + target=app.launch, + kwargs={'server_port': self.client_en_port}) + thread.start() + check_alive(self.client_en_port) + return self.client_en_port + else: + if self.client_port is None: + self.client_port = get_free_tcp_port() + app = create_gradio_client_app() + thread = Process( + target=app.launch, + kwargs={'server_port': self.client_port}) + thread.start() + check_alive(self.client_port) + return self.client_port + + def _poll_zombie_process(self): + # check if there are servers killed by other vdl app instance and become zoombie + should_delete = [] + for server_id, process in self.opened_servers.items(): + if process.poll() is not None: + mark_pid_for_dead_process(server_id) + should_delete.append(server_id) + + for server_id in should_delete: + del self.opened_servers[server_id] + + +def create_fastdeploy_api_call(): + api = FastDeployServerApi() + routes = { + 'get_directory': (api.get_directory, ['dir']), + 'config_update': (api.config_update, + ['dir', 'name', 'config', 'config_filename']), + 'get_config': (api.get_config, ['dir']), + 'get_config_filenames_for_model': (api.get_config_filenames_for_model, + ['dir', 'name']), + 'get_config_for_model': (api.get_config_for_model, + ['dir', 'name', 'config_filename']), + 'set_default_config_for_model': (api.set_default_config_for_model, + ['dir', 'name', 'config_filename']), + 'delete_config_for_model': (api.delete_config_for_model, + ['dir', 'name', 'config_filename']), + 'start_server': (api.start_server, ['config']), + 'stop_server': (api.stop_server, ['server_id']), + 'get_server_output': (api.get_server_output, ['server_id', 'length']), + 'create_fastdeploy_client': (api.create_fastdeploy_client, ['lang']), + 'get_server_list': (api.get_server_list, []), + 'get_server_metric': (api.get_server_metric, ['server_id']), + 'get_server_config': (api.get_server_config, ['server_id']), + 'get_pretrain_model_list': (api.get_pretrain_model_list, []), + 'check_server_alive': (api.check_server_alive, ['server_id']), + 'download_pretrain_model': + (api.download_pretrain_model, + ['dir', 'name', 'version', 'pretrain_model_name']), + 'delete_resource_for_model': + (api.delete_resource_for_model, + ['dir', 'name', 'version', 'resource_filename']), + 'rename_resource_for_model': (api.rename_resource_for_model, [ + 'dir', 'name', 'version', 'resource_filename', 'new_filename' + ]) + } + + def call(path: str, args): + route = routes.get(path) + if not route: + return json.dumps(gen_result( + status=1, msg='api not found')), 'application/json', None + method, call_arg_names = route + call_args = [args.get(name) for name in call_arg_names] + return method(*call_args) + + return call diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/model_convert_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/model_convert_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28869432dc44503ae8aa0f7222c7eb7fe6b979bb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/model_convert_server.py @@ -0,0 +1,284 @@ +# flake8: noqa +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import base64 +import hashlib +import json +import os +import shutil +import tempfile + +import paddle +import paddle2onnx +from flask import request +from x2paddle.convert import onnx2paddle + +from .xarfile import archive +from visualdl.io.bfile import BosFileSystem +from visualdl.server.api import gen_result +from visualdl.server.api import result +from visualdl.utils.dir import X2PADDLE_CACHE_PATH + +_max_cache_numbers = 200 + + +class ModelConvertApi(object): + '''! + Integrate multiple model convertion tools, and provide convertion service for users. + When user uploads a model to this server, convert model and upload the results to VDL Bos. + When user downloads the model, we get the data from Bos and send it to client. + Maybe users can download from bos directy if frontend can achieve it. + ''' + + def __init__(self): + ''' + Initialize a object to provide service. Need a BosFileSystem client to write data. + ''' + try: + self.bos_client = BosFileSystem() + self.bucket_name = os.getenv("BOS_BUCKET_NAME") + except Exception: + # When BOS_HOST, BOS_AK, BOS_SK, BOS_STS are not set in the environment variables. + # We use VDL BOS by default + self.bos_client = BosFileSystem(write_flag=False) + self.bos_client.renew_bos_client_from_server() + self.bucket_name = 'visualdl-server' + + @result() + def onnx2paddle_model_convert(self, convert_to_lite, lite_valid_places, + lite_model_type): # noqa:C901 + ''' + Convert onnx model to paddle model. + ''' + model_handle = request.files['model'] + data = model_handle.stream.read() + result = {} + # Do a simple data verification + if convert_to_lite in ['true', 'True', 'yes', 'Yes', 'y']: + convert_to_lite = True + else: + convert_to_lite = False + + if lite_valid_places not in [ + 'arm', 'opencl', 'x86', 'metal', 'xpu', 'bm', 'mlu', + 'intel_fpga', 'huawei_ascend_npu', 'imagination_nna', + 'rockchip_npu', 'mediatek_apu', 'huawei_kirin_npu', + 'amlogic_npu' + ]: + lite_valid_places = 'arm' + if lite_model_type not in ['protobuf', 'naive_buffer']: + lite_model_type = 'naive_buffer' + + # call x2paddle to convert models + hl = hashlib.md5() + hl.update(data) + identity = hl.hexdigest() + result['request_id'] = identity + + target_path = os.path.join(X2PADDLE_CACHE_PATH, 'onnx2paddle', + identity) + if not os.path.exists(target_path): + os.makedirs(target_path, exist_ok=True) + with tempfile.NamedTemporaryFile() as fp: + fp.write(data) + fp.flush() + try: + import onnx # noqa: F401 + except Exception: + raise RuntimeError( + "[ERROR] onnx is not installed, use \"pip install onnx>=1.6.0\"." + ) + try: + if convert_to_lite is False: + with paddle.fluid.dygraph.guard(): + onnx2paddle( + fp.name, + target_path, + convert_to_lite=convert_to_lite) + else: + with paddle.fluid.dygraph.guard(): + onnx2paddle( + fp.name, + target_path, + convert_to_lite=convert_to_lite, + lite_valid_places=lite_valid_places, + lite_model_type=lite_model_type) + except Exception as e: + raise RuntimeError( + "[Convertion error] {}.\n Please open an issue at " + "https://github.com/PaddlePaddle/X2Paddle/issues to report your problem." + .format(e)) + + origin_dir = os.getcwd() + os.chdir(os.path.dirname(target_path)) + archive(os.path.basename(target_path)) + os.chdir(origin_dir) + with open( + os.path.join(X2PADDLE_CACHE_PATH, 'onnx2paddle', + '{}.tar'.format(identity)), 'rb') as f: + # upload archived transformed model to vdl bos + data = f.read() + filename = 'bos://{}/onnx2paddle/{}.tar'.format( + self.bucket_name, identity) + try: + self.bos_client.write(filename, data, append=False) + except Exception as e: + print( + "Exception: Write file {}.tar to bos failed, due to {}" + .format(identity, e)) + with open( + os.path.join(target_path, 'inference_model', 'model.pdmodel'), + 'rb') as model_fp: + # upload pdmodel file to bos, if some model has been transformed before, we can directly download from bos + filename = 'bos://{}/onnx2paddle/{}/model.pdmodel'.format( + self.bucket_name, identity) + data = model_fp.read() + try: + self.bos_client.write(filename, data) + except Exception as e: + print( + "Exception: Write file {}/model.pdmodel to bos failed, due to {}" + .format(identity, e)) + # return transformed pdmodel file to frontend to show model structure graph + model_encoded = base64.b64encode(data).decode('utf-8') + # delete target_path + shutil.rmtree(target_path) + result['model'] = model_encoded + print(len(model_encoded)) + return result + + @result('application/octet-stream') + def onnx2paddle_model_download(self, request_id): + ''' + Download converted paddle model from bos. + ''' + filename = 'bos://{}/onnx2paddle/{}.tar'.format( + self.bucket_name, request_id) + data = None + if self.bos_client.exists(filename): + data = self.bos_client.read_file(filename) + if not data: + raise RuntimeError( + "The requested model can not be downloaded due to not existing or convertion failed." + ) + print(len(data)) + return data + + @result() + def paddle2onnx_convert(self, opset_version, deploy_backend): + ''' + Convert paddle model to onnx model. + ''' + model_handle = request.files['model'] + params_handle = request.files['param'] + model_data = model_handle.stream.read() + param_data = params_handle.stream.read() + result = {} + # Do a simple data verification + try: + opset_version = int(opset_version) + except Exception: + opset_version = 11 + + if deploy_backend not in ['onnxruntime', 'tensorrt', 'others']: + deploy_backend = 'onnxruntime' + + # call paddle2onnx to convert models + hl = hashlib.md5() + hl.update(model_data + param_data) + identity = hl.hexdigest() + result['request_id'] = identity + + with tempfile.NamedTemporaryFile() as model_fp: + with tempfile.NamedTemporaryFile() as param_fp: + model_fp.write(model_data) + param_fp.write(param_data) + model_fp.flush() + param_fp.flush() + try: + onnx_model = paddle2onnx.export( + model_fp.name, + param_fp.name, + opset_version=opset_version, + deploy_backend=deploy_backend) + except Exception as e: + raise RuntimeError( + "[Convertion error] {}.\n Please open an issue at " + "https://github.com/PaddlePaddle/Paddle2ONNX/issues to report your problem." + .format(e)) + if not onnx_model: + raise RuntimeError( + "[Convertion error] Please check your input model and param files." + ) + + # upload transformed model to vdl bos + filename = 'bos://{}/paddle2onnx/{}/model.onnx'.format( + self.bucket_name, identity) + model_encoded = None + if onnx_model: + try: + self.bos_client.write( + filename, onnx_model, append=False) + except Exception as e: + print( + "Exception: Write file {}/model.onnx to bos failed, due to {}" + .format(identity, e)) + model_encoded = base64.b64encode(onnx_model).decode( + 'utf-8') + result['model'] = model_encoded + print(len(model_encoded)) + return result + + @result('application/octet-stream') + def paddle2onnx_download(self, request_id): + ''' + Download converted onnx model from bos. + ''' + filename = 'bos://{}/paddle2onnx/{}/model.onnx'.format( + self.bucket_name, request_id) + data = None + if self.bos_client.exists(filename): + data = self.bos_client.read_file(filename) + if not data: + raise RuntimeError( + "The requested model can not be downloaded due to not existing or convertion failed." + ) + print(len(data)) + return data + + +def create_model_convert_api_call(): + api = ModelConvertApi() + routes = { + 'paddle2onnx/convert': (api.paddle2onnx_convert, + ['opset_version', 'deploy_backend']), + 'paddle2onnx/download': (api.paddle2onnx_download, ['request_id']), + 'onnx2paddle/convert': + (api.onnx2paddle_model_convert, + ['convert_to_lite', 'lite_valid_places', 'lite_model_type']), + 'onnx2paddle/download': (api.onnx2paddle_model_download, + ['request_id']) + } + + def call(path: str, args): + route = routes.get(path) + if not route: + return json.dumps(gen_result( + status=1, msg='api not found')), 'application/json', None + method, call_arg_names = route + call_args = [args.get(name) for name in call_arg_names] + return method(*call_args) + + return call diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19f7b87ee86723af4d909e34a05647f7e40fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/model_config_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/model_config_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..769691003549fd9050f1fc3d5c22c695bf3f52c8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/proto/model_config_pb2.py @@ -0,0 +1,170 @@ +# flake8: noqa +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: model_config.protxt +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x13model_config.protxt\x12\tinference\"\x96\x01\n\x10ModelRateLimiter\x12\x37\n\tresources\x18\x01 \x03(\x0b\x32$.inference.ModelRateLimiter.Resource\x12\x10\n\x08priority\x18\x02 \x01(\r\x1a\x37\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06global\x18\x02 \x01(\x08\x12\r\n\x05\x63ount\x18\x03 \x01(\r\"\x87\x04\n\x12ModelInstanceGroup\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x30\n\x04kind\x18\x04 \x01(\x0e\x32\".inference.ModelInstanceGroup.Kind\x12\r\n\x05\x63ount\x18\x02 \x01(\x05\x12\x31\n\x0crate_limiter\x18\x06 \x01(\x0b\x32\x1b.inference.ModelRateLimiter\x12\x0c\n\x04gpus\x18\x03 \x03(\x05\x12H\n\x11secondary_devices\x18\x08 \x03(\x0b\x32-.inference.ModelInstanceGroup.SecondaryDevice\x12\x0f\n\x07profile\x18\x05 \x03(\t\x12\x0f\n\x07passive\x18\x07 \x01(\x08\x12\x13\n\x0bhost_policy\x18\t \x01(\t\x1a\x9c\x01\n\x0fSecondaryDevice\x12O\n\x04kind\x18\x01 \x01(\x0e\x32\x41.inference.ModelInstanceGroup.SecondaryDevice.SecondaryDeviceKind\x12\x11\n\tdevice_id\x18\x02 \x01(\x03\"%\n\x13SecondaryDeviceKind\x12\x0e\n\nKIND_NVDLA\x10\x00\"A\n\x04Kind\x12\r\n\tKIND_AUTO\x10\x00\x12\x0c\n\x08KIND_GPU\x10\x01\x12\x0c\n\x08KIND_CPU\x10\x02\x12\x0e\n\nKIND_MODEL\x10\x03\"#\n\x12ModelTensorReshape\x12\r\n\x05shape\x18\x01 \x03(\x03\"\xb2\x02\n\nModelInput\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\tdata_type\x18\x02 \x01(\x0e\x32\x13.inference.DataType\x12,\n\x06\x66ormat\x18\x03 \x01(\x0e\x32\x1c.inference.ModelInput.Format\x12\x0c\n\x04\x64ims\x18\x04 \x03(\x03\x12.\n\x07reshape\x18\x05 \x01(\x0b\x32\x1d.inference.ModelTensorReshape\x12\x17\n\x0fis_shape_tensor\x18\x06 \x01(\x08\x12\x1a\n\x12\x61llow_ragged_batch\x18\x07 \x01(\x08\x12\x10\n\x08optional\x18\x08 \x01(\x08\";\n\x06\x46ormat\x12\x0f\n\x0b\x46ORMAT_NONE\x10\x00\x12\x0f\n\x0b\x46ORMAT_NHWC\x10\x01\x12\x0f\n\x0b\x46ORMAT_NCHW\x10\x02\"\xb2\x01\n\x0bModelOutput\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\tdata_type\x18\x02 \x01(\x0e\x32\x13.inference.DataType\x12\x0c\n\x04\x64ims\x18\x03 \x03(\x03\x12.\n\x07reshape\x18\x05 \x01(\x0b\x32\x1d.inference.ModelTensorReshape\x12\x16\n\x0elabel_filename\x18\x04 \x01(\t\x12\x17\n\x0fis_shape_tensor\x18\x06 \x01(\x08\"\xd9\x02\n\nBatchInput\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.inference.BatchInput.Kind\x12\x13\n\x0btarget_name\x18\x02 \x03(\t\x12&\n\tdata_type\x18\x03 \x01(\x0e\x32\x13.inference.DataType\x12\x14\n\x0csource_input\x18\x04 \x03(\t\"\xcd\x01\n\x04Kind\x12\x17\n\x13\x42\x41TCH_ELEMENT_COUNT\x10\x00\x12#\n\x1f\x42\x41TCH_ACCUMULATED_ELEMENT_COUNT\x10\x01\x12-\n)BATCH_ACCUMULATED_ELEMENT_COUNT_WITH_ZERO\x10\x02\x12$\n BATCH_MAX_ELEMENT_COUNT_AS_SHAPE\x10\x03\x12\x14\n\x10\x42\x41TCH_ITEM_SHAPE\x10\x04\x12\x1c\n\x18\x42\x41TCH_ITEM_SHAPE_FLATTEN\x10\x05\"\x8f\x01\n\x0b\x42\x61tchOutput\x12\x13\n\x0btarget_name\x18\x01 \x03(\t\x12)\n\x04kind\x18\x02 \x01(\x0e\x32\x1b.inference.BatchOutput.Kind\x12\x14\n\x0csource_input\x18\x03 \x03(\t\"*\n\x04Kind\x12\"\n\x1e\x42\x41TCH_SCATTER_WITH_INPUT_SHAPE\x10\x00\"\x90\x02\n\x12ModelVersionPolicy\x12\x36\n\x06latest\x18\x01 \x01(\x0b\x32$.inference.ModelVersionPolicy.LatestH\x00\x12\x30\n\x03\x61ll\x18\x02 \x01(\x0b\x32!.inference.ModelVersionPolicy.AllH\x00\x12:\n\x08specific\x18\x03 \x01(\x0b\x32&.inference.ModelVersionPolicy.SpecificH\x00\x1a\x1e\n\x06Latest\x12\x14\n\x0cnum_versions\x18\x01 \x01(\r\x1a\x05\n\x03\x41ll\x1a\x1c\n\x08Specific\x12\x10\n\x08versions\x18\x01 \x03(\x03\x42\x0f\n\rpolicy_choice\"\xfd\r\n\x17ModelOptimizationPolicy\x12\x37\n\x05graph\x18\x01 \x01(\x0b\x32(.inference.ModelOptimizationPolicy.Graph\x12\x42\n\x08priority\x18\x02 \x01(\x0e\x32\x30.inference.ModelOptimizationPolicy.ModelPriority\x12\x35\n\x04\x63uda\x18\x03 \x01(\x0b\x32\'.inference.ModelOptimizationPolicy.Cuda\x12X\n\x16\x65xecution_accelerators\x18\x04 \x01(\x0b\x32\x38.inference.ModelOptimizationPolicy.ExecutionAccelerators\x12R\n\x13input_pinned_memory\x18\x05 \x01(\x0b\x32\x35.inference.ModelOptimizationPolicy.PinnedMemoryBuffer\x12S\n\x14output_pinned_memory\x18\x06 \x01(\x0b\x32\x35.inference.ModelOptimizationPolicy.PinnedMemoryBuffer\x12&\n\x1egather_kernel_buffer_threshold\x18\x07 \x01(\r\x12\x16\n\x0e\x65\x61ger_batching\x18\x08 \x01(\x08\x1a\x16\n\x05Graph\x12\r\n\x05level\x18\x01 \x01(\x05\x1a\xba\x05\n\x04\x43uda\x12\x0e\n\x06graphs\x18\x01 \x01(\x08\x12\x18\n\x10\x62usy_wait_events\x18\x02 \x01(\x08\x12\x45\n\ngraph_spec\x18\x03 \x03(\x0b\x32\x31.inference.ModelOptimizationPolicy.Cuda.GraphSpec\x12\x1a\n\x12output_copy_stream\x18\x04 \x01(\x08\x1a\xa4\x04\n\tGraphSpec\x12\x12\n\nbatch_size\x18\x01 \x01(\x05\x12K\n\x05input\x18\x02 \x03(\x0b\x32<.inference.ModelOptimizationPolicy.Cuda.GraphSpec.InputEntry\x12W\n\x11graph_lower_bound\x18\x03 \x01(\x0b\x32<.inference.ModelOptimizationPolicy.Cuda.GraphSpec.LowerBound\x1a\x14\n\x05Shape\x12\x0b\n\x03\x64im\x18\x01 \x03(\x03\x1a\xdf\x01\n\nLowerBound\x12\x12\n\nbatch_size\x18\x01 \x01(\x05\x12V\n\x05input\x18\x02 \x03(\x0b\x32G.inference.ModelOptimizationPolicy.Cuda.GraphSpec.LowerBound.InputEntry\x1a\x65\n\nInputEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x46\n\x05value\x18\x02 \x01(\x0b\x32\x37.inference.ModelOptimizationPolicy.Cuda.GraphSpec.Shape:\x02\x38\x01\x1a\x65\n\nInputEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x46\n\x05value\x18\x02 \x01(\x0b\x32\x37.inference.ModelOptimizationPolicy.Cuda.GraphSpec.Shape:\x02\x38\x01\x1a\xa4\x03\n\x15\x45xecutionAccelerators\x12g\n\x19gpu_execution_accelerator\x18\x01 \x03(\x0b\x32\x44.inference.ModelOptimizationPolicy.ExecutionAccelerators.Accelerator\x12g\n\x19\x63pu_execution_accelerator\x18\x02 \x03(\x0b\x32\x44.inference.ModelOptimizationPolicy.ExecutionAccelerators.Accelerator\x1a\xb8\x01\n\x0b\x41\x63\x63\x65lerator\x12\x0c\n\x04name\x18\x01 \x01(\t\x12h\n\nparameters\x18\x02 \x03(\x0b\x32T.inference.ModelOptimizationPolicy.ExecutionAccelerators.Accelerator.ParametersEntry\x1a\x31\n\x0fParametersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a$\n\x12PinnedMemoryBuffer\x12\x0e\n\x06\x65nable\x18\x01 \x01(\x08\"I\n\rModelPriority\x12\x14\n\x10PRIORITY_DEFAULT\x10\x00\x12\x10\n\x0cPRIORITY_MAX\x10\x01\x12\x10\n\x0cPRIORITY_MIN\x10\x02\"\xdb\x01\n\x10ModelQueuePolicy\x12\x41\n\x0etimeout_action\x18\x01 \x01(\x0e\x32).inference.ModelQueuePolicy.TimeoutAction\x12$\n\x1c\x64\x65\x66\x61ult_timeout_microseconds\x18\x02 \x01(\x04\x12\x1e\n\x16\x61llow_timeout_override\x18\x03 \x01(\x08\x12\x16\n\x0emax_queue_size\x18\x04 \x01(\r\"&\n\rTimeoutAction\x12\n\n\x06REJECT\x10\x00\x12\t\n\x05\x44\x45LAY\x10\x01\"\x9b\x03\n\x14ModelDynamicBatching\x12\x1c\n\x14preferred_batch_size\x18\x01 \x03(\x05\x12$\n\x1cmax_queue_delay_microseconds\x18\x02 \x01(\x04\x12\x19\n\x11preserve_ordering\x18\x03 \x01(\x08\x12\x17\n\x0fpriority_levels\x18\x04 \x01(\r\x12\x1e\n\x16\x64\x65\x66\x61ult_priority_level\x18\x05 \x01(\r\x12\x39\n\x14\x64\x65\x66\x61ult_queue_policy\x18\x06 \x01(\x0b\x32\x1b.inference.ModelQueuePolicy\x12W\n\x15priority_queue_policy\x18\x07 \x03(\x0b\x32\x38.inference.ModelDynamicBatching.PriorityQueuePolicyEntry\x1aW\n\x18PriorityQueuePolicyEntry\x12\x0b\n\x03key\x18\x01 \x01(\r\x12*\n\x05value\x18\x02 \x01(\x0b\x32\x1b.inference.ModelQueuePolicy:\x02\x38\x01\"\xef\t\n\x15ModelSequenceBatching\x12\x41\n\x06\x64irect\x18\x03 \x01(\x0b\x32/.inference.ModelSequenceBatching.StrategyDirectH\x00\x12\x41\n\x06oldest\x18\x04 \x01(\x0b\x32/.inference.ModelSequenceBatching.StrategyOldestH\x00\x12&\n\x1emax_sequence_idle_microseconds\x18\x01 \x01(\x04\x12\x44\n\rcontrol_input\x18\x02 \x03(\x0b\x32-.inference.ModelSequenceBatching.ControlInput\x12\x35\n\x05state\x18\x05 \x03(\x0b\x32&.inference.ModelSequenceBatching.State\x1a\xb1\x02\n\x07\x43ontrol\x12;\n\x04kind\x18\x01 \x01(\x0e\x32-.inference.ModelSequenceBatching.Control.Kind\x12\x18\n\x10int32_false_true\x18\x02 \x03(\x05\x12\x17\n\x0f\x66p32_false_true\x18\x03 \x03(\x02\x12\x17\n\x0f\x62ool_false_true\x18\x05 \x03(\x08\x12&\n\tdata_type\x18\x04 \x01(\x0e\x32\x13.inference.DataType\"u\n\x04Kind\x12\x1a\n\x16\x43ONTROL_SEQUENCE_START\x10\x00\x12\x1a\n\x16\x43ONTROL_SEQUENCE_READY\x10\x01\x12\x18\n\x14\x43ONTROL_SEQUENCE_END\x10\x02\x12\x1b\n\x17\x43ONTROL_SEQUENCE_CORRID\x10\x03\x1aW\n\x0c\x43ontrolInput\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x39\n\x07\x63ontrol\x18\x02 \x03(\x0b\x32(.inference.ModelSequenceBatching.Control\x1a\x8a\x01\n\x0cInitialState\x12&\n\tdata_type\x18\x01 \x01(\x0e\x32\x13.inference.DataType\x12\x0c\n\x04\x64ims\x18\x02 \x03(\x03\x12\x13\n\tzero_data\x18\x03 \x01(\x08H\x00\x12\x13\n\tdata_file\x18\x04 \x01(\tH\x00\x12\x0c\n\x04name\x18\x05 \x01(\tB\x0c\n\nstate_data\x1a\xac\x01\n\x05State\x12\x12\n\ninput_name\x18\x01 \x01(\t\x12\x13\n\x0boutput_name\x18\x02 \x01(\t\x12&\n\tdata_type\x18\x03 \x01(\x0e\x32\x13.inference.DataType\x12\x0c\n\x04\x64ims\x18\x04 \x03(\x03\x12\x44\n\rinitial_state\x18\x05 \x03(\x0b\x32-.inference.ModelSequenceBatching.InitialState\x1aX\n\x0eStrategyDirect\x12$\n\x1cmax_queue_delay_microseconds\x18\x01 \x01(\x04\x12 \n\x18minimum_slot_utilization\x18\x02 \x01(\x02\x1au\n\x0eStrategyOldest\x12\x1f\n\x17max_candidate_sequences\x18\x01 \x01(\x05\x12\x1c\n\x14preferred_batch_size\x18\x02 \x03(\x05\x12$\n\x1cmax_queue_delay_microseconds\x18\x03 \x01(\x04\x42\x11\n\x0fstrategy_choice\"\xdd\x02\n\x0fModelEnsembling\x12-\n\x04step\x18\x01 \x03(\x0b\x32\x1f.inference.ModelEnsembling.Step\x1a\x9a\x02\n\x04Step\x12\x12\n\nmodel_name\x18\x01 \x01(\t\x12\x15\n\rmodel_version\x18\x02 \x01(\x03\x12@\n\tinput_map\x18\x03 \x03(\x0b\x32-.inference.ModelEnsembling.Step.InputMapEntry\x12\x42\n\noutput_map\x18\x04 \x03(\x0b\x32..inference.ModelEnsembling.Step.OutputMapEntry\x1a/\n\rInputMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x30\n\x0eOutputMapEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"&\n\x0eModelParameter\x12\x14\n\x0cstring_value\x18\x01 \x01(\t\"\xd9\x02\n\x0bModelWarmup\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nbatch_size\x18\x02 \x01(\r\x12\x32\n\x06inputs\x18\x03 \x03(\x0b\x32\".inference.ModelWarmup.InputsEntry\x12\r\n\x05\x63ount\x18\x04 \x01(\r\x1a\x97\x01\n\x05Input\x12&\n\tdata_type\x18\x01 \x01(\x0e\x32\x13.inference.DataType\x12\x0c\n\x04\x64ims\x18\x02 \x03(\x03\x12\x13\n\tzero_data\x18\x03 \x01(\x08H\x00\x12\x15\n\x0brandom_data\x18\x04 \x01(\x08H\x00\x12\x19\n\x0finput_data_file\x18\x05 \x01(\tH\x00\x42\x11\n\x0finput_data_type\x1aK\n\x0bInputsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12+\n\x05value\x18\x02 \x01(\x0b\x32\x1c.inference.ModelWarmup.Input:\x02\x38\x01\".\n\x0fModelOperations\x12\x1b\n\x13op_library_filename\x18\x01 \x03(\t\"+\n\x16ModelTransactionPolicy\x12\x11\n\tdecoupled\x18\x01 \x01(\x08\"\xe6\x01\n\x15ModelRepositoryAgents\x12\x36\n\x06\x61gents\x18\x01 \x03(\x0b\x32&.inference.ModelRepositoryAgents.Agent\x1a\x94\x01\n\x05\x41gent\x12\x0c\n\x04name\x18\x01 \x01(\t\x12J\n\nparameters\x18\x02 \x03(\x0b\x32\x36.inference.ModelRepositoryAgents.Agent.ParametersEntry\x1a\x31\n\x0fParametersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"$\n\x12ModelResponseCache\x12\x0e\n\x06\x65nable\x18\x01 \x01(\x08\"\xb2\n\n\x0bModelConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x08platform\x18\x02 \x01(\t\x12\x0f\n\x07\x62\x61\x63kend\x18\x11 \x01(\t\x12\x35\n\x0eversion_policy\x18\x03 \x01(\x0b\x32\x1d.inference.ModelVersionPolicy\x12\x16\n\x0emax_batch_size\x18\x04 \x01(\x05\x12$\n\x05input\x18\x05 \x03(\x0b\x32\x15.inference.ModelInput\x12&\n\x06output\x18\x06 \x03(\x0b\x32\x16.inference.ModelOutput\x12*\n\x0b\x62\x61tch_input\x18\x14 \x03(\x0b\x32\x15.inference.BatchInput\x12,\n\x0c\x62\x61tch_output\x18\x15 \x03(\x0b\x32\x16.inference.BatchOutput\x12\x38\n\x0coptimization\x18\x0c \x01(\x0b\x32\".inference.ModelOptimizationPolicy\x12;\n\x10\x64ynamic_batching\x18\x0b \x01(\x0b\x32\x1f.inference.ModelDynamicBatchingH\x00\x12=\n\x11sequence_batching\x18\r \x01(\x0b\x32 .inference.ModelSequenceBatchingH\x00\x12\x39\n\x13\x65nsemble_scheduling\x18\x0f \x01(\x0b\x32\x1a.inference.ModelEnsemblingH\x00\x12\x35\n\x0einstance_group\x18\x07 \x03(\x0b\x32\x1d.inference.ModelInstanceGroup\x12\x1e\n\x16\x64\x65\x66\x61ult_model_filename\x18\x08 \x01(\t\x12H\n\x12\x63\x63_model_filenames\x18\t \x03(\x0b\x32,.inference.ModelConfig.CcModelFilenamesEntry\x12;\n\x0bmetric_tags\x18\n \x03(\x0b\x32&.inference.ModelConfig.MetricTagsEntry\x12:\n\nparameters\x18\x0e \x03(\x0b\x32&.inference.ModelConfig.ParametersEntry\x12,\n\x0cmodel_warmup\x18\x10 \x03(\x0b\x32\x16.inference.ModelWarmup\x12\x34\n\x10model_operations\x18\x12 \x01(\x0b\x32\x1a.inference.ModelOperations\x12\x43\n\x18model_transaction_policy\x18\x13 \x01(\x0b\x32!.inference.ModelTransactionPolicy\x12\x41\n\x17model_repository_agents\x18\x17 \x01(\x0b\x32 .inference.ModelRepositoryAgents\x12\x35\n\x0eresponse_cache\x18\x18 \x01(\x0b\x32\x1d.inference.ModelResponseCache\x1a\x37\n\x15\x43\x63ModelFilenamesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x31\n\x0fMetricTagsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1aL\n\x0fParametersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12(\n\x05value\x18\x02 \x01(\x0b\x32\x19.inference.ModelParameter:\x02\x38\x01\x42\x13\n\x11scheduling_choice*\xfa\x01\n\x08\x44\x61taType\x12\x10\n\x0cTYPE_INVALID\x10\x00\x12\r\n\tTYPE_BOOL\x10\x01\x12\x0e\n\nTYPE_UINT8\x10\x02\x12\x0f\n\x0bTYPE_UINT16\x10\x03\x12\x0f\n\x0bTYPE_UINT32\x10\x04\x12\x0f\n\x0bTYPE_UINT64\x10\x05\x12\r\n\tTYPE_INT8\x10\x06\x12\x0e\n\nTYPE_INT16\x10\x07\x12\x0e\n\nTYPE_INT32\x10\x08\x12\x0e\n\nTYPE_INT64\x10\t\x12\r\n\tTYPE_FP16\x10\n\x12\r\n\tTYPE_FP32\x10\x0b\x12\r\n\tTYPE_FP64\x10\x0c\x12\x0f\n\x0bTYPE_STRING\x10\r\x12\r\n\tTYPE_BF16\x10\x0e\x62\x06proto3' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'model_config.protxt_pb2', + globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND_INPUTENTRY._options = None + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND_INPUTENTRY._serialized_options = b'8\001' + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_INPUTENTRY._options = None + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_INPUTENTRY._serialized_options = b'8\001' + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR_PARAMETERSENTRY._options = None + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR_PARAMETERSENTRY._serialized_options = b'8\001' + _MODELDYNAMICBATCHING_PRIORITYQUEUEPOLICYENTRY._options = None + _MODELDYNAMICBATCHING_PRIORITYQUEUEPOLICYENTRY._serialized_options = b'8\001' + _MODELENSEMBLING_STEP_INPUTMAPENTRY._options = None + _MODELENSEMBLING_STEP_INPUTMAPENTRY._serialized_options = b'8\001' + _MODELENSEMBLING_STEP_OUTPUTMAPENTRY._options = None + _MODELENSEMBLING_STEP_OUTPUTMAPENTRY._serialized_options = b'8\001' + _MODELWARMUP_INPUTSENTRY._options = None + _MODELWARMUP_INPUTSENTRY._serialized_options = b'8\001' + _MODELREPOSITORYAGENTS_AGENT_PARAMETERSENTRY._options = None + _MODELREPOSITORYAGENTS_AGENT_PARAMETERSENTRY._serialized_options = b'8\001' + _MODELCONFIG_CCMODELFILENAMESENTRY._options = None + _MODELCONFIG_CCMODELFILENAMESENTRY._serialized_options = b'8\001' + _MODELCONFIG_METRICTAGSENTRY._options = None + _MODELCONFIG_METRICTAGSENTRY._serialized_options = b'8\001' + _MODELCONFIG_PARAMETERSENTRY._options = None + _MODELCONFIG_PARAMETERSENTRY._serialized_options = b'8\001' + _DATATYPE._serialized_start = 8137 + _DATATYPE._serialized_end = 8387 + _MODELRATELIMITER._serialized_start = 35 + _MODELRATELIMITER._serialized_end = 185 + _MODELRATELIMITER_RESOURCE._serialized_start = 130 + _MODELRATELIMITER_RESOURCE._serialized_end = 185 + _MODELINSTANCEGROUP._serialized_start = 188 + _MODELINSTANCEGROUP._serialized_end = 707 + _MODELINSTANCEGROUP_SECONDARYDEVICE._serialized_start = 484 + _MODELINSTANCEGROUP_SECONDARYDEVICE._serialized_end = 640 + _MODELINSTANCEGROUP_SECONDARYDEVICE_SECONDARYDEVICEKIND._serialized_start = 603 + _MODELINSTANCEGROUP_SECONDARYDEVICE_SECONDARYDEVICEKIND._serialized_end = 640 + _MODELINSTANCEGROUP_KIND._serialized_start = 642 + _MODELINSTANCEGROUP_KIND._serialized_end = 707 + _MODELTENSORRESHAPE._serialized_start = 709 + _MODELTENSORRESHAPE._serialized_end = 744 + _MODELINPUT._serialized_start = 747 + _MODELINPUT._serialized_end = 1053 + _MODELINPUT_FORMAT._serialized_start = 994 + _MODELINPUT_FORMAT._serialized_end = 1053 + _MODELOUTPUT._serialized_start = 1056 + _MODELOUTPUT._serialized_end = 1234 + _BATCHINPUT._serialized_start = 1237 + _BATCHINPUT._serialized_end = 1582 + _BATCHINPUT_KIND._serialized_start = 1377 + _BATCHINPUT_KIND._serialized_end = 1582 + _BATCHOUTPUT._serialized_start = 1585 + _BATCHOUTPUT._serialized_end = 1728 + _BATCHOUTPUT_KIND._serialized_start = 1686 + _BATCHOUTPUT_KIND._serialized_end = 1728 + _MODELVERSIONPOLICY._serialized_start = 1731 + _MODELVERSIONPOLICY._serialized_end = 2003 + _MODELVERSIONPOLICY_LATEST._serialized_start = 1919 + _MODELVERSIONPOLICY_LATEST._serialized_end = 1949 + _MODELVERSIONPOLICY_ALL._serialized_start = 1951 + _MODELVERSIONPOLICY_ALL._serialized_end = 1956 + _MODELVERSIONPOLICY_SPECIFIC._serialized_start = 1958 + _MODELVERSIONPOLICY_SPECIFIC._serialized_end = 1986 + _MODELOPTIMIZATIONPOLICY._serialized_start = 2006 + _MODELOPTIMIZATIONPOLICY._serialized_end = 3795 + _MODELOPTIMIZATIONPOLICY_GRAPH._serialized_start = 2536 + _MODELOPTIMIZATIONPOLICY_GRAPH._serialized_end = 2558 + _MODELOPTIMIZATIONPOLICY_CUDA._serialized_start = 2561 + _MODELOPTIMIZATIONPOLICY_CUDA._serialized_end = 3259 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC._serialized_start = 2711 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC._serialized_end = 3259 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_SHAPE._serialized_start = 2910 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_SHAPE._serialized_end = 2930 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND._serialized_start = 2933 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND._serialized_end = 3156 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND_INPUTENTRY._serialized_start = 3055 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_LOWERBOUND_INPUTENTRY._serialized_end = 3156 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_INPUTENTRY._serialized_start = 3055 + _MODELOPTIMIZATIONPOLICY_CUDA_GRAPHSPEC_INPUTENTRY._serialized_end = 3156 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS._serialized_start = 3262 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS._serialized_end = 3682 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR._serialized_start = 3498 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR._serialized_end = 3682 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR_PARAMETERSENTRY._serialized_start = 3633 + _MODELOPTIMIZATIONPOLICY_EXECUTIONACCELERATORS_ACCELERATOR_PARAMETERSENTRY._serialized_end = 3682 + _MODELOPTIMIZATIONPOLICY_PINNEDMEMORYBUFFER._serialized_start = 3684 + _MODELOPTIMIZATIONPOLICY_PINNEDMEMORYBUFFER._serialized_end = 3720 + _MODELOPTIMIZATIONPOLICY_MODELPRIORITY._serialized_start = 3722 + _MODELOPTIMIZATIONPOLICY_MODELPRIORITY._serialized_end = 3795 + _MODELQUEUEPOLICY._serialized_start = 3798 + _MODELQUEUEPOLICY._serialized_end = 4017 + _MODELQUEUEPOLICY_TIMEOUTACTION._serialized_start = 3979 + _MODELQUEUEPOLICY_TIMEOUTACTION._serialized_end = 4017 + _MODELDYNAMICBATCHING._serialized_start = 4020 + _MODELDYNAMICBATCHING._serialized_end = 4431 + _MODELDYNAMICBATCHING_PRIORITYQUEUEPOLICYENTRY._serialized_start = 4344 + _MODELDYNAMICBATCHING_PRIORITYQUEUEPOLICYENTRY._serialized_end = 4431 + _MODELSEQUENCEBATCHING._serialized_start = 4434 + _MODELSEQUENCEBATCHING._serialized_end = 5697 + _MODELSEQUENCEBATCHING_CONTROL._serialized_start = 4759 + _MODELSEQUENCEBATCHING_CONTROL._serialized_end = 5064 + _MODELSEQUENCEBATCHING_CONTROL_KIND._serialized_start = 4947 + _MODELSEQUENCEBATCHING_CONTROL_KIND._serialized_end = 5064 + _MODELSEQUENCEBATCHING_CONTROLINPUT._serialized_start = 5066 + _MODELSEQUENCEBATCHING_CONTROLINPUT._serialized_end = 5153 + _MODELSEQUENCEBATCHING_INITIALSTATE._serialized_start = 5156 + _MODELSEQUENCEBATCHING_INITIALSTATE._serialized_end = 5294 + _MODELSEQUENCEBATCHING_STATE._serialized_start = 5297 + _MODELSEQUENCEBATCHING_STATE._serialized_end = 5469 + _MODELSEQUENCEBATCHING_STRATEGYDIRECT._serialized_start = 5471 + _MODELSEQUENCEBATCHING_STRATEGYDIRECT._serialized_end = 5559 + _MODELSEQUENCEBATCHING_STRATEGYOLDEST._serialized_start = 5561 + _MODELSEQUENCEBATCHING_STRATEGYOLDEST._serialized_end = 5678 + _MODELENSEMBLING._serialized_start = 5700 + _MODELENSEMBLING._serialized_end = 6049 + _MODELENSEMBLING_STEP._serialized_start = 5767 + _MODELENSEMBLING_STEP._serialized_end = 6049 + _MODELENSEMBLING_STEP_INPUTMAPENTRY._serialized_start = 5952 + _MODELENSEMBLING_STEP_INPUTMAPENTRY._serialized_end = 5999 + _MODELENSEMBLING_STEP_OUTPUTMAPENTRY._serialized_start = 6001 + _MODELENSEMBLING_STEP_OUTPUTMAPENTRY._serialized_end = 6049 + _MODELPARAMETER._serialized_start = 6051 + _MODELPARAMETER._serialized_end = 6089 + _MODELWARMUP._serialized_start = 6092 + _MODELWARMUP._serialized_end = 6437 + _MODELWARMUP_INPUT._serialized_start = 6209 + _MODELWARMUP_INPUT._serialized_end = 6360 + _MODELWARMUP_INPUTSENTRY._serialized_start = 6362 + _MODELWARMUP_INPUTSENTRY._serialized_end = 6437 + _MODELOPERATIONS._serialized_start = 6439 + _MODELOPERATIONS._serialized_end = 6485 + _MODELTRANSACTIONPOLICY._serialized_start = 6487 + _MODELTRANSACTIONPOLICY._serialized_end = 6530 + _MODELREPOSITORYAGENTS._serialized_start = 6533 + _MODELREPOSITORYAGENTS._serialized_end = 6763 + _MODELREPOSITORYAGENTS_AGENT._serialized_start = 6615 + _MODELREPOSITORYAGENTS_AGENT._serialized_end = 6763 + _MODELREPOSITORYAGENTS_AGENT_PARAMETERSENTRY._serialized_start = 3633 + _MODELREPOSITORYAGENTS_AGENT_PARAMETERSENTRY._serialized_end = 3682 + _MODELRESPONSECACHE._serialized_start = 6765 + _MODELRESPONSECACHE._serialized_end = 6801 + _MODELCONFIG._serialized_start = 6804 + _MODELCONFIG._serialized_end = 8134 + _MODELCONFIG_CCMODELFILENAMESENTRY._serialized_start = 7929 + _MODELCONFIG_CCMODELFILENAMESENTRY._serialized_end = 7984 + _MODELCONFIG_METRICTAGSENTRY._serialized_start = 7986 + _MODELCONFIG_METRICTAGSENTRY._serialized_end = 8035 + _MODELCONFIG_PARAMETERSENTRY._serialized_start = 8037 + _MODELCONFIG_PARAMETERSENTRY._serialized_end = 8113 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/xarfile.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/xarfile.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf82313499c4cd45d1cddbc2f929ded1c81e503 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/inference/xarfile.py @@ -0,0 +1,252 @@ +# 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. +import os +import tarfile +import zipfile +from typing import Callable +from typing import Generator +from typing import List + +import rarfile + + +class XarInfo(object): + '''Informational class which holds the details about an archive member given by a XarFile.''' + + def __init__(self, _xarinfo, arctype='tar'): + self._info = _xarinfo + self.arctype = arctype + + @property + def name(self) -> str: + if self.arctype == 'tar': + return self._info.name + return self._info.filename + + @property + def size(self) -> int: + if self.arctype == 'tar': + return self._info.size + return self._info.file_size + + +class XarFile(object): + ''' + The XarFile Class provides an interface to tar/rar/zip archives. + + Args: + name(str) : file or directory name to be archived + mode(str) : specifies the mode in which the file is opened, it must be: + ======== ============================================================================================== + Charater Meaning + -------- ---------------------------------------------------------------------------------------------- + 'r' open for reading + 'w' open for writing, truncating the file first, file will be saved according to the arctype field + 'a' open for writing, appending to the end of the file if it exists + ======== =============================================================================================== + arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz'], if + the mode if 'w' or 'a', the default is 'tar', if the mode is 'r', it will be based on actual + archive type of file + ''' + + def __init__(self, name: str, mode: str, arctype: str = 'tar', **kwargs): + # if mode is 'w', adjust mode according to arctype field + if mode == 'w': + if arctype in ['tar.gz', 'tgz']: + mode = 'w:gz' + self.arctype = 'tar' + elif arctype == 'tar.bz2': + mode = 'w:bz2' + self.arctype = 'tar' + elif arctype in ['tar.xz', 'txz']: + mode = 'w:xz' + self.arctype = 'tar' + else: + self.arctype = arctype + # if mode is 'r', adjust mode according to actual archive type of file + elif mode == 'r': + if tarfile.is_tarfile(name): + self.arctype = 'tar' + mode = 'r:*' + elif zipfile.is_zipfile(name): + self.arctype = 'zip' + elif rarfile.is_rarfile(name): + self.arctype = 'rar' + elif mode == 'a': + self.arctype = arctype + else: + raise RuntimeError('Unsupported mode {}'.format(mode)) + + if self.arctype in [ + 'tar.gz', 'tar.bz2', 'tar.xz', 'tar', 'tgz', 'txz' + ]: + self._archive_fp = tarfile.open(name, mode, **kwargs) + elif self.arctype == 'zip': + self._archive_fp = zipfile.ZipFile(name, mode, **kwargs) + elif self.arctype == 'rar': + self._archive_fp = rarfile.RarFile(name, mode, **kwargs) + else: + raise RuntimeError('Unsupported archive type {}'.format( + self.arctype)) + + def __del__(self): + self._archive_fp.close() + + def __enter__(self): + return self + + def __exit__(self, exit_exception, exit_value, exit_traceback): + if exit_exception: + print(exit_traceback) + raise exit_exception(exit_value) + self._archive_fp.close() + return self + + def add(self, + name: str, + arcname: str = None, + recursive: bool = True, + exclude: Callable = None): + ''' + Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). + If given, `arcname' specifies an alternative name for the file in the archive. Directories are added + recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that + should return True for each filename to be excluded. + ''' + if self.arctype == 'tar': + self._archive_fp.add(name, arcname, recursive, filter=exclude) + else: + self._archive_fp.write(name) + if not recursive or not os.path.isdir(name): + return + items = [] + for _d, _sub_ds, _files in os.walk(name): + items += [os.path.join(_d, _file) for _file in _files] + items += [os.path.join(_d, _sub_d) for _sub_d in _sub_ds] + + for item in items: + if exclude and not exclude(item): + continue + self._archive_fp.write(item) + + def extract(self, name: str, path: str): + '''Extract a file from the archive to the specified path.''' + return self._archive_fp.extract(name, path) + + def extractall(self, path: str): + '''Extract all files from the archive to the specified path.''' + return self._archive_fp.extractall(path) + + def getnames(self) -> List[str]: + '''Return a list of file names in the archive.''' + if self.arctype == 'tar': + return self._archive_fp.getnames() + return self._archive_fp.namelist() + + def getxarinfo(self, name: str) -> List[XarInfo]: + '''Return the instance of XarInfo given 'name'.''' + if self.arctype == 'tar': + return XarInfo(self._archive_fp.getmember(name), self.arctype) + return XarInfo(self._archive_fp.getinfo(name), self.arctype) + + +def open(name: str, mode: str = 'w', **kwargs) -> XarFile: + ''' + Open a xar archive for reading, writing or appending. Return + an appropriate XarFile class. + ''' + return XarFile(name, mode, **kwargs) + + +def archive(filename: str, + recursive: bool = True, + exclude: Callable = None, + arctype: str = 'tar') -> str: + ''' + Archive a file or directory + + Args: + name(str) : file or directory path to be archived + recursive(bool) : whether to recursively archive directories + exclude(Callable) : function that should return True for each filename to be excluded + arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz'] + + Returns: + str: archived file path + + Examples: + .. code-block:: python + + archive_path = '/PATH/TO/FILE' + archive(archive_path, arcname='output.tar.gz', arctype='tar.gz') + ''' + basename = os.path.splitext(os.path.basename(filename))[0] + savename = '{}.{}'.format(basename, arctype) + with open(savename, mode='w', arctype=arctype) as file: + file.add(filename, recursive=recursive, exclude=exclude) + + return savename + + +def unarchive(name: str, path: str): + ''' + Unarchive a file + + Args: + name(str) : file or directory name to be unarchived + path(str) : storage name of archive file + + Examples: + .. code-block:: python + + unarchive_path = '/PATH/TO/FILE' + unarchive(unarchive_path, path='./output') + ''' + with open(name, mode='r') as file: + file.extractall(path) + + +def unarchive_with_progress(name: str, path: str) -> Generator[str, int, int]: + ''' + Unarchive a file and return the unarchiving progress -> Generator[filename, extrace_size, total_size] + + Args: + name(str) : file or directory name to be unarchived + path(str) : storage name of archive file + + Examples: + .. code-block:: python + + unarchive_path = 'test.tar.gz' + for filename, extract_size, total_szie in unarchive_with_progress(unarchive_path, path='./output'): + print(filename, extract_size, total_size) + ''' + with open(name, mode='r') as file: + total_size = extract_size = 0 + for filename in file.getnames(): + total_size += file.getxarinfo(filename).size + + for filename in file.getnames(): + file.extract(filename, path) + extract_size += file.getxarinfo(filename).size + yield filename, extract_size, total_size + + +def is_xarfile(file: str) -> bool: + '''Return True if xarfile supports specific file, otherwise False''' + _x_func = [zipfile.is_zipfile, tarfile.is_tarfile, rarfile.is_rarfile] + for _f in _x_func: + if _f(file): + return True + return False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19f7b87ee86723af4d909e34a05647f7e40fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c19f7b87ee86723af4d909e34a05647f7e40fe2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/const_description.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/const_description.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8f46cc7f5eba8349d28731770112e62bb1e099 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/const_description.py @@ -0,0 +1,159 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +__ALL__ = [ + 'TOOLTIP_DEVICE_INFO_CN', 'TOOLTIP_MODEL_PERSPECTIVE_CN', + 'TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_CN', + 'TOOLTIP_EVENT_TYPE_PERSPECTIVE_CN', + 'TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_CN', 'TOOLTIP_DEVICE_INFO_EN', + 'TOOLTIP_MODEL_PERSPECTIVE_EN', 'TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_EN', + 'TOOLTIP_EVENT_TYPE_PERSPECTIVE_EN', + 'TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_EN' +] + +TOOLTIP_DEVICE_INFO_CN = \ + 'CPU进程利用率:
'\ + '进程所利用到的CPU的时间 / ProfileStep的时间(即性能分析的时间跨度)
'\ + 'CPU系统利用率:
'\ + '整个系统所有进程利用到的CPU时间 / CPU总时间(ProfileStep的时间*CPU核心数)
'\ + 'GPU利用率:
'\ + '进程利用GPU计算的时间 / ProfileStep的时间,进程利用GPU计算的时间即是GPU Kernel计算的时间,越高越好
'\ + '流处理器效率:
'\ + '对于流处理器处理某个GPU Kernel, 其效率为SM_Eff_i = min(Kernel所用的Blocks数量 / GPU的流处理器数量, 100%)。'\ + '流处理器效率为SM_Eff_i关于每个Kernel的执行时间加权和 / ProfileStep的时间
'\ + '流处理器占用率:
'\ + '对于流处理器处理某个GPU Kernel, 其占用率Occu_i = 为活跃的warp数 / 能支持的最大warp数。流处理器占用率为Occu_i关于每个Kernel执行时间的加权平均
'\ + 'Tensor cores使用时间占比:
'\ + '使用Tensor Cores的GPU Kernel的计算时间 / 所有Kernel的计算时间
' + +TOOLTIP_MODEL_PERSPECTIVE_CN = \ + '展示模型各阶段DataLoader, Forward, Backward, Optimization以及Other的总CPU和GPU时间。
'\ + 'CPU时间即是各阶段代码执行的时间,GPU时间是各阶段所调用的GPU Kernel在GPU上的计算时间。
'\ + 'DataLoader: 表示使用paddle.io.DataLoader从数据集中取数据的阶段
'\ + 'Forward: 表示模型前向计算的阶段
'\ + 'Backward: 表示模型反向梯度计算的阶段
'\ + 'Optimization: 表示模型优化更新参数的阶段
'\ + 'Other: 其它时间
' + +TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_CN = \ + '展示每一个ProfileStep内模型各阶段DataLoader, Forward, Backward, Optimization以及Other的CPU和GPU时间。
'\ + 'CPU时间即是各阶段代码执行的时间,GPU时间是各阶段所调用的GPU Kernel在GPU上的计算时间。
'\ + 'DataLoader: 表示使用paddle.io.DataLoader从数据集中取数据的阶段
'\ + 'Forward: 表示模型前向计算的阶段
'\ + 'Backward: 表示模型反向梯度计算的阶段
'\ + 'Optimization: 表示模型优化更新参数的阶段
'\ + 'Other: 其它时间
' + +TOOLTIP_EVENT_TYPE_PERSPECTIVE_CN = \ + '展示不同类型的事件在模型各阶段DataLoader, Forward, Backward, Optimization以及Other的分布。
'\ + 'Operator: 表示框架内的算子执行
'\ + 'CudaRuntime: 表示cuda runtime的函数执行
'\ + 'Kernel: 表示GPU上计算的Kernel函数执行
'\ + 'Memcpy: 表示CPU和GPU之间的数据传输
'\ + 'Memset: 表示GPU的显存值设置
'\ + 'UserDefined: 表示用户在python脚本中自定义的事件
'\ + 'OperatorInner: 表示框架内算子的执行子过程
'\ + 'Communication: 表示分布式通信有关的事件
' + +TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_CN = \ + '展示在模型各阶段DataLoader, Forward, Backward, Optimization以及Other所包含的各种事件的时间。
'\ + 'Operator: 表示框架内的算子执行
'\ + 'CudaRuntime: 表示cuda runtime的函数执行
'\ + 'Kernel: 表示GPU上计算的Kernel函数执行
'\ + 'Memcpy: 表示CPU和GPU之间的数据传输
'\ + 'Memset: 表示GPU的显存值设置
'\ + 'UserDefined: 表示用户在python脚本中自定义的事件
'\ + 'OperatorInner: 表示框架内算子的执行子过程
'\ + 'Communication: 表示分布式通信有关的数据通信和计算事件
' + +TOOLTIP_EVENT_DISTRIBUTED_HISTOGRAM_CN = \ + '展示模型在每个迭代过程中通信、计算以及两者重叠部分的时间。
'\ + 'ProfileStep: 表示某一步迭代的总时间
'\ + 'Communication: 表示和通信相关的时间,包括框架内打的Communication事件、和通信有关的算子和Kernel(nccl)执行的时间
'\ + 'Computation: 表示GPU Kernel计算的时间,但是去除了和通信有关的Kernel(nccl)
'\ + 'Overlap: 表示通信和计算过程并行执行时候时间相互重叠的部分
'\ + 'Others: 表示通信和计算之外的时间
' + +TOOLTIP_DEVICE_INFO_EN = \ + 'CPU Process Utilization:
'\ + 'Process CPU time / ProfileStep time(total time of profiling)
'\ + 'CPU System Utilization:
'\ + 'Sum of system\'s all processes CPU time/ CPU total time(ProfileStep time* #CPU Core)
'\ + 'GPU Utilization:
'\ + 'GPU busy time / ProfileStep time,GPU busy time is the time during in which at least one GPU kernel is\ + running on it.
'\ + 'Est. SM Efficiency:
'\ + 'The SM efficiency for one kernel can be denoted as SM_Eff_i = min(blocks of this kernel / SM number \ + of this GPU, 100%).'\ + 'Est. SM efficiency of GPU is the weighted sum of SM_Eff_i across all kernels / ProfileStep time
'\ + 'Est. Achieved Occupancy:
'\ + 'The SM occupancy for one kernel can be denoted as Occu_i = active warps on an SM / maximum number \ + of active warps supported by the SM. \ + Est. SM occupancy of GPU is the weighted average of Occu_i across all kernels
'\ + 'Tensor cores ratio:
'\ + 'Sum of kernel time using Tensor Cores / Sum of total kernel time
' + +TOOLTIP_MODEL_PERSPECTIVE_EN = \ + 'Present CPU and GPU time for each stage of a model, i.e. DataLoader, Forward, Backward, Optimization and Other.
'\ + 'CPU time is the execution time for code,GPU time is the calculation time of kernels launched in the stage.
'\ + 'DataLoader: denote data fetching using paddle.io.DataLoader
'\ + 'Forward: denote model forward
'\ + 'Backward: denote gradient back-propagate
'\ + 'Optimization: denote parameters update
'\ + 'Other: other time out of above range' + +TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_EN = \ + 'Present CPU and GPU time in each ProfileStep for each stage of a model, \ + i.e. DataLoader, Forward, Backward, Optimization and Other.
'\ + 'CPU time is the execution time for code,GPU time is the calculation time of kernels launched in the stage.
'\ + 'DataLoader: denote data fetching using paddle.io.DataLoader
'\ + 'Forward: denote model forward
'\ + 'Backward: denote gradient back-propagate
'\ + 'Optimization: denote parameters update
'\ + 'Other: other time out of above range' + +TOOLTIP_EVENT_TYPE_PERSPECTIVE_EN = \ + 'Present the distribution of each kind of events across DataLoader,\ + Forward, Backward, Optimization and Other stage.
'\ + 'Operator: denote operator execution
'\ + 'CudaRuntime: denote cuda runtime function execution
'\ + 'Kernel: denote kernel execution on GPU
'\ + 'Memcpy: denote data transfer between CPU and GPU
'\ + 'Memset: denote memory data set on GPU
'\ + 'UserDefined: denote events defined by users in python script
'\ + 'OperatorInner: denote operator\'s subprocess execution
'\ + 'Communication: denote events associated with distributed data transfer and computation.
' + +TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_EN = \ + 'Present the time of each kind of events included in DataLoader, Forward, Backward, Optimization \ + and Other stage.
'\ + 'Operator: denote operator execution
'\ + 'CudaRuntime: denote cuda runtime function execution
'\ + 'Kernel: denote kernel execution on GPU
'\ + 'Memcpy: denote data transfer between CPU and GPU
'\ + 'Memset: denote memory data set on GPU
'\ + 'UserDefined: denote events defined by users in python script
'\ + 'OperatorInner: denote operator\'s subprocess execution
'\ + 'Communication: denote events associated with distributed data transfer and computation.
' + +TOOLTIP_EVENT_DISTRIBUTED_HISTOGRAM_EN = \ + 'Present the time of communication, computation and their overlap in program.
'\ + 'ProfileStep: denote an iteration step of training process
'\ + 'Communication: denote the time related to communication, including events of communication type\ + in paddle framework、communication-related operators and GPU Kernels(nccl)
'\ + 'Computation: denote the computation \ + time of GPU Kernels,except communication-related Kernels(nccl)
'\ + 'Overlap: denote the overlap time between Communication and \ + Computation when they are executed parallelly.
'\ + 'Others: denote the time out of Communication and Computation
' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/distributed_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/distributed_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5139ea8f270845eab5528dc8c4d73cf0d7635f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/distributed_parser.py @@ -0,0 +1,163 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from collections import defaultdict + +from .utils import get_device_nodes +from .utils import intersection_ranges +from .utils import merge_ranges +from .utils import merge_self_ranges +from .utils import rebuild_node_trees +from .utils import sum_ranges +from .utils import traverse_tree + +_CommunicationOpName = ['allreduce', 'broadcast', 'rpc'] + + +class DistributedParser: + r""" + Analysis communication and computation time range, and their overlap. + The computation time is all kernel except kernels for communication like nccl. + """ + + def __init__(self): + self.steps_data = defaultdict(lambda: defaultdict(list)) + self.calls = defaultdict(lambda: defaultdict(int)) + self.steps_time = defaultdict(lambda: defaultdict(float)) + self.profile_steps_time = {} + + def parse(self, nodetrees): + ''' + Collect all communication and computation time ranges. + ''' + total_time = 0.0 + nodetrees = rebuild_node_trees(nodetrees) + thread2hostnodes = traverse_tree(nodetrees) + thread_count = 0 + for threadid, hostnodes in thread2hostnodes.items(): + for hostnode in hostnodes[1:]: # skip root node + # case 1: TracerEventType is Communication + if hostnode.type == 'ProfileStep': + if thread_count == 0: + total_time += (hostnode.end_ns - hostnode.start_ns) + self._parse_step(hostnode) + continue + thread_count += 1 + + new_steps_data = defaultdict(lambda: defaultdict(list)) + self.profile_steps_time['All'] = total_time + for step, step_data in self.steps_data.items(): + self.calls[step]['cpu_communication_range'] = len( + step_data['cpu_communication_range']) + self.calls[step]['gpu_communication_range'] = len( + step_data['gpu_communication_range']) + new_steps_data[step][ + 'cpu_communication_range'] = merge_self_ranges( + step_data['cpu_communication_range'], is_sorted=False) + new_steps_data[step][ + 'gpu_communication_range'] = merge_self_ranges( + step_data['gpu_communication_range'], is_sorted=False) + new_steps_data[step]['communication_range'] = merge_ranges( + new_steps_data[step]['cpu_communication_range'], + new_steps_data[step]['gpu_communication_range'], + is_sorted=True) + new_steps_data[step]['computation_range'] = merge_self_ranges( + step_data['computation_range'], is_sorted=False) + new_steps_data[step]['overlap_range'] = intersection_ranges( + new_steps_data[step]['communication_range'], + new_steps_data[step]['computation_range'], + is_sorted=True) + self.steps_time[step]['communication_time'] = sum_ranges( + new_steps_data[step]['communication_range']) + self.steps_time[step]['computation_time'] = sum_ranges( + new_steps_data[step]['computation_range']) + self.steps_time[step]['overlap_time'] = sum_ranges( + new_steps_data[step]['overlap_range']) + self.steps_time[step]['others_time'] = self.profile_steps_time[ + step] - self.steps_time[step][ + 'communication_time'] - self.steps_time[step][ + 'computation_time'] + self.steps_time[step][ + 'overlap_time'] + self.steps_data = new_steps_data + + def _parse_step(self, profile_step_node): + step = profile_step_node.name.split('#')[1] + self.profile_steps_time[ + step] = profile_step_node.end_ns - profile_step_node.start_ns + nodes = [] + stack = [] + stack.append(profile_step_node) + while stack: + current_node = stack.pop() + nodes.append(current_node) + for childnode in current_node.children_node: + stack.append(childnode) + for hostnode in nodes: + if hostnode.type == 'Communication': + self.steps_data[step]['cpu_communication_range'].append( + (hostnode.start_ns, hostnode.end_ns)) + self.steps_data['All']['cpu_communication_range'].append( + (hostnode.start_ns, hostnode.end_ns)) + device_nodes = get_device_nodes(hostnode) + for device_node in device_nodes: + if device_node.type == 'Kernel': + self.steps_data[step][ + 'gpu_communication_range'].append( + (device_node.start_ns, device_node.end_ns)) + self.steps_data['All'][ + 'gpu_communication_range'].append( + (device_node.start_ns, device_node.end_ns)) + + # case 2: TracerEventType is Operator but is communication op + elif hostnode.type == 'Operator' and any([ + name in hostnode.name.lower() + for name in _CommunicationOpName + ]): + self.steps_data[step]['cpu_communication_range'].append( + (hostnode.start_ns, hostnode.end_ns)) + self.steps_data['All']['cpu_communication_range'].append( + (hostnode.start_ns, hostnode.end_ns)) + device_nodes = get_device_nodes(hostnode) + for device_node in device_nodes: + if device_node.type == 'Kernel': + self.steps_data[step][ + 'gpu_communication_range'].append( + (device_node.start_ns, device_node.end_ns)) + self.steps_data['All'][ + 'gpu_communication_range'].append( + (device_node.start_ns, device_node.end_ns)) + + # case 3: Others, filter kernels named with nccl + else: + for runtimenode in hostnode.runtime_node: + for devicenode in runtimenode.device_node: + if devicenode.type == 'Kernel': + if 'nccl' in devicenode.name.lower(): + self.steps_data[step][ + 'gpu_communication_range'].append( + (devicenode.start_ns, + devicenode.end_ns)) + self.steps_data['All'][ + 'gpu_communication_range'].append( + (devicenode.start_ns, + devicenode.end_ns)) + else: + self.steps_data[step][ + 'computation_range'].append( + (devicenode.start_ns, + devicenode.end_ns)) + self.steps_data['All'][ + 'computation_range'].append( + (devicenode.start_ns, + devicenode.end_ns)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/event_node.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/event_node.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d0eebf78af05b246b3151b85718a17898a0253 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/event_node.py @@ -0,0 +1,587 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections +import functools +import json +import re +import sys +import tempfile + +from .utils import traverse_tree + +_show_name_pattern = re.compile(r'(.+)(\[.+\])') +_show_tid_pattern = re.compile(r'\w+(\(.+\))') + +host_node_type_map = { + "Operator", "Dataloader", "ProfileStep", "CudaRuntime", "UserDefined", + "OperatorInner", "Forward", "Backward", "Optimization", "Communication", + "PythonOp", "PythonUserDefined" +} + +device_node_type_map = {"Kernel", "Memcpy", "Memset"} + +memory_node_event_map = { + "Allocate", "Free", "ReservedAllocate", "ReservedFree" +} + + +class HostNode: + def __init__(self): + self.name = None + self.type = None + self.start_ns = 0 + self.end_ns = 0 + self.process_id = 0 + self.thread_id = 0 + self.correlation_id = -1 + self.input_shapes = {} + self.dtypes = {} + self.callstack = "" + self.children_node = [] + self.runtime_node = [] + self.device_node = [] + self.mem_node = [] + + @classmethod + def from_json(cls, json_obj): + self = cls() + self.name = json_obj['name'].replace( + _show_name_pattern.match(json_obj['name']).group(2), "") + self.type = json_obj['cat'] + self.start_ns = int( + float(json_obj['args']['start_time'].split(' ')[0]) * 1000) + self.end_ns = int( + float(json_obj['args']['end_time'].split(' ')[0]) * 1000) + self.process_id = json_obj['pid'] + self.thread_id = json_obj['tid'].replace( + _show_tid_pattern.match(json_obj['tid']).group(1), "") + self.correlation_id = json_obj['args'][ + 'correlation id'] if 'correlation id' in json_obj['args'] else -1 + self.input_shapes = json_obj['args'][ + 'input_shapes'] if 'input_shapes' in json_obj['args'] else {} + self.dtypes = json_obj['args'][ + 'input_dtypes'] if 'input_dtypes' in json_obj['args'] else {} + self.callstack = json_obj['args'][ + 'callstack'] if 'callstack' in json_obj['args'] else "" + self.children_node = [] + self.runtime_node = [] + self.device_node = [] + self.mem_node = [] + return self + + @classmethod + def from_protobuf(cls, obj): + self = cls() + self.name = obj.name + self.type = str(obj.type).split('.')[1] + self.start_ns = obj.start_ns + self.end_ns = obj.end_ns + self.process_id = obj.process_id + self.thread_id = obj.thread_id + self.correlation_id = obj.correlation_id + self.input_shapes = obj.input_shapes + self.dtypes = obj.dtypes + self.callstack = obj.callstack + self.children_node = [] + self.runtime_node = [] + self.device_node = [] + self.mem_node = [] + return self + + +class MemNode: + def __init__(self): + self.type = None + self.timestamp_ns = 0 + self.addr = 0 + self.process_id = 0 + self.thread_id = 0 + self.increase_bytes = 0 + self.place = None + self.current_allocated = 0 + self.current_reserved = 0 + self.peak_allocated = 0 + self.peak_reserved = 0 + + @classmethod + def from_json(cls, json_obj): + self = cls() + self.type = json_obj['cat'] + self.timestamp_ns = json_obj['ts'] * 1000 + self.addr = hex(int( + json_obj['args']['addr'])) if 'addr' in json_obj['args'] else 0 + self.process_id = json_obj['pid'] + self.thread_id = json_obj['tid'].replace( + _show_tid_pattern.match(json_obj['tid']).group(1), "") + self.increase_bytes = json_obj['args'][ + 'increase_bytes'] if 'increase_bytes' in json_obj['args'] else 0 + self.place = json_obj['args']['place'] if 'place' in json_obj[ + 'args'] else "Place(cpu)" + self.current_allocated = json_obj['args'][ + 'current_allocated'] if 'current_allocated' in json_obj[ + 'args'] else 0 + self.current_reserved = json_obj['args'][ + 'current_reserved'] if 'current_reserved' in json_obj['args'] else 0 + self.peak_allocated = json_obj['args'][ + 'peak_allocated'] if 'peak_allocated' in json_obj['args'] else 0 + self.peak_reserved = json_obj['args'][ + 'peak_reserved'] if 'peak_reserved' in json_obj['args'] else 0 + return self + + @classmethod + def from_protobuf(cls, obj): + self = cls() + self.type = str(obj.type).split('.')[1] + self.timestamp_ns = obj.timestamp_ns + self.addr = hex(int(obj.addr)) + self.process_id = obj.process_id + self.thread_id = obj.thread_id + self.increase_bytes = obj.increase_bytes + self.place = obj.place + self.current_allocated = obj.current_allocated + self.current_reserved = obj.current_reserved + self.peak_allocated = obj.peak_allocated + self.peak_reserved = obj.peak_reserved + return self + + +class DeviceNode: + def __init__(self): + self.name = None + self.type = None + self.start_ns = 0 + self.end_ns = 0 + self.device_id = 0 + self.stream_id = 0 + self.context_id = 0 + self.correlation_id = 0 + self.block_x, self.block_y, self.block_z = [0, 0, 0] + self.grid_x, self.grid_y, self.grid_z = [0, 0, 0] + self.shared_memory = 0 + self.registers_per_thread = 0 + self.num_bytes = 0 + self.value = 0 + self.occupancy = 0 + self.blocks_per_sm = 0 + self.warps_per_sm = 0 + + @classmethod + def from_json(cls, json_obj): + self = cls() + self.name = json_obj['name'].replace( + _show_name_pattern.match(json_obj['name']).group(2), "") + self.type = json_obj['cat'] + self.start_ns = int( + float(json_obj['args']['start_time'].split(' ')[0]) * 1000) + self.end_ns = int( + float(json_obj['args']['end_time'].split(' ')[0]) * 1000) + self.device_id = json_obj['pid'] + self.stream_id = json_obj['tid'] + self.context_id = json_obj['args']['context'] if 'context' in json_obj[ + 'args'] else 0 + self.correlation_id = json_obj['args']['correlation id'] + self.block_x, self.block_y, self.block_z = json_obj['args'][ + 'block'] if 'block' in json_obj['args'] else [0, 0, 0] + self.grid_x, self.grid_y, self.grid_z = json_obj['args'][ + 'grid'] if 'grid' in json_obj['args'] else [0, 0, 0] + self.shared_memory = json_obj['args'][ + 'shared memory'] if 'shared memory' in json_obj['args'] else 0 + self.registers_per_thread = json_obj['args'][ + 'registers per thread'] if 'registers per thread' in json_obj[ + 'args'] else 0 + self.num_bytes = json_obj['args']['bytes'] if 'bytes' in json_obj[ + 'args'] else 0 + self.value = json_obj['args']['value'] if 'value' in json_obj[ + 'args'] else 0 + self.occupancy = json_obj['args'][ + 'theoretical achieved occupancy %'] if 'theoretical achieved occupancy %' in json_obj[ + 'args'] else 0 + self.blocks_per_sm = json_obj['args'][ + "blocks per SM"] if "blocks per SM" in json_obj['args'] else 0 + self.warps_per_sm = json_obj['args'][ + "warps per SM"] if "warps per SM" in json_obj['args'] else 0 + return self + + @classmethod + def from_protobuf(cls, obj): + self = cls() + self.name = obj.name + self.type = str(obj.type).split('.')[1] + self.start_ns = obj.start_ns + self.end_ns = obj.end_ns + self.device_id = obj.device_id + self.stream_id = obj.stream_id + self.context_id = obj.context_id + self.correlation_id = obj.correlation_id + self.block_x, self.block_y, self.block_z = [ + obj.block_x, obj.block_y, obj.block_z + ] + self.grid_x, self.grid_y, self.grid_z = [ + obj.grid_x, obj.grid_y, obj.grid_z + ] + self.shared_memory = obj.shared_memory + self.registers_per_thread = obj.registers_per_thread + self.num_bytes = obj.num_bytes + self.value = obj.value + self.occupancy = obj.occupancy * 100 + self.blocks_per_sm = obj.blocks_per_sm + self.warps_per_sm = obj.warps_per_sm + return self + + +class ProfilerResult: + def __init__(self, data): + self.device_infos = None + self.span_idx = None + self.data = None + self.extra_info = None + self.schema_version = None + self.has_hostnodes = True + self.has_devicenodes = True + self.has_memnodes = True + self.start_in_timeline_ns = None + if isinstance(data, dict): + self.parse_json(data) + self.content = data + else: + self.parse_protobuf(data) + with tempfile.NamedTemporaryFile("r") as fp: + data.save(fp.name, "json") + fp.seek(0) + self.content = json.loads(fp.read()) + + def parse_json(self, json_data): + self.schema_version = json_data['schemaVersion'] + self.span_idx = json_data['span_indx'] + try: + self.device_infos = { + device_info['id']: device_info + for device_info in json_data['deviceProperties'] + } + except Exception: + print( + "paddlepaddle-gpu version is needed to get GPU device informations." + ) + self.device_infos = {} + hostnodes = [] + runtimenodes = [] + devicenodes = [] + memnodes = [] + for event in json_data['traceEvents']: + if not event or (event['ph'] != 'X' and event['ph'] != 'i'): + continue + if event['cat'] in host_node_type_map: + if event['cat'] == 'CudaRuntime' or event[ + 'cat'] == 'MluRuntime': + runtimenodes.append(HostNode.from_json(event)) + else: + hostnodes.append(HostNode.from_json(event)) + if hostnodes[-1].start_ns == 0: + self.start_in_timeline_ns = int(event['ts']) * 1000 + elif event['cat'] in device_node_type_map: + devicenodes.append(DeviceNode.from_json(event)) + elif event['cat'] in memory_node_event_map: + memnodes.append(MemNode.from_json(event)) + if memnodes: + for memnode in memnodes: + assert self.start_in_timeline_ns is not None + memnode.timestamp_ns = memnode.timestamp_ns - self.start_in_timeline_ns + if not hostnodes: + self.has_hostnodes = False + if not devicenodes: + self.has_devicenodes = False + if not memnodes: + self.has_memnodes = False + + self.data = self.build_tree(hostnodes, runtimenodes, devicenodes, + memnodes) + self.extra_info = json_data['ExtraInfo'] + + def parse_protobuf(self, protobuf_data): # noqa: C901 + self.schema_version = protobuf_data.get_version() + self.span_idx = str(protobuf_data.get_span_indx()) + try: + self.device_infos = { + device_id: { + 'name': device_property.name, + 'totalGlobalMem': device_property.total_memory, + 'computeMajor': device_property.major, + 'computeMinor': device_property.minor + } + for device_id, device_property in + protobuf_data.get_device_property().items() + } + except Exception: + print( + "paddlepaddle-gpu version is needed to get GPU device informations." + ) + self.device_infos = {} + self.extra_info = protobuf_data.get_extra_info() + self.start_in_timeline_ns = float('inf') + self.has_hostnodes = False + self.has_devicenodes = False + self.has_memnodes = False + node_trees = protobuf_data.get_data() + new_node_trees = {} + for threadid, root in node_trees.items(): + stack = [] + new_stack = [] + new_root = HostNode.from_protobuf(root) + new_node_trees[threadid] = new_root + stack.append(root) + new_stack.append(new_root) + while stack: + current_node = stack.pop() + new_current_node = new_stack.pop() + for child_node in current_node.children_node: + if self.has_hostnodes is False: + self.has_hostnodes = True + new_child_node = HostNode.from_protobuf(child_node) + new_current_node.children_node.append(new_child_node) + stack.append(child_node) + new_stack.append(new_child_node) + for runtime_node in current_node.runtime_node: + new_runtime_node = HostNode.from_protobuf(runtime_node) + new_current_node.runtime_node.append(new_runtime_node) + for device_node in runtime_node.device_node: + new_device_node = DeviceNode.from_protobuf(device_node) + new_runtime_node.device_node.append(new_device_node) + for mem_node in current_node.mem_node: + new_mem_node = MemNode.from_protobuf(mem_node) + new_current_node.mem_node.append(new_mem_node) + new_node_tree_list = traverse_tree(new_node_trees) + for threadid, node_tree_list in new_node_tree_list.items(): + for node in node_tree_list[1:]: # skip root + if node.start_ns < self.start_in_timeline_ns: + self.start_in_timeline_ns = node.start_ns + for threadid, node_tree_list in new_node_tree_list.items(): + for node in node_tree_list: + if node != node_tree_list[0]: # skip root + node.start_ns -= self.start_in_timeline_ns + node.end_ns -= self.start_in_timeline_ns + for runtimenode in node.runtime_node: + runtimenode.end_ns -= self.start_in_timeline_ns + runtimenode.start_ns -= self.start_in_timeline_ns + for device_node in runtimenode.device_node: + if self.has_devicenodes is False: + self.has_devicenodes = True + device_node.start_ns -= self.start_in_timeline_ns + device_node.end_ns -= self.start_in_timeline_ns + for mem_node in node.mem_node: + if self.has_memnodes is False: + self.has_memnodes = True + mem_node.timestamp_ns -= self.start_in_timeline_ns + self.data = new_node_trees + + def build_tree( # noqa: C901 + self, hostnodes, runtimenodes, devicenodes, memnodes): + thread2host_event_nodes = collections.defaultdict(list) + thread2runtime_event_nodes = collections.defaultdict(list) + thread2mem_event_nodes = collections.defaultdict(list) + correlation_id2runtime_event_node = {} + thread_event_trees = {} + thread_ids = set() + for hostnode in hostnodes: + thread2host_event_nodes[hostnode.thread_id].append(hostnode) + thread_ids.add(hostnode.thread_id) + # construct thread2runtime_event_nodes and correlation_id2runtime_event_node + for runtimenode in runtimenodes: + thread2runtime_event_nodes[runtimenode.thread_id].append( + runtimenode) + thread_ids.add(runtimenode.thread_id) + correlation_id2runtime_event_node[ + runtimenode.correlation_id] = runtimenode + + # associate CudaRuntimeTraceEventNode and DeviceTraceEventNode + # construct correlation_id2device_event_nodes + for devicenode in devicenodes: + if devicenode.correlation_id not in correlation_id2runtime_event_node: + continue + runtimenode = correlation_id2runtime_event_node[ + devicenode.correlation_id] + runtimenode.device_node.append(devicenode) + + # construct thread2mem_event_nodes + for memnode in memnodes: + thread2mem_event_nodes[memnode.thread_id].append(memnode) + # sort host event nodes and runtime event nodes according to start_ns and + # end_ns + # the smaller start_ns is, the further ahead position is. + # when start_ns of two nodes are equal, the one with bigger end_ns should be + # ahead. + + def compare_hostnode_func(hostnode1, hostnode2): + if hostnode1.start_ns < hostnode2.start_ns: + return -1 + if hostnode1.start_ns == hostnode2.start_ns: + if hostnode1.end_ns > hostnode2.end_ns: + return -1 + return 1 + + def compare_memnode_func(memnode1, memnode2): + if memnode1.timestamp_ns <= memnode2.timestamp_ns: + return -1 + return 1 + + for threadid, hostnodes in thread2host_event_nodes.items(): + thread2host_event_nodes[threadid] = sorted( + hostnodes, key=functools.cmp_to_key(compare_hostnode_func)) + for threadid, runtimenodes in thread2runtime_event_nodes.items(): + thread2runtime_event_nodes[threadid] = sorted( + runtimenodes, key=functools.cmp_to_key(compare_hostnode_func)) + for threadid, memnodes in thread2mem_event_nodes.items(): + thread2mem_event_nodes[threadid] = sorted( + memnodes, key=functools.cmp_to_key(compare_memnode_func)) + + # construct trees + for threadid in thread_ids: + thread_event_trees[threadid] = self._build_tree_relationship( + thread2host_event_nodes[threadid], + thread2runtime_event_nodes[threadid], + thread2mem_event_nodes[threadid]) + + return thread_event_trees + + def _build_tree_relationship( # noqa: C901 + self, host_event_nodes, runtime_event_nodes, mem_event_nodes): + # root node + root_node = HostNode() + root_node.name, root_node.type, root_node.start_ns, root_node.end_ns = "root node", "UserDefined", \ + 0, sys.maxsize + # push root node into node_stack + node_stack = [] + node_stack.append(root_node) + # handle host_event_nodes + for host_node in host_event_nodes: + while True: + stack_top_node = node_stack[-1] + if host_node.start_ns < stack_top_node.end_ns: + stack_top_node.children_node.append(host_node) + node_stack.append(host_node) + break + else: + node_stack.pop() + # insert runtime node + # select runtime nodes which time range within stack_top_node + hasenter = False + firstposition = 0 + lastposition = len(runtime_event_nodes) + for i, runtimenode in enumerate(runtime_event_nodes): + if runtimenode.start_ns >= stack_top_node.start_ns and \ + runtimenode.end_ns <= stack_top_node.end_ns: + if not hasenter: + firstposition = i + hasenter = True + stack_top_node.runtime_node.append(runtimenode) + else: + # from this runtime node, not within stack_top_node, erase the + # nodes from runtime_event_nodes + if runtimenode.start_ns > stack_top_node.end_ns: + lastposition = i + break + if hasenter: + del runtime_event_nodes[firstposition:lastposition] + # to insert left runtimenode into host_event_nodes + while node_stack: + stack_top_node = node_stack.pop() + # insert runtime node + # select runtime nodes which time range within stack_top_node + firstposition = 0 + lastposition = len(runtime_event_nodes) + hasenter = False + for i, runtimenode in enumerate(runtime_event_nodes): + if runtimenode.start_ns >= stack_top_node.start_ns and runtimenode.end_ns <= stack_top_node.end_ns: + if not hasenter: + firstposition = i + hasenter = True + stack_top_node.runtime_node.append(runtimenode) + else: + # from this runtime node, not within stack_top_node, erase the + # nodes from runtime_event_nodes + if runtimenode.start_ns > stack_top_node.end_ns: + lastposition = i + break + if hasenter: + del runtime_event_nodes[firstposition:lastposition] + + # build relationship between host event node and mem event node + # First, post-order traverse the tree. Then, insert the memory and op + # supplement node into correct host nodes. + stack = [] + flag_stack = [] + post_order_nodes = [] + stack.append(root_node) + flag_stack.append(0) + while stack: + current_node = stack.pop() + flag = flag_stack.pop() + if flag == 0: + stack.append(current_node) + flag_stack.append(1) + for child in current_node.children_node[::-1]: + stack.append(child) + flag_stack.append(0) + else: + post_order_nodes.append(current_node) + for node in post_order_nodes: + hasenter = False + firstposition = 0 + lastposition = len(mem_event_nodes) + for i, mem_node in enumerate(mem_event_nodes): + if mem_node.timestamp_ns >= node.start_ns and mem_node.timestamp_ns <= node.end_ns: + node.mem_node.append(mem_node) + if not hasenter: + firstposition = i + hasenter = True + else: + if mem_node.timestamp_ns > node.end_ns: + lastposition = i + break + if hasenter: + del mem_event_nodes[firstposition:lastposition] + + return root_node + + def get_data(self): + return self.data + + def get_extra_info(self): + return self.extra_info + + def get_schema_version(self): + return self.schema_version + + def get_device_infos(self): + return self.device_infos + + def get_span_idx(self): + return self.span_idx + + def has_device(self): + return self.has_devicenodes + + def has_host(self): + return self.has_hostnodes + + def has_memory(self): + return self.has_memnodes + + def save(self, path, format): + pass + + +def load_profiler_json(file_name): + content = json.load(open(file_name, 'r')) + return ProfilerResult(content) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/kernel_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/kernel_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c1289da5be96c58184057005c76afeec096021 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/kernel_parser.py @@ -0,0 +1,175 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections + + +class TC_Allowlist(dict): + # Refer to https://github.com/NVIDIA/PyProf/blob/fd1b2902e3306119eee40ba6b6e8b2f816920c29/pyprof/prof/tc.py#L19 + allowlist = [ + 'h884', 's884', 'h1688', 's1688', 'hmma', 'i8816', '16816', + 'dgrad_1x1_stride_2x2', 'first_layer_wgrad_kernel', 'conv1x1', + 'conv2d_c1_k1', 'direct_group', 'xmma_implicit_gemm', + 'xmma_sparse_conv', 'xmma_warp_specialized_implicit_gemm', 'xmma_gemm', + 'xmma_sparse_gemm', 'c1688' + ] + + def __init__(self): + pass + + def __contains__(self, item): + # If kernel name contains substring equal to any one in allowlist, then it uses tensor core. + for pattern in self.allowlist: + if pattern in item: + return True + return False + + +_allow_list = TC_Allowlist() + + +class DeviceItem: + def __init__(self, name): + self.name = name + self.call = 0 + self.gpu_time = 0 + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.tensorcore_used = True if name in _allow_list else False + self.sum_blocks_per_sm = 0.0 + self.sum_occupancy = 0.0 + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_item(self, node): + self.call += 1 + self.add_gpu_time(node.end_ns - node.start_ns) + self.sum_blocks_per_sm += node.blocks_per_sm + self.sum_occupancy += node.occupancy + + +class KernelParser: + def __init__(self): + self.kernel_items = {} # for kernel summary + self.kernel_items_with_op_name_attributes = collections.defaultdict( + dict) + self.gpu_ids = set() + self.occupancy = 0.0 + self.sm_efficiency = 0.0 + self.tensor_core_ratio = 0.0 + + def parse(self, nodelists): # noqa: C901 + total_duration = 0.0 + weighted_occupancy = 0.0 + weighted_sm_efficiency = 0.0 + for threadid, nodes in nodelists.items(): + for node in nodes: + if node.type == 'Operator': + op_name = node.name + for children in node.children_node: + if children.type == 'OperatorInner': + for runtime_node in children.runtime_node: + for device_node in runtime_node.device_node: + if device_node.type == 'Kernel': + op_attribute_name = self._translate_op_name_attributes_to_string( + op_name, device_node) + if op_attribute_name not in self.kernel_items_with_op_name_attributes[ + device_node.name]: + self.kernel_items_with_op_name_attributes[ + device_node.name][ + op_attribute_name] = DeviceItem( + device_node.name) + self.kernel_items_with_op_name_attributes[ + device_node. + name][op_attribute_name].add_item( + device_node) + for runtime_node in node.runtime_node: + for device_node in runtime_node.device_node: + if device_node.type == 'Kernel': + op_attribute_name = self._translate_op_name_attributes_to_string( + op_name, device_node) + if op_attribute_name not in self.kernel_items_with_op_name_attributes[ + device_node.name]: + self.kernel_items_with_op_name_attributes[ + device_node. + name][op_attribute_name] = DeviceItem( + device_node.name) + self.kernel_items_with_op_name_attributes[ + device_node. + name][op_attribute_name].add_item( + device_node) + elif node.type == 'OperatorInner': + continue + op_name = node.name + for runtime_node in node.runtime_node: + for device_node in runtime_node.device_node: + if device_node.type == 'Kernel': + op_attribute_name = self._translate_op_name_attributes_to_string( + op_name, device_node) + if op_attribute_name not in self.kernel_items_with_op_name_attributes[ + device_node.name]: + self.kernel_items_with_op_name_attributes[ + device_node. + name][op_attribute_name] = DeviceItem( + device_node.name) + self.kernel_items_with_op_name_attributes[ + device_node.name][op_attribute_name].add_item( + device_node) + + for threadid, nodes in nodelists.items(): + for node in nodes: + for runtime_node in node.runtime_node: + for device_node in runtime_node.device_node: + if device_node.type == 'Kernel': + name = device_node.name + if name not in self.kernel_items: + self.kernel_items[name] = DeviceItem(name) + self.kernel_items[name].add_item(device_node) + weighted_occupancy += ( + device_node.occupancy / 100) * ( + device_node.end_ns - device_node.start_ns) + if device_node.blocks_per_sm > 1: + sm_efficiency = 1 + else: + sm_efficiency = device_node.blocks_per_sm + weighted_sm_efficiency += sm_efficiency * ( + device_node.end_ns - device_node.start_ns) + total_duration += ( + device_node.end_ns - device_node.start_ns) + self.gpu_ids.add(device_node.device_id) + self.occupancy = weighted_occupancy / total_duration if total_duration != 0 else 0.0 + self.sm_efficiency = weighted_sm_efficiency # to divide ProfileStep time in ProfileData + total_time = 0 + total_tensorcore_time = 0 + for name, node in self.kernel_items.items(): + if node.tensorcore_used: + total_tensorcore_time += node.gpu_time + total_time += node.gpu_time + self.tensor_core_ratio = total_tensorcore_time / total_time if total_time != 0 else 0.0 + + def _translate_op_name_attributes_to_string(self, op_name, event): + result = '{}-[{},{},{}]-[{},{},{}]-{}-{}'.format( + op_name, event.grid_x, event.grid_y, event.grid_z, event.block_x, + event.block_y, event.block_z, event.registers_per_thread, + event.shared_memory) + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/memory_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/memory_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..7836c88d8c20d185c1aab992ddd3570215b8e82f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/memory_parser.py @@ -0,0 +1,180 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections + +from .utils import traverse_tree + + +class MemoryItem: + def __init__(self, event_name, place, memory_type='Allocated'): + self.event_name = event_name + self.place = place + self.allocation_count = 0 + self.free_count = 0 + self.allocation_size = 0 + self.free_size = 0 + self.increase_size = 0 + self.memory_type = memory_type + + def add_memory_record(self, size, allocation_type): + if allocation_type == 'Allocate' or allocation_type == 'ReservedAllocate': + self.allocation_count += 1 + self.allocation_size += size + + elif allocation_type == 'Free' or allocation_type == 'ReservedFree': + self.free_count += 1 + self.free_size -= size # size is sign(-) when free. + + else: + print("No corresponding type.") + self.increase_size = self.allocation_size - self.free_size + + +class MemoryParser: + def __init__(self): + self.allocated_items = collections.defaultdict( + dict) # for memory summary, device type: event + self.reserved_items = collections.defaultdict( + dict) # for memory summary, device type: event + self.peak_allocation_values = collections.defaultdict(int) + self.peak_reserved_values = collections.defaultdict(int) + self.memory_events = collections.defaultdict(lambda: collections. + defaultdict(list)) + self.memory_curve = collections.defaultdict(lambda: collections. + defaultdict(list)) + self.paired_events = collections.defaultdict(list) + self.size_ranges = {} + + def parse(self, nodetrees): # noqa: C901 + r""" + Analyse memory event in the nodetress. + """ + thread2hostnodes = traverse_tree(nodetrees) + for threadid, host_nodes in thread2hostnodes.items(): + for host_node in host_nodes[1:]: # skip root node + if host_node.type == 'OperatorInner': + continue + if host_node.type == 'Operator': + for child in host_node.children_node: + self._analyse_node_memory(host_node.name, child) + self._analyse_node_memory(host_node.name, host_node) + + # pair for memory events + for device_type, memory_events in self.memory_events.items(): + max_size = 0 + for (addr, memory_type), memory_lists in memory_events.items(): + memory_lists = sorted(memory_lists, key=lambda x: x[0]) + paired_results = [] + for memory_list in memory_lists: + timestamp, memory_type, hostnodename, size = memory_list + if memory_type == 'Allocate' or memory_type == 'ReservedAllocate': + if size > max_size: + max_size = size + if memory_type == 'Allocate': + paired_results.append([ + addr, 'Allocated', hostnodename, timestamp, + None, None, size + ]) + else: + paired_results.append([ + addr, 'ReservedAllocate', hostnodename, + timestamp, None, None, size + ]) + elif memory_type == 'Free' or memory_type == 'ReservedFree': + if -size > max_size: + max_size = -size + if paired_results: + if paired_results[-1][-3] is None: + paired_results[-1][-3] = hostnodename + paired_results[-1][-2] = timestamp + self.paired_events[device_type].append( + paired_results.pop()) + else: + if memory_type == 'Free': + paired_results.append([ + addr, 'Allocated', None, None, + hostnodename, timestamp, -size + ]) + else: + paired_results.append([ + addr, 'ReservedAllocate', None, None, + hostnodename, timestamp, -size + ]) + self.paired_events[device_type].append( + paired_results.pop()) + else: + if memory_type == 'Free': + paired_results.append([ + addr, 'Allocated', None, None, + hostnodename, timestamp, -size + ]) + else: + paired_results.append([ + addr, 'ReservedAllocate', None, None, + hostnodename, timestamp, -size + ]) + self.paired_events[device_type].append( + paired_results.pop()) + + self.paired_events[device_type].extend(paired_results) + self.size_ranges[device_type] = (0, max_size) + + def _analyse_node_memory(self, event_name, node): + for memnode in node.mem_node: # self mem node + if memnode.type == 'Allocate' or memnode.type == 'Free': + if event_name not in self.allocated_items[memnode.place]: + self.allocated_items[ + memnode.place][event_name] = MemoryItem( + event_name, memnode.place, 'Allocated') + self.allocated_items[ + memnode.place][event_name].add_memory_record( + memnode.increase_bytes, memnode.type) + self.memory_events[memnode.place][(memnode.addr, + 'Allocated')].append([ + memnode.timestamp_ns, + memnode.type, + event_name, + memnode.increase_bytes + ]) + + elif memnode.type == 'ReservedAllocate' or memnode.type == 'ReservedFree': + if event_name not in self.reserved_items[memnode.place]: + self.reserved_items[ + memnode.place][event_name] = MemoryItem( + event_name, memnode.place, 'Reserved') + self.reserved_items[ + memnode.place][event_name].add_memory_record( + memnode.increase_bytes, memnode.type) + self.memory_events[memnode.place][(memnode.addr, + "Reserved")].append([ + memnode.timestamp_ns, + memnode.type, + event_name, + memnode.increase_bytes + ]) + self.memory_curve[memnode.place]['Allocated'].append( + (memnode.timestamp_ns, memnode.current_allocated, event_name)) + self.memory_curve[memnode.place]['Reserved'].append( + (memnode.timestamp_ns, memnode.current_reserved, event_name)) + self.memory_curve[memnode.place]['PeakAllocated'].append( + (memnode.timestamp_ns, memnode.peak_allocated, event_name)) + self.memory_curve[memnode.place]['PeakReserved'].append( + (memnode.timestamp_ns, memnode.peak_reserved, event_name)) + self.peak_allocation_values[memnode.place] = max( + self.peak_allocation_values[memnode.place], + memnode.peak_allocated) + self.peak_reserved_values[memnode.place] = max( + self.peak_reserved_values[memnode.place], + memnode.peak_reserved) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/operator_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/operator_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..9c72b24f07bd5969e6399180078667affb2fca4c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/operator_parser.py @@ -0,0 +1,133 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections + +from .kernel_parser import DeviceItem +from .utils import wrap_tree + + +class OperatorItem: + def __init__(self, name): + self.name = name + self.call = 0 + self.cpu_time = 0 + self.gpu_time = 0 + self.max_cpu_time = 0 + self.min_cpu_time = float('inf') + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.devices = {} + self.operator_inners = {} + self.general_gpu_time = 0 + self.min_general_gpu_time = float('inf') + self.max_general_gpu_time = 0 + + @property + def avg_cpu_time(self): + return self.cpu_time / self.call + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + @property + def avg_general_gpu_time(self): + return self.general_gpu_time / self.call + + def add_cpu_time(self, time): + if time > self.max_cpu_time: + self.max_cpu_time = time + if time < self.min_cpu_time: + self.min_cpu_time = time + self.cpu_time += time + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_general_gpu_time(self, time): + if time > self.max_general_gpu_time: + self.max_general_gpu_time = time + if time < self.min_general_gpu_time: + self.min_general_gpu_time = time + self.general_gpu_time += time + + def add_call(self): + self.call += 1 + + def add_item(self, node): + self.add_call() + self.add_cpu_time(node.cpu_time) + self.add_gpu_time(node.gpu_time) + self.add_general_gpu_time(node.general_gpu_time) + for child in node.children_node: + if child.type != 'Operator': + if child.name not in self.operator_inners: + self.operator_inners[child.name] = OperatorItem(child.name) + self.operator_inners[child.name].add_item(child) + + for runtimenode in node.runtime_node: + for devicenode in runtimenode.device_node: + name = devicenode.name + if name not in self.devices: + self.devices[name] = DeviceItem(name) + self.devices[name].add_item(devicenode) + + +class OperatorParser: + r""" + Analyse operator event in profiling data, correlate with its device event. + """ + + def __init__(self): + self.items = {} # for operator summary + self.items_with_input_shape = collections.defaultdict(dict) + + def parse(self, nodetrees): + r""" + Analysis operator event in the nodetress. + """ + node_statistic_trees, thread2host_statistic_nodes = wrap_tree( + nodetrees) + for threadid, host_statistic_nodes in thread2host_statistic_nodes.items( + ): + for host_statistic_node in host_statistic_nodes[ + 1:]: # skip root node + if host_statistic_node.type == 'Operator': + self.add_operator_item(host_statistic_node) + + def add_operator_item(self, operator_node): + if operator_node.name not in self.items: + self.items[operator_node.name] = OperatorItem(operator_node.name) + input_shape_str = self._translate_op_input_shape_to_string( + operator_node.input_shapes) + if input_shape_str not in self.items_with_input_shape[ + operator_node.name]: + self.items_with_input_shape[ + operator_node.name][input_shape_str] = OperatorItem( + operator_node.name) + + self.items[operator_node.name].add_item(operator_node) + self.items_with_input_shape[ + operator_node.name][input_shape_str].add_item(operator_node) + + def _translate_op_input_shape_to_string(self, input_shape): + result = '' + for arg, shape in input_shape.items(): + result += '{}-{}\t'.format(arg, shape) + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/overview_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/overview_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..0c058cc4ea80905afbb2c7c9dca7e1096ee99451 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/overview_parser.py @@ -0,0 +1,456 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections + +from .utils import merge_ranges +from .utils import merge_self_ranges +from .utils import rebuild_node_trees +from .utils import sum_ranges +from .utils import traverse_tree + +StageType = ['Dataloader', 'Forward', 'Backward', 'Optimization'] + +CPUType = [ + 'Operator', 'CudaRuntime', 'UserDefined', 'OperatorInner', 'Communication', + 'PythonOp', 'PythonUserDefined', 'MluRuntime' +] + +GPUType = ['Kernel', 'Memcpy', 'Memset'] + + +class GeneralItem: + def __init__(self, name): + self.name = name + self.call = 0 + self.cpu_time = 0 + self.max_cpu_time = 0 + self.min_cpu_time = float('inf') + self.gpu_time = 0 + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.general_gpu_time = 0 + self.min_general_gpu_time = float('inf') + self.max_general_gpu_time = 0 + + @property + def avg_cpu_time(self): + return self.cpu_time / self.call + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + @property + def avg_general_gpu_time(self): + return self.general_gpu_time / self.call + + def add_cpu_time(self, time): + if time > self.max_cpu_time: + self.max_cpu_time = time + if time < self.min_cpu_time: + self.min_cpu_time = time + self.cpu_time += time + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + self.gpu_time += time + + def add_general_gpu_time(self, time): + if time > self.max_general_gpu_time: + self.max_general_gpu_time = time + if time < self.min_general_gpu_time: + self.min_general_gpu_time = time + self.general_gpu_time += time + + def add_call(self): + self.call += 1 + + def add_item(self, node): + self.add_call() + self.add_cpu_time(node.cpu_time) + self.add_gpu_time(node.gpu_time) + self.add_general_gpu_time(node.general_gpu_time) + + +class ModelPerspectiveItem: + def __init__(self, name): + self.name = name + self.call = 0 + self.cpu_time = 0 + self.max_cpu_time = 0 + self.min_cpu_time = float('inf') + self.gpu_time = 0 + self.max_gpu_time = 0 + self.min_gpu_time = float('inf') + self.cpu_times = {} + self.gpu_times = {} + + @property + def avg_cpu_time(self): + return self.cpu_time / self.call + + @property + def avg_gpu_time(self): + return self.gpu_time / self.call + + def add_call(self): + self.call += 1 + + def add_cpu_time(self, time): + self.add_call() + if time > self.max_cpu_time: + self.max_cpu_time = time + if time < self.min_cpu_time: + self.min_cpu_time = time + self.cpu_time += time + + def add_gpu_time(self, time): + if time > self.max_gpu_time: + self.max_gpu_time = time + if time < self.min_gpu_time: + self.min_gpu_time = time + + def set_gpu_time(self, time): + ''' + Use this to set total gpu time in case gpu time calculated by add_gpu_time include overlap. + ''' + self.gpu_time = time + + +class OverviewParser: + r""" + Analyse time ranges for each TracerEventType, and summarize the time. + """ + + def __init__(self): + # event name: GeneralItem + self.memory_manipulation_items = {} # for memory manipulation summary + self.userdefined_items = {} # for userdefined summary + self.model_perspective_items = {} + # phase name: + # device name: + # stage idx: + # thread name: + # event type: + # {"events" :[], "times": []} + self.events_per_stage = collections.defaultdict( + lambda: collections.defaultdict(lambda: collections.defaultdict( + lambda: collections.defaultdict( + lambda: collections.defaultdict(lambda: collections. + defaultdict(list)))))) + # phase name: + # device name: + # stage idx: + # event type: + # { "calls" :[], "times": [], "total_time": 0 } + + self.merged_events_per_stage = collections.defaultdict( + lambda: collections.defaultdict(lambda: collections.defaultdict( + lambda: collections.defaultdict(lambda: collections. + defaultdict(list))))) + + self.stage_nums = 0 + self.gpu_ulitization = 0.0 + self.has_forward = False + self.has_device = False + + def parse(self, nodetrees): # noqa: C901 + r""" + Analysis node trees in profiler result, and get time range for different tracer event type. + """ + self._parse_events(nodetrees) + # statistic calling times + # merge time, get time summarization + for stage_name, stage_data in self.events_per_stage.items(): + for device_name, steps_data in stage_data.items(): + for step_idx, thread_data in steps_data.items(): + for thread_id, events in thread_data.items(): + for event_type, events_data in events.items(): + if 'calls' not in self.merged_events_per_stage[ + stage_name][device_name][step_idx][ + event_type]: + self.merged_events_per_stage[stage_name][ + device_name][step_idx][event_type][ + 'calls'] = 0 + if 'total_time' not in self.merged_events_per_stage[ + stage_name][device_name][step_idx][ + event_type]: + self.merged_events_per_stage[stage_name][ + device_name][step_idx][event_type][ + 'total_time'] = 0 + events_data['times'] = merge_self_ranges( + events_data['times'], is_sorted=False) + self.merged_events_per_stage[stage_name][ + device_name][step_idx][event_type][ + 'calls'] += len(events_data['events']) + self.merged_events_per_stage[stage_name][device_name][step_idx][event_type]['times'] =\ + merge_ranges( + self.merged_events_per_stage[stage_name][device_name][step_idx][event_type]['times'], + events_data['times'], is_sorted=True) + + # merge different stages into profile step + stage_names = list(self.merged_events_per_stage.keys()) + self.merged_events_per_stage['ProfileStep'] + for stage_name in stage_names: + stage_data = self.merged_events_per_stage[stage_name] + for device_name, steps_data in stage_data.items(): + for step_idx, events in steps_data.items(): + for event_type, events_data in events.items(): + events_data['total_time'] = sum_ranges( + events_data['times']) + if 'calls' not in self.merged_events_per_stage[ + 'ProfileStep'][device_name][step_idx][ + event_type]: + self.merged_events_per_stage['ProfileStep'][ + device_name][step_idx][event_type]['calls'] = 0 + if 'total_time' not in self.merged_events_per_stage[ + 'ProfileStep'][device_name][step_idx][ + event_type]: + self.merged_events_per_stage['ProfileStep'][ + device_name][step_idx][event_type][ + 'total_time'] = 0 + self.merged_events_per_stage['ProfileStep'][ + device_name][step_idx][event_type][ + 'calls'] += events_data['calls'] + self.merged_events_per_stage['ProfileStep'][ + device_name][step_idx][event_type][ + 'total_time'] += events_data['total_time'] + self.merged_events_per_stage['ProfileStep'][ + device_name][step_idx][event_type][ + 'times'] = merge_ranges( + self.merged_events_per_stage['ProfileStep'] + [device_name][step_idx][event_type] + ['times'], + events_data['times'], + is_sorted=True) + + # add gpu time for model perspective summary + for stage_name, stage_data in self.merged_events_per_stage.items(): + for device_name, steps_data in stage_data.items(): + for step_idx, events in steps_data.items(): + if 'Kernel' in events: + if step_idx == 'ALL': + self.model_perspective_items[ + stage_name].set_gpu_time( + events['Kernel']['total_time']) + continue + self.model_perspective_items[stage_name].add_gpu_time( + events['Kernel']['total_time']) + self.model_perspective_items[stage_name].gpu_times[ + step_idx] = events['Kernel']['total_time'] + + if self.has_device: + self.gpu_ulitization = self.merged_events_per_stage['ProfileStep'][ + 'GPU']['ALL']['Kernel'][ + 'total_time'] / self.model_perspective_items[ + 'ProfileStep'].cpu_time + + def _fill_stage_events( # noqa: C901 + self, node, stage_idx, should_recursive=True): + if node.type == 'Forward': + stage_name = 'Forward' + self.has_forward = True + elif node.type == 'Backward': + stage_name = 'Backward' + elif node.type == 'Optimization': + stage_name = 'Optimization' + elif node.type == 'Dataloader': + stage_name = 'Dataloader' + else: + stage_name = 'Other' + + if should_recursive: + stack = [] + if node.type in StageType: + for children in node.children_node: + stack.append(children) + else: + stack.append(node) + while stack: + current_node = stack.pop() + for childnode in current_node.children_node: + stack.append(childnode) + for runtimenode in current_node.runtime_node: + self.events_per_stage[stage_name]["CPU"][stage_idx][ + runtimenode.thread_id][ + runtimenode.type]['events'].append(runtimenode) + self.events_per_stage[stage_name]["CPU"][stage_idx][ + runtimenode.thread_id][ + runtimenode.type]['times'].append( + (runtimenode.start_ns, runtimenode.end_ns)) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + runtimenode.thread_id][ + runtimenode.type]['events'].append(runtimenode) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + runtimenode.thread_id][ + runtimenode.type]['times'].append( + (runtimenode.start_ns, runtimenode.end_ns)) + for devicenode in runtimenode.device_node: + self.has_device = True + self.events_per_stage[stage_name]["GPU"][stage_idx][ + devicenode.stream_id][ + devicenode.type]['events'].append(devicenode) + self.events_per_stage[stage_name]["GPU"][stage_idx][ + devicenode.stream_id][ + devicenode.type]['times'].append( + (devicenode.start_ns, devicenode.end_ns)) + self.events_per_stage[stage_name]["GPU"]['ALL'][ + devicenode.stream_id][ + devicenode.type]['events'].append(devicenode) + self.events_per_stage[stage_name]["GPU"]['ALL'][ + devicenode.stream_id][ + devicenode.type]['times'].append( + (devicenode.start_ns, devicenode.end_ns)) + if current_node.type == 'Forward' or current_node.type == 'UserDefined': + continue + node_type = current_node.type + if node_type == 'PythonUserDefined': + node_type = 'UserDefined' + self.events_per_stage[stage_name]["CPU"][stage_idx][ + current_node.thread_id][node_type]['events'].append( + current_node) + self.events_per_stage[stage_name]["CPU"][stage_idx][ + current_node.thread_id][node_type]['times'].append( + (current_node.start_ns, current_node.end_ns)) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + current_node.thread_id][node_type]['events'].append( + current_node) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + current_node.thread_id][node_type]['times'].append( + (current_node.start_ns, current_node.end_ns)) + + else: + for runtimenode in node.runtime_node: + self.events_per_stage[stage_name]["CPU"][stage_idx][ + runtimenode.thread_id][runtimenode.type]['events'].append( + runtimenode) + self.events_per_stage[stage_name]["CPU"][stage_idx][ + runtimenode.thread_id][runtimenode.type]['times'].append( + (runtimenode.start_ns, runtimenode.end_ns)) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + runtimenode.thread_id][runtimenode.type]['events'].append( + runtimenode) + self.events_per_stage[stage_name]["CPU"]['ALL'][ + runtimenode.thread_id][runtimenode.type]['times'].append( + (runtimenode.start_ns, runtimenode.end_ns)) + for devicenode in runtimenode.device_node: + self.has_device = True + self.events_per_stage[stage_name]["GPU"][stage_idx][ + devicenode.stream_id][ + devicenode.type]['events'].append(devicenode) + self.events_per_stage[stage_name]["GPU"][stage_idx][ + devicenode.stream_id][devicenode.type]['times'].append( + (devicenode.start_ns, devicenode.end_ns)) + self.events_per_stage[stage_name]["GPU"]['ALL'][ + devicenode.stream_id][ + devicenode.type]['events'].append(devicenode) + self.events_per_stage[stage_name]["GPU"]['ALL'][ + devicenode.stream_id][devicenode.type]['times'].append( + (devicenode.start_ns, devicenode.end_ns)) + + def _parse_events(self, nodetrees): + node_wrapped_trees = rebuild_node_trees(nodetrees) + node_wrapped_threadlist = traverse_tree(node_wrapped_trees) + # analyse user-defined summary + for threadid, wrapped_nodes in node_wrapped_threadlist.items(): + for wrapped_node in wrapped_nodes[1:]: # skip root node + if wrapped_node.type == 'PythonUserDefined': + self.add_userdefined_item(wrapped_node) + + # analyse all events in per stage + thread_count = 0 + for threadid, root_wrapped_node in node_wrapped_trees.items(): + thread_count += 1 + wrapped_profiler_step_nodes = [] + for wrapped_node in root_wrapped_node.children_node: + wrapped_profiler_step_nodes.append(wrapped_node) + self.stage_nums = 0 + current_stage_idx = None + for wrapped_profiler_step_node in wrapped_profiler_step_nodes: + if wrapped_profiler_step_node.type == 'ProfileStep': + self.process_id = wrapped_profiler_step_node.process_id + stage_idx = wrapped_profiler_step_node.name.split('#')[1] + total_time = 0 + accumulated_stage_time = 0 + if thread_count == 1: + self.add_model_perspective_item( + wrapped_profiler_step_node) + self.model_perspective_items['ProfileStep'].cpu_times[ + stage_idx] = wrapped_profiler_step_node.cpu_time + total_time = wrapped_profiler_step_node.cpu_time + self.stage_nums += 1 + for stage_wrapped_node in wrapped_profiler_step_node.children_node: + if thread_count == 1: + self.add_model_perspective_item(stage_wrapped_node) + if stage_wrapped_node.type in StageType: + self.model_perspective_items[ + stage_wrapped_node.type].cpu_times[ + stage_idx] = stage_wrapped_node.cpu_time + if stage_wrapped_node.type in StageType: + accumulated_stage_time += stage_wrapped_node.cpu_time + self._fill_stage_events(stage_wrapped_node, stage_idx) + if 'Other' not in self.model_perspective_items: + self.model_perspective_items[ + 'Other'] = ModelPerspectiveItem('Other') + if thread_count == 1: + self.model_perspective_items['Other'].add_cpu_time( + total_time - accumulated_stage_time) + self.model_perspective_items['Other'].cpu_times[ + stage_idx] = total_time - accumulated_stage_time + self._fill_stage_events( + wrapped_profiler_step_node, + stage_idx, + should_recursive=False) + else: + self._fill_stage_events(wrapped_profiler_step_node, + current_stage_idx) + self._fill_stage_events( + root_wrapped_node, current_stage_idx, should_recursive=False) + + def add_userdefined_item(self, userdefined_node): + if userdefined_node.name not in self.userdefined_items: + self.userdefined_items[userdefined_node.name] = GeneralItem( + userdefined_node.name) + self.userdefined_items[userdefined_node.name].add_item( + userdefined_node) + + def add_memory_manipulation_item(self, memory_manipulation_node): + if memory_manipulation_node.name not in self.memory_manipulation_items: + self.memory_manipulation_items[ + memory_manipulation_node.name] = GeneralItem( + memory_manipulation_node.name) + self.memory_manipulation_items[memory_manipulation_node.name].add_item( + memory_manipulation_node) + + def add_model_perspective_item(self, model_perspective_node): + if model_perspective_node.type == 'Forward': + name = 'Forward' + elif model_perspective_node.type == 'Backward': + name = 'Backward' + elif model_perspective_node.type == 'Optimization': + name = 'Optimization' + elif model_perspective_node.type == 'Dataloader': + name = 'Dataloader' + elif model_perspective_node.type == 'ProfileStep': + name = 'ProfileStep' + else: + return + if name not in self.model_perspective_items: + self.model_perspective_items[name] = ModelPerspectiveItem(name) + self.model_perspective_items[name].add_cpu_time( + model_perspective_node.cpu_time) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/trace_parser.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/trace_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1ef29bd0b0453bb775e017f6a2bab3ede103ce --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/trace_parser.py @@ -0,0 +1,20 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +class TraceParser: + def __init__(self): + pass + + def parse(self, content): + self.content = content diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/utils.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..48f7494fea02ca83b6b98d5a4a83c675e77eae17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/parser/utils.py @@ -0,0 +1,516 @@ +# Copyright (c) 2022 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. +import collections +import os +import sys + +StageType = ['Dataloader', 'Forward', 'Backward', 'Optimization'] + + +def sum_ranges(ranges): + result = 0 + for time_range in ranges: + result += (time_range[1] - time_range[0]) + return result + + +def merge_self_ranges(src_ranges, is_sorted=False): + merged_ranges = [] + if len(src_ranges) > 0: + if not is_sorted: + src_ranges.sort(key=lambda x: x[0]) + cur_indx = 0 + merged_ranges.append((src_ranges[cur_indx][0], + src_ranges[cur_indx][1])) + for cur_indx in range(1, len(src_ranges)): + if src_ranges[cur_indx][1] > merged_ranges[-1][1]: + if src_ranges[cur_indx][0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], + src_ranges[cur_indx][1]) + else: + merged_ranges.append((src_ranges[cur_indx][0], + src_ranges[cur_indx][1])) + return merged_ranges + + +def merge_ranges(range_list1, range_list2, is_sorted=False): # noqa:C901 + merged_ranges = [] + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + len1 = len(range_list1) + len2 = len(range_list2) + if len1 == 0 and len2 == 0: + return merged_ranges + elif len1 == 0: + return range_list2 + elif len2 == 0: + return range_list1 + else: + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + if range1[0] < range2[0]: + merged_ranges.append(range1) + indx1 += 1 + else: + merged_ranges.append(range2) + indx2 += 1 + while indx1 < len1 and indx2 < len2: + range1 = range_list1[indx1] + range2 = range_list2[indx2] + if range1[0] < range2[0]: + if range1[1] > merged_ranges[-1][1]: + if range1[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range1[1]) + else: + merged_ranges.append((range1[0], range1[1])) + indx1 += 1 + else: + indx1 += 1 + else: + if range2[1] > merged_ranges[-1][1]: + if range2[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range2[1]) + else: + merged_ranges.append((range2[0], range2[1])) + indx2 += 1 + else: + indx2 += 1 + + while indx1 < len1: + range1 = range_list1[indx1] + if range1[1] > merged_ranges[-1][1]: + if range1[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range1[1]) + else: + merged_ranges.append((range1[0], range1[1])) + indx1 += 1 + else: + indx1 += 1 + while indx2 < len2: + range2 = range_list2[indx2] + if range2[1] > merged_ranges[-1][1]: + if range2[0] <= merged_ranges[-1][1]: + merged_ranges[-1] = (merged_ranges[-1][0], range2[1]) + else: + merged_ranges.append((range2[0], range2[1])) + indx2 += 1 + else: + indx2 += 1 + return merged_ranges + + +def intersection_ranges(range_list1, range_list2, is_sorted=False): + result_range = [] + if len(range_list1) == 0 or len(range_list2) == 0: + return result_range + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + + len1 = len(range_list1) + len2 = len(range_list2) + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + while indx1 < len1 and indx2 < len2: + if range2[1] <= range1[0]: + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] <= range1[0] and range2[1] < range1[1]: + assert (range2[1] > range1[0]) + result_range.append((range1[0], range2[1])) + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] <= range1[0]: + assert (range2[1] >= range1[1]) + result_range.append(range1) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + + elif range2[1] < range1[1]: + assert (range2[0] > range1[0]) + result_range.append(range2) + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 == len2: + break + range2 = range_list2[indx2] + + elif range2[0] < range1[1]: + assert (range2[1] >= range1[1]) + result_range.append((range2[0], range1[1])) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + + else: + assert (range2[0] >= range1[1]) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + return result_range + + +def subtract_ranges(range_list1, range_list2, is_sorted=False): + result_range = [] + if not is_sorted: + range_list1 = merge_self_ranges(range_list1) + range_list2 = merge_self_ranges(range_list2) + if len(range_list1) == 0: + return result_range + if len(range_list2) == 0: + return range_list1 + + len1 = len(range_list1) + len2 = len(range_list2) + indx1 = 0 + indx2 = 0 + range1 = range_list1[indx1] + range2 = range_list2[indx2] + + while indx1 < len(range_list1): + if indx2 == len(range_list2): + result_range.append(range1) + indx1 += 1 + if indx1 == len1: + break + range1 = range_list1[indx1] + elif range2[1] <= range1[0]: + indx2 += 1 + if indx2 != len2: + range2 = range_list2[indx2] + elif range2[0] <= range1[0] and range2[1] < range1[1]: + range1 = (range2[1], range1[1]) + indx2 += 1 + if indx2 != len2: + range2 = range_list2[indx2] + elif range2[0] <= range1[0]: + assert (range2[1] >= range1[1]) + range2 = (range1[1], range2[1]) + indx1 += 1 + if indx1 != len1: + range1 = range_list1[indx1] + elif range2[0] < range1[1]: + assert (range2[0] > range1[0]) + result_range.append((range1[0], range2[0])) + range1 = (range2[0], range1[1]) + else: + assert (range2[0] >= range1[1]) + result_range.append(range1) + indx1 += 1 + if indx1 != len1: + range1 = range_list1[indx1] + return result_range + + +class HostStatisticNode: + r''' + Wrap original node for calculating statistic metrics. + ''' + + def __init__(self, hostnode): + self.hostnode = hostnode + self.children_node = [] + self.runtime_node = [] + self.cpu_time = 0 + self.self_cpu_time = 0 + self.gpu_time = 0 # kernel time + self.self_gpu_time = 0 + self.general_gpu_time = 0 # besides kernel, include time of gpu events like memcpy and memset + self.self_general_gpu_time = 0 + self.is_terminal_operator_node = True + + def cal_statistic(self): + for child in self.children_node: + child.cal_statistic() + if child.is_terminal_operator_node is False: + self.is_terminal_operator_node = False + for rt in self.runtime_node: + rt.cal_statistic() + self.cpu_time = self.hostnode.end_ns - self.hostnode.start_ns + self.self_cpu_time = self.cpu_time + for child in self.children_node: + if child.type == 'Operator': + self.is_terminal_operator_node = False + self.gpu_time += child.gpu_time + self.general_gpu_time += child.general_gpu_time + self.self_cpu_time -= (child.end_ns - child.start_ns) + for rt in self.runtime_node: + self.self_cpu_time -= (rt.end_ns - rt.start_ns) + self.gpu_time += rt.gpu_time + self.self_gpu_time += rt.gpu_time + self.general_gpu_time += rt.general_gpu_time + self.self_general_gpu_time += rt.general_gpu_time + for device in self.hostnode.device_node: + if device.type == 'Kernel': + self.gpu_time += (device.end_ns - device.start_ns) + self.self_gpu_time += (device.end_ns - device.start_ns) + self.general_gpu_time += (device.end_ns - device.start_ns) + self.self_general_gpu_time += (device.end_ns - device.start_ns) + + @property + def end_ns(self): + return self.hostnode.end_ns + + @property + def start_ns(self): + return self.hostnode.start_ns + + def __getattr__(self, name): + return getattr(self.hostnode, name) + + +def traverse_tree(nodetrees): + results = collections.defaultdict(list) + for thread_id, rootnode in nodetrees.items(): + stack = [] + stack.append(rootnode) + threadlist = results[thread_id] + while stack: + current_node = stack.pop() + threadlist.append(current_node) + for childnode in current_node.children_node: + stack.append(childnode) + return results + + +def get_device_nodes(hostnode): + ''' + Get all device nodes called in the time range of hostnode. + ''' + stack = [] + device_nodes = [] + stack.append(hostnode) + while stack: + current_node = stack.pop() + for childnode in current_node.children_node: + stack.append(childnode) + for runtimenode in current_node.runtime_node: + for devicenode in runtimenode.device_node: + device_nodes.append(devicenode) + return device_nodes + + +def wrap_tree(nodetrees): + ''' + Using HostStatisticNode to wrap original profiler result tree, and calculate node statistic metrics. + ''' + node_statistic_tree = {} + results = collections.defaultdict(list) + newresults = collections.defaultdict(list) + for thread_id, rootnode in nodetrees.items(): + stack = [] + stack.append(rootnode) + root_statistic_node = HostStatisticNode(rootnode) + newstack = [] + newstack.append(root_statistic_node) + node_statistic_tree[thread_id] = root_statistic_node + threadlist = results[thread_id] + newthreadlist = newresults[thread_id] + while stack: + current_node = stack.pop() + threadlist.append(current_node) + current_statistic_node = newstack.pop() + newthreadlist.append(current_statistic_node) + for childnode in current_node.children_node: + stack.append(childnode) + child_statistic_node = HostStatisticNode(childnode) + current_statistic_node.children_node.append( + child_statistic_node) + newstack.append(child_statistic_node) + for runtimenode in current_node.runtime_node: + runtime_statistic_node = HostStatisticNode(runtimenode) + current_statistic_node.runtime_node.append( + runtime_statistic_node) + # recursive calculate node statistic values + for thread_id, root_statistic_node in node_statistic_tree.items(): + root_statistic_node.cal_statistic() + + return node_statistic_tree, newresults + + +def rebuild_node_trees(nodetrees): # noqa:C901 + template_root = None + # First, we find the tree which includes Forward event. + for threadid, root in nodetrees.items(): + has_find_template_root = False + template_root = HostStatisticNode(root) + for children in root.children_node: + if children.type == 'ProfileStep': + profiler_step_node = HostStatisticNode(children) + template_root.children_node.append(profiler_step_node) + has_find_template_root = True + for stage_node in children.children_node: + if stage_node.type in StageType: + profiler_step_node.children_node.append( + HostStatisticNode(stage_node)) + else: + break + if has_find_template_root is True: + break + + if template_root is None: + print('No profiler steps found, overview page will have no data.') + + wrapped_tree = {} + for thread_id, rootnode in nodetrees.items(): + has_find_template_root = False + for children in rootnode.children_node: + if children.type == 'ProfileStep': + has_find_template_root = True + break + + unwrapped_stack = [] + warpped_stack = [] + + root_statistic_node = HostStatisticNode(rootnode) + wrapped_tree[thread_id] = root_statistic_node + if has_find_template_root is False: + for profiler_step_node in template_root.children_node: + profiler_step_wrap_node = HostStatisticNode( + profiler_step_node.hostnode) + root_statistic_node.children_node.append( + profiler_step_wrap_node) + for stage_node in profiler_step_node.children_node: + stage_wrap_node = HostStatisticNode(stage_node.hostnode) + profiler_step_wrap_node.children_node.append( + stage_wrap_node) + # insert nodes in original root into new stage nodes + # algorithm: post order traversal the tree + stack = [] + flag_stack = [] + post_order_nodes = [] + stack.append(root_statistic_node) + flag_stack.append(0) + while stack: + current_node = stack.pop() + flag = flag_stack.pop() + if flag == 0: + stack.append(current_node) + flag_stack.append(1) + for children_node in reversed(current_node.children_node): + stack.append(children_node) + flag_stack.append(0) + else: + post_order_nodes.append(current_node) + # traverse post_order_nodes and insert right position + for runtimenode in rootnode.runtime_node: + runtime_wrapped_node = HostStatisticNode(runtimenode) + root_statistic_node.runtime_node.append(runtime_wrapped_node) + for node in rootnode.children_node: + unwrapped_stack.append(node) + for wrapped_node in post_order_nodes: + if node.start_ns >= wrapped_node.start_ns and node.end_ns <= wrapped_node.end_ns: + child_wrapped_node = HostStatisticNode(node) + warpped_stack.append(child_wrapped_node) + wrapped_node.children_node.append(child_wrapped_node) + break + else: + unwrapped_stack.append(rootnode) + warpped_stack.append(root_statistic_node) + while unwrapped_stack: + current_node = unwrapped_stack.pop() + current_wrapped_node = warpped_stack.pop() + for childnode in current_node.children_node: + unwrapped_stack.append(childnode) + child_wrapped_node = HostStatisticNode(childnode) + current_wrapped_node.children_node.append(child_wrapped_node) + warpped_stack.append(child_wrapped_node) + for runtimenode in current_node.runtime_node: + runtime_wrapped_node = HostStatisticNode(runtimenode) + current_wrapped_node.runtime_node.append(runtime_wrapped_node) + + # recursive calculate node statistic values + for thread_id, root_wrapped_node in wrapped_tree.items(): + root_wrapped_node.cal_statistic() + return wrapped_tree + + +def format_time(time, unit='ms', inf_subs='-'): + r""" + Transform time in ns to time in unit. + """ + if time == float('inf'): + return inf_subs + else: + result = float(time) + if unit == 's': + result /= 1e9 + elif unit == 'ms': + result /= 1e6 + elif unit == 'us': + result /= 1e3 + return round(result, 2) + + +def format_ratio(ratio): + r""" + Transform ratio within [0, 1] to percentage presentation. + """ + return round(ratio * 100, 2) + + +def format_float(float_data): + return round(float_data, 2) + + +def format_memory(memory, memory_unit='KB'): + result = float(memory) + if memory_unit == 'GB': + result /= (1024 * 1024 * 1024) + elif memory_unit == 'MB': + result /= (1024 * 1024) + elif memory_unit == 'KB': + result /= 1024 + return round(result, 2) + + +class RedirectStdStreams(object): + def __init__(self, stdout=None, stderr=None): + self._stdout = stdout or sys.stdout + self._stderr = stderr or sys.stderr + + def __enter__(self): + ''' + Replace stdout and stderr to specified stream. + ''' + sys.stdout.flush() + sys.stderr.flush() + self.old_stdout_fileno, self.old_stderr_fileno = os.dup( + sys.stdout.fileno()), os.dup(sys.stderr.fileno()) + os.dup2(self._stdout.fileno(), sys.stdout.fileno()) + os.dup2(self._stderr.fileno(), sys.stderr.fileno()) + + def __exit__(self, exc_type, exc_value, traceback): + os.dup2(self.old_stdout_fileno, sys.stdout.fileno()) + os.dup2(self.old_stderr_fileno, sys.stderr.fileno()) + os.close(self.old_stdout_fileno) + os.close(self.old_stderr_fileno) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_data.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_data.py new file mode 100644 index 0000000000000000000000000000000000000000..469cb52be9f969161b00078eccba643a5968eedf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_data.py @@ -0,0 +1,1879 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from collections import defaultdict +from collections import OrderedDict + +from .parser.distributed_parser import DistributedParser +from .parser.kernel_parser import KernelParser +from .parser.memory_parser import MemoryParser +from .parser.operator_parser import OperatorParser +from .parser.overview_parser import CPUType +from .parser.overview_parser import GPUType +from .parser.overview_parser import OverviewParser +from .parser.trace_parser import TraceParser +from .parser.utils import format_float +from .parser.utils import format_memory +from .parser.utils import format_ratio +from .parser.utils import format_time +from .parser.utils import traverse_tree + + +def filter_type(node_trees): + nodelists = traverse_tree(node_trees) + for thread_id, nodelist in nodelists.items(): + for node in nodelist: + if not isinstance(node.type, str): + node.type = str(node.type).split('.')[1] + + +class ProfilerData: + ''' + Hold all parsed data to serve for user requests. + ''' + + def __init__(self, run, worker_name, span_indx, profiler_result): + self.run = run + self.worker_name = worker_name + self.span_indx = span_indx + self.node_trees = profiler_result.get_data() + filter_type(self.node_trees) + self.extra_infos = profiler_result.get_extra_info() + self.span_idx = profiler_result.get_span_idx() + self.device_infos = profiler_result.get_device_infos() + self.overview_parser = None + self.operator_parser = None + self.distributed_parser = None + self.memory_parser = None + self.kernel_parser = None + self.trace_parser = None + self.has_gpu = profiler_result.has_device() + + if profiler_result.has_host(): + # overview parser + self.overview_parser = OverviewParser() + self.overview_parser.parse(self.node_trees) + self.merged_events_per_stage = self.overview_parser.merged_events_per_stage + self.model_perspective_items = self.overview_parser.model_perspective_items + self.userdefined_items = self.overview_parser.userdefined_items + self.gpu_ulitization = self.overview_parser.gpu_ulitization + self.process_id = self.overview_parser.process_id + # operator parser + self.operator_parser = OperatorParser() + self.operator_parser.parse(self.node_trees) + self.operator_items = self.operator_parser.items + self.operator_items_with_input_shape = self.operator_parser.items_with_input_shape + + # distributed parser + if profiler_result.has_device(): + self.distributed_parser = DistributedParser() + self.distributed_parser.parse(self.node_trees) + self.distributed_time = self.distributed_parser.steps_time + + if profiler_result.has_memory(): + # memory parser + self.memory_parser = MemoryParser() + self.memory_parser.parse(self.node_trees) + self.memory_curve = self.memory_parser.memory_curve + self.allocated_items = self.memory_parser.allocated_items + self.reserved_items = self.memory_parser.reserved_items + self.paired_events = self.memory_parser.paired_events + self.size_ranges = self.memory_parser.size_ranges + self.peak_allocation_values = self.memory_parser.peak_allocation_values + + if profiler_result.has_device(): + # kernel parser + self.kernel_parser = KernelParser() + self.kernel_parser.parse(traverse_tree(self.node_trees)) + self.kernel_items = self.kernel_parser.kernel_items + self.kernel_items_with_op_name_attributes = self.kernel_parser.kernel_items_with_op_name_attributes + self.occupancy = self.kernel_parser.occupancy + self.sm_efficiency = self.kernel_parser.sm_efficiency + self.tensorcore_ratio = self.kernel_parser.tensor_core_ratio + self.gpu_ids = self.kernel_parser.gpu_ids + + # trace parser + self.trace_parser = TraceParser() + self.trace_parser.parse(profiler_result.content) + + def get_views(self): + ''' + Return available views this profile data can provide. + ''' + views = [] + if self.overview_parser: + if self.overview_parser.has_forward: + views.append('Overview') + if self.operator_parser: + if self.operator_items: + views.append('Operator') + if self.kernel_parser: + if self.kernel_items: + views.append('GPU Kernel') + if self.memory_parser: + if self.memory_curve: + views.append('Memory') + if self.distributed_parser: + if self.distributed_time: + views.append('Distributed') + views.append('Trace') + return views + + def get_device_infos(self): + if not self.overview_parser: + return + if not self.overview_parser.has_device: + device_type = 'CPU' + return { + "device_type": device_type, + "CPU": { + "process_utilization": + format_ratio( + float(self.extra_infos["Process Cpu Utilization"])), + "system_utilization": + format_ratio( + float(self.extra_infos["System Cpu Utilization"])) + } + } + else: + device_type = 'GPU' + gpu_id = int(next(iter(self.gpu_ids))) + if gpu_id in self.device_infos: + return { + "device_type": device_type, + "CPU": { + "process_utilization": + format_ratio( + float( + self.extra_infos["Process Cpu Utilization"])), + "system_utilization": + format_ratio( + float(self.extra_infos["System Cpu Utilization"])) + }, + "GPU": { + "name": + self.device_infos[gpu_id]['name'], + "memory": + "{} GB".format( + format_memory( + self.device_infos[gpu_id]['totalGlobalMem'], + 'GB')), + "compute_capability": + '{}.{}'.format( + self.device_infos[gpu_id]['computeMajor'], + self.device_infos[gpu_id]['computeMinor']), + "utilization": + format_ratio(self.gpu_ulitization), + "sm_efficiency": + format_ratio( + self.sm_efficiency / self. + model_perspective_items['ProfileStep'].cpu_time), + "achieved_occupancy": + format_ratio(self.occupancy), + "tensor_core_percentage": + format_ratio(self.tensorcore_ratio) + } + } + else: + return { + "device_type": device_type, + "CPU": { + "process_utilization": + format_ratio( + float( + self.extra_infos["Process Cpu Utilization"])), + "system_utilization": + format_ratio( + float(self.extra_infos["System Cpu Utilization"])) + }, + "GPU": { + "name": + "-", + "memory": + "-", + "compute_capability": + '-', + "utilization": + format_ratio(self.gpu_ulitization), + "sm_efficiency": + format_ratio( + self.sm_efficiency / self. + model_perspective_items['ProfileStep'].cpu_time), + "achieved_occupancy": + format_ratio(self.occupancy), + "tensor_core_percentage": + format_ratio(self.tensorcore_ratio) + } + } + + def get_model_perspective(self, time_unit): + ''' + Get total cpu and gpu statistics for model perspective of each profiler step. + ''' + if not self.overview_parser: + return + data = OrderedDict() + data['column_name'] = [ + "name", "calls", "total_time", "avg_time", "max_time", "min_time", + "ratio" + ] + data['cpu'] = [] + if self.overview_parser.has_device: + data['gpu'] = [] + total_cpu_time = self.model_perspective_items['ProfileStep'].cpu_time + total_gpu_time = self.model_perspective_items['ProfileStep'].gpu_time + for stage_name in [ + 'ProfileStep', 'Dataloader', 'Forward', 'Backward', + 'Optimization', 'Other' + ]: + if stage_name in self.model_perspective_items: + cpu_stage_data = OrderedDict() + cpu_stage_data['name'] = stage_name + cpu_stage_data['calls'] = self.model_perspective_items[ + stage_name].call + cpu_stage_data['total_time'] = format_time( + self.model_perspective_items[stage_name].cpu_time, + time_unit) + cpu_stage_data['avg_time'] = format_time( + self.model_perspective_items[stage_name].avg_cpu_time, + time_unit) + cpu_stage_data['max_time'] = format_time( + self.model_perspective_items[stage_name].max_cpu_time, + time_unit) + cpu_stage_data['min_time'] = format_time( + self.model_perspective_items[stage_name].min_cpu_time, + time_unit, + inf_subs=0) + cpu_stage_data['ratio'] = format_ratio( + self.model_perspective_items[stage_name].cpu_time / + total_cpu_time) + if self.overview_parser.has_device: + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = stage_name + gpu_stage_data['calls'] = self.model_perspective_items[ + stage_name].call + gpu_stage_data['total_time'] = format_time( + self.model_perspective_items[stage_name].gpu_time, + time_unit) + gpu_stage_data['avg_time'] = format_time( + self.model_perspective_items[stage_name].avg_gpu_time, + time_unit) + gpu_stage_data['max_time'] = format_time( + self.model_perspective_items[stage_name].max_gpu_time, + time_unit) + gpu_stage_data['min_time'] = format_time( + self.model_perspective_items[stage_name].min_gpu_time, + time_unit, + inf_subs=0) + gpu_stage_data['ratio'] = format_ratio( + self.model_perspective_items[stage_name].gpu_time / + total_gpu_time) + data['cpu'].append(cpu_stage_data) + if self.overview_parser.has_device: + data['gpu'].append(gpu_stage_data) + return data + + def get_model_perspective_perstep(self, device_type, time_unit): + if not self.overview_parser: + return + try: + data = OrderedDict() + data['order'] = [] + steps = [ + int(step_id) for step_id in + self.model_perspective_items['ProfileStep'].cpu_times.keys() + ] + steps = sorted(steps) + data['steps'] = steps + for stage_name in [ + 'Dataloader', 'Forward', 'Backward', 'Optimization', + 'Other' + ]: + if stage_name not in self.model_perspective_items: + continue + data['order'].append(stage_name) + data[stage_name] = [] + for stage_idx in steps: + stage_idx = str(stage_idx) + if device_type == 'cpu': + if stage_idx in self.model_perspective_items[ + stage_name].cpu_times: + data[stage_name].append( + format_time( + self.model_perspective_items[stage_name]. + cpu_times[stage_idx], time_unit)) + else: + data[stage_name].append(0) + else: + if stage_idx in self.model_perspective_items[ + stage_name].gpu_times: + data[stage_name].append( + format_time( + self.model_perspective_items[stage_name]. + gpu_times[stage_idx], time_unit)) + else: + data[stage_name].append(0) + except Exception as e: + print('error in get_model_perspective_perstep', e) + new_data = {} + new_data['order'] = data['order'] + new_data['steps'] = data['steps'] + new_data['data'] = [] + for name in new_data['order']: + new_data['data'].append(data[name]) + return new_data + + def get_event_type_perspective(self, device_type, time_unit): + if not self.overview_parser: + return + data = OrderedDict() + data['order'] = [] + if device_type == 'cpu': + for event_type in CPUType: + event_type_data = {} + event_type_data['calling_times'] = {} + event_type_data['calling_times']['key'] = [] + event_type_data['calling_times']['value'] = [] + event_type_data['durations'] = {} + event_type_data['durations']['key'] = [] + event_type_data['durations']['value'] = [] + event_type_data['ratios'] = {} + event_type_data['ratios']['key'] = [] + event_type_data['ratios']['value'] = [] + for stage_name in [ + 'Dataloader', 'Forward', 'Backward', 'Optimization', + 'Other' + ]: + if stage_name in self.merged_events_per_stage: + if event_type in self.merged_events_per_stage[ + stage_name]['CPU']['ALL']: + event_type_data['calling_times']['key'].append( + stage_name) + event_type_data['durations']['key'].append( + stage_name) + event_type_data['ratios']['key'].append(stage_name) + event_type_data['calling_times']['value'].append( + self.merged_events_per_stage[stage_name]['CPU'] + ['ALL'][event_type]['calls']) + event_type_data['durations']['value'].append( + format_time( + self.merged_events_per_stage[stage_name] + ['CPU']['ALL'][event_type]['total_time'], + time_unit)) + event_type_data['ratios']['value'].append( + format_ratio( + self.merged_events_per_stage[stage_name] + ['CPU']['ALL'][event_type]['total_time'] / + self.merged_events_per_stage['ProfileStep'] + ['CPU']['ALL'][event_type]['total_time'])) + if event_type_data['calling_times']['key']: + data[event_type] = event_type_data + data['order'].append(event_type) + else: + for event_type in GPUType: + event_type_data = {} + event_type_data['calling_times'] = {} + event_type_data['calling_times']['key'] = [] + event_type_data['calling_times']['value'] = [] + event_type_data['durations'] = {} + event_type_data['durations']['key'] = [] + event_type_data['durations']['value'] = [] + event_type_data['ratios'] = {} + event_type_data['ratios']['key'] = [] + event_type_data['ratios']['value'] = [] + for stage_name in [ + 'Dataloader', 'Forward', 'Backward', 'Optimization', + 'Other' + ]: + if stage_name in self.merged_events_per_stage: + if event_type in self.merged_events_per_stage[ + stage_name]['GPU']['ALL']: + event_type_data['calling_times']['key'].append( + stage_name) + event_type_data['durations']['key'].append( + stage_name) + event_type_data['ratios']['key'].append(stage_name) + event_type_data['calling_times']['value'].append( + self.merged_events_per_stage[stage_name]['GPU'] + ['ALL'][event_type]['calls']) + event_type_data['durations']['value'].append( + format_time( + self.merged_events_per_stage[stage_name] + ['GPU']['ALL'][event_type]['total_time'], + time_unit)) + event_type_data['ratios']['value'].append( + format_ratio( + self.merged_events_per_stage[stage_name] + ['GPU']['ALL'][event_type]['total_time'] / + self.merged_events_per_stage['ProfileStep'] + ['GPU']['ALL'][event_type]['total_time'])) + if event_type_data['calling_times']['key']: + data[event_type] = event_type_data + data['order'].append(event_type) + return data + + def get_event_type_model_perspective(self, time_unit): # noqa: C901 + if not self.overview_parser: + return + data = OrderedDict() + data['order'] = [] + data['phase_type'] = [] + try: + for event_type in CPUType: + if event_type in self.merged_events_per_stage['ProfileStep'][ + 'CPU']['ALL']: + data['order'].append(event_type) + data[event_type] = [] + if self.overview_parser.has_device: + for event_type in GPUType: + if event_type in self.merged_events_per_stage[ + 'ProfileStep']['GPU']['ALL']: + data['order'].append(event_type) + data[event_type] = [] + for stage_name in [ + 'ProfileStep', 'Dataloader', 'Forward', 'Backward', + 'Optimization', 'Other' + ]: + if stage_name in self.merged_events_per_stage: + data['phase_type'].append(stage_name) + for event_type in data['order']: + if event_type in CPUType: + if event_type in self.merged_events_per_stage[ + stage_name]['CPU']['ALL']: + data[event_type].append( + format_time( + self.merged_events_per_stage[ + stage_name]['CPU']['ALL'] + [event_type]['total_time'], time_unit)) + else: + data[event_type].append(0) + elif event_type in GPUType: + if event_type in self.merged_events_per_stage[ + stage_name]['GPU']['ALL']: + data[event_type].append( + format_time( + self.merged_events_per_stage[ + stage_name]['GPU']['ALL'] + [event_type]['total_time'], time_unit)) + else: + data[event_type].append(0) + newdata = OrderedDict() + newdata['order'] = data['order'] + newdata['phase_type'] = data['phase_type'] + newdata['data'] = [] + for key in newdata['order']: + newdata['data'].append(data[key]) + + except Exception as e: + print('error in get_event_type_model_perspective', e) + return newdata + + def get_userdefined_perspective(self, time_unit): + if not self.overview_parser: + return + data = OrderedDict() + if self.overview_parser.has_device: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio', 'gpu_total_time', + 'gpu_avg_time', 'gpu_max_time', 'gpu_min_time', 'gpu_ratio' + ] + data['has_gpu'] = True + else: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio' + ] + data['has_gpu'] = False + data['events'] = [] + + total_cpu_time = 0 + total_gpu_time = 0 + for name, event in self.userdefined_items.items(): + total_cpu_time += event.cpu_time + total_gpu_time += event.general_gpu_time + for name, event in self.userdefined_items.items(): + if self.overview_parser.has_device: + data['events'].append({ + "name": + name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + }) + return data + + def get_operator_pie(self, topk, time_unit='ms'): + if not self.operator_parser: + return + data = OrderedDict() + data['column_name'] = [ + "name", "calls", "total_time", "avg_time", "max_time", "min_time", + "ratio" + ] + data['cpu'] = [] + if self.has_gpu: + data['gpu'] = [] + gpu_sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + + cpu_sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + + if topk <= 0: + cpu_items = cpu_sorted_items + if self.has_gpu: + gpu_items = gpu_sorted_items + else: + cpu_items = cpu_sorted_items[:topk] + if self.has_gpu: + gpu_items = gpu_sorted_items[:topk] + total_cpu_time = 0.0 + total_gpu_time = 0.0 + for op_name, item in cpu_items: + total_cpu_time += item.cpu_time + if self.has_gpu: + for op_name, item in gpu_items: + total_gpu_time += item.general_gpu_time + + for op_name, item in cpu_items: + cpu_stage_data = OrderedDict() + cpu_stage_data['name'] = op_name + cpu_stage_data['calls'] = item.call + cpu_stage_data['total_time'] = format_time(item.cpu_time, + time_unit) + cpu_stage_data['avg_time'] = format_time(item.avg_cpu_time, + time_unit) + cpu_stage_data['max_time'] = format_time(item.max_cpu_time, + time_unit) + cpu_stage_data['min_time'] = format_time(item.min_cpu_time, + time_unit) + cpu_stage_data['ratio'] = format_ratio( + item.cpu_time / total_cpu_time) + data['cpu'].append(cpu_stage_data) + if self.has_gpu: + for op_name, item in gpu_items: + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = op_name + gpu_stage_data['calls'] = item.call + gpu_stage_data['total_time'] = format_time( + item.general_gpu_time, time_unit) + gpu_stage_data['avg_time'] = format_time( + item.avg_general_gpu_time, time_unit) + gpu_stage_data['max_time'] = format_time( + item.max_general_gpu_time, time_unit) + gpu_stage_data['min_time'] = format_time( + item.min_general_gpu_time, time_unit) + gpu_stage_data['ratio'] = format_ratio( + item.general_gpu_time / total_gpu_time) + data['gpu'].append(gpu_stage_data) + return data + + def get_operator_pie_expand( # noqa: C901 + self, topk, device_type, time_unit): + if not self.operator_parser: + return + data = OrderedDict() + data['order'] = [] + data['phase_type'] = [] + data['data'] = [] + if device_type == 'cpu': + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + + else: + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + if topk <= 0 or topk >= 20: + items = sorted_items[:20] + other_items = sorted_items[20:] + else: + items = sorted_items[:topk] + other_items = [] + data['order'].extend( + ['infer_shape', 'compute', 'node_creation', 'others']) + inner_op_data = defaultdict(list) + for op_name, event in items: + data['phase_type'].append(op_name) + innerop_knownsub_times = 0 + have_innerop_name = set() + for innerop_name, item in event.operator_inners.items(): + if 'infer_shape' in innerop_name or 'infer_meta' in innerop_name: + innerop_name = 'infer_shape' + elif 'compute' in innerop_name: + innerop_name = 'compute' + elif 'node_creation' in innerop_name: + innerop_name = 'node_creation' + else: + continue + have_innerop_name.add(innerop_name) + if device_type == 'cpu': + inner_op_data[innerop_name].append( + format_time(item.cpu_time, time_unit)) + innerop_knownsub_times += item.cpu_time + else: + inner_op_data[innerop_name].append( + format_time(item.general_gpu_time, time_unit)) + innerop_knownsub_times += item.general_gpu_time + if device_type == 'cpu': + inner_op_data['others'].append( + format_time(event.cpu_time - innerop_knownsub_times, + time_unit)) + else: + inner_op_data['others'].append( + format_time( + event.general_gpu_time - innerop_knownsub_times, + time_unit)) + have_innerop_name.add('others') + for innerop_name in data['order']: + if innerop_name in have_innerop_name: + continue + else: + inner_op_data[innerop_name].append(0) + if other_items: + innerop_knownsub_times = 0 + total_event_times = 0 + data['phase_type'].append('others') + others_time = defaultdict(float) + for op_name, event in other_items: + for innerop_name, item in event.operator_inners.items(): + if 'infer_shape' in innerop_name: + innerop_name = 'infer_shape' + elif 'compute' in innerop_name: + innerop_name = 'compute' + elif 'node_creation' in innerop_name: + innerop_name = 'node_creation' + else: + continue + if device_type == 'cpu': + others_time[innerop_name] += item.cpu_time + innerop_knownsub_times += item.cpu_time + else: + others_time[innerop_name] += item.general_gpu_time + innerop_knownsub_times += item.general_gpu_time + if device_type == 'cpu': + total_event_times += event.cpu_time + else: + total_event_times += event.general_gpu_time + others_time['others'] = total_event_times - innerop_knownsub_times + for innerop_name in data['order']: + if innerop_name not in others_time: + others_time[innerop_name] = 0.0 + inner_op_data[innerop_name].append( + format_time(others_time[innerop_name], time_unit)) + + for innerop_name in data['order']: + data['data'].append(inner_op_data[innerop_name]) + return data + + def get_operator_table( # noqa: C901 Todo: Optimize code + self, + group_by='op_name', + search_name=None, + time_unit='ms'): + if not self.operator_parser: + return + + def get_children_data(event): + datas = [] + for innerop_name, item in event.operator_inners.items(): + + if item.cpu_time == 0: + cpu_ratio = 0 + else: + cpu_ratio = float(item.cpu_time) / event.cpu_time + if item.general_gpu_time == 0: + gpu_ratio = 0 + else: + gpu_ratio = float( + item.general_gpu_time) / event.general_gpu_time + data = { + "name": + innerop_name, + "calls": + item.call, + "cpu_total_time": + format_time(item.cpu_time, time_unit), + "cpu_avg_time": + format_time(item.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(item.max_cpu_time, time_unit), + "cpu_min_time": + format_time(item.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(cpu_ratio), + "gpu_total_time": + format_time(item.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(item.avg_general_gpu_time, time_unit), + "gpu_max_time": + format_time(item.max_general_gpu_time, time_unit), + "gpu_min_time": + format_time(item.min_general_gpu_time, time_unit), + "gpu_ratio": + format_ratio(gpu_ratio) + } + datas.append(data) + return datas + + data = OrderedDict() + data['events'] = [] + total_cpu_time = 0 + total_gpu_time = 0 + for name, event in self.operator_items.items(): + total_cpu_time += event.cpu_time + total_gpu_time += event.general_gpu_time + if not search_name: + if group_by == 'op_name': + if self.has_gpu: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio', + 'gpu_total_time', 'gpu_avg_time', 'gpu_max_time', + 'gpu_min_time', 'gpu_ratio' + ] + data['has_gpu'] = True + else: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio' + ] + data['has_gpu'] = False + if self.has_gpu: + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + else: + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + for name, event in sorted_items: + if self.has_gpu: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + name, + "calls": + event.call, + "children": + children_events, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + name, + "calls": + event.call, + "children": + children_events, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + + else: + if self.has_gpu: + data['column_name'] = [ + 'name', 'calls', 'input_shape', 'cpu_total_time', + 'cpu_avg_time', 'cpu_max_time', 'cpu_min_time', + 'cpu_ratio', 'gpu_total_time', 'gpu_avg_time', + 'gpu_max_time', 'gpu_min_time', 'gpu_ratio' + ] + data['has_gpu'] = True + else: + data['column_name'] = [ + 'name', 'calls', 'input_shape', 'cpu_total_time', + 'cpu_avg_time', 'cpu_max_time', 'cpu_min_time', + 'cpu_ratio' + ] + data['has_gpu'] = False + new_arrange_data = {} + for op_name, items_with_input_shape in self.operator_items_with_input_shape.items( + ): + for input_shape, item in items_with_input_shape.items(): + new_arrange_data[(op_name, input_shape)] = item + if self.has_gpu: + sorted_items = sorted( + new_arrange_data.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + else: + sorted_items = sorted( + new_arrange_data.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + for (name, input_shape), event in sorted_items: + if not input_shape: + shape_string = [] + else: + shapes = input_shape.split('\t')[:-1] + shape_string = [ + '{}:{}'.format(*shape.split('-')) + for shape in shapes + ] + if self.has_gpu: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + name, + "calls": + event.call, + "children": + children_events, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + name, + "calls": + event.call, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + name, + "calls": + event.call, + "children": + children_events, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + name, + "calls": + event.call, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + + else: + if self.has_gpu: + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].general_gpu_time, + reverse=True) + else: + sorted_items = sorted( + self.operator_items.items(), + key=lambda x: x[1].cpu_time, + reverse=True) + + results = [] + for op_name, item in sorted_items: + if search_name in op_name: + results.append(op_name) + + if group_by == 'op_name': + if self.has_gpu: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio', + 'gpu_total_time', 'gpu_avg_time', 'gpu_max_time', + 'gpu_min_time', 'gpu_ratio' + ] + data['has_gpu'] = True + else: + data['column_name'] = [ + 'name', 'calls', 'cpu_total_time', 'cpu_avg_time', + 'cpu_max_time', 'cpu_min_time', 'cpu_ratio' + ] + data['has_gpu'] = False + for op_name in results: + event = self.operator_items[op_name] + if self.has_gpu: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "children": + children_events, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time + if total_gpu_time != 0 else 0.0) + }) + + else: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "children": + children_events, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / total_cpu_time + if total_cpu_time != 0 else 0.0) + }) + + else: + if self.has_gpu: + data['column_name'] = [ + 'name', 'calls', 'input_shape', 'cpu_total_time', + 'cpu_avg_time', 'cpu_max_time', 'cpu_min_time', + 'cpu_ratio', 'gpu_total_time', 'gpu_avg_time', + 'gpu_max_time', 'gpu_min_time', 'gpu_ratio' + ] + data['has_gpu'] = True + else: + data['column_name'] = [ + 'name', 'calls', 'input_shape', 'cpu_total_time', + 'cpu_avg_time', 'cpu_max_time', 'cpu_min_time', + 'cpu_ratio' + ] + data['has_gpu'] = False + for op_name in results: + for input_shape, event in self.operator_items_with_input_shape[ + op_name].items(): + if not input_shape: + shape_string = [] + else: + shapes = input_shape.split('\t')[:-1] + shape_string = [ + '{}:{}'.format(*shape.split('-')) + for shape in shapes + ] + if self.has_gpu: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "children": + children_events, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / + total_cpu_time if + total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, + time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time if + total_gpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / + total_cpu_time if + total_cpu_time != 0 else 0.0), + "gpu_total_time": + format_time(event.general_gpu_time, + time_unit), + "gpu_avg_time": + format_time(event.avg_general_gpu_time, + time_unit), + "gpu_max_time": + format_time(event.max_general_gpu_time, + time_unit), + "gpu_min_time": + format_time(event.min_general_gpu_time, + time_unit), + "gpu_ratio": + format_ratio(event.general_gpu_time / + total_gpu_time if + total_gpu_time != 0 else 0.0) + }) + else: + children_events = get_children_data(event) + if children_events: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "children": + get_children_data(event), + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / + total_cpu_time if + total_cpu_time != 0 else 0.0) + }) + else: + data['events'].append({ + "name": + op_name, + "calls": + event.call, + "input_shape": + shape_string, + "cpu_total_time": + format_time(event.cpu_time, time_unit), + "cpu_avg_time": + format_time(event.avg_cpu_time, time_unit), + "cpu_max_time": + format_time(event.max_cpu_time, time_unit), + "cpu_min_time": + format_time(event.min_cpu_time, time_unit), + "cpu_ratio": + format_ratio(event.cpu_time / + total_cpu_time if + total_cpu_time != 0 else 0.0) + }) + return data + + def get_kernel_pie(self, topk, time_unit='ms'): + if not self.kernel_parser: + return + data = OrderedDict() + data['column_name'] = [ + "name", "calls", "total_time", "avg_time", "max_time", "min_time", + "mean blocks per sm", "mean est achieved occupancy", + "tensor core used", "ratio" + ] + + data['events'] = [] + + sorted_items = sorted( + self.kernel_items.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + + if topk <= 0: + items = sorted_items + else: + items = sorted_items[:topk] + + total_gpu_time = 0.0 + for kernel_name, item in items: + total_gpu_time += item.gpu_time + + for kernel_name, item in items: + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = kernel_name + gpu_stage_data['calls'] = item.call + gpu_stage_data['total_time'] = format_time(item.gpu_time, + time_unit) + gpu_stage_data['avg_time'] = format_time(item.avg_gpu_time, + time_unit) + gpu_stage_data['max_time'] = format_time(item.max_gpu_time, + time_unit) + gpu_stage_data['min_time'] = format_time(item.min_gpu_time, + time_unit) + gpu_stage_data['mean blocks per sm'] = format_float( + item.sum_blocks_per_sm / item.call) + gpu_stage_data['mean est achieved occupancy'] = format_float( + item.sum_occupancy / item.call) + gpu_stage_data['tensor core used'] = item.tensorcore_used + gpu_stage_data['ratio'] = format_ratio( + item.gpu_time / total_gpu_time) + data['events'].append(gpu_stage_data) + return data + + def get_kernel_table(self, group_by='', search_name=None, time_unit='ms'): + if not self.kernel_parser: + return + data = OrderedDict() + data['events'] = [] + total_gpu_time = 0 + for name, event in self.kernel_items.items(): + total_gpu_time += event.gpu_time + if not search_name: + if group_by == 'kernel_name': + data['column_name'] = [ + "name", "calls", "total_time", "avg_time", "max_time", + "min_time", "mean blocks per sm", + "mean est achieved occupancy", "tensor core used", "ratio" + ] + sorted_items = sorted( + self.kernel_items.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + for name, item in sorted_items: + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = name + gpu_stage_data['calls'] = item.call + gpu_stage_data['total_time'] = format_time( + item.gpu_time, time_unit) + gpu_stage_data['avg_time'] = format_time( + item.avg_gpu_time, time_unit) + gpu_stage_data['max_time'] = format_time( + item.max_gpu_time, time_unit) + gpu_stage_data['min_time'] = format_time( + item.min_gpu_time, time_unit) + gpu_stage_data['mean blocks per sm'] = format_float( + item.sum_blocks_per_sm / item.call) + gpu_stage_data[ + 'mean est achieved occupancy'] = format_float( + item.sum_occupancy / item.call) + gpu_stage_data['tensor core used'] = item.tensorcore_used + gpu_stage_data['ratio'] = format_ratio( + item.gpu_time / total_gpu_time) + data['events'].append(gpu_stage_data) + else: + data['column_name'] = [ + "name", "calls", "operator", "grid", "block", + "register per thread", "shared memory", "total_time", + "avg_time", "max_time", "min_time", "mean blocks per sm", + "mean est achieved occupancy", "tensor core used", "ratio" + ] + new_arrange_data = {} + for name, items_with_attributes in self.kernel_items_with_op_name_attributes.items( + ): + for attributes, item in items_with_attributes.items(): + new_arrange_data[(name, attributes)] = item + sorted_items = sorted( + new_arrange_data.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + for (name, attributes), item in sorted_items: + operator, grid, block, register_per_thread, shared_memory = attributes.split( + '-') + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = name + gpu_stage_data['calls'] = item.call + gpu_stage_data['operator'] = operator + gpu_stage_data['grid'] = grid + gpu_stage_data['block'] = block + gpu_stage_data['register per thread'] = register_per_thread + gpu_stage_data['shared memory'] = shared_memory + gpu_stage_data['total_time'] = format_time( + item.gpu_time, time_unit) + gpu_stage_data['avg_time'] = format_time( + item.avg_gpu_time, time_unit) + gpu_stage_data['max_time'] = format_time( + item.max_gpu_time, time_unit) + gpu_stage_data['min_time'] = format_time( + item.min_gpu_time, time_unit) + gpu_stage_data['mean blocks per sm'] = format_float( + item.sum_blocks_per_sm / item.call) + gpu_stage_data[ + 'mean est achieved occupancy'] = format_float( + item.sum_occupancy / item.call) + gpu_stage_data['tensor core used'] = item.tensorcore_used + gpu_stage_data['ratio'] = format_ratio( + item.gpu_time / total_gpu_time) + data['events'].append(gpu_stage_data) + + else: + sorted_items = sorted( + self.kernel_items.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + results = [] + for kernel_name, item in sorted_items: + if search_name in kernel_name: + results.append(kernel_name) + + if group_by == 'kernel_name': + data['column_name'] = [ + "name", "calls", "total_time", "avg_time", "max_time", + "min_time", "mean blocks per sm", + "mean est achieved occupancy", "tensor core used", "ratio" + ] + for kernel_name in results: + item = self.kernel_items[kernel_name] + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = kernel_name + gpu_stage_data['calls'] = item.call + gpu_stage_data['total_time'] = format_time( + item.gpu_time, time_unit) + gpu_stage_data['avg_time'] = format_time( + item.avg_gpu_time, time_unit) + gpu_stage_data['max_time'] = format_time( + item.max_gpu_time, time_unit) + gpu_stage_data['min_time'] = format_time( + item.min_gpu_time, time_unit) + gpu_stage_data['mean blocks per sm'] = format_float( + item.sum_blocks_per_sm / item.call) + gpu_stage_data[ + 'mean est achieved occupancy'] = format_float( + item.sum_occupancy / item.call) + gpu_stage_data['tensor core used'] = item.tensorcore_used + gpu_stage_data['ratio'] = format_ratio( + item.gpu_time / total_gpu_time) + data['events'].append(gpu_stage_data) + else: + for kernel_name in results: + for items_with_attributes, item in self.kernel_items_with_op_name_attributes[ + kernel_name].items(): + operator, grid, block, register_per_thread, shared_memory = attributes.split( + '-') + gpu_stage_data = OrderedDict() + gpu_stage_data['name'] = kernel_name + gpu_stage_data['calls'] = item.call + gpu_stage_data['operator'] = operator + gpu_stage_data['grid'] = grid + gpu_stage_data['block'] = block + gpu_stage_data[ + 'register per thread'] = register_per_thread + gpu_stage_data['shared memory'] = shared_memory + gpu_stage_data['total_time'] = format_time( + item.gpu_time, time_unit) + gpu_stage_data['avg_time'] = format_time( + item.avg_gpu_time, time_unit) + gpu_stage_data['max_time'] = format_time( + item.max_gpu_time, time_unit) + gpu_stage_data['min_time'] = format_time( + item.min_gpu_time, time_unit) + gpu_stage_data['mean blocks per sm'] = format_float( + item.sum_blocks_per_sm / item.call) + gpu_stage_data[ + 'mean est achieved occupancy'] = format_float( + item.sum_occupancy / item.call) + gpu_stage_data[ + 'tensor core used'] = item.tensorcore_used + gpu_stage_data['ratio'] = format_ratio( + item.gpu_time / total_gpu_time) + data['events'].append(gpu_stage_data) + return data + + def get_kernel_tc_pie(self, topk, time_unit='ms'): + if not self.kernel_parser: + return + data = OrderedDict() + data['column_name'] = ["name", "calls", "ratio"] + + data['events'] = [] + + sorted_items = sorted( + self.kernel_items.items(), + key=lambda x: x[1].gpu_time, + reverse=True) + + if topk <= 0: + items = sorted_items + else: + items = sorted_items[:topk] + + total_calls = 0.0 + tensorcore_calls = 0.0 + for kernel_name, item in items: + if item.tensorcore_used: + tensorcore_calls += item.call + total_calls += item.call + + data['events'].append({ + "name": + "Tensor core used", + "calls": + tensorcore_calls, + "ratio": + format_ratio(tensorcore_calls / total_calls) + }) + data['events'].append({ + "name": + "Tensor core unused", + "calls": + total_calls - tensorcore_calls, + "ratio": + format_ratio((total_calls - tensorcore_calls) / total_calls) + }) + return data + + def get_trace_data(self): + if not self.trace_parser: + return + return self.trace_parser.content + + def get_memory_devices(self): + if not self.memory_parser: + return + data = [] + for device in self.memory_curve.keys(): + data.append({ + "device": + device, + "min_size": + format_memory(self.size_ranges[device][0], 'KB'), + "max_size": + format_memory(self.size_ranges[device][1], 'KB'), + "max_allocation_size": + format_memory(self.peak_allocation_values[device], 'KB'), + }) + return data + + def get_memory_curve(self, device_type, time_unit='ms'): + if not self.memory_parser: + return + curves = self.memory_curve[device_type] + data = {} + data['name'] = { + 'Allocated': '已分配', + 'Reserved': '已预留', + 'PeakAllocated': '最大已分配', + 'PeakReserved': '最大已预留' + } + for key, events in curves.items(): + data[key] = [] + sorted_events = sorted(events, key=lambda x: x[0]) + for item in sorted_events: + timestamp = item[0] + size = item[1] + event_name = item[2] + data[key].append([ + format_time(timestamp, time_unit), + format_memory(size, 'KB'), event_name + ]) + return data + + def get_memory_events(self, + device_type, + min_size=0, + max_size=float('inf'), + search_name=None, + time_unit='ms'): + if not self.memory_parser: + return + data = {} + data['column_name'] = [ + 'MemoryAddr', 'MemoryType', 'AllocatedEvent', 'AllocatedTimestamp', + 'FreeEvent', 'FreeTimestamp', 'Duration', 'Size' + ] + data['data'] = [] + paired_event_list = self.paired_events[device_type] + + def filter_func(item): + nonlocal min_size + nonlocal max_size + nonlocal search_name + size = format_memory(item[-1], 'KB') + if not search_name: + if size >= min_size and size <= max_size: + return True + else: + if size >= min_size and size <= max_size: + if item[2]: + if search_name in item[2]: + return True + if item[4]: + if search_name in item[4]: + return True + return False + + paired_event_list = filter(filter_func, paired_event_list) + paired_event_list = sorted(paired_event_list, key=lambda x: x[-1]) + if not paired_event_list: + return data + duration = None + for item in paired_event_list: + if item[3] and item[5]: + duration = item[5] - item[3] + else: + duration = None + data['data'].append({ + "MemoryAddr": + item[0], + "MemoryType": + item[1], + "AllocatedEvent": + item[2], + "AllocatedTimestamp": + format_time(item[3], time_unit) if item[3] else None, + "FreeEvent": + item[4], + "FreeTimestamp": + format_time(item[5], time_unit) if item[5] else None, + "Duration": + format_time(duration, time_unit) + if duration is not None else None, + "Size": + format_memory(item[6], 'KB') + }) + return data + + def get_op_memory_events(self, device_type, search_name=None): + if not self.memory_parser: + return + data = {} + data['column_name'] = [ + 'EventName', 'MemoryType', 'AllocationCount', 'FreeCount', + 'AllocationSize', 'FreeSize', 'IncreasedSize' + ] + data['data'] = [] + allocated_events = self.allocated_items[device_type] + + def filter_func(item): + nonlocal search_name + if not search_name: + return True + else: + if search_name in item[0]: + return True + return False + + reserved_events = self.reserved_items[device_type] + all_events = [(key, item) for key, item in allocated_events.items()] + all_events.extend( + [(key, item) for key, item in reserved_events.items()]) + if search_name: + all_events = filter(filter_func, all_events) + sorted_items = sorted( + all_events, key=lambda x: x[1].increase_size, reverse=True) + if not sorted_items: + return data + for event_name, item in sorted_items: + data['data'].append({ + 'EventName': + event_name, + 'MemoryType': + item.memory_type, + 'AllocationCount': + item.allocation_count, + 'FreeCount': + item.free_count, + 'AllocationSize': + format_memory(item.allocation_size, 'KB'), + 'FreeSize': + format_memory(item.free_size, 'KB'), + 'IncreasedSize': + format_memory(item.increase_size, 'KB') + }) + return data + + +class DistributedProfilerData: + ''' + Hold data for distributed view. + Aggregate all data for distributed in ProfileData object. + ''' + + def __init__(self, run, span, profile_datas): + self.run = run + self.span = span + self.profile_datas = profile_datas + + def get_distributed_info(self): + data = [] + for profile_data in self.profile_datas: + device_infos = profile_data.device_infos + if not device_infos: + return data + if not profile_data.has_gpu: + continue + gpu_id = int(next(iter(profile_data.gpu_ids))) + data.append({ + 'worker_name': + profile_data.worker_name, + 'process_id': + 'pid: {}'.format(profile_data.process_id), + 'device_id': + 'GPU{}'.format(gpu_id), + 'name': + device_infos[gpu_id]['name'], + 'memory': + "{} GB".format( + format_memory(device_infos[gpu_id]['totalGlobalMem'], + 'GB')), + 'computeCapability': + '{}.{}'.format(device_infos[gpu_id]['computeMajor'], + device_infos[gpu_id]['computeMinor']), + 'utilization': + '{}%'.format(format_ratio(profile_data.gpu_ulitization)) + }) + return data + + def get_distributed_histogram(self, step, time_unit='ms'): + data = {} + data['order'] = [ + "ProfileStep", "Communication", "Computation", "Overlap", "Others" + ] + data['worker_name'] = [] + data['data'] = [] + new_data = defaultdict(list) + for profile_data in self.profile_datas: + if not profile_data.distributed_parser: + continue + data['worker_name'].append(profile_data.worker_name) + if step != 'All': + new_data['ProfileStep'].append( + format_time( + profile_data.model_perspective_items['ProfileStep']. + cpu_times[step], time_unit)) + else: + new_data['ProfileStep'].append( + format_time( + profile_data.model_perspective_items['ProfileStep']. + cpu_time, time_unit)) + new_data['Communication'].append( + format_time( + profile_data.distributed_time[step]['communication_time'], + time_unit)) + new_data['Computation'].append( + format_time( + profile_data.distributed_time[step]['computation_time'], + time_unit)) + new_data['Overlap'].append( + format_time( + profile_data.distributed_time[step]['overlap_time'], + time_unit)) + new_data['Others'].append( + format_time(profile_data.distributed_time[step]['others_time'], + time_unit)) + for order in data['order']: + data['data'].append(new_data[order]) + return data + + def get_distributed_steps(self): + for profile_data in self.profile_datas: + if not profile_data.distributed_parser: + continue + steps = list(profile_data.distributed_time.keys()) + final_steps = ['All'] + sorted( + [int(step) for step in steps if step != 'All']) + return final_steps diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_reader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..7b97a12906db3d4c0840bc98eccb9ab42336f1ef --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_reader.py @@ -0,0 +1,246 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import os +import re +from multiprocessing import Process +from multiprocessing import Queue +from threading import Lock +from threading import Thread + +import packaging.version + +from .parser.const_description import * # noqa: F403 +from .parser.event_node import load_profiler_json +from .parser.event_node import ProfilerResult +from .parser.utils import RedirectStdStreams +from .run_manager import RunManager +from visualdl.io import bfile + +_name_pattern = re.compile(r"(.+)_time_(.+)\.paddle_trace\.((pb)|(json))") +_lock = Lock() + + +def is_VDLProfiler_file(path): + """Determine whether it is a paddle profile file that can be read by vdl according to the file name. + + File name of a paddle profile file must contain `paddle_trace`. + + Args: + path: File name to determine. + Returns: + True if the file is a paddle profile file, otherwise false. + """ + if "paddle_trace" not in path: + return False + return True + + +class ProfilerReader(object): + """Profile reader to read paddle profile files, support for frontend api in lib.py. + """ + + def __init__(self, logdir=''): + """Instance of ProfileReader + + Args: + logdir: The dir include paddle profile files, multiple subfolders allowed. + """ + if isinstance(logdir, str): + self.dir = [logdir] + else: + self.dir = logdir + + self.walks = {} + self.displayname2runs = {} + self.runs2displayname = {} + self.run_managers = {} + self.profile_result_queue = Queue() + self.tempfile = None + if logdir: + self.runs() + Thread(target=self._get_data_from_queue, args=()).start() + + @property + def logdir(self): + return self.dir + + def get_all_walk(self): + flush_walks = {} + for dir in self.dir: + for root, dirs, files in bfile.walk(dir): + flush_walks.update({root: files}) + return flush_walks + + def get_run_manager(self, run): + if run in self.run_managers: + self.run_managers[run].join() + return self.run_managers[run] + else: + return None + + def component_tabs(self, update=False): + """Get component tabs used by vdl frontend. + """ + component_tabs = set() + if not self.logdir: + return component_tabs + if update is True: + self.runs(update=update) + if self.walks: + component_tabs.add('profiler') + return component_tabs + + def profile_runs(self, update=False): + """Get profile run files. + + Every dir(means `run` in vdl) has may have more than one profiler file. + + Returns: + walks: A dict like {"exp1": ["1587375595_paddle_trace.json", "1587375685_paddle_trace.json"], + "exp2": ["1587375686_paddle_trace.json"]} + """ + if not self.walks or update is True: + flush_walks = self.get_all_walk() + + walks_temp = {} + for run, filenames in flush_walks.items(): + tags_temp = [ + filename for filename in filenames + if is_VDLProfiler_file(filename) + ] + if len(tags_temp) > 0: + walks_temp.update({run: tags_temp}) + self.walks = walks_temp + return self.walks + + def runs(self, update=True): + self.profile_runs(update=update) + for run, filenames in self.walks.items(): + if run not in self.run_managers: + self.run_managers[run] = RunManager(run) + self.run_managers[run].set_all_filenames(filenames) + for filename in filenames: + with _lock: # we add this to prevent parallel requests for handling a file multiple times + if self.run_managers[run].has_handled(filename): + continue + self.run_managers[run].handled_filenames.add(filename) + self._read_data(run, filename) + return list(self.walks.keys()) + + def get_descriptions(self, lang): + if lang == 'zh': + return { + "overview_environment": TOOLTIP_DEVICE_INFO_CN, # noqa: F405 + "overview_model_perspective": + TOOLTIP_MODEL_PERSPECTIVE_CN, # noqa: F405 + "overview_model_perspective_perstep": + TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_CN, # noqa: F405 + "overview_event_type_perspective": + TOOLTIP_EVENT_TYPE_PERSPECTIVE_CN, # noqa: F405 + "overview_event_type_model_perspective": + TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_CN, # noqa: F405 + "distributed_histogram": + TOOLTIP_EVENT_DISTRIBUTED_HISTOGRAM_CN # noqa: F405 + } + else: + return { + "overview_environment": TOOLTIP_DEVICE_INFO_EN, # noqa: F405 + "overview_model_perspective": + TOOLTIP_MODEL_PERSPECTIVE_EN, # noqa: F405 + "overview_model_perspective_perstep": + TOOLTIP_MODEL_PERSPECTIVE_PERSTEP_EN, # noqa: F405 + "overview_event_type_perspective": + TOOLTIP_EVENT_TYPE_PERSPECTIVE_EN, # noqa: F405 + "overview_event_type_model_perspective": + TOOLTIP_EVENT_TYPE_MODEL_PERSPECTIVE_EN, # noqa: F405 + "distributed_histogram": + TOOLTIP_EVENT_DISTRIBUTED_HISTOGRAM_EN # noqa: F405 + } + + def set_displayname(self, log_reader): + self.displayname2runs = log_reader.name2tags + self.runs2displayname = log_reader.tags2name + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + def _get_data_from_queue(self): + while True: + try: + run, filename, worker_name, profile_result = self.profile_result_queue.get( + ) + self.run_managers[run].add_profile_result( + filename, worker_name, profile_result) + except Exception as e: + print('Read profiler data error in multiprocess, error: {}'. + format(e)) + + def _read_data(self, run, filename): + match = _name_pattern.match(filename) + if match: + worker_name = match.group(1) + if '.pb' in filename: + + def _load_profiler_protobuf(run, filename, worker_name): + devnull = open(os.devnull, 'w+') + with RedirectStdStreams(stdout=devnull, stderr=devnull): + try: + import paddle + except Exception as e: + print('Paddle is required to read protobuf file. "\ + "Please install [paddlepaddle](https://www.paddlepaddle.org.cn/install/quick?"\ + "docurl=/documentation/docs/zh/develop/install/pip/linux-pip.html) first.' + ) + raise RuntimeError(str(e)) + if packaging.version.parse( + '2.4.0') > packaging.version.parse( + paddle.__version__): + raise RuntimeError( + "Please make sure paddlepaddle version >= 2.4.0" + ) + from paddle.profiler import load_profiler_result + try: + + content = load_profiler_result( + os.path.join(run, filename)) + if content is None: + raise RuntimeError("Missing required fields.") + profile_result = ProfilerResult(content) + except Exception as e: + raise RuntimeError( + "An error occurred while loading the protobuf file, which may be caused " + "by the outdated version of paddle that generated the profile file. " + "Please make sure protobuf file is exported by paddlepaddle version >= 2.4.0. " + "Error message: {}".format(e)) + self.profile_result_queue.put( + (run, filename, worker_name, profile_result)) + + Process( + target=_load_profiler_protobuf, + args=(run, filename, worker_name)).start() + else: + + def _load_profiler_json(run, filename, worker_name): + profile_result = load_profiler_json( + os.path.join(run, filename)) + self.profile_result_queue.put((run, filename, worker_name, + profile_result)) + + Process( + target=_load_profiler_json, + args=(run, filename, worker_name)).start() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_server.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4b9efdf2b50fd547bd8c572cd57f34bf395dc3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/profiler_server.py @@ -0,0 +1,473 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json + +from .profiler_reader import ProfilerReader +from visualdl.server.api import gen_result +from visualdl.server.api import result + + +class ProfilerApi(object): + def __init__(self, logdir): + self._reader = ProfilerReader(logdir) + + @result() + def runs(self): + return self._reader.runs() + + @result() + def views(self, run): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + return list(run_manager.get_views()) + + @result() + def workers(self, run, view): + if view == 'Distributed': + return ['All'] + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + return run_manager.get_workers(view) + + @result() + def spans(self, run, worker): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + if worker == 'All': + return run_manager.get_distributed_spans() + return run_manager.get_spans(worker) + + @result() + def timeunits(self): + return ['ns', 'us', 'ms', 's'] + + @result() + def descriptions(self, lang): + if lang == 'undefined' or lang is None: + lang = 'zh' + lang = lang.lower() + return self._reader.get_descriptions(lang) + + def component_tabs(self): + ''' + Get all component tabs supported by readers in Api. + ''' + tabs = set() + tabs.update(self._reader.component_tabs(update=True)) + return tabs + + @result() + def overview_environment(self, run, worker, span): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + span = str(span) + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + result = profiler_data.get_device_infos() + num_workers = len(run_manager.get_workers('Overview')) + result['num_workers'] = num_workers + return result + + @result() + def model_perspective(self, run, worker, span, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_model_perspective(time_unit) + + @result() + def model_perspective_perstep(self, + run, + worker, + span, + device_type, + time_unit='ms'): + device_type = device_type.lower() + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_model_perspective_perstep( + device_type, time_unit) + + @result() + def event_type_perspective(self, + run, + worker, + span, + device_type, + time_unit='ms'): + device_type = device_type.lower() + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_event_type_perspective( + device_type, time_unit) + + @result() + def event_type_model_perspective(self, run, worker, span, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_event_type_model_perspective(time_unit) + + @result() + def userdefined_perspective(self, run, worker, span, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_userdefined_perspective(time_unit) + + @result() + def operator_pie(self, run, worker, span, topk, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + topk = int(topk) + if profiler_data: + return profiler_data.get_operator_pie(topk, time_unit) + + @result() + def operator_pie_expand(self, run, worker, span, topk, device_type, + time_unit): + device_type = device_type.lower() + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + + topk = int(topk) + if profiler_data: + return profiler_data.get_operator_pie_expand( + topk, device_type, time_unit) + + @result() + def operator_table(self, + run, + worker, + span, + group_by, + search_name, + time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_operator_table(group_by, search_name, + time_unit) + + @result() + def operator_stack_table(self, + run, + worker, + span, + op_name, + group_by, + input_shape, + time_unit='ms'): + pass + + @result() + def kernel_pie(self, run, worker, span, topk, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + topk = int(topk) + if profiler_data: + return profiler_data.get_kernel_pie(topk, time_unit) + + @result() + def kernel_table(self, + run, + worker, + span, + group_by, + search_name, + time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_kernel_table(group_by, search_name, + time_unit) + + @result() + def kernel_tc_pie(self, run, worker, span, topk, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + topk = int(topk) + return profiler_data.get_kernel_tc_pie(topk, time_unit) + + @result() + def distributed_info(self, run, worker, span): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + distributed_profiler_data = run_manager.get_distributed_profiler_data( + span) + if distributed_profiler_data is None: + return + return distributed_profiler_data.get_distributed_info() + + @result() + def distributed_steps(self, run, worker, span): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + distributed_profiler_data = run_manager.get_distributed_profiler_data( + span) + if distributed_profiler_data is None: + return + return distributed_profiler_data.get_distributed_steps() + + @result() + def distributed_histogram(self, run, worker, span, step, time_unit='ms'): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + distributed_profiler_data = run_manager.get_distributed_profiler_data( + span) + if distributed_profiler_data is None: + return + return distributed_profiler_data.get_distributed_histogram( + step, time_unit) + + @result(headers={'content-encoding': 'gzip'}) + def trace(self, run, worker, span): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_trace_data() + + @result() + def memory_devices(self, run, worker, span): + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_memory_devices() + + @result(headers={'content-encoding': 'gzip'}) + def memory_curve(self, run, worker, span, device_type, time_unit='ms'): + if device_type == 'undefined': + return + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_memory_curve(device_type, time_unit) + + @result(headers={'content-encoding': 'gzip'}) + def memory_events(self, + run, + worker, + span, + device_type, + min_size=0, + max_size=float('inf'), + search_name=None, + time_unit='ms'): + if device_type == 'undefined': + return + try: + min_size = float(min_size) + except Exception: + min_size = 0 + try: + max_size = float(max_size) + except Exception: + max_size = float('inf') + if search_name == 'undefined' or not search_name: + search_name = None + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_memory_events( + device_type, min_size, max_size, search_name, time_unit) + + @result(headers={'content-encoding': 'gzip'}) + def op_memory_events(self, + run, + worker, + span, + device_type, + search_name=None): + if search_name == 'undefined' or not search_name: + search_name = None + if device_type == 'undefined': + return + run_manager = self._reader.get_run_manager(run) + if run_manager is None: + return [] + profiler_data = run_manager.get_profiler_data(worker, span) + if profiler_data: + return profiler_data.get_op_memory_events(device_type, search_name) + + @result() + def comparison_phase(self, base_run, base_worker, base_span, exp_run, + exp_worker, exp_span): + pass + + @result() + def comparison_phase_diff(self, base_run, base_worker, base_span, exp_run, + exp_worker, exp_span): + pass + + @result() + def comparison_phase_table(self, base_run, base_worker, base_span, exp_run, + exp_worker, exp_span): + pass + + @result() + def comparison_phase_inner(self, base_run, base_worker, base_span, exp_run, + exp_worker, exp_span, phase_name): + pass + + @result() + def comparison_phase_diff_inner(self, base_run, base_worker, base_span, + exp_run, exp_worker, exp_span, phase_name): + pass + + @result() + def comparison_phase_table_inner(self, base_run, base_worker, base_span, + exp_run, exp_worker, exp_span, + phase_name): + pass + + +def create_profiler_api_call(logdir): + api = ProfilerApi(logdir) + routes = { + 'runs': (api.runs, []), + 'views': (api.views, ["run"]), + 'workers': (api.workers, ["run", "view"]), + 'spans': (api.spans, ["run", "worker"]), + 'timeunits': (api.timeunits, []), + 'descriptions': (api.descriptions, ["lang"]), + 'overview/environment': (api.overview_environment, + ["run", "worker", "span"]), + 'overview/model_perspective': (api.model_perspective, + ["run", "worker", "span", "time_unit"]), + 'overview/model_perspective_perstep': (api.model_perspective_perstep, [ + "run", "worker", "span", "device_type", "time_unit" + ]), + 'overview/event_type_perspective': (api.event_type_perspective, [ + "run", "worker", "span", "device_type", "time_unit" + ]), + 'overview/event_type_model_perspective': + (api.event_type_model_perspective, + ["run", "worker", "span", "time_unit"]), + 'overview/userdefined_perspective': + (api.userdefined_perspective, ["run", "worker", "span", "time_unit"]), + 'operator/pie': (api.operator_pie, + ["run", "worker", "span", "topk", "time_unit"]), + 'operator/pie_expand': (api.operator_pie_expand, [ + "run", "worker", "span", "topk", "device_type", "time_unit" + ]), + 'operator/table': (api.operator_table, [ + "run", "worker", "span", "group_by", "search_name", "time_unit" + ]), + 'operator/stack_table': (api.operator_stack_table, [ + "run", "worker", "span", "op_name", "group_by", "time_unit" + "input_shape" + ]), + 'kernel/pie': (api.kernel_pie, + ["run", "worker", "span", "topk", "time_unit"]), + 'kernel/tensorcore_pie': + (api.kernel_tc_pie, ["run", "worker", "span", "topk", "time_unit"]), + 'kernel/table': (api.kernel_table, [ + "run", "worker", "span", "group_by", "search_name", "time_unit" + ]), + 'distributed/info': (api.distributed_info, ["run", "worker", "span"]), + 'distributed/steps': (api.distributed_steps, ["run", "worker", + "span"]), + 'distributed/histogram': (api.distributed_histogram, [ + "run", "worker", "span", "step", "time_unit" + ]), + 'trace': (api.trace, ["run", "worker", "span"]), + 'memory/devices': (api.memory_devices, ["run", "worker", "span"]), + 'memory/curve': (api.memory_curve, + ["run", "worker", "span", "device_type", + "time_unit"]), + 'memory/memory_events': (api.memory_events, [ + "run", "worker", "span", "device_type", "min_size", "max_size", + "search_name", "time_unit" + ]), + 'memory/op_memory_events': (api.op_memory_events, [ + "run", "worker", "span", "device_type", "search_name" + ]), + 'comparison/phase': (api.comparison_phase, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span" + ]), + 'comparison/phase_diff': (api.comparison_phase_diff, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span" + ]), + 'comparison/phase_table': (api.comparison_phase_table, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span" + ]), + 'comparison/phase_inner': (api.comparison_phase_inner, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span", "phase_name" + ]), + 'comparison/phase_diff_inner': (api.comparison_phase_diff_inner, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span", "phase_name" + ]), + 'comparison/phase_table_inner': (api.comparison_phase_table_inner, [ + "base_run", "base_worker", "base_span", "exp_run", "exp_worker", + "exp_span", "phase_name" + ]), + 'component_tabs': (api.component_tabs, []) + } + + def call(path: str, args): + route = routes.get(path) + if not route: + return json.dumps(gen_result( + status=1, msg='api not found')), 'application/json', None + method, call_arg_names = route + call_args = [args.get(name) for name in call_arg_names] + return method(*call_args) + + return call diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/run_manager.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/run_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..418626abf0a212a68a7bc13e8019d9de9728037c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/component/profiler/run_manager.py @@ -0,0 +1,131 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from collections import defaultdict +from threading import Thread + +from .profiler_data import DistributedProfilerData +from .profiler_data import ProfilerData + + +class RunManager: + ''' + Manage profile data for each run, each run may have multiple workers and spans. + We should manage profile data of each (worker, span) unit. + Besides, a special worker "all" is created to merge all profile data for distributed view. + ''' + + def __init__(self, run): + self.run = run + # worker: + # span: + # ProfileData + self.profiler_data = defaultdict(dict) + self.all_filenames = set() + self.handled_filenames = set() + # span: + # DistributedProfileData + self.distributed_data = {} + self.threads = {} + self.has_join = False + + def get_profiler_data(self, worker, span): + if worker in self.profiler_data: + if span in self.profiler_data[worker]: + return self.profiler_data[worker][span] + + def get_distributed_profiler_data(self, span): + if span in self.distributed_data: + return self.distributed_data[span] + + def get_views(self): + ''' + Return all views supported in current run data. + ''' + all_views = set() + for worker, span_data in self.profiler_data.items(): + for span, profiler_data in span_data.items(): + all_views.update(profiler_data.get_views()) + ordered_views = [ + 'Overview', 'Operator', 'GPU Kernel', 'Distributed', 'Trace', + 'Memory' + ] + final_views = [] + for view in ordered_views: + if view in all_views: + final_views.append(view) + return final_views + + def get_workers(self, view_name): + ''' + Return all workers(processes) in current run data. + ''' + workers = [] + for worker, span_data in self.profiler_data.items(): + for span, profiler_data in span_data.items(): + if view_name in profiler_data.get_views(): + workers.append(worker) + break + return workers + + def get_spans(self, worker_name): + ''' + Return all spans in current run data. + spans: Collecting profile data when training your model can be divided into several parts supported by\ + paddle.profiler api, for example, you may profile steps 2-4, 6-8. Each range is called a span here. \ + And We index each span by orders. + ''' + spans = list(self.profiler_data[worker_name].keys()) + spans = sorted([int(span) for span in spans]) + spans = [str(span) for span in spans] + return spans + + def get_distributed_spans(self): + spans = list(self.distributed_data.keys()) + spans = sorted([int(span) for span in spans]) + spans = [str(span) for span in spans] + return spans + + def _parse_file(self, worker_name, result): + span = result.get_span_idx() + self.profiler_data[worker_name][span] = ProfilerData( + self.run, worker_name, span, result) + return + + def join(self): + for thread in self.threads.values(): + thread.join() + distributed_profiler_data = defaultdict(list) + for worker_name, span_data in self.profiler_data.items(): + for span_idx, profiler_data in span_data.items(): + distributed_profiler_data[span_idx].append(profiler_data) + for span_idx, profiler_datas in distributed_profiler_data.items(): + self.distributed_data[span_idx] = DistributedProfilerData( + self.run, span_idx, profiler_datas) + + def add_profile_result(self, filename, worker_name, profile_result): + thread = Thread( + target=self._parse_file, args=(worker_name, profile_result)) + thread.start() + self.handled_filenames.add(filename) + self.threads[filename] = thread + + def set_all_filenames(self, filenames): + self.all_filenames.update(filenames) + + def has_handled(self, filename): + if filename in self.handled_filenames: + return True + else: + return False diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c86d9d714fe1c9a14daae3805cd52181a999a7fe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from . import bfile # noqa: F401 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bfile.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bfile.py new file mode 100644 index 0000000000000000000000000000000000000000..9055a80cfc0f3d5b1d8073e12ed84dcf672ac291 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bfile.py @@ -0,0 +1,747 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import base64 +import hashlib +import os +import tempfile +import time + +try: + import hdfs + from hdfs.util import HdfsError + HDFS_ENABLED = True +except ImportError: + HDFS_ENABLED = False +try: + from baidubce.services.bos.bos_client import BosClient + from baidubce import exception + from baidubce.bce_client_configuration import BceClientConfiguration + from baidubce.auth.bce_credentials import BceCredentials + BOS_ENABLED = True +except ImportError: + BOS_ENABLED = False + +# Note: Some codes here refer to TensorBoardX. +# A good default block size depends on the system in question. +# A somewhat conservative default chosen here. +_DEFAULT_BLOCK_SIZE = 16 * 1024 * 1024 + + +def content_md5(buffer): + md5 = hashlib.md5() + md5.update(buffer) + return base64.standard_b64encode(md5.digest()) + + +class FileFactory(object): + def __init__(self): + self._register_factories = {} + + def register_filesystem(self, path, filesystem): + self._register_factories.update({path: filesystem}) + + def get_filesystem(self, path): + if path.startswith( + 'hdfs://') and "hdfs" not in self._register_factories: + if not HDFS_ENABLED: + raise RuntimeError('Please install module named "hdfs".') + try: + default_file_factory.register_filesystem( + "hdfs", HDFileSystem()) + except hdfs.util.HdfsError: + raise RuntimeError( + "Please initialize `~/.hdfscli.cfg` for HDFS.") + elif path.startswith( + 'bos://') and "bos" not in self._register_factories: + if not BOS_ENABLED: + raise RuntimeError( + 'Please install module named "bce-python-sdk".') + default_file_factory.register_filesystem("bos", BosFileSystem()) + + prefix = "" + index = path.find("://") + if index >= 0: + prefix = path[:index] + fs = self._register_factories.get(prefix, None) + if fs is None: + raise ValueError("No recognized filesystem for prefix %s" % prefix) + return fs + + +default_file_factory = FileFactory() + + +class LocalFileSystem(object): + def __init__(self): + pass + + @staticmethod + def exists(path): + return os.path.exists(path) + + @staticmethod + def makedirs(path): + os.makedirs(path) + + @staticmethod + def join(path, *paths): + return os.path.join(path, *paths) + + def isfile(self, filename): + return os.path.isfile(filename) + + def read_file(self, filename, binary_mode=True): + mode = "rb" if binary_mode else "r" + with open(filename, mode) as reader: + data = reader.read() + return data + + def read(self, filename, binary_mode=False, size=None, continue_from=None): + mode = "rb" if binary_mode else "r" + encoding = None if binary_mode else "utf-8" + offset = None + if continue_from is not None: + offset = continue_from.get("last_offset", None) + with open(filename, mode=mode, encoding=encoding) as fp: + if offset is not None: + fp.seek(offset) + data = fp.read(size) + continue_from_token = {"last_offset": fp.tell()} + return data, continue_from_token + + def _write(self, filename, file_content, mode): + encoding = None if "b" in mode else "utf-8" + with open(filename, mode, encoding=encoding) as fp: + fp.write(file_content) + + def append(self, filename, file_content, binary_mode=False): + try: + self._write(filename, file_content, "ab" if binary_mode else "a") + except FileNotFoundError: + self.makedirs(os.path.dirname(filename)) + + def write(self, filename, file_content, binary_mode=False): + try: + self._write(filename, file_content, "ab" if binary_mode else "a") + except FileNotFoundError: + self.makedirs(os.path.dirname(filename)) + # self._write(filename, file_content, "wb" if binary_mode else "w") + + def walk(self, dir): + if 'posix' == os.name: + return os.walk(dir, followlinks=True) + return os.walk(dir) + + +default_file_factory.register_filesystem("", LocalFileSystem()) + + +class HDFileSystem(object): + def __init__(self): + self.cli = hdfs.config.Config().get_client('dev') + + def exists(self, path): + if self.cli.status(hdfs_path=path[7:], strict=False) is None: + return False + else: + return True + + def isfile(self, filename): + return exists(filename) + + def read_file(self, filename, binary_mode=True): + with self.cli.read(hdfs_path=filename[7:]) as reader: + data = reader.read() + return data + + def makedirs(self, path): + self.cli.makedirs(hdfs_path=path[7:]) + + @staticmethod + def join(path, *paths): + result = os.path.join(path, *paths) + result.replace('\\', '/') + return result + + def read(self, filename, binary_mode=False, size=0, continue_from=None): + offset = 0 + if continue_from is not None: + offset = continue_from.get("last_offset", 0) + + encoding = None if binary_mode else "utf-8" + try: + with self.cli.read( + hdfs_path=filename[7:], offset=offset, + encoding=encoding) as reader: + data = reader.read() + continue_from_token = {"last_offset": offset + len(data)} + return data, continue_from_token + except HdfsError: + raise EOFError('No more events to read on HDFS.') + + def append(self, filename, file_content, binary_mode=False): + self.cli.write(hdfs_path=filename[7:], data=file_content, append=True) + + def write(self, filename, file_content, binary_mode=False): + self.cli.write(hdfs_path=filename[7:], data=file_content, append=True) + # self.cli.write(hdfs_path=filename[7:], data=file_content) + + def walk(self, dir): + walks = self.cli.walk(hdfs_path=dir[7:]) + return (['hdfs://' + root, dirs, files] for root, dirs, files in walks) + + +def get_object_info(path): + path = path[6:] + index = path.index('/') + bucket_name = path[0:index] + object_key = path[index + 1:] + return bucket_name, object_key + + +class BosConfigClient(object): + def __init__(self, bos_ak, bos_sk, bos_sts, bos_host="bj.bcebos.com"): + self.config = BceClientConfiguration( + credentials=BceCredentials(bos_ak, bos_sk), + endpoint=bos_host, + security_token=bos_sts) + self.bos_client = BosClient(self.config) + + def exists(self, path): + bucket_name, object_key = get_object_info(path) + try: + self.bos_client.get_object_meta_data(bucket_name, object_key) + return True + except exception.BceError: + return False + + def makedirs(self, path): + if not path.endswith('/'): + path += '/' + if self.exists(path): + return + bucket_name, object_key = get_object_info(path) + if not object_key.endswith('/'): + object_key += '/' + init_data = b'' + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=init_data, + content_md5=content_md5(init_data), + content_length=len(init_data)) + + @staticmethod + def join(path, *paths): + result = os.path.join(path, *paths) + result.replace('\\', '/') + return result + + def upload_object_from_file(self, path, filename): + """! + Upload a local file to baidu bos filesystem. The path can de divided as bucket name and prefix directory. + The file would be uploaded in bucket at path `join(prefix directory in path, filename)` + @param self object + @param path(str) bos directory path to store file, which consists of bucket_name + prefix directory. + @param filename(str) local file path to upload + """ + if not self.exists(path): + self.makedirs(path) + bucket_name, object_key = get_object_info(path) + + object_key = self.join(object_key, filename) + # if not object_key.endswith('/'): + # object_key += '/' + print('Uploading file `%s`' % filename) + self.bos_client.put_object_from_file( + bucket=bucket_name, key=object_key, file_name=filename) + + +class BosFileSystem(object): + def __init__(self, write_flag=True): + self.max_contents_count = 1 + self.max_contents_time = 1 + self.file_length_map = {} + + self._file_contents_to_add = b'' + self._file_contents_count = 0 + self._start_append_time = time.time() + if write_flag: + self.get_bos_config() + self.bos_client = BosClient(self.config) + + def get_bos_config(self): + ''' + Get Bos configuration from environment variables. + ''' + bos_host = os.getenv("BOS_HOST") + if not bos_host: + raise KeyError('${BOS_HOST} is not found.') + access_key_id = os.getenv("BOS_AK") + if not access_key_id: + raise KeyError('${BOS_AK} is not found.') + secret_access_key = os.getenv("BOS_SK") + if not secret_access_key: + raise KeyError('${BOS_SK} is not found.') + self.max_contents_count = int(os.getenv('BOS_CACHE_COUNT', 1)) + self.max_contents_time = int(os.getenv('BOS_CACHE_TIME', 1)) + bos_sts = os.getenv("BOS_STS") + self.config = BceClientConfiguration( + credentials=BceCredentials(access_key_id, secret_access_key), + endpoint=bos_host, + security_token=bos_sts) + + def set_bos_config(self, bos_ak, bos_sk, bos_sts, + bos_host="bj.bcebos.com"): + ''' + Set Bos configuration and get bos client according to parameters. + ''' + self.config = BceClientConfiguration( + credentials=BceCredentials(bos_ak, bos_sk), + endpoint=bos_host, + security_token=bos_sts) + self.bos_client = BosClient(self.config) + + def renew_bos_client_from_server(self): + ''' + Get bos client by visualdl provided ak, sk, and sts token + ''' + import requests + import json + from visualdl.utils.dir import CONFIG_PATH + with open(CONFIG_PATH, 'r') as fp: + server_url = json.load(fp)['server_url'] + url = server_url + '/sts/' + res = requests.post(url=url).json() + err_code = res.get('code') + msg = res.get('msg') + if '000000' == err_code: + sts_ak = msg.get('sts_ak') + sts_sk = msg.get('sts_sk') + sts_token = msg.get('token') + self.set_bos_config(sts_ak, sts_sk, sts_token) + else: + print('Renew bos client error. Error msg: {}'.format(msg)) + return + + def isfile(self, filename): + return exists(filename) + + def read_file(self, filename, binary=True): + bucket_name, object_key = get_object_info(filename) + result = self.bos_client.get_object_as_string(bucket_name, object_key) + return result + + def exists(self, path): + bucket_name, object_key = get_object_info(path) + try: + self.bos_client.get_object_meta_data(bucket_name, object_key) + return True + except exception.BceError: + return False + + def get_meta(self, bucket_name, object_key): + return self.bos_client.get_object_meta_data(bucket_name, object_key) + + def makedirs(self, path): + if not path.endswith('/'): + path += '/' + if self.exists(path): + return + bucket_name, object_key = get_object_info(path) + if not object_key.endswith('/'): + object_key += '/' + init_data = b'' + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=init_data, + content_md5=content_md5(init_data), + content_length=len(init_data)) + + @staticmethod + def join(path, *paths): + result = os.path.join(path, *paths) + result.replace('\\', '/') + return result + + def read(self, filename, binary_mode=False, size=0, continue_from=None): + bucket_name, object_key = get_object_info(filename) + offset = 0 + if continue_from is not None: + offset = continue_from.get("last_offset", 0) + length = int( + self.get_meta(bucket_name, object_key).metadata.content_length) + if offset < length: + data = self.bos_client.get_object_as_string( + bucket_name=bucket_name, + key=object_key, + range=[offset, length - 1]) + else: + data = b'' + + continue_from_token = {"last_offset": length} + return data, continue_from_token + + def ready_to_append(self): + if self._file_contents_count >= self.max_contents_count or \ + time.time() - self._start_append_time > self.max_contents_time: + return True + else: + return False + + def append(self, filename, file_content, binary_mode=False, force=False): + self._file_contents_to_add += file_content + self._file_contents_count += 1 + + if not force and not self.ready_to_append(): + return + file_content = self._file_contents_to_add + bucket_name, object_key = get_object_info(filename) + if not self.exists(filename): + init_data = b'' + # Two cases will come here + # 1. the file not exist, then we need to create the file + # 2. sts token invalid in self.exists, we should renew the token, and continue to write + try: + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=init_data, + content_md5=content_md5(init_data), + content_length=len(init_data)) + except (exception.BceServerError, + exception.BceHttpClientError) as e: + if bucket_name == 'visualdl-server': # only sts token from visualdl-server, we can renew automatically + self.renew_bos_client_from_server() + # we should add a judgement for case 2 + try: + self.bos_client.get_object_meta_data( + bucket_name, object_key) + except exception.BceError: + # the file not exists, then create the file + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=init_data, + content_md5=content_md5(init_data), + content_length=len(init_data)) + return + else: + raise e # user defined bos token, we have no idea to renew the token, so throw the exception + content_length = len(file_content) + + try: + offset = self.get_meta(bucket_name, + object_key).metadata.content_length + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=file_content, + content_md5=content_md5(file_content), + content_length=content_length, + offset=offset) + except (exception.BceServerError, exception.BceHttpClientError) as e: + if bucket_name == 'visualdl-server': # only sts token from visualdl-server, we can renew automatically + self.renew_bos_client_from_server() + offset = self.get_meta(bucket_name, + object_key).metadata.content_length + self.bos_client.append_object( + bucket_name=bucket_name, + key=object_key, + data=file_content, + content_md5=content_md5(file_content), + content_length=content_length, + offset=offset) + else: + raise e # user defined bos token, we have no idea to renew the token, so throw the exception + self._file_contents_to_add = b'' + self._file_contents_count = 0 + self._start_append_time = time.time() + + def write(self, filename, file_content, binary_mode=False, append=True): + if append: + self.append(filename, file_content, binary_mode=False) + else: + bucket_name, object_key = get_object_info(filename) + try: + self.bos_client.put_object( + bucket_name=bucket_name, + key=object_key, + data=file_content, + content_length=len(file_content), + content_md5=content_md5(file_content)) + except (exception.BceServerError, + exception.BceHttpClientError) as e: # sts token invalid + if bucket_name == 'visualdl-server': # only sts token from visualdl-server, we can renew automatically + self.renew_bos_client_from_server() + self.bos_client.put_object( + bucket_name=bucket_name, + key=object_key, + data=file_content, + content_length=len(file_content), + content_md5=content_md5(file_content)) + else: + raise e # user defined bos token, we have no idea to renew the token, so throw the exception + + def walk(self, dir): + class WalkGenerator(): + def __init__(self, bucket_name, contents): + self.contents = None + self.length = 0 + self.bucket = bucket_name + self.handle_contents(contents) + self.count = 0 + + def handle_contents(self, contents): + contents_map = {} + for item in contents: + try: + rindex = item.rindex('/') + key = item[0:rindex] + value = item[rindex + 1:] + except ValueError: + key = '.' + value = item + if key in contents_map.keys(): + contents_map[key].append(value) + else: + contents_map[key] = [value] + temp_walk = [] + for key, value in contents_map.items(): + temp_walk.append([ + BosFileSystem.join('bos://' + self.bucket, key), [], + value + ]) + self.length = len(temp_walk) + self.contents = temp_walk + + def __iter__(self): + return self + + def __next__(self): + if self.count < self.length: + self.count += 1 + return self.contents[self.count - 1] + else: + raise StopIteration + + bucket_name, object_key = get_object_info(dir) + + if object_key in ['.', './']: + prefix = None + else: + prefix = object_key if object_key.endswith( + '/') else object_key + '/' + response = self.bos_client.list_objects(bucket_name, prefix=prefix) + contents = [content.key for content in response.contents] + return WalkGenerator(bucket_name, contents) + + +class BFile(object): + def __init__(self, filename, mode): + if mode not in ('r', 'rb', 'br', 'w', 'wb', 'bw'): + raise NotImplementedError("mode {} not supported by " + "BFile.".format(mode)) + self._filename = filename + self.fs = default_file_factory.get_filesystem(filename) + self.fs_supports_append = hasattr(self.fs, 'append') + self.buff = None + self.buff_chunk_size = _DEFAULT_BLOCK_SIZE + self.buff_offset = 0 + self.continuation_token = None + self.write_temp = None + self.write_started = False + self.binary_mode = 'b' in mode + self.write_mode = 'w' in mode + self.closed = False + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + self.buff = None + self.buff_offset = 0 + self.continuation_token = None + + def __iter__(self): + return self + + def isfile(self, filename): + return self.fs.isfile(filename) + + def _read_buffer_to_offset(self, new_buff_offset): + """Read buffer from index self.buffer_offset to index new_buff_offset. + + self.buff_offset marks the last position of the last read, + new_buff_offset indicates the last position of this read. + self.buff_offset will be updated by new_buff_offset after this read. + + Returns: + self.buff[i1: i2]: Content of self.buff. + """ + old_buff_offset = self.buff_offset + read_size = min(len(self.buff), new_buff_offset) - old_buff_offset + self.buff_offset += read_size + return self.buff[old_buff_offset:old_buff_offset + read_size] + + def read_file(self, filename, binnary=True): + return self.fs.read_file(filename, binnary) + + def read(self, n=None): + """Read `n` or all contents of self.buff or file. + + Returns: + result: Data from self.buff or file. + """ + result = None + # If self.buff is not none and length of self.buff more than + # self.buff_offset, means there are some content in self.buff have + # not been read. + if self.buff and len(self.buff) > self.buff_offset: + if n is not None: + chunk = self._read_buffer_to_offset(self.buff_offset + n) + # If length of data in self.buff is more than `n`, then read `n` + # data from local buffer. + if len(chunk) == n: + return chunk + result = chunk + # The length of all data in self.buff may less than `n`, + # so we should read other `n-length(self.buff)` data. + n -= len(chunk) + # If n is none, read all data in self.buff. + else: + # add all local buffer and update offsets + result = self._read_buffer_to_offset(len(self.buff)) + + # self.buff is empty if program is here. + # Read from filesystem. + # If n is not none, read max(n, self.buff_chunk_size) data from file, + # otherwise read all data from file. + # TODO(shenhuhan) N is limited to max_buff, but all-data is unlimited? + read_size = max(self.buff_chunk_size, n) if n is not None else None + self.buff, self.continuation_token = self.fs.read( + self._filename, self.binary_mode, read_size, + self.continuation_token) + self.buff_offset = 0 + + if n is not None: + chunk = self._read_buffer_to_offset(n) + else: + # add all local buffer and update offsets + chunk = self._read_buffer_to_offset(len(self.buff)) + result = result + chunk if result else chunk + + return result + + def write(self, file_content): + """Write contents to file. + + Args: + file_content: Contents waiting to be written to file. + """ + if not self.write_mode: + raise RuntimeError("File not opened in write mode") + if self.closed: + raise RuntimeError("File already closed") + + if self.fs_supports_append: + if not self.write_started: + self.fs.write(self._filename, file_content, self.binary_mode) + self.write_started = True + else: + self.fs.append(self._filename, file_content, self.binary_mode) + else: + # add to temp file, but wait for flush to write to final filesystem + if self.write_temp is None: + mode = "w+b" if self.binary_mode else "w+" + self.write_temp = tempfile.TemporaryFile(mode) + self.write_temp.write(file_content) + + def __next__(self): + line = None + while True: + if not self.buff: + # read one unit into the buffer + line = self.read(1) + if line and (line[-1] == '\n' or not self.buff): + return line + if not self.buff: + raise StopIteration() + else: + index = self.buff.find('\n', self.buff_offset) + if index != -1: + # include line until now plus newline + chunk = self.read(index + 1 - self.buff_offset) + line = line + chunk if line else chunk + return line + + # read one unit past end of buffer + chunk = self.read(len(self.buff) + 1 - self.buff_offset) + line = line + chunk if line else chunk + if line and (line[-1] == '\n' or not self.buff): + return line + if not self.buff: + raise StopIteration() + + def next(self): + return self.__next__() + + def flush(self): + """Flush data to disk. + """ + if self.closed: + raise RuntimeError("File already closed") + if not self.fs_supports_append: + if self.write_temp is not None: + # read temp file from the beginning + self.write_temp.flush() + self.write_temp.seek(0) + chunk = self.write_temp.read() + if chunk is not None: + # write full contents and keep in temp file + self.fs.write(self._filename, chunk, self.binary_mode) + self.write_temp.seek(len(chunk)) + + def close(self): + if isinstance(self.fs, BosFileSystem): + try: + self.fs.append( + self._filename, b'', self.binary_mode, force=True) + except Exception: + pass + self.flush() + if self.write_temp is not None: + self.write_temp.close() + self.write_temp = None + self.write_started = False + self.closed = True + + +def exists(path): + return default_file_factory.get_filesystem(path).exists(path) + + +def makedirs(path): + return default_file_factory.get_filesystem(path).makedirs(path) + + +def join(path, *paths): + return default_file_factory.get_filesystem(path).join(path, *paths) + + +def walk(dir): + return default_file_factory.get_filesystem(dir).walk(dir) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bos_conf.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bos_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..5be94f468aa5f7ad2d5a37c6f1bb3518dd5babc4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/io/bos_conf.py @@ -0,0 +1,29 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from baidubce.bce_client_configuration import BceClientConfiguration +from baidubce.auth.bce_credentials import BceCredentials +import os +# Set Host, AccessKeyID and SecretAccessKey of BosClient + +bos_host = os.getenv("BOS_HOST") +access_key_id = os.getenv("BOS_AK") +secret_access_key = os.getenv("BOS_SK") + + +# Create BceClientConfiguration +config = BceClientConfiguration( + credentials=BceCredentials(access_key_id, secret_access_key), + endpoint=bos_host) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bab744b75600618b2912de1ad551f15c5686580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/record_pb2.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/record_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..a665d880e14737ca778d050bf1875c7cc19bbd5a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/proto/record_pb2.py @@ -0,0 +1,74 @@ +# flake8: noqa +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: record.proto +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x0crecord.proto\x12\x08visualdl\"\xa2\x0c\n\x06Record\x12&\n\x06values\x18\x01 \x03(\x0b\x32\x16.visualdl.Record.Value\x1a%\n\x05Image\x12\x1c\n\x14\x65ncoded_image_string\x18\x04 \x01(\x0c\x1a#\n\x04Text\x12\x1b\n\x13\x65ncoded_text_string\x18\x01 \x01(\t\x1a}\n\x05\x41udio\x12\x13\n\x0bsample_rate\x18\x01 \x01(\x02\x12\x14\n\x0cnum_channels\x18\x02 \x01(\x03\x12\x15\n\rlength_frames\x18\x03 \x01(\x03\x12\x1c\n\x14\x65ncoded_audio_string\x18\x04 \x01(\x0c\x12\x14\n\x0c\x63ontent_type\x18\x05 \x01(\t\x1a+\n\tEmbedding\x12\r\n\x05label\x18\x01 \x03(\t\x12\x0f\n\x07vectors\x18\x02 \x03(\x02\x1aP\n\nEmbeddings\x12.\n\nembeddings\x18\x01 \x03(\x0b\x32\x1a.visualdl.Record.Embedding\x12\x12\n\nlabel_meta\x18\x02 \x03(\t\x1a\x43\n\x10\x62ytes_embeddings\x12\x16\n\x0e\x65ncoded_labels\x18\x01 \x01(\x0c\x12\x17\n\x0f\x65ncoded_vectors\x18\x02 \x01(\x0c\x1a\x34\n\tHistogram\x12\x10\n\x04hist\x18\x01 \x03(\x01\x42\x02\x10\x01\x12\x15\n\tbin_edges\x18\x02 \x03(\x01\x42\x02\x10\x01\x1al\n\x07PRCurve\x12\x0e\n\x02TP\x18\x01 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02\x46P\x18\x02 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02TN\x18\x03 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02\x46N\x18\x04 \x03(\x03\x42\x02\x10\x01\x12\x11\n\tprecision\x18\x05 \x03(\x01\x12\x0e\n\x06recall\x18\x06 \x03(\x01\x1a\x65\n\tROC_Curve\x12\x0e\n\x02TP\x18\x01 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02\x46P\x18\x02 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02TN\x18\x03 \x03(\x03\x42\x02\x10\x01\x12\x0e\n\x02\x46N\x18\x04 \x03(\x03\x42\x02\x10\x01\x12\x0b\n\x03tpr\x18\x05 \x03(\x01\x12\x0b\n\x03\x66pr\x18\x06 \x03(\x01\x1a\xf0\x01\n\x06HParam\x12\x37\n\x0bhparamInfos\x18\x01 \x03(\x0b\x32\".visualdl.Record.HParam.HparamInfo\x12\x37\n\x0bmetricInfos\x18\x02 \x03(\x0b\x32\".visualdl.Record.HParam.HparamInfo\x12\x0c\n\x04name\x18\x03 \x01(\t\x1a\x66\n\nHparamInfo\x12\x13\n\tint_value\x18\x01 \x01(\x03H\x00\x12\x15\n\x0b\x66loat_value\x18\x02 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x03 \x01(\tH\x00\x12\x0c\n\x04name\x18\x04 \x01(\tB\x06\n\x04type\x1a \n\x08MetaData\x12\x14\n\x0c\x64isplay_name\x18\x01 \x01(\t\x1a&\n\x08TagValue\x12\x0b\n\x03tag\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x02\x1a\x98\x04\n\x05Value\x12\n\n\x02id\x18\x01 \x01(\x03\x12\x0b\n\x03tag\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x0f\n\x05value\x18\x04 \x01(\x02H\x00\x12\'\n\x05image\x18\x05 \x01(\x0b\x32\x16.visualdl.Record.ImageH\x00\x12\'\n\x05\x61udio\x18\x06 \x01(\x0b\x32\x16.visualdl.Record.AudioH\x00\x12\x31\n\nembeddings\x18\x07 \x01(\x0b\x32\x1b.visualdl.Record.EmbeddingsH\x00\x12/\n\thistogram\x18\x08 \x01(\x0b\x32\x1a.visualdl.Record.HistogramH\x00\x12,\n\x08pr_curve\x18\t \x01(\x0b\x32\x18.visualdl.Record.PRCurveH\x00\x12.\n\tmeta_data\x18\n \x01(\x0b\x32\x19.visualdl.Record.MetaDataH\x00\x12/\n\troc_curve\x18\x0b \x01(\x0b\x32\x1a.visualdl.Record.ROC_CurveH\x00\x12%\n\x04text\x18\x0c \x01(\x0b\x32\x15.visualdl.Record.TextH\x00\x12)\n\x06hparam\x18\r \x01(\x0b\x32\x17.visualdl.Record.HParamH\x00\x12.\n\ttag_value\x18\x0e \x01(\x0b\x32\x19.visualdl.Record.TagValueH\x00\x42\x0b\n\tone_valueb\x06proto3' +) + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'record_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _RECORD_HISTOGRAM.fields_by_name['hist']._options = None + _RECORD_HISTOGRAM.fields_by_name['hist']._serialized_options = b'\020\001' + _RECORD_HISTOGRAM.fields_by_name['bin_edges']._options = None + _RECORD_HISTOGRAM.fields_by_name[ + 'bin_edges']._serialized_options = b'\020\001' + _RECORD_PRCURVE.fields_by_name['TP']._options = None + _RECORD_PRCURVE.fields_by_name['TP']._serialized_options = b'\020\001' + _RECORD_PRCURVE.fields_by_name['FP']._options = None + _RECORD_PRCURVE.fields_by_name['FP']._serialized_options = b'\020\001' + _RECORD_PRCURVE.fields_by_name['TN']._options = None + _RECORD_PRCURVE.fields_by_name['TN']._serialized_options = b'\020\001' + _RECORD_PRCURVE.fields_by_name['FN']._options = None + _RECORD_PRCURVE.fields_by_name['FN']._serialized_options = b'\020\001' + _RECORD_ROC_CURVE.fields_by_name['TP']._options = None + _RECORD_ROC_CURVE.fields_by_name['TP']._serialized_options = b'\020\001' + _RECORD_ROC_CURVE.fields_by_name['FP']._options = None + _RECORD_ROC_CURVE.fields_by_name['FP']._serialized_options = b'\020\001' + _RECORD_ROC_CURVE.fields_by_name['TN']._options = None + _RECORD_ROC_CURVE.fields_by_name['TN']._serialized_options = b'\020\001' + _RECORD_ROC_CURVE.fields_by_name['FN']._options = None + _RECORD_ROC_CURVE.fields_by_name['FN']._serialized_options = b'\020\001' + _RECORD._serialized_start = 27 + _RECORD._serialized_end = 1597 + _RECORD_IMAGE._serialized_start = 77 + _RECORD_IMAGE._serialized_end = 114 + _RECORD_TEXT._serialized_start = 116 + _RECORD_TEXT._serialized_end = 151 + _RECORD_AUDIO._serialized_start = 153 + _RECORD_AUDIO._serialized_end = 278 + _RECORD_EMBEDDING._serialized_start = 280 + _RECORD_EMBEDDING._serialized_end = 323 + _RECORD_EMBEDDINGS._serialized_start = 325 + _RECORD_EMBEDDINGS._serialized_end = 405 + _RECORD_BYTES_EMBEDDINGS._serialized_start = 407 + _RECORD_BYTES_EMBEDDINGS._serialized_end = 474 + _RECORD_HISTOGRAM._serialized_start = 476 + _RECORD_HISTOGRAM._serialized_end = 528 + _RECORD_PRCURVE._serialized_start = 530 + _RECORD_PRCURVE._serialized_end = 638 + _RECORD_ROC_CURVE._serialized_start = 640 + _RECORD_ROC_CURVE._serialized_end = 741 + _RECORD_HPARAM._serialized_start = 744 + _RECORD_HPARAM._serialized_end = 984 + _RECORD_HPARAM_HPARAMINFO._serialized_start = 882 + _RECORD_HPARAM_HPARAMINFO._serialized_end = 984 + _RECORD_METADATA._serialized_start = 986 + _RECORD_METADATA._serialized_end = 1018 + _RECORD_TAGVALUE._serialized_start = 1020 + _RECORD_TAGVALUE._serialized_end = 1058 + _RECORD_VALUE._serialized_start = 1061 + _RECORD_VALUE._serialized_end = 1597 +# @@protoc_insertion_point(module_scope) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eabf5f1e0d449273054645bb9840a535dee4981a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/cache.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..16bff11f42de62b2d1964d1e0b710dcd56b52a02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/cache.py @@ -0,0 +1,73 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import time + + +class MemCache(object): + class Record: + def __init__(self, value): + self.time = time.time() + self.value = value + + def clear(self): + self.value = None + + def expired(self, timeout): + return timeout > 0 and time.time() - self.time >= timeout + + ''' + A global dict to help cache some temporary data. + ''' + + def __init__(self, timeout=-1): + self._timeout = timeout + self._data = {} + + def set(self, key, value): + self._data[key] = MemCache.Record(value) + + def get(self, key): + rcd = self._data.get(key, None) + if not rcd: + return None + # do not delete the key to accelerate speed + if rcd.expired(self._timeout): + rcd.clear() + return None + return rcd.value + + +if __name__ == '__main__': + import unittest + + class TestMemCacheTest(unittest.TestCase): + def setUp(self): + self.cache = MemCache(timeout=1) + + def expire(self): + self.cache.set("message", "hello") + self.assertFalse(self.cache.expired(1)) + time.sleep(4) + self.assertTrue(self.cache.expired(1)) + + def test_have_key(self): + self.cache.set('message', 'hello') + self.assertTrue(self.cache.get('message')) + time.sleep(1.1) + self.assertFalse(self.cache.get('message')) + self.assertTrue(self.cache.get("message") is None) + + unittest.main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/testing.wav b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/testing.wav new file mode 100644 index 0000000000000000000000000000000000000000..ce4ae92b57f8985377b12f8a83424ead07487ac4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/python/testing.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e77c9354dd855279308b23e63a9a980ca420c541c88465d576a91baf3eda87f +size 64044 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bab744b75600618b2912de1ad551f15c5686580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/graph_reader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/graph_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..1acc99ed9c6e9b844c78d63a9e709282cd0c8be8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/graph_reader.py @@ -0,0 +1,222 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json +import os + +from visualdl.component.graph import analyse_model +from visualdl.component.graph import Model +from visualdl.io import bfile + + +def is_VDLGraph_file(path): + """Determine whether it is a VDL graph file according to the file name. + + File name of a VDL graph file must contain `vdlgraph`. + + Args: + path: File name to determine. + Returns: + True if the file is a VDL graph file, otherwise false. + """ + if "vdlgraph" not in path and 'pdmodel' not in path: + return False + return True + + +class GraphReader(object): + """Graph reader to read vdl graph files, support for frontend api in lib.py. + """ + + def __init__(self, logdir=''): + """Instance of GraphReader + + Args: + logdir: The dir include vdl graph files, multiple subfolders allowed. + """ + if isinstance(logdir, str): + self.dir = [logdir] + else: + self.dir = logdir + + self.walks = {} + self.displayname2runs = {} + self.runs2displayname = {} + self.graph_buffer = {} + self.walks_buffer = {} + + @property + def logdir(self): + return self.dir + + def component_tabs(self, update=False): + """Get component tabs used by vdl frontend. + """ + component_tabs = set() + if not self.logdir: + return component_tabs + if update is True: + self.runs(update=update) + if self.walks: + component_tabs.add('dynamic_graph') + return component_tabs + + def get_all_walk(self): + flush_walks = {} + for dir in self.dir: + dir = os.path.realpath(dir) + for root, dirs, files in bfile.walk(dir): + flush_walks.update({root: files}) + return flush_walks + + def graphs(self, update=False): + """Get graph files. + + Every dir(means `run` in vdl) has only one graph file(means `actual log file`). + + Returns: + walks: A dict like {"exp1": "vdlgraph.1587375595.log", + "exp2": "vdlgraph.1587375685.log"} + """ + if not self.walks or update is True: + flush_walks = self.get_all_walk() + + walks_temp = {} + for run, filenames in flush_walks.items(): + tags_temp = [ + filename for filename in filenames + if is_VDLGraph_file(filename) + ] + tags_temp.sort(reverse=True) + if len(tags_temp) > 0: + walks_temp.update({run: tags_temp[0]}) + self.walks = walks_temp + return self.walks + + def runs(self, update=True): + self.graphs(update=update) + graph_runs = list(self.walks.keys( + )) if 'manual_input_model' not in self.graph_buffer else list( + self.walks.keys()) + ['manual_input_model'] + return sorted(graph_runs) + + def get_graph(self, + run, + nodeid=None, + expand=False, + keep_state=False, + expand_all=False, + refresh=False): + if run == 'manual_input_model' and run in self.graph_buffer: + graph_model = self.graph_buffer[run] + if nodeid is not None: + graph_model.adjust_visible(nodeid, expand, keep_state) + return graph_model.make_graph( + refresh=refresh, expand_all=expand_all) + if run in self.walks: + if run in self.walks_buffer: + if self.walks[run] == self.walks_buffer[run]: + graph_model = self.graph_buffer[run] + if nodeid is not None: + graph_model.adjust_visible(nodeid, expand, keep_state) + return graph_model.make_graph( + refresh=refresh, expand_all=expand_all) + + data = bfile.BFile(bfile.join(run, self.walks[run]), 'rb').read() + if 'pdmodel' in self.walks[run]: + graph_model = Model(analyse_model(data)) + else: + graph_model = Model(json.loads(data.decode())) + self.graph_buffer[run] = graph_model + self.walks_buffer[run] = self.walks[run] + if nodeid is not None: + graph_model.adjust_visible(nodeid, expand, keep_state) + return graph_model.make_graph( + refresh=refresh, expand_all=expand_all) + + def search_graph_node(self, run, nodeid, keep_state=False, is_node=True): + if run == 'manual_input_model' and run in self.graph_buffer: + graph_model = self.graph_buffer[run] + graph_model.adjust_search_node_visible( + nodeid, keep_state=keep_state, is_node=is_node) + return graph_model.make_graph(refresh=False, expand_all=False) + if run in self.walks: + if run in self.walks_buffer: + if self.walks[run] == self.walks_buffer[run]: + graph_model = self.graph_buffer[run] + graph_model.adjust_search_node_visible( + nodeid, keep_state=keep_state, is_node=is_node) + return graph_model.make_graph( + refresh=False, expand_all=False) + + data = bfile.BFile(bfile.join(run, self.walks[run]), 'rb').read() + if 'pdmodel' in self.walks[run]: + graph_model = Model(analyse_model(data)) + else: + graph_model = Model(json.loads(data.decode())) + self.graph_buffer[run] = graph_model + self.walks_buffer[run] = self.walks[run] + graph_model.adjust_search_node_visible( + nodeid, keep_state=keep_state, is_node=is_node) + return graph_model.make_graph(refresh=False, expand_all=False) + + def get_all_nodes(self, run): + if run == 'manual_input_model' and run in self.graph_buffer: + graph_model = self.graph_buffer[run] + return graph_model.get_all_leaf_nodes() + if run in self.walks: + if run in self.walks_buffer: + if self.walks[run] == self.walks_buffer[run]: + graph_model = self.graph_buffer[run] + return graph_model.get_all_leaf_nodes() + + data = bfile.BFile(bfile.join(run, self.walks[run]), 'rb').read() + if 'pdmodel' in self.walks[run]: + graph_model = Model(analyse_model(data)) + else: + graph_model = Model(json.loads(data.decode())) + self.graph_buffer[run] = graph_model + self.walks_buffer[run] = self.walks[run] + return graph_model.get_all_leaf_nodes() + + def set_displayname(self, log_reader): + self.displayname2runs = log_reader.name2tags + self.runs2displayname = log_reader.tags2name + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + def set_input_graph(self, content, file_type='pdmodel'): + if isinstance(content, str): + if not is_VDLGraph_file(content): + return + if 'pdmodel' in content: + file_type = 'pdmodel' + else: + file_type = 'vdlgraph' + content = bfile.BFile(content, 'rb').read() + + if file_type == 'pdmodel': + data = analyse_model(content) + self.graph_buffer['manual_input_model'] = Model(data) + + elif file_type == 'vdlgraph': + self.graph_buffer['manual_input_model'] = Model( + json.loads(content.decode())) + + else: + return diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/reader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f79489ff7cae7f2d4c20ad40b1903f998796b2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/reader.py @@ -0,0 +1,393 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections +import os # noqa: F401 +from functools import partial # noqa: F401 + +from visualdl.component import components +from visualdl.io import bfile +from visualdl.proto import record_pb2 +from visualdl.reader.record_reader import RecordReader +from visualdl.server.data_manager import default_data_manager +from visualdl.utils.string_util import decode_tag +from visualdl.utils.string_util import encode_tag + + +def is_VDLRecord_file(path, check=False): + """Determine whether it is a VDL log file according to the file name. + + File name of a VDL log file must contain `vdlrecords`. + + Args: + path: File name to determine. + check: Check file is valid or not. + + Returns: + True if the file is a VDL log file, otherwise false. + """ + if "vdlrecords" not in path: + return False + if check: + _reader = RecordReader(filepath=path) + meta_data = _reader.get_next() + record = record_pb2.Record() + record.ParseFromString(meta_data) + if 'meta_data_tag' != record.values[0].tag: + return False + return True + + +class LogReader(object): + """Log reader to read vdl log, support for frontend api in lib.py. + + """ + + def __init__(self, logdir='', file_path=''): + """Instance of LogReader + + Args: + logdir: The dir include vdl log files, multiple subfolders allowed. + """ + if isinstance(logdir, str): + self.dir = [logdir] + else: + self.dir = logdir + + self.reader = None + self.readers = {} + self.walks = None + self._tags = {} + self.name2tags = {} + self.tags2name = {} + + self.file_readers = {} + + # {'run': {'scalar': {'tag1': data, 'tag2': data}}} + self._log_datas = collections.defaultdict( + lambda: collections.defaultdict(lambda: collections.defaultdict( + list))) + + if file_path: + self._log_data = collections.defaultdict(lambda: collections. + defaultdict(list)) + self.get_file_reader(file_path=file_path) + remain = self.get_remain() + self.read_log_data(remain=remain) + components_name = components.keys() + for name in components_name: + exec("self.get_%s=partial(self.get_data, '%s')" % (name, name)) + elif logdir: + self.data_manager = default_data_manager + self.load_new_data(update=True) + self._a_tags = {} + + self._model = "" + + @property + def model(self): + return self._model + + @model.setter + def model(self, model_path): + self._model = model_path + with bfile.BFile(model_path, 'rb') as bfp: + if not bfp.isfile(model_path): + print( + "Model path %s should be file path, please check this path." + % model_path) + else: + if bfile.exists(model_path): + self._model = model_path + else: + print("Model path %s is invalid, please check this path." % + model_path) + + @property + def logdir(self): + return self.dir + + def parsing_from_proto(self, component, proto_datas): + data = [] + if 'scalar' == component: + for item in proto_datas: + data.append([item.id, item.tag, item.timestamp, item.value]) + return data + elif 'scalars' == component: + for item in proto_datas: + data.append([ + item.id, item.tag, item.tag_value.tag, item.timestamp, + item.tag_value.value + ]) + return data + return proto_datas + + def _get_log_tags(self): + component_keys = self._log_data.keys() + log_tags = {} + for key in component_keys: + _tags = list(self._log_data[key].keys()) + tags = list(map(lambda x: encode_tag(x), _tags)) + log_tags[key] = tags + + return log_tags + + def get_log_data(self, component, run, tag): + if (run in self._log_datas.keys() + and component in self._log_datas[run].keys() + and tag in self._log_datas[run][component].keys()): + return self._log_datas[run][component][tag] + else: + file_path = bfile.join(run, self.walks[run]) + reader = self._get_file_reader(file_path=file_path, update=False) + remain = self.get_remain(reader=reader) + data = self.read_log_data( + remain=remain, update=False)[component][tag] + data = self.parsing_from_proto(component, data) + self._log_datas[run][component][tag] = data + return data + + def get_tags(self): + return self._get_log_tags() + + def get_data(self, component, tag): + return self._log_data[component][decode_tag(tag)] + + def parse_from_bin(self, record_bin): + """Register to self._tags by component type. + + Args: + record_bin: Binary data from vdl log file. + """ + record = record_pb2.Record() + record.ParseFromString(record_bin) + value = record.values[0] + tag = decode_tag(value.tag) + path = bfile.join(self.reader.dir, tag) + + if path not in self._tags.keys(): + value_type = value.WhichOneof("one_value") + if "value" == value_type: + component = "scalar" + elif "image" == value_type: + component = "image" + elif "embeddings" == value_type: + component = "embeddings" + elif "audio" == value_type: + component = "audio" + elif "histogram" == value_type: + component = "histogram" + elif "pr_curve" == value_type: + component = "pr_curve" + elif "roc_curve" == value_type: + component = "roc_curve" + elif "meta_data" == value_type: + self.update_meta_data(record) + component = "meta_data" + elif "text" == value_type: + component = "text" + elif "hparam" == value_type: + component = "hyper_parameters" + elif "tag_value" == value_type: + component = "scalars" + else: + raise TypeError("Invalid value type `%s`." % value_type) + self._tags[path] = component + + return self._tags[path], self.reader.dir, tag, value + + def update_meta_data(self, record): + meta = record.values[0].meta_data + if meta.display_name: + self.name2tags[meta.display_name] = self.reader.dir + self.tags2name[self.reader.dir] = meta.display_name + + def get_all_walk(self): + self.walks = {} + for dir in self.dir: + for root, dirs, files in bfile.walk(dir): + self.walks.update({root: files}) + + def logs(self, update=False): + """Get logs. + + Every dir(means `run` in vdl) has only one log(meads `actual log file`). + + Returns: + walks: A dict like {"exp1": "vdlrecords.1587375595.log", + "exp2": "vdlrecords.1587375685.log"} + """ + if self.walks is None or update is True: + self.get_all_walk() + + walks_temp = {} + for run, tags in self.walks.items(): + tags_temp = [tag for tag in tags if is_VDLRecord_file(tag)] + tags_temp.sort(reverse=True) + if len(tags_temp) > 0: + walks_temp.update({run: tags_temp[0]}) + self.walks = walks_temp + return self.walks + + def get_log_reader(self, dir, log): + """Get log reader for every vdl log file. + + Get instance of class RecordReader base on BFile. Note that each + `log` may contain multi `tag`. + + Args: + dir: Dir name of log. + log: Vdl log file name. + """ + if self.walks is None: + self.logs() + if self.walks.get(dir, None) != log: + raise FileNotFoundError("Can't find file %s.", (dir + "/" + log)) + + filepath = bfile.join(dir, log) + if filepath not in self.readers.keys(): + self.register_reader(filepath, dir) + self.reader = self.readers[filepath] + return self.reader + + def get_file_reader(self, file_path): + """Get file reader for specified vdl log file. + + Get instance of class RecordReader base on BFile. + + Args: + file_path: Vdl log file path. + """ + return self._get_file_reader(file_path, True) + + def _get_file_reader(self, file_path, update=True): + if update: + self.register_reader(file_path) + self.reader = self.readers[file_path] + self.reader.dir = file_path + return self.reader + else: + reader = RecordReader(filepath=file_path) + return reader + + def register_reader(self, path, dir=None, update=True): + if update: + if path not in list(self.readers.keys()): + reader = RecordReader(filepath=path, dir=dir) + self.readers[path] = reader + else: + pass + + def register_readers(self, update=False): + """Register all readers for all vdl log files. + + Args: + update: Need update if `update` is True. + """ + self.logs(update) + for dir, path in self.walks.items(): + filepath = bfile.join(dir, path) + self.register_reader(filepath, dir) + + def add_remain(self): + """Add remain data to data_manager. + + Add remain data to data manager according its component type and tag + one by one. + """ + for reader in self.readers.values(): + self.reader = reader + remain = self.reader.get_remain() + for item in remain: + component, dir, tag, record = self.parse_from_bin(item) + + self.data_manager.add_item(component, self.reader.dir, tag, + record) + + def get_remain(self, reader=None): + """Get all remain data by self.reader. + """ + if self.reader is None and reader is None: + raise RuntimeError("Please specify log path!") + return self.reader.get_remain( + ) if reader is None else reader.get_remain() + + def read_log_data(self, remain, update=True): + """Parse data from log file without sampling. + + Args: + remain: Raw data from log file. + """ + _log_data = collections.defaultdict(lambda: collections.defaultdict( + list)) + for item in remain: + component, dir, tag, record = self.parse_from_bin(item) + _log_data[component][tag].append(record) + if update: + self._log_data = _log_data + return _log_data + + @property + def log_data(self): + return self._log_data + + def runs(self, update=True): + self.logs(update=update) + return list(self.walks.keys()) + + def tags(self): + if self._tags is None: + self.add_remain() + return self._tags + + def components(self, update=False): + """Get components type used by vdl. + """ + if self.logdir is None: + return set() + if update is True: + self.load_new_data(update=update) + components_set = set(self._tags.values()) + + return components_set + + def component_tabs(self, update=False): + """Get component tabs used by vdl frontend. + """ + component_tabs = set() + if not self.logdir: + return component_tabs + if update is True: + self.load_new_data(update=update) + for component in set(self._tags.values()): + if component == 'meta_data': + continue + component_tabs.add(component) + return component_tabs + + def load_new_data(self, update=True): + """Load remain data. + + Make sure all readers for every vdl log file are registered, load all + remain data. + """ + if self.logdir is not None: + self.register_readers(update=update) + self.add_remain() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + pass diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/record_reader.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/record_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..1f26c34a5991f9a97355e3bfe5ce905a62cc134e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/reader/record_reader.py @@ -0,0 +1,116 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from visualdl.io import bfile +import struct + + +class _RecordReader(object): + def __init__(self, filepath=None): + if filepath is None: + raise FileNotFoundError('No filename provided, cannot read Events') + if not bfile.exists(filepath): + raise FileNotFoundError( + '{} does not point to valid Events file'.format(filepath)) + + self._curr_event = None + self.file_handle = bfile.BFile(filepath, 'rb') + + def get_next(self): + # Read the header + self._curr_event = None + header_str = self.file_handle.read(8) + if len(header_str) != 8: + # Hit EOF so raise and exit + raise EOFError('No more events to read on LFS.') + header = struct.unpack('Q', header_str) + header_len = int(header[0]) + event_str = self.file_handle.read(header_len) + + self._curr_event = event_str + + def record(self): + return self._curr_event + + +class _RecordReaderIterator(object): + """A iterator of record reader. + """ + + def __init__(self, filepath): + self._reader = _RecordReader(filepath=filepath) + + def __iter__(self): + return self + + def __next__(self): + try: + self._reader.get_next() + except EOFError: + raise StopIteration + return self._reader.record() + + +class RecordReader(object): + """Record reader of log file. + + Get one data or all data with this class. + """ + + def __init__(self, filepath, dir=None): + self._filepath = filepath + self._dir = dir + self._reader = _RecordReaderIterator(filepath) + + def get_next(self, update=False): + """Get next data in log file. + + Args: + update (boolean): Get writer again if `update` is True. + """ + if update: + self._reader = _RecordReaderIterator(self._filepath) + return self._reader.__next__() + + def get_all(self, update=False): + """Get all data in log file. + + Args: + update (boolean): Get writer again if `update` is True. + """ + if update: + self._reader = _RecordReaderIterator(self._filepath) + return list(self._reader) + + def get_remain(self, update=False): + """Get remain data in log file. + + Args: + update (boolean): Get writer again if `update` is True. + """ + if update: + return self.get_all() + results = [] + for item in self._reader: + results.append(item) + return results + + @property + def dir(self): + return self._dir + + @dir.setter + def dir(self, value): + self._dir = value diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bab744b75600618b2912de1ad551f15c5686580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/api.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/api.py new file mode 100644 index 0000000000000000000000000000000000000000..43bb08e2cee28203235e8c836833e694a6ccf263 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/api.py @@ -0,0 +1,486 @@ +#!/user/bin/env python +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import functools +import gzip +import json +import os +from io import BytesIO + +from flask import request + +from visualdl import LogReader +from visualdl.python.cache import MemCache +from visualdl.reader.graph_reader import GraphReader +from visualdl.server import lib +from visualdl.server.client_manager import ClientManager +from visualdl.server.log import logger + +error_retry_times = 3 +error_sleep_time = 2 # seconds + + +def gen_result(data=None, status=0, msg=''): + return {'status': status, 'msg': msg, 'data': data} + + +def result(mimetype='application/json', headers=None): + def decorator(func): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + data = None + status = 0 + msg = '' + try: + data = func(self, *args, **kwargs) + except Exception as e: + msg = '{}'.format(e) + status = -1 + if mimetype == 'application/json': + data = json.dumps(gen_result(data, status, msg)) + if callable(headers): + headers_output = headers(self) + else: + headers_output = headers + if headers is not None: + if 'content-encoding' in headers: + buf = BytesIO() + with gzip.GzipFile(mode='wb', fileobj=buf) as fp: + gzip_value = data.encode() + fp.write(gzip_value) + data = buf.getvalue() + return data, mimetype, headers_output + + return wrapper + + return decorator + + +def try_call(function, *args, **kwargs): + res = lib.retry(error_retry_times, function, error_sleep_time, *args, + **kwargs) + if not res: + logger.error("Internal server error. Retry later.") + return res + + +class Api(object): + def __init__(self, logdir, model, cache_timeout): + self._reader = LogReader(logdir) + self._graph_reader = GraphReader(logdir) + self._graph_reader.set_displayname(self._reader) + if model: + if 'vdlgraph' in model: + self._graph_reader.set_input_graph(model) + self._reader.model = model + self.model_name = os.path.basename(model) + else: + self.model_name = '' + self.graph_reader_client_manager = ClientManager(self._graph_reader) + # use a memory cache to reduce disk reading frequency. + cache = MemCache(timeout=cache_timeout) + self._cache = lib.cache_get(cache) + + def _get(self, key, func, *args, **kwargs): + return self._cache(key, func, self._reader, *args, **kwargs) + + def _get_with_retry(self, key, func, *args, **kwargs): + return self._cache(key, try_call, func, self._reader, *args, **kwargs) + + @result() + def components(self): + return self._get('data/components', lib.get_components) + + def component_tabs(self): + ''' + Get all component tabs supported by readers in Api. + ''' + tabs = set() + tabs.update(self._reader.component_tabs(update=True)) + tabs.update(self._graph_reader.component_tabs(update=True)) + return tabs + + @result() + def runs(self): + return self._get('data/runs', lib.get_runs) + + @result() + def graph_runs(self): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + return lib.get_graph_runs(graph_reader) + + @result() + def tags(self): + return self._get('data/tags', lib.get_tags) + + @result() + def logs(self): + return self._get('data/logs', lib.get_logs) + + @result() + def scalar_tags(self): + return self._get_with_retry('data/plugin/scalars/tags', + lib.get_scalar_tags) + + @result() + def scalars_tags(self): + return self._get_with_retry('data/plugin/multiscalars/tags', + lib.get_scalars_tags) + + @result() + def image_tags(self): + return self._get_with_retry('data/plugin/images/tags', + lib.get_image_tags) + + @result() + def text_tags(self): + return self._get_with_retry('data/plugin/text/tags', lib.get_text_tags) + + @result() + def audio_tags(self): + return self._get_with_retry('data/plugin/audio/tags', + lib.get_audio_tags) + + @result() + def embedding_tags(self): + return self._get_with_retry('data/plugin/embeddings/tags', + lib.get_embeddings_tags) + + @result() + def pr_curve_tags(self): + return self._get_with_retry('data/plugin/pr_curves/tags', + lib.get_pr_curve_tags) + + @result() + def roc_curve_tags(self): + return self._get_with_retry('data/plugin/roc_curves/tags', + lib.get_roc_curve_tags) + + @result() + def hparam_importance(self): + return self._get_with_retry('data/plugin/hparams/importance', + lib.get_hparam_importance) + + @result() + def hparam_indicator(self): + return self._get_with_retry('data/plugin/hparams/indicators', + lib.get_hparam_indicator) + + @result() + def hparam_list(self): + return self._get_with_retry('data/plugin/hparams/list', + lib.get_hparam_list) + + @result() + def hparam_metric(self, run, metric): + key = os.path.join('data/plugin/hparams/metric', run, metric) + return self._get_with_retry(key, lib.get_hparam_metric, run, metric) + + @result('text/csv') + def hparam_data(self, type='tsv'): + key = os.path.join('data/plugin/hparams/data', type) + return self._get_with_retry(key, lib.get_hparam_data, type) + + @result() + def scalar_list(self, run, tag): + key = os.path.join('data/plugin/scalars/scalars', run, tag) + return self._get_with_retry(key, lib.get_scalar, run, tag) + + @result() + def scalars_list(self, run, tag, sub_tag): + key = os.path.join('data/plugin/multiscalars/scalars', run, tag, + sub_tag) + return self._get_with_retry(key, lib.get_scalars, run, tag, sub_tag) + + @result('text/csv') + def scalar_data(self, run, tag, type='tsv'): + key = os.path.join('data/plugin/scalars/data', run, tag, type) + return self._get_with_retry(key, lib.get_scalar_data, run, tag, type) + + @result('text/csv') + def scalars_data(self, run, tag, sub_tag, type='tsv'): + key = os.path.join('data/plugin/multiscalars/data', run, tag, sub_tag, + type) + return self._get_with_retry(key, lib.get_scalars_data, run, tag, + sub_tag, type) + + @result() + def image_list(self, mode, tag): + key = os.path.join('data/plugin/images/images', mode, tag) + return self._get_with_retry(key, lib.get_image_tag_steps, mode, tag) + + @result('image/png') + def image_image(self, mode, tag, index=0): + index = int(index) + key = os.path.join('data/plugin/images/individualImage', mode, tag, + str(index)) + return self._get_with_retry(key, lib.get_individual_image, mode, tag, + index) + + @result() + def text_list(self, mode, tag): + key = os.path.join('data/plugin/text/text', mode, tag) + return self._get_with_retry(key, lib.get_text_tag_steps, mode, tag) + + @result('text/plain') + def text_text(self, mode, tag, index=0): + index = int(index) + key = os.path.join('data/plugin/text/individualText', mode, tag, + str(index)) + return self._get_with_retry(key, lib.get_individual_text, mode, tag, + index) + + @result() + def audio_list(self, run, tag): + key = os.path.join('data/plugin/audio/audio', run, tag) + return self._get_with_retry(key, lib.get_audio_tag_steps, run, tag) + + @result('audio/wav') + def audio_audio(self, run, tag, index=0): + index = int(index) + key = os.path.join('data/plugin/audio/individualAudio', run, tag, + str(index)) + return self._get_with_retry(key, lib.get_individual_audio, run, tag, + index) + + @result() + def embedding_embedding(self, + run, + tag='default', + reduction='pca', + dimension=2): + dimension = int(dimension) + key = os.path.join('data/plugin/embeddings/embeddings', run, + str(dimension), reduction) + return self._get_with_retry(key, lib.get_embeddings, run, tag, + reduction, dimension) + + @result() + def embedding_list(self): + return self._get_with_retry('data/plugin/embeddings/list', + lib.get_embeddings_list) + + @result('text/tab-separated-values') + def embedding_metadata(self, name): + key = os.path.join('data/plugin/embeddings/metadata', name) + return self._get_with_retry(key, lib.get_embedding_labels, name) + + @result('application/octet-stream') + def embedding_tensor(self, name): + key = os.path.join('data/plugin/embeddings/tensor', name) + return self._get_with_retry(key, lib.get_embedding_tensors, name) + + @result() + def histogram_tags(self): + return self._get_with_retry('data/plugin/histogram/tags', + lib.get_histogram_tags) + + @result() + def histogram_list(self, run, tag): + key = os.path.join('data/plugin/histogram/histogram', run, tag) + return self._get_with_retry(key, lib.get_histogram, run, tag) + + @result() + def pr_curves_pr_curve(self, run, tag): + key = os.path.join('data/plugin/pr_curves/pr_curve', run, tag) + return self._get_with_retry(key, lib.get_pr_curve, run, tag) + + @result() + def roc_curves_roc_curve(self, run, tag): + key = os.path.join('data/plugin/roc_curves/roc_curve', run, tag) + return self._get_with_retry(key, lib.get_roc_curve, run, tag) + + @result() + def pr_curves_steps(self, run): + key = os.path.join('data/plugin/pr_curves/steps', run) + return self._get_with_retry(key, lib.get_pr_curve_step, run) + + @result() + def roc_curves_steps(self, run): + key = os.path.join('data/plugin/roc_curves/steps', run) + return self._get_with_retry(key, lib.get_roc_curve_step, run) + + @result('application/octet-stream', lambda s: { + "Content-Disposition": 'attachment; filename="%s"' % s.model_name + } if len(s.model_name) else None) + def graph_static_graph(self): + key = os.path.join('data/plugin/graphs/static_graph') + return self._get_with_retry(key, lib.get_static_graph) + + @result() + def graph_graph(self, run, expand_all, refresh): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + if expand_all is not None: + if (expand_all.lower() == 'true'): + expand_all = True + else: + expand_all = False + else: + expand_all = False + if refresh is not None: + if (refresh.lower() == 'true'): + refresh = True + else: + refresh = False + else: + refresh = True + return lib.get_graph( + graph_reader, run, expand_all=expand_all, refresh=refresh) + + @result() + def graph_upload(self): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + files = request.files + if 'file' in files: + file_handle = request.files['file'] + if 'pdmodel' in file_handle.filename: + graph_reader.set_input_graph(file_handle.stream.read(), + 'pdmodel') + elif 'vdlgraph' in file_handle.filename: + graph_reader.set_input_graph(file_handle.stream.read(), + 'vdlgraph') + + @result() + def graph_manipulate(self, run, nodeid, expand, keep_state): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + if expand is not None: + if (expand.lower() == 'true'): + expand = True + else: + expand = False + else: + expand = False + if keep_state is not None: + if (keep_state.lower() == 'true'): + keep_state = True + else: + keep_state = False + else: + keep_state = False + return lib.get_graph(graph_reader, run, nodeid, expand, keep_state) + + @result() + def graph_search(self, run, nodeid, keep_state, is_node): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + if keep_state is not None: + if (keep_state.lower() == 'true'): + keep_state = True + else: + keep_state = False + else: + keep_state = False + + if is_node is not None: + if (is_node.lower() == 'true'): + is_node = True + else: + is_node = False + else: + is_node = False + return lib.get_graph_search(graph_reader, run, nodeid, keep_state, + is_node) + + @result() + def graph_get_all_nodes(self, run): + client_ip = request.remote_addr + graph_reader = self.graph_reader_client_manager.get_data(client_ip) + return lib.get_graph_all_nodes(graph_reader, run) + + +@result() +def get_component_tabs(*apis, vdl_args, request_args): + ''' + Get component tabs in all apis, so tabs can be presented according to existed data in frontend. + ''' + all_tabs = set() + if vdl_args.component_tabs: + return list(vdl_args.component_tabs) + if vdl_args.logdir: + for api in apis: + all_tabs.update(api('component_tabs', request_args)) + all_tabs.add('static_graph') + else: + return ['static_graph'] + return list(all_tabs) + + +def create_api_call(logdir, model, cache_timeout): + api = Api(logdir, model, cache_timeout) + routes = { + 'components': (api.components, []), + 'runs': (api.runs, []), + 'graph_runs': (api.graph_runs, []), + 'tags': (api.tags, []), + 'logs': (api.logs, []), + 'scalar/tags': (api.scalar_tags, []), + 'scalars/tags': (api.scalars_tags, []), + 'image/tags': (api.image_tags, []), + 'text/tags': (api.text_tags, []), + 'audio/tags': (api.audio_tags, []), + 'embedding/tags': (api.embedding_tags, []), + 'histogram/tags': (api.histogram_tags, []), + 'pr-curve/tags': (api.pr_curve_tags, []), + 'roc-curve/tags': (api.roc_curve_tags, []), + 'scalar/list': (api.scalar_list, ['run', 'tag']), + 'scalars/list': (api.scalars_list, ['run', 'tag', 'sub_tag']), + 'scalar/data': (api.scalar_data, ['run', 'tag', 'type']), + 'scalars/data': (api.scalars_data, ['run', 'tag', 'sub_tag', 'type']), + 'image/list': (api.image_list, ['run', 'tag']), + 'image/image': (api.image_image, ['run', 'tag', 'index']), + 'text/list': (api.text_list, ['run', 'tag']), + 'text/text': (api.text_text, ['run', 'tag', 'index']), + 'audio/list': (api.audio_list, ['run', 'tag']), + 'audio/audio': (api.audio_audio, ['run', 'tag', 'index']), + 'embedding/embedding': (api.embedding_embedding, + ['run', 'tag', 'reduction', 'dimension']), + 'embedding/list': (api.embedding_list, []), + 'embedding/tensor': (api.embedding_tensor, ['name']), + 'embedding/metadata': (api.embedding_metadata, ['name']), + 'histogram/list': (api.histogram_list, ['run', 'tag']), + 'graph/graph': (api.graph_graph, ['run', 'expand_all', 'refresh']), + 'graph/static_graph': (api.graph_static_graph, []), + 'graph/upload': (api.graph_upload, []), + 'graph/search': (api.graph_search, + ['run', 'nodeid', 'keep_state', 'is_node']), + 'graph/get_all_nodes': (api.graph_get_all_nodes, ['run']), + 'graph/manipulate': (api.graph_manipulate, + ['run', 'nodeid', 'expand', 'keep_state']), + 'pr-curve/list': (api.pr_curves_pr_curve, ['run', 'tag']), + 'roc-curve/list': (api.roc_curves_roc_curve, ['run', 'tag']), + 'pr-curve/steps': (api.pr_curves_steps, ['run']), + 'roc-curve/steps': (api.roc_curves_steps, ['run']), + 'hparams/importance': (api.hparam_importance, []), + 'hparams/data': (api.hparam_data, ['type']), + 'hparams/indicators': (api.hparam_indicator, []), + 'hparams/list': (api.hparam_list, []), + 'hparams/metric': (api.hparam_metric, ['run', 'metric']), + 'component_tabs': (api.component_tabs, []) + } + + def call(path: str, args): + route = routes.get(path) + if not route: + return json.dumps(gen_result( + status=1, msg='api not found')), 'application/json', None + method, call_arg_names = route + call_args = [args.get(name) for name in call_arg_names] + return method(*call_args) + + return call diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/app.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..c74219768ca38b6d566b04141a8c17562b1172ff --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/app.py @@ -0,0 +1,748 @@ +#!/user/bin/env python +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json +import multiprocessing +import os +import re +import signal +import sys +import threading +import time +import urllib +import webbrowser + +import requests +from flask import Flask +from flask import make_response +from flask import redirect +from flask import request +from flask import Response +from flask import send_file +from flask_babel import Babel + +import visualdl.server +from visualdl import __version__ +from visualdl.component.inference.fastdeploy_lib import get_start_arguments +from visualdl.component.profiler.profiler_server import create_profiler_api_call +from visualdl.server.api import create_api_call +from visualdl.server.api import get_component_tabs +from visualdl.server.args import parse_args +from visualdl.server.args import ParseArgs +from visualdl.server.log import info +from visualdl.server.serve import upload_to_dev +from visualdl.server.template import Template +from visualdl.utils import update_util + +SERVER_DIR = os.path.join(visualdl.ROOT, 'server') + +support_language = ["en", "zh"] +default_language = support_language[0] + +server_path = os.path.abspath(os.path.dirname(sys.argv[0])) +template_file_path = os.path.join(SERVER_DIR, "./dist") +mock_data_path = os.path.join(SERVER_DIR, "./mock_data/") + +check_live_path = '/alive' + + +def create_app(args): # noqa: C901 + # disable warning from flask + cli = sys.modules['flask.cli'] + cli.show_server_banner = lambda *x: None + + app = Flask('visualdl', static_folder=None) + app.logger.disabled = True + + # set static expires in a short time to reduce browser's memory usage. + app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30 + + app.config['BABEL_DEFAULT_LOCALE'] = default_language + + def get_locale(): + lang = args.language + if not lang or lang not in support_language: + lang = request.accept_languages.best_match(support_language) + return lang + + signal.signal( + signal.SIGINT, signal.SIG_DFL + ) # we add this to prevent SIGINT not work in multiprocess queue waiting + babel = Babel(app, locale_selector=get_locale) # noqa:F841 + if args.telemetry: + update_util.PbUpdater(args.product).start() + public_path = args.public_path + api_path = public_path + '/api' + # Babel api from flask_babel v3.0.0 + api_call = create_api_call(args.logdir, args.model, args.cache_timeout) + profiler_api_call = create_profiler_api_call(args.logdir) + if args.component_tabs is not None: + if 'x2paddle' in args.component_tabs: + try: + import x2paddle # noqa F401 + except Exception: + os.system('pip install x2paddle') + os.system('pip install onnx') + try: + import paddle2onnx # noqa F401 + except Exception: + os.system('pip install paddle2onnx') + from visualdl.component.inference.model_convert_server import create_model_convert_api_call + inference_api_call = create_model_convert_api_call() + + @app.route( + api_path + '/inference/', methods=["GET", "POST"]) + def serve_inference_api(method): + if request.method == 'POST': + data, mimetype, headers = inference_api_call( + method, request.form) + else: + data, mimetype, headers = inference_api_call( + method, request.args) + return make_response( + Response(data, mimetype=mimetype, headers=headers)) + + if 'fastdeploy_server' in args.component_tabs or 'fastdeploy_client' in args.component_tabs: + try: + import tritonclient # noqa F401 + except Exception: + os.system('pip install tritonclient[all]') + try: + import gradio # noqa F401 + except Exception: + os.system('pip install gradio==3.11.0') + from visualdl.component.inference.fastdeploy_server import create_fastdeploy_api_call + fastdeploy_api_call = create_fastdeploy_api_call() + + @app.route( + api_path + '/fastdeploy/', + methods=["GET", "POST"]) + def serve_fastdeploy_api(method): + if request.method == 'POST': + data, mimetype, headers = fastdeploy_api_call( + method, request.form) + else: + data, mimetype, headers = fastdeploy_api_call( + method, request.args) + return make_response( + Response(data, mimetype=mimetype, headers=headers)) + + @app.route( + api_path + '/fastdeploy/fastdeploy_client', + methods=["GET", "POST"]) + def serve_fastdeploy_create_fastdeploy_client(): + try: + if request.method == 'POST': + fastdeploy_api_call('create_fastdeploy_client', + request.form) + request_args = request.form + else: + fastdeploy_api_call('create_fastdeploy_client', + request.args) + request_args = request.args + except Exception as e: + error_msg = '{}'.format(e) + return make_response(error_msg) + args = urllib.parse.urlencode(request_args) + + if args: + return redirect( + api_path + + "/fastdeploy/fastdeploy_client/app?{}".format(args), + code=302) + return redirect( + api_path + "/fastdeploy/fastdeploy_client/app", code=302) + + @app.route( + api_path + "/fastdeploy/fastdeploy_client/", + methods=["GET", "POST"]) + def request_fastdeploy_create_fastdeploy_client_app(path: str): + ''' + Gradio app server url interface. We route urls for gradio app to gradio server. + + Args: + path(str): All resource path from gradio server. + + Returns: + Any thing from gradio server. + ''' + lang = 'zh' + if request.method == 'POST': + if request.mimetype == 'application/json': + request_args = request.json + else: + request_args = request.form.to_dict() + if 'data' in request_args: + lang = request_args['data'][-1] + request_args['lang'] = lang + elif 'lang' in request_args: + lang = request_args['lang'] + + port = fastdeploy_api_call('create_fastdeploy_client', + request_args) + else: + request_args = request.args.to_dict() + if 'data' in request_args: + lang = request_args['data'][-1] + request_args['lang'] = lang + elif 'lang' in request_args: + lang = request_args['lang'] + port = fastdeploy_api_call('create_fastdeploy_client', + request_args) + + if path == 'app': + proxy_url = request.url.replace( + request.host_url.rstrip('/') + api_path + + '/fastdeploy/fastdeploy_client/app', + 'http://localhost:{}/'.format(port)) + else: + proxy_url = request.url.replace( + request.host_url.rstrip('/') + api_path + + '/fastdeploy/fastdeploy_client/', + 'http://localhost:{}/'.format(port)) + resp = requests.request( + method=request.method, + url=proxy_url, + headers={ + key: value + for (key, value) in request.headers if key != 'Host' + }, + data=request.get_data(), + cookies=request.cookies, + allow_redirects=False) + if path == 'app': + content = resp.content + if request_args and 'server_id' in request_args: + server_id = request_args.get('server_id') + start_args = get_start_arguments(server_id) + http_port = start_args.get('http-port', '') + metrics_port = start_args.get('metrics-port', '') + model_name = start_args.get('default_model_name', '') + content = content.decode() + try: + if request_args.get('lang', 'zh') == 'en': + server_addr_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "server ip", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not server_addr_match or server_addr_match.group( + 0).count('"label"') >= 2: + server_addr_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "server ip", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + default_server_addr = server_addr_match.group( + 0) + if '"value": ""' in default_server_addr: + cur_server_addr = default_server_addr.replace( + '"value": ""', '"value": "localhost"') + else: + cur_server_addr = default_server_addr.replace( + '"value":""', '"value": "localhost"') + content = content.replace( + default_server_addr, cur_server_addr) + http_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "server port", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not http_port_match or http_port_match.group( + 0).count('"label"') >= 2: + http_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "server port", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + default_http_port = http_port_match.group(0) + + if '"value": ""' in default_http_port: + cur_http_port = default_http_port.replace( + '"value": ""', + '"value": "{}"'.format(http_port)) + else: + cur_http_port = default_http_port.replace( + '"value":""', + '"value": "{}"'.format(http_port)) + if http_port: + content = content.replace( + default_http_port, cur_http_port) + metrics_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "metrics port", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not metrics_port_match or metrics_port_match.group( + 0).count('"label"') >= 2: + metrics_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "metrics port", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + default_metrics_port = metrics_port_match.group( + 0) + if '"value": ""' in default_metrics_port: + cur_metrics_port = default_metrics_port.replace( + '"value": ""', + '"value": "{}"'.format(metrics_port)) + else: + cur_metrics_port = default_metrics_port.replace( + '"value":""', + '"value": "{}"'.format(metrics_port)) + if metrics_port: + content = content.replace( + default_metrics_port, cur_metrics_port) + model_name_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "model name", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_name_match or model_name_match.group( + 0).count('"label"') >= 2: + model_name_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "model name", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + default_model_name = model_name_match.group(0) + if '"value": ""' in default_model_name: + cur_model_name = default_model_name.replace( + '"value": ""', + '"value": "{}"'.format(model_name)) + else: + cur_model_name = default_model_name.replace( + '"value":""', + '"value": "{}"'.format(model_name)) + if model_name: + content = content.replace( + default_model_name, cur_model_name) + model_version_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "model version", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_version_match or model_version_match.group( + 0).count('"label"') >= 2: + model_version_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "model version", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + default_model_version = model_version_match.group( + 0) + if '"value": ""' in default_model_version: + cur_model_version = default_model_version.replace( + '"value": ""', + '"value": "{}"'.format('1')) + else: + cur_model_version = default_model_version.replace( + '"value":""', + '"value": "{}"'.format('1')) + content = content.replace( + default_model_version, cur_model_version) + + else: + server_addr_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps("服务ip", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not server_addr_match or server_addr_match.group( + 0).count('"label"') >= 2: + server_addr_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "服务ip", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not server_addr_match: + server_addr_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}' + .format( + json.dumps( + "服务ip", ensure_ascii=False + ).replace('\\', + '\\\\')), content) + if not server_addr_match or server_addr_match.group( + 0).count('"label"') >= 2: + server_addr_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}' + .format( + json.dumps( + "服务ip", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + + default_server_addr = server_addr_match.group( + 0) + if '"value": ""' in default_server_addr: + cur_server_addr = default_server_addr.replace( + '"value": ""', '"value": "localhost"') + else: + cur_server_addr = default_server_addr.replace( + '"value":""', '"value": "localhost"') + content = content.replace( + default_server_addr, cur_server_addr) + http_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "推理服务端口", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not http_port_match or http_port_match.group( + 0).count('"label"') >= 2: + http_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "推理服务端口", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not http_port_match: + http_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}' + .format( + json.dumps( + "推理服务端口", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + if not http_port_match or http_port_match.group( + 0).count('"label"') >= 2: + http_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}' + .format( + json.dumps( + "推理服务端口", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + default_http_port = http_port_match.group(0) + + if '"value": ""' in default_http_port: + cur_http_port = default_http_port.replace( + '"value": ""', + '"value": "{}"'.format(http_port)) + else: + cur_http_port = default_http_port.replace( + '"value":""', + '"value": "{}"'.format(http_port)) + if http_port: + content = content.replace( + default_http_port, cur_http_port) + metrics_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps( + "性能服务端口", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not metrics_port_match or metrics_port_match.group( + 0).count('"label"') >= 2: + metrics_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "性能服务端口", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not metrics_port_match: + metrics_port_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}' + .format( + json.dumps( + "性能服务端口", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + if not metrics_port_match or metrics_port_match.group( + 0).count('"label"') >= 2: + metrics_port_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}' + .format( + json.dumps( + "性能服务端口", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + default_metrics_port = metrics_port_match.group( + 0) + if '"value": ""' in default_metrics_port: + cur_metrics_port = default_metrics_port.replace( + '"value": ""', + '"value": "{}"'.format(metrics_port)) + else: + cur_metrics_port = default_metrics_port.replace( + '"value":""', + '"value": "{}"'.format(metrics_port)) + if metrics_port: + content = content.replace( + default_metrics_port, cur_metrics_port) + model_name_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps("模型名称", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_name_match or model_name_match.group( + 0).count('"label"') >= 2: + model_name_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "模型名称", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_name_match: + model_name_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}' + .format( + json.dumps( + "模型名称", ensure_ascii=False + ).replace('\\', + '\\\\')), content) + if not model_name_match or model_name_match.group( + 0).count('"label"') >= 2: + model_name_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}' + .format( + json.dumps( + "模型名称", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + default_model_name = model_name_match.group(0) + if '"value": ""' in default_model_name: + cur_model_name = default_model_name.replace( + '"value": ""', + '"value": "{}"'.format(model_name)) + else: + cur_model_name = default_model_name.replace( + '"value":""', + '"value": "{}"'.format(model_name)) + if model_name: + content = content.replace( + default_model_name, cur_model_name) + model_version_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}'. + format( + json.dumps("模型版本", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_version_match or model_version_match.group( + 0).count('"label"') >= 2: + model_version_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}'. + format( + json.dumps( + "模型版本", + ensure_ascii=True).replace( + '\\', '\\\\')), content) + if not model_version_match: + model_version_match = re.search( + '"label":\\s*{}.*?"value":\\s*"".*?}}' + .format( + json.dumps( + "模型版本", ensure_ascii=False + ).replace('\\', + '\\\\')), content) + if not model_version_match or model_version_match.group( + 0).count('"label"') >= 2: + model_version_match = re.search( + '"value":\\s*"".*?"label":\\s*{}.*?}}' + .format( + json.dumps( + "模型版本", + ensure_ascii=False). + replace('\\', + '\\\\')), content) + + default_model_version = model_version_match.group( + 0) + if '"value": ""' in default_model_version: + cur_model_version = default_model_version.replace( + '"value": ""', + '"value": "{}"'.format('1')) + else: + cur_model_version = default_model_version.replace( + '"value":""', + '"value": "{}"'.format('1')) + content = content.replace( + default_model_version, cur_model_version) + except Exception: + pass + finally: + content = content.encode() + else: + content = resp.content + headers = [(name, value) + for (name, value) in resp.raw.headers.items()] + response = Response(content, resp.status_code, headers) + return response + + def append_query_string(url): + query_string = '' + if request.query_string: + query_string = '?' + request.query_string.decode() + return url + query_string + + if not args.api_only: + + template = Template( + os.path.join(server_path, template_file_path), + PUBLIC_PATH=public_path, + BASE_URI=public_path, + API_URL=api_path, + TELEMETRY_ID='63a600296f8a71f576c4806376a9245b' + if args.telemetry else '', + THEME='' if args.theme is None else args.theme) + + @app.route('/') + def base(): + return redirect(append_query_string(public_path), code=302) + + @app.route('/favicon.ico') + def favicon(): + icon = os.path.join(template_file_path, 'favicon.ico') + if os.path.exists(icon): + return send_file(icon) + return 'file not found', 404 + + @app.route(public_path + '/') + def index(): + return redirect( + append_query_string(public_path + '/index'), code=302) + + @app.route(public_path + '/') + def serve_static(filename): + is_not_page_request = re.search(r'\..+$', filename) + response = template.render( + filename if is_not_page_request else 'index.html') + if not is_not_page_request: + response.set_cookie( + 'vdl_lng', + get_locale(), + path='/', + samesite='Strict', + secure=False, + httponly=False) + return response + + @app.route(api_path + '/', methods=["GET", "POST"]) + def serve_api(method): + data, mimetype, headers = api_call(method, request.args) + return make_response( + Response(data, mimetype=mimetype, headers=headers)) + + @app.route(api_path + '/profiler/', methods=["GET", "POST"]) + def serve_profiler_api(method): + data, mimetype, headers = profiler_api_call(method, request.args) + return make_response( + Response(data, mimetype=mimetype, headers=headers)) + + @app.route(api_path + '/component_tabs') + def component_tabs(): + data, mimetype, headers = get_component_tabs( + api_call, + profiler_api_call, + vdl_args=args, + request_args=request.args) + return make_response( + Response(data, mimetype=mimetype, headers=headers)) + + @app.route(check_live_path) + def check_live(): + return '', 204 + + return app + + +def wait_until_live(args: ParseArgs): + url = 'http://{host}:{port}'.format(host=args.host, port=args.port) + while True: + try: + requests.get(url + check_live_path) + info('Running VisualDL at http://%s:%s/ (Press CTRL+C to quit)', + args.host, args.port) + + if args.host == 'localhost': + info( + 'Serving VisualDL on localhost; to expose to the network, use a proxy or pass --host 0.0.0.0' + ) + + if args.api_only: + info('Running in API mode, only %s/* will be served.', + args.public_path + '/api') + + break + except Exception: + time.sleep(0.5) + if not args.api_only and args.open_browser: + webbrowser.open(url + args.public_path) + + +def _run(args): + args = ParseArgs(**args) + os.system('') + info('\033[1;33mVisualDL %s\033[0m', __version__) + app = create_app(args) + threading.Thread(target=wait_until_live, args=(args, )).start() + app.run(debug=False, host=args.host, port=args.port, threaded=False) + + +def run(logdir=None, **options): + args = {'logdir': logdir} + args.update(options) + p = multiprocessing.Process(target=_run, args=(args, )) + p.start() + return p.pid + + +def main(): + args = parse_args() + if args.get('dest') == 'service': + if args.get('behavior') == 'upload': + upload_to_dev(args.get('logdir'), args.get('model')) + else: + _run(args) + + +if __name__ == '__main__': + main() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/args.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/args.py new file mode 100644 index 0000000000000000000000000000000000000000..71f97afb10edd5c0e5f3d1ad0be6fb2bb67f3cab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/args.py @@ -0,0 +1,237 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import socket +import sys +from argparse import ArgumentParser + +from visualdl import __version__ +from visualdl.server.log import init_logger +from visualdl.server.log import logger + +default_host = None +default_port = 8040 +default_cache_timeout = 20 +default_public_path = '/app' +default_product = 'normal' + +support_themes = ['light', 'dark'] + + +class DefaultArgs(object): + def __init__(self, args): + self.logdir = args.get('logdir') + self.host = args.get('host', default_host) + self.port = args.get('port', default_port) + self.cache_timeout = args.get('cache_timeout', default_cache_timeout) + self.language = args.get('language') + self.public_path = args.get('public_path') + self.api_only = args.get('api_only', False) + self.open_browser = args.get('open_browser', False) + self.model = args.get('model', '') + self.product = args.get('product', default_product) + self.telemetry = args.get('telemetry', True) + self.theme = args.get('theme', None) + self.dest = args.get('dest', '') + self.behavior = args.get('behavior', '') + self.component_tabs = args.get('component_tabs', None) + + +def get_host(host=default_host, port=default_port): + if not host: + host = socket.getfqdn() + try: + socket.create_connection((host, port), timeout=1) + except socket.error: + host = 'localhost' + return host + + +def validate_args(args): + # if not in API mode, public path cannot be set to root path + if not args.api_only and args.public_path == '/': + logger.error('Public path cannot be set to root path.') + sys.exit(-1) + + # public path must start with `/` + if args.public_path is not None and not args.public_path.startswith('/'): + logger.error('Public path should always start with a `/`.') + sys.exit(-1) + + # theme not support + if args.theme is not None and args.theme not in support_themes: + logger.error('Theme {} is not support.'.format(args.theme)) + sys.exit(-1) + + # input unsupported component tab name + supported_tabs = [ + 'scalar', 'image', 'text', 'embeddings', 'audio', 'histogram', + 'hyper_parameters', 'static_graph', 'dynamic_graph', 'pr_curve', + 'roc_curve', 'profiler', 'x2paddle', 'fastdeploy_server', + 'fastdeploy_client' + ] + if args.component_tabs is not None: + for component_tab in args.component_tabs: + if component_tab not in supported_tabs: + logger.error( + 'Component_tab {} is not support. Please choose tabs in {}' + .format(component_tab, supported_tabs)) + sys.exit(-1) + + +def format_args(args): + # set default public path according to API mode option + if args.public_path is None: + args.public_path = '' if args.api_only else default_public_path + else: + args.public_path = args.public_path.rstrip('/') + + # don't open browser in API mode + if args.api_only: + args.open_browser = False + + # set host to localhost if host is not set + if not args.host: + args.host = get_host(args.host, args.port) + + return args + + +class ParseArgs(object): + def __init__(self, **kwargs): + args = DefaultArgs(kwargs) + validate_args(args) + args = format_args(args) + + self.logdir = args.logdir + self.host = args.host + self.port = args.port + self.cache_timeout = args.cache_timeout + self.language = args.language + self.public_path = args.public_path + self.api_only = args.api_only + self.open_browser = args.open_browser + self.model = args.model + self.product = args.product + self.telemetry = args.telemetry + self.theme = args.theme + self.dest = args.dest + self.behavior = args.behavior + self.component_tabs = args.component_tabs + + +def parse_args(): + """ + :return: + """ + parser = ArgumentParser( + prog="VisualDL", + description="VisualDL, a tool to visualize deep learning.", + epilog="For more information: https://github.com/PaddlePaddle/VisualDL" + ) + + parser.add_argument( + "--logdir", action="store", nargs="+", help="log file directory") + + parser.add_argument( + "--component_tabs", + action="store", + nargs="+", + help="component tabs presented in html page.") + + parser.add_argument( + "-p", + "--port", + type=int, + default=default_port, + action="store", + help="port of %(prog)s board") + parser.add_argument( + "-t", + "--host", + type=str, + default=default_host, + action="store", + help="bind %(prog)s board to ip/host") + parser.add_argument( + "--model", + type=str, + action="store", + default="", + help="model file path") + parser.add_argument( + "--cache-timeout", + action="store", + dest="cache_timeout", + type=float, + default=default_cache_timeout, + help="memory cache timeout duration in seconds (default: %(default)s)", + ) + parser.add_argument( + "-L", + "--language", + type=str, + action="store", + default=None, + help="specify the default language") + parser.add_argument( + "--public-path", + type=str, + action="store", + dest="public_path", + default=None, + help="set public path") + parser.add_argument( + "--api-only", + action="store_true", + dest="api_only", + default=False, + help="serve api only") + parser.add_argument( + "--verbose", + "-v", + action="count", + default=0, + help="set log level, use -vvv... to get more information") + parser.add_argument( + "--version", + action="version", + version="%(prog)s {}".format(__version__)) + parser.add_argument( + "--product", + type=str, + action="store", + default=default_product, + help="specify the product") + parser.add_argument( + "--disable-telemetry", + action="store_false", + dest="telemetry", + default=True, + help="disable telemetry") + parser.add_argument( + "--theme", + action="store", + dest="theme", + default=None, + choices=support_themes, + help="set theme") + parser.add_argument('dest', nargs='?', help='set destination for log') + parser.add_argument("behavior", nargs='?') + + args = parser.parse_args() + + init_logger(args.verbose) + + return vars(args) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/client_manager.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/client_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..25fd964ccb489126a722c1c427235955057a2226 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/client_manager.py @@ -0,0 +1,31 @@ +# Copyright (c) 2022 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import copy + + +class ClientManager: + ''' + This class manages data with status like graph. For data with status but managed by backend, + we should prevent data for different clients interfere with each other. + ''' + + def __init__(self, data): + self._proto_data = data + self.ip_data_map = {} + + def get_data(self, ip): + if ip not in self.ip_data_map: + self.ip_data_map[ip] = copy.deepcopy(self._proto_data) + return self.ip_data_map[ip] diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/data_manager.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/data_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..87599c78a8533d63d3253969a8d67ac025a37892 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/data_manager.py @@ -0,0 +1,529 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import collections +import random +import threading + +DEFAULT_PLUGIN_MAXSIZE = { + "scalar": 1000, + "image": 10, + "histogram": 100, + "embeddings": 50000000, + "audio": 10, + "pr_curve": 300, + "roc_curve": 300, + "meta_data": 100, + "text": 10, + "hyper_parameters": 10000 +} + + +def add_sub_tag(tag, sub_tag): + return tag.replace('%', '_') + '_' + sub_tag + + +class Reservoir(object): + """A map-to-arrays dict, with deterministic Reservoir Sampling. + + Store each reservoir bucket by key, and each bucket is a list sampling + with reservoir algorithm. + """ + + def __init__(self, max_size, seed=0): + """Creates a new reservoir. + + Args: + max_size: The number of values to keep in the reservoir for each tag, + if max_size is zero, all values will be kept in bucket. + seed: The seed to initialize a random.Random(). + num_item_index: The index of data to add. + + Raises: + ValueError: If max_size is not a nonnegative integer. + """ + if max_size < 0 or max_size != round(max_size): + raise ValueError("Max_size must be nonnegative integer.") + self._max_size = max_size + self._buckets = collections.defaultdict(lambda: _ReservoirBucket( + max_size=self._max_size, random_instance=random.Random(seed))) + self._mutex = threading.Lock() + + @property + def keys(self): + """Return all keys in self._buckets. + + Returns: + All keys in reservoir buckets. + :return: + """ + with self._mutex: + return list(self._buckets.keys()) + + def _exist_in_keys(self, key): + """Determine if key exists. + + Args: + key: Key to determine if exists. + + Returns: + True if key exists in buckets.keys, otherwise False. + """ + return True if key in self._buckets.keys() else False + + def exist_in_keys(self, run, tag): + """Determine if run_tag exists. + + For usage habits of VisualDL, actually call self._exist_in_keys() + + Args: + run: Identity of one tablet. + tag: Identity of one record in tablet. + + Returns: + True if run_tag exists in buckets.keys, otherwise False. + """ + key = run + "/" + tag + return self._exist_in_keys(key) + + def _get_num_items_index(self, key): + keys = self.keys + if key not in keys: + raise KeyError("Key %s not in buckets.keys()" % key) + return self._buckets[key].num_items_index + + def get_num_items_index(self, run, tag): + key = run + "/" + tag + return self._get_num_items_index(key) + + def _get_items(self, key): + """Get items with tag "key" + + Args: + key: Key to finding bucket in reservoir buckets. + + Returns: + One bucket in reservoir buckets by key. + """ + keys = self.keys + with self._mutex: + if key not in keys: + raise KeyError("Key %s not in buckets.keys()" % key) + return self._buckets[key].items + + def get_items(self, run, tag): + """Get items with tag 'run_tag' + + For usage habits of VisualDL, actually call self._get_items() + + Args: + run: Identity of one tablet. + tag: Identity of one record in tablet. + + Returns: + One bucket in reservoir buckets by run and tag. + """ + key = run + "/" + tag + return self._get_items(key) + + def _add_item(self, key, item): + """Add a new item to reservoir buckets with given tag as key. + + If bucket with key has not yet reached full size, each item will be + added. + + If bucket with key is full, each item will be added with same + probability. + + Add new item to buckets will always valid because self._buckets is a + collection.defaultdict. + + Args: + key: Tag of one bucket to add new item. + item: New item to add to bucket. + """ + with self._mutex: + self._buckets[key].add_item(item) + + def _add_scalar_item(self, key, item): + """Add a new scalar item to reservoir buckets with given tag as key. + + If bucket with key has not yet reached full size, each item will be + added. + + If bucket with key is full, each item will be added with same + probability. + + Add new item to buckets will always valid because self._buckets is a + collection.defaultdict. + + Args: + key: Tag of one bucket to add new item. + item: New item to add to bucket. + """ + with self._mutex: + self._buckets[key].add_scalar_item(item) + + def _add_scalars_item(self, key, item): + """Add a new scalar item to reservoir buckets with given tag as key. + + If bucket with key has not yet reached full size, each item will be + added. + + If bucket with key is full, each item will be added with same + probability. + + Add new item to buckets will always valid because self._buckets is a + collection.defaultdict. + + Args: + key: Tag of one bucket to add new item. + item: New item to add to bucket. + """ + with self._mutex: + self._buckets[key].add_scalars_item(item) + + def add_item(self, run, tag, item): + """Add a new item to reservoir buckets with given tag as key. + + For usage habits of VisualDL, actually call self._add_items() + + Args: + run: Identity of one tablet. + tag: Identity of one record in tablet. + item: New item to add to bucket. + """ + key = run + "/" + tag + self._add_item(key, item) + + def add_scalar_item(self, run, tag, item): + """Add a new scalar item to reservoir buckets with given tag as key. + + For usage habits of VisualDL, actually call self._add_items() + + Args: + run: Identity of one tablet. + tag: Identity of one record in tablet. + item: New item to add to bucket. + """ + if item.WhichOneof("one_value") == "value": + key = run + "/" + tag + self._add_scalar_item(key, item) + elif item.WhichOneof("one_value") == "tag_value": + key = run + "/" + add_sub_tag(tag, item.tag_value.tag) + "/" + tag + self._add_scalars_item(key, item) + else: + raise ValueError("Not scalar type:" + item.WhichOneof("one_value")) + + def _cut_tail(self, key): + with self._mutex: + self._buckets[key].cut_tail() + + def cut_tail(self, run, tag): + """Pop the last item in reservoir buckets. + + Sometimes the tail of the retrieved data is abnormal 0. This + method is used to handle this problem. + + Args: + run: Identity of one tablet. + tag: Identity of one record in tablet. + """ + key = run + "/" + tag + self._cut_tail(key) + + +class _ReservoirBucket(object): + """Data manager for sampling data, use reservoir sampling. + """ + + def __init__(self, max_size, random_instance=None): + """Create a _ReservoirBucket instance. + + Args: + max_size: The maximum size of reservoir bucket. If max_size is + zero, the bucket has unbounded size. + random_instance: The random number generator. If not specified, + default to random.Random(0) + num_item_index: The index of data to add. + + Raises: + ValueError: If args max_size is not a nonnegative integer. + """ + if max_size < 0 or max_size != round(max_size): + raise ValueError("Max_size must be nonnegative integer.") + self._max_size = max_size + self._random = random_instance if random_instance is not None else \ + random.Random(0) + self._items = [] + self._mutex = threading.Lock() + self._num_items_index = 0 + + self.max_scalar = None + self.min_scalar = None + + # improve performance when data is monotonous + self._last_special = False + + def add_item(self, item): + """ Add an item to bucket, replacing an old item with probability. + + Use reservoir sampling to add a new item to sampling bucket, + each item in a steam has same probability stay in the bucket. + + Args: + item: The item to add to reservoir bucket. + """ + with self._mutex: + if len(self._items) < self._max_size or self._max_size == 0: + self._items.append(item) + else: + r = self._random.randint(1, self._num_items_index) + if r < self._max_size: + self._items.pop(r) + self._items.append(item) + else: + self._items[-1] = item + self._num_items_index += 1 + + def add_scalar_item(self, item): + """ Add an scalar item to bucket, replacing an old item with probability. + + Use reservoir sampling to add a new item to sampling bucket, + each item in a steam has same probability stay in the bucket. + + use _last_special mark to improve performance when data is monotonous + + Args: + item: The item to add to reservoir bucket. + """ + with self._mutex: + # save max and min value + if not self.max_scalar or self.max_scalar.value < item.value: + self.max_scalar = item + if not self.min_scalar or self.min_scalar.value > item.value: + self.min_scalar = item + + if len(self._items) < self._max_size or self._max_size == 0: + # capacity is valid, append directly + self._items.append(item) + else: + if self._last_special: + if self._items[-1].id == self.min_scalar.id or self._items[ + -1].id == self.max_scalar.id: + # data is not monotonous, set special to False + self._last_special = False + else: + # data is monotonous, drop last item by reservoir algorithm + r = self._random.randint(1, self._num_items_index) + if r >= self._max_size: + self._items.pop(-1) + self._items.append(item) + self._num_items_index += 1 + return + if item.id == self.min_scalar.id or item.id == self.max_scalar.id: + # this item is max or min, should be reserved + r = self._random.randint(1, self._max_size - 1) + self._last_special = True + else: + # drop by reservoir algorithm + r = self._random.randint(1, self._num_items_index) + self._last_special = False + if r < self._max_size: + if self._items[r].id == self.min_scalar.id or self._items[ + r].id == self.max_scalar.id: + # reserve max and min point + if r - 1 > 0: + r = r - 1 + elif r + 1 < self._max_size: + r = r + 1 + self._items.pop(r) + self._items.append(item) + + self._num_items_index += 1 + + def add_scalars_item(self, item): + """ Add an scalar item to bucket, replacing an old item with probability. + + Use reservoir sampling to add a new item to sampling bucket, + each item in a steam has same probability stay in the bucket. + + Args: + item: The item to add to reservoir bucket. + """ + with self._mutex: + # save max and min value + if not self.max_scalar or self.max_scalar.tag_value.value < item.tag_value.value: + self.max_scalar = item + if not self.min_scalar or self.min_scalar.tag_value.value > item.tag_value.value: + self.min_scalar = item + + if len(self._items) < self._max_size or self._max_size == 0: + # capacity is valid, append directly + self._items.append(item) + else: + if self._last_special: + if self._items[-1].id == self.min_scalar.id or self._items[ + -1].id == self.max_scalar.id: + # data is not monotic, set special to False + self._last_special = False + else: + # data is monotic, drop last item by reservoir algorithm + r = self._random.randint(1, self._num_items_index) + if r >= self._max_size: + self._items.pop(-1) + self._items.append(item) + self._num_items_index += 1 + return + if item.id == self.min_scalar.id or item.id == self.max_scalar.id: + # this item is max or min, should be reserved + r = self._random.randint(1, self._max_size - 1) + self._last_special = True + else: + # drop by reservoir algorithm + r = self._random.randint(1, self._num_items_index) + self._last_special = False + if r < self._max_size: + if self._items[r].id == self.min_scalar.id or self._items[ + r].id == self.max_scalar.id: + # reserve max and min point + if r - 1 > 0: + r = r - 1 + elif r + 1 < self._max_size: + r = r + 1 + self._items.pop(r) + self._items.append(item) + else: + self._items[-1] = item + + self._num_items_index += 1 + + @property + def items(self): + """Get self._items + + Returns: + All items. + """ + with self._mutex: + return self._items + + @property + def num_items_index(self): + with self._mutex: + return self._num_items_index + + def cut_tail(self): + """Pop the last item in reservoir buckets. + + Sometimes the tail of the retrieved data is abnormal 0. This + method is used to handle this problem. + """ + with self._mutex: + self._items.pop() + self._num_items_index -= 1 + + +class DataManager(object): + """Data manager for all plugin. + """ + + def __init__(self): + """Create a data manager for all plugin. + + All kinds of plugin has own reservoir, stored in a dict with plugin + name as key. + + """ + self._reservoirs = { + "scalar": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["scalar"]), + "histogram": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["histogram"]), + "image": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["image"]), + "embeddings": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["embeddings"]), + "audio": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["audio"]), + "pr_curve": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["pr_curve"]), + "roc_curve": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["roc_curve"]), + "meta_data": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["meta_data"]), + "text": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["text"]), + "hyper_parameters": + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE["hyper_parameters"]) + } + self._mutex = threading.Lock() + + def add_reservoir(self, plugin): + """Add reservoir to reservoirs. + + Every reservoir is attached to one plugin. + + Args: + plugin: Key to get one reservoir bucket for one specified plugin. + """ + with self._mutex: + if plugin not in self._reservoirs.keys(): + self._reservoirs.update({ + plugin: + Reservoir(max_size=DEFAULT_PLUGIN_MAXSIZE[plugin]) + }) + + def get_reservoir(self, plugin): + """Get reservoir by plugin as key. + + Args: + plugin: Key to get one reservoir bucket for one specified plugin. + + Returns: + Reservoir bucket for plugin. + """ + with self._mutex: + if plugin not in self._reservoirs.keys(): + raise KeyError("Key %s not in reservoirs." % plugin) + return self._reservoirs[plugin] + + def add_item(self, plugin, run, tag, item): + """Add item to one plugin reservoir bucket. + + Use 'run', 'tag' for usage habits of VisualDL. + + Args: + plugin: Key to get one reservoir bucket. + run: Each tablet has different 'run'. + tag: Tag will be used to generate paths of tablets. + item: The item to add to reservoir bucket. + """ + with self._mutex: + if 'scalar' == plugin or 'scalars' == plugin: # We adapt scalars data to be saved in scalar reservoir. + self._reservoirs['scalar'].add_scalar_item(run, tag, item) + else: + self._reservoirs[plugin].add_item(run, tag, item) + + def get_keys(self): + """Get all plugin buckets name. + + Returns: + All plugin keys. + """ + with self._mutex: + return self._reservoirs.keys() + + +default_data_manager = DataManager() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.js new file mode 100644 index 0000000000000000000000000000000000000000..79db07993d9e1b9c1bbb4ea310ee28b8d42b3cd1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.js @@ -0,0 +1 @@ +const env = globalThis.__snowpack_env__ || {}; export const MOCK=env["MOCK"],MODE=env["MODE"],NODE_ENV=env["NODE_ENV"],SNOWPACK_PUBLIC_API_TOKEN_KEY=env["SNOWPACK_PUBLIC_API_TOKEN_KEY"],SNOWPACK_PUBLIC_API_URL=env["SNOWPACK_PUBLIC_API_URL"],SNOWPACK_PUBLIC_BASE_URI=env["SNOWPACK_PUBLIC_BASE_URI"],SNOWPACK_PUBLIC_DEFAULT_LANGUAGE=env["SNOWPACK_PUBLIC_DEFAULT_LANGUAGE"],SNOWPACK_PUBLIC_LANGUAGES=env["SNOWPACK_PUBLIC_LANGUAGES"],SNOWPACK_PUBLIC_PATH=env["SNOWPACK_PUBLIC_PATH"],SNOWPACK_PUBLIC_TELEMETRY_ID=env["SNOWPACK_PUBLIC_TELEMETRY_ID"],SNOWPACK_PUBLIC_THEME=env["SNOWPACK_PUBLIC_THEME"],SSR=env["SSR"]; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.local.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.local.js new file mode 100644 index 0000000000000000000000000000000000000000..65697ca7469c00eb29052c43966ea134f891c0ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/env.local.js @@ -0,0 +1 @@ +export const MOCK="",SNOWPACK_PUBLIC_API_TOKEN_KEY="{{API_TOKEN_KEY}}",SNOWPACK_PUBLIC_API_URL="{{API_URL}}",SNOWPACK_PUBLIC_BASE_URI="{{BASE_URI}}",SNOWPACK_PUBLIC_DEFAULT_LANGUAGE="en",SNOWPACK_PUBLIC_LANGUAGES="en,zh",SNOWPACK_PUBLIC_PATH="{{PUBLIC_PATH}}",SNOWPACK_PUBLIC_TELEMETRY_ID="{{TELEMETRY_ID}}",SNOWPACK_PUBLIC_THEME="{{THEME}}",MODE="production",NODE_ENV="production",SSR=!1; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/components/a.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/components/a.js new file mode 100644 index 0000000000000000000000000000000000000000..818a4c681d4b8950c34e1334c5dbc30af1bd8778 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/components/a.js @@ -0,0 +1 @@ +function _extends(){_extends=Object.assign||function(target){for(var i=1;iimport(`./components/${o}.js`); diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/a.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/a.svg new file mode 100644 index 0000000000000000000000000000000000000000..17c7925fa1900182fb9637a92e2fa3d837ab1751 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/a.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/audio.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/audio.svg new file mode 100644 index 0000000000000000000000000000000000000000..92b1abadd34cb9a7e969335b769dd12d4f8b6e46 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/audio.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/check-mark.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/check-mark.svg new file mode 100644 index 0000000000000000000000000000000000000000..fab834ac7b463641619c926628aaa5e0d07b482c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/check-mark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-down.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-down.svg new file mode 100644 index 0000000000000000000000000000000000000000..263a8e70d971907597d19c5cb9ce99f88eb287a5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-left.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-left.svg new file mode 100644 index 0000000000000000000000000000000000000000..8137cd4efc4c3be4ad19438e9243f2b6ea486f74 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-right.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-right.svg new file mode 100644 index 0000000000000000000000000000000000000000..87493b1b45e25eda39a68db1f4ac4822d3356f0b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-up.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-up.svg new file mode 100644 index 0000000000000000000000000000000000000000..c96c2bb9e12bdd348dc4a5896d7dba829f5b017e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/chevron-up.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/close.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/close.svg new file mode 100644 index 0000000000000000000000000000000000000000..8bea65f5b03256f8232ffd8f5d9d5587d34a350c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/close.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultLeft.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultLeft.svg new file mode 100644 index 0000000000000000000000000000000000000000..3992cbbe87001b1382973eaabe58812c77bba7bc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultLeft.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultRight.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultRight.svg new file mode 100644 index 0000000000000000000000000000000000000000..5349af540d0df4038fe615bcbd4e2682ebe6b9df --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/defaultRight.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dimension.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dimension.svg new file mode 100644 index 0000000000000000000000000000000000000000..208f54ee3a4cc46d4f948fb3e2e29d9dd819a3e2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dimension.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/download.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/download.svg new file mode 100644 index 0000000000000000000000000000000000000000..2629a34b1b5e153a751311ee5d5119f2650d2ec4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/download.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dragger.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dragger.svg new file mode 100644 index 0000000000000000000000000000000000000000..3f70c3f9e4c5a13a1cf2e2f1fdf06a59efa3847e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/dragger.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/histogram.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/histogram.svg new file mode 100644 index 0000000000000000000000000000000000000000..baf49135e72ad834f83a4a9e39545c00b6da835e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/histogram.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/hover.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/hover.svg new file mode 100644 index 0000000000000000000000000000000000000000..4b5a34501e84364594701245628acfb5e47ddda0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/hover.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/image.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/image.svg new file mode 100644 index 0000000000000000000000000000000000000000..fd673e32b779cc63de531cdd56f4e9ab5a11e4ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/image.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/left.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/left.svg new file mode 100644 index 0000000000000000000000000000000000000000..3d5a725f8320cf7e71ea112d3b636cfb63d20b65 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/leftClick.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/leftClick.svg new file mode 100644 index 0000000000000000000000000000000000000000..3d5a725f8320cf7e71ea112d3b636cfb63d20b65 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/leftClick.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/log-axis.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/log-axis.svg new file mode 100644 index 0000000000000000000000000000000000000000..f9f3664fbc6c0184a2bc492e9e3c87b15bacd839 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/log-axis.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/maximize.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/maximize.svg new file mode 100644 index 0000000000000000000000000000000000000000..fd11e9db90eb5aea7ae6fe0ffc4e5be87ba3a4ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/maximize.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minimize.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minimize.svg new file mode 100644 index 0000000000000000000000000000000000000000..cbeed62bfca5b9c6cb7148895eb3f1b5d1be4198 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minimize.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus-circle.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus-circle.svg new file mode 100644 index 0000000000000000000000000000000000000000..f854aa1654c8d54d50ee44395fa54ee2c902c17b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus.svg new file mode 100644 index 0000000000000000000000000000000000000000..81d01181a59106ecd6f2617a0f5130b0fb712111 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/minus.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/mute.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/mute.svg new file mode 100644 index 0000000000000000000000000000000000000000..18a1b5513397e969a576d71d96ab4226b5363eab --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/mute.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/pause.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/pause.svg new file mode 100644 index 0000000000000000000000000000000000000000..1a2d0ac7530d07414af0a4f65cef9d9a60d912dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/pause.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/play.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/play.svg new file mode 100644 index 0000000000000000000000000000000000000000..0eca61e90ab2fb4c3505a4142fc23c6691634a1a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/play.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus-circle.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus-circle.svg new file mode 100644 index 0000000000000000000000000000000000000000..5c8d531fa2f512eb68286bf78696c6ab500f4d3e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus.svg new file mode 100644 index 0000000000000000000000000000000000000000..50f6f4877acfa2bfa6c18a07efe4096a5df409a1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/plus.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/question-circle.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/question-circle.svg new file mode 100644 index 0000000000000000000000000000000000000000..a5c3b8f6f8d73733810f70ee17892279d4946459 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/question-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reduction.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reduction.svg new file mode 100644 index 0000000000000000000000000000000000000000..735202e27f5cedced7bb675f16ac4df32f181cfa --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reduction.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/refresh.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/refresh.svg new file mode 100644 index 0000000000000000000000000000000000000000..d99d90090215632e9680a67e858b9d17658e269b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/refresh.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reset.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reset.svg new file mode 100644 index 0000000000000000000000000000000000000000..918aaa5a86a6ea9ecc5aa001cae1a2cd8ef90af3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/reset.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-circle.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-circle.svg new file mode 100644 index 0000000000000000000000000000000000000000..ed8e311f7f6ed617e643b52926bd92f11416303d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-circle.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-size.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-size.svg new file mode 100644 index 0000000000000000000000000000000000000000..49eda9a83a1f575e6555a8ee8b486e552c7cc7b6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/restore-size.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/revert.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/revert.svg new file mode 100644 index 0000000000000000000000000000000000000000..b2a76f6c1d88cf665be8356f510b6fc42e8030cc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/revert.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/right.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/right.svg new file mode 100644 index 0000000000000000000000000000000000000000..28803d33405d1cbb9fa26c8456bd717ff72fc2c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/rightClick.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/rightClick.svg new file mode 100644 index 0000000000000000000000000000000000000000..28803d33405d1cbb9fa26c8456bd717ff72fc2c9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/rightClick.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/scalar.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/scalar.svg new file mode 100644 index 0000000000000000000000000000000000000000..c464dfc638bd91666d6beee6adda2dea410a35ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/scalar.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/search.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/search.svg new file mode 100644 index 0000000000000000000000000000000000000000..c482e540015ed03b917fbfbeb9c4263dfbc8dfc6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/search.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/selection.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/selection.svg new file mode 100644 index 0000000000000000000000000000000000000000..1a37381321ba942c1decbd198e9fe7d8f05e695d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/selection.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/shrink.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/shrink.svg new file mode 100644 index 0000000000000000000000000000000000000000..cbd24de0675f682099987a67386068d99836724b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/shrink.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/text.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/text.svg new file mode 100644 index 0000000000000000000000000000000000000000..d9ff5488f659753c939bde9c25f6b081f4b75a64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/text.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/theme.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/theme.svg new file mode 100644 index 0000000000000000000000000000000000000000..41faa6666f9d1495792d0a312cbe64682c0b919b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/theme.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/three-d.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/three-d.svg new file mode 100644 index 0000000000000000000000000000000000000000..f0eb759b8018b68ed3ad141dc344e51f57b754dd --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/three-d.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/upload.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/upload.svg new file mode 100644 index 0000000000000000000000000000000000000000..cc521bd0e376c855d7f8145cade37792c423dd18 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/upload.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume-low.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume-low.svg new file mode 100644 index 0000000000000000000000000000000000000000..472fd1967230e920051d23c9ff4a10fa6c65ace5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume-low.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume.svg new file mode 100644 index 0000000000000000000000000000000000000000..a224869a8d353b70001b236abfe7c3b36a8d4e04 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/volume.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-in.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-in.svg new file mode 100644 index 0000000000000000000000000000000000000000..bf09b7b284204097771b992ff6c1b819cd432fbf --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-in.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-out.svg b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-out.svg new file mode 100644 index 0000000000000000000000000000000000000000..245faf4a3c997658f39fa1f40033a066ccc6a6ed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/icons/svgs/zoom-out.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/mock/index.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/mock/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7c761299cd24ecc00b7c1b526666f8fd94bcdb14 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/mock/index.js @@ -0,0 +1 @@ +var c;import*as a from"../../../env.js";const u=(c=a==null?void 0:a.SNOWPACK_PUBLIC_API_URL)!=null?c:"";export async function initMock(){const{default:r}=await import("../../../pkg/fetch-mock/esm/client.js");r.config.overwriteRoutes=!0,r.config.fallbackToNetwork=!0,r.mock(`begin:${u}`,async(f,l,p)=>{try{const o=p||new Request(f,l),i=new URL(o.url),m=i.pathname.replace(u,""),{default:n}=await import(`./data${m}.js`);return typeof n=="function"?await n({query:[...i.searchParams.entries()].reduce((e,k)=>{const[t,s]=k;return e.hasOwnProperty(t)?Array.isArray(e[t])?e[t]=[...e[t],s]:e[t]=[e[t],s]:e[t]=s,e},{})}):n}catch(o){return console.error(o),500}})} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1f8a8be17df94d968919398191cdf563a4756979 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-metadata.json @@ -0,0 +1 @@ +[{"name":"InputLayer","schema":{"bindings":[{"name":"layerBindingId","type":"int","src":"layerBindingId"}]}},{"name":"OutputLayer","schema":{"category":"Tensor","bindings":[{"name":"layerBindingId","type":"int","src":"layerBindingId"}]}},{"name":"Pooling2dLayer","schema":{"category":"Pool","attributes":[{"name":"type","type":"string","src":"poolType","src_type":"PoolingAlgorithm"},{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"width","type":"string","src":"poolWidth"},{"name":"height","type":"string","src":"poolHeight"},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"outputShapeRounding","type":"string","src":"outputShapeRounding","src_type":"OutputShapeRounding"},{"name":"paddingMethod","type":"string","src":"paddingMethod","src_type":"PaddingMethod"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ReshapeLayer","schema":{"category":"Shape","attributes":[{"name":"targetShape","type":"string","src":"targetShape"}]}},{"name":"SoftmaxLayer","schema":{"category":"Activation","attributes":[{"name":"beta","type":"float","src":"beta"}]}},{"name":"Convolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dilation","type":"string","src":["dilationX","dilationY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"DepthwiseConvolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dilation","type":"string","src":["dilationX","dilationY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ActivationLayer","schema":{"category":"Activation","attributes":[{"name":"function","type":"string","src":"activationFunction","src_type":"ActivationFunction"},{"name":"a","type":"float","src":"a"},{"name":"b","type":"float","src":"b"}]}},{"name":"PermuteLayer","schema":{"category":"Shape","attributes":[{"name":"dimMappings","type":"string","src":"dimMappings"}]}},{"name":"FullyConnectedLayer","schema":{"category":"Layer","inputs":[{"name":"weights","src":"weights"},{"name":"biases","src":"biases"}],"attributes":[{"name":"transposeWeightsMatrix","type":"bool","src":"transposeWeightsMatrix"}]}},{"name":"ConstantLayer","schema":{"category":"Constant","inputs":[{"name":"input","src":"input"}]}},{"name":"SpaceToBatchNdLayer","schema":{"category":"Layer","attributes":[{"name":"blockShape","type":"string","src":"blockShape"},{"name":"padList","type":"string","src":"padList"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"BatchToSpaceNdLayer","schema":{"category":"Layer","attributes":[{"name":"blockShape","type":"string","src":"blockShape"},{"name":"crops","type":"string","src":"crops"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"DivisionLayer","schema":{"category":"Layer"}},{"name":"MinimumLayer","schema":{"category":"Layer"}},{"name":"EqualLayer","schema":{"category":"Layer"}},{"name":"MaximumLayer","schema":{"category":"Layer"}},{"name":"NormalizationLayer","schema":{"category":"Normalization","attributes":[{"name":"normChannelType","type":"string","src":"normChannelType","src_type":"NormalizationAlgorithmChannel"},{"name":"normMethodType","type":"string","src":"normMethodType","src_type":"NormalizationAlgorithmMethod"},{"name":"normSize","type":"uint","src":"normSize"},{"name":"alpha","type":"float","src":"alpha"},{"name":"beta","type":"float","src":"beta"},{"name":"k","type":"float","src":"k"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"PadLayer","schema":{"category":"Layer","attributes":[{"name":"padList","type":"uint","src":"padList"},{"name":"padValue","type":"float","src":"padValue"}]}},{"name":"RsqrtLayer","schema":{"category":"Layer"}},{"name":"FloorLayer","schema":{"category":"Layer"}},{"name":"BatchNormalizationLayer","schema":{"category":"Normalization","inputs":[{"name":"mean","src":"mean"},{"name":"variance","src":"variance"},{"name":"beta","src":"beta"},{"name":"gamma","src":"gamma"}],"attributes":[{"name":"eps","type":"float","src":"eps"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"GreaterLayer","schema":{"category":"Layer","attributes":[]}},{"name":"ResizeBilinearLayer","schema":{"category":"Layer","attributes":[{"name":"targetWidth","type":"uint","src":"targetWidth"},{"name":"targetHeight","type":"uint","src":"targetHeight"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"SubtractionLayer","schema":{}},{"name":"StridedSliceLayer","schema":{"category":"Tensor","attributes":[{"name":"begin","type":"int","src":"begin"},{"name":"end","type":"int","src":"end"},{"name":"stride","type":"int","src":"stride"},{"name":"beginMask","type":"int","src":"beginMask"},{"name":"endMask","type":"int","src":"endMask"},{"name":"shrinkAxisMask","type":"int","src":"shrinkAxisMask"},{"name":"ellipsisMask","type":"int","src":"ellipsisMask"},{"name":"newAxisMask","type":"int","src":"newAxisMask"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"GatherLayer","schema":{"category":"Tensor"}},{"name":"MeanLayer","schema":{"attributes":[{"name":"axis","type":"uint","src":"axis"},{"name":"keepDims","type":"bool","src":"keepDims"}]}},{"name":"MergerLayer","schema":{"category":"Tensor"}},{"name":"L2NormalizationLayer","schema":{"category":"Normalization","attributes":[{"name":"eps","type":"float","src":"eps"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"SplitterLayer","schema":{"category":"Tensor","attributes":[{"name":"concatAxis","type":"uint","src":"concatAxis"},{"name":"numViews","type":"uint","src":"numViewes"},{"name":"numDimensions","type":"uint","src":"numDimensions"}]}},{"name":"DetectionPostProcessLayer","schema":{"category":"Custom","attributes":[{"name":"maxDetections","type":"uint","src":"maxDetections"},{"name":"maxClassesPerDetection","type":"uint","src":"maxClassesPerDetection"},{"name":"detectionsPerClass","type":"uint","src":"detectionsPerClass"},{"name":"nmsScoreThreshold","type":"float","src":"nmsScoreThreshold"},{"name":"numIouThreshold","type":"float","src":"nmsIouThreshold"},{"name":"numClasses","type":"uint","src":"numClasses"},{"name":"useRegularNms","type":"bool","src":"useRegularNms"},{"name":"scaleX","type":"float","src":"scaleX"},{"name":"scaleY","type":"float","src":"scaleY"},{"name":"scaleW","type":"float","src":"scaleW"},{"name":"scaleH","type":"float","src":"scaleH"}]}},{"name":"LstmLayer","schema":{"category":"Layer","inputs":[{"name":"inputToForgetWeights1","src":"inputToForgetWeights1"},{"name":"inputToCellWeights1","src":"inputToCellWeights1"},{"name":"inputToOutputWeights1","src":"inputToOutputWeights1"},{"name":"recurrentToForgetWeights1","src":"recurrentToForgetWeights1"},{"name":"recurrentToCellWeights1","src":"recurrentToCellWeights1"},{"name":"recurrentToOutputWeights1","src":"recurrentToOutputWeights1"},{"name":"forgetGateBias1","src":"forgetGateBias1"},{"name":"cellBias1","src":"cellBias1"},{"name":"outputGateBias1","src":"outputGateBias1"},{"name":"inputToInputWeights1","src":"inputToInputWeights1"},{"name":"recurrentToInputWeights1","src":"recurrentToInputWeights1"},{"name":"cellToInputWeights1","src":"cellToInputWeights1"},{"name":"inputGateBias1","src":"inputGateBias1"},{"name":"projectionWeights1","src":"projectionWeights1"},{"name":"projectionBias1","src":"projectionBias1"},{"name":"cellToForgetWeights1","src":"cellToForgetWeights1"},{"name":"cellToOutputWeights1","src":"cellToOutputWeights1"},{"name":"inputLayerNormWeights1","src":"inputLayerNormWeights1"},{"name":"forgetLayerNormWeights1","src":"forgetLayerNormWeights1"},{"name":"cellLayerNormWeights1","src":"cellLayerNormWeights1"},{"name":"outputLayerNormWeights1","src":"outputLayerNormWeights1"}],"attributes":[{"name":"activationFunc","type":"uint","src":"activationFunc"},{"name":"clippingThresCell","type":"float","src":"clippingThresCell"},{"name":"clippingThresProj","type":"float","src":"clippingThresProj"},{"name":"cifgEnabled","type":"bool","src":"cifgEnabled"},{"name":"peepholeEnabled","type":"bool","src":"peepholeEnabled"},{"name":"projectionEnabled","type":"bool","src":"projectionEnabled"},{"name":"layerNormEnabled","type":"bool","src":"layerNormEnabled"}]}},{"name":"QuantizeLayer"},{"name":"DequantizeLayer"},{"name":"MergeLayer","schema":{"category":"Layer"}},{"name":"SwitchLayer","schema":{"category":"Layer"}},{"name":"ConcatLayer","schema":{"category":"Tensor","attributes":[{"name":"concatAxis","type":"uint","src":"concatAxis"},{"name":"numViews","type":"uint","src":"numViewes"},{"name":"numDimensions","type":"uint","src":"numDimensions"}]}},{"name":"SpaceToDepthLayer","schema":{"category":"Layer","attributes":[{"name":"blockSize","type":"uint","src":"blockSize"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"PreluLayer","schema":{"category":"Layer"}},{"name":"TransposeConvolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ResizeLayer","schema":{"category":"Layer","attributes":[{"name":"targetWidth","type":"uint","src":"targetWidth"},{"name":"targetHeight","type":"uint","src":"targetHeight"},{"name":"method","type":"string","src":"method","src_type":"ResizeMethod"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"StackLayer","schema":{"category":"Layer","attributes":[{"name":"axis","type":"uint","src":"axis"},{"name":"numInputs","type":"uint","src":"numInputs"},{"name":"inputShape","type":"uint","src":"inputShape"}]}},{"name":"QuantizedLstmLayer","schema":{"category":"Layer","inputs":[{"name":"inputToInputWeights1","src":"inputToInputWeights1"},{"name":"inputToForgetWeights1","src":"inputToForgetWeights1"},{"name":"inputToCellWeights1","src":"inputToCellWeights1"},{"name":"inputToOutputWeights1","src":"inputToOutputWeights1"},{"name":"recurrentToInputWeights1","src":"recurrentToInputWeights1"},{"name":"recurrentToForgetWeights1","src":"recurrentToForgetWeights1"},{"name":"recurrentToCellWeights1","src":"recurrentToCellWeights1"},{"name":"recurrentToOutputWeights1","src":"recurrentToOutputWeights1"},{"name":"inputGateBias1","src":"inputGateBias1"},{"name":"forgetGateBias1","src":"forgetGateBias1"},{"name":"cellBias1","src":"cellBias1"},{"name":"outputGateBias1","src":"outputGateBias1"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-schema.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..cd4479c390d2d37c73357d01bc39bb60f17ea55b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn-schema.js @@ -0,0 +1 @@ +var $root=flatbuffers.get("armnn");$root.armnnSerializer=$root.armnnSerializer||{},$root.armnnSerializer.ActivationFunction={Sigmoid:0,TanH:1,Linear:2,ReLu:3,BoundedReLu:4,SoftReLu:5,LeakyReLu:6,Abs:7,Sqrt:8,Square:9,Elu:10,HardSwish:11},$root.armnnSerializer.ArgMinMaxFunction={Min:0,Max:1},$root.armnnSerializer.DataType={Float16:0,Float32:1,QuantisedAsymm8:2,Signed32:3,Boolean:4,QuantisedSymm16:5,QAsymmU8:6,QSymmS16:7,QAsymmS8:8,QSymmS8:9},$root.armnnSerializer.DataLayout={NHWC:0,NCHW:1},$root.armnnSerializer.ResizeMethod={NearestNeighbor:0,Bilinear:1},$root.armnnSerializer.TensorInfo=class{static decode(e,r){const t=new $root.armnnSerializer.TensorInfo;return t.dimensions=e.typedArray(r,4,Uint32Array),t.dataType=e.int8_(r,6,0),t.quantizationScale=e.float32_(r,8,1),t.quantizationOffset=e.int32_(r,10,0),t.quantizationScales=e.typedArray(r,12,Float32Array),t.quantizationDim=e.uint32_(r,14,0),t.dimensionality=e.uint32_(r,16,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.TensorInfo;return t.dimensions=e.typedArray(r.dimensions,Uint32Array),t.dataType=$root.armnnSerializer.DataType[r.dataType],t.quantizationScale=e.value(r.quantizationScale,1),t.quantizationOffset=e.value(r.quantizationOffset,0),t.quantizationScales=e.typedArray(r.quantizationScales,Float32Array),t.quantizationDim=e.value(r.quantizationDim,0),t.dimensionality=e.value(r.dimensionality,1),t}},$root.armnnSerializer.Connection=class{static decode(e,r){const t=new $root.armnnSerializer.Connection;return t.sourceLayerIndex=e.uint32(r+0),t.outputSlotIndex=e.uint32(r+4),t}static decodeText(e,r){const t=new $root.armnnSerializer.Connection;return t.sourceLayerIndex=r.sourceLayerIndex,t.outputSlotIndex=r.outputSlotIndex,t}},$root.armnnSerializer.ByteData=class{static decode(e,r){const t=new $root.armnnSerializer.ByteData;return t.data=e.typedArray(r,4,Int8Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ByteData;return t.data=e.typedArray(r.data,Int8Array),t}},$root.armnnSerializer.ShortData=class{static decode(e,r){const t=new $root.armnnSerializer.ShortData;return t.data=e.typedArray(r,4,Int16Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ShortData;return t.data=e.typedArray(r.data,Int16Array),t}},$root.armnnSerializer.IntData=class{static decode(e,r){const t=new $root.armnnSerializer.IntData;return t.data=e.typedArray(r,4,Int32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.IntData;return t.data=e.typedArray(r.data,Int32Array),t}},$root.armnnSerializer.LongData=class{static decode(e,r){const t=new $root.armnnSerializer.LongData;return t.data=e.int64s_(r,4),t}static decodeText(e,r){const t=new $root.armnnSerializer.LongData;return t.data=e.array(r.data),t}},$root.armnnSerializer.ConstTensorData=class{static decode(e,r,t){switch(t){case 1:return $root.armnnSerializer.ByteData.decode(e,r);case 2:return $root.armnnSerializer.ShortData.decode(e,r);case 3:return $root.armnnSerializer.IntData.decode(e,r);case 4:return $root.armnnSerializer.LongData.decode(e,r)}}static decodeText(e,r,t){switch(t){case"ByteData":return $root.armnnSerializer.ByteData.decodeText(e,r);case"ShortData":return $root.armnnSerializer.ShortData.decodeText(e,r);case"IntData":return $root.armnnSerializer.IntData.decodeText(e,r);case"LongData":return $root.armnnSerializer.LongData.decodeText(e,r)}}},$root.armnnSerializer.ConstTensor=class{static decode(e,r){const t=new $root.armnnSerializer.ConstTensor;return t.info=e.table(r,4,$root.armnnSerializer.TensorInfo.decode),t.data=e.union(r,6,$root.armnnSerializer.ConstTensorData.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConstTensor;return t.info=e.object(r.info,$root.armnnSerializer.TensorInfo.decodeText),t.data=$root.armnnSerializer.ConstTensorData.decodeText(e,r.data,r.data_type),t}},$root.armnnSerializer.InputSlot=class{static decode(e,r){const t=new $root.armnnSerializer.InputSlot;return t.index=e.uint32_(r,4,0),t.connection=e.struct(r,6,$root.armnnSerializer.Connection.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InputSlot;return t.index=e.value(r.index,0),t.connection=e.object(r.connection,$root.armnnSerializer.Connection.decodeText),t}},$root.armnnSerializer.OutputSlot=class{static decode(e,r){const t=new $root.armnnSerializer.OutputSlot;return t.index=e.uint32_(r,4,0),t.tensorInfo=e.table(r,6,$root.armnnSerializer.TensorInfo.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OutputSlot;return t.index=e.value(r.index,0),t.tensorInfo=e.object(r.tensorInfo,$root.armnnSerializer.TensorInfo.decodeText),t}},$root.armnnSerializer.LayerType={Addition:0,Input:1,Multiplication:2,Output:3,Pooling2d:4,Reshape:5,Softmax:6,Convolution2d:7,DepthwiseConvolution2d:8,Activation:9,Permute:10,FullyConnected:11,Constant:12,SpaceToBatchNd:13,BatchToSpaceNd:14,Division:15,Minimum:16,Equal:17,Maximum:18,Normalization:19,Pad:20,Rsqrt:21,Floor:22,BatchNormalization:23,Greater:24,ResizeBilinear:25,Subtraction:26,StridedSlice:27,Gather:28,Mean:29,Merger:30,L2Normalization:31,Splitter:32,DetectionPostProcess:33,Lstm:34,Quantize:35,Dequantize:36,Merge:37,Switch:38,Concat:39,SpaceToDepth:40,Prelu:41,TransposeConvolution2d:42,Resize:43,Stack:44,QuantizedLstm:45,Abs:46,ArgMinMax:47,Slice:48,DepthToSpace:49,InstanceNormalization:50,LogSoftmax:51,Comparison:52,StandIn:53,ElementwiseUnary:54,Transpose:55,QLstm:56,Fill:57,Rank:58},$root.armnnSerializer.LayerBase=class{static decode(e,r){const t=new $root.armnnSerializer.LayerBase;return t.index=e.uint32_(r,4,0),t.layerName=e.string_(r,6,null),t.layerType=e.uint32_(r,8,0),t.inputSlots=e.tableArray(r,10,$root.armnnSerializer.InputSlot.decode),t.outputSlots=e.tableArray(r,12,$root.armnnSerializer.OutputSlot.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LayerBase;return t.index=e.value(r.index,0),t.layerName=e.value(r.layerName,null),t.layerType=$root.armnnSerializer.LayerType[r.layerType],t.inputSlots=e.objectArray(r.inputSlots,$root.armnnSerializer.InputSlot.decodeText),t.outputSlots=e.objectArray(r.outputSlots,$root.armnnSerializer.OutputSlot.decodeText),t}},$root.armnnSerializer.BindableLayerBase=class{static decode(e,r){const t=new $root.armnnSerializer.BindableLayerBase;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.layerBindingId=e.int32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BindableLayerBase;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.layerBindingId=e.value(r.layerBindingId,0),t}},$root.armnnSerializer.AbsLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AbsLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AbsLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.ActivationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ActivationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ActivationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ActivationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ActivationDescriptor.decodeText),t}},$root.armnnSerializer.ActivationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ActivationDescriptor;return t.activationFunction=e.int8_(r,4,0),t.a=e.float32_(r,6,0),t.b=e.float32_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ActivationDescriptor;return t.activationFunction=$root.armnnSerializer.ActivationFunction[r.activationFunction],t.a=e.value(r.a,0),t.b=e.value(r.b,0),t}},$root.armnnSerializer.AdditionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AdditionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AdditionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.ArgMinMaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ArgMinMaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ArgMinMaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ArgMinMaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ArgMinMaxDescriptor.decodeText),t}},$root.armnnSerializer.ArgMinMaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ArgMinMaxDescriptor;return t.argMinMaxFunction=e.int8_(r,4,0),t.axis=e.int32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ArgMinMaxDescriptor;return t.argMinMaxFunction=$root.armnnSerializer.ArgMinMaxFunction[r.argMinMaxFunction],t.axis=e.value(r.axis,0),t}},$root.armnnSerializer.ComparisonOperation={Equal:0,Greater:1,GreaterOrEqual:2,Less:3,LessOrEqual:4,NotEqual:5},$root.armnnSerializer.ComparisonDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ComparisonDescriptor;return t.operation=e.int8_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ComparisonDescriptor;return t.operation=$root.armnnSerializer.ComparisonOperation[r.operation],t}},$root.armnnSerializer.ComparisonLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ComparisonLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ComparisonDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ComparisonLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ComparisonDescriptor.decodeText),t}},$root.armnnSerializer.ConstantLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ConstantLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.input=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConstantLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.input=e.object(r.input,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.Convolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.Convolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.Convolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.Convolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.Convolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.Convolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.Convolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.dilationX=e.uint32_(r,16,1),t.dilationY=e.uint32_(r,18,1),t.biasEnabled=e.bool_(r,20,!1),t.dataLayout=e.int8_(r,22,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.Convolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.dilationX=e.value(r.dilationX,1),t.dilationY=e.value(r.dilationY,1),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.DepthToSpaceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DepthToSpaceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DepthToSpaceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthToSpaceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DepthToSpaceDescriptor.decodeText),t}},$root.armnnSerializer.DepthToSpaceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DepthToSpaceDescriptor;return t.blockSize=e.uint32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthToSpaceDescriptor;return t.blockSize=e.value(r.blockSize,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.DivisionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DivisionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DivisionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.UnaryOperation={Abs:0,Rsqrt:1,Sqrt:2,Exp:3,Neg:4},$root.armnnSerializer.ElementwiseUnaryDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryDescriptor;return t.operation=e.int8_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryDescriptor;return t.operation=$root.armnnSerializer.UnaryOperation[r.operation],t}},$root.armnnSerializer.ElementwiseUnaryLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ElementwiseUnaryDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ElementwiseUnaryDescriptor.decodeText),t}},$root.armnnSerializer.EqualLayer=class{static decode(e,r){const t=new $root.armnnSerializer.EqualLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.EqualLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.FillLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FillLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.FillDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FillLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.FillDescriptor.decodeText),t}},$root.armnnSerializer.FillDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.FillDescriptor;return t.value=e.float32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.FillDescriptor;return t.value=e.value(r.value,0),t}},$root.armnnSerializer.FloorLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FloorLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FloorLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.FullyConnectedLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FullyConnectedLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.FullyConnectedDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FullyConnectedLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.FullyConnectedDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.FullyConnectedDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.FullyConnectedDescriptor;return t.biasEnabled=e.bool_(r,4,!1),t.transposeWeightsMatrix=e.bool_(r,6,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.FullyConnectedDescriptor;return t.biasEnabled=e.value(r.biasEnabled,!1),t.transposeWeightsMatrix=e.value(r.transposeWeightsMatrix,!1),t}},$root.armnnSerializer.GatherLayer=class{static decode(e,r){const t=new $root.armnnSerializer.GatherLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.GatherDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.GatherLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.GatherDescriptor.decodeText),t}},$root.armnnSerializer.GatherDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.GatherDescriptor;return t.axis=e.int32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.GatherDescriptor;return t.axis=e.value(r.axis,0),t}},$root.armnnSerializer.GreaterLayer=class{static decode(e,r){const t=new $root.armnnSerializer.GreaterLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.GreaterLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.InputLayer=class{static decode(e,r){const t=new $root.armnnSerializer.InputLayer;return t.base=e.table(r,4,$root.armnnSerializer.BindableLayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InputLayer;return t.base=e.object(r.base,$root.armnnSerializer.BindableLayerBase.decodeText),t}},$root.armnnSerializer.InstanceNormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.InstanceNormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.InstanceNormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InstanceNormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.InstanceNormalizationDescriptor.decodeText),t}},$root.armnnSerializer.InstanceNormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.InstanceNormalizationDescriptor;return t.gamma=e.float32_(r,4,0),t.beta=e.float32_(r,6,0),t.eps=e.float32_(r,8,0),t.dataLayout=e.int8_(r,10,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.InstanceNormalizationDescriptor;return t.gamma=e.value(r.gamma,0),t.beta=e.value(r.beta,0),t.eps=e.value(r.eps,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.LogSoftmaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.LogSoftmaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.LogSoftmaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LogSoftmaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.LogSoftmaxDescriptor.decodeText),t}},$root.armnnSerializer.LogSoftmaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.LogSoftmaxDescriptor;return t.beta=e.float32_(r,4,1),t.axis=e.int32_(r,6,-1),t}static decodeText(e,r){const t=new $root.armnnSerializer.LogSoftmaxDescriptor;return t.beta=e.value(r.beta,1),t.axis=e.value(r.axis,-1),t}},$root.armnnSerializer.L2NormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.L2NormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.L2NormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.L2NormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.L2NormalizationDescriptor.decodeText),t}},$root.armnnSerializer.L2NormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.L2NormalizationDescriptor;return t.dataLayout=e.int8_(r,4,1),t.eps=e.float32_(r,6,1e-12),t}static decodeText(e,r){const t=new $root.armnnSerializer.L2NormalizationDescriptor;return t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.eps=e.value(r.eps,1e-12),t}},$root.armnnSerializer.MinimumLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MinimumLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MinimumLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MaximumLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MaximumLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MaximumLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MultiplicationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MultiplicationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MultiplicationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.Pooling2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.Pooling2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.Pooling2dDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.Pooling2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.Pooling2dDescriptor.decodeText),t}},$root.armnnSerializer.PoolingAlgorithm={Max:0,Average:1,L2:2},$root.armnnSerializer.OutputShapeRounding={Floor:0,Ceiling:1},$root.armnnSerializer.PaddingMethod={IgnoreValue:0,Exclude:1},$root.armnnSerializer.Pooling2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.Pooling2dDescriptor;return t.poolType=e.int8_(r,4,0),t.padLeft=e.uint32_(r,6,0),t.padRight=e.uint32_(r,8,0),t.padTop=e.uint32_(r,10,0),t.padBottom=e.uint32_(r,12,0),t.poolWidth=e.uint32_(r,14,0),t.poolHeight=e.uint32_(r,16,0),t.strideX=e.uint32_(r,18,0),t.strideY=e.uint32_(r,20,0),t.outputShapeRounding=e.int8_(r,22,0),t.paddingMethod=e.int8_(r,24,0),t.dataLayout=e.int8_(r,26,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.Pooling2dDescriptor;return t.poolType=$root.armnnSerializer.PoolingAlgorithm[r.poolType],t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.poolWidth=e.value(r.poolWidth,0),t.poolHeight=e.value(r.poolHeight,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.outputShapeRounding=$root.armnnSerializer.OutputShapeRounding[r.outputShapeRounding],t.paddingMethod=$root.armnnSerializer.PaddingMethod[r.paddingMethod],t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.QuantizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.SoftmaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SoftmaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SoftmaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SoftmaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SoftmaxDescriptor.decodeText),t}},$root.armnnSerializer.SoftmaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SoftmaxDescriptor;return t.beta=e.float32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SoftmaxDescriptor;return t.beta=e.value(r.beta,0),t}},$root.armnnSerializer.DepthwiseConvolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DepthwiseConvolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DepthwiseConvolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.DepthwiseConvolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.dilationX=e.uint32_(r,16,1),t.dilationY=e.uint32_(r,18,1),t.biasEnabled=e.bool_(r,20,!1),t.dataLayout=e.int8_(r,22,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.dilationX=e.value(r.dilationX,1),t.dilationY=e.value(r.dilationY,1),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.OutputLayer=class{static decode(e,r){const t=new $root.armnnSerializer.OutputLayer;return t.base=e.table(r,4,$root.armnnSerializer.BindableLayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OutputLayer;return t.base=e.object(r.base,$root.armnnSerializer.BindableLayerBase.decodeText),t}},$root.armnnSerializer.ReshapeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ReshapeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ReshapeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ReshapeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ReshapeDescriptor.decodeText),t}},$root.armnnSerializer.ReshapeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ReshapeDescriptor;return t.targetShape=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ReshapeDescriptor;return t.targetShape=e.typedArray(r.targetShape,Uint32Array),t}},$root.armnnSerializer.PermuteLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PermuteLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.PermuteDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PermuteLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.PermuteDescriptor.decodeText),t}},$root.armnnSerializer.PermuteDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.PermuteDescriptor;return t.dimMappings=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.PermuteDescriptor;return t.dimMappings=e.typedArray(r.dimMappings,Uint32Array),t}},$root.armnnSerializer.SpaceToBatchNdLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SpaceToBatchNdDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SpaceToBatchNdDescriptor.decodeText),t}},$root.armnnSerializer.SpaceToBatchNdDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdDescriptor;return t.blockShape=e.typedArray(r,4,Uint32Array),t.padList=e.typedArray(r,6,Uint32Array),t.dataLayout=e.int8_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdDescriptor;return t.blockShape=e.typedArray(r.blockShape,Uint32Array),t.padList=e.typedArray(r.padList,Uint32Array),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.SpaceToDepthLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToDepthLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SpaceToDepthDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToDepthLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SpaceToDepthDescriptor.decodeText),t}},$root.armnnSerializer.SpaceToDepthDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToDepthDescriptor;return t.blockSize=e.uint32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToDepthDescriptor;return t.blockSize=e.value(r.blockSize,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.SubtractionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SubtractionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SubtractionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.BatchToSpaceNdLayer=class{static decode(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.BatchToSpaceNdDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.BatchToSpaceNdDescriptor.decodeText),t}},$root.armnnSerializer.BatchToSpaceNdDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdDescriptor;return t.blockShape=e.typedArray(r,4,Uint32Array),t.crops=e.typedArray(r,6,Uint32Array),t.dataLayout=e.int8_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdDescriptor;return t.blockShape=e.typedArray(r.blockShape,Uint32Array),t.crops=e.typedArray(r.crops,Uint32Array),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.NormalizationAlgorithmChannel={Across:0,Within:1},$root.armnnSerializer.NormalizationAlgorithmMethod={LocalBrightness:0,LocalContrast:1},$root.armnnSerializer.NormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.NormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.NormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.NormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.NormalizationDescriptor.decodeText),t}},$root.armnnSerializer.NormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.NormalizationDescriptor;return t.normChannelType=e.int8_(r,4,0),t.normMethodType=e.int8_(r,6,0),t.normSize=e.uint32_(r,8,0),t.alpha=e.float32_(r,10,0),t.beta=e.float32_(r,12,0),t.k=e.float32_(r,14,0),t.dataLayout=e.int8_(r,16,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.NormalizationDescriptor;return t.normChannelType=$root.armnnSerializer.NormalizationAlgorithmChannel[r.normChannelType],t.normMethodType=$root.armnnSerializer.NormalizationAlgorithmMethod[r.normMethodType],t.normSize=e.value(r.normSize,0),t.alpha=e.value(r.alpha,0),t.beta=e.value(r.beta,0),t.k=e.value(r.k,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.MeanLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MeanLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.MeanDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MeanLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.MeanDescriptor.decodeText),t}},$root.armnnSerializer.MeanDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.MeanDescriptor;return t.axis=e.typedArray(r,4,Uint32Array),t.keepDims=e.bool_(r,6,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.MeanDescriptor;return t.axis=e.typedArray(r.axis,Uint32Array),t.keepDims=e.value(r.keepDims,!1),t}},$root.armnnSerializer.PadLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PadLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.PadDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PadLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.PadDescriptor.decodeText),t}},$root.armnnSerializer.PadDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.PadDescriptor;return t.padList=e.typedArray(r,4,Uint32Array),t.padValue=e.float32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.PadDescriptor;return t.padList=e.typedArray(r.padList,Uint32Array),t.padValue=e.value(r.padValue,0),t}},$root.armnnSerializer.RsqrtLayer=class{static decode(e,r){const t=new $root.armnnSerializer.RsqrtLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.RsqrtLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.BatchNormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.BatchNormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.BatchNormalizationDescriptor.decode),t.mean=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.variance=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.beta=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.gamma=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchNormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.BatchNormalizationDescriptor.decodeText),t.mean=e.object(r.mean,$root.armnnSerializer.ConstTensor.decodeText),t.variance=e.object(r.variance,$root.armnnSerializer.ConstTensor.decodeText),t.beta=e.object(r.beta,$root.armnnSerializer.ConstTensor.decodeText),t.gamma=e.object(r.gamma,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.BatchNormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.BatchNormalizationDescriptor;return t.eps=e.float32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchNormalizationDescriptor;return t.eps=e.value(r.eps,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.ResizeBilinearLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeBilinearLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ResizeBilinearDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeBilinearLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ResizeBilinearDescriptor.decodeText),t}},$root.armnnSerializer.ResizeBilinearDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeBilinearDescriptor;return t.targetWidth=e.uint32_(r,4,0),t.targetHeight=e.uint32_(r,6,0),t.dataLayout=e.int8_(r,8,0),t.alignCorners=e.bool_(r,10,!1),t.halfPixelCenters=e.bool_(r,12,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeBilinearDescriptor;return t.targetWidth=e.value(r.targetWidth,0),t.targetHeight=e.value(r.targetHeight,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.alignCorners=e.value(r.alignCorners,!1),t.halfPixelCenters=e.value(r.halfPixelCenters,!1),t}},$root.armnnSerializer.SliceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SliceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SliceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SliceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SliceDescriptor.decodeText),t}},$root.armnnSerializer.SliceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SliceDescriptor;return t.begin=e.typedArray(r,4,Uint32Array),t.size=e.typedArray(r,6,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.SliceDescriptor;return t.begin=e.typedArray(r.begin,Uint32Array),t.size=e.typedArray(r.size,Uint32Array),t}},$root.armnnSerializer.StridedSliceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StridedSliceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StridedSliceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StridedSliceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StridedSliceDescriptor.decodeText),t}},$root.armnnSerializer.StridedSliceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StridedSliceDescriptor;return t.begin=e.typedArray(r,4,Int32Array),t.end=e.typedArray(r,6,Int32Array),t.stride=e.typedArray(r,8,Int32Array),t.beginMask=e.int32_(r,10,0),t.endMask=e.int32_(r,12,0),t.shrinkAxisMask=e.int32_(r,14,0),t.ellipsisMask=e.int32_(r,16,0),t.newAxisMask=e.int32_(r,18,0),t.dataLayout=e.int8_(r,20,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.StridedSliceDescriptor;return t.begin=e.typedArray(r.begin,Int32Array),t.end=e.typedArray(r.end,Int32Array),t.stride=e.typedArray(r.stride,Int32Array),t.beginMask=e.value(r.beginMask,0),t.endMask=e.value(r.endMask,0),t.shrinkAxisMask=e.value(r.shrinkAxisMask,0),t.ellipsisMask=e.value(r.ellipsisMask,0),t.newAxisMask=e.value(r.newAxisMask,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.ConcatLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ConcatLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.OriginsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConcatLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.OriginsDescriptor.decodeText),t}},$root.armnnSerializer.MergerLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MergerLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.OriginsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MergerLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.OriginsDescriptor.decodeText),t}},$root.armnnSerializer.UintVector=class{static decode(e,r){const t=new $root.armnnSerializer.UintVector;return t.data=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.UintVector;return t.data=e.typedArray(r.data,Uint32Array),t}},$root.armnnSerializer.OriginsDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.OriginsDescriptor;return t.concatAxis=e.uint32_(r,4,0),t.numViews=e.uint32_(r,6,0),t.numDimensions=e.uint32_(r,8,0),t.viewOrigins=e.tableArray(r,10,$root.armnnSerializer.UintVector.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OriginsDescriptor;return t.concatAxis=e.value(r.concatAxis,0),t.numViews=e.value(r.numViews,0),t.numDimensions=e.value(r.numDimensions,0),t.viewOrigins=e.objectArray(r.viewOrigins,$root.armnnSerializer.UintVector.decodeText),t}},$root.armnnSerializer.ViewsDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ViewsDescriptor;return t.origins=e.table(r,4,$root.armnnSerializer.OriginsDescriptor.decode),t.viewSizes=e.tableArray(r,6,$root.armnnSerializer.UintVector.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ViewsDescriptor;return t.origins=e.object(r.origins,$root.armnnSerializer.OriginsDescriptor.decodeText),t.viewSizes=e.objectArray(r.viewSizes,$root.armnnSerializer.UintVector.decodeText),t}},$root.armnnSerializer.SplitterLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SplitterLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ViewsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SplitterLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ViewsDescriptor.decodeText),t}},$root.armnnSerializer.DetectionPostProcessLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DetectionPostProcessLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DetectionPostProcessDescriptor.decode),t.anchors=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DetectionPostProcessLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DetectionPostProcessDescriptor.decodeText),t.anchors=e.object(r.anchors,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.DetectionPostProcessDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DetectionPostProcessDescriptor;return t.maxDetections=e.uint32_(r,4,0),t.maxClassesPerDetection=e.uint32_(r,6,0),t.detectionsPerClass=e.uint32_(r,8,0),t.nmsScoreThreshold=e.float32_(r,10,0),t.nmsIouThreshold=e.float32_(r,12,0),t.numClasses=e.uint32_(r,14,0),t.useRegularNms=e.bool_(r,16,!1),t.scaleX=e.float32_(r,18,0),t.scaleY=e.float32_(r,20,0),t.scaleW=e.float32_(r,22,0),t.scaleH=e.float32_(r,24,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.DetectionPostProcessDescriptor;return t.maxDetections=e.value(r.maxDetections,0),t.maxClassesPerDetection=e.value(r.maxClassesPerDetection,0),t.detectionsPerClass=e.value(r.detectionsPerClass,0),t.nmsScoreThreshold=e.value(r.nmsScoreThreshold,0),t.nmsIouThreshold=e.value(r.nmsIouThreshold,0),t.numClasses=e.value(r.numClasses,0),t.useRegularNms=e.value(r.useRegularNms,!1),t.scaleX=e.value(r.scaleX,0),t.scaleY=e.value(r.scaleY,0),t.scaleW=e.value(r.scaleW,0),t.scaleH=e.value(r.scaleH,0),t}},$root.armnnSerializer.LstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.LstmInputParams;return t.inputToForgetWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.inputToInputWeights=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.cellToInputWeights=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,28,$root.armnnSerializer.ConstTensor.decode),t.projectionWeights=e.table(r,30,$root.armnnSerializer.ConstTensor.decode),t.projectionBias=e.table(r,32,$root.armnnSerializer.ConstTensor.decode),t.cellToForgetWeights=e.table(r,34,$root.armnnSerializer.ConstTensor.decode),t.cellToOutputWeights=e.table(r,36,$root.armnnSerializer.ConstTensor.decode),t.inputLayerNormWeights=e.table(r,38,$root.armnnSerializer.ConstTensor.decode),t.forgetLayerNormWeights=e.table(r,40,$root.armnnSerializer.ConstTensor.decode),t.cellLayerNormWeights=e.table(r,42,$root.armnnSerializer.ConstTensor.decode),t.outputLayerNormWeights=e.table(r,44,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmInputParams;return t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToInputWeights=e.object(r.cellToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.projectionWeights=e.object(r.projectionWeights,$root.armnnSerializer.ConstTensor.decodeText),t.projectionBias=e.object(r.projectionBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellToForgetWeights=e.object(r.cellToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToOutputWeights=e.object(r.cellToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputLayerNormWeights=e.object(r.inputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetLayerNormWeights=e.object(r.forgetLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellLayerNormWeights=e.object(r.cellLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.outputLayerNormWeights=e.object(r.outputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.LstmDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.LstmDescriptor;return t.activationFunc=e.uint32_(r,4,0),t.clippingThresCell=e.float32_(r,6,0),t.clippingThresProj=e.float32_(r,8,0),t.cifgEnabled=e.bool_(r,10,!0),t.peepholeEnabled=e.bool_(r,12,!1),t.projectionEnabled=e.bool_(r,14,!1),t.layerNormEnabled=e.bool_(r,16,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmDescriptor;return t.activationFunc=e.value(r.activationFunc,0),t.clippingThresCell=e.value(r.clippingThresCell,0),t.clippingThresProj=e.value(r.clippingThresProj,0),t.cifgEnabled=e.value(r.cifgEnabled,!0),t.peepholeEnabled=e.value(r.peepholeEnabled,!1),t.projectionEnabled=e.value(r.projectionEnabled,!1),t.layerNormEnabled=e.value(r.layerNormEnabled,!1),t}},$root.armnnSerializer.LstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.LstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.LstmDescriptor.decode),t.inputParams=e.table(r,8,$root.armnnSerializer.LstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.LstmDescriptor.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.LstmInputParams.decodeText),t}},$root.armnnSerializer.QLstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmInputParams;return t.inputToForgetWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.inputToInputWeights=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t.projectionWeights=e.table(r,28,$root.armnnSerializer.ConstTensor.decode),t.projectionBias=e.table(r,30,$root.armnnSerializer.ConstTensor.decode),t.cellToInputWeights=e.table(r,32,$root.armnnSerializer.ConstTensor.decode),t.cellToForgetWeights=e.table(r,34,$root.armnnSerializer.ConstTensor.decode),t.cellToOutputWeights=e.table(r,36,$root.armnnSerializer.ConstTensor.decode),t.inputLayerNormWeights=e.table(r,38,$root.armnnSerializer.ConstTensor.decode),t.forgetLayerNormWeights=e.table(r,40,$root.armnnSerializer.ConstTensor.decode),t.cellLayerNormWeights=e.table(r,42,$root.armnnSerializer.ConstTensor.decode),t.outputLayerNormWeights=e.table(r,44,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmInputParams;return t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.projectionWeights=e.object(r.projectionWeights,$root.armnnSerializer.ConstTensor.decodeText),t.projectionBias=e.object(r.projectionBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellToInputWeights=e.object(r.cellToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToForgetWeights=e.object(r.cellToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToOutputWeights=e.object(r.cellToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputLayerNormWeights=e.object(r.inputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetLayerNormWeights=e.object(r.forgetLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellLayerNormWeights=e.object(r.cellLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.outputLayerNormWeights=e.object(r.outputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.QLstmDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmDescriptor;return t.cifgEnabled=e.bool_(r,4,!0),t.peepholeEnabled=e.bool_(r,6,!1),t.projectionEnabled=e.bool_(r,8,!1),t.layerNormEnabled=e.bool_(r,10,!1),t.cellClip=e.float32_(r,12,0),t.projectionClip=e.float32_(r,14,0),t.inputIntermediateScale=e.float32_(r,16,0),t.forgetIntermediateScale=e.float32_(r,18,0),t.cellIntermediateScale=e.float32_(r,20,0),t.outputIntermediateScale=e.float32_(r,22,0),t.hiddenStateZeroPoint=e.int32_(r,24,0),t.hiddenStateScale=e.float32_(r,26,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmDescriptor;return t.cifgEnabled=e.value(r.cifgEnabled,!0),t.peepholeEnabled=e.value(r.peepholeEnabled,!1),t.projectionEnabled=e.value(r.projectionEnabled,!1),t.layerNormEnabled=e.value(r.layerNormEnabled,!1),t.cellClip=e.value(r.cellClip,0),t.projectionClip=e.value(r.projectionClip,0),t.inputIntermediateScale=e.value(r.inputIntermediateScale,0),t.forgetIntermediateScale=e.value(r.forgetIntermediateScale,0),t.cellIntermediateScale=e.value(r.cellIntermediateScale,0),t.outputIntermediateScale=e.value(r.outputIntermediateScale,0),t.hiddenStateZeroPoint=e.value(r.hiddenStateZeroPoint,0),t.hiddenStateScale=e.value(r.hiddenStateScale,0),t}},$root.armnnSerializer.QLstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.QLstmDescriptor.decode),t.inputParams=e.table(r,8,$root.armnnSerializer.QLstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.QLstmDescriptor.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.QLstmInputParams.decodeText),t}},$root.armnnSerializer.QuantizedLstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizedLstmInputParams;return t.inputToInputWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToForgetWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizedLstmInputParams;return t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.QuantizedLstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizedLstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.inputParams=e.table(r,6,$root.armnnSerializer.QuantizedLstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizedLstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.QuantizedLstmInputParams.decodeText),t}},$root.armnnSerializer.DequantizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DequantizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DequantizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MergeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MergeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MergeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.SwitchLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SwitchLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SwitchLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.PreluLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PreluLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PreluLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.TransposeConvolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.TransposeConvolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.TransposeConvolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.TransposeConvolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.biasEnabled=e.bool_(r,16,!1),t.dataLayout=e.int8_(r,18,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.TransposeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.TransposeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.TransposeDescriptor.decodeText),t}},$root.armnnSerializer.TransposeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeDescriptor;return t.dimMappings=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeDescriptor;return t.dimMappings=e.typedArray(r.dimMappings,Uint32Array),t}},$root.armnnSerializer.ResizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ResizeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ResizeDescriptor.decodeText),t}},$root.armnnSerializer.ResizeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeDescriptor;return t.targetHeight=e.uint32_(r,4,0),t.targetWidth=e.uint32_(r,6,0),t.method=e.int8_(r,8,0),t.dataLayout=e.int8_(r,10,0),t.alignCorners=e.bool_(r,12,!1),t.halfPixelCenters=e.bool_(r,14,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeDescriptor;return t.targetHeight=e.value(r.targetHeight,0),t.targetWidth=e.value(r.targetWidth,0),t.method=$root.armnnSerializer.ResizeMethod[r.method],t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.alignCorners=e.value(r.alignCorners,!1),t.halfPixelCenters=e.value(r.halfPixelCenters,!1),t}},$root.armnnSerializer.StackLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StackLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StackDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StackLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StackDescriptor.decodeText),t}},$root.armnnSerializer.StackDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StackDescriptor;return t.axis=e.uint32_(r,4,0),t.numInputs=e.uint32_(r,6,0),t.inputShape=e.typedArray(r,8,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.StackDescriptor;return t.axis=e.value(r.axis,0),t.numInputs=e.value(r.numInputs,0),t.inputShape=e.typedArray(r.inputShape,Uint32Array),t}},$root.armnnSerializer.StandInDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StandInDescriptor;return t.numInputs=e.uint32_(r,4,0),t.numOutputs=e.uint32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.StandInDescriptor;return t.numInputs=e.value(r.numInputs,0),t.numOutputs=e.value(r.numOutputs,0),t}},$root.armnnSerializer.StandInLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StandInLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StandInDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StandInLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StandInDescriptor.decodeText),t}},$root.armnnSerializer.RankLayer=class{static decode(e,r){const t=new $root.armnnSerializer.RankLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.RankLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.Layer=class{static decode(e,r,t){switch(t){case 1:return $root.armnnSerializer.ActivationLayer.decode(e,r);case 2:return $root.armnnSerializer.AdditionLayer.decode(e,r);case 3:return $root.armnnSerializer.BatchToSpaceNdLayer.decode(e,r);case 4:return $root.armnnSerializer.BatchNormalizationLayer.decode(e,r);case 5:return $root.armnnSerializer.ConstantLayer.decode(e,r);case 6:return $root.armnnSerializer.Convolution2dLayer.decode(e,r);case 7:return $root.armnnSerializer.DepthwiseConvolution2dLayer.decode(e,r);case 8:return $root.armnnSerializer.FullyConnectedLayer.decode(e,r);case 9:return $root.armnnSerializer.InputLayer.decode(e,r);case 10:return $root.armnnSerializer.MultiplicationLayer.decode(e,r);case 11:return $root.armnnSerializer.OutputLayer.decode(e,r);case 12:return $root.armnnSerializer.PermuteLayer.decode(e,r);case 13:return $root.armnnSerializer.Pooling2dLayer.decode(e,r);case 14:return $root.armnnSerializer.ReshapeLayer.decode(e,r);case 15:return $root.armnnSerializer.SoftmaxLayer.decode(e,r);case 16:return $root.armnnSerializer.SpaceToBatchNdLayer.decode(e,r);case 17:return $root.armnnSerializer.DivisionLayer.decode(e,r);case 18:return $root.armnnSerializer.MinimumLayer.decode(e,r);case 19:return $root.armnnSerializer.EqualLayer.decode(e,r);case 20:return $root.armnnSerializer.MaximumLayer.decode(e,r);case 21:return $root.armnnSerializer.NormalizationLayer.decode(e,r);case 22:return $root.armnnSerializer.PadLayer.decode(e,r);case 23:return $root.armnnSerializer.RsqrtLayer.decode(e,r);case 24:return $root.armnnSerializer.FloorLayer.decode(e,r);case 25:return $root.armnnSerializer.GreaterLayer.decode(e,r);case 26:return $root.armnnSerializer.ResizeBilinearLayer.decode(e,r);case 27:return $root.armnnSerializer.SubtractionLayer.decode(e,r);case 28:return $root.armnnSerializer.StridedSliceLayer.decode(e,r);case 29:return $root.armnnSerializer.GatherLayer.decode(e,r);case 30:return $root.armnnSerializer.MeanLayer.decode(e,r);case 31:return $root.armnnSerializer.MergerLayer.decode(e,r);case 32:return $root.armnnSerializer.L2NormalizationLayer.decode(e,r);case 33:return $root.armnnSerializer.SplitterLayer.decode(e,r);case 34:return $root.armnnSerializer.DetectionPostProcessLayer.decode(e,r);case 35:return $root.armnnSerializer.LstmLayer.decode(e,r);case 36:return $root.armnnSerializer.QuantizedLstmLayer.decode(e,r);case 37:return $root.armnnSerializer.QuantizeLayer.decode(e,r);case 38:return $root.armnnSerializer.DequantizeLayer.decode(e,r);case 39:return $root.armnnSerializer.MergeLayer.decode(e,r);case 40:return $root.armnnSerializer.SwitchLayer.decode(e,r);case 41:return $root.armnnSerializer.ConcatLayer.decode(e,r);case 42:return $root.armnnSerializer.SpaceToDepthLayer.decode(e,r);case 43:return $root.armnnSerializer.PreluLayer.decode(e,r);case 44:return $root.armnnSerializer.TransposeConvolution2dLayer.decode(e,r);case 45:return $root.armnnSerializer.ResizeLayer.decode(e,r);case 46:return $root.armnnSerializer.StackLayer.decode(e,r);case 47:return $root.armnnSerializer.AbsLayer.decode(e,r);case 48:return $root.armnnSerializer.ArgMinMaxLayer.decode(e,r);case 49:return $root.armnnSerializer.SliceLayer.decode(e,r);case 50:return $root.armnnSerializer.DepthToSpaceLayer.decode(e,r);case 51:return $root.armnnSerializer.InstanceNormalizationLayer.decode(e,r);case 52:return $root.armnnSerializer.LogSoftmaxLayer.decode(e,r);case 53:return $root.armnnSerializer.ComparisonLayer.decode(e,r);case 54:return $root.armnnSerializer.StandInLayer.decode(e,r);case 55:return $root.armnnSerializer.ElementwiseUnaryLayer.decode(e,r);case 56:return $root.armnnSerializer.TransposeLayer.decode(e,r);case 57:return $root.armnnSerializer.QLstmLayer.decode(e,r);case 58:return $root.armnnSerializer.FillLayer.decode(e,r);case 59:return $root.armnnSerializer.RankLayer.decode(e,r)}}static decodeText(e,r,t){switch(t){case"ActivationLayer":return $root.armnnSerializer.ActivationLayer.decodeText(e,r);case"AdditionLayer":return $root.armnnSerializer.AdditionLayer.decodeText(e,r);case"BatchToSpaceNdLayer":return $root.armnnSerializer.BatchToSpaceNdLayer.decodeText(e,r);case"BatchNormalizationLayer":return $root.armnnSerializer.BatchNormalizationLayer.decodeText(e,r);case"ConstantLayer":return $root.armnnSerializer.ConstantLayer.decodeText(e,r);case"Convolution2dLayer":return $root.armnnSerializer.Convolution2dLayer.decodeText(e,r);case"DepthwiseConvolution2dLayer":return $root.armnnSerializer.DepthwiseConvolution2dLayer.decodeText(e,r);case"FullyConnectedLayer":return $root.armnnSerializer.FullyConnectedLayer.decodeText(e,r);case"InputLayer":return $root.armnnSerializer.InputLayer.decodeText(e,r);case"MultiplicationLayer":return $root.armnnSerializer.MultiplicationLayer.decodeText(e,r);case"OutputLayer":return $root.armnnSerializer.OutputLayer.decodeText(e,r);case"PermuteLayer":return $root.armnnSerializer.PermuteLayer.decodeText(e,r);case"Pooling2dLayer":return $root.armnnSerializer.Pooling2dLayer.decodeText(e,r);case"ReshapeLayer":return $root.armnnSerializer.ReshapeLayer.decodeText(e,r);case"SoftmaxLayer":return $root.armnnSerializer.SoftmaxLayer.decodeText(e,r);case"SpaceToBatchNdLayer":return $root.armnnSerializer.SpaceToBatchNdLayer.decodeText(e,r);case"DivisionLayer":return $root.armnnSerializer.DivisionLayer.decodeText(e,r);case"MinimumLayer":return $root.armnnSerializer.MinimumLayer.decodeText(e,r);case"EqualLayer":return $root.armnnSerializer.EqualLayer.decodeText(e,r);case"MaximumLayer":return $root.armnnSerializer.MaximumLayer.decodeText(e,r);case"NormalizationLayer":return $root.armnnSerializer.NormalizationLayer.decodeText(e,r);case"PadLayer":return $root.armnnSerializer.PadLayer.decodeText(e,r);case"RsqrtLayer":return $root.armnnSerializer.RsqrtLayer.decodeText(e,r);case"FloorLayer":return $root.armnnSerializer.FloorLayer.decodeText(e,r);case"GreaterLayer":return $root.armnnSerializer.GreaterLayer.decodeText(e,r);case"ResizeBilinearLayer":return $root.armnnSerializer.ResizeBilinearLayer.decodeText(e,r);case"SubtractionLayer":return $root.armnnSerializer.SubtractionLayer.decodeText(e,r);case"StridedSliceLayer":return $root.armnnSerializer.StridedSliceLayer.decodeText(e,r);case"GatherLayer":return $root.armnnSerializer.GatherLayer.decodeText(e,r);case"MeanLayer":return $root.armnnSerializer.MeanLayer.decodeText(e,r);case"MergerLayer":return $root.armnnSerializer.MergerLayer.decodeText(e,r);case"L2NormalizationLayer":return $root.armnnSerializer.L2NormalizationLayer.decodeText(e,r);case"SplitterLayer":return $root.armnnSerializer.SplitterLayer.decodeText(e,r);case"DetectionPostProcessLayer":return $root.armnnSerializer.DetectionPostProcessLayer.decodeText(e,r);case"LstmLayer":return $root.armnnSerializer.LstmLayer.decodeText(e,r);case"QuantizedLstmLayer":return $root.armnnSerializer.QuantizedLstmLayer.decodeText(e,r);case"QuantizeLayer":return $root.armnnSerializer.QuantizeLayer.decodeText(e,r);case"DequantizeLayer":return $root.armnnSerializer.DequantizeLayer.decodeText(e,r);case"MergeLayer":return $root.armnnSerializer.MergeLayer.decodeText(e,r);case"SwitchLayer":return $root.armnnSerializer.SwitchLayer.decodeText(e,r);case"ConcatLayer":return $root.armnnSerializer.ConcatLayer.decodeText(e,r);case"SpaceToDepthLayer":return $root.armnnSerializer.SpaceToDepthLayer.decodeText(e,r);case"PreluLayer":return $root.armnnSerializer.PreluLayer.decodeText(e,r);case"TransposeConvolution2dLayer":return $root.armnnSerializer.TransposeConvolution2dLayer.decodeText(e,r);case"ResizeLayer":return $root.armnnSerializer.ResizeLayer.decodeText(e,r);case"StackLayer":return $root.armnnSerializer.StackLayer.decodeText(e,r);case"AbsLayer":return $root.armnnSerializer.AbsLayer.decodeText(e,r);case"ArgMinMaxLayer":return $root.armnnSerializer.ArgMinMaxLayer.decodeText(e,r);case"SliceLayer":return $root.armnnSerializer.SliceLayer.decodeText(e,r);case"DepthToSpaceLayer":return $root.armnnSerializer.DepthToSpaceLayer.decodeText(e,r);case"InstanceNormalizationLayer":return $root.armnnSerializer.InstanceNormalizationLayer.decodeText(e,r);case"LogSoftmaxLayer":return $root.armnnSerializer.LogSoftmaxLayer.decodeText(e,r);case"ComparisonLayer":return $root.armnnSerializer.ComparisonLayer.decodeText(e,r);case"StandInLayer":return $root.armnnSerializer.StandInLayer.decodeText(e,r);case"ElementwiseUnaryLayer":return $root.armnnSerializer.ElementwiseUnaryLayer.decodeText(e,r);case"TransposeLayer":return $root.armnnSerializer.TransposeLayer.decodeText(e,r);case"QLstmLayer":return $root.armnnSerializer.QLstmLayer.decodeText(e,r);case"FillLayer":return $root.armnnSerializer.FillLayer.decodeText(e,r);case"RankLayer":return $root.armnnSerializer.RankLayer.decodeText(e,r)}}},$root.armnnSerializer.AnyLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AnyLayer;return t.layer=e.union(r,4,$root.armnnSerializer.Layer.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AnyLayer;return t.layer=$root.armnnSerializer.Layer.decodeText(e,r.layer,r.layer_type),t}},$root.armnnSerializer.FeatureCompatibilityVersions=class{static decode(e,r){const t=new $root.armnnSerializer.FeatureCompatibilityVersions;return t.bindingIdsScheme=e.uint32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.FeatureCompatibilityVersions;return t.bindingIdsScheme=e.value(r.bindingIdsScheme,0),t}},$root.armnnSerializer.SerializedGraph=class{static identifier(e){return e.identifier("ARMN")}static create(e){return $root.armnnSerializer.SerializedGraph.decode(e,e.root)}static createText(e){return $root.armnnSerializer.SerializedGraph.decodeText(e,e.root)}static decode(e,r){const t=new $root.armnnSerializer.SerializedGraph;return t.layers=e.tableArray(r,4,$root.armnnSerializer.AnyLayer.decode),t.inputIds=e.typedArray(r,6,Int32Array),t.outputIds=e.typedArray(r,8,Int32Array),t.featureVersions=e.table(r,10,$root.armnnSerializer.FeatureCompatibilityVersions.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SerializedGraph;return t.layers=e.objectArray(r.layers,$root.armnnSerializer.AnyLayer.decodeText),t.inputIds=e.typedArray(r.inputIds,Int32Array),t.outputIds=e.typedArray(r.outputIds,Int32Array),t.featureVersions=e.object(r.featureVersions,$root.armnnSerializer.FeatureCompatibilityVersions.decodeText),t}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn.js new file mode 100644 index 0000000000000000000000000000000000000000..d86f5dda02bb65f0269e1f03eeedc04b53fd6c08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/armnn.js @@ -0,0 +1 @@ +var armnn=armnn||{},base=base||require("./base"),flatbuffers=flatbuffers||require("./flatbuffers"),long=long||{Long:require("long")};armnn.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("armnn"==e)return!0;if("json"===e){const e=t.text;if(-1!==e.indexOf('"layers"',0)&&-1!==e.indexOf('"layer_type"',0))return!0}return!1}open(t,e){return e.require("./armnn-schema").then((n=>{armnn.schema=flatbuffers.get("armnn").armnnSerializer;const a=t.identifier;let r=null;try{switch(a.split(".").pop().toLowerCase()){case"armnn":{const e=new flatbuffers.Reader(t.buffer);r=armnn.schema.SerializedGraph.create(e);break}case"json":{const e=new flatbuffers.TextReader(t.text);r=armnn.schema.SerializedGraph.createText(e);break}}}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new armnn.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}return armnn.Metadata.open(e).then((t=>{try{return new armnn.Model(t,r)}catch(t){const e=t&&t.message?t.message:t.toString();throw new new armnn.Error(e.replace(/\.$/,"")+" in '"+a+"'.")}}))}))}},armnn.Model=class{constructor(t,e){this._graphs=[],this._graphs.push(new armnn.Graph(t,e))}get format(){return"Arm NN"}get description(){return""}get graphs(){return this._graphs}},armnn.Graph=class{constructor(t,e){this._name="",this._nodes=[],this._inputs=[],this._outputs=[];const n={};for(let t=0;tt.limit)return r.push("..."),r;switch(t.dataType){case"float16":r.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":r.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"quint8":r.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"qint16":r.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++;break;case"int32":r.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"boolean":r.push(t.data.getInt8(t.index)),t.index+=1,t.count++}}else for(let n=0;nt.limit)return r.push("..."),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}},armnn.TensorType=class{constructor(t){const e=t.dataType;switch(e){case 0:this._dataType="float16";break;case 1:this._dataType="float32";break;case 2:this._dataType="quint8";break;case 3:this._dataType="int32";break;case 4:this._dataType="boolean";break;case 5:this._dataType="qint16";break;case 6:this._dataType="quint8";break;case 7:this._dataType="qint16";break;default:throw new armnn.Error("Unknown data type '"+JSON.stringify(e)+"'.")}this._shape=new armnn.TensorShape(t.dimensions)}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},armnn.TensorShape=class{constructor(t){this._dimensions=Array.from(t)}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},armnn.Metadata=class{static open(t){return armnn.Metadata._metadata?Promise.resolve(armnn.Metadata._metadata):t.request(null,"armnn-metadata.json","utf-8").then((t=>(armnn.Metadata._metadata=new armnn.Metadata(t),armnn.Metadata._metadata))).catch((()=>(armnn.Metadata._metadata=new armnn.Metadata(null),armnn.Metadata._metadata)))}constructor(t){if(this._map={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]}attribute(t,e){const n=this.type(t);if(n){let t=n.attributeMap;if(!t){if(t={},n.attributes)for(const e of n.attributes)t[e.name]=e;n.attributeMap=t}const a=t[e];if(a)return a}return null}},armnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading Arm NN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=armnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/barracuda.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/barracuda.js new file mode 100644 index 0000000000000000000000000000000000000000..2b6b6208aae5693c8f9dc719cb34a3e617797919 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/barracuda.js @@ -0,0 +1 @@ +var barracuda=barracuda||{},base=base||require("./base"),long=long||{Long:require("long")};barracuda.ModelFactory=class{match(t){if("nn"===t.identifier.split(".").pop().toLowerCase()){const e=t.buffer;if(e.length>12&&e[0]<=16&&e.subarray(1,8).every((t=>0==t)))return!0}return!1}open(t){return barracuda.Metadata.open().then((e=>{try{const s=new barracuda.NNModel(t.buffer);return new barracuda.Model(e,s)}catch(e){const s=t.identifier.toLowerCase(),r=e&&e.message?e.message:e.toString();throw new barracuda.Error(r.replace(/\.$/,"")+" in '"+s+"'.")}}))}},barracuda.Model=class{constructor(t,e){this._version=e.version.toString(),this._graphs=[new barracuda.Graph(t,e)]}get format(){return"Barracuda v"+this._version}get graphs(){return this._graphs}},barracuda.Graph=class{constructor(t,e){this._inputs=[],this._outputs=[],this._nodes=[];for(const t of e.inputs)this._inputs.push(new barracuda.Parameter(t.name,[new barracuda.Argument(t.name,new barracuda.TensorType(4,new barracuda.TensorShape(t.shape)))]));for(const t of e.outputs)this._outputs.push(new barracuda.Parameter(t,[new barracuda.Argument(t)]));const s=[],r=new Map;for(const t of e.layers)if(255!==t.type||t.inputs.length>0)s.push(t);else for(const e of t.tensors)r.set(e.name,new barracuda.Tensor(e));for(const e of s)this._nodes.push(new barracuda.Node(t,e,r))}get name(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},barracuda.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},barracuda.Argument=class{constructor(t,e,s){this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},barracuda.Node=class{constructor(t,e,s){this._name=e.name||"",this._metadata=t.type(e.type)||{name:e.type.toString()},this._type=this._metadata.name,this._inputs=[],this._outputs=[],this._attributes=[];const r=Array.prototype.slice.call(this._metadata.inputs||["input"]);if(this._metadata.inputs&&1===this._metadata.inputs.length&&"inputs"===this._metadata.inputs[0])this._inputs.push(new barracuda.Parameter("inputs",e.inputs.map((t=>{const e=s.has(t)?s.get(t):null;return new barracuda.Argument(t,e?e.type:null,e)}))));else if(e.inputs)for(let t=0;t0?r.shift():t.toString(),[new barracuda.Argument(a,i?i.type:null,i)]))}if(e.tensors)for(let t=0;t0?r.shift():t.toString(),[new barracuda.Argument(s.name,a.type,a)]))}if(void 0!==e.inputs&&this._outputs.push(new barracuda.Parameter("output",[new barracuda.Argument(this._name)])),!barracuda.Activation[e.activation])throw new barracuda.Error("Unknown activation '"+e.activation+"'.");"Activation"===this._type?this._type=barracuda.Activation[e.activation]:0!==e.activation&&(this._chain=[new barracuda.Node(t,{type:50,activation:e.activation},s)]);const a=(t,e,s,r)=>{void 0!==s&&(Array.isArray(r)&&Array.isArray(s)&&s.length==r.length&&s.every(((t,e)=>t===r[e]))||"function"==typeof r&&r(s)||r!==s&&this._attributes.push(new barracuda.Attribute(t,e,s)))};a("strides","int32[]",e.strides,[]),a("pads","int32[]",e.pads,(t=>Array.isArray(t)&&(t.every((t=>0===t))||t.every((t=>-1===t))))),a("size","int32[]",e.pool_size,[]),a("alpha","float32",e.alpha,1),a("beta","float32",e.beta,0),a("axis","int32",e.axis,-1)}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}},barracuda.Attribute=class{constructor(t,e,s){this._name=t,this._type=e,this._value=s}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return!0}},barracuda.Tensor=class{constructor(t){this._type=new barracuda.TensorType(t.itemsize,new barracuda.TensorShape(t.shape)),this._data=t.data}get kind(){return""}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape||this._type.shape.dimensions&&0==this._type.shape.dimensions.length)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const s=0==t.shape.length?[1]:t.shape,r=[],a=s[e];if(e==s.length-1)for(let e=0;et.limit)return r.push("..."),r;switch(this._type.dataType){case"float32":r.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++}}else for(let s=0;st.limit)return r.push("..."),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}},barracuda.TensorType=class{constructor(t,e){switch(t){case 4:this._dataType="float32";break;default:throw new barracuda.Error("Unsupported data type size '"+t.toString()+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},barracuda.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},barracuda.NNModel=class{constructor(t){const e=new barracuda.BinaryReader(t);this._version=e.int32(),e.int32(),this._inputs=[];const s=e.int32();for(let t=0;tthis._buffer.length)throw new barracuda.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}bytes(t,e){const s=this._position+t,r=s+e;if(r>this._buffer.length)throw new barracuda.Error("Expected "+(r-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.");return this._buffer.slice(s,r)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int32s(){const t=[],e=this.int32();for(let s=0;s>>3){case 1:e.name=t.string();break;case 2:e.subModules.push($root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32()));break;case 3:e.weight=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 4:e.bias=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 5:e.preModules.push(t.string());break;case 6:e.nextModules.push(t.string());break;case 7:e.moduleType=t.string();break;case 8:t.pair(e.attr,(()=>t.string()),(()=>$root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32())));break;case 9:e.version=t.string();break;case 10:e.train=t.bool();break;case 11:e.namePostfix=t.string();break;case 12:e.id=t.int32();break;case 13:e.inputShape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;case 14:e.outputShape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;case 15:e.hasParameters=t.bool();break;case 16:e.parameters.push($root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32()));break;case 17:e.isMklInt8Enabled=t.bool();break;case 18:e.inputDimMasks=t.int32();break;case 19:e.inputScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;case 20:e.outputDimMasks=t.int32();break;case 21:e.outputScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;case 22:e.weightDimMasks=t.int32();break;case 23:e.weightScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.name="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.weight=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.bias=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.moduleType="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.version="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.train=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.namePostfix="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.inputShape=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.outputShape=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.hasParameters=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.isMklInt8Enabled=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.inputDimMasks=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.outputDimMasks=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.weightDimMasks=0,$root.com.intel.analytics.bigdl.serialization.VarFormat={EMPTY_FORMAT:0,DEFAULT:1,ONE_D:2,IN_OUT:3,OUT_IN:4,IN_OUT_KW_KH:5,OUT_IN_KW_KH:6,GP_OUT_IN_KW_KH:7,GP_IN_OUT_KW_KH:8,OUT_IN_KT_KH_KW:9},$root.com.intel.analytics.bigdl.serialization.InitMethodType={EMPTY_INITIALIZATION:0,RANDOM_UNIFORM:1,RANDOM_UNIFORM_PARAM:2,RANDOM_NORMAL:3,ZEROS:4,ONES:5,CONST:6,XAVIER:7,BILINEARFILLER:8},$root.com.intel.analytics.bigdl.serialization.RegularizerType={L1L2Regularizer:0,L1Regularizer:1,L2Regularizer:2},$root.com.intel.analytics.bigdl.serialization.InputDataFormat={NCHW:0,NHWC:1},$root.com.intel.analytics.bigdl.serialization.TensorType={DENSE:0,QUANT:1},$root.com.intel.analytics.bigdl.serialization.InitMethod=class{constructor(){this.data=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.InitMethod,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.methodType=t.int32();break;case 2:e.data=t.doubles(e.data,a);break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.InitMethod.prototype.methodType=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor=class{constructor(){this.size=[],this.stride=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.BigDLTensor,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.datatype=t.int32();break;case 2:e.size=t.array(e.size,(()=>t.int32()),a);break;case 3:e.stride=t.array(e.stride,(()=>t.int32()),a);break;case 4:e.offset=t.int32();break;case 5:e.dimension=t.int32();break;case 6:e.nElements=t.int32();break;case 7:e.isScalar=t.bool();break;case 8:e.storage=$root.com.intel.analytics.bigdl.serialization.TensorStorage.decode(t,t.uint32());break;case 9:e.id=t.int32();break;case 10:e.tensorType=t.int32();break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.offset=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.dimension=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.nElements=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.isScalar=!1,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.storage=null,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.tensorType=0,$root.com.intel.analytics.bigdl.serialization.TensorStorage=class{constructor(){this.float_data=[],this.double_data=[],this.bool_data=[],this.string_data=[],this.int_data=[],this.long_data=[],this.bytes_data=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.TensorStorage,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.datatype=t.int32();break;case 2:e.float_data=t.floats(e.float_data,a);break;case 3:e.double_data=t.doubles(e.double_data,a);break;case 4:e.bool_data=t.array(e.bool_data,(()=>t.bool()),a);break;case 5:e.string_data.push(t.string());break;case 6:e.int_data=t.array(e.int_data,(()=>t.int32()),a);break;case 7:e.long_data=t.array(e.long_data,(()=>t.int64()),a);break;case 8:e.bytes_data.push(t.bytes());break;case 9:e.id=t.int32();break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.TensorStorage.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.TensorStorage.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.Regularizer=class{constructor(){this.regularData=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.Regularizer,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.regularizerType=t.int32();break;case 2:e.regularData=t.doubles(e.regularData,a);break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.Regularizer.prototype.regularizerType=0,$root.com.intel.analytics.bigdl.serialization.DataType={INT32:0,INT64:1,FLOAT:2,DOUBLE:3,STRING:4,BOOL:5,CHAR:6,SHORT:7,BYTES:8,REGULARIZER:9,TENSOR:10,VARIABLE_FORMAT:11,INITMETHOD:12,MODULE:13,NAME_ATTR_LIST:14,ARRAY_VALUE:15,DATA_FORMAT:16,CUSTOM:17,SHAPE:18},$root.com.intel.analytics.bigdl.serialization.AttrValue=class{constructor(){}get value(){return $root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet=$root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet||new Set(["int32Value","int64Value","floatValue","doubleValue","stringValue","boolValue","regularizerValue","tensorValue","variableFormatValue","initMethodValue","bigDLModuleValue","nameAttrListValue","arrayValue","dataFormatValue","customValue","shape"]),Object.keys(this).find((t=>$root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet.has(t)&&null!=this[t]))}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.AttrValue,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.dataType=t.int32();break;case 2:e.subType=t.string();break;case 3:e.int32Value=t.int32();break;case 4:e.int64Value=t.int64();break;case 5:e.floatValue=t.float();break;case 6:e.doubleValue=t.double();break;case 7:e.stringValue=t.string();break;case 8:e.boolValue=t.bool();break;case 9:e.regularizerValue=$root.com.intel.analytics.bigdl.serialization.Regularizer.decode(t,t.uint32());break;case 10:e.tensorValue=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 11:e.variableFormatValue=t.int32();break;case 12:e.initMethodValue=$root.com.intel.analytics.bigdl.serialization.InitMethod.decode(t,t.uint32());break;case 13:e.bigDLModuleValue=$root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32());break;case 14:e.nameAttrListValue=$root.com.intel.analytics.bigdl.serialization.NameAttrList.decode(t,t.uint32());break;case 15:e.arrayValue=$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.decode(t,t.uint32());break;case 16:e.dataFormatValue=t.int32();break;case 17:e.customValue=$root.google.protobuf.Any.decode(t,t.uint32());break;case 18:e.shape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.AttrValue.prototype.dataType=0,$root.com.intel.analytics.bigdl.serialization.AttrValue.prototype.subType="",$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue=class{constructor(){this.i32=[],this.i64=[],this.flt=[],this.dbl=[],this.str=[],this.boolean=[],this.Regularizer=[],this.tensor=[],this.variableFormat=[],this.initMethod=[],this.bigDLModule=[],this.nameAttrList=[],this.dataFormat=[],this.custom=[],this.shape=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.size=t.int32();break;case 2:e.datatype=t.int32();break;case 3:e.i32=t.array(e.i32,(()=>t.int32()),a);break;case 4:e.i64=t.array(e.i64,(()=>t.int64()),a);break;case 5:e.flt=t.floats(e.flt,a);break;case 6:e.dbl=t.doubles(e.dbl,a);break;case 7:e.str.push(t.string());break;case 8:e.boolean=t.array(e.boolean,(()=>t.bool()),a);break;case 9:e.Regularizer.push($root.com.intel.analytics.bigdl.serialization.Regularizer.decode(t,t.uint32()));break;case 10:e.tensor.push($root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32()));break;case 11:e.variableFormat=t.array(e.variableFormat,(()=>t.int32()),a);break;case 12:e.initMethod.push($root.com.intel.analytics.bigdl.serialization.InitMethod.decode(t,t.uint32()));break;case 13:e.bigDLModule.push($root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32()));break;case 14:e.nameAttrList.push($root.com.intel.analytics.bigdl.serialization.NameAttrList.decode(t,t.uint32()));break;case 15:e.dataFormat=t.array(e.dataFormat,(()=>t.int32()),a);break;case 16:e.custom.push($root.google.protobuf.Any.decode(t,t.uint32()));break;case 17:e.shape.push($root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.prototype.size=0,$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.NameAttrList=class{constructor(){this.attr={}}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.NameAttrList,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.name=t.string();break;case 2:t.pair(e.attr,(()=>t.string()),(()=>$root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32())));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.NameAttrList.prototype.name="",$root.com.intel.analytics.bigdl.serialization.Shape=class{constructor(){this.shapeValue=[],this.shape=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.Shape,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.shapeType=t.int32();break;case 2:e.ssize=t.int32();break;case 3:e.shapeValue=t.array(e.shapeValue,(()=>t.int32()),a);break;case 4:e.shape.push($root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.Shape.prototype.shapeType=0,$root.com.intel.analytics.bigdl.serialization.Shape.prototype.ssize=0,$root.com.intel.analytics.bigdl.serialization.Shape.ShapeType={SINGLE:0,MULTI:1},$root.google={},$root.google.protobuf={},$root.google.protobuf.Any=class{constructor(){}static decode(t,a){const e=new $root.google.protobuf.Any,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.type_url=t.string();break;case 2:e.value=t.bytes();break;default:t.skipType(7&a)}}return e}},$root.google.protobuf.Any.prototype.type_url="",$root.google.protobuf.Any.prototype.value=new Uint8Array([]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bigdl.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bigdl.js new file mode 100644 index 0000000000000000000000000000000000000000..7387dee91d178e118a44b1a55c097f4adce7a4b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bigdl.js @@ -0,0 +1 @@ +var bigdl=bigdl||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");bigdl.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"==e||"bigdl"==e){const e=t.tags("pb");if(e.has(2)&&e.has(7)&&e.has(8)&&e.has(9)&&e.has(10)&&e.has(11)&&e.has(12))return!0}}open(t,e){return e.require("./bigdl-proto").then((()=>bigdl.Metadata.open(e).then((a=>{const i=t.identifier;try{bigdl.proto=protobuf.get("bigdl").com.intel.analytics.bigdl.serialization;const e=protobuf.Reader.create(t.buffer),i=bigdl.proto.BigDLModule.decode(e);return new bigdl.Model(a,i)}catch(t){e.exception(t,!1);const a=t&&t.message?t.message:t.toString();throw new bigdl.Error(a.replace(/\.$/,"")+" in '"+i+"'.")}}))))}},bigdl.Model=class{constructor(t,e){this._version=e&&e.version?e.version:"",this._graphs=[new bigdl.Graph(t,e)]}get format(){return"BigDL"+(this._version?" v"+this._version:"")}get graphs(){return this._graphs}},bigdl.Graph=class{constructor(t,e){this._type=e.moduleType,this._inputs=[],this._outputs=[],this._nodes=[],this._loadModule(t,"",e)}_loadModule(t,e,a){switch(a.moduleType){case"com.intel.analytics.bigdl.nn.StaticGraph":this._loadStaticGraph(t,e,a);break;case"com.intel.analytics.bigdl.nn.Sequential":this._loadSequential(t,e,a);break;case"com.intel.analytics.bigdl.nn.Input":this._inputs.push(new bigdl.Parameter(a.name,[new bigdl.Argument(a.name)]));break;default:this._nodes.push(new bigdl.Node(t,e,a))}}_loadSequential(t,e,a){e=e.length>0?e+"."+a.namePostfix:a.namePostfix;for(const i of a.subModules)this._loadModule(t,e,i)}_loadStaticGraph(t,e,a){e=e.length>0?e+"."+a.namePostfix:a.namePostfix;for(const i of a.subModules)this._loadModule(t,e,i)}get groups(){return this._groups||!1}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},bigdl.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},bigdl.Argument=class{constructor(t,e,a){if("string"!=typeof t)throw new bigdl.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=a||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},bigdl.Node=class{constructor(t,e,a){this._metadata=t,this._group=e,this._type=a.moduleType.split(".").pop(),this._name=a.name,this._attributes=[],this._inputs=[],this._outputs=[],this._inputs.push(new bigdl.Parameter("input",a.preModules.map((t=>new bigdl.Argument(t,null,null)))));const i=t.type(this.type),r=i&&i.inputs?i.inputs.slice():[];if(r.shift(),a.weight&&(r.shift(),this._inputs.push(new bigdl.Parameter("weight",[new bigdl.Argument("",null,new bigdl.Tensor(a.weight))]))),a.bias&&(r.shift(),this._inputs.push(new bigdl.Parameter("bias",[new bigdl.Argument("",null,new bigdl.Tensor(a.bias))]))),a.parameters&&a.parameters.length>0)for(const t of a.parameters){const e=r.shift(),a=e?e.name:this._inputs.length.toString();this._inputs.push(new bigdl.Parameter(a,[new bigdl.Argument("",null,new bigdl.Tensor(t))]))}for(const e of Object.keys(a.attr)){const i=a.attr[e];"module_numerics"!==e&&"module_tags"!==e&&(i.dataType!==bigdl.proto.DataType.TENSOR?i.dataType===bigdl.proto.DataType.REGULARIZER&&void 0===i.value||(i.dataType!==bigdl.proto.DataType.ARRAY_VALUE||i.arrayValue.datatype!==bigdl.proto.DataType.TENSOR?this._attributes.push(new bigdl.Attribute(t.attribute(this._type,e),e,i)):this._inputs.push(new bigdl.Parameter(e,i.arrayValue.tensor.map((t=>new bigdl.Argument("",null,new bigdl.Tensor(t))))))):i.value&&this._inputs.push(new bigdl.Parameter(e,[new bigdl.Argument("",null,new bigdl.Tensor(i.tensorValue))])))}const s=this._name||this._type+a.namePostfix;this._outputs.push(new bigdl.Parameter("output",[new bigdl.Argument(s,null,null)]))}get group(){return this._group}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},bigdl.Attribute=class{constructor(t,e,a){switch(this._name=e,a.dataType){case bigdl.proto.DataType.INT32:this._type="int32",this._value=a.int32Value;break;case bigdl.proto.DataType.FLOAT:this._type="float32",this._value=a.floatValue;break;case bigdl.proto.DataType.DOUBLE:this._type="float64",this._value=a.doubleValue;break;case bigdl.proto.DataType.BOOL:this._type="boolean",this._value=a.boolValue;break;case bigdl.proto.DataType.REGULARIZER:this._value=a.value;break;case bigdl.proto.DataType.MODULE:this._value=a.bigDLModule;break;case bigdl.proto.DataType.NAME_ATTR_LIST:this._value=a.nameAttrListValue;break;case bigdl.proto.DataType.ARRAY_VALUE:switch(a.arrayValue.datatype){case bigdl.proto.DataType.INT32:this._type="int32[]",this._value=a.arrayValue.i32;break;case bigdl.proto.DataType.FLOAT:this._type="float32[]",this._value=a.arrayValue.flt;break;case bigdl.proto.DataType.STRING:this._type="string[]",this._value=a.arrayValue.str;break;case bigdl.proto.DataType.TENSOR:this._type="tensor[]",this._value=a.arrayValue.tensor;break;default:throw new bigdl.Error("Unsupported attribute array data type '"+a.arrayValue.datatype+"'.")}break;case bigdl.proto.DataType.DATA_FORMAT:switch(this._dataType="InputDataFormat",a.dataFormatValue){case 0:this._value="NCHW";break;case 1:this._value="NHWC"}break;default:throw new bigdl.Error("Unsupported attribute data type '"+a.dataType+"'.")}}get type(){return""}get name(){return this._name}get value(){return this._value}get visible(){return!0}},bigdl.Tensor=class{constructor(t){this._type=new bigdl.TensorType(t.datatype,new bigdl.TensorShape(t.size))}get kind(){return"Parameter"}get type(){return this._type}get state(){return"Not supported."}get value(){return null}toString(){return""}},bigdl.TensorType=class{constructor(t,e){switch(t){case bigdl.proto.DataType.FLOAT:this._dataType="float32";break;case bigdl.proto.DataType.DOUBLE:this._dataType="float64";break;default:throw new bigdl.Error("Unsupported tensor type '"+t+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},bigdl.TensorShape=class{constructor(t){this._dimensions=t.map((t=>t&&long.Long.isLong(t)?t.toNumber():t))}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},bigdl.Metadata=class{static open(t){return bigdl.Metadata._metadata?Promise.resolve(bigdl.Metadata._metadata):t.request(null,"bigdl-metadata.json","utf-8").then((t=>(bigdl.Metadata._metadata=new bigdl.Metadata(t),bigdl.Metadata._metadata))).catch((()=>(bigdl.Metadata._metadata=new bigdl.Metadata(null),bigdl.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},bigdl.Error=class extends Error{constructor(t){super(t),this.name="Error loading BigDL model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=bigdl.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bson.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bson.js new file mode 100644 index 0000000000000000000000000000000000000000..d17823cebee6fc4de98507e35bd55779f0d8720a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/bson.js @@ -0,0 +1 @@ +var bson={},long=long||{Long:require("long")};bson.Reader=class{constructor(t){this._asciiDecoder=new TextDecoder("ascii"),this._utf8Decoder=new TextDecoder("utf-8"),this._buffer=t,this._position=0,this._view=new DataView(t.buffer,t.byteOffset,t.byteLength)}read(){return this.document()}document(t){const i=this._position,e=this.int32();if(e<5||i+e>this._buffer.length||0!=this._buffer[i+e-1])throw new bson.Reader("Invalid BSON size.");const s=t?[]:{};let n=0;for(;;){const i=this.byte();if(0==i)break;const e=this.cstring();let o=null;switch(i){case 1:o=this.double();break;case 2:o=this.string();break;case 3:o=this.document(!1);break;case 4:o=this.document(!0);break;case 5:o=this.binary();break;case 8:o=this.boolean();break;case 10:o=null;break;case 16:o=this.int32();break;case 17:o=this.uint64();break;case 18:o=this.int64();break;default:throw new bson.Error("Unknown value type '"+i+"'.")}if(t){if(n!==parseInt(e,10))throw new bson.Error("Invalid array index '"+e+"'.");s.push(o),n++}else s[e]=o}return s}cstring(){const t=this._buffer.indexOf(0,this._position),i=this._asciiDecoder.decode(this._buffer.subarray(this._position,t));return this._position=t+1,i}string(){const t=this.int32()+this._position-1,i=this._utf8Decoder.decode(this._buffer.subarray(this._position,t));if(this._position=t,"0x00"!=this.byte())throw new bson.Error("String missing terminal 0.");return i}binary(){const t=this.int32(),i=this.byte(),e=this._buffer.subarray(this._position,this._position+t);switch(this._position+=t,i){case 0:return e;default:throw new bson.Error("Unknown binary subtype '"+i+"'.")}}boolean(){const t=this.byte();switch(t){case 0:return!1;case 1:return!0;default:throw new bson.Error("Invalid boolean value '"+t+"'.")}}byte(){return this._buffer[this._position++]}int32(){const t=this._view.getInt32(this._position,!0);return this._position+=4,t}int64(){const t=this._view.getUint32(this._position,!0),i=this._view.getUint32(this._position+4,!0);return this._position+=8,new long.Long(t,i,!1).toNumber()}uint64(){const t=this._view.getUint32(this._position,!0),i=this._view.getUint32(this._position+4,!0);return this._position+=8,new long.Long(t,i,!0).toNumber()}},bson.Error=class extends Error{constructor(t){super(t),this.name="BSON Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Reader=bson.Reader); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..723d9f6529edec34f229f8386d9602fae4c4db00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false},{"name":"pad","default":[0]},{"name":"kernel_size","default":[]},{"name":"stride","default":[1]},{"name":"dilation","default":[]},{"name":"group","default":1}]}},{"name":"Deconvolution","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false},{"name":"pad","default":[]},{"name":"kernel_size","default":[]},{"name":"stride","default":[]},{"name":"dilation","default":[]}]}},{"name":"DepthwiseConvolution","schema":{"category":"Layer","attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}],"inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"ConvolutionDepthwise","schema":{"category":"Layer","attributes":[{"name":"pad","default":[0]},{"name":"kernel_size","default":[]},{"name":"stride","default":[1]},{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}],"inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"InnerProduct","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}]}},{"name":"Scale","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"filler","visible":false},{"name":"bias_term","visible":false},{"name":"bias_filler","visible":false}]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[{"name":"dropout_ratio","default":0.5}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Flatten","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LRN","schema":{"category":"Normalization","attributes":[{"name":"local_size","type":"uint32","default":5},{"name":"alpha","type":"float32","default":0.0001},{"name":"beta","type":"float32","default":0.75}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"BatchNorm","schema":{"category":"Normalization","attributes":[{"name":"use_global_stats","visible":false},{"name":"eps","default":0.00001}],"inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"mean"},{"name":"variance"}],"outputs":[{"name":"output"}]}},{"name":"BN","schema":{"category":"Normalization","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sigmoid","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxLoss","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxWithLoss","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"ContrastiveLossParameter","schema":{"attributes":[{"name":"margin","default":1},{"name":"legacy_version","default":false}]}},{"name":"ReLU","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"PReLU","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"slope"}],"outputs":[{"name":"output"}]}},{"name":"Concat","schema":{"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Split","schema":{"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"Eltwise","schema":{"attributes":[{"name":"operation","default":1}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"category":"Pool","attributes":[{"name":"pool","default":0}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Crop","schema":{"category":"Data","inputs":[{"name":"data"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Data","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"DummyData","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"AnnotatedData","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"HDF5Data","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"ImageData","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"WindowData","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"Slice","schema":{"category":"Tensor","attributes":[{"name":"axis","default":1}],"inputs":[{"name":"input"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"EuclideanLoss","schema":{"inputs":[{"name":"predictions"},{"name":"targets"}],"outputs":[{"name":"output"}]}},{"name":"Accuracy","schema":{"inputs":[{"name":"predictions"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"LSTM","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"h_0"},{"name":"c_0"}],"outputs":[{"name":"output"},{"name":"h_T"},{"name":"c_T"}],"attributes":[{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"data"}],"outputs":[{"name":"reshaped"}]}},{"name":"ColorConv","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Permute","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Parameter","schema":{"outputs":[{"name":"output"}]}},{"name":"Python","schema":{}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..c753282efbb4dc560cd6465bdb8490dbfabd5775 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("caffe");$root.caffe={},$root.caffe.BlobShape=class{constructor(){this.dim=[]}static decode(e,a){const r=new $root.caffe.BlobShape,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.dim=e.array(r.dim,(()=>e.int64()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobShape;for(e.start();!e.end();){const r=e.tag();switch(r){case"dim":e.array(a.dim,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.BlobProto=class{constructor(){this.data=[],this.diff=[],this.double_data=[],this.double_diff=[]}static decode(e,a){const r=new $root.caffe.BlobProto,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 7:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;case 5:r.data=e.floats(r.data,a);break;case 6:r.diff=e.floats(r.diff,a);break;case 8:r.double_data=e.doubles(r.double_data,a);break;case 9:r.double_diff=e.doubles(r.double_diff,a);break;case 1:r.num=e.int32();break;case 2:r.channels=e.int32();break;case 3:r.height=e.int32();break;case 4:r.width=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobProto;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;case"data":e.array(a.data,(()=>e.float()));break;case"diff":e.array(a.diff,(()=>e.float()));break;case"double_data":e.array(a.double_data,(()=>e.float()));break;case"double_diff":e.array(a.double_diff,(()=>e.float()));break;case"num":a.num=e.integer();break;case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.BlobProto.prototype.shape=null,$root.caffe.BlobProto.prototype.num=0,$root.caffe.BlobProto.prototype.channels=0,$root.caffe.BlobProto.prototype.height=0,$root.caffe.BlobProto.prototype.width=0,$root.caffe.BlobProtoVector=class{constructor(){this.blobs=[]}static decode(e,a){const r=new $root.caffe.BlobProtoVector,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobProtoVector;for(e.start();!e.end();){const r=e.tag();switch(r){case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.Datum=class{constructor(){this.float_data=[]}static decode(e,a){const r=new $root.caffe.Datum,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.channels=e.int32();break;case 2:r.height=e.int32();break;case 3:r.width=e.int32();break;case 4:r.data=e.bytes();break;case 5:r.label=e.int32();break;case 6:r.float_data=e.floats(r.float_data,a);break;case 7:r.encoded=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.Datum;for(e.start();!e.end();){const r=e.tag();switch(r){case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;case"data":a.data=e.bytes();break;case"label":a.label=e.integer();break;case"float_data":e.array(a.float_data,(()=>e.float()));break;case"encoded":a.encoded=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.Datum.prototype.channels=0,$root.caffe.Datum.prototype.height=0,$root.caffe.Datum.prototype.width=0,$root.caffe.Datum.prototype.data=new Uint8Array([]),$root.caffe.Datum.prototype.label=0,$root.caffe.Datum.prototype.encoded=!1,$root.caffe.FillerParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.FillerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.type=e.string();break;case 2:r.value=e.float();break;case 3:r.min=e.float();break;case 4:r.max=e.float();break;case 5:r.mean=e.float();break;case 6:r.std=e.float();break;case 7:r.sparse=e.int32();break;case 8:r.variance_norm=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.FillerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"type":a.type=e.string();break;case"value":a.value=e.float();break;case"min":a.min=e.float();break;case"max":a.max=e.float();break;case"mean":a.mean=e.float();break;case"std":a.std=e.float();break;case"sparse":a.sparse=e.integer();break;case"variance_norm":a.variance_norm=e.enum($root.caffe.FillerParameter.VarianceNorm);break;default:e.field(r,a)}}return a}},$root.caffe.FillerParameter.prototype.type="constant",$root.caffe.FillerParameter.prototype.value=0,$root.caffe.FillerParameter.prototype.min=0,$root.caffe.FillerParameter.prototype.max=1,$root.caffe.FillerParameter.prototype.mean=0,$root.caffe.FillerParameter.prototype.std=1,$root.caffe.FillerParameter.prototype.sparse=-1,$root.caffe.FillerParameter.prototype.variance_norm=0,$root.caffe.FillerParameter.VarianceNorm={FAN_IN:0,FAN_OUT:1,AVERAGE:2},$root.caffe.NetParameter=class{constructor(){this.input=[],this.input_shape=[],this.input_dim=[],this.layer=[],this.layers=[]}static decode(e,a){const r=new $root.caffe.NetParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 3:r.input.push(e.string());break;case 8:r.input_shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;case 4:r.input_dim=e.array(r.input_dim,(()=>e.int32()),a);break;case 5:r.force_backward=e.bool();break;case 6:r.state=$root.caffe.NetState.decode(e,e.uint32());break;case 7:r.debug_info=e.bool();break;case 100:r.layer.push($root.caffe.LayerParameter.decode(e,e.uint32()));break;case 2:r.layers.push($root.caffe.V1LayerParameter.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"input":e.array(a.input,(()=>e.string()));break;case"input_shape":a.input_shape.push($root.caffe.BlobShape.decodeText(e,!0));break;case"input_dim":e.array(a.input_dim,(()=>e.integer()));break;case"force_backward":a.force_backward=e.boolean();break;case"state":a.state=$root.caffe.NetState.decodeText(e,!0);break;case"debug_info":a.debug_info=e.boolean();break;case"layer":a.layer.push($root.caffe.LayerParameter.decodeText(e,!0));break;case"layers":a.layers.push($root.caffe.V1LayerParameter.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.NetParameter.prototype.name="",$root.caffe.NetParameter.prototype.force_backward=!1,$root.caffe.NetParameter.prototype.state=null,$root.caffe.NetParameter.prototype.debug_info=!1,$root.caffe.SolverParameter=class{constructor(){this.test_net=[],this.test_net_param=[],this.test_state=[],this.test_iter=[],this.stepvalue=[],this.weights=[]}static decode(e,a){const r=new $root.caffe.SolverParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 24:r.net=e.string();break;case 25:r.net_param=$root.caffe.NetParameter.decode(e,e.uint32());break;case 1:r.train_net=e.string();break;case 2:r.test_net.push(e.string());break;case 21:r.train_net_param=$root.caffe.NetParameter.decode(e,e.uint32());break;case 22:r.test_net_param.push($root.caffe.NetParameter.decode(e,e.uint32()));break;case 26:r.train_state=$root.caffe.NetState.decode(e,e.uint32());break;case 27:r.test_state.push($root.caffe.NetState.decode(e,e.uint32()));break;case 3:r.test_iter=e.array(r.test_iter,(()=>e.int32()),a);break;case 4:r.test_interval=e.int32();break;case 19:r.test_compute_loss=e.bool();break;case 32:r.test_initialization=e.bool();break;case 5:r.base_lr=e.float();break;case 6:r.display=e.int32();break;case 33:r.average_loss=e.int32();break;case 7:r.max_iter=e.int32();break;case 36:r.iter_size=e.int32();break;case 8:r.lr_policy=e.string();break;case 9:r.gamma=e.float();break;case 10:r.power=e.float();break;case 11:r.momentum=e.float();break;case 12:r.weight_decay=e.float();break;case 29:r.regularization_type=e.string();break;case 13:r.stepsize=e.int32();break;case 34:r.stepvalue=e.array(r.stepvalue,(()=>e.int32()),a);break;case 35:r.clip_gradients=e.float();break;case 14:r.snapshot=e.int32();break;case 15:r.snapshot_prefix=e.string();break;case 16:r.snapshot_diff=e.bool();break;case 37:r.snapshot_format=e.int32();break;case 17:r.solver_mode=e.int32();break;case 18:r.device_id=e.int32();break;case 20:r.random_seed=e.int64();break;case 40:r.type=e.string();break;case 31:r.delta=e.float();break;case 39:r.momentum2=e.float();break;case 38:r.rms_decay=e.float();break;case 23:r.debug_info=e.bool();break;case 28:r.snapshot_after_train=e.bool();break;case 30:r.solver_type=e.int32();break;case 41:r.layer_wise_reduce=e.bool();break;case 42:r.weights.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SolverParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"net":a.net=e.string();break;case"net_param":a.net_param=$root.caffe.NetParameter.decodeText(e,!0);break;case"train_net":a.train_net=e.string();break;case"test_net":e.array(a.test_net,(()=>e.string()));break;case"train_net_param":a.train_net_param=$root.caffe.NetParameter.decodeText(e,!0);break;case"test_net_param":a.test_net_param.push($root.caffe.NetParameter.decodeText(e,!0));break;case"train_state":a.train_state=$root.caffe.NetState.decodeText(e,!0);break;case"test_state":a.test_state.push($root.caffe.NetState.decodeText(e,!0));break;case"test_iter":e.array(a.test_iter,(()=>e.integer()));break;case"test_interval":a.test_interval=e.integer();break;case"test_compute_loss":a.test_compute_loss=e.boolean();break;case"test_initialization":a.test_initialization=e.boolean();break;case"base_lr":a.base_lr=e.float();break;case"display":a.display=e.integer();break;case"average_loss":a.average_loss=e.integer();break;case"max_iter":a.max_iter=e.integer();break;case"iter_size":a.iter_size=e.integer();break;case"lr_policy":a.lr_policy=e.string();break;case"gamma":a.gamma=e.float();break;case"power":a.power=e.float();break;case"momentum":a.momentum=e.float();break;case"weight_decay":a.weight_decay=e.float();break;case"regularization_type":a.regularization_type=e.string();break;case"stepsize":a.stepsize=e.integer();break;case"stepvalue":e.array(a.stepvalue,(()=>e.integer()));break;case"clip_gradients":a.clip_gradients=e.float();break;case"snapshot":a.snapshot=e.integer();break;case"snapshot_prefix":a.snapshot_prefix=e.string();break;case"snapshot_diff":a.snapshot_diff=e.boolean();break;case"snapshot_format":a.snapshot_format=e.enum($root.caffe.SolverParameter.SnapshotFormat);break;case"solver_mode":a.solver_mode=e.enum($root.caffe.SolverParameter.SolverMode);break;case"device_id":a.device_id=e.integer();break;case"random_seed":a.random_seed=e.integer();break;case"type":a.type=e.string();break;case"delta":a.delta=e.float();break;case"momentum2":a.momentum2=e.float();break;case"rms_decay":a.rms_decay=e.float();break;case"debug_info":a.debug_info=e.boolean();break;case"snapshot_after_train":a.snapshot_after_train=e.boolean();break;case"solver_type":a.solver_type=e.enum($root.caffe.SolverParameter.SolverType);break;case"layer_wise_reduce":a.layer_wise_reduce=e.boolean();break;case"weights":e.array(a.weights,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.SolverParameter.prototype.net="",$root.caffe.SolverParameter.prototype.net_param=null,$root.caffe.SolverParameter.prototype.train_net="",$root.caffe.SolverParameter.prototype.train_net_param=null,$root.caffe.SolverParameter.prototype.train_state=null,$root.caffe.SolverParameter.prototype.test_interval=0,$root.caffe.SolverParameter.prototype.test_compute_loss=!1,$root.caffe.SolverParameter.prototype.test_initialization=!0,$root.caffe.SolverParameter.prototype.base_lr=0,$root.caffe.SolverParameter.prototype.display=0,$root.caffe.SolverParameter.prototype.average_loss=1,$root.caffe.SolverParameter.prototype.max_iter=0,$root.caffe.SolverParameter.prototype.iter_size=1,$root.caffe.SolverParameter.prototype.lr_policy="",$root.caffe.SolverParameter.prototype.gamma=0,$root.caffe.SolverParameter.prototype.power=0,$root.caffe.SolverParameter.prototype.momentum=0,$root.caffe.SolverParameter.prototype.weight_decay=0,$root.caffe.SolverParameter.prototype.regularization_type="L2",$root.caffe.SolverParameter.prototype.stepsize=0,$root.caffe.SolverParameter.prototype.clip_gradients=-1,$root.caffe.SolverParameter.prototype.snapshot=0,$root.caffe.SolverParameter.prototype.snapshot_prefix="",$root.caffe.SolverParameter.prototype.snapshot_diff=!1,$root.caffe.SolverParameter.prototype.snapshot_format=1,$root.caffe.SolverParameter.prototype.solver_mode=1,$root.caffe.SolverParameter.prototype.device_id=0,$root.caffe.SolverParameter.prototype.random_seed=protobuf.Long?protobuf.Long.fromBits(-1,-1,!1):-1,$root.caffe.SolverParameter.prototype.type="SGD",$root.caffe.SolverParameter.prototype.delta=1e-8,$root.caffe.SolverParameter.prototype.momentum2=.999,$root.caffe.SolverParameter.prototype.rms_decay=.99,$root.caffe.SolverParameter.prototype.debug_info=!1,$root.caffe.SolverParameter.prototype.snapshot_after_train=!0,$root.caffe.SolverParameter.prototype.solver_type=0,$root.caffe.SolverParameter.prototype.layer_wise_reduce=!0,$root.caffe.SolverParameter.SnapshotFormat={HDF5:0,BINARYPROTO:1},$root.caffe.SolverParameter.SolverMode={CPU:0,GPU:1},$root.caffe.SolverParameter.SolverType={SGD:0,NESTEROV:1,ADAGRAD:2,RMSPROP:3,ADADELTA:4,ADAM:5},$root.caffe.SolverState=class{constructor(){this.history=[]}static decode(e,a){const r=new $root.caffe.SolverState,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.iter=e.int32();break;case 2:r.learned_net=e.string();break;case 3:r.history.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 4:r.current_step=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SolverState;for(e.start();!e.end();){const r=e.tag();switch(r){case"iter":a.iter=e.integer();break;case"learned_net":a.learned_net=e.string();break;case"history":a.history.push($root.caffe.BlobProto.decodeText(e,!0));break;case"current_step":a.current_step=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SolverState.prototype.iter=0,$root.caffe.SolverState.prototype.learned_net="",$root.caffe.SolverState.prototype.current_step=0,$root.caffe.Phase={TRAIN:0,TEST:1},$root.caffe.NetState=class{constructor(){this.stage=[]}static decode(e,a){const r=new $root.caffe.NetState,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.phase=e.int32();break;case 2:r.level=e.int32();break;case 3:r.stage.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetState;for(e.start();!e.end();){const r=e.tag();switch(r){case"phase":a.phase=e.enum($root.caffe.Phase);break;case"level":a.level=e.integer();break;case"stage":e.array(a.stage,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.NetState.prototype.phase=1,$root.caffe.NetState.prototype.level=0,$root.caffe.NetStateRule=class{constructor(){this.stage=[],this.not_stage=[]}static decode(e,a){const r=new $root.caffe.NetStateRule,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.phase=e.int32();break;case 2:r.min_level=e.int32();break;case 3:r.max_level=e.int32();break;case 4:r.stage.push(e.string());break;case 5:r.not_stage.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetStateRule;for(e.start();!e.end();){const r=e.tag();switch(r){case"phase":a.phase=e.enum($root.caffe.Phase);break;case"min_level":a.min_level=e.integer();break;case"max_level":a.max_level=e.integer();break;case"stage":e.array(a.stage,(()=>e.string()));break;case"not_stage":e.array(a.not_stage,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.NetStateRule.prototype.phase=0,$root.caffe.NetStateRule.prototype.min_level=0,$root.caffe.NetStateRule.prototype.max_level=0,$root.caffe.ParamSpec=class{constructor(){}static decode(e,a){const r=new $root.caffe.ParamSpec,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.share_mode=e.int32();break;case 3:r.lr_mult=e.float();break;case 4:r.decay_mult=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ParamSpec;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"share_mode":a.share_mode=e.enum($root.caffe.ParamSpec.DimCheckMode);break;case"lr_mult":a.lr_mult=e.float();break;case"decay_mult":a.decay_mult=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ParamSpec.prototype.name="",$root.caffe.ParamSpec.prototype.share_mode=0,$root.caffe.ParamSpec.prototype.lr_mult=1,$root.caffe.ParamSpec.prototype.decay_mult=1,$root.caffe.ParamSpec.DimCheckMode={STRICT:0,PERMISSIVE:1},$root.caffe.LayerParameter=class{constructor(){this.bottom=[],this.top=[],this.loss_weight=[],this.param=[],this.blobs=[],this.propagate_down=[],this.include=[],this.exclude=[]}static decode(e,a){const r=new $root.caffe.LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.type=e.string();break;case 3:r.bottom.push(e.string());break;case 4:r.top.push(e.string());break;case 10:r.phase=e.int32();break;case 5:r.loss_weight=e.floats(r.loss_weight,a);break;case 6:r.param.push($root.caffe.ParamSpec.decode(e,e.uint32()));break;case 7:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 11:r.propagate_down=e.array(r.propagate_down,(()=>e.bool()),a);break;case 8:r.include.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 9:r.exclude.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 100:r.transform_param=$root.caffe.TransformationParameter.decode(e,e.uint32());break;case 101:r.loss_param=$root.caffe.LossParameter.decode(e,e.uint32());break;case 102:r.accuracy_param=$root.caffe.AccuracyParameter.decode(e,e.uint32());break;case 103:r.argmax_param=$root.caffe.ArgMaxParameter.decode(e,e.uint32());break;case 139:r.batch_norm_param=$root.caffe.BatchNormParameter.decode(e,e.uint32());break;case 141:r.bias_param=$root.caffe.BiasParameter.decode(e,e.uint32());break;case 148:r.clip_param=$root.caffe.ClipParameter.decode(e,e.uint32());break;case 104:r.concat_param=$root.caffe.ConcatParameter.decode(e,e.uint32());break;case 105:r.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decode(e,e.uint32());break;case 106:r.convolution_param=$root.caffe.ConvolutionParameter.decode(e,e.uint32());break;case 144:r.crop_param=$root.caffe.CropParameter.decode(e,e.uint32());break;case 107:r.data_param=$root.caffe.DataParameter.decode(e,e.uint32());break;case 108:r.dropout_param=$root.caffe.DropoutParameter.decode(e,e.uint32());break;case 109:r.dummy_data_param=$root.caffe.DummyDataParameter.decode(e,e.uint32());break;case 110:r.eltwise_param=$root.caffe.EltwiseParameter.decode(e,e.uint32());break;case 140:r.elu_param=$root.caffe.ELUParameter.decode(e,e.uint32());break;case 137:r.embed_param=$root.caffe.EmbedParameter.decode(e,e.uint32());break;case 111:r.exp_param=$root.caffe.ExpParameter.decode(e,e.uint32());break;case 135:r.flatten_param=$root.caffe.FlattenParameter.decode(e,e.uint32());break;case 112:r.hdf5_data_param=$root.caffe.HDF5DataParameter.decode(e,e.uint32());break;case 113:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;case 114:r.hinge_loss_param=$root.caffe.HingeLossParameter.decode(e,e.uint32());break;case 115:r.image_data_param=$root.caffe.ImageDataParameter.decode(e,e.uint32());break;case 116:r.infogain_loss_param=$root.caffe.InfogainLossParameter.decode(e,e.uint32());break;case 117:r.inner_product_param=$root.caffe.InnerProductParameter.decode(e,e.uint32());break;case 143:r.input_param=$root.caffe.InputParameter.decode(e,e.uint32());break;case 134:r.log_param=$root.caffe.LogParameter.decode(e,e.uint32());break;case 118:r.lrn_param=$root.caffe.LRNParameter.decode(e,e.uint32());break;case 119:r.memory_data_param=$root.caffe.MemoryDataParameter.decode(e,e.uint32());break;case 120:r.mvn_param=$root.caffe.MVNParameter.decode(e,e.uint32());break;case 145:r.parameter_param=$root.caffe.ParameterParameter.decode(e,e.uint32());break;case 121:r.pooling_param=$root.caffe.PoolingParameter.decode(e,e.uint32());break;case 122:r.power_param=$root.caffe.PowerParameter.decode(e,e.uint32());break;case 131:r.prelu_param=$root.caffe.PReLUParameter.decode(e,e.uint32());break;case 130:r.python_param=$root.caffe.PythonParameter.decode(e,e.uint32());break;case 146:r.recurrent_param=$root.caffe.RecurrentParameter.decode(e,e.uint32());break;case 136:r.reduction_param=$root.caffe.ReductionParameter.decode(e,e.uint32());break;case 123:r.relu_param=$root.caffe.ReLUParameter.decode(e,e.uint32());break;case 133:r.reshape_param=$root.caffe.ReshapeParameter.decode(e,e.uint32());break;case 142:r.scale_param=$root.caffe.ScaleParameter.decode(e,e.uint32());break;case 124:r.sigmoid_param=$root.caffe.SigmoidParameter.decode(e,e.uint32());break;case 125:r.softmax_param=$root.caffe.SoftmaxParameter.decode(e,e.uint32());break;case 132:r.spp_param=$root.caffe.SPPParameter.decode(e,e.uint32());break;case 126:r.slice_param=$root.caffe.SliceParameter.decode(e,e.uint32());break;case 147:r.swish_param=$root.caffe.SwishParameter.decode(e,e.uint32());break;case 127:r.tanh_param=$root.caffe.TanHParameter.decode(e,e.uint32());break;case 128:r.threshold_param=$root.caffe.ThresholdParameter.decode(e,e.uint32());break;case 138:r.tile_param=$root.caffe.TileParameter.decode(e,e.uint32());break;case 129:r.window_data_param=$root.caffe.WindowDataParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"type":a.type=e.string();break;case"bottom":e.array(a.bottom,(()=>e.string()));break;case"top":e.array(a.top,(()=>e.string()));break;case"phase":a.phase=e.enum($root.caffe.Phase);break;case"loss_weight":e.array(a.loss_weight,(()=>e.float()));break;case"param":a.param.push($root.caffe.ParamSpec.decodeText(e,!0));break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"propagate_down":e.array(a.propagate_down,(()=>e.boolean()));break;case"include":a.include.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"exclude":a.exclude.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"transform_param":a.transform_param=$root.caffe.TransformationParameter.decodeText(e,!0);break;case"loss_param":a.loss_param=$root.caffe.LossParameter.decodeText(e,!0);break;case"accuracy_param":a.accuracy_param=$root.caffe.AccuracyParameter.decodeText(e,!0);break;case"argmax_param":a.argmax_param=$root.caffe.ArgMaxParameter.decodeText(e,!0);break;case"batch_norm_param":a.batch_norm_param=$root.caffe.BatchNormParameter.decodeText(e,!0);break;case"bias_param":a.bias_param=$root.caffe.BiasParameter.decodeText(e,!0);break;case"clip_param":a.clip_param=$root.caffe.ClipParameter.decodeText(e,!0);break;case"concat_param":a.concat_param=$root.caffe.ConcatParameter.decodeText(e,!0);break;case"contrastive_loss_param":a.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decodeText(e,!0);break;case"convolution_param":a.convolution_param=$root.caffe.ConvolutionParameter.decodeText(e,!0);break;case"crop_param":a.crop_param=$root.caffe.CropParameter.decodeText(e,!0);break;case"data_param":a.data_param=$root.caffe.DataParameter.decodeText(e,!0);break;case"dropout_param":a.dropout_param=$root.caffe.DropoutParameter.decodeText(e,!0);break;case"dummy_data_param":a.dummy_data_param=$root.caffe.DummyDataParameter.decodeText(e,!0);break;case"eltwise_param":a.eltwise_param=$root.caffe.EltwiseParameter.decodeText(e,!0);break;case"elu_param":a.elu_param=$root.caffe.ELUParameter.decodeText(e,!0);break;case"embed_param":a.embed_param=$root.caffe.EmbedParameter.decodeText(e,!0);break;case"exp_param":a.exp_param=$root.caffe.ExpParameter.decodeText(e,!0);break;case"flatten_param":a.flatten_param=$root.caffe.FlattenParameter.decodeText(e,!0);break;case"hdf5_data_param":a.hdf5_data_param=$root.caffe.HDF5DataParameter.decodeText(e,!0);break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;case"hinge_loss_param":a.hinge_loss_param=$root.caffe.HingeLossParameter.decodeText(e,!0);break;case"image_data_param":a.image_data_param=$root.caffe.ImageDataParameter.decodeText(e,!0);break;case"infogain_loss_param":a.infogain_loss_param=$root.caffe.InfogainLossParameter.decodeText(e,!0);break;case"inner_product_param":a.inner_product_param=$root.caffe.InnerProductParameter.decodeText(e,!0);break;case"input_param":a.input_param=$root.caffe.InputParameter.decodeText(e,!0);break;case"log_param":a.log_param=$root.caffe.LogParameter.decodeText(e,!0);break;case"lrn_param":a.lrn_param=$root.caffe.LRNParameter.decodeText(e,!0);break;case"memory_data_param":a.memory_data_param=$root.caffe.MemoryDataParameter.decodeText(e,!0);break;case"mvn_param":a.mvn_param=$root.caffe.MVNParameter.decodeText(e,!0);break;case"parameter_param":a.parameter_param=$root.caffe.ParameterParameter.decodeText(e,!0);break;case"pooling_param":a.pooling_param=$root.caffe.PoolingParameter.decodeText(e,!0);break;case"power_param":a.power_param=$root.caffe.PowerParameter.decodeText(e,!0);break;case"prelu_param":a.prelu_param=$root.caffe.PReLUParameter.decodeText(e,!0);break;case"python_param":a.python_param=$root.caffe.PythonParameter.decodeText(e,!0);break;case"recurrent_param":a.recurrent_param=$root.caffe.RecurrentParameter.decodeText(e,!0);break;case"reduction_param":a.reduction_param=$root.caffe.ReductionParameter.decodeText(e,!0);break;case"relu_param":a.relu_param=$root.caffe.ReLUParameter.decodeText(e,!0);break;case"reshape_param":a.reshape_param=$root.caffe.ReshapeParameter.decodeText(e,!0);break;case"scale_param":a.scale_param=$root.caffe.ScaleParameter.decodeText(e,!0);break;case"sigmoid_param":a.sigmoid_param=$root.caffe.SigmoidParameter.decodeText(e,!0);break;case"softmax_param":a.softmax_param=$root.caffe.SoftmaxParameter.decodeText(e,!0);break;case"spp_param":a.spp_param=$root.caffe.SPPParameter.decodeText(e,!0);break;case"slice_param":a.slice_param=$root.caffe.SliceParameter.decodeText(e,!0);break;case"swish_param":a.swish_param=$root.caffe.SwishParameter.decodeText(e,!0);break;case"tanh_param":a.tanh_param=$root.caffe.TanHParameter.decodeText(e,!0);break;case"threshold_param":a.threshold_param=$root.caffe.ThresholdParameter.decodeText(e,!0);break;case"tile_param":a.tile_param=$root.caffe.TileParameter.decodeText(e,!0);break;case"window_data_param":a.window_data_param=$root.caffe.WindowDataParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.LayerParameter.prototype.name="",$root.caffe.LayerParameter.prototype.type="",$root.caffe.LayerParameter.prototype.phase=0,$root.caffe.LayerParameter.prototype.transform_param=null,$root.caffe.LayerParameter.prototype.loss_param=null,$root.caffe.LayerParameter.prototype.accuracy_param=null,$root.caffe.LayerParameter.prototype.argmax_param=null,$root.caffe.LayerParameter.prototype.batch_norm_param=null,$root.caffe.LayerParameter.prototype.bias_param=null,$root.caffe.LayerParameter.prototype.clip_param=null,$root.caffe.LayerParameter.prototype.concat_param=null,$root.caffe.LayerParameter.prototype.contrastive_loss_param=null,$root.caffe.LayerParameter.prototype.convolution_param=null,$root.caffe.LayerParameter.prototype.crop_param=null,$root.caffe.LayerParameter.prototype.data_param=null,$root.caffe.LayerParameter.prototype.dropout_param=null,$root.caffe.LayerParameter.prototype.dummy_data_param=null,$root.caffe.LayerParameter.prototype.eltwise_param=null,$root.caffe.LayerParameter.prototype.elu_param=null,$root.caffe.LayerParameter.prototype.embed_param=null,$root.caffe.LayerParameter.prototype.exp_param=null,$root.caffe.LayerParameter.prototype.flatten_param=null,$root.caffe.LayerParameter.prototype.hdf5_data_param=null,$root.caffe.LayerParameter.prototype.hdf5_output_param=null,$root.caffe.LayerParameter.prototype.hinge_loss_param=null,$root.caffe.LayerParameter.prototype.image_data_param=null,$root.caffe.LayerParameter.prototype.infogain_loss_param=null,$root.caffe.LayerParameter.prototype.inner_product_param=null,$root.caffe.LayerParameter.prototype.input_param=null,$root.caffe.LayerParameter.prototype.log_param=null,$root.caffe.LayerParameter.prototype.lrn_param=null,$root.caffe.LayerParameter.prototype.memory_data_param=null,$root.caffe.LayerParameter.prototype.mvn_param=null,$root.caffe.LayerParameter.prototype.parameter_param=null,$root.caffe.LayerParameter.prototype.pooling_param=null,$root.caffe.LayerParameter.prototype.power_param=null,$root.caffe.LayerParameter.prototype.prelu_param=null,$root.caffe.LayerParameter.prototype.python_param=null,$root.caffe.LayerParameter.prototype.recurrent_param=null,$root.caffe.LayerParameter.prototype.reduction_param=null,$root.caffe.LayerParameter.prototype.relu_param=null,$root.caffe.LayerParameter.prototype.reshape_param=null,$root.caffe.LayerParameter.prototype.scale_param=null,$root.caffe.LayerParameter.prototype.sigmoid_param=null,$root.caffe.LayerParameter.prototype.softmax_param=null,$root.caffe.LayerParameter.prototype.spp_param=null,$root.caffe.LayerParameter.prototype.slice_param=null,$root.caffe.LayerParameter.prototype.swish_param=null,$root.caffe.LayerParameter.prototype.tanh_param=null,$root.caffe.LayerParameter.prototype.threshold_param=null,$root.caffe.LayerParameter.prototype.tile_param=null,$root.caffe.LayerParameter.prototype.window_data_param=null,$root.caffe.TransformationParameter=class{constructor(){this.mean_value=[]}static decode(e,a){const r=new $root.caffe.TransformationParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.scale=e.float();break;case 2:r.mirror=e.bool();break;case 3:r.crop_size=e.uint32();break;case 4:r.mean_file=e.string();break;case 5:r.mean_value=e.floats(r.mean_value,a);break;case 6:r.force_color=e.bool();break;case 7:r.force_gray=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TransformationParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"scale":a.scale=e.float();break;case"mirror":a.mirror=e.boolean();break;case"crop_size":a.crop_size=e.integer();break;case"mean_file":a.mean_file=e.string();break;case"mean_value":e.array(a.mean_value,(()=>e.float()));break;case"force_color":a.force_color=e.boolean();break;case"force_gray":a.force_gray=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.TransformationParameter.prototype.scale=1,$root.caffe.TransformationParameter.prototype.mirror=!1,$root.caffe.TransformationParameter.prototype.crop_size=0,$root.caffe.TransformationParameter.prototype.mean_file="",$root.caffe.TransformationParameter.prototype.force_color=!1,$root.caffe.TransformationParameter.prototype.force_gray=!1,$root.caffe.LossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.ignore_label=e.int32();break;case 3:r.normalization=e.int32();break;case 2:r.normalize=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"ignore_label":a.ignore_label=e.integer();break;case"normalization":a.normalization=e.enum($root.caffe.LossParameter.NormalizationMode);break;case"normalize":a.normalize=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.LossParameter.prototype.ignore_label=0,$root.caffe.LossParameter.prototype.normalization=1,$root.caffe.LossParameter.prototype.normalize=!1,$root.caffe.LossParameter.NormalizationMode={FULL:0,VALID:1,BATCH_SIZE:2,NONE:3},$root.caffe.AccuracyParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.AccuracyParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.top_k=e.uint32();break;case 2:r.axis=e.int32();break;case 3:r.ignore_label=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.AccuracyParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"top_k":a.top_k=e.integer();break;case"axis":a.axis=e.integer();break;case"ignore_label":a.ignore_label=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.AccuracyParameter.prototype.top_k=1,$root.caffe.AccuracyParameter.prototype.axis=1,$root.caffe.AccuracyParameter.prototype.ignore_label=0,$root.caffe.ArgMaxParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ArgMaxParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.out_max_val=e.bool();break;case 2:r.top_k=e.uint32();break;case 3:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ArgMaxParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"out_max_val":a.out_max_val=e.boolean();break;case"top_k":a.top_k=e.integer();break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ArgMaxParameter.prototype.out_max_val=!1,$root.caffe.ArgMaxParameter.prototype.top_k=1,$root.caffe.ArgMaxParameter.prototype.axis=0,$root.caffe.ClipParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ClipParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.min=e.float();break;case 2:r.max=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ClipParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"min":a.min=e.float();break;case"max":a.max=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ClipParameter.prototype.min=0,$root.caffe.ClipParameter.prototype.max=0,$root.caffe.ConcatParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ConcatParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 2:r.axis=e.int32();break;case 1:r.concat_dim=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ConcatParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"concat_dim":a.concat_dim=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ConcatParameter.prototype.axis=1,$root.caffe.ConcatParameter.prototype.concat_dim=1,$root.caffe.BatchNormParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.BatchNormParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.use_global_stats=e.bool();break;case 2:r.moving_average_fraction=e.float();break;case 3:r.eps=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BatchNormParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"use_global_stats":a.use_global_stats=e.boolean();break;case"moving_average_fraction":a.moving_average_fraction=e.float();break;case"eps":a.eps=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.BatchNormParameter.prototype.use_global_stats=!1,$root.caffe.BatchNormParameter.prototype.moving_average_fraction=.999,$root.caffe.BatchNormParameter.prototype.eps=1e-5,$root.caffe.BiasParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.BiasParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.num_axes=e.int32();break;case 3:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BiasParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.BiasParameter.prototype.axis=1,$root.caffe.BiasParameter.prototype.num_axes=1,$root.caffe.BiasParameter.prototype.filler=null,$root.caffe.ContrastiveLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ContrastiveLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.margin=e.float();break;case 2:r.legacy_version=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ContrastiveLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"margin":a.margin=e.float();break;case"legacy_version":a.legacy_version=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.ContrastiveLossParameter.prototype.margin=1,$root.caffe.ContrastiveLossParameter.prototype.legacy_version=!1,$root.caffe.ConvolutionParameter=class{constructor(){this.pad=[],this.kernel_size=[],this.stride=[],this.dilation=[]}static decode(e,a){const r=new $root.caffe.ConvolutionParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.bias_term=e.bool();break;case 3:r.pad=e.array(r.pad,(()=>e.uint32()),a);break;case 4:r.kernel_size=e.array(r.kernel_size,(()=>e.uint32()),a);break;case 6:r.stride=e.array(r.stride,(()=>e.uint32()),a);break;case 18:r.dilation=e.array(r.dilation,(()=>e.uint32()),a);break;case 9:r.pad_h=e.uint32();break;case 10:r.pad_w=e.uint32();break;case 11:r.kernel_h=e.uint32();break;case 12:r.kernel_w=e.uint32();break;case 13:r.stride_h=e.uint32();break;case 14:r.stride_w=e.uint32();break;case 5:r.group=e.uint32();break;case 7:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 8:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 15:r.engine=e.int32();break;case 16:r.axis=e.int32();break;case 17:r.force_nd_im2col=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ConvolutionParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"pad":e.array(a.pad,(()=>e.integer()));break;case"kernel_size":e.array(a.kernel_size,(()=>e.integer()));break;case"stride":e.array(a.stride,(()=>e.integer()));break;case"dilation":e.array(a.dilation,(()=>e.integer()));break;case"pad_h":a.pad_h=e.integer();break;case"pad_w":a.pad_w=e.integer();break;case"kernel_h":a.kernel_h=e.integer();break;case"kernel_w":a.kernel_w=e.integer();break;case"stride_h":a.stride_h=e.integer();break;case"stride_w":a.stride_w=e.integer();break;case"group":a.group=e.integer();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"engine":a.engine=e.enum($root.caffe.ConvolutionParameter.Engine);break;case"axis":a.axis=e.integer();break;case"force_nd_im2col":a.force_nd_im2col=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.ConvolutionParameter.prototype.num_output=0,$root.caffe.ConvolutionParameter.prototype.bias_term=!0,$root.caffe.ConvolutionParameter.prototype.pad_h=0,$root.caffe.ConvolutionParameter.prototype.pad_w=0,$root.caffe.ConvolutionParameter.prototype.kernel_h=0,$root.caffe.ConvolutionParameter.prototype.kernel_w=0,$root.caffe.ConvolutionParameter.prototype.stride_h=0,$root.caffe.ConvolutionParameter.prototype.stride_w=0,$root.caffe.ConvolutionParameter.prototype.group=1,$root.caffe.ConvolutionParameter.prototype.weight_filler=null,$root.caffe.ConvolutionParameter.prototype.bias_filler=null,$root.caffe.ConvolutionParameter.prototype.engine=0,$root.caffe.ConvolutionParameter.prototype.axis=1,$root.caffe.ConvolutionParameter.prototype.force_nd_im2col=!1,$root.caffe.ConvolutionParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.CropParameter=class{constructor(){this.offset=[]}static decode(e,a){const r=new $root.caffe.CropParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.offset=e.array(r.offset,(()=>e.uint32()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.CropParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"offset":e.array(a.offset,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.CropParameter.prototype.axis=2,$root.caffe.DataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.DataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 4:r.batch_size=e.uint32();break;case 7:r.rand_skip=e.uint32();break;case 8:r.backend=e.int32();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 9:r.force_encoded_color=e.bool();break;case 10:r.prefetch=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"rand_skip":a.rand_skip=e.integer();break;case"backend":a.backend=e.enum($root.caffe.DataParameter.DB);break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"force_encoded_color":a.force_encoded_color=e.boolean();break;case"prefetch":a.prefetch=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.DataParameter.prototype.source="",$root.caffe.DataParameter.prototype.batch_size=0,$root.caffe.DataParameter.prototype.rand_skip=0,$root.caffe.DataParameter.prototype.backend=0,$root.caffe.DataParameter.prototype.scale=1,$root.caffe.DataParameter.prototype.mean_file="",$root.caffe.DataParameter.prototype.crop_size=0,$root.caffe.DataParameter.prototype.mirror=!1,$root.caffe.DataParameter.prototype.force_encoded_color=!1,$root.caffe.DataParameter.prototype.prefetch=4,$root.caffe.DataParameter.DB={LEVELDB:0,LMDB:1},$root.caffe.DropoutParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.DropoutParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.dropout_ratio=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DropoutParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"dropout_ratio":a.dropout_ratio=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.DropoutParameter.prototype.dropout_ratio=.5,$root.caffe.DummyDataParameter=class{constructor(){this.data_filler=[],this.shape=[],this.num=[],this.channels=[],this.height=[],this.width=[]}static decode(e,a){const r=new $root.caffe.DummyDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.data_filler.push($root.caffe.FillerParameter.decode(e,e.uint32()));break;case 6:r.shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;case 2:r.num=e.array(r.num,(()=>e.uint32()),a);break;case 3:r.channels=e.array(r.channels,(()=>e.uint32()),a);break;case 4:r.height=e.array(r.height,(()=>e.uint32()),a);break;case 5:r.width=e.array(r.width,(()=>e.uint32()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DummyDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"data_filler":a.data_filler.push($root.caffe.FillerParameter.decodeText(e,!0));break;case"shape":a.shape.push($root.caffe.BlobShape.decodeText(e,!0));break;case"num":e.array(a.num,(()=>e.integer()));break;case"channels":e.array(a.channels,(()=>e.integer()));break;case"height":e.array(a.height,(()=>e.integer()));break;case"width":e.array(a.width,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.EltwiseParameter=class{constructor(){this.coeff=[]}static decode(e,a){const r=new $root.caffe.EltwiseParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.operation=e.int32();break;case 2:r.coeff=e.floats(r.coeff,a);break;case 3:r.stable_prod_grad=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.EltwiseParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"operation":a.operation=e.enum($root.caffe.EltwiseParameter.EltwiseOp);break;case"coeff":e.array(a.coeff,(()=>e.float()));break;case"stable_prod_grad":a.stable_prod_grad=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.EltwiseParameter.prototype.operation=1,$root.caffe.EltwiseParameter.prototype.stable_prod_grad=!0,$root.caffe.EltwiseParameter.EltwiseOp={PROD:0,SUM:1,MAX:2},$root.caffe.ELUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ELUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.alpha=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ELUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"alpha":a.alpha=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ELUParameter.prototype.alpha=1,$root.caffe.EmbedParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.EmbedParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.input_dim=e.uint32();break;case 3:r.bias_term=e.bool();break;case 4:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 5:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.EmbedParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"input_dim":a.input_dim=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.EmbedParameter.prototype.num_output=0,$root.caffe.EmbedParameter.prototype.input_dim=0,$root.caffe.EmbedParameter.prototype.bias_term=!0,$root.caffe.EmbedParameter.prototype.weight_filler=null,$root.caffe.EmbedParameter.prototype.bias_filler=null,$root.caffe.ExpParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ExpParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.base=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ExpParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"base":a.base=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ExpParameter.prototype.base=-1,$root.caffe.ExpParameter.prototype.scale=1,$root.caffe.ExpParameter.prototype.shift=0,$root.caffe.FlattenParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.FlattenParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.end_axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.FlattenParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"end_axis":a.end_axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.FlattenParameter.prototype.axis=1,$root.caffe.FlattenParameter.prototype.end_axis=-1,$root.caffe.HDF5DataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HDF5DataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.batch_size=e.uint32();break;case 3:r.shuffle=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HDF5DataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"shuffle":a.shuffle=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.HDF5DataParameter.prototype.source="",$root.caffe.HDF5DataParameter.prototype.batch_size=0,$root.caffe.HDF5DataParameter.prototype.shuffle=!1,$root.caffe.HDF5OutputParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HDF5OutputParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.file_name=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HDF5OutputParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"file_name":a.file_name=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.HDF5OutputParameter.prototype.file_name="",$root.caffe.HingeLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HingeLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.norm=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HingeLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"norm":a.norm=e.enum($root.caffe.HingeLossParameter.Norm);break;default:e.field(r,a)}}return a}},$root.caffe.HingeLossParameter.prototype.norm=1,$root.caffe.HingeLossParameter.Norm={L1:1,L2:2},$root.caffe.ImageDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ImageDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 4:r.batch_size=e.uint32();break;case 7:r.rand_skip=e.uint32();break;case 8:r.shuffle=e.bool();break;case 9:r.new_height=e.uint32();break;case 10:r.new_width=e.uint32();break;case 11:r.is_color=e.bool();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 12:r.root_folder=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ImageDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"rand_skip":a.rand_skip=e.integer();break;case"shuffle":a.shuffle=e.boolean();break;case"new_height":a.new_height=e.integer();break;case"new_width":a.new_width=e.integer();break;case"is_color":a.is_color=e.boolean();break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"root_folder":a.root_folder=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.ImageDataParameter.prototype.source="",$root.caffe.ImageDataParameter.prototype.batch_size=1,$root.caffe.ImageDataParameter.prototype.rand_skip=0,$root.caffe.ImageDataParameter.prototype.shuffle=!1,$root.caffe.ImageDataParameter.prototype.new_height=0,$root.caffe.ImageDataParameter.prototype.new_width=0,$root.caffe.ImageDataParameter.prototype.is_color=!0,$root.caffe.ImageDataParameter.prototype.scale=1,$root.caffe.ImageDataParameter.prototype.mean_file="",$root.caffe.ImageDataParameter.prototype.crop_size=0,$root.caffe.ImageDataParameter.prototype.mirror=!1,$root.caffe.ImageDataParameter.prototype.root_folder="",$root.caffe.InfogainLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.InfogainLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InfogainLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.InfogainLossParameter.prototype.source="",$root.caffe.InfogainLossParameter.prototype.axis=1,$root.caffe.InnerProductParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.InnerProductParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.bias_term=e.bool();break;case 3:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 5:r.axis=e.int32();break;case 6:r.transpose=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InnerProductParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"axis":a.axis=e.integer();break;case"transpose":a.transpose=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.InnerProductParameter.prototype.num_output=0,$root.caffe.InnerProductParameter.prototype.bias_term=!0,$root.caffe.InnerProductParameter.prototype.weight_filler=null,$root.caffe.InnerProductParameter.prototype.bias_filler=null,$root.caffe.InnerProductParameter.prototype.axis=1,$root.caffe.InnerProductParameter.prototype.transpose=!1,$root.caffe.InputParameter=class{constructor(){this.shape=[]}static decode(e,a){const r=new $root.caffe.InputParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InputParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape.push($root.caffe.BlobShape.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.LogParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LogParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.base=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LogParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"base":a.base=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.LogParameter.prototype.base=-1,$root.caffe.LogParameter.prototype.scale=1,$root.caffe.LogParameter.prototype.shift=0,$root.caffe.LRNParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LRNParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.local_size=e.uint32();break;case 2:r.alpha=e.float();break;case 3:r.beta=e.float();break;case 4:r.norm_region=e.int32();break;case 5:r.k=e.float();break;case 6:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LRNParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"local_size":a.local_size=e.integer();break;case"alpha":a.alpha=e.float();break;case"beta":a.beta=e.float();break;case"norm_region":a.norm_region=e.enum($root.caffe.LRNParameter.NormRegion);break;case"k":a.k=e.float();break;case"engine":a.engine=e.enum($root.caffe.LRNParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.LRNParameter.prototype.local_size=5,$root.caffe.LRNParameter.prototype.alpha=1,$root.caffe.LRNParameter.prototype.beta=.75,$root.caffe.LRNParameter.prototype.norm_region=0,$root.caffe.LRNParameter.prototype.k=1,$root.caffe.LRNParameter.prototype.engine=0,$root.caffe.LRNParameter.NormRegion={ACROSS_CHANNELS:0,WITHIN_CHANNEL:1},$root.caffe.LRNParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.MemoryDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.MemoryDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.batch_size=e.uint32();break;case 2:r.channels=e.uint32();break;case 3:r.height=e.uint32();break;case 4:r.width=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.MemoryDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"batch_size":a.batch_size=e.integer();break;case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.MemoryDataParameter.prototype.batch_size=0,$root.caffe.MemoryDataParameter.prototype.channels=0,$root.caffe.MemoryDataParameter.prototype.height=0,$root.caffe.MemoryDataParameter.prototype.width=0,$root.caffe.MVNParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.MVNParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.normalize_variance=e.bool();break;case 2:r.across_channels=e.bool();break;case 3:r.eps=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.MVNParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"normalize_variance":a.normalize_variance=e.boolean();break;case"across_channels":a.across_channels=e.boolean();break;case"eps":a.eps=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.MVNParameter.prototype.normalize_variance=!0,$root.caffe.MVNParameter.prototype.across_channels=!1,$root.caffe.MVNParameter.prototype.eps=1e-9,$root.caffe.ParameterParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ParameterParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ParameterParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.ParameterParameter.prototype.shape=null,$root.caffe.PoolingParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PoolingParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.pool=e.int32();break;case 4:r.pad=e.uint32();break;case 9:r.pad_h=e.uint32();break;case 10:r.pad_w=e.uint32();break;case 2:r.kernel_size=e.uint32();break;case 5:r.kernel_h=e.uint32();break;case 6:r.kernel_w=e.uint32();break;case 3:r.stride=e.uint32();break;case 7:r.stride_h=e.uint32();break;case 8:r.stride_w=e.uint32();break;case 11:r.engine=e.int32();break;case 12:r.global_pooling=e.bool();break;case 13:r.round_mode=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PoolingParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"pool":a.pool=e.enum($root.caffe.PoolingParameter.PoolMethod);break;case"pad":a.pad=e.integer();break;case"pad_h":a.pad_h=e.integer();break;case"pad_w":a.pad_w=e.integer();break;case"kernel_size":a.kernel_size=e.integer();break;case"kernel_h":a.kernel_h=e.integer();break;case"kernel_w":a.kernel_w=e.integer();break;case"stride":a.stride=e.integer();break;case"stride_h":a.stride_h=e.integer();break;case"stride_w":a.stride_w=e.integer();break;case"engine":a.engine=e.enum($root.caffe.PoolingParameter.Engine);break;case"global_pooling":a.global_pooling=e.boolean();break;case"round_mode":a.round_mode=e.enum($root.caffe.PoolingParameter.RoundMode);break;default:e.field(r,a)}}return a}},$root.caffe.PoolingParameter.prototype.pool=0,$root.caffe.PoolingParameter.prototype.pad=0,$root.caffe.PoolingParameter.prototype.pad_h=0,$root.caffe.PoolingParameter.prototype.pad_w=0,$root.caffe.PoolingParameter.prototype.kernel_size=0,$root.caffe.PoolingParameter.prototype.kernel_h=0,$root.caffe.PoolingParameter.prototype.kernel_w=0,$root.caffe.PoolingParameter.prototype.stride=1,$root.caffe.PoolingParameter.prototype.stride_h=0,$root.caffe.PoolingParameter.prototype.stride_w=0,$root.caffe.PoolingParameter.prototype.engine=0,$root.caffe.PoolingParameter.prototype.global_pooling=!1,$root.caffe.PoolingParameter.prototype.round_mode=0,$root.caffe.PoolingParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.PoolingParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.PoolingParameter.RoundMode={CEIL:0,FLOOR:1},$root.caffe.PowerParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PowerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.power=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PowerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"power":a.power=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.PowerParameter.prototype.power=1,$root.caffe.PowerParameter.prototype.scale=1,$root.caffe.PowerParameter.prototype.shift=0,$root.caffe.PythonParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PythonParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.module=e.string();break;case 2:r.layer=e.string();break;case 3:r.param_str=e.string();break;case 4:r.share_in_parallel=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PythonParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"module":a.module=e.string();break;case"layer":a.layer=e.string();break;case"param_str":a.param_str=e.string();break;case"share_in_parallel":a.share_in_parallel=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.PythonParameter.prototype.module="",$root.caffe.PythonParameter.prototype.layer="",$root.caffe.PythonParameter.prototype.param_str="",$root.caffe.PythonParameter.prototype.share_in_parallel=!1,$root.caffe.RecurrentParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.RecurrentParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 3:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.debug_info=e.bool();break;case 5:r.expose_hidden=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.RecurrentParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"debug_info":a.debug_info=e.boolean();break;case"expose_hidden":a.expose_hidden=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.RecurrentParameter.prototype.num_output=0,$root.caffe.RecurrentParameter.prototype.weight_filler=null,$root.caffe.RecurrentParameter.prototype.bias_filler=null,$root.caffe.RecurrentParameter.prototype.debug_info=!1,$root.caffe.RecurrentParameter.prototype.expose_hidden=!1,$root.caffe.ReductionParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReductionParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.operation=e.int32();break;case 2:r.axis=e.int32();break;case 3:r.coeff=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReductionParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"operation":a.operation=e.enum($root.caffe.ReductionParameter.ReductionOp);break;case"axis":a.axis=e.integer();break;case"coeff":a.coeff=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ReductionParameter.prototype.operation=1,$root.caffe.ReductionParameter.prototype.axis=0,$root.caffe.ReductionParameter.prototype.coeff=1,$root.caffe.ReductionParameter.ReductionOp={SUM:1,ASUM:2,SUMSQ:3,MEAN:4},$root.caffe.ReLUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReLUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.negative_slope=e.float();break;case 2:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReLUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"negative_slope":a.negative_slope=e.float();break;case"engine":a.engine=e.enum($root.caffe.ReLUParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.ReLUParameter.prototype.negative_slope=0,$root.caffe.ReLUParameter.prototype.engine=0,$root.caffe.ReLUParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.ReshapeParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReshapeParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;case 2:r.axis=e.int32();break;case 3:r.num_axes=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReshapeParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ReshapeParameter.prototype.shape=null,$root.caffe.ReshapeParameter.prototype.axis=0,$root.caffe.ReshapeParameter.prototype.num_axes=-1,$root.caffe.ScaleParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ScaleParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.num_axes=e.int32();break;case 3:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.bias_term=e.bool();break;case 5:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ScaleParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_term":a.bias_term=e.boolean();break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.ScaleParameter.prototype.axis=1,$root.caffe.ScaleParameter.prototype.num_axes=1,$root.caffe.ScaleParameter.prototype.filler=null,$root.caffe.ScaleParameter.prototype.bias_term=!1,$root.caffe.ScaleParameter.prototype.bias_filler=null,$root.caffe.SigmoidParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SigmoidParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SigmoidParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.SigmoidParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.SigmoidParameter.prototype.engine=0,$root.caffe.SigmoidParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.SliceParameter=class{constructor(){this.slice_point=[]}static decode(e,a){const r=new $root.caffe.SliceParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 3:r.axis=e.int32();break;case 2:r.slice_point=e.array(r.slice_point,(()=>e.uint32()),a);break;case 1:r.slice_dim=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SliceParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"slice_point":e.array(a.slice_point,(()=>e.integer()));break;case"slice_dim":a.slice_dim=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SliceParameter.prototype.axis=1,$root.caffe.SliceParameter.prototype.slice_dim=1,$root.caffe.SoftmaxParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SoftmaxParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;case 2:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SoftmaxParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.SoftmaxParameter.Engine);break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SoftmaxParameter.prototype.engine=0,$root.caffe.SoftmaxParameter.prototype.axis=1,$root.caffe.SoftmaxParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.SwishParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SwishParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.beta=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SwishParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"beta":a.beta=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.SwishParameter.prototype.beta=1,$root.caffe.TanHParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.TanHParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TanHParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.TanHParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.TanHParameter.prototype.engine=0,$root.caffe.TanHParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.TileParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.TileParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.tiles=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TileParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"tiles":a.tiles=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.TileParameter.prototype.axis=1,$root.caffe.TileParameter.prototype.tiles=0,$root.caffe.ThresholdParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ThresholdParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.threshold=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ThresholdParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"threshold":a.threshold=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ThresholdParameter.prototype.threshold=0,$root.caffe.WindowDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.WindowDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 4:r.batch_size=e.uint32();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 7:r.fg_threshold=e.float();break;case 8:r.bg_threshold=e.float();break;case 9:r.fg_fraction=e.float();break;case 10:r.context_pad=e.uint32();break;case 11:r.crop_mode=e.string();break;case 12:r.cache_images=e.bool();break;case 13:r.root_folder=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.WindowDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"fg_threshold":a.fg_threshold=e.float();break;case"bg_threshold":a.bg_threshold=e.float();break;case"fg_fraction":a.fg_fraction=e.float();break;case"context_pad":a.context_pad=e.integer();break;case"crop_mode":a.crop_mode=e.string();break;case"cache_images":a.cache_images=e.boolean();break;case"root_folder":a.root_folder=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.WindowDataParameter.prototype.source="",$root.caffe.WindowDataParameter.prototype.scale=1,$root.caffe.WindowDataParameter.prototype.mean_file="",$root.caffe.WindowDataParameter.prototype.batch_size=0,$root.caffe.WindowDataParameter.prototype.crop_size=0,$root.caffe.WindowDataParameter.prototype.mirror=!1,$root.caffe.WindowDataParameter.prototype.fg_threshold=.5,$root.caffe.WindowDataParameter.prototype.bg_threshold=.5,$root.caffe.WindowDataParameter.prototype.fg_fraction=.25,$root.caffe.WindowDataParameter.prototype.context_pad=0,$root.caffe.WindowDataParameter.prototype.crop_mode="warp",$root.caffe.WindowDataParameter.prototype.cache_images=!1,$root.caffe.WindowDataParameter.prototype.root_folder="",$root.caffe.SPPParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SPPParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.pyramid_height=e.uint32();break;case 2:r.pool=e.int32();break;case 6:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SPPParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"pyramid_height":a.pyramid_height=e.integer();break;case"pool":a.pool=e.enum($root.caffe.SPPParameter.PoolMethod);break;case"engine":a.engine=e.enum($root.caffe.SPPParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.SPPParameter.prototype.pyramid_height=0,$root.caffe.SPPParameter.prototype.pool=0,$root.caffe.SPPParameter.prototype.engine=0,$root.caffe.SPPParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.SPPParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.V1LayerParameter=class{constructor(){this.bottom=[],this.top=[],this.include=[],this.exclude=[],this.blobs=[],this.param=[],this.blob_share_mode=[],this.blobs_lr=[],this.weight_decay=[],this.loss_weight=[]}static decode(e,a){const r=new $root.caffe.V1LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 2:r.bottom.push(e.string());break;case 3:r.top.push(e.string());break;case 4:r.name=e.string();break;case 32:r.include.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 33:r.exclude.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 5:r.type=e.int32();break;case 6:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 1001:r.param.push(e.string());break;case 1002:r.blob_share_mode=e.array(r.blob_share_mode,(()=>e.int32()),a);break;case 7:r.blobs_lr=e.floats(r.blobs_lr,a);break;case 8:r.weight_decay=e.floats(r.weight_decay,a);break;case 35:r.loss_weight=e.floats(r.loss_weight,a);break;case 27:r.accuracy_param=$root.caffe.AccuracyParameter.decode(e,e.uint32());break;case 23:r.argmax_param=$root.caffe.ArgMaxParameter.decode(e,e.uint32());break;case 9:r.concat_param=$root.caffe.ConcatParameter.decode(e,e.uint32());break;case 40:r.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decode(e,e.uint32());break;case 10:r.convolution_param=$root.caffe.ConvolutionParameter.decode(e,e.uint32());break;case 11:r.data_param=$root.caffe.DataParameter.decode(e,e.uint32());break;case 12:r.dropout_param=$root.caffe.DropoutParameter.decode(e,e.uint32());break;case 26:r.dummy_data_param=$root.caffe.DummyDataParameter.decode(e,e.uint32());break;case 24:r.eltwise_param=$root.caffe.EltwiseParameter.decode(e,e.uint32());break;case 41:r.exp_param=$root.caffe.ExpParameter.decode(e,e.uint32());break;case 13:r.hdf5_data_param=$root.caffe.HDF5DataParameter.decode(e,e.uint32());break;case 14:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;case 29:r.hinge_loss_param=$root.caffe.HingeLossParameter.decode(e,e.uint32());break;case 15:r.image_data_param=$root.caffe.ImageDataParameter.decode(e,e.uint32());break;case 16:r.infogain_loss_param=$root.caffe.InfogainLossParameter.decode(e,e.uint32());break;case 17:r.inner_product_param=$root.caffe.InnerProductParameter.decode(e,e.uint32());break;case 18:r.lrn_param=$root.caffe.LRNParameter.decode(e,e.uint32());break;case 22:r.memory_data_param=$root.caffe.MemoryDataParameter.decode(e,e.uint32());break;case 34:r.mvn_param=$root.caffe.MVNParameter.decode(e,e.uint32());break;case 19:r.pooling_param=$root.caffe.PoolingParameter.decode(e,e.uint32());break;case 21:r.power_param=$root.caffe.PowerParameter.decode(e,e.uint32());break;case 30:r.relu_param=$root.caffe.ReLUParameter.decode(e,e.uint32());break;case 38:r.sigmoid_param=$root.caffe.SigmoidParameter.decode(e,e.uint32());break;case 39:r.softmax_param=$root.caffe.SoftmaxParameter.decode(e,e.uint32());break;case 31:r.slice_param=$root.caffe.SliceParameter.decode(e,e.uint32());break;case 37:r.tanh_param=$root.caffe.TanHParameter.decode(e,e.uint32());break;case 25:r.threshold_param=$root.caffe.ThresholdParameter.decode(e,e.uint32());break;case 20:r.window_data_param=$root.caffe.WindowDataParameter.decode(e,e.uint32());break;case 36:r.transform_param=$root.caffe.TransformationParameter.decode(e,e.uint32());break;case 42:r.loss_param=$root.caffe.LossParameter.decode(e,e.uint32());break;case 1:r.layer=$root.caffe.V0LayerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.V1LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"bottom":e.array(a.bottom,(()=>e.string()));break;case"top":e.array(a.top,(()=>e.string()));break;case"name":a.name=e.string();break;case"include":a.include.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"exclude":a.exclude.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"type":a.type=e.enum($root.caffe.V1LayerParameter.LayerType);break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"param":e.array(a.param,(()=>e.string()));break;case"blob_share_mode":e.array(a.blob_share_mode,(()=>e.enum($root.caffe.V1LayerParameter.DimCheckMode)));break;case"blobs_lr":e.array(a.blobs_lr,(()=>e.float()));break;case"weight_decay":e.array(a.weight_decay,(()=>e.float()));break;case"loss_weight":e.array(a.loss_weight,(()=>e.float()));break;case"accuracy_param":a.accuracy_param=$root.caffe.AccuracyParameter.decodeText(e,!0);break;case"argmax_param":a.argmax_param=$root.caffe.ArgMaxParameter.decodeText(e,!0);break;case"concat_param":a.concat_param=$root.caffe.ConcatParameter.decodeText(e,!0);break;case"contrastive_loss_param":a.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decodeText(e,!0);break;case"convolution_param":a.convolution_param=$root.caffe.ConvolutionParameter.decodeText(e,!0);break;case"data_param":a.data_param=$root.caffe.DataParameter.decodeText(e,!0);break;case"dropout_param":a.dropout_param=$root.caffe.DropoutParameter.decodeText(e,!0);break;case"dummy_data_param":a.dummy_data_param=$root.caffe.DummyDataParameter.decodeText(e,!0);break;case"eltwise_param":a.eltwise_param=$root.caffe.EltwiseParameter.decodeText(e,!0);break;case"exp_param":a.exp_param=$root.caffe.ExpParameter.decodeText(e,!0);break;case"hdf5_data_param":a.hdf5_data_param=$root.caffe.HDF5DataParameter.decodeText(e,!0);break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;case"hinge_loss_param":a.hinge_loss_param=$root.caffe.HingeLossParameter.decodeText(e,!0);break;case"image_data_param":a.image_data_param=$root.caffe.ImageDataParameter.decodeText(e,!0);break;case"infogain_loss_param":a.infogain_loss_param=$root.caffe.InfogainLossParameter.decodeText(e,!0);break;case"inner_product_param":a.inner_product_param=$root.caffe.InnerProductParameter.decodeText(e,!0);break;case"lrn_param":a.lrn_param=$root.caffe.LRNParameter.decodeText(e,!0);break;case"memory_data_param":a.memory_data_param=$root.caffe.MemoryDataParameter.decodeText(e,!0);break;case"mvn_param":a.mvn_param=$root.caffe.MVNParameter.decodeText(e,!0);break;case"pooling_param":a.pooling_param=$root.caffe.PoolingParameter.decodeText(e,!0);break;case"power_param":a.power_param=$root.caffe.PowerParameter.decodeText(e,!0);break;case"relu_param":a.relu_param=$root.caffe.ReLUParameter.decodeText(e,!0);break;case"sigmoid_param":a.sigmoid_param=$root.caffe.SigmoidParameter.decodeText(e,!0);break;case"softmax_param":a.softmax_param=$root.caffe.SoftmaxParameter.decodeText(e,!0);break;case"slice_param":a.slice_param=$root.caffe.SliceParameter.decodeText(e,!0);break;case"tanh_param":a.tanh_param=$root.caffe.TanHParameter.decodeText(e,!0);break;case"threshold_param":a.threshold_param=$root.caffe.ThresholdParameter.decodeText(e,!0);break;case"window_data_param":a.window_data_param=$root.caffe.WindowDataParameter.decodeText(e,!0);break;case"transform_param":a.transform_param=$root.caffe.TransformationParameter.decodeText(e,!0);break;case"loss_param":a.loss_param=$root.caffe.LossParameter.decodeText(e,!0);break;case"layer":a.layer=$root.caffe.V0LayerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.V1LayerParameter.prototype.name="",$root.caffe.V1LayerParameter.prototype.type=0,$root.caffe.V1LayerParameter.prototype.accuracy_param=null,$root.caffe.V1LayerParameter.prototype.argmax_param=null,$root.caffe.V1LayerParameter.prototype.concat_param=null,$root.caffe.V1LayerParameter.prototype.contrastive_loss_param=null,$root.caffe.V1LayerParameter.prototype.convolution_param=null,$root.caffe.V1LayerParameter.prototype.data_param=null,$root.caffe.V1LayerParameter.prototype.dropout_param=null,$root.caffe.V1LayerParameter.prototype.dummy_data_param=null,$root.caffe.V1LayerParameter.prototype.eltwise_param=null,$root.caffe.V1LayerParameter.prototype.exp_param=null,$root.caffe.V1LayerParameter.prototype.hdf5_data_param=null,$root.caffe.V1LayerParameter.prototype.hdf5_output_param=null,$root.caffe.V1LayerParameter.prototype.hinge_loss_param=null,$root.caffe.V1LayerParameter.prototype.image_data_param=null,$root.caffe.V1LayerParameter.prototype.infogain_loss_param=null,$root.caffe.V1LayerParameter.prototype.inner_product_param=null,$root.caffe.V1LayerParameter.prototype.lrn_param=null,$root.caffe.V1LayerParameter.prototype.memory_data_param=null,$root.caffe.V1LayerParameter.prototype.mvn_param=null,$root.caffe.V1LayerParameter.prototype.pooling_param=null,$root.caffe.V1LayerParameter.prototype.power_param=null,$root.caffe.V1LayerParameter.prototype.relu_param=null,$root.caffe.V1LayerParameter.prototype.sigmoid_param=null,$root.caffe.V1LayerParameter.prototype.softmax_param=null,$root.caffe.V1LayerParameter.prototype.slice_param=null,$root.caffe.V1LayerParameter.prototype.tanh_param=null,$root.caffe.V1LayerParameter.prototype.threshold_param=null,$root.caffe.V1LayerParameter.prototype.window_data_param=null,$root.caffe.V1LayerParameter.prototype.transform_param=null,$root.caffe.V1LayerParameter.prototype.loss_param=null,$root.caffe.V1LayerParameter.prototype.layer=null,$root.caffe.V1LayerParameter.LayerType={NONE:0,ABSVAL:35,ACCURACY:1,ARGMAX:30,BNLL:2,CONCAT:3,CONTRASTIVE_LOSS:37,CONVOLUTION:4,DATA:5,DECONVOLUTION:39,DROPOUT:6,DUMMY_DATA:32,EUCLIDEAN_LOSS:7,ELTWISE:25,EXP:38,FLATTEN:8,HDF5_DATA:9,HDF5_OUTPUT:10,HINGE_LOSS:28,IM2COL:11,IMAGE_DATA:12,INFOGAIN_LOSS:13,INNER_PRODUCT:14,LRN:15,MEMORY_DATA:29,MULTINOMIAL_LOGISTIC_LOSS:16,MVN:34,POOLING:17,POWER:26,RELU:18,SIGMOID:19,SIGMOID_CROSS_ENTROPY_LOSS:27,SILENCE:36,SOFTMAX:20,SOFTMAX_LOSS:21,SPLIT:22,SLICE:33,TANH:23,WINDOW_DATA:24,THRESHOLD:31},$root.caffe.V1LayerParameter.DimCheckMode={STRICT:0,PERMISSIVE:1},$root.caffe.V0LayerParameter=class{constructor(){this.blobs=[],this.blobs_lr=[],this.weight_decay=[]}static decode(e,a){const r=new $root.caffe.V0LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.type=e.string();break;case 3:r.num_output=e.uint32();break;case 4:r.biasterm=e.bool();break;case 5:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 6:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 7:r.pad=e.uint32();break;case 8:r.kernelsize=e.uint32();break;case 9:r.group=e.uint32();break;case 10:r.stride=e.uint32();break;case 11:r.pool=e.int32();break;case 12:r.dropout_ratio=e.float();break;case 13:r.local_size=e.uint32();break;case 14:r.alpha=e.float();break;case 15:r.beta=e.float();break;case 22:r.k=e.float();break;case 16:r.source=e.string();break;case 17:r.scale=e.float();break;case 18:r.meanfile=e.string();break;case 19:r.batchsize=e.uint32();break;case 20:r.cropsize=e.uint32();break;case 21:r.mirror=e.bool();break;case 50:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 51:r.blobs_lr=e.floats(r.blobs_lr,a);break;case 52:r.weight_decay=e.floats(r.weight_decay,a);break;case 53:r.rand_skip=e.uint32();break;case 54:r.det_fg_threshold=e.float();break;case 55:r.det_bg_threshold=e.float();break;case 56:r.det_fg_fraction=e.float();break;case 58:r.det_context_pad=e.uint32();break;case 59:r.det_crop_mode=e.string();break;case 60:r.new_num=e.int32();break;case 61:r.new_channels=e.int32();break;case 62:r.new_height=e.int32();break;case 63:r.new_width=e.int32();break;case 64:r.shuffle_images=e.bool();break;case 65:r.concat_dim=e.uint32();break;case 1001:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.V0LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"type":a.type=e.string();break;case"num_output":a.num_output=e.integer();break;case"biasterm":a.biasterm=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"pad":a.pad=e.integer();break;case"kernelsize":a.kernelsize=e.integer();break;case"group":a.group=e.integer();break;case"stride":a.stride=e.integer();break;case"pool":a.pool=e.enum($root.caffe.V0LayerParameter.PoolMethod);break;case"dropout_ratio":a.dropout_ratio=e.float();break;case"local_size":a.local_size=e.integer();break;case"alpha":a.alpha=e.float();break;case"beta":a.beta=e.float();break;case"k":a.k=e.float();break;case"source":a.source=e.string();break;case"scale":a.scale=e.float();break;case"meanfile":a.meanfile=e.string();break;case"batchsize":a.batchsize=e.integer();break;case"cropsize":a.cropsize=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"blobs_lr":e.array(a.blobs_lr,(()=>e.float()));break;case"weight_decay":e.array(a.weight_decay,(()=>e.float()));break;case"rand_skip":a.rand_skip=e.integer();break;case"det_fg_threshold":a.det_fg_threshold=e.float();break;case"det_bg_threshold":a.det_bg_threshold=e.float();break;case"det_fg_fraction":a.det_fg_fraction=e.float();break;case"det_context_pad":a.det_context_pad=e.integer();break;case"det_crop_mode":a.det_crop_mode=e.string();break;case"new_num":a.new_num=e.integer();break;case"new_channels":a.new_channels=e.integer();break;case"new_height":a.new_height=e.integer();break;case"new_width":a.new_width=e.integer();break;case"shuffle_images":a.shuffle_images=e.boolean();break;case"concat_dim":a.concat_dim=e.integer();break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.V0LayerParameter.prototype.name="",$root.caffe.V0LayerParameter.prototype.type="",$root.caffe.V0LayerParameter.prototype.num_output=0,$root.caffe.V0LayerParameter.prototype.biasterm=!0,$root.caffe.V0LayerParameter.prototype.weight_filler=null,$root.caffe.V0LayerParameter.prototype.bias_filler=null,$root.caffe.V0LayerParameter.prototype.pad=0,$root.caffe.V0LayerParameter.prototype.kernelsize=0,$root.caffe.V0LayerParameter.prototype.group=1,$root.caffe.V0LayerParameter.prototype.stride=1,$root.caffe.V0LayerParameter.prototype.pool=0,$root.caffe.V0LayerParameter.prototype.dropout_ratio=.5,$root.caffe.V0LayerParameter.prototype.local_size=5,$root.caffe.V0LayerParameter.prototype.alpha=1,$root.caffe.V0LayerParameter.prototype.beta=.75,$root.caffe.V0LayerParameter.prototype.k=1,$root.caffe.V0LayerParameter.prototype.source="",$root.caffe.V0LayerParameter.prototype.scale=1,$root.caffe.V0LayerParameter.prototype.meanfile="",$root.caffe.V0LayerParameter.prototype.batchsize=0,$root.caffe.V0LayerParameter.prototype.cropsize=0,$root.caffe.V0LayerParameter.prototype.mirror=!1,$root.caffe.V0LayerParameter.prototype.rand_skip=0,$root.caffe.V0LayerParameter.prototype.det_fg_threshold=.5,$root.caffe.V0LayerParameter.prototype.det_bg_threshold=.5,$root.caffe.V0LayerParameter.prototype.det_fg_fraction=.25,$root.caffe.V0LayerParameter.prototype.det_context_pad=0,$root.caffe.V0LayerParameter.prototype.det_crop_mode="warp",$root.caffe.V0LayerParameter.prototype.new_num=0,$root.caffe.V0LayerParameter.prototype.new_channels=0,$root.caffe.V0LayerParameter.prototype.new_height=0,$root.caffe.V0LayerParameter.prototype.new_width=0,$root.caffe.V0LayerParameter.prototype.shuffle_images=!1,$root.caffe.V0LayerParameter.prototype.concat_dim=1,$root.caffe.V0LayerParameter.prototype.hdf5_output_param=null,$root.caffe.V0LayerParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.PReLUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PReLUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 2:r.channel_shared=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PReLUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"channel_shared":a.channel_shared=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.PReLUParameter.prototype.filler=null,$root.caffe.PReLUParameter.prototype.channel_shared=!1; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe.js new file mode 100644 index 0000000000000000000000000000000000000000..3396d443340ff0489750ec2a4f1cd7e3edd0ce5d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe.js @@ -0,0 +1 @@ +var caffe=caffe||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");caffe.ModelFactory=class{match(t){const e=t.identifier,a=e.split(".").pop().toLowerCase();if("caffemodel"==a)return!0;if("pbtxt"==a||"prototxt"==a){if("saved_model.pbtxt"==e||"saved_model.prototxt"==e||e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const a=t.tags("pbtxt");if(a.has("layer")||a.has("layers")||a.has("net")||a.has("train_net")||a.has("net_param"))return!0}if("pt"==a){const e=t.buffer,a=[138,10,108,252,156,70,249,32,106,168,80,25];if(e&&e.length>14&&128==e[0]&&a.every(((t,a)=>t==e[a+2])))return!1;if(e&&e.length>2&&80==e[0]&&75==e[1])return!1;const n=t.tags("pbtxt");if(n.has("layer")||n.has("layers")||n.has("net")||n.has("train_net")||n.has("net_param"))return!0}return!1}open(t,e){return e.require("./caffe-proto").then((()=>(caffe.proto=protobuf.get("caffe").caffe,caffe.Metadata.open(e).then((a=>{const n=t.identifier.split(".").pop();if("pbtxt"==n||"prototxt"==n||"pt"==n){const n=t.tags("pbtxt");if(n.has("net")||n.has("train_net")||n.has("net_param"))try{const n=protobuf.TextReader.create(t.text);n.field=function(t,e){if(!(e instanceof caffe.proto.SolverParameter))throw new Error("Unknown field '"+t+"'"+this.location());e[t]=this.skip()};const r=caffe.proto.SolverParameter.decodeText(n);if(r.net_param)return this._openNetParameter(a,r.net_param,e);if(r.net||r.train_net){let n=r.net||r.train_net;return n=n.split("/").pop(),t.request(n,"utf-8").then((n=>this._openNetParameterText(a,t.identifier,n,e))).catch((t=>{if(t){const e=t&&t.message?t.message:t.toString();throw new caffe.Error("Failed to load '"+n+"' ("+e.replace(/\.$/,"")+").")}}))}}catch(t){}return this._openNetParameterText(a,t.identifier,t.text,e)}return this._openNetParameterBuffer(a,t.identifier,t.buffer,e)})))))}_openNetParameterBuffer(t,e,a,n,r,s){try{const e=protobuf.Reader.create(a),i=caffe.proto.NetParameter.decode(e);return this._openNetParameter(t,i,n,r,s)}catch(t){throw new caffe.Error("File format is not caffe.NetParameter ("+t.message+") in '"+e+"'.")}}_openNetParameterText(t,e,a,n){try{const e=protobuf.TextReader.create(a);e.field=function(t,a){const n=a.constructor.name;if(!t.endsWith("_param")||"LayerParameter"!=n&&"V1LayerParameter"!=n&&"V0LayerParameter"!=n){if(!a.constructor.name.endsWith("Parameter")&&"ParamSpec"!==a.constructor.name)throw new Error("Unknown field '"+t+"'"+this.location());a[t]?(Array.isArray(a[t])||(a[t]=[a[t]]),a[t].push(this.skip())):a[t]=this.skip()}else a[t]=caffe.ModelFactory._decodeText(e)},e.enum=function(t){const e=this.read();if(!Object.prototype.hasOwnProperty.call(t,e)){const t=Number.parseInt(e,10);return Number.isNaN(e-t)?e:t}return t[e]};const r=caffe.proto.NetParameter.decodeText(e);return this._openNetParameter(t,r,n)}catch(t){throw new caffe.Error("File text format is not caffe.NetParameter ("+t.message+") in '"+e+"'.")}}_openNetParameter(t,e,a){try{return new caffe.Model(t,e)}catch(t){throw a.exception(t,!1),new caffe.Error(t.message)}}static _decodeText(t){const e={};for(t.start();!t.end();){const a=t.tag(),n=t.skip();e[a]?(Array.isArray(e[a])||(e[a]=[e[a]]),e[a].push(n)):e[a]=n}return e}},caffe.Model=class{constructor(t,e){this._name=e.name,e.layers&&e.layers.length>0?e.layers.every((t=>Object.prototype.hasOwnProperty.call(t,"layer")))?(this._version=0,e.layer=e.layers):(this._version=1,e.layer=e.layers):e.layer&&e.layer.length>0&&(this._version=2),this._graphs=[];const a=new Set;for(const t of e.layer)for(const e of t.include)void 0!==e.phase&&a.add(e.phase);0===a.size&&a.add(-1);for(const n of a)this._graphs.push(new caffe.Graph(t,n,e,this._version))}get format(){return"Caffe"+(this._version?" v"+this._version.toString():"")}get graphs(){return this._graphs}},caffe.Graph=class{constructor(t,e,a,n){switch(e){case 0:this._phase="TRAIN";break;case 1:this._phase="TEST";break;case-1:this._phase="";break;default:this._phase=e.toString()}this._nodes=[],this._inputs=[],this._outputs=[];for(const t of a.layer)t.input=t.bottom.slice(0),t.output=t.top.slice(0),t.chain=[];const r=[];for(const t of a.layer)(-1===e||t.include.every((t=>t.phase===e)))&&r.push(t);const s={};let i=0;for(const t of r)t.input=t.input.map((t=>s[t]?s[t]:t)),t.output=t.output.map((t=>(s[t]=s[t]?t+"\n"+i.toString():t,s[t]))),i++;const o=new Set;for(const t of r)for(const e of t.output)o.add(e);const c=[];for(const t of r)for(const e of t.input)o.has(e)||c.push(e);const u=[];let p=null,f=null;for(;r.length>0;){let t=r.shift();if(1==t.output.length&&1==t.input.length&&t.output[0].split("\n").shift()==t.input[0].split("\n").shift()&&p&&f==t.output[0].split("\n").shift())p.chain=p.chain||[],p.chain.push(t);else{if(("Input"==t.type||"Data"==t.type)&&0==t.input.length&&1==t.output.length&&t.input_param&&t.input_param.shape&&1==t.input_param.shape.length&&t.input_param.shape[0].dim){const e=new caffe.TensorType(null,new caffe.TensorShape(t.input_param.shape[0].dim));this._inputs.push(new caffe.Parameter(t.output[0],[new caffe.Argument(t.output[0],e)])),t=null}t&&(u.push(t),p=null,f=null,1==t.output.length&&(p=t,f=t.output[0].split("\n").shift()))}}if(a.input)for(let t=0;tt.name===e)))continue;let n=null;if(a.input_shape&&t=r&&(n=new caffe.TensorType(null,new caffe.TensorShape(a.input_dim.slice(r,r+4)))),this._inputs.push(new caffe.Parameter(e,[new caffe.Argument(e,n,null)]))}for(const e of u){const a=new caffe.Node(t,e,n);if(e.chain&&e.chain.length>0)for(const r of e.chain)a.chain.push(new caffe.Node(t,r,n));this._nodes.push(a)}0===this._inputs.length&&1===c.length&&this._inputs.push(new caffe.Parameter(c[0],[new caffe.Argument(c[0],null)]))}get name(){return this._phase}get type(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},caffe.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},caffe.Argument=class{constructor(t,e,a){if("string"!=typeof t)throw new caffe.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=a||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},caffe.Node=class{constructor(t,e,a){switch(this._metadata=t,this._chain=[],this._attributes=[],a){case 0:this._name=e.layer.name,this._type=e.layer.type;break;case 1:{this._name=e.name;const t=e.type;if(void 0===t)this._type="?";else{if(!caffe.Node._typeMap){caffe.Node._typeMap={};const t={BNLL:"BNLL",HDF5:"HDF5",LRN:"LRN",RELU:"ReLU",TANH:"TanH",ARGMAX:"ArgMax",MVN:"MVN",ABSVAL:"AbsVal"};for(const e of Object.keys(caffe.proto.V1LayerParameter.LayerType)){const a=caffe.proto.V1LayerParameter.LayerType[e];caffe.Node._typeMap[a]=e.split("_").map((e=>t[e]||e.substring(0,1)+e.substring(1).toLowerCase())).join("")}}this._type=caffe.Node._typeMap[t]||t.toString()}break}case 2:this._name=e.name,this._type=e.type}let n=[];switch(a){case 0:for(const a of Object.keys(e.layer))"type"!=a&&"name"!=a&&"blobs"!=a&&"blobs_lr"!=a&&this._attributes.push(new caffe.Attribute(t.attribute(this.type,a),a,e.layer[a]));n=e.layer.blobs.map((t=>new caffe.Tensor(t)));break;case 1:case 2:for(const a of Object.keys(e))if(a.endsWith("_param")||"transform_param"==a){const n=e[a];let r=this._type;"Deconvolution"==r&&(r="Convolution");const s=Object.getPrototypeOf(n);for(const e of Object.keys(n)){const a=s[e],r=n[e];r==a||Array.isArray(r)&&Array.isArray(a)&&0==r.length&&0==a.length||this._attributes.push(new caffe.Attribute(t.attribute(this.type,e),e,r))}}e.include&&e.include.length>0&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"include"),"include",e.include)),e.exclude&&e.exclude.length>0&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"exclude"),"exclude",e.exclude)),"Data"==this._type&&e.input_param&&e.input_param.shape&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"shape"),"shape",e.input_param.shape)),n=e.blobs.map((t=>new caffe.Tensor(t)))}const r=this._metadata.type(this.type);this._inputs=[];const s=e.input.concat(n);let i=0;if(r&&r.inputs)for(const t of r.inputs)if(i""!==e||"optional"!=t.option)).map((t=>t instanceof caffe.Tensor?new caffe.Argument("",t.type,t):new caffe.Argument(t,null,null))))),i+=e}this._inputs=this._inputs.concat(s.slice(i).map((t=>new caffe.Parameter(i.toString(),[t instanceof caffe.Tensor?new caffe.Argument("",t.type,t):new caffe.Argument(t,null,null)])))),this._outputs=[];const o=e.output;let c=0;if(r&&r.outputs)for(const t of r.outputs)if(cnew caffe.Argument(t,null,null))))),c+=e}this._outputs=this._outputs.concat(o.slice(c).map(((t,e)=>new caffe.Parameter((c+e).toString(),[new caffe.Argument(t,null,null)]))))}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}},caffe.Attribute=class{constructor(t,e,a){if(this._name=e,this._value=a,a instanceof caffe.proto.BlobShape&&(this._value=new caffe.TensorShape(a.dim)),t)if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){const e=t.default;(this._value==e||Array.isArray(this._value)&&Array.isArray(e)&&this._value.length==e.length&&this._value.every(((t,a)=>t==e[a])))&&(this._visible=!1)}}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},caffe.Tensor=class{constructor(t){this._blob=t;let e=[];Object.prototype.hasOwnProperty.call(t,"num")&&Object.prototype.hasOwnProperty.call(t,"channels")&&Object.prototype.hasOwnProperty.call(t,"width")&&Object.prototype.hasOwnProperty.call(t,"height")?(1!=t.num&&e.push(t.num),1!=t.channels&&e.push(t.channels),1!=t.width&&e.push(t.width),1!=t.height&&e.push(t.height)):Object.prototype.hasOwnProperty.call(t,"shape")&&(e=t.shape.dim);let a="?";t.data.length>0?(a="float32",this._data=t.data):t.double_data.length>0&&(a="float64",this._data=t.double_data),this._type=new caffe.TensorType(a,new caffe.TensorShape(e))}get kind(){return"Blob"}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return t.data=this._data,t.dimensions=this.type.shape.dimensions,this._data||(t.state="Tensor data is empty."),t}_decode(t,e){const a=[],n=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return a.push("..."),a;a.push(t.data[t.index]),t.index++,t.count++}else for(let r=0;rt.limit)return a.push("..."),a;a.push(this._decode(t,e+1))}return a}},caffe.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},caffe.TensorShape=class{constructor(t){this._dimensions=t.map((t=>t&&long.Long.isLong(t)?t.toNumber():t))}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},caffe.Metadata=class{static open(t){return caffe.Metadata._metadata?Promise.resolve(caffe.Metadata._metadata):t.request(null,"caffe-metadata.json","utf-8").then((t=>(caffe.Metadata._metadata=new caffe.Metadata(t),caffe.Metadata._metadata))).catch((()=>(caffe.Metadata._metadata=new caffe.Metadata(null),caffe.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},caffe.Error=class extends Error{constructor(t){super(t),this.name="Error loading Caffe model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=caffe.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..072a1ec57b9ae6e7fd010eaf4303dac8f4fed82e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-metadata.json @@ -0,0 +1 @@ +[{"name":"Conv","schema":{"attributes":[{"default":0,"name":"pad"},{"default":1,"name":"stride"},{"name":"exhaustive_search","type":"boolean","visible":false}],"category":"Layer","description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"ConvTranspose","schema":{"attributes":[{"description":"Should the legacy padding be VALID or SAME. When used, pads should not be used.","name":"legacy_pad","option":"optional","type":"int64"},{"description":"Desired kernel size. If left at default the kernel size will be inferred from the input $filter$ blob.","name":"kernels","option":"optional","type":"int64[]"},{"description":"Controls the stride of the kernel as it traverses the input blob.","name":"strides","option":"optional","type":"int64[]"},{"description":"Controls the amount of padding applied to the input feature map before computation.","name":"pads","option":"optional","type":"int64[]"},{"description":"","name":"adjs","option":"optional","type":"int64[]"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"},{"default":0,"description":"","name":"shared_buffer","option":"optional","type":"int64"},{"default":false,"description":"","name":"no_bias","option":"optional","type":"boolean"}],"category":"Layer","description":"\nThe ConvTranspose op takes an input data tensor $X$, an input weight tensor $filter$, and optionally an input bias tensor $bias$. It then computes the transposed convolution, sometimes referred to as deconvolution, and produces a single output tensor $Y$. The hyperparameters of the op such as kernel size, stride, and padding are specified as args. At each stride, the filter is deconvolved with a subset of $X$ and the $bias$ is added. This is done throughout the input data until the output computation is complete.\n\nThe output shapes are computed as follows. The number of channels in the output feature map is the number of kernels specified in the filter blob. The spatial height and width are computed as:\n\n$$H_{out} = (H_{in}-1)*strides[0] - 2*pads[0] + kernels[0]$$\n\n\n$$W_{out} = (W_{in}-1)*strides[1] - 2*pads[1] + kernels[1]$$\n\nNote on the implementation layout: conv_transpose_op_impl.h is the templated implementation of the conv_transpose_op.h file, which is why they are separate files. Also, in the implementation this operator inherits from the *ConvTransposeUnpoolOpBase* operator.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_op.h\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_op.cc\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_unpool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConvTranspose\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernels=[2,2],\n pads=[4,4,4,4],\n strides=[2,2]\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(2,3,5,5).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create filter: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,2,2).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (2, 3, 5, 5)\nFilter shape: (3, 1, 2, 2)\nBias shape: (1,)\nY:\n [[[[0.53606427 0.5775447 ]\n [0.40148795 1.5188271 ]]]\n\n\n [[[1.9903406 3.2794335 ]\n [0.09960175 0.31917763]]]]\n\n```\n\n
\n\n ","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be operated on.","name":"X"},{"description":"The filter blob, of shape $(M, C_{out}, K_H, K_W)$, containing the filters to be used in the transposed convolution.","name":"filter"},{"description":"The bias blob, of length $C_{out}$, containing the biases for the operation, one bias per output channel. If not passed, biases assumed to be zeros.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the operation.","name":"Y"}],"support_level":"default"}},{"name":"FC","schema":{"attributes":[{"default":1,"description":"Describes the axis of the input data $X$. Defaults to one because in the common case when the input $X$ has shape $(M,K)$, the first axis encodes the batch size.","name":"axis","option":"optional","type":"int64"},{"default":1,"description":"Describes the axis of the input weight matrix $W$. Defaults to one because the first axis most likely describes the batch_size.","name":"axis_w","option":"optional","type":"int64"},{"default":false,"description":"Whether to use float-16 compute kernel.","name":"float16_compute","option":"optional","type":"boolean"}],"category":"Layer","description":"\nThe FC operator computes an output $(Y)$ as a linear combination of the input data blob $(X)$ with a weight blob $(W)$ and bias blob $(b)$. More formally,\n\n$$Y = XW^T+b$$\n\nHere, $X$ is a matrix of shape $(M,K)$, $W$ is a matrix of shape $(N,K)$, $b$ is a vector of length $N$, and $Y$ is a matrix of shape $(M,N)$. $N$ can be thought of as the number of nodes in the layer, $M$ is the batch size, and $K$ is the number of features in an input observation.\n\n*NOTE: $X$ does not need to explicitly be a 2-dimensional matrix, however, if it is not it will be coerced into one. For an arbitrary $n$-dimensional tensor $X$, e.g. $[a_0, a_1, \\ldots ,a_{k-1}, a_k, \\ldots , a_{n-1}]$, where $a_i$ in $N$, and $k$ is the $axis$ arg provided, then $X$ will be coerced into a 2-dimensional tensor with dimensions $[a_0 * \\ldots * a_{k-1}, a_k * \\ldots * a_{n-1}]$. For the default case where axis=1, this means the $X$ tensor will be coerced into a 2D tensor of dimensions $[a_0, a_1 * \\ldots * a_{n-1}]$, where $a_0$ is often the batch size. In this situation, we must have $a_0 = M$ and $a_1 * \\ldots * a_{n-1} = K$. Lastly, even though $b$ is a vector of length $N$, it is copied and resized to shape $(M x N)$ implicitly, then added to each vector in the batch.*\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/fully_connected_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/fully_connected_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\n// In this example, our batch size is 1 (M=1), the input observation will have\n// 6 features (K=6), and the layer will have one hidden node (N=1). The\n// expected output is Y=7.\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FC\",\n [\"X\", \"W\", \"b\"],\n [\"Y\"]\n)\n\n// Create X: MxK\ndata = np.array([1,2,3,4,5,6]).astype(np.float32)\ndata = data[np.newaxis,:]\n\n// Create W: NxK\nweights = np.array(np.array([1,1/2.,1/3.,1/4.,1/5.,1/6.])).astype(np.float32)\nweights = weights[np.newaxis,:]\n\n// Create b: N\nbias = np.array([1.]).astype(np.float32)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"W\", weights)\nworkspace.FeedBlob(\"b\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nY:\n [[7.]]\n\n```\n\n
\n\n","inputs":[{"description":"Input blob to be coerced into a 2D matrix of shape $(M,K)$, where $M$ is the batch size and $K$ is the number of features in a single observation.","name":"X"},{"description":"Input blob to be coerced into a 2D matrix of shape $(N,K)$ describing a fully connected weight matrix. Here, $K$ is the number of features in a single observation and $N$ is the number of nodes in the FC layer.","name":"W"},{"description":"Input blob containing vector of length $N$ which describes one bias for each node in the layer.","name":"b"}],"outputs":[{"description":"Output blob containing a 2D output matrix of shape $(M,N)$, where $M$ is the batch size and $N$ is the number of nodes in the layer. The output is calculated as $Y=XW^T+b$.","name":"Y"}],"support_level":"default"}},{"name":"Add","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Add\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[1 2]\n [3 4]]\nB:\n[[5 6]\n [7 8]]\nC:\n[[ 6 8]\n [10 12]]\n\n```\n\n
\n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"Sum","schema":{"description":"\nElement-wise sum of each of the input tensors. The first input tensor can be used\nin-place as the output tensor, in which case the sum will be done in place and\nresults will be accumulated the first input tensor. All inputs and outputs must\nhave the same shape and data type.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_sum_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sum\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA: [[1. 2.]\n [3. 4.]]\nB: [[5. 6.]\n [7. 8.]]\nC: [[1. 2.]\n [3. 4.]]\n\n```\n\n
\n\n
\n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sum\",\n [\"A\", \"B\"],\n [\"A\"], // inplace\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2,5],[8,3,4]]).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.array([[9,5,6],[6,7,8]]).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"A after Sum:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA: [[1. 2. 5.]\n [8. 3. 4.]]\nB: [[9. 5. 6.]\n [6. 7. 8.]]\nA after Sum: [[10. 7. 11.]\n [14. 10. 12.]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First tensor to be added element-wise.","name":"A"},{"description":"*(type: Tensor``)* Second tensor to be added element-wise.","name":"B"},{"description":"First of the input tensors. Can be inplace.","name":"data_0"}],"outputs":[{"description":"*(type: Tensor``)* Sum of A and B.","name":"C"},{"description":"Output tensor. Same dimension as inputs.","name":"sum"}],"support_level":"default"}},{"name":"Mul","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mul\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[1 2]\n [3 4]]\nB:\n[[5 6]\n [7 8]]\nC:\n[[ 5 12]\n [21 32]]\n\n```\n\n
\n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"MatMul","schema":{"attributes":[{"default":1,"description":"Exclusive axis that divides the first and second dimension of matrix `A`.","name":"axis_a","option":"optional","type":"int64"},{"default":1,"description":"Exclusive axis that divides the first and second dimension of matrix `B`.","name":"axis_b","option":"optional","type":"int64"},{"default":0,"description":"Pass 1 to transpose `A` before multiplication and after the dimension adjustment using `axis_a`.","name":"trans_a","option":"optional","type":"int64"},{"default":0,"description":"Pass 1 to transpose `B` before multiplication and after the dimension adjustment using `axis_b`.","name":"trans_b","option":"optional","type":"int64"}],"description":"\nMatrix multiplication $Y = A * B$, where `A` has size (M x K), `B` has size\n(K x N), and `Y` will have a size (M x N). To transpose `A` or `B` before\nmultiplication, pass 1 to the `trans_a` and/or `trans_b` arguments, which\nseparate the first and second dimensions of the respective matrices using\n`axis_a` and `axis_b`.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/matmul_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MatMul\",\n [\"A\", \"B\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nA: [[1. 8. 3.]\n [6. 4. 4.]\n [5. 4. 7.]]\nB: [[4. 0. 3.]\n [3. 1. 1.]\n [8. 5. 8.]]\nY: [[52. 23. 35.]\n [68. 24. 54.]\n [88. 39. 75.]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* 2D matrix of size (M x K).","name":"A"},{"description":"*(type: Tensor``)* 2D matrix of size (K x N).","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* 2D matrix of size (M x N).","name":"Y"}],"support_level":"default"}},{"name":"Relu","schema":{"attributes":[{"name":"cudnn_exhaustive_search","type":"boolean","visible":false}],"category":"Activation","description":"\nApplies rectified linear unit operation to the input data element-wise. The Relu operation takes one input $X$, produces one output $Y$, and is defined as:\n\n$$Y = max(0,X)$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/relu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/relu_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Relu\",\n [\"X\"],\n [\"Y\"]\n )\n\nworkspace.FeedBlob(\"X\", np.random.randn(4, 4).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-1.4655551 0.64575136 0.7921748 0.4150579 ]\n [ 0.41085166 -0.2837964 0.9881425 -1.9300346 ]\n [ 0.39705405 0.44639114 0.9940703 0.2926532 ]\n [-0.6726489 0.01330667 1.101319 0.33858967]]\n\nY:\n [[0. 0.64575136 0.7921748 0.4150579 ]\n [0.41085166 0. 0.9881425 0. ]\n [0.39705405 0.44639114 0.9940703 0.2926532 ]\n [0. 0.01330667 1.101319 0.33858967]]\n\n```\n\n
\n\n\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor with same shape as input","name":"Y"}],"support_level":"default"}},{"name":"Sigmoid","schema":{"category":"Activation","description":"\nApply the Sigmoid function element-wise to the input tensor. This is often used\nas a non-linear activation function in a neural network. The sigmoid function is\ndefined as:\n\n$$Sigmoid(x) = \\frac{1}{1+\\exp(-x)}$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sigmoid_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sigmoid\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"sigmoid:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\ninput: [ 1.5744036 0.31632107 1.7842269 1.4450722 -2.1726978 ]\nsigmoid: [0.8284105 0.57842743 0.85621804 0.80923885 0.10222916]\n\n```\n\n
\n\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"PRelu","schema":{"category":"Activation","description":"\n\nThe *PRelu* op takes input data tensor $X$, an input slope tensor $slope$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise *PRelu* operation, defined as\n\n$$y=prelu(x) =\\begin{cases}slope * x & x < 0\\\\x & otherwise\\end{cases}$$\n\nNote, is slope is size 1, the value is shared across the channels, otherwise $X$ and $slope$ must be the same shape. See [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://arxiv.org/abs/1502.01852) for more information.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/prelu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/prelu_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"PRelu\",\n [\"X\",\"Slope\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.FeedBlob(\"Slope\", np.array([0.1]).astype(np.float32))\nprint(\"Slope:\\n\", workspace.FetchBlob(\"Slope\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 0.3957382 -0.19725518 -0.26991343]\n [ 1.5513182 -0.27427664 -0.14584002]\n [-0.4121164 0.9292345 0.96426094]]\n\nSlope:\n [0.1]\n\nY:\n [[ 0.3957382 -0.01972552 -0.02699134]\n [ 1.5513182 -0.02742766 -0.014584 ]\n [-0.04121164 0.9292345 0.96426094]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"},{"description":"1D input slope tensor. If `Slope` is of size 1, the value is shared across different channels","name":"Slope"}],"outputs":[{"description":"Output tensor, with same shape as $X$.","name":"Y"}],"support_level":"default"}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Axis of the inputs when coerced to 2D matrix.","name":"axis","option":"optional","type":"int64"}],"category":"Activation","description":"\n\nApplies the Softmax function to an n-dimensional input Tensor rescaling them so\nthat the elements of the n-dimensional output Tensor lie in the range (0,1) and\nsum to 1. The softmax operator is typically the last layer in a classifier network,\nas its output can be interpreted as confidence probabilities of an input belonging\nto each class. The input is a 2-D tensor (Tensor) of size (batch_size x\ninput_feature_dimensions). The output tensor has the same shape and contains the\nsoftmax normalized values of the corresponding input. The softmax function is\ndefined as follows:\n\n$$softmax(x_i) = \\frac{\\exp(x_i)}{\\sum_{j} \\exp(x_j)}$$\n\nThe input does not need to explicitly be a 2D vector; rather, it will be coerced\ninto one. For an arbitrary n-dimensional tensor `X` in\n$[a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}]$, where k is the `axis` provided,\nthen `X` will be coerced into a 2-dimensional tensor with dimensions\n$[(a_0 * ... * a_{k-1}), (a_k * ... * a_{n-1})]$. For the default case where\n`axis`=1, the `X` tensor will be coerced into a 2D tensor of dimensions\n$[a_0, (a_1 * ... * a_{n-1})]$, where $a_0$ is often the batch size. In this\nsituation, we must have $a_0 = N$ and $a_1 * ... * a_{n-1} = D$. Each of these\ndimensions must be matched correctly, or else the operator will throw errors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softmax\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\ninput: [[ 0.0417839 0.61960053 -0.23150268 -0.64389366 -3.0000346 ]]\nsoftmax: [[0.24422921 0.43525138 0.18582782 0.12303016 0.01166145]]\n\n```\n\n
\n\n\n\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"},{"description":"*(type: Tensor``)* Input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"X"}],"outputs":[{"description":"The softmax normalized output values with the same shape as input tensor.","name":"output"},{"description":"*(type: Tensor``)* The softmax normalized output tensor with the same shape as input tensor.","name":"Y"}],"support_level":"default"}},{"name":"MaxPool","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"name":"pad"},{"name":"cudnn_exhaustive_search","type":"boolean","visible":false}],"category":"Pool","description":"MaxPool \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool","schema":{"category":"Pool","description":"AveragePool \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"SpatialBN","schema":{"attributes":[{"default":0,"description":"If set to nonzero, run spatial batch normalization in test mode.","name":"is_test","type":"int64"},{"default":0.00001,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","option":"optional","type":"float32"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"},{"default":0.9,"description":"Factor used in computing the running mean and variance. e.g., running_mean = running_mean x momentum + mean x (1 - momentum)","name":"momentum","option":"optional","type":"float32"},{"default":1,"description":"Specifies the number of batches to apply normalization on. Requires specifying the optional sums and sumsq inputs that provide statistics across multiple batches from which mean and variance can be determined.","name":"num_batches","option":"optional","type":"int64"}],"category":"Normalization","description":"\nApplies spatial batch normalization to the input tensor as described in the original paper, [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167). Be aware, this operator has two different output sets, depending on the value of *is_test*. According to the paper, the primary operation of spatial batch normalization is:\n\n$$Y = \\frac{X - \\mu_x}{\\sqrt{\\sigma^2_{x} + \\epsilon}}*\\gamma + b$$\n\nIn the equation, $\\mu_x$ is the *mean*, $X$ is the input data, $\\sigma^2_{x}$ is the *var*, $\\epsilon$ is *epsilon*, $\\gamma$ is the *scale*, $b$ is the *bias*, and $Y$ is the output data. The *momentum* arg also affects this calculation in the computation of the running mean and variance. The influence of *momentum* is as follows:\n\n$$running\\_mean = running\\_mean * momentum + mean * (1 - momentum)$$\n\n$$running\\_var = running\\_var * momentum + var * (1 - momentum)$$\n\nOutput when is_test = 0 (train mode): *Y, mean, var, saved_mean, saved_var*\n\nOutput when is_test = 1 (test mode): *Y*\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/spatial_batch_norm_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/spatial_batch_norm_op.h\n\n","inputs":[{"name":"input"},{"description":"The scale as a 1-dimensional tensor of size $C$ to be applied to the output.","name":"scale"},{"description":"The bias as a 1-dimensional tensor of size $C$ to be applied to the output.","name":"bias"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size $C$.","name":"mean"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size $C$.","name":"var"},{"description":"The input 4-dimensional tensor of shape $NCHW$ or $NHWC$ depending on the order parameter.","name":"X"},{"description":"*(optional)* Per-channel sums of elements to be used to determine the mean and variance for this batch.","name":"sums"},{"description":"*(optional)* Per-channel sum of elements squared per channel to be used to determine the variance for this batch.","name":"sumsq"}],"outputs":[{"description":"The output 4-dimensional tensor of the same shape as $X$.","name":"Y"},{"description":"The running mean after the spatial BN operator. Must be in-place with the input *mean*. Should not be used for testing.","name":"mean"},{"description":"The running variance after the spatial BN operator. Must be in-place with the input *var*. Should not be used for testing.","name":"var"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var"}],"support_level":"default"}},{"name":"LRN","schema":{"attributes":[{"default":0,"description":"Amount of neighboring channels to sum over for normalization","name":"size","option":"optional","type":"int64"},{"default":0,"description":"Multiplicative (scaling) factor.","name":"alpha","option":"optional","type":"float32"},{"default":0,"description":"Exponent.","name":"beta","option":"optional","type":"float32"},{"default":1,"description":"Additive factor.","name":"bias","option":"optional","type":"float32"},{"default":0,"description":"Order of blob dimensions.","name":"order","option":"optional","type":"float32"}],"category":"Normalization","description":"\n\n`LRN` applies Local Response Normalization to an input blob. This operation performs\na kind of \"lateral inhibition\" by normalizing over local input regions, where\nnormalization is applied across channels. This operator is typically used to\nnormalize an unbounded activation (such as ReLU). The output shape is the same as\nthe input shape. The `brew` module has a wrapper for this operator for use in a\n`ModelHelper` object.\n\nThe formula for LRN is as follows:\n\n$$b_{c} = a_{c}(bias + \\frac{\\alpha}{n}\\sum_{c'=max(0,c-n/2)}^{min(N-1,c+n/2)} a_{c'}^2 )^{-\\beta}$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/local_response_normalization_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/local_response_normalization_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\"LRN\",\n [\"X\"],\n [\"Y\", \"Y_scale\"],\n size=11,\n alpha=0.001,\n beta=0.5,\n bias=2.0,\n order=\"NHWC\"\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 6, 6, 1).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nprint(\"Y_scale:\\n\", workspace.FetchBlob(\"Y_scale\"))\n```\n\n**Result**\n\n```\nX:\n [[[[ 0.72985137]\n [-0.3753357 ]\n [ 2.7344604 ]\n [-0.5937792 ]\n [ 0.38440478]\n [-2.1659644 ]]\n\n [[-0.92846817]\n [-0.9996144 ]\n [ 0.212943 ]\n [-1.968045 ]\n [-0.77839696]\n [ 0.45492038]]\n\n [[-0.11263168]\n [ 1.9901097 ]\n [ 0.19275683]\n [ 0.15630436]\n [ 0.7536298 ]\n [-0.77339894]]\n\n [[ 0.8353551 ]\n [-0.7784452 ]\n [ 1.779317 ]\n [ 0.22421335]\n [ 1.3846219 ]\n [-3.0546608 ]]\n\n [[ 0.09977621]\n [ 2.2071757 ]\n [ 0.79971045]\n [ 3.563886 ]\n [-0.7169287 ]\n [ 0.77170426]]\n\n [[-1.4296649 ]\n [ 0.19181213]\n [ 0.45961624]\n [-1.0201577 ]\n [ 0.62854475]\n [-0.6395456 ]]]]\n\nY:\n [[[[ 0.5160766 ]\n [-0.26540157]\n [ 1.9332271 ]\n [-0.41986194]\n [ 0.27181432]\n [-1.5314047 ]]\n\n [[-0.6565133 ]\n [-0.7068181 ]\n [ 0.15057328]\n [-1.3914955 ]\n [-0.5504022 ]\n [ 0.32167578]]\n\n [[-0.0796426 ]\n [ 1.4070934 ]\n [ 0.13629955]\n [ 0.11052381]\n [ 0.53288984]\n [-0.5468682 ]]\n\n [[ 0.5906759 ]\n [-0.5504363 ]\n [ 1.2580767 ]\n [ 0.1585426 ]\n [ 0.9790328 ]\n [-2.1595135 ]]\n\n [[ 0.07055242]\n [ 1.5605361 ]\n [ 0.5654725 ]\n [ 2.5193207 ]\n [-0.50693923]\n [ 0.54567 ]]\n\n [[-1.0108787 ]\n [ 0.13563155]\n [ 0.3249962 ]\n [-0.72134334]\n [ 0.44444424]\n [-0.45222285]]]]\nY_scale:\n [[[[2.0000484]\n [2.0000129]\n [2.0006797]\n [2.000032 ]\n [2.0000134]\n [2.0004265]]\n\n [[2.0000784]\n [2.0000908]\n [2.000004 ]\n [2.0003521]\n [2.000055 ]\n [2.0000188]]\n\n [[2.0000012]\n [2.00036 ]\n [2.0000033]\n [2.0000021]\n [2.0000517]\n [2.0000544]]\n\n [[2.0000634]\n [2.000055 ]\n [2.0002878]\n [2.0000045]\n [2.0001743]\n [2.0008483]]\n\n [[2.000001 ]\n [2.000443 ]\n [2.0000582]\n [2.0011547]\n [2.0000467]\n [2.0000541]]\n\n [[2.0001857]\n [2.0000033]\n [2.0000193]\n [2.0000947]\n [2.000036 ]\n [2.0000372]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor (ReLU output).","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"},{"description":"*(type: Tensor``)* Output scale.","name":"Y_scale"}],"support_level":"default"}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"Probability of an element to be zeroed.","name":"ratio","option":"optional","type":"float32"},{"default":0,"description":"If zero (train mode), perform dropout. If non-zero(test mode), Y = X.","name":"is_test","type":"int64"}],"category":"Dropout","description":"\n\n`Dropout` takes one input data tensor (`X`) and produces two tensor outputs, `Y` and\n`mask`. If the `is_test` argument is zero (default=0), the output `Y` will be the input\nwith random elements zeroed. The probability that a given element is zeroed is\ndetermined by the `ratio` argument.\n\nIf the `is_test` argument is set to non-zero, the output `Y` is exactly the same as the\ninput `X`. Note that outputs are scaled by a factor of $\\frac{1}{1-ratio}$ during\ntraining, so that during test time, we can simply compute an identity function. This\nscaling is important because we want the output at test time to equal the expected value\nat training time. Dropout has been proven to be an effective regularization technique to\nprevent overfitting during training.\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dropout_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dropout_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Dropout\",\n [\"X\"],\n [\"Y\"] + [\"mask\"],\n ratio=0.5,\n is_test=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(5, 5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\n```\n\n**Result**\n\n```\nX: [[5. 4. 3. 6. 9.]\n [2. 1. 8. 0. 9.]\n [7. 3. 0. 6. 3.]\n [1. 8. 2. 6. 4.]\n [6. 2. 6. 4. 0.]]\nY: [[ 0. 0. 0. 12. 18.]\n [ 0. 0. 16. 0. 0.]\n [ 0. 0. 0. 12. 6.]\n [ 0. 0. 4. 0. 0.]\n [12. 0. 0. 0. 0.]]\nmask: [[False False False True True]\n [False False True True False]\n [False False True True True]\n [False False True False False]\n [ True False False False False]]\n```\n\n
\n\n","inputs":[{"description":"The input data as Tensor.","name":"data"},{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"The output.","name":"output"},{"description":"*(type: Tensor``)* The output mask containing boolean values foreach element, signifying which elements are dropped out. If `is_test` isnonzero, this output is not filled.","name":"mask"},{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"Concat","schema":{"attributes":[{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"},{"description":"Order of blob dimensions. Concats on the C dimension.","name":"order","option":"optional","type":"string"},{"description":"Pass non-zero integer to add the axis specified in `axis` to all input tensors.","name":"add_axis","option":"optional","type":"int64"}],"category":"Tensor","description":"\nConcatenate a list of tensors into a single tensor. Similar functionality to\nNumpy's [concatenate](https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html)\nfunction. The `axis` argument specifies what axis along which the arrays will be concatenated.\nWhen set to non-zero (default=0), the `add_axis` argument adds the axis specified in `axis` to\nall input tensors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Concat\",\n [\"X1\", \"X2\"],\n [\"Y\", \"split_info\"],\n axis=0\n)\n\nworkspace.FeedBlob(\"X1\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"X2\", np.array([[5,6]]))\nprint(\"X1:\", workspace.FetchBlob(\"X1\"))\nprint(\"X2:\", workspace.FetchBlob(\"X2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"split_info:\", workspace.FetchBlob(\"split_info\"))\n\n```\n\n**Result**\n\n```\n\nX1: [[1 2]\n [3 4]]\nX2: [[5 6]]\nY: [[1 2]\n [3 4]\n [5 6]]\nsplit_info: [2 1]\n\n```\n\n
\n\n
\n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Concat\",\n [\"X1\", \"X2\"],\n [\"Y\", \"split_info\"],\n add_axis=1,\n axis=3\n)\n\nworkspace.FeedBlob(\"X1\", np.random.randint(10, size=(1, 1, 5, 5))) // NCHW\nworkspace.FeedBlob(\"X2\", np.random.randint(10, size=(1, 1, 5, 5))) // NCHW\nprint(\"X1:\", workspace.FetchBlob(\"X1\"))\nprint(\"X2:\", workspace.FetchBlob(\"X2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"split_info:\", workspace.FetchBlob(\"split_info\"))\n\n```\n\n**Result**\n\n```\n\nX1: [[[[1 8 3 9 0]\n [6 4 6 5 6]\n [3 9 1 9 9]\n [5 1 0 7 7]\n [9 4 0 0 9]]]]\nX2: [[[[7 0 2 6 1]\n [3 9 4 0 3]\n [5 3 8 9 4]\n [3 4 2 1 0]\n [0 8 8 8 1]]]]\nY: [[[[[1 8 3 9 0]\n [7 0 2 6 1]]\n\n [[6 4 6 5 6]\n [3 9 4 0 3]]\n\n [[3 9 1 9 9]\n [5 3 8 9 4]]\n\n [[5 1 0 7 7]\n [3 4 2 1 0]]\n\n [[9 4 0 0 9]\n [0 8 8 8 1]]]]]\nsplit_info: [1 1]\n\n```\n\n
\n\n ","inputs":[{"name":"inputs","option":"variadic"},{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"*(type: Tensor``)* Concatenated tensor.","name":"concat_result"},{"description":"*(type: Tensor``)* The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"GenerateProposals","schema":{"attributes":[{"description":"(float) spatial scale","name":"spatial_scale","option":"optional"},{"description":"(int) RPN_PRE_NMS_TOP_N","name":"pre_nms_topN","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"post_nms_topN","option":"optional"},{"description":"(float) RPN_NMS_THRESH","name":"nms_thresh","option":"optional"},{"description":"(float) RPN_MIN_SIZE","name":"min_size","option":"optional"},{"description":"bool (default false), Correct bounding box transform coordates, see bbox_transform() in boxes.py Set to true to match the detectron code, set to false for backward compatibility","name":"correct_transform_coords","option":"optional"},{"description":"bool (default true). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_on","option":"optional"},{"description":"int (default -90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_lo","option":"optional"},{"description":"int (default 90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_hi","option":"optional"},{"description":"float (default 1.0 degrees). For RRPN, clip almost horizontal boxes within this threshold of tolerance for backward compatibility. Set to negative value for no clipping.","name":"clip_angle_thresh","option":"optional"}],"description":"\nGenerate bounding box proposals for Faster RCNN. The propoasls are generated for\na list of images based on image score 'score', bounding box regression result\n'deltas' as well as predefined bounding box shapes 'anchors'. Greedy\nnon-maximum suppression is applied to generate the final bounding boxes.\n","inputs":[{"description":"Scores from conv layer, size (img_count, A, H, W)","name":"scores"},{"description":"Bounding box deltas from conv layer, size (img_count, 4 * A, H, W)","name":"bbox_deltas"},{"description":"Image info, size (img_count, 3), format (height, width, scale)","name":"im_info"},{"description":"Bounding box anchors, size (A, 4)","name":"anchors"}],"outputs":[{"description":"Proposals, size (n x 5), format (image_index, x1, y1, x2, y2)","name":"rois"},{"description":"scores of proposals, size (n)","name":"rois_probs"}],"support_level":"default"}},{"name":"RoIAlign","schema":{"attributes":[{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nRegion of Interest (RoI) align operation as used in Mask R-CNN.\n","inputs":[{"description":"4D feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 4 or 5) specifying R RoIs representing: batch index in [0, N - 1], x1, y1, x2, y2. The RoI coordinates are in the coordinate system of the input image. For inputs corresponding to a single image, batch index can be excluded to have just 4 columns.","name":"RoIs"}],"outputs":[{"description":"4D output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"BBoxTransform","schema":{"attributes":[{"description":"vector weights [wx, wy, ww, wh] for the deltas","name":"weights","option":"optional"},{"description":"bool (default true), transform the boxes to the scaled image space after applying the bbox deltas.Set to false to match the detectron code, set to true for keypoint models and for backward compatibility","name":"apply_scale","option":"optional"},{"description":"bool (default false), Correct bounding box transform coordates, see bbox_transform() in boxes.py Set to true to match the detectron code, set to false for backward compatibility","name":"correct_transform_coords","option":"optional"},{"description":"bool (default false). If true, then boxes (rois and deltas) include angle info to handle rotation. The format will be [ctr_x, ctr_y, width, height, angle (in degrees)].","name":"rotated","option":"optional"},{"description":"bool (default true). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_on","option":"optional"},{"description":"int (default -90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_lo","option":"optional"},{"description":"int (default 90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_hi","option":"optional"},{"description":"float (default 1.0 degrees). For RRPN, clip almost horizontal boxes within this threshold of tolerance for backward compatibility. Set to negative value for no clipping.","name":"clip_angle_thresh","option":"optional"}],"description":"\nTransform proposal bounding boxes to target bounding box using bounding box\n regression deltas.\n","inputs":[{"description":"Bounding box proposals in pixel coordinates, Size (M, 4), format [x1, y1, x2, y2], orSize (M, 5), format [batch_index, x1, y1, x2, y2]. If proposals from multiple images in a batch are present, they should be grouped sequentially and in incremental order.For rotated boxes, this would have an additional angle (in degrees) in the format [, ctr_x, ctr_y, w, h, angle].","name":"rois"},{"description":"bounding box translations and scales,size (M, 4*K), format [dx, dy, dw, dh], K = # classes. For rotated boxes, size (M, 5*K, format [dx, dy, dw, dh, da].","name":"deltas"},{"description":"Image dimensions, size (batch_size, 3), format [img_height, img_width, img_scale]","name":"im_info"}],"outputs":[{"description":"Pixel coordinates of the transformed bounding boxes,Size (M, 4*K), format [x1, y1, x2, y2]. For rotated boxes, size (M, 5*K), format [ctr_x, ctr_y, w, h, angle].","name":"box_out"},{"description":"Tensor of shape (batch_size) with each element denoting the number of RoIs belonging to the corresponding image in batch","name":"roi_batch_splits"}],"support_level":"default"}},{"name":"BoxWithNMSLimit","schema":{"attributes":[{"description":"(float) TEST.SCORE_THRESH","name":"score_thresh","option":"optional"},{"description":"(float) TEST.NMS","name":"nms","option":"optional"},{"description":"(int) TEST.DEECTIONS_PER_IM","name":"detections_per_im","option":"optional"},{"description":"(bool) TEST.SOFT_NMS.ENABLED","name":"soft_nms_enabled","option":"optional"},{"description":"(string) TEST.SOFT_NMS.METHOD","name":"soft_nms_method","option":"optional"},{"description":"(float) TEST.SOFT_NMS.SIGMA","name":"soft_nms_sigma","option":"optional"},{"description":"(float) Lower bound on updated scores to discard boxes","name":"soft_nms_min_score_thres","option":"optional"},{"description":"bool (default false). If true, then boxes (rois and deltas) include angle info to handle rotation. The format will be [ctr_x, ctr_y, width, height, angle (in degrees)].","name":"rotated","option":"optional"}],"description":"\nApply NMS to each class (except background) and limit the number of\nreturned boxes.\n","inputs":[{"description":"Scores, size (count, num_classes)","name":"scores"},{"description":"Bounding box for each class, size (count, num_classes * 4). For rotated boxes, this would have an additional angle (in degrees) in the format [, ctr_x, ctr_y, w, h, angle]. Size: (count, num_classes * 5).","name":"boxes"},{"description":"Tensor of shape (batch_size) with each element denoting the number of RoIs/boxes belonging to the corresponding image in batch. Sum should add up to total count of scores/boxes.","name":"batch_splits"}],"outputs":[{"description":"Filtered scores, size (n)","name":"scores"},{"description":"Filtered boxes, size (n, 4). For rotated boxes, size (n, 5), format [ctr_x, ctr_y, w, h, angle].","name":"boxes"},{"description":"Class id for each filtered score/box, size (n)","name":"classes"},{"description":"Output batch splits for scores/boxes after applying NMS","name":"batch_splits"},{"description":"Optional filtered indices, size (n)","name":"keeps"},{"description":"Optional number of filtered indices per class, size (num_classes)","name":"keeps_size"}],"support_level":"default"}},{"name":"ONNXWhile","schema":{"attributes":[{"description":"Net executed on each iteration","name":"body","option":"optional"},{"description":"Whether to use the trip count input","name":"has_trip_count","option":"optional"},{"description":"Whether to use the condition input","name":"has_cond","option":"optional"},{"description":"Whether to save the scopes across iterations, as in for backprop","name":"save_scopes","option":"optional"},{"description":"Do not create new scopes. Use this only if you're certain there will be no name collision, for example if you're converting from a fully-SSA IR","name":"disable_scopes","option":"optional"}],"description":"\n*** EXPERIMENTAL. This operator is a work-in-progress. No assumption should be\nmade about the stability or correctness of this op. ***\n\nGeneric Looping construct confirming to the ONNX Loop operator spec. This loop\nhas multiple termination conditions:\n\n1. Trip count. Iteration count specified at runtime. Set by specifying the\n input M. Optional. Set to empty string to omit. Note that a static trip\n count (specified at graph construction time) can be specified by passing\n in a constant node for input M.\n2. Loop termination condition. This is an input to the op that determines\n whether to run the first interation and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition\n variable, whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\nOperator inputs defined as (max_trip_count, condition_var). Omitted optional\ninputs are represented as empty string. Concretely, in this caffe2 op an input\nis marked as omitted by setting its 'has_{name}' argument to False.\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n ","inputs":[{"description":"Number of iterations to go out to. Used if the flag has_trip_count is True.","name":"max_trip_count"},{"name":"condition"},{"name":"initial","option":"variadic"},{"description":"Dynamic condition value for the first iteration. For all subsequent iterations, the condition from the body graph is used. This input is used if the flag has_cond is true.","name":"first_iter_condition"}],"outputs":[{"name":"final_and_scan_outputs","option":"variadic"}],"support_level":"default"}},{"name":"Int8Quantize","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"inputs":[{"description":"FP32 Tensor X.","name":"X"},{"description":"Optional scale quantization param computed on activation histogram dataWill overwrite Y_scale argument if specified","name":"Scale qparam"},{"description":"Optionsl zero-point quantization param computed on activation dataWill overwrite Y_zero_point argument if specified","name":"Zero-point qparam"},{"description":"Optional Qparam blob that constans quant param computed on activation histogram dataWill overwrite Y_scale and Y_zero_point argument if specified","name":"Qparam"}],"outputs":[{"description":"Int8 Tensor qX representing X with linear quantization.","name":"Y"}],"support_level":"default"}},{"name":"Int8Conv","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"default":0,"name":"pad"},{"default":1,"name":"stride"}],"category":"Layer","description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \n[Only NHWC order is supported now]Note that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is convolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_op_impl.h is the templated implementation of the conv_op.h file, which is\nwhy they are separate files.\n","inputs":[{"description":"Input data blob from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the NCHW usage. On the other hand, the NHWC Op has a different set of dimension constraints. ","name":"X"},{"description":"The filter blob that will be used in the convolutions; has size (M x C x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution; has size (M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"Int8FC","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Layer","description":"\nComputes the result of passing an input vector X into a fully\nconnected layer with 2D weight matrix W and 1D bias vector b. That is,\nthe layer computes Y = X * W^T + b, where X has size (M x K),\nW has size (N x K), b has size (N), and Y has size (M x N),\nwhere M is often the batch size.\n\n\nNOTE: X does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\nX \\in [a_0, a_1 * ... * a_{n-1}]. Only this case is supported!\nLastly, even though b is a 1D vector of size N, it is copied/resized to\nbe size (M x N) implicitly and added to each vector in the batch.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","inputs":[{"description":"input tensor that's coerced into a 2D matrix of size (MxK) as described above","name":"X"},{"description":"A tensor that is coerced into a 2D blob of size (KxN) containing fully connected weight matrix","name":"W"},{"description":"1D blob containing bias vector","name":"b"},{"description":"Optional scale quantization param computed on activation histogram dataWill overwrite Y_scale argument if specified","name":"Scale qparam"},{"description":"Optionsl zero-point quantization param computed on activation dataWill overwrite Y_zero_point argument if specified","name":"Zero-point qparam"},{"description":"Optional Qparam blob that constans quant param computed on activation histogram dataWill overwrite Y_scale and Y_zero_point argument if specified","name":"Qparam"}],"outputs":[{"description":"2D output tensor","name":"Y"}],"support_level":"default"}},{"name":"Int8AveragePool","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Pool","description":"AveragePool \nconsumes an input blob X and applies average pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Average pooling consisting of averaging all values of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from average pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y"}],"support_level":"default"}},{"name":"Int8Sum","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Int8Softmax","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(int) default to 1; describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","option":"optional"}],"category":"Activation","description":"\nThe operator computes the softmax normalized values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the softmax normalized values of the corresponding input.\n\nX does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\nX \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then X will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the X tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"}],"outputs":[{"description":"The softmax normalized output values with the same shape as input tensor.","name":"output"}],"support_level":"default"}},{"name":"Int8Relu","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Activation","description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"AffineChannel","schema":{"category":"Normalization","description":"\nApplies a separate affine transformation to each channel of the input. Useful\nfor replacing spatial batch norm with its equivalent fixed transformation.\n","inputs":[{"description":"Feature map input with order NCHW or NHWC.","name":"X"},{"description":"1D input of shape (C); the c-th element is the scale factor of the affine transformation for the c-th channel of the input.","name":"scale"},{"description":"1D input of shape (C); the c-th element is the bias of the affine transformation for the c-th channel of the input.","name":"bias"}],"outputs":[{"description":"Output with the same order of Input.","name":"Y"}],"support_level":"default"}},{"name":"LearningRateAdaption","schema":{"attributes":[{"description":"the learning rate for performing gradient descent on learning rate lr","name":"lr_alpha","option":"optional"},{"description":"whether to apply normalized lr adaption or not","name":"normalized_lr_adaption","option":"optional"}],"description":"\n Learning Rate Adaption is an operation that perform one iteration of\n gradient descent based on learning rate:\n lr(k) = lr(k-1) - lr_alpha * df(k-1)/dlr,\n where df(k-1)/dlr is the gradient of objective function f on lr, and\n lr_alpha is a learning rate hyperparameter. It can be prove that\n df(k-1)/dlr equals INNERPRODUCT(grad(k-1), -grad(k-2)), where grad(k-1) is\n the grad of f(k-1) on parameters. When the argument\n \"normalized_lr_adaption\" is false, we simply perform the\n following update:\n lr(k) = lr(k-1) - lr_alpha * INNERPRODUCT(grad(k-1), grad(k-2)).\n If we set \"normalized_lr_adaption\" to be true, we do not directly apply\n INNERPRODUCT(grad(k-1), -grad(k-2)) as the grad. Instead, we perform the\n following update:\n lr(k) = lr(k-1) + lr_alpha * cosineSimilarity(grad(k-1), grad(k-2)).\n","inputs":[{"description":"Learning rate","name":"lr"},{"description":"Gradient computed","name":"grad"},{"description":"The effective grad","name":"effgrad"}],"outputs":[{"description":"Updated learning rate","name":"output_lr"}],"support_level":"default"}},{"name":"MeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"CoshGradient","schema":{"description":null,"support_level":"default"}},{"name":"IndexSize","schema":{"description":"\nReturns the number of entries currently present in the index.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"Scalar int64 tensor with number of entries.","name":"items"}],"support_level":"default"}},{"name":"LpPool","schema":{"attributes":[{"description":"(*float*): type of $L_p$ norm to use (default=2.0)","name":"p","option":"optional"},{"description":"(*int*): the size of the window to take a max over","name":"kernel","option":"optional"},{"description":"(*int*): the stride of the window","name":"stride","option":"optional"},{"description":"(*int*): implicit zero padding to be added on both sides","name":"pad","option":"optional"},{"description":"(*int*): parameter that controls the stride of elements in the window","name":"dilation","option":"optional"},{"description":"(*string*): order of blob dimensions (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\n`LpPool` consumes an input blob and applies max pooling across the the blob according to kernel sizes, stride sizes, pad lengths and dilation. $L_p$ pooling consists of taking the $L_p$ norm of a subset of the input tensor according to the kernel size and downsampling the data into the output blob for further processing.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the output blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lp_pool_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LpPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n p=2.0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[[-1.1113514 -1.1173418 -0.1504435 0.1327146 -1.2221841 -0.5654315 ]\n [-1.9209646 -0.04675794 0.8604731 1.2042469 0.28154245 0.38656202]\n [-0.8772837 -0.03264008 0.26222762 0.28526652 0.321102 -2.5891325 ]\n [-0.9248281 1.440776 -0.56832 -0.6017927 1.2262512 -2.1443934 ]\n [ 0.5194415 -1.6858683 0.45221648 0.65029615 -0.8574544 0.8121054 ]\n [ 0.25902653 0.4934758 0.49870652 -0.48134378 -0.9178449 -0.07626943]]]]\n\nY:\n [[[[2.4851248 1.49361 1.4290358]\n [1.9240153 0.9139378 3.5928857]\n [1.8500228 1.0525136 1.4976646]]]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 8-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Transpose","schema":{"attributes":[{"description":"Order to permute axes of input tensor. Reverses the dimensions by default.","name":"axes","option":"optional"}],"description":"\nTranspose the input tensor by permuting the axes of the input according\nto the `axes` argument. Similar to numpy's\n[transpose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)\nfunction.\n\nFor example, when axes=(1, 0, 2), given an input tensor of shape\n(1, 2, 3), the output shape will be (2, 1, 3).\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/transpose_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Transpose\",\n [\"X\"],\n [\"Y\"],\n axes=(0,3,1,2)\n)\n\nx = np.random.rand(1,32,32,3)\nworkspace.FeedBlob(\"X\", x)\nprint(\"X.shape (NHWC order):\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape (NCHW order):\", workspace.FetchBlob(\"Y\").shape)\n```\n\n**Result**\n\n```\nX.shape (NHWC order): (1, 32, 32, 3)\nY.shape (NCHW order): (1, 3, 32, 32)\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Transposed output.","name":"Y"}],"support_level":"default"}},{"name":"Accuracy","schema":{"attributes":[{"description":"Count as correct by comparing the true label to the top k scoring classes (default 1: only compare to the top scoring class i.e. argmax)","name":"top_k","option":"optional"}],"description":"\nAccuracy takes two inputs- predictions and labels, and returns a float\naccuracy value for the batch. Predictions are expected in the form of 2-D tensor\ncontaining a batch of scores for various classes, and labels are expected in the\n form of 1-D tensor containing true label indices of samples in the batch. If\nthe score for the label index in the predictions is the highest among all\nclasses, it is considered a correct prediction.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing scores","name":"predictions"},{"description":"1-D tensor (Tensor) of size (num_batches) having the indices of true labels","name":"labels"}],"outputs":[{"description":"1-D tensor (Tensor) of size 1 containing accuracy","name":"accuracy"}],"support_level":"default"}},{"name":"TimerEnd","schema":{"description":"\nStop a timer started with **TimerBegin**. Publishes a CAFFE_EVENT.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"support_level":"default"}},{"name":"LengthsRangeFill","schema":{"description":"\nThe *LengthsRangeFill* op takes a single input *lengths* and outputs a single tensor *range_sequence*. For each element of *lengths*, the op appends the range(0,lengths) vector to the end of *range_sequence*. For example, if input=[2,4,1], the output would be [0,1,0,1,2,3,0].\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsRangeFill\",\n [\"lengths\"],\n [\"range_sequence\"],\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([2,4,1]).astype(np.int32))\nprint(\"lengths:\\n\", workspace.FetchBlob(\"lengths\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"range_sequence: \\n\", workspace.FetchBlob(\"range_sequence\"))\n\n```\n\n**Result**\n\n```\n\nlengths:\n [2 4 1]\nrange_sequence:\n [0 1 0 1 2 3 0]\n\n```\n\n
\n\n","inputs":[{"description":"1D tensor of int32 or int64 segment lengths.","name":"lengths"}],"outputs":[{"description":"1D tensor whose size is the sum of *lengths*","name":"range_sequence"}],"support_level":"default"}},{"name":"AccumulateHistogram","schema":{"attributes":[{"description":"the lower bound value","name":"lower_bound","option":"optional"},{"description":"the upper bound value","name":"upper_bound","option":"optional"},{"description":"number of buckets to use in [lower_bound, upper_bound)","name":"num_buckets","option":"optional"}],"description":"\nThis operator calculate thes histogram of values in input tensor.\nThere're 2 outputs, one for histogram of current input tensor, and another\nfor histogram of the all input tensors accumulated through history.\nThe output would contain num_buckets + 2 values. index[1 ... num_buckets]\nfor values in [lower_bound, upper_bound) interval. And the rest 2 for values\nsmaller than lower_bound or greater than upper_bound respectively.\n","inputs":[{"description":"Input tensor.","name":"X"}],"outputs":[{"description":"Output histogram of the current tensor.","name":"CurHist"},{"description":"Accumulated histogram of the history tensor.","name":"AccHist"}],"support_level":"default"}},{"name":"Int8ConvRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \n[Only NHWC order is supported now]Note that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is convolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_op_impl.h is the templated implementation of the conv_op.h file, which is\nwhy they are separate files.\n","inputs":[{"description":"Input data blob from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the NCHW usage. On the other hand, the NHWC Op has a different set of dimension constraints. ","name":"X"},{"description":"The filter blob that will be used in the convolutions; has size (M x C x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution; has size (M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths. Output will go through rectified linear function, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsSum8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsSum operator, where DATA is\nstored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentMean).\n\nThis op is basically Gather and UnsortedSegmentMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"Load","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"default":"","description":"Blobs will be prefixed with this when loading. Useful for avoiding collisions with blobs existing in the workspace. The output blob names specified to this op should include this prefix.","name":"add_prefix","option":"optional","type":"string"},{"default":"","description":"Characters in the provided blob names that match `strip_prefix` will be removed prior to saving. Also, characters that precede `strip_prefix` will be removed. Useful for removing device scope from blob names.","name":"strip_prefix","option":"optional","type":"string"},{"description":"The output path of the db. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db","option":"optional","type":"string"},{"description":"List of paths to dbs to load blobs from. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"dbs","option":"optional","type":"string[]"},{"description":"(type: string)* Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional"},{"default":0,"description":"If nonzero, the blobs are loaded into the device that is specified in the serialized `BlobProto`. Otherwise, the device will be set as the one that the `Load` operator is being run under.","name":"keep_device","option":"optional","type":"int64"},{"default":0,"description":"If nonzero, will load all blobs pointed to by the db to the workspace overwriting/creating blobs as needed.","name":"load_all","option":"optional","type":"int64"},{"default":false,"description":"If True, will allow not loading all the output blobs specified in the outputs.","name":"allow_incomplete","option":"optional","type":"boolean"},{"description":"If set, used instead of output blob names to specify which blobs in the db shall be loaded. Must be the same length as number of output blobs.","name":"source_blob_names","option":"optional","type":"string[]"}],"description":"\nThe Load operator loads a set of serialized blobs from a db or multiple dbs. It\ntakes $[0, \\infty)$ number of inputs and $[0, \\infty)$ number of outputs, using\nthe db keys to match the db entries with the outputs.\n\nIf at least one input is passed, then it is assumed that that input blobs are a\nset of DBReaders to load from. Otherwise the `db` or `dbs` argument is used to load\nblobs from one single db or multiple dbs respectively. `db_type` argument is used\nto specify the type of the input db/dbs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Load\",\n [],\n [\"X\", \"Y\"],\n db=\"test_db\",\n db_type=\"lmdb\"\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n
\n\n","inputs":[{"description":"*(type: List(DBReader))* [OPTIONAL] List of DBReaders to load from. Can use this instead of the `db`/`dbs` args.","name":"X, Y, ..."}],"support_level":"default"}},{"name":"Exp","schema":{"description":"\nCalculates the exponential of the given input tensor ($exp(x)$), element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/exp_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Exp\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[0.5821691 0.07719802 0.50159824]\n [0.40952456 0.36788362 0.84887683]\n [0.02472685 0.65730894 0.9066397 ]]\nX after running op:\n[[1.7899168 1.080256 1.6513585]\n [1.5061016 1.4446739 2.3370204]\n [1.0250351 1.9295927 2.4759884]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* The exponential of the input tensor computed element-wise.","name":"Y"}],"support_level":"default"}},{"name":"ConvTransposeGradient","schema":{"description":null,"support_level":"default"}},{"name":"LayerNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"SinhGradient","schema":{"description":null,"support_level":"default"}},{"name":"FlattenToVec","schema":{"description":"\n\nThe *FlattenToVec* op flattens the input tensor into a 1-D vector. The op accepts a single input tensor and returns a single output tensor.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FlattenToVec\",\n [\"input\"],\n [\"output\"],\n)\n\nworkspace.FeedBlob(\"input\", np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output: \\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [[ 1. 2. 3.]\n [ 4. 5. 6.]\n [ 7. 8. 9.]\n [10. 11. 12.]]\noutput:\n [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.]\n\n```\n\n
\n\n","inputs":[{"description":"A tensor of rank >= 1.","name":"input"}],"outputs":[{"description":"A tensor of rank 1 (vector) with the contents of the input tensor.","name":"output"}],"support_level":"default"}},{"name":"Ftrl","schema":{"description":null,"support_level":"default"}},{"name":"UnsortedSegmentMean","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"}],"description":"\nApplies 'Mean' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentMean).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sinh","schema":{"description":"\nCalculates the hyperbolic sine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sinh_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sinh\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.98907769 0.52907848 0.03216429 0.94983935 0.47881418]\nY: [1.15841695 0.5541099 0.03216984 1.09924557 0.49732079]\n\n```\n\n
\n\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic sine values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"CloseRebatchingQueue","schema":{"description":"\nCloses the Queue.\n","inputs":[{"description":"object representing the queue","name":"queue"}],"support_level":"default"}},{"name":"LpPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"StumpFunc","schema":{"description":"\nConverts each input element into either high_ or low_value\nbased on the given threshold.\n","inputs":[{"description":"tensor of float","name":"X"}],"outputs":[{"description":"tensor of float","name":"Y"}],"support_level":"default"}},{"name":"BooleanMask","schema":{"description":"\nGiven a 1D `data` tensor and a boolean `mask` tensor of the same shape, returns a `masked_data` tensor containing only the elements corresponding to positions where the `mask` is True, and a `masked_indices` tensor containing the indices of the True elements.\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_mask_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanMask\",\n [\"data\", \"mask\"],\n [\"masked_data\", \"masked_indices\"]\n)\n\nworkspace.FeedBlob(\"data\", np.array([1,2,3,4,5,6]))\nworkspace.FeedBlob(\"mask\", np.array([True,False,False,True,True,False]))\nprint(\"data:\", workspace.FetchBlob(\"data\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\nworkspace.RunOperatorOnce(op)\nprint(\"masked_data:\", workspace.FetchBlob(\"masked_data\"))\nprint(\"masked_indices:\", workspace.FetchBlob(\"masked_indices\"))\n\n```\n\n**Result**\n\n```\n\ndata: [1 2 3 4 5 6]\nmask: [ True False False True True False]\nmasked_data: [1 4 5]\nmasked_indices: [0 3 4]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): 1D input tensor","name":"data"},{"description":"(*Tensor``*): tensor of bools which determines the input elements that will be left in the `masked_data` output tensor; same shape as `data`","name":"mask"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as `data` input that contains the masked input tensor","name":"masked_data"},{"description":"(*Tensor``*): 1D tensor of indices of the True elements in the `mask` tensor","name":"masked_indices"}],"support_level":"default"}},{"name":"ReduceFrontMean","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **mean**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the mean operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [mean(1,4), mean(5,1,7), mean(2), mean(9,2)] = [2.5, 4.333, 2, 5.5]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_mean_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontMean\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[5. 0. 9.]\n [4. 1. 1.]\n [9. 0. 8.]]\n\n [[2. 6. 7.]\n [6. 2. 6.]\n [0. 4. 5.]]]\nY: [4.3333335 2.1666667 6.]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"SigmoidCrossEntropyWithLogits","schema":{"attributes":[{"description":"default is false; if enabled, will use the log d trick to avoid the vanishing\ngradients early on; see Goodfellow et. al (2014)","name":"log_D_trick","option":"optional"},{"description":"default is false; if enabled, the model will be allowed to train on an unjoined\ndataset, where some examples might be false negative and might appear\nin the dataset later as (true) positive example.","name":"unjoined_lr_loss","option":"optional"}],"description":"\nGiven two matrices logits and targets, of same shape,\n(batch_size, num_classes), computes the sigmoid cross entropy between the two.\nReturns a tensor of shape (batch_size,) of losses for each example.\n","inputs":[{"description":"matrix of logits for each example and class.","name":"logits"},{"description":"matrix of targets, same shape as logits.","name":"targets"}],"outputs":[{"description":"Vector with the total xentropy for each example.","name":"xentropy"}],"support_level":"default"}},{"name":"CosineEmbeddingCriterionGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResizeLike","schema":{"description":"\nProduces tensor containing data of first input and shape of second input.\n","inputs":[{"description":"Tensor whose data will be copied into the output.","name":"data"},{"description":"Tensor whose shape will be applied to output.","name":"shape_tensor"}],"outputs":[{"description":"Tensor with data of input 0 and shape of input 1.","name":"output"}],"support_level":"default"}},{"name":"HSoftmaxSearch","schema":{"attributes":[{"description":"Serialized TreeProto string containing a tree including all intermidate nodes and leafs. All nodes must have names for correct outputs","name":"tree","option":"optional"},{"description":"beam used for pruning tree. The pruning algorithm is that only children, whose score is smaller than parent's score puls beam, will be propagated.","name":"beam","option":"optional"},{"description":"Number of nodes in outputs","name":"topN","option":"optional"}],"description":"\nHSoftmaxSearch is an operator to generate the most possible paths given a\nwell-trained model and input vector. Greedy algorithm is used for pruning the\nsearch tree.\n","inputs":[{"description":"Input data from previous layer","name":"X"},{"description":"The matrix trained from Softmax Ops","name":"W"},{"description":"The bias trained from Softmax Ops","name":"b"}],"outputs":[{"description":"The name of selected nodes and leafs. For nodes, it will be the name defined in the tree. For leafs, it will be the index of the word in the tree.","name":"Y_names"},{"description":"The corresponding scores of Y_names","name":"Y_scores"}],"support_level":"default"}},{"name":"HSoftmaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"CloneCommonWorld","schema":{"description":"\nClones existing common world.\n","inputs":[{"description":"Existing common world to clone.","name":"existing_comm_world"}],"outputs":[{"description":"A common world for collective operations.","name":"comm_world"}],"support_level":"default"}},{"name":"SortedSegmentRangeMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"LCGradient","schema":{"description":null,"support_level":"default"}},{"name":"SubGradient","schema":{"description":null,"support_level":"default"}},{"name":"PackedInt8BGRANHWCToNCHWCStylizerPreprocess","schema":{"description":null,"support_level":"default"}},{"name":"ConcatBatchMatMulBatchGatherOp","schema":{"description":null,"support_level":"default"}},{"name":"Gather","schema":{"description":"\n\nThe *Gather* op accepts a *DATA* tensor of rank $r >= 1$ and *INDICES* tensor of rank $q$ as inputs. It then gathers entries of the outer-most dimension of *DATA*, indexed by *INDICES*, and concatenate them in an output tensor of rank $q + (r - 1)$.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/gather_op.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/gather_op.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Gather\",\n [\"DATA\", \"INDICES\"],\n [\"OUTPUT\"]\n)\ndata = np.array([[1., 1.2],[2.3, 3.4],[4.5, 5.7]])\nprint(\"DATA:\\n\",data)\n\ninds = np.array([[0, 1],[1, 2]])\nprint(\"INDICES:\\n\",inds)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"DATA\", data.astype(np.float32))\nworkspace.FeedBlob(\"INDICES\", inds.astype(np.int32))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT:\\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [[1. 1.2]\n [2.3 3.4]\n [4.5 5.7]]\nINDICES:\n [[0 1]\n [1 2]]\nOUTPUT:\n [[[1. 1.2]\n [2.3 3.4]]\n\n [[2.3 3.4]\n [4.5 5.7]]]\n\n```\n\n
\n\n","inputs":[{"description":"Input data tensor of rank $r>=1$","name":"DATA"},{"description":"Input indices tensor of rank $q$. This tensor must contain integers.","name":"INDICES"}],"outputs":[{"description":"Output tensor of rank $q+(r-1)$","name":"OUTPUT"}],"support_level":"default"}},{"name":"KeyValueToMap","schema":{"description":"Convert key and value blob pairs into a map blob","inputs":[{"description":"Blob reference to the key","name":"key blob"},{"description":"Blob reference to the value","name":"value blob"}],"outputs":[{"description":"Blob reference to the map","name":"map blob"}],"support_level":"default"}},{"name":"Unique","schema":{"description":"\nDeduplicates input indices vector and optionally produces reverse remapping.\nThere's no guarantees on the ordering of the output indices.\n","inputs":[{"description":"1D tensor of int32 or int64 indices.","name":"indices"}],"outputs":[{"description":"1D tensor of deduped entries.","name":"unique_indices"},{"description":"(optional) mapping from `indices` to `unique_indices`. This has the same shape as `indices`. Its elements are the indices into `unique_indices` such that `Gather(['unique_indices', 'remapping'])` yields `indices`.","name":"remapping"}],"support_level":"default"}},{"name":"ResizeNearestGradient","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"AveragePut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an average.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"SoftmaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"BatchBucketize","schema":{"description":"\nBucketize the float_features into sparse features.\nThe float_features is a N * D tensor where N is the batch_size, and D is the feature_dim.\nThe indices is a 1D tensor containing the indices of the features that need to be bucketized.\nThe lengths is a 1D tensor that splits the following 'boundaries' argument.\nThe boundaries is a 1D tensor containing the border list for each feature.\n\nWith in each batch, `indices` should not have duplicate number,\nand the number of elements in `indices` should be less than or equal to `D`.\nEach element in `lengths` vector (lengths[`i`]) represents\nthe number of boundaries in the sub border list.\nThe sum of all elements in `lengths` must be equal to the size of `boundaries`.\nIf lengths[0] = 2, the first sub border list is [0.5, 1.0], which separate the\nvalue to (-inf, 0.5], (0,5, 1.0], (1.0, inf). The bucketized feature will have\nthree possible values (i.e. 0, 1, 2).\n\n\nFor example, with input:\n\n float_features = [[1.42, 2.07, 3.19, 0.55, 4.32],\n [4.57, 2.30, 0.84, 4.48, 3.09],\n [0.89, 0.26, 2.41, 0.47, 1.05],\n [0.03, 2.97, 2.43, 4.36, 3.11],\n [2.74, 5.77, 0.90, 2.63, 0.38]]\n indices = [0, 1, 4]\n lengths = [2, 3, 1]\n boundaries = [0.5, 1.0, 1.5, 2.5, 3.5, 2.5]\n\nThe output is:\n\n output =[[2, 1, 1],\n [2, 1, 1],\n [1, 0, 0],\n [0, 2, 1],\n [2, 3, 0]]\n\nafter running this operator.\n","inputs":[{"description":"2-D dense tensor, the second dimension must be greater or equal to the indices dimension","name":"float_features"},{"description":"Flatten tensor, containing the indices of `float_features` to be bucketized. The datatype must be int32.","name":"indices"},{"description":"Flatten tensor, the size must be equal to that of `indices`. The datatype must be int32.","name":"lengths"},{"description":"Flatten tensor, dimension has to match the sum of lengths","name":"boundaries"}],"outputs":[{"description":"2-D dense tensor, with 1st dim = float_features.dim(0), 2nd dim = size(indices)in the arg list, the tensor is of the same data type as `feature`.","name":"bucktized_feat"}],"support_level":"default"}},{"name":"CreateTensorVector","schema":{"description":"Create a std::unique_ptr >","support_level":"default"}},{"name":"UnsortedSegmentSum","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"}],"description":"\nApplies 'Sum' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentSum).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"CreateTreeCursor","schema":{"attributes":[{"description":"A list of strings each one representing a field of the dataset.","name":"fields","option":"optional"}],"description":"\nCreates a cursor to iterate through a list of tensors, where some of those\ntensors contain the lengths in a nested schema. The schema is determined by\nthe `fields` arguments.\n\nFor example, to represent the following schema:\n\n Struct(\n a=Int(),\n b=List(List(Int)),\n c=List(\n Struct(\n c1=String,\n c2=List(Int),\n ),\n ),\n )\n\nthe field list will be:\n [\n \"a\",\n \"b:lengths\",\n \"b:values:lengths\",\n \"b:values:values\",\n \"c:lengths\",\n \"c:c1\",\n \"c:c2:lengths\",\n \"c:c2:values\",\n ]\n\nAnd for the following instance of the struct:\n\n Struct(\n a=3,\n b=[[4, 5], [6, 7, 8], [], [9]],\n c=[\n Struct(c1='alex', c2=[10, 11]),\n Struct(c1='bob', c2=[12]),\n ],\n )\n\nThe values of the fields will be:\n {\n \"a\": [3],\n \"b:lengths\": [4],\n \"b:values:lengths\": [2, 3, 0, 1],\n \"b:values:values\": [4, 5, 6, 7, 8, 9],\n \"c:lengths\": [2],\n \"c:c1\": [\"alex\", \"bob\"],\n \"c:c2:lengths\": [2, 1],\n \"c:c2:values\", [10, 11, 12],\n }\n\nIn general, every field name in the format \"{prefix}:lengths\" defines a domain\n\"{prefix}\", and every subsequent field in the format \"{prefix}:{field}\" will\nbe in that domain, and the length of the domain is provided for each entry of\nthe parent domain. In the example, \"b:lengths\" defines a domain of length 4, so\nevery field under domain \"b\" will have 4 entries.\nThe \"lengths\" field for a given domain must appear before any reference to\nthat domain.\n\nReturns a pointer to an instance of the Cursor, which keeps the current offset\non each of the domains defined by `fields`. Cursor also ensures thread-safety\nsuch that ReadNextBatch and ResetCursor can be used safely in parallel.\n\nA cursor does not contain data per se, so calls to ReadNextBatch actually need\nto pass a list of blobs containing the data to read for each one of the fields.\n","outputs":[{"description":"A blob pointing to an instance of a new TreeCursor.","name":"cursor"}],"support_level":"default"}},{"name":"UnsortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"HasElements","schema":{"description":"\nThe *HasElements* op accepts a single or multiple input tensors, and produces a single boolean output $has\\_elements$. The output is *True* if and only if any of the input tensor has size > 0. Note, this op is the opposite of the *IsEmpty* op.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"HasElements\",\n [\"tensor\"],\n [\"has_elements\"],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"tensor\", np.random.randn(2, 2).astype(np.float32))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"has_elements: \", workspace.FetchBlob(\"has_elements\"),\"\\n\")\n\n// Use an empty tensor\nworkspace.FeedBlob(\"tensor\", np.empty(0))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"has_elements: \", workspace.FetchBlob(\"has_elements\"))\n\n```\n\n**Result**\n\n```\n\ntensor:\n [[ 0.6116506 -0.54433197]\n [ 0.19406661 -0.7338629 ]]\nhas_elements: True\n\ntensor:\n []\nhas_elements: False\n\n```\n\n
\n\n","inputs":[{"description":"Input data tensor to check for elements.","name":"tensor"},{"description":"List of input data tensors to check for elements.","name":"X1, X2, ..."}],"outputs":[{"description":"Output scalar boolean tensor. True if input has size > 0.","name":"has_elements"}],"support_level":"default"}},{"name":"Int8ConvTranspose","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nThe transposed convolution consumes an input vector, the filter blob, and\nthe bias blob, and computes the output. Note that other parameters, such as\nthe stride and kernel size, or the pads' sizes in each direction are not\nnecessary for input because they are provided by the\nConvTransposeUnpoolOpBase operator. Various dimension checks are done\nimplicitly, and the sizes are specified in the Input docs for this operator.\nAs is expected, the filter is deconvolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_transpose_op_impl.h is the templated implementation of the\nconv_transpose_op.h file, which is why they are separate files.\n ","inputs":[{"description":"Input data blob from previous layer; has size (N x H x W x C), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that NHWC is supported now","name":"X"},{"description":"The filter blob that will be used in the transposed convolution; has size (M x kH x kW x C), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution;has size (C). Optional, if not passed, will treat it as all 0.","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the transposed convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"LastNWindowCollector","schema":{"attributes":[{"description":"The number of random samples to append for each positive samples","name":"num_to_collect","option":"optional"}],"description":"\nCollect the last N rows from input data. The purpose is to keep track of data\naccross batches, so for example suppose the LastNWindowCollector is called\nsuccessively with the following input data\n\n [1, 2, 3, 4]\n [5, 6, 7]\n [8, 9, 10, 11]\n\nAnd the number of items is set to 6, then the output after the 3rd call\nwill contain the following elements:\n\n [6, 7, 8, 9, 10, 11]\n\nNo guarantee is made on the ordering of elements in input. So a valid value for\noutput could have been\n\n [11, 10, 9, 8, 7, 6]\n\nAlso, this method works for any order tensor, treating the first dimension as\ninput rows and keeping the last N rows seen as input. So for instance:\n\n [[1, 2], [2, 3], [3, 4], [4, 5]]\n [[5, 6], [6, 7], [7, 8]]\n [[8, 9], [9, 10], [10, 11], [11, 12]]\n\nA possible output would be\n\n [[6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12]]\n\nThis is not thread safe unless a mutex is given.\n","inputs":[{"description":"The buffer for last-N record. Should be initialized to empty tensor","name":"last-N buffer"},{"description":"The cursor pointing to the next position that should be replaced. Should be initialized to 0.","name":"next cursor"},{"description":"tensor to collect from","name":"DATA"},{"description":"(optional) mutex to use to make this thread-safe","name":"MUTEX"},{"description":"","name":"NUM_VISITED"}],"outputs":[{"description":"Data stored in sessions","name":"last-N buffer"},{"description":"Updated input cursor","name":"next cursor"},{"description":"number of records seen so far","name":"NUM_VISITED"}],"support_level":"default"}},{"name":"Bucketize","schema":{"attributes":[{"description":"bucketization boundaries","name":"boundaries","option":"optional"}],"description":"\nThis operator works as bucketize in tensorflow and digitize\nin numpy. It bucketizes the input 'X' based on argument 'boundaries'.\nFor each value x in input 'data', the operator returns index i given\nboundaries[i-1] < x <= boundaries[i].\nIf values in 'data' are beyond the bounds of boundaries, 0 or\nlen(boundaries) is returned as appropriate.\nThe boundaries need to be monotonically increasing.\nFor example\n\nIf data = [2, 4, 1] and boundaries = [0.1, 2.5], then\n\noutput = [1, 2, 1]\n\nIf data = [[2, 3], [4, 1], [2, 5]] and boundaries = [0.1, 2.5], then\n\noutput = [[1, 2], [2, 1], [1, 2]]\n\n","inputs":[{"description":"input tensor","name":"data"}],"outputs":[{"description":"indices of bins given by boundaries to which each valuein data belongs","name":"output"}],"support_level":"default"}},{"name":"HSoftmax","schema":{"attributes":[{"description":"Serialized HierarchyProto string containing list of vocabulary words and their paths from root of hierarchy to the leaf","name":"hierarchy","option":"optional"}],"description":"\nHierarchical softmax is an operator which approximates the softmax operator\nwhile giving significant training speed gains and reasonably comparable\nperformance. In this operator, instead of calculating the probabilities of all\nthe classes, we calculate the probability of each step in the path from root to\nthe target word in the hierarchy.\n\nThe operator takes a 2-D tensor (Tensor) containing a batch of layers, a\nset of parameters represented by the weight matrix and bias terms, and a 1-D\ntensor (Tensor) holding labels, or the indices of the target class. The\nhierarchy has to be specified as an argument to the operator.\n\nThe operator returns a 1-D tensor holding the computed log probability of the\ntarget class and a 2-D tensor of intermediate outputs (from the weight matrix\nand softmax from each step in the path from root to target class) which will be\nused by the gradient operator to compute gradients for all samples in the batch.\n","inputs":[{"description":"Input data from previous layer","name":"X"},{"description":"2D blob containing 'stacked' fully connected weight matrices. Each node in the hierarchy contributes one FC weight matrix if it has children nodes. Dimension is N*D, D is input dimension of data (X), N is sum of all output dimensions, or total number of nodes (excl root)","name":"W"},{"description":"1D blob with N parameters","name":"b"},{"description":"int word_id of the target word","name":"labels"}],"outputs":[{"description":"1-D of log probability outputs, one per sample","name":"Y"},{"description":"Extra blob to store the intermediate FC and softmax outputs for each node in the hierarchical path of a word. The outputs from samples are stored in consecutive blocks in the forward pass and are used in reverse order in the backward gradientOp pass","name":"intermediate_output"}],"support_level":"default"}},{"name":"ReduceFrontWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SpatialSoftmaxWithLoss","schema":{"description":"\nCombined Spatial Softmax and Cross-Entropy loss operator.\nSimilar to SoftmaxWithLoss, this operator computes the spatial softmax\nnormalized values for each layer in the batch of the given input, after which\ncross-entropy loss is computed. This operator is numerically more stable than\nseparate Softmax and CrossEntropy ops. The inputs are a 2-D tensor\n(Tensor) of size (batch_size x input_feature_dimensions) and tensor of\nlabels (ground truth).\nOutput is tensor with the probability for each label in a pixel for each example\n(N x D x W x H) and averaged loss (scalar).\nFor spatial softmax, weighting is by x,y position of the input.\n","inputs":[{"description":"Unscaled log probabilities","name":"logits"},{"description":"Ground truth","name":"labels"},{"description":"Optional blob to be used to weight the samples for the loss. With spatial set, weighting is by x,y of the input","name":"weight_tensor"}],"outputs":[{"description":"Tensor with softmax cross entropy loss","name":"softmax"},{"description":"Average loss","name":"loss"}],"support_level":"default"}},{"name":"SafeDequeueBlobs","schema":{"attributes":[{"description":"(default 1) If > 1, multiple records will be dequeued and tensors for each column will be concatenated. This requires all tensors in the records to be at least 1D, and to have the same inner dimensions.","name":"num_records","option":"optional"}],"description":"\nDequeue the blobs from queue. When the queue is closed and empty, the output\nstatus will be set to true which can be used as exit criteria for execution\nstep.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"outputs":[{"description":"The blob to store the dequeued data","name":"blob"},{"description":"Is set to 0/1 depending on the success of dequeue","name":"status"}],"support_level":"default"}},{"name":"Copy","schema":{"description":"\nCopy input tensor into output, potentially across devices.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/copy_op.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/copy_op.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Copy\",\n [\"input\"],\n [\"output\"]\n)\n\nworkspace.FeedBlob(\"input\", np.random.rand(3,3))\nprint(\"input:\", workspace.FetchBlob(\"input\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output:\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n[[0.16826761 0.68168217 0.55196001]\n [0.19735483 0.34837823 0.69015595]\n [0.09448514 0.57390828 0.37097193]]\noutput:\n[[0.16826761 0.68168217 0.55196001]\n [0.19735483 0.34837823 0.69015595]\n [0.09448514 0.57390828 0.37097193]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): input tensor to copy","name":"input"}],"outputs":[{"description":"(*Tensor*): copy of input tensor","name":"output"}],"support_level":"default"}},{"name":"AveragePool2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeLogMeanExp","schema":{"description":"\nApplies 'LogMeanExp' to each segment of input tensor. In order to allow for more\nefficient implementation of 'LogMeanExp', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nLogMeanExp computes the element-wise log of the mean of exponentials of input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"MergeMultiListFeatureTensors","schema":{"description":"Merge given multi-feature tensors with list features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values","name":"in1_values_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"CountUp","schema":{"description":"\nIncreases count value by 1 and outputs the previous value atomically.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* Count value BEFORE this operation.","name":"previous_count"}],"support_level":"default"}},{"name":"MergeSingleScalarFeatureTensorsGradient","schema":{"description":"Explode multi-feature tensor of scalar features into one or moresingle-feature tensors\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".presence","name":"in1_presence"},{"description":".values_grad","name":".values_grad"}],"outputs":[{"description":"_grad of inputs","name":"in1_grad"}],"support_level":"default"}},{"name":"GFtrl","schema":{"description":null,"support_level":"default"}},{"name":"Acos","schema":{"description":"\nCalculates the arccosine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arccosine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"SoftsignGradient","schema":{"description":"\nCalculates the softsign gradient (sgn(x)/(1+|x|)^2) of the given input tensor\nelement-wise.\n","inputs":[{"description":"1-D input tensor","name":"input"}],"outputs":[{"description":"The softsign gradient (sgn(x)/(1+|x|)^2) values of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"MergeDim","schema":{"description":"\nMerge first two dimensions in a single dimension with size dim(0) * dim(1).\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reshaped tensor.","name":"reshaped"}],"support_level":"default"}},{"name":"Int8ResizeNearest","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"},{"description":"Output dimensions (HxW). If specified this takes precedence over scale values.","name":"output_size","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input Int8 tensor","name":"X"}],"outputs":[{"description":"Output Int8 tensor","name":"Y"}],"support_level":"default"}},{"name":"LC","schema":{"description":"\nThe locally connected operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"AcosGradient","schema":{"description":null,"support_level":"default"}},{"name":"IndexHash","schema":{"attributes":[{"description":"seed for the hash function","name":"seed","option":"optional"},{"description":"must be > 0, hashed ids will be modulo this number","name":"modulo","option":"optional"}],"description":"\nThis operator translates a list of indices into a list of hashed indices.\nA seed can be fed as an argument to change the behavior of the hash function.\nIf a modulo is specified, all the hashed indices will be modulo the\nspecified number. All input and output indices are enforced to be positive.\n","inputs":[{"description":"Input feature indices.","name":"Indices"}],"outputs":[{"description":"Hashed feature indices.","name":"HashedIndices"}],"support_level":"default"}},{"name":"GroupNorm","schema":{"attributes":[{"description":"(int) default 32; number of groups used by GN.","name":"num_groups","option":"optional"},{"description":"(float) default 1e-5; small constant added to var.","name":"epsilon","option":"optional"}],"description":"\nGroup Normalization (GN) operation: https://arxiv.org/abs/1803.08494\n","inputs":[{"description":">=4D feature map input of shape (N, C, H, W) or (N, C, T, H, W)","name":"X"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"gamma"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"beta"}],"outputs":[{"description":"The output >=4-dimensional tensor of the same shape as X.","name":"Y"},{"description":"The mean of shape (N, G). For backward usage or reference. Cannot be used as activations.","name":"mean"},{"description":"The std of shape (N, G). For backward usage or reference. Cannot be used as activations.","name":"std"}],"support_level":"default"}},{"name":"ChannelShuffleGradient","schema":{"description":null,"support_level":"default"}},{"name":"DestroyCommonWorld","schema":{"description":"Closes all connections managed by a common world.","inputs":[{"description":"The common world to be destroyed.","name":"common_world"}],"support_level":"default"}},{"name":"Floor","schema":{"description":"\nElement-wise application of the floor function ($y=floor(x)$) to the input\ntensor `X`. Output tensor shape is the same as the input tensor. This\noperator can be used in an in-place fashion by using the same input blob as the\noutput blob.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/floor_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Floor\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.uniform(-10, 10, (5,5))).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[ 3.813361 -1.319647 5.2089314 -4.931328 0.6218652 ]\n [ 7.2757645 5.5552588 5.785643 -2.4790506 -0.41400087]\n [ 1.1541046 -6.933266 3.3754056 1.6569928 -1.7670316 ]\n [-3.4932013 4.891472 1.5530115 -3.2443287 -4.605099 ]\n [-4.574543 -7.360948 5.91305 -8.196495 -5.357458 ]]\nX after running op:\n[[ 3. -2. 5. -5. 0.]\n [ 7. 5. 5. -3. -1.]\n [ 1. -7. 3. 1. -2.]\n [-4. 4. 1. -4. -5.]\n [-5. -8. 5. -9. -6.]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"LengthsPartition","schema":{"attributes":[{"description":"(int, default 0) If set, the operator transforms the first tensor values as floor(X_ij / num_partitions)","name":"pack_first_input","option":"optional"}],"description":"\nLengthsPartition splits the input int tensor into multiple ones according to the\nsecond tensor. The first dimension is expected to be the tensor that describes\nlengths of the elements.\n\nTakes the second input and partitions it to shards according to the remainder of\nvalues modulo the number of partitions. It requires the second tensor to be\na 1D-tensor of the integral type. The first tensor should be 1D-tensor of int32\nthat would represent the lengths of the elements in the input. The number of\npartitions is derived as (num_output / num_input).\n\nIf additional inputs are present they must have the same shape as the first\ninput, optionally with extra trailing dimensions. They will be partitioned\naccordingly to the first input.\n\nOptional arg 'pack_first_input' transforms the first tensor values as\nX_ij / num_partitions.\n\nOutputs are ordered as\nX_0_part_0, X_1_part_0, ..., X_N-1_part_0, X_0_part_1, ..., X_N-1_part_K-1\n","inputs":[{"description":"Input tensor containing data to be partitioned. The number of input tensors might be greater than 1 but must have the same shape as the previous tensors.","name":"input"}],"outputs":[{"description":"Output Partitions. The number of output tensors has to be a multiple of the number of input tensors.","name":"partitions"}],"support_level":"default"}},{"name":"CreateCounter","schema":{"attributes":[{"default":0,"description":"Initial count for the counter, must be >= 0.","name":"init_count","option":"optional","type":"int64"}],"description":"\nCreates a count-down counter with initial value specified by the `init_count`\nargument.\n\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","outputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a new counter.","name":"counter"}],"support_level":"default"}},{"name":"MarginRankingCriterion","schema":{"attributes":[{"description":"The margin value as a float. Default is 1.0.","name":"margin","option":"optional"}],"description":"\nMarginRankingCriterion takes two input data X1 (Tensor),\nX2 (Tensor), and label Y (Tensor) to produce the\nloss (Tensor) where the loss function,\nloss(X1, X2, Y) = max(0, -Y * (X1 - X2) + margin), is applied to\nthe tensor elementwise.\n\nIf y == 1 then it assumed the first input should be ranked higher\n(have a larger value) than the second input, and vice-versa for\ny == -1.\n","inputs":[{"description":"The left input vector as a 1-dim TensorCPU.","name":"X1"},{"description":"The right input vector as a 1-dim TensorCPU.","name":"X2"},{"description":"The label as a 1-dim TensorCPU with int value of 1 or -1.","name":"Y"}],"outputs":[{"description":"The output loss with the same dimensionality as X1.","name":"loss"}],"support_level":"default"}},{"name":"MergeIdLists","schema":{"description":"\nMergeIdLists: Merge multiple ID_LISTs into a single ID_LIST.\n\nAn ID_LIST is a list of IDs (may be ints, often longs) that represents a single\nfeature. As described in https://caffe2.ai/docs/sparse-operations.html, a batch\nof ID_LIST examples is represented as a pair of lengths and values where the\n`lengths` (int32) segment the `values` or ids (int32/int64) into examples.\n\nGiven multiple inputs of the form lengths_0, values_0, lengths_1, values_1, ...\nwhich correspond to lengths and values of ID_LISTs of different features, this\noperator produces a merged ID_LIST that combines the ID_LIST features. The\nfinal merged output is described by a lengths and values vector.\n\nWARNING: The merge makes no guarantee about the relative order of ID_LISTs\nwithin a batch. This can be an issue if ID_LIST are order sensitive.\n","inputs":[{"description":"Lengths of the ID_LISTs batch for first feature","name":"lengths_0"},{"description":"Values of the ID_LISTs batch for first feature","name":"values_0"}],"outputs":[{"description":"Lengths of the merged ID_LISTs batch","name":"merged_lengths"},{"description":"Values of the merged ID_LISTs batch","name":"merged_values"}],"support_level":"default"}},{"name":"SumElements","schema":{"attributes":[{"description":"(*bool*): set to True to compute the average of the elements rather than the sum","name":"average","option":"optional"}],"description":"\nSums the elements of the input tensor. Tensor type must be float32.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nsum_op = core.CreateOperator(\n \"SumElements\",\n [\"X\"],\n [\"Y\"]\n)\n\navg_op = core.CreateOperator(\n \"SumElements\",\n [\"X\"],\n [\"Y\"],\n average=True\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(sum_op)\nprint(\"Y (sum_op):\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(avg_op)\nprint(\"Y (avg_op):\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[7. 2. 5.]\n [9. 4. 2.]\n [1. 2. 5.]]\nY (sum_op): 37.0\nY (avg_op): 4.111111\n\n```\n\n
\n\n ","inputs":[{"description":"(*Tensor``*): blob pointing to an instance of a counter","name":"X"}],"outputs":[{"description":"(*Tensor``*): Scalar tensor containing the sum (or average)","name":"sum"}],"support_level":"default"}},{"name":"ThresholdedReluGradient","schema":{"description":"\nThresholdedReluGradient takes both Y and dY and uses this to update dX\naccording to the chain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"GivenTensorInt64Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SparseLengthsSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"CountDown","schema":{"description":"\nIf the internal count value > 0, decreases count value by 1 and outputs False,\notherwise outputs True.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: bool)* False unless the internal count is zero.","name":"done"}],"support_level":"default"}},{"name":"ReciprocalGradient","schema":{"description":null,"support_level":"default"}},{"name":"Sqr","schema":{"description":"\nPerforms element-wise squaring ($x^2$) of input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sqr_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sqr\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[4. 6. 2.]\n [0. 1. 6.]\n [9. 2. 7.]]\nY:\n[[16. 36. 4.]\n [ 0. 1. 36.]\n [81. 4. 49.]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"StoreWait","schema":{"attributes":[{"description":"names of the blobs to wait for (optional)","name":"blob_names","option":"optional"}],"description":"\nWait for the specified blob names to be set. The blob names can be passed\neither as an input blob with blob names or as an argument.\n","inputs":[{"description":"unique_ptr","name":"handler"},{"description":"names of the blobs to wait for (optional)","name":"names"}],"support_level":"default"}},{"name":"ColwiseMax","schema":{"description":"\nCompute column-wise max reduction of the input tensor. This op takes one input, $X$, of shape $BxMxN$, where $B$ is the batch size, $M$ is number of rows, and $N$ is number of columns. The output of this op, $Y$, is a matrix of shape $BxN$, with one row for each element of the batch, and the same number of columns as the input tensor.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ColwiseMax\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X, simulating a batch of 2, 4x4 matricies\nX = np.random.randint(0,high=20,size=(2,4,4))\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[17 15 2 6]\n [ 8 12 6 0]\n [ 6 9 7 3]\n [ 4 13 16 13]]\n\n [[ 0 3 4 12]\n [18 1 17 12]\n [ 7 17 13 14]\n [12 17 2 1]]]\nY:\n [[17. 15. 16. 13.]\n [18. 17. 17. 14.]]\n\n```\n\n
\n\n ","inputs":[{"description":"A tensor of dimensions $B x M x N$ to compute columnwise-max. Here, $B$ is batch size, and $M$ and $N$ are the number of rows and columns of each element of the batch, respectively.","name":"X"}],"outputs":[{"description":"The output tensor of shape $B x N$, where each row represents the column-wise maximums for that element of the input batch.","name":"Y"}],"support_level":"default"}},{"name":"LogFatal","schema":{"description":null,"support_level":"default"}},{"name":"StringIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps string keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"support_level":"default"}},{"name":"CopyRowsToTensor","schema":{"description":"\n This operator takes in a 2d tensor, a list of indices, and a 1d tensor\n with the same width of the 2d tensor. It will replace the rows in 2d\n tensor specified in indices with the 2d tensor. The operator does an\n in-place change to the input tensor.\n Example:\n INPUT_TENSOR = [[1, 2], [3, 4], [5, 6]]\n INDICES = [1]\n ROW = [9, 0]\n OUTPUT_TENSOR = [[1, 2], [9, 0], [5, 6]]\n ","inputs":[{"description":"Input tensor needs to be modified.","name":"input_tensor"},{"description":"Indices of rows need to be copied","name":"indices"},{"description":"1-d tensor that is going to replace the rows","name":"row"}],"outputs":[{"description":"updated tensor","name":"output_tensor"}],"support_level":"default"}},{"name":"MakeTwoClass","schema":{"description":"\nGiven a vector of probabilities, this operator transforms this into a 2-column\n matrix with complimentary probabilities for binary classification. In explicit\n terms, given the vector X, the output Y is vstack(1 - X, X).\n ","inputs":[{"description":"Input vector of probabilities","name":"X"}],"outputs":[{"description":"2-column matrix with complimentary probabilities of X for binary classification","name":"Y"}],"support_level":"default"}},{"name":"Snapshot","schema":{"description":null,"support_level":"default"}},{"name":"NegateGradient","schema":{"description":"\nNegagteGradient operator in forward pass simply copies input to the\noutput, and in backward pass, flips the sign of the output gradient\n","support_level":"default"}},{"name":"Not","schema":{"description":"\nPerforms element-wise negation on input tensor `X`.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n\"Not\",\n[\"X\"],\n[\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3, 3) > 0.5))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[ True False False]\n[False False False]\n[ True True True]]\nY:\n[[False True True]\n[ True True True]\n[False False False]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(Tensor``)* Negated output tensor.","name":"Y"}],"support_level":"default"}},{"name":"PrependDim","schema":{"attributes":[{"description":"Size of the dimension to prepend.","name":"dim_size","option":"optional"}],"description":"\nReshape the tensor by prepending a dimension of fixed size and dividing the\nsize of the next dimension by that amount.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reshaped tensor.","name":"reshaped"}],"support_level":"default"}},{"name":"SendTensor","schema":{"attributes":[{"description":"The rank to send the tensor to.","name":"dst","option":"optional"},{"description":"(int) a tag to send the tensor with.","name":"tag","option":"optional"},{"description":"(bool) if set, only send the content and assume that the receiver has already known the tensor's shape and information.","name":"raw_buffer","option":"optional"}],"description":"\nSends the tensor to another node.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allgathered.","name":"X"},{"description":"An int CPUtensor of size 1 specifying the rank. If given, this overrides the 'to' argument of the op.","name":"dst"},{"description":"An int CPUtensor of size 1 specifying the tag to send the tensor with. This overrides the 'tag' argument of the op.","name":"tag"}],"support_level":"default"}},{"name":"InferenceLSTM","schema":{"attributes":[{"description":"(*long*): number of layers in the lstm stack","name":"num_layers","option":"optional"},{"description":"(*bool*): whether the cells have biases or not","name":"has_biases","option":"optional"},{"description":"(*bool*): whether the batch is at dim 0","name":"batch_first","option":"optional"},{"description":"(*bool*): if bidirectional","name":"bidirectional","option":"optional"}],"description":null,"outputs":[{"description":"the output of the last layer of lstm","name":"output"},{"description":"hidden state at t = seq_len","name":"hidden"},{"description":"cell state at t = seq_len","name":"cell"}],"support_level":"default"}},{"name":"SumElementsInt","schema":{"description":"Sums the integer elements of the input tensor.","inputs":[{"description":"Tensor to sum up","name":"X"}],"outputs":[{"description":"Scalar sum","name":"sum"}],"support_level":"default"}},{"name":"SparseAdagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nGiven inputs (param, moment, indices, grad, lr), runs the dense AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment_1"}],"support_level":"default"}},{"name":"Int8AveragePoolRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"AveragePool \nconsumes an input blob X and applies average pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Average pooling consisting of averaging all values of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from average pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linear function, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"SegmentIdsToRanges","schema":{"description":"\nTransfers a vector of segment ids to a vector of segment ranges. This operation\nsupports non-consecutive segment ids. Segments not appearing in the input vector\nwill have length 0. If the second input is provided, the number of segments =\nthe size of its first dimension. Otherwise, the number of segments = the last\nindex in the first input vector + 1.\n","inputs":[{"description":"1-D int32_t or int64_t tensor of segment ids","name":"segment_ids"},{"description":"if provided, number of segments = the size of its first dimension","name":"data (optional)"}],"outputs":[{"description":"1-D int64_t tensor of segment lengths","name":"lengths"}],"support_level":"default"}},{"name":"CreateCommonWorld","schema":{"attributes":[{"description":"(int) size of the common world.","name":"size","option":"optional"},{"description":"(int) rank of this node in the common world.","name":"rank","option":"optional"}],"description":"\nCreates a common world for communication operators.\n","inputs":[{"description":"Key/value handler for rendezvous (optional).","name":"kv_handler"}],"outputs":[{"description":"A common world for collective operations.","name":"comm_world"}],"support_level":"default"}},{"name":"SliceGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseUnsortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"DBExists","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"description":"Path to the db in question; see the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db_name","option":"optional","type":"string"},{"description":"Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional","type":"string"}],"description":"\nChecks if the db described by the arguments exists.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"DBExists\",\n [],\n [\"exists\"],\n db_name=\"test_db\",\n db_type=\"leveldb\",\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"exists:\", workspace.FetchBlob(\"exists\"))\n\n```\n\n
\n\n","outputs":[{"description":"*(type: Tensor``)* Scalar boolean output tensor. True if the db exists, else false.","name":"exists"}],"support_level":"default"}},{"name":"ReceiveTensor","schema":{"attributes":[{"description":"(int) he rank to receive the tensor from.","name":"src","option":"optional"},{"description":"(int) a tag to receive the tensor with.","name":"tag","option":"optional"},{"description":"(bool) if set, only send the content and assume that the receiver has already known the tensor's shape and information.","name":"raw_buffer","option":"optional"}],"description":"\nReceives the tensor from another node.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"In-place output. If raw_buffer is specified, Y should have pre-allocated data and type..","name":"Y"},{"description":"An int CPUtensor of size 1 specifying the rank. If given, this overrides the 'from' argument of the op.","name":"src"},{"description":"An int CPUtensor of size 1 specifying the tag to send the tensor with. This overrides the 'tag' argument of the op.","name":"tag"}],"outputs":[{"description":"The received tensor.","name":"Y"},{"description":"The sender that sent the message as a CPUTensor of size 1 and of type int.","name":"src"},{"description":"The tag that the message is sent with as a CPUTensor of size 1 and of type int.","name":"tag"}],"support_level":"default"}},{"name":"SquaredL2DistanceGradient","schema":{"description":null,"support_level":"default"}},{"name":"Swish","schema":{"description":"\nSwish takes one input data (Tensor) and produces one output data\n(Tensor) where the swish function, y = x / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchGatherGradient","schema":{"description":null,"support_level":"default"}},{"name":"LearningRate","schema":{"attributes":[{"description":"(float, required) base learning rate","name":"base_lr","option":"optional"},{"description":"(float, default 1.0) strategy for gamma enforcement","name":"policy","option":"optional"},{"description":"(float, default 1.0) used only for inv policy type","name":"power","option":"optional"},{"description":"(float, default 1.0) momentum of change","name":"gamma","option":"optional"},{"description":"(float, default 1.0) sampling rate on iterations","name":"stepsize","option":"optional"},{"description":"(boolean, default True) in alter policy","name":"active_first","option":"optional"},{"description":"(int64_t, required) in alter policy","name":"active_period","option":"optional"},{"description":"(int64_t, required) in alter policy","name":"inactive_period","option":"optional"},{"description":"(int, default -1) maximum iterations in this training run","name":"max_iter","option":"optional"},{"description":"(int, default 0) number of iterations over which to warmup lr","name":"num_iter","option":"optional"},{"description":"(float, default 0) starting multiplier for learning rate","name":"start_multiplier","option":"optional"},{"description":"(float, default 0) end multiplier for learning rate","name":"end_multiplier","option":"optional"},{"description":"(float, default 0.5) constant multiplier for learning rate","name":"multiplier","option":"optional"},{"description":"(float, default 1) start multiplier for learning rate","name":"multiplier_1","option":"optional"},{"description":"(float, default 1) end multiplier for learning rate","name":"multiplier_2","option":"optional"},{"description":"(int array, default empty) number of iterations for each sub learning rate policy in composite policy","name":"sub_policy_num_iters","option":"optional"},{"description":"","name":"m1","option":"optional"},{"description":"","name":"n1","option":"optional"},{"description":"","name":"m2","option":"optional"},{"description":"","name":"n2","option":"optional"},{"description":"","name":"m3","option":"optional"},{"description":"(float, default 0.005) max learning rate","name":"max_lr","option":"optional"},{"description":"defaults to 0.1","name":"start_warmup_multiplier","option":"optional"},{"description":"defaults to 10000000","name":"constant_warmup_num_iter","option":"optional"},{"description":"defaults to 10000000","name":"linear_warmup_num_iter","option":"optional"},{"description":"defaults to 0.05, part of CompositeCyclicalLRPolicy","name":"cyclical_max_lr","option":"optional"},{"description":"defaults to 1000000, part of CompositeCyclicalLRPolicy","name":"cyclical_step_size","option":"optional"},{"description":"defaults to 0.999, part of CompositeCyclicalLRPolicy","name":"cyclical_decay","option":"optional"},{"description":"defaults to 0.01, part of CompositeCosineLRPolicy","name":"cosine_min_lr","option":"optional"},{"description":"defaults to 0.05, part of CompositeCosineLRPolicy","name":"cosine_max_lr","option":"optional"},{"description":"defaults to 50, part of CompositeCosineLRPolicy","name":"cosine_period","option":"optional"},{"description":"defaults to 1,0, part of CompositeCosineLRPolicy","name":"cosine_t_mult","option":"optional"},{"description":"defaults to 0.99, part of CompositeCosineLRPolicy","name":"cosine_lr_shrink","option":"optional"}],"description":"\nLearning rate is a decreasing function of time. With low learning rates the\nimprovements will be linear. With high learning rates they will start to look\nmore exponential. Learning rate is controlled by the following arguments:\n\n\nRequired:\n `iterations`\n `base_lr`: base learning rate\n `policy`: this controls how the learning rate is applied, options are:\n `fixed`\n `step`: uses `stepsize`, `gamma`\n `exp`: uses `gamma`\n `gate`: uses 'multiplier_1', 'multiplier_2', `num_iter``\n `inv`: uses `gamma`, `power`\n `linearWarmup`: uses `start_multiplier`, `num_iter`\n `constantWarmup`: uses `multiplier`, `num_iter`\n `alter`: uses `active_first`, `active_period`, `inactive_period`\n `hill`: uses those in both `linearWarmup` and `inv`, plus `end_multiplier`\n `composite`: uses `sub_policy_num_iters` and additional args with format\n `cyclic`: uses `max_lr`, `stepsize`\n `cosine`: uses `min_lr`, `max_lr`, `period`, `t_mult`, `lr_shrink`\n `constantThenLinearWarmup`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`\n `compositeCyclical`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`, `cyclical_max_lr`, `cyclical_step_size`, `cyclical_decay`\n `compositeCosine`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`, `cosine_max_lr`, `cosine_period`, `cosine_t_mult`, `cosine_lr_shrink`\n sub_policy_{sub_policy_index}_{sub_policy_arg}, for example:\n sub_policy_0_policy: \"exp\", sub_policy_0_gamma: 0.99,\n sub_policy_0_lr_scale: 1.2\n sub_policy_0_policy: \"fixed\", sub_policy_0_lr_scale: 1.0\n sub_policy_num_iters: [1000, 1000]\n\nOptional:\n `stepsize`: defaults to 0\n `max_lr`: defaults to 0.005\n `gamma`: defaults to 0\n `power`: defaults to 0\n `num_iter`: defaults to 0\n `start_multiplier`: defaults to 0\n `multiplier`: defaults to 0.5\n `multiplier_1`: defaults to 1\n `multiplier_2`: defaults to 1\n `m1`: defaults to 0.5, the first piece lr of piece warmup\n `n1`: defaults to 0, iter threshold of the first piece lr\n `m2`: defaults to 0.5, the second piece lr of piece warmup\n `n2`: defaults to 0, iter threshold of the second piece lr\n `m3`: defaults to 0.5, the third piece lr of piece warmup\n `start_warmup_multiplier`: defaults to 0.1, part of constantThenLinearWarmup\n `constant_warmup_num_iter`: defaults to 10000000, part of constantThenLinearWarmup and constantThenLinearWarmup\n `linear_warmup_num_iter`: defaults to 10000000, part of constantThenLinearWarmup, CompositeCyclicalLRPolicy, CompositeCosineLRPolicy\n `cyclical_max_lr`: defaults to 0.05, part of CompositeCyclicalLRPolicy\n `cyclical_step_size`: defaults to 1000000, part of CompositeCyclicalLRPolicy\n `cyclical_decay`: defaults to 1.0, part of CompositeCyclicalLRPolicy\n `cosine_min_lr`:defaults to 0.01, part of CompositeCosineLRPolicy\n `cosine_max_lr`:defaults to 0.05, part of CompositeCosineLRPolicy\n `cosine_period`:defaults to 50, part of CompositeCosineLRPolicy\n `cosine_t_mult`:defaults to 1.0, part of CompositeCosineLRPolicy\n `cosine_lr_shrink`:defaults to 0.99, part of CompositeCosineLRPolicy\n\nUsage:\n train_net.LearningRate(*iterations*, \"*label*\", base_lr=*float*,\n policy=\"policy_name\", stepsize=*int*, gamma=*float*)\n\n\nExample usage:\n train_net.LearningRate(200, \"LR\", base_lr=-0.1,\n policy=\"step\", stepsize=20, gamma=0.9)\n","inputs":[{"description":"description needed","name":"input"}],"outputs":[{"description":"description needed","name":"output"}],"support_level":"default"}},{"name":"PReluGradient","schema":{"description":"\n\nPReluGradient takes both Y and dY and uses this to update dX and dW according\nto the chain rule and derivatives of the rectified linear function.\n\n","support_level":"default"}},{"name":"LengthsMean","schema":{"description":"\nApplies 'Mean' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Mean' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n\n\nThe *LengthsMean* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the mean value in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [mean([2,4]), mean([3,1,2]), mean([10])] = [3,2,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsMean\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 3. 2. 10.]\n\n```\n\n
\n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"Conv3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CheckCounterDone","schema":{"description":"\nIf the internal count value <= 0, outputs true, otherwise outputs false.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: bool)* True if the internal count is zero or negative, otherwise False.","name":"done"}],"support_level":"default"}},{"name":"LabelCrossEntropyGradient","schema":{"description":null,"support_level":"default"}},{"name":"Adam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nComputes the Adam update (https://arxiv.org/abs/1412.6980) for an\ninput gradient and momentum parameters. Concretely, given inputs\n(param, m1, m2, grad, lr, iters),\n\n t = iters + 1\n correction_multiplier = sqrt(1 - power(beta2, t)) /\n (1 - power(beta1, t))\n m1_o = (beta1 * m1) + (1 - beta1) * grad\n m2_o = (beta2 * m2) + (1 - beta2) * np.square(grad)\n grad_o = correction_multiplier * m1_o / \\\n (sqrt(m2_o) + epsilon)\n param_o = param + lr * grad_o\n\nand returns (param_o, m1_o, m2_o, grad_o), in which grad_o is an optional output\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"FCGradient","schema":{"description":null,"support_level":"default"}},{"name":"IsNaN","schema":{"description":"Returns a new tensor with boolean elements representing if each element is NaN or not.","inputs":[{"description":"Tensor to check for nan","name":"tensor"}],"outputs":[{"description":"Tensor containing a 1 at each location of NaN elements.","name":"output"}],"support_level":"default"}},{"name":"LengthsWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceBackSum","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **sum**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the sum operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [sum(1,5), sum(4,1,8), sum(2)] = [6, 13, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_sum_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackSum\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[2. 7. 7.]\n [1. 1. 0.]\n [9. 7. 2.]]\n\n [[6. 6. 4.]\n [1. 2. 6.]\n [6. 6. 3.]]]]\nY: [[36. 40.]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"LogitGradient","schema":{"attributes":[{"description":"small positive epsilon value, the default is 1e-6.","name":"eps","option":"optional"}],"description":null,"inputs":[{"description":"input float tensor","name":"X"},{"description":"input float tensor","name":"dY"}],"outputs":[{"description":"output float tensor","name":"dX"}],"support_level":"default"}},{"name":"RowwiseMax","schema":{"description":"\nCompute row-wise max reduction of the input tensor. This op takes one input, $X$, of shape $BxMxN$, where $B$ is the batch size, $M$ is number of rows, and $N$ is number of columns. The output of this op, $Y$, is a matrix of shape $BxM$, with one row for each element of the batch, and the same number of columns as the number of rows of the input tensor.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"RowwiseMax\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X, simulating a batch of 2, 4x4 matricies\nX = np.random.randint(0,high=20,size=(2,4,4))\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[ 5 12 10 1]\n [ 4 16 2 15]\n [ 5 11 12 15]\n [15 4 17 19]]\n\n [[16 5 5 13]\n [17 2 1 17]\n [18 3 19 5]\n [14 16 10 16]]]\nY:\n [[12. 16. 15. 19.]\n [16. 17. 19. 16.]]\n\n```\n\n
\n\n ","inputs":[{"description":"A tensor of dimensions $B x M x N$ to compute rowwise-max. Here, $B$ is batch size, and $M$ and $N$ are the number of rows and columns of each element of the batch, respectively.","name":"X"}],"outputs":[{"description":"The output tensor of shape $B x M$, where each row represents the row-wise maximums for that element of the input batch.","name":"Y"}],"support_level":"default"}},{"name":"Fail","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentMean","schema":{"description":"\nApplies 'Mean' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentMean that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceFrontMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"RemoveDataBlocks","schema":{"description":"\nShrink the data tensor by removing data blocks with given zero-based indices in\nthe outermost dimension of the tensor. Indices are not assumed in any order or\nunique but with the range [0, blocks_size). Indices could be empty.\n ","inputs":[{"description":"a N-D data tensor, N >= 1","name":"data"},{"description":"zero-based indices of blocks to be removed","name":"indices"}],"outputs":[{"description":"data after removing data blocks indexed by 'indices'","name":"shrunk data"}],"support_level":"default"}},{"name":"SwapBestPath","schema":{"description":"\nGiven a sequence of indices and a matrix, enforce that these indices have the\nbest columnwise scores\nscore\n","inputs":[{"description":"N*D predictions matrix","name":"predictions"},{"description":"N*1 vector holds the best path indices ","name":"bestPath"}],"outputs":[{"description":"N*D updated predictions matrix","name":"new_predictions"}],"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"StringEndsWith","schema":{"attributes":[{"description":"The suffix to check input strings against.","name":"suffix","option":"optional"}],"description":"\nPerforms the ends-with check on each string in the input tensor.\nReturns tensor of boolean of the same dimension of input.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of bools of same shape as input.","name":"bools"}],"support_level":"default"}},{"name":"While","schema":{"attributes":[{"description":"Net executed on each iteration","name":"loop_net","option":"optional"},{"description":"Net to (re)compute condition value","name":"cond_net","option":"optional"}],"description":"\n'While' control operator, first input is a scalar boolean blob that stores loop's\ncondition value. Accepts 'loop_net' (required) and 'cond_net' (optional) arguments for\nloop's body and condition subnets respectively. If condition subnet is specified,\nit is executed before the first and after each iteration. Subnets are executed in\nthe same workspace as 'While'.\n ","inputs":[{"description":"Scalar boolean condition","name":"condition"}],"support_level":"default"}},{"name":"Range","schema":{"description":"\nGenerates an output tensor within the half-open interval $[start, stop)$ (the interval including start but excluding stop).\n- The `start` input is optional, and defaults to 0 when not set.\n- The `step` input is optional, and defaults to 1 when not set.\n- The type of the `output` tensor is determined by the types of inputs used.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Range\",\n [\"start\", \"stop\", \"step\"],\n [\"output\"]\n)\n\nworkspace.FeedBlob(\"start\", np.array(4, dtype=np.int32))\nworkspace.FeedBlob(\"stop\", np.array(17, dtype=np.int32))\nworkspace.FeedBlob(\"step\", np.array(2, dtype=np.int32))\nprint(\"start:\", workspace.FetchBlob(\"start\"))\nprint(\"stop:\", workspace.FetchBlob(\"stop\"))\nprint(\"step:\", workspace.FetchBlob(\"step\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output:\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\nstart: 4\nstop: 17\nstep: 2\noutput: [ 4 6 8 10 12 14 16]\n\n```\n\n
\n ","inputs":[{"description":"(*Tensor*): [OPTIONAL] scalar or 1-element tensor containing the start of the interval (inclusive) (default=0)","name":"start"},{"description":"(*Tensor*): scalar or 1-element tensor containing the end of the interval (exclusive)","name":"stop"},{"description":"(*Tensor*): [OPTIONAL] scalar or 1-element tensor specifying the spacing between values (default=1)","name":"step"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as inputs that contains the sequence","name":"output"}],"support_level":"default"}},{"name":"Int8AddRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Performs element-wise binary Add (with no broadcast support). \"\n \"Output will go through rectified linear \"\n \"function, where y = max(0, x).\n","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. It should be of the same size as A.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as A","name":"C"}],"support_level":"default"}},{"name":"SquareRootDivide","schema":{"description":"\nGiven DATA tensor with first dimension N and SCALE vector of the same size N\nproduces an output tensor with same dimensions as DATA. Which consists of DATA\nslices. i-th slice is divided by sqrt(SCALE[i]) elementwise. If SCALE[i] == 0\noutput slice is identical to the input one (no scaling)\n\nExample:\n\n Data = [\n [2.0, 4.0],\n [9.0, 12.0]\n ]\n\n SCALE = [4, 9]\n\n OUTPUT = [\n [1.0, 2.0],\n [3.0, 4.0]\n ]\n\n","support_level":"default"}},{"name":"SortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Sign","schema":{"description":"\nComputes sign for each element of the input: -1, 0 or 1.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n\"Sign\",\n[\"X\"],\n[\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3, 3).astype(np.float32) - np.random.rand(3, 3).astype(np.float32)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[ 0.02816287 0.22408086 -0.30342305]\n[-0.18481976 0.03948995 0.39698976]\n[-0.63304734 -0.6919183 -0.31524038]]\nY:\n[[ 1. 1. -1.]\n[-1. 1. 1.]\n[-1. -1. -1.]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"Xor","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **xor** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Xor\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[ True True True]\n [False False True]\n [False True False]]\nB:\n[[False False False]\n [ True True True]\n [False False False]]\nC:\n[[ True True True]\n [ True True False]\n [False True False]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"SigmoidGradient","schema":{"description":"\nSigmoidGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the sigmoid function.\n","support_level":"default"}},{"name":"MergeMultiScalarFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with scalar features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values_grad","name":"out_values_grad"}],"outputs":[{"description":".values_grad","name":"in1_values_grad"}],"support_level":"default"}},{"name":"Sin","schema":{"description":"\nCalculates the sine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sin_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sin\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.8466114 0.1803606 0.5601509 0.04959291 0.64770824]\nY: [0.74903965 0.17938434 0.5313141 0.04957259 0.60336035]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the sine of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"Log","schema":{"description":"\nCalculates the natural log of the given input tensor ($ln(x)$), element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/log_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Log\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[0.07341351 0.15404125 0.386613 ]\n [0.34090295 0.99727786 0.24141751]\n [0.32016268 0.8724168 0.93515724]]\nX after running op:\n[[-2.6116474 -1.8705349 -0.9503311 ]\n [-1.0761575 -0.00272586 -1.4212275 ]\n [-1.138926 -0.13648799 -0.06704059]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor computed as the natural log of the input tensor computed, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"DenseVectorToIdList","schema":{"description":"\nDenseVectorToIdList: Convert a blob with dense feature into a ID_LIST.\n\nAn ID_LIST is a list of IDs (may be ints, often longs) that represents a single\nfeature. As described in https://caffe2.ai/docs/sparse-operations.html, a batch\nof ID_LIST examples is represented as a pair of lengths and values where the\n`lengths` (int32) segment the `values` or ids (int32/int64) into examples.\n\nInput is a single blob where the first dimension is the batch size and the\nsecond dimension is the length of dense vectors. This operator produces a\nID_LIST where out_values are the indices of non-zero entries\nand out_lengths are the number of non-zeros entries in each row.\n\n","inputs":[{"description":"A data blob of dense vectors","name":"values"}],"outputs":[{"description":"Lengths of the sparse feature","name":"out_lengths"},{"description":"Values of the sparse feature","name":"out_values"}],"support_level":"default"}},{"name":"Reshape","schema":{"attributes":[{"description":"New shape. Do not set if using `new_shape` input.","name":"shape","option":"optional"}],"category":"Shape","description":"\nReshape the input tensor similar to numpy's\n[reshape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html).\n\nTakes a tensor as input and an optional tensor specifying the new shape. When\nthe second input is absent, an extra argument shape must be specified. Outputs\nthe reshaped tensor as well as the original shape.\n\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is going to be copied\nfrom the input tensor.\n\nFor empty tensor, we will set the -1 dimension to be 0 (if one dimension is -1).\nWhen the tensor is empty, dimension of 0 will remain to be 0.\nE.g: data=np.empty(shape=[4, 0]), shape=[0, -1], the output tensor will be\nnp.emtpy(shape=[0, 0])\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reshape_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Reshape\",\n [\"data\"],\n [\"reshaped\", \"old_shape\"],\n shape=(3,2)\n)\n\nworkspace.FeedBlob(\"data\", (np.random.randint(100, size=(6))))\nprint(\"data:\", workspace.FetchBlob(\"data\"))\nworkspace.RunOperatorOnce(op)\nprint(\"reshaped:\", workspace.FetchBlob(\"reshaped\"))\nprint(\"old_shape:\", workspace.FetchBlob(\"old_shape\"))\n```\n\n**Result**\n\n```\ndata: [86 60 85 96 7 37]\nreshaped: [[86 60]\n [85 96]\n [ 7 37]]\nold_shape: [6]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"data"},{"description":"*(type: Tensor``)* [OPTIONAL] Tensor containing new shape.","name":"new_shape"}],"outputs":[{"description":"*(type: Tensor)* Reshaped output tensor.","name":"reshaped"},{"description":"*(type: Tensor``)* Tensor containing old shape of `data`.","name":"old_shape"}],"support_level":"default"}},{"name":"AveragePoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnqueueBlobs","schema":{"description":null,"support_level":"default"}},{"name":"DepthConcat","schema":{"description":"Backward compatible operator name for Concat.","support_level":"default"}},{"name":"GatherPadding","schema":{"attributes":[{"description":"Outer-size of padding present around each range.","name":"padding_width","option":"optional"},{"description":"(Optional) Specifies a different end-padding width.","name":"end_padding_width","option":"optional"}],"description":"\nGather the sum of start and end paddings in a padded input sequence. Used in\norder to compute the gradients of AddPadding w.r.t the padding tensors.\n","inputs":[{"description":"T Padded input data","name":"data_in"},{"description":"(i64) Num of elements in each range. sum(lengths) = N. If not provided, considers all data as a single segment.","name":"lengths"}],"outputs":[{"description":"Sum of all start paddings, or of all paddings if end_padding_sum is not provided.","name":"padding_sum"},{"description":"T Sum of all end paddings, if provided.","name":"end_padding_sum"}],"support_level":"default"}},{"name":"DepthSplit","schema":{"description":"Backward compatible operator name for Split.","support_level":"default"}},{"name":"UnsortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the min of the input tensor's element along the provided axes.\n The resulted tensor has the same rank as the input if keepdims equal True.\n If keepdims equal false, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced output tensor.","name":"reduced"}],"support_level":"default"}},{"name":"StatRegistryExport","schema":{"attributes":[{"description":"(default true) Whether to atomically reset the counters afterwards.","name":"reset","option":"optional"}],"description":null,"inputs":[{"description":"If provided, export values from given StatRegistry.Otherwise, export values from the global singleton StatRegistry.","name":"handle"}],"outputs":[{"description":"1D string tensor with exported key names","name":"keys"},{"description":"1D int64 tensor with exported values","name":"values"},{"description":"The unix timestamp at counter retrieval.","name":"timestamps"}],"support_level":"default"}},{"name":"Free","schema":{"description":"\nFrees the content of the blobs. The input and output blobs should be\none-to-one inplace.","support_level":"default"}},{"name":"FlexibleTopK","schema":{"description":"\nGiven two tensors: X and K,\nretrieve the top K[..., 1] elements from X on the last dimension.\nX is an input tensor of shape [a_1, a_2, ..., a_n, r].\nK is an input tensor of shape [a_1, a_2, ..., a_n, 1],\nwhere for each element, r >= K[..., 1] > 0\nOutput two outputs:\n-Flatten values tensor of shape [ \\sum_i K[i, 1] ] which contains the values of\n the top K[..., 1] elements along the last dimension\n-Flatten indices tensor of shape [ \\sum_i K[i, 1] ] which contains the indices\n of the top K[..., 1] elements, flatten indices from the input tensor).\nThese two outputs should be used with the input K, so that we know which indices\nin X are picked.\n\nGiven two equivalent values, this operator uses the indices along the last dim-\nension as a tiebreaker. That is, the element with the lower index will appear\nfirst.\n ","inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X"},{"description":"Tensor of shape [a_1, a_2, ..., a_n, 1]","name":"K"}],"outputs":[{"description":"Tensor of shape [ \\sum_i K[i, 1] ] containing top K[..., 1] values from the input tensor","name":"Flatten values"},{"description":"Tensor of shape [ \\sum_i K[i, 1] ] containing the indices into the flatten input","name":"Flatten indices"}],"support_level":"default"}},{"name":"ReduceL1","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **L1 norm** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceL1\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[ 2. 7. 6. 4. 5.]\n [ 2. 1. 9. 8. 7.]\n [ 4. 9. 1. 0. 0.]\n [ 6. 4. 0. 8. 1.]\n [ 1. 7. 1. 0. 2.]]\n\n [[ 5. 8. 1. 7. 7.]\n [ 4. 5. 6. 5. 4.]\n [ 1. 9. 6. 6. 3.]\n [ 6. 6. 8. 8. 4.]\n [ 2. 3. 5. 8. 1.]]]]\n\nY:\n[[ 7. 15. 7. 11. 12.]\n [ 6. 6. 15. 13. 11.]\n [ 5. 18. 7. 6. 3.]\n [ 12. 10. 8. 16. 5.]\n [ 3. 10. 6. 8. 3.]]\n\n```\n\n
\n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"NumpyTile","schema":{"description":null,"inputs":[{"description":"The input tensor.","name":"data"},{"description":"1-D Tensor specifying how many times to repeat each axis.","name":"repeats"}],"outputs":[{"description":"Tensor that will contain input replicated along the given axis.","name":"tiled_data"}],"support_level":"default"}},{"name":"EluGradient","schema":{"description":"\nEluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"ArgMax","schema":{"attributes":[{"default":-1,"description":"The axis to get argmax.","name":"axis","option":"optional","type":"int64"},{"default":true,"description":"If True (default), the output tensor shape will match the input tensor shape except the `axis` dimension equals 1. Else, the `axis` dimension of the output tensor is removed.","name":"keepdims","option":"optional","type":"boolean"}],"description":"\nRetrieve the argmax of an axis dimension specified by the `axis`\nargument. Given an input tensor and two arguments (`axis` and\n`keepdims`), returns a tensor containing the indices of the largest\nelement along the given axis. If the `keepdims` arg is *True* (default),\nthe shape of the output tensor matches the input tensor except the\n`axis` dimension equals 1. Else, the `axis` dimension of the output\ntensor is removed.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/arg_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ArgMax\",\n [\"X\"],\n [\"Indices\"],\n axis=2,\n keepdims=False\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\n\n```\n\n**Result**\n\n```\nX: [[[4. 9. 6.]\n [6. 6. 1.]\n [9. 5. 4.]]\n\n [[6. 7. 4.]\n [7. 9. 1.]\n [3. 2. 8.]]\n\n [[3. 4. 6.]\n [5. 2. 7.]\n [1. 5. 7.]]]\nIndices: [[1 0 0]\n [1 1 2]\n [2 2 2]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Tensor of indices for the largest values.","name":"Indices"}],"support_level":"default"}},{"name":"IndexGet","schema":{"description":"\nGiven an index handle and a tensor of keys, return an Int tensor of same shape\ncontaining the indices for each of the keys. If the index is frozen, unknown\nentries are given index 0. Otherwise, new entries are added into the index.\nIf an insert is necessary but max_elements has been reached, fail.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"},{"description":"Tensor of keys to be looked up.","name":"keys"}],"outputs":[{"description":"Indices for each of the keys.","name":"indices"}],"support_level":"default"}},{"name":"HeatmapMaxKeypoint","schema":{"description":null,"support_level":"default"}},{"name":"MomentsGradient","schema":{"description":null,"support_level":"default"}},{"name":"L1Distance","schema":{"description":"\nComputes the row-wise L1 Distance between the two input tensors $X$ and $Y$, which is defined as\n\n$$L1Distance(\\mathbf{x},\\mathbf{y}) = \\sum_{i}\\mid x_i - y_i\\mid$$\n\nNote, both inputs must either be 1-dimensional or 2-dimensional and both must have the same shape. The output $Z$ will be 1-dimensional regardless and its length will equal the number of rows in the inputs.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"L1Distance\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\n// Create X\nX = 5*np.ones((1, 4))\nprint(\"X:\\n\",X)\n\n// Create Y\nY = np.ones((1, 4))\nprint(\"Y:\\n\",Y)\n\n// Feed X & Y into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"Y\", Y.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[5. 5. 5. 5.]]\nY:\n [[1. 1. 1. 1.]]\nZ:\n [16.]\n\n```\n\n
\n\n","inputs":[{"description":"First input tensor. (1D or 2D)","name":"X"},{"description":"Second input tensor. (must have the same shape as $X$)","name":"Y"}],"outputs":[{"description":"1D output tensor. One value for each row of the inputs.","name":"Z"}],"support_level":"default"}},{"name":"Allreduce","schema":{"description":"\nDoes an allreduce operation among the nodes. Currently only Sum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allreduced.","name":"X"}],"outputs":[{"description":"The allreduced tensor, same on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"Onnxifi","schema":{"attributes":[{"description":"(string default=\"\") Serialized ONNX model to be converted to backend representation","name":"onnx_model","option":"optional"},{"description":"Initialization pair indicating the mapping of the name between NetDef and ONNX model","name":"initializers","option":"optional"},{"description":"A list of key/value pairs indicating which input index to look up for real batch size for the given max output batch size","name":"output_resize_hints","option":"optional"}],"description":"\n The Onnxifi operator is a black-box operator to lower the computation to Onnxifi backend\n ","support_level":"default"}},{"name":"Partition","schema":{"attributes":[{"description":"(int, default 0) If set, the operator transforms the first tensor values as floor(X_ij / num_partitions)","name":"pack_first_input","option":"optional"}],"description":"\nSplits the input int tensor into multiple ones according to the first tensor.\n\nTakes the first input and partitions it to shards according to the remainder of\nvalues modulo the number of partitions. It requires that the first tensor is of\nintegral type. The number of partitions is derived as (num_output / num_input).\n\nIf additional inputs are present they must have the same shape as the first\ninput, optionally with extra trailing dimensions. They will be partitioned\naccordingly to the first input.\n\nOptional arg 'pack_first_input' transforms the first tensor values as\nX_ij / num_partitions.\n\nOutputs are ordered as\nX_0_part_0, X_1_part_0, ..., X_N-1_part_0, X_0_part_1, ..., X_N-1_part_K-1\n","inputs":[{"description":"Input tensor containing data to be partitioned. The number of input tensors might be greater than 1 but must have the same shape as the previous tensors.","name":"input"}],"outputs":[{"description":"Output Partitions. The number of output tensors has to be a multiple of the number of input tensors.","name":"partitions"}],"support_level":"default"}},{"name":"LengthsTopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"FlexibleTopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"ThrowException","schema":{"description":null,"support_level":"default"}},{"name":"LengthsMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Tile","schema":{"attributes":[{"description":"(*int*): number of replicas","name":"tiles","option":"optional"},{"description":"(*int*): axis to replicate along","name":"axis","option":"optional"}],"description":"\nConstructs a tensor by tiling a given tensor along a specified axis. This operation creates a new tensor by replicating the input tensor a number of times specified by the `tiles` argument along the `axis` dimension. The output tensor's `axis` dimension has $(X.dims(axis) * tiles)$ elements.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/tile_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Tile\",\n [\"X\", \"tiles\", \"axis\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(5,5)))\nworkspace.FeedBlob(\"tiles\", np.array([5]).astype(np.int32))\nworkspace.FeedBlob(\"axis\", np.array([1]).astype(np.int32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[9 1 7 1 3]\n [2 3 6 2 5]\n [0 9 2 6 4]\n [5 8 1 5 9]\n [2 0 1 3 7]]\nY:\n[[9 1 7 1 3 9 1 7 1 3 9 1 7 1 3 9 1 7 1 3 9 1 7 1 3]\n [2 3 6 2 5 2 3 6 2 5 2 3 6 2 5 2 3 6 2 5 2 3 6 2 5]\n [0 9 2 6 4 0 9 2 6 4 0 9 2 6 4 0 9 2 6 4 0 9 2 6 4]\n [5 8 1 5 9 5 8 1 5 9 5 8 1 5 9 5 8 1 5 9 5 8 1 5 9]\n [2 0 1 3 7 2 0 1 3 7 2 0 1 3 7 2 0 1 3 7 2 0 1 3 7]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): input tensor","name":"X"},{"description":"(*Tensor``*): [OPTIONAL] number of replicas (overrides `tiles` argument)","name":"tiles"},{"description":"(*Tensor``*): [OPTIONAL] axis to replicate along (overrides `axis` argument)","name":"axis"}],"outputs":[{"description":"(*Tensor*): output tensor","name":"Y"}],"support_level":"default"}},{"name":"Asin","schema":{"description":"\nCalculates the arcsine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"SplitByLengths","schema":{"attributes":[{"description":"Which axis to split on","name":"axis","option":"optional"},{"description":"Either NHWC or NCWH, will split on C axis, defaults to NCHW","name":"order","option":"optional"}],"description":"\nSplit a tensor into a list of tensors, given a lengths input, along the specified\n'axis'. If `K` outputs are provided, the op assumes `len(lengths) % K == 0`.\nThe `input` will be split into `K` parts. Each part of length\n`sum(lengths[i*k:i*k+k))`","inputs":[{"description":"The tensor to split","name":"input"},{"description":"The tensor `l_i` indicates the logic block of input.","name":"legnths"}],"support_level":"default"}},{"name":"CreateBlobsQueueDB","schema":{"attributes":[{"description":"(default: -1 (no key)) index of blob for DB key in the BlobsQueue.","name":"key_blob_index","option":"optional"},{"description":"(default: 0) index of blob for DB value in the BlobsQueue.","name":"value_blob_index","option":"optional"},{"description":"(default: 0.0 (no timeout)) Timeout in seconds for reading from the BlobsQueue.","name":"timeout_secs","option":"optional"}],"description":"Create a DBReader from a BlobsQueue","inputs":[{"description":"The shared pointer to a queue containing Blobs.","name":"queue"}],"outputs":[{"description":"The DBReader for the given BlobsQueue","name":"reader"}],"support_level":"default"}},{"name":"GRUUnitGradient","schema":{"attributes":[{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":null,"support_level":"default"}},{"name":"CloseBlobsQueue","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8Sigmoid","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nApply the Sigmoid function element-wise to the input tensor. This is often used\nas a non-linear activation function in a neural network. The sigmoid function is\ndefined as:\n\n$$Sigmoid(x) = \\frac{1}{1+\\exp(-x)}$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sigmoid_op.cc\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"}],"outputs":[{"description":"The sigmoid normalized output values with the same shape as input tensor.","name":"output"}],"support_level":"default"}},{"name":"GRUUnit","schema":{"attributes":[{"description":"Bool to determine if hidden state is zeroes or passed along for timesteps past the given sequence_length.","name":"drop_states","option":"optional"},{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":"\nGRUUnit computes the activations of a standard GRU,\nin a sequence-length aware fashion.\n\nConcretely, given the (fused) inputs X (TxNxD), the previous hidden\nstate (NxD), and the sequence lengths (N), computes the GRU\nactivations, avoiding computation if the input is invalid (as in, the\nvalue at X[t][n] >= seqLengths[n].\n\n","outputs":[{"description":"The new GRU hidden state calculated by this op.","name":"hidden"}],"support_level":"default"}},{"name":"SortedSegmentSum","schema":{"description":"\nApplies 'Sum' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentSum that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sqrt","schema":{"description":"\nPerforms element-wise square-root ($\\sqrt{x}$) of input tensor $X$.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sqrt_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sqrt\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[8. 3. 3.]\n [4. 0. 0.]\n [1. 2. 5.]]\nY:\n[[2.8284268 1.7320508 1.7320508 ]\n [1.9999999 0. 0. ]\n [0.99999994 1.4142134 2.236068 ]]\n\n```\n\n
\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"TTLinearGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseFtrl","schema":{"description":null,"support_level":"default"}},{"name":"LambdaRankNdcgGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseNormalize","schema":{"attributes":[{"description":"A bool variable to control whether to use max norm or constant norm. When use_max_norm = false, constant norm is used so that all the embedding vectors are scaled to have a L2 norm equals to A (see blow argument norm=A). If use_max_norm = true, max norm is used so that embedding is scaled so that its l2 norm is no larger than A. If an embedding's norm is less than A originally, the embedding is left unchanged. The default is True.","name":"use_max_norm","option":"optional"},{"description":"L2 norm of the embedding. The default is 1.0.","name":"norm","option":"optional"}],"description":"\nGiven a sparse matrix, apply max_norm or constant_norm sparse regularization.\n","inputs":[{"description":"Parameters to be normalized","name":"param"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed (optional - not used, this argument is for backwards compatibility)","name":"grad"}],"outputs":[{"description":"Normalized parameters","name":"output_param"}],"support_level":"default"}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.01,"description":"Coefficient of leakage.","name":"alpha","option":"optional","type":"float32"}],"description":"\nThe *LeakyRelu* op takes one input tensor $X$ and an argument $alpha$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise leaky relu operation, defined as\n\n$$y=LeakyRelu(x) =\\begin{cases}\\alpha x & x < 0\\\\x & otherwise\\end{cases}$$\n\nThe default value of *alpha* is 0.01.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/leaky_relu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/leaky_relu_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LeakyRelu\",\n [\"X\"],\n [\"Y\"],\n alpha=0.01\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.91060215 0.09374836 2.1429708 ]\n [-0.748983 0.19164062 -1.5130422 ]\n [-0.29539835 -0.8530696 0.7673204 ]]\n\nY:\n [[-0.00910602 0.09374836 2.1429708 ]\n [-0.00748983 0.19164062 -0.01513042]\n [-0.00295398 -0.0085307 0.7673204 ]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"Output tensor, calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"AddGradient","schema":{"description":null,"support_level":"default"}},{"name":"LeakyReluGradient","schema":{"attributes":[{"description":"Coefficient of leakage","name":"alpha","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ReadRandomBatch","schema":{"attributes":[{"description":"Number of top-level entries to read.","name":"batch_size","option":"optional"},{"description":"(bool) Repeat the dataset indefinitely","name":"loop_over","option":"optional"}],"description":"\nRead the next batch of examples out of the given cursor,\nidx blob, offset matrix and data blobs.\n\nInput(0) is a blob pointing to a TreeCursor,\nInput(1) is a blob pointing to the shuffled idx\nInput(2) is a blob pointing to the offset matrix and\n[Input(3),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nReadRandomBatch is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"idx with a shuffled order.","name":"idx"},{"description":"offset matrix containing length offset info.","name":"offsetsmat"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing the next batch for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"HalfToFloat","schema":{"description":null,"support_level":"default"}},{"name":"ReduceScatter","schema":{"description":"\nDoes reduce-scatter operation among the nodes. Currently only Sum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be reduce-scattered.","name":"X"}],"outputs":[{"description":"The reduced tensor, scattered on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"SeluGradient","schema":{"attributes":[{"description":"(float) default to 1.6732~; affects the activation function itself.This should go with the weight initialization in the paper. See https://arxiv.org/abs/1706.02515","name":"alpha","option":"optional"},{"description":"(float) default to 1.0507~; affects the activation function itself.","name":"scale","option":"optional"}],"description":"\nSeluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the selu function.\n","inputs":[{"description":"input tensor","name":"Y"},{"description":"input tensor","name":"dY"}],"support_level":"default"}},{"name":"LengthsToShape","schema":{"description":"\nThis operator takes a list of $N$ equal integers as input which represent the lengths of $N$ vectors. The output is the calculated shape of the matrix if the $N$ integers were combined into a single matrix.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsToShape\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([2,2,2,2,2,2,2,2,2,2])\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.int32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [2 2 2 2 2 2 2 2 2 2]\nY:\n [10 2]\n\n```\n\n
\n\n ","inputs":[{"description":"List, of length $N$, of equal integers representing the lengths of several vectors.","name":"X"}],"outputs":[{"description":"Vector of length 2 describing the dimensions of the data if the $N$ vectors from the input were combined to a single matrix.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResetCounter","schema":{"attributes":[{"default":0,"description":"Resets counter to this value, must be >= 0.","name":"init_count","option":"optional","type":"int64"}],"description":"\nResets a count-down counter with initial value specified by the `init_count`\nargument.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* [OPTIONAL] count value BEFORE this operation.","name":"previous_value"}],"support_level":"default"}},{"name":"NormalizeGradient","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SparseMomentumSGDUpdate","schema":{"attributes":[{"description":"Momentum hyperparameter.","name":"momentum","option":"optional"},{"description":"(boolean) Whether to use Nesterov Accelerated Gradient.","name":"nesterov","option":"optional"}],"description":"\n\nPerforms a momentum SGD update analogous to MomentumSGDUpdate, but using a\nGradientSlice and indices into the full param and momentum tables. Both param\nand momentum should be in-place (corresponding inputs and outputs should be the\nsame blobs).\n\n\n\n","inputs":[{"description":"GradientSlice with gradients for updated indices.","name":"grad"},{"description":"Momentum blob, same shape as param.","name":"moment"},{"description":"Learning rate.","name":"lr"},{"description":"Full parameter blob.","name":"param"},{"description":"Indices (in first dimension of param) where updates are performed.","name":"indices"}],"outputs":[{"description":"Adjusted gradient.","name":"output_grad"},{"description":"Updated momentum.","name":"output_moment"},{"description":"Updated parameter","name":"output_param"}],"support_level":"default"}},{"name":"AffineChannelGradient","schema":{"description":null,"support_level":"default"}},{"name":"ColwiseMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosGradient","schema":{"description":null,"support_level":"default"}},{"name":"Scatter","schema":{"attributes":[{"default":1,"description":"Which dimension to scatter on.","name":"axis","option":"optional","type":"int64"}],"description":"\nUpdate values of the tensor by overriding current value specified by indices.\n\nWrites all values from the tensor UPDATES into DATA at the indices specified in the INDICES tensor.\nFor each value in DATA, its output index is specified by its index in UPDATES and by the corresponding value in INDICES for the specified axis.\n\nFor a 3-D tensor, DATA is updated as:\n\nDATA[INDICES[i][j][k]][j][k] = UPDATES[i][j][k] # if axis == 0\nDATA[i][INDICES[i][j][k]][k] = UPDATES[i][j][k] # if axis == 1\nDATA[i][j][INDICES[i][j][k]] = UPDATES[i][j][k] # if axis == 2\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"DATA"},{"description":"1-D list of indices on the first dimensionof X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"UPDATES"}],"outputs":[{"description":"The updated output.","name":"OUTPUT"}],"support_level":"default"}},{"name":"MapToKeyValue","schema":{"description":"Convert a map blob into key and value blob pairs","inputs":[{"description":"Blob reference to the map","name":"map blob"}],"outputs":[{"description":"Blob reference to the key","name":"key blob"},{"description":"Blob reference to the value","name":"value blob"}],"support_level":"default"}},{"name":"StringStartsWith","schema":{"attributes":[{"description":"The prefix to check input strings against.","name":"prefix","option":"optional"}],"description":"\nPerforms the starts-with check on each string in the input tensor.\nReturns tensor of boolean of the same dimension of input.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of bools of same shape as input.","name":"bools"}],"support_level":"default"}},{"name":"IndexStore","schema":{"description":"\nStores the keys of this index in a 1-D tensor. Since element 0 is reserved\nfor unknowns, the first element of the output tensor will be element of index 1.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"1-D tensor with elements starting with index 1.","name":"items"}],"support_level":"default"}},{"name":"Im2Col","schema":{"description":"The Im2Col operator from Matlab.","inputs":[{"description":"4-tensor in NCHW or NHWC.","name":"X"}],"outputs":[{"description":"4-tensor. For NCHW: N x (C x kH x kW) x outH x outW.For NHWC: N x outH x outW x (kH x kW x C","name":"Y"}],"support_level":"default"}},{"name":"FCTransposedGradient","schema":{"description":null,"support_level":"default"}},{"name":"AddPadding","schema":{"attributes":[{"description":"Number of copies of padding to add around each range.","name":"padding_width","option":"optional","type":"int64"},{"description":"[OPTIONAL] Specifies a different end-padding width. If this is not set, will use same as `padding_width`.","name":"end_padding_width","option":"optional","type":"int64"}],"description":"\nGiven a partitioned tensor $T$, where the partitions are\ndefined as ranges on its outer-most (slowest varying) dimension $N$,\nreturn a tensor $T<(N + 2 * padding\\_width), D_1, ..., D_n>$ with paddings\nadded to the start and end of each range.\n\nOptionally, different paddings can be provided for beginning and end.\nPaddings provided must be a tensor $T$. If no padding is\nprovided, add zero padding. If no lengths vector is provided, add padding\nonly once, at the start and end of data.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sequence_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AddPadding\",\n [\"X\", \"lengths\"],\n [\"Y\", \"lengths_out\"],\n padding_width=1\n\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,2,2).astype(np.float32)))\nworkspace.FeedBlob(\"lengths\", np.array([3]).astype(np.int32))\n\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"lengths_out:\", workspace.FetchBlob(\"lengths_out\"))\n```\n\n**Result**\n\n```\nX: [[[0.2531572 0.4588472 ]\n [0.45140603 0.61161053]]\n\n [[0.92500854 0.8045306 ]\n [0.03356671 0.30233648]]\n\n [[0.4660227 0.6287745 ]\n [0.79372746 0.08609265]]]\nY: [[[0. 0. ]\n [0. 0. ]]\n\n [[0.2531572 0.4588472 ]\n [0.45140603 0.61161053]]\n\n [[0.92500854 0.8045306 ]\n [0.03356671 0.30233648]]\n\n [[0.4660227 0.6287745 ]\n [0.79372746 0.08609265]]\n\n [[0. 0. ]\n [0. 0. ]]]\nlengths_out: [5]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input data ($T$).","name":"data_in"},{"description":"*(type: Tensor``)* Number of elements in each range. sum(lengths) = N.","name":"lengths"},{"description":"*(type: Tensor``)* [OPTIONAL] Padding data for range start ($T$).","name":"start_padding"},{"description":"*(type: Tensor``)* [OPTIONAL] Padding for range end. If not provided, `start_padding` is used ($T$).","name":"end_padding"}],"outputs":[{"description":"*(type: Tensor)* Padded data tensor ($T$).","name":"data_out"},{"description":"*(type: Tensor``)* [OPTIONAL] Lengths for each padded range.","name":"lengths_out"}],"support_level":"default"}},{"name":"Int8Reshape","schema":{"attributes":[{"description":"New shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nReshape the input tensor similar to numpy.reshape.\n\nIt takes a tensor as input and an optional tensor specifying the new shape.\nWhen the second input is absent, an extra argument `shape` must be specified.\nIt outputs the reshaped tensor as well as the original shape.\n\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is going to be copied\nfrom the input tensor.\n","inputs":[{"description":"An input tensor.","name":"data"},{"description":"New shape.","name":"new_shape"}],"outputs":[{"description":"Reshaped data.","name":"reshaped"},{"description":"Original shape.","name":"old_shape"}],"support_level":"default"}},{"name":"Where","schema":{"description":"\nOperator Where takes three input data (Tensor, Tensor, Tensor) and\nproduces one output data (Tensor) where z = c ? x : y is applied elementwise.\n","inputs":[{"description":"input tensor containing booleans","name":"C"},{"description":"input tensor","name":"X"},{"description":"input tensor","name":"Y"}],"outputs":[{"description":"output tensor","name":"Z"}],"support_level":"default"}},{"name":"GetAllBlobNames","schema":{"attributes":[{"description":"(bool, default true) Whether to include blobs inherited from parent workspaces.","name":"include_shared","option":"optional"}],"description":"\nReturn a 1D tensor of strings containing the names\nof each blob in the active workspace.\n","outputs":[{"description":"1D tensor of strings containing blob names.","name":"blob_names"}],"support_level":"default"}},{"name":"FloatToFusedRandRowwiseQuantized","schema":{"attributes":[{"description":"How many bits to quantize per data (defaults to 8).","name":"bitwidth","option":"optional"},{"description":"random or not (True). False is set up for unittest.","name":"random","option":"optional"}],"description":"\nApplies row-wise stochastic/random quantization by determining the range of\neach row in the input matrix, and then quantize each element to one of two\nclosest discrete levels by randomly drawing Bernoulli distribution.\nThe method is extended from TernGrad [1],\nwhich randomly quantizes gradients to three levels to reduce communication in distributed training.\nThe format of each row (x) in the output matrix is [bitwidth][tail][min][max][data]:\nbitwidth[1 Byte]: bitwidth per data [1, 2, 4 or 8];\ntail[1 Byte]: the number of unused buckets [1-8] (One byte is split to 8/bitwidth buckets and each bucket stores one low-precision data in bitwidth bits);\nmin[4 Bytes]: the minimum floating value min(x);\nmax[4 Bytes]: the maximum floating value max(x);\ndata: quantized data.\nThe quantization is uniform with levels q = min + (max-min)/(2^bitwidth - 1)*[0:1:2^bitwidth].\nDuring stochastic/random quantization x'=Quantize(x), for q_j < x_i <= q_{j+1}, we draw quantization x'_i from Bernoulli distributions with\nP(x'_i = q_{j+1}) = (x_i - q_j)/(q_{j+1} - q_j), and\nP(x'_i = q_j) = (q_{j+1} - x_i)/(q_{j+1} - q_j) where x'_i is the quantized value of x_i.\n[1] proved E{x'_i}=x_i, which is an unbiased approximation. More details are in the paper.\nFor example, suppose targeted bitwidth = 2 and x = [0.3, -1.4, -0.6, 0.9, 1.0],\nthen tail = 3, min = -1.4, max = 1.0 and q = [-1.4, -0.6, 0.2, 1.0].\nx_1 = 0.3 will be quantized to x'_1 = 0.2 with probability 7/8 and to x'_1 = 1.0 with probability 1/8.\nThe storage format of quantized data is: [x'_1|x'_3|x'_5|xxx]-[x'_2|x'_4|xxx|xxx].\nIn general, a input row is split to multiple segments. One segment is a continuous subarray of the row,\nand its length is the number of bytes storing quantized data in the output matrix.\nThe b-th bucket of the i-th byte stores the i-th data of the b-th segment of input row.\n\n[1] Wen, Wei, Cong Xu, Feng Yan, Chunpeng Wu, Yandan Wang, Yiran Chen, and Hai Li.\n\"Terngrad: Ternary gradients to reduce communication in distributed deep learning.\"\nIn Advances in Neural Information Processing Systems, pp. 1508-1518. 2017.\n\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused bitwidth, tail, min, max and quantized data","name":"output"}],"support_level":"default"}},{"name":"PackRNNSequence","schema":{"description":"\nPack values based on the length blob. Each number from length blob represents\nthe corresponding values that need to be packed. The dimension for each pack\nis the same as the maximum number from the length blob (padding with zero is\nimplemented for smaller length value). The overall output dimension is:\nT * N * D, where T is the max number of lengths, N is the size of lengths,\nand D is the dimension of each feature value. The following example shows\nthe input and output of this operator:\n\n\nGiven:\n values = [v1, v2, v3, v4, v5, v6, v7, v8]\n lengths = [2, 3, 1, 2];\n\n\nOutput:\n output = [\n [v1, v3, v6, v7],\n [v2, v4, 0, v8],\n [0, v5, 0, 0 ],\n ]\n\n\nOne application for this operator is the transfer data into the format that is\nused for RNN models. Note that the gradient operator of PackRNNSequence is\nUnpackRNNSequence.\n","inputs":[{"description":"Data tensor, contains a sequence of features","name":"values"},{"description":"lengths with each number representing the pack size.","name":"lengths"}],"outputs":[{"description":"Output tensor after packing","name":"output"}],"support_level":"default"}},{"name":"PadEmptySamples","schema":{"description":"\nPad empty field given lengths and index features,\n\nInput(0) is a blob pointing to the lengths of samples in one batch,\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the features.\n\nPadEmptySamples is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the lengths.","name":"lengths"}],"outputs":[{"description":"Tensor containing lengths with empty sample padded.","name":"out_lengths"}],"support_level":"default"}},{"name":"PadImage","schema":{"description":"\nPadImage pads values around the boundary of an image according to the pad\nvalues and stride sizes defined by the ConvPoolOpBase operator.\n ","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case. ","name":"X"}],"outputs":[{"description":"Output data tensor from padding the H and W dimensions on the tensor. Dimensions will vary based on various pad and stride sizes.","name":"Y"}],"support_level":"default"}},{"name":"Glu","schema":{"description":"\nApplies gated linear unit to the input Tensor X. The output Y is half the size\nof the input X, so if the shape of X is [d1, d2, ..., N] shape of Y will be\n[d1, d2, ..., dn/2] and Y(:dn-1, i) = GLU(X(:dn-1, i), X(:dn-1, i+N/2)) =\nX(dn-1, i) * sigmoid(X(dn-1, i+N/2))\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"Shape","schema":{"attributes":[{"description":"Array of interested axes.If given, this operator only returns the dimensions of the given axes.Otherwise, the operator returns the dimensions of all axes.","name":"axes","option":"optional","type":"int64[]"}],"description":"\nProduce a 1D int64 tensor with the shape of the input tensor.\nIf called with an optional argument `axes`, the result will only\ncontain the dimensions of specified axes.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/shape_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Shape\",\n [\"X\"],\n [\"shape\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(2,3))))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"shape:\", workspace.FetchBlob(\"shape\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[3 2 5]\n [5 7 3]]\nshape: [2 3]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Output tensor containing shape of input tensor.","name":"shape"}],"support_level":"default"}},{"name":"ReservoirSampling","schema":{"attributes":[{"description":"The number of random samples to append for each positive samples","name":"num_to_collect","option":"optional"}],"description":"\nCollect `DATA` tensor into `RESERVOIR` of size `num_to_collect`. `DATA` is\nassumed to be a batch.\n\nIn case where 'objects' may be repeated in data and you only want at most one\ninstance of each 'object' in the reservoir, `OBJECT_ID` can be given for\ndeduplication. If `OBJECT_ID` is given, then you also need to supply additional\nbook-keeping tensors. See input blob documentation for details.\n\nThis operator is thread-safe.\n","inputs":[{"description":"The reservoir; should be initialized to empty tensor","name":"RESERVOIR"},{"description":"Number of examples seen so far; should be initialized to 0","name":"NUM_VISITED"},{"description":"Tensor to collect from. The first dimension is assumed to be batch size. If the object to be collected is represented by multiple tensors, use `PackRecords` to pack them into single tensor.","name":"DATA"},{"description":"Mutex to prevent data race","name":"MUTEX"},{"description":"(Optional, int64) If provided, used for deduplicating object in the reservoir","name":"OBJECT_ID"},{"description":"(Optional) Auxiliary bookkeeping map. This should be created from `CreateMap` with keys of type int64 and values of type int32","name":"OBJECT_TO_POS_MAP_IN"},{"description":"(Optional) Tensor of type int64 used for bookkeeping in deduplication","name":"POS_TO_OBJECT_IN"}],"outputs":[{"description":"Same as the input","name":"RESERVOIR"},{"description":"Same as the input","name":"NUM_VISITED"},{"description":"(Optional) Same as the input","name":"OBJECT_TO_POS_MAP"},{"description":"(Optional) Same as the input","name":"POS_TO_OBJECT"}],"support_level":"default"}},{"name":"BatchBoxCox","schema":{"description":"\nInput `data` is a N * D matrix. Apply box-cox transform for each column.\n`lambda1` and `lambda2` is of size D that defines the hyper-parameters for\nthe transform of each column `x` of the input `data`:\n\n ln(x + lambda2), if lambda1 == 0\n ((x + lambda2)^lambda1 - 1)/lambda1, if lambda1 != 0\n\n","inputs":[{"description":"input float or double N * D matrix","name":"data"},{"description":"tensor of size D with the same type as data","name":"lambda1"},{"description":"tensor of size D with the same type as data","name":"lambda2"}],"outputs":[{"description":"output matrix that applied box-cox transform","name":"output"}],"support_level":"default"}},{"name":"Clip","schema":{"attributes":[{"description":"Minimum value, under which element is replaced by min (default=*numeric_limits::lowest()*).","name":"min","option":"optional","type":"float32"},{"description":"Maximum value, under which element is replaced by max (default=*numeric_limits::max()*).","name":"max","option":"optional","type":"float32"}],"description":"\nThis operator limits the given input within an interval. The interval is\nspecified by the `min` and `max` arguments. They default to\n*numeric_limits::lowest()* and *numeric_limits::max()* respectively. The\nclipping operation can be done in an in-place fashion by using the same output\nblob as the input blob.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/clip_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Clip\",\n [\"X\"],\n [\"Y\"],\n min=20.0,\n max=60.0\n\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(5,5))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\nX: [[45. 16. 59. 99. 48.]\n [12. 44. 46. 82. 28.]\n [ 1. 91. 18. 9. 71.]\n [24. 37. 61. 12. 81.]\n [36. 38. 30. 84. 40.]]\nY: [[45. 20. 59. 60. 48.]\n [20. 44. 46. 60. 28.]\n [20. 60. 20. 20. 60.]\n [24. 37. 60. 20. 60.]\n [36. 38. 30. 60. 40.]]\n```\n\n
\n\n","inputs":[{"description":"*(Tensor``)* Input tensor within range [*numeric_limits::lowest()*, *numeric_limits::max()*].","name":"X"}],"outputs":[{"description":"*(Tensor``)* Output tensor clipped within range [`min`, `max`].","name":"Y"}],"support_level":"default"}},{"name":"FeedBlob","schema":{"attributes":[{"description":"(string) if provided then we will use this string as the value for theprovided output tensor","name":"value","option":"optional"}],"description":"\nFeedBlobs the content of the blobs. The input and output blobs should be\none-to-one inplace.","support_level":"default"}},{"name":"CreateBlobsQueue","schema":{"description":null,"support_level":"default"}},{"name":"BisectPercentile","schema":{"attributes":[{"description":"1D tensor, which is the concatenation of all sorted raw feature values for all features.","name":"percentile_raw","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_mapping and percentile_raw such that each element in percentile_mapping corresponds to the percentile value of the corresponding raw feature value.","name":"percentile_mapping","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile lower bound of the corresponding raw feature value.","name":"percentile_lower","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile upper bound of the corresponding raw feature value.","name":"percentile_upper","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile upper bound of the corresponding raw feature value.","name":"lengths","option":"optional"}],"description":"\n This operator is to map raw feature values into the percentile\n representations based on Bisection for more than one feature.\n\n The input is the bath of input feature values, with the size of (batch_size,\n num_feature), where num_feature = F (F >= 1).\n\n For each feature, we also need additional information regarding the feature\n value distribution.\n There are several vectors to keep data to percentile mappping information\n as arguments (context):\n 1. feature raw values (R)\n 2. feature percentile mapping (P)\n 3. feature percentile lower bound (L)\n 4. feature percentile upper bound (U)\n\n A toy example:\n Suppose the sampled data distribution is as follows:\n 1, 1, 2, 2, 2, 2, 2, 2, 3, 4\n We have the mapping vectors as follows:\n R = [1, 2, 3, 4]\n P = [0.15, 0.55, 0.9, 1.0]\n L = [0.1, 0.3, 0.9, 1.0]\n U = [0.2, 0.8, 0.9, 1.0]\n Where P is computed as (L + U) / 2.\n\n For a given list of feature values, X = [x_0, x_1, ..., x_i, ...], for each\n feature value (x_i) we first apply bisection to find the right index (t),\n such that R[t] <= x_i < R[t+1].\n If x_i = R[t], P[t] is returned;\n otherwise, the interpolation is apply by (R[t], R[t+1]) and (U[t] and L[t]).\n\n As there are F features (F >= 1), we concate all the R_f, P_f, L_f, and\n U_f for each feature f and use an additional input length to keep track of\n the number of points for each set of raw feature value to percentile mapping.\n For example, there are two features:\n R_1 =[0.1, 0.4, 0.5];\n R_2 = [0.3, 1.2];\n We will build R = [0.1, 0.4, 0.5, 0.3, 1.2]; besides, we have\n lengths = [3, 2]\n to indicate the boundaries of the percentile information.\n\n","inputs":[{"description":"Input 2D tensor of floats of size (N, D), where N is the batch size and D is the feature dimension.","name":"raw_values"}],"outputs":[{"description":"2D tensor of output with the same dimensions as the input raw_values.","name":"percentile"}],"support_level":"default"}},{"name":"ReversePackedSegs","schema":{"description":"\nReverse segments in a 3-D tensor (lengths, segments, embeddings,), leaving\npaddings unchanged. This operator is used to reverse input of a recurrent neural\nnetwork to make it a BRNN.\n ","inputs":[{"description":"a 3-D (lengths, segments, embeddings,) tensor.","name":"data"},{"description":"length of each segment.","name":"lengths"}],"outputs":[{"description":"a (lengths, segments, embeddings,) tensor with each segment reversedand paddings unchanged.","name":"reversed data"}],"support_level":"default"}},{"name":"CreateScope","schema":{"description":"\n'CreateScope' operator initializes and outputs empty scope that is used\nby Do operator to store local blobs\n ","support_level":"default"}},{"name":"SpatialSoftmaxWithLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"StoreAdd","schema":{"attributes":[{"description":"key of the counter (required)","name":"blob_name","option":"optional"},{"description":"value that is added (optional, default: 1)","name":"add_value","option":"optional"}],"description":"\nAdd a value to a remote counter. If the key is not set, the store\ninitializes it to 0 and then performs the add operation. The operation\nreturns the resulting counter value.\n","inputs":[{"description":"unique_ptr","name":"handler"}],"outputs":[{"description":"the current value of the counter","name":"value"}],"support_level":"default"}},{"name":"MergeSingleListFeatureTensorsGradient","schema":{"description":"Explode multi-feature tensors with list features into single-feature tensors.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".presence","name":"in1_presence"},{"description":".values.values_grad","name":"out_values_values"}],"outputs":[{"description":".values_grad","name":"out1_values"}],"support_level":"default"}},{"name":"DistributeFpnProposals","schema":{"attributes":[{"description":"(int) ROI_CANONICAL_SCALE","name":"roi_canonical_scale","option":"optional"},{"description":"(int) ROI_CANONICAL_LEVEL","name":"roi_canonical_level","option":"optional"},{"description":"(int) ROI_MAX_LEVEL","name":"roi_max_level","option":"optional"},{"description":"(int) ROI_MIN_LEVEL","name":"roi_min_level","option":"optional"}],"description":"\n...\n","inputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"}],"outputs":[{"description":"RPN proposals for ROI level 2, format (image_index, x1, y1, x2, y2)","name":"rois_fpn2"},{"description":"RPN proposals for ROI level 3, format (image_index, x1, y1, x2, y2)","name":"rois_fpn3"},{"description":"RPN proposals for ROI level 4, format (image_index, x1, y1, x2, y2)","name":"rois_fpn4"},{"description":"RPN proposals for ROI level 5, format (image_index, x1, y1, x2, y2)","name":"rois_fpn5"},{"description":"Permutation on the concatenation of all rois_fpni, i=min...max, such that when applied the RPN RoIs are restored to their original order in the input blobs.","name":"rois_idx_restore"}],"support_level":"default"}},{"name":"CollectRpnProposals","schema":{"attributes":[{"description":"(int) RPN_MAX_LEVEL","name":"rpn_max_level","option":"optional"},{"description":"(int) RPN_MIN_LEVEL","name":"rpn_min_level","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"rpn_post_nms_topN","option":"optional"}],"description":"\n...\n","inputs":[{"description":"RPN proposals for FPN level 2, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn2"},{"description":"RPN proposals for FPN level 3, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn3"},{"description":"RPN proposals for FPN level 4, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn4"},{"description":"RPN proposals for FPN level 5, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn5"},{"description":"RPN proposals for FPN level 6, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn6"},{"description":"RPN objectness probabilities for FPN level 2. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn2"},{"description":"RPN objectness probabilities for FPN level 3. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn3"},{"description":"RPN objectness probabilities for FPN level 4. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn4"},{"description":"RPN objectness probabilities for FPN level 5. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn5"},{"description":"RPN objectness probabilities for FPN level 6. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn6"}],"outputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"}],"support_level":"default"}},{"name":"LengthsMaxWithMainInputAndForwardOutputGradient","schema":{"description":null,"support_level":"default"}},{"name":"MomentumSGDUpdate","schema":{"description":"\n\nPerforms a momentum SGD update for an input gradient and momentum\nparameters. Concretely, given inputs (grad, m, lr, param) and arguments\n(momentum, nesterov), computes:\n\n if not nesterov:\n adjusted_gradient = lr * grad + momentum * m\n param = param - adjusted_gradient\n return (adjusted_gradient, adjusted_gradient, param)\n else:\n m_new = momentum * m + lr * grad\n param = param - ((1 + momentum) * m_new - momentum * m),\n return ((1 + momentum) * m_new - momentum * m, m_new, param)\n\nOutput is (grad, momentum, parameter).\n\nNote the difference to MomentumSGD, which returns a new gradient\nbut does not perform the parameter update.\n\n","support_level":"default"}},{"name":"SparseLengthsIndicesInGradientWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Pow","schema":{"attributes":[{"description":"The exponent of the power function. Do not use if setting exponent via input.","name":"exponent","option":"optional"},{"default":-1,"description":"","name":"axis","option":"optional","type":"int64"},{"default":false,"description":"","name":"broadcast","option":"optional","type":"boolean"}],"description":"\nThe *Pow* op takes an input data tensor $X$ and an exponent parameter *exponent*, which can be a scalar or another tensor. As output, it produces a single output data tensor $Y$, where the function $f(x) = x^{exponent}$ has been applied to $X$ elementwise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Pow\",\n [\"X\", \"exponent\"],\n [\"Y\"],\n broadcast=1\n)\n\nworkspace.FeedBlob(\"X\", np.array([1,2,3,4,5,6]).astype(np.float32))\nprint(\"X: \", workspace.FetchBlob(\"X\"))\n\nworkspace.FeedBlob(\"exponent\", np.array([2]).astype(np.float32))\nprint(\"exponent: \", workspace.FetchBlob(\"exponent\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y: \", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [1. 2. 3. 4. 5. 6.]\nexponent: [2.]\nY: [ 1. 4. 9. 16. 25. 36.]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob to be operated on.","name":"X"},{"description":"Exponent blob containing the exponent(s) for calculation. Do not use if setting exponent via argument.","name":"exponent"}],"outputs":[{"description":"Output data blob with the same shape as the input.","name":"Y"}],"support_level":"default"}},{"name":"Cube","schema":{"description":null,"inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cube of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool2D","schema":{"description":"AveragePool2D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"BitwiseAnd","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_and` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"Mean","schema":{"description":"\nElement-wise mean of an arbitrary number of input tensors. This operation can be\nperformed in-place, by using the first input blob as the output blob. All inputs\nmust have the same shape and data type, and the output will have the same shape\nas the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/mean_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mean\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Mean:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.6035237 0.5305746 0.6298913 ]\n [0.9169737 0.01280353 0.16286302]\n [0.6017664 0.9946255 0.05128575]]\nY:\n[[0.07544111 0.45371833 0.08460239]\n [0.9708728 0.7422064 0.7933344 ]\n [0.97671497 0.3411384 0.73818344]]\nZ:\n[[0.08837954 0.90187573 0.46734726]\n [0.6308827 0.8719029 0.39888734]\n [0.90059936 0.92883426 0.5695987 ]]\nMean:\n[[0.25578147 0.6287229 0.39394698]\n [0.8395764 0.5423043 0.45169494]\n [0.8263602 0.75486606 0.45302266]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with the same dimensions as inputs. Contains the mean values of the input tensors calculated element-wise.","name":"M"}],"support_level":"default"}},{"name":"And","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **and** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"And\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n [[ True False False]\n [False True False]\n [False False True]]\nB:\n [[ True False True]\n [False False False]\n [False False False]]\nC:\n [[ True False False]\n [False False False]\n [False False False]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"GivenTensorFill","schema":{"attributes":[{"description":"The value of the elements to go in the *output* tensor.","name":"values"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"},{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with the data specified by the *value* and *dtype* arguments. The output tensor shape is specified by the *shape* argument. Beware, when using this argument *value* should have a value for every element of the *output*, as missing values will not be initialized automatically. If *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: Do not set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/given_tensor_fill_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/given_tensor_fill_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GivenTensorFill\",\n [],\n [\"out\"],\n values=[1., 2., 3.],\n shape=[3],\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [1. 2. 3.]\n\n```\n\n
\n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor with desired dimension filled with specified data. If the shape argument is set, this is the shape specified, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"GeluGradient","schema":{"description":null,"support_level":"default"}},{"name":"LayerNorm","schema":{"attributes":[{"description":"(int) default to 1; Describes axis of the inputs. Defaults to one because the 0th axis most likely describes the batch size","name":"axis","option":"optional"},{"description":"(float) default to 0.001. Small value to be added to the stdev when dividing out by that value. This prevents division by zero.","name":"epsilon","option":"optional"},{"description":"(bool) default to False; If true, this op will do affine transformation after normalization.","name":"elementwise_affine","option":"optional"}],"description":"\nComputes layer normalization as described in https://arxiv.org/pdf/1607.06450.pdf.\nGiven an input vector x \\in [a_0, a_1, ...,a_{k-1}, a_k, ..., a_{n-1}],\nthis op treats dimensions a_k through a_{n-1} as feature vectors. For each\nfeature vector, the op contains the mean and standard deviation. Then,\nit returns the normalized values (with respect to the feature vector).\n\nNote that this op does not contain the scale an bias terms described in the\npaper. Simply follow this op with an FC op to add those. Concretely, this op\nimplements:\n\nh = \\frac{1}{\\sigma}(a - \\mu)\nwhere \\mu = \\frac{1}{H}\\sum_{i=1}^{H} a_i\nand \\sigma = \\sqrt{\\frac{1}{H}\\sum_{i=1}^{H}(a_i - \\mu)^2}\nwhere H is the number of hidden units (i.e. product of dimensions from 'axis'\nto the end.)\n","inputs":[{"description":"Input tensor which layer normalization will be applied to","name":"input"},{"description":"scale tensor for elementwise_affine, the shape should be the same as the dimensions of X begin from axis","name":"gamma"},{"description":"bias tensor for elementwise_affine, the shape should be the same as the dimensions of X begin from axis","name":"beta"}],"outputs":[{"description":"Normalized values","name":"output"},{"description":"Mean values for each feature vector","name":"mean"},{"description":"Standard deviations for each feature vector","name":"stddev"}],"support_level":"default"}},{"name":"SortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentWeightedSum that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"BernoulliJSD","schema":{"description":"\nComputes the Jensen-Shannon divergence (JSD) between two Bernoulli distributions\nwhere each is parametrized by a single probability.\n","inputs":[{"description":"array of probabilities for target","name":"T"}],"outputs":[{"description":"array of JSD losses","name":"L"}],"support_level":"default"}},{"name":"Cosh","schema":{"description":"\nCalculates the hyperbolic cosine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cosh_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cosh\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.66423494 0.32074615 0.81523746 0.90423071 0.39275789]\nY: [1.22883528 1.05188156 1.35112322 1.43744212 1.07812598]\n\n```\n\n
\n\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic cosine values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"ReduceFrontWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nReduces the input tensor along the first dimension of the input tensor by\napplying 'WeightedSum'. This op acts in a similar way to SortedSegmentWeightedSum and\nUnsortedSegmentWeightedSum but as if all input slices belong to a single segment.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"}],"outputs":[{"description":"Aggregated tensor","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"UnpackRNNSequence","schema":{"description":"\nThis is the reverse operator for PackRNNSequence. It maps the packed values\nback to sequence values based on the length blob. Each number from length blob\nrepresents the corresponding values that has been grouped. The dimension\nfor each pack is the same as the maximum number from the length blob (padding\nwith zero was implemented for smaller length value). The overall output\ndimension is: M * D, where M is the sum of lengths, and D is the dimension of\neach feature value. The following example shows the input and output of\nthis operator:\n\n\nGiven:\n values = [\n [v1, v3, v6, v7],\n [v2, v4, 0, v8],\n [0, v5, 0, 0 ],\n ]\n lengths = [2, 3, 1, 2]\n\n\nOutput:\n output = [v1, v2, v3, v4, v5, v6, v7, v8];\n\n\nOne application for this operator is the transfer data from the format of RNN\nback to sequence values. Note that the gradient operator of\nUnpackRNNSequence is PackRNNSequence.\n","inputs":[{"description":"Data tensor, contains the packed features","name":"values"},{"description":"lengths with each number representing the pack size.","name":"lengths"}],"outputs":[{"description":"Output tensor before packing","name":"output"}],"support_level":"default"}},{"name":"ScaleBlobs","schema":{"attributes":[{"description":"(float, default 1.0) the scale to apply.","name":"scale","option":"optional"}],"description":"\nScaleBlobs takes one or more input data (Tensor) and produces one\nor more output data (Tensor) whose value is the input data tensor\nscaled element-wise.\n","support_level":"default"}},{"name":"SafeEnqueueBlobs","schema":{"description":"\nEnqueue the blobs into queue. When the queue is closed and full, the output\nstatus will be set to true which can be used as exit criteria for execution\nstep.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"support_level":"default"}},{"name":"UnsortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Alias","schema":{"description":"\nMakes the output and the input share the same underlying storage.\n\nWARNING: in general, in caffe2's operator interface different tensors should\nhave different underlying storage, which is the assumption made by\ncomponents such as the dependency engine and memory optimization. Thus, in\nnormal situations you should not use the AliasOp, especially in a normal\nforward-backward pass.\n\nThe Alias op is provided so one can achieve true asynchrony, such as\nHogwild, in a graph. But make sure you understand all the implications\nsimilar to multi-thread computation before you use it explicitly.\n","inputs":[{"description":"Input tensor whose storage will be shared.","name":"input"}],"outputs":[{"description":"Tensor of same shape as input, sharing its storage.","name":"output"}],"support_level":"default"}},{"name":"ScatterWeightedSum","schema":{"description":"\nSimilar to WeightedSum, computes the weighted sum of several tensors, with\nthe difference that inputs are sliced tensors. The first tensor has to be\nin-place and only slices of it on the first dimension as indexed by INDICES\nwill be updated.\n\nNote: The op pretty much ignores the exact shapes of the input arguments and\ncares only about sizes. It's done for performance consideration to avoid\nunnecessary reshapes. Only first dimension of X_0 is important, let's call it\nN. If M is the total size of X_0 and K is the size of INDICES then X_i is\nassumed to be of shape K x (M / N) regardless of the real shape.\n\nNote: Each update in INDICES is applied independently which means that if\nduplicated elements are present in INDICES the corresponding slice of X_0\nwill be scaled multiple times. Manual collapsing of INDICES is required\nbeforehand if necessary.\n\nNote: Updates are applied sequentially by inputs which might have undesired\nconsequences if the input tensor is accessed concurrently by different op\n(e.g. when doing Hogwild). Other threads might see intermediate results even\non individual slice level, e.g. X_0 scaled by weight_0 but without any\nupdates applied.\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"X_0"},{"description":"Scalar weight for X_0, applied only to slices affected.","name":"Weight_0"},{"description":"1-D list of indices on the first dimension of X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"X_1"},{"description":"Scalar weight for X_1 update","name":"Weight_1"}],"outputs":[{"description":"Has to be exactly the same tensor as the input 0","name":"X_0"}],"support_level":"default"}},{"name":"Int8Flatten","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(Default to 1) Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output","name":"axis","option":"optional"}],"description":"\nFlattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn)\n","inputs":[{"description":"A Int8 tensor of rank >= axis.","name":"input"}],"outputs":[{"description":"A 2D Int8 tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output"}],"support_level":"default"}},{"name":"LRNGradient","schema":{"description":null,"support_level":"default"}},{"name":"MaxPool2D","schema":{"description":"MaxPool2D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Softplus","schema":{"description":"\nSoftplus takes one input data tensor $X$ and produces one output data tensor $Y,$ where the softplus function, $y = ln(e^x + 1)$, is applied to $X$ elementwise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softplus_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softplus_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softplus\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.5380011 0.65190786 0.55673236]\n [-0.16272168 0.5451048 0.30880353]\n [-0.76606876 -0.6238556 -0.40444514]]\n\nY:\n [[0.4598992 1.0713093 1.0097669 ]\n [0.61509246 1.0023911 0.8594219 ]\n [0.38174385 0.42909983 0.5112337 ]]\n\n```\n\n
\n\n","inputs":[{"description":"Input data blob to be operated on.","name":"X"}],"outputs":[{"description":"Output data blob with same shape as input.","name":"Y"}],"support_level":"default"}},{"name":"ReduceL2","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **L2 norm** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceL2\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[ 8. 0. 2. 5. 1.]\n [ 1. 3. 0. 4. 0.]\n [ 1. 3. 6. 7. 7.]\n [ 6. 9. 8. 4. 6.]\n [ 6. 1. 5. 7. 3.]]\n\n [[ 2. 4. 6. 2. 8.]\n [ 1. 1. 8. 0. 8.]\n [ 5. 9. 0. 3. 2.]\n [ 1. 7. 3. 7. 3.]\n [ 6. 8. 9. 8. 7.]]]]\n\nY:\n[[ 8.24621105 4. 6.3245554 5.38516474 8.06225777]\n [ 1.41421354 3.1622777 8. 4. 8. ]\n [ 5.09901953 9.48683262 6. 7.6157732 7.28010988]\n [ 6.08276272 11.40175438 8.54400349 8.06225777 6.70820379]\n [ 8.48528099 8.06225777 10.29563046 10.63014603 7.6157732 ]]\n\n```\n\n
\n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"WallClockTime","schema":{"description":"Time since epoch in nanoseconds.","outputs":[{"description":"The time in nanoseconds.","name":"time"}],"support_level":"default"}},{"name":"Cos","schema":{"description":"\nCalculates the cosine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cos_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cos\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.6816719 0.76771533 0.933932 0.01404487 0.11862425]\nY: [0.7765203 0.71949923 0.5946774 0.99990135 0.9929724 ]\n\n```\n\n
\n\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cosine of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool1D","schema":{"description":"AveragePool1D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Col2Im","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsPositionalWeightedSum","schema":{"description":"\nVariation of SparseLengthsWeightedSum operator, where, for each row,\nweights are accessed by indices [0..L-1], where L is the length of given row.\nThis is basically a fused operator of LengthsRangeFill + Gather +\nSparseWeightedSum\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of DATA","name":"WEIGHT"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Size","schema":{"description":"\nReturn a 1D tensor of type *int64* that contains the number of elements of the input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Size\",\n [\"X\"],\n [\"size\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"size:\", workspace.FetchBlob(\"size\"))\n\nworkspace.ResetWorkspace()\n\nworkspace.FeedBlob(\"X\", (np.random.rand(6,4)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"size:\", workspace.FetchBlob(\"size\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[3 7 0]\n [0 1 6]\n [5 0 8]]\nsize: 9\nX:\n[[0.92017884 0.32115368 0.68692035 0.64135016]\n [0.8723328 0.77830265 0.80688656 0.25524236]\n [0.37970216 0.76407047 0.85689564 0.30692883]\n [0.69352573 0.42531502 0.16415212 0.59209324]\n [0.52684188 0.37094846 0.60670079 0.6489272 ]\n [0.94715906 0.34800557 0.61898769 0.28947359]]\nsize: 24\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor)* Input tensor to calculate number of elements.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* 1D tensor of type int64 that contains the number of elements in the input tensor *X*.","name":"size"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 32-bit float in the second to the last 4 bytes of each\nrow, followed by the bias as a 32-bit float in the next 4 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"NanCheck","schema":{"description":"Identity operator, but checks all values for nan or inf","inputs":[{"description":"Tensor to check for nan/inf","name":"tensor"}],"outputs":[{"description":"Tensor to copy input into if no NaNs or inf. Can be in-place","name":"output"}],"support_level":"default"}},{"name":"CbrtGradient","schema":{"description":null,"support_level":"default"}},{"name":"RowWiseSparseAdagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nGiven inputs (param, moment, indices, grad, lr), runs a modified sparse Adagrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_momwnr), where moment is a 1D tensor with length equal to the number of\nrows in param: shape(moment) == shape(param)[0]. Each element of moment is\napplied to an entire row of param, and the new moment is calculated by adding\nthe average squared sum of gradients across each row. Note that indices must\nalso be a 1D tensor indexing into the rows of param.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment_1"}],"support_level":"default"}},{"name":"GivenTensorDoubleFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"LengthsToRanges","schema":{"description":"\nGiven a vector of segment lengths, calculates offsets of each segment and packs\nthem next to the lengths. For the input vector of length N the output is a Nx2\nmatrix with (offset, lengths) packaged for each segment.\n\nFor example, `[1, 3, 0, 2]` transforms into `[[0, 1], [1, 3], [4, 0], [4, 2]]`.\n","inputs":[{"description":"1D tensor of int32 segment lengths.","name":"lengths"}],"outputs":[{"description":"2D tensor of shape len(lengths) X 2 and the same type as `lengths`","name":"ranges"}],"support_level":"default"}},{"name":"SparseSortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosineEmbeddingCriterion","schema":{"description":"\nCosineEmbeddingCriterion takes two inputs: the similarity value and\nthe label, and computes the elementwise criterion output as\n\n output = 1 - s, if y == 1\n max(0, s - margin), if y == -1\n","inputs":[{"description":"The cosine similarity as a 1-dim TensorCPU.","name":"S"},{"description":"The label as a 1-dim TensorCPU with int value of 1 or -1.","name":"Y"}],"outputs":[{"description":"The output loss with the same dimensionality as S.","name":"loss"}],"support_level":"default"}},{"name":"IsEmpty","schema":{"description":"\nThe *IsEmpty* op accepts a single input $tensor$, and produces a single boolean output $is\\_empty$. The output is *True* if and only if $tensor$ has size == 0.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"IsEmpty\",\n [\"tensor\"],\n [\"is_empty\"],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"tensor\", np.random.randn(2, 2).astype(np.float32))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"is_empty: \", workspace.FetchBlob(\"is_empty\"),\"\\n\")\n\n// Use an empty tensor\nworkspace.FeedBlob(\"tensor\", np.empty(0))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"is_empty: \", workspace.FetchBlob(\"is_empty\"))\n\n```\n\n**Result**\n\n```\n\ntensor:\n [[ 0.26018378 0.6778789 ]\n [-1.3097627 -0.40083608]]\nis_empty: False\n\ntensor:\n []\nis_empty: True\n\n```\n\n
\n\n","inputs":[{"description":"Input data tensor to check if empty.","name":"tensor"}],"outputs":[{"description":"Output scalar boolean tensor. True if input has size == 0.","name":"is_empty"}],"support_level":"default"}},{"name":"KeySplit","schema":{"description":null,"support_level":"default"}},{"name":"LC1D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 1D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"GenerateProposalsCPP","schema":{"description":null,"support_level":"default"}},{"name":"XavierFill","schema":{"attributes":[{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with values sampled from a uniform distribution with the range determined by the desired shape of the output. Rather, than specifying the range of values manually, the novelty of Xavier Fill is that it automatically scales the range of the distribution it draws from based on the size of the desired output tensor. For more information check out the paper [Understanding the difficulty of training deep feedforward neural networks](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf). The output tensor shape is specified by the *shape* argument. However, if *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: Do not set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"XavierFill\",\n [],\n [\"out\"],\n shape=[3,3],\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [[-0.8412168 0.33207083 -0.88418937]\n [ 0.43059897 -0.8340702 0.07781601]\n [ 0.93261135 -0.24542928 -0.3980782 ]]\n\n```\n\n
\n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor of random values drawn from an automatically scaled uniform distribution, based on the size of the output tensor. If the shape argument is set, this is the shape specified by the shape argument, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"QuantDecode","schema":{"description":"\nDecode inputs using codebook. This is a general LUT operator that returns\ntensors with values from codebook (input 0) based on given indices in\ncodes (input 1 ~ n).\n\n\nExample:\n\n\nInput:\n codebook = [1.5, 2.5, 3.5]\n codes_0 = [0, 1, 1, 2]\n codes_1 = [2, 0, 0]\n\n\nOutput:\n decoded_0 = [1.5, 2.5, 2.5, 3.5]\n decoded_1 = [3.5, 1.5, 1.5]\n","inputs":[{"description":"Codebook in 1d tensor (float)","name":"codebook"},{"description":"Encoded codes 0 (uint8/uint16/int32)","name":"codes_0"},{"description":"Encoded codes 1 if existed (uint8/uint16/int32)","name":"codes_1"},{"description":"Encoded codes n if existed (uint8/uint16/int32)","name":"codes_n"}],"outputs":[{"description":"Decoded tensor for codes_0 (float)","name":"decoded_0"},{"description":"Decoded tensor for codes_1 (float)","name":"decoded_1"},{"description":"Decoded tensor for codes_n (float)","name":"decoded_n"}],"support_level":"default"}},{"name":"ElementwiseLinearGradient","schema":{"description":null,"support_level":"default"}},{"name":"TimerGetAndEnd","schema":{"description":"\nQueries the current time of a timer in nanos, stops the timer publishing a CAFFE_EVENT.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\ntimerbegin_op = core.CreateOperator(\n \"TimerBegin\",\n [],\n [\"timer\"]\n)\n\ntimerget_op = core.CreateOperator(\n \"TimerGet\",\n [\"timer\"],\n [\"nanos\"]\n)\n\ntimerend_op = core.CreateOperator(\n \"TimerEnd\",\n [\"timer\"],\n []\n)\n\ntimergetandend_op = core.CreateOperator(\n \"TimerGetAndEnd\",\n [\"timer\"],\n [\"nanos\"]\n)\n\n// Test TimerBegin/TimerGet/TimerEnd\nworkspace.RunOperatorOnce(timerbegin_op)\nprint(\"timer:\", workspace.FetchBlob(\"timer\"))\nworkspace.RunOperatorOnce(timerget_op)\nprint(\"nanos:\", workspace.FetchBlob(\"nanos\"))\nworkspace.RunOperatorOnce(timerend_op)\n\n\n// Test TimerBegin/TimerGetAndEnd\nworkspace.RunOperatorOnce(timerbegin_op)\nprint(\"timer:\", workspace.FetchBlob(\"timer\"))\nworkspace.RunOperatorOnce(timergetandend_op)\nprint(\"nanos:\", workspace.FetchBlob(\"nanos\"))\n\n```\n\n**Result**\n\n```\n\ntimer: b'timer, a C++ native class of type caffe2::TimerInstance*.'\nnanos: 361140\ntimer: b'timer, a C++ native class of type caffe2::TimerInstance*.'\nnanos: [252250]\n\n```\n\n
\n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"outputs":[{"description":"(*Tensor``*): scalar tensor containing time in nanoseconds","name":"nanos"}],"support_level":"default"}},{"name":"DivGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"Do","schema":{"attributes":[{"description":"Subnet with blob bindings","name":"net","option":"optional"},{"description":"List of inner net blob names to bind to outer workspace","name":"inner_blobs","option":"optional"},{"description":"Indices of corresponding outer workspace blobs, in order: operator inputs, operator outputs (skipping workspace blobs)","name":"outer_blobs_idx","option":"optional"},{"description":"List of blobs from the forward Do operator workspace needed in backward pass, used in gradient Do operator","name":"saved_fwd_blobs","option":"optional"},{"description":"Whether to reuse workspace or create a new one in a given scope","name":"reuse_workspace","option":"optional"}],"description":"\n'Do' control operator, executes a subnet in a separate workspace.\nLast blobs in the input and output lists should be the same blob created with\nCreateScope op. Arguments 'inner_blobs' and 'outer_blobs_idx' provide a mapping\nbetween selected inner blob names and corresponding outer blob indices.\n ","support_level":"default"}},{"name":"DotProductWithPaddingGradient","schema":{"description":null,"support_level":"default"}},{"name":"UniqueUniformFill","schema":{"attributes":[{"description":"Minimum value, inclusive","name":"min","option":"optional"},{"description":"Maximum value, inclusive","name":"max","option":"optional"},{"description":"The data type for the elements of the output tensor.Strictly must be one of the types from DataType enum in TensorProto.This only supports INT32 and INT64 now. If not set, assume INT32","name":"dtype","option":"optional"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob. Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with uniform samples between min and max (inclusive).\nIf the second input is given, its elements will be excluded from uniform\nsampling. Using the second input will require you to provide shape via the first\ninput.\n","inputs":[{"description":"Input tensor to provide shape information","name":"input"},{"description":"(optional) Avoid elements in this tensor. Elements must be unique.","name":"avoid"}],"outputs":[{"description":"Output tensor of unique uniform samples","name":"output"}],"support_level":"default"}},{"name":"LongIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps int64 keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handler"}],"support_level":"default"}},{"name":"ComputeOffset","schema":{"description":"\nCompute the offsets matrix given cursor and data blobs. Need to be ran at\nbeginning or after reseting cursor\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nComputeOffset is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing offset info for this chunk.","name":"field_0"}],"support_level":"default"}},{"name":"ByteWeightDequant","schema":{"description":null,"support_level":"default"}},{"name":"CopyOnDeviceLike","schema":{"description":"Copy input tensor into output to the specific device.","inputs":[{"description":"The input tensor.","name":"input"},{"description":"Tensor, on which device the copy will be performed.","name":"dst"}],"outputs":[{"description":"Tensor that will contain a copy of the input.","name":"output"}],"support_level":"default"}},{"name":"BatchOneHot","schema":{"description":"\nInput is a matrix tensor. Its first dimension is the batch\nsize. Expand each column of it using one hot encoding. The `lengths` specifies\nthe size of each column after encoding, and the `values` is the dictionary value\nof one-hot encoding for each column. For example\n\n If data = [[2, 3], [4, 1], [2, 5]], lengths = [2, 3],\n and values = [2, 4, 1, 3, 5], then\n\n output = [[1, 0, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 1]]\n","inputs":[{"description":"input tensor matrix","name":"data"},{"description":"the size is the same as the width of the `data`","name":"lengths"},{"description":"one hot encoding dictionary values","name":"values"}],"outputs":[{"description":"output matrix that expands each input column with one hot encoding","name":"output"}],"support_level":"default"}},{"name":"DropoutGrad","schema":{"description":null,"support_level":"default"}},{"name":"MulGradient","schema":{"description":null,"support_level":"default"}},{"name":"MarginRankingCriterionGradient","schema":{"description":"\nMarginRankingCriterionGradient takes both X1, X2, Y and dY and\nuses them to update dX1, and dX2 according to the chain rule\nand derivatives of the loss function.\n","support_level":"default"}},{"name":"CreateMutex","schema":{"description":"Creates an unlocked mutex and returns it in a unique_ptr blob.","outputs":[{"description":"Blob containing a std::unique_ptr.","name":"mutex_ptr"}],"support_level":"default"}},{"name":"Float16UniformFill","schema":{"attributes":[{"description":"Shape of the tensor","name":"shape","option":"optional"},{"description":"Minimim value to generate","name":"min","option":"optional"},{"description":"Maximum value to generate","name":"max","option":"optional"}],"description":"Fills a half float tensor of a specified shape with values from a uniform distribution[min,max]","support_level":"default"}},{"name":"SparseAdadelta","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 0.95, the squared gradient sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nGiven inputs (param, moment, moment_delta, indices, grad, lr),\nruns the dense AdaDelta update on (param, grad, moment[indices],\n moment_delta[indices], lr), and returns (new_param, new_moment,\n new_moment_delta) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Average of squared gradients","name":"moment"},{"description":"Average of squared parameter updates","name":"moment_delta"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated average squared gradient","name":"output_moment"},{"description":"Updated average of squared parameter updates","name":"output_moment_delta"}],"support_level":"default"}},{"name":"FloatToRowwiseQuantized8Bits","schema":{"description":"\nThis operator applies 8Bit row-wise quantization to\ninput tensor and returns quantized tensor. Row wise quantization of\ninput tensor is the following process. We take tensor of size\n(m_1, m_2,...,m_n), n >= 2, reshape it into matrix of size\n(m_1, m_2 x... x m_n) and apply row-wise quantization. After this,\nwe compute scale_i= (min_i - max_i) / 255 and bias_i = min_i for\ni-th row r_i of reshaped matrix, where min_i and max_i -- minimum\nand maximum elements of i-th row, and quantize each element r_{ij} as\n0 <= round(r_ij - bias_i) / scale_i) < 256. Instead of input tensor\nwe obtain uint8 tensor and auxiliary information as scale and bias to\nrestore input tensor (with losses).\n","inputs":[{"description":"input","name":"input"}],"outputs":[{"description":"quantized_input","name":"quantized_input"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i","name":"scale_bias"}],"support_level":"default"}},{"name":"SumRelu","schema":{"description":null,"inputs":[{"description":"First of the input tensors. Can be inplace.","name":"data_0"}],"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum"}],"support_level":"default"}},{"name":"LSTMUnitGradient","schema":{"attributes":[{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":null,"support_level":"default"}},{"name":"AveragePool3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeMean","schema":{"description":"\nApplies 'Mean' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Mean', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computation is done element-wise, so that each element of the output slice corresponds to the average value of the respective elements in the input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"DiagonalFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor.Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape","name":"input_as_shape","option":"optional"}],"description":"\nThe operator fills the diagonal elements of the output tensor (>= 2D)\nwith a constant value specified by the 'value' argument, and others 0. If\nnumber of dimensions of the output tensor is greater than 2, all dimensions\nmust be equal.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message. If the 'dtype' argument is not provided, the data type of\n'value' is used.\n\nThe output tensor shape is specified by the 'shape' argument. If the number of\ninput is 1, the shape will be identical to that of the input at run time with\noptional additional dimensions appended at the end as specified by 'extra_shape'\nargument. In that case the 'shape' argument should not be set.\n\nIf input_as_shape is set to true, then the input should be a 1D tensor\ncontaining the desired output shape (the dimensions specified in extra_shape\nwill also be appended)\n\nNOTE: Currently, it supports data type of float, int32, int64, and bool.\n","inputs":[{"description":"Input tensor (optional) to provide shape information.","name":"input"}],"outputs":[{"description":"Output tensorargument and its type is specified by the 'dtype' argument","name":"output"}],"support_level":"default"}},{"name":"ConcatTensorVector","schema":{"description":"\nConcat Tensors in the std::unique_ptr >\nalong the first dimension.\n ","inputs":[{"description":"std::unique_ptr >","name":"vector of Tensor"}],"outputs":[{"description":"tensor after concatenating","name":"tensor"}],"support_level":"default"}},{"name":"Conv2D","schema":{"description":"\nThe convolution operator consumes an input vector, a 2D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"MultiClassAccuracy","schema":{"description":"\nRespectively compute accuracy score for each class given a number of instances\nand predicted scores of each class for each instance.\n","inputs":[{"description":"2-D float tensor (N,D,) of predicted scores of each class for each data. N is the number of instances, i.e., batch size. D is number of possible classes/labels.","name":"prediction"},{"description":"1-D int tensor (N,) of labels for each instance.","name":"labels"}],"outputs":[{"description":"1-D float tensor (D,) of accuracy for each class. If a class has no instance in the batch, its accuracy score is set to zero.","name":"accuracies"},{"description":"1-D int tensor (D,) of number of instances for each class in the batch.","name":"amounts"}],"support_level":"default"}},{"name":"ReduceL2Gradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseUnsortedSegmentSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentSum).\n\nThis op is basically Gather and UnsortedSegmentSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceFrontMax","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **max**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the max operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [max(1,4), max(5,1,7), max(2), max(9,2)] = [4, 7, 2, 9]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_max_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontMax\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[2. 8. 1.]\n [9. 6. 6.]\n [7. 7. 0.]]\n\n [[4. 3. 9.]\n [9. 2. 7.]\n [6. 4. 7.]]]\nY: [9. 8. 9.]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ExpandDims","schema":{"attributes":[{"description":"List of dimensions of *data* to add single dimensional entry.","name":"dims","option":"optional","type":"int64[]"}],"description":"\nThe *ExpandDims* op inserts single-dimensional entries into the shape of the input tensor *data,* and produces a single output tensor *expanded*. The op also takes an argument *dims* with a list of dimensions for where to add the single dimensional entries. If the same blob is provided as input and output, the operation is copy-free. This is the exact inverse operation of *Squeeze*.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ExpandDims\",\n [\"data\"],\n [\"expanded\"],\n dims=[0,1],\n)\n\nworkspace.FeedBlob(\"data\", np.zeros((100,100)).astype(np.float32))\nprint(\"data.shape:\", workspace.FetchBlob(\"data\").shape)\n\nworkspace.RunOperatorOnce(op)\nprint(\"expanded.shape:\", workspace.FetchBlob(\"expanded\").shape)\n\n```\n\n**Result**\n\n```\n\ndata.shape: (100, 100)\nexpanded.shape: (1, 1, 100, 100)\n\n```\n\n
\n\n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"data"}],"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded"}],"support_level":"default"}},{"name":"RowMul","schema":{"description":"\nGiven a matrix A and column vector w, the output is the multiplication of row i\nof A and element i of w, e.g. C[i][j] = A[i][j] * w[i]. This operator should be\ndeprecated when the gradient operator of Mul with broadcast is implemented.\n","inputs":[{"description":"The matrix","name":"mat"},{"description":"The column vector","name":"w"}],"outputs":[{"description":"Output","name":"output"}],"support_level":"default"}},{"name":"BatchMoments","schema":{"description":null,"support_level":"default"}},{"name":"IsMemberOf","schema":{"attributes":[{"description":"List of values to check for membership.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"}],"description":"\nThe *IsMemberOf* op takes an input tensor *X* and a list of values as argument, and produces one output data tensor *Y*. The output tensor is the same shape as *X* and contains booleans. The output is calculated as the function *f(x) = x in value* and is applied to *X* elementwise.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/elementwise_logical_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/elementwise_logical_ops.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"IsMemberOf\",\n [\"X\"],\n [\"Y\"],\n value=[0,2,4,6,8],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"X\", np.array([0,1,2,3,4,5,6,7,8]).astype(np.int32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y: \\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n// value=[0,2,4,6,8]\n\nX:\n [0 1 2 3 4 5 6 7 8]\nY:\n [ True False True False True False True False True]\n\n```\n\n
\n\n","inputs":[{"description":"Input tensor of any shape","name":"X"}],"outputs":[{"description":"Output tensor (same size as X containing booleans)","name":"Y"}],"support_level":"default"}},{"name":"MinGradient","schema":{"description":null,"support_level":"default"}},{"name":"RangeFill","schema":{"description":null,"support_level":"default"}},{"name":"ReluN","schema":{"attributes":[{"description":"the cap of output","name":"n","option":"optional"}],"description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = min(max(0, x), n),\nis applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"TanhGradient","schema":{"description":null,"support_level":"default"}},{"name":"CubeGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceTailSum","schema":{"description":"\nReduce the tailing dimensions\n","inputs":[{"description":"The matrix","name":"mat"}],"outputs":[{"description":"Output","name":"output"}],"support_level":"default"}},{"name":"GroupNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"Moments","schema":{"attributes":[{"description":"A list of integers, along which to reduce. If axes is not provided, the op computes the element-wise mean and variance.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the mean and variance of the input tensor's element along the\n provided axes. The resulted tensor has the same rank as the input if keepdims\n equals True.\n If keepdims equals False, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced mean tensor.","name":"mean"},{"description":"Reduced variance tensor.","name":"variance"}],"support_level":"default"}},{"name":"ATen","schema":{"description":null,"support_level":"contribution"}},{"name":"LC1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsToSegmentIds","schema":{"description":"\nGiven a vector of segment lengths (*lengths*) the *LengthsToSegmentIds* op returns a zero-based, consecutive vector of segment ids (*segment_ids*). For example, *lengths=[1, 3, 0, 2]* will produce *segment_ids=[0, 1, 1, 1, 3, 3]*. In general, the inverse operation is *SegmentIdsToLengths*. Notice though that trailing empty sequence lengths can't be properly recovered from segment ids.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsToSegmentIds\",\n [\"lengths\"],\n [\"segment_ids\"],\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([1, 3, 0, 2]).astype(np.int32))\nprint(\"lengths:\\n\", workspace.FetchBlob(\"lengths\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"segment_ids: \\n\", workspace.FetchBlob(\"segment_ids\"))\n\n```\n\n**Result**\n\n```\n\nlengths:\n [1 3 0 2]\nsegment_ids:\n [0 1 1 1 3 3]\n\n```\n\n
\n\n","inputs":[{"description":"1D tensor of int32 or int64 segment lengths.","name":"lengths"}],"outputs":[{"description":"1D tensor of length *sum(lengths)*","name":"segment_ids"}],"support_level":"default"}},{"name":"Wngrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nComputes the WnGrad update for an input gradient and accumulated\nhistory. This operator implement the optimization algorithm\nin https://arxiv.org/abs/1803.02865 by Wu, Ward and Bottou.\nConcretely, given inputs (param, grad, seq_b, learning_rate),\ncomputes\n\n new_seq_b = seq_b + 1 / seq_b * norm(grad)^2\n effective_lr = learning_rate / (new_seq_b + epsilon)\n update = learning_rate * grad / (new_seq_b + epsilon)\n new_param = param + update\nand returns (new_param, new_seq_b).\n\nOptionally returns effective_lr and update as well.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Seq_b history","name":"seq_b"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated seq_b","name":"output_seq_b"},{"description":"(optional) Effective learning rate","name":"output_effective_lr"},{"description":"(optional) Actual update that is applied.","name":"output_update"}],"support_level":"default"}},{"name":"Or","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **or** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Or\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[False True True]\n [False True True]\n [ True True True]]\nB:\n[[False True False]\n [ True True True]\n [False True False]]\nC:\n[[False True True]\n [ True True True]\n [ True True True]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"EQ","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise equal to comparison **==** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"EQ\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True False False True True False]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"ErfGradient","schema":{"description":null,"support_level":"default"}},{"name":"ChannelBackpropStats","schema":{"description":"\nGiven an input tensor in NCHW format, the gradient for the output of SpatialBN\nand the per-channel mean and inverse std var vectors for the input, computes the\nper-channel bias and scale gradient to be used during the backward pass for\nsubsequent spatial batch normalization gradient calculation. Typically, the\nresults of this op are subsequently reduced over multiple devices to obtain\nstatistics over a larger batch size in cases where the batch size for a single\nmodel copy is too low to yield the full benefit of batch normalization. The\nresulting bias and scale can then be plugged back into SpatialBNGradient to get\nresults over the larger batch size ","inputs":[{"description":"The input 4-dimensional tensor of shape NCHW","name":"X"},{"description":"The mean saved from the forward pass as a 1-dimensional tensor of size C.","name":"mean"},{"description":"The saved inverse standard deviation as a 1-dimensional tensor of size C.","name":"inv_std"},{"description":"Gradient for the output layer of SpatialBN, here used as input because we are on the backward pass","name":"output_grad"}],"outputs":[{"description":"Gradient for the scale vector","name":"scale_grad"},{"description":"Gradient for the bias vector","name":"bias_grad"}],"support_level":"default"}},{"name":"GatherRangesToDense","schema":{"attributes":[{"description":"Expected lengths for ranges","name":"lengths","option":"optional"},{"description":"The number of observations needed before deciding that the ratio of mismatched ranges is alarming, also determines whether an info sumarizing the empty and mismatch ratio will be printed at the end.","name":"min_observation","option":"optional"},{"description":"An error is raised when ratio of empty ranges exceeds this (default is 1, which means by default no error will be triggered).","name":"max_empty_ratio","option":"optional"},{"description":"An error is raised when ratio of mismatched ranges exceeds this.","name":"max_mismatched_ratio","option":"optional"},{"description":"A log is recorded only after an error is triggered every n times.","name":"log_every_n","option":"optional"}],"description":"\nGiven DATA tensor of rank 1, and RANGES tensor of rank 3, gather values\ncorresponding to each range into a separate output tensor. If the optional input\nKEY tensor is also given, the output will be sorted by KEY for each example.\n\nRANGES dimensions description:\n1: represents list of examples within a batch\n2: represents list features\n3: two values which are start and length or a range (to be applied on DATA)\n\nEach feature has fixed lengths which are passed as lengths argument and a\nseparate tensor will be produced for each feature.\ni.e. DATA.dim(1) = len(lengths) = NumOuptuts.\n\nMissing features (represented by empty ranges) filled with default_value.\n\nExample 1:\n DATA = [1, 2, 3, 4, 5, 6, 7, 8]\n RANGES = [\n [\n [2, 4],\n [0, 2],\n ],\n [\n [0, 0],\n [6, 2],\n ]\n ]\n lengths = [4, 2]\n OUTPUT[0] = [[3, 4, 5, 6], [0, 0, 0, 0]]\n OUTPUT[1] = [[1, 2], [7, 8]]\n\nExample 2 (with KEY):\nDATA = [1, 2, 3, 4, 5, 6, 7, 8]\nKEY = [0, 1, 3, 2, 1, 0, 1, 0]\nRANGES = [\n [\n [2, 4],\n [0, 2],\n ],\n [\n [0, 0],\n [6, 2],\n ]\n]\nlengths = [4, 2]\nOUTPUT[0] = [[6, 5, 4, 3], [0, 0, 0, 0]]\nOUTPUT[1] = [[1, 2], [8, 7]]\n\nContrast Example 2 with Example 1. For each data point per feature, the values\nare sorted by the corresponding KEY.\n","inputs":[{"description":"Tensor of rank 1.","name":"DATA"},{"description":"Tensor of int32/int64 ranges, of dims (N, M, 2). Where N is number of examples and M is a size of each example. Last dimension represents a range in the format (start, lengths)","name":"RANGES"},{"description":"Tensor of rank 1 and type int64.","name":"KEY"}],"outputs":[{"description":"1-D tensor of size sum of range lengths","name":"OUTPUT"}],"support_level":"default"}},{"name":"LambdaRankNdcg","schema":{"description":"\nIt implements the LambdaRank as appeared in Wu, Qiang, et al. \"Adapting boosting\nfor information retrieval measures.\" Information Retrieval 13.3 (2010): 254-270.\n\nThis method heuristically optimizes the NDCG.\n","support_level":"default"}},{"name":"TileGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResetCursor","schema":{"description":"\nResets the offsets for the given TreeCursor. This operation is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"}],"support_level":"default"}},{"name":"SortedSegmentRangeMax","schema":{"description":"\nApplies 'Max' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Max', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMax computation is done element-wise, so that each element of the output slice corresponds to the max value of the respective elements in the input slices. Operation doesn't change the shape of individual blocks. This implementation imitates torch nn.Max operator. If the maximum value occurs more than once, the operator will return the first occurrence of value. When computing the gradient using the backward propagation, the gradient input corresponding to the first occurrence of the maximum value will be used.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"PairWiseLoss","schema":{"description":"\nOperator computes the pair wise loss between all pairs within a batch\n using the logit loss function on the difference in scores between pairs\n","inputs":[{"description":"Input blob from the previous layer, which is almost always the result of a softmax operation; X is a 2D array of size N x 1where N is the batch size. For more info: D. Sculley, Large Scale Learning to Rank. https://www.eecs.tufts.edu/~dsculley/papers/large-scale-rank.pdf","name":"X"},{"description":"Blob containing the labels used to compare the input","name":"label"},{"description":"Optional input blob that contains the lengthsof multiple sessions. The summation of this blob must be equalto the size of blob X. If lengths blob is provided, the outputblob has the same size as lengths blob, and the cross entropyis computed within each session.","name":"lengths"}],"outputs":[{"description":"Output blob after the cross entropy computation","name":"Y"}],"support_level":"default"}},{"name":"NHWC2NCHW","schema":{"description":"\nThe operator switches the order of data in a tensor from NHWC- sample index N,\nheight H, width H and channels C, to the NCHW order (this is for 2D images).\nIn general, this operator switches the order of data in a tensor from N H_1 ...\nH_k C to N C H_1 ... H_k for k-dimensional features, and currently supports\nk=1, 2, and 3.\n","inputs":[{"description":"The input data (Tensor) in the NHWC order.","name":"data"}],"outputs":[{"description":"The output tensor (Tensor) in the NCHW order.","name":"output"}],"support_level":"default"}},{"name":"CreateRebatchingQueue","schema":{"attributes":[{"description":"Number of input tensors the queue will support","name":"num_blobs","option":"optional"},{"description":"Maximal number of elements the queue can hold at any given point","name":"capacity","option":"optional"}],"description":"\nCreates the Queue.\n","outputs":[{"description":"object representing the queue","name":"queue"}],"support_level":"default"}},{"name":"GE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise greater or equal than comparison **>=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True True False True True False]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"SinusoidPositionEncoding","schema":{"attributes":[{"description":"Desired embedding size/number of dimensions -- defaults to 100","name":"embedding_size","option":"optional"},{"description":"Sinusoid tuning parameter -- defaults to 10000","name":"alpha","option":"optional"},{"description":"Amplitude of Sin/Cos output","name":"amplitude","option":"optional"}],"description":"\nCalculates a sinusoid position encoding tensor as described\nin https://arxiv.org/abs/1706.03762. Takes a 2-D tensor\n(of size M x K) of positions as input, the embedding size\nas an argument, and outputs a position encoding tensor of\nsize (M x K x embedding_size). Here M is typically the max\nsequence length and K is typically the batch size.\nThe input tensor must satisfy input[m, 0] == input[m, k] for all k.\n\nEncoded as amplitude * SIN(pos/alpha^(i/embedding_size)) if i is even,\nelse amplitude * COS(pos/alpha^(i/embedding_size)). Here, pos is the position,\nalpha and amplitude are tuning parameters, i is the current dimension for\nthe embedding, and embedding_size is the number of total dimensions in\nthe embedding.\n","inputs":[{"description":"2-D tensor of positions to be encoded","name":"positions"}],"outputs":[{"description":"3-D tensor representing the positional encoding","name":"output"}],"support_level":"default"}},{"name":"SortedSegmentRangeMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"RoIAlignGradient","schema":{"description":null,"inputs":[{"description":"See RoIPoolF.","name":"X"},{"description":"See RoIPoolF.","name":"RoIs"},{"description":"Gradient of forward output 0 (Y)","name":"dY"}],"outputs":[{"description":"Gradient of forward input 0 (X)","name":"dX"}],"support_level":"default"}},{"name":"UnsortedSegmentWeightedSum","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"},{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentWeightedSum).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"BatchMatMul","schema":{"attributes":[{"description":"Pass 1 to transpose the last two dimensions of A before doing multiplication","name":"trans_a","option":"optional"},{"description":"Pass 1 to transpose the last two dimensions of B before doing multiplication","name":"trans_b","option":"optional"},{"description":"Pass 1 to allow broadcasting of dimensions. Behavior is the same as numpy.matmul. Gradient is currently not supported when running in broadcast mode.","name":"broadcast","option":"optional"}],"description":"\nBatch Matrix multiplication Yi = Ai * Bi, where A has shape (dim0, dim1, ... M, K),\nB has shape (dim0, dim1, ... K, N), Y has shape (dim0, dim1, ... M, N) and i ranges\nfrom 0 to (dim0 * dim1 ...) - 1. rank(A) == rank(B) >= 2. In case of A and B being\ntwo dimensional, it behaves like normal matrix multiplication.\n","inputs":[{"description":"tensor of shape (dim0, dim1 ... M, K)","name":"A"},{"description":"tensor of shape (dim0, dim1 ... K, N)","name":"B"}],"outputs":[{"description":"tensor of shape (dim0, dim1 ... M, N)","name":"Y"}],"support_level":"default"}},{"name":"LpNormGradient","schema":{"attributes":[{"description":"Order of the norm in p-norm","name":"p","option":"optional"},{"description":"whehther we calculate norm or averaged_norm.The Lp_averaged_norm(x) is defined asLp_averaged_normgradient(x) = LpNormGradient(x) / size(x)","name":"average","option":"optional"}],"description":"\nGiven one input float tensor X, derivative dout, and produces one output\nfloat tensor dX. dX is the derivative of the Lp norm of tensor X, computed as\ndx = d(sum over |x^p|)/dx, in which p is either 1 or 2(currently only\nsupports l1 and l2 norm) determined by the argument p.\n","inputs":[{"description":"1D input tensor","name":"X"},{"description":"1D input tensor","name":"dout"}],"outputs":[{"description":"1D output tensor","name":"dx"}],"support_level":"default"}},{"name":"DotProduct","schema":{"description":"\nComputes and outputs the dot product of the two input float tensors `X` and `Y`.\nNote that `X` and `Y` must be either 1D or 2D, and they must be the same shape.\nThe output tensor is 1D, which represents either the product of each element in\na respective dimension if the inputs are 1D, or the sum of the products in a\ngiven dimension if the inputs are 2D matrices. Note that the actual dot product\nis a scalar value, which is effectively the sum of the elements in the 1D\noutput tensor.\n\nFor 1D inputs:\nGiven two vectors $X = [x_0, x_1, x_2]$ and $Y = [y_0, y_1, y_2]$; $Z = [x_0 * y_0, x_1 * y_1, x_2 * y_2]$\n\nFor 2D inputs:\nGiven two matrices:\n$$X = [[x_0^0, x_1^0, x_2^0], \\\\ [x_0^1, x_1^1, x_2^1], \\\\ [x_0^2, x_1^2, x_2^2], \\\\ ..., \\\\ [x_0^n, x_1^n, x_2^n]]$$\n\nand\n\n$$Y = [[y_0^0, y_1^0, y_2^0], \\\\ [y_0^1, y_1^1, y_2^1], \\\\ [y_0^2, y_1^2, y_2^2], \\\\ ..., \\\\ [y_0^n, y_1^n, y_2^n]]$$\n\nthen\n\n$$Z = \\biggl[\\Big((x_0^0 * y_0^0) + (x_1^0 * y_1^0) + (x_2^0 * y_2^0)\\Big), \\\\ \\Big((x_0^1 * y_0^1) + (x_1^1 * y_1^1) + (x_2^1 * y_2^1)\\Big), \\\\ \\Big((x_0^2 * y_0^2) + (x_1^2 * y_1^2) + (x_2^2 * y_2^2)\\Big), \\\\ ..., \\\\ \\Big((x_0^n * y_0^n) + (x_1^n * y_1^n) + (x_2^n * y_2^n)\\Big)\\biggr]$$\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"DotProduct\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(20, size=(5)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", np.random.randint(20, size=(5)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Z:\\n\", workspace.FetchBlob(\"X\"))\n\n\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [ 2. 15. 2. 7. 12.]\nY:\n [ 3. 12. 9. 3. 18.]\nZ:\n [ 2. 15. 2. 7. 12.]\nX:\n [[2. 0. 4.]\n [7. 7. 4.]\n [7. 9. 9.]]\nY:\n [[2. 0. 8.]\n [9. 6. 1.]\n [7. 8. 0.]]\nZ:\n [ 36. 109. 121.]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* 1D or 2D input tensor.","name":"X"},{"description":"*(type: Tensor``)* 1D or 2D input tensor (must have the same shape as X).","name":"Y"}],"outputs":[{"description":"*(type: Tensor``)* 1D output tensor.","name":"Z"}],"support_level":"default"}},{"name":"NGramFromCategorical","schema":{"description":null,"support_level":"default"}},{"name":"Int8Slice","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"List of starting indices","name":"starts","option":"optional"},{"description":"List of ending indices","name":"ends","option":"optional"},{"description":"(Optional) The dimension to slice over. If specified start_idx and end_idx should also be given and it takes precedence over starts and ends","name":"dim","option":"optional"},{"description":"(Optional) The dimension to start slice from. Default is 0","name":"start_idx","option":"optional"},{"description":"(Optional) The dimension to end the slice. Default is -1","name":"end_idx","option":"optional"}],"description":"\nProduces a slice of the input Int8 tensor. Currently, only slicing in a single\ndimension is supported.\nSlices are passed as 2 1D vectors or as two keyword argument lists with starting\nand end indices for each dimension of the input `data` tensor. If a negative\nvalue is passed for any of the start or end indices, it represents the number of\nelements before the end of that dimension. End indices are non-inclusive unless\nnegative (end index -1 means up to and including the last element).\n\n\nExample:\n\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 3]\n\n result = [\n [2, 3],\n [6, 7],\n ]\n","inputs":[{"description":"Int8 Tensor of data to extract slices from.","name":"data"},{"description":"1D tensor: start-indices for each dimension of data.","name":"starts"},{"description":"1D tensor: end-indices for each dimension of data.","name":"ends"}],"outputs":[{"description":"Sliced Int8 data tensor.","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceFrontSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ViterbiPath","schema":{"description":"\nGiven a predictions matrix and a transitions matrix, get the path with the best\nscore\n","inputs":[{"description":"N*D predictions matrix","name":"predictions"},{"description":"D*D transitions matrix","name":"transitions"}],"outputs":[{"description":"N*1 vector holds the best path indices","name":"viterbi_path"}],"support_level":"default"}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the max of the input tensor's element along the provided axes.\n The resulted tensor has the same rank as the input if keepdims equal True.\n If keepdims equal false, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced output tensor.","name":"reduced"}],"support_level":"default"}},{"name":"SparseLengthsWeightedMean8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsWeightedMean operator, where\nDATA is stored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of INDICES","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Slice","schema":{"attributes":[{"description":"(*Tuple(int)*): list of starting indices","name":"starts","option":"optional"},{"description":"(*Tuple(int)*): list of ending indices","name":"ends","option":"optional"}],"category":"Tensor","description":"\nProduces a slice of the input tensor.\n\n- Currently, only slicing in a single dimension is supported.\n\n- Start and end indices are either passed as two 1D input tensors or using the `starts` and `ends` arguments.\n\n- If a negative value is passed for any of the start or end indices, it represents the number of elements before the end of that dimension. End indices are non-inclusive unless negative (end index -1 means up to and including the last element).\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/slice_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Slice\",\n [\"X\"],\n [\"Y\"],\n starts=(0,1),\n ends=(-1,3)\n)\n\nworkspace.FeedBlob(\"X\", np.array([[1,2,3,4],[5,6,7,8]]))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[1 2 3 4]\n [5 6 7 8]]\nY:\n[[2 3]\n [6 7]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): tensor to extract slices from","name":"X"},{"description":"(*Tensor``*): 1D tensor of start-indices for each dimension of data","name":"starts"},{"description":"(*Tensor``*): 1D tensor of end-indices for each dimension of data","name":"ends"}],"outputs":[{"description":"(*Tensor*): sliced output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"InstanceNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"UpsampleBilinearGradient","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SortAndShuffle","schema":{"description":"\nCompute the sorted indices given a field index to sort by and break the sorted\nindices into chunks of shuffle_size * batch_size and shuffle each chunk,\nfinally we shuffle between batches. If sort_by_field_idx is -1 we skip sort.\n\nFor example, we have data sorted as\n1,2,3,4,5,6,7,8,9,10,11,12\n\nand batchSize = 2 and shuffleSize = 3, when we shuffle we get:\n[3,1,4,6,5,2] [12,10,11,8,9,7]\n\nAfter this we will shuffle among different batches with size 2\n[3,1],[4,6],[5,2],[12,10],[11,8],[9,7]\n\nWe may end up with something like\n[9,7],[5,2],[12,10],[4,6],[3,1],[11,8]\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nSortAndShuffle is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing sorted indices.","name":"indices"}],"support_level":"default"}},{"name":"Int8MaxPoolRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"MaxPool \nconsumes an input blob X and applies max pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Max pooling consisting of taking the maximum value of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linearfunction, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"BitwiseOr","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_or` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"Int8SumRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"MaxPool2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"Percentile","schema":{"description":"\n This operator is used to find percentile representations for raw values, given a sample\n set of raw values, labeled with their corresponding percentiles from the same distribution.\n In particular, this operator takes as input a tensor of floats to find the percentile values\n for, a 2D tensor of floats, where the first column of the tensor represents sampled values,\n and the second column represents the percentile labels, and a tensor of integers lengths.\n\n This lengths tensor is used because the operator works on multiple sets of raw values at the same time. For\n example, for an input:\n original_values=[[3, 5, 3],[5, 1, 6]], lengths = [2, 1, 1], value_to_pct = [[3, 0.2], [5, 0.5], [1, 0.3], [3. 0.6]]\n\n Our operator expects that each column i of the input tensor is sampled from distribution i. Lengths tells\n us that the first two elements in value_to_pct are sampled from distribution 1, the next is from distribution two,\n and the last is from distribution 3. We expect the output of our operator to give us [[0.2, 1.0, 0.6], [0.5, 0.3, 1.0]].\n\n To calculate the percentile of an element, we check to see if its value is already mapped to\n a percentile in value_to_pct. If so, we return that value. If not, we linearly interpolate between\n the two closest values in value_to_pct. If the value is larger than all values in value_to_pct, we\n return 1. If it's smaller than all the values, we return 0.\n\n","inputs":[{"description":"Input 2D tensor of floats, representing the original, raw data to calculate percentiles for.","name":"original_values"},{"description":"Sorted 2D tensor, with 2 columns. Each element in the first column is a float representing the raw value of a sample. Its corresponding element in the next column represents the percentile it maps to.","name":"value_to_pct"},{"description":"1D tensor, representing the length of each distribution. We expect that the sum of elements of this tensor is equal to the total length of value_to_pct.","name":"lengths"}],"outputs":[{"description":"1D tensor of floats, with the same dimensions as the flattened input tensor. Each element of this tensor, percentile_values[i], corresponds to the percentile calculated for original_values[i].","name":"percentile_values"}],"support_level":"default"}},{"name":"MergeSingleListFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with list features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values","name":"in1_values"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"RowwiseMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"rnn_internal_apply_link","schema":{"description":"\nInternal RNN operator.\n","support_level":"default"}},{"name":"MergeSingleScalarFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with scalar features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":"","name":"in1"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values","name":"out_values"}],"support_level":"default"}},{"name":"BRGNCHWCToPackedInt8BGRAStylizerDeprocess","schema":{"description":null,"support_level":"default"}},{"name":"TrimDataset","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nTrim the given dataset inplace, given the dataset blobs and the field specs.\nTrimming happens such that the dataset will contain the largest possible number\nof records that is a multiple of the 'multiple_of' argument.\n","support_level":"default"}},{"name":"PiecewiseLinearTransform","schema":{"attributes":[{"description":"1-D vector of size (prediction_dimensions x (pieces+1)) contain the upper bounds of each piece of linear function. One special case is the first bound is the lower bound of whole piecewise function and we treat it the same as the left most functions. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"bounds","option":"optional"},{"description":"1-D vector of size (prediction_dimensions x pieces) containing the slopes of linear function","name":"slopes","option":"optional"},{"description":"1-D vector of size (prediction_dimensions x pieces) containing the intercepts of linear function","name":"intercepts","option":"optional"},{"description":"If set true, we assume the input is a Nx1 or Nx2 tensor. If it is Nx1 tensor, it is positive predictions. If the input is Nx2 tensor, its first column is negative predictions and second column is positive and negative + positive = 1. We just need one group of piecewise linear functions for the positive predictions.","name":"binary","option":"optional"}],"description":"\nPiecewiseLinearTransform takes inputs -- predictions, a 2-D or 1-D tensor\n(Tensor) of size (batch_size x prediction_dimensions). The piecewise\nlinear functions are stored in bounds, slopes and intercepts. The output tensor\nhas the same shape of input `predictions` and contains the predictions\ntransformed by the piecewise linear functions. Each column of predictions has\nits own piecewise linear transformation functions. Therefore the size of\npiecewise function parameters are pieces x prediction_dimensions, except for\nbinary predictions where only the positive prediction needs them. Note that in\neach piece, low bound is excluded while high bound is included. Also the\npiecewise linear function must be continuous.\n\nNotes\n- If the input is binary predictions (Nx2 or Nx1 tensor), set the binary arg\nto true so that one group of piecewise linear functions is needed (see\ndetails below).\n- The transform parameters (bounds, slopes, intercepts) can be passed either\nthrough args or through input blobs.\n- If we have multiple groups of piecewise linear functions, each group has the\nsame number of pieces.\n- If a prediction is out of the bounds, it is capped to the smallest or largest\nbound.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing scores","name":"predictions"},{"description":"See bounds in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"bounds (optional)"},{"description":"See slopes in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"slopes (optional)"},{"description":"See intercepts in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"intercepts (optional)"}],"outputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing transformed predictions","name":"transforms"}],"support_level":"default"}},{"name":"CosineSimilarity","schema":{"description":"\nThis op takes two input float tensors of the same size, $X$ and $Y$, and produces one output float tensor , $Z$, calculated as the cosine similarity between $X$ and $Y$. Recall, the cosine similarity between two tensors $X$ and $Y$ is defined as:\n\n$$\\mathbf{Z}=CosineSimilarity(\\mathbf{X},\\mathbf{Y}) = \\frac{\\mathbf{X}\\cdot\\mathbf{Y}}{\\|\\mathbf{X}\\|\\|\\mathbf{Y}\\|} = \\frac{\\sum_n^{i=1}X_iY_i}{\\sqrt{\\sum_n^{i=1}X_i^2}\\sqrt{\\sum_n^{i=1}Y_i^2}}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"CosineSimilarity\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\n// Create X\nX = np.random.randn(3, 3)\nprint(\"X:\\n\",X)\n\n// Create Y\nY = np.random.randn(3, 3)\nprint(\"Y:\\n\",Y)\n\n// Feed X & Y into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"Y\", Y.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.42635564 -0.23831588 -0.25515547]\n [ 1.43914719 -1.05613228 1.01717373]\n [ 0.06883105 0.33386519 -1.46648334]]\nY:\n [[-0.90648691 -0.14241514 -1.1070837 ]\n [ 0.92152729 -0.28115511 -0.17756722]\n [-0.88394254 1.34654037 -0.80080998]]\nZ:\n [-1.7849885e-23 1.7849885e-23 -1.0842022e-07]\n\n```\n\n
\n\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor (must have the same shape as X)","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"ClipTensorByScaling","schema":{"attributes":[{"description":"Threshold to determine whether to scale down the tensor","name":"threshold","option":"optional"}],"description":"\n Clips the input tensor by scaling based on the input value and the threshold.\n The value is usually the (pre-computed) norm of the tensor. If the value is\n larger than the threshold, scaling would be performed in this way:\n\n tensor *= (threshold / value).\n\n An optional input called additional_threshold can be provided which\n will scale the original threshold before it is used. That is,\n the final threshold will become threshold * additional_threshold.\n This op could be used for gradient clipping.\n","inputs":[{"description":"Tensor of floats to be clipped.","name":"input_tensor"},{"description":"Value to be compared against the threshold","name":"val"},{"description":"An optional additional threshold to scale the original threshold","name":"additional_threshold"}],"outputs":[{"description":"Tensor of floats, which is the same size as the input tensor, representing the clipped tensor.","name":"clipped"}],"support_level":"default"}},{"name":"InstanceNorm","schema":{"attributes":[{"default":0.00001,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","option":"optional","type":"float32"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"}],"description":"\nThe *InstanceNorm* op applies Instance Normalization over a 4D input as described in [Instance Normalization: The Missing Ingredient for Fast Stylization](https://arxiv.org/abs/1607.08022).\n\n$$output = \\frac{input-\\mu_{input}}{\\sqrt{\\sigma_{input}^2} + \\epsilon}*scale + bias$$\n\nNotice, two of the outputs are optional so there are three output cases for this op. Case 1: output; Case 2: output, saved_mean; Case 3: output, saved_mean, saved_inv_stdev.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/instance_norm_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/instance_norm_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"InstanceNorm\",\n [\"input\", \"scale\", \"bias\"],\n [\"output\"],\n epsilon=1e-5,\n)\n\nworkspace.FeedBlob(\"input\", np.random.randn(2, 1, 3, 3).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"), \"\\n\")\n\nworkspace.FeedBlob(\"scale\", np.array([1.5]).astype(np.float32))\nprint(\"scale: \", workspace.FetchBlob(\"scale\"))\n\nworkspace.FeedBlob(\"bias\", np.array([1.]).astype(np.float32))\nprint(\"bias: \", workspace.FetchBlob(\"bias\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output:\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [[[[ 0.97856593 -1.1832817 -0.2540021 ]\n [-1.3315694 -0.7485018 0.3787225 ]\n [-0.6826597 -1.4637762 0.57116514]]]\n\n\n [[[-0.44948956 0.85544354 -0.9315333 ]\n [-0.37202677 -0.22266895 -0.27194235]\n [ 0.4948163 -0.7296504 1.3393803 ]]]]\n\nscale: [1.5]\nbias: [1.]\noutput:\n [[[[ 3.5017493 -0.3791256 1.2890853 ]\n [-0.6453266 0.40137637 2.4249308 ]\n [ 0.5195738 -0.8826599 2.7703972 ]]]\n\n\n [[[ 0.12639964 2.856744 -0.8821926 ]\n [ 0.28847694 0.60098207 0.49788612]\n [ 2.1021945 -0.45978796 3.869297 ]]]]\n\n```\n\n
\n\n","inputs":[{"description":"The input 4-dimensional NCHW tensor to be operated on.","name":"input"},{"description":"The input 1-dimensional scale tensor of size *C*.","name":"scale"},{"description":"The input 1-dimensional bias tensor of size *C*.","name":"bias"}],"outputs":[{"description":"The output 4-dimensional tensor of the same shape as input.","name":"output"},{"description":"(Optional) Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean"},{"description":"(Optional) Saved inverse stdev used during training to speed up gradient computation. Should not be used for testing.","name":"saved_inv_stdev"}],"support_level":"default"}},{"name":"RoIAlignRotated","schema":{"attributes":[{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nSimilar to RoIAlign but can handle rotated region proposals.\nBased on https://arxiv.org/abs/1703.01086.\n","inputs":[{"description":"4D feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 5 or 6) specifying R RoIs representing: batch index in [0, N - 1], center_x, center_y, width, height, angle. The RoI coordinates are in the coordinate system of the input image. `angle` should be specified in degrees and represents the RoI rotated counter-clockwise. For inputs corresponding to a single image, batch index can be excluded to have just 5 columns.","name":"RoIs"}],"outputs":[{"description":"4D output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"StringJoin","schema":{"attributes":[{"description":"Delimiter for join (Default: \",\").","name":"delimiter","option":"optional"},{"description":"Axis for the join (either 0 or 1)","name":"axis","option":"optional"}],"description":"\nTakes a 1-D or a 2-D tensor as input and joins elements in each row with the\nprovided delimiter. Output is a 1-D tensor of size equal to the first dimension\nof the input. Each element in the output tensor is a string of concatenated\nelements corresponding to each row in the input tensor. For 1-D input, each\nelement is treated as a row.\n","inputs":[{"description":"1-D or 2-D tensor","name":"input"}],"outputs":[{"description":"1-D tensor of strings created by joining row elements from the input tensor.","name":"strings"}],"support_level":"default"}},{"name":"ConvGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherFused8BitRowwise","schema":{"description":"\nPerform the same operation as Gather, but operating on 8-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\nthe scale and offset).\nDATA needs to have rank 2 and INDICES needs to have rank 1.\n","inputs":[{"description":"uint8 tensor with rank 2 obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA forthe rows that are being gathered","name":"INDICES"}],"outputs":[{"description":"output","name":"OUTPUT"}],"support_level":"default"}},{"name":"Lars","schema":{"attributes":[{"description":"rescaling offset parameter","name":"offset","option":"optional"},{"description":"minimum learning rate for clipping","name":"lr_min","option":"optional"}],"description":"\nImplement Layer-wise Adaptive Rate Scaling (LARS) with clipping. Before adding weight\ndecay, given a parameter tensor X and its gradient dX, the local learning rate\nfor X will be\n\nlocal_lr = trust * norm(X) / ( norm(dX) + wd * norm(X) + offset * norm(X) )\n\n = trust / ( norm(dX) / norm(X) + wd + offset ),\n\nwhere offset is a preset hyper-parameter to avoid numerical issue and trust\nindicates how much we trust the layer to change its parameters during one update.\nIn this implementation, we uses l2 norm and the computed local learning rate is\nclipped based on the upper bound lr_max and the lower bound lr_min:\n\nlocal_lr = min(local_lr, lr_max) and local_lr = max(local_lr, lr_min)\n\n","inputs":[{"description":"Parameter tensor","name":"X"},{"description":"Gradient tensor","name":"dX"},{"description":"Weight decay","name":"wd"},{"description":"Trust","name":"trust"},{"description":"Upper bound of learning rate","name":"lr_max"}],"outputs":[{"description":"Rescaled local learning rate","name":"lr_rescaled"}],"support_level":"default"}},{"name":"MergeMultiMapFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with map features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values.values_grad","name":"in1_values_values_grad"}],"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Tan","schema":{"description":"\nCalculates the tangent of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The tangent of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"BooleanMaskLengths","schema":{"description":"\nGiven a tensor of int32 `lengths` tensor representing segment lengths and a `mask` (boolean) tensor, return the segment lengths of the corresponding segmented tensor after **BooleanMask** is applied.\n\nIf `lengths` tensor is $[a_1, a_2, ..., a_n]$, then length of `mask` tensor must be $a_1 + a_2 + ... + a_n$.\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_mask_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanMaskLengths\",\n [\"lengths\", \"mask\"],\n [\"masked_lengths\"]\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([1,3,2], dtype=np.int32))\nworkspace.FeedBlob(\"mask\", np.array([False,True,True,False,True,True]))\nprint(\"lengths:\", workspace.FetchBlob(\"lengths\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\nworkspace.RunOperatorOnce(op)\nprint(\"masked_lengths:\", workspace.FetchBlob(\"masked_lengths\"))\n\n```\n\n**Result**\n\n```\n\nlengths: [1 3 2]\nmask: [False True True False True True]\nmasked_lengths: [0 2 2]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor containing segment lengths","name":"lengths"},{"description":"(*Tensor``*): A 1D bool tensor of values to keep.","name":"mask"}],"outputs":[{"description":"(*Tensor``*): 1D tensor of same type as inputs that contains the sequence","name":"masked_lengths"}],"support_level":"default"}},{"name":"Reciprocal","schema":{"description":"\nPerforms element-wise reciprocal ($\\1/x$) of input tensor $X$.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reciprocal_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Reciprocal\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[8. 3. 3.]\n [4. 0. 0.]\n [1. 2. 5.]]\nY:\n[[0.125 0.3333333 0.3333333 ]\n [0.25 inf inf ]\n [1 0.5 0.2 ]]\n\n```\n\n
\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"SquaredL2Distance","schema":{"description":"\nGiven two input float tensors X, Y, and produces one output float tensor\nof the L2 difference between X and Y that is computed as ||(X - Y)^2 / 2||.\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor (must have the same shape as X)","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"ArgMin","schema":{"attributes":[{"default":-1,"description":"The axis to get argmin.","name":"axis","option":"optional","type":"int64"},{"default":true,"description":"If True (default), the output tensor shape will match the input tensor shape except the `axis` dimension equals 1. Else, the `axis` dimension of the output tensor is removed.","name":"keepdims","option":"optional","type":"boolean"}],"description":"\nRetrieve the argmin of an axis dimension specified by the `axis`\nargument. Given an input tensor and two arguments (`axis` and\n`keepdims`), returns a tensor containing the indices of the smallest\nelement along the given axis. If the `keepdims` arg is *True* (default),\nthe shape of the output tensor matches the input tensor except the\n`axis` dimension equals 1. Else, the `axis` dimension of the output\ntensor is removed.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/arg_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ArgMin\",\n [\"X\"],\n [\"Indices\"],\n axis=1\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(5,5))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\n\n```\n\n**Result**\n\n```\n\nX: [[9. 4. 6. 4. 1.]\n [5. 9. 8. 3. 4.]\n [6. 1. 0. 2. 9.]\n [7. 8. 2. 4. 9.]\n [3. 9. 4. 9. 4.]]\nIndices: [[4]\n [3]\n [2]\n [2]\n [0]]\n\n```\n\n
\n\n ","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Tensor of indices for the smallest values.","name":"Indices"}],"support_level":"default"}},{"name":"RecurrentNetwork","schema":{"description":"\nRun the input network in a recurrent fashion. This can be used to\nimplement fairly general recurrent neural networks (RNNs).\n\nThe operator proceeds as follows.\n\n- First, initialized the states from the input recurrent states\n- For each timestep T, apply the links (that map offsets from input/output\ntensors into the inputs/outputs for the `step` network)\n- Finally, alias the recurrent states to the specified output blobs.\n\nThis is a fairly special-case meta-operator, and so the implementation\nis somewhat complex. It trades of generality (and frankly usability)\nagainst performance and control (compared to e.g. TF\ndynamic_rnn, Theano scan, etc).\n\nSee the usage examples for a flavor of how to use it.\n","support_level":"default"}},{"name":"Broadcast","schema":{"attributes":[{"description":"(int, default 0) the root to run broadcast from.","name":"root","option":"optional"}],"description":"\nDoes a broadcast operation from the root node to every other node. The tensor\non each node should have been pre-created with the same shape and data type.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be broadcasted.","name":"X"}],"outputs":[{"description":"In-place as input 1.","name":"X"}],"support_level":"default"}},{"name":"PythonDLPackGradient","schema":{"description":null,"support_level":"default"}},{"name":"SpaceToBatch","schema":{"attributes":[{"description":"(*int*): exclusive axis that divides the first and second dimension of matrix `A` (default=0)","name":"pad","option":"optional"},{"description":"(*int*): height/width of spatial blocks to be moved (default=2)","name":"block_size","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; only \"NCHW\" order is currently supported (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\nZero-pads and then rearranges (permutes) blocks of spatial data into batch. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the batch dimension. After the zero-padding is according to the `pad` argument, both height and width of the input must be divisible by the `block_size`. Only \"NCHW\" order is currently supported.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/space_batch_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SpaceToBatch\",\n [\"X\"],\n [\"Y\"],\n pad=2,\n block_size=3\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(1,3,5,5).astype(np.float32))\nprint(\"X.shape:\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape:\", workspace.FetchBlob(\"Y\").shape)\n\n```\n\n**Result**\n\n```\n\nX.shape: (1, 3, 5, 5)\nY.shape: (9, 3, 3, 3)\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor (NCHW order)","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor (NCHW order)","name":"Y"}],"support_level":"default"}},{"name":"BatchToSpace","schema":{"attributes":[{"description":"(*int*): exclusive axis that divides the first and second dimension of matrix `A` (default=0)","name":"pad","option":"optional"},{"description":"(*int*): height/width of spatial blocks to be moved (default=2)","name":"block_size","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; only \"NCHW\" order is currently supported (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\nRearranges (permutes) data from batch into blocks of spatial data, followed by cropping. This is the reverse transformation of `SpaceToBatch`. More specifically, this op outputs a copy of the input tensor where values from the batch dimension are moved in spatial blocks to the height and width dimensions, followed by cropping along the height and width dimensions. Only \"NCHW\" order is currently supported.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/space_batch_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BatchToSpace\",\n [\"X\"],\n [\"Y\"],\n pad=3\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(10,3,32,32).astype(np.float32))\nprint(\"X.shape:\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape:\", workspace.FetchBlob(\"Y\").shape)\n\n```\n\n**Result**\n\n```\n\nX.shape: (10, 3, 32, 32)\nY.shape: (2, 3, 58, 58)\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor (NCHW order)","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor (NCHW order)","name":"Y"}],"support_level":"default"}},{"name":"Erf","schema":{"description":"\nCalculates the arcsine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"AtomicAppend","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorBoolFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ConvRelu","schema":{"description":null,"support_level":"default"}},{"name":"StumpFuncIndex","schema":{"description":"\nSplit the elements and return the indices based on the given threshold.\n","inputs":[{"description":"tensor of float","name":"X"}],"outputs":[{"description":"tensor of int64 indices for elements below/equal threshold","name":"Index_Low"},{"description":"tensor of int64 indices for elements above threshold","name":"Index_High"}],"support_level":"default"}},{"name":"TopK","schema":{"description":"\nRetrieve the top-K elements of the last dimension. \nGiven an input tensor of shape $(a_1, a_2, ..., a_n, r)$. `k` can be passed as an integer argument or a 1D tensor containing a single integer.\nReturns up to three outputs:\n\n1. Value tensor of shape $(a_1, a_2, ..., a_n, k)$ which contains the values of the top k elements along the last dimension\n2. Index tensor of shape $(a_1, a_2, ..., a_n, k)$ which contains the indices of the top k elements (original indices from the input tensor).\n3. [OPTIONAL] Flattened index tensor of shape $(a_1 * a_2 * ... * a_n * k,)$.\n\nGiven two equivalent values, this operator uses the indices along the last dimension as a tiebreaker. That is, the element with the lower index will appear first.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/top_k.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"TopK\",\n [\"X\"],\n [\"Values\", \"Indices\", \"Flattened_indices\"],\n k=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Values:\", workspace.FetchBlob(\"Values\"))\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\nprint(\"Flattened_indices:\", workspace.FetchBlob(\"Flattened_indices\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[6. 7. 0.]\n [8. 7. 7.]\n [1. 5. 6.]]\n\n [[0. 6. 1.]\n [2. 8. 4.]\n [1. 2. 9.]]\n\n [[4. 3. 7.]\n [0. 1. 7.]\n [0. 1. 8.]]]\nValues:\n[[[7. 6.]\n [8. 7.]\n [6. 5.]]\n\n [[6. 1.]\n [8. 4.]\n [9. 2.]]\n\n [[7. 4.]\n [7. 1.]\n [8. 1.]]]\nIndices:\n[[[1 0]\n [0 1]\n [2 1]]\n\n [[1 2]\n [1 2]\n [2 1]]\n\n [[2 0]\n [2 1]\n [2 1]]]\nFlattened_indices: [ 1 0 3 4 8 7 10 11 13 14 17 16 20 18 23 22 26 25]\n\n```\n\n
\n\n ","inputs":[{"description":"(*Tensor``*): input tensor of shape $(a_1, a_2, ..., a_n, r)$","name":"X"},{"description":"(*int*): number of top elements to retrieve","name":"k"}],"outputs":[{"description":"(*Tensor``*): output tensor of shape $(a_1, a_2, ..., a_n, k)$","name":"Values"},{"description":"(*Tensor``*): tensor of indices of shape $(a_1, a_2, ..., a_n, k)$; indices values refer to each element's index in the last dimension of the `X` input tensor","name":"Indices"},{"description":"(*Tensor``*): tensor of indices of shape $(a_1 * a_2 * ... * a_n * k,)$; indices values refer to each element's index in the flattened input tensor `X`","name":"Flattened_indices"}],"support_level":"default"}},{"name":"SpatialBNGradient","schema":{"description":null,"support_level":"default"}},{"name":"ThrowChildThreadException","schema":{"description":null,"support_level":"default"}},{"name":"CheckDatasetConsistency","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nChecks that the given data fields represents a consistent dataset under\nthe schema specified by the `fields` argument. Operator fails if the fields\nare not consistent. If data is consistent, each field's data can be safely\nappended to an existing dataset, keeping it consistent.\n","inputs":[{"description":"Data for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"RoIPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"CreateTextFileReader","schema":{"attributes":[{"description":"Path to the file.","name":"filename","option":"optional"},{"description":"Number of passes over the file.","name":"num_passes","option":"optional"},{"description":"List with type of each field. Type enum is found at core.DataType.","name":"field_types","option":"optional"}],"description":"Create a text file reader. Fields are delimited by .","outputs":[{"description":"Pointer to the created TextFileReaderInstance.","name":"handler"}],"support_level":"default"}},{"name":"StringSuffix","schema":{"attributes":[{"description":"Maximum size of the suffix, in bytes.","name":"length","option":"optional"}],"description":"\nComputes the element-wise string suffix of the string tensor.\nInput strings that are shorter than suffix length will be returned unchanged.\nNOTE: Prefix is computed on number of bytes, which may lead to wrong behavior\nand potentially invalid strings for variable-length encodings such as utf-8.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of std::string containing suffixes for each output.","name":"suffixes"}],"support_level":"default"}},{"name":"Expand","schema":{"description":"\n Broadcast the input tensor to a materialized new tensor using given shape.\n Broadcast rule is similar to \"numpy.array(input) * numpy.ones(shape)\":\n Dimensions are right alignment;\n Two corresponding dimensions must have the same value, or one of them\n equals to 1.\n In order to align with PyTorch's `expand`, `shape` is allowed to have entries\n equal to -1, which means to preserve the size of the corresponding dimension\n in `X` (so it's actually equivalent to equal to 1).\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): expand shape","name":"shape"}],"outputs":[{"description":"(*Tensor``*): expanded tensor","name":"Y"}],"support_level":"default"}},{"name":"Gelu","schema":{"attributes":[{"description":"If true, use y = 0.5x * (1 + tanh(sqrt(2/Pi) * (x + 0.044715x^3))).","name":"fast_gelu","option":"optional"}],"description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = xP(X <= x) where X ~ N(0, 1),\nis applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"LpNorm","schema":{"attributes":[{"default":2,"description":"Order of the norm in p-norm.","name":"p","option":"optional","type":"int64"},{"default":false,"description":"Whether we calculate norm or averaged_norm.The Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x)","name":"average","option":"optional","type":"boolean"}],"description":"\nThis op computes the $L_p$ norm of the one dimensional input tensor $X$, and outputs a one dimensional output tensor $Y$. Here, the $L_p$ norm is calculated as\n\n$$L_p(\\mathbf{x}) = \\sum_i x_i^p$$\n\nThis op supports $p$ values of 1 or 2. If the average argument is set, the norm is calculated as Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x).\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LpNorm\",\n [\"X\"],\n [\"Y\"],\n p=2\n)\nX = np.array([5., 2.])\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [5. 2.]\nY:\n [29.]\n\n```\n\n
\n\n","inputs":[{"description":"1D Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 8-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8Add","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Performs element-wise binary Add (with no broadcast support).\n","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. It should be of the same size as A.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as A","name":"C"}],"support_level":"default"}},{"name":"AtanGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"GetCursorOffset","schema":{"description":"Get the current offset in the cursor.","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"}],"outputs":[{"description":"Tensor containing the offsets for the cursor.","name":"offsets"}],"support_level":"default"}},{"name":"Int8LeakyRelu","schema":{"attributes":[{"description":"Coefficient of leakage, default value is 0.01","name":"alpha","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nLeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"TanGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceL1Gradient","schema":{"description":null,"support_level":"default"}},{"name":"MergeMultiListFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with list features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values.values_grad","name":"in1_values_values_grad"}],"support_level":"default"}},{"name":"Int8GivenIntTensorFill","schema":{"attributes":[{"description":"Input array of type int32","name":"values","option":"optional"},{"description":"Input tensor shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Creates quantized tensor of type int32 with scale and zero point info.\n","outputs":[{"description":"An Int8TensorCPU with scale and zero point info","name":"Tensor"}],"support_level":"default"}},{"name":"TensorProtosDBInput","schema":{"attributes":[{"description":"(int, default 0) the number of samples in a batch. The default value of 0 means that the operator will attempt to insert the entire data in a single output blob.","name":"batch_size","option":"optional"}],"description":"\nTensorProtosDBInput is a simple input operator that basically reads things\nfrom a db where each key-value pair stores an index as key, and a TensorProtos\nobject as value. These TensorProtos objects should have the same size, and they\nwill be grouped into batches of the given size. The DB Reader is provided as\ninput to the operator and it returns as many output tensors as the size of the\nTensorProtos object. Each output will simply be a tensor containing a batch of\ndata with size specified by the 'batch_size' argument containing data from the\ncorresponding index in the TensorProtos objects in the DB.\n","inputs":[{"description":"A pre-initialized DB reader. Typically, this is obtained by calling CreateDB operator with a db_name and a db_type. The resulting output blob is a DB Reader tensor","name":"data"}],"outputs":[{"description":"The output tensor in which the batches of data are returned. The number of output tensors is equal to the size of (number of TensorProto's in) the TensorProtos objects stored in the DB as values. Each output tensor will be of size specified by the 'batch_size' argument of the operator","name":"output"}],"support_level":"default"}},{"name":"RemovePadding","schema":{"attributes":[{"description":"Outer-size of padding to remove around each range.","name":"padding_width","option":"optional","type":"int64"},{"description":"[OPTIONAL] Specifies a different end-padding width. If this is not set, will use same as `padding_width`.","name":"end_padding_width","option":"optional","type":"int64"}],"description":"\nRemove padding around the edges of each segment of the input data. This is the\nreverse operation of **AddPadding**, and uses the same arguments and conventions\nfor input and output data format.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sequence_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\naddpad_op = core.CreateOperator(\n \"AddPadding\",\n [\"X\", \"lengths_add\"],\n [\"Y\", \"lengths_out_add\"],\n padding_width=1\n)\n\nrmpad_op = core.CreateOperator(\n \"RemovePadding\",\n [\"Y\", \"lengths_rm\"],\n [\"Z\", \"lengths_out_rm\"],\n padding_width=1\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(20, size=(3,5))))\nworkspace.FeedBlob(\"lengths_add\", np.array([3]).astype(np.int32))\nworkspace.FeedBlob(\"lengths_rm\", np.array([5]).astype(np.int32))\n\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(addpad_op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"lengths_out_add:\", workspace.FetchBlob(\"lengths_out_add\"))\n\nworkspace.RunOperatorOnce(rmpad_op)\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nprint(\"lengths_out_rm:\", workspace.FetchBlob(\"lengths_out_rm\"))\n```\n\n**Result**\n\n```\nX: [[17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]]\nY: [[ 0 0 0 0 0]\n [17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]\n [ 0 0 0 0 0]]\nlengths_out_add: [5]\nZ: [[17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]]\nlengths_out_rm: [3]\n```\n\n
\n\n","inputs":[{"description":"Input tensor ($T$).","name":"data_in"},{"description":"*(type: Tensor``)* Number of elements in each range. sum(lengths) = N. If not provided, considers all data as a single segment.","name":"lengths"}],"outputs":[{"description":"*(type: Tensor)* Padded data tensor ($T$).","name":"data_out"},{"description":"*(type: Tensor``)* [OPTIONAL] Lengths for each padded range.","name":"lengths_out"}],"support_level":"default"}},{"name":"AveragedLoss","schema":{"description":"\nThe *AveragedLoss* op takes a single 1-D input tensor *input* and returns a single output float value *output*. The output represents the average of the values in *input*. This op is commonly used for averaging losses, hence the name, however it does not exclusively operate on losses.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/loss_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/loss_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragedLoss\",\n [\"input\"],\n [\"output\"],\n)\n\nworkspace.FeedBlob(\"input\", np.array([8, 10, 12]).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output: \\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [ 8. 10. 12.]\noutput:\n 10.0\n\n```\n\n
\n\n\n","inputs":[{"description":"The input data as Tensor","name":"input"}],"outputs":[{"description":"The output tensor of size 1 containing the averaged value.","name":"output"}],"support_level":"default"}},{"name":"ReluGradient","schema":{"description":"\nReluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"TextFileReaderRead","schema":{"attributes":[{"description":"Maximum number of rows to read.","name":"batch_size","option":"optional"}],"description":"Read a batch of rows from the given text file reader instance. Expects the number of fields to be equal to the number of outputs. Each output is a 1D tensor containing the values for the given field for each row. When end of file is reached, returns empty tensors.","inputs":[{"description":"Pointer to an existing TextFileReaderInstance.","name":"handler"}],"support_level":"default"}},{"name":"LengthsTile","schema":{"description":"\nGiven DATA tensor of rank r >= 1, and LENGTHS tensor of rank 1, duplicate each\nentry of the outer-most dimension of DATA according to LENGTHS, and concatenate\nthem in an output tensor of rank r.\n\nExample:\n DATA = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n [6.8, 7.9],\n ]\n LENGTHS = [0, 1, 3, 2]\n OUTPUT = [\n [2.3, 3.4],\n [4.5, 5.7],\n [4.5, 5.7],\n [4.5, 5.7],\n [6.8, 7.9],\n [6.8, 7.9],\n ]\n","inputs":[{"description":"Tensor of rank r >= 1. First dimension must be equal to the size of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Tensor of rank r","name":"OUTPUT"}],"support_level":"default"}},{"name":"Int8ChannelShuffle","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"RowWiseSparseAdam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\n Computes a modified Adam Update for the sparse case.\n Given inputs (param, moment1, moment2, indices, grad, lr, iter), runs the\n Adam update on (param, moment1[indices], moment2[indices], lr, iter) and returns\n (new_param, new_moment1, new_moment2), where moment2 is a 1D tensor\n with length equal to the number of rows in param:\n shape(moment2) == shape(param)[0]. Each element of moment2 is\n applied to an entire row of param, and the new moment2 values are\n calculated by averaging across the row.\n\n ","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"Negative","schema":{"description":"\nComputes the element-wise negative of the input.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/negative_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Negative\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3).astype(np.float32)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[0.83296907 0.61407167 0.32562155]\n [0.59304523 0.03111175 0.29365504]\n [0.09478621 0.5424558 0.73940724]]\nY: [[-0.83296907 -0.61407167 -0.32562155]\n [-0.59304523 -0.03111175 -0.29365504]\n [-0.09478621 -0.5424558 -0.73940724]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* 1D input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* 1D output tensor.","name":"Y"}],"support_level":"default"}},{"name":"StdDevPut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an standard deviation.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"Perplexity","schema":{"description":"\nPerplexity calculates how well a probability distribution predicts a sample.\nPerplexity takes a 1-D tensor containing a batch of probabilities. Each value\nin the tensor belongs to a different sample and represents the probability of\nthe model predicting the true label for that sample. The operator returns a\nsingle (float) perplexity value for the batch.\n","inputs":[{"description":"The input data as Tensor. It contains a batch oftrue label or target probabilities","name":"probabilities"}],"outputs":[{"description":"The output- a single (float) perplexity value for the batch","name":"output"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"OneHot","schema":{"description":"\nThe *OneHot* op accepts two inputs *indices* and *index_size_tensor*, and produces a single output *one_hots*. For each index in *indices* the op creates a one-hot row in *one_hots* of length *index_size_tensor* where all entries are zero except the entry at the index is 1. The size of *one_hots* is *len(indices)* x *index_size_tensor*.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/one_hot_ops.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/one_hot_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"OneHot\",\n [\"indices\", \"index_size_tensor\"],\n [\"one_hots\"],\n)\n\nworkspace.FeedBlob(\"indices\", np.array([0,1,2,3,4]).astype(np.long))\nprint(\"indices:\\n\", workspace.FetchBlob(\"indices\"))\n\nworkspace.FeedBlob(\"index_size_tensor\", np.array([5]).astype(np.long))\nprint(\"index_size_tensor:\\n\", workspace.FetchBlob(\"index_size_tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"one_hots: \\n\", workspace.FetchBlob(\"one_hots\"))\n\n```\n\n**Result**\n\n```\n\nindices:\n [0 1 2 3 4]\nindex_size_tensor:\n [5]\none_hots:\n [[1. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 1.]]\n\n```\n\n
\n\n","inputs":[{"description":"The active index for each example in the batch.","name":"indices"},{"description":"Scalar with the size of the index. Must be in CPU context","name":"index_size_tensor"}],"outputs":[{"description":"Matrix of size len(indices) x index_size","name":"one_hots"}],"support_level":"default"}},{"name":"MergeSingleMapFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with map features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values","name":"in1_values"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.keys","name":"out_values_keys"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"Cbrt","schema":{"description":null,"inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cbrt of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"TensorVectorSize","schema":{"description":"Get the size of the input vector","inputs":[{"description":"std::unique_ptr >","name":"tensor vector"}],"outputs":[{"description":"int32_t size","name":"size"}],"support_level":"default"}},{"name":"AbsGradient","schema":{"description":null,"support_level":"default"}},{"name":"IncrementPut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an sum.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"MSRAFill","schema":{"description":null,"support_level":"default"}},{"name":"LC2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"Accumulate","schema":{"attributes":[{"description":"(float, default 1.0) Accumulation multiplier","name":"gamma","option":"optional"}],"description":"\nAccumulate operator accumulates the input tensor to the output tensor. If the\noutput tensor already has the right size, we add to it; otherwise, we first\ninitialize the output tensor to all zeros, and then do accumulation. Any\nfurther calls to the operator, given that no one else fiddles with the output\nin the interim, will do simple accumulations.\nAccumulation is done using Axpby operation as shown:\n Y = 1*X + gamma*Y\nwhere X is the input tensor, Y is the output tensor and gamma is the multiplier\nargument.\n","inputs":[{"description":"The input tensor that has to be accumulated to the output tensor. If the output size is not the same as input size, the output tensor is first reshaped and initialized to zero, and only then, accumulation is done.","name":"input"}],"outputs":[{"description":"Accumulated output tensor","name":"output"}],"support_level":"default"}},{"name":"CheckAtomicBool","schema":{"description":"Copy the value of an atomic to a bool","inputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"}],"outputs":[{"description":"Copy of the value for the atomic","name":"value"}],"support_level":"default"}},{"name":"StatRegistryCreate","schema":{"description":"\nCreate a StatRegistry object that will contain a map of performance counters\nkeyed by name. A StatRegistry is used to gather and retrieve performance\ncounts throughout the caffe2 codebase.\n","outputs":[{"description":"A Blob pointing to the newly created StatRegistry.","name":"handle"}],"support_level":"default"}},{"name":"GT","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise greater than comparison **>** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GT\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False True False False False False]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"SumSqrElements","schema":{"attributes":[{"description":"whether to average or not","name":"average","option":"optional"}],"description":"Sums the squares elements of the input tensor.","inputs":[{"description":"Tensor to sum up","name":"X"}],"outputs":[{"description":"Scalar sum of squares","name":"sum"}],"support_level":"default"}},{"name":"WeightedSample","schema":{"description":"\nThe operator performs sampling based on the input sampling weights for\neach batch. All weights must be non-negative numbers.\nThe input is a 2-D tensor (Tensor) of size (batch_size x weights_dim).\nFor each batch, an index is randomly sampled from the distribution given by\nthe weights of the corresponding batch.\nThe output is a 1-D tensor (Tensor) of size (batch_size x 1) and\ncontains the index(es) of the sampled output.\n","inputs":[{"description":"A 2-D Tensor of size (batch_size x weights_dim).All weights must be non-negative numbers.","name":"sampling_weights"},{"description":"An optional 2-D Tensor of size (batch_size x weights_dim).Its values correspond to the sampling weights.","name":"sampling_values"}],"outputs":[{"description":"The output tensor contains index(es) sampled from distribution givenby the weight vector(s) in the input tensorThe output is a 1-D Tensor of size (batch_size x 1)","name":"sampled_indexes"},{"description":"The output tensor contains value(s) selected by the sampled index(es)It is a 1-D Tensor of size (batch_size x 1)","name":"sampled_values"}],"support_level":"default"}},{"name":"WeightedMultiSampling","schema":{"attributes":[{"description":"number of samples to sample from the input data","name":"num_samples","option":"optional"}],"description":"\nThe operator performs sampling based on the input sampling weights.\nAll weights are cummulative probability thus sorted. The output is\na 1-D tensor (Tensor). If two inputs are given, the second input\nis used to provide shape of the output sample tensor. Otherwise, we use\nargument `num_samples` to determine the number of samples to generate.\n","inputs":[{"description":"An optional 1-D Tensor.Input cumulative sampling probability (such as [0.2, 0.5, 0.8, 1.5]). All weights must be non-negative numbers. Note that the last value of CDF is not necessary 1. If the last value is not 1, all values in sampling_cdf will be scaled by this number.","name":"sampling_cdf"},{"description":"Tensor whose shape will be applied to output.","name":"shape_tensor (optional)"}],"outputs":[{"description":"The output tensor contains indices sampled from distribution givenby the weight vector in the input tensorThe output is a 1-D Tensor of size determined by argument`num_samples` or the second input tensor.","name":"sampled_indexes"}],"support_level":"default"}},{"name":"SwishGradient","schema":{"description":"\nSwishGradient takes X, Y and dY and uses this to update dX according to the\nchain rule and derivatives of the swish function.\n","support_level":"default"}},{"name":"CrossEntropyGradient","schema":{"description":null,"support_level":"default"}},{"name":"LT","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise less than comparison **<** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LT\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False False True False False True]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"Softsign","schema":{"description":"\n*Softsign* takes one input data tensor $X$ and produces one output data $Y,$ where the softsign function, $y = \\frac{x}{1+ |x|}$, is applied to $X$ elementwise. This operation can be done in an in-place fashion too, by providing the same input and output blobs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softsign_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softsign\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-1.3060539 0.7242748 -1.9907674 ]\n [-0.64802396 -0.03244735 0.7455406 ]\n [-0.298492 -0.5774271 2.8364444 ]]\n\nY:\n [[-0.5663588 0.420046 -0.6656376 ]\n [-0.39321268 -0.03142761 0.4271116 ]\n [-0.2298759 -0.36605626 0.739342 ]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob to be operated on.","name":"input"}],"outputs":[{"description":"Output data blob with same shape as input","name":"output"}],"support_level":"default"}},{"name":"FloatToHalf","schema":{"description":null,"support_level":"default"}},{"name":"HardSigmoid","schema":{"attributes":[{"description":"float: the slope of the function. Defaults to 0.2","name":"alpha","option":"optional"},{"description":"float: the bias value of the function. Defaults to 0.5","name":"beta","option":"optional"}],"description":"\nApplies hard sigmoid operation to the input data element-wise.\nThe HardSigmoid operation takes one input $X$, produces one output $Y$, and is defined as:\n\n$$Y = max(0,min(1,x * alpha + beta))$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/hard_sigmoid_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/hard_sigmoid_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"HardSigmoid\",\n [\"X\"],\n [\"Y\"],\n alpha = 0.2,\n beta = 0.5,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"sigmoid:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\ninput: [ 1.5744036 0.31632107 1.7842269 1.4450722 -2.1726978 ]\nhard_sigmoid: [ 0.81488073, 0.56326419, 0.85684538, 0.78901446, 0.06546044]\n\n```\n\n
\n\n\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor with same shape as input","name":"Y"}],"support_level":"default"}},{"name":"GivenTensorStringFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"UniformIntFill","schema":{"attributes":[{"description":"(*int*): minimum value, inclusive","name":"min","option":"optional"},{"description":"(*int*): maximum value, inclusive","name":"max","option":"optional"},{"description":"(*Tuple(int)*): shape of the output, do not set when `input_as_shape`=1","name":"shape","option":"optional"},{"description":"(*int*): set to 1 to use the first input as shape; `shape` input must be in CPU context","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with int32 samples from uniform distribution [`min`, `max`].\n\n- The range can be defined either by arguments or input blobs. `min` and `max` are inclusive.\n - If the range is given by input blobs, you also need to give the shape as input.\n - When the range is given as arguments, this operator enforces min <= max. When the range is given as inputs, the constraint is not enforced.\n - When the range is given as inputs and max < min, the first dimension of the output is set to 0. This behavior is allowed so that dynamically sampling indices into a dynamically sized tensor is possible.\n- The shape of the output can be given as argument or input.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop_1 = core.CreateOperator(\n \"UniformIntFill\",\n [],\n [\"output\"],\n min=5,\n max=10,\n shape=(3,3)\n)\n\nop_2 = core.CreateOperator(\n \"UniformIntFill\",\n [\"shape\", \"min\", \"max\"],\n [\"output\"],\n input_as_shape=1\n)\n\n// Test arg-based op\nworkspace.RunOperatorOnce(op_1)\nprint(\"output (op_1):\\n\", workspace.FetchBlob(\"output\"))\n\n// Test input-based op\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"shape\", np.array([5,5]))\nworkspace.FeedBlob(\"min\", np.array(13, dtype=np.int32))\nworkspace.FeedBlob(\"max\", np.array(19, dtype=np.int32))\nworkspace.RunOperatorOnce(op_2)\nprint(\"output (op_2):\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\noutput (op_1):\n [[ 6 10 7]\n [ 5 10 6]\n [ 7 5 10]]\noutput (op_2):\n [[19 13 15 13 13]\n [14 17 14 15 15]\n [17 14 19 13 13]\n [17 18 16 13 18]\n [14 15 16 18 16]]\n\n```\n\n
\n\n ","inputs":[{"description":"(*Tensor``*): 1-D tensor of the shape of the output, must be used with `input_as_shape` argument","name":"shape"},{"description":"(*Tensor``*): scalar tensor containing minimum value, inclusive","name":"min"},{"description":"(*Tensor``*): scalar tensor containing maximum value, inclusive","name":"max"}],"outputs":[{"description":"(*Tensor``*): filled output tensor","name":"output"}],"support_level":"default"}},{"name":"PackRecords","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nGiven a dataset under a schema specified by the `fields` argument, pack all\nthe input tensors into one, where each tensor element represents a row of data\n(batch of size 1). This format allows easier use with the rest of Caffe2\noperators.\n","outputs":[{"description":"One dimensional tensor having a complex type of SharedTensorVectorPtr. In order to reverse it back to the original input it has to be inserted into UnPackRecordsOp.","name":"tensor"}],"support_level":"default"}},{"name":"Conditional","schema":{"description":"\nGiven a 1-D tensor of boolean values, apply conditional operator along the first\ndimension of DataT and DataF and return DataO. Note, DataT and DataF must\nhave the exact same shape and type.\n","inputs":[{"description":"Boolean tensor to select DataT or DataF","name":"Condition"},{"description":"Data to use when True","name":"DataT"},{"description":"Data to use when False","name":"DataF"}],"outputs":[{"description":"Output data after applying ConditionalOp","name":"DataO"}],"support_level":"default"}},{"name":"CopyFromCPUInput","schema":{"description":"\nTake a CPU input tensor and copy it to an output in the current\nContext (GPU or CPU). This may involves cross-device MemCpy.\n","inputs":[{"description":"The input CPU tensor.","name":"input"}],"outputs":[{"description":"either a TensorCUDA or a TensorCPU","name":"output"}],"support_level":"default"}},{"name":"MaxPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"CollectAndDistributeFpnRpnProposals","schema":{"attributes":[{"description":"(int) ROI_CANONICAL_SCALE","name":"roi_canonical_scale","option":"optional"},{"description":"(int) ROI_CANONICAL_LEVEL","name":"roi_canonical_level","option":"optional"},{"description":"(int) ROI_MAX_LEVEL","name":"roi_max_level","option":"optional"},{"description":"(int) ROI_MIN_LEVEL","name":"roi_min_level","option":"optional"},{"description":"(int) RPN_MAX_LEVEL","name":"rpn_max_level","option":"optional"},{"description":"(int) RPN_MIN_LEVEL","name":"rpn_min_level","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"rpn_post_nms_topN","option":"optional"}],"description":"\nMerge RPN proposals generated at multiple FPN levels and then\ndistribute those proposals to their appropriate FPN levels for Faster RCNN.\nAn anchor at one FPN level may predict an RoI that will map to another level,\nhence the need to redistribute the proposals.\n\nOnly inference is supported. To train, please use the original Python\noperator in Detectron.\n\nInputs and outputs are examples only; if min/max levels change,\nthe number of inputs and outputs, as well as their level numbering,\nwill change.\n","inputs":[{"description":"RPN proposals for FPN level 2, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn2"},{"description":"RPN proposals for FPN level 3, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn3"},{"description":"RPN proposals for FPN level 4, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn4"},{"description":"RPN proposals for FPN level 5, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn5"},{"description":"RPN proposals for FPN level 6, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn6"},{"description":"RPN objectness probabilities for FPN level 2. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn2"},{"description":"RPN objectness probabilities for FPN level 3. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn3"},{"description":"RPN objectness probabilities for FPN level 4. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn4"},{"description":"RPN objectness probabilities for FPN level 5. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn5"},{"description":"RPN objectness probabilities for FPN level 6. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn6"}],"outputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"},{"description":"RPN proposals for ROI level 2, format (image_index, x1, y1, x2, y2)","name":"rois_fpn2"},{"description":"RPN proposals for ROI level 3, format (image_index, x1, y1, x2, y2)","name":"rois_fpn3"},{"description":"RPN proposals for ROI level 4, format (image_index, x1, y1, x2, y2)","name":"rois_fpn4"},{"description":"RPN proposals for ROI level 5, format (image_index, x1, y1, x2, y2)","name":"rois_fpn5"},{"description":"Permutation on the concatenation of all rois_fpni, i=min...max, such that when applied the RPN RoIs are restored to their original order in the input blobs.","name":"rois_idx_restore"}],"support_level":"default"}},{"name":"ScatterAssign","schema":{"description":"\nUpdate slices of the tensor in-place by overriding current value.\n\nNote: The op pretty much ignores the exact shapes of the input arguments and\ncares only about sizes. It's done for performance consideration to avoid\nunnecessary reshapes. Only first dimension of X_0 is important, let's call it\nN. If M is the total size of X_0 and K is the size of INDICES then X_i is\nassumed to be of shape K x (M / N) regardless of the real shape.\n\nNote: Each update in INDICES is applied independently which means that if\nduplicated elements are present in INDICES arbitrary one will win.\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"DATA"},{"description":"1-D list of indices on the first dimensionof X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"SLICES"}],"outputs":[{"description":"Has to be exactly the same tensor as the input 0","name":"DATA"}],"support_level":"default"}},{"name":"FusedRandRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the FloatToFusedRandRowwiseQuantized operator.\nRefer FloatToFusedRandRowwiseQuantized operator for details.\n","inputs":[{"description":"Fused bitwidth, tail, min, max and quantized data","name":"quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_input"}],"support_level":"default"}},{"name":"MergeSingleMapFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with map features into multiple single-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".presence","name":"in1_presence"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values_grad","name":"in1_values_grad"}],"support_level":"default"}},{"name":"TopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"SinGradient","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorIntFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Int8MaxPool","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"MaxPool \nconsumes an input blob X and applies max pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Max pooling consisting of taking the maximum value of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linear","name":"Y"}],"support_level":"default"}},{"name":"Int8Dequantize","schema":{"description":null,"inputs":[{"description":"Int8 Tensor qX.","name":"qX"}],"outputs":[{"description":"FP32 Tensor that represents mapped real value of qX.","name":"Y"}],"support_level":"default"}},{"name":"Adagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 1. If it is in (0, 1), the gradient square sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nComputes the AdaGrad update for an input gradient and accumulated\nhistory. Concretely, given inputs (param, grad, moment, learning_rate),\ncomputes\n\n new_moment = moment + square(grad)\n effective_lr = learning_rate / (sqrt(new_moment) + epsilon)\n update = learning_rate * grad / (sqrt(new_moment) + epsilon)\n new_param = param + update\nand returns (new_param, new_moment).\n\nOptionally returns effective_lr and update as well.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"(optional) Effective learning rate","name":"output_effective_lr"},{"description":"(optional) Actual update that is applied.","name":"output_update"}],"support_level":"default"}},{"name":"ConstantFill","schema":{"attributes":[{"description":"value to populate output tensor with.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from *DataType* enum in TensorProto.","name":"dtype","option":"optional","type":"int64"},{"description":"Shape of the output tensor. Cannot pass an input blob and this arg at the same time.","name":"shape","option":"optional"},{"description":"Additional dimensions appended at the end of the shape indicated by the input blob. Cannot set thisargument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nThis operator fills the elements of the output tensor with a constant value\nspecified by the `value` argument.\n\n- The data type is specified by the `dtype` argument\n\n- Currently, the data types supported are *float*, *int32*, *int64*, and *bool*\n\n- If the `dtype` argument is not provided, the data type of `value` is used\n\n- The output tensor shape is either specified by the `shape` argument or will\nmatch the shape of the input tensor if one is provided (if an input tensor is\nprovided, a shape argument should not be set)\n\n- Optional additional dimensions can be appended at the end as specified by\n`extra_shape` argument\n\n- If `input_as_shape` is set to True, the input should be a 1D tensor\ncontaining the desired output shape (the dimensions specified in `extra_shape`\nwill also be appended)\n\n- If a second input V is passed, fill the output with the first element of V\n\nWhen specifying `dtype` argument, use the integer keys from the *DataType* enum\nin TensorProto:\n\n```\nmessage TensorProto {\n ...\n enum DataType {\n UNDEFINED = 0;\n FLOAT = 1; // float\n INT32 = 2; // int\n BYTE = 3; // BYTE, when deserialized, is going to be restored as uint8.\n STRING = 4; // string\n BOOL = 5; // bool\n UINT8 = 6; // uint8_t\n INT8 = 7; // int8_t\n UINT16 = 8; // uint16_t\n INT16 = 9; // int16_t\n INT64 = 10; // int64_t\n FLOAT16 = 12; // at::Half\n DOUBLE = 13; // double\n }\n```\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConstantFill\",\n [],\n [\"Y\"],\n shape=(1,5,5)\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nY: [[[0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]]]\n```\n
\n\n
\n Example 2 \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConstantFill\",\n [\"X\"],\n [\"Y\"],\n value=4.0,\n dtype=1,\n extra_shape=(1,2)\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[86. 30. 84.]\n [34. 51. 9.]\n [29. 86. 59.]]\nY: [[[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]\n\n\n [[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]\n\n\n [[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* [OPTIONAL] Input tensor to provide shape information.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Output tensor of constant values.","name":"Y"}],"support_level":"default"}},{"name":"FloatToFused8BitRowwiseQuantized","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 8 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.\nFor N-dimensional input tensor, the first N-1 dimensions are interpreted as\nrows and the last dimension is interpreted as a column. For example, an\ninput tensor with dimension 5x2x4 is interpreted as 10 rows and 4 columns.\n)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Conv3D","schema":{"description":"\nThe convolution operator consumes an input vector, a 3D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"LSTMUnit","schema":{"attributes":[{"description":"Bias term to add in while calculating forget gate","name":"forget_bias","option":"optional"},{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":"\nLSTMUnit computes the activations of a standard LSTM (without peephole\nconnections), in a sequence-length aware fashion.\n\nConcretely, given the (fused) inputs X (TxNxD), the previous cell\nstate (NxD), and the sequence lengths (N), computes the LSTM\nactivations, avoiding computation if the input is invalid (as in, the\nvalue at X{t][n] >= seqLengths[n].\n\n","support_level":"default"}},{"name":"SortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherByKey","schema":{"description":"\nInverse operation of Partition.\n\nTakes the original, full 'keys' tensor followed by sharded value tensors,\nand returns the full value tensor, combined using the same hash used in\nPartition.\n","inputs":[{"description":"The first input is the full keys tensor (same as the first input of Partition).","name":"keys"},{"description":"Subsequented inputs are sharded values tensors.","name":"sharded_values"}],"outputs":[{"description":"Reconstructed values tensor.","name":"values"}],"support_level":"default"}},{"name":"ReduceMean","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **mean** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceMean\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[9. 0. 3. 6. 0.]\n [3. 4. 5. 0. 9.]\n [6. 9. 1. 1. 5.]\n [6. 2. 3. 7. 7.]\n [3. 1. 1. 0. 1.]]\n\n [[4. 3. 9. 8. 1.]\n [8. 2. 0. 4. 0.]\n [8. 9. 9. 0. 2.]\n [7. 2. 5. 8. 9.]\n [5. 9. 1. 9. 0.]]]]\nY:\n[[6.5 1.5 6. 7. 0.5]\n [5.5 3. 2.5 2. 4.5]\n [7. 9. 5. 0.5 3.5]\n [6.5 2. 4. 7.5 8. ]\n [4. 5. 1. 4.5 0.5]]\n\n```\n\n
\n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"IntIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps int32 keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handler"}],"support_level":"default"}},{"name":"Div","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Div\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[18,8],[2,9]]))\nworkspace.FeedBlob(\"B\", np.array([[9,2],[3,2]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[18 8]\n [ 2 9]]\nB:\n[[9 2]\n [3 2]]\nC:\n[[2 4]\n [0 4]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"WeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"TimerBegin","schema":{"attributes":[{"description":"(*str*): name of the timer object; if not set use output name","name":"counter_name","option":"optional"}],"description":"\nStart a wallclock timer, returning a scalar tensor containing a pointer to it. The timer is stopped by calling **TimerEnd**.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","outputs":[{"description":"(*Tensor``*): pointer to a timer object","name":"timer"}],"support_level":"default"}},{"name":"UnpackSegments","schema":{"attributes":[{"description":"The pre-defined max_length for the packed segments","name":"max_length","option":"optional"}],"description":"Map N+1 dim tensor to N dim based on length blob","inputs":[{"description":"1-d int/long tensor contains the length in each of the input.","name":"lengths"},{"description":"N+1 dim Tensor.","name":"tensor"}],"outputs":[{"description":"N dim Tensor","name":"packed_tensor"}],"support_level":"default"}},{"name":"ThresholdedRelu","schema":{"attributes":[{"description":"(float) defaults to 1.0.","name":"alpha","option":"optional"}],"description":"\nThresholdedRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = x for x > alpha, y = 0\notherwise, is applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseSortedSegmentSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentSum that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Checkpoint","schema":{"attributes":[{"description":"(int, default 0) if set, use the db path directly and do not prepend the current root folder of the workspace.","name":"absolute_path","option":"optional"},{"description":"(string) a template string that one can combine with the iteration to create the final db name. For example, \"/home/lonestarr/checkpoint_%08d.db\"","name":"db","option":"optional"},{"description":"(string) the type of the db.","name":"db_type","option":"optional"},{"description":"(int, default 1) the checkpointing is carried out when (iter mod every) is zero.","name":"every","option":"optional"}],"description":"\nThe Checkpoint operator is similar to the Save operator, but allows one to save\nto db every few iterations, with a db name that is appended with the iteration\ncount. It takes [1, infinity) number of inputs and has no output. The first\ninput has to be a TensorCPU of type int and has size 1 (i.e. the iteration\ncounter). This is determined whether we need to do checkpointing.\n","support_level":"default"}},{"name":"LengthsIndicesInGradientMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"MaxPool1D","schema":{"description":"MaxPool1D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Atan","schema":{"description":"\nCalculates the arctangent of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arctangent of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"PythonDLPack","schema":{"description":null,"support_level":"default"}},{"name":"CTCBeamSearchDecoder","schema":{"attributes":[{"description":"Maximum number of candidates to carry over to next activation step.","name":"beam_width","option":"optional"},{"description":"Probability threshold below which outputs are ignored.","name":"prune_threshold","option":"optional"}],"description":"Prefix beam search decoder for connectionist temporal classification.","inputs":[{"description":"3D float Tensor sized [max_activation_length, batch_size, alphabet_size] of network logits (before softmax application).","name":"INPUTS"},{"description":"(optional) 1D int vector containing sequence lengths, having size [batch_size] seq_len will be set to max_time if not provided.","name":"SEQ_LEN"}],"outputs":[{"description":"Output_len matrix size (batch_size * num_candidates). Each index stores lengths of candidates for its corresponding batch item.","name":"OUTPUT_LEN"},{"description":"Values vector, size (total_decoded_outputs). The flattened vector of final output sequences, in batch order.","name":"VALUES"},{"description":"Probability vector, size (total_decoded_outputs). Each index stores final output probability of its corresponding batch item.","name":"OUTPUT_PROB"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"WeightedSampleDequeueBlobs","schema":{"attributes":[{"description":"Weights for sampling from multiple queues","name":"weights","option":"optional"},{"description":"The index of the blob (among the output blob list) that will be used to store the index of the table chosen to read the current batch.","name":"table_idx_blob","option":"optional"}],"description":"\nDequeue the blobs from multiple queues. When one of queues is closed and empty,\nthe output status will be set to true which can be used as exit criteria for\nexecution step.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","support_level":"default"}},{"name":"SigmoidCrossEntropyWithLogitsGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8RoIAlign","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nRegion of Interest (RoI) align operation as used in Mask R-CNN.\n","inputs":[{"description":"4D Int8 Tensor feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 4 or 5) specifying R RoIs representing: batch index in [0, N - 1], x1, y1, x2, y2. The RoI coordinates are in the coordinate system of the input image. For inputs corresponding to a single image, batch index can be excluded to have just 4 columns.","name":"RoIs"}],"outputs":[{"description":"4D Int8 Tensor output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"SortedSegmentRangeLogMeanExpGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsSum","schema":{"description":"\nApplies 'Sum' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Sum' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n\n\nThe *LengthsSum* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the sum in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [sum([2,4]), sum([3,1,2]), sum([10])] = [6,6,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsSum\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 6. 6. 10.]\n\n```\n\n
\n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"DequeueBlobs","schema":{"attributes":[{"description":"Timeout in secs, default: no timeout","name":"timeout_secs","option":"optional"}],"description":"\n Dequeue the blobs from queue.\n ","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"outputs":[{"description":"The blob to store the dequeued data","name":"blob"}],"support_level":"default"}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Defines alpha parameter used in calculation.","name":"alpha","option":"optional","type":"float32"}],"description":"\n\nThis op implements the exponential linear unit (ELU) activation function as described in [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)](https://arxiv.org/abs/1511.07289). The op takes an input tensor $X$ of arbitrary shape, computes the elementwise elu operation, and returns a vector $Y$ of the same shape as output. The alpha parameter may be passed as an argument, but defaults to 1. The elu operation is defined as\n\n$$y=f(x) =\\begin{cases}\\alpha(e^x-1) & x < 0 \\\\ x & otherwise\\end{cases}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elu_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Elu\",\n [\"X\"],\n [\"Y\"],\n alpha=1.1\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 0.35339102 1.1860217 -0.10710736]\n [-3.1173866 -0.1889988 -0.20330353]\n [ 1.8525308 -0.368949 0.506277 ]]\n\nY:\n [[ 0.35339102 1.1860217 -0.11172786]\n [-1.0513 -0.18943374 -0.20236646]\n [ 1.8525308 -0.33939326 0.506277 ]]\n\n```\n\n
\n\n","inputs":[{"description":"1D input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"1D input tensor, calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicates up to which input dimensions (exclusive) should be flattened to the outer dimension of the output.","name":"axis","option":"optional","type":"int64"}],"description":"\nFlattens the input tensor into a 2D matrix. If input tensor has shape\n$(d_0, d_1, ..., d_n)$ then the output will have shape\n$\\bigl((d_0 * d_1 * ... * d_{(axis-1)}), (d_{axis} * d_{(axis+1)} * ... * d_n)\\bigr)$.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/flatten_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Flatten\",\n [\"X\"],\n [\"Y\"],\n axis=1\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(1,3,2,2))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[[[0.53432311 0.23734561]\n [0.56481598 0.52152617]]\n\n [[0.33662627 0.32472711]\n [0.17939016 0.97175851]]\n\n [[0.87226421 0.49045439]\n [0.92470531 0.30935077]]]]\nY: [[0.53432311 0.23734561 0.56481598 0.52152617 0.33662627 0.32472711\n 0.17939016 0.97175851 0.87226421 0.49045439 0.92470531 0.30935077]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input Tensor of rank >= axis.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* A 2D tensor with the contents of the input tensor, with input dimensions up to `axis` flattened to the outer dimension of the output and the remaining input dimensions flattened into the inner dimension of the output.","name":"Y"}],"support_level":"default"}},{"name":"MaxPool1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeLogSumExp","schema":{"description":"\nApplies 'LogSumExp' to each segment of input tensor. In order to allow for more\nefficient implementation of 'LogSumExp', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nLogSumExp computes the element-wise log of the sum of exponentials of input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"SumElementsGradient","schema":{"description":null,"support_level":"default"}},{"name":"RetrieveCount","schema":{"description":"\nRetrieve the current value from the counter as an integer.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* Current count value.","name":"count"}],"support_level":"default"}},{"name":"CopyRowsToTensorGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnsureClipped","schema":{"description":"\nGiven a tensor, apply clip after gradient is applied; when the param is sparse as\nindicated by valid indices and grad, in-place is required\n","inputs":[{"description":"Parameters to be normalized","name":"param"},{"description":"Sparse indices, only needed for sparse param","name":"indices"},{"description":"Gradient computed, only needed for sparse param","name":"grad"}],"outputs":[{"description":"param ensured to be clipped within range","name":"output_param"}],"support_level":"default"}},{"name":"WeightedSigmoidCrossEntropyWithLogits","schema":{"description":"\nGiven three matrices: logits, targets, weights, all of the same shape,\n(batch_size, num_classes), computes the weighted sigmoid cross entropy between\nlogits and targets. Specifically, at each position r,c, this computes\nweights[r, c] * crossentropy(sigmoid(logits[r, c]), targets[r, c]), and then\naverages over each row.\nReturns a tensor of shape (batch_size,) of losses for each example.\n","inputs":[{"description":"matrix of logits for each example and class.","name":"logits"},{"description":"matrix of targets, same shape as logits.","name":"targets"},{"description":"matrix of weights, same shape as logits.","name":"weights"}],"outputs":[{"description":"Vector with the total xentropy for each example.","name":"xentropy"}],"support_level":"default"}},{"name":"IndexLoad","schema":{"attributes":[{"description":"If set, skips the first entry of the tensor. This allows to load tensors that are aligned with an embedding, where the first entry corresponds to the default 0 index entry.","name":"skip_first_entry","option":"optional"}],"description":"\nLoads the index from the given 1-D tensor. Elements in the tensor will be given\nconsecutive indexes starting at 1. Fails if tensor contains repeated elements.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"},{"description":"1-D tensor with elements starting with index 1.","name":"items"}],"outputs":[{"description":"The input handle.","name":"handle"}],"support_level":"default"}},{"name":"BatchDenseToSparse","schema":{"description":"\nThis Op is a inverse of BatchSparseToDenseOp.\nBasically, given a `lengths` vector, a `indices` vector,\nand a dense matrix `dense`, output `value` vector so that, along with\n`lengths` vector and `indices` vector, forms a sparse representation\nof the dense matrix.\n\nA sparse matrix is represented by `lengths` vector, `indices` vector,\nand `values` vector. Each element in `lengths` vector (lengths[`i`]) represents\nthe number of indices in this batch (batch `i`).\nWith in each batch, `indices` should not have duplicate number.\n\nFor example, with input:\n\n lengths = [2, 3, 1]\n indices = [0, 1, 2, 3, 4, 5]\n output = [[6, 7, 0, 0, 0, 0],\n [0, 0, 8, 9, 10, 0],\n [0, 0, 0, 0, 0, 11]]\n\nThe output is:\n\n values = [6, 7, 8, 9, 10, 11]\n\nafter running this operator.\n","inputs":[{"description":"Flatten lengths, Used to break down indices into per batch indices","name":"lengths"},{"description":"Flatten indices, tensor of total size = \\sum lengths, containing the indices ","name":"indices"},{"description":"dense 2-D tensor, first dim = len(lengths), last dim > Any(indices)","name":"dense"}],"outputs":[{"description":"Values, tensor of the same size as `indices` and same data type as dense tensor.","name":"values"}],"support_level":"default"}},{"name":"UniformFill","schema":{"attributes":[{"description":"(*float*): minimum value, inclusive","name":"min","option":"optional"},{"description":"(*float*): maximum value, inclusive","name":"max","option":"optional"},{"description":"(*Tuple(int)*): shape of the output, do not set when `input_as_shape`=1","name":"shape","option":"optional"},{"description":"(*int*): set to 1 to use the first input as shape; `shape` input must be in CPU context","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with float samples from uniform distribution [`min`, `max`].\n\n- The range can be defined either by arguments or input blobs. `min` and `max` are inclusive.\n - If the range is given by input blobs, you also need to give the shape as input.\n - When the range is given as arguments, this operator enforces min <= max. When the range is given as inputs, the constraint is not enforced.\n - When the range is given as inputs and max < min, the first dimension of the output is set to 0. This behavior is allowed so that dynamically sampling indices into a dynamically sized tensor is possible.\n- The shape of the output can be given as argument or input.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop_1 = core.CreateOperator(\n \"UniformFill\",\n [],\n [\"output\"],\n min=5.5,\n max=10.5,\n shape=(3,3)\n)\n\nop_2 = core.CreateOperator(\n \"UniformFill\",\n [\"shape\", \"min\", \"max\"],\n [\"output\"],\n input_as_shape=1\n)\n\n// Test arg-based op\nworkspace.RunOperatorOnce(op_1)\nprint(\"output (op_1):\\n\", workspace.FetchBlob(\"output\"))\n\n// Test input-based op\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"shape\", np.array([5,5]))\nworkspace.FeedBlob(\"min\", np.array(13.8, dtype=np.float32))\nworkspace.FeedBlob(\"max\", np.array(19.3, dtype=np.float32))\nworkspace.RunOperatorOnce(op_2)\nprint(\"output (op_2):\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\noutput (op_1):\n [[8.894862 8.225005 6.7890406]\n [9.588293 7.1072135 7.7234955]\n [8.210596 6.0202913 9.665462 ]]\noutput (op_2):\n [[18.965155 15.603871 15.038921 17.14872 18.134571]\n [18.84237 17.845276 19.214737 16.970337 15.494069]\n [18.754795 16.724329 15.311974 16.962536 18.60965 ]\n [15.186268 15.264773 18.73341 19.077969 14.237255]\n [15.917589 15.844325 16.248466 17.006554 17.502048]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): 1-D tensor of the shape of the output, must be used with `input_as_shape` argument","name":"shape"},{"description":"(*Tensor``*): scalar tensor containing minimum value, inclusive","name":"min"},{"description":"(*Tensor``*): scalar tensor containing maximum value, inclusive","name":"max"}],"outputs":[{"description":"(*Tensor``*): filled output tensor","name":"output"}],"support_level":"default"}},{"name":"ChannelStats","schema":{"description":"\nGiven an input tensor in NCHW format, computes the sum of all elements per\nchannel and the sum of all elements squared per channel. These values can be\nreduced across multiple batches and used to obtain the mean and variance across\nthe full set of batches. Using the new mean and variance as input to SpatialBN\nhas the effect of changing the batch size over which SpatialBN is applied.\n","inputs":[{"description":"The input 4-dimensional tensor of shape NCHW","name":"X"}],"outputs":[{"description":"The output 1-dimensional tensor of size C containing the sum of elements of X per channel.","name":"sum"},{"description":"The output 1-dimensional tensor of size C containing the sum of elements squared per channel.","name":"sumsq"}],"support_level":"default"}},{"name":"FCTransposed","schema":{"description":"\nSame as FC, but weight matrix is supposed to be already pretransposed.\nFCTransposed stands for calling blass with no noTrans, noTrans\n","support_level":"default"}},{"name":"SortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"LC2D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 2D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"RoIPool","schema":{"attributes":[{"description":"If set, run in test mode and skip computation of argmaxes (used for gradient computation). Only one output tensor is produced. (Default: false).","name":"is_test","option":"optional"},{"description":"A StorageOrder string (Default: \"NCHW\").","name":"order","option":"optional"},{"description":"The pooled output height (Default: 1).","name":"pooled_h","option":"optional"},{"description":"The pooled output width (Default: 1).","name":"pooled_w","option":"optional"},{"description":"Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling (Default: 1.0).","name":"spatial_scale","option":"optional"}],"description":"\nCarries out ROI Pooling for Faster-RCNN.\nDepending on the mode, there are multiple output cases:\n\n Output case #1: Y, argmaxes (train mode)\n Output case #2: Y (test mode)\n","inputs":[{"description":"The input 4-D tensor of data. Only NCHW order is currently supported.","name":"X"},{"description":"RoIs (Regions of Interest) to pool over. Should be a 2-D tensor of shape (num_rois, 5) given as [[batch_id, x1, y1, x2, y2], ...].","name":"rois"}],"outputs":[{"description":"RoI pooled output 4-D tensor of shape (num_rois, channels, pooled_h, pooled_w).","name":"Y"},{"description":"Argmaxes corresponding to indices in X used for gradient computation. Only output if arg \"is_test\" is false.","name":"argmaxes"}],"support_level":"default"}},{"name":"ElementwiseLinear","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs; defaults to one because the 0th axis most likely describes the batch size.","name":"axis","option":"optional","type":"int64"}],"description":"\nThis op computes the elementwise linear combination of a batch of input vectors with a weight vector and bias vector. As input, the op takes an input tensor $X$ of shape $NxD$, a weight vector $w$ of length $D$, and a bias vector $b$ of length $D$. Here, $N$ represents the batch size and $D$ represents the length of the feature vectors. The output, $Y$, is a tensor of shape $NxD$ and is calculated as\n\n$$Y_{ij} = X_{ij}w_j + b_j \\ for \\ i\\in{N}, j\\in{D}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_linear_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_linear_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ElementwiseLinear\",\n [\"X\", \"w\", \"b\"],\n [\"Y\"]\n)\n\n// Create X\nX = np.array([[1,2,3,4,5],[6,8,9,16,10]])\nprint(\"X:\\n\",X)\n\n// Create w\nw = np.array([1,1/2.,1/3.,1/4.,1/5.])\nprint(\"w:\\n\",w)\n\n// Create b\nb = np.array([1.,1.,1.,1.,1.])\nprint(\"b:\\n\",b)\n\n\n// Feed X & w & b into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"w\", w.astype(np.float32))\nworkspace.FeedBlob(\"b\", b.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 1 2 3 4 5]\n [ 6 8 9 16 10]]\nw:\n [1. 0.5 0.33333333 0.25 0.2]\nb:\n [1. 1. 1. 1. 1.]\nY:\n [[2. 2. 2. 2. 2.]\n [7. 5. 4. 5. 3.]]\n\n```\n\n
\n\n ","inputs":[{"description":"2D input tensor of size $NxD$. This input represents the input data to be operated on.","name":"X"},{"description":"1D scaling factors, or weights, of size $D$. This input contains the weights that will be multiplied by the data.","name":"w"},{"description":"1D biases of size $D$. This input contains the biases that will be added to the products of the weights and data.","name":"b"}],"outputs":[{"description":"2D output tensor of size $NxD$. Calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"LengthsSplit","schema":{"attributes":[{"description":"Number of splits for each element in LENGTHS","name":"n_split","option":"optional"}],"description":"\nGiven input vector LENGTHS, and input n_split, LengthsSplit returns\na single output vector. It \"splits\" each length into n_split values which add\nup to the original length. It will attempt to do equal splits, and if not possible,\nit orders larger values first. If the n_split is larger than the length, zero\npadding will be applied.\n\ne.g. LENGTHS = [9 4 5]\n n_split = 3\n Y = [3 3 3 2 1 1 2 2 1]\n\ne.g. LENGTHS = [2, 1, 2]\n n_split = 3\n Y = [1 1 0 1 0 0 1 1 0]\n","inputs":[{"description":"Mx1 Input tensor denoting INT32 lengths","name":"LENGTHS"},{"description":"(Optional) Number of splits for each element in LENGTHS (overrides argument)","name":"n_split"}],"outputs":[{"description":"(M*n_split)x1 Output vector denoting split lengths","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sub","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sub\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[10,12],[4,14]]))\nworkspace.FeedBlob(\"B\", np.array([[5,16],[1,19]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[10 12]\n [ 4 14]]\nB:\n[[ 5 16]\n [ 1 19]]\nC:\n[[ 5 -4]\n [ 3 -5]]\n\n```\n\n
\n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"Adadelta","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 0.95, the squared gradient sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nComputes the AdaDelta update (https://arxiv.org/abs/1212.5701) for an input\ngradient and accumulated history of squared gradients. Concretely, given\ninputs (param, moment, moment_delta, grad, learning_rate), computes:\n\n new_moment = moment * decay + square(grad) * (1 - decay)\n new_grad = sqrt(moment_delta + epsilon) / sqrt(new_moment + epsilon) * grad\n new_param = param + learning_rate * new_grad\n new_moment_delta = moment_delta * decay + square(new_grad) * (1 - decay)\n\nand returns (new_param, new_moment, new_moment_delta).\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Average of squared gradients","name":"moment"},{"description":"Average of squared parameter updates","name":"moment_delta"},{"description":"Gradient computed","name":"grad"},{"description":"Learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated average squared gradient","name":"output_moment"},{"description":"Updated average of squared parameter updates","name":"output_moment_delta"}],"support_level":"default"}},{"name":"If","schema":{"attributes":[{"description":"Net executed when condition is true","name":"then_net","option":"optional"},{"description":"Net executed when condition is false (optional)","name":"else_net","option":"optional"}],"description":"\n'If' control operator, first input is a scalar boolean blob that stores condition\nvalue. Accepts 'then_net' (required) and 'else_net' (optional) arguments for 'then' and\n'else' subnets respectively. Subnets are executed in the same workspace as 'If'.\n ","inputs":[{"description":"Scalar boolean condition","name":"condition"}],"support_level":"default"}},{"name":"IntegralImage","schema":{"description":"\nComputes an integral image, which contains the sum of pixel values within\nan image vertically and horizontally. This integral image can then be used\nwith other detection and tracking techniques.\n","inputs":[{"description":"Images tensor of the form (N, C, H, W)","name":"X"}],"outputs":[{"description":"Integrated image of the form (N, C, H+1, W+1)","name":"Y"}],"support_level":"default"}},{"name":"LengthsWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'WeightedSum' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n\n\nThe *LengthsWeightedSum* op takes three inputs *DATA*, *LENGTHS*, and *SCALARS*, and produces a single output *OUTPUT*. The op finds the weighted sum in each of the segments of *DATA*, where segments are defined by their lengths. Before calculating the sums, the input *DATA* is weighted by the contents of *SCALARS*.\nFor example, if $DATA = [2,4,3,1,2,10]$, $SCALARS = [8, 2, 1, 4, 1, 0.6]$, and $LENGTHS = [2,3,1]$, then $OUTPUT = [sum([8*2,2*4]), sum([1*3,4*1,1*2]), sum([0.6*10])] = [24,9,6]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsWeightedSum\",\n [\"DATA\", \"SCALARS\",\"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"SCALARS\", np.array([8, 2, 1, 4, 1, 0.6]).astype(np.float32))\nprint(\"SCALARS:\\n\", workspace.FetchBlob(\"SCALARS\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nSCALARS:\n [8. 2. 1. 4. 1. 0.6]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [24. 9. 6.]\n\n```\n\n
\n\n\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"Print","schema":{"attributes":[{"description":"(bool) if 1, saves contents to the root folder of the current workspace, appending the tensor contents to a file named after the blob name. Otherwise, logs to stderr.","name":"to_file","option":"optional"},{"description":"(int, default 0) If set, prints the first `limit` elements of tensor. If 0, prints the first `k_limit_default`(1000) elements of tensor","name":"limit","option":"optional"},{"description":"(int, default 1) Print tensor every `every_n` runs","name":"every_n","option":"optional"}],"description":"Logs shape and contents of input tensor to stderr or to a file.","inputs":[{"description":"The tensor to print.","name":"tensor"}],"support_level":"default"}},{"name":"ReduceFrontMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"AsinGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseToDenseMask","schema":{"attributes":[{"description":"list(int) argument with desired ids on the 'dense' output dimension","name":"mask","option":"optional"},{"description":"bool whether to return presence mask, false by default","name":"return_presence_mask","option":"optional"}],"description":"\nConvert sparse representations to dense with given indices.\n\nTransforms a sparse representation of map represented as `indices`\nvector and `values` tensor into a compacted tensor where the first dimension\ncorresponds to each id provided in mask argument. Missing values are filled with\nthe value of `default_value`. After running this op:\n\n output[j, :] = values[i] // where mask[j] == indices[i]\n output[j, ...] = default_value // when mask[j] doesn't appear in indices\n\nIf `lengths` is provided and not empty, and extra \"batch\" dimension is prepended\nto the output.\n\n`values` and `default_value` can have additional matching dimensions, operation\nis performed on the entire subtensor in thise case.\n\nFor example, if `lengths` is supplied and `values` is 1-D vector of floats and\n`default_value` is a float scalar, the output is going to be a float matrix\nof size `len(lengths) X len(mask)`\n","inputs":[{"description":"1-D int32/int64 tensor of concatenated ids of data","name":"indices"},{"description":"Data tensor, first dimension has to match `indices`","name":"values"},{"description":"Default value for the output if the id is not present in `indices`. Must have the same type as `values` and the same shape, but without the first dimension","name":"default_value"},{"description":"Optional lengths to represent a batch of `indices` and `values`.","name":"lengths"}],"outputs":[{"description":"Output tensor of the same type as `values` of shape `[len(lengths), len(mask)] + shape(default_value)` (if `lengths` is not provided the first dimension is omitted)","name":"output"},{"description":"Bool tensor of shape `[len(lengths), len(mask)]` (if `lengths` is not provided the first dimension is omitted). True when a value for given id was present, false otherwise.","name":"presence_mask"}],"support_level":"default"}},{"name":"SparseToDenseMaskGradient","schema":{"description":"\nThe output is the gradient of the input value from SparseToDenseMask. The\ngradient for default_value has not been implemented.\n","support_level":"default"}},{"name":"LC3D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 3D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"UpsampleBilinear","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using bilinear\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input tensor","name":"X"},{"description":"1D, 2-element, Scales tensor, [height_scale, width_scale]","name":"scales"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"Append","schema":{"description":"\nAppend input `B` to the end of input `A`.\n\n- It is required that this operation run in-place, meaning that the input `A` blob must match the output blob.\n- All except the outer-most dimension must be the same between `A` and `B`.\n- Input `A` may have to be re-allocated in order for accommodate to the new size. Currently, an exponential growth ratio is used in order to ensure amortized constant time complexity.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dataset_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Append\",\n [\"A\", \"B\"],\n [\"A\"],\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(1,3,3)))\nworkspace.FeedBlob(\"B\", np.random.randint(10, size=(2,3,3)))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"A:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[[3 8 7]\n [1 6 6]\n [5 0 6]]]\nB:\n[[[4 3 1]\n [7 9 6]\n [9 4 5]]\n\n [[7 7 4]\n [9 8 7]\n [1 6 6]]]\nA:\n[[[3 8 7]\n [1 6 6]\n [5 0 6]]\n\n [[4 3 1]\n [7 9 6]\n [9 4 5]]\n\n [[7 7 4]\n [9 8 7]\n [1 6 6]]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): base input tensor of shape $(N, d_1, d_2, ..., d_n)$","name":"A"},{"description":"(*Tensor*): second input tensor of shape $(M, d_1, d_2, ..., d_n)$ to be appended to the base","name":"B"}],"outputs":[{"description":"(*Tensor*): output tensor of shape $(N+M, d_1, d_2, ..., d_n)$","name":"A"}],"support_level":"default"}},{"name":"AtomicIter","schema":{"description":"\nSimilar to Iter, but takes a mutex as the first input to make sure that\nupdates are carried out atomically. This can be used in e.g. Hogwild sgd\nalgorithms.\n","inputs":[{"description":"The mutex used to do atomic increment.","name":"mutex"},{"description":"The iter counter as an int64_t TensorCPU.","name":"iter"}],"support_level":"default"}},{"name":"StatRegistryUpdate","schema":{"description":"\nUpdate the given StatRegistry, or the global StatRegistry,\nwith the values of counters for the given keys.\n","inputs":[{"description":"1D string tensor with the key names to update.","name":"keys"},{"description":"1D int64 tensor with the values to update.","name":"values"},{"description":"If provided, update the given StatRegistry. Otherwise, update the global singleton.","name":"handle"}],"support_level":"default"}},{"name":"EnqueueRebatchingQueue","schema":{"attributes":[{"description":"Are we enqueuing a batch or just a single element. By default we enqueue single element.","name":"enqueue_batch","option":"optional"}],"description":"\nEnqueues Tensors into the queue.\nNumber of input tensors should be equal to the number of components passed\nduring creation of the queue.\nIf the Queue is closed this operation will fail.\nIf enqueue_batch argument is set. We will split the input tensors by the\nfirst dimension to produce single queue elements.\n","inputs":[{"description":"object representing the queue","name":"queue"},{"description":"First tensor to enque. ","name":"tensor"}],"support_level":"default"}},{"name":"SparseAdam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default false","name":"enableRAdam","option":"optional"}],"description":"\n\n Computes the Adam Update for the sparse case.\n Given inputs (param, moment1, moment2, indices, grad, lr, iter), runs the dense\n Adam on (param, moment1[indices], momemnt2[indices], lr, iter) and returns\n (new_param, new_moment1, new_moment2) as in dense case.\n Adam can be customized as Rectified Adam (RAdam) by setting enableRAdam = true.\n\n ","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"NormalizePlanarYUV","schema":{"description":null,"support_level":"default"}},{"name":"EnsureCPUOutput","schema":{"description":"\nThis Op always create TensorCPU output, and may involves cross-device MemCpy.\nUnder CPU Context, this Op takes TensorCPU as input. Under the CUDA Context,\nthis Op accepts either CUDA or CPU Tensor input.\n","inputs":[{"description":"The input CUDA or CPU tensor.","name":"input"}],"outputs":[{"description":"TensorCPU that is a copy of the input.","name":"output"}],"support_level":"default"}},{"name":"FindDuplicateElements","schema":{"description":"\nThe *FindDuplicateElements* op takes a single 1-D tensor *data* as input and returns a single 1-D output tensor *indices*. The output tensor contains the indices of the duplicate elements of the input, excluding the first occurrences. If all elements of *data* are unique, *indices* will be empty.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/find_duplicate_elements_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/find_duplicate_elements_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FindDuplicateElements\",\n [\"data\"],\n [\"indices\"],\n)\n\nworkspace.FeedBlob(\"data\", np.array([8,2,1,1,7,8,1]).astype(np.float32))\nprint(\"data:\\n\", workspace.FetchBlob(\"data\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"indices: \\n\", workspace.FetchBlob(\"indices\"))\n\n```\n\n**Result**\n\n```\n\ndata:\n [8. 2. 1. 1. 7. 8. 1.]\nindices:\n [3 5 6]\n\n```\n\n
\n\n\n ","inputs":[{"description":"a 1-D tensor.","name":"data"}],"outputs":[{"description":"Indices of duplicate elements in data, excluding first occurrences.","name":"indices"}],"support_level":"default"}},{"name":"BernoulliJSDGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv1D","schema":{"description":"\nThe convolution operator consumes an input vector, a 1D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"LengthsPad","schema":{"attributes":[{"description":"The value to pad the data","name":"padding_value","option":"optional"},{"description":"The target length of each segment","name":"target_length","option":"optional"}],"description":"\nGiven DATA tensor of rank r >= 1, and LENGTHS tensor of rank 1, pad each\nsegment in DATA with `value`, so that each segment's length is `target_length`.\nIf will throw, if there is segment of length larger than `target_length`.\n\nExample:\n DATA = [\n [2.3, 3.4],\n [4.5, 5.7],\n [6.8, 7.9],\n ]\n LENGTHS = [0, 1, 1, 1]\n and target_length = 2, padding value = -1.0\n OUTPUT = [\n [-1.0, -1.0],\n [-1.0, -1.0],\n [2.3, 3.4],\n [-1.0, -1.0],\n [4.5, 5.7],\n [-1.0, -1.0],\n [6.8, 7.9],\n [-1.0, -1.0],\n ]\n","inputs":[{"description":"Tensor of rank r >= 1. First dimension must be equal to the size of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Padded DATA tensor","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReadNextBatch","schema":{"attributes":[{"description":"Number of top-level entries to read.","name":"batch_size","option":"optional"}],"description":"\nRead the next batch of examples out of the given cursor and data blobs.\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nReadNextBatch is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing the next batch for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"IntegralImageGradient","schema":{"description":null,"support_level":"default"}},{"name":"Cast","schema":{"attributes":[{"description":"Data type to which the elements of the input tensor are cast. Strictly must be one of the types from *DataType* enum in TensorProto.","name":"to","option":"optional","type":"int64"}],"description":"\nCasts the elements of a given input tensor to a data type specified by the `to`\nargument and returns an output tensor of the same size in the converted type.\nThe `to` argument must be one of the data types specified in the *DataType*\nenum field in the TensorProto message (see below). If the `to` argument is not\nprovided or is not one of the enumerated types in *DataType*, Caffe2 throws an\nEnforce error.\n\nNOTE: Casting from strings is not supported, and casting to strings is only\nsupported on CPU.\n\nTensorProto *DataType* field:\n```\nmessage TensorProto {\n ...\n enum DataType {\n UNDEFINED = 0;\n FLOAT = 1; // float\n INT32 = 2; // int\n BYTE = 3; // BYTE, when deserialized, is going to be restored as uint8.\n STRING = 4; // string\n BOOL = 5; // bool\n UINT8 = 6; // uint8_t\n INT8 = 7; // int8_t\n UINT16 = 8; // uint16_t\n INT16 = 9; // int16_t\n INT64 = 10; // int64_t\n FLOAT16 = 12; // at::Half\n DOUBLE = 13; // double\n }\n```\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cast_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cast\",\n [\"X\"],\n [\"Y\"],\n to=2\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32)*10)\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[9.436466 5.8529844 0.54932857]\n [1.1583444 2.9936118 0.22950427]\n [3.9143739 3.4040766 8.905341 ]]\nY: [[9 5 0]\n [1 2 0]\n [3 3 8]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input tensor to be cast.","name":"X"}],"outputs":[{"description":"*(type: Tensor`<'to' type>`)* Output tensor with the same shape as input with type specified by the `to` argument.","name":"Y"}],"support_level":"default"}},{"name":"Barrier","schema":{"description":"\nDoes a barrier operation among the nodes.\n","inputs":[{"description":"The common world.","name":"comm_world"}],"support_level":"default"}},{"name":"SparseToDense","schema":{"description":"\nConvert sparse representations to dense with given indices.\n\nTransforms a sparse representation of map represented as `indices`\nvector and `values` tensor into a compacted tensor where the first dimension\nis determined by the first dimension of the 3rd input if it is given or the\nmax index. Missing values are filled with zeros.\n\nThe op supports duplicated indices and performs summation over corresponding\nvalues. This behavior is useful for converting GradientSlices into dense\nrepresentation.\n\nAfter running this op:\n\n output[indices[i], :] += values[i] // sum over all indices[i] equal to the index\n output[j, ...] = 0 if j not in indices\n","inputs":[{"description":"1-D int32/int64 tensor of concatenated ids of data","name":"indices"},{"description":"Data tensor, first dimension has to match `indices`, basic numeric types are supported","name":"values"},{"description":"Optional: if provided, the first dimension of output is the first dimension of this tensor.","name":"data_to_infer_dim"}],"outputs":[{"description":"Output tensor of the same type as `values` of shape `[len(lengths), len(mask)] + shape(default_value)` (if `lengths` is not provided the first dimension is omitted)","name":"output"}],"support_level":"default"}},{"name":"Iter","schema":{"description":"\nStores a singe integer, that gets incremented on each call to Run().\nUseful for tracking the iteration count during SGD, for example.\n","support_level":"default"}},{"name":"SparseLengthsMean8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsMean operator, where DATA is\nstored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"LE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise less or equal than comparison **<=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True False True True True True]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"Split","schema":{"attributes":[{"description":"(*int*): axis to split on","name":"axis","option":"optional"},{"description":"Pass non-zero integer to remove the axis specified in `axis` to all input tensors.","name":"add_axis","option":"optional","type":"int64"},{"description":"(*Tuple(int)*): length of each output","name":"split","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; either \"NCHW\" or \"NHWC\"","name":"order","option":"optional"}],"description":"\nSplit an `input` tensor into a list of tensors, along the axis specified by the `axis` dimension. The lengths of the split can be specified using argument `split` or optional second input blob to the operator. Otherwise, the tensor is split to equal sized parts.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Split\",\n [\"input\"],\n [\"output_0\",\"output_1\",\"output_2\"],\n split=(3,2,4),\n axis=0\n)\n\nworkspace.FeedBlob(\"input\", np.random.randint(10, size=(9)))\nprint(\"input:\", workspace.FetchBlob(\"input\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output_0:\", workspace.FetchBlob(\"output_0\"))\nprint(\"output_1:\", workspace.FetchBlob(\"output_1\"))\nprint(\"output_2:\", workspace.FetchBlob(\"output_2\"))\n\n```\n\n**Result**\n\n```\n\ninput: [2 2 6 6 6 0 5 7 4]\noutput_0: [2 2 6]\noutput_1: [6 6]\noutput_2: [0 5 7 4]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor*): tensor to split","name":"input"},{"description":"(*Tensor``*): [OPTIONAL] list of output lengths (see also arg `split`)","name":"split"}],"outputs":[{"description":"(*Tensor*): output tensor","name":"[output_0, output_1, ...]"}],"support_level":"default"}},{"name":"LengthsToWeights","schema":{"attributes":[{"description":"n of 1/pow(length,n) for normalization","name":"power","option":"optional"}],"description":"\nSimilar as LengthsToSegmentIds but output vector of segment\nweights derived by lengths. i.e 1/pow(length, power)\n","inputs":[{"description":"1-D int32_t or int64_t tensor of lengths","name":"lengths"}],"outputs":[{"description":"1-D float tensor of weights by length","name":"a vector of weights"}],"support_level":"default"}},{"name":"CreateAtomicBool","schema":{"description":"Create an unique_ptr blob to hold an atomic","outputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"}],"support_level":"default"}},{"name":"RsqrtGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherRanges","schema":{"description":"\nGiven DATA tensor of rank 1, and RANGES tensor of rank 3, gather\ncorresponding ranges into a 1-D tensor OUTPUT.\n\nRANGES dimentions description:\n1: represents list of examples within a batch\n2: represents list features\n3: two values which are start and length or a range (to be applied on DATA)\n\nAnother output LENGTHS represents each example length within OUTPUT\n\nExample:\n DATA = [1, 2, 3, 4, 5, 6]\n RANGES = [\n [\n [0, 1],\n [2, 2],\n ],\n [\n [4, 1],\n [5, 1],\n ]\n ]\n OUTPUT = [1, 3, 4, 5, 6]\n LENGTHS = [3, 2]\n","inputs":[{"description":"Tensor of rank 1.","name":"DATA"},{"description":"Tensor of int32/int64 ranges, of dims (N, M, 2). Where N is number of examples and M is a size of each example. Last dimension represents a range in the format (start, lengths)","name":"RANGES"}],"outputs":[{"description":"1-D tensor of size sum of range lengths","name":"OUTPUT"},{"description":"1-D tensor of size N with lengths over gathered data for each row in a batch. sum(LENGTHS) == OUTPUT.size()","name":"LENGTHS"}],"support_level":"default"}},{"name":"CrossEntropy","schema":{"description":"\nThis operator computes the cross entropy between a $NxD$ dimensional input data tensor $X$ and a $NxD$ dimensional input label tensor $label$. The op produces a single length $N$ output tensor $Y$. Here, $N$ is considered the batch size and $D$ is the size of each element in the batch. In practice, it is most commonly used at the end of models as a part of the loss computation, after the SoftMax operator and before the AveragedLoss operator. The cross entropy operation is defined as follows\n\n$$Y_i = \\sum_j (label_{ij} * log(X_{ij}))$$\n\nwhere ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"CrossEntropy\",\n [\"X\", \"label\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([[.01, .05, .02, .02, .9],[.03, .1, .42, .05, .4]])\nprint(\"X:\\n\",X)\n\n// Create label: Sample 1-hot ground truth label vectors\nlabel = np.array([[0.,0.,0.,0.,1.],[0.,0.,1.,0.,0.]])\nprint(\"label:\\n\",label)\n\n// Feed X & label into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"label\", label.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[0.01 0.05 0.02 0.02 0.9 ]\n [0.03 0.1 0.42 0.05 0.4 ]]\nlabel:\n [[0. 0. 0. 0. 1.]\n [0. 0. 1. 0. 0.]]\nY:\n [0.10536055 0.8675006 ]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input tensor which is almost always the result of a softmax operation. $X$ is a 2D array of size $NxD$, where $N$ is the batch size and $D$ is the number of classes.","name":"X"},{"description":"Blob containing the labels used to compare the input. $label$ is the same shape as $X$.","name":"label"}],"outputs":[{"description":"Output blob from the cross entropy computation. $Y$ is 1D length $N$ tensor.","name":"Y"}],"support_level":"default"}},{"name":"ReduceBackMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceBackMean","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **mean**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the mean operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [mean(1,5), mean(4,1,8), mean(2)] = [3, 4.333, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_mean_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackMean\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[5. 9. 0.]\n [8. 4. 0.]\n [2. 2. 4.]]\n\n [[9. 0. 9.]\n [7. 9. 7.]\n [1. 0. 2.]]]]\nY: [[3.7777777 4.888889 ]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ResizeNearest","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input tensor","name":"X"},{"description":"1D, 2-element, Scales tensor, [height_scale, width_scale]","name":"scales"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseDropoutWithReplacement","schema":{"attributes":[{"default":0,"description":"Probability of an element to be replaced.","name":"ratio","option":"optional","type":"float32"},{"default":0,"description":"Value elements are replaced with.","name":"replacement_value","option":"optional","type":"int64"}],"description":"\n\n`SparseDropoutWithReplacement` takes a 1-d input tensor and a lengths tensor.\nValues in the Lengths tensor represent how many input elements consitute each\nexample in a given batch. The set of input values for an example will be\nreplaced with the single dropout value with probability given by the `ratio`\nargument.\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SparseDropoutWithReplacement\",\n [\"X\", \"Lengths\"],\n [\"Y\", \"OutputLengths\"],\n ratio=0.5,\n replacement_value=-1\n)\n\nworkspace.FeedBlob(\"X\", np.array([1, 2, 3, 4, 5]).astype(np.int64))\nworkspace.FeedBlob(\"Lengths\", np.array([2, 3]).astype(np.int32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Lengths:\", workspace.FetchBlob(\"Lengths\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"OutputLengths:\", workspace.FetchBlob(\"OutputLengths\"))\n```\n\n**Result**\n\n```\nX: [1, 2, 3, 4, 5]\nLengths: [2, 3]\nY: [1, 2, -1]\nOutputLengths: [2, 1]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"},{"description":"*(type: Tensor``)* Lengths tensor for input.","name":"Lengths"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"},{"description":"*(type: Tensor``)* Output tensor.","name":"OutputLengths"}],"support_level":"default"}},{"name":"SparseWngrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nThis operator implement the optimization algorithm\nin https://arxiv.org/abs/1803.02865 by Wu, Ward and Bottou.\nGiven inputs (param, seq_b, indices, grad, lr), runs the dense WnGrad\nupdate on (param, grad, seq_b, lr), and returns (new_param,\nnew_seq_b) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"seq_b history","name":"seq_b"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated seq_b","name":"output_seq_b"}],"support_level":"default"}},{"name":"Find","schema":{"attributes":[{"description":"Placeholder for items that are not found","name":"missing_value","option":"optional"}],"description":"\nFinds elements of second input from first input,\noutputting the last (max) index for each query.\nIf query not find, inserts missing_value.\nSee IndexGet() for a version that modifies the index when\nvalues are not found.\n","inputs":[{"description":"Index (integers)","name":"index"},{"description":"Needles / query","name":"query"}],"outputs":[{"description":"Indices of the needles in index or 'missing value'","name":"query_indices"}],"support_level":"default"}},{"name":"BatchBucketOneHot","schema":{"description":"\nInput is a matrix tensor. Its first dimension is the batch\nsize. For each column, bucketize it based on the boundary values and then do\none hot encoding. The `lengths` specifies the number of boundary values for each\ncolumn. The final number of buckets is this number plus 1. This would also be\nthe expanded feature size. `boundaries` specifies all the boundary values.\nNote that each bucket is right-inclusive. That is, given boundary values\n[b1, b2, b3], the buckets are defined as (-int, b1], (b1, b2], (b2, b3], (b3, inf).\nFor example\n\n data = [[2, 3], [4, 1], [2, 5]], lengths = [2, 3],\n If boundaries = [0.1, 2.5, 1, 3.1, 4.5], then\n output = [[0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 1]]\n\n If boundaries = [0.1, 2.5, 1, 1, 3.1], then\n output = [[0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1]]\n\n","inputs":[{"description":"input tensor matrix","name":"data"},{"description":"the size is the same as the width of the `data`","name":"lengths"},{"description":"bucket boundaries","name":"boundaries"}],"outputs":[{"description":"output matrix that expands each input column with one hot encodingbased on the bucketization","name":"output"}],"support_level":"default"}},{"name":"PairWiseLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"ExpandGradient","schema":{"description":null,"support_level":"default"}},{"name":"BatchGather","schema":{"description":"\nBatch gather operation, first dimension in DATA is the batch size.\nGiven DATA tensor of rank r >= 2, and INDICES tensor of rank q >= 1, gather\nentries of the second outer dimension (axis == 1) of DATA indexed by INDICES,\nand concatenate them in an output tensor of rank q + (r - 1).\n\nExample:\n DATA = [\n [1.0, 1.2, 2.4, 4.5],\n [2.3, 3.4, 3.6, 2.3],\n [4.5, 5.7, 1.2, 4.5],\n ]\n INDICES = [0, 2]\n\n OUTPUT = [\n [1.0, 2.4],\n [2.3, 3.6],\n [4.5, 1.2],\n ]\n","inputs":[{"description":"Tensor of rank r >= 2.","name":"DATA"},{"description":"Tensor of int32/int64 indices, of any rank q.","name":"INDICES"}],"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Float16ConstantFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","option":"optional"},{"description":"The shape of the output tensor.","name":"shape","option":"optional"}],"description":null,"outputs":[{"description":"Output tensor of constant values specified by 'value'","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentWeightedSum that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"DequeueRebatchingQueue","schema":{"attributes":[{"description":"Number of elements to dequeue. By default we dequeue one element.","name":"num_elements","option":"optional"}],"description":"\nDequeue Tensors from the Queue.\nIf the Queue is closed this might return less elements than asked.\nIf num_elements > 1 the returned elements will be concatenated into one\ntensor per component.\n","inputs":[{"description":"object representing the queue","name":"rebatching_queue"},{"description":"First tensor to enqueue","name":"tensor"}],"support_level":"default"}},{"name":"StoreGet","schema":{"attributes":[{"description":"alternative key for the blob (optional)","name":"blob_name","option":"optional"}],"description":"\nGet a blob from a store. The key is the output blob's name. The key\ncan be overridden by specifying the 'blob_name' argument.\n","inputs":[{"description":"unique_ptr","name":"handler"}],"outputs":[{"description":"data blob","name":"data"}],"support_level":"default"}},{"name":"MergeMultiScalarFeatureTensors","schema":{"description":"Merge given multi-feature tensors with scalar features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values","name":"in1_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values","name":"out_values"}],"support_level":"default"}},{"name":"ReluNGradient","schema":{"attributes":[{"description":"the cap of forward op output","name":"n","option":"optional"}],"description":"\nReluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"PadImageGradient","schema":{"description":null,"support_level":"default"}},{"name":"Assert","schema":{"attributes":[{"description":"(*string*): custom error message to be thrown when the input does not pass assertion","name":"error_msg","option":"optional"}],"description":"\nTakes in a tensor of type *bool*, *int*, *long*, or *long long* and checks if all values are True when coerced into a boolean. In other words, for non-bool types this asserts that all values in the tensor are non-zero. If a value is False after coerced into a boolean, the operator throws an error. Else, if all values are True, nothing is returned. For tracability, a custom error message can be set using the `error_msg` argument.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/assert_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Assert\",\n [\"A\"],\n [],\n error_msg=\"Failed assertion from Assert operator\"\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(3,3)).astype(np.int32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\ntry:\n workspace.RunOperatorOnce(op)\nexcept RuntimeError:\n print(\"Assertion Failed!\")\nelse:\n print(\"Assertion Passed!\")\n\n```\n\n**Result**\n\n```\n\nA:\n[[7 5 6]\n [1 2 4]\n [5 3 7]]\nAssertion Passed!\n\n```\n\n
\n\n ","inputs":[{"description":"(*Tensor*): input tensor","name":"X"}],"support_level":"default"}},{"name":"Reduce","schema":{"attributes":[{"description":"(int, default 0) the root to run reduce into.","name":"root","option":"optional"}],"description":"\nDoes a reduce operation from every node to the root node. Currently only\nSum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be reduced.","name":"X"}],"outputs":[{"description":"The reduced result on root, not set for other nodes.","name":"Y"}],"support_level":"default"}},{"name":"TimerGet","schema":{"description":"\nQueries the current time of a timer object in nanoseconds.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"outputs":[{"description":"(*Tensor``*): scalar containing time in nanoseconds","name":"nanos"}],"support_level":"default"}},{"name":"Int8GivenTensorFill","schema":{"attributes":[{"description":"Input array of type char(byte)","name":"values","option":"optional"},{"description":"Input tensor shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Creates quantized tensor of type char(byte) with scale and zero point info.\n","outputs":[{"description":"An Int8TensorCPU with scale and zero point info","name":"Tensor"}],"support_level":"default"}},{"name":"LengthsIndicesInGradientSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"DotProductWithPadding","schema":{"attributes":[{"description":"the padding value for tensors with smaller dimension","name":"pad_value","option":"optional"},{"description":"whether to replicate the smaller tensor or not","name":"replicate","option":"optional"}],"description":"\nGiven two input float tensors X, Y with different shapes and produces one\noutput float tensor of the dot product between X and Y. We currently support\ntwo kinds of strategies to achieve this. Before doing normal dot_product 1)\npad the smaller tensor (using pad_value) to the same shape as the other one.\n2) replicate the smaller tensor to the same shape as the other one. Note the\nfirst dimension of X, Y must be equal. Only the second dimension of X or Y\ncan be padded.\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"MakeTwoClassGradient","schema":{"description":null,"support_level":"default"}},{"name":"HardSigmoidGradient","schema":{"description":"\nHardSigmoidGradient takes both Y and dY as well as an argument alpha and uses\nthis to update dX according to the chain rule and derivatives of the hard\nsigmoid function.\n","support_level":"default"}},{"name":"IndexFreeze","schema":{"description":"\nFreezes the given index, disallowing creation of new index entries.\nShould not be called concurrently with IndexGet.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"The input handle.","name":"handle"}],"support_level":"default"}},{"name":"Scale","schema":{"attributes":[{"description":"(float, default 1.0) the scale to apply.","name":"scale","option":"optional"}],"description":"\nScale takes one input data (Tensor) and produces one output data\n(Tensor) whose value is the input data tensor scaled element-wise.\n","support_level":"default"}},{"name":"APMeter","schema":{"attributes":[{"description":"(int32_t) indicates how many predictions should the op buffer. defaults to 1000","name":"buffer_size","option":"optional"}],"description":"\nAPMeter computes Average Precision for binary or multi-class classification.\nIt takes two inputs: prediction scores P of size (n_samples x n_classes), and\ntrue labels Y of size (n_samples x n_classes). It returns a single float number\nper class for the average precision of that class.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_samples xnum_classes) containing prediction scores","name":"predictions"},{"description":"2-D tensor (Tensor) of size (num_samples) containing true labels for each sample","name":"labels"}],"outputs":[{"description":"1-D tensor (Tensor) of size num_classes containing average precision for each class","name":"AP"}],"support_level":"default"}},{"name":"Rowwise8BitQuantizedToFloat","schema":{"description":"\nGiven uint8 tensor, quantized using 8bit row-wise\nquantization, and auxiliary scales and biases, this operator\nrestores float tensor in the following way. We take input 8bits tensor\nof size (m_1, m_2, ..., m_n), n >= 2, reshape it into matrix of size\n(m_1, m_2 x... x m_n). We compute element r_{ij} of output matrix as\nr_{ij} * s_i + b_i and after this we reshape this output matrix into\noutput tensor of size (m_1, m_2, ..., m_n).\n","inputs":[{"description":"quantized_input","name":"quantized_input"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":null,"name":null},{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Mod","schema":{"attributes":[{"default":0,"description":"Divisor of the modulo operation (must be >= 1).","name":"divisor","option":"optional","type":"int64"},{"default":false,"description":"If true, sign of output matches divisor, else if false, sign follows dividend.","name":"sign_follow_divisor","option":"optional","type":"boolean"}],"description":"\nElement-wise modulo operation. Each element in the output is the modulo result\nof the corresponding element in the input data. The divisor of the modulo is\nprovided by the `divisor` argument.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/mod_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mod\",\n [\"X\"],\n [\"Y\"],\n divisor=10\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(5,5))))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[56 22 43 13 60]\n [ 4 55 58 10 45]\n [64 66 4 3 66]\n [10 36 47 52 78]\n [91 4 36 47 95]]\nX after running op:\n[[6 2 3 3 0]\n [4 5 8 0 5]\n [4 6 4 3 6]\n [0 6 7 2 8]\n [1 4 6 7 5]]\n\n ```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor with int32 or int64 data.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of data with modulo operation applied.","name":"Y"}],"support_level":"default"}},{"name":"StringPrefix","schema":{"attributes":[{"description":"Maximum size of the prefix, in bytes.","name":"length","option":"optional"}],"description":"\nComputes the element-wise string prefix of the string tensor.\nInput strings that are shorter than prefix length will be returned unchanged.\nNOTE: Prefix is computed on number of bytes, which may lead to wrong behavior\nand potentially invalid strings for variable-length encodings such as utf-8.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of std::string containing prefixes for each input.","name":"prefixes"}],"support_level":"default"}},{"name":"SparseLengthsSumFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n8-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FileStoreHandlerCreate","schema":{"attributes":[{"description":"base path used by the FileStoreHandler","name":"path","option":"optional"},{"description":"prefix for all keys used by this store","name":"prefix","option":"optional"}],"description":"\nCreates a unique_ptr that uses the filesystem as backing\nstore (typically a filesystem shared between many nodes, such as NFS).\nThis store handler is not built to be fast. Its recommended use is for\nintegration tests and prototypes where extra dependencies are\ncumbersome. Use an ephemeral path to ensure multiple processes or runs\ndon't interfere.\n","outputs":[{"description":"unique_ptr","name":"handler"}],"support_level":"default"}},{"name":"AtomicFetchAdd","schema":{"description":"\nGiven a mutex and two int32 scalar tensors, performs an atomic fetch add\nby mutating the first argument and adding it to the second input\nargument. Returns the updated integer and the value prior to the update.\n","inputs":[{"description":"Blob containing to a unique_ptr","name":"mutex_ptr"},{"description":"Value to be mutated after the sum.","name":"mut_value"},{"description":"Value to add to the first operand.","name":"increment"}],"outputs":[{"description":"Mutated value after sum. Usually same as input 1.","name":"mut_value"},{"description":"Value of the first operand before sum.","name":"fetched_value"}],"support_level":"default"}},{"name":"Tanh","schema":{"description":"\nCalculates the hyperbolic tangent of the given input tensor element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/tanh_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Tanh\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 2.032603 -2.3556721 -0.14955314]\n [ 0.39309832 -1.1020128 -0.92951244]\n [-0.62815386 0.21342885 1.4002231 ]]\n\nX:\n [[ 0.9662601 -0.982175 -0.14844811]\n [ 0.3740282 -0.8012209 -0.73036647]\n [-0.55677974 0.21024609 0.8853999 ]]\n\n```\n\n
\n\n","inputs":[{"description":"1-D input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic tangent values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"Python","schema":{"description":null,"support_level":"default"}},{"name":"QuantDecodeGradient","schema":{"description":null,"support_level":"default"}},{"name":"PythonGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of dimensions of *data* to squeeze out.","name":"dims","option":"optional","type":"int64[]"}],"category":"Transform","description":"\nThe *Squeeze* op removes single-dimensional entries from the shape of the input tensor *data,* and produces a single output tensor *squeezed*. The op also takes an argument *dims* with a list of dimensions to squeeze. If the same blob is provided as input and output, the operation is copy-free. This is the exact inverse operation of *ExpandDims* given the same *dims* argument.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Squeeze\",\n [\"data\"],\n [\"squeezed\"],\n dims=[0,1],\n)\n\nworkspace.FeedBlob(\"data\", np.zeros((1,1,100,100)).astype(np.float32))\nprint(\"data.shape:\", workspace.FetchBlob(\"data\").shape)\n\nworkspace.RunOperatorOnce(op)\nprint(\"squeezed.shape:\", workspace.FetchBlob(\"squeezed\").shape)\n\n```\n\n**Result**\n\n```\n\ndata.shape: (1, 1, 100, 100)\nsqueezed.shape: (100, 100)\n\n```\n\n
\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"data"}],"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed"}],"support_level":"default"}},{"name":"NE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise not equal to comparison **!=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"NE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False True True False False True]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"ReduceSum","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **sum** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceSum\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[5. 3. 7. 9. 5.]\n [4. 5. 1. 8. 3.]\n [1. 0. 9. 7. 6.]\n [7. 5. 0. 3. 1.]\n [6. 4. 4. 8. 3.]]\n\n [[8. 9. 6. 7. 7.]\n [5. 5. 4. 7. 0.]\n [9. 7. 6. 6. 7.]\n [7. 5. 2. 4. 2.]\n [4. 5. 1. 9. 4.]]]]\nY:\n[[13. 12. 13. 16. 12.]\n [ 9. 10. 5. 15. 3.]\n [10. 7. 15. 13. 13.]\n [14. 10. 2. 7. 3.]\n [10. 9. 5. 17. 7.]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"PackSegments","schema":{"attributes":[{"description":"The pre-defined max_length for the packed segments","name":"max_length","option":"optional"},{"description":"Padding number in the packed segments. Use true to pad -infinity, otherwise pad zeros","name":"pad_minf","option":"optional"},{"description":"bool whether to return presence mask, false by default","name":"return_presence_mask","option":"optional"}],"description":"Map N dim tensor to N+1 dim based on length blob. Sequences that are shorter than the longest sequence are padded with zeros.","inputs":[{"description":"1-d int/long tensor contains the length in each of the output.","name":"lengths"},{"description":"N dim Tensor.","name":"tensor"}],"outputs":[{"description":"N + 1 dim Tensorwhere dim(1) is the max length, dim(0) is the batch size.","name":"packed_tensor"},{"description":"2 dim boolean tensor, false where packed_tensor is padded, true otherwise.","name":"presence_mask"}],"support_level":"default"}},{"name":"UnPackRecords","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nGiven a packed dataset (packed by the PackRecordsOp) and the `fields` argument\ndescribing the datasets schema, return the original dataset format. Number of\nreturned tensors is equal to the number of fields in the `fields` argument.\n\nThe first input is the packed tensor to be unpacked. Optionally, you can provide\nprototype tensors to give the expected shapes of the output tensors. This is\nhelpful when you expected to unpack empty tensor, e.g., output of a sampling\nprocess.\n","inputs":[{"description":"The tensor to be unpacked","name":"packed_tensor"}],"support_level":"default"}},{"name":"Normalize","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":"\nGiven a matrix, apply L2-normalization along the specified dimension.\n","support_level":"default"}},{"name":"LengthsMax","schema":{"description":"\nApplies 'Max' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Max' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nMax computes the element-wise max of the input slices. Operation doesn't change the shape of the individual blocks.\n\n\nThe *LengthsMax* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the maximum value in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [max([2,4]), max([3,1,2]), max([10])] = [4,3,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsMax\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 4. 3. 10.]\n\n```\n\n
\n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"L1DistanceGradient","schema":{"description":null,"support_level":"default"}},{"name":"MomentumSGD","schema":{"description":"\n\nComputes a momentum SGD update for an input gradient and momentum\nparameters. Concretely, given inputs (grad, m, lr) and parameters\n(momentum, nesterov), computes:\n\n if not nesterov:\n adjusted_gradient = lr * grad + momentum * m\n return (adjusted_gradient, adjusted_gradient)\n else:\n m_new = momentum * m + lr * grad\n return ((1 + momentum) * m_new - momentum * m, m_new)\n\nOutput is (grad, momentum)\n\nNote the difference to MomemtumSGDUpdate, which actually performs the\nparameter update (and is thus faster).\n","support_level":"default"}},{"name":"ReduceSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeSum","schema":{"description":"\nApplies 'Sum' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Sum', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"TT","schema":{"attributes":[{"description":"(int[]) Input sizes of cores. Indicates the input size of the individual cores; the size of the input vector X must match the product of the inp_sizes array.","name":"inp_sizes","option":"optional"},{"description":"(int[]) Output sizes of cores. Indicates the output size of the individual cores; the size of the output vector Y must match the product of the out_sizes array.","name":"out_sizes","option":"optional"},{"description":"(int[]) Ranks of cores. Indicates the ranks of the individual cores; lower rank means larger compression, faster computation but reduce accuracy.","name":"tt_ranks","option":"optional"}],"description":"\nThe TT-layer serves as a low-rank decomposition of a fully connected layer. The\ninputs are the same as to a fully connected layer, but the number of parameters\nare greatly reduced and forward computation time can be drastically reduced\nespecially for layers with large weight matrices. The multiplication is computed\nas a product of the input vector with each of the cores that make up the TT\nlayer. Given the input sizes (inp_sizes), output sizes(out_sizes), and the ranks\nof each of the cores (tt_ranks), the ith core will have size:\n\n inp_sizes[i] * tt_ranks[i] * tt_ranks[i + 1] * out_sizes[i].\n\nThe complexity of the computation is dictated by the sizes of inp_sizes,\nout_sizes, and tt_ranks, where there is the trade off between accuracy of the\nlow-rank decomposition and the speed of the computation.\n","inputs":[{"description":"Input tensor from previous layer with size (M x K), where M is the batch size and K is the input size.","name":"X"},{"description":"1D blob containing the bias vector","name":"b"},{"description":"1D blob containing each individual cores with sizes specified above.","name":"cores"}],"outputs":[{"description":"Output tensor from previous layer with size (M x N), where M is the batch size and N is the output size.","name":"Y"}],"support_level":"default"}},{"name":"BitwiseXor","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_xor` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"StoreSet","schema":{"attributes":[{"description":"alternative key for the blob (optional)","name":"blob_name","option":"optional"}],"description":"\nSet a blob in a store. The key is the input blob's name and the value\nis the data in that blob. The key can be overridden by specifying the\n'blob_name' argument.\n","inputs":[{"description":"unique_ptr","name":"handler"},{"description":"data blob","name":"data"}],"support_level":"default"}},{"name":"CTCGreedyDecoder","schema":{"attributes":[{"description":"When merge_repeated is true, merge repeated classes in output.","name":"merge_repeated","option":"optional"}],"description":"Greedy decoder for connectionist temporal classification.","inputs":[{"description":"3D float Tensor sized [max_time, batch_size, num_classes]","name":"INPUTS"},{"description":"(optional) 1D int vector containing sequence lengths, having size [batch_size]seq_len will be set to max_time if not provided","name":"SEQ_LEN"}],"outputs":[{"description":"Output_len matrix size (batch). The row store: [decoded_length]","name":"OUTPUT_LEN"},{"description":"Values vector, size (total_decoded_outputs). The vector stores the decoded classes","name":"VALUES"}],"support_level":"default"}},{"name":"SegmentOneHot","schema":{"description":"\nGiven a sequence of indices, segmented by the lengths tensor, returns a matrix\nthat has the elements in each sequence set to 1.0, and 0.0 everywhere else.\n","inputs":[{"description":"Size of each segment.","name":"lengths"},{"description":"Active indices, of size sum(lengths)","name":"indices"},{"description":"Size of the index","name":"index_size_tensor"}],"outputs":[{"description":"Matrix of size len(lengths) x index_size","name":"one_hots"}],"support_level":"default"}},{"name":"Max","schema":{"description":"\nElement-wise max of an arbitrary number of input tensors. This operation can be\nperformed in-place, by using the first input blob as the output blob. All inputs\nmust have the same shape and data type, and the output will have the same shape\nas the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/minmax_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Max\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Max:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.4496477 0.07061381 0.7139333 ]\n [0.83203 0.05970785 0.72786295]\n [0.75988126 0.04601283 0.32820013]]\nY:\n[[0.05683139 0.16872478 0.671098 ]\n [0.70739156 0.09878621 0.03416285]\n [0.34087983 0.94986707 0.67263436]]\nZ:\n[[0.48051122 0.07141234 0.85264146]\n [0.77086854 0.22082241 0.13154659]\n [0.42401117 0.995431 0.4263775 ]]\nMax:\n[[0.48051122 0.16872478 0.85264146]\n [0.83203 0.22082241 0.72786295]\n [0.75988126 0.995431 0.67263436]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as input(s).Contains the maximum valued element at each location.","name":"M"}],"support_level":"default"}},{"name":"MaxPool3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CreateDB","schema":{"description":null,"support_level":"default"}},{"name":"Rsqrt","schema":{"description":"Computes the element-wise rsqrt of the input.","inputs":[{"description":"ND input tensor","name":"X"}],"outputs":[{"description":"ND output tensor","name":"Y"}],"support_level":"default"}},{"name":"WeightedSum","schema":{"description":"\nElement-wise weighted sum of several data, weight tensor pairs.\nInput should be in the form X_0, weight_0, X_1, weight_1, ... where X_i all\nhave the same shape, and weight_i are size 1 tensors that specifies the weight\nof each vector. Note that if one wants to do in-place computation, it could\nonly be done with X_0 also as the output, but not other X_i.\n","inputs":[{"description":"Weight of the first input in the sum.","name":"weight_0"}],"outputs":[{"description":"Result containing weighted elem-wise sum of inputs.","name":"output"}],"support_level":"default"}},{"name":"NCHW2NHWC","schema":{"description":"\nThe operator switches the order of data in a tensor from NCHW- sample index N,\nchannels C, height H and width W, to the NHWC order (this is for 2D images).\nIn general, this operator switches the order of data in a tensor from N C H_1\n... H_k to N H_1 ... H_k C for k-dimensional features, and currently supports\nk=1, 2, and 3.\n","inputs":[{"description":"The input data (Tensor) in the NCHW order.","name":"data"}],"outputs":[{"description":"The output tensor (Tensor) in the NHWC order.","name":"output"}],"support_level":"default"}},{"name":"GivenTensorByteStringToUInt8Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nThis op fills a uint8 output tensor with the data specified by the *value* argument. The data must previously be serialized as a byte string. The output tensor shape is specified by the *shape* argument. Beware, when using this argument *value* should have a value for every element of the *output*, as missing values will not be initialized automatically. If *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\nThis op allows us to write uint8 tensors to Protobuf as byte strings and read them back as uint8 tensors in order to avoid the Protobuf uint32_t varint encoding size penalty.\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nval = np.array([1, 2, 3], dtype=np.uint8)\nop = core.CreateOperator(\n \"GivenTensorByteStringToUInt8Fill\",\n [],\n [\"out\"],\n values=[val.tobytes()],\n shape=val.shape,\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [1 2 3]\n\n```\n\n
\n\n","support_level":"default"}},{"name":"LC3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"rnn_internal_accumulate_gradient_input","schema":{"description":"\nInternal RNN operator.\n","support_level":"default"}},{"name":"SumInt","schema":{"description":null,"support_level":"default"}},{"name":"DotProductGradient","schema":{"description":null,"support_level":"default"}},{"name":"MergeMultiMapFeatureTensors","schema":{"description":"Merge given multi-feature tensors with map features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.keys","name":"in1_values_keys"},{"description":".values.values","name":"in1_values_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values_lengths","name":"out_values_lengths"},{"description":".values.keys","name":"out_values_keys"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"SortedSegmentRangeLogSumExpGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosineSimilarityGradient","schema":{"description":null,"support_level":"default"}},{"name":"SoftmaxWithLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnforceFinite","schema":{"description":"\nRaise if there is NaN or Inf values in the input tensor.\n","inputs":[{"description":"Input tensor","name":"input"}],"support_level":"default"}},{"name":"AveragePool3D","schema":{"description":"AveragePool3D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"ReduceFrontSum","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **sum**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the sum operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example, if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [sum(1,4), sum(5,1,7), sum(2), sum(9,2)] = [2.5, 4.333, 2, 5.5]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_sum_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontSum\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[4. 1. 1.]\n [0. 6. 7.]\n [7. 8. 6.]]\n\n [[5. 7. 7.]\n [0. 1. 6.]\n [2. 9. 0.]]]\nY: [18. 32. 27.]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ConditionalSetAtomicBool","schema":{"description":"\nSet an atomic to true if the given condition bool variable is true\n ","inputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"},{"description":"Blob containing a bool","name":"condition"}],"support_level":"default"}},{"name":"CollectTensor","schema":{"attributes":[{"description":"The max number of tensors to collect","name":"num_to_collect","option":"optional"}],"description":"\nCollect tensor into tensor vector by reservoir sampling,\nargument num_to_collect indicates the max number of tensors that will be\ncollected. The first half of the inputs are tensor vectors, which are also the\noutputs. The second half of the inputs are the tensors to be collected into each\nvector (in the same order). The input tensors are collected in all-or-none\nmanner. If they are collected, they will be placed at the same index in the\noutput vectors.\n","support_level":"default"}},{"name":"Min","schema":{"description":"\nElement-wise min of an arbitrary number of input tensors. This operation can be performed in-place, by using the first input blob as the output blob. All inputs must have the same shape and data type, and the output will have the same shape as the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/minmax_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Min\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(2,2)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(2,2)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(2,2)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Min:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.32731926 0.4939747 ]\n [0.29242373 0.43460014]]\nY:\n[[0.40928316 0.916115 ]\n [0.77526504 0.29339448]]\nZ:\n[[0.7899794 0.90335774]\n [0.82599413 0.2843068 ]]\nMin:\n[[0.32731926 0.4939747 ]\n [0.29242373 0.2843068 ]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as input(s).Contains the minimum valued element at each location.","name":"M"}],"support_level":"default"}},{"name":"Ceil","schema":{"description":"\nElement-wise application of the ceil function ($y=ceil(x)$) to the input tensor\n`X`. Output tensor shape is the same as the input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/ceil_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Ceil\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.uniform(-10, 10, (5,5))).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[ 8.44598 -6.5098248 -2.2993476 -7.6859694 0.58566964]\n [-7.846551 -0.03689406 6.9362907 -4.0521703 4.4969673 ]\n [ 0.33355865 -7.895527 -8.393201 9.374202 -2.3930092 ]\n [-6.3061996 3.1403487 3.782099 -8.516556 -2.8387244 ]\n [-2.0164998 4.7663913 -3.422966 0.3636999 8.75713 ]]\nX after running op:\n[[ 9. -6. -2. -7. 1.]\n [-7. -0. 7. -4. 5.]\n [ 1. -7. -8. 10. -2.]\n [-6. 4. 4. -8. -2.]\n [-2. 5. -3. 1. 9.]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"RecurrentNetworkBlobFetcher","schema":{"attributes":[{"description":"Prefix string to prepend extracted blobs.","name":"prefix","option":"optional"}],"description":"\nRetrieves blobs from scratch workspaces (which contain intermediate recurrent\nnetwork computation for each timestep) and puts them in the global\nworkspace under CPUContext.\n","inputs":[{"description":"Name of scratch workspace blob returned by recurrent network.","name":"ScratchWorkspaceBlob"}],"outputs":[{"description":"1D tensor of strings containing extracted blob names.","name":"blob_names"}],"support_level":"default"}},{"name":"Selu","schema":{"attributes":[{"default":1.673263,"description":"Alpha constant in equation.","name":"alpha","option":"optional","type":"float32"},{"default":1.0507,"description":"Scale constant in equation.","name":"scale","option":"optional","type":"float32"}],"description":"\n\nThe *Selu* op takes one input tensor $X$, an argument $alpha$, an argument $scale$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise *Selu* operation, defined as\n\n$$y=selu(x) =\\begin{cases}scale (\\alpha e^{x} - \\alpha) & x < 0\\\\scale * x & otherwise\\end{cases}$$\n\nThe default value of *alpha* is 1.6732632423543772848170429916717 and the default value of *scale* is 1.0507009873554804934193349852946. See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) for more information.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/selu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/selu_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Selu\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 1.1613879 -0.27111396 -1.2076733 ]\n [ 1.3442237 -1.0701777 1.2070968 ]\n [ 0.23810555 0.9740916 -1.7872391 ]]\n\nY:\n [[ 1.2202715 -0.4174965 -1.2326177 ]\n [ 1.4123772 -1.1551634 1.2682979 ]\n [ 0.25017774 1.023479 -1.4637551 ]]\n\n```\n\n
\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"Output tensor with same shape as input.","name":"Y"}],"support_level":"default"}},{"name":"DataCouple","schema":{"description":"\n\nA one to one operator that takes an arbitrary number of input and output blobs\nsuch that each input blob is inplace with it's matching output blob. It then proceedes\nto do nothing with each of these operators. This serves two purposes. It can make it\nappear as if a blob has been written to, as well as can tie together different blobs\nin a data dependency\n\n","support_level":"default"}},{"name":"Logit","schema":{"attributes":[{"description":"small positive epsilon value, the default is 1e-6.","name":"eps (optional)","option":"optional"}],"description":"\nElementwise logit transform: logit(x) = log(x / (1 - x)), where x is the\ninput data clampped in (eps, 1-eps).\n","inputs":[{"description":"input float tensor","name":"X"}],"outputs":[{"description":"output float tensor","name":"Y"}],"support_level":"default"}},{"name":"SegmentIdsToLengths","schema":{"description":"\nTransfers a vector of segment ids to a vector of segment lengths. This operation\nsupports non-consecutive segment ids. Segments not appearing in the input vector\nwill have length 0. If the second input is provided, the number of segments =\nthe size of its first dimension. Otherwise, the number of segments = the last\nindex in the first input vector + 1.\n\nIn general, for consecutive, zero-based segment IDs, this is the inverse\noperation of LengthsToSegmentIds, except that a vector of segment IDs\ncannot represent empty segments at the end (if the second input is absent).\n","inputs":[{"description":"1-D int32_t or int64_t tensor of segment ids","name":"segment_ids"},{"description":"if provided, number of segments = the size of its first dimension","name":"data (optional)"}],"outputs":[{"description":"1-D int64_t tensor of segment lengths","name":"lengths"}],"support_level":"default"}},{"name":"YellowFin","schema":{"attributes":[{"description":"Default 0.999","name":"beta","option":"optional"},{"description":"Default 20","name":"curv_win_width","option":"optional"},{"description":"Default 1e-6","name":"epsilon","option":"optional"},{"description":"Default false","name":"nesterov","option":"optional"},{"description":"Default true","name":"zero_debias","option":"optional"}],"description":"\n\nComputes the YellowFin update (https://arxiv.org/abs/1706.03471) and performs\nmomentum SGD optimization step. lr and mu are not being shared between\nparameters. curv_win, g_avg, g2_avg and scalars_memory are just auxiliary\nmemory for computing moving averages (see the publication). Takes arguments\nbeta: coefficient for moving averages,\ncurv_win_width: timeframe when average squared gradient is being stored,\nepsilon: for numerical purposes,\nnesterov and zero_debias for debias of moving average.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Momentum","name":"moment"},{"description":"Learning rate","name":"lr"},{"description":"Momentum coefficient","name":"mu"},{"description":"Memory for latest curvature ranges","name":"curv_win"},{"description":"Moving average of gradient","name":"g_avg"},{"description":"Moving average of squared gradient","name":"g2_avg"},{"description":"Memory for stateful scalars","name":"scalars_memory"},{"description":"Gradient computed","name":"grad"},{"description":"Iteration number","name":"iter"}],"outputs":[{"description":"Parameters to be updated","name":"output_param"},{"description":"Momentum","name":"output_moment"},{"description":"Output learning rate","name":"output_lr"},{"description":"Output momentum coefficient","name":"output_mu"},{"description":"Output memory for latest curvature ranges","name":"output_curv_win"},{"description":"Output moving average of gradient","name":"output_g_avg"},{"description":"Output moving average of squared gradient","name":"output_g2_avg"},{"description":"Output memory for stateful scalars","name":"output_scalars_memory"}],"support_level":"default"}},{"name":"ReduceBackMax","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **max**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the max operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [max(1,5), max(4,1,8), max(2)] = [5, 8, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_max_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackMax\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[2. 5. 1.]\n [6. 1. 9.]\n [8. 5. 9.]]\n\n [[5. 7. 8.]\n [9. 9. 6.]\n [6. 5. 0.]]]]\nY: [[9. 9.]]\n\n```\n\n
\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"Int8Concat","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"Which axis to concat on","name":"axis","option":"optional"},{"description":"Pass 1 to add the axis specified in arg 'axis' to all input tensors","name":"add_axis","option":"optional"}],"description":"Concatenate a list of tensors into a single tensor","outputs":[{"description":"Concatenated tensor","name":"concat_result"},{"description":"The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"Allgather","schema":{"description":"\nDoes an allgather operation among the nodes.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allgathered.","name":"X"}],"outputs":[{"description":"The allgathered tensor, same on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"RecurrentNetworkGradient","schema":{"description":null,"support_level":"default"}},{"name":"HalfFloatToFused8BitRowwiseQuantized","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 8 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"StopGradient","schema":{"description":"\nStopGradient is a helper operator that does no actual numerical computation,\nand in the gradient computation phase stops the gradient from being computed\nthrough it.\n","support_level":"default"}},{"name":"Summarize","schema":{"attributes":[{"description":"(int, default 0) flag to indicate if the summarized statistics have to be written to a log file.","name":"to_file","option":"optional"}],"description":"\nSummarize computes four statistics of the input tensor (Tensor)- min,\nmax, mean and standard deviation. The output will be written to a 1-D tensor of\nsize 4 if an output tensor is provided. Else, if the argument 'to_file' is\ngreater than 0, the values are written to a log file in the root folder.\n","inputs":[{"description":"The input data as Tensor.","name":"data"}],"outputs":[{"description":"1-D tensor (Tensor) of size 4 containing min, max, mean and standard deviation","name":"output"}],"support_level":"default"}},{"name":"NormalizeL1","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":"\nGiven a matrix, apply L1-normalization along the specified axis.\n","support_level":"default"}},{"name":"BatchSparseToDense","schema":{"attributes":[{"description":"Optional, output dense last dimension. If both this argument and output_shape_inference are set, it should be consistent with output_shape_inference's last dim","name":"dense_last_dim","option":"optional"},{"description":"Optional, missing values are filled with this value.default_value = 0 when not set","name":"default_value","option":"optional"}],"description":"\nConvert sparse matrix representation into dense matrix.\n\nA sparse matrix is represented by `lengths` vector, `indices` vector,\nand `values` vector. Each element in `lengths` vector (lengths[`i`]) represents\nthe number of indices in this batch (batch `i`).\nWith in each batch, `indices` should not have duplicate number.\n\nFor example, with input:\n\n lengths = [2, 3, 1]\n indices = [0, 1, 2, 3, 4, 5]\n values = [6, 7, 8, 9, 10, 11]\n dense_dim = 6\n default_value = 0\n\nThe output is:\n\n output = [[6, 7, 0, 0, 0, 0],\n [0, 0, 8, 9, 10, 0],\n [0, 0, 0, 0, 0, 11]]\n\nafter running this operator.\n","inputs":[{"description":"Flatten tensor, used to break down indices and values into per batch indices and values.","name":"lengths"},{"description":"Flatten tensor of total size = \\sum lengths, containing the indices ","name":"indices"},{"description":"Data tensor, dimension has to match `indices`","name":"values"},{"description":"Optional, a dense tensor whose shape define the output shape","name":"output_shape_inference"}],"outputs":[{"description":"2-D dense tensor, with 1st dim = len(lengths), 2nd dim = dense_last_dimin the arg list, the tensor is of the same data type as `values`.Missing values are filled with default_value","name":"dense"}],"support_level":"default"}},{"name":"MaxPool3D","schema":{"description":"MaxPool3D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"CreateMap","schema":{"attributes":[{"description":"Key's TensorProto::DataType (default INT32)","name":"key_dtype","option":"optional"},{"description":"Value's TensorProto::DataType (default INT32)","name":"value_dtype","option":"optional"}],"description":"Create an empty map blob","outputs":[{"description":"Blob reference to the map","name":"map blob"}],"support_level":"default"}},{"name":"BatchMomentsGradient","schema":{"description":null,"support_level":"default"}},{"name":"WeightedSigmoidCrossEntropyWithLogitsGradient","schema":{"description":null,"support_level":"default"}},{"name":"RmsProp","schema":{"description":"\nComputes the RMSProp update\n(http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf).\nConcretely, given inputs (grad, mean_squares, mom, lr), computes:\n\n mean_squares_o = mean_squares + (1 - decay) * (square(grad) - mean_squares)\n mom_o = momentum * mom + lr * grad / sqrt(epsilon + mean_squares_o)\n grad_o = mom_o\n\nReturns (grad_o, mean_squares_o, mom_o).\n","support_level":"default"}},{"name":"SoftmaxWithLoss","schema":{"attributes":[{"default":0,"description":"Setting to 1 enables inputting labels as probability distribution.","name":"label_prob","option":"optional","type":"int64"},{"default":1,"description":"Axis of the inputs when coerced to 2D.","name":"axis","option":"optional","type":"int64"},{"description":"Average loss output scaling factor (must be >= 0).","name":"scale","option":"optional","type":"float32"},{"default":"'NCHW'","description":"Order of blob dimensions (only 'NCHW' is supported currently).","name":"order","option":"optional","type":"string"}],"description":"\nCombined Softmax and Cross-Entropy loss operator. The operator first computes the softmax normalized values for each layer in the batch of the given input, then computes cross-entropy loss. This operator is numerically more stable than separate `Softmax` and `CrossEntropy` ops. The inputs are a 2-D tensor `logits` of size (batch_size x input_feature_dimensions), which represents the unscaled log probabilities, and a 1-dimensional integer `labels` tensor for ground truth. An optional third input blob (`weight_tensor`) can be used to weight the samples for the loss, which is useful if the training set is unbalanced. This operator outputs a `softmax` tensor which contains the probability for each label for each example (same shape is `logits` input), and a scalar `loss` value, which is the averaged cross-entropy loss between the softmax probabilities and the ground truth values. Use parameter `label_prob`=1 to enable inputting labels as a probability distribution.\n\nSoftmax cross-entropy loss function:\n\n$$loss(x, class) = -\\log{\\biggl(\\frac{\\exp(x[class])}{\\sum_{j} \\exp(x[j])}\\biggr)} = -x[class] + \\log{\\biggl(\\sum_{j} \\exp(x[j])\\biggr)}$$\n\nor if the `weight_tensor` has been passed:\n\n$$loss(x, class) = weight[class]\\biggl(-x[class] + \\log{\\biggl(\\sum_{j} \\exp(x[j])\\biggr)}\\biggr)$$\n\nThe `logits` input does not need to explicitly be a 2D vector; rather, it will be coerced into one. For an arbitrary n-dimensional tensor `X` in $[a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}]$, where k is the `axis` provided, then `X` will be coerced into a 2-dimensional tensor with dimensions $[(a_0 * ... * a_{k-1}), (a_k * ... * a_{n-1})]$. For the default case where `axis`=1, the `X` tensor will be coerced into a 2D tensor of dimensions $[a_0, (a_1 * ... * a_{n-1})]$, where $a_0$ is often the batch size. In this situation, we must have $a_0 = N$ and $a_1 * ... * a_{n-1} = D$. Each of these dimensions must be matched correctly, or else the operator will throw errors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_with_loss_op.cc\n\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SoftmaxWithLoss\",\n [\"logits\", \"labels\"],\n [\"softmax\", \"avgloss\"]\n)\n\nworkspace.FeedBlob(\"logits\", np.random.randn(1, 5).astype(np.float32))\nworkspace.FeedBlob(\"labels\", np.asarray([4]).astype(np.int32))\nprint(\"logits:\", workspace.FetchBlob(\"logits\"))\nprint(\"labels:\", workspace.FetchBlob(\"labels\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"softmax\"))\nprint(\"avgloss:\", workspace.FetchBlob(\"avgloss\"))\n\n```\n\n**Result**\n\n```\n\nlogits: [[-0.3429451 -0.80375195 0.23104447 1.4569176 -0.5268362 ]]\nlabels: [4]\nsoftmax: [[0.09721052 0.0613179 0.17258129 0.58800864 0.0808817 ]]\navgloss: 2.5147676\n\n```\n\n
\n\n
\n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SoftmaxWithLoss\",\n [\"logits\", \"labels\"],\n [\"softmax\", \"avgloss\"],\n scale=5.0\n)\n\nworkspace.FeedBlob(\"logits\", np.asarray([[.1, .4, .7, 1.5, .2]]).astype(np.float32))\nworkspace.FeedBlob(\"labels\", np.asarray([4]).astype(np.int32))\nprint(\"logits:\", workspace.FetchBlob(\"logits\"))\nprint(\"labels:\", workspace.FetchBlob(\"labels\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"softmax\"))\nprint(\"avgloss:\", workspace.FetchBlob(\"avgloss\"))\n\n```\n\n**Result**\n\n```\n\nlogits: [[0.1 0.4 0.7 1.5 0.2]]\nlabels: [4]\nsoftmax: [[0.10715417 0.144643 0.19524762 0.4345316 0.11842369]]\navgloss: 10.667433\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"logits"},{"description":"*(type: Tensor``)* Ground truth label tensor.","name":"labels"},{"description":"*(type: Tensor``)* [OPTIONAL] Blob used to weight the samples for the loss.","name":"weight_tensor"}],"outputs":[{"description":"*(type: Tensor``)* Softmax output tensor.","name":"softmax"},{"description":"*(type: float)* Averaged cross-entropy loss output.","name":"loss"}],"support_level":"default"}},{"name":"VariableLengthSequencePadding","schema":{"description":"\nSuper special-case operator. Used to pad a tensor to mimic pytorch's\npad_packed_sequence.\n\nGiven an input tensor INPUT of size NxBxM and an input tensor LENS\nof size B, where\n\nN = maximum sequence length\nB = batch size\nM = hidden size\n\nset each element of INPUT to zero if it is is past the end of the\ncorresponding sequence (i.e. if LENS[j] > i for an index (i,j,k)).\n\n","support_level":"default"}},{"name":"SparseLengthsMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"SoftplusGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentWeightedSum).\n\nThis op is basically Gather and UnsortedSegmentWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"EnsureDense","schema":{"description":"\nThis operator converts dense or sparse gradients to dense ones.\nTherefore, sparse gradient can be back propagated to Operators that consume\ndense gradients only (e.g., FCGradient).\n\nThe operator's behaviors:\n\n- In forward, simply pass in place or copy input to the output.\n- In backward, if the gradient passed-in is sparse gradient, change it to dense gradient in linear time; otherwise, simply pass the dense gradient.\n","inputs":[{"description":"Input tensors.","name":"input"}],"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"output"}],"support_level":"default"}},{"name":"LabelCrossEntropy","schema":{"description":"\nThis operator computes the cross entropy between a $NxD$ dimensional input data tensor $X$ and a one dimensional input label tensor $label$. The op produces a single length $N$ output tensor $Y$. Here, $N$ is considered the batch size and $D$ is the size of each element in the batch. In practice, it is most commonly used at the end of models as a part of the loss computation, after the SoftMax operator and before the AveragedLoss operator. The cross entropy operation is defined as follows\n\n$$Y_i = -log(X_{ij})$$\n\nwhere ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nThe difference between *LabelCrossEntropy* and *CrossEntropy* is how the labels are specified. Here, the labels are a length $N$ list of integers, whereas in CrossEntropy the labels are a $NxD$ dimensional matrix of one hot label vectors. However, the results of computation should be the same, as shown in the two examples where ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LabelCrossEntropy\",\n [\"X\", \"label\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([[.01, .05, .02, .02, .9],[.03, .1, .42, .05, .4]])\nprint(\"X:\\n\",X)\n\n// Create label: Sample 1-hot ground truth label vectors\nlabel = np.array([4,2])\nprint(\"label:\\n\",label)\n\n// Feed X & label into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"label\", label.astype(np.int32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[0.01 0.05 0.02 0.02 0.9 ]\n [0.03 0.1 0.42 0.05 0.4 ]]\nlabel:\n [4 2]\nY:\n [0.10536055 0.8675006 ]\n\n```\n\n
\n\n\n","inputs":[{"description":"Input tensor which is almost always the result of a softmax operation. $X$ is a 2D array of size $NxD$, where $N$ is the batch size and $D$ is the number of classes.","name":"X"},{"description":"Blob containing the labels used to compare the input. $label$ is a length $N$ list of integers, where each element is the integer label for the $n$th element of the batch.","name":"label"}],"outputs":[{"description":"Output blob from the cross entropy computation. $Y$ is 1D length $N$ tensor.","name":"Y"}],"support_level":"default"}},{"name":"BooleanMaskGradient","schema":{"description":null,"support_level":"default"}},{"name":"Save","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"default":"","description":"Characters in the provided blob names that match `strip_prefix` will be removed prior to saving. Also, characters that precede `strip_prefix` will be removed. Useful for removing device scope from blob names.","name":"strip_prefix","option":"optional","type":"string"},{"description":"If set, used as blob names instead of original blob names. Must be same length as number of blobs.","name":"blob_name_overrides","option":"optional","type":"string[]"},{"description":"The output path of the db. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db","option":"optional","type":"string"},{"description":"Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional","type":"string"},{"default":"kDefaultChunkSize","description":"The chunk size to split tensor data into. If not set, caffe2_tensor_chunk_size will be used","name":"chunk_size","option":"optional","type":"string"}],"description":"\nSaves a set of blobs to a db. It takes $[1, \\infty)$ number of inputs and has\nno output. The contents of the inputs are written into the db using the\nsettings specified by the arguments.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Save\",\n [\"X\", \"Y\", \"Z\"],\n [],\n db=\"test_db2\",\n db_type=\"leveldb\",\n blob_name_overrides=[\"x_scores\", \"y_scores\", \"z_scores\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(20, size=(5,5)))\nworkspace.FeedBlob(\"Y\", np.random.randint(20, size=(5,5)))\nworkspace.FeedBlob(\"Z\", np.random.randint(20, size=(5,5)))\nworkspace.RunOperatorOnce(op)\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input tensor(s).","name":"X"}],"support_level":"default"}},{"name":"SparseSortedSegmentMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentMean that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"GaussianFill","schema":{"attributes":[{"default":0,"description":"Mean of the distribution to draw from.","name":"mean","option":"optional","type":"float32"},{"default":1,"description":"Standard deviation of the distribution to draw from.","name":"std","option":"optional","type":"float32"},{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with samples drawn from a normal distribution specified by the mean and standard deviation arguments. The output tensor shape is specified by the *shape* argument. However, if *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: cannot set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GaussianFill\",\n [],\n [\"out\"],\n shape=[3,3],\n mean=2.0,\n std=1.1\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [[1.2084167 2.3336504 2.827349 ]\n [2.7108908 0.9374752 1.7173369 ]\n [0.03320992 2.1775863 1.0894578 ]]\n\n```\n\n
\n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor of random values drawn from a normal distribution. If the shape argument is set, this is the shape specified, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"ReduceMinGradient","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorInt16Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Abs","schema":{"description":"\nCalculates the absolute value of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/abs_op.cc\n\n
\n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Abs\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [ 0.3005476 1.551666 -1.3591481 0.39191285 -0.21866608]\nY: [0.3005476 1.551666 1.3591481 0.39191285 0.21866608]\n\n```\n\n
\n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Absolute value of input element-wise.","name":"Y"}],"support_level":"default"}},{"name":"LengthsTopK","schema":{"attributes":[{"description":"the number of top values to return for each segment, if the number of values is smaller than k, the values would be padded with 0 and indices would be padded with -1.","name":"k","option":"optional"}],"description":"\nApply TopK to each segment of the input tensor, where segments are defined by\ntheir LENGTHS, and concatenate them in an output tensor of\nshape=(SIZE(LENGTHs), k). In case there's less than k values in a segment,\nthe output value will be padded by 0, and the corresponding output indices will\nbe padded by -1.\n","inputs":[{"description":"Tensor of rank 1. First dimension must be equal to the sum of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Output top k elements for each segment, withshape=(SIZE(lengths), k)","name":"TopKValue"},{"description":"Output indices in DATA corresponding to value in TopKValue","name":"TopKIndices"}],"support_level":"default"}},{"name":"RMACRegions","schema":{"attributes":[{"description":"Number of scales to sample regions at.","name":"scales","option":"optional"},{"description":"Overlap between consecutive regions.","name":"overlap","option":"optional"}],"description":"\nComputes a fixed-grid of RMAC region coordinates at various levels\nas described in https://arxiv.org/abs/1511.05879.\n","inputs":[{"description":"The input 4D tensor of shape NCHW.","name":"X"}],"outputs":[{"description":"The output RMAC regions for all items in the batch. Tensor of shape (N x 5) following the ROIPoolOp format - each row is of the format (batch_index x1 y1 x2 y2) where x1, y1, x2, y2 are the region co-ordinates. Each region is repeated N times corresponding to each item in the batch.","name":"RMAC_REGIONS"}],"support_level":"default"}},{"name":"SumReduceLike","schema":{"attributes":[{"description":"If set, defines the starting dimension for reduction. Args `axis` and `axis_str` cannot be used simultaneously.","name":"axis","option":"optional"},{"description":"If set, it could only be N or C or H or W. `order` arg should also be provided. It defines the reduction dimensions on NCHW or NHWC. Args `axis` and `axis_str` cannot be used simultaneously.","name":"axis_str","option":"optional"},{"description":"Either NHWC or HCWH","name":"order","option":"optional"}],"description":"\nSumReduceLike operator takes 2 tensors as input. It performs reduce sum to the\nfirst input so that the output looks like the second one.\nIt assumes that the first input\nhas more dimensions than the second, and the dimensions of the second input is\nthe contiguous subset of the dimensions of the first.\nFor example, the following tensor shapes are supported:\n\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 2, 5), shape(B) = (2), with axis=0\n ","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as B","name":"C"}],"support_level":"default"}},{"name":"MaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReplaceNaN","schema":{"attributes":[{"description":"the value to replace NaN, the default is 0","name":"value (optional)","option":"optional"}],"description":"\nReplace the NaN (not a number) element in the input tensor with argument `value`\n","inputs":[{"description":"Input tensor","name":"input"},{"description":"Output tensor","name":"output"}],"support_level":"default"}},{"name":"HasScope","schema":{"description":"\nChecks whether scope blob has any saved scopes left\n ","support_level":"default"}},{"name":"ReduceBackSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ZeroGradient","schema":{"description":"\nZeroGradient operators doesn't produce any output blobs. One can use\nthis operator to produce 0 gradient for the input blob.\n","support_level":"default"}},{"name":"ReduceBackMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"ClipGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsWeightedSum8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsWeightedSum operator, where\nDATA is stored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of INDICES","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HuffmanTreeHierarchy","schema":{"attributes":[{"description":"The number of classes used to build the hierarchy.","name":"num_classes","option":"optional"}],"description":"\nHuffmanTreeHierarchy is an operator to generate huffman tree hierarchy given\nthe input labels. It returns the tree as serialized HierarchyProto\n","inputs":[{"description":"The labels vector","name":"Labels"}],"outputs":[{"description":"Huffman coding hierarchy of the labels","name":"Hierarch"}],"support_level":"default"}},{"name":"ChannelShuffle","schema":{"description":null,"support_level":"default"}},{"name":"AveragedLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"BooleanUnmask","schema":{"description":"\nGiven a series of masks and values, reconstruct values together according to masks. A comprehensive example:\n```\nmask1 = True, False, True, False, False\nvalues1 = 1.0, 3.0\nmask2 = False, True, False, False, False\nvalues2 = 2.0\nmask3 = False, False, False, True, True\nvalues3 = 4.0, 5.0\n```\n\nReconstruct by:\n\n```\noutput = net.BooleanUnmask([mask1, values1, mask2, values2, mask3, values3], [\"output\"])\noutput = 1.0, 2.0, 3.0, 4.0, 5.0\n```\n\nNote that for all mask positions, there must be at least one True. This is not allowed:\n\n```\nmask1 = True, False\nvalues1 = 1.0\nmask2 = False, False\nvalues2 =\n\noutput = net.BooleanUnmask([mask1, values1, mask2, values2], [\"output\"])\n```\n\nIf there are multiple True values for a field, we accept the first value, and no longer expect a value for that location:\n\n```\nmask1 = True, False\nvalues1 = 1.0\nmask2 = True, True\nvalues2 = 2.0\n\noutput = net.BooleanUnmask([mask1, values1, mask2, values2], [\"output\"])\noutput = 1.0, 2.0\n```\n\n*** Note that we alternate `data` and `mask` inputs\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_unmask_ops.cc\n\n
\n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanUnmask\",\n [\"mask1\", \"data1\", \"mask2\", \"data2\"],\n [\"unmasked_data\"]\n)\n\nworkspace.FeedBlob(\"mask1\", np.array([True,False,False,True,True,False]))\nworkspace.FeedBlob(\"data1\", np.array([1,4,5]))\nworkspace.FeedBlob(\"mask2\", np.array([False,True,True,False,False,True]))\nworkspace.FeedBlob(\"data2\", np.array([2,3,6]))\n\nprint(\"data1:\", workspace.FetchBlob(\"data1\"))\nprint(\"mask1:\", workspace.FetchBlob(\"mask1\"))\nprint(\"data2:\", workspace.FetchBlob(\"data2\"))\nprint(\"mask2:\", workspace.FetchBlob(\"mask2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"unmasked_data:\", workspace.FetchBlob(\"unmasked_data\"))\n\n```\n\n**Result**\n\n```\n\ndata1: [1 4 5]\nmask1: [ True False False True True False]\ndata2: [2 3 6]\nmask2: [False True True False False True]\nunmasked_data: [1 2 3 4 5 6]\n\n```\n\n
\n","inputs":[{"description":"(*Tensor*): 1D input tensor(s)","name":"data"},{"description":"(*Tensor``*): 1D boolean mask tensor(s)","name":"mask"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as `data` input that contains the unmasked input tensor","name":"unmasked_data"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedToHalfFloat","schema":{"description":"\nDe-quantizes the result of the\nHalfFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 32-bit float in the second to the last 4 bytes of each\nrow, followed by the bias as a 32-bit float in the next 4 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"LengthsGather","schema":{"description":"\nGather items from sparse tensor. Sparse tensor is described by items and\nlengths. This operator gathers items corresponding to lengths at the given\nindices. This deliberately doesn't return lengths of OUTPUTS so that both lists\nand maps can be supported without special cases. If you need lengths tensor for\n OUTPUT, use `Gather`.\n\nExample:\n ITEMS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n LENGTHS = [0, 2, 3, 1, 4]\n INDICES = [0, 2, 4]\n\n OUTPUT = [2, 3, 4, 6, 7, 8, 9]\n","inputs":[{"description":"items tensor","name":"ITEMS"},{"description":"lengths tensor","name":"LENGTHS"},{"description":"indices into LENGTHS where items should be gathered","name":"INDICES"}],"outputs":[{"description":"1-D tensor containing gathered items","name":"OUTPUT"}],"support_level":"default"}},{"name":"SequenceMask","schema":{"attributes":[{"description":"(string) Mode selection. Possible values: 'sequence', 'upper', 'lower', 'upperdiag', 'lowerdiag'","name":"mode","option":"optional"},{"description":"(int) Beginning axis of row elements. All dimensions to the left will be treated as row indices and those to the right (inclusive) will be treated as column indices in the 2D mask","name":"axis","option":"optional"},{"description":"(bool) operate in gradient mode","name":"grad","option":"optional"},{"description":"(int) radius of windows in window mode","name":"radius","option":"optional"},{"description":"(int) batch dimension of tensor (optional)","name":"batch","option":"optional"},{"description":"(int) used when mask should be repeated for one or more data dimensions (beginning at this axis). (currently only supported for sequence mode without batch argument)","name":"repeat_from_axis","option":"optional"}],"description":"\nMask op designed for use in attention mechanisms for sequence modeling tasks.\nSupports batching: given batch_dim, collapses dims 0 through batch_dim into a\nsingle dimension, e.g. if tensor dims are [4,2,1,3,4] and batch_dim=2, first\ncollapse tensor to [4*2*1,3,4], then mask each batch [i,:,:].\n\n\nTwo current operating modes:\n\n\n1) Given a 2D input tensor and 1D tensor of sequence lengths, for each row i in\nthe input tensor, set elements in that row to -inf if their column index\nj >= sequence_lengths[i]. This mode takes two inputs and argument mode =\n'sequence'\n\n\n2) Triangular mask. Given row index i and column index j, set elements to -inf\ngiven the following conditions:\n\n mode='upper', x_ij = -inf if j < i\n mode='lower', x_ij = -inf if j > i\n mode='upperdiag', x_ij = -inf if j <= i\n mode='lowerdiag', x_ij = -inf if j >= i\n\nThis mode takes one input.\n\n\n3) Window Mask. Given a 2D input tensor and 1D tensor of window centers,\nfor each row i in the input tensor, set elements in that row to -inf\nif their column index j outside [center - radius, center + radius].\nThis mode takes two inputs and argument mode = 'sequence'.\nArgument 'radius' should be provided.\n","inputs":[{"description":"Tensor to apply masking to","name":"input"},{"description":"1D Tensor of sequence lengths for mode #1","name":"sequence_lengths"}],"outputs":[{"description":"Input tensor with masking applied","name":"masked_tensor"}],"support_level":"default"}},{"name":"Int8Transpose","schema":{"attributes":[{"description":"Order to permute axes of input tensor. Reverses the dimensions by default.","name":"axes","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nTranspose the input tensor by permuting the axes of the input according\nto the `axes` argument. Similar to numpy's\n[transpose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)\nfunction.\n\nFor example, when axes=(1, 0, 2), given an input tensor of shape\n(1, 2, 3), the output shape will be (2, 1, 3).\n","inputs":[{"description":"Input tensor","name":"X"}],"outputs":[{"description":"Transposed output","name":"Y"}],"support_level":"default"}},{"name":"ResizeNearest3DGradient","schema":{"attributes":[{"description":"Scale along temporal dimension","name":"temporal_scale","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ResizeNearest3D","schema":{"attributes":[{"description":"Scale along temporal dimension","name":"temporal_scale","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input tensor using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\nAssumptions:\n - Only resize height and width\n - Both width_scale and height_scale scale are 2\n","inputs":[{"description":"Input tensor","name":"X"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchPermutation","schema":{"description":"\nBatch permutation of an input tensor X given input indices. First dimension of\nX equals batch size N. The indices stores a be permutation of N.\nThe output Y is a tensor of same shape as X, with data re-ordered according to\nthe indices within the batch size.\n\nExample of batch permutation on a 2-D tensor with batch size 4:\n X = [\n [1, 5, 2, 3, 4, 6, 0],\n [4, 3, 3, 5, 2, 3, 1],\n [2, 2, 3, 6, 0, 0, 1],\n [0, 0, 1, 1, 2, 2, 3]\n ]\n indices = [2, 0, 1, 3]\n Y = [\n [2, 2, 3, 6, 0, 0, 1],\n [1, 5, 2, 3, 4, 6, 0],\n [4, 3, 3, 5, 2, 3, 1],\n [0, 0, 1, 1, 2, 2, 3]\n ]\n\nExample of batch permutation on a 3-D tensor with batch size 4:\n X = [\n [[1, 5, 2], [3, 4, 6, 0]],\n [[4, 3, 3], [5, 2, 3, 1]],\n [[2, 2, 3], [6, 0, 0, 1]],\n [[0, 0, 1], [1, 2, 2, 3]]\n ]\n indices = [2, 0, 1, 3]\n Y = [\n [[2, 2, 3], [6, 0, 0, 1]],\n [[1, 5, 2], [3, 4, 6, 0]],\n [[4, 3, 3], [5, 2, 3, 1]],\n [[0, 0, 1], [1, 2, 2, 3]]\n ]\n","inputs":[{"description":"Input tensor, where 1st dimension equals batch size","name":"X"},{"description":"Input indices of batch to permute","name":"indices"}],"outputs":[{"description":"Output permuted tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchPermutationGradient","schema":{"description":null,"support_level":"default"}},{"name":"AliasWithName","schema":{"attributes":[{"description":"name of the aliasing","name":"name","option":"optional"},{"description":"weather or not to alias forward or backward","name":"is_backward","option":"optional"}],"description":"\nSimilar with AliasOp, storing the alias name as operator argument.\n","inputs":[{"description":"Input tensor whose storage will be shared.","name":"input"}],"outputs":[{"description":"Tensor of same shape as input, sharing its storage.","name":"output"}],"support_level":"default"}},{"name":"RowWiseCounter","schema":{"attributes":[{"description":"Default -1: off","name":"counter_halflife","option":"optional"}],"description":"\n Count the number recent update on rows. Exponential decay is\n applied on the counter with decay rate r, such that\n r^{counter_halflife} = 0.5; If counter_halflife is nonpositive,\n this operator is turned off.\n","inputs":[{"description":"Iter at last update","name":"prev_iter"},{"description":"update counter","name":"update_counter"},{"description":"Sparse indices","name":"indices"},{"description":"current iteration","name":"iter"}],"outputs":[{"description":"Updated iter at last update","name":"output_prev_iter"},{"description":"Output update counter","name":"output_update_counter"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedHalfScaleBiasToHalfFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 16-bit float in the second to the last 2 bytes of each\nrow, followed by the bias as a 16-bit float in the next 2 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"FloatToFused8BitRowwiseQuantizedHalfScaleBias","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 4 bytes\nof each row in the output matrix are a half float storing the scale\nfollowed by another half float containing the scale.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"HalfFloatToFused8BitRowwiseQuantizedHalfScaleBias","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 4 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedHalfScaleBiasToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 16-bit float in the second to the last 2 bytes of each\nrow, followed by the bias as a 16-bit float in the next 2 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"AtomicFetchAdd64","schema":{"description":"\nLike, AtomicFetchAdd but with int64_t scalar tensors,\nperforms an atomic fetch add\nby mutating the first argument and adding it to the second input\nargument. Returns the updated integer and the value prior to the update.\n","inputs":[{"description":"Blob containing to a unique_ptr","name":"mutex_ptr"},{"description":"Value to be mutated after the sum.","name":"mut_value"},{"description":"Value to add to the first operand.","name":"increment"}],"outputs":[{"description":"Mutated value after sum. Usually same as input 1.","name":"mut_value"},{"description":"Value of the first operand before sum.","name":"fetched_value"}],"support_level":"default"}},{"name":"Quantile","schema":{"attributes":[{"description":"If true (default), apply abs() on the tensor values.","name":"abs","option":"optional"},{"description":"multiplicative tolerance of the quantile_value.","name":"tol","option":"optional"}],"description":"\n Calculate the quantile for the value in the given list of tensors.\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"Value at the given quantile","name":"quantile_value"}],"support_level":"default"}},{"name":"SparseLengthsSumFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n2-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FloatToFused4BitRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 4-bit number between 0 and\n15. To later de-quantize values, the scale (range / 15) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 2-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n2-byte fp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FloatToFused2BitRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 2-bit number between 0 and\n3. To later de-quantize values, the scale (range / 3) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 4-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n2-byte fp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMean4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 4-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMean2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 2-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 2-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused4BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused4BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"SparseLengthsMean8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 8-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 4-byte\nfp32 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused4BitRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 4-bit number between 0 and\n15. To later de-quantize values, the scale (range / 15) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSumFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n4-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused4BitRowwiseQuantizedToHalf","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused4BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 4-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused2BitFakeRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise fake quantization to a tensor of half floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"FloatToFused2BitFakeRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise fake quantization to a tensor of floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"FloatToFused4BitFakeRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise fake quantization to a tensor of floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Fused2BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused2BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"SparseLengthsSum4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 4-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and 2-byte fp16 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused2BitRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 2-bit number between 0 and\n3. To later de-quantize values, the scale (range / 3) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 2-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 4-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSum8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 8-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 4-byte\nfp32 scale and 4-byte fp32 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSum2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 2-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and 2-byte fp16 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused4BitFakeRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise fake quantization to a tensor of half floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 8-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n4-byte fp32 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused2BitRowwiseQuantizedToHalf","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused2BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"WeightScale","schema":{"attributes":[{"description":"Every iteration number to do weight scaling","name":"stepsize","option":"optional"},{"description":"After iter passes this bound, do not perform the weight rescaling","name":"upper_bound_iter","option":"optional"},{"description":"The multiplicative factor applied to weights.","name":"scale","option":"optional"}],"description":"\nEvery `stepsize` iterations, multiply the weights by a constant `scale`:\n nw = w * scale\n","inputs":[{"description":"Current weights","name":"w"},{"description":"Training Iteration","name":"iter"}],"outputs":[{"description":"Updated weights","name":"nw"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsWeightedSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nApproximately fused operator of\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + SparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere's race condition w.r.t. ordering between reading params and writing to\nparam, hence the name Approx.\nThere're auxiliary inputs (aux_param) for which gradient is computed and\nreturns (aux_grad).\nYet additional input (lengths) is for fused\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradients","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsWeightedSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + RowWiseSparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere're auxiliary inputs (aux_param) for which gradient is computed and\nreturns (aux_grad).\nYet additional input (lengths) is for fused SparseLengthsWeightedSumGradient\noperator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsWeightedSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + SparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere're auxiliary inputs (aux_param) for which gradient is computed\nand returns (aux_grad).\nYet additional input (lengths) is for fused\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsWeightedSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nApproximately fused operator of\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + RowWiseSparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere's race condition w.r.t. ordering between reading params and writing to\nparam, hence the name Approx.\nThere're auxiliary inputs (aux_param) for which gradient is computed\nand returns (aux_grad).\nYet additional input (lengths) is for fused SparseLengthsWeightedSumGradient\noperator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"SparseLengthsSumSparseLookup","schema":{"description":"\nThis op converts compressed indices of SparseLengthsSum*Sparse to\nuncompressed indices of SparseLengthsSum*. For compressed indices that maps\nto -1. It means it will correspond to a zero row in the uncompressed data.\nTherefore we will remove this indices and adjust the lengths.\n","inputs":[{"description":"Integer vector containing compressed indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of INDICES","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"},{"description":"Vector of weights to scale rows of DATA with before reduction. Same size as INDICES.","name":"WEIGHTS"}],"outputs":[{"description":"Uncompressed indices","name":"output_indices"},{"description":"Adjusted lengths","name":"output_lengths"},{"description":"Adjusted weights","name":"output_weights"}],"support_level":"default"}},{"name":"Storm","schema":{"attributes":[{"description":"Momentum hyperparameter, c in the original paper.","name":"momentum","option":"optional"},{"description":"denominator in adaptive learning rate, w in the original paper.","name":"beta","option":"optional"}],"description":"\n\nComputes the STORM (https://arxiv.org/abs/1905.10018) update for an input\ngradient and accumulated history of gradients. Concretely, given inputs\n(param, moment, grad_sq_sum, grad, lr), computes:\n\n new_grad_sq_sum = grad_sq_sum + norm(grad)^2\n effective_lr = lr / (beta + new_grad_sq_sum)^1/3\n alpha = momentum * square(effective_lr)\n new_moment = grad + (1 - alpha) * (moment - grad)\n new_param = param + effective_lr * new_moment\n\nand returns (new_param, new_moment, new_grad_sq_sum).\n\nNote that due to caffe2 limitation, it is difficult to re-calculate gradient\nin the previous iteration using the current example. We simplied calculation\nfor new_moment by using the gradient from the current iteration.\n\n","inputs":[{"description":"Parameters to be updated.","name":"param"},{"description":"Moment history.","name":"moment"},{"description":"Sum of observed squared gradients.","name":"grad_sq_sum"},{"description":"Gradients computed.","name":"grad"},{"description":"Learning rate, k in the original paper.","name":"lr"}],"outputs":[{"description":"Updated parameters.","name":"output_param"},{"description":"Updated moment.","name":"output_moment"},{"description":"Updated sum of squared gradients.","name":"output_grad_sq_sum"}],"support_level":"default"}},{"name":"SparseStorm","schema":{"attributes":[{"description":"Momentum hyperparameter, c in the original paper.","name":"momentum","option":"optional"},{"description":"denominator in adaptive learning rate, w in the original paper.","name":"beta","option":"optional"}],"description":"\n\nThis operator implement the STORM (https://arxiv.org/abs/1905.10018)\noptimization algorithm. Given inputs (param, moment, grad_sq_sum, grad,\nindices, lr), computes the dense STORM update on (param, moment[indices],\ngrad_sq_sum, grad, lr), and returns (new_param, new_moment, new_grad_sq_sum)\nas in the dense case.\n","inputs":[{"description":"Parameters to be updated.","name":"param"},{"description":"Moment history.","name":"moment"},{"description":"Sum of observed squared gradients.","name":"grad_sq_sum"},{"description":"Gradients computed.","name":"grad"},{"description":"Sparse indices.","name":"indices"},{"description":"Learning rate, k in the original paper.","name":"lr"}],"outputs":[{"description":"Updated parameters.","name":"output_param"},{"description":"Updated moment.","name":"output_moment"},{"description":"Updated sum of squared gradients.","name":"output_grad_sq_sum"}],"support_level":"default"}},{"name":"FbGemmPackTranspose","schema":{"description":"Prepack weight for fbgemm","inputs":[{"description":"col major format weight matrix","name":"X"}],"outputs":[{"description":"Block col major packed format weight matrix","name":"Y"}],"support_level":"default"}},{"name":"FbGemmPack","schema":{"description":"Prepack weight for fbgemm","inputs":[{"description":"row major format weight matrix","name":"X"}],"outputs":[{"description":"Block row major packed format weight matrix","name":"Y"}],"support_level":"default"}},{"name":"FbFCPacked","schema":{"description":"Same as FC,\n but the weight is prepacked as a fbgemm::PackedGemmMatrixFP16","support_level":"default"}},{"name":"Histogram","schema":{"attributes":[{"description":"length-(k + 1) sequence of float values wherein the i-th element represents the inclusive left boundary of the i-th bin for i in [0, k - 1] and the exclusive right boundary of the (i-1)-th bin for i in [1, k].","name":"bin_edges","option":"optional"}],"description":"\n Computes a histogram for values in the given list of tensors.\n For logging activation histograms for post-hoc analyses, consider using the\n HistogramObserver observer.\n For iteratively computing a histogram for all input tensors encountered through\n history, consider using the AccumulateHistogram operator.\n ","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"1D tensor of length k, wherein the i-th element expresses the count of tensor values that fall within range [bin_edges[i], bin_edges[i + 1])","name":"histogram"}],"support_level":"default"}},{"name":"SparseLpRegularizer","schema":{"attributes":[{"description":"Value of p in the Lp regularization to use. The default is 2.0.","name":"p","option":"optional"},{"description":"Value of lambda (multiplier for the regularization term). The default is 1e-5.","name":"reg_lambda","option":"optional"}],"description":"\nGiven a sparse matrix, apply Lp regularization. Currently only L1 and L2 are implemented.\n","inputs":[{"description":"Parameters to be regularized","name":"param"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed (optional - not used, this argument is for backwards compatibility)","name":"grad"}],"outputs":[{"description":"Regularized parameters","name":"output_param"}],"support_level":"default"}},{"name":"Int8GenQuantParams","schema":{"description":"Operator wrapper for generating int8 tensor quantization parameters given the input data and quant scheme","inputs":[{"description":"The input data, or last N samples of the output activations.","name":"X"},{"description":"Int8QuantSchemeBlob that specifies the quantization kind and preserve_sparsity options when generating the quant params.","name":"quant_scheme"}],"outputs":[{"description":"Int8QuantParamsBlob that contains the scale and zero_point info in TensorQuantizationParams type.","name":"quant_param"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsSumGradientApprox","schema":{"attributes":[{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"MishGradient","schema":{"description":"\nMishGradient takes X, Y and dY and uses this to update dX according to the\nchain rule and derivatives of the Mish function.\n","support_level":"default"}},{"name":"SelfBinningHistogram","schema":{"attributes":[{"description":"Number of bins to use for the histogram. Must be >= 1.","name":"num_bins","option":"optional"},{"description":"A string indicating 'linear' or 'logarithmic' spacing for the bins.","name":"bin_spacing","option":"optional"},{"description":"A float that's used as the starting point for logarithmic spacing. Since logarithmic spacing cannot contain <=0 values this value will be used to represent all such values.","name":"logspace_start","option":"optional"}],"description":"\n Computes a histogram for values in the given list of tensors.\n For logging activation histograms for post-hoc analyses, consider using the\n HistogramObserver observer.\n For iteratively computing a histogram for all input tensors encountered through\n history, consider using the AccumulateHistogram operator.\n ","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"1D tensor of edges of the bins, of dimension [num_bins+1]. The range appears as: [first, ..., last), wherein the i-th element expresses the start of a bin and i+1-th value represents the exclusive end of that bin.","name":"histogram_values"},{"description":"1D tensor of counts of each bin, of dimension [num_bins+1]. It is guaranteed to end with a 0 since the last edge is exclusive.","name":"histogram_counts"}],"support_level":"default"}},{"name":"Mish","schema":{"description":"\nMish takes one input data (Tensor) and produces one output data\n(Tensor) where the Mish function, y = x / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsMeanGradientApprox","schema":{"attributes":[{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsMeanGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsMeanGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsMeanGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..559579d5546c75d53e478646f4c3a19d329cb879 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("caffe2");$root.caffe2={},$root.caffe2.ExternalDataProto=class{constructor(){this.strides=[]}static decode(e,t){const o=new $root.caffe2.ExternalDataProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.source_type=e.int32();break;case 2:o.record_id=e.string();break;case 5:o.record_size=e.uint64();break;case 3:o.offset=e.int64();break;case 4:o.strides=e.array(o.strides,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.ExternalDataProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"source_type":t.source_type=e.enum($root.caffe2.ExternalDataProto.SourceType);break;case"record_id":t.record_id=e.string();break;case"record_size":t.record_size=e.integer();break;case"offset":t.offset=e.integer();break;case"strides":e.array(t.strides,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.caffe2.ExternalDataProto.prototype.source_type=0,$root.caffe2.ExternalDataProto.prototype.record_id="",$root.caffe2.ExternalDataProto.prototype.record_size=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.caffe2.ExternalDataProto.prototype.offset=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExternalDataProto.SourceType={INLINE_CONTAINER:0,SIMPLE_FILE:1},$root.caffe2.TensorProto=class{constructor(){this.dims=[],this.float_data=[],this.int32_data=[],this.string_data=[],this.double_data=[],this.int64_data=[]}static decode(e,t){const o=new $root.caffe2.TensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.data_type=e.int32();break;case 12:o.storage_type=e.int32();break;case 3:o.float_data=e.floats(o.float_data,t);break;case 4:o.int32_data=e.array(o.int32_data,(()=>e.int32()),t);break;case 5:o.byte_data=e.bytes();break;case 6:o.string_data.push(e.bytes());break;case 9:o.double_data=e.doubles(o.double_data,t);break;case 10:o.int64_data=e.array(o.int64_data,(()=>e.int64()),t);break;case 13:o.raw_data=e.bytes();break;case 14:o.external_data=$root.caffe2.ExternalDataProto.decode(e,e.uint32());break;case 7:o.name=e.string();break;case 8:o.device_detail=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 11:o.segment=$root.caffe2.TensorProto.Segment.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"storage_type":t.storage_type=e.enum($root.caffe2.TensorProto.StorageType);break;case"float_data":e.array(t.float_data,(()=>e.float()));break;case"int32_data":e.array(t.int32_data,(()=>e.integer()));break;case"byte_data":t.byte_data=e.bytes();break;case"string_data":e.array(t.string_data,(()=>e.bytes()));break;case"double_data":e.array(t.double_data,(()=>e.float()));break;case"int64_data":e.array(t.int64_data,(()=>e.integer()));break;case"raw_data":t.raw_data=e.bytes();break;case"external_data":t.external_data=$root.caffe2.ExternalDataProto.decodeText(e,!0);break;case"name":t.name=e.string();break;case"device_detail":t.device_detail=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"segment":t.segment=$root.caffe2.TensorProto.Segment.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.caffe2.TensorProto.prototype.data_type=1,$root.caffe2.TensorProto.prototype.storage_type=1,$root.caffe2.TensorProto.prototype.byte_data=new Uint8Array([]),$root.caffe2.TensorProto.prototype.raw_data=new Uint8Array([]),$root.caffe2.TensorProto.prototype.external_data=null,$root.caffe2.TensorProto.prototype.name="",$root.caffe2.TensorProto.prototype.device_detail=null,$root.caffe2.TensorProto.prototype.segment=null,$root.caffe2.TensorProto.DataType={UNDEFINED:0,FLOAT:1,INT32:2,BYTE:3,STRING:4,BOOL:5,UINT8:6,INT8:7,UINT16:8,INT16:9,INT64:10,FLOAT16:12,DOUBLE:13,ZERO_COLLISION_HASH:14},$root.caffe2.TensorProto.StorageType={TYPED:1,RAW:2,EXTERNAL:3,NO_CONTENT:4},$root.caffe2.TensorProto.Segment=class{constructor(){}static decode(e,t){const o=new $root.caffe2.TensorProto.Segment,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.begin=e.int64();break;case 2:o.end=e.int64();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"begin"))throw new protobuf.Error("Excepted 'begin'.");if(!Object.prototype.hasOwnProperty.call(o,"end"))throw new protobuf.Error("Excepted 'end'.");return o}static decodeText(e){const t=new $root.caffe2.TensorProto.Segment;for(e.start();!e.end();){const o=e.tag();switch(o){case"begin":t.begin=e.integer();break;case"end":t.end=e.integer();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"begin"))throw new protobuf.Error("Excepted 'begin'.");if(!Object.prototype.hasOwnProperty.call(t,"end"))throw new protobuf.Error("Excepted 'end'.");return t}},$root.caffe2.TensorProto.Segment.prototype.begin=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.TensorProto.Segment.prototype.end=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.QTensorProto=class{constructor(){this.dims=[],this.data=[],this.scales=[],this.biases=[]}static decode(e,t){const o=new $root.caffe2.QTensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.precision=e.int32();break;case 3:o.scale=e.double();break;case 4:o.bias=e.double();break;case 5:o.is_signed=e.bool();break;case 6:o.data=e.array(o.data,(()=>e.int32()),t);break;case 7:o.name=e.string();break;case 8:o.data_type=e.int32();break;case 9:o.scales=e.doubles(o.scales,t);break;case 10:o.biases=e.doubles(o.biases,t);break;case 11:o.axis=e.int32();break;case 12:o.is_multiparam=e.bool();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"precision"))throw new protobuf.Error("Excepted 'precision'.");if(!Object.prototype.hasOwnProperty.call(o,"scale"))throw new protobuf.Error("Excepted 'scale'.");if(!Object.prototype.hasOwnProperty.call(o,"bias"))throw new protobuf.Error("Excepted 'bias'.");if(!Object.prototype.hasOwnProperty.call(o,"is_signed"))throw new protobuf.Error("Excepted 'is_signed'.");return o}static decodeText(e){const t=new $root.caffe2.QTensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"precision":t.precision=e.integer();break;case"scale":t.scale=e.float();break;case"bias":t.bias=e.float();break;case"is_signed":t.is_signed=e.boolean();break;case"data":e.array(t.data,(()=>e.integer()));break;case"name":t.name=e.string();break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"scales":e.array(t.scales,(()=>e.float()));break;case"biases":e.array(t.biases,(()=>e.float()));break;case"axis":t.axis=e.integer();break;case"is_multiparam":t.is_multiparam=e.boolean();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"precision"))throw new protobuf.Error("Excepted 'precision'.");if(!Object.prototype.hasOwnProperty.call(t,"scale"))throw new protobuf.Error("Excepted 'scale'.");if(!Object.prototype.hasOwnProperty.call(t,"bias"))throw new protobuf.Error("Excepted 'bias'.");if(!Object.prototype.hasOwnProperty.call(t,"is_signed"))throw new protobuf.Error("Excepted 'is_signed'.");return t}},$root.caffe2.QTensorProto.prototype.precision=0,$root.caffe2.QTensorProto.prototype.scale=0,$root.caffe2.QTensorProto.prototype.bias=0,$root.caffe2.QTensorProto.prototype.is_signed=!1,$root.caffe2.QTensorProto.prototype.name="",$root.caffe2.QTensorProto.prototype.data_type=2,$root.caffe2.QTensorProto.prototype.axis=0,$root.caffe2.QTensorProto.prototype.is_multiparam=!1,$root.caffe2.TensorProtos=class{constructor(){this.protos=[]}static decode(e,t){const o=new $root.caffe2.TensorProtos,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.protos.push($root.caffe2.TensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorProtos;for(e.start();!e.end();){const o=e.tag();switch(o){case"protos":t.protos.push($root.caffe2.TensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.TensorShape=class{constructor(){this.dims=[],this.unknown_dims=[]}static decode(e,t){const o=new $root.caffe2.TensorShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.data_type=e.int32();break;case 3:o.unknown_dims=e.array(o.unknown_dims,(()=>e.int32()),t);break;case 4:o.unknown_shape=e.bool();break;case 5:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"unknown_dims":e.array(t.unknown_dims,(()=>e.integer()));break;case"unknown_shape":t.unknown_shape=e.boolean();break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorShape.prototype.data_type=1,$root.caffe2.TensorShape.prototype.unknown_shape=!1,$root.caffe2.TensorShape.prototype.name="",$root.caffe2.TensorShapes=class{constructor(){this.shapes=[]}static decode(e,t){const o=new $root.caffe2.TensorShapes,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shapes.push($root.caffe2.TensorShape.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorShapes;for(e.start();!e.end();){const o=e.tag();switch(o){case"shapes":t.shapes.push($root.caffe2.TensorShape.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShape=class{constructor(){this.dim_type=[]}static decode(e,t){const o=new $root.caffe2.TensorBoundShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shape=$root.caffe2.TensorShape.decode(e,e.uint32());break;case 2:o.dim_type=e.array(o.dim_type,(()=>e.int32()),t);break;case 3:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorBoundShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"shape":t.shape=$root.caffe2.TensorShape.decodeText(e,!0);break;case"dim_type":e.array(t.dim_type,(()=>e.enum($root.caffe2.TensorBoundShape.DimType)));break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShape.prototype.shape=null,$root.caffe2.TensorBoundShape.prototype.name="",$root.caffe2.TensorBoundShape.DimType={UNKNOWN:0,CONSTANT:1,BATCH:2,BATCH_OF_FEATURE_MAX:3,BATCH_OF_FEATURE_MAX_DEFAULT:4,FEATURE_MAX:5,FEATURE_MAX_DEFAULT:6},$root.caffe2.TensorBoundShapes=class{constructor(){this.shapes=[]}static decode(e,t){const o=new $root.caffe2.TensorBoundShapes,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shapes.push($root.caffe2.TensorBoundShape.decode(e,e.uint32()));break;case 2:o.max_batch_size=e.int64();break;case 3:o.max_feature_len=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorBoundShapes;for(e.start();!e.end();){const o=e.tag();switch(o){case"shapes":t.shapes.push($root.caffe2.TensorBoundShape.decodeText(e,!0));break;case"max_batch_size":t.max_batch_size=e.integer();break;case"max_feature_len":t.max_feature_len=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShapes.prototype.max_batch_size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.TensorBoundShapes.prototype.max_feature_len=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.Argument=class{constructor(){this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.nets=[],this.qtensors=[]}static decode(e,t){const o=new $root.caffe2.Argument,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.f=e.float();break;case 3:o.i=e.int64();break;case 4:o.s=e.bytes();break;case 10:o.t=$root.caffe2.TensorProto.decode(e,e.uint32());break;case 8:o.n=$root.caffe2.NetDef.decode(e,e.uint32());break;case 5:o.floats=e.floats(o.floats,t);break;case 6:o.ints=e.array(o.ints,(()=>e.int64()),t);break;case 7:o.strings.push(e.bytes());break;case 11:o.tensors.push($root.caffe2.TensorProto.decode(e,e.uint32()));break;case 9:o.nets.push($root.caffe2.NetDef.decode(e,e.uint32()));break;case 12:o.qtensors.push($root.caffe2.QTensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.Argument;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"f":t.f=e.float();break;case"i":t.i=e.integer();break;case"s":t.s=e.bytes();break;case"t":t.t=$root.caffe2.TensorProto.decodeText(e,!0);break;case"n":t.n=$root.caffe2.NetDef.decodeText(e,!0);break;case"floats":e.array(t.floats,(()=>e.float()));break;case"ints":e.array(t.ints,(()=>e.integer()));break;case"strings":e.array(t.strings,(()=>e.bytes()));break;case"tensors":t.tensors.push($root.caffe2.TensorProto.decodeText(e,!0));break;case"nets":t.nets.push($root.caffe2.NetDef.decodeText(e,!0));break;case"qtensors":t.qtensors.push($root.caffe2.QTensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.Argument.prototype.name="",$root.caffe2.Argument.prototype.f=0,$root.caffe2.Argument.prototype.i=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.Argument.prototype.s=new Uint8Array([]),$root.caffe2.Argument.prototype.t=null,$root.caffe2.Argument.prototype.n=null,$root.caffe2.DeviceTypeProto={PROTO_CPU:0,PROTO_CUDA:1,PROTO_MKLDNN:2,PROTO_OPENGL:3,PROTO_OPENCL:4,PROTO_IDEEP:5,PROTO_HIP:6,PROTO_FPGA:7,PROTO_MSNPU:8,PROTO_XLA:9,PROTO_COMPILE_TIME_MAX_DEVICE_TYPES:10,PROTO_ONLY_FOR_TEST:20901},$root.caffe2.DeviceOption=class{constructor(){this.extra_info=[]}static decode(e,t){const o=new $root.caffe2.DeviceOption,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device_type=e.int32();break;case 2:o.device_id=e.int32();break;case 3:o.random_seed=e.uint32();break;case 4:o.node_name=e.string();break;case 5:o.numa_node_id=e.int32();break;case 6:o.extra_info.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.DeviceOption;for(e.start();!e.end();){const o=e.tag();switch(o){case"device_type":t.device_type=e.integer();break;case"device_id":t.device_id=e.integer();break;case"random_seed":t.random_seed=e.integer();break;case"node_name":t.node_name=e.string();break;case"numa_node_id":t.numa_node_id=e.integer();break;case"extra_info":e.array(t.extra_info,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.caffe2.DeviceOption.prototype.device_type=0,$root.caffe2.DeviceOption.prototype.device_id=0,$root.caffe2.DeviceOption.prototype.random_seed=0,$root.caffe2.DeviceOption.prototype.node_name="",$root.caffe2.DeviceOption.prototype.numa_node_id=0,$root.caffe2.OperatorDef=class{constructor(){this.input=[],this.output=[],this.arg=[],this.control_input=[]}static decode(e,t){const o=new $root.caffe2.OperatorDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.input.push(e.string());break;case 2:o.output.push(e.string());break;case 3:o.name=e.string();break;case 4:o.type=e.string();break;case 5:o.arg.push($root.caffe2.Argument.decode(e,e.uint32()));break;case 6:o.device_option=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 7:o.engine=e.string();break;case 8:o.control_input.push(e.string());break;case 9:o.is_gradient_op=e.bool();break;case 10:o.debug_info=e.string();break;case 11:o.domain=e.string();break;case 12:o.op_version=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.OperatorDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"input":e.array(t.input,(()=>e.string()));break;case"output":e.array(t.output,(()=>e.string()));break;case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"arg":t.arg.push($root.caffe2.Argument.decodeText(e,!0));break;case"device_option":t.device_option=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"engine":t.engine=e.string();break;case"control_input":e.array(t.control_input,(()=>e.string()));break;case"is_gradient_op":t.is_gradient_op=e.boolean();break;case"debug_info":t.debug_info=e.string();break;case"domain":t.domain=e.string();break;case"op_version":t.op_version=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.OperatorDef.prototype.name="",$root.caffe2.OperatorDef.prototype.type="",$root.caffe2.OperatorDef.prototype.device_option=null,$root.caffe2.OperatorDef.prototype.engine="",$root.caffe2.OperatorDef.prototype.is_gradient_op=!1,$root.caffe2.OperatorDef.prototype.debug_info="",$root.caffe2.OperatorDef.prototype.domain="",$root.caffe2.OperatorDef.prototype.op_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.MapFieldEntry=class{constructor(){}static decode(e,t){const o=new $root.caffe2.MapFieldEntry,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.key=e.string();break;case 2:o.val=e.string();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"key"))throw new protobuf.Error("Excepted 'key'.");if(!Object.prototype.hasOwnProperty.call(o,"val"))throw new protobuf.Error("Excepted 'val'.");return o}static decodeText(e){const t=new $root.caffe2.MapFieldEntry;for(e.start();!e.end();){const o=e.tag();switch(o){case"key":t.key=e.string();break;case"val":t.val=e.string();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"key"))throw new protobuf.Error("Excepted 'key'.");if(!Object.prototype.hasOwnProperty.call(t,"val"))throw new protobuf.Error("Excepted 'val'.");return t}},$root.caffe2.MapFieldEntry.prototype.key="",$root.caffe2.MapFieldEntry.prototype.val="",$root.caffe2.BackendOptions=class{constructor(){this.option=[]}static decode(e,t){const o=new $root.caffe2.BackendOptions,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.backend_name=e.string();break;case 2:o.option.push($root.caffe2.MapFieldEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"backend_name"))throw new protobuf.Error("Excepted 'backend_name'.");return o}static decodeText(e){const t=new $root.caffe2.BackendOptions;for(e.start();!e.end();){const o=e.tag();switch(o){case"backend_name":t.backend_name=e.string();break;case"option":t.option.push($root.caffe2.MapFieldEntry.decodeText(e,!0));break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"backend_name"))throw new protobuf.Error("Excepted 'backend_name'.");return t}},$root.caffe2.BackendOptions.prototype.backend_name="",$root.caffe2.PartitionInfo=class{constructor(){this.device_id=[],this.backend_options=[]}static decode(e,t){const o=new $root.caffe2.PartitionInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.device_id=e.array(o.device_id,(()=>e.int32()),t);break;case 3:o.extra_info=e.string();break;case 4:o.backend_options.push($root.caffe2.BackendOptions.decode(e,e.uint32()));break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"name"))throw new protobuf.Error("Excepted 'name'.");return o}static decodeText(e){const t=new $root.caffe2.PartitionInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"device_id":e.array(t.device_id,(()=>e.integer()));break;case"extra_info":t.extra_info=e.string();break;case"backend_options":t.backend_options.push($root.caffe2.BackendOptions.decodeText(e,!0));break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"name"))throw new protobuf.Error("Excepted 'name'.");return t}},$root.caffe2.PartitionInfo.prototype.name="",$root.caffe2.PartitionInfo.prototype.extra_info="",$root.caffe2.NetDef=class{constructor(){this.op=[],this.arg=[],this.external_input=[],this.external_output=[],this.partition_info=[]}static decode(e,t){const o=new $root.caffe2.NetDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.op.push($root.caffe2.OperatorDef.decode(e,e.uint32()));break;case 3:o.type=e.string();break;case 4:o.num_workers=e.int32();break;case 5:o.device_option=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 6:o.arg.push($root.caffe2.Argument.decode(e,e.uint32()));break;case 7:o.external_input.push(e.string());break;case 8:o.external_output.push(e.string());break;case 9:o.partition_info.push($root.caffe2.PartitionInfo.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.NetDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"op":t.op.push($root.caffe2.OperatorDef.decodeText(e,!0));break;case"type":t.type=e.string();break;case"num_workers":t.num_workers=e.integer();break;case"device_option":t.device_option=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"arg":t.arg.push($root.caffe2.Argument.decodeText(e,!0));break;case"external_input":e.array(t.external_input,(()=>e.string()));break;case"external_output":e.array(t.external_output,(()=>e.string()));break;case"partition_info":t.partition_info.push($root.caffe2.PartitionInfo.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.NetDef.prototype.name="",$root.caffe2.NetDef.prototype.type="",$root.caffe2.NetDef.prototype.num_workers=0,$root.caffe2.NetDef.prototype.device_option=null,$root.caffe2.ExecutionStep=class{constructor(){this.substep=[],this.network=[]}static decode(e,t){const o=new $root.caffe2.ExecutionStep,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.substep.push($root.caffe2.ExecutionStep.decode(e,e.uint32()));break;case 3:o.network.push(e.string());break;case 4:o.num_iter=e.int64();break;case 5:o.criteria_network=e.string();break;case 7:o.report_net=e.string();break;case 8:o.report_interval=e.int32();break;case 11:o.run_every_ms=e.int64();break;case 6:o.concurrent_substeps=e.bool();break;case 9:o.should_stop_blob=e.string();break;case 10:o.only_once=e.bool();break;case 12:o.create_workspace=e.bool();break;case 13:o.num_concurrent_instances=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.ExecutionStep;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"substep":t.substep.push($root.caffe2.ExecutionStep.decodeText(e,!0));break;case"network":e.array(t.network,(()=>e.string()));break;case"num_iter":t.num_iter=e.integer();break;case"criteria_network":t.criteria_network=e.string();break;case"report_net":t.report_net=e.string();break;case"report_interval":t.report_interval=e.integer();break;case"run_every_ms":t.run_every_ms=e.integer();break;case"concurrent_substeps":t.concurrent_substeps=e.boolean();break;case"should_stop_blob":t.should_stop_blob=e.string();break;case"only_once":t.only_once=e.boolean();break;case"create_workspace":t.create_workspace=e.boolean();break;case"num_concurrent_instances":t.num_concurrent_instances=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.ExecutionStep.prototype.name="",$root.caffe2.ExecutionStep.prototype.num_iter=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExecutionStep.prototype.criteria_network="",$root.caffe2.ExecutionStep.prototype.report_net="",$root.caffe2.ExecutionStep.prototype.report_interval=0,$root.caffe2.ExecutionStep.prototype.run_every_ms=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExecutionStep.prototype.concurrent_substeps=!1,$root.caffe2.ExecutionStep.prototype.should_stop_blob="",$root.caffe2.ExecutionStep.prototype.only_once=!1,$root.caffe2.ExecutionStep.prototype.create_workspace=!1,$root.caffe2.ExecutionStep.prototype.num_concurrent_instances=0,$root.caffe2.PlanDef=class{constructor(){this.network=[],this.execution_step=[]}static decode(e,t){const o=new $root.caffe2.PlanDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.network.push($root.caffe2.NetDef.decode(e,e.uint32()));break;case 3:o.execution_step.push($root.caffe2.ExecutionStep.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.PlanDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"network":t.network.push($root.caffe2.NetDef.decodeText(e,!0));break;case"execution_step":t.execution_step.push($root.caffe2.ExecutionStep.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.PlanDef.prototype.name="",$root.caffe2.BlobProto=class{constructor(){}static decode(e,t){const o=new $root.caffe2.BlobProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.type=e.string();break;case 3:o.tensor=$root.caffe2.TensorProto.decode(e,e.uint32());break;case 4:o.content=e.bytes();break;case 5:o.qtensor=$root.caffe2.QTensorProto.decode(e,e.uint32());break;case 6:o.content_num_chunks=e.int32();break;case 7:o.content_chunk_id=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.BlobProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"tensor":t.tensor=$root.caffe2.TensorProto.decodeText(e,!0);break;case"content":t.content=e.bytes();break;case"qtensor":t.qtensor=$root.caffe2.QTensorProto.decodeText(e,!0);break;case"content_num_chunks":t.content_num_chunks=e.integer();break;case"content_chunk_id":t.content_chunk_id=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.BlobProto.prototype.name="",$root.caffe2.BlobProto.prototype.type="",$root.caffe2.BlobProto.prototype.tensor=null,$root.caffe2.BlobProto.prototype.content=new Uint8Array([]),$root.caffe2.BlobProto.prototype.qtensor=null,$root.caffe2.BlobProto.prototype.content_num_chunks=0,$root.caffe2.BlobProto.prototype.content_chunk_id=0,$root.caffe2.DBReaderProto=class{constructor(){}static decode(e,t){const o=new $root.caffe2.DBReaderProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.source=e.string();break;case 3:o.db_type=e.string();break;case 4:o.key=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.DBReaderProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"source":t.source=e.string();break;case"db_type":t.db_type=e.string();break;case"key":t.key=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.DBReaderProto.prototype.name="",$root.caffe2.DBReaderProto.prototype.source="",$root.caffe2.DBReaderProto.prototype.db_type="",$root.caffe2.DBReaderProto.prototype.key=""; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2.js new file mode 100644 index 0000000000000000000000000000000000000000..bbaa522e292a0efcc084edbb69ad96d911046571 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/caffe2.js @@ -0,0 +1 @@ +var caffe2=caffe2||{},protobuf=protobuf||require("./protobuf");caffe2.ModelFactory=class{match(t){const e=t.identifier.toLowerCase(),n=e.split(".").pop().toLowerCase();if("pb"==n){if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb")||e.startsWith("predict_net")||e.startsWith("init_net"))return!0;const n=t.tags("pb");if(n.size>0&&n.has(1)&&0==n.get(1)&&n.has(2)&&0==n.get(2)&&n.has(9)&&2==n.get(9))return!1;if(n.size>0&&Array.from(n.values()).some((t=>5===t)))return!1;if(!(!(n.size>0)||n.has(1)&&2!==n.get(1)||n.has(2)&&2!==n.get(2)||n.has(7)&&2!==n.get(7)||n.has(8)&&2!==n.get(8))){const e=t.buffer;if(e.length>3&&10==e[0]){const t=e[1];if(t<64&&e.length>2+t+1&&e.slice(2,2+t).every((t=>t>=32&&t<=127))&&18==e[2+t])return!0}if(e.length>3&&18==e[0])return!0}}if("pbtxt"==n||"prototxt"==n){if(e.endsWith("predict_net"))return!0;if(t.tags("pbtxt").has("op"))return"ops.pbtxt"!==t.identifier||-1===t.text.indexOf(" attr {")}return!1}open(t,e){return e.require("./caffe2-proto").then((()=>caffe2.Metadata.open(e).then((n=>{const a=t.identifier,i=a.split("."),s=i.pop().toLowerCase(),r=i.join(".");if("pbtxt"==s||"prototxt"==s){const i=(t,i)=>{let s=null,r=null;try{caffe2.proto=protobuf.get("caffe2").caffe2;const e=protobuf.TextReader.create(t);e.field=function(t,e){if(!(e instanceof caffe2.proto.DeviceOption))throw new Error("Unknown field '"+t+"'"+this.location());e[t]=this.skip()},s=caffe2.proto.NetDef.decodeText(e)}catch(t){throw new caffe2.Error("File text format is not caffe2.NetDef ("+t.message+") in '"+a+"'.")}try{caffe2.proto=protobuf.get("caffe2").caffe2,r="string"==typeof i?caffe2.proto.NetDef.decodeText(protobuf.TextReader.create(i)):caffe2.proto.NetDef.decode(protobuf.Reader.create(i))}catch(t){}try{return new caffe2.Model(n,s,r)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new caffe2.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}};return r.toLowerCase().endsWith("init_net")||r.toLowerCase().startsWith("init_net")?t.request(a.replace("init_net","predict_net"),"utf-8").then((e=>i(e,t.text))).catch((()=>i(t.text,null))):r.toLowerCase().endsWith("predict_net")||r.toLowerCase().startsWith("predict_net")?t.request(a.replace("predict_net","init_net").replace(/\.pbtxt/,".pb"),null).then((e=>i(t.text,e))).catch((()=>t.request(a.replace("predict_net","init_net"),"utf-8").then((e=>i(t.text,e))).catch((()=>i(t.text,null))))):t.request(r+"_init.pb",null).then((e=>i(t.text,e))).catch((()=>i(t.text,null)))}{const i=(t,i)=>{let s=null,r=null;try{caffe2.proto=protobuf.get("caffe2").caffe2;const e=protobuf.Reader.create(t);s=caffe2.proto.NetDef.decode(e)}catch(t){throw new caffe2.Error("File format is not caffe2.NetDef ("+t.message+") in '"+a+"'.")}try{if(i){caffe2.proto=protobuf.get("caffe2").caffe2;const t=protobuf.Reader.create(i);r=caffe2.proto.NetDef.decode(t)}}catch(t){}try{return new caffe2.Model(n,s,r)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new caffe2.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}};return r.toLowerCase().endsWith("init_net")?t.request(r.replace(/init_net$/,"")+"predict_net."+s,null).then((e=>i(e,t.buffer))).catch((()=>i(t.buffer,null))):r.toLowerCase().endsWith("_init")?t.request(r.replace(/_init$/,"")+"."+s,null).then((e=>i(e,t.buffer))).catch((()=>i(t.buffer,null))):r.toLowerCase().endsWith("predict_net")||r.toLowerCase().startsWith("predict_net")?t.request(a.replace("predict_net","init_net"),null).then((e=>i(t.buffer,e))).catch((()=>i(t.buffer,null))):t.request(r+"_init."+s,null).then((e=>i(t.buffer,e))).catch((()=>i(t.buffer,null)))}}))))}},caffe2.Model=class{constructor(t,e,n){this._domain=e.domain||null;const a=new caffe2.Graph(t,e,n);this._graphs=[a]}get format(){return"Caffe2"}get domain(){return this._domain}get graphs(){return this._graphs}},caffe2.Graph=class{constructor(t,e,n){this._name=e.name||"",this._type=e.type||"",this._nodes=[];const a=new Map;for(const t of e.external_input)a.set(t,{});if(n)for(const t of n.op)if(t.output&&1==t.output.length){const e=t.output[0];a.has(e)||a.set(e,{});const n=a.get(e);for(const e of t.arg)n[e.name]=e;switch(t.type){case"GivenTensorFill":n.dataType="float32";break;case"GivenTensorDoubleFill":n.dataType="float64";break;case"GivenTensorBoolFill":n.dataType="boolean";break;case"GivenTensorByteStringToUInt8Fill":n.dataType="uint8";break;case"GivenTensorInt16Fill":case"GivenTensorSInt16Fill":n.dataType="int16";break;case"GivenTensorIntFill":n.dataType="int32";break;case"GivenTensorInt64Fill":n.dataType="int64";break;case"GivenTensorStringFill":n.dataType="string";break;case"Int8GivenIntTensorFill":n.dataType="int32";break;case"Int8GivenTensorFill":n.dataType="int8";break;case"XavierFill":case"ConstantFill":break;default:throw new caffe2.Error("Unknown init op '"+t.type+"'.")}n.values&&n.values.floats&&(1!==n.values.floats.length||0!==n.values.floats[0])&&(n.input=!1)}const i={};let s=0;for(const t of e.op)t.input=t.input.map((t=>i[t]?i[t]:t)),t.output=t.output.map((t=>{if(i[t]){const e=t+"\n"+s.toString();return i[t]=e,e}return i[t]=t,t})),s++;let r=null,o=null;for(const n of e.op){const e=new caffe2.Node(t,n,a);1==n.input.length&&n.output.length>=1&&n.input[0].split("\n").shift()==n.output[0].split("\n").shift()&&r&&o==n.input[0].split("\n").shift()?r.chain.push(e):(this._nodes.push(e),r=null,o=null,1==n.output.length&&(r=e,o=n.output[0].split("\n").shift()))}this._inputs=[];for(const t of e.external_input){if(e.external_input.length>1){const e=a.get(t);if(e&&!1===e.input)continue}this._inputs.push(new caffe2.Parameter(t,[new caffe2.Argument(t,null,null)]))}this._outputs=[];for(const t of e.external_output)this._outputs.push(new caffe2.Parameter(t,[new caffe2.Argument(t,null,null)]))}get name(){return this._name}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}toString(){return"graph("+this.name+")"}},caffe2.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},caffe2.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new caffe2.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get quantization(){return this._initializer?this._initializer.quantization:null}get initializer(){return this._initializer}},caffe2.Node=class{constructor(t,e,n){this._name=e.name||"",this._device=e.engine||"",this._metadata=t,this._type=e.type,this._chain=[],this._attributes=[];for(const n of e.arg)this._attributes.push(new caffe2.Attribute(t,t.attribute(this._type,n.name),n));const a=t.type(this._type),i=e.input,s=e.output,r={};let o=0;for(const t of i){if(o>0&&n.has(t)){const e=n.get(t);r[t]=new caffe2.Tensor(t,e),e.input=!1}o++}for(const t of s)n.has(t)&&(n.get(t).input=!1);this._inputs=[];let u=0;if(a&&a.inputs){for(const t of a.inputs)if(u""!=e||"optional"!=t.option)).map((t=>new caffe2.Argument(t,null,r[t])));this._inputs.push(new caffe2.Parameter(t.name,n)),u+=e}}else this._inputs=this._inputs.concat(i.slice(u).map(((t,e)=>{const n=u+e==0?"input":(u+e).toString();return new caffe2.Parameter(n,[new caffe2.Argument(t,null,r[t])])})));this._outputs=[];let f=0;if(a&&a.outputs){for(const t of a.outputs)if(fnew caffe2.Argument(t)));this._outputs.push(new caffe2.Parameter(t.name,n)),f+=e}}else this._outputs=this._outputs.concat(s.slice(f).map(((t,e)=>{const n=f+e==0?"output":(f+e).toString();return new caffe2.Parameter(n,[new caffe2.Argument(t,null,null)])})))}get name(){return this._name||""}get device(){return this._device||""}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}},caffe2.Attribute=class{constructor(t,e,n){if(this._name=n.name,n.floats&&n.floats.length>0?this._value=n.floats:n.ints&&n.ints.length>0?this._value=n.ints:n.nets&&n.nets.length>0?(this._value=n.nets.map((e=>new caffe2.Graph(t,e,null))),this._type="graph[]"):n.n?(this._value=new caffe2.Graph(t,n.n,null),this._type="graph"):(n.i,this._value=n.i),e&&Object.prototype.hasOwnProperty.call(e,"type")&&(this._type=e.type,"boolean"==this._type))switch(this._value){case 1:this._value=!0;break;case 0:this._value=!1}e&&(Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible||Object.prototype.hasOwnProperty.call(e,"default")&&(this._value==e.default||this._value&&this._value.toString()==e.default.toString()))&&(this._visible=!1)}get name(){return this._name}get type(){return this._type||null}get value(){return this._value}get visible(){return 0!=this._visible}},caffe2.Tensor=class{constructor(t,e){this._name=t;const n=e.shape&&e.shape.ints?e.shape.ints:null;this._type=new caffe2.TensorType(e.dataType,new caffe2.TensorShape(n)),this._values=e.values||null,this._scale=e.Y_scale?e.Y_scale.f:0,this._zeroPoint=e.Y_zero_point?e.Y_zero_point.i:0}get name(){return this._name}get type(){return this._type}get kind(){return"Initializer"}get quantization(){return 0!=this._scale||0!=this._zeroPoint?this._scale.toString()+" * "+(0==this._zeroPoint?"q":"(q - "+this._zeroPoint.toString()+")"):null}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return caffe2.Tensor._stringify(e,""," ")}_context(){const t={state:null,index:0,count:0};if(!this._values)return t.state="Tensor data is empty.",t;if(void 0===this._values.floats)return t.state="Tensor data is too large to load in Chrome.",t;switch(this._type.dataType){case"float32":t.data=this._values.floats;break;case"boolean":t.data=this._values.ints;break;case"int8":t.data=new Int8Array(this._values.s);break;case"int32":t.data=this._values.ints;break;default:return t.state="Unknown data type.",t}return t.shape=this._type.shape.dimensions,t.dataType=this._type.dataType,t}_decode(t,e){const n=[],a=t.shape[e];if(e==t.shape.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"float32":n.push(t.data[t.index]);break;case"boolean":n.push(0!=t.data[t.index]);break;case"int8":case"int32":n.push(t.data[t.index]);break;default:t.state="Unknown data type."}t.index++,t.count++}else for(let i=0;it.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return n}static _stringify(t,e,n){if(Array.isArray(t)){const a=[];a.push(e+"[");const i=t.map((t=>caffe2.Tensor._stringify(t,e+n,n)));return i.length>0&&a.push(i.join(",\n")),a.push(e+"]"),a.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},caffe2.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType||"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},caffe2.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},caffe2.Metadata=class{static open(t){return caffe2.Metadata._metadata?Promise.resolve(caffe2.Metadata._metadata):t.request(null,"caffe2-metadata.json","utf-8").then((t=>(caffe2.Metadata._metadata=new caffe2.Metadata(t),caffe2.Metadata._metadata))).catch((()=>(caffe2.Metadata._metadata=new caffe2.Metadata(null),caffe2.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},caffe2.Error=class extends Error{constructor(t){super(t),this.name="Error loading Caffe2 model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=caffe2.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..86402d4440238fa827e1d6f2707da01c351f064e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-metadata.json @@ -0,0 +1 @@ +[{"name":"Negate","schema":{"operator":0,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sigmoid","schema":{"category":"Activation","operator":1,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Tanh","schema":{"category":"Activation","operator":2,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ReLU","schema":{"category":"Activation","operator":3,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"RectifiedLinear","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Exp","schema":{"operator":4,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Log","schema":{"operator":5,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sqrt","schema":{"operator":6,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Floor","schema":{"operator":7,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Abs","schema":{"operator":8}},{"name":"Reciprocal","schema":{"operator":9,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Softmax","schema":{"category":"Activation","operator":10,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Hardmax","schema":{"category":"Activation","operator":11}},{"name":"TransposeAxes","schema":{"category":"Activation","operator":12}},{"name":"TransposeDimensions","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Where","schema":{"operator":13,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Slice","schema":{"category":"Tensor","operator":14,"inputs":[{"name":"input"},{"name":"begin"},{"name":"end"}],"outputs":[{"name":"output"}]}},{"name":"Dropout","schema":{"category":"Dropout","operator":15,"attributes":[{"name":"rngSeed","visible":false},{"name":"rngOffset","visible":false}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Reshape","schema":{"category":"Shape","operator":16,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"MaxPooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"AveragePooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"category":"Pool","operator":17,"attributes":[{"name":"transpose","default":false},{"name":"includePad","default":false},{"name":"ceilOutDim","default":false},{"name":"autoPadding","default":[false,null]},{"name":"sharing","default":[true,null]},{"name":"strides","default":[1,null]},{"name":"lowerPad","default":[0,null]},{"name":"upperPad","default":[0,null]},{"name":"outputShape","default":0},{"name":"maxTempMemSizeInSamples","default":0},{"name":"poolingType","type":"PoolingType","default":"Max"},{"name":"poolKind","type":"PoolKind","default":"None"},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SumAll","schema":{"operator":18}},{"name":"Plus","schema":{"operator":19,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Minus","schema":{"operator":20,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"ElementTimes","schema":{"operator":21,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Equal","schema":{"operator":22,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"NotEqual","schema":{"operator":23,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Less","schema":{"operator":24,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"LessEqual","schema":{"operator":25,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Greater","schema":{"operator":26,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"GreaterEqual","schema":{"operator":27,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"PackedIndex","schema":{"operator":28,"inputs":[{"name":"source"},{"name":"index"}],"outputs":[{"name":"output"}]}},{"name":"GatherPacked","schema":{"operator":29,"inputs":[{"name":"index"},{"name":"source"}],"outputs":[{"name":"output"}]}},{"name":"ScatterPacked","schema":{"operator":30}},{"name":"Times","schema":{"operator":31,"attributes":[{"name":"outputRank","default":1},{"name":"inferInputRankToMap","visible":false,"default":-1}],"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"TransposeTimes","schema":{"operator":32}},{"name":"Convolution","schema":{"category":"Layer","operator":33,"attributes":[{"name":"transpose","default":false},{"name":"maxTempMemSizeInSamples","default":0},{"name":"dilation","default":[1,null]},{"name":"outputShape","default":0},{"name":"sharing","default":[true,null]},{"name":"strides","default":[1,null]},{"name":"includePad","default":false},{"name":"ceilOutDim","default":false},{"name":"autoPadding","default":[true,null]},{"name":"lowerPad","default":[0,null]},{"name":"upperPad","default":[0,null]},{"name":"convolution2D","visible":false},{"name":"poolKind","type":"PoolKind","default":"None"},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"},{"name":"W"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"SquaredError","schema":{"operator":34}},{"name":"CrossEntropyWithSoftmax","schema":{"operator":35,"outputs":[{"name":"output"}]}},{"name":"ClassificationError","schema":{"operator":36,"outputs":[{"name":"output"}]}},{"name":"PastValue","schema":{"operator":37,"attributes":[{"name":"offset","type":"uint32","default":1}],"inputs":[{"name":"input"},{"name":"initialState"}],"outputs":[{"name":"output"}]}},{"name":"FutureValue","schema":{"operator":38,"attributes":[{"name":"offset","type":"uint32","default":1}],"inputs":[{"name":"input"},{"name":"initialState"}],"outputs":[{"name":"output"}]}},{"name":"ReduceElements","schema":{"operator":39,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"BatchNormalization","schema":{"category":"Normalization","operator":40,"attributes":[{"name":"disableRegularization","default":false},{"name":"useCuDNNEngine","visible":false},{"name":"useCntkEngine","visible":false},{"name":"runCountUntied","visible":false},{"name":"epsilon","default":0.00001},{"name":"normalizationTimeConstant","default":0},{"name":"disableRegularization","default":false},{"name":"blendTimeConstant","default":0},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"},{"name":"mean"},{"name":"variance"},{"name":"count"}],"outputs":[{"name":"output"}]}},{"name":"Clip","schema":{"operator":41}},{"name":"Select","schema":{"operator":42}},{"name":"Splice","schema":{"category":"Tensor","operator":43,"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Combine","schema":{"category":"Tensor","operator":44,"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"RandomSample","schema":{"operator":45}},{"name":"RandomSampleInclusionFrequency","schema":{"operator":46}},{"name":"ROIPooling","schema":{"operator":47,"category":"Pool","attributes":[{"name":"spatialScale","default":0.0625},{"name":"poolKind","type":"PoolKind","default":"None"}],"inputs":[{"name":"inputs"},{"name":"ROIs"}],"outputs":[{"name":"outputs"}]}},{"name":"Logistic","schema":{"operator":48}},{"name":"OptimizedRNNStack","schema":{"operator":49}},{"name":"ReconcileDynamicAxis","schema":{"operator":50}},{"name":"LogSoftmax","schema":{"operator":51}},{"name":"LogPlus","schema":{"operator":52}},{"name":"CosDistance","schema":{"operator":53}},{"name":"Sin","schema":{"operator":54}},{"name":"Cos","schema":{"operator":55}},{"name":"Pass","schema":{"operator":56}},{"name":"Block","schema":{"operator":57}},{"name":"Unpooling","schema":{"operator":58}},{"name":"LambdaRank","schema":{"operator":59}},{"name":"NDCG","schema":{"operator":60}},{"name":"EditDistanceError","schema":{"operator":61}},{"name":"NoOp","schema":{"operator":62,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LabelsToGraph","schema":{"operator":63}},{"name":"StopGradient","schema":{"operator":64}},{"name":"ELU","schema":{"operator":65}},{"name":"ForwardBackward","schema":{"operator":66}},{"name":"CosDistanceWithNegativeSamples","schema":{"operator":67}},{"name":"OneHot","schema":{"operator":68}},{"name":"Pow","schema":{"operator":69}},{"name":"ToSequence","schema":{"operator":70}},{"name":"ToSequenceLike","schema":{"operator":71}},{"name":"UnpackSequence","schema":{"operator":72}},{"name":"Assign","schema":{"operator":73}},{"name":"Gather","schema":{"operator":74}},{"name":"StableSigmoid","schema":{"operator":75,"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"RandomDistribution","schema":{"operator":76}},{"name":"Sinh","schema":{"operator":77}},{"name":"Cosh","schema":{"operator":78}},{"name":"UnpackBatch","schema":{"operator":79}},{"name":"ToBatch","schema":{"operator":80}},{"name":"Asin","schema":{"operator":81}},{"name":"Acos","schema":{"operator":82}},{"name":"Pad","schema":{"operator":83,"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Crop","schema":{"operator":84,"category":"Data"}},{"name":"Atanh","schema":{"operator":85}},{"name":"Asinh","schema":{"operator":86}},{"name":"TopK","schema":{"operator":87,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Squeeze","schema":{"operator":88,"category":"Transform"}},{"name":"ConstantOp","schema":{"operator":89}},{"name":"LatticeSequenceWithSoftmax","schema":{"operator":90}},{"name":"Cast","schema":{"operator":91}},{"name":"EyeLikeOp","schema":{"operator":92}},{"name":"CustomProxyOp","schema":{"operator":93}},{"name":"StraightThrough","schema":{"operator":94}},{"name":"Tan","schema":{"operator":95}},{"name":"Atan","schema":{"operator":96}},{"name":"ConvolutionSequenceShape","schema":{"operator":97}},{"name":"Function:Dense","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"W"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"Function:Convolution","schema":{"category":"Layer","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:ConvolutionTranspose","schema":{"category":"Layer","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:Softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:linear","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"scale"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"Function:lrn","schema":{"category":"Normalization","outputs":[{"name":"output"}]}},{"name":"Function:PReLU","schema":{"category":"Activation","inputs":[{"name":"x"},{"name":"axis"},{"name":"slope"}],"outputs":[{"name":"y"}]}},{"name":"Function:ElementDivide","schema":{"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Function:BatchNormalization","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"},{"name":"mean"},{"name":"variance"},{"name":"count"}],"outputs":[{"name":"output"}]}},{"name":"Function:MaxPooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:AveragePooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:Dropout","schema":{"category":"Dropout","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:LSTM","schema":{"category":"Layer","inputs":[{"name":"0"},{"name":"1"},{"name":"2"},{"name":"b"},{"name":"W"},{"name":"H"}]}},{"name":"Mean","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"InvStdDev","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..08f0bd87fb1ff8bcbf5cfb3780b640b55dbf8708 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("cntk");$root.CNTK={},$root.CNTK.proto={},$root.CNTK.proto.NDShape=class{constructor(){this.shape_dim=[]}static decode(o,t){const e=new $root.CNTK.proto.NDShape,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.shape_dim=o.array(e.shape_dim,(()=>o.uint64()),t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Axis=class{constructor(){}static decode(o,t){const e=new $root.CNTK.proto.Axis,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.static_axis_idx=o.int32();break;case 2:e.name=o.string();break;case 3:e.is_ordered_dynamic_axis=o.bool();break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Axis.prototype.static_axis_idx=0,$root.CNTK.proto.Axis.prototype.name="",$root.CNTK.proto.Axis.prototype.is_ordered_dynamic_axis=!1,$root.CNTK.proto.NDArrayView=class{constructor(){}get values(){return $root.CNTK.proto.NDArrayView.valuesSet=$root.CNTK.proto.NDArrayView.valuesSet||new Set(["float_values","double_values","bytes_value","sint32_values"]),Object.keys(this).find((o=>$root.CNTK.proto.NDArrayView.valuesSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.data_type=o.int32();break;case 2:e.storage_format=o.int32();break;case 3:e.shape=$root.CNTK.proto.NDShape.decode(o,o.uint32());break;case 4:e.float_values=$root.CNTK.proto.NDArrayView.FloatValues.decode(o,o.uint32());break;case 5:e.double_values=$root.CNTK.proto.NDArrayView.DoubleValues.decode(o,o.uint32());break;case 6:e.bytes_value=$root.CNTK.proto.NDArrayView.BytesValue.decode(o,o.uint32());break;case 7:e.sint32_values=$root.CNTK.proto.NDArrayView.IntValues.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.prototype.data_type=0,$root.CNTK.proto.NDArrayView.prototype.storage_format=0,$root.CNTK.proto.NDArrayView.prototype.shape=null,$root.CNTK.proto.NDArrayView.DataType={Unknown:0,Float:1,Double:2,Float16:4,Int8:5,Int16:6},$root.CNTK.proto.NDArrayView.StorageFormat={Dense:0,SparseCSC:1,SparseBlockCol:2},$root.CNTK.proto.NDArrayView.FloatValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.FloatValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.floats(e.value,t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.DoubleValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.DoubleValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.doubles(e.value,t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.BytesValue=class{constructor(){}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.BytesValue,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.bytes();break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.BytesValue.prototype.value=new Uint8Array([]),$root.CNTK.proto.NDArrayView.IntValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.IntValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.array(e.value,(()=>o.sint32()),t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Vector=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.Vector,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value.push($root.CNTK.proto.DictionaryValue.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Dictionary=class{constructor(){this.data={}}static decode(o,t){const e=new $root.CNTK.proto.Dictionary,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.version=o.uint64();break;case 2:o.pair(e.data,(()=>o.string()),(()=>$root.CNTK.proto.DictionaryValue.decode(o,o.uint32())));break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Dictionary.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CNTK.proto.DictionaryValue=class{constructor(){}get value(){return $root.CNTK.proto.DictionaryValue.valueSet=$root.CNTK.proto.DictionaryValue.valueSet||new Set(["bool_value","int_value","size_t_value","float_value","double_value","string_value","nd_shape_value","axis_value","vector_value","dictionary_value","nd_array_view_value"]),Object.keys(this).find((o=>$root.CNTK.proto.DictionaryValue.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.CNTK.proto.DictionaryValue,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.version=o.uint64();break;case 2:e.value_type=o.int32();break;case 3:e.bool_value=o.bool();break;case 4:e.int_value=o.int32();break;case 5:e.size_t_value=o.uint64();break;case 6:e.float_value=o.float();break;case 7:e.double_value=o.double();break;case 8:e.string_value=o.string();break;case 9:e.nd_shape_value=$root.CNTK.proto.NDShape.decode(o,o.uint32());break;case 10:e.axis_value=$root.CNTK.proto.Axis.decode(o,o.uint32());break;case 11:e.vector_value=$root.CNTK.proto.Vector.decode(o,o.uint32());break;case 12:e.dictionary_value=$root.CNTK.proto.Dictionary.decode(o,o.uint32());break;case 13:e.nd_array_view_value=$root.CNTK.proto.NDArrayView.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.DictionaryValue.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CNTK.proto.DictionaryValue.prototype.value_type=0,$root.CNTK.proto.DictionaryValue.Type={None:0,Bool:1,Int:2,SizeT:3,Float:4,Double:5,String:6,NDShape:7,Axis:8,Vector:9,Dictionary:10,NDArrayView:11}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk.js new file mode 100644 index 0000000000000000000000000000000000000000..982be67c1cb007c58c5078c0d40ad6fee7b280a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/cntk.js @@ -0,0 +1 @@ +var cntk=cntk||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf"),cntk_v1={},cntk_v2=null;cntk.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"==e||"cmf"==e||"dnn"==e||"cntk"==e){const e=t.buffer,n=[138,10,108,252,156,70,249,32,106,168,80,25];if(e&&e.length>14&&128==e[0]&&n.every(((t,n)=>t==e[n+2])))return!1;if(e&&e.length>=8&&66==e[0]&&0==e[1]&&67==e[2]&&0==e[3]&&78==e[4]&&0==e[5]&&0==e[6]&&0==e[7])return!0;const i=t.tags("pb");return 0===i.get(1)&&2===i.get(2)}}open(t,e){return e.require("./cntk-proto").then((()=>{let n=0,i=null;try{const e=t.buffer;e&&e.length>=8&&66==e[0]&&0==e[1]&&67==e[2]&&0==e[3]&&78==e[4]&&0==e[5]&&0==e[6]&&0==e[7]&&(i=new cntk_v1.ComputationNetwork(e),n=1)}catch(e){throw new cntk.Error("File format is not CNTK v1 ("+e.message+") in '"+t.identifier+"'.")}try{if(!i){(cntk_v2=protobuf.get("cntk").CNTK.proto).PoolingType={0:"Max",1:"Average"};const e=protobuf.Reader.create(t.buffer),s=cntk_v2.Dictionary.decode(e);i=cntk.ModelFactory._convertDictionary(s),n=2}}catch(e){throw new cntk.Error("File format is not cntk.Dictionary ("+e.message+") in '"+t.identifier+"'.")}return cntk.Metadata.open(e).then((t=>{try{return new cntk.Model(t,n,i)}catch(t){throw new cntk.Error(t.message)}}))}))}static _convertDictionary(t){const e={};for(const n of Object.keys(t.data).filter((t=>"version"!=t)))e[n]=cntk.ModelFactory._convertDictionaryValue(t.data[n]);return e}static _convertDictionaryValue(t){switch(t.value_type){case cntk_v2.DictionaryValue.Type.Bool:return t.bool_value;case cntk_v2.DictionaryValue.Type.Int:return t.int_value;case cntk_v2.DictionaryValue.Type.SizeT:return t.size_t_value;case cntk_v2.DictionaryValue.Type.Float:return t.float_value;case cntk_v2.DictionaryValue.Type.Double:return t.double_value;case cntk_v2.DictionaryValue.Type.String:return t.string_value;case cntk_v2.DictionaryValue.Type.Vector:return cntk.ModelFactory._convertVectorValue(t.vector_value);case cntk_v2.DictionaryValue.Type.NDShape:return t.nd_shape_value;case cntk_v2.DictionaryValue.Type.Axis:return t.axis_value;case cntk_v2.DictionaryValue.Type.Dictionary:return cntk.ModelFactory._convertDictionary(t.dictionary_value);case cntk_v2.DictionaryValue.Type.NDArrayView:return t.nd_array_view_value}throw new cntk.Error("Unknown dictionary value type '"+t.value_type.toString()+"'.")}static _convertVectorValue(t){return t.value.map((t=>cntk.ModelFactory._convertDictionaryValue(t)))}},cntk.Model=class{constructor(t,e,n){switch(e){case 1:this._format="CNTK v1"+(n.version?"."+n.version.toString():"");break;case 2:this._format="CNTK v2"}this._graphs=[],this._graphs.push(new cntk.Graph(t,e,n))}get graphs(){return this._graphs}get format(){return this._format}},cntk.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[],this._functions=[];const i={};switch(e){case 1:for(const t of Object.keys(n.nodes)){const s=n.nodes[t];switch(s.__type__){case"InputValue":this._inputs.push(new cntk.Parameter(s.name,[new cntk.Argument(e,s)]));break;case"LearnableParameter":i[s.name]=new cntk.Argument(e,s)}}for(const s of Object.keys(n.nodes)){const o=n.nodes[s];"InputValue"!=o.__type__&&"LearnableParameter"!=o.__type__&&this._nodes.push(new cntk.Node(t,e,o,i))}if(n.output)for(const t of n.output)this._outputs.push(new cntk.Parameter(t,[new cntk.Argument(e,t)]));break;case 2:{const s=new Map;for(const t of n.primitive_functions)s.set(t.uid,t);for(const t of n.inputs){const n=new cntk.Argument(e,t);if(i[t.uid]=n,0==t.kind){const e=t.name||t.uid;this._inputs.push(new cntk.Parameter(e,[n]))}}for(const o of n.primitive_functions)if(57==o.op&&o.block_function_composite){const n=[o.block_function_composite.root],a=[];for(;n.length>0;){const o=n.shift();if(s.has(o)){const r=s.get(o);a.push(new cntk.Node(t,e,r,i)),s.delete(o);for(let t=0;t=3&&(e.pop(),"Output"==e.pop()&&n.push(e.join("_")))}}}const r=[],u=[o.block_function_composite.root];this._functions.push(new cntk.Function(o.block_function_op_name,a,r,u))}for(const o of n.primitive_functions)s.has(o.uid)&&this._nodes.push(new cntk.Node(t,e,o,i));break}default:throw new cntk.Error("Unsupported graph version '"+e+"'.")}}get nodes(){return this._nodes}get functions(){return this._functions}get inputs(){return this._inputs}get outputs(){return this._outputs}},cntk.Function=class{constructor(t,e,n,i){this._name=t,this._inputs=n,this._outputs=i,this._nodes=e}get name(){return this._name}get description(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},cntk.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},cntk.Argument=class{constructor(t,e){if("string"==typeof e)this._name=e;else switch(t){case 1:switch(e.__type__){case"InputValue":this._name=e.name,this._type=new cntk.TensorType(t,e.precision,e.sampleLayout),this._initializer=null;break;case"LearnableParameter":this._name=e.name,this._type=null,this._initializer=new cntk.Tensor(t,e)}break;case 2:e.value?(this._name=e.name||e.uid,this._type=null,this._initializer=new cntk.Tensor(t,e)):(this._name=e.uid,this._type=new cntk.TensorType(t,e.data_type,e.shape),this._initializer=null)}}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get description(){return""}get initializer(){return this._initializer}},cntk.Node=class{constructor(t,e,n,i){this._metadata=t,this._attributes=[],this._inputs=[],this._outputs=[];let s=[],o=[];const a=[];switch(e){case 1:this._type=n.__type__,this._name=n.name;for(const e of Object.keys(n))"__type__"!=e&&"name"!=e&&"inputs"!=e&&"precision"!=e&&this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n[e]));s=n.inputs.map((t=>i[t]?i[t]:new cntk.Argument(e,t))),o=[new cntk.Argument(e,this._name)];break;case 2:{this._name=n.name||n.uid||null;const r=n.uid;if(57==n.op)this._type="Block",n.block_function_op_name&&(this._type=n.block_function_op_name,this._function=!0);else if(Object.prototype.hasOwnProperty.call(n,"op"))this._type=this._metadata.name(n.op),null==this.type&&(this._type=n.op?n.op.toString():"?");else if(this._type=n.type,n.user_defined_state)for(const e of Object.keys(n.user_defined_state))this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n.user_defined_state[e]));if(n.attributes)for(const e of Object.keys(n.attributes))this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n.attributes[e]));for(const t of n.inputs){const n=i[t];n?n.initializer?a.push(n):s.push(n):s.push(new cntk.Argument(e,t))}o.push(new cntk.Argument(e,r+"_Output_0")),s=s.concat(a);break}}let r=0;const u=this._metadata.type(this._function?"Function:"+this._type:this._type);if(u&&u.inputs)for(const t of u.inputs)if(rnew cntk.Parameter((r+e).toString(),[t]))));let c=0;if(u&&u.outputs)for(const t of u.outputs)if(cnew cntk.Parameter(c.toString(),[t]))))}get name(){return this._name}get type(){return this._type}get function(){return this._function||!1}get metadata(){return this._metadata.type(this._function?"Function:"+this._type:this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},cntk.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,this._type=null,cntk_v1&&this._value instanceof cntk_v1.TensorShape&&(this._value=new cntk.TensorShape(1,n),this._type="shape"),cntk_v2&&this._value instanceof cntk_v2.NDShape&&(this._value=new cntk.TensorShape(2,n),this._type="shape"),cntk_v2&&this._value instanceof cntk_v2.Axis){const t={__type__:"Axis"};for(const e of Object.keys(n).filter((t=>"name"!==t)))t[e]=n[e];this._value=t}if(t){if(t.type){this._type=t.type;const e=cntk_v1[this._type]||cntk_v2[this._type];e&&e[this._value]&&(this._value=e[this._value])}if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){let e=t.default;if("function"==typeof(n=this._value)&&(n=n()),"shape"==this._type&&(n=n.dimensions),n==e)this._visible=!1;else if(Array.isArray(n)&&Array.isArray(e)){if(e=e.slice(0,e.length),e.length>1&&null==e[e.length-1])for(e.pop();e.lengtht==e[n]))&&(this._visible=!1)}}}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},cntk.Tensor=class{constructor(t,e){switch(t){case 1:"LearnableParameter"==e.__type__&&(this._name=e.name||null,this._type=new cntk.TensorType(t,e.precision,e.sampleLayout));break;case 2:this._name=e.name||e.uid||null,this._type=new cntk.TensorType(t,e.data_type,e.shape),this._value=e.value}}get name(){return this._name}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;const e=this._value;if(!e)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float32":e.float_values&&e.float_values.value&&e.float_values.value.length>0?t.data=e.float_values.value:t.state="Tensor data is empty.";break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){let n=t.shape;0==t.shape.length&&(n=[1]);const i=[],s=n[e];if(e==n.length-1)for(let e=0;et.limit)return i.push("..."),i;i.push(t.data[t.index++]),t.count++}else for(let n=0;nt.limit)return i.push("..."),i;i.push(this._decode(t,e+1))}return 0==t.shape.length?i[0]:i}},cntk.TensorType=class{constructor(t,e,n){switch(this._dataType="?",t){case 1:switch(e){case"float":this._dataType="float32";break;case"double":this._dataType="float64";break;case"half":this._dataType="float16";break;case"":this._dataType="float32"}this._shape=new cntk.TensorShape(t,n);break;case 2:switch(long.Long.isLong(e)&&(e=e.toNumber()),e){case 1:this._dataType="float32"}this._shape=new cntk.TensorShape(t,n)}}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},cntk.TensorShape=class{constructor(t,e){switch(t){case 1:this._dimensions=e.dims;break;case 2:this._dimensions=e.shape_dim.map((t=>-1==t.low&&-1==t.high&&1==t.unsigned?-1:t&&long.Long.isLong(t)?t.toNumber():t))}}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},cntk.Metadata=class{static open(t){return cntk.Metadata._metadata?Promise.resolve(cntk.Metadata._metadata):t.request(null,"cntk-metadata.json","utf-8").then((t=>(cntk.Metadata._metadata=new cntk.Metadata(t),cntk.Metadata._metadata))).catch((()=>(cntk.Metadata._metadata=new cntk.Metadata(null),cntk.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},this._typeMap={},t){const e=JSON.parse(t);if(e)for(const t of e)if(t.name&&t.schema){const e=t.name,n=t.schema;n.name=e,this._map[e]=n,Object.prototype.hasOwnProperty.call(n,"operator")&&(this._typeMap[n.operator.toString()]=e)}}}name(t){return this._typeMap[t]||null}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},cntk_v1.ComputationNetwork=class{constructor(t){const e=new cntk_v1.Reader(t);e.assert("BCN"),e.assert("BVersion"),this.version=e.uint64(),e.assert("EVersion");const n=e.uint64();e.assert("BNodeList");const i={Minus:function(){},Plus:function(){},GreaterEqual:function(){},Equal:function(){},NotEqual:function(){},Exp:function(){},Log:function(){},Reciprocal:function(){},ElementTimes:function(){},ClassificationError:function(){},RectifiedLinear:function(){},InputValue:function(t,e){this.rows=t.uint64(),this.cols=t.uint64(),this.sampleLayout=new cntk_v1.TensorShape(t,!0),this.dynamicAxisNodeName="",e>=8&&1==t.uint32()&&(this.dynamicAxisNodeName=t.string()),this.learningRateMultiplier=0,e>=10&&(this.learningRateMultiplier=t.float32())},LearnableParameter:function(t,e){if(!(e>=3))throw new cntk.Error("LeanableParameter reader implemented.");this.learningRateMultiplier=t.float32(),this.sampleLayout=new cntk_v1.TensorShape(t),this.value=new cntk_v1.Matrix(t)},CrossEntropyWithSoftmax:function(t){this.evalMode=t.uint32(),this.evalMode>2&&(this.evalMode=0,t.skip(-4))},Times:function(t,e){this.outputRank=e>=3?t.uint64():1,this.inferInputRankToMap=e>=12?t.int32():-1},Dropout:function(t,e){e>=16&&(this.rngSeed=16==e?t.uint32():t.uint64(),this.rngOffset=t.uint64())},ConvolutionBase:function(t,e){e>=5&&(this.kernelShape=new cntk_v1.TensorShape(t),this.mapCount=new cntk_v1.TensorShape(t),this.strides=new cntk_v1.TensorShape(t),this.sharing=t.booleans(t.uint64()),this.autoPadding=t.booleans(t.uint64()),this.lowerPad=new cntk_v1.TensorShape(t),this.upperPad=new cntk_v1.TensorShape(t),this.poolKind=t.enum(),this.imageLayoutKind=t.enum(),this.maxTempMemSizeInSamples=t.uint64()),e>=9&&(this.transpose=t.boolean()),e>=20&&(this.outputShape=new cntk_v1.TensorShape(t)),e>=21&&(this.ceilOutDim=t.boolean()),e>=23&&(this.includePad=t.boolean())},Convolution:function(t,e){i.ConvolutionBase.apply(this,[t,e]),e<5?(this.kernelShape=new cntk_v1.TensorShape([t.uint64(),t.uint64(),1]),this.strides=new cntk_v1.TensorShape([t.uint64(),t.uint64(),1]),this.mapCount=new cntk_v1.TensorShape([t.uint32()]),this.imageLayoutKind=t.enum(),this.autoPadding=[t.boolean()],this.maxTempMemSizeInSamples=t.uint64(),this.poolKind="None",this.convolution2D=!0,this.sharing=[!0],this.lowerPad=new cntk_v1.TensorShape([0]),this.upperPad=new cntk_v1.TensorShape([0])):(this.convolution2D=t.boolean(),this.dilation=e>=18?new cntk_v1.TensorShape(t):new cntk_v1.TensorShape([1]))},Pooling:function(t,e){i.ConvolutionBase.apply(this,[t,e])},PoolingBase:function(t){this.imageLayoutKind=t.enum(),this.windowWidth=t.uint32(),this.windowHeight=t.uint64(),this.horizontalSubsample=t.uint64(),this.verticalSubsample=t.uint64()},MaxPooling:function(t,e){i.PoolingBase.apply(this,[t,e])},ROIPooling:function(t,e){this.roiOutputShape=new cntk_v1.TensorShape(t),this.poolKind=e<26?"Max":t.enum(),this.spatialScale=e<26?.0625:t.float64()},Reshape:function(t){this.beginDimParameter=t.uint32(),this.endDimParameter=t.uint32(),this.replacementSampleLayout=new cntk_v1.TensorShape(t)},ReduceElements:function(t,e){let n=1;e>=27&&(n=t.uint32()),this.axes=[];for(let e=0;e=24&&(this.keepDimensions=t.boolean())},BatchNormalization:function(t,e){let n=0;if(e>=6)this.spatial=t.boolean(),this.normalizationTimeConstant=t.float64(),this.blendTimeConstant=t.float64(),this.imageLayoutKind=t.enum(),e>=13?this.runCountUntied=19!=e?t.uint64():t.boolean()?0:"SIZE_MAX":n=t.uint64(),this.epsilon=t.float64(),this.useCntkEngine=t.boolean();else{const e=t.int32(),i=t.int32();if(i>e||e<65537||i>65540)throw new cntk.Error("BatchNormalization version not supported.");this.eval=t.boolean(),this.spatial=t.boolean(),e>=65540?this.normalizationTimeConstant=t.float64():t.float64(),e>=65538&&(this.imageLayoutKind=t.enum(),n=t.uint64()),e>=65539&&(this.epsilon=t.float64(),this.useCntkEngine=t.boolean())}e<13&&(this.runCountUntied=16*n,this.convertRunningVariancePending=!0)},Tanh:function(){},Sigmoid:function(){},Logistic:function(){},SquareError:function(){},ErrorPrediction:function(){},RowStack:function(t,e){this.spliceDim=e>=3?t.int32():1},Slice:function(t,e){let n=1;e>=22&&(n=t.int32()),this.index=[],this.axis=[],this.strideMultiplier=[];for(let i=0;i=3&&this.axis.push(t.int32()),e>=27&&this.strideMultiplier.push(t.int32())},PastValue:function(t,e){if(this.timeStep=t.int32(),e>3)this.sampleLayout=new cntk_v1.TensorShape(t,!1);else{const e=t.uint64();t.uint64(),this.sampleLayout=new cntk_v1.TensorShape([e],!0)}e>=2&&(this.initialStateValue=t.int32())},FutureValue:function(t,e){if(this.timeStep=t.int32(),e>3)this.sampleLayout=new cntk_v1.TensorShape(t,!1);else{const e=t.uint64();t.uint64(),this.sampleLayout=new cntk_v1.TensorShape([e],!0)}e>=2&&(this.initialStateValue=t.int32())},TransposeDimensions:function(t,e){if(e>=3){if(this.axis1=t.int32(),this.axis2=t.int32(),e>=25&&0==this.axis1&&0==this.axis2){const e=t.uint64();this.perm=[];for(let n=0;n=7?e.string():"";if("float"!=t&&"double"!=t&&"half"!=t&&""!=t)throw new cntk.Error("Invalid precision format '"+t+"'.");const n={__type__:e.string()};n.name=e.string(),n.precision=t;const o=i[n.__type__];if(!o)throw new cntk.Error("Unknown node type '"+n.__type__+"'.");o.apply(n,[e,this.version]),s.push(n),this.nodes[n.name]=n}e.assert("ENodeList"),e.assert("BRelation");for(let t=0;t1&&o.splice(0,0,o.pop()),n.inputs=o}e.assert("ERelation"),e.assert("BRootNodes"),e.match("BFeatureNodes")&&(this.feature=e.strings(e.uint64()),e.assert("EFeatureNodes")),e.match("BLabelNodes")&&(this.label=e.strings(e.uint64()),e.assert("ELabelNodes")),e.match("BCriterionNodes")&&(this.criterion=e.strings(e.uint64()),e.assert("ECriterionNodes")),0==this.criterion.length&&e.match("BCriteriaNodes")&&(this.criterion=e.strings(e.uint64()),e.assert("ECriteriaNodes")),e.match("BNodesReqMultiSeqHandling")&&(e.strings(e.uint64()),e.assert("ENodesReqMultiSeqHandling")),e.match("BEvalNodes")&&(this.eval=e.strings(e.uint64()),e.assert("EEvalNodes")),e.match("BOutputNodes")&&(this.output=e.strings(e.uint64()),e.assert("EOutputNodes")),e.match("BPairNodes")&&(this.pair=e.strings(e.uint64()),e.assert("EPairNodes")),e.assert("ERootNodes"),e.assert("ECN")}},cntk_v1.Reader=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0}match(t){const e=this._position;for(let n=0;nthis._buffer.length)throw new cntk.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}boolean(){return 0!=this.byte()}booleans(t){const e=[];for(let n=0;n65536)throw new cntk_v1.Error("Value not in 48-bit range.");return e<<32|t}float32(){const t=this._position;return this.skip(4),this._dataView.getFloat32(t,!0)}float64(){const t=this._position;return this.skip(8),this._dataView.getFloat64(t,!0)}string(){let t="",e=this.uint16();for(;0!=e;)t+=String.fromCharCode(e),e=this.uint16();return t}strings(t){const e=[];for(let n=0;n0&&(i=t.uint32()),e&&0==i){const e=t.uint32();this.dims.push(t.uint32()),this.dims.push(n),this.dims.push(e)}else{n>0&&this.dims.push(i);for(let e=1;e>>3){case 1:t.models.push($root.CoreML.Specification.Model.decode(e,e.uint32()));break;case 2:t.names.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineClassifier=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PipelineClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineClassifier.prototype.pipeline=null,$root.CoreML.Specification.PipelineRegressor=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PipelineRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineRegressor.prototype.pipeline=null,$root.CoreML.Specification.FeatureDescription=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FeatureDescription,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 2:t.shortDescription=e.string();break;case 3:t.type=$root.CoreML.Specification.FeatureType.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureDescription.prototype.name="",$root.CoreML.Specification.FeatureDescription.prototype.shortDescription="",$root.CoreML.Specification.FeatureDescription.prototype.type=null,$root.CoreML.Specification.Metadata=class{constructor(){this.userDefined={}}static decode(e,o){const t=new $root.CoreML.Specification.Metadata,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shortDescription=e.string();break;case 2:t.versionString=e.string();break;case 3:t.author=e.string();break;case 4:t.license=e.string();break;case 100:e.pair(t.userDefined,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Metadata.prototype.shortDescription="",$root.CoreML.Specification.Metadata.prototype.versionString="",$root.CoreML.Specification.Metadata.prototype.author="",$root.CoreML.Specification.Metadata.prototype.license="",$root.CoreML.Specification.ModelDescription=class{constructor(){this.input=[],this.output=[],this.trainingInput=[]}static decode(e,o){const t=new $root.CoreML.Specification.ModelDescription,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 10:t.output.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 11:t.predictedFeatureName=e.string();break;case 12:t.predictedProbabilitiesName=e.string();break;case 50:t.trainingInput.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 100:t.metadata=$root.CoreML.Specification.Metadata.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ModelDescription.prototype.predictedFeatureName="",$root.CoreML.Specification.ModelDescription.prototype.predictedProbabilitiesName="",$root.CoreML.Specification.ModelDescription.prototype.metadata=null,$root.CoreML.Specification.SerializedModel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SerializedModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.identifier=e.string();break;case 2:t.model=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SerializedModel.prototype.identifier="",$root.CoreML.Specification.SerializedModel.prototype.model=new Uint8Array([]),$root.CoreML.Specification.Model=class{constructor(){}get Type(){return $root.CoreML.Specification.Model.TypeSet=$root.CoreML.Specification.Model.TypeSet||new Set(["pipelineClassifier","pipelineRegressor","pipeline","glmRegressor","supportVectorRegressor","treeEnsembleRegressor","neuralNetworkRegressor","bayesianProbitRegressor","glmClassifier","supportVectorClassifier","treeEnsembleClassifier","neuralNetworkClassifier","kNearestNeighborsClassifier","neuralNetwork","itemSimilarityRecommender","customModel","linkedModel","oneHotEncoder","imputer","featureVectorizer","dictVectorizer","scaler","categoricalMapping","normalizer","arrayFeatureExtractor","nonMaximumSuppression","identity","textClassifier","wordTagger","visionFeaturePrint","soundAnalysisPreprocessing","gazetteer","wordEmbedding","serializedModel"]),Object.keys(this).find((e=>$root.CoreML.Specification.Model.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Model,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.specificationVersion=e.int32();break;case 2:t.description=$root.CoreML.Specification.ModelDescription.decode(e,e.uint32());break;case 10:t.isUpdatable=e.bool();break;case 200:t.pipelineClassifier=$root.CoreML.Specification.PipelineClassifier.decode(e,e.uint32());break;case 201:t.pipelineRegressor=$root.CoreML.Specification.PipelineRegressor.decode(e,e.uint32());break;case 202:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;case 300:t.glmRegressor=$root.CoreML.Specification.GLMRegressor.decode(e,e.uint32());break;case 301:t.supportVectorRegressor=$root.CoreML.Specification.SupportVectorRegressor.decode(e,e.uint32());break;case 302:t.treeEnsembleRegressor=$root.CoreML.Specification.TreeEnsembleRegressor.decode(e,e.uint32());break;case 303:t.neuralNetworkRegressor=$root.CoreML.Specification.NeuralNetworkRegressor.decode(e,e.uint32());break;case 304:t.bayesianProbitRegressor=$root.CoreML.Specification.BayesianProbitRegressor.decode(e,e.uint32());break;case 400:t.glmClassifier=$root.CoreML.Specification.GLMClassifier.decode(e,e.uint32());break;case 401:t.supportVectorClassifier=$root.CoreML.Specification.SupportVectorClassifier.decode(e,e.uint32());break;case 402:t.treeEnsembleClassifier=$root.CoreML.Specification.TreeEnsembleClassifier.decode(e,e.uint32());break;case 403:t.neuralNetworkClassifier=$root.CoreML.Specification.NeuralNetworkClassifier.decode(e,e.uint32());break;case 404:t.kNearestNeighborsClassifier=$root.CoreML.Specification.KNearestNeighborsClassifier.decode(e,e.uint32());break;case 500:t.neuralNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 501:t.itemSimilarityRecommender=$root.CoreML.Specification.ItemSimilarityRecommender.decode(e,e.uint32());break;case 555:t.customModel=$root.CoreML.Specification.CustomModel.decode(e,e.uint32());break;case 556:t.linkedModel=$root.CoreML.Specification.LinkedModel.decode(e,e.uint32());break;case 600:t.oneHotEncoder=$root.CoreML.Specification.OneHotEncoder.decode(e,e.uint32());break;case 601:t.imputer=$root.CoreML.Specification.Imputer.decode(e,e.uint32());break;case 602:t.featureVectorizer=$root.CoreML.Specification.FeatureVectorizer.decode(e,e.uint32());break;case 603:t.dictVectorizer=$root.CoreML.Specification.DictVectorizer.decode(e,e.uint32());break;case 604:t.scaler=$root.CoreML.Specification.Scaler.decode(e,e.uint32());break;case 606:t.categoricalMapping=$root.CoreML.Specification.CategoricalMapping.decode(e,e.uint32());break;case 607:t.normalizer=$root.CoreML.Specification.Normalizer.decode(e,e.uint32());break;case 609:t.arrayFeatureExtractor=$root.CoreML.Specification.ArrayFeatureExtractor.decode(e,e.uint32());break;case 610:t.nonMaximumSuppression=$root.CoreML.Specification.NonMaximumSuppression.decode(e,e.uint32());break;case 900:t.identity=$root.CoreML.Specification.Identity.decode(e,e.uint32());break;case 2e3:t.textClassifier=$root.CoreML.Specification.CoreMLModels.TextClassifier.decode(e,e.uint32());break;case 2001:t.wordTagger=$root.CoreML.Specification.CoreMLModels.WordTagger.decode(e,e.uint32());break;case 2002:t.visionFeaturePrint=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.decode(e,e.uint32());break;case 2003:t.soundAnalysisPreprocessing=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.decode(e,e.uint32());break;case 2004:t.gazetteer=$root.CoreML.Specification.CoreMLModels.Gazetteer.decode(e,e.uint32());break;case 2005:t.wordEmbedding=$root.CoreML.Specification.CoreMLModels.WordEmbedding.decode(e,e.uint32());break;case 3e3:t.serializedModel=$root.CoreML.Specification.SerializedModel.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Model.prototype.specificationVersion=0,$root.CoreML.Specification.Model.prototype.description=null,$root.CoreML.Specification.Model.prototype.isUpdatable=!1,$root.CoreML.Specification.CoreMLModels={},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint=class{constructor(){}get VisionFeaturePrintType(){return $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet||new Set(["scene","objects"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 20:t.scene=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.decode(e,e.uint32());break;case 21:t.objects=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.version=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.prototype.version=0,$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.SceneVersion={SCENE_VERSION_INVALID:0,SCENE_VERSION_1:1},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects=class{constructor(){this.output=[]}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.version=e.int32();break;case 100:t.output.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.prototype.version=0,$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.ObjectsVersion={OBJECTS_VERSION_INVALID:0,OBJECTS_VERSION_1:1},$root.CoreML.Specification.CoreMLModels.TextClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet=$root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet||new Set(["stringClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.TextClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.language="",$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.WordTagger=class{constructor(){}get Tags(){return $root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet=$root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet||new Set(["stringTags"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.WordTagger,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 20:t.tokensOutputFeatureName=e.string();break;case 21:t.tokenTagsOutputFeatureName=e.string();break;case 22:t.tokenLocationsOutputFeatureName=e.string();break;case 23:t.tokenLengthsOutputFeatureName=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringTags=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.language="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokensOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenTagsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenLocationsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenLengthsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.Gazetteer=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet=$root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet||new Set(["stringClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.Gazetteer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.language="",$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.WordEmbedding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.WordEmbedding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.language="",$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing=class{constructor(){}get SoundAnalysisPreprocessingType(){return $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet||new Set(["vggish"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 20:t.vggish=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.StringToInt64Map=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.StringToInt64Map,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.string()),(()=>e.int64()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64ToStringMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.Int64ToStringMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.int64()),(()=>e.string()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringToDoubleMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.StringToDoubleMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.string()),(()=>e.double()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64ToDoubleMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.Int64ToDoubleMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.int64()),(()=>e.double()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.StringVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Vector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.Int64Vector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.array(t.vector,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FloatVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.FloatVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.floats(t.vector,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.DoubleVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.doubles(t.vector,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Range=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Int64Range,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minValue=e.int64();break;case 2:t.maxValue=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Range.prototype.minValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.Int64Range.prototype.maxValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.Int64Set=class{constructor(){this.values=[]}static decode(e,o){const t=new $root.CoreML.Specification.Int64Set,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.values=e.array(t.values,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DoubleRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minValue=e.double();break;case 2:t.maxValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleRange.prototype.minValue=0,$root.CoreML.Specification.DoubleRange.prototype.maxValue=0,$root.CoreML.Specification.Int64FeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Int64FeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DoubleFeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DoubleFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.StringFeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StringFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SizeRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SizeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.lowerBound=e.uint64();break;case 2:t.upperBound=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SizeRange.prototype.lowerBound=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SizeRange.prototype.upperBound=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType=class{constructor(){}get SizeFlexibility(){return $root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet=$root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet||new Set(["enumeratedSizes","imageSizeRange"]),Object.keys(this).find((e=>$root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.width=e.int64();break;case 2:t.height=e.int64();break;case 21:t.enumeratedSizes=$root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes.decode(e,e.uint32());break;case 31:t.imageSizeRange=$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.decode(e,e.uint32());break;case 3:t.colorSpace=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.prototype.width=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType.prototype.height=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType.prototype.colorSpace=0,$root.CoreML.Specification.ImageFeatureType.ColorSpace={INVALID_COLOR_SPACE:0,GRAYSCALE:10,RGB:20,BGR:30},$root.CoreML.Specification.ImageFeatureType.ImageSize=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.ImageSize,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.width=e.uint64();break;case 2:t.height=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSize.prototype.width=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ImageFeatureType.ImageSize.prototype.height=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes=class{constructor(){this.sizes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.sizes.push($root.CoreML.Specification.ImageFeatureType.ImageSize.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSizeRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.ImageSizeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.widthRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;case 2:t.heightRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.prototype.widthRange=null,$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.prototype.heightRange=null,$root.CoreML.Specification.ArrayFeatureType=class{constructor(){this.shape=[]}get ShapeFlexibility(){return $root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet=$root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet||new Set(["enumeratedShapes","shapeRange"]),Object.keys(this).find((e=>$root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet.has(e)&&null!=this[e]))}get defaultOptionalValue(){return $root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet=$root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet||new Set(["intDefaultValue","floatDefaultValue","doubleDefaultValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.int64()),o);break;case 2:t.dataType=e.int32();break;case 21:t.enumeratedShapes=$root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes.decode(e,e.uint32());break;case 31:t.shapeRange=$root.CoreML.Specification.ArrayFeatureType.ShapeRange.decode(e,e.uint32());break;case 41:t.intDefaultValue=e.int32();break;case 51:t.floatDefaultValue=e.float();break;case 61:t.doubleDefaultValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.prototype.dataType=0,$root.CoreML.Specification.ArrayFeatureType.ArrayDataType={INVALID_ARRAY_DATA_TYPE:0,FLOAT32:65568,DOUBLE:65600,INT32:131104},$root.CoreML.Specification.ArrayFeatureType.Shape=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.Shape,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes=class{constructor(){this.shapes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shapes.push($root.CoreML.Specification.ArrayFeatureType.Shape.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.ShapeRange=class{constructor(){this.sizeRanges=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.ShapeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.sizeRanges.push($root.CoreML.Specification.SizeRange.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DictionaryFeatureType=class{constructor(){}get KeyType(){return $root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet=$root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet||new Set(["int64KeyType","stringKeyType"]),Object.keys(this).find((e=>$root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DictionaryFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64KeyType=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 2:t.stringKeyType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceFeatureType=class{constructor(){}get Type(){return $root.CoreML.Specification.SequenceFeatureType.TypeSet=$root.CoreML.Specification.SequenceFeatureType.TypeSet||new Set(["int64Type","stringType"]),Object.keys(this).find((e=>$root.CoreML.Specification.SequenceFeatureType.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SequenceFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64Type=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 3:t.stringType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;case 101:t.sizeRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceFeatureType.prototype.sizeRange=null,$root.CoreML.Specification.FeatureType=class{constructor(){}get Type(){return $root.CoreML.Specification.FeatureType.TypeSet=$root.CoreML.Specification.FeatureType.TypeSet||new Set(["int64Type","doubleType","stringType","imageType","multiArrayType","dictionaryType","sequenceType"]),Object.keys(this).find((e=>$root.CoreML.Specification.FeatureType.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.FeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64Type=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 2:t.doubleType=$root.CoreML.Specification.DoubleFeatureType.decode(e,e.uint32());break;case 3:t.stringType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;case 4:t.imageType=$root.CoreML.Specification.ImageFeatureType.decode(e,e.uint32());break;case 5:t.multiArrayType=$root.CoreML.Specification.ArrayFeatureType.decode(e,e.uint32());break;case 6:t.dictionaryType=$root.CoreML.Specification.DictionaryFeatureType.decode(e,e.uint32());break;case 7:t.sequenceType=$root.CoreML.Specification.SequenceFeatureType.decode(e,e.uint32());break;case 1e3:t.isOptional=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureType.prototype.isOptional=!1,$root.CoreML.Specification.ArrayFeatureExtractor=class{constructor(){this.extractIndex=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureExtractor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.extractIndex=e.array(t.extractIndex,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor=class{constructor(){this.features=[]}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfFeatures=e.uint32();break;case 2:t.bias=$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.decode(e,e.uint32());break;case 3:t.features.push($root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight.decode(e,e.uint32()));break;case 10:t.regressionInputFeatureName=e.string();break;case 11:t.optimismInputFeatureName=e.string();break;case 12:t.samplingScaleInputFeatureName=e.string();break;case 13:t.samplingTruncationInputFeatureName=e.string();break;case 20:t.meanOutputFeatureName=e.string();break;case 21:t.varianceOutputFeatureName=e.string();break;case 22:t.pessimisticProbabilityOutputFeatureName=e.string();break;case 23:t.sampledProbabilityOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.prototype.numberOfFeatures=0,$root.CoreML.Specification.BayesianProbitRegressor.prototype.bias=null,$root.CoreML.Specification.BayesianProbitRegressor.prototype.regressionInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.optimismInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.samplingScaleInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.samplingTruncationInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.meanOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.varianceOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.pessimisticProbabilityOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.sampledProbabilityOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.Gaussian=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.Gaussian,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mean=e.double();break;case 2:t.precision=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.prototype.mean=0,$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.prototype.precision=0,$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureValue=e.uint32();break;case 2:t.featureWeight=$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.prototype.featureValue=0,$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.prototype.featureWeight=null,$root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight=class{constructor(){this.weights=[]}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureId=e.uint32();break;case 2:t.weights.push($root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight.prototype.featureId=0,$root.CoreML.Specification.CategoricalMapping=class{constructor(){}get MappingType(){return $root.CoreML.Specification.CategoricalMapping.MappingTypeSet=$root.CoreML.Specification.CategoricalMapping.MappingTypeSet||new Set(["stringToInt64Map","int64ToStringMap"]),Object.keys(this).find((e=>$root.CoreML.Specification.CategoricalMapping.MappingTypeSet.has(e)&&null!=this[e]))}get ValueOnUnknown(){return $root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet=$root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet||new Set(["strValue","int64Value"]),Object.keys(this).find((e=>$root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalMapping,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringToInt64Map=$root.CoreML.Specification.StringToInt64Map.decode(e,e.uint32());break;case 2:t.int64ToStringMap=$root.CoreML.Specification.Int64ToStringMap.decode(e,e.uint32());break;case 101:t.strValue=e.string();break;case 102:t.int64Value=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomModel=class{constructor(){this.parameters={}}static decode(e,o){const t=new $root.CoreML.Specification.CustomModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.className=e.string();break;case 30:e.pair(t.parameters,(()=>e.string()),(()=>$root.CoreML.Specification.CustomModel.CustomModelParamValue.decode(e,e.uint32())));break;case 40:t.description=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomModel.prototype.className="",$root.CoreML.Specification.CustomModel.prototype.description="",$root.CoreML.Specification.CustomModel.CustomModelParamValue=class{constructor(){}get value(){return $root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet=$root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet||new Set(["doubleValue","stringValue","intValue","longValue","boolValue","bytesValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CustomModel.CustomModelParamValue,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.doubleValue=e.double();break;case 20:t.stringValue=e.string();break;case 30:t.intValue=e.int32();break;case 40:t.longValue=e.int64();break;case 50:t.boolValue=e.bool();break;case 60:t.bytesValue=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DictVectorizer=class{constructor(){}get Map(){return $root.CoreML.Specification.DictVectorizer.MapSet=$root.CoreML.Specification.DictVectorizer.MapSet||new Set(["stringToIndex","int64ToIndex"]),Object.keys(this).find((e=>$root.CoreML.Specification.DictVectorizer.MapSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DictVectorizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringToIndex=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 2:t.int64ToIndex=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer=class{constructor(){this.inputList=[]}static decode(e,o){const t=new $root.CoreML.Specification.FeatureVectorizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputList.push($root.CoreML.Specification.FeatureVectorizer.InputColumn.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer.InputColumn=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FeatureVectorizer.InputColumn,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputColumn=e.string();break;case 2:t.inputDimensions=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer.InputColumn.prototype.inputColumn="",$root.CoreML.Specification.FeatureVectorizer.InputColumn.prototype.inputDimensions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GLMRegressor=class{constructor(){this.weights=[],this.offset=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.weights.push($root.CoreML.Specification.GLMRegressor.DoubleArray.decode(e,e.uint32()));break;case 2:t.offset=e.doubles(t.offset,o);break;case 3:t.postEvaluationTransform=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMRegressor.prototype.postEvaluationTransform=0,$root.CoreML.Specification.GLMRegressor.DoubleArray=class{constructor(){this.value=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMRegressor.DoubleArray,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.doubles(t.value,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMRegressor.PostEvaluationTransform={NoTransform:0,Logit:1,Probit:2},$root.CoreML.Specification.GLMClassifier=class{constructor(){this.weights=[],this.offset=[]}get ClassLabels(){return $root.CoreML.Specification.GLMClassifier.ClassLabelsSet=$root.CoreML.Specification.GLMClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.GLMClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.GLMClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.weights.push($root.CoreML.Specification.GLMClassifier.DoubleArray.decode(e,e.uint32()));break;case 2:t.offset=e.doubles(t.offset,o);break;case 3:t.postEvaluationTransform=e.int32();break;case 4:t.classEncoding=e.int32();break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMClassifier.prototype.postEvaluationTransform=0,$root.CoreML.Specification.GLMClassifier.prototype.classEncoding=0,$root.CoreML.Specification.GLMClassifier.DoubleArray=class{constructor(){this.value=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMClassifier.DoubleArray,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.doubles(t.value,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMClassifier.PostEvaluationTransform={Logit:0,Probit:1},$root.CoreML.Specification.GLMClassifier.ClassEncoding={ReferenceClass:0,OneVsRest:1},$root.CoreML.Specification.KNearestNeighborsClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet=$root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}get DefaultClassLabel(){return $root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet=$root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet||new Set(["defaultStringLabel","defaultInt64Label"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet.has(e)&&null!=this[e]))}get WeightingScheme(){return $root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet=$root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet||new Set(["uniformWeighting","inverseDistanceWeighting"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.KNearestNeighborsClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nearestNeighborsIndex=$root.CoreML.Specification.NearestNeighborsIndex.decode(e,e.uint32());break;case 3:t.numberOfNeighbors=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 110:t.defaultStringLabel=e.string();break;case 111:t.defaultInt64Label=e.int64();break;case 200:t.uniformWeighting=$root.CoreML.Specification.UniformWeighting.decode(e,e.uint32());break;case 210:t.inverseDistanceWeighting=$root.CoreML.Specification.InverseDistanceWeighting.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.KNearestNeighborsClassifier.prototype.nearestNeighborsIndex=null,$root.CoreML.Specification.KNearestNeighborsClassifier.prototype.numberOfNeighbors=null,$root.CoreML.Specification.NearestNeighborsIndex=class{constructor(){this.floatSamples=[]}get IndexType(){return $root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet=$root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet||new Set(["linearIndex","singleKdTreeIndex"]),Object.keys(this).find((e=>$root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet.has(e)&&null!=this[e]))}get DistanceFunction(){return $root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet=$root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet||new Set(["squaredEuclideanDistance"]),Object.keys(this).find((e=>$root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NearestNeighborsIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfDimensions=e.int32();break;case 2:t.floatSamples.push($root.CoreML.Specification.FloatVector.decode(e,e.uint32()));break;case 100:t.linearIndex=$root.CoreML.Specification.LinearIndex.decode(e,e.uint32());break;case 110:t.singleKdTreeIndex=$root.CoreML.Specification.SingleKdTreeIndex.decode(e,e.uint32());break;case 200:t.squaredEuclideanDistance=$root.CoreML.Specification.SquaredEuclideanDistance.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NearestNeighborsIndex.prototype.numberOfDimensions=0,$root.CoreML.Specification.UniformWeighting=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UniformWeighting,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.InverseDistanceWeighting=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.InverseDistanceWeighting,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LinearIndex=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinearIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SingleKdTreeIndex=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SingleKdTreeIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.leafSize=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SingleKdTreeIndex.prototype.leafSize=0,$root.CoreML.Specification.SquaredEuclideanDistance=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SquaredEuclideanDistance,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Int64Parameter=class{constructor(){}get AllowedValues(){return $root.CoreML.Specification.Int64Parameter.AllowedValuesSet=$root.CoreML.Specification.Int64Parameter.AllowedValuesSet||new Set(["range","set"]),Object.keys(this).find((e=>$root.CoreML.Specification.Int64Parameter.AllowedValuesSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Int64Parameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.int64();break;case 10:t.range=$root.CoreML.Specification.Int64Range.decode(e,e.uint32());break;case 11:t.set=$root.CoreML.Specification.Int64Set.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Parameter.prototype.defaultValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.DoubleParameter=class{constructor(){}get AllowedValues(){return $root.CoreML.Specification.DoubleParameter.AllowedValuesSet=$root.CoreML.Specification.DoubleParameter.AllowedValuesSet||new Set(["range"]),Object.keys(this).find((e=>$root.CoreML.Specification.DoubleParameter.AllowedValuesSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DoubleParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.double();break;case 10:t.range=$root.CoreML.Specification.DoubleRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleParameter.prototype.defaultValue=0,$root.CoreML.Specification.StringParameter=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StringParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringParameter.prototype.defaultValue="",$root.CoreML.Specification.BoolParameter=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BoolParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BoolParameter.prototype.defaultValue=!1,$root.CoreML.Specification.Identity=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Identity,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Imputer=class{constructor(){}get ImputedValue(){return $root.CoreML.Specification.Imputer.ImputedValueSet=$root.CoreML.Specification.Imputer.ImputedValueSet||new Set(["imputedDoubleValue","imputedInt64Value","imputedStringValue","imputedDoubleArray","imputedInt64Array","imputedStringDictionary","imputedInt64Dictionary"]),Object.keys(this).find((e=>$root.CoreML.Specification.Imputer.ImputedValueSet.has(e)&&null!=this[e]))}get ReplaceValue(){return $root.CoreML.Specification.Imputer.ReplaceValueSet=$root.CoreML.Specification.Imputer.ReplaceValueSet||new Set(["replaceDoubleValue","replaceInt64Value","replaceStringValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.Imputer.ReplaceValueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Imputer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.imputedDoubleValue=e.double();break;case 2:t.imputedInt64Value=e.int64();break;case 3:t.imputedStringValue=e.string();break;case 4:t.imputedDoubleArray=$root.CoreML.Specification.DoubleVector.decode(e,e.uint32());break;case 5:t.imputedInt64Array=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 6:t.imputedStringDictionary=$root.CoreML.Specification.StringToDoubleMap.decode(e,e.uint32());break;case 7:t.imputedInt64Dictionary=$root.CoreML.Specification.Int64ToDoubleMap.decode(e,e.uint32());break;case 11:t.replaceDoubleValue=e.double();break;case 12:t.replaceInt64Value=e.int64();break;case 13:t.replaceStringValue=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkMultiArrayShapeMapping={RANK5_ARRAY_MAPPING:0,EXACT_ARRAY_MAPPING:1},$root.CoreML.Specification.NeuralNetworkImageShapeMapping={RANK5_IMAGE_MAPPING:0,RANK4_IMAGE_MAPPING:1},$root.CoreML.Specification.NeuralNetwork=class{constructor(){this.layers=[],this.preprocessing=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetwork,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetwork.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetwork.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetwork.prototype.updateParams=null,$root.CoreML.Specification.NeuralNetworkImageScaler=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkImageScaler,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.channelScale=e.float();break;case 20:t.blueBias=e.float();break;case 21:t.greenBias=e.float();break;case 22:t.redBias=e.float();break;case 30:t.grayBias=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.channelScale=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.blueBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.greenBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.redBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.grayBias=0,$root.CoreML.Specification.NeuralNetworkMeanImage=class{constructor(){this.meanImage=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkMeanImage,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.meanImage=e.floats(t.meanImage,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkPreprocessing=class{constructor(){}get preprocessor(){return $root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet=$root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet||new Set(["scaler","meanImage"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkPreprocessing,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureName=e.string();break;case 10:t.scaler=$root.CoreML.Specification.NeuralNetworkImageScaler.decode(e,e.uint32());break;case 11:t.meanImage=$root.CoreML.Specification.NeuralNetworkMeanImage.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkPreprocessing.prototype.featureName="",$root.CoreML.Specification.ActivationReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationLeakyReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationLeakyReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationLeakyReLU.prototype.alpha=0,$root.CoreML.Specification.ActivationTanh=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationTanh,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationScaledTanh=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationScaledTanh,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationScaledTanh.prototype.alpha=0,$root.CoreML.Specification.ActivationScaledTanh.prototype.beta=0,$root.CoreML.Specification.ActivationSigmoid=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSigmoid,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationLinear=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationLinear,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationLinear.prototype.alpha=0,$root.CoreML.Specification.ActivationLinear.prototype.beta=0,$root.CoreML.Specification.ActivationSigmoidHard=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSigmoidHard,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationSigmoidHard.prototype.alpha=0,$root.CoreML.Specification.ActivationSigmoidHard.prototype.beta=0,$root.CoreML.Specification.ActivationPReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationPReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationPReLU.prototype.alpha=null,$root.CoreML.Specification.ActivationELU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationELU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationELU.prototype.alpha=0,$root.CoreML.Specification.ActivationThresholdedReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationThresholdedReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationThresholdedReLU.prototype.alpha=0,$root.CoreML.Specification.ActivationSoftsign=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSoftsign,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationSoftplus=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSoftplus,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationParametricSoftplus=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationParametricSoftplus,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 2:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationParametricSoftplus.prototype.alpha=null,$root.CoreML.Specification.ActivationParametricSoftplus.prototype.beta=null,$root.CoreML.Specification.ActivationParams=class{constructor(){}get NonlinearityType(){return $root.CoreML.Specification.ActivationParams.NonlinearityTypeSet=$root.CoreML.Specification.ActivationParams.NonlinearityTypeSet||new Set(["linear","ReLU","leakyReLU","thresholdedReLU","PReLU","tanh","scaledTanh","sigmoid","sigmoidHard","ELU","softsign","softplus","parametricSoftplus"]),Object.keys(this).find((e=>$root.CoreML.Specification.ActivationParams.NonlinearityTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ActivationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 5:t.linear=$root.CoreML.Specification.ActivationLinear.decode(e,e.uint32());break;case 10:t.ReLU=$root.CoreML.Specification.ActivationReLU.decode(e,e.uint32());break;case 15:t.leakyReLU=$root.CoreML.Specification.ActivationLeakyReLU.decode(e,e.uint32());break;case 20:t.thresholdedReLU=$root.CoreML.Specification.ActivationThresholdedReLU.decode(e,e.uint32());break;case 25:t.PReLU=$root.CoreML.Specification.ActivationPReLU.decode(e,e.uint32());break;case 30:t.tanh=$root.CoreML.Specification.ActivationTanh.decode(e,e.uint32());break;case 31:t.scaledTanh=$root.CoreML.Specification.ActivationScaledTanh.decode(e,e.uint32());break;case 40:t.sigmoid=$root.CoreML.Specification.ActivationSigmoid.decode(e,e.uint32());break;case 41:t.sigmoidHard=$root.CoreML.Specification.ActivationSigmoidHard.decode(e,e.uint32());break;case 50:t.ELU=$root.CoreML.Specification.ActivationELU.decode(e,e.uint32());break;case 60:t.softsign=$root.CoreML.Specification.ActivationSoftsign.decode(e,e.uint32());break;case 70:t.softplus=$root.CoreML.Specification.ActivationSoftplus.decode(e,e.uint32());break;case 71:t.parametricSoftplus=$root.CoreML.Specification.ActivationParametricSoftplus.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Tensor=class{constructor(){this.dimValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.Tensor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.rank=e.uint32();break;case 2:t.dimValue=e.array(t.dimValue,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Tensor.prototype.rank=0,$root.CoreML.Specification.NeuralNetworkLayer=class{constructor(){this.input=[],this.output=[],this.inputTensor=[],this.outputTensor=[]}get layer(){return $root.CoreML.Specification.NeuralNetworkLayer.layerSet=$root.CoreML.Specification.NeuralNetworkLayer.layerSet||new Set(["convolution","pooling","activation","innerProduct","embedding","batchnorm","mvn","l2normalize","softmax","lrn","crop","padding","upsample","resizeBilinear","cropResize","unary","add","multiply","average","scale","bias","max","min","dot","reduce","loadConstant","reshape","flatten","permute","concat","split","sequenceRepeat","reorganizeData","slice","simpleRecurrent","gru","uniDirectionalLSTM","biDirectionalLSTM","custom","copy","branch","loop","loopBreak","loopContinue","rangeStatic","rangeDynamic","clip","ceil","floor","sign","round","exp2","sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","asinh","acosh","atanh","erf","gelu","equal","notEqual","lessThan","lessEqual","greaterThan","greaterEqual","logicalOr","logicalXor","logicalNot","logicalAnd","modBroadcastable","minBroadcastable","maxBroadcastable","addBroadcastable","powBroadcastable","divideBroadcastable","floorDivBroadcastable","multiplyBroadcastable","subtractBroadcastable","tile","stack","gather","scatter","gatherND","scatterND","softmaxND","gatherAlongAxis","scatterAlongAxis","reverse","reverseSeq","splitND","concatND","transpose","sliceStatic","sliceDynamic","slidingWindows","topK","argMin","argMax","embeddingND","batchedMatmul","getShape","loadConstantND","fillLike","fillStatic","fillDynamic","broadcastToLike","broadcastToStatic","broadcastToDynamic","squeeze","expandDims","flattenTo2D","reshapeLike","reshapeStatic","reshapeDynamic","rankPreservingReshape","constantPad","randomNormalLike","randomNormalStatic","randomNormalDynamic","randomUniformLike","randomUniformStatic","randomUniformDynamic","randomBernoulliLike","randomBernoulliStatic","randomBernoulliDynamic","categoricalDistribution","reduceL1","reduceL2","reduceMax","reduceMin","reduceSum","reduceProd","reduceMean","reduceLogSum","reduceSumSquare","reduceLogSumExp","whereNonZero","matrixBandPart","lowerTriangular","upperTriangular","whereBroadcastable","layerNormalization","NonMaximumSuppression","oneHot","cumSum","clampedReLU","argSort","pooling3d","globalPooling3d","sliceBySize","convolution3d"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkLayer.layerSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 2:t.input.push(e.string());break;case 3:t.output.push(e.string());break;case 4:t.inputTensor.push($root.CoreML.Specification.Tensor.decode(e,e.uint32()));break;case 5:t.outputTensor.push($root.CoreML.Specification.Tensor.decode(e,e.uint32()));break;case 10:t.isUpdatable=e.bool();break;case 100:t.convolution=$root.CoreML.Specification.ConvolutionLayerParams.decode(e,e.uint32());break;case 120:t.pooling=$root.CoreML.Specification.PoolingLayerParams.decode(e,e.uint32());break;case 130:t.activation=$root.CoreML.Specification.ActivationParams.decode(e,e.uint32());break;case 140:t.innerProduct=$root.CoreML.Specification.InnerProductLayerParams.decode(e,e.uint32());break;case 150:t.embedding=$root.CoreML.Specification.EmbeddingLayerParams.decode(e,e.uint32());break;case 160:t.batchnorm=$root.CoreML.Specification.BatchnormLayerParams.decode(e,e.uint32());break;case 165:t.mvn=$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.decode(e,e.uint32());break;case 170:t.l2normalize=$root.CoreML.Specification.L2NormalizeLayerParams.decode(e,e.uint32());break;case 175:t.softmax=$root.CoreML.Specification.SoftmaxLayerParams.decode(e,e.uint32());break;case 180:t.lrn=$root.CoreML.Specification.LRNLayerParams.decode(e,e.uint32());break;case 190:t.crop=$root.CoreML.Specification.CropLayerParams.decode(e,e.uint32());break;case 200:t.padding=$root.CoreML.Specification.PaddingLayerParams.decode(e,e.uint32());break;case 210:t.upsample=$root.CoreML.Specification.UpsampleLayerParams.decode(e,e.uint32());break;case 211:t.resizeBilinear=$root.CoreML.Specification.ResizeBilinearLayerParams.decode(e,e.uint32());break;case 212:t.cropResize=$root.CoreML.Specification.CropResizeLayerParams.decode(e,e.uint32());break;case 220:t.unary=$root.CoreML.Specification.UnaryFunctionLayerParams.decode(e,e.uint32());break;case 230:t.add=$root.CoreML.Specification.AddLayerParams.decode(e,e.uint32());break;case 231:t.multiply=$root.CoreML.Specification.MultiplyLayerParams.decode(e,e.uint32());break;case 240:t.average=$root.CoreML.Specification.AverageLayerParams.decode(e,e.uint32());break;case 245:t.scale=$root.CoreML.Specification.ScaleLayerParams.decode(e,e.uint32());break;case 250:t.bias=$root.CoreML.Specification.BiasLayerParams.decode(e,e.uint32());break;case 260:t.max=$root.CoreML.Specification.MaxLayerParams.decode(e,e.uint32());break;case 261:t.min=$root.CoreML.Specification.MinLayerParams.decode(e,e.uint32());break;case 270:t.dot=$root.CoreML.Specification.DotProductLayerParams.decode(e,e.uint32());break;case 280:t.reduce=$root.CoreML.Specification.ReduceLayerParams.decode(e,e.uint32());break;case 290:t.loadConstant=$root.CoreML.Specification.LoadConstantLayerParams.decode(e,e.uint32());break;case 300:t.reshape=$root.CoreML.Specification.ReshapeLayerParams.decode(e,e.uint32());break;case 301:t.flatten=$root.CoreML.Specification.FlattenLayerParams.decode(e,e.uint32());break;case 310:t.permute=$root.CoreML.Specification.PermuteLayerParams.decode(e,e.uint32());break;case 320:t.concat=$root.CoreML.Specification.ConcatLayerParams.decode(e,e.uint32());break;case 330:t.split=$root.CoreML.Specification.SplitLayerParams.decode(e,e.uint32());break;case 340:t.sequenceRepeat=$root.CoreML.Specification.SequenceRepeatLayerParams.decode(e,e.uint32());break;case 345:t.reorganizeData=$root.CoreML.Specification.ReorganizeDataLayerParams.decode(e,e.uint32());break;case 350:t.slice=$root.CoreML.Specification.SliceLayerParams.decode(e,e.uint32());break;case 400:t.simpleRecurrent=$root.CoreML.Specification.SimpleRecurrentLayerParams.decode(e,e.uint32());break;case 410:t.gru=$root.CoreML.Specification.GRULayerParams.decode(e,e.uint32());break;case 420:t.uniDirectionalLSTM=$root.CoreML.Specification.UniDirectionalLSTMLayerParams.decode(e,e.uint32());break;case 430:t.biDirectionalLSTM=$root.CoreML.Specification.BiDirectionalLSTMLayerParams.decode(e,e.uint32());break;case 500:t.custom=$root.CoreML.Specification.CustomLayerParams.decode(e,e.uint32());break;case 600:t.copy=$root.CoreML.Specification.CopyLayerParams.decode(e,e.uint32());break;case 605:t.branch=$root.CoreML.Specification.BranchLayerParams.decode(e,e.uint32());break;case 615:t.loop=$root.CoreML.Specification.LoopLayerParams.decode(e,e.uint32());break;case 620:t.loopBreak=$root.CoreML.Specification.LoopBreakLayerParams.decode(e,e.uint32());break;case 625:t.loopContinue=$root.CoreML.Specification.LoopContinueLayerParams.decode(e,e.uint32());break;case 635:t.rangeStatic=$root.CoreML.Specification.RangeStaticLayerParams.decode(e,e.uint32());break;case 640:t.rangeDynamic=$root.CoreML.Specification.RangeDynamicLayerParams.decode(e,e.uint32());break;case 660:t.clip=$root.CoreML.Specification.ClipLayerParams.decode(e,e.uint32());break;case 665:t.ceil=$root.CoreML.Specification.CeilLayerParams.decode(e,e.uint32());break;case 670:t.floor=$root.CoreML.Specification.FloorLayerParams.decode(e,e.uint32());break;case 680:t.sign=$root.CoreML.Specification.SignLayerParams.decode(e,e.uint32());break;case 685:t.round=$root.CoreML.Specification.RoundLayerParams.decode(e,e.uint32());break;case 700:t.exp2=$root.CoreML.Specification.Exp2LayerParams.decode(e,e.uint32());break;case 710:t.sin=$root.CoreML.Specification.SinLayerParams.decode(e,e.uint32());break;case 715:t.cos=$root.CoreML.Specification.CosLayerParams.decode(e,e.uint32());break;case 720:t.tan=$root.CoreML.Specification.TanLayerParams.decode(e,e.uint32());break;case 730:t.asin=$root.CoreML.Specification.AsinLayerParams.decode(e,e.uint32());break;case 735:t.acos=$root.CoreML.Specification.AcosLayerParams.decode(e,e.uint32());break;case 740:t.atan=$root.CoreML.Specification.AtanLayerParams.decode(e,e.uint32());break;case 750:t.sinh=$root.CoreML.Specification.SinhLayerParams.decode(e,e.uint32());break;case 755:t.cosh=$root.CoreML.Specification.CoshLayerParams.decode(e,e.uint32());break;case 760:t.tanh=$root.CoreML.Specification.TanhLayerParams.decode(e,e.uint32());break;case 770:t.asinh=$root.CoreML.Specification.AsinhLayerParams.decode(e,e.uint32());break;case 775:t.acosh=$root.CoreML.Specification.AcoshLayerParams.decode(e,e.uint32());break;case 780:t.atanh=$root.CoreML.Specification.AtanhLayerParams.decode(e,e.uint32());break;case 790:t.erf=$root.CoreML.Specification.ErfLayerParams.decode(e,e.uint32());break;case 795:t.gelu=$root.CoreML.Specification.GeluLayerParams.decode(e,e.uint32());break;case 815:t.equal=$root.CoreML.Specification.EqualLayerParams.decode(e,e.uint32());break;case 820:t.notEqual=$root.CoreML.Specification.NotEqualLayerParams.decode(e,e.uint32());break;case 825:t.lessThan=$root.CoreML.Specification.LessThanLayerParams.decode(e,e.uint32());break;case 827:t.lessEqual=$root.CoreML.Specification.LessEqualLayerParams.decode(e,e.uint32());break;case 830:t.greaterThan=$root.CoreML.Specification.GreaterThanLayerParams.decode(e,e.uint32());break;case 832:t.greaterEqual=$root.CoreML.Specification.GreaterEqualLayerParams.decode(e,e.uint32());break;case 840:t.logicalOr=$root.CoreML.Specification.LogicalOrLayerParams.decode(e,e.uint32());break;case 845:t.logicalXor=$root.CoreML.Specification.LogicalXorLayerParams.decode(e,e.uint32());break;case 850:t.logicalNot=$root.CoreML.Specification.LogicalNotLayerParams.decode(e,e.uint32());break;case 855:t.logicalAnd=$root.CoreML.Specification.LogicalAndLayerParams.decode(e,e.uint32());break;case 865:t.modBroadcastable=$root.CoreML.Specification.ModBroadcastableLayerParams.decode(e,e.uint32());break;case 870:t.minBroadcastable=$root.CoreML.Specification.MinBroadcastableLayerParams.decode(e,e.uint32());break;case 875:t.maxBroadcastable=$root.CoreML.Specification.MaxBroadcastableLayerParams.decode(e,e.uint32());break;case 880:t.addBroadcastable=$root.CoreML.Specification.AddBroadcastableLayerParams.decode(e,e.uint32());break;case 885:t.powBroadcastable=$root.CoreML.Specification.PowBroadcastableLayerParams.decode(e,e.uint32());break;case 890:t.divideBroadcastable=$root.CoreML.Specification.DivideBroadcastableLayerParams.decode(e,e.uint32());break;case 895:t.floorDivBroadcastable=$root.CoreML.Specification.FloorDivBroadcastableLayerParams.decode(e,e.uint32());break;case 900:t.multiplyBroadcastable=$root.CoreML.Specification.MultiplyBroadcastableLayerParams.decode(e,e.uint32());break;case 905:t.subtractBroadcastable=$root.CoreML.Specification.SubtractBroadcastableLayerParams.decode(e,e.uint32());break;case 920:t.tile=$root.CoreML.Specification.TileLayerParams.decode(e,e.uint32());break;case 925:t.stack=$root.CoreML.Specification.StackLayerParams.decode(e,e.uint32());break;case 930:t.gather=$root.CoreML.Specification.GatherLayerParams.decode(e,e.uint32());break;case 935:t.scatter=$root.CoreML.Specification.ScatterLayerParams.decode(e,e.uint32());break;case 940:t.gatherND=$root.CoreML.Specification.GatherNDLayerParams.decode(e,e.uint32());break;case 945:t.scatterND=$root.CoreML.Specification.ScatterNDLayerParams.decode(e,e.uint32());break;case 950:t.softmaxND=$root.CoreML.Specification.SoftmaxNDLayerParams.decode(e,e.uint32());break;case 952:t.gatherAlongAxis=$root.CoreML.Specification.GatherAlongAxisLayerParams.decode(e,e.uint32());break;case 954:t.scatterAlongAxis=$root.CoreML.Specification.ScatterAlongAxisLayerParams.decode(e,e.uint32());break;case 960:t.reverse=$root.CoreML.Specification.ReverseLayerParams.decode(e,e.uint32());break;case 965:t.reverseSeq=$root.CoreML.Specification.ReverseSeqLayerParams.decode(e,e.uint32());break;case 975:t.splitND=$root.CoreML.Specification.SplitNDLayerParams.decode(e,e.uint32());break;case 980:t.concatND=$root.CoreML.Specification.ConcatNDLayerParams.decode(e,e.uint32());break;case 985:t.transpose=$root.CoreML.Specification.TransposeLayerParams.decode(e,e.uint32());break;case 995:t.sliceStatic=$root.CoreML.Specification.SliceStaticLayerParams.decode(e,e.uint32());break;case 1e3:t.sliceDynamic=$root.CoreML.Specification.SliceDynamicLayerParams.decode(e,e.uint32());break;case 1005:t.slidingWindows=$root.CoreML.Specification.SlidingWindowsLayerParams.decode(e,e.uint32());break;case 1015:t.topK=$root.CoreML.Specification.TopKLayerParams.decode(e,e.uint32());break;case 1020:t.argMin=$root.CoreML.Specification.ArgMinLayerParams.decode(e,e.uint32());break;case 1025:t.argMax=$root.CoreML.Specification.ArgMaxLayerParams.decode(e,e.uint32());break;case 1040:t.embeddingND=$root.CoreML.Specification.EmbeddingNDLayerParams.decode(e,e.uint32());break;case 1045:t.batchedMatmul=$root.CoreML.Specification.BatchedMatMulLayerParams.decode(e,e.uint32());break;case 1065:t.getShape=$root.CoreML.Specification.GetShapeLayerParams.decode(e,e.uint32());break;case 1070:t.loadConstantND=$root.CoreML.Specification.LoadConstantNDLayerParams.decode(e,e.uint32());break;case 1080:t.fillLike=$root.CoreML.Specification.FillLikeLayerParams.decode(e,e.uint32());break;case 1085:t.fillStatic=$root.CoreML.Specification.FillStaticLayerParams.decode(e,e.uint32());break;case 1090:t.fillDynamic=$root.CoreML.Specification.FillDynamicLayerParams.decode(e,e.uint32());break;case 1100:t.broadcastToLike=$root.CoreML.Specification.BroadcastToLikeLayerParams.decode(e,e.uint32());break;case 1105:t.broadcastToStatic=$root.CoreML.Specification.BroadcastToStaticLayerParams.decode(e,e.uint32());break;case 1110:t.broadcastToDynamic=$root.CoreML.Specification.BroadcastToDynamicLayerParams.decode(e,e.uint32());break;case 1120:t.squeeze=$root.CoreML.Specification.SqueezeLayerParams.decode(e,e.uint32());break;case 1125:t.expandDims=$root.CoreML.Specification.ExpandDimsLayerParams.decode(e,e.uint32());break;case 1130:t.flattenTo2D=$root.CoreML.Specification.FlattenTo2DLayerParams.decode(e,e.uint32());break;case 1135:t.reshapeLike=$root.CoreML.Specification.ReshapeLikeLayerParams.decode(e,e.uint32());break;case 1140:t.reshapeStatic=$root.CoreML.Specification.ReshapeStaticLayerParams.decode(e,e.uint32());break;case 1145:t.reshapeDynamic=$root.CoreML.Specification.ReshapeDynamicLayerParams.decode(e,e.uint32());break;case 1150:t.rankPreservingReshape=$root.CoreML.Specification.RankPreservingReshapeLayerParams.decode(e,e.uint32());break;case 1155:t.constantPad=$root.CoreML.Specification.ConstantPaddingLayerParams.decode(e,e.uint32());break;case 1170:t.randomNormalLike=$root.CoreML.Specification.RandomNormalLikeLayerParams.decode(e,e.uint32());break;case 1175:t.randomNormalStatic=$root.CoreML.Specification.RandomNormalStaticLayerParams.decode(e,e.uint32());break;case 1180:t.randomNormalDynamic=$root.CoreML.Specification.RandomNormalDynamicLayerParams.decode(e,e.uint32());break;case 1190:t.randomUniformLike=$root.CoreML.Specification.RandomUniformLikeLayerParams.decode(e,e.uint32());break;case 1195:t.randomUniformStatic=$root.CoreML.Specification.RandomUniformStaticLayerParams.decode(e,e.uint32());break;case 1200:t.randomUniformDynamic=$root.CoreML.Specification.RandomUniformDynamicLayerParams.decode(e,e.uint32());break;case 1210:t.randomBernoulliLike=$root.CoreML.Specification.RandomBernoulliLikeLayerParams.decode(e,e.uint32());break;case 1215:t.randomBernoulliStatic=$root.CoreML.Specification.RandomBernoulliStaticLayerParams.decode(e,e.uint32());break;case 1220:t.randomBernoulliDynamic=$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.decode(e,e.uint32());break;case 1230:t.categoricalDistribution=$root.CoreML.Specification.CategoricalDistributionLayerParams.decode(e,e.uint32());break;case 1250:t.reduceL1=$root.CoreML.Specification.ReduceL1LayerParams.decode(e,e.uint32());break;case 1255:t.reduceL2=$root.CoreML.Specification.ReduceL2LayerParams.decode(e,e.uint32());break;case 1260:t.reduceMax=$root.CoreML.Specification.ReduceMaxLayerParams.decode(e,e.uint32());break;case 1265:t.reduceMin=$root.CoreML.Specification.ReduceMinLayerParams.decode(e,e.uint32());break;case 1270:t.reduceSum=$root.CoreML.Specification.ReduceSumLayerParams.decode(e,e.uint32());break;case 1275:t.reduceProd=$root.CoreML.Specification.ReduceProdLayerParams.decode(e,e.uint32());break;case 1280:t.reduceMean=$root.CoreML.Specification.ReduceMeanLayerParams.decode(e,e.uint32());break;case 1285:t.reduceLogSum=$root.CoreML.Specification.ReduceLogSumLayerParams.decode(e,e.uint32());break;case 1290:t.reduceSumSquare=$root.CoreML.Specification.ReduceSumSquareLayerParams.decode(e,e.uint32());break;case 1295:t.reduceLogSumExp=$root.CoreML.Specification.ReduceLogSumExpLayerParams.decode(e,e.uint32());break;case 1313:t.whereNonZero=$root.CoreML.Specification.WhereNonZeroLayerParams.decode(e,e.uint32());break;case 1315:t.matrixBandPart=$root.CoreML.Specification.MatrixBandPartLayerParams.decode(e,e.uint32());break;case 1320:t.lowerTriangular=$root.CoreML.Specification.LowerTriangularLayerParams.decode(e,e.uint32());break;case 1325:t.upperTriangular=$root.CoreML.Specification.UpperTriangularLayerParams.decode(e,e.uint32());break;case 1330:t.whereBroadcastable=$root.CoreML.Specification.WhereBroadcastableLayerParams.decode(e,e.uint32());break;case 1350:t.layerNormalization=$root.CoreML.Specification.LayerNormalizationLayerParams.decode(e,e.uint32());break;case 1400:t.NonMaximumSuppression=$root.CoreML.Specification.NonMaximumSuppressionLayerParams.decode(e,e.uint32());break;case 1450:t.oneHot=$root.CoreML.Specification.OneHotLayerParams.decode(e,e.uint32());break;case 1455:t.cumSum=$root.CoreML.Specification.CumSumLayerParams.decode(e,e.uint32());break;case 1460:t.clampedReLU=$root.CoreML.Specification.ClampedReLULayerParams.decode(e,e.uint32());break;case 1461:t.argSort=$root.CoreML.Specification.ArgSortLayerParams.decode(e,e.uint32());break;case 1465:t.pooling3d=$root.CoreML.Specification.Pooling3DLayerParams.decode(e,e.uint32());break;case 1466:t.globalPooling3d=$root.CoreML.Specification.GlobalPooling3DLayerParams.decode(e,e.uint32());break;case 1470:t.sliceBySize=$root.CoreML.Specification.SliceBySizeLayerParams.decode(e,e.uint32());break;case 1471:t.convolution3d=$root.CoreML.Specification.Convolution3DLayerParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkLayer.prototype.name="",$root.CoreML.Specification.NeuralNetworkLayer.prototype.isUpdatable=!1,$root.CoreML.Specification.BranchLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BranchLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.ifBranch=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 2:t.elseBranch=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BranchLayerParams.prototype.ifBranch=null,$root.CoreML.Specification.BranchLayerParams.prototype.elseBranch=null,$root.CoreML.Specification.LoopLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.maxLoopIterations=e.uint64();break;case 2:t.conditionVar=e.string();break;case 3:t.conditionNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 4:t.bodyNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoopLayerParams.prototype.maxLoopIterations=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LoopLayerParams.prototype.conditionVar="",$root.CoreML.Specification.LoopLayerParams.prototype.conditionNetwork=null,$root.CoreML.Specification.LoopLayerParams.prototype.bodyNetwork=null,$root.CoreML.Specification.LoopBreakLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopBreakLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LoopContinueLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopContinueLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CopyLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CopyLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GreaterThanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GreaterThanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GreaterThanLayerParams.prototype.alpha=0,$root.CoreML.Specification.GreaterEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GreaterEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GreaterEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.LessThanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LessThanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LessThanLayerParams.prototype.alpha=0,$root.CoreML.Specification.LessEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LessEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LessEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.EqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.NotEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NotEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NotEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.LogicalAndLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalAndLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalOrLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalOrLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalXorLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalXorLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalNotLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalNotLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.BorderAmounts=class{constructor(){this.borderAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.BorderAmounts,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.borderAmounts.push($root.CoreML.Specification.BorderAmounts.EdgeSizes.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BorderAmounts.EdgeSizes=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BorderAmounts.EdgeSizes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.startEdgeSize=e.uint64();break;case 2:t.endEdgeSize=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BorderAmounts.EdgeSizes.prototype.startEdgeSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BorderAmounts.EdgeSizes.prototype.endEdgeSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ValidPadding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ValidPadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.paddingAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ValidPadding.prototype.paddingAmounts=null,$root.CoreML.Specification.SamePadding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SamePadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.asymmetryMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SamePadding.prototype.asymmetryMode=0,$root.CoreML.Specification.SamePadding.SamePaddingMode={BOTTOM_RIGHT_HEAVY:0,TOP_LEFT_HEAVY:1},$root.CoreML.Specification.SamplingMode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SamplingMode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.samplingMethod=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SamplingMode.prototype.samplingMethod=0,$root.CoreML.Specification.SamplingMode.Method={STRICT_ALIGN_ENDPOINTS_MODE:0,ALIGN_ENDPOINTS_MODE:1,UPSAMPLE_MODE:2,ROI_ALIGN_MODE:3},$root.CoreML.Specification.BoxCoordinatesMode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BoxCoordinatesMode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.boxMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BoxCoordinatesMode.prototype.boxMode=0,$root.CoreML.Specification.BoxCoordinatesMode.Coordinates={CORNERS_HEIGHT_FIRST:0,CORNERS_WIDTH_FIRST:1,CENTER_SIZE_HEIGHT_FIRST:2,CENTER_SIZE_WIDTH_FIRST:3},$root.CoreML.Specification.WeightParams=class{constructor(){this.floatValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.WeightParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.floatValue=e.floats(t.floatValue,o);break;case 2:t.float16Value=e.bytes();break;case 30:t.rawValue=e.bytes();break;case 31:t.int8RawValue=e.bytes();break;case 40:t.quantization=$root.CoreML.Specification.QuantizationParams.decode(e,e.uint32());break;case 50:t.isUpdatable=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.WeightParams.prototype.float16Value=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.rawValue=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.int8RawValue=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.quantization=null,$root.CoreML.Specification.WeightParams.prototype.isUpdatable=!1,$root.CoreML.Specification.QuantizationParams=class{constructor(){}get QuantizationType(){return $root.CoreML.Specification.QuantizationParams.QuantizationTypeSet=$root.CoreML.Specification.QuantizationParams.QuantizationTypeSet||new Set(["linearQuantization","lookupTableQuantization"]),Object.keys(this).find((e=>$root.CoreML.Specification.QuantizationParams.QuantizationTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.QuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfBits=e.uint64();break;case 101:t.linearQuantization=$root.CoreML.Specification.LinearQuantizationParams.decode(e,e.uint32());break;case 102:t.lookupTableQuantization=$root.CoreML.Specification.LookUpTableQuantizationParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.QuantizationParams.prototype.numberOfBits=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LinearQuantizationParams=class{constructor(){this.scale=[],this.bias=[]}static decode(e,o){const t=new $root.CoreML.Specification.LinearQuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.scale=e.floats(t.scale,o);break;case 2:t.bias=e.floats(t.bias,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LookUpTableQuantizationParams=class{constructor(){this.floatValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.LookUpTableQuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.floatValue=e.floats(t.floatValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConvolutionLayerParams=class{constructor(){this.kernelSize=[],this.stride=[],this.dilationFactor=[],this.outputShape=[]}get ConvolutionPaddingType(){return $root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet=$root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet||new Set(["valid","same"]),Object.keys(this).find((e=>$root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ConvolutionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.outputChannels=e.uint64();break;case 2:t.kernelChannels=e.uint64();break;case 10:t.nGroups=e.uint64();break;case 20:t.kernelSize=e.array(t.kernelSize,(()=>e.uint64()),o);break;case 30:t.stride=e.array(t.stride,(()=>e.uint64()),o);break;case 40:t.dilationFactor=e.array(t.dilationFactor,(()=>e.uint64()),o);break;case 50:t.valid=$root.CoreML.Specification.ValidPadding.decode(e,e.uint32());break;case 51:t.same=$root.CoreML.Specification.SamePadding.decode(e,e.uint32());break;case 60:t.isDeconvolution=e.bool();break;case 70:t.hasBias=e.bool();break;case 90:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 91:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConvolutionLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.kernelChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.nGroups=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.isDeconvolution=!1,$root.CoreML.Specification.ConvolutionLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.ConvolutionLayerParams.prototype.weights=null,$root.CoreML.Specification.ConvolutionLayerParams.prototype.bias=null,$root.CoreML.Specification.Convolution3DLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.Convolution3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.outputChannels=e.int32();break;case 2:t.inputChannels=e.int32();break;case 10:t.nGroups=e.int32();break;case 20:t.kernelDepth=e.int32();break;case 21:t.kernelHeight=e.int32();break;case 22:t.kernelWidth=e.int32();break;case 31:t.strideDepth=e.int32();break;case 32:t.strideHeight=e.int32();break;case 33:t.strideWidth=e.int32();break;case 40:t.dilationDepth=e.int32();break;case 41:t.dilationHeight=e.int32();break;case 42:t.dilationWidth=e.int32();break;case 50:t.hasBias=e.bool();break;case 60:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 61:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 70:t.paddingType=e.int32();break;case 80:t.customPaddingFront=e.int32();break;case 81:t.customPaddingBack=e.int32();break;case 82:t.customPaddingTop=e.int32();break;case 83:t.customPaddingBottom=e.int32();break;case 84:t.customPaddingLeft=e.int32();break;case 85:t.customPaddingRight=e.int32();break;case 86:t.isDeconvolution=e.bool();break;case 87:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Convolution3DLayerParams.prototype.outputChannels=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.inputChannels=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.nGroups=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.Convolution3DLayerParams.prototype.weights=null,$root.CoreML.Specification.Convolution3DLayerParams.prototype.bias=null,$root.CoreML.Specification.Convolution3DLayerParams.prototype.paddingType=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingFront=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingBack=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingTop=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingBottom=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingLeft=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingRight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.isDeconvolution=!1,$root.CoreML.Specification.Convolution3DLayerParams.PaddingType={CUSTOM:0,VALID:1,SAME:2},$root.CoreML.Specification.InnerProductLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.InnerProductLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputChannels=e.uint64();break;case 2:t.outputChannels=e.uint64();break;case 10:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 22:t.int8DynamicQuantize=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.InnerProductLayerParams.prototype.inputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.InnerProductLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.InnerProductLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.InnerProductLayerParams.prototype.weights=null,$root.CoreML.Specification.InnerProductLayerParams.prototype.bias=null,$root.CoreML.Specification.InnerProductLayerParams.prototype.int8DynamicQuantize=!1,$root.CoreML.Specification.EmbeddingLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EmbeddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputDim=e.uint64();break;case 2:t.outputChannels=e.uint64();break;case 10:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EmbeddingLayerParams.prototype.inputDim=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.EmbeddingLayerParams.prototype.weights=null,$root.CoreML.Specification.EmbeddingLayerParams.prototype.bias=null,$root.CoreML.Specification.EmbeddingNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EmbeddingNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vocabSize=e.uint64();break;case 2:t.embeddingSize=e.uint64();break;case 3:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.vocabSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.embeddingSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.weights=null,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.bias=null,$root.CoreML.Specification.BatchnormLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BatchnormLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.channels=e.uint64();break;case 5:t.computeMeanVar=e.bool();break;case 6:t.instanceNormalization=e.bool();break;case 10:t.epsilon=e.float();break;case 15:t.gamma=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 16:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 17:t.mean=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 18:t.variance=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchnormLayerParams.prototype.channels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchnormLayerParams.prototype.computeMeanVar=!1,$root.CoreML.Specification.BatchnormLayerParams.prototype.instanceNormalization=!1,$root.CoreML.Specification.BatchnormLayerParams.prototype.epsilon=0,$root.CoreML.Specification.BatchnormLayerParams.prototype.gamma=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.beta=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.mean=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.variance=null,$root.CoreML.Specification.PoolingLayerParams=class{constructor(){this.kernelSize=[],this.stride=[]}get PoolingPaddingType(){return $root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet=$root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet||new Set(["valid","same","includeLastPixel"]),Object.keys(this).find((e=>$root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.PoolingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 10:t.kernelSize=e.array(t.kernelSize,(()=>e.uint64()),o);break;case 20:t.stride=e.array(t.stride,(()=>e.uint64()),o);break;case 30:t.valid=$root.CoreML.Specification.ValidPadding.decode(e,e.uint32());break;case 31:t.same=$root.CoreML.Specification.SamePadding.decode(e,e.uint32());break;case 32:t.includeLastPixel=$root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding.decode(e,e.uint32());break;case 50:t.avgPoolExcludePadding=e.bool();break;case 60:t.globalPooling=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PoolingLayerParams.prototype.type=0,$root.CoreML.Specification.PoolingLayerParams.prototype.avgPoolExcludePadding=!1,$root.CoreML.Specification.PoolingLayerParams.prototype.globalPooling=!1,$root.CoreML.Specification.PoolingLayerParams.PoolingType={MAX:0,AVERAGE:1,L2:2},$root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding=class{constructor(){this.paddingAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.paddingAmounts=e.array(t.paddingAmounts,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Pooling3DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Pooling3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 2:t.kernelDepth=e.int32();break;case 3:t.kernelHeight=e.int32();break;case 4:t.kernelWidth=e.int32();break;case 5:t.strideDepth=e.int32();break;case 6:t.strideHeight=e.int32();break;case 7:t.strideWidth=e.int32();break;case 15:t.paddingType=e.int32();break;case 8:t.customPaddingFront=e.int32();break;case 9:t.customPaddingBack=e.int32();break;case 10:t.customPaddingTop=e.int32();break;case 11:t.customPaddingBottom=e.int32();break;case 12:t.customPaddingLeft=e.int32();break;case 13:t.customPaddingRight=e.int32();break;case 14:t.countExcludePadding=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Pooling3DLayerParams.prototype.type=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelDepth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelHeight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelWidth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideDepth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideHeight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideWidth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.paddingType=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingFront=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingBack=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingTop=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingBottom=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingLeft=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingRight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.countExcludePadding=!1,$root.CoreML.Specification.Pooling3DLayerParams.PoolingType3D={MAX:0,AVERAGE:1},$root.CoreML.Specification.Pooling3DLayerParams.Pooling3DPaddingType={CUSTOM:0,VALID:1,SAME:2},$root.CoreML.Specification.GlobalPooling3DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GlobalPooling3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GlobalPooling3DLayerParams.prototype.type=0,$root.CoreML.Specification.GlobalPooling3DLayerParams.GlobalPoolingType3D={MAX:0,AVERAGE:1},$root.CoreML.Specification.PaddingLayerParams=class{constructor(){}get PaddingType(){return $root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet=$root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet||new Set(["constant","reflection","replication"]),Object.keys(this).find((e=>$root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.constant=$root.CoreML.Specification.PaddingLayerParams.PaddingConstant.decode(e,e.uint32());break;case 2:t.reflection=$root.CoreML.Specification.PaddingLayerParams.PaddingReflection.decode(e,e.uint32());break;case 3:t.replication=$root.CoreML.Specification.PaddingLayerParams.PaddingReplication.decode(e,e.uint32());break;case 10:t.paddingAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PaddingLayerParams.prototype.paddingAmounts=null,$root.CoreML.Specification.PaddingLayerParams.PaddingConstant=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingConstant,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PaddingLayerParams.PaddingConstant.prototype.value=0,$root.CoreML.Specification.PaddingLayerParams.PaddingReflection=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingReflection,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.PaddingLayerParams.PaddingReplication=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingReplication,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ConcatLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ConcatLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 100:t.sequenceConcat=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConcatLayerParams.prototype.sequenceConcat=!1,$root.CoreML.Specification.LRNLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LRNLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;case 3:t.localSize=e.uint64();break;case 4:t.k=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LRNLayerParams.prototype.alpha=0,$root.CoreML.Specification.LRNLayerParams.prototype.beta=0,$root.CoreML.Specification.LRNLayerParams.prototype.localSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LRNLayerParams.prototype.k=0,$root.CoreML.Specification.SoftmaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SoftmaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SplitLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SplitLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nOutputs=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SplitLayerParams.prototype.nOutputs=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.AddLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AddLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.AddLayerParams.prototype.alpha=0,$root.CoreML.Specification.MultiplyLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MultiplyLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MultiplyLayerParams.prototype.alpha=0,$root.CoreML.Specification.UnaryFunctionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UnaryFunctionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 2:t.alpha=e.float();break;case 3:t.epsilon=e.float();break;case 4:t.shift=e.float();break;case 5:t.scale=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.type=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.alpha=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.epsilon=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.shift=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.scale=0,$root.CoreML.Specification.UnaryFunctionLayerParams.Operation={SQRT:0,RSQRT:1,INVERSE:2,POWER:3,EXP:4,LOG:5,ABS:6,THRESHOLD:7},$root.CoreML.Specification.UpsampleLayerParams=class{constructor(){this.scalingFactor=[],this.fractionalScalingFactor=[]}static decode(e,o){const t=new $root.CoreML.Specification.UpsampleLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.scalingFactor=e.array(t.scalingFactor,(()=>e.uint64()),o);break;case 7:t.fractionalScalingFactor=e.floats(t.fractionalScalingFactor,o);break;case 5:t.mode=e.int32();break;case 6:t.linearUpsampleMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UpsampleLayerParams.prototype.mode=0,$root.CoreML.Specification.UpsampleLayerParams.prototype.linearUpsampleMode=0,$root.CoreML.Specification.UpsampleLayerParams.InterpolationMode={NN:0,BILINEAR:1},$root.CoreML.Specification.UpsampleLayerParams.LinearUpsampleMode={DEFAULT:0,ALIGN_CORNERS_TRUE:1,ALIGN_CORNERS_FALSE:2},$root.CoreML.Specification.ResizeBilinearLayerParams=class{constructor(){this.targetSize=[]}static decode(e,o){const t=new $root.CoreML.Specification.ResizeBilinearLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetSize=e.array(t.targetSize,(()=>e.uint64()),o);break;case 2:t.mode=$root.CoreML.Specification.SamplingMode.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ResizeBilinearLayerParams.prototype.mode=null,$root.CoreML.Specification.CropResizeLayerParams=class{constructor(){this.targetSize=[]}static decode(e,o){const t=new $root.CoreML.Specification.CropResizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetSize=e.array(t.targetSize,(()=>e.uint64()),o);break;case 2:t.normalizedCoordinates=e.bool();break;case 3:t.mode=$root.CoreML.Specification.SamplingMode.decode(e,e.uint32());break;case 4:t.boxIndicesMode=$root.CoreML.Specification.BoxCoordinatesMode.decode(e,e.uint32());break;case 5:t.spatialScale=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CropResizeLayerParams.prototype.normalizedCoordinates=!1,$root.CoreML.Specification.CropResizeLayerParams.prototype.mode=null,$root.CoreML.Specification.CropResizeLayerParams.prototype.boxIndicesMode=null,$root.CoreML.Specification.CropResizeLayerParams.prototype.spatialScale=0,$root.CoreML.Specification.BiasLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.BiasLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BiasLayerParams.prototype.bias=null,$root.CoreML.Specification.ScaleLayerParams=class{constructor(){this.shapeScale=[],this.shapeBias=[]}static decode(e,o){const t=new $root.CoreML.Specification.ScaleLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shapeScale=e.array(t.shapeScale,(()=>e.uint64()),o);break;case 2:t.scale=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 3:t.hasBias=e.bool();break;case 4:t.shapeBias=e.array(t.shapeBias,(()=>e.uint64()),o);break;case 5:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScaleLayerParams.prototype.scale=null,$root.CoreML.Specification.ScaleLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.ScaleLayerParams.prototype.bias=null,$root.CoreML.Specification.LoadConstantLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LoadConstantLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.data=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoadConstantLayerParams.prototype.data=null,$root.CoreML.Specification.L2NormalizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.L2NormalizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.epsilon=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.L2NormalizeLayerParams.prototype.epsilon=0,$root.CoreML.Specification.FlattenLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FlattenLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenLayerParams.prototype.mode=0,$root.CoreML.Specification.FlattenLayerParams.FlattenOrder={CHANNEL_FIRST:0,CHANNEL_LAST:1},$root.CoreML.Specification.ReshapeLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReshapeLayerParams.prototype.mode=0,$root.CoreML.Specification.ReshapeLayerParams.ReshapeOrder={CHANNEL_FIRST:0,CHANNEL_LAST:1},$root.CoreML.Specification.PermuteLayerParams=class{constructor(){this.axis=[]}static decode(e,o){const t=new $root.CoreML.Specification.PermuteLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.array(t.axis,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReorganizeDataLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReorganizeDataLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;case 2:t.blockSize=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReorganizeDataLayerParams.prototype.mode=0,$root.CoreML.Specification.ReorganizeDataLayerParams.prototype.blockSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ReorganizeDataLayerParams.ReorganizationType={SPACE_TO_DEPTH:0,DEPTH_TO_SPACE:1,PIXEL_SHUFFLE:2},$root.CoreML.Specification.SliceLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SliceLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.startIndex=e.int64();break;case 2:t.endIndex=e.int64();break;case 3:t.stride=e.uint64();break;case 4:t.axis=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceLayerParams.prototype.startIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceLayerParams.prototype.endIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceLayerParams.prototype.stride=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SliceLayerParams.prototype.axis=0,$root.CoreML.Specification.SliceLayerParams.SliceAxis={CHANNEL_AXIS:0,HEIGHT_AXIS:1,WIDTH_AXIS:2},$root.CoreML.Specification.ReduceLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;case 2:t.epsilon=e.float();break;case 3:t.axis=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLayerParams.prototype.mode=0,$root.CoreML.Specification.ReduceLayerParams.prototype.epsilon=0,$root.CoreML.Specification.ReduceLayerParams.prototype.axis=0,$root.CoreML.Specification.ReduceLayerParams.ReduceOperation={SUM:0,AVG:1,PROD:2,LOGSUM:3,SUMSQUARE:4,L1:5,L2:6,MAX:7,MIN:8,ARGMAX:9},$root.CoreML.Specification.ReduceLayerParams.ReduceAxis={CHW:0,HW:1,C:2,H:3,W:4},$root.CoreML.Specification.CropLayerParams=class{constructor(){this.offset=[]}static decode(e,o){const t=new $root.CoreML.Specification.CropLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.cropAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;case 5:t.offset=e.array(t.offset,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CropLayerParams.prototype.cropAmounts=null,$root.CoreML.Specification.AverageLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AverageLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DotProductLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DotProductLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.cosineSimilarity=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DotProductLayerParams.prototype.cosineSimilarity=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MeanVarianceNormalizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.acrossChannels=e.bool();break;case 2:t.normalizeVariance=e.bool();break;case 3:t.epsilon=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.acrossChannels=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.normalizeVariance=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.epsilon=0,$root.CoreML.Specification.SequenceRepeatLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SequenceRepeatLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nRepetitions=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceRepeatLayerParams.prototype.nRepetitions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SimpleRecurrentLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activation=$root.CoreML.Specification.ActivationParams.decode(e,e.uint32());break;case 15:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVector=e.bool();break;case 30:t.weightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 31:t.recursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 32:t.biasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.activation=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.hasBiasVector=!1,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.weightMatrix=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.recursionMatrix=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.biasVector=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.GRULayerParams=class{constructor(){this.activations=[]}static decode(e,o){const t=new $root.CoreML.Specification.GRULayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activations.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVectors=e.bool();break;case 30:t.updateGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 31:t.resetGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 32:t.outputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 50:t.updateGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 51:t.resetGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 52:t.outputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 70:t.updateGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 71:t.resetGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 72:t.outputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GRULayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GRULayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GRULayerParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.GRULayerParams.prototype.hasBiasVectors=!1,$root.CoreML.Specification.GRULayerParams.prototype.updateGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.updateGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.updateGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.LSTMParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LSTMParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVectors=e.bool();break;case 30:t.forgetBias=e.bool();break;case 40:t.hasPeepholeVectors=e.bool();break;case 50:t.coupledInputAndForgetGate=e.bool();break;case 60:t.cellClipThreshold=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LSTMParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.LSTMParams.prototype.hasBiasVectors=!1,$root.CoreML.Specification.LSTMParams.prototype.forgetBias=!1,$root.CoreML.Specification.LSTMParams.prototype.hasPeepholeVectors=!1,$root.CoreML.Specification.LSTMParams.prototype.coupledInputAndForgetGate=!1,$root.CoreML.Specification.LSTMParams.prototype.cellClipThreshold=0,$root.CoreML.Specification.LSTMWeightParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LSTMWeightParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 2:t.forgetGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 3:t.blockInputWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 4:t.outputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 20:t.inputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.forgetGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 22:t.blockInputRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 23:t.outputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 40:t.inputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 41:t.forgetGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 42:t.blockInputBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 43:t.outputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 60:t.inputGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 61:t.forgetGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 62:t.outputGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGatePeepholeVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGatePeepholeVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGatePeepholeVector=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams=class{constructor(){this.activations=[]}static decode(e,o){const t=new $root.CoreML.Specification.UniDirectionalLSTMLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activations.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.params=$root.CoreML.Specification.LSTMParams.decode(e,e.uint32());break;case 20:t.weightParams=$root.CoreML.Specification.LSTMWeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.params=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.weightParams=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.BiDirectionalLSTMLayerParams=class{constructor(){this.activationsForwardLSTM=[],this.activationsBackwardLSTM=[],this.weightParams=[]}static decode(e,o){const t=new $root.CoreML.Specification.BiDirectionalLSTMLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activationsForwardLSTM.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 11:t.activationsBackwardLSTM.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.params=$root.CoreML.Specification.LSTMParams.decode(e,e.uint32());break;case 20:t.weightParams.push($root.CoreML.Specification.LSTMWeightParams.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.params=null,$root.CoreML.Specification.CustomLayerParams=class{constructor(){this.weights=[],this.parameters={}}static decode(e,o){const t=new $root.CoreML.Specification.CustomLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.className=e.string();break;case 20:t.weights.push($root.CoreML.Specification.WeightParams.decode(e,e.uint32()));break;case 30:e.pair(t.parameters,(()=>e.string()),(()=>$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.decode(e,e.uint32())));break;case 40:t.description=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomLayerParams.prototype.className="",$root.CoreML.Specification.CustomLayerParams.prototype.description="",$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue=class{constructor(){}get value(){return $root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet=$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet||new Set(["doubleValue","stringValue","intValue","longValue","boolValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.doubleValue=e.double();break;case 20:t.stringValue=e.string();break;case 30:t.intValue=e.int32();break;case 40:t.longValue=e.int64();break;case 50:t.boolValue=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TransposeLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.TransposeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchedMatMulLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BatchedMatMulLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.transposeA=e.bool();break;case 2:t.transposeB=e.bool();break;case 5:t.weightMatrixFirstDimension=e.uint64();break;case 6:t.weightMatrixSecondDimension=e.uint64();break;case 7:t.hasBias=e.bool();break;case 8:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 9:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 10:t.int8DynamicQuantize=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.transposeA=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.transposeB=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weightMatrixFirstDimension=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weightMatrixSecondDimension=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weights=null,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.bias=null,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.int8DynamicQuantize=!1,$root.CoreML.Specification.ConcatNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ConcatNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConcatNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SoftmaxNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SoftmaxNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SoftmaxNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReverseLayerParams=class{constructor(){this.reverseDim=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReverseLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.reverseDim=e.array(t.reverseDim,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReverseSeqLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReverseSeqLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.batchAxis=e.int64();break;case 2:t.sequenceAxis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReverseSeqLayerParams.prototype.batchAxis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReverseSeqLayerParams.prototype.sequenceAxis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.LoadConstantNDLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LoadConstantNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.data=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoadConstantNDLayerParams.prototype.data=null,$root.CoreML.Specification.FillLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FillLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillLikeLayerParams.prototype.value=0,$root.CoreML.Specification.FillStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.FillStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;case 2:t.targetShape=e.array(t.targetShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillStaticLayerParams.prototype.value=0,$root.CoreML.Specification.FillDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FillDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillDynamicLayerParams.prototype.value=0,$root.CoreML.Specification.WhereBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.WhereBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CosLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CosLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.TanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AsinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AsinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AcosLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AcosLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AtanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AtanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SinhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SinhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CoshLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoshLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.TanhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TanhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AsinhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AsinhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AcoshLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AcoshLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AtanhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AtanhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.PowBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PowBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Exp2LayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Exp2LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.WhereNonZeroLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.WhereNonZeroLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MatrixBandPartLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MatrixBandPartLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numLower=e.int64();break;case 2:t.numUpper=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MatrixBandPartLayerParams.prototype.numLower=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.MatrixBandPartLayerParams.prototype.numUpper=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.UpperTriangularLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UpperTriangularLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.k=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UpperTriangularLayerParams.prototype.k=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.LowerTriangularLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LowerTriangularLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.k=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LowerTriangularLayerParams.prototype.k=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.BroadcastToLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.BroadcastToStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BroadcastToDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AddBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AddBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MaxBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MaxBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MinBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MinBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ModBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ModBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.FloorDivBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FloorDivBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SubtractBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SubtractBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MultiplyBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MultiplyBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DivideBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DivideBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GatherLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GatherLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterMode={SCATTER_UPDATE:0,SCATTER_ADD:1,SCATTER_SUB:2,SCATTER_MUL:3,SCATTER_DIV:4,SCATTER_MAX:5,SCATTER_MIN:6},$root.CoreML.Specification.ScatterLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterLayerParams.prototype.mode=0,$root.CoreML.Specification.GatherNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ScatterNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterNDLayerParams.prototype.mode=0,$root.CoreML.Specification.GatherAlongAxisLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherAlongAxisLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GatherAlongAxisLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterAlongAxisLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterAlongAxisLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterAlongAxisLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterAlongAxisLayerParams.prototype.mode=0,$root.CoreML.Specification.StackLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StackLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StackLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RankPreservingReshapeLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RankPreservingReshapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConstantPaddingLayerParams=class{constructor(){this.padAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.ConstantPaddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;case 2:t.padAmounts=e.array(t.padAmounts,(()=>e.uint64()),o);break;case 3:t.padToGivenOutputSizeMode=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConstantPaddingLayerParams.prototype.value=0,$root.CoreML.Specification.ConstantPaddingLayerParams.prototype.padToGivenOutputSizeMode=!1,$root.CoreML.Specification.RandomNormalLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomNormalStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;case 4:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomNormalDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomUniformLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomUniformStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;case 4:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomUniformDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomBernoulliLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliLikeLayerParams.prototype.prob=0,$root.CoreML.Specification.RandomBernoulliStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;case 3:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliStaticLayerParams.prototype.prob=0,$root.CoreML.Specification.RandomBernoulliDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.prototype.prob=0,$root.CoreML.Specification.CategoricalDistributionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalDistributionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.numSamples=e.int64();break;case 3:t.isLogits=e.bool();break;case 4:t.eps=e.float();break;case 5:t.temperature=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.numSamples=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.isLogits=!1,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.eps=0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.temperature=0,$root.CoreML.Specification.ReduceL1LayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceL1LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceL1LayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceL1LayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceL2LayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceL2LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceL2LayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceL2LayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMaxLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMaxLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMaxLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMinLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMinLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMinLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceSumLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceSumLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceSumLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceProdLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceProdLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceProdLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceProdLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMeanLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMeanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMeanLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMeanLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceLogSumLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLogSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLogSumLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceLogSumLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceSumSquareLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceSumSquareLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceSumSquareLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceSumSquareLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceLogSumExpLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLogSumExpLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLogSumExpLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceLogSumExpLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ExpandDimsLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ExpandDimsLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenTo2DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FlattenTo2DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenTo2DLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReshapeStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReshapeLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ReshapeDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SqueezeLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SqueezeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.squeezeAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SqueezeLayerParams.prototype.squeezeAll=!1,$root.CoreML.Specification.TopKLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TopKLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.K=e.uint64();break;case 3:t.useBottomK=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TopKLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.TopKLayerParams.prototype.K=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TopKLayerParams.prototype.useBottomK=!1,$root.CoreML.Specification.ArgMaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgMaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.removeDim=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgMaxLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgMaxLayerParams.prototype.removeDim=!1,$root.CoreML.Specification.ArgMinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgMinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.removeDim=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgMinLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgMinLayerParams.prototype.removeDim=!1,$root.CoreML.Specification.SplitNDLayerParams=class{constructor(){this.splitSizes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SplitNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.numSplits=e.uint64();break;case 3:t.splitSizes=e.array(t.splitSizes,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SplitNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SplitNDLayerParams.prototype.numSplits=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.CeilLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CeilLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.RoundLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RoundLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.FloorLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FloorLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SignLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SignLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ClipLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ClipLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minVal=e.float();break;case 2:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ClipLayerParams.prototype.minVal=0,$root.CoreML.Specification.ClipLayerParams.prototype.maxVal=0,$root.CoreML.Specification.SliceStaticLayerParams=class{constructor(){this.beginIds=[],this.beginMasks=[],this.endIds=[],this.endMasks=[],this.strides=[],this.squeezeMasks=[]}static decode(e,o){const t=new $root.CoreML.Specification.SliceStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.beginIds=e.array(t.beginIds,(()=>e.int64()),o);break;case 2:t.beginMasks=e.array(t.beginMasks,(()=>e.bool()),o);break;case 3:t.endIds=e.array(t.endIds,(()=>e.int64()),o);break;case 4:t.endMasks=e.array(t.endMasks,(()=>e.bool()),o);break;case 5:t.strides=e.array(t.strides,(()=>e.int64()),o);break;case 6:t.squeezeMasks=e.array(t.squeezeMasks,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceDynamicLayerParams=class{constructor(){this.beginMasks=[],this.endIds=[],this.endMasks=[],this.strides=[],this.squeezeMasks=[]}static decode(e,o){const t=new $root.CoreML.Specification.SliceDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.beginMasks=e.array(t.beginMasks,(()=>e.bool()),o);break;case 3:t.endIds=e.array(t.endIds,(()=>e.int64()),o);break;case 4:t.endMasks=e.array(t.endMasks,(()=>e.bool()),o);break;case 5:t.strides=e.array(t.strides,(()=>e.int64()),o);break;case 6:t.squeezeMasks=e.array(t.squeezeMasks,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TileLayerParams=class{constructor(){this.reps=[]}static decode(e,o){const t=new $root.CoreML.Specification.TileLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.reps=e.array(t.reps,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GetShapeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GetShapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ErfLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ErfLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GeluLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GeluLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GeluLayerParams.prototype.mode=0,$root.CoreML.Specification.GeluLayerParams.GeluMode={EXACT:0,TANH_APPROXIMATION:1,SIGMOID_APPROXIMATION:2},$root.CoreML.Specification.RangeStaticLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RangeStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.endValue=e.float();break;case 2:t.startValue=e.float();break;case 3:t.stepSizeValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RangeStaticLayerParams.prototype.endValue=0,$root.CoreML.Specification.RangeStaticLayerParams.prototype.startValue=0,$root.CoreML.Specification.RangeStaticLayerParams.prototype.stepSizeValue=0,$root.CoreML.Specification.RangeDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RangeDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.startValue=e.float();break;case 3:t.stepSizeValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RangeDynamicLayerParams.prototype.startValue=0,$root.CoreML.Specification.RangeDynamicLayerParams.prototype.stepSizeValue=0,$root.CoreML.Specification.SlidingWindowsLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SlidingWindowsLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.windowSize=e.uint64();break;case 3:t.step=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.windowSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.step=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LayerNormalizationLayerParams=class{constructor(){this.normalizedShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LayerNormalizationLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.normalizedShape=e.array(t.normalizedShape,(()=>e.int64()),o);break;case 2:t.eps=e.float();break;case 3:t.gamma=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 4:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.eps=0,$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.gamma=null,$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.beta=null,$root.CoreML.Specification.NonMaximumSuppressionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppressionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.iouThreshold=e.float();break;case 2:t.scoreThreshold=e.float();break;case 3:t.maxBoxes=e.uint64();break;case 4:t.perClassSuppression=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.iouThreshold=0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.scoreThreshold=0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.maxBoxes=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.perClassSuppression=!1,$root.CoreML.Specification.ClampedReLULayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ClampedReLULayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ClampedReLULayerParams.prototype.alpha=0,$root.CoreML.Specification.ClampedReLULayerParams.prototype.beta=0,$root.CoreML.Specification.ArgSortLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgSortLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.descending=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgSortLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgSortLayerParams.prototype.descending=!1,$root.CoreML.Specification.SliceBySizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SliceBySizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.size=e.int64();break;case 3:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceBySizeLayerParams.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceBySizeLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.NeuralNetworkClassifier=class{constructor(){this.layers=[],this.preprocessing=[]}get ClassLabels(){return $root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet=$root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 200:t.labelProbabilityLayerName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkClassifier.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.updateParams=null,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.labelProbabilityLayerName="",$root.CoreML.Specification.OneHotLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.OneHotLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.oneHotVectorSize=e.uint64();break;case 2:t.axis=e.int64();break;case 3:t.onValue=e.float();break;case 4:t.offValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.OneHotLayerParams.prototype.oneHotVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.OneHotLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.OneHotLayerParams.prototype.onValue=0,$root.CoreML.Specification.OneHotLayerParams.prototype.offValue=0,$root.CoreML.Specification.CumSumLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CumSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.excludeFinalSum=e.bool();break;case 3:t.reverse=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CumSumLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CumSumLayerParams.prototype.excludeFinalSum=!1,$root.CoreML.Specification.CumSumLayerParams.prototype.reverse=!1,$root.CoreML.Specification.NeuralNetworkRegressor=class{constructor(){this.layers=[],this.preprocessing=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkRegressor.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkRegressor.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkRegressor.prototype.updateParams=null,$root.CoreML.Specification.NetworkUpdateParameters=class{constructor(){this.lossLayers=[]}static decode(e,o){const t=new $root.CoreML.Specification.NetworkUpdateParameters,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.lossLayers.push($root.CoreML.Specification.LossLayer.decode(e,e.uint32()));break;case 2:t.optimizer=$root.CoreML.Specification.Optimizer.decode(e,e.uint32());break;case 3:t.epochs=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 10:t.shuffle=$root.CoreML.Specification.BoolParameter.decode(e,e.uint32());break;case 20:t.seed=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NetworkUpdateParameters.prototype.optimizer=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.epochs=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.shuffle=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.seed=null,$root.CoreML.Specification.LossLayer=class{constructor(){}get LossLayerType(){return $root.CoreML.Specification.LossLayer.LossLayerTypeSet=$root.CoreML.Specification.LossLayer.LossLayerTypeSet||new Set(["categoricalCrossEntropyLossLayer","meanSquaredErrorLossLayer"]),Object.keys(this).find((e=>$root.CoreML.Specification.LossLayer.LossLayerTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.LossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 10:t.categoricalCrossEntropyLossLayer=$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.decode(e,e.uint32());break;case 11:t.meanSquaredErrorLossLayer=$root.CoreML.Specification.MeanSquaredErrorLossLayer.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LossLayer.prototype.name="",$root.CoreML.Specification.CategoricalCrossEntropyLossLayer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalCrossEntropyLossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input=e.string();break;case 2:t.target=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.prototype.input="",$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.prototype.target="",$root.CoreML.Specification.MeanSquaredErrorLossLayer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MeanSquaredErrorLossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input=e.string();break;case 2:t.target=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MeanSquaredErrorLossLayer.prototype.input="",$root.CoreML.Specification.MeanSquaredErrorLossLayer.prototype.target="",$root.CoreML.Specification.Optimizer=class{constructor(){}get OptimizerType(){return $root.CoreML.Specification.Optimizer.OptimizerTypeSet=$root.CoreML.Specification.Optimizer.OptimizerTypeSet||new Set(["sgdOptimizer","adamOptimizer"]),Object.keys(this).find((e=>$root.CoreML.Specification.Optimizer.OptimizerTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Optimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.sgdOptimizer=$root.CoreML.Specification.SGDOptimizer.decode(e,e.uint32());break;case 11:t.adamOptimizer=$root.CoreML.Specification.AdamOptimizer.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SGDOptimizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SGDOptimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.learningRate=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 2:t.miniBatchSize=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 3:t.momentum=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SGDOptimizer.prototype.learningRate=null,$root.CoreML.Specification.SGDOptimizer.prototype.miniBatchSize=null,$root.CoreML.Specification.SGDOptimizer.prototype.momentum=null,$root.CoreML.Specification.AdamOptimizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AdamOptimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.learningRate=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 2:t.miniBatchSize=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 3:t.beta1=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 4:t.beta2=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 5:t.eps=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.AdamOptimizer.prototype.learningRate=null,$root.CoreML.Specification.AdamOptimizer.prototype.miniBatchSize=null,$root.CoreML.Specification.AdamOptimizer.prototype.beta1=null,$root.CoreML.Specification.AdamOptimizer.prototype.beta2=null,$root.CoreML.Specification.AdamOptimizer.prototype.eps=null,$root.CoreML.Specification.Normalizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Normalizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.normType=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Normalizer.prototype.normType=0,$root.CoreML.Specification.Normalizer.NormType={LMax:0,L1:1,L2:2},$root.CoreML.Specification.OneHotEncoder=class{constructor(){}get CategoryType(){return $root.CoreML.Specification.OneHotEncoder.CategoryTypeSet=$root.CoreML.Specification.OneHotEncoder.CategoryTypeSet||new Set(["stringCategories","int64Categories"]),Object.keys(this).find((e=>$root.CoreML.Specification.OneHotEncoder.CategoryTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.OneHotEncoder,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringCategories=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 2:t.int64Categories=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 10:t.outputSparse=e.bool();break;case 11:t.handleUnknown=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.OneHotEncoder.prototype.outputSparse=!1,$root.CoreML.Specification.OneHotEncoder.prototype.handleUnknown=0,$root.CoreML.Specification.OneHotEncoder.HandleUnknown={ErrorOnUnknown:0,IgnoreUnknown:1},$root.CoreML.Specification.Scaler=class{constructor(){this.shiftValue=[],this.scaleValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.Scaler,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shiftValue=e.doubles(t.shiftValue,o);break;case 2:t.scaleValue=e.doubles(t.scaleValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression=class{constructor(){}get SuppressionMethod(){return $root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet=$root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet||new Set(["pickTop"]),Object.keys(this).find((e=>$root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet.has(e)&&null!=this[e]))}get ClassLabels(){return $root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet=$root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppression,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pickTop=$root.CoreML.Specification.NonMaximumSuppression.PickTop.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 110:t.iouThreshold=e.double();break;case 111:t.confidenceThreshold=e.double();break;case 200:t.confidenceInputFeatureName=e.string();break;case 201:t.coordinatesInputFeatureName=e.string();break;case 202:t.iouThresholdInputFeatureName=e.string();break;case 203:t.confidenceThresholdInputFeatureName=e.string();break;case 210:t.confidenceOutputFeatureName=e.string();break;case 211:t.coordinatesOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression.prototype.iouThreshold=0,$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceThreshold=0,$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.coordinatesInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.iouThresholdInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceThresholdInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceOutputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.coordinatesOutputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.PickTop=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppression.PickTop,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.perClass=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression.PickTop.prototype.perClass=!1,$root.CoreML.Specification.LinearKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinearKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.RBFKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RBFKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.gamma=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RBFKernel.prototype.gamma=0,$root.CoreML.Specification.PolyKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PolyKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.degree=e.int32();break;case 2:t.c=e.double();break;case 3:t.gamma=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PolyKernel.prototype.degree=0,$root.CoreML.Specification.PolyKernel.prototype.c=0,$root.CoreML.Specification.PolyKernel.prototype.gamma=0,$root.CoreML.Specification.SigmoidKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SigmoidKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.gamma=e.double();break;case 2:t.c=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SigmoidKernel.prototype.gamma=0,$root.CoreML.Specification.SigmoidKernel.prototype.c=0,$root.CoreML.Specification.Kernel=class{constructor(){}get kernel(){return $root.CoreML.Specification.Kernel.kernelSet=$root.CoreML.Specification.Kernel.kernelSet||new Set(["linearKernel","rbfKernel","polyKernel","sigmoidKernel"]),Object.keys(this).find((e=>$root.CoreML.Specification.Kernel.kernelSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Kernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linearKernel=$root.CoreML.Specification.LinearKernel.decode(e,e.uint32());break;case 2:t.rbfKernel=$root.CoreML.Specification.RBFKernel.decode(e,e.uint32());break;case 3:t.polyKernel=$root.CoreML.Specification.PolyKernel.decode(e,e.uint32());break;case 4:t.sigmoidKernel=$root.CoreML.Specification.SigmoidKernel.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseNode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SparseNode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.index=e.int32();break;case 2:t.value=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseNode.prototype.index=0,$root.CoreML.Specification.SparseNode.prototype.value=0,$root.CoreML.Specification.SparseVector=class{constructor(){this.nodes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SparseVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nodes.push($root.CoreML.Specification.SparseNode.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseSupportVectors=class{constructor(){this.vectors=[]}static decode(e,o){const t=new $root.CoreML.Specification.SparseSupportVectors,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vectors.push($root.CoreML.Specification.SparseVector.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DenseVector=class{constructor(){this.values=[]}static decode(e,o){const t=new $root.CoreML.Specification.DenseVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.values=e.doubles(t.values,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DenseSupportVectors=class{constructor(){this.vectors=[]}static decode(e,o){const t=new $root.CoreML.Specification.DenseSupportVectors,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vectors.push($root.CoreML.Specification.DenseVector.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Coefficients=class{constructor(){this.alpha=[]}static decode(e,o){const t=new $root.CoreML.Specification.Coefficients,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.doubles(t.alpha,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorRegressor=class{constructor(){}get supportVectors(){return $root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet=$root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet||new Set(["sparseSupportVectors","denseSupportVectors"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SupportVectorRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.kernel=$root.CoreML.Specification.Kernel.decode(e,e.uint32());break;case 2:t.sparseSupportVectors=$root.CoreML.Specification.SparseSupportVectors.decode(e,e.uint32());break;case 3:t.denseSupportVectors=$root.CoreML.Specification.DenseSupportVectors.decode(e,e.uint32());break;case 4:t.coefficients=$root.CoreML.Specification.Coefficients.decode(e,e.uint32());break;case 5:t.rho=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorRegressor.prototype.kernel=null,$root.CoreML.Specification.SupportVectorRegressor.prototype.coefficients=null,$root.CoreML.Specification.SupportVectorRegressor.prototype.rho=0,$root.CoreML.Specification.SupportVectorClassifier=class{constructor(){this.numberOfSupportVectorsPerClass=[],this.coefficients=[],this.rho=[],this.probA=[],this.probB=[]}get supportVectors(){return $root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet=$root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet||new Set(["sparseSupportVectors","denseSupportVectors"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet.has(e)&&null!=this[e]))}get ClassLabels(){return $root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet=$root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SupportVectorClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.kernel=$root.CoreML.Specification.Kernel.decode(e,e.uint32());break;case 2:t.numberOfSupportVectorsPerClass=e.array(t.numberOfSupportVectorsPerClass,(()=>e.int32()),o);break;case 3:t.sparseSupportVectors=$root.CoreML.Specification.SparseSupportVectors.decode(e,e.uint32());break;case 4:t.denseSupportVectors=$root.CoreML.Specification.DenseSupportVectors.decode(e,e.uint32());break;case 5:t.coefficients.push($root.CoreML.Specification.Coefficients.decode(e,e.uint32()));break;case 6:t.rho=e.doubles(t.rho,o);break;case 7:t.probA=e.doubles(t.probA,o);break;case 8:t.probB=e.doubles(t.probB,o);break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorClassifier.prototype.kernel=null,$root.CoreML.Specification.TreeEnsemblePostEvaluationTransform={NoTransform:0,Classification_SoftMax:1,Regression_Logistic:2,Classification_SoftMaxWithZeroClassReference:3},$root.CoreML.Specification.TreeEnsembleParameters=class{constructor(){this.nodes=[],this.basePredictionValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nodes.push($root.CoreML.Specification.TreeEnsembleParameters.TreeNode.decode(e,e.uint32()));break;case 2:t.numPredictionDimensions=e.uint64();break;case 3:t.basePredictionValue=e.doubles(t.basePredictionValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.prototype.numPredictionDimensions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode=class{constructor(){this.evaluationInfo=[]}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters.TreeNode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeId=e.uint64();break;case 2:t.nodeId=e.uint64();break;case 3:t.nodeBehavior=e.int32();break;case 10:t.branchFeatureIndex=e.uint64();break;case 11:t.branchFeatureValue=e.double();break;case 12:t.trueChildNodeId=e.uint64();break;case 13:t.falseChildNodeId=e.uint64();break;case 14:t.missingValueTracksTrueChild=e.bool();break;case 20:t.evaluationInfo.push($root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.decode(e,e.uint32()));break;case 30:t.relativeHitRate=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.treeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0;$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.nodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.nodeBehavior=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.branchFeatureIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.branchFeatureValue=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.trueChildNodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.falseChildNodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.missingValueTracksTrueChild=!1,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.relativeHitRate=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.TreeNodeBehavior={BranchOnValueLessThanEqual:0,BranchOnValueLessThan:1,BranchOnValueGreaterThanEqual:2,BranchOnValueGreaterThan:3,BranchOnValueEqual:4,BranchOnValueNotEqual:5,LeafNode:6},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.evaluationIndex=e.uint64();break;case 2:t.evaluationValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.prototype.evaluationIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.prototype.evaluationValue=0,$root.CoreML.Specification.TreeEnsembleClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet=$root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeEnsemble=$root.CoreML.Specification.TreeEnsembleParameters.decode(e,e.uint32());break;case 2:t.postEvaluationTransform=e.int32();break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleClassifier.prototype.treeEnsemble=null,$root.CoreML.Specification.TreeEnsembleClassifier.prototype.postEvaluationTransform=0,$root.CoreML.Specification.TreeEnsembleRegressor=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeEnsemble=$root.CoreML.Specification.TreeEnsembleParameters.decode(e,e.uint32());break;case 2:t.postEvaluationTransform=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleRegressor.prototype.treeEnsemble=null,$root.CoreML.Specification.TreeEnsembleRegressor.prototype.postEvaluationTransform=0,$root.CoreML.Specification.ItemSimilarityRecommender=class{constructor(){this.itemItemSimilarities=[]}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemItemSimilarities.push($root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.decode(e,e.uint32()));break;case 2:t.itemStringIds=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 3:t.itemInt64Ids=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 10:t.itemInputFeatureName=e.string();break;case 11:t.numRecommendationsInputFeatureName=e.string();break;case 12:t.itemRestrictionInputFeatureName=e.string();break;case 13:t.itemExclusionInputFeatureName=e.string();break;case 20:t.recommendedItemListOutputFeatureName=e.string();break;case 21:t.recommendedItemScoreOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemStringIds=null,$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemInt64Ids=null,$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.numRecommendationsInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemRestrictionInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemExclusionInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.recommendedItemListOutputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.recommendedItemScoreOutputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemId=e.uint64();break;case 2:t.similarityScore=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.prototype.itemId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.prototype.similarityScore=0,$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems=class{constructor(){this.similarItemList=[]}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemId=e.uint64();break;case 2:t.similarItemList.push($root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.decode(e,e.uint32()));break;case 3:t.itemScoreAdjustment=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.prototype.itemId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.prototype.itemScoreAdjustment=0,$root.CoreML.Specification.LinkedModel=class{constructor(){}get LinkType(){return $root.CoreML.Specification.LinkedModel.LinkTypeSet=$root.CoreML.Specification.LinkedModel.LinkTypeSet||new Set(["linkedModelFile"]),Object.keys(this).find((e=>$root.CoreML.Specification.LinkedModel.LinkTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.LinkedModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linkedModelFile=$root.CoreML.Specification.LinkedModelFile.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LinkedModelFile=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinkedModelFile,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linkedModelFileName=$root.CoreML.Specification.StringParameter.decode(e,e.uint32());break;case 2:t.linkedModelSearchPath=$root.CoreML.Specification.StringParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LinkedModelFile.prototype.linkedModelFileName=null,$root.CoreML.Specification.LinkedModelFile.prototype.linkedModelSearchPath=null; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/coreml.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/coreml.js new file mode 100644 index 0000000000000000000000000000000000000000..b267622a1d12cd3b2ef1644232074d6cdee8c3b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/coreml.js @@ -0,0 +1 @@ +var coreml=coreml||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");coreml.ModelFactory=class{match(e){return"mlmodel"==e.identifier.split(".").pop().toLowerCase()}open(e,t){return t.require("./coreml-proto").then((()=>{const i=e.identifier;let r=null;try{coreml.proto=protobuf.get("coreml").CoreML.Specification;const t=protobuf.Reader.create(e.buffer);r=coreml.proto.Model.decode(t)}catch(e){throw new coreml.Error("File format is not coreml.Model ("+e.message+") in '"+i+"'.")}return coreml.Metadata.open(t).then((e=>{try{return new coreml.Model(e,r)}catch(e){t.exception(e,!1);const r=e&&e.message?e.message:e.toString();throw new coreml.Error(r.replace(/\.$/,"")+" in '"+i+"'.")}}))}))}},coreml.Model=class{constructor(e,t){if(this._specificationVersion=t.specificationVersion,this._graphs=[new coreml.Graph(e,t)],t.description&&t.description.metadata){const i=t.description.metadata;i.versionString&&(this._version=i.versionString),i.author&&(this._author=i.author),i.shortDescription&&(this._description=i.shortDescription),i.license&&(this._license=i.license),e.userDefined&&Object.keys(i.userDefined).length}}get format(){return"Core ML v"+this._specificationVersion.toString()}get version(){return this._version||null}get description(){return this._description||null}get author(){return this._author||null}get license(){return this._license||null}get graphs(){return this._graphs}},coreml.Graph=class{constructor(e,t){this._metadata=e,this._description=t.description,this._groups=!1,this._inputs=[],this._outputs=[],this._nodes=[],this._description&&(this._inputs=this._description.input.map((e=>{const t=new coreml.Argument(e.name,coreml.Graph._formatFeatureType(e.type),e.shortDescription,null);return new coreml.Parameter(e.name,!0,[t])})),this._outputs=this._description.output.map((e=>{const t=new coreml.Argument(e.name,coreml.Graph._formatFeatureType(e.type),e.shortDescription,null);return new coreml.Parameter(e.name,!0,[t])}))),this._type=this._loadModel(t,{},"")}get name(){return""}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get groups(){return this._groups}_updateOutput(e,t){for(const i of this._nodes)for(const r of i.outputs)for(const i of r.arguments)i.name===e&&(i.name=t);return t}_updateClassifierOutput(e,t){let i=t.labelProbabilityLayerName;if(!i&&this._nodes.length>0){const e=this._nodes.slice(-1).pop();e&&1==e.outputs.length&&1==e.outputs[0].arguments.length&&(i=e.outputs[0].arguments[0].name)}let r=this._description.predictedFeatureName,s=this._description.predictedProbabilitiesName;if((r||s)&&i&&t.ClassLabels){r=r||"?",s=s||"?";const e=this._updateOutput(i,i+":labelProbabilityLayerName"),a=t.ClassLabels;this._nodes.push(new coreml.Node(this._metadata,this._group,a,null,"",t[a],[e],[s,r]))}}_updatePreprocessing(e,t,i){if(i&&i.length>0){const r=this._description.input[0].name,s=[];for(const e of this._nodes)e.inputs.some((e=>e.arguments.some((e=>e.name==r))))&&s.push(e);let a=r,n=0;for(const s of i){const i=s.featureName?s.featureName:a;a=r+":"+n.toString(),this._createNode(e,t,s.preprocessor,null,"",s[s.preprocessor],[i],[a]),n++}for(const e of s)for(const t of e.inputs)for(const e of t.arguments)e.name===r&&(e.name=a)}}_loadModel(e,t,i){this._groups=this._groups|i.length>0;const r=e&&e.description&&e.description.metadata&&e.description.metadata.shortDescription?e.description.metadata.shortDescription:"";switch(e.Type){case"neuralNetworkClassifier":{const s=e.neuralNetworkClassifier;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updateClassifierOutput(i,s),this._updatePreprocessing(t,i,s.preprocessing),"Neural Network Classifier"}case"neuralNetwork":{const s=e.neuralNetwork;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updatePreprocessing(t,i,s.preprocessing),"Neural Network"}case"neuralNetworkRegressor":{const s=e.neuralNetworkRegressor;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updatePreprocessing(t,i,s),"Neural Network Regressor"}case"pipeline":for(let r=0;re.name)),e.description.output.map((e=>e.name))),"Item Similarity Recommender";case"linkedModel":return this._createNode(t,i,"linkedModel",null,r,e.linkedModel.linkedModelFile,[e.description.input[0].name],[e.description.output[0].name]),"Linked Model";case"customModel":return this._createNode(t,i,"customModel",null,r,{className:e.customModel.className,parameters:e.customModel.parameters},[e.description.input[0].name],[e.description.output[0].name]),"customModel"}throw new coreml.Error("Unknown model type '"+JSON.stringify(Object.keys(e))+"'.")}_createNode(e,t,i,r,s,a,n,o){n=n.map((t=>e[t]?e[t].argument:t)),o=o.map((t=>{if(e[t]){e[t].counter++;const i=t+"\n"+e[t].counter.toString();return e[t].argument=i,i}return e[t]={argument:t,counter:0},t}));const u=new coreml.Node(this._metadata,t,i,r,s,a,n,o);return this._nodes.push(u),u}static _formatFeatureType(e){let t="?";if(e){switch(e.Type){case"multiArrayType":{let i=new coreml.TensorShape([]);e.multiArrayType.shape&&e.multiArrayType.shape.length>0&&(i=new coreml.TensorShape(e.multiArrayType.shape));let r="?";switch(e.multiArrayType.dataType){case coreml.proto.ArrayFeatureType.ArrayDataType.FLOAT32:r="float32";break;case coreml.proto.ArrayFeatureType.ArrayDataType.INT32:r="int32";break;case coreml.proto.ArrayFeatureType.ArrayDataType.DOUBLE:r="float64"}t=new coreml.TensorType(r,i);break}case"stringType":t=new coreml.TensorType("string");break;case"doubleType":t=new coreml.TensorType("float64");break;case"int64Type":t=new coreml.TensorType("int64");break;case"dictionaryType":t=new coreml.MapType(e.dictionaryType.KeyType.replace("KeyType",""),"float64");break;case"imageType":t=new coreml.ImageType(e.imageType.colorSpace,e.imageType.width,e.imageType.height)}e.isOptional&&(t=new coreml.OptionalType(t))}return t}static _formatFeatureDescriptionList(e){return e.map((e=>e.name))}},coreml.Parameter=class{constructor(e,t,i){this._name=e,this._visible=t,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},coreml.Argument=class{constructor(e,t,i,r){if("string"!=typeof e)throw new coreml.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t,this._description=i||null,this._initializer=r||null}get name(){return this._name}set name(e){this._name=e}get type(){return this._initializer?this._initializer.type:this._type}get description(){return this._description}get quantization(){return this._initializer?this._initializer.quantization:null}get initializer(){return this._initializer}},coreml.Node=class{constructor(e,t,i,r,s,a,n,o){if(this._metadata=e,t&&(this._group=t),!i)throw new Error("Undefined node type.");this._type=i,this._name=r||"",this._description=s||"",this._attributes=[];const u=[];if(a){const t=this._initialize(a,u);for(const i of Object.keys(a))if(!t[i]){const t=e.attribute(this.type,i);this._attributes.push(new coreml.Attribute(t,i,a[i]))}}this._inputs=this._metadata.getInputs(this._type,n).map((e=>new coreml.Parameter(e.name,!0,e.arguments.map((e=>new coreml.Argument(e.name,e.type,null,null)))))),this._inputs=this._inputs.concat(u),this._outputs=o.map(((e,t)=>{const i=this._metadata.getOutputName(this._type,t);return new coreml.Parameter(i,!0,[new coreml.Argument(e,null,null,null)])}))}get type(){return this._type}get name(){return this._name}get description(){return this._description}get metadata(){return this._metadata.type(this.type)}get group(){return this._group?this._group:null}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}_initialize(e,t){switch(this._type){case"convolution":{const i=[e.outputChannels,e.kernelChannels,e.kernelSize[0],e.kernelSize[1]];return e.isDeconvolution&&(i[0]=e.kernelChannels,i[1]=Math.floor(e.outputChannels/(0!=e.nGroups?e.nGroups:1))),this._initializer(t,"Weights","weights",i,e.weights),e.hasBias&&this._initializer(t,"Weights","bias",[e.outputChannels],e.bias),{weights:!0,bias:e.hasBias}}case"innerProduct":return this._initializer(t,"Weights","weights",[e.outputChannels,e.inputChannels],e.weights),e.hasBias&&this._initializer(t,"Weights","bias",[e.outputChannels],e.bias),{weights:!0,bias:e.hasBias};case"batchnorm":return this._initializer(t,"Weights","gamma",[e.channels],e.gamma),this._initializer(t,"Weights","beta",[e.channels],e.beta),e.mean&&this._initializer(t,"Weights","mean",[e.channels],e.mean),e.variance&&this._initializer(t,"Weights","variance",[e.channels],e.variance),{gamma:!0,beta:!0,mean:!0,variance:!0};case"embedding":return this._initializer(t,"Weights","weights",[e.inputDim,e.outputChannels],e.weights),{weights:!0};case"loadConstant":return this._initializer(t,"Weights","data",e.shape,e.data),{data:!0};case"scale":return this._initializer(t,"Weights","scale",e.shapeScale,e.scale),e.hasBias&&this._initializer(t,"Weights","bias",e.shapeBias,e.bias),{scale:!0,bias:e.hasBias};case"bias":return this._initializer(t,"Weights","bias",e.shape,e.bias),{bias:!0};case"simpleRecurrent":return this._initializer(t,"Weights","weights",[e.outputVectorSize,e.inputVectorSize],e.weightMatrix),this._initializer(t,"Weights","recurrent",[e.outputVectorSize,e.inputVectorSize],e.recursionMatrix),e.hasBiasVectors&&this._initializer(t,"Weights","bias",[e.outputVectorSize],e.biasVector),{weightMatrix:!0,recursionMatrix:!0,biasVector:e.hasBiasVectors};case"gru":{const i=[e.outputVectorSize,e.outputVectorSize],r=[e.outputVectorSize,e.inputVectorSize],s=[e.outputVectorSize];return this._initializer(t,"Weights","updateGateWeightMatrix",r,e.updateGateWeightMatrix),this._initializer(t,"Weights","resetGateWeightMatrix",r,e.resetGateWeightMatrix),this._initializer(t,"Weights","outputGateWeightMatrix",r,e.outputGateWeightMatrix),this._initializer(t,"Weights","updateGateRecursionMatrix",i,e.updateGateRecursionMatrix),this._initializer(t,"Weights","resetGateRecursionMatrix",i,e.resetGateRecursionMatrix),this._initializer(t,"Weights","outputGateRecursionMatrix",i,e.outputGateRecursionMatrix),e.hasBiasVectors&&(this._initializer(t,"Weights","updateGateBiasVector",s,e.updateGateBiasVector),this._initializer(t,"Weights","resetGateBiasVector",s,e.resetGateBiasVector),this._initializer(t,"Weights","outputGateBiasVector",s,e.outputGateBiasVector)),{updateGateWeightMatrix:!0,resetGateWeightMatrix:!0,outputGateWeightMatrix:!0,updateGateRecursionMatrix:!0,resetGateRecursionMatrix:!0,outputGateRecursionMatrix:!0,updateGateBiasVector:e.hasBiasVectors,resetGateBiasVector:e.hasBiasVectors,outputGateBiasVector:e.hasBiasVectors}}case"uniDirectionalLSTM":case"biDirectionalLSTM":{const i="uniDirectionalLSTM"==this._type?1:2,r=[e.outputVectorSize,e.inputVectorSize],s=[e.outputVectorSize];for(let a=0;a0;)e=e[t.shift()];e&&e[this._value]&&(this._value=e[this.value])}Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible?this._visible=!1:Object.prototype.hasOwnProperty.call(e,"default")&&(Array.isArray(i)&&(i=i.map((e=>e&&long.Long.isLong(e)?e.toNumber():e))),JSON.stringify(e.default)==JSON.stringify(i)&&(this._visible=!1))}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},coreml.Tensor=class{constructor(e,t,i,r){this._kind=e,this._name=t,this._data=null;let s="?";r&&(r.floatValue&&r.floatValue.length>0?(this._data=r.floatValue,s="float32"):r.float16Value&&r.float16Value.length>0?(this._data=r.float16Value,s="float16"):r.rawValue&&r.rawValue.length>0&&(r.quantization?(this._data=r.rawValue,s="uint"+r.quantization.numberOfBits.toString()):i=[]),this._quantization=r.quantization||null),this._type=new coreml.TensorType(s,new coreml.TensorShape(i))}get name(){return this._name}get kind(){return this._kind}get type(){return this._type}get quantization(){if(this._quantization){if(this._quantization.lookupTableQuantization&&this._quantization.lookupTableQuantization.floatValue&&this._quantization.lookupTableQuantization.floatValue.length>0){const e=[];for(const t of Object.keys(this._quantization.lookupTableQuantization.floatValue))e.push(t.toString()+" = "+this._quantization.lookupTableQuantization.floatValue[t].toString());return e.join("; ")}return"?"}return null}get state(){return this._context().state}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);return JSON.stringify(t,null,4)}_context(){const e={state:null,index:0,count:0};if(e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,!this._data)return e.state="Tensor data is empty.",e;switch(e.dataType){case"float32":e.data=this._data;break;case"float16":e.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:this._quantization?(e.dataType="quantization",e.bits=long.Long.isLong(this._quantization.numberOfBits)?this._quantization.numberOfBits.toNumber():this._quantization.numberOfBits,e.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength)):e.state="Tensor data type is not implemented."}return e}_decode(e,t){const i=[],r=e.dimensions[t];if(t==e.dimensions.length-1)for(let t=0;te.limit)return i.push("..."),i;switch(e.dataType){case"float32":i.push(this._data[e.index]),e.index++;break;case"float16":i.push(e.data.getFloat16(e.index,!0)),e.index+=2;break;case"quantization":i.push(e.data.getBits(e.index,e.bits)),e.index++}e.count++}else for(let s=0;se.limit)return i.push("..."),i;i.push(this._decode(e,t+1))}return i}},coreml.TensorType=class{constructor(e,t){this._dataType=e,this._shape=t||new coreml.TensorShape([])}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},coreml.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((e=>e.toString())).join(",")+"]":""}},coreml.MapType=class{constructor(e,t){this._keyType=e,this._valueType=t}get keyType(){return this._keyType}get valueType(){return this._valueType}toString(){return"map<"+this._keyType+","+this._valueType.toString()+">"}},coreml.ImageType=class{constructor(e,t,i){switch(this._colorSpace="?",e){case coreml.proto.ImageFeatureType.ColorSpace.GRAYSCALE:this._colorSpace="Grayscale";break;case coreml.proto.ImageFeatureType.ColorSpace.RGB:this._colorSpace="RGB";break;case coreml.proto.ImageFeatureType.ColorSpace.BGR:this._colorSpace="BGR"}this._width=t,this._height=i}toString(){return"image<"+this._colorSpace+","+this._width.toString()+"x"+this._height.toString()+">"}},coreml.OptionalType=class{constructor(e){this._type=e}toString(){return this._type.toString()+"?"}},coreml.Metadata=class{static open(e){return coreml.Metadata._metadata?Promise.resolve(coreml.Metadata._metadata):e.request(null,"coreml-metadata.json","utf-8").then((e=>(coreml.Metadata._metadata=new coreml.Metadata(e),coreml.Metadata._metadata))).catch((()=>(coreml.Metadata._metadata=new coreml.Metadata(null),coreml.Metadata._metadata)))}constructor(e){if(this._map=new Map,this._attributeCache=new Map,this._inputCache={},e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.get(e)}attribute(e,t){const i=e+":"+t;if(!this._attributeCache.has(i)){const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const i of t.attributes)this._attributeCache.set(e+":"+i.name,i);this._attributeCache.has(i)||this._attributeCache.set(i,null)}return this._attributeCache.get(i)}getInputSchema(e,t){let i=this._inputCache[e];if(!i){i={};const t=this.type(e);if(t&&t.inputs&&t.inputs.length>0)for(const e of t.inputs)i[e.name]=e;this._inputCache[e]=i}return i[t]||null}getInputs(e,t){const i=[],r=this._map[e];let s=0;for(;s{const s=t.identifier,n=s.split(".");n.pop();const o=n.join(".");return t.request(o+".weights",null).then((n=>this._openModel(e,s,t.text,n))).catch((()=>this._openModel(e,s,t.text,null)))}))}_openModel(t,e,s,n){try{return new darknet.Model(t,s,n?new darknet.Weights(n):null)}catch(t){const s=t&&t.message?t.message:t.toString();throw new darknet.Error(s.replace(/\.$/,"")+" in '"+e+"'.")}}},darknet.Model=class{constructor(t,e,s){this._graphs=[],this._graphs.push(new darknet.Graph(t,e,s))}get format(){return"Darknet"}get graphs(){return this._graphs}},darknet.Graph=class{constructor(t,e,s){this._inputs=[],this._outputs=[],this._nodes=[];const n=[];let o=null;const u=e.split("\n");let a=0;for(;u.length>0;){a++;const t=u.shift(),e=t.replace(/\s/g,"");if(e.length>0)switch(e[0]){case"#":case";":break;case"[":o={},o.line=a,o.type="]"===e[e.length-1]?e.substring(1,e.length-1):e.substring(1),o.options={},n.push(o);break;default:if(!o||e[0]<32||e[0]>126)throw new darknet.Error("Invalid cfg '"+t.replace(/[^\x20-\x7E]+/g,"").trim()+"' at line "+a.toString()+".");if(o){const s=e.indexOf("=");if(s<0)throw new darknet.Error("Invalid cfg '"+t.replace(/[^\x20-\x7E]+/g,"").trim()+"' at line "+a.toString()+".");const n=e.substring(0,s),u=e.substring(s+1);o.options[n]=u}}}const r=(t,e,s)=>{let n=t[e];if("string"==typeof n&&n.startsWith("$")){const t=n.substring(1);n=g.has(t)?g.get(t):n}if(void 0!==n){const s=parseInt(n,10);if(!Number.isInteger(s))throw new darknet.Error("Invalid int option '"+JSON.stringify(t[e])+"'.");return s}return s},i=(t,e,s)=>{const n=t[e];return void 0!==n?n:s},h=(t,e)=>{if(t.some((t=>0===t||void 0===t||isNaN(t))))throw new darknet.Error("Invalid tensor shape '"+JSON.stringify(t)+"' in '"+e+"'.");return new darknet.TensorShape(t)},l=(t,e,n)=>{const o=s?s.bytes(4*e.reduce(((t,e)=>t*e))):null,u=new darknet.TensorType("float32",h(e,"load_weights")),a=new darknet.Tensor(u,o),r=new darknet.Argument("",null,a);return new darknet.Parameter(t,!1!==n,[r])},p=(t,e,s)=>{t.weights.push(l(e+"scale",[s],""===e)),t.weights.push(l(e+"mean",[s],""===e)),t.weights.push(l(e+"variance",[s],""===e))},c=(t,e,s,n,o,u,a,r,i,c,_,w)=>{t.out_w=Math.floor((s+2*_-r)/i)+1,t.out_h=Math.floor((n+2*_-r)/c)+1,t.out_c=u,t.out=t.out_w*t.out_h*t.out_c,t.weights.push(l(e+"biases",[u],""===e)),w&&p(t,e,u),t.weights.push(l(e+"weights",[Math.floor(o/a),u,r,r],""===e)),t.outputs[0].type=new darknet.TensorType("float32",h([t.out_w,t.out_h,t.out_c],"make_convolutional_layer"))},_=(t,e,s,n,o)=>{t.out_h=1,t.out_w=1,t.out_c=n,t.out=n,t.weights.push(l(e+"biases",[n],""===e)),o&&p(t,e,n),t.weights.push(l(e+"weights",[s,n],""===e)),t.outputs[0].type=new darknet.TensorType("float32",h([n],"make_connected_layer"))},w={},g=new Map,d=n.shift();switch(d.type){case"net":case"network":w.h=r(d.options,"height",0),w.w=r(d.options,"width",0),w.c=r(d.options,"channels",0),w.inputs=r(d.options,"inputs",w.h*w.w*w.c);for(const t of Object.keys(d.options))g.set(t,d.options[t])}const y=w.w&&w.h&&w.c?new darknet.TensorType("float32",h([w.w,w.h,w.c],"params-if")):new darknet.TensorType("float32",h([w.inputs],"params-else")),f="input";if(w.arguments=[new darknet.Argument(f,y,null)],this._inputs.push(new darknet.Parameter(f,!0,w.arguments)),0===n.length)throw new darknet.Error("Config file has no sections.");let m=!0;for(let t=0;tNumber.parseInt(t.trim(),10))):[];for(let s of e){s=s<0?t+s:s;const e=n[s].layer;e&&u.inputs.push(e.outputs[0])}delete o.from;break}case"sam":case"scale_channels":{let e=r(o,"from",0);e=e<0?t+e:e;const s=n[e].layer;s&&u.inputs.push(s.outputs[0]),delete o.from;break}case"route":{u.inputs=[],u.layers=[];const e=o.layers?o.layers.split(",").map((t=>Number.parseInt(t.trim(),10))):[];for(let s=0;s>1:r(o,"padding",0);let h=r(o,"stride_x",-1),l=r(o,"stride_y",-1);if(h<1||l<1){const t=r(o,"stride",1);h=h<1?t:h,l=l<1?t:l}const p=r(o,"groups",1),_=r(o,"batch_normalize",0),g=i(o,"activation","logistic");c(u,"",w.w,w.h,w.c,n,p,s,h,l,a,_),"logistic"!==g&&e.chain.push({type:g});break}case"connected":{const t=r(o,"output",1),s=r(o,"batch_normalize",0),n=i(o,"activation","logistic");_(u,"",w.inputs,t,s),"logistic"!==n&&e.chain.push({type:n});break}case"local":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before avgpool layer must output image.");const s=r(o,"filters",1),n=r(o,"size",1),a=r(o,"stride",1),p=r(o,"pad",0),c=i(o,"activation","logistic");u.out_h=Math.floor((w.h-(p?1:n))/a)+1,u.out_w=Math.floor((w.w-(p?1:n))/a)+1,u.out_c=s,u.out=u.out_w*u.out_h*u.out_c,u.weights.push(l("weights",[w.c,s,n,n,u.out_h*u.out_w])),u.weights.push(l("biases",[u.out_w*u.out_h*u.out_c])),u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"local")),"logistic"!==c&&e.chain.push({type:c});break}case"batchnorm":u.out_h=w.h,u.out_w=w.w,u.out_c=w.c,u.out=u.in,p(s,e,"",u.out),u.outputs[0].type=new darknet.TensorType("float32",h([u.ouputs],"batchnorm"));break;case"activation":u.out_h=w.h,u.out_w=w.w,u.out_c=w.c,u.out=u.in,u.outputs[0].type=new darknet.TensorType("float32",h([u.ouputs],"activation"));break;case"max":case"maxpool":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before maxpool layer must output image.");const e=r(o,"antialiasing",0),s=r(o,"stride",1),n=r(o,"stride_x",s),a=r(o,"stride_y",s),i=e?1:n,l=e?1:a,p=r(o,"size",s),_=r(o,"padding",p-1),g=r(o,"out_channels",1);if(r(o,"maxpool_depth",0)?(u.out_c=g,u.out_w=w.w,u.out_h=w.h):(u.out_w=Math.floor((w.w+_-p)/i)+1,u.out_h=Math.floor((w.h+_-p)/l)+1,u.out_c=w.c),e){const t=2===e?2:3,s=2===e?0:Math.floor(t/3);u.input_layer={weights:[],outputs:u.outputs},c(u.input_layer,"",u.out_h,u.out_w,u.out_c,u.out_c,u.out_c,t,n,a,s,0),u.out_w=u.input_layer.out_w,u.out_h=u.input_layer.out_h,u.out_c=u.input_layer.out_c}else u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"maxpool"));u.out=u.out_w*u.out_h*u.out_c;break}case"avgpool":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before avgpool layer must output image.");u.out_w=1,u.out_h=1,u.out_c=w.c,u.out=u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"avgpool"));break}case"crnn":{const t=r(o,"size",3),e=r(o,"stride",1),s=r(o,"output",1),n=r(o,"hidden",1),a=r(o,"groups",1),i=r(o,"pad",0)?t>>1:r(o,"padding",0),h=r(o,"batch_normalize",0);u.input_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},c(u.input_layer,"input_",w.h,w.w,w.c,n,a,t,e,e,i,h),u.self_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},c(u.self_layer,"self_",w.h,w.w,n,n,a,t,e,e,i,h),u.output_layer={weights:[],outputs:u.outputs},c(u.output_layer,"output_",w.h,w.w,n,s,a,t,e,e,i,h),u.weights=u.weights.concat(u.input_layer.weights),u.weights=u.weights.concat(u.self_layer.weights),u.weights=u.weights.concat(u.output_layer.weights),u.out_h=u.output_layer.out_h,u.out_w=u.output_layer.out_w,u.out_c=s,u.out=u.output_layer.out;break}case"rnn":{const t=r(o,"output",1),e=r(o,"hidden",1),s=r(o,"batch_normalize",0),n=w.inputs;u.input_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_layer,"input_",n,e,s),u.self_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.self_layer,"self_",e,e,s),u.output_layer={weights:[],outputs:u.outputs},_(u.output_layer,"output_",e,t,s),u.weights=u.weights.concat(u.input_layer.weights),u.weights=u.weights.concat(u.self_layer.weights),u.weights=u.weights.concat(u.output_layer.weights),u.out_w=1,u.out_h=1,u.out_c=t,u.out=t;break}case"gru":{const t=w.inputs,e=r(o,"output",1),s=r(o,"batch_normalize",0);u.input_z_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_z_layer,"input_z",t,e,s),u.state_z_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_z_layer,"state_z",e,e,s),u.input_r_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_r_layer,"input_r",t,e,s),u.state_r_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_r_layer,"state_r",e,e,s),u.input_h_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_h_layer,"input_h",t,e,s),u.state_h_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_h_layer,"state_h",e,e,s),u.weights=u.weights.concat(u.input_z_layer.weights),u.weights=u.weights.concat(u.state_z_layer.weights),u.weights=u.weights.concat(u.input_r_layer.weights),u.weights=u.weights.concat(u.state_r_layer.weights),u.weights=u.weights.concat(u.input_h_layer.weights),u.weights=u.weights.concat(u.state_h_layer.weights),u.out=e,u.outputs[0].type=new darknet.TensorType("float32",h([e],"gru"));break}case"lstm":{const t=w.inputs,e=r(o,"output",1),n=r(o,"batch_normalize",0);u.uf={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.uf,"uf_",t,e,n),u.ui={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.ui,"ui_",t,e,n),u.ug={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.ug,"ug_",t,e,n),u.uo={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.uo,"uo_",t,e,n),u.wf={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wf,"wf_",e,e,n),u.wi={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wi,"wi_",e,e,n),u.wg={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wg,"wg_",e,e,n),u.wo={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wo,"wo_",e,e,n),u.weights=u.weights.concat(u.uf.weights),u.weights=u.weights.concat(u.ui.weights),u.weights=u.weights.concat(u.ug.weights),u.weights=u.weights.concat(u.uo.weights),u.weights=u.weights.concat(u.wf.weights),u.weights=u.weights.concat(u.wi.weights),u.weights=u.weights.concat(u.wg.weights),u.weights=u.weights.concat(u.wo.weights),u.out_w=1,u.out_h=1,u.out_c=e,u.out=e,u.outputs[0].type=new darknet.TensorType("float32",h([e],"lstm")),s=null;break}case"softmax":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"softmax"));break;case"dropout":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"dropout"));break;case"upsample":{const t=r(o,"stride",2);u.out_w=w.w*t,u.out_h=w.h*t,u.out_c=w.c,u.out=u.out_w*u.out_h*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"upsample"));break}case"crop":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before crop layer must output image.");const e=r(o,"crop_height",1),s=r(o,"crop_width",1);u.out_w=s,u.out_h=e,u.out_c=w.c,u.out=u.out_w*u.out_h*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"crop"));break}case"yolo":{const t=r(o,"classes",20),e=r(o,"num",1);u.out_h=w.h,u.out_w=w.w,u.out_c=e*(t+4+1),u.out=u.out_h*u.out_w*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"yolo"));break}case"Gaussian_yolo":{const t=r(o,"classes",20),e=r(o,"num",1);u.out_h=w.h,u.out_w=w.w,u.out_c=e*(t+8+1),u.out=u.out_h*u.out_w*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"Gaussian_yolo"));break}case"region":{const t=r(o,"coords",4),e=r(o,"classes",20),s=r(o,"num",1);u.out=w.h*w.w*s*(e+t+1),u.outputs[0].type=new darknet.TensorType("float32",h([w.h,w.w,s,e+t+1],"region"));break}case"cost":u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"cost"));break;case"reorg":{const t=r(o,"stride",1),e=r(o,"reverse",0),s=r(o,"extra",0);e?(u.out_w=w.w*t,u.out_h=w.h*t,u.out_c=Math.floor(w.c/(t*t))):(u.out_w=Math.floor(w.w/t),u.out_h=Math.floor(w.h/t),u.out_c=w.c*(t*t)),u.out=u.out_h*u.out_w*u.out_c,s&&(u.out_w=0,u.out_h=0,u.out_c=0,u.out=w.h*w.w*w.c+s),u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"reorg"));break}case"route":{const t=[].concat(u.layers),e=r(o,"groups",1);u.out=0;for(const s of t)u.out+=s.outputs/e;if(t.length>0){const s=t.shift();for(u.out_w=s.out_w,u.out_h=s.out_h,u.out_c=s.out_c/e;t.length>0;){const e=t.shift();if(e.out_w!==s.out_w||e.out_h!==s.out_h){m=!1;break}u.out_c+=e.out_c}m&&(u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"route")))}else m=!1;m||(u.out_h=0,u.out_w=0,u.out_c=0);break}case"shortcut":case"scale_channels":case"sam":{const t=i(o,"activation","linear");u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.w*w.h*w.c,u.outputs[0].type=new darknet.TensorType("float32",h([w.w,w.h,w.c],"shortcut|scale_channels|sam")),"linear"!==t&&e.chain.push({type:t});break}case"detection":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"detection"));break;default:m=!1}w.h=u.out_h,w.w=u.out_w,w.c=u.out_c,w.inputs=u.out,w.last=e}w.arguments=u.outputs}for(let e=0;e0&&this._inputs.push(new darknet.Parameter(n.inputs.length<=1?"input":"inputs",!0,n.inputs)),n&&n.weights&&n.weights.length>0&&(this._inputs=this._inputs.concat(n.weights)),n&&n.outputs&&n.outputs.length>0&&this._outputs.push(new darknet.Parameter(n.outputs.length<=1?"output":"outputs",!0,n.outputs)),s.chain)for(const n of s.chain)this._chain.push(new darknet.Node(t,e,n,""));const o=s.options;if(o)for(const e of Object.keys(o))this._attributes.push(new darknet.Attribute(t.attribute(this._type,e),e,o[e]))}get name(){return this._name}get location(){return this._location}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}},darknet.Attribute=class{constructor(t,e,s){if(this._name=e,this._value=s,t){switch(this._type=t.type||"",this._type){case"int32":{const t=parseInt(this._value,10);Number.isInteger(t)&&(this._value=t);break}case"float32":{const t=parseFloat(this._value);isNaN(t)||(this._value=t);break}case"int32[]":{const t=this._value.split(",").map((t=>parseInt(t.trim(),10)));t.every((t=>Number.isInteger(t)))&&(this._value=t);break}}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&this._value==t.default)&&(this._visible=!1)}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},darknet.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Tensor"}get name(){return""}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={};return this._data?(t.state=null,t.position=0,t.count=0,t.dataView=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dimensions=this.type.shape.dimensions,t):(t.state="Tensor data is empty.",t)}_decode(t,e){const s=[],n=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return s.push("..."),s;s.push(t.dataView.getFloat32(t.position,!0)),t.position+=4,t.count++}else for(let o=0;ot.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return s}},darknet.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this._dataType||"?")+this._shape.toString()}},darknet.TensorShape=class{constructor(t){if(t.some((t=>0===t||void 0===t||isNaN(t))))throw new darknet.Error("Invalid tensor shape '"+JSON.stringify(t)+"'.");this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},darknet.Weights=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0;const e=this.int32(),s=this.int32(),n=this.int32();if(this._seen=10*e+s>=2?this.int64():this.int32(),e>1e3||s>1e3)throw new darknet.Error("Unsupported transpose weights file version '"+[e,s,n].join(".")+"'.")}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int64(){const t=this.int32(),e=this.int32();return new long.Long(t,e,!0).toNumber()}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new darknet.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}validate(){if(this._position!==this._buffer.length)throw new darknet.Error("Invalid weights size.")}},darknet.Metadata=class{static open(t){return darknet.Metadata._metadata?Promise.resolve(darknet.Metadata._metadata):t.request(null,"darknet-metadata.json","utf-8").then((t=>(darknet.Metadata._metadata=new darknet.Metadata(t),darknet.Metadata._metadata))).catch((()=>(darknet.Metadata._metadata=new darknet.Metadata(null),darknet.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeMap=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)if(t&&t.name&&t.schema){if(this._map.has(t.name))throw new darknet.Error("Duplicate metadata key '"+t.name+"'.");t.schema.name=t.name,this._map.set(t.name,t.schema)}}}type(t){return this._map.get(t)||null}attribute(t,e){const s=t+":"+e;if(!this._attributeMap.has(s)){this._attributeMap.set(s,null);const e=this.type(t);if(e&&e.attributes)for(const s of e.attributes)this._attributeMap.set(t+":"+s.name,s)}return this._attributeMap.get(s)}},darknet.Error=class extends Error{constructor(t){super(t),this.name="Error loading Darknet model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=darknet.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..646ce4d993b6239b2f208ad12b2710bf1ff86d52 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j-metadata.json @@ -0,0 +1 @@ +[{"name":"Dense","schema":{"category":"Layer","attributes":[]}},{"name":"Output","schema":{"category":"Layer","attributes":[]}},{"name":"Convolution","schema":{"category":"Layer","attributes":[{"name":"dilation"},{"name":"kernelSize"},{"name":"padding"}]}},{"name":"SeparableConvolution2D","schema":{"category":"Layer","attributes":[]}},{"name":"BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"eps"},{"name":"gamma"},{"name":"decay"}]}},{"name":"Sigmoid","schema":{"category":"Activation","attributes":[]}},{"name":"LReLU","schema":{"category":"Activation","attributes":[]}},{"name":"ReLU","schema":{"category":"Activation","attributes":[]}},{"name":"TanH","schema":{"category":"Activation","attributes":[]}},{"name":"Softmax","schema":{"category":"Activation","attributes":[]}},{"name":"Merge","schema":{"category":"Tensor","attributes":[]}},{"name":"Upsampling2D","schema":{"category":"Layer","attributes":[]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[]}},{"name":"GlobalPooling","schema":{"category":"Pool","attributes":[]}},{"name":"Subsampling","schema":{"category":"Layer","attributes":[]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j.js new file mode 100644 index 0000000000000000000000000000000000000000..854345a94072a77f8f4fbefe6f60c9e368c917ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/dl4j.js @@ -0,0 +1 @@ +var dl4j=dl4j||{},long=long||{Long:require("long")};dl4j.ModelFactory=class{match(t){return!!("zip"===t.identifier.toLowerCase().split(".").pop().toLowerCase()&&t.entries("zip").length>0&&dl4j.ModelFactory._openContainer(t))}open(t,e){const n=t.identifier;try{const s=dl4j.ModelFactory._openContainer(t),r=JSON.parse(s.configuration);return dl4j.Metadata.open(e).then((t=>{try{return new dl4j.Model(t,r,s.coefficients)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new dl4j.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}}))}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();return Promise.reject(new dl4j.Error(s.replace(/\.$/,"")+" in '"+n+"'."))}}static _openContainer(t){const e=t.entries("zip"),n=e.filter((t=>"configuration.json"===t.name));if(1!=n.length)return null;let s=null;try{s=new TextDecoder("utf-8").decode(n[0].data)}catch(t){return null}if(-1===s.indexOf('"vertices"')&&-1===s.indexOf('"confs"'))return null;const r=e.filter((t=>"coefficients.bin"===t.name));return r.length>1?null:{configuration:s,coefficients:1==r.length?r[0].data:[]}}},dl4j.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new dl4j.Graph(t,e,n))}get format(){return"Deeplearning4j"}get graphs(){return this._graphs}},dl4j.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new dl4j.NDArrayReader(n).dataType;if(e.networkInputs)for(const t of e.networkInputs)this._inputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,null)]));if(e.networkOutputs)for(const t of e.networkOutputs)this._outputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,null)]));let r=null;if(e.vertices)for(const n in e.vertices){const i=dl4j.Node._object(e.vertices[n]);r=e.vertexInputs[n];let a=[],o=null;switch(i.__type__){case"LayerVertex":o=dl4j.Node._object(i.layerConf.layer),a=i.layerConf.variables;break;case"MergeVertex":o={__type__:"Merge",layerName:n};break;case"ElementWiseVertex":o={__type__:"ElementWise",layerName:n,op:i.op};break;case"PreprocessorVertex":o={__type__:"Preprocessor",layerName:n};break;default:throw new dl4j.Error("Unsupported vertex class '"+i["@class"]+"'.")}this._nodes.push(new dl4j.Node(t,o,r,s,a))}if(e.confs){r=["input"],this._inputs.push(new dl4j.Parameter("input",!0,[new dl4j.Argument("input",null,null)]));for(const n of e.confs){const e=dl4j.Node._object(n.layer);this._nodes.push(new dl4j.Node(t,e,r,s,n.variables)),r=[e.layerName]}this._outputs.push(new dl4j.Parameter("output",!0,[new dl4j.Argument(r[0],null,null)]))}}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},dl4j.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},dl4j.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new dl4j.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e,this._initializer=n}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},dl4j.Node=class{constructor(t,e,n,s,r){if(this._metadata=t,this._type=e.__type__,this._name=e.layerName||"",this._inputs=[],this._outputs=[],this._attributes=[],n&&n.length>0){const t=n.map((t=>new dl4j.Argument(t,null,null)));this._inputs.push(new dl4j.Parameter(t.length<2?"input":"inputs",!0,t))}if(r)for(const t of r){let n=null;switch(this._type){case"Convolution":switch(t){case"W":n=new dl4j.Tensor(s,e.kernelSize.concat([e.nin,e.nout]));break;case"b":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"SeparableConvolution2D":switch(t){case"W":n=new dl4j.Tensor(s,e.kernelSize.concat([e.nin,e.nout]));break;case"pW":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"Output":case"Dense":switch(t){case"W":n=new dl4j.Tensor(s,[e.nout,e.nin]);break;case"b":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"BatchNormalization":n=new dl4j.Tensor(s,[e.nin]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}this._inputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,n)]))}this._name&&this._outputs.push(new dl4j.Parameter("output",!0,[new dl4j.Argument(this._name,null,null)]));let i=e;if(e.activationFn){const n=dl4j.Node._object(e.activationFn);"ActivationIdentity"!==n.__type__&&"Identity"!==n.__type__&&(n.__type__.startsWith("Activation")&&(n.__type__=n.__type__.substring("Activation".length)),"Activation"==this._type?(this._type=n.__type__,i=n):(this._chain=this._chain||[],this._chain.push(new dl4j.Node(t,n,[],null,null))))}for(const e in i){switch(e){case"__type__":case"constraints":case"layerName":case"activationFn":case"idropout":case"hasBias":continue}this._attributes.push(new dl4j.Attribute(t.attribute(this._type,e),e,i[e]))}if(e.idropout&&1!==dl4j.Node._object(e.idropout).p)throw new dl4j.Error("Layer 'idropout' not implemented.")}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}static _object(t){let e={};if(t["@class"]){e=t;let n=t["@class"].split(".").pop();n.endsWith("Layer")&&(n=n.substring(0,n.length-5)),delete t["@class"],e.__type__=n}else{let n=Object.keys(t)[0];e=t[n],n.length>0&&(n=n[0].toUpperCase()+n.substring(1)),e.__type__=n}return e}},dl4j.Attribute=class{constructor(t,e,n){this._name=e,this._value=n,this._visible=!1,t&&t.visible&&(this._visible=!0)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return this._visible}},dl4j.Tensor=class{constructor(t,e){this._type=new dl4j.TensorType(t,new dl4j.TensorShape(e))}get type(){return this._type}get state(){return"Not implemented."}},dl4j.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},dl4j.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},dl4j.Metadata=class{static open(t){return dl4j.Metadata.textDecoder=dl4j.Metadata.textDecoder||new TextDecoder("utf-8"),dl4j.Metadata._metadata?Promise.resolve(dl4j.Metadata._metadata):t.request(null,"dl4j-metadata.json","utf-8").then((t=>(dl4j.Metadata._metadata=new dl4j.Metadata(t),dl4j.Metadata._metadata))).catch((()=>(dl4j.Metadata._metadata=new dl4j.Metadata(null),dl4j.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t&&t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},dl4j.NDArrayReader=class{constructor(t){const e=new dl4j.BinaryReader(t);dl4j.NDArrayReader._header(e);const n=dl4j.NDArrayReader._header(e);this._dataType=n.type}get dataType(){return this._dataType}static _header(t){const e={};switch(e.alloc=t.string(),e.length=0,e.alloc){case"DIRECT":case"HEAP":case"JAVACPP":e.length=t.int32();break;case"LONG_SHAPE":case"MIXED_DATA_TYPES":e.length=t.int64()}switch(e.type=t.string(),e.type){case"INT":e.type="int32",e.itemsize=4;break;case"FLOAT":e.type="float32",e.itemsize=4}return e.data=t.bytes(e.itemsize*e.length),e}},dl4j.BinaryReader=class{constructor(t){this._buffer=t,this._position=0}bytes(t){const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}string(){const t=this._buffer[this._position++]<<8|this._buffer[this._position++],e=this.bytes(t);return new TextDecoder("ascii").decode(e)}int32(){return this._buffer[this._position++]<<24|this._buffer[this._position++]<<16|this._buffer[this._position++]<<8|this._buffer[this._position++]}int64(){const t=this.int32(),e=this.int32();return new long.Long(t,e,!0).toNumber()}},dl4j.Error=class extends Error{constructor(t){super(t),this.name="Error loading Deeplearning4j model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=dl4j.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/flatbuffers.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/flatbuffers.js new file mode 100644 index 0000000000000000000000000000000000000000..882e63fca1d772daa5f6ba9fb4db4701eca2e03a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/flatbuffers.js @@ -0,0 +1 @@ +var flatbuffers={},long=long||{Long:require("long")};flatbuffers.get=t=>(flatbuffers._map=flatbuffers._map||new Map,flatbuffers._map.has(t)||flatbuffers._map.set(t,{}),flatbuffers._map.get(t)),flatbuffers.Long=long.Long,flatbuffers.Reader=class{constructor(t){this._buffer=t,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength)}get root(){return this.int32(this._position)+this._position}identifier(t){if(4!==t.length)throw new flatbuffers.Error("File identifier must be 4 characters in length.");for(let r=0;r<4;r++)if(t.charCodeAt(r)!=this.int8(this._position+4+r))return!1;return!0}bool(t){return!!this.int8(t)}bool_(t,r,e){return(r=this._offset(t,r))?this.bool(t+r):e}int8(t){return this.uint8(t)<<24>>24}int8_(t,r,e){return(r=this._offset(t,r))?this.int8(t+r):e}uint8(t){return this._buffer[t]}uint8_(t,r,e){return(r=this._offset(t,r))?this.uint8(t+r):e}int16(t){return this._dataView.getInt16(t,!0)}int16_(t,r,e){return(r=this._offset(t,r))?this.int16(t+r):e}uint16(t){return this._dataView.getUint16(t,!0)}uint16_(t,r,e){return(r=this._offset(t,r))?this.uint16(t+r):e}int32(t){return this._dataView.getInt32(t,!0)}int32_(t,r,e){return(r=this._offset(t,r))?this.int32(t+r):e}uint32(t){return this._dataView.getUint32(t,!0)}uint32_(t,r,e){return(r=this._offset(t,r))?this.int32(t+r):e}int64(t){return new flatbuffers.Long(this.int32(t),this.int32(t+4))}uint64(t){return new flatbuffers.Long(this.uint32(t),this.uint32(t+4))}float32(t){return this._dataView.getFloat32(t,!0)}float32_(t,r,e){return(r=this._offset(t,r))?this.float32(t+r):e}float64(t){return this._dataView.getFloat64(t,!0)}float64_(t,r,e){return(r=this._offset(t,r))?this.float64(t+r):e}string(t,r){t+=this.int32(t);const e=this.int32(t);var i="",n=0;if(t+=4,1===r)return this._buffer.subarray(t,t+e);for(;n>10),56320+(1023&s)))}return i}string_(t,r,e){return(r=this._offset(t,r))?this.string(t+r):e}bools_(t,r){if(r=this._offset(t,r)){const e=this._length(t+r);r=this._vector(t+r);const i=new Array(e);for(let t=0;t>3)),this.uint32(r+(t>>3)+4),!1);return i}return[]}strings_(t,r){if(r=this._offset(t,r)){const e=this._length(t+r);r=this._vector(t+r);const i=new Array(e);for(let t=0;t{let r=null;const o=t.identifier;try{const e=new a.Reader(t.buffer).read(),o=flux.ModelFactory._backref(e,e);if(r=o.model,!r)throw new flux.Error("File does not contain Flux model.")}catch(t){const e=t&&t.message?t.message:t.toString();throw new flux.Error(e.replace(/\.$/,"")+" in '"+o+"'.")}return flux.Metadata.open(e).then((t=>{try{return new flux.Model(t,r)}catch(t){const e=t&&t.message?t.message:t.toString();throw new flux.Error(e.replace(/\.$/,"")+" in '"+o+"'.")}}))}))}static _backref(t,e){if(Array.isArray(t))for(let a=0;a(flux.Metadata._metadata=new flux.Metadata(t),flux.Metadata._metadata))).catch((()=>(flux.Metadata._metadata=new flux.Metadata(null),flux.Metadata._metadatas)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},flux.Error=class extends Error{constructor(t){super(t),this.name="Flux Error"}},module&&module.exports&&(module.exports.ModelFactory=flux.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/gzip.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/gzip.js new file mode 100644 index 0000000000000000000000000000000000000000..66788e5257ed8d5c291ed04bb6c07798083105de --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/gzip.js @@ -0,0 +1 @@ +var gzip=gzip||{};gzip.Archive=class{constructor(t){if(this._entries=[],t.length<18||31!=t[0]||139!=t[1])throw new gzip.Error("Invalid gzip archive.");const i=new gzip.Reader(t,0,t.length);this._entries.push(new gzip.Entry(i))}get entries(){return this._entries}},gzip.Entry=class{constructor(t){if(!t.match([31,139]))throw new gzip.Error("Invalid gzip signature.");const i=t.byte();if(8!=i)throw new gzip.Error("Invalid compression method '"+i.toString()+"'.");const s=t.byte();if(t.uint32(),t.byte(),t.byte(),0!=(4&s)){const i=t.uint16();t.skip(i)}0!=(8&s)&&(this._name=t.string()),0!=(16&s)&&t.string(),0!=(1&s)&&t.uint16();const n=t.bytes();if("object"==typeof process&&"object"==typeof process.versions&&void 0!==process.versions.node?this._data=require("zlib").inflateRawSync(n):"undefined"!=typeof pako?this._data=pako.inflateRaw(n):this._data=new require("./zip").Inflater().inflateRaw(n),t.position=-8,t.uint32(),t.uint32()!=this._data.length)throw new gzip.Error("Invalid size.")}get name(){return this._name}get data(){return this._data}},gzip.Reader=class{constructor(t,i,s){this._buffer=t,this._position=i,this._end=s}match(t){if(this._position+t.length<=this._end)for(let i=0;i=0?t:this._end+t}skip(t){if(this._position+t>this._end)throw new gzip.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new gzip.Error("Data not available.");t=void 0===t?this._end:t;const i=this._buffer.subarray(this._position,this._position+t);return this._position+=t,i}byte(){if(this._position+1>this._end)throw new gzip.Error("Data not available.");const t=this._buffer[this._position];return this._position++,t}uint16(){if(this._position+2>this._end)throw new gzip.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}string(){let t="";const i=this._buffer.indexOf(0,this._position);if(i<0)throw new gzip.Error("End of string not found.");for(;this._position0&&(this._indexedStorageInternalNodeK=e.uint16(),this.seek(2)),this._baseAddress=e.offset(),e.offset(),this._endOfFileAddress=e.offset(),e.offset(),0!=this._baseAddress)throw new hdf5.Error("Base address is not zero.");const t=new hdf5.SymbolTableEntry(e);this._rootGroup=new hdf5.Group(e,t,null,this._globalHeap,"","");break}case 2:case 3:{e.initialize(),e.byte(),this._baseAddress=e.offset(),this._superBlockExtensionAddress=e.offset(),this._endOfFileAddress=e.offset();const t=new hdf5.DataObjectHeader(e.at(e.offset()));this._rootGroup=new hdf5.Group(e,null,t,this._globalHeap,"","");break}default:throw new hdf5.Error("Unsupported Superblock version "+s+".")}}get rootGroup(){return this._rootGroup}},hdf5.Group=class{constructor(t,e,s,i,a,r){this._reader=t,this._entry=e,this._dataObjectHeader=s,this._globalHeap=i,this._name=r,this._path="/"==a?a+r:a+"/"+r}get name(){return this._name}get path(){return this._path}group(t){this._decodeGroups();const e=t.indexOf("/");if(-1!=e){const s=t.substring(e+1),i=t.substring(0,e),a=this.group(i);if(null!=a)return a.group(s)}else{const e=this._groupMap[t];if(e)return e}return null}get groups(){return this._decodeGroups(),this._groups}attribute(t){return this._decodeDataObject(),this._attributes[t]}get attributes(){return this._decodeDataObject(),this._attributes}get value(){return this._decodeDataObject(),this._value}_decodeDataObject(){if(this._dataObjectHeader||(this._dataObjectHeader=new hdf5.DataObjectHeader(this._reader.at(this._entry.objectHeaderAddress))),!this._attributes){this._attributes={};for(const t of this._dataObjectHeader.attributes){const e=t.name,s=t.decodeValue(this._globalHeap);this._attributes[e]=s}this._value=null;const t=this._dataObjectHeader.datatype,e=this._dataObjectHeader.dataspace,s=this._dataObjectHeader.dataLayout,i=this._dataObjectHeader.filterPipeline;t&&e&&s&&(this._value=new hdf5.Variable(this._reader,this._globalHeap,t,e,s,i))}}_decodeGroups(){if(!this._groups)if(this._groupMap={},this._groups=[],this._entry){if(this._entry.treeAddress||this._entry.heapAddress){const t=new hdf5.Heap(this._reader.at(this._entry.heapAddress)),e=new hdf5.Tree(this._reader.at(this._entry.treeAddress));for(const s of e.nodes)for(const e of s.entries){const s=t.getString(e.linkNameOffset),i=new hdf5.Group(this._reader,e,null,this._globalHeap,this._path,s);this._groups.push(i),this._groupMap[s]=i}}}else{this._decodeDataObject();for(const t of this._dataObjectHeader.links)if(Object.prototype.hasOwnProperty.call(t,"objectHeaderAddress")){const e=t.name,s=new hdf5.DataObjectHeader(this._reader.at(t.objectHeaderAddress)),i=new hdf5.Group(this._reader,null,s,this._globalHeap,this._path,e);this._groups.push(i),this._groupMap[e]=i}}}},hdf5.Variable=class{constructor(t,e,s,i,a,r){this._reader=t,this._globalHeap=e,this._datatype=s,this._dataspace=i,this._dataLayout=a,this._filterPipeline=r}get type(){return this._datatype.type}get littleEndian(){return this._datatype.littleEndian}get shape(){return this._dataspace.shape}get value(){const t=this.data;if(t){const e=new hdf5.Reader(t),s=this._dataspace.read(this._datatype,e);return this._dataspace.decode(this._datatype,s,s,this._globalHeap)}return null}get data(){switch(this._dataLayout.layoutClass){case 1:if(this._dataLayout.address)return this._reader.at(this._dataLayout.address).bytes(this._dataLayout.size);break;case 2:{const t=new hdf5.Tree(this._reader.at(this._dataLayout.address),this._dataLayout.dimensionality);if(2==this._dataLayout.dimensionality&&1==this._dataspace.shape.length){let e=this._dataLayout.datasetElementSize;for(let t=0;tthis._buffer.length)throw new hdf5.Error("Expected "+(this._position+this._offset-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}int8(){const t=this._offset;return this.skip(1),this._dataView.getInt8(this._position+t)}byte(){const t=this._offset;return this.skip(1),this._dataView.getUint8(this._position+t)}bytes(t){const e=this._offset;return this.skip(t),this._buffer.subarray(this._position+e,this._position+this._offset)}int16(){const t=this._offset;return this.skip(2),this._dataView.getInt16(this._position+t,!0)}uint16(){const t=this._offset;return this.skip(2),this._dataView.getUint16(this._position+t,!0)}int32(){const t=this._offset;return this.skip(4),this._dataView.getInt32(this._position+t,!0)}uint32(){const t=this._offset;return this.skip(4),this._dataView.getUint32(this._position+t,!0)}int64(){const t=this._offset;this.skip(8);const e=this._dataView.getUint32(this._position+t,!0),s=this._dataView.getUint32(this._position+t+4,!0);return new long.Long(e,s,!1).toNumber()}uint64(){const t=this._offset;this.skip(8);const e=this._dataView.getUint32(this._position+t,!0),s=this._dataView.getUint32(this._position+t+4,!0);return new long.Long(e,s,!0).toNumber()}uint(t){switch(t){case 0:return this.byte();case 1:return this.uint16();case 2:return this.uint32();case 3:return this.uint64()}}float16(){const t=this._offset;this.skip(2);const e=this._dataView.getUint16(this._position+t,!0),s=(32768&e)>>15,i=(31744&e)>>10,a=1023&e;return 0==i?(s?-1:1)*Math.pow(2,-14)*(a/Math.pow(2,10)):31==i?a?NaN:1/0*(s?-1:1):(s?-1:1)*Math.pow(2,i-15)*(1+a/Math.pow(2,10))}float32(){const t=this._offset;return this.skip(4),this._dataView.getFloat32(this._position+t,!0)}float64(){const t=this._offset;return this.skip(8),this._dataView.getFloat64(this._position+t,!0)}string(t,e){if(!t||-1==t){let e=this._position+this._offset;for(;0!=this._buffer[e];)e++;t=e-this._position-this._offset+1}const s=this.bytes(t);return hdf5.Reader.decode(s,e)}static decode(t,e){let s="";return"utf-8"==e?(hdf5.Reader._utf8Decoder||(hdf5.Reader._utf8Decoder=new TextDecoder("utf-8")),s=hdf5.Reader._utf8Decoder.decode(t)):(hdf5.Reader._asciiDecoder||(hdf5.Reader._asciiDecoder=new TextDecoder("ascii")),s=hdf5.Reader._asciiDecoder.decode(t)),s.replace(/\0/g,"")}offset(){switch(this._offsetSize){case 8:{const t=this.uint32(),e=this.uint32();if(4294967295===t&&4294967295===e)return;return new long.Long(t,e,!0).toNumber()}case 4:{const t=this.uint32();if(4294967295===t)return;return t}}throw new hdf5.Error("Unsupported offset size '"+this._offsetSize+"'.")}length(){switch(this._lengthSize){case 8:{const t=this.uint32(),e=this.uint32();if(4294967295===t&&4294967295===e)return;return new long.Long(t,e,!0).toNumber()}case 4:{const t=this.uint32();if(4294967295===t)return;return t}}throw new hdf5.Error("Unsupported length size '"+this._lengthSize+"'.")}at(t){const e=new hdf5.Reader(null);return e._buffer=this._buffer,e._dataView=this._dataView,e._position=t,e._offset=0,e._offsetSize=this._offsetSize,e._lengthSize=this._lengthSize,e}clone(){const t=new hdf5.Reader(this._buffer,this._position);return t._buffer=this._buffer,t._dataView=this._dataView,t._position=this._position,t._offset=this._offset,t._offsetSize=this._offsetSize,t._lengthSize=this._lengthSize,t}align(t){this._offset%t!=0&&(this._offset=(Math.floor(this._offset/t)+1)*t)}match(t){if(this._position+this._offset+t.length>this._buffer.length)return!1;const e=this._offset,s=this.bytes(t.length);for(let i=0;i=i)&&this.continuations.length>0){const e=this.continuations.shift();t=t.at(e.offset),i=e.offset+e.length}else t.align(8)}break}case 2:{const e=t.byte();0!=(32&e)&&(t.uint32(),t.uint32(),t.uint32(),t.uint32()),0!=(16&e)&&(t.uint16(),t.uint16());const s=t.uint(3&e);let i=!0,a=t.position+s;for(;i&&t.position=a)&&this.continuations.length>0){const e=this.continuations.shift();if(t=t.at(e.offset),a=e.offset+e.length,!t.match("OCHK"))throw new hdf5.Error("Invalid continuation block signature.");i=!0}}break}default:throw new hdf5.Error("Unsupported data object header version '"+e+"'.")}}_readMessage(t,e,s,i){switch(e){case 0:return!1;case 1:this.dataspace=4!=s||1!=i?new hdf5.Dataspace(t.clone()):null;break;case 2:this.linkInfo=new hdf5.LinkInfo(t.clone());break;case 3:this.datatype=new hdf5.Datatype(t.clone());break;case 4:case 5:this.fillValue=new hdf5.FillValue(t.clone(),e);break;case 6:this.links.push(new hdf5.Link(t.clone()));break;case 8:this.dataLayout=new hdf5.DataLayout(t.clone());break;case 10:this.groupInfo=new hdf5.GroupInfo(t.clone());break;case 11:this.filterPipeline=new hdf5.FilterPipeline(t.clone());break;case 12:this.attributes.push(new hdf5.Attribute(t.clone()));break;case 13:this.comment=t.string(-1,"ascii");break;case 16:this.continuations.push(new hdf5.ObjectHeaderContinuation(t.clone()));break;case 17:this.symbolTable=new hdf5.SymbolTable(t.clone());break;case 14:case 18:this.objectModificationTime=new hdf5.ObjectModificationTime(t.clone(),e);break;case 21:this.attributeInfo=new hdf5.AttributeInfo(t.clone());break;default:throw new hdf5.Error("Unsupported message type '"+e+"'.")}return t.skip(s),!0}},hdf5.Message=class{constructor(t,e,s){this._type=t,this._data=e,this._flags=s}},hdf5.Dataspace=class{constructor(t){this._sizes=[];const e=t.byte();switch(e){case 1:this._dimensions=t.byte(),this._flags=t.byte(),t.skip(1),t.skip(4);for(let e=0;e>4;switch(this._class=15&e,s){case 1:case 2:switch(this._flags=t.byte()|t.byte()<<8|t.byte()<<16,this._size=t.uint32(),this._class){case 0:this._bitOffset=t.uint16(),this._bitPrecision=t.uint16();break;case 8:{this._base=new hdf5.Datatype(t),this._names=[],this._values=[];const e=65535&this._flags;for(let s=0;s>8&15){case 0:return hdf5.Reader.decode(t.bytes(this._size),"ascii");case 1:return hdf5.Reader.decode(t.bytes(this._size),"utf-8")}throw new hdf5.Error("Unsupported character encoding.");case 5:return t.bytes(this._size);case 9:return{length:t.uint32(),globalHeapID:new hdf5.GlobalHeapID(t)}}throw new hdf5.Error("Unsupported datatype class '"+this._class+"'.")}decode(t,e){switch(this._class){case 0:case 1:case 3:case 5:return t;case 9:{const s=e.get(t.globalHeapID);if(null!=s){switch(this._flags>>8&15){case 0:return hdf5.Reader.decode(s.data,"ascii");case 1:return hdf5.Reader.decode(s.data,"utf-8")}throw new hdf5.Error("Unsupported character encoding.")}break}default:throw new hdf5.Error("Unsupported datatype class '"+this._class+"'.")}return null}},hdf5.FillValue=class{constructor(t,e){switch(e){case 4:{const e=t.uint32();this.data=t.bytes(e);break}case 5:default:{const e=t.byte();switch(e){case 1:case 2:{t.byte(),t.byte();const s=t.byte();if(1===e||1===s){const e=t.uint32();this.data=t.bytes(e)}break}default:throw new hdf5.Error("Unsupported fill value version '"+e+"'.")}break}}}},hdf5.Link=class{constructor(t){const e=t.byte();switch(e){case 1:{const e=t.byte();this.type=0!=(8&e)?t.byte():0,0!=(4&e)&&(this.creationOrder=t.uint32());const s=0!=(16&e)&&1==t.byte()?"utf-8":"ascii";switch(this.name=t.string(t.uint(3&e),s),this.type){case 0:this.objectHeaderAddress=t.offset()}break}default:throw new hdf5.Error("Unsupported link message version '"+e+"'.")}}},hdf5.DataLayout=class{constructor(t){const e=t.byte();switch(e){case 1:case 2:switch(this.dimensionality=t.byte(),this.layoutClass=t.byte(),t.skip(5),this.layoutClass){case 1:this.address=t.offset(),this.dimensionSizes=[];for(let e=0;e{var e,t={63332:(e,t,s)=>{var i=s(32845),n=n||{};n.Archive=class{constructor(e){if(this._entries=[],e.length<18||31!=e[0]||139!=e[1])throw new n.Error("Invalid gzip archive.");const t=new n.Reader(e,0,e.length);this._entries.push(new n.Entry(t))}get entries(){return this._entries}},n.Entry=class{constructor(e){if(!e.match([31,139]))throw new n.Error("Invalid gzip signature.");const t=e.byte();if(8!=t)throw new n.Error("Invalid compression method '"+t.toString()+"'.");const o=e.byte();if(e.uint32(),e.byte(),e.byte(),0!=(4&o)){const t=e.uint16();e.skip(t)}0!=(8&o)&&(this._name=e.string()),0!=(16&o)&&e.string(),0!=(1&o)&&e.uint16();const r=e.bytes();if("object"==typeof process&&"object"==typeof process.versions&&void 0!==process.versions.node?this._data=s(83260).inflateRawSync(r):this._data=void 0!==i?i.inflateRaw(r):new s(71681).Inflater().inflateRaw(r),e.position=-8,e.uint32(),e.uint32()!=this._data.length)throw new n.Error("Invalid size.")}get name(){return this._name}get data(){return this._data}},n.Reader=class{constructor(e,t,s){this._buffer=e,this._position=t,this._end=s}match(e){if(this._position+e.length<=this._end)for(let t=0;t=0?e:this._end+e}skip(e){if(this._position+e>this._end)throw new n.Error("Data not available.");this._position+=e}bytes(e){if(this._position+e>this._end)throw new n.Error("Data not available.");e=void 0===e?this._end:e;const t=this._buffer.subarray(this._position,this._position+e);return this._position+=e,t}byte(){if(this._position+1>this._end)throw new n.Error("Data not available.");const e=this._buffer[this._position];return this._position++,e}uint16(){if(this._position+2>this._end)throw new n.Error("Data not available.");const e=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,e}uint32(){return this.uint16()|this.uint16()<<16}string(){let e="";const t=this._buffer.indexOf(0,this._position);if(t<0)throw new n.Error("End of string not found.");for(;this._position{var i=i||{},n=n||{Long:s(27808)};i.get=e=>(i._map=i._map||new Map,i._map.has(e)||i._map.set(e,{}),i._map.get(e)),i.Reader=class{constructor(e){this._buffer=e,this._length=e.length,this._position=0,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._decoder=new TextDecoder("utf-8")}static create(e){return new i.Reader(e)}next(e){return void 0===e?this._length:this._position+e}end(e){return this._positionthis._length)throw this._indexOutOfRangeError(e);return this._position+=e,this._buffer.slice(t,s)}uint32(){let e=4294967295;if(e=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return e;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const e=this._position;return this._position+=4,this._dataView.getFloat32(e,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const e=this._position;return this._position+=8,this._dataView.getFloat64(e,!0)}array(e,t,s){if(2==(7&s)){const s=this.uint32()+this._position;for(;this._position0)throw new i.Error("Invalid packed float array.");const t=this.uint32(),s=this._position+t,n=t>>>2;e=t>1048576?new Float32Array(n):new Array(n);let o=this._position;for(let t=0;t0)throw new i.Error("Invalid packed float array.");const t=this.uint32(),s=this._position+t,n=t>>>3;e=t>1048576?new Float64Array(n):new Array(n);let o=this._position;for(let t=0;tthis._length)throw this._indexOutOfRangeError(e);this._position+=e}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw new i.Error("invalid wire type "+e+" at offset "+this._position)}}pair(e,t,s){this.skip(),this._position++;const n="object"==typeof t?i.LongBits.hash(t()):t();this._position++;const o=s();e[n]=o}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const e=this._readFixed32();this._position+=4;const t=this._readFixed32();return new i.LongBits(e,t)}_readLongVarint(){const e=new i.LongBits(0,0);let t=0;if(!(this._length-this._position>4)){for(;t<3;++t){if(this._position>=this._length)throw this._indexOutOfRangeError();if(e.lo=(e.lo|(127&this._buffer[this._position])<<7*t)>>>0,this._buffer[this._position++]<128)return e}return e.lo=(e.lo|(127&this._buffer[this._position++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this._buffer[this._position])<<7*t)>>>0,this._buffer[this._position++]<128)return e;if(e.lo=(e.lo|(127&this._buffer[this._position])<<28)>>>0,e.hi=(e.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return e;if(t=0,this._length-this._position>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this._buffer[this._position])<<7*t+3)>>>0,this._buffer[this._position++]<128)return e}else for(;t<5;++t){if(this._position>=this._length)throw this._indexOutOfRangeError();if(e.hi=(e.hi|(127&this._buffer[this._position])<<7*t+3)>>>0,this._buffer[this._position++]<128)return e}throw new i.Error("Invalid varint encoding.")}_indexOutOfRangeError(e){return RangeError("index out of range: "+this._position+" + "+(e||1)+" > "+this._length)}},i.TextReader=class{constructor(e){this._text=e,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(e){return new i.TextReader(e)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const e=this.peek();return this._depth>0&&"}"===e?(this.expect("}"),this.match(";"),this._depth--,!0):""===e}tag(){const e=this.read(),t=this.peek();return"["!==t&&"{"!==t&&this.expect(":"),e}assert(e){const t=this.tag();if(t!==e)throw new i.Error("Unexpected '"+t+"' instead of '"+e+"'"+this.location())}integer(){const e=this.read(),t=Number.parseInt(e,10);if(Number.isNaN(e-t))throw new i.Error("Couldn't parse integer '"+e+"'"+this.location());return this.semicolon(),t}float(){let e=this.read();if(e.startsWith("nan"))return NaN;if(e.startsWith("inf"))return 1/0;if(e.startsWith("-inf"))return-1/0;e.endsWith("f")&&(e=e.substring(0,e.length-1));const t=Number.parseFloat(e);if(Number.isNaN(e-t))throw new i.Error("Couldn't parse float '"+e+"'"+this.location());return this.semicolon(),t}string(){const e=this.read();if(e.length<2)throw new i.Error("String is too short"+this.location());const t=e[0];if("'"!==t&&'"'!==t)throw new i.Error("String is not in quotes"+this.location());if(t!==e[e.length-1])throw new i.Error("String quotes do not match"+this.location());const s=e.substring(1,e.length-1);return this.semicolon(),s}boolean(){const e=this.read();switch(e){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new i.Error("Couldn't parse boolean '"+e+"'"+this.location())}bytes(){const e=this.string();let t=0,s=0;const n=e.length,o=new Uint8Array(n);for(;t=n)throw new i.Error("Unexpected end of bytes string"+this.location());switch(r=e.charCodeAt(t++),r){case 39:o[s++]=39;break;case 92:o[s++]=92;break;case 34:o[s++]=34;break;case 114:o[s++]=13;break;case 110:o[s++]=10;break;case 116:o[s++]=9;break;case 98:o[s++]=8;break;case 88:case 120:for(let r=0;r<2;r++){if(t>=n)throw new i.Error("Unexpected end of bytes string"+this.location());let r=e.charCodeAt(t++);if(r=r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r>=48&&r<=57?r-48:-1,-1===r)throw new i.Error("Unexpected hex digit '"+r+"' in bytes string"+this.location());o[s]=o[s]<<4|r}s++;break;default:if(r<48||r>57)throw new i.Error("Unexpected character '"+r+"' in bytes string"+this.location());t--;for(let r=0;r<3;r++){if(t>=n)throw new i.Error("Unexpected end of bytes string"+this.location());const r=e.charCodeAt(t++);if(r<48||r>57)throw new i.Error("Unexpected octal digit '"+r+"' in bytes string"+this.location());o[s]=o[s]<<3|r-48}s++}}}return o.slice(0,s)}enum(e){const t=this.read();if(!Object.prototype.hasOwnProperty.call(e,t)){const e=Number.parseInt(t,10);if(!Number.isNaN(t-e))return this.semicolon(),e;throw new i.Error("Couldn't parse enum '"+t+"'"+this.location())}return this.semicolon(),e[t]}any(e){if(this.match("[")){this.read();const t=this._position,s=this._text.indexOf("]",t);if(-1===s||s>=this.next)throw new i.Error("End of Any type_url not found"+this.location());return e.type_url=this._text.substring(t,s),this._position=s+1,e.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(e,t,s){let i,n;for(this.start();!this.end();)switch(this.tag()){case"key":i=t();break;case"value":n=s()}e[i]=n}array(e,t){if(this.first())for(;!this.last();)e.push(t()),this.next();else e.push(t())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const e=this.peek();","!==e?"]"!==e&&this.handle(e):this.read()}skip(){let e=this.peek();if("{"===e){const t=this._position,s=this._depth;for(this.start();!this.end()||s=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let e=this._text[this._position];if("["===e&&this._position+2="a"&&t<="z"||t>="A"&&t<="Z")for(e++;e="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"."===t||"/"===t)&&"]"===t)return this._token=this._text.substring(this._position,e),this._token}if("{"===e||"}"===e||":"===e||"["===e||","===e||"]"===e||";"===e)return this._token=e,this._token;let t=this._position+1;if(e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e||"$"===e){for(;t="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"+"===e||"-"===e);)t++;return this._token=this._text.substring(this._position,t),this._token}if(e>="0"&&e<="9"||"-"===e||"+"===e||"."===e){for(;t="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"+"===e||"-"===e||"."===e);)t++;return this._token=this._text.substring(this._position,t),this._token}if('"'===e||"'"===e){const s=e;for(;t>>0,this.hi=t>>>0}toLong(e){return i.Long?new i.Long(0|this.lo,0|this.hi,e):{low:0|this.lo,high:0|this.hi,unsigned:e}}toNumber(e){if(!e&&this.hi>>>31){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return e||(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}from(e){if("number"==typeof e)return i.LongBits.fromNumber(e);if("string"==typeof e||e instanceof String){if(!i.Long)return i.LongBits.fromNumber(parseInt(e,10));e=i.Long.fromString(e)}return e.low||e.high?new i.LongBits(e.low>>>0,e.high>>>0):i.LongBits.zero}hash(e){return e?i.LongBits.from(e).toHash():"\0\0\0\0\0\0\0\0"}},i.LongBits.zero=new i.LongBits(0,0),i.LongBits.zero.toNumber=function(){return 0},i.LongBits.zero.zzDecode=function(){return this},i.Error=class extends Error{constructor(e){super(e),this.name="Protocol Buffer Error",this.message=e}},"object"==typeof e.exports&&(e.exports.Reader=i.Reader,e.exports.TextReader=i.TextReader,e.exports.Error=i.Error,e.exports.Long=i.Long,e.exports.get=i.get)},499:e=>{var t=t||{};t.Archive=class{constructor(e){this._entries=[];const s=new t.Reader(e,0,e.length);for(;s.peek()&&(this._entries.push(new t.Entry(s)),!s.match(512,0)););}get entries(){return this._entries}},t.Entry=class{constructor(e){const s=e.bytes(512);e.skip(-512);let i=0;for(let e=0;e=148&&e<156?32:s[e];this._name=e.string(100),e.string(8),e.string(8),e.string(8);const n=parseInt(e.string(12).trim(),8);e.string(12);const o=parseInt(e.string(8).trim(),8);if(isNaN(o)||i!=o)throw new t.Error("Invalid tar archive.");e.string(1),e.string(100),e.bytes(255),this._data=e.bytes(n),e.bytes(n%512!=0?512-n%512:0)}get name(){return this._name}get data(){return this._data}},t.Reader=class{constructor(e){this._buffer=e,this._position=0,this._end=e.length}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new t.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}peek(){return this._positione==t)))&&(this._position+=e,!0)}bytes(e){const t=this._position;return this.skip(e),this._buffer.subarray(t,this._position)}string(e){const t=this.bytes(e);let s=0,i="";for(let n=0;n{var i=i||{},n=n||s(46506);i.Renderer=class{constructor(e,t){this._document=e,this._svgElement=t}render(e){const t=this.createElement("g");t.setAttribute("id","clusters"),t.setAttribute("class","clusters"),this._svgElement.appendChild(t);const s=this.createElement("g");s.setAttribute("id","edge-paths"),s.setAttribute("class","edge-paths"),this._svgElement.appendChild(s);const o=this.createElement("g");o.setAttribute("id","edge-labels"),o.setAttribute("class","edge-labels"),this._svgElement.appendChild(o);const r=this.createElement("g");r.setAttribute("id","nodes"),r.setAttribute("class","nodes"),this._svgElement.appendChild(r);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t),i=this.createElement("g");s.id&&i.setAttribute("id",s.id),i.setAttribute("class",Object.prototype.hasOwnProperty.call(s,"class")?"node "+s.class:"node"),i.style.opacity=0;const n=this.createElement("g");n.appendChild(s.label),i.appendChild(n),r.appendChild(i);const o=s.label.getBBox(),a=-o.width/2,h=-o.height/2;n.setAttribute("transform","translate("+a+","+h+")"),s.width=o.width,s.height=o.height,s.element=i}for(const t of e.edges()){const s=e.edge(t);if(s.label){const e=this.createElement("tspan");e.setAttribute("xml:space","preserve"),e.setAttribute("dy","1em"),e.setAttribute("x","1"),e.appendChild(this._document.createTextNode(s.label));const t=this.createElement("text");t.appendChild(e);const i=this.createElement("g");i.appendChild(t);const n=this.createElement("g");n.style.opacity=0,n.setAttribute("class","edge-label"),n.appendChild(i),o.appendChild(n);const r=i.getBBox(),a=-r.width/2,h=-r.height/2;i.setAttribute("transform","translate("+a+","+h+")"),s.width=r.width,s.height=r.height,s.labelElement=n}}n.layout(e);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);s.element.setAttribute("transform","translate("+s.x+","+s.y+")"),s.element.style.opacity=1,delete s.element}for(const t of e.edges()){const s=e.edge(t);s.labelElement&&(s.labelElement.setAttribute("transform","translate("+s.x+","+s.y+")"),s.labelElement.style.opacity=1,delete s.labelElement)}const a=this.createElement("defs");s.appendChild(a);const h=this.createElement("marker");h.setAttribute("id","arrowhead-vee"),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX",9),h.setAttribute("refY",5),h.setAttribute("markerUnits","strokeWidth"),h.setAttribute("markerWidth",8),h.setAttribute("markerHeight",6),h.setAttribute("orient","auto"),a.appendChild(h);const c=this.createElement("path");c.setAttribute("d","M 0 0 L 10 5 L 0 10 L 4 5 z"),c.style.setProperty("stroke-width",1),c.style.setProperty("stroke-dasharray","1,0"),h.appendChild(c);for(const t of e.edges()){const n=e.edge(t),o=i.Renderer._computeCurvePath(n,e.node(t.v),e.node(t.w)),r=this.createElement("path");r.setAttribute("class",Object.prototype.hasOwnProperty.call(n,"class")?"edge-path "+n.class:"edge-path"),r.setAttribute("d",o),r.setAttribute("marker-end","url(#arrowhead-vee)"),n.id&&r.setAttribute("id",n.id),s.appendChild(r)}for(const s of e.nodes())if(e.children(s).length>0){const i=e.node(s),n=this.createElement("g");n.setAttribute("class","cluster"),n.setAttribute("transform","translate("+i.x+","+i.y+")");const o=this.createElement("rect");o.setAttribute("x",-i.width/2),o.setAttribute("y",-i.height/2),o.setAttribute("width",i.width),o.setAttribute("height",i.height),i.rx&&o.setAttribute("rx",i.rx),i.ry&&o.setAttribute("ry",i.ry),n.appendChild(o),t.appendChild(n)}}createElement(e){return this._document.createElementNS("http://www.w3.org/2000/svg",e)}static _computeCurvePath(e,t,s){const n=e.points.slice(1,e.points.length-1);n.unshift(i.Renderer.intersectRect(t,n[0])),n.push(i.Renderer.intersectRect(s,n[n.length-1]));const a=new o,h=new r(a);for(let e=0;eMath.abs(n)*c?(o<0&&(c=-c),r=0===o?0:c*n/o,a=c):(n<0&&(h=-h),r=h,a=0===n?0:h*o/n),{x:s+r,y:i+a}}},i.NodeElement=class{constructor(e){this._document=e,this._blocks=[]}block(e){switch(this._block=null,e){case"header":this._block=new i.NodeElement.Header(this._document);break;case"list":this._block=new i.NodeElement.List(this._document)}return this._blocks.push(this._block),this._block}format(e){const t=this.createElement("g");e.appendChild(t);let s=0,n=0;const o=[];for(const e of this._blocks)o.push(n),e.layout(t),sthis._width&&(this._width=t)}}get width(){return this._width}get height(){return this._height}update(e,t,s,n,o){const r=s-this._width;let a,h,c;for(a=0;a{var i=s(32845),n=n||{};n.Archive=class{constructor(e){if(this._entries=[],e.length<4||80!=e[0]||75!=e[1])throw new n.Error("Invalid Zip archive.");let t=null;for(let s=e.length-4;s>=0;s--)if(80===e[s]&&75===e[s+1]&&5===e[s+2]&&6===e[s+3]){t=new n.Reader(e,s+4,e.length);break}if(!t)throw new n.Error("End of central directory not found.");for(t.skip(12),t.position=t.uint32();t.match([80,75,1,2]);)this._entries.push(new n.Entry(t))}get entries(){return this._entries}},n.Entry=class{constructor(e){if(e.uint16(),e.skip(2),this._flags=e.uint16(),1==(1&this._flags))throw new n.Error("Encrypted entries not supported.");this._compressionMethod=e.uint16(),e.uint32(),e.uint32(),this._compressedSize=e.uint32(),this._size=e.uint32();let t=e.uint16(),s=e.uint16();const i=e.uint16();e.uint16(),e.uint16(),e.uint32();const o=e.uint32();e.skip(t),e.skip(s),e.bytes(i);const r=e.position;if(e.position=o,!e.match([80,75,3,4]))throw new n.Error("Invalid local file header signature.");e.skip(22),t=e.uint16(),s=e.uint16();const a=e.bytes(t);this._name="";for(const e of a)this._name+=String.fromCharCode(e);e.skip(s),this._compressedData=e.bytes(this._compressedSize),e.position=r}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new n.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new n.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new n.Error("Invalid uncompressed size.");break;default:throw new n.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},n.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),n.HuffmanTree._offsets=n.HuffmanTree._offsets||new Uint16Array(16)}build(e,t,s){for(let e=0;e<16;++e)this.table[e]=0;for(let i=0;i>>1){case 0:this._inflateUncompressedBlock(t,o);break;case 1:this._inflateBlockData(t,o,n.HuffmanTree.staticLiteralLengthTree,n.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(t,r,a),this._inflateBlockData(t,o,r,a);break;default:throw new n.Error("Unknown block type.")}}while(0==(1&h));return o.merge()}_inflateUncompressedBlock(e,t){for(;e.data>8;)e.position--,e.data-=8;e.data=0;const s=e.uint16();if(s!==(65535&~e.uint16()))throw new n.Error("Invalid uncompressed block length.");const i=e.bytes(s);t.push(i),s>32768?(t.buffer.set(i.subarray(i.length-32768,i.length),0),t.position=32768):(t.reset(),t.buffer.set(i,t.position),t.position+=i.length)}_decodeTrees(e,t,s){const i=e.bits(5)+257,o=e.bits(5)+1,r=e.bits(4)+4;for(let e=0;e<19;e++)n.Inflater._lengths[e]=0;for(let t=0;t62464&&(t.position=r,t.push(new Uint8Array(o.subarray(a,r))),r=t.reset(),a=r);let h=e.symbol(s);if(256===h)return t.position=r,t.push(new Uint8Array(o.subarray(a,t.position))),void t.reset();if(h<256)o[r++]=h;else{h-=257;const t=e.bitsBase(n.Inflater._lengthBits[h],n.Inflater._lengthBase[h]),s=e.symbol(i);let a=r-e.bitsBase(n.Inflater._distanceBits[s],n.Inflater._distanceBase[s]);for(let e=0;e32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(e){this._blocks.push(e)}merge(){let e=0;for(const t of this._blocks)e+=t.length;const t=new Uint8Array(e);let s=0;for(const e of this._blocks)t.set(e,s),s+=e.length;return t}},n.BitReader=class{constructor(e){this.buffer=e,this.position=0,this.data=0,this.value=0}bits(e){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-e;return this.value>>>=e,this.data-=e,t}bitsBase(e,t){if(0==e)return t;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-e;return this.value>>>=e,this.data-=e,s+t}bytes(e){const t=this.buffer.subarray(this.position,this.position+e);return this.position+=e,t}uint16(){const e=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,e}symbol(e){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,i++,t+=o[i],s-=o[i]}while(s>=0);return this.value=n,this.data-=i,e.symbol[t+s]}},n.Reader=class{constructor(e,t,s){this._buffer=e,this._position=t,this._end=s}match(e){if(this._position+e.length<=this._end)for(let t=0;t=0?e:this._end+e}peek(){return this._positionthis._end)throw new n.Error("Data not available.");this._position+=e}bytes(e){if(this._position+e>this._end)throw new n.Error("Data not available.");e=void 0===e?this._end:e;const t=this._buffer.subarray(this._position,this._position+e);return this._position+=e,t}uint16(){if(this._position+2>this._end)throw new n.Error("Data not available.");const e=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,e}uint32(){return this.uint16()|this.uint16()<<16}},n.Error=class extends Error{constructor(e){super(e),this.name="Zip Error"}},"object"==typeof e.exports&&(e.exports.Archive=n.Archive,e.exports.Inflater=n.Inflater)},68138:(e,t,s)=>{const i=s(68513),n=s(24137),o=class{constructor(){window.eval=()=>{throw new Error("window.eval() not supported.")},this._document=window.document,this._meta={};for(const e of Array.from(this._document.getElementsByTagName("meta")))e.content&&(this._meta[e.name]=this._meta[e.name]||[],this._meta[e.name].push(e.content));this._type=this._meta.type?this._meta.type[0]:"Browser",this._version=this._meta.version?this._meta.version[0]:null,this._ready=!1}get document(){return this._document}get version(){return this._version}get type(){return this._type}initialize(e){return this._view=e,Promise.resolve()}start(){window.addEventListener("message",(e=>{const t=e.data;if(t){const e=t.type,s=t.data;switch(e){case"change-files":return this._changeFiles(s);case"zoom-in":return this._view.zoomIn();case"zoom-out":return this._view.zoomOut();case"select-item":return this._view.selectItem(s);case"toggle-Language":return this._view.toggleLanguage(s);case"isAlt":return this._view.changeAlt(s);case"zoom-reset":return this._view.resetZoom();case"toggle-attributes":return this._view.toggleAttributes(s);case"toggle-initializers":return this._view.toggleInitializers(s);case"toggle-names":return this._view.toggleNames(s);case"toggle-KeepData":return this._view.toggleKeepData(s);case"toggle-direction":return this._view.toggleDirection(s);case"toggle-theme":return this._view.toggleTheme(s);case"export":return this._view.export(`${document.title}.${s}`);case"change-graph":return this._view.changeGraph(s);case"change-allGraph":return this._view.changeAllGrap(s);case"change-select":return this._view.changeSelect(s);case"search":return this._view.find(s);case"select":return this._view.select(s);case"show-model-properties":return this._view.showModelProperties();case"show-node-documentation":return this._view.showNodeDocumentation(s);case"ready":return this._ready?this.status("ready"):void 0}}}),!1),this._ready=!0,this.status("ready")}message(e,t){window.parent&&window.parent.postMessage({type:e,data:t},"*")}status(e){this.message("status",e)}selectNodeId(e){this.message("nodeId",e)}selectItems(e){this.message("selectItem",e)}error(e,t){this.message("error",("Error"===e?"":e+" ")+t)}confirm(e,t){const s=confirm(e+" "+t);return s||this.message("cancel"),s}require(e){const t=this._url(e+".js");return window.__modules__=window.__modules__||{},window.__modules__[t]?Promise.resolve(window.__exports__[t]):new Promise(((s,i)=>{window.module={exports:{}};const n=document.createElement("script");n.setAttribute("id",e),n.setAttribute("type","text/javascript"),n.setAttribute("src",t),n.onload=()=>{const t=window.module.exports;delete window.module,window.__modules__[e]=t,s(t)},n.onerror=e=>{delete window.module,i(new Error("The script '"+e.target.src+"' failed to load."))},this.document.head.appendChild(n)}))}save(e,t,s,i){i(s+"."+t)}export(e,t){const s=this.document.createElement("a");s.download=e,s.href=URL.createObjectURL(t),this.document.body.appendChild(s),s.click(),this.document.body.removeChild(s)}request(e,t,s){const i=e?e+"/"+t:this._url(t);return this._request(i,null,s)}_changeFiles(e){if(console.log("files",e),e&&e?.length){if(console.log("files.length",e.length),!(e=Array.from(e)).find((e=>this._view.accept(e.name))))return void this.error("Error opening file.","Cannot open file "+e[0].name);this._open(e.find((e=>this._view.accept(e.name))),e)}}_request(e,t,s,i){return new Promise(((n,o)=>{const r=new XMLHttpRequest;s||(r.responseType="arraybuffer"),i&&(r.timeout=i);const a=t=>{const s=new Error("The web request failed with status code "+t+" at '"+e+"'.");return s.type="error",s.url=e,s};if(r.onload=()=>{200==r.status?"arraybuffer"==r.responseType?n(new Uint8Array(r.response)):n(r.responseText):o(a(r.status))},r.onerror=e=>{const t=a(r.status);t.type=e.type,o(t)},r.ontimeout=()=>{r.abort();const t=new Error("The web request timed out in '"+e+"'.");t.type="timeout",t.url=e,o(t)},r.open("GET",e,!0),t)for(const e of Object.keys(t))r.setRequestHeader(e,t[e]);r.send()}))}_url(e){let t=e;if(window&&window.location&&window.location.href){let s=window.location.href.split("?").shift();s.endsWith(".html")&&(s=s.split("/").slice(0,-1).join("/")),s.endsWith("/")&&(s=s.slice(0,-1)),t=s+"/"+e}return t}_open(e,t){this.status("loading");const s=new r(e,t);s.open().then((()=>this._view.open(s).then((e=>(this._view.actived&&this.status("rendered"),this.document.title=t[0].name,e))))).catch((e=>{this.error(e.name,e.message)}))}};if("undefined"==typeof TextDecoder&&(TextDecoder=function(e){this._encoding=e},TextDecoder.prototype.decode=function(e){let t="";const s=e.length;let i=0;switch(this._encoding){case"utf-8":for(;i>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=String.fromCharCode(s);break;case 12:case 13:{const n=e[i++];t+=String.fromCharCode((31&s)<<6|63&n);break}case 14:{const n=e[i++],o=e[i++];t+=String.fromCharCode((15&s)<<12|(63&n)<<6|(63&o)<<0);break}}}break;case"ascii":for(;i=55296&&n<=56319){if(r===t){i[s+=1]=239,i[s+=1]=191,i[s+=1]=189;break}if(o=e.charCodeAt(r),!(o>=56320&&o<=57343)){i[s+=1]=239,i[s+=1]=191,i[s+=1]=189;continue}if(n=1024*(n-55296)+o-56320+65536,r+=1,n>65535){i[s+=1]=240|n>>>18,i[s+=1]=128|n>>>12&63,i[s+=1]=128|n>>>6&63,i[s+=1]=128|63&n;continue}}n<=127?i[s+=1]=0|n:n<=2047?(i[s+=1]=192|n>>>6,i[s+=1]=128|63&n):(i[s+=1]=224|n>>>12,i[s+=1]=128|n>>>6&63,i[s+=1]=128|63&n)}return"undefined"!=typeof Uint8Array?new Uint8Array(i.buffer.slice(0,s+1)):i.length===s+1?i:i.slice(0,s+1)},TextEncoder.prototype.toString=function(){return"[object TextEncoder]"};try{Object.defineProperty(TextEncoder.prototype,"encoding",{get:function(){if(Object.prototype.isPrototypeOf.call(TextEncoder.prototype,this))return"utf-8";throw TypeError("Illegal invocation")}})}catch(e){TextEncoder.prototype.encoding="utf-8"}"undefined"!=typeof Symbol&&(TextEncoder.prototype[Symbol.toStringTag]="TextEncoder")}"undefined"==typeof URLSearchParams&&(URLSearchParams=function(e){const t=e=>e.replace(/[ +]/g,"%20").replace(/(%[a-f0-9]{2})+/gi,(e=>decodeURIComponent(e)));if(this._dict={},"string"==typeof e){const s=(e=0===e.indexOf("?")?e.substring(1):e).split("&");for(const e of s){const s=e.indexOf("="),i=t(s>-1?e.substring(0,s):e),n=s>-1?t(e.substring(s+1)):"";Object.prototype.hasOwnProperty.call(this._dict,i)||(this._dict[i]=[]),this._dict[i].push(n)}}},URLSearchParams.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this._dict,e)?this._dict[e][0]:null}),HTMLCanvasElement.prototype.toBlob||(HTMLCanvasElement.prototype.toBlob=function(e,t,s){setTimeout((()=>{const i=atob(this.toDataURL(t,s).split(",")[1]),n=i.length,o=new Uint8Array(n);for(let e=0;e{this._buffer=e}))}request(e,t){const s=this._blobs[e];return s?new Promise(((i,n)=>{const o=new FileReader;o.onload=e=>{i(t?e.target.result:new Uint8Array(e.target.result))},o.onerror=t=>{let s="";switch((t=t||window.event).target.error.code){case t.target.error.NOT_FOUND_ERR:s="File not found '"+e+"'.";break;case t.target.error.NOT_READABLE_ERR:s="File not readable '"+e+"'.";break;case t.target.error.SECURITY_ERR:s="File access denied '"+e+"'.";break;default:s="File read '"+t.target.error.code.toString()+"' error '"+e+"'."}n(new Error(s))},"utf-8"===t?o.readAsText(s,t):o.readAsArrayBuffer(s)})):Promise.reject(new Error("File not found '"+e+"'."))}}const a=function(e){let t=e.lastIndexOf("/");return e.substring(t+1,e.length)}(document.referrer);window.__view__="static_graph"===a||"x2paddle"===a?new n.View(new o):new i.View(new o)},42473:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>i});const i={leaf_nodes:[{name:"layer",schema:{category:"container"}},{name:"layerlist",schema:{category:"container"}},{name:"parameterlist",schema:{category:"container"}},{name:"layerdict",schema:{category:"container"}},{name:"conv1d",schema:{category:"conv"}},{name:"conv1dtranspose",schema:{category:"conv"}},{name:"conv2d",schema:{category:"conv"}},{name:"conv2dtranspose",schema:{category:"conv"}},{name:"conv3d",schema:{category:"conv"}},{name:"conv3dtranspose",schema:{category:"conv"}},{name:"adaptiveavgpool1d",schema:{category:"pool"}},{name:"adaptiveavgpool2d",schema:{category:"pool"}},{name:"adaptiveavgpool3d",schema:{category:"pool"}},{name:"adaptivemaxpool1d",schema:{category:"pool"}},{name:"adaptivemaxpool2d",schema:{category:"pool"}},{name:"adaptivemaxpool3d",schema:{category:"pool"}},{name:"avgpool1d",schema:{category:"pool"}},{name:"avgpool2d",schema:{category:"pool"}},{name:"avgpool3d",schema:{category:"pool"}},{name:"maxpool1d",schema:{category:"pool"}},{name:"maxpool2d",schema:{category:"pool"}},{name:"maxpool3d",schema:{category:"pool"}},{name:"maxunpool1d",schema:{category:"pool"}},{name:"maxunpool2d",schema:{category:"pool"}},{name:"maxunpool3d",schema:{category:"pool"}},{name:"pad1d",schema:{category:"pad"}},{name:"pad2d",schema:{category:"pad"}},{name:"pad3d",schema:{category:"pad"}},{name:"zeropad2d",schema:{category:"pad"}},{name:"celu",schema:{category:"activation"}},{name:"elu",schema:{category:"activation"}},{name:"gelu",schema:{category:"activation"}},{name:"hardshrink",schema:{category:"activation"}},{name:"hardsigmoid",schema:{category:"activation"}},{name:"hardswish",schema:{category:"activation"}},{name:"hardtanh",schema:{category:"activation"}},{name:"leakyrelu",schema:{category:"activation"}},{name:"logsigmoid",schema:{category:"activation"}},{name:"logsoftmax",schema:{category:"activation"}},{name:"maxout",schema:{category:"activation"}},{name:"prelu",schema:{category:"activation"}},{name:"relu",schema:{category:"activation"}},{name:"relu6",schema:{category:"activation"}},{name:"selu",schema:{category:"activation"}},{name:"sigmoid",schema:{category:"activation"}},{name:"silu",schema:{category:"activation"}},{name:"softmax",schema:{category:"activation"}},{name:"softplus",schema:{category:"activation"}},{name:"softshrink",schema:{category:"activation"}},{name:"softsign",schema:{category:"activation"}},{name:"swish",schema:{category:"activation"}},{name:"mish",schema:{category:"activation"}},{name:"tanh",schema:{category:"activation"}},{name:"tanhshrink",schema:{category:"activation"}},{name:"thresholdedrelu",schema:{category:"activation"}},{name:"batchnorm",schema:{category:"normalization"}},{name:"batchnorm1d",schema:{category:"normalization"}},{name:"batchnorm2d",schema:{category:"normalization"}},{name:"batchnorm3d",schema:{category:"normalization"}},{name:"groupnorm",schema:{category:"normalization"}},{name:"instancenorm1d",schema:{category:"normalization"}},{name:"instancenorm2d",schema:{category:"normalization"}},{name:"instancenorm3d",schema:{category:"normalization"}},{name:"layernorm",schema:{category:"normalization"}},{name:"localresponsenorm",schema:{category:"normalization"}},{name:"spectralnorm",schema:{category:"normalization"}},{name:"syncbatchnorm",schema:{category:"normalization"}},{name:"alphadropout",schema:{category:"normalization"}},{name:"dropout",schema:{category:"normalization"}},{name:"dropout2d",schema:{category:"normalization"}},{name:"dropout3d",schema:{category:"normalization"}},{name:"birnn",schema:{category:"sequence"}},{name:"gru",schema:{category:"sequence"}},{name:"grucell",schema:{category:"sequence"}},{name:"lstm",schema:{category:"sequence"}},{name:"lstmcell",schema:{category:"sequence"}},{name:"rnn",schema:{category:"sequence"}},{name:"rnncellbase",schema:{category:"sequence"}},{name:"simplernn",schema:{category:"sequence"}},{name:"simplernncell",schema:{category:"sequence"}},{name:"multiheadattention",schema:{category:"sequence"}},{name:"transformer",schema:{category:"sequence"}},{name:"transformerdecoder",schema:{category:"sequence"}},{name:"transformerdecoderlayer",schema:{category:"sequence"}},{name:"transformerencoder",schema:{category:"sequence"}},{name:"transformerencoderlayer",schema:{category:"sequence"}},{name:"linear",schema:{category:"sequence"}},{name:"embedding",schema:{category:"sequence"}},{name:"bceloss",schema:{category:"tensor"}},{name:"bcewithlogitsloss",schema:{category:"tensor"}},{name:"crossentropyloss",schema:{category:"tensor"}},{name:"ctcloss",schema:{category:"tensor"}},{name:"hsigmoidloss",schema:{category:"tensor"}},{name:"kldivloss",schema:{category:"tensor"}},{name:"l1loss",schema:{category:"tensor"}},{name:"marginrankingloss",schema:{category:"tensor"}},{name:"mseloss",schema:{category:"tensor"}},{name:"nllloss",schema:{category:"tensor"}},{name:"smoothl1loss",schema:{category:"tensor"}},{name:"pixelshuffle",schema:{category:"shape"}},{name:"upsample",schema:{category:"shape"}},{name:"upsamplingbilinear2d",schema:{category:"shape"}},{name:"upsamplingnearest2d",schema:{category:"shape"}},{name:"clipgradbyglobalnorm",schema:{category:"shape"}},{name:"clipgradbynorm",schema:{category:"shape"}},{name:"clipgradbyvalue",schema:{category:"shape"}},{name:"beamsearchdecoder",schema:{category:"shape"}},{name:"cosinesimilarity",schema:{category:"shape"}},{name:"dynamic_decode",schema:{category:"shape"}},{name:"flatten",schema:{category:"shape"}},{name:"pairwisedistance",schema:{category:"shape"}},{name:"identity",schema:{category:"shape"}},{name:"unfold",schema:{category:"shape"}},{name:"fold",schema:{category:"shape"}},{name:"conv2d_grad",schema:{category:"conv"}},{name:"conv2d_transpose_grad",schema:{category:"conv"}},{name:"depthwise_conv2d_transpose",schema:{category:"conv"}},{name:"depthwise_conv2d_transpose_grad",schema:{category:"conv"}},{name:"deformable_conv_grad",schema:{category:"conv"}},{name:"depthwise_conv2d",schema:{category:"conv"}},{name:"deformable_conv",schema:{category:"conv"}},{name:"conv2d_transpose",schema:{category:"conv"}},{name:"depthwise_conv2d_grad",schema:{category:"conv"}},{name:"pool2d",schema:{category:"pool"}},{name:"pool2d_grad",schema:{category:"pool"}},{name:"max_pool2d_with_index",schema:{category:"pool"}},{name:"max_pool2d_with_index_grad",schema:{category:"pool"}},{name:"pad3d_grad",schema:{category:"pad"}},{name:"relu6_grad",schema:{category:"activation"}},{name:"leaky_relu",schema:{category:"activation"}},{name:"leaky_relu_grad",schema:{category:"activation"}},{name:"hard_sigmoid",schema:{category:"activation"}},{name:"hard_sigmoid_grad",schema:{category:"activation"}},{name:"sigmoid_grad",schema:{category:"activation"}},{name:"batch_norm",schema:{category:"normalization"}},{name:"batch_norm_grad",schema:{category:"normalization"}},{name:"sync_batch_norm",schema:{category:"normalization"}},{name:"sync_batch_norm_grad",schema:{category:"normalization"}},{name:"norm_grad",schema:{category:"normalization"}},{name:"p_norm",schema:{category:"normalization"}},{name:"p_norm_grad",schema:{category:"normalization"}},{name:"group_norm_grad",schema:{category:"normalization"}},{name:"squared_l2_norm",schema:{category:"normalization"}},{name:"squared_l2_norm_grad",schema:{category:"normalization"}},{name:"group_norm",schema:{category:"normalization"}},{name:"norm",schema:{category:"normalization"}},{name:"rnn_grad",schema:{category:"sequence"}},{name:"sequence_mask",schema:{category:"sequence"}},{name:"one_hot",schema:{category:"sequence"}},{name:"one_hot_v2",schema:{category:"sequence"}},{name:"bce_loss",schema:{category:"tensor"}},{name:"bce_loss_grad",schema:{category:"tensor"}},{name:"huber_loss",schema:{category:"tensor"}},{name:"huber_loss_grad",schema:{category:"tensor"}},{name:"log_loss",schema:{category:"tensor"}},{name:"log_loss_grad",schema:{category:"tensor"}},{name:"smooth_l1_loss",schema:{category:"tensor"}},{name:"smooth_l1_loss_grad",schema:{category:"tensor"}},{name:"elementwise_add",schema:{category:"tensor"}},{name:"elementwise_add_grad",schema:{category:"tensor"}},{name:"cumsum",schema:{category:"tensor"}},{name:"clip",schema:{category:"tensor"}},{name:"clip_grad",schema:{category:"tensor"}},{name:"greater_equal",schema:{category:"tensor"}},{name:"greater_than",schema:{category:"tensor"}},{name:"less_equal",schema:{category:"tensor"}},{name:"logical_and",schema:{category:"tensor"}},{name:"logical_or",schema:{category:"tensor"}},{name:"momentum",schema:{category:"tensor"}},{name:"reduce_max",schema:{category:"tensor"}},{name:"reduce_mean",schema:{category:"tensor"}},{name:"reduce_prod",schema:{category:"tensor"}},{name:"seed",schema:{category:"tensor"}},{name:"sigmoid_cross_entropy_with_logits",schema:{category:"tensor"}},{name:"label_smooth",schema:{category:"tensor"}},{name:"where_index",schema:{category:"tensor"}},{name:"is_empty",schema:{category:"tensor"}},{name:"sigmoid_cross_entropy_with_logits_grad",schema:{category:"tensor"}},{name:"target_assign",schema:{category:"tensor"}},{name:"gradient_accumulator",schema:{category:"tensor"}},{name:"size",schema:{category:"tensor"}},{name:"where",schema:{category:"tensor"}},{name:"elementwise_pow_grad",schema:{category:"tensor"}},{name:"argsort",schema:{category:"tensor"}},{name:"argsort_grad",schema:{category:"tensor"}},{name:"rmsprop",schema:{category:"tensor"}},{name:"atan",schema:{category:"tensor"}},{name:"atan_grad",schema:{category:"tensor"}},{name:"flatten_contiguous_range",schema:{category:"tensor"}},{name:"crop",schema:{category:"tensor"}},{name:"eye",schema:{category:"tensor"}},{name:"matmul",schema:{category:"tensor"}},{name:"set_value",schema:{category:"tensor"}},{name:"exp",schema:{category:"tensor"}},{name:"exp_grad",schema:{category:"tensor"}},{name:"square_grad",schema:{category:"tensor"}},{name:"log_softmax",schema:{category:"tensor"}},{name:"log_softmax_grad",schema:{category:"tensor"}},{name:"matmul_grad",schema:{category:"tensor"}},{name:"assign_value",schema:{category:"tensor"}},{name:"top_k_v2",schema:{category:"tensor"}},{name:"arg_max",schema:{category:"tensor"}},{name:"cos",schema:{category:"tensor"}},{name:"sin",schema:{category:"tensor"}},{name:"index_sample",schema:{category:"shape"}},{name:"squeeze_grad",schema:{category:"shape"}},{name:"squeeze2_grad",schema:{category:"shape"}},{name:"stack_grad",schema:{category:"shape"}},{name:"tril_triu",schema:{category:"shape"}},{name:"unstack",schema:{category:"shape"}},{name:"unstack_grad",schema:{category:"shape"}},{name:"bilinear_interp_v2",schema:{category:"shape"}},{name:"bilinear_interp_v2_grad",schema:{category:"shape"}},{name:"nearest_interp_v2",schema:{category:"shape"}},{name:"nearest_interp_v2_grad",schema:{category:"shape"}},{name:"randperm",schema:{category:"shape"}},{name:"sampling_id",schema:{category:"shape"}},{name:"bipartite_match",schema:{category:"shape"}},{name:"box_coder",schema:{category:"shape"}},{name:"density_prior_box",schema:{category:"shape"}},{name:"distribute_fpn_proposals",schema:{category:"shape"}},{name:"generate_proposals_v2",schema:{category:"shape"}},{name:"meshgrid",schema:{category:"shape"}},{name:"mine_hard_examples",schema:{category:"shape"}},{name:"yolo_box",schema:{category:"shape"}},{name:"warpctc",schema:{category:"shape"}},{name:"warpctc_grad",schema:{category:"shape"}},{name:"iou_similarity",schema:{category:"shape"}},{name:"split",schema:{category:"shape"}},{name:"flatten2",schema:{category:"shape"}},{name:"flatten2_grad",schema:{category:"shape"}},{name:"masked_select_grad",schema:{category:"shape"}},{name:"strided_slice",schema:{category:"shape"}},{name:"prior_box",schema:{category:"shape"}},{name:"elementwise_max_grad",schema:{category:"shape"}},{name:"not_equal",schema:{category:"shape"}},{name:"strided_slice_grad",schema:{category:"shape"}},{name:"fill_any_like",schema:{category:"shape"}},{name:"hard_swish",schema:{category:"shape"}},{name:"hard_swish_grad",schema:{category:"shape"}},{name:"expand_v2",schema:{category:"shape"}},{name:"expand_v2_grad",schema:{category:"shape"}},{name:"flatten_contiguous_range_grad",schema:{category:"shape"}},{name:"gather_nd",schema:{category:"shape"}},{name:"gather_nd_grad",schema:{category:"shape"}},{name:"reciprocal",schema:{category:"shape"}},{name:"reciprocal_grad",schema:{category:"shape"}},{name:"index_select",schema:{category:"shape"}},{name:"roi_align",schema:{category:"shape"}},{name:"roi_align_grad",schema:{category:"shape"}},{name:"reduce_mean_grad",schema:{category:"shape"}},{name:"masked_select",schema:{category:"shape"}},{name:"index_select_grad",schema:{category:"shape"}},{name:"elementwise_min_grad",schema:{category:"shape"}},{name:"fill_constant_batch_size_like",schema:{category:"shape"}},{name:"unsqueeze2_grad",schema:{category:"shape"}},{name:"unique",schema:{category:"shape"}},{name:"expand_as_v2",schema:{category:"shape"}},{name:"tile",schema:{category:"shape"}},{name:"nearest_interp_grad",schema:{category:"shape"}}],non_leaf_nodes:[{name:"Layer",schema:{category:"container"}},{name:"LayerList",schema:{category:"container"}},{name:"ParameterList",schema:{category:"container"}},{name:"LayerDict",schema:{category:"container"}},{name:"Conv1D",schema:{category:"conv"}},{name:"Conv1DTranspose",schema:{category:"conv"}},{name:"Conv2D",schema:{category:"conv"}},{name:"Conv2DTranspose",schema:{category:"conv"}},{name:"Conv3D",schema:{category:"conv"}},{name:"Conv3DTranspose",schema:{category:"conv"}},{name:"AdaptiveAvgPool1D",schema:{category:"pool"}},{name:"AdaptiveAvgPool2D",schema:{category:"pool"}},{name:"AdaptiveAvgPool3D",schema:{category:"pool"}},{name:"AdaptiveMaxPool1D",schema:{category:"pool"}},{name:"AdaptiveMaxPool2D",schema:{category:"pool"}},{name:"AdaptiveMaxPool3D",schema:{category:"pool"}},{name:"AvgPool1D",schema:{category:"pool"}},{name:"AvgPool2D",schema:{category:"pool"}},{name:"AvgPool3D",schema:{category:"pool"}},{name:"MaxPool1D",schema:{category:"pool"}},{name:"MaxPool2D",schema:{category:"pool"}},{name:"MaxPool3D",schema:{category:"pool"}},{name:"MaxUnPool1D",schema:{category:"pool"}},{name:"MaxUnPool2D",schema:{category:"pool"}},{name:"MaxUnPool3D",schema:{category:"pool"}},{name:"Pad1D",schema:{category:"pad"}},{name:"Pad2D",schema:{category:"pad"}},{name:"Pad3D",schema:{category:"pad"}},{name:"ZeroPad2D",schema:{category:"pad"}},{name:"CELU",schema:{category:"activation"}},{name:"ELU",schema:{category:"activation"}},{name:"GELU",schema:{category:"activation"}},{name:"Hardshrink",schema:{category:"activation"}},{name:"Hardsigmoid",schema:{category:"activation"}},{name:"Hardswish",schema:{category:"activation"}},{name:"Hardtanh",schema:{category:"activation"}},{name:"LeakyReLU",schema:{category:"activation"}},{name:"LogSigmoid",schema:{category:"activation"}},{name:"LogSoftmax",schema:{category:"activation"}},{name:"Maxout",schema:{category:"activation"}},{name:"PReLU",schema:{category:"activation"}},{name:"ReLU",schema:{category:"activation"}},{name:"ReLU6",schema:{category:"activation"}},{name:"SELU",schema:{category:"activation"}},{name:"Sigmoid",schema:{category:"activation"}},{name:"Silu",schema:{category:"activation"}},{name:"Softmax",schema:{category:"activation"}},{name:"Softplus",schema:{category:"activation"}},{name:"Softshrink",schema:{category:"activation"}},{name:"Softsign",schema:{category:"activation"}},{name:"Swish",schema:{category:"activation"}},{name:"Mish",schema:{category:"activation"}},{name:"Tanh",schema:{category:"activation"}},{name:"Tanhshrink",schema:{category:"activation"}},{name:"ThresholdedReLU",schema:{category:"activation"}},{name:"BatchNorm",schema:{category:"normalization"}},{name:"BatchNorm1D",schema:{category:"normalization"}},{name:"BatchNorm2D",schema:{category:"normalization"}},{name:"BatchNorm3D",schema:{category:"normalization"}},{name:"GroupNorm",schema:{category:"normalization"}},{name:"InstanceNorm1D",schema:{category:"normalization"}},{name:"InstanceNorm2D",schema:{category:"normalization"}},{name:"InstanceNorm3D",schema:{category:"normalization"}},{name:"LayerNorm",schema:{category:"normalization"}},{name:"LocalResponseNorm",schema:{category:"normalization"}},{name:"SpectralNorm",schema:{category:"normalization"}},{name:"SyncBatchNorm",schema:{category:"normalization"}},{name:"AlphaDropout",schema:{category:"normalization"}},{name:"Dropout",schema:{category:"normalization"}},{name:"Dropout2D",schema:{category:"normalization"}},{name:"Dropout3D",schema:{category:"normalization"}},{name:"BiRNN",schema:{category:"sequence"}},{name:"GRU",schema:{category:"sequence"}},{name:"GRUCell",schema:{category:"sequence"}},{name:"LSTM",schema:{category:"sequence"}},{name:"LSTMCell",schema:{category:"sequence"}},{name:"RNN",schema:{category:"sequence"}},{name:"RNNCellBase",schema:{category:"sequence"}},{name:"SimpleRNN",schema:{category:"sequence"}},{name:"SimpleRNNCell",schema:{category:"sequence"}},{name:"MultiHeadAttention",schema:{category:"sequence"}},{name:"Transformer",schema:{category:"sequence"}},{name:"TransformerDecoder",schema:{category:"sequence"}},{name:"TransformerDecoderLayer",schema:{category:"sequence"}},{name:"TransformerEncoder",schema:{category:"sequence"}},{name:"TransformerEncoderLayer",schema:{category:"sequence"}},{name:"Linear",schema:{category:"sequence"}},{name:"Embedding",schema:{category:"sequence"}},{name:"BCELoss",schema:{category:"tensor"}},{name:"BCEWithLogitsLoss",schema:{category:"tensor"}},{name:"CrossEntropyLoss",schema:{category:"tensor"}},{name:"CTCLoss",schema:{category:"tensor"}},{name:"HSigmoidLoss",schema:{category:"tensor"}},{name:"KLDivLoss",schema:{category:"tensor"}},{name:"L1Loss",schema:{category:"tensor"}},{name:"MarginRankingLoss",schema:{category:"tensor"}},{name:"MSELoss",schema:{category:"tensor"}},{name:"NLLLoss",schema:{category:"tensor"}},{name:"SmoothL1Loss",schema:{category:"tensor"}},{name:"PixelShuffle",schema:{category:"shape"}},{name:"Upsample",schema:{category:"shape"}},{name:"UpsamplingBilinear2D",schema:{category:"shape"}},{name:"UpsamplingNearest2D",schema:{category:"shape"}},{name:"ClipGradByGlobalNorm",schema:{category:"shape"}},{name:"ClipGradByNorm",schema:{category:"shape"}},{name:"ClipGradByValue",schema:{category:"shape"}},{name:"BeamSearchDecoder",schema:{category:"shape"}},{name:"CosineSimilarity",schema:{category:"shape"}},{name:"dynamic_decode",schema:{category:"shape"}},{name:"Flatten",schema:{category:"shape"}},{name:"PairwiseDistance",schema:{category:"shape"}},{name:"Identity",schema:{category:"shape"}},{name:"Unfold",schema:{category:"shape"}},{name:"Fold",schema:{category:"shape"}}]}},74872:(e,t,s)=>{const i={},n={Long:s(27808)},o=s(13917);i.NodeSidebar=class{constructor(e,t){this._host=e,this._node=t,this._properties=[],this._attributes=[],this._inputs=[],this._outputs=[],t.type&&this._addProperty("type",new i.ValueTextView(this._host,t.type,{documentation:!!t.metadata})),t.name&&this._addProperty("name",new i.ValueTextView(this._host,t.name)),t.location&&this._addProperty("location",new i.ValueTextView(this._host,t.location)),t.domain&&this._addProperty("domain",new i.ValueTextView(this._host,t.domain)),t.description&&this._addProperty("description",new i.ValueTextView(this._host,t.description)),t.device&&this._addProperty("device",new i.ValueTextView(this._host,t.device));const s=t.attributes;if(s&&s.length>0){const e=t.attributes.slice();e.sort(((e,t)=>{const s=e.name.toUpperCase(),i=t.name.toUpperCase();return si?1:0}));for(const t of e)this._addAttribute(t.name,t)}const n=t.inputs;if(n&&n.length>0)for(const e of n)this._addInput(e.name,e);const o=t.outputs;if(o&&o.length>0)for(const e of o)this._addOutput(e.name,e)}render(){return{properties:this._properties,groups:[{name:"attributes",properties:this._attributes},{name:"inputs",properties:this._inputs},{name:"outputs",properties:this._outputs}]}}_addProperty(e,t){const s=new i.NameValueView(this._host,e,t);this._properties.push(s.render())}_addAttribute(e,t){const s=new i.NameValueView(this._host,e,new r(this._host,t));this._attributes.push(s.render())}_addInput(e,t){if(t.arguments.length>0){const s=new i.ParameterView(this._host,t),n=new i.NameValueView(this._host,e,s);this._inputs.push(n.render())}}_addOutput(e,t){if(t.arguments.length>0){const s=new i.ParameterView(this._host,t),n=new i.NameValueView(this._host,e,s);this._outputs.push(n.render())}}static formatAttributeValue(e,t,s){if("function"==typeof e)return e();if(e&&n.Long.isLong(e))return e.toString();if(Number.isNaN(e))return"NaN";switch(t){case"shape":return e.toString();case"shape[]":return e?e.map((e=>e.toString())).join(", "):"(null)";case"graph":return e.toString();case"graph[]":return e?e.map((e=>e.toString())).join(", "):"(null)";case"tensor":return e&&e.type&&e.type.shape&&e.type.shape.dimensions&&0==e.type.shape.dimensions.length?e.toString():"[...]"}if("string"==typeof e&&(!t||"string"!=t))return s?'"'+e+'"':e;if(Array.isArray(e)){if(0==e.length)return s?"[]":"";let t=!1;e.length>1e3&&(e=e.slice(0,1e3),t=!0);const o=e.map((e=>e&&n.Long.isLong(e)?e.toString():Number.isNaN(e)?"NaN":i.NodeSidebar.formatAttributeValue(e,null,!0)));return t&&o.push("…"),s?["[",o.join(", "),"]"].join(" "):o.join(", ")}if(null===e)return s?"null":"";if(void 0===e)return"undefined";if(e!==Object(e))return e.toString();const o=[],r=Object.keys(e).filter((e=>!e.startsWith("__")&&!e.endsWith("__")));if(1==r.length)o.push(i.NodeSidebar.formatAttributeValue(e[Object.keys(e)[0]],null,!0));else for(const t of r)o.push(t+": "+i.NodeSidebar.formatAttributeValue(e[t],null,!0));let a=e.__type__;if(!a&&e.constructor.name&&"Object"!==e.constructor.name&&(a=e.constructor.name),a)return a+(0==o.length?"()":["(",o.join(", "),")"].join(""));switch(o.length){case 0:return s?"()":"";case 1:return o[0];default:return s?["(",o.join(", "),")"].join(" "):o.join(", ")}}},i.NameValueView=class{constructor(e,t,s){this._host=e,this._name=t,this._value=s,this._element={name:t,values:s.render()}}get name(){return this._name}render(){return this._element}},i.ValueTextView=class{constructor(e,t,s){this._host=e,this._elements=[],this._elements.push(Object.assign({value:t},s))}render(){return this._elements}};class r{constructor(e,t){this._host=e,this._attribute=t,this._element={},t.type&&(this._element.children=this.renderChildren());let s=i.NodeSidebar.formatAttributeValue(this._attribute.value,this._attribute.type);s&&s.length>1e3&&(s=s.substring(0,1e3)+"…"),this._element.value=s||" "}render(){return[this._element]}renderChildren(){const e=[];this._host.document.createElement("div").className="sidebar-view-item-value-line-border";const t=this._attribute.type,s=this._attribute.value;"tensor"==t&&s&&s.type?e.push({name:"type",value:s.type.toString(),type:"code"}):e.push({name:"type",value:this._attribute.type,type:"code"});const i=this._attribute.description;if(i&&e.push({value:i}),"tensor"==this._attribute.type&&s){const t=s.state;e.push({value:t||s.toString(),type:"raw"})}return e}}i.ParameterView=class{constructor(e,t){this._list=t,this._elements=[],this._items=[];for(const s of t.arguments){const t=new i.ArgumentView(e,s);this._items.push(t),this._elements.push(t.render())}}render(){return this._elements}},i.ArgumentView=class{constructor(e,t){this._host=e,this._argument=t,this._element={};const s=t.initializer,i=t.quantization;(t.type||s||i)&&(this._element.children=this.renderChildren());let n=this._argument.name||"";if(this._hasId=!!n,s&&!this._hasId)this._element.name="kind",this._element.value=s.kind;else{if("string"!=typeof n)throw new Error("Invalid argument identifier '"+JSON.stringify(n)+"'.");n=n.split("\n").shift(),this._element.name="name",this._element.value=n||" "}}render(){return this._element}renderChildren(){const e=[];let t="?",s=null;this._argument.type&&(t=this._argument.type.toString(),s=this._argument.type.denotation||null),t&&e.push({name:"type",value:t,type:"code"}),s&&e.push({name:"denotation",value:s,type:"code"});const i=this._argument.description;i&&e.push({name:"description",value:i});const n=this._argument.quantization;n&&e.push({name:"quantization",value:n}),this._argument.location&&e.push({name:"location",value:this._argument.location});const o=this._argument.initializer;if(o){o.reference&&e.push({name:"reference",value:this._argument.reference});const t=o.state;let s="";try{s=t||o.toString()}catch(e){s=e.toString(),this._host.exception(e,!1)}e.push({value:s,type:"raw"})}return e}},i.ModelSidebar=class{constructor(e,t,s){this._host=e,this._model=t,this._properties=[],this._groups=[],this._model.format&&this._addProperty("format",new i.ValueTextView(this._host,this._model.format)),this._model.producer&&this._addProperty("producer",new i.ValueTextView(this._host,this._model.producer)),this._model.source&&this._addProperty("source",new i.ValueTextView(this._host,this._model.source)),this._model.name&&this._addProperty("name",new i.ValueTextView(this._host,this._model.name)),this._model.version&&this._addProperty("version",new i.ValueTextView(this._host,this._model.version)),this._model.description&&this._addProperty("description",new i.ValueTextView(this._host,this._model.description)),this._model.author&&this._addProperty("author",new i.ValueTextView(this._host,this._model.author)),this._model.company&&this._addProperty("company",new i.ValueTextView(this._host,this._model.company)),this._model.license&&this._addProperty("license",new i.ValueTextView(this._host,this._model.license)),this._model.domain&&this._addProperty("domain",new i.ValueTextView(this._host,this._model.domain)),this._model.imports&&this._addProperty("imports",new i.ValueTextView(this._host,this._model.imports)),this._model.runtime&&this._addProperty("runtime",new i.ValueTextView(this._host,this._model.runtime));const n=this._model.metadata;if(n)for(const e of n)this._addProperty(e.name,new i.ValueTextView(this._host,e.value));if(this._model&&this._addProperty("subgraph",new i.ValueTextView(this._host,s.name)),s){if(s.version&&this._addProperty("version",new i.ValueTextView(this._host,s.version)),s.type&&this._addProperty("type",new i.ValueTextView(this._host,s.type)),s.tags&&this._addProperty("tags",new i.ValueTextView(this._host,s.tags)),s.description&&this._addProperty("description",new i.ValueTextView(this._host,s.description)),s.inputs.length)for(const e of s.inputs)this._addGroupProperty("inputs",e.name,e);if(s.outputs.length)for(const e of s.outputs)this._addGroupProperty("outputs",e.name,e)}}render(){return{properties:this._properties,groups:this._groups}}_addGroupProperty(e,t,s){const i=this._groups.find((t=>t.name===e));i?i.properties.push(this._addArgument(t,s)):this._groups.push({name:e,properties:[this._addArgument(t,s)]})}_addProperty(e,t){const s=new i.NameValueView(this._host,e,t);this._properties.push(s.render())}_addArgument(e,t){const s=new i.ParameterView(this._host,t);return new i.NameValueView(this._host,e,s).render()}},i.DocumentationSidebar=class{constructor(e,t){this._host=e,this._metadata=t}render(){return i.DocumentationSidebar.formatDocumentation(this._metadata)}static formatDocumentation(e){if(e){if((e=JSON.parse(JSON.stringify(e))).summary&&(e.summary=o(e.summary)),e.description&&(e.description=o(e.description)),e.attributes)for(const t of e.attributes)t.description&&(t.description=o(t.description));if(e.inputs)for(const t of e.inputs)t.description&&(t.description=o(t.description));if(e.outputs)for(const t of e.outputs)t.description&&(t.description=o(t.description));if(e.references)for(const t of e.references)t&&(t.description=o(t.description));return e}return""}},i.FindSidebar=class{constructor(e,t,s){this._host=e,this._graphElement=t,this._graph=s}static selection(e,t){const s=[],i=e.id,n=t.getElementById("nodes");if(n){let e=n.firstChild;for(;e;)e.id==i&&s.push(e),e=e.nextSibling}const o=t.getElementById("clusters");if(o){let e=o.firstChild;for(;e;)e.id==i&&s.push(e),e=e.nextSibling}const r=t.getElementById("edge-paths");if(r){let e=r.firstChild;for(;e;)e.id===i&&s.push(e),e=e.nextSibling}let a=t.getElementById(i);if(a)for(;a.parentElement;)if(a=a.parentElement,a.id&&a.id.startsWith("node-")){s.push(a);break}return s.length>0?s:null}static selection2(e,t){const s=[],i=e.id,n=t.getElementById("nodes");if(n){let e=n.firstChild;for(;e;)e.id==i&&s.push(e),e=e.nextSibling}const o=t.getElementById("clusters");if(o){let e=o.firstChild;for(;e;)e.id==i&&s.push(e),e=e.nextSibling}const r=t.getElementById("edge-paths");if(r){let t=r.firstChild;for(;t;)t.id===i&&(e.fromnode&&t.getAttribute("fromnode")===e.fromnode&&s.push(t),e.tonode&&t.getAttribute("tonode")===e.tonode&&s.push(t)),t=t.nextSibling}let a=t.getElementById(i);if(a)for(;a.parentElement;)if(a=a.parentElement,a.id&&a.id.startsWith("node-")){s.push(a);break}return s.length>0?s:null}update(e){const t=e.toLowerCase(),s=new Set,i=new Set,n=[];for(const e of this._graph.nodes){const o=[];for(const s of e.inputs)for(const e of s.arguments)e.name&&-1!=e.name.toLowerCase().indexOf(t)&&!i.has(e.name)&&(e.initializer||(n.push({type:"input",name:e.name.split("\n").shift(),id:"edge-"+e.name}),i.add(e.name)));const r=e.name;console.log("name",e);const a=e.type;!s.has(r)&&r&&(-1!=r.toLowerCase().indexOf(t)||a&&-1!=a.toLowerCase().indexOf(t))&&(n.push({type:"node",name:r,id:"node-"+r}),s.add(r));for(const e of o)n.push({type:"initializer",name:e.name,id:"initializer-"+e.name})}for(const e of this._graph.nodes)for(const s of e.outputs)for(const e of s.arguments)e.name&&-1!=e.name.toLowerCase().indexOf(t)&&!i.has(e.name)&&(n.push({type:"output",name:e.name.split("\n").shift(),id:"edge-"+e.name}),i.add(e.name));return{text:e,result:n}}},"object"==typeof e.exports&&(e.exports.Sidebar=i.Sidebar,e.exports.ModelSidebar=i.ModelSidebar,e.exports.NodeSidebar=i.NodeSidebar,e.exports.DocumentationSidebar=i.DocumentationSidebar,e.exports.FindSidebar=i.FindSidebar)},74913:(e,t,s)=>{var i=i||{},n=n||s(46506);i.Renderer=class{constructor(e,t,s){this._document=e.document,this._svgElement=t,this._host=e,this._view=s}render(e){let t=null,s=null,o=null,r=null;t=this.createElement("g"),t.setAttribute("id","clusters"),t.setAttribute("class","clusters"),this._svgElement.appendChild(t),s=this.createElement("g"),s.setAttribute("id","edge-paths"),s.setAttribute("class","edge-paths"),this._svgElement.appendChild(s),o=this.createElement("g"),o.setAttribute("id","edge-labels"),o.setAttribute("class","edge-labels"),this._svgElement.appendChild(o),r=this.createElement("g"),r.setAttribute("id","nodes"),r.setAttribute("class","nodes"),this._svgElement.appendChild(r);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);if(this._view._nodes.hasOwnProperty(s.id)){r.appendChild(this._view._nodes[s.id]);const e=this._view._nodes[s.id].getBBox();s.width=e.width,s.height=e.height,s.element=this._view._nodes[s.id]}else{const e=this.createElement("g");s.id&&e.setAttribute("id",s.id),e.setAttribute("class",Object.prototype.hasOwnProperty.call(s,"class")?"node "+s.class:"node"),e.style.opacity=0;const t=this.createElement("g");t.appendChild(s.label),e.appendChild(t),r.appendChild(e);const i=s.label.getBBox(),n=-i.width/2,o=-i.height/2;t.setAttribute("transform","translate("+n+","+o+")"),s.width=i.width,s.height=i.height,s.element=e}}for(const t of e.edges()){const s=e.edge(t);if(s.label){const e=this.createElement("tspan");e.setAttribute("xml:space","preserve"),e.setAttribute("dy","1em"),e.setAttribute("x","1"),e.appendChild(this._document.createTextNode(s.label));const t=this.createElement("text");t.appendChild(e);const i=this.createElement("g");i.appendChild(t);const n=this.createElement("g");n.style.opacity=0,n.setAttribute("class","edge-label"),n.appendChild(i),o.appendChild(n);const r=i.getBBox(),a=-r.width/2,h=-r.height/2;i.setAttribute("transform","translate("+a+","+h+")"),s.width=r.width,s.height=r.height,s.labelElement=n}}n.layout(e);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);s.element.setAttribute("transform","translate("+s.x+","+s.y+")"),s.element.style.opacity=1,delete s.element}for(const t of e.edges()){const s=e.edge(t);s.labelElement&&(s.labelElement.setAttribute("transform","translate("+s.x+","+s.y+")"),s.labelElement.style.opacity=1,delete s.labelElement)}const a=this.createElement("defs");s.appendChild(a);const h=this.createElement("marker");h.setAttribute("id","arrowhead-vee"),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX",9),h.setAttribute("refY",5),h.setAttribute("markerUnits","strokeWidth"),h.setAttribute("markerWidth",8),h.setAttribute("markerHeight",6),h.setAttribute("orient","auto"),a.appendChild(h);const c=this.createElement("path");c.setAttribute("d","M 0 0 L 10 5 L 0 10 L 4 5 z"),c.style.setProperty("stroke-width",1),c.style.setProperty("stroke-dasharray","1,0"),h.appendChild(c);for(const t of e.edges()){const n=e.edge(t),o=i.Renderer._computeCurvePath(n,e.node(t.v),e.node(t.w)),r=this.createElement("path");r.setAttribute("class",Object.prototype.hasOwnProperty.call(n,"class")?"edge-path "+n.class:"edge-path"),r.setAttribute("d",o),r.setAttribute("marker-end","url(#arrowhead-vee)"),n.id&&r.setAttribute("id",n.id),n.fromnode&&r.setAttribute("fromnode",n.fromnode),n.tonode&&r.setAttribute("tonode",n.tonode),s.appendChild(r)}const l=[];for(const t of e.nodes())Number(t)||0===Number(t)||l.push(t);const m=l.sort(((e,t)=>e.split("/").length-t.split("/").length));for(const s of m)if(e.children(s).length>0){const n=e.node(s);if(this._view._clusters.hasOwnProperty(n.id)){const e=this._view._clusters.hasOwnProperty(n.id);e.setAttribute("transform","translate("+n.x+","+n.y+")"),e.firstChild.setAttribute("x",-n.width/2),e.firstChild.setAttribute("y",-n.height/2),e.firstChild.setAttribute("width",n.width+10),e.firstChild.setAttribute("height",n.height+10)}else{const e=this.createElement("g");e.setAttribute("class","cluster"),e.setAttribute("id",`node-${s}`),e.setAttribute("transform","translate("+n.x+","+n.y+")");const o=this.createElement("rect"),r=this.createElement("tspan"),a=this.createElement("circle"),h=this.createElement("tspan");a.setAttribute("r","6.5"),a.setAttribute("cx",n.width/2-20+7.5+10),a.setAttribute("cy",-n.height/2+5+7.5),h.setAttribute("x",n.width/2-15+9),h.setAttribute("y",-n.height/2+1.3),h.setAttribute("xml:space","preserve"),h.setAttribute("dy","1em"),h.setAttribute("font-size","16px"),h.setAttribute("class","button-text"),a.setAttribute("class","clusterButton"),r.setAttribute("xml:space","preserve"),r.setAttribute("dy","1em"),r.setAttribute("x",0),r.setAttribute("y",-n.height/2+5),r.setAttribute("text-anchor","middle");let c="";for(const e of this._host._view._allGraph.nodes)e.name===n.nodeId&&(c=e.show_name.split("/")[e.show_name.split("/").length-1]);r.appendChild(this._document.createTextNode(c)),h.appendChild(this._document.createTextNode("-"));const l=this.createElement("text");l.appendChild(r);const m=this.createElement("text");m.appendChild(h),o.setAttribute("class",n.classList.join(" ")),o.setAttribute("x",-n.width/2),o.setAttribute("y",-n.height/2),o.setAttribute("width",n.width+10),o.setAttribute("height",n.height+10);const d=this.createElement("path");d.setAttribute("class",["cluster","border"].join(" ")),d.setAttribute("d",i.NodeElement.roundedRect2(-n.width/2,-n.height/2,n.width+10,n.height+10,!0,!0,!0,!0)),e.addEventListener("click",(()=>{this._view.select({id:`node-${s}`,name:s,type:"node"})})),m.addEventListener("click",(()=>{this._host.selectNodeId({nodeId:n.nodeId,expand:n.expand,isKeepData:n.isKeepData}),this._host.selectItems({id:`node-${n.nodeId}`,name:n.nodeId,type:"node"})})),o.addEventListener("click",(()=>{if(this._view.isCtrl){for(const e of this._view._allGraph.nodes)if(e.name===n.nodeId){for(const t of this._view.non_graphMetadatas)t.name===e.type&&("zh"===this._view.Language?window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`):window.open(`https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/${t.name}_en.html`));return void this._view.showNodeProperties(e)}}else for(const e of this._view._allGraph.nodes)if(e.name===n.nodeId)return void this._view.showNodeProperties(e)})),n.rx&&o.setAttribute("rx",n.rx),n.ry&&o.setAttribute("ry",n.ry),e.appendChild(o),e.appendChild(l),e.appendChild(a),e.appendChild(m),e.appendChild(d),t.appendChild(e)}}}createElement(e){return this._document.createElementNS("http://www.w3.org/2000/svg",e)}static _computeCurvePath(e,t,s){const n=e.points.slice(1,e.points.length-1);n.unshift(i.Renderer.intersectRect(t,n[0])),n.push(i.Renderer.intersectRect(s,n[n.length-1]));const a=new o,h=new r(a);for(let e=0;eMath.abs(n)*c?(o<0&&(c=-c),r=0===o?0:c*n/o,a=c):(n<0&&(h=-h),r=h,a=0===n?0:h*o/n),{x:s+r,y:i+a}}},i.NodeElement=class{constructor(e){this._document=e,this._blocks=[]}block(e){switch(this._block=null,e){case"header":this._block=new i.NodeElement.Header(this._document);break;case"list":this._block=new i.NodeElement.List(this._document)}return this._blocks.push(this._block),this._block}format(e){const t=this.createElement("g");e.appendChild(t);let s=0,n=0;const o=[];for(const e of this._blocks)o.push(n),e.layout(t),sthis._width&&(this._width=t)}}get width(){return this._width}get height(){return this._height}update(e,t,s,n,o){const r=s-this._width;let a,h,c;for(a=0;a{const i=s(71681),n=s(63332),o=s(499),r=s(81600),a=s(71462),h=s(46506),c=s(74913),l=s(74872),m={},d=s(42473),{style:p}=s(71462);m.View=class{constructor(e){this._host=e,this._host.initialize(this).then((()=>{this.typeLayer={},this.Language="zh",this.graphMetadatas=[],this.non_graphMetadatas=[],this.isCtrl=!1,this._clusters={},this._nodeName={},this._nodes={},this._model=null,this._selection=[],this._selectItem=null,this._host.start(),this._showAttributes=!1,this._showInitializers=!0,this._showNames=!1,this._KeepData=!1,this._showHorizontal=!1,this._modelFactoryService=new m.ModelFactoryService(this._host),this._graphNodes={}})).catch((e=>{this.error(e.message,e)}))}cut(){this._host.document.execCommand("cut")}copy(){this._host.document.execCommand("copy")}paste(){this._host.document.execCommand("paste")}selectAll(){this._host.document.execCommand("selectall")}find(e){if(this._activeGraph){this.clearSelection();const t=document.getElementById("canvas");if(this._allGraph){const s=new l.FindSidebar(this._host,t,this._allGraph);this._host.message("search",s.update(e))}else{const s=new l.FindSidebar(this._host,t,this._activeGraph);this._host.message("search",s.update(e))}}}toggleAttributes(e){(null==e||e^this._showAttributes)&&(this._showAttributes=null==e?!this._showAttributes:e,this._nodes={},this._clusters={},this._reload())}get showAttributes(){return this._showAttributes}toggleInitializers(e){(null==e||e^this._showInitializers)&&(this._showInitializers=null==e?!this._showInitializers:e,this._nodes={},this._clusters={},this._reload())}get showInitializers(){return this._showInitializers}toggleNames(e){(null==e||e^this._showNames)&&(this._showNames=null==e?!this._showNames:e,this._nodes={},this._clusters={},this._reload())}toggleKeepData(e){(null==e||e^this._KeepData)&&(this._KeepData=null==e?!this._KeepData:e)}toggleLanguage(e){this.Language=e}get showNames(){return this._showNames}get KeepData(){return this._KeepData}toggleDirection(e){(null==e||e^this._showHorizontal)&&(this._showHorizontal=null==e?!this._showHorizontal:e,this._reload())}get showHorizontal(){return this._showHorizontal}toggleTheme(e){this._host.document.body.className=e}_reload(){this._host.status("loading"),this._model&&this._activeGraph&&this._updateGraph2(this._model,this._activeGraph).catch((e=>{e&&this.error("Graph update failed.",e)}))}_timeout(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}zoomIn(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),1.2)}zoomOut(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),.8)}selectItem(e){this._selectItem=e}resetZoom(){this._zoom&&this._zoom.scaleTo(a.select(this._host.document.getElementById("canvas")),1)}select(e){if(this.clearSelection(),"node"===e.type)for(const t of this._allGraph.nodes)if(t.name===e.name){this.showNodeProperties(t);break}const t=document.getElementById("canvas"),s=l.FindSidebar.selection(e,t);if(s&&s.length>0){const e=this._host.document.getElementById("canvas"),t=e.getBoundingClientRect();let i=0,n=0;for(const e of s){e.classList.add("select"),this._selection.push(e);const t=e.transform.baseVal.consolidate(),s=e.getBBox(),o=t?t.matrix.e:s.x+s.width/2,r=t?t.matrix.f:s.y+s.height/2;i+=o,n+=r}i/=s.length,n/=s.length,this._zoom.transform(a.select(e),a.zoomIdentity.translate(t.width/2-i,t.height/2-n))}}select2(e){const t=document.getElementById("canvas"),s=l.FindSidebar.selection2(e,t);if(s&&s.length>0)for(const e of s)this._selection.push(e),e.classList.add("select")}clearSelection(){for(;this._selection.length>0;)this._selection.pop().classList.remove("select")}error(e,t){this._host.error(e,t.toString())}accept(e){return this._modelFactoryService.accept(e)}open(e){return this._timeout(2).then((()=>this._modelFactoryService.open(e).then((e=>this._timeout(20).then((()=>{console.log("model.graphs.length",e.graphs.length);const t=e.graphs.length>0?e.graphs[0]:null;return this._host.message("opened",{graphs:e.graphs.map((e=>e.name||"")),selected:t&&(t.name||"")}),this._updateGraph2(t)}))))))}changeAlt(e){this.isCtrl=e,console.log("isCtrl",this.isCtrl)}keydown(){this._host.document.onkeydown=e=>{"MetaLeft"!==e.code&&"MetaRight"!==e.code&&"ControlLeft"!==e.code&&"AltLeft"!==e.code&&"AltRight"!==e.code||(this.isCtrl=!0)},this._host.document.onkeyup=e=>{"MetaLeft"!==e.code&&"MetaRight"!==e.code&&"ControlLeft"!==e.code&&"AltLeft"!==e.code&&"AltRight"!==e.code||(this.isCtrl=!1)}}changeGraph(e){this._updateActiveGraph(e)}changeAllGrap(e){this._allGraph=e;for(const t of e.nodes)this._nodeName[t.name]=t}changeSelect(e){this._selectItem=e}_updateActiveGraph(e){e&&(this._host.status("loading"),this._timeout(200).then((()=>this._updateGraph(e).catch((e=>{e&&this.error("Graph update failed.",e)})))))}_updateGraph(e){return this._timeout(100).then((()=>e&&e!=this._activeGraph&&e.nodes.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?")?null:this.renderGraph(e,e).then((()=>(this._model=e,this._activeGraph=e,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{this._host.status("rendered")})).finally((()=>{throw e}))))))}_updateGraph2(e){return this._timeout(100).then((()=>{if(e&&e!=this._activeGraph){this._selectItem=null;const t=e.nodes;if(console.log("graphs",e),console.log("nodes.length",t),t.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?"))return null}return this.renderGraph(e,e).then((()=>(this._model=e,this._activeGraph=e,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{this._host.status("rendered")})).finally((()=>{throw e}))))}))}jumpRoute(e){if(e.is_leaf){if(this.isCtrl)for(const t of this._allGraph.nodes)if(t.name===e.name)for(const t of this.non_graphMetadatas)t.name.toLowerCase()===e.type&&("zh"===this.Language?window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`):window.open(`https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/${t.name}_en.html`))}else if(this.isCtrl)for(const t of this._allGraph.nodes)if(t.name===e.name)for(const t of this.non_graphMetadatas)t.name===e.type&&window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`)}renderGraph(e,t){try{this.keydown(),this.graphMetadatas=d.default.leaf_nodes,this.non_graphMetadatas=d.default.non_leaf_nodes;const s={};for(const e of d.default.non_leaf_nodes)s[e.name]=!0;this.typeLayer=s;const i=this._host.document.getElementById("canvas");for(;i.lastChild;)i.removeChild(i.lastChild);if(t){this._zoom=null,i.style.position="absolute",i.style.margin="0";const s=!0,n={nodesep:65,ranksep:60};this._showHorizontal&&(n.rankdir="LR");const o=new h.graphlib.Graph({compound:s});o.setGraph(n),o.setDefaultEdgeLabel((()=>({})));let r=0;const m={},p={},g={};let _=(new Date).getTime(),f=t.nodes;if(f.length>1500&&(n.ranker="longest-path"),s)for(const e of f){let t=e.name.split("/");for(t.pop(),console.log("path.length",t.length);t.length>0;){const e=t.join("/");t.pop(),e&&(g[e]=t.join("/"))}}for(const t of f){let n=null;document.getElementById(`node-${t.name}`)||(n=new c.NodeElement(this._host.document));const a=(t,s,i)=>{if(!document.getElementById(`node-${s.name}`)){const i=t.block("header"),n=["node-item-type"],o=s.type;if(s.is_leaf)for(const e of this.graphMetadatas)s.type===e.name&&e.schema.category&&n.push("node-item-type-"+e.schema.category.toLowerCase());else for(const e of this.non_graphMetadatas)s.type===e.name&&e.schema.category&&n.push("node-item-type-"+e.schema.category.toLowerCase());if("string"!=typeof o||!o.split)throw new u("Unknown node type '"+JSON.stringify(o)+"' in '"+e.format+"'.");const r=s.name.split("/")[s.name.split("/").length-1],a=this.showNames&&s.name?r:o.split(".").pop(),h=this.showNames&&s.name?o:r;i.add(null,n,a,h,(()=>{this.jumpRoute(s),this.showNodeProperties(s),this.select({id:`node-${s.name}`,name:s.name,type:"node"});const e=s.inputs;for(const t of e)for(const e of t.arguments)""==e.name||e.initializer||this.select2({id:`edge-${e.name}`,name:e.name,type:"input",tonode:s.name});let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)""!=t.name&&this.select2({id:`edge-${t.name}`,name:t.name,type:"input",fromnode:s.name})}));const c=["node-item-buttons"];s.is_leaf||i.add(null,c,"+",null,(()=>{this._host.selectNodeId({nodeId:s.name,expand:!0}),this._host.selectItems({id:`node-${s.name}`,name:s.name,type:"node"})}));const m=[];let d=!1;if(this._showInitializers)for(const e of s.inputs)e.visible&&1==e.arguments.length&&null!=e.arguments[0].initializer&&m.push(e),(!e.visible||e.arguments.length>1)&&e.arguments.some((e=>null!=e.initializer))&&(d=!0);let p=[];const g=s.attributes;if(this.showAttributes&&g&&(p=g.filter((e=>e.visible)).slice(),p.sort(((e,t)=>{const s=e.name.toUpperCase(),i=t.name.toUpperCase();return si?1:0}))),m.length>0||d||p.length>0){const e=t.block("list");e.handler=()=>{this.jumpRoute(s),this.showNodeProperties(s),this.select({id:`node-${s.name}`,name:s.name,type:"node"});const e=s.inputs;for(const t of e)for(const e of t.arguments)""==e.name||e.initializer||this.select2({id:`edge-${e.name}`,name:e.name,type:"input",tonode:s.name});let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)""!=t.name&&this.select2({id:`edge-${t.name}`,name:t.name,type:"input",fromnode:s.name})};for(const t of m){const s=t.arguments[0],i=s.type;let n="",o="";i&&i.shape&&i.shape.dimensions&&Object.prototype.hasOwnProperty.call(i.shape.dimensions,"length")&&(n="〈"+i.shape.dimensions.map((e=>e||"?")).join("×")+"〉",0==i.shape.dimensions.length&&s.initializer&&!s.initializer.state&&(n=s.initializer.toString(),n&&n.length>10&&(n=n.substring(0,10)+"…"),o=" = ")),e.add("initializer-"+s.name,t.name,n,i?i.toString():"",o)}d&&e.add(null,"〈…〉","",null,"");for(const t of p)if(t.visible){let s=l.NodeSidebar.formatAttributeValue(t.value,t.type);s&&s.length>25&&(s=s.substring(0,25)+"…"),e.add(null,t.name,s,t.type," = ")}}}if(i){const e=s.inputs;for(const t of e)for(const e of t.arguments)if(""!=e.name&&!e.initializer){let i=m[e.name];i||(i={from:null,to:[]},m[e.name]=i),i.to.push({node:r,name:t.name,nodename:s.name})}let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)if(""!=t.name){let i=m[t.name];i||(i={from:null,to:[]},m[t.name]=i),i.from={node:r,name:e.name,type:t.type,nodename:s.name}}}if(s.chain&&s.chain.length>0)for(const e of s.chain)a(t,e,!1);s.inner&&a(t,s.inner,!1)};if(a(n,t,!0),t.controlDependencies&&t.controlDependencies.length>0)for(const e of t.controlDependencies){let s=m[e];s||(s={from:null,to:[]},m[e]=s),s.to.push({node:r,name:e,controlDependency:!0,nodename:t.name})}const h=t.name;document.getElementById(`node-${t.name}`)?o.setNode(r,{label:"node-"+h,id:"node-"+h}):h?o.setNode(r,{label:n.format(i),id:"node-"+h}):(o.setNode(r,{label:n.format(i),id:"node-"+_.toString()}),_++);const f=this._KeepData,y=(e,t)=>{const s=d.default.non_leaf_nodes,i=["clusterGroup"],n=t.show_name.split("/")[t.show_name.split("/").length-1];if(this._nodeName[e])for(const t of s)if(this._nodeName[e].type===t.name){i.push(`clusterGroup-${t.schema.category.toLowerCase()}`);break}let r=["clusterGroup"];if(i.length>1&&(r=["clusterGroup",i[1]]),!p[e]){o.setNode(e,{rx:10,ry:10,nodeId:e,showName:n,expand:!1,classList:r,isKeepData:f}),p[e]=!0;const s=g[e];s&&(y(s,t),o.setParent(e,s))}};if(s){let e=t.name.split("/");e.pop();let s=e.join("/");if(s&&s.length>0){if(!Object.prototype.hasOwnProperty.call(g,s)){const e=s.lastIndexOf("/");-1!=e?(s=s.substring(0,e),Object.prototype.hasOwnProperty.call(g,s)||(s=null)):s=null}s&&(y(s,t),o.setParent(r,s))}}this._graphNodes[t.name]=n,r++}for(const e of t.inputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.from={node:r,type:t.type}}const t=e.arguments.map((e=>e.type||"")).join("\n");let s=e.name||"";s.length>16&&(s=s.split("/").pop());const n=new c.NodeElement(this._host.document);n.block("header").add(null,["graph-item-input"],s,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:n.format(i),class:"graph-input"})}for(const e of t.outputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.to.push({node:r})}const t=e.arguments.map((e=>e.type||"")).join("\n");let s=e.name||"";s.length>16&&(s=s.split("/").pop());const n=new c.NodeElement(this._host.document);n.block("header").add(null,["graph-item-output"],s,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:n.format(i)})}for(const e of Object.keys(m)){const t=m[e];if(null!=t.from)for(const s of t.to){let i="";const n=t.from.type;n&&n.shape&&n.shape.dimensions&&n.shape.dimensions.length>0&&(i=n.shape.dimensions.join("×")),this._showNames&&(i=e.split("\n").shift()),s.controlDependency?o.setEdge(t.from.node,s.node,{label:i,id:"edge-"+e,arrowhead:"vee",class:"edge-path-control-dependency",fromnode:t.from.nodename,tonode:s.nodename}):o.setEdge(t.from.node,s.node,{label:i,id:"edge-"+e,arrowhead:"vee",fromnode:t.from.nodename,tonode:s.nodename})}}const y=this._host.document.createElementNS("http://www.w3.org/2000/svg","rect");y.setAttribute("id","background"),y.setAttribute("width","100%"),y.setAttribute("height","100%"),y.setAttribute("fill","none"),y.setAttribute("pointer-events","all"),i.appendChild(y);const b=this._host.document.createElementNS("http://www.w3.org/2000/svg","g");b.setAttribute("id","origin"),i.appendChild(b);let w=null;return w=a.select(i),y.addEventListener("click",(()=>{this.clearSelection()})),this._zoom=a.zoom(),this._zoom(w),this._zoom.scaleExtent([.01,2]),this._zoom.on("zoom",(()=>{b.setAttribute("transform",a.event.transform.toString())})),this._zoom.transform(w,a.zoomIdentity),this._timeout(200).then((()=>{new c.Renderer(this._host,b,this).render(o);for(const e of document.getElementById("clusters").children)this._clusters[e.getAttribute("id")]=e;for(const e of document.getElementById("nodes").children)this._nodes[e.getAttribute("id")]=e;const e=i.getElementsByClassName("graph-input"),t=i.getBoundingClientRect();if(e&&e.length>0)if(this._selectItem)this.select(this._selectItem);else{const s=[],i=[];for(let t=0;te==i[0]))&&(n=s.reduce(((e,t)=>e+t))/s.length);const r=t.width/(this._showHorizontal?4:2)-n,h=t.height/(this._showHorizontal?2:4)-o;this._zoom.transform(w,a.zoomIdentity.translate(r,h))}else this._selectItem?this.select(this._selectItem):this._zoom.transform(w,a.zoomIdentity.translate((t.width-o.graph().width)/2,(t.height-o.graph().height)/2))}))}return Promise.resolve()}catch(e){return Promise.reject(e)}}applyStyleSheet(e,t){let s=[];for(let e=0;e{const s=Math.max(c,l),i=2*s>24e3?24e3/s:2,n=this._host.document.createElement("canvas");n.width=Math.ceil(c*i),n.height=Math.ceil(l*i);const o=n.getContext("2d");o.scale(i,i),o.drawImage(t,0,0),this._host.document.body.removeChild(t),n.toBlob((t=>{if(t)this._host.export(e,t);else{const e=new Error;e.name="Error exporting image.",e.message="Image may be too large to render as PNG.",this._host.exception(e,!1),this._host.error(e.name,e.message)}}),"image/png")},t.src="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(m))),this._host.document.body.insertBefore(t,this._host.document.body.firstChild)}}}showModelProperties(){if(this._model){const e=new l.ModelSidebar(this._host,this._model,this._activeGraph);this._host.message("show-model-properties",e.render())}}showNodeProperties(e){if(e){const t=new l.NodeSidebar(this._host,e);this._host.message("show-node-properties",{...t.render(),metadata:e.metadata})}}showNodeDocumentation(e){const t=e.metadata;if(t){const e=new l.DocumentationSidebar(this._host,t);this._host.message("show-node-documentation",e.render())}}};class u extends Error{constructor(e,t){super(e),this.name="Error loading model.",this.telemetry=t}}class g{constructor(e){this._context=e,this._tags=new Map,this._entries=new Map}request(e,t){return this._context.request(e,t)}get identifier(){return this._context.identifier}get buffer(){return this._context.buffer}get text(){return this._text||(this._text=new TextDecoder("utf-8").decode(this.buffer)),this._text}entries(e){let t=this._entries.get(e);if(!t){t=[];try{const s=this.buffer;switch(e){case"zip":s&&s.length>2&&80==s[0]&&75==s[1]&&(t=new i.Archive(s).entries);break;case"tar":if(s.length>=512){let e=0;for(let t=0;t<512;t++)e+=t>=148&&t<156?32:s[t];let i="";for(let e=148;e<156&&0!==s[e];e++)i+=String.fromCharCode(s[e]);i=parseInt(i,8),isNaN(i)||e!=i||(t=new o.Archive(s).entries)}}}catch(e){t=[]}this._entries.set(e,t)}return t}tags(e){let t=this._tags.get(e);if(!t){t=new Map;try{switch(e){case"pbtxt":{const e=this.buffer,s=e.length;if(!(s>=3&&239===e[0]&&187===e[1]&&191===e[2]||s>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]||s>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]||s>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3]||s>=2&&254===e[0]&&255===e[1]||s>=2&&255===e[0]&&254===e[1])&&e.subarray(0,Math.min(1024,s)).some((e=>e<7||e>14&&e<32)))break;const i=r.TextReader.create(this.text);for(i.start(!1);!i.end(!1);){const e=i.tag();t.set(e,!0),i.skip()}break}case"pb":{const e=new Set([0,1,2,3,5]),s=r.Reader.create(this.buffer),i=s.next();for(;s.pos>>3,7&i),!e.has(7&i)){t=new Map;break}try{s.skipType(7&i)}catch(e){t=new Map;break}}break}}}catch(e){t=new Map}this._tags.set(e,t)}return t}}class _{constructor(e,t,s,i){if(this._entries={},e)for(const i of e)if(i.name.startsWith(t)){const e=i.name.substring(t.length);s.length>0&&s.indexOf("/")<0&&(this._entries[e]=i)}this._identifier=s.substring(t.length),this._buffer=i}request(e,t){const s=this._entries[e];if(!s)return Promise.reject(new Error("File not found."));const i=t?new TextDecoder(t).decode(s.data):s.data;return Promise.resolve(i)}get identifier(){return this._identifier}get buffer(){return this._buffer}}class f extends Error{constructor(e){super(e),this.name="Error loading archive."}}m.ModelFactoryService=class{constructor(e){this._host=e,this._extensions=[],this.register("./onnx",[".onnx",".pb",".pbtxt",".prototxt"]),this.register("./mxnet",[".mar",".model",".json",".params"]),this.register("./keras",[".h5",".hd5",".hdf5",".keras",".json",".model",".pb",".pth"]),this.register("./coreml",[".mlmodel"]),this.register("./caffe",[".caffemodel",".pbtxt",".prototxt",".pt"]),this.register("./caffe2",[".pb",".pbtxt",".prototxt"]),this.register("./pytorch",[".pt",".pth",".pt1",".pkl",".h5",".t7",".model",".dms",".tar",".ckpt",".bin",".pb",".zip"]),this.register("./torch",[".t7"]),this.register("./tflite",[".tflite",".lite",".tfl",".bin",".pb",".tmfile",".h5",".model",".json"]),this.register("./tf",[".pb",".meta",".pbtxt",".prototxt",".json",".index",".ckpt"]),this.register("./mediapipe",[".pbtxt"]),this.register("./uff",[".uff",".pb",".trt",".pbtxt",".uff.txt"]),this.register("./sklearn",[".pkl",".pickle",".joblib",".model",".meta",".pb",".pt",".h5"]),this.register("./cntk",[".model",".cntk",".cmf",".dnn"]),this.register("./paddle",[".paddle",".pdmodel","__model__"]),this.register("./armnn",[".armnn"]),this.register("./bigdl",[".model",".bigdl"]),this.register("./darknet",[".cfg",".model"]),this.register("./mnn",[".mnn"]),this.register("./ncnn",[".param",".bin",".cfg.ncnn",".weights.ncnn"]),this.register("./tnn",[".tnnproto",".tnnmodel"]),this.register("./tengine",[".tmfile"]),this.register("./barracuda",[".nn"]),this.register("./openvino",[".xml",".bin"]),this.register("./flux",[".bson"]),this.register("./npz",[".npz",".h5",".hd5",".hdf5"]),this.register("./dl4j",[".zip"]),this.register("./mlnet",[".zip"])}register(e,t){for(const s of t)this._extensions.push({extension:s,id:e})}open(e){return this._openSignature(e).then((e=>this._openArchive(e).then((e=>{const t=(e=new g(e)).identifier,s=t.split(".").pop().toLowerCase(),i=this._filter(e);if(0==i.length)throw new u("Unsupported file extension '."+s+"'.");const n=[];let o=!1;const r=()=>{if(i.length>0){const t=i.shift();return this._host.require(t).then((s=>{if(!s.ModelFactory)throw new u("Failed to load module '"+t+"'.");const i=new s.ModelFactory;return i.match(e)?(o++,i.open(e,this._host).then((e=>e)).catch((e=>(n.push(e),r())))):r()}))}{if(o){if(1==n.length)throw n[0];throw new u(n.map((e=>e.message)).join("\n"))}const i=new Set(["natives_blob.bin","v8_context_snapshot.bin","snapshot_blob.bin","image_net_labels.json","package.json","models.json","LICENSE.meta","input_0.pb","output_0.pb"]).has(t),r=e.buffer,a=Array.from(r.subarray(0,Math.min(16,r.length))).map((e=>(e<16?"0":"")+e.toString(16))).join("");throw new u("Unsupported file content ("+a+") for extension '."+s+"' in '"+t+"'.",!i)}};return r()}))))}_openArchive(e){let t,s=null,r=e.identifier,a=e.buffer;try{if(t=r.split(".").pop().toLowerCase(),("gz"==t||"tgz"==t)&&(s=new n.Archive(a),1==s.entries.length)){const e=s.entries[0];e.name?r=e.name:(r=r.substring(0,r.lastIndexOf(".")),"tgz"==t&&(r+=".tar")),a=e.data}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new f(t.replace(/\.$/,"")+" in '"+r+"'."))}try{switch(t=r.split(".").pop().toLowerCase(),t){case"tar":{const e=[138,10,108,252,156,70,249,32,106,168,80,25];(!a||a.length<14||128!=a[0]||!e.every(((e,t)=>e==a[t+2])))&&(s=new o.Archive(a));break}case"zip":if(s=new i.Archive(a),s.entries.some((e=>"version"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"data.pkl"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e);if(s.entries.some((e=>"coefficients.bin"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"configuration.json"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e)}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new f(t.replace(/\.$/,"")+" in '"+r+"'."))}if(!s)return Promise.resolve(e);try{const i={};for(const e of s.entries)-1!=e.name.indexOf("/")?i[e.name.split("/").shift()+"/"]=!0:i["/"]=!0;"tar"==t&&delete i["PaxHeader/"];let n=1==Object.keys(i).length?Object.keys(i)[0]:"";n="/"==n?"":n;let o=[];const r=s.entries.slice(),a=()=>{if(r.length>0){const e=r.shift();if(e.name.startsWith(n)){const t=e.name.substring(n.length);if(t.length>0&&t.indexOf("/")<0&&!t.startsWith(".")){const t=new g(new _(null,n,e.name,e.data));let s=this._filter(t);const i=()=>{if(s.length>0){const n=s.shift();return this._host.require(n).then((r=>{if(!r.ModelFactory)throw new f("Failed to load module '"+n+"'.",null);return(new r.ModelFactory).match(t)&&(o.push(e),s=[]),i()}))}return a()};return i()}}return a()}{if(0==o.length)return Promise.resolve(e);if(2==o.length&&o.some((e=>e.name.endsWith(".params")))&&o.some((e=>e.name.endsWith("-symbol.json")))&&(o=o.filter((e=>e.name.endsWith(".params")))),o.length>1)return Promise.reject(new f("Archive contains multiple model files."));const t=o[0];return Promise.resolve(new g(new _(s.entries,n,t.name,t.data)))}};return a()}catch(e){return Promise.reject(new f(e.message))}}accept(e){e=e.toLowerCase();for(const t of this._extensions)if(e.endsWith(t.extension))return!0;return!!(e.endsWith(".zip")||e.endsWith(".tar")||e.endsWith(".tar.gz")||e.endsWith(".tgz"))}_filter(e){const t=e.identifier.toLowerCase(),s=this._extensions.filter((e=>t.endsWith(e.extension))).map((e=>e.id));return Array.from(new Set(s))}_openSignature(e){const t=e.buffer;if(0===e.buffer.length)return Promise.reject(new u("File has no content.",!0));const s=[{name:"ELF executable",value:/^\x7FELF/},{name:"Git LFS header",value:/^version https:\/\/git-lfs.github.com\/spec\/v1\n/},{name:"Git LFS header",value:/^oid sha256:/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"Unity metadata",value:/^fileFormatVersion:/},{name:"Vulkan SwiftShader ICD manifest",value:/^{\s*"file_format_version":\s*"1.0.0"\s*,\s*"ICD":/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*id:/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*name:/},{name:"Python source code",value:/^\s*import sys, types, os;/}],i=(new TextDecoder).decode(t.subarray(0,Math.min(1024,t.length)));for(const e of s)if(i.match(e.value))return Promise.reject(new u("Invalid file content. File contains "+e.name+".",!0));return Promise.resolve(e)}},"object"==typeof e.exports&&(e.exports.View=m.View,e.exports.ModelFactoryService=m.ModelFactoryService)},24137:(e,t,s)=>{const i=s(71681),n=s(63332),o=s(499),r=s(81600),a=s(71462),h=s(46506),c=s(19684),l=s(74872),m={View:class{constructor(e){this._host=e,this._host.initialize(this).then((()=>{this._model=null,this._selection=[],this._host.start(),this._showAttributes=!1,this._showInitializers=!0,this._showNames=!1,this._showHorizontal=!1,this._modelFactoryService=new m.ModelFactoryService(this._host)})).catch((e=>{this.error(e.message,e)}))}cut(){this._host.document.execCommand("cut")}copy(){this._host.document.execCommand("copy")}paste(){this._host.document.execCommand("paste")}selectAll(){this._host.document.execCommand("selectall")}find(e){if(this._activeGraph){this.clearSelection();const t=document.getElementById("canvas"),s=new l.FindSidebar(this._host,t,this._activeGraph);this._host.message("search",s.update(e))}}toggleAttributes(e){(null==e||e^this._showAttributes)&&(this._showAttributes=null==e?!this._showAttributes:e,this._reload())}get showAttributes(){return this._showAttributes}toggleInitializers(e){(null==e||e^this._showInitializers)&&(this._showInitializers=null==e?!this._showInitializers:e,this._reload())}get showInitializers(){return this._showInitializers}toggleNames(e){(null==e||e^this._showNames)&&(this._showNames=null==e?!this._showNames:e,this._reload())}get showNames(){return this._showNames}toggleDirection(e){(null==e||e^this._showHorizontal)&&(this._showHorizontal=null==e?!this._showHorizontal:e,this._reload())}get showHorizontal(){return this._showHorizontal}toggleTheme(e){this._host.document.body.className=e}_reload(){this._host.status("loading"),this._model&&this._activeGraph&&this._updateGraph(this._model,this._activeGraph).catch((e=>{e&&this.error("Graph update failed.",e)}))}_timeout(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}zoomIn(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),1.2)}zoomOut(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),.8)}resetZoom(){this._zoom&&this._zoom.scaleTo(a.select(this._host.document.getElementById("canvas")),1)}select(e){this.clearSelection();const t=document.getElementById("canvas"),s=l.FindSidebar.selection(e,t);if(s&&s.length>0){const e=this._host.document.getElementById("canvas"),t=e.getBoundingClientRect();let i=0,n=0;for(const e of s){e.classList.add("select"),this._selection.push(e);const t=e.transform.baseVal.consolidate(),s=e.getBBox(),o=t?t.matrix.e:s.x+s.width/2,r=t?t.matrix.f:s.y+s.height/2;i+=o,n+=r}i/=s.length,n/=s.length,this._zoom.transform(a.select(e),a.zoomIdentity.translate(t.width/2-i,t.height/2-n))}}clearSelection(){for(;this._selection.length>0;)this._selection.pop().classList.remove("select")}error(e,t){this._host.error(e,t.toString())}accept(e){return this._modelFactoryService.accept(e)}open(e){return this._timeout(2).then((()=>this._modelFactoryService.open(e).then((e=>this._timeout(20).then((()=>{const t=e.graphs.length>0?e.graphs[0]:null;return this._host.message("opened",{graphs:e.graphs.map((e=>e.name||"")),selected:t&&(t.name||"")}),this._updateGraph(e,t)}))))))}changeGraph(e){this._updateActiveGraph(e)}_updateActiveGraph(e){if(this._model){const t=this._model,s=t.graphs.filter((t=>e==t.name)).shift();s&&(this._host.status("loading"),this._timeout(200).then((()=>this._updateGraph(t,s).catch((e=>{e&&this.error("Graph update failed.",e)})))))}}_updateGraph(e,t){return this._timeout(100).then((()=>t&&t!=this._activeGraph&&t.nodes.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?")?null:this.renderGraph(e,t).then((()=>(this._model=e,this._activeGraph=t,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{throw this._host.status("rendered"),e})).catch((()=>{throw e}))))))}renderGraph(e,t){try{const s=this._host.document.getElementById("canvas");for(;s.lastChild;)s.removeChild(s.lastChild);if(t){this._zoom=null,s.style.position="absolute",s.style.margin="0";const i=t.groups,n={nodesep:25,ranksep:20};this._showHorizontal&&(n.rankdir="LR");const o=new h.graphlib.Graph({compound:i});o.setGraph(n),o.setDefaultEdgeLabel((()=>({})));let r=0;const m={},p={},u={};let g=(new Date).getTime();const _=t.nodes;if(_.length>1500&&(n.ranker="longest-path"),i)for(const e of _)if(e.group){const t=e.group.split("/");for(;t.length>0;){const e=t.join("/");t.pop(),u[e]=t.join("/")}}for(const t of _){const n=new c.NodeElement(this._host.document),a=(t,s,i)=>{const n=t.block("header"),o=["node-item-type"],h=s.metadata,c=h&&h.category?h.category:"";c&&o.push("node-item-type-"+c.toLowerCase());const p=s.type;if("string"!=typeof p||!p.split)throw new d("Unknown node type '"+JSON.stringify(p)+"' in '"+e.format+"'.");const u=this.showNames&&s.name?s.name:p.split(".").pop(),g=this.showNames&&s.name?p:s.name;n.add(null,o,u,g,(()=>{this.showNodeProperties(s)})),s.function&&n.add(null,["node-item-function"],"+",null,(()=>{}));const _=[];let f=!1;if(this._showInitializers)for(const e of s.inputs)e.visible&&1==e.arguments.length&&null!=e.arguments[0].initializer&&_.push(e),(!e.visible||e.arguments.length>1)&&e.arguments.some((e=>null!=e.initializer))&&(f=!0);let y=[];const b=s.attributes;if(this.showAttributes&&b&&(y=b.filter((e=>e.visible)).slice(),y.sort(((e,t)=>{const s=e.name.toUpperCase(),i=t.name.toUpperCase();return si?1:0}))),_.length>0||f||y.length>0){const e=t.block("list");e.handler=()=>{this.showNodeProperties(s)};for(const t of _){const s=t.arguments[0],i=s.type;let n="",o="";i&&i.shape&&i.shape.dimensions&&Object.prototype.hasOwnProperty.call(i.shape.dimensions,"length")&&(n="〈"+i.shape.dimensions.map((e=>e||"?")).join("×")+"〉",0==i.shape.dimensions.length&&s.initializer&&!s.initializer.state&&(n=s.initializer.toString(),n&&n.length>10&&(n=n.substring(0,10)+"…"),o=" = ")),e.add("initializer-"+s.name,t.name,n,i?i.toString():"",o)}f&&e.add(null,"〈…〉","",null,"");for(const t of y)if(t.visible){let s=l.NodeSidebar.formatAttributeValue(t.value,t.type);s&&s.length>25&&(s=s.substring(0,25)+"…"),e.add(null,t.name,s,t.type," = ")}}if(i){const e=s.inputs;for(const t of e)for(const e of t.arguments)if(""!=e.name&&!e.initializer){let s=m[e.name];s||(s={from:null,to:[]},m[e.name]=s),s.to.push({node:r,name:t.name})}let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)if(""!=t.name){let s=m[t.name];s||(s={from:null,to:[]},m[t.name]=s),s.from={node:r,name:e.name,type:t.type}}}if(s.chain&&s.chain.length>0)for(const e of s.chain)a(t,e,!1);s.inner&&a(t,s.inner,!1)};if(a(n,t,!0),t.controlDependencies&&t.controlDependencies.length>0)for(const e of t.controlDependencies){let t=m[e];t||(t={from:null,to:[]},m[e]=t),t.to.push({node:r,name:e,controlDependency:!0})}const h=t.name;h?o.setNode(r,{label:n.format(s),id:"node-"+h}):(o.setNode(r,{label:n.format(s),id:"node-"+g.toString()}),g++);const _=function(e){if(!p[e]){o.setNode(e,{rx:5,ry:5}),p[e]=!0;const t=u[e];t&&(_(t),o.setParent(e,t))}};if(i){let e=t.group;if(e&&e.length>0){if(!Object.prototype.hasOwnProperty.call(u,e)){const t=e.lastIndexOf("/");-1!=t?(e=e.substring(0,t),Object.prototype.hasOwnProperty.call(u,e)||(e=null)):e=null}e&&(_(e),o.setParent(r,e))}}r++}for(const e of t.inputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.from={node:r,type:t.type}}const t=e.arguments.map((e=>e.type||"")).join("\n");let i=e.name||"";i.length>16&&(i=i.split("/").pop());const n=new c.NodeElement(this._host.document);n.block("header").add(null,["graph-item-input"],i,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:n.format(s),class:"graph-input"})}for(const e of t.outputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.to.push({node:r})}const t=e.arguments.map((e=>e.type||"")).join("\n");let i=e.name||"";i.length>16&&(i=i.split("/").pop());const n=new c.NodeElement(this._host.document);n.block("header").add(null,["graph-item-output"],i,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:n.format(s)})}for(const e of Object.keys(m)){const t=m[e];if(null!=t.from)for(const s of t.to){let i="";const n=t.from.type;n&&n.shape&&n.shape.dimensions&&n.shape.dimensions.length>0&&(i=n.shape.dimensions.join("×")),this._showNames&&(i=e.split("\n").shift()),s.controlDependency?o.setEdge(t.from.node,s.node,{label:i,id:"edge-"+e,arrowhead:"vee",class:"edge-path-control-dependency"}):o.setEdge(t.from.node,s.node,{label:i,id:"edge-"+e,arrowhead:"vee"})}}const f=this._host.document.createElementNS("http://www.w3.org/2000/svg","rect");f.setAttribute("id","background"),f.setAttribute("width","100%"),f.setAttribute("height","100%"),f.setAttribute("fill","none"),f.setAttribute("pointer-events","all"),s.appendChild(f);const y=this._host.document.createElementNS("http://www.w3.org/2000/svg","g");y.setAttribute("id","origin"),s.appendChild(y);let b=null;return b=a.select(s),this._zoom=a.zoom(),this._zoom(b),this._zoom.scaleExtent([.1,2]),this._zoom.on("zoom",(()=>{y.setAttribute("transform",a.event.transform.toString())})),this._zoom.transform(b,a.zoomIdentity),this._timeout(20).then((()=>{new c.Renderer(this._host.document,y).render(o);const e=s.getElementsByClassName("graph-input"),t=s.getBoundingClientRect();if(e&&e.length>0){const s=[],i=[];for(let t=0;te==i[0]))&&(n=s.reduce(((e,t)=>e+t))/s.length);const r=t.width/(this._showHorizontal?4:2)-n,h=t.height/(this._showHorizontal?2:4)-o;this._zoom.transform(b,a.zoomIdentity.translate(r,h))}else this._zoom.transform(b,a.zoomIdentity.translate((t.width-o.graph().width)/2,(t.height-o.graph().height)/2))}))}return Promise.resolve()}catch(e){return Promise.reject(e)}}applyStyleSheet(e,t){let s=[];for(let e=0;e{const s=Math.max(c,l),i=2*s>24e3?24e3/s:2,n=this._host.document.createElement("canvas");n.width=Math.ceil(c*i),n.height=Math.ceil(l*i);const o=n.getContext("2d");o.scale(i,i),o.drawImage(t,0,0),this._host.document.body.removeChild(t),n.toBlob((t=>{if(t)this._host.export(e,t);else{const e=new Error;e.name="Error exporting image.",e.message="Image may be too large to render as PNG.",this._host.exception(e,!1),this._host.error(e.name,e.message)}}),"image/png")},t.src="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(m))),this._host.document.body.insertBefore(t,this._host.document.body.firstChild)}}}showModelProperties(){if(this._model){const e=new l.ModelSidebar(this._host,this._model,this._activeGraph);this._host.message("show-model-properties",e.render())}}showNodeProperties(e){if(e){const t=new l.NodeSidebar(this._host,e);this._host.message("show-node-properties",{...t.render(),metadata:e.metadata})}}showNodeDocumentation(e){const t=e.metadata;if(t){const e=new l.DocumentationSidebar(this._host,t);this._host.message("show-node-documentation",e.render())}}}};class d extends Error{constructor(e,t){super(e),this.name="Error loading model.",this.telemetry=t}}class p{constructor(e){this._context=e,this._tags=new Map,this._entries=new Map}request(e,t){return this._context.request(e,t)}get identifier(){return this._context.identifier}get buffer(){return this._context.buffer}get text(){return this._text||(this._text=new TextDecoder("utf-8").decode(this.buffer)),this._text}entries(e){let t=this._entries.get(e);if(!t){t=[];try{const s=this.buffer;switch(e){case"zip":s&&s.length>2&&80==s[0]&&75==s[1]&&(t=new i.Archive(s).entries);break;case"tar":if(s.length>=512){let e=0;for(let t=0;t<512;t++)e+=t>=148&&t<156?32:s[t];let i="";for(let e=148;e<156&&0!==s[e];e++)i+=String.fromCharCode(s[e]);i=parseInt(i,8),isNaN(i)||e!=i||(t=new o.Archive(s).entries)}}}catch(e){t=[]}this._entries.set(e,t)}return t}tags(e){let t=this._tags.get(e);if(!t){t=new Map;try{switch(e){case"pbtxt":{const e=this.buffer,s=e.length;if(!(s>=3&&239===e[0]&&187===e[1]&&191===e[2]||s>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]||s>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]||s>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3]||s>=2&&254===e[0]&&255===e[1]||s>=2&&255===e[0]&&254===e[1])&&e.subarray(0,Math.min(1024,s)).some((e=>e<7||e>14&&e<32)))break;const i=r.TextReader.create(this.text);for(i.start(!1);!i.end(!1);){const e=i.tag();t.set(e,!0),i.skip()}break}case"pb":{const e=new Set([0,1,2,3,5]),s=r.Reader.create(this.buffer),i=s.next();for(;s.pos>>3,7&i),!e.has(7&i)){t=new Map;break}try{s.skipType(7&i)}catch(e){t=new Map;break}}break}}}catch(e){t=new Map}this._tags.set(e,t)}return t}}class u{constructor(e,t,s,i){if(this._entries={},e)for(const i of e)if(i.name.startsWith(t)){const e=i.name.substring(t.length);s.length>0&&s.indexOf("/")<0&&(this._entries[e]=i)}this._identifier=s.substring(t.length),this._buffer=i}request(e,t){const s=this._entries[e];if(!s)return Promise.reject(new Error("File not found."));const i=t?new TextDecoder(t).decode(s.data):s.data;return Promise.resolve(i)}get identifier(){return this._identifier}get buffer(){return this._buffer}}class g extends Error{constructor(e){super(e),this.name="Error loading archive."}}m.ModelFactoryService=class{constructor(e){this._host=e,this._extensions=[],this.register("./onnx",[".onnx",".pb",".pbtxt",".prototxt"]),this.register("./mxnet",[".mar",".model",".json",".params"]),this.register("./keras",[".h5",".hd5",".hdf5",".keras",".json",".model",".pb",".pth"]),this.register("./coreml",[".mlmodel"]),this.register("./caffe",[".caffemodel",".pbtxt",".prototxt",".pt"]),this.register("./caffe2",[".pb",".pbtxt",".prototxt"]),this.register("./pytorch",[".pt",".pth",".pt1",".pkl",".h5",".t7",".model",".dms",".tar",".ckpt",".bin",".pb",".zip"]),this.register("./torch",[".t7"]),this.register("./tflite",[".tflite",".lite",".tfl",".bin",".pb",".tmfile",".h5",".model",".json"]),this.register("./tf",[".pb",".meta",".pbtxt",".prototxt",".json",".index",".ckpt"]),this.register("./mediapipe",[".pbtxt"]),this.register("./uff",[".uff",".pb",".trt",".pbtxt",".uff.txt"]),this.register("./sklearn",[".pkl",".pickle",".joblib",".model",".meta",".pb",".pt",".h5"]),this.register("./cntk",[".model",".cntk",".cmf",".dnn"]),this.register("./paddle",[".paddle",".pdmodel","__model__"]),this.register("./armnn",[".armnn"]),this.register("./bigdl",[".model",".bigdl"]),this.register("./darknet",[".cfg",".model"]),this.register("./mnn",[".mnn"]),this.register("./ncnn",[".param",".bin",".cfg.ncnn",".weights.ncnn"]),this.register("./tnn",[".tnnproto",".tnnmodel"]),this.register("./tengine",[".tmfile"]),this.register("./barracuda",[".nn"]),this.register("./openvino",[".xml",".bin"]),this.register("./flux",[".bson"]),this.register("./npz",[".npz",".h5",".hd5",".hdf5"]),this.register("./dl4j",[".zip"]),this.register("./mlnet",[".zip"])}register(e,t){for(const s of t)this._extensions.push({extension:s,id:e})}open(e){return this._openSignature(e).then((e=>this._openArchive(e).then((e=>{const t=(e=new p(e)).identifier,s=t.split(".").pop().toLowerCase(),i=this._filter(e);if(0==i.length)throw new d("Unsupported file extension '."+s+"'.");const n=[];let o=!1;const r=()=>{if(i.length>0){const t=i.shift();return this._host.require(t).then((s=>{if(!s.ModelFactory)throw new d("Failed to load module '"+t+"'.");const i=new s.ModelFactory;return i.match(e)?(o++,i.open(e,this._host).then((e=>e)).catch((e=>(n.push(e),r())))):r()}))}{if(o){if(1==n.length)throw n[0];throw new d(n.map((e=>e.message)).join("\n"))}const i=new Set(["natives_blob.bin","v8_context_snapshot.bin","snapshot_blob.bin","image_net_labels.json","package.json","models.json","LICENSE.meta","input_0.pb","output_0.pb"]).has(t),r=e.buffer,a=Array.from(r.subarray(0,Math.min(16,r.length))).map((e=>(e<16?"0":"")+e.toString(16))).join("");throw new d("Unsupported file content ("+a+") for extension '."+s+"' in '"+t+"'.",!i)}};return r()}))))}_openArchive(e){let t,s=null,r=e.identifier,a=e.buffer;try{if(t=r.split(".").pop().toLowerCase(),("gz"==t||"tgz"==t)&&(s=new n.Archive(a),1==s.entries.length)){const e=s.entries[0];e.name?r=e.name:(r=r.substring(0,r.lastIndexOf(".")),"tgz"==t&&(r+=".tar")),a=e.data}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new g(t.replace(/\.$/,"")+" in '"+r+"'."))}try{switch(t=r.split(".").pop().toLowerCase(),t){case"tar":{const e=[138,10,108,252,156,70,249,32,106,168,80,25];(!a||a.length<14||128!=a[0]||!e.every(((e,t)=>e==a[t+2])))&&(s=new o.Archive(a));break}case"zip":if(s=new i.Archive(a),s.entries.some((e=>"version"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"data.pkl"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e);if(s.entries.some((e=>"coefficients.bin"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"configuration.json"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e)}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new g(t.replace(/\.$/,"")+" in '"+r+"'."))}if(!s)return Promise.resolve(e);try{const i={};for(const e of s.entries)-1!=e.name.indexOf("/")?i[e.name.split("/").shift()+"/"]=!0:i["/"]=!0;"tar"==t&&delete i["PaxHeader/"];let n=1==Object.keys(i).length?Object.keys(i)[0]:"";n="/"==n?"":n;let o=[];const r=s.entries.slice(),a=()=>{if(r.length>0){const e=r.shift();if(e.name.startsWith(n)){const t=e.name.substring(n.length);if(t.length>0&&t.indexOf("/")<0&&!t.startsWith(".")){const t=new p(new u(null,n,e.name,e.data));let s=this._filter(t);const i=()=>{if(s.length>0){const n=s.shift();return this._host.require(n).then((r=>{if(!r.ModelFactory)throw new g("Failed to load module '"+n+"'.",null);return(new r.ModelFactory).match(t)&&(o.push(e),s=[]),i()}))}return a()};return i()}}return a()}{if(0==o.length)return Promise.resolve(e);if(2==o.length&&o.some((e=>e.name.endsWith(".params")))&&o.some((e=>e.name.endsWith("-symbol.json")))&&(o=o.filter((e=>e.name.endsWith(".params")))),o.length>1)return Promise.reject(new g("Archive contains multiple model files."));const t=o[0];return Promise.resolve(new p(new u(s.entries,n,t.name,t.data)))}};return a()}catch(e){return Promise.reject(new g(e.message))}}accept(e){e=e.toLowerCase();for(const t of this._extensions)if(e.endsWith(t.extension))return!0;return!!(e.endsWith(".zip")||e.endsWith(".tar")||e.endsWith(".tar.gz")||e.endsWith(".tgz"))}_filter(e){const t=e.identifier.toLowerCase(),s=this._extensions.filter((e=>t.endsWith(e.extension))).map((e=>e.id));return Array.from(new Set(s))}_openSignature(e){const t=e.buffer;if(0===e.buffer.length)return Promise.reject(new d("File has no content.",!0));const s=[{name:"ELF executable",value:/^\x7FELF/},{name:"Git LFS header",value:/^version https:\/\/git-lfs.github.com\/spec\/v1\n/},{name:"Git LFS header",value:/^oid sha256:/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"Unity metadata",value:/^fileFormatVersion:/},{name:"Vulkan SwiftShader ICD manifest",value:/^{\s*"file_format_version":\s*"1.0.0"\s*,\s*"ICD":/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*id:/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*name:/},{name:"Python source code",value:/^\s*import sys, types, os;/}],i=(new TextDecoder).decode(t.subarray(0,Math.min(1024,t.length)));for(const e of s)if(i.match(e.value))return Promise.reject(new d("Invalid file content. File contains "+e.name+".",!0));return Promise.resolve(e)}},"object"==typeof e.exports&&(e.exports.View=m.View,e.exports.ModelFactoryService=m.ModelFactoryService)},83260:()=>{}},s={};function i(e){var n=s[e];if(void 0!==n)return n.exports;var o=s[e]={id:e,loaded:!1,exports:{}};return t[e].call(o.exports,o,o.exports,i),o.loaded=!0,o.exports}i.m=t,e=[],i.O=(t,s,n,o)=>{if(!s){var r=1/0;for(l=0;l=o)&&Object.keys(i.O).every((e=>i.O[e](s[h])))?s.splice(h--,1):(a=!1,o0&&e[l-1][2]>o;l--)e[l]=e[l-1];e[l]=[s,n,o]},i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),i.j=826,(()=>{var e={826:0};i.O.j=t=>0===e[t];var t=(t,s)=>{var n,o,[r,a,h]=s,c=0;if(r.some((t=>0!==e[t]))){for(n in a)i.o(a,n)&&(i.m[n]=a[n]);if(h)var l=h(i)}for(t&&t(s);ci(68138)));n=i.O(n)})(); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7f00302fc76d5158b0918bc0fd2105db2bb1b044 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html.proxy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html.proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..4942133b61d5a31c4435037e9dd051a16da0dd1e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/index.html.proxy.js @@ -0,0 +1 @@ +export default"/__snowpack__/link/packages/netron/dist/index.html"; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..e6f00d784e5e1b34b3e494dfb402ab6c4a65559d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras-metadata.json @@ -0,0 +1 @@ +[{"name":"Bidirectional","schema":{"attributes":[{"default":"concat","description":"Mode by which outputs of the forward and backward RNNs will be\n combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the\n outputs will not be combined, they will be returned as a list. Default\n value is 'concat'.","name":"merge_mode"},{"description":"`keras.layers.RNN` instance, such as `keras.layers.LSTM` or\n `keras.layers.GRU`. It could also be a `keras.layers.Layer` instance\n that meets the following criteria:\n 1. Be a sequence-processing layer (accepts 3D+ inputs).\n 2. Have a `go_backwards`, `return_sequences` and `return_state`\n attribute (with the same semantics as for the `RNN` class).\n 3. Have an `input_spec` attribute.\n 4. Implement serialization via `get_config()` and `from_config()`.\n Note that the recommended way to create new RNN layers is to write a\n custom RNN cell and use it with `keras.layers.RNN`, instead of\n subclassing `keras.layers.Layer` directly.","name":"layer"},{"description":"Initial weights to load in the Bidirectional model\n","name":"weights"},{"description":"Optional `keras.layers.RNN`, or `keras.layers.Layer`\n instance to be used to handle backwards input processing.\n If `backward_layer` is not provided, the layer instance passed as the\n `layer` argument will be used to generate the backward layer\n automatically.\n Note that the provided `backward_layer` layer should have properties\n matching those of the `layer` argument, in particular it should have the\n same values for `stateful`, `return_states`, `return_sequence`, etc.\n In addition, `backward_layer` and `layer` should have different\n `go_backwards` argument values.\n A `ValueError` will be raised if these requirements are not met.","name":"backward_layer"}],"category":"Wrapper","description":"Bidirectional wrapper for RNNs.","examples":[{"code":"model = Sequential()\nmodel.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10)))\nmodel.add(Bidirectional(LSTM(10)))\nmodel.add(Dense(5))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\n # With custom backward layer\n model = Sequential()\n forward_layer = LSTM(10, return_sequences=True)\n backward_layer = LSTM(10, activation='relu', return_sequences=True,\n go_backwards=True)\n model.add(Bidirectional(forward_layer, backward_layer=backward_layer,\n input_shape=(5, 10)))\n model.add(Dense(5))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"TimeDistributed","schema":{"attributes":[{"description":"a `tf.keras.layers.Layer` instance.","name":"layer"}],"category":"Wrapper","description":"This wrapper allows to apply a layer to every temporal slice of an input.\n\nThe input should be at least 3D, and the dimension of index one\nwill be considered to be the temporal dimension.\n\nConsider a batch of 32 video samples, where each sample is a 128x128 RGB image\nwith `channels_last` data format, across 10 timesteps.\nThe batch input shape is `(32, 10, 128, 128, 3)`.\n\nYou can then use `TimeDistributed` to apply a `Conv2D` layer to each of the\n10 timesteps, independently:\n\n```\n>>> inputs = tf.keras.Input(shape=(10, 128, 128, 3))\n>>> conv_2d_layer = tf.keras.layers.Conv2D(64, (3, 3))\n>>> outputs = tf.keras.layers.TimeDistributed(conv_2d_layer)(inputs)\n>>> outputs.shape\nTensorShape([None, 10, 126, 126, 64])\n```","inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Activation","schema":{"attributes":[{"description":"Activation function, such as `tf.nn.relu`, or string name of\n built-in activation function, such as \"relu\".","name":"activation"}],"category":"Activation","description":"Applies an activation function to an output.","examples":[{"code":">>> layer = tf.keras.layers.Activation('relu')\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.Activation(tf.nn.relu)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ReLU","schema":{"attributes":[{"description":"Float >= 0. Maximum activation value. Default to None, which\n means unlimited.","name":"max_value"},{"description":"Float >= 0. Negative slope coefficient. Default to 0.","name":"negative_slope"},{"description":"Float. Threshold value for thresholded activation. Default to 0.","name":"threshold"}],"category":"Activation","description":"Rectified Linear Unit activation function.\n\nWith default values, it returns element-wise `max(x, 0)`.\n\nOtherwise, it follows:\n\n```\n f(x) = max_value if x >= max_value\n f(x) = x if threshold <= x < max_value\n f(x) = negative_slope * (x - threshold) otherwise\n```","examples":[{"code":">>> layer = tf.keras.layers.ReLU()\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.ReLU(max_value=1.0)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 1.0]\n>>> layer = tf.keras.layers.ReLU(negative_slope=1.0)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-3.0, -1.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.ReLU(threshold=1.5)\n>>> output = layer([-3.0, -1.0, 1.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LeakyReLU","schema":{"attributes":[{"description":"Float >= 0. Negative slope coefficient. Default to 0.3.","name":"alpha"}],"category":"Activation","description":"Leaky version of a Rectified Linear Unit.\n\nIt allows a small gradient when the unit is not active:\n\n```\n f(x) = alpha * x if x < 0\n f(x) = x if x >= 0\n```","examples":[{"code":">>> layer = tf.keras.layers.LeakyReLU()\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-0.9, -0.3, 0.0, 2.0]\n>>> layer = tf.keras.layers.LeakyReLU(alpha=0.1)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-0.3, -0.1, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Rectifier Nonlinearities Improve Neural Network Acoustic Models]( https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf)"}]}},{"name":"PReLU","schema":{"attributes":[{"description":"Initializer function for the weights.","name":"alpha_initializer"},{"description":"Regularizer for the weights.","name":"alpha_regularizer","visible":false},{"description":"Constraint for the weights.","name":"alpha_constraint"},{"description":"The axes along which to share learnable\n parameters for the activation function.\n For example, if the incoming feature maps\n are from a 2D convolution\n with output shape `(batch, height, width, channels)`,\n and you wish to share parameters across space\n so that each filter only has one set of parameters,\n set `shared_axes=[1, 2]`.","name":"shared_axes"}],"category":"Activation","description":"Parametric Rectified Linear Unit.\n\nIt follows:\n\n```\n f(x) = alpha * x for x < 0\n f(x) = x for x >= 0\n```\n\nwhere `alpha` is a learned array with the same shape as x.","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"},{"name":"params"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://arxiv.org/abs/1502.01852)"}]}},{"name":"ELU","schema":{"attributes":[{"description":"Scale for the negative factor.","name":"alpha"}],"category":"Activation","description":"Exponential Linear Unit.\n\nIt follows:\n\n```\n f(x) = alpha * (exp(x) - 1.) for x < 0\n f(x) = x for x >= 0\n```","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)](https://arxiv.org/abs/1511.07289v1)"}]}},{"name":"ThresholdedReLU","schema":{"attributes":[{"description":"Float >= 0. Threshold location of activation.","name":"theta"}],"category":"Activation","description":"Thresholded Rectified Linear Unit.\n\nIt follows:\n\n```\n f(x) = x for x > theta\n f(x) = 0 otherwise`\n```","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Zero-Bias Autoencoders and the Benefits of Co-Adapting Features]( https://arxiv.org/abs/1402.3337)"}]}},{"name":"MaxPooling1D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"},{"default":"valid","description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":[2,2],"description":"Integer, size of the max pooling window.","name":"pool_size"},{"default":[2,2],"description":"Integer, or None. Specifies how much the pooling window moves\n for each pooling step.\n If None, it will default to `pool_size`.","name":"strides"}],"category":"Pool","description":"Max pooling operation for 1D temporal data.\n\nDownsamples the input representation by taking the maximum value over the\nwindow defined by `pool_size`. The window is shifted by `strides`. The\nresulting output when using \"valid\" padding option has a shape of:\n`output_shape = (input_shape - pool_size + 1) / strides)`\n\nThe resulting output shape when using the \"same\" padding option is:\n`output_shape = input_shape / strides`\n\nFor example, for strides=1 and padding=\"valid\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=1, padding='valid')\n>>> max_pool_1d(x)\n\n```\n\nFor example, for strides=2 and padding=\"valid\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=2, padding='valid')\n>>> max_pool_1d(x)\n\n```\n\nFor example, for strides=1 and padding=\"same\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=1, padding='same')\n>>> max_pool_1d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"MaxPooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"default":"valid","description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":[2,2],"description":"integer or tuple of 2 integers,\n window size over which to take the maximum.\n `(2, 2)` will take the max value over a 2x2 pooling window.\n If only one integer is specified, the same window length\n will be used for both dimensions.","name":"pool_size"},{"default":[2,2],"description":"Integer, tuple of 2 integers, or None.\n Strides values. Specifies how far the pooling window moves\n for each pooling step. If None, it will default to `pool_size`.","name":"strides"}],"category":"Pool","description":"Max pooling operation for 2D spatial data.\n\nDownsamples the input representation by taking the maximum value over the\nwindow defined by `pool_size` for each dimension along the features axis.\nThe window is shifted by `strides` in each dimension. The resulting output\nwhen using \"valid\" padding option has a shape(number of rows or columns) of:\n`output_shape = (input_shape - pool_size + 1) / strides)`\n\nThe resulting output shape when using the \"same\" padding option is:\n`output_shape = input_shape / strides`\n\nFor example, for stride=(1,1) and padding=\"valid\":\n\n```\n>>> x = tf.constant([[1., 2., 3.],\n... [4., 5., 6.],\n... [7., 8., 9.]])\n>>> x = tf.reshape(x, [1, 3, 3, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='valid')\n>>> max_pool_2d(x)\n\n```\n\nFor example, for stride=(2,2) and padding=\"valid\":\n\n```\n>>> x = tf.constant([[1., 2., 3., 4.],\n... [5., 6., 7., 8.],\n... [9., 10., 11., 12.]])\n>>> x = tf.reshape(x, [1, 3, 4, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='valid')\n>>> max_pool_2d(x)\n\n \nUsage Example:\n```\n\n```\n>>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]],\n... [[2.], [2.], [3.], [2.]],\n... [[4.], [1.], [1.], [1.]],\n... [[2.], [2.], [1.], [4.]]]]) \n>>> output = tf.constant([[[[1], [0]],\n... [[0], [1]]]]) \n>>> model = tf.keras.models.Sequential()\n>>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), \n... input_shape=(4,4,1)))\n>>> model.compile('adam', 'mean_squared_error')\n>>> model.predict(input_image, steps=1)\narray([[[[2.],\n [4.]],\n [[4.],\n [4.]]]], dtype=float32)\n```\n\nFor example, for stride=(1,1) and padding=\"same\":\n\n```\n>>> x = tf.constant([[1., 2., 3.],\n... [4., 5., 6.],\n... [7., 8., 9.]])\n>>> x = tf.reshape(x, [1, 3, 3, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='same')\n>>> max_pool_2d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"MaxPooling3D","schema":{"attributes":[{"description":"Tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.","name":"pool_size"},{"description":"tuple of 3 integers, or None. Strides values.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Max pooling operation for 3D data (spatial or spatio-temporal).","inputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling1D","schema":{"attributes":[{"default":"channels_last","name":"data_format"},{"description":"Integer. Upsampling factor.","name":"size"}],"category":"Layer","description":"Upsampling layer for 1D inputs.\n\nRepeats each temporal step `size` times along the time axis.","examples":[{"code":">>> input_shape = (2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n>>> y = tf.keras.layers.UpSampling1D(size=2)(x)\n>>> print(y)\ntf.Tensor(\n [[[ 0 1 2]\n [ 0 1 2]\n [ 3 4 5]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 6 7 8]\n [ 9 10 11]\n [ 9 10 11]]], shape=(2, 4, 3), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape: `(batch_size, steps, features)`.","name":"input"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, upsampled_steps, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Int, or tuple of 2 integers.\n The upsampling factors for rows and columns.","name":"size"},{"description":"A string, one of `nearest` or `bilinear`.","name":"interpolation"}],"category":"Layer","description":"Upsampling layer for 2D inputs.\n\nRepeats the rows and columns of the data\nby `size[0]` and `size[1]` respectively.","examples":[{"code":">>> input_shape = (2, 2, 1, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[[ 0 1 2]]\n [[ 3 4 5]]]\n [[[ 6 7 8]]\n [[ 9 10 11]]]]\n>>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x)\n>>> print(y)\ntf.Tensor(\n [[[[ 0 1 2]\n [ 0 1 2]]\n [[ 3 4 5]\n [ 3 4 5]]]\n [[[ 6 7 8]\n [ 6 7 8]]\n [[ 9 10 11]\n [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_rows, upsampled_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_rows, upsampled_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling3D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Int, or tuple of 3 integers.\n The upsampling factors for dim1, dim2 and dim3.","name":"size"}],"category":"Layer","description":"Upsampling layer for 3D inputs.\n\nRepeats the 1st, 2nd and 3rd dimensions\nof the data by `size[0]`, `size[1]` and `size[2]` respectively.","examples":[{"code":">>> input_shape = (2, 1, 2, 1, 3)\n>>> x = tf.constant(1, shape=input_shape)\n>>> y = tf.keras.layers.UpSampling3D(size=2)(x)\n>>> print(y.shape)\n(2, 2, 4, 2, 3)"}],"inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, dim1, dim2, dim3, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, dim1, dim2, dim3)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding1D","schema":{"attributes":[{"description":"Int, or tuple of int (length 2), or dictionary.\n - If int:\n How many zeros to add at the beginning and end of\n the padding dimension (axis 1).\n - If tuple of int (length 2):\n How many zeros to add at the beginning and the end of\n the padding dimension (`(left_pad, right_pad)`).","name":"padding"}],"category":"Tensor","description":"Zero-padding layer for 1D input (e.g. temporal sequence).","examples":[{"code":">>> input_shape = (2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n>>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x)\n>>> print(y)\ntf.Tensor(\n [[[ 0 0 0]\n [ 0 0 0]\n [ 0 1 2]\n [ 3 4 5]\n [ 0 0 0]\n [ 0 0 0]]\n [[ 0 0 0]\n [ 0 0 0]\n [ 6 7 8]\n [ 9 10 11]\n [ 0 0 0]\n [ 0 0 0]]], shape=(2, 6, 3), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape `(batch_size, axis_to_pad, features)`","name":"input"}],"outputs":[{"description":"3D tensor with shape `(batch_size, padded_axis, features)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding2D","schema":{"attributes":[{"description":"Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_height_pad, symmetric_width_pad)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_pad, bottom_pad), (left_pad, right_pad))`","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Tensor","description":"Zero-padding layer for 2D input (e.g. picture).\n\nThis layer can add rows and columns of zeros\nat the top, bottom, left and right side of an image tensor.","examples":[{"code":">>> input_shape = (1, 1, 2, 2)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[[0 1]\n [2 3]]]]\n>>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x)\n>>> print(y)\ntf.Tensor(\n [[[[0 0]\n [0 0]\n [0 0]\n [0 0]]\n [[0 0]\n [0 1]\n [2 3]\n [0 0]]\n [[0 0]\n [0 0]\n [0 0]\n [0 0]]]], shape=(1, 3, 4, 2), dtype=int64)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, padded_rows, padded_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, padded_rows, padded_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding3D","schema":{"attributes":[{"description":"Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 3 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`.\n - If tuple of 3 tuples of 2 ints:\n interpreted as\n `((left_dim1_pad, right_dim1_pad), (left_dim2_pad,\n right_dim2_pad), (left_dim3_pad, right_dim3_pad))`","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Tensor","description":"Zero-padding layer for 3D data (spatial or spatio-temporal).","examples":[{"code":">>> input_shape = (1, 1, 2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x)\n>>> print(y.shape)\n(1, 5, 6, 6, 3)"}],"inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_pad, second_axis_to_pad,\n third_axis_to_pad)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_padded_axis, second_padded_axis,\n third_axis_to_pad)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalMaxPooling1D","schema":{"attributes":[{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Global max pooling operation for 1D temporal data.\n\nDownsamples the input representation by taking the maximum value over\nthe time dimension.\n\nFor example:\n\n```\n>>> x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])\n>>> x = tf.reshape(x, [3, 3, 1])\n>>> x\n\n>>> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D()\n>>> max_pool_1d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n- If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalMaxPooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Global max pooling operation for spatial data.","examples":[{"code":">>> input_shape = (2, 4, 5, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalMaxPool2D()(x)\n>>> print(y.shape)\n(2, 3)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, channels)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalAveragePooling1D","schema":{"attributes":[{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Global average pooling operation for temporal data.","examples":[{"code":">>> input_shape = (2, 3, 4)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalAveragePooling1D()(x)\n>>> print(y.shape)\n(2, 4)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n- If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalAveragePooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Global average pooling operation for spatial data.","examples":[{"code":">>> input_shape = (2, 4, 5, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalAveragePooling2D()(x)\n>>> print(y.shape)\n(2, 3)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, channels)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling1D","schema":{"attributes":[{"description":"Integer, size of the average pooling windows.","name":"pool_size"},{"description":"Integer, or None. Factor by which to downscale.\n E.g. 2 will halve the input.\n If None, it will default to `pool_size`.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Average pooling for temporal data.","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"integer or tuple of 2 integers,\n factors by which to downscale (vertical, horizontal).\n `(2, 2)` will halve the input in both spatial dimension.\n If only one integer is specified, the same window length\n will be used for both dimensions.","name":"pool_size"},{"description":"Integer, tuple of 2 integers, or None.\n Strides values.\n If None, it will default to `pool_size`.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"}],"category":"Pool","description":"Average pooling operation for spatial data.","inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling3D","schema":{"attributes":[{"description":"tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.","name":"pool_size"},{"description":"tuple of 3 integers, or None. Strides values.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"description":"Average pooling operation for 3D data (spatial or spatio-temporal).","inputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"BatchNormalization","schema":{"attributes":[{"default":-1,"description":"Integer, the axis that should be normalized (typically the features\n axis). For instance, after a `Conv2D` layer with\n `data_format=\"channels_first\"`, set `axis=1` in `BatchNormalization`.","name":"axis"},{"default":0.001,"description":"Small float added to variance to avoid dividing by zero.","name":"epsilon"},{"default":0.99,"description":"Momentum for the moving average.","name":"momentum"},{"default":true,"description":"If True, multiply by `gamma`. If False, `gamma` is not used. When the\n next layer is linear (also e.g. `nn.relu`), this can be disabled since the\n scaling will be done by the next layer.","name":"scale","type":"boolean"},{"default":true,"description":"If True, add offset of `beta` to normalized tensor. If False, `beta`\n is ignored.","name":"center"},{"default":{"class_name":"Ones","config":{}},"description":"Initializer for the gamma weight.","name":"gamma_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the moving mean.","name":"moving_mean_initializer","visible":false},{"default":{"class_name":"Ones","config":{}},"description":"Initializer for the moving variance.","name":"moving_variance_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the beta weight.","name":"beta_initializer","visible":false},{"description":"Optional regularizer for the beta weight.","name":"beta_regularizer","visible":false},{"description":"Optional regularizer for the gamma weight.","name":"gamma_regularizer","visible":false},{"description":"Optional constraint for the beta weight.","name":"beta_constraint"},{"description":"Optional constraint for the gamma weight.","name":"gamma_constraint"},{"description":"Whether to use [Batch Renormalization](\n https://arxiv.org/abs/1702.03275). This adds extra variables during\n training. The inference is the same for either value of this parameter.","name":"renorm"},{"description":"A dictionary that may map keys 'rmax', 'rmin', 'dmax' to\n scalar `Tensors` used to clip the renorm correction. The correction `(r,\n d)` is used as `corrected_value = normalized_value * r + d`, with `r`\n clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin,\n dmax are set to inf, 0, inf, respectively.","name":"renorm_clipping"},{"description":"Momentum used to update the moving means and standard\n deviations with renorm. Unlike `momentum`, this affects training and\n should be neither too small (which would add noise) nor too large (which\n would give stale estimates). Note that `momentum` is still applied to get\n the means and variances for inference.","name":"renorm_momentum"},{"description":"if `True`, use a faster, fused implementation, or raise a ValueError\n if the fused implementation cannot be used. If `None`, use the faster\n implementation if possible. If False, do not used the fused\n implementation.","name":"fused"},{"description":"Boolean, if `True` the variables will be marked as trainable.","name":"trainable"},{"description":"An `int`. By default, `virtual_batch_size` is `None`,\n which means batch normalization is performed across the whole batch. When\n `virtual_batch_size` is not `None`, instead perform \"Ghost Batch\n Normalization\", which creates virtual sub-batches which are each\n normalized separately (with shared gamma, beta, and moving statistics).\n Must divide the actual batch size during execution.","name":"virtual_batch_size"},{"description":"A function taking the `Tensor` containing the (dynamic) shape of\n the input tensor and returning a pair (scale, bias) to apply to the\n normalized values (before gamma and beta), only during training. For\n example, if axis==-1,\n `adjustment = lambda shape: (\n tf.random.uniform(shape[-1:], 0.93, 1.07),\n tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized\n value by up to 7% up or down, then shift the result by up to 0.1\n (with independent scaling and bias for each feature but shared\n across all examples), and finally apply gamma and/or beta. If\n `None`, no adjustment is applied. Cannot be specified if\n virtual_batch_size is specified.","name":"adjustment"}],"category":"Normalization","description":"Normalize and scale inputs or activations.\n\nNormalize the activations of the previous layer at each batch,\ni.e. applies a transformation that maintains the mean activation\nclose to 0 and the activation standard deviation close to 1.\n\nBatch normalization differs from other layers in several key aspects:\n\n1) Adding BatchNormalization with `training=True` to a model causes the\nresult of one example to depend on the contents of all other examples in a\nminibatch. Be careful when padding batches or masking examples, as these can\nchange the minibatch statistics and affect other examples.\n\n2) Updates to the weights (moving statistics) are based on the forward pass\nof a model rather than the result of gradient computations.\n\n3) When performing inference using a model containing batch normalization, it\nis generally (though not always) desirable to use accumulated statistics\nrather than mini-batch statistics. This is accomplished by passing\n`training=False` when calling the model, or using `model.predict`.","inputs":[{"description":"Same shape as input.\n\n\n**About setting `layer.trainable = False` on a `BatchNormalization layer:**\n\nThe meaning of setting `layer.trainable = False` is to freeze the layer,\ni.e. its internal state will not change during training:\nits trainable weights will not be updated\nduring `fit()` or `train_on_batch()`, and its state updates will not be run.\n\nUsually, this does not necessarily mean that the layer is run in inference\nmode (which is normally controlled by the `training` argument that can\nbe passed when calling a layer). \"Frozen state\" and \"inference mode\"\nare two separate concepts.\n\nHowever, in the case of the `BatchNormalization` layer, **setting\n`trainable = False` on the layer means that the layer will be\nsubsequently run in inference mode** (meaning that it will use\nthe moving mean and the moving variance to normalize the current batch,\nrather than using the mean and variance of the current batch).\n\nThis behavior has been introduced in TensorFlow 2.0, in order\nto enable `layer.trainable = False` to produce the most commonly\nexpected behavior in the convnet fine-tuning use case.\n\nNote that:\n - This behavior only occurs as of TensorFlow 2.0. In 1.*,\n setting `layer.trainable = False` would freeze the layer but would\n not switch it to inference mode.\n - Setting `trainable` on an model containing other layers will\n recursively set the `trainable` value of all inner layers.\n - If the value of the `trainable`\n attribute is changed after calling `compile()` on a model,\n the new value doesn't take effect for this model\n until `compile()` is called again.\n \n\nNormalization equations:\n Consider the intermediate activations \\(x\\) of a mini-batch of size\n \\\\(m\\\\):\n\n We can compute the mean and variance of the batch\n\n \\\\({\\mu_B} = \\frac{1}{m} \\sum_{i=1}^{m} {x_i}\\\\)\n\n \\\\({\\sigma_B^2} = \\frac{1}{m} \\sum_{i=1}^{m} ({x_i} - {\\mu_B})^2\\\\)\n\n and then compute a normalized \\\\(x\\\\), including a small factor\n \\\\({\\epsilon}\\\\) for numerical stability.\n\n \\\\(\\hat{x_i} = \\frac{x_i - \\mu_B}{\\sqrt{\\sigma_B^2 + \\epsilon}}\\\\)\n\n And finally \\\\(\\hat{x}\\) is linearly transformed by \\({\\gamma}\\\\)\n and \\\\({\\beta}\\\\), which are learned parameters:\n\n \\\\({y_i} = {\\gamma * \\hat{x_i} + \\beta}\\\\)","name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"moving_mean"},{"name":"moving_variance"}],"outputs":[{"description":"\nSame shape as input.\n","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167)"}]}},{"name":"BatchNorm","schema":{"attributes":[{"default":-1,"name":"axis"},{"default":0.001,"name":"epsilon"},{"default":0.99,"name":"momentum"},{"default":true,"name":"scale"},{"default":true,"name":"center"},{"default":{"class_name":"Ones","config":{}},"name":"gamma_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"name":"moving_mean_initializer","visible":false},{"default":{"class_name":"Ones","config":{}},"name":"moving_variance_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"name":"beta_initializer","visible":false},{"name":"beta_regularizer","visible":false},{"name":"gamma_regularizer","visible":false},{"name":"beta_constraint"},{"name":"gamma_constraint"}],"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"running_mean"},{"name":"running_std"}],"outputs":[{"name":"output"}]}},{"name":"ActivityRegularization","schema":{"attributes":[{"description":"L1 regularization factor (positive float).","name":"l1"},{"description":"L2 regularization factor (positive float).","name":"l2"}],"description":"Layer that applies an update to the cost function based input activity.","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Masking","schema":{"attributes":[{"description":"Either None or mask value to skip\n","name":"mask_value"}],"description":"Masks a sequence by using a mask value to skip timesteps.\n\nFor each timestep in the input tensor (dimension #1 in the tensor),\nif all values in the input tensor at that timestep\nare equal to `mask_value`, then the timestep will be masked (skipped)\nin all downstream layers (as long as they support masking).\n\nIf any downstream layer does not support masking yet receives such\nan input mask, an exception will be raised.","examples":[{"code":"samples, timesteps, features = 32, 10, 8\ninputs = np.random.random([samples, timesteps, features]).astype(np.float32)\ninputs[:, 3, :] = 0.\ninputs[:, 5, :] = 0.\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Masking(mask_value=0.,\n input_shape=(timesteps, features)))\nmodel.add(tf.keras.layers.LSTM(32))\n\noutput = model(inputs)\n# The time step 3 and 5 will be skipped from LSTM calculation.","summary":"Consider a Numpy data array `x` of shape `(samples, timesteps, features)`,\nto be fed to an LSTM layer. You want to mask timestep #3 and #5 because you\nlack data for these timesteps. You can:\n- Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.`\n- Insert a `Masking` layer with `mask_value=0.` before the LSTM layer:"}],"package":"tensorflow.keras.layers"}},{"name":"Dense","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","type":"boolean"},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"}],"category":"Layer","description":"Just your regular densely-connected NN layer.\n\n`Dense` implements the operation:\n`output = activation(dot(input, kernel) + bias)`\nwhere `activation` is the element-wise activation function\npassed as the `activation` argument, `kernel` is a weights matrix\ncreated by the layer, and `bias` is a bias vector created by the layer\n(only applicable if `use_bias` is `True`).\n\nNote: If the input to the layer has a rank greater than 2, then `Dense`\ncomputes the dot product between the `inputs` and the `kernel` along the\nlast axis of the `inputs` and axis 1 of the `kernel` (using `tf.tensordot`).\nFor example, if input has dimensions `(batch_size, d0, d1)`,\nthen we create a `kernel` with shape `(d1, units)`, and the `kernel` operates\nalong axis 2 of the `input`, on every sub-tensor of shape `(1, 1, d1)`\n(there are `batch_size * d0` such sub-tensors).\nThe output in this case will have shape `(batch_size, d0, units)`.\n\nBesides, layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":">>> # Create a `Sequential` model and add a Dense layer as the first layer.\n>>> model = tf.keras.models.Sequential()\n>>> model.add(tf.keras.Input(shape=(16,)))\n>>> model.add(tf.keras.layers.Dense(32, activation='relu'))\n>>> # Now the model will take as input arrays of shape (None, 16)\n>>> # and output arrays of shape (None, 32).\n>>> # Note that after the first layer, you don't need to specify\n>>> # the size of the input anymore:\n>>> model.add(tf.keras.layers.Dense(32))\n>>> model.output_shape\n(None, 32)"}],"inputs":[{"description":"N-D tensor with shape: `(batch_size, ..., input_dim)`.\nThe most common situation would be\na 2D input with shape `(batch_size, input_dim)`.","name":"input","type":"T"},{"name":"kernel","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"description":"N-D tensor with shape: `(batch_size, ..., units)`.\nFor instance, for a 2D input with shape `(batch_size, input_dim)`,\nthe output would have shape `(batch_size, units)`.","name":"output","type":"T"}],"package":"tensorflow.keras.layers"}},{"name":"LocallyConnected1D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.","name":"kernel_size"},{"description":"An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"Currently only supports `\"valid\"` (case-insensitive).\n `\"same\"` may be supported in the future.\n `\"valid\"` means no padding.","name":"padding"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias"},{"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\")..","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, length)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"implementation mode, either `1`, `2`, or `3`.\n `1` loops over input spatial locations to perform the forward pass.\n It is memory-efficient but performs a lot of (small) ops.\n\n `2` stores layer weights in a dense but sparsely-populated 2D matrix\n and implements the forward pass as a single matrix-multiply. It uses\n a lot of RAM but performs few (large) ops.\n\n `3` stores layer weights in a sparse tensor and implements the forward\n pass as a single sparse matrix-multiply.\n\n How to choose:\n\n `1`: large, dense models,\n `2`: small models,\n `3`: large, sparse models,\n\n where \"large\" stands for large input/output activations\n (i.e. many `filters`, `input_filters`, large `input_size`,\n `output_size`), and \"sparse\" stands for few connections between inputs\n and outputs, i.e. small ratio\n `filters * input_filters * kernel_size / (input_size * strides)`,\n where inputs to and outputs of the layer are assumed to have shapes\n `(input_size, input_filters)`, `(output_size, filters)`\n respectively.\n\n It is recommended to benchmark each in the setting of interest to pick\n the most efficient one (in terms of speed and memory usage). Correct\n choice of implementation can lead to dramatic speed improvements (e.g.\n 50X), potentially at the expense of RAM.\n\n Also, only `padding=\"valid\"` is supported by `implementation=1`.","name":"implementation"}],"category":"Layer","description":"Locally-connected layer for 1D inputs.\n\nThe `LocallyConnected1D` layer works similarly to\nthe `Conv1D` layer, except that weights are unshared,\nthat is, a different set of filters is applied at each different patch\nof the input.\n\nNote: layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":" # apply a unshared weight convolution 1d of length 3 to a sequence with\n # 10 timesteps, with 64 output filters\n model = Sequential()\n model.add(LocallyConnected1D(64, 3, input_shape=(10, 32)))\n # now model.output_shape == (None, 8, 64)\n # add a new conv1d on top\n model.add(LocallyConnected1D(32, 3))\n # now model.output_shape == (None, 6, 32)"}],"inputs":[{"description":"3D tensor with shape: `(batch_size, steps, input_dim)`","name":"input"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, new_steps, filters)`\n`steps` value might have changed due to padding or strides.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LocallyConnected2D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"strides"},{"description":"Currently only support `\"valid\"` (case-insensitive).\n `\"same\"` will be supported in future.\n `\"valid\"` means no padding.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").","name":"activity_regularizer"},{"description":"Constraint function applied to the kernel matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"},{"description":"implementation mode, either `1`, `2`, or `3`.\n `1` loops over input spatial locations to perform the forward pass.\n It is memory-efficient but performs a lot of (small) ops.\n\n `2` stores layer weights in a dense but sparsely-populated 2D matrix\n and implements the forward pass as a single matrix-multiply. It uses\n a lot of RAM but performs few (large) ops.\n\n `3` stores layer weights in a sparse tensor and implements the forward\n pass as a single sparse matrix-multiply.\n\n How to choose:\n\n `1`: large, dense models,\n `2`: small models,\n `3`: large, sparse models,\n\n where \"large\" stands for large input/output activations\n (i.e. many `filters`, `input_filters`, large `np.prod(input_size)`,\n `np.prod(output_size)`), and \"sparse\" stands for few connections\n between inputs and outputs, i.e. small ratio\n `filters * input_filters * np.prod(kernel_size) / (np.prod(input_size)\n * np.prod(strides))`, where inputs to and outputs of the layer are\n assumed to have shapes `input_size + (input_filters,)`,\n `output_size + (filters,)` respectively.\n\n It is recommended to benchmark each in the setting of interest to pick\n the most efficient one (in terms of speed and memory usage). Correct\n choice of implementation can lead to dramatic speed improvements (e.g.\n 50X), potentially at the expense of RAM.\n\n Also, only `padding=\"valid\"` is supported by `implementation=1`.","name":"implementation"}],"category":"Layer","description":"Locally-connected layer for 2D inputs.\n\nThe `LocallyConnected2D` layer works similarly\nto the `Conv2D` layer, except that weights are unshared,\nthat is, a different set of filters is applied at each\ndifferent patch of the input.\n\nNote: layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":" # apply a 3x3 unshared weights convolution with 64 output filters on a\n 32x32 image\n # with `data_format=\"channels_last\"`:\n model = Sequential()\n model.add(LocallyConnected2D(64, (3, 3), input_shape=(32, 32, 3)))\n # now model.output_shape == (None, 30, 30, 64)\n # notice that this layer will consume (30*30)*(3*3*3*64) + (30*30)*64\n parameters\n\n # add a 3x3 unshared weights convolution on top, with 32 output filters:\n model.add(LocallyConnected2D(32, (3, 3)))\n # now model.output_shape == (None, 28, 28, 32)"}],"inputs":[{"description":"4D tensor with shape:\n`(samples, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(samples, rows, cols, channels)` if data_format='channels_last'.","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n`(samples, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(samples, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LSTM","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":"hard_sigmoid","description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"description":"Boolean (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix, used for\n the linear transformation of the inputs. Default: `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel` weights\n matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":true,"description":"Boolean (default `True`). If True, add 1 to the bias of\n the forget gate at initialization. Setting it to true will also force\n `bias_initializer=\"zeros\"`. This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).","name":"unit_forget_bias"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint","visible":false},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint","visible":false},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"default":1,"description":"Implementation mode, either 1 or 2. Mode 1 will structure\n its operations as a larger number of smaller dot products and additions,\n whereas mode 2 will batch them into fewer, larger operations. These modes\n will have different performance profiles on different hardware and for\n different applications. Default: 2.","name":"implementation"},{"default":false,"description":"Boolean. Whether to return the last output. in the output\n sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state in addition to the\n output. Default: `False`.","name":"return_state"},{"default":false,"description":"Boolean (default `False`). If True, process the input sequence\n backwards and return the reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default `False`). If True, the last state for each sample\n at index i in a batch will be used as initial state for the sample of\n index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default `False`). If True, the network will be unrolled,\n else a symbolic loop will be used. Unrolling can speed-up a RNN, although\n it tends to be more memory-intensive. Unrolling is only suitable for short\n sequences.","name":"unroll"},{"description":"`orthogonal`.","name":"Default"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `[timesteps, batch, feature]`, whereas in the False case, it will be\n `[batch, timesteps, feature]`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"}],"category":"Layer","description":"Long Short-Term Memory layer - Hochreiter 1997.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nBased on available runtime hardware and constraints, this layer\nwill choose different implementations (cuDNN-based or pure-TensorFlow)\nto maximize the performance. If a GPU is available and all\nthe arguments to the layer meet the requirement of the CuDNN kernel\n(see below for details), the layer will use a fast cuDNN implementation.\n\nThe requirements to use the cuDNN implementation are:\n\n1. `activation` == `tanh`\n2. `recurrent_activation` == `sigmoid`\n3. `recurrent_dropout` == 0\n4. `unroll` is `False`\n5. `use_bias` is `True`\n6. Inputs, if use masking, are strictly right-padded.\n7. Eager execution is enabled in the outermost context.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> lstm = tf.keras.layers.LSTM(4)\n>>> output = lstm(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> lstm = tf.keras.layers.LSTM(4, return_sequences=True, return_state=True)\n>>> whole_seq_output, final_memory_state, final_carry_state = lstm(inputs)\n>>> print(whole_seq_output.shape)\n(32, 10, 4)\n>>> print(final_memory_state.shape)\n(32, 4)\n>>> print(final_carry_state.shape)\n(32, 4)\n```","inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Long short-term memory](http://www.bioinf.jku.at/publications/older/2604.pdf)"},{"description":"[Learning to forget: Continual prediction with LSTM](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015)"},{"description":"[Supervised sequence labeling with recurrent neural networks](http://www.cs.toronto.edu/~graves/preprint.pdf)"},{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](https://arxiv.org/abs/1512.05287)"}]}},{"name":"GRU","schema":{"attributes":[{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":"hard_sigmoid","description":"Activation function to use\n for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Orthogonal","config":{"gain":1,"seed":null}},"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent\n state. Default: `orthogonal`.","name":"recurrent_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":1,"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications. Default: 2.","name":"implementation"},{"default":false,"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state in addition to the\n output. Default: `False`.","name":"return_state"},{"default":false,"description":"Boolean (default `False`).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.","name":"unroll"},{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"sigmoid (`sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"Default"},{"description":"GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\",\n True = \"after\" (default and CuDNN compatible).","name":"reset_after"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `[timesteps, batch, feature]`, whereas in the False case, it will be\n `[batch, timesteps, feature]`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"}],"category":"Layer","description":"Gated Recurrent Unit - Cho et al. 2014.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nBased on available runtime hardware and constraints, this layer\nwill choose different implementations (cuDNN-based or pure-TensorFlow)\nto maximize the performance. If a GPU is available and all\nthe arguments to the layer meet the requirement of the CuDNN kernel\n(see below for details), the layer will use a fast cuDNN implementation.\n\nThe requirements to use the cuDNN implementation are:\n\n1. `activation` == `tanh`\n2. `recurrent_activation` == `sigmoid`\n3. `recurrent_dropout` == 0\n4. `unroll` is `False`\n5. `use_bias` is `True`\n6. `reset_after` is `True`\n7. Inputs, if use masking, are strictly right-padded.\n8. Eager execution is enabled in the outermost context.\n\nThere are two variants of the GRU implementation. The default one is based on\n[v3](https://arxiv.org/abs/1406.1078v3) and has reset gate applied to hidden\nstate before matrix multiplication. The other one is based on\n[original](https://arxiv.org/abs/1406.1078v1) and has the order reversed.\n\nThe second variant is compatible with CuDNNGRU (GPU-only) and allows\ninference on CPU. Thus it has separate biases for `kernel` and\n`recurrent_kernel`. To use this variant, set `'reset_after'=True` and\n`recurrent_activation='sigmoid'`.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> gru = tf.keras.layers.GRU(4)\n>>> output = gru(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> gru = tf.keras.layers.GRU(4, return_sequences=True, return_state=True)\n>>> whole_sequence_output, final_state = gru(inputs)\n>>> print(whole_sequence_output.shape)\n(32, 10, 4)\n>>> print(final_state.shape)\n(32, 4)\n```","inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation](https://arxiv.org/abs/1406.1078)"},{"description":"[On the Properties of Neural Machine Translation: Encoder-Decoder Approaches](https://arxiv.org/abs/1409.1259)"},{"description":"[Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling](https://arxiv.org/abs/1412.3555v1)"},{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](https://arxiv.org/abs/1512.05287)"}]}},{"name":"ConvLSTM2D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of n integers, specifying the\n dimensions of the convolution window.","name":"kernel_size"},{"description":"An integer or tuple/list of n integers,\n specifying the strides of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, time, ..., channels)`\n while `channels_first` corresponds to\n inputs with shape `(batch, time, channels, ...)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"An integer or tuple/list of n integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"description":"Activation function to use.\n By default hyperbolic tangent activation function is applied\n (`tanh(x)`).","name":"activation"},{"description":"Activation function to use\n for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Use in combination with `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et al., 2015](\n http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)","name":"unit_forget_bias"},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix.","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix.","name":"recurrent_constraint","visible":false},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint","visible":false},{"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. (default False)","name":"return_sequences"},{"description":"Boolean (default False).\n If True, process the input sequence backwards.","name":"go_backwards"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.","name":"dropout"},{"description":"Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.","name":"recurrent_dropout"},{"description":"Boolean Whether to return the last state\n in addition to the output. (default False)","name":"return_state"}],"description":"Convolutional LSTM.\n\nIt is similar to an LSTM layer, but the input transformations\nand recurrent transformations are both convolutional.","inputs":[{"description":"- If data_format='channels_first'\n 5D tensor with shape:\n `(samples, time, channels, rows, cols)`\n- If data_format='channels_last'\n 5D tensor with shape:\n `(samples, time, rows, cols, channels)`","name":"input"}],"outputs":[{"description":"- If `return_state`: a list of tensors. The first tensor is\n the output. The remaining tensors are the last states,\n each 4D tensor with shape:\n `(samples, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, new_rows, new_cols, filters)`\n if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n- If `return_sequences`: 5D tensor with shape:\n `(samples, timesteps, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 5D tensor with shape:\n `(samples, timesteps, new_rows, new_cols, filters)`\n if data_format='channels_last'.\n- Else, 4D tensor with shape:\n `(samples, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, new_rows, new_cols, filters)`\n if data_format='channels_last'.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) (the current implementation does not include the feedback loop on the cells output)."}]}},{"name":"CuDNNGRU","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n (see [initializers](https://keras.io/initializers)).","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n (see [initializers](https://keras.io/initializers)).","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector\n (see [initializers](https://keras.io/initializers)).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector\n (see [regularizer](https://keras.io/regularizers)).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"kernel_constraint"},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector\n (see [constraints](https://keras.io/constraints)).","name":"bias_constraint"},{"description":"Boolean. Whether to return the last output.\n in the output sequence, or the full sequence.","name":"return_sequences"},{"description":"Boolean. Whether to return the last state\n in addition to the output.","name":"return_state"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n","name":"stateful"}],"description":"Fast GRU implementation backed by [CuDNN](https://developer.nvidia.com/cudnn).\n\nCan only be run on GPU, with the TensorFlow backend.\n"}},{"name":"CuDNNLSTM","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n (see [initializers](https://keras.io/initializers)).","name":"kernel_initializer"},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n (see [initializers](https://keras.io/initializers)).","name":"recurrent_initializer"},{"description":"Initializer for the bias vector\n (see [initializers](https://keras.io/initializers)).","name":"bias_initializer"},{"description":"Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Setting it to true will also force `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et al. (2015)](\n http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).","name":"unit_forget_bias"},{"description":"Regularizer function applied to\n the `kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"kernel_regularizer"},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"recurrent_regularizer"},{"description":"Regularizer function applied to the bias vector\n (see [regularizer](https://keras.io/regularizers)).","name":"bias_regularizer"},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer"},{"description":"Constraint function applied to\n the `kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"kernel_constraint"},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector\n (see [constraints](https://keras.io/constraints)).","name":"bias_constraint"},{"description":"Boolean. Whether to return the last output.\n in the output sequence, or the full sequence.","name":"return_sequences"},{"description":"Boolean. Whether to return the last state\n in addition to the output.","name":"return_state"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n","name":"stateful"}],"description":"Fast LSTM implementation with [CuDNN](https://developer.nvidia.com/cudnn).\n\nCan only be run on GPU, with the TensorFlow backend.\n"}},{"name":"SimpleRNN","schema":{"attributes":[{"default":false,"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state\n in addition to the output. Default: `False`","name":"return_state"},{"default":false,"description":"Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.","name":"unroll"},{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Orthogonal","config":{"gain":1,"seed":null}},"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for the linear transformation of the inputs.","name":"dropout"},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for the linear transformation of the\n recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"description":"0.","name":"Default"}],"category":"Layer","description":"Fully-connected RNN where the output is to be fed back to input.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.","examples":[{"code":"inputs = np.random.random([32, 10, 8]).astype(np.float32)\nsimple_rnn = tf.keras.layers.SimpleRNN(4)\n\noutput = simple_rnn(inputs) # The output has shape `[32, 4]`.\n\nsimple_rnn = tf.keras.layers.SimpleRNN(\n 4, return_sequences=True, return_state=True)\n\n# whole_sequence_output has shape `[32, 10, 4]`.\n# final_state has shape `[32, 4]`.\nwhole_sequence_output, final_state = simple_rnn(inputs)"}],"inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"RNN","schema":{"attributes":[{"default":false,"description":"Boolean (default `False`). Whether to return the last\n output in the output sequence, or the full sequence.","name":"return_sequences"},{"default":false,"description":"Boolean (default `False`). Whether to return the last state\n in addition to the output.","name":"return_state"},{"default":false,"description":"Boolean (default `False`).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default `False`). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default `False`).\n If True, the network will be unrolled, else a symbolic loop will be used.\n Unrolling can speed-up a RNN, although it tends to be more\n memory-intensive. Unrolling is only suitable for short sequences.","name":"unroll"},{"description":"A RNN cell instance or a list of RNN cell instances.\n A RNN cell is a class that has:\n - A `call(input_at_t, states_at_t)` method, returning\n `(output_at_t, states_at_t_plus_1)`. The call method of the\n cell can also take the optional argument `constants`, see\n section \"Note on passing external constants\" below.\n - A `state_size` attribute. This can be a single integer\n (single state) in which case it is the size of the recurrent\n state. This can also be a list/tuple of integers (one size per state).\n The `state_size` can also be TensorShape or tuple/list of\n TensorShape, to represent high dimension state.\n - A `output_size` attribute. This can be a single integer or a\n TensorShape, which represent the shape of the output. For backward\n compatible reason, if this attribute is not available for the\n cell, the value will be inferred by the first element of the\n `state_size`.\n - A `get_initial_state(inputs=None, batch_size=None, dtype=None)`\n method that creates a tensor meant to be fed to `call()` as the\n initial state, if the user didn't specify any initial state via other\n means. The returned initial state should have a shape of\n [batch_size, cell.state_size]. The cell might choose to create a\n tensor full of zeros, or full of other values based on the cell's\n implementation.\n `inputs` is the input tensor to the RNN layer, which should\n contain the batch size as its shape[0], and also dtype. Note that\n the shape[0] might be `None` during the graph construction. Either\n the `inputs` or the pair of `batch_size` and `dtype` are provided.\n `batch_size` is a scalar tensor that represents the batch size\n of the inputs. `dtype` is `tf.DType` that represents the dtype of\n the inputs.\n For backward compatible reason, if this method is not implemented\n by the cell, the RNN layer will create a zero filled tensor with the\n size of [batch_size, cell.state_size].\n In the case that `cell` is a list of RNN cell instances, the cells\n will be stacked on top of each other in the RNN, resulting in an\n efficient stacked RNN.","name":"cell"},{"description":"dimensionality of the input (integer).\n This argument (or alternatively,\n the keyword argument `input_shape`)\n is required when using this layer as the first layer in a model.","name":"input_dim"},{"description":"Length of input sequences, to be specified\n when it is constant.\n This argument is required if you are going to connect\n `Flatten` then `Dense` layers upstream\n (without it, the shape of the dense outputs cannot be computed).\n Note that if the recurrent layer is not the first layer\n in your model, you would need to specify the input length\n at the level of the first layer\n (e.g. via the `input_shape` argument)\n","name":"input_length"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `(timesteps, batch, ...)`, whereas in the False case, it will be\n `(batch, timesteps, ...)`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"},{"description":"Boolean (default `False`).\n Whether the output should use zeros for the masked timesteps. Note that\n this field is only used when `return_sequences` is True and mask is\n provided. It can useful if you want to reuse the raw output sequence of\n the RNN without interference from the masked timesteps, eg, merging\n bidirectional RNNs.","name":"zero_output_for_mask"}],"category":"Layer","description":"Base class for recurrent layers.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.","examples":[{"code":"# First, let's define a RNN Cell, as a layer subclass.\n\nclass MinimalRNNCell(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(MinimalRNNCell, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.built = True\n\n def call(self, inputs, states):\n prev_output = states[0]\n h = K.dot(inputs, self.kernel)\n output = h + K.dot(prev_output, self.recurrent_kernel)\n return output, [output]\n\n# Let's use this cell in a RNN layer:\n\ncell = MinimalRNNCell(32)\nx = keras.Input((None, 5))\nlayer = RNN(cell)\ny = layer(x)\n\n# Here's how to use the cell to build a stacked RNN:\n\ncells = [MinimalRNNCell(32), MinimalRNNCell(64)]\nx = keras.Input((None, 5))\nlayer = RNN(cells)\ny = layer(x)"}],"inputs":[{"description":"N-D tensor with shape `[batch_size, timesteps, ...]` or\n`[timesteps, batch_size, ...]` when time_major is True.","name":"input"}],"outputs":[{"description":"- If `return_state`: a list of tensors. The first tensor is\n the output. The remaining tensors are the last states,\n each with shape `[batch_size, state_size]`, where `state_size` could\n be a high dimension tensor shape.\n - If `return_sequences`: N-D tensor with shape\n `[batch_size, timesteps, output_size]`, where `output_size` could\n be a high dimension tensor shape, or\n `[timesteps, batch_size, output_size]` when `time_major` is True.\n - Else, N-D tensor with shape `[batch_size, output_size]`, where\n `output_size` could be a high dimension tensor shape.\n\nMasking:\n This layer supports masking for input data with a variable number\n of timesteps. To introduce masks to your data,\n use an [tf.keras.layers.Embedding] layer with the `mask_zero` parameter\n set to `True`.\n\nNote on using statefulness in RNNs:\n You can set RNN layers to be 'stateful', which means that the states\n computed for the samples in one batch will be reused as initial states\n for the samples in the next batch. This assumes a one-to-one mapping\n between samples in different successive batches.\n\n To enable statefulness:\n - Specify `stateful=True` in the layer constructor.\n - Specify a fixed batch size for your model, by passing\n If sequential model:\n `batch_input_shape=(...)` to the first layer in your model.\n Else for functional model with 1 or more Input layers:\n `batch_shape=(...)` to all the first layers in your model.\n This is the expected shape of your inputs\n *including the batch size*.\n It should be a tuple of integers, e.g. `(32, 10, 100)`.\n - Specify `shuffle=False` when calling `fit()`.\n\n To reset the states of your model, call `.reset_states()` on either\n a specific layer, or on your entire model.\n\nNote on specifying the initial state of RNNs:\n You can specify the initial state of RNN layers symbolically by\n calling them with the keyword argument `initial_state`. The value of\n `initial_state` should be a tensor or list of tensors representing\n the initial state of the RNN layer.\n\n You can specify the initial state of RNN layers numerically by\n calling `reset_states` with the keyword argument `states`. The value of\n `states` should be a numpy array or list of numpy arrays representing\n the initial state of the RNN layer.\n\nNote on passing external constants to RNNs:\n You can pass \"external\" constants to the cell using the `constants`\n keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This\n requires that the `cell.call` method accepts the same keyword argument\n `constants`. Such constants can be used to condition the cell\n transformation on additional static inputs (not changing over time),\n a.k.a. an attention mechanism.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"SimpleRNNCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Activation function to use.","name":"activation"},{"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"`orthogonal`.","name":"Default"}],"description":"Cell class for SimpleRNN.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.SimpleRNN` processes the whole sequence.","examples":[{"code":"inputs = np.random.random([32, 10, 8]).astype(np.float32)\nrnn = tf.keras.layers.RNN(tf.keras.layers.SimpleRNNCell(4))\n\noutput = rnn(inputs) # The output has shape `[32, 4]`.\n\nrnn = tf.keras.layers.RNN(\n tf.keras.layers.SimpleRNNCell(4),\n return_sequences=True,\n return_state=True)\n\n# whole_sequence_output has shape `[32, 10, 4]`.\n# final_state has shape `[32, 4]`.\nwhole_sequence_output, final_state = rnn(inputs)"}],"package":"tensorflow.keras.layers"}},{"name":"GRUCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Activation function to use. Default: hyperbolic tangent\n (`tanh`). If you pass None, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the\n linear transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 (default) will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications. Default: 2.","name":"implementation"},{"description":"`orthogonal`.","name":"Default"},{"description":"GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\",\n True = \"after\" (default and CuDNN compatible).","name":"reset_after"}],"description":"Cell class for the GRU layer.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.GRU` processes the whole sequence.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> rnn = tf.keras.layers.RNN(tf.keras.layers.GRUCell(4))\n>>> output = rnn(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> rnn = tf.keras.layers.RNN(\n... tf.keras.layers.GRUCell(4),\n... return_sequences=True,\n... return_state=True)\n>>> whole_sequence_output, final_state = rnn(inputs)\n>>> print(whole_sequence_output.shape)\n(32, 10, 4)\n>>> print(final_state.shape)\n(32, 4)\n```","package":"tensorflow.keras.layers"}},{"name":"LSTMCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"`a(x) = x`).","name":"activation"},{"description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias"},{"description":"Initializer for the `kernel` weights matrix, used for\n the linear transformation of the inputs. Default: `glorot_uniform`.","name":"kernel_initializer"},{"description":"Initializer for the `recurrent_kernel` weights\n matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer"},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer"},{"description":"Boolean (default `True`). If True, add 1 to the bias of\n the forget gate at initialization. Setting it to true will also force\n `bias_initializer=\"zeros\"`. This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)","name":"unit_forget_bias"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer"},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer"},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer"},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of smaller dot\n products and additions, whereas mode 2 (default) will batch them into\n fewer, larger operations. These modes will have different performance\n profiles on different hardware and for different applications. Default: 2.","name":"implementation"},{"description":"`orthogonal`.","name":"Default"}],"description":"Cell class for the LSTM layer.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.LSTM` processes the whole sequence.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> rnn = tf.keras.layers.RNN(tf.keras.layers.LSTMCell(4))\n>>> output = rnn(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> rnn = tf.keras.layers.RNN(\n... tf.keras.layers.LSTMCell(4),\n... return_sequences=True,\n... return_state=True)\n>>> whole_seq_output, final_memory_state, final_carry_state = rnn(inputs)\n>>> print(whole_seq_output.shape)\n(32, 10, 4)\n>>> print(final_memory_state.shape)\n(32, 4)\n>>> print(final_carry_state.shape)\n(32, 4)\n```","package":"tensorflow.keras.layers"}},{"name":"StackedRNNCells","schema":{"attributes":[{"description":"List of RNN cell instances.","name":"cells"}],"description":"Wrapper allowing a stack of RNN cells to behave as a single cell.\n\nUsed to implement efficient stacked RNNs.","examples":[{"code":"batch_size = 3\nsentence_max_length = 5\nn_features = 2\nnew_shape = (batch_size, sentence_max_length, n_features)\nx = tf.constant(np.reshape(np.arange(30), new_shape), dtype = tf.float32)\n\nrnn_cells = [tf.keras.layers.LSTMCell(128) for _ in range(2)]\nstacked_lstm = tf.keras.layers.StackedRNNCells(rnn_cells)\nlstm_layer = tf.keras.layers.RNN(stacked_lstm)\n\nresult = lstm_layer(x)"}],"package":"tensorflow.keras.layers"}},{"name":"Conv1D","schema":{"attributes":[{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":"valid","description":"One of `\"valid\"`, `\"same\"` or `\"causal\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.\n `\"causal\"` results in causal (dilated) convolutions, e.g. `output[t]`\n does not depend on `input[t+1:]`. Useful when modeling temporal data\n where the model should not violate the temporal order.\n See [WaveNet: A Generative Model for Raw Audio, section\n 2.1](https://arxiv.org/abs/1609.03499).","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.","name":"data_format"},{"default":[1],"description":"An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"default":[1],"description":"an integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (\n see `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.","name":"kernel_size"},{"description":"Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (\n see `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved\n separately with `filters / groups` filters. The output is the\n concatenation of all the `groups` results along the channel axis.\n Input channels and `filters` must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"1D convolution layer (e.g. temporal convolution).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input over a single spatial (or temporal) dimension\nto produce a tensor of outputs.\nIf `use_bias` is True, a bias vector is created and added to the outputs.\nFinally, if `activation` is not `None`,\nit is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide an `input_shape` argument\n(tuple of integers or `None`, e.g.\n`(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,\nor `(None, 128)` for variable-length sequences of 128-dimensional vectors.","examples":[{"code":">>> # The inputs are 128-length vectors with 10 timesteps, and the batch size\n>>> # is 4.\n>>> input_shape = (4, 10, 128)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv1D(\n... 32, 3, activation='relu',input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 8, 32)"},{"code":">>> # With extended batch shape [4, 7] (e.g. weather data where batch\n>>> # dimensions correspond to spatial location and the third dimension\n>>> # corresponds to time.)\n>>> input_shape = (4, 7, 10, 128)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv1D(\n... 32, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 8, 32)"}],"inputs":[{"description":"3+D tensor with shape: `batch_shape + (steps, input_dim)`","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"3+D tensor with shape: `batch_shape + (new_steps, filters)`\n `steps` value might have changed due to padding or strides.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `(batch_size, height, width, channels)` while\n `channels_first` corresponds to inputs with shape `(batch_size, channels,\n height, width)`. It defaults to the `image_data_format` value found in\n your Keras config file at `~/.keras/keras.json`. If you never set it, then\n it will be `channels_last`.","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying the strides of\n the convolution along the height and width. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"an integer or tuple/list of 2 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the height\n and width of the 2D convolution window. Can be a single integer to specify\n the same value for all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint","visible":false},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"2D convolution layer (e.g. spatial convolution over images).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28 RGB images with `channels_last` and the batch\n>>> # size is 4.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 2)"},{"code":">>> # With `dilation_rate` as 2.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 24, 24, 2)"},{"code":">>> # With `padding` as \"same\".\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', padding=\"same\", input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 28, 28, 2)"},{"code":">>> # With extended batch shape [4, 7]:\n>>> input_shape = (4, 7, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 2)"}],"inputs":[{"description":"4+D tensor with shape: `batch_shape + (channels, rows, cols)` if\n `data_format='channels_first'`\nor 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if\n `data_format='channels_last'`.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if\n`data_format='channels_first'` or 4+D tensor with shape: `batch_shape +\n (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows`\n and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv3D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 3 integers, specifying the depth,\n height and width of the 3D convolution window. Can be a single integer to\n specify the same value for all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 3 integers, specifying the strides of\n the convolution along each spatial dimension. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `batch_shape + (spatial_dim1, spatial_dim2,\n spatial_dim3, channels)` while `channels_first` corresponds to inputs with\n shape `batch_shape + (channels, spatial_dim1, spatial_dim2,\n spatial_dim3)`. It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`. If you never set it, then it\n will be \"channels_last\".","name":"data_format"},{"description":"an integer or tuple/list of 3 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"3D convolution layer (e.g. spatial convolution over volumes).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes\nwith a single channel,\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28x28 volumes with a single channel, and the\n>>> # batch size is 4\n>>> input_shape =(4, 28, 28, 28, 1)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv3D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 26, 2)"},{"code":">>> # With extended batch shape [4, 7], e.g. a batch of 4 videos of 3D frames,\n>>> # with 7 frames per video.\n>>> input_shape = (4, 7, 28, 28, 28, 1)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv3D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 26, 2)"}],"inputs":[{"description":"5+D tensor with shape: `batch_shape + (channels, conv_dim1, conv_dim2,\n conv_dim3)` if data_format='channels_first'\nor 5+D tensor with shape: `batch_shape + (conv_dim1, conv_dim2, conv_dim3,\n channels)` if data_format='channels_last'.","name":"input"}],"outputs":[{"description":"5+D tensor with shape: `batch_shape + (filters, new_conv_dim1,\n new_conv_dim2, new_conv_dim3)` if data_format='channels_first'\nor 5+D tensor with shape: `batch_shape + (new_conv_dim1, new_conv_dim2,\n new_conv_dim3, filters)` if data_format='channels_last'. `new_conv_dim1`,\n `new_conv_dim2` and `new_conv_dim3` values might have changed due to\n padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv2DTranspose","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.","name":"dilation_rate"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (\n see `keras.initializers`).","name":"kernel_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (\n see `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"},{"description":"An integer or tuple/list of 2 integers,\n specifying the amount of padding along the height and width\n of the output tensor.\n Can be a single integer to specify the same value for all\n spatial dimensions.\n The amount of output padding along a given dimension must be\n lower than the stride along that same dimension.\n If set to `None` (default), the output shape is inferred.","name":"output_padding"}],"category":"Layer","description":"Transposed convolution layer (sometimes called Deconvolution).\n\nThe need for transposed convolutions generally arises\nfrom the desire to use a transformation going in the opposite direction\nof a normal convolution, i.e., from something that has the shape of the\noutput of some convolution to something that has the shape of its input\nwhile maintaining a connectivity pattern that is compatible with\nsaid convolution.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","inputs":[{"description":"4D tensor with shape:\n`(batch_size, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, rows, cols, channels)` if data_format='channels_last'.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4D tensor with shape:\n`(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.\nIf `output_padding` is specified:\n```\nnew_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] +\noutput_padding[0])\nnew_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] +\noutput_padding[1])\n```","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1)"},{"description":"[Deconvolutional Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf)"}]}},{"name":"Cropping1D","schema":{"attributes":[{"description":"Int or tuple of int (length 2)\n How many units should be trimmed off at the beginning and end of\n the cropping dimension (axis 1).\n If a single int is provided, the same value will be used for both.","name":"cropping"}],"category":"Shape","description":"Cropping layer for 1D input (e.g. temporal sequence).\n\nIt crops along the time dimension (axis 1).","examples":[{"code":">>> input_shape = (2, 3, 2)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1]\n [ 2 3]\n [ 4 5]]\n [[ 6 7]\n [ 8 9]\n [10 11]]]\n>>> y = tf.keras.layers.Cropping1D(cropping=1)(x)\n>>> print(y)\ntf.Tensor(\n [[[2 3]]\n [[8 9]]], shape=(2, 1, 2), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape `(batch_size, axis_to_crop, features)`","name":"input"}],"outputs":[{"description":"3D tensor with shape `(batch_size, cropped_axis, features)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Cropping2D","schema":{"attributes":[{"description":"Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric cropping values for height and width:\n `(symmetric_height_crop, symmetric_width_crop)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_crop, bottom_crop), (left_crop, right_crop))`","name":"cropping"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Cropping layer for 2D input (e.g. picture).\n\nIt crops along spatial dimensions, i.e. height and width.","examples":[{"code":">>> input_shape = (2, 28, 28, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x)\n>>> print(y.shape)\n(2, 24, 20, 3)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, cropped_rows, cropped_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, cropped_rows, cropped_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Cropping3D","schema":{"attributes":[{"description":"Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to depth, height, and width.\n - If tuple of 3 ints: interpreted as two different\n symmetric cropping values for depth, height, and width:\n `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`.\n - If tuple of 3 tuples of 2 ints: interpreted as\n `((left_dim1_crop, right_dim1_crop), (left_dim2_crop,\n right_dim2_crop), (left_dim3_crop, right_dim3_crop))`","name":"cropping"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Cropping layer for 3D data (e.g. spatial or spatio-temporal).\n\n Examples:\n\n```\n>>> input_shape = (2, 28, 28, 10, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x)\n>>> print(y.shape)\n(2, 24, 20, 6, 3)\n```","inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_crop, second_axis_to_crop,\n third_axis_to_crop)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_cropped_axis, second_cropped_axis,\n third_cropped_axis)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"SeparableConv2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"default":1,"description":"The number of depthwise convolution output channels\n for each input channel.\n The total number of depthwise convolution output\n channels will be equal to `filters_in * depth_multiplier`.","name":"depth_multiplier"},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the pointwise kernel matrix (\n see `keras.initializers`).","name":"pointwise_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the depthwise kernel matrix (\n see `keras.initializers`).","name":"depthwise_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to\n the depthwise kernel matrix (see `keras.regularizers`).","name":"depthwise_regularizer","visible":false},{"description":"Regularizer function applied to\n the pointwise kernel matrix (see `keras.regularizers`).","name":"pointwise_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the depthwise kernel matrix (\n see `keras.constraints`).","name":"depthwise_constraint","visible":false},{"description":"Constraint function applied to\n the pointwise kernel matrix (\n see `keras.constraints`).","name":"pointwise_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"}],"category":"Layer","description":"Depthwise separable 2D convolution.\n\nSeparable convolutions consist of first performing\na depthwise spatial convolution\n(which acts on each input channel separately)\nfollowed by a pointwise convolution which mixes the resulting\noutput channels. The `depth_multiplier` argument controls how many\noutput channels are generated per input channel in the depthwise step.\n\nIntuitively, separable convolutions can be understood as\na way to factorize a convolution kernel into two smaller kernels,\nor as an extreme version of an Inception block.","inputs":[{"description":"4D tensor with shape:\n`(batch_size, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, rows, cols, channels)` if data_format='channels_last'.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4D tensor with shape:\n`(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Convolution2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `(batch_size, height, width, channels)` while\n `channels_first` corresponds to inputs with shape `(batch_size, channels,\n height, width)`. It defaults to the `image_data_format` value found in\n your Keras config file at `~/.keras/keras.json`. If you never set it, then\n it will be `channels_last`.","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying the strides of\n the convolution along the height and width. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"an integer or tuple/list of 2 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"default":1,"name":"depth_multiplier"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the height\n and width of the 2D convolution window. Can be a single integer to specify\n the same value for all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"2D convolution layer (e.g. spatial convolution over images).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28 RGB images with `channels_last` and the batch\n>>> # size is 4.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 2)"},{"code":">>> # With `dilation_rate` as 2.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 24, 24, 2)"},{"code":">>> # With `padding` as \"same\".\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', padding=\"same\", input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 28, 28, 2)"},{"code":">>> # With extended batch shape [4, 7]:\n>>> input_shape = (4, 7, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 2)"}],"inputs":[{"description":"4+D tensor with shape: `batch_shape + (channels, rows, cols)` if\n `data_format='channels_first'`\nor 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if\n `data_format='channels_last'`.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if\n`data_format='channels_first'` or 4+D tensor with shape: `batch_shape +\n (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows`\n and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"DepthwiseConv2D","schema":{"attributes":[{"default":"linear","name":"activation"},{"default":"valid","name":"padding"},{"default":true,"name":"use_bias","visible":false},{"default":"channels_last","name":"data_format"},{"default":[1,1],"name":"strides"},{"default":[1,1],"name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"name":"depthwise_initializer","visible":false},{"default":1,"name":"depth_multiplier"}],"category":"Layer","inputs":[{"name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"Concatenate","schema":{"attributes":[{"description":"Axis along which to concatenate.","name":"axis"},{"description":"standard layer keyword arguments.\n","name":"**kwargs"}],"category":"Tensor","description":"Layer that concatenates a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape except\nfor the concatenation axis, and returns a single tensor that is the\nconcatenation of all inputs.\n\n```\n>>> x = np.arange(20).reshape(2, 2, 5)\n>>> print(x)\n[[[ 0 1 2 3 4]\n [ 5 6 7 8 9]]\n [[10 11 12 13 14]\n [15 16 17 18 19]]]\n>>> y = np.arange(20, 30).reshape(2, 1, 5)\n>>> print(y)\n[[[20 21 22 23 24]]\n [[25 26 27 28 29]]]\n>>> tf.keras.layers.Concatenate(axis=1)([x, y])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> concatted = tf.keras.layers.Concatenate()([x1, x2])\n>>> concatted.shape\nTensorShape([5, 16])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Average","schema":{"category":"Tensor","description":"Layer that averages a list of inputs element-wise.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).","examples":[{"code":">>> x1 = np.ones((2, 2))\n>>> x2 = np.zeros((2, 2))\n>>> y = tf.keras.layers.Average()([x1, x2])\n>>> y.numpy().tolist()\n[[0.5, 0.5], [0.5, 0.5]]"},{"code":">>> input1 = tf.keras.layers.Input(shape=(16,))\n>>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1)\n>>> input2 = tf.keras.layers.Input(shape=(32,))\n>>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2)\n>>> avg = tf.keras.layers.Average()([x1, x2])\n>>> out = tf.keras.layers.Dense(4)(avg)\n>>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out)","summary":"Usage in a functional model:"}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Maximum","schema":{"category":"Tensor","description":"Layer that computes the maximum (element-wise) a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).\n\n```\n>>> tf.keras.layers.Maximum()([np.arange(5).reshape(5, 1),\n... np.arange(5, 10).reshape(5, 1)])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> maxed = tf.keras.layers.Maximum()([x1, x2])\n>>> maxed.shape\nTensorShape([5, 8])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Dot","schema":{"attributes":[{"description":"Integer or tuple of integers,\n axis or axes along which to take the dot product.","name":"axes"},{"description":"Whether to L2-normalize samples along the\n dot product axis before taking the dot product.\n If set to True, then the output of the dot product\n is the cosine proximity between the two samples.","name":"normalize"},{"description":"Standard layer keyword arguments.\n","name":"**kwargs"}],"description":"Layer that computes a dot product between samples in two tensors.\n\nE.g. if applied to a list of two tensors `a` and `b` of shape\n`(batch_size, n)`, the output will be a tensor of shape `(batch_size, 1)`\nwhere each entry `i` will be the dot product between\n`a[i]` and `b[i]`.\n\n```\n>>> x = np.arange(10).reshape(1, 5, 2)\n>>> print(x)\n[[[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]]\n>>> y = np.arange(10, 20).reshape(1, 2, 5)\n>>> print(y)\n[[[10 11 12 13 14]\n [15 16 17 18 19]]]\n>>> tf.keras.layers.Dot(axes=(1, 2))([x, y])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> dotted = tf.keras.layers.Dot(axes=1)([x1, x2])\n>>> dotted.shape\nTensorShape([5, 1])\n```","inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}],"package":"tensorflow.keras.layers"}},{"name":"Flatten","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, ..., channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, ...)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Flattens the input. Does not affect the batch size.\n\nNote: If inputs are shaped `(batch,)` without a feature axis, then\nflattening adds an extra channel dimension and output shape is `(batch, 1)`.","examples":[{"code":">>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Conv2D(64, 3, 3, input_shape=(3, 32, 32)))\n>>> model.output_shape\n(None, 1, 10, 64)"},{"code":">>> model.add(Flatten())\n>>> model.output_shape\n(None, 640)"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Reshape","schema":{"attributes":[{"description":"target shape. Tuple of integers.\n Does not include the batch axis.\n","name":"target_shape"}],"category":"Shape","description":"Layer that reshapes inputs into the given shape.","examples":[{"code":">>> # as first layer in a Sequential model\n>>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,)))\n>>> # model.output_shape == (None, 3, 4), `None` is the batch size.\n>>> model.output_shape\n(None, 3, 4)"},{"code":">>> # as intermediate layer in a Sequential model\n>>> model.add(tf.keras.layers.Reshape((6, 2)))\n>>> model.output_shape\n(None, 6, 2)"},{"code":">>> # also supports shape inference using `-1` as dimension\n>>> model.add(tf.keras.layers.Reshape((-1, 2, 2)))\n>>> model.output_shape\n(None, 3, 2, 2)"}],"inputs":[{"description":"Arbitrary, although all dimensions in the input shape must be known/fixed.\nUse the keyword argument `input_shape` (tuple of integers, does not include\nthe samples/batch size axis) when using this layer as the first layer\nin a model.","name":"input"}],"outputs":[{"description":"`(batch_size,) + target_shape`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Permute","schema":{"attributes":[{"description":"Tuple of integers. Permutation pattern does not include the\n samples dimension. Indexing starts at 1.\n For instance, `(2, 1)` permutes the first and second dimensions\n of the input.","name":"dims"}],"category":"Shape","description":"Permutes the dimensions of the input according to a given pattern.\n\nUseful e.g. connecting RNNs and convnets.","examples":[{"code":"model = Sequential()\nmodel.add(Permute((2, 1), input_shape=(10, 64)))\n# now: model.output_shape == (None, 64, 10)\n# note: `None` is the batch dimension"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same as the input shape, but with the dimensions re-ordered according\nto the specified pattern.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"RepeatVector","schema":{"attributes":[{"description":"Integer, repetition factor.","name":"n"}],"category":"Shape","description":"Repeats the input n times.","examples":[{"code":"model = Sequential()\nmodel.add(Dense(32, input_dim=32))\n# now: model.output_shape == (None, 32)\n# note: `None` is the batch dimension\n\nmodel.add(RepeatVector(3))\n# now: model.output_shape == (None, 3, 32)"}],"inputs":[{"description":"2D tensor of shape `(num_samples, features)`.","name":"input"}],"outputs":[{"description":"3D tensor of shape `(num_samples, n, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Dropout","schema":{"attributes":[{"description":"Float between 0 and 1. Fraction of the input units to drop.","name":"rate"},{"description":"1D integer tensor representing the shape of the\n binary dropout mask that will be multiplied with the input.\n For instance, if your inputs have shape\n `(batch_size, timesteps, features)` and\n you want the dropout mask to be the same for all timesteps,\n you can use `noise_shape=(batch_size, 1, features)`.","name":"noise_shape"},{"description":"A Python integer to use as random seed.","name":"seed"}],"category":"Dropout","description":"Applies Dropout to the input.\n\nThe Dropout layer randomly sets input units to 0 with a frequency of `rate`\nat each step during training time, which helps prevent overfitting.\nInputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\nall inputs is unchanged.\n\nNote that the Dropout layer only applies when `training` is set to True\nsuch that no values are dropped during inference. When using `model.fit`,\n`training` will be appropriately set to True automatically, and in other\ncontexts, you can set the kwarg explicitly to True when calling the layer.\n\n(This is in contrast to setting `trainable=False` for a Dropout layer.\n`trainable` does not affect the layer's behavior, as Dropout does\nnot have any variables/weights that can be frozen during training.)\n\n```\n>>> tf.random.set_seed(0)\n>>> layer = tf.keras.layers.Dropout(.2, input_shape=(2,))\n>>> data = np.arange(10).reshape(5, 2).astype(np.float32)\n>>> print(data)\n[[0. 1.]\n [2. 3.]\n [4. 5.]\n [6. 7.]\n [8. 9.]]\n>>> outputs = layer(data, training=True)\n>>> print(outputs)\ntf.Tensor(\n[[ 0. 1.25]\n [ 2.5 3.75]\n [ 5. 6.25]\n [ 7.5 8.75]\n [10. 0. ]], shape=(5, 2), dtype=float32)\n```","inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Dropout: A Simple Way to Prevent Neural Networks from Overfitting]( http://www.jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf)"}]}},{"name":"Embedding","schema":{"attributes":[{"default":false,"description":"Boolean, whether or not the input value 0 is a special \"padding\"\n value that should be masked out.\n This is useful when using recurrent layers\n which may take variable length input.\n If this is `True`, then all subsequent layers\n in the model need to support masking or an exception will be raised.\n If mask_zero is set to True, as a consequence, index 0 cannot be\n used in the vocabulary (input_dim should equal size of\n vocabulary + 1).","name":"mask_zero"},{"default":{"class_name":"RandomUniform","config":{"maxval":0.05,"minval":-0.05,"seed":null}},"description":"Initializer for the `embeddings`\n matrix (see `keras.initializers`).","name":"embeddings_initializer","visible":false},{"description":"Integer. Size of the vocabulary,\n i.e. maximum integer index + 1.","name":"input_dim"},{"description":"Integer. Dimension of the dense embedding.","name":"output_dim"},{"description":"Regularizer function applied to\n the `embeddings` matrix (see `keras.regularizers`).","name":"embeddings_regularizer","visible":false},{"description":"Constraint function applied to\n the `embeddings` matrix (see `keras.constraints`).","name":"embeddings_constraint"},{"description":"Length of input sequences, when it is constant.\n This argument is required if you are going to connect\n `Flatten` then `Dense` layers upstream\n (without it, the shape of the dense outputs cannot be computed).","name":"input_length"},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer"}],"category":"Transform","description":"Turns positive integers (indexes) into dense vectors of fixed size.\n\ne.g. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]`\n\nThis layer can only be used as the first layer in a model.","examples":[{"code":">>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Embedding(1000, 64, input_length=10))\n>>> # The model will take as input an integer matrix of size (batch,\n>>> # input_length), and the largest integer (i.e. word index) in the input\n>>> # should be no larger than 999 (vocabulary size).\n>>> # Now model.output_shape is (None, 10, 64), where `None` is the batch\n>>> # dimension.\n>>> input_array = np.random.randint(1000, size=(32, 10))\n>>> model.compile('rmsprop', 'mse')\n>>> output_array = model.predict(input_array)\n>>> print(output_array.shape)\n(32, 10, 64)"}],"inputs":[{"description":"2D tensor with shape: `(batch_size, input_length)`.","name":"input"},{"name":"embeddings"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, input_length, output_dim)`.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](http://arxiv.org/abs/1512.05287)"}]}},{"name":"Add","schema":{"description":"Layer that adds a list of inputs.\n\nIt takes as input a list of tensors,\nall of the same shape, and returns\na single tensor (also of the same shape).","examples":[{"code":">>> input_shape = (2, 3, 4)\n>>> x1 = tf.random.normal(input_shape)\n>>> x2 = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Add()([x1, x2])\n>>> print(y.shape)\n(2, 3, 4)"},{"code":">>> input1 = tf.keras.layers.Input(shape=(16,))\n>>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1)\n>>> input2 = tf.keras.layers.Input(shape=(32,))\n>>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2)\n>>> # equivalent to `added = tf.keras.layers.add([x1, x2])`\n>>> added = tf.keras.layers.Add()([x1, x2])\n>>> out = tf.keras.layers.Dense(4)(added)\n>>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out)","summary":"Used in a functional model:"}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Subtract","schema":{"description":"Layer that subtracts two inputs.\n\nIt takes as input a list of tensors of size 2,\nboth of the same shape, and returns a single tensor, (inputs[0] - inputs[1]),\nalso of the same shape.","examples":[{"code":" import keras\n\n input1 = keras.layers.Input(shape=(16,))\n x1 = keras.layers.Dense(8, activation='relu')(input1)\n input2 = keras.layers.Input(shape=(32,))\n x2 = keras.layers.Dense(8, activation='relu')(input2)\n # Equivalent to subtracted = keras.layers.subtract([x1, x2])\n subtracted = keras.layers.Subtract()([x1, x2])\n\n out = keras.layers.Dense(4)(subtracted)\n model = keras.models.Model(inputs=[input1, input2], outputs=out)"}],"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}],"package":"tensorflow.keras.layers"}},{"name":"Multiply","schema":{"description":"Layer that multiplies (element-wise) a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).\n\n```\n>>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1),\n... np.arange(5, 10).reshape(5, 1)])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> multiplied = tf.keras.layers.Multiply()([x1, x2])\n>>> multiplied.shape\nTensorShape([5, 8])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Lambda","schema":{"attributes":[{"description":"The function to be evaluated. Takes input tensor as first\n argument.","name":"function"},{"description":"Expected output shape from function. This argument can be\n inferred if not explicitly provided. Can be a tuple or function. If a\n tuple, it only specifies the first dimension onward;\n sample dimension is assumed either the same as the input: `output_shape =\n (input_shape[0], ) + output_shape` or, the input is `None` and\n the sample dimension is also `None`: `output_shape = (None, ) +\n output_shape` If a function, it specifies the entire shape as a function\n of the\n input shape: `output_shape = f(input_shape)`","name":"output_shape"},{"description":"Optional dictionary of keyword arguments to be passed to the\n function.","name":"arguments"},{"description":"Either None (indicating no masking) or a callable with the same\n signature as the `compute_mask` layer method, or a tensor that will be\n returned as output mask regardless of what the input is.","name":"mask"}],"description":"Wraps arbitrary expressions as a `Layer` object.\n\nThe `Lambda` layer exists so that arbitrary TensorFlow functions\ncan be used when constructing `Sequential` and Functional API\nmodels. `Lambda` layers are best suited for simple operations or\nquick experimentation. For more advanced use cases, follow\n[this guide](https://www.tensorflow.org/guide/keras/custom_layers_and_models)\nfor subclassing `tf.keras.layers.Layer`.\n\nThe main reason to subclass `tf.keras.layers.Layer` instead of using a\n`Lambda` layer is saving and inspecting a Model. `Lambda` layers\nare saved by serializing the Python bytecode, whereas subclassed\nLayers can be saved via overriding their `get_config` method. Overriding\n`get_config` improves the portability of Models. Models that rely on\nsubclassed Layers are also often easier to visualize and reason about.","examples":[{"code":"# add a x -> x^2 layer\nmodel.add(Lambda(lambda x: x ** 2))"},{"code":"# add a layer that returns the concatenation\n# of the positive part of the input and\n# the opposite of the negative part\n\ndef antirectifier(x):\n x -= K.mean(x, axis=1, keepdims=True)\n x = K.l2_normalize(x, axis=1)\n pos = K.relu(x)\n neg = K.relu(-x)\n return K.concatenate([pos, neg], axis=1)\n\nmodel.add(Lambda(antirectifier))"}],"inputs":[{"description":"Arbitrary. Use the keyword argument input_shape (tuple of\nintegers, does not include the samples axis) when using this layer as the\nfirst layer in a model.","name":"inputs","option":"variadic"}],"outputs":[{"description":"Specified by `output_shape` argument","name":"output"}],"package":"tensorflow.keras.layers"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras.js new file mode 100644 index 0000000000000000000000000000000000000000..7bd57012b6d0b907187b3db8f5680c758c868d3d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/keras.js @@ -0,0 +1 @@ +var keras=keras||{},base=base||require("./base"),long=long||{Long:require("long")};keras.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("h5"===s||"hd5"===s||"hdf5"===s||"keras"===s||"model"===s||"pb"==s||"pth"==s){const e=t.buffer,s=[137,72,68,70,13,10,26,10];return e&&e.length>s.length&&s.every(((t,s)=>t===e[s]))}if("json"==s&&!e.endsWith("-symbol.json")){const e=t.text;if(-1==e.indexOf('"mxnet_version":',0))try{let t=keras.JsonParser.parse(e);if(t&&t.nodes&&t.arg_nodes&&t.heads)return!1;if(t&&t.modelTopology&&(t=t.modelTopology),t&&t.model_config&&(t=t.model_config),t&&t.class_name)return!0;if(t&&Array.isArray(t)&&t.every((t=>Array.isArray(t.weights)&&Array.isArray(t.paths))))return!0}catch(t){}}return!1}open(t,e){return e.require("./hdf5").then((s=>{let r="Keras",n="",i="",a=null,o=null;const h=t.identifier,u=new keras.Weights;try{switch(h.split(".").pop().toLowerCase()){case"keras":case"h5":case"hd5":case"hdf5":case"model":case"pb":case"pth":if(o=new s.File(t.buffer).rootGroup,o.attribute("model_config")||o.attribute("layer_names")){const t=o.attribute("model_config");t&&(a=keras.JsonParser.parse(t)),i=o.attribute("backend")||"";const e=o.attribute("keras_version")||"";r+=e?" v"+e:"";let s=o.group("model_weights");if(!s&&o.attribute("layer_names")&&(s=o),s){s=new keras.Group(s);for(const t of s.attribute("layer_names")){const e=s.group(t);if(e){const s=e.attribute("weight_names");if(s&&s.length>0)for(const r of s){const s=e.group(r);if(s&&s.value){const e=s.value,n=new keras.Tensor(r,e.type,e.shape,e.littleEndian,e.data,"");if(a)u.add(t,n);else{const e=r.split("/");e.pop();const s=0==e.length||e[0]!==t?[t].concat(e).join("/"):e.join("/");u.add(s,n)}}}}}}}else{const t=new Set(["nb_layers"]);if(0!==Object.keys(o.attributes).filter((e=>!t.has(e))).length||null!==o.value)throw new keras.Error("File format is not HDF5 Weights");if(r="HDF5 Weights",0===Object.keys(o.attributes).length&&null===o.value&&1==o.groups.length&&o.groups[0]&&0===Object.keys(o.groups[0].attributes).length&&null===o.groups[0].value&&(o=o.groups[0]),o.groups.every((t=>0===Object.keys(t.attributes).length&&0==t.groups.length&&null!==t.value)))for(const t of o.groups){const e=t.value,s=new keras.Tensor(t.name,e.type,e.shape,e.littleEndian,"string"===e.type?e.value:e.data);u.add("",s)}else if(o.groups.every((t=>0===Object.keys(t.attributes).length&&null===t.value)))for(const t of o.groups){const e=t.attributes.name||t.name;for(const s of t.groups){if(0!==Object.keys(s.attributes).length||0!==s.groups.length)throw new keras.Error("Group format is not HDF5 tensor variable.");const t=s.value;if(!t)throw new keras.Error("Variable value is not HDF5 tensor.");const r=e?[e,s.name].join("/"):e.name,n=new keras.Tensor(r,t.type,t.shape,t.littleEndian,"string"===t.type?t.value:t.data);u.add(e,n)}}else{if(!o.groups.every((t=>null===t.value&&t.groups.every((t=>0===Object.keys(t.attributes).length&&null!==t.value)))))throw new keras.Error("Module group format is not HDF5 Weights");for(const t of o.groups){const e=t.attributes.name||t.name;for(const s of t.groups){if(0!==Object.keys(s.attributes).length||0!==s.groups.length)throw new keras.Error("Variable format is not HDF5 Weights");const t=s.value;if(!t)throw new keras.Error("Variable value is not HDF5 Weights");const r=e?[e,s.name].join("/"):e.name,n=new keras.Tensor(r,t.type,t.shape,t.littleEndian,"string"===t.type?t.value:t.data);u.add(e,n)}}}}break;case"json":{const e=keras.JsonParser.parse(t.text);if(e&&Array.isArray(e)&&e.every((t=>Array.isArray(t.weights)&&Array.isArray(t.paths)))){r="TensorFlow.js Weights",o={};for(const t of e)for(const e of t.weights){const s=new keras.Tensor(e.name,e.dtype,e.shape,!1,null,t.paths.join(";")),r=e.name.split("/");r.pop();const n=r.join("/");u.add(n,s)}}else{if(e.keras_version){const t=e.keras_version;r+=t?" v"+t:""}if(e.backend&&(i=e.backend),a=e,a&&a.modelTopology){i=a.modelTopology.backend;const t=a.modelTopology.keras_version;r+=t?" v"+t:"",r="TensorFlow.js "+(a.format?a.format:r),n=a.convertedBy||a.generatedBy||"";for(const t of a.weightsManifest)for(const e of t.weights){const s=new keras.Tensor(e.name,e.dtype,e.shape,!1,null,t.paths.join(";"));u.add("",s)}a=a.modelTopology}a.model_config&&(a=a.model_config)}break}}}catch(t){const e=t&&t.message?t.message:t.toString();throw new keras.Error(e.replace(/\.$/,"")+" in '"+h+"'.")}if(!o&&!a)throw new keras.Error("'model_config' is not present.");if(!o&&!a.class_name)throw new keras.Error("'class_name' is not present.");return keras.Metadata.open(e).then((t=>{try{return new keras.Model(t,r,n,i,a,u)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new keras.Error(s.replace(/\.$/,"")+" in '"+h+"'.")}}))}))}},keras.Model=class{constructor(t,e,s,r,n,i){this._format=e,this._backend=r,this._producer=s,this._graphs=[new keras.Graph(t,n,i)]}get name(){return null}get description(){return null}get format(){return this._format}get producer(){return this._producer}get runtime(){return this._backend}get graphs(){return this._graphs}},keras.Graph=class{constructor(t,e,s){if(this._metadata=t,this._inputs=[],this._outputs=[],this._nodes=[],this._groups=!1,e)switch(this._name=e.name||(e.config&&e.config.name?e.config.name:""),e.class_name){case"AllCNN":case"Sequential":this._loadSequential(e.config,s,"",null,null);break;case"Functional":case"Model":this._loadModel(e.config,s,"",null,null);break;default:throw new keras.Error("'"+e.class_name+"' is not supported.")}else if(s)for(const e of s.keys())if(s.get("",e).length<=6){const r=new keras.Node(t,"Weights",{name:e},[],[],"",s);this._nodes.push(r)}}get name(){return this._name}get groups(){return!!this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}_loadModel(t,e,s,r,n){s&&(this._groups=!0);const i=new Map;if(t.layers){for(const e of t.layers)e.name&&(i.has(e.name)||(i.set(e.name,e),e._inputs=[],e._outputs=[]));for(const e of t.layers)if(e.inbound_nodes)for(const t of e.inbound_nodes)for(const s of t){let t=s[0];const r=i.get(t);if(r){const e=s[2];for(0!=e&&(t+=":"+e.toString());e>=r._outputs.length;)r._outputs.push("");r._outputs[e]=t}e._inputs.push(t)}}const a=t.input_layers;if(a)for(let e=0;et===s?r[e]:t)))}else this._inputs.push(new keras.Parameter(s,!0,[new keras.Argument(s,n,null)]))}const o=new Map,h=t.output_layers;if(h)for(let t=0;t=r._outputs.length;)r._outputs.push("");r._outputs[t]=s}a&&this._outputs.push(new keras.Parameter(s,!0,[new keras.Argument(s,null,null)]))}if(t.layers)for(const r of t.layers)i.has(r.name)&&this._loadNode(r,r._inputs,r._outputs,e,s,o)}_loadSequential(t,e,s,r,n){s&&(this._groups=!0);const i="input";let a=null,o=i,h=0;const u=t.layers?t.layers:t;for(const t of u){let i=h.toString(),l=[o];0==h&&(r&&r.length>0?l=[r[0]]:a=this._getInputType(t)),h++,t.config&&t.config.name&&(i=t.config.name),o=i;let c=[o];h==u.length&&n&&n.length>0&&(c=[n[0]],o=null),this._loadNode(t,l,c,e,s)}r||this._inputs.push(new keras.Parameter(i,!0,[new keras.Argument(i,a,null)])),o&&this._outputs.push(new keras.Parameter(o,!0,[new keras.Argument(o,null,null)]))}_loadNode(t,e,s,r,n,i){const a=t.class_name;switch(a){case"Sequential":{const i=t.name||(t.config?t.config.name:"");this._loadSequential(t.config,r,(n?n+"/":"")+i,e,s);break}case"Model":{const i=t.name||(t.config?t.config.name:"");this._loadModel(t.config,r,(n?n+"/":"")+i,e,s);break}default:{e=e.map((t=>i&&i.has(t)?i.get(t):t));const o=new keras.Node(this._metadata,a,t.config,e,s,n,r);this._nodes.push(o);break}}}_getInputType(t){if(t&&t.config){let e="?",s=[];const r=t.config;return r.dtype&&(e=r.dtype,delete r.dtype),r.batch_input_shape&&(s=r.batch_input_shape.map((t=>null==t?"?":t)),delete r.batch_input_shape),new keras.TensorType(e,new keras.TensorShape(s))}return null}},keras.Parameter=class{constructor(t,e,s){this._name=t,this._visible=e,this._arguments=s}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},keras.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new keras.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},keras.Node=class{constructor(t,e,s,r,n,i,a){this._group=i||"",this._metadata=t,this._type=e;const o=s&&s.name?s.name:"";this._name=(this._group?this._group+"/":"")+o,this._inputs=[],this._outputs=[],this._attributes=[];let h=[o];if(("Bidirectional"==e||"TimeDistributed"==e)&&s&&s.layer){const t=s.layer;delete s.layer,this._inner=new keras.Node(this._metadata,t.class_name,t.config,[],[],null,null),"Bidirectional"==e&&t.config.name&&(h=[o+"/forward_"+t.config.name,o+"/backward_"+t.config.name],i||(i=o))}const u={};if(a)for(const t of h)for(const e of a.get(i,t))r.push(e.name),u[e.name]=e;if(s)for(const e of Object.keys(s)){const r=s[e];"name"!=e&&null!=r&&this._attributes.push(new keras.Attribute(t.attribute(this.type,e),e,r))}const l=this._metadata.type(this.type),c=this.inner?this.inner.type:null,p=c?this._metadata.type(c):null;let _=0;for(;r.length>0;){let t=!1,n=null,i=!0;if(p&&0!=_)switch(e){case"Bidirectional":{let t=_;p&&p.inputs&&(tnew keras.Argument(t,null,u[t])));if(!n&&1==a.length&&a[0].initializer&&a[0].initializer.name)if(1===h.length&&""===h[0])n=a[0].initializer.name;else{const t=a[0].initializer.name.split("/").pop().split(":").shift().split("_"),e=t.pop(),s=t.length>0?[t.pop(),e].join("_"):"";n=new Set(["recurrent_kernel","running_mean","running_std","moving_mean","moving_variance","depthwise_filter","pointwise_filter"]).has(s)?s:e}this._inputs.push(new keras.Parameter(n||_.toString(),i,a)),_++}this._outputs=n.map(((t,e)=>{const s=l&&l.outputs&&et.limit)return r.push(null),r;switch(t.dataType){case"float16":r.push(t.data.getFloat16(t.index,i)),t.index+=2;break;case"float32":r.push(t.data.getFloat32(t.index,i)),t.index+=4;break;case"float64":r.push(t.data.getFloat64(t.index,i)),t.index+=8;break;case"boolean":r.push(0!==t.data.getInt8(t.index)),t.index+=1;break;case"uint8":r.push(t.data.getUint8(t.index)),t.index+=1;break;case"int64":r.push(new long.Long(t.data.getUint32(t.index+(i?0:4),i),t.data.getUint32(t.index+ +(i?4:0),i),!1)),t.index+=8;break;case"string":r.push(t.data[t.index]),t.index++}t.count++}else for(let s=0;st.limit)return r.push(null),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}static _stringify(t,e,s){if(Array.isArray(t)){const r=[];r.push(e+"[");const n=t.map((t=>keras.Tensor._stringify(t,e+s,s)));return n.length>0&&r.push(n.join(",\n")),r.push(e+"]"),r.join("\n")}return null===t?e+"...":"string"==typeof t?e+'"'+t+'"':t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},keras.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},keras.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},keras.Metadata=class{static open(t){return keras.Metadata._metadata?Promise.resolve(keras.Metadata._metadata):t.request(null,"keras-metadata.json","utf-8").then((t=>(keras.Metadata._metadata=new keras.Metadata(t),keras.Metadata._metadata))).catch((()=>(keras.Metadata._metadata=new keras.Metadata(null),keras.Metadata._metadatas)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema))}}type(t){return this._map.get(t)}attribute(t,e){const s=t+":"+e;if(!this._attributeCache.has(s)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const s of e.attributes)this._attributeCache.set(t+":"+s.name,s);this._attributeCache.has(s)||this._attributeCache.set(s,null)}return this._attributeCache.get(s)}},keras.Group=class{constructor(t){this._group=t}attribute(t){let e=this._group.attribute(t);if(!e&&this._group.attribute(t+"0")){let s=0;for(e=[];;){const r=this._group.attribute(t+s.toString());if(!r)break;e=e.concat(r),s++}}return e}group(t){const e=this._group.group(t);return e?new keras.Group(e):null}get value(){return this._group.value}},keras.JsonParser=class{static parse(t){if(t&&(-1!==t.indexOf("NaN")||-1!==t.indexOf("Infinity")))try{return JSON.parse(t)}catch(e){try{return new keras.JsonParser(t)._read()}catch(t){}}return JSON.parse(t)}constructor(t){this._text=t,this._position=0,this._ch=" ",this._escape={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"}}_read(){const t=this._value();return this._whitespace(),this._ch&&this._error("Syntax error"),t}_next(){return this._ch=this._text.charAt(this._position++)}_expect(t){for(let e=0;e="0"&&this._ch<="9";)t+=this._ch,this._next();if("."===this._ch)for(t+=".";this._next()&&this._ch>="0"&&this._ch<="9";)t+=this._ch;if("e"===this._ch||"E"===this._ch)for(t+=this._ch,this._next(),"-"!==this._ch&&"+"!==this._ch||(t+=this._ch,this._next());this._ch>="0"&&this._ch<="9";)t+=this._ch,this._next();return+t}_string(){let t,e,s,r="";if('"'===this._ch)for(;this._next();){if('"'===this._ch)return this._next(),r;if("\\"===this._ch)if(this._next(),"u"===this._ch){for(s=0,e=0;e<4&&(t=parseInt(this._next(),16),isFinite(t));e++)s=16*s+t;r+=String.fromCharCode(s)}else{if(!this._escape[this._ch])break;r+=this._escape[this._ch]}else r+=this._ch}this._error("Invalid string")}_literal(){switch(this._ch){case"t":return this._expect("true"),!0;case"f":return this._expect("false"),!1;case"n":return this._expect("null"),null;case"N":return this._expect("NaN"),NaN;case"I":return this._expect("Infinity"),1/0}this._error("Unexpected '"+this._ch+"'")}_array(){const t=[];if("["===this._ch){if(this._expect("["),this._whitespace(),"]"===this._ch)return this._expect("]"),t;for(;this._ch;){if(t.push(this._value()),this._whitespace(),"]"===this._ch)return this._expect("]"),t;this._expect(","),this._whitespace()}}this._error("Invalid array")}_object(){let t;const e={};if("{"===this._ch){if(this._expect("{"),this._whitespace(),"}"===this._ch)return this._expect("}"),e;for(;this._ch;){if(t=this._string(),this._whitespace(),this._expect(":"),Object.hasOwnProperty.call(e,t)&&this._error('Duplicate key "'+t+'"'),e[t]=this._value(),this._whitespace(),"}"===this._ch)return this._expect("}"),e;this._expect(","),this._whitespace()}}this._error("Invalid object")}_value(){switch(this._whitespace(),this._ch){case"{":return this._object();case"[":return this._array();case'"':return this._string();case"-":return this._number();default:return this._ch>="0"&&this._ch<="9"?this._number():this._literal()}}_error(t){throw new Error(t+" at "+this._position+".")}},keras.Weights=class{constructor(){this._map=new Map}add(t,e){this._map.has(t)||this._map.set(t,[]),this._map.get(t).push(e)}get(t,e){if(t){const s=this._map.get(t.split("/").shift());if(s){const r=s.filter((t=>t.name.startsWith(e+"/")));if(r.length>0)return r;const n=s.filter((s=>s.name.startsWith(t+"/"+e+"/")));if(n.length>0)return n}}else{const s=this._map.get(e);if(s&&s.length>0)return s;const r=this._map.get("");if(r&&r.length>0){const s=r.filter((s=>s.name.startsWith((t?t+"/":"")+e+"/")));if(s.length>0)return s}}return[]}keys(){return this._map.keys()}},keras.Error=class extends Error{constructor(t){super(t),this.name="Error loading Keras model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=keras.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mediapipe.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mediapipe.js new file mode 100644 index 0000000000000000000000000000000000000000..c31ce0e061988385099059f2a75d9e71481321b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mediapipe.js @@ -0,0 +1 @@ +var mediapipe=mediapipe||{},protobuf=protobuf||require("./protobuf");mediapipe.ModelFactory=class{match(t){if("pbtxt"===t.identifier.split(".").pop().toLowerCase()){const e=t.tags("pbtxt"),i=t.text;if(e.has("node")&&(-1!==i.indexOf("input_stream:")||-1!==i.indexOf("input_side_packet:")||-1!==i.indexOf("output_stream:")))return!0}return!1}open(t,e){const i=t.identifier;try{const e=protobuf.TextReader.create(t.text),i=new mediapipe.Object(e);return Promise.resolve(new mediapipe.Model(i))}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();return Promise.reject(new mediapipe.Error(s.replace(/\.$/,"")+" in '"+i+"'."))}}},mediapipe.Model=class{constructor(t){this._graphs=[new mediapipe.Graph(t)]}get format(){return"MediaPipe"}get graphs(){return this._graphs}},mediapipe.Graph=class{constructor(t){if(this._inputs=[],this._outputs=[],this._nodes=[],t){if(t.input_stream){const e=Array.isArray(t.input_stream)?t.input_stream:[t.input_stream];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._inputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.output_stream){const e=Array.isArray(t.output_stream)?t.output_stream:[t.output_stream];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._outputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.input_side_packet){const e=Array.isArray(t.input_side_packet)?t.input_side_packet:[t.input_side_packet];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._inputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.output_side_packet){const e=Array.isArray(t.output_side_packet)?t.output_side_packet:[t.output_side_packet];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._outputs.push(new mediapipe.Parameter(t,[new mediapipe.Argument(s,i,null)]))}}if(t.node){const e=Array.isArray(t.node)?t.node:[t.node];for(const t of e)this._nodes.push(new mediapipe.Node(t))}}}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},mediapipe.Node=class{constructor(t){if(this._type=t.calculator||"?",this._type=this._type.replace(/Calculator$/,""),this._inputs=[],this._outputs=[],this._attributes=[],t.input_stream){const e=[],i=Array.isArray(t.input_stream)?t.input_stream:[t.input_stream];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._inputs.push(new mediapipe.Parameter("input_stream",e))}if(t.output_stream){const e=[],i=Array.isArray(t.output_stream)?t.output_stream:[t.output_stream];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._outputs.push(new mediapipe.Parameter("output_stream",e))}if(t.input_side_packet){const e=[],i=Array.isArray(t.input_side_packet)?t.input_side_packet:[t.input_side_packet];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._inputs.push(new mediapipe.Parameter("input_side_packet",e))}if(t.output_side_packet){const e=[],i=Array.isArray(t.output_side_packet)?t.output_side_packet:[t.output_side_packet];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._outputs.push(new mediapipe.Parameter("output_side_packet",e))}const e=t.options||t.node_options||null;if(e)for(const t of Object.keys(e)){if("__type__"===t)continue;const i=e[t];this._attributes.push(new mediapipe.Attribute(t,i))}}get name(){return""}get type(){return this._type}get metadata(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mediapipe.Attribute=class{constructor(t,e){this._name=t,this._value=e}get name(){return this._name}get value(){return this._value}get visible(){return!0}},mediapipe.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mediapipe.Argument=class{constructor(t,e,i){if("string"!=typeof t)throw new mediapipe.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=i||null}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get initializer(){return this._initializer}},mediapipe.Object=class{constructor(t){t.start();let e=!1;const i=t.peek();i.startsWith("[")&&i.endsWith("]")&&(this.__type__=t.read().substring(0,i.length-1),t.match(":"),t.start(),e=!0);const s=new Set;for(;!t.end();){var r=t.tag(),p=t.peek(),n=null;if("{"===p)n=new mediapipe.Object(t);else if(p.startsWith('"')&&p.endsWith('"'))n=t.read().substring(1,p.length-1);else if("true"===p||"false"===p)n=t.read();else if(t.first())for(n=[];!t.last();){const e=t.read();isNaN(e)||n.push(parseFloat(e))}else n=isNaN(p)?t.read():parseFloat(t.read());!this[r]||Array.isArray(this[r])&&!s.has(r)||(this[r]=[this[r]],s.delete(r)),this[r]?this[r].push(n):(Array.isArray(n)&&s.add(r),this[r]=n)}e&&t.expect("}")}},mediapipe.Error=class extends Error{constructor(t){super(t),this.name="Error loading MediaPipe model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mediapipe.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5b70a93fb9c04be0af3f95e68cfc5b79ca7fcf17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet-metadata.json @@ -0,0 +1 @@ +[{"name":"ImageLoaderTransform","schema":{"description":"Load images from files.","attributes":[{"name":"ImageFolder","type":"string","description":"Folder where to search for images"}]}},{"name":"ImageScalerTransform","schema":{"description":"Scales an image to specified dimensions using one of the three scale types: isotropic with padding, isotropic with cropping or anisotropic. In case of isotropic padding, transparent color is used to pad resulting image.","attributes":[{"name":"Width"},{"name":"Height"},{"name":"Resizing","type":"ImageResizingTransformer.ResizingKind"},{"name":"Anchor","type":"ImageResizingTransformer.Anchor"}]}},{"name":"ImagePixelExtractor","schema":{"description":"Scales an image to specified dimensions using one of the three scale types: isotropic with padding, isotropic with cropping or anisotropic. In case of isotropic padding, transparent color is used to pad resulting image.","attributes":[{"name":"ColorsToExtract","type":"ImagePixelExtractingTransformer.ColorBits"},{"name":"OrderOfExtraction","type":"ImagePixelExtractingTransformer.ColorsOrder"},{"name":"Planes","type":"uint8"},{"name":"OutputAsFloatArray","type":"boolean"},{"name":"OffsetImage","type":"float32"},{"name":"ScaleImage","type":"float32"},{"name":"InterleavePixelColors","type":"boolean"}]}},{"name":"TensorFlowTransform","schema":{"description":"Transforms the data using the TensorFlow model.","attributes":[{"name":"IsFrozen","type":"boolean"},{"name":"AddBatchDimensionInput","type":"boolean"}]}},{"name":"TextNormalizerTransform","schema":{"description":"A text normalization transform that allows normalizing text case, removing diacritical marks, punctuation marks and/or numbers. The transform operates on text input as well as vector of tokens/text (vector of ReadOnlyMemory).","attributes":[{"name":"CaseMode","type":"TextNormalizingTransformer.CaseMode"},{"name":"KeepDiacritics","type":"boolean"},{"name":"KeepPunctuations","type":"boolean"},{"name":"KeepNumbers","type":"boolean"}]}},{"name":"CharToken","schema":{"description":"Character-oriented tokenizer where text is considered a sequence of characters.","attributes":[{"name":"UseMarkerChars","type":"boolean"},{"name":"IsSeparatorStartEnd","type":"boolean"}]}},{"name":"ConcatTransform","schema":{"category":"Tensor","description":"Concatenates one or more columns of the same item type."}},{"name":"CopyTransform","schema":{"category":"Tensor","description":"Duplicates columns from the dataset."}},{"name":"SSAModel","schema":{"attributes":[{"name":"UseMarkerChars","type":"boolean"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet.js new file mode 100644 index 0000000000000000000000000000000000000000..e8bb9c4b0ee1b17f19de32efbf8828919042b3c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mlnet.js @@ -0,0 +1 @@ +var mlnet=mlnet||{},zip=zip||require("./zip");mlnet.ModelFactory=class{match(e){if("zip"===e.identifier.split(".").pop().toLowerCase()){const t=e.entries("zip");if(t.length>0){const e=new Set(["TransformerChain","Predictor"]);if(t.some((t=>e.has(t.name.split("\\").shift().split("/").shift()))))return!0}}return!1}open(e,t){const s=e.identifier;return mlnet.Metadata.open(t).then((t=>{try{const s=new mlnet.ModelReader(e.entries("zip"));return new mlnet.Model(t,s)}catch(e){const t=e&&e.message?e.message:e.toString();throw new mlnet.Error(t.replace(/\.$/,"")+" in '"+s+"'.")}}))}},mlnet.Model=class{constructor(e,t){this._format="ML.NET",t.version&&t.version.length>0&&(this._format+=" v"+t.version),this._graphs=[],this._graphs.push(new mlnet.Graph(e,t))}get format(){return this._format}get graphs(){return this._graphs}},mlnet.Graph=class{constructor(e,t){if(this._inputs=[],this._outputs=[],this._nodes=[],this._groups=!1,t.schema&&t.schema.inputs)for(const e of t.schema.inputs)this._inputs.push(new mlnet.Parameter(e.name,[new mlnet.Argument(e.name,new mlnet.TensorType(e.type))]));const s=new Map;t.dataLoaderModel&&this._loadTransformer(e,s,"",t.dataLoaderModel),t.predictor&&this._loadTransformer(e,s,"",t.predictor),t.transformerChain&&this._loadTransformer(e,s,"",t.transformerChain)}_loadTransformer(e,t,s,r){switch(r.__type__){case"TransformerChain":case"Text":this._loadChain(e,t,r.__name__,r.chain);break;default:this._createNode(e,t,s,r)}}_loadChain(e,t,s,r){this._groups=!0;const n=s.split("/").splice(1).join("/");for(const s of r)this._loadTransformer(e,t,n,s)}_createNode(e,t,s,r){if(r.inputs&&r.outputs){for(const e of r.inputs)e.name=t[e.name]?t[e.name].argument:e.name;for(const e of r.outputs)if(t[e.name]){t[e.name].counter++;const s=e.name+"\n"+t[e.name].counter.toString();t[e.name].argument=s,e.name=s}else t[e.name]={argument:e.name,counter:0}}this._nodes.push(new mlnet.Node(e,s,r))}get groups(){return this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},mlnet.Parameter=class{constructor(e,t){this._name=e,this._arguments=t}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mlnet.Argument=class{constructor(e,t){if("string"!=typeof e)throw new mlnet.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t}get name(){return this._name}get type(){return this._type}},mlnet.Node=class{constructor(e,t,s){if(this._metadata=e,this._group=t,this._name=s.__name__,this._type=s.__type__,this._inputs=[],this._outputs=[],this._attributes=[],s.inputs){let e=0;for(const t of s.inputs)this._inputs.push(new mlnet.Parameter(e.toString(),[new mlnet.Argument(t.name)])),e++}if(s.outputs){let e=0;for(const t of s.outputs)this._outputs.push(new mlnet.Parameter(e.toString(),[new mlnet.Argument(t.name)])),e++}for(const t of Object.keys(s).filter((e=>!e.startsWith("_")&&"inputs"!==e&&"outputs"!==e))){const r=e.attribute(this._type,this._name);this._attributes.push(new mlnet.Attribute(r,t,s[t]))}}get group(){return this._group}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mlnet.Attribute=class{constructor(e,t,s){if(this._name=t,this._value=s,e&&(e.type&&(this._type=e.type),this._type)){let e=mlnet;const t=this._type.split(".");for(;e&&t.length>0;)e=e[t.shift()];if(e){mlnet.Attribute._reverseMap=mlnet.Attribute._reverseMap||{};let t=mlnet.Attribute._reverseMap[this._type];if(!t){t={};for(const s of Object.keys(e))t[e[s.toString()]]=s;mlnet.Attribute._reverseMap[this._type]=t}Object.prototype.hasOwnProperty.call(t,this._value)&&(this._value=t[this._value])}}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return!0}},mlnet.TensorType=class{constructor(e){if(mlnet.TensorType._map=mlnet.TensorType._map||new Map([["Byte","uint8"],["Boolean","boolean"],["Single","float32"],["Double","float64"],["UInt32","uint32"],["TextSpan","string"]]),this._dataType="?",this._shape=new mlnet.TensorShape(null),mlnet.TensorType._map.has(e.name))this._dataType=mlnet.TensorType._map.get(e.name);else if("VBuffer"==e.name){if(!mlnet.TensorType._map.has(e.itemType.name))throw new mlnet.Error("Unknown data type '"+e.itemType.name+"'.");this._dataType=mlnet.TensorType._map.get(e.itemType.name),this._shape=new mlnet.TensorShape(e.dims)}else{if("Key2"!=e.name)throw new mlnet.Error("Unknown data type '"+e.name+"'.");this._dataType="key2"}}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},mlnet.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},mlnet.Metadata=class{static open(e){return mlnet.Metadata._metadata?Promise.resolve(mlnet.Metadata._metadata):e.request(null,"mlnet-metadata.json","utf-8").then((e=>(mlnet.Metadata._metadata=new mlnet.Metadata(e),mlnet.Metadata._metadata))).catch((()=>(mlnet.Metadata._metadata=new mlnet.Metadata(null),mlnet.Metadata._metadatas)))}constructor(e){if(this._map={},this._attributeCache={},e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map[e.name]=e.schema)}}type(e){return this._map[e]||null}attribute(e,t){let s=this._attributeCache[e];if(!s){s={};const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const e of t.attributes)s[e.name]=e;this._attributeCache[e]=s}return s[t]||null}},mlnet.ModelReader=class{constructor(e){const t=new mlnet.ComponentCatalog;t.register("AffineNormExec",mlnet.AffineNormSerializationUtils),t.register("AnomalyPredXfer",mlnet.AnomalyPredictionTransformer),t.register("BinaryPredXfer",mlnet.BinaryPredictionTransformer),t.register("BinaryLoader",mlnet.BinaryLoader),t.register("CaliPredExec",mlnet.CalibratedPredictor),t.register("CdfNormalizeFunction",mlnet.CdfColumnFunction),t.register("CharToken",mlnet.TokenizingByCharactersTransformer),t.register("ChooseColumnsTransform",mlnet.ColumnSelectingTransformer),t.register("ClusteringPredXfer",mlnet.ClusteringPredictionTransformer),t.register("ConcatTransform",mlnet.ColumnConcatenatingTransformer),t.register("CopyTransform",mlnet.ColumnCopyingTransformer),t.register("ConvertTransform",mlnet.TypeConvertingTransformer),t.register("CSharpTransform",mlnet.CSharpTransform),t.register("DropColumnsTransform",mlnet.DropColumnsTransform),t.register("FAFMPredXfer",mlnet.FieldAwareFactorizationMachinePredictionTransformer),t.register("FastForestBinaryExec",mlnet.FastForestClassificationPredictor),t.register("FastTreeBinaryExec",mlnet.FastTreeBinaryModelParameters),t.register("FastTreeTweedieExec",mlnet.FastTreeTweedieModelParameters),t.register("FastTreeRankerExec",mlnet.FastTreeRankingModelParameters),t.register("FastTreeRegressionExec",mlnet.FastTreeRegressionModelParameters),t.register("FeatWCaliPredExec",mlnet.FeatureWeightsCalibratedModelParameters),t.register("FieldAwareFactMacPredict",mlnet.FieldAwareFactorizationMachineModelParameters),t.register("GcnTransform",mlnet.LpNormNormalizingTransformer),t.register("GenericScoreTransform",mlnet.GenericScoreTransform),t.register("IidChangePointDetector",mlnet.IidChangePointDetector),t.register("IidSpikeDetector",mlnet.IidSpikeDetector),t.register("ImageClassificationTrans",mlnet.ImageClassificationTransformer),t.register("ImageClassificationPred",mlnet.ImageClassificationModelParameters),t.register("ImageLoaderTransform",mlnet.ImageLoadingTransformer),t.register("ImageScalerTransform",mlnet.ImageResizingTransformer),t.register("ImagePixelExtractor",mlnet.ImagePixelExtractingTransformer),t.register("KeyToValueTransform",mlnet.KeyToValueMappingTransformer),t.register("KeyToVectorTransform",mlnet.KeyToVectorMappingTransformer),t.register("KMeansPredictor",mlnet.KMeansModelParameters),t.register("LinearRegressionExec",mlnet.LinearRegressionModelParameters),t.register("LightGBMRegressionExec",mlnet.LightGbmRegressionModelParameters),t.register("LightGBMBinaryExec",mlnet.LightGbmBinaryModelParameters),t.register("Linear2CExec",mlnet.LinearBinaryModelParameters),t.register("LinearModelStats",mlnet.LinearModelParameterStatistics),t.register("MaFactPredXf",mlnet.MatrixFactorizationPredictionTransformer),t.register("MFPredictor",mlnet.MatrixFactorizationModelParameters),t.register("MulticlassLinear",mlnet.LinearMulticlassModelParameters),t.register("MultiClassLRExec",mlnet.MaximumEntropyModelParameters),t.register("MultiClassNaiveBayesPred",mlnet.NaiveBayesMulticlassModelParameters),t.register("MultiClassNetPredictor",mlnet.MultiClassNetPredictor),t.register("MulticlassPredXfer",mlnet.MulticlassPredictionTransformer),t.register("NgramTransform",mlnet.NgramExtractingTransformer),t.register("NgramHashTransform",mlnet.NgramHashingTransformer),t.register("NltTokenizeTransform",mlnet.NltTokenizeTransform),t.register("Normalizer",mlnet.NormalizingTransformer),t.register("NormalizeTransform",mlnet.NormalizeTransform),t.register("OnnxTransform",mlnet.OnnxTransformer),t.register("OptColTransform",mlnet.OptionalColumnTransform),t.register("OVAExec",mlnet.OneVersusAllModelParameters),t.register("pcaAnomExec",mlnet.PcaModelParameters),t.register("PcaTransform",mlnet.PrincipalComponentAnalysisTransformer),t.register("PipeDataLoader",mlnet.CompositeDataLoader),t.register("PlattCaliExec",mlnet.PlattCalibrator),t.register("PMixCaliPredExec",mlnet.ParameterMixingCalibratedModelParameters),t.register("PoissonRegressionExec",mlnet.PoissonRegressionModelParameters),t.register("ProtonNNMCPred",mlnet.ProtonNNMCPred),t.register("RegressionPredXfer",mlnet.RegressionPredictionTransformer),t.register("RowToRowMapper",mlnet.RowToRowMapperTransform),t.register("SsaForecasting",mlnet.SsaForecastingTransformer),t.register("SSAModel",mlnet.AdaptiveSingularSpectrumSequenceModelerInternal),t.register("SelectColumnsTransform",mlnet.ColumnSelectingTransformer),t.register("StopWordsTransform",mlnet.StopWordsTransform),t.register("TensorFlowTransform",mlnet.TensorFlowTransformer),t.register("TermLookupTransform",mlnet.ValueMappingTransformer),t.register("TermTransform",mlnet.ValueToKeyMappingTransformer),t.register("TermManager",mlnet.TermManager),t.register("Text",mlnet.TextFeaturizingEstimator),t.register("TextLoader",mlnet.TextLoader),t.register("TextNormalizerTransform",mlnet.TextNormalizingTransformer),t.register("TokenizeTextTransform",mlnet.WordTokenizingTransformer),t.register("TransformerChain",mlnet.TransformerChain),t.register("ValueMappingTransformer",mlnet.ValueMappingTransformer),t.register("XGBoostMulticlass",mlnet.XGBoostMulticlass);const s=new mlnet.ModelHeader(t,e,"",null),r=s.openText("TrainingInfo/Version.txt");r&&(this.version=r.split(" ").shift().split("\r").shift());const n=s.openBinary("Schema");n&&(this.schema=new mlnet.BinaryLoader(null,n).schema);const i=s.open("TransformerChain");i&&(this.transformerChain=i);const o=s.open("DataLoaderModel");o&&(this.dataLoaderModel=o);const a=s.open("Predictor");a&&(this.predictor=a)}},mlnet.ComponentCatalog=class{constructor(){this._map=new Map}register(e,t){this._map.set(e,t)}create(e,t){if(!this._map.has(e))throw new mlnet.Error("Unknown loader signature '"+e+"'.");const s=this._map.get(e);return Reflect.construct(s,[t])}},mlnet.ModelHeader=class{constructor(e,t,s,r){if(this._entries=t,this._catalog=e,this._directory=s,r){const e=new mlnet.Reader(r),t=new TextDecoder("ascii");e.assert("ML\0MODEL"),this.versionWritten=e.uint32(),this.versionReadable=e.uint32();const s=e.uint64();e.uint64();const n=e.uint64(),i=e.uint64(),o=e.uint64();e.uint64(),this.modelSignature=t.decode(e.bytes(8)),this.modelVersionWritten=e.uint32(),this.modelVersionReadable=e.uint32(),this.loaderSignature=t.decode(e.bytes(24).filter((e=>0!=e))),this.loaderSignatureAlt=t.decode(e.bytes(24).filter((e=>0!=e)));const a=e.uint64();e.uint64();const l=e.uint64(),m=e.uint32();if(0!=n&&0!=o){e.position=n;const t=i>>3,s=[];let r=0;for(let n=0;n>1;let n="";for(let s=0;s0?this._directory+"/":this._directory)+e)+"/Model.key",s=this._entries.find((e=>e.name==t||e.name==t.replace(/\//g,"\\")));if(s){const t=new mlnet.ModelHeader(this._catalog,this._entries,e,s.data),r=this._catalog.create(t.loaderSignature,t);return r.__type__=r.__type__||t.loaderSignature,r.__name__=e,r}return null}openBinary(e){const t=this._directory.length>0?this._directory+"/":this._directory;e=t+e;const s=this._entries.find((t=>t.name==e||t.name==e.replace(/\//g,"\\")));return s?new mlnet.Reader(s.data):null}openText(e){const t=this._directory.length>0?this._directory+"/":this._directory;e=t+e;const s=this._entries.find((t=>t.name.split("\\").join("/")==e));return s?(new TextDecoder).decode(s.data):null}check(e,t,s){return e===this.modelSignature&&t>=this.modelVersionReadable&&s<=this.modelVersionWritten}},mlnet.Reader=class{constructor(e){this._buffer=e,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._position=0}set position(e){this._position=e}get position(){return this._position}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new mlnet.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}match(e){const t=this._position;for(let s=0;s1048576)throw new mlnet.Error("Value not in 48-bit range.");return 4294967296*t+e}float32(){const e=this._position;return this.skip(4),this._dataView.getFloat32(e,!0)}float32s(e){const t=[];for(let s=0;s=65538&&(this.Threads=e.reader.int32(),this.GeneratedRowIndexName=e.string(null)),this.ShuffleBlocks=e.modelVersionWritten>=65539?e.reader.float64():4,t=e.openBinary("Schema.idv")),t.assert("CML\0DVB\0"),t.bytes(8),t.bytes(8);const s=t.uint64(),r=t.int64();t.int64();const n=t.int32();t.position=r,t.assert("\0BVD\0LMC"),t.position=s,this.schema={},this.schema.inputs=[];for(let e=0;e=65539){const s=t.int32();for(let r=0;r=65538)for(let r=0;r=65538)for(;;){const r=t.int32();if(-1==r)break;s[r]=e.string()}}if(s>1)throw new mlnet.Error("");this.outputs=[];for(let e=0;e0&&this._featureHistogram.push(t.int32s(this._featureCount));this._absentFeaturesLogProb=t.float64s(this._labelHistogram.length)}},mlnet.LinearModelParameters=class extends mlnet.ModelParametersBase{constructor(e){super(e);const t=e.reader;this.Bias=t.float32(),t.int32(),this.Indices=t.int32s(t.int32()),this.Weights=t.float32s(t.int32())}},mlnet.LinearBinaryModelParameters=class extends mlnet.LinearModelParameters{constructor(e){super(e),e.modelVersionWritten>131073&&(this.Statistics=e.open("ModelStats"))}},mlnet.ModelStatisticsBase=class{constructor(e){const t=e.reader;this.ParametersCount=t.int32(),this.TrainingExampleCount=t.int64(),this.Deviance=t.float32(),this.NullDeviance=t.float32()}},mlnet.LinearModelParameterStatistics=class extends mlnet.ModelStatisticsBase{constructor(e){super(e);const t=e.reader;if(e.modelVersionWritten<65538&&!t.boolean())return;const s=t.float32s(this.ParametersCount);t.int32()==this.ParametersCount||(this.stdErrorIndices=t.int32s(this.ParametersCount)),this._coeffStdError=s,this._bias=t.float32();const r=t.byte(),n=t.int32(),i=t.float32s(n);r?this._weights=i:this.weightsIndices=t.int32s(n)}},mlnet.LinearMulticlassModelParametersBase=class extends mlnet.ModelParametersBase{constructor(e){super(e);const t=e.reader,s=t.int32(),r=t.int32();if(this.Biases=t.float32s(r),0==t.int32()){t.int32(),t.int32(),this.Weights=[];for(let e=0;e=65538;s.NgramLength=t.int32(),s.SkipLength=t.int32(),r&&(s.Weighting=t.int32()),s.NonEmptyLevels=t.booleans(s.NgramLength),s.NgramMap=new mlnet.SequencePool(t),r&&(s.InvDocFreqs=t.float64s(t.int32()))}},mlnet.NgramHashingTransformer=class extends mlnet.RowToRowTransformerBase{constructor(e){super(e);const t=e.modelVersionWritten<65539,s=e.reader;t&&s.int32(),this.inputs=[],this.outputs=[];const r=s.int32();if(t);else for(let t=0;t>1&5),r=(3&r)+(r>>2&3),s.Planes=255&r,s.OutputAsFloatArray=t.boolean(),s.OffsetImage=t.float32(),s.ScaleImage=t.float32(),s.InterleavePixelColors=t.boolean()}},mlnet.ImagePixelExtractingTransformer.ColorBits={Alpha:1,Red:2,Green:4,Blue:8,Rgb:14,All:15},mlnet.ImagePixelExtractingTransformer.ColorsOrder={ARGB:1,ARBG:2,ABRG:3,ABGR:4,AGRB:5,AGBR:6},mlnet.NormalizingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e);const t=e.reader;this.Options=[];for(let s=0;se.toString())).join(",")+"]":""),l="Normalizer_"+("00"+s).slice(-3),m=e.open(l);this.Options.push({type:a,func:m})}}},mlnet.KeyToValueMappingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e)}},mlnet.ValueToKeyMappingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e);const t=e.reader;if(e.modelVersionWritten>=65539)this.textMetadata=t.booleans(this.outputs.length+this.inputs.length);else{this.textMetadata=[];for(let e=0;e=65538))throw new mlnet.Error("Unsupported TermManager version.");for(let s=0;s=65538&&(t=e.string(),s=e.string(null)),r.push([t,s])}this.chain=[];for(let t=0;t65537?t.int32():1;this.inputs=[];for(let t=0;t65537?t.int32():1;this.outputs=[];for(let t=0;t65548){const s=t.int32();this.LoadedCustomShapeInfos=[];for(let r=0;r=65538)||t.boolean(),this.AddBatchDimensionInput=!(e.modelVersionReadable>=65539)||t.boolean();const s=t.int32();this.inputs=[];for(let t=0;t=65538?t.int32():1;this.outputs=[];for(let t=0;t=65538?t.int32():this.Dimensionality,r=s=this.VerDefaultValueSerialized,r=e.modelVersionWritten>=this.VerCategoricalSplitSerialized;this.TrainedEnsemble=new mlnet.InternalTreeEnsemble(e,s,r),this.InnerOptions=e.string(null),e.modelVersionWritten>=this.verNumFeaturesSerialized&&(this.NumFeatures=t.int32())}},mlnet.InternalTreeEnsemble=class{constructor(e,t,s){const r=e.reader;this.Trees=[];const n=r.int32();for(let i=0;i0){this.CategoricalSplitFeatures=[],this.CategoricalSplitFeatureRanges=[];for(const t of e)this.CategoricalSplitFeatures[t]=r.int32s(r.int32()),this.CategoricalSplitFeatureRanges[t]=r.int32s(2)}}this.Thresholds=r.uint32s(r.int32()),this.RawThresholds=r.float32s(r.int32()),this.DefaultValueForMissing=t?r.float32s(r.int32()):null,this.LeafValues=r.float64s(r.int32()),this.SplitGain=r.float64s(r.int32()),this.GainPValue=r.float64s(r.int32()),this.PreviousLeafValue=r.float64s(r.int32())}},mlnet.InternalTreeEnsemble.TreeType={Regression:0,Affine:1,FastForest:2},mlnet.TreeEnsembleModelParametersBasedOnRegressionTree=class extends mlnet.TreeEnsembleModelParameters{constructor(e){super(e)}},mlnet.FastTreeTweedieModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65537}get VerDefaultValueSerialized(){return 65538}get VerCategoricalSplitSerialized(){return 65539}},mlnet.FastTreeRankingModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FastTreeBinaryModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FastTreeRegressionModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.LightGbmRegressionModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.LightGbmBinaryModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FeatureWeightsCalibratedModelParameters=class extends mlnet.ValueMapperCalibratedModelParametersBase{constructor(e){super(e)}},mlnet.FastTreePredictionWrapper=class{constructor(){}},mlnet.FastForestClassificationPredictor=class extends mlnet.FastTreePredictionWrapper{constructor(e){super(e)}},mlnet.PlattCalibrator=class{constructor(e){const t=e.reader;this.ParamA=t.float64(),this.ParamB=t.float64()}},mlnet.Codec=class{constructor(e){this.name=e.string();const t=e.leb128(),s=e.bytes(t);switch(e=new mlnet.Reader(s),this.name){case"Boolean":case"Single":case"Double":case"Byte":case"Int32":case"UInt32":case"Int64":case"TextSpan":break;case"VBuffer":this.itemType=new mlnet.Codec(e),this.dims=e.int32s(e.int32());break;case"Key":case"Key2":this.itemType=new mlnet.Codec(e),this.count=e.uint64();break;default:throw new mlnet.Error("Unknown codec '"+this.name+"'.")}}read(e,t){const s=[];switch(this.name){case"Single":for(let r=0;r=65538&&(this._state=t.float32s(t.int32())),this.ShouldComputeForecastIntervals=t.byte(),this._observationNoiseVariance=t.float32(),this._autoregressionNoiseVariance=t.float32(),this._observationNoiseMean=t.float32(),this._autoregressionNoiseMean=t.float32(),e.modelVersionReadable>=65538&&(this._nextPrediction=t.float32()),this._maxRank=t.int32(),this._shouldStablize=t.byte(),this._shouldMaintainInfo=t.byte(),this._maxTrendRatio=t.float64(),s&&(this._wTrans=t.float32s(t.int32()),this._y=t.float32s(t.int32())),this._buffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t)}},mlnet.SequentialForecastingTransformBase=class extends mlnet.SequentialTransformerBase{constructor(e){super(e);const t=e.reader;this._outputLength=t.int32()}},mlnet.SsaForecastingBaseWrapper=class extends mlnet.SequentialForecastingTransformBase{constructor(e){super(e);const t=e.reader;this.IsAdaptive=t.boolean(),this.Horizon=t.int32(),this.ConfidenceLevel=t.float32(),this.WindowedBuffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t),this.InitialWindowedBuffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t),this.Model=e.open("SSA")}},mlnet.SsaForecastingTransformer=class extends mlnet.SsaForecastingBaseWrapper{constructor(e){super(e)}},mlnet.ColumnSelectingTransformer=class{constructor(e){const t=e.reader;if(e.check("DRPCOLST",65538,65538))throw new mlnet.Error("'LoadDropColumnsTransform' not supported.");if(e.check("CHSCOLSF",65537,65537)){t.int32(),this.KeepHidden=this._getHiddenOption(t.byte());const s=t.int32();this.inputs=[];for(let r=0;rmnn.Metadata.open(t).then((n=>{const a=e.identifier;try{mnn.schema=flatbuffers.get("mnn").MNN;const t=new flatbuffers.Reader(e.buffer),a=mnn.schema.Net.create(t);return new mnn.Model(n,a)}catch(e){t.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new mnn.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}}))))}},mnn.Model=class{constructor(e,t){switch(t.sourceType){case mnn.schema.NetSource.CAFFE:this._source="Caffe";break;case mnn.schema.NetSource.TENSORFLOW:this._source="TensorFlow";break;case mnn.schema.NetSource.TFLITE:this._source="TensorFlow Lite";break;case mnn.schema.NetSource.ONNX:this._source="ONNX"}this._graphs=[new mnn.Graph(e,t)]}get format(){return"MNN v2"}get source(){return this._source||""}get graphs(){return this._graphs}},mnn.Graph=class{constructor(e,t){this._nodes=[],this._inputs=[],this._outputs=[];const n=new Set;for(let a=0;a0&&this._buildAttributes(e,i,t,this._attributes)}}_buildTensor(e,t,n,a){this._inputs.push(new mnn.Parameter(t,!0,[new mnn.Argument("",null,new mnn.Tensor("Weight",new mnn.TensorType(e,new mnn.TensorShape(n)),a))]))}_buildAttributes(e,t,n,a){if(t)for(const s of Object.keys(t)){if(n&&n.has(s))continue;const i=t[s];if(Object.keys(mnn.schema).find((e=>mnn.schema[e].prototype&&i instanceof mnn.schema[e])))this._buildAttributes(e,i,null,a);else if(i){const t=e.attribute(this.type,s);a.push(new mnn.Attribute(t,s,i))}}}get type(){return this._type}get name(){return this._name}get domain(){return null}get metadata(){return this._metadata.type(this.type)}get group(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chains}get attributes(){return this._attributes}},mnn.Attribute=class{constructor(e,t,n,a){if(this._type=null,this._value=ArrayBuffer.isView(n)?Array.from(n):n,this._name=t,this._visible=a,e&&e.type){this._type=e.type;const t=mnn.schema[this._type+"Name"];t&&(this._value=t[this._value])}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},mnn.Parameter=class{constructor(e,t,n){this._name=e,this._visible=t,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},mnn.Argument=class{constructor(e,t,n){this._name=e,this._type=t||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},mnn.Tensor=class{constructor(e,t,n){this._kind=e,this._type=t,this._data=n.slice(0)}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);return JSON.stringify(t,null,4)}_context(){const e={state:null};return this._data&&0!==this._data.length?(e.index=0,e.count=0,e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,e.data=this._data,e):(e.state="Tensor data is empty.",e)}_decode(e,t){let n=e.dimensions;0==n.length&&(n=[1]);const a=[],s=n[t];if(t==n.length-1)for(let t=0;te.limit)return a.push("..."),a;a.push(e.data[e.index]),e.index++,e.count++}else for(let n=0;ne.limit)return a.push("..."),a;a.push(this._decode(e,t+1))}return 0==e.dimensions.length?a[0]:a}},mnn.TensorType=class{constructor(e,t){switch(e){case mnn.schema.DataType.DT_INVALID:this._dataType="?";break;case mnn.schema.DataType.DT_FLOAT:this._dataType="float32";break;case mnn.schema.DataType.DT_DOUBLE:this._dataType="float64";break;case mnn.schema.DataType.DT_INT32:this._dataType="int32";break;case mnn.schema.DataType.DT_UINT8:this._dataType="uint8";break;case mnn.schema.DataType.DT_INT16:this._dataType="int16";break;case mnn.schema.DataType.DT_INT8:this._dataType="int8";break;case mnn.schema.DataType.DT_STRING:this._dataType="string";break;case mnn.schema.DataType.DT_COMPLEX64:this._dataType="complex64";break;case mnn.schema.DataType.DT_INT64:this._dataType="int64";break;case mnn.schema.DataType.DT_BOOL:this._dataType="boolean";break;case mnn.schema.DataType.DT_QINT8:this._dataType="qint8";break;case mnn.schema.DataType.DT_QUINT8:this._dataType="quint8";break;case mnn.schema.DataType.DT_QINT32:this._dataType="qint32";break;case mnn.schema.DataType.DT_BFLOAT16:this._dataType="bfloat16";break;case mnn.schema.DataType.DT_QINT16:this._dataType="qint16";break;case mnn.schema.DataType.DT_QUINT16:this._dataType="quint16";break;case mnn.schema.DataType.DT_UINT16:this._dataType="uint16";break;case mnn.schema.DataType.DT_COMPLEX128:this._dataType="complex128";break;case mnn.schema.DataType.DT_HALF:this._dataType="float16";break;case mnn.schema.DataType.DT_RESOURCE:this._dataType="resource";break;case mnn.schema.DataType.DT_VARIANT:this._dataType="variant";break;default:throw new mnn.Error("Unknown data type '"+JSON.stringify(e)+"'.")}this._shape=t}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},mnn.TensorShape=class{constructor(e){this._dimensions=Array.from(e)}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length>0?"["+this._dimensions.map((e=>e?e.toString():"?")).join(",")+"]":""}},mnn.Metadata=class{static open(e){return mnn.Metadata._metadata?Promise.resolve(mnn.Metadata._metadata):e.request(null,"mnn-metadata.json","utf-8").then((e=>(mnn.Metadata._metadata=new mnn.Metadata(e),mnn.Metadata._metadata))).catch((()=>(mnn.Metadata._metadata=new mnn.Metadata(null),mnn.Metadata._metadata)))}constructor(e){if(this._map=new Map,e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.has(e)?this._map.get(e):null}attribute(e,t){const n=this.type(e);if(n){let e=n.attributeMap;if(!e){if(e={},n.attributes)for(const t of n.attributes)e[t.name]=t;n.attributeMap=e}const a=e[t];if(a)return a}return null}},mnn.Utility=class{static enum(e,t){const n=e&&mnn.schema?mnn.schema[e]:void 0;if(n){if(mnn.Utility._enumKeyMap=mnn.Utility._enumKeyMap||new Map,!mnn.Utility._enumKeyMap.has(e)){const t=new Map;for(const e of Object.keys(n))t.set(n[e],e);mnn.Utility._enumKeyMap.set(e,t)}const a=mnn.Utility._enumKeyMap.get(e);if(a.has(t))return a.get(t)}return t}},mnn.Error=class extends Error{constructor(e){super(e),this.name="Error loading MNN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0ccc4bade96f31cc62762bbe777ffd8deb9c02cb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"attributes":[{"default":false,"name":"cudnn_off","type":"boolean"},{"default":"off","name":"cudnn_tune"},{"default":[1,null],"name":"dilate","type":"int32[]"},{"name":"kernel","type":"int32[]"},{"visible":false,"name":"no_bias","type":"boolean"},{"type":"int32","default":1,"name":"num_group"},{"type":"int32","name":"num_filter"},{"default":[0,null],"name":"pad","type":"int32[]"},{"default":[1,null],"name":"stride","type":"int32[]"},{"type":"int32","default":"1024","name":"workspace"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias","option":"optional"}],"outputs":[{"name":"output"}]}},{"name":"Deconvolution","schema":{"attributes":[{"visible":false,"name":"no_bias"},{"default":"1","name":"num_group"},{"type":"int32","default":"1024","name":"workspace"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"FullyConnected","schema":{"attributes":[{"type":"boolean","default":true,"name":"flatten"},{"type":"boolean","visible":false,"name":"no_bias"},{"type":"int32","name":"num_hidden"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[{"type":"float32","default":0.5,"name":"p"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LRN","schema":{"category":"Normalization","attributes":[{"name":"alpha","type":"float32","default":0.0001},{"name":"beta","type":"float32","default":0.75},{"name":"knorm","type":"float32","default":2},{"name":"nsize","type":"int32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxOutput","schema":{"attributes":[{"default":"1","name":"grad_scale"},{"default":"-1","name":"ignore_label"},{"default":false,"name":"multi_output"},{"default":"null","name":"normalization"},{"default":false,"name":"out_grad"},{"default":"0","name":"smooth_alpha"},{"default":false,"name":"use_ignore"},{"default":false,"name":"preserve_shape"}],"category":"Activation","inputs":[{"name":"input"},{"name":"label"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxActivation","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LeakyReLU","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}]}},{"name":"Activation","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"attributes":[{"default":false,"name":"cudnn_off"},{"default":false,"name":"global_pool"},{"name":"kernel","type":"int32[]"},{"default":[0,null],"name":"pad","type":"int32[]"},{"default":"valid","name":"pooling_convention"},{"default":"max","name":"pool_type"},{"default":[1,null],"name":"stride","type":"int32[]"}],"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Flatten","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Concat","schema":{"attributes":[{"default":"1","name":"dim"},{"visible":false,"name":"num_args"}],"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"SliceChannel","schema":{"inputs":[{"name":"inputs"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"_Plus","schema":{"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"elemwise_add","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"elemwise_sub","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"elemwise_div","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"BatchNorm","schema":{"attributes":[{"type":"int32","default":1,"name":"axis"},{"type":"float64","default":0.001,"name":"eps"},{"type":"float32","default":0.9,"name":"momentum"},{"type":"boolean","default":true,"name":"fix_gamma"},{"type":"boolean","default":false,"name":"use_global_stats"}],"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"mean"},{"name":"variance"}],"outputs":[{"name":"output"}]}},{"name":"CuDNNBatchNorm","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"}],"outputs":[{"name":"output"}]}},{"name":"ElementWiseSum","schema":{"category":"Normalization","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Embedding","schema":{"category":"Transform","attributes":[{"type":"int32","name":"input_dim"},{"type":"int32","name":"output_dim"}],"inputs":[{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}]}},{"name":"RNN","schema":{"category":"Layer","attributes":[{"type":"boolean","name":"bidirectional","default":false},{"name":"lstm_parameters","visible":false},{"type":"int32","name":"num_layers"},{"type":"boolean","default":false,"name":"state_outputs"},{"type":"int32","name":"state_size"},{"type":"float32","name":"p","default":0}],"inputs":[{"name":"input"},{"name":"state_0"},{"name":"state_1"}],"outputs":[{"name":"output"}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_minus_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_rminus_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_mul_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"broadcast_mul","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"broadcast_add","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"broadcast_div","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"_copy","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_minus_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_mul_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"slice_axis","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pad","schema":{"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"relu","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_linalg_gemm2","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"_zeros","schema":{"category":"Constant","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_sub","schema":{"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}]}},{"name":"_mul","schema":{"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}]}},{"name":"MakeLoss","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"transpose","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"sum","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"square","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"sqrt","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"mean","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"log","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_plus_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet.js new file mode 100644 index 0000000000000000000000000000000000000000..c742213b7c5b0b6497b212d1c5c5c94d53f399e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/mxnet.js @@ -0,0 +1 @@ +var mxnet=mxnet||{},long=long||{Long:require("long")},zip=zip||require("./zip"),ndarray=ndarray||{};mxnet.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"===e||"mar"===e){if(t.entries("zip").length>0)return!0}else if("json"==e){const e=t.text;if(-1!=e.indexOf('"nodes":',0))try{const t=JSON.parse(e);if(t&&t.nodes&&t.arg_nodes&&t.heads)return!0}catch(t){}}else if("params"==e){const e=t.buffer,n=[18,1,0,0,0,0,0,0];if(e&&e.length>n.length&&n.every(((t,n)=>t==e[n])))return!0}return!1}open(t,e){const n=t.identifier,s=t.identifier.split(".").pop().toLowerCase();let r=null,a=null,i=null,o=null;switch(s){case"json":try{return r=JSON.parse(t.text),r&&r.nodes&&r.nodes.some((t=>t&&"tvm_op"==t.op))&&(i="TVM"),o=mxnet.ModelFactory._basename(n,"json","symbol"),o?t.request(o+"-0000.params",null).then((t=>this._openModel(n,i,null,r,null,t,e))).catch((()=>this._openModel(n,i,null,r,null,a,e))):this._openModel(n,i,null,r,null,null,e)}catch(t){throw e.exception(t,!1),new mxnet.Error(t.message),null}case"params":return a=t.buffer,o=mxnet.ModelFactory._basename(t.identifier,"params"),o?t.request(o+"-symbol.json","utf-8").then((t=>(r=JSON.parse(t),r&&r.nodes&&r.nodes.some((t=>t&&"tvm_op"==t.op))&&(i="TVM"),this._openModel(n,i,null,r,null,a,e)))).catch((()=>this._openModel(n,i,null,null,null,a,e))):this._openModel(n,i,null,null,null,a,e);case"mar":case"model":{const s=new Map;try{for(const e of t.entries("zip"))s.set(e.name,e)}catch(t){throw new mxnet.Error("Failed to decompress Zip archive. "+t.message)}let o=s.get(s.has("MANIFEST.json")?"MANIFEST.json":"MAR-INF/MANIFEST.json"),h="";if(!o){const e=Array.from(s.keys()).filter((t=>t.endsWith("/"))).filter((t=>s.get(t+"MANIFEST.json")));if(1!=e.length)throw new mxnet.Error("Manifest not found in '"+t.identifier+"'.");h=e[0],o=s.get(h+"MANIFEST.json")}const l=new TextDecoder("utf-8");let u=null;try{u=JSON.parse(l.decode(o.data))}catch(t){throw new mxnet.Error("Failed to read manifest. "+t.message)}let p=null,d=null,c=null,m=null;if(u.Model){if(p=u.Model["Model-Format"],p&&"MXNet-Symbolic"!=p)throw new mxnet.Error("Model format '"+p+"' not supported.");if(i="MXNet Model Server",u["Model-Archive-Version"]&&(i+=" v"+u["Model-Archive-Version"].toString()),!u.Model.Symbol)throw new mxnet.Error("Manifest does not contain symbol entry.");d=s.get(h+u.Model.Symbol),u.Model.Signature&&(c=s.get(h+u.Model.Signature)),u.Model.Parameters&&(m=s.get(h+u.Model.Parameters))}else{if(!u.model)throw new mxnet.Error("Manifest does not contain model.");if(i="MXNet Model Archive",u.specificationVersion&&(i+=" v"+u.specificationVersion.toString()),u.model.modelName){d=s.get(h+u.model.modelName+"-symbol.json");let t=null;for(t of Array.from(s.keys()))if(t=t.substring(h.length),t.endsWith(".params")&&t.startsWith(u.model.modelName)){m=s.get(t);break}if(!d&&!m)for(t of Object.keys(s))if(t=t.substring(h.length),t.endsWith(".params")){m=s.get(t);break}}}if(!d&&!m)throw new mxnet.Error("Model does not contain symbol entry.");try{d&&(r=JSON.parse(l.decode(d.data)))}catch(t){throw new mxnet.Error("Failed to load symbol entry."+t.message)}m&&(a=m.data);let _=null;try{c&&(_=JSON.parse(l.decode(c.data)))}catch(t){}try{return this._openModel(n,i,u,r,_,a,e)}catch(t){const e=t&&t.message?t.message:t.toString();throw new mxnet.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}}default:throw new mxnet.Error("Unsupported file extension.")}}_openModel(t,e,n,s,r,a,i){return mxnet.Metadata.open(i).then((o=>{const h=new Map;if(a)try{const t=new ndarray.Stream(a);for(const e of Object.keys(t.arrays)){const n=e.startsWith("arg:")||e.startsWith("aux:")?e.substring(4):e;h.set(n,t.arrays[e])}}catch(t){}try{return new mxnet.Model(o,e,n,s,r,h)}catch(e){i.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new mxnet.Error(n.replace(/\.$/,"")+" in '"+t+"'.")}}))}static _basename(t,e,n){const s=t.split(".");if(s.length>=2&&s.pop().toLowerCase()===e){const t=s.join(".").split("-");if(t.length>=2){const e=t.pop();if(n){if(e!=n)return null}else for(let t=0;t="0"&&n<="9"||n>="A"&&n<="Z"||n>="a"&&n<="z"))return null}return t.join("-")}}return null}},mxnet.Model=class{constructor(t,e,n,s,r,a){if(!s&&!a)throw new mxnet.Error("JSON symbol data not available.");if(s){if(!Object.prototype.hasOwnProperty.call(s,"nodes"))throw new mxnet.Error("JSON file does not contain an MXNet 'nodes' property.");if(!Object.prototype.hasOwnProperty.call(s,"arg_nodes"))throw new mxnet.Error("JSON file does not contain an MXNet 'arg_nodes' property.");if(!Object.prototype.hasOwnProperty.call(s,"heads"))throw new mxnet.Error("JSON file does not contain an MXNet 'heads' property.")}if(n){if(n.Model&&n.Model["Model-Name"]&&(this._name=n.Model["Model-Name"]),n.Model&&n.Model.Description&&this._name!=n.Model.Description&&(this._description=n.Model.Description),n.Engine&&n.Engine.MXNet){const t=mxnet.Model._convert_version(n.Engine.MXNet);this._runtime="MXNet v"+(t||n.Engine.MXNet.toString())}if(n.License&&(this._license=n.License),n.model&&n.model.modelName&&(this._name=n.model.modelName),n.model&&n.model.modelVersion&&(this._version=n.model.modelVersion),n.model&&n.model.modelName&&this._name!=n.model.description&&(this._description=n.model.description),n.runtime&&(this._runtime=n.runtime),n.engine&&n.engine.engineName){const t=n.engine.engineVersion?n.engine.engineName+" "+n.engine.engineVersion:n.engine.engineName;this._runtime=this._runtime?this._runtime+" ("+t+")":t}n.publisher&&n.publisher.author&&(this._author=n.publisher.author,n.publisher.email&&(this._author=this._author+" <"+n.publisher.email+">")),n.license&&(this._license=n.license)}if(this._format=e,!this._format&&s&&s.attrs&&s.attrs.mxnet_version){const t=mxnet.Model._convert_version(s.attrs.mxnet_version);t&&(this._format="MXNet v"+t)}this._format||(this._format="MXNet"),this._graphs=[],this._graphs.push(new mxnet.Graph(t,n,s,r,a))}get format(){return this._format}get name(){return this._name}get version(){return this._version}get description(){return this._description}get author(){return this._author}get license(){return this._license}get runtime(){return this._runtime}get graphs(){return this._graphs}static _convert_version(t){if(Array.isArray(t)&&2==t.length&&"int"==t[0]){const e=Math.floor(t[1]/1e4)%100,n=Math.floor(t[1]/100)%100,s=Math.floor(t[1])%100;return[e.toString(),n.toString(),s.toString()].join(".")}return null}},mxnet.Graph=class{constructor(t,e,n,s,r){this._metadata=t,this._nodes=[],this._inputs=[],this._outputs=[];const a=new Map;if(r)for(const t of r){const e=t[0],n=t[1];a.set(e,new mxnet.Tensor("Initializer",e,new mxnet.TensorType(n.dataType,new mxnet.TensorShape(n.shape.dimensions)),n.data))}if(n){const t=n.nodes,e={};if(s&&s.inputs)for(const t of s.inputs)e[t.data_name]=t;const r={};if(s&&s.outputs)for(const t of s.outputs)r[t.data_name]=t;for(const e of t)e.outputs=[];for(const e of t)e.inputs=e.inputs.map((e=>mxnet.Graph._updateOutput(t,e)));const i={};for(const e of t)for(const t of e.outputs)i[t]=(i[t]||0)+1;const o={};for(const e of n.arg_nodes)o[e]=e!o[e])))this._nodes.push(new mxnet.Node(this._metadata,e,o,h,a));for(const t of Object.keys(o)){const n=o[t];if(n&&(!n.inputs||0==n.inputs.length)&&n.outputs&&1==n.outputs.length){const t=n.outputs[0],s=n.name;let r=null;const a=e[s];a&&a.data_shape&&(r=new mxnet.TensorType(-1,new mxnet.TensorShape(a.data_shape))),this._inputs.push(new mxnet.Parameter(s,[new mxnet.Argument("["+t.join(",")+"]",r)]))}}}else if(r){let e=null;const n=[];let s=Object.keys(r).every((t=>-1!=t.indexOf("_")))?"_":"";if(0==s.length&&(s=Object.keys(r).every((t=>-1!=t.indexOf(".")))?".":""),!(s.length>0))throw new mxnet.Error("Unsupported key format in params.");{const t={};for(const a of Object.keys(r)){const r=a.split(s);let i=r.pop();(a.endsWith("moving_mean")||a.endsWith("moving_var"))&&(i=[r.pop(),i].join(s));const o=r.join(s);e=t[o],e||(e={name:o,op:"Weights",params:[]},t[o]=e,n.push(e)),t[o].params.push({name:i,id:a})}}for(e of n)this._nodes.push(new mxnet.Node(t,e,{},{},r))}}get name(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}static _updateOutput(t,e){const n=e[0],s=t[n],r=e[1];if(s)for(;r>=s.outputs.length;)s.outputs.push([n,s.outputs.length]);return[n,r]}},mxnet.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mxnet.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new mxnet.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._initializer?this._initializer.name:this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},mxnet.Node=class{constructor(t,e,n,s,r){this._metadata=t,this._type=e.op,this._name=e.name,this._attributes=[],this._inputs=[],this._outputs=[];const a=e.attrs||e.attr||e.param;if(a){"tvm_op"==this._type&&a.func_name&&(this._type=a.func_name);for(const t of Object.keys(a))"tvm_op"!=this._type&&"func_name"!=t&&this._attributes.push(new mxnet.Attribute(this._metadata,this.type,t,a[t]))}let i=null;const o=t.type(this.type);if(e.inputs){let a=e.inputs;"RNN"==this._type&&(a=a.map((t=>{const e=t[0],s=n[e];return s&&"null"==s.op&&s.name&&s.name.endsWith("_parameters")&&s.attr&&s.attr.__init__?(this._attributes.push(new mxnet.Attribute(this._metadata,this.type,s.name,s.attr.__init__)),delete n[e],null):t})),a=a.filter((t=>null!=t)));const h={};for(const e of a){const a="["+e.join(",")+"]";if(i=s[a],!i){const s=e[0],a=n[s];if(a&&a.name&&(!a.inputs||0==a.inputs.length)&&a.outputs&&1==a.outputs.length)if(i=r.get(a.name)||null,i)delete n[s];else{let e=this._name;if(e.endsWith("_fwd")&&(e=e.slice(0,-3)),a.name&&(a.name.startsWith(e+"_")||a.name.startsWith(e+"."))){let e=-1,r=[];if(a.attrs&&a.attrs.__dtype__&&a.attrs.__shape__)try{e=parseInt(a.attrs.__dtype__),r=JSON.parse("["+a.attrs.__shape__.replace("(","").replace(")","").split(" ").join("").split(",").map((t=>t||'"?"')).join(",")+"]")}catch(t){}let o=null;o=-1!==e||r.length>0?new mxnet.TensorType(e,new mxnet.TensorShape(r)):new mxnet.TensorType(-1,new mxnet.TensorShape(null)),i=new mxnet.Tensor("Initializer",a.name,o,null),delete n[s]}}}i&&(h[a]=i,s[a]=i)}let l=0;if(o&&o.inputs)for(const t of o.inputs)if(l{const n="["+t.join(",")+"]";return new mxnet.Parameter((l+e).toString(),[new mxnet.Argument(n,null,h[n])])}))))}if(e.outputs){const t=e.outputs;let n=0;if(o&&o.outputs)for(const e of o.outputs)if(nnew mxnet.Parameter((n+e).toString(),[new mxnet.Argument("["+t.join(",")+"]",null,null)])))))}if(e.params)for(const t of e.params)this._inputs.push(new mxnet.Parameter(t.name,[new mxnet.Argument(t.id,null,r.get(t.id)||null)]))}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mxnet.Attribute=class{constructor(t,e,n,s){let r;this._name=n,this._value=s;const a=t.attribute(e,n);if(a&&a.type)switch(a.type){case"boolean":switch(s){case"True":this._value=!0;break;case"False":this._value=!1}break;case"int32":r=Number.parseInt(this._value,10),this._value=Number.isNaN(this._value-r)?s:r;break;case"float32":case"float64":r=Number.parseFloat(this._value),this._value=Number.isNaN(this._value-r)?s:r;break;case"int32[]":if(this._value.length>2&&this._value.startsWith("(")&&this._value.endsWith(")")){let t=[];const e=this._value.substring(1,this._value.length-1).split(",").map((t=>t.trim())).map((t=>t.endsWith("L")?t.substring(0,t.length-1):t));for(const n of e)r=Number.parseInt(n,10),Number.isNaN(n-r)?t=null:null!=t&&t.push(r);null!=t&&(this._value=t)}}if(a)if(Object.prototype.hasOwnProperty.call(a,"visible")&&!a.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(a,"default")){let t=a.default;if(this._value==t)this._visible=!1;else if(Array.isArray(this._value)&&Array.isArray(t)){if(t=t.slice(0,t.length),t.length>1&&null==t[t.length-1])for(t.pop();t.lengthe==t[n]))&&(this._visible=!1)}}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},mxnet.Tensor=class{constructor(t,e,n,s){this._kind=t,this._name=e,this._type=n,this._data=s}get kind(){return"Initializer"}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return this._data?this._type||"?"!==this._type.dataType?this._type.shape.length<1?(t.state="Tensor has unknown shape.",t):(t.dataType=this._type.dataType,t.dimensions=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t):(t.state="Tensor has no data type.",t):(t.state="Tensor data is empty.",t)}_decode(t,e){const n=[],s=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"float32":n.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float64":n.push(t.data.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case"float16":n.push(mxnet.Tensor._decodeNumberFromFloat16(t.data.getUint16(t.index,!0))),t.index+=2,t.count++;break;case"uint8":n.push(t.data.getUint8(t.index,!0)),t.index+=1,t.count++;break;case"int32":n.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int8":n.push(t.data.getInt8(t.index,!0)),t.index+=1,t.count++;break;case"int64":n.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++}}else for(let r=0;rt.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return n}static _decodeNumberFromFloat16(t){const e=(32768&t)>>15,n=(31744&t)>>10,s=1023&t;return 0==n?(e?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==n?s?NaN:1/0*(e?-1:1):(e?-1:1)*Math.pow(2,n-15)*(1+s/Math.pow(2,10))}},mxnet.TensorType=class{constructor(t,e){switch(t){case 0:this._dataType="float32";break;case 1:this._dataType="float64";break;case 2:this._dataType="float16";break;case 3:this._dataType="uint8";break;case 4:this._dataType="int32";break;case 5:this._dataType="int8";break;case 6:this._dataType="int64";break;case-1:this._dataType="?";break;default:throw new mxnet.Error("Unknown type '"+t+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},mxnet.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},mxnet.Metadata=class{static open(t){return mxnet.Metadata._metadata?Promise.resolve(mxnet.Metadata._metadata):t.request(null,"mxnet-metadata.json","utf-8").then((t=>(mxnet.Metadata._metadata=new mxnet.Metadata(t),mxnet.Metadata._metadata))).catch((()=>(mxnet.Metadata._metadata=new mxnet.Metadata(null),mxnet.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},mxnet.Error=class extends Error{constructor(t){super(t),this.name="Error loading MXNet model."}},ndarray.Stream=class{constructor(t){this._arrays={};const e=new ndarray.Reader(t);if(!e.checkSignature([18,1,0,0,0,0,0,0]))throw new ndarray.Error("Invalid signature.");if(!e.checkSignature([0,0,0,0,0,0,0,0]))throw new ndarray.Error("Invalid reserved block.");const n=[];for(let t=e.uint64();t>0;t--)n.push(new ndarray.Array(e));const s=new TextDecoder("ascii"),r=[];for(let t=e.uint64();t>0;t--){const t=s.decode(e.read(e.uint64()));r.push(t)}if(r.length!=n.length)throw new ndarray.Error("Label count mismatch.");for(let t=0;t0&&(this.sshape=new ndarray.Shape(t,!0)),this._shape=new ndarray.Shape(t,!0),0==this._shape.dimensions.length)return;if(this._context=new ndarray.Context(t),this._dataType=t.uint32(),e>0)throw new ndarray.Error("Not implemented.");const n=(this._dataTypet*e))}},ndarray.Context=class{constructor(t){this._deviceType=t.uint32(),this._deviceId=t.uint32()}},ndarray.Reader=class{constructor(t){this._buffer=t,this._position=0,this._end=t.length}checkSignature(t){if(this._position+t.length<=this._end)for(let e=0;ethis._end)throw new ndarray.Error("Data not available.");const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}uint16(){if(this._position+2>this._end)throw new ndarray.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}uint64(){const t=this.uint32();if(0!=this.uint32())throw new ndarray.Error("Large int64 value.");return t}},ndarray.Error=class extends Error{constructor(t){super(t),this.name="NDArray Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mxnet.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..88f491c553cf439b7daf396b8a49ee1b5dfd4eb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn-metadata.json @@ -0,0 +1 @@ +[{"name":"AbsVal","schema":{"operator":0}},{"name":"ArgMax","schema":{"operator":1}},{"name":"BatchNorm","schema":{"operator":2,"category":"Normalization","attributes":[{"name":"channels","type":"int32","default":0},{"name":"eps","type":"float32","default":0}]}},{"name":"Bias","schema":{"operator":3,"category":"Layer","attributes":[{"name":"bias_data_size","default":0,"visible":false}]}},{"name":"BNLL","schema":{"operator":4}},{"name":"Concat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Convolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"dilation_w","type":"int32","default":1},{"name":"stride_w","type":"int32","default":1},{"name":"pad_w","type":"int32","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","type":"int32","default":0,"visible":false},{"name":"group","type":"int32","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","type":"int32","default":0},{"name":"dilation_h","type":"int32","default":1},{"name":"stride_h","type":"int32","default":1},{"name":"pad_h","type":"int32","default":0}]}},{"name":"Crop","schema":{"operator":7,"category":"Data","attributes":[{"name":"woffset","default":0},{"name":"hoffset","default":0},{"name":"coffset","default":0},{"name":"outw","default":0},{"name":"outh","default":0},{"name":"outc","default":0}]}},{"name":"Deconvolution","schema":{"operator":8,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"Dropout","schema":{"operator":9,"category":"Dropout","attributes":[{"name":"scale","type":"float32","default":1}]}},{"name":"Eltwise","schema":{"operator":10,"attributes":[{"name":"op_type","default":0},{"name":"coeffs","default":[]}],"inputs":[{"name":"inputs","option":"variadic"}]}},{"name":"ELU","schema":{"operator":11}},{"name":"Embed","schema":{"operator":12,"category":"Transform","attributes":[{"name":"num_output","default":0},{"name":"input_dim","default":0},{"name":"bias_term","default":0},{"name":"weight_data_size","default":0}]}},{"name":"Exp","schema":{"operator":13}},{"name":"Flatten","schema":{"operator":14,"category":"Shape"}},{"name":"InnerProduct","schema":{"operator":15,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":""},{"name":""},{"name":""},{"name":""},{"name":""},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":0}]}},{"name":"Input","schema":{"operator":16}},{"name":"Exp","schema":{"operator":17}},{"name":"LRN","schema":{"operator":18,"category":"Normalization","attributes":[{"name":"region_type","default":0},{"name":"local_size","default":5},{"name":"alpha","default":1},{"name":"beta","default":0.75},{"name":"bias","default":1}]}},{"name":"Exp","schema":{"operator":19}},{"name":"MVN","schema":{"operator":20}},{"name":"Pooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pooling_type","default":0},{"name":"kernel_w","default":0},{"name":"stride_w","default":1},{"name":"pad_left","default":0},{"name":"global_pooling","default":0},{"name":"pad_mode","default":0},{"name":""},{"name":""},{"name":""},{"name":""},{"name":""},{"name":"kernel_h","default":0},{"name":"stride_h","default":1},{"name":"pad_top","default":0},{"name":"pad_right","default":0},{"name":"pad_bottom","default":0}]}},{"name":"Power","schema":{"operator":22}},{"name":"PReLU","schema":{"operator":23,"category":"Activation","attributes":[{"name":"num_slope","type":"int32","default":0,"visible":false}]}},{"name":"Proposal","schema":{"operator":24}},{"name":"Reducation","schema":{"operator":25}},{"name":"ReLU","schema":{"operator":26,"category":"Activation","attributes":[{"name":"slope","type":"float32","default":0}]}},{"name":"Reshape","schema":{"operator":27,"category":"Shape","attributes":[{"name":"w","default":-233},{"name":"h","default":-233},{"name":"c","default":-233},{"name":"permute","default":0}]}},{"name":"ROIPooling","schema":{"operator":28}},{"name":"Scale","schema":{"operator":29,"category":"Layer","attributes":[{"name":"scale_data_size","default":0,"visible":false},{"name":"bias_term","default":0,"visible":false}]}},{"name":"Sigmoid","schema":{"operator":30,"category":"Activation"}},{"name":"Slice","schema":{"operator":31,"category":"Tensor","attributes":[{"name":"slices","default":[]},{"name":"axis","default":0}]}},{"name":"Softmax","schema":{"operator":32,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0},{"name":"fixbug0","type":"int32","default":0}]}},{"name":"Split","schema":{"operator":33,"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output","option":"variadic"}]}},{"name":"SPP","schema":{"operator":34,"category":"Activation"}},{"name":"TanH","schema":{"operator":35,"category":"Activation"}},{"name":"Threshold","schema":{"operator":36}},{"name":"Tile","schema":{"operator":37}},{"name":"RNN","schema":{"operator":38,"category":"Layer"}},{"name":"LSTM","schema":{"operator":39,"category":"Layer"}},{"name":"BinaryOp","schema":{"operator":40,"attributes":[{"name":"op_type","type":"int32","default":0},{"name":"with_scalar","type":"int32","default":0},{"name":"b","type":"float32","default":0}]}},{"name":"UnaryOp","schema":{"operator":41}},{"name":"ConvolutionDepthWise","schema":{"operator":42,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"Padding","schema":{"operator":43}},{"name":"Squeeze","schema":{"operator":44}},{"name":"ExpandDims","schema":{"operator":45}},{"name":"Normalize","schema":{"operator":46}},{"name":"Permute","schema":{"operator":47,"category":"Shape","attributes":[{"name":"order_type","default":0}]}},{"name":"PriorBox","schema":{"operator":48,"attributes":[{"name":"min_sizes","default":[]},{"name":"max_sizes","default":[]},{"name":"aspect_ratios","default":[]},{"name":"varainces0","type":"float32","default":0},{"name":"varainces1","type":"float32","default":0},{"name":"varainces2","type":"float32","default":0},{"name":"varainces3","type":"float32","default":0},{"name":"flip","default":1},{"name":"clip","default":0},{"name":"image_width","default":0},{"name":"image_height","default":0},{"name":"step_width","default":-233},{"name":"step_height","default":-233},{"name":"offset","default":0}]}},{"name":"DetectionOutput","schema":{"operator":49,"attributes":[{"name":"num_class","default":0},{"name":"nms_threshold","default":0.05},{"name":"nms_top_k","default":300},{"name":"keep_top_k","default":100},{"name":"confidence_threshold","default":0.5},{"name":"varainces0","default":0.1},{"name":"varainces1","default":0.1},{"name":"varainces2","default":0.2},{"name":"varainces3","default":0.2}]}},{"name":"Interp","schema":{"operator":50}},{"name":"DeconvolutionDepthWise","schema":{"operator":51,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"ShuffleChannel","schema":{"operator":52,"attributes":[{"name":"group","default":1}]}},{"name":"InstanceNorm","schema":{"operator":53}},{"name":"Clip","schema":{"operator":54}},{"name":"Reorg","schema":{"operator":55}},{"name":"YoloDetectionOutput","schema":{"operator":56,"attributes":[{"name":"num_class","type":"int32","default":20},{"name":"num_box","type":"int32","default":5},{"name":"confidence_threshold","type":"float32","default":0.01},{"name":"nms_threshold","type":"float32","default":0.45},{"name":"biases"}],"inputs":[{"name":"input","option":"variadic"}]}},{"name":"Quantize","schema":{"operator":57}},{"name":"Dequantize","schema":{"operator":58}},{"name":"Yolov3DetectionOutput","schema":{"operator":59,"attributes":[{"name":"num_class","type":"int32","default":20},{"name":"num_box","type":"int32","default":5},{"name":"confidence_threshold","type":"float32","default":0.01},{"name":"nms_threshold","type":"float32","default":0.45},{"name":"biases","type":"float32[]"},{"name":"mask","type":"float32[]"},{"name":"anchors_scale","type":"float32[]"}],"inputs":[{"name":"input","option":"variadic"}]}},{"name":"PSROIPooling","schema":{"operator":60}},{"name":"ROIAlign","schema":{"operator":61}},{"name":"Packing","schema":{"operator":62}},{"name":"Requantize","schema":{"operator":63}},{"name":"Cast","schema":{"operator":64}},{"name":"HardSigmoid","schema":{"operator":65,"category":"Activation"}},{"name":"SELU","schema":{"operator":66,"category":"Activation"}},{"name":"ReLU6","schema":{"category":"Activation"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn.js new file mode 100644 index 0000000000000000000000000000000000000000..8178ab0f4992bae6b40934475b3ad106dde86b0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/ncnn.js @@ -0,0 +1 @@ +var ncnn=ncnn||{},base=base||require("./base");ncnn.ModelFactory=class{match(t){const e=t.identifier.toLowerCase();if(e.endsWith(".param")||e.endsWith(".cfg.ncnn")){let e=t.text;if(e=e.substring(0,Math.min(e.length,32)),"7767517"===e.split("\n").shift().trim())return!0}if(e.endsWith(".param.bin")){const e=t.buffer;if(e.length>4&&7767517==(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0)return!0}if(e.endsWith(".bin")||e.endsWith(".weights.ncnn")){if("snapshot_blob.bin"==e||"v8_context_snapshot.bin"===e)return!1;const n=t.buffer;if(n.length>4){const t=(n[0]|n[1]<<8|n[2]<<16|n[3]<<24)>>>0;if(0===t||1===t||19950407===t||871224===t||180310===t)return!0}}return!1}open(t,e){return ncnn.Metadata.open(e).then((e=>{const n=t.identifier.toLowerCase(),s=(t,s)=>{try{return new ncnn.Model(e,t,s)}catch(t){const e=t&&t.message?t.message:t.toString();throw new ncnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}};let i=null;if(n.endsWith(".param")||n.endsWith(".cfg.ncnn"))return n.endsWith(".param")?i=t.identifier.substring(0,t.identifier.length-6)+".bin":n.endsWith(".cfg.ncnn")&&(i=t.identifier.substring(0,t.identifier.length-9)+".weights.ncnn"),t.request(i,null).then((e=>s(t.text,e))).catch((()=>s(t.text,null)));if(n.endsWith(".param.bin"))return i=t.identifier.substring(0,t.identifier.length-10)+".bin",t.request(i,null).then((e=>s(t.buffer,e))).catch((()=>s(t.buffer,null)));if(n.endsWith(".bin")||n.endsWith(".weights.ncnn")){let e=null;return n.endsWith("bin")?e=t.identifier.substring(0,t.identifier.length-4)+".param":n.endsWith(".weights.ncnn")&&(e=t.identifier.substring(0,t.identifier.length-13)+".cfg.ncnn"),t.request(e,"utf-8").then((e=>s(e,t.buffer))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new ncnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}}))}},ncnn.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new ncnn.Graph(t,e,n))}get format(){return"ncnn"}get graphs(){return this._graphs}},ncnn.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new ncnn.BlobReader(n),i=("string"==typeof e?new ncnn.TextParamReader(e):new ncnn.BinaryParamReader(t,e)).layers;for(const e of i)if("Input"==e.type){const t=e.attributes.map((t=>isNaN(parseInt(t.value,10))?t.value:parseInt(t.value,10))),n=new ncnn.TensorShape(t),s=new ncnn.TensorType("float32",n);this._inputs.push(new ncnn.Parameter(e.name,!0,e.outputs.map((t=>new ncnn.Argument(t,s,null)))))}else this._nodes.push(new ncnn.Node(t,s,e))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},ncnn.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},ncnn.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new ncnn.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},ncnn.Node=class{constructor(t,e,n){this._metadata=t,this._inputs=[],this._outputs=[],this._attributes=[],this._type=n.type,this._name=n.name;const s=t.operator(this._type);s&&(this._type=s);const i=t.type(this._type),a=i&&i.attributes?i&&i.attributes:[];for(const t of n.attributes){const e=a[t.key];this._attributes.push(new ncnn.Attribute(e,t.key,t.value))}const r=n.inputs;let o=0;if(i&&i.inputs)for(const t of i.inputs)if(o""!=e||"optional"!=t.option)).map((t=>new ncnn.Argument(t,null,null)));this._inputs.push(new ncnn.Parameter(t.name,!0,n)),o+=e}this._inputs=this._inputs.concat(r.slice(o).map(((t,e)=>{const n=o+e==0?"input":(o+e).toString();return new ncnn.Parameter(n,!0,[new ncnn.Argument(t,null,null)])})));const h=n.outputs;let u=0;if(i&&i.outputs)for(const t of i.outputs)if(unew ncnn.Argument(t,null,null)));this._outputs.push(new ncnn.Parameter(t.name,!0,n)),u+=e}switch(this._outputs=this._outputs.concat(h.slice(u).map(((t,e)=>{const n=u+e==0?"output":(u+e).toString();return new ncnn.Parameter(n,!0,[new ncnn.Argument(t,null,null)])}))),this._type){case"BatchNorm":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"slope",[t],"float32"),this._weight(e,"mean",[t],"float32"),this._weight(e,"variance",[t],"float32"),this._weight(e,"bias",[t],"float32");break}case"InnerProduct":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[2]||0,10);this._weight(e,"weight",[t,s/t]),"1"==n.attr[1]&&this._weight(e,"bias",[t],"float32");break}case"Bias":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"bias",[t],"float32");break}case"Embed":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[3]||0,10);this._weight(e,"weight",[s]),"1"==n.attr[2]&&this._weight(e,"bias",[t],"float32");break}case"Convolution":case"ConvolutionDepthWise":case"Deconvolution":case"DeconvolutionDepthWise":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[1]||0,10),i=parseInt(n.attr[11]||s,10),a=parseInt(n.attr[6]||0,10);this._weight(e,"weight",[t,a/(t*s*i),s,i]),"1"==n.attr[5]&&this._weight(e,"bias",[t],"float32");break}case"Dequantize":if("1"==n.attr[1]){const t=parseInt(n.attr[2]||0,10);this._weight(e,"bias",[t],"float32")}break;case"Requantize":if("1"==n.attr[2]){const t=parseInt(n.attr[3]||0,10);this._weight(e,"bias",[t],"float32")}break;case"InstanceNorm":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"gamma",[t],"float32"),this._weight(e,"beta",[t],"float32");break}case"Scale":{const t=parseInt(n.attr[0]||0,10);-233!=t&&(this._weight(e,"scale",[t],"float32"),"1"==n.attr[1]&&this._weight(e,"bias",[t],"float32"));break}case"Normalize":{const t=parseInt(n.attr[3]||0,10);this._weight(e,"scale",[t],"float32");break}case"PReLU":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"slope",[t],"float32");break}}}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_weight(t,e,n,s){const i=t.read(n,s);s=i?i.dataType||"?":s||"?";const a=i?i.data:null;this._inputs.push(new ncnn.Parameter(e,!0,[new ncnn.Argument("",null,new ncnn.Tensor(new ncnn.TensorType(s,new ncnn.TensorShape(n)),a))]))}},ncnn.Attribute=class{constructor(t,e,n){if(this._type="",this._name=e,this._value=n,t){switch(this._name=t.name,t.type&&(this._type=t.type),this._type){case"int32":this._value=parseInt(this._value,10);break;case"float32":this._value=parseFloat(this._value);break;case"float32[]":this._value=this._value.map((t=>parseFloat(t)))}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1)}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},ncnn.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Weight"}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},ncnn.TensorType=class{constructor(t,e){this._dataType=t||"?",this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},ncnn.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},ncnn.Metadata=class{static open(t){return ncnn.Metadata._metadata?Promise.resolve(ncnn.Metadata._metadata):t.request(null,"ncnn-metadata.json","utf-8").then((t=>(ncnn.Metadata._metadata=new ncnn.Metadata(t),ncnn.Metadata._metadata))).catch((()=>(ncnn.Metadata._metadata=new ncnn.Metadata(null),ncnn.Metadata._metadatas)))}constructor(t){if(this._operatorMap=new Map,this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema),Object.prototype.hasOwnProperty.call(t.schema,"operator")&&this._operatorMap.set(t.schema.operator,t.name))}}operator(t){return this._operatorMap.get(t)}type(t){return this._map.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},ncnn.TextParamReader=class{constructor(t){const e=t.split(/\r?\n/);if("7767517"!==e.shift())throw new ncnn.Error("Invalid signature.");if(2!==e.shift().split(" ").length)throw new ncnn.Error("Invalid header count.");const n=[];for(;e.length>0;){const t=e.shift().trim();if(t.length>0){const e=t.split(" ").filter((t=>0!=t.length)),s={};s.type=e.shift(),s.name=e.shift();const i=parseInt(e.shift(),10),a=parseInt(e.shift(),10);s.inputs=e.splice(0,i),s.outputs=e.splice(0,a),s.attr={},s.attributes=[];for(const t of e){const e=t.split("=");if(2===e.length){let t=e[0].trim(),n=e[1].trim();const i=parseInt(t,10);i<0&&(n=n.split(",").map((t=>t.trim())),n.shift(),t=(-(i+23300)).toString()),s.attr[t]=n,s.attributes.push({key:t,value:n})}}n.push(s)}}this._layers=n}get layers(){return this._layers}},ncnn.BinaryParamReader=class{constructor(t,e){const n=new ncnn.BinaryReader(e);if(7767517!==n.int32())throw new ncnn.Error("Invalid signature.");const s=n.int32();n.int32();const i=[];for(let e=0;ethis._buffer.length)throw new ncnn.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}},ncnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading ncnn model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=ncnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/npz.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/npz.js new file mode 100644 index 0000000000000000000000000000000000000000..dd4f89b758f92803da553e2aac5a661d74103f31 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/npz.js @@ -0,0 +1 @@ +var npz=npz||{},long=long||{Long:require("long")};npz.ModelFactory=class{match(t){if("npz"===t.identifier.split(".").pop().toLowerCase()){const e=t.entries("zip");return e.length>0&&e.every((t=>t.name.endsWith(".npy")))}return!1}open(t,e){return e.require("./numpy").then((n=>e.require("./pickle").then((e=>{const i=t.identifier;try{const i=[],s=new Map,a=new Map,r=new Map;a.set("_codecs.encode",(function(t){return t})),r.set("numpy.core.multiarray._reconstruct",(function(t,e,n){this.subtype=t,this.shape=e,this.dtype=n,this.__setstate__=function(t){this.version=t[0],this.shape=t[1],this.typecode=t[2],this.is_f_order=t[3],this.rawdata=t[4]},this.__read__=function(t){const e={};e.__type__=this.subtype,e.dtype=this.typecode,e.shape=this.shape;let n=e.dtype.itemsize;for(let t=0;t{if(a.has(t))return a.get(t).apply(null,e);const n={__type__:t};if(!r.has(t))throw new npz.Error("Unknown function '"+t+"'.");return r.get(t).apply(n,e),n},o=new Map([["i1","int8"],["i2","int16"],["i4","int32"],["i8","int64"],["u1","uint8"],["u2","uint16"],["u4","uint32"],["u8","uint64"],["f2","float16"],["f4","float32"],["f8","float64"]]);for(const a of t.entries("zip")){if(!a.name.endsWith(".npy"))throw new npz.Error("Invalid file name '"+a.name+"'.");const t=a.name.replace(/\.npy$/,"").split("/"),r=t.pop(),p=t.length>=2?t.join("/"):"";if(!s.has(p)){const t={name:p,parameters:[]};i.push(t),s.set(p,t)}const u=s.get(p);let d=new n.Array(a.data);if("|"===d.byteOrder){if("O"!==d.dataType)throw new npz.Error("Invalid data type '"+d.dataType+"'.");d={dataType:new e.Unpickler(d.data).load(h).dtype.name,shape:null,data:null,byteOrder:"|"}}u.parameters.push({name:r,dataType:o.has(d.dataType)?o.get(d.dataType):d.dataType,shape:d.shape,data:d.data,byteOrder:d.byteOrder})}return new npz.Model(i,"NumPy Zip")}catch(t){const e=t&&t.message?t.message:t.toString();throw new npz.Error(e.replace(/\.$/,"")+" in '"+i+"'.")}}))))}},npz.Model=class{constructor(t,e){this._format=e,this._graphs=[],this._graphs.push(new npz.Graph(t))}get format(){return this._format}get graphs(){return this._graphs}},npz.Graph=class{constructor(t){this._nodes=[];for(const e of t)this._nodes.push(new npz.Node(e))}get inputs(){return[]}get outputs(){return[]}get nodes(){return this._nodes}},npz.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},npz.Argument=class{constructor(t,e){if("string"!=typeof t)throw new npz.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._initializer=e||null}get name(){return this._name}get type(){return this._initializer.type}get initializer(){return this._initializer}},npz.Node=class{constructor(t){this._name=t.name,this._inputs=[];for(const e of t.parameters){const t=this._name?[this._name,e.name].join("/"):e.name,n=new npz.Tensor(t,e.dataType,e.shape,e.data,e.byteOrder);this._inputs.push(new npz.Parameter(e.name,[new npz.Argument(t,n)]))}}get type(){return"Module"}get name(){return this._name}get metadata(){return null}get inputs(){return this._inputs}get outputs(){return[]}get attributes(){return[]}},npz.Tensor=class{constructor(t,e,n,i,s){this._name=t,this._type=new npz.TensorType(e,new npz.TensorShape(n)),this._shape=n,this._data=i,this._byteOrder=s}get kind(){return""}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return npz.Tensor._stringify(e,""," ")}_context(){const t={index:0,count:0,state:null};if("<"!==this._byteOrder&&">"!==this._byteOrder)return t.state="Tensor byte order is not supported.",t;if(this._reference)return t.state="Tensor reference not implemented.",t;if(!this._data||0==this._data.length)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":t.itemSize=2;break;case"float32":t.itemSize=4;break;case"float64":t.itemSize=8;break;case"int8":t.itemSize=1;break;case"int16":t.itemSize=2;break;case"int32":t.itemSize=4;break;case"int64":t.itemSize=8;break;case"uint8":t.itemSize=1;break;case"uint16":t.itemSize=2;break;case"uint32":t.itemSize=4;break;default:return t.state="Tensor data type is not supported.",t}return t.dimensions=this._type.shape.dimensions,t.dataType=this._type.dataType,t.littleEndian="<"==this._byteOrder,t.data=this._data,t.rawData=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t}_decode(t,e){const n=t.littleEndian,i=0==t.dimensions.length?[1]:t.dimensions,s=[],a=i[e];if(e==i.length-1)for(let e=0;et.limit)return s.push("..."),s;if(t.rawData){switch(t.dataType){case"float16":s.push(t.rawData.getFloat16(t.index,n));break;case"float32":s.push(t.rawData.getFloat32(t.index,n));break;case"float64":s.push(t.rawData.getFloat64(t.index,n));break;case"int8":s.push(t.rawData.getInt8(t.index,n));break;case"int16":s.push(t.rawData.getInt16(t.index,n));break;case"int32":s.push(t.rawData.getInt32(t.index,n));break;case"int64":s.push(long.Long.fromBytes(t.data.subarray(t.index,t.index+8),!0,n));break;case"uint8":s.push(t.rawData.getUint8(t.index,n));break;case"uint16":s.push(t.rawData.getUint16(t.index,n));break;case"uint32":s.push(t.rawData.getUint32(t.index,n))}t.index+=t.itemSize,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.dimensions.length?s[0]:s}static _stringify(t,e,n){if(Array.isArray(t)){const i=[];i.push(e+"[");const s=t.map((t=>npz.Tensor._stringify(t,e+n,n)));return s.length>0&&i.push(s.join(",\n")),i.push(e+"]"),i.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},npz.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType||"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},npz.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},npz.Error=class extends Error{constructor(t){super(t),this.name="Error loading Chainer model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=npz.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/numpy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/numpy.js new file mode 100644 index 0000000000000000000000000000000000000000..ca88fd6a83f69a4aceaa67afbc4086c67b8ab1d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/numpy.js @@ -0,0 +1 @@ +var numpy=numpy||{};numpy.Array=class{constructor(t){if(t){const e=new numpy.Reader(t),r=[147,78,85,77,80,89];if(!e.bytes(6).every(((t,e)=>t==r[e])))throw new numpy.Error("Invalid signature.");const s=e.byte(),i=e.byte();if(1!==s&&0!==i)throw new numpy.Error("Invalid version '"+[s,i].join(".")+"'.");const a=JSON.parse(e.string().trim().replace(/'/g,'"').replace("False","false").replace("(","[").replace(/,*\),*/g,"]"));if(a.fortran_order)throw new numpy.Error("Fortran order is not supported.'");if(!a.descr||a.descr.length<2)throw new numpy.Error("Missing property 'descr'.");if(!a.shape)throw new numpy.Error("Missing property 'shape'.");switch(this._shape=a.shape,this._byteOrder=a.descr[0],this._byteOrder){case"|":this._dataType=a.descr.substring(1),this._data=e.bytes(e.size-e.position);break;case">":case"<":{if(3!==a.descr.length)throw new numpy.Error("Unsupported data type '"+a.descr+"'.");this._dataType=a.descr.substring(1);const t=parseInt(a.descr[2],10)*this._shape.reduce(((t,e)=>t*e),1);this._data=e.bytes(t);break}default:throw new numpy.Error("Unsupported data type '"+a.descr+"'.")}}}get data(){return this._data}set data(t){this._data=t}get dataType(){return this._dataType}set dataType(t){this._dataType=t}get shape(){return this._shape}set shape(t){this._shape=t}get byteOrder(){return this._byteOrder}set byteOrder(t){this._byteOrder=t}toBuffer(){const t=new numpy.Writer;t.bytes([147,78,85,77,80,89]),t.byte(1),t.byte(0);const e={itemSize:1,position:0,dataType:this._dataType,byteOrder:this._byteOrder||"<",shape:this._shape,descr:""};if("<"!==e.byteOrder&&">"!==e.byteOrder)throw new numpy.Error("Unknown byte order '"+this._byteOrder+"'.");if(2!==e.dataType.length||"f"!==e.dataType[0]&&"i"!==e.dataType[0]&&"u"!==e.dataType[0])throw new numpy.Error("Unsupported data type '"+this._dataType+"'.");e.itemSize=parseInt(e.dataType[1],10);let r="";switch(this._shape.length){case 0:throw new numpy.Error("Invalid shape.");case 1:r="("+this._shape[0].toString()+",)";break;default:r="("+this._shape.map((t=>t.toString())).join(", ")+")"}let s="{ "+["'descr': '"+e.byteOrder+e.dataType+"'","'fortran_order': False","'shape': "+r].join(", ")+" }";s+=" ".repeat(16-(s.length+2+8+1&15))+"\n",t.string(s);const i=e.itemSize*this._shape.reduce(((t,e)=>t*e));return e.data=new Uint8Array(i),e.dataView=new DataView(e.data.buffer,e.data.byteOffset,i),numpy.Array._encodeDimension(e,this._data,0),t.bytes(e.data),t.toBuffer()}static _encodeDimension(t,e,r){const s=t.shape[r],i="<"===t.byteOrder;if(r==t.shape.length-1)for(let r=0;r>8&255])}bytes(t){const e=new Uint8Array(t.length);for(let r=0;r) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Abs","schema":{"description":"Absolute takes one input data (Tensor) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Abs","schema":{"description":"Absolute takes one input data (Tensor) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Acos","schema":{"description":"Calculates the arccosine (inverse of cosine) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Acos',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arccos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acos_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32)\ny = np.arccos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acos')","summary":"acos"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arccosine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Acosh","schema":{"description":"Calculates the hyperbolic arccosine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Acosh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([10, np.e, 1]).astype(np.float32)\ny = np.arccosh(x) # expected output [2.99322295, 1.65745449, 0.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_acosh_example')\n\nx = np.random.uniform(1.0, 10.0, (3, 4, 5)).astype(np.float32)\ny = np.arccosh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acosh')","summary":"acosh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arccosine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Adagrad","schema":{"attributes":[{"description":"The decay factor of learning rate after one update.The effective learning rate is computed by r = R / (1 + T * decay_factor). Default to 0 so that increasing update counts doesn't reduce the learning rate.","name":"decay_factor","required":false,"type":"float32"},{"default":9.999999974752427e-7,"description":"Small scalar to avoid dividing by zero.","name":"epsilon","required":false,"type":"float32"},{"description":"Regularization coefficient in 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient","required":false,"type":"float32"}],"description":"Compute one iteration of ADAGRAD, a stochastic gradient based optimization\n algorithm. This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. As you can imagine, ADAGRAD requires\n some parameters:\n \n - The initial learning-rate \"R\".\n - The update count \"T\". That is, the number of training iterations conducted.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A learning-rate decay factor \"decay_factor\".\n - A small constant \"epsilon\" to avoid dividing-by-zero. \n\n At each ADAGRAD iteration, the optimized tensors are moved along a direction\n computed based on their estimated gradient and accumulated squared gradient. Assume\n that only a single tensor \"X\" is updated by this operator. We need the value of \"X\",\n its gradient \"G\", and its accumulated squared gradient \"H\". Therefore, variables in\n this operator's input list are sequentially \"R\", \"T\", \"X\", \"G\", and \"H\". Other\n parameters are given as attributes because they are usually constants. Also, the\n corresponding output tensors are the new value of \"X\" (called \"X_new\"), and then\n the new accumulated squared gradient (called \"H_new\"). Those outputs are computed\n from the given inputs following the pseudo code below.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise arithmetic operations with\n numpy-style broadcasting support. The pseudo code to compute those outputs is:\n\n // Compute a scalar learning-rate factor. At the first update of X, T is generally\n // 0 (0-based update index) or 1 (1-based update index).\n r = R / (1 + T * decay_factor);\n\n // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.\n G_regularized = norm_coefficient * X + G;\n\n // Compute new accumulated squared gradient.\n H_new = H + G_regularized * G_regularized;\n\n // Compute the adaptive part of per-coordinate learning rate. Note that Sqrt(...)\n // computes element-wise square-root.\n H_adaptive = Sqrt(H_new) + epsilon\n\n // Compute the new value of \"X\".\n X_new = X - r * G_regularized / H_adaptive;\n\n If one assign this operators to optimize multiple inputs, for example, \"X_1\" and \"X_2\", the same\n pseudo code may be extended to handle all tensors jointly. More specifically, we can view \"X\" as a\n concatenation of \"X_1\" and \"X_2\" (of course, their gradient and accumulate gradient should\n be concatenated too) and then just reuse the entire pseudo code.\n\n Note that ADAGRAD was first proposed in http://jmlr.org/papers/volume12/duchi11a/duchi11a.pdf.\n In that reference paper, this operator is a special case of the Figure 1's composite mirror\n descent update.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nepsilon = 1e-5\ndecay_factor = 0.1\n\n# Create operator.\nnode = onnx.helper.make_node('Adagrad',\n inputs=['R', 'T', 'X', 'G', 'H'],\n outputs=['X_new', 'H_new'],\n norm_coefficient=norm_coefficient,\n epsilon=epsilon,\n decay_factor=decay_factor,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.0], dtype=np.float32)\ng = np.array([-1.0], dtype=np.float32)\nh = np.array([2.0], dtype=np.float32)\n\n# Compute expected outputs of Adagrad.\nx_new, h_new = apply_adagrad(r, t, x, g, h,\n norm_coefficient, epsilon, decay_factor)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, h],\n outputs=[x_new, h_new], name='test_adagrad',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adagrad"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nepsilon = 1e-5\ndecay_factor = 0.1\n\nnode = onnx.helper.make_node('Adagrad',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'H1_new', 'H2_new'],\n norm_coefficient=norm_coefficient,\n epsilon=epsilon,\n decay_factor=decay_factor,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nh1 = np.array([2.0], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nh2 = np.array([4.0, 1.0], dtype=np.float32)\n\n# Compute expected outputs of Adagrad.\nx1_new, h1_new = apply_adagrad(r, t, x1, g1, h1,\n norm_coefficient, epsilon, decay_factor)\nx2_new, h2_new = apply_adagrad(r, t, x2, g2, h2,\n norm_coefficient, epsilon, decay_factor)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, h1, h2],\n outputs=[x1_new, x2_new, h1_new, h2_new], name='test_adagrad_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adagrad_multiple"}],"inputs":[{"description":"The initial learning rate.","name":"R","type":"T1"},{"description":"The update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"The current values of optimized tensors, followed by their respective gradients, followed by their respective accumulated squared gradients.For example, if two tensor \"X_1\" and \"X_2\" are optimized, The input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", accumulated squared gradient of \"X_1\", accumulated squared gradient of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"Updated values of optimized tensors, followed by their updated values of accumulated squared gradients. For example, if two tensor \"X_1\" and \"X_2\" are optimized, the output list would be [new value of \"X_1,\" new value of \"X_2\" new accumulated squared gradient of \"X_1\", new accumulated squared gradient of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T3"}]}},{"name":"Adam","schema":{"attributes":[{"default":0.8999999761581421,"description":"Coefficient of previously accumulated gradient in running average. Default to 0.9.","name":"alpha","required":false,"type":"float32"},{"default":0.9990000128746033,"description":"Coefficient of previously accumulated squared-gradient in running average. Default to 0.999.","name":"beta","required":false,"type":"float32"},{"default":9.999999974752427e-7,"description":"Small scalar to avoid dividing by zero.","name":"epsilon","required":false,"type":"float32"},{"description":"Regularization coefficient of 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient","required":false,"type":"float32"},{"description":"Regularization coefficient of 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient_post","required":false,"type":"float32"}],"description":"Compute one iteration of Adam, a stochastic gradient based optimization\n algorithm. This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. First of all, Adam requires\n some parameters:\n \n - The learning-rate \"R\".\n - The update count \"T\". That is, the number of training iterations conducted.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A small constant \"epsilon\" to avoid dividing-by-zero. \n - Two coefficients, \"alpha\" and \"beta\".\n\n At each Adam iteration, the optimized tensors are moved along a direction\n computed based on their exponentially-averaged historical gradient and\n exponentially-averaged historical squared gradient. Assume that only a tensor\n \"X\" is being optimized. The rest of required information is\n \n - the value of \"X\",\n - \"X\"'s gradient (denoted by \"G\"),\n - \"X\"'s exponentially-averaged historical gradient (denoted by \"V\"), and\n - \"X\"'s exponentially-averaged historical squared gradient (denoted by \"H\").\n\n Some of those parameters are passed into this operator as input tensors and others\n are stored as this operator's attributes. Specifically, this operator's input tensor\n list is [\"R\", \"T\", \"X\", \"G\", \"V\", \"H\"]. That is, \"R\" is the first input, \"T\" is\n the second input, and so on. Other parameters are given as attributes because they\n are constants. Moreover, the corresponding output tensors are \n \n - the new value of \"X\" (called \"X_new\"),\n - the new exponentially-averaged historical gradient (denoted by \"V_new\"), and\n - the new exponentially-averaged historical squared gradient (denoted by \"H_new\").\n\n Those outputs are computed following the pseudo code below.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise arithmetic operations with\n numpy-style broadcasting support. The pseudo code to compute those outputs is:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.\n G_regularized = norm_coefficient * X + G\n\n // Update exponentially-averaged historical gradient.\n V_new = alpha * V + (1 - alpha) * G_regularized\n\n // Update exponentially-averaged historical squared gradient.\n H_new = beta * H + (1 - beta) * G_regularized * G_regularized\n\n // Compute the element-wise square-root of H_new. V_new will be element-wisely\n // divided by H_sqrt for a better update direction.\n H_sqrt = Sqrt(H_new) + epsilon\n\n // Compute learning-rate. Note that \"alpha**T\"/\"beta**T\" is alpha's/beta's T-th power.\n R_adjusted = T > 0 ? R * Sqrt(1 - beta**T) / (1 - alpha**T) : R\n\n // Compute new value of \"X\".\n X_new = X - R_adjusted * V_new / H_sqrt\n\n // Post-update regularization.\n X_final = (1 - norm_coefficient_post) * X_new \n\n If there are multiple inputs to be optimized, the pseudo code will be applied\n independently to each of them.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.1\nepsilon = 1e-7\n\n# Create operator.\nnode = onnx.helper.make_node('Adam',\n inputs=['R', 'T', 'X', 'G', 'V', 'H'],\n outputs=['X_new', 'V_new', 'H_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n epsilon=epsilon,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\nh = np.array([0.1, 0.1], dtype=np.float32)\n\n# Compute expected outputs of Adam.\nx_new, v_new, h_new = apply_adam(r, t, x, g, v, h,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v, h],\n outputs=[x_new, v_new, h_new], name='test_adam',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adam"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.85\nepsilon = 1e-2\n\nnode = onnx.helper.make_node('Adam',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'V1', 'V2',\n 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'V1_new', 'V2_new',\n 'H1_new', 'H2_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nv1 = np.array([2.0], dtype=np.float32)\nh1 = np.array([0.5], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nv2 = np.array([4.0, 1.0], dtype=np.float32)\nh2 = np.array([1.0, 10.0], dtype=np.float32)\n\n# Compute expected outputs of Adam.\nx1_new, v1_new, h1_new = apply_adam(r, t, x1, g1, v1, h1,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\nx2_new, v2_new, h2_new = apply_adam(r, t, x2, g2, v2, h2,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2, h1, h2],\n outputs=[x1_new, x2_new, v1_new, v2_new, h1_new, h2_new],\n name='test_adam_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adam_multiple"}],"inputs":[{"description":"The initial learning rate.","name":"R","type":"T1"},{"description":"The update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"The tensors to be optimized, followed by their respective gradients, followed by their respective accumulated gradients (aka momentum), followed by their respective accumulated squared gradients. For example, to optimize tensors \"X_1\" and \"X_2,\", the input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", accumulated gradient of \"X_1\", accumulated gradient of \"X_2\", accumulated squared gradient of \"X_1\", accumulated squared gradient of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"New values of optimized tensors, followed by their respective new accumulated gradients, followed by their respective new accumulated squared gradients. For example, if two tensors \"X_1\" and \"X_2\" are optimized, the outputs list would be [new value of \"X_1\", new value of \"X_2\", new accumulated gradient of \"X_1\", new accumulated gradient of \"X_2\", new accumulated squared gradient of \"X_1\", new accumulated squared gradient of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T3"}]}},{"name":"Add","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"description":"Performs element-wise binary addition (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"description":"Performs element-wise binary addition (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"And","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `and` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and4d')","summary":"and"},{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v4d')","summary":"and_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"And","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `and` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and4d')","summary":"and"},{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v4d')","summary":"and_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices.","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the\nprovided axis. The resulted tensor has the same rank as the input if keepdims equal 1.\nIf keepdims equal 0, then the resulted tensor have the reduced dimension pruned.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the max \nis selected if the max appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the max \nis selected if the max appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices.","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the\nprovided axis. The resulted tensor has the same rank as the input if keepdims equal 1.\nIf keepdims equal 0, then the resulted tensor have the reduced dimension pruned.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the min \nis selected if the min appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the min \nis selected if the min appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArrayFeatureExtractor","schema":{"description":"Select elements of the input tensor based on the indices passed.
\n The indices are applied to the last axes of the tensor.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be selected","name":"X","type":"T"},{"description":"The indices, based on 0 as the first index of any dimension.","name":"Y","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Selected output data as an array","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)","tensor(string)"],"description":"The input must be a tensor of a numeric type or string. The output will be of the same tensor type.","type_param_str":"T"}]}},{"name":"Asin","schema":{"description":"Calculates the arcsine (inverse of sine) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Asin',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arcsin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asin_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32)\ny = np.arcsin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asin')","summary":"asin"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Asinh","schema":{"description":"Calculates the hyperbolic arcsine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Asinh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.arcsinh(x) # expected output [-0.88137358, 0., 0.88137358]\nexpect(node, inputs=[x], outputs=[y],\n name='test_asinh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.arcsinh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asinh')","summary":"asinh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arcsine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Atan","schema":{"description":"Calculates the arctangent (inverse of tangent) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Atan',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.arctan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atan_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.arctan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atan')","summary":"atan"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arctangent of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Atanh","schema":{"description":"Calculates the hyperbolic arctangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Atanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arctanh(x) # expected output [-0.54930615, 0., 0.54930615]\nexpect(node, inputs=[x], outputs=[y],\n name='test_atanh_example')\n\nx = np.random.uniform(0.0, 1.0, (3, 4, 5)).astype(np.float32)\ny = np.arctanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atanh')","summary":"atanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arctangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":true,"type":"int64[]"},{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"},{"description":"If set to nonzero, run spatial batch normalization in test mode, default is 0.","name":"is_test","required":false,"type":"int64"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum), default is 0.9f.","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across all spatial elements If false, compute the mean and variance across per feature.Default is 1.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n ","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"The input 4-dimensional tensor of shape NCHW.","name":"X","type":"T"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"scale","type":"T"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"B","type":"T"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size C.","name":"mean","type":"T"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size C.","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output 4-dimensional tensor of the same shape as X.","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator. Must be in-place with the input mean. Should not be used for testing.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator. Must be in-place with the input var. Should not be used for testing.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"},{"description":"If set to nonzero, run spatial batch normalization in test mode, default is 0.","name":"is_test","required":false,"type":"int64"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum), default is 0.9f.","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across all spatial elements If false, compute the mean and variance across per feature.Default is 1.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"scale","type":"T"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"B","type":"T"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size C.","name":"mean","type":"T"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size C.","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X.","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator. Must be in-place with the input mean. Should not be used for testing.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator. Must be in-place with the input var. Should not be used for testing.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum).","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across per activation. If false, compute the mean and variance across per feature over each mini-batch.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\n https://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\n there are multiple cases for the number of outputs, which we list below:\n \n Output case #1: Y, mean, var, saved_mean, saved_var (training mode)\n Output case #2: Y (test mode)\n This operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"},{"description":"If spatial is true, the dimension of scale is (C). If spatial is false, the dimensions of scale are (C x D1 x ... x Dn)","name":"scale","type":"T"},{"description":"If spatial is true, the dimension of bias is (C). If spatial is false, the dimensions of bias are (C x D1 x ... x Dn)","name":"B","type":"T"},{"description":"If spatial is true, the dimension of the running mean (training) or the estimated mean (testing) is (C). If spatial is false, the dimensions of the running mean (training) or the estimated mean (testing) are (C x D1 x ... x Dn).","name":"mean","type":"T"},{"description":"If spatial is true, the dimension of the running variance(training) or the estimated variance (testing) is (C). If spatial is false, the dimensions of the running variance(training) or the estimated variance (testing) are (C x D1 x ... x Dn).","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum).","name":"momentum","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n\nFor previous (depreciated) non-spatial cases, implementors are suggested\nto flatten the input shape to (N x C*D1*D2 ..*Dn) before a BatchNormalization Op.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size, C is the number of channels. Statistics are computed for every channel of C over N and D1 to Dn dimensions. For image data, input dimensions become (N x C x H x W). The op also accepts single dimension input of size N in which case C is assumed to be 1","name":"X","type":"T"},{"description":"Scale tensor of shape (C).","name":"scale","type":"T"},{"description":"Bias tensor of shape (C).","name":"B","type":"T"},{"description":"running (training) or estimated (testing) mean tensor of shape (C).","name":"mean","type":"T"},{"description":"running (training) or estimated (testing) variance tensor of shape (C).","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Binarizer","schema":{"attributes":[{"description":"Values greater than this are mapped to 1, others to 0.","name":"threshold","required":false,"type":"float32"}],"description":"Maps the values of the input tensor to either 0 or 1, element-wise, based on the outcome of a comparison against a threshold value.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be binarized","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Binarized output data","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type. The output will be of the same tensor type.","type_param_str":"T"}]}},{"name":"BitShift","schema":{"attributes":[{"description":"Direction of moving bits. It can be either \"RIGHT\" (for right shift) or \"LEFT\" (for left shift).","name":"direction","required":true,"type":"string"}],"description":"Bitwise shift operator performs element-wise operation. For each input element, if the\n attribute \"direction\" is \"RIGHT\", this operator moves its binary representation toward\n the right side so that the input value is effectively decreased. If the attribute \"direction\"\n is \"LEFT\", bits of binary representation moves toward the left side, which results the\n increase of its actual value. The input X is the tensor to be shifted and another input\n Y specifies the amounts of shifting. For example, if \"direction\" is \"Right\", X is [1, 4],\n and S is [1, 1], the corresponding output Z would be [0, 2]. If \"direction\" is \"LEFT\" with\n X=[1, 2] and S=[1, 2], the corresponding output Y would be [2, 8].\n \n Because this operator supports Numpy-style broadcasting, X's and Y's shapes are\n not necessarily identical.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint16)\ny = np.array([1, 2, 3]).astype(np.uint16)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint16')","summary":"left_unit16"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint32)\ny = np.array([1, 2, 3]).astype(np.uint32)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint32')","summary":"left_unit32"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint64)\ny = np.array([1, 2, 3]).astype(np.uint64)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint64')","summary":"left_unit64"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint8)\ny = np.array([1, 2, 3]).astype(np.uint8)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint8')","summary":"left_unit8"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint16)\ny = np.array([1, 2, 3]).astype(np.uint16)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint16')","summary":"right_unit16"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint32)\ny = np.array([1, 2, 3]).astype(np.uint32)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint32')","summary":"right_unit32"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint64)\ny = np.array([1, 2, 3]).astype(np.uint64)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint64')","summary":"right_unit64"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint8)\ny = np.array([1, 2, 3]).astype(np.uint8)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint8')","summary":"right_unit8"}],"inputs":[{"description":"First operand, input to be shifted.","name":"X","type":"T"},{"description":"Second operand, amounts of shift.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Z","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)"],"description":"Constrain input and output types to integer tensors.","type_param_str":"T"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"string"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\nNOTE: Casting to and from strings is not supported yet.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Casting from strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Casting to strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\nNOTE: Casting to and from strings is not supported yet.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Casting from strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Casting to strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\n\nCasting from string tensor in plain (e.g., \"3.14\" and \"1000\") and scientific numeric representations\n(e.g., \"1e-5\" and \"1E8\") to float types is supported. For example, converting string \"100.5\" to an integer may\nresult 100. There are some string literals reserved for special floating-point values;\n\"+INF\" (and \"INF\"), \"-INF\", and \"NaN\" are positive infinity, negative infinity, and not-a-number, respectively.\nAny string which can exactly match \"+INF\" in a case-insensitive way would be mapped to positive infinite. Similarly,\nthis case-insensitive rule is applied to \"INF\" and \"NaN\". When casting from numeric tensors\nto string tensors, plain floating-point representation (such as \"314.15926\") would be used. \nConverting non-numerical-literal string such as \"Hello World!\" is an undefined behavior. Cases \nof converting string representing floating-point arithmetic value, such as \"2.718\", to INT is an undefined behavior.\n\nConversion from a numerical type to any numerical type is always allowed.\nUser must be aware of precision loss and value change caused by range difference between two types.\nFor example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting\nan integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)"],"description":"Constrain input types. Casting from complex is not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)"],"description":"Constrain output types. Casting to complex is not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\n\nCasting from string tensor in plain (e.g., \"3.14\" and \"1000\") and scientific numeric representations\n(e.g., \"1e-5\" and \"1E8\") to float types is supported. For example, converting string \"100.5\" to an integer may\nresult 100. There are some string literals reserved for special floating-point values;\n\"+INF\" (and \"INF\"), \"-INF\", and \"NaN\" are positive infinity, negative infinity, and not-a-number, respectively.\nAny string which can exactly match \"+INF\" in a case-insensitive way would be mapped to positive infinite. Similarly,\nthis case-insensitive rule is applied to \"INF\" and \"NaN\". When casting from numeric tensors\nto string tensors, plain floating-point representation (such as \"314.15926\") would be used. \nConverting non-numerical-literal string such as \"Hello World!\" is an undefined behavior. Cases \nof converting string representing floating-point arithmetic value, such as \"2.718\", to INT is an undefined behavior.\n\nConversion from a numerical type to any numerical type is always allowed.\nUser must be aware of precision loss and value change caused by range difference between two types.\nFor example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting\nan integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)","tensor(bfloat16)"],"description":"Constrain input types. Casting from complex is not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)","tensor(bfloat16)"],"description":"Constrain output types. Casting to complex is not supported.","type_param_str":"T2"}]}},{"name":"CastMap","schema":{"attributes":[{"default":"TO_FLOAT","description":"A string indicating the desired element type of the output tensor, one of 'TO_FLOAT', 'TO_STRING', 'TO_INT64'.","name":"cast_to","required":false,"type":"string"},{"default":"DENSE","description":"Indicates whether to only output as many values as are in the input (dense), or position the input based on using the key of the map as the index of the output (sparse).
One of 'DENSE', 'SPARSE'.","name":"map_form","required":false,"type":"string"},{"default":1,"description":"If the value of map_form is 'SPARSE,' this attribute indicates the total length of the output tensor.","name":"max_map","required":false,"type":"int64"}],"description":"Converts a map to a tensor.
The map key must be an int64 and the values will be ordered\n in ascending order based on this key.
The operator supports dense packing or sparse packing.\n If using sparse packing, the key cannot exceed the max_map-1 value.\n","domain":"ai.onnx.ml","inputs":[{"description":"The input map that is to be cast to a tensor","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A tensor representing the same data as the input map, ordered by their keys","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["map(int64, string)","map(int64, float)"],"description":"The input must be an integer map to either string or float.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(float)","tensor(int64)"],"description":"The output is a 1-D tensor of string, float, or integer.","type_param_str":"T2"}]}},{"name":"CategoryMapper","schema":{"attributes":[{"description":"The integers of the map. This sequence must be the same length as the 'cats_strings' sequence.","name":"cats_int64s","required":false,"type":"int64[]"},{"description":"The strings of the map. This sequence must be the same length as the 'cats_int64s' sequence","name":"cats_strings","required":false,"type":"string[]"},{"default":-1,"description":"An integer to use when an input string value is not found in the map.
One and only one of the 'default_*' attributes must be defined.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string to use when an input integer value is not found in the map.
One and only one of the 'default_*' attributes must be defined.","name":"default_string","required":false,"type":"string"}],"description":"Converts strings to integers and vice versa.
\n Two sequences of equal length are used to map between integers and strings,\n with strings and integers at the same index detailing the mapping.
\n Each operator converts either integers to strings or strings to integers, depending \n on which default value attribute is provided. Only one default value attribute\n should be defined.
\n If the string default value is set, it will convert integers to strings.\n If the int default value is set, it will convert strings to integers.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input data","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data. If strings are input, the output values are integers, and vice versa.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The input must be a tensor of strings or integers, either [N,C] or [C].","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output is a tensor of strings or integers. Its shape will be the same as the input shape.","type_param_str":"T2"}]}},{"name":"Ceil","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Ceil","schema":{"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Ceil","schema":{"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Celu","schema":{"attributes":[{"default":1,"description":"The Alpha value in Celu formula which control the shape of the unit. The default value is 1.0.","name":"alpha","required":false,"type":"float32"}],"description":"Continuously Differentiable Exponential Linear Units:\nPerform the linear unit element-wise on the input tensor X\nusing formula: \n\n```\nmax(0,x) + min(0,alpha*(exp(x/alpha)-1))\n```\n","domain":"ai.onnx","examples":[{"code":"alpha = 2.0\nnode = onnx.helper.make_node(\n 'Celu',\n inputs=['X'],\n outputs=['Y'],\n alpha=alpha,\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\npositive_input = np.maximum(0, input_data)\nnegative_input = np.minimum(0, alpha * (np.exp(input_data / alpha) - 1))\nexpected_output = positive_input + negative_input\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_celu')","summary":"celu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)"],"description":"Constrain input and output types to float32 tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"Maximum value, above which element is replaced by max","name":"max","required":false,"type":"float32"},{"description":"Minimum value, under which element is replaced by min","name":"min","required":false,"type":"float32"}],"description":"Clip operator limits the given input within an interval. The interval is\nspecified with arguments 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max() respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"attributes":[{"default":3.4028234663852886e+38,"description":"Maximum value, above which element is replaced by max","name":"max","required":false,"type":"float32"},{"default":-3.4028234663852886e+38,"description":"Minimum value, under which element is replaced by min","name":"min","required":false,"type":"float32"}],"description":"Clip operator limits the given input within an interval. The interval is\nspecified with arguments 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max() respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Compress","schema":{"attributes":[{"description":"(Optional) Axis along which to take slices. If not specified, input is flattened before elements being selected.","name":"axis","required":false,"type":"int64"}],"description":"Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index.\n In case axis is not provided, input is flattened before elements are selected.\n Compress behaves like numpy.compress: https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=0,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 1])\noutput = np.compress(condition, input, axis=0)\n#print(output)\n#[[ 3. 4.]\n# [ 5. 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_0')","summary":"compress_0"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=1)\n#print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_1')","summary":"compress_1"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 0, 0, 1])\noutput = np.compress(condition, input)\n#print(output)\n#[ 2., 5.]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_default_axis')","summary":"compress_default_axis"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=-1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=-1)\n# print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_negative_axis')","summary":"compress_negative_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"input","type":"T"},{"description":"Rank 1 tensor of booleans to indicate which slices or data elements to be selected. Its length can be less than the input length alone the axis or the flattened input size if axis is not specified. In such cases data slices or elements exceeding the condition length are discarded.","name":"condition","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank r if axis is specified. Otherwise output is a Tensor of rank 1.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains to boolean tensors.","type_param_str":"T1"}]}},{"name":"Compress","schema":{"attributes":[{"description":"(Optional) Axis along which to take slices. If not specified, input is flattened before elements being selected. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index.\n In case axis is not provided, input is flattened before elements are selected.\n Compress behaves like numpy.compress: https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=0,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 1])\noutput = np.compress(condition, input, axis=0)\n#print(output)\n#[[ 3. 4.]\n# [ 5. 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_0')","summary":"compress_0"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=1)\n#print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_1')","summary":"compress_1"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 0, 0, 1])\noutput = np.compress(condition, input)\n#print(output)\n#[ 2., 5.]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_default_axis')","summary":"compress_default_axis"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=-1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=-1)\n# print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_negative_axis')","summary":"compress_negative_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"input","type":"T"},{"description":"Rank 1 tensor of booleans to indicate which slices or data elements to be selected. Its length can be less than the input length along the axis or the flattened input size if axis is not specified. In such cases data slices or elements exceeding the condition length are discarded.","name":"condition","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank r if axis is specified. Otherwise output is a Tensor of rank 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains to boolean tensors.","type_param_str":"T1"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. Default value is 1.","name":"axis","required":false,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":4,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. A negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(inputs)..","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor. All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. A negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(inputs)..","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor. All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"ConcatFromSequence","schema":{"attributes":[{"description":"Which axis to concat on. Accepted range in `[-r, r - 1]`, where `r` is the rank of input tensors. When `new_axis` is 1, accepted range is `[-r - 1, r]`. ","name":"axis","required":true,"type":"int64"},{"description":"Insert and concatenate on a new axis or not, default 0 means do not insert new axis.","name":"new_axis","required":false,"type":"int64"}],"description":"Concatenate a sequence of tensors into a single tensor.\nAll input tensors must have the same shape, except for the dimension size of the axis to concatenate on.\nBy default 'new_axis' is 0, the behavior is similar to numpy.concatenate.\nWhen 'new_axis' is 1, the behavior is similar to numpy.stack.\n","domain":"ai.onnx","inputs":[{"description":"Sequence of tensors for concatenation","name":"input_sequence","type":"S"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain input types to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","required":true,"type":"tensor"}],"category":"Constant","description":"A constant tensor.","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","required":true,"type":"tensor"}],"category":"Constant","description":"A constant tensor.","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"}],"category":"Constant","description":"A constant tensor. Exactly one of the two attributes, either value or sparse_value,\nmust be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"},{"description":"The value for the sole element for the scalar, float32, output tensor.","name":"value_float","required":false,"type":"float32"},{"description":"The values for the elements for the 1D, float32, output tensor.","name":"value_floats","required":false,"type":"float32[]"},{"description":"The value for the sole element for the scalar, int64, output tensor.","name":"value_int","required":false,"type":"int64"},{"description":"The values for the elements for the 1D, int64, output tensor.","name":"value_ints","required":false,"type":"int64[]"},{"description":"The value for the sole element for the scalar, UTF-8 string, output tensor.","name":"value_string","required":false,"type":"string"},{"description":"The values for the elements for the 1D, UTF-8 string, output tensor.","name":"value_strings","required":false,"type":"string[]"}],"category":"Constant","description":"This operator produces a constant tensor. Exactly one of the provided attributes, either value, sparse_value,\nor value_* must be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"},{"description":"The value for the sole element for the scalar, float32, output tensor.","name":"value_float","required":false,"type":"float32"},{"description":"The values for the elements for the 1D, float32, output tensor.","name":"value_floats","required":false,"type":"float32[]"},{"description":"The value for the sole element for the scalar, int64, output tensor.","name":"value_int","required":false,"type":"int64"},{"description":"The values for the elements for the 1D, int64, output tensor.","name":"value_ints","required":false,"type":"int64[]"},{"description":"The value for the sole element for the scalar, UTF-8 string, output tensor.","name":"value_string","required":false,"type":"string"},{"description":"The values for the elements for the 1D, UTF-8 string, output tensor.","name":"value_strings","required":false,"type":"string[]"}],"category":"Constant","description":"This operator produces a constant tensor. Exactly one of the provided attributes, either value, sparse_value,\nor value_* must be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"ConstantOfShape","schema":{"attributes":[{"description":"(Optional) The value of the output elements.Should be a one-element tensor. If not specified, it defaults to a tensor of value 0 and datatype float32","name":"value","required":false,"type":"tensor"}],"description":"Generate a tensor with given value and shape.\n","domain":"ai.onnx","examples":[{"code":"x = np.array([4, 3, 2]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.FLOAT,\n [1], [1])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\n\ny = np.ones(x, dtype=np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_float_ones')","summary":"float_ones"},{"code":"x = np.array([0, ]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.INT32,\n [1], [0])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\ny = np.zeros(x, dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_int_shape_zero')","summary":"int32_shape_zero"},{"code":"x = np.array([10, 6]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.INT32,\n [1], [0])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\ny = np.zeros(x, dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_int_zeros')","summary":"int32_zeros"}],"inputs":[{"description":"1D tensor. The shape of the expected output tensor. If empty tensor is given, the output would be a scalar. All values must be >= 0.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of shape specified by 'input'.If attribute 'value' is specified, the value and datatype of the output tensor is taken from 'value'.If attribute 'value' is not specified, the value in the output defaults to 0, and the datatype defaults to float32.","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types to be numerics.","type_param_str":"T2"}]}},{"name":"Conv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution operator consumes an input tensor and a filter, and\ncomputes the output.","domain":"ai.onnx","examples":[{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[1, 1, 1, 1],\n)\ny_with_padding = np.array([[[[12., 21., 27., 33., 24.], # (1, 1, 5, 5) output tensor\n [33., 54., 63., 72., 51.],\n [63., 99., 108., 117., 81.],\n [93., 144., 153., 162., 111.],\n [72., 111., 117., 123., 84.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_basic_conv_with_padding')\n\n# Convolution without padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[0, 0, 0, 0],\n)\ny_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor\n [99., 108., 117.],\n [144., 153., 162.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_basic_conv_without_padding')","summary":"conv"},{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 7, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with strides=2 and padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 1, 1, 1],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_padding = np.array([[[[12., 27., 24.], # (1, 1, 4, 3) output tensor\n [63., 108., 81.],\n [123., 198., 141.],\n [112., 177., 124.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_conv_with_strides_padding')\n\n# Convolution with strides=2 and no padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[0, 0, 0, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_without_padding = np.array([[[[54., 72.], # (1, 1, 3, 2) output tensor\n [144., 162.],\n [234., 252.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_conv_with_strides_no_padding')\n\n# Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor)\nnode_with_asymmetric_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 0, 1, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_asymmetric_padding = np.array([[[[21., 33.], # (1, 1, 4, 2) output tensor\n [99., 117.],\n [189., 207.],\n [171., 183.]]]]).astype(np.float32)\nexpect(node_with_asymmetric_padding, inputs=[x, W], outputs=[y_with_asymmetric_padding],\n name='test_conv_with_strides_and_asymmetric_padding')","summary":"conv_with_strides"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Conv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults is 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults is 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution operator consumes an input tensor and a filter, and\ncomputes the output.","domain":"ai.onnx","examples":[{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[1, 1, 1, 1],\n)\ny_with_padding = np.array([[[[12., 21., 27., 33., 24.], # (1, 1, 5, 5) output tensor\n [33., 54., 63., 72., 51.],\n [63., 99., 108., 117., 81.],\n [93., 144., 153., 162., 111.],\n [72., 111., 117., 123., 84.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_basic_conv_with_padding')\n\n# Convolution without padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[0, 0, 0, 0],\n)\ny_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor\n [99., 108., 117.],\n [144., 153., 162.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_basic_conv_without_padding')","summary":"conv"},{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 7, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with strides=2 and padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 1, 1, 1],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_padding = np.array([[[[12., 27., 24.], # (1, 1, 4, 3) output tensor\n [63., 108., 81.],\n [123., 198., 141.],\n [112., 177., 124.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_conv_with_strides_padding')\n\n# Convolution with strides=2 and no padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[0, 0, 0, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_without_padding = np.array([[[[54., 72.], # (1, 1, 3, 2) output tensor\n [144., 162.],\n [234., 252.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_conv_with_strides_no_padding')\n\n# Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor)\nnode_with_asymmetric_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 0, 1, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_asymmetric_padding = np.array([[[[21., 33.], # (1, 1, 4, 2) output tensor\n [99., 117.],\n [189., 207.],\n [171., 183.]]]]).astype(np.float32)\nexpect(node_with_asymmetric_padding, inputs=[x, W], outputs=[y_with_asymmetric_padding],\n name='test_conv_with_strides_and_asymmetric_padding')","summary":"conv_with_strides"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ConvInteger","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into. default is 1.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input 'w'.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0.The value represent the number of pixels added to the beginning and end part of the corresponding axis.`pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number ofpixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaultsto 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The integer convolution operator consumes an input tensor, its zero-point, a filter, and its zero-point,\nand computes the output. The production MUST never overflow. The accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"\nx = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.uint8).reshape((1, 1, 3, 3))\nx_zero_point = np.uint8(1)\nw = np.array([1, 1, 1, 1]).astype(np.uint8).reshape((1, 1, 2, 2))\n\ny = np.array([12, 16, 24, 28]).astype(np.int32).reshape(1, 1, 2, 2)\n\n# ConvInteger without padding\nconvinteger_node = onnx.helper.make_node('ConvInteger',\n inputs=['x', 'w', 'x_zero_point'],\n outputs=['y'])\n\nexpect(convinteger_node, inputs=[x, w, x_zero_point], outputs=[y],\n name='test_basic_convinteger')\n\n# ConvInteger with padding\ny_with_padding = np.array([1, 3, 5, 3, 5, 12, 16, 9, 11, 24, 28, 15, 7, 15, 17, 9]).astype(np.int32).reshape((1, 1, 4, 4))\n\nconvinteger_node_with_padding = onnx.helper.make_node('ConvInteger',\n inputs=['x', 'w', 'x_zero_point'],\n outputs=['y'],\n pads=[1, 1, 1, 1],)\n\nexpect(convinteger_node_with_padding, inputs=[x, w, x_zero_point], outputs=[y_with_padding],\n name='test_convinteger_with_padding')","summary":"convinteger"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"x","type":"T1"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"w","type":"T2"},{"description":"Zero point tensor for input 'x'. It's optional and default value is 0. It's a scalar, which means a per-tensor/layer quantization.","name":"x_zero_point","option":"optional","type":"T1"},{"description":"Zero point tensor for input 'w'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M)","name":"w_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 4","max_input":4,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input x and its zero point data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input w and its zero point data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain output y data type to 32-bit integer tensor.","type_param_str":"T3"}]}},{"name":"ConvTranspose","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"The zero-padding added to one side of the output. This is also called adjs/adjustment in some frameworks.","name":"output_padding","required":false,"type":"int64[]"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If output_shape is specified pads values are ignored. See doc for details for equations to generate pads","name":"output_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution transpose operator consumes an input tensor and a filter,\nand computes the output.\n\nIf the pads parameter is provided the shape of the output is calculated via the following equation:\n\n output_shape[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - pads[start_i] - pads[end_i]\n\noutput_shape can also be explicitly specified in which case pads values are auto generated using these equations:\n\n total_padding[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]\n If (auto_pads != SAME_UPPER): pads[start_i] = total_padding[i]/2; pads[end_i] = total_padding[i] - (total_padding[i]/2)\n Else: pads[start_i] = total_padding[i] - (total_padding[i]/2); pads[end_i] = (total_padding[i]/2).\n\n ","domain":"ai.onnx","examples":[{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[0., 1., 3., 3., 2.], # (1, 2, 5, 5)\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]],\n\n [[0., 1., 3., 3., 2.],\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose')","summary":"convtranspose"},{"code":"x = np.array([[[0., 1., 2.]]]).astype(np.float32) # (1, 1, 3)\n\nW = np.array([[[1., 1., 1.], # (1, 2, 3)\n [1., 1., 1.]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[0., 1., 3., 3., 2.], # (1, 2, 5)\n [0., 1., 3., 3., 2.]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_1d')","summary":"convtranspose_1d"},{"code":"x = np.array([[[[[0., 1., 2., 3., 4.], # (1, 1, 3, 4, 5)\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.]],\n [[20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.],\n [35., 36., 37., 38., 39.]],\n [[40., 41., 42., 43., 44.],\n [45., 46., 47., 48., 49.],\n [50., 51., 52., 53., 54.],\n [55., 56., 57., 58., 59.]]]]]).astype(np.float32)\n\nW = np.array([[[[[1., 1., 1.], # (1, 2, 3, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]],\n [[[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[[0., 1., 3., 6., 9., 7., 4.], # (1, 2, 5, 6, 7)\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]],\n\n [[[0., 1., 3., 6., 9., 7., 4.],\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_3d')","summary":"convtranspose_3d"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\ny = np.array([[[[0., 0., 1., 1., 3., 2., 2., 0.], # (1, 2, 10, 8)\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]],\n\n [[0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_shape=[10, 8])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_output_shape')\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_padding=[1, 1])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pad')\n\nnode = onnx.helper.make_node(\n 'ConvTranspose', ['X', 'W'], ['Y'],\n name='test',\n strides=[3, 2],\n output_shape=[10, 8],\n kernel_shape=[3, 3],\n output_padding=[1, 1]\n)\nexpect(node, inputs=[x, W], outputs=[y],\n name='test_convtranspose_kernel_shape')","summary":"convtranspose_attributes"},{"code":"x = np.array([[[[3., 8., 1.], # (1, 1, 3, 3)\n [9., 5., 7.],\n [3., 2., 6.]]]]).astype(np.float32)\nW = np.array([[[[7., 2.], # (1, 1, 2, 2)\n [1., 9.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"], dilations=[2, 2])\n\ny = np.array([[[[21., 56., 13., 16., 2.], # [1, 1, 5, 5]\n [63., 35., 67., 10., 14.],\n [24., 22., 76., 76., 21.],\n [9., 5., 88., 45., 63.],\n [3., 2., 33., 18., 54.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_dilations')","summary":"convtranspose_dilations"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n pads=[1, 2, 1, 2])\n\ny = np.array([[[[1., 1., 3.], # (1, 2, 7, 3)\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]],\n\n [[1., 1., 3.],\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pads')","summary":"convtranspose_pads"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn)","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn), where (k1 x k2 x ... x kn) is the dimension of the kernel. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, pad lengths and group count. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ConvTranspose","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Additional elements added to the side with higher coordinate indices in the output. Each padding value in \"output_padding\" must be less than the corresponding stride/dilation dimension. By default, this attribute is a zero vector. Note that this attribute doesn't directly affect the computed output values. It only controls the selection of the computed values, so changing this attribute only adds or removes output elements. If \"output_shape\" is explicitly provided, \"output_padding\" does not contribute additional size to \"output_shape\" but participates in the computation of the needed padding amount. This is also called adjs or adjustment in some frameworks.","name":"output_padding","required":false,"type":"int64[]"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If output_shape is specified pads values are ignored. See doc for details for equations to generate pads","name":"output_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution transpose operator consumes an input tensor and a filter,\nand computes the output.\n\nIf the pads parameter is provided the shape of the output is calculated via the following equation:\n\n output_shape[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - pads[start_i] - pads[end_i]\n\noutput_shape can also be explicitly specified in which case pads values are auto generated using these equations:\n\n total_padding[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]\n If (auto_pads != SAME_UPPER): pads[start_i] = total_padding[i]/2; pads[end_i] = total_padding[i] - (total_padding[i]/2)\n Else: pads[start_i] = total_padding[i] - (total_padding[i]/2); pads[end_i] = (total_padding[i]/2).\n\n ","domain":"ai.onnx","examples":[{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[0., 1., 3., 3., 2.], # (1, 2, 5, 5)\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]],\n\n [[0., 1., 3., 3., 2.],\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose')","summary":"convtranspose"},{"code":"x = np.array([[[0., 1., 2.]]]).astype(np.float32) # (1, 1, 3)\n\nW = np.array([[[1., 1., 1.], # (1, 2, 3)\n [1., 1., 1.]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[0., 1., 3., 3., 2.], # (1, 2, 5)\n [0., 1., 3., 3., 2.]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_1d')","summary":"convtranspose_1d"},{"code":"x = np.array([[[[[0., 1., 2., 3., 4.], # (1, 1, 3, 4, 5)\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.]],\n [[20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.],\n [35., 36., 37., 38., 39.]],\n [[40., 41., 42., 43., 44.],\n [45., 46., 47., 48., 49.],\n [50., 51., 52., 53., 54.],\n [55., 56., 57., 58., 59.]]]]]).astype(np.float32)\n\nW = np.array([[[[[1., 1., 1.], # (1, 2, 3, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]],\n [[[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[[0., 1., 3., 6., 9., 7., 4.], # (1, 2, 5, 6, 7)\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]],\n\n [[[0., 1., 3., 6., 9., 7., 4.],\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_3d')","summary":"convtranspose_3d"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\ny = np.array([[[[0., 0., 1., 1., 3., 2., 2., 0.], # (1, 2, 10, 8)\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]],\n\n [[0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_shape=[10, 8])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_output_shape')\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_padding=[1, 1])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pad')\n\nnode = onnx.helper.make_node(\n 'ConvTranspose', ['X', 'W'], ['Y'],\n name='test',\n strides=[3, 2],\n output_shape=[10, 8],\n kernel_shape=[3, 3],\n output_padding=[1, 1]\n)\nexpect(node, inputs=[x, W], outputs=[y],\n name='test_convtranspose_kernel_shape')","summary":"convtranspose_attributes"},{"code":"x = np.array([[[[3., 8., 1.], # (1, 1, 3, 3)\n [9., 5., 7.],\n [3., 2., 6.]]]]).astype(np.float32)\nW = np.array([[[[7., 2.], # (1, 1, 2, 2)\n [1., 9.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"], dilations=[2, 2])\n\ny = np.array([[[[21., 56., 13., 16., 2.], # [1, 1, 5, 5]\n [63., 35., 67., 10., 14.],\n [24., 22., 76., 76., 21.],\n [9., 5., 88., 45., 63.],\n [3., 2., 33., 18., 54.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_dilations')","summary":"convtranspose_dilations"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n pads=[1, 2, 1, 2])\n\ny = np.array([[[[1., 1., 3.], # (1, 2, 7, 3)\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]],\n\n [[1., 1., 3.],\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pads')","summary":"convtranspose_pads"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn)","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn), where (k1 x k2 x ... x kn) is the dimension of the kernel. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, pad lengths and group count. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Cos","schema":{"description":"Calculates the cosine of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Cos',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.cos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cos_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.cos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cos')","summary":"cos"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The cosine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Cosh","schema":{"description":"Calculates the hyperbolic cosine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Cosh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.cosh(x) # expected output [1.54308069, 1., 1.54308069]\nexpect(node, inputs=[x], outputs=[y],\n name='test_cosh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.cosh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cosh')","summary":"cosh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic cosine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"CumSum","schema":{"attributes":[{"description":"If set to 1 will return exclusive sum in which the top element is not included. In other terms, if set to 1, the j-th output element would be the sum of the first (j-1) elements. Otherwise, it would be the sum of the first j elements.","name":"exclusive","required":false,"type":"int64"},{"description":"If set to 1 will perform the sums in reverse direction.","name":"reverse","required":false,"type":"int64"}],"description":"Performs cumulative sum of the input elements along the given axis.\nBy default, it will do the sum inclusively meaning the first element is copied as is.\nThrough an `exclusive` attribute, this behavior can change to exclude the first element.\nIt can also perform summation in the opposite direction of the axis. For that, set `reverse` attribute to 1.\n\nExample:\n```\ninput_x = [1, 2, 3]\naxis=0\noutput = [1, 3, 6]\nexclusive=1\noutput = [0, 1, 3]\nexclusive=0\nreverse=1\noutput = [6, 5, 3]\nexclusive=1\nreverse=1\noutput = [5, 3, 0]\n```\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y']\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([1., 3., 6., 10., 15.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d')","summary":"cumsum_1d"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n exclusive=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([0., 1., 3., 6., 10.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_exclusive')","summary":"cumsum_1d_exclusive"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n reverse=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([15., 14., 12., 9., 5.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_reverse')","summary":"cumsum_1d_reverse"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n reverse=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([14., 12., 9., 5., 0.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_reverse_exclusive')","summary":"cumsum_1d_reverse_exclusive"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([0]).astype(np.int32)\ny = np.array([1., 2., 3., 5., 7., 9.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_axis_0')","summary":"cumsum_2d_axis_0"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([1]).astype(np.int32)\ny = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_axis_1')","summary":"cumsum_2d_axis_1"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([-1]).astype(np.int32)\ny = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_negative_axis')","summary":"cumsum_2d_negative_axis"}],"inputs":[{"description":"An input tensor that is to be processed.","name":"x","type":"T"},{"description":"(Optional) A 0-D tensor. Must be in the range [-rank(x), rank(x)-1]. Negative value means counting dimensions from the back.","name":"axis","type":"T2"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same type as 'x' with cumulative sums of the x's elements","name":"y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float)","tensor(double)"],"description":"Input can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"axis tensor can be int32 or int64 only","type_param_str":"T2"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"},{"default":"DCR","description":"DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order.","name":"mode","required":false,"type":"string"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions. By default, `mode` = `DCR`.\nIn the DCR mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: depth, column, and then row. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w])\n\ntmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2])\n\ny = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize])\n\n\nIn the CRD mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: column, row, and the depth. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, c // (blocksize ** 2), blocksize, blocksize, h, w])\n\ntmp = np.transpose(tmp, [0, 1, 4, 2, 5, 3])\n\ny = np.reshape(tmp, [b, c // (blocksize ** 2), h * blocksize, w * blocksize])\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"},{"default":"DCR","description":"DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order.","name":"mode","required":false,"type":"string"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions. By default, `mode` = `DCR`.\nIn the DCR mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: depth, column, and then row. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w])\n\ntmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2])\n\ny = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize])\n\n\nIn the CRD mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: column, row, and the depth. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, c // (blocksize ** 2), blocksize, blocksize, h, w])\n\ntmp = np.transpose(tmp, [0, 1, 4, 2, 5, 3])\n\ny = np.reshape(tmp, [b, c // (blocksize ** 2), h * blocksize, w * blocksize])\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DequantizeLinear","schema":{"description":"The linear dequantization operator. It consumes a quantized tensor, a scale, a zero point to compute the full precision tensor.\nThe dequantization formula is y = (x - x_zero_point) * x_scale. 'x_scale' and 'x_zero_point' must have same shape.\n'x_zero_point' and 'x' must have same type. 'x' and 'y' must have same shape. In the case of dequantizing int32,\nthere's no zero point (zero point is supposed to be 0).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# 1-D tensor zero point and scale of size equal to axis 1 of the input tensor\nx = np.array([[[[3, 89],\n [34, 200],\n [74, 59]],\n\n [[5, 24],\n [24, 87],\n [32, 13]],\n\n [[245, 99],\n [4, 142],\n [121, 102]], ], ], dtype=np.uint8)\nx_scale = np.array([2, 4, 5], dtype=np.float32)\nx_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x.astype(np.float32) - x_zero_point.reshape(1, 3, 1, 1).astype(np.float32)) * x_scale.reshape(1, 3, 1, 1)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# scalar zero point and scale\nx = np.array([0, 3, 128, 255]).astype(np.uint8)\nx_scale = np.float32(2)\nx_zero_point = np.uint8(128)\ny = np.array([-256, -250, 0, 254], dtype=np.float32)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear')","summary":"dequantizelinear"}],"inputs":[{"description":"N-D quantized input tensor to be de-quantized.","name":"x","type":"T"},{"description":"Scale for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point for input 'x'. It's a scalar, which means a per-tensor/layer quantization. It's optional. 0 is the default value when it's not specified.","name":"x_zero_point","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D full precision output tensor. It has same shape as input 'x'.","name":"y","type":"tensor(float)"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)","tensor(int32)"],"description":"Constrain 'x_zero_point' and 'x' to 8-bit/32-bit integer tensor.","type_param_str":"T"}]}},{"name":"DequantizeLinear","schema":{"attributes":[{"default":1,"description":"(Optional) The axis of the dequantizing dimension of the input tensor. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input)","name":"axis","required":false,"type":"int64"}],"description":"The linear dequantization operator. It consumes a quantized tensor, a scale, and a zero point to compute the full precision tensor.\nThe dequantization formula is y = (x - x_zero_point) * x_scale. 'x_scale' and 'x_zero_point' must have same shape, and can be either a scalar\nfor per-tensor / per layer quantization, or a 1-D tensor for per-axis quantizations.\n'x_zero_point' and 'x' must have same type. 'x' and 'y' must have same shape. In the case of dequantizing int32,\nthere's no zero point (zero point is supposed to be 0).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# 1-D tensor zero point and scale of size equal to axis 1 of the input tensor\nx = np.array([[[[3, 89],\n [34, 200],\n [74, 59]],\n\n [[5, 24],\n [24, 87],\n [32, 13]],\n\n [[245, 99],\n [4, 142],\n [121, 102]], ], ], dtype=np.uint8)\nx_scale = np.array([2, 4, 5], dtype=np.float32)\nx_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x.astype(np.float32) - x_zero_point.reshape(1, 3, 1, 1).astype(np.float32)) * x_scale.reshape(1, 3, 1, 1)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# scalar zero point and scale\nx = np.array([0, 3, 128, 255]).astype(np.uint8)\nx_scale = np.float32(2)\nx_zero_point = np.uint8(128)\ny = np.array([-256, -250, 0, 254], dtype=np.float32)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear')","summary":"dequantizelinear"}],"inputs":[{"description":"N-D quantized input tensor to be de-quantized.","name":"x","type":"T"},{"description":"Scale for input 'x'. It can be a scalar, which means a per-tensor/layer dequantization, or a 1-D tensor for per-axis dequantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point for input 'x'. It can be a scalar, which means a per-tensor/layer dequantization, or a 1-D tensor for per-axis dequantization. It's optional. 0 is the default value when it's not specified.","name":"x_zero_point","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D full precision output tensor. It has same shape as input 'x'.","name":"y","type":"tensor(float)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)","tensor(int32)"],"description":"Constrain 'x_zero_point' and 'x' to 8-bit/32-bit integer tensor.","type_param_str":"T"}]}},{"name":"Det","schema":{"description":"Det calculates determinant of a square matrix or batches of square matrices.\nDet takes one input tensor of shape `[*, M, M]`, where `*` is zero or more batch dimensions,\nand the inner-most 2 dimensions form square matrices.\nThe output is a tensor of shape `[*]`, containing the determinants of all input submatrices.\ne.g., When the input is 2-D, the output is a scalar(shape is empty: `[]`).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Det',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.arange(4).reshape(2, 2).astype(np.float32)\ny = np.linalg.det(x) # expect -2\nexpect(node, inputs=[x], outputs=[y],\n name='test_det_2d')","summary":"2d"},{"code":"node = onnx.helper.make_node(\n 'Det',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]]]).astype(np.float32)\ny = np.linalg.det(x) # expect array([-2., -3., -8.])\nexpect(node, inputs=[x], outputs=[y],\n name='test_det_nd')","summary":"nd"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to floating-point tensors.","type_param_str":"T"}]}},{"name":"DictVectorizer","schema":{"attributes":[{"description":"An integer vocabulary array.
One and only one of the vocabularies must be defined.","name":"int64_vocabulary","required":false,"type":"int64[]"},{"description":"A string vocabulary array.
One and only one of the vocabularies must be defined.","name":"string_vocabulary","required":false,"type":"string[]"}],"description":"Uses an index mapping to convert a dictionary to an array.
\n Given a dictionary, each key is looked up in the vocabulary attribute corresponding to\n the key type. The index into the vocabulary array at which the key is found is then\n used to index the output 1-D tensor 'Y' and insert into it the value found in the dictionary 'X'.
\n The key type of the input map must correspond to the element type of the defined vocabulary attribute.\n Therefore, the output array will be equal in length to the index mapping vector parameter.\n All keys in the input dictionary must be present in the index mapping vector.\n For each item in the input dictionary, insert its value in the output array.\n Any keys not present in the input dictionary, will be zero in the output array.
\n For example: if the ``string_vocabulary`` parameter is set to ``[\"a\", \"c\", \"b\", \"z\"]``,\n then an input of ``{\"a\": 4, \"c\": 8}`` will produce an output of ``[4, 8, 0, 0]``.\n ","domain":"ai.onnx.ml","inputs":[{"description":"A dictionary.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 1-D tensor holding values from the input dictionary.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["map(string, int64)","map(int64, string)","map(int64, float)","map(int64, double)","map(string, float)","map(string, double)"],"description":"The input must be a map from strings or integers to either strings or a numeric type. The key and value types cannot be the same.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)","tensor(float)","tensor(double)","tensor(string)"],"description":"The output will be a tensor of the value type of the input map. It's shape will be [1,C], where C is the length of the input dictionary.","type_param_str":"T2"}]}},{"name":"Div","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"description":"Performs element-wise binary division (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"description":"Performs element-wise binary division (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"(int, default 0) if nonzero, run dropout in test mode where the output is simply Y = X.","name":"is_test","required":false,"type":"int64"},{"default":0.5,"description":"(float, default 0.5) the ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask. If is_test is nonzero, this output is not filled.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(int, default 0) if nonzero, run dropout in test mode where the output is simply Y = X.","name":"is_test","required":false,"type":"int64"},{"default":0.5,"description":"(float, default 0.5) the ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask. If is_test is nonzero, this output is not filled.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"The ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"The ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input floating tensor and produces two tensor outputs,\noutput (floating tensor) and mask (`Tensor`). Depending on whether it is\nin test mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T1"}],"outputs_range":"1 - 2","since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output mask types to boolean tensors.","type_param_str":"T1"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"int64"}],"category":"Dropout","description":"Dropout takes an input floating-point tensor, an optional input ratio (floating-point scalar) and an optional input training_mode (boolean scalar). It produces two tensor outputs,\noutput (floating-point tensor) and mask (optional `Tensor`). If `training_mode` is true then the output Y will be a random dropout;\nNote that this Dropout scales the masked input data by the following equation, so to convert the trained model into inference mode,\nthe user can simply not pass `training_mode` input or set it to false.\n```\noutput = scale * data * mask,\n```\nwhere\n```\nscale = 1. / (1. - ratio).\n```\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"},{"description":"The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.","name":"ratio","option":"optional","type":"T1"},{"description":"If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.","name":"training_mode","option":"optional","type":"T2"}],"inputs_range":"1 - 3","max_input":3,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T2"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input 'ratio' types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output 'mask' types to boolean tensors.","type_param_str":"T2"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"int64"}],"category":"Dropout","description":"Dropout takes an input floating-point tensor, an optional input ratio (floating-point scalar) and an optional input training_mode (boolean scalar). It produces two tensor outputs,\noutput (floating-point tensor) and mask (optional `Tensor`). If `training_mode` is true then the output Y will be a random dropout;\nNote that this Dropout scales the masked input data by the following equation, so to convert the trained model into inference mode,\nthe user can simply not pass `training_mode` input or set it to false.\n```\noutput = scale * data * mask,\n```\nwhere\n```\nscale = 1. / (1. - ratio).\n```\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"},{"description":"The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.","name":"ratio","option":"optional","type":"T1"},{"description":"If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.","name":"training_mode","option":"optional","type":"T2"}],"inputs_range":"1 - 3","max_input":3,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T2"}],"outputs_range":"1 - 2","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input 'ratio' types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output 'mask' types to boolean tensors.","type_param_str":"T2"}]}},{"name":"DynamicQuantizeLinear","schema":{"description":"A Function to fuse calculation for Scale, Zero Point and FP32->8Bit convertion of FP32 Input data.\nOutputs Scale, ZeroPoint and Quantized Input for a given FP32 Input.\nScale is calculated as:\n```\n y_scale = (max(x) - min(x))/(qmax - qmin)\n * where qmax and qmin are max and min values for quantization range .i.e [0, 255] in case of uint8\n * data range is adjusted to include 0.\n```\nZero point is calculated as:\n```\nintermediate_zero_point = qmin - min(x)/y_scale\ny_zero_point = cast(round(saturate(itermediate_zero_point)))\n* where qmax and qmin are max and min values for quantization range .i.e [0, 255] in case of uint8\n* for saturation, it saturates to [0, 255] if it's uint8, or [-127, 127] if it's int8. Right now only uint8 is supported.\n* rounding to nearest ties to even.\n```\nData quantization formula is:\n```\ny = saturate (round (x / y_scale) + y_zero_point)\n* for saturation, it saturates to [0, 255] if it's uint8, or [-127, 127] if it's int8. Right now only uint8 is supported.\n* rounding to nearest ties to even.\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DynamicQuantizeLinear',\n inputs=['x'],\n outputs=['y', 'y_scale', 'y_zero_point'],\n)\n\n# expected scale 0.0196078438 and zero point 153\nX = np.array([0, 2, -3, -2.5, 1.34, 0.5]).astype(np.float32)\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear')\n\n# expected scale 0.0156862754 and zero point 255\nX = np.array([-1.0, -2.1, -1.3, -2.5, -3.34, -4.0]).astype(np.float32)\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear_max_adjusted')\n\nX = np.array([1, 2.1, 1.3, 2.5,\n 3.34, 4.0, 1.5, 2.6,\n 3.9, 4.0, 3.0, 2.345]).astype(np.float32).reshape((3, 4))\n\n# expected scale 0.0156862754 and zero point 0\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear_min_adjusted')","summary":"dynamicquantizelinear"}],"inputs":[{"description":"Input tensor","name":"x","type":"T1"}],"max_input":1,"max_output":3,"min_input":1,"min_output":3,"outputs":[{"description":"Quantized output tensor","name":"y","type":"T2"},{"description":"Output scale. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Output zero point. It's a scalar, which means a per-tensor/layer quantization.","name":"y_zero_point","type":"T2"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)"],"description":"Constrain 'x' to float tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit unsigned integer tensor.","type_param_str":"T2"}]}},{"name":"Einsum","schema":{"attributes":[{"description":"Einsum expression string.","name":"equation","required":true,"type":"string"}],"description":"An einsum of the form ```term1, term2 -> output-term``` produces an output tensor using the following equation\n\n```output[output-term] = reduce-sum( input1[term1] * input2[term] )```\n\nwhere the reduce-sum performs a summation over all the indices occurring in in the input terms (term1, term2)\nthat do not occur in the output-term.\n\nThe Einsum operator evaluates algebraic tensor operations on a sequence of tensors, using the Einstein summation\nconvention. The equation string contains a comma-separated sequence of lower case letters. Each term corresponds to\nan operand tensor, and the characters within the terms correspond to operands dimensions.\n\nThis sequence may be followed by \"->\" to separate the left and right hand side of the equation.\nIf the equation contains \"->\" followed by the right-hand side, the explicit (not classical) form of the Einstein\nsummation is performed, and the right-hand side indices indicate output tensor dimensions. In other cases,\noutput indices are (implicitly) set to the alphabetically sorted sequence of indices appearing exactly once in the\nequation.\n\nWhen a dimension character is repeated in the left-hand side, it represents summation along the dimension.\n\nThe equation may contain ellipsis (\"...\") to enable broadcasting. Ellipsis must indicate a fixed number of dimensions.\nSpecifically, every occurrence of ellipsis in the equation must represent the same number of dimensions.\nThe right-hand side may contain exactly one ellipsis. In implicit mode, the ellipsis dimensions are set to the\nbeginning of the output. The equation string may contain space (U+0020) character.\n","domain":"ai.onnx","examples":[{"code":"Eqn = '...ii ->...i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 5, 5)\nZ = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Z], name='test_einsum_batch_diagonal')","summary":"einsum_batch_diagonal"},{"code":"Eqn = 'bij, bjk -> bik'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x', 'y'],\n outputs=['z'],\n equation=Eqn\n)\n\nX = np.random.randn(5, 2, 3)\nY = np.random.randn(5, 3, 4)\nZ = einsum_reference_implementation(Eqn, (X, Y))\n\nexpect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_batch_matmul')","summary":"einsum_batch_matmul"},{"code":"Eqn = 'i,i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x', 'y'],\n outputs=['z'],\n equation=Eqn\n)\n\nX = np.random.randn(5)\nY = np.random.randn(5)\nZ = einsum_reference_implementation(Eqn, (X, Y))\n\nexpect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_inner_prod')","summary":"einsum_inner_prod"},{"code":"Eqn = 'ij->i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 4)\nZ = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Z], name='test_einsum_sum')","summary":"einsum_sum"},{"code":"Eqn = 'ij->ji'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 4)\nY = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Y], name='test_einsum_transpose')","summary":"einsum_transpose"}],"inputs":[{"description":"Operands","name":"Inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numerical tensor types.","type_param_str":"T"}]}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Coefficient of ELU default to 1.0.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Elu takes one input data (Tensor) and produces one output data\n(Tensor) where the function `f(x) = alpha * (exp(x) - 1.) for x <\n0`, `f(x) = x for x >= 0`., is applied to the tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-1.2642411, 0., 1.]\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu')","summary":"elu"},{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_default')","summary":"elu_default"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Coefficient of ELU.","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"Elu takes one input data (Tensor) and produces one output data\n(Tensor) where the function `f(x) = alpha * (exp(x) - 1.) for x <\n0`, `f(x) = x for x >= 0`., is applied to the tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-1.2642411, 0., 1.]\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu')","summary":"elu"},{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_default')","summary":"elu_default"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Equal","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)"],"description":"Constrains input to integral tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)"],"description":"Constrains input to integral tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Erf","schema":{"description":"Computes the error function of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Erf',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\ny = np.vectorize(math.erf)(x).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_erf')","summary":"erf"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The error function of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Erf","schema":{"description":"Computes the error function of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Erf',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\ny = np.vectorize(math.erf)(x).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_erf')","summary":"erf"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The error function of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Expand","schema":{"description":"Broadcast the input tensor following the given shape and the broadcast rule.\nThe broadcast rule is similar to numpy.array(input) * numpy.ones(shape):\nDimensions are right alignment;\nTwo corresponding dimension must have the same value, or one of them is equal to 1.\nAlso, this operator is similar to numpy.broadcast_to(input, shape),\nbut the major difference is numpy.broadcast_to() does not allow shape to be smaller than input.size().\nIt is possible that the output.shape is not equal to shape, when some dimensions in shape is equal to 1,\nor the shape.ndim < input.shape.ndim.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nnew_shape = [2, 1, 6]\nexpanded = data * np.ones(new_shape, dtype=np.float32)\n#print(expanded)\n#[[[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]],\n#\n# [[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_changed')","summary":"dim_changed"},{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\nnew_shape = [3, 4]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nexpanded = np.tile(data, 4)\n#print(expanded)\n#[[1., 1., 1., 1.],\n# [2., 2., 2., 2.],\n# [3., 3., 3., 3.]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_unchanged')","summary":"dim_unchanged"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"},{"description":"A 1-D tensor indicates the shape you want to expand to, following the broadcast rule","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"output","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensors.","type_param_str":"T"}]}},{"name":"Expand","schema":{"description":"Broadcast the input tensor following the given shape and the broadcast rule.\nThe broadcast rule is similar to numpy.array(input) * numpy.ones(shape):\nDimensions are right alignment;\nTwo corresponding dimension must have the same value, or one of them is equal to 1.\nAlso, this operator is similar to numpy.broadcast_to(input, shape),\nbut the major difference is numpy.broadcast_to() does not allow shape to be smaller than input.size().\nIt is possible that the output.shape is not equal to shape, when some dimensions in shape is equal to 1,\nor the shape.ndim < input.shape.ndim.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nnew_shape = [2, 1, 6]\nexpanded = data * np.ones(new_shape, dtype=np.float32)\n#print(expanded)\n#[[[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]],\n#\n# [[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_changed')","summary":"dim_changed"},{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\nnew_shape = [3, 4]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nexpanded = np.tile(data, 4)\n#print(expanded)\n#[[1., 1., 1., 1.],\n# [2., 2., 2., 2.],\n# [3., 3., 3., 3.]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_unchanged')","summary":"dim_unchanged"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"},{"description":"A 1-D tensor indicates the shape you want to expand to, following the broadcast rule","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensors.","type_param_str":"T"}]}},{"name":"EyeLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor. If not specified,the data type of the input tensor T1 is used. If input tensor T1 is also notspecified, then type defaults to 'float'.","name":"dtype","required":false,"type":"int64"},{"description":"(Optional) Index of the diagonal to be populated with ones. Default is 0. If T2 is the output, this op sets T2[i, i+k] = 1. k = 0 populates the main diagonal, k > 0 populates an upper diagonal, and k < 0 populates a lower diagonal.","name":"k","required":false,"type":"int64"}],"description":"Generate a 2D tensor (matrix) with ones on the diagonal and zeros everywhere else. Only 2D\ntensors are supported, i.e. input T1 must be of rank 2. The shape of the output tensor is the\nsame as the input tensor. The data type can be specified by the 'dtype' argument. If\n'dtype' is not specified, then the type of input tensor is used. By default, the main diagonal\nis populated with ones, but attribute 'k' can be used to populate upper or lower diagonals.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message and be valid as an output type.\n","domain":"ai.onnx","examples":[{"code":"shape = (4, 5)\noff_diagonal_offset = 1\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n k=off_diagonal_offset,\n dtype=onnx.TensorProto.FLOAT,\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_populate_off_main_diagonal')","summary":"populate_off_main_diagonal"},{"code":"shape = (3, 4)\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n dtype=onnx.TensorProto.DOUBLE,\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], dtype=np.float64)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_with_dtype')","summary":"with_dtype"},{"code":"shape = (4, 4)\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_without_dtype')","summary":"without_dtype"}],"inputs":[{"description":"2D input tensor to copy shape, and optionally, type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, same shape as input tensor T1.","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"FeatureVectorizer","schema":{"attributes":[{"description":"The size of each input in the input list","name":"inputdimensions","required":false,"type":"int64[]"}],"description":"Concatenates input tensors into one continuous output.
\n All input shapes are 2-D and are concatenated along the second dimention. 1-D tensors are treated as [1,C].\n Inputs are copied to the output maintaining the order of the input arguments.
\n All inputs must be integers or floats, while the output will be all floating point values.\n","domain":"ai.onnx.ml","inputs":[{"description":"An ordered collection of tensors, all with the same element type.","name":"X","option":"variadic","type":"T1"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output array, elements ordered as the inputs.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float)","tensor(double)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T1"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [0, R], where R is the rank of the input tensor. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [0, R], where R is the rank of the input tensor. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Floor","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Floor","schema":{"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Floor","schema":{"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"foward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*Rz + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*Rr + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*Rh + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*Rh + Rbh) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":2,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"When computing the output of the hidden gate, apply the linear transformation before multiplying by the output of the reset gate.","name":"linear_before_reset","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*Rz + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*Rr + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*Rh + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*Rh + Rbh) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":3,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"When computing the output of the hidden gate, apply the linear transformation before multiplying by the output of the reset gate.","name":"linear_before_reset","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*(Rz^T) + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*(Rr^T) + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*(Rh^T) + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*(Rh^T) + Rbh)) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1]","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\nExample 1:\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\n\naxis = 0 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\naxis = 1 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[j_{0}, k, j_{1}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\n\naxis = 0 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\naxis = 1 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[j_{0}, k, j_{1}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherElements","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"GatherElements takes two inputs `data` and `indices` of the same rank r >= 1\nand an optional attribute `axis` that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). It is an indexing operation\nthat produces its output by indexing into the input data tensor at index\npositions determined by elements of the `indices` tensor.\nIts output shape is the same as the shape of `indices` and consists of one value\n(gathered from the `data`) for each element in `indices`.\n\nFor instance, in the 3-D case (r = 3), the output produced is determined\nby the following equations: \n```\n out[i][j][k] = input[index[i][j][k]][j][k] if axis = 0,\n out[i][j][k] = input[i][index[i][j][k]][k] if axis = 1,\n out[i][j][k] = input[i][j][index[i][j][k]] if axis = 2,\n```\n\nThis operator is also the inverse of ScatterElements. It is similar to Torch's gather operation.\n\nExample 1:\n```\n data = [\n [1, 2],\n [3, 4],\n ]\n indices = [\n [0, 0],\n [1, 0],\n ]\n axis = 1\n output = [\n [\n [1, 1],\n [4, 3],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n ]\n indices = [\n [1, 2, 0],\n [2, 0, 0],\n ]\n axis = 0\n output = [\n [\n [4, 8, 3],\n [7, 2, 3],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2],\n [3, 4]], dtype=np.float32)\nindices = np.array([[0, 0],\n [1, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[1, 1],\n# [4, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_0')","summary":"gather_elements_0"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[1, 2, 0],\n [2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[4, 8, 3],\n# [7, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_1')","summary":"gather_elements_1"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[-1, -2, 0],\n [-2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[7, 5, 3],\n# [4, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_negative_indices')","summary":"gather_elements_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, with the same rank r as the input. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of the same shape as indices.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherElements","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"GatherElements takes two inputs `data` and `indices` of the same rank r >= 1\nand an optional attribute `axis` that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). It is an indexing operation\nthat produces its output by indexing into the input data tensor at index\npositions determined by elements of the `indices` tensor.\nIts output shape is the same as the shape of `indices` and consists of one value\n(gathered from the `data`) for each element in `indices`.\n\nFor instance, in the 3-D case (r = 3), the output produced is determined\nby the following equations: \n```\n out[i][j][k] = input[index[i][j][k]][j][k] if axis = 0,\n out[i][j][k] = input[i][index[i][j][k]][k] if axis = 1,\n out[i][j][k] = input[i][j][index[i][j][k]] if axis = 2,\n```\n\nThis operator is also the inverse of ScatterElements. It is similar to Torch's gather operation.\n\nExample 1:\n```\n data = [\n [1, 2],\n [3, 4],\n ]\n indices = [\n [0, 0],\n [1, 0],\n ]\n axis = 1\n output = [\n [\n [1, 1],\n [4, 3],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n ]\n indices = [\n [1, 2, 0],\n [2, 0, 0],\n ]\n axis = 0\n output = [\n [\n [4, 8, 3],\n [7, 2, 3],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2],\n [3, 4]], dtype=np.float32)\nindices = np.array([[0, 0],\n [1, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[1, 1],\n# [4, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_0')","summary":"gather_elements_0"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[1, 2, 0],\n [2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[4, 8, 3],\n# [7, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_1')","summary":"gather_elements_1"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[-1, -2, 0],\n [-2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[7, 5, 3],\n# [4, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_negative_indices')","summary":"gather_elements_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, with the same rank r as the input. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of the same shape as indices.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherND","schema":{"description":"Given `data` tensor of rank `r` >= 1, and `indices` tensor of rank `q` >= 1, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r` (inclusive) \n\n3) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r` => error condition\n\n2) If `indices_shape[-1] == r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor\n containing 1-D tensors of dimension `r`. Let us think of each such `r` ranked tensor as `indices_slice`. \n Each *scalar value* corresponding to `data[indices_slice]` is filled into the corresponding location of the `(q-1)`-dimensional tensor \n to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r`. Let us think of each such tensors as `indices_slice`. \n Each *tensor slice* corresponding to `data[indices_slice , :]` is filled into the corresponding location of the `(q-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, and 4 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"GatherND","schema":{"attributes":[{"description":"The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:]","name":"batch_dims","required":false,"type":"int64"}],"description":"Given `data` tensor of rank `r` >= 1, `indices` tensor of rank `q` >= 1, and `batch_dims` integer `b`, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1 - b`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\n`batch_dims` (denoted as `b`) is an integer indicating the number of batch dimensions, i.e the leading `b` number of dimensions of \n`data` tensor and `indices` are representing the batches, and the gather starts from the `b+1` dimension. \n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The first `b` dimensions of the shape of `indices` tensor and `data` tensor must be equal.\n\n3) b < min(q, r) is to be honored.\n\n4) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r-b` (inclusive) \n\n5) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r-b` => error condition\n\n2) If `indices_shape[-1] == r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensors\n containing 1-D tensors of dimension `r-b`, where `N` is an integer equals to the product of 1 and all the elements in the batch dimensions \n of the indices_shape. Let us think of each such `r-b` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[0:b-1,indices_slice]` \n is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r-b`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding \n to `data[0:b-1, indices_slice , :]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, 4 and 5 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n`Example 5`\n\n batch_dims = 1\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"GatherND","schema":{"attributes":[{"description":"The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:]","name":"batch_dims","required":false,"type":"int64"}],"description":"Given `data` tensor of rank `r` >= 1, `indices` tensor of rank `q` >= 1, and `batch_dims` integer `b`, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1 - b`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\n`batch_dims` (denoted as `b`) is an integer indicating the number of batch dimensions, i.e the leading `b` number of dimensions of \n`data` tensor and `indices` are representing the batches, and the gather starts from the `b+1` dimension. \n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The first `b` dimensions of the shape of `indices` tensor and `data` tensor must be equal.\n\n3) b < min(q, r) is to be honored.\n\n4) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r-b` (inclusive) \n\n5) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r-b` => error condition\n\n2) If `indices_shape[-1] == r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensors\n containing 1-D tensors of dimension `r-b`, where `N` is an integer equals to the product of 1 and all the elements in the batch dimensions \n of the indices_shape. Let us think of each such `r-b` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[0:b-1,indices_slice]` \n is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r-b`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding \n to `data[0:b-1, indices_slice , :]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, 4 and 5 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n`Example 5`\n\n batch_dims = 1\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B, the default value is 1.0.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C, the default value is 1.0.","name":"beta","required":false,"type":"float32"},{"description":"Whether C should be broadcasted","name":"broadcast","required":false,"type":"int64"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\nCompute Y = alpha * A * B + beta * C, where input tensor A has\ndimension (M X K), input tensor B has dimension (K X N), input tensor C and\noutput tensor Y have dimension (M X N).\nIf attribute broadcast is non-zero, input tensor C will be broadcasted to match\nthe dimension requirement. A will be transposed before doing the computation\nif attribute transA is non-zero, same for B and transB.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A","name":"A","type":"T"},{"description":"Input tensor B","name":"B","type":"T"},{"description":"Input tensor C, can be inplace.","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B, the default value is 1.0.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C, the default value is 1.0.","name":"beta","required":false,"type":"float32"},{"description":"Whether C should be broadcasted","name":"broadcast","required":false,"type":"int64"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\nCompute Y = alpha * A * B + beta * C, where input tensor A has\ndimension (M X K), input tensor B has dimension (K X N), input tensor C and\noutput tensor Y have dimension (M X N).\nIf attribute broadcast is non-zero, input tensor C will be broadcasted to match\nthe dimension requirement. A will be transposed before doing the computation\nif attribute transA is non-zero, same for B and transB.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A","name":"A","type":"T"},{"description":"Input tensor B","name":"B","type":"T"},{"description":"Input tensor C","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor.","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Input tensor C. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Input tensor C. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Optional input tensor C. If not specified, the computation is done as if C is a scalar 0. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Optional input tensor C. If not specified, the computation is done as if C is a scalar 0. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(bfloat16)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"GlobalAveragePool","schema":{"category":"Pool","description":"GlobalAveragePool consumes an input tensor X and applies average pooling across\n the values in the same channel. This is equivalent to AveragePool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GlobalAveragePool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(1, 3, 5, 5).astype(np.float32)\nspatial_shape = np.ndim(x) - 2\ny = np.average(x, axis=tuple(range(spatial_shape, spatial_shape + 2)))\nfor _ in range(spatial_shape):\n y = np.expand_dims(y, -1)\nexpect(node, inputs=[x], outputs=[y], name='test_globalaveragepool')","summary":"globalaveragepool"},{"code":"\nnode = onnx.helper.make_node(\n 'GlobalAveragePool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n]]]).astype(np.float32)\ny = np.array([[[[5]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_globalaveragepool_precomputed')","summary":"globalaveragepool_precomputed"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalLpPool","schema":{"attributes":[{"default":2,"description":"p value of the Lp norm used to pool over the input data, default is 2.0.","name":"p","required":false,"type":"float32"}],"category":"Pool","description":"GlobalLpPool consumes an input tensor X and applies lp pool pooling across the\n the values in the same channel. This is equivalent to LpPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimension are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. Dimensions will be N x C x 1 x 1","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalLpPool","schema":{"attributes":[{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"}],"category":"Pool","description":"GlobalLpPool consumes an input tensor X and applies lp pool pooling across\n the values in the same channel. This is equivalent to LpPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalMaxPool","schema":{"category":"Pool","description":"GlobalMaxPool consumes an input tensor X and applies max pooling across\n the values in the same channel. This is equivalent to MaxPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","examples":[{"code":"\nnode = onnx.helper.make_node(\n 'GlobalMaxPool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(1, 3, 5, 5).astype(np.float32)\nspatial_shape = np.ndim(x) - 2\ny = np.max(x, axis=tuple(range(spatial_shape, spatial_shape + 2)))\nfor _ in range(spatial_shape):\n y = np.expand_dims(y, -1)\nexpect(node, inputs=[x], outputs=[y], name='test_globalmaxpool')","summary":"globalmaxpool"},{"code":"\nnode = onnx.helper.make_node(\n 'GlobalMaxPool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n]]]).astype(np.float32)\ny = np.array([[[[9]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_globalmaxpool_precomputed')","summary":"globalmaxpool_precomputed"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gradient","schema":{"attributes":[{"description":"Input tensor names of the differentiated sub-graph. It contains only the necessary differentiated inputs of a (sub-)graph. Variables (usually called intermediate variables) that can be generated from inputs cannot be included in this attribute.","name":"xs","required":true,"type":"string[]"},{"description":"The targeted tensor. It can be viewed as the output of the differentiated function. The attribute \"xs\" and attribute \"zs\" are the minimal independent variable set that determines the value of \"y\".","name":"y","required":true,"type":"string"},{"description":"Input tensor names of the differentiated sub-graph. It contains only the necessary non-differentiated inputs of a (sub-)graph. Variables (usually called intermediate variables) that can be generated from inputs cannot be included in this attribute.","name":"zs","required":false,"type":"string[]"}],"description":"Gradient operator computes the partial derivatives of a specific tensor w.r.t.\nsome other tensors. This operator is widely used in gradient-based training\nalgorithms. To illustrate its use, let's consider a computation graph,\n\n```\nX -----.\n |\n v\nW --> Conv --> H --> Gemm --> Y\n ^\n |\n Z\n```\n\n, where W and Z are trainable tensors. Note that operators' attributes are\nomitted for the sake of simplicity. Let dY/dW (dY/dZ) be the gradient of\nY with respect to W (Z). The user can compute gradient by inserting Gradient\noperator to form another graph shown below.\n\n```\nW --> Conv --> H --> Gemm --> Y\n| ^ ^\n| | |\n| X Z\n| | |\n| | .----------'\n| | | (W/Z/X is the 1st/2nd/3rd input of Gradient as shown in\n| | | \"xs\" followed by \"zs\")\n| v v\n'---> Gradient(xs=[\"W\", \"Z\"], zs=[\"X\"], y=\"Y\")\n | |\n | '-----------------------------------> dY/dW (1st output of Gradient)\n |\n '---------------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nBy definition, the tensor \"y\" is a function of independent variables in \"xs\"\nand \"zs\". Since we only compute the gradient of \"y\" w.r.t. the differentiable\nvariables in \"xs\", this Gradient only outputs dY/dW and dY/dZ. Note that \"H\"\ncannot appear in \"xs\" and \"zs\". The reason is that \"H\" can be determined by\ntensors \"W\" and \"X\" and therefore \"H\" is not an independent variable.\n\nAll outputs are optional. If needed, for example, user can assign an empty\nstring to the 1st output name of that Gradient to skip the generation of dY/dW.\nNote that the concept of optional outputs can also be found in ONNX's RNN, GRU,\nand LSTM.\n\nGradient operator can compute derivative against intermediate tensors. For\nexample, the gradient of Y with respect to H can be done via\n\n```\nW --> Conv --> H --> Gemm --> Y\n ^ | ^\n | | |\n X | Z\n .-------' |\n | .----------'\n | | (H/Z is the 1st/2nd input of Gradient as shown in \"xs\")\n v v\n Gradient(xs=[\"H\", \"Z\"], y=\"Y\")\n | |\n | '-----------------------------------> dY/dH (1st output of Gradient)\n |\n '---------------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nIt is possible to represent high-order differentiation using Gradient operators.\nFor example, given the following linear model:\n\n```\nW --> Gemm --> Y --> Loss --> O\n ^ ^\n | |\n X L\n```\n\nTo compute the 2nd order derivative of O with respect to W (denoted by\nd^2O/dW^2), one can do\n\n```\nW --> Gemm --> Y --> Loss --> O\n| ^ ^\n| | |\n| X .------------L\n| | | |\n| | | v\n+------+-+> Gradient(xs=[\"X\", \"W\"], zs=[\"L\"], y=\"O\") ---> dO/dX (1st output of Gradient)\n| | | |\n| | | '---> dO/dW (2nd output of Gradient)\n| v v\n'---> Gradient(xs=[\"X\", \"W\"], zs=[\"L\"], y=\"dO/dW\") ---> d(dO/dW)dX (1st output of\n | Gradient)\n |\n |\n '---> d^2O/dW^2 (2nd output of Gradient)\n```\n\nThe tensors named in attributes \"xs\", \"zs\", and \"y\" define the differentiated\ncomputation graph, and the inputs to Gradient node define the values at\nwhich the gradient is computed. We can feed different tensors to the identified\ngraph. For example, one can compute the gradient of Y with respect to H at \na specific value of H, H_1, by providing that value as an input to the Gradient\nnode.\n\n```\nW --> Conv --> H --> Gemm --> Y\n ^ ^\n | |\n X Z\n\n Z_1 (2nd input of Gradient)\n |\n v\nH_1 --> Gradient(xs=[\"H\", \"Z\"], y=\"Y\") ---> dY/dH when H = H_1 and Y = Y_1.\n |\n '------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nWhen the inputs of Gradient are the tensors named in \"xs\" and \"zs\", the\ncomputation can be optimized. More specifically, intermediate variables in\nforward pass can be reused if the gradient is computed via reverse-mode\nauto-differentiation.\n\n","domain":"ai.onnx.preview.training","examples":[{"code":"add_node = onnx.helper.make_node('Add',\n ['a', 'b'], ['c'], name='my_add')\ngradient_node = onnx.helper.make_node(\n 'Gradient', ['a', 'b'],\n ['dc_da', 'dc_db'], name='my_gradient',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN,\n xs=['a', 'b'], y='c')\n\na = np.array(1.0).astype(np.float32)\nb = np.array(2.0).astype(np.float32)\nc = a + b\n# dc / da = d(a+b) / da = 1\ndc_da = np.array(1).astype(np.float32)\n# db / db = d(a+b) / db = 1\ndc_db = np.array(1).astype(np.float32)\n\ngraph = onnx.helper.make_graph(\n nodes=[add_node, gradient_node],\n name='GradientOfAdd',\n inputs=[\n onnx.helper.make_tensor_value_info('a', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('b', onnx.TensorProto.FLOAT,\n [])],\n outputs=[\n onnx.helper.make_tensor_value_info('c', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('dc_da',\n onnx.TensorProto.FLOAT, []),\n onnx.helper.make_tensor_value_info('dc_db',\n onnx.TensorProto.FLOAT, [])])\nopsets = [\n onnx.helper.make_operatorsetid(ONNX_DOMAIN, 12),\n onnx.helper.make_operatorsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)]\nmodel = onnx.helper.make_model(\n graph,\n producer_name='backend-test',\n opset_imports=opsets)\nexpect(model, inputs=[a, b], outputs=[c, dc_da, dc_db],\n name='test_gradient_of_add')","summary":"gradient_scalar_add"},{"code":"add_node = onnx.helper.make_node('Add',\n ['a', 'b'], ['c'], name='my_add')\nmul_node = onnx.helper.make_node('Mul',\n ['c', 'a'], ['d'], name='my_mul')\ngradient_node = onnx.helper.make_node(\n 'Gradient', ['a', 'b'],\n ['dd_da', 'dd_db'], name='my_gradient',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN,\n xs=['a', 'b'], y='d')\n\na = np.array(1.0).astype(np.float32)\nb = np.array(2.0).astype(np.float32)\nc = a + b\n# d = a * c = a * (a + b)\nd = a * c\n# dd / da = d(a*a+a*b) / da = 2 * a + b\ndd_da = (2 * a + b).astype(np.float32)\n# dd / db = d(a*a+a*b) / db = a\ndd_db = a\n\ngraph = onnx.helper.make_graph(\n nodes=[add_node, mul_node, gradient_node],\n name='GradientOfTwoOperators',\n inputs=[\n onnx.helper.make_tensor_value_info('a', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('b', onnx.TensorProto.FLOAT,\n [])],\n outputs=[\n onnx.helper.make_tensor_value_info('d', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('dd_da',\n onnx.TensorProto.FLOAT, []),\n onnx.helper.make_tensor_value_info('dd_db',\n onnx.TensorProto.FLOAT, [])])\n\nopsets = [\n onnx.helper.make_operatorsetid(ONNX_DOMAIN, 12),\n onnx.helper.make_operatorsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)]\nmodel = onnx.helper.make_model(graph,\n producer_name='backend-test',\n opset_imports=opsets)\nexpect(model, inputs=[a, b], outputs=[d, dd_da, dd_db],\n name='test_gradient_of_add_and_mul')","summary":"gradient_scalar_add_and_mul"}],"inputs":[{"description":"The values fed into graph identified by the attributes. The i-th input is the value of the i-th tensor specified in the concatenated list of the attribute \"xs\" and the attribute \"zs\". For example, if xs=[\"A\", \"B\"] and zs=[\"C\"], the first input is used as the value of symbol \"A\" and the 3rd input is substituted for all the occurrences of \"C\".","name":"Inputs","option":"variadic","type":"T1"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"The gradient of the tensor specified by the attribute \"y\" with respect to each of tensors specified in the attribute \"xs\". The i-th output is the gradient of \"y\" with respect to the i-th tensor specified in the attribute \"xs\".","name":"Outputs","option":"variadic","type":"T2"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Allow outputs to be any kind of tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Allow inputs to be any kind of floating-point tensor.","type_param_str":"T2"}]}},{"name":"GraphCall","schema":{"attributes":[{"description":"The invoked graph's name. The only allowed value is the name of the inference graph, which is stored in \"ModelProto.graph.name\" in the ONNX model format.","name":"graph_name","required":true,"type":"string"}],"description":"The GraphCall operator invokes a graph inside TrainingInfoProto's\nalgorithm field. The GraphCall inputs and outputs are bound to those of\ninvoked graph by position. If a graph input has an initializer, that input\nis considered optional. All graph outputs are optional.\n\nBelow Python syntax is used for describing dictionary and list.\n\nAssume that ModelProto's graph field has\n- name: \"MyInferenceGraph\"\n- input: [\"X\", \"W\", \"Z\"]\n- initializer: [W]\n- output: [\"Y\"]\n\nas visualized below for inference.\n\n```\nX -----.\n |\n v\nW --> Conv --> H --> Gemm --> Y\n ^\n |\n Z\n```\n\nAssume that the training algorithm contains\n\n- inputs: [\"X_1\", \"Z_1\", \"C\"]\n- initializer: [T]\n- outputs: [\"W_new\"]\n\nwith a dictionary\n\n- update_binding: {\"W\": \"W_new\", \"T\": \"T_new\"}\n\nInside the training algorithm graph, one can invoke the inference\ngraph via adding a GraphCall node with\n\n- inputs: [\"X_1\", \"W\", Z_1\"]\n- outputs: [\"Y_1\"]\n- an attribute graph_name=\"MyInferenceGraph\",\n\nThe initializers, \"W\" and \"T\" in this case, in update_binding\nare considered globally-visible and mutable variables, which\ncan be used as inputs of operators in the training graph.\n\nAn example training algorithm graph may look like\n\n```\n.-------- W (a global and mutable variable from\n| | the inference graph)\n| |\n| .-----'-----------.\n| | |\n| | v\n| | .-- X_1 --> GraphCall(graph_name=\"MyInferenceGraph\")\n| | | | |\n| | | | |\n| | | Z_1 -----' |\n| | | | V\n| | | | Y_1 ---> Loss ---> O\n| | | | ^\n| | | | |\n| | `--. | C\n| | | | |\n| | | | .----------------'\n| | | | |\n| | v v v\n| `--> Gradient(xs=[\"W\"], zs=[\"X_1\", \"Z_1\", \"C\"], y=\"O\")\n| |\n| v\n| dO_dW (gradient of W) 1 (a scalar one)\n| | |\n| V v\n| Div <--- T ------------> Add ---> T_new\n| | (T is the number of training iterations.\n| | T is also globally visible and mutable.)\n| v\n`-----> Sub ----> W_new\n```\n\nwhere Loss is a dummy node which computes the minimized objective function.\n\nThe variable \"W\" is an optional input in the called graph.\nIf the user omits it, the input list of GraphCall becomes [\"X_1\", \"\", \"Z_1\"].\nIn this case, from the view of computation graph, the Conv operator invoked by\nGraphCall's may be still connected the global \"W\" variable and therefore the\nstructure of the computation graph is unchanged.\n","domain":"ai.onnx.preview.training","inputs":[{"description":"Inputs fed to the invoked graph. The i-th input here goes to the i-th input of the invoked graph. To omit an optional input in this field, the user can drop it or use an empty string.","name":"Inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"The outputs generated by the called graph. Its i-th value is bound to the i-th output of the called graph. Similar to the inputs, all outputs are optional.","name":"Outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Allow inputs and outputs to be any kind of tensor.","type_param_str":"T"}]}},{"name":"Greater","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"GreaterOrEqual","schema":{"description":"Returns the tensor resulted from performing the `greater_equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"HardSigmoid","schema":{"attributes":[{"default":0.20000000298023224,"description":"Value of alpha default to 0.2","name":"alpha","required":false,"type":"float32"},{"default":0.5,"description":"Value of beta default to 0.5","name":"beta","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"HardSigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the HardSigmoid function, y = max(0, min(1, alpha * x + beta)),\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n alpha=0.5,\n beta=0.6\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid')","summary":"hardsigmoid"},{"code":"default_alpha = 0.2\ndefault_beta = 0.5\nnode = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * default_alpha + default_beta, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_default')","summary":"hardsigmoid_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"HardSigmoid","schema":{"attributes":[{"default":0.20000000298023224,"description":"Value of alpha.","name":"alpha","required":false,"type":"float32"},{"default":0.5,"description":"Value of beta.","name":"beta","required":false,"type":"float32"}],"category":"Activation","description":"HardSigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the HardSigmoid function, y = max(0, min(1, alpha * x + beta)),\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n alpha=0.5,\n beta=0.6\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid')","summary":"hardsigmoid"},{"code":"default_alpha = 0.2\ndefault_beta = 0.5\nnode = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * default_alpha + default_beta, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_default')","summary":"hardsigmoid_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Identity","schema":{"description":"Identity operator","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Identity',\n inputs=['x'],\n outputs=['y'],\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data], outputs=[data],\n name='test_identity')","summary":"identity"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor to copy input into.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Identity","schema":{"description":"Identity operator","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Identity',\n inputs=['x'],\n outputs=['y'],\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data], outputs=[data],\n name='test_identity')","summary":"identity"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor to copy input into.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"If","schema":{"attributes":[{"description":"Graph to run if condition is false. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the then_branch.","name":"else_branch","required":true,"type":"graph"},{"description":"Graph to run if condition is true. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the else_branch.","name":"then_branch","required":true,"type":"graph"}],"description":"If conditional","domain":"ai.onnx","inputs":[{"description":"Condition for the if","name":"cond","type":"B"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Values that are live-out to the enclosing scope. The return values in the `then_branch` and `else_branch` must be of the same shape and same data type.","name":"outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(bool)"],"description":"Only bool","type_param_str":"B"}]}},{"name":"If","schema":{"attributes":[{"description":"Graph to run if condition is false. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the then_branch.","name":"else_branch","required":true,"type":"graph"},{"description":"Graph to run if condition is true. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the else_branch.","name":"then_branch","required":true,"type":"graph"}],"description":"If conditional","domain":"ai.onnx","inputs":[{"description":"Condition for the if","name":"cond","type":"B"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Values that are live-out to the enclosing scope. The return values in the `then_branch` and `else_branch` must be of the same data type. The `then_branch` and `else_branch` may produce tensors with the same element type and different shapes. If corresponding outputs from the then-branch and the else-branch have static shapes S1 and S2, then the shape of the corresponding output variable of the if-node (if present) must be compatible with both S1 and S2 as it represents the union of both possible shapes.For example, if in a model file, the the first output of `then_branch` is typed float tensor with shape [2] and the first output of `else_branch` is another float tensor with shape [3], If's first output should have (a) no shape set, or (b) a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) a shape of rank 1 with a unique `dim_param`. In contrast, the first output cannot have the shape [2] since [2] and [3] are not compatible.","name":"outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(bool)"],"description":"Only bool","type_param_str":"B"}]}},{"name":"Imputer","schema":{"attributes":[{"description":"Value(s) to change to","name":"imputed_value_floats","required":false,"type":"float32[]"},{"description":"Value(s) to change to.","name":"imputed_value_int64s","required":false,"type":"int64[]"},{"description":"A value that needs replacing.","name":"replaced_value_float","required":false,"type":"float32"},{"description":"A value that needs replacing.","name":"replaced_value_int64","required":false,"type":"int64"}],"description":"Replaces inputs that equal one value with another, leaving all other elements alone.
\n This operator is typically used to replace missing values in situations where they have a canonical\n representation, such as -1, 0, NaN, or some extreme value.
\n One and only one of imputed_value_floats or imputed_value_int64s should be defined -- floats if the input tensor\n holds floats, integers if the input tensor holds integers. The imputed values must all fit within the\n width of the tensor element type. One and only one of the replaced_value_float or replaced_value_int64 should be defined,\n which one depends on whether floats or integers are being processed.
\n The imputed_value attribute length can be 1 element, or it can have one element per input feature.
In other words, if the input tensor has the shape [*,F], then the length of the attribute array may be 1 or F. If it is 1, then it is broadcast along the last dimension and applied to each feature.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be processed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Imputed output data","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type, either [N,C] or [C]. The output type will be of the same tensor type and shape.","type_param_str":"T"}]}},{"name":"InstanceNormalization","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out instance normalization as described in the paper\nhttps://arxiv.org/abs/1607.08022.\n\ny = scale * (x - mean) / sqrt(variance + epsilon) + B,\nwhere mean and variance are computed per instance per channel.\n\n","domain":"ai.onnx","examples":[{"code":"def _instancenorm_test_mode(x, s, bias, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n axis = tuple(range(2, dims_x))\n mean = np.mean(x, axis=axis, keepdims=True)\n var = np.var(x, axis=axis, keepdims=True)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\ny = _instancenorm_test_mode(x, s, bias).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nepsilon = 1e-2\ny = _instancenorm_test_mode(x, s, bias, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_epsilon')","summary":"instancenormalization"}],"inputs":[{"description":"The input 4-dimensional tensor of shape NCHW.","name":"input","type":"T"},{"description":"The input 1-dimensional scale tensor of size C.","name":"scale","type":"T"},{"description":"The input 1-dimensional bias tensor of size C.","name":"B","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"The output 4-dimensional tensor of the same shape as input.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"InstanceNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out instance normalization as described in the paper\nhttps://arxiv.org/abs/1607.08022.\n\ny = scale * (x - mean) / sqrt(variance + epsilon) + B,\nwhere mean and variance are computed per instance per channel.\n\n","domain":"ai.onnx","examples":[{"code":"def _instancenorm_test_mode(x, s, bias, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n axis = tuple(range(2, dims_x))\n mean = np.mean(x, axis=axis, keepdims=True)\n var = np.var(x, axis=axis, keepdims=True)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\ny = _instancenorm_test_mode(x, s, bias).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nepsilon = 1e-2\ny = _instancenorm_test_mode(x, s, bias, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_epsilon')","summary":"instancenormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"input","type":"T"},{"description":"The input 1-dimensional scale tensor of size C.","name":"scale","type":"T"},{"description":"The input 1-dimensional bias tensor of size C.","name":"B","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as input.","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"IsInf","schema":{"attributes":[{"default":1,"description":"(Optional) Whether map negative infinity to true. Default to 1 so that negative infinity induces true. Set this attribute to 0 if negative infinity should be mapped to false.","name":"detect_negative","required":false,"type":"int64"},{"default":1,"description":"(Optional) Whether map positive infinity to true. Default to 1 so that positive infinity induces true. Set this attribute to 0 if positive infinity should be mapped to false.","name":"detect_positive","required":false,"type":"int64"}],"description":"Map infinity to true and other values to false.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n )\n\nx = np.array([-1.2, np.nan, np.inf, 2.8, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isinf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf')","summary":"infinity"},{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n detect_positive=0\n )\n\nx = np.array([-1.7, np.nan, np.inf, -3.6, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isneginf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf_negative')","summary":"negative_infinity_only"},{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n detect_negative=0\n )\n\nx = np.array([-1.7, np.nan, np.inf, 3.6, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isposinf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf_positive')","summary":"positive_infinity_only"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"IsNaN","schema":{"description":"Returns which elements of the input are NaN.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'IsNaN',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([3.0, np.nan, 4.0, np.nan], dtype=np.float32)\ny = np.isnan(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isnan')","summary":"isnan"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"IsNaN","schema":{"description":"Returns which elements of the input are NaN.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'IsNaN',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([3.0, np.nan, 4.0, np.nan], dtype=np.float32)\ny = np.isnan(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isnan')","summary":"isnan"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"LRN","schema":{"attributes":[{"default":0.00009999999747378752,"description":"Scaling parameter.","name":"alpha","required":false,"type":"float32"},{"default":0.75,"description":"The exponent.","name":"beta","required":false,"type":"float32"},{"default":1,"description":"","name":"bias","required":false,"type":"float32"},{"description":"The number of channels to sum over","name":"size","required":true,"type":"int64"}],"category":"Normalization","description":"Local Response Normalization proposed in the [AlexNet paper](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf).\nIt normalizes over local input regions.\nThe local region is defined across the channels. For an element X[n, c, d1, ..., dk] in a tensor\nof shape (N x C x D1 x D2, ..., Dk), its region is\n{X[n, i, d1, ..., dk] | max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2))}.\n\nsquare_sum[n, c, d1, ..., dk] = sum(X[n, i, d1, ..., dk] ^ 2),\nwhere max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2)).\n\nY[n, c, d1, ..., dk] = X[n, c, d1, ..., dk] / (bias + alpha / size * square_sum[n, c, d1, ..., dk] ) ^ beta\n","domain":"ai.onnx","examples":[{"code":"alpha = 0.0001\nbeta = 0.75\nbias = 1.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n size=3\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn_default')","summary":"default"},{"code":"alpha = 0.0002\nbeta = 0.5\nbias = 2.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha,\n beta=beta,\n bias=bias,\n size=nsize\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn')","summary":"lrn"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, which has the shape and type as input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LRN","schema":{"attributes":[{"default":0.00009999999747378752,"description":"Scaling parameter.","name":"alpha","required":false,"type":"float32"},{"default":0.75,"description":"The exponent.","name":"beta","required":false,"type":"float32"},{"default":1,"description":"","name":"bias","required":false,"type":"float32"},{"description":"The number of channels to sum over","name":"size","required":true,"type":"int64"}],"category":"Normalization","description":"Local Response Normalization proposed in the [AlexNet paper](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf).\nIt normalizes over local input regions.\nThe local region is defined across the channels. For an element X[n, c, d1, ..., dk] in a tensor\nof shape (N x C x D1 x D2, ..., Dk), its region is\n{X[n, i, d1, ..., dk] | max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2))}.\n\nsquare_sum[n, c, d1, ..., dk] = sum(X[n, i, d1, ..., dk] ^ 2),\nwhere max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2)).\n\nY[n, c, d1, ..., dk] = X[n, c, d1, ..., dk] / (bias + alpha / size * square_sum[n, c, d1, ..., dk] ) ^ beta\n","domain":"ai.onnx","examples":[{"code":"alpha = 0.0001\nbeta = 0.75\nbias = 1.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n size=3\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn_default')","summary":"default"},{"code":"alpha = 0.0002\nbeta = 0.5\nbias = 2.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha,\n beta=beta,\n bias=bias,\n size=nsize\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn')","summary":"lrn"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, which has the shape and type as input tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LSTM","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"Couple the input and forget gates if 1, default 0.","name":"input_forget","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer LSTM. This operator is usually supported via some\ncustom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`o` - output gate\n\n`f` - forget gate\n\n`c` - cell gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates\n\n`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates\n\n`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates\n\n`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates\n\n`P[iof]` - P peephole weight vector for input, output, and forget gates\n\n`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates\n\n`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates\n\n`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates\n\n`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates\n\n`PB[iof]` - P peephole weight vector for backward input, output, and forget gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh, h=Tanh):\n\n - it = f(Xt*(Wi^T) + Ht-1*Ri + Pi (.) Ct-1 + Wbi + Rbi)\n\n - ft = f(Xt*(Wf^T) + Ht-1*Rf + Pf (.) Ct-1 + Wbf + Rbf)\n\n - ct = g(Xt*(Wc^T) + Ht-1*Rc + Wbc + Rbc)\n\n - Ct = ft (.) Ct-1 + it (.) ct\n\n - ot = f(Xt*(Wo^T) + Ht-1*Ro + Po (.) Ct + Wbo + Rbo)\n\n - Ht = ot (.) h(Ct)\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_lstm_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 4\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), 1)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3., 4.], [5., 6., 7., 8.]]]).astype(np.float32)\n\ninput_size = 4\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\nnumber_of_peepholes = 3\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B', 'sequence_lens', 'initial_h', 'initial_c', 'P'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\n# Initializing Inputs\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\nB = np.zeros((1, 2 * number_of_gates * hidden_size)).astype(np.float32)\nseq_lens = np.repeat(input.shape[0], input.shape[1]).astype(np.int32)\ninit_h = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\ninit_c = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\nP = weight_scale * np.ones((1, number_of_peepholes * hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B, P=P, initial_c=init_c, initial_h=init_h)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B, seq_lens, init_h, init_c, P], outputs=[Y_h.astype(np.float32)],\n name='test_lstm_with_peepholes')","summary":"peepholes"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, 4*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 4*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"},{"description":"Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_c","option":"optional","type":"T"},{"description":"The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.","name":"P","option":"optional","type":"T"}],"inputs_range":"3 - 8","max_input":8,"max_output":3,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"},{"description":"The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_c","option":"optional","type":"T"}],"outputs_range":"0 - 3","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"LSTM","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"Couple the input and forget gates if 1.","name":"input_forget","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer LSTM. This operator is usually supported via some\ncustom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`o` - output gate\n\n`f` - forget gate\n\n`c` - cell gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates\n\n`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates\n\n`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates\n\n`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates\n\n`P[iof]` - P peephole weight vector for input, output, and forget gates\n\n`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates\n\n`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates\n\n`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates\n\n`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates\n\n`PB[iof]` - P peephole weight vector for backward input, output, and forget gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh, h=Tanh):\n\n - it = f(Xt*(Wi^T) + Ht-1*(Ri^T) + Pi (.) Ct-1 + Wbi + Rbi)\n\n - ft = f(Xt*(Wf^T) + Ht-1*(Rf^T) + Pf (.) Ct-1 + Wbf + Rbf)\n\n - ct = g(Xt*(Wc^T) + Ht-1*(Rc^T) + Wbc + Rbc)\n\n - Ct = ft (.) Ct-1 + it (.) ct\n\n - ot = f(Xt*(Wo^T) + Ht-1*(Ro^T) + Po (.) Ct + Wbo + Rbo)\n\n - Ht = ot (.) h(Ct)\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_lstm_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 4\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), 1)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3., 4.], [5., 6., 7., 8.]]]).astype(np.float32)\n\ninput_size = 4\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\nnumber_of_peepholes = 3\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B', 'sequence_lens', 'initial_h', 'initial_c', 'P'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\n# Initializing Inputs\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\nB = np.zeros((1, 2 * number_of_gates * hidden_size)).astype(np.float32)\nseq_lens = np.repeat(input.shape[0], input.shape[1]).astype(np.int32)\ninit_h = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\ninit_c = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\nP = weight_scale * np.ones((1, number_of_peepholes * hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B, P=P, initial_c=init_c, initial_h=init_h)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B, seq_lens, init_h, init_c, P], outputs=[Y_h.astype(np.float32)],\n name='test_lstm_with_peepholes')","summary":"peepholes"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, 4*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 4*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"},{"description":"Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_c","option":"optional","type":"T"},{"description":"The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.","name":"P","option":"optional","type":"T"}],"inputs_range":"3 - 8","max_input":8,"max_output":3,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"},{"description":"The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_c","option":"optional","type":"T"}],"outputs_range":"0 - 3","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"LabelEncoder","schema":{"attributes":[{"description":"A list of labels.","name":"classes_strings","required":false,"type":"string[]"},{"default":-1,"description":"An integer to use when an input string value is not found in the map.
One and only one of the 'default_*' attributes must be defined.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string to use when an input integer value is not found in the map.
One and only one of the 'default_*' attributes must be defined.","name":"default_string","required":false,"type":"string"}],"description":"Converts strings to integers and vice versa.
\n If the string default value is set, it will convert integers to strings.\n If the int default value is set, it will convert strings to integers.
\n Each operator converts either integers to strings or strings to integers, depending \n on which default value attribute is provided. Only one default value attribute\n should be defined.
\n When converting from integers to strings, the string is fetched from the\n 'classes_strings' list, by simple indexing.
\n When converting from strings to integers, the string is looked up in the list\n and the index at which it is found is used as the converted value.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input data.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data. If strings are input, the output values are integers, and vice versa.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The input type must be a tensor of integers or strings, of any shape.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, and will have the same shape as the input.","type_param_str":"T2"}]}},{"name":"LabelEncoder","schema":{"attributes":[{"description":"A float.","name":"default_float","required":false,"type":"float32"},{"default":-1,"description":"An integer.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string.","name":"default_string","required":false,"type":"string"},{"description":"A list of floats.","name":"keys_floats","required":false,"type":"float32[]"},{"description":"A list of ints.","name":"keys_int64s","required":false,"type":"int64[]"},{"description":"A list of strings. One and only one of 'keys_*'s should be set.","name":"keys_strings","required":false,"type":"string[]"},{"description":"A list of floats.","name":"values_floats","required":false,"type":"float32[]"},{"description":"A list of ints.","name":"values_int64s","required":false,"type":"int64[]"},{"description":"A list of strings. One and only one of 'value_*'s should be set.","name":"values_strings","required":false,"type":"string[]"}],"description":"Maps each element in the input tensor to another value.
\n The mapping is determined by the two parallel attributes, 'keys_*' and\n 'values_*' attribute. The i-th value in the specified 'keys_*' attribute\n would be mapped to the i-th value in the specified 'values_*' attribute. It\n implies that input's element type and the element type of the specified\n 'keys_*' should be identical while the output type is identical to the\n specified 'values_*' attribute. If an input element can not be found in the\n specified 'keys_*' attribute, the 'default_*' that matches the specified\n 'values_*' attribute may be used as its output value.
\n Let's consider an example which maps a string tensor to an integer tensor.\n Assume and 'keys_strings' is [\"Amy\", \"Sally\"], 'values_int64s' is [5, 6],\n and 'default_int64' is '-1'. The input [\"Dori\", \"Amy\", \"Amy\", \"Sally\",\n \"Sally\"] would be mapped to [-1, 5, 5, 6, 6].
\n Since this operator is an one-to-one mapping, its input and output shapes\n are the same. Notice that only one of 'keys_*'/'values_*' can be set.
\n For key look-up, bit-wise comparison is used so even a float NaN can be\n mapped to a value in 'values_*' attribute.
\n","domain":"ai.onnx.ml","inputs":[{"description":"Input data. It can be either tensor or scalar.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data.","name":"Y","type":"T2"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(float)"],"description":"The input type is a tensor of any shape.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(float)"],"description":"Output type is determined by the specified 'values_*' attribute.","type_param_str":"T2"}]}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.009999999776482582,"description":"Coefficient of leakage default to 0.01.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"LeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=0.1\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-0.1, 0., 1.]\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu')","summary":"leakyrelu"},{"code":"default_alpha = 0.01\nnode = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_default')","summary":"leakyrelu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.009999999776482582,"description":"Coefficient of leakage.","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"LeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=0.1\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-0.1, 0., 1.]\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu')","summary":"leakyrelu"},{"code":"default_alpha = 0.01\nnode = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_default')","summary":"leakyrelu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Less","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"LessOrEqual","schema":{"description":"Returns the tensor resulted from performing the `less_equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"LinearClassifier","schema":{"attributes":[{"description":"Class labels when using integer labels. One and only one 'classlabels' attribute must be defined.","name":"classlabels_ints","required":false,"type":"int64[]"},{"description":"Class labels when using string labels. One and only one 'classlabels' attribute must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"A collection of weights of the model(s).","name":"coefficients","required":true,"type":"float32[]"},{"description":"A collection of intercepts.","name":"intercepts","required":false,"type":"float32[]"},{"description":"Indicates whether to do OvR or multinomial (0=OvR is the default).","name":"multi_class","required":false,"type":"int64"},{"default":"NONE","description":"Indicates the transform to apply to the scores vector.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"}],"description":"Linear classifier\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be classified.","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Classification outputs (one class per example).","name":"Y","type":"T2"},{"description":"Classification scores ([N,E] - one score for each class and example","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type, and of of shape [N,C] or [C]. In the latter case, it will be treated as [1,C]","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output will be a tensor of strings or integers.","type_param_str":"T2"}]}},{"name":"LinearRegressor","schema":{"attributes":[{"description":"Weights of the model(s).","name":"coefficients","required":false,"type":"float32[]"},{"description":"Weights of the intercepts, if used.","name":"intercepts","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the regression output vector.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"default":1,"description":"The total number of regression targets, 1 if not defined.","name":"targets","required":false,"type":"int64"}],"description":"Generalized linear regression evaluation.
\n If targets is set to 1 (default) then univariate regression is performed.
\n If targets is set to M then M sets of coefficients must be passed in as a sequence\n and M results will be output for each input n in N.
\n The coefficients array is of length n, and the coefficients for each target are contiguous.\n Intercepts are optional but if provided must match the number of targets.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be regressed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Regression outputs (one per target, per example).","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Log","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Log","schema":{"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Log","schema":{"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Loop","schema":{"attributes":[{"description":"The graph run each iteration. It has 2+N inputs: (iteration_num, condition, loop carried dependencies...). It has 1+N+K outputs: (condition, loop carried dependencies..., scan_outputs...). Each scan_output is created by concatenating the value of the specified output value at the end of each iteration of the loop. It is an error if the dimensions or data type of these scan_outputs change across loop iterations.","name":"body","required":true,"type":"graph"}],"description":"Generic Looping construct. This loop has multiple termination conditions:\n\n1) Trip count. Iteration count specified at runtime. Set by\n specifying the input M. Optional. Set to empty string to omit.\n Note that a static trip count (specified at graph construction time) can be\n specified by passing in a constant node for input M.\n2) Loop termination condition. This is an input to the op that determines\n whether to run the first iteration and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition variable,\n whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\n Operator inputs defined as (max_trip_count, condition_var).\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n\n\n*Sample usage - cond as well as trip count*\n\n graph predict-net {\n %a = Constant[value = ]()\n %b = Constant[value = ]()\n %keepgoing = Constant[value = ]()\n %max_trip_count = Constant[value = ]()\n %keepgoing_out, %b_out, %user_defined_vals = Loop[body = ](%max_trip_count, %keepgoing, %b)\n return\n }\n\n graph body-net (\n %i[INT32, scalar]\n %keepgoing[BOOL, scalar]\n %b[INT32, scalar]\n ) {\n %my_local = Add(%a, %b)\n %b_out = Sub(%a, %b)\n %keepgoing_out = Greater(%my_local, %b_out)\n %user_defined_vals = Add(%b, %b)\n return %keepgoing_out, %b_out, %user_defined_vals\n }\n\n*Sample equivalent C code*\n\n {\n /* User-defined code (enclosing scope) */\n int a = 3, b = 6;\n bool keepgoing = true; // Analogous to input cond\n /* End user-defined code */\n\n /* Implicitly-defined code */\n const int max_trip_count = 10; // Analogous to input M\n int user_defined_vals[]; // Imagine this is resizable\n /* End implicitly-defined code */\n for (int i=0; i < max_trip_count && keepgoing; ++i) {\n /* User-defined code (loop body) */\n int my_local = a + b; // Reading values in the enclosing scope is fine\n b = a - b; // writes fine if we specify b as a loop-carried dependency\n keepgoing = my_local > b; // keepgoing is a loop-carried dependency\n user_defined_vals[i] = b + b;\n /* End user-defined code */\n }\n // my_local = 123; // Can't do this. my_local was defined in the the body\n\n // These below values are live-out from the loop and therefore accessible\n b_out; user_defined_vals; keepgoing_out;\n }\n\nThere are several things of note in this code snippet:\n\n1) Values from the enclosing scope (i.e. variable a here) are in scope and can\n be referenced in the inputs of the loop.\n2) Any variables which you wish to make available in the enclosing scope (i.e.\n the variables b and keepgoing) must be declared as either loop-carried\n dependencies (both at the op inputs and output and at the body net input and\n output) or scan_outputs.\n3) Values created in the body cannot be accessed in the enclosing scope.\n\nNote that the semantics of this op support \"diagonal\" or \"wavefront\" execution.\n(See Step 3 here for an example:\nhttps://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).\nFrontends should emit multi-layer RNNs as a series of While operators (with\ntime being the inner looping dimension), with each successive layer consuming\nthe scan_outputs from the previous layer, possibly going through several\npoint-wise operators (e.g. dropout, residual connections, linear layer).\n","domain":"ai.onnx","inputs":[{"description":"A maximum trip-count for the loop specified at runtime. Optional. Pass empty string to skip.","name":"M","option":"optional","type":"I"},{"description":"A boolean termination condition. Optional. Pass empty string to skip.","name":"cond","option":"optional","type":"B"},{"description":"The initial values of any loop-carried dependencies (values that change across loop iterations)","name":"v_initial","option":"variadic","type":"V"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"Final N loop carried dependency values then K scan_outputs","name":"v_final_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(int64)"],"description":"tensor of int64, which should be a scalar.","type_param_str":"I"},{"allowed_type_strs":["tensor(bool)"],"description":"tensor of bool, which should be a scalar.","type_param_str":"B"}]}},{"name":"Loop","schema":{"attributes":[{"description":"The graph run each iteration. It has 2+N inputs: (iteration_num, condition, loop carried dependencies...). It has 1+N+K outputs: (condition, loop carried dependencies..., scan_outputs...). Each scan_output is created by concatenating the value of the specified output value at the end of each iteration of the loop. It is an error if the dimensions or data type of these scan_outputs change across loop iterations.","name":"body","required":true,"type":"graph"}],"description":"Generic Looping construct. This loop has multiple termination conditions:\n\n1) Trip count. Iteration count specified at runtime. Set by\n specifying the input M. Optional. Set to empty string to omit.\n Note that a static trip count (specified at graph construction time) can be\n specified by passing in a constant node for input M.\n2) Loop termination condition. This is an input to the op that determines\n whether to run the first iteration and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition variable,\n whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\n Operator inputs defined as (max_trip_count, condition_var).\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n\n\n*Sample usage - cond as well as trip count*\n\n graph predict-net {\n %a = Constant[value = ]()\n %b = Constant[value = ]()\n %keepgoing = Constant[value = ]()\n %max_trip_count = Constant[value = ]()\n %keepgoing_out, %b_out, %user_defined_vals = Loop[body = ](%max_trip_count, %keepgoing, %b)\n return\n }\n\n graph body-net (\n %i[INT32, scalar] // iteration number\n %keepgoing_in[BOOL, scalar] // incoming loop-termination-condition; not used\n %b_in[INT32, scalar] // incoming value of loop-carried-dependency b\n ) {\n %my_local = Add(%a, %b_in)\n %b_out = Sub(%a, %b_in) // outgoing value of loop-carried-dependency b\n %keepgoing_out = Greater(%my_local, %b_out) // outgoing loop-termination-condition\n %user_defined_val = Add(%b_in, %b_in) // scan-output value to be accumulated\n return %keepgoing_out, %b_out, %user_defined_val\n }\n\n*Sample equivalent C code*\n\n {\n /* User-defined code (enclosing scope) */\n int a = 3, b = 6;\n bool keepgoing = true; // Analogous to input cond\n /* End user-defined code */\n\n /* Implicitly-defined code */\n const int max_trip_count = 10; // Analogous to input M\n int user_defined_vals[]; // Imagine this is resizable\n /* End implicitly-defined code */\n /* initialize loop-carried variables and scan-output variables */\n bool keepgoing_out = keepgoing\n int b_out = b\n\n for (int i=0; i < max_trip_count && keepgoing_out; ++i) {\n /* Implicitly-defined code: bind actual parameter values\n to formal parameter variables of loop-body */\n bool keepgoing_in = keepgoing_out; \n bool b_in = b_out;\n\n /* User-defined code (loop body) */\n int my_local = a + b_in; // Reading value \"a\" from the enclosing scope is fine\n b_out = a - b_in;\n keepgoing_out = my_local > b_out; \n user_defined_val = b_in + b_in; // b_in and b_out are different variables\n /* End user-defined code */\n\n /* Implicitly defined-code */\n user_defined_vals[i] = user_defined_val // accumulate scan-output values\n }\n // int t = my_local; // Can't do this. my_local is not accessible here.\n\n // The values below are bound to the output variables of the loop and therefore accessible\n // b_out; user_defined_vals; keepgoing_out;\n }\n\nThere are several things of note in this code snippet:\n\n1) Values from the enclosing scope (i.e. variable \"a\" here) are in scope and can\n be referenced in the inputs of the loop.\n2) Any values computed in the loop body that needs to be used in a subsequent\n iteration or after the loop are modelled using a pair of variables in the loop-body,\n consisting of an input variable (eg., b_in) and an output variable (eg., b_out).\n These are referred to as loop-carried dependences. The loop operation node\n supplies the input value of the input variable for the first iteration, and\n returns the output value of the output variable produced by the final\n iteration.\n3) Scan_output variables are used to implicitly concatenate values computed across\n all the iterations. In the above example, the value of user_defined_val computed\n over all iterations are concatenated and returned as the value of user_defined_vals\n after the loop.\n4) Values created in the body cannot be accessed in the enclosing scope,\n except using the mechanism described above.\n\nNote that the semantics of this op support \"diagonal\" or \"wavefront\" execution.\n(See Step 3 here for an example:\nhttps://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).\nFrontends should emit multi-layer RNNs as a series of While operators (with\ntime being the inner looping dimension), with each successive layer consuming\nthe scan_outputs from the previous layer, possibly going through several\npoint-wise operators (e.g. dropout, residual connections, linear layer).\n\nThe input/output of subgraph (produced by loop node) matching is based on order instead of name. The implementation will figure out the names based on this order.\n","domain":"ai.onnx","inputs":[{"description":"A maximum trip-count for the loop specified at runtime. Optional. Pass empty string to skip.","name":"M","option":"optional","type":"I"},{"description":"A boolean termination condition. Optional. Pass empty string to skip.","name":"cond","option":"optional","type":"B"},{"description":"The initial values of any loop-carried dependencies (values that change across loop iterations)","name":"v_initial","option":"variadic","type":"V"}],"inputs_range":"2 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":2,"min_output":1,"outputs":[{"description":"Final N loop carried dependency values then K scan_outputs","name":"v_final_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(int64)"],"description":"tensor of int64, which should be a scalar.","type_param_str":"I"},{"allowed_type_strs":["tensor(bool)"],"description":"tensor of bool, which should be a scalar.","type_param_str":"B"}]}},{"name":"LpNormalization","schema":{"attributes":[{"default":-1,"description":"The axis on which to apply normalization, -1 mean last axis.","name":"axis","required":false,"type":"int64"},{"default":2,"description":"The order of the normalization, only 1 or 2 are supported.","name":"p","required":false,"type":"int64"}],"category":"Normalization","description":"Given a matrix, apply Lp-normalization along the provided axis.\n","domain":"ai.onnx","inputs":[{"description":"Input matrix","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Matrix after normalization","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding. DEPRECATION NOTE: auto_pad is only intended to support legacy uses, and for framework authors, one is explicitly encouraged to use explicit padding specified in the pads attribute.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":false,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data, default is 2.0.","name":"p","required":false,"type":"float32"},{"description":"Padding for the beginning and ending along each axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across the\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimension are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(bfloat16)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"MatMulInteger","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html.\nThe production MUST never overflow. The accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('MatMulInteger',\n inputs=['A', 'B', 'a_zero_point', 'b_zero_point'],\n outputs=['Y'],)\n\nA = np.array([[11, 7, 3],\n [10, 6, 2],\n [9, 5, 1],\n [8, 4, 0], ], dtype=np.uint8)\n\na_zero_point = np.array([12], dtype=np.uint8)\n\nB = np.array([[1, 4],\n [2, 5],\n [3, 6], ], dtype=np.uint8)\n\nb_zero_point = np.array([0], dtype=np.uint8)\n\noutput = np.array([[-38, -83],\n [-44, -98],\n [-50, -113],\n [-56, -128], ], dtype=np.int32)\n\nexpect(node, inputs=[A, B, a_zero_point, b_zero_point], outputs=[output],\n name='test_matmulinteger')","summary":"matmulinteger"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T1"},{"description":"N-dimensional matrix B","name":"B","type":"T2"},{"description":"Zero point tensor for input 'A'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-row quantization. If it's a 1-D tensor, its number of elements should be equal to the number of rows of input 'A'.","name":"a_zero_point","option":"optional","type":"T1"},{"description":"Zero point tensor for input 'B'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.","name":"b_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 4","max_input":4,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input A data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input B data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain output Y data type as 32-bit integer tensor.","type_param_str":"T3"}]}},{"name":"Max","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise max of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for Max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"max","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for Max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"max","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad. \n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(uint8)"],"description":"Constrain input and output types to float and 8 bit tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxRoiPool","schema":{"attributes":[{"description":"ROI pool output shape (height, width).","name":"pooled_shape","required":true,"type":"int64[]"},{"default":1,"description":"Multiplicative spatial scale factor to translate ROI coordinates from their input scale to the scale used when pooling.","name":"spatial_scale","required":false,"type":"float32"}],"category":"Pool","description":"ROI max pool consumes an input tensor X and region of interests (RoIs) to\n apply max pooling across each RoI, to produce output 4-D tensor of shape\n (num_rois, channels, pooled_shape[0], pooled_shape[1]).","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data.","name":"X","type":"T"},{"description":"RoIs (Regions of Interest) to pool over. Should be a 2-D tensor of shape (num_rois, 5) given as [[batch_id, x1, y1, x2, y2], ...].","name":"rois","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"RoI pooled output 4-D tensor of shape (num_rois, channels, pooled_shape[0], pooled_shape[1]).","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MaxUnpool","schema":{"attributes":[{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"MaxUnpool essentially computes the partial inverse of the MaxPool op.\n The input information to this op is typically the the output information from a MaxPool op. The first\n input tensor X is the tensor that needs to be unpooled, which is typically the pooled tensor (first output)\n from MaxPool. The second input tensor, I, contains the indices to the (locally maximal) elements corrsponding\n to the elements in the first input tensor X. Input tensor I is typically the second output of the MaxPool op.\n The third (optional) input is a tensor that specifies the output size of the unpooling operation.\n\nMaxUnpool is intended to do 'partial' inverse of the MaxPool op. 'Partial' because all the non-maximal\n values from the original input to MaxPool are set to zero in the output of the MaxUnpool op. Pooling\n the result of an unpooling operation should give back the original input to the unpooling op.\n\nMaxUnpool can produce the same output size for several input sizes, which makes unpooling op ambiguous.\n The third input argument, output_size, is meant to disambiguate the op and produce output tensor of\n known/predictable size.\n\nIn addition to the inputs, MaxUnpool takes three attributes, namely kernel_shape, strides, and pads,\n which define the exact unpooling op. The attributes typically have the same values as the corrsponding\n pooling op that the unpooling op is trying to invert.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI', 'output_shape'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[5, 6],\n [7, 8]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\noutput_shape = np.array((1, 1, 5, 5), dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0, 0],\n [0, 5, 0, 6, 0],\n [0, 0, 0, 0, 0],\n [0, 7, 0, 8, 0],\n [0, 0, 0, 0, 0]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI, output_shape], outputs=[y], name='test_maxunpool_export_with_output_shape')","summary":"with_output_shape"},{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[1, 2],\n [3, 4]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0],\n [0, 1, 0, 2],\n [0, 0, 0, 0],\n [0, 3, 0, 4]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI], outputs=[y], name='test_maxunpool_export_without_output_shape')","summary":"without_output_shape"}],"inputs":[{"description":"Input data tensor that has to be unpooled. This tensor is typically the first output of the MaxPool op.Dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non-image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T1"},{"description":"Input data tensor containing the indices corresponding to elements in the first input tensor X.This tensor is typically the second output of the MaxPool op.Dimensions must be the same as input tensor X. The indices are linear, i.e. computed considering the tensor as flattened 1-D tensor, assuming row-major storage. Also, the linear indices should not consider padding. So the values in indices are in the range [0, N x C x D1 x ... x Dn).","name":"I","type":"T2"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If 'output_shape' is specified, 'pads' values are ignored.","name":"output_shape","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the unpooling.","name":"output","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"T2"}]}},{"name":"MaxUnpool","schema":{"attributes":[{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"MaxUnpool essentially computes the partial inverse of the MaxPool op.\n The input information to this op is typically the the output information from a MaxPool op. The first\n input tensor X is the tensor that needs to be unpooled, which is typically the pooled tensor (first output)\n from MaxPool. The second input tensor, I, contains the indices to the (locally maximal) elements corrsponding\n to the elements in the first input tensor X. Input tensor I is typically the second output of the MaxPool op.\n The third (optional) input is a tensor that specifies the output size of the unpooling operation.\n\nMaxUnpool is intended to do 'partial' inverse of the MaxPool op. 'Partial' because all the non-maximal\n values from the original input to MaxPool are set to zero in the output of the MaxUnpool op. Pooling\n the result of an unpooling operation should give back the original input to the unpooling op.\n\nMaxUnpool can produce the same output size for several input sizes, which makes unpooling op ambiguous.\n The third input argument, output_size, is meant to disambiguate the op and produce output tensor of\n known/predictable size.\n\nIn addition to the inputs, MaxUnpool takes three attributes, namely kernel_shape, strides, and pads,\n which define the exact unpooling op. The attributes typically have the same values as the corrsponding\n pooling op that the unpooling op is trying to invert.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI', 'output_shape'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[5, 6],\n [7, 8]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\noutput_shape = np.array((1, 1, 5, 5), dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0, 0],\n [0, 5, 0, 6, 0],\n [0, 0, 0, 0, 0],\n [0, 7, 0, 8, 0],\n [0, 0, 0, 0, 0]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI, output_shape], outputs=[y], name='test_maxunpool_export_with_output_shape')","summary":"with_output_shape"},{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[1, 2],\n [3, 4]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0],\n [0, 1, 0, 2],\n [0, 0, 0, 0],\n [0, 3, 0, 4]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI], outputs=[y], name='test_maxunpool_export_without_output_shape')","summary":"without_output_shape"}],"inputs":[{"description":"Input data tensor that has to be unpooled. This tensor is typically the first output of the MaxPool op.Dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non-image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T1"},{"description":"Input data tensor containing the indices corresponding to elements in the first input tensor X.This tensor is typically the second output of the MaxPool op.Dimensions must be the same as input tensor X. The indices are linear, i.e. computed considering the tensor as flattened 1-D tensor, assuming row-major storage. Also, the linear indices should not consider padding. So the values in indices are in the range [0, N x C x D1 x ... x Dn).","name":"I","type":"T2"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If 'output_shape' is specified, 'pads' values are ignored.","name":"output_shape","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the unpooling.","name":"output","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"T2"}]}},{"name":"Mean","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise mean of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for Mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"mean","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for Mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"mean","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"mean","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"mean","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MeanVarianceNormalization","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to caculate along axes [0,2,3] for calculating mean and variance along each channel. Two variables with the same C-coordinate are associated with the same mean and variance.","name":"axes","required":false,"type":"int64[]"}],"description":"A MeanVarianceNormalization Function: Perform mean variance normalization\n on the input tensor X using formula:
``` (X-EX)/sqrt(E(X-EX)^2) ```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MeanVarianceNormalization',\n inputs=['X'],\n outputs=['Y']\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\ndata_mean = np.mean(input_data, axis=(0, 2, 3), keepdims=1)\ndata_mean_squared = np.power(data_mean, 2)\ndata_squared = np.power(input_data, 2)\ndata_squared_mean = np.mean(data_squared, axis=(0, 2, 3), keepdims=1)\nstd = np.sqrt(data_squared_mean - data_mean_squared)\nexpected_output = (input_data - data_mean) / (std + 1e-9)\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_mvn')","summary":"meanvariancenormalization"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"MeanVarianceNormalization","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to caculate along axes [0,2,3] for calculating mean and variance along each channel. Two variables with the same C-coordinate are associated with the same mean and variance.","name":"axes","required":false,"type":"int64[]"}],"description":"A MeanVarianceNormalization Function: Perform mean variance normalization\n on the input tensor X using formula:
``` (X-EX)/sqrt(E(X-EX)^2) ```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MeanVarianceNormalization',\n inputs=['X'],\n outputs=['Y']\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\ndata_mean = np.mean(input_data, axis=(0, 2, 3), keepdims=1)\ndata_mean_squared = np.power(data_mean, 2)\ndata_squared = np.power(input_data, 2)\ndata_squared_mean = np.mean(data_squared, axis=(0, 2, 3), keepdims=1)\nstd = np.sqrt(data_squared_mean - data_mean_squared)\nexpected_output = (input_data - data_mean) / (std + 1e-9)\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_mvn')","summary":"meanvariancenormalization"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise min of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for Min","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"min","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for Min","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"min","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Mod","schema":{"attributes":[{"description":"Whether the operator should behave like fmod (default=0 meaning it will do integer mods); Set this to 1 to force fmod treatment","name":"fmod","required":false,"type":"int64"}],"description":"Performs element-wise binary modulus (with Numpy-style broadcasting support). \n The sign of the remainder is the same as that of the Divisor.\n \n Mod operator can also behave like C fmod() or numpy.fmod. In this case, the sign of the remainder however, will be the same as the Dividend \n (in contrast to integer mod). To force a behavior like numpy.fmod() an 'fmod' Attribute is provided.\n This attribute is set to 0 by default causing the behavior to be like integer mod. \n Setting this attribute to 1 causes the remainder to be calculated similar to that of numpy.fmod().\n\n If the input type is floating point, then `fmod` attribute must be set to 1.\n \n In case of dividend being zero, the results will be platform dependent.\n\n This operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.arange(0, 30).reshape([3, 2, 5])\ny = np.array([7])\nz = np.mod(x, y)\nz\n# array([[[0, 1, 2, 3, 4],\n# [5, 6, 0, 1, 2]],\n\n# [[3, 4, 5, 6, 0],\n# [1, 2, 3, 4, 5]],\n\n# [[6, 0, 1, 2, 3],\n# [4, 5, 6, 0, 1]]], dtype=int32)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_broadcast')","summary":"mod_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.fmod(x, y) # expected output [ 0, 1, 5, 0, -1, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_int64_fmod')","summary":"mod_int64_fmod"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float16)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float16)\nz = np.fmod(x, y) # expected output [-0.10156, 0.3984 , 5. , 0.10156, -0.3984 , 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float16')","summary":"mod_mixed_sign_float16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float32)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float32)\nz = np.fmod(x, y) # expected output [-0.10000038, 0.39999962, 5. , 0.10000038, -0.39999962, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float32')","summary":"mod_mixed_sign_float32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float64)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float64)\nz = np.fmod(x, y) # expected output [-0.1, 0.4, 5. , 0.1, -0.4, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float64')","summary":"mod_mixed_sign_float64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int16)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int16)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int16')","summary":"mod_mixed_sign_int16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int32)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int32)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int32')","summary":"mod_mixed_sign_int32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int64')","summary":"mod_mixed_sign_int64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int8)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int8)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int8')","summary":"mod_mixed_sign_int8"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint16)\ny = np.array([2, 3, 8]).astype(np.uint16)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint16')","summary":"mod_uint16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint32)\ny = np.array([2, 3, 8]).astype(np.uint32)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint32')","summary":"mod_uint32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint64)\ny = np.array([2, 3, 8]).astype(np.uint64)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint64')","summary":"mod_uint64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint8)\ny = np.array([2, 3, 8]).astype(np.uint8)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint8')","summary":"mod_uint8"}],"inputs":[{"description":"Dividend tensor","name":"A","type":"T"},{"description":"Divisor tensor","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Remainder tensor","name":"C","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mod","schema":{"attributes":[{"description":"Whether the operator should behave like fmod (default=0 meaning it will do integer mods); Set this to 1 to force fmod treatment","name":"fmod","required":false,"type":"int64"}],"description":"Performs element-wise binary modulus (with Numpy-style broadcasting support). \n The sign of the remainder is the same as that of the Divisor.\n \n Mod operator can also behave like C fmod() or numpy.fmod. In this case, the sign of the remainder however, will be the same as the Dividend \n (in contrast to integer mod). To force a behavior like numpy.fmod() an 'fmod' Attribute is provided.\n This attribute is set to 0 by default causing the behavior to be like integer mod. \n Setting this attribute to 1 causes the remainder to be calculated similar to that of numpy.fmod().\n\n If the input type is floating point, then `fmod` attribute must be set to 1.\n \n In case of dividend being zero, the results will be platform dependent.\n\n This operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.arange(0, 30).reshape([3, 2, 5])\ny = np.array([7])\nz = np.mod(x, y)\nz\n# array([[[0, 1, 2, 3, 4],\n# [5, 6, 0, 1, 2]],\n\n# [[3, 4, 5, 6, 0],\n# [1, 2, 3, 4, 5]],\n\n# [[6, 0, 1, 2, 3],\n# [4, 5, 6, 0, 1]]], dtype=int32)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_broadcast')","summary":"mod_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.fmod(x, y) # expected output [ 0, 1, 5, 0, -1, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_int64_fmod')","summary":"mod_int64_fmod"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float16)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float16)\nz = np.fmod(x, y) # expected output [-0.10156, 0.3984 , 5. , 0.10156, -0.3984 , 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float16')","summary":"mod_mixed_sign_float16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float32)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float32)\nz = np.fmod(x, y) # expected output [-0.10000038, 0.39999962, 5. , 0.10000038, -0.39999962, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float32')","summary":"mod_mixed_sign_float32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float64)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float64)\nz = np.fmod(x, y) # expected output [-0.1, 0.4, 5. , 0.1, -0.4, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float64')","summary":"mod_mixed_sign_float64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int16)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int16)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int16')","summary":"mod_mixed_sign_int16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int32)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int32)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int32')","summary":"mod_mixed_sign_int32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int64')","summary":"mod_mixed_sign_int64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int8)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int8)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int8')","summary":"mod_mixed_sign_int8"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint16)\ny = np.array([2, 3, 8]).astype(np.uint16)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint16')","summary":"mod_uint16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint32)\ny = np.array([2, 3, 8]).astype(np.uint32)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint32')","summary":"mod_uint32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint64)\ny = np.array([2, 3, 8]).astype(np.uint64)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint64')","summary":"mod_uint64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint8)\ny = np.array([2, 3, 8]).astype(np.uint8)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint8')","summary":"mod_uint8"}],"inputs":[{"description":"Dividend tensor","name":"A","type":"T"},{"description":"Divisor tensor","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Remainder tensor","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Momentum","schema":{"attributes":[{"description":"The decay factor of momentum. It should be a scalar.","name":"alpha","required":true,"type":"float32"},{"description":"The coefficient of gradient in computing new momentum. It should be a scalar.","name":"beta","required":true,"type":"float32"},{"description":"Its value should be either \"nesterov\" or \"standard\". The value \"nesterov\" leads to the use of Nesterov's momentum while \"standard\" invokes stochastic gradient method using standard momentum","name":"mode","required":true,"type":"string"},{"description":"Coefficient of 0.5 * norm_coefficient * ||X||^2.","name":"norm_coefficient","required":true,"type":"float32"}],"description":"Compute one iteration of stochastic gradient update with momentum.\n This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. As you can imagine, SG with momentum requires\n several parameters:\n \n - The learning-rate \"R\".\n - The update count \"T\". That is, the number of conducted training iterations. It should\n be zero in the first training iteration.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A decay coefficient of previous accumulated gradient (i.e., momentum) \"alpha\".\n - The scaling coefficient of current gradient \"beta\".\n - An attribute to choose either standard momentum or Nesterov's momentum \"mode\" should\n be used.\n\n For the sake of simplicity, assume that there is only one tensor (called \"X\") to be optimized.\n Other necessary inputs are \"X\"'s gradient (called \"G\") and \"X\"'s momentum (called \"V\"). This\n Momentum operator maps all these inputs to the new value of \"X\" (called \"X_new\") and its new\n momentum (called \"V_new\").\n \n This operator supports two different momentum algorithms. Set the attribute \"mode\" to\n \"nesterov\" if Nesterov's momentum is desired. Otherwise, set the attribute \"model\" to\n \"standard\" to use standard momentum. Computation details are described subsequently.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise operations with numpy-style broadcasting.\n\n Pseudo code for SG with standard momentum:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared\n // values of all elements in X.\n G_regularized = norm_coefficient * X + G\n\n // In the first training iteration, beta should always be 1.\n beta_adjusted = T > 0 ? beta : 1\n\n // Compute the current momentum based on previous momentum and the current gradient.\n V_new = alpha * V + beta_adjusted * G_regularized\n\n // Update X.\n X_new = X - R * V_new\n\n Pseudo code for SG with Nesterov's momentum:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared\n // values of all elements in X.\n G_regularized = norm_coefficient * X + G;\n\n // In the first training iteration, beta should always be 1.\n beta_adjusted = T > 0 ? beta : 1\n\n // Compute the current momentum based on previous momentum and the current gradient.\n V_new = alpha * V + beta_adjusted * G_regularized;\n\n // Compute final update direction and then update X.\n X_new = X - R * (G_regularized + alpha * V_new)\n\n If one assign this operators to optimize multiple inputs, for example, \"X_1\" and \"X_2\". The same\n pseudo code would be extended to handle all tensors jointly. More specifically, we can view \"X\" as a\n concatenation of \"X_1\" and \"X_2\" (of course, their gradient and accumulate gradient should\n be concatenated too) and then our pseudo code becomes applicable.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.1\n\n# Create operator.\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X', 'G', 'V'],\n outputs=['X_new', 'V_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='standard',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx_new, v_new = apply_momentum(r, t, x, g, v,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v],\n outputs=[x_new, v_new], name='test_momentum',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"momentum"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.85\n\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'V1_new', 'V2_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='standard',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nv1 = np.array([2.0], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nv2 = np.array([4.0, 1.0], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx1_new, v1_new = apply_momentum(r, t, x1, g1, v1,\n norm_coefficient, alpha, beta)\nx2_new, v2_new = apply_momentum(r, t, x2, g2, v2,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2],\n outputs=[x1_new, x2_new, v1_new, v2_new], name='test_momentum_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"momentum_multiple"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.01\nalpha = 0.95\nbeta = 1.0\n\n# Create operator.\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X', 'G', 'V'],\n outputs=['X_new', 'V_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='nesterov',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx_new, v_new = apply_nesterov(r, t, x, g, v,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v],\n outputs=[x_new, v_new], name='test_nesterov_momentum',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"nesterov_momentum"}],"inputs":[{"description":"The learning rate.","name":"R","type":"T1"},{"description":"Update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"It sequentially contains the current values of optimized tensors, then their gradient tensors, and finally their momentum tensors. For example, if two tensors \"X_1\" and \"X_2\" are optimized, The expected input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", momentum of \"X_1\", momentum of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"It sequentially contains the new values of optimized tensors and then the new values of their momentum tensors. For example, if two tensors \"X_1\" and \"X_2\" are optimized, the output list would be [new value of \"X_1,\" new value of \"X_2\" new momentum of \"X_1\", new momentum of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T3"}]}},{"name":"Mul","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"description":"Performs element-wise binary multiplication (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"description":"Performs element-wise binary multiplication (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Multinomial","schema":{"attributes":[{"default":6,"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use int32.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Number of times to sample.","name":"sample_size","required":false,"type":"int64"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor of samples from a multinomial distribution according to the probabilities\nof each of the possible outcomes.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor with shape [batch_size, class_size], where class_size is the number of all possible outcomes. Each value along the axis zero represents the unnormalized log-probability of each corresponding outcome in a batch.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with shape [batch_size, sample_size], where sample_size is the number of times to sample. Each value along the axis zero represents the outcome of the corresponding sample in a batch.","name":"output","type":"T2"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain output types to integral tensors.","type_param_str":"T2"}]}},{"name":"Neg","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Neg","schema":{"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)","tensor(int8)","tensor(int16)","tensor(int64)","tensor(float16)","tensor(double)"],"description":"Constrain input and output types to signed numeric tensors.","type_param_str":"T"}]}},{"name":"Neg","schema":{"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)","tensor(int8)","tensor(int16)","tensor(int64)","tensor(float16)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to signed numeric tensors.","type_param_str":"T"}]}},{"name":"NegativeLogLikelihoodLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean (default). 'none': the output is the loss for each sample. 'sum': the output will be summed. 'mean': the sum of the output will be divided by the sum of applied weights.","name":"reduction","required":false,"type":"string"}],"description":"A NegativeLogLikelihoodLoss operator computes (weighted) negative log likelihood loss.\nIts \"input\" tensor has the shape of (N, C, d1, d2, ..., dk) where k >= 0.\nThe \"input\" tensor contains log-probabilities for input[n, :, d_1, d_2,..., d_k] being in a class of [0, C).\nThe operator's \"target\" input tensor has the shape of (N, d1, d2, ..., dk). It encodes class labels (one of C classes)\nor it may contain a special value (indicated by an attribute ignore_index) for N x d1 x d2 x ... x dk samples.\nThe loss value for input[n, :, d_1, d_2,...d_k] being classified as class c = target[n][d_1][d_2]...[d_k] is computed as:\n\n loss[n][d_1][d_2]...[d_k] = -input[n][c][d_1][d_2]...[d_k].\n\nWhen an optional \"weight\" is provided, the sample loss is calculated as:\n\n loss[n][d_1][d_2]...[d_k] = -input[n][c][d_1][d_2]...[d_k] * weight[c].\n\nloss is zero for the case when target-value equals ignore_index.\n \n loss[n][d_1][d_2]...[d_k] = 0, when target[n][d_1][d_2]...[d_k] = ignore_index\n\nIf \"reduction\" attribute is set to \"none\", the operator's output will be the above loss with shape (N, d1, d2, ..., dk).\nIf \"reduction\" attribute is set to \"mean\" (the default attribute value), the output loss is (weight) averaged:\n\n mean(loss), if \"weight\" is not provided,\n\nor if weight is provided,\n\n sum(loss) / sum(weight[target[n][d_1][d_2]...[d_k]]]), for all samples.\n\nIf \"reduction\" attribute is set to \"sum\", the output is a scalar:\n sum(loss).\n\nSee also https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss.\n\nExample 1:\n\n // negative log likelihood loss, \"none\" reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n\n loss = np.zeros((N, d1))\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1]\n\n // print(loss)\n // [[-3. -2.]\n // [-0. -2.]]\n\nExample 2:\n\n // weighted negative log likelihood loss, sum reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n weight = [0.2, 0.3, 0.1]\n loss = np.zeros((N, d1))\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1] * weight[c]\n\n loss = np.sum(loss)\n // print(loss)\n // -1.1\n\nExample 3:\n\n // weighted negative log likelihood loss, mean reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n weight = [0.2, 0.3, 0.1]\n loss = np.zeros((N, d1))\n weight_total = 0\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1] * weight[c]\n weight_total = weight_total + weight[c]\n\n loss = np.sum(loss) / weight_total\n // print(loss)\n // -1.57\n","domain":"ai.onnx","examples":[{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C = 3, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, ))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NC')","summary":"input_shape_is_NC"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1')","summary":"input_shape_is_NCd1"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\ntarget[0][0] = np.int64(1)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_ii')","summary":"input_shape_is_NCd1_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1))\ntarget[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_weight')","summary":"input_shape_is_NCd1_weight"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\ntarget[0][0] = np.int64(1)\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_weight_ii')","summary":"input_shape_is_NCd1_weight_ii"},{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2')","summary":"input_shape_is_NCd1d2"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\ntarget[0][0][0] = np.int64(1)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_no_weight_reduction_mean_ii')","summary":"input_shape_is_NCd1d2_no_weight_reduction_mean_ii"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_reduction_mean')","summary":"input_shape_is_NCd1d2_reduction_mean"},{"code":"reduction = 'sum'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_reduction_sum')","summary":"input_shape_is_NCd1d2_reduction_sum"},{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight')","summary":"input_shape_is_NCd1d2_with_weight"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_mean')","summary":"input_shape_is_NCd1d2_with_weight_reduction_mean"},{"code":"reduction = 'sum'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_sum')","summary":"input_shape_is_NCd1d2_with_weight_reduction_sum"},{"code":"reduction = 'sum'\nignore_index = np.int64(0)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\ntarget[0][0][0] = np.int64(0)\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_sum_ii')","summary":"input_shape_is_NCd1d2_with_weight_reduction_sum_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\ntarget[0][0][0][0] = -5\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N))\ntarget[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"}],"inputs":[{"description":"Input tensor of shape (N, C) or (N, C, d1, d2, ..., dk).","name":"input","type":"T"},{"description":"Target tensor of shape (N) or (N, d1, d2, ..., dk). Target element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the target values should either be in the range [0, C) or have the value ignore_index.","name":"target","type":"Tind"},{"description":"Optional rescaling weight tensor. If given, it has to be a tensor of size C. Otherwise, it is treated as if having all ones.","name":"weight","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"The negative log likelihood loss","name":"loss","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input, weight, and output types to floating-point tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"NonMaxSuppression","schema":{"attributes":[{"description":"Integer indicate the format of the box data. The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Mostly used for TF models. 1 - the box data is supplied as [x_center, y_center, width, height]. Mostly used for Pytorch models.","name":"center_point_box","required":false,"type":"int64"}],"description":"Filter out boxes that have high intersection-over-union (IOU) overlap with previously selected boxes.\nBounding boxes with score less than score_threshold are removed. Bounding box format is indicated by attribute center_point_box.\nNote that this algorithm is agnostic to where the origin is in the coordinate system and more generally is invariant to\northogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system\nresult in the same boxes being selected by the algorithm.\nThe selected_indices output is a set of integers indexing into the input collection of bounding boxes representing the selected boxes.\nThe bounding box coordinates corresponding to the selected indices can then be obtained using the Gather or GatherND operation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices'],\n center_point_box=1\n)\nboxes = np.array([[\n [0.5, 0.5, 1.0, 1.0],\n [0.5, 0.6, 1.0, 1.0],\n [0.5, 0.4, 1.0, 1.0],\n [0.5, 10.5, 1.0, 1.0],\n [0.5, 10.6, 1.0, 1.0],\n [0.5, 100.5, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_center_point_box_format')","summary":"nonmaxsuppression_center_point_box_format"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [1.0, 1.0, 0.0, 0.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, 0.9, 1.0, -0.1],\n [0.0, 10.0, 1.0, 11.0],\n [1.0, 10.1, 0.0, 11.1],\n [1.0, 101.0, 0.0, 100.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_flipped_coordinates')","summary":"nonmaxsuppression_flipped_coordinates"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_identical_boxes')","summary":"nonmaxsuppression_identical_boxes"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_limit_output_size')","summary":"nonmaxsuppression_limit_output_size"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_single_box')","summary":"nonmaxsuppression_single_box"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU')","summary":"nonmaxsuppression_suppress_by_IOU"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.4]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU_and_scores')","summary":"nonmaxsuppression_suppress_by_IOU_and_scores"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]],\n [[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]],\n [[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [1, 0, 3], [1, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_batches')","summary":"nonmaxsuppression_two_batches"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3],\n [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 1, 3], [0, 1, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_classes')","summary":"nonmaxsuppression_two_classes"}],"inputs":[{"description":"An input tensor with shape [num_batches, spatial_dimension, 4]. The single box data format is indicated by center_point_box.","name":"boxes","type":"tensor(float)"},{"description":"An input tensor with shape [num_batches, num_classes, spatial_dimension]","name":"scores","type":"tensor(float)"},{"description":"Integer representing the maximum number of boxes to be selected per batch per class. It is a scalar. Default to 0, which means no output.","name":"max_output_boxes_per_class","option":"optional","type":"tensor(int64)"},{"description":"Float representing the threshold for deciding whether boxes overlap too much with respect to IOU. It is scalar. Value range [0, 1]. Default to 0.","name":"iou_threshold","option":"optional","type":"tensor(float)"},{"description":"Float representing the threshold for deciding when to remove boxes based on score. It is a scalar.","name":"score_threshold","option":"optional","type":"tensor(float)"}],"inputs_range":"2 - 5","max_input":5,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"selected indices from the boxes tensor. [num_selected_indices, 3], the selected index format is [batch_index, class_index, box_index].","name":"selected_indices","type":"tensor(int64)"}],"since_version":10,"support_level":"common"}},{"name":"NonMaxSuppression","schema":{"attributes":[{"description":"Integer indicate the format of the box data. The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Mostly used for TF models. 1 - the box data is supplied as [x_center, y_center, width, height]. Mostly used for Pytorch models.","name":"center_point_box","required":false,"type":"int64"}],"description":"Filter out boxes that have high intersection-over-union (IOU) overlap with previously selected boxes.\nBounding boxes with score less than score_threshold are removed. Bounding box format is indicated by attribute center_point_box.\nNote that this algorithm is agnostic to where the origin is in the coordinate system and more generally is invariant to\northogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system\nresult in the same boxes being selected by the algorithm.\nThe selected_indices output is a set of integers indexing into the input collection of bounding boxes representing the selected boxes.\nThe bounding box coordinates corresponding to the selected indices can then be obtained using the Gather or GatherND operation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices'],\n center_point_box=1\n)\nboxes = np.array([[\n [0.5, 0.5, 1.0, 1.0],\n [0.5, 0.6, 1.0, 1.0],\n [0.5, 0.4, 1.0, 1.0],\n [0.5, 10.5, 1.0, 1.0],\n [0.5, 10.6, 1.0, 1.0],\n [0.5, 100.5, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_center_point_box_format')","summary":"nonmaxsuppression_center_point_box_format"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [1.0, 1.0, 0.0, 0.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, 0.9, 1.0, -0.1],\n [0.0, 10.0, 1.0, 11.0],\n [1.0, 10.1, 0.0, 11.1],\n [1.0, 101.0, 0.0, 100.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_flipped_coordinates')","summary":"nonmaxsuppression_flipped_coordinates"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_identical_boxes')","summary":"nonmaxsuppression_identical_boxes"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_limit_output_size')","summary":"nonmaxsuppression_limit_output_size"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_single_box')","summary":"nonmaxsuppression_single_box"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU')","summary":"nonmaxsuppression_suppress_by_IOU"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.4]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU_and_scores')","summary":"nonmaxsuppression_suppress_by_IOU_and_scores"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]],\n [[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]],\n [[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [1, 0, 3], [1, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_batches')","summary":"nonmaxsuppression_two_batches"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3],\n [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 1, 3], [0, 1, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_classes')","summary":"nonmaxsuppression_two_classes"}],"inputs":[{"description":"An input tensor with shape [num_batches, spatial_dimension, 4]. The single box data format is indicated by center_point_box.","name":"boxes","type":"tensor(float)"},{"description":"An input tensor with shape [num_batches, num_classes, spatial_dimension]","name":"scores","type":"tensor(float)"},{"description":"Integer representing the maximum number of boxes to be selected per batch per class. It is a scalar. Default to 0, which means no output.","name":"max_output_boxes_per_class","option":"optional","type":"tensor(int64)"},{"description":"Float representing the threshold for deciding whether boxes overlap too much with respect to IOU. It is scalar. Value range [0, 1]. Default to 0.","name":"iou_threshold","option":"optional","type":"tensor(float)"},{"description":"Float representing the threshold for deciding when to remove boxes based on score. It is a scalar.","name":"score_threshold","option":"optional","type":"tensor(float)"}],"inputs_range":"2 - 5","max_input":5,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"selected indices from the boxes tensor. [num_selected_indices, 3], the selected index format is [batch_index, class_index, box_index].","name":"selected_indices","type":"tensor(int64)"}],"since_version":11,"support_level":"common"}},{"name":"NonZero","schema":{"description":"Returns the indices of the elements that are non-zero\n (in row-major order - by dimension).\n NonZero behaves similar to numpy.nonzero:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonZero',\n inputs=['condition'],\n outputs=['result'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nresult = np.array((np.nonzero(condition))) # expected output [[0, 1, 1], [0, 0, 1]]\nexpect(node, inputs=[condition], outputs=[result],\n name='test_nonzero_example')","summary":"nonzero"}],"inputs":[{"description":"input","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"tensor(int64)"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to all tensor types.","type_param_str":"T"}]}},{"name":"NonZero","schema":{"description":"Returns the indices of the elements that are non-zero\n (in row-major order - by dimension).\n NonZero behaves similar to numpy.nonzero:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonZero',\n inputs=['condition'],\n outputs=['result'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nresult = np.array((np.nonzero(condition))) # expected output [[0, 1, 1], [0, 0, 1]]\nexpect(node, inputs=[condition], outputs=[result],\n name='test_nonzero_example')","summary":"nonzero"}],"inputs":[{"description":"input","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to all tensor types.","type_param_str":"T"}]}},{"name":"Normalizer","schema":{"attributes":[{"default":"MAX","description":"One of 'MAX,' 'L1,' 'L2'","name":"norm","required":false,"type":"string"}],"description":"Normalize the input. There are three normalization modes, which have the corresponding formulas,\n defined using element-wise infix operators '/' and '^' and tensor-wide functions 'max' and 'sum':
\n
\n Max: Y = X / max(X)
\n L1: Y = X / sum(X)
\n L2: Y = sqrt(X^2 / sum(X^2)}
\n In all modes, if the divisor is zero, Y == X.\n
\n For batches, that is, [N,C] tensors, normalization is done along the C axis. In other words, each row\n of the batch is normalized independently.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be encoded, a tensor of shape [N,C] or [C]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Encoded output data","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Not","schema":{"category":"Logic","description":"Returns the negation of the input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Not',\n inputs=['x'],\n outputs=['not'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_4d')","summary":"not"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input/output to boolean tensors.","type_param_str":"T"}]}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"(Optional) Axis along which one-hot representation in added. Default: axis=-1. axis=-1 means that the additional dimension will be inserted as the innermost/last dimension in the output tensor.","name":"axis","required":false,"type":"int64"}],"description":"Produces a one-hot tensor based on inputs.\n The locations represented by the index values in the 'indices' input tensor will have 'on_value'\n and the other locations will have 'off_value' in the output tensor, where 'on_value' and 'off_value'\n are specified as part of required input argument 'values', which is a two-element tensor of format\n [off_value, on_value]. The rank of the output tensor will be one greater than the rank of the\n input tensor. The additional dimension is for one-hot representation. The additional dimension will\n be inserted at the position specified by 'axis'. If 'axis' is not specified then then additional\n dimension will be inserted as the innermost dimension, i.e. axis=-1. The size of the additional\n dimension is specified by required scalar input 'depth'. The type of the output tensor is the same\n as the type of the 'values' input. Any entries in the 'indices' input tensor with values outside\n the range [0, depth) will result in one-hot representation with all 'off_value' values in the\n output tensor.\n","domain":"ai.onnx","examples":[{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_axis')","summary":"with_axis"},{"code":"axisValue = -2\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_negative_axis')","summary":"with_negative_axis"},{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([0, -7, -8], dtype=np.int64)\n\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_negative_indices')","summary":"with_negative_indices"},{"code":"on_value = 5\noff_value = 2\noutput_type = np.int32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y']\n)\nindices = np.array([0, 7, 8], dtype=np.int64)\ndepth = np.float32(12)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_without_axis')","summary":"without_axis"}],"inputs":[{"description":"Input tensor containing indices. The values must be non-negative integers. Any entries in the 'indices' input tensor with values outside the range [0, depth) will result in one-hot representation with all 'off_value' values in the output tensor.In case 'indices' is of non-integer type, the values will be casted to int64 before use.","name":"indices","type":"T1"},{"description":"Scalar specifying the number of classes in one-hot tensor. This is also the size of the one-hot dimension (specified by 'axis' attribute) added on in the output tensor. The values in the 'indices' input tensor are expected to be in the range [0, depth). In case 'depth' is of non-integer type, it will be casted to int64 before use.","name":"depth","type":"T2"},{"description":"Rank 1 tensor containing exactly two elements, in the format [off_value, on_value], where 'on_value' is the value used for filling locations specified in 'indices' input tensor, and 'off_value' is the value used for filling locations other than those specified in 'indices' input tensor. ","name":"values","type":"T3"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank one greater than input tensor 'indices', i.e. rank(output) = rank(indices) + 1. The data type for the elements of the output tensor is the same as the type of input 'values' is used.","name":"output","type":"T3"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T2"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T3"}]}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"(Optional) Axis along which one-hot representation in added. Default: axis=-1. axis=-1 means that the additional dimension will be inserted as the innermost/last dimension in the output tensor. Negative value means counting dimensions from the back. Accepted range is [-r-1, r] where r = rank(indices).","name":"axis","required":false,"type":"int64"}],"description":"Produces a one-hot tensor based on inputs.\n The locations represented by the index values in the 'indices' input tensor will have 'on_value'\n and the other locations will have 'off_value' in the output tensor, where 'on_value' and 'off_value'\n are specified as part of required input argument 'values', which is a two-element tensor of format\n [off_value, on_value]. The rank of the output tensor will be one greater than the rank of the\n input tensor. The additional dimension is for one-hot representation. The additional dimension will\n be inserted at the position specified by 'axis'. If 'axis' is not specified then then additional\n dimension will be inserted as the innermost dimension, i.e. axis=-1. The size of the additional\n dimension is specified by required scalar input 'depth'. The type of the output tensor is the same\n as the type of the 'values' input. Any entries in the 'indices' input tensor with values outside\n the range [-depth, depth-1] will result in one-hot representation with all 'off_value' values in the\n output tensor.\n\n when axis = 0:\n output[input[i, j, k], i, j, k] = 1 for all i, j, k and 0 otherwise.\n\n when axis = -1:\n output[i, j, k, input[i, j, k]] = 1 for all i, j, k and 0 otherwise.\n\n","domain":"ai.onnx","examples":[{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_axis')","summary":"with_axis"},{"code":"axisValue = -2\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_negative_axis')","summary":"with_negative_axis"},{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([0, -7, -8], dtype=np.int64)\n\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_negative_indices')","summary":"with_negative_indices"},{"code":"on_value = 5\noff_value = 2\noutput_type = np.int32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y']\n)\nindices = np.array([0, 7, 8], dtype=np.int64)\ndepth = np.float32(12)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_without_axis')","summary":"without_axis"}],"inputs":[{"description":"Input tensor containing indices. Any entries in the 'indices' input tensor with values outside the range [-depth, depth-1] will result in one-hot representation with all 'off_value' values in the output tensor.In case 'indices' is of non-integer type, the values will be casted to int64 before use.","name":"indices","type":"T1"},{"description":"Scalar specifying the number of classes in one-hot tensor. This is also the size of the one-hot dimension (specified by 'axis' attribute) added on in the output tensor. The values in the 'indices' input tensor are expected to be in the range [-depth, depth-1]. In case 'depth' is of non-integer type, it will be casted to int64 before use.","name":"depth","type":"T2"},{"description":"Rank 1 tensor containing exactly two elements, in the format [off_value, on_value], where 'on_value' is the value used for filling locations specified in 'indices' input tensor, and 'off_value' is the value used for filling locations other than those specified in 'indices' input tensor. ","name":"values","type":"T3"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank one greater than input tensor 'indices', i.e. rank(output) = rank(indices) + 1. The data type for the elements of the output tensor is the same as the type of input 'values' is used.","name":"output","type":"T3"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T2"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T3"}]}},{"name":"OneHotEncoder","schema":{"attributes":[{"description":"List of categories, ints.
One and only one of the 'cats_*' attributes must be defined.","name":"cats_int64s","required":false,"type":"int64[]"},{"description":"List of categories, strings.
One and only one of the 'cats_*' attributes must be defined.","name":"cats_strings","required":false,"type":"string[]"},{"default":1,"description":"If true and category is not present, will return all zeros; if false and a category if not found, the operator will fail.","name":"zeros","required":false,"type":"int64"}],"description":"Replace each input element with an array of ones and zeros, where a single\n one is placed at the index of the category that was passed in. The total category count \n will determine the size of the extra dimension of the output array Y.
\n For example, if we pass a tensor with a single value of 4, and a category count of 8, \n the output will be a tensor with ``[0,0,0,0,1,0,0,0]``.
\n This operator assumes every input feature is from the same set of categories.
\n If the input is a tensor of float, int32, or double, the data will be cast\n to integers and the cats_int64s category list will be used for the lookups.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be encoded.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Encoded output data, having one more dimension than X.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(int32)","tensor(float)","tensor(double)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Or","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `or` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or4d')","summary":"or"},{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v4d')","summary":"or_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Or","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `or` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or4d')","summary":"or"},{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v4d')","summary":"or_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"PRelu","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. If `Slope` is of size 1, the value is sharedacross different channels","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. If `Slope` is of size 1, the value is sharedacross different channels","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\nThis operator supports **unidirectional broadcasting** (tensor slope should be unidirectional broadcastable to input tensor X); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. The shape of slope can be smaller then first input X; if so, its shape must be unidirectional broadcastable to X","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\nThis operator supports **unidirectional broadcasting** (tensor slope should be unidirectional broadcastable to input tensor X); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. The shape of slope can be smaller then first input X; if so, its shape must be unidirectional broadcastable to X","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Three modes: constant(default), reflect, edge","name":"mode","required":false,"type":"string"},{"description":"List of integers indicate the padding element count at the beginning and end of each axis, for 2D it is the number of pixel. `paddings` rank should be double of the input's rank. `paddings` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.","name":"paddings","required":true,"type":"int64[]"},{"description":"One float, indicates the value to be filled, default is 0","name":"value","required":false,"type":"float32"}],"category":"Tensor","description":"Given `data` tensor, paddings, mode, and value.\nExample:\n Insert 0 paddings to the beginning of the second dimension.\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n paddings = [0, 0, 2, 0]\n output = [\n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Three modes: constant(default), reflect, edge","name":"mode","required":false,"type":"string"},{"description":"List of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D it is the number of pixels. `pads` rank should be double of the input's rank. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.","name":"pads","required":true,"type":"int64[]"},{"description":"One float, indicates the value to be filled.","name":"value","required":false,"type":"float32"}],"category":"Tensor","description":"Given `data` tensor, pads, mode, and value.\nExample:\n Insert 0 pads to the beginning of the second dimension.\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n pads = [0, 2, 0, 0]\n output = [\n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Supported modes: `constant`(default), `reflect`, `edge`","name":"mode","required":false,"type":"string"}],"category":"Tensor","description":"Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, \na padded tensor (`output`) is generated.\n\nThe three supported `modes` are (similar to corresponding modes supported by `numpy.pad`):\n\n1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0)\n\n2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis\n\n3) `edge` - pads with the edge values of array\n\n\nExample 1 (`constant` mode):\n Insert 0 pads to the beginning of the second dimension.\n\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'constant'\n\n constant_value = 0.0\n\n output = \n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ]\n\n\nExample 2 (`reflect` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'reflect'\n\n output = \n [\n [1.0, 1.2, 1.0, 1.2],\n [2.3, 3.4, 2.3, 3.4],\n [4.5, 5.7, 4.5, 5.7],\n ]\n\n\nExample 3 (`edge` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'edge'\n\n output = \n [\n [1.0, 1.0, 1.0, 1.2],\n [2.3, 2.3, 2.3, 3.4],\n [4.5, 4.5, 4.5, 5.7],\n ]\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"},{"description":"Tensor of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. `pads` should be a 1D tensor of shape [2 * input_rank]. `pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], where xi_begin is the number of pad values added at the beginning of axis `i` and xi_end, the number of pad values added at the end of axis `i`.","name":"pads","type":"tensor(int64)"},{"description":"(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0).","name":"constant_value","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input and output to only numeric types.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Supported modes: `constant`(default), `reflect`, `edge`","name":"mode","required":false,"type":"string"}],"category":"Tensor","description":"Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, \na padded tensor (`output`) is generated.\n\nThe three supported `modes` are (similar to corresponding modes supported by `numpy.pad`):\n\n1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0)\n\n2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis\n\n3) `edge` - pads with the edge values of array\n\n\nExample 1 (`constant` mode):\n Insert 0 pads to the beginning of the second dimension.\n\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'constant'\n\n constant_value = 0.0\n\n output = \n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ]\n\n\nExample 2 (`reflect` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'reflect'\n\n output = \n [\n [1.0, 1.2, 1.0, 1.2],\n [2.3, 3.4, 2.3, 3.4],\n [4.5, 5.7, 4.5, 5.7],\n ]\n\n\nExample 3 (`edge` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'edge'\n\n output = \n [\n [1.0, 1.0, 1.0, 1.2],\n [2.3, 2.3, 2.3, 3.4],\n [4.5, 4.5, 4.5, 5.7],\n ]\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"},{"description":"Tensor of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. `pads` should be a 1D tensor of shape [2 * input_rank]. `pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], where xi_begin is the number of pad values added at the beginning of axis `i` and xi_end, the number of pad values added at the end of axis `i`.","name":"pads","type":"tensor(int64)"},{"description":"(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0).","name":"constant_value","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrains input and output to only numeric types.","type_param_str":"T"}]}},{"name":"Pow","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"Input tensor of any shape, base of the exponent.","name":"X","type":"T"},{"description":"Input tensor of any shape broadcastable to X shape, the exponent component.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input X and output types to float/int tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input Y types to float/int tensors.","type_param_str":"T1"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input X and output types to float/int tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input Y types to float/int tensors.","type_param_str":"T1"}]}},{"name":"QLinearConv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into. default is 1.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input 'w'.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0.The value represent the number of pixels added to the beginning and end part of the corresponding axis.`pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number ofpixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaultsto 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"The convolution operator consumes a quantized input tensor, its scale and zero point,\na quantized filter, its scale and zero point, and output's scale and zero point,\nand computes the quantized output. Each scale and zero-point pair must have same shape.\nIt means they must be either scalars (per tensor) or 1-D tensors (per output channel).\nEach input or output and its related zero point must have same type.\nWhen bias is present it must be quantized using scale = input scale * weight scale and \nzero point as 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QLinearConv',\n inputs=['x', 'x_scale', 'x_zero_point', 'w', 'w_scale', 'w_zero_point', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[255, 174, 162, 25, 203, 168, 58],\n [15, 59, 237, 95, 129, 0, 64],\n [56, 242, 153, 221, 168, 12, 166],\n [232, 178, 186, 195, 237, 162, 237],\n [188, 39, 124, 77, 80, 102, 43],\n [127, 230, 21, 83, 41, 40, 134],\n [255, 154, 92, 141, 42, 148, 247], ], dtype=np.uint8).reshape((1, 1, 7, 7))\n\nx_scale = np.float32(0.00369204697)\nx_zero_point = np.uint8(132)\n\nw = np.array([0], dtype=np.uint8).reshape((1, 1, 1, 1))\n\nw_scale = np.array([0.00172794575], dtype=np.float32)\nw_zero_point = np.array([255], dtype=np.uint8)\n\ny_scale = np.float32(0.00162681262)\ny_zero_point = np.uint8(123)\n\noutput = np.array([[0, 81, 93, 230, 52, 87, 197],\n [240, 196, 18, 160, 126, 255, 191],\n [199, 13, 102, 34, 87, 243, 89],\n [23, 77, 69, 60, 18, 93, 18],\n [67, 216, 131, 178, 175, 153, 212],\n [128, 25, 234, 172, 214, 215, 121],\n [0, 101, 163, 114, 213, 107, 8], ], dtype=np.uint8).reshape((1, 1, 7, 7))\n\nexpect(node, inputs=[x, x_scale, x_zero_point, w, w_scale, w_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearconv')","summary":"qlinearconv"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"x","type":"T1"},{"description":"Scale tensor for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point tensor for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_zero_point","type":"T1"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"w","type":"T2"},{"description":"Scale tensor for input 'w'. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M).","name":"w_scale","type":"tensor(float)"},{"description":"Zero point tensor for input 'w'. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M).","name":"w_zero_point","type":"T2"},{"description":"Scale tensor for output 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point tensor for output 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_zero_point","type":"T3"},{"description":"Optional 1D bias to be added to the convolution, has size of M. Bias must be quantized using scale = x_scale * w_scale and zero_point = 0","name":"B","option":"optional","type":"T4"}],"inputs_range":"8 - 9","max_input":9,"max_output":1,"min_input":8,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain filter type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain output type to 8-bit integer tensor.","type_param_str":"T3"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain bias type to 32-bit integer tensor.","type_param_str":"T4"}]}},{"name":"QLinearMatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html.\nIt consumes two quantized input tensors, their scales and zero points, scale and zero point of output, and computes the quantized output.\nThe quantization formula is y = saturate((x / y_scale) + y_zero_point). For (x / y_scale), it is rounding to nearest ties to even.\nRefer to https://en.wikipedia.org/wiki/Rounding for details. Scale and zero point must have same shape.\nThey must be either scalar (per tensor) or 1-D tensor (per row for 'a' and per column for 'b'). If scale and zero point are 1-D tensor,\nthe number of elements of scale and zero point tensor of input 'a' and output 'y' should be equal to the number of rows of input 'a',\nand the number of elements of scale and zero point tensor of input 'b' should be equal to the number of columns of input 'b'.\nProduction must never overflow, and accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QLinearMatMul',\n inputs=['a', 'a_scale', 'a_zero_point', 'b', 'b_scale', 'b_zero_point', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\n#2D\na = np.array([[208, 236, 0, 238],\n [3, 214, 255, 29], ], dtype=np.uint8)\n\na_scale = np.array([0.0066], dtype=np.float32)\na_zero_point = np.array([113], dtype=np.uint8)\n\nb = np.array([[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]], dtype=np.uint8)\n\nb_scale = np.array([0.00705], dtype=np.float32)\nb_zero_point = np.array([114], dtype=np.uint8)\n\ny_scale = np.array([0.0107], dtype=np.float32)\ny_zero_point = np.array([118], dtype=np.uint8)\n\noutput = np.array([[168, 115, 255],\n [1, 66, 151], ], dtype=np.uint8)\n\nexpect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearmatmul_2D')\n\n#3D\na = np.array([[[208, 236, 0, 238],\n [3, 214, 255, 29]],\n [[208, 236, 0, 238],\n [3, 214, 255, 29]]], dtype=np.uint8)\n\na_scale = np.array([0.0066], dtype=np.float32)\na_zero_point = np.array([113], dtype=np.uint8)\n\nb = np.array([[[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]],\n [[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]]], dtype=np.uint8)\n\nb_scale = np.array([0.00705], dtype=np.float32)\nb_zero_point = np.array([114], dtype=np.uint8)\n\ny_scale = np.array([0.0107], dtype=np.float32)\ny_zero_point = np.array([118], dtype=np.uint8)\n\noutput = np.array([[[168, 115, 255],\n [1, 66, 151]],\n [[168, 115, 255],\n [1, 66, 151]]], dtype=np.uint8)\n\nexpect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearmatmul_3D')","summary":"qlinearmatmul"}],"inputs":[{"description":"N-dimensional quantized matrix a","name":"a","type":"T1"},{"description":"scale of quantized input a","name":"a_scale","type":"tensor(float)"},{"description":"zero point of quantized input a","name":"a_zero_point","type":"T1"},{"description":"N-dimensional quantized matrix b","name":"b","type":"T2"},{"description":"scale of quantized input b","name":"b_scale","type":"tensor(float)"},{"description":"zero point of quantized input b","name":"b_zero_point","type":"T2"},{"description":"scale of quantized output y","name":"y_scale","type":"tensor(float)"},{"description":"zero point of quantized output y","name":"y_zero_point","type":"T3"}],"max_input":8,"max_output":1,"min_input":8,"min_output":1,"outputs":[{"description":"Quantized matrix multiply results from a * b","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input a and its zero point data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input b and its zero point data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain output y and its zero point data type to 8-bit integer tensor.","type_param_str":"T3"}]}},{"name":"QuantizeLinear","schema":{"description":"The linear per-tensor/layer quantization operator. It consumes a high precision tensor, a scale, a zero point to compute the low precision / quantized tensor.\nThe quantization formula is y = saturate ((x / y_scale) + y_zero_point). For saturation, it saturates to [0, 255] if it's uint8, or [-128, 127] if it's int8.\nFor (x / y_scale), it's rounding to nearest ties to even. Refer to https://en.wikipedia.org/wiki/Rounding for details. 'y_zero_point' and 'y' must have same type.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[[[-162, 10],\n [-100, 232],\n [-20, -50]],\n\n [[-76, 0],\n [0, 252],\n [32, -44]],\n\n [[245, -485],\n [-960, -270],\n [-375, -470]], ], ], dtype=np.float32)\ny_scale = np.array([2, 4, 5], dtype=np.float32)\ny_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x / y_scale.reshape(1, 3, 1, 1) + y_zero_point.reshape(1, 3, 1, 1)).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([0, 2, 3, 1000, -254, -1000]).astype(np.float32)\ny_scale = np.float32(2)\ny_zero_point = np.uint8(128)\ny = np.array([128, 129, 130, 255, 1, 0]).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear')","summary":"quantizelinear"}],"inputs":[{"description":"N-D full precision Input tensor to be quantized.","name":"x","type":"T1"},{"description":"Scale for doing quantization to get 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point for doing quantization to get 'y'. It's a scalar, which means a per-tensor/layer quantization. Default value is uint8 typed 0 if it's not specified.","name":"y_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D quantized output tensor. It has same shape as input 'x'.","name":"y","type":"T2"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)"],"description":"Constrain 'x' to float or int32 tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit integer tensor.","type_param_str":"T2"}]}},{"name":"QuantizeLinear","schema":{"attributes":[{"default":1,"description":"(Optional) The axis of the quantization dimension of the input tensor. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input)","name":"axis","required":false,"type":"int64"}],"description":"The linear quantization operator. It consumes a high precision tensor, a scale, and a zero point to compute the low precision / quantized tensor. The scale factor can be a scalar\n(per-tensor/layer quantization), or a 1-D tensor for per-axis quantization. The quantization formula is y = saturate ((x / y_scale) + y_zero_point).\nFor saturation, it saturates to [0, 255] if it's uint8, or [-128, 127] if it's int8.\nFor (x / y_scale), it's rounding to nearest ties to even. Refer to https://en.wikipedia.org/wiki/Rounding for details. 'y_zero_point' and 'y' must have same type.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[[[-162, 10],\n [-100, 232],\n [-20, -50]],\n\n [[-76, 0],\n [0, 252],\n [32, -44]],\n\n [[245, -485],\n [-960, -270],\n [-375, -470]], ], ], dtype=np.float32)\ny_scale = np.array([2, 4, 5], dtype=np.float32)\ny_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x / y_scale.reshape(1, 3, 1, 1) + y_zero_point.reshape(1, 3, 1, 1)).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([0, 2, 3, 1000, -254, -1000]).astype(np.float32)\ny_scale = np.float32(2)\ny_zero_point = np.uint8(128)\ny = np.array([128, 129, 130, 255, 1, 0]).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear')","summary":"quantizelinear"}],"inputs":[{"description":"N-D full precision Input tensor to be quantized.","name":"x","type":"T1"},{"description":"Scale for doing quantization to get 'y'. It can be a scalar, which means per-tensor/layer quantization, or a 1-D Tensor for per-axis quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point for doing quantization to get 'y'. It can be a scalar, which means a per-tensor/layer quantization, or a 1-D tensor for per-axis quantization. Default value is uint8 typed 0 if it's not specified.","name":"y_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D quantized output tensor. It has same shape as input 'x'.","name":"y","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)"],"description":"Constrain 'x' to float or int32 tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit integer tensor.","type_param_str":"T2"}]}},{"name":"RNN","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"One (or two if bidirectional) activation function for input gate. The activation function must be one of the activation functions specified above. Optional: Default `Tanh` if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer simple RNN. This operator is usually supported\nvia some custom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`t` - time step (t-1 means previous time step)\n\n`Wi` - W parameter weight matrix for input gate\n\n`Ri` - R recurrence weight matrix for input gate\n\n`Wbi` - W parameter bias vector for input gate\n\n`Rbi` - R parameter bias vector for input gate\n\n`WBi` - W parameter weight matrix for backward input gate\n\n`RBi` - R recurrence weight matrix for backward input gate\n\n`WBbi` - WR bias vectors for backward input gate\n\n`RBbi` - RR bias vectors for backward input gate\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Tanh):\n\n - Ht = f(Xt*(Wi^T) + Ht-1*Ri + Wbi + Rbi)\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 4\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\nrnn = RNN_Helper(X=input, W=W, R=R)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\ncustom_bias = 0.1\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, hidden_size)).astype(np.float32)\nR_B = np.zeros((1, hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)],\n name='test_simple_rnn_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, hidden_size).astype(np.float32)\nR_B = np.random.randn(1, hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_rnn_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for input gate. Concatenation of `Wi` and `WBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `Ri` and `RBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` and `[WBbi, RBbi]` (if bidirectional). The tensor has shape `[num_directions, 2*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"RNN","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"One (or two if bidirectional) activation function for input gate. The activation function must be one of the activation functions specified above. Optional: Default `Tanh` if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer simple RNN. This operator is usually supported\nvia some custom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`t` - time step (t-1 means previous time step)\n\n`Wi` - W parameter weight matrix for input gate\n\n`Ri` - R recurrence weight matrix for input gate\n\n`Wbi` - W parameter bias vector for input gate\n\n`Rbi` - R parameter bias vector for input gate\n\n`WBi` - W parameter weight matrix for backward input gate\n\n`RBi` - R recurrence weight matrix for backward input gate\n\n`WBbi` - WR bias vectors for backward input gate\n\n`RBbi` - RR bias vectors for backward input gate\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Tanh):\n\n - Ht = f(Xt*(Wi^T) + Ht-1*(Ri^T) + Wbi + Rbi)\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 4\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\nrnn = RNN_Helper(X=input, W=W, R=R)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\ncustom_bias = 0.1\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, hidden_size)).astype(np.float32)\nR_B = np.zeros((1, hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)],\n name='test_simple_rnn_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, hidden_size).astype(np.float32)\nR_B = np.random.randn(1, hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_rnn_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for input gate. Concatenation of `Wi` and `WBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `Ri` and `RBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` and `[WBbi, RBbi]` (if bidirectional). The tensor has shape `[num_directions, 2*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"RandomNormal","schema":{"attributes":[{"default":1,"description":"The data type for the elements of the output tensor. Default is TensorProto::FLOAT.","name":"dtype","required":false,"type":"int64"},{"description":"The mean of the normal distribution.","name":"mean","required":false,"type":"float32"},{"default":1,"description":"The standard deviation of the normal distribution.","name":"scale","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"},{"description":"The shape of the output tensor.","name":"shape","required":true,"type":"int64[]"}],"description":"Generate a tensor with random values drawn from a normal distribution. The shape\nof the tensor is specified by the `shape` argument and the parameter of the normal distribution\nspecified by `mean` and `scale`.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from normal distribution","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"RandomNormalLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use the data type of the input tensor.","name":"dtype","required":false,"type":"int64"},{"description":"The mean of the normal distribution.","name":"mean","required":false,"type":"float32"},{"default":1,"description":"The standard deviation of the normal distribution.","name":"scale","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor with random values drawn from a normal distribution.\nThe shape of the output tensor is copied from the shape of the input tensor,\nand the parameters of the normal distribution are specified by `mean` and `scale`.\n\nThe data type is specified by the 'dtype' argument, or copied from the input tensor if not provided.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message, and be valid as an output type.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor to copy shape and optionally type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from normal distribution","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T2"}]}},{"name":"RandomUniform","schema":{"attributes":[{"default":1,"description":"The data type for the elements of the output tensor. If not specified, default is TensorProto::FLOAT.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Upper boundary of the output values.","name":"high","required":false,"type":"float32"},{"description":"Lower boundary of the output values.","name":"low","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"},{"description":"The shape of the output tensor.","name":"shape","required":true,"type":"int64[]"}],"description":"Generate a tensor with random values drawn from a uniform distribution. The shape\nof the tensor is specified by the `shape` argument and the range by `low` and `high`.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from uniform distribution","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"RandomUniformLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use the data type of the input tensor.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Upper boundary of the output values.","name":"high","required":false,"type":"float32"},{"description":"Lower boundary of the output values.","name":"low","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor with random values drawn from a uniform distribution.\nThe shape of the output tensor is copied from the shape of the input tensor,\nand the parameters of the uniform distribution are specified by `low` and `high`.\n\nThe data type is specified by the 'dtype' argument, or copied from the input tensor if not provided.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message and be valid as an output type.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor to copy shape and optionally type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from uniform distribution","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T2"}]}},{"name":"Range","schema":{"description":"Generate a tensor containing a sequence of numbers that begin at `start` and extends by increments of `delta`\nup to `limit` (exclusive).\n\nThe number of elements in the output of range is computed as below-\n\n`number_of_elements = max( ceil( (limit - start) / delta ) , 0 )`\n\nThe pseudocode determining the contents of the output is shown below-\n\n`for(int i=0; i) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reciprocal","schema":{"description":"Reciprocal takes one input data (Tensor) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reciprocal","schema":{"description":"Reciprocal takes one input data (Tensor) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"New shape","name":"shape","required":false,"type":"int64[]"}],"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nIt takes a tensor as input and an argument `shape`. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nFirst input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"},{"description":"Specified shape for output.","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":5,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nFirst input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"},{"description":"Specified shape for output.","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Resize","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"description":"Resize the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Resize","schema":{"attributes":[{"default":"half_pixel","description":"\nThis attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
\n\nThe coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. \nDenote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input \"roi\", scale = length_resized / length_original,
\n\nif coordinate_transformation_mode is \"half_pixel\",
\nx_original = (x_resized + 0.5) / scale - 0.5,
\n\nif coordinate_transformation_mode is \"pytorch_half_pixel\",
\nx_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
\n\nif coordinate_transformation_mode is \"align_corners\",
\nx_original = x_resized * (length_original - 1) / (length_resized - 1),
\n\nif coordinate_transformation_mode is \"asymmetric\",
\nx_original = x_resized / scale,
\n\nif coordinate_transformation_mode is \"tf_half_pixel_for_nn\",
\nx_original = (x_resized + 0.5) / scale,
\n\nif coordinate_transformation_mode is \"tf_crop_and_resize\",
\nx_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).","name":"coordinate_transformation_mode","required":false,"type":"string"},{"default":-0.75,"description":"The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75 (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. This attribute is valid only if \"mode\" is \"cubic\".","name":"cubic_coeff_a","required":false,"type":"float32"},{"description":"If set to 1, the weight of sampling locations outside the tensor will be set to 0 and the weight will be renormalized so that their sum is 1.0. The default value is 0.","name":"exclude_outside","required":false,"type":"int64"},{"description":"When coordinate_transformation_mode is \"tf_crop_and_resize\" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f.","name":"extrapolation_value","required":false,"type":"float32"},{"default":"nearest","description":"Three interpolation modes: nearest (default), linear and cubic. The \"linear\" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). The \"cubic\" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor).","name":"mode","required":false,"type":"string"},{"default":"round_prefer_floor","description":"Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \"nearest\" pixel in input tensor from x_original, so this attribute is valid only if \"mode\" is \"nearest\".","name":"nearest_mode","required":false,"type":"string"}],"description":"Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \\\"sizes\\\" is not specified.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T1"},{"description":"1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \"tf_crop_and_resize\"","name":"roi","type":"T2"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified. If 'size' is needed, the user can use an empty string as the name of 'scales' in this operator's input list.","name":"scales","type":"tensor(float)"},{"description":"The size of the output tensor. The number of elements of 'sizes' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified.","name":"sizes","option":"optional","type":"tensor(int64)"}],"inputs_range":"3 - 4","max_input":4,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain roi type to float or double.","type_param_str":"T2"}]}},{"name":"Resize","schema":{"attributes":[{"default":"half_pixel","description":"\nThis attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
\n\nThe coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. \nDenote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input \"roi\", scale = length_resized / length_original,
\n\nif coordinate_transformation_mode is \"half_pixel\",
\nx_original = (x_resized + 0.5) / scale - 0.5,
\n\nif coordinate_transformation_mode is \"pytorch_half_pixel\",
\nx_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
\n\nif coordinate_transformation_mode is \"align_corners\",
\nx_original = x_resized * (length_original - 1) / (length_resized - 1),
\n\nif coordinate_transformation_mode is \"asymmetric\",
\nx_original = x_resized / scale,
\n\nif coordinate_transformation_mode is \"tf_half_pixel_for_nn\",
\nx_original = (x_resized + 0.5) / scale,
\n\nif coordinate_transformation_mode is \"tf_crop_and_resize\",
\nx_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).","name":"coordinate_transformation_mode","required":false,"type":"string"},{"default":-0.75,"description":"The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75 (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. This attribute is valid only if \"mode\" is \"cubic\".","name":"cubic_coeff_a","required":false,"type":"float32"},{"description":"If set to 1, the weight of sampling locations outside the tensor will be set to 0 and the weight will be renormalized so that their sum is 1.0. The default value is 0.","name":"exclude_outside","required":false,"type":"int64"},{"description":"When coordinate_transformation_mode is \"tf_crop_and_resize\" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f.","name":"extrapolation_value","required":false,"type":"float32"},{"default":"nearest","description":"Three interpolation modes: nearest (default), linear and cubic. The \"linear\" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). The \"cubic\" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor).","name":"mode","required":false,"type":"string"},{"default":"round_prefer_floor","description":"Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \"nearest\" pixel in input tensor from x_original, so this attribute is valid only if \"mode\" is \"nearest\".","name":"nearest_mode","required":false,"type":"string"}],"description":"Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \\\"sizes\\\" is not specified.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T1"},{"description":"1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \"tf_crop_and_resize\"","name":"roi","type":"T2"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified. If 'size' is needed, the user can use an empty string as the name of 'scales' in this operator's input list.","name":"scales","type":"tensor(float)"},{"description":"The size of the output tensor. The number of elements of 'sizes' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified.","name":"sizes","option":"optional","type":"tensor(int64)"}],"inputs_range":"3 - 4","max_input":4,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain roi type to float or double.","type_param_str":"T2"}]}},{"name":"ReverseSequence","schema":{"attributes":[{"default":1,"description":"(Optional) Specify which axis is batch axis. Must be one of 1 (default), or 0.","name":"batch_axis","required":false,"type":"int64"},{"description":"(Optional) Specify which axis is time axis. Must be one of 0 (default), or 1.","name":"time_axis","required":false,"type":"int64"}],"description":"Reverse batch of sequences having different lengths specified by `sequence_lens`.\n\nFor each slice i iterating on batch axis, the operator reverses the first sequence_lens[i] elements on time axis,\nand copies elements whose index's beyond sequence_lens[i] to the output. So the output slice i contains reversed\nsequences on the first sequence_lens[i] elements, then have original values copied for the other elements.\n\nExample 1:\n input = [[0.0, 4.0, 8.0, 12.0],\n [1.0, 5.0, 9.0, 13.0],\n [2.0, 6.0, 10.0, 14.0],\n [3.0, 7.0, 11.0, 15.0]]\n sequence_lens = [4, 3, 2, 1]\n time_axis = 0\n batch_axis = 1\n\n output = [[3.0, 6.0, 9.0, 12.0],\n [2.0, 5.0, 8.0, 13.0],\n [1.0, 4.0, 10.0, 14.0],\n [0.0, 7.0, 11.0, 15.0]]\n\nExample 2:\n input = [[0.0, 1.0, 2.0, 3.0 ],\n [4.0, 5.0, 6.0, 7.0 ],\n [8.0, 9.0, 10.0, 11.0],\n [12.0, 13.0, 14.0, 15.0]]\n sequence_lens = [1, 2, 3, 4]\n time_axis = 1\n batch_axis = 0\n\n output = [[0.0, 1.0, 2.0, 3.0 ],\n [5.0, 4.0, 6.0, 7.0 ],\n [10.0, 9.0, 8.0, 11.0],\n [15.0, 14.0, 13.0, 12.0]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReverseSequence',\n inputs=['x', 'sequence_lens'],\n outputs=['y'],\n time_axis=1,\n batch_axis=0,\n)\nx = np.array([[0.0, 1.0, 2.0, 3.0],\n [4.0, 5.0, 6.0, 7.0],\n [8.0, 9.0, 10.0, 11.0],\n [12.0, 13.0, 14.0, 15.0]], dtype=np.float32)\nsequence_lens = np.array([1, 2, 3, 4], dtype=np.int64)\n\ny = np.array([[0.0, 1.0, 2.0, 3.0],\n [5.0, 4.0, 6.0, 7.0],\n [10.0, 9.0, 8.0, 11.0],\n [15.0, 14.0, 13.0, 12.0]], dtype=np.float32)\n\nexpect(node, inputs=[x, sequence_lens], outputs=[y],\n name='test_reversesequence_batch')","summary":"reversesequence_batch"},{"code":"node = onnx.helper.make_node(\n 'ReverseSequence',\n inputs=['x', 'sequence_lens'],\n outputs=['y'],\n time_axis=0,\n batch_axis=1,\n)\nx = np.array([[0.0, 4.0, 8.0, 12.0],\n [1.0, 5.0, 9.0, 13.0],\n [2.0, 6.0, 10.0, 14.0],\n [3.0, 7.0, 11.0, 15.0]], dtype=np.float32)\nsequence_lens = np.array([4, 3, 2, 1], dtype=np.int64)\n\ny = np.array([[3.0, 6.0, 9.0, 12.0],\n [2.0, 5.0, 8.0, 13.0],\n [1.0, 4.0, 10.0, 14.0],\n [0.0, 7.0, 11.0, 15.0]], dtype=np.float32)\n\nexpect(node, inputs=[x, sequence_lens], outputs=[y],\n name='test_reversesequence_time')","summary":"reversesequence_time"}],"inputs":[{"description":"Tensor of rank r >= 2.","name":"input","type":"T"},{"description":"Tensor specifying lengths of the sequences in a batch. It has shape `[batch_size]`.","name":"sequence_lens","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor with same shape of input.","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"}]}},{"name":"RoiAlign","schema":{"attributes":[{"default":"avg","description":"The pooling method. Two modes are supported: 'avg' and 'max'. Default is 'avg'.","name":"mode","required":false,"type":"string"},{"default":1,"description":"default 1; Pooled output Y's height.","name":"output_height","required":false,"type":"int64"},{"default":1,"description":"default 1; Pooled output Y's width.","name":"output_width","required":false,"type":"int64"},{"description":"Number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If == 0, then an adaptive number of grid points are used (computed as ceil(roi_width / output_width), and likewise for height). Default is 0.","name":"sampling_ratio","required":false,"type":"int64"},{"default":1,"description":"Multiplicative spatial scale factor to translate ROI coordinates from their input spatial scale to the scale used when pooling, i.e., spatial scale of the input feature map X relative to the input image. E.g.; default is 1.0f. ","name":"spatial_scale","required":false,"type":"float32"}],"description":"Region of Interest (RoI) align operation described in the\n[Mask R-CNN paper](https://arxiv.org/abs/1703.06870).\nRoiAlign consumes an input tensor X and region of interests (rois)\nto apply pooling across each RoI; it produces a 4-D tensor of shape\n(num_rois, C, output_height, output_width).\n\nRoiAlign is proposed to avoid the misalignment by removing\nquantizations while converting from original image into feature\nmap and from feature map into RoI feature; in each ROI bin,\nthe value of the sampled locations are computed directly\nthrough bilinear interpolation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n \"RoiAlign\",\n inputs=[\"X\", \"rois\", \"batch_indices\"],\n outputs=[\"Y\"],\n spatial_scale=1.0,\n output_height=5,\n output_width=5,\n sampling_ratio=2,\n)\n\nX = np.array(\n [\n [\n [\n [\n 0.2764,\n 0.7150,\n 0.1958,\n 0.3416,\n 0.4638,\n 0.0259,\n 0.2963,\n 0.6518,\n 0.4856,\n 0.7250,\n ],\n [\n 0.9637,\n 0.0895,\n 0.2919,\n 0.6753,\n 0.0234,\n 0.6132,\n 0.8085,\n 0.5324,\n 0.8992,\n 0.4467,\n ],\n [\n 0.3265,\n 0.8479,\n 0.9698,\n 0.2471,\n 0.9336,\n 0.1878,\n 0.4766,\n 0.4308,\n 0.3400,\n 0.2162,\n ],\n [\n 0.0206,\n 0.1720,\n 0.2155,\n 0.4394,\n 0.0653,\n 0.3406,\n 0.7724,\n 0.3921,\n 0.2541,\n 0.5799,\n ],\n [\n 0.4062,\n 0.2194,\n 0.4473,\n 0.4687,\n 0.7109,\n 0.9327,\n 0.9815,\n 0.6320,\n 0.1728,\n 0.6119,\n ],\n [\n 0.3097,\n 0.1283,\n 0.4984,\n 0.5068,\n 0.4279,\n 0.0173,\n 0.4388,\n 0.0430,\n 0.4671,\n 0.7119,\n ],\n [\n 0.1011,\n 0.8477,\n 0.4726,\n 0.1777,\n 0.9923,\n 0.4042,\n 0.1869,\n 0.7795,\n 0.9946,\n 0.9689,\n ],\n [\n 0.1366,\n 0.3671,\n 0.7011,\n 0.6234,\n 0.9867,\n 0.5585,\n 0.6985,\n 0.5609,\n 0.8788,\n 0.9928,\n ],\n [\n 0.5697,\n 0.8511,\n 0.6711,\n 0.9406,\n 0.8751,\n 0.7496,\n 0.1650,\n 0.1049,\n 0.1559,\n 0.2514,\n ],\n [\n 0.7012,\n 0.4056,\n 0.7879,\n 0.3461,\n 0.0415,\n 0.2998,\n 0.5094,\n 0.3727,\n 0.5482,\n 0.0502,\n ],\n ]\n ]\n ],\n dtype=np.float32,\n)\nbatch_indices = np.array([0, 0, 0], dtype=np.int64)\nrois = np.array([[0, 0, 9, 9], [0, 5, 4, 9], [5, 5, 9, 9]], dtype=np.float32)\n# (num_rois, C, output_height, output_width)\nY = np.array(\n [\n [\n [\n [0.4664, 0.4466, 0.3405, 0.5688, 0.6068],\n [0.3714, 0.4296, 0.3835, 0.5562, 0.3510],\n [0.2768, 0.4883, 0.5222, 0.5528, 0.4171],\n [0.4713, 0.4844, 0.6904, 0.4920, 0.8774],\n [0.6239, 0.7125, 0.6289, 0.3355, 0.3495],\n ]\n ],\n [\n [\n [0.3022, 0.4305, 0.4696, 0.3978, 0.5423],\n [0.3656, 0.7050, 0.5165, 0.3172, 0.7015],\n [0.2912, 0.5059, 0.6476, 0.6235, 0.8299],\n [0.5916, 0.7389, 0.7048, 0.8372, 0.8893],\n [0.6227, 0.6153, 0.7097, 0.6154, 0.4585],\n ]\n ],\n [\n [\n [0.2384, 0.3379, 0.3717, 0.6100, 0.7601],\n [0.3767, 0.3785, 0.7147, 0.9243, 0.9727],\n [0.5749, 0.5826, 0.5709, 0.7619, 0.8770],\n [0.5355, 0.2566, 0.2141, 0.2796, 0.3600],\n [0.4365, 0.3504, 0.2887, 0.3661, 0.2349],\n ]\n ],\n ],\n dtype=np.float32,\n)\n\nexpect(node, inputs=[X, rois, batch_indices], outputs=[Y], name=\"test_roialign\")","summary":"roialign"}],"inputs":[{"description":"Input data tensor from the previous operator; 4-D feature map of shape (N, C, H, W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data.","name":"X","type":"T1"},{"description":"RoIs (Regions of Interest) to pool over; rois is 2-D input of shape (num_rois, 4) given as [[x1, y1, x2, y2], ...]. The RoIs' coordinates are in the coordinate system of the input image. Each coordinate set has a 1:1 correspondence with the 'batch_indices' input.","name":"rois","type":"T1"},{"description":"1-D tensor of shape (num_rois,) with each element denoting the index of the corresponding image in the batch.","name":"batch_indices","type":"T2"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"RoI pooled output, 4-D tensor of shape (num_rois, C, output_height, output_width). The r-th batch element Y[r-1] is a pooled feature map corresponding to the r-th RoI X[r-1].","name":"Y","type":"T1"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain types to int tensors.","type_param_str":"T2"}]}},{"name":"Round","schema":{"description":"Round takes one input Tensor and rounds the values, element-wise, meaning\nit finds the nearest integer for each value.\nIn case of halfs, the rule is to round them to the nearest even integer.\nThe output tensor has the same shape and type as the input.\n\nExamples:\n```\nround([0.9]) = [1.0]\nround([2.5]) = [2.0]\nround([2.3]) = [2.0]\nround([1.5]) = [2.0]\nround([-4.5]) = [-4.0]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Round',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([0.1, 0.5, 0.9, 1.2, 1.5,\n 1.8, 2.3, 2.5, 2.7, -1.1,\n -1.5, -1.9, -2.2, -2.5, -2.8]).astype(np.float32)\ny = np.array([0., 0., 1., 1., 2.,\n 2., 2., 2., 3., -1.,\n -2., -2., -2., -2., -3.]).astype(np.float32) # expected output\nexpect(node, inputs=[x], outputs=[y],\n name='test_round')","summary":"round"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SVMClassifier","schema":{"attributes":[{"description":"Class labels if using integer labels.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_ints","required":false,"type":"int64[]"},{"description":"Class labels if using string labels.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"","name":"coefficients","required":false,"type":"float32[]"},{"description":"List of 3 elements containing gamma, coef0, and degree, in that order. Zero if unused for the kernel.","name":"kernel_params","required":false,"type":"float32[]"},{"default":"LINEAR","description":"The kernel type, one of 'LINEAR,' 'POLY,' 'RBF,' 'SIGMOID'.","name":"kernel_type","required":false,"type":"string"},{"default":"NONE","description":"Indicates the transform to apply to the score.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"description":"First set of probability coefficients.","name":"prob_a","required":false,"type":"float32[]"},{"description":"Second set of probability coefficients. This array must be same size as prob_a.
If these are provided then output Z are probability estimates, otherwise they are raw scores.","name":"prob_b","required":false,"type":"float32[]"},{"description":"","name":"rho","required":false,"type":"float32[]"},{"description":"","name":"support_vectors","required":false,"type":"float32[]"},{"description":"","name":"vectors_per_class","required":false,"type":"int64[]"}],"description":"Support Vector Machine classifier\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be classified.","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Classification outputs (one class per example).","name":"Y","type":"T2"},{"description":"Class scores (one per class per example), if prob_a and prob_b are provided they are probabilities for each class, otherwise they are raw scores.","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type, either [C] or [N,C].","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, depending on which of the the classlabels_* attributes is used. Its size will match the bactch size of the input.","type_param_str":"T2"}]}},{"name":"SVMRegressor","schema":{"attributes":[{"description":"Support vector coefficients.","name":"coefficients","required":false,"type":"float32[]"},{"description":"List of 3 elements containing gamma, coef0, and degree, in that order. Zero if unused for the kernel.","name":"kernel_params","required":false,"type":"float32[]"},{"default":"LINEAR","description":"The kernel type, one of 'LINEAR,' 'POLY,' 'RBF,' 'SIGMOID'.","name":"kernel_type","required":false,"type":"string"},{"description":"The number of support vectors.","name":"n_supports","required":false,"type":"int64"},{"description":"Flag indicating whether the regression is a one-class SVM or not.","name":"one_class","required":false,"type":"int64"},{"default":"NONE","description":"Indicates the transform to apply to the score.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT.'","name":"post_transform","required":false,"type":"string"},{"description":"","name":"rho","required":false,"type":"float32[]"},{"description":"Chosen support vectors","name":"support_vectors","required":false,"type":"float32[]"}],"description":"Support Vector Machine regression prediction and one-class SVM anomaly detection.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be regressed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Regression outputs (one score per target per example).","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type, either [C] or [N,C].","type_param_str":"T"}]}},{"name":"Scaler","schema":{"attributes":[{"description":"First, offset by this.
Can be length of features in an [N,F] tensor or length 1, in which case it applies to all features, regardless of dimension count.","name":"offset","required":false,"type":"float32[]"},{"description":"Second, multiply by this.
Can be length of features in an [N,F] tensor or length 1, in which case it applies to all features, regardless of dimension count.
Must be same length as 'offset'","name":"scale","required":false,"type":"float32[]"}],"description":"Rescale input data, for example to standardize features by removing the mean and scaling to unit variance.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be scaled.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Scaled output data.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"directions","required":false,"type":"int64[]"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops). All these tensors are required to\nhave the same shape in each iteration of the loop (a restriction imposed to enable efficient\nmemory allocation). Many common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs).\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe operation supports batching, and the batch-axis is required to be 0.\nWhen multiple scan_input tensors are used, they must all have the same batch-size,\nand they must all have the same maximum-sequence-length (the dimensionality of the\nsequence axis or scan axis). The sequence axis or scan axis is required to be 1.\n\nThe operation has an optional sequence_lens input (of shape [BATCH_SIZE]) to\nallow variable length sequences of length <= the maximum-sequence-length. If this\ninput is not specified, all sequences are assumed to be of length equal to\nmaximum-sequence-length. For variable length input sequences, the scan_outputs\nwill consist of a sequence of same length as the input, padded to the\nmaximum-sequence-length.\n\nThe optional attribute directions can be used to scan a sequence in the reverse direction.\nIf this attribute is omitted, all sequences are scanned in the forward direction.\nA bidirectional scan be performed by specifying the same tensor input twice in the\nscan_inputs, once with a forward direction, and once with a backward direction.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body\n > (sequence_lengths, init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // T.shape[0] denotes the batch-size of T\n // The batch-size of scan_1, ..., scan_m are all required to be equal\n batch_size = scan_1.shape[0];\n\n // scan_i.shape[1] denotes the (max) sequence-length of scan_i\n // scan_i.shape[1] is required to be equal to scan_j.shape[1] for all i,j.\n max_sequence_length = scan_1.shape[1];\n\n for (int batch = 0; batch < batch_size; ++batch) {\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n N = (sequence_lengths specified) ? sequence_lengths[batch] : max_sequence_length;\n\n // execute loop\n for (int t = 0; t < N; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = (scan_1[batch])[t];\n ... ;\n si_m = (scan_m[batch])[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n // accumulate the outputs for this batch:\n bst_1[batch] = st_1; ..., bst_n[batch] = st_n;\n // Note scan-outputs will have size max_sequence_length, but only first N values will be meaningful.\n // The remaining values have an undefined value.\n b_scan_out_1[batch] = scan_out_1; ...; b_scan_out_k[batch] = scan_out_k;\n }\n return bst_1, ..., bst_n, b_scan_out_1, ..., b_scan_out_k;\n\n\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ... \n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](\"\", %H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n \n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Optional tensor specifying lengths of the sequences in a batch. If this input is not specified, all sequences are assumed to be of the maximum sequence length (the dimension of the sequence axis of the scan_input tensors).","name":"sequence_lens","option":"optional","type":"I"},{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"2 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":2,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"},{"description":"An optional list of M flags. The i-th element of the list specifies the axis to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will be used as the scan axis for every scan_input.","name":"scan_input_axes","required":false,"type":"int64[]"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"scan_input_directions","required":false,"type":"int64[]"},{"description":"An optional list of K flags. The i-th element of the list specifies the axis for the i-th scan_output. The scan outputs are accumulated along the specified axis. If omitted, 0 will be used as the scan axis for every scan_output.","name":"scan_output_axes","required":false,"type":"int64[]"},{"description":"An optional list of K flags, one for each scan_output. The i-th element of the list specifies whether the i-th scan_output should be constructed by appending or prepending a new value in each iteration: 0 indicates appending and 1 indicates prepending. If omitted, all scan_output tensors will be produced by appending a value in each iteration.","name":"scan_output_directions","required":false,"type":"int64[]"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops).\nMany common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs). All the output tensors (state_variables as\nwell as scan_output_element tensors) are required to have the same shape in each iteration\nof the loop (a restriction imposed to enable efficient memory allocation).\n\nNote that the iterated element passed to the body subgraph does not have a sequence\naxis. It will have a rank one less than the rank of the corresponding scan_input.\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe optional attribute scan_input_directions specifies the direction (forward or backward)\nfor each scan input. If this attribute is omitted, all sequences are scanned in the forward\ndirection. A bidirectional scan may be performed by specifying the same tensor input twice\nin the scan_inputs, once with a forward direction, and once with a backward direction.\n\nThe scan_output of the operation is produced by concatenating the scan_output_element\nvalues produced by the body in each iteration. The optional attribute scan_output_directions\nspecifies the direction in which scan_output is constructed (by appending or prepending the\nscan_output_element to scan_output in each iteration) for each scan_output. If this attribute\nis omitted, the scan_output_element is appended to the scan_output in each iteration.\n\nThe optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.\nIf omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the\nbatch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.\nNote that scanning a non-zero axis may be less efficient than scanning axis zero.\n\nThe optional attribute scan_output_axes specifies the axis along which the scan_outputs\nare accumulated for each scan_output. For example, if axis 1 is the time axis (to be\nscanned) for both inputs and outputs, specify a scan_input axis and scan_output axis\nvalue of 1.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body,\n scan_input_axes = [axis_1, ..., axis_m]\n > (init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i\n // scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.\n sequence_length = scan_1.shape[axis_1];\n\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n\n // execute loop\n for (int t = 0; t < sequence_length; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = scan_1[t];\n ... ;\n si_m = scan_m[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n\n return st_1, ..., st_n, scan_out_1, ..., scan_out_k;\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ...\n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](%H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n\n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"},{"description":"An optional list of M flags. The i-th element of the list specifies the axis to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will be used as the scan axis for every scan_input. Negative value for an axis means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"scan_input_axes","required":false,"type":"int64[]"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"scan_input_directions","required":false,"type":"int64[]"},{"description":"An optional list of K flags. The i-th element of the list specifies the axis for the i-th scan_output. The scan outputs are accumulated along the specified axis. If omitted, 0 will be used as the scan axis for every scan_output. Negative value for an axis means counting dimensions from the back. Accepted range is [-r, r-1].","name":"scan_output_axes","required":false,"type":"int64[]"},{"description":"An optional list of K flags, one for each scan_output. The i-th element of the list specifies whether the i-th scan_output should be constructed by appending or prepending a new value in each iteration: 0 indicates appending and 1 indicates prepending. If omitted, all scan_output tensors will be produced by appending a value in each iteration.","name":"scan_output_directions","required":false,"type":"int64[]"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops).\nMany common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs). All the output tensors (state_variables as\nwell as scan_output_element tensors) are required to have the same shape in each iteration\nof the loop (a restriction imposed to enable efficient memory allocation).\n\nNote that the iterated element passed to the body subgraph does not have a sequence\naxis. It will have a rank one less than the rank of the corresponding scan_input.\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe optional attribute scan_input_directions specifies the direction (forward or backward)\nfor each scan input. If this attribute is omitted, all sequences are scanned in the forward\ndirection. A bidirectional scan may be performed by specifying the same tensor input twice\nin the scan_inputs, once with a forward direction, and once with a backward direction.\n\nThe scan_output of the operation is produced by concatenating the scan_output_element\nvalues produced by the body in each iteration. The optional attribute scan_output_directions\nspecifies the direction in which scan_output is constructed (by appending or prepending the\nscan_output_element to scan_output in each iteration) for each scan_output. If this attribute\nis omitted, the scan_output_element is appended to the scan_output in each iteration.\n\nThe optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.\nIf omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the\nbatch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.\nNote that scanning a non-zero axis may be less efficient than scanning axis zero.\n\nThe optional attribute scan_output_axes specifies the axis along which the scan_outputs\nare accumulated for each scan_output. For example, if axis 1 is the time axis (to be\nscanned) for both inputs and outputs, specify a scan_input axis and scan_output axis\nvalue of 1.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body,\n scan_input_axes = [axis_1, ..., axis_m]\n > (init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i\n // scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.\n sequence_length = scan_1.shape[axis_1];\n\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n\n // execute loop\n for (int t = 0; t < sequence_length; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = scan_1[t];\n ... ;\n si_m = scan_m[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n\n return st_1, ..., st_n, scan_out_1, ..., scan_out_k;\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ... \n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](%H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n\n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1]","name":"axis","required":false,"type":"int64"}],"description":"Given `data`, `updates` and `indices` input tensors of rank r >= 1, write the values provided by `updates` \ninto the first input, `data`, along `axis` dimension of `data` (by default outer-most one as axis=0) at corresponding `indices`. \nFor each entry in `updates`, the target index in `data` is specified by corresponding entry in `indices`\nfor dimension = axis, and index in source for dimension != axis. For instance, in a 2-D tensor case,\ndata[indices[i][j]][j] = updates[i][j] if axis = 0, or data[i][indices[i][j]] = updates[i][j] if axis = 1,\nwhere i and j are loop counters from 0 up to the respective size in `updates` - 1.\nExample 1:\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\nExample 2:\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input).","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"This operator is deprecated. Please use ScatterElements, which provides the same functionality.\n\nScatter takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"This operator is deprecated. Please use ScatterElements, which provides the same functionality.\n\nScatter takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterElements","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"ScatterElements takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_axis')","summary":"scatter_elements_with_axis"},{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, -3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 2.1, 4.0, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_negative_indices')","summary":"scatter_elements_with_negative_indices"},{"code":"node = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_without_axis')","summary":"scatter_elements_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterElements","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"ScatterElements takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_axis')","summary":"scatter_elements_with_axis"},{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, -3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 2.1, 4.0, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_negative_indices')","summary":"scatter_elements_with_negative_indices"},{"code":"node = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_without_axis')","summary":"scatter_elements_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterND","schema":{"description":"ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1,\nand `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value to values\nspecified by `updates` at specific index positions specified by `indices`. Its output shape\nis the same as the shape of `data`. Note that `indices` should not have duplicate entries.\nThat is, two or more `updates` for the same index-location is not supported.\n\n`indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`.\n `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`.\nHence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an\nupdate to a single element of the tensor. When k is less than rank(data) each update entry specifies an\nupdate to a slice of the tensor.\n\n`updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the\nfirst (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape.\nThe remaining dimensions of `updates` correspond to the dimensions of the\nreplacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor,\ncorresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates`\nmust equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation\nof shapes.\n\nThe `output` is calculated via the following equation:\n\n output = np.copy(data)\n update_indices = indices.shape[:-1]\n for idx in np.ndindex(update_indices):\n output[indices[idx]] = updates[idx]\n\nThe order of iteration in the above loop is not specified.\nIn particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2].\nThis ensures that the output value does not depend on the iteration order.\n\nThis operator is the inverse of GatherND.\n\nExample 1:\n```\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n indices = [[4], [3], [1], [7]]\n updates = [9, 10, 11, 12]\n output = [1, 11, 3, 10, 9, 6, 7, 12]\n```\n\nExample 2:\n```\n data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n indices = [[0], [2]]\n updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]]\n output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ScatterND',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.array(\n [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\nindices = np.array([[0], [2]], dtype=np.int64)\nupdates = np.array(\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32)\n# Expecting output as np.array(\n# [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n# [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n# [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n# [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\noutput = scatter_nd_impl(data, indices, updates)\nexpect(node, inputs=[data, indices, updates], outputs=[output],\n name='test_scatternd')","summary":"scatternd"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1.","name":"indices","type":"tensor(int64)"},{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"ScatterND","schema":{"description":"ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1,\nand `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value to values\nspecified by `updates` at specific index positions specified by `indices`. Its output shape\nis the same as the shape of `data`. Note that `indices` should not have duplicate entries.\nThat is, two or more `updates` for the same index-location is not supported.\n\n`indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`.\n `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`.\nHence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an\nupdate to a single element of the tensor. When k is less than rank(data) each update entry specifies an\nupdate to a slice of the tensor.\n\n`updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the\nfirst (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape.\nThe remaining dimensions of `updates` correspond to the dimensions of the\nreplacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor,\ncorresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates`\nmust equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation\nof shapes.\n\nThe `output` is calculated via the following equation:\n\n output = np.copy(data)\n update_indices = indices.shape[:-1]\n for idx in np.ndindex(update_indices):\n output[indices[idx]] = updates[idx]\n\nThe order of iteration in the above loop is not specified.\nIn particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2].\nThis ensures that the output value does not depend on the iteration order.\n\nThis operator is the inverse of GatherND.\n\nExample 1:\n```\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n indices = [[4], [3], [1], [7]]\n updates = [9, 10, 11, 12]\n output = [1, 11, 3, 10, 9, 6, 7, 12]\n```\n\nExample 2:\n```\n data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n indices = [[0], [2]]\n updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]]\n output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ScatterND',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.array(\n [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\nindices = np.array([[0], [2]], dtype=np.int64)\nupdates = np.array(\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32)\n# Expecting output as np.array(\n# [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n# [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n# [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n# [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\noutput = scatter_nd_impl(data, indices, updates)\nexpect(node, inputs=[data, indices, updates], outputs=[output],\n name='test_scatternd')","summary":"scatternd"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1.","name":"indices","type":"tensor(int64)"},{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"Selu","schema":{"attributes":[{"default":1.673200011253357,"description":"Coefficient of SELU default to 1.6732.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"default":1.0506999492645264,"description":"Coefficient of SELU default to 1.0507.","name":"gamma","required":false,"type":"float32"}],"category":"Activation","description":"Selu takes one input data (Tensor) and produces one output data\n(Tensor) where the scaled exponential linear unit function,\n`y = gamma * (alpha * e^x - alpha) for x <= 0`, `y = gamma * x for x > 0`,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0,\n gamma=3.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-3.79272318, 0., 3.]\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu')","summary":"selu"},{"code":"default_alpha = 1.67326319217681884765625\ndefault_gamma = 1.05070102214813232421875\nnode = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * default_gamma + \\\n (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha * default_gamma\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_default')","summary":"selu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Selu","schema":{"attributes":[{"default":1.6732631921768188,"description":"Coefficient of SELU default to 1.67326319217681884765625 (i.e., float32 approximation of 1.6732632423543772848170429916717).","name":"alpha","required":false,"type":"float32"},{"default":1.0507010221481323,"description":"Coefficient of SELU default to 1.05070102214813232421875 (i.e., float32 approximation of 1.0507009873554804934193349852946).","name":"gamma","required":false,"type":"float32"}],"category":"Activation","description":"Selu takes one input data (Tensor) and produces one output data\n(Tensor) where the scaled exponential linear unit function,\n`y = gamma * (alpha * e^x - alpha) for x <= 0`, `y = gamma * x for x > 0`,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0,\n gamma=3.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-3.79272318, 0., 3.]\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu')","summary":"selu"},{"code":"default_alpha = 1.67326319217681884765625\ndefault_gamma = 1.05070102214813232421875\nnode = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * default_gamma + \\\n (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha * default_gamma\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_default')","summary":"selu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SequenceAt","schema":{"description":"Outputs a tensor copy from the tensor at 'position' in 'input_sequence'.\nAccepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Position of the tensor in the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","type":"I"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor at the specified position in the input sequence.","name":"tensor","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceConstruct","schema":{"description":"Construct a tensor sequence containing 'inputs' tensors.\nAll tensors in 'inputs' must have the same data type.\n","domain":"ai.onnx","inputs":[{"description":"Tensors.","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Sequence enclosing the input tensors.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to any tensor type.","type_param_str":"S"}]}},{"name":"SequenceEmpty","schema":{"attributes":[{"description":"(Optional) The data type of the tensors in the output sequence. The default type is 'float'.","name":"dtype","required":false,"type":"int64"}],"description":"Construct an empty tensor sequence, with given data type.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Empty sequence.","name":"output","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to any tensor type.","type_param_str":"S"}]}},{"name":"SequenceErase","schema":{"description":"Outputs a tensor sequence that removes the tensor at 'position' from 'input_sequence'.\nAccepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n'position' is optional, by default it erases the last tensor from 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Position of the tensor in the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","option":"optional","type":"I"}],"inputs_range":"1 - 2","max_input":2,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output sequence that has the tensor at the specified position removed.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceInsert","schema":{"description":"Outputs a tensor sequence that inserts 'tensor' into 'input_sequence' at 'position'.\n'tensor' must have the same data type as 'input_sequence'.\nAccepted range for 'position' is in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n'position' is optional, by default it inserts 'tensor' to the back of 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Input tensor to be inserted into the input sequence.","name":"tensor","type":"T"},{"description":"Position in the sequence where the new tensor is inserted. It is optional and default is to insert to the back of the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","option":"optional","type":"I"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output sequence that contains the inserted tensor at given position.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceLength","schema":{"description":"Produces a scalar(tensor of empty shape) containing the number of tensors in 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Length of input sequence. It must be a scalar(tensor of empty shape).","name":"length","type":"I"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"Shape","schema":{"description":"Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shape',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array([\n 2, 3,\n]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.shape).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape')","summary":"shape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Shape of the input tensor","name":"shape","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor.","type_param_str":"T1"}]}},{"name":"Shape","schema":{"description":"Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shape',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array([\n 2, 3,\n]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.shape).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape')","summary":"shape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Shape of the input tensor","name":"shape","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor.","type_param_str":"T1"}]}},{"name":"Shrink","schema":{"attributes":[{"description":"The bias value added to output. Default is 0.","name":"bias","required":false,"type":"float32"},{"default":0.5,"description":"The lambd value for the Shrink formulation. Default is 0.5.","name":"lambd","required":false,"type":"float32"}],"description":"Shrink takes one input data (Tensor) and produces one Tensor output,\nhaving same datatype and shape with input. It has two attributes, lambd and\nbias. The formula of this operator is: If x < -lambd, y = x + bias;\nIf x > lambd, y = x - bias; Otherwise, y = 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shrink',\n inputs=['x'],\n outputs=['y'],\n lambd=1.5,\n)\nX = np.arange(-2.0, 2.1, dtype=np.float32)\nY = np.array([-2, 0, 0, 0, 2], dtype=np.float32)\nexpect(node, inputs=[X], outputs=[Y],\n name='test_shrink_hard')","summary":"hard_shrink"},{"code":"node = onnx.helper.make_node(\n 'Shrink',\n inputs=['x'],\n outputs=['y'],\n lambd=1.5,\n bias=1.5,\n)\nX = np.arange(-2.0, 2.1, dtype=np.float32)\nY = np.array([-0.5, 0, 0, 0, 0.5], dtype=np.float32)\nexpect(node, inputs=[X], outputs=[Y],\n name='test_shrink_soft')","summary":"soft_shrink"}],"inputs":[{"description":"The input data as Tensor.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sign","schema":{"description":"Calculate the sign of the given input tensor element-wise.\nIf input > 0, output 1. if input < 0, output -1. if input == 0, output 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array(range(-5, 6)).astype(np.float32)\ny = np.sign(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sign')","summary":"sign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sign of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Sign","schema":{"description":"Calculate the sign of the given input tensor element-wise.\nIf input > 0, output 1. if input < 0, output -1. if input == 0, output 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array(range(-5, 6)).astype(np.float32)\ny = np.sign(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sign')","summary":"sign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sign of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Sin","schema":{"description":"Calculates the sine of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sin',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.sin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sin_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.sin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sin')","summary":"sin"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sinh","schema":{"description":"Calculates the hyperbolic sine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sinh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.sinh(x) # expected output [-1.17520118, 0., 1.17520118]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sinh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.sinh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sinh')","summary":"sinh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic sine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Size","schema":{"description":"Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Size',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array(6).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.size).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size')","summary":"size"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Total number of elements of the input tensor","name":"size","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor, which should be a scalar though.","type_param_str":"T1"}]}},{"name":"Size","schema":{"description":"Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Size',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array(6).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.size).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size')","summary":"size"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Total number of elements of the input tensor","name":"size","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor, which should be a scalar though.","type_param_str":"T1"}]}},{"name":"Slice","schema":{"attributes":[{"description":"Axes that `starts` and `ends` apply to. It's optional. If not present, will be treated as [0, 1, ..., len(`starts`) - 1].","name":"axes","required":false,"type":"int64[]"},{"description":"Ending indices (exclusive) of corresponding axis in axes`","name":"ends","required":true,"type":"int64[]"},{"description":"Starting indices of corresponding axis in `axes`","name":"starts","required":true,"type":"int64[]"}],"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `axes`, `starts` and `ends` attributes to specify the start and end\ndimension for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represent number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX`.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n result = [\n [5, 6, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represent number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX`.\nIf a negative value is passed for step, it represents slicing backward.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to.","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Default to 1. ","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represents number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX` \nwhen sclicing forward and 'INT_MIN' when slicing backward.\nIf a negative value is passed for step, it represents slicing backward. \nHowever step value cannot be 0.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Negative value means slicing backward. 'steps' cannot be 0. Defaults to 1.","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represents number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX` \nwhen sclicing forward and 'INT_MIN' when slicing backward.\nIf a negative value is passed for step, it represents slicing backward. \nHowever step value cannot be 0.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Negative value means slicing backward. 'steps' cannot be 0. Defaults to 1.","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SoftmaxCrossEntropyLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean(default). 'none': no reduction will be applied, 'sum': the output will be summed. 'mean': the sum of the output will be divided by the number of elements in the output.","name":"reduction","required":false,"type":"string"}],"description":"Loss function that measures the softmax cross entropy\nbetween 'scores' and 'labels'.\nThis operator first computes a loss tensor whose shape is identical to the labels input.\nIf the input is 2-D with shape (N, C), the loss tensor may be a N-element vector L = (l_1, l_2, ..., l_N).\nIf the input is N-D tensor with shape (N, C, D1, D2, ..., Dk),\nthe loss tensor L may have (N, D1, D2, ..., Dk) as its shape and L[i,][j_1][j_2]...[j_k] denotes a scalar element in L.\nAfter L is available, this operator can optionally do a reduction operator.\n\nshape(scores): (N, C) where C is the number of classes, or (N, C, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\nshape(labels): (N) where each value is 0 <= labels[i] <= C-1, or (N, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\n\nThe loss for one sample, l_i, can caculated as follows:\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk], where i is the index of classes.\nor\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk] * weights[c], if 'weights' is provided.\n\nloss is zero for the case when label-value equals ignore_index.\n l[i][d1][d2]...[dk] = 0, when labels[n][d1][d2]...[dk] = ignore_index\n\nwhere:\n p = Softmax(scores)\n y = Log(p)\n c = labels[i][d1][d2]...[dk]\n\nFinally, L is optionally reduced:\nIf reduction = 'none', the output is L with shape (N, D1, D2, ..., Dk).\nIf reduction = 'sum', the output is scalar: Sum(L).\nIf reduction = 'mean', the output is scalar: ReduceMean(L), or if weight is provided: ReduceSum(L) / ReduceSum(W),\nwhere tensor W is of shape (N, D1, D2, ..., Dk) and W[n][d1][d2]...[dk] = weights[labels[i][d1][d2]...[dk]].\n","domain":"ai.onnx","examples":[{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1_mean_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1_mean_weight_negative_ii_log_prob"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_none_no_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii_log_prob"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_sum_weight_high_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii_log_prob"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_mean_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_none_no_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean')","summary":"softmaxcrossentropy_mean"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, y)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[sce], name='test_sce_mean_3d')","summary":"softmaxcrossentropy_mean_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, y, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[loss, log_prob], name='test_sce_mean_3d_log_prob')","summary":"softmaxcrossentropy_mean_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_log_prob')","summary":"softmaxcrossentropy_mean_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii')","summary":"softmaxcrossentropy_mean_no_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_3d')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_4d')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight')","summary":"softmaxcrossentropy_mean_weights"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii')","summary":"softmaxcrossentropy_mean_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_3d')","summary":"softmaxcrossentropy_mean_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_4d')","summary":"softmaxcrossentropy_mean_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_log_prob')","summary":"softmaxcrossentropy_mean_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_none')","summary":"softmaxcrossentropy_none"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_none_log_prob')","summary":"softmaxcrossentropy_none_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_none_weights')","summary":"softmaxcrossentropy_none_weights"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_none_weights_log_prob')","summary":"softmaxcrossentropy_none_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='sum')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_sum')","summary":"softmaxcrossentropy_sum"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='sum', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_sum_log_prob')","summary":"softmaxcrossentropy_sum_log_prob"}],"inputs":[{"description":"The predicted outputs with shape [batch_size, class_size], or [batch_size, class_size, D1, D2 , ..., Dk], where K is the number of dimensions.","name":"scores","type":"T"},{"description":"The ground truth output tensor, with shape [batch_size], or [batch_size, D1, D2, ..., Dk], where K is the number of dimensions. Labels element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the label values should either be in the range [0, C) or have the value ignore_index.","name":"labels","type":"Tind"},{"description":"A manual rescaling weight given to each class. If given, it has to be a 1D Tensor assigning weight to each of the classes. Otherwise, it is treated as if having all ones.","name":"weights","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":2,"min_input":2,"min_output":1,"outputs":[{"description":"Weighted loss float Tensor. If reduction is 'none', this has the shape of [batch_size], or [batch_size, D1, D2, ..., Dk] in case of K-dimensional loss. Otherwise, it is a scalar.","name":"output","type":"T"},{"description":"Log probability tensor. If the output of softmax is prob, its value is log(prob).","name":"log_prob","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"SoftmaxCrossEntropyLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean(default). 'none': no reduction will be applied, 'sum': the output will be summed. 'mean': the sum of the output will be divided by the number of elements in the output.","name":"reduction","required":false,"type":"string"}],"description":"Loss function that measures the softmax cross entropy\nbetween 'scores' and 'labels'.\nThis operator first computes a loss tensor whose shape is identical to the labels input.\nIf the input is 2-D with shape (N, C), the loss tensor may be a N-element vector L = (l_1, l_2, ..., l_N).\nIf the input is N-D tensor with shape (N, C, D1, D2, ..., Dk),\nthe loss tensor L may have (N, D1, D2, ..., Dk) as its shape and L[i,][j_1][j_2]...[j_k] denotes a scalar element in L.\nAfter L is available, this operator can optionally do a reduction operator.\n\nshape(scores): (N, C) where C is the number of classes, or (N, C, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\nshape(labels): (N) where each value is 0 <= labels[i] <= C-1, or (N, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\n\nThe loss for one sample, l_i, can caculated as follows:\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk], where i is the index of classes.\nor\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk] * weights[c], if 'weights' is provided.\n\nloss is zero for the case when label-value equals ignore_index.\n l[i][d1][d2]...[dk] = 0, when labels[n][d1][d2]...[dk] = ignore_index\n\nwhere:\n p = Softmax(scores)\n y = Log(p)\n c = labels[i][d1][d2]...[dk]\n\nFinally, L is optionally reduced:\nIf reduction = 'none', the output is L with shape (N, D1, D2, ..., Dk).\nIf reduction = 'sum', the output is scalar: Sum(L).\nIf reduction = 'mean', the output is scalar: ReduceMean(L), or if weight is provided: ReduceSum(L) / ReduceSum(W),\nwhere tensor W is of shape (N, D1, D2, ..., Dk) and W[n][d1][d2]...[dk] = weights[labels[i][d1][d2]...[dk]].\n","domain":"ai.onnx","examples":[{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1_mean_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1_mean_weight_negative_ii_log_prob"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_none_no_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii_log_prob"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_sum_weight_high_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii_log_prob"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_mean_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_none_no_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean')","summary":"softmaxcrossentropy_mean"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, y)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[sce], name='test_sce_mean_3d')","summary":"softmaxcrossentropy_mean_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, y, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[loss, log_prob], name='test_sce_mean_3d_log_prob')","summary":"softmaxcrossentropy_mean_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_log_prob')","summary":"softmaxcrossentropy_mean_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii')","summary":"softmaxcrossentropy_mean_no_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_3d')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_4d')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight')","summary":"softmaxcrossentropy_mean_weights"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii')","summary":"softmaxcrossentropy_mean_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_3d')","summary":"softmaxcrossentropy_mean_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_4d')","summary":"softmaxcrossentropy_mean_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_log_prob')","summary":"softmaxcrossentropy_mean_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_none')","summary":"softmaxcrossentropy_none"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_none_log_prob')","summary":"softmaxcrossentropy_none_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_none_weights')","summary":"softmaxcrossentropy_none_weights"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_none_weights_log_prob')","summary":"softmaxcrossentropy_none_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='sum')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_sum')","summary":"softmaxcrossentropy_sum"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='sum', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_sum_log_prob')","summary":"softmaxcrossentropy_sum_log_prob"}],"inputs":[{"description":"The predicted outputs with shape [batch_size, class_size], or [batch_size, class_size, D1, D2 , ..., Dk], where K is the number of dimensions.","name":"scores","type":"T"},{"description":"The ground truth output tensor, with shape [batch_size], or [batch_size, D1, D2, ..., Dk], where K is the number of dimensions. Labels element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the label values should either be in the range [0, C) or have the value ignore_index.","name":"labels","type":"Tind"},{"description":"A manual rescaling weight given to each class. If given, it has to be a 1D Tensor assigning weight to each of the classes. Otherwise, it is treated as if having all ones.","name":"weights","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":2,"min_input":2,"min_output":1,"outputs":[{"description":"Weighted loss float Tensor. If reduction is 'none', this has the shape of [batch_size], or [batch_size, D1, D2, ..., Dk] in case of K-dimensional loss. Otherwise, it is a scalar.","name":"output","type":"T"},{"description":"Log probability tensor. If the output of softmax is prob, its value is log(prob).","name":"log_prob","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"Softplus","schema":{"category":"Activation","description":"Softplus takes one input data (Tensor) and produces one output data\n(Tensor) where the softplus function, y = ln(exp(x) + 1), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softplus',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.log(np.exp(x) + 1) # expected output [0.31326166, 0.69314718, 1.31326163]\nexpect(node, inputs=[x], outputs=[y],\n name='test_softplus_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.log(np.exp(x) + 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softplus')","summary":"softplus"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softsign","schema":{"category":"Activation","description":"Calculates the softsign (x/(1+|x|)) of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softsign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-0.5, 0, 0.5]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softsign_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x / (1 + np.abs(x))\nexpect(node, inputs=[x], outputs=[y],\n name='test_softsign')","summary":"softsign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The softsign (x/(1+|x|)) values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SpaceToDepth","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"SpaceToDepth rearranges blocks of spatial data into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the height and width dimensions\nare moved to the depth dimension.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C * blocksize * blocksize, H/blocksize, W/blocksize].","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"SpaceToDepth","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"SpaceToDepth rearranges blocks of spatial data into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the height and width dimensions\nare moved to the depth dimension.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C * blocksize * blocksize, H/blocksize, W/blocksize].","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on","name":"axis","required":false,"type":"int64"},{"description":"length of each output","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. The lengths of the split can be specified using argument 'axis' or\noptional second input blob to the operator. Otherwise, the tensor is split\nto equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"},{"description":"Optional list of output lengths (see also arg 'split')","name":"split","option":"optional","type":"T"}],"inputs_range":"1 - 2","max_input":2,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs...","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. ","name":"axis","required":false,"type":"int64"},{"description":"length of each output","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"description":"length of each output. Values should be >= 0.","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"description":"length of each output. Values should be >= 0.","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"SplitToSequence","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1].","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the split dimension or not. Default 1, which means we keep split dimension. If input 'split' is specified, this attribute is ignored.","name":"keepdims","required":false,"type":"int64"}],"description":"Split a tensor into a sequence of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\n'split' must contain only positive numbers.\n'split' is either a scalar (tensor of empty shape), or a 1-D tensor.\nIf 'split' is a scalar, then 'input' will be split into equally sized chunks(if possible).\nLast chunk will be smaller if the 'input' size along the given axis 'axis' is not divisible\nby 'split'.\nOtherwise, the tensor is split into 'size(split)' chunks, with lengths of the parts on 'axis'\nspecified in 'split'. In this scenario, the sum of entries in 'split' must be equal to the\ndimension size of input tensor on 'axis'.\n","domain":"ai.onnx","inputs":[{"description":"The tensor to split","name":"input","type":"T"},{"description":"Length of each output. It can be either a scalar(tensor of empty shape), or a 1-D tensor. All values must be >= 0. ","name":"split","option":"optional","type":"I"}],"inputs_range":"1 - 2","max_input":2,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming a sequence of tensors after splitting","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain split size to integral tensor.","type_param_str":"I"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to all tensor types.","type_param_str":"S"}]}},{"name":"Sqrt","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sqrt","schema":{"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sqrt","schema":{"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of non-negative integers, indicate the dimensions to squeeze.","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to squeeze. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to squeeze. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"StringNormalizer","schema":{"attributes":[{"default":"NONE","description":"string enum that cases output to be lowercased/uppercases/unchanged. Valid values are \"LOWER\", \"UPPER\", \"NONE\". Default is \"NONE\"","name":"case_change_action","required":false,"type":"string"},{"description":"Boolean. Whether the identification of stop words in X is case-sensitive. Default is false","name":"is_case_sensitive","required":false,"type":"int64"},{"description":"Environment dependent string that denotes the locale according to which output strings needs to be upper/lowercased.Default en_US or platform specific equivalent as decided by the implementation.","name":"locale","required":false,"type":"string"},{"description":"List of stop words. If not set, no word would be removed from X.","name":"stopwords","required":false,"type":"string[]"}],"description":"StringNormalization performs string operations for basic cleaning.\nThis operator has only one input (denoted by X) and only one output\n(denoted by Y). This operator first examines the elements in the X,\nand removes elements specified in \"stopwords\" attribute.\nAfter removing stop words, the intermediate result can be further lowercased,\nuppercased, or just returned depending the \"case_change_action\" attribute.\nThis operator only accepts [C]- and [1, C]-tensor.\nIf all elements in X are dropped, the output will be the empty value of string tensor with shape [1]\nif input shape is [C] and shape [1, 1] if input shape is [1, C].\n","domain":"ai.onnx","examples":[{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'tuesday', u'wednesday', u'thursday']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='LOWER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_lower')","summary":"monday_casesensintive_lower"},{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'tuesday', u'wednesday', u'thursday']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_nochangecase')","summary":"monday_casesensintive_nochangecase"},{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'TUESDAY', u'WEDNESDAY', u'THURSDAY']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_upper')","summary":"monday_casesensintive_upper"},{"code":"input = np.array([u'monday', u'monday']).astype(np.object)\noutput = np.array([u'']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_empty_output')","summary":"monday_empty_output"},{"code":"input = np.array([u'Monday', u'tuesday', u'wednesday', u'Monday', u'tuesday', u'wednesday']).astype(np.object).reshape([1, 6])\n\n# It does upper case cecedille, accented E\n# and german umlaut but fails\n# with german eszett\noutput = np.array([u'TUESDAY', u'WEDNESDAY', u'TUESDAY', u'WEDNESDAY']).astype(np.object).reshape([1, 4])\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_insensintive_upper_twodim')","summary":"monday_insensintive_upper_twodim"},{"code":"input = np.array([u'monday', u'tuesday']).astype(np.object)\noutput = input\n\n# No stopwords. This is a NOOP\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n is_case_sensitive=1,\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_nostopwords_nochangecase')","summary":"nostopwords_nochangecase"}],"inputs":[{"description":"UTF-8 strings to normalize","name":"X","type":"tensor(string)"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"UTF-8 Normalized strings","name":"Y","type":"tensor(string)"}],"since_version":10,"support_level":"common"}},{"name":"Sub","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"description":"Performs element-wise binary subtraction (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"description":"Performs element-wise binary subtraction (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise sum of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for Sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for Sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"sum","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"sum","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tan","schema":{"description":"Calculates the tangent of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tan',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tan_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tan')","summary":"tan"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The tangent of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"1-D input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"TfIdfVectorizer","schema":{"attributes":[{"description":"Maximum n-gram length. If this value is 3, 3-grams will be used to generate the output.","name":"max_gram_length","required":true,"type":"int64"},{"description":"Maximum number of items (integers/strings) to be skipped when constructing an n-gram from X. If max_skip_count=1, min_gram_length=2, max_gram_length=3, this operator may generate 2-grams with skip_count=0 and skip_count=1, and 3-grams with skip_count=0 and skip_count=1","name":"max_skip_count","required":true,"type":"int64"},{"description":"Minimum n-gram length. If this value is 2 and max_gram_length is 3, output may contain counts of 2-grams and 3-grams.","name":"min_gram_length","required":true,"type":"int64"},{"description":"The weighting criteria. It can be one of \"TF\" (term frequency), \"IDF\" (inverse document frequency), and \"TFIDF\" (the combination of TF and IDF)","name":"mode","required":true,"type":"string"},{"description":"The starting indexes of 1-grams, 2-grams, and so on in pool. It is useful when determining the boundary between two consecutive collections of n-grams. For example, if ngram_counts is [0, 17, 36], the first index (zero-based) of 1-gram/2-gram/3-gram in pool are 0/17/36. This format is essentially identical to CSR (or CSC) sparse matrix format, and we choose to use this due to its popularity.","name":"ngram_counts","required":true,"type":"int64[]"},{"description":"list of int64s (type: AttributeProto::INTS). This list is parallel to the specified 'pool_*' attribute. The i-th element in ngram_indexes indicate the coordinate of the i-th n-gram in the output tensor.","name":"ngram_indexes","required":true,"type":"int64[]"},{"description":"List of int64 n-grams learned from the training set. Either this or pool_strings attributes must be present but not both. It's an 1-D tensor starting with the collections of all 1-grams and ending with the collections of n-grams. The i-th element in pool stores the n-gram that should be mapped to coordinate ngram_indexes[i] in the output vector.","name":"pool_int64s","required":false,"type":"int64[]"},{"description":"List of strings n-grams learned from the training set. Either this or pool_int64s attributes must be present but not both. It's an 1-D tensor starting with the collections of all 1-grams and ending with the collections of n-grams. The i-th element in pool stores the n-gram that should be mapped to coordinate ngram_indexes[i] in the output vector.","name":"pool_strings","required":false,"type":"string[]"},{"description":"list of floats. This attribute stores the weight of each n-gram in pool. The i-th element in weights is the weight of the i-th n-gram in pool. Its length equals to the size of ngram_indexes. By default, weights is an all-one tensor.This attribute is used when mode is \"IDF\" or \"TFIDF\" to scale the associated word counts.","name":"weights","required":false,"type":"float32[]"}],"description":"This transform extracts n-grams from the input sequence and save them as a vector. Input can\nbe either a 1-D or 2-D tensor. For 1-D input, output is the n-gram representation of that input.\nFor 2-D input, the output is also a 2-D tensor whose i-th row is the n-gram representation of the i-th input row.\nMore specifically, if input shape is [C], the corresponding output shape would be [max(ngram_indexes) + 1].\nIf input shape is [N, C], this operator produces a [N, max(ngram_indexes) + 1]-tensor.\n\nIn contrast to standard n-gram extraction, here, the indexes of extracting an n-gram from the original\nsequence are not necessarily consecutive numbers. The discontinuity between indexes are controlled by the number of skips.\nIf the number of skips is 2, we should skip two tokens when scanning through the original sequence.\nLet's consider an example. Assume that input sequence is [94, 17, 36, 12, 28] and the number of skips is 2.\nThe associated 2-grams are [94, 12] and [17, 28] respectively indexed by [0, 3] and [1, 4].\nIf the number of skips becomes 0, the 2-grams generated are [94, 17], [17, 36], [36, 12], [12, 28]\nindexed by [0, 1], [1, 2], [2, 3], [3, 4], respectively.\n\nThe output vector (denoted by Y) stores the count of each n-gram;\nY[ngram_indexes[i]] indicates the times that the i-th n-gram is found. The attribute ngram_indexes is used to determine the mapping\nbetween index i and the corresponding n-gram's output coordinate. If pool_int64s is [94, 17, 17, 36], ngram_indexes is [1, 0],\nngram_counts=[0, 0], then the Y[0] (first element in Y) and Y[1] (second element in Y) are the counts of [17, 36] and [94, 17],\nrespectively. An n-gram which cannot be found in pool_strings/pool_int64s should be ignored and has no effect on the output.\nNote that we may consider all skips up to S when generating the n-grams.\n\nThe examples used above are true if mode is \"TF\". If mode is \"IDF\", all the counts larger than 1 would be truncated to 1 and\nthe i-th element in weights would be used to scale (by multiplication) the count of the i-th n-gram in pool. If mode is \"TFIDF\",\nthis operator first computes the counts of all n-grams and then scale them by the associated values in the weights attribute.\n\nOnly one of pool_strings and pool_int64s can be set. If pool_int64s is set, the input should be an integer tensor.\nIf pool_strings is set, the input must be a string tensor.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip0')","summary":"tf_batch_onlybigrams_skip0"},{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 1., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip5')","summary":"tf_batch_onlybigrams_skip5"},{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 3., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 1., 1., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=1,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_uniandbigrams_skip5')","summary":"tf_batch_uniandbigrams_skip5"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 0., 0., 0., 1., 1., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_only_bigrams_skip0')","summary":"tf_only_bigrams_skip0"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([1., 1., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 0]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2]).astype(np.int64)\npool_int64s = np.array([ # unigrams none\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_levelempty')","summary":"tf_onlybigrams_levelempty"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 0., 0., 0., 1., 3., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_skip5')","summary":"tf_onlybigrams_skip5"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 3., 1., 0., 1., 3., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=1,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_uniandbigrams_skip5')","summary":"tf_uniandbigrams_skip5"}],"inputs":[{"description":"Input for n-gram extraction","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Ngram results","name":"Y","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int32)","tensor(int64)"],"description":"Input is ether string UTF-8 or int32/int64","type_param_str":"T"},{"allowed_type_strs":["tensor(float)"],"description":"1-D tensor of floats","type_param_str":"T1"}]}},{"name":"ThresholdedRelu","schema":{"attributes":[{"default":1,"description":"Threshold value","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"ThresholdedRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = x for x > alpha, y = 0 otherwise,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'ThresholdedRelu',\n inputs=['x'],\n outputs=['y']\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, default_alpha, np.inf)\ny[y == default_alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu_default')","summary":"default"},{"code":"alpha = 2.0\nnode = onnx.helper.make_node(\n 'ThresholdedRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha\n)\n\nx = np.array([-1.5, 0., 1.2, 2.0, 2.2]).astype(np.float32)\ny = np.clip(x, alpha, np.inf) # expected output [0., 0., 0., 0., 2.2]\ny[y == alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, alpha, np.inf)\ny[y == alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu')","summary":"thresholdedrelu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Repeat the elements of a tensor along an axis.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"Number of repeated copies to make of the input tensor.","name":"tiles","type":"T"},{"description":"Axis along which to repeat.","name":"axis","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of same shape and type as input.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain tiles and axis's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Constructs a tensor by tiling a given tensor.\nThis is the same as function `tile` in Numpy, but no broadcast.\nFor example A = [[1, 2], [3, 4]], B = [1, 2], tile(A, B) = [[1, 2, 1, 2], [3, 4, 3, 4]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"1D int64 tensor of the same length as input's dimension number, includes numbers of repeated copies along input's dimensions.","name":"repeats","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same dimension and type as tensor input. output_dim[i] = input_dim[i] * repeats[i]","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain repeat's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Constructs a tensor by tiling a given tensor.\nThis is the same as function `tile` in Numpy, but no broadcast.\nFor example A = [[1, 2], [3, 4]], B = [1, 2], tile(A, B) = [[1, 2, 1, 2], [3, 4, 3, 4]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"1D int64 tensor of the same length as input's dimension number, includes numbers of repeated copies along input's dimensions.","name":"repeats","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same dimension and type as tensor input. output_dim[i] = input_dim[i] * repeats[i]","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain repeat's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort.","name":"axis","required":false,"type":"int64"},{"description":"Number of top elements to retrieve","name":"k","required":true,"type":"int64"}],"description":"Retrieve the top-K elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort.","name":"axis","required":false,"type":"int64"}],"description":"Retrieve the top-K elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\n \nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"},{"description":"A 1-D tensor containing a single positive value corresponding to the number of top elements to retrieve","name":"K","type":"tensor(int64)"}],"max_input":2,"max_output":2,"min_input":2,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Whether to return the top-K largest or smallest elements.","name":"largest","required":false,"type":"int64"},{"default":1,"description":"Whether to return the elements in sorted order.","name":"sorted","required":false,"type":"int64"}],"description":"Retrieve the top-K largest or smallest elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\n\nIf \"largest\" is 1 (the default value) then the k largest elements are returned.\nIf \"sorted\" is 1 (the default value) then the resulting k elements will be sorted.\nIf \"sorted\" is 0, order of returned 'Values' and 'Indices' are undefined.\n\nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"},{"description":"A 1-D tensor containing a single positive value corresponding to the number of top elements to retrieve","name":"K","type":"tensor(int64)"}],"max_input":2,"max_output":2,"min_input":2,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"Transpose","schema":{"attributes":[{"description":"A list of integers. By default, reverse the dimensions, otherwise permute the axes according to the values given.","name":"perm","required":false,"type":"int64[]"}],"category":"Transform","description":"Transpose the input tensor similar to numpy.transpose. For example, when\nperm=(1, 0, 2), given an input tensor of shape (1, 2, 3), the output shape\nwill be (2, 1, 3).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\npermutations = list(itertools.permutations(np.arange(len(shape))))\n\nfor i in range(len(permutations)):\n node = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed'],\n perm=permutations[i]\n )\n transposed = np.transpose(data, permutations[i])\n expect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_all_permutations_' + str(i))","summary":"all_permutations"},{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed']\n)\n\ntransposed = np.transpose(data)\nexpect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_default')","summary":"default"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Transposed output.","name":"transposed","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Transpose","schema":{"attributes":[{"description":"A list of integers. By default, reverse the dimensions, otherwise permute the axes according to the values given.","name":"perm","required":false,"type":"int64[]"}],"category":"Transform","description":"Transpose the input tensor similar to numpy.transpose. For example, when\nperm=(1, 0, 2), given an input tensor of shape (1, 2, 3), the output shape\nwill be (2, 1, 3).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\npermutations = list(itertools.permutations(np.arange(len(shape))))\n\nfor i in range(len(permutations)):\n node = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed'],\n perm=permutations[i]\n )\n transposed = np.transpose(data, permutations[i])\n expect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_all_permutations_' + str(i))","summary":"all_permutations"},{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed']\n)\n\ntransposed = np.transpose(data)\nexpect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_default')","summary":"default"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Transposed output.","name":"transposed","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"TreeEnsembleClassifier","schema":{"attributes":[{"description":"Base values for classification, added to final class score; the size must be the same as the classes or can be left unassigned (assumed 0)","name":"base_values","required":false,"type":"float32[]"},{"description":"The index of the class list that each weight is for.","name":"class_ids","required":false,"type":"int64[]"},{"description":"node id that this weight is for.","name":"class_nodeids","required":false,"type":"int64[]"},{"description":"The id of the tree that this node is in.","name":"class_treeids","required":false,"type":"int64[]"},{"description":"The weight for the class in class_id.","name":"class_weights","required":false,"type":"float32[]"},{"description":"Class labels if using integer labels.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_int64s","required":false,"type":"int64[]"},{"description":"Class labels if using string labels.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"Child node if expression is false.","name":"nodes_falsenodeids","required":false,"type":"int64[]"},{"description":"Feature id for each node.","name":"nodes_featureids","required":false,"type":"int64[]"},{"description":"Popularity of each node, used for performance and may be omitted.","name":"nodes_hitrates","required":false,"type":"float32[]"},{"description":"For each node, define what to do in the presence of a missing value: if a value is missing (NaN), use the 'true' or 'false' branch based on the value in this array.
This attribute may be left undefined, and the defalt value is false (0) for all nodes.","name":"nodes_missing_value_tracks_true","required":false,"type":"int64[]"},{"description":"The node kind, that is, the comparison to make at the node. There is no comparison to make at a leaf node.
One of 'BRANCH_LEQ', 'BRANCH_LT', 'BRANCH_GTE', 'BRANCH_GT', 'BRANCH_EQ', 'BRANCH_NEQ', 'LEAF'","name":"nodes_modes","required":false,"type":"string[]"},{"description":"Node id for each node. Ids may restart at zero for each tree, but it not required to.","name":"nodes_nodeids","required":false,"type":"int64[]"},{"description":"Tree id for each node.","name":"nodes_treeids","required":false,"type":"int64[]"},{"description":"Child node if expression is true.","name":"nodes_truenodeids","required":false,"type":"int64[]"},{"description":"Thresholds to do the splitting on for each node.","name":"nodes_values","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the score.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT.'","name":"post_transform","required":false,"type":"string"}],"description":"Tree Ensemble classifier. Returns the top class for each of N inputs.
\n The attributes named 'nodes_X' form a sequence of tuples, associated by \n index into the sequences, which must all be of equal length. These tuples\n define the nodes.
\n Similarly, all fields prefixed with 'class_' are tuples of votes at the leaves.\n A leaf may have multiple votes, where each vote is weighted by\n the associated class_weights index.
\n One and only one of classlabels_strings or classlabels_int64s\n will be defined. The class_ids are indices into this list.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input of shape [N,F]","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"N, Top class for each point","name":"Y","type":"T2"},{"description":"The class score for each class, for each point, a tensor of shape [N,E].","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, depending on which of the the classlabels_* attributes is used.","type_param_str":"T2"}]}},{"name":"TreeEnsembleRegressor","schema":{"attributes":[{"default":"SUM","description":"Defines how to aggregate leaf values within a target.
One of 'AVERAGE,' 'SUM,' 'MIN,' 'MAX.'","name":"aggregate_function","required":false,"type":"string"},{"description":"Base values for classification, added to final class score; the size must be the same as the classes or can be left unassigned (assumed 0)","name":"base_values","required":false,"type":"float32[]"},{"description":"The total number of targets.","name":"n_targets","required":false,"type":"int64"},{"description":"Child node if expression is false","name":"nodes_falsenodeids","required":false,"type":"int64[]"},{"description":"Feature id for each node.","name":"nodes_featureids","required":false,"type":"int64[]"},{"description":"Popularity of each node, used for performance and may be omitted.","name":"nodes_hitrates","required":false,"type":"float32[]"},{"description":"For each node, define what to do in the presence of a NaN: use the 'true' (if the attribute value is 1) or 'false' (if the attribute value is 0) branch based on the value in this array.
This attribute may be left undefined and the defalt value is false (0) for all nodes.","name":"nodes_missing_value_tracks_true","required":false,"type":"int64[]"},{"description":"The node kind, that is, the comparison to make at the node. There is no comparison to make at a leaf node.
One of 'BRANCH_LEQ', 'BRANCH_LT', 'BRANCH_GTE', 'BRANCH_GT', 'BRANCH_EQ', 'BRANCH_NEQ', 'LEAF'","name":"nodes_modes","required":false,"type":"string[]"},{"description":"Node id for each node. Node ids must restart at zero for each tree and increase sequentially.","name":"nodes_nodeids","required":false,"type":"int64[]"},{"description":"Tree id for each node.","name":"nodes_treeids","required":false,"type":"int64[]"},{"description":"Child node if expression is true","name":"nodes_truenodeids","required":false,"type":"int64[]"},{"description":"Thresholds to do the splitting on for each node.","name":"nodes_values","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the score.
One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"description":"The index of the target that each weight is for","name":"target_ids","required":false,"type":"int64[]"},{"description":"The node id of each weight","name":"target_nodeids","required":false,"type":"int64[]"},{"description":"The id of the tree that each node is in.","name":"target_treeids","required":false,"type":"int64[]"},{"description":"The weight for each target","name":"target_weights","required":false,"type":"float32[]"}],"description":"Tree Ensemble regressor. Returns the regressed values for each input in N.
\n All args with nodes_ are fields of a tuple of tree nodes, and\n it is assumed they are the same length, and an index i will decode the\n tuple across these inputs. Each node id can appear only once\n for each tree id.
\n All fields prefixed with target_ are tuples of votes at the leaves.
\n A leaf may have multiple votes, where each vote is weighted by\n the associated target_weights index.
\n All trees must have their node ids start at 0 and increment by 1.
\n Mode enum is BRANCH_LEQ, BRANCH_LT, BRANCH_GTE, BRANCH_GT, BRANCH_EQ, BRANCH_NEQ, LEAF\n","domain":"ai.onnx.ml","inputs":[{"description":"Input of shape [N,F]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"N classes","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Unique","schema":{"attributes":[{"description":"(Optional) The dimension to apply unique. If not specified, the unique elements of the flattened input are returned. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"(Optional) Whether to sort the unique elements in ascending order before returning as output. Must be one of 0, or 1 (default).","name":"sorted","required":false,"type":"int64"}],"description":"Find the unique elements of a tensor. When an optional attribute 'axis' is provided, unique subtensors sliced along the 'axis' are returned. \nOtherwise the input tensor is flattened and unique values of the flattened tensor are returned. \n\nThis operator returns the unique values or sliced unique subtensors of the input tensor and three optional outputs. \nThe first output tensor 'Y' contains all unique values or subtensors of the input. \nThe second optional output tensor 'indices' contains indices of 'Y' elements' first occurance in 'X'.. \nThe third optional output tensor 'inverse_indices' contains, for elements of 'X', its corresponding indices in 'Y'. \". \nThe fourth optional output tensor 'counts' contains the count of each element of 'Y' in the input. \n\nOutputs are either sorted in ascending order or optionally in the order of the first occurrence of the values in the input. \n\nhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html\n\nExample 1:\n input_X = [2, 1, 1, 3, 4, 3]\n attribute_sorted = 0\n attribute_axis = None\n output_Y = [2, 1, 3, 4]\n output_indices = [0, 1, 3, 4]\n output_inverse_indices = [0, 1, 1, 2, 3, 2]\n output_counts = [1, 2, 2, 1]\n\nExample 2:\n input_X = [[1, 3], [2, 3]]\n attribute_sorted = 1\n attribute_axis = None\n output_Y = [1, 2, 3]\n output_indices = [0, 2, 1]\n output_inverse_indices = [0, 2, 1, 2]\n output_counts = [1, 1, 2]\n\nExample 3:\n input_X = [[1, 0, 0], [1, 0, 0], [2, 3, 4]]\n attribute_sorted = 1\n attribute_axis = 0\n output_Y = [[1, 0, 0], [2, 3, 4]]\n output_indices = [0, 2]\n output_inverse_indices = [0, 0, 1]\n output_counts = [2, 1]\n\nExample 4:\n input_x = [[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], \n [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]]\n attribute_sorted = 1\n attribute_axis = 1\n\n intermediate data are presented below for better understanding: \n \n there are 4 subtensors sliced along axis 1 of input_x (shape = (2, 4, 2)):\n A: [[1, 1], [1, 1]], \n [[0, 1], [0, 1]], \n [[2, 1], [2, 1]], \n [[0, 1], [0, 1]].\n \n there are 3 unique subtensors: \n [[1, 1], [1, 1]], \n [[0, 1], [0, 1]], \n [[2, 1], [2, 1]].\n \n sorted unique subtensors:\n B: [[0, 1], [0, 1]], \n [[1, 1], [1, 1]], \n [[2, 1], [2, 1]].\n \n output_Y is constructed from B:\n [[[0. 1.], [1. 1.], [2. 1.]], \n [[0. 1.], [1. 1.], [2. 1.]]]\n\n output_indices is to map from B to A:\n [1, 0, 2]\n \n output_inverse_indices is to map from A to B:\n [1, 0, 2, 0]\n\n output_counts = [2 1 1]\n","domain":"ai.onnx","examples":[{"code":"node_not_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=0\n)\n# numpy unique does not retain original order (it sorts the output unique values)\n# https://github.com/numpy/numpy/issues/8621\n# we need to recover unsorted output and indices\nx = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True)\n\n# prepare index mapping from sorted to unsorted\nargsorted_indices = np.argsort(indices)\ninverse_indices_map = {i: si for i, si in zip(argsorted_indices, np.arange(len(argsorted_indices)))}\n\nindices = indices[argsorted_indices]\ny = np.take(x, indices, axis=0)\ninverse_indices = np.asarray([inverse_indices_map[i] for i in inverse_indices], dtype=np.int64)\ncounts = counts[argsorted_indices]\n# print(y)\n# [2.0, 1.0, 3.0, 4.0]\n# print(indices)\n# [0 1 3 4]\n# print(inverse_indices)\n# [0, 1, 1, 2, 3, 2]\n# print(counts)\n# [1, 2, 2, 1]\n\nexpect(node_not_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_not_sorted_without_axis')","summary":"not_sorted_without_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=0\n)\n\nx = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=0)\n# print(y)\n# [[1. 0. 0.]\n# [2. 3. 4.]]\n# print(indices)\n# [0 2]\n# print(inverse_indices)\n# [0 0 1]\n# print(counts)\n# [2 1]\n\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis')","summary":"sorted_with_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=1\n)\n\nx = np.array([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]],\n [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=1)\n# print(y)\n# [[[0. 1.]\n# [1. 1.]\n# [2. 1.]]\n# [[0. 1.]\n# [1. 1.]\n# [2. 1.]]]\n# print(indices)\n# [1 0 2]\n# print(inverse_indices)\n# [1 0 2 0]\n# print(counts)\n# [2 1 1]\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis_3d')","summary":"sorted_with_axis_3d"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=-1\n)\n\nx = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 3]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=-1)\n# print(y)\n# [[0. 1.]\n# [0. 1.]\n# [3. 2.]]\n# print(indices)\n# [1 0]\n# print(inverse_indices)\n# [1 0 0]\n# print(counts)\n# [2 1]\n\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_negative_axis')","summary":"sorted_with_negative_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts']\n)\n\nx = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True)\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_without_axis')","summary":"sorted_without_axis"}],"inputs":[{"description":"A N-D input tensor that is to be processed.","name":"X","type":"T"}],"max_input":1,"max_output":4,"min_input":1,"min_output":1,"outputs":[{"description":"A tensor of the same type as 'X' containing all the unique values or subtensors sliced along a provided 'axis' in 'X', either sorted or maintained in the same order they occur in input 'X'","name":"Y","type":"T"},{"description":"A 1-D INT64 tensor containing indices of 'Y' elements' first occurance in 'X'. When 'axis' is provided, it contains indices to subtensors in input 'X' on the 'axis'. When 'axis' is not provided, it contains indices to values in the flattened input tensor. ","name":"indices","option":"optional","type":"tensor(int64)"},{"description":"A 1-D INT64 tensor containing, for elements of 'X', its corresponding indices in 'Y'. When 'axis' is provided, it contains indices to subtensors in output 'Y' on the 'axis'. When 'axis' is not provided, it contains indices to values in output 'Y'. ","name":"inverse_indices","option":"optional","type":"tensor(int64)"},{"description":"A 1-D INT64 tensor containing the count of each element of 'Y' in input 'X'","name":"counts","option":"optional","type":"tensor(int64)"}],"outputs_range":"1 - 4","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input can be of any tensor type.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of non-negative integers, indicate the dimensions to be inserted","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of a tensor.\nTakes one required argument `axes`, a list of dimensions that will be inserted.\nDimension indices in `axes` are as seen in the output tensor. For example:\n Given a tensor such that tensor with shape [3, 4, 5], then\n Unsqueeze(tensor, axes=[0, 4]) has shape [1, 3, 4, 5, 1]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to be inserted. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(expanded).","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of an input tensor (`data`).\nTakes one required argument `axes` - which contains a list of dimension indices and this operator will insert a dimension of value `1` into the corresponding index of the output tensor (`expanded`).\n\nFor example:\n Given an input tensor (`data`) of shape [3, 4, 5], then\n Unsqueeze(data, axes=[0, 4]) outputs a tensor (`expanded`) containing same data as `data` but with shape [1, 3, 4, 5, 1].\n\nThe attribute `axes` should not contain any duplicate entries. It is an error if it contains duplicates.\nThe rank of the output tensor (`output_rank`) is the rank of the input tensor (`data`) plus the number of values in `axes`.\nEach value in `axes` should be within the (inclusive) range [-output_rank , output_rank - 1]. \nThe order of values in `axes` does not matter and can come in any order. \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to be inserted. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(expanded).","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of an input tensor (`data`).\nTakes one required argument `axes` - which contains a list of dimension indices and this operator will insert a dimension of value `1` into the corresponding index of the output tensor (`expanded`).\n\nFor example:\n Given an input tensor (`data`) of shape [3, 4, 5], then\n Unsqueeze(data, axes=[0, 4]) outputs a tensor (`expanded`) containing same data as `data` but with shape [1, 3, 4, 5, 1].\n\nThe attribute `axes` should not contain any duplicate entries. It is an error if it contains duplicates.\nThe rank of the output tensor (`output_rank`) is the rank of the input tensor (`data`) plus the number of values in `axes`.\nEach value in `axes` should be within the (inclusive) range [-output_rank , output_rank - 1]. \nThe order of values in `axes` does not matter and can come in any order. \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"description":"The scale along height dimension. It takes value greater than or equal to 1.","name":"height_scale","required":true,"type":"float32"},{"default":"nearest","description":"Two interpolation modes: nearest(default), bilinear","name":"mode","required":false,"type":"string"},{"description":"The scale along width dimension. It takes value greater than or equal to 1.","name":"width_scale","required":true,"type":"float32"}],"category":"Data","description":"Upsample the input tensor.\nThe width and height of the output tensor are:\n output_width = floor(input_width * width_scale),\n output_height = floor(input_height * height_scale).\nExample:\n Given `data` tensor, width_scale, height_scale, mode,\n Upsample the input 4-D tensor in nearest mode:\n data = [[[\n [1, 2],\n [3, 4]\n ]]]\n width_scale = 2\n height_scale = 2\n mode = \"nearest\"\n output = [[[\n [1, 1, 2, 2],\n [1, 1, 2, 2],\n [3, 3, 4, 4],\n [3, 3, 4, 4]\n ]]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"4-D tensor, [N,C,H,W]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"4-D tensor after resizing, [N,C,H,W]","name":"Y","type":"T"}],"since_version":1,"support_level":"experimental","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to bool, int32, int64, float16, float, double tensors.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","required":true,"type":"float32[]"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Where","schema":{"description":"Return elements, either from X or Y, depending on condition\n (with Numpy-style broadcasting support).\n Where behaves like numpy.where with three parameters:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Where',\n inputs=['condition', 'x', 'y'],\n outputs=['z'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nx = np.array([[1, 2], [3, 4]], dtype=np.int64)\ny = np.array([[9, 8], [7, 6]], dtype=np.int64)\nz = np.where(condition, x, y) # expected output [[1, 8], [3, 4]]\nexpect(node, inputs=[condition, x, y], outputs=[z],\n name='test_where_long_example')","summary":"long"},{"code":"node = onnx.helper.make_node(\n 'Where',\n inputs=['condition', 'x', 'y'],\n outputs=['z'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nx = np.array([[1, 2], [3, 4]], dtype=np.float32)\ny = np.array([[9, 8], [7, 6]], dtype=np.float32)\nz = np.where(condition, x, y) # expected output [[1, 8], [3, 4]]\nexpect(node, inputs=[condition, x, y], outputs=[z],\n name='test_where_example')","summary":"where"}],"inputs":[{"description":"When True (nonzero), yield X, otherwise yield Y","name":"condition","type":"B"},{"description":"values selected at indices where condition is True","name":"X","type":"T"},{"description":"values selected at indices where condition is False","name":"Y","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of shape equal to the broadcasted shape of condition, X, and Y.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrain to boolean tensors.","type_param_str":"B"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Xor","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `xor` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor4d')","summary":"xor"},{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v4d')","summary":"xor_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Xor","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `xor` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor4d')","summary":"xor"},{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v4d')","summary":"xor_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"ZipMap","schema":{"attributes":[{"description":"The keys when using int keys.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_int64s","required":false,"type":"int64[]"},{"description":"The keys when using string keys.
One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"}],"description":"Creates a map from the input and the attributes.
\n The values are provided by the input tensor, while the keys are specified by the attributes.\n Must provide keys in either classlabels_strings or classlabels_int64s (but not both).
\n The columns of the tensor correspond one-by-one to the keys specified by the attributes. There must be as many columns as keys.
\n","domain":"ai.onnx.ml","inputs":[{"description":"The input values","name":"X","type":"tensor(float)"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output map","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(map(string, float))","seq(map(int64, float))"],"description":"The output will be a sequence of string or integer maps to float.","type_param_str":"T"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..04388872ab836940bd9b29fca9be599296cf3d41 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("onnx");$root.onnx={},$root.onnx.Version={_START_VERSION:0,IR_VERSION_2017_10_10:1,IR_VERSION_2017_10_30:2,IR_VERSION_2017_11_3:3,IR_VERSION_2019_1_22:4,IR_VERSION_2019_3_18:5,IR_VERSION_2019_9_19:6,IR_VERSION:7},$root.onnx.AttributeProto=class{constructor(){this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparse_tensors=[]}static decode(o,t){const e=new $root.onnx.AttributeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 21:e.ref_attr_name=o.string();break;case 13:e.doc_string=o.string();break;case 20:e.type=o.int32();break;case 2:e.f=o.float();break;case 3:e.i=o.int64();break;case 4:e.s=o.bytes();break;case 5:e.t=$root.onnx.TensorProto.decode(o,o.uint32());break;case 6:e.g=$root.onnx.GraphProto.decode(o,o.uint32());break;case 22:e.sparse_tensor=$root.onnx.SparseTensorProto.decode(o,o.uint32());break;case 7:e.floats=o.floats(e.floats,t);break;case 8:e.ints=o.array(e.ints,(()=>o.int64()),t);break;case 9:e.strings.push(o.bytes());break;case 10:e.tensors.push($root.onnx.TensorProto.decode(o,o.uint32()));break;case 11:e.graphs.push($root.onnx.GraphProto.decode(o,o.uint32()));break;case 23:e.sparse_tensors.push($root.onnx.SparseTensorProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.AttributeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"ref_attr_name":t.ref_attr_name=o.string();break;case"doc_string":t.doc_string=o.string();break;case"type":t.type=o.enum($root.onnx.AttributeProto.AttributeType);break;case"f":t.f=o.float();break;case"i":t.i=o.integer();break;case"s":t.s=o.bytes();break;case"t":t.t=$root.onnx.TensorProto.decodeText(o,!0);break;case"g":t.g=$root.onnx.GraphProto.decodeText(o,!0);break;case"sparse_tensor":t.sparse_tensor=$root.onnx.SparseTensorProto.decodeText(o,!0);break;case"floats":o.array(t.floats,(()=>o.float()));break;case"ints":o.array(t.ints,(()=>o.integer()));break;case"strings":o.array(t.strings,(()=>o.bytes()));break;case"tensors":t.tensors.push($root.onnx.TensorProto.decodeText(o,!0));break;case"graphs":t.graphs.push($root.onnx.GraphProto.decodeText(o,!0));break;case"sparse_tensors":t.sparse_tensors.push($root.onnx.SparseTensorProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.AttributeProto.prototype.name="",$root.onnx.AttributeProto.prototype.ref_attr_name="",$root.onnx.AttributeProto.prototype.doc_string="",$root.onnx.AttributeProto.prototype.type=0,$root.onnx.AttributeProto.prototype.f=0,$root.onnx.AttributeProto.prototype.i=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.AttributeProto.prototype.s=new Uint8Array([]),$root.onnx.AttributeProto.prototype.t=null,$root.onnx.AttributeProto.prototype.g=null,$root.onnx.AttributeProto.prototype.sparse_tensor=null,$root.onnx.AttributeProto.AttributeType={UNDEFINED:0,FLOAT:1,INT:2,STRING:3,TENSOR:4,GRAPH:5,SPARSE_TENSOR:11,FLOATS:6,INTS:7,STRINGS:8,TENSORS:9,GRAPHS:10,SPARSE_TENSORS:12},$root.onnx.ValueInfoProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.ValueInfoProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 2:e.type=$root.onnx.TypeProto.decode(o,o.uint32());break;case 3:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.ValueInfoProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"type":t.type=$root.onnx.TypeProto.decodeText(o,!0);break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.ValueInfoProto.prototype.name="",$root.onnx.ValueInfoProto.prototype.type=null,$root.onnx.ValueInfoProto.prototype.doc_string="",$root.onnx.NodeProto=class{constructor(){this.input=[],this.output=[],this.attribute=[]}static decode(o,t){const e=new $root.onnx.NodeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.input.push(o.string());break;case 2:e.output.push(o.string());break;case 3:e.name=o.string();break;case 4:e.op_type=o.string();break;case 7:e.domain=o.string();break;case 5:e.attribute.push($root.onnx.AttributeProto.decode(o,o.uint32()));break;case 6:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.NodeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"input":o.array(t.input,(()=>o.string()));break;case"output":o.array(t.output,(()=>o.string()));break;case"name":t.name=o.string();break;case"op_type":t.op_type=o.string();break;case"domain":t.domain=o.string();break;case"attribute":t.attribute.push($root.onnx.AttributeProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.NodeProto.prototype.name="",$root.onnx.NodeProto.prototype.op_type="",$root.onnx.NodeProto.prototype.domain="",$root.onnx.NodeProto.prototype.doc_string="",$root.onnx.TrainingInfoProto=class{constructor(){this.initialization_binding=[],this.update_binding=[]}static decode(o,t){const e=new $root.onnx.TrainingInfoProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.initialization=$root.onnx.GraphProto.decode(o,o.uint32());break;case 2:e.algorithm=$root.onnx.GraphProto.decode(o,o.uint32());break;case 3:e.initialization_binding.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 4:e.update_binding.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TrainingInfoProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"initialization":t.initialization=$root.onnx.GraphProto.decodeText(o,!0);break;case"algorithm":t.algorithm=$root.onnx.GraphProto.decodeText(o,!0);break;case"initialization_binding":t.initialization_binding.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"update_binding":t.update_binding.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TrainingInfoProto.prototype.initialization=null,$root.onnx.TrainingInfoProto.prototype.algorithm=null,$root.onnx.ModelProto=class{constructor(){this.opset_import=[],this.metadata_props=[],this.training_info=[]}static decode(o,t){const e=new $root.onnx.ModelProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.ir_version=o.int64();break;case 8:e.opset_import.push($root.onnx.OperatorSetIdProto.decode(o,o.uint32()));break;case 2:e.producer_name=o.string();break;case 3:e.producer_version=o.string();break;case 4:e.domain=o.string();break;case 5:e.model_version=o.int64();break;case 6:e.doc_string=o.string();break;case 7:e.graph=$root.onnx.GraphProto.decode(o,o.uint32());break;case 14:e.metadata_props.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 20:e.training_info.push($root.onnx.TrainingInfoProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.ModelProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"ir_version":t.ir_version=o.integer();break;case"opset_import":t.opset_import.push($root.onnx.OperatorSetIdProto.decodeText(o,!0));break;case"producer_name":t.producer_name=o.string();break;case"producer_version":t.producer_version=o.string();break;case"domain":t.domain=o.string();break;case"model_version":t.model_version=o.integer();break;case"doc_string":t.doc_string=o.string();break;case"graph":t.graph=$root.onnx.GraphProto.decodeText(o,!0);break;case"metadata_props":t.metadata_props.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"training_info":t.training_info.push($root.onnx.TrainingInfoProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.ModelProto.prototype.ir_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.ModelProto.prototype.producer_name="",$root.onnx.ModelProto.prototype.producer_version="",$root.onnx.ModelProto.prototype.domain="",$root.onnx.ModelProto.prototype.model_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.ModelProto.prototype.doc_string="",$root.onnx.ModelProto.prototype.graph=null,$root.onnx.StringStringEntryProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.StringStringEntryProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.key=o.string();break;case 2:e.value=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.StringStringEntryProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"key":t.key=o.string();break;case"value":t.value=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.StringStringEntryProto.prototype.key="",$root.onnx.StringStringEntryProto.prototype.value="",$root.onnx.TensorAnnotation=class{constructor(){this.quant_parameter_tensor_names=[]}static decode(o,t){const e=new $root.onnx.TensorAnnotation,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.tensor_name=o.string();break;case 2:e.quant_parameter_tensor_names.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorAnnotation;for(o.start();!o.end();){const e=o.tag();switch(e){case"tensor_name":t.tensor_name=o.string();break;case"quant_parameter_tensor_names":t.quant_parameter_tensor_names.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TensorAnnotation.prototype.tensor_name="",$root.onnx.GraphProto=class{constructor(){this.node=[],this.initializer=[],this.sparse_initializer=[],this.input=[],this.output=[],this.value_info=[],this.quantization_annotation=[]}static decode(o,t){const e=new $root.onnx.GraphProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.node.push($root.onnx.NodeProto.decode(o,o.uint32()));break;case 2:e.name=o.string();break;case 5:e.initializer.push($root.onnx.TensorProto.decode(o,o.uint32()));break;case 15:e.sparse_initializer.push($root.onnx.SparseTensorProto.decode(o,o.uint32()));break;case 10:e.doc_string=o.string();break;case 11:e.input.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 12:e.output.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 13:e.value_info.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 14:e.quantization_annotation.push($root.onnx.TensorAnnotation.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.GraphProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"node":t.node.push($root.onnx.NodeProto.decodeText(o,!0));break;case"name":t.name=o.string();break;case"initializer":t.initializer.push($root.onnx.TensorProto.decodeText(o,!0));break;case"sparse_initializer":t.sparse_initializer.push($root.onnx.SparseTensorProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;case"input":t.input.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"output":t.output.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"value_info":t.value_info.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"quantization_annotation":t.quantization_annotation.push($root.onnx.TensorAnnotation.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.GraphProto.prototype.name="",$root.onnx.GraphProto.prototype.doc_string="",$root.onnx.TensorProto=class{constructor(){this.dims=[],this.float_data=[],this.int32_data=[],this.string_data=[],this.int64_data=[],this.external_data=[],this.double_data=[],this.uint64_data=[]}static decode(o,t){const e=new $root.onnx.TensorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dims=o.array(e.dims,(()=>o.int64()),t);break;case 2:e.data_type=o.int32();break;case 3:e.segment=$root.onnx.TensorProto.Segment.decode(o,o.uint32());break;case 4:e.float_data=o.floats(e.float_data,t);break;case 5:e.int32_data=o.array(e.int32_data,(()=>o.int32()),t);break;case 6:e.string_data.push(o.bytes());break;case 7:e.int64_data=o.array(e.int64_data,(()=>o.int64()),t);break;case 8:e.name=o.string();break;case 12:e.doc_string=o.string();break;case 9:e.raw_data=o.bytes();break;case 13:e.external_data.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 14:e.data_location=o.int32();break;case 10:e.double_data=o.doubles(e.double_data,t);break;case 11:e.uint64_data=o.array(e.uint64_data,(()=>o.uint64()),t);break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"dims":o.array(t.dims,(()=>o.integer()));break;case"data_type":t.data_type=o.integer();break;case"segment":t.segment=$root.onnx.TensorProto.Segment.decodeText(o,!0);break;case"float_data":o.array(t.float_data,(()=>o.float()));break;case"int32_data":o.array(t.int32_data,(()=>o.integer()));break;case"string_data":o.array(t.string_data,(()=>o.bytes()));break;case"int64_data":o.array(t.int64_data,(()=>o.integer()));break;case"name":t.name=o.string();break;case"doc_string":t.doc_string=o.string();break;case"raw_data":t.raw_data=o.bytes();break;case"external_data":t.external_data.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"data_location":t.data_location=o.enum($root.onnx.TensorProto.DataLocation);break;case"double_data":o.array(t.double_data,(()=>o.float()));break;case"uint64_data":o.array(t.uint64_data,(()=>o.integer()));break;default:o.field(e,t)}}return t}},$root.onnx.TensorProto.prototype.data_type=0,$root.onnx.TensorProto.prototype.segment=null,$root.onnx.TensorProto.prototype.name="",$root.onnx.TensorProto.prototype.doc_string="",$root.onnx.TensorProto.prototype.raw_data=new Uint8Array([]),$root.onnx.TensorProto.prototype.data_location=0,$root.onnx.TensorProto.DataType={UNDEFINED:0,FLOAT:1,UINT8:2,INT8:3,UINT16:4,INT16:5,INT32:6,INT64:7,STRING:8,BOOL:9,FLOAT16:10,DOUBLE:11,UINT32:12,UINT64:13,COMPLEX64:14,COMPLEX128:15,BFLOAT16:16},$root.onnx.TensorProto.Segment=class{constructor(){}static decode(o,t){const e=new $root.onnx.TensorProto.Segment,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.begin=o.int64();break;case 2:e.end=o.int64();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorProto.Segment;for(o.start();!o.end();){const e=o.tag();switch(e){case"begin":t.begin=o.integer();break;case"end":t.end=o.integer();break;default:o.field(e,t)}}return t}},$root.onnx.TensorProto.Segment.prototype.begin=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.TensorProto.Segment.prototype.end=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.TensorProto.DataLocation={DEFAULT:0,EXTERNAL:1},$root.onnx.SparseTensorProto=class{constructor(){this.dims=[]}static decode(o,t){const e=new $root.onnx.SparseTensorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.values=$root.onnx.TensorProto.decode(o,o.uint32());break;case 2:e.indices=$root.onnx.TensorProto.decode(o,o.uint32());break;case 3:e.dims=o.array(e.dims,(()=>o.int64()),t);break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.SparseTensorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"values":t.values=$root.onnx.TensorProto.decodeText(o,!0);break;case"indices":t.indices=$root.onnx.TensorProto.decodeText(o,!0);break;case"dims":o.array(t.dims,(()=>o.integer()));break;default:o.field(e,t)}}return t}},$root.onnx.SparseTensorProto.prototype.values=null,$root.onnx.SparseTensorProto.prototype.indices=null,$root.onnx.TensorShapeProto=class{constructor(){this.dim=[]}static decode(o,t){const e=new $root.onnx.TensorShapeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dim.push($root.onnx.TensorShapeProto.Dimension.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorShapeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"dim":t.dim.push($root.onnx.TensorShapeProto.Dimension.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TensorShapeProto.Dimension=class{constructor(){}get value(){return $root.onnx.TensorShapeProto.Dimension.valueSet=$root.onnx.TensorShapeProto.Dimension.valueSet||new Set(["dim_value","dim_param"]),Object.keys(this).find((o=>$root.onnx.TensorShapeProto.Dimension.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.onnx.TensorShapeProto.Dimension,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dim_value=o.int64();break;case 2:e.dim_param=o.string();break;case 3:e.denotation=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorShapeProto.Dimension;for(o.start();!o.end();){const e=o.tag();switch(e){case"dim_value":t.dim_value=o.integer();break;case"dim_param":t.dim_param=o.string();break;case"denotation":t.denotation=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TensorShapeProto.Dimension.prototype.denotation="",$root.onnx.TypeProto=class{constructor(){}get value(){return $root.onnx.TypeProto.valueSet=$root.onnx.TypeProto.valueSet||new Set(["tensor_type","sequence_type","map_type","sparse_tensor_type","opaque_type"]),Object.keys(this).find((o=>$root.onnx.TypeProto.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.onnx.TypeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.tensor_type=$root.onnx.TypeProto.Tensor.decode(o,o.uint32());break;case 4:e.sequence_type=$root.onnx.TypeProto.Sequence.decode(o,o.uint32());break;case 5:e.map_type=$root.onnx.TypeProto.Map.decode(o,o.uint32());break;case 8:e.sparse_tensor_type=$root.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break;case 7:e.opaque_type=$root.onnx.TypeProto.Opaque.decode(o,o.uint32());break;case 6:e.denotation=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"tensor_type":t.tensor_type=$root.onnx.TypeProto.Tensor.decodeText(o,!0);break;case"sequence_type":t.sequence_type=$root.onnx.TypeProto.Sequence.decodeText(o,!0);break;case"map_type":t.map_type=$root.onnx.TypeProto.Map.decodeText(o,!0);break;case"sparse_tensor_type":t.sparse_tensor_type=$root.onnx.TypeProto.SparseTensor.decodeText(o,!0);break;case"opaque_type":t.opaque_type=$root.onnx.TypeProto.Opaque.decodeText(o,!0);break;case"denotation":t.denotation=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.prototype.denotation="",$root.onnx.TypeProto.Tensor=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Tensor,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=o.int32();break;case 2:e.shape=$root.onnx.TensorShapeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Tensor;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=o.integer();break;case"shape":t.shape=$root.onnx.TensorShapeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Tensor.prototype.elem_type=0,$root.onnx.TypeProto.Tensor.prototype.shape=null,$root.onnx.TypeProto.Sequence=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Sequence,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=$root.onnx.TypeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Sequence;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=$root.onnx.TypeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Sequence.prototype.elem_type=null,$root.onnx.TypeProto.Map=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Map,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.key_type=o.int32();break;case 2:e.value_type=$root.onnx.TypeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Map;for(o.start();!o.end();){const e=o.tag();switch(e){case"key_type":t.key_type=o.integer();break;case"value_type":t.value_type=$root.onnx.TypeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Map.prototype.key_type=0,$root.onnx.TypeProto.Map.prototype.value_type=null,$root.onnx.TypeProto.SparseTensor=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.SparseTensor,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=o.int32();break;case 2:e.shape=$root.onnx.TensorShapeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.SparseTensor;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=o.integer();break;case"shape":t.shape=$root.onnx.TensorShapeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.SparseTensor.prototype.elem_type=0,$root.onnx.TypeProto.SparseTensor.prototype.shape=null,$root.onnx.TypeProto.Opaque=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Opaque,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.domain=o.string();break;case 2:e.name=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Opaque;for(o.start();!o.end();){const e=o.tag();switch(e){case"domain":t.domain=o.string();break;case"name":t.name=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Opaque.prototype.domain="",$root.onnx.TypeProto.Opaque.prototype.name="",$root.onnx.OperatorSetIdProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.OperatorSetIdProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.domain=o.string();break;case 2:e.version=o.int64();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorSetIdProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"domain":t.domain=o.string();break;case"version":t.version=o.integer();break;default:o.field(e,t)}}return t}},$root.onnx.OperatorSetIdProto.prototype.domain="",$root.onnx.OperatorSetIdProto.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorStatus={EXPERIMENTAL:0,STABLE:1},$root.onnx.FunctionProto=class{constructor(){this.input=[],this.output=[],this.attribute=[],this.node=[],this.opset_import=[]}static decode(o,t){const e=new $root.onnx.FunctionProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 2:e.since_version=o.int64();break;case 3:e.status=o.int32();break;case 4:e.input.push(o.string());break;case 5:e.output.push(o.string());break;case 6:e.attribute.push(o.string());break;case 7:e.node.push($root.onnx.NodeProto.decode(o,o.uint32()));break;case 8:e.doc_string=o.string();break;case 9:e.opset_import.push($root.onnx.OperatorSetIdProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.FunctionProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"since_version":t.since_version=o.integer();break;case"status":t.status=o.enum($root.onnx.OperatorStatus);break;case"input":o.array(t.input,(()=>o.string()));break;case"output":o.array(t.output,(()=>o.string()));break;case"attribute":o.array(t.attribute,(()=>o.string()));break;case"node":t.node.push($root.onnx.NodeProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;case"opset_import":t.opset_import.push($root.onnx.OperatorSetIdProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.FunctionProto.prototype.name="",$root.onnx.FunctionProto.prototype.since_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.FunctionProto.prototype.status=0,$root.onnx.FunctionProto.prototype.doc_string="",$root.onnx.OperatorProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.OperatorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.op_type=o.string();break;case 2:e.since_version=o.int64();break;case 3:e.status=o.int32();break;case 10:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"op_type":t.op_type=o.string();break;case"since_version":t.since_version=o.integer();break;case"status":t.status=o.enum($root.onnx.OperatorStatus);break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.OperatorProto.prototype.op_type="",$root.onnx.OperatorProto.prototype.since_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorProto.prototype.status=0,$root.onnx.OperatorProto.prototype.doc_string="",$root.onnx.OperatorSetProto=class{constructor(){this.operator=[],this.functions=[]}static decode(o,t){const e=new $root.onnx.OperatorSetProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.magic=o.string();break;case 2:e.ir_version=o.int64();break;case 3:e.ir_version_prerelease=o.string();break;case 7:e.ir_build_metadata=o.string();break;case 4:e.domain=o.string();break;case 5:e.opset_version=o.int64();break;case 6:e.doc_string=o.string();break;case 8:e.operator.push($root.onnx.OperatorProto.decode(o,o.uint32()));break;case 9:e.functions.push($root.onnx.FunctionProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorSetProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"magic":t.magic=o.string();break;case"ir_version":t.ir_version=o.integer();break;case"ir_version_prerelease":t.ir_version_prerelease=o.string();break;case"ir_build_metadata":t.ir_build_metadata=o.string();break;case"domain":t.domain=o.string();break;case"opset_version":t.opset_version=o.integer();break;case"doc_string":t.doc_string=o.string();break;case"operator":t.operator.push($root.onnx.OperatorProto.decodeText(o,!0));break;case"functions":t.functions.push($root.onnx.FunctionProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.OperatorSetProto.prototype.magic="",$root.onnx.OperatorSetProto.prototype.ir_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorSetProto.prototype.ir_version_prerelease="",$root.onnx.OperatorSetProto.prototype.ir_build_metadata="",$root.onnx.OperatorSetProto.prototype.domain="",$root.onnx.OperatorSetProto.prototype.opset_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorSetProto.prototype.doc_string=""; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx.js new file mode 100644 index 0000000000000000000000000000000000000000..88f7000b8f8444922b13a5c3c58363c1a7f6937e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/onnx.js @@ -0,0 +1 @@ +var onnx=onnx||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");onnx.ModelFactory=class{match(t){const e=t.identifier,n=e.split(".").pop().toLowerCase();if("onnx"==n)return!0;if("pb"==n){if(e.endsWith("saved_model.pb"))return!1;if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb"))return!1;const n=t.tags("pb");return!(0===n.size||n.size>0&&n.has(1)&&0===n.get(1)&&n.has(2)&&0===n.get(2)&&n.has(9)&&2===n.get(9)||n.size>0&&Array.from(n.values()).some((t=>5===t))||n.has(1)&&0!=n.get(1)||n.has(2)&&2!=n.get(2)||n.has(3)&&2!=n.get(3)||n.has(4)&&2!=n.get(4)||n.has(5)&&0!=n.get(5)||n.has(6)&&2!=n.get(6)||n.has(8)&&2!=n.get(8)||n.has(14)&&2!=n.get(14)||!n.has(7)||2!=n.get(7))}if("pbtxt"===n||"prototxt"===n||"model"===n){if(e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const o=t.tags("pbtxt");if(o.has("ir_version"))return!0;if(o.has("graph")&&"model"!==n)return!0}return!1}open(t,e){return e.require("./onnx-proto").then((()=>{let n=null;const o=t.identifier,a=o.split(".").pop().toLowerCase();if("pbtxt"==a||"prototxt"==a)try{onnx.proto=protobuf.get("onnx").onnx;const e=protobuf.TextReader.create(t.text);n=onnx.proto.ModelProto.decodeText(e)}catch(t){throw new onnx.Error("File text format is not onnx.ModelProto ("+t.message+") in '"+o+"'.")}else try{onnx.proto=protobuf.get("onnx").onnx;const e=protobuf.Reader.create(t.buffer);n=onnx.proto.ModelProto.decode(e)}catch(t){throw new onnx.Error("File format is not onnx.ModelProto ("+t.message+") in '"+o+"'.")}return onnx.Metadata.open(e).then((t=>{try{return new onnx.Model(t,n)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new onnx.Error(n.replace(/\.$/,"")+" in '"+o+"'.")}}))}))}},onnx.Model=class{constructor(t,e){this._graphs=[],this._irVersion=e.ir_version,this._producerName=e.producer_name,this._producerVersion=e.producer_version,this._domain=e.domain,this._modelVersion=e.model_version,this._description=e.doc_string,this._metadata=[],this._imports=null;const n={};if(e.opset_import&&e.opset_import.length>0){const t=[];for(const o of e.opset_import){let e=o.domain||"ai.onnx";const a=e+" v"+o.version;t.includes(a)||t.push(a),e="ai.onnx"==e?"":e,(!n[e]||n[e]>o.version)&&(n[e]=o.version)}this._imports=t.join(", ")}0==Object.keys(n).length&&(n[""]=1,n["ai.onnx.ml"]=1);let o="";if(e.metadata_props){const t={};for(const n of e.metadata_props)switch(n.key){case"author":this._author=n.value;break;case"company":this._company=n.value;break;case"converted_from":this._converted_from=n.value;break;case"license":this._license=n.value;break;case"license_url":this._licenseUrl=n.value;break;case"Image.BitmapPixelFormat":case"Image.ColorSpaceGamma":case"Image.NominalPixelRange":t[n.key]=n.value;break;default:this._metadata.push({name:n.key,value:n.value})}o=[t["Image.BitmapPixelFormat"],t["Image.ColorSpaceGamma"],t["Image.NominalPixelRange"]].filter((t=>t))}if(this._graphs=[],e&&e.graph){const a=new onnx.GraphMetadata(t,n),r=new onnx.Graph(a,o,e.graph);this._graphs.push(r)}}get format(){return"ONNX"+(this._irVersion?" v"+this._irVersion.toString():"")}get imports(){return this._imports}get producer(){const t=[];return this._producerName&&t.push(this._producerName),this._producerVersion&&this._producerVersion.length>0&&t.push(this._producerVersion),t.length>0?t.join(" "):null}get domain(){return this._domain||null}get description(){return this._description||null}get author(){return this._author||null}get company(){return this._company||null}get source(){return this._converted_from||null}get license(){const t=[];return this._license&&this._license.length>0&&t.push(this._license),this._licenseUrl&&this._licenseUrl.length>0&&t.push("
"+this._licenseUrl+""),t.length>0?t:null}get metadata(){return this._metadata}get graphs(){return this._graphs}},onnx.Graph=class{constructor(t,e,n){if(this._node="",this._description="",this._nodes=[],this._inputs=[],this._outputs=[],n){this._name=n.name||null,this._description=n.doc_string||"";const o=new Map;for(const t of n.initializer)o.set(t.name,new onnx.Tensor(t,"Initializer"));const a=[],r=new Map,s=new Map;for(const t of n.node){for(const e of t.input)r.set(e,r.has(e)?r.get(e)+1:1);for(const e of t.output)s.set(e,r.has(e)?r.get(e)+1:1)}for(const t of n.input)r.delete(t);for(const t of n.output)s.delete(t);for(const t of n.node){let e=!1;if("Constant"==t.op_type&&0==t.input.length&&1==t.output.length){const n=t.output[0];if(r.has(n)&&1==r.get(n)&&s.has(n)&&1==s.get(n)&&1==t.attribute.length){const a=t.attribute[0];a&&"value"==a.name&&a.t&&(o.set(n,new onnx.Tensor(a.t,"Constant")),e=!0)}}e||a.push(t)}const i=new Map;for(const t of n.quantization_annotation){const e={};for(const n of t.quant_parameter_tensor_names)e[n.key]=n.value;i.set(t.tensor_name,e)}const p=new Map,h=(t,e,n,o,a)=>{if(!p.has(t)){e=o?o.type:e?onnx.Utility.formatType(e,a):null;const r=i.get(t);p.set(t,new onnx.Argument(t,e,o,r,n))}return p.get(t)};for(const t of n.value_info)h(t.name,t.type,t.doc_string,o.get(t.name),e);for(const t of n.input){const n=h(t.name,t.type,t.doc_string,o.get(t.name),e);o.has(t.name)||this._inputs.push(new onnx.Parameter(t.name,[n]))}for(const t of n.output){const n=h(t.name,t.type,t.doc_string,o.get(t.name),e);this._outputs.push(new onnx.Parameter(t.name,[n]))}for(const n of a){let a=[];const r=t.type(n.op_type);if(n.input&&n.input.length>0){let t=0;if(r&&r.inputs){for(const s of r.inputs)if(th(t,null,null,o.get(t),e)));t+=r,a.push(new onnx.Parameter(s.name,i))}}else a=a.concat(n.input.slice(t).map(((n,o)=>new onnx.Parameter((t+o).toString(),[h(n,null,null,null,e)]))))}let s=[];if(n.output&&n.output.length>0){let t=0;if(r&&r.outputs){for(const o of r.outputs)if(th(t,null,null,null,e)));t+=a,s.push(new onnx.Parameter(o.name,r))}}else s=s.concat(n.output.slice(t).map(((n,o)=>new onnx.Parameter((t+o).toString(),[h(n,null,null,null,e)]))))}this._nodes.push(new onnx.Node(t,e,n.op_type,n.domain,n.name,n.doc_string,n.attribute,a,s))}}}get name(){return this._name}get description(){return this._description}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}toString(){return"graph("+this.name+")"}},onnx.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},onnx.Argument=class{constructor(t,e,n,o,a){if("string"!=typeof t)throw new onnx.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null,this._annotation=o,this._description=a||""}get name(){return this._name}get type(){return this._type}get description(){return this._description}get quantization(){return this._annotation?Object.keys(this._annotation).map((t=>t+": "+this._annotation[t])).join(", "):null}get initializer(){return this._initializer}},onnx.Node=class{constructor(t,e,n,o,a,r,s,i,p){this._metadata=t,this._type=n,this._domain=o||"",this._name=a||"",this._description=r||"",this._inputs=i,this._outputs=p,this._attributes=(s||[]).map((t=>new onnx.Attribute(this._metadata,e,this.type,t)))}get type(){return this._type}get name(){return this._name}get description(){return this._description}get metadata(){return this._metadata.type(this._type)}get domain(){return this._domain}get group(){return null}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},onnx.Attribute=class{constructor(t,e,n,o){this._name=o.name,this._description=o.doc_string||"",this._type=null,this._value=null;const a=t.attribute(n,o.name);if(!this._type)if(Object.prototype.hasOwnProperty.call(o,"type")){if(!onnx.Attribute._attributeTypeMap){const t={};t[onnx.proto.AttributeProto.AttributeType.UNDEFINED]="undefined",t[onnx.proto.AttributeProto.AttributeType.FLOAT]="float32",t[onnx.proto.AttributeProto.AttributeType.INT]="int64",t[onnx.proto.AttributeProto.AttributeType.STRING]="string",t[onnx.proto.AttributeProto.AttributeType.TENSOR]="tensor",t[onnx.proto.AttributeProto.AttributeType.GRAPH]="graph",t[onnx.proto.AttributeProto.AttributeType.FLOATS]="float32",t[onnx.proto.AttributeProto.AttributeType.INTS]="int64[]",t[onnx.proto.AttributeProto.AttributeType.STRINGS]="string[]",t[onnx.proto.AttributeProto.AttributeType.TENSORS]="tensor[]",t[onnx.proto.AttributeProto.AttributeType.GRAPHS]="graph[]",onnx.Attribute._attributeTypeMap=t}const t=onnx.Attribute._attributeTypeMap[o.type];this._type=t||onnx.Attribute._attributeTypeMap[onnx.proto.AttributeProto.AttributeType.UNDEFINED]}else a&&a.type&&(this._type=a.type);if(o.ints&&o.ints.length>0)this._value=o.ints;else if(o.floats&&o.floats.length>0)this._value=o.floats;else if(o.strings&&o.strings.length>0)this._value=o.strings.map((t=>onnx.Utility.decodeText(t)));else if(o.graphs&&o.graphs.length>0)this._value=o.graphs.map((n=>new onnx.Graph(t,e,n))),this._type="graph[]";else if(o.s&&o.s.length>0)switch(n){case"Int8GivenTensorFill":this._value=Array.from(o.s);break;default:this._value=onnx.Utility.decodeText(o.s)}else Object.prototype.hasOwnProperty.call(o,"f")?this._value=o.f:Object.prototype.hasOwnProperty.call(o,"i")?this._value=o.i:Object.prototype.hasOwnProperty.call(o,"t")?(this._type="tensor",this._value=new onnx.Tensor(o.t).value):Object.prototype.hasOwnProperty.call(o,"g")&&(this._type="graph",this._value=new onnx.Graph(t,e,o.g));a&&Object.prototype.hasOwnProperty.call(a,"default")&&a.default&&this._value==a.default&&(this._visible=!1)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get description(){return this._description}get visible(){return 0!=this._visible}},onnx.Tensor=class{constructor(t,e){if(this._tensor=t,this._name=t.name||"",this._kind=e||null,this._type=new onnx.TensorType(this._tensor.data_type,new onnx.TensorShape(this._tensor.dims.map((t=>t))),null),this._tensor.data_type==onnx.proto.TensorProto.DataType.FLOAT16&&this._tensor.int32_data&&this._tensor.int32_data.length>0){const t=new Uint8Array(this._tensor.int32_data.length<<1),e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=this._tensor.int32_data;for(let t=0;t0?t.data=this._tensor.float_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.DOUBLE:this._tensor.double_data&&this._tensor.double_data.length>0?t.data=this._tensor.double_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.FLOAT16:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.BOOL:case onnx.proto.TensorProto.DataType.INT8:case onnx.proto.TensorProto.DataType.UINT8:case onnx.proto.TensorProto.DataType.INT16:case onnx.proto.TensorProto.DataType.UINT16:case onnx.proto.TensorProto.DataType.INT32:this._tensor.int32_data&&this._tensor.int32_data.length>0?t.data=this._tensor.int32_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.UINT32:this._tensor.uint64_data&&this._tensor.uint64_data.length>0?t.data=this._tensor.uint64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.INT64:this._tensor.int64_data&&this._tensor.int64_data.length>0?t.data=this._tensor.int64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.UINT64:this._tensor.uint64_data&&this._tensor.uint64_data.length>0?t.data=this._tensor.uint64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;default:t.state="Tensor data type is not implemented."}return t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],o=[],a=n[e];if(e==n.length-1)for(let e=0;et.limit)return o.push("..."),o;if(t.data){let e=t.data[t.index++];switch(this._tensor.data_type){case onnx.proto.TensorProto.DataType.BOOL:e=0!==e}o.push(e),t.count++}else if(t.rawData)switch(this._tensor.data_type){case onnx.proto.TensorProto.DataType.FLOAT16:o.push(t.rawData.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.FLOAT:o.push(t.rawData.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.DOUBLE:o.push(t.rawData.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.INT8:o.push(t.rawData.getInt8(t.index,!0)),t.index++,t.count++;break;case onnx.proto.TensorProto.DataType.UINT8:o.push(t.rawData.getUint8(t.index,!0)),t.index++,t.count++;break;case onnx.proto.TensorProto.DataType.INT16:o.push(t.rawData.getInt16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.UINT16:o.push(t.rawData.getUint16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.INT32:o.push(t.rawData.getInt32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.UINT32:o.push(t.rawData.getUint32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.INT64:o.push(new long.Long(t.rawData.getUint32(t.index,!0),t.rawData.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.UINT64:o.push(new long.Long(t.rawData.getUint32(t.index,!0),t.rawData.getUint32(t.index+4,!0),!0)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.BOOL:o.push(0!==t.rawData.getInt8(t.index,!0)),t.index+=1,t.count++}}else for(let n=0;nt.limit)return o.push("..."),o;o.push(this._decode(t,e+1))}return 0==t.shape.length?o[0]:o}static _stringify(t,e,n){if(Array.isArray(t)){const o=[];o.push(e+"[");const a=t.map((t=>onnx.Tensor._stringify(t,e+n,n)));return a.length>0&&o.push(a.join(",\n")),o.push(e+"]"),o.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},onnx.TensorType=class{constructor(t,e,n){this._dataType=onnx.Utility.formatElementType(t),this._shape=e,this._denotation=n||null}get dataType(){return this._dataType}get shape(){return this._shape}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},onnx.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},onnx.SequenceType=class{constructor(t,e){this._elementType=t,this._denotation=e}get elementType(){return this._elementType}get dennotation(){return this._dennotation}toString(){return"sequence<"+this._elementType.toString()+">"}},onnx.MapType=class{constructor(t,e,n){this._keyType=onnx.Utility.formatElementType(t),this._valueType=e,this._denotation=n}get keyType(){return this._keyType}get valueType(){return this._valueType}get denotation(){return this._denotation}toString(){return"map<"+this._keyType+","+this._valueType.toString()+">"}},onnx.OpaqueType=class{constructor(t,e){this._domain=t,this._name=e}toString(){return"opaque<"+(this._domain?this._domain+".":"")+this._name+">"}},onnx.GraphMetadata=class{constructor(t,e){this._metadata=t,this._imports=e,this._cache=new Map,this._attributeCache=new Map}type(t){return this._cache.has(t)||this._cache.set(t,this._metadata.type(t,this._imports)),this._cache.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},onnx.Metadata=class{static open(t){return onnx.Metadata._metadata?Promise.resolve(onnx.Metadata._metadata):t.request(null,"onnx-metadata.json","utf-8").then((t=>(onnx.Metadata._metadata=new onnx.Metadata(t),onnx.Metadata._metadata))).catch((()=>(onnx.Metadata._metadata=new onnx.Metadata(null),onnx.Metadata._metadata)))}constructor(t){if(this._map={},t){const e=JSON.parse(t);if(e)for(const t of e)if(t.name&&t.schema){const e=t.name;t.schema.name=e,this._map[e]=this._map[e]||[],this._map[e].push(t.schema)}}}type(t,e){let n=null;const o=this._map[t];if(o){let t=-1;for(const a of o){const o=e["ai.onnx"===a.domain?"":a.domain],r=a.since_version;o>=r&&tt.dim_param?t.dim_param:t.dim_value))),new onnx.TensorType(t.tensor_type.elem_type,new onnx.TensorShape(e),n)}case"map_type":return new onnx.MapType(t.map_type.key_type,onnx.Utility.formatType(t.map_type.value_type,e),n);case"sequence_type":return new onnx.SequenceType(onnx.Utility.formatType(t.sequence_type.elem_type,e),n);case"opaque_type":return new onnx.OpaqueType(t.opaque_type.domain,t.opaque_type.name)}return null}},onnx.Error=class extends Error{constructor(t){super(t),this.name="Error loading ONNX model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=onnx.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..24c510288ee20a492493b1c2d73265aa89630d02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"attributes":[{"default":[1,null],"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32[]"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":[1,null],"name":"strides","type":"int32[]"},{"default":0,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":0,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":"int32"},{"default":0,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":0,"name":"pad-r","type":"int32"},{"default":0,"name":"pad-b","type":"int32"},{"default":[1,1],"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32[]"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":1,"description":" *output* is a number of output feature maps per whole output (when *group* > 1, *output* still matches the number of output features regardless of *group* value). For example, *output* equals 1 means that there is 1 output feature map in a layer.","name":"output","option":"required","type":"int32","visible":false},{"default":1,"description":" *group* denotes the number of groups to which *output* and *input* should be split. For example, *group* equal 1 means that all the filters are applied to full input (usual convolution), *group* equals 2 means that both *input* and *output* channels are separated into 2 groups and *i-th output* group is connected to *i-th input* group channels. *group* equals number of output feature maps denotes depth-wise separable convolution ([Reference](https://medium.com/towards-data-science/types-of-convolutions-in-deep-learning-717013397f4d#6f51)).","name":"group","option":"required","type":"int32"},{"default":1,"description":" *dilation* denotes the distance in width and height between elements (weights) in the filter. For example, *dilation* equal \"1,1\" means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation* equal \"2,2\" means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation","option":"required","type":"int32"},{"default":1,"name":"dilation-x","type":"int32"},{"default":[1,null],"name":"dilations","type":"int32[]"},{"default":"same_upper","name":"auto_pad"},{"default":[0,null],"name":"pads_begin","type":"int32[]"},{"default":[0,null],"name":"pads_end","type":"int32[]"},{"default":1,"description":" *dilation-y* denotes the distance in height between elements (weights) in the filter. For example, *dilation-y* equal 1 means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation-y* equal 2 means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation-y","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/convolution.html)
**Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#conv)\n**Parameters**: *Convolution* layer parameters should be specified in the `convolution_data` node, which is a child of the layer node.\n**Weights Layout** Weights layout is GOIYX, which means that *X* is changing the fastest, then *Y*, then *Input*, *Output*, then *Group*.\n**Mathematical Formulation**\n* For the convolutional layer, the number of output features in each dimension is calculated using the formula:\n\\f[\nn_{out} = \\left ( \\frac{n_{in} + 2p - k}{s} \\right ) + 1\n\\f]\n* The receptive field in each layer is calculated using the formulas:\n * Jump in the output feature map:\n \\f[\n j_{out} = j_{in} * s\n \\f]\n * Size of the receptive field of output feature:\n \\f[\n r_{out} = r_{in} + ( k - 1 ) * j_{in}\n \\f]\n * Center position of the receptive field of the first output feature:\n \\f[\n start_{out} = start_{in} + ( \\frac{k - 1}{2} - p ) * j_{in}\n \\f]\n * Output is calculated using the following formula:\n \\f[\n out = \\sum_{i = 0}^{n}w_{i}x_{i} + b\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n \n \n```","inputs":[{"name":"inputs","option":"variadic"},{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"*(type: Tensor``)* Concatenated tensor.","name":"concat_result"},{"description":"*(type: Tensor``)* The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"BinaryConvolution","schema":{"category":"Layer"}},{"name":"Pooling","schema":{"attributes":[{"default":[1,null],"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32[]"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":[1,null],"name":"strides","type":"int32[]"},{"default":1,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":0,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":"int32"},{"default":0,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":0,"name":"pad-r","type":"int32"},{"default":0,"name":"pad-b","type":"int32"},{"default":[0,null],"name":"pads_begin","type":"int32[]"},{"default":[0,null],"name":"pads_end","type":"int32[]"},{"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32[]"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":"max","description":" *pool-method* is a type of pooling strategy for values.","name":"pool-method","option":"required","type":""},{"default":false,"description":" *exclude-pad* is a type of pooling strategy for values in the padding area. For example, if *exclude-pad* is \"true\", zero-values in the padding are not used.","name":"exclude-pad","option":"required","type":"boolean"},{"default":"ceil","description":" *rounding_type* is a type of rounding to be applied.","name":"rounding-type","option":"required","type":"\n * *ceil*\n * *floor*"}],"category":"Pool","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/pooling.html)\n**Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#pool)\n**Parameters**: Specify pooling layer parameters in the `pooling_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n* For *max pool-method*:\n \\f[\n output_{j} = MAX\\{ x_{0}, ... x_{i}\\}\n \\f]\n* For *avg pool-method*:\n \\f[\n output_{j} = \\frac{\\sum_{i = 0}^{n}x_{i}}{n}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ROIPooling","schema":{"attributes":[{"default":1,"description":" *pooled_h* is a height of the ROI output feature map. For example, *pooled_h* equal 6 means that the height of the output of *ROIpooling* is 6.","name":"pooled_h","option":"required","type":"int32"},{"default":1,"description":" *pooled_w* is a width of the ROI output feature map. For example, *pooled_w* equal 6 means that the width of the output of *ROIpooling* is 6.","name":"pooled_w","option":"required","type":"int32"},{"default":1,"description":" *spatial_scale* is a ratio of the input feature map over the input image size.","name":"spatial_scale","option":"required","type":" positive floating point value"}],"category":"Layer","description":"**Short description**: It is a *pooling layer* with *max* pooling strategy (see *max* option in the *Pooling layer* parameters description). It is used over feature maps of non-uniform sizes and outputs another feature map of a fixed size.\n**Detailed description**: [deepsense.io reference](https://blog.deepsense.ai/region-of-interest-pooling-explained/)\n**Parameters**: Specify *ROIPooling* layer parameters in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\noutput_{j} = MAX\\{ x_{0}, ... x_{i}\\}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"FullyConnected","schema":{"attributes":[{"default":1,"description":" *out-size* is a length of the output vector. For example, *out-size* equal 4096 means that the output vector length is 4096.","name":"out-size","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/innerproduct.html)\n**Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#fc)\n**Parameters**: Specify *FullyConnected* layer parameters in the `fc_data` node, which is a child of the layer node.\n**Weights Layout** OI, which means that Input is changing the fastest, then Output.\n**Mathematical Formulation**\n* If previous layer is *FullyConnected*:\n \\f[\n y_{i} = f( z_{i} ) \\quad with \\quad z_{i} = \\sum_{j=1}^{m_{1}^{( l-1 )}}w_{i,j}^{( l )}y_{i}^{ ( l -1 )}\n \\f]\n* Otherwise:\n \\f[\n y_{i} = f( z_{i} ) \\quad with \\quad z_{i}^{ ( l )} = \\sum_{j=1}^{m_{1}^{( l-1 )}}\\sum_{r=1}^{m_{2}^{ ( l-1 )}}\\sum_{s=1}^{m_{3}^{ ( l-1 )}}w_{i,j,r,s}^{ ( l )} ( Y_{i}^{ (l-1) })_{r,s}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ReLU","schema":{"attributes":[{"default":0,"description":" *negative_slope* is a multiplier, which is used if the unit is not active (that is negative). For example, *negative_slope* equal 0.1 means that an inactive unit value would be multiplied by 0.1 and this is the [Leaky ReLU](https://keras.io/layers/advanced-activations/#leakyrelu). If *negative_slope* is equal to 0, this is the usual *ReLU*.","name":"negative_slope","option":"required","type":"float64"}],"category":"Activation","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/relu.html)\n**Detailed description**: [Reference](https://github.com/Kulbear/deep-learning-nano-foundation/wiki/ReLU-and-Softmax-Activation-Functions#rectified-linear-units)\n**Parameters**: *ReLU* layer parameters can be (not mandatory) specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\nY_{i}^{( l )} = max(0, Y_{i}^{( l - 1 )})\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Activation","schema":{"attributes":[{"description":" *type* represents particular activation function. For example, *type* equal *sigmoid* means that neurons of this layer have a sigmoid activation function.","name":"type","option":"required"},{"default":1,"name":"alpha","type":"float32"}],"category":"Activation","description":"**Short description**: *Activation* layer represents an activation function of each neuron in a layer, which is used to add non-linearity to the computational flow.\n**Detailed description**: [Reference](https://medium.com/the-theory-of-everything/understanding-activation-functions-in-neural-networks-9491262884e0)\n**Parameters**: *Activation layer* parameters should be specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n* Sigmoid function:\n \\f[\n f( x ) = \\frac{1}{1+e^{-x}}\n \\f]\n* Tahn function:\n \\f[\n f ( x ) = \\frac{2}{1+e^{-2x}} - 1 = 2sigmoid(2x) - 1\n \\f]\n*\tElu function:\n\t\\f[\n f(x) = \\left\\{\\begin{array}{ll}\n\t\te^{x} - 1 \\quad \\mbox{if } x < 0 \\\\\n\t\tx \\quad \\mbox{if } x \\geq 0\n\t\\end{array}\\right.\n\t\\f]\n*\tRelu6 function:\n\t\\f[\n f(x) = min(max(0, x), 6)\n\t\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"SoftMax","schema":{"attributes":[{"description":" *axis* represents the axis of which the *SoftMax* is calculated. *axis* equal 1 is a default value.","name":"axis","option":"required","type":"int32"}],"category":"Activation","description":"**Short description**: [Reference](https://github.com/Kulbear/deep-learning-nano-foundation/wiki/ReLU-and-Softmax-Activation-Functions#softmax)\n**Detailed description**: [Reference](http://cs231n.github.io/linear-classify/#softmax)\n**Parameters**: *SoftMax* layer parameters can be (not mandatory) specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\ny_{c} = \\frac{e^{Z_{c}}}{\\sum_{d=1}^{C}e^{Z_{d}}}\n\\f]\nwhere \\f$C\\f$ is a number of classes\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Deconvolution","schema":{"attributes":[{"default":1,"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":1,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":1,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":" int32"},{"default":1,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":1,"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":1,"description":" *output* is a number of output feature maps per whole output (when *group* > 1, *output* still matches the number of output features regardless of *group* value). For example, *output* equals 1 means that there is 1 output feature map in a layer.","name":"output","option":"required","type":"int32"},{"default":1,"description":" *group* denotes the number of groups to which *output* and *input* should be split. For example, *group* equal 1 means that all the filters are applied to full input (usual convolution), *group* equals 2 means that both *input* and *output* channels are separated into 2 groups and *i-th output* group is connected to *i-th input* group channels. *group* equals number of output feature maps denotes depth-wise separable convolution ([Reference](https://medium.com/towards-data-science/types-of-convolutions-in-deep-learning-717013397f4d#6f51)).","name":"group","option":"required","type":"int32"},{"default":1,"description":" *dilation* denotes the distance in width and height between elements (weights) in the filter. For example, *dilation* equal \"1,1\" means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation* equal \"2,2\" means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation","option":"required","type":"int32"},{"default":1,"description":" *dilation-y* denotes the distance in height between elements (weights) in the filter. For example, *dilation-y* equal 1 means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation-y* equal 2 means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation-y","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *Deconvolution* layer is applied for upsampling the output to the higher image resolution.\n**Detailed description**: [Reference](https://distill.pub/2016/deconv-checkerboard/)\n**Parameters**: *Deconvolution* layer parameters should be specified in the `deconvolution_data` node, which is a child of the layer node.\n**Parameters**: *Convolution* layer parameters should be specified in the `convolution_data` node, which is a child of the layer node.\n**Weights Layout** Weights layout is the following: GOIYX, which means that *X* is changing the fastest, then *Y*, then *Input*, *Output*, then *Group*.\n**Mathematical Formulation**\n*Deconvolution* is also called transpose convolution and performs operation, reverse to convolution.\nThe number of output features for each dimensions is calculated:\n\\f[S_{o}=stride(S_{i} - 1 ) + S_{f} - 2pad \\f]\nWhere \\f$S\\f$ is size of output, input and filter.\nOutput is calculated in the same way as for convolution layer:\n\\f[out = \\sum_{i = 0}^{n}w_{i}x_{i} + b\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Norm","schema":{"attributes":[{"default":1,"description":" *alpha* represents the scaling parameter for the normalizing sum. For example, *alpha* equal 0.0001 means that the normalizing sum is multiplied by 0.0001.","name":"alpha","option":"required","type":" floating point positive number"},{"default":1,"description":" *beta* represents the exponent for the normalizing sum. For example, *beta* equal 0.75 means that the normalizing sum is raised to the power of 0.75.","name":"beta","option":"required","type":" floating point positive number"},{"default":1,"description":" *region* represents strategy of local regions extension. For example, *region* equal *across* means that the normalizing sum is performed over adjacent channels.","name":"region","option":"required","type":""},{"default":1,"description":" *local-size* represents the side length of the region to be used for the normalization sum or number of channels depending on the strategy specified in the *region* parameter. For example, *local-size* equal 5 for the across strategy means application of sum across 5 adjacent channels.","name":"local-size","option":"required","type":" positive integer bigger than zero"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/lrn.html)\n**Detailed description**: [Reference](http://yeephycho.github.io/2016/08/03/Normalizations-in-neural-networks/#Local-Response-Normalization-LRN)\n**Parameters**: *Norm* layer parameters should be specified in the `norm_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[o_{i} = \\left( 1 + \\left( \\frac{\\alpha}{n} \\right)\\sum_{i}x_{i}^{2} \\right)^{\\beta}\\f]\nWhere \\f$n\\f$ is the size of each local region.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Concat","schema":{"attributes":[{"description":" *axis* is the number of axis over which input blobs are concatenated. For example, *axis* equal 1 means that input blobs are concatenated over the first axis.","name":"axis","option":"required","type":"int32"}],"category":"Tensor","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/concat.html)\n**Parameters**: *Concat* layer parameters should be specified in the `concat_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Axis* parameter specifies a blob dimension to concat values. For example, for two input blobs *B1xC1xH1xW1* and *B2xC2xh4xW2* if axis: 1, output blob is****: *B1xC1+C2xH1xW1*. This is only possible if *B1=B2*, *H1=H4*, *W1=W2*.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Split","schema":{"attributes":[{"name":"axis","type":"int32"}],"category":"Tensor","description":"**Short description**: *Split* layer splits the input into several output groups. Group sizes are denoted by the number and the size of output ports.\n**Detailed description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/split.html)\n**Parameters**: *None*\n**Mathematical Formulation**\nSplits input blob among children. For example, blob is *BxC+CxHxW* and there are two children. Then, output blob is *BxCxHxW*.\n**Example**\n\n```html\n\n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Reshape","schema":{"attributes":[{"default":1,"description":" *axis* is the number of the starting axis for reshape. For example, *axis* equal 1 means that *Reshape* replaces dimensions starting from the next after the first dimension.","name":"axis","option":"required","type":"int32"},{"description":" *dim* is a set of numbers separated with comma, which denote the dimensions of output blob. For example, *dim* equal 88,1,71 means that output blob gets following dimensions: first dimension equals 88, second dimension equals 1, third dimension equals 71. For more information, refer to the **Description** block. If *dim* is equal to two numbers, it performs [flattening](http://caffe.berkeleyvision.org/tutorial/layers/flatten.html).","name":"dim","option":"required","type":"int32[]"},{"default":1,"description":" *num_axes* is the number of dimensions to be replaced with a reshaped blob starting from the dimension number specified in *axis* property. For example, *num_axes* equal 2 means that 2 dimensions are replaced with reshaped blob.","name":"num_axes","option":"required","type":"int32"}],"category":"Shape","description":"**Short description**: *Reshape* layer changes dimensions of the input blob according to the specified order. Input blob volume is equal to output blob volume, where volume is the product of dimensions.\n**Detailed description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/reshape.html)\n**Parameters**: *Reshape* layer parameters should be specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nIf you want to reshape input blob *BxCxHxW* into *Bx1x(C*H)xW*, the *dim* parameters of your layer should be:\n```html\n layer {\n name: \"reshape\"\n type: \"Reshape\"\n bottom: \"input\"\n top: \"output\"\n reshape_param {\n shape {\n dim: 0 # copy the dimension from below\n dim: 1\n dim: -1 # infer it from the other dimensions\n dim: 0\n }\n }\n }\n```\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Eltwise","schema":{"attributes":[{"default":"sum","description":" *operation* is the simple mathematical operation to be performed over inputs. For example, *operation* equal *mul* means that input blobs are multiplied.","name":"operation","option":"required","type":"string"}],"description":"**Short description**: *Eltwise* layer performs element-wise operation, which is specified in parameters, over given inputs.\n**Parameters**: *Eltwise* layer parameters should be specified in the `elementwise_data` node, which is placed as a child of the layer node.\n**Mathematical Formulation** *Eltwise* accepts 2 inputs of any number of dimensions - from 1 to 4, however, it is required for both of them to have absolutely same dimensions. The produced blob is also of the same dimension as each of its parents\n*Eltwise* does the following with the input blobs:\n\\f[\no_{i} = f(b_{i}^{1}, b_{i}^{2})\n\\f]\nwhere \\f$b_{i}^{1}\\f$ - first blob \\f$i\\f$-th element, \\f$b_{i}^{2}\\f$ - second blob \\f$i\\f$-th element, \\f$o_{i}\\f$ - output blob \\f$i\\f$-th element, \\f$f(a, b)\\f$ - is a function that performs an operation over its two arguments \\f$a, b\\f$.\n* For *sum* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = a + b\n \\f]\n* For *mul* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = a * b\n \\f]\n* For *max* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = \\left\\{\\begin{array}{ll}\n\t\ta \\quad \\mbox{if } a \\geq b \\\\\n\t\tb \\quad \\mbox{if } b > a\n\t\\end{array}\\right. \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ScaleShift","schema":{"category":"Layer","attributes":[],"description":"**Short description**: *ScaleShift* layer performs linear transformation of the input blobs. Weights denote scaling parameter, biases - a shift.\n**Parameters**: *ScaleShift* layer does not have additional parameters.\n**Mathematical Formulation**\n\\f[\no_{i} =\\gamma b_{i} + \\beta\n\\f]\n**Example**\n\n```\n\n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Crop","schema":{"attributes":[{"default":1,"description":" *axis* is a number of a dimension to be used for cropping. For example, *axis* equal to 1 means that cropping is performed over the first dimension.","name":"axis","option":"required","type":" a list of unique integers, where each element is greater than or equal to 0 and less than input shape length."},{"default":1,"description":" *offset* denotes the starting point for crop in the input blob. For example, *offset* equal to 2 means that crop is starting from the second value in the given axis.","name":"offset","option":"required","type":" a list of integers of the length equal to the length of *axis* attribute. In the list, `offset[i]` is greater than or equal to 0 and less than or equal to `input_shape[axis[i]] - crop_size[axis[i]]`, where `crop_size` is the shape of the second input."}],"category":"Data","description":"**Short description**: *Crop* layer changes selected dimensions of the input blob according to the specified parameters.\n**Parameters**: *Crop* layer parameters should be specified in `data` section, which is placed as a child of the layer node. Due to various representation of Crop attributes in existing frameworks, this layer can be described in three independent ways: *Crop* **Type 1** layer takes two input blobs, and the shape of the second blob specifies the *Crop* size. The layer has two attributes: *axis* and *offset*. Crop layer takes two input blobs, and the shape of the second blob specifies the *Crop* size. The *Crop* layer of this type supports shape inference.\n**Inputs**\n* **1**: Multidimensional input blob *(for example, NCHW, NCH, or NC)*\n* **2**: Shape of this input will be used for crop\n**Example**\n\n```html\n\n \n \n \n 1\n 21\n 44\n 44\n \n \n 1\n 21\n 34\n 34\n \n \n \n \n 1\n 21\n 34\n 34\n \n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"BatchNormalization","schema":{"attributes":[{"default":1,"description":" *epsilon* is the number to be added to the variance to avoid division by zero when normalizing the value. For example, *epsilon* equal 0.001 means that 0.001 is added to the variance.","name":"epsilon","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/batchnorm.html)\n**Detailed description**: [Reference](https://kratzert.github.io/2016/02/12/understanding-the-gradient-flow-through-the-batch-normalization-layer.html)\n**Parameters**: *BatchNormalization* layer parameters should be specified as the `batch_norm_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*BatchNormalization* is the normalization of the output in each hidden layer.\n* **Input**: Values of \\f$x\\f$ over a mini-batch:\n \\f[\n \\beta = \\{ x_{1...m} \\}\n \\f]\n* **Parameters to learn**: \\f$ \\gamma, \\beta\\f$\n* **Output**:\n \\f[\n \\{ o_{i} = BN_{\\gamma, \\beta} ( b_{i} ) \\}\n \\f]\n* **Mini-batch mean**:\n \\f[\n \\mu_{\\beta} \\leftarrow \\frac{1}{m}\\sum_{i=1}^{m}b_{i}\n \\f]\n* **Mini-batch variance**:\n \\f[\n \\sigma_{\\beta }^{2}\\leftarrow \\frac{1}{m}\\sum_{i=1}^{m} ( b_{i} - \\mu_{\\beta} )^{2}\n \\f]\n* **Normalize**:\n \\f[\n \\hat{b_{i}} \\leftarrow \\frac{b_{i} - \\mu_{\\beta}}{\\sqrt{\\sigma_{\\beta }^{2} + \\epsilon }}\n \\f]\n* **Scale and shift**:\n \\f[\n o_{i} \\leftarrow \\gamma\\hat{b_{i}} + \\beta = BN_{\\gamma ,\\beta } ( b_{i} )\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Normalize","schema":{"attributes":[{"default":1,"description":" *across_spatial* is a flag that denotes if normalization is performed over CHW or HW. For example, *across_spatial* equals 0 means that normalization is not shared across channels.","name":"across_spatial","option":"required","type":"\n * 0\n * 1 - not supported"},{"default":1,"description":" *channel_shared* is a flag that denotes if scale parameters are shared across channels. For example, *channel_shared* equal 0 means that scale parameters are not shared across channels.","name":"channel_shared","option":"required","type":"\n * 0 - scale parameters are not shared across channels\n * 1 - not supported"},{"default":1,"description":" *eps* is the epsilon used to avoid division by zero when normalizing the value. For example, *eps* equals 0.001 means that 0.001 is used if all the values in normalization are equal to zero.","name":"eps","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: *Normalize* layer performs l-p normalization of 1 of input blob.\n**Parameters**: *Normalize* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\no_{i} = \\sum_{i}^{H*W}\\frac{\\left ( n*C*H*W \\right )* scale}{\\sqrt{\\sum_{i=0}^{C*H*W}\\left ( n*C*H*W \\right )^{2}}}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Tile","schema":{"attributes":[{"default":1,"description":" *axis* is the index of the axis to tile. For example, *axis* equals 3 means that fourth axis is used for tiling.","name":"axis","option":"required","type":"int32"},{"description":" *tiles* is a size of the specified axis in the output blob. For example, *tiles* equal 88 means that output blob gets 88 copies of data from specified axis.","name":"tiles","option":"required","type":"int32"}],"description":"**Short description**: *Tile* layer extends input blob with copies of data along specific axis.\n**Detailed description**: [Reference](http://caffe.help/manual/layers/tile.html)\n**Parameters**: *Tile* layer parameters should be specified as the `tile_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Tile* extends input blobs and filling in output blobs following rules:\n\\f[\nout_i=input_i[inner\\_dim*t]\n\\f]\n\\f[\nt \\in \\left ( 0, \\quad tiles \\right )\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Permute","schema":{"attributes":[{"description":" *order* is the set of dimensions indexes for output blob. For example, *order* equal 0,2,3,1 means that the output blob has following dimensions: first dimension from the input blob, third dimension from the input blob, fourth dimension from the input blob, second dimension from the input blob.","name":"order","option":"required","type":"int32[]"}],"category":"Shape","description":"**Short description**: *Permute* layer performs reordering of input blob dimensions.\n**Detailed description**: [Reference](http://caffe.help/manual/layers/tile.html)\n**Parameters**: *Permute* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Permute* layer performs reordering input blob. Source indexes and destination indexes are bound by formula:\n\\f[\nsrc\\_ind_{offset} = n * ordered[1] * ordered[2] * ordered[3] + (h * ordered[3] + w)\n\\f]\n\\f[\nn \\in ( 0, order[0] )\n\\f]\n\\f[\nh \\in ( 0, order[2] )\n\\f]\n\\f[\nw \\in ( 0, order[3] )\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PriorBox","schema":{"attributes":[{"name":"min_size","option":"required","type":"float32"},{"name":"max_size","option":"required","type":"float32"},{"default":1,"description":" *aspect_ratio* is a variance of aspect ratios. Duplicate values are ignored. For example, *aspect_ratio* equal 2.000000,3.000000 means that for the first box aspect_ratio is equal to 2 and for the second box - 3.","name":"aspect_ratio","option":"required","type":"float32"},{"default":false,"description":" *flip* is a flag that denotes that each *aspect_ratio* is duplicated and flipped. For example, *flip* equals 1 and *aspect_ratio* equals 3 mean that aspect_ratio is equal to 1/3.","name":"flip","option":"required","type":"boolean"},{"default":false,"description":" *clip* is a flag that denotes if each value in the output blob is within [0,1]. For example, *clip* equal 1 means that each value in the output blob is within [0,1].","name":"clip","option":"required","type":"boolean"},{"description":" *step* is a distance between box centers. For example, *step* equal 85 means that the distance between neighborhood prior boxes centers is 85.","name":"step","option":"required","type":"float32"},{"default":0.5,"description":" *offset* is a shift of box respectively to top left corner. For example, *offset* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"offset","option":"required","type":"float32"},{"description":" *variance* denotes a variance of adjusting bounding boxes. For example, *variance* equals 85 means that the shift of neighborhood prior boxes centers is 85.","name":"variance","option":"required","type":"float32[]"},{"default":1,"description":" *scale_all_sizes* is a flag that denotes type of inference. For example, *scale_all_sizes* equals 0 means that priorbox layer is inferd in MXNet-like manner. In particular, *max_size* parameter is ignored.","name":"scale_all_sizes","option":"required","type":"int32"}],"description":"**Short description**: *PriorBox* layer generates prior boxes of specified sizes and aspect ratios across all dimensions.\n**Parameters**: *PriorBox* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**:\n*PriorBox* computes coordinates of prior boxes by following:\n1. First calculates *center_x* and *center_y* of prior box:\n \\f[\n W \\equiv Width \\quad Of \\quad Image\n \\f]\n \\f[\n H \\equiv Height \\quad Of \\quad Image\n \\f]\n * If step equals 0:\n \\f[\n center_x=(w+0.5)\n \\f]\n \\f[\n center_y=(h+0.5)\n \\f]\n * else:\n \\f[\n center_x=(w+offset)*step\n \\f]\n \\f[\n center_y=(h+offset)*step\n \\f]\n \\f[\n w \\subset \\left( 0, W \\right )\n \\f]\n \\f[\n h \\subset \\left( 0, H \\right )\n \\f]\n2. Then, for each \\f$ s \\subset \\left( 0, min_sizes \\right ) \\f$ calculates coordinates of priorboxes:\n \\f[\n xmin = \\frac{\\frac{center_x - s}{2}}{W}\n \\f]\n \\f[\n ymin = \\frac{\\frac{center_y - s}{2}}{H}\n \\f]\n \\f[\n xmax = \\frac{\\frac{center_x + s}{2}}{W}\n \\f]\n \\f[\n ymin = \\frac{\\frac{center_y + s}{2}}{H}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"SimplerNMS","schema":{"attributes":[{"default":1,"description":" *pre_nms_topn (post_nms_topn)* is the quantity of bounding boxes before (after) applying NMS operation. For example, *pre_nms_topn (post_nms_topn)* equals 15 means that the minimum (maximum) box size is 15.","name":"pre_nms_topn (post_nms_topn)","option":"required","type":"int32"},{"default":1,"description":" *cls_threshold* is the minimum value of the proposal to be taken into consideration. For example, *cls_threshold* equal 0.5 means that all boxes with prediction probability less than 0.5 are filtered out.","name":"cls_threshold","option":"required","type":"float32"},{"default":1,"description":" *iou_threshold* is the minimum ratio of boxes overlapping to be taken into consideration. For example, *iou_threshold* equal 0.7 means that all boxes with overlapping ratio less than 0.7 are filtered out.","name":"iou_threshold","option":"required","type":"float32"},{"default":1,"description":" *feat_stride* is the step size to slide over boxes (in pixels). For example, *feat_stride* equal 16 means that all boxes are analyzed with the slide 16.","name":"feat_stride","option":"required","type":"int32"},{"default":1,"description":" *min_bbox_size* is the minimum size of box to be taken into consideration. For example, *min_bbox_size* equal 35 means that all boxes with box size less than 35 are filtered out.","name":"min_bbox_size","option":"required","type":"int32"},{"default":1,"description":" *scale* is array of scales for anchor boxes generating.","name":"scale","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *SimplerNMS* layer performs filtering of bounding boxes and outputs only those with the highest confidence of prediction.\n**Parameters**: *SimplerNMS* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*SimplerNMS* accepts three inputs with four dimensions. Produced blob has two dimensions, the first one equals *post_nms_topn*.\n*SimplerNMS* does the following with the input blob:\n1. Generates initial anchor boxes. Left top corner of all boxes is (0, 0). Width and height of boxes are calculated based on scaled (according to the scale parameter) default widths and heights\n2. For each point in the first input blob:\n * pins anchor boxes to picture according to the second input blob, which contains four deltas for each box: for x and y of center, for width, and for height\n * finds out score in the first input blob\n3. Filters out boxes with size less than *min_bbox_size.*\n4. Sorts all proposals (*box, score*) by score from highest to lowest\n5. Takes top *pre_nms_topn* proposals\n6. Calculates intersections for boxes and filters out all with \\f$intersection/union > iou\\_threshold\\f$\n7. Takes top *post_nms_topn* proposals\n8. Returns top proposals\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"DetectionOutput","schema":{"attributes":[{"default":1,"description":" number of classes to be predicted","name":"num_classes","option":"required","type":"int32"},{"default":1,"description":" background label id. If there is no background class, set it to -1.","name":"background_label_id","option":"required","type":"int32"},{"default":1,"description":" maximum number of results to be kept on NMS stage","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if \"true\", variance is encoded in target. Otherwise, we need to adjust the predicted offset accordingly.","name":"variance_encoded_in_target","option":"required","type":" logical values"},{"default":1,"description":" number of total bboxes to be kept per image after NMS step. -1 means keeping all bboxes after NMS step.","name":"keep_top_k","option":"required","type":"int32"},{"default":1,"description":null,"name":"num_orient_classes","option":"required","type":"int32"},{"default":1,"description":" type of coding method for bounding boxes. caffe.PriorBoxParameter.CENTER_SIZE and others.","name":"code_type","option":"required","type":"int32"},{"default":1,"description":" bounding boxes are shared among different classes.","name":"share_location","option":"required","type":" logical values"},{"default":1,"description":null,"name":"interpolate_orientation","option":"required","type":"int32"},{"default":1,"description":" threshold to be used in NMS stage","name":"nms_threshold","option":"required","type":"float32"},{"default":1,"description":" only consider detections whose confidences are larger than a threshold. If not provided, consider all boxes.","name":"confidence_threshold","option":"required","type":"float32"}],"description":"**Short description**: *DetectionOutput* layer performs non-maximum suppression to generate the detection output using information on location and confidence predictions.\n**Detailed description**: [Reference](https://arxiv.org/pdf/1512.02325.pdf)\n**Parameters**: *DetectionOutput* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nAt each feature map cell, *DetectionOutput* predicts the offsets relative to the default box shapes in the cell, as well as the per-class scores that indicate the presence of a class instance in each of those boxes. Specifically, for each box out of k at a given location, *DetectionOutput* computes class scores and the four offsets relative to the original default box shape. This results in a total of \\f$(c + 4)k\\f$ filters that are applied around each location in the feature map, yielding \\f$(c + 4)kmn\\f$ outputs for a m × n feature map.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Memory","schema":{"attributes":[{"default":1,"description":" *id* is the id of the pair of *Memory* layers. For example, *id* equals r_27-28 means that layers with id 27 and 28 are in one pair.","name":"id","option":"required","type":"int32"},{"default":1,"description":" *index* represents if the given layer is input or output. For example, *index* equal 0 means this layer is output one.","name":"index","option":"required","type":"int32"},{"default":1,"description":" *size* represents the size of the group. For example, *size* equals 2 means this group is a pair.","name":"size","option":"required","type":"int32"}],"description":"**Short description**: *Memory* layer represents delay layer in terms of LSTM terminology. To read more about LSTM topologies please refer this [link](http://colah.github.io/posts/2015-08-Understanding-LSTMs).\n**Detailed description**: *Memory* layer saves state between two infer requests. In the topology, it is the single layer, however, in the Intermediate Representation, it is always represented as a pair of **Memory** layers. One of these layers does not have outputs and another does not have inputs (in terms of the Intermediate Representation).\n**Parameters**: *Memory* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Memory* save data from the input blob.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Clamp","schema":{"attributes":[{"default":0,"description":" *min* is the lower bound of values in the output shape. Any value in the input shape that is smaller than the bound, is replaced by the *min* value. For example, *min* equal 10 means that any value in the input shape that is smaller than the bound, is replaced by 10.","name":"min","option":"required","type":"int32"},{"default":1,"description":" *max* is the upper bound of values in the output shape. Any value in the input shape that is greater than the bound, is replaced by the *max* value. For example, *max* equals 50 means that any value in the input shape that is greater than the bound, is replaced by 50.","name":"max","option":"required","type":"int32"}],"description":"**Short description**: *Clamp* layer represents clipping activation operation.\n**Detailed description**: [Reference](https://www.tensorflow.org/versions/r1.2/api_docs/MO_DG/prepare_model/python/tf/clip_by_value)\n**Parameters**: *Clamp* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Clamp* generally does the following with the input blobs:\n\\f[\nout_i=\\left\\{\\begin{array}{ll}\n\tmax\\_value \\quad \\mbox{if } \\quad input_i>max\\_value \\\\\n\tmin\\_value \\quad \\mbox{if } \\quad input_i\n\\end{array}\\right.\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ArgMax","schema":{"attributes":[{"default":1,"description":" if *out_max_val* equals 1, output is a vector of pairs *(max_ind, max_val)*, unless axis is set. Then output is *max_val* along the specified axis.","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if *out_max_val* equals 1, output is a vector of pairs *(max_ind, max_val)*, unless axis is set. Then output is *max_val* along the specified axis.","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if set, maximizes along the specified axis, else maximizes the flattened trailing dimensions for each index of the first / num dimension.","name":"axis","option":"required","type":"int32"}],"description":"**Short description**: *ArgMax* layer compute the index of the *K* maximum values for each datum across all dimensions *CxHxW*.\n**Detailed description**: Intended for use after a classification layer to produce a prediction. If parameter *out_max_val* is set to \"true\", output is a vector of pairs *(max_ind, max_val)* for each image. The *axis* parameter specifies an axis along which to maximize.\n**Parameters**: *ArgMax* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*ArgMax* generally does the following with the input blobs:\n\\f[\no_{i} = \\left\\{\nx| x \\in S \\wedge \\forall y \\in S : f(y) \\leq f(x)\n\\right\\}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PSROIPooling","schema":{"attributes":[{"default":1,"description":" pooled output channel number","name":"output_dim","option":"required","type":"int32"},{"default":1,"description":" number of groups to encode position-sensitive score maps","name":"group_size","option":"required","type":"int32"},{"default":1,"description":" multiplicative spatial scale factor to translate ROI coordinates from their input scale to the scale used when pooling","name":"spatial_scale","option":"required","type":"float32"}],"category":"Pool","description":"**Short description**: *PSROIPooling* layer compute position-sensitive max pooling on regions of interest specified by input, takes as input N position-sensitive score maps and a list of R regions of interest.\n**Detailed description**: [Reference](https://arxiv.org/pdf/1703.06211.pdf)\n**Parameters**: *PSRoiPooling* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nThe output value for \\f$(i, j)\\f$-th bin is obtained by summation from one score map \\f$x_{i,j}\\f$ corresponding to that bin. In short, the difference from *RoIPooling* is that a general feature map \\f$x\\f$ is replaced by a specific positive-sensitive score map \\f$x_{i,j}\\f$.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"GRN","schema":{"attributes":[{"default":1,"description":" *bias* is added to the variance.","name":"bias","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: *GRN* is Global Response Normalization with L2 norm (across channels only).\n**Parameters**: GRN layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*GRN* computes L2 norm by channels for input blob. *GRN* generally does the following with the input blob:\n\\f[\noutput_{i} = \\frac{input_{i}}{\\sqrt{\\sum_{i}^{C} input_{i}}}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PReLU","schema":{"attributes":[{"default":1,"description":" *channel_shared* shows if negative slope shared across channels or not.","name":"channel_shared","option":"required","type":"int32"},{"description":" *filler_type* defines initialization type for negative slope.","name":"filler_type","option":"required","type":"string"},{"default":1,"description":" *filler_value* defines the value in constant filler.","name":"filler_value","option":"required","type":"int32"},{"default":1,"description":" *min(max)* defines the minimal(maximal) value in uniform filler.","name":"min(max)","option":"required","type":"int32"},{"default":1,"description":" *mean* defines the mean value in Gaussian filler.","name":"mean","option":"required","type":"int32"}],"category":"Activation","description":"**Short description**: *PReLU* is the Parametric Rectifier Linear Unit. The difference from *ReLU* is that negative slopes can vary across channels.\n**Parameters**: *PReLU* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*PReLU* accepts one input with four dimensions. The produced blob has the same dimensions as input.\n*PReLU* does the following with the input blob:\n\\f[\no_{i} = max(0, x_{i}) + w_{i} * min(0,x_{i})\n\\f]\nwhere \\f$w_{i}\\f$ is from weights blob.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"RegionYolo","schema":{"attributes":[{"default":1,"description":" *coords* is num coordinates for each region","name":"coords","option":"required","type":"int32"},{"default":1,"description":" *classes* is num classes for each region","name":"classes","option":"required","type":"int32"},{"default":1,"description":" *num* is number of regions","name":"num","option":"required","type":"int32"},{"default":1,"description":" *do_softmax* is a flag which specifies the method of infer","name":"do_softmax","option":"required","type":"int32"},{"default":1,"description":" *anchors* coordinates regions","name":"anchors","option":"required","type":"float32[]"},{"default":1,"description":" *mask* specifies which anchors to use","name":"mask","option":"required","type":"int32"},{"default":1,"description":" *mask* specifies which anchors to use","name":"mask","option":"required","type":"int32"},{"default":1,"description":" *axis* is the number of the dimension from which flattening is performed. For example, *axis* equals 1 means that flattening is started from the 1st dimension.","name":"axis","option":"required","type":"int32"},{"default":1,"description":" *end_axis* is the number of the dimension on which flattening is ended. For example, *end_axis* equals -1 means that flattening is performed till the last dimension.","name":"end_axis","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *RegionYolo* computes coordinates of regions with probability for each class.\n**Detailed description**: [Reference][p_yolo]\n**Parameters**: *RegionYolo* layer parameters should be specified as the `data` node, which is a child of the `layer` node.\n**Example**\n\n```html\n\n \n ... \n ... \n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ReorgYolo","schema":{"attributes":[{"default":1,"description":" *stride* is distance of cut throws in output blobs.","name":"stride","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *ReorgYolo* reorganizes input blob taking into account strides.\n**Detailed description**: [Reference][p_yolo]\n**Parameters**: *ReorgYolo* layer parameters should be specified as the `data` node, which is a child of the `layer` node.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PriorBoxClustered","schema":{"attributes":[{"description":" *width* is a parameter that specifies desired boxes widths in pixels.","name":"width","option":"required","type":"float32[]"},{"name":"height","option":"required","type":"float32[]"},{"default":false,"description":" *clip* is a flag that denotes if each value in the output blob is within [0,1]. For example, *clip* equal 1 means that each value in the output blob is within [0,1].","name":"clip","option":"required","type":"boolean"},{"default":false,"description":" *flip* is a flag that denotes whether the list of boxes is augmented with the flipped ones.","name":"flip","option":"required","type":"boolean"},{"description":" *step* is a distance between box centers. For example, *step* equal 85 means that the distance between neighborhood prior boxes centers is 85.","name":"step","option":"required","type":"float32"},{"name":"step_w","option":"required","type":"float32"},{"name":"step_h","option":"required","type":"float32"},{"default":1,"description":" *offset* is a shift of box respectively to top left corner. For example, *offset* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"offset","option":"required","type":"float32"},{"description":" *variance* denotes a variance of adjusting bounding boxes. For example, *variance* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"variance","option":"required","type":"float32[]"},{"description":" *img_h* specifies height of input image. These parameters are calculated unless provided explicitly.","name":"img_h","option":"required","type":"float32"},{"name":"img_w","option":"required","type":"float32"}],"description":"**Short description**: *PriorBoxClustered* layer generates prior boxes of specified sizes.\n**Parameters**: *PriorBoxClustered* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*PriorBoxClustered* computes coordinates of prior boxes by following:\n1. Calculates the *center_x* and *center_y* of prior box:\n \\f[\n W \\equiv Width \\quad Of \\quad Image\n \\f]\n \\f[\n H \\equiv Height \\quad Of \\quad Image\n \\f]\n \\f[\n center_x=(w+offset)*step\n \\f]\n \\f[\n center_y=(h+offset)*step\n \\f]\n \\f[\n w \\subset \\left( 0, W \\right )\n \\f]\n \\f[\n h \\subset \\left( 0, H \\right )\n \\f]\n2. For each \\f$s \\subset \\left( 0, W \\right )\\f$ calculates the prior boxes coordinates:\n \\f[\n xmin = \\frac{center_x - \\frac{width_s}{2}}{W}\n \\f]\n\t\\f[\n\tymin = \\frac{center_y - \\frac{height_s}{2}}{H}\n\t\\f]\n\t\\f[\n\txmax = \\frac{center_x - \\frac{width_s}{2}}{W}\n\t\\f]\n\t\\f[\n\tymax = \\frac{center_y - \\frac{height_s}{2}}{H}\n\t\\f]\nIf *clip* is defined, the coordinates of prior boxes are recalculated with the formula:\n\\f$coordinate = \\min(\\max(coordinate,0), 1)\\f$\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"MVN","schema":{"attributes":[{"default":1,"description":" *across_channels* is a flag that denotes if mean values are shared across channels. For example, *across_channels* equal 0 means that mean values are not shared across channels.","name":"across_channels","option":"required","type":"int32"},{"default":1,"description":" *normalize_variance* is a flag that denotes whether to perform variance normalization.","name":"normalize_variance","option":"required","type":"int32"},{"default":1,"description":" *eps* is the number to be added to the variance to avoid division by zero when normalizing the value. For example, *epsilon* equal 0.001 means that 0.001 is added to the variance.","name":"eps","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/mvn.html)\n**Parameters**: *MVN* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*MVN* subtracts mean from the input blob:\n\\f[\no_{i} = i_{i} - \\frac{\\sum{i_{k}}}{C * H * W}\n\\f]\nIf *normalize_variance* is set to 1, the output blob is divided by variance:\n\\f[\no_{i}=\\frac{o_{i}}{\\sum \\sqrt {o_{k}^2}+\\epsilon}\n\\f]\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"CTCGreadyDecoder","schema":{"attributes":[{"default":1,"description":" *ctc_merge_repeated* is a flag for collapsing the repeated labels during the ctc calculation.","name":"ctc_merge_repeated","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *CTCGreadyDecoder* performs greedy decoding on the logits given in input (best path).\n**Detailed description**: [Reference](https://www.tensorflow.org/api_docs/python/tf/nn/ctc_greedy_decoder)\n**Parameters**: *CTCGreadyDecoder* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nGiven an input sequence \\f$X\\f$ of length \\f$T\\f$, *CTCGreadyDecoder* assumes the probability of a length \\f$T\\f$ character sequence \\f$C\\f$ is given by\n\\f[\np(C|X) = \\prod_{t=1}^{T} p(c_{t}|X)\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Proposal","schema":{"attributes":[{"default":1,"description":" *pre_nms_topn (post_nms_topn)* is the quantity of bounding boxes before (after) applying NMS operation. For example, *pre_nms_topn (post_nms_topn)* equal 15 means that the minimum (maximum) box size is 15.","name":"pre_nms_topn (post_nms_topn)","option":"required","type":"int32"},{"default":1,"description":" *nms_thresh* is the minimum value of the proposal to be taken into consideration. For example, *nms_thresh* equal 0.5 means that all boxes with prediction probability less than 0.5 are filtered out.","name":"nms_thresh","option":"required","type":"float32"},{"default":1,"description":" *feat_stride* is the step size to slide over boxes (in pixels). For example, *feat_stride* equal 16 means that all boxes are analyzed with the slide 16.","name":"feat_stride","option":"required","type":"int32"},{"default":1,"description":" *min_size* is the minimum size of box to be taken into consideration. For example, *min_size* equal 35 means that all boxes with box size less than 35 are filtered out.","name":"min_size","option":"required","type":"int32"},{"default":1,"description":" *ratio* is the ratios for anchor generation.","name":"ratio","option":"required","type":"float32[]"},{"default":1,"description":" *ratio* is the ratios for anchor generation.","name":"ratio","option":"required","type":"float32[]"},{"default":1,"description":" *scale* is the scales for anchor generation.","name":"scale","option":"required","type":"float32[]"}],"category":"Layer","description":"**Short description**: *Proposal* layer performs filtering of only those bounding boxes and outputs with the highest confidence of prediction.\n**Parameters**: Proposal layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Proposal* layer accepts three inputs with four dimensions. The produced blob has two dimensions: first one equals *batch_size * post_nms_topn*.\n*Proposal* does the following with the input blob:\n1. Generates initial anchor boxes Left top corner of all boxes in (0, 0). Width and height of boxes are calculated from *base_size* with scale and ratio parameters\n2. For each point in the first input blob:\n * pins anchor boxes to the image according to the second input blob that contains four deltas for each box: for *x* and *y* of center, for *width* and for *height*\n * finds out score in the first input blob\n3. Filters out boxes with size less than *min_size*\n4. Sorts all proposals (*box*, *score*) by score from highest to lowest\n5. Takes top *pre_nms_topn* proposals\n6. Calculates intersections for boxes and filter out all with \\f$intersection/union > nms\\_thresh\\f$\n7. Takes top *post_nms_topn* proposals\n8. Returns top proposals\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Resample","schema":{"attributes":[{"default":1,"description":" *type* parameter specifies type of blob interpolation.","name":"type","option":"required","type":"\n * *LINEAR* - linear blob interpolation\n * *CUBIC* - cubic blob interpolation\n * *NEAREST* - nearest-neighbor blob interpolation"},{"default":1,"description":" *antialias* is a flag that denotes whether to perform anti-aliasing.","name":"antialias","option":"required","type":"\n * 0 - anti-aliasing is not performed\n * 1 - anti-aliasing is performed"}],"category":"Layer","description":"**Short description**: *Resample* layer scales the input blob by the specified parameters.\n**Parameters**: Resample layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n​\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Power","schema":{"attributes":[],"description":"**Short description**: *Power* layer computes the output as (shift + scale * x) ^ power for each input element x.\n**Parameters**: Power layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\np = (shift + scale * x)^{power}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Flatten","schema":{"category":"Shape","attributes":[{"name":"axis","type":"int32"},{"name":"end_axis","type":"int32","default":-1}]}},{"name":"Pad","schema":{"category":"Tensor","attributes":[{"name":"pad_value","type":"float32"},{"name":"pads_begin","type":"int32[]"},{"name":"pads_end","type":"int32[]"},{"name":"pad_mode"}]}},{"name":"GRUCell","schema":{"category":"Layer"}},{"name":"LSTMCell","schema":{"category":"Layer"}},{"name":"MaxPool","schema":{"category":"Pool"}},{"name":"Transpose","schema":{"category":"Transform"}},{"name":"Squeeze","schema":{"category":"Transform"}},{"name":"Unsqueeze","schema":{"category":"Transform"}},{"name":"Gather","schema":{"category":"Transform"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino.js new file mode 100644 index 0000000000000000000000000000000000000000..5b2a3972d3615afc7cf8b386d2cfb9da3762ec47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/openvino.js @@ -0,0 +1 @@ +var openvino=openvino||{},base=base||require("./base"),long=long||{Long:require("long")};openvino.ModelFactory=class{match(t){const e=t.identifier,n=e.split(".").pop().toLowerCase();if("xml"===n&&t.text.includes("6&&s.every(((t,e)=>t==n[e])))return!1;if(n.length>4){const t=n[0]|n[1]<<8|n[2]<<16|n[3]<<24;if(0===t||1===t||19950407===t||871224===t||180310===t)return!1}return!0}return!1}open(t,e){const n=t.identifier;switch(n.split(".").pop().toLowerCase()){case"xml":return t.request(n.substring(0,n.length-4)+".bin",null).then((s=>this._openModel(n,e,t.text,s))).catch((()=>this._openModel(n,e,t.text,null)));case"bin":return t.request(n.substring(0,n.length-4)+".xml","utf-8").then((s=>this._openModel(n,e,s,t.buffer))).catch((t=>{e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new openvino.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}))}}_openModel(t,e,n,s){return openvino.Metadata.open(e).then((i=>{try{let o=!1;const a=new DOMParser({errorHandler:()=>{o=!0}}).parseFromString(n,"text/xml");if(o||null==a.documentElement||a.getElementsByTagName("parsererror").length>0)throw new openvino.Error("File format is not OpenVINO.");if(!a.documentElement||"net"!=a.documentElement.nodeName)throw new openvino.Error("File format is not OpenVINO IR.");const r=openvino.XmlReader.read(a.documentElement),u=new openvino.Model(i,r,s);return r.disconnectedLayers&&e.exception(new openvino.Error("Graph contains not connected layers "+JSON.stringify(r.disconnectedLayers)+" in '"+t+"'.")),u}catch(n){e.exception(n,!1);const s=n&&n.message?n.message:n.toString();throw new openvino.Error(s.replace(/\.$/,"")+" in '"+t+"'.")}}))}},openvino.Model=class{constructor(t,e,n){this._name=e.name||"",this._graphs=[new openvino.Graph(t,e,n)]}get name(){return this._name}get format(){return"OpenVINO IR"}get graphs(){return this._graphs}},openvino.Graph=class{constructor(t,e,n){this._name=e.name||"",this._nodes=[],this._inputs=[],this._outputs=[],this._arguments={};for(const s of this._const(e.layers,e.edges)){const i=s.inputs.map((t=>this._argument(s.id,s.precision,t,e.edges))),o=s.outputs.map((t=>this._argument(s.id,t.precision||s.precision,t,null)));switch(s.type){case"Input":{const t=s.name||"";this._inputs.push(new openvino.Parameter(t,o));break}default:this._nodes.push(new openvino.Node(this,t,n,s,i,o))}}this._replaceTensorIteratorWithSubgraph(t,n,e.layers,e.edges),delete this._arguments;const s=new Set;for(const t of this._nodes)for(const e of t.outputs)for(const t of e.arguments)s.add(t.name);for(const t of this.inputs)for(const e of t.arguments)s.add(e.name);const i=new Set;for(const t of this._nodes)for(const e of t.inputs)for(const n of e.arguments)n.initializer||s.has(n.name)||i.add(t);0!==i.size&&(e.disconnectedLayers=Array.from(i).map((t=>t.name)))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}_argument(t,e,n,s){let i=t+":"+n.id;s&&(i=s[i]);let o=this._arguments[i];if(!o){const t=0==n.dims.length?null:new openvino.TensorShape(n.dims);o=new openvino.Argument(i,new openvino.TensorType(e,t),null)}return o}_replaceTensorIteratorWithSubgraph(t,e,n,s){const i=n.filter((t=>"TensorIterator"===t.type));for(const n of i){const i=n.id,o=this._nodes.find((t=>t._id===i)),a=n.body.layers,r=n.body.edges,u=n.back_edges,p=Object.assign({},r,u),l=n.port_map;for(const n of this._const(a,p,u)){const s=n.inputs.map((t=>this._argument(n.id,n.precision,t,p))),o=n.outputs.map((t=>this._argument(n.id,n.precision||t.precision,t,null))),a=new openvino.Node(this,t,e,n,s,o);a._id=i+"_"+n.id;for(const t of a._inputs)for(const e of t.arguments)e.name&&(e._name=i+"_"+e.name);for(const t of a._outputs)for(const e of t.arguments)e.name&&(e._name=i+"_"+e.name);this._nodes.push(a)}for(const t of l.input){const e=this._nodes.find((e=>e._id===i+"_"+t.internal_layer_id)),n=s[i+":"+t.external_port_id];if(n){const t=n.split(":"),s=t[0],i=t[1];if(this._nodes.find((t=>t._id===s))){if(!e._inputs)throw new openvino.Error("Tensor Iterator node with name '"+e._id+"' does not have inputs.");const t=s+":"+i,n=e._inputs.find((t=>Boolean(t.arguments.find((t=>!t.name)))));if(n){const e=n._arguments.find((t=>!t._name));e&&(e._name=t)}else e._inputs.push(new openvino.Parameter((e._inputs.length+1).toString(),[new openvino.Argument(t,null,null)]))}else{const t=o._inputs.find((t=>"input"===t._name));if(!t)return;const n=e._inputs.find((t=>Boolean(t.arguments.find((t=>!t.name)))));if(n){const e=n.arguments.find((t=>!t.name));e&&(e._name=t.arguments[0].name)}}}}for(const t of l.output){const e=this._nodes.find((e=>e._id===`${i}_${t.internal_layer_id}`)),n=i+":"+t.external_port_id,o=Object.keys(s).filter((t=>s[t]===n));for(const t of o){const n=t.split(":")[0],s=this._nodes.find((t=>t._id===n));if(s._inputs&&(!s._inputs||0!==s._inputs.length)&&e._outputs&&e._outputs[0])for(const t of s._inputs)for(const n of t._arguments){if(!n.name||n.name&&n.name.split(":")[0]!==i)continue;const t=e.outputs[0].arguments[0].name.split(":")[1];n._name=e.id+":"+t}}}this._nodes=this._nodes.filter((t=>t.id!==n.id))}}_const(t,e,n){const s=[];n=n||{},t=t.slice();for(const e of t){if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length&&0===e.blobs.length&&e.data&&e.data.length>3){const t={};for(const n of e.data)t[n.name]=n.value;if(t.element_type&&t.offset&&t.size){const n=t.element_type;let s=null;switch(n){case"f16":s="FP16";break;case"f32":s="FP32";break;default:s=n.toUpperCase()}const i=t.shape?t.shape.split(",").map((t=>parseInt(t.trim(),10))):null;e.data=[],e.blobs.push({name:"custom",precision:s,offset:parseInt(t.offset,10),size:parseInt(t.size,10),shape:i})}}"Const"===e.type&&1===e.blobs.length&&!e.blobs[0].shape&&0===e.inputs.length&&1===e.outputs.length&&e.outputs[0].dims&&(e.blobs[0].shape=e.outputs[0].dims)}const i=new Map;for(const e of t)if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length){const t=e.id+":"+e.outputs[0].id;i.set(t,{layer:e,counter:0})}for(const t of Object.keys(e)){const n=e[t];i.has(n)&&i.get(n).counter++}if(n)for(const t of Object.keys(n)){const e=n[t];i.has(e)&&i.get(e).counter++}for(const t of i)1!==t[1].counter&&i.delete(t[0]);for(const s of t)if(0===s.blobs.length)for(let t=s.inputs.length-1;t>0;t--){const o=s.inputs[t],a=s.id+":"+o.id,r=e[a]||n[a];if(!i.has(r))break;const u=i.get(r).layer,p=u.blobs[0];p&&(p.id=u.name||u.id,p.kind="Const",s.blobs.push(p),s.inputs.splice(t,1),i.get(r).layer=null,i.get(r).delete=!0)}for(;t.length>0;){const e=t.shift();if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length){const t=e.id+":"+e.outputs[0].id;if(i.has(t)&&i.get(t).delete)continue}s.push(e)}return s}},openvino.Node=class{constructor(t,e,n,s,i,o){this._metadata=e,this._type=s.type,this._name=s.name||"",this._id=s.id,this._inputs=[],this._outputs=[],this._initializers=[],this._attributes=[];const a=s.precision;let r=0;for(const t of i){const e=0==r?"input":r.toString();this._inputs.push(new openvino.Parameter(e,[t])),r++}let u=0;for(const t of o){const e=0==u?"output":u.toString();this._outputs.push(new openvino.Parameter(e,[t])),u++}const p={};for(const t of s.data){p[t.name]=t.value;const n=e.attribute(this.type,t.name);this._attributes.push(new openvino.Attribute(n,t.name,t.value))}for(const t of s.blobs){const e=t.name,s=t.offset,i=t.size,o=n&&s+i<=n.length?n.slice(s,s+i):null;let r=t.shape||null;const u=t.kind||"Blob",l=t.id||"",h=t.precision||a,c={FP16:2,FP32:4,I8:1,I16:2,I32:4,I64:8,U8:1,U16:2,U32:4,U64:8}[h];if(c)switch(this._type+":"+e){case"FullyConnected:weights":{const t=parseInt(p["out-size"],10);r=[i/(t*c),t];break}case"FullyConnected:biases":r=[parseInt(p["out-size"],10)];break;case"Convolution:weights":case"Deconvolution:weights":{const t=this.inputs[0].arguments[0].type.shape.dimensions[1],e=parseInt(p.group||"1",10),n=p["kernel-x"]&&p["kernel-y"]?[parseInt(p["kernel-x"],10),parseInt(p["kernel-y"],10)]:p.kernel.split(",").map((t=>parseInt(t.trim(),10))),s=parseInt(p.output,10);r=[Math.floor(t/e),s].concat(n);break}case"ScaleShift:weights":case"ScaleShift:biases":case"Convolution:biases":case"Normalize:weights":case"PReLU:weights":r=[Math.floor(i/c)];break;case"Const:custom":this._outputs.length>0&&this._outputs[0].arguments.length>0&&this._outputs[0].arguments[0].type&&this._outputs[0].arguments[0].type.shape&&this._outputs[0].arguments[0].type.shape.dimensions&&(r=this._outputs[0].arguments[0].type.shape.dimensions)}const d=r?new openvino.TensorShape(r):null;this._initializers.push(new openvino.Parameter(e,[new openvino.Argument(l,null,new openvino.Tensor(h,d,o,u))]))}}get id(){return this._id}get name(){return this._name}get device(){return this._device||""}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs.concat(this._initializers)}get outputs(){return this._outputs}},openvino.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},openvino.Argument=class{constructor(t,e,n){this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},openvino.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,t){if(Object.prototype.hasOwnProperty.call(t,"type"))switch(this._type=t.type,t.type){case"boolean":switch(n){case"1":case"true":this._value=!0;break;case"0":case"false":this._value=!1}break;case"int32":{const t=Number.parseInt(this._value,10);this._value=Number.isNaN(this._value-t)?n:t;break}case"float32":case"float64":{const t=Number.parseFloat(this._value);this._value=Number.isNaN(this._value-t)?n:t;break}case"int32[]":if(this._value.length>2){let t=[];this._value.split(",").map((e=>{e=e.trim();const n=Number.parseInt(e,10);Number.isNaN(e-n)?t=null:null!=t&&t.push(n)})),null!=t&&(this._value=t)}break;case"float32[]":if(this._value.length>2){let t=[];this._value.split(",").map((e=>{e=e.trim();const n=Number.parseFloat(e);Number.isNaN(e-n)?t=null:null!=t&&t.push(n)})),null!=t&&(this._value=t)}}if(Object.prototype.hasOwnProperty.call(t,"visible")&&0==t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){let e=t.default;if(this._value==e)this._visible=!1;else if(Array.isArray(this._value)&&Array.isArray(e)){if(e=e.slice(0,e.length),e.length>1&&null==e[e.length-1])for(e.pop();e.lengtht==e[n]))&&(this._visible=!1)}}}}get name(){return this._name}get value(){return this._value}get type(){return this._type}get visible(){return 0!=this._visible}},openvino.Tensor=class{constructor(t,e,n,s){this._data=n,this._type=new openvino.TensorType(t,e),this._kind=s}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return openvino.Tensor._stringify(e,""," ")}_context(){const t={state:null};return this._data?this._type.shape?(t.index=0,t.count=0,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t):(t.state="Tensor shape is not defined.",t):(t.state="Tensor data is empty.",t)}_decode(t,e){const n=0==t.shape.length?[1]:t.shape,s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"int8":s.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":s.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"uint8":s.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"uint16":s.push(t.data.getUint16(t.index,!0)),t.index+=2,t.count++;break;case"uint32":s.push(t.data.getUint32(t.index,!0)),t.index+=4,t.count++;break;case"uint64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!0)),t.index+=8,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}static _stringify(t,e,n){if(Array.isArray(t)){const s=[];s.push(e+"[");const i=t.map((t=>openvino.Tensor._stringify(t,e+n,n)));return i.length>0&&s.push(i.join(",\n")),s.push(e+"]"),s.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},openvino.TensorType=class{constructor(t,e){switch(t=t?t.toLowerCase():t){case"f16":case"fp16":this._dataType="float16";break;case"f32":case"fp32":this._dataType="float32";break;case"i8":this._dataType="int8";break;case"i16":this._dataType="int16";break;case"i32":this._dataType="int32";break;case"i64":this._dataType="int64";break;case"u1":this._dataType="boolean";break;case"u8":this._dataType="uint8";break;case"u16":this._dataType="uint16";break;case"u32":this._dataType="uint32";break;case"u64":this._dataType="uint64";break;case"bool":this._dataType="boolean";break;case"":case null:this._dataType="?";break;default:throw new openvino.Error("Unknown precision '"+JSON.stringify(t)+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return null==this._shape?this.dataType+"[?]":this.dataType+this._shape.toString()}},openvino.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},openvino.Metadata=class{static open(t){return openvino.Metadata._metadata?Promise.resolve(openvino.Metadata._metadata):t.request(null,"openvino-metadata.json","utf-8").then((t=>(openvino.Metadata._metadata=new openvino.Metadata(t),openvino.Metadata._metadata))).catch((()=>(openvino.Metadata._metadata=new openvino.Metadata(null),openvino.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeMap=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)if(t&&t.name&&t.schema){if(this._map.has(t.name))throw new openvino.Error("Duplicate metadata key '"+t.name+"'.");t.schema.name=t.name,this._map.set(t.name,t.schema)}}}type(t){return this._map.get(t)||null}attribute(t,e){const n=t+":"+e;if(!this._attributeMap.has(n)){this._attributeMap.set(n,null);const e=this.type(t);if(e&&e.attributes)for(const n of e.attributes)this._attributeMap.set(t+":"+n.name,n)}return this._attributeMap.get(n)}},openvino.XmlReader=class{static read(t){const e=(t,e)=>{const n=[];let s=t.firstChild;for(;null!=s;)1==s.nodeType&&s.nodeName==e&&n.push(s),s=s.nextSibling;return n},n=(t,n)=>{const s=e(t,n);if(s.length>1)throw new openvino.Error("Element '"+t.nodeName+"' has multiple '"+n+"' elements.");return s.length>0?s[0]:null},s=(t,s)=>{const i=n(t,s);return i?e(i,"port").map((t=>({id:t.getAttribute("id"),precision:t.getAttribute("precision"),dims:Array.prototype.slice.call(t.getElementsByTagName("dim")).map((t=>parseInt(t.textContent.trim(),10)))}))):[]},i=t=>{const a=n(t,"layers");return a?e(a,"layer").map((t=>{const e=n(t,"data"),a=n(t,"blobs"),r={id:t.getAttribute("id"),name:t.getAttribute("name"),type:t.getAttribute("type"),precision:t.getAttribute("precision"),data:e?Array.from(e.attributes).map((t=>({name:t.name,value:t.value}))):[],blobs:a?Array.from(a.childNodes).filter((t=>1===t.nodeType)).map((t=>({name:t.nodeName,precision:t.getAttribute("precision"),offset:parseInt(t.getAttribute("offset"),10),size:parseInt(t.getAttribute("size"),10)}))):[],inputs:s(t,"input"),outputs:s(t,"output")};if("TensorIterator"===r.type){r.back_edges=o(t,"back_edges");const e=n(t,"body");e&&(r.body={layers:i(e),edges:o(e)});const s=n(t,"port_map");if(s){r.port_map={input:[],output:[]};for(const t of Array.from(s.childNodes).filter((t=>1===t.nodeType))){const e={axis:t.getAttribute("axis"),external_port_id:t.getAttribute("external_port_id"),internal_layer_id:t.getAttribute("internal_layer_id"),internal_port_id:t.getAttribute("internal_port_id")};switch(t.nodeName){case"input":r.port_map.input.push(e);break;case"output":r.port_map.output.push(e)}}}}return r})):[]},o=(t,s)=>{const i={},o=n(t,s||"edges");if(o)for(const t of e(o,"edge")){const e=t.getAttribute("from-layer"),n=t.getAttribute("from-port");i[t.getAttribute("to-layer")+":"+t.getAttribute("to-port")]=e+":"+n}return i};return{name:t.getAttribute("name"),batch:t.getAttribute("batch"),version:t.getAttribute("version"),layers:i(t),edges:o(t)}}},openvino.Error=class extends Error{constructor(t){super(t),this.name="Error loading OpenVINO model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=openvino.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9a16703f3c40386abe6db2e5e168c66aa23a427e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-metadata.json @@ -0,0 +1 @@ +[{"name":"conv2d","schema":{"category":"Layer","attributes":[{"name":"workspace_size_MB","default":4096},{"name":"fuse_residual_connection","default":false},{"name":"fuse_eltwise","default":false},{"name":"fuse_relu","default":false},{"name":"data_format","default":"AnyLayout"},{"name":"groups","default":1},{"name":"paddings","default":[0,0]},{"name":"dilations","default":[1,1]},{"name":"strides","default":[1,1]}]}},{"name":"depthwise_conv2d","schema":{"category":"Layer","attributes":[{"name":"workspace_size_MB","default":4096},{"name":"fuse_residual_connection","default":false},{"name":"data_format","default":"AnyLayout"},{"name":"groups","default":1},{"name":"fuse_relu","default":false}]}},{"name":"relu","schema":{"category":"Activation"}},{"name":"softmax","schema":{"category":"Activation","attributes":[{"name":"data_format","default":"AnyLayout"}]}},{"name":"batch_norm","schema":{"category":"Normalization","attributes":[{"name":"momentum","default":0.8999999761581421},{"name":"epsilon","default":0.000009999999747378752},{"name":"fuse_with_relu","default":false},{"name":"data_layout","default":"NCHW"}]}},{"name":"pool2d","schema":{"category":"Pool","attributes":[{"name":"data_format","default":"AnyLayout"},{"name":"ceil_mode","default":false},{"name":"global_pooling","default":false},{"name":"exclusive","default":true},{"name":"pooling_type","default":"max"},{"name":"paddings","default":[0,0]}]}},{"name":"elementwise_add","schema":{"attributes":[{"name":"axis","default":-1}]}},{"name":"concat","schema":{"category":"Tensor"}},{"name":"reshape","schema":{"category":"Shape"}},{"name":"reshape2","schema":{"category":"Shape"}},{"name":"lrn","schema":{"category":"Normalization","attributes":[{"name":"alpha","default":0.00009999999747378752},{"name":"beta","default":0.75},{"name":"k","default":1}]}},{"name":"pad2d","schema":{"category":"Tensor"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..8efbe3e9c82920e4e9197e421694d0e76cb1b2ec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("paddle");$root.paddle={},$root.paddle.framework={},$root.paddle.framework.proto={},$root.paddle.framework.proto.Version=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.Version,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.version=o.int64();break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.Version.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.paddle.framework.proto.AttrType={INT:0,FLOAT:1,STRING:2,INTS:3,FLOATS:4,STRINGS:5,BOOLEAN:6,BOOLEANS:7,BLOCK:8,LONG:9,BLOCKS:10,LONGS:11},$root.paddle.framework.proto.OpDesc=class{constructor(){this.inputs=[],this.outputs=[],this.attrs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 3:e.type=o.string();break;case 1:e.inputs.push($root.paddle.framework.proto.OpDesc.Var.decode(o,o.uint32()));break;case 2:e.outputs.push($root.paddle.framework.proto.OpDesc.Var.decode(o,o.uint32()));break;case 4:e.attrs.push($root.paddle.framework.proto.OpDesc.Attr.decode(o,o.uint32()));break;case 5:e.is_target=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.OpDesc.prototype.type="",$root.paddle.framework.proto.OpDesc.prototype.is_target=!1,$root.paddle.framework.proto.OpDesc.Attr=class{constructor(){this.ints=[],this.floats=[],this.strings=[],this.bools=[],this.blocks_idx=[],this.longs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc.Attr,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=o.int32();break;case 3:e.i=o.int32();break;case 4:e.f=o.float();break;case 5:e.s=o.string();break;case 6:e.ints=o.array(e.ints,(()=>o.int32()),r);break;case 7:e.floats=o.floats(e.floats,r);break;case 8:e.strings.push(o.string());break;case 10:e.b=o.bool();break;case 11:e.bools=o.array(e.bools,(()=>o.bool()),r);break;case 12:e.block_idx=o.int32();break;case 13:e.l=o.int64();break;case 14:e.blocks_idx=o.array(e.blocks_idx,(()=>o.int32()),r);break;case 15:e.longs=o.array(e.longs,(()=>o.int64()),r);break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.OpDesc.Attr.prototype.name="",$root.paddle.framework.proto.OpDesc.Attr.prototype.type=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.i=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.f=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.s="",$root.paddle.framework.proto.OpDesc.Attr.prototype.b=!1,$root.paddle.framework.proto.OpDesc.Attr.prototype.block_idx=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.l=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.paddle.framework.proto.OpDesc.Var=class{constructor(){this.arguments=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc.Var,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.parameter=o.string();break;case 2:e.arguments.push(o.string());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"parameter"))throw new protobuf.Error("Excepted 'parameter'.");return e}},$root.paddle.framework.proto.OpDesc.Var.prototype.parameter="",$root.paddle.framework.proto.OpProto=class{constructor(){this.inputs=[],this.outputs=[],this.attrs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.type=o.string();break;case 2:e.inputs.push($root.paddle.framework.proto.OpProto.Var.decode(o,o.uint32()));break;case 3:e.outputs.push($root.paddle.framework.proto.OpProto.Var.decode(o,o.uint32()));break;case 4:e.attrs.push($root.paddle.framework.proto.OpProto.Attr.decode(o,o.uint32()));break;case 5:e.comment=o.string();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.prototype.type="",$root.paddle.framework.proto.OpProto.prototype.comment="",$root.paddle.framework.proto.OpProto.Var=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto.Var,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.comment=o.string();break;case 3:e.duplicable=o.bool();break;case 4:e.intermediate=o.bool();break;case 5:e.dispensable=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.Var.prototype.name="",$root.paddle.framework.proto.OpProto.Var.prototype.comment="",$root.paddle.framework.proto.OpProto.Var.prototype.duplicable=!1,$root.paddle.framework.proto.OpProto.Var.prototype.intermediate=!1,$root.paddle.framework.proto.OpProto.Var.prototype.dispensable=!1,$root.paddle.framework.proto.OpProto.Attr=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto.Attr,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=o.int32();break;case 3:e.comment=o.string();break;case 4:e.generated=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.Attr.prototype.name="",$root.paddle.framework.proto.OpProto.Attr.prototype.type=0,$root.paddle.framework.proto.OpProto.Attr.prototype.comment="",$root.paddle.framework.proto.OpProto.Attr.prototype.generated=!1,$root.paddle.framework.proto.VarType=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.type=o.int32();break;case 2:e.selected_rows=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 3:e.lod_tensor=$root.paddle.framework.proto.VarType.LoDTensorDesc.decode(o,o.uint32());break;case 4:e.tensor_array=$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.decode(o,o.uint32());break;case 5:e.reader=$root.paddle.framework.proto.VarType.ReaderDesc.decode(o,o.uint32());break;case 7:e.tuple=$root.paddle.framework.proto.VarType.Tuple.decode(o,o.uint32());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.VarType.prototype.type=0,$root.paddle.framework.proto.VarType.prototype.selected_rows=null,$root.paddle.framework.proto.VarType.prototype.lod_tensor=null,$root.paddle.framework.proto.VarType.prototype.tensor_array=null,$root.paddle.framework.proto.VarType.prototype.reader=null,$root.paddle.framework.proto.VarType.prototype.tuple=null,$root.paddle.framework.proto.VarType.Type={BOOL:0,INT16:1,INT32:2,INT64:3,FP16:4,FP32:5,FP64:6,SIZE_T:19,UINT8:20,INT8:21,LOD_TENSOR:7,SELECTED_ROWS:8,FEED_MINIBATCH:9,FETCH_LIST:10,STEP_SCOPES:11,LOD_RANK_TABLE:12,LOD_TENSOR_ARRAY:13,PLACE_LIST:14,READER:15,RAW:17,TUPLE:18},$root.paddle.framework.proto.VarType.TensorDesc=class{constructor(){this.dims=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.TensorDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.data_type=o.int32();break;case 2:e.dims=o.array(e.dims,(()=>o.int64()),r);break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"data_type"))throw new protobuf.Error("Excepted 'data_type'.");return e}},$root.paddle.framework.proto.VarType.TensorDesc.prototype.data_type=0,$root.paddle.framework.proto.VarType.LoDTensorDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.LoDTensorDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.tensor=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 2:e.lod_level=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"tensor"))throw new protobuf.Error("Excepted 'tensor'.");return e}},$root.paddle.framework.proto.VarType.LoDTensorDesc.prototype.tensor=null,$root.paddle.framework.proto.VarType.LoDTensorDesc.prototype.lod_level=0,$root.paddle.framework.proto.VarType.LoDTensorArrayDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.LoDTensorArrayDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.tensor=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 2:e.lod_level=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"tensor"))throw new protobuf.Error("Excepted 'tensor'.");return e}},$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.prototype.tensor=null,$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.prototype.lod_level=0,$root.paddle.framework.proto.VarType.ReaderDesc=class{constructor(){this.lod_tensor=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.ReaderDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.lod_tensor.push($root.paddle.framework.proto.VarType.LoDTensorDesc.decode(o,o.uint32()));break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.VarType.Tuple=class{constructor(){this.element_type=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.Tuple,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.element_type=o.array(e.element_type,(()=>o.int32()),r);break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.VarDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=$root.paddle.framework.proto.VarType.decode(o,o.uint32());break;case 3:e.persistable=o.bool();break;case 4:e.need_check_feed=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.VarDesc.prototype.name="",$root.paddle.framework.proto.VarDesc.prototype.type=null,$root.paddle.framework.proto.VarDesc.prototype.persistable=!1,$root.paddle.framework.proto.VarDesc.prototype.need_check_feed=!1,$root.paddle.framework.proto.BlockDesc=class{constructor(){this.vars=[],this.ops=[]}static decode(o,r){const e=new $root.paddle.framework.proto.BlockDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.idx=o.int32();break;case 2:e.parent_idx=o.int32();break;case 3:e.vars.push($root.paddle.framework.proto.VarDesc.decode(o,o.uint32()));break;case 4:e.ops.push($root.paddle.framework.proto.OpDesc.decode(o,o.uint32()));break;case 5:e.forward_block_idx=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"idx"))throw new protobuf.Error("Excepted 'idx'.");if(!Object.prototype.hasOwnProperty.call(e,"parent_idx"))throw new protobuf.Error("Excepted 'parent_idx'.");return e}},$root.paddle.framework.proto.BlockDesc.prototype.idx=0,$root.paddle.framework.proto.BlockDesc.prototype.parent_idx=0,$root.paddle.framework.proto.BlockDesc.prototype.forward_block_idx=-1,$root.paddle.framework.proto.CompatibleInfo=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.CompatibleInfo,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.version=o.string();break;case 2:e.type=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"version"))throw new protobuf.Error("Excepted 'version'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.CompatibleInfo.prototype.version="",$root.paddle.framework.proto.CompatibleInfo.prototype.type=0,$root.paddle.framework.proto.CompatibleInfo.Type={COMPATIBLE:0,DEFINITELY_NOT:1,POSSIBLE:2,BUG_FIX:3,PRECISION_CHANGE:4},$root.paddle.framework.proto.OpCompatibleMap=class{constructor(){this.pair=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpCompatibleMap,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.pair.push($root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.decode(o,o.uint32()));break;case 2:e.default_required_version=o.string();break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.OpCompatibleMap.prototype.default_required_version="",$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.op_name=o.string();break;case 2:e.compatible_info=$root.paddle.framework.proto.CompatibleInfo.decode(o,o.uint32());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"op_name"))throw new protobuf.Error("Excepted 'op_name'.");if(!Object.prototype.hasOwnProperty.call(e,"compatible_info"))throw new protobuf.Error("Excepted 'compatible_info'.");return e}},$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.prototype.op_name="",$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.prototype.compatible_info=null,$root.paddle.framework.proto.ProgramDesc=class{constructor(){this.blocks=[]}static decode(o,r){const e=new $root.paddle.framework.proto.ProgramDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.blocks.push($root.paddle.framework.proto.BlockDesc.decode(o,o.uint32()));break;case 4:e.version=$root.paddle.framework.proto.Version.decode(o,o.uint32());break;case 3:e.op_compatible_map=$root.paddle.framework.proto.OpCompatibleMap.decode(o,o.uint32());break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.ProgramDesc.prototype.version=null,$root.paddle.framework.proto.ProgramDesc.prototype.op_compatible_map=null; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle.js new file mode 100644 index 0000000000000000000000000000000000000000..d73321262416cc347633456a746c1ffdfb7b3a21 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/paddle.js @@ -0,0 +1 @@ +var paddle=paddle||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");paddle.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();return"__model__"===e||"paddle"===s||"pdmodel"===s}open(t,e){return e.require("./paddle-proto").then((()=>{let s=null;const a=t.identifier;try{paddle.proto=protobuf.get("paddle").paddle.framework.proto;const e=protobuf.Reader.create(t.buffer);s=paddle.proto.ProgramDesc.decode(e)}catch(t){throw new paddle.Error("File format is not paddle.ProgramDesc ("+t.message+") in '"+a+"'.")}return paddle.Metadata.open(e).then((a=>{try{const e=new Set;for(const t of s.blocks){const s=new Set;for(const e of t.vars)e.persistable&&e.type&&e.type.type!=paddle.proto.VarType.Type.FETCH_LIST&&e.type.type!=paddle.proto.VarType.Type.FEED_MINIBATCH&&s.add(e.name);for(const a of t.ops)for(const t of a.inputs)for(const a of t.arguments)s.has(a)&&e.add(a)}const r=Array.from(e).map((e=>t.request(e,null)));return Promise.all(r).then((t=>{const r=new Map,n=Array.from(e);for(let e=0;enew paddle.Model(a,s,new Map)))}catch(t){throw e.exception(t,!1),new paddle.Error(t.message)}}))}))}},paddle.Model=class{constructor(t,e,s){this._graphs=e.blocks.map((e=>new paddle.Graph(t,e,s)))}get graphs(){return this._graphs}get format(){return"PaddlePaddle"}},paddle.Graph=class{constructor(t,e,s){this._nodes=[],this._inputs=[],this._outputs=[],this._name=`blocks[${e.idx}]`;const a=new Map;for(const t of e.vars){const e=t.type&&t.type.type&&t.type.lod_tensor&&t.type.lod_tensor.tensor?new paddle.TensorType(t.type.lod_tensor.tensor):null,r=t.persistable&&t.type&&t.type.type!=paddle.proto.VarType.Type.FETCH_LIST&&t.type.type!=paddle.proto.VarType.Type.FEED_MINIBATCH?new paddle.Tensor(e,s.get(t.name)):null;a.set(t.name,new paddle.Argument(t.name,e,r))}const r={};for(let t=0;tr[t]?r[t]:t));for(const s of e.ops[t].outputs)s.arguments=s.arguments.map((e=>{if(r[e]){const s=e+"\n"+t.toString();return r[e]=s,s}return r[e]=e,e}))}for(const t of e.ops){for(const e of t.inputs)for(const t of e.arguments){const e=t;a.has(e)||a.set(e,new paddle.Argument(e,null,null))}for(const e of t.outputs)for(const t of e.arguments){const e=t;a.has(e)||a.set(e,new paddle.Argument(e,null,null))}}let n=null,i=null;for(const s of e.ops)if("feed"==s.type){const t=s.attrs.filter((t=>"col"==t.name))[0].i.toString();this._inputs.push(new paddle.Parameter(t,s.outputs[0].arguments.map((t=>a.get(t)))))}else if("fetch"==s.type){const t=s.attrs.filter((t=>"col"==t.name))[0].i.toString();this._outputs.push(new paddle.Parameter(t,s.inputs[0].arguments.map((t=>a.get(t)))))}else{const e=new paddle.Node(t,s,a);1==s.inputs.length&&1==s.inputs[0].arguments.length&&s.outputs.length>=1&&1==s.outputs[0].arguments.length&&s.inputs[0].arguments[0].split("\n").shift()==s.outputs[0].arguments[0].split("\n").shift()&&n&&i==s.inputs[0].arguments[0].split("\n").shift()?n.chain.push(e):(this._nodes.push(e),n=null,i=null,1==s.outputs.length&&1==s.outputs[0].arguments.length&&(n=e,i=s.outputs[0].arguments[0].split("\n").shift()))}}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},paddle.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},paddle.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new paddle.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get initializer(){return this._initializer}},paddle.Node=class{constructor(t,e,s){this._metadata=t,this._type=e.type,this._attributes=[],this._inputs=[],this._outputs=[],this._chain=[];for(const s of e.attrs){const e=t.attribute(this._type,this._name);this._attributes.push(new paddle.Attribute(e,s))}for(const t of e.inputs)t.arguments.length>0&&this._inputs.push(new paddle.Parameter(t.parameter,t.arguments.map((t=>s.get(t)))));for(const t of e.outputs)t.arguments.length>0&&this._outputs.push(new paddle.Parameter(t.parameter,t.arguments.map((t=>s.get(t)))));this._update(this._inputs,"X"),this._update(this._inputs,"Input"),this._update(this._outputs,"Y"),this._update(this._outputs,"Out")}get type(){return this._type}get name(){return""}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}_update(t,e){let s=null;for(let a=0;at==e[s])))&&(this._visible=!1)}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},paddle.Tensor=class{constructor(t,e){if(this._type=t,e&&e.length>20&&e.slice(0,16).every((t=>0===t))){const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(16,!0);this._data=e.slice(20+t)}}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return paddle.Tensor._stringify(e,""," ")}_context(){const t={index:0,count:0,state:null};if(!this._data)return t.state="Tensor data is empty.",t;if(!this._type)return t.state="Tensor has no data type.",t;switch(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.view=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dataType){case"float32":case"int32":case"int64":break;default:t.state="Tensor data type '"+t.dataType+"' is not implemented."}return t}_decode(t,e){const s=0!==t.shape.length?t.shape:[1],a=[],r=s[e];if(e==s.length-1)for(let e=0;et.limit)return a.push("..."),a;switch(t.dataType){case"float32":a.push(t.view.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"int32":a.push(t.view.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":a.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++}}else for(let s=0;st.limit)return a.push("..."),a;a.push(this._decode(t,e+1))}return 0==t.shape.length?a[0]:a}static _stringify(t,e,s){if(Array.isArray(t)){const a=[];a.push(e+"[");const r=t.map((t=>paddle.Tensor._stringify(t,e+s,s)));return r.length>0&&a.push(r.join(",\n")),a.push(e+"]"),a.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},paddle.TensorType=class{constructor(t){switch(t.data_type){case paddle.proto.VarType.Type.INT32:this._dataType="int32";break;case paddle.proto.VarType.Type.INT64:this._dataType="int64";break;case paddle.proto.VarType.Type.FP32:this._dataType="float32";break;case paddle.proto.VarType.Type.FP64:this._dataType="float64";break;default:this._dataType="?"}this._shape=new paddle.TensorShape(t.dims)}get dataType(){return this._dataType}get shape(){return this._shape}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},paddle.TensorShape=class{constructor(t){t=t.map((t=>t.toNumber())),this._dimensions=t.map((t=>-1!=t?t:"?"))}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},paddle.Metadata=class{static open(t){return paddle.Metadata._metadata?Promise.resolve(paddle.Metadata._metadata):t.request(null,"paddle-metadata.json","utf-8").then((t=>(paddle.Metadata._metadata=new paddle.Metadata(t),paddle.Metadata._metadata))).catch((()=>(paddle.Metadata._metadata=new paddle.Metadata(null),paddle.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]||null}attribute(t,e){let s=this._attributeCache[t];if(!s){s={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)s[t.name]=t;this._attributeCache[t]=s}return s[e]||null}},paddle.Error=class extends Error{constructor(t){super(t),this.name="Error loading PaddlePaddle model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=paddle.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/pickle.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/pickle.js new file mode 100644 index 0000000000000000000000000000000000000000..c4714eea288526ea65caed42b228b4311dc49ddb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/pickle.js @@ -0,0 +1 @@ +var pickle=pickle||{};pickle.Unpickler=class{constructor(e){this._reader=new pickle.Reader(e,0)}load(e,s){const t=this._reader,p=[];let i=[];const o=new Map;for(;t.position5)throw new pickle.Error("Unsupported protocol version '"+e+"'.");break}case pickle.OpCode.GLOBAL:i.push([t.line(),t.line()].join("."));break;case pickle.OpCode.STACK_GLOBAL:i.push([i.pop(),i.pop()].reverse().join("."));break;case pickle.OpCode.PUT:{const e=parseInt(t.line(),10);o.set(e,i[i.length-1]);break}case pickle.OpCode.OBJ:{const s=i;i=p.pop(),i.push(e(s.pop(),s));break}case pickle.OpCode.GET:{const e=parseInt(t.line(),10);i.push(o.get(e));break}case pickle.OpCode.POP:i.pop();break;case pickle.OpCode.POP_MARK:i=p.pop();break;case pickle.OpCode.DUP:i.push(i[i.length-1]);break;case pickle.OpCode.PERSID:i.push(s(t.line()));break;case pickle.OpCode.BINPERSID:i.push(s(i.pop()));break;case pickle.OpCode.REDUCE:{const s=i.pop(),t=i.pop();i.push(e(t,s));break}case pickle.OpCode.NEWOBJ:{const s=i.pop(),t=i.pop();i.push(e(t,s));break}case pickle.OpCode.BINGET:i.push(o.get(t.byte()));break;case pickle.OpCode.LONG_BINGET:i.push(o.get(t.uint32()));break;case pickle.OpCode.BINPUT:o.set(t.byte(),i[i.length-1]);break;case pickle.OpCode.LONG_BINPUT:o.set(t.uint32(),i[i.length-1]);break;case pickle.OpCode.BININT:i.push(t.int32());break;case pickle.OpCode.BININT1:i.push(t.byte());break;case pickle.OpCode.LONG:i.push(parseInt(t.line(),10));break;case pickle.OpCode.BININT2:i.push(t.uint16());break;case pickle.OpCode.BINBYTES:i.push(t.bytes(t.int32()));break;case pickle.OpCode.SHORT_BINBYTES:i.push(t.bytes(t.byte()));break;case pickle.OpCode.FLOAT:i.push(parseFloat(t.line()));break;case pickle.OpCode.BINFLOAT:i.push(t.float64());break;case pickle.OpCode.INT:{const e=t.line();"01"==e?i.push(!0):"00"==e?i.push(!1):i.push(parseInt(e,10));break}case pickle.OpCode.EMPTY_LIST:case pickle.OpCode.EMPTY_TUPLE:case pickle.OpCode.EMPTY_SET:i.push([]);break;case pickle.OpCode.ADDITEMS:{const e=i;i=p.pop();const s=i[i.length-1];for(let t=0;t=t)p[o++]=s;else switch(s=e.charCodeAt(i++),s){case 39:p[o++]=39;break;case 92:p[o++]=92;break;case 34:p[o++]=34;break;case 114:p[o++]=13;break;case 110:p[o++]=10;break;case 116:p[o++]=9;break;case 98:p[o++]=8;break;case 88:case 120:{const s=i-1,c=o;for(let a=0;a<2;a++){if(i>=t){i=s,o=c,p[o]=92;break}let a=e.charCodeAt(i++);if(a=a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:a>=48&&a<=57?a-48:-1,-1===a){i=s,o=c,p[o]=92;break}p[o]=p[o]<<4|a}o++;break}default:if(s<48||s>57)p[o++]=92,p[o++]=s;else{i--;const s=i,c=o;for(let a=0;a<3;a++){if(i>=t){i=s,o=c,p[o]=92;break}const a=e.charCodeAt(i++);if(a<48||a>57){i=s,o=c,p[o]=92;break}p[o]=p[o]<<3|a-48}o++}}}return p.slice(0,o)}},pickle.OpCode={MARK:40,EMPTY_TUPLE:41,STOP:46,POP:48,POP_MARK:49,DUP:50,BINBYTES:66,SHORT_BINBYTES:67,FLOAT:70,BINFLOAT:71,INT:73,BININT:74,BININT1:75,LONG:76,BININT2:77,NONE:78,PERSID:80,BINPERSID:81,REDUCE:82,STRING:83,BINSTRING:84,SHORT_BINSTRING:85,UNICODE:86,BINUNICODE:88,EMPTY_LIST:93,APPEND:97,BUILD:98,GLOBAL:99,DICT:100,APPENDS:101,GET:103,BINGET:104,LONG_BINGET:106,LIST:108,OBJ:111,PUT:112,BINPUT:113,LONG_BINPUT:114,SETITEM:115,TUPLE:116,SETITEMS:117,EMPTY_DICT:125,PROTO:128,NEWOBJ:129,TUPLE1:133,TUPLE2:134,TUPLE3:135,NEWTRUE:136,NEWFALSE:137,LONG1:138,LONG4:139,SHORT_BINUNICODE:140,BINUNICODE8:141,BINBYTES8:142,EMPTY_SET:143,ADDITEMS:144,FROZENSET:145,NEWOBJ_EX:146,STACK_GLOBAL:147,MEMOIZE:148,FRAME:149},pickle.Reader=class{constructor(e){e&&(this._buffer=e,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._position=0),pickle.Reader._utf8Decoder=pickle.Reader._utf8Decoder||new TextDecoder("utf-8"),pickle.Reader._asciiDecoder=pickle.Reader._asciiDecoder||new TextDecoder("ascii")}get length(){return this._buffer.byteLength}get position(){return this._position}byte(){const e=this._position;return this.skip(1),this._dataView.getUint8(e)}bytes(e){const s=this._position;return this.skip(e),this._buffer.subarray(s,this._position)}uint16(){const e=this.position;return this.skip(2),this._dataView.getUint16(e,!0)}int32(){const e=this.position;return this.skip(4),this._dataView.getInt32(e,!0)}uint32(){const e=this.position;return this.skip(4),this._dataView.getUint32(e,!0)}float32(){const e=this.position;return this.skip(4),this._dataView.getFloat32(e,!0)}float64(){const e=this.position;return this.skip(8),this._dataView.getFloat64(e,!0)}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new pickle.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}string(e,s){const t=this.bytes(e);return"utf-8"==s?pickle.Reader._utf8Decoder.decode(t):pickle.Reader._asciiDecoder.decode(t)}line(){const e=this._buffer.indexOf(10,this._position);if(-1==e)throw new pickle.Error("Could not find end of line.");const s=e-this._position,t=this.string(s,"ascii");return this.skip(1),t}},pickle.Error=class extends Error{constructor(e){super(e),this.name="Unpickle Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Unpickler=pickle.Unpickler); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/protobuf.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/protobuf.js new file mode 100644 index 0000000000000000000000000000000000000000..05ddc6f56e22aadab680651a5cc5dfb84201b804 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/protobuf.js @@ -0,0 +1 @@ +var protobuf=protobuf||{},long=long||{Long:require("long")};protobuf.get=t=>(protobuf._map=protobuf._map||new Map,protobuf._map.has(t)||protobuf._map.set(t,{}),protobuf._map.get(t)),protobuf.Reader=class{constructor(t){this._buffer=t,this._length=t.length,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._decoder=new TextDecoder("utf-8")}static create(t){return new protobuf.Reader(t)}next(t){return void 0===t?this._length:this._position+t}end(t){return this._positionthis._length)throw this._indexOutOfRangeError(t);return this._position+=t,this._buffer.slice(i,o)}uint32(){let t=4294967295;if(t=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return t;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=4,this._dataView.getFloat32(t,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=8,this._dataView.getFloat64(t,!0)}array(t,i,o){if(2==(7&o)){const o=this.uint32()+this._position;for(;this._position0)throw new protobuf.Error("Invalid packed float array.");const i=this.uint32(),o=this._position+i,s=i>>>2;t=i>1048576?new Float32Array(s):new Array(s);let e=this._position;for(let i=0;i0)throw new protobuf.Error("Invalid packed float array.");const i=this.uint32(),o=this._position+i,s=i>>>3;t=i>1048576?new Float64Array(s):new Array(s);let e=this._position;for(let i=0;ithis._length)throw this._indexOutOfRangeError(t);this._position+=t}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw new protobuf.Error("invalid wire type "+t+" at offset "+this._position)}}pair(t,i,o){this.skip(),this._position++;const s="object"==typeof i?protobuf.LongBits.hash(i()):i();this._position++;const e=o();t[s]=e}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const t=this._readFixed32();this._position+=4;const i=this._readFixed32();return new protobuf.LongBits(t,i)}_readLongVarint(){const t=new protobuf.LongBits(0,0);let i=0;if(!(this._length-this._position>4)){for(;i<3;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t}return t.lo=(t.lo|(127&this._buffer[this._position++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t;if(t.lo=(t.lo|(127&this._buffer[this._position])<<28)>>>0,t.hi=(t.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return t;if(i=0,this._length-this._position>4){for(;i<5;++i)if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}else for(;i<5;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}throw new protobuf.Error("Invalid varint encoding.")}_indexOutOfRangeError(t){return RangeError("index out of range: "+this._position+" + "+(t||1)+" > "+this._length)}},protobuf.TextReader=class{constructor(t){this._text=t,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(t){return new protobuf.TextReader(t)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const t=this.peek();return this._depth>0&&"}"===t?(this.expect("}"),this.match(";"),this._depth--,!0):""===t}tag(){const t=this.read(),i=this.peek();return"["!==i&&"{"!==i&&this.expect(":"),t}assert(t){const i=this.tag();if(i!==t)throw new protobuf.Error("Unexpected '"+i+"' instead of '"+t+"'"+this.location())}integer(){const t=this.read(),i=Number.parseInt(t,10);if(Number.isNaN(t-i))throw new protobuf.Error("Couldn't parse integer '"+t+"'"+this.location());return this.semicolon(),i}float(){let t=this.read();if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;t.endsWith("f")&&(t=t.substring(0,t.length-1));const i=Number.parseFloat(t);if(Number.isNaN(t-i))throw new protobuf.Error("Couldn't parse float '"+t+"'"+this.location());return this.semicolon(),i}string(){const t=this.read();if(t.length<2)throw new protobuf.Error("String is too short"+this.location());const i=t[0];if("'"!==i&&'"'!==i)throw new protobuf.Error("String is not in quotes"+this.location());if(i!==t[t.length-1])throw new protobuf.Error("String quotes do not match"+this.location());const o=t.substring(1,t.length-1);return this.semicolon(),o}boolean(){const t=this.read();switch(t){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new protobuf.Error("Couldn't parse boolean '"+t+"'"+this.location())}bytes(){const t=this.string();let i=0,o=0;const s=t.length,e=new Uint8Array(s);for(;i=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());switch(r=t.charCodeAt(i++),r){case 39:e[o++]=39;break;case 92:e[o++]=92;break;case 34:e[o++]=34;break;case 114:e[o++]=13;break;case 110:e[o++]=10;break;case 116:e[o++]=9;break;case 98:e[o++]=8;break;case 88:case 120:for(let r=0;r<2;r++){if(i>=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());let r=t.charCodeAt(i++);if(r=r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r>=48&&r<=57?r-48:-1,-1===r)throw new protobuf.Error("Unexpected hex digit '"+r+"' in bytes string"+this.location());e[o]=e[o]<<4|r}o++;break;default:if(r<48||r>57)throw new protobuf.Error("Unexpected character '"+r+"' in bytes string"+this.location());i--;for(let r=0;r<3;r++){if(i>=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());const r=t.charCodeAt(i++);if(r<48||r>57)throw new protobuf.Error("Unexpected octal digit '"+r+"' in bytes string"+this.location());e[o]=e[o]<<3|r-48}o++}}}return e.slice(0,o)}enum(t){const i=this.read();if(!Object.prototype.hasOwnProperty.call(t,i)){const t=Number.parseInt(i,10);if(!Number.isNaN(i-t))return this.semicolon(),t;throw new protobuf.Error("Couldn't parse enum '"+i+"'"+this.location())}return this.semicolon(),t[i]}any(t){if(this.match("[")){this.read();const i=this._position,o=this._text.indexOf("]",i);if(-1===o||o>=this.next)throw new protobuf.Error("End of Any type_url not found"+this.location());return t.type_url=this._text.substring(i,o),this._position=o+1,t.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(t,i,o){let s,e;for(this.start();!this.end();)switch(this.tag()){case"key":s=i();break;case"value":e=o()}t[s]=e}array(t,i){if(this.first())for(;!this.last();)t.push(i()),this.next();else t.push(i())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const t=this.peek();","!==t?"]"!==t&&this.handle(t):this.read()}skip(){let t=this.peek();if("{"===t){const i=this._position,o=this._depth;for(this.start();!this.end()||o=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let t=this._text[this._position];if("["===t&&this._position+2="a"&&i<="z"||i>="A"&&i<="Z")for(t++;t="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||"."===i||"/"===i)&&"]"===i)return this._token=this._text.substring(this._position,t),this._token}if("{"===t||"}"===t||":"===t||"["===t||","===t||"]"===t||";"===t)return this._token=t,this._token;let i=this._position+1;if(t>="a"&&t<="z"||t>="A"&&t<="Z"||"_"===t||"$"===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if(t>="0"&&t<="9"||"-"===t||"+"===t||"."===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t||"."===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if('"'===t||"'"===t){const o=t;for(;i>>0,this.hi=i>>>0}toLong(t){return protobuf.Long?new protobuf.Long(0|this.lo,0|this.hi,t):{low:0|this.lo,high:0|this.hi,unsigned:t}}toNumber(t){if(!t&&this.hi>>>31){const t=1+~this.lo>>>0;let i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}from(t){if("number"==typeof t)return protobuf.LongBits.fromNumber(t);if("string"==typeof t||t instanceof String){if(!protobuf.Long)return protobuf.LongBits.fromNumber(parseInt(t,10));t=protobuf.Long.fromString(t)}return t.low||t.high?new protobuf.LongBits(t.low>>>0,t.high>>>0):protobuf.LongBits.zero}hash(t){return t?protobuf.LongBits.from(t).toHash():"\0\0\0\0\0\0\0\0"}},protobuf.LongBits.zero=new protobuf.LongBits(0,0),protobuf.LongBits.zero.toNumber=function(){return 0},protobuf.LongBits.zero.zzDecode=function(){return this},protobuf.Error=class extends Error{constructor(t){super(t),this.name="Protocol Buffer Error",this.message=t}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Reader=protobuf.Reader,module.exports.TextReader=protobuf.TextReader,module.exports.Error=protobuf.Error,module.exports.Long=protobuf.Long,module.exports.get=protobuf.get); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/python.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/python.js new file mode 100644 index 0000000000000000000000000000000000000000..49e461c4c18def2afac95d5fddd66c928df956d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/python.js @@ -0,0 +1 @@ +var python=python||{};python.Parser=class{constructor(e,t){this._tokenizer=new python.Tokenizer(e,t),python.Parser._precedence||(python.Parser._precedence={or:2,and:3,not:4,in:5,instanceof:5,is:5,"<":5,">":5,"<=":5,">=":5,"<>":5,"==":5,"!=":5,"|":6,"^":7,"&":8,"<<":9,">>":9,"+":10,"-":10,"*":11,"@":11,"/":11,"//":11,"%":11,"~":13,"**":14})}parse(){const e=this._node("program");for(e.body=[];!this._tokenizer.match("eof");){const t=this._parseStatement();if(t)e.body.push(t);else if(!(this._tokenizer.eat("\n")||this._tokenizer.eat(";")||"eof"==this._tokenizer.peek().type||this._tokenizer.eat("indent")&&"eof"==this._tokenizer.peek().type))throw new python.Error("Unknown statement"+this._tokenizer.location())}return e}_parseSuite(){const e=this._node("block");e.statements=[];let t=null;if(this._tokenizer.eat("\n")){if(this._tokenizer.eat("indent"))for(;!this._tokenizer.eat("eof")&&!this._tokenizer.eat("dedent");)if(!this._tokenizer.eat(";"))if(t=this._parseStatement(),t)e.statements.push(t);else if(!this._tokenizer.eat("\n")&&!this._tokenizer.match("dedent")&&!this._tokenizer.match("eof"))throw new python.Error("Empty statement"+this._tokenizer.location())}else if(!this._tokenizer.eat("eof")){for(;!this._tokenizer.match("\n")&&!this._tokenizer.match("eof")&&!this._tokenizer.match("dedent");)if(!this._tokenizer.eat(";")){if(t=this._parseStatement(),!t)throw new python.Error("Empty statement"+this._tokenizer.location());e.statements.push(t)}this._tokenizer.eat("\n")}return e}_parseStatement(){let e=this._node();if(e=this._eat("id","break"),e)return e;if(e=this._eat("id","continue"),e)return e;if(e=this._eat("id","return"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","raise"),e)return e.exception=this._parseExpression(-1,["from"]),this._tokenizer.eat("id","from")?e.from=this._parseExpression():this._tokenizer.eat(",")&&(e.exception=[e.exception],e.exception.push(this._parseExpression()),this._tokenizer.eat(",")&&e.exception.push(this._parseExpression())),e;if(e=this._eat("id","assert"),e){for(e.condition=this._parseExpression();this._tokenizer.eat(",");)e.condition={type:"list",value:[e.condition]},e.condition.value.push(this._parseExpression());return e}if(e=this._eat("id","exec"),e){if(e.variable=this._parseExpression(-1,["in"]),this._tokenizer.eat("in"))do{e.target=e.target||[],e.target.push(this._parseExpression(-1,["in"],!1))}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","global"),e){e.variable=[];do{e.variable.push(this._parseName())}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","nonlocal"),e){e.variable=[];do{e.variable.push(this._parseName())}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","import"),e){e.modules=[];do{const t=this._node("module");t.name=this._parseExpression(-1,[],!1),this._tokenizer.eat("id","as")&&(t.as=this._parseExpression(-1,[],!1)),e.modules.push(t)}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","from"),e){const t=this._tokenizer.peek();t&&Array.from(t.type).every((e=>"."==e))?(e.from=this._eat(t.type),e.from.expression=this._parseExpression()):e.from=this._parseExpression(),this._tokenizer.expect("id","import"),e.import=[];const i=this._tokenizer.eat("(");do{const t=this._node();t.symbol=this._parseExpression(-1,[],!1),this._tokenizer.eat("id","as")&&(t.as=this._parseExpression(-1,[],!1)),e.import.push(t)}while(this._tokenizer.eat(","));return i&&this._tokenizer.expect(")"),e}if(e=this._eat("id","class"),e)return e.name=this._parseName().value,"("===this._tokenizer.peek().value&&(e.base=this._parseArguments()),this._tokenizer.expect(":"),e.body=this._parseSuite(),e;const t=this._eat("id","async");if(t&&!this._tokenizer.match("id","def")&&!this._tokenizer.match("id","with")&&!this._tokenizer.match("id","for"))throw new python.Error("Expected 'def', 'with' or 'for'"+this._tokenizer.location());if(e=this._eat("id","def"),e)return t&&(e.async=t),e.name=this._parseName().value,this._tokenizer.expect("("),e.parameters=this._parseParameters(")"),this._tokenizer.eat("->")&&(e.returnType=this._parseType()),this._tokenizer.expect(":"),e.body=this._parseSuite(),e;if(e=this._eat("id","del"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","print"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","if"),e){e.condition=this._parseExpression(),this._tokenizer.expect(":"),e.then=this._parseSuite();let t=e;for(this._tokenizer.eat("\n");this._tokenizer.eat("id","elif");)t.else=this._node("if"),t=t.else,t.condition=this._parseExpression(),this._tokenizer.expect(":"),t.then=this._parseSuite(),this._tokenizer.eat("\n");return this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),t.else=this._parseSuite()),e}if(e=this._eat("id","while"),e)return e.condition=this._parseExpression(),this._tokenizer.expect(":"),e.body=this._parseSuite(),this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),e.else=this._parseSuite()),e;if(e=this._eat("id","pass"),e)return e;if(e=this._eat("id","for"),e){for(e.variable=[],e.variable.push(this._parseExpression(-1,["in"]));this._tokenizer.eat(",");){if(this._tokenizer.match("id","in")){e.variable.push({});break}e.variable.push(this._parseExpression(-1,["in"]))}for(this._tokenizer.expect("id","in"),e.target=[],e.target.push(this._parseExpression());this._tokenizer.eat(",");){if(this._tokenizer.match(":")){e.target.push({});break}e.target.push(this._parseExpression(-1,["in"]))}return this._tokenizer.expect(":"),e.body=this._parseSuite(),this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),e.else=this._parseSuite()),e}if(e=this._eat("id","with"),e){t&&(e.async=t),e.item=[];do{const t=this._node();t.type="with_item",t.expression=this._parseExpression(),this._tokenizer.eat("id","as")&&(t.variable=this._parseExpression()),e.item.push(t)}while(this._tokenizer.eat(","));return this._tokenizer.expect(":"),e.body=this._parseSuite(),e}if(e=this._eat("id","try"),e){for(this._tokenizer.expect(":"),e.body=this._parseSuite(),e.except=[];this._tokenizer.match("id","except");){const t=this._node("except");for(this._tokenizer.expect("id","except"),t.clause=[],t.clause.push(this._parseExpression());this._tokenizer.eat(",");){if(this._tokenizer.match(":")||this._tokenizer.match("as")){t.clause.push({});break}t.clause.push(this._parseExpression())}this._tokenizer.eat("id","as")&&(t.variable=this._parseExpression()),this._tokenizer.expect(":"),t.body=this._parseSuite(),e.except.push(t)}return this._tokenizer.match("id","else")&&(e.else=this._node("else"),this._tokenizer.expect("id","else"),this._tokenizer.expect(":"),e.else.body=this._parseSuite()),this._tokenizer.match("id","finally")&&(e.finally=this._node("finally"),this._tokenizer.expect("id","finally"),this._tokenizer.expect(":"),e.finally.body=this._parseSuite()),e}if(this._tokenizer.match("@")){if(e=this._node("decorator"),this._tokenizer.expect("@"),e.value=this._parseExpression(),!e.value||"call"!==e.value.type&&"id"!==e.value.type&&"."!==e.value.type)throw new python.Error("Invalid decorator"+this._tokenizer.location());return e}const i=this._parseExpression(-1,[],!0);if(i){if("id"==i.type&&this._tokenizer.eat(":"))return e=this._node("var"),e.name=i.value,e.location=i.location,e.variableType=this._parseExpression(-1,["="]),this._tokenizer.eat("=")&&(e.initializer=this._parseExpression()),e;let t=!1;switch(i.type){case"=":case":=":case"==":case"!=":case"+=":case"-=":case"*=":case"@=":case"/=":case"//=":case"**=":case"&=":case"|=":case"%=":case">>=":case"<<=":case">>":case"<<":case">=":case"<=":case"<":case">":case"%":case"^=":case"...":case"call":case"assert":case"raise":case"string":case"list":case"var":case".":case"[]":case"yield":case"+":case"-":case"*":case"**":case"@":case"/":case"//":case"~":case"&":case"^":case"|":case"not":case"id":case"number":case"in":case"and":case"or":case"if":case"for":case"tuple":case"lambda":case"await":t=!0}if(t)return i;throw new python.Error("Unhandled expression"+this._tokenizer.location())}return null}_parseExpression(e,t,i){e=e||-1;const s=new Set(t),n=[];for(;;){let r=this._node();const o=this._tokenizer.peek();if(1==n.length&&s.has(o.value))break;const h=python.Parser._precedence[o.value];if(h&&h>=e){if(this._tokenizer.read(),r.type=o.value,"id"!=o.type||"in"!==o.value&&"not"!==o.value){if("~"==o.value){r.type="~",r.expression=this._parseExpression(h,t,!1!==i),n.push(r);continue}"id"==o.type&&"is"==o.value&&this._tokenizer.eat("id","not")&&(r.type="is not")}else if("in"===o.value)r.type="in";else{if(!this._tokenizer.eat("id","in")){r.type="not",r.expression=this._parseExpression(h,t,!1!==i),n.push(r);continue}r.type="not in"}r.left=n.pop(),r.right=this._parseExpression(h,t,!1!==i),n.push(r);continue}if(this._tokenizer.eat(":=")){r.type=":=",r.target=n.pop(),r.expression=this._parseExpression(-1,t,!1!==i),n.push(r);continue}if(this._tokenizer.eat("=")){r.type="=",r.target=n.pop(),r.expression=this._parseExpression(-1,t,!1!==i),n.push(r);continue}switch(o.type){case"-=":case"**=":case"*=":case"//=":case"/=":case"&=":case"%=":case"^=":case"+=":case"<<=":case">>=":case"|=":case"@=":r=this._node(o.type),this._tokenizer.expect(o.type),r.target=n.pop(),r.expression=this._parseExpression(-1,t,!0),n.push(r);continue}if(r=this._eat("id","if"),r){r.then=n.pop(),r.condition=this._parseExpression(),this._tokenizer.expect("id","else"),r.else=this._parseExpression(),n.push(r);continue}for(;this._tokenizer.match("id","for")||this._tokenizer.match("id","async");){const e=this._eat("id","async");if(e&&!this._tokenizer.match("id","for"))throw new python.Error("Expected 'for'"+this._tokenizer.location());if(r=this._eat("id","for"),r){for(e&&(r.async=e),r.expression=n.pop(),r.variable=this._parseExpression(-1,["in"],!0),this._tokenizer.expect("id","in"),r.target=this._parseExpression(-1,["for","if"],!0);this._tokenizer.eat("id","if");)r.condition=r.condition||[],r.condition.push(this._parseExpression(-1,["for","if"]));n.push(r)}}if(r=this._eat("id","lambda"),r){r.parameters=this._parseParameters(":"),r.body=this._parseExpression(-1,t,!1),n.push(r);continue}if(r=this._eat("id","yield"),r){if(this._tokenizer.eat("id","from"))r.from=this._parseExpression(-1,[],!0);else{r.expression=[];do{r.expression.push(this._parseExpression(-1,[],!1))}while(this._tokenizer.eat(","))}n.push(r);continue}if(r=this._eat("id","await"),r){r.expression=this._parseExpression(e,t,i),n.push(r);continue}if(r=this._eat("."),r){this._tokenizer.eat("\n"),r.target=n.pop(),r.member=this._parseName(),n.push(r);continue}if("("===this._tokenizer.peek().value){if(0==n.length){r=this._node("tuple");const e=this._parseArguments();1==e.length?n.push(e[0]):(r.value=e,n.push(r))}else r=this._node("call"),r.target=n.pop(),r.arguments=this._parseArguments(),n.push(r);continue}if("["===this._tokenizer.peek().value){0==n.length?n.push(this._parseExpressions()):(r=this._node("[]"),r.target=n.pop(),r.arguments=this._parseSlice(),n.push(r));continue}if("{"==this._tokenizer.peek().value){n.push(this._parseDictOrSetMaker());continue}r=this._node();const a=this._parseLiteral();if(a){n.length>0&&"number"==a.type&&(a.value.startsWith("-")||a.value.startsWith("+"))?(r.type=a.value.substring(0,1),a.value=a.value.substring(1),r.left=n.pop(),r.right=a,n.push(r)):1==n.length&&"string"==a.type&&"string"==n[0].type?n[0].value+=a.value:n.push(a);continue}if(this._tokenizer.peek().keyword)break;if(r=this._eat("..."),r){n.push(r);continue}const _=this._parseName();if(!_){if(!0===i&&1==n.length&&this._tokenizer.eat(",")){if("tuple"===n[0].type?r=n[0]:(r=this._node("tuple"),r.value=[n.pop()],n.push(r)),"="===this._tokenizer.peek().value)continue;if(!this._tokenizer.match("=")&&!s.has(this._tokenizer.peek().value)){const s=t.slice(0).concat([",","="]),n=this._parseExpression(e,s,i);if(n){r.value.push(n);continue}}break}break}n.push(_)}if(1==n.length)return n.pop();if(0!=n.length)throw new python.Error("Unexpected expression"+this._tokenizer.location());return null}_parseDictOrSetMaker(){const e=[];this._tokenizer.expect("{");let t=!0;for(;!this._tokenizer.eat("}");){const i=this._parseExpression(-1,[],!1);if(null==i)throw new python.Error("Expected expression"+this._tokenizer.location());if(this._tokenizer.eat(":")||(t=!1),t){const t=this._parseExpression(-1,[],!1);if(null==t)throw new python.Error("Expected expression"+this._tokenizer.location());e.push({type:"pair",key:i,value:t})}else e.push(i);if(this._tokenizer.eat(","),this._tokenizer.eat("\n"),this._tokenizer.eat("}"))break}return t?{type:"dict",value:e}:{type:"set",value:e}}_parseExpressions(){const e=[];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");){const t=this._parseExpression();if(null==t)throw new python.Error("Expected expression"+this._tokenizer.location());for(e.push(t),this._tokenizer.eat(",");this._tokenizer.eat("\n"););if(this._tokenizer.eat("]"))break}return{type:"list",value:e}}_parseSlice(){let e={type:"::"},t=[];const i=["start","stop","step"];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");)if(this._tokenizer.eat(":"))e[i.shift()]={type:"list",value:t},t=[];else if(!this._tokenizer.eat(",")&&"]"!=this._tokenizer.peek().value){const e=this._parseExpression();if(null==e)throw new python.Error("Expected expression"+this._tokenizer.location());t.push(e)}return t.length>0&&(e[i.shift()]={type:"list",value:t}),!e.start||e.stop||e.step||(e=e.start),e}_parseName(){const e=this._tokenizer.peek();return"id"!=e.type||e.keyword?null:(this._tokenizer.read(),e)}_parseLiteral(){const e=this._tokenizer.peek();return"string"==e.type||"number"==e.type||"boolean"==e.type?(this._tokenizer.read(),e):null}_parseTypeArguments(){const e=[];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");){const t=this._parseType();if(null==t)throw new python.Error("Expected type "+this._tokenizer.location());if(e.push(t),!this._tokenizer.eat(",")){this._tokenizer.expect("]");break}}return e}_parseType(){const e=this._node();return e.type="type",e.name=this._parseExpression(-1,["[","="]),e.name?("["===this._tokenizer.peek().value&&(e.arguments=this._parseTypeArguments()),e):null}_parseParameter(e){const t=this._node("parameter");if(this._tokenizer.eat("/"))return t.name="/",t;this._tokenizer.eat("**")&&(t.parameterType="**"),this._tokenizer.eat("*")&&(t.parameterType="*");const i=this._parseName();return null!==i?(t.name=i.value,":"!==e&&this._tokenizer.eat(":")&&(t.parameterType=this._parseType()),this._tokenizer.eat("=")&&(t.initializer=this._parseExpression()),t):null}_parseParameters(e){const t=[];for(;!this._tokenizer.eat(e);)if(this._tokenizer.eat("\n"),this._tokenizer.eat("(")?t.push(this._parseParameters(")")):t.push(this._parseParameter(e)),this._tokenizer.eat("\n"),!this._tokenizer.eat(",")){this._tokenizer.expect(e);break}return t}_parseArguments(){const e=[];for(this._tokenizer.expect("(");!this._tokenizer.eat(")");){if(this._tokenizer.eat("\n"))continue;const t=this._parseExpression(-1,[],!1);if(null==t)throw new python.Error("Expected expression "+this._tokenizer.location());if(e.push(t),!this._tokenizer.eat(",")){this._tokenizer.eat("\n"),this._tokenizer.expect(")");break}}return e}_node(e){const t={};return t.location=this._tokenizer.location(),e&&(t.type=e),t}_eat(e,t){if(this._tokenizer.match(e,t)){const i=this._node("id"===e?t:e);return this._tokenizer.expect(e,t),i}return null}},python.Tokenizer=class{constructor(e,t){if(this._text=e,this._file=t,this._position=0,this._lineStart=0,this._line=0,this._token={type:"",value:""},this._brackets=0,this._indentation=[],this._outdent=0,!python.Tokenizer._whitespace){python.Tokenizer._whitespace=new RegExp("[ ᠎ -    \ufeff]");const e="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",t="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‌‍‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_";python.Tokenizer._identifierStart=new RegExp("["+e+"]"),python.Tokenizer._identifierChar=new RegExp("["+e+t+"]")}}peek(){return this._cache||(this._token=this._tokenize(this._token),this._cache=!0),this._token}read(){this._cache||(this._token=this._tokenize(this._token));const e=this._position+this._token.value.length;for(;this._position=5760&&python.Tokenizer._whitespace.test(e)}}static _isNewline(e){switch(e){case"\n":case"\r":case"\u2028":case"\u2029":return!0}return!1}static _isIdentifierStartChar(e){return e<"A"?"$"===e:e<="Z"||(e<"a"?"_"===e:e<="z"||e.charCodeAt(0)>=170&&python.Tokenizer._identifierStart.test(e))}static _isIdentifierChar(e){return e<"0"?"$"===e:e<="9"||!(e<"A")&&(e<="Z"||(e<"a"?"_"===e:e<="z"||e.charCodeAt(0)>=170&&python.Tokenizer._identifierChar.test(e)))}static _isDecimal(e){return e>="0"&&e<="9"||"_"===e}static _isHex(e){return python.Tokenizer._isDecimal(e)||e>="a"&&e<="f"||e>="A"&&e<="F"||"_"===e}static _isOctal(e){return e>="0"&&e<="7"||"_"===e}static _isBinary(e){return"0"===e||"1"===e||"_"===e}_get(e){return e>=this._text.length?"\0":this._text[e]}_skipLine(){for(;this._position0&&python.Tokenizer._isNewline(e)))break;this._position=this._newLine(this._position),this._lineStart=this._position,this._line++}}}_newLine(e){return"\n"===this._get(e)&&"\r"===this._get(e+1)||"\r"===this._get(e)&&"\n"===this._get(e+1)?e+2:e+1}_tokenize(e){if("\n"!==this._token.type&&this._skipWhitespace(),"dedent"===this._token.type&&(this._indentation.pop(),this._outdent--,this._outdent>0))return{type:"dedent",value:""};if("\n"==e.type){let e="",t=this._position;for(;t0){const t=this._indentation.length>0?this._indentation[this._indentation.length-1]:"";if(e.length>t.length)i="indent",this._indentation.push(e);else if(e.length>0&&e.length=0&&e.length=this._text.length)return{type:"eof",value:""};this._indentation.length>0&&(i="dedent",this._outdent=this._indentation.length)}switch(i){case"indent":case"dedent":return{type:i,value:e}}}if(this._position>=this._text.length)return{type:"eof",value:""};const t=this._get(this._position),i=this._string();if(i)return i;switch(t){case"(":case"[":case"{":return this._brackets++,{type:t,value:t};case")":case"]":case"}":if(0===this._brackets)throw new python.Error("Unexpected '"+t+"'"+this.location);return this._brackets--,{type:t,value:t};case",":case";":case"?":return{type:t,value:t};default:{const e=this._number();if(e)return e;if("."===t){let e=this._position+1;for(;"."===this._get(e);)e++;const t=this._text.substring(this._position,e);return{type:t,value:t}}const i=this._identifier();if(i)return i;const s=this._operator();if(s)return s;break}}if("."===t)return{type:t,value:t};if("\\"===t)return{type:"\\",value:t};if(python.Tokenizer._isNewline(t))return{type:"\n",value:this._text.substring(this._position,this._newLine(this._position))};throw new python.Error("Unexpected token '"+t+"'"+this.location())}_number(){let e=this._get(this._position);const t="-"===e||"+"===e?1:0;let i=this._position+t;if(e=this._get(i),"0"===e){let e=0;const t=this._get(i+1);if("x"!==t&&"X"!==t||!python.Tokenizer._isHex(this._get(i+2)))if("b"!==t&&"B"!==t||!python.Tokenizer._isBinary(this._get(i+2)))if("o"!==t&&"O"!==t||!python.Tokenizer._isOctal(this._get(i+2))){if(t>="0"&&t<="7"){for(i++;python.Tokenizer._isOctal(this._get(i));)i+=1;"l"!==this._get(i)&&"L"!==this._get(i)||(i+=1),e=8}}else{for(i+=2;python.Tokenizer._isOctal(this._get(i));)i++;e=8}else{for(i+=2;python.Tokenizer._isBinary(this._get(i));)i++;e=2}else{for(i+=2;python.Tokenizer._isHex(this._get(i));)i+=1;"l"!==this._get(i)&&"L"!==this._get(i)||(i+=1),e=16}if(e>0&&"."!==this._get(i)){const t=this._text.substring(this._position,i),s=-1!==t.indexOf("_")?t.split("_").join(""):t;if(!isNaN(parseInt(s,e)))return{type:"number",value:t}}}i=this._position+t;let s=!1;if(this._get(i)>="1"&&this._get(i)<="9"){for(;python.Tokenizer._isDecimal(this._get(i));)i++;e=this._get(i).toLowerCase(),s="."!==e&&"e"!==e}if("0"===this._get(i)&&(i++,e=this._get(i).toLowerCase(),s=!python.Tokenizer._isDecimal(e)&&"."!==e&&"e"!==e&&"j"!==e),s){if("j"===this._get(i)||"J"===this._get(i)||"l"===this._get(i)||"L"===this._get(i))return{type:"number",value:this._text.substring(this._position,i+1)};const e=this._text.substring(this._position,i);if(!isNaN(parseInt(e,10)))return{type:"number",value:e}}if(i=this._position+t,this._get(i)>="0"&&this._get(i)<="9"||"."===this._get(i)&&this._get(i+1)>="0"&&this._get(i+1)<="9"){for(;python.Tokenizer._isDecimal(this._get(i));)i++;for("."===this._get(i)&&i++;python.Tokenizer._isDecimal(this._get(i));)i++;if(i>this._position+t)if("e"===this._get(i)||"E"===this._get(i))if(i++,"-"!=this._get(i)&&"+"!=this._get(i)||i++,python.Tokenizer._isDecimal(this._get(i)))for(;python.Tokenizer._isDecimal(this._get(i));)i++;else i=this._position;else for(;python.Tokenizer._isDecimal(this._get(i));)i++;if(i>this._position+t){if("j"===this._get(i)||"J"===this._get(i))return{type:"number",value:this._text.substring(this._position,i+1)};const e=this._text.substring(this._position,i),t=-1!=e.indexOf("_")?e.split("_").join(""):e;if(!isNaN(parseFloat(t)))return{type:"number",value:e}}}return null}_identifier(){let e=this._position;if(python.Tokenizer._isIdentifierStartChar(this._get(e)))for(e++;python.Tokenizer._isIdentifierChar(this._get(e));)e++;if(e>this._position){const t=this._text.substring(this._position,e);return{type:"id",value:t,keyword:python.Tokenizer._isKeyword(t)}}return null}_operator(){let e=0;const t=this._get(this._position),i=this._get(this._position+1),s=this._get(this._position+2);switch(t){case"+":case"&":case"|":case"^":case"=":case"!":case"%":case"~":e="="===i?2:1;break;case"-":e="="===i||">"===i?2:1;break;case"*":e="*"===i?"="===s?3:2:"="===i?2:1;break;case"/":e="/"===i?"="===s?3:2:"="===i?2:1;break;case"<":e=">"===i?2:"<"===i?"="===s?3:2:"="===i?2:1;break;case">":e=">"===i?"="===s?3:2:"="===i?2:1;break;case"@":e="="===i?2:1;break;case":":e="="===i?2:1}if(e>0){const t=this._text.substring(this._position,this._position+e);return{type:t,value:t}}return null}_string(){let e=this._position,t=-1;if("'"===this._get(e)||'"'===this._get(e))t="";else if("'"===this._get(e+1)||'"'===this._get(e+1)){const i=this._get(e);switch(i.toLowerCase()){case"b":case"f":case"r":case"u":t=i}}else if("'"===this._get(e+2)||'"'===this._get(e+2)){const e=this._text.substr(this._position,2);switch(e.toLowerCase()){case"br":case"fr":case"rb":case"rf":case"ur":t=e}}if(t.length>=0){e+=t.length;let i="",s=0;const n=this._get(e),r=this._get(e+1),o=this._get(e+2);switch(n){case"'":i=n,s="'"===r&&"'"===o?3:1;break;case'"':i=n,s='"'===r&&'"'===o?3:1}if(e+=s,1==s)for(;ee.require("./python").then((r=>pytorch.Metadata.open(e).then((o=>{try{const i=pytorch.Container.open(t,o,s,r,((t,s)=>{const r=t&&t.message?t.message:t.toString();e.exception(new pytorch.Error(r.replace(/\.$/,"")+" in '"+n+"'."),s)}));return new pytorch.Model(o,i)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new pytorch.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}}))))))}},pytorch.Model=class{constructor(t,e){this._format=e.format,this._producer=e.producer||"",this._graphs=[new pytorch.Graph(t,e)]}get format(){return this._format}get graphs(){return this._graphs}},pytorch.Graph=class{constructor(t,e){if(this._nodes=[],this._inputs=[],this._outputs=[],this._groups=!0,this._littleEndian=e.littleEndian,e.format.startsWith("TorchScript ")){this._name=e.name;const n=e.trace(),s=new Map;if(e.data){const t=[e.data];for(;t.length>0;){const e=t.shift();for(const n of Object.keys(e))if("__module__"!==n&&"__name__"!==n&&"__parent__"!==n){const r=e[n];if(!Array.isArray(r)&&r===Object(r))if(pytorch.Utility.isTensor(r)){const t=r;t.__parent__=e,!t.initializer&&t.storage&&(t.initializer=new pytorch.Tensor(t.name,t,!0)),t.__variable__&&1===t.__count__&&s.set(t.__variable__,t)}else r&&r.__module__&&r.__name__&&(r.__parent__=e,r.__id__||(r.__id__=n),t.push(r))}}}if(n){if(e.inputs)for(const t of e.inputs)this._inputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]));if(e.outputs)for(const t of e.outputs)this._outputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]));if(e.nodes)for(const n of e.nodes){const e={type:n.type,node:n};this._nodes.push(new pytorch.Node(t,"",e,s))}}e.data&&this._loadScriptModule(t,e,e.data,s)}else if(e.data){const n=e.data;this._type=n.__module__&&n.__name__?n.__module__+"."+n.__name__:"";const s="data";this._inputs.push(new pytorch.Parameter(s,!0,[new pytorch.Argument(s,null,null)]));const r=this._loadModule(t,e.data,[],[s]);for(const t of r)this._outputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]))}else if(e.state)for(const n of e.state){const e=n.attributes||[],s=n.states.map((t=>new pytorch.Parameter(t.name,!0,t.arguments.map((t=>{const e=new pytorch.Tensor(t.id,t.value,this._littleEndian);return new pytorch.Argument(t.id,null,e)}))))),r={name:n.name,type:n.type||"torch.nn.Module",attributes:e,inputs:s,outputs:[]};this._nodes.push(new pytorch.Node(t,"",r,null))}}_loadModule(t,e,n,s){if(e.__module__&&"torch.nn.modules.container"===!e.__module__&&(!e._modules||0==e._modules.length))return this._createNode(n,"",e,s),[];if(!e._modules)throw new pytorch.Error("Module does not contain modules.");for(const r of e._modules){const e=r[0],o=r[1];if(r&&o)switch(o.__module__+"."+o.__name__){case"torch.nn.modules.container.Sequential":n.push(e),s=this._loadModule(t,o,n,s),n.pop(e);break;case"torchvision.models.densenet._Transition":case"torchvision.models.resnet.Bottleneck":case"torchvision.models.densenet._DenseBlock":case"torchvision.models.densenet._DenseLayer":case"torchvision.models.inception.BasicConv2d":case"torchvision.models.inception.InceptionAux":case"torchvision.models.inception.InceptionA":case"torchvision.models.inception.InceptionB":case"torchvision.models.inception.InceptionC":case"torchvision.models.inception.InceptionD":case"torchvision.models.inception.InceptionE":n.push(e),s=[this._createNode(t,n,e,o,s,this._littleEndian).name],n.pop(e);break;default:s=[this._createNode(t,n,e,o,s).name]}}return s}_createNode(t,e,n,s,r){const o=s.__module__+"."+s.__name__,i=t.type(o);let a=[{name:"input"}];i&&i.inputs&&i.inputs.length>0&&(a=i.inputs.slice());const c=[new pytorch.Parameter(a.shift().name,!0,r.map((t=>new pytorch.Argument(t,null,null))))],_=s._parameters||s._buffers||[];for(const t of _){const e=t[0],n=t[1];let s=!0,r="";if(a.length>0){const t=a.shift();r=t.name,s=!1!==t.visible}if(t&&n&&(n.data||n.storage)){let t=null;n.data?t=new pytorch.Tensor("",n.data,this._littleEndian):n.storage&&(t=new pytorch.Tensor("",n,this._littleEndian)),c.push(new pytorch.Parameter(r||e,s,[new pytorch.Argument("",null,t)]))}}const u=e.join("/"),h=u?u+"/"+n:n,l=[new pytorch.Parameter("output",!0,[new pytorch.Argument(h,null,null)])],p=[];for(const t of Object.keys(s))t.startsWith("_")||p.push({name:t,value:s[t]});const d={name:h,type:o,attributes:p,inputs:c,outputs:l},m=new pytorch.Node(t,u,d,{});return this._nodes.push(m),m}_loadScriptModule(t,e,n,s){if(n){if(pytorch.Graph._getParameters(n).length>0&&!n.__hide__){const e={module:n};this._nodes.push(new pytorch.Node(t,"",e,s))}const r=pytorch.Graph._getSubmodules(n);for(const n of r)this._loadScriptModule(t,e,n,s)}}static _getParameters(t){const e=[];if(t&&t.__module__&&t.__name__)for(const n of Object.keys(t))if(pytorch.Utility.isTensor(t[n])){const s=t[n];s.__id__=n,e.push(s)}return e}static _getSubmodules(t){const e=[];if(t&&t.__module__&&t.__name__)for(const n of Object.keys(t))if(!n.startsWith("__")){const s=t[n];s&&s.__module__&&s.__name__&&!pytorch.Utility.isTensor(s)&&e.push(s)}return e}get type(){return this._type}get name(){return this._name}get groups(){return this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},pytorch.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},pytorch.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new pytorch.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e,this._initializer=n}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},pytorch.Node=class{constructor(t,e,n,s){if(this._metadata=t,this._group=e||"",this._name=n.name||"",n.module||n.node){this._attributes=[],this._inputs=[],this._outputs=[];let e=n.module;if(e){this._type="torch.nn.modules.module.Module";for(const t of pytorch.Graph._getParameters(e))this._inputs.push(new pytorch.Parameter(t.__id__,!0,[new pytorch.Argument("",null,t.initializer||null)])),t.__variable__&&this._outputs.push(new pytorch.Parameter(t.__id__,!0,[new pytorch.Argument(t.__variable__,null,null)]))}if(n.node){this._type=n.type;const r=t.type(this._type);e=null;let o=!0,i=0;for(const t of n.node.inputs){for(const n of t){const t=s.get(n.id);if(t){if(!t.__parent__||null!=e&&e!=t.__parent__){o=!1;break}e=t.__parent__,i++}}if(!o)break}if(e)if(pytorch.Graph._getParameters(e).filter((t=>"num_batches_tracked"!==t.__id__)).length==i&&o){e.__hide__=!0;for(const t of n.node.inputs)for(const e of t){const t=s.get(e.id);t&&t.initializer&&(e.initializer=t.initializer)}}else e=null;for(let t=0;tt&&(e=r.inputs[t].name),this._inputs.push(new pytorch.Parameter(e,!0,n.node.inputs[t].map((t=>new pytorch.Argument(t.id,null,t.initializer||null)))))}for(let t=0;tt&&(e=r.outputs[t].name),this._outputs.push(new pytorch.Parameter(e,!0,n.node.outputs[t].map((t=>new pytorch.Argument(t.id,null,null)))))}for(const e of n.node.attributes){const n=e.name,s=e.value,r=t.attribute(this._type,n);this._attributes.push(new pytorch.Attribute(r,n,s))}}if(e&&e.__id__){let t=e;for(this._name=t.__id__;null!=t.__parent__&&(t=t.__parent__,t.__parent__||t.__id__);)this._name=[t.__id__,this._name].join(".")}}else this._type=n.type,this._inputs=n.inputs,this._outputs=n.outputs,this._attributes=n.attributes.map((e=>{const n=t.attribute(this._type,e.name);return new pytorch.Attribute(n,e.name,e.value)}))}get name(){return this._name}get group(){return this._group}get type(){const t=this._type.indexOf(":");return-1===t?this._type:this._type.substring(0,t)}get metadata(){return this._metadata.type(this._type)}get function(){return this._type.startsWith("torch.nn.modules.")&&"torch.nn.modules.module.Module"!==this._type}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},pytorch.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,"training"===this._name)return this._visible=!1,void(this._type="boolean");if(n&&n.type)switch(n.type){case"number":case"string":case"boolean":case"id":this._value=n.value}if(t){switch(Object.prototype.hasOwnProperty.call(t,"type")&&(this._type=t.type),this._type){case"boolean":"False"==this._value?this._value=!1:"True"==this._value&&(this._value=!0);break;case"int32":case"int64":"number"!=typeof this._value&&"string"==typeof this._value&&(this._value=parseInt(this._value,10));break;case"float32":case"float64":"number"!=typeof this._value&&"string"==typeof this._value&&(this._value=parseFloat(this._value));break;case"int32[]":case"int64[]":switch(this._value.type){case"list":this._value=this._value.value.map((t=>{if("number"===t.type){const e=parseInt(t.value,10);if(!Number.isNaN(t.value-e))return e}return t}))}}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(JSON.stringify(t.default)==JSON.stringify(this._value)||Array.isArray(this._value)&&!Array.isArray(t.default)&&this.value.every((e=>e==t.default))))&&(this._visible=!1)}Array.isArray(n)&&n.length>0&&n.every((t=>t&&t.__module__&&t.__module__.startsWith("torch.nn")))&&(this._value="?")}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},pytorch.Tensor=class{constructor(t,e,n){this._name=t||"",this._type=new pytorch.TensorType(e.storage.dataType,new pytorch.TensorShape(e.size)),this._data=e.storage.data,this._littleEndian=n}get kind(){return"Tensor"}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return pytorch.Tensor._stringify(e,""," ")}_context(){const t={state:null,index:0,count:0};if(!this._type.dataType)return t.state="Tensor has no data type.",t;switch(this._type.dataType){case"uint8":case"qint8":case"int8":case"int16":case"int32":case"int64":case"float16":case"float32":case"float64":break;default:return t.state="Tensor data type '"+this._type.dataType+"' is not supported.",t}return this._type.shape?this._data?(t.data=this._data,t.dataType=this._type.dataType,t.dimensions=this._type.shape.dimensions,t.dataView=new DataView(t.data.buffer,t.data.byteOffset,t.data.byteLength),t):(t.state="Tensor data is empty.",t):(t.state="Tensor has no dimensions.",t)}_decode(t,e){const n=[],s=0==t.dimensions.length?[1]:t.dimensions,r=s[e];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"uint8":n.push(t.dataView.getUint8(t.index,this._littleEndian)),t.index++,t.count++;break;case"qint8":case"int8":n.push(t.dataView.getInt8(t.index,this._littleEndian)),t.index++,t.count++;break;case"int16":n.push(t.dataView.getInt16(t.index,this._littleEndian)),t.index+=2,t.count++;break;case"int32":n.push(t.dataView.getInt32(t.index,this._littleEndian)),t.index+=4,t.count++;break;case"int64":n.push(new long.Long(t.dataView.getUint32(t.index,!0),t.dataView.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":n.push(t.dataView.getFloat16(t.index,this._littleEndian)),t.index+=2,t.count++;break;case"float32":n.push(t.dataView.getFloat32(t.index,this._littleEndian)),t.index+=4,t.count++;break;case"float64":n.push(t.dataView.getFloat64(t.index,this._littleEndian)),t.index+=8,t.count++}}else for(let s=0;st.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return 0==t.dimensions.length?n[0]:n}static _stringify(t,e,n){if(Array.isArray(t)){const s=[];s.push(e+"[");const r=t.map((t=>pytorch.Tensor._stringify(t,e+n,n)));return r.length>0&&s.push(r.join(",\n")),s.push(e+"]"),s.join("\n")}return t&&long.Long.isLong(t)?e+t.toString():"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},pytorch.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},pytorch.TensorShape=class{constructor(t){this._dimensions=t||[]}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length>0?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},pytorch.Metadata=class{static open(t){return pytorch.Metadata._metadata?Promise.resolve(pytorch.Metadata._metadata):t.request(null,"pytorch-metadata.json","utf-8").then((t=>(pytorch.Metadata._metadata=new pytorch.Metadata(t),pytorch.Metadata._metadata))).catch((()=>(pytorch.Metadata._metadata=new pytorch.Metadata(null),pytorch.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e){t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema));const e=t.name.indexOf(":");if(-1!==e){const n=t.name.substring(0,e);this._map.has(n)||this._map.set(n,[]),this._map.get(n).push(t.name)}}}}type(t){const e=this._map.get(t);return e?Array.isArray(e)?e.map((t=>this._map.get(t))):e:null}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){this._attributeCache.set(n,null);const e=this.type(t);if(e){if(e.inputs)for(const n of e.inputs)this._attributeCache.set(t+":"+n.name,n);if(e.attributes)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n)}}return this._attributeCache.get(n)}},pytorch.Error=class extends Error{constructor(t){super(t),this.name="Error loading PyTorch model."}},pytorch.Execution=class{constructor(t,e,n){const s=this;this._python=t,this._sources=e,this._exceptionCallback=n,this._utf8Decoder=new TextDecoder("utf-8"),this._unknownNameMap=new Set,this._knownPackageMap=new Set(["torch","torchvision","collections","__builtin__","_codecs","argparse","numpy"]),this._packages=new Map,this._context=new pytorch.Execution.Context,this._context.scope.builtins={},this._context.scope.builtins.type={__module__:"builtins",__name__:"type"},this._context.scope.builtins.module={__module__:"builtins",__name__:"module",__class__:this._context.scope.builtins.type},this._context.scope.builtins.function={__module__:"builtins",__name__:"function",__class__:this._context.scope.builtins.type},this._context.scope.builtins.method={__module__:"builtins",__name__:"method",__class__:this._context.scope.builtins.type},this._context.scope.builtins.dict={__module__:"builtins",__name__:"dict",__class__:this._context.scope.builtins.type},this._context.scope.builtins.list={__module__:"builtins",__name__:"list",__class__:this._context.scope.builtins.type},this._context.scope.builtins.str={__module__:"builtins",__name__:"str",__class__:this._context.scope.builtins.type},this._context.scope.builtins.tuple={__module__:"builtins",__name__:"tuple",__class__:this._context.scope.builtins.type},this._context.scope.typing={__name__:"typing",__class__:this._context.scope.builtins.module},this._context.scope.typing._GenericAlias={__module__:"typing",__name__:"_GenericAlias",__class__:this._context.scope.builtins.type},this._context.scope.typing._SpecialForm={__module__:"typing",__name__:"_SpecialForm",__class__:this._context.scope.builtins.type},this._context.scope.typing._VariadicGenericAlias={__module__:"typing",__name__:"_VariadicGenericAlias",__class__:this._context.scope.builtins.type},this._context.scope.typing.Dict={__module__:"typing",__name__:"Dict",__class__:this._context.scope.typing._VariadicGenericAlias,__origin__:this._context.scope.builtins.dict},this._context.scope.typing.List={__module__:"typing",__name__:"List",__class__:this._context.scope.typing._GenericAlias,__origin__:this._context.scope.builtins.list},this._context.scope.typing.Optional={__module__:"typing",__class__:this._context.scope.typing._SpecialForm},this._context.scope.typing.Tuple={__module__:"typing",__name__:"Tuple",__class__:this._context.scope.typing._GenericAlias,__origin__:this._context.scope.builtins.tuple},this._context.scope.torch={__name__:"torch",__class__:this._context.scope.builtins.module},this._context.scope.torch.Tensor={__module__:"torch",__name__:"Tensor",__class__:this._context.scope.builtins.type},this._registerConstructor("argparse.Namespace",(function(t){this.args=t})),this._registerConstructor("torch.autograd.variable.Variable",(function(){})),this._registerConstructor("torch.backends.cudnn.rnn.Unserializable",(function(){})),this._registerConstructor("torch.device",(function(t,e){this.type=t,e&&(this.index=e)})),this._registerConstructor("torch.distributions.multivariate_normal.MultivariateNormal",(function(){})),this._registerConstructor("torch.nn.backends.thnn._get_thnn_function_backend",(function(){})),this._registerConstructor("torch.nn.intrinsic.modules.fused.ConvReLU2d",(function(){})),this._registerConstructor("torch.nn.modules.activation.CELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.ELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.GELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.GLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.Hardtanh",(function(){})),this._registerConstructor("torch.nn.modules.activation.LeakyReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.LogSigmoid",(function(){})),this._registerConstructor("torch.nn.modules.activation.LogSoftmax",(function(){})),this._registerConstructor("torch.nn.modules.activation.MultiheadAttention",(function(){})),this._registerConstructor("torch.nn.modules.activation.ReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.ReLU6",(function(){})),this._registerConstructor("torch.nn.modules.activation.PReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.RReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.SELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.Sigmoid",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softmax",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softmax2d",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softplus",(function(){})),this._registerConstructor("torch.nn.modules.activation.Tanh",(function(){})),this._registerConstructor("torch.nn.modules.activation.Threshold",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm1d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm2d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm3d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.SyncBatchNorm",(function(){})),this._registerConstructor("torch.nn.modules.container.ModuleDict",(function(){})),this._registerConstructor("torch.nn.modules.container.ModuleList",(function(){})),this._registerConstructor("torch.nn.modules.container.ParameterList",(function(){})),this._registerConstructor("torch.nn.modules.container.Sequential",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv1d",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv2d",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv3d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose1d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose2d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose3d",(function(){})),this._registerConstructor("torch.nn.modules.distance.CosineSimilarity",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout2d",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout3d",(function(){})),this._registerConstructor("torch.nn.modules.fold.Unfold",(function(){})),this._registerConstructor("torch.nn.modules.flatten.Flatten",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm1d",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm2d",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm3d",(function(){})),this._registerConstructor("torch.nn.modules.linear.Linear",(function(){})),this._registerConstructor("torch.nn.modules.linear.Identity",(function(){})),this._registerConstructor("torch.nn.modules.loss.BCELoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.BCEWithLogitsLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.CrossEntropyLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.L1Loss",(function(){})),this._registerConstructor("torch.nn.modules.loss.MSELoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.NLLLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.SmoothL1Loss",(function(){})),this._registerConstructor("torch.nn.modules.normalization.CrossMapLRN2d",(function(){})),this._registerConstructor("torch.nn.modules.normalization.GroupNorm",(function(){})),this._registerConstructor("torch.nn.modules.normalization.LayerNorm",(function(){})),this._registerConstructor("torch.nn.modules.normalization.LocalResponseNorm",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReflectionPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReflectionPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad3d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ZeroPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad3d",(function(){})),this._registerConstructor("torch.nn.modules.pixelshuffle.PixelShuffle",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.FractionalMaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool3d",(function(){})),this._registerConstructor("torch.nn.modules.rnn.GRU",(function(){})),this._registerConstructor("torch.nn.modules.rnn.GRUCell",(function(){})),this._registerConstructor("torch.nn.modules.rnn.LSTM",(function(){})),this._registerConstructor("torch.nn.modules.rnn.LSTMCell",(function(){})),this._registerConstructor("torch.nn.modules.rnn.RNN",(function(){})),this._registerConstructor("torch.nn.modules.sparse.Embedding",(function(){})),this._registerConstructor("torch.nn.modules.sparse.EmbeddingBag",(function(){})),this._registerConstructor("torch.nn.modules.transformer.TransformerEncoder",(function(){})),this._registerConstructor("torch.nn.modules.transformer.TransformerEncoderLayer",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.Upsample",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.UpsamplingBilinear2d",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.UpsamplingNearest2d",(function(){})),this._registerConstructor("torch.nn.parallel.data_parallel.DataParallel",(function(){})),this._registerConstructor("torch.nn.parallel.distributed.DistributedDataParallel",(function(){})),this._registerConstructor("torch.nn.parameter.Parameter",(function(t,e){this.data=t,this.requires_grad=e})),this._registerConstructor("torch.nn.quantized.modules.functional_modules.FloatFunctional",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNorm",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNormStateDictHook",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook",(function(){})),this._registerConstructor("torch.nn.utils.weight_norm.WeightNorm",(function(){})),this._registerConstructor("torch.optim.adam.Adam",(function(){})),this._registerConstructor("torch.optim.adagrad.Adagrad",(function(){})),this._registerConstructor("torch.optim.lr_scheduler.MultiStepLR",(function(){})),this._registerConstructor("torch.optim.lr_scheduler.StepLR",(function(){})),this._registerConstructor("torch.optim.rmsprop.RMSprop",(function(){})),this._registerConstructor("torch.optim.sgd.SGD",(function(){})),this._registerConstructor("torch.quantization.stubs.DeQuantStub",(function(){})),this._registerConstructor("torch.quantization.stubs.QuantStub",(function(){})),this._registerConstructor("torchvision.datasets.folder.ImageFolder",(function(){})),this._registerConstructor("torchvision.models.alexnet.AlexNet",(function(){})),this._registerConstructor("torchvision.models.densenet.DenseNet",(function(){})),this._registerConstructor("torchvision.models.densenet._DenseBlock",(function(){})),this._registerConstructor("torchvision.models.densenet._DenseLayer",(function(){})),this._registerConstructor("torchvision.models.densenet._Transition",(function(){})),this._registerConstructor("torchvision.models.detection._utils.BalancedPositiveNegativeSampler",(function(){})),this._registerConstructor("torchvision.models.detection._utils.BoxCoder",(function(){})),this._registerConstructor("torchvision.models.detection._utils.Matcher",(function(){})),this._registerConstructor("torchvision.models.detection.backbone_utils.BackboneWithFPN",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.FasterRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.FastRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.TwoMLPHead",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNNHeads",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.roi_heads.RoIHeads",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.AnchorGenerator",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.RegionProposalNetwork",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.RPNHead",(function(){})),this._registerConstructor("torchvision.models.detection.transform.GeneralizedRCNNTransform",(function(){})),this._registerConstructor("torchvision.models.googlenet.BasicConv2d",(function(){})),this._registerConstructor("torchvision.models.googlenet.GoogLeNet",(function(){})),this._registerConstructor("torchvision.models.googlenet.Inception",(function(){})),this._registerConstructor("torchvision.models.inception.BasicConv2d",(function(){})),this._registerConstructor("torchvision.models.inception.Inception3",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionAux",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionA",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionB",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionC",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionD",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionE",(function(){})),this._registerConstructor("torchvision.models.mobilenet.ConvBNReLU",(function(){})),this._registerConstructor("torchvision.models.mobilenet.MobileNetV2",(function(){})),this._registerConstructor("torchvision.models.mobilenet.InvertedResidual",(function(){})),this._registerConstructor("torchvision.models.resnet.Bottleneck",(function(){})),this._registerConstructor("torchvision.models.resnet.BasicBlock",(function(){})),this._registerConstructor("torchvision.models.quantization.resnet.QuantizableBottleneck",(function(){})),this._registerConstructor("torchvision.models.quantization.resnet.QuantizableResNet",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPP",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPPConv",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPPPooling",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.DeepLabHead",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.DeepLabV3",(function(){})),this._registerConstructor("torchvision.models.segmentation.fcn.FCN",(function(){})),this._registerConstructor("torchvision.models.segmentation.fcn.FCNHead",(function(){})),this._registerConstructor("torchvision.models.shufflenetv2.ShuffleNetV2",(function(){})),this._registerConstructor("torchvision.models.shufflenetv2.InvertedResidual",(function(){})),this._registerConstructor("torchvision.models.squeezenet.Fire",(function(){})),this._registerConstructor("torchvision.models.squeezenet.SqueezeNet",(function(){})),this._registerConstructor("torchvision.models.resnet.ResNet",(function(){})),this._registerConstructor("torchvision.models.vgg.VGG",(function(){})),this._registerConstructor("torchvision.models.video.resnet.BasicBlock",(function(){})),this._registerConstructor("torchvision.models.video.resnet.BasicStem",(function(){})),this._registerConstructor("torchvision.models.video.resnet.Conv3DNoTemporal",(function(){})),this._registerConstructor("torchvision.models.video.resnet.Conv3DSimple",(function(){})),this._registerConstructor("torchvision.models.video.resnet.VideoResNet",(function(){})),this._registerConstructor("torchvision.models._utils.IntermediateLayerGetter",(function(){})),this._registerConstructor("torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork",(function(){})),this._registerConstructor("torchvision.ops.feature_pyramid_network.LastLevelMaxPool",(function(){})),this._registerConstructor("torchvision.ops.misc.ConvTranspose2d",(function(){})),this._registerConstructor("torchvision.ops.misc.FrozenBatchNorm2d",(function(){})),this._registerConstructor("torchvision.ops.poolers.LevelMapper",(function(){})),this._registerConstructor("torchvision.ops.poolers.MultiScaleRoIAlign",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Compose",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Normalize",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Resize",(function(){})),this._registerConstructor("torchvision.transforms.transforms.ToTensor",(function(){})),this._registerConstructor("torch.ByteStorage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="uint8"})),this._registerConstructor("torch.CharStorage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="int8"})),this._registerConstructor("torch.ShortStorage",(function(t){this.size=t,this.dataTypeSize=2,this.dataType="int16"})),this._registerConstructor("torch.IntStorage",(function(t){this.size=t,this.dataTypeSize=4,this.dataType="int32"})),this._registerConstructor("torch.LongStorage",(function(t){this.size=t,this.dataTypeSize=8,this.dataType="int64"})),this._registerConstructor("torch.HalfStorage",(function(t){this.size=t,this.dataTypeSize=2,this.dataType="float16"})),this._registerConstructor("torch.FloatStorage",(function(t){this.size=t,this.dataTypeSize=4,this.dataType="float32"})),this._registerConstructor("torch.DoubleStorage",(function(t){this.size=t,this.dataTypeSize=8,this.dataType="float64"})),this._registerConstructor("torch.QInt8Storage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="qint8"})),this._registerConstructor("torch.FloatTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.DoubleTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.cuda.FloatTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.cuda.DoubleTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("numpy.dtype",(function(t,e,n){switch(t){case"i1":this.name="int8",this.itemsize=1;break;case"i2":this.name="int16",this.itemsize=2;break;case"i4":this.name="int32",this.itemsize=4;break;case"i8":this.name="int64",this.itemsize=8;break;case"b1":case"u1":this.name="uint8",this.itemsize=1;break;case"u2":this.name="uint16",this.itemsize=2;break;case"u4":this.name="uint32",this.itemsize=4;break;case"u8":this.name="uint64",this.itemsize=8;break;case"f4":this.name="float32",this.itemsize=4;break;case"f8":this.name="float64",this.itemsize=8;break;default:if(t.startsWith("V"))this.itemsize=Number(t.substring(1)),this.name="void"+(8*this.itemsize).toString();else if(t.startsWith("O"))this.itemsize=Number(t.substring(1)),this.name="object";else if(t.startsWith("S"))this.itemsize=Number(t.substring(1)),this.name="string";else if(t.startsWith("U"))this.itemsize=Number(t.substring(1)),this.name="string";else{if(!t.startsWith("M"))throw new pytorch.Error("Unknown dtype '"+t.toString()+"'.");this.itemsize=Number(t.substring(1)),this.name="datetime"}}this.align=e,this.copy=n,this.__setstate__=function(t){switch(t.length){case 8:this.version=t[0],this.byteorder=t[1],this.subarray=t[2],this.names=t[3],this.fields=t[4],this.elsize=t[5],this.alignment=t[6],this.int_dtypeflags=t[7];break;default:throw new pytorch.Error("Unknown numpy.dtype setstate length '"+t.length.toString()+"'.")}}})),this._registerConstructor("numpy.core.multiarray._reconstruct",(function(t,e,n){this.subtype=t,this.shape=e,this.dtype=n,this.__setstate__=function(t){this.version=t[0],this.shape=t[1],this.typecode=t[2],this.is_f_order=t[3],this.rawdata=t[4]},this.__read__=function(t){const e={},n=this.subtype.split(".");e.__name__=n.pop(),e.__module__=n.join("."),e.dtype=this.typecode,e.shape=this.shape;let s=e.dtype.itemsize;for(let t=0;t0&&te?1+(t-1-e)/(0-n):0})),this._registerFunction("torch._unwrap_optional",(function(t){return t})),this._registerFunction("torch.add",(function(t,e){if("number"==typeof t&&"number"==typeof e)return t*e;throw new pytorch.Error("Unknown torch.add expression type.")})),this._registerFunction("torch.append",(function(t,e){return t.push(e),e})),this._registerFunction("torch.dict",(function(t){if(t)throw new pytorch.Error("'torch.dict' arguments not supported.");return{}})),this._registerFunction("torch.dim",(function(t){return t&&t.size?t.size.length:0})),this._registerFunction("torch.eq",(function(t,e){if("string"==typeof t&&"string"==typeof e)return t===e;if("number"==typeof t&&"number"==typeof e)return t===e;throw new pytorch.Error("Unknown 'torch.eq' expression type.")})),this._registerFunction("torch.floordiv",(function(){})),this._registerFunction("torch.gt",(function(t,e){if("number"==typeof t&&"number"==typeof e&&!isNaN(t)&&!isNaN(e))return t>e;if(isNaN(t)&&!isNaN(e))return!0;throw new pytorch.Error("Unknown 'torch.gt' expression type.")})),this._registerFunction("torch.jit._pickle.build_boollist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_doublelist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_intlist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_tensorlist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_tensor_from_id",(function(t){return t})),this._registerFunction("torch.jit._pickle.restore_type_tag",(function(t){return t})),this._registerFunction("torch.keys",(function(t){return Object.keys(t)})),this._registerFunction("torch.len",(function(t){return t?t.length:NaN})),this._registerFunction("torch.le",(function(t,e){if("number"==typeof t&&"number"==typeof e)return!isNaN(t)&&!isNaN(e)&&t<=e;throw new pytorch.Error("Unknown 'torch.le' expression type.")})),this._registerFunction("torch.list",(function(t){return t})),this._registerFunction("torch.list_with_default",(function(t){return t})),this._registerFunction("torch.lt",(function(t,e){if("number"==typeof t&&"number"==typeof e)return t=0&&et[e]))})),this._registerFunction("torch.warn",(function(){})),this._registerFunction("uninitialized",(function(t){if(t&&"typing"===t.__module__&&"Tuple"===t.__name__)return[];if(t&&"typing"===t.__module__&&"List"===t.__name__)return[];if(t&&"typing"===t.__module__&&"Dict"===t.__name__)return{};if(t&&"torch"===t.__module__&&"Tensor"===t.__name__)return{__module__:t.__module__,__name__:t.__name__};throw new pytorch.Error("Unsupported uninitialized argument '"+JSON.stringify(t)+"'.")}))}get context(){return this._context}parse(t){const e=this._sources[t];if(e){const n=this._utf8Decoder.decode(e),s=new this._python.Parser(n,t).parse();if(!s)throw new pytorch.Error("Module '"+t+"' parse error.");return s}return null}package(t,e,n){if(this._python&&!this._packages.has(t)){e=e||"code/"+t.split(".").join("/")+".py";const s=this.parse(e);if(s){let r=this._context.getx(t);void 0===r&&(r={},this._context.setx(t,r)),r.__class__=this._context.scope.builtins.module,r.__name__=t,r.__file__=e,this._packages.set(t,r);const o=this._context.push(r);if(this._block(s.body,o),n)return s}}return this._packages.get(t)}type(t){const e=this._context.getx(t);if(void 0!==e)return e;const n=t.split("."),s=n.pop(),r=n.join("."),o=this.package(r);return o?o[s]:null}invoke(t,e){const n=this.type(t);if(n){if(n.__class__===this._context.scope.builtins.type){const t={};return t.__proto__=n,t.__init__&&"function"==typeof t.__init__&&t.__init__.apply(t,e),t}if(n.__class__===this._context.scope.builtins.function)return n.__call__?n.__call__(e):n.apply(null,e)}this._raiseUnkownName(t);const s=t.split("."),r=s.pop();return{__module__:s.join("."),__name__:r}}call(t,e,n,s){const r=this._target(t,s),o=n.map((t=>this.expression(t,s)));if(!r||null!==e&&!r[e]){const n=pytorch.Utility.target(t)+"."+e;if(this.type(n))return this.invoke(n,o);throw new pytorch.Error("Unsupported function '"+n+"'.")}const i=e?r[e]:r;if(i.__class__===this._context.scope.builtins.type){const t={};return t.__proto__=i,t.__init__&&"function"==typeof t.__init__&&t.__init__.apply(t,n),t}if(i.__class__===this._context.scope.builtins.function&&i.__call__)return i.__call__(o);if(i.__class__===this._context.scope.builtins.method&&i.__call__)return i.__call__([r].concat(o));if("function"==typeof i)return i.apply(r,o);throw new pytorch.Error("Unsupported call expression.")}apply(t,e,n){const s=Array.prototype.slice.call(e);n=n.push();for(const e of t.parameters)n.set(e.name,s.shift());return this._block(t.body.statements,n)}_block(t,e){for(t=Array.prototype.slice.call(t);t.length>0;){const n=t.shift();switch(n.type){case"pass":break;case"return":return this.expression(n.expression,e);case"def":{const t=e.get("__name__"),s=this,r=e.get("__class__");let o=null;if(r===this._context.scope.builtins.type)o=this._context.scope.builtins.method;else{if(r!==this._context.scope.builtins.module)throw new pytorch.Error("Invalid function scope.");o=this._context.scope.builtins.function}const i={__class__:o,__globals__:e,__module__:t,__name__:n.name,__code__:n,__call__:function(t){return s.apply(this.__code__,t,this.__globals__)}};e.set(n.name,i);break}case"class":{const t={__class__:this._context.scope.builtins.type,__module__:e.get("__name__"),__name__:n.name};e.set(n.name,t),e=e.push(t),this._block(n.body.statements,e),e=e.pop();break}case"var":e.set(n.name,void 0);break;case"=":this.expression(n,e);break;case"if":{const s=this.expression(n.condition,e);if(!0===s||s){t=n.then.statements.concat(t);break}if(!1===s){t=n.else.statements.concat(t);break}throw new pytorch.Error("Unknown condition.")}case"for":if(1==n.target.length&&1===n.variable.length&&"id"===n.variable[0].type){const s=this.expression(n.target[0],e),r=n.variable[0];let o=[];for(const t of s)o.push({type:"=",target:r,expression:{type:"number",value:t}}),o=o.concat(n.body.statements);t=o.concat(t);break}throw new pytorch.Error("Unsupported 'for' statement.");case"call":this.expression(n,e);break;case"import":for(const t of n.modules){const n=pytorch.Utility.target(t.name),s=this.package(n);t.as&&e.set(t.as,s)}break;default:throw new pytorch.Error("Unknown statement '"+n.type+"'.")}}}expression(t,e){const n=e.getx("self");switch(t.type){case"=":{const n=t.target;if("id"===n.type)return void e.set(n.value,this.expression(t.expression,e));if("[]"===n.type){if("id"===n.target.type&&"list"===n.arguments.type&&1===n.arguments.value.length){const s=this.expression(n.arguments.value[0],e);return"__annotations__"===n.target.value&&e.set(n.target.value,e.get(n.target.value)||{}),void(e.get(n.target.value)[s]=this.expression(t.expression,e))}}else{if("."===n.type&&"id"===n.member.type)return void(this.expression(n.target,e)[n.member.value]=this.expression(t.expression,e));if("tuple"===n.type){const s=this.expression(t.expression,e);if(n.value.length==s.length&&n.value.every((t=>"id"===t.type))){for(let t=0;tthis.expression(t,e)));case"string":return t.value.substring(1,t.value.length-1);case"number":return Number(t.value);case"[]":{if("id"===t.target.type&&"list"===t.arguments.type&&1===t.arguments.value.length&&e.get(t.target.value)){const n=this.expression(t.arguments.value[0],e);return e.get(t.target.value)[n]}const n=this.expression(t.target,e);if(n&&"list"===t.arguments.type&&(n.__class__===this.context.scope.typing._VariadicGenericAlias||n.__class__===this.context.scope.typing._GenericAlias||n.__class__===this.context.scope.typing._SpecialForm)){const s=Object.assign({},n);return s.__args__=t.arguments.value.map((t=>this.expression(t,e))),s}if("list"===t.arguments.type&&1===t.arguments.value.length)return n[this.expression(t.arguments.value[0],e)];break}case".":if("id"==t.member.type)return this._target(t.target,e)[t.member.value];throw new pytorch.Error("Unsupported field expression.");case"call":return"id"===t.target.type&&"annotate"===t.target.value&&2===t.arguments.length||"id"===t.target.type&&"unchecked_cast"===t.target.value&&2===t.arguments.length?this.expression(t.arguments[1],e):"."===t.target.type?this.call(t.target.target,t.target.member.value,t.arguments,e):this.call(t.target,null,t.arguments,e);case"id":{switch(t.value){case"self":return n;case"None":return null;case"True":return!0;case"False":return!1}const s=this._context.scope.builtins[t.value]||this._context.scope.typing[t.value]||this._context.scope.torch[t.value];return!s||s.__class__!==this._context.scope.builtins.type&&s.__class__!==this._context.scope.typing._VariadicGenericAlias&&s.__class__!==this._context.scope.typing._GenericAlias&&s.__class__!==this._context.scope.typing._SpecialForm?e.get(t.value):s}case"tuple":return t.value.map((t=>this.expression(t,e)))}throw new pytorch.Error("Unknown expression '"+t.type+"'.")}_target(t,e){let n=t,s="";for(;;){if("."!==n.type||!n.member||"id"!==n.member.type){if("id"===n.type&&"self"!==n.value&&"CONSTANTS"!==n.value){s=n.value+s;break}s=null;break}s="."+n.member.value+s,n=n.target}if(s){let t=e.getx(s);if(!t&&(t=this.package(s),!t))throw new pytorch.Error("Failed to resolve module '"+s+"'.");return t}return this.expression(t,e)}_registerFunction(t,e){if(this._context.getx(t))throw new pytorch.Error("Function '"+t+"' is already registered.");const n=t.split(".");e.__class__=this._context.scope.builtins.function,e.__name__=n.pop(),e.__module__=n.join("."),this._context.setx(t,e)}_registerConstructor(t,e){if(this._context.getx(t))throw new pytorch.Error("Constructor '"+t+"' is already registered.");const n=t.split("."),s=n.pop(),r=n.join("."),o={__class__:this._context.scope.builtins.type,__name__:s,__module__:r,__init__:function(){e.apply(this,arguments)}};this._context.setx(t,o)}_raiseUnkownName(t){t&&!this._unknownNameMap.has(t)&&(this._unknownNameMap.add(t),this._knownPackageMap.has(t.split(".").shift())&&this._exceptionCallback(new pytorch.Error("Unknown function '"+t+"'."),!1))}},pytorch.Execution.Context=class{constructor(t,e){this._parent=t||null,this._scope=e||{}}push(t){return new pytorch.Execution.Context(this,t)}pop(){return this._parent}get scope(){return this._scope}set(t,e){this._scope[t]=e}get(t){return t in this._scope?this._scope[t]:this._parent?this._parent.get(t):void 0}setx(t,e){const n=t.split(".");if(1==n.length)this.set(n[0],e);else{let t=this.get(n[0]);for(t||(t={},this.set(n[0],t)),n.shift();n.length>1;){const e=n.shift();t[e]=t[e]||{},t=t[e]}t[n[0]]=e}}getx(t){const e=t.split(".");let n=this.get(e[0]);if(n){for(e.shift();e.length>0&&n[e[0]];)n=n[e[0]],e.shift();if(0===e.length)return n}}},pytorch.Container=class{static open(t,e,n,s,r){if(t.entries("zip").some((t=>"model.json"===t.name||"data.pkl"===t.name||t.name.endsWith("/model.json")||t.name.endsWith("/data.pkl"))))return new pytorch.Container.Zip(t.entries("zip"),e,n,s,r);const o=t.buffer;return o&&o.length>14&&128==o[0]&&o[1]<16&&[138,10,108,252,156,70,249,32,106,168,80,25].every(((t,e)=>t==o[e+2]))?new pytorch.Container.Pickle(o,n,r):t.entries("tar").some((t=>"pickle"==t.name))?new pytorch.Container.Tar(t.entries("tar"),n,r):null}},pytorch.Container.Tar=class{constructor(t,e,n){this._entries=t,this._pickle=e,this._exceptionCallack=n}get format(){return"PyTorch v0.1.1"}get data(){return this._unpickle(),this._data}get state(){return this._unpickle(),this._state}get littleEndian(){return this._unpickle(),this._littleEndian}_unpickle(){if(!this._entries)return;this._data=null,this._state=null,this._littleEndian=!0;const t=new pytorch.Execution(null,[],this._exceptionCallback),e={};for(const t of this._entries)switch(t.name){case"sys_info":e.sys_info=t.data;break;case"pickle":e.pickle=t.data;break;case"storages":e.storages=t.data;break;case"tensors":e.tensors=t.data}if(this._exceptionCallback=null,this._entries=null,e.sys_info){const n=new this._pickle.Unpickler(e.sys_info).load(((e,n)=>t.invoke(e,n)));if(1e3!=n.protocol_version)throw new pytorch.Error("Unsupported protocol version '"+n.protocol_version+"'.");if(n.type_sizes&&(n.type_sizes.int&&4!=n.type_sizes.int||n.type_sizes.long&&4!=n.type_sizes.long||n.type_sizes.short&&2!=n.type_sizes.short))throw new pytorch.Error("Unsupported type sizes.");this._littleEndian=n.little_endian}const n={};if(e.storages){const s=new this._pickle.Unpickler(e.storages),r=s.load(((e,n)=>t.invoke(e,n)));for(let e=0;et.invoke(e,n)));for(let e=0;en[t];let r=new this._pickle.Unpickler(e.pickle).load(((e,n)=>t.invoke(e,n)),s);if(r){if(!(r instanceof Map)){const t=new Map;for(const e of Object.keys(r))t.set(e,r[e]);r=t}this._state=[];const t={};if(r instanceof Map)for(const e of r){const n=e[0],s=e[1];if(!n||!s){this._state=null;break}const r={};if(r.id=n,r.value=null,s&&"torch.nn.parameter"===s.__module__&&"Parameter"===s.__name__?r.value=s[0]:pytorch.Utility.isTensor(s)&&(r.value=s),!r.value){this._state=null;break}const o=r.id.split(".");if(o.length<2){this._state=null;break}r.name=o.pop();const i=o.join(".");let a=t[i];a||(a={},a.name=i,a.states=[],t[i]=a,this._state.push(a)),a.states.push({name:r.name,arguments:[r]})}}}}},pytorch.Container.Pickle=class{constructor(t,e,n){this._buffer=t,this._pickle=e,this._exceptionCallback=n}get format(){return"PyTorch v0.1.10"}get data(){return this._unpickle(),this._data}get state(){return this._unpickle(),this._state}get littleEndian(){return this._unpickle(),this._littleEndian}_unpickle(){if(!this._buffer)return;const t=new pytorch.Execution(null,[],this._exceptionCallback),e=new this._pickle.Unpickler(this._buffer);this._buffer=null,this._pickle=null,this._exceptionCallback=null,e.load();const n=e.load();if(1001!=n)throw new pytorch.Error("Unsupported protocol version '"+n+"'.");const s=e.load();if(1001!=s.protocol_version)throw new pytorch.Error("Unsupported protocol version '"+s.protocol_version+"'.");if(s.type_sizes&&(s.type_sizes.int&&4!=s.type_sizes.int||s.type_sizes.long&&4!=s.type_sizes.long||s.type_sizes.short&&2!=s.type_sizes.short))throw new pytorch.Error("Unsupported type sizes.");this._littleEndian=s.little_endian;const r=new Map,o=new Map,i=e.load(((e,n)=>t.invoke(e,n)),(e=>{const n=e.shift(),s=e;switch(n){case"module":{const t=s[0],e=s[2];return r.set(t,e),s[0]}case"storage":{const e=s.shift(),n=s.shift();s.shift();const r=s.shift(),i=s.shift();if(!o.has(n)){const s=t.invoke(e,[r]);o.set(n,s)}if(i){const t=i.shift();if(i.shift(),i.shift(),!o.has(t)){const e=null;o.set(t,e)}return o.get(t)}return o.get(n)}}throw new pytorch.Error("Unknown persistent load type '"+n+"'.")}));if(!i)throw new pytorch.Error("File format is not PyTorch.");const a=e.load();for(const t of a){const n=o.get(t);if(long.Long.fromBytesLE(e.read(8),!1).toNumber()!=n.size)throw new pytorch.Error("Storage size mismatch.");n.data=e.read(n.dataTypeSize*n.size)}if(this._data=this._findRootModule(i),this._data||(this._state=this._findStateDict(i)),!this._data&&!this._state&&"None"!==i)throw new pytorch.Error("File does not contain root module or state dictionary.")}_findRootModule(t){const e=[t,t.model,t.net];for(const t of e)if(t&&t._modules)return t;return null}_findStateDict(t){if(!t)return null;if(t.encoder&&Array.isArray(t.encoder)&&t.decoder&&Array.isArray(t.decoder)&&!t.state_dict&&(t=t.encoder.concat(t.decoder)),t instanceof Map){const e={};for(const n of t){const t=n[0],s=n[1];e[t]=s}t=e}const e=[t.state_dict,t.state,t.model_state,t.model,t.model_state_dict,t.net_dict,t.params,t.generator,t.discriminator,t.g_state,t.network,t.net,t.netG,t.net_states,t.state_dict_stylepredictor,t.state_dict_ghiasi,t];for(const t of e){let e=null;if(e=e||this._convertStateDictList(t),e=e||this._convertStateDictMap(t),e=e||this._convertStateDictGroupMap(t),e)return e}return null}_convertStateDictList(t){if(t&&Array.isArray(t)&&t.every((t=>t.__module__&&t.__name__&&Object.keys(t).filter((e=>pytorch.Utility.isTensor(t[e]).length>0))))){const e=[];for(const n of t){const t={type:n.__module__+"."+n.__name__,states:[],attributes:[]};for(const e of Object.keys(n)){const s=n[e];pytorch.Utility.isTensor(s)?t.states.push({name:e,arguments:[{id:"",value:s}]}):t.attributes.push({name:e,value:s})}e.push(t)}return e}if(!t||Array.isArray(t)||t instanceof Map||(t=new Map(Object.keys(t).map((e=>[e,t[e]])))),t&&t instanceof Map){for(const e of t){const t=e[0],n=e[1];if(!t||!n)return null;if(!pytorch.Utility.isTensor(n)&&!(t.endsWith("._packed_params.dtype")||t.endsWith("._packed_params._packed_params")&&Array.isArray(n)&&n.every((t=>pytorch.Utility.isTensor(t)))))return null}const e=new Map;for(const n of t){const t=n[0],s=n[1];if(null!==s){let n="",r="";if(t.endsWith("_packed_params.dtype"))r="_packed_params.dtype",n=t.substring(0,t.length-r.length-1);else if(t.endsWith("_packed_params._packed_params")&&Array.isArray(s))r="_packed_params._packed_params",n=t.substring(0,t.length-r.length-1);else{let e=t.split(".");e.length<2&&(e=["",e[0]]),r=e.pop(),n=e.join(".")}e.has(n)||e.set(n,{name:n,states:[],attributes:[]});const o=e.get(n);switch(r){case"_packed_params.dtype":o.attributes.push({name:r,value:s});break;case"_packed_params._packed_params":o.states.push({name:r,arguments:s.map((t=>({id:"",value:t})))});break;default:if(o.states.push({name:r,arguments:[{id:t,value:s}]}),""==o.name&&o.states.length>4)return null}}}return e.values()}return null}_convertStateDictMap(t){if(!t||Array.isArray(t))return null;const e=[],n={};for(const s in t){const r=s.split(".");if(r.length<1)return null;const o={};if(o.id=s,o.name=r.pop(),o.value=t[s],o.value&&"torch.nn.parameter"===o.value.__module__&&"Parameter"===o.value.__name__&&pytorch.Utility.isTensor(o.value.data)&&(o.value=o.value.data),!pytorch.Utility.isTensor(o.value))return null;const i=r.join(".");let a=n[i];a||(a={},a.name=i,a.states=[],n[i]=a,e.push(a)),a.states.push({name:o.name,arguments:[o]})}return e}_convertStateDictGroupMap(t){if(!t||Array.isArray(t))return null;const e=[],n={};for(const s in t){let r=n[s];r||(r={},r.name=s,r.states=[],r.attributes=[],n[s]=r,e.push(r));const o=t[s];if(!o)return null;if(o instanceof Map)for(const t of o){const e=t[0],n=t[1];if(!e)return null;if(n&&!pytorch.Utility.isTensor(n))return null;const o={id:s+"."+e,value:n};r.states.push({name:e,arguments:[o]})}else{if(o instanceof Uint8Array)return null;if(Object(o)!==o)return null;{let t=!1;for(const e in o){const n=o[e];if(pytorch.Utility.isTensor(n)){const o={id:s+"."+e,value:n};r.states.push({name:e,arguments:[o]}),t=!0}else if(n!==Object(n))r.attributes.push({name:e,value:n});else{if(!n||!n.data||"torch.nn.parameter"!==n.__module__||"Parameter"!==n.__name__)return null;{const o={id:s+"."+e,value:n.data};r.states.push({name:e,arguments:[o]}),t=!0}}}if(!t)return null}}}return e}},pytorch.Container.Zip=class{constructor(t,e,n,s,r){this._entries=t,this._metadata=e,this._pickle=n,this._python=s,this._exceptionCallback=r;const o=this._entries.find((t=>"model.json"==t.name||"data.pkl"==t.name||t.name.endsWith("/model.json")||t.name.endsWith("/data.pkl")));if(!o)throw new pytorch.Error("PyTorch Zip container does not contain 'data.pkl' or 'model.json'.");const i=o.name.lastIndexOf("/");this._prefix=-1===i?"":o.name.substring(0,i+1),this._utf8Decoder=new TextDecoder("utf-8")}get format(){if(void 0===this._format)if(this._entry("model.json"))this._format=this._entry("attributes.pkl")?"TorchScript v1.1":"TorchScript v1.0";else if(this._entry("data.pkl")){const t=this._entry("version"),e=t?this._utf8Decoder.decode(t.data).split("\n").shift():"",n={1:"v1.3",2:"v1.4",3:"v1.6",4:"v1.7"}[e];n||this._exceptionCallback(new pytorch.Error("Unsupported PyTorch Zip version '"+e+"'.")),this._format=(this._entry("constants.pkl")?"TorchScript":"PyTorch")+" "+(n||"v-"+e.toString())}return this._format}get producer(){return this.data?this._producer:""}get name(){return this._name}get data(){if(void 0===this._data){this._data=null;const t=this._entry("data.pkl");if(t&&t.data)this._data=this._unpickle(t.data,this._storage("data"));else{const t=this._entry("model.json");if(t){const e=JSON.parse(this._utf8Decoder.decode(t.data));this._producer=e.producerName+(e.producerVersion?" v"+e.producerVersion:""),this._data=e.mainModule||{},this._name=this._data.name||"",this._data.torchscriptArena&&(this._torchscriptArena=this._data.torchscriptArena.key);const n=[this._data],s=new Map;for(const t of this._entries)s.set(t.name,t.data);const r=new Map([["FLOAT","Float"],["FLOAT16","Half"],["DOUBLE","Double"],["INT8","Char"],["INT32","Int"],["INT64","Long"]]);this._constants=e.tensors||[];for(const t of this._constants){const e=this._prefix+t.data.key;if(!r.has(t.dataType))throw new pytorch.Error("Unknown tensor data type '"+t.dataType+"'.");const n=r.get(t.dataType);t.__module__="torch",t.__name__="Tensor",t.name=t.data.key,t.size=t.dims?t.dims.map((t=>parseInt(t,10))):null,t.storage=this.execution.invoke("torch."+n+"Storage",[t.size]),t.storage.data=s.get(e)}for(;n.length>0;){const t=n.shift();if(t.__module__||t.__name__||(t.__module__="torch.nn.modules.module",t.__name__="Module"),t.name&&(t.__id__=t.name),t.submodules){for(const e of t.submodules)t[e.name]=e,e.__parent__=t,n.push(e);delete t.submodules}let e=[];t.parameters&&(e=e.concat(t.parameters),delete t.parameters),t.arguments&&(e=e.concat(t.arguments),delete t.arguments);for(const n of e){const e=this._constants[n.tensorId];t[n.name]=e,n.__module__&&n.__name__||(n.__module__="torch",n.__name__="Tensor")}}}}}return this._data}get constants(){if(void 0===this._constants){this._constants=[];const t=this._entry("constants.pkl");t&&t.data&&(this._constants=this._unpickle(t.data,this._storage("constants")))}return this._constants}get execution(){if(void 0===this._execution){this._types=new Map;const t={};for(const e of this._entries)if(e.name.startsWith(this._prefix+"code")){const n=e.name.substring(this._prefix.length);if(t[n])throw new pytorch.Error("Duplicate source file '"+n+"'.");t[n]=e.data}this._execution=new pytorch.Container.Zip.Execution(this._python,t,this._exceptionCallback,this._metadata);const e={};for(let t=0;te.name==this._prefix+t))}_unpickle(t,e){const n=new Map;return new this._pickle.Unpickler(t).load(((t,e)=>this.execution.invoke(t,e)),(t=>{const s=t.shift();if("storage"!==s)throw new pytorch.Error("Unknown persistent load type '"+s+"'.");const r=t.shift(),o=t.shift();t.shift();const i=t.shift();let a=null;n.has(o)?a=n.get(o):(a=this.execution.invoke(r,[i]),a.data=e.get(o),n.set(o,a));const c=t.shift();if(c){const t=c.shift();c.shift(),c.shift();let e=null;return n.has(t)?e=n.get(o):(e=null,n.set(t,e)),e}return a}))}_storage(t){const e=new Map,n=this._prefix+t+"/";for(const t of this._entries)if(t.name.startsWith(n)){const s=t.name.substring(n.length);e.set(s,t.data)}return e}_type(t){if(!this._types.has(t)){const e=t.split("."),n=e.pop(),s="code/"+e.join("/")+".py",r=this.execution.parse(s);if(r)for(const e of r.body)if("class"===e.type&&e.name==n){this._types.set(t,e);break}}return this._types.get(t)}trace(){if(this._inputs=[],this._outputs=[],this.execution.reset(),this._torchscriptArena){const t=this.execution.parse(this._torchscriptArena);for(const e of t.body)if("def"==e.type){const t=this,n=this.execution.context,s={__class__:this.execution.context.scope.builtins.function,__name__:e.name,__code__:e,__call__:function(e){return t.execution.apply(this.__code__,e,n)}};this.data[e.name]=s}}if(this.data.forward){const t=[this.data];if(this.data.forward.__code__&&this.data.forward.__code__.parameters)for(const e of this.data.forward.__code__.parameters)if("self"!==e.name){const n=e.parameterType;"type"===n.type&&n.name.type&&("Tensor"===n.name.value&&(this._inputs.push(e.name),t.push({__module__:"torch",__name__:"Tensor",__variable__:e.name,__origin__:"trace-input-tensor"})),"Tuple"===n.name.value&&n.arguments.every((t=>"type"===t.type&&"id"===t.name.type&&"Tensor"===t.name.value))&&(this._inputs.push(e.name),t.push(n.arguments.map((()=>({__module__:"torch",__name__:"Tensor",__variable__:e.name,__origin__:"trace-input-tuple"}))))),"List"===n.name.value&&n.arguments.every((t=>"type"===t.type&&"id"===t.name.type&&"Tensor"===t.name.value))&&(this._inputs.push(e.name),t.push([{__module__:"torch",__name__:"Tensor",__variable__:e.name,size:[NaN,NaN],__origin__:"trace-input-list"}])))}const e=this.data.forward.__call__(t),n=Array.isArray(e)?e:[e];for(const t of n)pytorch.Utility.isTensor(t)&&this._outputs.push(t.__variable__);return this._nodes=this.execution.nodes,!0}throw new pytorch.Error("Module 'forward' not implemented.")}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},pytorch.Container.Zip.Execution=class extends pytorch.Execution{constructor(t,e,n,s){super(t,e,n),this._metadata=s,this.reset()}reset(){this._nodes=[],this._variableIndex=0}get nodes(){return this._nodes}call(t,e,n,s){let r=pytorch.Utility.target(t),o=null;if(r&&r+"."+e=="ops.prim.NumToTensor"&&1===n.length&&"call"===n[0].type&&"id"==n[0].target.member.type){const t=n[0];r=pytorch.Utility.target(t.target.target),n=t.arguments,e=t.target.member.value,o=["int64"]}if(r){const t=r+"."+e;let i=this._metadata.type(t);if(i){Array.isArray(i)||(i=[i]);const e=n.map((t=>"="===t.type&&t.target&&"id"===t.target.type?this.expression(t.expression,s):this.expression(t,s)));for(const r of i){const i=Array.prototype.slice.call(n),a=Array.prototype.slice.call(e),c={type:r.name,inputs:[],attributes:[],outputs:[]},_=[];let u=!1;const h=Array.prototype.slice.call(r.inputs||[]).concat(Array.prototype.slice.call(r.attributes||[]));for(;h.length>0&&a.length>0;){if(i.every((t=>"="===t.type&&t.target&&"id"===t.target.type))&&h.every((t=>"tensor"!==t.type&&"tensor[]"!==t.type))){const t=new Map;for(const e of h)t.set(e.name,e);for(;i.length>0;){const e=i.shift(),n=a.shift(),s=t.get(e.target.value);if(!s){u=!0;break}if(!pytorch.Utility.isType(n,s.type)){if(s.optional)continue;u=!0;break}c.attributes.push({name:s.name,value:n})}continue}if(u)break;const t=h.shift();switch(t.type){case"tensor":{let e=a[0];if(Array.isArray(e)||!pytorch.Utility.isTensor(e)&&null!==e){if(t.optional){void 0===e&&(i.shift(),a.shift());continue}u=!0;break}i.shift(),a.shift(),null===e&&(e={}),e.__variable__||(e.__variable__=this._variable());const n=[];n.push({id:e.__variable__}),_.push(e),c.inputs.push(n);break}case"tensor[]":{const e=a[0];if(!Array.isArray(e)||!e.every((t=>pytorch.Utility.isTensor(t)||null===t))){if(t.optional)continue;u=!0;break}i.shift(),a.shift();const n=[];for(let t of e)null===t&&(t={}),t.__variable__||(t.__variable__=this._variable()),n.push({id:t.__variable__}),_.push(t);c.inputs.push(n);break}default:{const e=i[0],n=a[0];if(!pytorch.Utility.isType(n,t.type)){if(t.optional)continue;u=!0;break}if("="===e.type)throw new pytorch.Error("Expected named argument.");i.shift(),a.shift(),c.attributes.push({name:t.name,value:n});break}}if(u)break}if(u)continue;const l=[];for(const e of r.outputs)switch(e.type){case"tensor":{const e={__module__:"torch",__name__:"Tensor",__origin__:"invoke-output-"+t};switch(t){case"torch.cat":case"torch.conv2d":case"torch.dropout":case"torch.flatten":case"torch.max_pool2d":case"torch.quantize_per_tensor":case"torch.relu_":case"torch.hardtanh_":case"torch.slice":e.size=[NaN,NaN,NaN,NaN];break;case"torch.conv3d":e.size=[NaN,NaN,NaN,NaN,NaN];break;case"torch.embedding":e.size=[NaN,NaN,NaN];break;case"torch.ones":case"torch.zeros":case"torch.zeros_like":e.size=this.expression(n[0],s)}e.__variable__=this._variable(),l.push(e),c.outputs.push([{id:e.__variable__}]);break}case"tensor[]":{let e=1;switch(t){case"torch.chunk":e=c.attributes.filter((t=>"chunks"==t.name))[0].value}const n=[],s=[];for(let r=0;r1?l:l[0]}}}}return super.call(t,e,n,s)}_variable(){return this._variableIndex++,this._variableIndex.toString()}},pytorch.ScalarType={uint8:0,int8:1,int16:2,int32:3,int64:4,float16:5,float32:6,float64:7,complex32:8,complex64:9,complex128:10,boolean:11,qint8:12,quint8:13,qint32:14,bfloat16:15},pytorch.MemoryFormat={Contiguous:0,Preserve:1,ChannelsLast:2,ChannelsLast3d:3},pytorch.Layout={Strided:0,Sparse:1,Mkldnn:2},pytorch.Utility=class{static target(t){return"id"==t.type?t.value:"."==t.type?pytorch.Utility.target(t.target)+"."+pytorch.Utility.target(t.member):null}static isTensor(t){return t&&("torch"===t.__module__||"torch.cuda"===t.__module__)&&t.__name__&&t.__name__.endsWith("Tensor")}static isType(t,e){switch(e){case"tensor":return!Array.isArray(t)&&(pytorch.Utility.isTensor(t)||null===t);case"tensor[]":return Array.isArray(t)&&t.length>0&&t.every((t=>pytorch.Utility.isTensor(t)||null===t));case"boolean":return!0===t||!1===t;case"int64":return Number.isInteger(t)||isNaN(t);case"int64[]":return Array.isArray(t)&&t.every((t=>Number.isInteger(t)||Number.isNaN(t)||void 0===t));case"float32":case"float64":return null!==t&&t!==Object(t);case"Layout":case"ScalarType":case"MemoryFormat":return Number.isInteger(t);case"Device":return null===t||t===Object(t);case"scalar":return null!==t||t!==Object(t)}return!0}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=pytorch.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/shim.f615a7b13d08c028a2c9.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/shim.f615a7b13d08c028a2c9.js new file mode 100644 index 0000000000000000000000000000000000000000..4bdf3d2f6d2150f71fded3c4b3c58b5b355dc851 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/shim.f615a7b13d08c028a2c9.js @@ -0,0 +1 @@ +(()=>{var t,i={87958:()=>{if("undefined"!=typeof window&&void 0!==window.Long&&(window.long={Long:window.Long}),DataView.prototype.getFloat16||(DataView.prototype.getFloat16=function(t,i){const e=this.getUint16(t,i),s=(31744&e)>>10;let r=1023&e;return r=0==s?r/1024*6103515625e-14:31==s?r?NaN:1/0:DataView.__float16_pow[s]*(1+r/1024),32768&e?-r:r},DataView.__float16_pow={1:1/16384,2:1/8192,3:1/4096,4:1/2048,5:1/1024,6:1/512,7:1/256,8:1/128,9:1/64,10:1/32,11:1/16,12:1/8,13:1/4,14:.5,15:1,16:2,17:4,18:8,19:16,20:32,21:64,22:128,23:256,24:512,25:1024,26:2048,27:4096,28:8192,29:16384,30:32768,31:65536}),!DataView.prototype.setFloat16){DataView.prototype.setFloat16=function(t,i,e){DataView.__float16_float[0]=i;const s=(i=DataView.__float16_int[0])>>>23&255,r=8388607&i,n=i>>>16&32768|DataView.__float16_base[s]|r>>DataView.__float16_shift[s];this.setUint16(t,n,e)},DataView.__float16_float=new Float32Array(1),DataView.__float16_int=new Uint32Array(DataView.__float16_float.buffer,0,DataView.__float16_float.length),DataView.__float16_base=new Uint32Array(256),DataView.__float16_shift=new Uint32Array(256);for(let t=0;t<256;++t){const i=t-127;i<-27?(DataView.__float16_base[t]=0,DataView.__float16_shift[t]=24):i<-14?(DataView.__float16_base[t]=1024>>-i-14,DataView.__float16_shift[t]=-i-1):i<=15?(DataView.__float16_base[t]=i+15<<10,DataView.__float16_shift[t]=13):i<128?(DataView.__float16_base[t]=31744,DataView.__float16_shift[t]=24):(DataView.__float16_base[t]=31744,DataView.__float16_shift[t]=13)}}DataView.prototype.getBits||(DataView.prototype.getBits=function(t,i){if(t*=i,i>(this.byteLength<<3)-t)throw new RangeError;let e=0,s=0;for(;s>3)>>8-n-r&~(255<{var s={},r=r||{Long:e(27808)};s.get=t=>(s._map=s._map||new Map,s._map.has(t)||s._map.set(t,{}),s._map.get(t)),s.Long=r.Long,s.Reader=class{constructor(t){this._buffer=t,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength)}get root(){return this.int32(this._position)+this._position}identifier(t){if(4!==t.length)throw new s.Error("File identifier must be 4 characters in length.");for(let i=0;i<4;i++)if(t.charCodeAt(i)!=this.int8(this._position+4+i))return!1;return!0}bool(t){return!!this.int8(t)}bool_(t,i,e){return(i=this._offset(t,i))?this.bool(t+i):e}int8(t){return this.uint8(t)<<24>>24}int8_(t,i,e){return(i=this._offset(t,i))?this.int8(t+i):e}uint8(t){return this._buffer[t]}uint8_(t,i,e){return(i=this._offset(t,i))?this.uint8(t+i):e}int16(t){return this._dataView.getInt16(t,!0)}int16_(t,i,e){return(i=this._offset(t,i))?this.int16(t+i):e}uint16(t){return this._dataView.getUint16(t,!0)}uint16_(t,i,e){return(i=this._offset(t,i))?this.uint16(t+i):e}int32(t){return this._dataView.getInt32(t,!0)}int32_(t,i,e){return(i=this._offset(t,i))?this.int32(t+i):e}uint32(t){return this._dataView.getUint32(t,!0)}uint32_(t,i,e){return(i=this._offset(t,i))?this.int32(t+i):e}int64(t){return new s.Long(this.int32(t),this.int32(t+4))}uint64(t){return new s.Long(this.uint32(t),this.uint32(t+4))}float32(t){return this._dataView.getFloat32(t,!0)}float32_(t,i,e){return(i=this._offset(t,i))?this.float32(t+i):e}float64(t){return this._dataView.getFloat64(t,!0)}float64_(t,i,e){return(i=this._offset(t,i))?this.float64(t+i):e}string(t,i){t+=this.int32(t);const e=this.int32(t);var s="",r=0;if(t+=4,1===i)return this._buffer.subarray(t,t+e);for(;r>10),56320+(1023&n)))}return s}string_(t,i,e){return(i=this._offset(t,i))?this.string(t+i):e}bools_(t,i){if(i=this._offset(t,i)){const e=this._length(t+i);i=this._vector(t+i);const s=new Array(e);for(let t=0;t>3)),this.uint32(i+(t>>3)+4),!1);return r}return[]}strings_(t,i){if(i=this._offset(t,i)){const e=this._length(t+i);i=this._vector(t+i);const s=new Array(e);for(let t=0;t{var s=s||{},r=r||{Long:e(27808)};s.get=t=>(s._map=s._map||new Map,s._map.has(t)||s._map.set(t,{}),s._map.get(t)),s.Reader=class{constructor(t){this._buffer=t,this._length=t.length,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._decoder=new TextDecoder("utf-8")}static create(t){return new s.Reader(t)}next(t){return void 0===t?this._length:this._position+t}end(t){return this._positionthis._length)throw this._indexOutOfRangeError(t);return this._position+=t,this._buffer.slice(i,e)}uint32(){let t=4294967295;if(t=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return t;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=4,this._dataView.getFloat32(t,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=8,this._dataView.getFloat64(t,!0)}array(t,i,e){if(2==(7&e)){const e=this.uint32()+this._position;for(;this._position0)throw new s.Error("Invalid packed float array.");const i=this.uint32(),e=this._position+i,r=i>>>2;t=i>1048576?new Float32Array(r):new Array(r);let n=this._position;for(let i=0;i0)throw new s.Error("Invalid packed float array.");const i=this.uint32(),e=this._position+i,r=i>>>3;t=i>1048576?new Float64Array(r):new Array(r);let n=this._position;for(let i=0;ithis._length)throw this._indexOutOfRangeError(t);this._position+=t}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw new s.Error("invalid wire type "+t+" at offset "+this._position)}}pair(t,i,e){this.skip(),this._position++;const r="object"==typeof i?s.LongBits.hash(i()):i();this._position++;const n=e();t[r]=n}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const t=this._readFixed32();this._position+=4;const i=this._readFixed32();return new s.LongBits(t,i)}_readLongVarint(){const t=new s.LongBits(0,0);let i=0;if(!(this._length-this._position>4)){for(;i<3;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t}return t.lo=(t.lo|(127&this._buffer[this._position++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t;if(t.lo=(t.lo|(127&this._buffer[this._position])<<28)>>>0,t.hi=(t.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return t;if(i=0,this._length-this._position>4){for(;i<5;++i)if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}else for(;i<5;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}throw new s.Error("Invalid varint encoding.")}_indexOutOfRangeError(t){return RangeError("index out of range: "+this._position+" + "+(t||1)+" > "+this._length)}},s.TextReader=class{constructor(t){this._text=t,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(t){return new s.TextReader(t)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const t=this.peek();return this._depth>0&&"}"===t?(this.expect("}"),this.match(";"),this._depth--,!0):""===t}tag(){const t=this.read(),i=this.peek();return"["!==i&&"{"!==i&&this.expect(":"),t}assert(t){const i=this.tag();if(i!==t)throw new s.Error("Unexpected '"+i+"' instead of '"+t+"'"+this.location())}integer(){const t=this.read(),i=Number.parseInt(t,10);if(Number.isNaN(t-i))throw new s.Error("Couldn't parse integer '"+t+"'"+this.location());return this.semicolon(),i}float(){let t=this.read();if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;t.endsWith("f")&&(t=t.substring(0,t.length-1));const i=Number.parseFloat(t);if(Number.isNaN(t-i))throw new s.Error("Couldn't parse float '"+t+"'"+this.location());return this.semicolon(),i}string(){const t=this.read();if(t.length<2)throw new s.Error("String is too short"+this.location());const i=t[0];if("'"!==i&&'"'!==i)throw new s.Error("String is not in quotes"+this.location());if(i!==t[t.length-1])throw new s.Error("String quotes do not match"+this.location());const e=t.substring(1,t.length-1);return this.semicolon(),e}boolean(){const t=this.read();switch(t){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new s.Error("Couldn't parse boolean '"+t+"'"+this.location())}bytes(){const t=this.string();let i=0,e=0;const r=t.length,n=new Uint8Array(r);for(;i=r)throw new s.Error("Unexpected end of bytes string"+this.location());switch(o=t.charCodeAt(i++),o){case 39:n[e++]=39;break;case 92:n[e++]=92;break;case 34:n[e++]=34;break;case 114:n[e++]=13;break;case 110:n[e++]=10;break;case 116:n[e++]=9;break;case 98:n[e++]=8;break;case 88:case 120:for(let o=0;o<2;o++){if(i>=r)throw new s.Error("Unexpected end of bytes string"+this.location());let o=t.charCodeAt(i++);if(o=o>=65&&o<=70?o-55:o>=97&&o<=102?o-87:o>=48&&o<=57?o-48:-1,-1===o)throw new s.Error("Unexpected hex digit '"+o+"' in bytes string"+this.location());n[e]=n[e]<<4|o}e++;break;default:if(o<48||o>57)throw new s.Error("Unexpected character '"+o+"' in bytes string"+this.location());i--;for(let o=0;o<3;o++){if(i>=r)throw new s.Error("Unexpected end of bytes string"+this.location());const o=t.charCodeAt(i++);if(o<48||o>57)throw new s.Error("Unexpected octal digit '"+o+"' in bytes string"+this.location());n[e]=n[e]<<3|o-48}e++}}}return n.slice(0,e)}enum(t){const i=this.read();if(!Object.prototype.hasOwnProperty.call(t,i)){const t=Number.parseInt(i,10);if(!Number.isNaN(i-t))return this.semicolon(),t;throw new s.Error("Couldn't parse enum '"+i+"'"+this.location())}return this.semicolon(),t[i]}any(t){if(this.match("[")){this.read();const i=this._position,e=this._text.indexOf("]",i);if(-1===e||e>=this.next)throw new s.Error("End of Any type_url not found"+this.location());return t.type_url=this._text.substring(i,e),this._position=e+1,t.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(t,i,e){let s,r;for(this.start();!this.end();)switch(this.tag()){case"key":s=i();break;case"value":r=e()}t[s]=r}array(t,i){if(this.first())for(;!this.last();)t.push(i()),this.next();else t.push(i())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const t=this.peek();","!==t?"]"!==t&&this.handle(t):this.read()}skip(){let t=this.peek();if("{"===t){const i=this._position,e=this._depth;for(this.start();!this.end()||e=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let t=this._text[this._position];if("["===t&&this._position+2="a"&&i<="z"||i>="A"&&i<="Z")for(t++;t="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||"."===i||"/"===i)&&"]"===i)return this._token=this._text.substring(this._position,t),this._token}if("{"===t||"}"===t||":"===t||"["===t||","===t||"]"===t||";"===t)return this._token=t,this._token;let i=this._position+1;if(t>="a"&&t<="z"||t>="A"&&t<="Z"||"_"===t||"$"===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if(t>="0"&&t<="9"||"-"===t||"+"===t||"."===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t||"."===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if('"'===t||"'"===t){const e=t;for(;i>>0,this.hi=i>>>0}toLong(t){return s.Long?new s.Long(0|this.lo,0|this.hi,t):{low:0|this.lo,high:0|this.hi,unsigned:t}}toNumber(t){if(!t&&this.hi>>>31){const t=1+~this.lo>>>0;let i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}from(t){if("number"==typeof t)return s.LongBits.fromNumber(t);if("string"==typeof t||t instanceof String){if(!s.Long)return s.LongBits.fromNumber(parseInt(t,10));t=s.Long.fromString(t)}return t.low||t.high?new s.LongBits(t.low>>>0,t.high>>>0):s.LongBits.zero}hash(t){return t?s.LongBits.from(t).toHash():"\0\0\0\0\0\0\0\0"}},s.LongBits.zero=new s.LongBits(0,0),s.LongBits.zero.toNumber=function(){return 0},s.LongBits.zero.zzDecode=function(){return this},s.Error=class extends Error{constructor(t){super(t),this.name="Protocol Buffer Error",this.message=t}},"object"==typeof t.exports&&(t.exports.Reader=s.Reader,t.exports.TextReader=s.TextReader,t.exports.Error=s.Error,t.exports.Long=s.Long,t.exports.get=s.get)},71681:(t,i,e)=>{var s=e(32845),r=r||{};r.Archive=class{constructor(t){if(this._entries=[],t.length<4||80!=t[0]||75!=t[1])throw new r.Error("Invalid Zip archive.");let i=null;for(let e=t.length-4;e>=0;e--)if(80===t[e]&&75===t[e+1]&&5===t[e+2]&&6===t[e+3]){i=new r.Reader(t,e+4,t.length);break}if(!i)throw new r.Error("End of central directory not found.");for(i.skip(12),i.position=i.uint32();i.match([80,75,1,2]);)this._entries.push(new r.Entry(i))}get entries(){return this._entries}},r.Entry=class{constructor(t){if(t.uint16(),t.skip(2),this._flags=t.uint16(),1==(1&this._flags))throw new r.Error("Encrypted entries not supported.");this._compressionMethod=t.uint16(),t.uint32(),t.uint32(),this._compressedSize=t.uint32(),this._size=t.uint32();let i=t.uint16(),e=t.uint16();const s=t.uint16();t.uint16(),t.uint16(),t.uint32();const n=t.uint32();t.skip(i),t.skip(e),t.bytes(s);const o=t.position;if(t.position=n,!t.match([80,75,3,4]))throw new r.Error("Invalid local file header signature.");t.skip(22),i=t.uint16(),e=t.uint16();const h=t.bytes(i);this._name="";for(const t of h)this._name+=String.fromCharCode(t);t.skip(e),this._compressedData=t.bytes(this._compressedSize),t.position=o}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new r.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new r.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new r.Error("Invalid uncompressed size.");break;default:throw new r.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},r.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),r.HuffmanTree._offsets=r.HuffmanTree._offsets||new Uint16Array(16)}build(t,i,e){for(let t=0;t<16;++t)this.table[t]=0;for(let s=0;s>>1){case 0:this._inflateUncompressedBlock(i,n);break;case 1:this._inflateBlockData(i,n,r.HuffmanTree.staticLiteralLengthTree,r.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(i,o,h),this._inflateBlockData(i,n,o,h);break;default:throw new r.Error("Unknown block type.")}}while(0==(1&a));return n.merge()}_inflateUncompressedBlock(t,i){for(;t.data>8;)t.position--,t.data-=8;t.data=0;const e=t.uint16();if(e!==(65535&~t.uint16()))throw new r.Error("Invalid uncompressed block length.");const s=t.bytes(e);i.push(s),e>32768?(i.buffer.set(s.subarray(s.length-32768,s.length),0),i.position=32768):(i.reset(),i.buffer.set(s,i.position),i.position+=s.length)}_decodeTrees(t,i,e){const s=t.bits(5)+257,n=t.bits(5)+1,o=t.bits(4)+4;for(let t=0;t<19;t++)r.Inflater._lengths[t]=0;for(let i=0;i62464&&(i.position=o,i.push(new Uint8Array(n.subarray(h,o))),o=i.reset(),h=o);let a=t.symbol(e);if(256===a)return i.position=o,i.push(new Uint8Array(n.subarray(h,i.position))),void i.reset();if(a<256)n[o++]=a;else{a-=257;const i=t.bitsBase(r.Inflater._lengthBits[a],r.Inflater._lengthBase[a]),e=t.symbol(s);let h=o-t.bitsBase(r.Inflater._distanceBits[e],r.Inflater._distanceBase[e]);for(let t=0;t32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(t){this._blocks.push(t)}merge(){let t=0;for(const i of this._blocks)t+=i.length;const i=new Uint8Array(t);let e=0;for(const t of this._blocks)i.set(t,e),e+=t.length;return i}},r.BitReader=class{constructor(t){this.buffer=t,this.position=0,this.data=0,this.value=0}bits(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,i}bitsBase(t,i){if(0==t)return i;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,e+i}bytes(t){const i=this.buffer.subarray(this.position,this.position+t);return this.position+=t,i}uint16(){const t=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,t}symbol(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,s++,i+=n[s],e-=n[s]}while(e>=0);return this.value=r,this.data-=s,t.symbol[i+e]}},r.Reader=class{constructor(t,i,e){this._buffer=t,this._position=i,this._end=e}match(t){if(this._position+t.length<=this._end)for(let i=0;i=0?t:this._end+t}peek(){return this._positionthis._end)throw new r.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new r.Error("Data not available.");t=void 0===t?this._end:t;const i=this._buffer.subarray(this._position,this._position+t);return this._position+=t,i}uint16(){if(this._position+2>this._end)throw new r.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}},r.Error=class extends Error{constructor(t){super(t),this.name="Zip Error"}},"object"==typeof t.exports&&(t.exports.Archive=r.Archive,t.exports.Inflater=r.Inflater)},27918:(t,i,e)=>{window.base=e(87958),window.flatbuffers=e(45570),window.long={Long:e(27808)},window.protobuf=e(81600),window.zip=e(71681)},83260:()=>{}},e={};function s(t){var r=e[t];if(void 0!==r)return r.exports;var n=e[t]={id:t,loaded:!1,exports:{}};return i[t].call(n.exports,n,n.exports,s),n.loaded=!0,n.exports}s.m=i,t=[],s.O=(i,e,r,n)=>{if(!e){var o=1/0;for(l=0;l=n)&&Object.keys(s.O).every((t=>s.O[t](e[a])))?e.splice(a--,1):(h=!1,n0&&t[l-1][2]>n;l--)t[l]=t[l-1];t[l]=[e,r,n]},s.d=(t,i)=>{for(var e in i)s.o(i,e)&&!s.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:i[e]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),s.o=(t,i)=>Object.prototype.hasOwnProperty.call(t,i),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},s.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),s.j=307,(()=>{var t={307:0};s.O.j=i=>0===t[i];var i=(i,e)=>{var r,n,[o,h,a]=e,f=0;if(o.some((i=>0!==t[i]))){for(r in h)s.o(h,r)&&(s.m[r]=h[r]);if(a)var l=a(s)}for(i&&i(e);fs(27918)));r=s.O(r)})(); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..724c4c12977a5f819f1a30141d542df5033b3833 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn-metadata.json @@ -0,0 +1 @@ +[{"name":"sklearn.preprocessing.Binarizer","schema":{"attributes":[{"default":true,"description":"set to False to perform inplace binarization and avoid a copy (if\nthe input is already a numpy array or a scipy.sparse CSR matrix).\n","name":"copy","option":"optional","type":"boolean"},{"default":0,"description":"Feature values below or equal to this are replaced by 0, above it by 1.\nThreshold may not be less than 0 for operations on sparse matrices.\n","name":"threshold","option":"optional","type":"float32"}],"description":"Binarize data (set feature values to 0 or 1) according to a threshold\n\nValues greater than the threshold map to 1, while values less than\nor equal to the threshold map to 0. With the default threshold of 0,\nonly positive values map to 1.\n\nBinarization is a common operation on text count data where the\nanalyst can decide to only consider the presence or absence of a\nfeature rather than a quantified number of occurrences for instance.\n\nIt can also be used as a pre-processing step for estimators that\nconsider boolean random variables (e.g. modelled using the Bernoulli\ndistribution in a Bayesian setting).\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.preprocessing.MultiLabelBinarizer","schema":{"attributes":[{"description":"Indicates an ordering for the class labels.\nAll entries should be unique (cannot contain duplicate classes).\n","name":"classes","option":"optional"},{"description":"Set to true if output binary array is desired in CSR sparse format\n","name":"sparse_output"}],"description":"Transform between iterable of iterables and a multilabel format\n\nAlthough a list of sets or tuples is a very intuitive format for multilabel\ndata, it is unwieldy to process. This transformer converts between this\nintuitive format and the supported multilabel format: a (samples x classes)\nbinary matrix indicating the presence of a class label.\n"}},{"name":"sklearn.preprocessing.LabelEncoder","schema":{"description":"Encode target labels with value between 0 and n_classes-1.\n\nThis transformer should be used to encode target values, *i.e.* `y`, and\nnot the input `X`.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.12\n"}},{"name":"sklearn.svm.classes.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","type":"int32"},{"description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","type":"float32"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","type":"boolean"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","type":"boolean"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.svm.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","option":"optional","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel","option":"optional","type":"string"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","option":"optional","type":"int32"},{"default":"auto","description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma","option":"optional","type":"float32"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","option":"optional","type":"float32"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","option":"optional","type":"boolean"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","option":"optional","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","option":"optional","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","option":"optional","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight","option":"optional"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","option":"optional","type":"int32"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","option":"optional","type":"boolean"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.svm.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","option":"optional","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel","option":"optional","type":"string"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","option":"optional","type":"int32"},{"default":"auto","description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma","option":"optional","type":"float32"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","option":"optional","type":"float32"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","option":"optional","type":"boolean"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","option":"optional","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","option":"optional","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","option":"optional","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight","option":"optional"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","option":"optional"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","option":"optional","type":"boolean"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.linear_model._logistic.LogisticRegression","schema":{"attributes":[{"default":"l2","description":"Used to specify the norm used in the penalization. The 'newton-cg',\n'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\nonly supported by the 'saga' solver. If 'none' (not supported by the\nliblinear solver), no regularization is applied.\n\n.. versionadded:: 0.19\nl1 penalty with SAGA solver (allowing 'multinomial' + L1)\n","name":"penalty"},{"default":false,"description":"Dual or primal formulation. Dual formulation is only implemented for\nl2 penalty with liblinear solver. Prefer dual=False when\nn_samples > n_features.\n","name":"dual","type":"boolean"},{"default":0.0001,"description":"Tolerance for stopping criteria.\n","name":"tol","type":"float32"},{"default":1,"description":"Inverse of regularization strength; must be a positive float.\nLike in support vector machines, smaller values specify stronger\nregularization.\n","name":"C","type":"float32"},{"default":true,"description":"Specifies if a constant (a.k.a. bias or intercept) should be\nadded to the decision function.\n","name":"fit_intercept","type":"boolean"},{"default":1,"description":"Useful only when the solver 'liblinear' is used\nand self.fit_intercept is set to True. In this case, x becomes\n[x, self.intercept_scaling],\ni.e. a \"synthetic\" feature with constant value equal to\nintercept_scaling is appended to the instance vector.\nThe intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\nNote! the synthetic feature weight is subject to l1/l2 regularization\nas all other features.\nTo lessen the effect of regularization on synthetic feature weight\n(and therefore on the intercept) intercept_scaling has to be increased.\n","name":"intercept_scaling","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one.\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n\n.. versionadded:: 0.17\n*class_weight='balanced'*\n","name":"class_weight"},{"default":null,"description":"Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\ndata. See :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":"lbfgs","description":"\nAlgorithm to use in the optimization problem.\n\n- For small datasets, 'liblinear' is a good choice, whereas 'sag' and\n'saga' are faster for large ones.\n- For multiclass problems, only 'newton-cg', 'sag', 'saga' and 'lbfgs'\nhandle multinomial loss; 'liblinear' is limited to one-versus-rest\nschemes.\n- 'newton-cg', 'lbfgs', 'sag' and 'saga' handle L2 or no penalty\n- 'liblinear' and 'saga' also handle L1 penalty\n- 'saga' also supports 'elasticnet' penalty\n- 'liblinear' does not support setting ``penalty='none'``\n\nNote that 'sag' and 'saga' fast convergence is only guaranteed on\nfeatures with approximately the same scale. You can\npreprocess the data with a scaler from sklearn.preprocessing.\n\n.. versionadded:: 0.17\nStochastic Average Gradient descent solver.\n.. versionadded:: 0.19\nSAGA solver.\n.. versionchanged:: 0.22\nThe default solver changed from 'liblinear' to 'lbfgs' in 0.22.\n","name":"solver"},{"default":100,"description":"Maximum number of iterations taken for the solvers to converge.\n","name":"max_iter","type":"int32"},{"default":"auto","description":"If the option chosen is 'ovr', then a binary problem is fit for each\nlabel. For 'multinomial' the loss minimised is the multinomial loss fit\nacross the entire probability distribution, *even when the data is\nbinary*. 'multinomial' is unavailable when solver='liblinear'.\n'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\nand otherwise selects 'multinomial'.\n\n.. versionadded:: 0.18\nStochastic Average Gradient descent solver for 'multinomial' case.\n.. versionchanged:: 0.22\nDefault changed from 'ovr' to 'auto' in 0.22.\n","name":"multi_class"},{"default":0,"description":"For the liblinear and lbfgs solvers set verbose to any positive\nnumber for verbosity.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to True, reuse the solution of the previous call to fit as\ninitialization, otherwise, just erase the previous solution.\nUseless for liblinear solver. See :term:`the Glossary `.\n\n.. versionadded:: 0.17\n*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Number of CPU cores used when parallelizing over classes if\nmulti_class='ovr'\". This parameter is ignored when the ``solver`` is\nset to 'liblinear' regardless of whether 'multi_class' is specified or\nnot. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors.\nSee :term:`Glossary ` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\nused if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\nto using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\nto using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\ncombination of L1 and L2.\n","name":"l1_ratio","type":"float32"}],"description":"\nLogistic Regression (aka logit, MaxEnt) classifier.\n\nIn the multiclass case, the training algorithm uses the one-vs-rest (OvR)\nscheme if the 'multi_class' option is set to 'ovr', and uses the\ncross-entropy loss if the 'multi_class' option is set to 'multinomial'.\n(Currently the 'multinomial' option is supported only by the 'lbfgs',\n'sag', 'saga' and 'newton-cg' solvers.)\n\nThis class implements regularized logistic regression using the\n'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note\nthat regularization is applied by default**. It can handle both dense\nand sparse input. Use C-ordered arrays or CSR matrices containing 64-bit\nfloats for optimal performance; any other input format will be converted\n(and copied).\n\nThe 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization\nwith primal formulation, or no regularization. The 'liblinear' solver\nsupports both L1 and L2 regularization, with a dual formulation only for\nthe L2 penalty. The Elastic-Net regularization is only supported by the\n'saga' solver.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.linear_model.LogisticRegression","schema":{"attributes":[{"default":"l2","description":"Used to specify the norm used in the penalization. The 'newton-cg',\n'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\nonly supported by the 'saga' solver. If 'none' (not supported by the\nliblinear solver), no regularization is applied.\n\n.. versionadded:: 0.19\nl1 penalty with SAGA solver (allowing 'multinomial' + L1)\n","name":"penalty","option":"optional"},{"default":false,"description":"Dual or primal formulation. Dual formulation is only implemented for\nl2 penalty with liblinear solver. Prefer dual=False when\nn_samples > n_features.\n","name":"dual","option":"optional","type":"boolean"},{"default":0.0001,"description":"Tolerance for stopping criteria.\n","name":"tol","option":"optional","type":"float32"},{"default":1,"description":"Inverse of regularization strength; must be a positive float.\nLike in support vector machines, smaller values specify stronger\nregularization.\n","name":"C","option":"optional","type":"float32"},{"default":true,"description":"Specifies if a constant (a.k.a. bias or intercept) should be\nadded to the decision function.\n","name":"fit_intercept","option":"optional","type":"boolean"},{"default":1,"description":"Useful only when the solver 'liblinear' is used\nand self.fit_intercept is set to True. In this case, x becomes\n[x, self.intercept_scaling],\ni.e. a \"synthetic\" feature with constant value equal to\nintercept_scaling is appended to the instance vector.\nThe intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\nNote! the synthetic feature weight is subject to l1/l2 regularization\nas all other features.\nTo lessen the effect of regularization on synthetic feature weight\n(and therefore on the intercept) intercept_scaling has to be increased.\n","name":"intercept_scaling","option":"optional","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one.\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n\n.. versionadded:: 0.17\n*class_weight='balanced'*\n","name":"class_weight","option":"optional"},{"default":null,"description":"Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\ndata. See :term:`Glossary ` for details.\n","name":"random_state","option":"optional","type":"int32"},{"default":"lbfgs","description":"\nAlgorithm to use in the optimization problem.\n\n- For small datasets, 'liblinear' is a good choice, whereas 'sag' and\n'saga' are faster for large ones.\n- For multiclass problems, only 'newton-cg', 'sag', 'saga' and 'lbfgs'\nhandle multinomial loss; 'liblinear' is limited to one-versus-rest\nschemes.\n- 'newton-cg', 'lbfgs', 'sag' and 'saga' handle L2 or no penalty\n- 'liblinear' and 'saga' also handle L1 penalty\n- 'saga' also supports 'elasticnet' penalty\n- 'liblinear' does not support setting ``penalty='none'``\n\nNote that 'sag' and 'saga' fast convergence is only guaranteed on\nfeatures with approximately the same scale. You can\npreprocess the data with a scaler from sklearn.preprocessing.\n\n.. versionadded:: 0.17\nStochastic Average Gradient descent solver.\n.. versionadded:: 0.19\nSAGA solver.\n.. versionchanged:: 0.22\nThe default solver changed from 'liblinear' to 'lbfgs' in 0.22.\n","name":"solver","option":"optional"},{"default":100,"description":"Maximum number of iterations taken for the solvers to converge.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"auto","description":"If the option chosen is 'ovr', then a binary problem is fit for each\nlabel. For 'multinomial' the loss minimised is the multinomial loss fit\nacross the entire probability distribution, *even when the data is\nbinary*. 'multinomial' is unavailable when solver='liblinear'.\n'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\nand otherwise selects 'multinomial'.\n\n.. versionadded:: 0.18\nStochastic Average Gradient descent solver for 'multinomial' case.\n.. versionchanged:: 0.22\nDefault changed from 'ovr' to 'auto' in 0.22.\n","name":"multi_class","option":"optional"},{"default":0,"description":"For the liblinear and lbfgs solvers set verbose to any positive\nnumber for verbosity.\n","name":"verbose","option":"optional","type":"int32"},{"default":false,"description":"When set to True, reuse the solution of the previous call to fit as\ninitialization, otherwise, just erase the previous solution.\nUseless for liblinear solver. See :term:`the Glossary `.\n\n.. versionadded:: 0.17\n*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.\n","name":"warm_start","option":"optional","type":"boolean"},{"default":null,"description":"Number of CPU cores used when parallelizing over classes if\nmulti_class='ovr'\". This parameter is ignored when the ``solver`` is\nset to 'liblinear' regardless of whether 'multi_class' is specified or\nnot. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors.\nSee :term:`Glossary ` for more details.\n","name":"n_jobs","option":"optional","type":"int32"},{"default":null,"description":"The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\nused if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\nto using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\nto using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\ncombination of L1 and L2.\n","name":"l1_ratio","option":"optional","type":"float32"}],"description":"\nLogistic Regression (aka logit, MaxEnt) classifier.\n\nIn the multiclass case, the training algorithm uses the one-vs-rest (OvR)\nscheme if the 'multi_class' option is set to 'ovr', and uses the\ncross-entropy loss if the 'multi_class' option is set to 'multinomial'.\n(Currently the 'multinomial' option is supported only by the 'lbfgs',\n'sag', 'saga' and 'newton-cg' solvers.)\n\nThis class implements regularized logistic regression using the\n'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note\nthat regularization is applied by default**. It can handle both dense\nand sparse input. Use C-ordered arrays or CSR matrices containing 64-bit\nfloats for optimal performance; any other input format will be converted\n(and copied).\n\nThe 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization\nwith primal formulation, or no regularization. The 'liblinear' solver\nsupports both L1 and L2 regularization, with a dual formulation only for\nthe L2 penalty. The Elastic-Net regularization is only supported by the\n'saga' solver.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.naive_bayes.BernoulliNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter\n(0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":"0.0","description":"Threshold for binarizing (mapping to booleans) of sample features.\nIf None, input is presumed to already consist of binary vectors.\n","name":"binarize","option":"optional"},{"default":true,"description":"Whether to learn class prior probabilities or not.\nIf false, a uniform prior will be used.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. If specified the priors are not\nadjusted according to the data.\n","name":"class_prior","option":"optional"}],"description":"Naive Bayes classifier for multivariate Bernoulli models.\n\nLike MultinomialNB, this classifier is suitable for discrete data. The\ndifference is that while MultinomialNB works with occurrence counts,\nBernoulliNB is designed for binary/boolean features.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.naive_bayes.ComplementNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":true,"description":"Only used in edge case with a single class in the training set.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. Not used.\n","name":"class_prior","option":"optional"},{"default":false,"description":"Whether or not a second normalization of the weights is performed. The\ndefault behavior mirrors the implementations found in Mahout and Weka,\nwhich do not follow the full algorithm described in Table 9 of the\npaper.\n","name":"norm","option":"optional","type":"boolean"}],"description":"The Complement Naive Bayes classifier described in Rennie et al. (2003).\n\nThe Complement Naive Bayes classifier was designed to correct the \"severe\nassumptions\" made by the standard Multinomial Naive Bayes classifier. It is\nparticularly suited for imbalanced data sets.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n"}},{"name":"sklearn.naive_bayes.MultinomialNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter\n(0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":true,"description":"Whether to learn class prior probabilities or not.\nIf false, a uniform prior will be used.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. If specified the priors are not\nadjusted according to the data.\n","name":"class_prior","option":"optional"}],"description":"\nNaive Bayes classifier for multinomial models\n\nThe multinomial Naive Bayes classifier is suitable for classification with\ndiscrete features (e.g., word counts for text classification). The\nmultinomial distribution normally requires integer feature counts. However,\nin practice, fractional counts such as tf-idf may also work.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neighbors.KNeighborsClassifier","schema":{"attributes":[{"default":5,"description":"Number of neighbors to use by default for :meth:`kneighbors` queries.\n","name":"n_neighbors","option":"optional","type":"int32"},{"default":"uniform","description":"weight function used in prediction. Possible values:\n\n- 'uniform' : uniform weights. All points in each neighborhood\nare weighted equally.\n- 'distance' : weight points by the inverse of their distance.\nin this case, closer neighbors of a query point will have a\ngreater influence than neighbors which are further away.\n- [callable] : a user-defined function which accepts an\narray of distances, and returns an array of the same shape\ncontaining the weights.\n","name":"weights","option":"optional"},{"default":"auto","description":"Algorithm used to compute the nearest neighbors:\n\n- 'ball_tree' will use :class:`BallTree`\n- 'kd_tree' will use :class:`KDTree`\n- 'brute' will use a brute-force search.\n- 'auto' will attempt to decide the most appropriate algorithm\nbased on the values passed to :meth:`fit` method.\n\nNote: fitting on sparse input will override the setting of\nthis parameter, using brute force.\n","name":"algorithm","option":"optional"},{"default":30,"description":"Leaf size passed to BallTree or KDTree. This can affect the\nspeed of the construction and query, as well as the memory\nrequired to store the tree. The optimal value depends on the\nnature of the problem.\n","name":"leaf_size","option":"optional","type":"int32"},{"default":2,"description":"Power parameter for the Minkowski metric. When p = 1, this is\nequivalent to using manhattan_distance (l1), and euclidean_distance\n(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.\n","name":"p","option":"optional","type":"int32"},{"default":"minkowski","description":"the distance metric to use for the tree. The default metric is\nminkowski, and with p=2 is equivalent to the standard Euclidean\nmetric. See the documentation of :class:`DistanceMetric` for a\nlist of available metrics.\nIf metric is \"precomputed\", X is assumed to be a distance matrix and\nmust be square during fit. X may be a :term:`sparse graph`,\nin which case only \"nonzero\" elements may be considered neighbors.\n","name":"metric"},{"default":null,"description":"Additional keyword arguments for the metric function.\n","name":"metric_params","option":"optional"},{"default":null,"description":"The number of parallel jobs to run for neighbors search.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\nDoesn't affect :meth:`fit` method.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"Classifier implementing the k-nearest neighbors vote.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neighbors.KNeighborsRegressor","schema":{"attributes":[{"default":5,"description":"Number of neighbors to use by default for :meth:`kneighbors` queries.\n","name":"n_neighbors","option":"optional","type":"int32"},{"description":"weight function used in prediction. Possible values:\n\n- 'uniform' : uniform weights. All points in each neighborhood\nare weighted equally.\n- 'distance' : weight points by the inverse of their distance.\nin this case, closer neighbors of a query point will have a\ngreater influence than neighbors which are further away.\n- [callable] : a user-defined function which accepts an\narray of distances, and returns an array of the same shape\ncontaining the weights.\n\nUniform weights are used by default.\n","name":"weights"},{"default":"auto","description":"Algorithm used to compute the nearest neighbors:\n\n- 'ball_tree' will use :class:`BallTree`\n- 'kd_tree' will use :class:`KDTree`\n- 'brute' will use a brute-force search.\n- 'auto' will attempt to decide the most appropriate algorithm\nbased on the values passed to :meth:`fit` method.\n\nNote: fitting on sparse input will override the setting of\nthis parameter, using brute force.\n","name":"algorithm","option":"optional"},{"default":30,"description":"Leaf size passed to BallTree or KDTree. This can affect the\nspeed of the construction and query, as well as the memory\nrequired to store the tree. The optimal value depends on the\nnature of the problem.\n","name":"leaf_size","option":"optional","type":"int32"},{"default":2,"description":"Power parameter for the Minkowski metric. When p = 1, this is\nequivalent to using manhattan_distance (l1), and euclidean_distance\n(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.\n","name":"p","option":"optional","type":"int32"},{"default":"minkowski","description":"the distance metric to use for the tree. The default metric is\nminkowski, and with p=2 is equivalent to the standard Euclidean\nmetric. See the documentation of :class:`DistanceMetric` for a\nlist of available metrics.\nIf metric is \"precomputed\", X is assumed to be a distance matrix and\nmust be square during fit. X may be a :term:`sparse graph`,\nin which case only \"nonzero\" elements may be considered neighbors.\n","name":"metric"},{"default":null,"description":"Additional keyword arguments for the metric function.\n","name":"metric_params","option":"optional"},{"default":null,"description":"The number of parallel jobs to run for neighbors search.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\nDoesn't affect :meth:`fit` method.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"Regression based on k-nearest neighbors.\n\nThe target is predicted by local interpolation of the targets\nassociated of the nearest neighbors in the training set.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.9\n"}},{"name":"sklearn.linear_model.LassoLars","schema":{"attributes":[{"default":1,"description":"Constant that multiplies the penalty term. Defaults to 1.0.\n``alpha = 0`` is equivalent to an ordinary least square, solved\nby :class:`LinearRegression`. For numerical reasons, using\n``alpha = 0`` with the LassoLars object is not advised and you\nshould prefer the LinearRegression object.\n","name":"alpha","type":"float32"},{"default":true,"description":"whether to calculate the intercept for this model. If set\nto false, no intercept will be used in calculations\n(i.e. data is expected to be centered).\n","name":"fit_intercept","type":"boolean"},{"default":"False","description":"Sets the verbosity amount\n","name":"verbose","option":"optional"},{"default":true,"description":"This parameter is ignored when ``fit_intercept`` is set to False.\nIf True, the regressors X will be normalized before regression by\nsubtracting the mean and dividing by the l2-norm.\nIf you wish to standardize, please use\n:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``\non an estimator with ``normalize=False``.\n","name":"normalize","option":"optional","type":"boolean"},{"default":"auto","description":"Whether to use a precomputed Gram matrix to speed up\ncalculations. If set to ``'auto'`` let us decide. The Gram\nmatrix can also be passed as argument.\n","name":"precompute","type":"boolean"},{"default":500,"description":"Maximum number of iterations to perform.\n","name":"max_iter","option":"optional","type":"int32"},{"description":"The machine-precision regularization in the computation of the\nCholesky diagonal factors. Increase this for very ill-conditioned\nsystems. Unlike the ``tol`` parameter in some iterative\noptimization-based algorithms, this parameter does not control\nthe tolerance of the optimization.\nBy default, ``np.finfo(np.float).eps`` is used.\n","name":"eps","option":"optional","type":"float32"},{"default":true,"description":"If True, X will be copied; else, it may be overwritten.\n","name":"copy_X","option":"optional","type":"boolean"},{"default":true,"description":"If ``True`` the full path is stored in the ``coef_path_`` attribute.\nIf you compute the solution for a large problem or many targets,\nsetting ``fit_path`` to ``False`` will lead to a speedup, especially\nwith a small alpha.\n","name":"fit_path","type":"boolean"},{"default":false,"description":"Restrict coefficients to be >= 0. Be aware that you might want to\nremove fit_intercept which is set True by default.\nUnder the positive restriction the model coefficients will not converge\nto the ordinary-least-squares solution for small values of alpha.\nOnly coefficients up to the smallest alpha value (``alphas_[alphas_ >\n0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso\nalgorithm are typically in congruence with the solution of the\ncoordinate descent Lasso estimator.\n","name":"positive","type":"boolean"},{"default":null,"description":"Upper bound on a uniform noise parameter to be added to the\n`y` values, to satisfy the model's assumption of\none-at-a-time computations. Might help with stability.\n","name":"jitter","type":"float32"},{"description":"Determines random number generation for jittering. Pass an int\nfor reproducible output across multiple function calls.\nSee :term:`Glossary `. Ignored if `jitter` is None.\n","name":"random_state"}],"description":"Lasso model fit with Least Angle Regression a.k.a. Lars\n\nIt is a Linear Model trained with an L1 prior as regularizer.\n\nThe optimization objective for Lasso is::\n\n(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition._pca.PCA","schema":{"attributes":[{"description":"Number of components to keep.\nif n_components is not set all components are kept::\n\nn_components == min(n_samples, n_features)\n\nIf ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's\nMLE is used to guess the dimension. Use of ``n_components == 'mle'``\nwill interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.\n\nIf ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the\nnumber of components such that the amount of variance that needs to be\nexplained is greater than the percentage specified by n_components.\n\nIf ``svd_solver == 'arpack'``, the number of components must be\nstrictly less than the minimum of n_features and n_samples.\n\nHence, the None case results in::\n\nn_components == min(n_samples, n_features) - 1\n","name":"n_components"},{"default":true,"description":"If False, data passed to fit are overwritten and running\nfit(X).transform(X) will not yield the expected results,\nuse fit_transform(X) instead.\n","name":"copy","type":"boolean"},{"default":false,"description":"When True (False by default) the `components_` vectors are multiplied\nby the square root of n_samples and then divided by the singular values\nto ensure uncorrelated outputs with unit component-wise variances.\n\nWhitening will remove some information from the transformed signal\n(the relative variance scales of the components) but can sometime\nimprove the predictive accuracy of the downstream estimators by\nmaking their data respect some hard-wired assumptions.\n","name":"whiten","option":"optional","type":"boolean"},{"description":"If auto :\nThe solver is selected by a default policy based on `X.shape` and\n`n_components`: if the input data is larger than 500x500 and the\nnumber of components to extract is lower than 80% of the smallest\ndimension of the data, then the more efficient 'randomized'\nmethod is enabled. Otherwise the exact full SVD is computed and\noptionally truncated afterwards.\nIf full :\nrun exact full SVD calling the standard LAPACK solver via\n`scipy.linalg.svd` and select the components by postprocessing\nIf arpack :\nrun SVD truncated to n_components calling ARPACK solver via\n`scipy.sparse.linalg.svds`. It requires strictly\n0 < n_components < min(X.shape)\nIf randomized :\nrun randomized SVD by the method of Halko et al.\n\n.. versionadded:: 0.18.0\n","name":"svd_solver"},{"default":".0","description":"Tolerance for singular values computed by svd_solver == 'arpack'.\n\n.. versionadded:: 0.18.0\n","name":"tol","option":"optional"},{"default":"auto","description":"Number of iterations for the power method computed by\nsvd_solver == 'randomized'.\n\n.. versionadded:: 0.18.0\n","name":"iterated_power"},{"default":null,"description":"Used when ``svd_solver`` == 'arpack' or 'randomized'. Pass an int\nfor reproducible results across multiple function calls.\nSee :term:`Glossary `.\n\n.. versionadded:: 0.18.0\n","name":"random_state","type":"int32"}],"description":"Principal component analysis (PCA).\n\nLinear dimensionality reduction using Singular Value Decomposition of the\ndata to project it to a lower dimensional space. The input data is centered\nbut not scaled for each feature before applying the SVD.\n\nIt uses the LAPACK implementation of the full SVD or a randomized truncated\nSVD by the method of Halko et al. 2009, depending on the shape of the input\ndata and the number of components to extract.\n\nIt can also use the scipy.sparse.linalg ARPACK implementation of the\ntruncated SVD.\n\nNotice that this class does not support sparse input. See\n:class:`TruncatedSVD` for an alternative with sparse data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition.PCA","schema":{"attributes":[{"description":"Number of components to keep.\nif n_components is not set all components are kept::\n\nn_components == min(n_samples, n_features)\n\nIf ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's\nMLE is used to guess the dimension. Use of ``n_components == 'mle'``\nwill interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.\n\nIf ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the\nnumber of components such that the amount of variance that needs to be\nexplained is greater than the percentage specified by n_components.\n\nIf ``svd_solver == 'arpack'``, the number of components must be\nstrictly less than the minimum of n_features and n_samples.\n\nHence, the None case results in::\n\nn_components == min(n_samples, n_features) - 1\n","name":"n_components"},{"default":true,"description":"If False, data passed to fit are overwritten and running\nfit(X).transform(X) will not yield the expected results,\nuse fit_transform(X) instead.\n","name":"copy","type":"boolean"},{"default":false,"description":"When True (False by default) the `components_` vectors are multiplied\nby the square root of n_samples and then divided by the singular values\nto ensure uncorrelated outputs with unit component-wise variances.\n\nWhitening will remove some information from the transformed signal\n(the relative variance scales of the components) but can sometime\nimprove the predictive accuracy of the downstream estimators by\nmaking their data respect some hard-wired assumptions.\n","name":"whiten","option":"optional","type":"boolean"},{"description":"If auto :\nThe solver is selected by a default policy based on `X.shape` and\n`n_components`: if the input data is larger than 500x500 and the\nnumber of components to extract is lower than 80% of the smallest\ndimension of the data, then the more efficient 'randomized'\nmethod is enabled. Otherwise the exact full SVD is computed and\noptionally truncated afterwards.\nIf full :\nrun exact full SVD calling the standard LAPACK solver via\n`scipy.linalg.svd` and select the components by postprocessing\nIf arpack :\nrun SVD truncated to n_components calling ARPACK solver via\n`scipy.sparse.linalg.svds`. It requires strictly\n0 < n_components < min(X.shape)\nIf randomized :\nrun randomized SVD by the method of Halko et al.\n\n.. versionadded:: 0.18.0\n","name":"svd_solver","type":"string"},{"default":".0","description":"Tolerance for singular values computed by svd_solver == 'arpack'.\n\n.. versionadded:: 0.18.0\n","name":"tol","option":"optional"},{"default":"auto","description":"Number of iterations for the power method computed by\nsvd_solver == 'randomized'.\n\n.. versionadded:: 0.18.0\n","name":"iterated_power"},{"default":null,"description":"Used when ``svd_solver`` == 'arpack' or 'randomized'. Pass an int\nfor reproducible results across multiple function calls.\nSee :term:`Glossary `.\n\n.. versionadded:: 0.18.0\n","name":"random_state","option":"optional","type":"int32"}],"description":"Principal component analysis (PCA).\n\nLinear dimensionality reduction using Singular Value Decomposition of the\ndata to project it to a lower dimensional space. The input data is centered\nbut not scaled for each feature before applying the SVD.\n\nIt uses the LAPACK implementation of the full SVD or a randomized truncated\nSVD by the method of Halko et al. 2009, depending on the shape of the input\ndata and the number of components to extract.\n\nIt can also use the scipy.sparse.linalg ARPACK implementation of the\ntruncated SVD.\n\nNotice that this class does not support sparse input. See\n:class:`TruncatedSVD` for an alternative with sparse data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.calibration.CalibratedClassifierCV","schema":{"attributes":[{"description":"The classifier whose output need to be calibrated to provide more\naccurate `predict_proba` outputs.\n","name":"base_estimator"},{"description":"The method to use for calibration. Can be 'sigmoid' which\ncorresponds to Platt's method (i.e. a logistic regression model) or\n'isotonic' which is a non-parametric approach. It is not advised to\nuse isotonic calibration with too few calibration samples\n``(<<1000)`` since it tends to overfit.\n","name":"method"},{"description":"Determines the cross-validation splitting strategy.\nPossible inputs for cv are:\n\n- None, to use the default 5-fold cross-validation,\n- integer, to specify the number of folds.\n- :term:`CV splitter`,\n- An iterable yielding (train, test) splits as arrays of indices.\n\nFor integer/None inputs, if ``y`` is binary or multiclass,\n:class:`sklearn.model_selection.StratifiedKFold` is used. If ``y`` is\nneither binary nor multiclass, :class:`sklearn.model_selection.KFold`\nis used.\n\nRefer :ref:`User Guide ` for the various\ncross-validation strategies that can be used here.\n\nIf \"prefit\" is passed, it is assumed that `base_estimator` has been\nfitted already and all data is used for calibration.\n\n.. versionchanged:: 0.22\n``cv`` default value if None changed from 3-fold to 5-fold.\n","name":"cv","option":"optional","type":"int32"}],"description":"Probability calibration with isotonic regression or logistic regression.\n\nThe calibration is based on the :term:`decision_function` method of the\n`base_estimator` if it exists, else on :term:`predict_proba`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.feature_extraction.text.CountVectorizer","schema":{"attributes":[{"default":"content","description":"If 'filename', the sequence passed as an argument to fit is\nexpected to be a list of filenames that need reading to fetch\nthe raw content to analyze.\n\nIf 'file', the sequence items must have a 'read' method (file-like\nobject) that is called to fetch the bytes in memory.\n\nOtherwise the input is expected to be a sequence of items that\ncan be of type string or byte.\n","name":"input","type":"string"},{"default":"utf-8","description":"If bytes or files are given to analyze, this encoding is used to\ndecode.\n","name":"encoding","type":"string"},{"default":"strict","description":"Instruction on what to do if a byte sequence is given to analyze that\ncontains characters not of the given `encoding`. By default, it is\n'strict', meaning that a UnicodeDecodeError will be raised. Other\nvalues are 'ignore' and 'replace'.\n","name":"decode_error"},{"default":null,"description":"Remove accents and perform other character normalization\nduring the preprocessing step.\n'ascii' is a fast method that only works on characters that have\nan direct ASCII mapping.\n'unicode' is a slightly slower method that works on any characters.\nNone (default) does nothing.\n\nBoth 'ascii' and 'unicode' use NFKD normalization from\n:func:`unicodedata.normalize`.\n","name":"strip_accents"},{"default":true,"description":"Convert all characters to lowercase before tokenizing.\n","name":"lowercase","type":"boolean"},{"default":null,"description":"Override the preprocessing (string transformation) stage while\npreserving the tokenizing and n-grams generation steps.\nOnly applies if ``analyzer is not callable``.\n","name":"preprocessor"},{"default":null,"description":"Override the string tokenization step while preserving the\npreprocessing and n-grams generation steps.\nOnly applies if ``analyzer == 'word'``.\n","name":"tokenizer"},{"default":"None","description":"If 'english', a built-in stop word list for English is used.\nThere are several known issues with 'english' and you should\nconsider an alternative (see :ref:`stop_words`).\n\nIf a list, that list is assumed to contain stop words, all of which\nwill be removed from the resulting tokens.\nOnly applies if ``analyzer == 'word'``.\n\nIf None, no stop words will be used. max_df can be set to a value\nin the range [0.7, 1.0) to automatically detect and filter stop\nwords based on intra corpus document frequency of terms.\n","name":"stop_words","type":"string"},{"description":"Regular expression denoting what constitutes a \"token\", only used\nif ``analyzer == 'word'``. The default regexp select tokens of 2\nor more alphanumeric characters (punctuation is completely ignored\nand always treated as a token separator).\n","name":"token_pattern","type":"string"},{"default":"(1, 1)","description":"The lower and upper boundary of the range of n-values for different\nword n-grams or char n-grams to be extracted. All values of n such\nsuch that min_n <= n <= max_n will be used. For example an\n``ngram_range`` of ``(1, 1)`` means only unigrams, ``(1, 2)`` means\nunigrams and bigrams, and ``(2, 2)`` means only bigrams.\nOnly applies if ``analyzer is not callable``.\n","name":"ngram_range"},{"default":"word","description":"Whether the feature should be made of word n-gram or character\nn-grams.\nOption 'char_wb' creates character n-grams only from text inside\nword boundaries; n-grams at the edges of words are padded with space.\n\nIf a callable is passed it is used to extract the sequence of features\nout of the raw, unprocessed input.\n\n.. versionchanged:: 0.21\n\nSince v0.21, if ``input`` is ``filename`` or ``file``, the data is\nfirst read from the file and then passed to the given callable\nanalyzer.\n","name":"analyzer","type":"string"},{"default":"1.0","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly higher than the given threshold (corpus-specific\nstop words).\nIf float, the parameter represents a proportion of documents, integer\nabsolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"max_df"},{"default":"1","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly lower than the given threshold. This value is also\ncalled cut-off in the literature.\nIf float, the parameter represents a proportion of documents, integer\nabsolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"min_df"},{"default":null,"description":"If not None, build a vocabulary that only consider the top\nmax_features ordered by term frequency across the corpus.\n\nThis parameter is ignored if vocabulary is not None.\n","name":"max_features","type":"int32"},{"default":null,"description":"Either a Mapping (e.g., a dict) where keys are terms and values are\nindices in the feature matrix, or an iterable over terms. If not\ngiven, a vocabulary is determined from the input documents. Indices\nin the mapping should not be repeated and should not have any gap\nbetween 0 and the largest index.\n","name":"vocabulary","option":"optional"},{"default":false,"description":"If True, all non zero counts are set to 1. This is useful for discrete\nprobabilistic models that model binary events rather than integer\ncounts.\n","name":"binary","type":"boolean"},{"default":"np.int64","description":"Type of the matrix returned by fit_transform() or transform().\n","name":"dtype","option":"optional"}],"description":"Convert a collection of text documents to a matrix of token counts\n\nThis implementation produces a sparse representation of the counts using\nscipy.sparse.csr_matrix.\n\nIf you do not provide an a-priori dictionary and you do not use an analyzer\nthat does some kind of feature selection then the number of features will\nbe equal to the vocabulary size found by analyzing the data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.feature_extraction.text.TfidfVectorizer","schema":{"attributes":[{"default":"content","description":"If 'filename', the sequence passed as an argument to fit is\nexpected to be a list of filenames that need reading to fetch\nthe raw content to analyze.\n\nIf 'file', the sequence items must have a 'read' method (file-like\nobject) that is called to fetch the bytes in memory.\n\nOtherwise the input is expected to be a sequence of items that\ncan be of type string or byte.\n","name":"input","type":"string"},{"default":"utf-8","description":"If bytes or files are given to analyze, this encoding is used to\ndecode.\n","name":"encoding","type":"string"},{"default":"strict","description":"Instruction on what to do if a byte sequence is given to analyze that\ncontains characters not of the given `encoding`. By default, it is\n'strict', meaning that a UnicodeDecodeError will be raised. Other\nvalues are 'ignore' and 'replace'.\n","name":"decode_error"},{"default":null,"description":"Remove accents and perform other character normalization\nduring the preprocessing step.\n'ascii' is a fast method that only works on characters that have\nan direct ASCII mapping.\n'unicode' is a slightly slower method that works on any characters.\nNone (default) does nothing.\n\nBoth 'ascii' and 'unicode' use NFKD normalization from\n:func:`unicodedata.normalize`.\n","name":"strip_accents"},{"default":true,"description":"Convert all characters to lowercase before tokenizing.\n","name":"lowercase","type":"boolean"},{"default":null,"description":"Override the preprocessing (string transformation) stage while\npreserving the tokenizing and n-grams generation steps.\nOnly applies if ``analyzer is not callable``.\n","name":"preprocessor"},{"default":null,"description":"Override the string tokenization step while preserving the\npreprocessing and n-grams generation steps.\nOnly applies if ``analyzer == 'word'``.\n","name":"tokenizer"},{"description":"Whether the feature should be made of word or character n-grams.\nOption 'char_wb' creates character n-grams only from text inside\nword boundaries; n-grams at the edges of words are padded with space.\n\nIf a callable is passed it is used to extract the sequence of features\nout of the raw, unprocessed input.\n\n.. versionchanged:: 0.21\n\nSince v0.21, if ``input`` is ``filename`` or ``file``, the data is\nfirst read from the file and then passed to the given callable\nanalyzer.\n","name":"analyzer"},{"default":null,"description":"If a string, it is passed to _check_stop_list and the appropriate stop\nlist is returned. 'english' is currently the only supported string\nvalue.\nThere are several known issues with 'english' and you should\nconsider an alternative (see :ref:`stop_words`).\n\nIf a list, that list is assumed to contain stop words, all of which\nwill be removed from the resulting tokens.\nOnly applies if ``analyzer == 'word'``.\n\nIf None, no stop words will be used. max_df can be set to a value\nin the range [0.7, 1.0) to automatically detect and filter stop\nwords based on intra corpus document frequency of terms.\n","name":"stop_words"},{"description":"Regular expression denoting what constitutes a \"token\", only used\nif ``analyzer == 'word'``. The default regexp selects tokens of 2\nor more alphanumeric characters (punctuation is completely ignored\nand always treated as a token separator).\n","name":"token_pattern","type":"string"},{"default":"(1, 1)","description":"The lower and upper boundary of the range of n-values for different\nn-grams to be extracted. All values of n such that min_n <= n <= max_n\nwill be used. For example an ``ngram_range`` of ``(1, 1)`` means only\nunigrams, ``(1, 2)`` means unigrams and bigrams, and ``(2, 2)`` means\nonly bigrams.\nOnly applies if ``analyzer is not callable``.\n","name":"ngram_range"},{"default":"1.0","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly higher than the given threshold (corpus-specific\nstop words).\nIf float in range [0.0, 1.0], the parameter represents a proportion of\ndocuments, integer absolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"max_df"},{"default":"1","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly lower than the given threshold. This value is also\ncalled cut-off in the literature.\nIf float in range of [0.0, 1.0], the parameter represents a proportion\nof documents, integer absolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"min_df"},{"default":null,"description":"If not None, build a vocabulary that only consider the top\nmax_features ordered by term frequency across the corpus.\n\nThis parameter is ignored if vocabulary is not None.\n","name":"max_features","type":"int32"},{"default":null,"description":"Either a Mapping (e.g., a dict) where keys are terms and values are\nindices in the feature matrix, or an iterable over terms. If not\ngiven, a vocabulary is determined from the input documents.\n","name":"vocabulary","option":"optional"},{"default":false,"description":"If True, all non-zero term counts are set to 1. This does not mean\noutputs will have only 0/1 values, only that the tf term in tf-idf\nis binary. (Set idf and normalization to False to get 0/1 outputs).\n","name":"binary","type":"boolean"},{"default":"float64","description":"Type of the matrix returned by fit_transform() or transform().\n","name":"dtype","option":"optional"},{"default":"l2","description":"Each output row will have unit norm, either:\n* 'l2': Sum of squares of vector elements is 1. The cosine\nsimilarity between two vectors is their dot product when l2 norm has\nbeen applied.\n* 'l1': Sum of absolute values of vector elements is 1.\nSee :func:`preprocessing.normalize`.\n","name":"norm"},{"default":true,"description":"Enable inverse-document-frequency reweighting.\n","name":"use_idf","type":"boolean"},{"default":true,"description":"Smooth idf weights by adding one to document frequencies, as if an\nextra document was seen containing every term in the collection\nexactly once. Prevents zero divisions.\n","name":"smooth_idf","type":"boolean"},{"default":false,"description":"Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).\n","name":"sublinear_tf","type":"boolean"}],"description":"Convert a collection of raw documents to a matrix of TF-IDF features.\n\nEquivalent to :class:`CountVectorizer` followed by\n:class:`TfidfTransformer`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"lightgbm.sklearn.LGBMRegressor","schema":{"attributes":[{"default":"gbdt","name":"boosting_type","type":"string"},{"default":null,"name":"class_weight"},{"default":1,"name":"colsample_bytree"},{"default":0.05,"name":"learning_rate"},{"default":-1,"name":"max_depth"},{"default":20,"name":"min_child_samples"},{"default":0.001,"name":"min_child_weight"},{"default":0,"name":"min_split_gain"},{"default":100,"name":"n_estimators"},{"default":-1,"name":"n_jobs"},{"default":31,"name":"num_leaves"},{"default":null,"name":"random_state"},{"default":0,"name":"reg_alpha"},{"default":0,"name":"reg_lambda"},{"default":true,"name":"silent","type":"boolean"},{"default":200000,"name":"subsample_for_bin"},{"default":0,"name":"subsample_freq"},{"default":1,"name":"subsample"}]}},{"name":"lightgbm.sklearn.LGBMClassifier","schema":{"attributes":[{"default":"gbdt","name":"boosting_type","type":"string"},{"default":null,"name":"class_weight"},{"default":1,"name":"colsample_bytree"},{"default":0.05,"name":"learning_rate"},{"default":-1,"name":"max_depth"},{"default":20,"name":"min_child_samples"},{"default":0.001,"name":"min_child_weight"},{"default":0,"name":"min_split_gain"},{"default":100,"name":"n_estimators"},{"default":-1,"name":"n_jobs"},{"default":31,"name":"num_leaves"},{"default":null,"name":"random_state"},{"default":0,"name":"reg_alpha"},{"default":0,"name":"reg_lambda"},{"default":true,"name":"silent","type":"boolean"},{"default":200000,"name":"subsample_for_bin"},{"default":0,"name":"subsample_freq"},{"default":1,"name":"subsample"}]}},{"name":"lightgbm.basic.Booster","schema":{"attributes":[{"default":-1,"name":"best_iteration"},{"default":false,"name":"network"},{"default":null,"name":"train_set"},{"default":false,"name":"stride"},{"default":null,"name":"model_file"},{"default":null,"name":"params"},{"default":null,"name":"pandas_categorical"}]}},{"name":"sklearn.linear_model.LinearRegression","schema":{"attributes":[{"default":true,"description":"Whether to calculate the intercept for this model. If set\nto False, no intercept will be used in calculations\n(i.e. data is expected to be centered).\n","name":"fit_intercept","option":"optional","type":"boolean"},{"default":false,"description":"This parameter is ignored when ``fit_intercept`` is set to False.\nIf True, the regressors X will be normalized before regression by\nsubtracting the mean and dividing by the l2-norm.\nIf you wish to standardize, please use\n:class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on\nan estimator with ``normalize=False``.\n","name":"normalize","option":"optional","type":"boolean"},{"default":true,"description":"If True, X will be copied; else, it may be overwritten.\n","name":"copy_X","option":"optional","type":"boolean"},{"default":null,"description":"The number of jobs to use for the computation. This will only provide\nspeedup for n_targets > 1 and sufficient large problems.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"\nOrdinary least squares Linear Regression.\n\nLinearRegression fits a linear model with coefficients w = (w1, ..., wp)\nto minimize the residual sum of squares between the observed targets in\nthe dataset, and the targets predicted by the linear approximation.\n"}},{"name":"sklearn.pipeline.FeatureUnion","schema":{"attributes":[{"description":"List of transformer objects to be applied to the data. The first\nhalf of each tuple is the name of the transformer.\n\n.. versionchanged:: 0.22\nDeprecated `None` as a transformer in favor of 'drop'.\n","name":"transformer_list"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n\n.. versionchanged:: v0.20\n`n_jobs` default changed from 1 to None\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Multiplicative weights for features per transformer.\nKeys are transformer names, values the weights.\n","name":"transformer_weights"},{"default":false,"description":"If True, the time elapsed while fitting each transformer will be\nprinted as it is completed.\n","name":"verbose","type":"boolean"}],"description":"Concatenates results of multiple transformer objects.\n\nThis estimator applies a list of transformer objects in parallel to the\ninput data, then concatenates the results. This is useful to combine\nseveral feature extraction mechanisms into a single transformer.\n\nParameters of the transformers may be set using its name and the parameter\nname separated by a '__'. A transformer may be replaced entirely by\nsetting the parameter with its name to another transformer,\nor removed by setting to 'drop'.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.13\n"}},{"name":"sklearn.compose._column_transformer.ColumnTransformer","schema":{"attributes":[{"description":"List of (name, transformer, columns) tuples specifying the\ntransformer objects to be applied to subsets of the data.\n\nname : str\nLike in Pipeline and FeatureUnion, this allows the transformer and\nits parameters to be set using ``set_params`` and searched in grid\nsearch.\ntransformer : {'drop', 'passthrough'} or estimator\nEstimator must support :term:`fit` and :term:`transform`.\nSpecial-cased strings 'drop' and 'passthrough' are accepted as\nwell, to indicate to drop the columns or to pass them through\nuntransformed, respectively.\ncolumns : str, array-like of str, int, array-like of int, array-like of bool, slice or callable\nIndexes the data on its second axis. Integers are interpreted as\npositional columns, while strings can reference DataFrame columns\nby name. A scalar string or int should be used where\n``transformer`` expects X to be a 1d array-like (vector),\notherwise a 2d array will be passed to the transformer.\nA callable is passed the input data `X` and can return any of the\nabove. To select multiple columns by name or dtype, you can use\n:obj:`make_column_selector`.\n","name":"transformers"},{"description":"By default, only the specified columns in `transformers` are\ntransformed and combined in the output, and the non-specified\ncolumns are dropped. (default of ``'drop'``).\nBy specifying ``remainder='passthrough'``, all remaining columns that\nwere not specified in `transformers` will be automatically passed\nthrough. This subset of columns is concatenated with the output of\nthe transformers.\nBy setting ``remainder`` to be an estimator, the remaining\nnon-specified columns will use the ``remainder`` estimator. The\nestimator must support :term:`fit` and :term:`transform`.\nNote that using this feature requires that the DataFrame columns\ninput at :term:`fit` and :term:`transform` have identical order.\n","name":"remainder"},{"default":0.3,"description":"If the output of the different transformers contains sparse matrices,\nthese will be stacked as a sparse matrix if the overall density is\nlower than this value. Use ``sparse_threshold=0`` to always return\ndense. When the transformed output consists of all dense data, the\nstacked result will be dense, and this keyword will be ignored.\n","name":"sparse_threshold","type":"float32"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Multiplicative weights for features per transformer. The output of the\ntransformer is multiplied by these weights. Keys are transformer names,\nvalues the weights.\n","name":"transformer_weights"},{"default":false,"description":"If True, the time elapsed while fitting each transformer will be\nprinted as it is completed.\n","name":"verbose","type":"boolean"}],"description":"Applies transformers to columns of an array or pandas DataFrame.\n\nThis estimator allows different columns or column subsets of the input\nto be transformed separately and the features generated by each transformer\nwill be concatenated to form a single feature space.\nThis is useful for heterogeneous or columnar data, to combine several\nfeature extraction mechanisms or transformations into a single transformer.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n"}},{"name":"sklearn.preprocessing._encoders.OneHotEncoder","schema":{"attributes":[{"description":"Categories (unique values) per feature:\n\n- 'auto' : Determine categories automatically from the training data.\n- list : ``categories[i]`` holds the categories expected in the ith\ncolumn. The passed categories should not mix strings and numeric\nvalues within a single feature, and should be sorted in case of\nnumeric values.\n\nThe used categories can be found in the ``categories_`` attribute.\n\n.. versionadded:: 0.20\n","name":"categories"},{"description":"Specifies a methodology to use to drop one of the categories per\nfeature. This is useful in situations where perfectly collinear\nfeatures cause problems, such as when feeding the resulting data\ninto a neural network or an unregularized regression.\n\nHowever, dropping one category breaks the symmetry of the original\nrepresentation and can therefore induce a bias in downstream models,\nfor instance for penalized linear classification or regression models.\n\n- None : retain all features (the default).\n- 'first' : drop the first category in each feature. If only one\ncategory is present, the feature will be dropped entirely.\n- 'if_binary' : drop the first category in each feature with two\ncategories. Features with 1 or more than 2 categories are\nleft intact.\n- array : ``drop[i]`` is the category in feature ``X[:, i]`` that\nshould be dropped.\n","name":"drop"},{"default":true,"description":"Will return sparse matrix if set True else will return an array.\n","name":"sparse","type":"boolean"},{"default":"np.float","description":"Desired dtype of output.\n","name":"dtype"},{"default":"error","description":"Whether to raise an error or ignore if an unknown categorical feature\nis present during transform (default is to raise). When this parameter\nis set to 'ignore' and an unknown category is encountered during\ntransform, the resulting one-hot encoded columns for this feature\nwill be all zeros. In the inverse transform, an unknown category\nwill be denoted as None.\n","name":"handle_unknown"}],"description":"\nEncode categorical features as a one-hot numeric array.\n\nThe input to this transformer should be an array-like of integers or\nstrings, denoting the values taken on by categorical (discrete) features.\nThe features are encoded using a one-hot (aka 'one-of-K' or 'dummy')\nencoding scheme. This creates a binary column for each category and\nreturns a sparse matrix or dense array (depending on the ``sparse``\nparameter)\n\nBy default, the encoder derives the categories based on the unique values\nin each feature. Alternatively, you can also specify the `categories`\nmanually.\n\nThis encoding is needed for feeding categorical data to many scikit-learn\nestimators, notably linear models and SVMs with the standard kernels.\n\nNote: a one-hot encoding of y labels should use a LabelBinarizer\ninstead.\n\nRead more in the :ref:`User Guide `.\n\n.. versionchanged:: 0.20\n"}},{"name":"sklearn.feature_selection._univariate_selection.SelectKBest","schema":{"attributes":[{"description":"Function taking two arrays X and y, and returning a pair of arrays\n(scores, pvalues) or a single array with scores.\nDefault is f_classif (see below \"See also\"). The default function only\nworks with classification tasks.\n\n.. versionadded:: 0.18\n","name":"score_func"},{"default":"10","description":"Number of top features to select.\nThe \"all\" option bypasses selection, for use in a parameter search.\n","name":"k","option":"optional"}],"description":"Select features according to the k highest scores.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.impute._base.SimpleImputer","schema":{"attributes":[{"description":"The placeholder for the missing values. All occurrences of\n`missing_values` will be imputed. For pandas' dataframes with\nnullable integer dtypes with missing values, `missing_values`\nshould be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.\n","name":"missing_values"},{"default":"mean","description":"The imputation strategy.\n\n- If \"mean\", then replace missing values using the mean along\neach column. Can only be used with numeric data.\n- If \"median\", then replace missing values using the median along\neach column. Can only be used with numeric data.\n- If \"most_frequent\", then replace missing using the most frequent\nvalue along each column. Can be used with strings or numeric data.\n- If \"constant\", then replace missing values with fill_value. Can be\nused with strings or numeric data.\n\n.. versionadded:: 0.20\nstrategy=\"constant\" for fixed value imputation.\n","name":"strategy","type":"string"},{"default":null,"description":"When strategy == \"constant\", fill_value is used to replace all\noccurrences of missing_values.\nIf left to the default, fill_value will be 0 when imputing numerical\ndata and \"missing_value\" for strings or object data types.\n","name":"fill_value"},{"default":0,"description":"Controls the verbosity of the imputer.\n","name":"verbose","type":"int32"},{"default":true,"description":"If True, a copy of X will be created. If False, imputation will\nbe done in-place whenever possible. Note that, in the following cases,\na new copy will always be made, even if `copy=False`:\n\n- If X is not an array of floating values;\n- If X is encoded as a CSR matrix;\n- If add_indicator=True.\n","name":"copy","type":"boolean"},{"default":false,"description":"If True, a :class:`MissingIndicator` transform will stack onto output\nof the imputer's transform. This allows a predictive estimator\nto account for missingness despite imputation. If a feature has no\nmissing values at fit/train time, the feature won't appear on\nthe missing indicator even if there are missing values at\ntransform/test time.\n","name":"add_indicator","type":"boolean"}],"description":"Imputation transformer for completing missing values.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n`SimpleImputer` replaces the previous `sklearn.preprocessing.Imputer`\nestimator which is now removed.\n"}},{"name":"sklearn.model_selection._search.GridSearchCV","schema":{"attributes":[{"description":"This is assumed to implement the scikit-learn estimator interface.\nEither estimator needs to provide a ``score`` function,\nor ``scoring`` must be passed.\n","name":"estimator"},{"description":"Dictionary with parameters names (`str`) as keys and lists of\nparameter settings to try as values, or a list of such\ndictionaries, in which case the grids spanned by each dictionary\nin the list are explored. This enables searching over any sequence\nof parameter settings.\n","name":"param_grid"},{"default":null,"description":"A single str (see :ref:`scoring_parameter`) or a callable\n(see :ref:`scoring`) to evaluate the predictions on the test set.\n\nFor evaluating multiple metrics, either give a list of (unique) strings\nor a dict with names as keys and callables as values.\n\nNOTE that when using custom scorers, each scorer should return a single\nvalue. Metric functions returning a list/array of values can be wrapped\ninto multiple scorers that return one value each.\n\nSee :ref:`multimetric_grid_search` for an example.\n\nIf None, the estimator's score method is used.\n","name":"scoring"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n\n.. versionchanged:: v0.20\n`n_jobs` default changed from 1 to None\n","name":"n_jobs","type":"int32"},{"description":"Controls the number of jobs that get dispatched during parallel\nexecution. Reducing this number can be useful to avoid an\nexplosion of memory consumption when more jobs get dispatched\nthan CPUs can process. This parameter can be:\n\n- None, in which case all the jobs are immediately\ncreated and spawned. Use this for lightweight and\nfast-running jobs, to avoid delays due to on-demand\nspawning of the jobs\n\n- An int, giving the exact number of total jobs that are\nspawned\n\n- A str, giving an expression as a function of n_jobs,\nas in '2*n_jobs'\n","name":"pre_dispatch"},{"default":false,"description":"If True, return the average score across folds, weighted by the number\nof samples in each test set. In this case, the data is assumed to be\nidentically distributed across the folds, and the loss minimized is\nthe total loss per sample, and not the mean loss across the folds.\n\n.. deprecated:: 0.22\nParameter ``iid`` is deprecated in 0.22 and will be removed in 0.24\n","name":"iid","type":"boolean"},{"default":null,"description":"Determines the cross-validation splitting strategy.\nPossible inputs for cv are:\n\n- None, to use the default 5-fold cross validation,\n- integer, to specify the number of folds in a `(Stratified)KFold`,\n- :term:`CV splitter`,\n- An iterable yielding (train, test) splits as arrays of indices.\n\nFor integer/None inputs, if the estimator is a classifier and ``y`` is\neither binary or multiclass, :class:`StratifiedKFold` is used. In all\nother cases, :class:`KFold` is used.\n\nRefer :ref:`User Guide ` for the various\ncross-validation strategies that can be used here.\n\n.. versionchanged:: 0.22\n``cv`` default value if None changed from 3-fold to 5-fold.\n","name":"cv","type":"int32"},{"default":true,"description":"Refit an estimator using the best found parameters on the whole\ndataset.\n\nFor multiple metric evaluation, this needs to be a `str` denoting the\nscorer that would be used to find the best parameters for refitting\nthe estimator at the end.\n\nWhere there are considerations other than maximum score in\nchoosing a best estimator, ``refit`` can be set to a function which\nreturns the selected ``best_index_`` given ``cv_results_``. In that\ncase, the ``best_estimator_`` and ``best_params_`` will be set\naccording to the returned ``best_index_`` while the ``best_score_``\nattribute will not be available.\n\nThe refitted estimator is made available at the ``best_estimator_``\nattribute and permits using ``predict`` directly on this\n``GridSearchCV`` instance.\n\nAlso for multiple metric evaluation, the attributes ``best_index_``,\n``best_score_`` and ``best_params_`` will only be available if\n``refit`` is set and all of them will be determined w.r.t this specific\nscorer.\n\nSee ``scoring`` parameter to know more about multiple metric\nevaluation.\n\n.. versionchanged:: 0.20\nSupport for callable added.\n","name":"refit","type":"boolean"},{"description":"Controls the verbosity: the higher, the more messages.\n","name":"verbose","type":"int32"},{"description":"Value to assign to the score if an error occurs in estimator fitting.\nIf set to 'raise', the error is raised. If a numeric value is given,\nFitFailedWarning is raised. This parameter does not affect the refit\nstep, which will always raise the error.\n","name":"error_score"},{"default":false,"description":"If ``False``, the ``cv_results_`` attribute will not include training\nscores.\nComputing training scores is used to get insights on how different\nparameter settings impact the overfitting/underfitting trade-off.\nHowever computing the scores on the training set can be computationally\nexpensive and is not strictly required to select the parameters that\nyield the best generalization performance.\n\n.. versionadded:: 0.19\n\n.. versionchanged:: 0.21\nDefault value was changed from ``True`` to ``False``\n\n","name":"return_train_score","type":"boolean"}],"description":"Exhaustive search over specified parameter values for an estimator.\n\nImportant members are fit, predict.\n\nGridSearchCV implements a \"fit\" and a \"score\" method.\nIt also implements \"predict\", \"predict_proba\", \"decision_function\",\n\"transform\" and \"inverse_transform\" if they are implemented in the\nestimator used.\n\nThe parameters of the estimator used to apply these methods are optimized\nby cross-validated grid-search over a parameter grid.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition._truncated_svd.TruncatedSVD","schema":{"attributes":[{"default":2,"description":"Desired dimensionality of output data.\nMust be strictly less than the number of features.\nThe default value is useful for visualisation. For LSA, a value of\n100 is recommended.\n","name":"n_components","type":"int32"},{"default":"randomized","description":"SVD solver to use. Either \"arpack\" for the ARPACK wrapper in SciPy\n(scipy.sparse.linalg.svds), or \"randomized\" for the randomized\nalgorithm due to Halko (2009).\n","name":"algorithm","type":"string"},{"default":5,"description":"Number of iterations for randomized SVD solver. Not used by ARPACK. The\ndefault is larger than the default in\n:func:`~sklearn.utils.extmath.randomized_svd` to handle sparse\nmatrices that may have large slowly decaying spectrum.\n","name":"n_iter","option":"optional","type":"int32"},{"default":null,"description":"Used during randomized svd. Pass an int for reproducible results across\nmultiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","type":"int32"},{"description":"Tolerance for ARPACK. 0 means machine precision. Ignored by randomized\nSVD solver.\n","name":"tol","option":"optional","type":"float32"}],"description":"Dimensionality reduction using truncated SVD (aka LSA).\n\nThis transformer performs linear dimensionality reduction by means of\ntruncated singular value decomposition (SVD). Contrary to PCA, this\nestimator does not center the data before computing the singular value\ndecomposition. This means it can work with sparse matrices\nefficiently.\n\nIn particular, truncated SVD works on term count/tf-idf matrices as\nreturned by the vectorizers in :mod:`sklearn.feature_extraction.text`. In\nthat context, it is known as latent semantic analysis (LSA).\n\nThis estimator supports two algorithms: a fast randomized SVD solver, and\na \"naive\" algorithm that uses ARPACK as an eigensolver on `X * X.T` or\n`X.T * X`, whichever is more efficient.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.ensemble.forest.RandomForestClassifier","schema":{"attributes":[{"default":100,"description":"The number of trees in the forest.\n\n.. versionchanged:: 0.22\nThe default value of ``n_estimators`` changed from 10 to 100\nin 0.22.\n","name":"n_estimators","type":"int32"},{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\nNote: this parameter is tree-specific.\n","name":"criterion"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":"\"auto\"","description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)` (same as \"auto\").\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features"},{"default":null,"description":"Grow trees with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":null,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n\n","name":"min_impurity_split","type":"float32"},{"default":true,"description":"Whether bootstrap samples are used when building trees. If False, the\nwhole dataset is used to build each tree.\n","name":"bootstrap","type":"boolean"},{"default":false,"description":"Whether to use out-of-bag samples to estimate\nthe generalization accuracy.\n","name":"oob_score","type":"boolean"},{"default":null,"description":"The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,\n:meth:`decision_path` and :meth:`apply` are all parallelized over the\ntrees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors. See :term:`Glossary\n` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Controls both the randomness of the bootstrapping of the samples used\nwhen building trees (if ``bootstrap=True``) and the sampling of the\nfeatures to consider when looking for the best split at each node\n(if ``max_features < n_features``).\nSee :term:`Glossary ` for details.\n","name":"random_state"},{"default":0,"description":"Controls the verbosity when fitting and predicting.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to ``True``, reuse the solution of the previous call to fit\nand add more estimators to the ensemble, otherwise, just fit a whole\nnew forest. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nThe \"balanced_subsample\" mode is the same as \"balanced\" except that\nweights are computed based on the bootstrap sample for every tree\ngrown.\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"},{"default":null,"description":"If bootstrap is True, the number of samples to draw from X\nto train each base estimator.\n\n- If None (default), then draw `X.shape[0]` samples.\n- If int, then draw `max_samples` samples.\n- If float, then draw `max_samples * X.shape[0]` samples. Thus,\n`max_samples` should be in the interval `(0, 1)`.\n\n.. versionadded:: 0.22\n","name":"max_samples"}],"description":"\nA random forest classifier.\n\nA random forest is a meta estimator that fits a number of decision tree\nclassifiers on various sub-samples of the dataset and uses averaging to\nimprove the predictive accuracy and control over-fitting.\nThe sub-sample size is controlled with the `max_samples` parameter if\n`bootstrap=True` (default), otherwise the whole dataset is used to build\neach tree.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.ensemble.weight_boosting.AdaBoostClassifier","schema":{"attributes":[{"default":null,"description":"The base estimator from which the boosted ensemble is built.\nSupport for sample weighting is required, as well as proper\n``classes_`` and ``n_classes_`` attributes. If ``None``, then\nthe base estimator is ``DecisionTreeClassifier(max_depth=1)``.\n","name":"base_estimator"},{"default":50,"description":"The maximum number of estimators at which boosting is terminated.\nIn case of perfect fit, the learning procedure is stopped early.\n","name":"n_estimators","type":"int32"},{"default":1,"description":"Learning rate shrinks the contribution of each classifier by\n``learning_rate``. There is a trade-off between ``learning_rate`` and\n``n_estimators``.\n","name":"learning_rate","type":"float32"},{"default":"SAMME.R","description":"If 'SAMME.R' then use the SAMME.R real boosting algorithm.\n``base_estimator`` must support calculation of class probabilities.\nIf 'SAMME' then use the SAMME discrete boosting algorithm.\nThe SAMME.R algorithm typically converges faster than SAMME,\nachieving a lower test error with fewer boosting iterations.\n","name":"algorithm"},{"default":null,"description":"Controls the random seed given at each `base_estimator` at each\nboosting iteration.\nThus, it is only used when `base_estimator` exposes a `random_state`.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state"}],"description":"An AdaBoost classifier.\n\nAn AdaBoost [1] classifier is a meta-estimator that begins by fitting a\nclassifier on the original dataset and then fits additional copies of the\nclassifier on the same dataset but where the weights of incorrectly\nclassified instances are adjusted such that subsequent classifiers focus\nmore on difficult cases.\n\nThis class implements the algorithm known as AdaBoost-SAMME [2].\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.14\n"}},{"name":"sklearn.ensemble.forest.ExtraTreesClassifier","schema":{"attributes":[{"default":100,"description":"The number of trees in the forest.\n\n.. versionchanged:: 0.22\nThe default value of ``n_estimators`` changed from 10 to 100\nin 0.22.\n","name":"n_estimators","type":"int32"},{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\n","name":"criterion"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":"\"auto\"","description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)`.\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features"},{"default":null,"description":"Grow trees with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":null,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n","name":"min_impurity_split","type":"float32"},{"default":false,"description":"Whether bootstrap samples are used when building trees. If False, the\nwhole dataset is used to build each tree.\n","name":"bootstrap","type":"boolean"},{"default":false,"description":"Whether to use out-of-bag samples to estimate\nthe generalization accuracy.\n","name":"oob_score","type":"boolean"},{"default":null,"description":"The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,\n:meth:`decision_path` and :meth:`apply` are all parallelized over the\ntrees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors. See :term:`Glossary\n` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Controls 3 sources of randomness:\n\n- the bootstrapping of the samples used when building trees\n(if ``bootstrap=True``)\n- the sampling of the features to consider when looking for the best\nsplit at each node (if ``max_features < n_features``)\n- the draw of the splits for each of the `max_features`\n\nSee :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":0,"description":"Controls the verbosity when fitting and predicting.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to ``True``, reuse the solution of the previous call to fit\nand add more estimators to the ensemble, otherwise, just fit a whole\nnew forest. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nThe \"balanced_subsample\" mode is the same as \"balanced\" except that\nweights are computed based on the bootstrap sample for every tree\ngrown.\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"},{"default":null,"description":"If bootstrap is True, the number of samples to draw from X\nto train each base estimator.\n\n- If None (default), then draw `X.shape[0]` samples.\n- If int, then draw `max_samples` samples.\n- If float, then draw `max_samples * X.shape[0]` samples. Thus,\n`max_samples` should be in the interval `(0, 1)`.\n\n.. versionadded:: 0.22\n","name":"max_samples"}],"description":"\nAn extra-trees classifier.\n\nThis class implements a meta estimator that fits a number of\nrandomized decision trees (a.k.a. extra-trees) on various sub-samples\nof the dataset and uses averaging to improve the predictive accuracy\nand control over-fitting.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neural_network.multilayer_perceptron.MLPRegressor","schema":{"attributes":[{"default":"(100,)","description":"The ith element represents the number of neurons in the ith\nhidden layer.\n","name":"hidden_layer_sizes"},{"default":"relu","description":"Activation function for the hidden layer.\n\n- 'identity', no-op activation, useful to implement linear bottleneck,\nreturns f(x) = x\n\n- 'logistic', the logistic sigmoid function,\nreturns f(x) = 1 / (1 + exp(-x)).\n\n- 'tanh', the hyperbolic tan function,\nreturns f(x) = tanh(x).\n\n- 'relu', the rectified linear unit function,\nreturns f(x) = max(0, x)\n","name":"activation"},{"default":"adam","description":"The solver for weight optimization.\n\n- 'lbfgs' is an optimizer in the family of quasi-Newton methods.\n\n- 'sgd' refers to stochastic gradient descent.\n\n- 'adam' refers to a stochastic gradient-based optimizer proposed by\nKingma, Diederik, and Jimmy Ba\n\nNote: The default solver 'adam' works pretty well on relatively\nlarge datasets (with thousands of training samples or more) in terms of\nboth training time and validation score.\nFor small datasets, however, 'lbfgs' can converge faster and perform\nbetter.\n","name":"solver"},{"default":0.0001,"description":"L2 penalty (regularization term) parameter.\n","name":"alpha","type":"float32"},{"default":"auto","description":"Size of minibatches for stochastic optimizers.\nIf the solver is 'lbfgs', the classifier will not use minibatch.\nWhen set to \"auto\", `batch_size=min(200, n_samples)`\n","name":"batch_size","type":"int32"},{"default":"constant","description":"Learning rate schedule for weight updates.\n\n- 'constant' is a constant learning rate given by\n'learning_rate_init'.\n\n- 'invscaling' gradually decreases the learning rate ``learning_rate_``\nat each time step 't' using an inverse scaling exponent of 'power_t'.\neffective_learning_rate = learning_rate_init / pow(t, power_t)\n\n- 'adaptive' keeps the learning rate constant to\n'learning_rate_init' as long as training loss keeps decreasing.\nEach time two consecutive epochs fail to decrease training loss by at\nleast tol, or fail to increase validation score by at least tol if\n'early_stopping' is on, the current learning rate is divided by 5.\n\nOnly used when solver='sgd'.\n","name":"learning_rate"},{"default":"0.001","description":"The initial learning rate used. It controls the step-size\nin updating the weights. Only used when solver='sgd' or 'adam'.\n","name":"learning_rate_init"},{"default":"0.5","description":"The exponent for inverse scaling learning rate.\nIt is used in updating effective learning rate when the learning_rate\nis set to 'invscaling'. Only used when solver='sgd'.\n","name":"power_t"},{"default":200,"description":"Maximum number of iterations. The solver iterates until convergence\n(determined by 'tol') or this number of iterations. For stochastic\nsolvers ('sgd', 'adam'), note that this determines the number of epochs\n(how many times each data point will be used), not the number of\ngradient steps.\n","name":"max_iter","type":"int32"},{"default":true,"description":"Whether to shuffle samples in each iteration. Only used when\nsolver='sgd' or 'adam'.\n","name":"shuffle","type":"boolean"},{"default":null,"description":"Determines random number generation for weights and bias\ninitialization, train-test split if early stopping is used, and batch\nsampling when solver='sgd' or 'adam'.\nPass an int for reproducible results across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","type":"int32"},{"default":0.0001,"description":"Tolerance for the optimization. When the loss or score is not improving\nby at least ``tol`` for ``n_iter_no_change`` consecutive iterations,\nunless ``learning_rate`` is set to 'adaptive', convergence is\nconsidered to be reached and training stops.\n","name":"tol","type":"float32"},{"default":false,"description":"Whether to print progress messages to stdout.\n","name":"verbose","type":"boolean"},{"default":false,"description":"When set to True, reuse the solution of the previous\ncall to fit as initialization, otherwise, just erase the\nprevious solution. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":0.9,"description":"Momentum for gradient descent update. Should be between 0 and 1. Only\nused when solver='sgd'.\n","name":"momentum","type":"float32"},{"default":true,"description":"Whether to use Nesterov's momentum. Only used when solver='sgd' and\nmomentum > 0.\n","name":"nesterovs_momentum","type":"boolean"},{"default":false,"description":"Whether to use early stopping to terminate training when validation\nscore is not improving. If set to true, it will automatically set\naside 10% of training data as validation and terminate training when\nvalidation score is not improving by at least ``tol`` for\n``n_iter_no_change`` consecutive epochs.\nOnly effective when solver='sgd' or 'adam'\n","name":"early_stopping","type":"boolean"},{"default":0.1,"description":"The proportion of training data to set aside as validation set for\nearly stopping. Must be between 0 and 1.\nOnly used if early_stopping is True\n","name":"validation_fraction","type":"float32"},{"default":0.9,"description":"Exponential decay rate for estimates of first moment vector in adam,\nshould be in [0, 1). Only used when solver='adam'\n","name":"beta_1","type":"float32"},{"default":0.999,"description":"Exponential decay rate for estimates of second moment vector in adam,\nshould be in [0, 1). Only used when solver='adam'\n","name":"beta_2","type":"float32"},{"default":1e-8,"description":"Value for numerical stability in adam. Only used when solver='adam'\n","name":"epsilon","type":"float32"},{"default":10,"description":"Maximum number of epochs to not meet ``tol`` improvement.\nOnly effective when solver='sgd' or 'adam'\n\n.. versionadded:: 0.20\n","name":"n_iter_no_change","type":"int32"},{"default":15000,"description":"Only used when solver='lbfgs'. Maximum number of function calls.\nThe solver iterates until convergence (determined by 'tol'), number\nof iterations reaches max_iter, or this number of function calls.\nNote that number of function calls will be greater than or equal to\nthe number of iterations for the MLPRegressor.\n\n.. versionadded:: 0.22\n","name":"max_fun","type":"int32"}],"description":"Multi-layer Perceptron regressor.\n\nThis model optimizes the squared-loss using LBFGS or stochastic gradient\ndescent.\n\n.. versionadded:: 0.18\n"}},{"name":"sklearn.discriminant_analysis.LinearDiscriminantAnalysis","schema":{"attributes":[{"default":"svd","description":"Solver to use, possible values:\n- 'svd': Singular value decomposition (default).\nDoes not compute the covariance matrix, therefore this solver is\nrecommended for data with a large number of features.\n- 'lsqr': Least squares solution, can be combined with shrinkage.\n- 'eigen': Eigenvalue decomposition, can be combined with shrinkage.\n","name":"solver"},{"description":"Shrinkage parameter, possible values:\n- None: no shrinkage (default).\n- 'auto': automatic shrinkage using the Ledoit-Wolf lemma.\n- float between 0 and 1: fixed shrinkage parameter.\n\nNote that shrinkage works only with 'lsqr' and 'eigen' solvers.\n","name":"shrinkage"},{"default":null,"description":"The class prior probabilities. By default, the class proportions are\ninferred from the training data.\n","name":"priors"},{"default":null,"description":"Number of components (<= min(n_classes - 1, n_features)) for\ndimensionality reduction. If None, will be set to\nmin(n_classes - 1, n_features). This parameter only affects the\n`transform` method.\n","name":"n_components","type":"int32"},{"default":false,"description":"If True, explicitely compute the weighted within-class covariance\nmatrix when solver is 'svd'. The matrix is always computed\nand stored for the other solvers.\n\n.. versionadded:: 0.17\n","name":"store_covariance","type":"boolean"},{"default":0.0001,"description":"Absolute threshold for a singular value of X to be considered\nsignificant, used to estimate the rank of X. Dimensions whose\nsingular values are non-significant are discarded. Only used if\nsolver is 'svd'.\n\n.. versionadded:: 0.17\n","name":"tol","type":"float32"}],"description":"Linear Discriminant Analysis\n\nA classifier with a linear decision boundary, generated by fitting class\nconditional densities to the data and using Bayes' rule.\n\nThe model fits a Gaussian density to each class, assuming that all classes\nshare the same covariance matrix.\n\nThe fitted model can also be used to reduce the dimensionality of the input\nby projecting it to the most discriminative directions, using the\n`transform` method.\n\n.. versionadded:: 0.17\n*LinearDiscriminantAnalysis*.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.preprocessing._data.StandardScaler","schema":{"attributes":[{"default":true,"description":"If False, try to avoid a copy and do inplace scaling instead.\nThis is not guaranteed to always work inplace; e.g. if the data is\nnot a NumPy array or scipy.sparse CSR matrix, a copy may still be\nreturned.\n","name":"copy","option":"optional","type":"boolean"},{"default":true,"description":"If True, center the data before scaling.\nThis does not work (and will raise an exception) when attempted on\nsparse matrices, because centering them entails building a dense\nmatrix which in common use cases is likely to be too large to fit in\nmemory.\n","name":"with_mean","type":"boolean"},{"default":true,"description":"If True, scale the data to unit variance (or equivalently,\nunit standard deviation).\n","name":"with_std","type":"boolean"}],"description":"Standardize features by removing the mean and scaling to unit variance\n\nThe standard score of a sample `x` is calculated as:\n\nz = (x - u) / s\n\nwhere `u` is the mean of the training samples or zero if `with_mean=False`,\nand `s` is the standard deviation of the training samples or one if\n`with_std=False`.\n\nCentering and scaling happen independently on each feature by computing\nthe relevant statistics on the samples in the training set. Mean and\nstandard deviation are then stored to be used on later data using\n:meth:`transform`.\n\nStandardization of a dataset is a common requirement for many\nmachine learning estimators: they might behave badly if the\nindividual features do not more or less look like standard normally\ndistributed data (e.g. Gaussian with 0 mean and unit variance).\n\nFor instance many elements used in the objective function of\na learning algorithm (such as the RBF kernel of Support Vector\nMachines or the L1 and L2 regularizers of linear models) assume that\nall features are centered around 0 and have variance in the same\norder. If a feature has a variance that is orders of magnitude larger\nthat others, it might dominate the objective function and make the\nestimator unable to learn from other features correctly as expected.\n\nThis scaler can also be applied to sparse CSR or CSC matrices by passing\n`with_mean=False` to avoid breaking the sparsity structure of the data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.tree.tree.DecisionTreeClassifier","schema":{"attributes":[{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\n","name":"criterion"},{"default":"\"best\"","description":"The strategy used to choose the split at each node. Supported\nstrategies are \"best\" to choose the best split and \"random\" to choose\nthe best random split.\n","name":"splitter"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":null,"description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)`.\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features","type":"int32"},{"default":null,"description":"Controls the randomness of the estimator. The features are always\nrandomly permuted at each split, even if ``splitter`` is set to\n``\"best\"``. When ``max_features < n_features``, the algorithm will\nselect ``max_features`` at random at each split before finding the best\nsplit among them. But the best found split may vary across different\nruns, even if ``max_features=n_features``. That is the case, if the\nimprovement of the criterion is identical for several splits and one\nsplit has to be selected at random. To obtain a deterministic behaviour\nduring fitting, ``random_state`` has to be fixed to an integer.\nSee :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":null,"description":"Grow a tree with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":0,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n","name":"min_impurity_split","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf None, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"deprecated","description":"This parameter is deprecated and will be removed in v0.24.\n\n.. deprecated:: 0.22\n","name":"presort"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"}],"description":"A decision tree classifier.\n\nRead more in the :ref:`User Guide `.\n"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn.js new file mode 100644 index 0000000000000000000000000000000000000000..493509379375ec8aff36e8df6716c58ce1ce2542 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/sklearn.js @@ -0,0 +1 @@ +var sklearn=sklearn||{},long=long||{Long:require("long")},zip=zip||require("./zip");sklearn.ModelFactory=class{match(e){const t=e.identifier.split(".").pop().toLowerCase();if(-1!==["pkl","pickle","joblib","model","meta","pb","pt","h5"].indexOf(t)){const t=e.buffer;if(t){const e=[138,10,108,252,156,70,249,32,106,168,80,25];if(t.length>14&&128==t[0]&&e.every(((e,n)=>e==t[n+2])))return!1;if(t.length>1&&46===t[t.length-1])return!0;if(t.length>2&&128===t[0]&&t[1]<5)return!0}}if(-1!==["pkl","joblib"].indexOf(t)){const t=e.buffer;if(t&&t.length>0&&120==t[0])return!0}return!1}open(e,t){return t.require("./pickle").then((n=>{const s=e.identifier;return sklearn.Metadata.open(t).then((r=>{try{const i=new sklearn.Container(e.buffer,n,((e,n)=>{const r=e&&e.message?e.message:e.toString();t.exception(new sklearn.Error(r.replace(/\.$/,"")+" in '"+s+"'."),n)}));if(!i.weights&&!i.data)throw new sklearn.Error("No root object.");return new sklearn.Model(r,i.data,i.weights)}catch(e){t.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new sklearn.Error(n.replace(/\.$/,"")+" in '"+s+"'.")}}))}))}},sklearn.Model=class{constructor(e,t,n){const s=Array.isArray(t)?t:[t],r=Array.from(new Set(s.map((e=>{if(e&&e.__module__){if(e.__module__.startsWith("sklearn."))return"scikit-learn"+(e._sklearn_version?" v"+e._sklearn_version.toString():"");if(e.__module__.startsWith("xgboost."))return"XGBoost"+(e._sklearn_version?" v"+e._sklearn_version.toString():"");if(e.__module__.startsWith("nolearn.lasagne."))return"Lasagne";if(e.__module__.startsWith("gensim."))return"gensim"}return"Pickle"}))).values());if(r.length>1)throw new sklearn.Error("Invalid array format '"+JSON.stringify(r)+"'.");this._format=r[0],this._graphs=s.map(((t,s)=>new sklearn.Graph(e,s,t,n)))}get format(){return this._format}get graphs(){return this._graphs}},sklearn.Graph=class{constructor(e,t,n,s){if(this._name=t.toString(),this._metadata=e,this._nodes=[],this._groups=!1,n)this._process("","",n,["data"]);else if(s instanceof Map){const e=new Map,t=[];for(const n of s){const s=n[0],r=s.split("_"),i=n[1],a=r.length>1?r.pop():"?",o=r.join("_");let l=e.get(o);l||(l={id:o,arrays:[]},t.push(l),e.set(o,l)),l.arrays.push({key:s,name:a,value:i})}this._nodes=this._nodes.concat(t.map((e=>{const t=e.arrays.map((e=>new sklearn.Parameter(e.name,[new sklearn.Argument(e.key,null,new sklearn.Tensor(e.key,e.value))])));return new sklearn.Node(this._metadata,"",e.id,{__module__:"sklearn._",__name__:"Weights"},t,[])})))}}_process(e,t,n,s){switch([n.__module__,n.__name__].join(".")){case"sklearn.pipeline.Pipeline":{this._groups=!0,t=t||"pipeline";const r=this._concat(e,t);for(const e of n.steps)s=this._process(r,e[0],e[1],s);return s}case"sklearn.pipeline.FeatureUnion":{this._groups=!0;let r=[];t=t||"union";const i=this._concat(e,t),a=this._concat(e,t);this._add(a,i,n,s,[i]);for(const e of n.transformer_list)r=r.concat(this._process(a,e[0],e[1],[i]));return r}case"sklearn.compose._column_transformer.ColumnTransformer":{this._groups=!0,t=t||"transformer";const r=this._concat(e,t),i=this._concat(e,t);let a=[];this._add(i,r,n,s,[r]);for(const e of n.transformers)a=a.concat(this._process(i,e[0],e[1],[r]));return a}default:{const r=this._concat(e,t);return this._add(e,r,n,s,[r]),[r]}}}_add(e,t,n,s,r){const i=[];for(const e of Object.keys(n))if(!e.startsWith("_")){const t=n[e];sklearn.Utility.isTensor(t)&&i.push(new sklearn.Tensor(e,t))}s=(s=s.map((e=>new sklearn.Parameter(e,[new sklearn.Argument(e,null,null)])))).concat(i.map((e=>new sklearn.Parameter(e.name,[new sklearn.Argument("",null,e)])))),r=r.map((e=>new sklearn.Parameter(e,[new sklearn.Argument(e,null,null)]))),this._nodes.push(new sklearn.Node(this._metadata,e,t,n,s,r))}_concat(e,t){return""===e?t:`${e}/${t}`}get name(){return this._name}get groups(){return this._groups}get inputs(){return[]}get outputs(){return[]}get nodes(){return this._nodes}},sklearn.Parameter=class{constructor(e,t){this._name=e,this._arguments=t}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},sklearn.Argument=class{constructor(e,t,n){if("string"!=typeof e)throw new sklearn.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},sklearn.Node=class{constructor(e,t,n,s,r,i){this._metadata=e,this._group=t||"",this._name=n||"",this._type=s.__module__&&s.__name__?s.__module__+"."+s.__name__:s.__name__?s.__name__:"Object",this._inputs=r,this._outputs=i,this._attributes=[],this._initializers=[];for(const t of Object.keys(s))if(!t.startsWith("_")){const n=s[t];if(n&&!Array.isArray(n)&&n===Object(n)&&sklearn.Utility.isTensor(n))this._initializers.push(new sklearn.Tensor(t,n));else{const s=e.attribute(this._type,t);this._attributes.push(new sklearn.Attribute(s,t,n))}}}get type(){return this._type}get name(){return this._name}get group(){return this._group?this._group:null}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},sklearn.Attribute=class{constructor(e,t,n){this._name=t,this._value=n,e&&(Object.prototype.hasOwnProperty.call(e,"option")&&"optional"==e.option&&null==this._value||Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible||Object.prototype.hasOwnProperty.call(e,"default")&&sklearn.Attribute._isEquivalent(e.default,this._value))&&(this._visible=!1)}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}static _isEquivalent(e,t){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!=e)return t!=t;const n=typeof e;if("function"!==n&&"object"!==n&&"object"!=typeof t)return!1;const s=toString.call(e);if(s!==toString.call(t))return!1;switch(s){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Array]":{let n=e.length;if(n!==t.length)return!1;for(;n--;)if(!sklearn.Attribute._isEquivalent(e[n],t[n]))return!1;return!0}}const r=Object.keys(e);let i=r.length;if(Object.keys(t).length!=i)return!1;for(;i--;){const n=r[i];if(!Object.prototype.hasOwnProperty.call(t,n)||!sklearn.Attribute._isEquivalent(e[n],t[n]))return!1}return!0}},sklearn.Tensor=class{constructor(e,t){if(this._name=e,!sklearn.Utility.isTensor(t)){const e=[t.__module__,t.__name__].join(".");throw new sklearn.Error("Unknown tensor type '"+e+"'.")}this._kind="Array",this._type=new sklearn.TensorType(t.dtype.name,new sklearn.TensorShape(t.shape)),this._data=t.data}get name(){return this._name}get type(){return this._type}get kind(){return this._kind}get state(){return this._context().state||null}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);switch(this._type.dataType){case"int64":case"uint64":return sklearn.Tensor._stringify(t,""," ")}return JSON.stringify(t,null,4)}_context(){const e={index:0,count:0,state:null};if(!this._type)return e.state="Tensor has no data type.",e;if(!this._data)return e.state="Tensor is data is empty.",e;switch(e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,e.dataType){case"float32":case"float64":case"int32":case"uint32":case"int64":case"uint64":e.rawData=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:return e.state="Tensor data type '"+e.dataType+"' is not implemented.",e}return e}_decode(e,t){const n=[],s=e.dimensions[t];if(t==e.dimensions.length-1)for(let t=0;te.limit)return n.push("..."),n;switch(e.dataType){case"float32":n.push(e.rawData.getFloat32(e.index,!0)),e.index+=4,e.count++;break;case"float64":n.push(e.rawData.getFloat64(e.index,!0)),e.index+=8,e.count++;break;case"int32":n.push(e.rawData.getInt32(e.index,!0)),e.index+=4,e.count++;break;case"uint32":n.push(e.rawData.getUint32(e.index,!0)),e.index+=4,e.count++;break;case"int64":n.push(new long.Long(e.rawData.getUint32(e.index,!0),e.rawData.getUint32(e.index+4,!0),!1)),e.index+=8,e.count++;break;case"uint64":n.push(new long.Long(e.rawData.getUint32(e.index,!0),e.rawData.getUint32(e.index+4,!0),!0)),e.index+=8,e.count++}}else for(let r=0;re.limit)return n.push("..."),n;n.push(this._decode(e,t+1))}return n}static _stringify(e,t,n){if(Array.isArray(e)){const s=[];s.push("[");const r=e.map((e=>sklearn.Tensor._stringify(e,t+n,n)));return r.length>0&&s.push(r.join(",\n")),s.push("]"),s.join("\n")}return t+e.toString()}},sklearn.TensorType=class{constructor(e,t){this._dataType=e,this._shape=t}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},sklearn.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((e=>e.toString())).join(",")+"]":""}},sklearn.Metadata=class{static open(e){return sklearn.Metadata._metadata?Promise.resolve(sklearn.Metadata._metadata):e.request(null,"sklearn-metadata.json","utf-8").then((e=>(sklearn.Metadata._metadata=new sklearn.Metadata(e),sklearn.Metadata._metadata))).catch((()=>(sklearn.Metadata._metadata=new sklearn.Metadata(null),sklearn.Metadata._metadata)))}constructor(e){if(this._map=new Map,this._attributeCache=new Map,e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.get(e)}attribute(e,t){const n=e+":"+t;if(!this._attributeCache.has(n)){const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const n of t.attributes)this._attributeCache.set(e+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},sklearn.Container=class{constructor(e,t,n){e.length>0&&120==e[0]&&(e=(new zip.Inflater).inflate(e));const s=new t.Unpickler(e),r={},i={};r["numpy.dtype"]=function(e,t,n){switch(e){case"i1":this.name="int8",this.itemsize=1;break;case"i2":this.name="int16",this.itemsize=2;break;case"i4":this.name="int32",this.itemsize=4;break;case"i8":this.name="int64",this.itemsize=8;break;case"u1":this.name="uint8",this.itemsize=1;break;case"u2":this.name="uint16",this.itemsize=2;break;case"u4":this.name="uint32",this.itemsize=4;break;case"u8":this.name="uint64",this.itemsize=8;break;case"f2":this.name="float16",this.itemsize=2;break;case"f4":this.name="float32",this.itemsize=4;break;case"f8":this.name="float64",this.itemsize=8;break;case"b1":this.name="int8",this.itemsize=1;break;default:if(e.startsWith("V"))this.itemsize=Number(e.substring(1)),this.name="void"+(8*this.itemsize).toString();else if(e.startsWith("O"))this.itemsize=Number(e.substring(1)),this.name="object";else if(e.startsWith("S"))this.itemsize=Number(e.substring(1)),this.name="string";else if(e.startsWith("U"))this.itemsize=Number(e.substring(1)),this.name="string";else{if(!e.startsWith("M"))throw new sklearn.Error("Unknown dtype '"+e.toString()+"'.");this.itemsize=Number(e.substring(1)),this.name="datetime"}}this.align=t,this.copy=n,this.__setstate__=function(e){switch(e.length){case 8:this.version=e[0],this.byteorder=e[1],this.subarray=e[2],this.names=e[3],this.fields=e[4],this.elsize=e[5],this.alignment=e[6],this.int_dtypeflags=e[7];break;default:throw new sklearn.Error("Unknown numpy.dtype setstate length '"+e.length.toString()+"'.")}}},r["numpy.core.multiarray._reconstruct"]=function(e,t,n){this.subtype=e,this.shape=t,this.dtype=n,this.__setstate__=function(e){this.version=e[0],this.shape=e[1],this.typecode=e[2],this.is_f_order=e[3],this.rawdata=e[4]},this.__read__=function(e){const t={};sklearn.Utility.applyType(t,this.subtype),t.dtype=this.typecode,t.shape=this.shape;const n=t.shape&&t.shape.length>0?t.shape.reduce(((e,t)=>e*t)):1,s=t.dtype.itemsize*n;if("string"==typeof this.rawdata){if(t.data=e.unescape(this.rawdata,s),t.data.length!=s)throw new sklearn.Error("Invalid string array data size.")}else t.data=this.rawdata;return t}},r["joblib.numpy_pickle.NumpyArrayWrapper"]=function(){this.__setstate__=function(e){this.subclass=e.subclass,this.dtype=e.dtype,this.shape=e.shape,this.order=e.order,this.allow_mmap=e.allow_mmap},this.__read__=function(e){if("object"==this.dtype.name)return e.load(l,null);{const t=this.dtype.itemsize*this.shape.reduce(((e,t)=>e*t));this.data=e.read(t)}const t={dtype:this.dtype,shape:this.shape,data:this.data};return sklearn.Utility.applyType(t,this.subclass),t}},r["gensim.models.doc2vec.Doctag"]=function(){},r["gensim.models.doc2vec.Doc2Vec"]=function(){},r["gensim.models.doc2vec.Doc2VecTrainables"]=function(){},r["gensim.models.doc2vec.Doc2VecVocab"]=function(){},r["gensim.models.fasttext.FastText"]=function(){},r["gensim.models.fasttext.FastTextTrainables"]=function(){},r["gensim.models.fasttext.FastTextVocab"]=function(){},r["gensim.models.fasttext.FastTextKeyedVectors"]=function(){},r["gensim.models.keyedvectors.Doc2VecKeyedVectors"]=function(){},r["gensim.models.keyedvectors.Vocab"]=function(){},r["gensim.models.keyedvectors.Word2VecKeyedVectors"]=function(){},r["gensim.models.phrases.Phrases"]=function(){},r["gensim.models.tfidfmodel.TfidfModel"]=function(){},r["gensim.models.word2vec.Vocab"]=function(){},r["gensim.models.word2vec.Word2Vec"]=function(){},r["lightgbm.sklearn.LGBMRegressor"]=function(){},r["lightgbm.sklearn.LGBMClassifier"]=function(){},r["lightgbm.basic.Booster"]=function(){},r["nolearn.lasagne.base.BatchIterator"]=function(){},r["nolearn.lasagne.base.Layers"]=function(){},r["nolearn.lasagne.base.NeuralNet"]=function(){},r["nolearn.lasagne.base.TrainSplit"]=function(){},r["nolearn.lasagne.handlers.PrintLayerInfo"]=function(){},r["nolearn.lasagne.handlers.PrintLog"]=function(){},r["sklearn.calibration._CalibratedClassifier"]=function(){},r["sklearn.calibration._SigmoidCalibration"]=function(){},r["sklearn.calibration.CalibratedClassifierCV​"]=function(){},r["sklearn.compose._column_transformer.ColumnTransformer"]=function(){},r["sklearn.compose._target.TransformedTargetRegressor"]=function(){},r["sklearn.cluster._dbscan.DBSCAN"]=function(){},r["sklearn.cluster._kmeans.KMeans"]=function(){},r["sklearn.decomposition._pca.PCA"]=function(){},r["sklearn.decomposition.PCA"]=function(){},r["sklearn.decomposition.pca.PCA"]=function(){},r["sklearn.decomposition._truncated_svd.TruncatedSVD"]=function(){},r["sklearn.decomposition.truncated_svd.TruncatedSVD"]=function(){},r["sklearn.discriminant_analysis.LinearDiscriminantAnalysis"]=function(){},r["sklearn.dummy.DummyClassifier"]=function(){},r["sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper"]=r["joblib.numpy_pickle.NumpyArrayWrapper"],r["sklearn.externals.joblib.numpy_pickle.NDArrayWrapper"]=function(){},r["sklearn.ensemble._bagging.BaggingClassifier"]=function(){},r["sklearn.ensemble._forest.RandomForestRegressor"]=function(){},r["sklearn.ensemble._forest.RandomForestClassifier"]=function(){},r["sklearn.ensemble._forest.ExtraTreesClassifier"]=function(){},r["sklearn.ensemble._gb_losses.BinomialDeviance"]=function(){},r["sklearn.ensemble._gb_losses.MultinomialDeviance"]=function(){},r["sklearn.ensemble._gb.GradientBoostingClassifier"]=function(){},r["sklearn.ensemble._iforest.IsolationForest"]=function(){},r["sklearn.ensemble._voting.VotingClassifier"]=function(){},r["sklearn.ensemble.forest.RandomForestClassifier"]=function(){},r["sklearn.ensemble.forest.RandomForestRegressor"]=function(){},r["sklearn.ensemble.forest.ExtraTreesClassifier"]=function(){},r["sklearn.ensemble.gradient_boosting.BinomialDeviance"]=function(){},r["sklearn.ensemble.gradient_boosting.GradientBoostingClassifier"]=function(){},r["sklearn.ensemble.gradient_boosting.LogOddsEstimator"]=function(){},r["sklearn.ensemble.gradient_boosting.MultinomialDeviance"]=function(){},r["sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator"]=function(){},r["sklearn.ensemble.weight_boosting.AdaBoostClassifier"]=function(){},r["sklearn.feature_extraction._hashing.FeatureHasher"]=function(){},r["sklearn.feature_extraction.text.CountVectorizer"]=function(){},r["sklearn.feature_extraction.text.HashingVectorizer"]=function(){},r["sklearn.feature_extraction.text.TfidfTransformer"]=function(){},r["sklearn.feature_extraction.text.TfidfVectorizer"]=function(){},r["sklearn.feature_selection._univariate_selection.SelectKBest"]=function(){},r["sklearn.feature_selection._univariate_selection.SelectPercentile"]=function(){},r["sklearn.feature_selection.univariate_selection.SelectKBest"]=function(){},r["sklearn.feature_selection.variance_threshold.VarianceThreshold"]=function(){},r["sklearn.impute._base.SimpleImputer"]=function(){},r["sklearn.impute.SimpleImputer"]=function(){},r["sklearn.linear_model._base.LinearRegression"]=function(){},r["sklearn.linear_model._coordinate_descent.ElasticNet"]=function(){},r["sklearn.linear_model.base.LinearRegression"]=function(){},r["sklearn.linear_model.sgd_fast.Hinge"]=function(){},r["sklearn.linear_model.LogisticRegression"]=function(){},r["sklearn.linear_model.logistic.LogisticRegression"]=function(){},r["sklearn.linear_model._logistic.LogisticRegression"]=function(){},r["sklearn.linear_model.LassoLars​"]=function(){},r["sklearn.linear_model.ridge.Ridge"]=function(){},r["sklearn.linear_model.sgd_fast.Log"]=function(){},r["sklearn.linear_model.stochastic_gradient.SGDClassifier"]=function(){},r["sklearn.metrics.scorer._PredictScorer"]=function(){},r["sklearn.model_selection._search.GridSearchCV"]=function(){},r["sklearn.naive_bayes.BernoulliNB"]=function(){},r["sklearn.naive_bayes.ComplementNB"]=function(){},r["sklearn.naive_bayes.GaussianNB"]=function(){},r["sklearn.naive_bayes.MultinomialNB"]=function(){},r["sklearn.neighbors.classification.KNeighborsClassifier"]=function(){},r["sklearn.neighbors.dist_metrics.newObj"]=function(){},r["sklearn.neighbors.kd_tree.newObj"]=function(){},r["sklearn.neighbors.KNeighborsClassifier"]=function(){},r["sklearn.neighbors.KNeighborsRegressor"]=function(){},r["sklearn.neighbors.regression.KNeighborsRegressor"]=function(){},r["sklearn.neighbors.unsupervised.NearestNeighbors"]=function(){},r["sklearn.neural_network._multilayer_perceptron.MLPClassifier"]=function(){},r["sklearn.neural_network._multilayer_perceptron.MLPRegressor"]=function(){},r["sklearn.neural_network._stochastic_optimizers.AdamOptimizer"]=function(){},r["sklearn.neural_network._stochastic_optimizers.SGDOptimizer"]=function(){},r["sklearn.neural_network.rbm.BernoulliRBM"]=function(){},r["sklearn.neural_network.multilayer_perceptron.MLPClassifier"]=function(){},r["sklearn.neural_network.multilayer_perceptron.MLPRegressor"]=function(){},r["sklearn.neural_network.stochastic_gradient.SGDClassifier"]=function(){},r["sklearn.pipeline.Pipeline"]=function(){},r["sklearn.pipeline.FeatureUnion"]=function(){},r["sklearn.preprocessing._data.PolynomialFeatures"]=function(){},r["sklearn.preprocessing._data.RobustScaler"]=function(){},r["sklearn.preprocessing._data.StandardScaler"]=function(){},r["sklearn.preprocessing._discretization.KBinsDiscretizer"]=function(){},r["sklearn.preprocessing._encoders.OneHotEncoder"]=function(){},r["sklearn.preprocessing._function_transformer.FunctionTransformer"]=function(){},r["sklearn.preprocessing._label.LabelBinarizer"]=function(){},r["sklearn.preprocessing._label.LabelEncoder"]=function(){},r["sklearn.preprocessing.data.Binarizer"]=function(){},r["sklearn.preprocessing.data.MaxAbsScaler"]=function(){},r["sklearn.preprocessing.data.MinMaxScaler"]=function(){},r["sklearn.preprocessing.data.Normalizer"]=function(){},r["sklearn.preprocessing.data.OneHotEncoder"]=function(){},r["sklearn.preprocessing.data.PolynomialFeatures"]=function(){},r["sklearn.preprocessing.data.PowerTransformer"]=function(){},r["sklearn.preprocessing.data.RobustScaler"]=function(){},r["sklearn.preprocessing.data.QuantileTransformer"]=function(){},r["sklearn.preprocessing.data.StandardScaler"]=function(){},r["sklearn.preprocessing.imputation.Imputer"]=function(){},r["sklearn.preprocessing.label.LabelBinarizer"]=function(){},r["sklearn.preprocessing.label.LabelEncoder"]=function(){},r["sklearn.preprocessing.label.MultiLabelBinarizer"]=function(){},r["sklearn.svm._classes.SVC"]=function(){},r["sklearn.svm.classes.LinearSVC"]=function(){},r["sklearn.svm.classes.SVC"]=function(){},r["sklearn.svm.classes.SVR"]=function(){},r["sklearn.tree._classes.DecisionTreeClassifier"]=function(){},r["sklearn.tree._classes.DecisionTreeRegressor"]=function(){},r["sklearn.tree._classes.ExtraTreeClassifier"]=function(){},r["sklearn.tree._classes.ExtraTreeRegressor"]=function(){},r["sklearn.tree._tree.Tree"]=function(e,t,n){this.n_features=e,this.n_classes=t,this.n_outputs=n,this.__setstate__=function(e){this.max_depth=e.max_depth,this.node_count=e.node_count,this.nodes=e.nodes,this.values=e.values}},r["sklearn.tree.tree.DecisionTreeClassifier"]=function(){},r["sklearn.tree.tree.DecisionTreeRegressor"]=function(){},r["sklearn.tree.tree.ExtraTreeClassifier"]=function(){},r["sklearn.utils.deprecation.DeprecationDict"]=function(){},r["xgboost.compat.XGBoostLabelEncoder"]=function(){},r["xgboost.core.Booster"]=function(){},r["xgboost.sklearn.XGBClassifier"]=function(){},r["xgboost.sklearn.XGBRegressor"]=function(){},i["copy_reg._reconstructor"]=function(e,t,n){if("__builtin__.object"==t){const t={};return sklearn.Utility.applyType(t,e),t}if("__builtin__.tuple"==t)return n;throw new sklearn.Error("Unknown base type '"+t+"'.")},i["numpy.core.multiarray.scalar"]=function(e,t){let n=t;if("string"==typeof t||t instanceof String){n=new Uint8Array(t.length);for(let e=0;e{const s=i[e];if(s)return s.apply(null,t);const l={};sklearn.Utility.applyType(l,e);const c=r[e];return c?c.apply(l,t):e&&!a.has(e)&&(a.add(e),o.has(e.split(".").shift())&&n(new sklearn.Error("Unknown function '"+e+"'."),!1)),l};this._data=s.load(l,null),this._data&&(this._weights=function(e){for(const t of e)if(t&&!Array.isArray(t)){const e=new Map;for(const n in t){const s=t[n];if("weight_order"!=n&&"lr"!=n){if(!n||!sklearn.Utility.isTensor(s))return null;e.set(n,s)}}return e}for(const t of e)if(t&&Array.isArray(t)){const e=new Map;for(let n=0;n=148&&t<156?32:r[t];this._name=t.string(100),t.string(8),t.string(8),t.string(8);const s=parseInt(t.string(12).trim(),8);t.string(12);const i=parseInt(t.string(8).trim(),8);if(isNaN(i)||e!=i)throw new tar.Error("Invalid tar archive.");t.string(1),t.string(100),t.bytes(255),this._data=t.bytes(s),t.bytes(s%512!=0?512-s%512:0)}get name(){return this._name}get data(){return this._data}},tar.Reader=class{constructor(t){this._buffer=t,this._position=0,this._end=t.length}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new tar.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}peek(){return this._positiont==r)))&&(this._position+=t,!0)}bytes(t){const r=this._position;return this.skip(t),this._buffer.subarray(r,this._position)}string(t){const r=this.bytes(t);let e=0,s="";for(let i=0;i4&&(i[0]|i[1]<<8)<4)return!0}return!1}open(t,i){return tengine.Metadata.open(i).then((i=>{const e=t.identifier.toLowerCase();try{const e=t.buffer,s=e[0]|e[1]<<8,n=e[2]|e[3]<<8;if(2!==s)throw new tengine.Error("Unsupported format version 'v"+s.toString()+"."+n.toString()+"'.");return new tengine.Model(i,e)}catch(t){const i=t&&t.message?t.message:t.toString();throw new tengine.Error(i.replace(/\.$/,"")+" in '"+e+"'.")}}))}},tengine.Model=class{constructor(t,i){const e=new tengine.ModelFileReader(i);this._version=e.version,this._source=e.source,this._graphs=e.graphs.map((i=>new tengine.Graph(t,i)))}get format(){return"Tengine v"+this._version}get source(){return this._source}get graphs(){return this._graphs}},tengine.Graph=class{constructor(t,i){this._name=i.id.toString(),this._inputs=[],this._outputs=[],this._nodes=[];const e=i.tensors.map((t=>new tengine.Argument(t)));for(const t of i.inputs){const i=e[t];this._inputs.push(new tengine.Parameter(i.name,!0,[i]))}for(const t of i.outputs){const i=e[t];i.type&&i.type.shape&&i.type.shape.dimensions&&0==i.type.shape.dimensions.length&&null!==i.initializer||this._outputs.push(new tengine.Parameter(i.name,!0,[i]))}for(const s of i.nodes)"INPUT"!==s.type&&this._nodes.push(new tengine.Node(t,s,e))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},tengine.Parameter=class{constructor(t,i,e){this._name=t,this._visible=i,this._arguments=e}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},tengine.Argument=class{constructor(t){this._name=t.name,this._type=new tengine.TensorType(t.dataType,new tengine.TensorShape(t.dims)),this._initializer=2===t.type?new tengine.Tensor(this._type,t.buffer):null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get quantization(){return null}get initializer(){return this._initializer}},tengine.Node=class{constructor(t,i,e){this._metadata=t,this._name=i.name,this._type=i.type+(i.version&&1!==i.version?":"+i.version.toString():""),this._inputs=[],this._outputs=[],this._attributes=[];const s=t.type(this._type);for(let t=0;t""!=i||"optional"!=t.option)).map((t=>e[t]));this._inputs.push(new tengine.Parameter(t.name,!0,s)),a+=i}}else this._inputs=this._inputs.concat(n.slice(a).map(((t,i)=>{const s=a+i==0?"input":(a+i).toString();return new tengine.Parameter(s,!0,[e[t]])})));const r=i.outputs;let o=0;if(s&&s.outputs){for(const t of s.outputs)if(oe[t]));this._outputs.push(new tengine.Parameter(t.name,!0,s)),o+=i}}else this._outputs=this._outputs.concat(r.slice(o).map(((t,i)=>{const s=o+i==0?"output":(o+i).toString();return new tengine.Parameter(s,!0,[e[t]])})))}get type(){return this._type.split(":")[0]}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},tengine.Attribute=class{constructor(t,i,e){this._type="",this._name=i,this._value=e,t&&(this._name=t.name,t.type&&(this._type=t.type),(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1))}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},tengine.Tensor=class{constructor(t,i,e){this._type=t,this._data=i,this._kind=e}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const i=this._decode(t,0);return JSON.stringify(i,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape||this._type.shape.dimensions&&0==this._type.shape.dimensions.length)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"int8":case"uint8":case"float16":case"float32":case"int32":case"int16":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,i){const e=0==t.shape.length?[1]:t.shape,s=[],n=e[i];if(i==e.length-1)for(let i=0;it.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"int8":s.push(t.data.getInt8(t.index,!0)),t.index+=1,t.count++;break;case"uint8":s.push(t.data.getUint8(t.index,!0)),t.index+=1,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int16":s.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++}}else for(let e=0;et.limit)return s.push("..."),s;s.push(this._decode(t,i+1))}return 0==t.shape.length?s[0]:s}},tengine.TensorType=class{constructor(t,i){switch(t){case 0:this._dataType="float32";break;case 1:this._dataType="float16";break;case 2:this._dataType="int8";break;case 3:this._dataType="uint8";break;case 4:this._dataType="int32";break;case 5:this._dataType="int16";break;default:throw new tengine.Error("Unknown data type'"+t+"'.")}this._shape=i}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},tengine.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},tengine.Metadata=class{static open(t){return tengine.Metadata._metadata?Promise.resolve(tengine.Metadata._metadata):t.request(null,"tengine-metadata.json","utf-8").then((t=>(tengine.Metadata._metadata=new tengine.Metadata(t),tengine.Metadata._metadata))).catch((()=>(tengine.Metadata._metadata=new tengine.Metadata(null),tengine.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const i=JSON.parse(t);if(i)for(const t of i)if(t.name&&t.schema){t.schema.name=t.name;const i=t.name+(t.version&&1!==t.version?":"+t.version.toString():"");this._map[i]=t.schema}}}type(t){return this._map[t]||null}attribute(t,i){let e=this._attributeCache[t];if(!e){e={};const i=this.type(t);if(i&&i.attributes&&i.attributes.length>0)for(const t of i.attributes)e[t.name]=t;this._attributeCache[t]=e}return e[i]||null}},tengine.ModelFileReader=class{constructor(t){const i=new Map,e=(t,e,s,n)=>{i.set(t.toString()+":"+e.toString(),{name:s,params:n})};e(0,1,"Accuracy",[]),e(1,1,"BatchNormalization",["f","f","i"]),e(2,1,"BilinearResize",["f","f","i"]),e(3,1,"Concat",["i"]),e(4,1,"Const",[]),e(5,1,"Convolution",["i","i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(6,1,"DeConvolution",["i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(7,1,"DetectionOutput",["i","i","i","f","f"]),e(8,1,"DropOut",[]),e(9,1,"Eltwise",["i","i"]),e(10,1,"Flatten",["i"]),e(11,1,"FullyConnected",["i"]),e(12,1,"INPUT",[]),e(13,1,"LRN",["i","f","f","i","f"]),e(14,1,"Normalize",["i","i"]),e(15,1,"Permute",["i","i","i","i","i"]),e(16,1,"Pooling",["i","i","i","i","i","i","i","i","i","i","i"]),e(17,1,"Prelu",[]),e(18,1,"PriorBox",["f[]","f[]","f[]","f[]","i","i","i","i","i","f","f","f","i","i"]),e(19,1,"Region",["i","i","i","i","f","f","f[]"]),e(20,1,"ReLU",["f"]),e(21,1,"ReLU6",[]),e(22,1,"Reorg",["i"]),e(23,1,"Reshape",["i","i","i","i","i","i"]),e(23,2,"Reshape",["i","i","i[]"]),e(24,1,"RoiPooling",["i","i","f"]),e(25,1,"RPN",["f[]","f[]","i","i","i","i","i","f","anchors"]),e(26,1,"Scale",["i","i","i"]),e(27,1,"Slice",["i","i[]","i[]","i[]","i","i","i","i","i"]),e(28,1,"SoftMax",["i"]),e(29,1,"Split",["i","i","boolean","boolean","i[]"]),e(30,1,"DetectionPostProcess",["i","i","f","f","i","f[]"]),e(31,1,"Gemm",["f","f","i","i"]),e(32,1,"Generic",["i","i","string"]),e(33,1,"Logistic",[]),e(34,1,"LSTM",["f","f","i","i","i","i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(35,1,"RNN",["f","i","i","i","i","i","i","i","i","i"]),e(36,1,"TanH",[]),e(37,1,"Sigmoid",[]),e(38,1,"Squeeze",["i","i","i","i"]),e(39,1,"FusedbnScaleRelu",[]),e(40,1,"Pad",["i","i","i","i","i","i","i","i","i","f"]),e(41,1,"StridedSlice",["i","i","i","i","i","i","i","i","i","i","i","i"]),e(42,1,"ArgMax",["i"]),e(43,1,"ArgMin",["i"]),e(44,1,"TopKV2",["i","i"]),e(45,1,"Reduction",["i","i","i","i","i","i"]),e(46,1,"Max",[]),e(47,1,"Min",[]),e(48,1,"GRU",["f","i","i","i","i","i","i","i","i","i"]),e(49,1,"Addn","i"),e(50,1,"SwapAxis",["i","i"]),e(51,1,"Upsample",["f"]),e(52,1,"SpaceToBatchND",["i","i","i","i","i","i"]),e(53,1,"BatchToSpaceND",["i","i","i","i","i","i"]),e(54,1,"Resize",["f","f","i"]),e(55,1,"ShuffleChannel",["i"]),e(56,1,"Crop",["i","i","i","i","i","i","boolean","i","i"]),e(57,1,"ROIAlign",["i","i","f"]),e(58,1,"Psroipooling",["i","i","f","i"]),e(59,1,"Unary",["i"]),e(60,1,"Expanddims",["i"]),e(61,1,"Bias",["i"]),e(62,1,"Noop",[]),e(63,1,"Threshold",["f"]),e(64,1,"Hardsigmoid",["f","f"]),e(65,1,"Embed",["f","f","f","f"]),e(66,1,"InstanceNorm",["f"]),e(67,1,"MVN",["i","i","f"]),e(68,1,"Absval",[]),e(69,1,"Cast",["i","i"]),e(70,1,"HardSwish",["f","f"]),e(71,1,"Interp",["i","i","f","f","i"]),e(72,1,"SELU",["f","f"]),e(73,1,"ELU",["f"]),e(74,1,"BroadMul",[]),e(75,1,"Logical",["i"]),e(76,1,"Gather",["i","i"]),e(77,1,"Transpose",["i[]"]),e(78,1,"Comparison",["i"]),e(79,1,"SpaceToDepth",["i"]),e(80,1,"DepthToSpace",["i"]),e(81,1,"Reverse",[]),e(82,1,"SparseToDense",["i","i","i"]),e(83,1,"Ceil",[]),e(84,1,"SquaredDifference",[]),e(85,1,"Round",[]),e(86,1,"ZerosLike",[]),e(87,1,"Clip",["f","f"]),e(88,1,"MatMul",[]),e(89,1,"ReduceL2",["i","i"]),e(90,1,"Unsqueeze",["i[]"]),e(91,1,"Num",[]);const s=new tengine.BinaryReader(t);this._majorVersion=s.uint16(),this._minorVersion=s.uint16(),this._compileVersion=s.uint16(),s.skip(2),s.seek(s.uint32()),this._originalFormat=s.int32(),this._subFormat=s.int32(),this._graphs=[];const n=s.uint32s();for(const t of n){s.seek(t);const e={};e.id=s.int32(),e.graphLayout=s.int32(),e.originalLayout=s.int32(),e.inputs=s.uint32s(),e.outputs=s.uint32s();const n=s.uint32s(),a=s.uint32s(),r=s.uint32s();e.name=s.string(),e.nodes=[],e.tensors=[],this._graphs.push(e);for(const t of n){s.seek(t);const n={};n.id=s.int32(),n.inputs=s.uint32s(),n.outputs=s.uint32s();const a=s.int32();n.name=s.string();const r=s.uint32s();n.dynamicShape=!!s.boolean(),s.seek(a),n.version=s.int32();const o=s.int32(),h=s.uint32(),u=o.toString()+":"+n.version.toString(),p=i.has(u)?i.get(u):null;n.type=p?p.name:o.toString();const c=p?p.params:[];if(n.params=[],h){s.seek(h);for(const t of c)switch("boolean"!==t&&s.align(4),t){case"i":n.params.push(s.int32());break;case"f":n.params.push(s.float32());break;case"i[]":n.params.push(s.int32s());break;case"f[]":n.params.push(s.float32s());break;case"boolean":n.params.push(s.boolean());break;case"string":n.params.push(s.string());break;case"anchors":n.params.push(s.anchors(4));break;default:throw new tengine.Error("Unsupported param type '"+t+"' in '"+n.type+"'.")}}"Slice"===n.type&&(n.params[6]=5==this._originalFormat?n.params[6]:0),n.attributes=[];for(const t of r){s.seek(t);const i=s.string(),e=s.string(),a=s.int32();n.attributes.push({name:i,value:e,type:a})}"Const"!==n.type&&e.nodes.push(n)}const o=[];for(const t of r){s.seek(t);const i=s.uint32();s.seek(s.int32()),o.push(s.bytes(i))}for(const t of a){s.seek(t);const i={};i.id=s.int32(),i.buffer=o[s.int32()],i.dims=s.int32s(),i.name=s.string();const n=s.int32();i.layout=s.int32(),i.type=s.int32(),i.dataType=s.int32(),n&&(s.seek(n),i.quantparams={zeroPoint:s.int32(),scale:s.float32(),width:s.int32()}),e.tensors.push(i)}for(const t of e.nodes)if("Convolution"===t.type)switch(e.graphLayout){case 0:t.params[6]=e.tensors[t.inputs[1]].dims[1];break;case 1:t.params[6]=e.tensors[t.inputs[1]].dims[3]}}}get version(){return this._majorVersion+"."+this._minorVersion}get source(){switch(this._originalFormat){case 0:return"";case 1:return"Tengine";case 2:return"Caffe";case 3:return"ONNX";case 4:return"MXNet";case 5:return"TensorFlow";case 6:return"TensorFlow Lite";case 7:return"Darknet";case 8:return"DLA v"+this._subFormat;default:throw new tengine.Error("Unknown source '"+this._originalFormat.toString()+"'.")}}get graphs(){return this._graphs}},tengine.BinaryReader=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0}seek(t){if(this._position=t,this._position>this._buffer.length)throw new tengine.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new tengine.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}align(t){this._position%t!=0&&this.skip(t-this._position%t)}bytes(t){const i=this._position;return this.skip(t),this._buffer.slice(i,this._position)}byte(){return this.skip(1),this._dataView.getUint8(this._position)}boolean(){return 0==this.byte()}uint16(){const t=this._position;return this.skip(2),this._dataView.getUint16(t,!0)}uint32(){const t=this._position;return this.skip(4),this._dataView.getUint32(t,!0)}uint32s(){const t=[],i=this.uint32();if(i){const e=this._position;this.seek(i);const s=this.uint32();for(let i=0;i [nan nan 0. 0.62236255 5.9914584 9.903487 inf]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic cosine of x element-wise."}},{"name":"Add","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"*NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x + y element-wise."}},{"name":"AddManySparseToTensorsMap","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` created by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` created by this op.\nIf blank, the new Operation's unique name is used.","name":"shared_name","type":"string"}],"description":"A `SparseTensor` of rank `R` is represented by three tensors: `sparse_indices`,\n`sparse_values`, and `sparse_shape`, where\n\n```sparse_indices.shape[1] == sparse_shape.shape[0] == R```\n\nAn `N`-minibatch of `SparseTensor` objects is represented as a `SparseTensor`\nhaving a first `sparse_indices` column taking values between `[0, N)`, where\nthe minibatch size `N == sparse_shape[0]`.\n\nThe input `SparseTensor` must have rank `R` greater than 1, and the first\ndimension is treated as the minibatch dimension. Elements of the `SparseTensor`\nmust be sorted in increasing order of this first dimension. The stored\n`SparseTensor` objects pointed to by each row of the output `sparse_handles`\nwill have rank `R-1`.\n\nThe `SparseTensor` values can then be read out as part of a minibatch by passing\nthe given keys as vector elements to `TakeManySparseFromTensorsMap`. To ensure\nthe correct `SparseTensorsMap` is accessed, ensure that the same\n`container` and `shared_name` are passed to that Op. If no `shared_name`\nis provided here, instead use the *name* of the Operation created by calling\n`AddManySparseToTensorsMap` as the `shared_name` passed to\n`TakeManySparseFromTensorsMap`. Ensure the Operations are colocated.","inputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.\n`sparse_indices[:, 0]` must be ordered values in `[0, N)`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.\nThe minibatch size `N == sparse_shape[0]`.","name":"sparse_shape","type":9}],"outputs":[{"description":"1-D. The handles of the `SparseTensor` now stored in the\n`SparseTensorsMap`. Shape: `[N]`.","name":"sparse_handles","type":9}],"summary":"Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles."}},{"name":"AddN","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `variant`.","name":"T","type":"type"}],"description":" Inputs must be of same size and shape.\n\n ```python\n x = [9, 7, 10]\n tf.math.add_n(x) ==> 26\n ```","inputs":[{"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"sum","typeAttr":"T"}],"summary":"Add all input tensors element wise."}},{"name":"AddSparseToTensorsMap","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` created by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` created by this op.\nIf blank, the new Operation's unique name is used.","name":"shared_name","type":"string"}],"description":"A `SparseTensor` is represented by three tensors: `sparse_indices`,\n`sparse_values`, and `sparse_shape`.\n\nThis operator takes the given `SparseTensor` and adds it to a container\nobject (a `SparseTensorsMap`). A unique key within this container is generated\nin the form of an `int64`, and this is the value that is returned.\n\nThe `SparseTensor` can then be read out as part of a minibatch by passing\nthe key as a vector element to `TakeManySparseFromTensorsMap`. To ensure\nthe correct `SparseTensorsMap` is accessed, ensure that the same\n`container` and `shared_name` are passed to that Op. If no `shared_name`\nis provided here, instead use the *name* of the Operation created by calling\n`AddSparseToTensorsMap` as the `shared_name` passed to\n`TakeManySparseFromTensorsMap`. Ensure the Operations are colocated.","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"description":"0-D. The handle of the `SparseTensor` now stored in the\n`SparseTensorsMap`.","name":"sparse_handle","type":9}],"summary":"Add a `SparseTensor` to a `SparseTensorsMap` return its handle."}},{"name":"AddV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x + y element-wise."}},{"name":"AdjustContrast","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"images","typeAttr":"T"},{"name":"contrast_factor","type":1},{"name":"min_value","type":1},{"name":"max_value","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Deprecated. Disallowed in GraphDef version >= 2."}},{"name":"AdjustContrastv2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last 3 dimensions are\ninterpreted as `[height, width, channels]`. The other dimensions only\nrepresent a collection of images, such as `[batch, height, width, channels].`\n\nContrast is adjusted independently for each channel of each image.\n\nFor each channel, the Op first computes the mean of the image pixels in the\nchannel and then adjusts each component of each pixel to\n`(x - mean) * contrast_factor + mean`.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float multiplier for adjusting contrast.","name":"contrast_factor","type":1}],"outputs":[{"description":"The contrast-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the contrast of one or more images."}},{"name":"AdjustHue","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last dimension is\ninterpreted as channels, and must be three.\n\nThe input image is considered in the RGB colorspace. Conceptually, the RGB\ncolors are first mapped into HSV. A delta is then applied all the hue values,\nand then remapped back to RGB colorspace.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float delta to add to the hue.","name":"delta","type":1}],"outputs":[{"description":"The hue-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the hue of one or more images."}},{"name":"AdjustSaturation","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last dimension is\ninterpreted as channels, and must be three.\n\nThe input image is considered in the RGB colorspace. Conceptually, the RGB\ncolors are first mapped into HSV. A scale is then applied all the saturation\nvalues, and then remapped back to RGB colorspace.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float scale to add to the saturation.","name":"scale","type":1}],"outputs":[{"description":"The hue-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the saturation of one or more images."}},{"name":"All","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","type":10},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","type":10}],"summary":"Computes the \"logical and\" of elements across dimensions of a tensor."}},{"name":"AllCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to produce.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"AllToAll","schema":{"attributes":[{"description":"The type of elements to be exchanged. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"description":"The dimension number to concatenate.","name":"concat_dimension","type":"int64"},{"description":"The dimension number to split.","name":"split_dimension","type":"int64"},{"description":"The number of splits, this number must equal to the sub-group\nsize(group_assignment.get_shape()[1])","name":"split_count","type":"int64"}],"description":"On each replica, the input is split into `split_count` blocks along\n`split_dimension` and send to the other replicas given group_assignment. After\nreceiving `split_count` - 1 blocks from other replicas, we concatenate the\nblocks along `concat_dimension` as the output.\n\nFor example, suppose there are 2 TPU replicas:\nreplica 0 receives input: `[[A, B]]`\nreplica 1 receives input: `[[C, D]]`\n\ngroup_assignment=`[[0, 1]]`\nconcat_dimension=0\nsplit_dimension=1\nsplit_count=2\n\nreplica 0's output: `[[A], [C]]`\nreplica 1's output: `[[B], [D]]`","inputs":[{"description":"The local input to the sum.","name":"input","typeAttr":"T"},{"description":"An int32 tensor with shape\n[num_groups, num_replicas_per_group]. `group_assignment[i]` represents the\nreplica ids in the ith subgroup.","name":"group_assignment","type":3}],"outputs":[{"description":"The exchanged result.","name":"output","typeAttr":"T"}],"summary":"An Op to exchange data across TPU replicas."}},{"name":"Angle","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the argument of each element in `input`. All elements in\n`input` must be complex numbers of the form \\\\(a + bj\\\\), where *a*\nis the real part and *b* is the imaginary part.\n\nThe argument returned by this operation is of the form \\\\(atan2(b, a)\\\\).\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.angle(input) ==> [2.0132, 1.056]\n```\n\n@compatibility(numpy)\nEquivalent to np.angle.\n@end_compatibility","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the argument of a complex number."}},{"name":"AnonymousIterator","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\" or\n\"IteratorGetNext\" op. In contrast to Iterator, AnonymousIterator prevents\nresource sharing by name, and does not keep a reference to the resource\ncontainer.","name":"handle","type":20}],"summary":"A container for an iterator resource."}},{"name":"AnonymousIteratorV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\" or\n\"IteratorGetNext\" op. In contrast to Iterator, AnonymousIterator prevents\nresource sharing by name, and does not keep a reference to the resource\ncontainer.","name":"handle","type":20},{"description":"A variant deleter that should be passed into the op that deletes the iterator.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"AnonymousMemoryCache","schema":{"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"AnonymousMultiDeviceIterator","schema":{"attributes":[{"minimum":1,"name":"devices","type":"string[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to a multi device iterator that can be passed to a\n\"MultiDeviceIteratorGetNextFromShard\" op. In contrast to MultiDeviceIterator,\nAnonymousIterator prevents resource sharing by name, and does not keep a\nreference to the resource container.","name":"handle","type":20},{"description":"A variant deleter that should be passed into the op that deletes the iterator.","name":"deleter","type":21}],"summary":"A container for a multi device iterator resource."}},{"name":"AnonymousRandomSeedGenerator","schema":{"inputs":[{"name":"seed","type":9},{"name":"seed2","type":9}],"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"AnonymousSeedGenerator","schema":{"inputs":[{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"reshuffle","type":10}],"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"Any","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","type":10},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","type":10}],"summary":"Computes the \"logical or\" of elements across dimensions of a tensor."}},{"name":"ApplyAdaMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nv_t <- max(beta2 * v_{t-1}, abs(g))\nvariable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"v","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AdaMax algorithm."}},{"name":"ApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var, accum and update_accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum = rho() * accum + (1 - rho()) * grad.square();\nupdate = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad;\nupdate_accum = rho() * update_accum + (1 - rho()) * update.square();\nvar -= update;","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum_update","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adadelta scheme."}},{"name":"ApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_accumulator","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_squared_accumulator","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the proximal adagrad scheme."}},{"name":"ApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ApplyAdam","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, uses the nesterov update.","name":"use_nesterov","type":"boolean"}],"description":"$$lr_t := \\text{learning\\_rate} * \\sqrt{1 - beta_2^t} / (1 - beta_1^t)$$\n$$m_t := beta_1 * m_{t-1} + (1 - beta_1) * g$$\n$$v_t := beta_2 * v_{t-1} + (1 - beta_2) * g * g$$\n$$variable := variable - lr_t * m_t / (\\sqrt{v_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"v","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ApplyAddSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- (alpha + sign_decay * sign(g) *sign(m)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\n\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nmg <- rho * mg_{t-1} + (1-rho) * grad\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mg","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"accum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"grad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad * grad\nlinear += grad_with_shrinkage -\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ApplyGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' by subtracting 'alpha' * 'delta' from it."}},{"name":"ApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ApplyPowerSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"logbase","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum += grad * grad\nprox_v = var - lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' and '*accum' according to FOBOS with Adagrad learning rate."}},{"name":"ApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"prox_v = var - alpha * delta\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ApproximateEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":0.000009999999747378752,"name":"tolerance","type":"float32"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of abs(x-y) < tolerance element-wise."}},{"name":"ArgMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"Note that in case of ties the identity of the return value is not guaranteed.\n\nUsage:\n ```python\n import tensorflow as tf\n a = [1, 10, 26.9, 2.8, 166.32, 62.3]\n b = tf.math.argmax(input = a)\n c = tf.keras.backend.eval(b)\n # c = 4\n # here a[4] = 166.32 which is the largest element of a across axis 0\n ```","inputs":[{"name":"input","typeAttr":"T"},{"description":"int32 or int64, must be in the range `[-rank(input), rank(input))`.\nDescribes which dimension of the input Tensor to reduce across. For vectors,\nuse dimension = 0.","name":"dimension","typeAttr":"Tidx"}],"outputs":[{"name":"output","typeAttr":"output_type"}],"summary":"Returns the index with the largest value across dimensions of a tensor."}},{"name":"ArgMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"Note that in case of ties the identity of the return value is not guaranteed.\n\nUsage:\n ```python\n import tensorflow as tf\n a = [1, 10, 26.9, 2.8, 166.32, 62.3]\n b = tf.math.argmin(input = a)\n c = tf.keras.backend.eval(b)\n # c = 0\n # here a[0] = 1 which is the smallest element of a across axis 0\n ```","inputs":[{"name":"input","typeAttr":"T"},{"description":"int32 or int64, must be in the range `[-rank(input), rank(input))`.\nDescribes which dimension of the input Tensor to reduce across. For vectors,\nuse dimension = 0.","name":"dimension","typeAttr":"Tidx"}],"outputs":[{"name":"output","typeAttr":"output_type"}],"summary":"Returns the index with the smallest value across dimensions of a tensor."}},{"name":"AsString","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `float32`, `float64`, `bool`.","name":"T","type":"type"},{"default":-1,"description":"The post-decimal precision to use for floating point numbers.\nOnly used if precision > -1.","name":"precision","type":"int64"},{"default":false,"description":"Use scientific notation for floating point numbers.","name":"scientific","type":"boolean"},{"default":false,"description":"Use shortest representation (either scientific or standard) for\nfloating point numbers.","name":"shortest","type":"boolean"},{"default":-1,"description":"Pad pre-decimal numbers to this width.\nApplies to both floating point and integer numbers.\nOnly used if width > -1.","name":"width","type":"int64"},{"default":"","description":"The value to pad if width > -1. If empty, pads with spaces.\nAnother typical value is '0'. String cannot be longer than 1 character.","name":"fill","type":"string"}],"description":"Supports many numeric types and boolean.\n\nFor Unicode, see the\n[https://www.tensorflow.org/tutorials/representation/unicode](Working with Unicode text)\ntutorial.\n\nExamples:\n\n>>> tf.strings.as_string([3, 2])\n\n>>> tf.strings.as_string([3.1415926, 2.71828], precision=2).numpy()\narray([b'3.14', b'2.72'], dtype=object)","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":7}],"summary":"Converts each entry in the given tensor to strings."}},{"name":"Asin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The `tf.math.asin` operation returns the inverse of `tf.math.sin`, such that\nif `y = tf.math.sin(x)` then, `x = tf.math.asin(y)`.\n\n**Note**: The output of `tf.math.asin` will lie within the invertible range\nof sine, i.e [-pi/2, pi/2].\n\nFor example:\n\n```python\n# Note: [1.047, 0.785] ~= [(pi/3), (pi/4)]\nx = tf.constant([1.047, 0.785])\ny = tf.math.sin(x) # [0.8659266, 0.7068252]\n\ntf.math.asin(y) # [1.047, 0.785] = x\n```\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the trignometric inverse sine of x element-wise."}},{"name":"Asinh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes inverse hyperbolic sine\n for every element in the tensor. Both input and output has a range of\n `[-inf, inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -2, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.asinh(x) ==> [-inf -1.4436355 -0.4812118 0.8813736 1.0159732 5.991471 9.903487 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic sine of x element-wise."}},{"name":"Assert","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"},{"default":3,"description":"Print this many entries of each tensor.","name":"summarize","type":"int64"}],"description":"If `condition` evaluates to false, print the list of tensors in `data`.\n`summarize` determines how many entries of the tensors to print.","inputs":[{"description":"The condition to evaluate.","name":"condition","type":10},{"description":"The tensors to print out when condition is false.","name":"data","typeListAttr":"T"}],"summary":"Asserts that the given condition is true."}},{"name":"AssertCardinalityDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"cardinality","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"AssertNextDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"This transformation checks whether the camel-case names (i.e. \"FlatMap\", not\n\"flat_map\") of the transformations following this transformation match the list\nof names in the `transformations` argument. If there is a mismatch, the\ntransformation raises an exception.\n\nThe check occurs when iterating over the contents of the dataset, which\nmeans that the check happens *after* any static optimizations are applied\nto the dataset graph.","inputs":[{"description":"A variant tensor representing the input dataset.\n`AssertNextDataset` passes through the outputs of its input dataset.","name":"input_dataset","type":21},{"description":"A `tf.string` vector `tf.Tensor` identifying the transformations that are\nexpected to happen next.","name":"transformations","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"A transformation that asserts which transformations happen next."}},{"name":"Assign","schema":{"attributes":[{"name":"T","type":"type"},{"default":true,"description":"If true, the operation will validate that the shape\nof 'value' matches the shape of the Tensor being assigned to. If false,\n'ref' will take on the shape of 'value'.","name":"validate_shape","type":"boolean"},{"default":true,"description":"If True, the assignment will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"category":"Control","description":"This operation outputs \"ref\" after the assignment is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node. May be uninitialized.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be assigned to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been reset.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by assigning 'value' to it."}},{"name":"AssignAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the addition will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation outputs \"ref\" after the update is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be added to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been updated.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by adding 'value' to it."}},{"name":"AssignAddVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to\nsee the incremented value or a subsequent newer one.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value by which the variable will be incremented.","name":"value","typeAttr":"dtype"}],"summary":"Adds a value to the current value of a variable."}},{"name":"AssignSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation outputs \"ref\" after the update is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be subtracted to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been updated.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by subtracting 'value' from it."}},{"name":"AssignSubVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to\nsee the decremented value or a subsequent newer one.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value by which the variable will be incremented.","name":"value","typeAttr":"dtype"}],"summary":"Subtracts a value from the current value of a variable."}},{"name":"AssignVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to return\nthis value or a subsequent newer value of the variable.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value to set the new tensor to use.","name":"value","typeAttr":"dtype"}],"summary":"Assigns a new value to a variable."}},{"name":"Atan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The `tf.math.atan` operation returns the inverse of `tf.math.tan`, such that\nif `y = tf.math.tan(x)` then, `x = tf.math.atan(y)`.\n\n**Note**: The output of `tf.math.atan` will lie within the invertible range\nof tan, i.e (-pi/2, pi/2).\n\nFor example:\n\n```python\n# Note: [1.047, 0.785] ~= [(pi/3), (pi/4)]\nx = tf.constant([1.047, 0.785])\ny = tf.math.tan(x) # [1.731261, 0.99920404]\n\ntf.math.atan(y) # [1.047, 0.785] = x\n```\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the trignometric inverse tangent of x element-wise."}},{"name":"Atan2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"This is the angle \\( \\theta \\in [-\\pi, \\pi] \\) such that\n\\[ x = r \\cos(\\theta) \\]\nand\n\\[ y = r \\sin(\\theta) \\]\nwhere \\(r = \\sqrt(x^2 + y^2) \\).","inputs":[{"name":"y","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes arctangent of `y/x` element-wise, respecting signs of the arguments."}},{"name":"Atanh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes inverse hyperbolic tangent\n for every element in the tensor. Input range is `[-1,1]` and output range is\n `[-inf, inf]`. If input is `-1`, output will be `-inf` and if the\n input is `1`, output will be `inf`. Values outside the range will have\n `nan` as output.\n\n ```python\n x = tf.constant([-float(\"inf\"), -1, -0.5, 1, 0, 0.5, 10, float(\"inf\")])\n tf.math.atanh(x) ==> [nan -inf -0.54930615 inf 0. 0.54930615 nan nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic tangent of x element-wise."}},{"name":"AudioSpectrogram","schema":{"attributes":[{"description":"How wide the input window is in samples. For the highest efficiency\nthis should be a power of two, but other values are accepted.","name":"window_size","type":"int64"},{"description":"How widely apart the center of adjacent sample windows should be.","name":"stride","type":"int64"},{"default":false,"description":"Whether to return the squared magnitude or just the\nmagnitude. Using squared magnitude can avoid extra calculations.","name":"magnitude_squared","type":"boolean"}],"description":"Spectrograms are a standard way of representing audio information as a series of\nslices of frequency information, one slice for each window of time. By joining\nthese together into a sequence, they form a distinctive fingerprint of the sound\nover time.\n\nThis op expects to receive audio data as an input, stored as floats in the range\n-1 to 1, together with a window width in samples, and a stride specifying how\nfar to move the window between slices. From this it generates a three\ndimensional output. The first dimension is for the channels in the input, so a\nstereo audio input would have two here for example. The second dimension is time,\nwith successive frequency slices. The third dimension has an amplitude value for\neach frequency during that time slice.\n\nThis means the layout when converted and saved as an image is rotated 90 degrees\nclockwise from a typical spectrogram. Time is descending down the Y axis, and\nthe frequency decreases from left to right.\n\nEach value in the result represents the square root of the sum of the real and\nimaginary parts of an FFT on the current window of samples. In this way, the\nlowest dimension represents the power of each frequency in the current window,\nand adjacent windows are concatenated in the next dimension.\n\nTo get a more intuitive and visual look at what this operation does, you can run\ntensorflow/examples/wav_to_spectrogram to read in an audio file and save out the\nresulting spectrogram as a PNG image.","inputs":[{"description":"Float representation of audio data.","name":"input","type":1}],"outputs":[{"description":"3D representation of the audio frequencies as an image.","name":"spectrogram","type":1}],"summary":"Produces a visualization of audio data over time."}},{"name":"AudioSummary","schema":{"attributes":[{"description":"The sample rate of the signal in hertz.","name":"sample_rate","type":"float32"},{"default":3,"description":"Max number of batch elements to generate audio for.","minimum":1,"name":"max_outputs","type":"int64"}],"description":"The summary has up to `max_outputs` summary values containing audio. The\naudio is built from `tensor` which must be 3-D with shape `[batch_size,\nframes, channels]` or 2-D with shape `[batch_size, frames]`. The values are\nassumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_outputs` is 1, the summary value tag is '*tag*/audio'.\n* If `max_outputs` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"2-D of shape `[batch_size, frames]`.","name":"tensor","type":1}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with audio."}},{"name":"AudioSummaryV2","schema":{"attributes":[{"default":3,"description":"Max number of batch elements to generate audio for.","minimum":1,"name":"max_outputs","type":"int64"}],"description":"The summary has up to `max_outputs` summary values containing audio. The\naudio is built from `tensor` which must be 3-D with shape `[batch_size,\nframes, channels]` or 2-D with shape `[batch_size, frames]`. The values are\nassumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_outputs` is 1, the summary value tag is '*tag*/audio'.\n* If `max_outputs` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"2-D of shape `[batch_size, frames]`.","name":"tensor","type":1},{"description":"The sample rate of the signal in hertz.","name":"sample_rate","type":1}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with audio."}},{"name":"AutoShardDataset","schema":{"attributes":[{"default":0,"name":"auto_shard_policy","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that shards the input dataset by num_workers, returning a\nsharded dataset for the index-th worker. This attempts to automatically shard\na dataset by examining the Dataset graph and inserting a shard op before the\ninputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset).\n\nThis dataset will throw a NotFound error if we cannot shard the dataset\nautomatically.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of workers to distribute this dataset across.","name":"num_workers","type":9},{"description":"A scalar representing the index of the current worker out of num_workers.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shards the input dataset."}},{"name":"AvgPool","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `value`.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of `value`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Pool","description":"Each entry in `output` is the mean of the corresponding size `ksize`\nwindow in `value`.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The average pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs average pooling on the input."}},{"name":"AvgPool3D","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Each entry in `output` is the mean of the corresponding size `ksize` window in\n`value`.","inputs":[{"description":"Shape `[batch, depth, rows, cols, channels]` tensor to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The average pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs 3D average pooling on the input."}},{"name":"AvgPool3DGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input dimensions.","name":"orig_input_shape","type":3},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"The backprop for input.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of average pooling function."}},{"name":"AvgPoolGrad","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of the input.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"1-D. Shape of the original input to `avg_pool`.","name":"orig_input_shape","type":3},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t.\nthe output of `avg_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `avg_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the average pooling function."}},{"name":"BandedTriangularSolve","schema":{"attributes":[{"default":true,"name":"lower","type":"boolean"},{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"Barrier","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. Each shape must be 1 in the\nfirst dimension. The length of this attr must be the same as the length of\ncomponent_types.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The capacity of the barrier. The default capacity is MAX_INT32,\nwhich is the largest capacity of the underlying queue.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this barrier is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this barrier will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"A barrier represents a key-value map, where each key is a string, and\neach value is a tuple of tensors.\n\nAt runtime, the barrier contains 'complete' and 'incomplete'\nelements. A complete element has defined tensors for all components of\nits value tuple, and may be accessed using BarrierTakeMany. An\nincomplete element has some undefined components in its value tuple,\nand may be updated using BarrierInsertMany.","outputs":[{"description":"The handle to the barrier.","isRef":true,"name":"handle","type":7}],"summary":"Defines a barrier that persists across different graph executions."}},{"name":"BarrierClose","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the barrier's queue will be canceled. InsertMany will fail, even\nif no new key is introduced.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more new elements will be inserted in the\ngiven barrier. Subsequent InsertMany that try to introduce a new key will fail.\nSubsequent InsertMany operations that just add missing components to already\nexisting elements will continue to succeed. Subsequent TakeMany operations will\ncontinue to succeed if sufficient completed elements remain in the barrier.\nSubsequent TakeMany operations that would block will fail immediately.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"summary":"Closes the given barrier."}},{"name":"BarrierIncompleteSize","schema":{"inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of incomplete elements (i.e. those with some of their value\ncomponents not set) in the barrier.","name":"size","type":3}],"summary":"Computes the number of incomplete elements in the given barrier."}},{"name":"BarrierInsertMany","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The component of the barrier elements that is being assigned.","name":"component_index","type":"int64"}],"description":"If a key is not found in the barrier, this operation will create a new\nincomplete element. If a key is found in the barrier, and the element\nalready has a value at component_index, this operation will fail with\nINVALID_ARGUMENT, and leave the barrier in an undefined state.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7},{"description":"A one-dimensional tensor of keys, with length n.","name":"keys","type":7},{"description":"An any-dimensional tensor of values, which are associated with the\nrespective keys. The 0th dimension must have length n.","name":"values","typeAttr":"T"}],"summary":"For each key, assigns the respective value to the specified component."}},{"name":"BarrierReadySize","schema":{"inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of complete elements (i.e. those with all of their value\ncomponents set) in the barrier.","name":"size","type":3}],"summary":"Computes the number of complete elements in the given barrier."}},{"name":"BarrierTakeMany","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":false,"description":"Allow to return less than num_elements items if barrier is\nalready closed.","name":"allow_small_batch","type":"boolean"},{"default":false,"name":"wait_for_incomplete","type":"boolean"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation concatenates completed-element component tensors along\nthe 0th dimension to make a single component tensor.\n\nElements come out of the barrier when they are complete, and in the order\nin which they were placed into the barrier. The indices output provides\ninformation about the batch in which each element was originally inserted\ninto the barrier.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7},{"description":"A single-element tensor containing the number of elements to\ntake.","name":"num_elements","type":3}],"outputs":[{"description":"A one-dimensional tensor of indices, with length num_elems.\nThese indices refer to the batch in which the values were placed into the\nbarrier (starting with MIN_LONG and increasing with each BarrierInsertMany).","name":"indices","type":9},{"description":"A one-dimensional tensor of keys, with length num_elements.","name":"keys","type":7},{"description":"One any-dimensional tensor per component in a barrier element. All\nvalues have length num_elements in the 0th dimension.","name":"values","typeListAttr":"component_types"}],"summary":"Takes the given number of completed elements from a barrier."}},{"name":"Batch","schema":{"attributes":[{"name":"num_batch_threads","type":"int64"},{"name":"max_batch_size","type":"int64"},{"default":10,"name":"max_enqueued_batches","type":"int64"},{"name":"batch_timeout_micros","type":"int64"},{"default":[],"name":"allowed_batch_sizes","type":"int64[]"},{"name":"grad_timeout_micros","type":"int64"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"default":"","name":"batching_queue","type":"string"},{"minimum":1,"name":"T","type":"type[]"}],"description":"When many instances of this Op are being run concurrently with the same\ncontainer/shared_name in the same device, some will output zero-shaped Tensors\nand others will output Tensors of size up to max_batch_size.\n\nAll Tensors in in_tensors are batched together (so, for example, labels and\nfeatures should be batched with a single instance of this operation.\n\nEach invocation of batch emits an `id` scalar which will be used to identify\nthis particular invocation when doing unbatch or its gradient.\n\nEach op which emits a non-empty batch will also emit a non-empty batch_index\nTensor, which, is a [K, 3] matrix where each row contains the invocation's id,\nstart, and length of elements of each set of Tensors present in batched_tensors.\n\nBatched tensors are concatenated along the first dimension, and all tensors in\nin_tensors must have the first dimension of the same size.\n\nin_tensors: The tensors to be batched.\nnum_batch_threads: Number of scheduling threads for processing batches of work.\n Determines the number of batches processed in parallel.\nmax_batch_size: Batch sizes will never be bigger than this.\nbatch_timeout_micros: Maximum number of microseconds to wait before outputting\n an incomplete batch.\nallowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does\n nothing. Otherwise, supplies a list of batch sizes, causing the op to pad\n batches up to one of those sizes. The entries must increase monotonically, and\n the final entry must equal max_batch_size.\ngrad_timeout_micros: The timeout to use for the gradient. See Unbatch.\nbatched_tensors: Either empty tensors or a batch of concatenated Tensors.\nbatch_index: If out_tensors is non-empty, has information to invert it.\ncontainer: Controls the scope of sharing of this batch.\nid: always contains a scalar with a unique ID for this invocation of Batch.\nshared_name: Concurrently running instances of batch in the same device with the\n same container and shared_name will batch their elements together. If left\n empty, the op name will be used as the shared name.\nT: the types of tensors to be batched.","inputs":[{"name":"in_tensors","typeListAttr":"T"}],"outputs":[{"name":"batched_tensors","typeListAttr":"T"},{"name":"batch_index","type":9},{"name":"id","type":9}],"summary":"Batches all input tensors nondeterministically."}},{"name":"BatchCholesky","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchCholeskyGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"l","typeAttr":"T"},{"name":"grad","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches `batch_size` elements from `input_dataset`."}},{"name":"BatchDatasetV2","schema":{"attributes":[{"default":false,"name":"parallel_copy","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a batch.","name":"batch_size","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches `batch_size` elements from `input_dataset`."}},{"name":"BatchFFT","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFFT2D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFFT3D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFunction","schema":{"attributes":[{"name":"f","type":"function"},{"description":"Number of scheduling threads for processing batches of work.\nDetermines the number of batches processed in parallel.","name":"num_batch_threads","type":"int64"},{"description":"Batch sizes will never be bigger than this.","name":"max_batch_size","type":"int64"},{"description":"Maximum number of microseconds to wait before outputting\nan incomplete batch.","name":"batch_timeout_micros","type":"int64"},{"default":10,"description":"Maximum number of batches enqueued. Default: 10.","name":"max_enqueued_batches","type":"int64"},{"default":[],"description":"Optional list of allowed batch sizes. If left empty, does\nnothing. Otherwise, supplies a list of batch sizes, causing the op to pad\nbatches up to one of those sizes. The entries must increase monotonically.\nIf enable_large_batch_splitting is false (i.e., large-input-split is not\nenabled) the final entry must equal max_batch_size.","name":"allowed_batch_sizes","type":"int64[]"},{"default":"","description":"Controls the scope of sharing of this batch.","name":"container","type":"string"},{"default":"","description":"Concurrently running instances of batch in the same device with the\nsame container and shared_name will batch their elements together. If left\nempty, the op name will be used as the shared name.","name":"shared_name","type":"string"},{"default":"","name":"batching_queue","type":"string"},{"description":"the types of tensors to be batched.","minimum":1,"name":"Tin","type":"type[]"},{"description":"the types of the captured tensors.","minimum":0,"name":"Tcaptured","type":"type[]"},{"description":"the types of the output tensors.","minimum":1,"name":"Tout","type":"type[]"},{"default":false,"description":"input with a large size (i.e., larger than the largest value of\n`allowed_batch_sizes`) will be splitted into multiple batches with batch size.","name":"enable_large_batch_splitting","type":"boolean"}],"description":"So, for example, in the following code\n\n ```python\n\n # This input will be captured.\n y = tf.placeholder_with_default(1.0, shape=[])\n\n @tf.Defun(tf.float32)\n def computation(a):\n return tf.matmul(a, a) + y\n\n b = gen_batch_ops.batch_function(\n f=computation\n in_tensors=[a],\n captured_tensors=computation.captured_inputs,\n Tout=[o.type for o in computation.definition.signature.output_arg],\n num_batch_threads=1,\n max_batch_size=10,\n batch_timeout_micros=100000, # 100ms\n allowed_batch_sizes=[3, 10],\n batching_queue=\"\")\n\nIf more than one session.run call is simultaneously trying to compute `b`\nthe values of `a` will be gathered, non-deterministically concatenated\nalong the first axis, and only one thread will run the computation.\n\nAssumes that all arguments of the function are Tensors which will be batched\nalong their first dimension.\n\nArguments that are captured, are not batched. The session.run call which does\nthe concatenation, will use the values of the captured tensors available to it.\nTherefore, typical uses of captured tensors should involve values which remain\nunchanged across session.run calls. Inference is a good example of this.\n\nSparseTensor is not supported. The return value of the decorated function\nmust be a Tensor or a list/tuple of Tensors.","inputs":[{"description":"The tensors to be batched.","name":"in_tensors","typeListAttr":"Tin"},{"description":"The tensors which are captured in the function, and don't need\nto be batched.","name":"captured_tensors","typeListAttr":"Tcaptured"}],"outputs":[{"description":"The output tensors.","name":"out_tensors","typeListAttr":"Tout"}],"summary":"Batches all the inputs tensors to the computation done by the function."}},{"name":"BatchIFFT","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchIFFT2D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchIFFT3D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchMatMul","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":false,"description":"If `True`, adjoint the slices of `x`. Defaults to `False`.","name":"adj_x","type":"boolean"},{"default":false,"description":"If `True`, adjoint the slices of `y`. Defaults to `False`.","name":"adj_y","type":"boolean"}],"description":"Multiplies all slices of `Tensor` `x` and `y` (each slice can be\nviewed as an element of a batch), and arranges the individual results\nin a single output tensor of the same batch size. Each of the\nindividual slices can optionally be adjointed (to adjoint a matrix\nmeans to transpose and conjugate it) before multiplication by setting\nthe `adj_x` or `adj_y` flag to `True`, which are by default `False`.\n\nThe input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]`\nand `[..., r_y, c_y]`.\n\nThe output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where:\n\n r_o = c_x if adj_x else r_x\n c_o = r_y if adj_y else c_y\n\nIt is computed as:\n\n output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :])","inputs":[{"description":"2-D or higher with shape `[..., r_x, c_x]`.","name":"x","typeAttr":"T"},{"description":"2-D or higher with shape `[..., r_y, c_y]`.","name":"y","typeAttr":"T"}],"outputs":[{"description":"3-D or higher with shape `[..., r_o, c_o]`","name":"output","typeAttr":"T"}],"summary":"Multiplies slices of two tensors in batches."}},{"name":"BatchMatMulV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":false,"description":"If `True`, adjoint the slices of `x`. Defaults to `False`.","name":"adj_x","type":"boolean"},{"default":false,"description":"If `True`, adjoint the slices of `y`. Defaults to `False`.","name":"adj_y","type":"boolean"}],"description":"Multiplies all slices of `Tensor` `x` and `y` (each slice can be\nviewed as an element of a batch), and arranges the individual results\nin a single output tensor of the same batch size. Each of the\nindividual slices can optionally be adjointed (to adjoint a matrix\nmeans to transpose and conjugate it) before multiplication by setting\nthe `adj_x` or `adj_y` flag to `True`, which are by default `False`.\n\nThe input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]`\nand `[..., r_y, c_y]`.\n\nThe output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where:\n\n r_o = c_x if adj_x else r_x\n c_o = r_y if adj_y else c_y\n\nIt is computed as:\n\n output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :])\n\n*NOTE*: `BatchMatMulV2` supports broadcasting in the batch dimensions. More\nabout broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).\n","inputs":[{"description":"2-D or higher with shape `[..., r_x, c_x]`.","name":"x","typeAttr":"T"},{"description":"2-D or higher with shape `[..., r_y, c_y]`.","name":"y","typeAttr":"T"}],"outputs":[{"description":"3-D or higher with shape `[..., r_o, c_o]`","name":"output","typeAttr":"T"}],"summary":"Multiplies slices of two tensors in batches."}},{"name":"BatchMatrixBandPart","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"},{"name":"num_lower","type":9},{"name":"num_upper","type":9}],"outputs":[{"name":"band","typeAttr":"T"}]}},{"name":"BatchMatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixDiag","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixDiagPart","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"diagonal","typeAttr":"T"}]}},{"name":"BatchMatrixInverse","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSetDiag","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"},{"name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSolve","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSolveLs","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"},{"default":true,"name":"fast","type":"boolean"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"},{"name":"l2_regularizer","type":2}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixTriangularSolve","schema":{"attributes":[{"default":true,"name":"lower","type":"boolean"},{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchNormWithGlobalNormalization","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"category":"Normalization","description":"This op is deprecated. Prefer `tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"T"},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"T"},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"T"},{"description":"A 1D beta Tensor with size matching the last dimension of t.\nAn offset to be added to the normalized tensor.","name":"beta","typeAttr":"T"},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this tensor will be multiplied\nwith the normalized tensor.","name":"gamma","typeAttr":"T"}],"outputs":[{"name":"result","typeAttr":"T"}],"summary":"Batch normalization."}},{"name":"BatchNormWithGlobalNormalizationGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"description":"This op is deprecated. See `tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"T"},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"T"},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"T"},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this Tensor will be multiplied\nwith the normalized Tensor.","name":"gamma","typeAttr":"T"},{"description":"4D backprop Tensor.","name":"backprop","typeAttr":"T"}],"outputs":[{"description":"4D backprop tensor for input.","name":"dx","typeAttr":"T"},{"description":"1D backprop tensor for mean.","name":"dm","typeAttr":"T"},{"description":"1D backprop tensor for variance.","name":"dv","typeAttr":"T"},{"description":"1D backprop tensor for beta.","name":"db","typeAttr":"T"},{"description":"1D backprop tensor for gamma.","name":"dg","typeAttr":"T"}],"summary":"Gradients for batch normalization."}},{"name":"BatchSelfAdjointEig","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchSelfAdjointEigV2","schema":{"attributes":[{"default":true,"name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"e","typeAttr":"T"},{"name":"v","typeAttr":"T"}]}},{"name":"BatchSvd","schema":{"attributes":[{"default":true,"name":"compute_uv","type":"boolean"},{"default":false,"name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"s","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"v","typeAttr":"T"}]}},{"name":"BatchToSpace","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":2,"name":"block_size","type":"int64"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"This is a legacy version of the more general BatchToSpaceND.\n\nRearranges (permutes) data from batch into blocks of spatial data, followed by\ncropping. This is the reverse transformation of SpaceToBatch. More specifically,\nthis op outputs a copy of the input tensor where values from the `batch`\ndimension are moved in spatial blocks to the `height` and `width` dimensions,\nfollowed by cropping along the `height` and `width` dimensions.","inputs":[{"description":"4-D tensor with shape\n`[batch*block_size*block_size, height_pad/block_size, width_pad/block_size,\n depth]`. Note that the batch size of the input tensor must be divisible by\n`block_size * block_size`.","name":"input","typeAttr":"T"},{"description":"2-D tensor of non-negative integers with shape `[2, 2]`. It specifies\nhow many elements to crop from the intermediate result across the spatial\ndimensions as follows:\n\n crops = [[crop_top, crop_bottom], [crop_left, crop_right]]","name":"crops","typeAttr":"Tidx"}],"outputs":[{"description":"4-D with shape `[batch, height, width, depth]`, where:\n\n height = height_pad - crop_top - crop_bottom\n width = width_pad - crop_left - crop_right\n\nThe attr `block_size` must be greater than one. It indicates the block size.\n\nSome examples:\n\n(1) For the following input of shape `[4, 1, 1, 1]` and block_size of 2:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\n(2) For the following input of shape `[4, 1, 1, 3]` and block_size of 2:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 3]` and value:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[4, 2, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\nThe output tensor has shape `[1, 4, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\n(4) For the following input of shape `[8, 1, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],\n [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]\n```\n\nThe output tensor has shape `[2, 2, 4, 1]` and value:\n\n```\nx = [[[[1], [3]], [[5], [7]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```","name":"output","typeAttr":"T"}],"summary":"BatchToSpace for 4-D tensors of type T."}},{"name":"BatchToSpaceND","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tblock_shape","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tcrops","type":"type"}],"description":"This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of shape\n`block_shape + [batch]`, interleaves these blocks back into the grid defined by\nthe spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as\nthe input. The spatial dimensions of this intermediate result are then\noptionally cropped according to `crops` to produce the output. This is the\nreverse of SpaceToBatch. See below for a precise description.","inputs":[{"description":"N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`,\nwhere spatial_shape has M dimensions.","name":"input","typeAttr":"T"},{"description":"1-D with shape `[M]`, all values must be >= 1.","name":"block_shape","typeAttr":"Tblock_shape"},{"description":"2-D with shape `[M, 2]`, all values must be >= 0.\n `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input\n dimension `i + 1`, which corresponds to spatial dimension `i`. It is\n required that\n `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`.\n\nThis operation is equivalent to the following steps:\n\n1. Reshape `input` to `reshaped` of shape:\n [block_shape[0], ..., block_shape[M-1],\n batch / prod(block_shape),\n input_shape[1], ..., input_shape[N-1]]\n\n2. Permute dimensions of `reshaped` to produce `permuted` of shape\n [batch / prod(block_shape),\n\n input_shape[1], block_shape[0],\n ...,\n input_shape[M], block_shape[M-1],\n\n input_shape[M+1], ..., input_shape[N-1]]\n\n3. Reshape `permuted` to produce `reshaped_permuted` of shape\n [batch / prod(block_shape),\n\n input_shape[1] * block_shape[0],\n ...,\n input_shape[M] * block_shape[M-1],\n\n input_shape[M+1],\n ...,\n input_shape[N-1]]\n\n4. Crop the start and end of dimensions `[1, ..., M]` of\n `reshaped_permuted` according to `crops` to produce the output of shape:\n [batch / prod(block_shape),\n\n input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1],\n ...,\n input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1],\n\n input_shape[M+1], ..., input_shape[N-1]]\n\nSome examples:\n\n(1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\n(2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 3]` and value:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\nThe output tensor has shape `[1, 4, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\n(4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [2, 0]]`:\n\n```\nx = [[[[0], [1], [3]]], [[[0], [9], [11]]],\n [[[0], [2], [4]]], [[[0], [10], [12]]],\n [[[0], [5], [7]]], [[[0], [13], [15]]],\n [[[0], [6], [8]]], [[[0], [14], [16]]]]\n```\n\nThe output tensor has shape `[2, 2, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```","name":"crops","typeAttr":"Tcrops"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"BatchToSpace for N-D tensors of type T."}},{"name":"BesselI0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI0e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI1e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselJ0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselJ1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK0e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK1e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselY0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselY1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Betainc","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The regularized incomplete beta integral is defined as:\n\n\n\\\\(I_x(a, b) = \\frac{B(x; a, b)}{B(a, b)}\\\\)\n\nwhere\n\n\n\\\\(B(x; a, b) = \\int_0^x t^{a-1} (1 - t)^{b-1} dt\\\\)\n\n\nis the incomplete beta function and \\\\(B(a, b)\\\\) is the *complete*\nbeta function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"b","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the regularized incomplete beta integral \\\\(I_x(a, b)\\\\)."}},{"name":"BiasAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the bias tensor will be added to the last dimension\nof the value tensor.\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\nThe tensor will be added to \"in_channels\", the third-to-the-last\n dimension. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"}],"category":"Layer","description":"This is a special case of `tf.add` where `bias` is restricted to be 1-D.\nBroadcasting is supported, so `value` may have any number of dimensions.","inputs":[{"description":"Any number of dimensions.","name":"value","typeAttr":"T"},{"description":"1-D with size the last dimension of `value`.","name":"bias","typeAttr":"T"}],"outputs":[{"description":"Broadcasted sum of `value` and `bias`.","name":"output","typeAttr":"T"}],"summary":"Adds `bias` to `value`."}},{"name":"BiasAddGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the bias tensor will be added to the last dimension\nof the value tensor.\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\nThe tensor will be added to \"in_channels\", the third-to-the-last\n dimension. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"}],"description":"It accumulates all the values from out_backprop into the feature dimension.\nFor NHWC data format, the feature dimension is the last. For NCHW data format,\nthe feature dimension is the third-to-last.","inputs":[{"description":"Any number of dimensions.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"1-D with size the feature dimension of `out_backprop`.","name":"output","typeAttr":"T"}],"summary":"The backward operation for \"BiasAdd\" on the \"bias\" tensor."}},{"name":"BiasAddV1","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This is a deprecated version of BiasAdd and will be soon removed.\n\nThis is a special case of `tf.add` where `bias` is restricted to be 1-D.\nBroadcasting is supported, so `value` may have any number of dimensions.","inputs":[{"description":"Any number of dimensions.","name":"value","typeAttr":"T"},{"description":"1-D with size the last dimension of `value`.","name":"bias","typeAttr":"T"}],"outputs":[{"description":"Broadcasted sum of `value` and `bias`.","name":"output","typeAttr":"T"}],"summary":"Adds `bias` to `value`."}},{"name":"Bincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"int32 `Tensor`.","name":"arr","type":3},{"description":"non-negative int32 scalar `Tensor`.","name":"size","type":3},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size`. The counts or summed weights for\neach value in the range [0, size).","name":"bins","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"Bitcast","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`.","name":"T","type":"type"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`.","name":"type","type":"type"}],"description":"Given a tensor `input`, this operation returns a tensor that has the same buffer\ndata as `input` with datatype `type`.\n\nIf the input datatype `T` is larger than the output datatype `type` then the\nshape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)].\n\nIf `T` is smaller than `type`, the operator requires that the rightmost\ndimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from\n[..., sizeof(`type`)/sizeof(`T`)] to [...].\n\ntf.bitcast() and tf.cast() work differently when real dtype is casted as a complex dtype\n(e.g. tf.complex64 or tf.complex128) as tf.cast() make imaginary part 0 while tf.bitcast()\ngives module error.\nFor example,\n\nExample 1:\n\n>>> a = [1., 2., 3.]\n>>> equality_bitcast = tf.bitcast(a, tf.complex128)\nTraceback (most recent call last):\n...\nInvalidArgumentError: Cannot bitcast from 1 to 18 [Op:Bitcast]\n>>> equality_cast = tf.cast(a, tf.complex128)\n>>> print(equality_cast)\ntf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128)\n\nExample 2:\n\n>>> tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8)\n\n\nExample 3:\n\n>>> x = [1., 2., 3.]\n>>> y = [0., 2., 3.]\n>>> equality= tf.equal(x,y)\n>>> equality_cast = tf.cast(equality,tf.float32)\n>>> equality_bitcast = tf.bitcast(equality_cast,tf.uint8)\n>>> print(equality)\ntf.Tensor([False True True], shape=(3,), dtype=bool)\n>>> print(equality_cast)\ntf.Tensor([0. 1. 1.], shape=(3,), dtype=float32)\n>>> print(equality_bitcast)\ntf.Tensor(\n [[ 0 0 0 0]\n [ 0 0 128 63]\n [ 0 0 128 63]], shape=(3, 4), dtype=uint8)\n\n*NOTE*: Bitcast is implemented as a low-level cast, so machines with different\nendian orderings will give different results.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"type"}],"summary":"Bitcasts a tensor from one type to another without copying data."}},{"name":"BitwiseAnd","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are set in both `x` and `y`. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([0, 0, 3, 10], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_and(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise AND of `x` and `y`."}},{"name":"BitwiseOr","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are set in `x`, `y` or both. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([5, 5, 7, 15], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_or(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise OR of `x` and `y`."}},{"name":"BitwiseXor","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are different in `x` and `y`. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([5, 5, 4, 5], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_xor(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise XOR of `x` and `y`."}},{"name":"BlockLSTM","schema":{"attributes":[{"default":1,"description":"The forget gate bias.","name":"forget_bias","type":"float32"},{"default":3,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This is equivalent to applying LSTMBlockCell in a loop, like so:\n\n```python\nfor x1 in unpack(x):\n i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock(\n x1, cs_prev, h_prev, w, wci, wcf, wco, b)\n cs_prev = cs1\n h_prev = h1\n i.append(i1)\n cs.append(cs1)\n f.append(f1)\n o.append(o1)\n ci.append(ci1)\n co.append(co1)\n h.append(h1)\nreturn pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h)\n```","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for all the time steps."}},{"name":"BlockLSTMGrad","schema":{"attributes":[{"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of LSTMBlock.","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of x to be back-propped.","name":"x_grad","typeAttr":"T"},{"description":"The gradient of cs_prev to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The gradient of h_prev to be back-propped.","name":"h_prev_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"w_grad","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"b_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for the entire time sequence."}},{"name":"BlockLSTMGradV2","schema":{"attributes":[{"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of BlockLSTMV2.","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of x to be back-propped.","name":"x_grad","typeAttr":"T"},{"description":"The gradient of cs_prev to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The gradient of h_prev to be back-propped.","name":"h_prev_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"w_grad","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"b_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for the entire time sequence."}},{"name":"BlockLSTMV2","schema":{"attributes":[{"default":0,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This is equivalent to applying LSTMBlockCell in a loop, like so:\n\n```python\nfor x1 in unpack(x):\n i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock(\n x1, cs_prev, h_prev, w, wci, wcf, wco, b)\n cs_prev = cs1\n h_prev = h1\n i.append(i1)\n cs.append(cs1)\n f.append(f1)\n o.append(o1)\n ci.append(ci1)\n co.append(co1)\n h.append(h1)\nreturn pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h)\n\nNote that unlike LSTMBlockCell (and BlockLSTM) which uses ICFO gate layout,\nthis op uses IFCO. So in order for the following snippet to be equivalent\nall gate-related outputs should be reordered.\n```","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for all the time steps."}},{"name":"BoostedTreesAggregateStats","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated for each node, feature dimension id and bucket.","inputs":[{"description":"int32; Rank 1 Tensor containing node ids for each example, shape [batch_size].","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example.","name":"hessians","type":1},{"description":"int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]).","name":"feature","type":3}],"outputs":[{"description":"output Rank 4 Tensor (shape=[splits, feature_dimension, buckets, logits_dimension + hessian_dimension])\ncontaining accumulated stats for each node, feature dimension and bucket.","name":"stats_summary","type":1}],"summary":"Aggregates the summary of accumulated stats for the batch."}},{"name":"BoostedTreesBucketize","schema":{"attributes":[{"description":"inferred int; number of features.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that returns a list of float tensors, where each tensor represents the\nbucketized values for a single feature.","inputs":[{"description":"float; List of Rank 1 Tensor each containing float values for a single feature.","name":"float_values","numberAttr":"num_features","type":1},{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a single\nfeature.","name":"bucket_boundaries","numberAttr":"num_features","type":1}],"outputs":[{"description":"int; List of Rank 1 Tensors each containing the bucketized values for a single feature.","name":"buckets","numberAttr":"num_features","type":3}],"summary":"Bucketize each feature based on bucket boundaries."}},{"name":"BoostedTreesCalculateBestFeatureSplit","schema":{"attributes":[{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"},{"default":"inequality","description":"A string indicating if this Op should perform inequality split or equality split. Must be one of the following: `inequality`, `equality`.","name":"split_type","type":"string"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature.\nThe first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summary","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids","type":3},{"description":"A Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains","type":1},{"description":"A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds","type":3},{"description":"A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesCalculateBestFeatureSplitV2","schema":{"attributes":[{"description":"inferred from the size of `stats_summary_list`; the number of total features.","minimum":1,"name":"num_features","type":"int64"},{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A list of Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature.\nThe first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summaries_list","numberAttr":"num_features","type":1},{"description":"A Rank 1 tensor indicating if this Op should perform inequality split or equality split per feature.","name":"split_types","type":7},{"description":"Rank 1 tensor with ids for each feature. This is the real id of the feature.","name":"candidate_feature_ids","type":3},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids","type":3},{"description":"A Rank 1 tensor indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains","type":1},{"description":"A Rank 1 tensors indicating the best feature id for each node. See above for details like shapes and sizes.","name":"feature_ids","type":3},{"description":"A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds","type":3},{"description":"A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for each node. However, if no split is found, then no split information is returned for that node."}},{"name":"BoostedTreesCalculateBestGainsPerFeature","schema":{"attributes":[{"description":"the number of nodes that can be split in the whole tree. Used as a dimension of output tensors.","minimum":1,"name":"max_splits","type":"int64"},{"description":"inferred from the size of `stats_summary_list`; the number of total features.","minimum":1,"name":"num_features","type":"int64"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe length of output lists are all of the same length, `num_features`.\nThe output shapes are compatible in a way that the first dimension of all tensors of all lists are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summary_list","numberAttr":"num_features","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"An output list of Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids_list","numberAttr":"num_features","type":3},{"description":"An output list of Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains_list","numberAttr":"num_features","type":1},{"description":"An output list of Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds_list","numberAttr":"num_features","type":3},{"description":"A list of Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs_list","numberAttr":"num_features","type":1},{"description":"A list of Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs_list","numberAttr":"num_features","type":1}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesCenterBias","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20},{"description":"A tensor with shape=[logits_dimension] with mean of gradients for a first node.","name":"mean_gradients","type":1},{"description":"A tensor with shape=[logits_dimension] mean of hessians for a first node.","name":"mean_hessians","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1}],"outputs":[{"description":"Bool, whether to continue bias centering.","name":"continue_centering","type":10}],"summary":"Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering."}},{"name":"BoostedTreesCreateEnsemble","schema":{"inputs":[{"description":"Handle to the tree ensemble resource to be created.","name":"tree_ensemble_handle","type":20},{"description":"Token to use as the initial value of the resource stamp.","name":"stamp_token","type":9},{"description":"Serialized proto of the tree ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Creates a tree ensemble model and returns a handle to it."}},{"name":"BoostedTreesCreateQuantileStreamResource","schema":{"attributes":[{"default":1099511627776,"description":"int; The maximum number of data points that can be fed to the stream.","name":"max_elements","type":"int64"}],"inputs":[{"description":"resource; Handle to quantile stream resource.","name":"quantile_stream_resource_handle","type":20},{"description":"float; The required approximation error of the stream resource.","name":"epsilon","type":1},{"description":"int; The number of streams managed by the resource that shares the same epsilon.","name":"num_streams","type":9}],"summary":"Create the Resource for Quantile Streams."}},{"name":"BoostedTreesDeserializeEnsemble","schema":{"description":"ensemble.","inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20},{"description":"Token to use as the new value of the resource stamp.","name":"stamp_token","type":9},{"description":"Serialized proto of the ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Deserializes a serialized tree ensemble config and replaces current tree"}},{"name":"BoostedTreesEnsembleResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a BoostedTreesEnsembleResource"}},{"name":"BoostedTreesExampleDebugOutputs","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for constructing the protos in\nexamples_debug_outputs_serialized.","name":"logits_dimension","type":"int64"}],"description":"It traverses all the trees and computes debug metrics for individual examples,\nsuch as getting split feature ids and logits after each split along the decision\npath used to compute directional feature contributions.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Output rank 1 Tensor containing a proto serialized as a string for each example.","name":"examples_debug_outputs_serialized","type":7}],"summary":"Debugging/model interpretability outputs for each example."}},{"name":"BoostedTreesFlushQuantileSummaries","schema":{"attributes":[{"minimum":0,"name":"num_features","type":"int64"}],"description":"An op that outputs a list of quantile summaries of a quantile stream resource.\nEach summary Tensor is rank 2, containing summaries (value, weight, min_rank,\nmax_rank) for a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"name":"summaries","numberAttr":"num_features","type":1}],"summary":"Flush the quantile summaries from each quantile stream resource."}},{"name":"BoostedTreesGetEnsembleStates","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"Stamp token of the tree ensemble resource.","name":"stamp_token","type":9},{"description":"The number of trees in the tree ensemble resource.","name":"num_trees","type":3},{"description":"The number of trees that were finished successfully.","name":"num_finalized_trees","type":3},{"description":"The number of layers we attempted to build (but not necessarily succeeded).","name":"num_attempted_layers","type":3},{"description":"Rank size 2 tensor that contains start and end ids of the nodes in the latest\nlayer.","name":"last_layer_nodes_range","type":3}],"summary":"Retrieves the tree ensemble resource stamp token, number of trees and growing statistics."}},{"name":"BoostedTreesMakeQuantileSummaries","schema":{"attributes":[{"description":"int; Inferred from the size of float_values.\nThe number of float features.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that takes a list of tensors (one tensor per feature) and outputs the\nquantile summaries for each tensor.","inputs":[{"description":"float; List of Rank 1 Tensors each containing values for a single feature.","name":"float_values","numberAttr":"num_features","type":1},{"description":"float; Rank 1 Tensor with weights per instance.","name":"example_weights","type":1},{"description":"float; The required maximum approximation error.","name":"epsilon","type":1}],"outputs":[{"description":"float; List of Rank 2 Tensors each containing the quantile summary\n(value, weight, min_rank, max_rank) of a single feature.","name":"summaries","numberAttr":"num_features","type":1}],"summary":"Makes the summary of quantiles for the batch."}},{"name":"BoostedTreesMakeStatsSummary","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature.","minimum":1,"name":"num_buckets","type":"int64"},{"description":"int; inferred from the size of bucketized_features_list; the number of features.","minimum":1,"name":"num_features","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated into the corresponding node and bucket for each example.","inputs":[{"description":"int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer.","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians.","name":"hessians","type":1},{"description":"int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column).","name":"bucketized_features_list","numberAttr":"num_features","type":3}],"outputs":[{"description":"output Rank 4 Tensor (shape=[#features, #splits, #buckets, 2]) containing accumulated stats put into the corresponding node and bucket. The first index of 4th dimension refers to gradients, and the second to hessians.","name":"stats_summary","type":1}],"summary":"Makes the summary of accumulated stats for the batch."}},{"name":"BoostedTreesPredict","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for partial logits\nshape.","name":"logits_dimension","type":"int64"}],"description":"computes the logits. It is designed to be used during prediction.\nIt traverses all the trees and calculates the final score for each instance.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Output rank 2 Tensor containing logits for each example.","name":"logits","type":1}],"summary":"Runs multiple additive regression ensemble predictors on input instances and"}},{"name":"BoostedTreesQuantileStreamResourceAddSummaries","schema":{"attributes":[{"minimum":0,"name":"num_features","type":"int64"}],"description":"An op that adds a list of quantile summaries to a quantile stream resource. Each\nsummary Tensor is rank 2, containing summaries (value, weight, min_rank, max_rank)\nfor a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"string; List of Rank 2 Tensor each containing the summaries for a single feature.","name":"summaries","numberAttr":"num_features","type":1}],"summary":"Add the quantile summaries to each quantile stream resource."}},{"name":"BoostedTreesQuantileStreamResourceDeserialize","schema":{"attributes":[{"description":"inferred int; number of features to get bucket boundaries for.","minimum":1,"name":"num_streams","type":"int64"}],"description":"An op that deserializes bucket boundaries and are boundaries ready flag into current QuantileAccumulator.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a feature.","name":"bucket_boundaries","numberAttr":"num_streams","type":1}],"summary":"Deserialize bucket boundaries and ready flag into current QuantileAccumulator."}},{"name":"BoostedTreesQuantileStreamResourceFlush","schema":{"attributes":[{"default":false,"description":"bool; If True, the output will be the num_quantiles for each stream where the ith\nentry is the ith quantile of the input with an approximation error of epsilon.\nDuplicate values may be present.\nIf False, the output will be the points in the histogram that we got which roughly\ntranslates to 1/epsilon boundaries and without any duplicates.\nDefault to False.","name":"generate_quantiles","type":"boolean"}],"description":"An op that flushes the summaries for a quantile stream resource.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"int; approximate number of buckets unless using generate_quantiles.","name":"num_buckets","type":9}],"summary":"Flush the summaries for a quantile stream resource."}},{"name":"BoostedTreesQuantileStreamResourceGetBucketBoundaries","schema":{"attributes":[{"description":"inferred int; number of features to get bucket boundaries for.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that returns a list of float tensors for a quantile stream resource. Each\ntensor is Rank 1 containing bucket boundaries for a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a feature.","name":"bucket_boundaries","numberAttr":"num_features","type":1}],"summary":"Generate the bucket boundaries for each feature based on accumulated summaries."}},{"name":"BoostedTreesQuantileStreamResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a BoostedTreesQuantileStreamResource."}},{"name":"BoostedTreesSerializeEnsemble","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"Stamp token of the tree ensemble resource.","name":"stamp_token","type":9},{"description":"Serialized proto of the ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Serializes the tree ensemble to a proto."}},{"name":"BoostedTreesSparseAggregateStats","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature + 1.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated for each node, bucket and dimension id.","inputs":[{"description":"int32; Rank 1 Tensor containing node ids for each example, shape [batch_size].","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example.","name":"hessians","type":1},{"description":"int32; Rank 2 indices of feature sparse Tensors (shape=[number of sparse entries, 2]).\nNumber of sparse entries across all instances from the batch. The first value is\nthe index of the instance, the second is dimension of the feature. The second axis\ncan only have 2 values, i.e., the input dense version of Tensor can only be matrix.","name":"feature_indices","type":3},{"description":"int32; Rank 1 values of feature sparse Tensors (shape=[number of sparse entries]).\nNumber of sparse entries across all instances from the batch. The first value is\nthe index of the instance, the second is dimension of the feature.","name":"feature_values","type":3},{"description":"int32; Rank 1 dense shape of feature sparse Tensors (shape=[2]).\nThe first axis can only have 2 values, [batch_size, feature_dimension].","name":"feature_shape","type":3}],"outputs":[{"description":"int32; Rank 2 indices of summary sparse Tensors (shape=[number of non zero statistics, 4])\nThe second axis can only be 4 including node id, feature dimension, bucket id, and statistics_dimension.\nstatistics_dimension = logits_dimension + hessian_dimension.","name":"stats_summary_indices","type":3},{"description":"output Rank 1 Tensor (shape=[number of non zero statistics])","name":"stats_summary_values","type":1},{"description":"output Rank 1 Tensor (shape=[4])\nThe tensor has following 4 values: [max_splits, feature_dimension, num_buckets, statistics_dimension],\nwhere statistics_dimension = gradient_dimension + hessian_dimension. gradient_dimension\nis the same as label_dimension, i.e., the output space. hessian_dimension can be the same\nas logits dimension when diagonal hessian is used, or label_dimension^2 when full\nhessian is used.","name":"stats_summary_shape","type":3}],"summary":"Aggregates the summary of accumulated stats for the batch."}},{"name":"BoostedTreesSparseCalculateBestFeatureSplit","schema":{"attributes":[{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"},{"default":"inequality","description":"A string indicating if this Op should perform inequality split or equality split. Must be one of the following: `inequality`.","name":"split_type","type":"string"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A Rank 2 int64 tensor of dense shape [N, 4] (N specifies the number of non-zero values) for accumulated stats summary (gradient/hessian) per node per bucket for each feature. The second dimension contains node id, feature dimension, bucket id, and stats dim.\nstats dim is the sum of logits dimension and hessian dimension, hessian dimension can either be logits dimension if diagonal hessian is used, or logits dimension^2 if full hessian is used.","name":"stats_summary_indices","type":3},{"description":"A Rank 1 float tensor of dense shape [N] (N specifies the number of non-zero values), which supplies the values for each element in summary_indices.","name":"stats_summary_values","type":1},{"description":"A Rank 1 float tensor of dense shape [4], which specifies the dense shape of the sparse tensor, which is [num tree nodes, feature dimensions, num buckets, stats dim].","name":"stats_summary_shape","type":3},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensor indicating possible node ids that can be split.","name":"node_ids","type":3},{"description":"A Rank 1 tensor indicating the best gains to split each node.","name":"gains","type":1},{"description":"A Rank 1 tensor indicating the best feature dimension for each feature to split for each node.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensor indicating the bucket id to compare with (as a threshold) for split in each node.","name":"thresholds","type":3},{"description":"A Rank 2 tensor indicating the contribution of the left nodes when branching from parent nodes to the left direction by the given threshold for each feature.\nThis value will be used to make the left node value by adding to the parent node value. Second dimension size is logits dimension.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensor, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensor indicating which direction to go if data is missing.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesTrainingPredict","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for partial logits\nshape.","name":"logits_dimension","type":"int64"}],"description":"computes the update to cached logits. It is designed to be used during training.\nIt traverses the trees starting from cached tree id and cached node id and\ncalculates the updates to be pushed to the cache.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"Rank 1 Tensor containing cached tree ids which is the starting\ntree of prediction.","name":"cached_tree_ids","type":3},{"description":"Rank 1 Tensor containing cached node id which is the starting\nnode of prediction.","name":"cached_node_ids","type":3},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Rank 2 Tensor containing logits update (with respect to cached\nvalues stored) for each example.","name":"partial_logits","type":1},{"description":"Rank 1 Tensor containing new tree ids for each example.","name":"tree_ids","type":3},{"description":"Rank 1 Tensor containing new node ids in the new tree_ids.","name":"node_ids","type":3}],"summary":"Runs multiple additive regression ensemble predictors on input instances and"}},{"name":"BoostedTreesUpdateEnsemble","schema":{"attributes":[{"description":"0-No pruning, 1-Pre-pruning, 2-Post-pruning.","minimum":0,"name":"pruning_mode","type":"int64"},{"description":"Number of features that have best splits returned. INFERRED.","minimum":0,"name":"num_features","type":"int64"}],"description":"or by starting a new tree.","inputs":[{"description":"Handle to the ensemble variable.","name":"tree_ensemble_handle","type":20},{"description":"Rank 1 tensor with ids for each feature. This is the real id of\nthe feature that will be used in the split.","name":"feature_ids","type":3},{"description":"List of rank 1 tensors representing the nodes for which this feature\nhas a split.","name":"node_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the gains for each of the feature's\nsplit.","name":"gains","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the thesholds for each of the\nfeature's split.","name":"thresholds","numberAttr":"num_features","type":3},{"description":"List of rank 2 tensors with left leaf contribs for each of\nthe feature's splits. Will be added to the previous node values to constitute\nthe values of the left nodes.","name":"left_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 2 tensors with right leaf contribs for each\nof the feature's splits. Will be added to the previous node values to constitute\nthe values of the right nodes.","name":"right_node_contribs","numberAttr":"num_features","type":1},{"description":"Max depth of the tree to build.","name":"max_depth","type":3},{"description":"shrinkage const for each new tree.","name":"learning_rate","type":1}],"summary":"Updates the tree ensemble by either adding a layer to the last tree being grown"}},{"name":"BoostedTreesUpdateEnsembleV2","schema":{"attributes":[{"description":"Number of features that have best splits returned. INFERRED.","minimum":0,"name":"num_features","type":"int64"},{"default":1,"description":"scalar, dimension of the logits","name":"logits_dimension","type":"int64"},{"default":1,"description":"Number of groups of split information to process, where a group contains feature\nids that are processed together in BoostedTreesCalculateBestFeatureSplitOpV2.\nINFERRED.","minimum":1,"name":"num_groups","type":"int64"}],"description":"or by starting a new tree.","inputs":[{"description":"Handle to the ensemble variable.","name":"tree_ensemble_handle","type":20},{"description":"Rank 1 tensor with ids for each feature. This is the real id of\nthe feature that will be used in the split.","name":"feature_ids","numberAttr":"num_groups","type":3},{"description":"List of rank 1 tensors representing the dimension in each feature.","name":"dimension_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the nodes for which this feature\nhas a split.","name":"node_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the gains for each of the feature's\nsplit.","name":"gains","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the thesholds for each of the\nfeature's split.","name":"thresholds","numberAttr":"num_features","type":3},{"description":"List of rank 2 tensors with left leaf contribs for each of\nthe feature's splits. Will be added to the previous node values to constitute\nthe values of the left nodes.","name":"left_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 2 tensors with right leaf contribs for each\nof the feature's splits. Will be added to the previous node values to constitute\nthe values of the right nodes.","name":"right_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the split type for each feature.","name":"split_types","numberAttr":"num_features","type":7},{"description":"Max depth of the tree to build.","name":"max_depth","type":3},{"description":"shrinkage const for each new tree.","name":"learning_rate","type":1},{"description":"0-No pruning, 1-Pre-pruning, 2-Post-pruning.","name":"pruning_mode","type":3}],"summary":"Updates the tree ensemble by adding a layer to the last tree being grown"}},{"name":"BroadcastArgs","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the\nbroadcasted shape. `s0`, `s1` and `r0` are all integer vectors.","inputs":[{"name":"s0","typeAttr":"T"},{"name":"s1","typeAttr":"T"}],"outputs":[{"name":"r0","typeAttr":"T"}],"summary":"Return the shape of s0 op s1 with broadcast."}},{"name":"BroadcastGradientArgs","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This is typically used by gradient computations for a broadcasting operation.","inputs":[{"name":"s0","typeAttr":"T"},{"name":"s1","typeAttr":"T"}],"outputs":[{"name":"r0","typeAttr":"T"},{"name":"r1","typeAttr":"T"}],"summary":"Return the reduction indices for computing gradients of s0 op s1 with broadcast."}},{"name":"BroadcastTo","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Broadcasting is the process of making arrays to have compatible shapes\nfor arithmetic operations. Two shapes are compatible if for each\ndimension pair they are either equal or one of them is one. When trying\nto broadcast a Tensor to a shape, it starts with the trailing dimensions,\nand works its way forward.\n\nFor example,\n\n>>> x = tf.constant([1, 2, 3])\n>>> y = tf.broadcast_to(x, [3, 3])\n>>> print(y)\ntf.Tensor(\n [[1 2 3]\n [1 2 3]\n [1 2 3]], shape=(3, 3), dtype=int32)\n\nIn the above example, the input Tensor with the shape of `[1, 3]`\nis broadcasted to output Tensor with shape of `[3, 3]`.\n\nWhen doing broadcasted operations such as multiplying a tensor\nby a scalar, broadcasting (usually) confers some time or space\nbenefit, as the broadcasted tensor is never materialized.\n\nHowever, `broadcast_to` does not carry with it any such benefits.\nThe newly-created tensor takes the full memory of the broadcasted\nshape. (In a graph context, `broadcast_to` might be fused to\nsubsequent operation and then be optimized away, however.)","inputs":[{"description":"A Tensor to broadcast.","name":"input","typeAttr":"T"},{"description":"An 1-D `int` Tensor. The shape of the desired output.","name":"shape","typeAttr":"Tidx"}],"outputs":[{"description":"A Tensor.","name":"output","typeAttr":"T"}],"summary":"Broadcast an array for a compatible shape."}},{"name":"Bucketize","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"description":"A sorted list of floats gives the boundary of the buckets.","name":"boundaries","type":"float32[]"}],"description":"For example, if the inputs are\n boundaries = [0, 10, 100]\n input = [[-5, 10000]\n [150, 10]\n [5, 100]]\n\nthen the output will be\n output = [[0, 3]\n [3, 2]\n [1, 3]]","inputs":[{"description":"Any shape of Tensor contains with int or float type.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Same shape with 'input', each value of input replaced with bucket index.\n\n@compatibility(numpy)\nEquivalent to np.digitize.\n@end_compatibility","name":"output","type":3}],"summary":"Bucketizes 'input' based on 'boundaries'."}},{"name":"BytesProducedStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the bytes size of each element of `input_dataset` in a StatsAggregator."}},{"name":"CSRSparseMatrixComponents","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"This op is meant only for debugging / testing, and its interface is not expected\nto be stable.","inputs":[{"description":"A batched CSRSparseMatrix.","name":"csr_sparse_matrix","type":21},{"description":"The index in `csr_sparse_matrix`'s batch.","name":"index","type":3}],"outputs":[{"description":"An array containing CSR matrix row pointers.","name":"row_ptrs","type":3},{"description":"An array containing CSR matrix column indices.","name":"col_inds","type":3},{"description":"An array containing CSR matrix nonzero values.","name":"values","typeAttr":"type"}],"summary":"Reads out the CSR components at batch `index`."}},{"name":"CSRSparseMatrixToDense","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"A batched CSRSparseMatrix.","name":"sparse_input","type":21}],"outputs":[{"description":"A dense tensor.","name":"dense_output","typeAttr":"type"}],"summary":"Convert a (possibly batched) CSRSparseMatrix to dense."}},{"name":"CSRSparseMatrixToSparseTensor","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_matrix","type":21}],"outputs":[{"description":"SparseTensor indices.","name":"indices","type":9},{"description":"SparseTensor values.","name":"values","typeAttr":"type"},{"description":"SparseTensor dense shape.","name":"dense_shape","type":9}],"summary":"Converts a (possibly batched) CSRSparesMatrix to a SparseTensor."}},{"name":"CSVDataset","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"}],"outputs":[{"name":"handle","type":21}]}},{"name":"CSVDatasetV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"},{"name":"exclude_cols","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"CTCBeamSearchDecoder","schema":{"attributes":[{"description":"A scalar >= 0 (beam search beam width).","minimum":1,"name":"beam_width","type":"int64"},{"description":"A scalar >= 0, <= beam_width (controls output size).","minimum":1,"name":"top_paths","type":"int64"},{"default":true,"description":"If true, merge repeated classes in output.","name":"merge_repeated","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"A note about the attribute merge_repeated: For the beam search decoder,\nthis means that if consecutive entries in a beam are the same, only\nthe first of these is emitted. That is, when the top path is \"A B B B B\",\n\"A B\" is returned if merge_repeated = True but \"A B B B B\" is\nreturned if merge_repeated = False.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"A vector containing sequence lengths, size `(batch)`.","name":"sequence_length","type":3}],"outputs":[{"description":"A list (length: top_paths) of indices matrices. Matrix j,\nsize `(total_decoded_outputs[j] x 2)`, has indices of a\n`SparseTensor`. The rows store: [batch, time].","name":"decoded_indices","numberAttr":"top_paths","type":9},{"description":"A list (length: top_paths) of values vectors. Vector j,\nsize `(length total_decoded_outputs[j])`, has the values of a\n`SparseTensor`. The vector stores the decoded classes for beam j.","name":"decoded_values","numberAttr":"top_paths","type":9},{"description":"A list (length: top_paths) of shape vector. Vector j,\nsize `(2)`, stores the shape of the decoded `SparseTensor[j]`.\nIts values are: `[batch_size, max_decoded_length[j]]`.","name":"decoded_shape","numberAttr":"top_paths","type":9},{"description":"A matrix, shaped: `(batch_size x top_paths)`. The\nsequence log-probabilities.","name":"log_probability","typeAttr":"T"}],"summary":"Performs beam search decoding on the logits given in input."}},{"name":"CTCGreedyDecoder","schema":{"attributes":[{"default":false,"description":"If True, merge repeated classes in output.","name":"merge_repeated","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"A note about the attribute merge_repeated: if enabled, when\nconsecutive logits' maximum indices are the same, only the first of\nthese is emitted. Labeling the blank '*', the sequence \"A B B * B B\"\nbecomes \"A B B\" if merge_repeated = True and \"A B B B B\" if\nmerge_repeated = False.\n\nRegardless of the value of merge_repeated, if the maximum index of a given\ntime and batch corresponds to the blank, index `(num_classes - 1)`, no new\nelement is emitted.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"A vector containing sequence lengths, size `(batch_size)`.","name":"sequence_length","type":3}],"outputs":[{"description":"Indices matrix, size `(total_decoded_outputs x 2)`,\nof a `SparseTensor`. The rows store: [batch, time].","name":"decoded_indices","type":9},{"description":"Values vector, size: `(total_decoded_outputs)`,\nof a `SparseTensor`. The vector stores the decoded classes.","name":"decoded_values","type":9},{"description":"Shape vector, size `(2)`, of the decoded SparseTensor.\nValues are: `[batch_size, max_decoded_length]`.","name":"decoded_shape","type":9},{"description":"Matrix, size `(batch_size x 1)`, containing sequence\nlog-probabilities.","name":"log_probability","typeAttr":"T"}],"summary":"Performs greedy decoding on the logits given in inputs."}},{"name":"CTCLoss","schema":{"attributes":[{"default":false,"description":"Scalar, if true then repeated labels are\ncollapsed prior to the CTC calculation.","name":"preprocess_collapse_repeated","type":"boolean"},{"default":true,"description":"Scalar. If set to false, *during* CTC calculation\nrepeated non-blank labels will not be merged and are interpreted as\nindividual labels. This is a simplified version of CTC.","name":"ctc_merge_repeated","type":"boolean"},{"default":false,"description":"Scalar. If set to true, during CTC\ncalculation, items that have longer output sequences than input sequences\nare skipped: they don't contribute to the loss term and have zero-gradient.","name":"ignore_longer_outputs_than_inputs","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"the gradient. This class performs the softmax operation for you, so inputs\nshould be e.g. linear projections of outputs by an LSTM.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"The indices of a `SparseTensor`.\n`labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for\n`(batch b, time t)`.","name":"labels_indices","type":9},{"description":"The values (labels) associated with the given batch and time.","name":"labels_values","type":3},{"description":"A vector containing sequence lengths (batch).","name":"sequence_length","type":3}],"outputs":[{"description":"A vector (batch) containing log-probabilities.","name":"loss","typeAttr":"T"},{"description":"The gradient of `loss`. 3-D, shape:\n`(max_time x batch_size x num_classes)`.","name":"gradient","typeAttr":"T"}],"summary":"Calculates the CTC Loss (log probability) for each batch entry. Also calculates"}},{"name":"CTCLossV2","schema":{"attributes":[{"default":false,"description":"Scalar, if true then repeated labels are\ncollapsed prior to the CTC calculation.","name":"preprocess_collapse_repeated","type":"boolean"},{"default":true,"description":"Scalar. If set to false, *during* CTC calculation\nrepeated non-blank labels will not be merged and are interpreted as\nindividual labels. This is a simplified version of CTC.","name":"ctc_merge_repeated","type":"boolean"},{"default":false,"description":"Scalar. If set to true, during CTC\ncalculation, items that have longer output sequences than input sequences\nare skipped: they don't contribute to the loss term and have zero-gradient.","name":"ignore_longer_outputs_than_inputs","type":"boolean"}],"description":"the gradient. This class performs the softmax operation for you, so inputs\nshould be e.g. linear projections of outputs by an LSTM.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits. Default blank\nlabel is 0 rather num_classes - 1.","name":"inputs","type":1},{"description":"The indices of a `SparseTensor`.\n`labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for\n`(batch b, time t)`.","name":"labels_indices","type":9},{"description":"The values (labels) associated with the given batch and time.","name":"labels_values","type":3},{"description":"A vector containing sequence lengths (batch).","name":"sequence_length","type":3}],"outputs":[{"description":"A vector (batch) containing log-probabilities.","name":"loss","type":1},{"description":"The gradient of `loss`. 3-D, shape:\n`(max_time x batch_size x num_classes)`.","name":"gradient","type":1}],"summary":"Calculates the CTC Loss (log probability) for each batch entry. Also calculates"}},{"name":"CacheDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"A CacheDataset will iterate over the input_dataset, and store tensors. If the\ncache already exists, the cache will be used. If the cache is inappropriate\n(e.g. cannot be opened, contains tensors of the wrong shape / size), an error\nwill the returned when used.","inputs":[{"name":"input_dataset","type":21},{"description":"A path on the filesystem where we should cache the dataset. Note: this\nwill be a directory.","name":"filename","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that caches elements from `input_dataset`."}},{"name":"CacheDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"filename","type":7},{"name":"cache","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"Case","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A list of functions each of which takes 'inputs' and returns a list of\n tensors, whose types are the same as what every other branch returns.","minimum":1,"name":"branches","type":"function[]"},{"default":[],"name":"output_shapes","type":"shape[]"}],"description":" An n-way switch statement, implementing the following:\n ```\n switch (branch_index) {\n case 0:\n output = branches[0](input);\n break;\n case 1:\n output = branches[1](input);\n break;\n ...\n case [[nbranches-1]]:\n default:\n output = branches[nbranches-1](input);\n break;\n }\n ```","inputs":[{"description":"The branch selector, an int32 Tensor.","name":"branch_index","type":3},{"description":"A list of input tensors passed to the branch function.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"An n-way switch statement which calls a single branch function."}},{"name":"Cast","schema":{"attributes":[{"name":"SrcT","type":"type"},{"name":"DstT","type":"type"},{"default":false,"name":"Truncate","type":"boolean"}],"inputs":[{"name":"x","typeAttr":"SrcT"}],"outputs":[{"name":"y","typeAttr":"DstT"}],"summary":"Cast x of type SrcT to y of DstT."}},{"name":"Ceil","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise smallest integer not less than x."}},{"name":"CheckNumerics","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Prefix of the error message.","name":"message","type":"string"}],"description":"When run, reports an `InvalidArgument` error if `tensor` has any values\nthat are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is.","inputs":[{"name":"tensor","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Checks a tensor for NaN and Inf values."}},{"name":"CheckNumericsV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Prefix of the error message.","name":"message","type":"string"}],"description":"When run, reports an `InvalidArgument` error if `tensor` has any values\nthat are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is.\nUnlike CheckNumerics (V1), CheckNumericsV2 distinguishes -Inf and +Inf in the\nerrors it throws.","inputs":[{"name":"tensor","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Checks a tensor for NaN, -Inf and +Inf values."}},{"name":"Cholesky","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices.\n\nThe input has to be symmetric and positive definite. Only the lower-triangular\npart of the input will be used for this operation. The upper-triangular part\nwill not be read.\n\nThe output is a tensor of the same shape as the input\ncontaining the Cholesky decompositions for all input submatrices `[..., :, :]`.\n\n**Note**: The gradient computation on GPU is faster for large matrices but\nnot for large batch dimensions when the submatrices are small. In this\ncase it might be faster to use the CPU.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.","name":"output","typeAttr":"T"}],"summary":"Computes the Cholesky decomposition of one or more square matrices."}},{"name":"CholeskyGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"For an explanation see \"Differentiation of the Cholesky algorithm\" by\nIain Murray http://arxiv.org/abs/1602.07527.","inputs":[{"description":"Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`.\nAlgorithm depends only on lower triangular part of the innermost matrices of\nthis tensor.","name":"l","typeAttr":"T"},{"description":"df/dl where f is some scalar function. Shape is `[..., M, M]`.\nAlgorithm depends only on lower triangular part of the innermost matrices of\nthis tensor.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Symmetrized version of df/dA . Shape is `[..., M, M]`","name":"output","typeAttr":"T"}],"summary":"Computes the reverse mode backpropagated gradient of the Cholesky algorithm."}},{"name":"ChooseFastestBranchDataset","schema":{"attributes":[{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"num_elements_per_branch","type":"int64"},{"minimum":1,"name":"branches","type":"function[]"},{"minimum":1,"name":"other_arguments_lengths","type":"int64[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"ratio_numerator","type":9},{"name":"ratio_denominator","type":9},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}]}},{"name":"ChooseFastestDataset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"num_experiments","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ClipByValue","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Given a tensor `t`, this operation returns a tensor of the same type and\nshape as `t` with its values clipped to `clip_value_min` and `clip_value_max`.\nAny values less than `clip_value_min` are set to `clip_value_min`. Any values\ngreater than `clip_value_max` are set to `clip_value_max`.","inputs":[{"description":"A `Tensor`.","name":"t","typeAttr":"T"},{"description":"A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape\nas `t`. The minimum value to clip by.","name":"clip_value_min","typeAttr":"T"},{"description":"A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape\nas `t`. The maximum value to clip by.","name":"clip_value_max","typeAttr":"T"}],"outputs":[{"description":"A clipped `Tensor` with the same shape as input 't'.","name":"output","typeAttr":"T"}],"summary":"Clips tensor values to a specified min and max."}},{"name":"CloseSummaryWriter","schema":{"inputs":[{"name":"writer","type":20}]}},{"name":"CollectiveBcastRecv","schema":{"attributes":[{"description":"Must be one of the following: `bool`, `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Receives a tensor value broadcast from another device."}},{"name":"CollectiveBcastSend","schema":{"attributes":[{"description":"Must be one of the following: `bool`, `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Broadcasts a tensor value to one or more other devices."}},{"name":"CollectiveGather","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Mutually accumulates multiple tensors of identical type and shape."}},{"name":"CollectivePermute","schema":{"attributes":[{"description":"The type of elements to be exchanged. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Each instance supplies its own input.\n\nFor example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing\nsource_target_pairs=`[[0,1],[1,2],[2,3],[3,0]]` gets the outputs:\n`[D, A, B, C]`.","inputs":[{"description":"The local input to be permuted. Currently only supports float and\nbfloat16.","name":"input","typeAttr":"T"},{"description":"A tensor with shape [num_pairs, 2].","name":"source_target_pairs","type":3}],"outputs":[{"description":"The permuted input.","name":"output","typeAttr":"T"}],"summary":"An Op to permute tensors across replicated TPU instances."}},{"name":"CollectiveReduce","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"description":"Must be one of the following: `Min`, `Max`, `Mul`, `Add`.","name":"merge_op","type":"string"},{"description":"Must be one of the following: `Id`, `Div`.","name":"final_op","type":"string"},{"name":"subdiv_offsets","type":"int64[]"},{"default":[],"name":"wait_for","type":"int64[]"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Mutually reduces multiple tensors of identical type and shape."}},{"name":"CombinedNonMaxSuppression","schema":{"attributes":[{"default":false,"description":"If false, the output nmsed boxes, scores and classes\nare padded/clipped to `max_total_size`. If true, the\noutput nmsed boxes, scores and classes are padded to be of length\n`max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in\nwhich case it is clipped to `max_total_size`. Defaults to false.","name":"pad_per_class","type":"boolean"},{"default":true,"description":"If true, assume the box coordinates are between [0, 1] and clip the output boxes\nif they fall beyond [0, 1]. If false, do not do clipping and output the box\ncoordinates as it is.","name":"clip_boxes","type":"boolean"}],"description":"This operation performs non_max_suppression on the inputs per batch, across\nall classes.\nPrunes away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Also note that\nthis algorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is the final boxes, scores and classes tensor\nreturned after performing non_max_suppression.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then\nsame boxes are used for all classes otherwise, if `q` is equal to number of\nclasses, class-specific boxes are used.","name":"boxes","type":1},{"description":"A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]`\nrepresenting a single score corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression per class","name":"max_output_size_per_class","type":3},{"description":"A scalar representing maximum number of boxes retained over all classes.","name":"max_total_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","type":1},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","type":1}],"outputs":[{"description":"A [batch_size, max_detections, 4] float32 tensor\ncontaining the non-max suppressed boxes.","name":"nmsed_boxes","type":1},{"description":"A [batch_size, max_detections] float32 tensor\ncontaining the scores for the boxes.","name":"nmsed_scores","type":1},{"description":"A [batch_size, max_detections] float32 tensor\ncontaining the classes for the boxes.","name":"nmsed_classes","type":1},{"description":"A [batch_size] int32 tensor indicating the number of\nvalid detections per batch item. Only the top num_detections[i] entries in\nnms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the\nentries are zero paddings.","name":"valid_detections","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"CompareAndBitpack","schema":{"attributes":[{"description":"The type of the input and threshold. Must be one of the following: `bool`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Each comparison returns a boolean `true` (if `input_value > threshold`)\nor and `false` otherwise.\n\nThis operation is useful for Locality-Sensitive-Hashing (LSH) and other\nalgorithms that use hashing approximations of cosine and `L2` distances;\ncodes can be generated from an input via:\n\n```python\ncodebook_size = 50\ncodebook_bits = codebook_size * 32\ncodebook = tf.get_variable('codebook', [x.shape[-1].value, codebook_bits],\n dtype=x.dtype,\n initializer=tf.orthogonal_initializer())\ncodes = compare_and_threshold(tf.matmul(x, codebook), threshold=0.)\ncodes = tf.bitcast(codes, tf.int32) # go from uint8 to int32\n# now codes has shape x.shape[:-1] + [codebook_size]\n```\n\n**NOTE**: Currently, the innermost dimension of the tensor must be divisible\nby 8.\n\nGiven an `input` shaped `[s0, s1, ..., s_n]`, the output is\na `uint8` tensor shaped `[s0, s1, ..., s_n / 8]`.","inputs":[{"description":"Values to compare against `threshold` and bitpack.","name":"input","typeAttr":"T"},{"description":"Threshold to compare against.","name":"threshold","typeAttr":"T"}],"outputs":[{"description":"The bitpacked comparisons.","name":"output","type":4}],"summary":"Compare values of `input` to `threshold` and pack resulting bits into a `uint8`."}},{"name":"Complex","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tout","type":"type"}],"description":"Given a tensor `real` representing the real part of a complex number, and a\ntensor `imag` representing the imaginary part of a complex number, this\noperation returns complex numbers elementwise of the form \\\\(a + bj\\\\), where\n*a* represents the `real` part and *b* represents the `imag` part.\n\nThe input tensors `real` and `imag` must have the same shape.\n\nFor example:\n\n```\n# tensor 'real' is [2.25, 3.25]\n# tensor `imag` is [4.75, 5.75]\ntf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]]\n```","inputs":[{"name":"real","typeAttr":"T"},{"name":"imag","typeAttr":"T"}],"outputs":[{"name":"out","typeAttr":"Tout"}],"summary":"Converts two real numbers to a complex number."}},{"name":"ComplexAbs","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `x` of complex numbers, this operation returns a tensor of type\n`float` or `double` that is the absolute value of each element in `x`. All\nelements in `x` must be complex numbers of the form \\\\(a + bj\\\\). The absolute\nvalue is computed as \\\\( \\sqrt{a^2 + b^2}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"Tout"}],"summary":"Computes the complex absolute value of a tensor."}},{"name":"CompressElement","schema":{"attributes":[{"minimum":1,"name":"input_types","type":"type[]"}],"inputs":[{"name":"components","typeListAttr":"input_types"}],"outputs":[{"name":"compressed","type":21}],"summary":"Compresses a dataset element."}},{"name":"ComputeAccidentalHits","schema":{"attributes":[{"description":"Number of true labels per context.","name":"num_true","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"When doing log-odds NCE, the result of this op should be passed through a\nSparseToDense op, then added to the logits of the sampled candidates. This has\nthe effect of 'removing' the sampled labels that match the true labels by\nmaking the classifier sure that they are sampled labels.","inputs":[{"description":"The true_classes output of UnpackSparseLabels.","name":"true_classes","type":9},{"description":"The sampled_candidates output of CandidateSampler.","name":"sampled_candidates","type":9}],"outputs":[{"description":"A vector of indices corresponding to rows of true_candidates.","name":"indices","type":3},{"description":"A vector of IDs of positions in sampled_candidates that match a true_label\nfor the row with the corresponding index in indices.","name":"ids","type":9},{"description":"A vector of the same length as indices and ids, in which each element\nis -FLOAT_MAX.","name":"weights","type":1}],"summary":"Computes the ids of the positions in sampled_candidates that match true_labels."}},{"name":"ComputeBatchSize","schema":{"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"batch_size","type":9}],"summary":"Computes the static batch size of a dataset sans partial batches."}},{"name":"Concat","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"inputs":[{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [0, rank(values)).","name":"concat_dim","type":3},{"description":"The `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"}],"summary":"Concatenates tensors along one dimension."}},{"name":"ConcatOffset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"}],"description":"For example:\n\n```\n# 'x' is [2, 2, 7]\n# 'y' is [2, 3, 7]\n# 'z' is [2, 5, 7]\nconcat_offset(2, [x, y, z]) => [0, 0, 0], [0, 2, 0], [0, 5, 0]\n```\n\nThis is typically used by gradient computations for a concat operation.","inputs":[{"description":"The dimension along which to concatenate.","name":"concat_dim","type":3},{"description":"The `N` int32 vectors representing shape of tensors being concatenated.","name":"shape","numberAttr":"N","type":3}],"outputs":[{"description":"The `N` int32 vectors representing the starting offset\nof input tensors within the concatenated output.","name":"offset","numberAttr":"N","type":3}],"summary":"Computes offsets of concat inputs within its output."}},{"name":"ConcatV2","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"category":"Tensor","inputs":[{"description":"List of `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [-rank(values), rank(values)).","name":"axis","typeAttr":"Tidx"}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"}],"summary":"Concatenates tensors along one dimension."}},{"name":"ConcatenateDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"another_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that concatenates `input_dataset` with `another_dataset`."}},{"name":"ConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values, can be [], in which case shape is unknown.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the\ngiven name across multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.","outputs":[{"description":"The handle to the accumulator.","isRef":true,"name":"handle","type":7}],"summary":"A conditional accumulator for aggregating gradients."}},{"name":"ConfigureDistributedTPU","schema":{"attributes":[{"default":"","description":"Reserved. Do not use.","name":"embedding_config","type":"string"},{"default":"","description":"Serialized tensorflow.tpu.TPUEmbeddingConfiguration that\ndescribes the embedding lookups of the program.","name":"tpu_embedding_config","type":"string"},{"default":false,"description":"Reserved. Do not use.","name":"is_global_init","type":"boolean"},{"default":false,"name":"enable_whole_mesh_compilations","type":"boolean"},{"default":true,"name":"compilation_failure_closes_chips","type":"boolean"}],"outputs":[{"description":"A serialized tensorflow.tpu.TopologyProto that describes the TPU\ntopology.","name":"topology","type":7}],"summary":"Sets up the centralized structures for a distributed TPU system."}},{"name":"ConfigureTPUEmbedding","schema":{"attributes":[{"description":"Serialized tensorflow.tpu.TPUEmbeddingConfiguration that\ndescribes the embedding lookups of the program.","name":"config","type":"string"}],"summary":"Sets up TPUEmbedding in a distributed TPU system."}},{"name":"Conj","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`, `variant`.","name":"T","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ncomplex numbers that are the complex conjugate of each element in `input`. The\ncomplex numbers in `input` must be of the form \\\\(a + bj\\\\), where *a* is the\nreal part and *b* is the imaginary part.\n\nThe complex conjugate returned by this operation is of the form \\\\(a - bj\\\\).\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the complex conjugate of a complex number."}},{"name":"ConjugateTranspose","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tperm","type":"type"}],"description":"The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy:\n `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]`\n `y[i,j,k,...,s,t,u] == conj(x[perm[i], perm[j], perm[k],...,perm[s], perm[t], perm[u]])`","inputs":[{"name":"x","typeAttr":"T"},{"name":"perm","typeAttr":"Tperm"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Shuffle dimensions of x according to a permutation and conjugate the result."}},{"name":"Const","schema":{"attributes":[{"description":"Attr `value` is the tensor to return.","name":"value","type":"tensor"},{"name":"dtype","type":"type"}],"category":"Constant","outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Returns a constant tensor."}},{"name":"ConsumeMutexLock","schema":{"description":"This op exists to consume a tensor created by `MutexLock` (other than\ndirect control dependencies). It should be the only that consumes the tensor,\nand will raise an error if it is not. Its only purpose is to keep the\nmutex lock tensor alive until it is consumed by this op.\n\n**NOTE**: This operation must run on the same device as its input. This may\nbe enforced via the `colocate_with` mechanism.","inputs":[{"description":"A tensor returned by `MutexLock`.","name":"mutex_lock","type":21}],"summary":"This op consumes a lock created by `MutexLock`."}},{"name":"ControlTrigger","schema":{"description":"Only useful as a placeholder for control edges.","summary":"Does nothing. Serves as a control trigger for scheduling."}},{"name":"Conv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`.","name":"T","type":"type"},{"description":"1-D tensor of length 4. The stride of the sliding window for each\ndimension of `input`. The dimension order is determined by the value of\n`data_format`, see below for details.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"category":"Layer","description":"Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\nand a filter / kernel tensor of shape\n`[filter_height, filter_width, in_channels, out_channels]`, this op\nperforms the following:\n\n1. Flattens the filter to a 2-D matrix with shape\n `[filter_height * filter_width * in_channels, output_channels]`.\n2. Extracts image patches from the input tensor to form a *virtual*\n tensor of shape `[batch, out_height, out_width,\n filter_height * filter_width * in_channels]`.\n3. For each patch, right-multiplies the filter matrix and the image patch\n vector.\n\nIn detail, with the default NHWC format,\n\n output[b, i, j, k] =\n sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *\n filter[di, dj, q, k]\n\nMust have `strides[0] = strides[3] = 1`. For the most common case of the same\nhorizontal and vertices strides, `strides = [1, stride, stride, 1]`.","inputs":[{"description":"A 4-D tensor. The dimension order is interpreted according to the value\nof `data_format`, see below for details.","name":"input","typeAttr":"T"},{"description":"A 4-D tensor of shape\n`[filter_height, filter_width, in_channels, out_channels]`","name":"filter","typeAttr":"T"}],"outputs":[{"description":"A 4-D tensor. The dimension order is determined by the value of\n`data_format`, see below for details.","name":"output","typeAttr":"T"}],"summary":"Computes a 2-D convolution given 4-D `input` and `filter` tensors."}},{"name":"Conv2DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution. Must be in the same order as the dimension specified with\nformat.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 4-D\n`[filter_height, filter_width, in_channels, out_channels]` tensor.","name":"filter_sizes","type":3},{"description":"4-D with shape `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.\nthe `filter` input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of convolution with respect to the filter."}},{"name":"Conv2DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution. Must be in the same order as the dimension specified with\nformat.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"An integer vector representing the shape of `input`,\nwhere `input` is a 4-D `[batch, height, width, channels]` tensor.","name":"input_sizes","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`. Gradient\nw.r.t. the input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of convolution with respect to the input."}},{"name":"Conv3D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"description":"In signal processing, cross-correlation is a measure of similarity of\ntwo waveforms as a function of a time-lag applied to one of them. This\nis also known as a sliding dot product or sliding inner-product.\n\nOur Conv3D implements a form of cross-correlation.","inputs":[{"description":"Shape `[batch, in_depth, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[filter_depth, filter_height, filter_width, in_channels,\nout_channels]`. `in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes a 3-D convolution given 5-D `input` and `filter` tensors."}},{"name":"Conv3DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1,1],"name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the filter."}},{"name":"Conv3DBackpropFilterV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 5-D\n`[filter_depth, filter_height, filter_width, in_channels, out_channels]`\ntensor.","name":"filter_sizes","type":3},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the filter."}},{"name":"Conv3DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1,1],"name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the input."}},{"name":"Conv3DBackpropInputV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"inputs":[{"description":"An integer vector representing the tensor shape of `input`,\nwhere `input` is a 5-D\n`[batch, depth, rows, cols, in_channels]` tensor.","name":"input_sizes","typeAttr":"Tshape"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the input."}},{"name":"Copy","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"A list of debug op spec (op, url, gated_grpc) for attached debug\nops. Each element of the list has the format\n;;, wherein gated_grpc is boolean represented\nas 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n\"DebugIdentity;file:///tmp/tfdbg_1;0\".","name":"debug_ops_spec","type":"string[]"}],"description":"Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the\ndevice on which the tensor is allocated.\nN.B.: If the all downstream attached debug ops are disabled given the current\ngRPC gating status, the output will simply forward the input tensor without\ndeep-copying. See the documentation of Debug* ops for more details.\n\nUnlike the CopyHost Op, this op does not have HostMemory constraint on its\ninput or output.","inputs":[{"description":"Input tensor.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Copy a tensor from CPU-to-CPU or GPU-to-GPU."}},{"name":"CopyHost","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"A list of debug op spec (op, url, gated_grpc) for attached debug\nops. Each element of the list has the format\n;;, wherein gated_grpc is boolean represented\nas 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n\"DebugIdentity;file:///tmp/tfdbg_1;0\".","name":"debug_ops_spec","type":"string[]"}],"description":"Performs CPU-to-CPU deep-copying of tensor.\nN.B.: If the all downstream attached debug ops are disabled given the current\ngRPC gating status, the output will simply forward the input tensor without\ndeep-copying. See the documentation of Debug* ops for more details.\n\nUnlike the Copy Op, this op has HostMemory constraint on its input or output.","inputs":[{"description":"Input tensor.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Copy a tensor to host."}},{"name":"Cos","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes cosine of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `[-1,1]`. If input lies outside the boundary, `nan`\n is returned.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.cos(x) ==> [nan -0.91113025 0.87758255 0.5403023 0.36235774 0.48718765 -0.95215535 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes cos of x element-wise."}},{"name":"Cosh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic cosine of every\n element in the tensor. Input range is `[-inf, inf]` and output range\n is `[1, inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 2, 10, float(\"inf\")])\n tf.math.cosh(x) ==> [inf 4.0515420e+03 1.1276259e+00 1.5430807e+00 1.8106556e+00 3.7621956e+00 1.1013233e+04 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic cosine of x element-wise."}},{"name":"CountUpTo","schema":{"attributes":[{"description":"If incrementing ref would bring it above limit, instead generates an\n'OutOfRange' error.","name":"limit","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Should be from a scalar `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"}],"outputs":[{"description":"A copy of the input before increment. If nothing else modifies the\ninput, the values produced will all be distinct.","name":"output","typeAttr":"T"}],"summary":"Increments 'ref' until it reaches 'limit'."}},{"name":"CreateSummaryDbWriter","schema":{"inputs":[{"name":"writer","type":20},{"name":"db_uri","type":7},{"name":"experiment_name","type":7},{"name":"run_name","type":7},{"name":"user_name","type":7}]}},{"name":"CreateSummaryFileWriter","schema":{"inputs":[{"name":"writer","type":20},{"name":"logdir","type":7},{"name":"max_queue","type":3},{"name":"flush_millis","type":3},{"name":"filename_suffix","type":7}]}},{"name":"CropAndResize","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the sampling method for resizing. It can be either\n`\"bilinear\"` or `\"nearest\"` and default to `\"bilinear\"`. Currently two sampling\nmethods are supported: Bilinear and Nearest Neighbor. Must be one of the following: `bilinear`, `nearest`.","name":"method","type":"string"},{"default":0,"description":"Value used for extrapolation, when applicable.","name":"extrapolation_value","type":"float32"}],"description":"Extracts crops from the input image tensor and resizes them using bilinear\nsampling or nearest neighbor sampling (possibly with aspect ratio change) to a\ncommon output size specified by `crop_size`. This is more general than the\n`crop_to_bounding_box` op which extracts a fixed size slice from the input image\nand does not allow resizing or aspect ratio change.\n\nReturns a tensor with `crops` from the input `image` at positions defined at the\nbounding box locations in `boxes`. The cropped boxes are all resized (with\nbilinear or nearest neighbor interpolation) to a fixed\n`size = [crop_height, crop_width]`. The result is a 4-D tensor\n`[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned.\nIn particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical\nresults to using `tf.image.resize_bilinear()` or\n`tf.image.resize_nearest_neighbor()`(depends on the `method` argument) with\n`align_corners=True`.","inputs":[{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.\nBoth `image_height` and `image_width` need to be positive.","name":"image","typeAttr":"T"},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3},{"description":"A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All\ncropped image patches are resized to this size. The aspect ratio of the image\ncontent is not preserved. Both `crop_height` and `crop_width` need to be\npositive.","name":"crop_size","type":3}],"outputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"crops","type":1}],"summary":"Extracts crops from the input image tensor and resizes them."}},{"name":"CropAndResizeGradBoxes","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the interpolation method. Only 'bilinear' is\nsupported for now. Must be one of the following: `bilinear`.","name":"method","type":"string"}],"inputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"grads","type":1},{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.\nBoth `image_height` and `image_width` need to be positive.","name":"image","typeAttr":"T"},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3}],"outputs":[{"description":"A 2-D tensor of shape `[num_boxes, 4]`.","name":"output","type":1}],"summary":"Computes the gradient of the crop_and_resize op wrt the input boxes tensor."}},{"name":"CropAndResizeGradImage","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the interpolation method. Only 'bilinear' is\nsupported for now. Must be one of the following: `bilinear`, `nearest`.","name":"method","type":"string"}],"inputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"grads","type":1},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3},{"description":"A 1-D tensor with value `[batch, image_height, image_width, depth]`\ncontaining the original image size. Both `image_height` and `image_width` need\nto be positive.","name":"image_size","type":3}],"outputs":[{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of the crop_and_resize op wrt the input image tensor."}},{"name":"Cross","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"`a` and `b` must be the same shape; they can either be simple 3-element vectors,\nor any shape where the innermost dimension is 3. In the latter case, each pair\nof corresponding 3-element vectors is cross-multiplied independently.","inputs":[{"description":"A tensor containing 3-element vectors.","name":"a","typeAttr":"T"},{"description":"Another tensor, of same type and shape as `a`.","name":"b","typeAttr":"T"}],"outputs":[{"description":"Pairwise cross product of the vectors in `a` and `b`.","name":"product","typeAttr":"T"}],"summary":"Compute the pairwise cross product."}},{"name":"CrossReplicaSum","schema":{"attributes":[{"description":"The type of elements to be summed. Must be one of the following: `bfloat16`, `float32`, `int32`, `uint32`.","name":"T","type":"type"}],"description":"Each instance supplies its own input.\n\nFor example, suppose there are 8 TPU instances: `[A, B, C, D, E, F, G, H]`.\nPassing group_assignment=`[[0,2,4,6],[1,3,5,7]]` sets `A, C, E, G` as group 0,\nand `B, D, F, H` as group 1. Thus we get the outputs:\n`[A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H]`.","inputs":[{"description":"The local input to the sum.","name":"input","typeAttr":"T"},{"description":"An int32 tensor with shape\n[num_groups, num_replicas_per_group]. `group_assignment[i]` represents the\nreplica ids in the ith subgroup.","name":"group_assignment","type":3}],"outputs":[{"description":"The sum of all the distributed inputs.","name":"output","typeAttr":"T"}],"summary":"An Op to sum inputs across replicated TPU instances."}},{"name":"CudnnRNN","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":true,"name":"is_training","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is false.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"}],"summary":"A RNN backed by cuDNN."}},{"name":"CudnnRNNBackprop","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Compute the backprop of both data and weights in a RNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\nreserve_space: The same reserve_space produced in for forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNN."}},{"name":"CudnnRNNBackpropV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Compute the backprop of both data and weights in a RNN. Takes an extra\n \"host_reserved\" inupt than CudnnRNNBackprop, which is used to determine RNN\n cudnnRNNAlgo_t and cudnnMathType_t.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\nreserve_space: The same reserve_space produced in the forward operation.\nhost_reserved: The same host_reserved produced in the forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNN."}},{"name":"CudnnRNNBackpropV3","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"},{"default":true,"name":"time_major","type":"boolean"}],"description":"Compute the backprop of both data and weights in a RNN. Takes an extra\n \"sequence_lengths\" input than CudnnRNNBackprop.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, input_size]. If time_major is false, the shape is\n [batch_size, seq_length, input_size].\ninput_h: If time_major is true, this is a 3-D tensor with the shape of\n [num_layer * dir, batch_size, num_units]. If time_major is false, the shape\n is [batch_size, num_layer * dir, num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\nsequence_lengths: a vector of lengths of each input sequence.\noutput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, dir * num_units]. If time_major is false, the\n shape is [batch_size, seq_length, dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\ntime_major: Indicates whether the input/output format is time major or batch\n major.\nreserve_space: The same reserve_space produced in the forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"sequence_lengths","type":3},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNNV3."}},{"name":"CudnnRNNCanonicalToParams","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Writes a set of weights into the opaque params buffer so they can be used in\nupcoming training or inferences.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nnum_params: number of parameter sets for all layers.\n Each layer may contain multiple parameter sets, with each set consisting of\n a weight matrix and a bias vector.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"weights","numberAttr":"num_params","typeAttr":"T"},{"name":"biases","numberAttr":"num_params","typeAttr":"T"}],"outputs":[{"name":"params","typeAttr":"T"}],"summary":"Converts CudnnRNN params from canonical form to usable form."}},{"name":"CudnnRNNCanonicalToParamsV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params_weights","type":"int64"},{"minimum":1,"name":"num_params_biases","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Writes a set of weights into the opaque params buffer so they can be used in\nupcoming training or inferences.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nnum_params_weights: number of weight parameter matrix for all layers.\nnum_params_biases: number of bias parameter vector for all layers.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nnum_proj: The output dimensionality for the projection matrices. If None or 0,\n no projection is performed.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"weights","numberAttr":"num_params_weights","typeAttr":"T"},{"name":"biases","numberAttr":"num_params_biases","typeAttr":"T"}],"outputs":[{"name":"params","typeAttr":"T"}],"summary":"Converts CudnnRNN params from canonical form to usable form. It supports the projection in LSTM."}},{"name":"CudnnRNNParamsSize","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Return the params size that can be used by the Cudnn RNN model. Subsequent\nweight allocation and initialization should use this size.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nparams_size: The size of the params buffer that should be allocated and\n initialized for this RNN model. Note that this params buffer may not be\n compatible across GPUs. Please use CudnnRNNParamsWeights and\n CudnnRNNParamsBiases to save and restore them in a way that is compatible\n across different runs.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3}],"outputs":[{"name":"params_size","typeAttr":"S"}],"summary":"Computes size of weights that can be used by a Cudnn RNN model."}},{"name":"CudnnRNNParamsToCanonical","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Retrieves a set of weights from the opaque params buffer that can be saved and\nrestored in a way compatible with future runs.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nnum_params: number of parameter sets for all layers.\n Each layer may contain multiple parameter sets, with each set consisting of\n a weight matrix and a bias vector.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"weights","numberAttr":"num_params","typeAttr":"T"},{"name":"biases","numberAttr":"num_params","typeAttr":"T"}],"summary":"Retrieves CudnnRNN params in canonical form."}},{"name":"CudnnRNNParamsToCanonicalV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params_weights","type":"int64"},{"minimum":1,"name":"num_params_biases","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Retrieves a set of weights from the opaque params buffer that can be saved and\nrestored in a way compatible with future runs.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nnum_params_weights: number of weight parameter matrix for all layers.\nnum_params_biases: number of bias parameter vector for all layers.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nnum_proj: The output dimensionality for the projection matrices. If None or 0,\n no projection is performed.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"weights","numberAttr":"num_params_weights","typeAttr":"T"},{"name":"biases","numberAttr":"num_params_biases","typeAttr":"T"}],"summary":"Retrieves CudnnRNN params in canonical form. It supports the projection in LSTM."}},{"name":"CudnnRNNV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":true,"name":"is_training","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer. Produces one extra output \"host_reserved\" than CudnnRNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is true.\nhost_reserved: An opaque tensor that can be used in backprop calculation. It is\n only produced if is_training is true. It is output on host memory rather than\n device memory.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"summary":"A RNN backed by cuDNN."}},{"name":"CudnnRNNV3","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"},{"default":true,"name":"is_training","type":"boolean"},{"default":true,"name":"time_major","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer. Accepts one extra input \"sequence_lengths\" than CudnnRNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, input_size]. If time_major is false, the shape is\n [batch_size, seq_length, input_size].\ninput_h: If time_major is true, this is a 3-D tensor with the shape of\n [num_layer * dir, batch_size, num_units]. If time_major is false, the shape\n is [batch_size, num_layer * dir, num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\nsequence_lengths: a vector of lengths of each input sequence.\noutput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, dir * num_units]. If time_major is false, the\n shape is [batch_size, seq_length, dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\ntime_major: Indicates whether the input/output format is time major or batch\n major.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is true.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"sequence_lengths","type":3}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"summary":"A RNN backed by cuDNN."}},{"name":"Cumprod","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumprod.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumprod, which means that the first\nelement of the input is identical to the first element of the output:\n\n```python\ntf.cumprod([a, b, c]) # => [a, a * b, a * b * c]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumprod is\nperformed instead:\n\n```python\ntf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b]\n```\n\nBy setting the `reverse` kwarg to `True`, the cumprod is performed in the\nopposite direction:\n\n```python\ntf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c]\n```\n\nThis is more efficient than using separate `tf.reverse` ops.\n\nThe `reverse` and `exclusive` kwargs can also be combined:\n\n```python\ntf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1]\n```","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float32`, `float64`,\n`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n`complex128`, `qint8`, `quint8`, `qint32`, `half`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative product of the tensor `x` along `axis`."}},{"name":"Cumsum","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumsum.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumsum, which means that the first\nelement of the input is identical to the first element of the output:\n\n```python\ntf.cumsum([a, b, c]) # => [a, a + b, a + b + c]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumsum is\nperformed instead:\n\n```python\ntf.cumsum([a, b, c], exclusive=True) # => [0, a, a + b]\n```\n\nBy setting the `reverse` kwarg to `True`, the cumsum is performed in the\nopposite direction:\n\n```python\ntf.cumsum([a, b, c], reverse=True) # => [a + b + c, b + c, c]\n```\n\nThis is more efficient than using separate `tf.reverse` ops.\n\nThe `reverse` and `exclusive` kwargs can also be combined:\n\n```python\ntf.cumsum([a, b, c], exclusive=True, reverse=True) # => [b + c, c, 0]\n```","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float32`, `float64`,\n`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n`complex128`, `qint8`, `quint8`, `qint32`, `half`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative sum of the tensor `x` along `axis`."}},{"name":"CumulativeLogsumexp","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumulative log-sum-exp.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumulative log-sum-exp,\nwhich means that the first\nelement of the input is identical to the first element of the output:\n```python\ntf.math.cumulative_logsumexp([a, b, c]) # => [a, log(exp(a) + exp(b)), log(exp(a) + exp(b) + exp(c))]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumulative log-sum-exp is\nperformed instead:\n```python\ntf.cumulative_logsumexp([a, b, c], exclusive=True) # => [-inf, a, log(exp(a) * exp(b))]\n```\nNote that the neutral element of the log-sum-exp operation is `-inf`,\nhowever, for performance reasons, the minimal value representable by the\nfloating point type is used instead.\n\nBy setting the `reverse` kwarg to `True`, the cumulative log-sum-exp is performed in the\nopposite direction.","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float16`, `float32`, `float64`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative product of the tensor `x` along `axis`."}},{"name":"DataFormatDimMap","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"NHWC","description":"source data format.","name":"src_format","type":"string"},{"default":"NCHW","description":"destination data format.","name":"dst_format","type":"string"}],"description":"the source data format.","inputs":[{"description":"A Tensor with each element as a dimension index in source data format.\nMust be in the range [-4, 4).","name":"x","typeAttr":"T"}],"outputs":[{"description":"A Tensor with each element as a dimension index in destination data format.","name":"y","typeAttr":"T"}],"summary":"Returns the dimension index in the destination data format given the one in"}},{"name":"DataFormatVecPermute","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"NHWC","description":"source data format.","name":"src_format","type":"string"},{"default":"NCHW","description":"destination data format.","name":"dst_format","type":"string"}],"description":"one in the source data format.","inputs":[{"description":"Vector of size 4 or Tensor of shape (4, 2) in source data format.","name":"x","typeAttr":"T"}],"outputs":[{"description":"Vector of size 4 or Tensor of shape (4, 2) in destination data format.","name":"y","typeAttr":"T"}],"summary":"Returns the permuted vector/tensor in the destination data format given the"}},{"name":"DataServiceDataset","schema":{"attributes":[{"default":-1,"name":"task_refresh_interval_hint_ms","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"dataset_id","type":9},{"name":"processing_mode","type":7},{"name":"address","type":7},{"name":"protocol","type":7},{"name":"job_name","type":7},{"name":"max_outstanding_requests","type":9},{"name":"iteration_counter","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that reads data from the tf.data service."}},{"name":"DatasetCardinality","schema":{"description":"Returns the cardinality of `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return cardinality for.","name":"input_dataset","type":21}],"outputs":[{"description":"The cardinality of `input_dataset`. Named constants are used to represent\ninfinite and unknown cardinality.","name":"cardinality","type":9}],"summary":"Returns the cardinality of `input_dataset`."}},{"name":"DatasetFromGraph","schema":{"description":"Creates a dataset from the provided `graph_def`.","inputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph_def","type":7}],"outputs":[{"description":"A variant tensor representing the dataset.","name":"handle","type":21}],"summary":"Creates a dataset from the given `graph_def`."}},{"name":"DatasetToGraph","schema":{"attributes":[{"default":[],"minimum":0,"name":"stateful_whitelist","type":"string[]"},{"default":false,"name":"allow_stateful","type":"boolean"},{"default":false,"name":"strip_device_assignment","type":"boolean"}],"description":"Returns a graph representation for `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return the graph representation for.","name":"input_dataset","type":21}],"outputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph","type":7}],"summary":"Returns a serialized GraphDef representing `input_dataset`."}},{"name":"DatasetToGraphV2","schema":{"attributes":[{"default":0,"name":"external_state_policy","type":"int64"},{"default":false,"name":"strip_device_assignment","type":"boolean"}],"description":"Returns a graph representation for `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return the graph representation for.","name":"input_dataset","type":21}],"outputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph","type":7}],"summary":"Returns a serialized GraphDef representing `input_dataset`."}},{"name":"DatasetToSingleElement","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to a dataset that contains a single element.","name":"dataset","type":21}],"outputs":[{"description":"The components of the single element of `input`.","name":"components","typeListAttr":"output_types"}],"summary":"Outputs the single element from the given dataset."}},{"name":"DatasetToTFRecord","schema":{"inputs":[{"description":"A variant tensor representing the dataset to write.","name":"input_dataset","type":21},{"description":"A scalar string tensor representing the filename to use.","name":"filename","type":7},{"description":"A scalar string tensor containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7}],"summary":"Writes the given dataset to the given file using the TFRecord format."}},{"name":"Dawsn","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"DebugGradientIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This op is hidden from public in Python. It is used by TensorFlow Debugger to\nregister gradient tensors for gradient debugging.\nThis op operates on non-reference-type tensors.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Identity op for gradient debugging."}},{"name":"DebugGradientRefIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This op is hidden from public in Python. It is used by TensorFlow Debugger to\nregister gradient tensors for gradient debugging.\nThis op operates on reference-type tensors.","inputs":[{"isRef":true,"name":"input","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output","typeAttr":"T"}],"summary":"Identity op for gradient debugging."}},{"name":"DebugIdentity","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"Name of the device on which the tensor resides.","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011","name":"debug_urls","type":"string[]"},{"default":false,"description":"Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Provides an identity mapping of the non-Ref type input tensor for debugging.","inputs":[{"description":"Input tensor, non-Reference type","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Provides an identity mapping of the non-Ref type input tensor for debugging."}},{"name":"DebugIdentityV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"A tfdbg-generated ID for the context that the op belongs to,\n e.g., a concrete compiled tf.function.","name":"tfdbg_context_id","type":"string"},{"default":"","description":"Optional. Name of the op that the debug op is concerned with.\n Used only for single-tensor trace.","name":"op_name","type":"string"},{"default":-1,"description":"Optional. Output slot index of the tensor that the debug op\n is concerned with. Used only for single-tensor trace.","name":"output_slot","type":"int64"},{"default":-1,"description":"TensorDebugMode enum value. See debug_event.proto for details.","name":"tensor_debug_mode","type":"int64"},{"default":[],"description":"List of URLs to debug targets, e.g., file:///foo/tfdbg_dump.","name":"debug_urls","type":"string[]"},{"default":1000,"name":"circular_buffer_size","type":"int64"},{"default":"","name":"tfdbg_run_id","type":"string"}],"description":"Provides an identity mapping from input to output, while writing the content of\nthe input tensor by calling DebugEventsWriter.\n\nThe semantics of the input tensor depends on tensor_debug_mode. In typical\nusage, the input tensor comes directly from the user computation only when\ngraph_debug_mode is FULL_TENSOR (see protobuf/debug_event.proto for a\nlist of all the possible values of graph_debug_mode). For the other debug modes,\nthe input tensor should be produced by an additional op or subgraph that\ncomputes summary information about one or more tensors.","inputs":[{"description":"Input tensor, non-Reference type","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Debug Identity V2 Op."}},{"name":"DebugNanCount","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.","name":"debug_urls","type":"string[]"},{"default":false,"description":" Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Counts number of NaNs in the input tensor, for debugging.","inputs":[{"description":"Input tensor, non-Reference type.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":9}],"summary":"Debug NaN Value Counter Op."}},{"name":"DebugNumericSummary","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.","name":"debug_urls","type":"string[]"},{"default":"-NaN","description":"(float) The lower bound <= which values will be included in the\n generalized -inf count. Default: -inf.","name":"lower_bound","type":"float32"},{"default":"NaN","description":"(float) The upper bound >= which values will be included in the\n generalized +inf count. Default: +inf.","name":"upper_bound","type":"float32"},{"default":false,"description":"(bool) Do not send data to the debug URLs unless at least one\n of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and\n inf counts) is non-zero.","name":"mute_if_healthy","type":"boolean"},{"default":false,"description":"Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Provide a basic summary of numeric value types, range and distribution.\n\noutput: A double tensor of shape [14 + nDimensions], where nDimensions is the\n number of dimensions of the tensor's shape. The elements of output are:\n [0]: is initialized (1.0) or not (0.0).\n [1]: total number of elements\n [2]: NaN element count\n [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by\n default.\n [4]: negative element count (excluding -inf), if lower_bound is the default\n -inf. Otherwise, this is the count of elements > lower_bound and < 0.\n [5]: zero element count\n [6]: positive element count (excluding +inf), if upper_bound is the default\n +inf. Otherwise, this is the count of elements < upper_bound and > 0.\n [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by\n default.\nOutput elements [1:8] are all zero, if the tensor is uninitialized.\n [8]: minimum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: +inf.\n [9]: maximum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: -inf.\n [10]: mean of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [11]: variance of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [12]: Data type of the tensor encoded as an enum integer. See the DataType\n proto for more details.\n [13]: Number of dimensions of the tensor (ndims).\n [14+]: Sizes of the dimensions.\n","inputs":[{"description":"Input tensor, non-Reference type.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":2}],"summary":"Debug Numeric Summary Op."}},{"name":"DebugNumericSummaryV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Optional. The type of the output. Can be float32 or float64 (default: float32). Must be one of the following: `float32`, `float64`.","name":"output_dtype","type":"type"},{"name":"T","type":"type"},{"default":-1,"description":"Tensor debug mode: the mode in which the input tensor is summarized\n by the op. See the TensorDebugMode enum in\n tensorflow/core/protobuf/debug_event.proto for details.\n\nSupported values:\n 2 (CURT_HEALTH): Output a float32/64 tensor of shape [2]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is a bit which is set to 1 if the input tensor has an\n infinity or nan value, or zero otherwise.\n\n 3 (CONCISE_HEALTH): Output a float32/64 tensor of shape [5]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The\n remaining four slots are the total number of elements, -infs,\n +infs, and nans in the input tensor respectively.\n\n 4 (FULL_HEALTH): Output a float32/64 tensor of shape [11]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The remaining elements hold the total number of elements, -infs,\n +infs, nans, negative finite numbers, zeros, and positive finite\n numbers in the input tensor respectively.\n\n 5 (SHAPE): Output a float32/64 tensor of shape [10]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 3rd element holds the rank of the tensor. The 4th element holds\n the number of elements within the tensor. Finally the remaining 6\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated.\n\n 6 (FULL_NUMERICS): Output a float32/64 tensor of shape [22]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 4th element holds the rank of the tensor. The 5th to 11th\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated. The 12th to\n 18th elements hold the number of elements, -infs, +infs, nans,\n denormal floats, negative finite numbers, zeros, and positive\n finite numbers in the input tensor respectively. The final four\n elements hold the min value, max value, mean, and variance of the\n input tensor.\n\n 8 (REDUCE_INF_NAN_THREE_SLOTS): Output a float32/64 tensor of shape\n [3]. The 1st element is -inf if any elements of the input tensor\n is -inf, or zero otherwise. The 2nd element is +inf if any elements\n of the input tensor is +inf, or zero otherwise. The 3rd element is\n nan if any element of the input tensor is nan, or zero otherwise.","name":"tensor_debug_mode","type":"int64"},{"default":-1,"description":"Optional. An integer identifier for the tensor being summarized by this op.","name":"tensor_id","type":"int64"}],"description":"Computes a numeric summary of the input tensor. The shape of the output\ndepends on the tensor_debug_mode attribute.\nThis op is used internally by TensorFlow Debugger (tfdbg) v2.","inputs":[{"description":"Input tensor, to be summarized by the op.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"output_dtype"}],"summary":"Debug Numeric Summary V2 Op."}},{"name":"DecodeAndCropJpeg","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":1,"description":"Downscaling ratio.","name":"ratio","type":"int64"},{"default":true,"description":"If true use a slower but nicer upscaling of the\nchroma planes (yuv420/422 only).","name":"fancy_upscaling","type":"boolean"},{"default":false,"description":"If true try to recover an image from truncated input.","name":"try_recover_truncated","type":"boolean"},{"default":1,"description":"The minimum required fraction of lines before a truncated\ninput is accepted.","name":"acceptable_fraction","type":"float32"},{"default":"","description":"string specifying a hint about the algorithm used for\ndecompression. Defaults to \"\" which maps to a system-specific\ndefault. Currently valid values are [\"INTEGER_FAST\",\n\"INTEGER_ACCURATE\"]. The hint may be ignored (e.g., the internal\njpeg library changes to a version that does not have that specific\noption.)","name":"dct_method","type":"string"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the JPEG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n\nIf needed, the JPEG-encoded image is transformed to match the requested number\nof color channels.\n\nThe attr `ratio` allows downscaling the image by an integer factor during\ndecoding. Allowed values are: 1, 2, 4, and 8. This is much faster than\ndownscaling the image later.\n\n\nIt is equivalent to a combination of decode and crop, but much faster by only\ndecoding partial jpeg image.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7},{"description":"1-D. The crop window: [crop_y, crop_x, crop_height, crop_width].","name":"crop_window","type":3}],"outputs":[{"description":"3-D with shape `[height, width, channels]`..","name":"image","type":4}],"summary":"Decode and Crop a JPEG-encoded image to a uint8 tensor."}},{"name":"DecodeBase64","schema":{"description":"Input may or may not have padding at the end. See EncodeBase64 for padding.\nWeb-safe means that input must use - and _ instead of + and /.","inputs":[{"description":"Base64 strings to decode.","name":"input","type":7}],"outputs":[{"description":"Decoded strings.","name":"output","type":7}],"summary":"Decode web-safe base64-encoded strings."}},{"name":"DecodeBmp","schema":{"attributes":[{"default":0,"name":"channels","type":"int64"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the BMP-encoded image.\n* 3: output an RGB image.\n* 4: output an RGBA image.","inputs":[{"description":"0-D. The BMP-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`. RGB order","name":"image","type":4}],"summary":"Decode the first frame of a BMP-encoded image to a uint8 tensor."}},{"name":"DecodeCSV","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"OUT_TYPE","type":"type[]"},{"default":",","description":"char delimiter to separate fields in a record.","name":"field_delim","type":"string"},{"default":true,"description":"If false, treats double quotation marks as regular\ncharacters inside of the string fields (ignoring RFC 4180, Section 2,\nBullet 5).","name":"use_quote_delim","type":"boolean"},{"default":"","description":"Additional string to recognize as NA/NaN.","name":"na_value","type":"string"},{"default":[],"name":"select_cols","type":"int64[]"}],"description":"RFC 4180 format is expected for the CSV records.\n(https://tools.ietf.org/html/rfc4180)\nNote that we allow leading and trailing spaces with int or float field.","inputs":[{"description":"Each string is a record/row in the csv and all records should have\nthe same format.","name":"records","type":7},{"description":"One tensor per column of the input record, with either a\nscalar default value for that column or an empty vector if the column is\nrequired.","name":"record_defaults","typeListAttr":"OUT_TYPE"}],"outputs":[{"description":"Each tensor will have the same shape as records.","name":"output","typeListAttr":"OUT_TYPE"}],"summary":"Convert CSV records to tensors. Each column maps to one tensor."}},{"name":"DecodeCompressed","schema":{"attributes":[{"default":"","description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":"string"}],"description":"This op decompresses each element of the `bytes` input `Tensor`, which\nis assumed to be compressed using the given `compression_type`.\n\nThe `output` is a string `Tensor` of the same shape as `bytes`,\neach element containing the decompressed data from the corresponding\nelement in `bytes`.","inputs":[{"description":"A Tensor of string which is compressed.","name":"bytes","type":7}],"outputs":[{"description":"A Tensor with the same shape as input `bytes`, uncompressed\nfrom bytes.","name":"output","type":7}],"summary":"Decompress strings."}},{"name":"DecodeGif","schema":{"description":"GIF images with frame or transparency compression are not supported.\nOn Linux and MacOS systems, convert animated GIFs from compressed to\nuncompressed by running:\n\n convert $src.gif -coalesce $dst.gif\n\nThis op also supports decoding JPEGs and PNGs, though it is cleaner to use\n`tf.io.decode_image`.","inputs":[{"description":"0-D. The GIF-encoded image.","name":"contents","type":7}],"outputs":[{"description":"4-D with shape `[num_frames, height, width, 3]`. RGB channel order.","name":"image","type":4}],"summary":"Decode the frame(s) of a GIF-encoded image to a uint8 tensor."}},{"name":"DecodeImage","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":{"type":"type","value":4},"description":"The desired DType of the returned Tensor. Must be one of the following: `uint8`, `uint16`, `float32`.","name":"dtype","type":"type"},{"default":true,"description":"Controls the output shape of the returned op. If True, the returned op will\nproduce a 3-D tensor for PNG, JPEG, and BMP files; and a 4-D tensor for all\nGIFs, whether animated or not. If, False, the returned op will produce a 3-D\ntensor for all file types and will truncate animated GIFs to the first frame.","name":"expand_animations","type":"boolean"}],"description":"Detects whether an image is a BMP, GIF, JPEG, or PNG, and performs the\nappropriate operation to convert the input bytes string into a Tensor of type\ndtype.\n\n*NOTE*: decode_gif returns a 4-D array [num_frames, height, width, 3], as\nopposed to decode_bmp, decode_jpeg and decode_png, which return 3-D arrays\n[height, width, num_channels]. Make sure to take this into account when\nconstructing your graph if you are intermixing GIF files with BMP, JPEG, and/or\nPNG files. Alternately, set the expand_animations argument of this function to\nFalse, in which case the op will return 3-dimensional tensors and will truncate\nanimated GIF files to the first frame.","inputs":[{"description":"0-D. The encoded image bytes.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]` or 4-D with shape\n`[frame, height, width, channels]`..","name":"image","typeAttr":"dtype"}],"summary":"Function for decode_bmp, decode_gif, decode_jpeg, and decode_png."}},{"name":"DecodeJSONExample","schema":{"description":"This op translates a tensor containing Example records, encoded using\nthe [standard JSON\nmapping](https://developers.google.com/protocol-buffers/docs/proto3#json),\ninto a tensor containing the same records encoded as binary protocol\nbuffers. The resulting tensor can then be fed to any of the other\nExample-parsing ops.","inputs":[{"description":"Each string is a JSON object serialized according to the JSON\nmapping of the Example proto.","name":"json_examples","type":7}],"outputs":[{"description":"Each string is a binary Example protocol buffer corresponding\nto the respective element of `json_examples`.","name":"binary_examples","type":7}],"summary":"Convert JSON-encoded Example records to binary protocol buffer strings."}},{"name":"DecodeJpeg","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":1,"description":"Downscaling ratio.","name":"ratio","type":"int64"},{"default":true,"description":"If true use a slower but nicer upscaling of the\nchroma planes (yuv420/422 only).","name":"fancy_upscaling","type":"boolean"},{"default":false,"description":"If true try to recover an image from truncated input.","name":"try_recover_truncated","type":"boolean"},{"default":1,"description":"The minimum required fraction of lines before a truncated\ninput is accepted.","name":"acceptable_fraction","type":"float32"},{"default":"","description":"string specifying a hint about the algorithm used for\ndecompression. Defaults to \"\" which maps to a system-specific\ndefault. Currently valid values are [\"INTEGER_FAST\",\n\"INTEGER_ACCURATE\"]. The hint may be ignored (e.g., the internal\njpeg library changes to a version that does not have that specific\noption.)","name":"dct_method","type":"string"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the JPEG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n\nIf needed, the JPEG-encoded image is transformed to match the requested number\nof color channels.\n\nThe attr `ratio` allows downscaling the image by an integer factor during\ndecoding. Allowed values are: 1, 2, 4, and 8. This is much faster than\ndownscaling the image later.\n\n\nThis op also supports decoding PNGs and non-animated GIFs since the interface is\nthe same, though it is cleaner to use `tf.io.decode_image`.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`..","name":"image","type":4}],"summary":"Decode a JPEG-encoded image to a uint8 tensor."}},{"name":"DecodePaddedRaw","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`.","name":"out_type","type":"type"},{"default":true,"description":"Whether the input `input_bytes` is in little-endian order. Ignored for\n`out_type` values that are stored in a single byte, like `uint8`","name":"little_endian","type":"boolean"}],"inputs":[{"description":"Tensor of string to be decoded.","name":"input_bytes","type":7},{"description":"Length in bytes for each element of the decoded output. Must be a multiple\nof the size of the output type.","name":"fixed_length","type":3}],"outputs":[{"description":"A Tensor with one more dimension than the input `bytes`. The added dimension\nwill have size equal to the length of the elements of `bytes` divided by the\nnumber of bytes to represent `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Reinterpret the bytes of a string as a vector of numbers."}},{"name":"DecodePng","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":{"type":"type","value":4},"description":"Must be one of the following: `uint8`, `uint16`.","name":"dtype","type":"type"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the PNG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n* 4: output an RGBA image.\n\nIf needed, the PNG-encoded image is transformed to match the requested number\nof color channels.\n\nThis op also supports decoding JPEGs and non-animated GIFs since the interface\nis the same, though it is cleaner to use `tf.io.decode_image`.","inputs":[{"description":"0-D. The PNG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","typeAttr":"dtype"}],"summary":"Decode a PNG-encoded image to a uint8 or uint16 tensor."}},{"name":"DecodeProtoV2","schema":{"attributes":[{"description":"Name of the proto message type to decode.","name":"message_type","type":"string"},{"description":"List of strings containing proto field names. An extension field can be decoded\nby using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME.","name":"field_names","type":"string[]"},{"description":"List of TF types to use for the respective field in field_names.","minimum":0,"name":"output_types","type":"type[]"},{"default":"local://","description":"Either the special value `local://` or a path to a file containing\na serialized `FileDescriptorSet`.","name":"descriptor_source","type":"string"},{"default":"binary","description":"Either `binary` or `text`.","name":"message_format","type":"string"},{"default":false,"description":"Whether to sanitize the result or not.","name":"sanitize","type":"boolean"}],"description":"The `decode_proto` op extracts fields from a serialized protocol buffers\nmessage into tensors. The fields in `field_names` are decoded and converted\nto the corresponding `output_types` if possible.\n\nA `message_type` name must be provided to give context for the field names.\nThe actual message descriptor can be looked up either in the linked-in\ndescriptor pool or a filename provided by the caller using the\n`descriptor_source` attribute.\n\nEach output tensor is a dense tensor. This means that it is padded to hold\nthe largest number of repeated elements seen in the input minibatch. (The\nshape is also padded by one to prevent zero-sized dimensions). The actual\nrepeat counts for each example in the minibatch can be found in the `sizes`\noutput. In many cases the output of `decode_proto` is fed immediately into\ntf.squeeze if missing values are not a concern. When using tf.squeeze, always\npass the squeeze dimension explicitly to avoid surprises.\n\nFor the most part, the mapping between Proto field types and TensorFlow dtypes\nis straightforward. However, there are a few special cases:\n\n- A proto field that contains a submessage or group can only be converted\nto `DT_STRING` (the serialized submessage). This is to reduce the complexity\nof the API. The resulting string can be used as input to another instance of\nthe decode_proto op.\n\n- TensorFlow lacks support for unsigned integers. The ops represent uint64\ntypes as a `DT_INT64` with the same twos-complement bit pattern (the obvious\nway). Unsigned int32 values can be represented exactly by specifying type\n`DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in\nthe `output_types` attribute.\n\nBoth binary and text proto serializations are supported, and can be\nchosen using the `format` attribute.\n\nThe `descriptor_source` attribute selects the source of protocol\ndescriptors to consult when looking up `message_type`. This may be:\n\n- An empty string or \"local://\", in which case protocol descriptors are\ncreated for C++ (not Python) proto definitions linked to the binary.\n\n- A file, in which case protocol descriptors are created from the file,\nwhich is expected to contain a `FileDescriptorSet` serialized as a string.\nNOTE: You can build a `descriptor_source` file using the `--descriptor_set_out`\nand `--include_imports` options to the protocol compiler `protoc`.\n\n- A \"bytes://\", in which protocol descriptors are created from ``,\nwhich is expected to be a `FileDescriptorSet` serialized as a string.","inputs":[{"description":"Tensor of serialized protos with shape `batch_shape`.","name":"bytes","type":7}],"outputs":[{"description":"Tensor of int32 with shape `[batch_shape, len(field_names)]`.\nEach entry is the number of values found for the corresponding field.\nOptional fields may have 0 or 1 values.","name":"sizes","type":3},{"description":"List of tensors containing values for the corresponding field.\n`values[i]` has datatype `output_types[i]`\nand shape `[batch_shape, max(sizes[...,i])]`.","name":"values","typeListAttr":"output_types"}],"summary":"The op extracts fields from a serialized protocol buffers message into tensors."}},{"name":"DecodeRaw","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`, `complex64`, `complex128`, `bool`.","name":"out_type","type":"type"},{"default":true,"description":"Whether the input `bytes` are in little-endian order.\nIgnored for `out_type` values that are stored in a single byte like\n`uint8`.","name":"little_endian","type":"boolean"}],"inputs":[{"description":"All the elements must have the same length.","name":"bytes","type":7}],"outputs":[{"description":"A Tensor with one more dimension than the input `bytes`. The\nadded dimension will have size equal to the length of the elements\nof `bytes` divided by the number of bytes to represent `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Reinterpret the bytes of a string as a vector of numbers."}},{"name":"DecodeWav","schema":{"attributes":[{"default":-1,"description":"Number of sample channels wanted.","name":"desired_channels","type":"int64"},{"default":-1,"description":"Length of audio requested.","name":"desired_samples","type":"int64"}],"description":"The -32768 to 32767 signed 16-bit values will be scaled to -1.0 to 1.0 in float.\n\nWhen desired_channels is set, if the input contains fewer channels than this\nthen the last channel will be duplicated to give the requested number, else if\nthe input has more channels than requested then the additional channels will be\nignored.\n\nIf desired_samples is set, then the audio will be cropped or padded with zeroes\nto the requested length.\n\nThe first output contains a Tensor with the content of the audio samples. The\nlowest dimension will be the number of channels, and the second will be the\nnumber of samples. For example, a ten-sample-long stereo WAV file should give an\noutput shape of [10, 2].","inputs":[{"description":"The WAV-encoded audio, usually from a file.","name":"contents","type":7}],"outputs":[{"description":"2-D with shape `[length, channels]`.","name":"audio","type":1},{"description":"Scalar holding the sample rate found in the WAV header.","name":"sample_rate","type":3}],"summary":"Decode a 16-bit PCM WAV file to a float tensor."}},{"name":"DeepCopy","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The source tensor of type `T`.","name":"x","typeAttr":"T"}],"outputs":[{"description":" y: A `Tensor` of type `T`. A copy of `x`. Guaranteed that `y`\n is not an alias of `x`.","name":"y","typeAttr":"T"}],"summary":"Makes a copy of `x`."}},{"name":"DeleteIterator","schema":{"inputs":[{"description":"A handle to the iterator to delete.","name":"handle","type":20},{"description":"A variant deleter.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"DeleteMemoryCache","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteMultiDeviceIterator","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"}],"inputs":[{"description":"A handle to the multi device iterator to delete.","name":"multi_device_iterator","type":20},{"description":"A list of iterator handles (unused). This is added so that automatic control dependencies get added during function tracing that ensure this op runs after all the dependent iterators are deleted.","name":"iterators","numberAttr":"N","type":20},{"description":"A variant deleter.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"DeleteRandomSeedGenerator","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteSeedGenerator","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteSessionTensor","schema":{"inputs":[{"description":"The handle for a tensor stored in the session state.","name":"handle","type":7}],"summary":"Delete the tensor specified by its handle in the session."}},{"name":"DenseBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"1D or 2D int `Tensor`.","name":"input","typeAttr":"Tidx"},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"DenseCountSparseOutput","schema":{"attributes":[{"description":"Dtype of the input values tensor. Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing data to count.","name":"values","typeAttr":"T"},{"description":"A Tensor of the same shape as indices containing per-index weight values. May\nalso be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.","name":"output_dense_shape","type":9}],"summary":"Performs sparse-output bin counting for a tf.tensor input."}},{"name":"DenseToCSRSparseMatrix","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"description":"A Dense tensor.","name":"dense_input","typeAttr":"T"},{"description":"Indices of nonzero elements.","name":"indices","type":9}],"outputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_output","type":21}],"summary":"Converts a dense tensor to a (possibly batched) CSRSparseMatrix."}},{"name":"DenseToDenseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set1","typeAttr":"T"},{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set2","typeAttr":"T"}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of 2 `Tensor` inputs."}},{"name":"DenseToSparseBatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to an input dataset. Must have a single component.","name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A vector representing the dense shape of each row in the produced\nSparseTensor. The shape may be partially specified, using `-1` to indicate\nthat a particular dimension should use the maximum size of all batch elements.","name":"row_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches input elements into a SparseTensor."}},{"name":"DenseToSparseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nInput `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`,\nand `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same\nas `set1`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set2`\nindices.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set1","typeAttr":"T"},{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set2_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set2_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must\nbe the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the\nmax set size across `n-1` dimensions.","name":"set2_shape","type":9}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of `Tensor` and `SparseTensor`."}},{"name":"DepthToSpace","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The size of the spatial block, same as in Space2Depth.","minimum":2,"name":"block_size","type":"int64"},{"default":"NHWC","description":"Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"description":"Rearranges data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically,\nthis op outputs a copy of the input tensor where values from the `depth`\ndimension are moved in spatial blocks to the `height` and `width` dimensions.\nThe attr `block_size` indicates the input block size and how the data is moved.\n\n * Chunks of data of size `block_size * block_size` from depth are rearranged\n into non-overlapping blocks of size `block_size x block_size`\n * The width the output tensor is `input_depth * block_size`, whereas the\n height is `input_height * block_size`.\n * The Y, X coordinates within each block of the output image are determined\n by the high order component of the input channel index.\n * The depth of the input tensor must be divisible by\n `block_size * block_size`.\n\nThe `data_format` attr specifies the layout of the input and output tensors\nwith the following options:\n \"NHWC\": `[ batch, height, width, channels ]`\n \"NCHW\": `[ batch, channels, height, width ]`\n \"NCHW_VECT_C\":\n `qint8 [ batch, channels / 4, height, width, 4 ]`\n\nIt is useful to consider the operation as transforming a 6-D Tensor.\ne.g. for data_format = NHWC,\n Each element in the input tensor can be specified via 6 coordinates,\n ordered by decreasing memory layout significance as:\n n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates\n within the input image, bX, bY means coordinates\n within the output block, oC means output channels).\n The output would be the input transposed to the following layout:\n n,iY,bY,iX,bX,oC\n\nThis operation is useful for resizing the activations between convolutions\n(but keeping all data), e.g. instead of pooling. It is also useful for training\npurely convolutional models.\n\nFor example, given an input of shape `[1, 1, 1, 4]`, data_format = \"NHWC\" and\nblock_size = 2:\n\n```\nx = [[[[1, 2, 3, 4]]]]\n\n```\n\nThis operation will output a tensor of shape `[1, 2, 2, 1]`:\n\n```\n [[[[1], [2]],\n [[3], [4]]]]\n```\n\nHere, the input has a batch of 1 and each batch element has shape `[1, 1, 4]`,\nthe corresponding output will have 2x2 elements and will have a depth of\n1 channel (1 = `4 / (block_size * block_size)`).\nThe output element shape is `[2, 2, 1]`.\n\nFor an input tensor with larger depth, here of shape `[1, 1, 1, 12]`, e.g.\n\n```\nx = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]\n```\n\nThis operation, for block size of 2, will return the following tensor of shape\n`[1, 2, 2, 3]`\n\n```\n [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n\n```\n\nSimilarly, for the following input of shape `[1 2 2 4]`, and a block size of 2:\n\n```\nx = [[[[1, 2, 3, 4],\n [5, 6, 7, 8]],\n [[9, 10, 11, 12],\n [13, 14, 15, 16]]]]\n```\n\nthe operator will return the following tensor of shape `[1 4 4 1]`:\n\n```\nx = [[[ [1], [2], [5], [6]],\n [ [3], [4], [7], [8]],\n [ [9], [10], [13], [14]],\n [ [11], [12], [15], [16]]]]\n\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"DepthToSpace for tensors of type T."}},{"name":"DepthwiseConv2dNative","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"category":"Layer","description":"Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\nand a filter / kernel tensor of shape\n`[filter_height, filter_width, in_channels, channel_multiplier]`, containing\n`in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies\na different filter to each input channel (expanding from 1 channel to\n`channel_multiplier` channels for each), then concatenates the results\ntogether. Thus, the output has `in_channels * channel_multiplier` channels.\n\n```\nfor k in 0..in_channels-1\n for q in 0..channel_multiplier-1\n output[b, i, j, k * channel_multiplier + q] =\n sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] *\n filter[di, dj, k, q]\n```\n\nMust have `strides[0] = strides[3] = 1`. For the most common case of the same\nhorizontal and vertices strides, `strides = [1, stride, stride, 1]`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors."}},{"name":"DepthwiseConv2dNativeBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"4-D with shape based on `data_format`. For example, if\n`data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height,\nin_width, in_channels]` tensor.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 4-D\n`[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor.","name":"filter_sizes","type":3},{"description":"4-D with shape based on `data_format`.\nFor example, if `data_format` is 'NHWC' then\nout_backprop shape is `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.\nthe `filter` input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of depthwise convolution with respect to the filter."}},{"name":"DepthwiseConv2dNativeBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"An integer vector representing the shape of `input`, based\non `data_format`. For example, if `data_format` is 'NHWC' then\n `input` is a 4-D `[batch, height, width, channels]` tensor.","name":"input_sizes","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, depthwise_multiplier]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape based on `data_format`.\nFor example, if `data_format` is 'NHWC' then\nout_backprop shape is `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape according to `data_format`. For example, if\n`data_format` is 'NHWC', output shape is `[batch, in_height,\nin_width, in_channels]`. Gradient w.r.t. the input of the\nconvolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of depthwise convolution with respect to the input."}},{"name":"Dequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":"MIN_COMBINED","description":"Must be one of the following: `MIN_COMBINED`, `MIN_FIRST`, `SCALED`.","name":"mode","type":"string"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"},{"default":{"type":"type","value":1},"description":"Type of the output tensor. Currently Dequantize supports float and bfloat16.\nIf 'dtype' is 'bfloat16', it only supports 'MIN_COMBINED' mode. Must be one of the following: `bfloat16`, `float32`.","name":"dtype","type":"type"}],"category":"Tensor","description":"[min_range, max_range] are scalar floats that specify the range for\nthe output. The 'mode' attribute controls exactly which calculations are\nused to convert the float values to their quantized equivalents.\n\nIn 'MIN_COMBINED' mode, each value of the tensor will undergo the following:\n\n```\nif T == qint8: in[i] += (range(T) + 1)/ 2.0\nout[i] = min_range + (in[i]* (max_range - min_range) / range(T))\n```\nhere `range(T) = numeric_limits::max() - numeric_limits::min()`\n\n*MIN_COMBINED Mode Example*\n\nIf the input comes from a QuantizedRelu6, the output type is\nquint8 (range of 0-255) but the possible range of QuantizedRelu6 is\n0-6. The min_range and max_range values are therefore 0.0 and 6.0.\nDequantize on quint8 will take each value, cast to float, and multiply\nby 6 / 255.\nNote that if quantizedtype is qint8, the operation will additionally add\neach value by 128 prior to casting.\n\nIf the mode is 'MIN_FIRST', then this approach is used:\n\n```c++\nnum_discrete_values = 1 << (# of bits in T)\nrange_adjust = num_discrete_values / (num_discrete_values - 1)\nrange = (range_max - range_min) * range_adjust\nrange_scale = range / num_discrete_values\nconst double offset_input = static_cast(input) - lowest_quantized;\nresult = range_min + ((input - numeric_limits::min()) * range_scale)\n```\n\nIf the mode is `SCALED`, dequantization is performed by multiplying each\ninput value by a scaling_factor. (Thus an input of 0 always maps to 0.0).\n\nThe scaling_factor is determined from `min_range`, `max_range`, and\n`narrow_range` in a way that is compatible with `QuantizeAndDequantize{V2|V3}`\nand `QuantizeV2`, using the following algorithm:\n\n```c++\n\n const int min_expected_T = std::numeric_limits::min() +\n (narrow_range ? 1 : 0);\n const int max_expected_T = std::numeric_limits::max();\n const float max_expected_T = std::numeric_limits::max();\n\n const float scale_factor =\n (std::numeric_limits::min() == 0) ? (max_range / max_expected_T)\n : std::max(min_range / min_expected_T,\n max_range / max_expected_T);\n```","inputs":[{"name":"input","typeAttr":"T"},{"description":"The minimum scalar value possibly produced for the input.","name":"min_range","type":1},{"description":"The maximum scalar value possibly produced for the input.","name":"max_range","type":1}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Dequantize the 'input' tensor into a float or bfloat16 Tensor."}},{"name":"DeserializeIterator","schema":{"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20},{"description":"A variant tensor storing the state of the iterator contained in the\nresource.","name":"serialized","type":21}],"summary":"Converts the given variant tensor to an iterator and stores it in the given resource."}},{"name":"DeserializeManySparse","schema":{"attributes":[{"description":"The `dtype` of the serialized `SparseTensor` objects.","name":"dtype","type":"type"}],"description":"The input `serialized_sparse` must be a string matrix of shape `[N x 3]` where\n`N` is the minibatch size and the rows correspond to packed outputs of\n`SerializeSparse`. The ranks of the original `SparseTensor` objects\nmust all match. When the final `SparseTensor` is created, it has rank one\nhigher than the ranks of the incoming `SparseTensor` objects\n(they have been concatenated along a new row dimension).\n\nThe output `SparseTensor` object's shape values for all dimensions but the\nfirst are the max across the input `SparseTensor` objects' shape values\nfor the corresponding dimensions. Its first shape value is `N`, the minibatch\nsize.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the serialized input is a `[2 x 3]` matrix representing two\noriginal `SparseTensor` objects:\n\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n\nand\n\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n\nthen the final deserialized `SparseTensor` will be:\n\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]","inputs":[{"description":"2-D, The `N` serialized `SparseTensor` objects.\nMust have 3 columns.","name":"serialized_sparse","type":7}],"outputs":[{"name":"sparse_indices","type":9},{"name":"sparse_values","typeAttr":"dtype"},{"name":"sparse_shape","type":9}],"summary":"Deserialize and concatenate `SparseTensors` from a serialized minibatch."}},{"name":"DeserializeSparse","schema":{"attributes":[{"description":"The `dtype` of the serialized `SparseTensor` objects.","name":"dtype","type":"type"},{"default":{"type":"type","value":7},"description":"Must be one of the following: `string`, `variant`.","name":"Tserialized","type":"type"}],"description":"The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where\nthe last dimension stores serialized `SparseTensor` objects and the other N\ndimensions (N >= 0) correspond to a batch. The ranks of the original\n`SparseTensor` objects must all match. When the final `SparseTensor` is\ncreated, its rank is the rank of the incoming `SparseTensor` objects plus N;\nthe sparse tensors have been concatenated along new dimensions, one for each\nbatch.\n\nThe output `SparseTensor` object's shape values for the original dimensions\nare the max across the input `SparseTensor` objects' shape values for the\ncorresponding dimensions. The new dimensions match the size of the batch.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the serialized input is a `[2 x 3]` matrix representing two\noriginal `SparseTensor` objects:\n\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n\nand\n\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n\nthen the final deserialized `SparseTensor` will be:\n\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]","inputs":[{"description":"The serialized `SparseTensor` objects. The last dimension\nmust have 3 columns.","name":"serialized_sparse","typeAttr":"Tserialized"}],"outputs":[{"name":"sparse_indices","type":9},{"name":"sparse_values","typeAttr":"dtype"},{"name":"sparse_shape","type":9}],"summary":"Deserialize `SparseTensor` objects."}},{"name":"DestroyResourceOp","schema":{"attributes":[{"default":true,"description":"whether to ignore the error when the resource\ndoesn't exist.","name":"ignore_lookup_error","type":"boolean"}],"description":"All subsequent operations using the resource will result in a NotFound\nerror status.","inputs":[{"description":"handle to the resource to delete.","name":"resource","type":20}],"summary":"Deletes the resource specified by the handle."}},{"name":"DestroyTemporaryVariable","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Name of the temporary variable, usually the name of the matching\n'TemporaryVariable' op.","name":"var_name","type":"string"}],"description":"Sets output to the value of the Tensor pointed to by 'ref', then destroys\nthe temporary variable called 'var_name'.\nAll other uses of 'ref' *must* have executed before this op.\nThis is typically achieved by chaining the ref through each assign op, or by\nusing control dependencies.\n\nOutputs the final value of the tensor pointed to by 'ref'.","inputs":[{"description":"A reference to the temporary variable tensor.","isRef":true,"name":"ref","typeAttr":"T"}],"outputs":[{"name":"value","typeAttr":"T"}],"summary":"Destroys the temporary variable and returns its final value."}},{"name":"DeviceIndex","schema":{"attributes":[{"name":"device_names","type":"string[]"}],"description":"Given a list of device names, this operation returns the index of the device\nthis op runs. The length of the list is returned in two cases:\n(1) Device does not exist in the given device list.\n(2) It is in XLA compilation.","outputs":[{"name":"index","type":3}],"summary":"Return the index of device the op runs."}},{"name":"Diag","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Given a `diagonal`, this operation returns a tensor with the `diagonal` and\neverything else padded with zeros. The diagonal is computed as follows:\n\nAssume `diagonal` has dimensions [D1,..., Dk], then the output is a tensor of\nrank 2k with dimensions [D1,..., Dk, D1,..., Dk] where:\n\n`output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]` and 0 everywhere else.\n\nFor example:\n\n```\n# 'diagonal' is [1, 2, 3, 4]\ntf.diag(diagonal) ==> [[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]]\n```","inputs":[{"description":"Rank k tensor where k is at most 1.","name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns a diagonal tensor with a given diagonal values."}},{"name":"DiagPart","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"This operation returns a tensor with the `diagonal` part\nof the `input`. The `diagonal` part is computed as follows:\n\nAssume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a\ntensor of rank `k` with dimensions `[D1,..., Dk]` where:\n\n`diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`.\n\nFor example:\n\n```\n# 'input' is [[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]]\n\ntf.diag_part(input) ==> [1, 2, 3, 4]\n```","inputs":[{"description":"Rank k tensor where k is even and not zero.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal.","name":"diagonal","typeAttr":"T"}],"summary":"Returns the diagonal part of the tensor."}},{"name":"Digamma","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"`Gamma(x)`), element-wise.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes Psi, the derivative of Lgamma (the log of the absolute value of"}},{"name":"Dilation2D","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The input stride for atrous morphological dilation. Must be:\n`[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"The `input` tensor has shape `[batch, in_height, in_width, depth]` and the\n`filter` tensor has shape `[filter_height, filter_width, depth]`, i.e., each\ninput channel is processed independently of the others with its own structuring\nfunction. The `output` tensor has shape\n`[batch, out_height, out_width, depth]`. The spatial dimensions of the output\ntensor depend on the `padding` algorithm. We currently only support the default\n\"NHWC\" `data_format`.\n\nIn detail, the grayscale morphological 2-D dilation is the max-sum correlation\n(for consistency with `conv2d`, we use unmirrored filters):\n\n output[b, y, x, c] =\n max_{dy, dx} input[b,\n strides[1] * y + rates[1] * dy,\n strides[2] * x + rates[2] * dx,\n c] +\n filter[dy, dx, c]\n\nMax-pooling is a special case when the filter has size equal to the pooling\nkernel size and contains all zeros.\n\nNote on duality: The dilation of `input` by the `filter` is equal to the\nnegation of the erosion of `-input` by the reflected `filter`.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"output","typeAttr":"T"}],"summary":"Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors."}},{"name":"Dilation2DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension of\nthe input tensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"1-D of length 4. The input stride for atrous morphological dilation.\nMust be: `[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter_backprop","typeAttr":"T"}],"summary":"Computes the gradient of morphological 2-D dilation with respect to the filter."}},{"name":"Dilation2DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension of\nthe input tensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"1-D of length 4. The input stride for atrous morphological dilation.\nMust be: `[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"in_backprop","typeAttr":"T"}],"summary":"Computes the gradient of morphological 2-D dilation with respect to the input."}},{"name":"DirectedInterleaveDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A dataset of scalar `DT_INT64` elements that determines which of the\n`N` data inputs should produce the next output element.","name":"selector_input_dataset","type":21},{"description":"`N` datasets with the same type that will be interleaved according to\nthe values of `selector_input_dataset`.","name":"data_input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A substitute for `InterleaveDataset` on a fixed list of `N` datasets."}},{"name":"Div","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Div` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise."}},{"name":"DivNoNan","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n*NOTE*: `DivNoNan` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if the denominator is zero."}},{"name":"DrawBoundingBoxes","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float16`.","name":"T","type":"type"}],"description":"Outputs a copy of `images` but draws on top of the pixels zero or more bounding\nboxes specified by the locations in `boxes`. The coordinates of the each\nbounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example, if an image is 100 x 200 pixels (height x width) and the bounding\nbox is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of\nthe bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates).\n\nParts of the bounding box may fall outside the image.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`. A batch of images.","name":"images","typeAttr":"T"},{"description":"3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding\nboxes.","name":"boxes","type":1}],"outputs":[{"description":"4-D with the same shape as `images`. The batch of input images with\nbounding boxes drawn on the images.","name":"output","typeAttr":"T"}],"summary":"Draw bounding boxes on a batch of images."}},{"name":"DrawBoundingBoxesV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float16`.","name":"T","type":"type"}],"description":"Outputs a copy of `images` but draws on top of the pixels zero or more bounding\nboxes specified by the locations in `boxes`. The coordinates of the each\nbounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example, if an image is 100 x 200 pixels (height x width) and the bounding\nbox is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of\nthe bounding box will be `(40, 10)` to `(100, 50)` (in (x,y) coordinates).\n\nParts of the bounding box may fall outside the image.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`. A batch of images.","name":"images","typeAttr":"T"},{"description":"3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding\nboxes.","name":"boxes","type":1},{"description":"2-D. A list of RGBA colors to cycle through for the boxes.","name":"colors","type":1}],"outputs":[{"description":"4-D with the same shape as `images`. The batch of input images with\nbounding boxes drawn on the images.","name":"output","typeAttr":"T"}],"summary":"Draw bounding boxes on a batch of images."}},{"name":"DummyIterationCounter","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DummyMemoryCache","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DummySeedGenerator","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DynamicPartition","schema":{"attributes":[{"description":"The number of partitions to output.","minimum":1,"name":"num_partitions","type":"int64"},{"name":"T","type":"type"}],"description":"For each index tuple `js` of size `partitions.ndim`, the slice `data[js, ...]`\nbecomes part of `outputs[partitions[js]]`. The slices with `partitions[js] = i`\nare placed in `outputs[i]` in lexicographic order of `js`, and the first\ndimension of `outputs[i]` is the number of entries in `partitions` equal to `i`.\nIn detail,\n\n```python\n outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]\n\n outputs[i] = pack([data[js, ...] for js if partitions[js] == i])\n```\n\n`data.shape` must start with `partitions.shape`.\n\nFor example:\n\n```python\n # Scalar partitions.\n partitions = 1\n num_partitions = 2\n data = [10, 20]\n outputs[0] = [] # Empty with shape [0, 2]\n outputs[1] = [[10, 20]]\n\n # Vector partitions.\n partitions = [0, 0, 1, 1, 0]\n num_partitions = 2\n data = [10, 20, 30, 40, 50]\n outputs[0] = [10, 20, 50]\n outputs[1] = [30, 40]\n```\n\nSee `dynamic_stitch` for an example on how to merge partitions back.\n\n
\n\n
","inputs":[{"name":"data","typeAttr":"T"},{"description":"Any shape. Indices in the range `[0, num_partitions)`.","name":"partitions","type":3}],"outputs":[{"name":"outputs","numberAttr":"num_partitions","typeAttr":"T"}],"summary":"Partitions `data` into `num_partitions` tensors using indices from `partitions`."}},{"name":"DynamicStitch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Builds a merged tensor such that\n\n```python\n merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]\n```\n\nFor example, if each `indices[m]` is scalar or vector, we have\n\n```python\n # Scalar indices:\n merged[indices[m], ...] = data[m][...]\n\n # Vector indices:\n merged[indices[m][i], ...] = data[m][i, ...]\n```\n\nEach `data[i].shape` must start with the corresponding `indices[i].shape`,\nand the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we\nmust have `data[i].shape = indices[i].shape + constant`. In terms of this\n`constant`, the output shape is\n\n merged.shape = [max(indices)] + constant\n\nValues are merged in order, so if an index appears in both `indices[m][i]` and\n`indices[n][j]` for `(m,i) < (n,j)` the slice `data[n][j]` will appear in the\nmerged result. If you do not need this guarantee, ParallelDynamicStitch might\nperform better on some devices.\n\nFor example:\n\n```python\n indices[0] = 6\n indices[1] = [4, 1]\n indices[2] = [[5, 2], [0, 3]]\n data[0] = [61, 62]\n data[1] = [[41, 42], [11, 12]]\n data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]\n merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],\n [51, 52], [61, 62]]\n```\n\nThis method can be used to merge partitions created by `dynamic_partition`\nas illustrated on the following example:\n\n```python\n # Apply function (increments x_i) on elements for which a certain condition\n # apply (x_i != -1 in this example).\n x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4])\n condition_mask=tf.not_equal(x,tf.constant(-1.))\n partitioned_data = tf.dynamic_partition(\n x, tf.cast(condition_mask, tf.int32) , 2)\n partitioned_data[1] = partitioned_data[1] + 1.0\n condition_indices = tf.dynamic_partition(\n tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)\n x = tf.dynamic_stitch(condition_indices, partitioned_data)\n # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain\n # unchanged.\n```\n\n
\n\n
","inputs":[{"name":"indices","numberAttr":"N","type":3},{"name":"data","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"merged","typeAttr":"T"}],"summary":"Interleave the values from the `data` tensors into a single tensor."}},{"name":"EagerPyFunc","schema":{"attributes":[{"name":"token","type":"string"},{"default":false,"name":"is_async","type":"boolean"},{"minimum":0,"name":"Tin","type":"type[]"},{"minimum":0,"name":"Tout","type":"type[]"}],"description":"semantics of the input, output, and attributes are the same as those for\nPyFunc.","inputs":[{"name":"input","typeListAttr":"Tin"}],"outputs":[{"name":"output","typeListAttr":"Tout"}],"summary":"Eagerly executes a python function to compute func(input)->output. The"}},{"name":"EditDistance","schema":{"attributes":[{"default":true,"description":"boolean (if true, edit distances are normalized by length of truth).\n\nThe output is:","name":"normalize","type":"boolean"},{"name":"T","type":"type"}],"description":"The inputs are variable-length sequences provided by SparseTensors\n (hypothesis_indices, hypothesis_values, hypothesis_shape)\nand\n (truth_indices, truth_values, truth_shape).\n\nThe inputs are:","inputs":[{"description":"The indices of the hypothesis list SparseTensor.\nThis is an N x R int64 matrix.","name":"hypothesis_indices","type":9},{"description":"The values of the hypothesis list SparseTensor.\nThis is an N-length vector.","name":"hypothesis_values","typeAttr":"T"},{"description":"The shape of the hypothesis list SparseTensor.\nThis is an R-length vector.","name":"hypothesis_shape","type":9},{"description":"The indices of the truth list SparseTensor.\nThis is an M x R int64 matrix.","name":"truth_indices","type":9},{"description":"The values of the truth list SparseTensor.\nThis is an M-length vector.","name":"truth_values","typeAttr":"T"},{"description":"truth indices, vector.","name":"truth_shape","type":9}],"outputs":[{"description":"A dense float tensor with rank R - 1.\n\nFor the example input:\n\n // hypothesis represents a 2x1 matrix with variable-length values:\n // (0,0) = [\"a\"]\n // (1,0) = [\"b\"]\n hypothesis_indices = [[0, 0, 0],\n [1, 0, 0]]\n hypothesis_values = [\"a\", \"b\"]\n hypothesis_shape = [2, 1, 1]\n\n // truth represents a 2x2 matrix with variable-length values:\n // (0,0) = []\n // (0,1) = [\"a\"]\n // (1,0) = [\"b\", \"c\"]\n // (1,1) = [\"a\"]\n truth_indices = [[0, 1, 0],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0]]\n truth_values = [\"a\", \"b\", \"c\", \"a\"]\n truth_shape = [2, 2, 2]\n normalize = true\n\nThe output will be:\n\n // output is a 2x2 matrix with edit distances normalized by truth lengths.\n output = [[inf, 1.0], // (0,0): no truth, (0,1): no hypothesis\n [0.5, 1.0]] // (1,0): addition, (1,1): no hypothesis","name":"output","type":1}],"summary":"Computes the (possibly normalized) Levenshtein Edit Distance."}},{"name":"Eig","schema":{"attributes":[{"default":true,"description":"If `True` then eigenvectors will be computed and returned in `v`.\nOtherwise, only the eigenvalues will be computed.","name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"},{"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tout","type":"type"}],"description":"Computes the eigenvalues and (optionally) right eigenvectors of each inner matrix in\n`input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues\nare sorted in non-decreasing order.\n\n```python\n# a is a tensor.\n# e is a tensor of eigenvalues.\n# v is a tensor of eigenvectors.\ne, v = eig(a)\ne = eig(a, compute_v=False)\n```","inputs":[{"description":"`Tensor` input of shape `[N, N]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Eigenvalues. Shape is `[N]`.","name":"e","typeAttr":"Tout"},{"description":"Eigenvectors. Shape is `[N, N]`.","name":"v","typeAttr":"Tout"}],"summary":"Computes the eigen decomposition of one or more square matrices."}},{"name":"Einsum","schema":{"attributes":[{"description":"String describing the Einstein Summation operation; in the format of np.einsum.","name":"equation","type":"string"},{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Implements generalized Tensor contraction and reduction. Each input Tensor must\nhave a corresponding input subscript appearing in the comma-separated left-hand\nside of the equation. The right-hand side of the equation consists of the\noutput subscript. The input subscripts and the output subscript should consist\nof zero or more named axis labels and at most one ellipsis (`...`).\n\nThe named axis labels may be any single character other than those having\nspecial meaning, namely `,.->`. The behavior of this Op is undefined if it\nreceives an ill-formatted equation; since the validation is done at\ngraph-building time, we omit format validation checks at runtime.\n\nNote: This Op is *not* intended to be called by the user; instead users should\ncall `tf.einsum` directly. It is a hidden Op used by `tf.einsum`.\n\nOperations are applied to the input(s) according to the following rules:\n\n (a) Generalized Diagonals: For input dimensions corresponding to axis labels\n appearing more than once in the same input subscript, we take the\n generalized (`k`-dimensional) diagonal.\n For example, in the equation `iii->i` with input shape `[3, 3, 3]`, the\n generalized diagonal would consist of `3` elements at indices `(0, 0, 0)`,\n `(1, 1, 1)` and `(2, 2, 2)` to create a Tensor of shape `[3]`.\n\n (b) Reduction: Axes corresponding to labels appearing only in one input\n subscript but not in the output subscript are summed over prior to Tensor\n contraction.\n For example, in the equation `ab,bc->b`, the axis labels `a` and `c` are\n the reduction axis labels.\n\n (c) Batch Dimensions: Axes corresponding to labels appearing in each of the\n input subscripts and also in the output subscript make up the batch\n dimensions in Tensor contraction. Unnamed axis labels corresponding to\n ellipsis (`...`) also correspond to batch dimensions.\n For example, for the equation denoting batch matrix multiplication,\n `bij,bjk->bik`, the axis label `b` corresponds to a batch dimension.\n\n (d) Contraction: In case of binary einsum, axes corresponding to labels\n appearing in two different inputs (and not in the output) are contracted\n against each other.\n Considering the batch matrix multiplication equation again\n (`bij,bjk->bik`), the contracted axis label is `j`.\n\n (e) Expand Diagonal: If the output subscripts contain repeated (explicit) axis\n labels, the opposite operation of (a) is applied. For example, in the\n equation `i->iii`, and input shape `[3]`, the output of shape `[3, 3, 3]`\n are all zeros, except for the (generalized) diagonal which is populated\n with values from the input.\n Note: This operation is not supported by `np.einsum` or `tf.einsum`; it is\n provided to enable computing the symbolic gradient of `tf.einsum`.\n\nThe output subscripts must contain only labels appearing in at least one of the\ninput subscripts. Furthermore, all dimensions mapping to the same axis label\nmust be equal.\n\nAny of the input and output subscripts may contain at most a single ellipsis\n(`...`). These ellipsis are mapped against dimensions not corresponding to any\nnamed axis label. If two inputs contain ellipsis, then they are broadcasted\naccording to standard NumPy broadcasting\n[rules](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).\n\nThe broadcasted dimensions are placed in the corresponding location of the\nellipsis in the output subscript. If the broadcasted dimensions are non-empty\nand the output subscripts do not contain ellipsis, then an InvalidArgument error\nis raised.\n\n@compatibility(numpy)\nSimilar to [`numpy.einsum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html).\n\nComparison with `numpy.einsum`:\n\n * This Op only supports unary and binary forms of `numpy.einsum`.\n * This Op does not support implicit form. (i.e. equations without `->`).\n * This Op also supports repeated indices in the output subscript, which is not\n supported by `numpy.einsum`.\n@end_compatibility\n","inputs":[{"description":"List of 1 or 2 Tensors.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Output Tensor with shape depending upon `equation`.","name":"output","typeAttr":"T"}],"summary":"Tensor contraction according to Einstein summation convention."}},{"name":"Elu","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","description":"See [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)\n](http://arxiv.org/abs/1511.07289)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes exponential linear: `exp(features) - 1` if < 0, `features` otherwise."}},{"name":"EluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Elu operation.","name":"gradients","typeAttr":"T"},{"description":"The outputs of the corresponding Elu operation.","name":"outputs","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients * (outputs + 1)` if outputs < 0,\n`gradients` otherwise.","name":"backprops","typeAttr":"T"}],"summary":"Computes gradients for the exponential linear (Elu) operation."}},{"name":"Empty","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":false,"description":"If True, initialize the returned tensor with the default value of dtype. Otherwise, the implementation is free not to initializethe tensor's content.","name":"init","type":"boolean"}],"inputs":[{"description":"1-D. Represents the shape of the output tensor.","name":"shape","type":3}],"outputs":[{"description":"A `Tensor` of type `T`.","name":"output","typeAttr":"dtype"}],"summary":"Creates a tensor with the given shape.\n\nThis operation creates a tensor of `shape` and `dtype`."}},{"name":"EmptyTensorList","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"All list elements must be tensors of dtype element_dtype and shape compatible\nwith element_shape.\n\nhandle: an empty tensor list.\nelement_dtype: the type of elements in the list.\nelement_shape: a shape compatible with that of elements in the list.","inputs":[{"name":"element_shape","typeAttr":"shape_type"},{"name":"max_num_elements","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"Creates and returns an empty tensor list."}},{"name":"EncodeBase64","schema":{"attributes":[{"default":false,"description":"Bool whether padding is applied at the ends.","name":"pad","type":"boolean"}],"description":"Refer to the following article for more information on base64 format:\nen.wikipedia.org/wiki/Base64. Base64 strings may have padding with '=' at the\nend so that the encoded has length multiple of 4. See Padding section of the\nlink above.\n\nWeb-safe means that the encoder uses - and _ instead of + and /.","inputs":[{"description":"Strings to be encoded.","name":"input","type":7}],"outputs":[{"description":"Input strings encoded in base64.","name":"output","type":7}],"summary":"Encode strings into web-safe base64 format."}},{"name":"EncodeJpeg","schema":{"attributes":[{"default":"","description":"Per pixel image format. Must be one of the following: ``, `grayscale`, `rgb`.","name":"format","type":"string"},{"default":95,"description":"Quality of the compression from 0 to 100 (higher is better and slower).","name":"quality","type":"int64"},{"default":false,"description":"If True, create a JPEG that loads progressively (coarse to fine).","name":"progressive","type":"boolean"},{"default":false,"description":"If True, spend CPU/RAM to reduce size with no quality change.","name":"optimize_size","type":"boolean"},{"default":true,"description":"See http://en.wikipedia.org/wiki/Chroma_subsampling.","name":"chroma_downsampling","type":"boolean"},{"default":"in","description":"Unit used to specify `x_density` and `y_density`:\npixels per inch (`'in'`) or centimeter (`'cm'`). Must be one of the following: `in`, `cm`.","name":"density_unit","type":"string"},{"default":300,"description":"Horizontal pixels per density unit.","name":"x_density","type":"int64"},{"default":300,"description":"Vertical pixels per density unit.","name":"y_density","type":"int64"},{"default":"","description":"If not empty, embed this XMP metadata in the image header.","name":"xmp_metadata","type":"string"}],"description":"`image` is a 3-D uint8 Tensor of shape `[height, width, channels]`.\n\nThe attr `format` can be used to override the color format of the encoded\noutput. Values can be:\n\n* `''`: Use a default format based on the number of channels in the image.\n* `grayscale`: Output a grayscale JPEG image. The `channels` dimension\n of `image` must be 1.\n* `rgb`: Output an RGB JPEG image. The `channels` dimension\n of `image` must be 3.\n\nIf `format` is not specified or is the empty string, a default format is picked\nin function of the number of channels in `image`:\n\n* 1: Output a grayscale image.\n* 3: Output an RGB image.","inputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","type":4}],"outputs":[{"description":"0-D. JPEG-encoded image.","name":"contents","type":7}],"summary":"JPEG-encode an image."}},{"name":"EncodeJpegVariableQuality","schema":{"description":"`image` is a 3-D uint8 Tensor of shape `[height, width, channels]`.\n`quality` is an int32 jpeg compression quality value between 0 and 100.\n","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","type":4},{"description":"An int quality to encode to.","name":"quality","type":3}],"outputs":[{"description":"0-D. JPEG-encoded image.","name":"contents","type":7}],"summary":"JPEG encode input image with provided compression quality."}},{"name":"EncodePng","schema":{"attributes":[{"default":-1,"description":"Compression level.","name":"compression","type":"int64"},{"default":{"type":"type","value":4},"description":"Must be one of the following: `uint8`, `uint16`.","name":"T","type":"type"}],"description":"`image` is a 3-D uint8 or uint16 Tensor of shape `[height, width, channels]`\nwhere `channels` is:\n\n* 1: for grayscale.\n* 2: for grayscale + alpha.\n* 3: for RGB.\n* 4: for RGBA.\n\nThe ZLIB compression level, `compression`, can be -1 for the PNG-encoder\ndefault or a value from 0 to 9. 9 is the highest compression level, generating\nthe smallest output, but is slower.","inputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","typeAttr":"T"}],"outputs":[{"description":"0-D. PNG-encoded image.","name":"contents","type":7}],"summary":"PNG-encode an image."}},{"name":"EncodeProto","schema":{"attributes":[{"description":"List of strings containing proto field names.","name":"field_names","type":"string[]"},{"description":"Name of the proto message type to decode.","name":"message_type","type":"string"},{"default":"local://","name":"descriptor_source","type":"string"},{"description":"The input types.","minimum":1,"name":"Tinput_types","type":"type[]"}],"description":"The types of the tensors in `values` must match the schema for the fields\nspecified in `field_names`. All the tensors in `values` must have a common\nshape prefix, *batch_shape*.\n\nThe `sizes` tensor specifies repeat counts for each field. The repeat count\n(last dimension) of a each tensor in `values` must be greater than or equal\nto corresponding repeat count in `sizes`.\n\nA `message_type` name must be provided to give context for the field names.\nThe actual message descriptor can be looked up either in the linked-in\ndescriptor pool or a filename provided by the caller using the\n`descriptor_source` attribute.\n\nFor the most part, the mapping between Proto field types and TensorFlow dtypes\nis straightforward. However, there are a few special cases:\n\n- A proto field that contains a submessage or group can only be converted\nto `DT_STRING` (the serialized submessage). This is to reduce the complexity\nof the API. The resulting string can be used as input to another instance of\nthe decode_proto op.\n\n- TensorFlow lacks support for unsigned integers. The ops represent uint64\ntypes as a `DT_INT64` with the same twos-complement bit pattern (the obvious\nway). Unsigned int32 values can be represented exactly by specifying type\n`DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in\nthe `output_types` attribute.\n\nThe `descriptor_source` attribute selects the source of protocol\ndescriptors to consult when looking up `message_type`. This may be:\n\n- An empty string or \"local://\", in which case protocol descriptors are\ncreated for C++ (not Python) proto definitions linked to the binary.\n\n- A file, in which case protocol descriptors are created from the file,\nwhich is expected to contain a `FileDescriptorSet` serialized as a string.\nNOTE: You can build a `descriptor_source` file using the `--descriptor_set_out`\nand `--include_imports` options to the protocol compiler `protoc`.\n\n- A \"bytes://\", in which protocol descriptors are created from ``,\nwhich is expected to be a `FileDescriptorSet` serialized as a string.","inputs":[{"description":"Tensor of int32 with shape `[batch_shape, len(field_names)]`.","name":"sizes","type":3},{"description":"List of tensors containing values for the corresponding field.","name":"values","typeListAttr":"Tinput_types"}],"outputs":[{"description":"Tensor of serialized protos with shape `batch_shape`.","name":"bytes","type":7}],"summary":"The op serializes protobuf messages provided in the input tensors."}},{"name":"EncodeWav","schema":{"description":"This operation will generate a string suitable to be saved out to create a .wav\naudio file. It will be encoded in the 16-bit PCM format. It takes in float\nvalues in the range -1.0f to 1.0f, and any outside that value will be clamped to\nthat range.\n\n`audio` is a 2-D float Tensor of shape `[length, channels]`.\n`sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100).","inputs":[{"description":"2-D with shape `[length, channels]`.","name":"audio","type":1},{"description":"Scalar containing the sample frequency.","name":"sample_rate","type":3}],"outputs":[{"description":"0-D. WAV-encoded file contents.","name":"contents","type":7}],"summary":"Encode audio data using the WAV file format."}},{"name":"EnqueueTPUEmbeddingIntegerBatch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A list of 1D tensors, one for each embedding table, containing the\nindices into the tables.","name":"batch","numberAttr":"N","type":3},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"An op that enqueues a list of input batch tensors to TPUEmbedding."}},{"name":"EnqueueTPUEmbeddingRaggedTensorBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"},{"description":"A list of integers specifying the identifier of the embedding table\n(offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the\ncorresponding input. The ith input is looked up using table_ids[i]. The size\nof the table_ids list must be equal to that of sample_indices,\nembedding_indices and aggregation_weights.","name":"table_ids","type":"int64[]"},{"default":[],"name":"max_sequence_lengths","type":"int64[]"}],"description":"sample_splits[i], embedding_indices[i] and aggregation_weights[i] correspond\nto the ith feature. table_ids[i] indicates which embedding table to look up ith\nfeature.\n\nThe tensors at corresponding positions in two of the input lists,\nembedding_indices and aggregation_weights, must have the same shape, i.e. rank 1\nwith dim_size() equal to the total number of lookups into the table described by\nthe corresponding feature.","inputs":[{"description":"A list of rank 1 Tensors specifying the break points for splitting\nembedding_indices and aggregation_weights into rows.\nIt corresponds to ids.row_splits in embedding_lookup(), when ids is a\nRaggedTensor.","name":"sample_splits","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.\nIt corresponds to ids.values in embedding_lookup(), when ids is a RaggedTensor.","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per training example\naggregation weights. It corresponds to the values field of a RaggedTensor\nwith the same row_splits as ids in embedding_lookup(), when ids is a\nRaggedTensor.","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"Eases the porting of code that uses tf.nn.embedding_lookup()."}},{"name":"EnqueueTPUEmbeddingSparseBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"}],"description":"This Op eases the porting of code that uses embedding_lookup_sparse(),\nalthough some Python preprocessing of the SparseTensor arguments to\nembedding_lookup_sparse() is required to produce the arguments to this Op,\nsince only a single EnqueueTPUEmbeddingSparseBatch Op is allowed per training\nstep.\n\nThe tensors at corresponding positions in the three input lists\nmust have the same shape, i.e. rank 1 with dim_size() equal to the total\nnumber of lookups into the table described by the corresponding table_id.","inputs":[{"description":"A list of rank 1 Tensors specifying the training example and\nfeature to which the corresponding embedding_indices and aggregation_weights\nvalues belong. sample_indices[i] must equal b * nf + f, where nf is the\nnumber of features from the corresponding table, f is in [0, nf), and\nb is in [0, batch size).","name":"sample_indices","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per sample -- i.e. per\n(training example, feature) -- aggregation weights.","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"An op that enqueues TPUEmbedding input indices from a SparseTensor."}},{"name":"EnqueueTPUEmbeddingSparseTensorBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"},{"description":"A list of integers specifying the identifier of the embedding table\n(offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the\ncorresponding input. The ith input is looked up using table_ids[i]. The size\nof the table_ids list must be equal to that of sample_indices,\nembedding_indices and aggregation_weights.","name":"table_ids","type":"int64[]"},{"default":[],"name":"max_sequence_lengths","type":"int64[]"}],"description":"sample_indices[i], embedding_indices[i] and aggregation_weights[i] correspond\nto the ith feature. table_ids[i] indicates which embedding table to look up ith\nfeature.\n\nThe tensors at corresponding positions in the three input lists (sample_indices,\nembedding_indices and aggregation_weights) must have the same shape, i.e. rank 1\nwith dim_size() equal to the total number of lookups into the table described by\nthe corresponding feature.","inputs":[{"description":"A list of rank 1 Tensors specifying the training example to\nwhich the corresponding embedding_indices and aggregation_weights values\nbelong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse().","name":"sample_indices","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.\nIt corresponds to sp_ids.values in embedding_lookup_sparse().","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per training example\naggregation weights. It corresponds to sp_weights.values in\nembedding_lookup_sparse().","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"Eases the porting of code that uses tf.nn.embedding_lookup_sparse()."}},{"name":"EnsureShape","schema":{"attributes":[{"description":"The expected (possibly partially specified) shape of the input tensor.","name":"shape","type":"shape"},{"name":"T","type":"type"}],"description":"Raises an error if the input tensor's shape does not match the specified shape.\nReturns the input tensor otherwise.","inputs":[{"description":"A tensor, whose shape is to be validated.","name":"input","typeAttr":"T"}],"outputs":[{"description":"A tensor with the same shape and contents as the input tensor or value.","name":"output","typeAttr":"T"}],"summary":"Ensures that the tensor's shape matches the expected shape."}},{"name":"Enter","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the child frame.","name":"frame_name","type":"string"},{"default":false,"description":"If true, the output is constant within the child frame.","name":"is_constant","type":"boolean"},{"default":10,"description":"The number of iterations allowed to run in parallel.","name":"parallel_iterations","type":"int64"}],"description":"This op is used together with `Exit` to create loops in the graph.\nThe unique `frame_name` is used by the `Executor` to identify frames. If\n`is_constant` is true, `output` is a constant in the child frame; otherwise\nit may be changed in the child frame. At most `parallel_iterations` iterations\nare run in parallel in the child frame.","inputs":[{"description":"The tensor to be made available to the child frame.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Creates or finds a child frame, and makes `data` available to the child frame."}},{"name":"Equal","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `uint16`, `uint32`, `uint64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"incompatible_shape_error","type":"boolean"}],"description":"*NOTE*: `Equal` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\n```python\nx = tf.constant([2, 4])\ny = tf.constant(2)\ntf.math.equal(x, y) ==> array([True, False])\n\nx = tf.constant([2, 4])\ny = tf.constant([2, 4])\ntf.math.equal(x, y) ==> array([True, True])\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x == y) element-wise."}},{"name":"Erf","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the Gauss error function of `x` element-wise."}},{"name":"Erfc","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the complementary error function of `x` element-wise."}},{"name":"Erfinv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"EuclideanNorm","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the euclidean norm of elements across dimensions of a tensor."}},{"name":"Exit","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Exit makes its input `data` available to the parent frame.","inputs":[{"description":"The tensor to be made available to the parent frame.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Exits the current frame to its parent frame."}},{"name":"Exp","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" This function computes the exponential of every element in the input tensor.\n i.e. `exp(x)` or `e^(x)`, where `x` is the input tensor.\n `e` denotes Euler's number and is approximately equal to 2.718281.\n Output is positive for any real input.\n\n ```python\n x = tf.constant(2.0)\n tf.math.exp(x) ==> 7.389056\n\n x = tf.constant([2.0, 8.0])\n tf.math.exp(x) ==> array([7.389056, 2980.958], dtype=float32)\n ```\n\n For complex numbers, the exponential value is calculated as follows:\n\n ```\n e^(x+iy) = e^x * e^iy = e^x * (cos y + i sin y)\n ```\n\n Let's consider complex number 1+1j as an example.\n e^1 * (cos 1 + i sin 1) = 2.7182818284590 * (0.54030230586+0.8414709848j)\n\n ```python\n x = tf.constant(1 + 1j)\n tf.math.exp(x) ==> 1.4686939399158851+2.2873552871788423j\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes exponential of x element-wise. \\\\(y = e^x\\\\)."}},{"name":"ExpandDims","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tdim","type":"type"}],"description":"Given a tensor `input`, this operation inserts a dimension of 1 at the\ndimension index `dim` of `input`'s shape. The dimension index `dim` starts at\nzero; if you specify a negative number for `dim` it is counted backward from\nthe end.\n\nThis operation is useful if you want to add a batch dimension to a single\nelement. For example, if you have a single image of shape `[height, width,\nchannels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`,\nwhich will make the shape `[1, height, width, channels]`.\n\nOther examples:\n\n```\n# 't' is a tensor of shape [2]\nshape(expand_dims(t, 0)) ==> [1, 2]\nshape(expand_dims(t, 1)) ==> [2, 1]\nshape(expand_dims(t, -1)) ==> [2, 1]\n\n# 't2' is a tensor of shape [2, 3, 5]\nshape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]\nshape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]\nshape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]\n```\n\nThis operation requires that:\n\n`-1-input.dims() <= dim <= input.dims()`\n\nThis operation is related to `squeeze()`, which removes dimensions of\nsize 1.","inputs":[{"name":"input","typeAttr":"T"},{"description":"0-D (scalar). Specifies the dimension index at which to\nexpand the shape of `input`. Must be in the range\n`[-rank(input) - 1, rank(input)]`.","name":"dim","typeAttr":"Tdim"}],"outputs":[{"description":"Contains the same data as `input`, but its shape has an additional\ndimension of size 1 added.","name":"output","typeAttr":"T"}],"summary":"Inserts a dimension of 1 into a tensor's shape."}},{"name":"ExperimentalAssertNextDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"transformations","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalAutoShardDataset","schema":{"attributes":[{"default":0,"name":"auto_shard_policy","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that shards the input dataset by num_workers, returning a\nsharded dataset for the index-th worker. This attempts to automatically shard\na dataset by examining the Dataset graph and inserting a shard op before the\ninputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset).\n\nThis dataset will throw a NotFound error if we cannot shard the dataset\nautomatically.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of workers to distribute this dataset across.","name":"num_workers","type":9},{"description":"A scalar representing the index of the current worker out of num_workers.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shards the input dataset."}},{"name":"ExperimentalBytesProducedStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the bytes size of each element of `input_dataset` in a StatsAggregator."}},{"name":"ExperimentalCSVDataset","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalChooseFastestDataset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"num_experiments","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalDatasetCardinality","schema":{"description":"Returns the cardinality of `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return cardinality for.","name":"input_dataset","type":21}],"outputs":[{"description":"The cardinality of `input_dataset`. Named constants are used to represent\ninfinite and unknown cardinality.","name":"cardinality","type":9}],"summary":"Returns the cardinality of `input_dataset`."}},{"name":"ExperimentalDatasetToTFRecord","schema":{"inputs":[{"description":"A variant tensor representing the dataset to write.","name":"input_dataset","type":21},{"description":"A scalar string tensor representing the filename to use.","name":"filename","type":7},{"description":"A scalar string tensor containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7}],"summary":"Writes the given dataset to the given file using the TFRecord format."}},{"name":"ExperimentalDenseToSparseBatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to an input dataset. Must have a single component.","name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A vector representing the dense shape of each row in the produced\nSparseTensor. The shape may be partially specified, using `-1` to indicate\nthat a particular dimension should use the maximum size of all batch elements.","name":"row_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches input elements into a SparseTensor."}},{"name":"ExperimentalDirectedInterleaveDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A dataset of scalar `DT_INT64` elements that determines which of the\n`N` data inputs should produce the next output element.","name":"selector_input_dataset","type":21},{"description":"`N` datasets with the same type that will be interleaved according to\nthe values of `selector_input_dataset`.","name":"data_input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A substitute for `InterleaveDataset` on a fixed list of `N` datasets."}},{"name":"ExperimentalGroupByReducerDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"description":"A function mapping a key of type DT_INT64, concatenated with\n`init_func_other_arguments` to the initial reducer state.","name":"init_func","type":"function"},{"description":"A function mapping the current reducer state and an element of `input_dataset`,\nconcatenated with `reduce_func_other_arguments` to a new reducer state.","name":"reduce_func","type":"function"},{"description":"A function mapping the final reducer state to an output element.","name":"finalize_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tinit_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that computes a group-by on `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `key_func`.","name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `init_func`.","name":"init_func_other_arguments","typeListAttr":"Tinit_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `reduce_func`.","name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `finalize_func`.","name":"finalize_func_other_arguments","typeListAttr":"Tfinalize_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a group-by on `input_dataset`."}},{"name":"ExperimentalGroupByWindowDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"name":"reduce_func","type":"function"},{"name":"window_size_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Twindow_size_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"// TODO(mrry): Support non-int64 keys.","inputs":[{"name":"input_dataset","type":21},{"name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"name":"window_size_func_other_arguments","typeListAttr":"Twindow_size_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a windowed group-by on `input_dataset`."}},{"name":"ExperimentalIgnoreErrorsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the elements of `input_dataset` ignoring errors."}},{"name":"ExperimentalIteratorGetDevice","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"name":"device","type":7}],"summary":"Returns the name of the device on which `resource` has been placed."}},{"name":"ExperimentalLMDBDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalLatencyStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the latency of producing `input_dataset` elements in a StatsAggregator."}},{"name":"ExperimentalMapAndBatchDataset","schema":{"attributes":[{"description":"A function to apply to the outputs of `input_dataset`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Creates a dataset that applies `f` to the outputs of `input_dataset` and then\nbatches `batch_size` of them.\n\nUnlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `batch_size * num_parallel_batches` copies of `f` in parallel.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when building a closure\nfor `f`.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"A scalar representing the number of elements to accumulate in a\nbatch. It determines the number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"batch_size","type":9},{"description":"A scalar representing the maximum number of parallel invocations of the `map_fn`\nfunction. Applying the `map_fn` on consecutive input elements in parallel has\nthe potential to improve input pipeline throughput.","name":"num_parallel_calls","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that fuses mapping with batching."}},{"name":"ExperimentalMapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ExperimentalMatchingFilesDataset","schema":{"inputs":[{"name":"patterns","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalMaxIntraOpParallelismDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the maximum intra-op parallelism to use.","name":"max_intra_op_parallelism","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that overrides the maximum intra-op parallelism."}},{"name":"ExperimentalNonSerializableDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalParallelInterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! This dataset is not deterministic!","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9},{"name":"sloppy","type":10},{"name":"buffer_output_elements","type":9},{"name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ExperimentalParseExampleDataset","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ExperimentalPrivateThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the number of threads to use for the private threadpool.","name":"num_threads","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalRandomDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar seed for the random number generator. If either seed or\nseed2 is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a Dataset that returns pseudorandom numbers."}},{"name":"ExperimentalRebatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_fallback","type":"boolean"}],"description":"Creates a dataset that changes the batch size of the dataset to current batch\nsize // num_replicas.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of replicas to distribute this batch across. As\na result of this transformation the current batch size would end up being\ndivided by this parameter.","name":"num_replicas","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"ExperimentalScanDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset successively reduces `f` over the elements of `input_dataset`."}},{"name":"ExperimentalSetStatsAggregatorDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"stats_aggregator","type":20},{"name":"tag","type":7},{"name":"counter_prefix","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalSleepDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"sleep_microseconds","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalSlidingWindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements in the\nsliding window.","name":"window_size","type":9},{"description":"A scalar representing the steps moving the sliding window\nforward in one iteration. It must be positive.","name":"window_shift","type":9},{"description":"A scalar representing the stride of the input elements of the sliding window.\nIt must be positive.","name":"window_stride","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that passes a sliding window over `input_dataset`."}},{"name":"ExperimentalSqlDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"The database type. Currently, the only supported type is 'sqlite'.","name":"driver_name","type":7},{"description":"A connection string to connect to the database.","name":"data_source_name","type":7},{"description":"A SQL query to execute.","name":"query","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that executes a SQL query and emits rows of the result set."}},{"name":"ExperimentalStatsAggregatorHandle","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}],"summary":"Creates a statistics manager resource."}},{"name":"ExperimentalStatsAggregatorSummary","schema":{"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"summary","type":7}],"summary":"Produces a summary of any statistics recorded by the given statistics manager."}},{"name":"ExperimentalTakeWhileDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that stops iteration when predicate` is false."}},{"name":"ExperimentalThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A resource produced by the ThreadPoolHandle op.","name":"thread_pool","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalThreadPoolHandle","schema":{"attributes":[{"description":"The number of threads in the thread pool.","name":"num_threads","type":"int64"},{"default":1,"description":"The maximum degree of parallelism to use within operations that execute on this\nthreadpool.","name":"max_intra_op_parallelism","type":"int64"},{"description":"A human-readable name for the threads that may be visible in some\nvisualizations.\nthreadpool.","name":"display_name","type":"string"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"description":"A resource that can be consumed by one or more ExperimentalThreadPoolDataset\nops.","name":"handle","type":20}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalUnbatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A dataset that splits the elements of its input into multiple elements."}},{"name":"ExperimentalUniqueDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the unique elements of `input_dataset`."}},{"name":"Expint","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Expm1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" i.e. `exp(x) - 1` or `e^(x) - 1`, where `x` is the input tensor.\n `e` denotes Euler's number and is approximately equal to 2.718281.\n\n ```python\n x = tf.constant(2.0)\n tf.math.expm1(x) ==> 6.389056\n\n x = tf.constant([2.0, 8.0])\n tf.math.expm1(x) ==> array([6.389056, 2979.958], dtype=float32)\n\n x = tf.constant(1 + 1j)\n tf.math.expm1(x) ==> (0.46869393991588515+2.2873552871788423j)\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes `exp(x) - 1` element-wise."}},{"name":"ExtractGlimpse","schema":{"attributes":[{"default":true,"description":"indicates if the offset coordinates are centered relative to\nthe image, in which case the (0, 0) offset is relative to the center\nof the input images. If false, the (0,0) offset corresponds to the\nupper left corner of the input images.","name":"centered","type":"boolean"},{"default":true,"description":"indicates if the offset coordinates are normalized.","name":"normalized","type":"boolean"},{"default":true,"description":"indicates if the noise should be generated using a\nuniform distribution or a Gaussian distribution.","name":"uniform_noise","type":"boolean"},{"default":"uniform","description":"indicates if the noise should `uniform`, `gaussian`, or\n`zero`. The default is `uniform` which means the the noise type\nwill be decided by `uniform_noise`.","name":"noise","type":"string"}],"description":"Returns a set of windows called glimpses extracted at location\n`offsets` from the input tensor. If the windows only partially\noverlaps the inputs, the non overlapping areas will be filled with\nrandom noise.\n\nThe result is a 4-D tensor of shape `[batch_size, glimpse_height,\nglimpse_width, channels]`. The channels and batch dimensions are the\nsame as that of the input tensor. The height and width of the output\nwindows are specified in the `size` parameter.\n\nThe argument `normalized` and `centered` controls how the windows are built:\n\n* If the coordinates are normalized but not centered, 0.0 and 1.0\n correspond to the minimum and maximum of each height and width\n dimension.\n* If the coordinates are both normalized and centered, they range from\n -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper\n left corner, the lower right corner is located at (1.0, 1.0) and the\n center is at (0, 0).\n* If the coordinates are not normalized they are interpreted as\n numbers of pixels.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, height, width, channels]`.","name":"input","type":1},{"description":"A 1-D tensor of 2 elements containing the size of the glimpses\nto extract. The glimpse height must be specified first, following\nby the glimpse width.","name":"size","type":3},{"description":"A 2-D integer tensor of shape `[batch_size, 2]` containing\nthe y, x locations of the center of each window.","name":"offsets","type":1}],"outputs":[{"description":"A tensor representing the glimpses `[batch_size,\nglimpse_height, glimpse_width, channels]`.","name":"glimpse","type":1}],"summary":"Extracts a glimpse from the input tensor."}},{"name":"ExtractGlimpseV2","schema":{"attributes":[{"default":true,"description":"indicates if the offset coordinates are centered relative to\nthe image, in which case the (0, 0) offset is relative to the center\nof the input images. If false, the (0,0) offset corresponds to the\nupper left corner of the input images.","name":"centered","type":"boolean"},{"default":true,"description":"indicates if the offset coordinates are normalized.","name":"normalized","type":"boolean"},{"default":true,"description":"indicates if the noise should be generated using a\nuniform distribution or a Gaussian distribution.","name":"uniform_noise","type":"boolean"},{"default":"uniform","description":"indicates if the noise should `uniform`, `gaussian`, or\n`zero`. The default is `uniform` which means the the noise type\nwill be decided by `uniform_noise`.","name":"noise","type":"string"}],"description":"Returns a set of windows called glimpses extracted at location\n`offsets` from the input tensor. If the windows only partially\noverlaps the inputs, the non overlapping areas will be filled with\nrandom noise.\n\nThe result is a 4-D tensor of shape `[batch_size, glimpse_height,\nglimpse_width, channels]`. The channels and batch dimensions are the\nsame as that of the input tensor. The height and width of the output\nwindows are specified in the `size` parameter.\n\nThe argument `normalized` and `centered` controls how the windows are built:\n\n* If the coordinates are normalized but not centered, 0.0 and 1.0\n correspond to the minimum and maximum of each height and width\n dimension.\n* If the coordinates are both normalized and centered, they range from\n -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper\n left corner, the lower right corner is located at (1.0, 1.0) and the\n center is at (0, 0).\n* If the coordinates are not normalized they are interpreted as\n numbers of pixels.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, height, width, channels]`.","name":"input","type":1},{"description":"A 1-D tensor of 2 elements containing the size of the glimpses\nto extract. The glimpse height must be specified first, following\nby the glimpse width.","name":"size","type":3},{"description":"A 2-D integer tensor of shape `[batch_size, 2]` containing\nthe y, x locations of the center of each window.","name":"offsets","type":1}],"outputs":[{"description":"A tensor representing the glimpses `[batch_size,\nglimpse_height, glimpse_width, channels]`.","name":"glimpse","type":1}],"summary":"Extracts a glimpse from the input tensor."}},{"name":"ExtractImagePatches","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `images`.","minimum":4,"name":"ksizes","type":"int64[]"},{"description":"How far the centers of two consecutive patches are in\nthe images. Must be: `[1, stride_rows, stride_cols, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"Must be: `[1, rate_rows, rate_cols, 1]`. This is the\ninput stride, specifying how far two consecutive patch samples are in the\ninput. Equivalent to extracting patches with\n`patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by\nsubsampling them spatially by a factor of `rates`. This is equivalent to\n`rate` in dilated (a.k.a. Atrous) convolutions.","minimum":4,"name":"rates","type":"int64[]"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`, `bool`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D Tensor with shape `[batch, in_rows, in_cols, depth]`.","name":"images","typeAttr":"T"}],"outputs":[{"description":"4-D Tensor with shape `[batch, out_rows, out_cols, ksize_rows *\nksize_cols * depth]` containing image patches with size\n`ksize_rows x ksize_cols x depth` vectorized in the \"depth\" dimension. Note\n`out_rows` and `out_cols` are the dimensions of the output patches.","name":"patches","typeAttr":"T"}],"summary":"Extract `patches` from `images` and put them in the \"depth\" output dimension."}},{"name":"ExtractJpegShape","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"(Optional) The output type of the operation (int32 or int64).\nDefaults to int32. Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"This op only parses the image header, so it is much faster than DecodeJpeg.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"1-D. The image shape with format [height, width, channels].","name":"image_shape","typeAttr":"output_type"}],"summary":"Extract the shape information of a JPEG-encoded image."}},{"name":"ExtractVolumePatches","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `input`.","minimum":5,"name":"ksizes","type":"int64[]"},{"description":"1-D of length 5. How far the centers of two consecutive patches are in\n`input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use.\n\nThe size-related attributes are specified as follows:\n\n```python\nksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1]\nstrides = [1, stride_planes, strides_rows, strides_cols, 1]\n``` Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"5-D Tensor with shape `[batch, out_planes, out_rows, out_cols,\nksize_planes * ksize_rows * ksize_cols * depth]` containing patches\nwith size `ksize_planes x ksize_rows x ksize_cols x depth` vectorized\nin the \"depth\" dimension. Note `out_planes`, `out_rows` and `out_cols`\nare the dimensions of the output patches.","name":"patches","typeAttr":"T"}],"summary":"Extract `patches` from `input` and put them in the `\"depth\"` output dimension. 3D extension of `extract_image_patches`."}},{"name":"FFT","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 1-dimensional discrete Fourier transform over the inner-most\ndimension of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Fast Fourier transform."}},{"name":"FFT2D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 2-dimensional discrete Fourier transform over the inner-most\n2 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"2D fast Fourier transform."}},{"name":"FFT3D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 3-dimensional discrete Fourier transform over the inner-most 3\ndimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"3D fast Fourier transform."}},{"name":"FIFOQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"FIFOQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"Fact","schema":{"outputs":[{"name":"fact","type":7}],"summary":"Output a fact about factorials."}},{"name":"FakeParam","schema":{"attributes":[{"description":"The type of the output.","name":"dtype","type":"type"},{"description":" The purported shape of the output. This is only used for shape inference;\n the output will not necessarily have this shape. Can be a partial shape.","name":"shape","type":"shape"}],"outputs":[{"description":" \\\"Fake\\\" output value. This should not be consumed by another op.","name":"output","typeAttr":"dtype"}],"summary":" This op is used as a placeholder in If branch functions. It doesn't provide a\n valid output when run, so must either be removed (e.g. replaced with a\n function input) or guaranteed not to be used (e.g. if mirroring an\n intermediate output needed for the gradient computation of the other branch)."}},{"name":"FakeQuantWithMinMaxArgs","schema":{"attributes":[{"default":-6,"name":"min","type":"float32"},{"default":6,"name":"max","type":"float32"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Attributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nQuantization is called fake since the output is still in floating point.","inputs":[{"name":"inputs","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type."}},{"name":"FakeQuantWithMinMaxArgsGradient","schema":{"attributes":[{"default":-6,"name":"min","type":"float32"},{"default":6,"name":"max","type":"float32"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxArgs operation.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxArgs operation.","name":"inputs","type":1}],"outputs":[{"description":"Backpropagated gradients below the FakeQuantWithMinMaxArgs operation:\n`gradients * (inputs >= min && inputs <= max)`.","name":"backprops","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxArgs operation."}},{"name":"FakeQuantWithMinMaxVars","schema":{"attributes":[{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Fake-quantize the `inputs` tensor of type float via global float scalars\n`min` and `max` to `outputs` tensor of same shape as `inputs`.\n\nAttributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nThis operation has a gradient and thus allows for training `min` and `max`\nvalues.","inputs":[{"name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor of type float via global float scalars"}},{"name":"FakeQuantWithMinMaxVarsGradient","schema":{"attributes":[{"default":8,"description":"The bitwidth of the quantization; between 2 and 8, inclusive.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether to quantize into 2^num_bits - 1 distinct values.","name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxVars operation.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxVars operation.\nmin, max: Quantization interval, scalar floats.","name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"Backpropagated gradients w.r.t. inputs:\n`gradients * (inputs >= min && inputs <= max)`.","name":"backprops_wrt_input","type":1},{"description":"Backpropagated gradients w.r.t. min parameter:\n`sum(gradients * (inputs < min))`.","name":"backprop_wrt_min","type":1},{"description":"Backpropagated gradients w.r.t. max parameter:\n`sum(gradients * (inputs > max))`.","name":"backprop_wrt_max","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxVars operation."}},{"name":"FakeQuantWithMinMaxVarsPerChannel","schema":{"attributes":[{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Fake-quantize the `inputs` tensor of type float per-channel and one of the\nshapes: `[d]`, `[b, d]` `[b, h, w, d]` via per-channel floats `min` and `max`\nof shape `[d]` to `outputs` tensor of same shape as `inputs`.\n\nAttributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nThis operation has a gradient and thus allows for training `min` and `max`\nvalues.","inputs":[{"name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor of type float via per-channel floats"}},{"name":"FakeQuantWithMinMaxVarsPerChannelGradient","schema":{"attributes":[{"default":8,"description":"The bitwidth of the quantization; between 2 and 16, inclusive.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether to quantize into 2^num_bits - 1 distinct values.","name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxVars operation,\nshape one of: `[d]`, `[b, d]`, `[b, h, w, d]`.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape\n same as `gradients`.\nmin, max: Quantization interval, floats of shape `[d]`.","name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"Backpropagated gradients w.r.t. inputs, shape same as\n`inputs`:\n `gradients * (inputs >= min && inputs <= max)`.","name":"backprops_wrt_input","type":1},{"description":"Backpropagated gradients w.r.t. min parameter, shape `[d]`:\n`sum_per_d(gradients * (inputs < min))`.","name":"backprop_wrt_min","type":1},{"description":"Backpropagated gradients w.r.t. max parameter, shape `[d]`:\n`sum_per_d(gradients * (inputs > max))`.","name":"backprop_wrt_max","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation."}},{"name":"FakeQueue","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated. Do not use."}},{"name":"Fill","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"index_type","type":"type"}],"description":"This operation creates a tensor of shape `dims` and fills it with `value`.\n\nFor example:\n\n```\n# Output tensor has shape [2, 3].\nfill([2, 3], 9) ==> [[9, 9, 9]\n [9, 9, 9]]\n```\n\n`tf.fill` differs from `tf.constant` in a few ways:\n\n* `tf.fill` only supports scalar contents, whereas `tf.constant` supports\n Tensor values.\n* `tf.fill` creates an Op in the computation graph that constructs the actual\n Tensor value at runtime. This is in contrast to `tf.constant` which embeds\n the entire Tensor into the graph with a `Const` node.\n* Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes\n based on other runtime Tensors, unlike `tf.constant`.","inputs":[{"description":"1-D. Represents the shape of the output tensor.","name":"dims","typeAttr":"index_type"},{"description":"0-D (scalar). Value to fill the returned tensor.\n\n@compatibility(numpy)\nEquivalent to np.full\n@end_compatibility","name":"value","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Creates a tensor filled with a scalar value."}},{"name":"FilterByLastComponentDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"output","type":21}],"summary":"Creates a dataset containing elements of first component of `input_dataset` having true in the last component."}},{"name":"FilterDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset containing elements of `input_dataset` matching `predicate`."}},{"name":"Fingerprint","schema":{"attributes":[{"description":"This can be a POD-type or string type.","name":"T","type":"type"}],"description":"Generates fingerprint values of `data`.\n\nFingerprint op considers the first dimension of `data` as the batch dimension,\nand `output[i]` contains the fingerprint value generated from contents in\n`data[i, ...]` for all `i`.\n\nFingerprint op writes fingerprint values as byte arrays. For example, the\ndefault method `farmhash64` generates a 64-bit fingerprint value at a time.\nThis 8-byte value is written out as an `uint8` array of size 8, in little-endian\norder.\n\nFor example, suppose that `data` has data type `DT_INT32` and shape (2, 3, 4),\nand that the fingerprint method is `farmhash64`. In this case, the output shape\nis (2, 8), where 2 is the batch dimension size of `data`, and 8 is the size of\neach fingerprint value in bytes. `output[0, :]` is generated from 12 integers in\n`data[0, :, :]` and similarly `output[1, :]` is generated from other 12 integers\nin `data[1, :, :]`.\n\nNote that this op fingerprints the raw underlying buffer, and it does not\nfingerprint Tensor's metadata such as data type and/or shape. For example, the\nfingerprint values are invariant under reshapes and bitcasts as long as the\nbatch dimension remain the same:\n\n```\nFingerprint(data) == Fingerprint(Reshape(data, ...))\nFingerprint(data) == Fingerprint(Bitcast(data, ...))\n```\n\nFor string data, one should expect `Fingerprint(data) !=\nFingerprint(ReduceJoin(data))` in general.","inputs":[{"description":"Must have rank 1 or higher.","name":"data","typeAttr":"T"},{"description":"Fingerprint method used by this op. Currently available method is\n`farmhash::fingerprint64`.","name":"method","type":7}],"outputs":[{"description":"A two-dimensional `Tensor` of type `tf.uint8`. The first dimension equals to\n`data`'s first dimension, and the second dimension size depends on the\nfingerprint algorithm.","name":"fingerprint","type":4}],"summary":"Generates fingerprint values."}},{"name":"FixedLengthRecordDataset","schema":{"inputs":[{"description":"A scalar or a vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar representing the number of bytes to skip at the\nbeginning of a file.","name":"header_bytes","type":9},{"description":"A scalar representing the number of bytes in each record.","name":"record_bytes","type":9},{"description":"A scalar representing the number of bytes to skip at the end\nof a file.","name":"footer_bytes","type":9},{"description":"A scalar representing the number of bytes to buffer. Must be > 0.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the records from one or more binary files."}},{"name":"FixedLengthRecordDatasetV2","schema":{"inputs":[{"name":"filenames","type":7},{"name":"header_bytes","type":9},{"name":"record_bytes","type":9},{"name":"footer_bytes","type":9},{"name":"buffer_size","type":9},{"name":"compression_type","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"FixedLengthRecordReader","schema":{"attributes":[{"default":0,"description":"Number of bytes in the header, defaults to 0.","name":"header_bytes","type":"int64"},{"description":"Number of bytes in the record.","name":"record_bytes","type":"int64"},{"default":0,"description":"Number of bytes in the footer, defaults to 0.","name":"footer_bytes","type":"int64"},{"default":0,"description":"Number of bytes to hop before each read. Default of 0 means using\nrecord_bytes.","name":"hop_bytes","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs fixed-length records from a file."}},{"name":"FixedLengthRecordReaderV2","schema":{"attributes":[{"default":0,"description":"Number of bytes in the header, defaults to 0.","name":"header_bytes","type":"int64"},{"description":"Number of bytes in the record.","name":"record_bytes","type":"int64"},{"default":0,"description":"Number of bytes in the footer, defaults to 0.","name":"footer_bytes","type":"int64"},{"default":0,"description":"Number of bytes to hop before each read. Default of 0 means using\nrecord_bytes.","name":"hop_bytes","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","description":"The type of encoding for the file. Currently ZLIB and GZIP\nare supported. Defaults to none.","name":"encoding","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs fixed-length records from a file."}},{"name":"FixedUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":"","description":"Each valid line in this file (which should have a CSV-like format)\ncorresponds to a valid word ID. IDs are in sequential order, starting from\nnum_reserved_ids. The last entry in each line is expected to be a value\ncorresponding to the count or relative probability. Exactly one of vocab_file\nand unigrams needs to be passed to this op.","name":"vocab_file","type":"string"},{"default":1,"description":"The distortion is used to skew the unigram probability distribution.\nEach weight is first raised to the distortion's power before adding to the\ninternal unigram distribution. As a result, distortion = 1.0 gives regular\nunigram sampling (as defined by the vocab file), and distortion = 0.0 gives\na uniform distribution.","name":"distortion","type":"float32"},{"default":0,"description":"Optionally some reserved IDs can be added in the range [0,\n..., num_reserved_ids) by the users. One use case is that a special unknown\nword token is used as ID 0. These IDs will have a sampling probability of 0.","name":"num_reserved_ids","type":"int64"},{"default":1,"description":"A sampler can be used to sample from a subset of the original range\nin order to speed up the whole computation through parallelism. This parameter\n(together with 'shard') indicates the number of partitions that are being\nused in the overall computation.","minimum":1,"name":"num_shards","type":"int64"},{"default":0,"description":"A sampler can be used to sample from a subset of the original range\nin order to speed up the whole computation through parallelism. This parameter\n(together with 'num_shards') indicates the particular partition number of a\nsampler op, when partitioning is being used.","minimum":0,"name":"shard","type":"int64"},{"default":[],"description":"A list of unigram counts or probabilities, one per ID in sequential\norder. Exactly one of vocab_file and unigrams should be passed to this op.","name":"unigrams","type":"float32[]"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"A unigram sampler could use a fixed unigram distribution read from a\nfile or passed in as an in-memory array instead of building up the distribution\nfrom data on the fly. There is also an option to skew the distribution by\napplying a distortion power to the weights.\n\nThe vocabulary file should be in CSV-like format, with the last field\nbeing the weight associated with the word.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"FlatMapDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Unlike MapDataset, the `f` in FlatMapDataset is expected to return a\nDataset variant, and FlatMapDataset will flatten successive results\ninto a single Dataset.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Floor","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise largest integer not greater than x."}},{"name":"FloorDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `FloorDiv` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x // y element-wise."}},{"name":"FloorMod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `uint64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"true, this follows Python semantics in that the result here is consistent\nwith a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`.\n\n*NOTE*: `FloorMod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. When `x < 0` xor `y < 0` is"}},{"name":"FlushSummaryWriter","schema":{"inputs":[{"name":"writer","type":20}]}},{"name":"For","schema":{"attributes":[{"description":"A list of dtypes.","minimum":0,"name":"T","type":"type[]"},{"description":" A function that takes a list of tensors (int32, T) and returns another\n list of tensors (T).","name":"body","type":"function"}],"inputs":[{"description":"The lower bound. An int32","name":"start","type":3},{"description":"The upper bound. An int32","name":"limit","type":3},{"description":"The increment. An int32","name":"delta","type":3},{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":" ```python\n output = input;\n for i in range(start, limit, delta)\n output = body(i, output);\n ```"}},{"name":"FractionalAvgPool","schema":{"attributes":[{"description":"Pooling ratio for each dimension of `value`, currently only\nsupports row and col dimension and should be >= 1.0. For example, a valid\npooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements\nmust be 1.0 because we don't allow pooling on batch and channels\ndimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions\nrespectively.","minimum":4,"name":"pooling_ratio","type":"float32[]"},{"default":false,"description":"When set to True, generates the pooling sequence in a\npseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin\nGraham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for\ndifference between pseudorandom and random.","name":"pseudo_random","type":"boolean"},{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [41/3, 26/3] for fractional avg pooling.","name":"overlapping","type":"boolean"},{"default":false,"description":"When set to True, a fixed pooling region will be used when\niterating over a FractionalAvgPool node in the computation graph. Mainly used\nin unit test to make FractionalAvgPool deterministic.","name":"deterministic","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Fractional average pooling is similar to Fractional max pooling in the pooling\nregion generation step. The only difference is that after pooling regions are\ngenerated, a mean operation is performed instead of a max operation in each\npooling region.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"output tensor after fractional avg pooling.","name":"output","typeAttr":"T"},{"description":"row pooling sequence, needed to calculate gradient.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, needed to calculate gradient.","name":"col_pooling_sequence","type":9}],"summary":"Performs fractional average pooling on the input."}},{"name":"FractionalAvgPoolGrad","schema":{"attributes":[{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [41/3, 26/3] for fractional avg pooling.","name":"overlapping","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Unlike FractionalMaxPoolGrad, we don't need to find arg_max for\nFractionalAvgPoolGrad, we just need to evenly back-propagate each element of\nout_backprop to those indices that form the same pooling cell. Therefore, we\njust need to know the shape of original input tensor, instead of the whole\ntensor.","inputs":[{"description":"Original input tensor shape for `fractional_avg_pool`","name":"orig_input_tensor_shape","type":9},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients\nw.r.t. the output of `fractional_avg_pool`.","name":"out_backprop","typeAttr":"T"},{"description":"row pooling sequence, form pooling region with\ncol_pooling_sequence.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, form pooling region with\nrow_pooling sequence.","name":"col_pooling_sequence","type":9}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `fractional_avg_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradient of the FractionalAvgPool function."}},{"name":"FractionalMaxPool","schema":{"attributes":[{"description":"Pooling ratio for each dimension of `value`, currently only\nsupports row and col dimension and should be >= 1.0. For example, a valid\npooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements\nmust be 1.0 because we don't allow pooling on batch and channels\ndimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions\nrespectively.","minimum":4,"name":"pooling_ratio","type":"float32[]"},{"default":false,"description":"When set to True, generates the pooling sequence in a\npseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin\nGraham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for\ndifference between pseudorandom and random.","name":"pseudo_random","type":"boolean"},{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [20, 16] for fractional max pooling.","name":"overlapping","type":"boolean"},{"default":false,"description":"When set to True, a fixed pooling region will be used when\niterating over a FractionalMaxPool node in the computation graph. Mainly used\nin unit test to make FractionalMaxPool deterministic.","name":"deterministic","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Fractional max pooling is slightly different than regular max pooling. In\nregular max pooling, you downsize an input set by taking the maximum value of\nsmaller N x N subsections of the set (often 2x2), and try to reduce the set by\na factor of N, where N is an integer. Fractional max pooling, as you might\nexpect from the word \"fractional\", means that the overall reduction ratio N\ndoes not have to be an integer.\n\nThe sizes of the pooling regions are generated randomly but are fairly uniform.\nFor example, let's look at the height dimension, and the constraints on the\nlist of rows that will be pool boundaries.\n\nFirst we define the following:\n\n1. input_row_length : the number of rows from the input set\n2. output_row_length : which will be smaller than the input\n3. alpha = input_row_length / output_row_length : our reduction ratio\n4. K = floor(alpha)\n5. row_pooling_sequence : this is the result list of pool boundary rows\n\nThen, row_pooling_sequence should satisfy:\n\n1. a[0] = 0 : the first value of the sequence is 0\n2. a[end] = input_row_length : the last value of the sequence is the size\n3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size\n4. length(row_pooling_sequence) = output_row_length+1\n\nFor more details on fractional max pooling, see this paper:\n[Benjamin Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071)","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"output tensor after fractional max pooling.","name":"output","typeAttr":"T"},{"description":"row pooling sequence, needed to calculate gradient.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, needed to calculate gradient.","name":"col_pooling_sequence","type":9}],"summary":"Performs fractional max pooling on the input."}},{"name":"FractionalMaxPoolGrad","schema":{"attributes":[{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [20, 16] for fractional max pooling.","name":"overlapping","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Original input for `fractional_max_pool`","name":"orig_input","typeAttr":"T"},{"description":"Original output for `fractional_max_pool`","name":"orig_output","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients\nw.r.t. the output of `fractional_max_pool`.","name":"out_backprop","typeAttr":"T"},{"description":"row pooling sequence, form pooling region with\ncol_pooling_sequence.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, form pooling region with\nrow_pooling sequence.","name":"col_pooling_sequence","type":9}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `fractional_max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradient of the FractionalMaxPool function."}},{"name":"FresnelCos","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"FresnelSin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"FusedBatchNorm","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float32`.","name":"T","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"T"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"T"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"T"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"T"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"T"}],"summary":"Batch normalization."}},{"name":"FusedBatchNormGrad","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float32`.","name":"T","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"T"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"T"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"T"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"T"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_3","typeAttr":"T"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_4","typeAttr":"T"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormGradV2","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","type":1},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"U"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"U"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_3","typeAttr":"U"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_4","typeAttr":"U"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormGradV3","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","type":1},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for some intermediate results to be reused\nin gradient computation. When is_training is False, a dummy empty Tensor will be\ncreated.","name":"reserve_space_3","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"U"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"U"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_4","typeAttr":"U"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_5","typeAttr":"U"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormV2","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"U"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"U"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"U"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"U"}],"summary":"Batch normalization."}},{"name":"FusedBatchNormV3","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"U"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"U"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"U"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"U"},{"description":"A 1D Tensor for some intermediate results, to be reused in the gradient\ncomputation for better efficiency.","name":"reserve_space_3","typeAttr":"U"}],"summary":"Batch normalization."}},{"name":"FusedPadConv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`. Must be in the same order as the dimension specified with format.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"Similar to FusedResizeAndPadConv2d, this op allows for an optimized\nimplementation where the spatial padding transformation stage is fused with the\nim2col lookup, but in this case without the bilinear filtering required for\nresizing. Fusing the padding prevents the need to write out the intermediate\nresults as whole tensors, reducing memory pressure, and we can get some latency\ngains by merging the transformation calculations.\nThe data_format attribute for Conv2D isn't supported by this op, and 'NHWC'\norder is used instead.\nInternally this op uses a single per-graph scratch buffer, which means that it\nwill block if multiple versions are being run in parallel. This is because this\noperator is primarily an optimization to minimize memory usage.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Performs a padding as a preprocess during a convolution."}},{"name":"FusedResizeAndPadConv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"resize_align_corners","type":"boolean"},{"description":"Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`. Must be in the same order as the dimension specified with format.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"It's often possible to do spatial transformations more efficiently as part of\nthe packing stage of a convolution, so this op allows for an optimized\nimplementation where these stages are fused together. This prevents the need to\nwrite out the intermediate results as whole tensors, reducing memory pressure,\nand we can get some latency gains by merging the transformation calculations.\nThe data_format attribute for Conv2D isn't supported by this op, and defaults to\n'NHWC' order.\nInternally this op uses a single per-graph scratch buffer, which means that it\nwill block if multiple versions are being run in parallel. This is because this\noperator is primarily an optimization to minimize memory usage.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Performs a resize and padding as a preprocess during a convolution."}},{"name":"GRUBlockCell","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"}],"description":"Args\n x: Input to the GRU cell.\n h_prev: State input from the previous GRU cell.\n w_ru: Weight matrix for the reset and update gate.\n w_c: Weight matrix for the cell connection gate.\n b_ru: Bias vector for the reset and update gate.\n b_c: Bias vector for the cell connection gate.\n\nReturns\n r: Output of the reset gate.\n u: Output of the update gate.\n c: Output of the cell connection gate.\n h: Current state of the GRU cell.\n\nNote on notation of the variables:\n\nConcatenation of a and b is represented by a_b\nElement-wise dot product of a and b is represented by ab\nElement-wise dot product is represented by \\circ\nMatrix multiplication is represented by *\n\nBiases are initialized with :\n`b_ru` - constant_initializer(1.0)\n`b_c` - constant_initializer(0.0)\n\nThis kernel op implements the following mathematical equations:\n\n```\nx_h_prev = [x, h_prev]\n\n[r_bar u_bar] = x_h_prev * w_ru + b_ru\n\nr = sigmoid(r_bar)\nu = sigmoid(u_bar)\n\nh_prevr = h_prev \\circ r\n\nx_h_prevr = [x h_prevr]\n\nc_bar = x_h_prevr * w_c + b_c\nc = tanh(c_bar)\n\nh = (1-u) \\circ c + u \\circ h_prev\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"h_prev","typeAttr":"T"},{"name":"w_ru","typeAttr":"T"},{"name":"w_c","typeAttr":"T"},{"name":"b_ru","typeAttr":"T"},{"name":"b_c","typeAttr":"T"}],"outputs":[{"name":"r","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"c","typeAttr":"T"},{"name":"h","typeAttr":"T"}],"summary":"Computes the GRU cell forward propagation for 1 time step."}},{"name":"GRUBlockCellGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"}],"description":"Args\n x: Input to the GRU cell.\n h_prev: State input from the previous GRU cell.\n w_ru: Weight matrix for the reset and update gate.\n w_c: Weight matrix for the cell connection gate.\n b_ru: Bias vector for the reset and update gate.\n b_c: Bias vector for the cell connection gate.\n r: Output of the reset gate.\n u: Output of the update gate.\n c: Output of the cell connection gate.\n d_h: Gradients of the h_new wrt to objective function.\n\nReturns\n d_x: Gradients of the x wrt to objective function.\n d_h_prev: Gradients of the h wrt to objective function.\n d_c_bar Gradients of the c_bar wrt to objective function.\n d_r_bar_u_bar Gradients of the r_bar & u_bar wrt to objective function.\n\nThis kernel op implements the following mathematical equations:\n\nNote on notation of the variables:\n\nConcatenation of a and b is represented by a_b\nElement-wise dot product of a and b is represented by ab\nElement-wise dot product is represented by \\circ\nMatrix multiplication is represented by *\n\nAdditional notes for clarity:\n\n`w_ru` can be segmented into 4 different matrices.\n```\nw_ru = [w_r_x w_u_x\n w_r_h_prev w_u_h_prev]\n```\nSimilarly, `w_c` can be segmented into 2 different matrices.\n```\nw_c = [w_c_x w_c_h_prevr]\n```\nSame goes for biases.\n```\nb_ru = [b_ru_x b_ru_h]\nb_c = [b_c_x b_c_h]\n```\nAnother note on notation:\n```\nd_x = d_x_component_1 + d_x_component_2\n\nwhere d_x_component_1 = d_r_bar * w_r_x^T + d_u_bar * w_r_x^T\nand d_x_component_2 = d_c_bar * w_c_x^T\n\nd_h_prev = d_h_prev_component_1 + d_h_prevr \\circ r + d_h \\circ u\nwhere d_h_prev_componenet_1 = d_r_bar * w_r_h_prev^T + d_u_bar * w_r_h_prev^T\n```\n\nMathematics behind the Gradients below:\n```\nd_c_bar = d_h \\circ (1-u) \\circ (1-c \\circ c)\nd_u_bar = d_h \\circ (h-c) \\circ u \\circ (1-u)\n\nd_r_bar_u_bar = [d_r_bar d_u_bar]\n\n[d_x_component_1 d_h_prev_component_1] = d_r_bar_u_bar * w_ru^T\n\n[d_x_component_2 d_h_prevr] = d_c_bar * w_c^T\n\nd_x = d_x_component_1 + d_x_component_2\n\nd_h_prev = d_h_prev_component_1 + d_h_prevr \\circ r + u\n```\nBelow calculation is performed in the python wrapper for the Gradients\n(not in the gradient kernel.)\n```\nd_w_ru = x_h_prevr^T * d_c_bar\n\nd_w_c = x_h_prev^T * d_r_bar_u_bar\n\nd_b_ru = sum of d_r_bar_u_bar along axis = 0\n\nd_b_c = sum of d_c_bar along axis = 0\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"h_prev","typeAttr":"T"},{"name":"w_ru","typeAttr":"T"},{"name":"w_c","typeAttr":"T"},{"name":"b_ru","typeAttr":"T"},{"name":"b_c","typeAttr":"T"},{"name":"r","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"c","typeAttr":"T"},{"name":"d_h","typeAttr":"T"}],"outputs":[{"name":"d_x","typeAttr":"T"},{"name":"d_h_prev","typeAttr":"T"},{"name":"d_c_bar","typeAttr":"T"},{"name":"d_r_bar_u_bar","typeAttr":"T"}],"summary":"Computes the GRU cell back-propagation for 1 time step."}},{"name":"Gather","schema":{"attributes":[{"default":true,"name":"validate_indices","type":"boolean"},{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `indices.shape + params.shape[1:]` where:\n\n```python\n # Scalar indices\n output[:, ..., :] = params[indices, :, ... :]\n\n # Vector indices\n output[i, :, ..., :] = params[indices[i], :, ... :]\n\n # Higher rank indices\n output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]\n```\n\nIf `indices` is a permutation and `len(indices) == params.shape[0]` then\nthis operation will permute `params` accordingly.\n\n`validate_indices`: DEPRECATED. If this operation is assigned to CPU, values in\n`indices` are always validated to be within range. If assigned to GPU,\nout-of-bound indices result in safe but unspecified behavior, which may include\nraising an error.\n\n
\n\n
","inputs":[{"name":"params","typeAttr":"Tparams"},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` according to `indices`."}},{"name":"GatherNd","schema":{"attributes":[{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` is a K-dimensional integer tensor, best thought of as a\n(K-1)-dimensional tensor of indices into `params`, where each element defines a\nslice of `params`:\n\n output[\\\\(i_0, ..., i_{K-2}\\\\)] = params[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n\nWhereas in `tf.gather` `indices` defines slices into the `axis`\ndimension of `params`, in `tf.gather_nd`, `indices` defines slices into the\nfirst `N` dimensions of `params`, where `N = indices.shape[-1]`.\n\nThe last dimension of `indices` can be at most the rank of\n`params`:\n\n indices.shape[-1] <= params.rank\n\nThe last dimension of `indices` corresponds to elements\n(if `indices.shape[-1] == params.rank`) or slices\n(if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]`\nof `params`. The output tensor has shape\n\n indices.shape[:-1] + params.shape[indices.shape[-1]:]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, a 0 is stored in the\ncorresponding output value.\n\nSome examples below.\n\nSimple indexing into a matrix:\n\n```python\n indices = [[0, 0], [1, 1]]\n params = [['a', 'b'], ['c', 'd']]\n output = ['a', 'd']\n```\n\nSlice indexing into a matrix:\n\n```python\n indices = [[1], [0]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['c', 'd'], ['a', 'b']]\n```\n\nIndexing into a 3-tensor:\n\n```python\n indices = [[1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['a1', 'b1'], ['c1', 'd1']]]\n\n\n indices = [[0, 1], [1, 0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n\n indices = [[0, 0, 1], [1, 0, 1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = ['b0', 'b1']\n```\n\nBatched indexing into a matrix:\n\n```python\n indices = [[[0, 0]], [[0, 1]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['a'], ['b']]\n```\n\nBatched slice indexing into a matrix:\n\n```python\n indices = [[[1]], [[0]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [[['c', 'd']], [['a', 'b']]]\n```\n\nBatched indexing into a 3-tensor:\n\n```python\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[[['a1', 'b1'], ['c1', 'd1']]],\n [[['a0', 'b0'], ['c0', 'd0']]]]\n\n indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0'], ['a1', 'b1']],\n [['a0', 'b0'], ['c1', 'd1']]]\n\n\n indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['b0', 'b1'], ['d0', 'c1']]\n```\n\nSee also `tf.gather` and `tf.batch_gather`.","inputs":[{"description":"The tensor from which to gather values.","name":"params","typeAttr":"Tparams"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Values from `params` gathered from indices given by `indices`, with\nshape `indices.shape[:-1] + params.shape[indices.shape[-1]:]`.","name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` into a Tensor with shape specified by `indices`."}},{"name":"GatherV2","schema":{"attributes":[{"default":0,"name":"batch_dims","type":"int64"},{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `params.shape[:axis] +\nindices.shape[batch_dims:] + params.shape[axis + 1:]` where:\n\n```python\n # Scalar indices (output is rank(params) - 1).\n output[a_0, ..., a_n, b_0, ..., b_n] =\n params[a_0, ..., a_n, indices, b_0, ..., b_n]\n\n # Vector indices (output is rank(params)).\n output[a_0, ..., a_n, i, b_0, ..., b_n] =\n params[a_0, ..., a_n, indices[i], b_0, ..., b_n]\n\n # Higher rank indices (output is rank(params) + rank(indices) - 1).\n output[a_0, ..., a_n, i, ..., j, b_0, ... b_n] =\n params[a_0, ..., a_n, indices[i, ..., j], b_0, ..., b_n]\n```\n\n
\n\n
\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, a 0 is stored in the\ncorresponding output value.\n\nSee also `tf.batch_gather` and `tf.gather_nd`.","inputs":[{"description":"The tensor from which to gather values. Must be at least rank\n`axis + 1`.","name":"params","typeAttr":"Tparams"},{"description":"Index tensor. Must be in range `[0, params.shape[axis])`.","name":"indices","typeAttr":"Tindices"},{"description":"The axis in `params` to gather `indices` from. Defaults to the first\ndimension. Supports negative indexes.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"Values from `params` gathered from indices given by `indices`, with\nshape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]`.","name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` axis `axis` according to `indices`."}},{"name":"GenerateBoundingBoxProposals","schema":{"attributes":[{"default":300,"description":"An integer. Maximum number of rois in the output.","name":"post_nms_topn","type":"int64"}],"description":" The op selects top `pre_nms_topn` scoring boxes, decodes them with respect to anchors,\n applies non-maximal suppression on overlapping boxes with higher than\n `nms_threshold` intersection-over-union (iou) value, discarding boxes where shorter\n side is less than `min_size`.\n Inputs:\n `scores`: A 4D tensor of shape [Batch, Height, Width, Num Anchors] containing the scores per anchor at given position\n `bbox_deltas`: is a tensor of shape [Batch, Height, Width, 4 x Num Anchors] boxes encoded to each anchor\n `anchors`: A 1D tensor of shape [4 x Num Anchors], representing the anchors.\n Outputs:\n `rois`: output RoIs, a 3D tensor of shape [Batch, post_nms_topn, 4], padded by 0 if less than post_nms_topn candidates found.\n `roi_probabilities`: probability scores of each roi in 'rois', a 2D tensor of shape [Batch,post_nms_topn], padded with 0 if needed, sorted by scores.","inputs":[{"description":"A 4-D float tensor of shape `[num_images, height, width, num_achors]` containing scores of the boxes for given anchors, can be unsorted.","name":"scores","type":1},{"description":"A 4-D float tensor of shape `[num_images, height, width, 4 x num_anchors]`. encoding boxes with respec to each anchor.\nCoordinates are given in the form [dy, dx, dh, dw].","name":"bbox_deltas","type":1},{"description":"A 2-D float tensor of shape `[num_images, 5]` containing image information Height, Width, Scale.","name":"image_info","type":1},{"description":"A 2-D float tensor of shape `[num_anchors, 4]` describing the anchor boxes. Boxes are formatted in the form [y1, x1, y2, x2].","name":"anchors","type":1},{"description":"A scalar float tensor for non-maximal-suppression threshold.","name":"nms_threshold","type":1},{"description":"A scalar int tensor for the number of top scoring boxes to be used as input.","name":"pre_nms_topn","type":3},{"description":"A scalar float tensor. Any box that has a smaller size than min_size will be discarded.","name":"min_size","type":1}],"outputs":[{"description":"A 3-D float tensor of shape `[num_images,post_nms_topn,4]` representing the selected\nregion of interest boxes. Sorted in descending order in scores.","name":"rois","type":1},{"description":"A 2-D float tensor of shape `[num_images, post_nms_topn]` representing the score of the\nregion of interest box in `rois` tensor at the same index.","name":"roi_probabilities","type":1}],"summary":"This op produces Region of Interests from given bounding boxes(bbox_deltas) encoded wrt anchors according to eq.2 in arXiv:1506.01497"}},{"name":"GenerateVocabRemapping","schema":{"attributes":[{"description":"How many entries into the new vocab file to start reading.","minimum":0,"name":"new_vocab_offset","type":"int64"},{"description":"Number of entries in the new vocab file to remap.","minimum":0,"name":"num_new_vocab","type":"int64"},{"default":-1,"description":"Number of entries in the old vocab file to consider. If -1,\nuse the entire old vocabulary.","minimum":-1,"name":"old_vocab_size","type":"int64"}],"description":"length `num_new_vocab`, where `remapping[i]` contains the row number in the old\nvocabulary that corresponds to row `i` in the new vocabulary (starting at line\n`new_vocab_offset` and up to `num_new_vocab` entities), or `-1` if entry `i`\nin the new vocabulary is not in the old vocabulary. The old vocabulary is\nconstrained to the first `old_vocab_size` entries if `old_vocab_size` is not the\ndefault value of -1.\n\n`num_vocab_offset` enables\nuse in the partitioned variable case, and should generally be set through\nexamining partitioning info. The format of the files should be a text file,\nwith each line containing a single entity within the vocabulary.\n\nFor example, with `new_vocab_file` a text file containing each of the following\nelements on a single line: `[f0, f1, f2, f3]`, old_vocab_file = [f1, f0, f3],\n`num_new_vocab = 3, new_vocab_offset = 1`, the returned remapping would be\n`[0, -1, 2]`.\n\nThe op also returns a count of how many entries in the new vocabulary\nwere present in the old vocabulary, which is used to calculate the number of\nvalues to initialize in a weight matrix remapping\n\nThis functionality can be used to remap both row vocabularies (typically,\nfeatures) and column vocabularies (typically, classes) from TensorFlow\ncheckpoints. Note that the partitioning logic relies on contiguous vocabularies\ncorresponding to div-partitioned variables. Moreover, the underlying remapping\nuses an IndexTable (as opposed to an inexact CuckooTable), so client code should\nuse the corresponding index_table_from_file() as the FeatureColumn framework\ndoes (as opposed to tf.feature_to_id(), which uses a CuckooTable).","inputs":[{"description":"Path to the new vocab file.","name":"new_vocab_file","type":7},{"description":"Path to the old vocab file.","name":"old_vocab_file","type":7}],"outputs":[{"description":"A Tensor of length num_new_vocab where the element at index i\nis equal to the old ID that maps to the new ID i. This element is -1 for any\nnew ID that is not found in the old vocabulary.","name":"remapping","type":9},{"description":"Number of new vocab entries found in old vocab.","name":"num_present","type":3}],"summary":"Given a path to new and old vocabulary files, returns a remapping Tensor of"}},{"name":"GeneratorDataset","schema":{"attributes":[{"name":"init_func","type":"function"},{"name":"next_func","type":"function"},{"name":"finalize_func","type":"function"},{"minimum":0,"name":"Tinit_func_args","type":"type[]"},{"minimum":0,"name":"Tnext_func_args","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_args","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"init_func_other_args","typeListAttr":"Tinit_func_args"},{"name":"next_func_other_args","typeListAttr":"Tnext_func_args"},{"name":"finalize_func_other_args","typeListAttr":"Tfinalize_func_args"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that invokes a function to generate elements."}},{"name":"GetSessionHandle","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be stored.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The handle for the tensor stored in the session state, represented\nas a string.","name":"handle","type":7}],"summary":"Store the input tensor in the state of the current session."}},{"name":"GetSessionHandleV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be stored.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The handle for the tensor stored in the session state, represented\nas a ResourceHandle object.","name":"handle","type":20}],"summary":"Store the input tensor in the state of the current session."}},{"name":"GetSessionTensor","schema":{"attributes":[{"description":"The type of the output value.","name":"dtype","type":"type"}],"inputs":[{"description":"The handle for a tensor stored in the session state.","name":"handle","type":7}],"outputs":[{"description":"The tensor for the given handle.","name":"value","typeAttr":"dtype"}],"summary":"Get the value of the tensor specified by its handle."}},{"name":"Greater","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `Greater` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 2, 5])\ntf.math.greater(x, y) ==> [False, True, True]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.greater(x, y) ==> [False, False, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x > y) element-wise."}},{"name":"GreaterEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `GreaterEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6, 7])\ny = tf.constant([5, 2, 5, 10])\ntf.math.greater_equal(x, y) ==> [True, True, True, False]\n\nx = tf.constant([5, 4, 6, 7])\ny = tf.constant([5])\ntf.math.greater_equal(x, y) ==> [True, False, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x >= y) element-wise."}},{"name":"GroupByReducerDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"description":"A function mapping a key of type DT_INT64, concatenated with\n`init_func_other_arguments` to the initial reducer state.","name":"init_func","type":"function"},{"description":"A function mapping the current reducer state and an element of `input_dataset`,\nconcatenated with `reduce_func_other_arguments` to a new reducer state.","name":"reduce_func","type":"function"},{"description":"A function mapping the final reducer state to an output element.","name":"finalize_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tinit_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that computes a group-by on `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `key_func`.","name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `init_func`.","name":"init_func_other_arguments","typeListAttr":"Tinit_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `reduce_func`.","name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `finalize_func`.","name":"finalize_func_other_arguments","typeListAttr":"Tfinalize_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a group-by on `input_dataset`."}},{"name":"GroupByWindowDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"name":"reduce_func","type":"function"},{"name":"window_size_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Twindow_size_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"// TODO(mrry): Support non-int64 keys.","inputs":[{"name":"input_dataset","type":21},{"name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"name":"window_size_func_other_arguments","typeListAttr":"Twindow_size_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a windowed group-by on `input_dataset`."}},{"name":"GuaranteeConst","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The runtime is then free to make optimizations based on this.\n\nOnly accepts value typed tensors as inputs and rejects resource variable handles\nas input.\n\nReturns the input tensor without modification.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Gives a guarantee to the TF runtime that the input tensor is a constant."}},{"name":"HSVToRGB","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a tensor of the same shape as the `images` tensor, containing the RGB\nvalue of the pixels. The output is only well defined if the value in `images`\nare in `[0,1]`.\n\nSee `rgb_to_hsv` for a description of the HSV encoding.","inputs":[{"description":"1-D or higher rank. HSV data to convert. Last dimension must be size 3.","name":"images","typeAttr":"T"}],"outputs":[{"description":"`images` converted to RGB.","name":"output","typeAttr":"T"}],"summary":"Convert one or more images from HSV to RGB."}},{"name":"HashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a hash table, specifying the type of its keys and values.\nBefore using the table you will have to initialize it. After initialization the\ntable will be immutable.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates a non-initialized hash table."}},{"name":"HashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a hash table, specifying the type of its keys and values.\nBefore using the table you will have to initialize it. After initialization the\ntable will be immutable.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates a non-initialized hash table."}},{"name":"HistogramFixedWidth","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"dtype","type":"type"}],"description":"Given the tensor `values`, this operation returns a rank 1 histogram counting\nthe number of entries in `values` that fall into every bin. The bins are\nequal width and determined by the arguments `value_range` and `nbins`.\n\n```python\n# Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)\nnbins = 5\nvalue_range = [0.0, 5.0]\nnew_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]\n\nwith tf.get_default_session() as sess:\n hist = tf.histogram_fixed_width(new_values, value_range, nbins=5)\n variables.global_variables_initializer().run()\n sess.run(hist) => [2, 1, 1, 0, 2]\n```","inputs":[{"description":"Numeric `Tensor`.","name":"values","typeAttr":"T"},{"description":"Shape [2] `Tensor` of same `dtype` as `values`.\nvalues <= value_range[0] will be mapped to hist[0],\nvalues >= value_range[1] will be mapped to hist[-1].","name":"value_range","typeAttr":"T"},{"description":"Scalar `int32 Tensor`. Number of histogram bins.","name":"nbins","type":3}],"outputs":[{"description":"A 1-D `Tensor` holding histogram of values.","name":"out","typeAttr":"dtype"}],"summary":"Return histogram of values."}},{"name":"HistogramSummary","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The generated\n[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\nhas one summary value containing a histogram for `values`.\n\nThis op reports an `InvalidArgument` error if any value is not finite.","inputs":[{"description":"Scalar. Tag to use for the `Summary.Value`.","name":"tag","type":7},{"description":"Any shape. Values to use to build the histogram.","name":"values","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a histogram."}},{"name":"HostConst","schema":{"attributes":[{"description":"Attr `value` is the tensor to return.","name":"value","type":"tensor"},{"name":"dtype","type":"type"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Returns a constant tensor on the host. Only for writing C++ tests."}},{"name":"IFFT","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 1-dimensional discrete Fourier transform over the\ninner-most dimension of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its inverse 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse fast Fourier transform."}},{"name":"IFFT2D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 2-dimensional discrete Fourier transform over the\ninner-most 2 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse 2D fast Fourier transform."}},{"name":"IFFT3D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 3-dimensional discrete Fourier transform over the\ninner-most 3 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their inverse 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse 3D fast Fourier transform."}},{"name":"IRFFT","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 1-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most dimension of `input`.\n\nThe inner-most dimension of `input` is assumed to be the result of `RFFT`: the\n`fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If\n`fft_length` is not provided, it is computed from the size of the inner-most\ndimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to\ncompute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong the axis `IRFFT` is computed on, if `fft_length / 2 + 1` is smaller\nthan the corresponding dimension of `input`, the dimension is cropped. If it is\nlarger, the dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [1]. The FFT length.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length` samples of its inverse\n 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse real-valued fast Fourier transform."}},{"name":"IRFFT2D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 2-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 2 dimensions of `input`.\n\nThe inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`:\nThe inner-most dimension contains the `fft_length / 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 2 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong each axis `IRFFT2D` is computed on, if `fft_length` (or\n`fft_length / 2 + 1` for the inner-most dimension) is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [2]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft2\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse 2D real-valued fast Fourier transform."}},{"name":"IRFFT3D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 3-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 3 dimensions of `input`.\n\nThe inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`:\nThe inner-most dimension contains the `fft_length / 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 3 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong each axis `IRFFT3D` is computed on, if `fft_length` (or\n`fft_length / 2 + 1` for the inner-most dimension) is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [3]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 3D real Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.irfftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse 3D real-valued fast Fourier transform."}},{"name":"Identity","schema":{"attributes":[{"name":"T","type":"type"}],"category":"Control","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a tensor with the same shape and contents as the input tensor or value."}},{"name":"IdentityN","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"tensors.\n\nThis op can be used to override the gradient for complicated functions. For\nexample, suppose y = f(x) and we wish to apply a custom function g for backprop\nsuch that dx = g(dy). In Python,\n\n```python\nwith tf.get_default_graph().gradient_override_map(\n {'IdentityN': 'OverrideGradientWithG'}):\n y, _ = identity_n([f(x), x])\n\n@tf.RegisterGradient('OverrideGradientWithG')\ndef ApplyG(op, dy, _):\n return [None, g(dy)] # Do not backprop to f(x).\n```","inputs":[{"name":"input","typeListAttr":"T"}],"outputs":[{"name":"output","typeListAttr":"T"}],"summary":"Returns a list of tensors with the same shapes and contents as the input"}},{"name":"IdentityReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue strings in a Queue. ReaderRead will take the front\nwork string and output (work, work).","outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the queued work as both the key and value."}},{"name":"IdentityReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue strings in a Queue. ReaderRead will take the front\nwork string and output (work, work).","outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the queued work as both the key and value."}},{"name":"If","schema":{"attributes":[{"name":"Tcond","type":"type"},{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what else_branch returns.","name":"then_branch","type":"function"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what then_branch returns.","name":"else_branch","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":" A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n `True` and zero means False; if the scalar is a string, non-empty\n means `True` and empty means `False`. If the tensor is not a scalar,\n being empty means False and being non-empty means True.","name":"cond","typeAttr":"Tcond"},{"description":"A list of input tensors.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"output = cond ? then_branch(input) : else_branch(input)"}},{"name":"Igamma","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The lower regularized incomplete Gamma function is defined as:\n\n\n\\\\(P(a, x) = gamma(a, x) / Gamma(a) = 1 - Q(a, x)\\\\)\n\nwhere\n\n\\\\(gamma(a, x) = \\\\int_{0}^{x} t^{a-1} exp(-t) dt\\\\)\n\nis the lower incomplete Gamma function.\n\nNote, above `Q(a, x)` (`Igammac`) is the upper regularized complete\nGamma function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the lower regularized incomplete Gamma function `P(a, x)`."}},{"name":"IgammaGradA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient of `igamma(a, x)` wrt `a`."}},{"name":"Igammac","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The upper regularized incomplete Gamma function is defined as:\n\n\\\\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\\\)\n\nwhere\n\n\\\\(Gamma(a, x) = int_{x}^{\\infty} t^{a-1} exp(-t) dt\\\\)\n\nis the upper incomplete Gama function.\n\nNote, above `P(a, x)` (`Igamma`) is the lower regularized complete\nGamma function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the upper regularized incomplete Gamma function `Q(a, x)`."}},{"name":"IgnoreErrorsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the elements of `input_dataset` ignoring errors."}},{"name":"Imag","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the imaginary part of each element in `input`. All\nelements in `input` must be complex numbers of the form \\\\(a + bj\\\\), where *a*\nis the real part and *b* is the imaginary part returned by this operation.\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.imag(input) ==> [4.75, 5.75]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the imaginary part of a complex number."}},{"name":"ImageProjectiveTransformV2","schema":{"attributes":[{"description":"Input dtype. Must be one of the following: `uint8`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Interpolation method, \"NEAREST\" or \"BILINEAR\".","name":"interpolation","type":"string"},{"default":"CONSTANT","description":"Fill mode, \"REFLECT\", \"WRAP\", or \"CONSTANT\".","name":"fill_mode","type":"string"}],"description":"If one row of `transforms` is `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps\nthe *output* point `(x, y)` to a transformed *input* point\n`(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where\n`k = c0 x + c1 y + 1`. If the transformed point lays outside of the input\nimage, the output pixel is set to 0.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"dtype"},{"description":"2-D Tensor, `[batch, 8]` or `[1, 8]` matrix, where each row corresponds to a 3 x 3\nprojective transformation matrix, with the last entry assumed to be 1. If there\nis one row, the same transformation will be applied to all images.","name":"transforms","type":1},{"description":"1-D Tensor [new_height, new_width].","name":"output_shape","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"transformed_images","typeAttr":"dtype"}],"summary":"Applies the given transform to each of the images."}},{"name":"ImageSummary","schema":{"attributes":[{"default":3,"description":"Max number of batch elements to generate images for.","minimum":1,"name":"max_images","type":"int64"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `uint8`, `float32`, `float16`, `float64`.","name":"T","type":"type"},{"default":{"type":"tensor","value":"?"},"description":"Color to use for pixels with non-finite values.","name":"bad_color","type":"tensor"}],"description":"The summary has up to `max_images` summary values containing images. The\nimages are built from `tensor` which must be 4-D with shape `[batch_size,\nheight, width, channels]` and where `channels` can be:\n\n* 1: `tensor` is interpreted as Grayscale.\n* 3: `tensor` is interpreted as RGB.\n* 4: `tensor` is interpreted as RGBA.\n\nThe images have the same number of channels as the input tensor. For float\ninput, the values are normalized one image at a time to fit in the range\n`[0, 255]`. `uint8` values are unchanged. The op uses two different\nnormalization algorithms:\n\n* If the input values are all positive, they are rescaled so the largest one\n is 255.\n\n* If any input value is negative, the values are shifted so input value 0.0\n is at 127. They are then rescaled so that either the smallest value is 0,\n or the largest one is 255.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_images` is 1, the summary value tag is '*tag*/image'.\n* If `max_images` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/image/0', '*tag*/image/1', etc.\n\nThe `bad_color` argument is the color to use in the generated images for\nnon-finite input values. It is a `uint8` 1-D tensor of length `channels`.\nEach element must be in the range `[0, 255]` (It represents the value of a\npixel in the output image). Non-finite values in the input tensor are\nreplaced by this tensor in the output image. The default value is the color\nred.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"4-D of shape `[batch_size, height, width, channels]` where\n`channels` is 1, 3, or 4.","name":"tensor","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with images."}},{"name":"ImmutableConst","schema":{"attributes":[{"description":"Type of the returned tensor.","name":"dtype","type":"type"},{"description":"Shape of the returned tensor.","name":"shape","type":"shape"},{"description":"Name of readonly memory region used by the tensor, see\nNewReadOnlyMemoryRegionFromFile in tensorflow::Env.","name":"memory_region_name","type":"string"}],"description":"The current implementation memmaps the tensor from a file.","outputs":[{"name":"tensor","typeAttr":"dtype"}],"summary":"Returns immutable tensor from memory region."}},{"name":"ImportEvent","schema":{"inputs":[{"name":"writer","type":20},{"name":"event","type":7}]}},{"name":"InTopK","schema":{"attributes":[{"description":"Number of top elements to look at for computing precision.","name":"k","type":"int64"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the\nprediction for the target class is among the top `k` predictions among\nall predictions for example `i`. Note that the behavior of `InTopK` differs\nfrom the `TopK` op in its handling of ties; if multiple classes have the\nsame prediction value and straddle the top-`k` boundary, all of those\nclasses are considered to be in the top `k`.\n\nMore formally, let\n\n \\\\(predictions_i\\\\) be the predictions for all classes for example `i`,\n \\\\(targets_i\\\\) be the target class for example `i`,\n \\\\(out_i\\\\) be the output for example `i`,\n\n$$out_i = predictions_{i, targets_i} \\in TopKIncludingTies(predictions_i)$$","inputs":[{"description":"A `batch_size` x `classes` tensor.","name":"predictions","type":1},{"description":"A `batch_size` vector of class ids.","name":"targets","typeAttr":"T"}],"outputs":[{"description":"Computed Precision at `k` as a `bool Tensor`.","name":"precision","type":10}],"summary":"Says whether the targets are in the top `K` predictions."}},{"name":"InTopKV2","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the\nprediction for the target class is among the top `k` predictions among\nall predictions for example `i`. Note that the behavior of `InTopK` differs\nfrom the `TopK` op in its handling of ties; if multiple classes have the\nsame prediction value and straddle the top-`k` boundary, all of those\nclasses are considered to be in the top `k`.\n\nMore formally, let\n\n \\\\(predictions_i\\\\) be the predictions for all classes for example `i`,\n \\\\(targets_i\\\\) be the target class for example `i`,\n \\\\(out_i\\\\) be the output for example `i`,\n\n$$out_i = predictions_{i, targets_i} \\in TopKIncludingTies(predictions_i)$$","inputs":[{"description":"A `batch_size` x `classes` tensor.","name":"predictions","type":1},{"description":"A `batch_size` vector of class ids.","name":"targets","typeAttr":"T"},{"description":"Number of top elements to look at for computing precision.","name":"k","typeAttr":"T"}],"outputs":[{"description":"Computed precision at `k` as a `bool Tensor`.","name":"precision","type":10}],"summary":"Says whether the targets are in the top `K` predictions."}},{"name":"InfeedDequeue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor.","name":"shape","type":"shape"}],"outputs":[{"description":"A tensor that will be provided using the infeed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"InfeedDequeueTuple","schema":{"attributes":[{"description":"The element types of each element in `outputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `outputs`.","name":"shapes","type":"shape[]"}],"outputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"outputs","typeListAttr":"dtypes"}],"summary":"Fetches multiple values from infeed as an XLA tuple."}},{"name":"InfeedEnqueue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence.\nIf a layout attribute is passed, but its values are all -1, the layout will\nbe computed by the infeed operation.","name":"layout","type":"int64[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A tensor that will be provided using the infeed mechanism.","name":"input","typeAttr":"dtype"}],"summary":"An op which feeds a single Tensor value into the computation."}},{"name":"InfeedEnqueuePrelinearizedBuffer","schema":{"attributes":[{"default":-1,"description":"The TPU device to use. This should be -1 when the Op is running on a TPU device\nand = 0 when the Op is running on the CPU device.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A variant tensor representing linearized output.","name":"input","type":21}],"summary":"An op which enqueues prelinearized buffer into TPU infeed."}},{"name":"InfeedEnqueueTuple","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `inputs`.","name":"shapes","type":"shape[]"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence for\nall the tuple shapes, in the order the shapes appear in the \"shapes\" input.\nThe layout elements for a sub-shape can be set to -1, in which case the\ncorresponding layout will be computed by the infeed operation.","name":"layouts","type":"int64[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"inputs","typeListAttr":"dtypes"}],"summary":"Feeds multiple Tensor values into the computation as an XLA tuple."}},{"name":"InitializeTable","schema":{"attributes":[{"name":"Tkey","type":"type"},{"name":"Tval","type":"type"}],"inputs":[{"description":"Handle to a table which will be initialized.","isRef":true,"name":"table_handle","type":7},{"description":"Keys of type Tkey.","name":"keys","typeAttr":"Tkey"},{"description":"Values of type Tval.","name":"values","typeAttr":"Tval"}],"summary":"Table initializer that takes two tensors for keys and values respectively."}},{"name":"InitializeTableFromDataset","schema":{"inputs":[{"name":"table_handle","type":20},{"name":"dataset","type":21}]}},{"name":"InitializeTableFromTextFile","schema":{"attributes":[{"description":"Column index in a line to get the table `key` values from.","minimum":-2,"name":"key_index","type":"int64"},{"description":"Column index that represents information of a line to get the table\n`value` values from.","minimum":-2,"name":"value_index","type":"int64"},{"default":-1,"description":"Number of elements of the file, use -1 if unknown.","minimum":-1,"name":"vocab_size","type":"int64"},{"default":"\t","description":"Delimiter to separate fields in a line.","name":"delimiter","type":"string"}],"description":"It inserts one key-value pair into the table for each line of the file.\nThe key and value is extracted from the whole line content, elements from the\nsplit line based on `delimiter` or the line number (starting from zero).\nWhere to extract the key and value from a line is specified by `key_index` and\n`value_index`.\n\n- A value of -1 means use the line number(starting from zero), expects `int64`.\n- A value of -2 means use the whole line content, expects `string`.\n- A value >= 0 means use the index (starting at zero) of the split line based\n on `delimiter`.","inputs":[{"description":"Handle to a table which will be initialized.","isRef":true,"name":"table_handle","type":7},{"description":"Filename of a vocabulary text file.","name":"filename","type":7}],"summary":"Initializes a table from a text file."}},{"name":"InitializeTableFromTextFileV2","schema":{"attributes":[{"description":"Column index in a line to get the table `key` values from.","minimum":-2,"name":"key_index","type":"int64"},{"description":"Column index that represents information of a line to get the table\n`value` values from.","minimum":-2,"name":"value_index","type":"int64"},{"default":-1,"description":"Number of elements of the file, use -1 if unknown.","minimum":-1,"name":"vocab_size","type":"int64"},{"default":"\t","description":"Delimiter to separate fields in a line.","name":"delimiter","type":"string"}],"description":"It inserts one key-value pair into the table for each line of the file.\nThe key and value is extracted from the whole line content, elements from the\nsplit line based on `delimiter` or the line number (starting from zero).\nWhere to extract the key and value from a line is specified by `key_index` and\n`value_index`.\n\n- A value of -1 means use the line number(starting from zero), expects `int64`.\n- A value of -2 means use the whole line content, expects `string`.\n- A value >= 0 means use the index (starting at zero) of the split line based\n on `delimiter`.","inputs":[{"description":"Handle to a table which will be initialized.","name":"table_handle","type":20},{"description":"Filename of a vocabulary text file.","name":"filename","type":7}],"summary":"Initializes a table from a text file."}},{"name":"InitializeTableV2","schema":{"attributes":[{"name":"Tkey","type":"type"},{"name":"Tval","type":"type"}],"inputs":[{"description":"Handle to a table which will be initialized.","name":"table_handle","type":20},{"description":"Keys of type Tkey.","name":"keys","typeAttr":"Tkey"},{"description":"Values of type Tval.","name":"values","typeAttr":"Tval"}],"summary":"Table initializer that takes two tensors for keys and values respectively."}},{"name":"InplaceAdd","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A `Tensor` of type T.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":" Adds v into specified rows of x.\n\n Computes y = x; y[i, :] += v; return y."}},{"name":"InplaceSub","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A `Tensor` of type T.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":" Subtracts `v` into specified rows of `x`.\n\n Computes y = x; y[i, :] -= v; return y."}},{"name":"InplaceUpdate","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Computes `x[i, :] = v; return x`.\n\nOriginally this function is mutative however for compilation we make this\noperation create / operate on a copy of `x`.","inputs":[{"description":"A tensor of type `T`.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":"Updates specified rows 'i' with values 'v'."}},{"name":"InterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Unlike MapDataset, the `f` in InterleaveDataset is expected to return\na Dataset variant, and InterleaveDataset will flatten successive\nresults into a single Dataset. Unlike FlatMapDataset,\nInterleaveDataset will interleave sequences of up to `block_length`\nconsecutive elements from `cycle_length` input elements.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Inv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the reciprocal of x element-wise."}},{"name":"InvGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the inverse of `x` wrt its input."}},{"name":"Invert","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Flip each bit of supported types. For example, type `int8` (decimal 2) binary 00000010 becomes (decimal -3) binary 11111101.\nThis operation is performed on each element of the tensor argument `x`.\n\nExample:\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\n\n# flip 2 (00000010) to -3 (11111101)\ntf.assert_equal(-3, bitwise_ops.invert(2))\n\ndtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,\n dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]\n\ninputs = [0, 5, 3, 14]\nfor dtype in dtype_list:\n # Because of issues with negative numbers, let's test this indirectly.\n # 1. invert(a) and a = 0\n # 2. invert(a) or a = invert(0)\n input_tensor = tf.constant([0, 5, 3, 14], dtype=dtype)\n not_a_and_a, not_a_or_a, not_0 = [bitwise_ops.bitwise_and(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.bitwise_or(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.invert(\n tf.constant(0, dtype=dtype))]\n\n expected = tf.constant([0, 0, 0, 0], dtype=tf.float32)\n tf.assert_equal(tf.cast(not_a_and_a, tf.float32), expected)\n\n expected = tf.cast([not_0] * 4, tf.float32)\n tf.assert_equal(tf.cast(not_a_or_a, tf.float32), expected)\n\n # For unsigned dtypes let's also check the result directly.\n if dtype.is_unsigned:\n inverted = bitwise_ops.invert(input_tensor)\n expected = tf.constant([dtype.max - x for x in inputs], dtype=tf.float32)\n tf.assert_equal(tf.cast(inverted, tf.float32), tf.cast(expected, tf.float32))\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Invert (flip) each bit of supported types; for example, type `uint8` value 01010101 becomes 10101010."}},{"name":"InvertPermutation","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This operation computes the inverse of an index permutation. It takes a 1-D\ninteger tensor `x`, which represents the indices of a zero-based array, and\nswaps each value with its index position. In other words, for an output tensor\n`y` and an input tensor `x`, this operation computes the following:\n\n`y[x[i]] = i for i in [0, 1, ..., len(x) - 1]`\n\nThe values must include 0. There can be no duplicate values or negative values.\n\nFor example:\n\n```\n# tensor `x` is [3, 4, 0, 2, 1]\ninvert_permutation(x) ==> [2, 4, 3, 0, 1]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"}],"summary":"Computes the inverse permutation of a tensor."}},{"name":"IsBoostedTreesEnsembleInitialized","schema":{"inputs":[{"description":"Handle to the tree ensemble resource.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"output boolean on whether it is initialized or not.","name":"is_initialized","type":10}],"summary":"Checks whether a tree ensemble has been initialized."}},{"name":"IsBoostedTreesQuantileStreamResourceInitialized","schema":{"description":"An Op that checks if quantile stream resource is initialized.","inputs":[{"description":"resource; The reference to quantile stream resource handle.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"description":"bool; True if the resource is initialized, False otherwise.","name":"is_initialized","type":10}],"summary":"Checks whether a quantile stream has been initialized."}},{"name":"IsFinite","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isfinite\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, 4.8, 6.8, np.inf, np.nan])\ntf.math.is_finite(x) ==> [True, True, True, False, False]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are finite."}},{"name":"IsInf","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isinf\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, np.inf, 6.8, np.inf])\ntf.math.is_inf(x) ==> [False, True, False, True]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are Inf."}},{"name":"IsNan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isnan\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, np.nan, 6.8, np.nan, np.inf])\ntf.math.is_nan(x) ==> [False, True, False, True, False]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are NaN."}},{"name":"IsVariableInitialized","schema":{"attributes":[{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"}],"description":"Outputs boolean scalar indicating whether the tensor has been initialized.","inputs":[{"description":"Should be from a `Variable` node. May be uninitialized.","isRef":true,"name":"ref","typeAttr":"dtype"}],"outputs":[{"name":"is_initialized","type":10}],"summary":"Checks whether a tensor has been initialized."}},{"name":"Iterator","schema":{"attributes":[{"name":"shared_name","type":"string"},{"name":"container","type":"string"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\"\nor \"IteratorGetNext\" op.","name":"handle","type":20}],"summary":"A container for an iterator resource."}},{"name":"IteratorFromStringHandle","schema":{"attributes":[{"default":[],"description":"If specified, defines the type of each tuple component in an\nelement produced by the resulting iterator.","minimum":0,"name":"output_types","type":"type[]"},{"default":[],"description":"If specified, defines the shape of each tuple component in an\nelement produced by the resulting iterator.","minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A string representation of the given handle.","name":"string_handle","type":7}],"outputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"summary":"Converts the given string representing a handle to an iterator to a resource."}},{"name":"IteratorFromStringHandleV2","schema":{"attributes":[{"default":[],"minimum":0,"name":"output_types","type":"type[]"},{"default":[],"minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"string_handle","type":7}],"outputs":[{"name":"resource_handle","type":20}]}},{"name":"IteratorGetDevice","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"name":"device","type":7}],"summary":"Returns the name of the device on which `resource` has been placed."}},{"name":"IteratorGetNext","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Gets the next output from the given iterator ."}},{"name":"IteratorGetNextAsOptional","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"optional","type":21}],"summary":"Gets the next output from the given iterator as an Optional variant."}},{"name":"IteratorGetNextSync","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"This operation is a synchronous version IteratorGetNext. It should only be used\nin situations where the iterator does not block the calling thread, or where\nthe calling thread is not a member of the thread pool used to execute parallel\noperations (e.g. in eager mode).","inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Gets the next output from the given iterator."}},{"name":"IteratorToStringHandle","schema":{"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"outputs":[{"description":"A string representation of the given handle.","name":"string_handle","type":7}],"summary":"Converts the given `resource_handle` representing an iterator to a string."}},{"name":"IteratorV2","schema":{"attributes":[{"name":"shared_name","type":"string"},{"name":"container","type":"string"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"name":"handle","type":20}]}},{"name":"KMC2ChainInitialization","schema":{"description":"Entries in distances are assumed to be squared distances of candidate points to\nthe already sampled centers in the seed set. The op constructs one Markov chain\nof the k-MC^2 algorithm and returns the index of one candidate point to be added\nas an additional cluster center.","inputs":[{"description":"Vector with squared distances to the closest previously sampled cluster center\nfor each candidate point.","name":"distances","type":1},{"description":"Scalar. Seed for initializing the random number generator.","name":"seed","type":9}],"outputs":[{"description":"Scalar with the index of the sampled point.","name":"index","type":9}],"summary":"Returns the index of a data point that should be added to the seed set."}},{"name":"KmeansPlusPlusInitialization","schema":{"description":"Rows of points are assumed to be input points. One row is selected at random.\nSubsequent rows are sampled with probability proportional to the squared L2\ndistance from the nearest row selected thus far till num_to_sample rows have\nbeen sampled.","inputs":[{"description":"Matrix of shape (n, d). Rows are assumed to be input points.","name":"points","type":1},{"description":"Scalar. The number of rows to sample. This value must not be larger than n.","name":"num_to_sample","type":9},{"description":"Scalar. Seed for initializing the random number generator.","name":"seed","type":9},{"description":"Scalar. For each row that is sampled, this parameter\nspecifies the number of additional points to draw from the current\ndistribution before selecting the best. If a negative value is specified, a\nheuristic is used to sample O(log(num_to_sample)) additional points.","name":"num_retries_per_sample","type":9}],"outputs":[{"description":"Matrix of shape (num_to_sample, d). The sampled rows.","name":"samples","type":1}],"summary":"Selects num_to_sample rows of input using the KMeans++ criterion."}},{"name":"KthOrderStatistic","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"implementation uses a binary search requiring exactly 32 passes over\nthe input data. The running time is linear with respect to input\nsize. The median-of-medians algorithm is probably faster, but is\ndifficult to implement efficiently in XLA. The implementation imposes\na total ordering on floats. The ordering is consistent with the usual\npartial order. Positive NaNs are greater than positive\ninfinity. Negative NaNs are less than negative infinity. NaNs with\ndistinct payloads are treated as distinct. Subnormal numbers are\npreserved (not flushed to zero). Positive infinity is greater than all\nnumbers. Negative infinity is less than all numbers. Positive is\ngreater than negative zero. There are less than k values greater than\nthe kth order statistic. There are at least k values greater than or\nequal to the Kth order statistic. The semantics are not the same as\ntop_k_unique.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Computes the Kth order statistic of a data set. The current"}},{"name":"L2Loss","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Computes half the L2 norm of a tensor without the `sqrt`:\n\n output = sum(t ** 2) / 2","inputs":[{"description":"Typically 2-D, but may have any dimensions.","name":"t","typeAttr":"T"}],"outputs":[{"description":"0-D.","name":"output","typeAttr":"T"}],"summary":"L2 Loss."}},{"name":"LMDBDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The Lightning Memory-Mapped Database Manager, or LMDB, is an embedded binary\nkey-value database. This dataset can read the contents of LMDB database files,\nthe names of which generally have the `.mdb` suffix.\n\nEach output element consists of a key-value pair represented as a pair of\nscalar string `Tensor`s, where the first `Tensor` contains the key and the\nsecond `Tensor` contains the value.\n\nLMDB uses different file formats on big- and little-endian machines.\n`LMDBDataset` can only read files in the format of the host machine.","inputs":[{"description":"A scalar or a vector containing the name(s) of the binary file(s) to be\nread.","name":"filenames","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the key-value pairs in one or more LMDB files."}},{"name":"LMDBReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the records from a LMDB file."}},{"name":"LRN","schema":{"attributes":[{"default":5,"description":"0-D. Half-width of the 1-D normalization window.","name":"depth_radius","type":"int64"},{"default":1,"description":"An offset (usually positive to avoid dividing by 0).","name":"bias","type":"float32"},{"default":1,"description":"A scale factor, usually positive.","name":"alpha","type":"float32"},{"default":0.5,"description":"An exponent.","name":"beta","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"category":"Normalization","description":"The 4-D `input` tensor is treated as a 3-D array of 1-D vectors (along the last\ndimension), and each vector is normalized independently. Within a given vector,\neach component is divided by the weighted, squared sum of inputs within\n`depth_radius`. In detail,\n\n sqr_sum[a, b, c, d] =\n sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2)\n output = input / (bias + alpha * sqr_sum) ** beta\n\nFor details, see [Krizhevsky et al., ImageNet classification with deep\nconvolutional neural networks (NIPS 2012)](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks).","inputs":[{"description":"4-D.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Local Response Normalization."}},{"name":"LRNGrad","schema":{"attributes":[{"default":5,"description":"A depth radius.","name":"depth_radius","type":"int64"},{"default":1,"description":"An offset (usually > 0 to avoid dividing by 0).","name":"bias","type":"float32"},{"default":1,"description":"A scale factor, usually positive.","name":"alpha","type":"float32"},{"default":0.5,"description":"An exponent.","name":"beta","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input_grads","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input_image","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`.","name":"output_image","typeAttr":"T"}],"outputs":[{"description":"The gradients for LRN.","name":"output","typeAttr":"T"}],"summary":"Gradients for Local Response Normalization."}},{"name":"LSTMBlockCell","schema":{"attributes":[{"default":1,"description":"The forget gate bias.","name":"forget_bias","type":"float32"},{"default":3,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"category":"Layer","description":"This implementation uses 1 weight matrix and 1 bias vector, and there's an\noptional peephole connection.\n\nThis kernel op implements the following mathematical equations:\n\n```python\nxh = [x, h_prev]\n[i, f, ci, o] = xh * w + b\nf = f + forget_bias\n\nif not use_peephole:\n wci = wcf = wco = 0\n\ni = sigmoid(cs_prev * wci + i)\nf = sigmoid(cs_prev * wcf + f)\nci = tanh(ci)\n\ncs = ci .* i + cs_prev .* f\ncs = clip(cs, cell_clip)\n\no = sigmoid(cs * wco + o)\nco = tanh(cs)\nh = co .* o\n```","inputs":[{"description":"The input to the LSTM cell, shape (batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the cell state at previous time step.","name":"cs_prev","typeAttr":"T"},{"description":"Output of the previous cell at previous time step.","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh.","name":"cs","typeAttr":"T"},{"description":"The forget gate.","name":"f","typeAttr":"T"},{"description":"The output gate.","name":"o","typeAttr":"T"},{"description":"The cell input.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh.","name":"co","typeAttr":"T"},{"description":"The output h vector.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for 1 time step."}},{"name":"LSTMBlockCellGrad","schema":{"attributes":[{"description":"Whether the cell uses peephole connections.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of LSTMBlockCell.","inputs":[{"description":"The input to the LSTM cell, shape (batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"The previous cell state.","name":"cs_prev","typeAttr":"T"},{"description":"The previous h state.","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh.","name":"cs","typeAttr":"T"},{"description":"The forget gate.","name":"f","typeAttr":"T"},{"description":"The output gate.","name":"o","typeAttr":"T"},{"description":"The cell input.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh.","name":"co","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of cs to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The derivative wrt to [i, cs, f, o].","name":"dicfo","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for 1 timestep."}},{"name":"LatencyStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the latency of producing `input_dataset` elements in a StatsAggregator."}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.20000000298023224,"name":"alpha","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear: `max(features, features * alpha)`."}},{"name":"LeakyReluGrad","schema":{"attributes":[{"default":0.20000000298023224,"name":"alpha","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding LeakyRelu operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding LeakyRelu operation,\nOR the outputs of that operation (both work equivalently).","name":"features","typeAttr":"T"}],"outputs":[{"description":"`gradients * (features > 0) + alpha * gradients * (features <= 0)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear gradients for a LeakyRelu operation."}},{"name":"LearnedUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"LeftShift","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If `y` is negative, or greater than or equal to the width of `x` in bits the\nresult is implementation defined.\n\nExample:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\nimport numpy as np\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([-1, -5, -3, -14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n\n left_shift_result = bitwise_ops.left_shift(lhs, rhs)\n\n print(left_shift_result)\n\n# This will print:\n# tf.Tensor([ -32 -5 -128 0], shape=(4,), dtype=int8)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int16)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int32)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int64)\n\nlhs = np.array([-2, 64, 101, 32], dtype=np.int8)\nrhs = np.array([-1, -5, -3, -14], dtype=np.int8)\nbitwise_ops.left_shift(lhs, rhs)\n# \n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise left-shift of `x` and `y`."}},{"name":"LegacyParallelInterleaveDatasetV2","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","name":"deterministic","type":"string"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! This dataset is not deterministic!","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9},{"name":"buffer_output_elements","type":9},{"name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Less","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `Less` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.less(x, y) ==> [False, True, False]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 6, 7])\ntf.math.less(x, y) ==> [False, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x < y) element-wise."}},{"name":"LessEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `LessEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.less_equal(x, y) ==> [True, True, False]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 6, 6])\ntf.math.less_equal(x, y) ==> [True, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x <= y) element-wise."}},{"name":"Lgamma","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":" For positive numbers, this function computes log((input - 1)!) for every element in the tensor.\n `lgamma(5) = log((5-1)!) = log(4!) = log(24) = 3.1780539`\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 4.5, -4, -5.6])\ntf.math.lgamma(x) ==> [inf, 0.5723649, 0., 2.4537368, inf, -4.6477685]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the log of the absolute value of `Gamma(x)` element-wise."}},{"name":"LinSpace","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"A sequence of `num` evenly-spaced values are generated beginning at `start`.\nIf `num > 1`, the values in the sequence increase by `stop - start / num - 1`,\nso that the last one is exactly `stop`.\n\nFor example:\n\n```\ntf.linspace(10.0, 12.0, 3, name=\"linspace\") => [ 10.0 11.0 12.0]\n```","inputs":[{"description":"0-D tensor. First entry in the range.","name":"start","typeAttr":"T"},{"description":"0-D tensor. Last entry in the range.","name":"stop","typeAttr":"T"},{"description":"0-D tensor. Number of values to generate.","name":"num","typeAttr":"Tidx"}],"outputs":[{"description":"1-D. The generated values.","name":"output","typeAttr":"T"}],"summary":"Generates values in an interval."}},{"name":"ListDiff","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"Given a list `x` and a list `y`, this operation returns a list `out` that\nrepresents all values that are in `x` but not in `y`. The returned list `out`\nis sorted in the same order that the numbers appear in `x` (duplicates are\npreserved). This operation also returns a list `idx` that represents the\nposition of each `out` element in `x`. In other words:\n\n`out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]`\n\nFor example, given this input:\n\n```\nx = [1, 2, 3, 4, 5, 6]\ny = [1, 3, 5]\n```\n\nThis operation would return:\n\n```\nout ==> [2, 4, 6]\nidx ==> [1, 3, 5]\n```","inputs":[{"description":"1-D. Values to keep.","name":"x","typeAttr":"T"},{"description":"1-D. Values to remove.","name":"y","typeAttr":"T"}],"outputs":[{"description":"1-D. Values present in `x` but not in `y`.","name":"out","typeAttr":"T"},{"description":"1-D. Positions of `x` values preserved in `out`.","name":"idx","typeAttr":"out_idx"}],"summary":"Computes the difference between two lists of numbers or strings."}},{"name":"LoadAndRemapMatrix","schema":{"attributes":[{"description":"Number of rows (length of the 1st dimension) in the output matrix.","minimum":0,"name":"num_rows","type":"int64"},{"description":"Number of columns (length of the 2nd dimension) in the output matrix.","minimum":1,"name":"num_cols","type":"int64"},{"default":-1,"description":"The maximum number of rows to load from the checkpoint at\nonce. If less than or equal to 0, the entire matrix will be loaded into\nmemory. Setting this arg trades increased disk reads for lower memory usage.","name":"max_rows_in_memory","type":"int64"}],"description":"at `ckpt_path` and potentially reorders its rows and columns using the\nspecified remappings.\n\nMost users should use one of the wrapper initializers (such as\n`tf.contrib.framework.load_and_remap_matrix_initializer`) instead of this\nfunction directly.\n\nThe remappings are 1-D tensors with the following properties:\n\n* `row_remapping` must have exactly `num_rows` entries. Row `i` of the output\n matrix will be initialized from the row corresponding to index\n `row_remapping[i]` in the old `Tensor` from the checkpoint.\n* `col_remapping` must have either 0 entries (indicating that no column\n reordering is needed) or `num_cols` entries. If specified, column `j` of the\n output matrix will be initialized from the column corresponding to index\n `col_remapping[j]` in the old `Tensor` from the checkpoint.\n* A value of -1 in either of the remappings signifies a \"missing\" entry. In that\n case, values from the `initializing_values` tensor will be used to fill that\n missing row or column. If `row_remapping` has `r` missing entries and\n `col_remapping` has `c` missing entries, then the following condition must be\n true:\n\n`(r * num_cols) + (c * num_rows) - (r * c) == len(initializing_values)`\n\nThe remapping tensors can be generated using the GenerateVocabRemapping op.\n\nAs an example, with row_remapping = [1, 0, -1], col_remapping = [0, 2, -1],\ninitializing_values = [0.5, -0.5, 0.25, -0.25, 42], and w(i, j) representing\nthe value from row i, column j of the old tensor in the checkpoint, the output\nmatrix will look like the following:\n\n[[w(1, 0), w(1, 2), 0.5],\n [w(0, 0), w(0, 2), -0.5],\n [0.25, -0.25, 42]]","inputs":[{"description":"Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from\nwhich the old matrix `Tensor` will be loaded.","name":"ckpt_path","type":7},{"description":"Name of the 2-D `Tensor` to load from checkpoint.","name":"old_tensor_name","type":7},{"description":"An int `Tensor` of row remappings (generally created by\n`generate_vocab_remapping`). Even if no row remapping is needed, this must\nstill be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted\nindex-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`).","name":"row_remapping","type":9},{"description":"An int `Tensor` of column remappings (generally created by\n`generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping\nis to be done (e.g. column ordering is the same).","name":"col_remapping","type":9},{"description":"A float `Tensor` containing values to fill in for cells\nin the output matrix that are not loaded from the checkpoint. Length must be\nexactly the same as the number of missing / new cells.","name":"initializing_values","type":1}],"outputs":[{"description":"Output matrix containing existing values loaded from the\ncheckpoint, and with any missing values filled in from initializing_values.","name":"output_matrix","type":1}],"summary":"Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint"}},{"name":"LoadDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"compression","type":"string"},{"name":"reader_func","type":"function"},{"minimum":0,"name":"Treader_func_args","type":"type[]"}],"inputs":[{"name":"path","type":7},{"name":"reader_func_other_args","typeListAttr":"Treader_func_args"}],"outputs":[{"name":"handle","type":21}]}},{"name":"LoadTPUEmbeddingADAMParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Value of velocities used in the ADAM optimization algorithm.","name":"velocities","type":1}],"summary":"Load ADAM embedding parameters."}},{"name":"LoadTPUEmbeddingADAMParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Value of velocities used in the ADAM optimization algorithm.","name":"velocities","type":1},{"description":"Value of gradient_accumulators used in the ADAM optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load ADAM embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingAdadeltaParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Value of updates used in the Adadelta optimization algorithm.","name":"updates","type":1}],"summary":"Load Adadelta embedding parameters."}},{"name":"LoadTPUEmbeddingAdadeltaParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Value of updates used in the Adadelta optimization algorithm.","name":"updates","type":1},{"description":"Value of gradient_accumulators used in the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Adadelta parameters with debug support."}},{"name":"LoadTPUEmbeddingAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Load Adagrad embedding parameters."}},{"name":"LoadTPUEmbeddingAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Value of gradient_accumulators used in the Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Adagrad embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingCenteredRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the centered RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the centered RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the centered RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Value of mg used in the centered RMSProp optimization algorithm.","name":"mg","type":1}],"summary":"Load centered RMSProp embedding parameters."}},{"name":"LoadTPUEmbeddingFTRLParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Value of linears used in the FTRL optimization algorithm.","name":"linears","type":1}],"summary":"Load FTRL embedding parameters."}},{"name":"LoadTPUEmbeddingFTRLParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Value of linears used in the FTRL optimization algorithm.","name":"linears","type":1},{"description":"Value of gradient_accumulators used in the FTRL optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load FTRL embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingMDLAdagradLightParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the MDL Adagrad Light optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the MDL Adagrad Light optimization algorithm.","name":"accumulators","type":1},{"description":"Value of weights used in the MDL Adagrad Light optimization algorithm.","name":"weights","type":1},{"description":"Value of benefits used in the MDL Adagrad Light optimization algorithm.","name":"benefits","type":1}],"summary":"Load MDL Adagrad Light embedding parameters."}},{"name":"LoadTPUEmbeddingMomentumParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the Momentum optimization algorithm.","name":"momenta","type":1}],"summary":"Load Momentum embedding parameters."}},{"name":"LoadTPUEmbeddingMomentumParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the Momentum optimization algorithm.","name":"momenta","type":1},{"description":"Value of gradient_accumulators used in the Momentum optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Momentum embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingProximalAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the proximal Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Load proximal Adagrad embedding parameters."}},{"name":"LoadTPUEmbeddingProximalAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the proximal Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Value of gradient_accumulators used in the proximal Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load proximal Adagrad embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingProximalYogiParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"inputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1}]}},{"name":"LoadTPUEmbeddingProximalYogiParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"inputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1},{"name":"gradient_accumulators","type":1}]}},{"name":"LoadTPUEmbeddingRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the RMSProp optimization algorithm.","name":"mom","type":1}],"summary":"Load RMSProp embedding parameters."}},{"name":"LoadTPUEmbeddingRMSPropParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Value of gradient_accumulators used in the RMSProp optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load RMSProp embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingStochasticGradientDescentParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the stochastic gradient descent optimization algorithm.","name":"parameters","type":1}],"summary":"Load SGD embedding parameters."}},{"name":"LoadTPUEmbeddingStochasticGradientDescentParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the stochastic gradient descent optimization algorithm.","name":"parameters","type":1},{"description":"Value of gradient_accumulators used in the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load SGD embedding parameters."}},{"name":"Log","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\log_e x\\\\).\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 5])\ntf.math.log(x) ==> [-inf, -0.6931472, 0. , 1.609438]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes natural logarithm of x element-wise."}},{"name":"Log1p","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\log_e (1 + x)\\\\).\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 5])\ntf.math.log1p(x) ==> [0., 0.4054651, 0.6931472, 1.7917595]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes natural logarithm of (1 + x) element-wise."}},{"name":"LogMatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"one or more square matrices.\n\nThe input is a tensor of shape `[N, M, M]` whose inner-most 2 dimensions\nform square matrices. The outputs are two tensors containing the signs and\nabsolute values of the log determinants for all N input submatrices\n`[..., :, :]` such that the determinant = sign*exp(log_abs_determinant).\nThe log_abs_determinant is computed as det(P)*sum(log(diag(LU))) where LU\nis the LU decomposition of the input and P is the corresponding\npermutation matrix.","inputs":[{"description":"Shape is `[N, M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The signs of the log determinants of the inputs. Shape is `[N]`.","name":"sign","typeAttr":"T"},{"description":"The logs of the absolute values of the determinants\nof the N input matrices. Shape is `[N]`.","name":"log_abs_determinant","typeAttr":"T"}],"summary":"Computes the sign and the log of the absolute value of the determinant of"}},{"name":"LogSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"For each batch `i` and class `j` we have\n\n logsoftmax[i, j] = logits[i, j] - log(sum(exp(logits[i])))","inputs":[{"description":"2-D with shape `[batch_size, num_classes]`.","name":"logits","typeAttr":"T"}],"outputs":[{"description":"Same shape as `logits`.","name":"logsoftmax","typeAttr":"T"}],"summary":"Computes log softmax activations."}},{"name":"LogUniformCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a log-uniform distribution."}},{"name":"LogicalAnd","schema":{"description":"*NOTE*: `LogicalAnd` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","type":10},{"name":"y","type":10}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of x AND y element-wise."}},{"name":"LogicalNot","schema":{"inputs":[{"description":"A `Tensor` of type `bool`.","name":"x","type":10}],"outputs":[{"description":"A `Tensor` of type `bool` with the same shape as `x`. The logical negation of `x`.","name":"y","type":10}],"summary":"Returns the truth value of `NOT x` element-wise."}},{"name":"LogicalOr","schema":{"description":"*NOTE*: `LogicalOr` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","type":10},{"name":"y","type":10}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of x OR y element-wise."}},{"name":"LookupTableExport","schema":{"attributes":[{"name":"Tkeys","type":"type"},{"name":"Tvalues","type":"type"}],"inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7}],"outputs":[{"description":"Vector of all keys present in the table.","name":"keys","typeAttr":"Tkeys"},{"description":"Tensor of all values in the table. Indexed in parallel with `keys`.","name":"values","typeAttr":"Tvalues"}],"summary":"Outputs all keys and values in the table."}},{"name":"LookupTableExportV2","schema":{"attributes":[{"name":"Tkeys","type":"type"},{"name":"Tvalues","type":"type"}],"inputs":[{"description":"Handle to the table.","name":"table_handle","type":20}],"outputs":[{"description":"Vector of all keys present in the table.","name":"keys","typeAttr":"Tkeys"},{"description":"Tensor of all values in the table. Indexed in parallel with `keys`.","name":"values","typeAttr":"Tvalues"}],"summary":"Outputs all keys and values in the table."}},{"name":"LookupTableFind","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table.\nThe output `values` is of the type of the table values.\n\nThe scalar `default_value` is the value output for keys not present in the\ntable. It must also be of the same type as the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"name":"default_value","typeAttr":"Tout"}],"outputs":[{"description":"Same shape as `keys`. Values found in the table, or `default_values`\nfor missing keys.","name":"values","typeAttr":"Tout"}],"summary":"Looks up keys in a table, outputs the corresponding values."}},{"name":"LookupTableFindV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table.\nThe output `values` is of the type of the table values.\n\nThe scalar `default_value` is the value output for keys not present in the\ntable. It must also be of the same type as the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"name":"default_value","typeAttr":"Tout"}],"outputs":[{"description":"Same shape as `keys`. Values found in the table, or `default_values`\nfor missing keys.","name":"values","typeAttr":"Tout"}],"summary":"Looks up keys in a table, outputs the corresponding values."}},{"name":"LookupTableImport","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Replaces the contents of the table with the specified keys and values."}},{"name":"LookupTableImportV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Replaces the contents of the table with the specified keys and values."}},{"name":"LookupTableInsert","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Updates the table to associates keys with values."}},{"name":"LookupTableInsertV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Updates the table to associates keys with values."}},{"name":"LookupTableRemoveV2","schema":{"attributes":[{"name":"Tin","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table. Keys not\nalready in the table are silently ignored.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys of the elements to remove.","name":"keys","typeAttr":"Tin"}],"summary":"Removes keys and its associated values from a table."}},{"name":"LookupTableSize","schema":{"inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7}],"outputs":[{"description":"Scalar that contains number of elements in the table.","name":"size","type":9}],"summary":"Computes the number of elements in the given table."}},{"name":"LookupTableSizeV2","schema":{"inputs":[{"description":"Handle to the table.","name":"table_handle","type":20}],"outputs":[{"description":"Scalar that contains number of elements in the table.","name":"size","type":9}],"summary":"Computes the number of elements in the given table."}},{"name":"LoopCond","schema":{"description":"This operator represents the loop termination condition used by the\n\"pivot\" switches of a loop.","inputs":[{"description":"A boolean scalar, representing the branch predicate of the Switch op.","name":"input","type":10}],"outputs":[{"description":"The same tensor as `input`.","name":"output","type":10}],"summary":"Forwards the input to the output."}},{"name":"LowerBound","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"Each set of rows with the same index in (sorted_inputs, values) is treated\nindependently. The resulting row is the equivalent of calling\n`np.searchsorted(sorted_inputs, values, side='left')`.\n\nThe result is not a global index to the entire\n`Tensor`, but rather just the index in the last dimension.\n\nA 2-D example:\n sorted_sequence = [[0, 3, 9, 9, 10],\n [1, 2, 3, 4, 5]]\n values = [[2, 4, 9],\n [0, 2, 6]]\n\n result = LowerBound(sorted_sequence, values)\n\n result == [[1, 2, 2],\n [0, 1, 5]]","inputs":[{"description":"2-D Tensor where each row is ordered.","name":"sorted_inputs","typeAttr":"T"},{"description":"2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains\nthe values that will be searched for in `sorted_search_values`.","name":"values","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `values`. It contains the first scalar index\ninto the last dimension where values can be inserted without changing the\nordered property.","name":"output","typeAttr":"out_type"}],"summary":"Applies lower_bound(sorted_search_values, values) along each row."}},{"name":"Lu","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"output_idx_type","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices.\n\nThe input has to be invertible.\n\nThe output consists of two tensors LU and P containing the LU decomposition\nof all input submatrices `[..., :, :]`. LU encodes the lower triangular and\nupper triangular factors.\n\nFor each input submatrix of shape `[M, M]`, L is a lower triangular matrix of\nshape `[M, M]` with unit diagonal whose entries correspond to the strictly lower\ntriangular part of LU. U is a upper triangular matrix of shape `[M, M]` whose\nentries correspond to the upper triangular part, including the diagonal, of LU.\n\nP represents a permutation matrix encoded as a list of indices each between `0`\nand `M-1`, inclusive. If P_mat denotes the permutation matrix corresponding to\nP, then the L, U and P satisfies P_mat * input = L * U.","inputs":[{"description":"A tensor of shape `[..., M, M]` whose inner-most 2 dimensions form matrices of\nsize `[M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"A tensor of shape `[..., M, M]` whose strictly lower triangular part denotes the\nlower triangular factor `L` with unit diagonal, and whose upper triangular part\ndenotes the upper triangular factor `U`.","name":"lu","typeAttr":"T"},{"description":"Permutation of the rows encoded as a list of indices in `0..M-1`. Shape is\n`[..., M]`.\n@compatibility(scipy)\nSimilar to `scipy.linalg.lu`, except the triangular factors `L` and `U` are\npacked into a single tensor, the permutation is applied to `input` instead of\nthe right hand side and the permutation `P` is returned as a list of indices\ninstead of a permutation matrix.\n@end_compatibility","name":"p","typeAttr":"output_idx_type"}],"summary":"Computes the LU decomposition of one or more square matrices."}},{"name":"MakeIterator","schema":{"description":"This operation may be executed multiple times. Each execution will reset the\niterator in `iterator` to the first element of `dataset`.","inputs":[{"name":"dataset","type":21},{"name":"iterator","type":20}],"summary":"Makes a new iterator from the given `dataset` and stores it in `iterator`."}},{"name":"MakeUnique","schema":{"description":"their initial value. Never returns a sub-normal number. Never returns\nzero. The sign of each input element is always identical to the sign\nof the corresponding output element. Behavior for infinite elements is\nundefined. Behavior for subnormal elements is undefined.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Make all elements in the non-Batch dimension unique, but \\\"close\\\" to"}},{"name":"MapAndBatchDataset","schema":{"attributes":[{"description":"A function to apply to the outputs of `input_dataset`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Creates a dataset that applies `f` to the outputs of `input_dataset` and then\nbatches `batch_size` of them.\n\nUnlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `batch_size * num_parallel_batches` copies of `f` in parallel.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when building a closure\nfor `f`.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"A scalar representing the number of elements to accumulate in a\nbatch. It determines the number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"batch_size","type":9},{"description":"A scalar representing the maximum number of parallel invocations of the `map_fn`\nfunction. Applying the `map_fn` on consecutive input elements in parallel has\nthe potential to improve input pipeline throughput.","name":"num_parallel_calls","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that fuses mapping with batching."}},{"name":"MapClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"MapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"MapDefun","schema":{"attributes":[{"description":"A list of types.","minimum":1,"name":"Targuments","type":"type[]"},{"default":[],"description":"A list of types.","minimum":0,"name":"Tcaptured","type":"type[]"},{"description":"A list of types.","minimum":1,"name":"output_types","type":"type[]"},{"description":"A list of shapes.","minimum":1,"name":"output_shapes","type":"shape[]"},{"name":"f","type":"function"},{"default":1,"name":"max_intra_op_parallelism","type":"int64"}],"inputs":[{"description":" A list of tensors whose types are `Targuments`, corresponding to the inputs\n the function should be mapped over.","name":"arguments","typeListAttr":"Targuments"},{"description":" A list of tensors whose types are `Tcaptured`, corresponding to the captured\n inputs of the defun.","name":"captured_inputs","typeListAttr":"Tcaptured"}],"outputs":[{"description":" A list of output tensors whose types are `output_types` and whose dimensions\n 0 are the same as the dimensions 0 of the tensors in `arguments`, and whose\n remaining dimensions correspond to those in `output_shapes`.","name":"output","typeListAttr":"output_types"}],"summary":" Maps a function on the list of tensors unpacked from arguments on dimension 0.\n The function given by `f` is assumed to be stateless, and is executed\n concurrently on all the slices; up to batch_size (i.e. the size of the 0th\n dimension of each argument) functions will be scheduled at once.\n\n The `max_intra_op_parallelism` attr, which defaults to 1, can be used to\n limit the intra op parallelism. To limit inter-op parallelism, a user can\n set a private threadpool on the dataset using `tf.data.Options`'s\n `ThreadingOptions`.\n\n Note that this op is not exposed to users directly, but is invoked in tf.data\n rewrites."}},{"name":"MapIncompleteSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of incomplete elements in the underlying container."}},{"name":"MapPeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain this key\nthis op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified key. If the"}},{"name":"MapSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"MapStage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"minimum":1,"name":"fake_dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"inputs":[{"description":"int64","name":"key","type":9},{"name":"indices","type":3},{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"fake_dtypes"}],"summary":"Stage (key, values) in the underlying container which behaves like a hashtable."}},{"name":"MapUnstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain this key, the op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the values associated with the key"}},{"name":"MapUnstageNoKey","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain elements, the op will block until it does.","inputs":[{"name":"indices","type":3}],"outputs":[{"name":"key","type":9},{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns a random (key, value)"}},{"name":"MatMul","schema":{"attributes":[{"default":false,"description":"If true, \"a\" is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, \"b\" is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of\n\"a\" (after being transposed if transpose_a is true) must match the\nouter dimension of \"b\" (after being transposed if transposed_b is\ntrue).\n\n*Note*: The default kernel implementation for MatMul on GPUs uses\ncublas.","inputs":[{"name":"a","typeAttr":"T"},{"name":"b","typeAttr":"T"}],"outputs":[{"name":"product","typeAttr":"T"}],"summary":"Multiply the matrix \"a\" by the matrix \"b\"."}},{"name":"MatchingFiles","schema":{"description":"Note that this routine only supports wildcard characters in the\nbasename portion of the pattern, not in the directory portion.\nNote also that the order of filenames returned is deterministic.","inputs":[{"description":"Shell wildcard pattern(s). Scalar or vector of type string.","name":"pattern","type":7}],"outputs":[{"description":"A vector of matching filenames.","name":"filenames","type":7}],"summary":"Returns the set of files matching one or more glob patterns."}},{"name":"MatchingFilesDataset","schema":{"inputs":[{"name":"patterns","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"MatrixBandPart","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tindex","type":"type"}],"description":"The `band` part is computed as follows:\nAssume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a\ntensor with the same shape where\n\n`band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n\nThe indicator function\n\n`in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) &&\n (num_upper < 0 || (n-m) <= num_upper)`.\n\nFor example:\n\n```\n# if 'input' is [[ 0, 1, 2, 3]\n [-1, 0, 1, 2]\n [-2, -1, 0, 1]\n [-3, -2, -1, 0]],\n\ntf.matrix_band_part(input, 1, -1) ==> [[ 0, 1, 2, 3]\n [-1, 0, 1, 2]\n [ 0, -1, 0, 1]\n [ 0, 0, -1, 0]],\n\ntf.matrix_band_part(input, 2, 1) ==> [[ 0, 1, 0, 0]\n [-1, 0, 1, 0]\n [-2, -1, 0, 1]\n [ 0, -2, -1, 0]]\n```\n\nUseful special cases:\n\n```\n tf.matrix_band_part(input, 0, -1) ==> Upper triangular part.\n tf.matrix_band_part(input, -1, 0) ==> Lower triangular part.\n tf.matrix_band_part(input, 0, 0) ==> Diagonal.\n```","inputs":[{"description":"Rank `k` tensor.","name":"input","typeAttr":"T"},{"description":"0-D tensor. Number of subdiagonals to keep. If negative, keep entire\nlower triangle.","name":"num_lower","typeAttr":"Tindex"},{"description":"0-D tensor. Number of superdiagonals to keep. If negative, keep\nentire upper triangle.","name":"num_upper","typeAttr":"Tindex"}],"outputs":[{"description":"Rank `k` tensor of the same shape as input. The extracted banded tensor.","name":"band","typeAttr":"T"}],"summary":"Copy a tensor setting everything outside a central band in each innermost matrix to zero."}},{"name":"MatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor containing the determinants\nfor all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[...]`.","name":"output","typeAttr":"T"}],"summary":"Computes the determinant of one or more square matrices."}},{"name":"MatrixDiag","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given a `diagonal`, this operation returns a tensor with the `diagonal` and\neverything else padded with zeros. The diagonal is computed as follows:\n\nAssume `diagonal` has `k` dimensions `[I, J, K, ..., N]`, then the output is a\ntensor of rank `k+1` with dimensions [I, J, K, ..., N, N]` where:\n\n`output[i, j, k, ..., m, n] = 1{m=n} * diagonal[i, j, k, ..., n]`.\n\nFor example:\n\n```\n# 'diagonal' is [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nand diagonal.shape = (2, 4)\n\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]],\n [[5, 0, 0, 0]\n [0, 6, 0, 0]\n [0, 0, 7, 0]\n [0, 0, 0, 8]]]\n\nwhich has shape (2, 4, 4)\n```","inputs":[{"description":"Rank `k`, where `k >= 1`.","name":"diagonal","typeAttr":"T"}],"outputs":[{"description":"Rank `k+1`, with `output.shape = diagonal.shape + [diagonal.shape[-1]]`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with a given batched diagonal values."}},{"name":"MatrixDiagPart","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This operation returns a tensor with the `diagonal` part\nof the batched `input`. The `diagonal` part is computed as follows:\n\nAssume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a\ntensor of rank `k - 1` with dimensions `[I, J, K, ..., min(M, N)]` where:\n\n`diagonal[i, j, k, ..., n] = input[i, j, k, ..., n, n]`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\n# 'input' is [[[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]],\n [[5, 0, 0, 0]\n [0, 6, 0, 0]\n [0, 0, 7, 0]\n [0, 0, 0, 8]]]\n\nand input.shape = (2, 4, 4)\n\ntf.matrix_diag_part(input) ==> [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nwhich has shape (2, 4)\n```","inputs":[{"description":"Rank `k` tensor where `k >= 2`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s) having shape\n`diagonal.shape = input.shape[:-2] + [min(input.shape[-2:])]`.","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagPartV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n`input`.\n\nAssume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\nLet `max_diag_len` be the maximum length among all diagonals to be extracted,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\nLet `num_diags` be the number of diagonals to extract,\n`num_diags = k[1] - k[0] + 1`.\n\nIf `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n`[I, J, ..., L, max_diag_len]` and values:\n\n```\ndiagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\nOtherwise, the output tensor has rank `r` with dimensions\n`[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n```\ndiagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `d = k[1] - m`, `y = max(-d, 0)`, and `x = max(d, 0)`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\ninput = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n# A main diagonal from each batch.\ntf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n# A superdiagonal from each batch.\ntf.matrix_diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n# A tridiagonal band from each batch.\ntf.matrix_diag_part(input, k = (-1, 1))\n ==> [[[2, 7, 6], # Output shape: (2, 3, 3)\n [1, 6, 7],\n [5, 8, 0]],\n [[4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n# Padding value = 9\ntf.matrix_diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[4, 9, 9], # Output shape: (2, 3, 3)\n [3, 8, 9],\n [2, 7, 6]],\n [[2, 9, 9],\n [3, 4, 9],\n [4, 3, 8]]]\n```","inputs":[{"description":"Rank `r` tensor where `r >= 2`.","name":"input","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The value to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s).","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagPartV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n`input`.\n\nAssume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\nLet `max_diag_len` be the maximum length among all diagonals to be extracted,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\nLet `num_diags` be the number of diagonals to extract,\n`num_diags = k[1] - k[0] + 1`.\n\nIf `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n`[I, J, ..., L, max_diag_len]` and values:\n\n```\ndiagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\nOtherwise, the output tensor has rank `r` with dimensions\n`[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n```\ndiagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\ninput = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n# A main diagonal from each batch.\ntf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n# A superdiagonal from each batch.\ntf.matrix_diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n# A band from each batch.\ntf.matrix_diag_part(input, k = (-1, 2))\n ==> [[[0, 3, 8], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [5, 8, 0]],\n [[0, 3, 4],\n [4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n# LEFT_RIGHT alignment.\ntf.matrix_diag_part(input, k = (-1, 2), align=\"LEFT_RIGHT\")\n ==> [[[3, 8, 0], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [0, 5, 8]],\n [[3, 4, 0],\n [4, 3, 8],\n [5, 2, 7],\n [0, 1, 6]]]\n\n# max_diag_len can be shorter than the main diagonal.\ntf.matrix_diag_part(input, k = (-2, -1))\n ==> [[[5, 8],\n [9, 0]],\n [[1, 6],\n [5, 0]]]\n\n# padding_value = 9\ntf.matrix_diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[9, 9, 4], # Output shape: (2, 3, 3)\n [9, 3, 8],\n [2, 7, 6]],\n [[9, 9, 2],\n [9, 3, 4],\n [4, 3, 8]]]\n\n```","inputs":[{"description":"Rank `r` tensor where `r >= 2`.","name":"input","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The value to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s).","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\ndiagonals of a matrix, with everything else padded with `padding`. `num_rows`\nand `num_cols` specify the dimension of the innermost matrix of the output. If\nboth are not specified, the op assumes the innermost matrix is square and infers\nits size from `k` and the innermost dimension of `diagonal`. If only one of them\nis specified, the op assumes the unspecified value is the smallest possible\nbased on other criteria.\n\nLet `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has\nrank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one\ndiagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank\n`r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\nThe second innermost dimension of `diagonal` has double meaning.\nWhen `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size\n[I, J, ..., M], and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n```\n\nOtherwise, `M` is treated as the number of diagonals for the matrix in the\nsame batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`.\n\nFor example:\n\n```\n# The main diagonal.\ndiagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n# A superdiagonal (per batch).\ndiagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3)\n [4, 5, 0]],\n [[6, 7, 9],\n [9, 1, 0]]])\ntf.matrix_diag(diagonals, k = (-1, 0))\n ==> [[[1, 0, 0], # Output shape: (2, 3, 3)\n [4, 2, 0],\n [0, 5, 3]],\n [[6, 0, 0],\n [9, 7, 0],\n [0, 1, 9]]]\n\n# Rectangular matrix.\ndiagonal = np.array([1, 2]) # Input shape: (2)\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n# Rectangular matrix with inferred num_cols and padding_value = 9.\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n```","inputs":[{"description":"Rank `r`, where `r >= 1`","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The number of rows of the output matrix. If it is not provided, the op assumes\nthe output matrix is a square matrix and infers the matrix size from k and the\ninnermost dimension of `diagonal`.","name":"num_rows","type":3},{"description":"The number of columns of the output matrix. If it is not provided, the op\nassumes the output matrix is a square matrix and infers the matrix size from\nk and the innermost dimension of `diagonal`.","name":"num_cols","type":3},{"description":"The number to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"Has rank `r+1` when `k` is an integer or `k[0] == k[1]`, rank `r` otherwise.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with given batched diagonal values."}},{"name":"MatrixDiagV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\ndiagonals of a matrix, with everything else padded with `padding`. `num_rows`\nand `num_cols` specify the dimension of the innermost matrix of the output. If\nboth are not specified, the op assumes the innermost matrix is square and infers\nits size from `k` and the innermost dimension of `diagonal`. If only one of them\nis specified, the op assumes the unspecified value is the smallest possible\nbased on other criteria.\n\nLet `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has\nrank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one\ndiagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank\n`r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\nThe second innermost dimension of `diagonal` has double meaning.\nWhen `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size\n[I, J, ..., M], and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n```\n\nOtherwise, `M` is treated as the number of diagonals for the matrix in the\nsame batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n```\nwhere `d = n - m`, `diag_index = [k] - d`, and\n`index_in_diag = n - max(d, 0) + offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nFor example:\n\n```\n# The main diagonal.\ndiagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n# A superdiagonal (per batch).\ndiagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n# A tridiagonal band (per batch).\ndiagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 2, 3],\n [6, 7, 9],\n [9, 1, 0]]])\ntf.matrix_diag(diagonals, k = (-1, 1))\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n# LEFT_RIGHT alignment.\ndiagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [0, 4, 5]],\n [[2, 3, 0],\n [6, 7, 9],\n [0, 9, 1]]])\ntf.matrix_diag(diagonals, k = (-1, 1), align=\"LEFT_RIGHT\")\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n# Rectangular matrix.\ndiagonal = np.array([1, 2]) # Input shape: (2)\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n# Rectangular matrix with inferred num_cols and padding_value = 9.\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n\n```","inputs":[{"description":"Rank `r`, where `r >= 1`","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The number of rows of the output matrix. If it is not provided, the op assumes\nthe output matrix is a square matrix and infers the matrix size from k and the\ninnermost dimension of `diagonal`.","name":"num_rows","type":3},{"description":"The number of columns of the output matrix. If it is not provided, the op\nassumes the output matrix is a square matrix and infers the matrix size from\nk and the innermost dimension of `diagonal`.","name":"num_cols","type":3},{"description":"The number to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"Has rank `r+1` when `k` is an integer or `k[0] == k[1]`, rank `r` otherwise.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with given batched diagonal values."}},{"name":"MatrixExponential","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Deprecated, use python implementation tf.linalg.matrix_exponential."}},{"name":"MatrixInverse","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the inverse for all input submatrices `[..., :, :]`.\n\nThe op uses LU decomposition with partial pivoting to compute the inverses.\n\nIf a matrix is not invertible there is no guarantee what the op does. It\nmay detect the condition and raise an exception or it may simply return a\ngarbage result.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(numpy)\nEquivalent to np.linalg.inv\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes)."}},{"name":"MatrixLogarithm","schema":{"attributes":[{"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n\\\\(log(exp(A)) = A\\\\)\n\nThis op is only defined for complex matrices. If A is positive-definite and\nreal, then casting to a complex matrix, taking the logarithm and casting back\nto a real matrix will give the correct result.\n\nThis function computes the matrix logarithm using the Schur-Parlett algorithm.\nDetails of the algorithm can be found in Section 11.6.2 of:\nNicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008.\nISBN 978-0-898716-46-7.\n\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the exponential for all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(scipy)\nEquivalent to scipy.linalg.logm\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the matrix logarithm of one or more square matrices:"}},{"name":"MatrixSetDiag","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the main diagonal of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\nThe output is computed as follows:\n\nAssume `input` has `k+1` dimensions `[I, J, K, ..., M, N]` and `diagonal` has\n`k` dimensions `[I, J, K, ..., min(M, N)]`. Then the output is a\ntensor of rank `k+1` with dimensions `[I, J, K, ..., M, N]` where:\n\n * `output[i, j, k, ..., m, n] = diagonal[i, j, k, ..., n]` for `m == n`.\n * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`.","inputs":[{"description":"Rank `k+1`, where `k >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `k`, where `k >= 1`.","name":"diagonal","typeAttr":"T"}],"outputs":[{"description":"Rank `k+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSetDiagV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the specified diagonals of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\n`input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n`k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\nOtherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n`num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n`max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\nThe output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\nIf `k` is scalar or `k[0] == k[1]`:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\n\nOtherwise,\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`.\n\nFor example:\n\n```\n# The main diagonal.\ninput = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\ndiagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_set_diag(diagonal) ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n# A superdiagonal (per batch).\ntf.matrix_set_diag(diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[1, 2, 3], # Diagonal shape: (2, 2, 3)\n [4, 5, 0]],\n [[6, 1, 2],\n [3, 4, 0]]])\ntf.matrix_set_diag(diagonals, k = (-1, 0))\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [4, 2, 7, 7],\n [0, 5, 3, 7]],\n [[6, 7, 7, 7],\n [3, 1, 7, 7],\n [7, 4, 2, 7]]]\n\n```","inputs":[{"description":"Rank `r+1`, where `r >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`.\n`k >= 1`.","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3}],"outputs":[{"description":"Rank `r+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSetDiagV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the specified diagonals of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\n`input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n`k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\nOtherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n`num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n`max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\nThe output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\nIf `k` is scalar or `k[0] == k[1]`:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\n\nOtherwise,\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and\n`index_in_diag = n - max(d, 0) + offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nFor example:\n\n```\n# The main diagonal.\ninput = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\ndiagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_set_diag(input, diagonal)\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n# A superdiagonal (per batch).\ntf.matrix_set_diag(input, diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 1, 2],\n [5, 6, 4],\n [6, 1, 2],\n [3, 4, 0]]])\ntf.matrix_set_diag(input, diagonals, k = (-1, 2))\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n# LEFT_RIGHT alignment.\ndiagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [0, 4, 5]],\n [[1, 2, 0],\n [5, 6, 4],\n [6, 1, 2],\n [0, 3, 4]]])\ntf.matrix_set_diag(input, diagonals, k = (-1, 2), align=\"LEFT_RIGHT\")\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n```","inputs":[{"description":"Rank `r+1`, where `r >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`.\n`k >= 1`.","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3}],"outputs":[{"description":"Rank `r+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSolve","schema":{"attributes":[{"default":false,"description":"Boolean indicating whether to solve with `matrix` or its (block-wise)\nadjoint.","name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"`Matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. `Rhs` is a tensor of shape `[..., M, K]`. The `output` is\na tensor shape `[..., M, K]`. If `adjoint` is `False` then each output matrix\nsatisfies `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`.\nIf `adjoint` is `True` then each output matrix satisfies\n`adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves systems of linear equations."}},{"name":"MatrixSolveLs","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"fast","type":"boolean"}],"description":"`matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform real or complex matrices of size `[M, N]`. `Rhs` is a tensor of the same\ntype as `matrix` and shape `[..., M, K]`.\nThe output is a tensor shape `[..., N, K]` where each output matrix solves\neach of the equations\n`matrix[..., :, :]` * `output[..., :, :]` = `rhs[..., :, :]`\nin the least squares sense.\n\nWe use the following notation for (complex) matrix and right-hand sides\nin the batch:\n\n`matrix`=\\\\(A \\in \\mathbb{C}^{m \\times n}\\\\),\n`rhs`=\\\\(B \\in \\mathbb{C}^{m \\times k}\\\\),\n`output`=\\\\(X \\in \\mathbb{C}^{n \\times k}\\\\),\n`l2_regularizer`=\\\\(\\lambda \\in \\mathbb{R}\\\\).\n\nIf `fast` is `True`, then the solution is computed by solving the normal\nequations using Cholesky decomposition. Specifically, if \\\\(m \\ge n\\\\) then\n\\\\(X = (A^H A + \\lambda I)^{-1} A^H B\\\\), which solves the least-squares\nproblem \\\\(X = \\mathrm{argmin}_{Z \\in \\Re^{n \\times k} } ||A Z - B||_F^2 + \\lambda ||Z||_F^2\\\\).\nIf \\\\(m \\lt n\\\\) then `output` is computed as\n\\\\(X = A^H (A A^H + \\lambda I)^{-1} B\\\\), which (for \\\\(\\lambda = 0\\\\)) is the\nminimum-norm solution to the under-determined linear system, i.e.\n\\\\(X = \\mathrm{argmin}_{Z \\in \\mathbb{C}^{n \\times k} } ||Z||_F^2 \\\\),\nsubject to \\\\(A Z = B\\\\). Notice that the fast path is only numerically stable\nwhen \\\\(A\\\\) is numerically full rank and has a condition number\n\\\\(\\mathrm{cond}(A) \\lt \\frac{1}{\\sqrt{\\epsilon_{mach} } }\\\\) or \\\\(\\lambda\\\\) is\nsufficiently large.\n\nIf `fast` is `False` an algorithm based on the numerically robust complete\northogonal decomposition is used. This computes the minimum-norm\nleast-squares solution, even when \\\\(A\\\\) is rank deficient. This path is\ntypically 6-7 times slower than the fast path. If `fast` is `False` then\n`l2_regularizer` is ignored.","inputs":[{"description":"Shape is `[..., M, N]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"},{"description":"Scalar tensor.\n\n@compatibility(numpy)\nEquivalent to np.linalg.lstsq\n@end_compatibility","name":"l2_regularizer","type":2}],"outputs":[{"description":"Shape is `[..., N, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves one or more linear least-squares problems."}},{"name":"MatrixSquareRoot","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"matmul(sqrtm(A), sqrtm(A)) = A\n\nThe input matrix should be invertible. If the input matrix is real, it should\nhave no eigenvalues which are real and negative (pairs of complex conjugate\neigenvalues are allowed).\n\nThe matrix square root is computed by first reducing the matrix to\nquasi-triangular form with the real Schur decomposition. The square root\nof the quasi-triangular matrix is then computed directly. Details of\nthe algorithm can be found in: Nicholas J. Higham, \"Computing real\nsquare roots of a real matrix\", Linear Algebra Appl., 1987.\n\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the matrix square root for all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(scipy)\nEquivalent to scipy.linalg.sqrtm\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the matrix square root of one or more square matrices:"}},{"name":"MatrixTriangularSolve","schema":{"attributes":[{"default":true,"description":"Boolean indicating whether the innermost matrices in `matrix` are\nlower or upper triangular.","name":"lower","type":"boolean"},{"default":false,"description":"Boolean indicating whether to solve with `matrix` or its (block-wise)\n adjoint.\n\n@compatibility(numpy)\nEquivalent to scipy.linalg.solve_triangular\n@end_compatibility","name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n`matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form\nsquare matrices. If `lower` is `True` then the strictly upper triangular part\nof each inner-most matrix is assumed to be zero and not accessed.\nIf `lower` is False then the strictly lower triangular part of each inner-most\nmatrix is assumed to be zero and not accessed.\n`rhs` is a tensor of shape `[..., M, N]`.\n\nThe output is a tensor of shape `[..., M, N]`. If `adjoint` is\n`True` then the innermost matrices in `output` satisfy matrix equations\n`matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`.\nIf `adjoint` is `False` then the strictly then the innermost matrices in\n`output` satisfy matrix equations\n`adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`.\n\nNote, the batch shapes for the inputs only need to broadcast.\n\nExample:\n```python\n\na = tf.constant([[3, 0, 0, 0],\n [2, 1, 0, 0],\n [1, 0, 1, 0],\n [1, 1, 1, 1]], dtype=tf.float32)\n\nb = tf.constant([[4],\n [2],\n [4],\n [2]], dtype=tf.float32)\n\nx = tf.linalg.triangular_solve(a, b, lower=True)\nx\n# \n\n# in python3 one can use `a@x`\ntf.matmul(a, x)\n# \n```","inputs":[{"description":"Shape is `[..., M, M]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves systems of linear equations with upper or lower triangular matrices by backsubstitution."}},{"name":"Max","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum of elements across dimensions of a tensor."}},{"name":"MaxIntraOpParallelismDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the maximum intra-op parallelism to use.","name":"max_intra_op_parallelism","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that overrides the maximum intra-op parallelism."}},{"name":"MaxPool","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"category":"Pool","inputs":[{"description":"4-D input to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs max pooling on the input."}},{"name":"MaxPool3D","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, channels]` tensor to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs 3D max pooling on the input."}},{"name":"MaxPool3DGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"TInput","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"TInput"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"TInput"},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients of 3D max pooling function."}},{"name":"MaxPool3DGradGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGrad","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients w.r.t. the output of `max_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolGradGrad","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients of gradients w.r.t. the input of `max_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradGradV2","schema":{"attributes":[{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients of gradients w.r.t. the input of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradGradWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input.","name":"input","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the\ninput of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The indices of the maximum values chosen for each output of `max_pool`.","name":"argmax","typeAttr":"Targmax"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input of `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradV2","schema":{"attributes":[{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients w.r.t. the output of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"Gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolGradWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input.","name":"input","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the\noutput of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The indices of the maximum values chosen for each output of `max_pool`.","name":"argmax","typeAttr":"Targmax"}],"outputs":[{"description":"Gradients w.r.t. the input of `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"category":"Pool","inputs":[{"description":"4-D input to pool over.","name":"input","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs max pooling on the input."}},{"name":"MaxPoolWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The indices in `argmax` are flattened, so that a maximum value at position\n`[b, y, x, c]` becomes flattened index:\n`(y * width + x) * channels + c` if `include_batch_in_index` is False;\n`((b * height + y) * width + x) * channels + c` if `include_batch_in_index` is True.\n\nThe indices returned are always in `[0, height) x [0, width)` before flattening,\neven if padding is involved and the mathematically correct answer is outside\n(either negative or too large). This is a bug, but fixing it is difficult to do\nin a safe backwards compatible way, especially due to flattening.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`. Input to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"},{"description":"4-D. The flattened indices of the max values chosen for each output.","name":"argmax","typeAttr":"Targmax"}],"summary":"Performs max pooling on the input and outputs both max values and indices."}},{"name":"Maximum","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"*NOTE*: `Maximum` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns the max of x and y (i.e. x > y ? x : y) element-wise."}},{"name":"Mean","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the mean of elements across dimensions of a tensor."}},{"name":"Merge","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"description":"`Merge` waits for at least one of the tensors in `inputs` to become available.\nIt is usually combined with `Switch` to implement branching.\n\n`Merge` forwards the first tensor to become available to `output`, and sets\n`value_index` to its index in `inputs`.","inputs":[{"description":"The input tensors, exactly one of which will become available.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Will be set to the available input tensor.","name":"output","typeAttr":"T"},{"description":"The index of the chosen input tensor in `inputs`.","name":"value_index","type":3}],"summary":"Forwards the value of an available tensor from `inputs` to `output`."}},{"name":"MergeSummary","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"}],"description":"This op creates a\n[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\nprotocol buffer that contains the union of all the values in the input\nsummaries.\n\nWhen the Op is run, it reports an `InvalidArgument` error if multiple values\nin the summaries to merge use the same tag.","inputs":[{"description":"Can be of any shape. Each must contain serialized `Summary` protocol\nbuffers.","name":"inputs","numberAttr":"N","type":7}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Merges summaries."}},{"name":"MergeV2Checkpoints","schema":{"attributes":[{"default":true,"description":"see above.","name":"delete_old_dirs","type":"boolean"}],"description":"result is one logical checkpoint, with one physical metadata file and renamed\ndata files.\n\nIntended for \"grouping\" multiple checkpoints in a sharded checkpoint setup.\n\nIf delete_old_dirs is true, attempts to delete recursively the dirname of each\npath in the input checkpoint_prefixes. This is useful when those paths are non\nuser-facing temporary locations.","inputs":[{"description":"prefixes of V2 checkpoints to merge.","name":"checkpoint_prefixes","type":7},{"description":"scalar. The desired final prefix. Allowed to be the same\nas one of the checkpoint_prefixes.","name":"destination_prefix","type":7}],"summary":"V2 format specific: merges the metadata files of sharded checkpoints. The"}},{"name":"Mfcc","schema":{"attributes":[{"default":4000,"description":"The highest frequency to use when calculating the\nceptstrum.","name":"upper_frequency_limit","type":"float32"},{"default":20,"description":"The lowest frequency to use when calculating the\nceptstrum.","name":"lower_frequency_limit","type":"float32"},{"default":40,"description":"Resolution of the Mel bank used internally.","name":"filterbank_channel_count","type":"int64"},{"default":13,"description":"How many output channels to produce per time slice.","name":"dct_coefficient_count","type":"int64"}],"description":"Mel Frequency Cepstral Coefficients are a way of representing audio data that's\nbeen effective as an input feature for machine learning. They are created by\ntaking the spectrum of a spectrogram (a 'cepstrum'), and discarding some of the\nhigher frequencies that are less significant to the human ear. They have a long\nhistory in the speech recognition world, and https://en.wikipedia.org/wiki/Mel-frequency_cepstrum\nis a good resource to learn more.","inputs":[{"description":"Typically produced by the Spectrogram op, with magnitude_squared\nset to true.","name":"spectrogram","type":1},{"description":"How many samples per second the source audio used.","name":"sample_rate","type":3}],"outputs":[{"name":"output","type":1}],"summary":"Transforms a spectrogram into a form that's useful for speech recognition."}},{"name":"Min","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum of elements across dimensions of a tensor."}},{"name":"Minimum","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"*NOTE*: `Minimum` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns the min of x and y (i.e. x < y ? x : y) element-wise."}},{"name":"MirrorPad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"description":"Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions\ndo not include the borders, while in symmetric mode the padded regions\ndo include the borders. For example, if `input` is `[1, 2, 3]` and `paddings`\nis `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and\nit is `[1, 2, 3, 3, 2]` in symmetric mode. Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"}],"description":"This operation pads a `input` with mirrored values according to the `paddings`\nyou specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is\nthe rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many values to add before the contents of `input` in that dimension, and\n`paddings[D, 1]` indicates how many values to add after the contents of `input`\nin that dimension. Both `paddings[D, 0]` and `paddings[D, 1]` must be no greater\nthan `input.dim_size(D)` (or `input.dim_size(D) - 1`) if `copy_border` is true\n(if false, respectively).\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 2, 3], [4, 5, 6]].\n# 'paddings' is [[1, 1]], [2, 2]].\n# 'mode' is SYMMETRIC.\n# rank of 't' is 2.\npad(t, paddings) ==> [[2, 1, 1, 2, 3, 3, 2]\n [2, 1, 1, 2, 3, 3, 2]\n [5, 4, 4, 5, 6, 6, 5]\n [5, 4, 4, 5, 6, 6, 5]]\n```","inputs":[{"description":"The input tensor to be padded.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"description":"The padded tensor.","name":"output","typeAttr":"T"}],"summary":"Pads a tensor with mirrored values."}},{"name":"MirrorPadGrad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"description":"The mode used in the `MirrorPad` op. Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"}],"description":"This operation folds the padded areas of `input` by `MirrorPad` according to the\n`paddings` you specify. `paddings` must be the same as `paddings` argument\ngiven to the corresponding `MirrorPad` op.\n\nThe folded size of each dimension D of the output is:\n\n`input.dim_size(D) - paddings(D, 0) - paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 2, 3], [4, 5, 6], [7, 8, 9]].\n# 'paddings' is [[0, 1]], [0, 1]].\n# 'mode' is SYMMETRIC.\n# rank of 't' is 2.\npad(t, paddings) ==> [[ 1, 5]\n [11, 28]]\n```","inputs":[{"description":"The input tensor to be folded.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"description":"The folded tensor.","name":"output","typeAttr":"T"}],"summary":"Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor."}},{"name":"MlirPassthroughOp","schema":{"attributes":[{"name":"mlir_module","type":"string"},{"minimum":0,"name":"Tinputs","type":"type[]"},{"minimum":0,"name":"Toutputs","type":"type[]"}],"description":"This operation does not have an associated kernel and is not intended to be\nexecuted in a regular TensorFlow session. Instead it is intended to be used for\ntesting or for special case where a user intends to pass custom MLIR computation\nthrough a TensorFlow graph with the intent of having custom tooling processing\nit downstream (when targeting a different environment, like TensorFlow lite for\nexample).\nThe MLIR module is expected to have a main() function that will be used as an\nentry point. The inputs to the operations will be passed as argument to the\nmain() function and the returned values of the main function mapped to the\noutputs.\nExample usage:\n\n```\nimport tensorflow as tf\nfrom tensorflow.compiler.mlir.tensorflow.gen_mlir_passthrough_op import mlir_passthrough_op\n\nmlir_module = '''python\nfunc @main(%arg0 : tensor<10xf32>, %arg1 : tensor<10xf32>) -> tensor<10x10xf32> {\n %add = \"magic.op\"(%arg0, %arg1) : (tensor<10xf32>, tensor<10xf32>) -> tensor<10x10xf32>\n return %ret : tensor<10x10xf32>\n}\n'''\n\n@tf.function\ndef foo(x, y):\n return mlir_passthrough_op([x, y], mlir_module, Toutputs=[tf.float32])\n\ngraph_def = foo.get_concrete_function(tf.TensorSpec([10], tf.float32), tf.TensorSpec([10], tf.float32)).graph.as_graph_def()\n```","inputs":[{"name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"name":"outputs","typeListAttr":"Toutputs"}],"summary":"Wraps an arbitrary MLIR computation expressed as a module with a main() function."}},{"name":"Mod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float16`, `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"the result here is consistent with a truncating divide. E.g.\n`tf.truncatediv(x, y) * y + truncate_mod(x, y) = x`.\n\n*NOTE*: `Mod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. This emulates C semantics in that"}},{"name":"ModelDataset","schema":{"attributes":[{"default":0,"name":"algorithm","type":"int64"},{"default":0,"name":"cpu_budget","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Identity transformation that models performance.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Identity transformation that models performance."}},{"name":"Mul","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Mul` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x * y element-wise."}},{"name":"MulNoNan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `MulNoNan` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x * y element-wise. Returns zero if y is zero, even if x if infinite or NaN."}},{"name":"MultiDeviceIterator","schema":{"attributes":[{"description":"A list of devices the iterator works across.","minimum":1,"name":"devices","type":"string[]"},{"description":"If non-empty, this resource will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"},{"description":"If non-empty, this resource is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"Handle to the resource created.","name":"handle","type":20}],"summary":"Creates a MultiDeviceIterator resource."}},{"name":"MultiDeviceIteratorFromStringHandle","schema":{"attributes":[{"default":[],"description":"The type list for the return values.","minimum":0,"name":"output_types","type":"type[]"},{"default":[],"description":"The list of shapes being produced.","minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"String representing the resource.","name":"string_handle","type":7}],"outputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20}],"summary":"Generates a MultiDeviceIterator resource from its provided string handle."}},{"name":"MultiDeviceIteratorGetNextFromShard","schema":{"attributes":[{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20},{"description":"Integer representing which shard to fetch data for.","name":"shard_num","type":3},{"description":"Which incarnation of the MultiDeviceIterator is running.","name":"incarnation_id","type":9}],"outputs":[{"description":"Result of the get_next on the dataset.","name":"components","typeListAttr":"output_types"}],"summary":"Gets next element for the provided shard number."}},{"name":"MultiDeviceIteratorInit","schema":{"inputs":[{"description":"Dataset to be iterated upon.","name":"dataset","type":21},{"description":"A MultiDeviceIteratorResource.","name":"multi_device_iterator","type":20},{"description":"The maximum size of the host side per device buffer to keep.","name":"max_buffer_size","type":9}],"outputs":[{"description":"An int64 indicating which incarnation of the MultiDeviceIterator\nis running.","name":"incarnation_id","type":9}],"summary":"Initializes the multi device iterator with the given dataset."}},{"name":"MultiDeviceIteratorToStringHandle","schema":{"inputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20}],"outputs":[{"description":"A string representing the resource.","name":"string_handle","type":7}],"summary":"Produces a string handle for the given MultiDeviceIterator."}},{"name":"Multinomial","schema":{"attributes":[{"default":0,"description":"If either seed or seed2 is set to be non-zero, the internal random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_dtype","type":"type"}],"inputs":[{"description":"2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]`\nrepresents the unnormalized log probabilities for all classes.","name":"logits","typeAttr":"T"},{"description":"0-D. Number of independent samples to draw for each row slice.","name":"num_samples","type":3}],"outputs":[{"description":"2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]`\ncontains the drawn class labels with range `[0, num_classes)`.","name":"output","typeAttr":"output_dtype"}],"summary":"Draws samples from a multinomial distribution."}},{"name":"MutableDenseHashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of each value.","name":"value_shape","type":"shape"},{"default":131072,"description":"The initial number of hash table buckets. Must be a power\nto 2.","name":"initial_num_buckets","type":"int64"},{"default":0.800000011920929,"description":"The maximum ratio between number of entries and number of\nbuckets before growing the table. Must be between 0 and 1.","name":"max_load_factor","type":"float32"}],"description":"It uses \"open addressing\" with quadratic reprobing to resolve\ncollisions.\n\nThis op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","inputs":[{"description":"The key used to represent empty key buckets internally. Must not\nbe used in insert or lookup operations.","name":"empty_key","typeAttr":"key_dtype"}],"outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table that uses tensors as the backing store."}},{"name":"MutableDenseHashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of each value.","name":"value_shape","type":"shape"},{"default":131072,"description":"The initial number of hash table buckets. Must be a power\nto 2.","name":"initial_num_buckets","type":"int64"},{"default":0.800000011920929,"description":"The maximum ratio between number of entries and number of\nbuckets before growing the table. Must be between 0 and 1.","name":"max_load_factor","type":"float32"}],"description":"It uses \"open addressing\" with quadratic reprobing to resolve\ncollisions.\n\nThis op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","inputs":[{"description":"The key used to represent empty key buckets internally. Must not\nbe used in insert or lookup operations.","name":"empty_key","typeAttr":"key_dtype"},{"name":"deleted_key","typeAttr":"key_dtype"}],"outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table that uses tensors as the backing store."}},{"name":"MutableHashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableOfTensors","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"value_shape","type":"shape"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a vector. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableOfTensorsV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"value_shape","type":"shape"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a vector. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table."}},{"name":"MutexLock","schema":{"description":"is alive, any other request to use `MutexLock` with this mutex will wait.\n\nThis is particularly useful for creating a critical section when used in\nconjunction with `MutexLockIdentity`:\n\n```python\n\nmutex = mutex_v2(\n shared_name=handle_name, container=container, name=name)\n\ndef execute_in_critical_section(fn, *args, **kwargs):\n lock = gen_resource_variable_ops.mutex_lock(mutex)\n\n with ops.control_dependencies([lock]):\n r = fn(*args, **kwargs)\n\n with ops.control_dependencies(nest.flatten(r)):\n with ops.colocate_with(mutex):\n ensure_lock_exists = mutex_lock_identity(lock)\n\n # Make sure that if any element of r is accessed, all of\n # them are executed together.\n r = nest.map_structure(tf.identity, r)\n\n with ops.control_dependencies([ensure_lock_exists]):\n return nest.map_structure(tf.identity, r)\n```\n\nWhile `fn` is running in the critical section, no other functions which wish to\nuse this critical section may run.\n\nOften the use case is that two executions of the same graph, in parallel,\nwish to run `fn`; and we wish to ensure that only one of them executes\nat a time. This is especially important if `fn` modifies one or more\nvariables at a time.\n\nIt is also useful if two separate functions must share a resource, but we\nwish to ensure the usage is exclusive.","inputs":[{"description":"The mutex resource to lock.","name":"mutex","type":20}],"outputs":[{"description":"A tensor that keeps a shared pointer to a lock on the mutex;\nwhen the Tensor is destroyed, the use count on the shared pointer is decreased\nby 1. When it reaches 0, the lock is released.","name":"mutex_lock","type":21}],"summary":"Locks a mutex resource. The output is the lock. So long as the lock tensor"}},{"name":"MutexV2","schema":{"attributes":[{"default":"","description":"If non-empty, this variable is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this variable is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The mutex resource.","name":"resource","type":20}],"summary":"Creates a Mutex resource that can be locked by `MutexLock`."}},{"name":"NcclAllReduce","schema":{"attributes":[{"description":"Must be one of the following: `min`, `max`, `prod`, `sum`.","name":"reduction","type":"string"},{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"num_devices","type":"int64"},{"name":"shared_name","type":"string"}],"description":"Outputs a tensor containing the reduction across all input tensors passed to ops\nwithin the same `shared_name.\n\nThe graph should be constructed so if one op runs with shared_name value `c`,\nthen `num_devices` ops will run with shared_name value `c`. Failure to do so\nwill cause the graph execution to fail to complete.\n\ninput: the input to the reduction\ndata: the value of the reduction across all `num_devices` devices.\nreduction: the reduction operation to perform.\nnum_devices: The number of devices participating in this reduction.\nshared_name: Identifier that shared between ops of the same reduction.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Outputs a tensor containing the reduction across all input tensors."}},{"name":"NcclBroadcast","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"shape","type":"shape"}],"description":"Sends `input` to all devices that are connected to the output.\n\nThe graph should be constructed so that all ops connected to the output have a\nvalid device assignment, and the op itself is assigned one of these devices.\n\ninput: The input to the broadcast.\noutput: The same as input.\nshape: The shape of the input tensor.\n","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Sends `input` to all devices that are connected to the output."}},{"name":"NcclReduce","schema":{"attributes":[{"description":"Must be one of the following: `min`, `max`, `prod`, `sum`.","name":"reduction","type":"string"},{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"minimum":1,"name":"num_devices","type":"int64"}],"description":"Reduces `input` from `num_devices` using `reduction` to a single device.\n\nThe graph should be constructed so that all inputs have a valid device\nassignment, and the op itself is assigned one of these devices.\n\ninput: The input to the reduction.\ndata: the value of the reduction across all `num_devices` devices.\nreduction: the reduction operation to perform.","inputs":[{"name":"input","numberAttr":"num_devices","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Reduces `input` from `num_devices` using `reduction` to a single device."}},{"name":"Ndtri","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"NearestNeighbors","schema":{"description":"Rows of points are assumed to be input points. Rows of centers are assumed to be\nthe list of candidate centers. For each point, the k centers that have least L2\ndistance to it are computed.","inputs":[{"description":"Matrix of shape (n, d). Rows are assumed to be input points.","name":"points","type":1},{"description":"Matrix of shape (m, d). Rows are assumed to be centers.","name":"centers","type":1},{"description":"Number of nearest centers to return for each point. If k is larger than m, then\nonly m centers are returned.","name":"k","type":9}],"outputs":[{"description":"Matrix of shape (n, min(m, k)). Each row contains the indices of the centers\nclosest to the corresponding point, ordered by increasing distance.","name":"nearest_center_indices","type":9},{"description":"Matrix of shape (n, min(m, k)). Each row contains the squared L2 distance to the\ncorresponding center in nearest_center_indices.","name":"nearest_center_distances","type":1}],"summary":"Selects the k nearest centers for each point."}},{"name":"Neg","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = -x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes numerical negative value element-wise."}},{"name":"NegTrain","schema":{"attributes":[{"description":"Count of words in the vocabulary.","name":"vocab_count","type":"int64[]"},{"description":"Number of negative samples per example.","name":"num_negative_samples","type":"int64"}],"inputs":[{"description":"input word embedding.","isRef":true,"name":"w_in","type":1},{"description":"output word embedding.","isRef":true,"name":"w_out","type":1},{"description":"A vector of word ids.","name":"examples","type":3},{"description":"A vector of word ids.","name":"labels","type":3},{"name":"lr","type":1}],"summary":"Training via negative sampling."}},{"name":"NextAfter","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"description":"This operation returns the same result as the C++ std::nextafter function.\n\nIt can also return a subnormal number.\n\n@compatibility(cpp)\nEquivalent to C++ std::nextafter function.\n@end_compatibility","inputs":[{"name":"x1","typeAttr":"T"},{"name":"x2","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the next representable value of `x1` in the direction of `x2`, element-wise."}},{"name":"NextIteration","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be made available to the next iteration.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Makes its input available to the next iteration."}},{"name":"NoOp","schema":{"summary":"Does nothing. Only useful as a placeholder for control edges."}},{"name":"NonDeterministicInts","schema":{"attributes":[{"default":{"type":"type","value":9},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Non-deterministic integer values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Non-deterministically generates some integers."}},{"name":"NonMaxSuppression","schema":{"attributes":[{"default":0.5,"description":"A float representing the threshold for deciding whether boxes\noverlap too much with respect to IOU.","name":"iou_threshold","type":"float32"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Note that this\nalgorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression(\n boxes, scores, max_output_size, iou_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","type":1},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Note that this\nalgorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\n\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV3","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV4","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"},{"default":false,"description":"If true, the output `selected_indices` is padded to be of length\n`max_output_size`. Defaults to false.","name":"pad_to_max_output_size","type":"boolean"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3},{"description":"A 0-D integer tensor representing the number of valid elements in\n`selected_indices`, with the valid elements appearing first.","name":"valid_outputs","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV5","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":false,"description":"If true, the output `selected_indices` is padded to be of length\n`max_output_size`. Defaults to false.","name":"pad_to_max_output_size","type":"boolean"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)\nThis op also supports a Soft-NMS (with Gaussian weighting) mode (c.f.\nBodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\nof other overlapping boxes instead of directly causing them to be pruned.\nTo enable this Soft-NMS mode, set the `soft_nms_sigma` parameter to be\nlarger than 0.","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T"},{"description":"A 0-D float tensor representing the sigma parameter for Soft NMS; see Bodla et\nal (c.f. https://arxiv.org/abs/1704.04503). When `soft_nms_sigma=0.0` (which\nis default), we fall back to standard (hard) NMS.","name":"soft_nms_sigma","typeAttr":"T"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3},{"description":"A 1-D float tensor of shape `[M]` representing the corresponding\nscores for each selected box, where `M <= max_output_size`. Scores only differ\nfrom corresponding input scores when using Soft NMS (i.e. when\n`soft_nms_sigma>0`)","name":"selected_scores","typeAttr":"T"},{"description":"A 0-D integer tensor representing the number of valid elements in\n`selected_indices`, with the valid elements appearing first.","name":"valid_outputs","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionWithOverlaps","schema":{"description":"pruning away boxes that have high overlaps\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. N-by-n overlap values are supplied as square matrix,\nwhich allows for defining a custom overlap criterium (eg. intersection over union,\nintersection over area, etc.).\n\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n\n selected_indices = tf.image.non_max_suppression_with_overlaps(\n overlaps, scores, max_output_size, overlap_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, num_boxes]` representing\nthe n-by-n box overlap values.","name":"overlaps","type":1},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too.","name":"overlap_threshold","type":1},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","type":1}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonSerializableDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"NotEqual","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `uint16`, `uint32`, `uint64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"incompatible_shape_error","type":"boolean"}],"description":"*NOTE*: `NotEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x != y) element-wise."}},{"name":"NthElement","schema":{"attributes":[{"default":false,"description":"When set to True, find the nth-largest value in the vector and vice\nversa.","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the entries which is the nth-smallest\nvalue in the vector and outputs their values as scalar tensor.\n\nFor matrices (resp. higher rank input), computes the entries which is the\nnth-smallest value in each row (resp. vector along the last dimension). Thus,\n\n values.shape = input.shape[:-1]","inputs":[{"description":"1-D or higher with last dimension at least `n+1`.","name":"input","typeAttr":"T"},{"description":"0-D. Position of sorted vector to select along the last dimension (along\neach row for matrices). Valid range of n is `[0, input.shape[:-1])`","name":"n","type":3}],"outputs":[{"description":"The `n`-th order statistic along each last dimensional slice.","name":"values","typeAttr":"T"}],"summary":"Finds values of the `n`-th order statistic for the last dimension."}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"The axis to fill (default: -1, a new inner-most axis).","name":"axis","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `uint8`, `int32`, `int64`.","name":"TI","type":"type"}],"description":"The locations represented by indices in `indices` take value `on_value`,\nwhile all other locations take value `off_value`.\n\nIf the input `indices` is rank `N`, the output will have rank `N+1`,\nThe new axis is created at dimension `axis` (default: the new axis is\nappended at the end).\n\nIf `indices` is a scalar the output shape will be a vector of length `depth`.\n\nIf `indices` is a vector of length `features`, the output shape will be:\n```\n features x depth if axis == -1\n depth x features if axis == 0\n```\n\nIf `indices` is a matrix (batch) with shape `[batch, features]`,\nthe output shape will be:\n```\n batch x features x depth if axis == -1\n batch x depth x features if axis == 1\n depth x batch x features if axis == 0\n```\n\n\nExamples\n=========\n\nSuppose that\n```\n indices = [0, 2, -1, 1]\n depth = 3\n on_value = 5.0\n off_value = 0.0\n axis = -1\n```\n\nThen output is `[4 x 3]`:\n```\noutput =\n [5.0 0.0 0.0] // one_hot(0)\n [0.0 0.0 5.0] // one_hot(2)\n [0.0 0.0 0.0] // one_hot(-1)\n [0.0 5.0 0.0] // one_hot(1)\n```\n\nSuppose that\n```\n indices = [0, 2, -1, 1]\n depth = 3\n on_value = 0.0\n off_value = 3.0\n axis = 0\n```\n\nThen output is `[3 x 4]`:\n```\noutput =\n [0.0 3.0 3.0 3.0]\n [3.0 3.0 3.0 0.0]\n [3.0 3.0 3.0 3.0]\n [3.0 0.0 3.0 3.0]\n// ^ one_hot(0)\n// ^ one_hot(2)\n// ^ one_hot(-1)\n// ^ one_hot(1)\n```\n\nSuppose that\n```\n indices = [[0, 2], [1, -1]]\n depth = 3\n on_value = 1.0\n off_value = 0.0\n axis = -1\n```\n\nThen output is `[2 x 2 x 3]`:\n```\noutput =\n [\n [1.0, 0.0, 0.0] // one_hot(0)\n [0.0, 0.0, 1.0] // one_hot(2)\n ][\n [0.0, 1.0, 0.0] // one_hot(1)\n [0.0, 0.0, 0.0] // one_hot(-1)\n ]\n```","inputs":[{"description":"A tensor of indices.","name":"indices","typeAttr":"TI"},{"description":"A scalar defining the depth of the one hot dimension.","name":"depth","type":3},{"description":"A scalar defining the value to fill in output when `indices[j] = i`.","name":"on_value","typeAttr":"T"},{"description":"A scalar defining the value to fill in output when `indices[j] != i`.","name":"off_value","typeAttr":"T"}],"outputs":[{"description":"The one-hot tensor.","name":"output","typeAttr":"T"}],"summary":"Returns a one-hot tensor."}},{"name":"OneShotIterator","schema":{"attributes":[{"description":"A function of type `() -> DT_VARIANT`, where the returned\nDT_VARIANT is a dataset.","name":"dataset_factory","type":"function"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"A one-shot iterator bundles the logic for defining the dataset and\nthe state of the iterator in a single op, which allows simple input\npipelines to be defined without an additional initialization\n(\"MakeIterator\") step.\n\nOne-shot iterators have the following limitations:\n\n* They do not support parameterization: all logic for creating the underlying\n dataset must be bundled in the `dataset_factory` function.\n* They are not resettable. Once a one-shot iterator reaches the end of its\n underlying dataset, subsequent \"IteratorGetNext\" operations on that\n iterator will always produce an `OutOfRange` error.\n\nFor greater flexibility, use \"Iterator\" and \"MakeIterator\" to define\nan iterator using an arbitrary subgraph, which may capture tensors\n(including fed values) as parameters, and which may be reset multiple\ntimes by rerunning \"MakeIterator\".","outputs":[{"description":"A handle to the iterator that can be passed to an \"IteratorGetNext\"\nop.","name":"handle","type":20}],"summary":"Makes a \"one-shot\" iterator that can be iterated only once."}},{"name":"OnesLike","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`, `complex128`, `bool`.","name":"T","type":"type"}],"inputs":[{"description":"a tensor of type T.","name":"x","typeAttr":"T"}],"outputs":[{"description":"a tensor of the same shape and type as x but filled with ones.","name":"y","typeAttr":"T"}],"summary":"Returns a tensor of ones with the same shape and type as x."}},{"name":"OptimizeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":[],"name":"optimization_configs","type":"string[]"}],"description":"Creates a dataset by applying optimizations to `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A `tf.string` vector `tf.Tensor` identifying optimizations to use.","name":"optimizations","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset by applying optimizations to `input_dataset`."}},{"name":"OptionalFromValue","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"optional","type":21}],"summary":"Constructs an Optional variant from a tuple of tensors."}},{"name":"OptionalGetValue","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"optional","type":21}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Returns the value stored in an Optional variant or raises an error if none exists."}},{"name":"OptionalHasValue","schema":{"inputs":[{"name":"optional","type":21}],"outputs":[{"name":"has_value","type":10}],"summary":"Returns true if and only if the given Optional variant has a value."}},{"name":"OptionalNone","schema":{"outputs":[{"name":"optional","type":21}],"summary":"Creates an Optional variant with no value."}},{"name":"OrderedMapClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"OrderedMapIncompleteSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of incomplete elements in the underlying container."}},{"name":"OrderedMapPeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain this key\nthis op will block until it does. This Op is optimized for\nperformance.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified key. If the"}},{"name":"OrderedMapSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"OrderedMapStage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"minimum":1,"name":"fake_dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"description":"associative container. Elements are ordered by key.","inputs":[{"description":"int64","name":"key","type":9},{"name":"indices","type":3},{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"fake_dtypes"}],"summary":"Stage (key, values) in the underlying container which behaves like a ordered"}},{"name":"OrderedMapUnstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain this key, the op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the values associated with the key"}},{"name":"OrderedMapUnstageNoKey","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"key from the underlying container. If the underlying container\ndoes not contain elements, the op will block until it does.","inputs":[{"name":"indices","type":3}],"outputs":[{"name":"key","type":9},{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the (key, value) element with the smallest"}},{"name":"OutfeedDequeue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"description":"This operation will block indefinitely until data is available.","outputs":[{"description":"A tensor that will be read from the device outfeed.","name":"output","typeAttr":"dtype"}],"summary":"Retrieves a single tensor from the computation outfeed."}},{"name":"OutfeedDequeueTuple","schema":{"attributes":[{"description":"The element types of each element in `outputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `outputs`.","name":"shapes","type":"shape[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"description":"This operation will block indefinitely until data is available. Output `i`\ncorresponds to XLA tuple element `i`.","outputs":[{"description":"A list of tensors that will be read from the outfeed.","name":"outputs","typeListAttr":"dtypes"}],"summary":"Retrieve multiple values from the computation outfeed."}},{"name":"OutfeedEnqueue","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"description":"A tensor that will be inserted into the outfeed queue.","name":"input","typeAttr":"dtype"}],"summary":"Enqueue a Tensor on the computation outfeed."}},{"name":"OutfeedEnqueueTuple","schema":{"attributes":[{"minimum":1,"name":"dtypes","type":"type[]"}],"inputs":[{"description":"A list of tensors that will be inserted into the outfeed queue as an\nXLA tuple.","name":"inputs","typeListAttr":"dtypes"}],"summary":"Enqueue multiple Tensor values on the computation outfeed."}},{"name":"Pack","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"Dimension along which to pack. Negative values wrap around, so the\nvalid range is `[-(R+1), R+1)`.","name":"axis","type":"int64"}],"description":"Packs the `N` tensors in `values` into a tensor with rank one higher than each\ntensor in `values`, by packing them along the `axis` dimension.\nGiven a list of tensors of shape `(A, B, C)`;\n\nif `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`.\nif `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`.\nEtc.\n\nFor example:\n\n```\n# 'x' is [1, 4]\n# 'y' is [2, 5]\n# 'z' is [3, 6]\npack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim.\npack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]]\n```\n\nThis is the opposite of `unpack`.","inputs":[{"description":"Must be of same shape and type.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The packed tensor.","name":"output","typeAttr":"T"}],"summary":"Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor."}},{"name":"Pad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"category":"Tensor","description":"This operation pads a `input` with zeros according to the `paddings` you\nspecify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the\nrank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many zeros to add before the contents of `input` in that dimension, and\n`paddings[D, 1]` indicates how many zeros to add after the contents of `input`\nin that dimension.\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 1], [2, 2]]\n# 'paddings' is [[1, 1], [2, 2]]\n# rank of 't' is 2\npad(t, paddings) ==> [[0, 0, 0, 0, 0, 0]\n [0, 0, 1, 1, 0, 0]\n [0, 0, 2, 2, 0, 0]\n [0, 0, 0, 0, 0, 0]]\n```\n","inputs":[{"name":"input","typeAttr":"T"},{"name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Pads a tensor with zeros."}},{"name":"PadV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"description":"This operation pads `input` according to the `paddings` and `constant_values`\nyou specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is\nthe rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many padding values to add before the contents of `input` in that dimension,\nand `paddings[D, 1]` indicates how many padding values to add after the contents\nof `input` in that dimension. `constant_values` is a scalar tensor of the same\ntype as `input` that indicates the value to use for padding `input`.\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 1], [2, 2]]\n# 'paddings' is [[1, 1], [2, 2]]\n# 'constant_values' is 0\n# rank of 't' is 2\npad(t, paddings) ==> [[0, 0, 0, 0, 0, 0]\n [0, 0, 1, 1, 0, 0]\n [0, 0, 2, 2, 0, 0]\n [0, 0, 0, 0, 0, 0]]\n```","inputs":[{"name":"input","typeAttr":"T"},{"name":"paddings","typeAttr":"Tpaddings"},{"name":"constant_values","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Pads a tensor."}},{"name":"PaddedBatchDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A list of int64 tensors representing the desired padded shapes\nof the corresponding output components. These shapes may be partially\nspecified, using `-1` to indicate that a particular dimension should be\npadded to the maximum size of all batch elements.","name":"padded_shapes","numberAttr":"N","type":9},{"description":"A list of scalars containing the padding value to use for\neach of the outputs.","name":"padding_values","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches and pads `batch_size` elements from the input."}},{"name":"PaddedBatchDatasetV2","schema":{"attributes":[{"default":false,"name":"parallel_copy","type":"boolean"},{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A list of int64 tensors representing the desired padded shapes\nof the corresponding output components. These shapes may be partially\nspecified, using `-1` to indicate that a particular dimension should be\npadded to the maximum size of all batch elements.","name":"padded_shapes","numberAttr":"N","type":9},{"description":"A list of scalars containing the padding value to use for\neach of the outputs.","name":"padding_values","typeListAttr":"Toutput_types"},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches and pads `batch_size` elements from the input."}},{"name":"PaddingFIFOQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types.\nShapes of fixed rank but variable size are allowed by setting\nany shape dimension to -1. In this case, the inputs' shape may vary along\nthe given dimension, and DequeueMany will pad the given dimension with\nzeros up to the maximum shape of all elements in the given batch.\nIf the length of this attr is 0, different queue elements may have\ndifferent ranks and shapes, but only one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Variable-size shapes are allowed by setting the corresponding shape dimensions\nto 0 in the shape attr. In this case DequeueMany will pad up to the maximum\nsize of any given element in the minibatch. See below for details.","outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"PaddingFIFOQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types.\nShapes of fixed rank but variable size are allowed by setting\nany shape dimension to -1. In this case, the inputs' shape may vary along\nthe given dimension, and DequeueMany will pad the given dimension with\nzeros up to the maximum shape of all elements in the given batch.\nIf the length of this attr is 0, different queue elements may have\ndifferent ranks and shapes, but only one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Variable-size shapes are allowed by setting the corresponding shape dimensions\nto 0 in the shape attr. In this case DequeueMany will pad up to the maximum\nsize of any given element in the minibatch. See below for details.","outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"ParallelConcat","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"description":"the final shape of the result; should be equal to the shapes of any input\nbut with the number of input values in the first dimension.","name":"shape","type":"shape"}],"description":"The input tensors are all required to have size 1 in the first dimension.\n\nFor example:\n\n```\n# 'x' is [[1, 4]]\n# 'y' is [[2, 5]]\n# 'z' is [[3, 6]]\nparallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim.\n```\n\nThe difference between concat and parallel_concat is that concat requires all\nof the inputs be computed before the operation will begin but doesn't require\nthat the input shapes be known during graph construction. Parallel concat\nwill copy pieces of the input into the output as they become available, in\nsome situations this can provide a performance benefit.","inputs":[{"description":"Tensors to be concatenated. All must have size 1 in the first dimension\nand same shape.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The concatenated tensor.","name":"output","typeAttr":"T"}],"summary":"Concatenates a list of `N` tensors along the first dimension."}},{"name":"ParallelDynamicStitch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Builds a merged tensor such that\n\n```python\n merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]\n```\n\nFor example, if each `indices[m]` is scalar or vector, we have\n\n```python\n # Scalar indices:\n merged[indices[m], ...] = data[m][...]\n\n # Vector indices:\n merged[indices[m][i], ...] = data[m][i, ...]\n```\n\nEach `data[i].shape` must start with the corresponding `indices[i].shape`,\nand the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we\nmust have `data[i].shape = indices[i].shape + constant`. In terms of this\n`constant`, the output shape is\n\n merged.shape = [max(indices)] + constant\n\nValues may be merged in parallel, so if an index appears in both `indices[m][i]`\nand `indices[n][j]`, the result may be invalid. This differs from the normal\nDynamicStitch operator that defines the behavior in that case.\n\nFor example:\n\n```python\n indices[0] = 6\n indices[1] = [4, 1]\n indices[2] = [[5, 2], [0, 3]]\n data[0] = [61, 62]\n data[1] = [[41, 42], [11, 12]]\n data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]\n merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],\n [51, 52], [61, 62]]\n```\n\nThis method can be used to merge partitions created by `dynamic_partition`\nas illustrated on the following example:\n\n```python\n # Apply function (increments x_i) on elements for which a certain condition\n # apply (x_i != -1 in this example).\n x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4])\n condition_mask=tf.not_equal(x,tf.constant(-1.))\n partitioned_data = tf.dynamic_partition(\n x, tf.cast(condition_mask, tf.int32) , 2)\n partitioned_data[1] = partitioned_data[1] + 1.0\n condition_indices = tf.dynamic_partition(\n tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)\n x = tf.dynamic_stitch(condition_indices, partitioned_data)\n # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain\n # unchanged.\n```\n\n
\n\n
","inputs":[{"name":"indices","numberAttr":"N","type":3},{"name":"data","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"merged","typeAttr":"T"}],"summary":"Interleave the values from the `data` tensors into a single tensor."}},{"name":"ParallelInterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! If the `sloppy` parameter is set to `True`, the operation of this\ndataset will not be deterministic!\n\nThis dataset has been superseded by `ParallelInterleaveDatasetV2`. New code\nshould use `ParallelInterleaveDatasetV2`.\n\nThe Python API `tf.data.experimental.parallel_interleave` creates instances of\nthis op. `tf.data.experimental.parallel_interleave` is a deprecated API.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDataset` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"If `True`, return elements as they become available, even if that means returning\nthese elements in a non-deterministic order. Sloppy operation may result in better\nperformance in the presence of stragglers, but the dataset will still block if\nall of its open streams are blocked.\nIf `False`, always return elements in a deterministic order.","name":"sloppy","type":10},{"description":"The number of elements each iterator being interleaved should buffer (similar\nto the `.prefetch()` transformation for each interleaved iterator).","name":"buffer_output_elements","type":9},{"description":"Determines the number of iterators to prefetch, allowing buffers to warm up and\ndata to be pre-fetched without blocking the main thread.","name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV2","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`,\nwhich can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV3","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the interleave is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can either set the `deterministic`\nattribute to \"false\", or leave it as \"default\" and set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`.\nThis can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV4","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the interleave is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can either set the `deterministic`\nattribute to \"false\", or leave it as \"default\" and set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`.\nThis can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"The number of elements each iterator being interleaved should buffer (similar\nto the `.prefetch()` transformation for each interleaved iterator).","name":"buffer_output_elements","type":9},{"description":"Determines the number of iterators to prefetch, allowing buffers to warm up and\ndata to be pre-fetched without blocking the main thread.","name":"prefetch_input_elements","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelMapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"sloppy","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Unlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `num_parallel_calls` copies of `f` in parallel.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"description":"The number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"num_parallel_calls","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelMapDatasetV2","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":"default","name":"deterministic","type":"string"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Unlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `num_parallel_calls` copies of `f` in parallel.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"description":"The number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParameterizedTruncatedNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"scalar which applies to the entire output, or a vector of length shape[0] which\nstores the parameters for each batch.","inputs":[{"description":"The shape of the output tensor. Batches are indexed by the 0th dimension.","name":"shape","typeAttr":"T"},{"description":"The mean parameter of each batch.","name":"means","typeAttr":"dtype"},{"description":"The standard deviation parameter of each batch. Must be greater than 0.","name":"stdevs","typeAttr":"dtype"},{"description":"The minimum cutoff. May be -infinity.","name":"minvals","typeAttr":"dtype"},{"description":"The maximum cutoff. May be +infinity, and must be more than the minval\nfor each batch.","name":"maxvals","typeAttr":"dtype"}],"outputs":[{"description":"A matrix of shape num_batches x samples_per_batch, filled with random\ntruncated normal values using the parameters for each row.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution. The parameters may each be a"}},{"name":"ParseExample","schema":{"attributes":[{"minimum":0,"name":"Nsparse","type":"int64"},{"minimum":0,"name":"Ndense","type":"int64"},{"description":"A list of Nsparse types; the data types of data in each Feature\ngiven in sparse_keys.\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"A list of Ndense shapes; the shapes of data in each Feature\ngiven in dense_keys.\nThe number of elements in the Feature corresponding to dense_key[j]\nmust always equal dense_shapes[j].NumEntries().\nIf dense_shapes[j] == (D0, D1, ..., DN) then the shape of output\nTensor dense_values[j] will be (|serialized|, D0, D1, ..., DN):\nThe dense outputs are just the inputs row-stacked by batch.\nThis works for dense_shapes[j] = (-1, D1, ..., DN). In this case\nthe shape of the output Tensor dense_values[j] will be\n(|serialized|, M, D1, .., DN), where M is the maximum number of blocks\nof elements of length D1 * .... * DN, across all minibatch entries\nin the input. Any minibatch entry with less than M blocks of elements of\nlength D1 * ... * DN will be padded with the corresponding default_value\nscalar element along the second dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing a batch of binary serialized Example protos.","name":"serialized","type":7},{"description":"A vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) names for the\ncorresponding serialized protos. These are purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no names are available.\nIf non-empty, this vector must be the same length as \"serialized\".","name":"names","type":7},{"description":"A list of Nsparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with sparse values.","name":"sparse_keys","numberAttr":"Nsparse","type":7},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples' features associated with dense values.","name":"dense_keys","numberAttr":"Ndense","type":7},{"description":"A list of Ndense Tensors (some may be empty).\ndense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"Nsparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"Nsparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"}],"summary":"Transforms a vector of brain.Example protos (as strings) into typed tensors."}},{"name":"ParseExampleDataset","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"},{"default":[],"minimum":0,"name":"ragged_keys","type":"string[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ParseExampleDatasetV2","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the dataset is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"default":[],"minimum":0,"name":"ragged_keys","type":"string[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ParseExampleV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"The number of sparse keys.","minimum":0,"name":"num_sparse","type":"int64"},{"description":"A list of `num_sparse` types; the data types of data in each Feature\ngiven in sparse_keys.\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of `num_ragged` types; the data types of data in each Feature\ngiven in ragged_keys (where `num_ragged = sparse_keys.size()`).\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"description":"A list of `num_ragged` types; the data types of row_splits in each Feature\ngiven in ragged_keys (where `num_ragged = sparse_keys.size()`).\nMay be DT_INT32 or DT_INT64. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"},{"description":"A list of `num_dense` shapes; the shapes of data in each Feature\ngiven in dense_keys (where `num_dense = dense_keys.size()`).\nThe number of elements in the Feature corresponding to dense_key[j]\nmust always equal dense_shapes[j].NumEntries().\nIf dense_shapes[j] == (D0, D1, ..., DN) then the shape of output\nTensor dense_values[j] will be (|serialized|, D0, D1, ..., DN):\nThe dense outputs are just the inputs row-stacked by batch.\nThis works for dense_shapes[j] = (-1, D1, ..., DN). In this case\nthe shape of the output Tensor dense_values[j] will be\n(|serialized|, M, D1, .., DN), where M is the maximum number of blocks\nof elements of length D1 * .... * DN, across all minibatch entries\nin the input. Any minibatch entry with less than M blocks of elements of\nlength D1 * ... * DN will be padded with the corresponding default_value\nscalar element along the second dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar or vector containing binary serialized Example protos.","name":"serialized","type":7},{"description":"A tensor containing the names of the serialized protos.\nCorresponds 1:1 with the `serialized` tensor.\nMay contain, for example, table key (descriptive) names for the\ncorresponding serialized protos. These are purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no names are available.\nIf non-empty, this tensor must have the same shape as \"serialized\".","name":"names","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with sparse values.","name":"sparse_keys","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with dense values.","name":"dense_keys","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with ragged values.","name":"ragged_keys","type":7},{"description":"A list of Tensors (some may be empty). Corresponds 1:1 with `dense_keys`.\ndense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"num_sparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"num_sparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"},{"name":"ragged_values","typeListAttr":"ragged_value_types"},{"name":"ragged_row_splits","typeListAttr":"ragged_split_types"}],"summary":"Transforms a vector of tf.Example protos (as strings) into typed tensors."}},{"name":"ParseSequenceExample","schema":{"attributes":[{"description":"A vector listing the\nFeatureList keys which may be missing from the SequenceExamples. If the\nassociated FeatureList is missing, it is treated as empty. By default,\nany FeatureList not listed in this vector must exist in the SequenceExamples.","minimum":0,"name":"feature_list_dense_missing_assumed_empty","type":"string[]"},{"description":"A list of Ncontext_sparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with context_sparse\nvalues.","minimum":0,"name":"context_sparse_keys","type":"string[]"},{"description":"A list of Ncontext_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' context features associated with\ndense values.","minimum":0,"name":"context_dense_keys","type":"string[]"},{"description":"A list of Nfeature_list_sparse string Tensors\n(scalars). The keys expected in the FeatureLists associated with sparse\nvalues.","minimum":0,"name":"feature_list_sparse_keys","type":"string[]"},{"description":"A list of Nfeature_list_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","minimum":0,"name":"feature_list_dense_keys","type":"string[]"},{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Ncontext_dense","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing binary serialized SequenceExample protos.","name":"serialized","type":7},{"description":"A vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no name is available.","name":"debug_name","type":7},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"},{"name":"feature_list_dense_lengths","numberAttr":"Nfeature_list_dense","type":9}],"summary":"Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors."}},{"name":"ParseSequenceExampleV2","schema":{"attributes":[{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"RaggedTensor.value dtypes for the ragged context features. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_ragged_value_types","type":"type[]"},{"default":[],"description":"RaggedTensor.row_split dtypes for the ragged context features. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"context_ragged_split_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"RaggedTensor.value dtypes for the ragged FeatureList features. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_ragged_value_types","type":"type[]"},{"default":[],"description":"RaggedTensor.row_split dtypes for the ragged FeatureList features. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"feature_list_ragged_split_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar or vector containing binary serialized SequenceExample protos.","name":"serialized","type":7},{"description":"A scalar or vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no name is available.","name":"debug_name","type":7},{"description":"The keys expected in the Examples' features associated with context_sparse\nvalues.","name":"context_sparse_keys","type":7},{"description":"The keys expected in the SequenceExamples' context features associated with\ndense values.","name":"context_dense_keys","type":7},{"description":"The keys expected in the Examples' features associated with context_ragged\nvalues.","name":"context_ragged_keys","type":7},{"description":"The keys expected in the FeatureLists associated with sparse values.","name":"feature_list_sparse_keys","type":7},{"description":"The keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","name":"feature_list_dense_keys","type":7},{"description":"The keys expected in the FeatureLists associated with ragged values.","name":"feature_list_ragged_keys","type":7},{"description":"A vector corresponding 1:1 with feature_list_dense_keys, indicating which\nfeatures may be missing from the SequenceExamples. If the associated\nFeatureList is missing, it is treated as empty.","name":"feature_list_dense_missing_assumed_empty","type":10},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"context_ragged_values","typeListAttr":"context_ragged_value_types"},{"name":"context_ragged_row_splits","typeListAttr":"context_ragged_split_types"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"},{"name":"feature_list_dense_lengths","numberAttr":"Nfeature_list_dense","type":9},{"name":"feature_list_ragged_values","typeListAttr":"feature_list_ragged_value_types"},{"name":"feature_list_ragged_outer_splits","typeListAttr":"feature_list_ragged_split_types"},{"name":"feature_list_ragged_inner_splits","typeListAttr":"feature_list_ragged_split_types"}],"summary":"Transforms a vector of tf.io.SequenceExample protos (as strings) into\ntyped tensors."}},{"name":"ParseSingleExample","schema":{"attributes":[{"description":"The number of sparse features to be parsed from the example. This\nmust match the lengths of `sparse_keys` and `sparse_types`.","minimum":0,"name":"num_sparse","type":"int64"},{"description":"A list of `num_sparse` strings.\nThe keys expected in the Examples' features associated with sparse values.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"The keys expected in the Examples' features associated with dense\nvalues.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `num_sparse` types; the data types of data in each\nFeature given in sparse_keys.\nCurrently the ParseSingleExample op supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"The data types of data in each Feature given in dense_keys.\nThe length of this list must match the length of `dense_keys`.\nCurrently the ParseSingleExample op supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"The shapes of data in each Feature given in dense_keys.\nThe length of this list must match the length of `dense_keys`. The\nnumber of elements in the Feature corresponding to dense_key[j] must\nalways equal dense_shapes[j].NumEntries(). If dense_shapes[j] ==\n(D0, D1, ..., DN) then the shape of output Tensor dense_values[j]\nwill be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1,\n..., DN), the shape of the output Tensor dense_values[j] will be (M,\nD1, .., DN), where M is the number of blocks of elements of length\nD1 * .... * DN, in the input.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing a batch of binary serialized Example protos.","name":"serialized","type":7},{"description":"A list of Tensors (some may be empty), whose length matches\nthe length of `dense_keys`. dense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"num_sparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"num_sparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"}],"summary":"Transforms a tf.Example proto (as a string) into typed tensors."}},{"name":"ParseSingleSequenceExample","schema":{"attributes":[{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Ncontext_dense","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar containing a binary serialized SequenceExample proto.","name":"serialized","type":7},{"description":"A vector listing the\nFeatureList keys which may be missing from the SequenceExample. If the\nassociated FeatureList is missing, it is treated as empty. By default,\nany FeatureList not listed in this vector must exist in the SequenceExample.","name":"feature_list_dense_missing_assumed_empty","type":7},{"description":"A list of Ncontext_sparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with context_sparse\nvalues.","name":"context_sparse_keys","numberAttr":"Ncontext_sparse","type":7},{"description":"A list of Ncontext_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' context features associated with\ndense values.","name":"context_dense_keys","numberAttr":"Ncontext_dense","type":7},{"description":"A list of Nfeature_list_sparse string Tensors\n(scalars). The keys expected in the FeatureLists associated with sparse\nvalues.","name":"feature_list_sparse_keys","numberAttr":"Nfeature_list_sparse","type":7},{"description":"A list of Nfeature_list_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","name":"feature_list_dense_keys","numberAttr":"Nfeature_list_dense","type":7},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"},{"description":"A scalar containing the name of the serialized proto.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty scalar if no name is available.","name":"debug_name","type":7}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"}],"summary":"Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors."}},{"name":"ParseTensor","schema":{"attributes":[{"description":"The type of the serialized tensor. The provided type must match the\ntype of the serialized tensor and no implicit conversion will take place.","name":"out_type","type":"type"}],"inputs":[{"description":"A scalar string containing a serialized TensorProto proto.","name":"serialized","type":7}],"outputs":[{"description":"A Tensor of type `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Transforms a serialized tensorflow.TensorProto proto into a Tensor."}},{"name":"PartitionedCall","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'args', a list of tensors, and returns 'output',\n another list of tensors. Input and output types are specified by 'Tin'\n and 'Tout'. The function body of f will be placed and partitioned across\n devices, setting this op apart from the regular Call op.","name":"f","type":"function"},{"default":"","name":"config","type":"string"},{"default":"","name":"config_proto","type":"string"},{"default":"","name":"executor_type","type":"string"}],"inputs":[{"description":"A list of input tensors.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"returns `f(inputs)`, where `f`'s body is placed and partitioned."}},{"name":"Placeholder","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"(Optional) The shape of the tensor. If the shape has 0 dimensions, the\nshape is unconstrained.","name":"shape","type":"shape"}],"description":"N.B. This operation will fail with an error if it is executed. It is\nintended as a way to represent a value that will always be fed, and to\nprovide attrs that enable the fed value to be checked at runtime.","outputs":[{"description":"A placeholder tensor that must be replaced using the feed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"PlaceholderV2","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor. The shape can be any partially-specified\nshape. To be unconstrained, pass in a shape with unknown rank.","name":"shape","type":"shape"}],"description":"N.B. This operation will fail with an error if it is executed. It is\nintended as a way to represent a value that will always be fed, and to\nprovide attrs that enable the fed value to be checked at runtime.","outputs":[{"description":"A placeholder tensor that must be replaced using the feed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"PlaceholderWithDefault","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The (possibly partial) shape of the tensor.","name":"shape","type":"shape"}],"inputs":[{"description":"The default value to produce when `output` is not fed.","name":"input","typeAttr":"dtype"}],"outputs":[{"description":"A placeholder tensor that defaults to `input` if it is not fed.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op that passes through `input` when its output is not fed."}},{"name":"Polygamma","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The polygamma function is defined as:\n\n\n\\\\(\\psi^{(a)}(x) = \\frac{d^a}{dx^a} \\psi(x)\\\\)\n\nwhere \\\\(\\psi(x)\\\\) is the digamma function.\nThe polygamma function is defined only for non-negative integer orders \\\\a\\\\.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the polygamma function \\\\(\\psi^{(n)}(x)\\\\)."}},{"name":"PopulationCount","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"For each entry in `x`, calculates the number of `1` (on) bits in the binary\nrepresentation of that entry.\n\n**NOTE**: It is more efficient to first `tf.bitcast` your tensors into\n`int32` or `int64` and perform the bitcount on the result, than to feed in\n8- or 16-bit inputs and then aggregate the resulting counts.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":4}],"summary":"Computes element-wise population count (a.k.a. popcount, bitsum, bitcount)."}},{"name":"Pow","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float16`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Given a tensor `x` and a tensor `y`, this operation computes \\\\(x^y\\\\) for\ncorresponding elements in `x` and `y`. For example:\n\n```\n# tensor 'x' is [[2, 2]], [3, 3]]\n# tensor 'y' is [[8, 16], [2, 3]]\ntf.pow(x, y) ==> [[256, 65536], [9, 27]]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the power of one value to another."}},{"name":"PrefetchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":0,"name":"slack_period","type":"int64"},{"default":true,"name":"legacy_autotune","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"description":"The maximum number of elements to buffer in an iterator over\nthis dataset.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that asynchronously prefetches elements from `input_dataset`."}},{"name":"Prelinearize","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence. If a layout\nattribute is passed but its values are all -1 the layout will be computed by\nthe infeed operation.","name":"layout","type":"int64[]"}],"inputs":[{"description":"A tensor that will be linearized.","name":"input","typeAttr":"dtype"}],"outputs":[{"name":"output","type":21}],"summary":"An op which linearizes one Tensor value to an opaque variant tensor."}},{"name":"PrelinearizeTuple","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `inputs`.","name":"shapes","type":"shape[]"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence for all the\ntuple shapes in the order the shapes appear in the \"shapes\" input. The layout\nelements for a sub-shape can be set to -1 in which case the corresponding layout\nwill be computed by the infeed operation.","name":"layouts","type":"int64[]"}],"inputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"inputs","typeListAttr":"dtypes"}],"outputs":[{"name":"output","type":21}],"summary":"An op which linearizes multiple Tensor values to an opaque variant tensor."}},{"name":"PreventGradient","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"Will be printed in the error when anyone tries to differentiate\nthis operation.","name":"message","type":"string"}],"description":"When executed in a graph, this op outputs its input tensor as-is.\n\nWhen building ops to compute gradients, the TensorFlow gradient system\nwill return an error when trying to lookup the gradient of this op,\nbecause no gradient must ever be registered for this function. This\nop exists to prevent subtle bugs from silently returning unimplemented\ngradients in some corner cases.","inputs":[{"description":"any tensor.","name":"input","typeAttr":"T"}],"outputs":[{"description":"the same input tensor.","name":"output","typeAttr":"T"}],"summary":"An identity op that triggers an error if a gradient is requested."}},{"name":"Print","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":0,"name":"U","type":"type[]"},{"default":"","description":"A string, prefix of the error message.","name":"message","type":"string"},{"default":-1,"description":"Only log `first_n` number of times. -1 disables logging.","name":"first_n","type":"int64"},{"default":3,"description":"Only print this many entries of each tensor.","name":"summarize","type":"int64"}],"description":"Passes `input` through to `output` and prints `data` when evaluating.","inputs":[{"description":"The tensor passed to `output`","name":"input","typeAttr":"T"},{"description":"A list of tensors to print out when op is evaluated.","name":"data","typeListAttr":"U"}],"outputs":[{"description":"= The unmodified `input` tensor","name":"output","typeAttr":"T"}],"summary":"Prints a list of tensors."}},{"name":"PrintV2","schema":{"attributes":[{"default":"stderr","description":"A string specifying the output stream or logging level to print to.","name":"output_stream","type":"string"},{"default":"\n","name":"end","type":"string"}],"description":"Prints a string scalar to the desired output_stream.","inputs":[{"description":"The string scalar to print.","name":"input","type":7}],"summary":"Prints a string scalar."}},{"name":"PriorityQueue","schema":{"attributes":[{"default":[],"description":"The type of each component in a value.","minimum":0,"name":"component_types","type":"type[]"},{"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Note that the PriorityQueue requires the first component of any element\nto be a scalar int64, in addition to the other elements declared by\ncomponent_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue\nand DequeueMany) on a PriorityQueue will all require (resp. output) one extra\nentry in their input (resp. output) lists.","outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements sorted by the first component value."}},{"name":"PriorityQueueV2","schema":{"attributes":[{"default":[],"description":"The type of each component in a value.","minimum":0,"name":"component_types","type":"type[]"},{"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Note that the PriorityQueue requires the first component of any element\nto be a scalar int64, in addition to the other elements declared by\ncomponent_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue\nand DequeueMany) on a PriorityQueue will all require (resp. output) one extra\nentry in their input (resp. output) lists.","outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements sorted by the first component value."}},{"name":"PrivateThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the number of threads to use for the private threadpool.","name":"num_threads","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"Prod","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the product of elements across dimensions of a tensor."}},{"name":"PyFunc","schema":{"attributes":[{"description":"A token representing a registered python function in this address space.","name":"token","type":"string"},{"description":"Data types of the inputs to the op.","minimum":0,"name":"Tin","type":"type[]"},{"description":"Data types of the outputs from the op.\nThe length of the list specifies the number of outputs.","minimum":0,"name":"Tout","type":"type[]"}],"description":"This operation is considered stateful. For a stateless version, see\nPyFuncStateless.","inputs":[{"description":"List of Tensors that will provide input to the Op.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"The outputs from the Op.","name":"output","typeListAttr":"Tout"}],"summary":"Invokes a python function to compute func(input)->output."}},{"name":"PyFuncStateless","schema":{"attributes":[{"name":"token","type":"string"},{"minimum":0,"name":"Tin","type":"type[]"},{"minimum":0,"name":"Tout","type":"type[]"}],"inputs":[{"name":"input","typeListAttr":"Tin"}],"outputs":[{"name":"output","typeListAttr":"Tout"}],"summary":"A stateless version of PyFunc."}},{"name":"Qr","schema":{"attributes":[{"default":false,"description":"If true, compute full-sized `q` and `r`. If false\n(the default), compute only the leading `P` columns of `q`.","name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the QR decomposition of each inner matrix in `tensor` such that\n`tensor[..., :, :] = q[..., :, :] * r[..., :,:])`\n\n```python\n# a is a tensor.\n# q is a tensor of orthonormal matrices.\n# r is a tensor of upper triangular matrices.\nq, r = qr(a)\nq_full, r_full = qr(a, full_matrices=True)\n```","inputs":[{"description":"A tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Orthonormal basis for range of `a`. If `full_matrices` is `False` then\nshape is `[..., M, P]`; if `full_matrices` is `True` then shape is\n`[..., M, M]`.","name":"q","typeAttr":"T"},{"description":"Triangular factor. If `full_matrices` is `False` then shape is\n`[..., P, N]`. If `full_matrices` is `True` then shape is `[..., M, N]`.","name":"r","typeAttr":"T"}],"summary":"Computes the QR decompositions of one or more matrices."}},{"name":"QuantizeAndDequantize","schema":{"attributes":[{"default":true,"name":"signed_input","type":"boolean"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"range_given","type":"boolean"},{"default":0,"name":"input_min","type":"float32"},{"default":0,"name":"input_max","type":"float32"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Use QuantizeAndDequantizeV2 instead."}},{"name":"QuantizeAndDequantizeV2","schema":{"attributes":[{"default":true,"description":"Whether the quantization is signed or unsigned. (actually this parameter should\nhave been called `signed_output`)","name":"signed_input","type":"boolean"},{"default":8,"description":"The bitwidth of the quantization.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether the range is given or should be determined from the `input` tensor.","name":"range_given","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"HALF_TO_EVEN","description":"The 'round_mode' attribute controls which rounding tie-breaking algorithm is\nused when rounding float values to their quantized equivalents. The following\nrounding modes are currently supported:\n\n* HALF_TO_EVEN: this is the default round_mode.\n* HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5\n rounds up to -7.\n Must be one of the following: `HALF_TO_EVEN`, `HALF_UP`.","name":"round_mode","type":"string"},{"default":false,"description":"If True, then the absolute value of the quantized minimum value is the same as\nthe quantized maximum value, instead of 1 greater.\ni.e. for 8 bit quantization, the minimum value is -127 instead of -128.","name":"narrow_range","type":"boolean"},{"default":-1,"description":"If specified, this axis is treated as a channel or slice axis, and a separate\nquantization range is used for each channel or slice along this axis.","name":"axis","type":"int64"}],"description":"This op simulates the precision loss from the quantized forward pass by:\n\n1. Quantizing the tensor to fixed point numbers, which should match the target\n quantization method when it is used in inference.\n2. Dequantizing it back to floating point numbers for the following ops, most\n likely matmul.\n\nThere are different ways to quantize. This version uses only scaling, so 0.0\nmaps to 0.\n\nFrom the specified 'num_bits' in the quantized output type, it determines\nminimum and maximum representable quantized values.\n\ne.g.\n\n* [-128, 127] for signed, num_bits = 8, or\n* [0, 255] for unsigned, num_bits = 8.\n\nIf range_given == False, the initial input_min, input_max will be determined\nautomatically as the minimum and maximum values in the input tensor, otherwise\nthe specified values of input_min, input_max are used.\n\nNote: If the input_min, input_max are specified, they do not need to equal the\nactual minimum and maximum values in the tensor. e.g. in some cases it may be\nbeneficial to specify these values such that the low probability extremes of the\ninput distribution are clipped.\n\nThis op determines the maximum scale_factor that would map the initial\n[input_min, input_max] range to a range that lies within the representable\nquantized range.\n\nIt determines the scale from one of input_min and input_max, then updates the\nother one to maximize the representable range.\n\ne.g.\n\n* if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0,\n 5.0]: it would use a scale_factor of -128 / -10.0 = 12.8 In this case, it\n would update input_max to be 127 / 12.8 = 9.921875\n* if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0,\n 10.0]: it would use a scale_factor of 127 / 10.0 = 12.7 In this case, it\n would update input_min to be 128.0 / 12.7 = -10.07874\n* if the output is unsigned, input_min is forced to be 0, and only the\n specified input_max is used.\n\nAfter determining the scale_factor and updating the input range, it applies the\nfollowing to each value in the 'input' tensor.\n\noutput = round(clamp(value, input_min, input_max) * scale_factor) / scale_factor.\n\nThe above round function rounds the value based on the given round_mode.\n","inputs":[{"description":"Tensor to quantize and then dequantize.","name":"input","typeAttr":"T"},{"description":"If `range_given == True`, this specifies the minimum input value that needs to\nbe represented, otherwise it is determined from the min value of the `input`\ntensor.","name":"input_min","typeAttr":"T"},{"description":"If `range_given == True`, this specifies the maximum input value that needs to\nbe represented, otherwise it is determined from the max value of the `input`\ntensor.","name":"input_max","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Quantizes then dequantizes a tensor."}},{"name":"QuantizeAndDequantizeV3","schema":{"attributes":[{"default":true,"name":"signed_input","type":"boolean"},{"default":true,"name":"range_given","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"}],"description":"This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a\ntensor, so its value can change during training.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_min","typeAttr":"T"},{"name":"input_max","typeAttr":"T"},{"name":"num_bits","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Quantizes then dequantizes a tensor."}},{"name":"QuantizeDownAndShrinkRange","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the output. Should be a lower bit depth than Tinput. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"actual distribution of the values to maximize the usage of the lower bit depth\nand adjusting the output min and max ranges accordingly.\n\n[input_min, input_max] are scalar floats that specify the range for the float\ninterpretation of the 'input' data. For example, if input_min is -1.0f and\ninput_max is 1.0f, and we are dealing with quint16 quantized data, then a 0\nvalue in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f.\n\nThis operator tries to squeeze as much precision as possible into an output with\na lower bit depth by calculating the actual min and max values found in the\ndata. For example, maybe that quint16 input has no values lower than 16,384 and\nnone higher than 49,152. That means only half the range is actually needed, all\nthe float interpretations are between -0.5f and 0.5f, so if we want to compress\nthe data into a quint8 output, we can use that range rather than the theoretical\n-1.0f to 1.0f that is suggested by the input min and max.\n\nIn practice, this is most useful for taking output from operations like\nQuantizedMatMul that can produce higher bit-depth outputs than their inputs and\nmay have large potential output ranges, but in practice have a distribution of\ninput values that only uses a small fraction of the possible range. By feeding\nthat output into this operator, we can reduce it from 32 bits down to 8 with\nminimal loss of accuracy.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"output_max","type":1}],"summary":"Convert the quantized 'input' tensor into a lower-precision 'output', using the"}},{"name":"QuantizeV2","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":"MIN_COMBINED","description":"Must be one of the following: `MIN_COMBINED`, `MIN_FIRST`, `SCALED`.","name":"mode","type":"string"},{"default":"HALF_AWAY_FROM_ZERO","description":"Must be one of the following: `HALF_AWAY_FROM_ZERO`, `HALF_TO_EVEN`.","name":"round_mode","type":"string"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"},{"default":0.009999999776482582,"name":"ensure_minimum_range","type":"float32"}],"description":"[min_range, max_range] are scalar floats that specify the range for\nthe 'input' data. The 'mode' attribute controls exactly which calculations are\nused to convert the float values to their quantized equivalents. The\n'round_mode' attribute controls which rounding tie-breaking algorithm is used\nwhen rounding float values to their quantized equivalents.\n\nIn 'MIN_COMBINED' mode, each value of the tensor will undergo the following:\n\n```\nout[i] = (in[i] - min_range) * range(T) / (max_range - min_range)\nif T == qint8: out[i] -= (range(T) + 1) / 2.0\n```\n\nhere `range(T) = numeric_limits::max() - numeric_limits::min()`\n\n*MIN_COMBINED Mode Example*\n\nAssume the input is type float and has a possible range of [0.0, 6.0] and the\noutput type is quint8 ([0, 255]). The min_range and max_range values should be\nspecified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each\nvalue of the input by 255/6 and cast to quint8.\n\nIf the output type was qint8 ([-128, 127]), the operation will additionally\nsubtract each value by 128 prior to casting, so that the range of values aligns\nwith the range of qint8.\n\nIf the mode is 'MIN_FIRST', then this approach is used:\n\n```\nnum_discrete_values = 1 << (# of bits in T)\nrange_adjust = num_discrete_values / (num_discrete_values - 1)\nrange = (range_max - range_min) * range_adjust\nrange_scale = num_discrete_values / range\nquantized = round(input * range_scale) - round(range_min * range_scale) +\n numeric_limits::min()\nquantized = max(quantized, numeric_limits::min())\nquantized = min(quantized, numeric_limits::max())\n```\n\nThe biggest difference between this and MIN_COMBINED is that the minimum range\nis rounded first, before it's subtracted from the rounded value. With\nMIN_COMBINED, a small bias is introduced where repeated iterations of quantizing\nand dequantizing will introduce a larger and larger error.\n\n*SCALED mode Example*\n\n`SCALED` mode matches the quantization approach used in\n`QuantizeAndDequantize{V2|V3}`.\n\nIf the mode is `SCALED`, the quantization is performed by multiplying each\ninput value by a scaling_factor.\nThe scaling_factor is determined from `min_range` and `max_range` to be as large\nas possible such that the range from `min_range` to `max_range` is representable\nwithin values of type T.\n\n```c++\n\n const int min_T = std::numeric_limits::min();\n const int max_T = std::numeric_limits::max();\n const float max_float = std::numeric_limits::max();\n\n const float scale_factor_from_min_side =\n (min_T * min_range > 0) ? min_T / min_range : max_float;\n const float scale_factor_from_max_side =\n (max_T * max_range > 0) ? max_T / max_range : max_float;\n\n const float scale_factor = std::min(scale_factor_from_min_side,\n scale_factor_from_max_side);\n```\n\nWe next use the scale_factor to adjust min_range and max_range as follows:\n\n```c++\n min_range = min_T / scale_factor;\n max_range = max_T / scale_factor;\n```\n\n\ne.g. if T = qint8, and initially min_range = -10, and max_range = 9, we would\ncompare -128/-10.0 = 12.8 to 127/9.0 = 14.11, and set scaling_factor = 12.8\nIn this case, min_range would remain -10, but max_range would be adjusted to\n127 / 12.8 = 9.921875\n\nSo we will quantize input values in the range (-10, 9.921875) to (-128, 127).\n\nThe input tensor can now be quantized by clipping values to the range\n`min_range` to `max_range`, then multiplying by scale_factor as follows:\n\n```c++\nresult = round(min(max_range, max(min_range, input)) * scale_factor)\n```\n\nThe adjusted `min_range` and `max_range` are returned as outputs 2 and 3 of\nthis operation. These outputs should be used as the range for any further\ncalculations.\n\n\n*narrow_range (bool) attribute*\n\nIf true, we do not use the minimum quantized value.\ni.e. for int8 the quantized output, it would be restricted to the range\n-127..127 instead of the full -128..127 range.\nThis is provided for compatibility with certain inference backends.\n(Only applies to SCALED mode)\n\n\n*axis (int) attribute*\n\nAn optional `axis` attribute can specify a dimension index of the input tensor,\nsuch that quantization ranges will be calculated and applied separately for each\nslice of the tensor along that dimension. This is useful for per-channel\nquantization.\n\nIf axis is specified, min_range and max_range\n\nif `axis`=None, per-tensor quantization is performed as normal.\n\n\n*ensure_minimum_range (float) attribute*\n\nEnsures the minimum quantization range is at least this value.\nThe legacy default value for this is 0.01, but it is strongly suggested to\nset it to 0 for new uses.\n","inputs":[{"name":"input","type":1},{"description":"The minimum value of the quantization range. This value may be adjusted by the\nop depending on other parameters. The adjusted value is written to `output_min`.\nIf the `axis` attribute is specified, this must be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"min_range","type":1},{"description":"The maximum value of the quantization range. This value may be adjusted by the\nop depending on other parameters. The adjusted value is written to `output_max`.\nIf the `axis` attribute is specified, this must be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"max_range","type":1}],"outputs":[{"description":"The quantized data produced from the float input.","name":"output","typeAttr":"T"},{"description":"The final quantization range minimum, used to clip input values before scaling\nand rounding them to quantized values.\nIf the `axis` attribute is specified, this will be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"output_min","type":1},{"description":"The final quantization range maximum, used to clip input values before scaling\nand rounding them to quantized values.\nIf the `axis` attribute is specified, this will be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"output_max","type":1}],"summary":"Quantize the 'input' tensor of type float to 'output' tensor of type 'T'."}},{"name":"QuantizedAdd","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"}],"inputs":[{"name":"x","typeAttr":"T1"},{"name":"y","typeAttr":"T2"},{"description":"The float value that the lowest quantized `x` value represents.","name":"min_x","type":1},{"description":"The float value that the highest quantized `x` value represents.","name":"max_x","type":1},{"description":"The float value that the lowest quantized `y` value represents.","name":"min_y","type":1},{"description":"The float value that the highest quantized `y` value represents.","name":"max_y","type":1}],"outputs":[{"name":"z","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_z","type":1},{"description":"The float value that the highest quantized output value represents.\n\n*NOTE*: `QuantizedAdd` supports limited forms of broadcasting. More about\nbroadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","name":"max_z","type":1}],"summary":"Returns x + y element-wise, working on quantized buffers."}},{"name":"QuantizedAvgPool","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.\nThe length must be 4 to match the number of dimensions of the input.","name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. The length must be 4 to match the number of dimensions of the input.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input","typeAttr":"T"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Produces the average pool of the input tensor for quantized types."}},{"name":"QuantizedBatchNormWithGlobalNormalization","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"description":"This op is deprecated and will be removed in the future. Prefer\n`tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized input.","name":"t_min","type":1},{"description":"The value represented by the highest quantized input.","name":"t_max","type":1},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized mean.","name":"m_min","type":1},{"description":"The value represented by the highest quantized mean.","name":"m_max","type":1},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized variance.","name":"v_min","type":1},{"description":"The value represented by the highest quantized variance.","name":"v_max","type":1},{"description":"A 1D beta Tensor with size matching the last dimension of t.\nAn offset to be added to the normalized tensor.","name":"beta","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized offset.","name":"beta_min","type":1},{"description":"The value represented by the highest quantized offset.","name":"beta_max","type":1},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this tensor will be multiplied\nwith the normalized tensor.","name":"gamma","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized gamma.","name":"gamma_min","type":1},{"description":"The value represented by the highest quantized gamma.","name":"gamma_max","type":1}],"outputs":[{"name":"result","typeAttr":"out_type"},{"name":"result_min","type":1},{"name":"result_max","type":1}],"summary":"Quantized Batch normalization."}},{"name":"QuantizedBiasAdd","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"Broadcasts the values of bias on dimensions 0..N-2 of 'input'.","inputs":[{"name":"input","typeAttr":"T1"},{"description":"A 1D bias Tensor with size matching the last dimension of 'input'.","name":"bias","typeAttr":"T2"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the lowest quantized bias value represents.","name":"min_bias","type":1},{"description":"The float value that the highest quantized bias value represents.","name":"max_bias","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Adds Tensor 'bias' to Tensor 'input' for Quantized types."}},{"name":"QuantizedConcat","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"inputs":[{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [0, rank(values)).","name":"concat_dim","type":3},{"description":"The `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"The minimum scalar values for each of the input tensors.","name":"input_mins","numberAttr":"N","type":1},{"description":"The maximum scalar values for each of the input tensors.","name":"input_maxes","numberAttr":"N","type":1}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"},{"description":"The float value that the minimum quantized output value represents.","name":"output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"output_max","type":1}],"summary":"Concatenates quantized tensors along one dimension."}},{"name":"QuantizedConv2D","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\ntensor.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"description":"The inputs are quantized tensors where the lowest value represents the real\nnumber of the associated minimum, and the highest represents the maximum.\nThis means that you can only interpret the quantized output in the same way, by\ntaking the returned minimum and maximum values into account.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"filter's input_depth dimension must match input's depth dimensions.","name":"filter","typeAttr":"Tfilter"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the lowest quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the highest quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Computes a 2D convolution given quantized 4D input and filter tensors."}},{"name":"QuantizedConv2DAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":11},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DPerChannel","schema":{"attributes":[{"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The quantized type of filter tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The quantized type of output tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"list of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"list of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The minimum value of the input tensor","name":"min_input","type":1},{"description":"The maximum value of the input tensor.","name":"max_input","type":1},{"description":"The minimum value of the filter tensor.","name":"min_filter","type":1},{"description":"The maximum value of the filter tensor.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The minimum value of the final output tensor.","name":"min_output","type":1},{"description":"The maximum value of the final output tensor.","name":"max_output","type":1}],"summary":"Computes QuantizedConv2D per channel."}},{"name":"QuantizedConv2DWithBias","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":11},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSignedSumAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tsummand","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1},{"name":"summand","typeAttr":"Tsummand"},{"name":"min_summand","type":1},{"name":"max_summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSumAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSumAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tsummand","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1},{"name":"summand","typeAttr":"Tsummand"},{"name":"min_summand","type":1},{"name":"max_summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedDepthwiseConv2D","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D."}},{"name":"QuantizedDepthwiseConv2DWithBias","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","type":1},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias."}},{"name":"QuantizedDepthwiseConv2DWithBiasAndRelu","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","type":1},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias and Relu."}},{"name":"QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"The type of the bias. Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1},{"description":"The minimum float value of the output tensor.","name":"min_freezed_output","type":1},{"description":"The maximum float value of the output tensor.","name":"max_freezed_output","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias, Relu and Requantize."}},{"name":"QuantizedInstanceNorm","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":false,"description":"If True, `given_y_min` and `given_y_min`\nand `given_y_max` are used as the output range. Otherwise,\nthe implementation computes the output range.","name":"output_range_given","type":"boolean"},{"default":0,"description":"Output in `y_min` if `output_range_given` is True.","name":"given_y_min","type":"float32"},{"default":0,"description":"Output in `y_max` if `output_range_given` is True.","name":"given_y_max","type":"float32"},{"default":0.000009999999747378752,"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"default":0.0010000000474974513,"description":"Minimum value of `y_max - y_min`","name":"min_separation","type":"float32"}],"inputs":[{"description":"A 4D input Tensor.","name":"x","typeAttr":"T"},{"description":"The value represented by the lowest quantized input.","name":"x_min","type":1},{"description":"The value represented by the highest quantized input.","name":"x_max","type":1}],"outputs":[{"description":"A 4D Tensor.","name":"y","typeAttr":"T"},{"description":"The value represented by the lowest quantized output.","name":"y_min","type":1},{"description":"The value represented by the highest quantized output.","name":"y_max","type":1}],"summary":"Quantized Instance normalization."}},{"name":"QuantizedMatMul","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":{"type":"type","value":12},"description":"The type of output produced by activation function\nfollowing this operation. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tactivation","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of\n`a` (after being transposed if `transpose_a` is non-zero) must match the\nouter dimension of `b` (after being transposed if `transposed_b` is\nnon-zero).","inputs":[{"description":"Must be a two-dimensional tensor.","name":"a","typeAttr":"T1"},{"description":"Must be a two-dimensional tensor.","name":"b","typeAttr":"T2"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b`."}},{"name":"QuantizedMatMulWithBias","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Performs a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd."}},{"name":"QuantizedMatMulWithBiasAndDequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `float32`.","name":"Toutput","type":"type"},{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"inputs":[{"name":"a","typeAttr":"T1"},{"name":"b","typeAttr":"T2"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_a","type":1},{"name":"max_a","type":1},{"name":"min_b","type":1},{"name":"max_b","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"}]}},{"name":"QuantizedMatMulWithBiasAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`. Then do\nrelu activation to get non-negative result.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching with inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","type":1},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd and relu fusion."}},{"name":"QuantizedMatMulWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`. Then do\nrelu activation to get non-negative result. Then do requantize operation to get\nfinal uint8 result.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching with inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1},{"description":"The float value that the highest quantized output value after requantize.","name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd and relu and requantize fusion."}},{"name":"QuantizedMatMulWithBiasAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"inputs":[{"name":"a","typeAttr":"T1"},{"name":"b","typeAttr":"T2"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_a","type":1},{"name":"max_a","type":1},{"name":"min_b","type":1},{"name":"max_b","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"name":"min_out","type":1},{"name":"max_out","type":1}]}},{"name":"QuantizedMaxPool","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.\nThe length must be 4 to match the number of dimensions of the input.","name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. The length must be 4 to match the number of dimensions of the input.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"The 4D (batch x rows x cols x depth) Tensor to MaxReduce over.","name":"input","typeAttr":"T"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Produces the max pool of the input tensor for quantized types."}},{"name":"QuantizedMul","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"}],"inputs":[{"name":"x","typeAttr":"T1"},{"name":"y","typeAttr":"T2"},{"description":"The float value that the lowest quantized `x` value represents.","name":"min_x","type":1},{"description":"The float value that the highest quantized `x` value represents.","name":"max_x","type":1},{"description":"The float value that the lowest quantized `y` value represents.","name":"min_y","type":1},{"description":"The float value that the highest quantized `y` value represents.","name":"max_y","type":1}],"outputs":[{"name":"z","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_z","type":1},{"description":"The float value that the highest quantized output value represents.\n\n*NOTE*: `QuantizedMul` supports limited forms of broadcasting. More about\nbroadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","name":"max_z","type":1}],"summary":"Returns x * y element-wise, working on quantized buffers."}},{"name":"QuantizedRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear: `max(features, 0)`"}},{"name":"QuantizedRelu6","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)`"}},{"name":"QuantizedReluX","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"name":"max_value","type":1},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)`"}},{"name":"QuantizedReshape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"description":"```","inputs":[{"name":"tensor","typeAttr":"T"},{"description":"Defines the shape of the output tensor.","name":"shape","typeAttr":"Tshape"},{"description":"The minimum value of the input.","name":"input_min","type":1},{"description":"The maximum value of the input.","name":"input_max","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"This value is copied from input_min.","name":"output_min","type":1},{"description":"This value is copied from input_max.","name":"output_max","type":1}],"summary":"Reshapes a quantized tensor as per the Reshape op."}},{"name":"QuantizedResizeBilinear","schema":{"attributes":[{"description":"Must be one of the following: `quint8`, `qint32`, `float32`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images and output images must be quantized types.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","typeAttr":"T"},{"name":"out_min","type":1},{"name":"out_max","type":1}],"summary":"Resize quantized `images` to `size` using quantized bilinear interpolation."}},{"name":"QueueClose","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the given queue will be canceled.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more elements will be enqueued in the\ngiven queue. Subsequent Enqueue(Many) operations will fail.\nSubsequent Dequeue(Many) operations will continue to succeed if\nsufficient elements remain in the queue. Subsequent Dequeue(Many)\noperations that would block will fail immediately.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"summary":"Closes the given queue."}},{"name":"QueueCloseV2","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the given queue will be canceled.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more elements will be enqueued in the\ngiven queue. Subsequent Enqueue(Many) operations will fail.\nSubsequent Dequeue(Many) operations will continue to succeed if\nsufficient elements remain in the queue. Subsequent Dequeue(Many)\noperations that would block will fail immediately.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"summary":"Closes the given queue."}},{"name":"QueueDequeue","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation has k outputs, where k is the number of components\nin the tuples stored in the given queue, and output i is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until an element\nhas been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues a tuple of one or more tensors from the given queue."}},{"name":"QueueDequeueMany","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"If the queue is closed and there are fewer than `n` elements, then an\nOutOfRange error is returned.\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until `n` elements\nhave been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueManyV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"If the queue is closed and there are fewer than `n` elements, then an\nOutOfRange error is returned.\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until `n` elements\nhave been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueUpTo","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation is not supported by all queues. If a queue does not support\nDequeueUpTo, then an Unimplemented error is returned.\n\nIf the queue is closed and there are more than 0 but less than `n`\nelements remaining, then instead of returning an OutOfRange error like\nQueueDequeueMany, less than `n` elements are returned immediately. If\nthe queue is closed and there are 0 elements left in the queue, then\nan OutOfRange error is returned just like in QueueDequeueMany.\nOtherwise the behavior is identical to QueueDequeueMany:\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has k outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueUpToV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation is not supported by all queues. If a queue does not support\nDequeueUpTo, then an Unimplemented error is returned.\n\nIf the queue is closed and there are more than 0 but less than `n`\nelements remaining, then instead of returning an OutOfRange error like\nQueueDequeueMany, less than `n` elements are returned immediately. If\nthe queue is closed and there are 0 elements left in the queue, then\nan OutOfRange error is returned just like in QueueDequeueMany.\nOtherwise the behavior is identical to QueueDequeueMany:\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size n in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation has k outputs, where k is the number of components\nin the tuples stored in the given queue, and output i is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until an element\nhas been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues a tuple of one or more tensors from the given queue."}},{"name":"QueueEnqueue","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is full, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"The components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelement has been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"One or more tensors from which the enqueued tensors should be taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues a tuple of one or more tensors in the given queue."}},{"name":"QueueEnqueueMany","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is too full, this operation will block for up\nto timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation slices each component tensor along the 0th dimension to\nmake multiple queue elements. All of the tuple components must have the\nsame size in the 0th dimension.\n\nThe components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelements have been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"One or more tensors from which the enqueued tensors should\nbe taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues zero or more tuples of one or more tensors in the given queue."}},{"name":"QueueEnqueueManyV2","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is too full, this operation will block for up\nto timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation slices each component tensor along the 0th dimension to\nmake multiple queue elements. All of the tuple components must have the\nsame size in the 0th dimension.\n\nThe components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelements have been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"One or more tensors from which the enqueued tensors should\nbe taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues zero or more tuples of one or more tensors in the given queue."}},{"name":"QueueEnqueueV2","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is full, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"The components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelement has been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"One or more tensors from which the enqueued tensors should be taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues a tuple of one or more tensors in the given queue."}},{"name":"QueueIsClosed","schema":{"description":"This operation returns true if the queue is closed and false if the queue\nis open.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"name":"is_closed","type":10}],"summary":"Returns true if queue is closed."}},{"name":"QueueIsClosedV2","schema":{"description":"This operation returns true if the queue is closed and false if the queue\nis open.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"name":"is_closed","type":10}],"summary":"Returns true if queue is closed."}},{"name":"QueueSize","schema":{"inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of elements in the given queue.","name":"size","type":3}],"summary":"Computes the number of elements in the given queue."}},{"name":"QueueSizeV2","schema":{"inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"description":"The number of elements in the given queue.","name":"size","type":3}],"summary":"Computes the number of elements in the given queue."}},{"name":"RFFT","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 1-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most dimension of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the\n`fft_length / 2 + 1` unique components of the FFT: the zero-frequency term,\nfollowed by the `fft_length / 2` positive-frequency terms.\n\nAlong the axis `RFFT` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [1]. The FFT length.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length / 2 + 1` unique\n frequency components of its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Real-valued fast Fourier transform."}},{"name":"RFFT2D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 2-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 2 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the\n`fft_length / 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length / 2`\npositive-frequency terms.\n\nAlong each axis `RFFT2D` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [2]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform. The\n inner-most dimension contains `fft_length / 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"2D real-valued fast Fourier transform."}},{"name":"RFFT3D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 3-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 3 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the\n`fft_length / 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length / 2`\npositive-frequency terms.\n\nAlong each axis `RFFT3D` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [3]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the their 3D Fourier transform. The\n inner-most dimension contains `fft_length / 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"3D real-valued fast Fourier transform."}},{"name":"RGBToHSV","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a tensor of the same shape as the `images` tensor, containing the HSV\nvalue of the pixels. The output is only well defined if the value in `images`\nare in `[0,1]`.\n\n`output[..., 0]` contains hue, `output[..., 1]` contains saturation, and\n`output[..., 2]` contains value. All HSV values are in `[0,1]`. A hue of 0\ncorresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue.\n\nUsage Example:\n\n>>> blue_image = tf.stack([\n... tf.zeros([5,5]),\n... tf.zeros([5,5]),\n... tf.ones([5,5])],\n... axis=-1)\n>>> blue_hsv_image = tf.image.rgb_to_hsv(blue_image)\n>>> blue_hsv_image[0,0].numpy()\narray([0.6666667, 1. , 1. ], dtype=float32)\n","inputs":[{"description":"1-D or higher rank. RGB data to convert. Last dimension must be size 3.","name":"images","typeAttr":"T"}],"outputs":[{"description":"`images` converted to HSV.","name":"output","typeAttr":"T"}],"summary":"Converts one or more images from RGB to HSV."}},{"name":"RaggedBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"1D int64 `Tensor`.","name":"splits","type":9},{"description":"2D int `Tensor`.","name":"values","typeAttr":"Tidx"},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `input`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"RaggedCountSparseOutput","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing the row splits of the ragged tensor to count.","name":"splits","type":9},{"description":"Tensor containing values of the sparse tensor to count.","name":"values","typeAttr":"T"},{"description":"A Tensor of the same shape as indices containing per-index weight values.\nMay also be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.\n END\n }\n attr {\n name: \"T\"\n description: <\n```\n\nThe input tensors `starts`, `limits`, and `deltas` may be scalars or vectors.\nThe vector inputs must all have the same size. Scalar inputs are broadcast\nto match the size of the vector inputs.","inputs":[{"description":"The starts of each range.","name":"starts","typeAttr":"T"},{"description":"The limits of each range.","name":"limits","typeAttr":"T"},{"description":"The deltas of each range.","name":"deltas","typeAttr":"T"}],"outputs":[{"description":"The `row_splits` for the returned `RaggedTensor`.","name":"rt_nested_splits","typeAttr":"Tsplits"},{"description":"The `flat_values` for the returned `RaggedTensor`.","name":"rt_dense_values","typeAttr":"T"}],"summary":"Returns a `RaggedTensor` containing the specified sequences of numbers."}},{"name":"RaggedTensorFromVariant","schema":{"attributes":[{"description":"The ragged rank of each encoded `RaggedTensor` component in the input. If set to\n-1, this is inferred as `output_ragged_rank` - `rank(encoded_ragged)`","minimum":-1,"name":"input_ragged_rank","type":"int64"},{"description":"The expected ragged rank of the output `RaggedTensor`. The following must hold:\n`output_ragged_rank = rank(encoded_ragged) + input_ragged_rank`.","minimum":0,"name":"output_ragged_rank","type":"int64"},{"name":"Tvalues","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"Decodes the given `variant` Tensor and returns a `RaggedTensor`. The input\ncould be a scalar, meaning it encodes a single `RaggedTensor` with ragged_rank\n`output_ragged_rank`. It could also have an arbitrary rank, in which case each\nelement is decoded into a `RaggedTensor` with ragged_rank `input_ragged_rank`\nand these are then stacked according to the input shape to output a single\n`RaggedTensor` with ragged_rank `output_ragged_rank`. Each `variant` element in\nthe input Tensor is decoded by retrieving from the element a 1-D `variant`\nTensor with `input_ragged_rank + 1` Tensors, corresponding to the splits and\nvalues of the decoded `RaggedTensor`. If `input_ragged_rank` is -1, then it is\ninferred as `output_ragged_rank` - `rank(encoded_ragged)`. See\n`RaggedTensorToVariant` for the corresponding encoding logic.\n","inputs":[{"description":"A `variant` Tensor containing encoded `RaggedTensor`s.","name":"encoded_ragged","type":21}],"outputs":[{"description":"A list of one or more Tensors representing the splits of the output\n`RaggedTensor`.","name":"output_nested_splits","numberAttr":"output_ragged_rank","typeAttr":"Tsplits"},{"description":"A Tensor representing the values of the output `RaggedTensor`.","name":"output_dense_values","typeAttr":"Tvalues"}],"summary":"Decodes a `variant` Tensor into a `RaggedTensor`."}},{"name":"RaggedTensorToSparse","schema":{"attributes":[{"description":"The ragged rank of the input RaggedTensor. `rt_nested_splits` should contain\nthis number of ragged-splits tensors. This value should equal\n`input.ragged_rank`.","minimum":1,"name":"RAGGED_RANK","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"input=ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits)\noutput=SparseTensor(indices=sparse_indices, values=sparse_values,\n dense_shape=sparse_dense_shape)","inputs":[{"description":"The `row_splits` for the `RaggedTensor`.","name":"rt_nested_splits","numberAttr":"RAGGED_RANK","typeAttr":"Tsplits"},{"description":"The `flat_values` for the `RaggedTensor`.","name":"rt_dense_values","typeAttr":"T"}],"outputs":[{"description":"The indices for the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"The values of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"`sparse_dense_shape` is a tight bounding box of the input `RaggedTensor`.","name":"sparse_dense_shape","type":9}],"summary":"Converts a `RaggedTensor` into a `SparseTensor` with the same values."}},{"name":"RaggedTensorToTensor","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int64`, `int32`.","name":"Tindex","type":"type"},{"description":"Must be one of the following: `int64`, `int32`.","name":"Tshape","type":"type"},{"minimum":1,"name":"num_row_partition_tensors","type":"int64"},{"description":"The types of the row partition tensors. At present, these can be:\n* \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n* \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n* \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceeded by \"FIRST_DIM_SIZE\".\nThe tensors are in the order of the dimensions.","name":"row_partition_types","type":"string[]"}],"description":"The `ragged_to_dense` op creates a dense tensor from a list of row partition\ntensors, a value vector, and default values. If the shape is unspecified, the\nminimal shape required to contain all the elements in the ragged tensor (the\nnatural shape) will be used. If some dimensions are left unspecified, then the\nsize of the natural shape is used in that dimension.\n\nThe default_value will be broadcast to the output shape. After that, the values\nfrom the ragged tensor overwrite the default values. Note that the default_value\nmust have less dimensions than the value.\n\nThe row partition tensors are in the order of the dimensions.\nAt present, the types can be:\n* \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n* \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n* \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceded by \"FIRST_DIM_SIZE\".","inputs":[{"description":"The desired shape of the the output tensor. If left unspecified (empty),\nthe minimal shape required to contain all the elements in the ragged tensor\n(the natural shape) will be used. If some dimensions are left unspecified, then\nthe size of the natural shape is used in that dimension.\n\nNote that dense dimensions cannot be modified by the shape argument. Trying to\nchange the size of a dense dimension will cause the op to fail.\nExamples:\nnatural shape: [4, 5, 6]\nshape: -1\noutput shape: [4, 5, 6]\n\nnatural shape: [4, 5, 6]\nshape: [3, -1, 2]\noutput shape: [3, 5, 2]\n\nnatural shape: [4, 5, 6]\nshape: [3, 7, 2]\noutput shape: [3, 7, 2]\n","name":"shape","typeAttr":"Tshape"},{"description":"A 1D tensor representing the values of the ragged tensor.","name":"values","typeAttr":"T"},{"description":"The default_value when the shape is larger than the ragged tensor. The\ndefault_value is broadcast until it is the shape of the output tensor, and\nthen overwritten by values in the ragged tensor. The default value must be\ncompatible with this broadcast operation, and must have fewer dimensions than\nthe value tensor.","name":"default_value","typeAttr":"T"},{"name":"row_partition_tensors","numberAttr":"num_row_partition_tensors","typeAttr":"Tindex"}],"outputs":[{"description":"The resulting dense tensor.","name":"result","typeAttr":"T"}],"summary":"Create a dense tensor from a ragged tensor, possibly altering its shape."}},{"name":"RaggedTensorToVariant","schema":{"attributes":[{"minimum":0,"name":"RAGGED_RANK","type":"int64"},{"name":"Tvalues","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"},{"description":"A `bool` denoting whether the input is a batched `RaggedTensor`.","name":"batched_input","type":"boolean"}],"description":"\nEncodes the given `RaggedTensor` and returns a `variant` Tensor. If\n`batched_input` is True, then input `RaggedTensor` is unbatched along the\nzero-th dimension, each component `RaggedTensor` is encoded into a scalar\n`variant` Tensor, and these are stacked to return a 1-D `variant` Tensor.\nIf `batched_input` is False, then the input `RaggedTensor` is encoded as is and\na scalar `variant` Tensor is returned. A `RaggedTensor` is encoded by first\ncreating a 1-D `variant` Tensor with `ragged_rank + 1` elements, containing the\nsplits and values Tensors of the `RaggedTensor`. Then the 1-D `variant` Tensor\nis wrapped in a scalar `variant` Tensor. See `RaggedTensorFromVariant` for the\ncorresponding decoding logic.\n","inputs":[{"description":"A list of one or more Tensors representing the splits of the input\n`RaggedTensor`.","name":"rt_nested_splits","numberAttr":"RAGGED_RANK","typeAttr":"Tsplits"},{"description":"A Tensor representing the values of the input `RaggedTensor`.","name":"rt_dense_values","typeAttr":"Tvalues"}],"outputs":[{"description":"A `variant` Tensor that containing encoded `RaggedTensor`.","name":"encoded_ragged","type":21}],"summary":"Encodes a `RaggedTensor` into a `variant` Tensor."}},{"name":"RandomCrop","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"`size` is a 1-D int64 tensor with 2 elements representing the crop height and\nwidth. The values must be non negative.\n\nThis Op picks a random location in `image` and crops a `height` by `width`\nrectangle from that location. The random location is picked so the cropped\narea will fit inside the original image.","inputs":[{"description":"3-D of shape `[height, width, channels]`.","name":"image","typeAttr":"T"},{"description":"1-D of length 2 containing: `crop_height`, `crop_width`..","name":"size","type":9}],"outputs":[{"description":"3-D of shape `[crop_height, crop_width, channels].`","name":"output","typeAttr":"T"}],"summary":"Randomly crop `image`."}},{"name":"RandomDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a Dataset that returns a stream of uniformly distributed\npseudorandom 64-bit signed integers.\n\nIn the TensorFlow Python API, you can instantiate this dataset via the\nclass `tf.data.experimental.RandomDataset`.\n\nInstances of this dataset are also created as a result of the\n`hoist_random_uniform` static optimization. Whether this optimization is\nperformed is determined by the `experimental_optimization.hoist_random_uniform`\noption of `tf.data.Options`.","inputs":[{"description":"A scalar seed for the random number generator. If either seed or\nseed2 is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a Dataset that returns pseudorandom numbers."}},{"name":"RandomGamma","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"This op uses the algorithm by Marsaglia et al. to acquire samples via\ntransformation-rejection from pairs of uniform and normal random variables.\nSee http://dl.acm.org/citation.cfm?id=358414","inputs":[{"description":"1-D integer tensor. Shape of independent samples to draw from each\ndistribution described by the shape parameters given in alpha.","name":"shape","typeAttr":"S"},{"description":"A tensor in which each scalar is a \"shape\" parameter describing the\nassociated gamma distribution.","name":"alpha","typeAttr":"T"}],"outputs":[{"description":"A tensor with shape `shape + shape(alpha)`. Each slice\n`[:, ..., :, i0, i1, ...iN]` contains the samples drawn for\n`alpha[i0, i1, ...iN]`. The dtype of the output matches the dtype of alpha.","name":"output","typeAttr":"T"}],"summary":"Outputs random values from the Gamma distribution(s) described by alpha."}},{"name":"RandomGammaGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"alpha","typeAttr":"T"},{"name":"sample","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the derivative of a Gamma random sample w.r.t. `alpha`."}},{"name":"RandomPoisson","schema":{"attributes":[{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"}],"inputs":[{"name":"shape","typeAttr":"S"},{"name":"rate","typeAttr":"dtype"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Use RandomPoissonV2 instead."}},{"name":"RandomPoissonV2","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"R","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"description":"This op uses two algorithms, depending on rate. If rate >= 10, then\nthe algorithm by Hormann is used to acquire samples via\ntransformation-rejection.\nSee http://www.sciencedirect.com/science/article/pii/0167668793909974.\n\nOtherwise, Knuth's algorithm is used to acquire samples via multiplying uniform\nrandom variables.\nSee Donald E. Knuth (1969). Seminumerical Algorithms. The Art of Computer\nProgramming, Volume 2. Addison Wesley","inputs":[{"description":"1-D integer tensor. Shape of independent samples to draw from each\ndistribution described by the shape parameters given in rate.","name":"shape","typeAttr":"S"},{"description":"A tensor in which each scalar is a \"rate\" parameter describing the\nassociated poisson distribution.","name":"rate","typeAttr":"R"}],"outputs":[{"description":"A tensor with shape `shape + shape(rate)`. Each slice\n`[:, ..., :, i0, i1, ...iN]` contains the samples drawn for\n`rate[i0, i1, ...iN]`.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from the Poisson distribution(s) described by rate."}},{"name":"RandomShuffle","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"name":"T","type":"type"}],"description":" The tensor is shuffled along dimension 0, such that each `value[j]` is mapped\n to one and only one `output[i]`. For example, a mapping that might occur for a\n 3x2 tensor is:\n\n```\n[[1, 2], [[5, 6],\n [3, 4], ==> [1, 2],\n [5, 6]] [3, 4]]\n```","inputs":[{"description":"The tensor to be shuffled.","name":"value","typeAttr":"T"}],"outputs":[{"description":"A tensor of same shape and type as `value`, shuffled along its first\ndimension.","name":"output","typeAttr":"T"}],"summary":"Randomly shuffles a tensor along its first dimension."}},{"name":"RandomShuffleQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":0,"description":"Dequeue will block unless there would be this\nmany elements after the dequeue or the queue is closed. This\nensures a minimum level of mixing of elements.","name":"min_after_dequeue","type":"int64"},{"default":0,"description":"If either seed or seed2 is set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that randomizes the order of elements."}},{"name":"RandomShuffleQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":0,"description":"Dequeue will block unless there would be this\nmany elements after the dequeue or the queue is closed. This\nensures a minimum level of mixing of elements.","name":"min_after_dequeue","type":"int64"},{"default":0,"description":"If either seed or seed2 is set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that randomizes the order of elements."}},{"name":"RandomStandardNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution."}},{"name":"RandomUniform","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with uniform random values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a uniform distribution."}},{"name":"RandomUniformInt","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tout","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values are uniform integers in the range `[minval, maxval)`.\nThe lower bound `minval` is included in the range, while the upper bound\n`maxval` is excluded.\n\nThe random integers are slightly biased unless `maxval - minval` is an exact\npower of two. The bias is small for values of `maxval - minval` significantly\nsmaller than the range of the output (either `2^32` or `2^64`).","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"0-D. Inclusive lower bound on the generated integers.","name":"minval","typeAttr":"Tout"},{"description":"0-D. Exclusive upper bound on the generated integers.","name":"maxval","typeAttr":"Tout"}],"outputs":[{"description":"A tensor of the specified shape filled with uniform random integers.","name":"output","typeAttr":"Tout"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"Range","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"This operation creates a sequence of numbers that begins at `start` and\nextends by increments of `delta` up to but not including `limit`.\n\nFor example:\n\n```\n# 'start' is 3\n# 'limit' is 18\n# 'delta' is 3\ntf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]\n```","inputs":[{"description":"0-D (scalar). First entry in the sequence.","name":"start","typeAttr":"Tidx"},{"description":"0-D (scalar). Upper limit of sequence, exclusive.","name":"limit","typeAttr":"Tidx"},{"description":"0-D (scalar). Optional. Default is 1. Number that increments `start`.","name":"delta","typeAttr":"Tidx"}],"outputs":[{"description":"1-D.","name":"output","typeAttr":"Tidx"}],"summary":"Creates a sequence of numbers."}},{"name":"RangeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"corresponds to start in python's xrange().","name":"start","type":9},{"description":"corresponds to stop in python's xrange().","name":"stop","type":9},{"description":"corresponds to step in python's xrange().","name":"step","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset with a range of values. Corresponds to python's xrange."}},{"name":"Rank","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This operation returns an integer representing the rank of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\n# shape of tensor 't' is [2, 2, 3]\nrank(t) ==> 3\n```\n\n**Note**: The rank of a tensor is not the same as the rank of a matrix. The rank\nof a tensor is the number of indices required to uniquely select each element\nof the tensor. Rank is also known as \"order\", \"degree\", or \"ndims.\"","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":3}],"summary":"Returns the rank of a tensor."}},{"name":"ReadFile","schema":{"inputs":[{"name":"filename","type":7}],"outputs":[{"name":"contents","type":7}],"summary":"Reads and outputs the entire contents of the input filename."}},{"name":"ReadVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"The tensor returned by this operation is immutable.\n\nThe value returned by this operation is guaranteed to be influenced by all the\nwrites on which this operation depends directly or indirectly, and to not be\ninfluenced by any of the writes which depend directly or indirectly on this\noperation.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Reads the value of a variable."}},{"name":"ReaderNumRecordsProduced","schema":{"description":"This is the same as the number of ReaderRead executions that have\nsucceeded.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"records_produced","type":9}],"summary":"Returns the number of records this Reader has produced."}},{"name":"ReaderNumRecordsProducedV2","schema":{"description":"This is the same as the number of ReaderRead executions that have\nsucceeded.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"records_produced","type":9}],"summary":"Returns the number of records this Reader has produced."}},{"name":"ReaderNumWorkUnitsCompleted","schema":{"inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"units_completed","type":9}],"summary":"Returns the number of work units this Reader has finished processing."}},{"name":"ReaderNumWorkUnitsCompletedV2","schema":{"inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"units_completed","type":9}],"summary":"Returns the number of work units this Reader has finished processing."}},{"name":"ReaderRead","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7},{"description":"Handle to a Queue, with string work items.","isRef":true,"name":"queue_handle","type":7}],"outputs":[{"description":"A scalar.","name":"key","type":7},{"description":"A scalar.","name":"value","type":7}],"summary":"Returns the next record (key, value pair) produced by a Reader."}},{"name":"ReaderReadUpTo","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).\nIt may return less than `num_records` even before the last batch.","inputs":[{"description":"Handle to a `Reader`.","isRef":true,"name":"reader_handle","type":7},{"description":"Handle to a `Queue`, with string work items.","isRef":true,"name":"queue_handle","type":7},{"description":"number of records to read from `Reader`.","name":"num_records","type":9}],"outputs":[{"description":"A 1-D tensor.","name":"keys","type":7},{"description":"A 1-D tensor.","name":"values","type":7}],"summary":"Returns up to `num_records` (key, value) pairs produced by a Reader."}},{"name":"ReaderReadUpToV2","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).\nIt may return less than `num_records` even before the last batch.","inputs":[{"description":"Handle to a `Reader`.","name":"reader_handle","type":20},{"description":"Handle to a `Queue`, with string work items.","name":"queue_handle","type":20},{"description":"number of records to read from `Reader`.","name":"num_records","type":9}],"outputs":[{"description":"A 1-D tensor.","name":"keys","type":7},{"description":"A 1-D tensor.","name":"values","type":7}],"summary":"Returns up to `num_records` (key, value) pairs produced by a Reader."}},{"name":"ReaderReadV2","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20},{"description":"Handle to a Queue, with string work items.","name":"queue_handle","type":20}],"outputs":[{"description":"A scalar.","name":"key","type":7},{"description":"A scalar.","name":"value","type":7}],"summary":"Returns the next record (key, value pair) produced by a Reader."}},{"name":"ReaderReset","schema":{"inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"Restore a Reader to its initial clean state."}},{"name":"ReaderResetV2","schema":{"inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"summary":"Restore a Reader to its initial clean state."}},{"name":"ReaderRestoreState","schema":{"description":"Not all Readers support being restored, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7},{"description":"Result of a ReaderSerializeState of a Reader with type\nmatching reader_handle.","name":"state","type":7}],"summary":"Restore a reader to a previously saved state."}},{"name":"ReaderRestoreStateV2","schema":{"description":"Not all Readers support being restored, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20},{"description":"Result of a ReaderSerializeState of a Reader with type\nmatching reader_handle.","name":"state","type":7}],"summary":"Restore a reader to a previously saved state."}},{"name":"ReaderSerializeState","schema":{"description":"Not all Readers support being serialized, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"state","type":7}],"summary":"Produce a string tensor that encodes the state of a Reader."}},{"name":"ReaderSerializeStateV2","schema":{"description":"Not all Readers support being serialized, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"state","type":7}],"summary":"Produce a string tensor that encodes the state of a Reader."}},{"name":"Real","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the real part of each element in `input`. All elements in\n`input` must be complex numbers of the form \\\\(a + bj\\\\), where *a* is the real\n part returned by this operation and *b* is the imaginary part.\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.real(input) ==> [-2.25, 3.25]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the real part of a complex number."}},{"name":"RealDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"If `x` and `y` are reals, this will return the floating-point division.\n\n*NOTE*: `Div` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise for real types."}},{"name":"RebatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_fallback","type":"boolean"}],"description":"Creates a dataset that changes the batch size of the dataset to current batch\nsize // num_workers.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of replicas to distribute this batch across. As\na result of this transformation the current batch size would end up being\ndivided by this parameter.","name":"num_replicas","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"RebatchDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that rebatches elements from `input_dataset` into new batch\nsizes.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A vector of integers representing the size of batches to produce. These values\nare cycled through in order.","name":"batch_sizes","type":9},{"name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"Reciprocal","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the reciprocal of x element-wise."}},{"name":"ReciprocalGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the inverse of `x` wrt its input."}},{"name":"RecordInput","schema":{"attributes":[{"description":"Glob pattern for the data files.","name":"file_pattern","type":"string"},{"default":301,"description":"Random seeds used to produce randomized records.","name":"file_random_seed","type":"int64"},{"default":0,"description":"Shifts the list of files after the list is randomly\nshuffled.","name":"file_shuffle_shift_ratio","type":"float32"},{"default":10000,"description":"The randomization shuffling buffer.","name":"file_buffer_size","type":"int64"},{"default":16,"description":"How many sstables are opened and concurrently iterated over.","name":"file_parallelism","type":"int64"},{"default":32,"description":"The batch size.","name":"batch_size","type":"int64"},{"default":"","description":"The type of compression for the file. Currently ZLIB and\nGZIP are supported. Defaults to none.","name":"compression_type","type":"string"}],"outputs":[{"description":"A tensor of shape [batch_size].","name":"records","type":7}],"summary":"Emits randomized records."}},{"name":"Recv","schema":{"attributes":[{"name":"tensor_type","type":"type"},{"description":"The name of the tensor to receive.","name":"tensor_name","type":"string"},{"description":"The name of the device sending the tensor.","name":"send_device","type":"string"},{"description":"The current incarnation of send_device.","name":"send_device_incarnation","type":"int64"},{"description":"The name of the device receiving the tensor.","name":"recv_device","type":"string"},{"default":false,"description":"If set to true, this indicates that the node was added\nto the graph as a result of a client-side feed or fetch of Tensor data,\nin which case the corresponding send or recv is expected to be managed\nlocally by the caller.","name":"client_terminated","type":"boolean"}],"outputs":[{"description":"The tensor to receive.","name":"tensor","typeAttr":"tensor_type"}],"summary":"Receives the named tensor from send_device on recv_device."}},{"name":"RecvTPUEmbeddingActivations","schema":{"attributes":[{"description":"The number of output activation tensors, equal to the number of\nembedding tables in the model.","minimum":1,"name":"num_outputs","type":"int64"},{"description":"Serialized TPUEmbeddingConfiguration proto.","name":"config","type":"string"}],"description":"The TPU system performs the embedding lookups and aggregations specified by\nthe arguments to TPUEmbeddingEnqueue(Integer/Sparse/SparseTensor)Batch. The\nresults of these aggregations are visible to the Tensorflow Graph as the\noutputs of a RecvTPUEmbeddingActivations op. This op returns a list containing\none Tensor of activations per table specified in the model. There can be at\nmost one RecvTPUEmbeddingActivations op in the TPU graph.","outputs":[{"description":"A TensorList of embedding activations containing one Tensor per\nembedding table in the model.","name":"outputs","numberAttr":"num_outputs","type":1}],"summary":"An op that receives embedding activations on the TPU."}},{"name":"ReduceDataset","schema":{"attributes":[{"description":"A function that maps `(old_state, input_element)` to `new_state`. It must take\ntwo arguments and return a nested structures of tensors. The structure of\n`new_state` must match the structure of `initial_state`.","name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"}],"inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A nested structure of tensors, representing the initial state of the\ntransformation.","name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Reduces the input dataset to a singleton using a reduce function."}},{"name":"ReduceJoin","schema":{"attributes":[{"default":false,"description":"If `True`, retain reduced dimensions with length `1`.","name":"keep_dims","type":"boolean"},{"default":"","description":"The separator to use when joining.","name":"separator","type":"string"}],"description":"Computes the string join across dimensions in the given string Tensor of shape\n`[\\\\(d_0, d_1, ..., d_{n-1}\\\\)]`. Returns a new Tensor created by joining the input\nstrings with the given separator (default: empty string). Negative indices are\ncounted backwards from the end, with `-1` being equivalent to `n - 1`. If\nindices are not specified, joins across all dimensions beginning from `n - 1`\nthrough `0`.\n\nFor example:\n\n```python\n# tensor `a` is [[\"a\", \"b\"], [\"c\", \"d\"]]\ntf.reduce_join(a, 0) ==> [\"ac\", \"bd\"]\ntf.reduce_join(a, 1) ==> [\"ab\", \"cd\"]\ntf.reduce_join(a, -2) = tf.reduce_join(a, 0) ==> [\"ac\", \"bd\"]\ntf.reduce_join(a, -1) = tf.reduce_join(a, 1) ==> [\"ab\", \"cd\"]\ntf.reduce_join(a, 0, keep_dims=True) ==> [[\"ac\", \"bd\"]]\ntf.reduce_join(a, 1, keep_dims=True) ==> [[\"ab\"], [\"cd\"]]\ntf.reduce_join(a, 0, separator=\".\") ==> [\"a.c\", \"b.d\"]\ntf.reduce_join(a, [0, 1]) ==> \"acbd\"\ntf.reduce_join(a, [1, 0]) ==> \"abcd\"\ntf.reduce_join(a, []) ==> [[\"a\", \"b\"], [\"c\", \"d\"]]\ntf.reduce_join(a) = tf.reduce_join(a, [1, 0]) ==> \"abcd\"\n```","inputs":[{"description":"The input to be joined. All reduced indices must have non-zero size.","name":"inputs","type":7},{"description":"The dimensions to reduce over. Dimensions are reduced in the\norder specified. Omitting `reduction_indices` is equivalent to passing\n`[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported.","name":"reduction_indices","type":3}],"outputs":[{"description":"Has shape equal to that of the input with reduced dimensions removed or\nset to `1` depending on `keep_dims`.","name":"output","type":7}],"summary":"Joins a string Tensor across the given dimensions."}},{"name":"RefEnter","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the child frame.","name":"frame_name","type":"string"},{"default":false,"description":"If true, the output is constant within the child frame.","name":"is_constant","type":"boolean"},{"default":10,"description":"The number of iterations allowed to run in parallel.","name":"parallel_iterations","type":"int64"}],"description":"The unique `frame_name` is used by the `Executor` to identify frames. If\n`is_constant` is true, `output` is a constant in the child frame; otherwise\nit may be changed in the child frame. At most `parallel_iterations` iterations\nare run in parallel in the child frame.","inputs":[{"description":"The tensor to be made available to the child frame.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Creates or finds a child frame, and makes `data` available to the child frame."}},{"name":"RefExit","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Exit makes its input `data` available to the parent frame.","inputs":[{"description":"The tensor to be made available to the parent frame.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Exits the current frame to its parent frame."}},{"name":"RefIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"input","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output","typeAttr":"T"}],"summary":"Return the same ref tensor as the input ref tensor."}},{"name":"RefMerge","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"description":"`Merge` waits for at least one of the tensors in `inputs` to become available.\nIt is usually combined with `Switch` to implement branching.\n\n`Merge` forwards the first tensor for become available to `output`, and sets\n`value_index` to its index in `inputs`.","inputs":[{"description":"The input tensors, exactly one of which will become available.","isRef":true,"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Will be set to the available input tensor.","isRef":true,"name":"output","typeAttr":"T"},{"description":"The index of the chosen input tensor in `inputs`.","name":"value_index","type":3}],"summary":"Forwards the value of an available tensor from `inputs` to `output`."}},{"name":"RefNextIteration","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be made available to the next iteration.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Makes its input available to the next iteration."}},{"name":"RefSelect","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A scalar that determines the input that gets selected.","name":"index","type":3},{"description":"A list of ref tensors, one of which will be forwarded to `output`.","isRef":true,"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The forwarded tensor.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Forwards the `index`th element of `inputs` to `output`."}},{"name":"RefSwitch","schema":{"attributes":[{"name":"T","type":"type"}],"description":"If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise,\nthe data goes to `output_false`.\n\nSee also `Switch` and `Merge`.","inputs":[{"description":"The ref tensor to be forwarded to the appropriate output.","isRef":true,"name":"data","typeAttr":"T"},{"description":"A scalar that specifies which output port will receive data.","name":"pred","type":10}],"outputs":[{"description":"If `pred` is false, data will be forwarded to this output.","isRef":true,"name":"output_false","typeAttr":"T"},{"description":"If `pred` is true, data will be forwarded to this output.","isRef":true,"name":"output_true","typeAttr":"T"}],"summary":"Forwards the ref tensor `data` to the output port determined by `pred`."}},{"name":"RegexFullMatch","schema":{"description":"The input is a string tensor of any shape. The pattern is a scalar\nstring tensor which is applied to every element of the input tensor.\nThe boolean values (True or False) of the output tensor indicate\nif the input matches the regex pattern provided.\n\nThe pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)\n\nExamples:\n\n>>> tf.strings.regex_full_match([\"TF lib\", \"lib TF\"], \".*lib$\")\n\n>>> tf.strings.regex_full_match([\"TF lib\", \"lib TF\"], \".*TF$\")\n","inputs":[{"description":"A string tensor of the text to be processed.","name":"input","type":7},{"description":"A scalar string tensor containing the regular expression to match the input.","name":"pattern","type":7}],"outputs":[{"description":"A bool tensor with the same shape as `input`.","name":"output","type":10}],"summary":"Check if the input matches the regex pattern."}},{"name":"RegexReplace","schema":{"attributes":[{"default":true,"description":"If True, the replacement is global (that is, all matches of the `pattern` regular\nexpression in each input string are rewritten), otherwise the `rewrite`\nsubstitution is only made for the first `pattern` match.","name":"replace_global","type":"boolean"}],"description":"It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"The text to be processed.","name":"input","type":7},{"description":"The regular expression to be matched in the `input` strings.","name":"pattern","type":7},{"description":"The rewrite string to be substituted for the `pattern` expression where it is\nmatched in the `input` strings.","name":"rewrite","type":7}],"outputs":[{"description":"The text after applying pattern match and rewrite substitution.","name":"output","type":7}],"summary":"Replaces matches of the `pattern` regular expression in `input` with the\nreplacement string provided in `rewrite`."}},{"name":"RegisterDataset","schema":{"attributes":[{"name":"external_state_policy","type":"int64"}],"inputs":[{"name":"dataset","type":21},{"name":"address","type":7},{"name":"protocol","type":7}],"outputs":[{"name":"dataset_id","type":9}],"summary":"Registers a dataset with the tf.data service."}},{"name":"Relu","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`, `qint8`.","name":"T","type":"type"}],"category":"Activation","description":"See: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)\nExample usage:\n>>> tf.nn.relu([-2., 0., -0., 3.]).numpy()\narray([ 0., 0., -0., 3.], dtype=float32)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear: `max(features, 0)`."}},{"name":"Relu6","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"category":"Activation","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear 6: `min(max(features, 0), 6)`."}},{"name":"Relu6Grad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Relu6 operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding Relu6 operation, or\nits output; using either one produces the same result.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients:\n`gradients * (features > 0) * (features < 6)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear 6 gradients for a Relu6 operation."}},{"name":"ReluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Relu operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding Relu operation, OR\nthe outputs of that operation (both work equivalently).","name":"features","typeAttr":"T"}],"outputs":[{"description":"`gradients * (features > 0)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear gradients for a Relu operation."}},{"name":"RemoteCall","schema":{"attributes":[{"description":"The type list for the arguments.","minimum":1,"name":"Tin","type":"type[]"},{"description":"The type list for the return values.","minimum":1,"name":"Tout","type":"type[]"},{"description":"The function to run remotely.","name":"f","type":"function"}],"inputs":[{"description":"A fully specified device name where we want to run the function.","name":"target","type":7},{"description":"A list of arguments for the function.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"Runs function `f` on a remote device indicated by `target`."}},{"name":"RemoteFusedGraphExecute","schema":{"attributes":[{"minimum":0,"name":"Tinputs","type":"type[]"},{"minimum":0,"name":"Toutputs","type":"type[]"},{"description":"Serialized protocol buffer\nof RemoteFusedGraphExecuteInfo which contains graph specifications.","name":"serialized_remote_fused_graph_execute_info","type":"string"}],"description":"The graph specifications(such as graph itself, input tensors and output names)\nare stored as a serialized protocol buffer of RemoteFusedGraphExecuteInfo\nas serialized_remote_fused_graph_execute_info.\nThe specifications will be passed to a dedicated registered\nremote fused graph executor. The executor will send the graph specifications\nto a remote processor and execute that graph. The execution results\nwill be passed to consumer nodes as outputs of this node.","inputs":[{"description":"Arbitrary number of tensors with arbitrary data types","name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"description":"Arbitrary number of tensors with arbitrary data types","name":"outputs","typeListAttr":"Toutputs"}],"summary":"Execute a sub graph on a remote processor."}},{"name":"RepeatDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of times that `input_dataset` should\nbe repeated. A value of `-1` indicates that it should be repeated infinitely.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the outputs of `input_dataset` `count` times."}},{"name":"RequantizationRange","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"}],"description":"Given a quantized tensor described by `(input, input_min, input_max)`, outputs a\nrange that covers the actual values present in that tensor. This op is typically\nused to produce the `requested_output_min` and `requested_output_max` for\n`Requantize`.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1}],"outputs":[{"description":"The computed min output.","name":"output_min","type":1},{"description":"the computed max output.","name":"output_max","type":1}],"summary":"Computes a range that covers the actual values present in a quantized tensor."}},{"name":"RequantizationRangePerChannel","schema":{"attributes":[{"default":{"type":"type","value":13},"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The maximum value of the output that needs to be clipped.\nExample: set this to 6 for Relu6.","name":"clip_value_max","type":"float32"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"T"},{"description":"The minimum value of the input tensor","name":"input_min","type":1},{"description":"The maximum value of the input tensor.","name":"input_max","type":1}],"outputs":[{"description":"The minimum value of the final output tensor","name":"output_min","type":1},{"description":"The maximum value of the final output tensor.","name":"output_max","type":1}],"summary":"Computes requantization range per channel."}},{"name":"Requantize","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the output. Should be a lower bit depth than Tinput. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"Converts the quantized `input` tensor into a lower-precision `output`, using the\noutput range specified with `requested_output_min` and `requested_output_max`.\n\n`[input_min, input_max]` are scalar floats that specify the range for the float\ninterpretation of the `input` data. For example, if `input_min` is -1.0f and\n`input_max` is 1.0f, and we are dealing with `quint16` quantized data, then a 0\nvalue in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1},{"description":"The float value that the minimum quantized output value represents.","name":"requested_output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"requested_output_max","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The requested_output_min value is copied into this output.","name":"output_min","type":1},{"description":"The requested_output_max value is copied into this output.","name":"output_max","type":1}],"summary":"Converts the quantized `input` tensor into a lower-precision `output`."}},{"name":"RequantizePerChannel","schema":{"attributes":[{"default":{"type":"type","value":13},"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":{"type":"type","value":12},"description":"The quantized type of output tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"T"},{"description":"The minimum value of the input tensor","name":"input_min","type":1},{"description":"The maximum value of the input tensor.","name":"input_max","type":1},{"description":"The minimum value of the output tensor requested.","name":"requested_output_min","type":1},{"description":"The maximum value of the output tensor requested.","name":"requested_output_max","type":1}],"outputs":[{"description":"Output tensor.","name":"output","typeAttr":"out_type"},{"description":"The minimum value of the final output tensor","name":"output_min","type":1},{"description":"The maximum value of the final output tensor.","name":"output_max","type":1}],"summary":"Requantizes input with min and max values known per channel."}},{"name":"Reshape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"category":"Shape","description":"Given `tensor`, this operation returns a tensor that has the same values\nas `tensor` with shape `shape`.\n\nIf one component of 1-D tensor `shape` is the special value -1, the size of that\ndimension is computed so that the total size remains constant. In particular, a\n`shape` of `[-1]` flattens into 1-D. At most one component of `shape` may be\nunknown.\n\nThe `shape` must be 1-D and the operation returns a tensor with shape\n`shape` filled with the values of `tensor`. In this case, the number of elements\nimplied by `shape` must be the same as the number of elements in `tensor`.\n\nIt is an error if `shape` is not 1-D.\n\nFor example:\n\n```\n# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# tensor 't' has shape [9]\nreshape(t, [3, 3]) ==> [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n# tensor 't' is [[[1, 1], [2, 2]],\n# [[3, 3], [4, 4]]]\n# tensor 't' has shape [2, 2, 2]\nreshape(t, [2, 4]) ==> [[1, 1, 2, 2],\n [3, 3, 4, 4]]\n\n# tensor 't' is [[[1, 1, 1],\n# [2, 2, 2]],\n# [[3, 3, 3],\n# [4, 4, 4]],\n# [[5, 5, 5],\n# [6, 6, 6]]]\n# tensor 't' has shape [3, 2, 3]\n# pass '[-1]' to flatten 't'\nreshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]\n\n# -1 can also be used to infer the shape\n\n# -1 is inferred to be 9:\nreshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 2:\nreshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 3:\nreshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]]]\n\n# tensor 't' is [7]\n# shape `[]` reshapes to a scalar\nreshape(t, []) ==> 7\n```","inputs":[{"name":"tensor","typeAttr":"T"},{"description":"Defines the shape of the output tensor.","name":"shape","typeAttr":"Tshape"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Reshapes a tensor."}},{"name":"ResizeArea","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"}],"description":"Input images can be of different types but output images are always float.\n\nThe range of pixel values for the output image might be slightly different\nfrom the range for the input image because of limited numerical precision.\nTo guarantee an output range, for example `[0.0, 1.0]`, apply\n`tf.clip_by_value` to the output.\n\nEach output pixel is computed by first transforming the pixel's footprint into\nthe input tensor and then averaging the pixels that intersect the footprint. An\ninput pixel's contribution to the average is weighted by the fraction of its\narea that intersects the footprint. This is the same as OpenCV's INTER_AREA.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using area interpolation."}},{"name":"ResizeBicubic","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images can be of different types but output images are always float.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using bicubic interpolation."}},{"name":"ResizeBicubicGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","type":1},{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`,\nThe image tensor that was resized.","name":"original_image","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`.\nGradients with respect to the input image. Input image must have been\nfloat or double.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of bicubic interpolation."}},{"name":"ResizeBilinear","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images can be of different types but output images are always float.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using bilinear interpolation."}},{"name":"ResizeBilinearGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `bfloat16`, `float16`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","type":1},{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`,\nThe image tensor that was resized.","name":"original_image","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`.\nGradients with respect to the input image. Input image must have been\nfloat or double.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of bilinear interpolation."}},{"name":"ResizeNearestNeighbor","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","typeAttr":"T"}],"summary":"Resize `images` to `size` using nearest neighbor interpolation."}},{"name":"ResizeNearestNeighborGrad","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int32`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The\noriginal input size.","name":"size","type":3}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`. Gradients\nwith respect to the input image.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of nearest neighbor interpolation."}},{"name":"ResourceAccumulatorApplyGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"Does not add if local_step is lesser than the accumulator's global_step.","inputs":[{"description":"The handle to a accumulator.","name":"handle","type":20},{"description":"The local_step value at which the gradient was computed.","name":"local_step","type":9},{"description":"A tensor of the gradient to be accumulated.","name":"gradient","typeAttr":"dtype"}],"summary":"Applies a gradient to a given accumulator."}},{"name":"ResourceAccumulatorNumAccumulated","schema":{"inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20}],"outputs":[{"description":"The number of gradients aggregated in the given accumulator.","name":"num_accumulated","type":3}],"summary":"Returns the number of gradients aggregated in the given accumulators."}},{"name":"ResourceAccumulatorSetGlobalStep","schema":{"description":"Logs warning if the accumulator's value is already higher than\nnew_global_step.","inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20},{"description":"The new global_step value to set.","name":"new_global_step","type":9}],"summary":"Updates the accumulator with a new value for global_step."}},{"name":"ResourceAccumulatorTakeGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"The op blocks until sufficient (i.e., more than num_required)\ngradients have been accumulated. If the accumulator has already\naggregated more than num_required gradients, it returns the average of\nthe accumulated gradients. Also automatically increments the recorded\nglobal_step in the accumulator by 1, and resets the aggregate to 0.","inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20},{"description":"Number of gradients required before we return an aggregate.","name":"num_required","type":3}],"outputs":[{"description":"The average of the accumulated gradients.","name":"average","typeAttr":"dtype"}],"summary":"Extracts the average gradient in the given ConditionalAccumulator."}},{"name":"ResourceApplyAdaMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nv_t <- max(beta2 * v_{t-1}, abs(g))\nvariable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AdaMax algorithm."}},{"name":"ResourceApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var, accum and update_accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum = rho() * accum + (1 - rho()) * grad.square();\nupdate = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad;\nupdate_accum = rho() * update_accum + (1 - rho()) * update.square();\nvar -= update;","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"accum_update","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adadelta scheme."}},{"name":"ResourceApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ResourceApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"gradient_accumulator","type":20},{"description":"Should be from a Variable().","name":"gradient_squared_accumulator","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"summary":"Update '*var' according to the proximal adagrad scheme."}},{"name":"ResourceApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / (sqrt(accum) + epsilon))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ResourceApplyAdam","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, uses the nesterov update.","name":"use_nesterov","type":"boolean"}],"description":"$$\\text{lr}_t := \\mathrm{learning_rate} * \\sqrt{1 - \\beta_2^t} / (1 - \\beta_1^t)$$\n$$m_t := \\beta_1 * m_{t-1} + (1 - \\beta_1) * g$$\n$$v_t := \\beta_2 * v_{t-1} + (1 - \\beta_2) * g * g$$\n$$\\text{variable} := \\text{variable} - \\text{lr}_t * m_t / (\\sqrt{v_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ResourceApplyAdamWithAmsgrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"$$\\text{lr}_t := \\mathrm{learning_rate} * \\sqrt{1 - \\beta_2^t} / (1 - \\beta_1^t)$$\n$$m_t := \\beta_1 * m_{t-1} + (1 - \\beta_1) * g$$\n$$v_t := \\beta_2 * v_{t-1} + (1 - \\beta_2) * g * g$$\n$$\\hat{v}_t := max{\\hat{v}_{t-1}, v_t}$$\n$$\\text{variable} := \\text{variable} - \\text{lr}_t * m_t / (\\sqrt{\\hat{v}_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Should be from a Variable().","name":"vhat","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ResourceApplyAddSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- (alpha + sign_decay * sign(g) *sign(m)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ResourceApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\n\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nmg <- rho * mg_{t-1} + (1-rho) * grad\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"mg","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ResourceApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"accum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"grad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad_with_shrinkage * grad_with_shrinkage\nlinear += grad_with_shrinkage +\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceApplyGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"summary":"Update '*var' by subtracting 'alpha' * 'delta' from it."}},{"name":"ResourceApplyKerasMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar + momentum * accum, so in the end, the var you get is actually\nvar + momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum - lr * grad\nvar += accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ResourceApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ResourceApplyPowerSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"logbase","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ResourceApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum += grad * grad\nprox_v = var - lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' and '*accum' according to FOBOS with Adagrad learning rate."}},{"name":"ResourceApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"prox_v = var - alpha * delta\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"summary":"Update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ResourceApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ResourceConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values, can be [], in which case shape is unknown.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the\ngiven name across multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.\nThis is a resource version of ConditionalAccumulator that will work in TF2.0\nwith tf.cond version 2.","outputs":[{"description":"The handle to the accumulator.","name":"handle","type":20}],"summary":"A conditional accumulator for aggregating gradients."}},{"name":"ResourceCountUpTo","schema":{"attributes":[{"description":"If incrementing ref would bring it above limit, instead generates an\n'OutOfRange' error.","name":"limit","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Should be from a scalar `Variable` node.","name":"resource","type":20}],"outputs":[{"description":"A copy of the input before increment. If nothing else modifies the\ninput, the values produced will all be distinct.","name":"output","typeAttr":"T"}],"summary":"Increments variable pointed to by 'resource' until it reaches 'limit'."}},{"name":"ResourceGather","schema":{"attributes":[{"default":0,"name":"batch_dims","type":"int64"},{"default":true,"name":"validate_indices","type":"boolean"},{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `indices.shape + params.shape[1:]` where:\n\n```python\n # Scalar indices\n output[:, ..., :] = params[indices, :, ... :]\n\n # Vector indices\n output[i, :, ..., :] = params[indices[i], :, ... :]\n\n # Higher rank indices\n output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]\n```","inputs":[{"name":"resource","type":20},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Gather slices from the variable pointed to by `resource` according to `indices`."}},{"name":"ResourceGatherNd","schema":{"attributes":[{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"name":"resource","type":20},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"dtype"}]}},{"name":"ResourceScatterAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] += updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] += updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Adds sparse updates to the variable referenced by `resource`."}},{"name":"ResourceScatterDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] /= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] /= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Divides sparse updates into the variable referenced by `resource`."}},{"name":"ResourceScatterMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = max(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions are combined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Reduces sparse updates into the variable referenced by `resource` using the `max` operation."}},{"name":"ResourceScatterMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = min(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions are combined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Reduces sparse updates into the variable referenced by `resource` using the `min` operation."}},{"name":"ResourceScatterMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] *= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] *= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Multiplies sparse updates into the variable referenced by `resource`."}},{"name":"ResourceScatterNdAdd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that addition would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True)\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nadd = tf.scatter_nd_add(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(add)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse addition to individual values or slices in a Variable."}},{"name":"ResourceScatterNdMax","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues whose element wise max is taken with ref","name":"updates","typeAttr":"T"}]}},{"name":"ResourceScatterNdMin","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues whose element wise min is taken with ref.","name":"updates","typeAttr":"T"}]}},{"name":"ResourceScatterNdSub","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to subtract 4 scattered elements from a rank-1 tensor\nwith 8 elements. In Python, that subtraction would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True)\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nsub = tf.scatter_nd_sub(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(sub)\n```\n\nThe resulting update to ref would look like this:\n\n [1, -9, 3, -6, -4, 6, 7, -4]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse subtraction to individual values or slices in a Variable."}},{"name":"ResourceScatterNdUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n```\n\nFor example, say we want to update 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that update would look like this:\n\n```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n update = tf.scatter_nd_update(ref, indices, updates)\n with tf.Session() as sess:\n print sess.run(update)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse `updates` to individual values or slices within a given"}},{"name":"ResourceScatterSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] -= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] -= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Subtracts sparse updates from the variable referenced by `resource`."}},{"name":"ResourceScatterUpdate","schema":{"attributes":[{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] = updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Assigns sparse updates to the variable referenced by `resource`."}},{"name":"ResourceSparseApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":": Should be from a Variable().","name":"accum_update","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"var: Should be from a Variable()."}},{"name":"ResourceSparseApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"ResourceSparseApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"gradient_accumulator","type":20},{"description":"Should be from a Variable().","name":"gradient_squared_accumulator","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"summary":"Update entries in '*var' and '*accum' according to the proximal adagrad scheme."}},{"name":"ResourceSparseApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"ResourceSparseApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"mg","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ResourceSparseApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\naccum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceSparseApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\ngrad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad_with_shrinkage * grad_with_shrinkage\nlinear += grad_with_shrinkage +\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceSparseApplyKerasMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar + momentum * accum, so in the end, the var you get is actually\nvar + momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\naccum = accum * momentum - lr * grad\nvar += accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"ResourceSparseApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"ResourceSparseApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nprox_v = var\nprox_v -= lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Sparse update entries in '*var' and '*accum' according to FOBOS algorithm."}},{"name":"ResourceSparseApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var as follows:\nprox_v = var - alpha * grad\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Sparse update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ResourceSparseApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ResourceStridedSliceAssign","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the variable\n`ref` that are selected by the slice parameters. The slice parameters\n`begin, `end`, `strides`, etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s\nshape must be exactly the shape produced by the slice of `ref`.","inputs":[{"name":"ref","type":20},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `ref`."}},{"name":"Restore","schema":{"attributes":[{"description":"The type of the tensor to be restored.","name":"dt","type":"type"},{"default":-1,"description":"Index of file to open first if multiple files match\n`file_pattern`.","name":"preferred_shard","type":"int64"}],"description":"Reads a tensor stored in one or several files. If there are several files (for\ninstance because a tensor was saved as slices), `file_pattern` may contain\nwildcard symbols (`*` and `?`) in the filename portion only, not in the\ndirectory portion.\n\nIf a `file_pattern` matches several files, `preferred_shard` can be used to hint\nin which file the requested tensor is likely to be found. This op will first\nopen the file at index `preferred_shard` in the list of matching files and try\nto restore tensors from that file. Only if some tensors or tensor slices are\nnot found in that first file, then the Op opens all the files. Setting\n`preferred_shard` to match the value passed as the `shard` input\nof a matching `Save` Op may speed up Restore. This attribute only affects\nperformance, not correctness. The default value -1 means files are processed in\norder.\n\nSee also `RestoreSlice`.","inputs":[{"description":"Must have a single element. The pattern of the files from\nwhich we read the tensor.","name":"file_pattern","type":7},{"description":"Must have a single element. The name of the tensor to be\nrestored.","name":"tensor_name","type":7}],"outputs":[{"description":"The restored tensor.","name":"tensor","typeAttr":"dt"}],"summary":"Restores a tensor from checkpoint files."}},{"name":"RestoreSlice","schema":{"attributes":[{"description":"The type of the tensor to be restored.","name":"dt","type":"type"},{"default":-1,"description":"Index of file to open first if multiple files match\n`file_pattern`. See the documentation for `Restore`.","name":"preferred_shard","type":"int64"}],"description":"This is like `Restore` except that restored tensor can be listed as filling\nonly a slice of a larger tensor. `shape_and_slice` specifies the shape of the\nlarger tensor and the slice that the restored tensor covers.\n\nThe `shape_and_slice` input has the same format as the\nelements of the `shapes_and_slices` input of the `SaveSlices` op.","inputs":[{"description":"Must have a single element. The pattern of the files from\nwhich we read the tensor.","name":"file_pattern","type":7},{"description":"Must have a single element. The name of the tensor to be\nrestored.","name":"tensor_name","type":7},{"description":"Scalar. The shapes and slice specifications to use when\nrestoring a tensors.","name":"shape_and_slice","type":7}],"outputs":[{"description":"The restored tensor.","name":"tensor","typeAttr":"dt"}],"summary":"Restores a tensor from checkpoint files."}},{"name":"RestoreV2","schema":{"attributes":[{"description":"shape {N}. The list of expected dtype for the tensors. Must match\nthose stored in the checkpoint.","minimum":1,"name":"dtypes","type":"type[]"}],"description":"For backward compatibility with the V1 format, this Op currently allows\nrestoring from a V1 checkpoint as well:\n - This Op first attempts to find the V2 index file pointed to by \"prefix\", and\n if found proceed to read it as a V2 checkpoint;\n - Otherwise the V1 read path is invoked.\nRelying on this behavior is not recommended, as the ability to fall back to read\nV1 might be deprecated and eventually removed.\n\nBy default, restores the named tensors in full. If the caller wishes to restore\nspecific slices of stored tensors, \"shape_and_slices\" should be non-empty\nstrings and correspondingly well-formed.\n\nCallers must ensure all the named tensors are indeed stored in the checkpoint.","inputs":[{"description":"Must have a single element. The prefix of a V2 checkpoint.","name":"prefix","type":7},{"description":"shape {N}. The names of the tensors to be restored.","name":"tensor_names","type":7},{"description":"shape {N}. The slice specs of the tensors to be restored.\nEmpty strings indicate that they are non-partitioned tensors.","name":"shape_and_slices","type":7}],"outputs":[{"description":"shape {N}. The restored tensors, whose shapes are read from the\ncheckpoint directly.","name":"tensors","typeListAttr":"dtypes"}],"summary":"Restores tensors from a V2 checkpoint."}},{"name":"RetrieveTPUEmbeddingADAMParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Parameter velocities updated by the ADAM optimization algorithm.","name":"velocities","type":1}],"summary":"Retrieve ADAM embedding parameters."}},{"name":"RetrieveTPUEmbeddingADAMParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Parameter velocities updated by the ADAM optimization algorithm.","name":"velocities","type":1},{"description":"Parameter gradient_accumulators updated by the ADAM optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve ADAM embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingAdadeltaParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter updates updated by the Adadelta optimization algorithm.","name":"updates","type":1}],"summary":"Retrieve Adadelta embedding parameters."}},{"name":"RetrieveTPUEmbeddingAdadeltaParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter updates updated by the Adadelta optimization algorithm.","name":"updates","type":1},{"description":"Parameter gradient_accumulators updated by the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Adadelta embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Retrieve Adagrad embedding parameters."}},{"name":"RetrieveTPUEmbeddingAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter gradient_accumulators updated by the Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Adagrad embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingCenteredRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the centered RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the centered RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the centered RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Parameter mg updated by the centered RMSProp optimization algorithm.","name":"mg","type":1}],"summary":"Retrieve centered RMSProp embedding parameters."}},{"name":"RetrieveTPUEmbeddingFTRLParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter linears updated by the FTRL optimization algorithm.","name":"linears","type":1}],"summary":"Retrieve FTRL embedding parameters."}},{"name":"RetrieveTPUEmbeddingFTRLParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter linears updated by the FTRL optimization algorithm.","name":"linears","type":1},{"description":"Parameter gradient_accumulators updated by the FTRL optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve FTRL embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingMDLAdagradLightParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the MDL Adagrad Light optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the MDL Adagrad Light optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter weights updated by the MDL Adagrad Light optimization algorithm.","name":"weights","type":1},{"description":"Parameter benefits updated by the MDL Adagrad Light optimization algorithm.","name":"benefits","type":1}],"summary":"Retrieve MDL Adagrad Light embedding parameters."}},{"name":"RetrieveTPUEmbeddingMomentumParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the Momentum optimization algorithm.","name":"momenta","type":1}],"summary":"Retrieve Momentum embedding parameters."}},{"name":"RetrieveTPUEmbeddingMomentumParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the Momentum optimization algorithm.","name":"momenta","type":1},{"description":"Parameter gradient_accumulators updated by the Momentum optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Momentum embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingProximalAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the proximal Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Retrieve proximal Adagrad embedding parameters."}},{"name":"RetrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the proximal Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter gradient_accumulators updated by the proximal Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve proximal Adagrad embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingProximalYogiParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"outputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1}]}},{"name":"RetrieveTPUEmbeddingProximalYogiParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"outputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1},{"name":"gradient_accumulators","type":1}]}},{"name":"RetrieveTPUEmbeddingRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the RMSProp optimization algorithm.","name":"mom","type":1}],"summary":"Retrieve RMSProp embedding parameters."}},{"name":"RetrieveTPUEmbeddingRMSPropParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Parameter gradient_accumulators updated by the RMSProp optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve RMSProp embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingStochasticGradientDescentParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the stochastic gradient descent optimization algorithm.","name":"parameters","type":1}],"summary":"Retrieve SGD embedding parameters."}},{"name":"RetrieveTPUEmbeddingStochasticGradientDescentParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the stochastic gradient descent optimization algorithm.","name":"parameters","type":1},{"description":"Parameter gradient_accumulators updated by the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve SGD embedding parameters with debug support."}},{"name":"Reverse","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"Given a `tensor`, and a `bool` tensor `dims` representing the dimensions\nof `tensor`, this operation reverses each dimension i of `tensor` where\n`dims[i]` is `True`.\n\n`tensor` can have up to 8 dimensions. The number of dimensions\nof `tensor` must equal the number of elements in `dims`. In other words:\n\n`rank(tensor) = size(dims)`\n\nFor example:\n\n```\n# tensor 't' is [[[[ 0, 1, 2, 3],\n# [ 4, 5, 6, 7],\n# [ 8, 9, 10, 11]],\n# [[12, 13, 14, 15],\n# [16, 17, 18, 19],\n# [20, 21, 22, 23]]]]\n# tensor 't' shape is [1, 2, 3, 4]\n\n# 'dims' is [False, False, False, True]\nreverse(t, dims) ==> [[[[ 3, 2, 1, 0],\n [ 7, 6, 5, 4],\n [ 11, 10, 9, 8]],\n [[15, 14, 13, 12],\n [19, 18, 17, 16],\n [23, 22, 21, 20]]]]\n\n# 'dims' is [False, True, False, False]\nreverse(t, dims) ==> [[[[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]\n [[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]]]]\n\n# 'dims' is [False, False, True, False]\nreverse(t, dims) ==> [[[[8, 9, 10, 11],\n [4, 5, 6, 7],\n [0, 1, 2, 3]]\n [[20, 21, 22, 23],\n [16, 17, 18, 19],\n [12, 13, 14, 15]]]]\n```","inputs":[{"description":"Up to 8-D.","name":"tensor","typeAttr":"T"},{"description":"1-D. The dimensions to reverse.","name":"dims","type":10}],"outputs":[{"description":"The same shape as `tensor`.","name":"output","typeAttr":"T"}],"summary":"Reverses specific dimensions of a tensor."}},{"name":"ReverseSequence","schema":{"attributes":[{"description":"The dimension which is partially reversed.","name":"seq_dim","type":"int64"},{"default":0,"description":"The dimension along which reversal is performed.","name":"batch_dim","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlen","type":"type"}],"description":"This op first slices `input` along the dimension `batch_dim`, and for each\nslice `i`, reverses the first `seq_lengths[i]` elements along\nthe dimension `seq_dim`.\n\nThe elements of `seq_lengths` must obey `seq_lengths[i] <= input.dims[seq_dim]`,\nand `seq_lengths` must be a vector of length `input.dims[batch_dim]`.\n\nThe output slice `i` along dimension `batch_dim` is then given by input\nslice `i`, with the first `seq_lengths[i]` slices along dimension\n`seq_dim` reversed.\n\nFor example:\n\n```\n# Given this:\nbatch_dim = 0\nseq_dim = 1\ninput.dims = (4, 8, ...)\nseq_lengths = [7, 2, 3, 5]\n\n# then slices of input are reversed on seq_dim, but only up to seq_lengths:\noutput[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...]\noutput[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...]\noutput[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...]\noutput[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...]\n\n# while entries past seq_lens are copied through:\noutput[0, 7:, :, ...] = input[0, 7:, :, ...]\noutput[1, 2:, :, ...] = input[1, 2:, :, ...]\noutput[2, 3:, :, ...] = input[2, 3:, :, ...]\noutput[3, 2:, :, ...] = input[3, 2:, :, ...]\n```\n\nIn contrast, if:\n\n```\n# Given this:\nbatch_dim = 2\nseq_dim = 0\ninput.dims = (8, ?, 4, ...)\nseq_lengths = [7, 2, 3, 5]\n\n# then slices of input are reversed on seq_dim, but only up to seq_lengths:\noutput[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...]\noutput[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...]\noutput[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...]\noutput[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...]\n\n# while entries past seq_lens are copied through:\noutput[7:, :, 0, :, ...] = input[7:, :, 0, :, ...]\noutput[2:, :, 1, :, ...] = input[2:, :, 1, :, ...]\noutput[3:, :, 2, :, ...] = input[3:, :, 2, :, ...]\noutput[2:, :, 3, :, ...] = input[2:, :, 3, :, ...]\n```","inputs":[{"description":"The input to reverse.","name":"input","typeAttr":"T"},{"description":"1-D with length `input.dims(batch_dim)` and\n`max(seq_lengths) <= input.dims(seq_dim)`","name":"seq_lengths","typeAttr":"Tlen"}],"outputs":[{"description":"The partially reversed input. It has the same shape as `input`.","name":"output","typeAttr":"T"}],"summary":"Reverses variable length slices."}},{"name":"ReverseV2","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"NOTE `tf.reverse` has now changed behavior in preparation for 1.0.\n`tf.reverse_v2` is currently an alias that will be deprecated before TF 1.0.\n\nGiven a `tensor`, and a `int32` tensor `axis` representing the set of\ndimensions of `tensor` to reverse. This operation reverses each dimension\n`i` for which there exists `j` s.t. `axis[j] == i`.\n\n`tensor` can have up to 8 dimensions. The number of dimensions specified\nin `axis` may be 0 or more entries. If an index is specified more than\nonce, a InvalidArgument error is raised.\n\nFor example:\n\n```\n# tensor 't' is [[[[ 0, 1, 2, 3],\n# [ 4, 5, 6, 7],\n# [ 8, 9, 10, 11]],\n# [[12, 13, 14, 15],\n# [16, 17, 18, 19],\n# [20, 21, 22, 23]]]]\n# tensor 't' shape is [1, 2, 3, 4]\n\n# 'dims' is [3] or 'dims' is [-1]\nreverse(t, dims) ==> [[[[ 3, 2, 1, 0],\n [ 7, 6, 5, 4],\n [ 11, 10, 9, 8]],\n [[15, 14, 13, 12],\n [19, 18, 17, 16],\n [23, 22, 21, 20]]]]\n\n# 'dims' is '[1]' (or 'dims' is '[-3]')\nreverse(t, dims) ==> [[[[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]\n [[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]]]]\n\n# 'dims' is '[2]' (or 'dims' is '[-2]')\nreverse(t, dims) ==> [[[[8, 9, 10, 11],\n [4, 5, 6, 7],\n [0, 1, 2, 3]]\n [[20, 21, 22, 23],\n [16, 17, 18, 19],\n [12, 13, 14, 15]]]]\n```","inputs":[{"description":"Up to 8-D.","name":"tensor","typeAttr":"T"},{"description":"1-D. The indices of the dimensions to reverse. Must be in the range\n`[-rank(tensor), rank(tensor))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"description":"The same shape as `tensor`.","name":"output","typeAttr":"T"}],"summary":"Reverses specific dimensions of a tensor."}},{"name":"RightShift","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Performs a logical shift for unsigned integer types, and an arithmetic shift\nfor signed integer types.\n\nIf `y` is negative, or greater than or equal to than the width of `x` in bits\nthe result is implementation defined.\n\nExample:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\nimport numpy as np\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([-1, -5, -3, -14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n\n right_shift_result = bitwise_ops.right_shift(lhs, rhs)\n\n print(right_shift_result)\n\n# This will print:\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int8)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int16)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int32)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int64)\n\nlhs = np.array([-2, 64, 101, 32], dtype=np.int8)\nrhs = np.array([-1, -5, -3, -14], dtype=np.int8)\nbitwise_ops.right_shift(lhs, rhs)\n# \n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise right-shift of `x` and `y`."}},{"name":"Rint","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"If the result is midway between two representable values,\nthe even representable is chosen.\nFor example:\n\n```\nrint(-1.5) ==> -2.0\nrint(0.5000001) ==> 1.0\nrint([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) ==> [-2., -2., -0., 0., 2., 2., 2.]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise integer closest to x."}},{"name":"RngSkip","schema":{"description":"The state of the RNG after\n`rng_skip(n)` will be the same as that after `stateful_uniform([n])`\n(or any other distribution). The actual increment added to the\ncounter is an unspecified implementation detail.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The amount of advancement.","name":"delta","type":9}],"summary":"Advance the counter of a counter-based RNG."}},{"name":"Roll","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tshift","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"}],"description":"The elements are shifted positively (towards larger indices) by the offset of\n`shift` along the dimension of `axis`. Negative `shift` values will shift\nelements in the opposite direction. Elements that roll passed the last position\nwill wrap around to the first and vice versa. Multiple shifts along multiple\naxes may be specified.\n\nFor example:\n\n```\n# 't' is [0, 1, 2, 3, 4]\nroll(t, shift=2, axis=0) ==> [3, 4, 0, 1, 2]\n\n# shifting along multiple dimensions\n# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\nroll(t, shift=[1, -2], axis=[0, 1]) ==> [[7, 8, 9, 5, 6], [2, 3, 4, 0, 1]]\n\n# shifting along the same axis multiple times\n# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\nroll(t, shift=[2, -3], axis=[1, 1]) ==> [[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]\n```","inputs":[{"name":"input","typeAttr":"T"},{"description":"Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which\nelements are shifted positively (towards larger indices) along the dimension\nspecified by `axis[i]`. Negative shifts will roll the elements in the opposite\ndirection.","name":"shift","typeAttr":"Tshift"},{"description":"Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift\n`shift[i]` should occur. If the same axis is referenced more than once, the\ntotal shift for that axis will be the sum of all the shifts that belong to that\naxis.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"Has the same shape and size as the input. The elements are shifted\npositively (towards larger indices) by the offsets of `shift` along the\ndimensions of `axis`.","name":"output","typeAttr":"T"}],"summary":"Rolls the elements of a tensor along an axis."}},{"name":"Round","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Rounds half to even. Also known as bankers rounding. If you want to round\naccording to the current system rounding mode use std::cint.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Rounds the values of a tensor to the nearest integer, element-wise."}},{"name":"Rpc","schema":{"attributes":[{"default":"","description":"RPC protocol to use. Empty string means use the default protocol.\nOptions include 'grpc'.","name":"protocol","type":"string"},{"default":true,"description":"`boolean`. If `true` (default), then failures to connect\n(i.e., the server does not immediately respond) cause an RPC failure.","name":"fail_fast","type":"boolean"},{"default":0,"description":"`int`. If `0` (default), then the kernel will run the RPC\nrequest and only time out if the RPC deadline passes or the session times out.\nIf this value is greater than `0`, then the op will raise an exception if\nthe RPC takes longer than `timeout_in_ms`.","name":"timeout_in_ms","type":"int64"}],"description":"This op asynchronously performs either a single RPC request, or a batch\nof requests. RPC requests are defined by three main parameters:\n\n - `address` (the host+port or BNS address of the request)\n - `method` (the RPC method name for the request)\n - `request` (the serialized proto string, or vector of strings,\n of the RPC request argument).\n\nFor example, if you have an RPC service running on port localhost:2345,\nand its interface is configured with the following proto declaration:\n\n```\nservice MyService {\n rpc MyMethod(MyRequestProto) returns (MyResponseProto) {\n }\n};\n```\n\nthen call this op with arguments:\n\n```\naddress = \"localhost:2345\"\nmethod = \"MyService/MyMethod\"\n```\n\nThe `request` tensor is a string tensor representing serialized `MyRequestProto`\nstrings; and the output string tensor `response` will have the same shape\nand contain (upon successful completion) corresponding serialized\n`MyResponseProto` strings.\n\nFor example, to send a single, empty, `MyRequestProto`, call\nthis op with `request = \"\"`. To send 5 **parallel** empty requests,\ncall this op with `request = [\"\", \"\", \"\", \"\", \"\"]`.\n\nMore generally, one can create a batch of `MyRequestProto` serialized protos\nfrom regular batched tensors using the `encode_proto` op, and convert\nthe response `MyResponseProto` serialized protos to batched tensors\nusing the `decode_proto` op.\n\n**NOTE** Working with serialized proto strings is faster than instantiating\nactual proto objects in memory, so no performance degradation is expected\ncompared to writing custom kernels for this workflow.\n\nIf the connection fails or the remote worker returns an error\nstatus, the op reraises this exception locally.\n\nSee the `TryRpc` op if you prefer to handle RPC failures manually in the graph.","inputs":[{"description":"`0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `method` and `request`.","name":"address","type":7},{"description":"`0-D` or `1-D`. The method address on the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `request`.","name":"method","type":7},{"description":"`0-D` or `1-D`. Serialized proto strings: the rpc request argument.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `method`.","name":"request","type":7}],"outputs":[{"description":"Same shape as `request`. Serialized proto strings: the rpc responses.","name":"response","type":7}],"summary":"Perform batches of RPC requests."}},{"name":"Rsqrt","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / \\sqrt{x}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes reciprocal of square root of x element-wise."}},{"name":"RsqrtGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * -0.5 * y^3`, where `y = rsqrt(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the rsqrt of `x` wrt its input."}},{"name":"SampleDistortedBoundingBox","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"},{"default":0,"description":"If either `seed` or `seed2` are set to non-zero, the random number\ngenerator is seeded by the given `seed`. Otherwise, it is seeded by a random\nseed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":0.10000000149011612,"description":"The cropped area of the image must contain at least this\nfraction of any bounding box supplied. The value of this parameter should be\nnon-negative. In the case of 0, the cropped area does not need to overlap\nany of the bounding boxes supplied.","name":"min_object_covered","type":"float32"},{"default":[0.75,1.3300000429153442],"description":"The cropped area of the image must have an aspect ratio =\nwidth / height within this range.","name":"aspect_ratio_range","type":"float32[]"},{"default":[0.05000000074505806,1],"description":"The cropped area of the image must contain a fraction of the\nsupplied image within this range.","name":"area_range","type":"float32[]"},{"default":100,"description":"Number of attempts at generating a cropped region of the image\nof the specified constraints. After `max_attempts` failures, return the entire\nimage.","name":"max_attempts","type":"int64"},{"default":false,"description":"Controls behavior if no bounding boxes supplied.\nIf true, assume an implicit bounding box covering the whole input. If false,\nraise an error.","name":"use_image_if_no_bounding_boxes","type":"boolean"}],"description":"Bounding box annotations are often supplied in addition to ground-truth labels\nin image recognition or object localization tasks. A common technique for\ntraining such a system is to randomly distort an image while preserving\nits content, i.e. *data augmentation*. This Op outputs a randomly distorted\nlocalization of an object, i.e. bounding box, given an `image_size`,\n`bounding_boxes` and a series of constraints.\n\nThe output of this Op is a single bounding box that may be used to crop the\noriginal image. The output is returned as 3 tensors: `begin`, `size` and\n`bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the\nimage. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize\nwhat the bounding box looks like.\n\nBounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example,\n\n```python\n # Generate a single distorted bounding box.\n begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bounding_boxes)\n\n # Draw the bounding box in an image summary.\n image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),\n bbox_for_draw)\n tf.summary.image('images_with_box', image_with_box)\n\n # Employ the bounding box to distort the image.\n distorted_image = tf.slice(image, begin, size)\n```\n\nNote that if no bounding box information is available, setting\n`use_image_if_no_bounding_boxes = true` will assume there is a single implicit\nbounding box covering the whole image. If `use_image_if_no_bounding_boxes` is\nfalse and no bounding boxes are supplied, an error is raised.","inputs":[{"description":"1-D, containing `[height, width, channels]`.","name":"image_size","typeAttr":"T"},{"description":"3-D with shape `[batch, N, 4]` describing the N bounding boxes\nassociated with the image.","name":"bounding_boxes","type":1}],"outputs":[{"description":"1-D, containing `[offset_height, offset_width, 0]`. Provide as input to\n`tf.slice`.","name":"begin","typeAttr":"T"},{"description":"1-D, containing `[target_height, target_width, -1]`. Provide as input to\n`tf.slice`.","name":"size","typeAttr":"T"},{"description":"3-D with shape `[1, 1, 4]` containing the distorted bounding box.\nProvide as input to `tf.image.draw_bounding_boxes`.","name":"bboxes","type":1}],"summary":"Generate a single randomly distorted bounding box for an image."}},{"name":"SampleDistortedBoundingBoxV2","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"},{"default":0,"description":"If either `seed` or `seed2` are set to non-zero, the random number\ngenerator is seeded by the given `seed`. Otherwise, it is seeded by a random\nseed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":[0.75,1.3300000429153442],"description":"The cropped area of the image must have an aspect ratio =\nwidth / height within this range.","name":"aspect_ratio_range","type":"float32[]"},{"default":[0.05000000074505806,1],"description":"The cropped area of the image must contain a fraction of the\nsupplied image within this range.","name":"area_range","type":"float32[]"},{"default":100,"description":"Number of attempts at generating a cropped region of the image\nof the specified constraints. After `max_attempts` failures, return the entire\nimage.","name":"max_attempts","type":"int64"},{"default":false,"description":"Controls behavior if no bounding boxes supplied.\nIf true, assume an implicit bounding box covering the whole input. If false,\nraise an error.","name":"use_image_if_no_bounding_boxes","type":"boolean"}],"description":"Bounding box annotations are often supplied in addition to ground-truth labels\nin image recognition or object localization tasks. A common technique for\ntraining such a system is to randomly distort an image while preserving\nits content, i.e. *data augmentation*. This Op outputs a randomly distorted\nlocalization of an object, i.e. bounding box, given an `image_size`,\n`bounding_boxes` and a series of constraints.\n\nThe output of this Op is a single bounding box that may be used to crop the\noriginal image. The output is returned as 3 tensors: `begin`, `size` and\n`bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the\nimage. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize\nwhat the bounding box looks like.\n\nBounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example,\n\n```python\n # Generate a single distorted bounding box.\n begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bounding_boxes)\n\n # Draw the bounding box in an image summary.\n image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),\n bbox_for_draw)\n tf.summary.image('images_with_box', image_with_box)\n\n # Employ the bounding box to distort the image.\n distorted_image = tf.slice(image, begin, size)\n```\n\nNote that if no bounding box information is available, setting\n`use_image_if_no_bounding_boxes = true` will assume there is a single implicit\nbounding box covering the whole image. If `use_image_if_no_bounding_boxes` is\nfalse and no bounding boxes are supplied, an error is raised.","inputs":[{"description":"1-D, containing `[height, width, channels]`.","name":"image_size","typeAttr":"T"},{"description":"3-D with shape `[batch, N, 4]` describing the N bounding boxes\nassociated with the image.","name":"bounding_boxes","type":1},{"description":"The cropped area of the image must contain at least this\nfraction of any bounding box supplied. The value of this parameter should be\nnon-negative. In the case of 0, the cropped area does not need to overlap\nany of the bounding boxes supplied.","name":"min_object_covered","type":1}],"outputs":[{"description":"1-D, containing `[offset_height, offset_width, 0]`. Provide as input to\n`tf.slice`.","name":"begin","typeAttr":"T"},{"description":"1-D, containing `[target_height, target_width, -1]`. Provide as input to\n`tf.slice`.","name":"size","typeAttr":"T"},{"description":"3-D with shape `[1, 1, 4]` containing the distorted bounding box.\nProvide as input to `tf.image.draw_bounding_boxes`.","name":"bboxes","type":1}],"summary":"Generate a single randomly distorted bounding box for an image."}},{"name":"SamplingDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"There is no transformation in the `tf.data` Python API for creating this dataset.\nInstead, it is created as a result of the `filter_with_random_uniform_fusion`\nstatic optimization. Whether this optimization is performed is determined by the\n`experimental_optimization.filter_with_random_uniform_fusion` option of\n`tf.data.Options`.","inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the sample rate. Each element of `input_dataset` is\nretained with this probability, independent of all other elements.","name":"rate","type":1},{"description":"A scalar representing seed of random number generator.","name":"seed","type":9},{"description":"A scalar representing seed2 of random number generator.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that takes a Bernoulli sample of the contents of another dataset."}},{"name":"Save","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"The size of `tensor_names` must match the number of tensors in `data`. `data[i]`\nis written to `filename` with name `tensor_names[i]`.\n\nSee also `SaveSlices`.","inputs":[{"description":"Must have a single element. The name of the file to which we write\nthe tensor.","name":"filename","type":7},{"description":"Shape `[N]`. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"`N` tensors to save.","name":"data","typeListAttr":"T"}],"summary":"Saves the input tensors to disk."}},{"name":"SaveDataset","schema":{"attributes":[{"default":"","name":"compression","type":"string"},{"name":"shard_func","type":"function"},{"default":true,"name":"use_shard_func","type":"boolean"},{"minimum":0,"name":"Tshard_func_args","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"path","type":7},{"name":"shard_func_other_args","typeListAttr":"Tshard_func_args"}]}},{"name":"SaveSlices","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"This is like `Save` except that tensors can be listed in the saved file as being\na slice of a larger tensor. `shapes_and_slices` specifies the shape of the\nlarger tensor and the slice that this tensor covers. `shapes_and_slices` must\nhave as many elements as `tensor_names`.\n\nElements of the `shapes_and_slices` input must either be:\n\n* The empty string, in which case the corresponding tensor is\n saved normally.\n* A string of the form `dim0 dim1 ... dimN-1 slice-spec` where the\n `dimI` are the dimensions of the larger tensor and `slice-spec`\n specifies what part is covered by the tensor to save.\n\n`slice-spec` itself is a `:`-separated list: `slice0:slice1:...:sliceN-1`\nwhere each `sliceI` is either:\n\n* The string `-` meaning that the slice covers all indices of this dimension\n* `start,length` where `start` and `length` are integers. In that\n case the slice covers `length` indices starting at `start`.\n\nSee also `Save`.","inputs":[{"description":"Must have a single element. The name of the file to which we write the\ntensor.","name":"filename","type":7},{"description":"Shape `[N]`. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"Shape `[N]`. The shapes and slice specifications to use when\nsaving the tensors.","name":"shapes_and_slices","type":7},{"description":"`N` tensors to save.","name":"data","typeListAttr":"T"}],"summary":"Saves input tensors slices to disk."}},{"name":"SaveV2","schema":{"attributes":[{"minimum":1,"name":"dtypes","type":"type[]"}],"description":"By default, saves the named tensors in full. If the caller wishes to save\nspecific slices of full tensors, \"shape_and_slices\" should be non-empty strings\nand correspondingly well-formed.","inputs":[{"description":"Must have a single element. The prefix of the V2 checkpoint to which we\nwrite the tensors.","name":"prefix","type":7},{"description":"shape {N}. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"shape {N}. The slice specs of the tensors to be saved.\nEmpty strings indicate that they are non-partitioned tensors.","name":"shape_and_slices","type":7},{"description":"`N` tensors to save.","name":"tensors","typeListAttr":"dtypes"}],"summary":"Saves tensors in V2 checkpoint format."}},{"name":"ScalarSummary","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The input `tags` and `values` must have the same shape. The generated summary\nhas a summary value for each tag-value pair in `tags` and `values`.","inputs":[{"description":"Tags for the summary.","name":"tags","type":7},{"description":"Same shape as `tags. Values for the summary.","name":"values","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with scalar values."}},{"name":"ScaleAndTranslate","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lanczos3","name":"kernel_type","type":"string"},{"default":true,"name":"antialias","type":"boolean"}],"inputs":[{"name":"images","typeAttr":"T"},{"name":"size","type":3},{"name":"scale","type":1},{"name":"translation","type":1}],"outputs":[{"name":"resized_images","type":1}]}},{"name":"ScaleAndTranslateGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"},{"default":"lanczos3","name":"kernel_type","type":"string"},{"default":true,"name":"antialias","type":"boolean"}],"inputs":[{"name":"grads","typeAttr":"T"},{"name":"original_image","typeAttr":"T"},{"name":"scale","type":1},{"name":"translation","type":1}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"ScanDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"},{"default":true,"name":"use_default_device","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset successively reduces `f` over the elements of `input_dataset`."}},{"name":"ScatterAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the addition will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] += updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] += updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Adds sparse updates to a variable reference."}},{"name":"ScatterDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the operation will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] /= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] /= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions divide.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of values that `ref` is divided by.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Divides a variable reference by sparse updates."}},{"name":"ScatterMax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the update will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = max(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions combine.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to reduce into `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Reduces sparse updates into a variable reference using the `max` operation."}},{"name":"ScatterMin","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the update will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = min(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions combine.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to reduce into `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Reduces sparse updates into a variable reference using the `min` operation."}},{"name":"ScatterMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the operation will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] *= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] *= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to multiply to `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Multiplies sparse updates into a variable reference."}},{"name":"ScatterNd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Creates a new tensor by applying sparse `updates` to individual values or\nslices within a tensor (initially zero for numeric, empty for string) of\nthe given `shape` according to indices. This operator is the inverse of the\n`tf.gather_nd` operator which extracts values or slices from a given tensor.\n\nThis operation is similar to tensor_scatter_add, except that the tensor is\nzero-initialized. Calling `tf.scatter_nd(indices, values, shape)` is identical\nto `tensor_scatter_add(tf.zeros(shape, values.dtype), indices, values)`\n\nIf `indices` contains duplicates, then their updates are accumulated (summed).\n\n**WARNING**: The order in which updates are applied is nondeterministic, so the\noutput will be nondeterministic if `indices` contains duplicates -- because\nof some numerical approximation issues, numbers summed in different order\nmay yield different results.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of scatter is to insert individual elements in a tensor by\nindex. For example, say we want to insert 4 scattered elements in a rank-1\ntensor with 8 elements.\n\n
\n\n
\n\nIn Python, this scatter operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n shape = tf.constant([8])\n scatter = tf.scatter_nd(indices, updates, shape)\n print(scatter)\n```\n\nThe resulting tensor would look like this:\n\n [0, 11, 0, 10, 9, 0, 0, 12]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\n
\n\n
\n\nIn Python, this scatter operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n shape = tf.constant([4, 4, 4])\n scatter = tf.scatter_nd(indices, updates, shape)\n print(scatter)\n```\n\nThe resulting tensor would look like this:\n\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],\n [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"},{"description":"1-D. The shape of the resulting tensor.","name":"shape","typeAttr":"Tindices"}],"outputs":[{"description":"A new tensor with the given shape and updates applied according\nto the indices.","name":"output","typeAttr":"T"}],"summary":"Scatter `updates` into a new tensor according to `indices`."}},{"name":"ScatterNdAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that addition would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nadd = tf.scatter_nd_add(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(add)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse addition to individual values or slices in a Variable."}},{"name":"ScatterNdMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Computes element-wise maximum."}},{"name":"ScatterNdMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Computes element-wise minimum."}},{"name":"ScatterNdNonAliasingAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"from `updates` according to indices `indices`. The updates are non-aliasing:\n`input` is only modified in-place if no other operations will use it.\nOtherwise, a copy of `input` is made. This operation has a gradient with\nrespect to both `input` and `updates`.\n\n`input` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `input`.\nIt must be shape \\\\([d_0, ..., d_{Q-2}, K]\\\\) where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or `(P-K)`-dimensional slices\n(if `K < P`) along the `K`th dimension of `input`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n$$[d_0, ..., d_{Q-2}, input.shape[K], ..., input.shape[P-1]].$$\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to 8\nelements. In Python, that addition would look like this:\n\n input = tf.constant([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n output = tf.scatter_nd_non_aliasing_add(input, indices, updates)\n with tf.Session() as sess:\n print(sess.run(output))\n\nThe resulting value `output` would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to slices.","inputs":[{"description":"A Tensor.","name":"input","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: `int32`, `int64`.\nA tensor of indices into `input`.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to `input`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `input`, containing values of `input`\nupdated with `updates`.","name":"output","typeAttr":"T"}],"summary":"Applies sparse addition to `input` using individual values or slices"}},{"name":"ScatterNdSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"within a given variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to subtract 4 scattered elements from a rank-1 tensor\nwith 8 elements. In Python, that subtraction would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nsub = tf.scatter_nd_sub(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(sub)\n```\n\nThe resulting update to ref would look like this:\n\n [1, -9, 3, -6, -4, 6, 7, -4]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto subtract from ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse subtraction to individual values or slices in a Variable."}},{"name":"ScatterNdUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape \\\\([d_0, ..., d_{Q-2}, K]\\\\) where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n$$[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].$$\n\nFor example, say we want to update 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that update would look like this:\n\n```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n update = tf.scatter_nd_update(ref, indices, updates)\n with tf.Session() as sess:\n print sess.run(update)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.\n\nSee also `tf.scatter_update` and `tf.batch_scatter_update`.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want to\nuse the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse `updates` to individual values or slices within a given"}},{"name":"ScatterSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"```python\n # Scalar indices\n ref[indices, ...] -= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] -= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their (negated) contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to subtract from `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Subtracts sparse updates to a variable reference."}},{"name":"ScatterUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"If True, the assignment will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] = updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] = updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nIf values in `ref` is to be updated more than once, because there are\nduplicate entries in `indices`, the order at which the updates happen\nfor each value is undefined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
\n\n
\n\nSee also `tf.batch_scatter_update` and `tf.scatter_nd_update`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to store in `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse updates to a variable reference."}},{"name":"SdcaFprint","schema":{"inputs":[{"description":"vector of strings to compute fingerprints on.","name":"input","type":7}],"outputs":[{"description":"a (N,2) shaped matrix where N is the number of elements in the input\nvector. Each row contains the low and high parts of the fingerprint.","name":"output","type":9}],"summary":"Computes fingerprints of the input strings."}},{"name":"SdcaOptimizer","schema":{"attributes":[{"description":"Type of the primal loss. Currently SdcaSolver supports logistic,\nsquared and hinge losses. Must be one of the following: `logistic_loss`, `squared_loss`, `hinge_loss`, `smooth_hinge_loss`, `poisson_loss`.","name":"loss_type","type":"string"},{"default":false,"description":"Whether to use Adaptive SDCA for the inner loop.","name":"adaptative","type":"boolean"},{"description":"Number of sparse feature groups to train on.","minimum":0,"name":"num_sparse_features","type":"int64"},{"description":"Number of sparse feature groups with values\nassociated with it, otherwise implicitly treats values as 1.0.","minimum":0,"name":"num_sparse_features_with_values","type":"int64"},{"description":"Number of dense feature groups to train on.","minimum":0,"name":"num_dense_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength.","name":"l2","type":"float32"},{"description":"Number of partitions of the global loss function.","minimum":1,"name":"num_loss_partitions","type":"int64"},{"description":"Number of iterations per mini-batch.","minimum":1,"name":"num_inner_iterations","type":"int64"}],"description":"linear models with L1 + L2 regularization. As global optimization objective is\nstrongly-convex, the optimizer optimizes the dual objective at each step. The\noptimizer applies each update one example at a time. Examples are sampled\nuniformly, and the optimizer is learning rate free and enjoys linear convergence\nrate.\n\n[Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
\nShai Shalev-Shwartz, Tong Zhang. 2012\n\n$$Loss Objective = \\sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$\n\n[Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
\nChenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan,\nPeter Richtarik, Martin Takac. 2015\n\n[Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
\nDominik Csiba, Zheng Qu, Peter Richtarik. 2015","inputs":[{"description":"a list of vectors which contain example indices.","name":"sparse_example_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contain feature indices.","name":"sparse_feature_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contains feature value\nassociated with each feature group.","name":"sparse_feature_values","numberAttr":"num_sparse_features_with_values","type":1},{"description":"a list of matrices which contains the dense feature values.","name":"dense_features","numberAttr":"num_dense_features","type":1},{"description":"a vector which contains the weight associated with each\nexample.","name":"example_weights","type":1},{"description":"a vector which contains the label/target associated with each\nexample.","name":"example_labels","type":1},{"description":"a list of vectors where each value is the indices which has\ncorresponding weights in sparse_weights. This field maybe omitted for the\ndense approach.","name":"sparse_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors where each value is the weight associated with\na sparse feature group.","name":"sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the weights associated\nwith a dense feature group.","name":"dense_weights","numberAttr":"num_dense_features","type":1},{"description":"a list of vectors containing the example state data.","name":"example_state_data","type":1}],"outputs":[{"description":"a list of vectors containing the updated example state\ndata.","name":"out_example_state_data","type":1},{"description":"a list of vectors where each value is the delta\nweights associated with a sparse feature group.","name":"out_delta_sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the delta\nweights associated with a dense feature group.","name":"out_delta_dense_weights","numberAttr":"num_dense_features","type":1}],"summary":"Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for"}},{"name":"SdcaOptimizerV2","schema":{"attributes":[{"description":"Type of the primal loss. Currently SdcaSolver supports logistic,\nsquared and hinge losses. Must be one of the following: `logistic_loss`, `squared_loss`, `hinge_loss`, `smooth_hinge_loss`, `poisson_loss`.","name":"loss_type","type":"string"},{"default":false,"description":"Whether to use Adaptive SDCA for the inner loop.","name":"adaptive","type":"boolean"},{"description":"Number of sparse feature groups to train on.","minimum":0,"name":"num_sparse_features","type":"int64"},{"description":"Number of sparse feature groups with values\nassociated with it, otherwise implicitly treats values as 1.0.","minimum":0,"name":"num_sparse_features_with_values","type":"int64"},{"description":"Number of dense feature groups to train on.","minimum":0,"name":"num_dense_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength.","name":"l2","type":"float32"},{"description":"Number of partitions of the global loss function.","minimum":1,"name":"num_loss_partitions","type":"int64"},{"description":"Number of iterations per mini-batch.","minimum":1,"name":"num_inner_iterations","type":"int64"}],"description":"linear models with L1 + L2 regularization. As global optimization objective is\nstrongly-convex, the optimizer optimizes the dual objective at each step. The\noptimizer applies each update one example at a time. Examples are sampled\nuniformly, and the optimizer is learning rate free and enjoys linear convergence\nrate.\n\n[Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
\nShai Shalev-Shwartz, Tong Zhang. 2012\n\n$$Loss Objective = \\sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$\n\n[Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
\nChenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan,\nPeter Richtarik, Martin Takac. 2015\n\n[Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
\nDominik Csiba, Zheng Qu, Peter Richtarik. 2015","inputs":[{"description":"a list of vectors which contain example indices.","name":"sparse_example_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contain feature indices.","name":"sparse_feature_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contains feature value\nassociated with each feature group.","name":"sparse_feature_values","numberAttr":"num_sparse_features_with_values","type":1},{"description":"a list of matrices which contains the dense feature values.","name":"dense_features","numberAttr":"num_dense_features","type":1},{"description":"a vector which contains the weight associated with each\nexample.","name":"example_weights","type":1},{"description":"a vector which contains the label/target associated with each\nexample.","name":"example_labels","type":1},{"description":"a list of vectors where each value is the indices which has\ncorresponding weights in sparse_weights. This field maybe omitted for the\ndense approach.","name":"sparse_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors where each value is the weight associated with\na sparse feature group.","name":"sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the weights associated\nwith a dense feature group.","name":"dense_weights","numberAttr":"num_dense_features","type":1},{"description":"a list of vectors containing the example state data.","name":"example_state_data","type":1}],"outputs":[{"description":"a list of vectors containing the updated example state\ndata.","name":"out_example_state_data","type":1},{"description":"a list of vectors where each value is the delta\nweights associated with a sparse feature group.","name":"out_delta_sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the delta\nweights associated with a dense feature group.","name":"out_delta_dense_weights","numberAttr":"num_dense_features","type":1}],"summary":"Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for"}},{"name":"SdcaShrinkL1","schema":{"attributes":[{"description":"Number of feature groups to apply shrinking step.","minimum":0,"name":"num_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength. Should be a positive float.","name":"l2","type":"float32"}],"inputs":[{"description":"a list of vectors where each value is the weight associated with a\nfeature group.","isRef":true,"name":"weights","numberAttr":"num_features","type":1}],"summary":"Applies L1 regularization shrink step on the parameters."}},{"name":"SegmentMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\max_j(data_j)\\\\) where `max` is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the max is empty for a given segment ID `i`, `output[i] = 0`.\n\n
\n\n
\n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_max(c, tf.constant([0, 0, 1]))\n# ==> [[4, 3, 3, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum along segments of a tensor."}},{"name":"SegmentMean","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\frac{\\sum_j data_j}{N}\\\\) where `mean` is\nover `j` such that `segment_ids[j] == i` and `N` is the total number of\nvalues summed.\n\nIf the mean is empty for a given segment ID `i`, `output[i] = 0`.\n\n
\n\n
\n\nFor example:\n\n```\nc = tf.constant([[1.0,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_mean(c, tf.constant([0, 0, 1]))\n# ==> [[2.5, 2.5, 2.5, 2.5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along segments of a tensor."}},{"name":"SegmentMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\min_j(data_j)\\\\) where `min` is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the min is empty for a given segment ID `i`, `output[i] = 0`.\n\n
\n\n
\n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_min(c, tf.constant([0, 0, 1]))\n# ==> [[1, 2, 2, 1],\n# [5, 6, 7, 8]]\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum along segments of a tensor."}},{"name":"SegmentProd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\prod_j data_j\\\\) where the product is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the product is empty for a given segment ID `i`, `output[i] = 1`.\n\n
\n\n
\n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_prod(c, tf.constant([0, 0, 1]))\n# ==> [[4, 6, 6, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the product along segments of a tensor."}},{"name":"SegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\sum_j data_j\\\\) where sum is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the sum is empty for a given segment ID `i`, `output[i] = 0`.\n\n
\n\n
\n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_sum(c, tf.constant([0, 0, 1]))\n# ==> [[5, 5, 5, 5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along segments of a tensor."}},{"name":"Select","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The `t`, and `e` tensors must all have the same shape, and the\noutput will also have that shape.\n\nThe `condition` tensor must be a scalar if `t` and `e` are scalars.\nIf `t` and `e` are vectors or higher rank, then `condition` must be either a\nscalar, a vector with size matching the first dimension of `t`, or must have\nthe same shape as `t`.\n\nThe `condition` tensor acts as a mask that chooses, based on the value at each\nelement, whether the corresponding element / row in the output should be\ntaken from `t` (if true) or `e` (if false).\n\nIf `condition` is a vector and `t` and `e` are higher rank matrices, then\nit chooses which row (outer dimension) to copy from `t` and `e`.\nIf `condition` has the same shape as `t` and `e`, then it chooses which\nelement to copy from `t` and `e`.\n\nFor example:\n\n```python\n# 'condition' tensor is [[True, False]\n# [False, True]]\n# 't' is [[1, 2],\n# [3, 4]]\n# 'e' is [[5, 6],\n# [7, 8]]\nselect(condition, t, e) # => [[1, 6], [7, 4]]\n\n\n# 'condition' tensor is [True, False]\n# 't' is [[1, 2],\n# [3, 4]]\n# 'e' is [[5, 6],\n# [7, 8]]\nselect(condition, t, e) ==> [[1, 2],\n [7, 8]]\n\n```","inputs":[{"name":"condition","type":10},{"description":"= A `Tensor` which may have the same shape as `condition`.\nIf `condition` is rank 1, `t` may have higher rank,\nbut its first dimension must match the size of `condition`.","name":"t","typeAttr":"T"},{"description":"= A `Tensor` with the same type and shape as `t`.","name":"e","typeAttr":"T"}],"outputs":[{"description":"= A `Tensor` with the same type and shape as `t` and `e`.","name":"output","typeAttr":"T"}],"summary":"Selects elements from `t` or `e`, depending on `condition`."}},{"name":"SelectV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"condition","type":10},{"name":"t","typeAttr":"T"},{"name":"e","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"SelfAdjointEig","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices, with the same constraints as the single matrix\nSelfAdjointEig.\n\nThe result is a [..., M+1, M] matrix with [..., 0,:] containing the\neigenvalues, and subsequent [...,1:, :] containing the eigenvectors. The eigenvalues\nare sorted in non-decreasing order.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M+1, M]`.","name":"output","typeAttr":"T"}],"summary":"Computes the Eigen Decomposition of a batch of square self-adjoint matrices."}},{"name":"SelfAdjointEigV2","schema":{"attributes":[{"default":true,"description":"If `True` then eigenvectors will be computed and returned in `v`.\nOtherwise, only the eigenvalues will be computed.","name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the eigenvalues and (optionally) eigenvectors of each inner matrix in\n`input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues\nare sorted in non-decreasing order.\n\n```python\n# a is a tensor.\n# e is a tensor of eigenvalues.\n# v is a tensor of eigenvectors.\ne, v = self_adjoint_eig(a)\ne = self_adjoint_eig(a, compute_v=False)\n```","inputs":[{"description":"`Tensor` input of shape `[N, N]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Eigenvalues. Shape is `[N]`.","name":"e","typeAttr":"T"},{"description":"Eigenvectors. Shape is `[N, N]`.","name":"v","typeAttr":"T"}],"summary":"Computes the eigen decomposition of one or more square self-adjoint matrices."}},{"name":"Selu","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"if < 0, `scale * features` otherwise.\n\nTo be used together with\n`initializer = tf.variance_scaling_initializer(factor=1.0, mode='FAN_IN')`.\nFor correct dropout, use `tf.contrib.nn.alpha_dropout`.\n\nSee [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)`"}},{"name":"SeluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Selu operation.","name":"gradients","typeAttr":"T"},{"description":"The outputs of the corresponding Selu operation.","name":"outputs","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients * (outputs + scale * alpha)`\nif outputs < 0, `scale * gradients` otherwise.","name":"backprops","typeAttr":"T"}],"summary":"Computes gradients for the scaled exponential linear (Selu) operation."}},{"name":"Send","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the tensor to send.","name":"tensor_name","type":"string"},{"description":"The name of the device sending the tensor.","name":"send_device","type":"string"},{"description":"The current incarnation of send_device.","name":"send_device_incarnation","type":"int64"},{"description":"The name of the device receiving the tensor.","name":"recv_device","type":"string"},{"default":false,"description":"If set to true, this indicates that the node was added\nto the graph as a result of a client-side feed or fetch of Tensor data,\nin which case the corresponding send or recv is expected to be managed\nlocally by the caller.","name":"client_terminated","type":"boolean"}],"inputs":[{"description":"The tensor to send.","name":"tensor","typeAttr":"T"}],"summary":"Sends the named tensor from send_device to recv_device."}},{"name":"SendTPUEmbeddingGradients","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":0,"minimum":0,"name":"NN","type":"int64"},{"description":"Serialized TPUEmbeddingConfiguration proto.","name":"config","type":"string"}],"inputs":[{"description":"A TensorList of gradients with which to update embedding tables.\nThis argument has the same length and shapes as the return value of\nRecvTPUEmbeddingActivations, but contains gradients of the model's loss\nwith respect to the embedding activations. The embedding tables are updated\nfrom these gradients via the optimizer specified in the TPU embedding\nconfiguration given to tpu.initialize_system.","name":"inputs","numberAttr":"N","type":1},{"description":"A TensorList of float32 scalars, one for each dynamic learning\nrate tag: see the comments in\n//third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto.\nMultiple tables can share the same dynamic learning rate tag as specified\nin the configuration. If the learning rates for all tables are constant,\nthis list should be empty.","name":"learning_rates","numberAttr":"NN","type":1}],"summary":"Performs gradient updates of embedding tables."}},{"name":"SerializeIterator","schema":{"attributes":[{"default":0,"name":"external_state_policy","type":"int64"}],"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"outputs":[{"description":"A variant tensor storing the state of the iterator contained in the\nresource.","name":"serialized","type":21}],"summary":"Converts the given `resource_handle` representing an iterator to a variant tensor."}},{"name":"SerializeManySparse","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":7},"description":"The `dtype` to use for serialization; the supported types are `string`\n(default) and `variant`. Must be one of the following: `string`, `variant`.","name":"out_type","type":"type"}],"description":"The `SparseTensor` must have rank `R` greater than 1, and the first dimension\nis treated as the minibatch dimension. Elements of the `SparseTensor`\nmust be sorted in increasing order of this first dimension. The serialized\n`SparseTensor` objects going into each row of `serialized_sparse` will have\nrank `R-1`.\n\nThe minibatch size `N` is extracted from `sparse_shape[0]`.","inputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"name":"serialized_sparse","typeAttr":"out_type"}],"summary":"Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object."}},{"name":"SerializeSparse","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":7},"description":"The `dtype` to use for serialization; the supported types are `string`\n(default) and `variant`. Must be one of the following: `string`, `variant`.","name":"out_type","type":"type"}],"inputs":[{"description":"2-D. The `indices` of the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"name":"serialized_sparse","typeAttr":"out_type"}],"summary":"Serialize a `SparseTensor` into a `[3]` `Tensor` object."}},{"name":"SerializeTensor","schema":{"attributes":[{"description":"The type of the input tensor.","name":"T","type":"type"}],"inputs":[{"description":"A Tensor of type `T`.","name":"tensor","typeAttr":"T"}],"outputs":[{"description":"A serialized TensorProto proto of the input tensor.","name":"serialized","type":7}],"summary":"Transforms a Tensor into a serialized TensorProto proto."}},{"name":"SetSize","schema":{"attributes":[{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"Input `set` is a `SparseTensor` represented by `set_indices`, `set_values`,\nand `set_shape`. The last dimension contains values in a set, duplicates are\nallowed but ignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set`\nindices.","inputs":[{"description":"2D `Tensor`, indices of a `SparseTensor`.","name":"set_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`.","name":"set_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`.","name":"set_shape","type":9}],"outputs":[{"description":"For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st\n`n-1` dimensions as `set`. Each value is the number of unique elements in\nthe corresponding `[0...n-1]` dimension of `set`.","name":"size","type":3}],"summary":"Number of unique elements along last dimension of input `set`."}},{"name":"SetStatsAggregatorDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"stats_aggregator","type":20},{"name":"tag","type":7},{"name":"counter_prefix","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"Shape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns a 1-D integer tensor representing the shape of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\nshape(t) ==> [2, 2, 3]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the shape of a tensor."}},{"name":"ShapeN","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns N 1-D integer tensors representing shape of `input[i]s`.","inputs":[{"name":"input","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"output","numberAttr":"N","typeAttr":"out_type"}],"summary":"Returns shape of tensors."}},{"name":"ShardDataset","schema":{"attributes":[{"default":false,"name":"require_non_empty","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"An integer representing the number of shards operating in parallel.","name":"num_shards","type":9},{"description":"An integer representing the current worker index.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a `Dataset` that includes only 1/`num_shards` of this dataset."}},{"name":"ShardedFilename","schema":{"description":" %s-%05d-of-%05d, basename, shard, num_shards.","inputs":[{"name":"basename","type":7},{"name":"shard","type":3},{"name":"num_shards","type":3}],"outputs":[{"name":"filename","type":7}],"summary":"Generate a sharded filename. The filename is printf formatted as"}},{"name":"ShardedFilespec","schema":{"inputs":[{"name":"basename","type":7},{"name":"num_shards","type":3}],"outputs":[{"name":"filename","type":7}],"summary":"Generate a glob pattern matching all sharded file names."}},{"name":"ShuffleAndRepeatDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"reshuffle_each_iteration","type":"boolean"}],"description":"pseudorandomly.","inputs":[{"name":"input_dataset","type":21},{"description":"The number of output elements to buffer in an iterator over\nthis dataset. Compare with the `min_after_dequeue` attr when creating a\n`RandomShuffleQueue`.","name":"buffer_size","type":9},{"description":"A scalar seed for the random number generator. If either `seed` or\n`seed2` is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9},{"description":"A scalar representing the number of times the underlying dataset\nshould be repeated. The default is `-1`, which results in infinite repetition.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shuffles and repeats elements from `input_dataset`"}},{"name":"ShuffleAndRepeatDatasetV2","schema":{"attributes":[{"default":true,"name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"count","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShuffleDataset","schema":{"attributes":[{"default":true,"description":"If true, each iterator over this dataset will be given\na different pseudorandomly generated seed, based on a sequence seeded by the\n`seed` and `seed2` inputs. If false, each iterator will be given the same\nseed, and repeated iteration over this dataset will yield the exact same\nsequence of results.","name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"The number of output elements to buffer in an iterator over\nthis dataset. Compare with the `min_after_dequeue` attr when creating a\n`RandomShuffleQueue`.","name":"buffer_size","type":9},{"description":"A scalar seed for the random number generator. If either `seed` or\n`seed2` is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shuffles elements from `input_dataset` pseudorandomly."}},{"name":"ShuffleDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShuffleDatasetV3","schema":{"attributes":[{"default":true,"name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShutdownDistributedTPU","schema":{"description":"The op returns an error if no system is running.","summary":"Shuts down a running distributed TPU system."}},{"name":"Sigmoid","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"category":"Activation","description":"Specifically, `y = 1 / (1 + exp(-x))`.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes sigmoid of `x` element-wise."}},{"name":"SigmoidGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * y * (1 - y)`, where `y = sigmoid(x)`, and\n`dy` is the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient of the sigmoid of `x` wrt its input."}},{"name":"Sign","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"`y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`.\n\nFor complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`.\n\nExample usage:\n>>> tf.math.sign([0., 2., -3.])\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns an element-wise indication of the sign of a number."}},{"name":"Sin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes sine of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `[-1,1]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10, float(\"inf\")])\n tf.math.sin(x) ==> [nan -0.4121185 -0.47942555 0.84147096 0.9320391 -0.87329733 -0.54402107 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes sine of x element-wise."}},{"name":"Sinh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic sine of every\n element in the tensor. Input range is `[-inf,inf]` and output range\n is `[-inf,inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 2, 10, float(\"inf\")])\n tf.math.sinh(x) ==> [-inf -4.0515420e+03 -5.2109528e-01 1.1752012e+00 1.5094614e+00 3.6268604e+00 1.1013232e+04 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic sine of x element-wise."}},{"name":"Size","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns an integer representing the number of elements in\n`input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1,, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]\nsize(t) ==> 12\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the size of a tensor."}},{"name":"SkipDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements from the `input_dataset`\nthat should be skipped. If count is -1, skips everything.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that skips `count` elements from the `input_dataset`."}},{"name":"Skipgram","schema":{"attributes":[{"description":"The corpus's text file name.","name":"filename","type":"string"},{"description":"The size of produced batch.","name":"batch_size","type":"int64"},{"default":5,"description":"The number of words to predict to the left and right of the target.","name":"window_size","type":"int64"},{"default":5,"description":"The minimum number of word occurrences for it to be included in the\nvocabulary.","name":"min_count","type":"int64"},{"default":0.0010000000474974513,"description":"Threshold for word occurrence. Words that appear with higher\nfrequency will be randomly down-sampled. Set to 0 to disable.","name":"subsample","type":"float32"}],"outputs":[{"description":"A vector of words in the corpus.","name":"vocab_word","type":7},{"description":"Frequencies of words. Sorted in the non-ascending order.","name":"vocab_freq","type":3},{"description":"Number of words per epoch in the data file.","name":"words_per_epoch","type":9},{"description":"The current epoch number.","name":"current_epoch","type":3},{"description":"The total number of words processed so far.","name":"total_words_processed","type":9},{"description":"A vector of word ids.","name":"examples","type":3},{"description":"A vector of word ids.","name":"labels","type":3}],"summary":"Parses a text file and creates a batch of examples."}},{"name":"SleepDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"sleep_microseconds","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"Slice","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"}],"category":"Tensor","description":"The output tensor is a tensor with dimensions described by 'size'\nwhose values are extracted from 'input' starting at the offsets in\n'begin'.\n\n*Requirements*:\n 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n)","inputs":[{"name":"input","typeAttr":"T"},{"description":"begin[i] specifies the offset into the 'i'th dimension of\n'input' to slice from.","name":"begin","typeAttr":"Index"},{"description":"size[i] specifies the number of elements of the 'i'th dimension\nof 'input' to slice. If size[i] is -1, all remaining elements in dimension\ni are included in the slice (i.e. this is equivalent to setting\nsize[i] = input.dim_size(i) - begin[i]).","name":"size","typeAttr":"Index"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a slice from 'input'."}},{"name":"SlidingWindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements in the\nsliding window.","name":"window_size","type":9},{"description":"A scalar representing the steps moving the sliding window\nforward in one iteration. It must be positive.","name":"window_shift","type":9},{"description":"A scalar representing the stride of the input elements of the sliding window.\nIt must be positive.","name":"window_stride","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that passes a sliding window over `input_dataset`."}},{"name":"Snapshot","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns a copy of the input tensor."}},{"name":"SnapshotDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"compression","type":"string"},{"default":"","name":"reader_path_prefix","type":"string"},{"default":"","name":"writer_path_prefix","type":"string"},{"default":10737418240,"name":"shard_size_bytes","type":"int64"},{"default":86400,"name":"pending_snapshot_expiry_seconds","type":"int64"},{"default":1,"name":"num_reader_threads","type":"int64"},{"default":1,"name":"reader_buffer_size","type":"int64"},{"default":1,"name":"num_writer_threads","type":"int64"},{"default":1,"name":"writer_buffer_size","type":"int64"},{"default":false,"name":"shuffle_on_read","type":"boolean"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":"auto","name":"mode","type":"string"},{"default":"","name":"snapshot_name","type":"string"}],"description":"This dataset attempts to determine whether a valid snapshot exists at the\n`snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`.\nIf not, it will run the preprocessing pipeline as usual, and write out a\nsnapshot of the data processed for future use.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"The path we should write snapshots to / read snapshots from.","name":"path","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that will write to / read from a snapshot."}},{"name":"SnapshotDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","description":"The type of compression to be applied to the saved snapshot files.","name":"compression","type":"string"},{"description":"Optional. A function to control how to read data from snapshot shards.","name":"reader_func","type":"function"},{"description":"Optional. A function to control how to shard data when writing a snapshot.","name":"shard_func","type":"function"},{"minimum":0,"name":"Treader_func_args","type":"type[]"},{"minimum":0,"name":"Tshard_func_args","type":"type[]"}],"description":"This dataset attempts to determine whether a valid snapshot exists at the\n`snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`.\nIf not, it will run the preprocessing pipeline as usual, and write out a\nsnapshot of the data processed for future use.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"The path we should write snapshots to / read snapshots from.","name":"path","type":7},{"name":"reader_func_other_args","typeListAttr":"Treader_func_args"},{"name":"shard_func_other_args","typeListAttr":"Tshard_func_args"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that will write to / read from a snapshot."}},{"name":"SobolSample","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the sample. One of: `float32` or `float64`. Must be one of the following: `float32`, `float64`.","name":"dtype","type":"type"}],"description":"Creates a Sobol sequence with `num_results` samples. Each sample has dimension\n`dim`. Skips the first `skip` samples.","inputs":[{"description":"Positive scalar `Tensor` representing each sample's dimension.","name":"dim","type":3},{"description":"Positive scalar `Tensor` of dtype int32. The number of Sobol points to return\nin the output.","name":"num_results","type":3},{"description":"Positive scalar `Tensor` of dtype int32. The number of initial points of the\nSobol sequence to skip.","name":"skip","type":3}],"outputs":[{"description":"`Tensor` of samples from Sobol sequence with `shape` [num_results, dim].","name":"samples","typeAttr":"dtype"}],"summary":"Generates points from the Sobol sequence."}},{"name":"Softmax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","description":"For each batch `i` and class `j` we have\n\n $$softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))$$","inputs":[{"description":"2-D with shape `[batch_size, num_classes]`.","name":"logits","typeAttr":"T"}],"outputs":[{"description":"Same shape as `logits`.","name":"softmax","typeAttr":"T"}],"summary":"Computes softmax activations."}},{"name":"SoftmaxCrossEntropyWithLogits","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Inputs are the logits, not probabilities.","inputs":[{"description":"batch_size x num_classes matrix","name":"features","typeAttr":"T"},{"description":"batch_size x num_classes matrix\nThe caller must ensure that each batch of labels represents a valid\nprobability distribution.","name":"labels","typeAttr":"T"}],"outputs":[{"description":"Per example loss (batch_size vector).","name":"loss","typeAttr":"T"},{"description":"backpropagated gradients (batch_size x num_classes matrix).","name":"backprop","typeAttr":"T"}],"summary":"Computes softmax cross entropy cost and gradients to backpropagate."}},{"name":"Softplus","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes softplus: `log(exp(features) + 1)`."}},{"name":"SoftplusGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding softplus operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding softplus operation.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients / (1 + exp(-features))`.","name":"backprops","typeAttr":"T"}],"summary":"Computes softplus gradients for a softplus operation."}},{"name":"Softsign","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes softsign: `features / (abs(features) + 1)`."}},{"name":"SoftsignGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding softsign operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding softsign operation.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients / (1 + abs(features)) ** 2`.","name":"backprops","typeAttr":"T"}],"summary":"Computes softsign gradients for a softsign operation."}},{"name":"SpaceToBatch","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"minimum":2,"name":"block_size","type":"int64"}],"description":"This is a legacy version of the more general SpaceToBatchND.\n\nZero-pads and then rearranges (permutes) blocks of spatial data into batch.\nMore specifically, this op outputs a copy of the input tensor where values from\nthe `height` and `width` dimensions are moved to the `batch` dimension. After\nthe zero-padding, both `height` and `width` of the input must be divisible by the\nblock size.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`.","name":"input","typeAttr":"T"},{"description":"2-D tensor of non-negative integers with shape `[2, 2]`. It specifies\n the padding of the input with zeros across the spatial dimensions as follows:\n\n paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]\n\n The effective spatial dimensions of the zero-padded input tensor will be:\n\n height_pad = pad_top + height + pad_bottom\n width_pad = pad_left + width + pad_right\n\nThe attr `block_size` must be greater than one. It indicates the block size.\n\n * Non-overlapping blocks of size `block_size x block size` in the height and\n width dimensions are rearranged into the batch dimension at each location.\n * The batch of the output tensor is `batch * block_size * block_size`.\n * Both height_pad and width_pad must be divisible by block_size.\n\nThe shape of the output will be:\n\n [batch*block_size*block_size, height_pad/block_size, width_pad/block_size,\n depth]\n\nSome examples:\n\n(1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 1]` and value:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\n(2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 3]` and value:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[4, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\n(4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[8, 1, 2, 1]` and value:\n\n```\nx = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],\n [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]\n```\n\nAmong others, this operation is useful for reducing atrous convolution into\nregular convolution.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToBatch for 4-D tensors of type T."}},{"name":"SpaceToBatchND","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tblock_shape","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"description":"This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into a\ngrid of blocks of shape `block_shape`, and interleaves these blocks with the\n\"batch\" dimension (0) such that in the output, the spatial dimensions\n`[1, ..., M]` correspond to the position within the grid, and the batch\ndimension combines both the position within a spatial block and the original\nbatch position. Prior to division into blocks, the spatial dimensions of the\ninput are optionally zero padded according to `paddings`. See below for a\nprecise description.","inputs":[{"description":"N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`,\nwhere spatial_shape has `M` dimensions.","name":"input","typeAttr":"T"},{"description":"1-D with shape `[M]`, all values must be >= 1.","name":"block_shape","typeAttr":"Tblock_shape"},{"description":"2-D with shape `[M, 2]`, all values must be >= 0.\n `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension\n `i + 1`, which corresponds to spatial dimension `i`. It is required that\n `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`.\n\nThis operation is equivalent to the following steps:\n\n1. Zero-pad the start and end of dimensions `[1, ..., M]` of the\n input according to `paddings` to produce `padded` of shape `padded_shape`.\n\n2. Reshape `padded` to `reshaped_padded` of shape:\n\n [batch] +\n [padded_shape[1] / block_shape[0],\n block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1],\n block_shape[M-1]] +\n remaining_shape\n\n3. Permute dimensions of `reshaped_padded` to produce\n `permuted_reshaped_padded` of shape:\n\n block_shape +\n [batch] +\n [padded_shape[1] / block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1]] +\n remaining_shape\n\n4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch\n dimension, producing an output tensor of shape:\n\n [batch * prod(block_shape)] +\n [padded_shape[1] / block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1]] +\n remaining_shape\n\nSome examples:\n\n(1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 1]` and value:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\n(2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 3]` and value:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[4, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\n(4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and\n paddings = `[[0, 0], [2, 0]]`:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[8, 1, 3, 1]` and value:\n\n```\nx = [[[[0], [1], [3]]], [[[0], [9], [11]]],\n [[[0], [2], [4]]], [[[0], [10], [12]]],\n [[[0], [5], [7]]], [[[0], [13], [15]]],\n [[[0], [6], [8]]], [[[0], [14], [16]]]]\n```\n\nAmong others, this operation is useful for reducing atrous convolution into\nregular convolution.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToBatch for N-D tensors of type T."}},{"name":"SpaceToDepth","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The size of the spatial block.","minimum":2,"name":"block_size","type":"int64"},{"default":"NHWC","description":"Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"description":"Rearranges blocks of spatial data, into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the `height`\nand `width` dimensions are moved to the `depth` dimension.\nThe attr `block_size` indicates the input block size.\n\n * Non-overlapping blocks of size `block_size x block size` are rearranged\n into depth at each location.\n * The depth of the output tensor is `block_size * block_size * input_depth`.\n * The Y, X coordinates within each block of the input become the high order\n component of the output channel index.\n * The input tensor's height and width must be divisible by block_size.\n\nThe `data_format` attr specifies the layout of the input and output tensors\nwith the following options:\n \"NHWC\": `[ batch, height, width, channels ]`\n \"NCHW\": `[ batch, channels, height, width ]`\n \"NCHW_VECT_C\":\n `qint8 [ batch, channels / 4, height, width, 4 ]`\n\nIt is useful to consider the operation as transforming a 6-D Tensor.\ne.g. for data_format = NHWC,\n Each element in the input tensor can be specified via 6 coordinates,\n ordered by decreasing memory layout significance as:\n n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates\n within the output image, bX, bY means coordinates\n within the input block, iC means input channels).\n The output would be a transpose to the following layout:\n n,oY,oX,bY,bX,iC\n\nThis operation is useful for resizing the activations between convolutions\n(but keeping all data), e.g. instead of pooling. It is also useful for training\npurely convolutional models.\n\nFor example, given an input of shape `[1, 2, 2, 1]`, data_format = \"NHWC\" and\nblock_size = 2:\n\n```\nx = [[[[1], [2]],\n [[3], [4]]]]\n```\n\nThis operation will output a tensor of shape `[1, 1, 1, 4]`:\n\n```\n[[[[1, 2, 3, 4]]]]\n```\n\nHere, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`,\nthe corresponding output will have a single element (i.e. width and height are\nboth 1) and will have a depth of 4 channels (1 * block_size * block_size).\nThe output element shape is `[1, 1, 4]`.\n\nFor an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g.\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThis operation, for block_size of 2, will return the following tensor of shape\n`[1, 1, 1, 12]`\n\n```\n[[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]\n```\n\nSimilarly, for the following input of shape `[1 4 4 1]`, and a block size of 2:\n\n```\nx = [[[[1], [2], [5], [6]],\n [[3], [4], [7], [8]],\n [[9], [10], [13], [14]],\n [[11], [12], [15], [16]]]]\n```\n\nthe operator will return the following tensor of shape `[1 2 2 4]`:\n\n```\nx = [[[[1, 2, 3, 4],\n [5, 6, 7, 8]],\n [[9, 10, 11, 12],\n [13, 14, 15, 16]]]]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToDepth for tensors of type T."}},{"name":"SparseAccumulatorApplyGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Boolean indicating whether gradient_shape is unknown, in which\ncase the input is ignored during validation.","name":"has_known_shape","type":"boolean"}],"description":"Does not add if local_step is smaller than the accumulator's\nglobal_step.","inputs":[{"description":"The handle to a accumulator.","isRef":true,"name":"handle","type":7},{"description":"The local_step value at which the sparse gradient was computed.","name":"local_step","type":9},{"description":"Indices of the sparse gradient to be accumulated. Must be a\nvector.","name":"gradient_indices","type":9},{"description":"Values are the non-zero slices of the gradient, and must have\nthe same first dimension as indices, i.e., the nnz represented by indices and\nvalues must be consistent.","name":"gradient_values","typeAttr":"dtype"},{"description":"Shape of the sparse gradient to be accumulated.","name":"gradient_shape","type":9}],"summary":"Applies a sparse gradient to a given accumulator."}},{"name":"SparseAccumulatorTakeGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"The op will blocks until sufficient (i.e., more than num_required)\ngradients have been accumulated. If the accumulator has already\naggregated more than num_required gradients, it will return its\naverage of the accumulated gradients. Also automatically increments\nthe recorded global_step in the accumulator by 1, and resets the\naggregate to 0.","inputs":[{"description":"The handle to a SparseConditionalAccumulator.","isRef":true,"name":"handle","type":7},{"description":"Number of gradients required before we return an aggregate.","name":"num_required","type":3}],"outputs":[{"description":"Indices of the average of the accumulated sparse gradients.","name":"indices","type":9},{"description":"Values of the average of the accumulated sparse gradients.","name":"values","typeAttr":"dtype"},{"description":"Shape of the average of the accumulated sparse gradients.","name":"shape","type":9}],"summary":"Extracts the average sparse gradient in a SparseConditionalAccumulator."}},{"name":"SparseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"Treal","type":"type"}],"description":"The input `SparseTensor` objects' indices are assumed ordered in standard\nlexicographic order. If this is not the case, before this step run\n`SparseReorder` to restore index ordering.\n\nBy default, if two values sum to zero at some index, the output `SparseTensor`\nwould still include that particular location in its index, storing a zero in the\ncorresponding value slot. To override this, callers can specify `thresh`,\nindicating that if the sum has a magnitude strictly smaller than `thresh`, its\ncorresponding value and index would then not be included. In particular,\n`thresh == 0` (default) means everything is kept and actual thresholding happens\nonly for a positive value.\n\nIn the following shapes, `nnz` is the count after taking `thresh` into account.","inputs":[{"description":"2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix.","name":"a_indices","type":9},{"description":"1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector.","name":"a_shape","type":9},{"description":"2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix.","name":"b_indices","type":9},{"description":"1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector.","name":"b_values","typeAttr":"T"},{"description":"1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector.","name":"b_shape","type":9},{"description":"0-D. The magnitude threshold that determines if an output value/index\npair takes space.","name":"thresh","typeAttr":"Treal"}],"outputs":[{"name":"sum_indices","type":9},{"name":"sum_values","typeAttr":"T"},{"name":"sum_shape","type":9}],"summary":"Adds two `SparseTensor` objects to produce another `SparseTensor`."}},{"name":"SparseAddGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The SparseAdd op calculates A + B, where A, B, and the sum are all represented\nas `SparseTensor` objects. This op takes in the upstream gradient w.r.t.\nnon-empty values of the sum, and outputs the gradients w.r.t. the non-empty\nvalues of A and B.","inputs":[{"description":"1-D with shape `[nnz(sum)]`. The gradient with respect to\nthe non-empty values of the sum.","name":"backprop_val_grad","typeAttr":"T"},{"description":"2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`.","name":"a_indices","type":9},{"description":"2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`.","name":"b_indices","type":9},{"description":"2-D. The `indices` of the sum `SparseTensor`, size\n`[nnz(sum), ndims]`.","name":"sum_indices","type":9}],"outputs":[{"description":"1-D with shape `[nnz(A)]`. The gradient with respect to the\nnon-empty values of A.","name":"a_val_grad","typeAttr":"T"},{"description":"1-D with shape `[nnz(B)]`. The gradient with respect to the\nnon-empty values of B.","name":"b_val_grad","typeAttr":"T"}],"summary":"The gradient operator for the SparseAdd op."}},{"name":"SparseApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":": Should be from a Variable().","isRef":true,"name":"accum_update","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"var: Should be from a Variable()."}},{"name":"SparseApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$var -= lr * grad * (1 / sqrt(accum))$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"SparseApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_accumulator","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_squared_accumulator","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update entries in '*var' and '*accum' according to the proximal adagrad scheme."}},{"name":"SparseApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$var -= lr * grad * (1 / sqrt(accum))$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"SparseApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\n$$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$\n$$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$\n$$var <- var - mom$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mg","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"SparseApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\n$$accum_new = accum + grad * grad$$\n$$linear += grad + (accum_{new}^{-lr_{power}} - accum^{-lr_{power}} / lr * var$$\n$$quadratic = 1.0 / (accum_{new}^{lr_{power}} * lr) + 2 * l2$$\n$$var = (sign(linear) * l1 - linear) / quadratic\\ if\\ |linear| > l1\\ else\\ 0.0$$\n$$accum = accum_{new}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"SparseApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\ngrad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad * grad\nlinear += grad_with_shrinkage -\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"SparseApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\n$$accum = accum * momentum + grad$$\n$$var -= lr * accum$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"SparseApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$prox_v = var$$\n$$prox_v -= lr * grad * (1 / sqrt(accum))$$\n$$var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Sparse update entries in '*var' and '*accum' according to FOBOS algorithm."}},{"name":"SparseApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var as follows:\n$$prox_v = var - alpha * grad$$\n$$var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Sparse update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"SparseApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\n$$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$\n$$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$\n$$var <- var - mom$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"SparseBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"2D int64 `Tensor`.","name":"indices","type":9},{"description":"1D int `Tensor`.","name":"values","typeAttr":"Tidx"},{"description":"1D int64 `Tensor`.","name":"dense_shape","type":9},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `input`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"SparseConcat","schema":{"attributes":[{"description":"Dimension to concatenate along. Must be in range [-rank, rank),\nwhere rank is the number of dimensions in each input `SparseTensor`.","name":"concat_dim","type":"int64"},{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Concatenation is with respect to the dense versions of these sparse tensors.\nIt is assumed that each input is a `SparseTensor` whose elements are ordered\nalong increasing dimension number.\n\nAll inputs' shapes must match, except for the concat dimension. The\n`indices`, `values`, and `shapes` lists must have the same length.\n\nThe output shape is identical to the inputs', except along the concat\ndimension, where it is the sum of the inputs' sizes along that dimension.\n\nThe output elements will be resorted to preserve the sort order along\nincreasing dimension number.\n\nThis op runs in `O(M log M)` time, where `M` is the total number of non-empty\nvalues across all inputs. This is due to the need for an internal sort in\norder to concatenate efficiently across an arbitrary dimension.\n\nFor example, if `concat_dim = 1` and the inputs are\n\n sp_inputs[0]: shape = [2, 3]\n [0, 2]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n sp_inputs[1]: shape = [2, 4]\n [0, 1]: \"d\"\n [0, 2]: \"e\"\n\nthen the output will be\n\n shape = [2, 7]\n [0, 2]: \"a\"\n [0, 4]: \"d\"\n [0, 5]: \"e\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\nGraphically this is equivalent to doing\n\n [ a] concat [ d e ] = [ a d e ]\n [b c ] [ ] [b c ]","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. Non-empty values of each `SparseTensor`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated `SparseTensor`.","name":"output_values","typeAttr":"T"},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Concatenates a list of `SparseTensor` along the specified dimension."}},{"name":"SparseConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.","outputs":[{"description":"The handle to the accumulator.","isRef":true,"name":"handle","type":7}],"summary":"A conditional accumulator for aggregating sparse gradients."}},{"name":"SparseCountSparseOutput","schema":{"attributes":[{"description":"Dtype of the input values tensor. Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing the indices of the sparse tensor to count.","name":"indices","type":9},{"description":"Tensor containing values of the sparse tensor to count.","name":"values","typeAttr":"T"},{"description":"Tensor containing the dense shape of the sparse tensor to count.","name":"dense_shape","type":9},{"description":"A Tensor of the same shape as indices containing per-index weight values.\nMay also be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.","name":"output_dense_shape","type":9}],"summary":"Performs sparse-output bin counting for a sparse tensor input."}},{"name":"SparseCross","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"If true, returns the hash of the cross instead of the string.\nThis will allow us avoiding string manipulations.","name":"hashed_output","type":"boolean"},{"description":"It is used if hashed_output is true.\noutput = hashed_value%num_buckets if num_buckets > 0 else hashed_value.","minimum":0,"name":"num_buckets","type":"int64"},{"description":"Specify the hash_key that will be used by the `FingerprintCat64`\nfunction to combine the crosses fingerprints.","name":"hash_key","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","name":"out_type","type":"type"},{"description":"Must be one of the following: `int64`, `string`.","name":"internal_type","type":"type"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","typeAttr":"out_type"},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseCrossHashed","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"},{"description":"It is used if hashed_output is true.\noutput = hashed_value%num_buckets if num_buckets > 0 else hashed_value.","name":"num_buckets","type":9},{"description":"boolean, if true, siphash with salt will be used instead of farmhash.","name":"strong_hash","type":10},{"description":"Specify the salt that will be used by the siphash function.","name":"salt","type":9}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","type":9},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseCrossV2","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"},{"description":"string used when joining a list of string inputs, can be used as separator later.","name":"sep","type":7}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","type":7},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseDenseCwiseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"(1) Broadcasts the dense side to have the same shape as the sparse side, if\n eligible;\n(2) Then, only the dense values pointed to by the indices of the SparseTensor\n participate in the cwise addition.\n\nBy these rules, the result is a logical SparseTensor with exactly the same\nindices and shape, but possibly with different non-zero values. The output of\nthis Op is the resultant non-zero values.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Adds up a SparseTensor and a dense Tensor, using these special rules:"}},{"name":"SparseDenseCwiseDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*Limitation*: this Op only broadcasts the dense side to the sparse side, but not\nthe other direction.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Component-wise divides a SparseTensor by a dense Tensor."}},{"name":"SparseDenseCwiseMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The output locations corresponding to the implicitly zero elements in the sparse\ntensor will be zero (i.e., will not take up storage space), regardless of the\ncontents of the dense tensor (even if it's +/-INF and that INF*0 == NaN).\n\n*Limitation*: this Op only broadcasts the dense side to the sparse side, but not\nthe other direction.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Component-wise multiplies a SparseTensor by a dense Tensor."}},{"name":"SparseFillEmptyRows","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The input `SparseTensor` is represented via the tuple of inputs\n(`indices`, `values`, `dense_shape`). The output `SparseTensor` has the\nsame `dense_shape` but with indices `output_indices` and values\n`output_values`.\n\nThis op inserts a single entry for every row that doesn't have any values.\nThe index is created as `[row, 0, ..., 0]` and the inserted value\nis `default_value`.\n\nFor example, suppose `sp_input` has shape `[5, 6]` and non-empty values:\n\n [0, 1]: a\n [0, 3]: b\n [2, 0]: c\n [3, 1]: d\n\nRows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values:\n\n [0, 1]: a\n [0, 3]: b\n [1, 0]: default_value\n [2, 0]: c\n [3, 1]: d\n [4, 0]: default_value\n\nThe output `SparseTensor` will be in row-major order and will have the\nsame shape as the input.\n\nThis op also returns an indicator vector shaped `[dense_shape[0]]` such that\n\n empty_row_indicator[i] = True iff row i was an empty row.\n\nAnd a reverse index map vector shaped `[indices.shape[0]]` that is used during\nbackpropagation,\n\n reverse_index_map[j] = out_j s.t. indices[j, :] == output_indices[out_j, :]","inputs":[{"description":"2-D. the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D. the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. the shape of the sparse tensor.","name":"dense_shape","type":9},{"description":"0-D. default value to insert into location `[row, 0, ..., 0]`\n for rows missing from the input sparse tensor.\noutput indices: 2-D. the indices of the filled sparse tensor.","name":"default_value","typeAttr":"T"}],"outputs":[{"name":"output_indices","type":9},{"description":"1-D. the values of the filled sparse tensor.","name":"output_values","typeAttr":"T"},{"description":"1-D. whether the dense row was missing in the\ninput sparse tensor.","name":"empty_row_indicator","type":10},{"description":"1-D. a map from the input indices to the output indices.","name":"reverse_index_map","type":9}],"summary":"Fills empty rows in the input 2-D `SparseTensor` with a default value."}},{"name":"SparseFillEmptyRowsGrad","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Takes vectors reverse_index_map, shaped `[N]`, and grad_values,\nshaped `[N_full]`, where `N_full >= N` and copies data into either\n`d_values` or `d_default_value`. Here `d_values` is shaped `[N]` and\n`d_default_value` is a scalar.\n\n d_values[j] = grad_values[reverse_index_map[j]]\n d_default_value = sum_{k : 0 .. N_full - 1} (\n grad_values[k] * 1{k not in reverse_index_map})","inputs":[{"description":"1-D. The reverse index map from SparseFillEmptyRows.","name":"reverse_index_map","type":9},{"description":"1-D. The gradients from backprop.","name":"grad_values","typeAttr":"T"}],"outputs":[{"description":"1-D. The backprop into values.","name":"d_values","typeAttr":"T"},{"description":"0-D. The backprop into default_value.","name":"d_default_value","typeAttr":"T"}],"summary":"The gradient of SparseFillEmptyRows."}},{"name":"SparseMatMul","schema":{"attributes":[{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":false,"name":"a_is_sparse","type":"boolean"},{"default":false,"name":"b_is_sparse","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `bfloat16`.","name":"Ta","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `bfloat16`.","name":"Tb","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of \"a\" must\nmatch the outer dimension of \"b\". Both \"a\" and \"b\" must be `Tensor`s not\n`SparseTensor`s. This op is optimized for the case where at least one of \"a\" or\n\"b\" is sparse, in the sense that they have a large proportion of zero values.\nThe breakeven for using this versus a dense matrix multiply on one platform was\n30% zero values in the sparse matrix.\n\nThe gradient computation of this operation will only take advantage of sparsity\nin the input gradient when that gradient comes from a Relu.","inputs":[{"name":"a","typeAttr":"Ta"},{"name":"b","typeAttr":"Tb"}],"outputs":[{"name":"product","type":1}],"summary":"Multiply matrix \"a\" by matrix \"b\"."}},{"name":"SparseMatrixAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The gradients of SparseMatrixAdd outputs with respect to alpha and beta are not\ncurrently defined (TensorFlow will return zeros for these entries).","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A CSRSparseMatrix.","name":"b","type":21},{"description":"A constant scalar.","name":"alpha","typeAttr":"T"},{"description":"A constant scalar.","name":"beta","typeAttr":"T"}],"outputs":[{"description":"A CSRSparseMatrix.","name":"c","type":21}],"summary":"Sparse addition of two CSR matrices, C = alpha * A + beta * B."}},{"name":"SparseMatrixMatMul","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"description":"Indicates whether `a` should be transposed.","name":"transpose_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be transposed.","name":"transpose_b","type":"boolean"},{"default":false,"description":"Indicates whether `a` should be conjugate-transposed.","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be conjugate-transposed.","name":"adjoint_b","type":"boolean"},{"default":false,"description":"Transposes the product of `a` and `b`.","name":"transpose_output","type":"boolean"},{"default":false,"description":"Conjugates the product of `a` and `b`.","name":"conjugate_output","type":"boolean"}],"description":"Returns a dense matrix.\nFor inputs A and B, where A is CSR and B is dense; this op returns a dense C;\n\nIf transpose_output is false, returns:\n```\n C = A . B\n```\n\nIf transpose_output is `true`, returns:\n```\n C = transpose(A . B) = transpose(B) . transpose(A)\n```\nwhere the transposition is performed along the two innermost (matrix)\ndimensions.\n\nIf conjugate_output is `true`, returns:\n```\n C = conjugate(A . B) = conjugate(A) . conjugate(B)\n```\n\nIf both conjugate_output and transpose_output are `true`, returns:\n```\n C = conjugate(transpose(A . B)) = conjugate(transpose(B)) .\n conjugate(transpose(A))\n```","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A dense tensor.","name":"b","typeAttr":"T"}],"outputs":[{"description":"A dense output tensor.","name":"output","typeAttr":"T"}],"summary":"Matrix-multiplies a sparse matrix with a dense matrix."}},{"name":"SparseMatrixMul","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a sparse matrix.\n\nThe dense tensor `b` may be either a scalar; otherwise `a` must be a rank-3\n`SparseMatrix`; in this case `b` must be shaped `[batch_size, 1, 1]` and the\nmultiply operation broadcasts.\n\n**NOTE** even if `b` is zero, the sparsity structure of the output does not\nchange.","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A dense tensor.","name":"b","typeAttr":"T"}],"outputs":[{"description":"A dense output tensor.","name":"output","type":21}],"summary":"Element-wise multiplication of a sparse matrix with a dense tensor."}},{"name":"SparseMatrixNNZ","schema":{"inputs":[{"description":"A CSRSparseMatrix.","name":"sparse_matrix","type":21}],"outputs":[{"description":"The number of nonzeroes of `sparse_matrix`.","name":"nnz","type":3}],"summary":"Returns the number of nonzeroes of `sparse_matrix`."}},{"name":"SparseMatrixOrderingAMD","schema":{"description":"Computes the Approximate Minimum Degree (AMD) ordering for a sparse matrix.\n\nThe returned permutation may be used to permute the rows and columns of the\ngiven sparse matrix. This typically results in permuted sparse matrix's sparse\nCholesky (or other decompositions) in having fewer zero fill-in compared to\ndecomposition of the original matrix.\n\nThe input sparse matrix may have rank 2 or rank 3. The output Tensor,\nrepresenting would then have rank 1 or 2 respectively, with the same batch\nshape as the input.\n\nEach component of the input sparse matrix must represent a square symmetric\nmatrix; only the lower triangular part of the matrix is read. The values of the\nsparse matrix does not affect the returned permutation, only the sparsity\npattern of the sparse matrix is used. Hence, a single AMD ordering may be\nreused for the Cholesky decompositions of sparse matrices with the same sparsity\npattern but with possibly different values.\n\nEach batch component of the output permutation represents a permutation of `N`\nelements, where the input sparse matrix components each have `N` rows. That is,\nthe component contains each of the integers `{0, .. N-1}` exactly once. The\n`i`th element represents the row index that the `i`th row maps to.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]])\n a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32)\n a_dense_shape = [4, 4]\n\n with tf.Session() as sess:\n # Define (COO format) SparseTensor over Numpy array.\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix.\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n\n # Obtain the AMD Ordering for the CSR SparseMatrix.\n ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix)\n\n ordering_amd_value = sess.run(ordering_amd)\n```\n\n`ordering_amd_value` stores the AMD ordering: `[1 2 3 0]`.\n\ninput: A `CSRSparseMatrix`.","inputs":[{"description":"A `CSRSparseMatrix`.","name":"input","type":21}],"outputs":[{"description":"The Approximate Minimum Degree (AMD) ordering of `input`.","name":"output","type":3}],"summary":"Computes the Approximate Minimum Degree (AMD) ordering of `input`."}},{"name":"SparseMatrixSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"type","type":"type"}],"description":"Calculate the softmax of the innermost dimensions of a SparseMatrix.\n\nMissing values are treated as `-inf` (i.e., logits of zero probability); and\nthe output has the same sparsity structure as the input (though missing values\nin the output may now be treated as having probability zero).","inputs":[{"description":"A CSRSparseMatrix.","name":"logits","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"softmax","type":21}],"summary":"Calculates the softmax of a CSRSparseMatrix."}},{"name":"SparseMatrixSoftmaxGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"type","type":"type"}],"inputs":[{"description":"A CSRSparseMatrix.","name":"softmax","type":21},{"description":"The gradient of `softmax`.","name":"grad_softmax","type":21}],"outputs":[{"description":"The output gradient.","name":"gradient","type":21}],"summary":"Calculates the gradient of the SparseMatrixSoftmax op."}},{"name":"SparseMatrixSparseCholesky","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"Computes the Sparse Cholesky decomposition of a sparse matrix, with the given\nfill-in reducing permutation.\n\nThe input sparse matrix and the fill-in reducing permutation `permutation` must\nhave compatible shapes. If the sparse matrix has rank 3; with the batch\ndimension `B`, then the `permutation` must be of rank 2; with the same batch\ndimension `B`. There is no support for broadcasting.\n\nFurthermore, each component vector of `permutation` must be of length `N`,\ncontaining each of the integers {0, 1, ..., N - 1} exactly once, where `N` is\nthe number of rows of each component of the sparse matrix.\n\nEach component of the input sparse matrix must represent a symmetric positive\ndefinite (SPD) matrix; although only the lower triangular part of the matrix is\nread. If any individual component is not SPD, then an InvalidArgument error is\nthrown.\n\nThe returned sparse matrix has the same dense shape as the input sparse matrix.\nFor each component `A` of the input sparse matrix, the corresponding output\nsparse matrix represents `L`, the lower triangular Cholesky factor satisfying\nthe following identity:\n\n```\n A = L * Lt\n```\n\nwhere Lt denotes the transpose of L (or its conjugate transpose, if `type` is\n`complex64` or `complex128`).\n\nThe `type` parameter denotes the type of the matrix elements. The supported\ntypes are: `float32`, `float64`, `complex64` and `complex128`.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]])\n a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32)\n a_dense_shape = [4, 4]\n\n with tf.Session() as sess:\n # Define (COO format) SparseTensor over Numpy array.\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix.\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n\n # Obtain the Sparse Cholesky factor using AMD Ordering for reducing zero\n # fill-in (number of structural non-zeros in the sparse Cholesky factor).\n ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix)\n cholesky_sparse_matrices = (\n sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(\n sparse_matrix, ordering_amd, type=tf.float32))\n\n # Convert the CSRSparseMatrix Cholesky factor to a dense Tensor\n dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n cholesky_sparse_matrices, tf.float32)\n\n # Evaluate the dense Tensor value.\n dense_cholesky_value = sess.run(dense_cholesky)\n```\n\n`dense_cholesky_value` stores the dense Cholesky factor:\n\n```\n [[ 1. 0. 0. 0.]\n [ 0. 1.41 0. 0.]\n [ 0. 0.70 1.58 0.]\n [ 0. 0. 0. 2.]]\n```\n\n\ninput: A `CSRSparseMatrix`.\npermutation: A `Tensor`.\ntype: The type of `input`.","inputs":[{"description":"A `CSRSparseMatrix`.","name":"input","type":21},{"description":"A fill-in reducing permutation matrix.","name":"permutation","type":3}],"outputs":[{"description":"The sparse Cholesky decompsition of `input`.","name":"output","type":21}],"summary":"Computes the sparse Cholesky decomposition of `input`."}},{"name":"SparseMatrixSparseMatMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"},{"default":false,"description":"Indicates whether `a` should be transposed.","name":"transpose_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be transposed.","name":"transpose_b","type":"boolean"},{"default":false,"description":"Indicates whether `a` should be conjugate-transposed.","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be conjugate-transposed.","name":"adjoint_b","type":"boolean"}],"description":"Performs a matrix multiplication of a sparse matrix `a` with a sparse matrix\n`b`; returns a sparse matrix `a * b`, unless either `a` or `b` is transposed or\nadjointed.\n\nEach matrix may be transposed or adjointed (conjugated and transposed)\naccording to the Boolean parameters `transpose_a`, `adjoint_a`, `transpose_b`\nand `adjoint_b`. At most one of `transpose_a` or `adjoint_a` may be True.\nSimilarly, at most one of `transpose_b` or `adjoint_b` may be True.\n\nThe inputs must have compatible shapes. That is, the inner dimension of `a`\nmust be equal to the outer dimension of `b`. This requirement is adjusted\naccording to whether either `a` or `b` is transposed or adjointed.\n\nThe `type` parameter denotes the type of the matrix elements. Both `a` and `b`\nmust have the same type. The supported types are: `float32`, `float64`,\n`complex64` and `complex128`.\n\nBoth `a` and `b` must have the same rank. Broadcasting is not supported. If they\nhave rank 3, each batch of 2D CSRSparseMatrices within `a` and `b` must have the\nsame dense shape.\n\nThe sparse matrix product may have numeric (non-structural) zeros.\nTODO(anudhyan): Consider adding a boolean attribute to control whether to prune\nzeros.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])\n a_values = np.array([1.0, 5.0, -1.0, -2.0], np.float32)\n a_dense_shape = [4, 5]\n\n b_indices = np.array([[0, 0], [3, 0], [3, 1]])\n b_values = np.array([2.0, 7.0, 8.0], np.float32)\n b_dense_shape = [5, 3]\n\n with tf.Session() as sess:\n # Define (COO format) Sparse Tensors over Numpy arrays\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n b_st = tf.sparse.SparseTensor(b_indices, b_values, b_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n b_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n b_st.indices, b_st.values, b_st.dense_shape)\n\n # Compute the CSR SparseMatrix matrix multiplication\n c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(\n a=a_sm, b=b_sm, type=tf.float32)\n\n # Convert the CSR SparseMatrix product to a dense Tensor\n c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n c_sm, tf.float32)\n # Evaluate the dense Tensor value\n c_sm_dense_value = sess.run(c_sm_dense)\n```\n\n`c_sm_dense_value` stores the dense matrix product:\n\n```\n [[ 2. 0. 0.]\n [ 0. 0. 0.]\n [ 35. 40. 0.]\n [ -4. 0. 0.]]\n```\n\na: A `CSRSparseMatrix`.\nb: A `CSRSparseMatrix` with the same type and rank as `a`.\ntype: The type of both `a` and `b`.\ntranspose_a: If True, `a` transposed before multiplication.\ntranspose_b: If True, `b` transposed before multiplication.\nadjoint_a: If True, `a` adjointed before multiplication.\nadjoint_b: If True, `b` adjointed before multiplication.","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A CSRSparseMatrix.","name":"b","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"c","type":21}],"summary":"Sparse-matrix-multiplies two CSR matrices `a` and `b`."}},{"name":"SparseMatrixTranspose","schema":{"attributes":[{"default":false,"description":"Indicates whether `input` should be conjugated.","name":"conjugate","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"Transposes the inner (matrix) dimensions of a SparseMatrix and optionally\nconjugates its values.","inputs":[{"description":"A CSRSparseMatrix.","name":"input","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"output","type":21}],"summary":"Transposes the inner (matrix) dimensions of a CSRSparseMatrix."}},{"name":"SparseMatrixZeros","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"The desired matrix shape.","name":"dense_shape","type":9}],"outputs":[{"description":"An empty CSR matrix with shape `dense_shape`.","name":"sparse_matrix","type":21}],"summary":"Creates an all-zeros CSRSparseMatrix with shape `dense_shape`."}},{"name":"SparseReduceMax","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_max()`. In particular, this Op also returns a dense `Tensor`\ninstead of a sparse one.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"description":"`R-K`-D. The reduced Tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the max of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceMaxSparse","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_max()`. In contrast to SparseReduceMax, this Op returns a\nSparseTensor.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"name":"output_indices","type":9},{"name":"output_values","typeAttr":"T"},{"name":"output_shape","type":9}],"summary":"Computes the max of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceSum","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor`\ninstead of a sparse one.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"description":"`R-K`-D. The reduced Tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the sum of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceSumSparse","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a\nSparseTensor.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"name":"output_indices","type":9},{"name":"output_values","typeAttr":"T"},{"name":"output_shape","type":9}],"summary":"Computes the sum of elements across dimensions of a SparseTensor."}},{"name":"SparseReorder","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Note that by convention, all sparse ops preserve the canonical ordering along\nincreasing dimension number. The only time ordering can be violated is during\nmanual manipulation of the indices and values vectors to add entries.\n\nReordering does not affect the shape of the SparseTensor.\n\nIf the tensor has rank `R` and `N` non-empty values, `input_indices` has\nshape `[N, R]`, input_values has length `N`, and input_shape has length `R`.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9}],"outputs":[{"description":"2-D. `N x R` matrix with the same indices as input_indices, but\nin canonical row-major ordering.","name":"output_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `output_indices`.","name":"output_values","typeAttr":"T"}],"summary":"Reorders a SparseTensor into the canonical, row-major ordering."}},{"name":"SparseReshape","schema":{"description":"This operation has the same semantics as reshape on the represented dense\ntensor. The `input_indices` are recomputed based on the requested `new_shape`.\n\nIf one component of `new_shape` is the special value -1, the size of that\ndimension is computed so that the total dense size remains constant. At\nmost one component of `new_shape` can be -1. The number of dense elements\nimplied by `new_shape` must be the same as the number of dense elements\noriginally implied by `input_shape`.\n\nReshaping does not affect the order of values in the SparseTensor.\n\nIf the input tensor has rank `R_in` and `N` non-empty values, and `new_shape`\nhas length `R_out`, then `input_indices` has shape `[N, R_in]`,\n`input_shape` has length `R_in`, `output_indices` has shape `[N, R_out]`, and\n`output_shape` has length `R_out`.","inputs":[{"description":"2-D. `N x R_in` matrix with the indices of non-empty values in a\nSparseTensor.","name":"input_indices","type":9},{"description":"1-D. `R_in` vector with the input SparseTensor's dense shape.","name":"input_shape","type":9},{"description":"1-D. `R_out` vector with the requested new dense shape.","name":"new_shape","type":9}],"outputs":[{"description":"2-D. `N x R_out` matrix with the updated indices of non-empty\nvalues in the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. `R_out` vector with the full dense shape of the output\nSparseTensor. This is the same as `new_shape` but with any -1 dimensions\nfilled in.","name":"output_shape","type":9}],"summary":"Reshapes a SparseTensor to represent values in a new dense shape."}},{"name":"SparseSegmentMean","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"See `tf.sparse.segment_sum` for usage examples.\n\nLike `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\ndimension, selecting a subset of dimension 0, specified by `indices`.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along sparse segments of a tensor."}},{"name":"SparseSegmentMeanGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Returns tensor \"output\" with same shape as grad, except for dimension 0 whose\nvalue is output_dim0.","inputs":[{"description":"gradient propagated to the SparseSegmentMean op.","name":"grad","typeAttr":"T"},{"description":"indices passed to the corresponding SparseSegmentMean op.","name":"indices","typeAttr":"Tidx"},{"description":"segment_ids passed to the corresponding SparseSegmentMean op.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"dimension 0 of \"data\" passed to SparseSegmentMean op.","name":"output_dim0","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients for SparseSegmentMean."}},{"name":"SparseSegmentMeanWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along sparse segments of a tensor."}},{"name":"SparseSegmentSqrtN","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"N is the size of the segment being reduced.\n\nSee `tf.sparse.segment_sum` for usage examples.\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor divided by the sqrt of N."}},{"name":"SparseSegmentSqrtNGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Returns tensor \"output\" with same shape as grad, except for dimension 0 whose\nvalue is output_dim0.","inputs":[{"description":"gradient propagated to the SparseSegmentSqrtN op.","name":"grad","typeAttr":"T"},{"description":"indices passed to the corresponding SparseSegmentSqrtN op.","name":"indices","typeAttr":"Tidx"},{"description":"segment_ids passed to the corresponding SparseSegmentSqrtN op.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"dimension 0 of \"data\" passed to SparseSegmentSqrtN op.","name":"output_dim0","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients for SparseSegmentSqrtN."}},{"name":"SparseSegmentSqrtNWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"N is the size of the segment being reduced.\n\nLike `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor divided by the sqrt of N."}},{"name":"SparseSegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nLike `SegmentSum`, but `segment_ids` can have rank less than `data`'s first\ndimension, selecting a subset of dimension 0, specified by `indices`.\n\nFor example:\n\n```python\nc = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\n# Select two rows, one segment.\ntf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))\n# => [[0 0 0 0]]\n\n# Select two rows, two segment.\ntf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))\n# => [[ 1 2 3 4]\n# [-1 -2 -3 -4]]\n\n# Select all rows, two segments.\ntf.sparse_segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))\n# => [[0 0 0 0]\n# [5 6 7 8]]\n\n# Which is equivalent to:\ntf.segment_sum(c, tf.constant([0, 0, 1]))\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor."}},{"name":"SparseSegmentSumWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/sparse#Segmentation)\nfor an explanation of segments.\n\nFor example:\n\n```python\nc = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\ntf.sparse_segment_sum_with_num_segments(\n c, tf.constant([0, 1]), tf.constant([0, 0]), num_segments=3)\n# => [[0 0 0 0]\n# [0 0 0 0]\n# [0 0 0 0]]\n\ntf.sparse_segment_sum_with_num_segments(c,\n tf.constant([0, 1]),\n tf.constant([0, 2],\n num_segments=4))\n# => [[ 1 2 3 4]\n# [ 0 0 0 0]\n# [-1 -2 -3 -4]\n# [ 0 0 0 0]]\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor."}},{"name":"SparseSlice","schema":{"attributes":[{"name":"T","type":"type"}],"description":"For example, if the input is\n\n input_tensor = shape = [2, 7]\n [ a d e ]\n [b c ]\n\nGraphically the output tensors are:\n\n sparse_slice([0, 0], [2, 4]) = shape = [2, 4]\n [ a ]\n [b c ]\n\n sparse_slice([0, 4], [2, 3]) = shape = [2, 3]\n [ d e ]\n [ ]","inputs":[{"description":"2-D tensor represents the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D tensor represents the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. tensor represents the shape of the sparse tensor.","name":"shape","type":9},{"description":"1-D. tensor represents the start of the slice.","name":"start","type":9},{"description":"1-D. tensor represents the size of the slice.\noutput indices: A list of 1-D tensors represents the indices of the output\nsparse tensors.","name":"size","type":9}],"outputs":[{"name":"output_indices","type":9},{"description":"A list of 1-D tensors represents the values of the output sparse\ntensors.","name":"output_values","typeAttr":"T"},{"description":"A list of 1-D tensors represents the shape of the output sparse\ntensors.","name":"output_shape","type":9}],"summary":"Slice a `SparseTensor` based on the `start` and `size`."}},{"name":"SparseSliceGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This op takes in the upstream gradient w.r.t. non-empty values of\nthe sliced `SparseTensor`, and outputs the gradients w.r.t.\nthe non-empty values of input `SparseTensor`.","inputs":[{"description":"1-D. The gradient with respect to\nthe non-empty values of the sliced `SparseTensor`.","name":"backprop_val_grad","typeAttr":"T"},{"description":"2-D. The `indices` of the input `SparseTensor`.","name":"input_indices","type":9},{"description":"1-D. tensor represents the start of the slice.","name":"input_start","type":9},{"description":"2-D. The `indices` of the sliced `SparseTensor`.","name":"output_indices","type":9}],"outputs":[{"description":"1-D. The gradient with respect to the non-empty values of input `SparseTensor`.","name":"val_grad","typeAttr":"T"}],"summary":"The gradient operator for the SparseSlice op."}},{"name":"SparseSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The inputs represent an N-D SparseTensor with logical shape `[..., B, C]`\n(where `N >= 2`), and with indices sorted in the canonical lexicographic order.\n\nThis op is equivalent to applying the normal `tf.nn.softmax()` to each innermost\nlogical submatrix with shape `[B, C]`, but with the catch that *the implicitly\nzero elements do not participate*. Specifically, the algorithm is equivalent\nto the following:\n\n (1) Applies `tf.nn.softmax()` to a densified view of each innermost submatrix\n with shape `[B, C]`, along the size-C dimension;\n (2) Masks out the original implicitly-zero locations;\n (3) Renormalizes the remaining elements.\n\nHence, the `SparseTensor` result has exactly the same non-zero indices and\nshape.","inputs":[{"description":"2-D. `NNZ x R` matrix with the indices of non-empty values in a\nSparseTensor, in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `NNZ` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9}],"outputs":[{"description":"1-D. The `NNZ` values for the result `SparseTensor`.","name":"output","typeAttr":"T"}],"summary":"Applies softmax to a batched N-D `SparseTensor`."}},{"name":"SparseSoftmaxCrossEntropyWithLogits","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlabels","type":"type"}],"description":"Unlike `SoftmaxCrossEntropyWithLogits`, this operation does not accept\na matrix of label probabilities, but rather a single label per row\nof features. This label is considered to have probability 1.0 for the\ngiven row.\n\nInputs are the logits, not probabilities.","inputs":[{"description":"batch_size x num_classes matrix","name":"features","typeAttr":"T"},{"description":"batch_size vector with values in [0, num_classes).\nThis is the label for the given minibatch entry.","name":"labels","typeAttr":"Tlabels"}],"outputs":[{"description":"Per example loss (batch_size vector).","name":"loss","typeAttr":"T"},{"description":"backpropagated gradients (batch_size x num_classes matrix).","name":"backprop","typeAttr":"T"}],"summary":"Computes softmax cross entropy cost and gradients to backpropagate."}},{"name":"SparseSparseMaximum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Assumes the two SparseTensors have the same shape, i.e., no broadcasting.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, in the canonical lexicographic ordering.","name":"a_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `a_indices`.","name":"a_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"a_shape","type":9},{"description":"counterpart to `a_indices` for the other operand.","name":"b_indices","type":9},{"description":"counterpart to `a_values` for the other operand; must be of the same dtype.","name":"b_values","typeAttr":"T"},{"description":"counterpart to `a_shape` for the other operand; the two shapes must be equal.","name":"b_shape","type":9}],"outputs":[{"description":"2-D. The indices of the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. The values of the output SparseTensor.","name":"output_values","typeAttr":"T"}],"summary":"Returns the element-wise max of two SparseTensors."}},{"name":"SparseSparseMinimum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Assumes the two SparseTensors have the same shape, i.e., no broadcasting.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, in the canonical lexicographic ordering.","name":"a_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `a_indices`.","name":"a_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"a_shape","type":9},{"description":"counterpart to `a_indices` for the other operand.","name":"b_indices","type":9},{"description":"counterpart to `a_values` for the other operand; must be of the same dtype.","name":"b_values","typeAttr":"T"},{"description":"counterpart to `a_shape` for the other operand; the two shapes must be equal.","name":"b_shape","type":9}],"outputs":[{"description":"2-D. The indices of the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. The values of the output SparseTensor.","name":"output_values","typeAttr":"T"}],"summary":"Returns the element-wise min of two SparseTensors."}},{"name":"SparseSplit","schema":{"attributes":[{"description":"The number of ways to split.","minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"}],"description":"If the `shape[split_dim]` is not an integer multiple of `num_split`. Slices\n`[0 : shape[split_dim] % num_split]` gets one extra dimension.\nFor example, if `split_dim = 1` and `num_split = 2` and the input is\n\n input_tensor = shape = [2, 7]\n [ a d e ]\n [b c ]\n\nGraphically the output tensors are:\n\n output_tensor[0] = shape = [2, 4]\n [ a ]\n [b c ]\n\n output_tensor[1] = shape = [2, 3]\n [ d e ]\n [ ]","inputs":[{"description":"0-D. The dimension along which to split. Must be in the range\n`[0, rank(shape))`.","name":"split_dim","type":9},{"description":"2-D tensor represents the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D tensor represents the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. tensor represents the shape of the sparse tensor.\noutput indices: A list of 1-D tensors represents the indices of the output\nsparse tensors.","name":"shape","type":9}],"outputs":[{"name":"output_indices","numberAttr":"num_split","type":9},{"description":"A list of 1-D tensors represents the values of the output sparse\ntensors.","name":"output_values","numberAttr":"num_split","typeAttr":"T"},{"description":"A list of 1-D tensors represents the shape of the output sparse\ntensors.","name":"output_shape","numberAttr":"num_split","type":9}],"summary":"Split a `SparseTensor` into `num_split` tensors along one dimension."}},{"name":"SparseTensorDenseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This Op does not require `a_indices` be sorted in standard lexicographic order.","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`.","name":"a_indices","typeAttr":"Tindices"},{"description":"1-D. The `values` of the `SparseTensor`, with shape `[nnz]`.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`.","name":"a_shape","typeAttr":"Tindices"},{"description":"`ndims`-D Tensor. With shape `a_shape`.","name":"b","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`."}},{"name":"SparseTensorDenseMatMul","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"Use the adjoint of A in the matrix multiply. If A is complex, this\nis transpose(conj(A)). Otherwise it's transpose(A).","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Use the adjoint of B in the matrix multiply. If B is complex, this\nis transpose(conj(B)). Otherwise it's transpose(B).","name":"adjoint_b","type":"boolean"}],"description":"No validity checking is performed on the indices of A. However, the following\ninput format is recommended for optimal behavior:\n\nif adjoint_a == false:\n A should be sorted in lexicographically increasing order. Use SparseReorder\n if you're not sure.\nif adjoint_a == true:\n A should be sorted in order of increasing dimension 1 (i.e., \"column major\"\n order instead of \"row major\" order).","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix.","name":"a_indices","typeAttr":"Tindices"},{"description":"1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`, size `[2]` Vector.","name":"a_shape","type":9},{"description":"2-D. A dense Matrix.","name":"b","typeAttr":"T"}],"outputs":[{"name":"product","typeAttr":"T"}],"summary":"Multiply SparseTensor (of rank 2) \"A\" by dense matrix \"B\"."}},{"name":"SparseTensorSliceDataset","schema":{"attributes":[{"name":"Tvalues","type":"type"}],"inputs":[{"name":"indices","type":9},{"name":"values","typeAttr":"Tvalues"},{"name":"dense_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that splits a SparseTensor into elements row-wise."}},{"name":"SparseTensorToCSRSparseMatrix","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"description":"SparseTensor indices.","name":"indices","type":9},{"description":"SparseTensor values.","name":"values","typeAttr":"T"},{"description":"SparseTensor dense shape.","name":"dense_shape","type":9}],"outputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_matrix","type":21}],"summary":"Converts a SparseTensor to a (possibly batched) CSRSparseMatrix."}},{"name":"SparseToDense","schema":{"attributes":[{"default":true,"description":"If true, indices are checked to make sure they are sorted in\nlexicographic order and that there are no repeats.","name":"validate_indices","type":"boolean"},{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Builds an array `dense` with shape `output_shape` such that\n\n```\n# If sparse_indices is scalar\ndense[i] = (i == sparse_indices ? sparse_values : default_value)\n\n# If sparse_indices is a vector, then for each i\ndense[sparse_indices[i]] = sparse_values[i]\n\n# If sparse_indices is an n by d matrix, then for each i in [0, n)\ndense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i]\n```\n\nAll other values in `dense` are set to `default_value`. If `sparse_values` is a\nscalar, all sparse indices are set to this single value.\n\nIndices should be sorted in lexicographic order, and indices must not\ncontain any repeats. If `validate_indices` is true, these properties\nare checked during execution.","inputs":[{"description":"0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete\nindex where `sparse_values[i]` will be placed.","name":"sparse_indices","typeAttr":"Tindices"},{"description":"1-D. Shape of the dense output tensor.","name":"output_shape","typeAttr":"Tindices"},{"description":"1-D. Values corresponding to each row of `sparse_indices`,\nor a scalar value to be used for all sparse indices.","name":"sparse_values","typeAttr":"T"},{"description":"Scalar value to set for indices not specified in\n`sparse_indices`.","name":"default_value","typeAttr":"T"}],"outputs":[{"description":"Dense output tensor of shape `output_shape`.","name":"dense","typeAttr":"T"}],"summary":"Converts a sparse representation into a dense tensor."}},{"name":"SparseToSparseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nIf `validate_indices` is `True`, `SparseToSparseSetOperation` validates the\norder and range of `set1` and `set2` indices.\n\nInput `set1` is a `SparseTensor` represented by `set1_indices`, `set1_values`,\nand `set1_shape`. For `set1` ranked `n`, 1st `n-1` dimensions must be the same\nas `set2`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nInput `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`,\nand `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same\nas `set1`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set1`\nand `set2` indices.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set1_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set1_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must\nbe the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the\nmax set size across `0...n-1` dimensions.","name":"set1_shape","type":9},{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set2_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set2_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must\nbe the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the\nmax set size across `0...n-1` dimensions.","name":"set2_shape","type":9}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of 2 `SparseTensor` inputs."}},{"name":"Spence","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"The number of ways to split. Must evenly divide\n`value.shape[split_dim]`.","minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"}],"category":"Tensor","inputs":[{"description":"0-D. The dimension along which to split. Must be in the range\n`[-rank(value), rank(value))`.","name":"split_dim","type":3},{"description":"The tensor to split.","name":"value","typeAttr":"T"}],"outputs":[{"description":"They are identically shaped tensors, whose shape matches that of `value`\nexcept along `split_dim`, where their sizes are\n`values.shape[split_dim] / num_split`.","name":"output","numberAttr":"num_split","typeAttr":"T"}],"summary":"Splits a tensor into `num_split` tensors along one dimension."}},{"name":"SplitV","schema":{"attributes":[{"minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlen","type":"type"}],"inputs":[{"description":"The tensor to split.","name":"value","typeAttr":"T"},{"description":"list containing the sizes of each output tensor along the split\ndimension. Must sum to the dimension of value along split_dim.\nCan contain one -1 indicating that dimension is to be inferred.","name":"size_splits","typeAttr":"Tlen"},{"description":"0-D. The dimension along which to split. Must be in the range\n`[-rank(value), rank(value))`.","name":"split_dim","type":3}],"outputs":[{"description":"Tensors whose shape matches that of `value`\nexcept along `split_dim`, where their sizes are\n`size_splits[i]`.","name":"output","numberAttr":"num_split","typeAttr":"T"}],"summary":"Splits a tensor into `num_split` tensors along one dimension."}},{"name":"SqlDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"The database type. Currently, the only supported type is 'sqlite'.","name":"driver_name","type":7},{"description":"A connection string to connect to the database.","name":"data_source_name","type":7},{"description":"A SQL query to execute.","name":"query","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that executes a SQL query and emits rows of the result set."}},{"name":"Sqrt","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\sqrt{x} = x^{1/2}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes square root of x element-wise."}},{"name":"SqrtGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * 0.5 / y`, where `y = sqrt(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the sqrt of `x` wrt its input."}},{"name":"Square","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = x * x = x^2\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes square of x element-wise."}},{"name":"SquaredDifference","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `SquaredDifference` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns conj(x - y)(x - y) element-wise."}},{"name":"Squeeze","schema":{"attributes":[{"name":"T","type":"type"},{"default":[],"description":"If specified, only squeezes the dimensions listed. The dimension\nindex starts at 0. It is an error to squeeze a dimension that is not 1. Must\nbe in the range `[-rank(input), rank(input))`.","minimum":0,"name":"squeeze_dims","type":"int64[]"}],"category":"Shape","description":"Given a tensor `input`, this operation returns a tensor of the same type with\nall dimensions of size 1 removed. If you don't want to remove all size 1\ndimensions, you can remove specific size 1 dimensions by specifying\n`squeeze_dims`.\n\nFor example:\n\n```\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t)) ==> [2, 3]\n```\n\nOr, to remove specific size 1 dimensions:\n\n```\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]\n```","inputs":[{"description":"The `input` to squeeze.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Contains the same data as `input`, but has one or more dimensions of\nsize 1 removed.","name":"output","typeAttr":"T"}],"summary":"Removes dimensions of size 1 from the shape of a tensor."}},{"name":"Stack","schema":{"attributes":[{"name":"elem_type","type":"type"},{"default":"","name":"stack_name","type":"string"}],"outputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated, use StackV2."}},{"name":"StackClose","schema":{"inputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated, use StackCloseV2."}},{"name":"StackCloseV2","schema":{"inputs":[{"description":"The handle to a stack.","name":"handle","type":20}],"summary":"Delete the stack from its resource container."}},{"name":"StackPop","schema":{"attributes":[{"name":"elem_type","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7}],"outputs":[{"name":"elem","typeAttr":"elem_type"}],"summary":"Deprecated, use StackPopV2."}},{"name":"StackPopV2","schema":{"attributes":[{"description":"The type of the elem that is popped.","name":"elem_type","type":"type"}],"inputs":[{"description":"The handle to a stack.","name":"handle","type":20}],"outputs":[{"description":"The tensor that is popped from the top of the stack.","name":"elem","typeAttr":"elem_type"}],"summary":"Pop the element at the top of the stack."}},{"name":"StackPush","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"name":"swap_memory","type":"boolean"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"elem","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Deprecated, use StackPushV2."}},{"name":"StackPushV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"description":"Swap `elem` to CPU. Default to false.","name":"swap_memory","type":"boolean"}],"inputs":[{"description":"The handle to a stack.","name":"handle","type":20},{"description":"The tensor to be pushed onto the stack.","name":"elem","typeAttr":"T"}],"outputs":[{"description":"The same tensor as the input 'elem'.","name":"output","typeAttr":"T"}],"summary":"Push an element onto the stack."}},{"name":"StackV2","schema":{"attributes":[{"description":"The type of the elements on the stack.","name":"elem_type","type":"type"},{"default":"","description":"Overrides the name used for the temporary stack resource. Default\nvalue is the name of the 'Stack' op (which is guaranteed unique).","name":"stack_name","type":"string"}],"inputs":[{"description":"The maximum size of the stack if non-negative. If negative, the stack\nsize is unlimited.","name":"max_size","type":3}],"outputs":[{"description":"The handle to the stack.","name":"handle","type":20}],"summary":"A stack that produces elements in first-in last-out order."}},{"name":"Stage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"description":"The maximum number of bytes allowed for Tensors in the Staging Area.\nIf > 0, inserts will block until sufficient space is available.","minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"description":"The basic functionality of this Op is similar to a queue with many\nfewer capabilities and options. This Op is optimized for performance.","inputs":[{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"dtypes"}],"summary":"Stage values similar to a lightweight Enqueue."}},{"name":"StageClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"StagePeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain sufficient elements\nthis op will block until it does. This Op is optimized for\nperformance.","inputs":[{"name":"index","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified index. If the"}},{"name":"StageSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"StatefulPartitionedCall","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'args', a list of tensors, and returns 'output',\n another list of tensors. Input and output types are specified by 'Tin'\n and 'Tout'. The function body of f will be placed and partitioned across\n devices, setting this op apart from the regular Call op. This op is\n stateful.","name":"f","type":"function"},{"default":"","name":"config","type":"string"},{"default":"","name":"config_proto","type":"string"},{"default":"","name":"executor_type","type":"string"}],"inputs":[{"description":"A list of input tensors.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"returns `f(inputs)`, where `f`'s body is placed and partitioned."}},{"name":"StatefulRandomBinomial","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"inputs":[{"name":"resource","type":20},{"name":"algorithm","type":9},{"name":"shape","typeAttr":"S"},{"name":"counts","typeAttr":"T"},{"name":"probs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"dtype"}]}},{"name":"StatefulStandardNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2'"}},{"name":"StatefulStandardNormalV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution."}},{"name":"StatefulTruncatedNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a truncated normal distribution."}},{"name":"StatefulUniform","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a uniform distribution."}},{"name":"StatefulUniformFullInt","schema":{"attributes":[{"default":{"type":"type","value":23},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values are uniform integers covering the whole range of `dtype`.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"StatefulUniformInt","schema":{"attributes":[{"default":{"type":"type","value":9},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values are uniform integers in the range `[minval, maxval)`.\nThe lower bound `minval` is included in the range, while the upper bound\n`maxval` is excluded.\n\nThe random integers are slightly biased unless `maxval - minval` is an exact\npower of two. The bias is small for values of `maxval - minval` significantly\nsmaller than the range of the output (either `2^32` or `2^64`).","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"},{"description":"Minimum value (inclusive, scalar).","name":"minval","typeAttr":"dtype"},{"description":"Maximum value (exclusive, scalar).","name":"maxval","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"StatelessIf","schema":{"attributes":[{"name":"Tcond","type":"type"},{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what else_branch returns.","name":"then_branch","type":"function"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what then_branch returns.","name":"else_branch","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":" A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n `True` and zero means False; if the scalar is a string, non-empty\n means `True` and empty means `False`. If the tensor is not a scalar,\n being empty means False and being non-empty means True.\n\n This should only be used when the if then/else body functions do not\n have stateful ops.","name":"cond","typeAttr":"Tcond"},{"description":"A list of input tensors.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"output = cond ? then_branch(input) : else_branch(input)"}},{"name":"StatelessMultinomial","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_dtype","type":"type"}],"inputs":[{"description":"2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]`\nrepresents the unnormalized log probabilities for all classes.","name":"logits","typeAttr":"T"},{"description":"0-D. Number of independent samples to draw for each row slice.","name":"num_samples","type":3},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]`\ncontains the drawn class labels with range `[0, num_classes)`.","name":"output","typeAttr":"output_dtype"}],"summary":"Draws samples from a multinomial distribution."}},{"name":"StatelessParameterizedTruncatedNormal","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"}],"inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"S"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The mean parameter of each batch.","name":"means","typeAttr":"dtype"},{"description":"The standard deviation parameter of each batch. Must be greater than 0.","name":"stddevs","typeAttr":"dtype"},{"description":"The minimum cutoff. May be -infinity.","name":"minvals","typeAttr":"dtype"},{"description":"The maximum cutoff. May be +infinity, and must be more than the minval\nfor each batch.","name":"maxvals","typeAttr":"dtype"}],"outputs":[{"description":"The outputs are truncated normal samples and are a deterministic function of\n`shape`, `seed`, `minvals`, `maxvals`, `means` and `stddevs`.","name":"output","typeAttr":"dtype"}]}},{"name":"StatelessRandomBinomial","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"description":"Outputs random values from a binomial distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, `counts`, and `probs`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"S"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The counts of the binomial distribution. Must be broadcastable with `probs`,\nand broadcastable with the rightmost dimensions of `shape`.","name":"counts","typeAttr":"T"},{"description":"The probability of success for the binomial distribution. Must be broadcastable\nwith `counts` and broadcastable with the rightmost dimensions of `shape`.","name":"probs","typeAttr":"T"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a binomial distribution."}},{"name":"StatelessRandomGammaV2","schema":{"attributes":[{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"Outputs random values from a gamma distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, and `alpha`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The concentration of the gamma distribution. Shape must match the rightmost\ndimensions of `shape`.","name":"alpha","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a gamma distribution."}},{"name":"StatelessRandomNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom values from a normal distribution."}},{"name":"StatelessRandomPoisson","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"Rtype","type":"type"},{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"Outputs random values from a Poisson distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, and `lam`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The rate of the Poisson distribution. Shape must match the rightmost dimensions\nof `shape`.","name":"lam","typeAttr":"Rtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a Poisson distribution."}},{"name":"StatelessRandomUniform","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random values from a uniform distribution."}},{"name":"StatelessRandomUniformFullInt","schema":{"attributes":[{"default":{"type":"type","value":23},"description":"The type of the output. Must be one of the following: `int32`, `int64`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`, `uint32`, `uint64`.","name":"Tseed","type":"type"}],"description":"The generated values are uniform integers covering the whole range of `dtype`.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random integers from a uniform distribution."}},{"name":"StatelessRandomUniformInt","schema":{"attributes":[{"description":"The type of the output. Must be one of the following: `int32`, `int64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[minval, maxval)`.\n\nThe outputs are a deterministic function of `shape`, `seed`, `minval`, and `maxval`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"Minimum value (inclusive, scalar).","name":"minval","typeAttr":"dtype"},{"description":"Maximum value (exclusive, scalar).","name":"maxval","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random integers from a uniform distribution."}},{"name":"StatelessTruncatedNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom values from a truncated normal distribution."}},{"name":"StatelessWhile","schema":{"attributes":[{"description":"dtype in use.","minimum":0,"name":"T","type":"type[]"},{"description":" A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.\n\n This should only be used when the while condition and body functions\n do not have stateful ops.","name":"cond","type":"function"},{"description":" A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.","name":"body","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"},{"default":10,"name":"parallel_iterations","type":"int64"}],"inputs":[{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":"output = input; While (Cond(output)) { output = Body(output) }"}},{"name":"StaticRegexFullMatch","schema":{"attributes":[{"description":"The regular expression to match the input.","name":"pattern","type":"string"}],"description":"The input is a string tensor of any shape. The pattern is the\nregular expression to be matched with every element of the input tensor.\nThe boolean values (True or False) of the output tensor indicate\nif the input matches the regex pattern provided.\n\nThe pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"A string tensor of the text to be processed.","name":"input","type":7}],"outputs":[{"description":"A bool tensor with the same shape as `input`.","name":"output","type":10}],"summary":"Check if the input matches the regex pattern."}},{"name":"StaticRegexReplace","schema":{"attributes":[{"description":"The regular expression to match the input.","name":"pattern","type":"string"},{"description":"The rewrite to be applied to the matched expression.","name":"rewrite","type":"string"},{"default":true,"description":"If True, the replacement is global, otherwise the replacement\nis done only on the first match.","name":"replace_global","type":"boolean"}],"description":"It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"The text to be processed.","name":"input","type":7}],"outputs":[{"description":"The text after applying pattern and rewrite.","name":"output","type":7}],"summary":"Replaces the match of pattern in input with rewrite."}},{"name":"StatsAggregatorHandle","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}],"summary":"Creates a statistics manager resource."}},{"name":"StatsAggregatorHandleV2","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}]}},{"name":"StatsAggregatorSetSummaryWriter","schema":{"inputs":[{"name":"stats_aggregator","type":20},{"name":"summary","type":20}],"summary":"Set a summary_writer_interface to record statistics using given stats_aggregator."}},{"name":"StatsAggregatorSummary","schema":{"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"summary","type":7}],"summary":"Produces a summary of any statistics recorded by the given statistics manager."}},{"name":"StopGradient","schema":{"attributes":[{"name":"T","type":"type"}],"description":"When executed in a graph, this op outputs its input tensor as-is.\n\nWhen building ops to compute gradients, this op prevents the contribution of\nits inputs to be taken into account. Normally, the gradient generator adds ops\nto a graph to compute the derivatives of a specified 'loss' by recursively\nfinding out inputs that contributed to its computation. If you insert this op\nin the graph it inputs are masked from the gradient generator. They are not\ntaken into account for computing gradients.\n\nThis is useful any time you want to compute a value with TensorFlow but need\nto pretend that the value was a constant. Some examples include:\n\n* The *EM* algorithm where the *M-step* should not involve backpropagation\n through the output of the *E-step*.\n* Contrastive divergence training of Boltzmann machines where, when\n differentiating the energy function, the training must not backpropagate\n through the graph that generated the samples from the model.\n* Adversarial training, where no backprop should happen through the adversarial\n example generation process.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Stops gradient computation."}},{"name":"StridedSlice","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"description":"a bitmask where a bit i being 1 means to ignore the begin\nvalue and instead use the largest interval possible. At runtime\nbegin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or\n`[-1, n-1]` if `stride[i] < 0`","name":"begin_mask","type":"int64"},{"default":0,"description":"analogous to `begin_mask`","name":"end_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` being 1 means the `i`th\nposition is actually an ellipsis. One bit at most can be 1.\nIf `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)`\nis provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis\nimplicitly creates as many range specifications as necessary to fully\nspecify the sliced range for every dimension. For example for a 4-dimensional\ntensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`.","name":"ellipsis_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` being 1 means the `i`th\nspecification creates a new shape 1 dimension. For example\n`foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor.","name":"new_axis_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` implies that the `i`th\nspecification should shrink the dimensionality. begin and end\nmust imply a slice of size 1 in the dimension. For example in\npython one might do `foo[:, 3, :]` which would result in\n`shrink_axis_mask` being 2.","name":"shrink_axis_mask","type":"int64"}],"category":"Tensor","description":"Note, most python users will want to use the Python `Tensor.__getitem__`\nor `Variable.__getitem__` rather than this op directly.\n\nThe goal of this op is to produce a new tensor with a subset of\nthe elements from the `n` dimensional `input` tensor. The subset is chosen using\na sequence of `m` sparse range specifications encoded into the arguments\nof this function. Note, in some cases\n`m` could be equal to `n`, but this need not be the case. Each\nrange specification entry can be one of the following:\n\n- An ellipsis (...). Ellipses are used to imply zero or more\n dimensions of full-dimension selection and are produced using\n `ellipsis_mask`. For example, `foo[...]` is the identity slice.\n\n- A new axis. This is used to insert a new shape=1 dimension and is\n produced using `new_axis_mask`. For example, `foo[:, ...]` where\n `foo` is shape `(3, 4)` produces a `(1, 3, 4)` tensor.\n\n\n- A range `begin:end:stride`. This is used to specify how much to choose from\n a given dimension. `stride` can be any integer but 0. `begin` is an integer\n which represents the index of the first value to select while `end` represents\n the index of the last value to select. The number of values selected in each\n dimension is `end - begin` if `stride > 0` and `begin - end` if `stride < 0`.\n `begin` and `end` can be negative where `-1` is the last element, `-2` is\n the second to last. `begin_mask` controls whether to replace the explicitly\n given `begin` with an implicit effective value of `0` if `stride > 0` and\n `-1` if `stride < 0`. `end_mask` is analogous but produces the number\n required to create the largest open interval. For example, given a shape\n `(3,)` tensor `foo[:]`, the effective `begin` and `end` are `0` and `3`. Do\n not assume this is equivalent to `foo[0:-1]` which has an effective `begin`\n and `end` of `0` and `2`. Another example is `foo[-2::-1]` which reverses the\n first dimension of a tensor while dropping the last two (in the original\n order elements). For example `foo = [1,2,3,4]; foo[-2::-1]` is `[4,3]`.\n\n- A single index. This is used to keep only elements that have a given\n index. For example (`foo[2, :]` on a shape `(5,6)` tensor produces a\n shape `(6,)` tensor. This is encoded in `begin` and `end` and\n `shrink_axis_mask`.\n\nEach conceptual range specification is encoded in the op's argument. This\nencoding is best understand by considering a non-trivial example. In\nparticular,\n`foo[1, 2:4, None, ..., :-3:-1, :]` will be encoded as\n\n```\nbegin = [1, 2, x, x, 0, x] # x denotes don't care (usually 0)\nend = [2, 4, x, x, -3, x]\nstrides = [1, 1, x, x, -1, 1]\nbegin_mask = 1<<4 | 1<<5 = 48\nend_mask = 1<<5 = 32\nellipsis_mask = 1<<3 = 8\nnew_axis_mask = 1<<2 = 4\nshrink_axis_mask = 1<<0 = 1\n```\n\nIn this case if `foo.shape` is (5, 5, 5, 5, 5, 5) the final shape of\nthe slice becomes (2, 1, 5, 5, 2, 5).\nLet us walk step by step through each argument specification.\n\n1. The first argument in the example slice is turned into `begin = 1` and\n`end = begin + 1 = 2`. To disambiguate from the original spec `2:4` we\nalso set the appropriate bit in `shrink_axis_mask`.\n\n2. `2:4` is contributes 2, 4, 1 to begin, end, and stride. All masks have\nzero bits contributed.\n\n3. None is a synonym for `tf.newaxis`. This means insert a dimension of size 1\ndimension in the final shape. Dummy values are contributed to begin,\nend and stride, while the new_axis_mask bit is set.\n\n4. `...` grab the full ranges from as many dimensions as needed to\nfully specify a slice for every dimension of the input shape.\n\n5. `:-3:-1` shows the use of negative indices. A negative index `i` associated\nwith a dimension that has shape `s` is converted to a positive index\n`s + i`. So `-1` becomes `s-1` (i.e. the last element). This conversion\nis done internally so begin, end and strides receive x, -3, and -1.\nThe appropriate begin_mask bit is set to indicate the start range is the\nfull range (ignoring the x).\n\n6. `:` indicates that the entire contents of the corresponding dimension\nis selected. This is equivalent to `::` or `0::1`. begin, end, and strides\nreceive 0, 0, and 1, respectively. The appropriate bits in `begin_mask` and\n`end_mask` are also set.\n\n*Requirements*:\n `0 != strides[i] for i in [0, m)`\n `ellipsis_mask must be a power of two (only one ellipsis)`","inputs":[{"name":"input","typeAttr":"T"},{"description":"`begin[k]` specifies the offset into the `k`th range specification.\nThe exact dimension this corresponds to will be determined by context.\nOut-of-bounds values will be silently clamped. If the `k`th bit of\n`begin_mask` then `begin[k]` is ignored and the full range of the\nappropriate dimension is used instead. Negative values causes indexing\nto start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`.","name":"begin","typeAttr":"Index"},{"description":"`end[i]` is like `begin` with the exception that `end_mask` is\nused to determine full ranges.","name":"end","typeAttr":"Index"},{"description":"`strides[i]` specifies the increment in the `i`th specification\nafter extracting a given element. Negative indices will reverse\nthe original order. Out or range values are\nclamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0`","name":"strides","typeAttr":"Index"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a strided slice from `input`."}},{"name":"StridedSliceAssign","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the variable\n`ref` that are selected by the slice parameters. The slice parameters\n`begin`, `end`, `strides`, etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s\nshape must be exactly the shape produced by the slice of `ref`.","inputs":[{"isRef":true,"name":"ref","typeAttr":"T"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `ref`."}},{"name":"StridedSliceGrad","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"Since `StridedSlice` cuts out pieces of its `input` which is size\n`shape`, its gradient will have the same shape (which is passed here\nas `shape`). The gradient will be zero in any element that the slice\ndoes not select.\n\nArguments are the same as StridedSliceGrad with the exception that\n`dy` is the input gradient to be propagated and `shape` is the\nshape of `StridedSlice`'s `input`.","inputs":[{"name":"shape","typeAttr":"Index"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the gradient of `StridedSlice`."}},{"name":"StringFormat","schema":{"attributes":[{"minimum":0,"name":"T","type":"type[]"},{"default":"%s","description":"A string, the template to format tensor summaries into.","name":"template","type":"string"},{"default":"%s","description":"A string, at each placeholder in the template a subsequent tensor summary will be inserted.","name":"placeholder","type":"string"},{"default":3,"description":"When formatting the tensor summaries print the first and last summarize entries of each tensor dimension.","name":"summarize","type":"int64"}],"description":"Formats a string template using a list of tensors, pretty-printing tensor summaries.","inputs":[{"description":"The list of tensors to format into the placeholder string.","name":"inputs","typeListAttr":"T"}],"outputs":[{"description":"= The resulting string scalar.","name":"output","type":7}],"summary":"Formats a string template using a list of tensors."}},{"name":"StringJoin","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":"","description":"string, an optional join separator.","name":"separator","type":"string"}],"description":"with the given separator (default is an empty separator).\n\nExamples:\n\n>>> s = [\"hello\", \"world\", \"tensorflow\"]\n>>> tf.strings.join(s, \" \")\n","inputs":[{"description":"A list of string tensors. The tensors must all have the same shape,\nor be scalars. Scalars may be mixed in; these will be broadcast to the shape\nof non-scalar inputs.","name":"inputs","numberAttr":"N","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Joins the strings in the given list of string tensors into one tensor;"}},{"name":"StringLength","schema":{"attributes":[{"default":"BYTE","description":"The unit that is counted to compute string length. One of: `\"BYTE\"` (for\nthe number of bytes in each string) or `\"UTF8_CHAR\"` (for the number of UTF-8\nencoded Unicode code points in each string). Results are undefined\nif `unit=UTF8_CHAR` and the `input` strings do not contain structurally\nvalid UTF-8. Must be one of the following: `BYTE`, `UTF8_CHAR`.","name":"unit","type":"string"}],"description":"Computes the length of each string given in the input tensor.\n\n>>> strings = tf.constant(['Hello','TensorFlow', '\\U0001F642'])\n>>> tf.strings.length(strings).numpy() # default counts bytes\narray([ 5, 10, 4], dtype=int32)\n>>> tf.strings.length(strings, unit=\"UTF8_CHAR\").numpy()\narray([ 5, 10, 1], dtype=int32)\n","inputs":[{"description":"The strings for which to compute the length for each element.","name":"input","type":7}],"outputs":[{"description":"Integer tensor that has the same shape as `input`. The output contains the\nelement-wise string lengths of `input`.","name":"output","type":3}],"summary":"String lengths of `input`."}},{"name":"StringLower","schema":{"attributes":[{"default":"","name":"encoding","type":"string"}],"description":"Example:\n\n>>> tf.strings.lower(\"CamelCase string and ALL CAPS\")\n\n","inputs":[{"name":"input","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Converts all uppercase characters into their respective lowercase replacements."}},{"name":"StringNGrams","schema":{"attributes":[{"description":"The string to append between elements of the token. Use \"\" for no separator.","name":"separator","type":"string"},{"description":"The sizes of the ngrams to create.","minimum":0,"name":"ngram_widths","type":"int64[]"},{"description":"The string to use to pad the left side of the ngram sequence. Only used if\npad_width != 0.","name":"left_pad","type":"string"},{"description":"The string to use to pad the right side of the ngram sequence. Only used if\npad_width != 0.","name":"right_pad","type":"string"},{"description":"The number of padding elements to add to each side of each\nsequence. Note that padding will never be greater than 'ngram_widths'-1\nregardless of this value. If `pad_width=-1`, then add `max(ngram_widths)-1`\nelements.","name":"pad_width","type":"int64"},{"name":"preserve_short_sequences","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"This op accepts a ragged tensor with 1 ragged dimension containing only\nstrings and outputs a ragged tensor with 1 ragged dimension containing ngrams\nof that string, joined along the innermost axis.","inputs":[{"description":"The values tensor of the ragged string tensor to make ngrams out of. Must be a\n1D string tensor.","name":"data","type":7},{"description":"The splits tensor of the ragged string tensor to make ngrams out of.","name":"data_splits","typeAttr":"Tsplits"}],"outputs":[{"description":"The values tensor of the output ngrams ragged tensor.","name":"ngrams","type":7},{"description":"The splits tensor of the output ngrams ragged tensor.","name":"ngrams_splits","typeAttr":"Tsplits"}],"summary":"Creates ngrams from ragged string data."}},{"name":"StringSplit","schema":{"attributes":[{"default":true,"description":"A `bool`. If `True`, skip the empty strings from the result.","name":"skip_empty","type":"boolean"}],"description":"Let N be the size of source (typically N will be the batch size). Split each\nelement of `input` based on `delimiter` and return a `SparseTensor`\ncontaining the splitted tokens. Empty tokens are ignored.\n\n`delimiter` can be empty, or a string of split characters. If `delimiter` is an\n empty string, each element of `input` is split into individual single-byte\n character strings, including splitting of UTF-8 multibyte sequences. Otherwise\n every character of `delimiter` is a potential split point.\n\nFor example:\n N = 2, input[0] is 'hello world' and input[1] is 'a b c', then the output\n will be\n\n indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n shape = [2, 3]\n values = ['hello', 'world', 'a', 'b', 'c']","inputs":[{"description":"1-D. Strings to split.","name":"input","type":7},{"description":"0-D. Delimiter characters (bytes), or empty string.","name":"delimiter","type":7}],"outputs":[{"description":"A dense matrix of int64 representing the indices of the sparse tensor.","name":"indices","type":9},{"description":"A vector of strings corresponding to the splited values.","name":"values","type":7},{"description":"a length-2 vector of int64 representing the shape of the sparse\ntensor, where the first value is N and the second value is the maximum number\nof tokens in a single input entry.","name":"shape","type":9}],"summary":"Split elements of `input` based on `delimiter` into a `SparseTensor`."}},{"name":"StringSplitV2","schema":{"attributes":[{"default":-1,"description":"An `int`. If `maxsplit > 0`, limit of the split of the result.","name":"maxsplit","type":"int64"}],"description":"Let N be the size of source (typically N will be the batch size). Split each\nelement of `source` based on `sep` and return a `SparseTensor`\ncontaining the split tokens. Empty tokens are ignored.\n\nFor example, N = 2, source[0] is 'hello world' and source[1] is 'a b c',\nthen the output will be\n```\nst.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\nst.shape = [2, 3]\nst.values = ['hello', 'world', 'a', 'b', 'c']\n```\n\nIf `sep` is given, consecutive delimiters are not grouped together and are\ndeemed to delimit empty strings. For example, source of `\"1<>2<><>3\"` and\nsep of `\"<>\"` returns `[\"1\", \"2\", \"\", \"3\"]`. If `sep` is None or an empty\nstring, consecutive whitespace are regarded as a single separator, and the\nresult will contain no empty strings at the startor end if the string has\nleading or trailing whitespace.\n\nNote that the above mentioned behavior matches python's str.split.","inputs":[{"description":"`1-D` string `Tensor`, the strings to split.","name":"input","type":7},{"description":"`0-D` string `Tensor`, the delimiter character.","name":"sep","type":7}],"outputs":[{"name":"indices","type":9},{"name":"values","type":7},{"name":"shape","type":9}],"summary":"Split elements of `source` based on `sep` into a `SparseTensor`."}},{"name":"StringStrip","schema":{"inputs":[{"description":"A string `Tensor` of any shape.","name":"input","type":7}],"outputs":[{"description":"A string `Tensor` of the same shape as the input.\n\nExamples:\n\n>>> tf.strings.strip([\"\\nTensorFlow\", \" The python library \"]).numpy()\narray([b'TensorFlow', b'The python library'], dtype=object)","name":"output","type":7}],"summary":"Strip leading and trailing whitespaces from the Tensor."}},{"name":"StringToHashBucket","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The hash function is deterministic on the content of the string within the\nprocess.\n\nNote that the hash function may change from time to time.\nThis functionality will be deprecated and it's recommended to use\n`tf.string_to_hash_bucket_fast()` or `tf.string_to_hash_bucket_strong()`.","inputs":[{"name":"string_tensor","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToHashBucketFast","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The hash function is deterministic on the content of the string within the\nprocess and will never change. However, it is not suitable for cryptography.\nThis function may be used when CPU time is scarce and inputs are trusted or\nunimportant. There is a risk of adversaries constructing inputs that all hash\nto the same bucket. To prevent this problem, use a strong hash function with\n`tf.string_to_hash_bucket_strong`.\n\nExamples:\n\n>>> tf.strings.to_hash_bucket_fast([\"Hello\", \"TensorFlow\", \"2.x\"], 3).numpy()\narray([0, 2, 2])","inputs":[{"description":"The strings to assign a hash bucket.","name":"input","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToHashBucketStrong","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"},{"description":"The key used to seed the hash function, passed as a list of two uint64\nelements.","name":"key","type":"int64[]"}],"description":"The hash function is deterministic on the content of the string within the\nprocess. The hash function is a keyed hash function, where attribute `key`\ndefines the key of the hash function. `key` is an array of 2 elements.\n\nA strong hash is important when inputs may be malicious, e.g. URLs with\nadditional components. Adversaries could try to make their inputs hash to the\nsame bucket for a denial-of-service attack or to skew the results. A strong\nhash can be used to make it difficult to find inputs with a skewed hash value\ndistribution over buckets. This requires that the hash function is\nseeded by a high-entropy (random) \"key\" unknown to the adversary.\n\nThe additional robustness comes at a cost of roughly 4x higher compute\ntime than `tf.string_to_hash_bucket_fast`.\n\nExamples:\n\n>>> tf.strings.to_hash_bucket_strong([\"Hello\", \"TF\"], 3, [1, 2]).numpy()\narray([2, 0])","inputs":[{"description":"The strings to assign a hash bucket.","name":"input","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToNumber","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The numeric type to interpret each string in `string_tensor` as. Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"out_type","type":"type"}],"description":"(Note that int32 overflow results in an error while float overflow\nresults in a rounded value.)\n\nExample:\n\n>>> strings = [\"5.0\", \"3.0\", \"7.0\"]\n>>> tf.strings.to_number(strings)\n\n","inputs":[{"name":"string_tensor","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","typeAttr":"out_type"}],"summary":"Converts each string in the input Tensor to the specified numeric type."}},{"name":"StringUpper","schema":{"attributes":[{"default":"","name":"encoding","type":"string"}],"description":"Example:\n\n>>> tf.strings.upper(\"CamelCase string and ALL CAPS\")\n\n","inputs":[{"name":"input","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Converts all lowercase characters into their respective uppercase replacements."}},{"name":"Sub","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `uint32`.","name":"T","type":"type"}],"description":"*NOTE*: `Sub` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x - y element-wise."}},{"name":"Substr","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"BYTE","description":"The unit that is used to create the substring. One of: `\"BYTE\"` (for\ndefining position and length by bytes) or `\"UTF8_CHAR\"` (for the UTF-8\nencoded Unicode code points). The default is `\"BYTE\"`. Results are undefined if\n`unit=UTF8_CHAR` and the `input` strings do not contain structurally valid\nUTF-8. Must be one of the following: `BYTE`, `UTF8_CHAR`.","name":"unit","type":"string"}],"description":"For each string in the input `Tensor`, creates a substring starting at index\n`pos` with a total length of `len`.\n\nIf `len` defines a substring that would extend beyond the length of the input\nstring, or if `len` is negative, then as many characters as possible are used.\n\nA negative `pos` indicates distance within the string backwards from the end.\n\nIf `pos` specifies an index which is out of range for any of the input strings,\nthen an `InvalidArgumentError` is thrown.\n\n`pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on\nOp creation.\n\n*NOTE*: `Substr` supports broadcasting up to two dimensions. More about\nbroadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\n---\n\nExamples\n\nUsing scalar `pos` and `len`:\n\n```python\ninput = [b'Hello', b'World']\nposition = 1\nlength = 3\n\noutput = [b'ell', b'orl']\n```\n\nUsing `pos` and `len` with same shape as `input`:\n\n```python\ninput = [[b'ten', b'eleven', b'twelve'],\n [b'thirteen', b'fourteen', b'fifteen'],\n [b'sixteen', b'seventeen', b'eighteen']]\nposition = [[1, 2, 3],\n [1, 2, 3],\n [1, 2, 3]]\nlength = [[2, 3, 4],\n [4, 3, 2],\n [5, 5, 5]]\n\noutput = [[b'en', b'eve', b'lve'],\n [b'hirt', b'urt', b'te'],\n [b'ixtee', b'vente', b'hteen']]\n```\n\nBroadcasting `pos` and `len` onto `input`:\n\n```\ninput = [[b'ten', b'eleven', b'twelve'],\n [b'thirteen', b'fourteen', b'fifteen'],\n [b'sixteen', b'seventeen', b'eighteen'],\n [b'nineteen', b'twenty', b'twentyone']]\nposition = [1, 2, 3]\nlength = [1, 2, 3]\n\noutput = [[b'e', b'ev', b'lve'],\n [b'h', b'ur', b'tee'],\n [b'i', b've', b'hte'],\n [b'i', b'en', b'nty']]\n```\n\nBroadcasting `input` onto `pos` and `len`:\n\n```\ninput = b'thirteen'\nposition = [1, 5, 7]\nlength = [3, 2, 1]\n\noutput = [b'hir', b'ee', b'n']\n```\n\nRaises:\n\n * `ValueError`: If the first argument cannot be converted to a\n Tensor of `dtype string`.\n * `InvalidArgumentError`: If indices are out of range.\n * `ValueError`: If `pos` and `len` are not the same shape.\n","inputs":[{"description":"Tensor of strings","name":"input","type":7},{"description":"Scalar defining the position of first character in each substring","name":"pos","typeAttr":"T"},{"description":"Scalar defining the number of characters to include in each substring","name":"len","typeAttr":"T"}],"outputs":[{"description":"Tensor of substrings","name":"output","type":7}],"summary":"Return substrings from `Tensor` of strings."}},{"name":"Sum","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the sum of elements across dimensions of a tensor."}},{"name":"SummaryWriter","schema":{"attributes":[{"default":"","name":"shared_name","type":"string"},{"default":"","name":"container","type":"string"}],"outputs":[{"name":"writer","type":20}]}},{"name":"Svd","schema":{"attributes":[{"default":true,"description":"If true, left and right singular vectors will be\ncomputed and returned in `u` and `v`, respectively.\nIf false, `u` and `v` are not set and should never referenced.","name":"compute_uv","type":"boolean"},{"default":false,"description":"If true, compute full-sized `u` and `v`. If false\n(the default), compute only the leading `P` singular vectors.\nIgnored if `compute_uv` is `False`.","name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the SVD of each inner matrix in `input` such that\n`input[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])`\n\n```python\n# a is a tensor containing a batch of matrices.\n# s is a tensor of singular values for each matrix.\n# u is the tensor containing the left singular vectors for each matrix.\n# v is the tensor containing the right singular vectors for each matrix.\ns, u, v = svd(a)\ns, _, _ = svd(a, compute_uv=False)\n```","inputs":[{"description":"A tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Singular values. Shape is `[..., P]`.","name":"s","typeAttr":"T"},{"description":"Left singular vectors. If `full_matrices` is `False` then shape is\n`[..., M, P]`; if `full_matrices` is `True` then shape is\n`[..., M, M]`. Undefined if `compute_uv` is `False`.","name":"u","typeAttr":"T"},{"description":"Left singular vectors. If `full_matrices` is `False` then shape is\n`[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`.\nUndefined if `compute_uv` is false.","name":"v","typeAttr":"T"}],"summary":"Computes the singular value decompositions of one or more matrices."}},{"name":"Switch","schema":{"attributes":[{"name":"T","type":"type"}],"description":"If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise,\nthe data goes to `output_false`.\n\nSee also `RefSwitch` and `Merge`.","inputs":[{"description":"The tensor to be forwarded to the appropriate output.","name":"data","typeAttr":"T"},{"description":"A scalar that specifies which output port will receive data.","name":"pred","type":10}],"outputs":[{"description":"If `pred` is false, data will be forwarded to this output.","name":"output_false","typeAttr":"T"},{"description":"If `pred` is true, data will be forwarded to this output.","name":"output_true","typeAttr":"T"}],"summary":"Forwards `data` to the output port determined by `pred`."}},{"name":"SymbolicGradient","schema":{"attributes":[{"description":"the type list for the input list.","minimum":1,"name":"Tin","type":"type[]"},{"description":"the type list for the input list.","minimum":1,"name":"Tout","type":"type[]"},{"description":"The function we want to compute the gradient for.\n\nThe function 'f' must be a numerical function which takes N inputs and\nproduces M outputs. Its gradient function 'g', which is computed by\nthis SymbolicGradient op is a function taking N + M inputs and\nproduces N outputs.\n\nI.e. if we have\n (y1, y2, ..., y_M) = f(x1, x2, ..., x_N),\nthen, g is\n (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N,\n dL/dy1, dL/dy2, ..., dL/dy_M),\n\nwhere L is a scalar-value function of (x1, x2, ..., xN) (e.g., the\nloss function). dL/dx_i is the partial derivative of L with respect\nto x_i.\n\n(Needs some math expert to say the comment above better.)","name":"f","type":"function"}],"inputs":[{"description":"a list of input tensors of size N + M;","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"a list of output tensors of size N;","name":"output","typeListAttr":"Tout"}],"summary":"Computes the gradient function for function f via backpropagation."}},{"name":"TFRecordDataset","schema":{"inputs":[{"description":"A scalar or vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7},{"description":"A scalar representing the number of bytes to buffer. A value of\n0 means no buffering will be performed.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the records from one or more TFRecord files."}},{"name":"TFRecordReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","name":"compression_type","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the records from a TensorFlow Records file."}},{"name":"TFRecordReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","name":"compression_type","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the records from a TensorFlow Records file."}},{"name":"TPUCompilationResult","schema":{"description":"This operation returns the result of a TPU compilation as a serialized\nCompilationResultProto, which holds a status and an error message if an error\noccurred during compilation.","outputs":[{"name":"output","type":7}],"summary":"Returns the result of a TPU compilation."}},{"name":"TPUCompile","schema":{"attributes":[{"minimum":0,"name":"num_computations","type":"int64"},{"name":"function","type":"function"},{"name":"metadata","type":"string"},{"minimum":0,"name":"NumDynamicShapes","type":"int64"},{"minimum":0,"name":"Tguaranteed_constants","type":"type[]"}],"description":"For the internal use of the distributed TPU compiler.\n\n'num_computations' is the number of computations to be compiled.\n'function' is a function containing the computation to compile.\n'dynamic_shapes' contains dynamic shapes of arguments whose shapes were not\nknown statically at TPUReplication rewrite time.\n'guaranteed_constants' is a list of tensors which have been guaranteed to not\nchange their values during the session lifetime. These contain tensors marked as\nconstant using the GuaranteeConstOp.\n'metadata' is a serialized TPUCompileMetadataProto describing\nthe shapes and types of the inputs to the computation, as well as a mapping onto\nthe TPU pod topology.\nEach 'program' output is a string key that is passed to the _TPUExecute op and\nused to look up the program in the compilation cache.\n'may_modify_variables' indicates whether variables may be modified.","inputs":[{"name":"dynamic_shapes","numberAttr":"NumDynamicShapes","type":9},{"name":"guaranteed_constants","typeListAttr":"Tguaranteed_constants"}],"outputs":[{"name":"compilation_status","type":7},{"name":"program","numberAttr":"num_computations","type":7},{"name":"may_modify_variables","numberAttr":"num_computations","type":10}],"summary":"Compiles a computations for execution on one or more TPU devices."}},{"name":"TPUCompileSucceededAssert","schema":{"description":"device during failure to ensure all pending device interactions fail.\n\n'compilation_status' is a serialized CompilationResultProto.","inputs":[{"name":"compilation_status","type":7}],"summary":"Asserts that compilation succeeded. This op produces no output and closes the"}},{"name":"TPUEmbeddingActivations","schema":{"attributes":[{"description":"The id of the table in the embedding layer configuration from which\nthese activations were computed.","minimum":0,"name":"table_id","type":"int64"},{"description":"Identifier of the set of embedding indices which produced these\nactivations.","minimum":0,"name":"lookup_id","type":"int64"}],"description":"This op simply returns its first input, which is assumed to have been sliced\nfrom the Tensors returned by TPUEmbeddingDequeueActivations. The presence of\nthis op, and its first argument being a trainable Variable, enables automatic\ndifferentiation of graphs containing embeddings via the TPU Embedding Python\nlibraries.","inputs":[{"description":"A trainable variable, enabling optimizers to find this op.","name":"embedding_variable","type":1},{"description":"The embedding activations Tensor to return.","name":"sliced_activations","type":1}],"outputs":[{"name":"output","type":1}],"summary":"An op enabling differentiation of TPU Embeddings."}},{"name":"TPUExecute","schema":{"attributes":[{"minimum":0,"name":"Targs","type":"type[]"},{"minimum":0,"name":"Tresults","type":"type[]"}],"description":"For the internal use of the distributed TPU compiler.","inputs":[{"name":"args","typeListAttr":"Targs"},{"name":"key","type":7}],"outputs":[{"name":"results","typeListAttr":"Tresults"}],"summary":"Op that loads and executes a TPU program on a TPU device."}},{"name":"TPUExecuteAndUpdateVariables","schema":{"attributes":[{"minimum":0,"name":"Targs","type":"type[]"},{"minimum":0,"name":"Tresults","type":"type[]"},{"minimum":0,"name":"device_var_reads_indices","type":"int64[]"},{"minimum":0,"name":"device_var_updates_indices","type":"int64[]"}],"description":"It (optionally) reads device variables, loads and executes a TPU program on a\nTPU device, and then (optionally) in-place updates variables using the program\noutputs, as specified in attributes device_var_reads_indices (program input\nindices from directly reading variables) and device_var_updates_indices (program\noutput indices used to update variables, -1 means no-update/read-only). Such\nprogram outputs are consumed by these variables will not appear in the op\noutput. For the internal use of the distributed TPU compiler.","inputs":[{"name":"args","typeListAttr":"Targs"},{"name":"key","type":7}],"outputs":[{"name":"results","typeListAttr":"Tresults"}],"summary":"Op that executes a program with optional in-place variable updates."}},{"name":"TPUOrdinalSelector","schema":{"description":"This Op produces a set of TPU cores (for warm-up) or a single TPU core\n(for regular inference) to execute the TPU program on. The output is\nconsumed by TPUPartitionedCall.","outputs":[{"description":"A vector 1 or more TPU cores.","name":"device_ordinals","type":3}],"summary":"A TPU core selector Op."}},{"name":"TPUPartitionedCall","schema":{"attributes":[{"description":"The types of the arguments to the function.","minimum":0,"name":"Tin","type":"type[]"},{"description":"The types of the outputs of the function.","minimum":0,"name":"Tout","type":"type[]"},{"description":"The function to call.","name":"f","type":"function"},{"default":0,"name":"autotuner_thresh","type":"int64"}],"inputs":[{"description":"The arguments to the function.","name":"args","typeListAttr":"Tin"},{"description":"The TPU device ordinal to run the function on.","name":"device_ordinal","type":3}],"outputs":[{"description":"The output of the function call.","name":"output","typeListAttr":"Tout"}],"summary":"Calls a function placed on a specified TPU device."}},{"name":"TPUPartitionedInput","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"An integer describles which dimension is partitioned. -1 means\nthose inputs are replicated.","name":"partition_dim","type":"int64"}],"inputs":[{"description":"A list of partitioned inputs which must have the same shape.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"A handle which represents the full shape of partitioned tensors.","name":"output","typeAttr":"T"}],"summary":"An op that groups a list of partitioned inputs together. This op"}},{"name":"TPUPartitionedOutput","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"num_splits","type":"int64"},{"default":0,"description":"An integer describles which dimension is partitioned.","name":"partition_dim","type":"int64"}],"description":"outputs outside the XLA computation.","inputs":[{"description":"A tensor which represents the full shape of partitioned tensors.","name":"inputs","typeAttr":"T"}],"outputs":[{"description":"A list of partitioned inputs which must have the same shape.","name":"output","numberAttr":"num_splits","typeAttr":"T"}],"summary":"An op that demultiplexes a tensor to be sharded by XLA to a list of partitioned"}},{"name":"TPUReplicateMetadata","schema":{"attributes":[{"description":"Number of replicas of the computation","minimum":0,"name":"num_replicas","type":"int64"},{"default":1,"description":"Number of cores per replica. Used for model parallelism.","name":"num_cores_per_replica","type":"int64"},{"default":"","description":"TopologyProto indicating the topology of the TPU pod slice.","name":"topology","type":"string"},{"default":true,"description":"Whether to place the computation on the TPU.","name":"use_tpu","type":"boolean"},{"default":[],"description":"The assignment of devices for the computation.","name":"device_assignment","type":"int64[]"},{"default":[],"description":"DEPRECATED. Use num_cores_per_replica instead.","name":"computation_shape","type":"int64[]"},{"default":[],"name":"host_compute_core","type":"string[]"},{"default":[],"name":"padding_map","type":"string[]"},{"default":"STEP_MARK_AT_ENTRY","name":"step_marker_location","type":"string"},{"default":false,"name":"allow_soft_placement","type":"boolean"},{"default":false,"name":"use_spmd_for_xla_partitioning","type":"boolean"}],"description":"This operation holds the metadata common to operations of a `tpu.replicate()` computation subgraph.","summary":"Metadata indicating how the TPU computation should be replicated."}},{"name":"TPUReplicatedInput","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":false,"name":"is_mirrored_variable","type":"boolean"},{"default":-1,"name":"index","type":"int64"},{"default":false,"name":"is_packed","type":"boolean"}],"description":"This operation holds a replicated input to a `tpu.replicate()` computation subgraph.\nEach replicated input has the same shape and type alongside the output.\n\nFor example:\n```\n%a = \"tf.opA\"()\n%b = \"tf.opB\"()\n%replicated_input = \"tf.TPUReplicatedInput\"(%a, %b)\n%computation = \"tf.Computation\"(%replicated_input)\n```\nThe above computation has a replicated input of two replicas.","inputs":[{"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Connects N inputs to an N-way replicated TPU computation."}},{"name":"TPUReplicatedOutput","schema":{"attributes":[{"minimum":1,"name":"num_replicas","type":"int64"},{"name":"T","type":"type"}],"description":"This operation holds a replicated output from a `tpu.replicate()` computation subgraph.\nEach replicated output has the same shape and type alongside the input.\n\nFor example:\n```\n%computation = \"tf.Computation\"()\n%replicated_output:2 = \"tf.TPUReplicatedOutput\"(%computation)\n```\nThe above computation has a replicated output of two replicas.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"outputs","numberAttr":"num_replicas","typeAttr":"T"}],"summary":"Connects N outputs from an N-way replicated TPU computation."}},{"name":"TakeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements from the `input_dataset`\nthat should be taken. A value of `-1` indicates that all of `input_dataset`\nis taken.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains `count` elements from the `input_dataset`."}},{"name":"TakeManySparseFromTensorsMap","schema":{"attributes":[{"description":"The `dtype` of the `SparseTensor` objects stored in the\n`SparseTensorsMap`.","name":"dtype","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` read by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` read by this op.\nIt should not be blank; rather the `shared_name` or unique Operation name\nof the Op that created the original `SparseTensorsMap` should be used.","name":"shared_name","type":"string"}],"description":"The input `sparse_handles` must be an `int64` matrix of shape `[N, 1]` where\n`N` is the minibatch size and the rows correspond to the output handles of\n`AddSparseToTensorsMap` or `AddManySparseToTensorsMap`. The ranks of the\noriginal `SparseTensor` objects that went into the given input ops must all\nmatch. When the final `SparseTensor` is created, it has rank one\nhigher than the ranks of the incoming `SparseTensor` objects\n(they have been concatenated along a new row dimension on the left).\n\nThe output `SparseTensor` object's shape values for all dimensions but the\nfirst are the max across the input `SparseTensor` objects' shape values\nfor the corresponding dimensions. Its first shape value is `N`, the minibatch\nsize.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the handles represent an input, which is a `[2, 3]` matrix\nrepresenting two original `SparseTensor` objects:\n\n```\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n```\n\nand\n\n```\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n```\n\nthen the final `SparseTensor` will be:\n\n```\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]\n```","inputs":[{"description":"1-D, The `N` serialized `SparseTensor` objects.\nShape: `[N]`.","name":"sparse_handles","type":9}],"outputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"dtype"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.","name":"sparse_shape","type":9}],"summary":"Read `SparseTensors` from a `SparseTensorsMap` and concatenate them."}},{"name":"TakeWhileDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that stops iteration when predicate` is false."}},{"name":"Tan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes tangent of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `(-inf, inf)`. If input lies outside the boundary, `nan`\n is returned.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.tan(x) ==> [nan 0.45231566 -0.5463025 1.5574077 2.572152 -1.7925274 0.32097113 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes tan of x element-wise."}},{"name":"Tanh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic tangent of every\n element in the tensor. Input range is `[-inf, inf]` and\n output range is `[-1,1]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -5, -0.5, 1, 1.2, 2, 3, float(\"inf\")])\n tf.math.tanh(x) ==> [-1. -0.99990916 -0.46211717 0.7615942 0.8336547 0.9640276 0.9950547 1.]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic tangent of `x` element-wise."}},{"name":"TanhGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * (1 - y*y)`, where `y = tanh(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the tanh of `x` wrt its input."}},{"name":"TemporaryVariable","schema":{"attributes":[{"description":"The shape of the variable tensor.","name":"shape","type":"shape"},{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"},{"default":"","description":"Overrides the name used for the temporary variable resource. Default\nvalue is the name of the 'TemporaryVariable' op (which is guaranteed unique).","name":"var_name","type":"string"}],"description":"This is an experimental op for internal use only and it is possible to use this\nop in unsafe ways. DO NOT USE unless you fully understand the risks.\n\nIt is the caller's responsibility to ensure that 'ref' is eventually passed to a\nmatching 'DestroyTemporaryVariable' op after all other uses have completed.\n\nOutputs a ref to the tensor state so it may be read or modified.\n\n E.g.\n var = state_ops._temporary_variable([1, 2], types.float_)\n var_name = var.op.name\n var = state_ops.assign(var, [[4.0, 5.0]])\n var = state_ops.assign_add(var, [[6.0, 7.0]])\n final = state_ops._destroy_temporary_variable(var, var_name=var_name)","outputs":[{"description":"A reference to the variable tensor.","isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Returns a tensor that may be mutated, but only persists within a single step."}},{"name":"TensorArray","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":false,"name":"dynamic_size","type":"boolean"},{"default":true,"name":"clear_after_read","type":"boolean"},{"default":"","name":"tensor_array_name","type":"string"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"name":"size","type":3}],"outputs":[{"isRef":true,"name":"handle","type":7}]}},{"name":"TensorArrayClose","schema":{"inputs":[{"isRef":true,"name":"handle","type":7}]}},{"name":"TensorArrayCloseV2","schema":{"inputs":[{"name":"handle","type":7}],"summary":"Deprecated. Use TensorArrayCloseV3"}},{"name":"TensorArrayCloseV3","schema":{"description":"This enables the user to close and release the resource in the middle\nof a step/run.","inputs":[{"description":"The handle to a TensorArray (output of TensorArray or TensorArrayGrad).","name":"handle","type":20}],"summary":"Delete the TensorArray from its resource container."}},{"name":"TensorArrayConcat","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape_except0","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"},{"name":"lengths","type":9}]}},{"name":"TensorArrayConcatV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape_except0","type":"shape"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"},{"name":"lengths","type":9}],"summary":"Deprecated. Use TensorArrayConcatV3"}},{"name":"TensorArrayConcatV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known,\nexcluding the first dimension. Used to validate the shapes of\nTensorArray elements. If this shape is not fully specified, concatenating\nzero-size TensorArrays is an error.","name":"element_shape_except0","type":"shape"}],"description":"Takes `T` elements of shapes\n\n ```\n (n0 x d0 x d1 x ...), (n1 x d0 x d1 x ...), ..., (n(T-1) x d0 x d1 x ...)\n ```\n\nand concatenates them into a Tensor of shape:\n\n ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)```\n\nAll elements must have the same shape (excepting the first dimension).","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"All of the elements in the TensorArray, concatenated along the first\naxis.","name":"value","typeAttr":"dtype"},{"description":"A vector of the row sizes of the original T elements in the\nvalue output. In the example above, this would be the values:\n`(n1, n2, ..., n(T-1))`.","name":"lengths","type":9}],"summary":"Concat the elements from the TensorArray into value `value`."}},{"name":"TensorArrayGather","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"indices","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayGatherV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"name":"handle","type":7},{"name":"indices","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Deprecated. Use TensorArrayGatherV3"}},{"name":"TensorArrayGatherV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known. Used to\nvalidate the shapes of TensorArray elements. If this shape is not\nfully specified, gathering zero-size TensorArrays is an error.","name":"element_shape","type":"shape"}],"description":"All elements selected by `indices` must have the same shape.","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The locations in the TensorArray from which to read tensor elements.","name":"indices","type":3},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"All of the elements in the TensorArray, concatenated along a new\naxis (the new dimension 0).","name":"value","typeAttr":"dtype"}],"summary":"Gather specific elements from the TensorArray into output `value`."}},{"name":"TensorArrayGrad","schema":{"attributes":[{"name":"source","type":"string"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"isRef":true,"name":"grad_handle","type":7}]}},{"name":"TensorArrayGradV2","schema":{"attributes":[{"name":"source","type":"string"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"grad_handle","type":7}],"summary":"Deprecated. Use TensorArrayGradV3"}},{"name":"TensorArrayGradV3","schema":{"attributes":[{"description":"The gradient source string, used to decide which gradient TensorArray\nto return.","name":"source","type":"string"}],"description":"If the given TensorArray gradient already exists, returns a reference to it.\n\nLocks the size of the original TensorArray by disabling its dynamic size flag.\n\n**A note about the input flow_in:**\n\nThe handle flow_in forces the execution of the gradient lookup to occur\nonly after certain other operations have occurred. For example, when\nthe forward TensorArray is dynamically sized, writes to this TensorArray\nmay resize the object. The gradient TensorArray is statically sized based\non the size of the forward TensorArray when this operation executes.\nFurthermore, the size of the forward TensorArray is frozen by this call.\nAs a result, the flow is used to ensure that the call to generate the gradient\nTensorArray only happens after all writes are executed.\n\nIn the case of dynamically sized TensorArrays, gradient computation should\nonly be performed on read operations that have themselves been chained via\nflow to occur only after all writes have executed. That way the final size\nof the forward TensorArray is known when this operation is called.\n\n**A note about the source attribute:**\n\nTensorArray gradient calls use an accumulator TensorArray object. If\nmultiple gradients are calculated and run in the same session, the multiple\ngradient nodes may accidentally flow through the same accumulator TensorArray.\nThis double counts and generally breaks the TensorArray gradient flow.\n\nThe solution is to identify which gradient call this particular\nTensorArray gradient is being called in. This is performed by identifying\na unique string (e.g. \"gradients\", \"gradients_1\", ...) from the input\ngradient Tensor's name. This string is used as a suffix when creating\nthe TensorArray gradient object here (the attribute `source`).\n\nThe attribute `source` is added as a suffix to the forward TensorArray's\nname when performing the creation / lookup, so that each separate gradient\ncalculation gets its own TensorArray accumulator.","inputs":[{"description":"The handle to the forward TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"name":"grad_handle","type":20},{"name":"flow_out","type":1}],"summary":"Creates a TensorArray for storing the gradients of values in the given handle."}},{"name":"TensorArrayGradWithShape","schema":{"attributes":[{"description":"The gradient source string, used to decide which gradient TensorArray\nto return.","name":"source","type":"string"}],"description":"Similar to TensorArrayGradV3. However it creates an accumulator with an\nexpanded shape compared to the input TensorArray whose gradient is being\ncomputed. This enables multiple gradients for the same TensorArray to be\ncalculated using the same accumulator.","inputs":[{"description":"The handle to the forward TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1},{"description":"An int32 vector representing a shape. Elements in the gradient accumulator will\nhave shape which is this shape_to_prepend value concatenated with shape of the\nelements in the TensorArray corresponding to the input handle.","name":"shape_to_prepend","type":3}],"outputs":[{"name":"grad_handle","type":20},{"name":"flow_out","type":1}],"summary":"Creates a TensorArray for storing multiple gradients of values in the given handle."}},{"name":"TensorArrayPack","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayRead","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"index","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayReadV2","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"index","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Deprecated. Use TensorArrayReadV3"}},{"name":"TensorArrayReadV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"}],"inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"name":"index","type":3},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"The tensor that is read from the TensorArray.","name":"value","typeAttr":"dtype"}],"summary":"Read an element from the TensorArray into output `value`."}},{"name":"TensorArrayScatter","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"indices","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayScatterV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"indices","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArrayScatterV3"}},{"name":"TensorArrayScatterV3","schema":{"attributes":[{"name":"T","type":"type"}],"description":"`indices` must be a vector, its length must match the first dim of `value`.","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The locations at which to write the tensor elements.","name":"indices","type":3},{"description":"The concatenated tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Scatter the data from the input value into specific TensorArray elements."}},{"name":"TensorArraySize","schema":{"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"size","type":3}]}},{"name":"TensorArraySizeV2","schema":{"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"size","type":3}],"summary":"Deprecated. Use TensorArraySizeV3"}},{"name":"TensorArraySizeV3","schema":{"inputs":[{"description":"The handle to a TensorArray (output of TensorArray or TensorArrayGrad).","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"The current size of the TensorArray.","name":"size","type":3}],"summary":"Get the current size of the TensorArray."}},{"name":"TensorArraySplit","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"lengths","type":9},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArraySplitV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"lengths","type":9},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArraySplitV3"}},{"name":"TensorArraySplitV3","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Assuming that `lengths` takes on values\n\n ```(n0, n1, ..., n(T-1))```\n\nand that `value` has shape\n\n ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)```,\n\nthis splits values into a TensorArray with T tensors.\n\nTensorArray index t will be the subtensor of values with starting position\n\n ```(n0 + n1 + ... + n(t-1), 0, 0, ...)```\n\nand having size\n\n ```nt x d0 x d1 x ...```","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The concatenated tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"The vector of lengths, how to split the rows of value into the\nTensorArray.","name":"lengths","type":9},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Split the data from the input value into TensorArray elements."}},{"name":"TensorArrayUnpack","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"},{"default":false,"name":"dynamic_size","type":"boolean"},{"default":true,"name":"clear_after_read","type":"boolean"},{"default":"","name":"tensor_array_name","type":"string"}],"inputs":[{"name":"size","type":3}],"outputs":[{"name":"handle","type":7}],"summary":"Deprecated. Use TensorArrayV3"}},{"name":"TensorArrayV3","schema":{"attributes":[{"description":"The type of the elements on the tensor_array.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known. Used to\nvalidate the shapes of TensorArray elements. If this shape is not\nfully specified, gathering zero-size TensorArrays is an error.","name":"element_shape","type":"shape"},{"default":false,"description":"A boolean that determines whether writes to the TensorArray\nare allowed to grow the size. By default, this is not allowed.","name":"dynamic_size","type":"boolean"},{"default":true,"description":"If true (default), Tensors in the TensorArray are cleared\nafter being read. This disables multiple read semantics but allows early\nrelease of memory.","name":"clear_after_read","type":"boolean"},{"default":false,"description":"If true (default is false), then all\nelements in the TensorArray will be expected to have have identical shapes.\nThis allows certain behaviors, like dynamically checking for\nconsistent shapes on write, and being able to fill in properly\nshaped zero tensors on stack -- even if the element_shape attribute\nis not fully defined.","name":"identical_element_shapes","type":"boolean"},{"default":"","description":"Overrides the name used for the temporary tensor_array\nresource. Default value is the name of the 'TensorArray' op (which\nis guaranteed unique).","name":"tensor_array_name","type":"string"}],"description":"Write data via Write and read via Read or Pack.","inputs":[{"description":"The size of the array.","name":"size","type":3}],"outputs":[{"description":"The handle to the TensorArray.","name":"handle","type":20},{"description":"A scalar used to control gradient flow.","name":"flow","type":1}],"summary":"An array of Tensors of given size."}},{"name":"TensorArrayWrite","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"index","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayWriteV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"index","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArrayGradV3"}},{"name":"TensorArrayWriteV3","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The position to write to inside the TensorArray.","name":"index","type":3},{"description":"The tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Push an element onto the tensor_array."}},{"name":"TensorDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits `components` as a tuple of tensors once."}},{"name":"TensorForestCreateTreeVariable","schema":{"inputs":[{"description":"Handle to the tree resource to be created.","name":"tree_handle","type":20},{"description":"Serialized proto string of the boosted_trees.Tree.","name":"tree_config","type":7}],"summary":"Creates a tree resource and returns a handle to it."}},{"name":"TensorForestTreeDeserialize","schema":{"inputs":[{"description":"Handle to the tree resource to be restored.","name":"tree_handle","type":20},{"description":"Serialied proto string of the boosted_trees.Tree proto.","name":"tree_config","type":7}],"summary":"Deserializes a proto into the tree handle"}},{"name":"TensorForestTreeIsInitializedOp","schema":{"inputs":[{"description":"Handle to the tree.","name":"tree_handle","type":20}],"outputs":[{"description":"Whether the tree is initialized.","name":"is_initialized","type":10}],"summary":"Checks whether a tree has been initialized."}},{"name":"TensorForestTreePredict","schema":{"attributes":[{"description":"Scalar, dimension of the logits.","name":"logits_dimension","type":"int64"}],"inputs":[{"description":"Handle to the tree resource.","name":"tree_handle","type":20},{"description":"Rank 2 dense features tensor.","name":"dense_features","type":1}],"outputs":[{"description":"The logits predictions from the tree for each instance in the batch.","name":"logits","type":1}],"summary":"Output the logits for the given input data"}},{"name":"TensorForestTreeResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a TensorForestTreeResource"}},{"name":"TensorForestTreeSerialize","schema":{"inputs":[{"description":"Handle to the tree resource to be serialized.","name":"tree_handle","type":20}],"outputs":[{"description":"Serialied proto string of the tree resource.","name":"tree_config","type":7}],"summary":"Serializes the tree handle to a proto"}},{"name":"TensorForestTreeSize","schema":{"inputs":[{"description":"Handle to the tree resource.","name":"tree_handle","type":20}],"outputs":[{"description":"The size of the tree.","name":"tree_size","type":3}],"summary":"Get the number of nodes in a tree"}},{"name":"TensorListConcat","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"description":"Requires that all tensors have the same shape except the first dimension.\n\ninput_handle: The input list.\ntensor: The concated result.\nlengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient.\n","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"lengths","type":9}],"summary":"Concats all tensors in the list along the 0th dimension."}},{"name":"TensorListConcatLists","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_a","type":21},{"name":"input_b","type":21}],"outputs":[{"name":"output","type":21}]}},{"name":"TensorListConcatV2","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Requires that all tensors have the same shape except the first dimension.\n\ninput_handle: The input list.\nelement_shape: The shape of the uninitialized elements in the list. If the first\n dimension is not -1, it is assumed that all list elements have the same\n leading dim.\nleading_dims: The list of leading dims of uninitialized list elements. Used if\n the leading dim of input_handle.element_shape or the element_shape input arg\n is not already set.\ntensor: The concated result.\nlengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient.\n","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","typeAttr":"shape_type"},{"name":"leading_dims","type":9}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"lengths","type":9}],"summary":"Concats all tensors in the list along the 0th dimension."}},{"name":"TensorListElementShape","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":" input_handle: the list\n element_shape: the shape of elements of the list","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"element_shape","typeAttr":"shape_type"}],"summary":"The shape of the elements of the given list, as a tensor."}},{"name":"TensorListFromTensor","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each tensor in the result list corresponds to one row of the input tensor.\n\ntensor: The input tensor.\noutput_handle: The list.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"element_shape","typeAttr":"shape_type"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList which, when stacked, has the value of `tensor`."}},{"name":"TensorListGather","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Each row in the produced Tensor corresponds to the element in the TensorList\nspecified by the given index (see `tf.gather`).\n\ninput_handle: The input tensor list.\nindices: The indices used to index into the list.\nvalues: The tensor.","inputs":[{"name":"input_handle","type":21},{"name":"indices","type":3},{"name":"element_shape","type":3}],"outputs":[{"name":"values","typeAttr":"element_dtype"}],"summary":"Creates a Tensor by indexing into the TensorList."}},{"name":"TensorListGetItem","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_handle","type":21},{"name":"index","type":3},{"name":"element_shape","type":3}],"outputs":[{"name":"item","typeAttr":"element_dtype"}]}},{"name":"TensorListLength","schema":{"description":"input_handle: the input list\nlength: the number of tensors in the list","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"length","type":3}],"summary":"Returns the number of tensors in the input tensor list."}},{"name":"TensorListPopBack","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Fails if the list is empty.\n\ninput_handle: the input list\ntensor: the withdrawn last element of the list\nelement_dtype: the type of elements in the list\nelement_shape: the shape of the output tensor","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","type":3}],"outputs":[{"name":"output_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"summary":"Returns the last element of the input list as well as a list with all but that element."}},{"name":"TensorListPushBack","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"tensor: The tensor to put on the list.\ninput_handle: The old list.\noutput_handle: A list with the elements of the old list followed by tensor.\nelement_dtype: the type of elements in the list.\nelement_shape: a shape compatible with that of elements in the list.","inputs":[{"name":"input_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Returns a list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`."}},{"name":"TensorListPushBackBatch","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_handles","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handles","type":21}]}},{"name":"TensorListReserve","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"element_shape: the shape of the future elements of the list\nnum_elements: the number of elements to reserve\nhandle: the output list\nelement_dtype: the desired type of elements in the list.","inputs":[{"name":"element_shape","typeAttr":"shape_type"},{"name":"num_elements","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"List of the given size with empty elements."}},{"name":"TensorListResize","schema":{"description":"\ninput_handle: the input list\nsize: size of the output list\n","inputs":[{"name":"input_handle","type":21},{"name":"size","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Resizes the list."}},{"name":"TensorListScatter","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ntensor: The input tensor.\nindices: The indices used to index into the list.\nelement_shape: The shape of the elements in the list (can be less specified than\n the shape of the tensor).\noutput_handle: The TensorList.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3},{"name":"element_shape","typeAttr":"shape_type"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList by indexing into a Tensor."}},{"name":"TensorListScatterIntoExistingList","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ninput_handle: The list to scatter into.\ntensor: The input tensor.\nindices: The indices used to index into the list.\noutput_handle: The TensorList.","inputs":[{"name":"input_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Scatters tensor at indices in an input list."}},{"name":"TensorListScatterV2","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ntensor: The input tensor.\nindices: The indices used to index into the list.\nelement_shape: The shape of the elements in the list (can be less specified than\n the shape of the tensor).\nnum_elements: The size of the output list. Must be large enough to accommodate\n the largest index in indices. If -1, the list is just large enough to include\n the largest index in indices.\noutput_handle: The TensorList.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3},{"name":"element_shape","typeAttr":"shape_type"},{"name":"num_elements","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList by indexing into a Tensor."}},{"name":"TensorListSetItem","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"input_handle: the list\nindex: the position in the list to which the tensor will be assigned\nitem: the element to be assigned to that position\noutput_handle: the new list, with the element in the proper position\n","inputs":[{"name":"input_handle","type":21},{"name":"index","type":3},{"name":"item","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Sets the index-th position of the list to contain the given tensor."}},{"name":"TensorListSplit","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"list[i] corresponds to lengths[i] tensors from the input tensor.\nThe tensor must have rank at least 1 and contain exactly sum(lengths) elements.\n\ntensor: The input tensor.\nelement_shape: A shape compatible with that of elements in the tensor.\nlengths: Vector of sizes of the 0th dimension of tensors in the list.\noutput_handle: The list.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"element_shape","typeAttr":"shape_type"},{"name":"lengths","type":9}],"outputs":[{"name":"output_handle","type":21}],"summary":"Splits a tensor into a list."}},{"name":"TensorListStack","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"default":-1,"name":"num_elements","type":"int64"}],"description":"Requires that all tensors have the same shape.\n\ninput_handle: the input list\ntensor: the gathered result\nnum_elements: optional. If not -1, the number of elements in the list.\n","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","type":3}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"}],"summary":"Stacks all tensors in the list."}},{"name":"TensorScatterAdd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by adding sparse `updates` to the passed\nin `tensor`.\nThis operation is very similar to `tf.scatter_nd_add`, except that the updates\nare added onto an existing tensor (as opposed to a variable). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`tensor.shape`. The last dimension of `indices` can be at most the rank of\n`tensor.shape`:\n\n indices.shape[-1] <= tensor.shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = tensor.shape.rank`) or slices\n(if `indices.shape[-1] < tensor.shape.rank`) along dimension\n`indices.shape[-1]` of `tensor.shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + tensor.shape[indices.shape[-1]:]\n\nThe simplest form of tensor_scatter_add is to add individual elements to a\ntensor by index. For example, say we want to add 4 elements in a rank-1\ntensor with 8 elements.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n tensor = tf.ones([8], dtype=tf.int32)\n updated = tf.tensor_scatter_nd_add(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [1, 12, 1, 11, 10, 1, 1, 13]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n tensor = tf.ones([4, 4, 4],dtype=tf.int32)\n updated = tf.tensor_scatter_nd_add(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [[[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],\n [[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor and updates added according to the indices.","name":"output","typeAttr":"T"}],"summary":"Adds sparse `updates` to an existing tensor according to `indices`."}},{"name":"TensorScatterMax","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"description":"Tensor to update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor whose values are element-wise maximum between tensor and updates according to the indices.","name":"output","typeAttr":"T"}]}},{"name":"TensorScatterMin","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"description":"Tensor to update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor whose values are element-wise minimum between tensor and updates according to the indices.","name":"output","typeAttr":"T"}]}},{"name":"TensorScatterSub","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by subtracting sparse `updates` from the\npassed in `tensor`.\nThis operation is very similar to `tf.scatter_nd_sub`, except that the updates\nare subtracted from an existing tensor (as opposed to a variable). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of tensor_scatter_sub is to subtract individual elements\nfrom a tensor by index. For example, say we want to insert 4 scattered elements\nin a rank-1 tensor with 8 elements.\n\nIn Python, this scatter subtract operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n tensor = tf.ones([8], dtype=tf.int32)\n updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [1, -10, 1, -9, -8, 1, 1, -11]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n tensor = tf.ones([4, 4, 4],dtype=tf.int32)\n updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],\n [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor and updates subtracted according to the indices.","name":"output","typeAttr":"T"}],"summary":"Subtracts sparse `updates` from an existing tensor according to `indices`."}},{"name":"TensorScatterUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by applying sparse `updates` to the passed\nin `tensor`.\nThis operation is very similar to `tf.scatter_nd`, except that the updates are\nscattered onto an existing tensor (as opposed to a zero-tensor). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\nIf `indices` contains duplicates, then their updates are accumulated (summed).\n\n**WARNING**: The order in which updates are applied is nondeterministic, so the\noutput will be nondeterministic if `indices` contains duplicates -- because\nof some numerical approximation issues, numbers summed in different order\nmay yield different results.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of scatter is to insert individual elements in a tensor by\nindex. For example, say we want to insert 4 scattered elements in a rank-1\ntensor with 8 elements.\n\n
\n\n
\n\nIn Python, this scatter operation would look like this:\n\n >>> indices = tf.constant([[4], [3], [1], [7]])\n >>> updates = tf.constant([9, 10, 11, 12])\n >>> tensor = tf.ones([8], dtype=tf.int32)\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates))\n tf.Tensor([ 1 11 1 10 9 1 1 12], shape=(8,), dtype=int32)\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter operation would look like this:\n\n >>> indices = tf.constant([[0], [2]])\n >>> updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n ... [7, 7, 7, 7], [8, 8, 8, 8]],\n ... [[5, 5, 5, 5], [6, 6, 6, 6],\n ... [7, 7, 7, 7], [8, 8, 8, 8]]])\n >>> tensor = tf.ones([4, 4, 4], dtype=tf.int32)\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates).numpy())\n [[[5 5 5 5]\n [6 6 6 6]\n [7 7 7 7]\n [8 8 8 8]]\n [[1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]]\n [[5 5 5 5]\n [6 6 6 6]\n [7 7 7 7]\n [8 8 8 8]]\n [[1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor with the given shape and updates applied according\nto the indices.","name":"output","typeAttr":"T"}],"summary":"Scatter `updates` into an existing tensor according to `indices`."}},{"name":"TensorSliceDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits each dim-0 slice of `components` once."}},{"name":"TensorStridedSliceUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the tensor `input` that\nare selected by the slice parameters. The slice parameters `begin` `end`\n`strides` etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s shape\nmust be exactly the shape produced by the slice of `input`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `input`."}},{"name":"TensorSummary","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"A json-encoded SummaryDescription proto.","name":"description","type":"string"},{"default":[],"description":"An unused list of strings.","name":"labels","type":"string[]"},{"default":"","description":"An unused string.","name":"display_name","type":"string"}],"description":"This op is being phased out in favor of TensorSummaryV2, which lets callers pass\na tag as well as a serialized SummaryMetadata proto string that contains\nplugin-specific data. We will keep this op to maintain backwards compatibility.","inputs":[{"description":"A tensor to serialize.","name":"tensor","typeAttr":"T"}],"outputs":[{"name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a tensor."}},{"name":"TensorSummaryV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A string attached to this summary. Used for organization in TensorBoard.","name":"tag","type":7},{"description":"A tensor to serialize.","name":"tensor","typeAttr":"T"},{"description":"A serialized SummaryMetadata proto. Contains plugin\ndata.","name":"serialized_summary_metadata","type":7}],"outputs":[{"name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a tensor and per-plugin data."}},{"name":"TextLineDataset","schema":{"inputs":[{"description":"A scalar or a vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7},{"description":"A scalar containing the number of bytes to buffer.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the lines of one or more text files."}},{"name":"TextLineReader","schema":{"attributes":[{"default":0,"description":"Number of lines to skip from the beginning of every file.","name":"skip_header_lines","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the lines of a file delimited by '\\n'."}},{"name":"TextLineReaderV2","schema":{"attributes":[{"default":0,"description":"Number of lines to skip from the beginning of every file.","name":"skip_header_lines","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the lines of a file delimited by '\\n'."}},{"name":"ThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A resource produced by the ThreadPoolHandle op.","name":"thread_pool","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ThreadPoolHandle","schema":{"attributes":[{"description":"The number of threads in the thread pool.","name":"num_threads","type":"int64"},{"default":1,"description":"The maximum degree of parallelism to use within operations that execute on this\nthreadpool.","name":"max_intra_op_parallelism","type":"int64"},{"description":"A human-readable name for the threads that may be visible in some\nvisualizations.\nthreadpool.","name":"display_name","type":"string"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"description":"A resource that can be consumed by one or more ExperimentalThreadPoolDataset\nops.","name":"handle","type":20}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ThreadUnsafeUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"Tile","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tmultiples","type":"type"}],"description":"This operation creates a new tensor by replicating `input` `multiples` times.\nThe output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements,\nand the values of `input` are replicated `multiples[i]` times along the 'i'th\ndimension. For example, tiling `[a b c d]` by `[2]` produces\n`[a b c d a b c d]`.\n\n>>> a = tf.constant([[1,2,3],[4,5,6]], tf.int32)\n>>> b = tf.constant([1,2], tf.int32)\n>>> tf.tile(a, b)\n\n>>> c = tf.constant([2,1], tf.int32)\n>>> tf.tile(a, c)\n\n>>> d = tf.constant([2,2], tf.int32)\n>>> tf.tile(a, d)\n","inputs":[{"description":"1-D or higher.","name":"input","typeAttr":"T"},{"description":"1-D. Length must be the same as the number of dimensions in `input`","name":"multiples","typeAttr":"Tmultiples"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Constructs a tensor by tiling a given tensor."}},{"name":"TileGrad","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Since `Tile` takes an input and repeats the input `multiples` times\nalong each dimension, `TileGrad` takes in `multiples` and aggregates\neach repeated tile of `input` into `output`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"multiples","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the gradient of `Tile`."}},{"name":"Timestamp","schema":{"description":"Returns the timestamp as a `float64` for seconds since the Unix epoch.\n\nNote: the timestamp is computed when the op is executed, not when it is added\nto the graph.","outputs":[{"name":"ts","type":2}],"summary":"Provides the time since epoch in seconds."}},{"name":"ToBool","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Converts a tensor to a scalar predicate with the following rules:\n\n- For 0D tensors, truthiness is determined by comparing against a \"zero\"\n value. For numerical types it is the obvious zero. For strings it is the\n empty string.\n\n- For >0D tensors, truthiness is determined by looking at the number of\n elements. If has zero elements, then the result is false. Otherwise the\n result is true.\n\nThis matches the behavior of If and While for determining if a tensor counts\nas true/false for a branch condition.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":10}],"summary":"Converts a tensor to a scalar predicate."}},{"name":"TopK","schema":{"attributes":[{"description":"Number of top elements to look for along the last dimension (along each\nrow for matrices).","minimum":0,"name":"k","type":"int64"},{"default":true,"description":"If true the resulting `k` elements will be sorted by the values in\ndescending order.","name":"sorted","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the `k` largest entries in the vector\nand outputs their values and indices as vectors. Thus `values[j]` is the\n`j`-th largest entry in `input`, and its index is `indices[j]`.\n\nFor matrices (resp. higher rank input), computes the top `k` entries in each\nrow (resp. vector along the last dimension). Thus,\n\n values.shape = indices.shape = input.shape[:-1] + [k]\n\nIf two elements are equal, the lower-index element appears first.\n\nIf `k` varies dynamically, use `TopKV2` below.","inputs":[{"description":"1-D or higher with last dimension at least `k`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The `k` largest elements along each last dimensional slice.","name":"values","typeAttr":"T"},{"description":"The indices of `values` within the last dimension of `input`.","name":"indices","type":3}],"summary":"Finds values and indices of the `k` largest elements for the last dimension."}},{"name":"TopKUnique","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"running time is proportional to the product of K and the input\nsize. Sorting the whole array is more efficient for sufficiently large\nvalues of K. The median-of-medians algorithm is probably faster, but\ndifficult to implement efficiently in XLA. If there are fewer than K\nunique numbers (not NANs), the results are padded with negative\ninfinity. NaNs are never returned. Subnormal numbers are flushed to\nzero. If an element appears at multiple indices, the highest index is\nreturned. If a TopK element never appears in the input due to padding\nvalues, the indices are padded with negative one. If a padding value\nappears in the input and padding is needed, the highest index of the\npadding value will be returned. The semantics are not the same as\nkth_order_statistic.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"topk","type":1},{"name":"topk_indices","type":3}],"summary":"Returns the TopK unique values in the array in sorted order. The"}},{"name":"TopKV2","schema":{"attributes":[{"default":true,"description":"If true the resulting `k` elements will be sorted by the values in\ndescending order.","name":"sorted","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the `k` largest entries in the vector\nand outputs their values and indices as vectors. Thus `values[j]` is the\n`j`-th largest entry in `input`, and its index is `indices[j]`.\n\nFor matrices (resp. higher rank input), computes the top `k` entries in each\nrow (resp. vector along the last dimension). Thus,\n\n values.shape = indices.shape = input.shape[:-1] + [k]\n\nIf two elements are equal, the lower-index element appears first.","inputs":[{"description":"1-D or higher with last dimension at least `k`.","name":"input","typeAttr":"T"},{"description":"0-D. Number of top elements to look for along the last dimension (along each\nrow for matrices).","name":"k","type":3}],"outputs":[{"description":"The `k` largest elements along each last dimensional slice.","name":"values","typeAttr":"T"},{"description":"The indices of `values` within the last dimension of `input`.","name":"indices","type":3}],"summary":"Finds values and indices of the `k` largest elements for the last dimension."}},{"name":"TopKWithUnique","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"of MakeUnique and TopKUnique. The returned top-K will have its lower bits\nreplaced by iota, thus it will be close to the original value but not exactly\nthe same. The running time is proportional to the product of K and the input\nsize. NaNs are never returned. Subnormal numbers are flushed to zero.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"topk","type":1},{"name":"topk_indices","type":3}],"summary":"Returns the TopK values in the array in sorted order. This is a combination"}},{"name":"Transpose","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tperm","type":"type"}],"description":"The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy:\n `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]`","inputs":[{"name":"x","typeAttr":"T"},{"name":"perm","typeAttr":"Tperm"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Shuffle dimensions of x according to a permutation."}},{"name":"TridiagonalMatMul","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Calculates product of two matrices, where left matrix is a tridiagonal matrix.","inputs":[{"description":"Tensor of shape `[..., 1, M]`, representing superdiagonals of\ntri-diagonal matrices to the left of multiplication. Last element is ignored.","name":"superdiag","typeAttr":"T"},{"description":"Tensor of shape `[..., 1, M]`, representing main diagonals of tri-diagonal\nmatrices to the left of multiplication.","name":"maindiag","typeAttr":"T"},{"description":"Tensor of shape `[..., 1, M]`, representing subdiagonals of tri-diagonal\nmatrices to the left of multiplication. First element is ignored.","name":"subdiag","typeAttr":"T"},{"description":"Tensor of shape `[..., M, N]`, representing MxN matrices to the right of\nmultiplication.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Tensor of shape `[..., M, N]` containing the product.","name":"output","typeAttr":"T"}],"summary":"Calculate product with tridiagonal matrix."}},{"name":"TridiagonalSolve","schema":{"attributes":[{"default":true,"description":"Whether to apply partial pivoting. Partial pivoting makes the procedure more\nstable, but slower.","name":"partial_pivoting","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Solves tridiagonal systems of equations.\n Supports batch dimensions and multiple right-hand sides per each left-hand\n side.\n On CPU, solution is computed via Gaussian elimination with or without partial\n pivoting, depending on `partial_pivoting` attribute. On GPU, Nvidia's cuSPARSE\n library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv\n Partial pivoting is not yet supported by XLA backends.","inputs":[{"description":"Tensor of shape `[..., 3, M]` whose innermost 2 dimensions represent the\ntridiagonal matrices with three rows being the superdiagonal, diagonals, and\nsubdiagonals, in order. The last element of the superdiagonal and the first\nelement of the subdiagonal is ignored.","name":"diagonals","typeAttr":"T"},{"description":"Tensor of shape `[..., M, K]`, representing K right-hand sides per each\nleft-hand side.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Tensor of shape `[..., M, K]` containing the solutions","name":"output","typeAttr":"T"}],"summary":"Solves tridiagonal systems of equations."}},{"name":"TruncateDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Truncation designates that negative numbers will round fractional quantities\ntoward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different\nthan Python semantics. See `FloorDiv` for a division function that matches\nPython Semantics.\n\n*NOTE*: `TruncateDiv` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise for integer types."}},{"name":"TruncateMod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"the result here is consistent with a truncating divide. E.g. `truncate(x / y) *\ny + truncate_mod(x, y) = x`.\n\n*NOTE*: `TruncateMod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. This emulates C semantics in that"}},{"name":"TruncatedNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with random truncated normal\nvalues.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a truncated normal distribution."}},{"name":"TryRpc","schema":{"attributes":[{"default":"","description":"RPC protocol to use. Empty string means use the default protocol.\nOptions include 'grpc'.","name":"protocol","type":"string"},{"default":true,"description":"`boolean`. If `true` (default), then failures to connect\n(i.e., the server does not immediately respond) cause an RPC failure.","name":"fail_fast","type":"boolean"},{"default":0,"description":"`int`. If `0` (default), then the kernel will run the RPC\nrequest and only time out if the RPC deadline passes or the session times out.\nIf this value is greater than `0`, then the op will raise an exception if\nthe RPC takes longer than `timeout_in_ms`.","name":"timeout_in_ms","type":"int64"}],"description":"This op asynchronously performs either a single RPC request, or a batch\nof requests. RPC requests are defined by three main parameters:\n\n - `address` (the host+port or BNS address of the request)\n - `method` (the method name for the request)\n - `request` (the serialized proto string, or vector of strings,\n of the RPC request argument).\n\nFor example, if you have an RPC service running on port localhost:2345,\nand its interface is configured with the following proto declaration:\n\n```\nservice MyService {\n rpc MyMethod(MyRequestProto) returns (MyResponseProto) {\n }\n};\n```\n\nthen call this op with arguments:\n\n```\naddress = \"localhost:2345\"\nmethod = \"MyService/MyMethod\"\n```\n\nThe `request` tensor is a string tensor representing serialized `MyRequestProto`\nstrings; and the output string tensor `response` will have the same shape\nand contain (upon successful completion) corresponding serialized\n`MyResponseProto` strings.\n\nFor example, to send a single, empty, `MyRequestProto`, call\nthis op with `request = \"\"`. To send 5 **parallel** empty requests,\ncall this op with `request = [\"\", \"\", \"\", \"\", \"\"]`.\n\nMore generally, one can create a batch of `MyRequestProto` serialized protos\nfrom regular batched tensors using the `encode_proto` op, and convert\nthe response `MyResponseProto` serialized protos to batched tensors\nusing the `decode_proto` op.\n\n**NOTE** Working with serialized proto strings is faster than instantiating\nactual proto objects in memory, so no performance degradation is expected\ncompared to writing custom kernels for this workflow.\n\nUnlike the standard `Rpc` op, if the connection fails or the remote worker\nreturns an error status, this op does **not** reraise the exception.\nInstead, the `status_code` and `status_message` entry for the corresponding RPC\ncall is set with the error returned from the RPC call. The `response` tensor\nwill contain valid response values for those minibatch entries whose RPCs did\nnot fail; the rest of the entries will have empty strings.","inputs":[{"description":"`0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `method` and `request`.","name":"address","type":7},{"description":"`0-D` or `1-D`. The method address on the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `request`.","name":"method","type":7},{"description":"`0-D` or `1-D`. Serialized proto strings: the rpc request argument.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `method`.","name":"request","type":7}],"outputs":[{"description":"Same shape as `request`. Serialized proto strings: the rpc responses.","name":"response","type":7},{"description":"Same shape as `request`. Values correspond to tensorflow Status enum codes.","name":"status_code","type":3},{"description":"Same shape as `request`. Values correspond to Status messages\nreturned from the RPC calls.","name":"status_message","type":7}],"summary":"Perform batches of RPC requests."}},{"name":"Unbatch","schema":{"attributes":[{"name":"timeout_micros","type":"int64"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"name":"T","type":"type"}],"description":"An instance of Unbatch either receives an empty batched_tensor, in which case it\nasynchronously waits until the values become available from a concurrently\nrunning instance of Unbatch with the same container and shared_name, or receives\na non-empty batched_tensor in which case it finalizes all other concurrently\nrunning instances and outputs its own element from the batch.\n\nbatched_tensor: The possibly transformed output of Batch. The size of the first\n dimension should remain unchanged by the transformations for the operation to\n work.\nbatch_index: The matching batch_index obtained from Batch.\nid: The id scalar emitted by Batch.\nunbatched_tensor: The Tensor corresponding to this execution.\ntimeout_micros: Maximum amount of time (in microseconds) to wait to receive the\n batched input tensor associated with a given invocation of the op.\ncontainer: Container to control resource sharing.\nshared_name: Instances of Unbatch with the same container and shared_name are\n assumed to possibly belong to the same batch. If left empty, the op name will\n be used as the shared name.","inputs":[{"name":"batched_tensor","typeAttr":"T"},{"name":"batch_index","type":9},{"name":"id","type":9}],"outputs":[{"name":"unbatched_tensor","typeAttr":"T"}],"summary":"Reverses the operation of Batch for a single output Tensor."}},{"name":"UnbatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A dataset that splits the elements of its input into multiple elements."}},{"name":"UnbatchGrad","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"name":"T","type":"type"}],"description":"Acts like Batch but using the given batch_index index of batching things as they\nbecome available. This ensures that the gradients are propagated back in the\nsame session which did the forward pass.\n\noriginal_input: The input to the Unbatch operation this is the gradient of.\nbatch_index: The batch_index given to the Unbatch operation this is the gradient\nof.\ngrad: The downstream gradient.\nid: The id scalar emitted by Batch.\nbatched_grad: The return value, either an empty tensor or the batched gradient.\ncontainer: Container to control resource sharing.\nshared_name: Instances of UnbatchGrad with the same container and shared_name\n are assumed to possibly belong to the same batch. If left empty, the op name\n will be used as the shared name.","inputs":[{"name":"original_input","typeAttr":"T"},{"name":"batch_index","type":9},{"name":"grad","typeAttr":"T"},{"name":"id","type":9}],"outputs":[{"name":"batched_grad","typeAttr":"T"}],"summary":"Gradient of Unbatch."}},{"name":"UncompressElement","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"compressed","type":21}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Uncompresses a compressed dataset element."}},{"name":"UnicodeDecode","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"The character codepoints for all strings are returned using a single vector\n`char_values`, with strings expanded to characters in row-major order.\n\nThe `row_splits` tensor indicates where the codepoints for\neach input string begin and end within the `char_values` tensor.\nIn particular, the values for the `i`th\nstring (in row-major order) are stored in the slice\n`[row_splits[i]:row_splits[i+1]]`. Thus:\n\n* `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th\n character in the `i`th string (in row-major order).\n* `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th\n string (in row-major order).","inputs":[{"description":"The text to be decoded. Can have any shape. Note that the output is flattened\nto a vector of char values.","name":"input","type":7}],"outputs":[{"description":"A 1D int32 tensor containing the row splits.","name":"row_splits","typeAttr":"Tsplits"},{"description":"A 1D int32 Tensor containing the decoded codepoints.","name":"char_values","type":3}],"summary":"Decodes each string in `input` into a sequence of Unicode code points."}},{"name":"UnicodeDecodeWithOffsets","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"The character codepoints for all strings are returned using a single vector\n`char_values`, with strings expanded to characters in row-major order.\nSimilarly, the character start byte offsets are returned using a single vector\n`char_to_byte_starts`, with strings expanded in row-major order.\n\nThe `row_splits` tensor indicates where the codepoints and start offsets for\neach input string begin and end within the `char_values` and\n`char_to_byte_starts` tensors. In particular, the values for the `i`th\nstring (in row-major order) are stored in the slice\n`[row_splits[i]:row_splits[i+1]]`. Thus:\n\n* `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th\n character in the `i`th string (in row-major order).\n* `char_to_bytes_starts[row_splits[i]+j]` is the start byte offset for the `j`th\n character in the `i`th string (in row-major order).\n* `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th\n string (in row-major order).","inputs":[{"description":"The text to be decoded. Can have any shape. Note that the output is flattened\nto a vector of char values.","name":"input","type":7}],"outputs":[{"description":"A 1D int32 tensor containing the row splits.","name":"row_splits","typeAttr":"Tsplits"},{"description":"A 1D int32 Tensor containing the decoded codepoints.","name":"char_values","type":3},{"description":"A 1D int32 Tensor containing the byte index in the input string where each\ncharacter in `char_values` starts.","name":"char_to_byte_starts","type":9}],"summary":"Decodes each string in `input` into a sequence of Unicode code points."}},{"name":"UnicodeEncode","schema":{"attributes":[{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `ignore`, `replace`, `strict`.","name":"errors","type":"string"},{"description":"Unicode encoding of the output strings. Valid encodings are: `\"UTF-8\",\n\"UTF-16-BE\", and \"UTF-32-BE\"`. Must be one of the following: `UTF-8`, `UTF-16-BE`, `UTF-32-BE`.","name":"output_encoding","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD (U+65533).","name":"replacement_char","type":"int64"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"Returns a vector of strings, where `output[i]` is constructed by encoding the\nUnicode codepoints in `input_values[input_splits[i]:input_splits[i+1]]`\nusing `output_encoding`.\n\n---\n\nExample:\n\n```\ninput_values = [72, 101, 108, 108, 111, 87, 111, 114, 108, 100]\ninput_splits = [0, 5, 10]\noutput_encoding = 'UTF-8'\n\noutput = ['Hello', 'World']\n```","inputs":[{"description":"A 1D tensor containing the unicode codepoints that should be encoded.","name":"input_values","type":3},{"description":"A 1D tensor specifying how the unicode codepoints should be split into strings.\nIn particular, `output[i]` is constructed by encoding the codepoints in the\nslice `input_values[input_splits[i]:input_splits[i+1]]`.","name":"input_splits","typeAttr":"Tsplits"}],"outputs":[{"description":"The 1-D Tensor of strings encoded from the provided unicode codepoints.","name":"output","type":7}],"summary":"Encode a tensor of ints into unicode strings."}},{"name":"UnicodeScript","schema":{"description":"This operation converts Unicode code points to script codes corresponding to\neach code point. Script codes correspond to International Components for\nUnicode (ICU) UScriptCode values. See http://icu-project.org/apiref/icu4c/uscript_8h.html.\nReturns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will\nmatch input shape.\n\nExamples:\n\n>>> tf.strings.unicode_script([1, 31, 38])\n","inputs":[{"description":"A Tensor of int32 Unicode code points.","name":"input","type":3}],"outputs":[{"description":"A Tensor of int32 script codes corresponding to each input code point.","name":"output","type":3}],"summary":"Determine the script codes of a given tensor of Unicode integer code points."}},{"name":"UnicodeTranscode","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"description":"The unicode encoding to use in the output. Must be one of\n`\"UTF-8\", \"UTF-16-BE\", \"UTF-32-BE\"`. Multi-byte encodings will be big-endian. Must be one of the following: `UTF-8`, `UTF-16-BE`, `UTF-32-BE`.","name":"output_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)\n\nNote that for UTF-8, passing a replacement character expressible in 1 byte, such\nas ' ', will preserve string alignment to the source since invalid bytes will be\nreplaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte\nreplacement character will preserve byte alignment to the source.","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"}],"description":"The input is a string tensor of any shape. The output is a string tensor of\nthe same shape containing the transcoded strings. Output strings are always\nvalid unicode. If the input contains invalid encoding positions, the\n`errors` attribute sets the policy for how to deal with them. If the default\nerror-handling policy is used, invalid formatting will be substituted in the\noutput by the `replacement_char`. If the errors policy is to `ignore`, any\ninvalid encoding positions in the input are skipped and not included in the\noutput. If it set to `strict` then any invalid formatting will result in an\nInvalidArgument error.\n\nThis operation can be used with `output_encoding = input_encoding` to enforce\ncorrect formatting for inputs even if they are already in the desired encoding.\n\nIf the input is prefixed by a Byte Order Mark needed to determine encoding\n(e.g. if the encoding is UTF-16 and the BOM indicates big-endian), then that\nBOM will be consumed and not emitted into the output. If the input encoding\nis marked with an explicit endianness (e.g. UTF-16-BE), then the BOM is\ninterpreted as a non-breaking-space and is preserved in the output (including\nalways for UTF-8).\n\nThe end result is that if the input is marked as an explicit endianness the\ntranscoding is faithful to all codepoints in the source. If it is not marked\nwith an explicit endianness, the BOM is not considered part of the string itself\nbut as metadata, and so is not preserved in the output.\n\nExamples:\n\n>>> tf.strings.unicode_transcode([\"Hello\", \"TensorFlow\", \"2.x\"], \"UTF-8\", \"UTF-16-BE\")\n\n>>> tf.strings.unicode_transcode([\"A\", \"B\", \"C\"], \"US ASCII\", \"UTF-8\").numpy()\narray([b'A', b'B', b'C'], dtype=object)","inputs":[{"description":"The text to be processed. Can have any shape.","name":"input","type":7}],"outputs":[{"description":"A string tensor containing unicode text encoded using `output_encoding`.","name":"output","type":7}],"summary":"Transcode the input text from a source encoding to a destination encoding."}},{"name":"UniformCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a uniform distribution."}},{"name":"Unique","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation returns a tensor `y` containing all of the unique elements of `x`\nsorted in the same order that they occur in `x`; `x` does not need to be sorted.\nThis operation also returns a tensor `idx` the same size as `x` that contains\nthe index of each value of `x` in the unique output `y`. In other words:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nExamples:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx = unique(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\n```\n\n```\n# tensor 'x' is [4, 5, 1, 2, 3, 3, 4, 5]\ny, idx = unique(x)\ny ==> [4, 5, 1, 2, 3]\nidx ==> [0, 1, 2, 3, 4, 4, 0, 1]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"},{"description":"1-D.","name":"idx","typeAttr":"out_idx"}],"summary":"Finds unique elements in a 1-D tensor."}},{"name":"UniqueDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the unique elements of `input_dataset`."}},{"name":"UniqueV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation either returns a tensor `y` containing unique elements\nalong the `axis` of a tensor. The returned unique elements is sorted\nin the same order as they occur along `axis` in `x`.\nThis operation also returns a tensor `idx` that is the same size as\nthe number of the elements in `x` along the `axis` dimension. It\ncontains the index in the unique output `y`.\nIn other words, for an `1-D` tensor `x` with `axis = None:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx = unique(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\n```\n\nFor an `2-D` tensor `x` with `axis = 0`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx = unique(x, axis=0)\ny ==> [[1, 0, 0],\n [2, 0, 0]]\nidx ==> [0, 0, 1]\n```\n\nFor an `2-D` tensor `x` with `axis = 1`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx = unique(x, axis=1)\ny ==> [[1, 0],\n [1, 0],\n [2, 0]]\nidx ==> [0, 1, 1]\n```","inputs":[{"description":"A `Tensor`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: None). The axis of the Tensor to\nfind the unique elements.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"A `Tensor`. Unique elements along the `axis` of `Tensor` x.","name":"y","typeAttr":"T"},{"description":"A 1-D Tensor. Has the same type as x that contains the index of each\nvalue of x in the output y.","name":"idx","typeAttr":"out_idx"}],"summary":"Finds unique elements along an axis of a tensor."}},{"name":"UniqueWithCounts","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation returns a tensor `y` containing all of the unique elements of `x`\nsorted in the same order that they occur in `x`. This operation also returns a\ntensor `idx` the same size as `x` that contains the index of each value of `x`\nin the unique output `y`. Finally, it returns a third tensor `count` that\ncontains the count of each element of `y` in `x`. In other words:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx, count = unique_with_counts(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\ncount ==> [2, 1, 3, 1, 2]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"},{"description":"1-D.","name":"idx","typeAttr":"out_idx"},{"description":"1-D.","name":"count","typeAttr":"out_idx"}],"summary":"Finds unique elements in a 1-D tensor."}},{"name":"UniqueWithCountsV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation either returns a tensor `y` containing unique elements\nalong the `axis` of a tensor. The returned unique elements is sorted\nin the same order as they occur along `axis` in `x`.\nThis operation also returns a tensor `idx` and a tensor `count`\nthat are the same size as the number of the elements in `x` along the\n`axis` dimension. The `idx` contains the index in the unique output `y`\nand the `count` contains the count in the unique output `y`.\nIn other words, for an `1-D` tensor `x` with `axis = None:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx, count = unique_with_counts(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\ncount ==> [2, 1, 3, 1, 2]\n```\n\nFor an `2-D` tensor `x` with `axis = 0`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx, count = unique_with_counts(x, axis=0)\ny ==> [[1, 0, 0],\n [2, 0, 0]]\nidx ==> [0, 0, 1]\ncount ==> [2, 1]\n```\n\nFor an `2-D` tensor `x` with `axis = 1`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx, count = unique_with_counts(x, axis=1)\ny ==> [[1, 0],\n [1, 0],\n [2, 0]]\nidx ==> [0, 1, 1]\ncount ==> [1, 2]\n```","inputs":[{"description":"A `Tensor`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: None). The axis of the Tensor to\nfind the unique elements.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"A `Tensor`. Unique elements along the `axis` of `Tensor` x.","name":"y","typeAttr":"T"},{"description":"A 1-D Tensor. Has the same type as x that contains the index of each\nvalue of x in the output y.","name":"idx","typeAttr":"out_idx"},{"description":"A 1-D Tensor. The count of each value of x in the output y.","name":"count","typeAttr":"out_idx"}],"summary":"Finds unique elements along an axis of a tensor."}},{"name":"Unpack","schema":{"attributes":[{"minimum":0,"name":"num","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"Dimension along which to unpack. Negative values wrap around, so the\nvalid range is `[-R, R)`.","name":"axis","type":"int64"}],"description":"Unpacks `num` tensors from `value` by chipping it along the `axis` dimension.\nFor example, given a tensor of shape `(A, B, C, D)`;\n\nIf `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]`\n and each tensor in `output` will have shape `(B, C, D)`. (Note that the\n dimension unpacked along is gone, unlike `split`).\n\nIf `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]`\n and each tensor in `output` will have shape `(A, C, D)`.\nEtc.\n\nThis is the opposite of `pack`.","inputs":[{"description":"1-D or higher, with `axis` dimension size equal to `num`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The list of tensors unpacked from `value`.","name":"output","numberAttr":"num","typeAttr":"T"}],"summary":"Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors."}},{"name":"UnravelIndex","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"\nExample:\n\n```\ny = tf.unravel_index(indices=[2, 5, 7], dims=[3, 3])\n# 'dims' represent a hypothetical (3, 3) tensor of indices:\n# [[0, 1, *2*],\n# [3, 4, *5*],\n# [6, *7*, 8]]\n# For each entry from 'indices', this operation returns\n# its coordinates (marked with '*'), such as\n# 2 ==> (0, 2)\n# 5 ==> (1, 2)\n# 7 ==> (2, 1)\ny ==> [[0, 1, 2], [2, 2, 1]]\n```\n\n@compatibility(numpy)\nEquivalent to np.unravel_index\n@end_compatibility","inputs":[{"description":"An 0-D or 1-D `int` Tensor whose elements are indices into the\nflattened version of an array of dimensions dims.","name":"indices","typeAttr":"Tidx"},{"description":"An 1-D `int` Tensor. The shape of the array to use for unraveling\nindices.","name":"dims","typeAttr":"Tidx"}],"outputs":[{"description":"An 2-D (or 1-D if indices is 0-D) tensor where each row has the\nsame shape as the indices array.","name":"output","typeAttr":"Tidx"}],"summary":"Converts an array of flat indices into a tuple of coordinate arrays."}},{"name":"UnsortedSegmentJoin","schema":{"attributes":[{"default":"","description":"The separator to use when joining.","name":"separator","type":"string"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Computes the string join along segments of a tensor.\nGiven `segment_ids` with rank `N` and `data` with rank `N+M`:\n\n `output[i, k1...kM] = strings.join([data[j1...jN, k1...kM])`\n\nwhere the join is over all [j1...jN] such that segment_ids[j1...jN] = i.\nStrings are joined in row-major order.\n\nFor example:\n\n```python\ninputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']]\noutput_array = string_ops.unsorted_segment_join(inputs=inputs,\n segment_ids=[1, 0, 1],\n num_segments=2,\n separator=':'))\n# output_array ==> [['Y', '6', '6'], ['Y:p', 'q:G', 'c:a']]\n\n\ninputs = ['this', 'is', 'a', 'test']\noutput_array = string_ops.unsorted_segment_join(inputs=inputs,\n segment_ids=[0, 0, 0, 0],\n num_segments=1,\n separator=':'))\n# output_array ==> ['this:is:a:test']\n```","inputs":[{"description":"The input to be joined.","name":"inputs","type":7},{"description":"A tensor whose shape is a prefix of data.shape. Negative segment ids are not\nsupported.","name":"segment_ids","typeAttr":"Tindices"},{"description":"A scalar.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"name":"output","type":7}],"summary":"Joins the elements of `inputs` based on `segment_ids`."}},{"name":"UnsortedSegmentMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the maximum such that:\n\n\\\\(output_i = \\max_{j...} data[j...]\\\\) where max is over tuples `j...` such\nthat `segment_ids[j...] == i`.\n\nIf the maximum is empty for a given segment ID `i`, it outputs the smallest\npossible value for the specific numeric type,\n`output[i] = numeric_limits::lowest()`.\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.\n\n
\n\n
\n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_max(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 4, 3, 3, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum along segments of a tensor."}},{"name":"UnsortedSegmentMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the minimum such that:\n\n\\\\(output_i = \\min_{j...} data_[j...]\\\\) where min is over tuples `j...` such\nthat `segment_ids[j...] == i`.\n\nIf the minimum is empty for a given segment ID `i`, it outputs the largest\npossible value for the specific numeric type,\n`output[i] = numeric_limits::max()`.\n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_min(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 1, 2, 2, 1],\n# [5, 6, 7, 8]]\n```\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum along segments of a tensor."}},{"name":"UnsortedSegmentProd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the product of all\nentries belonging to a segment such that:\n\n\\\\(output_i = \\prod_{j...} data[j...]\\\\) where the product is over tuples\n`j...` such that `segment_ids[j...] == i`.\n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_prod(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 4, 6, 6, 4],\n# [5, 6, 7, 8]]\n```\n\nIf there is no entry for a given segment ID `i`, it outputs 1.\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the product along segments of a tensor."}},{"name":"UnsortedSegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output[i] = \\sum_{j...} data[j...]\\\\) where the sum is over tuples `j...` such\nthat `segment_ids[j...] == i`. Unlike `SegmentSum`, `segment_ids`\nneed not be sorted and need not cover all values in the full\nrange of valid values.\n\nIf the sum is empty for a given segment ID `i`, `output[i] = 0`.\nIf the given segment ID `i` is negative, the value is dropped and will not be\nadded to the sum of the segment.\n\n`num_segments` should equal the number of distinct segment IDs.\n\n
\n\n
\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 5, 5, 5, 5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along segments of a tensor."}},{"name":"Unstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"The basic functionality is similar to dequeue with many fewer\ncapabilities and options. This Op is optimized for performance.","outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op is similar to a lightweight Dequeue."}},{"name":"UnwrapDatasetVariant","schema":{"inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"output_handle","type":21}]}},{"name":"UpperBound","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"Each set of rows with the same index in (sorted_inputs, values) is treated\nindependently. The resulting row is the equivalent of calling\n`np.searchsorted(sorted_inputs, values, side='right')`.\n\nThe result is not a global index to the entire\n`Tensor`, but rather just the index in the last dimension.\n\nA 2-D example:\n sorted_sequence = [[0, 3, 9, 9, 10],\n [1, 2, 3, 4, 5]]\n values = [[2, 4, 9],\n [0, 2, 6]]\n\n result = UpperBound(sorted_sequence, values)\n\n result == [[1, 2, 4],\n [0, 2, 5]]","inputs":[{"description":"2-D Tensor where each row is ordered.","name":"sorted_inputs","typeAttr":"T"},{"description":"2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains\nthe values that will be searched for in `sorted_search_values`.","name":"values","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `values`. It contains the last scalar index\ninto the last dimension where values can be inserted without changing the\nordered property.","name":"output","typeAttr":"out_type"}],"summary":"Applies upper_bound(sorted_search_values, values) along each row."}},{"name":"VarHandleOp","schema":{"attributes":[{"default":"","description":"the container this variable is placed in.","name":"container","type":"string"},{"default":"","description":"the name by which this variable is referred to.","name":"shared_name","type":"string"},{"description":"the type of this variable. Must agree with the dtypes\nof all ops using this variable.","name":"dtype","type":"type"},{"description":"The (possibly partially specified) shape of this variable.","name":"shape","type":"shape"},{"default":[],"description":"DEPRECATED. The allowed devices containing the resource variable. Set when the\noutput ResourceHandle represents a per-replica/partitioned resource variable.","name":"allowed_devices","type":"string[]"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a Variable resource."}},{"name":"VarIsInitializedOp","schema":{"inputs":[{"description":"the input resource handle.","name":"resource","type":20}],"outputs":[{"description":"a scalar boolean which is true if the variable has been\ninitialized.","name":"is_initialized","type":10}],"summary":"Checks whether a resource handle-based variable has been initialized."}},{"name":"Variable","schema":{"attributes":[{"name":"shape","type":"shape"},{"name":"dtype","type":"type"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"category":"Control","outputs":[{"isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Use VariableV2 instead."}},{"name":"VariableShape","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns a 1-D integer tensor representing the shape of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\nshape(t) ==> [2, 2, 3]\n```","inputs":[{"name":"input","type":20}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the shape of the variable pointed to by `resource`."}},{"name":"VariableV2","schema":{"attributes":[{"description":"The shape of the variable tensor.","name":"shape","type":"shape"},{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"},{"default":"","description":"If non-empty, this variable is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this variable is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"category":"Control","description":"Outputs a ref to the tensor state so it may be read or modified.\nTODO(zhifengc/mrry): Adds a pointer to a more detail document\nabout sharing states in tensorflow.","outputs":[{"description":"A reference to the variable tensor.","isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Holds state in the form of a tensor that persists across steps."}},{"name":"Where","schema":{"attributes":[{"default":{"type":"type","value":10},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"}],"description":"This operation returns the coordinates of true elements in `input`. The\ncoordinates are returned in a 2-D tensor where the first dimension (rows)\nrepresents the number of true elements, and the second dimension (columns)\nrepresents the coordinates of the true elements. Keep in mind, the shape of\nthe output tensor can vary depending on how many true values there are in\n`input`. Indices are output in row-major order.\n\nFor example:\n\n```\n# 'input' tensor is [[True, False]\n# [True, False]]\n# 'input' has two true values, so output has two coordinates.\n# 'input' has rank of 2, so coordinates have two indices.\nwhere(input) ==> [[0, 0],\n [1, 0]]\n\n# `input` tensor is [[[True, False]\n# [True, False]]\n# [[False, True]\n# [False, True]]\n# [[False, False]\n# [False, True]]]\n# 'input' has 5 true values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n\n# `input` tensor is [[[1.5, 0.0]\n# [-0.5, 0.0]]\n# [[0.0, 0.25]\n# [0.0, 0.75]]\n# [[0.0, 0.0]\n# [0.0, 0.01]]]\n# 'input' has 5 nonzero values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n\n# `input` tensor is [[[1.5 + 0.0j, 0.0 + 0.0j]\n# [0.0 + 0.5j, 0.0 + 0.0j]]\n# [[0.0 + 0.0j, 0.25 + 1.5j]\n# [0.0 + 0.0j, 0.75 + 0.0j]]\n# [[0.0 + 0.0j, 0.0 + 0.0j]\n# [0.0 + 0.0j, 0.01 + 0.0j]]]\n# 'input' has 5 nonzero magnitude values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"index","type":9}],"summary":"Returns locations of nonzero / true values in a tensor."}},{"name":"While","schema":{"attributes":[{"description":"dtype in use.","minimum":0,"name":"T","type":"type[]"},{"description":" A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.","name":"cond","type":"function"},{"description":" A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.","name":"body","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"},{"default":10,"name":"parallel_iterations","type":"int64"}],"inputs":[{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":"output = input; While (Cond(output)) { output = Body(output) }"}},{"name":"WholeFileReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue filenames in a Queue. The output of ReaderRead will\nbe a filename (key) and the contents of that file (value).","outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the entire contents of a file as a value."}},{"name":"WholeFileReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue filenames in a Queue. The output of ReaderRead will\nbe a filename (key) and the contents of that file (value).","outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the entire contents of a file as a value."}},{"name":"WindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"An integer scalar, representing the number of elements\nof the input dataset to combine into a window. Must be positive.","name":"size","type":9},{"description":"An integer scalar, representing the number of input elements\nby which the window moves in each iteration. Defaults to `size`.\nMust be positive.","name":"shift","type":9},{"description":"An integer scalar, representing the stride of the input elements\nin the sliding window. Must be positive. The default value of 1 means\n\"retain every input element\".","name":"stride","type":9},{"description":"A Boolean scalar, representing whether the last window should be\ndropped if its size is smaller than `window_size`.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":" Combines (nests of) input elements into a dataset of (nests of) windows.\n\n A \"window\" is a finite dataset of flat elements of size `size` (or possibly\n fewer if there are not enough input elements to fill the window and\n `drop_remainder` evaluates to false).\n\n The `shift` argument determines the number of input elements by which\n the window moves on each iteration. The first element in the `k`th window\n will be element\n\n ```\n 1 + (k-1) * shift\n ```\n\n of the input dataset. In particular, the first element of the first window\n will always be the first element of the input dataset. \n\n If the `stride` parameter is greater than 1, then each window will skip\n `(stride - 1)` input elements between each element that appears in the\n window. Output windows will still contain `size` elements regardless of\n the value of `stride`.\n\n The `stride` argument determines the stride of the input elements, and the\n `shift` argument determines the shift of the window.\n\n For example, letting `{...}` to represent a Dataset:\n\n - `tf.data.Dataset.range(7).window(2)` produces\n `{{0, 1}, {2, 3}, {4, 5}, {6}}`\n - `tf.data.Dataset.range(7).window(3, 2, 1, True)` produces\n `{{0, 1, 2}, {2, 3, 4}, {4, 5, 6}}`\n - `tf.data.Dataset.range(7).window(3, 1, 2, True)` produces\n `{{0, 2, 4}, {1, 3, 5}, {2, 4, 6}}`\n\n Note that when the `window` transformation is applied to a dataset of\n nested elements, it produces a dataset of nested windows.\n\n For example:\n\n - `tf.data.Dataset.from_tensor_slices((range(4), range(4))).window(2)`\n produces `{({0, 1}, {0, 1}), ({2, 3}, {2, 3})}`\n - `tf.data.Dataset.from_tensor_slices({\"a\": range(4)}).window(2)`\n produces `{{\"a\": {0, 1}}, {\"a\": {2, 3}}}`"}},{"name":"WorkerHeartbeat","schema":{"description":"Heartbeats may be sent periodically to indicate the coordinator is still active,\nto retrieve the current worker status and to expedite shutdown when necessary.","inputs":[{"description":"A string tensor containing a serialized WorkerHeartbeatRequest","name":"request","type":7}],"outputs":[{"description":"A string tensor containing a serialized WorkerHeartbeatResponse","name":"response","type":7}],"summary":"Worker heartbeat op."}},{"name":"WrapDatasetVariant","schema":{"inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"output_handle","type":21}]}},{"name":"WriteAudioSummary","schema":{"attributes":[{"default":3,"minimum":1,"name":"max_outputs","type":"int64"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"tensor","type":1},{"name":"sample_rate","type":1}]}},{"name":"WriteFile","schema":{"description":"creates directory if not existing.","inputs":[{"description":"scalar. The name of the file to which we write the contents.","name":"filename","type":7},{"description":"scalar. The content to be written to the output file.","name":"contents","type":7}],"summary":"Writes contents to the file at input filename. Creates file and recursively"}},{"name":"WriteGraphSummary","schema":{"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","type":7}]}},{"name":"WriteHistogramSummary","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"values","typeAttr":"T"}]}},{"name":"WriteImageSummary","schema":{"attributes":[{"default":3,"minimum":1,"name":"max_images","type":"int64"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `uint8`, `float32`, `float16`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"tensor","typeAttr":"T"},{"name":"bad_color","type":4}]}},{"name":"WriteRawProtoSummary","schema":{"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","type":7}]}},{"name":"WriteScalarSummary","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"value","typeAttr":"T"}]}},{"name":"WriteSummary","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","typeAttr":"T"},{"name":"tag","type":7},{"name":"summary_metadata","type":7}]}},{"name":"Xdivy","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x / y otherwise, elementwise."}},{"name":"XlaHostCompute","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":0,"name":"Tinputs","type":"type[]"},{"description":"The element types of each element in `outputs`.","minimum":0,"name":"Toutputs","type":"type[]"},{"description":"A list of names of HostCompute computations that must be\nsequenced before this computation.","minimum":0,"name":"ancestors","type":"string[]"},{"description":"If shape_inference_graph is empty, a list of the shapes of `outputs`.","minimum":0,"name":"shapes","type":"shape[]"},{"description":"If non-empty, a serialized GraphDef representing a graph\nthat must be analyzed at compile time to determine the shapes of the outputs.","name":"shape_inference_graph","type":"function"},{"description":"A unique identifier for this region used to match up host transfers.","name":"key","type":"string"},{"default":1000000,"description":"Estimated duration of the host computation in nanoseconds.","name":"cost_estimate_ns","type":"int64"},{"default":0,"description":"Default core to use for host to device transfers.","name":"tpu_core","type":"int64"}],"inputs":[{"description":"A list of tensors that will be sent to the host.","name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"description":"A list of tensors that will be returned to the device.","name":"outputs","typeListAttr":"Toutputs"}],"summary":"A pseudo-op to represent host-side computation in an XLA program."}},{"name":"XlaRecvFromHost","schema":{"attributes":[{"name":"Toutput","type":"type"},{"name":"shape","type":"shape"},{"name":"key","type":"string"}],"outputs":[{"name":"output","typeAttr":"Toutput"}]}},{"name":"XlaSendToHost","schema":{"attributes":[{"name":"Tinput","type":"type"},{"name":"key","type":"string"}],"inputs":[{"name":"input","typeAttr":"Tinput"}]}},{"name":"Xlog1py","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x * log1p(y) otherwise, elementwise."}},{"name":"Xlogy","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x * log(y) otherwise, elementwise."}},{"name":"ZerosLike","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"a tensor of type T.","name":"x","typeAttr":"T"}],"outputs":[{"description":"a tensor of the same shape and type as x but filled with zeros.","name":"y","typeAttr":"T"}],"summary":"Returns a tensor of zeros with the same shape and type as x."}},{"name":"Zeta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The Hurwitz zeta function is defined as:\n\n\n\\\\(\\zeta(x, q) = \\sum_{n=0}^{\\infty} (q + n)^{-x}\\\\)","inputs":[{"name":"x","typeAttr":"T"},{"name":"q","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the Hurwitz zeta function \\\\(\\zeta(x, q)\\\\)."}},{"name":"ZipDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"description":"The length of `input_datasets`","minimum":1,"name":"N","type":"int64"}],"description":"The elements of the resulting dataset are created by zipping corresponding\nelements from each of the input datasets.\n\nThe size of the resulting dataset will match the size of the smallest input\ndataset, and no error will be raised if input datasets have different sizes.","inputs":[{"description":"List of `N` variant Tensors representing datasets to be zipped together.","name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that zips together `input_datasets`."}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..3d9412c09eb9cd118e7f7c64a14444fafd7a6bc4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("tf");$root.tensorflow={},$root.tensorflow.SavedModel=class{constructor(){this.meta_graphs=[]}static decode(e,t){const o=new $root.tensorflow.SavedModel,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.saved_model_schema_version=e.int64();break;case 2:o.meta_graphs.push($root.tensorflow.MetaGraphDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedModel;for(e.start();!e.end();){const o=e.tag();switch(o){case"saved_model_schema_version":t.saved_model_schema_version=e.integer();break;case"meta_graphs":t.meta_graphs.push($root.tensorflow.MetaGraphDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedModel.prototype.saved_model_schema_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.MetaGraphDef=class{constructor(){this.collection_def={},this.signature_def={},this.asset_file_def=[]}static decode(e,t){const o=new $root.tensorflow.MetaGraphDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta_info_def=$root.tensorflow.MetaGraphDef.MetaInfoDef.decode(e,e.uint32());break;case 2:o.graph_def=$root.tensorflow.GraphDef.decode(e,e.uint32());break;case 3:o.saver_def=$root.tensorflow.SaverDef.decode(e,e.uint32());break;case 4:e.pair(o.collection_def,(()=>e.string()),(()=>$root.tensorflow.CollectionDef.decode(e,e.uint32())));break;case 5:e.pair(o.signature_def,(()=>e.string()),(()=>$root.tensorflow.SignatureDef.decode(e,e.uint32())));break;case 6:o.asset_file_def.push($root.tensorflow.AssetFileDef.decode(e,e.uint32()));break;case 7:o.object_graph_def=$root.tensorflow.SavedObjectGraph.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.MetaGraphDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta_info_def":t.meta_info_def=$root.tensorflow.MetaGraphDef.MetaInfoDef.decodeText(e,!0);break;case"graph_def":t.graph_def=$root.tensorflow.GraphDef.decodeText(e,!0);break;case"saver_def":t.saver_def=$root.tensorflow.SaverDef.decodeText(e,!0);break;case"collection_def":e.pair(t.collection_def,(()=>e.string()),(()=>$root.tensorflow.CollectionDef.decodeText(e,!0)));break;case"signature_def":e.pair(t.signature_def,(()=>e.string()),(()=>$root.tensorflow.SignatureDef.decodeText(e,!0)));break;case"asset_file_def":t.asset_file_def.push($root.tensorflow.AssetFileDef.decodeText(e,!0));break;case"object_graph_def":t.object_graph_def=$root.tensorflow.SavedObjectGraph.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.MetaGraphDef.prototype.meta_info_def=null,$root.tensorflow.MetaGraphDef.prototype.graph_def=null,$root.tensorflow.MetaGraphDef.prototype.saver_def=null,$root.tensorflow.MetaGraphDef.prototype.object_graph_def=null,$root.tensorflow.MetaGraphDef.MetaInfoDef=class{constructor(){this.tags=[],this.function_aliases={}}static decode(e,t){const o=new $root.tensorflow.MetaGraphDef.MetaInfoDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta_graph_version=e.string();break;case 2:o.stripped_op_list=$root.tensorflow.OpList.decode(e,e.uint32());break;case 3:o.any_info=$root.google.protobuf.Any.decode(e,e.uint32());break;case 4:o.tags.push(e.string());break;case 5:o.tensorflow_version=e.string();break;case 6:o.tensorflow_git_version=e.string();break;case 7:o.stripped_default_attrs=e.bool();break;case 8:e.pair(o.function_aliases,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.MetaGraphDef.MetaInfoDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta_graph_version":t.meta_graph_version=e.string();break;case"stripped_op_list":t.stripped_op_list=$root.tensorflow.OpList.decodeText(e,!0);break;case"any_info":t.any_info=$root.google.protobuf.Any.decodeText(e,!0);break;case"tags":e.array(t.tags,(()=>e.string()));break;case"tensorflow_version":t.tensorflow_version=e.string();break;case"tensorflow_git_version":t.tensorflow_git_version=e.string();break;case"stripped_default_attrs":t.stripped_default_attrs=e.boolean();break;case"function_aliases":e.pair(t.function_aliases,(()=>e.string()),(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.meta_graph_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.stripped_op_list=null,$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.any_info=null,$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.tensorflow_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.tensorflow_git_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.stripped_default_attrs=!1,$root.tensorflow.CollectionDef=class{constructor(){}get kind(){return $root.tensorflow.CollectionDef.kindSet=$root.tensorflow.CollectionDef.kindSet||new Set(["node_list","bytes_list","int64_list","float_list","any_list"]),Object.keys(this).find((e=>$root.tensorflow.CollectionDef.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.CollectionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node_list=$root.tensorflow.CollectionDef.NodeList.decode(e,e.uint32());break;case 2:o.bytes_list=$root.tensorflow.CollectionDef.BytesList.decode(e,e.uint32());break;case 3:o.int64_list=$root.tensorflow.CollectionDef.Int64List.decode(e,e.uint32());break;case 4:o.float_list=$root.tensorflow.CollectionDef.FloatList.decode(e,e.uint32());break;case 5:o.any_list=$root.tensorflow.CollectionDef.AnyList.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"node_list":t.node_list=$root.tensorflow.CollectionDef.NodeList.decodeText(e,!0);break;case"bytes_list":t.bytes_list=$root.tensorflow.CollectionDef.BytesList.decodeText(e,!0);break;case"int64_list":t.int64_list=$root.tensorflow.CollectionDef.Int64List.decodeText(e,!0);break;case"float_list":t.float_list=$root.tensorflow.CollectionDef.FloatList.decodeText(e,!0);break;case"any_list":t.any_list=$root.tensorflow.CollectionDef.AnyList.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.NodeList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.NodeList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.NodeList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.BytesList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.BytesList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push(e.bytes());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.BytesList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.bytes()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.Int64List=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.Int64List,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value=e.array(o.value,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.Int64List;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.FloatList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.FloatList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value=e.floats(o.value,t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.FloatList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.float()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.AnyList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.AnyList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push($root.google.protobuf.Any.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.AnyList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":t.value.push($root.google.protobuf.Any.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo=class{constructor(){}get encoding(){return $root.tensorflow.TensorInfo.encodingSet=$root.tensorflow.TensorInfo.encodingSet||new Set(["name","coo_sparse","composite_tensor"]),Object.keys(this).find((e=>$root.tensorflow.TensorInfo.encodingSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.TensorInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 4:o.coo_sparse=$root.tensorflow.TensorInfo.CooSparse.decode(e,e.uint32());break;case 5:o.composite_tensor=$root.tensorflow.TensorInfo.CompositeTensor.decode(e,e.uint32());break;case 2:o.dtype=e.int32();break;case 3:o.tensor_shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"coo_sparse":t.coo_sparse=$root.tensorflow.TensorInfo.CooSparse.decodeText(e,!0);break;case"composite_tensor":t.composite_tensor=$root.tensorflow.TensorInfo.CompositeTensor.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"tensor_shape":t.tensor_shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.prototype.dtype=0,$root.tensorflow.TensorInfo.prototype.tensor_shape=null,$root.tensorflow.TensorInfo.CooSparse=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorInfo.CooSparse,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values_tensor_name=e.string();break;case 2:o.indices_tensor_name=e.string();break;case 3:o.dense_shape_tensor_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo.CooSparse;for(e.start();!e.end();){const o=e.tag();switch(o){case"values_tensor_name":t.values_tensor_name=e.string();break;case"indices_tensor_name":t.indices_tensor_name=e.string();break;case"dense_shape_tensor_name":t.dense_shape_tensor_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.CooSparse.prototype.values_tensor_name="",$root.tensorflow.TensorInfo.CooSparse.prototype.indices_tensor_name="",$root.tensorflow.TensorInfo.CooSparse.prototype.dense_shape_tensor_name="",$root.tensorflow.TensorInfo.CompositeTensor=class{constructor(){this.components=[]}static decode(e,t){const o=new $root.tensorflow.TensorInfo.CompositeTensor,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_spec=$root.tensorflow.TypeSpecProto.decode(e,e.uint32());break;case 2:o.components.push($root.tensorflow.TensorInfo.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo.CompositeTensor;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_spec":t.type_spec=$root.tensorflow.TypeSpecProto.decodeText(e,!0);break;case"components":t.components.push($root.tensorflow.TensorInfo.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.CompositeTensor.prototype.type_spec=null,$root.tensorflow.SignatureDef=class{constructor(){this.inputs={},this.outputs={}}static decode(e,t){const o=new $root.tensorflow.SignatureDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.inputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decode(e,e.uint32())));break;case 2:e.pair(o.outputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decode(e,e.uint32())));break;case 3:o.method_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SignatureDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"inputs":e.pair(t.inputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decodeText(e,!0)));break;case"outputs":e.pair(t.outputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decodeText(e,!0)));break;case"method_name":t.method_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SignatureDef.prototype.method_name="",$root.tensorflow.AssetFileDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.AssetFileDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.tensor_info=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:o.filename=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AssetFileDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"tensor_info":t.tensor_info=$root.tensorflow.TensorInfo.decodeText(e,!0);break;case"filename":t.filename=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.AssetFileDef.prototype.tensor_info=null,$root.tensorflow.AssetFileDef.prototype.filename="",$root.tensorflow.GraphDef=class{constructor(){this.node=[]}static decode(e,t){const o=new $root.tensorflow.GraphDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:o.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 3:o.version=e.int32();break;case 2:o.library=$root.tensorflow.FunctionDefLibrary.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.GraphDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"node":t.node.push($root.tensorflow.NodeDef.decodeText(e,!0));break;case"versions":t.versions=$root.tensorflow.VersionDef.decodeText(e,!0);break;case"version":t.version=e.integer();break;case"library":t.library=$root.tensorflow.FunctionDefLibrary.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.GraphDef.prototype.versions=null,$root.tensorflow.GraphDef.prototype.version=0,$root.tensorflow.GraphDef.prototype.library=null,$root.tensorflow.FunctionDefLibrary=class{constructor(){this.function=[],this.gradient=[]}static decode(e,t){const o=new $root.tensorflow.FunctionDefLibrary,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.function.push($root.tensorflow.FunctionDef.decode(e,e.uint32()));break;case 2:o.gradient.push($root.tensorflow.GradientDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDefLibrary;for(e.start();!e.end();){const o=e.tag();switch(o){case"function":t.function.push($root.tensorflow.FunctionDef.decodeText(e,!0));break;case"gradient":t.gradient.push($root.tensorflow.GradientDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionDef=class{constructor(){this.attr={},this.arg_attr={},this.resource_arg_unique_id={},this.node_def=[],this.ret={},this.control_ret={}}static decode(e,t){const o=new $root.tensorflow.FunctionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.signature=$root.tensorflow.OpDef.decode(e,e.uint32());break;case 5:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;case 7:e.pair(o.arg_attr,(()=>e.uint32()),(()=>$root.tensorflow.FunctionDef.ArgAttrs.decode(e,e.uint32())));break;case 8:e.pair(o.resource_arg_unique_id,(()=>e.uint32()),(()=>e.uint32()));break;case 3:o.node_def.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:e.pair(o.ret,(()=>e.string()),(()=>e.string()));break;case 6:e.pair(o.control_ret,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"signature":t.signature=$root.tensorflow.OpDef.decodeText(e,!0);break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;case"arg_attr":e.pair(t.arg_attr,(()=>e.integer()),(()=>$root.tensorflow.FunctionDef.ArgAttrs.decodeText(e,!0)));break;case"resource_arg_unique_id":e.pair(t.resource_arg_unique_id,(()=>e.integer()),(()=>e.uint32()));break;case"node_def":t.node_def.push($root.tensorflow.NodeDef.decodeText(e,!0));break;case"ret":e.pair(t.ret,(()=>e.string()),(()=>e.string()));break;case"control_ret":e.pair(t.control_ret,(()=>e.string()),(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionDef.prototype.signature=null,$root.tensorflow.FunctionDef.ArgAttrs=class{constructor(){this.attr={}}static decode(e,t){const o=new $root.tensorflow.FunctionDef.ArgAttrs,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDef.ArgAttrs;for(e.start();!e.end();){const o=e.tag();switch(o){case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.GradientDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.GradientDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.function_name=e.string();break;case 2:o.gradient_func=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.GradientDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"function_name":t.function_name=e.string();break;case"gradient_func":t.gradient_func=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.GradientDef.prototype.function_name="",$root.tensorflow.GradientDef.prototype.gradient_func="",$root.tensorflow.AttrValue=class{constructor(){}get value(){return $root.tensorflow.AttrValue.valueSet=$root.tensorflow.AttrValue.valueSet||new Set(["s","i","f","b","type","shape","tensor","list","func","placeholder"]),Object.keys(this).find((e=>$root.tensorflow.AttrValue.valueSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.AttrValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.s=e.bytes();break;case 3:o.i=e.int64();break;case 4:o.f=e.float();break;case 5:o.b=e.bool();break;case 6:o.type=e.int32();break;case 7:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 8:o.tensor=$root.tensorflow.TensorProto.decode(e,e.uint32());break;case 1:o.list=$root.tensorflow.AttrValue.ListValue.decode(e,e.uint32());break;case 10:o.func=$root.tensorflow.NameAttrList.decode(e,e.uint32());break;case 9:o.placeholder=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AttrValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"s":t.s=e.bytes();break;case"i":t.i=e.integer();break;case"f":t.f=e.float();break;case"b":t.b=e.boolean();break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"tensor":t.tensor=$root.tensorflow.TensorProto.decodeText(e,!0);break;case"list":t.list=$root.tensorflow.AttrValue.ListValue.decodeText(e,!0);break;case"func":t.func=$root.tensorflow.NameAttrList.decodeText(e,!0);break;case"placeholder":t.placeholder=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.AttrValue.ListValue=class{constructor(){this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[]}static decode(e,t){const o=new $root.tensorflow.AttrValue.ListValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.s.push(e.bytes());break;case 3:o.i=e.array(o.i,(()=>e.int64()),t);break;case 4:o.f=e.floats(o.f,t);break;case 5:o.b=e.array(o.b,(()=>e.bool()),t);break;case 6:o.type=e.array(o.type,(()=>e.int32()),t);break;case 7:o.shape.push($root.tensorflow.TensorShapeProto.decode(e,e.uint32()));break;case 8:o.tensor.push($root.tensorflow.TensorProto.decode(e,e.uint32()));break;case 9:o.func.push($root.tensorflow.NameAttrList.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AttrValue.ListValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"s":e.array(t.s,(()=>e.bytes()));break;case"i":e.array(t.i,(()=>e.integer()));break;case"f":e.array(t.f,(()=>e.float()));break;case"b":e.array(t.b,(()=>e.boolean()));break;case"type":e.array(t.type,(()=>e.enum($root.tensorflow.DataType)));break;case"shape":t.shape.push($root.tensorflow.TensorShapeProto.decodeText(e,!0));break;case"tensor":t.tensor.push($root.tensorflow.TensorProto.decodeText(e,!0));break;case"func":t.func.push($root.tensorflow.NameAttrList.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.NameAttrList=class{constructor(){this.attr={}}static decode(e,t){const o=new $root.tensorflow.NameAttrList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NameAttrList;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.NameAttrList.prototype.name="",$root.tensorflow.TensorProto=class{constructor(){this.half_val=[],this.float_val=[],this.double_val=[],this.int_val=[],this.string_val=[],this.scomplex_val=[],this.int64_val=[],this.bool_val=[],this.dcomplex_val=[],this.resource_handle_val=[],this.variant_val=[],this.uint32_val=[],this.uint64_val=[]}static decode(e,t){const o=new $root.tensorflow.TensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.tensor_shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.version_number=e.int32();break;case 4:o.tensor_content=e.bytes();break;case 13:o.half_val=e.array(o.half_val,(()=>e.int32()),t);break;case 5:o.float_val=e.floats(o.float_val,t);break;case 6:o.double_val=e.doubles(o.double_val,t);break;case 7:o.int_val=e.array(o.int_val,(()=>e.int32()),t);break;case 8:o.string_val.push(e.bytes());break;case 9:o.scomplex_val=e.floats(o.scomplex_val,t);break;case 10:o.int64_val=e.array(o.int64_val,(()=>e.int64()),t);break;case 11:o.bool_val=e.array(o.bool_val,(()=>e.bool()),t);break;case 12:o.dcomplex_val=e.doubles(o.dcomplex_val,t);break;case 14:o.resource_handle_val.push($root.tensorflow.ResourceHandleProto.decode(e,e.uint32()));break;case 15:o.variant_val.push($root.tensorflow.VariantTensorDataProto.decode(e,e.uint32()));break;case 16:o.uint32_val=e.array(o.uint32_val,(()=>e.uint32()),t);break;case 17:o.uint64_val=e.array(o.uint64_val,(()=>e.uint64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"tensor_shape":t.tensor_shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"version_number":t.version_number=e.integer();break;case"tensor_content":t.tensor_content=e.bytes();break;case"half_val":e.array(t.half_val,(()=>e.integer()));break;case"float_val":e.array(t.float_val,(()=>e.float()));break;case"double_val":e.array(t.double_val,(()=>e.float()));break;case"int_val":e.array(t.int_val,(()=>e.integer()));break;case"string_val":e.array(t.string_val,(()=>e.bytes()));break;case"scomplex_val":e.array(t.scomplex_val,(()=>e.float()));break;case"int64_val":e.array(t.int64_val,(()=>e.integer()));break;case"bool_val":e.array(t.bool_val,(()=>e.boolean()));break;case"dcomplex_val":e.array(t.dcomplex_val,(()=>e.float()));break;case"resource_handle_val":t.resource_handle_val.push($root.tensorflow.ResourceHandleProto.decodeText(e,!0));break;case"variant_val":t.variant_val.push($root.tensorflow.VariantTensorDataProto.decodeText(e,!0));break;case"uint32_val":e.array(t.uint32_val,(()=>e.integer()));break;case"uint64_val":e.array(t.uint64_val,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorProto.prototype.dtype=0,$root.tensorflow.TensorProto.prototype.tensor_shape=null,$root.tensorflow.TensorProto.prototype.version_number=0,$root.tensorflow.TensorProto.prototype.tensor_content=new Uint8Array([]),$root.tensorflow.VariantTensorDataProto=class{constructor(){this.tensors=[]}static decode(e,t){const o=new $root.tensorflow.VariantTensorDataProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_name=e.string();break;case 2:o.metadata=e.bytes();break;case 3:o.tensors.push($root.tensorflow.TensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VariantTensorDataProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_name":t.type_name=e.string();break;case"metadata":t.metadata=e.bytes();break;case"tensors":t.tensors.push($root.tensorflow.TensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.VariantTensorDataProto.prototype.type_name="",$root.tensorflow.VariantTensorDataProto.prototype.metadata=new Uint8Array([]),$root.tensorflow.ResourceHandleProto=class{constructor(){this.dtypes_and_shapes=[]}static decode(e,t){const o=new $root.tensorflow.ResourceHandleProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device=e.string();break;case 2:o.container=e.string();break;case 3:o.name=e.string();break;case 4:o.hash_code=e.uint64();break;case 5:o.maybe_type_name=e.string();break;case 6:o.dtypes_and_shapes.push($root.tensorflow.ResourceHandleProto.DtypeAndShape.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ResourceHandleProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"device":t.device=e.string();break;case"container":t.container=e.string();break;case"name":t.name=e.string();break;case"hash_code":t.hash_code=e.integer();break;case"maybe_type_name":t.maybe_type_name=e.string();break;case"dtypes_and_shapes":t.dtypes_and_shapes.push($root.tensorflow.ResourceHandleProto.DtypeAndShape.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.ResourceHandleProto.prototype.device="",$root.tensorflow.ResourceHandleProto.prototype.container="",$root.tensorflow.ResourceHandleProto.prototype.name="",$root.tensorflow.ResourceHandleProto.prototype.hash_code=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.tensorflow.ResourceHandleProto.prototype.maybe_type_name="",$root.tensorflow.ResourceHandleProto.DtypeAndShape=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.ResourceHandleProto.DtypeAndShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ResourceHandleProto.DtypeAndShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.ResourceHandleProto.DtypeAndShape.prototype.dtype=0,$root.tensorflow.ResourceHandleProto.DtypeAndShape.prototype.shape=null,$root.tensorflow.TensorShapeProto=class{constructor(){this.dim=[]}static decode(e,t){const o=new $root.tensorflow.TensorShapeProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.dim.push($root.tensorflow.TensorShapeProto.Dim.decode(e,e.uint32()));break;case 3:o.unknown_rank=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorShapeProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dim":t.dim.push($root.tensorflow.TensorShapeProto.Dim.decodeText(e,!0));break;case"unknown_rank":t.unknown_rank=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorShapeProto.prototype.unknown_rank=!1,$root.tensorflow.TensorShapeProto.Dim=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorShapeProto.Dim,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.size=e.int64();break;case 2:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorShapeProto.Dim;for(e.start();!e.end();){const o=e.tag();switch(o){case"size":t.size=e.integer();break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorShapeProto.Dim.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.TensorShapeProto.Dim.prototype.name="",$root.tensorflow.DataType={DT_INVALID:0,DT_FLOAT:1,DT_DOUBLE:2,DT_INT32:3,DT_UINT8:4,DT_INT16:5,DT_INT8:6,DT_STRING:7,DT_COMPLEX64:8,DT_INT64:9,DT_BOOL:10,DT_QINT8:11,DT_QUINT8:12,DT_QINT32:13,DT_BFLOAT16:14,DT_QINT16:15,DT_QUINT16:16,DT_UINT16:17,DT_COMPLEX128:18,DT_HALF:19,DT_RESOURCE:20,DT_VARIANT:21,DT_UINT32:22,DT_UINT64:23,DT_FLOAT_REF:101,DT_DOUBLE_REF:102,DT_INT32_REF:103,DT_UINT8_REF:104,DT_INT16_REF:105,DT_INT8_REF:106,DT_STRING_REF:107,DT_COMPLEX64_REF:108,DT_INT64_REF:109,DT_BOOL_REF:110,DT_QINT8_REF:111,DT_QUINT8_REF:112,DT_QINT32_REF:113,DT_BFLOAT16_REF:114,DT_QINT16_REF:115,DT_QUINT16_REF:116,DT_UINT16_REF:117,DT_COMPLEX128_REF:118,DT_HALF_REF:119,DT_RESOURCE_REF:120,DT_VARIANT_REF:121,DT_UINT32_REF:122,DT_UINT64_REF:123},$root.tensorflow.NodeDef=class{constructor(){this.input=[],this.attr={}}static decode(e,t){const o=new $root.tensorflow.NodeDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.op=e.string();break;case 3:o.input.push(e.string());break;case 4:o.device=e.string();break;case 5:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;case 6:o.experimental_debug_info=$root.tensorflow.NodeDef.ExperimentalDebugInfo.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NodeDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"op":t.op=e.string();break;case"input":e.array(t.input,(()=>e.string()));break;case"device":t.device=e.string();break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;case"experimental_debug_info":t.experimental_debug_info=$root.tensorflow.NodeDef.ExperimentalDebugInfo.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.NodeDef.prototype.name="",$root.tensorflow.NodeDef.prototype.op="",$root.tensorflow.NodeDef.prototype.device="",$root.tensorflow.NodeDef.prototype.experimental_debug_info=null,$root.tensorflow.NodeDef.ExperimentalDebugInfo=class{constructor(){this.original_node_names=[],this.original_func_names=[]}static decode(e,t){const o=new $root.tensorflow.NodeDef.ExperimentalDebugInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.original_node_names.push(e.string());break;case 2:o.original_func_names.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NodeDef.ExperimentalDebugInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"original_node_names":e.array(t.original_node_names,(()=>e.string()));break;case"original_func_names":e.array(t.original_func_names,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef=class{constructor(){this.input_arg=[],this.output_arg=[],this.control_output=[],this.attr=[]}static decode(e,t){const o=new $root.tensorflow.OpDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.input_arg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 3:o.output_arg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 20:o.control_output.push(e.string());break;case 4:o.attr.push($root.tensorflow.OpDef.AttrDef.decode(e,e.uint32()));break;case 8:o.deprecation=$root.tensorflow.OpDeprecation.decode(e,e.uint32());break;case 5:o.summary=e.string();break;case 6:o.description=e.string();break;case 18:o.is_commutative=e.bool();break;case 16:o.is_aggregate=e.bool();break;case 17:o.is_stateful=e.bool();break;case 19:o.allows_uninitialized_input=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"input_arg":t.input_arg.push($root.tensorflow.OpDef.ArgDef.decodeText(e,!0));break;case"output_arg":t.output_arg.push($root.tensorflow.OpDef.ArgDef.decodeText(e,!0));break;case"control_output":e.array(t.control_output,(()=>e.string()));break;case"attr":t.attr.push($root.tensorflow.OpDef.AttrDef.decodeText(e,!0));break;case"deprecation":t.deprecation=$root.tensorflow.OpDeprecation.decodeText(e,!0);break;case"summary":t.summary=e.string();break;case"description":t.description=e.string();break;case"is_commutative":t.is_commutative=e.boolean();break;case"is_aggregate":t.is_aggregate=e.boolean();break;case"is_stateful":t.is_stateful=e.boolean();break;case"allows_uninitialized_input":t.allows_uninitialized_input=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.prototype.name="",$root.tensorflow.OpDef.prototype.deprecation=null,$root.tensorflow.OpDef.prototype.summary="",$root.tensorflow.OpDef.prototype.description="",$root.tensorflow.OpDef.prototype.is_commutative=!1,$root.tensorflow.OpDef.prototype.is_aggregate=!1,$root.tensorflow.OpDef.prototype.is_stateful=!1,$root.tensorflow.OpDef.prototype.allows_uninitialized_input=!1,$root.tensorflow.OpDef.ArgDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDef.ArgDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.description=e.string();break;case 3:o.type=e.int32();break;case 4:o.type_attr=e.string();break;case 5:o.number_attr=e.string();break;case 6:o.type_list_attr=e.string();break;case 16:o.is_ref=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef.ArgDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"description":t.description=e.string();break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"type_attr":t.type_attr=e.string();break;case"number_attr":t.number_attr=e.string();break;case"type_list_attr":t.type_list_attr=e.string();break;case"is_ref":t.is_ref=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.ArgDef.prototype.name="",$root.tensorflow.OpDef.ArgDef.prototype.description="",$root.tensorflow.OpDef.ArgDef.prototype.type=0,$root.tensorflow.OpDef.ArgDef.prototype.type_attr="",$root.tensorflow.OpDef.ArgDef.prototype.number_attr="",$root.tensorflow.OpDef.ArgDef.prototype.type_list_attr="",$root.tensorflow.OpDef.ArgDef.prototype.is_ref=!1,$root.tensorflow.OpDef.AttrDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDef.AttrDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.type=e.string();break;case 3:o.default_value=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 4:o.description=e.string();break;case 5:o.has_minimum=e.bool();break;case 6:o.minimum=e.int64();break;case 7:o.allowed_values=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef.AttrDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"default_value":t.default_value=$root.tensorflow.AttrValue.decodeText(e,!0);break;case"description":t.description=e.string();break;case"has_minimum":t.has_minimum=e.boolean();break;case"minimum":t.minimum=e.integer();break;case"allowed_values":t.allowed_values=$root.tensorflow.AttrValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.AttrDef.prototype.name="",$root.tensorflow.OpDef.AttrDef.prototype.type="",$root.tensorflow.OpDef.AttrDef.prototype.default_value=null,$root.tensorflow.OpDef.AttrDef.prototype.description="",$root.tensorflow.OpDef.AttrDef.prototype.has_minimum=!1,$root.tensorflow.OpDef.AttrDef.prototype.minimum=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.OpDef.AttrDef.prototype.allowed_values=null,$root.tensorflow.OpDeprecation=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDeprecation,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.version=e.int32();break;case 2:o.explanation=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDeprecation;for(e.start();!e.end();){const o=e.tag();switch(o){case"version":t.version=e.integer();break;case"explanation":t.explanation=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDeprecation.prototype.version=0,$root.tensorflow.OpDeprecation.prototype.explanation="",$root.tensorflow.OpList=class{constructor(){this.op=[]}static decode(e,t){const o=new $root.tensorflow.OpList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.op.push($root.tensorflow.OpDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpList;for(e.start();!e.end();){const o=e.tag();switch(o){case"op":t.op.push($root.tensorflow.OpDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.VersionDef=class{constructor(){this.bad_consumers=[]}static decode(e,t){const o=new $root.tensorflow.VersionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.producer=e.int32();break;case 2:o.min_consumer=e.int32();break;case 3:o.bad_consumers=e.array(o.bad_consumers,(()=>e.int32()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VersionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"producer":t.producer=e.integer();break;case"min_consumer":t.min_consumer=e.integer();break;case"bad_consumers":e.array(t.bad_consumers,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.VersionDef.prototype.producer=0,$root.tensorflow.VersionDef.prototype.min_consumer=0,$root.tensorflow.SavedObjectGraph=class{constructor(){this.nodes=[],this.concrete_functions={}}static decode(e,t){const o=new $root.tensorflow.SavedObjectGraph,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.nodes.push($root.tensorflow.SavedObject.decode(e,e.uint32()));break;case 2:e.pair(o.concrete_functions,(()=>e.string()),(()=>$root.tensorflow.SavedConcreteFunction.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedObjectGraph;for(e.start();!e.end();){const o=e.tag();switch(o){case"nodes":t.nodes.push($root.tensorflow.SavedObject.decodeText(e,!0));break;case"concrete_functions":e.pair(t.concrete_functions,(()=>e.string()),(()=>$root.tensorflow.SavedConcreteFunction.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedObject=class{constructor(){this.children=[],this.slot_variables=[],this.saveable_objects={}}get kind(){return $root.tensorflow.SavedObject.kindSet=$root.tensorflow.SavedObject.kindSet||new Set(["user_object","asset","function","variable","bare_concrete_function","constant","resource"]),Object.keys(this).find((e=>$root.tensorflow.SavedObject.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.SavedObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decode(e,e.uint32()));break;case 3:o.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decode(e,e.uint32()));break;case 4:o.user_object=$root.tensorflow.SavedUserObject.decode(e,e.uint32());break;case 5:o.asset=$root.tensorflow.SavedAsset.decode(e,e.uint32());break;case 6:o.function=$root.tensorflow.SavedFunction.decode(e,e.uint32());break;case 7:o.variable=$root.tensorflow.SavedVariable.decode(e,e.uint32());break;case 8:o.bare_concrete_function=$root.tensorflow.SavedBareConcreteFunction.decode(e,e.uint32());break;case 9:o.constant=$root.tensorflow.SavedConstant.decode(e,e.uint32());break;case 10:o.resource=$root.tensorflow.SavedResource.decode(e,e.uint32());break;case 11:e.pair(o.saveable_objects,(()=>e.string()),(()=>$root.tensorflow.SaveableObject.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"children":t.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decodeText(e,!0));break;case"slot_variables":t.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decodeText(e,!0));break;case"user_object":t.user_object=$root.tensorflow.SavedUserObject.decodeText(e,!0);break;case"asset":t.asset=$root.tensorflow.SavedAsset.decodeText(e,!0);break;case"function":t.function=$root.tensorflow.SavedFunction.decodeText(e,!0);break;case"variable":t.variable=$root.tensorflow.SavedVariable.decodeText(e,!0);break;case"bare_concrete_function":t.bare_concrete_function=$root.tensorflow.SavedBareConcreteFunction.decodeText(e,!0);break;case"constant":t.constant=$root.tensorflow.SavedConstant.decodeText(e,!0);break;case"resource":t.resource=$root.tensorflow.SavedResource.decodeText(e,!0);break;case"saveable_objects":e.pair(t.saveable_objects,(()=>e.string()),(()=>$root.tensorflow.SaveableObject.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedUserObject=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedUserObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.identifier=e.string();break;case 2:o.version=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 3:o.metadata=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedUserObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"identifier":t.identifier=e.string();break;case"version":t.version=$root.tensorflow.VersionDef.decodeText(e,!0);break;case"metadata":t.metadata=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedUserObject.prototype.identifier="",$root.tensorflow.SavedUserObject.prototype.version=null,$root.tensorflow.SavedUserObject.prototype.metadata="",$root.tensorflow.SavedAsset=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedAsset,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.asset_file_def_index=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedAsset;for(e.start();!e.end();){const o=e.tag();switch(o){case"asset_file_def_index":t.asset_file_def_index=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedAsset.prototype.asset_file_def_index=0,$root.tensorflow.SavedFunction=class{constructor(){this.concrete_functions=[]}static decode(e,t){const o=new $root.tensorflow.SavedFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.concrete_functions.push(e.string());break;case 2:o.function_spec=$root.tensorflow.FunctionSpec.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"concrete_functions":e.array(t.concrete_functions,(()=>e.string()));break;case"function_spec":t.function_spec=$root.tensorflow.FunctionSpec.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedFunction.prototype.function_spec=null,$root.tensorflow.SavedConcreteFunction=class{constructor(){this.bound_inputs=[]}static decode(e,t){const o=new $root.tensorflow.SavedConcreteFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.bound_inputs=e.array(o.bound_inputs,(()=>e.int32()),t);break;case 3:o.canonicalized_input_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 4:o.output_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedConcreteFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"bound_inputs":e.array(t.bound_inputs,(()=>e.integer()));break;case"canonicalized_input_signature":t.canonicalized_input_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"output_signature":t.output_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedConcreteFunction.prototype.canonicalized_input_signature=null,$root.tensorflow.SavedConcreteFunction.prototype.output_signature=null,$root.tensorflow.SavedBareConcreteFunction=class{constructor(){this.argument_keywords=[]}static decode(e,t){const o=new $root.tensorflow.SavedBareConcreteFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.concrete_function_name=e.string();break;case 2:o.argument_keywords.push(e.string());break;case 3:o.allowed_positional_arguments=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedBareConcreteFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"concrete_function_name":t.concrete_function_name=e.string();break;case"argument_keywords":e.array(t.argument_keywords,(()=>e.string()));break;case"allowed_positional_arguments":t.allowed_positional_arguments=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedBareConcreteFunction.prototype.concrete_function_name="",$root.tensorflow.SavedBareConcreteFunction.prototype.allowed_positional_arguments=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.SavedConstant=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedConstant,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.operation=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedConstant;for(e.start();!e.end();){const o=e.tag();switch(o){case"operation":t.operation=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedConstant.prototype.operation="",$root.tensorflow.SavedVariable=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedVariable,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.trainable=e.bool();break;case 4:o.synchronization=e.int32();break;case 5:o.aggregation=e.int32();break;case 6:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedVariable;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"trainable":t.trainable=e.boolean();break;case"synchronization":t.synchronization=e.enum($root.tensorflow.VariableSynchronization);break;case"aggregation":t.aggregation=e.enum($root.tensorflow.VariableAggregation);break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedVariable.prototype.dtype=0,$root.tensorflow.SavedVariable.prototype.shape=null,$root.tensorflow.SavedVariable.prototype.trainable=!1,$root.tensorflow.SavedVariable.prototype.synchronization=0,$root.tensorflow.SavedVariable.prototype.aggregation=0,$root.tensorflow.SavedVariable.prototype.name="",$root.tensorflow.FunctionSpec=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.FunctionSpec,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.fullargspec=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 2:o.is_method=e.bool();break;case 5:o.input_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionSpec;for(e.start();!e.end();){const o=e.tag();switch(o){case"fullargspec":t.fullargspec=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"is_method":t.is_method=e.boolean();break;case"input_signature":t.input_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionSpec.prototype.fullargspec=null,$root.tensorflow.FunctionSpec.prototype.is_method=!1,$root.tensorflow.FunctionSpec.prototype.input_signature=null,$root.tensorflow.SavedResource=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedResource,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedResource;for(e.start();!e.end();){const o=e.tag();switch(o){case"device":t.device=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedResource.prototype.device="",$root.tensorflow.SaveableObject=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SaveableObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.save_function=e.int32();break;case 3:o.restore_function=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaveableObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"save_function":t.save_function=e.integer();break;case"restore_function":t.restore_function=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SaveableObject.prototype.save_function=0,$root.tensorflow.SaveableObject.prototype.restore_function=0,$root.tensorflow.VariableSynchronization={VARIABLE_SYNCHRONIZATION_AUTO:0,VARIABLE_SYNCHRONIZATION_NONE:1,VARIABLE_SYNCHRONIZATION_ON_WRITE:2,VARIABLE_SYNCHRONIZATION_ON_READ:3},$root.tensorflow.VariableAggregation={VARIABLE_AGGREGATION_NONE:0,VARIABLE_AGGREGATION_SUM:1,VARIABLE_AGGREGATION_MEAN:2,VARIABLE_AGGREGATION_ONLY_FIRST_REPLICA:3},$root.tensorflow.VariableDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.VariableDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.variable_name=e.string();break;case 6:o.initial_value_name=e.string();break;case 2:o.initializer_name=e.string();break;case 3:o.snapshot_name=e.string();break;case 4:o.save_slice_info_def=$root.tensorflow.SaveSliceInfoDef.decode(e,e.uint32());break;case 5:o.is_resource=e.bool();break;case 7:o.trainable=e.bool();break;case 8:o.synchronization=e.int32();break;case 9:o.aggregation=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VariableDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"variable_name":t.variable_name=e.string();break;case"initial_value_name":t.initial_value_name=e.string();break;case"initializer_name":t.initializer_name=e.string();break;case"snapshot_name":t.snapshot_name=e.string();break;case"save_slice_info_def":t.save_slice_info_def=$root.tensorflow.SaveSliceInfoDef.decodeText(e,!0);break;case"is_resource":t.is_resource=e.boolean();break;case"trainable":t.trainable=e.boolean();break;case"synchronization":t.synchronization=e.enum($root.tensorflow.VariableSynchronization);break;case"aggregation":t.aggregation=e.enum($root.tensorflow.VariableAggregation);break;default:e.field(o,t)}}return t}},$root.tensorflow.VariableDef.prototype.variable_name="",$root.tensorflow.VariableDef.prototype.initial_value_name="",$root.tensorflow.VariableDef.prototype.initializer_name="",$root.tensorflow.VariableDef.prototype.snapshot_name="",$root.tensorflow.VariableDef.prototype.save_slice_info_def=null,$root.tensorflow.VariableDef.prototype.is_resource=!1,$root.tensorflow.VariableDef.prototype.trainable=!1,$root.tensorflow.VariableDef.prototype.synchronization=0,$root.tensorflow.VariableDef.prototype.aggregation=0,$root.tensorflow.SaveSliceInfoDef=class{constructor(){this.full_shape=[],this.var_offset=[],this.var_shape=[]}static decode(e,t){const o=new $root.tensorflow.SaveSliceInfoDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.full_name=e.string();break;case 2:o.full_shape=e.array(o.full_shape,(()=>e.int64()),t);break;case 3:o.var_offset=e.array(o.var_offset,(()=>e.int64()),t);break;case 4:o.var_shape=e.array(o.var_shape,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaveSliceInfoDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"full_name":t.full_name=e.string();break;case"full_shape":e.array(t.full_shape,(()=>e.integer()));break;case"var_offset":e.array(t.var_offset,(()=>e.integer()));break;case"var_shape":e.array(t.var_shape,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.SaveSliceInfoDef.prototype.full_name="",$root.tensorflow.StructuredValue=class{constructor(){}get kind(){return $root.tensorflow.StructuredValue.kindSet=$root.tensorflow.StructuredValue.kindSet||new Set(["none_value","float64_value","int64_value","string_value","bool_value","tensor_shape_value","tensor_dtype_value","tensor_spec_value","type_spec_value","bounded_tensor_spec_value","list_value","tuple_value","dict_value","named_tuple_value"]),Object.keys(this).find((e=>$root.tensorflow.StructuredValue.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.StructuredValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.none_value=$root.tensorflow.NoneValue.decode(e,e.uint32());break;case 11:o.float64_value=e.double();break;case 12:o.int64_value=e.sint64();break;case 13:o.string_value=e.string();break;case 14:o.bool_value=e.bool();break;case 31:o.tensor_shape_value=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 32:o.tensor_dtype_value=e.int32();break;case 33:o.tensor_spec_value=$root.tensorflow.TensorSpecProto.decode(e,e.uint32());break;case 34:o.type_spec_value=$root.tensorflow.TypeSpecProto.decode(e,e.uint32());break;case 35:o.bounded_tensor_spec_value=$root.tensorflow.BoundedTensorSpecProto.decode(e,e.uint32());break;case 51:o.list_value=$root.tensorflow.ListValue.decode(e,e.uint32());break;case 52:o.tuple_value=$root.tensorflow.TupleValue.decode(e,e.uint32());break;case 53:o.dict_value=$root.tensorflow.DictValue.decode(e,e.uint32());break;case 54:o.named_tuple_value=$root.tensorflow.NamedTupleValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.StructuredValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"none_value":t.none_value=$root.tensorflow.NoneValue.decodeText(e,!0);break;case"float64_value":t.float64_value=e.float();break;case"int64_value":t.int64_value=e.integer();break;case"string_value":t.string_value=e.string();break;case"bool_value":t.bool_value=e.boolean();break;case"tensor_shape_value":t.tensor_shape_value=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"tensor_dtype_value":t.tensor_dtype_value=e.enum($root.tensorflow.DataType);break;case"tensor_spec_value":t.tensor_spec_value=$root.tensorflow.TensorSpecProto.decodeText(e,!0);break;case"type_spec_value":t.type_spec_value=$root.tensorflow.TypeSpecProto.decodeText(e,!0);break;case"bounded_tensor_spec_value":t.bounded_tensor_spec_value=$root.tensorflow.BoundedTensorSpecProto.decodeText(e,!0);break;case"list_value":t.list_value=$root.tensorflow.ListValue.decodeText(e,!0);break;case"tuple_value":t.tuple_value=$root.tensorflow.TupleValue.decodeText(e,!0);break;case"dict_value":t.dict_value=$root.tensorflow.DictValue.decodeText(e,!0);break;case"named_tuple_value":t.named_tuple_value=$root.tensorflow.NamedTupleValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.NoneValue=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.NoneValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();e.skipType(7&t)}return o}static decodeText(e){const t=new $root.tensorflow.NoneValue;for(e.start();!e.end();){const o=e.tag();e.field(o,t)}return t}},$root.tensorflow.ListValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.ListValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values.push($root.tensorflow.StructuredValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ListValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"values":t.values.push($root.tensorflow.StructuredValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TupleValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.TupleValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values.push($root.tensorflow.StructuredValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TupleValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"values":t.values.push($root.tensorflow.StructuredValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.DictValue=class{constructor(){this.fields={}}static decode(e,t){const o=new $root.tensorflow.DictValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.fields,(()=>e.string()),(()=>$root.tensorflow.StructuredValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.DictValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"fields":e.pair(t.fields,(()=>e.string()),(()=>$root.tensorflow.StructuredValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.PairValue=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.PairValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.key=e.string();break;case 2:o.value=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.PairValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"key":t.key=e.string();break;case"value":t.value=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.PairValue.prototype.key="",$root.tensorflow.PairValue.prototype.value=null,$root.tensorflow.NamedTupleValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.NamedTupleValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.values.push($root.tensorflow.PairValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NamedTupleValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"values":t.values.push($root.tensorflow.PairValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.NamedTupleValue.prototype.name="",$root.tensorflow.TensorSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.dtype=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSpecProto.prototype.name="",$root.tensorflow.TensorSpecProto.prototype.shape=null,$root.tensorflow.TensorSpecProto.prototype.dtype=0,$root.tensorflow.BoundedTensorSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.BoundedTensorSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.dtype=e.int32();break;case 4:o.minimum=$root.tensorflow.TensorProto.decode(e,e.uint32());break;case 5:o.maximum=$root.tensorflow.TensorProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BoundedTensorSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"minimum":t.minimum=$root.tensorflow.TensorProto.decodeText(e,!0);break;case"maximum":t.maximum=$root.tensorflow.TensorProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.BoundedTensorSpecProto.prototype.name="",$root.tensorflow.BoundedTensorSpecProto.prototype.shape=null,$root.tensorflow.BoundedTensorSpecProto.prototype.dtype=0,$root.tensorflow.BoundedTensorSpecProto.prototype.minimum=null,$root.tensorflow.BoundedTensorSpecProto.prototype.maximum=null,$root.tensorflow.TypeSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TypeSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_spec_class=e.int32();break;case 2:o.type_state=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 3:o.type_spec_class_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TypeSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_spec_class":t.type_spec_class=e.enum($root.tensorflow.TypeSpecProto.TypeSpecClass);break;case"type_state":t.type_state=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"type_spec_class_name":t.type_spec_class_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TypeSpecProto.prototype.type_spec_class=0,$root.tensorflow.TypeSpecProto.prototype.type_state=null,$root.tensorflow.TypeSpecProto.prototype.type_spec_class_name="",$root.tensorflow.TypeSpecProto.TypeSpecClass={UNKNOWN:0,SPARSE_TENSOR_SPEC:1,INDEXED_SLICES_SPEC:2,RAGGED_TENSOR_SPEC:3,TENSOR_ARRAY_SPEC:4,DATA_DATASET_SPEC:5,DATA_ITERATOR_SPEC:6,OPTIONAL_SPEC:7,PER_REPLICA_SPEC:8,VARIABLE_SPEC:9,ROW_PARTITION_SPEC:10},$root.tensorflow.TrackableObjectGraph=class{constructor(){this.nodes=[]}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.nodes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph;for(e.start();!e.end();){const o=e.tag();switch(o){case"nodes":t.nodes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject=class{constructor(){this.children=[],this.attributes=[],this.slot_variables=[]}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decode(e,e.uint32()));break;case 2:o.attributes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.decode(e,e.uint32()));break;case 3:o.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"children":t.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decodeText(e,!0));break;case"attributes":t.attributes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.decodeText(e,!0));break;case"slot_variables":t.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node_id=e.int32();break;case 2:o.local_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference;for(e.start();!e.end();){const o=e.tag();switch(o){case"node_id":t.node_id=e.integer();break;case"local_name":t.local_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.prototype.node_id=0,$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.prototype.local_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.full_name=e.string();break;case 3:o.checkpoint_key=e.string();break;case 4:o.optional_restore=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"full_name":t.full_name=e.string();break;case"checkpoint_key":t.checkpoint_key=e.string();break;case"optional_restore":t.optional_restore=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.full_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.checkpoint_key="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.optional_restore=!1,$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.original_variable_node_id=e.int32();break;case 2:o.slot_name=e.string();break;case 3:o.slot_variable_node_id=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference;for(e.start();!e.end();){const o=e.tag();switch(o){case"original_variable_node_id":t.original_variable_node_id=e.integer();break;case"slot_name":t.slot_name=e.string();break;case"slot_variable_node_id":t.slot_variable_node_id=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.original_variable_node_id=0,$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.slot_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.slot_variable_node_id=0,$root.tensorflow.SaverDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SaverDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.filename_tensor_name=e.string();break;case 2:o.save_tensor_name=e.string();break;case 3:o.restore_op_name=e.string();break;case 4:o.max_to_keep=e.int32();break;case 5:o.sharded=e.bool();break;case 6:o.keep_checkpoint_every_n_hours=e.float();break;case 7:o.version=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaverDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"filename_tensor_name":t.filename_tensor_name=e.string();break;case"save_tensor_name":t.save_tensor_name=e.string();break;case"restore_op_name":t.restore_op_name=e.string();break;case"max_to_keep":t.max_to_keep=e.integer();break;case"sharded":t.sharded=e.boolean();break;case"keep_checkpoint_every_n_hours":t.keep_checkpoint_every_n_hours=e.float();break;case"version":t.version=e.enum($root.tensorflow.SaverDef.CheckpointFormatVersion);break;default:e.field(o,t)}}return t}},$root.tensorflow.SaverDef.prototype.filename_tensor_name="",$root.tensorflow.SaverDef.prototype.save_tensor_name="",$root.tensorflow.SaverDef.prototype.restore_op_name="",$root.tensorflow.SaverDef.prototype.max_to_keep=0,$root.tensorflow.SaverDef.prototype.sharded=!1,$root.tensorflow.SaverDef.prototype.keep_checkpoint_every_n_hours=0,$root.tensorflow.SaverDef.prototype.version=0,$root.tensorflow.SaverDef.CheckpointFormatVersion={LEGACY:0,V1:1,V2:2},$root.tensorflow.BundleHeaderProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.BundleHeaderProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.num_shards=e.int32();break;case 2:o.endianness=e.int32();break;case 3:o.version=$root.tensorflow.VersionDef.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BundleHeaderProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"num_shards":t.num_shards=e.integer();break;case"endianness":t.endianness=e.enum($root.tensorflow.BundleHeaderProto.Endianness);break;case"version":t.version=$root.tensorflow.VersionDef.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.BundleHeaderProto.prototype.num_shards=0,$root.tensorflow.BundleHeaderProto.prototype.endianness=0,$root.tensorflow.BundleHeaderProto.prototype.version=null,$root.tensorflow.BundleHeaderProto.Endianness={LITTLE:0,BIG:1},$root.tensorflow.BundleEntryProto=class{constructor(){this.slices=[]}static decode(e,t){const o=new $root.tensorflow.BundleEntryProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.shard_id=e.int32();break;case 4:o.offset=e.int64();break;case 5:o.size=e.int64();break;case 6:o.crc32c=e.fixed32();break;case 7:o.slices.push($root.tensorflow.TensorSliceProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BundleEntryProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"shard_id":t.shard_id=e.integer();break;case"offset":t.offset=e.integer();break;case"size":t.size=e.integer();break;case"crc32c":t.crc32c=e.integer();break;case"slices":t.slices.push($root.tensorflow.TensorSliceProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.BundleEntryProto.prototype.dtype=0,$root.tensorflow.BundleEntryProto.prototype.shape=null,$root.tensorflow.BundleEntryProto.prototype.shard_id=0,$root.tensorflow.BundleEntryProto.prototype.offset=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.BundleEntryProto.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.BundleEntryProto.prototype.crc32c=0,$root.tensorflow.TensorSliceProto=class{constructor(){this.extent=[]}static decode(e,t){const o=new $root.tensorflow.TensorSliceProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.extent.push($root.tensorflow.TensorSliceProto.Extent.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSliceProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"extent":t.extent.push($root.tensorflow.TensorSliceProto.Extent.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSliceProto.Extent=class{constructor(){}get has_length(){return $root.tensorflow.TensorSliceProto.Extent.has_lengthSet=$root.tensorflow.TensorSliceProto.Extent.has_lengthSet||new Set(["length"]),Object.keys(this).find((e=>$root.tensorflow.TensorSliceProto.Extent.has_lengthSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.TensorSliceProto.Extent,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.start=e.int64();break;case 2:o.length=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSliceProto.Extent;for(e.start();!e.end();){const o=e.tag();switch(o){case"start":t.start=e.integer();break;case"length":t.length=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSliceProto.Extent.prototype.start=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.SavedSliceMeta=class{constructor(){this.slice=[]}static decode(e,t){const o=new $root.tensorflow.SavedSliceMeta,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.type=e.int32();break;case 4:o.slice.push($root.tensorflow.TensorSliceProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedSliceMeta;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"slice":t.slice.push($root.tensorflow.TensorSliceProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedSliceMeta.prototype.name="",$root.tensorflow.SavedSliceMeta.prototype.shape=null,$root.tensorflow.SavedSliceMeta.prototype.type=0,$root.tensorflow.SavedTensorSliceMeta=class{constructor(){this.tensor=[]}static decode(e,t){const o=new $root.tensorflow.SavedTensorSliceMeta,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.tensor.push($root.tensorflow.SavedSliceMeta.decode(e,e.uint32()));break;case 2:o.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedTensorSliceMeta;for(e.start();!e.end();){const o=e.tag();switch(o){case"tensor":t.tensor.push($root.tensorflow.SavedSliceMeta.decodeText(e,!0));break;case"versions":t.versions=$root.tensorflow.VersionDef.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedTensorSliceMeta.prototype.versions=null,$root.tensorflow.SavedSlice=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedSlice,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.slice=$root.tensorflow.TensorSliceProto.decode(e,e.uint32());break;case 3:o.data=$root.tensorflow.TensorProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedSlice;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"slice":t.slice=$root.tensorflow.TensorSliceProto.decodeText(e,!0);break;case"data":t.data=$root.tensorflow.TensorProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedSlice.prototype.name="",$root.tensorflow.SavedSlice.prototype.slice=null,$root.tensorflow.SavedSlice.prototype.data=null,$root.tensorflow.SavedTensorSlices=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedTensorSlices,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta=$root.tensorflow.SavedTensorSliceMeta.decode(e,e.uint32());break;case 2:o.data=$root.tensorflow.SavedSlice.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedTensorSlices;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta":t.meta=$root.tensorflow.SavedTensorSliceMeta.decodeText(e,!0);break;case"data":t.data=$root.tensorflow.SavedSlice.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedTensorSlices.prototype.meta=null,$root.tensorflow.SavedTensorSlices.prototype.data=null,$root.google={},$root.google.protobuf={},$root.google.protobuf.Any=class{constructor(){}static decode(e,t){const o=new $root.google.protobuf.Any,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_url=e.string();break;case 2:o.value=e.bytes();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.google.protobuf.Any;if(e.start(),e.any(t))return t;for(;!e.end();){const o=e.tag();switch(o){case"type_url":t.type_url=e.string();break;case"value":t.value=e.bytes();break;default:e.field(o,t)}}return t}},$root.google.protobuf.Any.prototype.type_url="",$root.google.protobuf.Any.prototype.value=new Uint8Array([]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf.js new file mode 100644 index 0000000000000000000000000000000000000000..b6c571adcb991fe33eac59eeedd39308cd4deca5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tf.js @@ -0,0 +1 @@ +var tf=tf||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");tf.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("meta"===s&&0!==t.tags("pb").size)return!0;if("pbtxt"===s||"prototxt"===s){if(e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const s=t.tags("pbtxt");if(s.has("input_stream")||s.has("output_stream"))return!1;if(s.has("node")||s.has("saved_model_schema_version")||s.has("meta_graphs")||s.has("graph_def"))return!0}if("pb"===s||"pbtxt"===s||"prototxt"===s){if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb"))return!1;if("tfhub_module.pb"==e){const e=t.buffer;if(e&&2==e.length&&8==e[0]&&3==e[1])return!1}const s=t.tags("pb");if(0===s.size){const e=t.tags("pbtxt");if(e.has("input_stream")||e.has("output_stream"))return!1;if(e.has("node")||e.has("saved_model_schema_version")||e.has("meta_graphs")||e.has("graph_def"))return!0}else{if(s.has(1)&&0===s.get(1)&&s.has(2)&&0===s.get(2)&&s.has(9)&&2===s.get(9))return!1;if(!Array.from(s.values()).some((t=>5===t)))return!0}}if("json"===s)try{const e=JSON.parse(t.text);if(e&&e.format&&"graph-model"===e.format&&e.modelTopology)return!0}catch(t){}if(("index"===s||"ckpt"===s)&&t.buffer.length>8){const e=t.buffer.subarray(t.buffer.length-8,t.buffer.length),s=[87,251,128,139,36,117,71,219];if(e.every(((t,e)=>t===s[e])))return!0}return!1}open(t,e){return e.require("./tf-proto").then((()=>{tf.proto=protobuf.get("tf").tensorflow;let s=null,n=null,o=null;const r=t.identifier,a=r.split(".").pop().toLowerCase();switch(a){case"ckpt":case"index":return tf.ModelFactory._openBundle(t,e);case"json":try{const e=JSON.parse(t.text),r=new tf.proto.GraphDef,a=new tf.proto.MetaGraphDef;a.graph_def=r,s=new tf.proto.SavedModel,s.meta_graphs.push(a);for(const t of e.modelTopology.node)r.node.push(t),t.input=t.input||[];n="TensorFlow.js "+e.format,o=e.convertedBy||e.generatedBy||""}catch(t){throw new tf.Error("File text format is not TensorFlow.js graph-model ("+t.message+") in '"+r+"'.")}break;default:{const e=t.tags("pbtxt");if(e.has("node")||e.has("saved_model_schema_version")||e.has("meta_graphs")||e.has("graph_def")){if(e.has("saved_model_schema_version")||e.has("meta_graphs"))try{(r.endsWith("saved_model.pbtxt")||r.endsWith("saved_model.prototxt"))&&(s=tf.proto.SavedModel.decodeText(protobuf.TextReader.create(t.text)),n="TensorFlow Saved Model",s&&Object.prototype.hasOwnProperty.call(s,"saved_model_schema_version")&&(n=n+" v"+s.saved_model_schema_version.toString()))}catch(t){throw new tf.Error("File text format is not tensorflow.SavedModel ("+t.message+") in '"+r+"'.")}else if(e.has("graph_def"))try{if(!s){const e=tf.proto.MetaGraphDef.decodeText(protobuf.TextReader.create(t.text));s=new tf.proto.SavedModel,s.meta_graphs.push(e),n="TensorFlow MetaGraph"}}catch(t){throw new tf.Error("File text format is not tensorflow.MetaGraphDef ("+t.message+") in '"+r+"'.")}else if(e.has("node"))try{const e=tf.proto.GraphDef.decodeText(protobuf.TextReader.create(t.text)),o=new tf.proto.MetaGraphDef;o.graph_def=e,s=new tf.proto.SavedModel,s.meta_graphs.push(o),n="TensorFlow Graph"}catch(t){throw new tf.Error("File text format is not tensorflow.GraphDef ("+t.message+") in '"+r+"'.")}}else{try{if(r.endsWith("saved_model.pb")){const e=protobuf.Reader.create(t.buffer);s=tf.proto.SavedModel.decode(e),n="TensorFlow Saved Model",s&&Object.prototype.hasOwnProperty.call(s,"saved_model_schema_version")&&(n=n+" v"+s.saved_model_schema_version.toString())}}catch(e){const s=t.buffer;if(s.length>3&&8==s[0]&&1==s[1]&&18==s[2])throw new tf.Error("File format is not tensorflow.SavedModel ("+e.message+") in '"+r+"'.")}try{if(!s&&"meta"==a){const e=protobuf.Reader.create(t.buffer),o=tf.proto.MetaGraphDef.decode(e);s=new tf.proto.SavedModel,s.meta_graphs.push(o),n="TensorFlow MetaGraph"}}catch(t){throw new tf.Error("File format is not tensorflow.MetaGraphDef ("+t.message+") in '"+r+"'.")}try{if(!s){const e=protobuf.Reader.create(t.buffer),o=tf.proto.GraphDef.decode(e),r=new tf.proto.MetaGraphDef;r.graph_def=o,s=new tf.proto.SavedModel,s.meta_graphs.push(r),n="TensorFlow Graph"}}catch(t){throw new tf.Error("File format is not tensorflow.GraphDef ("+t.message+") in '"+r+"'.")}}s&&s.meta_graphs&&s.meta_graphs.length>0&&s.meta_graphs[0].meta_info_def&&Object.prototype.hasOwnProperty.call(s.meta_graphs[0].meta_info_def,"tensorflow_version")&&(o="TensorFlow v"+s.meta_graphs[0].meta_info_def.tensorflow_version);break}}return tf.Metadata.open(e).then((a=>{if(1===s.meta_graphs.length&&s.meta_graphs[0].object_graph_def&&s.meta_graphs[0].object_graph_def.nodes&&s.meta_graphs[0].object_graph_def.nodes.length>0){const r="variables/variables.index";return t.request(r,null).then((i=>tf.TensorBundle.open(i,r,t,e).then((t=>tf.ModelFactory._openModel(r,e,a,s,n,o,t))))).catch((()=>tf.ModelFactory._openModel(r,e,a,s,n,o,null)))}return tf.ModelFactory._openModel(r,e,a,s,n,o,null)}))}))}static _openModel(t,e,s,n,o,r,a){try{return new tf.Model(s,n,o,r,a)}catch(s){e.exception(s,!1);const n=s&&s.message?s.message:s.toString();throw new tf.Error(n.replace(/\.$/,"")+" in '"+t+"'.")}}static _openBundle(t,e){return tf.Metadata.open(e).then((s=>{const n=t.identifier;return tf.TensorBundle.open(t.buffer,n,t,e).then((t=>new tf.Model(s,null,"TensorFlow Tensor Bundle v"+t.format.toString(),null,t))).catch((t=>{e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new tf.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}))}))}},tf.Model=class{constructor(t,e,s,n,o){if(this._format=s,this._producer=n||"",this._graphs=[],e){for(let s=0;s1?s.toString():"-",this._graphs.push(new tf.Graph(t,n,r,o))}const s=[],n=[...this._graphs];for(;n.length>0;){const t=n.shift();s.push(t);for(const e of t.functions)n.push(e)}this._graphs=s}else this._graphs.push(new tf.Graph(t,null,"",o))}get format(){return this._format}get producer(){return this._producer}get description(){return null}get graphs(){return this._graphs}},tf.Graph=class{constructor(t,e,s,n){if(this._metadata=t,this._version=null,this._name=s,this._inputs=[],this._outputs=[],this._nodes=[],this._functions=[],e&&e.graph_def){this._metadata=new tf.GraphMetadata(t,e.meta_info_def);const s=e.graph_def;s.versions?this._version="v"+s.versions.producer.toString():s.version?this._version=s.version:e.meta_info_def&&e.meta_info_def.tensorflow_version&&(this._version=e.meta_info_def.tensorflow_version),e.meta_info_def&&e.meta_info_def.tags&&(this._tags=e.meta_info_def.tags.join(", "));const n=s.node;if(n){const t={};this._namespaces={};for(const e of n){const s=e.name;if(t[s]=e,"Const"!=e.op){const t=s.lastIndexOf("/");if(-1!=t){const e=s.substring(0,t);this._namespaces[e]=!0}}e.output=[]}for(const e of n){const s=e.input;e.input=[],e.controlDependencies=[];for(const n of s){const s=n.split(":",2),o=s[0],r=1==s.length?0:parseInt(s[1]);let a=o.startsWith("^")?o.substring(1):o;const i=t[a];if(a=0==r?a:a+":"+r.toString(),o.startsWith("^")?e.controlDependencies.push(a):e.input.push(a),i){for(let t=i.output.length;t<=r;t++)i.output.push("");i.output[r]=a}}}this._nodeOutputCountMap={};for(const t of n){for(const e of t.input)this._nodeOutputCountMap[e]=(this._nodeOutputCountMap[e]||0)+1;for(const e of t.controlDependencies)this._nodeOutputCountMap[e]=(this._nodeOutputCountMap[e]||0)+1}const e={};for(const t of n)if("Const"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&this._checkSingleOutput(t)){const s=t.attr.value;if(s&&Object.prototype.hasOwnProperty.call(s,"tensor")){const n=t.output[0];n&&(e[n]=new tf.Tensor(s.tensor,t.name,"Constant"))}}for(const t of n)if("Identity"==t.op&&1==t.input.length&&0==t.controlDependencies.length&&this._checkSingleOutput(t)){const s=t.input[0],n=e[s];n&&(e[s]="-",n.kind="Identity Constant",e[t.output[0]]=n)}const s={};for(const t of n)if("Placeholder"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&1==t.output.length){const e=t.attr.dtype,n=t.attr.shape;if(e&&e.type&&n&&n.shape){const o=new tf.TensorType(e.type,n.shape),r=new tf.Argument(t.output[0],o,null);s[t.output[0]]=new tf.Parameter(t.name,[r])}}this._inputs=Object.keys(s).map((t=>s[t]));for(const t of n){const n=t.name;e[n]||s[n]||this._nodes.push(new tf.Node(this,t,t.op,t.name,e,null))}}if(s.library){const t=s.library.function;for(const e of t)this._functions.push(new tf.Function(this,e,this._metadata))}}else if(n){const t=[],e=new Map;for(const s of n.tensors){const o=s.name.split("/");if(2===n.format){if("_CHECKPOINTABLE_OBJECT_GRAPH"===s.name||s.name.startsWith("optimizer/")||s.name.startsWith("keras_api/metrics/")||s.name.endsWith("/ExponentialMovingAverage")||-1!==s.name.indexOf(".OPTIMIZER_SLOT"))continue;s.name.endsWith("/.ATTRIBUTES/VARIABLE_VALUE")&&(o.pop(),o.pop())}const r=o.pop(),a=o.join("/");e.has(a)||(t.push(a),e.set(a,[])),e.get(a).push({name:r,value:s})}for(const s of t)this._nodes.push(new tf.Node(this,null,"Node",s,null,e.get(s)))}}get name(){return this._name}get version(){return this._version}get tags(){return this._tags}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get metadata(){return this._metadata}get namespaces(){return this._namespaces}get functions(){return this._functions}_checkSingleOutput(t){if(1!=t.output.length)return!1;const e=t.output[0];return 1==this._nodeOutputCountMap[e]}},tf.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},tf.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new tf.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},tf.Function=class{constructor(t,e,s){this._name=e.signature.name,this._version=null,this._tags=null,this._inputs=[],this._outputs=[],this._nodes=[],this._metadata=s,this._namespaces={},this._functions=[];const n=e.signature.input_arg;if(n)for(const t of n){const e=new tf.Argument(t.name,new tf.TensorType(t.type,null),null);this._inputs.push(new tf.Parameter(t.name,[e]))}const o={};for(const t of Object.keys(e.ret)){const s=e.ret[t].split(":",2);o[t]=s[0]}const r={},a=e.signature.output_arg;if(a)for(const t of a){const e=o[t.name];this._outputs.push(new tf.Parameter(t.name,[new tf.Argument(e,new tf.TensorType(t.type,null),null)])),r[e]=t.name}const i=e.node_def;if(i){const t={};for(const e of i){const s=e.name;if(t[s]=e,"Const"!=e.op){const t=s.lastIndexOf("/");if(-1!=t){const e=s.substring(0,t);this._namespaces[e]=!0}}e.output=[]}for(const e of i){const s=e.input;e.input=[],e.controlDependencies=[];for(const n of s){const s=n.split(":",3),o=s[0],r=1==s.length?0:parseInt(s[s.length-1]);let a=o.startsWith("^")?o.substring(1):o;const i=t[a];if(a=0==r?a:a+":"+r.toString(),o.startsWith("^")?e.controlDependencies.push(a):e.input.push(a),i){for(let t=i.output.length;t<=r;t++)i.output.push("");i.output[r]=a}}r[e.name]&&e.output.push(e.name)}const e={};for(const t of i){for(const s of t.input)e[s]=(e[s]||0)+1;for(const s of t.controlDependencies)e[s]=(e[s]||0)+1}const s={};for(const t of i)if("Const"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&tf.Function._checkSingleOutput(t,e)){const e=t.attr.value;if(e&&Object.prototype.hasOwnProperty.call(e,"tensor")){const n=t.output[0];n&&(s[n]=new tf.Tensor(e.tensor,t.name,"Constant"))}}for(const t of i)if("Identity"==t.op&&1==t.input.length&&0==t.controlDependencies.length&&tf.Function._checkSingleOutput(t,e)){const e=t.input[0],n=s[e];n&&(s[e]="-",n.kind="Identity Constant",s[t.output[0]]=n)}for(const t of i)s[t.name]||this._nodes.push(new tf.Node(this,t,t.op,t.name,s,null))}}get name(){return this._name}get version(){return this._version}get tags(){return this._tags}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get metadata(){return this._metadata}get namespaces(){return this._namespaces}get functions(){return this._functions}static _checkSingleOutput(t,e){return 1==t.output.length&&1==e[t.output[0]]}},tf.Node=class{constructor(t,e,s,n,o,r){if(this._graph=t,this._type=s,this._name=n,this._attributes=[],this._inputs=[],this._outputs=[],e){Object.prototype.hasOwnProperty.call(e,"device")&&(this._device=e.device);const s=t.metadata;if(e.attr)for(const t of Object.keys(e.attr)){const n=s.attribute(this._type,t),o=!s.getAttributeVisibleMap(this._type)[t];this._attributes.push(new tf.Attribute(n,t,e.attr[t],o))}const n=s.type(this._type);let r=0;const a=e.input.filter((t=>!t.startsWith("^")));if(n&&n.inputs)for(const t of n.inputs){let s=1;if(t.numberAttr){const n=e.attr[t.numberAttr];n&&n.i&&(s=n.i)}else if(t.typeListAttr){const n=e.attr[t.typeListAttr];n&&n.list&&n.list.type&&(s=n.list.type.length)}const n=a.slice(r,r+s).map((t=>new tf.Argument(t,null,o[t])));this._inputs.push(new tf.Parameter(t.name,n)),r+=s}this._inputs=this._inputs.concat(a.slice(r).map(((t,e)=>new tf.Parameter((r+e).toString(),[new tf.Argument(t,null,o[t])]))));let i=0;const p=e.output;if(n&&n.outputs)for(const t of n.outputs){let s=1;if(t.numberAttr){const n=e.attr[t.numberAttr];n&&n.i&&(s=n.i)}else if(t.typeListAttr){const n=e.attr[t.typeListAttr];n&&n.list&&n.list.type&&(s=n.list.type.length)}const n=p.slice(i,i+s).map((t=>new tf.Argument(t,null,null)));this._outputs.push(new tf.Parameter(t.name,n)),i+=s}this._outputs=this._outputs.concat(p.slice(i).map(((t,e)=>new tf.Parameter((i+e).toString(),[new tf.Argument(t,null,null)])))),this._controlDependencies=e.controlDependencies}else if(r)for(const t of r)this._inputs.push(new tf.Parameter(t.name,[new tf.Argument(t.value.name,null,t.value)]))}get type(){return this._type}get name(){return this._name}get device(){return this._device||null}get group(){const t=this._name;if(this._graph.namespaces[t])return t;const e=t.lastIndexOf("/");if(-1!=e){const s=t.substring(0,e);if(this._graph.namespaces[s])return s}return""}get description(){return""}get domain(){return null}get metadata(){return this._graph.metadata.type(this.type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get controlDependencies(){return this._controlDependencies}get attributes(){return this._attributes}},tf.Attribute=class{constructor(t,e,s,n){switch(this._name=e,this._value=null,this._type=null,Object.prototype.hasOwnProperty.call(s,"tensor")?(this._type="tensor",this._value=new tf.Tensor(s.tensor)):t&&t.type&&(this._type=t.type),s.value){case"type":this._type="type",this._value=tf.Tensor.formatDataType(s.type);break;case"i":this._value=s.i;break;case"f":this._value=s.f;break;case"b":this._value=s.b;break;case"shape":this._type="shape",this._value=new tf.TensorShape(s.shape);break;case"s":this._value=tf.Utility.decodeText(s.s);break;case"func":{const t=s.func;this._type="function",this._value=t.name;break}case"list":{const t=s.list;t.s&&t.s.length>0?this._value=t.s.map((t=>tf.Utility.decodeText(t))):t.i&&t.i.length>0?this._value=t.i:t.f&&t.f.length>0?this._value=t.f:t.type&&t.type.length>0?(this._type="type[]",this._value=t.type.map((t=>tf.Tensor.formatDataType(t)))):t.shape&&t.shape.length>0?(this._type="shape[]",this._value=t.shape.map((t=>new tf.TensorShape(t)))):this._value=[];break}}if(t)if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")&&(!Array.isArray(this._value)||Array.isArray(t.default)||this._value.length===t.default.length)){let e=this._value,s=t.default;if("float32"===this._type){const t=new Float32Array(1);t[0]=e,e=t[0],t[0]=s,s=t[0]}const n=tf.GraphMetadata._formatAttributeValue(e),o=tf.GraphMetadata._formatAttributeValue(s);JSON.stringify(n)==JSON.stringify(o)&&(this._visible=!1)}"_output_shapes"==e&&(this._visible=!1,this._type="shape[]"),"_class"==e&&(this._visible=!1),!1===n&&(this._visible=!1)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},tf.Tensor=class{constructor(t,e,s){this._type=new tf.TensorType(t.dtype,t.tensor_shape||t.tensorShape),this._name=e,this._kind=s||null,this._tensor=t}get name(){return this._name}get type(){return this._type}get kind(){return this._kind}set kind(t){this._kind=t}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0,size:1};if(!this._tensor.dtype)return t.state="Tensor has no data type.",t;const e=this._tensor.tensor_shape||this._tensor.tensorShape;if(!e||!e.dim)return t.state="Tensor has no dimensions.",t;for(const s of e.dim)t.size=t.size*(s.size?s.size:0);switch(this._tensor.dtype){case"DT_FLOAT":case tf.proto.DataType.DT_FLOAT:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):this._tensor.float_val&&this._tensor.float_val.length==t.size?t.data=this._tensor.float_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_QINT8:case tf.proto.DataType.DT_QUINT8:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_INT32:case tf.proto.DataType.DT_UINT32:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):this._tensor.int_val&&this._tensor.int_val.length==t.size?t.data=this._tensor.int_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_STRING:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.state="Tensor data type is not implemented.":this._tensor.string_val&&this._tensor.string_val.length==t.size?t.data=this._tensor.string_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_BOOL:t.state="Tensor data type 'bool' is not implemented.";break;default:t.state="Tensor data type '"+this._tensor.dtype+"' is not implemented."}return t.shape=e.dim.map((t=>t.size)),t}_decode(t,e){let s=t.shape;0==s.length&&(s=[1]);const n=[],o=s[e];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;if(t.data){const e=t.data[t.index++];n.push(this._tensor.dtype==tf.proto.DataType.DT_STRING?tf.Utility.decodeText(e):e),t.count++}else if(t.rawData)switch(this._tensor.dtype){case tf.proto.DataType.DT_FLOAT:n.push(t.rawData.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_INT32:n.push(t.rawData.getInt32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_UINT32:n.push(t.rawData.getUint32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_QINT8:n.push(t.rawData.getInt8(t.index,!0)),t.index+=1,t.count++;break;case tf.proto.DataType.DT_QUINT8:n.push(t.rawData.getUint8(t.index,!0)),t.index+=1,t.count++}}else for(let r=0;rt.limit)return n.push("..."),n;n.push(this._decode(t,e+1,s))}return 0==t.shape.length?n[0]:n}static formatDataType(t){if(!tf.Tensor.dataType){tf.Tensor.dataType={};for(let t of Object.keys(tf.proto.DataType)){const e=tf.proto.DataType[t];t=t.startsWith("DT_")?t.substring(3):t,tf.Tensor.dataType[e]=t.toLowerCase()}tf.Tensor.dataType[tf.proto.DataType.DT_HALF]="float16",tf.Tensor.dataType[tf.proto.DataType.DT_FLOAT]="float32",tf.Tensor.dataType[tf.proto.DataType.DT_DOUBLE]="float64",tf.Tensor.dataType.DT_FLOAT="float32"}return tf.Tensor.dataType[t]||"?"}},tf.TensorType=class{constructor(t,e){this._dtype=t,this._shape=new tf.TensorShape(e)}get dataType(){return this._dtype?tf.Tensor.formatDataType(this._dtype):"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},tf.TensorShape=class{constructor(t){this._shape=t}get dimensions(){return this._shape&&this._shape.dim?this._shape.unknown_rank?null:0==this._shape.dim.length?[]:1!=this._shape.dim.length||this._shape.dim[0].size?this._shape.dim.map((t=>t.size&&-1!=t.size?t.size:"?")):[0]:null}toString(){return this._shape&&this._shape.dim?this._shape.unknown_rank?"[-]":0==this._shape.dim.length?"":1!=this._shape.dim.length||this._shape.dim[0].size?"["+this._shape.dim.map((t=>t.size&&-1!=t.size?t.size.toString():"?")).join(",")+"]":"[0]":"?"}},tf.TensorBundle=class{static open(t,e,s,n){const o=e.toLowerCase().endsWith(".index")?2:1;if(t.length<=48)throw new tf.Error("Invalid index file size.");const r=new tf.TensorBundle.BinaryReader(t,n);r.seek(-8);const a=[87,251,128,139,36,117,71,219];if(!r.bytes(8).every(((t,e)=>t===a[e])))throw new tf.Error("Invalid table signature.");r.seek(-48),r.varint64(),r.varint64();const i=r.varint64(),p=r.varint64();r.seek(i);const h=r.clone(p),u=r.byte();if(0!==u)throw new tf.Error("Unsupported block compression '"+u+"'.");h.seek(-4);const f=h.int32();h.seek(-4-4*f);const l=[];for(let t=0;tnew tf.TensorBundle(o,_,t))).catch((t=>(n.exception(t,!1),new tf.TensorBundle(o,_,null))))}constructor(t,e,s){switch(this._format=t,this._tensors=[],t){case 1:{const t=e.get(""),s=protobuf.Reader.create(t),n=tf.proto.SavedTensorSlices.decode(s),o=new Map;for(const t of e)if(""!==t[0]&&"global_step"!==t[0]){const e=protobuf.Reader.create(t[1]),s=tf.proto.SavedTensorSlices.decode(e),n=s.data.name,r=s.data.data;if(o.has(n)){const t=o.get(n);null!==t&&(r[t.key]&&r[t.key].length>0?t.value=t.value.concat(r[t.key]):o.set(n,null))}else if(r.tensor_content&&r.tensor_content.length>0)o.set(n,{key:"tensor_content",value:r.tensor_content});else{const t=Object.keys(r).filter((t=>t.endsWith("_val")&&r[t]&&r[t].length>0));o.set(n,1==t.length?{key:t[0],value:r[t[0]]}:null)}}for(const t of n.meta.tensor)if("global_step"!==t.name){const e=new tf.proto.TensorProto;e.dtype=t.type,e.tensor_shape=t.shape;const s=o.get(t.name);s&&(e[s.key]=s.value),this._tensors.push(new tf.Tensor(e,t.name,null))}break}case 2:e.forEach(((t,e)=>{if(""!==e){const n=protobuf.Reader.create(t),o=tf.proto.BundleEntryProto.decode(n),r=new tf.proto.TensorProto;r.dtype=o.dtype,r.tensor_shape=o.shape;const a=o.offset instanceof long.Long?o.offset.toNumber():o.offset,i=o.size instanceof long.Long?o.size.toNumber():o.size;s&&(r.tensor_content=s[o.shard_id].slice(a,a+i)),this._tensors.push(new tf.Tensor(r,e,null))}}))}}get format(){return this._format}get tensors(){return this._tensors}},tf.TensorBundle.BinaryReader=class{constructor(t){t&&(this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0,this._start=0,this._end=this._buffer.length)}seek(t){if(this._position=t>=0?this._start+t:this._end+t,this._position>this._end)throw new tf.Error("Expected "+(this._position-this._end)+" more bytes. The file might be corrupted. Unexpected end of file.")}skip(t){if(this._position+=t,this._position>this._end)throw new tf.Error("Expected "+(this._position-this._end)+" more bytes. The file might be corrupted. Unexpected end of file.")}end(){return this._position>=this._end}clone(t){const e=new tf.TensorBundle.BinaryReader;return e._buffer=this._buffer,e._dataView=this._dataView,e._start=this._position,e._position=this._position,this.skip(t),e._end=this._position,e}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}byte(){const t=this._position;return this.skip(1),this._dataView.getUint8(t)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}varint32(){return this.varint64()}varint64(){let t=0;for(let e=0;e<=63;e+=7){const s=this.byte();if(!(128&s)){t|=s<0)for(const t of e.attributes)s[t.name]=t;this._attributeCache[t]=s}return s[e]||null}getAttributeVisibleMap(t){const e=this.type(t);if(e){let t=e.__visisbleAttributeMap__;if(!t){if(t={},e.inputs)for(const s of e.inputs)s.typeAttr?t[s.typeAttr]=!0:s.typeListAttr&&(t[s.typeListAttr]=!0),s.numberAttr&&(t[s.numberAttr]=!0);if(e.outputs)for(const s of e.outputs)s.typeAttr?t[s.typeAttr]=!0:s.typeListAttr&&(t[s.typeListAttr]=!0),s.numberAttr&&(t[s.numberAttr]=!0);e.__visisbleAttributeMap__=t}return t}return{}}static _formatAttributeValue(t){if(null==t)return null;if(t&&long.Long.isLong(t)&&(t=t.toNumber()),Array.isArray(t))return t.map((t=>tf.GraphMetadata._formatAttributeValue(t)));if(t===Object(t))switch(t.type){case"type":return tf.Tensor.formatDataType(t.value);case"shape":case"tensor":return t.value}return"string"==typeof t?'"'+t+'"':t.toString()}},tf.Metadata=class{static open(t){return tf.Metadata._metadata?Promise.resolve(tf.Metadata._metadata):t.request(null,"tf-metadata.json","utf-8").then((t=>(tf.Metadata._metadata=new tf.Metadata(t),tf.Metadata._metadata))).catch((()=>(tf.Metadata._metadata=new tf.Metadata(null),tf.Metadata._metadata)))}constructor(t){if(this._map={},t&&t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]}},tf.Utility=class{static decodeText(t){return"string"==typeof t?t:0===t.length?"":(tf.Utility._utf8Decoder=tf.Utility._utf8Decoder||new TextDecoder("utf-8"),tf.Utility._utf8Decoder.decode(t))}},tf.Error=class extends Error{constructor(t){super(t),this.name="Error loading TensorFlow model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tf.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..2ffb8b80bcdcbbef7f32c2abb47af43cf6ed6510 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-metadata.json @@ -0,0 +1 @@ +[{"name":"Conv2D","schema":{"category":"Layer","inputs":[{"name":"input","description":"4D tensor"},{"name":"filter"},{"name":"bias","description":"(optional)"}],"outputs":[{"name":"output","description":"result of 2D convolution of the input tensor"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME","description":"`SAME`|`VALID`"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE","description":"`NONE`|`RELU`|`RELU6`"},{"name":"stride_w","type":"int32","default":1,"description":"stride of the filter window"},{"name":"stride_h","type":"int32","default":1,"description":"stride of the filter window"},{"name":"dilation_w_factor","type":"int32","default":1},{"name":"dilation_h_factor","type":"int32","default":1}]}},{"name":"LSTM","schema":{"category":"Layer","inputs":[{"name":"input","type":"T","description":"Input tensor."},{"name":"input_input_weights","type":"T","option":"optional","description":"Input to input weights tensor.","visible":false},{"name":"input_forget_weights","type":"T","description":"Input to forget weights tensor.","visible":false},{"name":"input_cell_weights","type":"T","description":"Input to cell weights tensor.","visible":false},{"name":"input_output_weights","type":"T","description":"Input to output weights tensor.","visible":false},{"name":"recurrent_input_weights","type":"T","option":"optional","description":"Recurrent to input weights tensor.","visible":false},{"name":"recurrent_forget_weights","type":"T","description":"Recurrent to forget weights tensor.","visible":false},{"name":"recurrent_cell_weights","type":"T","description":"Recurrent to cell weights tensor.","visible":false},{"name":"recurrent_output_weights","type":"T","description":"Recurrent to output weights tensor.","visible":false},{"name":"cell_input_weights","type":"T","option":"optional","description":"Cell to input weights tensor.","visible":false},{"name":"cell_forget_weights","type":"T","option":"optional","description":"Cell to forget weights tensor.","visible":false},{"name":"cell_output_weights","type":"T","option":"optional","description":"Cell to output weights tensor.","visible":false},{"name":"input_bias","type":"T","option":"optional","description":"Input gate bias tensor.","visible":false},{"name":"forget_bias","type":"T","description":"Forget gate bias tensor.","visible":false},{"name":"cell_bias","type":"T","description":"Cell gate bias tensor.","visible":false},{"name":"output_bias","type":"T","description":"Output gate bias tensor.","visible":false},{"name":"projection_weights","type":"T","option":"optional","description":"Projection weights tensor.","visible":false},{"name":"projection_bias","type":"T","option":"optional","description":"Projection bias tensor.","visible":false}],"outputs":[{"name":"scratch","type":"T"},{"name":"output_state","type":"T"},{"name":"cell_state","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"cell_clip","type":"float32","default":0},{"name":"proj_clip","type":"float32","default":0},{"name":"kernel_type","type":"LSTMKernelType","default":"FULL"}]}},{"name":"RNN","schema":{"category":"Layer","inputs":[{"name":"X","type":"T"},{"name":"W","type":"T"},{"name":"R","type":"T"},{"name":"b","type":"T"}],"outputs":[{"name":"hidden","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"FullyConnected","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"weights","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"weights_format","type":"FullyConnectedOptionsWeightsFormat","default":"DEFAULT"},{"name":"keep_num_dims","type":"boolean"}]}},{"name":"DepthwiseConv2D","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"weights","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32","default":1},{"name":"stride_h","type":"int32","default":1},{"name":"depth_multiplier","type":"int32","default":1},{"name":"dilation_w_factor","type":"int32","default":1},{"name":"dilation_h_factor","type":"int32","default":1}]}},{"name":"AveragePool2D","schema":{"category":"Pool","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"},{"name":"filter_width","type":"int32"},{"name":"filter_height","type":"int32"}]}},{"name":"Softmax","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"LogSoftmax","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Relu","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Relu6","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Prelu","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"},{"name":"slope","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","attributes":[{"name":"new_shape","type":"shape"}],"inputs":[{"name":"data","type":"T"},{"name":"shape","type":"T"}],"outputs":[{"name":"reshaped","type":"T"}]}},{"name":"MaxPool2D","schema":{"category":"Pool","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"},{"name":"filter_width","type":"int32"},{"name":"filter_height","type":"int32"}]}},{"name":"LSHProjection","schema":{"inputs":[{"name":"hash"},{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}],"attributes":[{"name":"type","type":"LSHProjectionType"}]}},{"name":"Normalize","schema":{"category":"Normalization","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LocalResponseNormalization","schema":{"category":"Normalization","attributes":[{"name":"radius","type":"int32","default":5},{"name":"bias","type":"float32","default":1},{"name":"alpha","type":"float32","default":1},{"name":"beta","type":"float32","default":0.5}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Predict","schema":{"inputs":[{"name":"hashes"},{"name":"keys"},{"name":"labels"},{"name":"weights"}],"outputs":[{"name":"label"},{"name":"weight"}]}},{"name":"HashtableLookup","schema":{"inputs":[{"name":"key"},{"name":"keys"},{"name":"values"}],"outputs":[{"name":"value"},{"name":"hits"}]}},{"name":"ExtractFeatures","schema":{"inputs":[{"name":"ngrams"}],"outputs":[{"name":"features"},{"name":"weights"}]}},{"name":"SkipGram","schema":{"inputs":[{"name":"inputs"}],"outputs":[{"name":"ngrams"}]}},{"name":"Concatenation","schema":{"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"attributes":[{"name":"axis","type":"int32"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Pad","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"paddings"}],"outputs":[{"name":"output"}]}},{"name":"Split","schema":{"category":"Tensor","inputs":[{"name":"axis"},{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Squeeze","schema":{"category":"Transform","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"StridedSlice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"end"},{"name":"strides"}],"outputs":[{"name":"output"}]}},{"name":"SVDF","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"feature","type":"T"},{"name":"time","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"state","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Add","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Sub","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Mul","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Div","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Sum","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"ReduceMax","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"ReduceMin","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"Mean","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"Logistic","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ResizeBilinear","schema":{"attributes":[{"name":"align_corners","default":false}],"inputs":[{"name":"input"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Gather","schema":{"attributes":[{"name":"axis","default":0}],"inputs":[{"name":"input"},{"name":"positions"}],"outputs":[{"name":"output"}]}},{"name":"Cast","schema":{"attributes":[{"name":"in_data_type","type":"TensorType"},{"name":"out_data_type","type":"TensorType"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ArgMax","schema":{"attributes":[{"name":"output_type","type":"TensorType"}]}},{"name":"ArgMin","schema":{"attributes":[{"name":"output_type","type":"TensorType"}]}},{"name":"TransposeConv","schema":{"category":"Layer","attributes":[{"name":"padding","type":"Padding"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"}],"inputs":[{"name":"output_shape"},{"name":"weights"},{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Shape","schema":{"attributes":[{"name":"out_type","type":"TensorType"}]}},{"name":"Unique","schema":{"attributes":[{"name":"idx_out_type","type":"TensorType","default":"int32"}]}},{"name":"Slice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Transpose","schema":{"category":"Transform","inputs":[{"name":"input"},{"name":"perm"}],"outputs":[{"name":"output"}]}},{"name":"Quantize","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Dequantize","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Minimum","schema":{"inputs":[{"name":"input1"},{"name":"input2"}],"outputs":[{"name":"output"}]}},{"name":"Maximum","schema":{"inputs":[{"name":"input1"},{"name":"input2"}],"outputs":[{"name":"output"}]}},{"name":"HardSwish","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-schema.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..85baa44a6b4f070d2028f15481c894a764e6f1ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite-schema.js @@ -0,0 +1 @@ +var $root=flatbuffers.get("tflite");$root.tflite=$root.tflite||{},$root.tflite.TensorType={FLOAT32:0,FLOAT16:1,INT32:2,UINT8:3,INT64:4,STRING:5,BOOL:6,INT16:7,COMPLEX64:8,INT8:9,FLOAT64:10,COMPLEX128:11},$root.tflite.CustomQuantization=class{static decode(t,e){const o=new $root.tflite.CustomQuantization;return o.custom=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.CustomQuantization;return o.custom=t.typedArray(e.custom,Uint8Array),o}},$root.tflite.QuantizationDetails=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.CustomQuantization.decode(t,e)}}static decodeText(t,e,o){switch(o){case"CustomQuantization":return $root.tflite.CustomQuantization.decodeText(t,e)}}},$root.tflite.QuantizationParameters=class{static decode(t,e){const o=new $root.tflite.QuantizationParameters;return o.min=t.typedArray(e,4,Float32Array),o.max=t.typedArray(e,6,Float32Array),o.scale=t.typedArray(e,8,Float32Array),o.zero_point=t.int64s_(e,10),o.details=t.union(e,12,$root.tflite.QuantizationDetails.decode),o.quantized_dimension=t.int32_(e,16,0),o}static decodeText(t,e){const o=new $root.tflite.QuantizationParameters;return o.min=t.typedArray(e.min,Float32Array),o.max=t.typedArray(e.max,Float32Array),o.scale=t.typedArray(e.scale,Float32Array),o.zero_point=t.array(e.zero_point),o.details=$root.tflite.QuantizationDetails.decodeText(t,e.details,e.details_type),o.quantized_dimension=t.value(e.quantized_dimension,0),o}},$root.tflite.DimensionType={DENSE:0,SPARSE_CSR:1},$root.tflite.Int32Vector=class{static decode(t,e){const o=new $root.tflite.Int32Vector;return o.values=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Int32Vector;return o.values=t.typedArray(e.values,Int32Array),o}},$root.tflite.Uint16Vector=class{static decode(t,e){const o=new $root.tflite.Uint16Vector;return o.values=t.typedArray(e,4,Uint16Array),o}static decodeText(t,e){const o=new $root.tflite.Uint16Vector;return o.values=t.typedArray(e.values,Uint16Array),o}},$root.tflite.Uint8Vector=class{static decode(t,e){const o=new $root.tflite.Uint8Vector;return o.values=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.Uint8Vector;return o.values=t.typedArray(e.values,Uint8Array),o}},$root.tflite.SparseIndexVector=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.Int32Vector.decode(t,e);case 2:return $root.tflite.Uint16Vector.decode(t,e);case 3:return $root.tflite.Uint8Vector.decode(t,e)}}static decodeText(t,e,o){switch(o){case"Int32Vector":return $root.tflite.Int32Vector.decodeText(t,e);case"Uint16Vector":return $root.tflite.Uint16Vector.decodeText(t,e);case"Uint8Vector":return $root.tflite.Uint8Vector.decodeText(t,e)}}},$root.tflite.DimensionMetadata=class{static decode(t,e){const o=new $root.tflite.DimensionMetadata;return o.format=t.int8_(e,4,0),o.dense_size=t.int32_(e,6,0),o.array_segments=t.union(e,8,$root.tflite.SparseIndexVector.decode),o.array_indices=t.union(e,12,$root.tflite.SparseIndexVector.decode),o}static decodeText(t,e){const o=new $root.tflite.DimensionMetadata;return o.format=$root.tflite.DimensionType[e.format],o.dense_size=t.value(e.dense_size,0),o.array_segments=$root.tflite.SparseIndexVector.decodeText(t,e.array_segments,e.array_segments_type),o.array_indices=$root.tflite.SparseIndexVector.decodeText(t,e.array_indices,e.array_indices_type),o}},$root.tflite.SparsityParameters=class{static decode(t,e){const o=new $root.tflite.SparsityParameters;return o.traversal_order=t.typedArray(e,4,Int32Array),o.block_map=t.typedArray(e,6,Int32Array),o.dim_metadata=t.tableArray(e,8,$root.tflite.DimensionMetadata.decode),o}static decodeText(t,e){const o=new $root.tflite.SparsityParameters;return o.traversal_order=t.typedArray(e.traversal_order,Int32Array),o.block_map=t.typedArray(e.block_map,Int32Array),o.dim_metadata=t.objectArray(e.dim_metadata,$root.tflite.DimensionMetadata.decodeText),o}},$root.tflite.Tensor=class{static decode(t,e){const o=new $root.tflite.Tensor;return o.shape=t.typedArray(e,4,Int32Array),o.type=t.int8_(e,6,0),o.buffer=t.uint32_(e,8,0),o.name=t.string_(e,10,null),o.quantization=t.table(e,12,$root.tflite.QuantizationParameters.decode),o.is_variable=t.bool_(e,14,!1),o.sparsity=t.table(e,16,$root.tflite.SparsityParameters.decode),o.shape_signature=t.typedArray(e,18,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Tensor;return o.shape=t.typedArray(e.shape,Int32Array),o.type=$root.tflite.TensorType[e.type],o.buffer=t.value(e.buffer,0),o.name=t.value(e.name,null),o.quantization=t.object(e.quantization,$root.tflite.QuantizationParameters.decodeText),o.is_variable=t.value(e.is_variable,!1),o.sparsity=t.object(e.sparsity,$root.tflite.SparsityParameters.decodeText),o.shape_signature=t.typedArray(e.shape_signature,Int32Array),o}},$root.tflite.BuiltinOperator={ADD:0,AVERAGE_POOL_2D:1,CONCATENATION:2,CONV_2D:3,DEPTHWISE_CONV_2D:4,DEPTH_TO_SPACE:5,DEQUANTIZE:6,EMBEDDING_LOOKUP:7,FLOOR:8,FULLY_CONNECTED:9,HASHTABLE_LOOKUP:10,L2_NORMALIZATION:11,L2_POOL_2D:12,LOCAL_RESPONSE_NORMALIZATION:13,LOGISTIC:14,LSH_PROJECTION:15,LSTM:16,MAX_POOL_2D:17,MUL:18,RELU:19,RELU_N1_TO_1:20,RELU6:21,RESHAPE:22,RESIZE_BILINEAR:23,RNN:24,SOFTMAX:25,SPACE_TO_DEPTH:26,SVDF:27,TANH:28,CONCAT_EMBEDDINGS:29,SKIP_GRAM:30,CALL:31,CUSTOM:32,EMBEDDING_LOOKUP_SPARSE:33,PAD:34,UNIDIRECTIONAL_SEQUENCE_RNN:35,GATHER:36,BATCH_TO_SPACE_ND:37,SPACE_TO_BATCH_ND:38,TRANSPOSE:39,MEAN:40,SUB:41,DIV:42,SQUEEZE:43,UNIDIRECTIONAL_SEQUENCE_LSTM:44,STRIDED_SLICE:45,BIDIRECTIONAL_SEQUENCE_RNN:46,EXP:47,TOPK_V2:48,SPLIT:49,LOG_SOFTMAX:50,DELEGATE:51,BIDIRECTIONAL_SEQUENCE_LSTM:52,CAST:53,PRELU:54,MAXIMUM:55,ARG_MAX:56,MINIMUM:57,LESS:58,NEG:59,PADV2:60,GREATER:61,GREATER_EQUAL:62,LESS_EQUAL:63,SELECT:64,SLICE:65,SIN:66,TRANSPOSE_CONV:67,SPARSE_TO_DENSE:68,TILE:69,EXPAND_DIMS:70,EQUAL:71,NOT_EQUAL:72,LOG:73,SUM:74,SQRT:75,RSQRT:76,SHAPE:77,POW:78,ARG_MIN:79,FAKE_QUANT:80,REDUCE_PROD:81,REDUCE_MAX:82,PACK:83,LOGICAL_OR:84,ONE_HOT:85,LOGICAL_AND:86,LOGICAL_NOT:87,UNPACK:88,REDUCE_MIN:89,FLOOR_DIV:90,REDUCE_ANY:91,SQUARE:92,ZEROS_LIKE:93,FILL:94,FLOOR_MOD:95,RANGE:96,RESIZE_NEAREST_NEIGHBOR:97,LEAKY_RELU:98,SQUARED_DIFFERENCE:99,MIRROR_PAD:100,ABS:101,SPLIT_V:102,UNIQUE:103,CEIL:104,REVERSE_V2:105,ADD_N:106,GATHER_ND:107,COS:108,WHERE:109,RANK:110,ELU:111,REVERSE_SEQUENCE:112,MATRIX_DIAG:113,QUANTIZE:114,MATRIX_SET_DIAG:115,ROUND:116,HARD_SWISH:117,IF:118,WHILE:119,NON_MAX_SUPPRESSION_V4:120,NON_MAX_SUPPRESSION_V5:121,SCATTER_ND:122,SELECT_V2:123,DENSIFY:124,SEGMENT_SUM:125,BATCH_MATMUL:126},$root.tflite.BuiltinOptions=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.Conv2DOptions.decode(t,e);case 2:return $root.tflite.DepthwiseConv2DOptions.decode(t,e);case 3:return $root.tflite.ConcatEmbeddingsOptions.decode(t,e);case 4:return $root.tflite.LSHProjectionOptions.decode(t,e);case 5:return $root.tflite.Pool2DOptions.decode(t,e);case 6:return $root.tflite.SVDFOptions.decode(t,e);case 7:return $root.tflite.RNNOptions.decode(t,e);case 8:return $root.tflite.FullyConnectedOptions.decode(t,e);case 9:return $root.tflite.SoftmaxOptions.decode(t,e);case 10:return $root.tflite.ConcatenationOptions.decode(t,e);case 11:return $root.tflite.AddOptions.decode(t,e);case 12:return $root.tflite.L2NormOptions.decode(t,e);case 13:return $root.tflite.LocalResponseNormalizationOptions.decode(t,e);case 14:return $root.tflite.LSTMOptions.decode(t,e);case 15:return $root.tflite.ResizeBilinearOptions.decode(t,e);case 16:return $root.tflite.CallOptions.decode(t,e);case 17:return $root.tflite.ReshapeOptions.decode(t,e);case 18:return $root.tflite.SkipGramOptions.decode(t,e);case 19:return $root.tflite.SpaceToDepthOptions.decode(t,e);case 20:return $root.tflite.EmbeddingLookupSparseOptions.decode(t,e);case 21:return $root.tflite.MulOptions.decode(t,e);case 22:return $root.tflite.PadOptions.decode(t,e);case 23:return $root.tflite.GatherOptions.decode(t,e);case 24:return $root.tflite.BatchToSpaceNDOptions.decode(t,e);case 25:return $root.tflite.SpaceToBatchNDOptions.decode(t,e);case 26:return $root.tflite.TransposeOptions.decode(t,e);case 27:return $root.tflite.ReducerOptions.decode(t,e);case 28:return $root.tflite.SubOptions.decode(t,e);case 29:return $root.tflite.DivOptions.decode(t,e);case 30:return $root.tflite.SqueezeOptions.decode(t,e);case 31:return $root.tflite.SequenceRNNOptions.decode(t,e);case 32:return $root.tflite.StridedSliceOptions.decode(t,e);case 33:return $root.tflite.ExpOptions.decode(t,e);case 34:return $root.tflite.TopKV2Options.decode(t,e);case 35:return $root.tflite.SplitOptions.decode(t,e);case 36:return $root.tflite.LogSoftmaxOptions.decode(t,e);case 37:return $root.tflite.CastOptions.decode(t,e);case 38:return $root.tflite.DequantizeOptions.decode(t,e);case 39:return $root.tflite.MaximumMinimumOptions.decode(t,e);case 40:return $root.tflite.ArgMaxOptions.decode(t,e);case 41:return $root.tflite.LessOptions.decode(t,e);case 42:return $root.tflite.NegOptions.decode(t,e);case 43:return $root.tflite.PadV2Options.decode(t,e);case 44:return $root.tflite.GreaterOptions.decode(t,e);case 45:return $root.tflite.GreaterEqualOptions.decode(t,e);case 46:return $root.tflite.LessEqualOptions.decode(t,e);case 47:return $root.tflite.SelectOptions.decode(t,e);case 48:return $root.tflite.SliceOptions.decode(t,e);case 49:return $root.tflite.TransposeConvOptions.decode(t,e);case 50:return $root.tflite.SparseToDenseOptions.decode(t,e);case 51:return $root.tflite.TileOptions.decode(t,e);case 52:return $root.tflite.ExpandDimsOptions.decode(t,e);case 53:return $root.tflite.EqualOptions.decode(t,e);case 54:return $root.tflite.NotEqualOptions.decode(t,e);case 55:return $root.tflite.ShapeOptions.decode(t,e);case 56:return $root.tflite.PowOptions.decode(t,e);case 57:return $root.tflite.ArgMinOptions.decode(t,e);case 58:return $root.tflite.FakeQuantOptions.decode(t,e);case 59:return $root.tflite.PackOptions.decode(t,e);case 60:return $root.tflite.LogicalOrOptions.decode(t,e);case 61:return $root.tflite.OneHotOptions.decode(t,e);case 62:return $root.tflite.LogicalAndOptions.decode(t,e);case 63:return $root.tflite.LogicalNotOptions.decode(t,e);case 64:return $root.tflite.UnpackOptions.decode(t,e);case 65:return $root.tflite.FloorDivOptions.decode(t,e);case 66:return $root.tflite.SquareOptions.decode(t,e);case 67:return $root.tflite.ZerosLikeOptions.decode(t,e);case 68:return $root.tflite.FillOptions.decode(t,e);case 69:return $root.tflite.BidirectionalSequenceLSTMOptions.decode(t,e);case 70:return $root.tflite.BidirectionalSequenceRNNOptions.decode(t,e);case 71:return $root.tflite.UnidirectionalSequenceLSTMOptions.decode(t,e);case 72:return $root.tflite.FloorModOptions.decode(t,e);case 73:return $root.tflite.RangeOptions.decode(t,e);case 74:return $root.tflite.ResizeNearestNeighborOptions.decode(t,e);case 75:return $root.tflite.LeakyReluOptions.decode(t,e);case 76:return $root.tflite.SquaredDifferenceOptions.decode(t,e);case 77:return $root.tflite.MirrorPadOptions.decode(t,e);case 78:return $root.tflite.AbsOptions.decode(t,e);case 79:return $root.tflite.SplitVOptions.decode(t,e);case 80:return $root.tflite.UniqueOptions.decode(t,e);case 81:return $root.tflite.ReverseV2Options.decode(t,e);case 82:return $root.tflite.AddNOptions.decode(t,e);case 83:return $root.tflite.GatherNdOptions.decode(t,e);case 84:return $root.tflite.CosOptions.decode(t,e);case 85:return $root.tflite.WhereOptions.decode(t,e);case 86:return $root.tflite.RankOptions.decode(t,e);case 87:return $root.tflite.ReverseSequenceOptions.decode(t,e);case 88:return $root.tflite.MatrixDiagOptions.decode(t,e);case 89:return $root.tflite.QuantizeOptions.decode(t,e);case 90:return $root.tflite.MatrixSetDiagOptions.decode(t,e);case 91:return $root.tflite.HardSwishOptions.decode(t,e);case 92:return $root.tflite.IfOptions.decode(t,e);case 93:return $root.tflite.WhileOptions.decode(t,e);case 94:return $root.tflite.DepthToSpaceOptions.decode(t,e);case 95:return $root.tflite.NonMaxSuppressionV4Options.decode(t,e);case 96:return $root.tflite.NonMaxSuppressionV5Options.decode(t,e);case 97:return $root.tflite.ScatterNdOptions.decode(t,e);case 98:return $root.tflite.SelectV2Options.decode(t,e);case 99:return $root.tflite.DensifyOptions.decode(t,e);case 100:return $root.tflite.SegmentSumOptions.decode(t,e);case 101:return $root.tflite.BatchMatMulOptions.decode(t,e)}}static decodeText(t,e,o){switch(o){case"Conv2DOptions":return $root.tflite.Conv2DOptions.decodeText(t,e);case"DepthwiseConv2DOptions":return $root.tflite.DepthwiseConv2DOptions.decodeText(t,e);case"ConcatEmbeddingsOptions":return $root.tflite.ConcatEmbeddingsOptions.decodeText(t,e);case"LSHProjectionOptions":return $root.tflite.LSHProjectionOptions.decodeText(t,e);case"Pool2DOptions":return $root.tflite.Pool2DOptions.decodeText(t,e);case"SVDFOptions":return $root.tflite.SVDFOptions.decodeText(t,e);case"RNNOptions":return $root.tflite.RNNOptions.decodeText(t,e);case"FullyConnectedOptions":return $root.tflite.FullyConnectedOptions.decodeText(t,e);case"SoftmaxOptions":return $root.tflite.SoftmaxOptions.decodeText(t,e);case"ConcatenationOptions":return $root.tflite.ConcatenationOptions.decodeText(t,e);case"AddOptions":return $root.tflite.AddOptions.decodeText(t,e);case"L2NormOptions":return $root.tflite.L2NormOptions.decodeText(t,e);case"LocalResponseNormalizationOptions":return $root.tflite.LocalResponseNormalizationOptions.decodeText(t,e);case"LSTMOptions":return $root.tflite.LSTMOptions.decodeText(t,e);case"ResizeBilinearOptions":return $root.tflite.ResizeBilinearOptions.decodeText(t,e);case"CallOptions":return $root.tflite.CallOptions.decodeText(t,e);case"ReshapeOptions":return $root.tflite.ReshapeOptions.decodeText(t,e);case"SkipGramOptions":return $root.tflite.SkipGramOptions.decodeText(t,e);case"SpaceToDepthOptions":return $root.tflite.SpaceToDepthOptions.decodeText(t,e);case"EmbeddingLookupSparseOptions":return $root.tflite.EmbeddingLookupSparseOptions.decodeText(t,e);case"MulOptions":return $root.tflite.MulOptions.decodeText(t,e);case"PadOptions":return $root.tflite.PadOptions.decodeText(t,e);case"GatherOptions":return $root.tflite.GatherOptions.decodeText(t,e);case"BatchToSpaceNDOptions":return $root.tflite.BatchToSpaceNDOptions.decodeText(t,e);case"SpaceToBatchNDOptions":return $root.tflite.SpaceToBatchNDOptions.decodeText(t,e);case"TransposeOptions":return $root.tflite.TransposeOptions.decodeText(t,e);case"ReducerOptions":return $root.tflite.ReducerOptions.decodeText(t,e);case"SubOptions":return $root.tflite.SubOptions.decodeText(t,e);case"DivOptions":return $root.tflite.DivOptions.decodeText(t,e);case"SqueezeOptions":return $root.tflite.SqueezeOptions.decodeText(t,e);case"SequenceRNNOptions":return $root.tflite.SequenceRNNOptions.decodeText(t,e);case"StridedSliceOptions":return $root.tflite.StridedSliceOptions.decodeText(t,e);case"ExpOptions":return $root.tflite.ExpOptions.decodeText(t,e);case"TopKV2Options":return $root.tflite.TopKV2Options.decodeText(t,e);case"SplitOptions":return $root.tflite.SplitOptions.decodeText(t,e);case"LogSoftmaxOptions":return $root.tflite.LogSoftmaxOptions.decodeText(t,e);case"CastOptions":return $root.tflite.CastOptions.decodeText(t,e);case"DequantizeOptions":return $root.tflite.DequantizeOptions.decodeText(t,e);case"MaximumMinimumOptions":return $root.tflite.MaximumMinimumOptions.decodeText(t,e);case"ArgMaxOptions":return $root.tflite.ArgMaxOptions.decodeText(t,e);case"LessOptions":return $root.tflite.LessOptions.decodeText(t,e);case"NegOptions":return $root.tflite.NegOptions.decodeText(t,e);case"PadV2Options":return $root.tflite.PadV2Options.decodeText(t,e);case"GreaterOptions":return $root.tflite.GreaterOptions.decodeText(t,e);case"GreaterEqualOptions":return $root.tflite.GreaterEqualOptions.decodeText(t,e);case"LessEqualOptions":return $root.tflite.LessEqualOptions.decodeText(t,e);case"SelectOptions":return $root.tflite.SelectOptions.decodeText(t,e);case"SliceOptions":return $root.tflite.SliceOptions.decodeText(t,e);case"TransposeConvOptions":return $root.tflite.TransposeConvOptions.decodeText(t,e);case"SparseToDenseOptions":return $root.tflite.SparseToDenseOptions.decodeText(t,e);case"TileOptions":return $root.tflite.TileOptions.decodeText(t,e);case"ExpandDimsOptions":return $root.tflite.ExpandDimsOptions.decodeText(t,e);case"EqualOptions":return $root.tflite.EqualOptions.decodeText(t,e);case"NotEqualOptions":return $root.tflite.NotEqualOptions.decodeText(t,e);case"ShapeOptions":return $root.tflite.ShapeOptions.decodeText(t,e);case"PowOptions":return $root.tflite.PowOptions.decodeText(t,e);case"ArgMinOptions":return $root.tflite.ArgMinOptions.decodeText(t,e);case"FakeQuantOptions":return $root.tflite.FakeQuantOptions.decodeText(t,e);case"PackOptions":return $root.tflite.PackOptions.decodeText(t,e);case"LogicalOrOptions":return $root.tflite.LogicalOrOptions.decodeText(t,e);case"OneHotOptions":return $root.tflite.OneHotOptions.decodeText(t,e);case"LogicalAndOptions":return $root.tflite.LogicalAndOptions.decodeText(t,e);case"LogicalNotOptions":return $root.tflite.LogicalNotOptions.decodeText(t,e);case"UnpackOptions":return $root.tflite.UnpackOptions.decodeText(t,e);case"FloorDivOptions":return $root.tflite.FloorDivOptions.decodeText(t,e);case"SquareOptions":return $root.tflite.SquareOptions.decodeText(t,e);case"ZerosLikeOptions":return $root.tflite.ZerosLikeOptions.decodeText(t,e);case"FillOptions":return $root.tflite.FillOptions.decodeText(t,e);case"BidirectionalSequenceLSTMOptions":return $root.tflite.BidirectionalSequenceLSTMOptions.decodeText(t,e);case"BidirectionalSequenceRNNOptions":return $root.tflite.BidirectionalSequenceRNNOptions.decodeText(t,e);case"UnidirectionalSequenceLSTMOptions":return $root.tflite.UnidirectionalSequenceLSTMOptions.decodeText(t,e);case"FloorModOptions":return $root.tflite.FloorModOptions.decodeText(t,e);case"RangeOptions":return $root.tflite.RangeOptions.decodeText(t,e);case"ResizeNearestNeighborOptions":return $root.tflite.ResizeNearestNeighborOptions.decodeText(t,e);case"LeakyReluOptions":return $root.tflite.LeakyReluOptions.decodeText(t,e);case"SquaredDifferenceOptions":return $root.tflite.SquaredDifferenceOptions.decodeText(t,e);case"MirrorPadOptions":return $root.tflite.MirrorPadOptions.decodeText(t,e);case"AbsOptions":return $root.tflite.AbsOptions.decodeText(t,e);case"SplitVOptions":return $root.tflite.SplitVOptions.decodeText(t,e);case"UniqueOptions":return $root.tflite.UniqueOptions.decodeText(t,e);case"ReverseV2Options":return $root.tflite.ReverseV2Options.decodeText(t,e);case"AddNOptions":return $root.tflite.AddNOptions.decodeText(t,e);case"GatherNdOptions":return $root.tflite.GatherNdOptions.decodeText(t,e);case"CosOptions":return $root.tflite.CosOptions.decodeText(t,e);case"WhereOptions":return $root.tflite.WhereOptions.decodeText(t,e);case"RankOptions":return $root.tflite.RankOptions.decodeText(t,e);case"ReverseSequenceOptions":return $root.tflite.ReverseSequenceOptions.decodeText(t,e);case"MatrixDiagOptions":return $root.tflite.MatrixDiagOptions.decodeText(t,e);case"QuantizeOptions":return $root.tflite.QuantizeOptions.decodeText(t,e);case"MatrixSetDiagOptions":return $root.tflite.MatrixSetDiagOptions.decodeText(t,e);case"HardSwishOptions":return $root.tflite.HardSwishOptions.decodeText(t,e);case"IfOptions":return $root.tflite.IfOptions.decodeText(t,e);case"WhileOptions":return $root.tflite.WhileOptions.decodeText(t,e);case"DepthToSpaceOptions":return $root.tflite.DepthToSpaceOptions.decodeText(t,e);case"NonMaxSuppressionV4Options":return $root.tflite.NonMaxSuppressionV4Options.decodeText(t,e);case"NonMaxSuppressionV5Options":return $root.tflite.NonMaxSuppressionV5Options.decodeText(t,e);case"ScatterNdOptions":return $root.tflite.ScatterNdOptions.decodeText(t,e);case"SelectV2Options":return $root.tflite.SelectV2Options.decodeText(t,e);case"DensifyOptions":return $root.tflite.DensifyOptions.decodeText(t,e);case"SegmentSumOptions":return $root.tflite.SegmentSumOptions.decodeText(t,e);case"BatchMatMulOptions":return $root.tflite.BatchMatMulOptions.decodeText(t,e)}}},$root.tflite.Padding={SAME:0,VALID:1},$root.tflite.ActivationFunctionType={NONE:0,RELU:1,RELU_N1_TO_1:2,RELU6:3,TANH:4,SIGN_BIT:5},$root.tflite.Conv2DOptions=class{static decode(t,e){const o=new $root.tflite.Conv2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.fused_activation_function=t.int8_(e,10,0),o.dilation_w_factor=t.int32_(e,12,1),o.dilation_h_factor=t.int32_(e,14,1),o}static decodeText(t,e){const o=new $root.tflite.Conv2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.dilation_w_factor=t.value(e.dilation_w_factor,1),o.dilation_h_factor=t.value(e.dilation_h_factor,1),o}},$root.tflite.Pool2DOptions=class{static decode(t,e){const o=new $root.tflite.Pool2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.filter_width=t.int32_(e,10,0),o.filter_height=t.int32_(e,12,0),o.fused_activation_function=t.int8_(e,14,0),o}static decodeText(t,e){const o=new $root.tflite.Pool2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.filter_width=t.value(e.filter_width,0),o.filter_height=t.value(e.filter_height,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.DepthwiseConv2DOptions=class{static decode(t,e){const o=new $root.tflite.DepthwiseConv2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.depth_multiplier=t.int32_(e,10,0),o.fused_activation_function=t.int8_(e,12,0),o.dilation_w_factor=t.int32_(e,14,1),o.dilation_h_factor=t.int32_(e,16,1),o}static decodeText(t,e){const o=new $root.tflite.DepthwiseConv2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.depth_multiplier=t.value(e.depth_multiplier,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.dilation_w_factor=t.value(e.dilation_w_factor,1),o.dilation_h_factor=t.value(e.dilation_h_factor,1),o}},$root.tflite.ConcatEmbeddingsOptions=class{static decode(t,e){const o=new $root.tflite.ConcatEmbeddingsOptions;return o.num_channels=t.int32_(e,4,0),o.num_columns_per_channel=t.typedArray(e,6,Int32Array),o.embedding_dim_per_channel=t.typedArray(e,8,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.ConcatEmbeddingsOptions;return o.num_channels=t.value(e.num_channels,0),o.num_columns_per_channel=t.typedArray(e.num_columns_per_channel,Int32Array),o.embedding_dim_per_channel=t.typedArray(e.embedding_dim_per_channel,Int32Array),o}},$root.tflite.LSHProjectionType={UNKNOWN:0,SPARSE:1,DENSE:2},$root.tflite.LSHProjectionOptions=class{static decode(t,e){const o=new $root.tflite.LSHProjectionOptions;return o.type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.LSHProjectionOptions;return o.type=$root.tflite.LSHProjectionType[e.type],o}},$root.tflite.SVDFOptions=class{static decode(t,e){const o=new $root.tflite.SVDFOptions;return o.rank=t.int32_(e,4,0),o.fused_activation_function=t.int8_(e,6,0),o.asymmetric_quantize_inputs=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SVDFOptions;return o.rank=t.value(e.rank,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.RNNOptions=class{static decode(t,e){const o=new $root.tflite.RNNOptions;return o.fused_activation_function=t.int8_(e,4,0),o.asymmetric_quantize_inputs=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.RNNOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.SequenceRNNOptions=class{static decode(t,e){const o=new $root.tflite.SequenceRNNOptions;return o.time_major=t.bool_(e,4,!1),o.fused_activation_function=t.int8_(e,6,0),o.asymmetric_quantize_inputs=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SequenceRNNOptions;return o.time_major=t.value(e.time_major,!1),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.BidirectionalSequenceRNNOptions=class{static decode(t,e){const o=new $root.tflite.BidirectionalSequenceRNNOptions;return o.time_major=t.bool_(e,4,!1),o.fused_activation_function=t.int8_(e,6,0),o.merge_outputs=t.bool_(e,8,!1),o.asymmetric_quantize_inputs=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.BidirectionalSequenceRNNOptions;return o.time_major=t.value(e.time_major,!1),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.merge_outputs=t.value(e.merge_outputs,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.FullyConnectedOptionsWeightsFormat={DEFAULT:0,SHUFFLED4x16INT8:1},$root.tflite.FullyConnectedOptions=class{static decode(t,e){const o=new $root.tflite.FullyConnectedOptions;return o.fused_activation_function=t.int8_(e,4,0),o.weights_format=t.int8_(e,6,0),o.keep_num_dims=t.bool_(e,8,!1),o.asymmetric_quantize_inputs=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.FullyConnectedOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.weights_format=$root.tflite.FullyConnectedOptionsWeightsFormat[e.weights_format],o.keep_num_dims=t.value(e.keep_num_dims,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.SoftmaxOptions=class{static decode(t,e){const o=new $root.tflite.SoftmaxOptions;return o.beta=t.float32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SoftmaxOptions;return o.beta=t.value(e.beta,0),o}},$root.tflite.ConcatenationOptions=class{static decode(t,e){const o=new $root.tflite.ConcatenationOptions;return o.axis=t.int32_(e,4,0),o.fused_activation_function=t.int8_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.ConcatenationOptions;return o.axis=t.value(e.axis,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.AddOptions=class{static decode(t,e){const o=new $root.tflite.AddOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.AddOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.MulOptions=class{static decode(t,e){const o=new $root.tflite.MulOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.MulOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.L2NormOptions=class{static decode(t,e){const o=new $root.tflite.L2NormOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.L2NormOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.LocalResponseNormalizationOptions=class{static decode(t,e){const o=new $root.tflite.LocalResponseNormalizationOptions;return o.radius=t.int32_(e,4,0),o.bias=t.float32_(e,6,0),o.alpha=t.float32_(e,8,0),o.beta=t.float32_(e,10,0),o}static decodeText(t,e){const o=new $root.tflite.LocalResponseNormalizationOptions;return o.radius=t.value(e.radius,0),o.bias=t.value(e.bias,0),o.alpha=t.value(e.alpha,0),o.beta=t.value(e.beta,0),o}},$root.tflite.LSTMKernelType={FULL:0,BASIC:1},$root.tflite.LSTMOptions=class{static decode(t,e){const o=new $root.tflite.LSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.kernel_type=t.int8_(e,10,0),o.asymmetric_quantize_inputs=t.bool_(e,12,!1),o}static decodeText(t,e){const o=new $root.tflite.LSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.kernel_type=$root.tflite.LSTMKernelType[e.kernel_type],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.UnidirectionalSequenceLSTMOptions=class{static decode(t,e){const o=new $root.tflite.UnidirectionalSequenceLSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.time_major=t.bool_(e,10,!1),o.asymmetric_quantize_inputs=t.bool_(e,12,!1),o}static decodeText(t,e){const o=new $root.tflite.UnidirectionalSequenceLSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.time_major=t.value(e.time_major,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.BidirectionalSequenceLSTMOptions=class{static decode(t,e){const o=new $root.tflite.BidirectionalSequenceLSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.merge_outputs=t.bool_(e,10,!1),o.time_major=t.bool_(e,12,!0),o.asymmetric_quantize_inputs=t.bool_(e,14,!1),o}static decodeText(t,e){const o=new $root.tflite.BidirectionalSequenceLSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.merge_outputs=t.value(e.merge_outputs,!1),o.time_major=t.value(e.time_major,!0),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.ResizeBilinearOptions=class{static decode(t,e){const o=new $root.tflite.ResizeBilinearOptions;return o.new_height=t.int32_(e,4,0),o.new_width=t.int32_(e,6,0),o.align_corners=t.bool_(e,8,!1),o.half_pixel_centers=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.ResizeBilinearOptions;return o.new_height=t.value(e.new_height,0),o.new_width=t.value(e.new_width,0),o.align_corners=t.value(e.align_corners,!1),o.half_pixel_centers=t.value(e.half_pixel_centers,!1),o}},$root.tflite.ResizeNearestNeighborOptions=class{static decode(t,e){const o=new $root.tflite.ResizeNearestNeighborOptions;return o.align_corners=t.bool_(e,4,!1),o.half_pixel_centers=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.ResizeNearestNeighborOptions;return o.align_corners=t.value(e.align_corners,!1),o.half_pixel_centers=t.value(e.half_pixel_centers,!1),o}},$root.tflite.CallOptions=class{static decode(t,e){const o=new $root.tflite.CallOptions;return o.subgraph=t.uint32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.CallOptions;return o.subgraph=t.value(e.subgraph,0),o}},$root.tflite.PadOptions=class{static decode(t,e){return new $root.tflite.PadOptions}static decodeText(t,e){return new $root.tflite.PadOptions}},$root.tflite.PadV2Options=class{static decode(t,e){return new $root.tflite.PadV2Options}static decodeText(t,e){return new $root.tflite.PadV2Options}},$root.tflite.ReshapeOptions=class{static decode(t,e){const o=new $root.tflite.ReshapeOptions;return o.new_shape=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.ReshapeOptions;return o.new_shape=t.typedArray(e.new_shape,Int32Array),o}},$root.tflite.SpaceToBatchNDOptions=class{static decode(t,e){return new $root.tflite.SpaceToBatchNDOptions}static decodeText(t,e){return new $root.tflite.SpaceToBatchNDOptions}},$root.tflite.BatchToSpaceNDOptions=class{static decode(t,e){return new $root.tflite.BatchToSpaceNDOptions}static decodeText(t,e){return new $root.tflite.BatchToSpaceNDOptions}},$root.tflite.SkipGramOptions=class{static decode(t,e){const o=new $root.tflite.SkipGramOptions;return o.ngram_size=t.int32_(e,4,0),o.max_skip_size=t.int32_(e,6,0),o.include_all_ngrams=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SkipGramOptions;return o.ngram_size=t.value(e.ngram_size,0),o.max_skip_size=t.value(e.max_skip_size,0),o.include_all_ngrams=t.value(e.include_all_ngrams,!1),o}},$root.tflite.SpaceToDepthOptions=class{static decode(t,e){const o=new $root.tflite.SpaceToDepthOptions;return o.block_size=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SpaceToDepthOptions;return o.block_size=t.value(e.block_size,0),o}},$root.tflite.DepthToSpaceOptions=class{static decode(t,e){const o=new $root.tflite.DepthToSpaceOptions;return o.block_size=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.DepthToSpaceOptions;return o.block_size=t.value(e.block_size,0),o}},$root.tflite.SubOptions=class{static decode(t,e){const o=new $root.tflite.SubOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SubOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.DivOptions=class{static decode(t,e){const o=new $root.tflite.DivOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.DivOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.TopKV2Options=class{static decode(t,e){return new $root.tflite.TopKV2Options}static decodeText(t,e){return new $root.tflite.TopKV2Options}},$root.tflite.CombinerType={SUM:0,MEAN:1,SQRTN:2},$root.tflite.EmbeddingLookupSparseOptions=class{static decode(t,e){const o=new $root.tflite.EmbeddingLookupSparseOptions;return o.combiner=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.EmbeddingLookupSparseOptions;return o.combiner=$root.tflite.CombinerType[e.combiner],o}},$root.tflite.GatherOptions=class{static decode(t,e){const o=new $root.tflite.GatherOptions;return o.axis=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.GatherOptions;return o.axis=t.value(e.axis,0),o}},$root.tflite.TransposeOptions=class{static decode(t,e){return new $root.tflite.TransposeOptions}static decodeText(t,e){return new $root.tflite.TransposeOptions}},$root.tflite.ExpOptions=class{static decode(t,e){return new $root.tflite.ExpOptions}static decodeText(t,e){return new $root.tflite.ExpOptions}},$root.tflite.CosOptions=class{static decode(t,e){return new $root.tflite.CosOptions}static decodeText(t,e){return new $root.tflite.CosOptions}},$root.tflite.ReducerOptions=class{static decode(t,e){const o=new $root.tflite.ReducerOptions;return o.keep_dims=t.bool_(e,4,!1),o}static decodeText(t,e){const o=new $root.tflite.ReducerOptions;return o.keep_dims=t.value(e.keep_dims,!1),o}},$root.tflite.SqueezeOptions=class{static decode(t,e){const o=new $root.tflite.SqueezeOptions;return o.squeeze_dims=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.SqueezeOptions;return o.squeeze_dims=t.typedArray(e.squeeze_dims,Int32Array),o}},$root.tflite.SplitOptions=class{static decode(t,e){const o=new $root.tflite.SplitOptions;return o.num_splits=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SplitOptions;return o.num_splits=t.value(e.num_splits,0),o}},$root.tflite.SplitVOptions=class{static decode(t,e){const o=new $root.tflite.SplitVOptions;return o.num_splits=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SplitVOptions;return o.num_splits=t.value(e.num_splits,0),o}},$root.tflite.StridedSliceOptions=class{static decode(t,e){const o=new $root.tflite.StridedSliceOptions;return o.begin_mask=t.int32_(e,4,0),o.end_mask=t.int32_(e,6,0),o.ellipsis_mask=t.int32_(e,8,0),o.new_axis_mask=t.int32_(e,10,0),o.shrink_axis_mask=t.int32_(e,12,0),o}static decodeText(t,e){const o=new $root.tflite.StridedSliceOptions;return o.begin_mask=t.value(e.begin_mask,0),o.end_mask=t.value(e.end_mask,0),o.ellipsis_mask=t.value(e.ellipsis_mask,0),o.new_axis_mask=t.value(e.new_axis_mask,0),o.shrink_axis_mask=t.value(e.shrink_axis_mask,0),o}},$root.tflite.LogSoftmaxOptions=class{static decode(t,e){return new $root.tflite.LogSoftmaxOptions}static decodeText(t,e){return new $root.tflite.LogSoftmaxOptions}},$root.tflite.CastOptions=class{static decode(t,e){const o=new $root.tflite.CastOptions;return o.in_data_type=t.int8_(e,4,0),o.out_data_type=t.int8_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.CastOptions;return o.in_data_type=$root.tflite.TensorType[e.in_data_type],o.out_data_type=$root.tflite.TensorType[e.out_data_type],o}},$root.tflite.DequantizeOptions=class{static decode(t,e){return new $root.tflite.DequantizeOptions}static decodeText(t,e){return new $root.tflite.DequantizeOptions}},$root.tflite.MaximumMinimumOptions=class{static decode(t,e){return new $root.tflite.MaximumMinimumOptions}static decodeText(t,e){return new $root.tflite.MaximumMinimumOptions}},$root.tflite.TileOptions=class{static decode(t,e){return new $root.tflite.TileOptions}static decodeText(t,e){return new $root.tflite.TileOptions}},$root.tflite.ArgMaxOptions=class{static decode(t,e){const o=new $root.tflite.ArgMaxOptions;return o.output_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ArgMaxOptions;return o.output_type=$root.tflite.TensorType[e.output_type],o}},$root.tflite.ArgMinOptions=class{static decode(t,e){const o=new $root.tflite.ArgMinOptions;return o.output_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ArgMinOptions;return o.output_type=$root.tflite.TensorType[e.output_type],o}},$root.tflite.GreaterOptions=class{static decode(t,e){return new $root.tflite.GreaterOptions}static decodeText(t,e){return new $root.tflite.GreaterOptions}},$root.tflite.GreaterEqualOptions=class{static decode(t,e){return new $root.tflite.GreaterEqualOptions}static decodeText(t,e){return new $root.tflite.GreaterEqualOptions}},$root.tflite.LessOptions=class{static decode(t,e){return new $root.tflite.LessOptions}static decodeText(t,e){return new $root.tflite.LessOptions}},$root.tflite.LessEqualOptions=class{static decode(t,e){return new $root.tflite.LessEqualOptions}static decodeText(t,e){return new $root.tflite.LessEqualOptions}},$root.tflite.NegOptions=class{static decode(t,e){return new $root.tflite.NegOptions}static decodeText(t,e){return new $root.tflite.NegOptions}},$root.tflite.SelectOptions=class{static decode(t,e){return new $root.tflite.SelectOptions}static decodeText(t,e){return new $root.tflite.SelectOptions}},$root.tflite.SliceOptions=class{static decode(t,e){return new $root.tflite.SliceOptions}static decodeText(t,e){return new $root.tflite.SliceOptions}},$root.tflite.TransposeConvOptions=class{static decode(t,e){const o=new $root.tflite.TransposeConvOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o}static decodeText(t,e){const o=new $root.tflite.TransposeConvOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o}},$root.tflite.ExpandDimsOptions=class{static decode(t,e){return new $root.tflite.ExpandDimsOptions}static decodeText(t,e){return new $root.tflite.ExpandDimsOptions}},$root.tflite.SparseToDenseOptions=class{static decode(t,e){const o=new $root.tflite.SparseToDenseOptions;return o.validate_indices=t.bool_(e,4,!1),o}static decodeText(t,e){const o=new $root.tflite.SparseToDenseOptions;return o.validate_indices=t.value(e.validate_indices,!1),o}},$root.tflite.EqualOptions=class{static decode(t,e){return new $root.tflite.EqualOptions}static decodeText(t,e){return new $root.tflite.EqualOptions}},$root.tflite.NotEqualOptions=class{static decode(t,e){return new $root.tflite.NotEqualOptions}static decodeText(t,e){return new $root.tflite.NotEqualOptions}},$root.tflite.ShapeOptions=class{static decode(t,e){const o=new $root.tflite.ShapeOptions;return o.out_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ShapeOptions;return o.out_type=$root.tflite.TensorType[e.out_type],o}},$root.tflite.RankOptions=class{static decode(t,e){return new $root.tflite.RankOptions}static decodeText(t,e){return new $root.tflite.RankOptions}},$root.tflite.PowOptions=class{static decode(t,e){return new $root.tflite.PowOptions}static decodeText(t,e){return new $root.tflite.PowOptions}},$root.tflite.FakeQuantOptions=class{static decode(t,e){const o=new $root.tflite.FakeQuantOptions;return o.min=t.float32_(e,4,0),o.max=t.float32_(e,6,0),o.num_bits=t.int32_(e,8,0),o.narrow_range=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.FakeQuantOptions;return o.min=t.value(e.min,0),o.max=t.value(e.max,0),o.num_bits=t.value(e.num_bits,0),o.narrow_range=t.value(e.narrow_range,!1),o}},$root.tflite.PackOptions=class{static decode(t,e){const o=new $root.tflite.PackOptions;return o.values_count=t.int32_(e,4,0),o.axis=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.PackOptions;return o.values_count=t.value(e.values_count,0),o.axis=t.value(e.axis,0),o}},$root.tflite.LogicalOrOptions=class{static decode(t,e){return new $root.tflite.LogicalOrOptions}static decodeText(t,e){return new $root.tflite.LogicalOrOptions}},$root.tflite.OneHotOptions=class{static decode(t,e){const o=new $root.tflite.OneHotOptions;return o.axis=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.OneHotOptions;return o.axis=t.value(e.axis,0),o}},$root.tflite.AbsOptions=class{static decode(t,e){return new $root.tflite.AbsOptions}static decodeText(t,e){return new $root.tflite.AbsOptions}},$root.tflite.HardSwishOptions=class{static decode(t,e){return new $root.tflite.HardSwishOptions}static decodeText(t,e){return new $root.tflite.HardSwishOptions}},$root.tflite.LogicalAndOptions=class{static decode(t,e){return new $root.tflite.LogicalAndOptions}static decodeText(t,e){return new $root.tflite.LogicalAndOptions}},$root.tflite.LogicalNotOptions=class{static decode(t,e){return new $root.tflite.LogicalNotOptions}static decodeText(t,e){return new $root.tflite.LogicalNotOptions}},$root.tflite.UnpackOptions=class{static decode(t,e){const o=new $root.tflite.UnpackOptions;return o.num=t.int32_(e,4,0),o.axis=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.UnpackOptions;return o.num=t.value(e.num,0),o.axis=t.value(e.axis,0),o}},$root.tflite.FloorDivOptions=class{static decode(t,e){return new $root.tflite.FloorDivOptions}static decodeText(t,e){return new $root.tflite.FloorDivOptions}},$root.tflite.SquareOptions=class{static decode(t,e){return new $root.tflite.SquareOptions}static decodeText(t,e){return new $root.tflite.SquareOptions}},$root.tflite.ZerosLikeOptions=class{static decode(t,e){return new $root.tflite.ZerosLikeOptions}static decodeText(t,e){return new $root.tflite.ZerosLikeOptions}},$root.tflite.FillOptions=class{static decode(t,e){return new $root.tflite.FillOptions}static decodeText(t,e){return new $root.tflite.FillOptions}},$root.tflite.FloorModOptions=class{static decode(t,e){return new $root.tflite.FloorModOptions}static decodeText(t,e){return new $root.tflite.FloorModOptions}},$root.tflite.RangeOptions=class{static decode(t,e){return new $root.tflite.RangeOptions}static decodeText(t,e){return new $root.tflite.RangeOptions}},$root.tflite.LeakyReluOptions=class{static decode(t,e){const o=new $root.tflite.LeakyReluOptions;return o.alpha=t.float32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.LeakyReluOptions;return o.alpha=t.value(e.alpha,0),o}},$root.tflite.SquaredDifferenceOptions=class{static decode(t,e){return new $root.tflite.SquaredDifferenceOptions}static decodeText(t,e){return new $root.tflite.SquaredDifferenceOptions}},$root.tflite.MirrorPadMode={REFLECT:0,SYMMETRIC:1},$root.tflite.MirrorPadOptions=class{static decode(t,e){const o=new $root.tflite.MirrorPadOptions;return o.mode=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.MirrorPadOptions;return o.mode=$root.tflite.MirrorPadMode[e.mode],o}},$root.tflite.UniqueOptions=class{static decode(t,e){const o=new $root.tflite.UniqueOptions;return o.idx_out_type=t.int8_(e,4,2),o}static decodeText(t,e){const o=new $root.tflite.UniqueOptions;return o.idx_out_type=$root.tflite.TensorType[e.idx_out_type],o}},$root.tflite.ReverseV2Options=class{static decode(t,e){return new $root.tflite.ReverseV2Options}static decodeText(t,e){return new $root.tflite.ReverseV2Options}},$root.tflite.AddNOptions=class{static decode(t,e){return new $root.tflite.AddNOptions}static decodeText(t,e){return new $root.tflite.AddNOptions}},$root.tflite.GatherNdOptions=class{static decode(t,e){return new $root.tflite.GatherNdOptions}static decodeText(t,e){return new $root.tflite.GatherNdOptions}},$root.tflite.WhereOptions=class{static decode(t,e){return new $root.tflite.WhereOptions}static decodeText(t,e){return new $root.tflite.WhereOptions}},$root.tflite.ReverseSequenceOptions=class{static decode(t,e){const o=new $root.tflite.ReverseSequenceOptions;return o.seq_dim=t.int32_(e,4,0),o.batch_dim=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.ReverseSequenceOptions;return o.seq_dim=t.value(e.seq_dim,0),o.batch_dim=t.value(e.batch_dim,0),o}},$root.tflite.MatrixDiagOptions=class{static decode(t,e){return new $root.tflite.MatrixDiagOptions}static decodeText(t,e){return new $root.tflite.MatrixDiagOptions}},$root.tflite.QuantizeOptions=class{static decode(t,e){return new $root.tflite.QuantizeOptions}static decodeText(t,e){return new $root.tflite.QuantizeOptions}},$root.tflite.MatrixSetDiagOptions=class{static decode(t,e){return new $root.tflite.MatrixSetDiagOptions}static decodeText(t,e){return new $root.tflite.MatrixSetDiagOptions}},$root.tflite.IfOptions=class{static decode(t,e){const o=new $root.tflite.IfOptions;return o.then_subgraph_index=t.int32_(e,4,0),o.else_subgraph_index=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.IfOptions;return o.then_subgraph_index=t.value(e.then_subgraph_index,0),o.else_subgraph_index=t.value(e.else_subgraph_index,0),o}},$root.tflite.WhileOptions=class{static decode(t,e){const o=new $root.tflite.WhileOptions;return o.cond_subgraph_index=t.int32_(e,4,0),o.body_subgraph_index=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.WhileOptions;return o.cond_subgraph_index=t.value(e.cond_subgraph_index,0),o.body_subgraph_index=t.value(e.body_subgraph_index,0),o}},$root.tflite.NonMaxSuppressionV4Options=class{static decode(t,e){return new $root.tflite.NonMaxSuppressionV4Options}static decodeText(t,e){return new $root.tflite.NonMaxSuppressionV4Options}},$root.tflite.NonMaxSuppressionV5Options=class{static decode(t,e){return new $root.tflite.NonMaxSuppressionV5Options}static decodeText(t,e){return new $root.tflite.NonMaxSuppressionV5Options}},$root.tflite.ScatterNdOptions=class{static decode(t,e){return new $root.tflite.ScatterNdOptions}static decodeText(t,e){return new $root.tflite.ScatterNdOptions}},$root.tflite.SelectV2Options=class{static decode(t,e){return new $root.tflite.SelectV2Options}static decodeText(t,e){return new $root.tflite.SelectV2Options}},$root.tflite.DensifyOptions=class{static decode(t,e){return new $root.tflite.DensifyOptions}static decodeText(t,e){return new $root.tflite.DensifyOptions}},$root.tflite.SegmentSumOptions=class{static decode(t,e){return new $root.tflite.SegmentSumOptions}static decodeText(t,e){return new $root.tflite.SegmentSumOptions}},$root.tflite.BatchMatMulOptions=class{static decode(t,e){const o=new $root.tflite.BatchMatMulOptions;return o.adj_x=t.bool_(e,4,!1),o.adj_y=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.BatchMatMulOptions;return o.adj_x=t.value(e.adj_x,!1),o.adj_y=t.value(e.adj_y,!1),o}},$root.tflite.OperatorCode=class{static decode(t,e){const o=new $root.tflite.OperatorCode;return o.builtin_code=t.int8_(e,4,0),o.custom_code=t.string_(e,6,null),o.version=t.int32_(e,8,1),o}static decodeText(t,e){const o=new $root.tflite.OperatorCode;return o.builtin_code=$root.tflite.BuiltinOperator[e.builtin_code],o.custom_code=t.value(e.custom_code,null),o.version=t.value(e.version,1),o}},$root.tflite.CustomOptionsFormat={FLEXBUFFERS:0},$root.tflite.Operator=class{static decode(t,e){const o=new $root.tflite.Operator;return o.opcode_index=t.uint32_(e,4,0),o.inputs=t.typedArray(e,6,Int32Array),o.outputs=t.typedArray(e,8,Int32Array),o.builtin_options=t.union(e,10,$root.tflite.BuiltinOptions.decode),o.custom_options=t.typedArray(e,14,Uint8Array),o.custom_options_format=t.int8_(e,16,0),o.mutating_variable_inputs=t.bools_(e,18),o.intermediates=t.typedArray(e,20,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Operator;return o.opcode_index=t.value(e.opcode_index,0),o.inputs=t.typedArray(e.inputs,Int32Array),o.outputs=t.typedArray(e.outputs,Int32Array),o.builtin_options=$root.tflite.BuiltinOptions.decodeText(t,e.builtin_options,e.builtin_options_type),o.custom_options=t.typedArray(e.custom_options,Uint8Array),o.custom_options_format=$root.tflite.CustomOptionsFormat[e.custom_options_format],o.mutating_variable_inputs=t.array(e.mutating_variable_inputs),o.intermediates=t.typedArray(e.intermediates,Int32Array),o}},$root.tflite.SubGraph=class{static decode(t,e){const o=new $root.tflite.SubGraph;return o.tensors=t.tableArray(e,4,$root.tflite.Tensor.decode),o.inputs=t.typedArray(e,6,Int32Array),o.outputs=t.typedArray(e,8,Int32Array),o.operators=t.tableArray(e,10,$root.tflite.Operator.decode),o.name=t.string_(e,12,null),o}static decodeText(t,e){const o=new $root.tflite.SubGraph;return o.tensors=t.objectArray(e.tensors,$root.tflite.Tensor.decodeText),o.inputs=t.typedArray(e.inputs,Int32Array),o.outputs=t.typedArray(e.outputs,Int32Array),o.operators=t.objectArray(e.operators,$root.tflite.Operator.decodeText),o.name=t.value(e.name,null),o}},$root.tflite.Buffer=class{static decode(t,e){const o=new $root.tflite.Buffer;return o.data=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.Buffer;return o.data=t.typedArray(e.data,Uint8Array),o}},$root.tflite.Metadata=class{static decode(t,e){const o=new $root.tflite.Metadata;return o.name=t.string_(e,4,null),o.buffer=t.uint32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.Metadata;return o.name=t.value(e.name,null),o.buffer=t.value(e.buffer,0),o}},$root.tflite.Model=class{static identifier(t){return t.identifier("TFL3")}static create(t){return $root.tflite.Model.decode(t,t.root)}static createText(t){return $root.tflite.Model.decodeText(t,t.root)}static decode(t,e){const o=new $root.tflite.Model;return o.version=t.uint32_(e,4,0),o.operator_codes=t.tableArray(e,6,$root.tflite.OperatorCode.decode),o.subgraphs=t.tableArray(e,8,$root.tflite.SubGraph.decode),o.description=t.string_(e,10,null),o.buffers=t.tableArray(e,12,$root.tflite.Buffer.decode),o.metadata_buffer=t.typedArray(e,14,Int32Array),o.metadata=t.tableArray(e,16,$root.tflite.Metadata.decode),o}static decodeText(t,e){const o=new $root.tflite.Model;return o.version=t.value(e.version,0),o.operator_codes=t.objectArray(e.operator_codes,$root.tflite.OperatorCode.decodeText),o.subgraphs=t.objectArray(e.subgraphs,$root.tflite.SubGraph.decodeText),o.description=t.value(e.description,null),o.buffers=t.objectArray(e.buffers,$root.tflite.Buffer.decodeText),o.metadata_buffer=t.typedArray(e.metadata_buffer,Int32Array),o.metadata=t.objectArray(e.metadata,$root.tflite.Metadata.decodeText),o}},$root.tflite=$root.tflite||{},$root.tflite.AssociatedFileType={UNKNOWN:0,DESCRIPTIONS:1,TENSOR_AXIS_LABELS:2,TENSOR_VALUE_LABELS:3,TENSOR_AXIS_SCORE_CALIBRATION:4,VOCABULARY:5},$root.tflite.AssociatedFile=class{static decode(t,e){const o=new $root.tflite.AssociatedFile;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.type=t.int8_(e,8,0),o.locale=t.string_(e,10,null),o}},$root.tflite.FeatureProperties=class{static decode(t,e){return new $root.tflite.FeatureProperties}},$root.tflite.ColorSpaceType={UNKNOWN:0,RGB:1,GRAYSCALE:2},$root.tflite.ImageSize=class{static decode(t,e){const o=new $root.tflite.ImageSize;return o.width=t.uint32_(e,4,0),o.height=t.uint32_(e,6,0),o}},$root.tflite.ImageProperties=class{static decode(t,e){const o=new $root.tflite.ImageProperties;return o.color_space=t.int8_(e,4,0),o.default_size=t.table(e,6,$root.tflite.ImageSize.decode),o}},$root.tflite.BoundingBoxType={UNKNOWN:0,BOUNDARIES:1,UPPER_LEFT:2,CENTER:3},$root.tflite.CoordinateType={RATIO:0,PIXEL:1},$root.tflite.BoundingBoxProperties=class{static decode(t,e){const o=new $root.tflite.BoundingBoxProperties;return o.index=t.typedArray(e,4,Uint32Array),o.type=t.int8_(e,6,0),o.coordinate_type=t.int8_(e,8,0),o}},$root.tflite.ContentProperties=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.FeatureProperties.decode(t,e);case 2:return $root.tflite.ImageProperties.decode(t,e);case 3:return $root.tflite.BoundingBoxProperties.decode(t,e)}}static decodeText(t,e,o){switch(o){case"FeatureProperties":return $root.tflite.FeatureProperties.decodeText(t,e);case"ImageProperties":return $root.tflite.ImageProperties.decodeText(t,e);case"BoundingBoxProperties":return $root.tflite.BoundingBoxProperties.decodeText(t,e)}}},$root.tflite.ValueRange=class{static decode(t,e){const o=new $root.tflite.ValueRange;return o.min=t.int32_(e,4,0),o.max=t.int32_(e,6,0),o}},$root.tflite.Content=class{static decode(t,e){const o=new $root.tflite.Content;return o.content_properties=t.union(e,4,$root.tflite.ContentProperties.decode),o.range=t.table(e,8,$root.tflite.ValueRange.decode),o}},$root.tflite.NormalizationOptions=class{static decode(t,e){const o=new $root.tflite.NormalizationOptions;return o.mean=t.typedArray(e,4,Float32Array),o.std=t.typedArray(e,6,Float32Array),o}},$root.tflite.ScoreTransformationType={IDENTITY:0,LOG:1,INVERSE_LOGISTIC:2},$root.tflite.ScoreCalibrationOptions=class{static decode(t,e){const o=new $root.tflite.ScoreCalibrationOptions;return o.score_transformation=t.int8_(e,4,0),o.default_score=t.float32_(e,6,0),o}},$root.tflite.ScoreThresholdingOptions=class{static decode(t,e){const o=new $root.tflite.ScoreThresholdingOptions;return o.global_score_threshold=t.float32_(e,4,0),o}},$root.tflite.BertTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.BertTokenizerOptions;return o.vocab_file=t.tableArray(e,4,$root.tflite.AssociatedFile.decode),o}},$root.tflite.SentencePieceTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.SentencePieceTokenizerOptions;return o.sentencePiece_model=t.tableArray(e,4,$root.tflite.AssociatedFile.decode),o.vocab_file=t.tableArray(e,6,$root.tflite.AssociatedFile.decode),o}},$root.tflite.RegexTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.RegexTokenizerOptions;return o.delim_regex_pattern=t.string_(e,4,null),o.vocab_file=t.tableArray(e,6,$root.tflite.AssociatedFile.decode),o}},$root.tflite.ProcessUnitOptions=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.NormalizationOptions.decode(t,e);case 2:return $root.tflite.ScoreCalibrationOptions.decode(t,e);case 3:return $root.tflite.ScoreThresholdingOptions.decode(t,e);case 4:return $root.tflite.BertTokenizerOptions.decode(t,e);case 5:return $root.tflite.SentencePieceTokenizerOptions.decode(t,e);case 6:return $root.tflite.RegexTokenizerOptions.decode(t,e)}}static decodeText(t,e,o){switch(o){case"NormalizationOptions":return $root.tflite.NormalizationOptions.decodeText(t,e);case"ScoreCalibrationOptions":return $root.tflite.ScoreCalibrationOptions.decodeText(t,e);case"ScoreThresholdingOptions":return $root.tflite.ScoreThresholdingOptions.decodeText(t,e);case"BertTokenizerOptions":return $root.tflite.BertTokenizerOptions.decodeText(t,e);case"SentencePieceTokenizerOptions":return $root.tflite.SentencePieceTokenizerOptions.decodeText(t,e);case"RegexTokenizerOptions":return $root.tflite.RegexTokenizerOptions.decodeText(t,e)}}},$root.tflite.ProcessUnit=class{static decode(t,e){const o=new $root.tflite.ProcessUnit;return o.options=t.union(e,4,$root.tflite.ProcessUnitOptions.decode),o}},$root.tflite.Stats=class{static decode(t,e){const o=new $root.tflite.Stats;return o.max=t.typedArray(e,4,Float32Array),o.min=t.typedArray(e,6,Float32Array),o}},$root.tflite.TensorGroup=class{static decode(t,e){const o=new $root.tflite.TensorGroup;return o.name=t.string_(e,4,null),o.tensor_names=t.strings_(e,6),o}},$root.tflite.TensorMetadata=class{static decode(t,e){const o=new $root.tflite.TensorMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.dimension_names=t.strings_(e,8),o.content=t.table(e,10,$root.tflite.Content.decode),o.process_units=t.tableArray(e,12,$root.tflite.ProcessUnit.decode),o.stats=t.table(e,14,$root.tflite.Stats.decode),o.associated_files=t.tableArray(e,16,$root.tflite.AssociatedFile.decode),o}},$root.tflite.SubGraphMetadata=class{static decode(t,e){const o=new $root.tflite.SubGraphMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.input_tensor_metadata=t.tableArray(e,8,$root.tflite.TensorMetadata.decode),o.output_tensor_metadata=t.tableArray(e,10,$root.tflite.TensorMetadata.decode),o.associated_files=t.tableArray(e,12,$root.tflite.AssociatedFile.decode),o.input_process_units=t.tableArray(e,14,$root.tflite.ProcessUnit.decode),o.output_process_units=t.tableArray(e,16,$root.tflite.ProcessUnit.decode),o.input_tensor_groups=t.tableArray(e,18,$root.tflite.TensorGroup.decode),o.output_tensor_groups=t.tableArray(e,20,$root.tflite.TensorGroup.decode),o}},$root.tflite.ModelMetadata=class{static identifier(t){return t.identifier("M001")}static create(t){return $root.tflite.ModelMetadata.decode(t,t.root)}static decode(t,e){const o=new $root.tflite.ModelMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.version=t.string_(e,8,null),o.subgraph_metadata=t.tableArray(e,10,$root.tflite.SubGraphMetadata.decode),o.author=t.string_(e,12,null),o.license=t.string_(e,14,null),o.associated_files=t.tableArray(e,16,$root.tflite.AssociatedFile.decode),o.min_parser_version=t.string_(e,18,null),o}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite.js new file mode 100644 index 0000000000000000000000000000000000000000..fcf752f84c7708fed770a3b78a553d4008c1df06 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tflite.js @@ -0,0 +1 @@ +var tflite=tflite||{},base=base||require("./base"),flatbuffers=flatbuffers||require("./flatbuffers"),long=long||{Long:require("long")};tflite.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if(-1!==["tflite","lite","tfl","bin","pb","model","tmfile","h5"].indexOf(e)){const e=t.buffer,i="TFL3";if(e&&e.length>8&&e.subarray(4,8).every(((t,e)=>t===i.charCodeAt(e))))return!0}if("json"===e){const e=t.text;if(-1!==e.indexOf('"subgraphs"',0)&&-1!==e.indexOf('"operator_codes"',0))return!0}return!1}open(t,e){return e.require("./tflite-schema").then((()=>(tflite.schema=flatbuffers.get("tflite").tflite,tflite.Metadata.open(e).then((e=>{const i=t.identifier;try{switch(i.split(".").pop().toLowerCase()){default:{const i=new flatbuffers.Reader(t.buffer);if(!tflite.schema.Model.identifier(i))throw new tflite.Error("File format is not tflite.Model.");const n=tflite.schema.Model.create(i);return new tflite.Model(e,n)}case"json":{const i=new flatbuffers.TextReader(t.text),n=tflite.schema.Model.createText(i);return new tflite.Model(e,n)}}}catch(t){const e=t&&t.message?t.message:t.toString();throw new tflite.Error(e.replace(/\.$/,"")+" in '"+i+"'.")}})))))}},tflite.Model=class{constructor(t,e){this._graphs=[],this._format="TensorFlow Lite",this._format=this._format+" v"+e.version.toString(),this._description=e.description||"";const i=[],n={};for(const t of Object.keys(tflite.schema.BuiltinOperator))n[tflite.schema.BuiltinOperator[t]]=tflite.Utility.type(t);for(let t=0;t1?n.toString():"",l=r&&n0||s?new tflite.Tensor(t,i,n,s):null;r.push(new tflite.Argument(t,i,u)),o.push(i.name)}const l=e.operators;for(let i=0;i{if(e){const i=e.description;i&&(t.description=i);const n=e.content;if(t.type&&n){let e=null;const i=n.content_properties;if(i instanceof tflite.schema.FeatureProperties)e="Feature";else if(i instanceof tflite.schema.ImageProperties)switch(e="Image",i.color_space){case 1:e+="(RGB)";break;case 2:e+="(Grayscale)"}else i instanceof tflite.schema.BoundingBoxProperties&&(e="BoundingBox");e&&(t.type.denotation=e)}}},h=e.inputs;for(let t=0;t0){const i=t.attribute(this.type,"custom");this._attributes.push(new tflite.Attribute(i,"custom",Array.from(e.custom_options)))}const l=e.builtin_options;if(l)for(const e of Object.keys(l)){const i=l[e];if("fused_activation_function"===e&&0!==i){const e={1:"Relu",2:"ReluN1To1",3:"Relu6",4:"Tanh",5:"SignBit"};if(!e[i])throw new tflite.Error("Unknown activation funtion index '"+JSON.stringify(i)+"'.");const n=e[i];this._chain=[new tflite.Node(t,null,{name:n},null,[])]}const n=t.attribute(this.type,e);this._attributes.push(new tflite.Attribute(n,e,i))}}}get type(){return this._type.name}get name(){return""}get location(){return this._location}get domain(){return null}get metadata(){return this._type.custom?{name:this.type,category:"custom"}:this._metadata.type(this.type)}get group(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}get attributes(){return this._attributes}},tflite.Attribute=class{constructor(t,e,i){if(this._type=null,this._name=e,this._value=i,"fused_activation_function"==this._name&&(this._visible=!1),t){if(t.type&&(this._type=t.type),this._type)switch(this._type){case"shape":this._value=new tflite.TensorShape(i);break;case"TensorType":this._value=tflite.Utility.dataType(this._value);break;default:this._value=tflite.Utility.enum(this._type,this._value)}Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible?this._visible=!1:Object.prototype.hasOwnProperty.call(t,"default")&&("function"==typeof(i=this._value)&&(i=i()),i==t.default&&(this._visible=!1))}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},tflite.Parameter=class{constructor(t,e,i){this._name=t,this._visible=e,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},tflite.Argument=class{constructor(t,e,i){this._location=t.toString(),this._type=new tflite.TensorType(e),this._initializer=i,this._name=e.name;const n=e.quantization;if(n){let t="q";const e=1==n.scale.length?n.scale[0]:0,i=1==n.zero_point.length?n.zero_point[0]:0;0==e&&0==i||(t=e.toString()+" * "+(0==i?"q":"(q - "+i.toString()+")")),1==n.min.length&&(t=n.min[0].toString()+" ≤ "+t),1==n.max.length&&(t=t+" ≤ "+n.max[0].toString()),"q"!=t&&(this._quantization=t)}}get name(){return this._name}get location(){return this._location}get type(){return this._type}get quantization(){return this._quantization}set description(t){this._description=t}get description(){return this._description}get initializer(){return this._initializer}},tflite.Tensor=class{constructor(t,e,i,n){this._location=t.toString(),this._type=new tflite.TensorType(e),this._is_variable=n,this._name=e.name,this._data=i.data.slice(0)}get kind(){return this._is_variable?"Variable":""}get name(){return this._name}get location(){return this._location}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};if(null==this._data||0===this._data.length)return t.state="Tensor data is empty.",t;if(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),"string"==this._type.dataType){let e=0;const i=t.data.getInt32(0,!0);e+=4;const n=[];for(let s=0;st.limit)return s.push("..."),s;switch(t.dataType){case"uint8":s.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"int8":s.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":s.push(t.data.getInt16(t.index)),t.index+=2,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float64":s.push(t.data.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case"string":s.push(t.data[t.index++]),t.count++}}else for(let i=0;it.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},tflite.TensorType=class{constructor(t){this._dataType=tflite.Utility.dataType(t.type),this._shape=new tflite.TensorShape(Array.from(t.shape||[]))}get dataType(){return this._dataType}get shape(){return this._shape}set denotation(t){this._denotation=t}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},tflite.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},tflite.Metadata=class{static open(t){return tflite.Metadata._metadata?Promise.resolve(tflite.Metadata._metadata):t.request(null,"tflite-metadata.json","utf-8").then((t=>(tflite.Metadata._metadata=new tflite.Metadata(t),tflite.Metadata._metadata))).catch((()=>(tflite.Metadata._metadata=new tflite.Metadata(null),tflite.Metadata._metadata)))}constructor(t){if(this._map=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map.set(t.name,t.schema)}}type(t){return this._map.has(t)?this._map.get(t):null}attribute(t,e){const i=this.type(t);if(i){let t=i.attributeMap;if(!t){if(t={},i.attributes)for(const e of i.attributes)t[e.name]=e;i.attributeMap=t}const n=t[e];if(n)return n}return null}},tflite.Utility=class{static dataType(t){if(!tflite.Utility._tensorTypeMap){tflite.Utility._tensorTypeMap=new Map;for(const t of Object.keys(tflite.schema.TensorType))tflite.Utility._tensorTypeMap.set(tflite.schema.TensorType[t],t.toLowerCase());tflite.Utility._tensorTypeMap.set(6,"boolean")}return tflite.Utility._tensorTypeMap.has(t)?tflite.Utility._tensorTypeMap.get(t):"?"}static enum(t,e){const i=t&&tflite.schema?tflite.schema[t]:void 0;if(i){if(tflite.Utility._enumKeyMap=tflite.Utility._enumKeyMap||new Map,!tflite.Utility._enumKeyMap.has(t)){const e=new Map;for(const t of Object.keys(i))e.set(i[t],t);tflite.Utility._enumKeyMap.set(t,e)}const n=tflite.Utility._enumKeyMap.get(t);if(n.has(e))return n.get(e)}return e}static type(t){const e=new Set(["2D","LSH","SVDF","RNN","L2","LSTM"]);return t.split("_").map((t=>t.length<1||e.has(t)?t:t[0]+t.substring(1).toLowerCase())).join("")}},tflite.Error=class extends Error{constructor(t){super(t),this.name="Error loading TensorFlow Lite model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tflite.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..27da838d8bd0ff2d958484f8e917812cb0cc948f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn-metadata.json @@ -0,0 +1 @@ +[{"name":"AbsVal","schema":{"operator":0}},{"name":"ArgMax","schema":{"operator":1}},{"name":"BatchNormCxx","schema":{"operator":2,"category":"Normalization"}},{"name":"Bias","schema":{"operator":3,"category":"Layer","attributes":[{"name":"bias_data_size","default":0,"visible":false}]}},{"name":"BNLL","schema":{"operator":4}},{"name":"Concat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"QuantizedConcat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Convolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"QuantizedConvolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"Crop","schema":{"operator":7,"category":"Data"}},{"name":"Deconvolution","schema":{"operator":8,"category":"Layer"}},{"name":"Dropout","schema":{"operator":9,"category":"Dropout","attributes":[{"name":"scale","type":"float32","default":1}]}},{"name":"Eltwise","schema":{"operator":10}},{"name":"ELU","schema":{"operator":11}},{"name":"Embed","schema":{"operator":12,"category":"Transform","attributes":[{"name":"num_output","default":0},{"name":"input_dim","default":0},{"name":"bias_term","default":0},{"name":"weight_data_size","default":0}]}},{"name":"Exp","schema":{"operator":13}},{"name":"Flatten","schema":{"operator":14,"category":"Shape","attributes":[{"name":"axis","default":1},{"name":"num_axis","default":4}]}},{"name":"InnerProduct","schema":{"operator":15,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"has_bias ","default":0,"visible":false},{"name":"transpose","default":0,"visible":false},{"name":"axis ","default":0}]}},{"name":"Input","schema":{"operator":16}},{"name":"Exp","schema":{"operator":17}},{"name":"LRN","schema":{"operator":18,"category":"Normalization","attributes":[{"name":"alpha","default":0},{"name":"beta","default":0.75},{"name":"bias","default":1},{"name":"size","default":1}]}},{"name":"Exp","schema":{"operator":19}},{"name":"MVN","schema":{"operator":20}},{"name":"Pooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"QuantizedPooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"Power","schema":{"operator":22}},{"name":"PReLU","schema":{"operator":23,"category":"Activation","attributes":[{"name":"channel_shared","default":0},{"name":"has_filler","default":0}]}},{"name":"Proposal","schema":{"operator":24}},{"name":"Reduce","schema":{"operator":25,"attributes":[{"name":"keep_dims","default":0},{"name":"axis","default":0}]}},{"name":"ReLU","schema":{"operator":26,"category":"Activation"}},{"name":"ROIPooling","schema":{"operator":27,"attributes":[{"name":"pool_type","default":0},{"name":"spatial_scale","default":0},{"name":"pooled_w ","default":0},{"name":"pooled_h","default":0},{"name":"pooled_d","default":0}]}},{"name":"Reshape","schema":{"operator":28,"category":"Shape","attributes":[{"name":"axis","default":0},{"name":"num_axes","default":4},{"name":"top_blob_dim_size","default":-233},{"name":"shape","type":"int32[]","size":2,"default":233},{"name":"reshape_type","default":0}]}},{"name":"Scale","schema":{"operator":29,"category":"Layer","attributes":[{"name":"axis","default":0,"visible":false},{"name":"num_axes","default":0,"visible":false},{"name":"bias_term","default":0,"visible":false}]}},{"name":"Sigmoid","schema":{"operator":30,"category":"Activation"}},{"name":"Slice","schema":{"operator":31,"category":"Tensor","attributes":[{"name":"slices","default":[]},{"name":"axis","default":1}]}},{"name":"Softmax","schema":{"operator":32,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0}]}},{"name":"Splitv","schema":{"operator":33,"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output","option":"variadic"}]}},{"name":"SPP","schema":{"operator":34,"category":"Activation"}},{"name":"Tanh","schema":{"operator":35,"category":"Activation"}},{"name":"Threshold","schema":{"operator":36}},{"name":"Tile","schema":{"operator":37}},{"name":"RNN","schema":{"operator":38,"category":"Layer"}},{"name":"LSTM","schema":{"operator":39,"category":"Layer"}},{"name":"BinaryOp","schema":{"operator":40,"attributes":[{"name":"op_type","type":"int32","default":0},{"name":"b","type":"float32","default":0}]}},{"name":"UnaryOp","schema":{"operator":41}},{"name":"ConvolutionDepthWise","schema":{"operator":42,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"Pad","schema":{"operator":43,"attributes":[{"name":" n1","default":0},{"name":" n2","default":0},{"name":" pad_h","default":0},{"name":" pad_b","default":0},{"name":" pad_w","default":0},{"name":" pad_r","default":0},{"name":" c1","default":0},{"name":" c2","default":0},{"name":" type","default":0}]}},{"name":"Squeeze","schema":{"operator":44}},{"name":"ExpandDims","schema":{"operator":45}},{"name":"Normalize","schema":{"operator":46,"arributes":[{"name":"across_spatial","default":0},{"name":"epsilon","type":"float32","default":0},{"name":"channel_shared","default":0},{"name":"axis","default":0},{"name":"p","default":0}]}},{"name":"Permute","schema":{"operator":47,"category":"Shape","attributes":[{"name":"order_size","default":0},{"name":"orders","type":"int32[]","size":"0"}]}},{"name":"PriorBox","schema":{"operator":48,"attributes":[{"name":"min_size","default":[]},{"name":"max_size","default":[]},{"name":"clip","default":1},{"name":"flip","default":1},{"name":"varainces0","type":"float32","default":0},{"name":"varainces1","type":"float32","default":0},{"name":"varainces2","type":"float32","default":0},{"name":"varainces3","type":"float32","default":0},{"name":"aspect_ratios","default":0},{"name":"img_w","default":0},{"name":"img_h","default":0},{"name":"step_w","default":-233},{"name":"step_h","default":-233},{"name":"offset","default":0}]}},{"name":"DetectionOutput","schema":{"operator":49,"attributes":[{"name":"num_class","default":0},{"name":"share_location","default":0},{"name":"background_label_id","default":0},{"name":"variance_encoded_in_target","default":0},{"name":"code_type","default":0},{"name":"keep_top_k","default":0},{"name":"confidence_threshold","default":0},{"name":"nms_param.nms_threshold","default":0},{"name":"nms_param.top_k","default":0},{"name":"eta","default":0}]}},{"name":"Interp","schema":{"operator":50}},{"name":"DeconvolutionDepthWise","schema":{"operator":51,"category":"Layer"}},{"name":"Shuffle","schema":{"operator":52,"attributes":[{"name":"group","default":1}]}},{"name":"InstanceNorm","schema":{"operator":53}},{"name":"Clip","schema":{"operator":54,"attributes":[{"name":"min","default":0},{"name":"max","default":0}]}},{"name":"Reorg","schema":{"operator":55,"attributes":[{"name":"stride","default":0},{"name":"reverse","default":0}]}},{"name":"YoloDetectionOutput","schema":{"operator":56}},{"name":"Quantize","schema":{"operator":57}},{"name":"Dequantize","schema":{"operator":58}},{"name":"Yolov3DetectionOutput","schema":{"operator":59}},{"name":"ROIPooling","schema":{"operator":60,"attributes":[{"name":"pool_type","default":0},{"name":"pool_type","type":"float32","default":0},{"name":"pooled_w","default":0},{"name":"pooled_h","default":0},{"name":"pooled_d","default":0}]}},{"name":"ROIAlign","schema":{"operator":61}},{"name":"Packing","schema":{"operator":62}},{"name":"Requantize","schema":{"operator":63}},{"name":"Cast","schema":{"operator":64}},{"name":"HardSigmoid","schema":{"operator":65,"category":"Activation","attributes":[{"name":"alpha","type":"float32","default":0},{"name":"beta","type":"float32","default":0}]}},{"name":"SELU","schema":{"operator":66,"category":"Activation","attributes":[{"name":"alpha","default":0},{"name":"gamma","default":0}]}},{"name":"ReLU6","schema":{"category":"Activation"}},{"name":"Conv3D","schema":{"operator":68,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_w","type":"int32","default":0},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_d","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"stride_d","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"pad_d ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_w","type":"int32","default":0},{"name":"dialation_h","type":"int32","default":1},{"name":"dialation_d","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"HardSwish","schema":{"operator":69,"category":"Layer","attributes":[{"name":"alpha","type":"float32","default":1},{"name":"beta","type":"float32","default":1}]}},{"name":"HdrGuide","schema":{"operator":70,"category":"Layer"}},{"name":"Max","schema":{"operator":71,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Min","schema":{"operator":72,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Mul","schema":{"operator":73,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Pooling3D","schema":{"operator":74,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"kernel_d","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"stride_d ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"pad_d","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"kernel_d_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"Pow","schema":{"operator":75,"category":"Layer","attributes":[{"name":"exponent","type":"float32","default":0},{"name":"scale ","type":"float32","default":0},{"name":"shift ","type":"float32","default":0}]}},{"name":"StridedSlice","schema":{"operator":76,"category":"Layer","attributes":[{"name":"n1","default":0}]}},{"name":"Sub","schema":{"operator":77,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Upsample","schema":{"operator":78,"category":"Layer","attributes":[{"name":"type","default":0},{"name":"scale_h","type":"float32","default":0},{"name":"scale_w","type":"float32","default":0},{"name":"align_corners","default":0},{"name":"height","default":0},{"name":"width","default":0}]}},{"name":"BlobScale","schema":{"operator":78,"category":"Layer"}},{"name":"Add","schema":{"operator":79,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Div","schema":{"operator":80,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"SplitV","schema":{"operator":81,"category":"Layer","attributes":[{"name":"axis","default":1},{"name":"slice_count","default":1}]}},{"name":"Sub","schema":{"operator":80,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"InstBatchNormCxx","schema":{"operator":81,"category":"Layer"}},{"name":"SoftmaxCaffe","schema":{"operator":82,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn.js new file mode 100644 index 0000000000000000000000000000000000000000..e1df76bdbd8b1132d037922d6a73b3b6d99bfdf8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/tnn.js @@ -0,0 +1 @@ +var tnn=tnn||{},base=base||require("./base");tnn.ModelFactory=class{match(t){const e=t.identifier.toLowerCase();if(e.endsWith(".tnnproto")){let e=t.text;e=e.substring(0,Math.min(e.length,128));const n=e.split("\n").shift().trim();if(n.startsWith('"')&&n.endsWith('"')){const t=n.replace(/(^")|("$)/g,"").split(",").shift().trim().split(" ");if(3===t.length||t.length>=4&&"4206624770"===t[3])return!0}}if(e.endsWith(".tnnmodel")){const e=t.buffer;if(e.length>4&&4206624770==(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0)return!0}return!1}open(t,e){return tnn.Metadata.open(e).then((e=>{const n=t.identifier.toLowerCase();if(n.endsWith(".tnnproto")){const s=t.identifier.substring(0,t.identifier.length-9)+".tnnmodel";return t.request(s,null).then((n=>new tnn.Model(e,t.text,n))).catch((()=>new tnn.Model(e,t.text,null))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new tnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}if(n.endsWith(".tnnmodel")){const s=t.identifier.substring(0,t.identifier.length-9)+".tnnproto";return t.request(s,"utf-8").then((n=>new tnn.Model(e,n,t.buffer))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new tnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}}))}},tnn.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new tnn.Graph(t,e,n))}get format(){return"TNN"}get graphs(){return this._graphs}},tnn.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new tnn.LayerResourceReader(n),i=new tnn.TextProtoReader(e);for(const t of i.inputs){const e=new tnn.TensorShape(t.shape),n=new tnn.TensorType("float32",e);this._inputs.push(new tnn.Parameter(t.name,[new tnn.Argument(t.name,n,null)]))}for(const t of i.outputs)this._outputs.push(new tnn.Parameter(t.name,[new tnn.Argument(t.name,null,null)]));for(const e of i.layers)this._nodes.push(new tnn.Node(t,s,e))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},tnn.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},tnn.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new tnn.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},tnn.Node=class{constructor(t,e,n){this._metadata=t,this._inputs=[],this._outputs=[],this._attributes=[],this._type=n.type,this._name=n.name;const s=t.operator(this._type);s&&(this._type=s);const i=t.type(this._type),a=i&&i.attributes?i&&i.attributes.slice():[],r=n.attributes.slice();for(;r.length>0;){const t=a.shift();let e=null,s="";if(t&&"int32[]"===t.type&&t.size)s=t.name,e=r.splice(0,n.attr[t.size]).map((t=>parseInt(t.value,10)));else{const t=r.shift();s=t.key,e=t.value}this._attributes.push(new tnn.Attribute(t,s,e))}const o=n.inputs;let h=0;if(i&&i.inputs){for(const t of i.inputs)if(h""!=e||"optional"!=t.option)).map((t=>new tnn.Argument(t,null,null)));this._inputs.push(new tnn.Parameter(t.name,n)),h+=e}}else this._inputs=this._inputs.concat(o.slice(h).map(((t,e)=>{const n=h+e==0?"input":(h+e).toString();return new tnn.Parameter(n,[new tnn.Argument(t,null,null)])})));const u=n.outputs;let l=0;if(i&&i.outputs){for(const t of i.outputs)if(lnew tnn.Argument(t,null,null)));this._outputs.push(new tnn.Parameter(t.name,n)),l+=e}}else this._outputs=this._outputs.concat(u.slice(l).map(((t,e)=>{const n=l+e==0?"output":(l+e).toString();return new tnn.Parameter(n,[new tnn.Argument(t,null,null)])})));switch(this._type){case"Convolution":case"ConvolutionDepthWise":case"Deconvolution":case"DeconvolutionDepthWise":{const t=e.read(this._name);if(t){const e=parseInt(n.attr[2]||0,10),s=parseInt(n.attr[3]||0,10),i=parseInt(n.attr[4]||s,10),a=t.filter.length;this._weight(t,"filter",[e,a/(e*s*i),s,i]),t.bias&&this._weight(t,"bias",[e]),t.quantized&&this._weight(t,"quantized",[e])}break}case"Conv3D":{const t=e.read(this._name);if(t){const s=parseInt(n.attr[2]||0,10),i=parseInt(n.attr[3]||0,10),a=parseInt(n.attr[4]||i,10),r=parseInt(n.attr[5]||i,10),o=t.filter.length;this._weight(t,"weight",[s,o/(s*i*a*r),i,a,r]),t.bias&&this._weight(e,"bias",[s])}break}case"InnerProduct":{const t=e.read(this._name);if(t){const e=parseInt(n.attr[0]||0,10),s=t.weight.length;this._weight(t,"weight",[e,s/e]),this._weight(t,"bias",[e]),"int8"===t.weight.dataType&&this._weight(t,"scale",[e])}break}case"PReLU":{const t=e.read(this._name);t&&this._weight(t,"slope",[t.slope.length]);break}case"BatchNormCxx":{const t=e.read(this._name);t&&(this._weight(t,"scale",[t.scale.length]),this._weight(t,"bias",[t.bias.length]));break}case"Div":case"Sub":case"Add":case"Mul":if(1===this._inputs.length){const t=e.read(this._name);if(t){const e=t.slope.length;this._weight(t,"slope",[e])}}break;case"HdrGuide":{const t=e.read(this._name);if(t){const e=t.ccm_weight.length;this._weight(t,"ccm_weight",[e]),this._weight(t,"ccm_bias",[e]),this._weight(t,"shifts",[e]),this._weight(t,"slopes",[e]),this._weight(t,"projection_weight",[e]),this._weight(t,"projection_bias",[e])}break}case"BlobScale":{const t=e.read(this._name);if(t){const e=t.scale.length;this._weight(t,"scale",[e]),this._weight(t,"bias",[e])}break}}}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_weight(t,e,n){const s=t[e];if(!s)throw new tnn.Error("Layer initializer'"+t.type+"."+e+"' not found '");const i=new tnn.Tensor(new tnn.TensorType(s.dataType,new tnn.TensorShape(n)),s.value);this._inputs.push(new tnn.Parameter(e,[new tnn.Argument("",null,i)]))}},tnn.Attribute=class{constructor(t,e,n){if(this._type="",this._name=e.toString(),this._value=n,t){switch(this._name=t.name,t.type&&(this._type=t.type),this._type){case"int32":this._value=parseInt(this._value,10);break;case"float32":this._value=parseFloat(this._value);break;case"float32[]":this._value=this._value.map((t=>parseFloat(t)))}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1)}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},tnn.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Weight"}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},tnn.TensorType=class{constructor(t,e){this._dataType=t||"?",this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},tnn.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},tnn.Metadata=class{static open(t){return tnn.Metadata._metadata?Promise.resolve(tnn.Metadata._metadata):t.request(null,"tnn-metadata.json","utf-8").then((t=>(tnn.Metadata._metadata=new tnn.Metadata(t),tnn.Metadata._metadata))).catch((()=>(tnn.Metadata._metadata=new tnn.Metadata(null),tnn.Metadata._metadatas)))}constructor(t){if(this._operatorMap=new Map,this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema),Object.prototype.hasOwnProperty.call(t.schema,"operator")&&this._operatorMap.set(t.schema.operator,t.name))}}operator(t){return this._operatorMap.get(t)}type(t){return this._map.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},tnn.TextProtoReader=class{constructor(t){const e=(t,e,n,s)=>t.split(e).map((t=>n?t.trim():t)).filter((t=>!s||t)),n=e(t.replace(/\r?\n|"/g,""),",",!0,!1);if(n.length<=5)throw new tnn.Error("Invalid line count.");const s=e(n.shift()," ",!0,!1);if(s.length<3)throw new tnn.Error("Invalid header size.");if(s.length>3&&"4206624770"!==s[3])throw new tnn.Error("Invalid signature '"+s[3]+"'.");for(this._inputs=e(n.shift(),":",!0,!1).map((t=>{const n=e(t," ",!0,!1);return{name:n.shift(),shape:n.map((t=>parseInt(t,10)))}})),n.shift(),this._outputs=e(n.shift()," ",!0,!1).map((t=>({name:t}))),n.shift(),this._layers=[];n.length>0;){const t=n.shift().trim();if(t.length>0){const n=e(t," ",!0,!0),s={};s.type=n.shift(),s.name=n.shift();const i=parseInt(n.shift(),10),a=parseInt(n.shift(),10);s.inputs=n.splice(0,i),s.outputs=n.splice(0,a),s.attr={},s.attributes=[];let r=0;for(const t of n){const e=t.split(" ");if(1===e.length){let t=r,n=e.toString();const i=parseInt(t,10);i<0&&(n=n.split(",").map((t=>t.trim())),n.shift(),t=(-(i+23300)).toString()),s.attr[t]=n,s.attributes.push({key:t,value:n}),r++}}this._layers.push(s)}}}get inputs(){return this._inputs}get outputs(){return this._outputs}get layers(){return this._layers}},tnn.LayerResourceReader=class{constructor(t){if(this._layerResources=[],t){const e=new tnn.BinaryReader(t),n=e.uint32();if(4206624770!==n)throw new tnn.Error("Invalid blob header signature '"+n.toString()+"'.");const s=536870911&e.int32(),i=t=>{const e=t.uint32();if(4206624770!==e)throw new tnn.Error("Invalid raw signature '"+e.toString()+"'.");const n=t.int32();if(n>4)throw new tnn.Error("Unknown data type '"+n+"'.");const s=t.int32();return s<=0?null:{dataType:["float32","float16","int8","int32","bfloat16"][n],length:s/[4,2,1,4,2][n],value:t.bytes(s)}};for(let t=0;tthis._buffer.length)throw new tnn.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}uint32(){const t=this._position;return this.skip(4),this._dataView.getUint32(t,!0)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}string(){const t=this.int32(),e=this._position;this.skip(t);const n=this._buffer.subarray(e,this._position);return new TextDecoder("utf-8").decode(n)}expect(t){const e=this.string();if(t!==e)throw new tnn.Error("Invalid string '"+e+"' instead of '"+t+"'.")}},tnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading TNN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..90575950f50131da82196d3202e19c88d56a5cba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch-metadata.json @@ -0,0 +1 @@ +[{"name":"nn.Linear","schema":{"category":"Layer"}},{"name":"nn.LinearNoBias","schema":{"category":"Layer"}},{"name":"nn.SpatialConvolution","schema":{"category":"Layer","attributes":[{"name":"benchmarked","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false},{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"fmode","visible":false},{"name":"bwmode","visible":false},{"name":"bdmode","visible":false}]}},{"name":"cudnn.SpatialConvolution","schema":{"category":"Layer","attributes":[{"name":"benchmarked","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false},{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"fmode","visible":false},{"name":"bwmode","visible":false},{"name":"bdmode","visible":false}]}},{"name":"nn.VolumetricConvolution","schema":{"category":"Layer"}},{"name":"nn.SpatialConvolutionMM","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false}]}},{"name":"nn.SpatialFullConvolution","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false}]}},{"name":"cudnn.SpatialFullConvolution","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false}]}},{"name":"nn.SpatialDilatedConvolution","schema":{"category":"Layer","attributes":[{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false}]}},{"name":"nn.SpatialSubtractiveNormalization","schema":{"category":"Normalization"}},{"name":"nn.InstanceNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"nOutput","visible":false},{"name":"prev_batch_size","visible":false},{"name":"eps","default":0.00001},{"name":"momentum","default":0.1}]}},{"name":"nn.BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"cudnn.BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"nn.SpatialBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001},{"name":"mode","default":"CUDNN_BATCHNORM_SPATIAL"},{"name":"nDim","default":4},{"name":"__shareGradInputKey","visible":false}]}},{"name":"cudnn.SpatialBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001},{"name":"mode","default":"CUDNN_BATCHNORM_SPATIAL"},{"name":"nDim","default":4},{"name":"__shareGradInputKey","visible":false}]}},{"name":"nn.VolumetricBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"nn.SpatialAveragePooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING"},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"count_include_pad","visible":false}]}},{"name":"cudnn.SpatialAveragePooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING"},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"count_include_pad","visible":false}]}},{"name":"nn.VolumetricAveragePooling","schema":{"category":"Pool"}},{"name":"nn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"cudnn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"inn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"nn.VolumetricMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false}]}},{"name":"nn.SpatialFractionalMaxPooling","schema":{"category":"Pool"}},{"name":"nn.SpatialZeroPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.SpatialReflectionPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.SpatialReplicationPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.Concat","schema":{"category":"Tensor","attributes":[{"name":"outputSize","visible":false}]}},{"name":"nn.PReLU","schema":{"category":"Activation"}},{"name":"nn.ReLU","schema":{"category":"Activation","attributes":[{"name":"threshold","default":0},{"name":"val","default":0},{"name":"inplace","default":false,"visible":false},{"name":"mode","default":"CUDNN_ACTIVATION_RELU"},{"name":"nElem","visible":false}]}},{"name":"cudnn.ReLU","schema":{"category":"Activation","attributes":[{"name":"threshold","default":0},{"name":"val","default":0},{"name":"inplace","default":false,"visible":false},{"name":"mode","default":"CUDNN_ACTIVATION_RELU"},{"name":"nElem","visible":false}]}},{"name":"nn.SoftMax","schema":{"category":"Activation"}},{"name":"nn.LogSoftMax","schema":{"category":"Activation"}},{"name":"cudnn.LogSoftMax","schema":{"category":"Activation"}},{"name":"nn.Tanh","schema":{"category":"Activation","attributes":[{"name":"mode","default":"CUDNN_ACTIVATION_TANH"},{"name":"nElem","visible":false}]}},{"name":"nn.LeakyReLU","schema":{"category":"Activation","attributes":[{"name":"negval","default":0.01,"visible":false},{"name":"inplace","default":false,"visible":false}]}},{"name":"nn.Sigmoid","schema":{"category":"Activation","attributes":[{"name":"mode","default":"CUDNN_ACTIVATION_SIGMOID"},{"name":"nElem","visible":false}]}},{"name":"nn.Reshape","schema":{"category":"Shape","attributes":[{"name":"nelement","visible":false}]}},{"name":"nn.Dropout","schema":{"category":"Dropout","attributes":[{"name":"v2","visible":false}]}},{"name":"nn.SpatialDropout","schema":{"category":"Dropout"}},{"name":"nn.Normalize","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.Normalize2","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.SpatialCrossMapLRN","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.Mean","schema":{"attributes":[{"name":"squeeze","default":true},{"name":"sizeAverage","default":false},{"name":"dimension","default":1},{"name":"nInputDims","visible":false}]}},{"name":"nn.MulConstant","schema":{"attributes":[{"name":"inplace","default":false,"visible":false}]}},{"name":"nn.Identity","schema":{}},{"name":"nn.ConcatTable","schema":{}},{"name":"nn.CAddTable","schema":{}},{"name":"nn.ScaleTable","schema":{}},{"name":"nn.SelectTable","schema":{}},{"name":"w2nn.ScaleTable","schema":{}},{"name":"nn.SplitTable","schema":{}},{"name":"nn.FlattenTable","schema":{}},{"name":"nn.View","schema":{}},{"name":"nn.Sequencer","schema":{}},{"name":"nn.TotalVariation","schema":{}},{"name":"nn.ShaveImage","schema":{}},{"name":"nn.Contiguous","schema":{}},{"name":"nn.Squeeze","schema":{"category":"Transform"}},{"name":"nn.MM","schema":{}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch.js new file mode 100644 index 0000000000000000000000000000000000000000..987552869673ca83037a9c6b45dab02e31fbd156 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/torch.js @@ -0,0 +1 @@ +var torch=torch||{},base=base||require("./base"),long=long||{Long:require("long")};torch.ModelFactory=class{match(t){if("t7"==t.identifier.split(".").pop().toLowerCase()){const n=t.buffer;return!(n.length>=1&&n[0]>58)}return!1}open(t,n){return torch.Metadata.open(n).then((i=>{const e=t.identifier;try{let s=new torch.T7Reader(t.buffer,(t=>(!t||"nn.JointTrainModule"==t||t.startsWith("nn.MSDNet_")||t.startsWith("onmt.")||n.exception(new torch.Error("Unknown type '"+t+"' in '"+e+"'."),!1),null))).read();return s&&Array.isArray(s)&&2==s.length&&s[0].__type__&&!s[1].__type__&&(s=s[0]),new torch.Model(i,s)}catch(t){const n=t&&t.message?t.message:t.toString();throw new torch.Error(n.replace(/\.$/,"")+" in '"+e+"'.")}}))}},torch.Model=class{constructor(t,n){this._graphs=[],this._graphs.push(new torch.Graph(t,n))}get graphs(){return this._graphs}get format(){return"Torch v7"}},torch.Graph=class{constructor(t,n){this._inputs=[],this._outputs=[],this._nodes=[],this._groups="false",Object.prototype.hasOwnProperty.call(n,"model")&&(n=n.model);const i=[],e=[];this._loadModule(t,n,[],"",i,e),this._inputs=this._inputs.concat(i.map(((t,n)=>new torch.Parameter("input"+(0!=n?(n+1).toString():""),!0,[t])))),this._outputs=this._outputs.concat(e.map(((t,n)=>new torch.Parameter("output"+(0!=n?(n+1).toString():""),!0,[t]))))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get groups(){return this._groups}_loadModule(t,n,i,e,s,r){switch(i.length>0&&(this._groups=!0),n.__type__){case"nn.Sequential":{i.push(e);let o=s,a=[];const h=n.modules.length;let c=0;for(const e of n.modules)c==h-1&&(a=r),this._loadModule(t,e,i,c.toString(),o,a),o=a,a=[],c++;i.pop();break}case"nn.Parallel":case"nn.ParallelTable":case"nn.JointTrain":{i.push(e);let o=[],a=[],h=0;for(const e of n.modules){const n=[].concat(s),c=[].concat(r);this._loadModule(t,e,i,h.toString(),n,c),0==s.length&&(o=o.concat(n)),0==r.length&&(a=a.concat(c)),h++}s=s.concat(o);for(const t of a)r.push(t);i.pop();break}case"nn.Concat":case"nn.ConcatTable":{const o=e;0==s.length&&s.push(new torch.Argument(i.join("/")+":"+e+":in",null,null));let a=[],h=0;for(const e of n.modules){const n=s.map((t=>t)),r=[];this._loadModule(t,e,i,o+"."+h.toString(),n,r),a=a.concat(r),h++}delete n.modules,delete n.dimension,this._createNode(t,n,i,e,a,r);break}case"nn.Inception":delete n.modules,delete n.module,delete n.transfer,delete n.pool,this._createNode(t,n,i,e,s,r);break;default:this._createNode(t,n,i,e,s,r)}}_createNode(t,n,i,e,s,r){this._nodes.push(new torch.Node(t,n,i,e,s,r))}},torch.Parameter=class{constructor(t,n,i){this._name=t,this._visible=n,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},torch.Argument=class{constructor(t,n,i){if("string"!=typeof t)throw new torch.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=n,this._initializer=i}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},torch.Node=class{constructor(t,n,i,e,s,r){this._metadata=t,this._group=i.join("/"),n.name&&"string"==typeof n.name?(this._name=n.name,delete n.name):this._name=this._group?this._group+":"+e:e,this._type=n.__type__||"nn.Module";let o=[];for(const t of Object.keys(n)){const i=n[t];if(i&&i.__type__&&i.__type__.startsWith("torch.")&&i.__type__.endsWith("Storage")){const e=[];i.reset();for(let t=0;tt&&t.__type__&&t.__type__.startsWith("nn.")))||(i.__type__&&i.__type__.startsWith("torch.")&&i.__type__.endsWith("Tensor")?o.push(new torch.Parameter(t,!0,[new torch.Argument(t,null,new torch.Tensor(i))])):"modules"==t||i.__type__&&"Function"!=i.__type__||this._attributes.push(new torch.Attribute(this._metadata,this._type,t,i)))}this._inputs=[],0==s.length&&this._name&&s.push(new torch.Argument(this._name+":in",null,null)),this._inputs.push(new torch.Parameter("input",!0,s)),0==r.length&&this._name&&r.push(new torch.Argument(this._name,null,null)),this._outputs=[],this._outputs.push(new torch.Parameter("output",!0,r)),o=o.filter((t=>"weight"!=t.name||(this._inputs.push(t),!1))),o=o.filter((t=>"bias"!=t.name||(this._inputs.push(t),!1))),this._inputs=this._inputs.concat(o)}get name(){return this._name}get type(){return this._type}get group(){return this._group}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_updateSize(t,n){Object.prototype.hasOwnProperty.call(t,n+"W")&&Object.prototype.hasOwnProperty.call(t,n+"H")&&(t[n]=[t[n+"W"],t[n+"H"]],delete t[n+"W"],delete t[n+"H"])}_updateBox(t,n){Object.prototype.hasOwnProperty.call(t,n+"_t")&&Object.prototype.hasOwnProperty.call(t,n+"_r")&&Object.prototype.hasOwnProperty.call(t,n+"_b")&&Object.prototype.hasOwnProperty.call(t,n+"_l")&&(t[n]=[t[n+"_t"],t[n+"_r"],t[n+"_b"],t[n+"_l"]],delete t[n+"_t"],delete t[n+"_r"],delete t[n+"_b"],delete t[n+"_l"])}},torch.Attribute=class{constructor(t,n,i,e){this._name=i,this._value=e,"train"==i&&(this._visible=!1);const s=t.attribute(n,i);s&&(Object.prototype.hasOwnProperty.call(s,"visible")?this._visible=s.visible:Object.prototype.hasOwnProperty.call(s,"default")&&JSON.stringify(s.default)==JSON.stringify(this._value)&&(this._visible=!1))}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},torch.Tensor=class{constructor(t){this._type=new torch.TensorType(t),this._storage=t.storage}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e3;const n=this._decode(t,0);return JSON.stringify(n,null,4)}_context(){const t={state:null,index:0,count:0};if(!this._storage||!this._storage.reader)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"uint8":case"int8":case"int16":case"int32":case"int64":case"float32":case"float64":break;default:t.state="Tensor data type is not implemented."}return t.dimensions=this._type.shape.dimensions,t.dimensions||0!=t.dimensions.length?(t.storage=this._storage,t.storage.reset(),t):(t.state="Tensor has no dimensions.",t)}_decode(t,n){const i=[],e=t.dimensions[n];if(n==t.dimensions.length-1)for(let n=0;nt.limit)return i.push("..."),i;i.push(t.storage.read()),t.index++,t.count++}else for(let s=0;st.limit)return i.push("..."),i;i.push(this._decode(t,n+1))}return i}},torch.TensorType=class{constructor(t){this._dataType=t.dataType,this._shape=new torch.TensorShape(t.size)}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},torch.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},torch.Metadata=class{static open(t){return torch.Metadata._metadata?Promise.resolve(torch.Metadata._metadata):t.request(null,"torch-metadata.json","utf-8").then((t=>(torch.Metadata._metadata=new torch.Metadata(t),torch.Metadata._metadata))).catch((()=>(torch.Metadata._metadata=new torch.Metadata(null),torch.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const n=JSON.parse(t);if(n)for(const t of n)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]||null}attribute(t,n){let i=this._attributeCache[t];if(!i){i={};const n=this.type(t);if(n&&n.attributes&&n.attributes.length>0)for(const t of n.attributes)i[t.name]=t;this._attributeCache[t]=i}return i[n]||null}},torch.Error=class extends Error{constructor(t){super(t),this.name="Error loading Torch model."}},torch.T7Reader=class{constructor(t,n){if(this._callback=n,this._memo=new Map,this._registry={},this._registry["bnn.Binary"]=function(t){t.nn(this)},this._registry["bnn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["cudnn.BatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.ReLU"]=function(t){t.nn(this)},this._registry["cudnn.Sigmoid"]=function(t){t.nn(this)},this._registry["cudnn.SoftMax"]=function(t){t.nn(this)},this._registry["cudnn.LogSoftMax"]=function(t){t.nn(this)},this._registry["cudnn.SpatialAveragePooling"]=function(t){t.nn(this)},this._registry["cudnn.SpatialBatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["cudnn.SpatialFullConvolution"]=function(t){t.nn(this)},this._registry["cudnn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["cudnn.SpatialSoftMax"]=function(t){t.nn(this)},this._registry["cudnn.Tanh"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricAveragePooling"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricBatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricConvolution"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricMaxPooling"]=function(t){t.nn(this)},this._registry.Dict=function(t){t.nn(this)},this._registry["inn.ConstAffine"]=function(t){t.nn(this)},this._registry["inn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["nn.Abs"]=function(t){t.nn(this)},this._registry["nn.AddConstant"]=function(t){t.nn(this)},this._registry["nn.BatchNormalization"]=function(t){t.nn(this)},this._registry["nn.BilinearSamplerBHWD"]=function(t){t.nn(this)},this._registry["nn.BinActiveZ"]=function(t){t.nn(this)},this._registry["nn.BCECriterion"]=function(t){t.nn(this)},this._registry["nn.CMul"]=function(t){t.nn(this)},this._registry["nn.CAddTable"]=function(t){t.nn(this)},this._registry["nn.CDivTable"]=function(t){t.nn(this)},this._registry["nn.CMulTable"]=function(t){t.nn(this)},this._registry["nn.CSubTable"]=function(t){t.nn(this)},this._registry["nn.Concat"]=function(t){t.nn(this)},this._registry["nn.Copy"]=function(t){t.nn(this)},this._registry["nn.ConcatTable"]=function(t){t.nn(this)},this._registry["nn.Contiguous"]=function(t){t.nn(this)},this._registry["nn.Constant"]=function(t){t.nn(this)},this._registry["nn.CostVolMulti"]=function(t){t.nn(this)},this._registry["nn.DepthConcat"]=function(t){t.nn(this)},this._registry["nn.Dropout"]=function(t){t.nn(this)},this._registry["nn.Exp"]=function(t){t.nn(this)},this._registry["nn.ExpOut"]=function(t){t.nn(this)},this._registry["nn.FlattenTable"]=function(t){t.nn(this)},this._registry["nn.GenNoise"]=function(t){t.nn(this)},this._registry["nn.Identity"]=function(t){t.nn(this)},this._registry["nn.Index"]=function(t){t.nn(this)},this._registry["nn.Inception"]=function(t){t.nn(this)},this._registry["nn.InstanceNormalization"]=function(t){t.nn(this)},this._registry["nn.JoinTable"]=function(t){t.nn(this)},this._registry["nn.JointTrain"]=function(t){t.nn(this)},this._registry["nn.KeypointCoordinate"]=function(t){t.nn(this)},this._registry["nn.LeakyReLU"]=function(t){t.nn(this)},this._registry["nn.Linear"]=function(t){t.nn(this)},this._registry["nn.LinearNoBias"]=function(t){t.nn(this)},this._registry["nn.LogSoftMax"]=function(t){t.nn(this)},this._registry["nn.LookupTable"]=function(t){t.nn(this)},this._registry["nn.LSTM"]=function(t){t.nn(this)},this._registry["nn.MaskZero"]=function(t){t.nn(this)},this._registry["nn.MapTable"]=function(t){t.nn(this)},this._registry["nn.Max"]=function(t){t.nn(this)},this._registry["nn.Mean"]=function(t){t.nn(this)},this._registry["nn.Min"]=function(t){t.nn(this)},this._registry["nn.MulConstant"]=function(t){t.nn(this)},this._registry["nn.MM"]=function(t){t.nn(this)},this._registry["nn.MSECriterion"]=function(t){t.nn(this)},this._registry["nn.Narrow"]=function(t){t.nn(this)},this._registry["nn.NarrowTable"]=function(t){t.nn(this)},this._registry["nn.Normalize"]=function(t){t.nn(this)},this._registry["nn.Normalize2"]=function(t){t.nn(this)},this._registry["nn.NoiseFill"]=function(t){t.nn(this)},this._registry["nn.Padding"]=function(t){t.nn(this)},this._registry["nn.Parallel"]=function(t){t.nn(this)},this._registry["nn.ParallelCriterion"]=function(t){t.nn(this)},this._registry["nn.ParallelTable"]=function(t){t.nn(this)},this._registry["nn.PixelShuffle"]=function(t){t.nn(this)},this._registry["nn.Power"]=function(t){t.nn(this)},this._registry["nn.PReLU"]=function(t){t.nn(this)},this._registry["nn.Recursor"]=function(t){t.nn(this)},this._registry["nn.ReLU"]=function(t){t.nn(this)},this._registry["nn.Replicate"]=function(t){t.nn(this)},this._registry["nn.Reshape"]=function(t){t.nn(this)},this._registry["nn.ShaveImage"]=function(t){t.nn(this)},this._registry["nn.Select"]=function(t){t.nn(this)},this._registry["nn.SelectTable"]=function(t){t.nn(this)},this._registry["nn.Sequencer"]=function(t){t.nn(this)},this._registry["nn.Sequential"]=function(t){t.nn(this)},this._registry["nn.Sigmoid"]=function(t){t.nn(this)},this._registry["nn.Sum"]=function(t){t.nn(this)},this._registry["nn.SoftMax"]=function(t){t.nn(this)},this._registry["nn.SpatialAveragePooling"]=function(t){t.nn(this)},this._registry["nn.SpatialBatchNormalization"]=function(t){t.nn(this)},this._registry["nn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialConvolutionMM"]=function(t){t.nn(this)},this._registry["nn.SpatialCrossMapLRN"]=function(t){t.nn(this)},this._registry["nn.SpatialDilatedConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialDropout"]=function(t){t.nn(this)},this._registry["nn.SpatialFractionalMaxPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialFullConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialLPPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialReflectionPadding"]=function(t){t.nn(this)},this._registry["nn.SpatialReplicationPadding"]=function(t){t.nn(this)},this._registry["nn.SpatialSoftMax"]=function(t){t.nn(this)},this._registry["nn.SpatialSubtractiveNormalization"]=function(t){t.nn(this)},this._registry["nn.SpatialUpSamplingBilinear"]=function(t){t.nn(this)},this._registry["nn.SpatialUpSamplingNearest"]=function(t){t.nn(this)},this._registry["nn.SpatialZeroPadding"]=function(t){t.nn(this)},this._registry["nn.SplitTable"]=function(t){t.nn(this)},this._registry["nn.Squeeze"]=function(t){t.nn(this)},this._registry["nn.Square"]=function(t){t.nn(this)},this._registry["nn.Sqrt"]=function(t){t.nn(this)},this._registry["nn.StereoJoin"]=function(t){t.nn(this)},this._registry["nn.Tanh"]=function(t){t.nn(this)},this._registry["nn.Transpose"]=function(t){t.nn(this)},this._registry["nn.TotalVariation"]=function(t){t.nn(this)},this._registry["nn.Unpool"]=function(t){t.nn(this)},this._registry["nn.View"]=function(t){t.nn(this)},this._registry["nn.gModule"]=function(t){t.nn(this)},this._registry["nngraph.Node"]=function(t){t.nn(this)},this._registry["graph.Edge"]=function(t){t.nn(this)},this._registry["graph.Graph"]=function(t){t.nn(this)},this._registry["torch.ByteTensor"]=function(t){t.tensor(this,"uint8")},this._registry["torch.CharTensor"]=function(t){t.tensor(this,"int8")},this._registry["torch.ShortTensor"]=function(t){t.tensor(this,"int16")},this._registry["torch.IntTensor"]=function(t){t.tensor(this,"int32")},this._registry["torch.LongTensor"]=function(t){t.tensor(this,"int64")},this._registry["torch.FloatTensor"]=function(t){t.tensor(this,"float32")},this._registry["torch.DoubleTensor"]=function(t){t.tensor(this,"float64")},this._registry["torch.CudaByteTensor"]=function(t){t.tensor(this,"uint8")},this._registry["torch.CudaCharTensor"]=function(t){t.tensor(this,"int8")},this._registry["torch.CudaShortTensor"]=function(t){t.tensor(this,"int16")},this._registry["torch.CudaIntTensor"]=function(t){t.tensor(this,"int32")},this._registry["torch.CudaLongTensor"]=function(t){t.tensor(this,"int64")},this._registry["torch.CudaTensor"]=function(t){t.tensor(this,"float32")},this._registry["torch.CudaDoubleTensor"]=function(t){t.tensor(this,"float64")},this._registry["torch.ByteStorage"]=function(t){t.storage(this,"uint8",1)},this._registry["torch.CharStorage"]=function(t){t.storage(this,"int8",1)},this._registry["torch.ShortStorage"]=function(t){t.storage(this,"int16",2)},this._registry["torch.IntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.LongStorage"]=function(t){t.storage(this,"int64",8)},this._registry["torch.FloatStorage"]=function(t){t.storage(this,"float32",4)},this._registry["torch.DoubleStorage"]=function(t){t.storage(this,"float64",8)},this._registry["torch.CudaByteStorage"]=function(t){t.storage(this,"uint8",1)},this._registry["torch.CudaCharStorage"]=function(t){t.storage(this,"int8",1)},this._registry["torch.CudaShortStorage"]=function(t){t.storage(this,"int16",2)},this._registry["torch.CudaIntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.CudaLongStorage"]=function(t){t.storage(this,"int64",8)},this._registry["torch.CudaIntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.CudaStorage"]=function(t){t.storage(this,"float32",4)},this._registry["torch.CudaFloatStorage"]=function(t){t.storage(this,"float64",8)},this._registry["w2nn.AuxiliaryLossTable"]=function(t){t.nn(this)},this._registry["w2nn.InplaceClip01"]=function(t){t.nn(this)},this._registry["w2nn.ScaleTable"]=function(t){t.nn(this)},0==t.length)throw new torch.Error("File is empty.");t[0]<=8?this._reader=new torch.BinaryReader(t):(this._reader=new torch.TextReader(t),this._reader.int32(),this._reader.reset())}read(){const t=this.int32();switch(t){case 0:return null;case 1:return this.float64();case 2:return this.string();case 3:return this.table();case 4:return this.object();case 5:return this.boolean();case 6:case 7:case 8:return this.function();default:throw new torch.Error("File format has invalid type '"+t+"'.")}}boolean(){return this._reader.boolean()}bytes(t){return this._reader.bytes(t)}int32(){return this._reader.int32()}int64(){return this._reader.int64()}int64s(t){return this._reader.int64s(t)}float64(){return this._reader.float64()}string(){return this._reader.string()}object(){const t=this.int32();if(this._memo.has(t))return this._memo.get(t);let n=this.string(),i=null;n.startsWith("V ")?(i=this.string(),n=Number(n.split(" ")[1])):(i=n,n=0);const e={__type__:i};this._memo.set(t,e);let s=this._registry[i];return s?s.apply(e,[this,n]):(s=this._callback(i),s&&s.apply(e,[this,n]),this.nn(e)),e}table(){const t=this.int32();if(this._memo.has(t))return this._memo.get(t);const n={};this._memo.set(t,n);const i=this.int32();let e=!0,s=0;for(let t=0;t=0?s+=t:e=!1}const r=Object.keys(n).length;if(e&&r*(r+1)==2*s){const i=[];for(let t=0;tthis._buffer.length)throw new torch.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}boolean(){return 1==this.int32()}bytes(t){const n=this._position;return this.skip(t),this._buffer.subarray(n,this._position)}int8(){const t=this._position;return this.skip(1),this._dataView.getInt8(t,!0)}int16(){const t=this._position;return this.skip(2),this._dataView.getInt16(t,!0)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int64(){const t=this._position;this.skip(8);const n=this._dataView.getUint32(t,!0),i=this._dataView.getUint32(t+4,!0);return new long.Long(n,i,!1).toNumber()}int64s(t){const n=[];for(let i=0;i-1;){if(this._buffer[this._position++]==this._separator)return this._buffer.slice(n,this._position-1);if(this._position==this._buffer.length)return this._buffer.slice(n,this._position);t--}throw new torch.Error("Line exceeded maximum length.")}boolean(){return 1==this.int32()}bytes(t){return this.line(t)}int8(){return this.int64()}int16(){return this.int64()}int32(){return this.int64()}int64(){const t=this._textDecoder.decode(this.line(20)),n=Number.parseInt(t,10);if(Number.isNaN(t-n))throw new torch.Error("Couldn't parse int64 '"+t+"'.");return n}int64s(t){const n=[];if(t>0){const t=this._textDecoder.decode(this.line(Number.MAX_SAFE_INTEGER));for(const i of t.split(" ")){const t=Number.parseInt(i,10);if(Number.isNaN(i-t))throw new torch.Error("Couldn't parse int64 '"+i+"'.");n.push(t)}}return n}float32(){return this.float64()}float64(){const t=this._textDecoder.decode(this.line(24));if(t.startsWith("-nan"))return NaN;if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;const n=Number.parseFloat(t);if(Number.isNaN(t-n))throw new torch.Error("Couldn't parse float '"+t+"'.");return n}string(){const t=this.int32();if(0==t)return"";const n=this.line(t),i=this._textDecoder.decode(n);if(t!=i.length)throw torch.Error("Invalid text length.");return i}storage(t,n,i){if(t<=0)throw new torch.Error("Unsupported storage size '"+t+"'.");if("uint8"===i){const n=this._position;this._position+=t;const i=this._buffer.slice(n,this._position);return this.line(0),new torch.BinaryReader(i)}const e=this.line(Number.MAX_SAFE_INTEGER);return new torch.TextReader(e,32)}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=torch.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1919181ad65f07bb4574c0ebdacb50a14d8379a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-metadata.json @@ -0,0 +1 @@ +[{"name":"Activation","schema":{"category":"Activation","inputs":[{"name":"input"}]}},{"name":"Binary","schema":{"inputs":[{"name":"x"},{"name":"y"}]}},{"name":"Unary","schema":{"inputs":[{"name":"input"}]}},{"name":"Conv","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"kernel"}]}},{"name":"FullyConnected","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"input"},{"name":"shape"}]}},{"name":"StridedSlice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"end"},{"name":"strides"}]}},{"name":"Squeeze","schema":{"category":"Transform"}},{"name":"BatchNorm","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"moving_mean"},{"name":"moving_variance"}]}},{"name":"Pool","schema":{"category":"Pool","inputs":[{"name":"input"}]}},{"name":"_MaxPool","schema":{"category":"Pool","inputs":[{"name":"input"}]}},{"name":"Concat","schema":{"category":"Tensor"}},{"name":"Flatten","schema":{"category":"Shape"}},{"name":"GatherV2","schema":{"category":"Data","inputs":[{"name":"input"},{"name":"indices"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..087812e9dd8ba63e5d1dabebbbb3a8f44d2dbc64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("uff");$root.uff={},$root.uff.MetaGraph=class{constructor(){this.descriptors=[],this.graphs=[],this.referenced_data=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.MetaGraph,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.version=e.int64();break;case 2:r.descriptor_core_version=e.int64();break;case 3:r.descriptors.push($root.uff.Descriptor.decode(e,e.uint32()));break;case 4:r.graphs.push($root.uff.Graph.decode(e,e.uint32()));break;case 5:r.referenced_data.push($root.uff.MetaGraph.ReferencedDataEntry.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.MetaGraph.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph;for(e.start();!e.end();){const r=e.tag();switch(r){case"version":t.version=e.integer();break;case"descriptor_core_version":t.descriptor_core_version=e.integer();break;case"descriptors":t.descriptors.push($root.uff.Descriptor.decodeText(e,!0));break;case"graphs":t.graphs.push($root.uff.Graph.decodeText(e,!0));break;case"referenced_data":t.referenced_data.push($root.uff.MetaGraph.ReferencedDataEntry.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.MetaGraph.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.MetaGraph.prototype.descriptor_core_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.MetaGraph.ReferencedDataEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.MetaGraph.ReferencedDataEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph.ReferencedDataEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.ReferencedDataEntry.prototype.key="",$root.uff.MetaGraph.ReferencedDataEntry.prototype.value=null,$root.uff.MetaGraph.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.MetaGraph.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.ExtraFieldsEntry.prototype.key="",$root.uff.MetaGraph.ExtraFieldsEntry.prototype.value=null,$root.uff.Descriptor=class{constructor(){}static decode(e,t){const r=new $root.uff.Descriptor,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.version=e.int64();break;case 3:r.optional=e.bool();break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Descriptor;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"version":t.version=e.integer();break;case"optional":t.optional=e.boolean();break;default:e.field(r,t)}}return t}},$root.uff.Descriptor.prototype.id="",$root.uff.Descriptor.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.Descriptor.prototype.optional=!1,$root.uff.Graph=class{constructor(){this.nodes=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.Graph,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.nodes.push($root.uff.Node.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.Graph.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Graph;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"nodes":t.nodes.push($root.uff.Node.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.Graph.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.Graph.prototype.id="",$root.uff.Graph.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Graph.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Graph.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Graph.ExtraFieldsEntry.prototype.key="",$root.uff.Graph.ExtraFieldsEntry.prototype.value=null,$root.uff.Node=class{constructor(){this.inputs=[],this.fields=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.Node,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.inputs.push(e.string());break;case 3:r.operation=e.string();break;case 4:r.fields.push($root.uff.Node.FieldsEntry.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.Node.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"inputs":e.array(t.inputs,(()=>e.string()));break;case"operation":t.operation=e.string();break;case"fields":t.fields.push($root.uff.Node.FieldsEntry.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.Node.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.Node.prototype.id="",$root.uff.Node.prototype.operation="",$root.uff.Node.FieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Node.FieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node.FieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Node.FieldsEntry.prototype.key="",$root.uff.Node.FieldsEntry.prototype.value=null,$root.uff.Node.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Node.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Node.ExtraFieldsEntry.prototype.key="",$root.uff.Node.ExtraFieldsEntry.prototype.value=null,$root.uff.Data=class{constructor(){}get type(){return $root.uff.Data.typeSet=$root.uff.Data.typeSet||new Set(["s","s_list","d","d_list","b","b_list","i","i_list","blob","ref","dtype","dtype_list","dim_orders","dim_orders_list"]),Object.keys(this).find((e=>$root.uff.Data.typeSet.has(e)&&null!=this[e]))}static decode(e,t){const r=new $root.uff.Data,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.s=e.string();break;case 2:r.s_list=$root.uff.ListString.decode(e,e.uint32());break;case 3:r.d=e.double();break;case 4:r.d_list=$root.uff.ListDouble.decode(e,e.uint32());break;case 5:r.b=e.bool();break;case 6:r.b_list=$root.uff.ListBool.decode(e,e.uint32());break;case 7:r.i=e.int64();break;case 8:r.i_list=$root.uff.ListInt64.decode(e,e.uint32());break;case 9:r.blob=e.bytes();break;case 100:r.ref=e.string();break;case 101:r.dtype=e.int32();break;case 102:r.dtype_list=$root.uff.ListDataType.decode(e,e.uint32());break;case 103:r.dim_orders=$root.uff.DimensionOrders.decode(e,e.uint32());break;case 104:r.dim_orders_list=$root.uff.ListDimensionOrders.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Data;for(e.start();!e.end();){const r=e.tag();switch(r){case"s":t.s=e.string();break;case"s_list":t.s_list=$root.uff.ListString.decodeText(e,!0);break;case"d":t.d=e.float();break;case"d_list":t.d_list=$root.uff.ListDouble.decodeText(e,!0);break;case"b":t.b=e.boolean();break;case"b_list":t.b_list=$root.uff.ListBool.decodeText(e,!0);break;case"i":t.i=e.integer();break;case"i_list":t.i_list=$root.uff.ListInt64.decodeText(e,!0);break;case"blob":t.blob=e.bytes();break;case"ref":t.ref=e.string();break;case"dtype":t.dtype=e.enum($root.uff.DataType);break;case"dtype_list":t.dtype_list=$root.uff.ListDataType.decodeText(e,!0);break;case"dim_orders":t.dim_orders=$root.uff.DimensionOrders.decodeText(e,!0);break;case"dim_orders_list":t.dim_orders_list=$root.uff.ListDimensionOrders.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.DataType={DT_INVALID:0,DT_INT8:65544,DT_INT16:65552,DT_INT32:65568,DT_INT64:65600,DT_FLOAT16:131088,DT_FLOAT32:131104},$root.uff.OrderEnum={OE_ZERO:0,OE_SPECIAL:-1,OE_INCREMENT:2147483647,OE_DECREMENT:-2147483648},$root.uff.DimensionOrders=class{constructor(){this.orders=[]}static decode(e,t){const r=new $root.uff.DimensionOrders,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.orders.push($root.uff.DimensionOrders.OrdersEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.DimensionOrders;for(e.start();!e.end();){const r=e.tag();switch(r){case"orders":t.orders.push($root.uff.DimensionOrders.OrdersEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.DimensionOrders.OrdersEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.DimensionOrders.OrdersEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.int32();break;case 2:r.value=$root.uff.ListInt64.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.DimensionOrders.OrdersEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.enum($root.uff.OrderEnum);break;case"value":t.value=$root.uff.ListInt64.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.DimensionOrders.OrdersEntry.prototype.key=0,$root.uff.DimensionOrders.OrdersEntry.prototype.value=null,$root.uff.ListString=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListString,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val.push(e.string());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListString;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.string()));break;default:e.field(r,t)}}return t}},$root.uff.ListDouble=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDouble,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.doubles(r.val,t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDouble;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.float()));break;default:e.field(r,t)}}return t}},$root.uff.ListBool=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListBool,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.bool()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListBool;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.boolean()));break;default:e.field(r,t)}}return t}},$root.uff.ListInt64=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListInt64,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListInt64;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.integer()));break;default:e.field(r,t)}}return t}},$root.uff.ListDataType=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDataType,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.int32()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDataType;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.enum($root.uff.DataType)));break;default:e.field(r,t)}}return t}},$root.uff.ListDimensionOrders=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDimensionOrders,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val.push($root.uff.DimensionOrders.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDimensionOrders;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":t.val.push($root.uff.DimensionOrders.decodeText(e,!0));break;default:e.field(r,t)}}return t}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff.js new file mode 100644 index 0000000000000000000000000000000000000000..811450868efdd49c58447865a957d9333c4d6b16 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/uff.js @@ -0,0 +1 @@ +var uff=uff||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");uff.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("uff"===s||"pb"===s){const e=t.tags("pb");if(e.size>0&&e.has(1)&&0===e.get(1)&&e.has(2)&&0===e.get(2)&&e.has(3)&&2===e.get(3)&&e.has(4)&&2===e.get(4)&&e.has(5)&&2===e.get(5))return!0}if("pbtxt"===s||e.toLowerCase().endsWith(".uff.txt")){const e=t.tags("pbtxt");if(e.has("version")&&e.has("descriptors")&&e.has("graphs"))return!0}return!1}open(t,e){return e.require("./uff-proto").then((()=>{let s=null;const a=t.identifier;if("pbtxt"===a.split(".").pop().toLowerCase()||a.toLowerCase().endsWith(".uff.txt"))try{uff.proto=protobuf.get("uff").uff;const e=protobuf.TextReader.create(t.text);s=uff.proto.MetaGraph.decodeText(e)}catch(t){throw new uff.Error("File text format is not uff.MetaGraph ("+t.message+") in '"+a+"'.")}else try{uff.proto=protobuf.get("uff").uff;const e=protobuf.Reader.create(t.buffer);s=uff.proto.MetaGraph.decode(e)}catch(t){throw new uff.Error("File format is not uff.MetaGraph ("+t.message+") in '"+a+"'.")}return uff.Metadata.open(e).then((t=>{try{return new uff.Model(t,s)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new uff.Error(s.replace(/\.$/,"")+" in '"+a+"'.")}}))}))}},uff.Model=class{constructor(t,e){this._version=e.version,this._imports=e.descriptors.map((t=>t.id+" v"+t.version.toString())).join(", ");const s=new Map(e.referenced_data.map((t=>[t.key,t.value])));for(const t of e.graphs)for(const e of t.nodes)for(const t of e.fields)"ref"===t.value.type&&s.has(t.value.ref)&&(t.value=s.get(t.value.ref));this._graphs=e.graphs.map((e=>new uff.Graph(t,e)))}get format(){return"UFF"+(this._version?" v"+this._version.toString():"")}get imports(){return this._imports}get graphs(){return this._graphs}},uff.Graph=class{constructor(t,e){this._name=e.id,this._inputs=[],this._outputs=[],this._nodes=[];const s=new Map,a=new Map;for(const t of e.nodes){for(const e of t.inputs)a.set(e,a.has(e)?a.get(e)+1:1),s.set(e,new uff.Argument(e));s.has(t.id)||s.set(t.id,new uff.Argument(t.id))}for(let t=e.nodes.length-1;t>=0;t--){const n=e.nodes[t];if("Const"===n.operation&&0===n.inputs.length&&1===a.get(n.id)){const a={};for(const t of n.fields)a[t.key]=t.value;if(a.dtype&&a.shape&&a.values){const i=new uff.Tensor(a.dtype,a.shape,a.values);s.set(n.id,new uff.Argument(n.id,i.type,i)),e.nodes.splice(t,1)}}if("Input"===n.operation&&0===n.inputs.length){const t={};for(const e of n.fields)t[e.key]=e.value;const e=t.dtype&&t.shape?new uff.TensorType(t.dtype,t.shape):null;s.set(n.id,new uff.Argument(n.id,e,null))}}for(const a of e.nodes)"Input"!==a.operation?"MarkOutput"!==a.operation||1!==a.inputs.length?this._nodes.push(new uff.Node(t,a,s)):this._outputs.push(new uff.Parameter(a.id,[s.get(a.inputs[0])])):this._inputs.push(new uff.Parameter(a.id,[s.get(a.id)]))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},uff.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},uff.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new uff.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},uff.Node=class{constructor(t,e,s){this._name=e.id,this._operation=e.operation,this._metadata=t.type(e.operation),this._attributes=[],this._inputs=[],this._outputs=[];const a=t.type(e.operation);if(e.inputs&&e.inputs.length>0){let t=0;if(a&&a.inputs)for(const n of a.inputs)if(ts.get(t)));t+=a,this._inputs.push(new uff.Parameter(n.name,i))}this._inputs=this._inputs.concat(e.inputs.slice(t).map(((e,a)=>{const n=t+a==0?"input":(t+a).toString();return new uff.Parameter(n,[s.get(e)])})))}this._outputs.push(new uff.Parameter("output",[s.get(e.id)]));for(const s of e.fields)this._attributes.push(new uff.Attribute(t.attribute(this._operation,s.key),s.key,s.value))}get name(){return this._name}get type(){return this._operation}get metadata(){return this._metadata}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},uff.Attribute=class{constructor(t,e,s){switch(this._name=e,s.type){case"s":this._value=s.s,this._type="string";break;case"s_list":this._value=s.s_list,this._type="string[]";break;case"d":this._value=s.d,this._type="float64";break;case"d_list":this._value=s.d_list.val,this._type="float64[]";break;case"i":this._value=s.i,this._type="int64";break;case"i_list":this._value=s.i_list.val,this._type="int64[]";break;case"b":this._value=s.b,this._type="boolean";break;case"b_list":this._value=s.b_list,this._type="boolean[]";break;case"blob":this._value=s.blob;break;case"dtype":this._value=new uff.TensorType(s,null).dataType;break;case"dim_orders_list":this._value=s.dim_orders_list.val;break;default:throw new uff.Error("Unknown attribute '"+e+"'format '"+JSON.stringify(s)+"'.")}}get type(){return this._type}get name(){return this._name}get value(){return this._value}},uff.Tensor=class{constructor(t,e,s){switch(this._type=new uff.TensorType(t,e),s.type){case"blob":this._data=s.blob;break;default:throw new uff.Error("Unknown values format '"+JSON.stringify(s.type)+"'.")}}get kind(){return"Const"}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return null==this._data||this._data.length>8&&40===this._data[0]&&46===this._data[1]&&46===this._data[2]&&46===this._data[3]&&41===this._data[this._data.length-1]&&46===this._data[this._data.length-2]&&46===this._data[this._data.length-3]&&46===this._data[this._data.length-4]?(t.state="Tensor data is empty.",t):(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t)}_decode(t,e){const s=0==t.shape.length?[1]:t.shape,a=s[e],n=[];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"int8":n.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":n.push(t.data.getInt16(t.index)),t.index+=2,t.count++;break;case"int32":n.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":n.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":n.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":n.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++}}else for(let s=0;st.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return 0==t.shape.length?n[0]:n}},uff.TensorType=class{constructor(t,e){if("dtype"!==t.type)throw new uff.Error("Unknown data type format '"+JSON.stringify(t.type)+"'.");switch(t.dtype){case uff.proto.DataType.DT_INT8:this._dataType="int8";break;case uff.proto.DataType.DT_INT16:this._dataType="int16";break;case uff.proto.DataType.DT_INT32:this._dataType="int32";break;case uff.proto.DataType.DT_INT64:this._dataType="int64";break;case uff.proto.DataType.DT_FLOAT16:this._dataType="float16";break;case uff.proto.DataType.DT_FLOAT32:this._dataType="float32";break;default:throw new uff.Error("Unknown data type '"+JSON.stringify(t)+"'.")}this._shape=e?new uff.TensorShape(e):null}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},uff.TensorShape=class{constructor(t){if("i_list"!==t.type)throw new uff.Error("Unknown shape format '"+JSON.stringify(t.type)+"'.");this._dimensions=t.i_list.val}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},uff.Metadata=class{static open(t){return uff.Metadata._metadata?Promise.resolve(uff.Metadata._metadata):t.request(null,"uff-metadata.json","utf-8").then((t=>(uff.Metadata._metadata=new uff.Metadata(t),uff.Metadata._metadata))).catch((()=>(uff.Metadata._metadata=new uff.Metadata(null),uff.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema))}}type(t){return this._map.get(t)}attribute(t,e){const s=t+":"+e;if(!this._attributeCache.has(s)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const s of e.attributes)this._attributeCache.set(t+":"+s.name,s);this._attributeCache.has(s)||this._attributeCache.set(s,null)}return this._attributeCache.get(s)}},uff.Error=class extends Error{constructor(t){super(t),this.name="Error loading UFF model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=uff.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/vendors.6247f3ee105723ca1ab6.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/vendors.6247f3ee105723ca1ab6.js new file mode 100644 index 0000000000000000000000000000000000000000..9b8a946f06cfa6d660677f62f95070fd14cae839 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/vendors.6247f3ee105723ca1ab6.js @@ -0,0 +1 @@ +(globalThis.webpackChunk_visualdl_netron=globalThis.webpackChunk_visualdl_netron||[]).push([[216],{81666:(t,e,n)=>{"use strict";function r(t,e){return te?1:t>=e?0:NaN}n.d(e,{Z:()=>r})},50533:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81666);function i(t){var e;return 1===t.length&&(e=t,t=function(t,n){return(0,r.Z)(e(t),n)}),{left:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)<0?r=a+1:i=a}return r},right:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)>0?i=a:r=a+1}return r}}}},53047:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},34825:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(98193);function i(t,e,n){var i,a,o,u,s=t.length,c=e.length,f=new Array(s*c);for(null==n&&(n=r.$),i=o=0;i{"use strict";function r(t,e){return et?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},34398:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(48347);function i(t,e){var n=(0,r.Z)(t,e);return n?Math.sqrt(n):n}},66804:(t,e,n)=>{"use strict";function r(t,e){var n,r,i,a=t.length,o=-1;if(null==e){for(;++o=n)for(r=i=n;++on&&(r=n),i=n)for(r=i=n;++on&&(r=n),ir})},13932:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},58470:(t,e,n)=>{"use strict";n.d(e,{j2:()=>r.Z,b4:()=>s,Nw:()=>u,ml:()=>o,YF:()=>i.Z,kC:()=>c.Z,$1:()=>f.Z,P3:()=>l.Z,We:()=>h.Z,KX:()=>E,Fp:()=>F.Z,J6:()=>B.Z,C2:()=>S.Z,TS:()=>N.Z,VV:()=>T.Z,X:()=>z.Z,FO:()=>O.Z,VR:()=>j.Z,w6:()=>b.Z,Rp:()=>R.Z,TV:()=>P.Z,Sm:()=>I.Z,o6:()=>C,FA:()=>M.Z,_X:()=>k.Z,G9:()=>Z,ly:()=>D,sd:()=>w,p4:()=>L.Z,CA:()=>U.Z,$R:()=>$.Z});var r=n(81666),i=n(50533),a=(0,i.Z)(r.Z),o=a.right,u=a.left;const s=o;var c=n(34825),f=n(62758),l=n(34398),h=n(66804),d=Array.prototype,p=d.slice,v=d.map,g=n(53047),_=n(13932),b=n(24228),y=Math.sqrt(50),m=Math.sqrt(10),x=Math.sqrt(2);function w(t,e,n){var r,i,a,o,u=-1;if(n=+n,(t=+t)==(e=+e)&&n>0)return[t];if((r=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++u=0?(a>=y?10:a>=m?5:a>=x?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=y?10:a>=m?5:a>=x?2:1)}function D(t,e,n){var r=Math.abs(e-t)/Math.max(0,n),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=y?i*=10:a>=m?i*=5:a>=x&&(i*=2),el;)h.pop(),--d;var p,v=new Array(d+1);for(i=0;i<=d;++i)(p=v[i]=[]).x0=i>0?h[i-1]:f,p.x1=i{"use strict";function r(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++ar&&(r=n)}else for(;++a=n)for(r=n;++ar&&(r=n);return r}n.d(e,{Z:()=>r})},23490:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e){var n,i=t.length,a=i,o=-1,u=0;if(null==e)for(;++o{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(81666);if(826==n.j)var i=n(8895);if(826==n.j)var a=n(80463);function o(t,e){var n,o=t.length,u=-1,s=[];if(null==e)for(;++u{"use strict";function r(t){for(var e,n,r,i=t.length,a=-1,o=0;++a=0;)for(e=(r=t[i]).length;--e>=0;)n[--o]=r[e];return n}n.d(e,{Z:()=>r})},27566:(t,e,n)=>{"use strict";function r(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++an&&(r=n)}else for(;++a=n)for(r=n;++an&&(r=n);return r}n.d(e,{Z:()=>r})},8895:(t,e,n)=>{"use strict";function r(t){return null===t?NaN:+t}n.d(e,{Z:()=>r})},98193:(t,e,n)=>{"use strict";function r(t,e){null==e&&(e=i);for(var n=0,r=t.length-1,a=t[0],o=new Array(r<0?0:r);nr,$:()=>i})},71756:(t,e,n)=>{"use strict";function r(t,e){for(var n=e.length,r=new Array(n);n--;)r[n]=t[e[n]];return r}n.d(e,{Z:()=>r})},80463:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e,n){if(null==n&&(n=r.Z),i=t.length){if((e=+e)<=0||i<2)return+n(t[0],0,t);if(e>=1)return+n(t[i-1],i-1,t);var i,a=(i-1)*e,o=Math.floor(a),u=+n(t[o],o,t);return u+(+n(t[o+1],o+1,t)-u)*(a-o)}}},24228:(t,e,n)=>{"use strict";function r(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=0|Math.max(0,Math.ceil((e-t)/n)),a=new Array(i);++rr})},68691:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81666);function i(t,e){if(n=t.length){var n,i,a=0,o=0,u=t[o];for(null==e&&(e=r.Z);++a{"use strict";function r(t,e,n){for(var r,i,a=(null==n?t.length:n)-(e=null==e?0:+e);a;)i=Math.random()*a--|0,r=t[a+e],t[a+e]=t[i+e],t[i+e]=r;return t}n.d(e,{Z:()=>r})},42507:(t,e,n)=>{"use strict";function r(t,e){var n,r=t.length,i=-1,a=0;if(null==e)for(;++ir})},34416:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(34398);function i(t,e,n){return Math.ceil((n-e)/(3.5*(0,r.Z)(t)*Math.pow(t.length,-1/3)))}},19823:(t,e,n)=>{"use strict";function r(t){return Math.ceil(Math.log(t.length)/Math.LN2)+1}n.d(e,{Z:()=>r})},93966:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(27566);function i(t){if(!(o=t.length))return[];for(var e=-1,n=(0,r.Z)(t,a),i=new Array(n);++e{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e){var n,i,a=t.length,o=0,u=-1,s=0,c=0;if(null==e)for(;++u1)return c/(o-1)}},20446:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(93966);function i(){return(0,r.Z)(arguments)}},71603:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},41989:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},14289:(t,e,n)=>{"use strict";function r(t,e,n){this.target=t,this.type=e,this.selection=n}n.d(e,{Z:()=>r})},78459:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},96199:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},1053:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push({key:n,value:t[n]});return e}n.d(e,{Z:()=>r})},55201:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push(n);return e}n.d(e,{Z:()=>r})},7781:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push(t[n]);return e}n.d(e,{Z:()=>r})},68847:(t,e,n)=>{"use strict";n.d(e,{Il:()=>i,xV:()=>a,J5:()=>o,ZP:()=>m,SU:()=>Z,B8:()=>D,Ss:()=>k,Ym:()=>F});var r=n(40948);function i(){}var a=.7,o=1/a,u="\\s*([+-]?\\d+)\\s*",s="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",c="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",f=/^#([0-9a-f]{3,8})$/,l=new RegExp("^rgb\\("+[u,u,u]+"\\)$"),h=new RegExp("^rgb\\("+[c,c,c]+"\\)$"),d=new RegExp("^rgba\\("+[u,u,u,s]+"\\)$"),p=new RegExp("^rgba\\("+[c,c,c,s]+"\\)$"),v=new RegExp("^hsl\\("+[s,c,c]+"\\)$"),g=new RegExp("^hsla\\("+[s,c,c,s]+"\\)$"),_={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function b(){return this.rgb().formatHex()}function y(){return this.rgb().formatRgb()}function m(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=f.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?x(e):3===n?new k(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?w(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?w(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=l.exec(t))?new k(e[1],e[2],e[3],1):(e=h.exec(t))?new k(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=d.exec(t))?w(e[1],e[2],e[3],e[4]):(e=p.exec(t))?w(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=v.exec(t))?C(e[1],e[2]/100,e[3]/100,1):(e=g.exec(t))?C(e[1],e[2]/100,e[3]/100,e[4]):_.hasOwnProperty(t)?x(_[t]):"transparent"===t?new k(NaN,NaN,NaN,0):null}function x(t){return new k(t>>16&255,t>>8&255,255&t,1)}function w(t,e,n,r){return r<=0&&(t=e=n=NaN),new k(t,e,n,r)}function Z(t){return t instanceof i||(t=m(t)),t?new k((t=t.rgb()).r,t.g,t.b,t.opacity):new k}function D(t,e,n,r){return 1===arguments.length?Z(t):new k(t,e,n,null==r?1:r)}function k(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function E(){return"#"+j(this.r)+j(this.g)+j(this.b)}function A(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function j(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function C(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new B(t,e,n,r)}function M(t){if(t instanceof B)return new B(t.h,t.s,t.l,t.opacity);if(t instanceof i||(t=m(t)),!t)return new B;if(t instanceof B)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,a=Math.min(e,n,r),o=Math.max(e,n,r),u=NaN,s=o-a,c=(o+a)/2;return s?(u=e===o?(n-r)/s+6*(n0&&c<1?0:u,new B(u,s,c,t.opacity)}function F(t,e,n,r){return 1===arguments.length?M(t):new B(t,e,n,null==r?1:r)}function B(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function S(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}(0,r.Z)(i,m,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:b,formatHex:b,formatHsl:function(){return M(this).formatHsl()},formatRgb:y,toString:y}),(0,r.Z)(k,D,(0,r.l)(i,{brighter:function(t){return t=null==t?o:Math.pow(o,t),new k(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?a:Math.pow(a,t),new k(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:E,formatHex:E,formatRgb:A,toString:A})),(0,r.Z)(B,F,(0,r.l)(i,{brighter:function(t){return t=null==t?o:Math.pow(o,t),new B(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?a:Math.pow(a,t),new B(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new k(S(t>=240?t-240:t+120,i,r),S(t,i,r),S(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}))},29607:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r=n(40948),i=n(68847),a=n(10810),o=-.14861,u=1.78277,s=-.29227,c=-.90649,f=1.97294,l=f*c,h=f*u,d=u*s-c*o;function p(t){if(t instanceof g)return new g(t.h,t.s,t.l,t.opacity);t instanceof i.Ss||(t=(0,i.SU)(t));var e=t.r/255,n=t.g/255,r=t.b/255,o=(d*r+l*e-h*n)/(d+l-h),u=r-o,p=(f*(n-o)-s*u)/c,v=Math.sqrt(p*p+u*u)/(f*o*(1-o)),_=v?Math.atan2(p,u)*a.B-120:NaN;return new g(_<0?_+360:_,v,o,t.opacity)}function v(t,e,n,r){return 1===arguments.length?p(t):new g(t,e,n,null==r?1:r)}function g(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}(0,r.Z)(g,v,(0,r.l)(i.Il,{brighter:function(t){return t=null==t?i.J5:Math.pow(i.J5,t),new g(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?i.xV:Math.pow(i.xV,t),new g(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*a.V,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),l=Math.sin(t);return new i.Ss(255*(e+n*(o*r+u*l)),255*(e+n*(s*r+c*l)),255*(e+n*(f*r)),this.opacity)}}))},40948:(t,e,n)=>{"use strict";function r(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function i(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}n.d(e,{Z:()=>r,l:()=>i})},75302:(t,e,n)=>{"use strict";if(n.d(e,{$_:()=>r.ZP,B8:()=>r.B8,Ym:()=>r.Ym,Nn:()=>i.ZP,Uc:()=>i.Uc,tW:()=>i.tW,MA:()=>i.MA,K:()=>a.Z}),826==n.j)var r=n(68847);if(826==n.j)var i=n(20966);if(826==n.j)var a=n(29607)},20966:(t,e,n)=>{"use strict";n.d(e,{MA:()=>h,ZP:()=>d,tW:()=>m,Uc:()=>x});var r=n(40948),i=n(68847),a=n(10810),o=.96422,u=.82521,s=4/29,c=6/29,f=3*c*c;function l(t){if(t instanceof p)return new p(t.l,t.a,t.b,t.opacity);if(t instanceof w)return Z(t);t instanceof i.Ss||(t=(0,i.SU)(t));var e,n,r=b(t.r),a=b(t.g),s=b(t.b),c=v((.2225045*r+.7168786*a+.0606169*s)/1);return r===a&&a===s?e=n=c:(e=v((.4360747*r+.3850649*a+.1430804*s)/o),n=v((.0139322*r+.0971045*a+.7141733*s)/u)),new p(116*c-16,500*(e-c),200*(c-n),t.opacity)}function h(t,e){return new p(t,0,0,null==e?1:e)}function d(t,e,n,r){return 1===arguments.length?l(t):new p(t,e,n,null==r?1:r)}function p(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function v(t){return t>.008856451679035631?Math.pow(t,1/3):t/f+s}function g(t){return t>c?t*t*t:f*(t-s)}function _(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function b(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function y(t){if(t instanceof w)return new w(t.h,t.c,t.l,t.opacity);if(t instanceof p||(t=l(t)),0===t.a&&0===t.b)return new w(NaN,0{"use strict";n.d(e,{V:()=>r,B:()=>i});var r=Math.PI/180,i=180/Math.PI},66847:(t,e,n)=>{"use strict";function r(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++er})},45163:(t,e,n)=>{"use strict";function r(t,e){return t-e}n.d(e,{Z:()=>r})},5109:(t,e,n)=>{"use strict";function r(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(u>=a&&(s-=t.data[u-a+o*r]),e.data[u-n+o*r]=s/Math.min(u+1,r-1+a-u,a))}function i(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(u>=a&&(s-=t.data[o+(u-a)*r]),e.data[o+(u-n)*r]=s/Math.min(u+1,i-1+a-u,a))}n.d(e,{_:()=>r,$:()=>i})},82261:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},97158:(t,e,n)=>{"use strict";function r(t,e){for(var n,r=-1,a=e.length;++rr!=p>r&&n<(d-f)*(r-l)/(p-l)+f&&(i=-i)}return i}function a(t,e,n){var r,i,a,o;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(i=t[r=+(t[0]===e[0])],a=n[r],o=e[r],i<=a&&a<=o||o<=a&&a<=i)}n.d(e,{Z:()=>r})},42451:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},65264:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r={value:function(){}};function i(){for(var t,e=0,n=arguments.length,r={};e=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function u(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;a{"use strict";if(n.d(e,{W:()=>r.Z}),826==n.j)var r=n(65264)},44223:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},44319:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>g}),826==n.j)var r=n(65264);if(826==n.j)var i=n(78011);if(826==n.j)var a=n(42637);if(826==n.j)var o=n(23475);if(826==n.j)var u=n(13171);if(826==n.j)var s=n(61062);if(826==n.j)var c=n(42254);if(826==n.j)var f=n(44223);if(826==n.j)var l=n(63932);function h(){return!i.B.ctrlKey&&!i.B.button}function d(){return this.parentNode}function p(t){return null==t?{x:i.B.x,y:i.B.y}:t}function v(){return navigator.maxTouchPoints||"ontouchstart"in this}function g(){var t,e,n,g,_=h,b=d,y=p,m=v,x={},w=(0,r.Z)("start","drag","end"),Z=0,D=0;function k(t){t.on("mousedown.drag",E).filter(m).on("touchstart.drag",C).on("touchmove.drag",M).on("touchend.drag touchcancel.drag",F).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function E(){if(!g&&_.apply(this,arguments)){var r=B("mouse",b.apply(this,arguments),a.Z,this,arguments);r&&((0,o.Z)(i.B.view).on("mousemove.drag",A,!0).on("mouseup.drag",j,!0),(0,s.Z)(i.B.view),(0,c.r)(),n=!1,t=i.B.clientX,e=i.B.clientY,r("start"))}}function A(){if((0,c.Z)(),!n){var r=i.B.clientX-t,a=i.B.clientY-e;n=r*r+a*a>D}x.mouse("drag")}function j(){(0,o.Z)(i.B.view).on("mousemove.drag mouseup.drag",null),(0,s.D)(i.B.view,n),(0,c.Z)(),x.mouse("end")}function C(){if(_.apply(this,arguments)){var t,e,n=i.B.changedTouches,r=b.apply(this,arguments),a=n.length;for(t=0;t{"use strict";function r(t,e,n,r,i,a,o,u,s,c){this.target=t,this.type=e,this.subject=n,this.identifier=r,this.active=i,this.x=a,this.y=o,this.dx=u,this.dy=s,this._=c}n.d(e,{Z:()=>r}),r.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t}},95520:(t,e,n)=>{"use strict";if(n.d(e,{oh:()=>r.Z,Kn:()=>i.Z,eF:()=>i.D}),826==n.j)var r=n(44319);if(826==n.j)var i=n(61062)},61062:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,D:()=>o}),826==n.j)var r=n(23475);if(826==n.j)var i=n(42254);function a(t){var e=t.document.documentElement,n=(0,r.Z)(t).on("dragstart.drag",i.Z,!0);"onselectstart"in e?n.on("selectstart.drag",i.Z,!0):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none")}function o(t,e){var n=t.document.documentElement,a=(0,r.Z)(t).on("dragstart.drag",null);e&&(a.on("click.drag",i.Z,!0),setTimeout((function(){a.on("click.drag",null)}),0)),"onselectstart"in n?a.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}},42254:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},65986:(t,e,n)=>{"use strict";function r(t){for(var e in t){var n,r,a=t[e].trim();if(a)if("true"===a)a=!0;else if("false"===a)a=!1;else if("NaN"===a)a=NaN;else if(isNaN(n=+a)){if(!(r=a.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;i&&r[4]&&!r[7]&&(a=a.replace(/-/g,"/").replace(/T/," ")),a=new Date(a)}else a=n;else a=null;t[e]=a}return t}n.d(e,{Z:()=>r});var i=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours()},55370:(t,e,n)=>{"use strict";n.d(e,{ue:()=>i,Bj:()=>a,Sf:()=>o,S:()=>u,Jb:()=>s,fh:()=>c,eX:()=>f});var r=(0,n(13428).Z)(","),i=r.parse,a=r.parseRows,o=r.format,u=r.formatBody,s=r.formatRows,c=r.formatRow,f=r.formatValue},13428:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r={},i={};function a(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function o(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r)})),n}function u(t,e){var n=t+"",r=n.length;return r=u?f=!0:10===(a=t.charCodeAt(s++))?l=!0:13===a&&(l=!0,10===t.charCodeAt(s)&&++s),t.slice(o+1,e-1).replace(/""/g,'"')}for(;s9999?"+"+u(r,6):u(r,4))+"-"+u(n.getUTCMonth()+1,2)+"-"+u(n.getUTCDate(),2)+(s?"T"+u(i,2)+":"+u(a,2)+":"+u(o,2)+"."+u(s,3)+"Z":o?"T"+u(i,2)+":"+u(a,2)+":"+u(o,2)+"Z":a||i?"T"+u(i,2)+":"+u(a,2)+"Z":"")):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t;var n,r,i,a,o,s}return{parse:function(t,e){var n,r,i=s(t,(function(t,i){if(n)return n(t,i-1);r=t,n=e?function(t,e){var n=a(t);return function(r,i){return e(n(r),i,t)}}(t,e):a(t)}));return i.columns=r||[],i},parseRows:s,format:function(e,n){return null==n&&(n=o(e)),[n.map(l).join(t)].concat(c(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=o(t)),c(t,e).join("\n")},formatRows:function(t){return t.map(f).join("\n")},formatRow:f,formatValue:l}}},83611:(t,e,n)=>{"use strict";if(n.d(e,{yv:()=>r.Z,ue:()=>i.ue,Bj:()=>i.Bj,Sf:()=>i.Sf,S:()=>i.S,Jb:()=>i.Jb,fh:()=>i.fh,eX:()=>i.eX,tJ:()=>a.tJ,E0:()=>a.E0,vP:()=>a.vP,uH:()=>a.uH,n5:()=>a.n5,Hf:()=>a.Hf,sS:()=>a.sS,rA:()=>o.Z}),826==n.j)var r=n(13428);if(826==n.j)var i=n(55370);if(826==n.j)var a=n(92044);if(826==n.j)var o=n(65986)},92044:(t,e,n)=>{"use strict";n.d(e,{tJ:()=>i,E0:()=>a,vP:()=>o,uH:()=>u,n5:()=>s,Hf:()=>c,sS:()=>f});var r=(0,n(13428).Z)("\t"),i=r.parse,a=r.parseRows,o=r.format,u=r.formatBody,s=r.formatRows,c=r.formatRow,f=r.formatValue},31704:(t,e,n)=>{"use strict";n.d(e,{G2:()=>i,CG:()=>a,XL:()=>o});var r=1.70158,i=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(r),a=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(r),o=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(r)},91105:(t,e,n)=>{"use strict";n.d(e,{h9:()=>h,gJ:()=>d,yD:()=>p});var r=826==n.j?6/11:null,i=826==n.j?8/11:null,a=826==n.j?3/4:null,o=826==n.j?9/11:null,u=826==n.j?10/11:null,s=826==n.j?15/16:null,c=826==n.j?21/22:null,f=826==n.j?63/64:null,l=7.5625;function h(t){return 1-d(1-t)}function d(t){return(t=+t)<.36363636363636365?l*t*t:t{"use strict";function r(t){return 1-Math.sqrt(1-t*t)}function i(t){return Math.sqrt(1- --t*t)}function a(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}n.d(e,{rf:()=>r,v2:()=>i,WE:()=>a})},2432:(t,e,n)=>{"use strict";function r(t){return t*t*t}function i(t){return--t*t*t+1}function a(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}n.d(e,{yD:()=>r,_e:()=>i,tw:()=>a})},70447:(t,e,n)=>{"use strict";n.d(e,{x8:()=>a,_D:()=>o,NL:()=>u});var r=n(11639),i=2*Math.PI,a=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return e*(0,r.N)(- --t)*Math.sin((a-t)/n)}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3),o=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return 1-e*(0,r.N)(t=+t)*Math.sin((t+a)/n)}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3),u=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return((t=2*t-1)<0?e*(0,r.N)(-t)*Math.sin((a-t)/n):2-e*(0,r.N)(t)*Math.sin((a+t)/n))/2}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3)},31081:(t,e,n)=>{"use strict";if(n.d(e,{oP:()=>i,M4:()=>a,Oo:()=>o}),826==n.j)var r=n(11639);function i(t){return(0,r.N)(1-+t)}function a(t){return 1-(0,r.N)(t)}function o(t){return((t*=2)<=1?(0,r.N)(1-t):2-(0,r.N)(t-1))/2}},13756:(t,e,n)=>{"use strict";if(n.d(e,{Ny:()=>r.G,uw:()=>i.U2,V_:()=>i.Kl,mm:()=>i.u4,Tu:()=>i.U2,LU:()=>a.tw,HU:()=>a.yD,oS:()=>a._e,cC:()=>a.tw,m2:()=>o.SE,Tf:()=>o.RY,Ct:()=>o.fW,z5:()=>o.SE,Tl:()=>u.xU,tl:()=>u.yx,p4:()=>u.Dh,v:()=>u.xU,Ll:()=>s.Oo,uY:()=>s.oP,mf:()=>s.M4,nm:()=>s.Oo,Xe:()=>c.WE,kO:()=>c.rf,te:()=>c.v2,sq:()=>c.WE,sf:()=>f.gJ,RK:()=>f.h9,qj:()=>f.gJ,hE:()=>f.yD,bW:()=>l.XL,gp:()=>l.G2,ZN:()=>l.CG,gI:()=>l.XL,Az:()=>h._D,aM:()=>h.x8,Px:()=>h._D,H1:()=>h.NL}),826==n.j)var r=n(72738);if(826==n.j)var i=n(91502);if(826==n.j)var a=n(2432);if(826==n.j)var o=n(106);if(826==n.j)var u=n(98614);if(826==n.j)var s=n(31081);if(826==n.j)var c=n(60605);if(826==n.j)var f=n(91105);if(826==n.j)var l=n(31704);if(826==n.j)var h=n(70447)},72738:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{G:()=>r})},11639:(t,e,n)=>{"use strict";function r(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}n.d(e,{N:()=>r})},106:(t,e,n)=>{"use strict";n.d(e,{RY:()=>r,fW:()=>i,SE:()=>a});var r=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),i=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),a=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3)},91502:(t,e,n)=>{"use strict";function r(t){return t*t}function i(t){return t*(2-t)}function a(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}n.d(e,{Kl:()=>r,u4:()=>i,U2:()=>a})},98614:(t,e,n)=>{"use strict";n.d(e,{yx:()=>a,Dh:()=>o,xU:()=>u});var r=Math.PI,i=r/2;function a(t){return 1==+t?1:1-Math.cos(t*i)}function o(t){return Math.sin(t*i)}function u(t){return(1-Math.cos(r*t))/2}},55710:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},42472:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},8557:(t,e,n)=>{"use strict";if(n.d(e,{ZP:()=>s,gy:()=>c,pv:()=>f}),826==n.j)var r=n(13428);var i=n(55370),a=n(92044),o=n(92935);function u(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),(0,o.Z)(e,n).then((function(e){return t(e,r)}))}}function s(t,e,n,i){3===arguments.length&&"function"==typeof n&&(i=n,n=void 0);var a=(0,r.Z)(t);return(0,o.Z)(e,n).then((function(t){return a.parse(t,i)}))}var c=u(i.ue),f=u(a.tJ)},43973:(t,e,n)=>{"use strict";function r(t,e){return new Promise((function(n,r){var i=new Image;for(var a in e)i[a]=e[a];i.onerror=r,i.onload=function(){n(i)},i.src=t}))}n.d(e,{Z:()=>r})},14413:(t,e,n)=>{"use strict";if(n.d(e,{Ik:()=>r.Z,f3:()=>i.Z,Ds:()=>a.ZP,gy:()=>a.gy,pv:()=>a.pv,BH:()=>o.Z,AV:()=>u.Z,fL:()=>s.Z,Ls:()=>c.ZP,dy:()=>c.dy,YP:()=>c.YP}),826==n.j)var r=n(55710);if(826==n.j)var i=n(42472);if(826==n.j)var a=n(8557);if(826==n.j)var o=n(43973);if(826==n.j)var u=n(27969);if(826==n.j)var s=n(92935);if(826==n.j)var c=n(5110)},27969:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},92935:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},5110:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,dy:()=>o,YP:()=>u});var r=n(92935);function i(t){return function(e,n){return(0,r.Z)(e,n).then((function(e){return(new DOMParser).parseFromString(e,t)}))}}const a=i("application/xml");var o=i("text/html"),u=i("image/svg+xml")},71233:(t,e,n)=>{"use strict";function r(t,e){var n;function r(){var r,i,a=n.length,o=0,u=0;for(r=0;rr})},47226:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(84442);if(826==n.j)var i=n(43266);if(826==n.j)var a=n(94673);function o(t){return t.x+t.vx}function u(t){return t.y+t.vy}function s(t){var e,n,s=1,c=1;function f(){for(var t,r,f,h,d,p,v,g=e.length,_=0;_h+c||rd+c||af.index){var l=h-o.x-o.vx,g=d-o.y-o.vy,_=l*l+g*g;_t.r&&(t.r=t[e].r)}function h(){if(e){var r,i,a=e.length;for(n=new Array(a),r=0;r{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},43266:(t,e,n)=>{"use strict";function r(){return 1e-6*(Math.random()-.5)}n.d(e,{Z:()=>r})},5724:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t,e,n){var i,a,o,u=(0,r.Z)(.1);function s(t){for(var r=0,u=i.length;r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t){var e,n,i,a=(0,r.Z)(.1);function o(t){for(var r,a=0,o=e.length;a{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t){var e,n,i,a=(0,r.Z)(.1);function o(t){for(var r,a=0,o=e.length;a{"use strict";function r(){return new i}function i(){this.reset()}n.d(e,{Z:()=>r}),i.prototype={constructor:i,reset:function(){this.s=this.t=0},add:function(t){o(a,t,this.t),o(this,a.s,this.s),this.s?this.t+=a.t:this.s=a.t},valueOf:function(){return this.s}};var a=new i;function o(t,e,n){var r=t.s=e+n,i=r-e,a=r-i;t.t=e-a+(n-i)}},86593:(t,e,n)=>{"use strict";n.d(e,{L9:()=>h,gL:()=>p,ZP:()=>y});var r=n(6236),i=n(66573),a=n(48340);if(826==n.j)var o=n(60600);var u,s,c,f,l,h=(0,r.Z)(),d=(0,r.Z)(),p={point:a.Z,lineStart:a.Z,lineEnd:a.Z,polygonStart:function(){h.reset(),p.lineStart=v,p.lineEnd=g},polygonEnd:function(){var t=+h;d.add(t<0?i.BZ+t:t),this.lineStart=this.lineEnd=this.point=a.Z},sphere:function(){d.add(i.BZ)}};function v(){p.point=_}function g(){b(u,s)}function _(t,e){p.point=b,u=t,s=e,t*=i.uR,e*=i.uR,c=t,f=(0,i.mC)(e=e/2+i.pu),l=(0,i.O$)(e)}function b(t,e){t*=i.uR,e=(e*=i.uR)/2+i.pu;var n=t-c,r=n>=0?1:-1,a=r*n,o=(0,i.mC)(e),u=(0,i.O$)(e),s=l*u,d=f*o+s*(0,i.mC)(a),p=s*r*(0,i.O$)(a);h.add((0,i.fv)(p,d)),c=t,f=o,l=u}function y(t){return d.reset(),(0,o.Z)(t,p),2*d}},70456:(t,e,n)=>{"use strict";n.d(e,{Z:()=>M});var r=n(6236),i=n(86593),a=n(67776),o=n(66573);if(826==n.j)var u=n(60600);var s,c,f,l,h,d,p,v,g,_,b=(0,r.Z)(),y={point:m,lineStart:w,lineEnd:Z,polygonStart:function(){y.point=D,y.lineStart=k,y.lineEnd=E,b.reset(),i.gL.polygonStart()},polygonEnd:function(){i.gL.polygonEnd(),y.point=m,y.lineStart=w,y.lineEnd=Z,i.L9<0?(s=-(f=180),c=-(l=90)):b>o.Ho?l=90:b<-o.Ho&&(c=-90),_[0]=s,_[1]=f},sphere:function(){s=-(f=180),c=-(l=90)}};function m(t,e){g.push(_=[s=t,f=t]),el&&(l=e)}function x(t,e){var n=(0,a.Og)([t*o.uR,e*o.uR]);if(v){var r=(0,a.T5)(v,n),i=[r[1],-r[0],0],u=(0,a.T5)(i,r);(0,a.iJ)(u),u=(0,a.Y1)(u);var d,p=t-h,b=p>0?1:-1,y=u[0]*o.RW*b,m=(0,o.Wn)(p)>180;m^(b*hl&&(l=d):m^(b*h<(y=(y+360)%360-180)&&yl&&(l=e)),m?tA(s,f)&&(f=t):A(t,f)>A(s,f)&&(s=t):f>=s?(tf&&(f=t)):t>h?A(s,t)>A(s,f)&&(f=t):A(t,f)>A(s,f)&&(s=t)}else g.push(_=[s=t,f=t]);el&&(l=e),v=n,h=t}function w(){y.point=x}function Z(){_[0]=s,_[1]=f,y.point=m,v=null}function D(t,e){if(v){var n=t-h;b.add((0,o.Wn)(n)>180?n+(n>0?360:-360):n)}else d=t,p=e;i.gL.point(t,e),x(t,e)}function k(){i.gL.lineStart()}function E(){D(d,p),i.gL.lineEnd(),(0,o.Wn)(b)>o.Ho&&(s=-(f=180)),_[0]=s,_[1]=f,v=null}function A(t,e){return(e-=t)<0?e+360:e}function j(t,e){return t[0]-e[0]}function C(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eA(r[0],r[1])&&(r[1]=i[1]),A(i[0],r[1])>A(r[0],r[1])&&(r[0]=i[0])):a.push(r=i);for(o=-1/0,e=0,r=a[n=a.length-1];e<=n;r=i,++e)i=a[e],(h=A(r[1],i[0]))>o&&(o=h,s=i[0],f=r[1])}return g=_=null,s===1/0||c===1/0?[[NaN,NaN],[NaN,NaN]]:[[s,c],[f,l]]}},67776:(t,e,n)=>{"use strict";if(n.d(e,{Y1:()=>i,Og:()=>a,j9:()=>o,T5:()=>u,s0:()=>s,T:()=>c,iJ:()=>f}),826==n.j)var r=n(66573);function i(t){return[(0,r.fv)(t[1],t[0]),(0,r.ZR)(t[2])]}function a(t){var e=t[0],n=t[1],i=(0,r.mC)(n);return[i*(0,r.mC)(e),i*(0,r.O$)(e),(0,r.O$)(n)]}function o(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function u(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function s(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function c(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function f(t){var e=(0,r._b)(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}},83922:(t,e,n)=>{"use strict";n.d(e,{Z:()=>S});var r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y=n(66573),m=n(48340);if(826==n.j)var x=n(60600);var w={sphere:m.Z,point:Z,lineStart:k,lineEnd:j,polygonStart:function(){w.lineStart=C,w.lineEnd=M},polygonEnd:function(){w.lineStart=k,w.lineEnd=j}};function Z(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e);D(n*(0,y.mC)(t),n*(0,y.O$)(t),(0,y.O$)(e))}function D(t,e,n){++r,a+=(t-a)/r,o+=(e-o)/r,u+=(n-u)/r}function k(){w.point=E}function E(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e);g=n*(0,y.mC)(t),_=n*(0,y.O$)(t),b=(0,y.O$)(e),w.point=A,D(g,_,b)}function A(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e),r=n*(0,y.mC)(t),a=n*(0,y.O$)(t),o=(0,y.O$)(e),u=(0,y.fv)((0,y._b)((u=_*o-b*a)*u+(u=b*r-g*o)*u+(u=g*a-_*r)*u),g*r+_*a+b*o);i+=u,s+=u*(g+(g=r)),c+=u*(_+(_=a)),f+=u*(b+(b=o)),D(g,_,b)}function j(){w.point=Z}function C(){w.point=F}function M(){B(p,v),w.point=Z}function F(t,e){p=t,v=e,t*=y.uR,e*=y.uR,w.point=B;var n=(0,y.mC)(e);g=n*(0,y.mC)(t),_=n*(0,y.O$)(t),b=(0,y.O$)(e),D(g,_,b)}function B(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e),r=n*(0,y.mC)(t),a=n*(0,y.O$)(t),o=(0,y.O$)(e),u=_*o-b*a,p=b*r-g*o,v=g*a-_*r,m=(0,y._b)(u*u+p*p+v*v),x=(0,y.ZR)(m),w=m&&-x/m;l+=w*u,h+=w*p,d+=w*v,i+=x,s+=x*(g+(g=r)),c+=x*(_+(_=a)),f+=x*(b+(b=o)),D(g,_,b)}function S(t){r=i=a=o=u=s=c=f=l=h=d=0,(0,x.Z)(t,w);var e=l,n=h,p=d,v=e*e+n*n+p*p;return v{"use strict";if(n.d(e,{m:()=>u,Z:()=>c}),826==n.j)var r=n(67776);if(826==n.j)var i=n(90303);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(85295);function u(t,e,n,i,o,u){if(n){var c=(0,a.mC)(e),f=(0,a.O$)(e),l=i*n;null==o?(o=e+i*a.BZ,u=e-l/2):(o=s(c,o),u=s(c,u),(i>0?ou)&&(o+=i*a.BZ));for(var h,d=o;i>0?d>u:d{"use strict";n.d(e,{Z:()=>a});var r=n(38147),i=n(66573);const a=(0,r.Z)((function(){return!0}),(function(t){var e,n=NaN,r=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,u){var s=o>0?i.pi:-i.pi,c=(0,i.Wn)(o-n);(0,i.Wn)(c-i.pi)0?i.ou:-i.ou),t.point(a,r),t.lineEnd(),t.lineStart(),t.point(s,r),t.point(o,r),e=0):a!==s&&c>=i.pi&&((0,i.Wn)(n-a)i.Ho?(0,i.z4)(((0,i.O$)(e)*(o=(0,i.mC)(r))*(0,i.O$)(n)-(0,i.O$)(r)*(a=(0,i.mC)(e))*(0,i.O$)(t))/(a*o*u)):(e+r)/2}(n,r,o,u),t.point(a,r),t.lineEnd(),t.lineStart(),t.point(s,r),e=0),t.point(n=o,r=u),a=s},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var a;if(null==t)a=n*i.ou,r.point(-i.pi,a),r.point(0,a),r.point(i.pi,a),r.point(i.pi,0),r.point(i.pi,-a),r.point(0,-a),r.point(-i.pi,-a),r.point(-i.pi,0),r.point(-i.pi,a);else if((0,i.Wn)(t[0]-e[0])>i.Ho){var o=t[0]{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(48340);function i(){var t,e=[];return{point:function(e,n,r){t.push([e,n,r])},lineStart:function(){e.push(t=[])},lineEnd:r.Z,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}},24883:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(67776);if(826==n.j)var i=n(62332);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(12447);if(826==n.j)var u=n(38147);function s(t){var e=(0,a.mC)(t),n=6*a.uR,s=e>0,c=(0,a.Wn)(e)>a.Ho;function f(t,n){return(0,a.mC)(t)*(0,a.mC)(n)>e}function l(t,n,i){var o=(0,r.Og)(t),u=(0,r.Og)(n),s=[1,0,0],c=(0,r.T5)(o,u),f=(0,r.j9)(c,c),l=c[0],h=f-l*l;if(!h)return!i&&t;var d=e*f/h,p=-e*l/h,v=(0,r.T5)(s,c),g=(0,r.T)(s,d),_=(0,r.T)(c,p);(0,r.s0)(g,_);var b=v,y=(0,r.j9)(g,b),m=(0,r.j9)(b,b),x=y*y-m*((0,r.j9)(g,g)-1);if(!(x<0)){var w=(0,a._b)(x),Z=(0,r.T)(b,(-y-w)/m);if((0,r.s0)(Z,g),Z=(0,r.Y1)(Z),!i)return Z;var D,k=t[0],E=n[0],A=t[1],j=n[1];E0^Z[1]<((0,a.Wn)(Z[0]-k)a.pi^(k<=Z[0]&&Z[0]<=E)){var F=(0,r.T)(b,(-y+w)/m);return(0,r.s0)(F,g),[Z,(0,r.Y1)(F)]}}}function h(e,n){var r=s?t:a.pi-t,i=0;return e<-r?i|=1:e>r&&(i|=2),n<-r?i|=4:n>r&&(i|=8),i}return(0,u.Z)(f,(function(t){var e,n,r,i,u;return{lineStart:function(){i=r=!1,u=1},point:function(d,p){var v,g=[d,p],_=f(d,p),b=s?_?0:h(d,p):_?h(d+(d<0?a.pi:-a.pi),p):0;if(!e&&(i=r=_)&&t.lineStart(),_!==r&&(!(v=l(e,g))||(0,o.Z)(e,v)||(0,o.Z)(g,v))&&(g[2]=1),_!==r)u=0,_?(t.lineStart(),v=l(g,e),t.point(v[0],v[1])):(v=l(e,g),t.point(v[0],v[1],2),t.lineEnd()),e=v;else if(c&&e&&s^_){var y;b&n||!(y=l(g,e,!0))||(u=0,s?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!_||e&&(0,o.Z)(e,g)||t.point(g[0],g[1]),e=g,r=_,n=b},lineEnd:function(){r&&t.lineEnd(),e=null},clean:function(){return u|(i&&r)<<1}}}),(function(e,r,a,o){(0,i.m)(o,t,n,a,e,r)}),s?[0,-t]:[-a.pi,t-a.pi])}},37023:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(94892);function i(){var t,e,n,i=0,a=0,o=960,u=500;return n={stream:function(n){return t&&e===n?t:t=(0,r.Z)(i,a,o,u)(e=n)},extent:function(r){return arguments.length?(i=+r[0][0],a=+r[0][1],o=+r[1][0],u=+r[1][1],t=e=null,n):[[i,a],[o,u]]}}}},38147:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(92590);if(826==n.j)var i=n(40559);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(3378);var u=n(58470);function s(t,e,n,a){return function(s){var l,h,d,p=e(s),v=(0,r.Z)(),g=e(v),_=!1,b={point:y,lineStart:x,lineEnd:w,polygonStart:function(){b.point=Z,b.lineStart=D,b.lineEnd=k,h=[],l=[]},polygonEnd:function(){b.point=y,b.lineStart=x,b.lineEnd=w,h=(0,u.TS)(h);var t=(0,o.Z)(l,a);h.length?(_||(s.polygonStart(),_=!0),(0,i.Z)(h,f,t,n,s)):t&&(_||(s.polygonStart(),_=!0),s.lineStart(),n(null,null,1,s),s.lineEnd()),_&&(s.polygonEnd(),_=!1),h=l=null},sphere:function(){s.polygonStart(),s.lineStart(),n(null,null,1,s),s.lineEnd(),s.polygonEnd()}};function y(e,n){t(e,n)&&s.point(e,n)}function m(t,e){p.point(t,e)}function x(){b.point=m,p.lineStart()}function w(){b.point=y,p.lineEnd()}function Z(t,e){d.push([t,e]),g.point(t,e)}function D(){g.lineStart(),d=[]}function k(){Z(d[0][0],d[0][1]),g.lineEnd();var t,e,n,r,i=g.clean(),a=v.result(),o=a.length;if(d.pop(),l.push(d),d=null,o)if(1&i){if((e=(n=a[0]).length-1)>0){for(_||(s.polygonStart(),_=!0),s.lineStart(),t=0;t1&&2&i&&a.push(a.pop().concat(a.shift())),h.push(a.filter(c))}return b}}function c(t){return t.length>1}function f(t,e){return((t=t.x)[0]<0?t[1]-a.ou-a.Ho:a.ou-t[1])-((e=e.x)[0]<0?e[1]-a.ou-a.Ho:a.ou-e[1])}},96610:(t,e,n)=>{"use strict";function r(t,e,n,r,i,a){var o,u=t[0],s=t[1],c=0,f=1,l=e[0]-u,h=e[1]-s;if(o=n-u,l||!(o>0)){if(o/=l,l<0){if(o0){if(o>f)return;o>c&&(c=o)}if(o=i-u,l||!(o<0)){if(o/=l,l<0){if(o>f)return;o>c&&(c=o)}else if(l>0){if(o0)){if(o/=h,h<0){if(o0){if(o>f)return;o>c&&(c=o)}if(o=a-s,h||!(o<0)){if(o/=h,h<0){if(o>f)return;o>c&&(c=o)}else if(h>0){if(o0&&(t[0]=u+c*l,t[1]=s+c*h),f<1&&(e[0]=u+f*l,e[1]=s+f*h),!0}}}}}n.d(e,{Z:()=>r})},94892:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>f}),826==n.j)var r=n(66573);if(826==n.j)var i=n(92590);if(826==n.j)var a=n(96610);if(826==n.j)var o=n(40559);var u=n(58470),s=1e9,c=-s;function f(t,e,n,f){function l(r,i){return t<=r&&r<=n&&e<=i&&i<=f}function h(r,i,a,o){var u=0,s=0;if(null==r||(u=d(r,a))!==(s=d(i,a))||v(r,i)<0^a>0)do{o.point(0===u||3===u?t:n,u>1?f:e)}while((u=(u+a+4)%4)!==s);else o.point(i[0],i[1])}function d(i,a){return(0,r.Wn)(i[0]-t)0?0:3:(0,r.Wn)(i[0]-n)0?2:1:(0,r.Wn)(i[1]-e)0?1:0:a>0?3:2}function p(t,e){return v(t.x,e.x)}function v(t,e){var n=d(t,1),r=d(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(r){var d,v,g,_,b,y,m,x,w,Z,D,k=r,E=(0,i.Z)(),A={point:j,lineStart:function(){A.point=C,v&&v.push(g=[]),Z=!0,w=!1,m=x=NaN},lineEnd:function(){d&&(C(_,b),y&&w&&E.rejoin(),d.push(E.result())),A.point=j,w&&k.lineEnd()},polygonStart:function(){k=E,d=[],v=[],D=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,r=v.length;nf&&(l-i)*(f-a)>(h-a)*(t-i)&&++e:h<=f&&(l-i)*(f-a)<(h-a)*(t-i)&&--e;return e}(),n=D&&e,i=(d=(0,u.TS)(d)).length;(n||i)&&(r.polygonStart(),n&&(r.lineStart(),h(null,null,1,r),r.lineEnd()),i&&(0,o.Z)(d,p,e,h,r),r.polygonEnd()),k=r,d=v=g=null}};function j(t,e){l(t,e)&&k.point(t,e)}function C(r,i){var o=l(r,i);if(v&&g.push([r,i]),Z)_=r,b=i,y=o,Z=!1,o&&(k.lineStart(),k.point(r,i));else if(o&&w)k.point(r,i);else{var u=[m=Math.max(c,Math.min(s,m)),x=Math.max(c,Math.min(s,x))],h=[r=Math.max(c,Math.min(s,r)),i=Math.max(c,Math.min(s,i))];(0,a.Z)(u,h,t,e,n,f)?(w||(k.lineStart(),k.point(u[0],u[1])),k.point(h[0],h[1]),o||k.lineEnd(),D=!1):o&&(k.lineStart(),k.point(r,i),D=!1)}m=r,x=i,w=o}return A}}},40559:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(12447);if(826==n.j)var i=n(66573);function a(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function o(t,e,n,o,s){var c,f,l=[],h=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,o=t[0],u=t[e];if((0,r.Z)(o,u)){if(!o[2]&&!u[2]){for(s.lineStart(),c=0;c=0;--c)s.point((p=d[c])[0],p[1]);else o(g.x,g.p.x,-1,s);g=g.p}d=(g=g.o).z,_=!_}while(!g.v);s.lineEnd()}}}function u(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r{"use strict";function r(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return(n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}n.d(e,{Z:()=>r})},90303:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},37236:(t,e,n)=>{"use strict";n.d(e,{Z:()=>p});var r=n(3378),i=n(65055),a=n(66573),o={Feature:function(t,e){return s(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r0&&(o=(0,i.Z)(t[u],t[u-1]))>0&&n<=o&&r<=o&&(n+r-o)*(1-Math.pow((n-r)/o,2)){"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(74108);var i=[null,null],a={type:"LineString",coordinates:i};function o(t,e){return i[0]=t,i[1]=e,(0,r.Z)(a)}},51418:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u,e:()=>s});var r=n(58470);if(826==n.j)var i=n(66573);function a(t,e,n){var a=(0,r.w6)(t,e-i.Ho,n).concat(e);return function(t){return a.map((function(e){return[t,e]}))}}function o(t,e,n){var a=(0,r.w6)(t,e-i.Ho,n).concat(e);return function(t){return a.map((function(e){return[e,t]}))}}function u(){var t,e,n,u,s,c,f,l,h,d,p,v,g=10,_=g,b=90,y=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:w()}}function w(){return(0,r.w6)((0,i.mD)(u/b)*b,n,b).map(p).concat((0,r.w6)((0,i.mD)(l/y)*y,f,y).map(v)).concat((0,r.w6)((0,i.mD)(e/g)*g,t,g).filter((function(t){return(0,i.Wn)(t%b)>i.Ho})).map(h)).concat((0,r.w6)((0,i.mD)(c/_)*_,s,_).filter((function(t){return(0,i.Wn)(t%y)>i.Ho})).map(d))}return x.lines=function(){return w().map((function(t){return{type:"LineString",coordinates:t}}))},x.outline=function(){return{type:"Polygon",coordinates:[p(u).concat(v(f).slice(1),p(n).reverse().slice(1),v(l).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.extentMajor(t).extentMinor(t):x.extentMinor()},x.extentMajor=function(t){return arguments.length?(u=+t[0][0],n=+t[1][0],l=+t[0][1],f=+t[1][1],u>n&&(t=u,u=n,n=t),l>f&&(t=l,l=f,f=t),x.precision(m)):[[u,l],[n,f]]},x.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],c=+n[0][1],s=+n[1][1],e>t&&(n=e,e=t,t=n),c>s&&(n=c,c=s,s=n),x.precision(m)):[[e,c],[t,s]]},x.step=function(t){return arguments.length?x.stepMajor(t).stepMinor(t):x.stepMinor()},x.stepMajor=function(t){return arguments.length?(b=+t[0],y=+t[1],x):[b,y]},x.stepMinor=function(t){return arguments.length?(g=+t[0],_=+t[1],x):[g,_]},x.precision=function(r){return arguments.length?(m=+r,h=a(c,s,90),d=o(e,t,m),p=a(l,f,90),v=o(u,n,m),x):m},x.extentMajor([[-180,-90+i.Ho],[180,90-i.Ho]]).extentMinor([[-180,-80-i.Ho],[180,80+i.Ho]])}function s(){return u()()}},59350:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},74200:(t,e,n)=>{"use strict";if(n.d(e,{ID:()=>r.ZP,qT:()=>i.Z,cS:()=>a.Z,ub:()=>o.Z,o6:()=>u.Z,Fh:()=>s.Z,iM:()=>c.Z,LF:()=>f.Z,xk:()=>l.Z,gD:()=>h.Z,S:()=>d.Z,HV:()=>d.e,iG:()=>p.Z,Jp:()=>v.Z,l4:()=>g.Z,FW:()=>_.Z,wk:()=>b.Z,Rf:()=>y.Z,fN:()=>y.l,aM:()=>m.Z,dz:()=>m.N,tJ:()=>x.Z,W$:()=>x.l,ET:()=>w.Z,SQ:()=>w.v,ah:()=>Z.Z,nh:()=>Z.o,bf:()=>D.Z,bw:()=>D.i,ES:()=>k.Z,Hw:()=>k.k,Bq:()=>E.Z,ot:()=>E.M,NL:()=>A.Z,OA:()=>j.Z,gv:()=>j.r,mw:()=>C.ZP,z:()=>C.hk,li:()=>M.Z,Bh:()=>M.K,Wv:()=>F.Z,jx:()=>F.I,kn:()=>B.Z,PA:()=>B.T,Il:()=>S.Z,GN:()=>S.F,w7:()=>N.Z,HZ:()=>T.Z,jD:()=>z.Z}),826==n.j)var r=n(86593);if(826==n.j)var i=n(70456);if(826==n.j)var a=n(83922);if(826==n.j)var o=n(62332);if(826==n.j)var u=n(98503);if(826==n.j)var s=n(24883);if(826==n.j)var c=n(37023);if(826==n.j)var f=n(94892);if(826==n.j)var l=n(37236);if(826==n.j)var h=n(65055);if(826==n.j)var d=n(51418);if(826==n.j)var p=n(70193);if(826==n.j)var v=n(74108);if(826==n.j)var g=n(53635);if(826==n.j)var _=n(48645);if(826==n.j)var b=n(51700);if(826==n.j)var y=n(13205);if(826==n.j)var m=n(71820);if(826==n.j)var x=n(54719);if(826==n.j)var w=n(41202);if(826==n.j)var Z=n(51105);if(826==n.j)var D=n(74749);if(826==n.j)var k=n(67650);if(826==n.j)var E=n(77164);if(826==n.j)var A=n(47880);if(826==n.j)var j=n(93137);if(826==n.j)var C=n(15317);if(826==n.j)var M=n(42617);if(826==n.j)var F=n(77792);if(826==n.j)var B=n(874);if(826==n.j)var S=n(17025);if(826==n.j)var N=n(85295);if(826==n.j)var T=n(60600);if(826==n.j)var z=n(13582)},70193:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(66573);function i(t,e){var n=t[0]*r.uR,i=t[1]*r.uR,a=e[0]*r.uR,o=e[1]*r.uR,u=(0,r.mC)(i),s=(0,r.O$)(i),c=(0,r.mC)(o),f=(0,r.O$)(o),l=u*(0,r.mC)(n),h=u*(0,r.O$)(n),d=c*(0,r.mC)(a),p=c*(0,r.O$)(a),v=2*(0,r.ZR)((0,r._b)((0,r.Jy)(o-i)+u*c*(0,r.Jy)(a-n))),g=(0,r.O$)(v),_=v?function(t){var e=(0,r.O$)(t*=v)/g,n=(0,r.O$)(v-t)/g,i=n*l+e*d,a=n*h+e*p,o=n*s+e*f;return[(0,r.fv)(a,i)*r.RW,(0,r.fv)(o,(0,r._b)(i*i+a*a))*r.RW]}:function(){return[n*r.RW,i*r.RW]};return _.distance=v,_}},74108:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r=n(6236),i=n(66573),a=n(48340);if(826==n.j)var o=n(60600);var u,s,c,f=(0,r.Z)(),l={sphere:a.Z,point:a.Z,lineStart:function(){l.point=d,l.lineEnd=h},lineEnd:a.Z,polygonStart:a.Z,polygonEnd:a.Z};function h(){l.point=l.lineEnd=a.Z}function d(t,e){t*=i.uR,e*=i.uR,u=t,s=(0,i.O$)(e),c=(0,i.mC)(e),l.point=p}function p(t,e){t*=i.uR,e*=i.uR;var n=(0,i.O$)(e),r=(0,i.mC)(e),a=(0,i.Wn)(t-u),o=(0,i.mC)(a),l=r*(0,i.O$)(a),h=c*n-s*r*o,d=s*n+c*r*o;f.add((0,i.fv)((0,i._b)(l*l+h*h),d)),u=t,s=n,c=r}function v(t){return f.reset(),(0,o.Z)(t,l),+f}},66573:(t,e,n)=>{"use strict";n.d(e,{Ho:()=>r,aW:()=>i,pi:()=>a,ou:()=>o,pu:()=>u,BZ:()=>s,RW:()=>c,uR:()=>f,Wn:()=>l,z4:()=>h,fv:()=>d,mC:()=>p,mD:()=>v,Qq:()=>g,cM:()=>_,sQ:()=>b,O$:()=>y,Xx:()=>m,_b:()=>x,OR:()=>w,Kh:()=>Z,ZR:()=>D,Jy:()=>k});var r=1e-6,i=1e-12,a=Math.PI,o=a/2,u=a/4,s=2*a,c=180/a,f=a/180,l=Math.abs,h=Math.atan,d=Math.atan2,p=Math.cos,v=Math.ceil,g=Math.exp,_=(Math.floor,Math.log),b=Math.pow,y=Math.sin,m=Math.sign||function(t){return t>0?1:t<0?-1:0},x=Math.sqrt,w=Math.tan;function Z(t){return t>1?0:t<-1?a:Math.acos(t)}function D(t){return t>1?o:t<-1?-o:Math.asin(t)}function k(t){return(t=y(t/2))*t}},48340:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},4503:(t,e,n)=>{"use strict";n.d(e,{Z:()=>_});var r,i,a,o,u=n(6236),s=n(66573),c=n(48340),f=(0,u.Z)(),l=(0,u.Z)(),h={point:c.Z,lineStart:c.Z,lineEnd:c.Z,polygonStart:function(){h.lineStart=d,h.lineEnd=g},polygonEnd:function(){h.lineStart=h.lineEnd=h.point=c.Z,f.add((0,s.Wn)(l)),l.reset()},result:function(){var t=f/2;return f.reset(),t}};function d(){h.point=p}function p(t,e){h.point=v,r=a=t,i=o=e}function v(t,e){l.add(o*t-a*e),a=t,o=e}function g(){v(r,i)}const _=826==n.j?h:null},57620:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=n(48340),i=1/0,a=i,o=-i,u=o,s={point:function(t,e){to&&(o=t),eu&&(u=e)},lineStart:r.Z,lineEnd:r.Z,polygonStart:r.Z,polygonEnd:r.Z,result:function(){var t=[[i,a],[o,u]];return o=u=-(a=i=1/0),t}};const c=826==n.j?s:null},93087:(t,e,n)=>{"use strict";n.d(e,{Z:()=>A});var r,i,a,o,u=n(66573),s=0,c=0,f=0,l=0,h=0,d=0,p=0,v=0,g=0,_={point:b,lineStart:y,lineEnd:w,polygonStart:function(){_.lineStart=Z,_.lineEnd=D},polygonEnd:function(){_.point=b,_.lineStart=y,_.lineEnd=w},result:function(){var t=g?[p/g,v/g]:d?[l/d,h/d]:f?[s/f,c/f]:[NaN,NaN];return s=c=f=l=h=d=p=v=g=0,t}};function b(t,e){s+=t,c+=e,++f}function y(){_.point=m}function m(t,e){_.point=x,b(a=t,o=e)}function x(t,e){var n=t-a,r=e-o,i=(0,u._b)(n*n+r*r);l+=i*(a+t)/2,h+=i*(o+e)/2,d+=i,b(a=t,o=e)}function w(){_.point=b}function Z(){_.point=k}function D(){E(r,i)}function k(t,e){_.point=E,b(r=a=t,i=o=e)}function E(t,e){var n=t-a,r=e-o,i=(0,u._b)(n*n+r*r);l+=i*(a+t)/2,h+=i*(o+e)/2,d+=i,p+=(i=o*t-a*e)*(a+t),v+=i*(o+e),g+=3*i,b(a=t,o=e)}const A=826==n.j?_:null},39695:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(66573),i=n(48340);function a(t){this._context=t}a.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,r.BZ)}},result:i.Z}},53635:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>l}),826==n.j)var r=n(59350);if(826==n.j)var i=n(60600);if(826==n.j)var a=n(4503);if(826==n.j)var o=n(57620);if(826==n.j)var u=n(93087);if(826==n.j)var s=n(39695);if(826==n.j)var c=n(61148);if(826==n.j)var f=n(21868);function l(t,e){var n,l,h=4.5;function d(t){return t&&("function"==typeof h&&l.pointRadius(+h.apply(this,arguments)),(0,i.Z)(t,n(l))),l.result()}return d.area=function(t){return(0,i.Z)(t,n(a.Z)),a.Z.result()},d.measure=function(t){return(0,i.Z)(t,n(c.Z)),c.Z.result()},d.bounds=function(t){return(0,i.Z)(t,n(o.Z)),o.Z.result()},d.centroid=function(t){return(0,i.Z)(t,n(u.Z)),u.Z.result()},d.projection=function(e){return arguments.length?(n=null==e?(t=null,r.Z):(t=e).stream,d):t},d.context=function(t){return arguments.length?(l=null==t?(e=null,new f.Z):new s.Z(e=t),"function"!=typeof h&&l.pointRadius(h),d):e},d.pointRadius=function(t){return arguments.length?(h="function"==typeof t?t:(l.pointRadius(+t),+t),d):h},d.projection(t).context(e)}},61148:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r,i,a,o,u,s=n(6236),c=n(66573),f=n(48340),l=(0,s.Z)(),h={point:f.Z,lineStart:function(){h.point=d},lineEnd:function(){r&&p(i,a),h.point=f.Z},polygonStart:function(){r=!0},polygonEnd:function(){r=null},result:function(){var t=+l;return l.reset(),t}};function d(t,e){h.point=p,i=o=t,a=u=e}function p(t,e){o-=t,u-=e,l.add((0,c._b)(o*o+u*u)),o=t,u=e}const v=826==n.j?h:null},21868:(t,e,n)=>{"use strict";function r(){this._string=[]}function i(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}n.d(e,{Z:()=>r}),r.prototype={_radius:4.5,_circle:i(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=i(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}}},12447:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(66573);function i(t,e){return(0,r.Wn)(t[0]-e[0]){"use strict";n.d(e,{Z:()=>s});var r=n(6236);if(826==n.j)var i=n(67776);if(826==n.j)var a=n(66573);var o=(0,r.Z)();function u(t){return(0,a.Wn)(t[0])<=a.pi?t[0]:(0,a.Xx)(t[0])*(((0,a.Wn)(t[0])+a.pi)%a.BZ-a.pi)}function s(t,e){var n=u(e),r=e[1],s=(0,a.O$)(r),c=[(0,a.O$)(n),-(0,a.mC)(n),0],f=0,l=0;o.reset(),1===s?r=a.ou+a.Ho:-1===s&&(r=-a.ou-a.Ho);for(var h=0,d=t.length;h=0?1:-1,C=j*A,M=C>a.pi,F=y*k;if(o.add((0,a.fv)(F*j*(0,a.O$)(C),m*E+F*(0,a.mC)(C))),f+=M?A+j*a.BZ:A,M^_>=n^Z>=n){var B=(0,i.T5)((0,i.Og)(g),(0,i.Og)(w));(0,i.iJ)(B);var S=(0,i.T5)(c,B);(0,i.iJ)(S);var N=(M^A>=0?-1:1)*(0,a.ZR)(S[2]);(r>N||r===N&&(B[0]||B[1]))&&(l+=M^A>=0?1:-1)}}return(f<-a.Ho||f{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(41202);function i(){return(0,r.Z)().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}},51700:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(48645);if(826==n.j)var a=n(41202);if(826==n.j)var o=n(80686);function u(){var t,e,n,u,s,c,f=(0,i.Z)(),l=(0,a.Z)().rotate([154,0]).center([-2,58.5]).parallels([55,65]),h=(0,a.Z)().rotate([157,0]).center([-3,19.9]).parallels([8,18]),d={point:function(t,e){c=[t,e]}};function p(t){var e=t[0],r=t[1];return c=null,n.point(e,r),c||(u.point(e,r),c)||(s.point(e,r),c)}function v(){return t=e=null,p}return p.invert=function(t){var e=f.scale(),n=f.translate(),r=(t[0]-n[0])/e,i=(t[1]-n[1])/e;return(i>=.12&&i<.234&&r>=-.425&&r<-.214?l:i>=.166&&i<.234&&r>=-.214&&r<-.115?h:f).invert(t)},p.stream=function(n){return t&&e===n?t:(r=[f.stream(e=n),l.stream(n),h.stream(n)],i=r.length,t={point:function(t,e){for(var n=-1;++n{"use strict";if(n.d(e,{W:()=>i,O:()=>a}),826==n.j)var r=n(66573);function i(t){return function(e,n){var i=(0,r.mC)(e),a=(0,r.mC)(n),o=t(i*a);return[o*a*(0,r.O$)(e),o*(0,r.O$)(n)]}}function a(t){return function(e,n){var i=(0,r._b)(e*e+n*n),a=t(i),o=(0,r.O$)(a),u=(0,r.mC)(a);return[(0,r.fv)(e*o,i*u),(0,r.ZR)(i&&n*o/i)]}}},13205:(t,e,n)=>{"use strict";n.d(e,{l:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);var o=(0,i.W)((function(t){return(0,r._b)(2/(1+t))}));function u(){return(0,a.Z)(o).scale(124.75).clipAngle(179.999)}o.invert=(0,i.O)((function(t){return 2*(0,r.ZR)(t/2)}))},71820:(t,e,n)=>{"use strict";n.d(e,{N:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);var o=(0,i.W)((function(t){return(t=(0,r.Kh)(t))&&t/(0,r.O$)(t)}));function u(){return(0,a.Z)(o).scale(79.4188).clipAngle(179.999)}o.invert=(0,i.O)((function(t){return t}))},32387:(t,e,n)=>{"use strict";if(n.d(e,{o:()=>a}),826==n.j)var r=n(66573);if(826==n.j)var i=n(93137);function a(t){var e=0,n=r.pi/3,a=(0,i.r)(t),o=a(e,n);return o.parallels=function(t){return arguments.length?a(e=t[0]*r.uR,n=t[1]*r.uR):[e*r.RW,n*r.RW]},o}},54719:(t,e,n)=>{"use strict";if(n.d(e,{l:()=>u,Z:()=>s}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(15317);function o(t){return(0,r.OR)((r.ou+t)/2)}function u(t,e){var n=(0,r.mC)(t),i=t===e?(0,r.O$)(t):(0,r.cM)(n/(0,r.mC)(e))/(0,r.cM)(o(e)/o(t)),u=n*(0,r.sQ)(o(t),i)/i;if(!i)return a.hk;function s(t,e){u>0?e<-r.ou+r.Ho&&(e=-r.ou+r.Ho):e>r.ou-r.Ho&&(e=r.ou-r.Ho);var n=u/(0,r.sQ)(o(e),i);return[n*(0,r.O$)(i*t),u-n*(0,r.mC)(i*t)]}return s.invert=function(t,e){var n=u-e,a=(0,r.Xx)(i)*(0,r._b)(t*t+n*n),o=(0,r.fv)(t,(0,r.Wn)(n))*(0,r.Xx)(n);return n*i<0&&(o-=r.pi*(0,r.Xx)(t)*(0,r.Xx)(n)),[o/i,2*(0,r.z4)((0,r.sQ)(u/a,1/i))-r.ou]},s}function s(){return(0,i.o)(u).scale(109.5).parallels([30,30])}},41202:(t,e,n)=>{"use strict";if(n.d(e,{v:()=>o,Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(8145);function o(t,e){var n=(0,r.O$)(t),i=(n+(0,r.O$)(e))/2;if((0,r.Wn)(i){"use strict";if(n.d(e,{o:()=>o,Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(67650);function o(t,e){var n=(0,r.mC)(t),i=t===e?(0,r.O$)(t):(n-(0,r.mC)(e))/(e-t),o=n/i+t;if((0,r.Wn)(i){"use strict";if(n.d(e,{V:()=>i}),826==n.j)var r=n(66573);function i(t){var e=(0,r.mC)(t);function n(t,n){return[t*e,(0,r.O$)(n)/e]}return n.invert=function(t,n){return[t/e,(0,r.ZR)(n*e)]},n}},74749:(t,e,n)=>{"use strict";if(n.d(e,{i:()=>f,Z:()=>l}),826==n.j)var r=n(93137);var i=n(66573),a=1.340264,o=-.081106,u=893e-6,s=.003796,c=(0,i._b)(3)/2;function f(t,e){var n=(0,i.ZR)(c*(0,i.O$)(e)),r=n*n,f=r*r*r;return[t*(0,i.mC)(n)/(c*(a+3*o*r+f*(7*u+9*s*r))),n*(a+o*r+f*(u+s*r))]}function l(){return(0,r.Z)(f).scale(177.158)}f.invert=function(t,e){for(var n,r=e,f=r*r,l=f*f*f,h=0;h<12&&(l=(f=(r-=n=(r*(a+o*f+l*(u+s*f))-e)/(a+3*o*f+l*(7*u+9*s*f)))*r)*f*f,!((0,i.Wn)(n){"use strict";if(n.d(e,{k:()=>i,Z:()=>a}),826==n.j)var r=n(93137);function i(t,e){return[t,e]}function a(){return(0,r.Z)(i).scale(152.63)}i.invert=i},80686:(t,e,n)=>{"use strict";if(n.d(e,{qg:()=>o,mF:()=>u,V6:()=>s,rf:()=>c}),826==n.j)var r=n(60600);if(826==n.j)var i=n(57620);function a(t,e,n){var a=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=a&&t.clipExtent(null),(0,r.Z)(n,t.stream(i.Z)),e(i.Z.result()),null!=a&&t.clipExtent(a),t}function o(t,e,n){return a(t,(function(n){var r=e[1][0]-e[0][0],i=e[1][1]-e[0][1],a=Math.min(r/(n[1][0]-n[0][0]),i/(n[1][1]-n[0][1])),o=+e[0][0]+(r-a*(n[1][0]+n[0][0]))/2,u=+e[0][1]+(i-a*(n[1][1]+n[0][1]))/2;t.scale(150*a).translate([o,u])}),n)}function u(t,e,n){return o(t,[[0,0],e],n)}function s(t,e,n){return a(t,(function(n){var r=+e,i=r/(n[1][0]-n[0][0]),a=(r-i*(n[1][0]+n[0][0]))/2,o=-i*n[0][1];t.scale(150*i).translate([a,o])}),n)}function c(t,e,n){return a(t,(function(n){var r=+e,i=r/(n[1][1]-n[0][1]),a=-i*n[0][0],o=(r-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([a,o])}),n)}},77164:(t,e,n)=>{"use strict";n.d(e,{M:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){var n=(0,r.mC)(e),i=(0,r.mC)(t)*n;return[n*(0,r.O$)(t)/i,(0,r.O$)(e)/i]}function u(){return(0,a.Z)(o).scale(144.049).clipAngle(60)}o.invert=(0,i.O)(r.z4)},47880:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(94892);if(826==n.j)var i=n(59350);if(826==n.j)var a=n(13582);if(826==n.j)var o=n(80686);if(826==n.j)var u=n(66573);function s(){var t,e,n,s,c,f,l,h=1,d=0,p=0,v=1,g=1,_=0,b=null,y=1,m=1,x=(0,a.l)({point:function(t,e){var n=D([t,e]);this.stream.point(n[0],n[1])}}),w=i.Z;function Z(){return y=h*v,m=h*g,f=l=null,D}function D(n){var r=n[0]*y,i=n[1]*m;if(_){var a=i*t-r*e;r=r*t+i*e,i=a}return[r+d,i+p]}return D.invert=function(n){var r=n[0]-d,i=n[1]-p;if(_){var a=i*t+r*e;r=r*t-i*e,i=a}return[r/y,i/m]},D.stream=function(t){return f&&l===t?f:f=x(w(l=t))},D.postclip=function(t){return arguments.length?(w=t,b=n=s=c=null,Z()):w},D.clipExtent=function(t){return arguments.length?(w=null==t?(b=n=s=c=null,i.Z):(0,r.Z)(b=+t[0][0],n=+t[0][1],s=+t[1][0],c=+t[1][1]),Z()):null==b?null:[[b,n],[s,c]]},D.scale=function(t){return arguments.length?(h=+t,Z()):h},D.translate=function(t){return arguments.length?(d=+t[0],p=+t[1],Z()):[d,p]},D.angle=function(n){return arguments.length?(_=n%360*u.uR,e=(0,u.O$)(_),t=(0,u.mC)(_),Z()):_*u.RW},D.reflectX=function(t){return arguments.length?(v=t?-1:1,Z()):v<0},D.reflectY=function(t){return arguments.length?(g=t?-1:1,Z()):g<0},D.fitExtent=function(t,e){return(0,o.qg)(D,t,e)},D.fitSize=function(t,e){return(0,o.mF)(D,t,e)},D.fitWidth=function(t,e){return(0,o.V6)(D,t,e)},D.fitHeight=function(t,e){return(0,o.rf)(D,t,e)},D}},93137:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>g,r:()=>_}),826==n.j)var r=n(98503);if(826==n.j)var i=n(24883);if(826==n.j)var a=n(94892);if(826==n.j)var o=n(81319);if(826==n.j)var u=n(59350);var s=n(66573);if(826==n.j)var c=n(85295);var f=n(13582);if(826==n.j)var l=n(80686);if(826==n.j)var h=n(9650);var d=(0,f.l)({point:function(t,e){this.stream.point(t*s.uR,e*s.uR)}});function p(t,e,n,r,i){function a(a,o){return[e+t*(a*=r),n-t*(o*=i)]}return a.invert=function(a,o){return[(a-e)/t*r,(n-o)/t*i]},a}function v(t,e,n,r,i,a){var o=(0,s.mC)(a),u=(0,s.O$)(a),c=o*t,f=u*t,l=o/t,h=u/t,d=(u*n-o*e)/t,p=(u*e+o*n)/t;function v(t,a){return[c*(t*=r)-f*(a*=i)+e,n-f*t-c*a]}return v.invert=function(t,e){return[r*(l*t-h*e+d),i*(p-h*t-l*e)]},v}function g(t){return _((function(){return t}))()}function _(t){var e,n,g,_,b,y,m,x,w,Z,D=150,k=480,E=250,A=0,j=0,C=0,M=0,F=0,B=0,S=1,N=1,T=null,z=r.Z,O=null,R=u.Z,P=.5;function I(t){return x(t[0]*s.uR,t[1]*s.uR)}function L(t){return(t=x.invert(t[0],t[1]))&&[t[0]*s.RW,t[1]*s.RW]}function U(){var t=v(D,0,0,S,N,B).apply(null,e(A,j)),r=(B?v:p)(D,k-t[0],E-t[1],S,N,B);return n=(0,c.I)(C,M,F),m=(0,o.Z)(e,r),x=(0,o.Z)(n,m),y=(0,h.Z)(m,P),$()}function $(){return w=Z=null,I}return I.stream=function(t){return w&&Z===t?w:w=d(function(t){return(0,f.l)({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(z(y(R(Z=t)))))},I.preclip=function(t){return arguments.length?(z=t,T=void 0,$()):z},I.postclip=function(t){return arguments.length?(R=t,O=g=_=b=null,$()):R},I.clipAngle=function(t){return arguments.length?(z=+t?(0,i.Z)(T=t*s.uR):(T=null,r.Z),$()):T*s.RW},I.clipExtent=function(t){return arguments.length?(R=null==t?(O=g=_=b=null,u.Z):(0,a.Z)(O=+t[0][0],g=+t[0][1],_=+t[1][0],b=+t[1][1]),$()):null==O?null:[[O,g],[_,b]]},I.scale=function(t){return arguments.length?(D=+t,U()):D},I.translate=function(t){return arguments.length?(k=+t[0],E=+t[1],U()):[k,E]},I.center=function(t){return arguments.length?(A=t[0]%360*s.uR,j=t[1]%360*s.uR,U()):[A*s.RW,j*s.RW]},I.rotate=function(t){return arguments.length?(C=t[0]%360*s.uR,M=t[1]%360*s.uR,F=t.length>2?t[2]%360*s.uR:0,U()):[C*s.RW,M*s.RW,F*s.RW]},I.angle=function(t){return arguments.length?(B=t%360*s.uR,U()):B*s.RW},I.reflectX=function(t){return arguments.length?(S=t?-1:1,U()):S<0},I.reflectY=function(t){return arguments.length?(N=t?-1:1,U()):N<0},I.precision=function(t){return arguments.length?(y=(0,h.Z)(m,P=t*t),$()):(0,s._b)(P)},I.fitExtent=function(t,e){return(0,l.qg)(I,t,e)},I.fitSize=function(t,e){return(0,l.mF)(I,t,e)},I.fitWidth=function(t,e){return(0,l.V6)(I,t,e)},I.fitHeight=function(t,e){return(0,l.rf)(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&L,U()}}},15317:(t,e,n)=>{"use strict";n.d(e,{hk:()=>o,ZP:()=>u,iW:()=>s});var r=n(66573);if(826==n.j)var i=n(85295);if(826==n.j)var a=n(93137);function o(t,e){return[t,(0,r.cM)((0,r.OR)((r.ou+e)/2))]}function u(){return s(o).scale(961/r.BZ)}function s(t){var e,n,u,s=(0,a.Z)(t),c=s.center,f=s.scale,l=s.translate,h=s.clipExtent,d=null;function p(){var a=r.pi*f(),c=s((0,i.Z)(s.rotate()).invert([0,0]));return h(null==d?[[c[0]-a,c[1]-a],[c[0]+a,c[1]+a]]:t===o?[[Math.max(c[0]-a,d),e],[Math.min(c[0]+a,n),u]]:[[d,Math.max(c[1]-a,e)],[n,Math.min(c[1]+a,u)]])}return s.scale=function(t){return arguments.length?(f(t),p()):f()},s.translate=function(t){return arguments.length?(l(t),p()):l()},s.center=function(t){return arguments.length?(c(t),p()):c()},s.clipExtent=function(t){return arguments.length?(null==t?d=e=n=u=null:(d=+t[0][0],e=+t[0][1],n=+t[1][0],u=+t[1][1]),p()):null==d?null:[[d,e],[n,u]]},p()}o.invert=function(t,e){return[t,2*(0,r.z4)((0,r.Qq)(e))-r.ou]}},42617:(t,e,n)=>{"use strict";if(n.d(e,{K:()=>a,Z:()=>o}),826==n.j)var r=n(93137);var i=n(66573);function a(t,e){var n=e*e,r=n*n;return[t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function o(){return(0,r.Z)(a).scale(175.295)}a.invert=function(t,e){var n,r=e,a=25;do{var o=r*r,u=o*o;r-=n=(r*(1.007226+o*(.015085+u*(.028874*o-.044475-.005916*u)))-e)/(1.007226+o*(.045255+u*(.259866*o-.311325-.005916*11*u)))}while((0,i.Wn)(n)>i.Ho&&--a>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]}},77792:(t,e,n)=>{"use strict";n.d(e,{I:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){return[(0,r.mC)(e)*(0,r.O$)(t),(0,r.O$)(e)]}function u(){return(0,a.Z)(o).scale(249.5).clipAngle(90+r.Ho)}o.invert=(0,i.O)(r.ZR)},9650:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(67776);var i=n(66573);if(826==n.j)var a=n(13582);var o=(0,i.mC)(30*i.uR);function u(t,e){return+e?function(t,e){function n(r,a,u,s,c,f,l,h,d,p,v,g,_,b){var y=l-r,m=h-a,x=y*y+m*m;if(x>4*e&&_--){var w=s+p,Z=c+v,D=f+g,k=(0,i._b)(w*w+Z*Z+D*D),E=(0,i.ZR)(D/=k),A=(0,i.Wn)((0,i.Wn)(D)-1)e||(0,i.Wn)((y*F+m*B)/x-.5)>.3||s*p+c*v+f*g{"use strict";n.d(e,{T:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){var n=(0,r.mC)(e),i=1+(0,r.mC)(t)*n;return[n*(0,r.O$)(t)/i,(0,r.O$)(e)/i]}function u(){return(0,a.Z)(o).scale(250).clipAngle(142)}o.invert=(0,i.O)((function(t){return 2*(0,r.z4)(t)}))},17025:(t,e,n)=>{"use strict";n.d(e,{F:()=>a,Z:()=>o});var r=n(66573);if(826==n.j)var i=n(15317);function a(t,e){return[(0,r.cM)((0,r.OR)((r.ou+e)/2)),-t]}function o(){var t=(0,i.iW)(a),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}a.invert=function(t,e){return[-e,2*(0,r.z4)((0,r.Qq)(t))-r.ou]}},85295:(t,e,n)=>{"use strict";if(n.d(e,{I:()=>o,Z:()=>f}),826==n.j)var r=n(81319);var i=n(66573);function a(t,e){return[(0,i.Wn)(t)>i.pi?t+Math.round(-t/i.BZ)*i.BZ:t,e]}function o(t,e,n){return(t%=i.BZ)?e||n?(0,r.Z)(s(t),c(e,n)):s(t):e||n?c(e,n):a}function u(t){return function(e,n){return[(e+=t)>i.pi?e-i.BZ:e<-i.pi?e+i.BZ:e,n]}}function s(t){var e=u(t);return e.invert=u(-t),e}function c(t,e){var n=(0,i.mC)(t),r=(0,i.O$)(t),a=(0,i.mC)(e),o=(0,i.O$)(e);function u(t,e){var u=(0,i.mC)(e),s=(0,i.mC)(t)*u,c=(0,i.O$)(t)*u,f=(0,i.O$)(e),l=f*n+s*r;return[(0,i.fv)(c*a-l*o,s*n-f*r),(0,i.ZR)(l*a+c*o)]}return u.invert=function(t,e){var u=(0,i.mC)(e),s=(0,i.mC)(t)*u,c=(0,i.O$)(t)*u,f=(0,i.O$)(e),l=f*a-c*o;return[(0,i.fv)(c*a+f*o,s*n+l*r),(0,i.ZR)(l*n-s*r)]},u}function f(t){function e(e){return(e=t(e[0]*i.uR,e[1]*i.uR))[0]*=i.RW,e[1]*=i.RW,e}return t=o(t[0]*i.uR,t[1]*i.uR,t.length>2?t[2]*i.uR:0),e.invert=function(e){return(e=t.invert(e[0]*i.uR,e[1]*i.uR))[0]*=i.RW,e[1]*=i.RW,e},e}a.invert=a},60600:(t,e,n)=>{"use strict";function r(t,e){t&&a.hasOwnProperty(t.type)&&a[t.type](t,e)}n.d(e,{Z:()=>s});var i={Feature:function(t,e){r(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,i=-1,a=n.length;++i{"use strict";function r(t){return{stream:i(t)}}function i(t){return function(e){var n=new a;for(var r in t)n[r]=t[r];return n.stream=e,n}}function a(){}n.d(e,{Z:()=>r,l:()=>i}),a.prototype={constructor:a,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}}},47033:(t,e,n)=>{"use strict";function r(t){return null==t?null:i(t)}function i(t){if("function"!=typeof t)throw new Error;return t}n.d(e,{j:()=>r,C:()=>i})},86642:(t,e,n)=>{"use strict";n.d(e,{t:()=>r,T:()=>i});var r=Array.prototype.slice;function i(t){for(var e,n,r=t.length;r;)n=Math.random()*r--|0,e=t[r],t[r]=t[n],t[n]=e;return t}},50287:(t,e,n)=>{"use strict";function r(t,e){return t.parent===e.parent?1:2}function i(t,e){return t+e.x}function a(t,e){return Math.max(t,e.y)}function o(){var t=r,e=1,n=1,o=!1;function u(r){var u,s=0;r.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(i,0)/t.length}(n),e.y=function(t){return 1+t.reduce(a,0)}(n)):(e.x=u?s+=t(e,u):0,e.y=0,u=e)}));var c=function(t){for(var e;e=t.children;)t=e[0];return t}(r),f=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(r),l=c.x-t(c,f)/2,h=f.x+t(f,c)/2;return r.eachAfter(o?function(t){t.x=(t.x-r.x)*e,t.y=(r.y-t.y)*n}:function(t){t.x=(t.x-l)/(h-l)*e,t.y=(1-(r.y?t.y/r.y:1))*n})}return u.separation=function(e){return arguments.length?(t=e,u):t},u.size=function(t){return arguments.length?(o=!1,e=+t[0],n=+t[1],u):o?null:[e,n]},u.nodeSize=function(t){return arguments.length?(o=!0,e=+t[0],n=+t[1],u):o?[e,n]:null},u}n.d(e,{Z:()=>o})},35227:(t,e,n)=>{"use strict";function r(){return 0}function i(t){return function(){return t}}n.d(e,{G:()=>r,Z:()=>i})},22210:(t,e,n)=>{"use strict";function r(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function i(t,e){var n,r,i,o,c,f=new s(t),l=+t.value&&(f.value=t.value),h=[f];for(null==e&&(e=a);n=h.pop();)if(l&&(n.value=+n.data.value),(i=e(n.data))&&(c=i.length))for(n.children=new Array(c),o=c-1;o>=0;--o)h.push(r=n.children[o]=new s(i[o])),r.parent=n,r.depth=n.depth+1;return f.eachBefore(u)}function a(t){return t.children}function o(t){t.data=t.data.data}function u(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function s(t){this.data=t,this.depth=this.height=0,this.parent=null}n.d(e,{NB:()=>s,le:()=>u,ZP:()=>i}),s.prototype=i.prototype={constructor:s,count:function(){return this.eachAfter(r)},each:function(t){var e,n,r,i,a=this,o=[a];do{for(e=o.reverse(),o=[];a=e.pop();)if(t(a),n=a.children)for(r=0,i=n.length;r=0;--n)i.push(e[n]);return this},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,i=r&&r.length;--i>=0;)n+=r[i].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;for(t=n.pop(),e=r.pop();t===e;)i=t,t=n.pop(),e=r.pop();return i}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){var t=[];return this.each((function(e){t.push(e)})),t},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return i(this).eachBefore(o)}}},27611:(t,e,n)=>{"use strict";if(n.d(e,{ki:()=>r.Z,bT:()=>i.ZP,P2:()=>a.Z,jA:()=>o.Z,O1:()=>u.Z,uK:()=>s.Z,QP:()=>c.Z,G_:()=>f.Z,pN:()=>l.Z,wL:()=>h.Z,LQ:()=>d.Z,Km:()=>p.Z,E_:()=>v.Z,o$:()=>g.ZP,eA:()=>_.Z}),826==n.j)var r=n(50287);if(826==n.j)var i=n(22210);if(826==n.j)var a=n(3438);if(826==n.j)var o=n(31750);if(826==n.j)var u=n(92589);if(826==n.j)var s=n(5610);if(826==n.j)var c=n(10018);if(826==n.j)var f=n(6046);if(826==n.j)var l=n(23062);if(826==n.j)var h=n(29483);if(826==n.j)var d=n(44925);if(826==n.j)var p=n(12460);if(826==n.j)var v=n(44164);if(826==n.j)var g=n(21086);if(826==n.j)var _=n(3346)},92589:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(86642);function i(t){for(var e,n,i=0,o=(t=(0,r.T)(r.t.call(t))).length,s=[];i0&&n*n>r*r+i*i}function s(t,e){for(var n=0;n{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(31750);if(826==n.j)var i=n(47033);if(826==n.j)var a=n(35227);function o(t){return Math.sqrt(t.value)}function u(){var t=null,e=1,n=1,r=a.G;function u(i){return i.x=e/2,i.y=n/2,t?i.eachBefore(s(t)).eachAfter(c(r,.5)).eachBefore(f(1)):i.eachBefore(s(o)).eachAfter(c(a.G,1)).eachAfter(c(r,i.r/Math.min(e,n))).eachBefore(f(Math.min(e,n)/(2*i.r))),i}return u.radius=function(e){return arguments.length?(t=(0,i.j)(e),u):t},u.size=function(t){return arguments.length?(e=+t[0],n=+t[1],u):[e,n]},u.padding=function(t){return arguments.length?(r="function"==typeof t?t:(0,a.Z)(+t),u):r},u}function s(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0))}}function c(t,e){return function(n){if(i=n.children){var i,a,o,u=i.length,s=t(n)*e||0;if(s)for(a=0;a{"use strict";if(n.d(e,{O:()=>s,Z:()=>c}),826==n.j)var r=n(92589);function i(t,e,n){var r,i,a,o,u=t.x-e.x,s=t.y-e.y,c=u*u+s*s;c?(i=e.r+n.r,i*=i,o=t.r+n.r,i>(o*=o)?(r=(c+o-i)/(2*c),a=Math.sqrt(Math.max(0,o/c-r*r)),n.x=t.x-r*u-a*s,n.y=t.y-r*s+a*u):(r=(c+i-o)/(2*c),a=Math.sqrt(Math.max(0,i/c-r*r)),n.x=e.x+r*u-a*s,n.y=e.y+r*s+a*u)):(n.x=e.x+n.r,n.y=e.y)}function a(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,i=e.y-t.y;return n>0&&n*n>r*r+i*i}function o(t){var e=t._,n=t.next._,r=e.r+n.r,i=(e.x*n.r+n.x*e.r)/r,a=(e.y*n.r+n.y*e.r)/r;return i*i+a*a}function u(t){this._=t,this.next=null,this.previous=null}function s(t){if(!(c=t.length))return 0;var e,n,s,c,f,l,h,d,p,v,g;if((e=t[0]).x=0,e.y=0,!(c>1))return e.r;if(n=t[1],e.x=-n.r,n.x=e.r,n.y=0,!(c>2))return e.r+n.r;i(n,e,s=t[2]),e=new u(e),n=new u(n),s=new u(s),e.next=s.previous=n,n.next=e.previous=s,s.next=n.previous=e;t:for(h=3;h{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(86228);if(826==n.j)var i=n(44925);function a(){var t=1,e=1,n=0,a=!1;function o(o){var u=o.height+1;return o.x0=o.y0=n,o.x1=t,o.y1=e/u,o.eachBefore(function(t,e){return function(r){r.children&&(0,i.Z)(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var a=r.x0,o=r.y0,u=r.x1-n,s=r.y1-n;u{"use strict";if(n.d(e,{Z:()=>c}),826==n.j)var r=n(47033);if(826==n.j)var i=n(22210);var a={depth:-1},o={};function u(t){return t.id}function s(t){return t.parentId}function c(){var t=u,e=s;function n(n){var r,u,s,c,f,l,h,d=n.length,p=new Array(d),v={};for(u=0;u0)throw new Error("cycle");return s}return n.id=function(e){return arguments.length?(t=(0,r.C)(e),n):t},n.parentId=function(t){return arguments.length?(e=(0,r.C)(t),n):e},n}},6046:(t,e,n)=>{"use strict";n.d(e,{Z:()=>f});var r=n(22210);function i(t,e){return t.parent===e.parent?1:2}function a(t){var e=t.children;return e?e[0]:t.t}function o(t){var e=t.children;return e?e[e.length-1]:t.t}function u(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function s(t,e,n){return t.a.parent===e.parent?t.a:n}function c(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function f(){var t=i,e=1,n=1,r=null;function f(i){var a=function(t){for(var e,n,r,i,a,o=new c(t,0),u=[o];e=u.pop();)if(r=e._.children)for(e.children=new Array(a=r.length),i=a-1;i>=0;--i)u.push(n=e.children[i]=new c(r[i],i)),n.parent=e;return(o.parent=new c(null,0)).children=[o],o}(i);if(a.eachAfter(l),a.parent.m=-a.z,a.eachBefore(h),r)i.eachBefore(d);else{var o=i,u=i,s=i;i.eachBefore((function(t){t.xu.x&&(u=t),t.depth>s.depth&&(s=t)}));var f=o===u?1:t(o,u)/2,p=f-o.x,v=e/(u.x+f+p),g=n/(s.depth||1);i.eachBefore((function(t){t.x=(t.x+p)*v,t.y=t.depth*g}))}return i}function l(e){var n=e.children,r=e.parent.children,i=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,i=t.children,a=i.length;--a>=0;)(e=i[a]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var c=(n[0].z+n[n.length-1].z)/2;i?(e.z=i.z+t(e._,i._),e.m=e.z-c):e.z=c}else i&&(e.z=i.z+t(e._,i._));e.parent.A=function(e,n,r){if(n){for(var i,c=e,f=e,l=n,h=c.parent.children[0],d=c.m,p=f.m,v=l.m,g=h.m;l=o(l),c=a(c),l&&c;)h=a(h),(f=o(f)).a=e,(i=l.z+v-c.z-d+t(l._,c._))>0&&(u(s(l,e,r),e,i),d+=i,p+=i),v+=l.m,d+=c.m,g+=h.m,p+=f.m;l&&!o(f)&&(f.t=l,f.m+=v-p),c&&!a(h)&&(h.t=c,h.m+=d-g,r=e)}return r}(e,i,e.parent.A||r[0])}function h(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function d(t){t.x*=e,t.y=t.depth*n}return f.separation=function(e){return arguments.length?(t=e,f):t},f.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],f):r?null:[e,n]},f.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],f):r?[e,n]:null},f}c.prototype=Object.create(r.NB.prototype)},29483:(t,e,n)=>{"use strict";function r(t,e,n,r,i){var a,o,u=t.children,s=u.length,c=new Array(s+1);for(c[0]=o=a=0;a=n-1){var f=u[e];return f.x0=i,f.y0=a,f.x1=o,void(f.y1=s)}for(var l=c[e],h=r/2+l,d=e+1,p=n-1;d>>1;c[v]s-a){var b=(i*_+o*g)/r;t(e,d,g,i,a,b,s),t(d,n,_,b,a,o,s)}else{var y=(a*_+s*g)/r;t(e,d,g,i,a,o,y),t(d,n,_,i,y,o,s)}}(0,s,t.value,e,n,r,i)}n.d(e,{Z:()=>r})},44925:(t,e,n)=>{"use strict";function r(t,e,n,r,i){for(var a,o=t.children,u=-1,s=o.length,c=t.value&&(r-e)/t.value;++ur})},23062:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(86228);if(826==n.j)var i=n(21086);if(826==n.j)var a=n(47033);if(826==n.j)var o=n(35227);function u(){var t=i.ZP,e=!1,n=1,u=1,s=[0],c=o.G,f=o.G,l=o.G,h=o.G,d=o.G;function p(t){return t.x0=t.y0=0,t.x1=n,t.y1=u,t.eachBefore(v),s=[0],e&&t.eachBefore(r.Z),t}function v(e){var n=s[e.depth],r=e.x0+n,i=e.y0+n,a=e.x1-n,o=e.y1-n;a{"use strict";n.d(e,{Z:()=>o});var r=n(44925),i=n(12460),a=n(21086);const o=function t(e){function n(t,n,o,u,s){if((c=t._squarify)&&c.ratio===e)for(var c,f,l,h,d,p=-1,v=c.length,g=t.value;++p1?e:1)},n}(a.Sk)},86228:(t,e,n)=>{"use strict";function r(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}n.d(e,{Z:()=>r})},12460:(t,e,n)=>{"use strict";function r(t,e,n,r,i){for(var a,o=t.children,u=-1,s=o.length,c=t.value&&(i-n)/t.value;++ur})},44164:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(44925);if(826==n.j)var i=n(12460);function a(t,e,n,a,o){(1&t.depth?i.Z:r.Z)(t,e,n,a,o)}},21086:(t,e,n)=>{"use strict";n.d(e,{Sk:()=>a,DD:()=>o,ZP:()=>u});var r=n(44925),i=n(12460),a=(1+Math.sqrt(5))/2;function o(t,e,n,a,o,u){for(var s,c,f,l,h,d,p,v,g,_,b,y=[],m=e.children,x=0,w=0,Z=m.length,D=e.value;xp&&(p=c),b=h*h*_,(v=Math.max(p/b,b/d))>g){h-=c;break}g=v}y.push(s={value:h,dice:f1?e:1)},n}(a)},47639:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,M:()=>o}),826==n.j)var r=n(69777);if(826==n.j)var i=n(43289);function a(t,e){return((0,i.v)(e)?i.Z:o)(t,e)}function o(t,e){var n,i=e?e.length:0,a=t?Math.min(i,t.length):0,o=new Array(a),u=new Array(i);for(n=0;n{"use strict";function r(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}function i(t){var e=t.length-1;return function(n){var i=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],u=i>0?t[i-1]:2*a-o,s=ir,Z:()=>i})},6984:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(67855);function i(t){var e=t.length;return function(n){var i=Math.floor(((n%=1)<0?++n:n)*e),a=t[(i+e-1)%e],o=t[i%e],u=t[(i+1)%e],s=t[(i+2)%e];return(0,r.t)((n-i/e)*e,a,o,u,s)}}},1234:(t,e,n)=>{"use strict";if(n.d(e,{wx:()=>a,yi:()=>o,ZP:()=>u}),826==n.j)var r=n(88992);function i(t,e){return function(n){return t+n*e}}function a(t,e){var n=e-t;return n?i(t,n>180||n<-180?n-360*Math.round(n/360):n):(0,r.Z)(isNaN(t)?e:t)}function o(t){return 1==(t=+t)?u:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):(0,r.Z)(isNaN(e)?n:e)}}function u(t,e){var n=e-t;return n?i(t,n):(0,r.Z)(isNaN(t)?e:t)}},88992:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},20546:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,B:()=>u});var r=n(29607),i=n(1234);function a(t){return function e(n){function a(e,a){var o=t((e=(0,r.Z)(e)).h,(a=(0,r.Z)(a)).h),u=(0,i.ZP)(e.s,a.s),s=(0,i.ZP)(e.l,a.l),c=(0,i.ZP)(e.opacity,a.opacity);return function(t){return e.h=o(t),e.s=u(t),e.l=s(Math.pow(t,n)),e.opacity=c(t),e+""}}return n=+n,a.gamma=e,a}(1)}const o=a(i.wx);var u=a(i.ZP)},91255:(t,e,n)=>{"use strict";function r(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}n.d(e,{Z:()=>r})},32165:(t,e,n)=>{"use strict";function r(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}n.d(e,{Z:()=>r})},87286:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,b:()=>u});var r=n(20966),i=n(1234);function a(t){return function(e,n){var a=t((e=(0,r.Uc)(e)).h,(n=(0,r.Uc)(n)).h),o=(0,i.ZP)(e.c,n.c),u=(0,i.ZP)(e.l,n.l),s=(0,i.ZP)(e.opacity,n.opacity);return function(t){return e.h=a(t),e.c=o(t),e.l=u(t),e.opacity=s(t),e+""}}}const o=a(i.wx);var u=a(i.ZP)},43780:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,q:()=>u});var r=n(68847),i=n(1234);function a(t){return function(e,n){var a=t((e=(0,r.Ym)(e)).h,(n=(0,r.Ym)(n)).h),o=(0,i.ZP)(e.s,n.s),u=(0,i.ZP)(e.l,n.l),s=(0,i.ZP)(e.opacity,n.opacity);return function(t){return e.h=a(t),e.s=o(t),e.l=u(t),e.opacity=s(t),e+""}}}const o=a(i.wx);var u=a(i.ZP)},7806:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(1234);function i(t,e){var n=(0,r.wx)(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}},67982:(t,e,n)=>{"use strict";if(n.d(e,{sX:()=>r.Z,Ck:()=>i.Z,nH:()=>a.Z,FO:()=>o.Z,NW:()=>u.Z,Tp:()=>s.Z,EP:()=>c.Z,k4:()=>f.Z,qN:()=>l.Z,IW:()=>h.Z,uL:()=>d.Z,IT:()=>p.Z,Yb:()=>v.Y,wL:()=>v.w,JX:()=>g.Z,LX:()=>_.ZP,u1:()=>_.hD,F5:()=>_.YD,US:()=>b.Z,H:()=>b.q,uU:()=>y.Z,JH:()=>m.Z,Yr:()=>m.b,Ji:()=>x.Z,tR:()=>x.B,sO:()=>w.Z,q$:()=>Z.Z}),826==n.j)var r=n(69777);if(826==n.j)var i=n(47639);if(826==n.j)var a=n(67855);if(826==n.j)var o=n(6984);if(826==n.j)var u=n(91255);if(826==n.j)var s=n(32165);if(826==n.j)var c=n(7806);if(826==n.j)var f=n(98876);if(826==n.j)var l=n(43289);if(826==n.j)var h=n(73363);if(826==n.j)var d=n(74672);if(826==n.j)var p=n(76060);if(826==n.j)var v=n(88994);if(826==n.j)var g=n(68498);if(826==n.j)var _=n(78978);if(826==n.j)var b=n(43780);if(826==n.j)var y=n(88751);if(826==n.j)var m=n(87286);if(826==n.j)var x=n(20546);if(826==n.j)var w=n(87475);if(826==n.j)var Z=n(78106)},88751:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(20966);if(826==n.j)var i=n(1234);function a(t,e){var n=(0,i.ZP)((t=(0,r.ZP)(t)).l,(e=(0,r.ZP)(e)).l),a=(0,i.ZP)(t.a,e.a),o=(0,i.ZP)(t.b,e.b),u=(0,i.ZP)(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=a(e),t.b=o(e),t.opacity=u(e),t+""}}},98876:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}n.d(e,{Z:()=>r})},43289:(t,e,n)=>{"use strict";function r(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,i=e.slice();return function(a){for(n=0;nr,v:()=>i})},73363:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(69777);function i(t,e){var n,i={},a={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?i[n]=(0,r.Z)(t[n],e[n]):a[n]=e[n];return function(t){for(n in i)a[n]=i[n](t);return a}}},87475:(t,e,n)=>{"use strict";function r(t,e){for(var n=0,r=e.length-1,i=e[0],a=new Array(r<0?0:r);nr})},78106:(t,e,n)=>{"use strict";function r(t,e){for(var n=new Array(e),r=0;rr})},78978:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>u,hD:()=>c,YD:()=>f});var r=n(68847),i=n(67855),a=n(6984),o=n(1234);const u=function t(e){var n=(0,o.yi)(e);function i(t,e){var i=n((t=(0,r.B8)(t)).r,(e=(0,r.B8)(e)).r),a=n(t.g,e.g),u=n(t.b,e.b),s=(0,o.ZP)(t.opacity,e.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=u(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function s(t){return function(e){var n,i,a=e.length,o=new Array(a),u=new Array(a),s=new Array(a);for(n=0;n{"use strict";function r(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}n.d(e,{Z:()=>r})},76060:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(98876);var i=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,a=new RegExp(i.source,"g");function o(t,e){var n,o,u,s=i.lastIndex=a.lastIndex=0,c=-1,f=[],l=[];for(t+="",e+="";(n=i.exec(t))&&(o=a.exec(e));)(u=o.index)>s&&(u=e.slice(s,u),f[c]?f[c]+=u:f[++c]=u),(n=n[0])===(o=o[0])?f[c]?f[c]+=o:f[++c]=o:(f[++c]=null,l.push({i:c,x:(0,r.Z)(n,o)})),s=a.lastIndex;return s{"use strict";n.d(e,{y:()=>i,Z:()=>a});var r=180/Math.PI,i={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function a(t,e,n,i,a,o){var u,s,c;return(u=Math.sqrt(t*t+e*e))&&(t/=u,e/=u),(c=t*n+e*i)&&(n-=t*c,i-=e*c),(s=Math.sqrt(n*n+i*i))&&(n/=s,i/=s,c/=s),t*i{"use strict";n.d(e,{Y:()=>f,w:()=>l});var r,i,a,o,u=n(98876),s=n(97367);function c(t,e,n,r){function i(t){return t.length?t.pop()+" ":""}return function(a,o){var s=[],c=[];return a=t(a),o=t(o),function(t,r,i,a,o,s){if(t!==i||r!==a){var c=o.push("translate(",null,e,null,n);s.push({i:c-4,x:(0,u.Z)(t,i)},{i:c-2,x:(0,u.Z)(r,a)})}else(i||a)&&o.push("translate("+i+e+a+n)}(a.translateX,a.translateY,o.translateX,o.translateY,s,c),function(t,e,n,a){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:(0,u.Z)(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:(0,u.Z)(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:(0,u.Z)(t,n)},{i:s-2,x:(0,u.Z)(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n{"use strict";if(n.d(e,{Z:()=>h}),826==n.j)var r=n(68847);if(826==n.j)var i=n(78978);if(826==n.j)var a=n(47639);if(826==n.j)var o=n(91255);if(826==n.j)var u=n(98876);if(826==n.j)var s=n(73363);if(826==n.j)var c=n(76060);if(826==n.j)var f=n(88992);if(826==n.j)var l=n(43289);function h(t,e){var n,h=typeof e;return null==e||"boolean"===h?(0,f.Z)(e):("number"===h?u.Z:"string"===h?(n=(0,r.ZP)(e))?(e=n,i.ZP):c.Z:e instanceof r.ZP?i.ZP:e instanceof Date?o.Z:(0,l.v)(e)?l.Z:Array.isArray(e)?a.M:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?s.Z:u.Z)(t,e)}},68498:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=Math.SQRT2;function i(t){return((t=Math.exp(t))+1/t)/2}function a(t,e){var n,a,o=t[0],u=t[1],s=t[2],c=e[0],f=e[1],l=e[2],h=c-o,d=f-u,p=h*h+d*d;if(p<1e-12)a=Math.log(l/s)/r,n=function(t){return[o+t*h,u+t*d,s*Math.exp(r*t*a)]};else{var v=Math.sqrt(p),g=(l*l-s*s+4*p)/(2*s*2*v),_=(l*l-s*s-4*p)/(2*l*2*v),b=Math.log(Math.sqrt(g*g+1)-g),y=Math.log(Math.sqrt(_*_+1)-_);a=(y-b)/r,n=function(t){var e,n=t*a,c=i(b),f=s/(2*v)*(c*(e=r*n+b,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(b));return[o+f*h,u+f*d,s*c/i(r*n+b)]}}return n.duration=1e3*a,n}},42540:(t,e,n)=>{"use strict";if(n.d(e,{E:()=>r.Z}),826==n.j)var r=n(91672)},91672:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=Math.PI,i=2*r,a=1e-6,o=i-a;function u(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function s(){return new u}u.prototype=s.prototype={constructor:u,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r)},bezierCurveTo:function(t,e,n,r,i,a){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+i)+","+(this._y1=+a)},arcTo:function(t,e,n,i,o){t=+t,e=+e,n=+n,i=+i,o=+o;var u=this._x1,s=this._y1,c=n-t,f=i-e,l=u-t,h=s-e,d=l*l+h*h;if(o<0)throw new Error("negative radius: "+o);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(d>a)if(Math.abs(h*c-f*l)>a&&o){var p=n-u,v=i-s,g=c*c+f*f,_=p*p+v*v,b=Math.sqrt(g),y=Math.sqrt(d),m=o*Math.tan((r-Math.acos((g+d-_)/(2*b*y)))/2),x=m/y,w=m/b;Math.abs(x-1)>a&&(this._+="L"+(t+x*l)+","+(e+x*h)),this._+="A"+o+","+o+",0,0,"+ +(h*p>l*v)+","+(this._x1=t+w*c)+","+(this._y1=e+w*f)}else this._+="L"+(this._x1=t)+","+(this._y1=e)},arc:function(t,e,n,u,s,c){t=+t,e=+e,c=!!c;var f=(n=+n)*Math.cos(u),l=n*Math.sin(u),h=t+f,d=e+l,p=1^c,v=c?u-s:s-u;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+h+","+d:(Math.abs(this._x1-h)>a||Math.abs(this._y1-d)>a)&&(this._+="L"+h+","+d),n&&(v<0&&(v=v%i+i),v>o?this._+="A"+n+","+n+",0,1,"+p+","+(t-f)+","+(e-l)+"A"+n+","+n+",0,1,"+p+","+(this._x1=h)+","+(this._y1=d):v>a&&(this._+="A"+n+","+n+",0,"+ +(v>=r)+","+p+","+(this._x1=t+n*Math.cos(s))+","+(this._y1=e+n*Math.sin(s))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const c=826==n.j?s:null},82162:(t,e,n)=>{"use strict";function r(t){for(var e,n=-1,r=t.length,i=t[r-1],a=0;++nr})},81473:(t,e,n)=>{"use strict";function r(t){for(var e,n,r=-1,i=t.length,a=0,o=0,u=t[i-1],s=0;++rr})},83972:(t,e,n)=>{"use strict";function r(t,e){for(var n,r,i=t.length,a=t[i-1],o=e[0],u=e[1],s=a[0],c=a[1],f=!1,l=0;lu!=c>u&&o<(s-n)*(u-r)/(c-r)+n&&(f=!f),s=n,c=r;return f}n.d(e,{Z:()=>r})},69847:(t,e,n)=>{"use strict";function r(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}n.d(e,{Z:()=>r})},50880:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(69847);function i(t,e){return t[0]-e[0]||t[1]-e[1]}function a(t){for(var e=t.length,n=[0,1],i=2,a=2;a1&&(0,r.Z)(t[n[i-2]],t[n[i-1]],t[a])<=0;)--i;n[i++]=a}return n.slice(0,i)}function o(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),o=new Array(n);for(e=0;e=0;--e)l.push(t[r[u[e]][2]]);for(e=+c;e{"use strict";if(n.d(e,{mI:()=>r.Z,tO:()=>i.Z,WF:()=>a.Z,Q6:()=>o.Z,NZ:()=>u.Z}),826==n.j)var r=n(82162);if(826==n.j)var i=n(81473);if(826==n.j)var a=n(50880);if(826==n.j)var o=n(83972);if(826==n.j)var u=n(40495)},40495:(t,e,n)=>{"use strict";function r(t){for(var e,n,r=-1,i=t.length,a=t[i-1],o=a[0],u=a[1],s=0;++rr})},93365:(t,e,n)=>{"use strict";if(n.d(e,{T:()=>r.Z}),826==n.j)var r=n(94673)},7196:(t,e,n)=>{"use strict";function r(t,e,n,r,i){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=i}n.d(e,{Z:()=>r})},94673:(t,e,n)=>{"use strict";function r(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var i,a,o,u,s,c,f,l,h,d=t._root,p={data:r},v=t._x0,g=t._y0,_=t._x1,b=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((c=e>=(a=(v+_)/2))?v=a:_=a,(f=n>=(o=(g+b)/2))?g=o:b=o,i=d,!(d=d[l=f<<1|c]))return i[l]=p,t;if(u=+t._x.call(null,d.data),s=+t._y.call(null,d.data),e===u&&n===s)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(c=e>=(a=(v+_)/2))?v=a:_=a,(f=n>=(o=(g+b)/2))?g=o:b=o}while((l=f<<1|c)==(h=(s>=o)<<1|u>=a));return i[h]=d,i[l]=p,t}n.d(e,{Z:()=>u});var i=n(7196);function a(t){return t[0]}function o(t){return t[1]}function u(t,e,n){var r=new s(null==e?a:e,null==n?o:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function s(t,e,n,r,i,a){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0}function c(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var f=u.prototype=s.prototype;f.copy=function(){var t,e,n=new s(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=c(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(e=r.source[i])&&(e.length?t.push({source:e,target:r.target[i]=new Array(4)}):r.target[i]=c(e));return n},f.add=function(t){var e=+this._x.call(null,t),n=+this._y.call(null,t);return r(this.cover(e,n),e,n,t)},f.addAll=function(t){var e,n,i,a,o=t.length,u=new Array(o),s=new Array(o),c=1/0,f=1/0,l=-1/0,h=-1/0;for(n=0;nl&&(l=i),ah&&(h=a));if(c>l||f>h)return this;for(this.cover(c,f).cover(l,h),n=0;nt||t>=i||r>e||e>=a;)switch(u=(ed||(o=c.y0)>p||(u=c.x1)=b)<<1|t>=_)&&(c=v[v.length-1],v[v.length-1]=v[v.length-1-f],v[v.length-1-f]=c)}else{var y=t-+this._x.call(null,g.data),m=e-+this._y.call(null,g.data),x=y*y+m*m;if(x=(u=(p+g)/2))?p=u:g=u,(f=o>=(s=(v+_)/2))?v=s:_=s,e=d,!(d=d[l=f<<1|c]))return this;if(!d.length)break;(e[l+1&3]||e[l+2&3]||e[l+3&3])&&(n=e,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):e?(i?e[l]=i:delete e[l],(d=e[0]||e[1]||e[2]||e[3])&&d===(e[3]||e[2]||e[1]||e[0])&&!d.length&&(n?n[h]=d:this._root=d),this):(this._root=i,this)},f.removeAll=function(t){for(var e=0,n=t.length;e{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666")},25673:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666")},52399:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928")},43642:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2")},62514:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc")},94841:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999")},33536:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3")},24966:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f")},27561:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab")},8475:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf")},89589:(t,e,n)=>{"use strict";function r(t){for(var e=t.length/6|0,n=new Array(e),r=0;rr})},28133:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(r.Z);const o=(0,i.Z)(a)},91233:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(r.Z);const o=(0,i.Z)(a)},33037:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(r.Z);const o=(0,i.Z)(a)},15333:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(r.Z);const o=(0,i.Z)(a)},21594:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(r.Z);const o=(0,i.Z)(a)},39418:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(r.Z);const o=(0,i.Z)(a)},65648:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(r.Z);const o=(0,i.Z)(a)},10549:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(r.Z);const o=(0,i.Z)(a)},30656:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(r.Z);const o=(0,i.Z)(a)},40989:(t,e,n)=>{"use strict";if(n.d(e,{Cn:()=>r.Z,Mr:()=>i.Z,Xg:()=>a.Z,xH:()=>o.Z,rp:()=>u.Z,i4:()=>s.Z,yK:()=>c.Z,W1:()=>f.Z,UC:()=>l.Z,K2:()=>h.Z,yl:()=>d.Z,QA:()=>d.r,nn:()=>p.Z,Uh:()=>p.r,qw:()=>v.Z,Lx:()=>v.r,xN:()=>g.Z,$K:()=>g.r,De:()=>_.Z,HW:()=>_.r,PL:()=>b.Z,u_:()=>b.r,zJ:()=>y.Z,XX:()=>y.r,BT:()=>m.Z,Kr:()=>m.r,T0:()=>x.Z,lq:()=>x.r,pl:()=>w.Z,S1:()=>w.r,hb:()=>Z.Z,DQ:()=>Z.r,Xw:()=>D.Z,AT:()=>D.r,RZ:()=>k.Z,MX:()=>k.r,S7:()=>E.Z,g1:()=>E.r,GM:()=>A.Z,UV:()=>A.r,cU:()=>j.Z,F6:()=>j.r,A4:()=>C.Z,zs:()=>C.r,Ht:()=>M.Z,Yi:()=>M.r,aE:()=>F.Z,GE:()=>F.r,Y_:()=>B.Z,Gb:()=>B.r,cj:()=>S.Z,M7:()=>S.r,sY:()=>N.Z,KH:()=>N.r,M:()=>T.Z,Yo:()=>T.r,A_:()=>z.Z,bU:()=>z.r,XW:()=>O.Z,DR:()=>O.r,bc:()=>R.Z,zU:()=>R.r,n$:()=>P.Z,P0:()=>P.r,r1:()=>I.Z,yB:()=>L.Z,IC:()=>U.ZP,AO:()=>U.s7,vc:()=>U.H7,OO:()=>$.Z,_B:()=>H.Z,V:()=>q.ZP,Gi:()=>q.uX,sN:()=>q.yy,iA:()=>q.zD}),826==n.j)var r=n(8475);if(826==n.j)var i=n(45795);if(826==n.j)var a=n(25673);if(826==n.j)var o=n(52399);if(826==n.j)var u=n(43642);if(826==n.j)var s=n(62514);if(826==n.j)var c=n(94841);if(826==n.j)var f=n(33536);if(826==n.j)var l=n(24966);if(826==n.j)var h=n(27561);if(826==n.j)var d=n(28133);if(826==n.j)var p=n(91233);if(826==n.j)var v=n(33037);if(826==n.j)var g=n(15333);if(826==n.j)var _=n(21594);if(826==n.j)var b=n(39418);if(826==n.j)var y=n(65648);if(826==n.j)var m=n(10549);if(826==n.j)var x=n(30656);if(826==n.j)var w=n(52149);if(826==n.j)var Z=n(43261);if(826==n.j)var D=n(4267);if(826==n.j)var k=n(22504);if(826==n.j)var E=n(8302);if(826==n.j)var A=n(93418);if(826==n.j)var j=n(65972);if(826==n.j)var C=n(1906);if(826==n.j)var M=n(44447);if(826==n.j)var F=n(5201);if(826==n.j)var B=n(5768);if(826==n.j)var S=n(91599);if(826==n.j)var N=n(61945);if(826==n.j)var T=n(99506);if(826==n.j)var z=n(54208);if(826==n.j)var O=n(64914);if(826==n.j)var R=n(90202);if(826==n.j)var P=n(7491);if(826==n.j)var I=n(3666);if(826==n.j)var L=n(35098);if(826==n.j)var U=n(155);if(826==n.j)var $=n(35996);if(826==n.j)var H=n(52858);if(826==n.j)var q=n(44687)},11303:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(78978);function i(t){return(0,r.hD)(t[t.length-1])}},52149:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(r.Z);const o=(0,i.Z)(a)},43261:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(r.Z);const o=(0,i.Z)(a)},4267:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(r.Z);const o=(0,i.Z)(a)},22504:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(r.Z);const o=(0,i.Z)(a)},93418:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(r.Z);const o=(0,i.Z)(a)},8302:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(r.Z);const o=(0,i.Z)(a)},65972:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(r.Z);const o=(0,i.Z)(a)},1906:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(r.Z);const o=(0,i.Z)(a)},5201:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(r.Z);const o=(0,i.Z)(a)},44447:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(r.Z);const o=(0,i.Z)(a)},5768:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(r.Z);const o=(0,i.Z)(a)},91599:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(r.Z);const o=(0,i.Z)(a)},3666:(t,e,n)=>{"use strict";function r(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}n.d(e,{Z:()=>r})},35098:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(29607);const i=(0,n(20546).B)((0,r.Z)(300,.5,0),(0,r.Z)(-240,.5,1))},155:(t,e,n)=>{"use strict";n.d(e,{s7:()=>a,H7:()=>o,ZP:()=>s});var r=n(29607),i=n(20546),a=(0,i.B)((0,r.Z)(-100,.75,.35),(0,r.Z)(80,1.5,.8)),o=(0,i.B)((0,r.Z)(260,.75,.35),(0,r.Z)(80,1.5,.8)),u=(0,r.Z)();function s(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return u.h=360*t-100,u.s=1.5-1.5*e,u.l=.8-.9*e,u+""}},35996:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=(0,n(68847).B8)(),i=Math.PI/3,a=2*Math.PI/3;function o(t){var e;return t=(.5-t)*Math.PI,r.r=255*(e=Math.sin(t))*e,r.g=255*(e=Math.sin(t+i))*e,r.b=255*(e=Math.sin(t+a))*e,r+""}},52858:(t,e,n)=>{"use strict";function r(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}n.d(e,{Z:()=>r})},44687:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,uX:()=>o,yy:()=>u,zD:()=>s});var r=n(89589);function i(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const a=i((0,r.Z)("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var o=i((0,r.Z)("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),u=i((0,r.Z)("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),s=i((0,r.Z)("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"))},61945:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(r.Z);const o=(0,i.Z)(a)},99506:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(r.Z);const o=(0,i.Z)(a)},54208:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(r.Z);const o=(0,i.Z)(a)},7491:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(r.Z);const o=(0,i.Z)(a)},64914:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(r.Z);const o=(0,i.Z)(a)},90202:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(r.Z);const o=(0,i.Z)(a)},46973:(t,e,n)=>{"use strict";n.d(e,{WU:()=>i,jH:()=>a});var r,i,a,o=n(29053),u=n(36159),s=n(49613),c=n(47681),f=n(52003),l=n(1166),h=n(61903),d=n(81015),p=Array.prototype.map,v=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];r=function(t){var e=void 0===t.grouping||void 0===t.thousands?d.Z:(0,u.Z)(p.call(t.grouping,Number),t.thousands+""),n=void 0===t.currency?"":t.currency[0]+"",r=void 0===t.currency?"":t.currency[1]+"",i=void 0===t.decimal?".":t.decimal+"",a=void 0===t.numerals?d.Z:(0,s.Z)(p.call(t.numerals,String)),g=void 0===t.percent?"%":t.percent+"",_=void 0===t.minus?"-":t.minus+"",b=void 0===t.nan?"NaN":t.nan+"";function y(t){var o=(t=(0,c.Z)(t)).fill,u=t.align,s=t.sign,d=t.symbol,p=t.zero,y=t.width,m=t.comma,x=t.precision,w=t.trim,Z=t.type;"n"===Z?(m=!0,Z="g"):l.Z[Z]||(void 0===x&&(x=12),w=!0,Z="g"),(p||"0"===o&&"="===u)&&(p=!0,o="0",u="=");var D="$"===d?n:"#"===d&&/[boxX]/.test(Z)?"0"+Z.toLowerCase():"",k="$"===d?r:/[%p]/.test(Z)?g:"",E=l.Z[Z],A=/[defgprs%]/.test(Z);function j(t){var n,r,c,l=D,d=k;if("c"===Z)d=E(t)+d,t="";else{var g=(t=+t)<0||1/t<0;if(t=isNaN(t)?b:E(Math.abs(t),x),w&&(t=(0,f.Z)(t)),g&&0==+t&&"+"!==s&&(g=!1),l=(g?"("===s?s:_:"-"===s||"("===s?"":s)+l,d=("s"===Z?v[8+h.y/3]:"")+d+(g&&"("===s?")":""),A)for(n=-1,r=t.length;++n(c=t.charCodeAt(n))||c>57){d=(46===c?i+t.slice(n+1):t.slice(n))+d,t=t.slice(0,n);break}}m&&!p&&(t=e(t,1/0));var j=l.length+t.length+d.length,C=j>1)+l+t+d+C.slice(j);break;default:t=C+l+t+d}return a(t)}return x=void 0===x?6:/[gprs]/.test(Z)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x)),j.toString=function(){return t+""},j}return{format:y,formatPrefix:function(t,e){var n=y(((t=(0,c.Z)(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor((0,o.Z)(e)/3))),i=Math.pow(10,-r),a=v[8+r/3];return function(t){return n(i*t)+a}}}}({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"}),i=r.format,a=r.formatPrefix},29053:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(57480);function i(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},57480:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function i(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{Z:()=>r,V:()=>i})},36159:(t,e,n)=>{"use strict";function r(t,e){return function(n,r){for(var i=n.length,a=[],o=0,u=t[0],s=0;i>0&&u>0&&(s+u+1>r&&(u=Math.max(1,r-s)),a.push(n.substring(i-=u,i+u)),!((s+=u+1)>r));)u=t[o=(o+1)%t.length];return a.reverse().join(e)}}n.d(e,{Z:()=>r})},49613:(t,e,n)=>{"use strict";function r(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}n.d(e,{Z:()=>r})},61903:(t,e,n)=>{"use strict";if(n.d(e,{y:()=>i,Z:()=>a}),826==n.j)var r=n(57480);var i;function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var a=n[0],o=n[1],u=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,s=a.length;return u===s?a:u>s?a+new Array(u-s+1).join("0"):u>0?a.slice(0,u)+"."+a.slice(u):"0."+new Array(1-u).join("0")+(0,r.V)(t,Math.max(0,e+u-1))[0]}},47681:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function i(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new a({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function a(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}i.prototype=a.prototype,a.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},52003:(t,e,n)=>{"use strict";function r(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}n.d(e,{Z:()=>r})},1166:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(57480),i=n(61903);function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var i=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+i:i.length>a+1?i.slice(0,a+1)+"."+i.slice(a+1):i+new Array(a-i.length+2).join("0")}const o={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:r.Z,e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return a(100*t,e)},r:a,s:i.Z,X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}}},81015:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},84418:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},94735:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},54415:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},84901:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},22274:(t,e,n)=>{"use strict";function r(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}function i(t,e){switch(arguments.length){case 0:break;case 1:this.interpolator(t);break;default:this.interpolator(e).domain(t)}return this}n.d(e,{o:()=>r,O:()=>i})},10070:(t,e,n)=>{"use strict";function r(t,e){var n,r=0,i=(t=t.slice()).length-1,a=t[r],o=t[i];return or})},5497:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{Z:()=>r})},57076:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},81648:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(15515);if(826==n.j)var i=n(23475);function a(t){return(0,i.Z)((0,r.Z)(t).call(document.documentElement))}},15515:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(69998);if(826==n.j)var i=n(70378);function a(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===i.P&&e.documentElement.namespaceURI===i.P?e.createElement(t):e.createElementNS(n,t)}}function o(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function u(t){var e=(0,r.Z)(t);return(e.local?o:a)(e)}},16761:(t,e,n)=>{"use strict";if(n.d(e,{Ue:()=>r.Z,Du:()=>i.Z,I_:()=>a.Z,C2:()=>o.Z,Jz:()=>u.Z,uD:()=>s.Z,aC:()=>c.Z,Eb:()=>f.Z,Ys:()=>l.Z,td:()=>h.Z,f_:()=>d.ZP,nZ:()=>p.Z,UK:()=>v.Z,oB:()=>g.S,Fq:()=>_.Z,W4:()=>b.Z,u9:()=>y.Z,B:()=>m.B,_H:()=>m._H}),826==n.j)var r=n(81648);if(826==n.j)var i=n(15515);if(826==n.j)var a=n(36857);if(826==n.j)var o=n(73151);if(826==n.j)var u=n(42637);if(826==n.j)var s=n(69998);if(826==n.j)var c=n(70378);if(826==n.j)var f=n(94040);if(826==n.j)var l=n(23475);if(826==n.j)var h=n(18321);if(826==n.j)var d=n(54632);if(826==n.j)var p=n(61566);if(826==n.j)var v=n(87393);if(826==n.j)var g=n(34675);if(826==n.j)var _=n(13171);if(826==n.j)var b=n(74357);if(826==n.j)var y=n(42044);if(826==n.j)var m=n(78011)},36857:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=0;function i(){return new a}function a(){this._="@"+(++r).toString(36)}a.prototype=i.prototype={constructor:a,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}}},73151:(t,e,n)=>{"use strict";function r(t){return function(){return this.matches(t)}}n.d(e,{Z:()=>r})},42637:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t){var e=(0,r.Z)();return e.changedTouches&&(e=e.changedTouches[0]),(0,i.Z)(t,e)}},69998:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(70378);function i(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),r.Z.hasOwnProperty(e)?{space:r.Z[e],local:t}:t}},70378:(t,e,n)=>{"use strict";n.d(e,{P:()=>r,Z:()=>i});var r="http://www.w3.org/1999/xhtml";const i={svg:"http://www.w3.org/2000/svg",xhtml:r,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"}},94040:(t,e,n)=>{"use strict";function r(t,e){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}n.d(e,{Z:()=>r})},23475:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(54632);function i(t){return"string"==typeof t?new r.Y1([[document.querySelector(t)]],[document.documentElement]):new r.Y1([[t]],r.Jz)}},18321:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(54632);function i(t){return"string"==typeof t?new r.Y1([document.querySelectorAll(t)],[document.documentElement]):new r.Y1([null==t?[]:t],r.Jz)}},64461:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,F:()=>o}),826==n.j)var r=n(56335);if(826==n.j)var i=n(54632);function a(){return new i.Y1(this._enter||this._groups.map(r.Z),this._parents)}function o(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}o.prototype={constructor:o,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}}},54632:(t,e,n)=>{"use strict";n.d(e,{Y1:()=>X,ZP:()=>J,Jz:()=>G});var r=n(61566),i=n(87393),a=n(73151),o=n(64461),u=n(57076);function s(t,e,n,r,i,a){for(var u,s=0,c=e.length,f=a.length;se?1:t>=e?0:NaN}var h=n(69998);function d(t){return function(){this.removeAttribute(t)}}function p(t){return function(){this.removeAttributeNS(t.space,t.local)}}function v(t,e){return function(){this.setAttribute(t,e)}}function g(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function _(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function b(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}var y=n(34675);function m(t){return function(){delete this[t]}}function x(t,e){return function(){this[t]=e}}function w(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function Z(t){return t.trim().split(/^|\s+/)}function D(t){return t.classList||new k(t)}function k(t){this._node=t,this._names=Z(t.getAttribute("class")||"")}function E(t,e){for(var n=D(t),r=-1,i=e.length;++r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var P=n(15515);function I(){return null}function L(){var t=this.parentNode;t&&t.removeChild(this)}function U(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function $(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}var H=n(78011),q=n(42044);function Y(t,e,n){var r=(0,q.Z)(t),i=r.CustomEvent;"function"==typeof i?i=new i(e,n):(i=r.document.createEvent("Event"),n?(i.initEvent(e,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(e,!1,!1)),t.dispatchEvent(i)}function W(t,e){return function(){return Y(this,t,e)}}function V(t,e){return function(){return Y(this,t,e.apply(this,arguments))}}var G=[null];function X(t,e){this._groups=t,this._parents=e}function K(){return new X([[document.documentElement]],G)}X.prototype=K.prototype={constructor:X,select:function(t){"function"!=typeof t&&(t=(0,r.Z)(t));for(var e=this._groups,n=e.length,i=new Array(n),a=0;a=Z&&(Z=w+1);!(x=y[Z])&&++Z<_;);m._next=x||null}}return(o=new X(o,r))._enter=f,o._exit=l,o},enter:o.Z,exit:function(){return new X(this._exit||this._groups.map(f.Z),this._parents)},join:function(t,e,n){var r=this.enter(),i=this,a=this.exit();return r="function"==typeof t?t(r):r.append(t+""),null!=e&&(i=e(i)),null==n?a.remove():n(a),r&&i?r.merge(i).order():i},merge:function(t){for(var e=this._groups,n=t._groups,r=e.length,i=n.length,a=Math.min(r,i),o=new Array(r),u=0;u=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=l);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?m:"function"==typeof e?w:x)(t,e)):this.node()[t]},classed:function(t,e){var n=Z(t+"");if(arguments.length<2){for(var r=D(this.node()),i=-1,a=n.length;++i{"use strict";n.d(e,{B:()=>i,ZP:()=>f,_H:()=>l});var r={},i=null;function a(t,e,n){return t=o(t,e,n),function(e){var n=e.relatedTarget;n&&(n===this||8&n.compareDocumentPosition(this))||t.call(this,e)}}function o(t,e,n){return function(r){var a=i;i=r;try{t.call(this,this.__data__,e,n)}finally{i=a}}}function u(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function s(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r{"use strict";function r(t){return new Array(t.length)}n.d(e,{Z:()=>r})},34675:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u,S:()=>s}),826==n.j)var r=n(42044);function i(t){return function(){this.style.removeProperty(t)}}function a(t,e,n){return function(){this.style.setProperty(t,e,n)}}function o(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function u(t,e,n){return arguments.length>1?this.each((null==e?i:"function"==typeof e?o:a)(t,e,null==n?"":n)):s(this.node(),t)}function s(t,e){return t.style.getPropertyValue(e)||(0,r.Z)(t).getComputedStyle(t,null).getPropertyValue(e)}},61566:(t,e,n)=>{"use strict";function r(){}function i(t){return null==t?r:function(){return this.querySelector(t)}}n.d(e,{Z:()=>i})},87393:(t,e,n)=>{"use strict";function r(){return[]}function i(t){return null==t?r:function(){return this.querySelectorAll(t)}}n.d(e,{Z:()=>i})},45778:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(78011);function i(){for(var t,e=r.B;t=e.sourceEvent;)e=t;return e}},13171:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t,e,n){arguments.length<3&&(n=e,e=(0,r.Z)().changedTouches);for(var a,o=0,u=e?e.length:0;o{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t,e){null==e&&(e=(0,r.Z)().touches);for(var n=0,a=e?e.length:0,o=new Array(a);n{"use strict";function r(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}n.d(e,{Z:()=>r})},38764:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>d}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(15);function o(t){return t.innerRadius}function u(t){return t.outerRadius}function s(t){return t.startAngle}function c(t){return t.endAngle}function f(t){return t&&t.padAngle}function l(t,e,n,r,i,o,u,s){var c=n-t,f=r-e,l=u-i,h=s-o,d=h*c-l*f;if(!(d*dF*F+B*B&&(k=A,E=j),{cx:k,cy:E,x01:-l,y01:-h,x11:k*(i/w-1),y11:E*(i/w-1)}}function d(){var t=o,e=u,n=(0,i.Z)(0),d=null,p=s,v=c,g=f,_=null;function b(){var i,o,u=+t.apply(this,arguments),s=+e.apply(this,arguments),c=p.apply(this,arguments)-a.ou,f=v.apply(this,arguments)-a.ou,b=(0,a.Wn)(f-c),y=f>c;if(_||(_=i=(0,r.Z)()),sa.Ho)if(b>a.BZ-a.Ho)_.moveTo(s*(0,a.mC)(c),s*(0,a.O$)(c)),_.arc(0,0,s,c,f,!y),u>a.Ho&&(_.moveTo(u*(0,a.mC)(f),u*(0,a.O$)(f)),_.arc(0,0,u,f,c,y));else{var m,x,w=c,Z=f,D=c,k=f,E=b,A=b,j=g.apply(this,arguments)/2,C=j>a.Ho&&(d?+d.apply(this,arguments):(0,a._b)(u*u+s*s)),M=(0,a.VV)((0,a.Wn)(s-u)/2,+n.apply(this,arguments)),F=M,B=M;if(C>a.Ho){var S=(0,a.ZR)(C/u*(0,a.O$)(j)),N=(0,a.ZR)(C/s*(0,a.O$)(j));(E-=2*S)>a.Ho?(D+=S*=y?1:-1,k-=S):(E=0,D=k=(c+f)/2),(A-=2*N)>a.Ho?(w+=N*=y?1:-1,Z-=N):(A=0,w=Z=(c+f)/2)}var T=s*(0,a.mC)(w),z=s*(0,a.O$)(w),O=u*(0,a.mC)(k),R=u*(0,a.O$)(k);if(M>a.Ho){var P,I=s*(0,a.mC)(Z),L=s*(0,a.O$)(Z),U=u*(0,a.mC)(D),$=u*(0,a.O$)(D);if(ba.Ho?B>a.Ho?(m=h(U,$,T,z,s,B,y),x=h(I,L,O,R,s,B,y),_.moveTo(m.cx+m.x01,m.cy+m.y01),Ba.Ho&&E>a.Ho?F>a.Ho?(m=h(O,R,I,L,u,-F,y),x=h(T,z,U,$,u,-F,y),_.lineTo(m.cx+m.x01,m.cy+m.y01),F{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(20651);if(826==n.j)var o=n(79767);if(826==n.j)var u=n(11053);function s(){var t=u.x,e=null,n=(0,i.Z)(0),s=u.y,c=(0,i.Z)(!0),f=null,l=a.Z,h=null;function d(i){var a,o,u,d,p,v=i.length,g=!1,_=new Array(v),b=new Array(v);for(null==f&&(h=l(p=(0,r.Z)())),a=0;a<=v;++a){if(!(a=o;--u)h.point(_[u],b[u]);h.lineEnd(),h.areaEnd()}g&&(_[a]=+t(d,a,i),b[a]=+n(d,a,i),h.point(e?+e(d,a,i):_[a],s?+s(d,a,i):b[a]))}if(p)return h=null,p+""||null}function p(){return(0,o.Z)().defined(c).curve(l).context(f)}return d.x=function(n){return arguments.length?(t="function"==typeof n?n:(0,i.Z)(+n),e=null,d):t},d.x0=function(e){return arguments.length?(t="function"==typeof e?e:(0,i.Z)(+e),d):t},d.x1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:(0,i.Z)(+t),d):e},d.y=function(t){return arguments.length?(n="function"==typeof t?t:(0,i.Z)(+t),s=null,d):n},d.y0=function(t){return arguments.length?(n="function"==typeof t?t:(0,i.Z)(+t),d):n},d.y1=function(t){return arguments.length?(s=null==t?null:"function"==typeof t?t:(0,i.Z)(+t),d):s},d.lineX0=d.lineY0=function(){return p().x(t).y(n)},d.lineY1=function(){return p().x(t).y(s)},d.lineX1=function(){return p().x(e).y(n)},d.defined=function(t){return arguments.length?(c="function"==typeof t?t:(0,i.Z)(!!t),d):c},d.curve=function(t){return arguments.length?(l=t,null!=f&&(h=l(f)),d):l},d.context=function(t){return arguments.length?(null==t?f=h=null:h=l(f=t),d):f},d}},69896:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(23165);if(826==n.j)var i=n(79493);if(826==n.j)var a=n(8329);function o(){var t=(0,i.Z)().curve(r.j),e=t.curve,n=t.lineX0,o=t.lineX1,u=t.lineY0,s=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return(0,a.X)(n())},delete t.lineX0,t.lineEndAngle=function(){return(0,a.X)(o())},delete t.lineX1,t.lineInnerRadius=function(){return(0,a.X)(u())},delete t.lineY0,t.lineOuterRadius=function(){return(0,a.X)(s())},delete t.lineY1,t.curve=function(t){return arguments.length?e((0,r.Z)(t)):e()._curve},t}},72299:(t,e,n)=>{"use strict";n.d(e,{t:()=>r});var r=Array.prototype.slice},33554:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},6023:(t,e,n)=>{"use strict";function r(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function i(t){this._context=t}function a(t){return new i(t)}n.d(e,{xm:()=>r,fE:()=>i,ZP:()=>a}),i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:r(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:r(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},25972:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(69706),i=n(6023);function a(t){this._context=t}function o(t){return new a(t)}a.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:(0,i.xm)(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},541:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(6023);function i(t){this._context=t}function a(t){return new i(t)}i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,i=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,i):this._context.moveTo(n,i);break;case 3:this._point=4;default:(0,r.xm)(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},94244:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(6023);function i(t,e){this._basis=new r.fE(t),this._beta=e}i.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,i=t[0],a=e[0],o=t[n]-i,u=e[n]-a,s=-1;++s<=n;)r=s/n,this._basis.point(this._beta*t[s]+(1-this._beta)*(i+r*o),this._beta*e[s]+(1-this._beta)*(a+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const a=function t(e){function n(t){return 1===e?new r.fE(t):new i(t,e)}return n.beta=function(e){return t(+e)},n}(.85)},46385:(t,e,n)=>{"use strict";function r(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function i(t,e){this._context=t,this._k=(1-e)/6}n.d(e,{xm:()=>r,pC:()=>i,ZP:()=>a}),i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:r(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:r(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const a=function t(e){function n(t){return new i(t,e)}return n.tension=function(e){return t(+e)},n}(0)},91931:(t,e,n)=>{"use strict";n.d(e,{U:()=>a,Z:()=>o});var r=n(69706),i=n(46385);function a(t,e){this._context=t,this._k=(1-e)/6}a.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:(0,i.xm)(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const o=function t(e){function n(t){return new a(t,e)}return n.tension=function(e){return t(+e)},n}(0)},42688:(t,e,n)=>{"use strict";n.d(e,{T:()=>i,Z:()=>a});var r=n(46385);function i(t,e){this._context=t,this._k=(1-e)/6}i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:(0,r.xm)(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const a=function t(e){function n(t){return new i(t,e)}return n.tension=function(e){return t(+e)},n}(0)},74924:(t,e,n)=>{"use strict";n.d(e,{x:()=>a,Z:()=>u});var r=n(15),i=n(46385);function a(t,e,n){var i=t._x1,a=t._y1,o=t._x2,u=t._y2;if(t._l01_a>r.Ho){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);i=(i*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,a=(a*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>r.Ho){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,l=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-e*t._l12_2a)/l,u=(u*f+t._y1*t._l23_2a-n*t._l12_2a)/l}t._context.bezierCurveTo(i,a,o,u,t._x2,t._y2)}function o(t,e){this._context=t,this._alpha=e}o.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:a(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const u=function t(e){function n(t){return e?new o(t,e):new i.pC(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},85578:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(91931),i=n(69706),a=n(74924);function o(t,e){this._context=t,this._alpha=e}o.prototype={areaStart:i.Z,areaEnd:i.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:(0,a.x)(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const u=function t(e){function n(t){return e?new o(t,e):new r.U(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},74129:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(42688),i=n(74924);function a(t,e){this._context=t,this._alpha=e}a.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:(0,i.x)(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const o=function t(e){function n(t){return e?new a(t,e):new r.T(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},20651:(t,e,n)=>{"use strict";function r(t){this._context=t}function i(t){return new r(t)}n.d(e,{Z:()=>i}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}}},71219:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(69706);function i(t){this._context=t}function a(t){return new i(t)}i.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}}},27266:(t,e,n)=>{"use strict";function r(t){return t<0?-1:1}function i(t,e,n){var i=t._x1-t._x0,a=e-t._x1,o=(t._y1-t._y0)/(i||a<0&&-0),u=(n-t._y1)/(a||i<0&&-0),s=(o*a+u*i)/(i+a);return(r(o)+r(u))*Math.min(Math.abs(o),Math.abs(u),.5*Math.abs(s))||0}function a(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function o(t,e,n){var r=t._x0,i=t._y0,a=t._x1,o=t._y1,u=(a-r)/3;t._context.bezierCurveTo(r+u,i+u*e,a-u,o-u*n,a,o)}function u(t){this._context=t}function s(t){this._context=new c(t)}function c(t){this._context=t}function f(t){return new u(t)}function l(t){return new s(t)}n.d(e,{Z:()=>f,s:()=>l}),u.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:o(this,this._t0,a(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,o(this,a(this,n=i(this,t,e)),n);break;default:o(this,this._t0,n=i(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}},(s.prototype=Object.create(u.prototype)).point=function(t,e){u.prototype.point.call(this,e,t)},c.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,i,a){this._context.bezierCurveTo(e,t,r,n,a,i)}}},43276:(t,e,n)=>{"use strict";function r(t){this._context=t}function i(t){var e,n,r=t.length-1,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;ea}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=i(t),a=i(e),o=0,u=1;u{"use strict";n.d(e,{j:()=>r,Z:()=>a});var r=a(n(20651).Z);function i(t){this._curve=t}function a(t){function e(e){return new i(t(e))}return e._curve=t,e}i.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}}},45742:(t,e,n)=>{"use strict";function r(t,e){this._context=t,this._t=e}function i(t){return new r(t,.5)}function a(t){return new r(t,0)}function o(t){return new r(t,1)}n.d(e,{ZP:()=>i,RN:()=>a,cD:()=>o}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}}},57119:(t,e,n)=>{"use strict";function r(t,e){return et?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},75435:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},33764:(t,e,n)=>{"use strict";if(n.d(e,{Nb:()=>r.Z,SO:()=>i.Z,jv:()=>a.Z,ve:()=>o.Z,am:()=>u.Z,N1:()=>u.Z,XB:()=>s.Z,aJ:()=>s.Z,Hs:()=>c.Z,h5:()=>f.h5,rR:()=>f.rR,M4:()=>f.M4,NA:()=>l.Z,uH:()=>l.u,JF:()=>h.Z,tJ:()=>d.Z,rZ:()=>p.Z,m_:()=>v.Z,Hm:()=>g.Z,P6:()=>_.Z,n3:()=>b.Z,Dt:()=>y.Z,WQ:()=>m.Z,$0:()=>x.ZP,tF:()=>w.Z,Ov:()=>Z.Z,dC:()=>D.Z,YY:()=>k.ZP,fG:()=>E.Z,$m:()=>A.Z,zg:()=>j.Z,fx:()=>C.Z,c_:()=>M.Z,Fd:()=>F.Z,ak:()=>F.s,Sx:()=>B.Z,eA:()=>S.ZP,js:()=>S.cD,iJ:()=>S.RN,kn:()=>N.Z,pB:()=>T.Z,W$:()=>z.Z,HL:()=>O.Z,Ku:()=>R.Z,YG:()=>P.Z,mG:()=>I.Z,$K:()=>L.Z,IX:()=>U.Z,FP:()=>$.Z,Qx:()=>H.Z,cY:()=>q.Z}),826==n.j)var r=n(38764);if(826==n.j)var i=n(79493);if(826==n.j)var a=n(79767);if(826==n.j)var o=n(95937);if(826==n.j)var u=n(69896);if(826==n.j)var s=n(8329);if(826==n.j)var c=n(3326);if(826==n.j)var f=n(72215);if(826==n.j)var l=n(24037);if(826==n.j)var h=n(62628);if(826==n.j)var d=n(9135);if(826==n.j)var p=n(82893);if(826==n.j)var v=n(44523);if(826==n.j)var g=n(86707);if(826==n.j)var _=n(42965);if(826==n.j)var b=n(60598);if(826==n.j)var y=n(25972);if(826==n.j)var m=n(541);if(826==n.j)var x=n(6023);if(826==n.j)var w=n(94244);if(826==n.j)var Z=n(91931);if(826==n.j)var D=n(42688);if(826==n.j)var k=n(46385);if(826==n.j)var E=n(85578);if(826==n.j)var A=n(74129);if(826==n.j)var j=n(74924);if(826==n.j)var C=n(71219);if(826==n.j)var M=n(20651);if(826==n.j)var F=n(27266);if(826==n.j)var B=n(43276);if(826==n.j)var S=n(45742);if(826==n.j)var N=n(98926);if(826==n.j)var T=n(22254);if(826==n.j)var z=n(76751);if(826==n.j)var O=n(90541);if(826==n.j)var R=n(36538);if(826==n.j)var P=n(34928);if(826==n.j)var I=n(42467);if(826==n.j)var L=n(19721);if(826==n.j)var U=n(82564);if(826==n.j)var $=n(12197);if(826==n.j)var H=n(81182);if(826==n.j)var q=n(40277)},79767:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(20651);if(826==n.j)var o=n(11053);function u(){var t=o.x,e=o.y,n=(0,i.Z)(!0),u=null,s=a.Z,c=null;function f(i){var a,o,f,l=i.length,h=!1;for(null==u&&(c=s(f=(0,r.Z)())),a=0;a<=l;++a)!(a{"use strict";if(n.d(e,{X:()=>a,Z:()=>o}),826==n.j)var r=n(23165);if(826==n.j)var i=n(79767);function a(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e((0,r.Z)(t)):e()._curve},t}function o(){return a((0,i.Z)().curve(r.j))}},72215:(t,e,n)=>{"use strict";if(n.d(e,{h5:()=>p,rR:()=>v,M4:()=>g}),826==n.j)var r=n(91672);if(826==n.j)var i=n(72299);if(826==n.j)var a=n(33554);if(826==n.j)var o=n(11053);if(826==n.j)var u=n(3326);function s(t){return t.source}function c(t){return t.target}function f(t){var e=s,n=c,u=o.x,f=o.y,l=null;function h(){var a,o=i.t.call(arguments),s=e.apply(this,o),c=n.apply(this,o);if(l||(l=a=(0,r.Z)()),t(l,+u.apply(this,(o[0]=s,o)),+f.apply(this,o),+u.apply(this,(o[0]=c,o)),+f.apply(this,o)),a)return l=null,a+""||null}return h.source=function(t){return arguments.length?(e=t,h):e},h.target=function(t){return arguments.length?(n=t,h):n},h.x=function(t){return arguments.length?(u="function"==typeof t?t:(0,a.Z)(+t),h):u},h.y=function(t){return arguments.length?(f="function"==typeof t?t:(0,a.Z)(+t),h):f},h.context=function(t){return arguments.length?(l=null==t?null:t,h):l},h}function l(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e=(e+r)/2,n,e,i,r,i)}function h(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e,n=(n+i)/2,r,n,r,i)}function d(t,e,n,r,i){var a=(0,u.Z)(e,n),o=(0,u.Z)(e,n=(n+i)/2),s=(0,u.Z)(r,n),c=(0,u.Z)(r,i);t.moveTo(a[0],a[1]),t.bezierCurveTo(o[0],o[1],s[0],s[1],c[0],c[1])}function p(){return f(l)}function v(){return f(h)}function g(){var t=f(d);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}},15:(t,e,n)=>{"use strict";n.d(e,{Wn:()=>r,fv:()=>i,mC:()=>a,Fp:()=>o,VV:()=>u,O$:()=>s,_b:()=>c,Ho:()=>f,pi:()=>l,ou:()=>h,BZ:()=>d,Kh:()=>p,ZR:()=>v});var r=Math.abs,i=Math.atan2,a=Math.cos,o=Math.max,u=Math.min,s=Math.sin,c=Math.sqrt,f=1e-12,l=Math.PI,h=l/2,d=2*l;function p(t){return t>1?0:t<-1?l:Math.acos(t)}function v(t){return t>=1?h:t<=-1?-h:Math.asin(t)}},69706:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},76751:(t,e,n)=>{"use strict";function r(t,e){if((u=t.length)>0)for(var n,r,i,a,o,u,s=0,c=t[e[0]].length;s0?(r[0]=a,r[1]=a+=i):i<0?(r[1]=o,r[0]=o+=i):(r[0]=0,r[1]=i)}n.d(e,{Z:()=>r})},22254:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((i=t.length)>0){for(var n,i,a,o=0,u=t[0].length;o{"use strict";function r(t,e){if((i=t.length)>1)for(var n,r,i,a=1,o=t[e[0]],u=o.length;ar})},36538:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((n=t.length)>0){for(var n,i=0,a=t[e[0]],o=a.length;i{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((a=t.length)>0&&(i=(n=t[e[0]]).length)>0){for(var n,i,a,o=0,u=1;u{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81182);function i(t){var e=t.map(a);return(0,r.Z)(t).sort((function(t,n){return e[t]-e[n]}))}function a(t){for(var e,n=-1,r=0,i=t.length,a=-1/0;++na&&(a=e,r=n);return r}},19721:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i,S:()=>a}),826==n.j)var r=n(81182);function i(t){var e=t.map(a);return(0,r.Z)(t).sort((function(t,n){return e[t]-e[n]}))}function a(t){for(var e,n=0,r=-1,i=t.length;++r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(19721);function i(t){return(0,r.Z)(t).reverse()}},12197:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(42467);if(826==n.j)var i=n(19721);function a(t){var e,n,a=t.length,o=t.map(i.S),u=(0,r.Z)(t),s=0,c=0,f=[],l=[];for(e=0;e{"use strict";function r(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}n.d(e,{Z:()=>r})},40277:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81182);function i(t){return(0,r.Z)(t).reverse()}},95937:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(33554);if(826==n.j)var i=n(57119);if(826==n.j)var a=n(75435);if(826==n.j)var o=n(15);function u(){var t=a.Z,e=i.Z,n=null,u=(0,r.Z)(0),s=(0,r.Z)(o.BZ),c=(0,r.Z)(0);function f(r){var i,a,f,l,h,d=r.length,p=0,v=new Array(d),g=new Array(d),_=+u.apply(this,arguments),b=Math.min(o.BZ,Math.max(-o.BZ,s.apply(this,arguments)-_)),y=Math.min(Math.abs(b)/d,c.apply(this,arguments)),m=y*(b<0?-1:1);for(i=0;i0&&(p+=h);for(null!=e?v.sort((function(t,n){return e(g[t],g[n])})):null!=n&&v.sort((function(t,e){return n(r[t],r[e])})),i=0,f=p?(b-d*m)/p:0;i0?h*f:0)+m,g[a]={data:r[a],index:i,value:h,startAngle:_,endAngle:l,padAngle:y};return g}return f.value=function(e){return arguments.length?(t="function"==typeof e?e:(0,r.Z)(+e),f):t},f.sortValues=function(t){return arguments.length?(e=t,n=null,f):e},f.sort=function(t){return arguments.length?(n=t,e=null,f):n},f.startAngle=function(t){return arguments.length?(u="function"==typeof t?t:(0,r.Z)(+t),f):u},f.endAngle=function(t){return arguments.length?(s="function"==typeof t?t:(0,r.Z)(+t),f):s},f.padAngle=function(t){return arguments.length?(c="function"==typeof t?t:(0,r.Z)(+t),f):c},f}},11053:(t,e,n)=>{"use strict";function r(t){return t[0]}function i(t){return t[1]}n.d(e,{x:()=>r,y:()=>i})},3326:(t,e,n)=>{"use strict";function r(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}n.d(e,{Z:()=>r})},98926:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(72299);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(90541);if(826==n.j)var o=n(81182);function u(t,e){return t[e]}function s(){var t=(0,i.Z)([]),e=o.Z,n=a.Z,s=u;function c(r){var i,a,o=t.apply(this,arguments),u=r.length,c=o.length,f=new Array(c);for(i=0;i{"use strict";if(n.d(e,{u:()=>h,Z:()=>d}),826==n.j)var r=n(91672);var i=n(62628),a=n(9135),o=n(82893),u=n(86707),s=n(44523),c=n(42965),f=n(60598);if(826==n.j)var l=n(33554);var h=[i.Z,a.Z,o.Z,s.Z,u.Z,c.Z,f.Z];function d(){var t=(0,l.Z)(i.Z),e=(0,l.Z)(64),n=null;function a(){var i;if(n||(n=i=(0,r.Z)()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(e){return arguments.length?(t="function"==typeof e?e:(0,l.Z)(e),a):t},a.size=function(t){return arguments.length?(e="function"==typeof t?t:(0,l.Z)(+t),a):e},a.context=function(t){return arguments.length?(n=null==t?null:t,a):n},a}},62628:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(15);const i={draw:function(t,e){var n=Math.sqrt(e/r.pi);t.moveTo(n,0),t.arc(0,0,n,0,r.BZ)}}},9135:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r={draw:function(t,e){var n=Math.sqrt(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}}},82893:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=Math.sqrt(1/3),i=2*r;const a={draw:function(t,e){var n=Math.sqrt(e/i),a=n*r;t.moveTo(0,-n),t.lineTo(a,0),t.lineTo(0,n),t.lineTo(-a,0),t.closePath()}}},44523:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r={draw:function(t,e){var n=Math.sqrt(e),r=-n/2;t.rect(r,r,n,n)}}},86707:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(15),i=Math.sin(r.pi/10)/Math.sin(7*r.pi/10),a=Math.sin(r.BZ/10)*i,o=-Math.cos(r.BZ/10)*i;const u={draw:function(t,e){var n=Math.sqrt(.8908130915292852*e),i=a*n,u=o*n;t.moveTo(0,-n),t.lineTo(i,u);for(var s=1;s<5;++s){var c=r.BZ*s/5,f=Math.cos(c),l=Math.sin(c);t.lineTo(l*n,-f*n),t.lineTo(f*i-l*u,l*i+f*u)}t.closePath()}}},42965:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=Math.sqrt(3);const i={draw:function(t,e){var n=-Math.sqrt(e/(3*r));t.moveTo(0,2*n),t.lineTo(-r*n,-n),t.lineTo(r*n,-n),t.closePath()}}},60598:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=-.5,i=Math.sqrt(3)/2,a=1/Math.sqrt(12),o=3*(a/2+1);const u={draw:function(t,e){var n=Math.sqrt(e/o),u=n/2,s=n*a,c=u,f=n*a+n,l=-c,h=f;t.moveTo(u,s),t.lineTo(c,f),t.lineTo(l,h),t.lineTo(r*u-i*s,i*u+r*s),t.lineTo(r*c-i*f,i*c+r*f),t.lineTo(r*l-i*h,i*l+r*h),t.lineTo(r*u+i*s,r*s-i*u),t.lineTo(r*c+i*f,r*f-i*c),t.lineTo(r*l+i*h,r*h-i*l),t.closePath()}}},49164:(t,e,n)=>{"use strict";n.d(e,{i$:()=>i,Z1:()=>a,g0:()=>o,wp:()=>u,ZP:()=>c});var r,i,a,o,u,s=n(30778);function c(t){return r=(0,s.Z)(t),i=r.format,a=r.parse,o=r.utcFormat,u=r.utcParse,r}c({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})},56221:(t,e,n)=>{"use strict";n.d(e,{Ds:()=>r.ZP,i$:()=>r.i$,Z1:()=>r.Z1,g0:()=>r.g0,wp:()=>r.wp,Dq:()=>i.Z,zh:()=>a.Z,ji:()=>o.Z});var r=n(49164);if(826==n.j)var i=n(30778);if(826==n.j)var a=n(25920);if(826==n.j)var o=n(77214)},25920:(t,e,n)=>{"use strict";n.d(e,{f:()=>i,Z:()=>o});var r=n(49164),i="%Y-%m-%dT%H:%M:%S.%LZ",a=Date.prototype.toISOString?function(t){return t.toISOString()}:(0,r.g0)(i);const o=826==n.j?a:null},77214:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(25920),i=n(49164),a=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:(0,i.wp)(r.f);const o=826==n.j?a:null},30778:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>h}),826==n.j)var r=n(97631);if(826==n.j)var i=n(12370);if(826==n.j)var a=n(76231);if(826==n.j)var o=n(68603);if(826==n.j)var u=n(97344);if(826==n.j)var s=n(2908);function c(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function f(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function l(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function h(t){var e=t.dateTime,n=t.date,u=t.time,s=t.periods,h=t.days,p=t.shortDays,v=t.months,g=t.shortMonths,_=y(s),b=m(s),J=y(h),bt=m(h),Mt=y(p),Ft=m(p),Bt=y(v),St=m(v),Nt=y(g),Tt=m(g),zt={a:function(t){return p[t.getDay()]},A:function(t){return h[t.getDay()]},b:function(t){return g[t.getMonth()]},B:function(t){return v[t.getMonth()]},c:null,d:L,e:L,f:Y,g:rt,G:at,H:U,I:$,j:H,L:q,m:W,M:V,p:function(t){return s[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:jt,s:Ct,S:G,u:X,U:K,V:Q,w:tt,W:et,x:null,X:null,y:nt,Y:it,Z:ot,"%":At},Ot={a:function(t){return p[t.getUTCDay()]},A:function(t){return h[t.getUTCDay()]},b:function(t){return g[t.getUTCMonth()]},B:function(t){return v[t.getUTCMonth()]},c:null,d:ut,e:ut,f:ht,g:Zt,G:kt,H:st,I:ct,j:ft,L:lt,m:dt,M:pt,p:function(t){return s[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:jt,s:Ct,S:vt,u:gt,U:_t,V:yt,w:mt,W:xt,x:null,X:null,y:wt,Y:Dt,Z:Et,"%":At},Rt={a:function(t,e,n){var r=Mt.exec(e.slice(n));return r?(t.w=Ft[r[0].toLowerCase()],n+r[0].length):-1},A:function(t,e,n){var r=J.exec(e.slice(n));return r?(t.w=bt[r[0].toLowerCase()],n+r[0].length):-1},b:function(t,e,n){var r=Nt.exec(e.slice(n));return r?(t.m=Tt[r[0].toLowerCase()],n+r[0].length):-1},B:function(t,e,n){var r=Bt.exec(e.slice(n));return r?(t.m=St[r[0].toLowerCase()],n+r[0].length):-1},c:function(t,n,r){return Lt(t,e,n,r)},d:F,e:F,f:O,g:A,G:E,H:S,I:S,j:B,L:z,m:M,M:N,p:function(t,e,n){var r=_.exec(e.slice(n));return r?(t.p=b[r[0].toLowerCase()],n+r[0].length):-1},q:C,Q:P,s:I,S:T,u:w,U:Z,V:D,w:x,W:k,x:function(t,e,r){return Lt(t,n,e,r)},X:function(t,e,n){return Lt(t,u,e,n)},y:A,Y:E,Z:j,"%":R};function Pt(t,e){return function(n){var r,i,a,o=[],u=-1,s=0,c=t.length;for(n instanceof Date||(n=new Date(+n));++u53)return null;"w"in h||(h.w=1),"Z"in h?(s=(u=f(l(h.y,0,1))).getUTCDay(),u=s>4||0===s?r.l6.ceil(u):(0,r.l6)(u),u=i.Z.offset(u,7*(h.V-1)),h.y=u.getUTCFullYear(),h.m=u.getUTCMonth(),h.d=u.getUTCDate()+(h.w+6)%7):(s=(u=c(l(h.y,0,1))).getDay(),u=s>4||0===s?a.wA.ceil(u):(0,a.wA)(u),u=o.Z.offset(u,7*(h.V-1)),h.y=u.getFullYear(),h.m=u.getMonth(),h.d=u.getDate()+(h.w+6)%7)}else("W"in h||"U"in h)&&("w"in h||(h.w="u"in h?h.u%7:"W"in h?1:0),s="Z"in h?f(l(h.y,0,1)).getUTCDay():c(l(h.y,0,1)).getDay(),h.m=0,h.d="W"in h?(h.w+6)%7+7*h.W-(s+5)%7:h.w+7*h.U-(s+6)%7);return"Z"in h?(h.H+=h.Z/100|0,h.M+=h.Z%100,f(h)):c(h)}}function Lt(t,e,n,r){for(var i,a,o=0,u=e.length,s=n.length;o=s)return-1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=Rt[i in d?e.charAt(o++):i])||(r=a(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}return zt.x=Pt(n,zt),zt.X=Pt(u,zt),zt.c=Pt(e,zt),Ot.x=Pt(n,Ot),Ot.X=Pt(u,Ot),Ot.c=Pt(e,Ot),{format:function(t){var e=Pt(t+="",zt);return e.toString=function(){return t},e},parse:function(t){var e=It(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=Pt(t+="",Ot);return e.toString=function(){return t},e},utcParse:function(t){var e=It(t+="",!0);return e.toString=function(){return t},e}}}var d={"-":"",_:" ",0:"0"},p=/^\s*\d+/,v=/^%/,g=/[\\^$*+?|[\]().{}]/g;function _(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",a=i.length;return r+(a68?1900:2e3),n+r[0].length):-1}function j(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function C(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function M(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function F(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function B(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function S(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function N(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function T(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function z(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function O(t,e,n){var r=p.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function R(t,e,n){var r=v.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function P(t,e,n){var r=p.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function I(t,e,n){var r=p.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function L(t,e){return _(t.getDate(),e,2)}function U(t,e){return _(t.getHours(),e,2)}function $(t,e){return _(t.getHours()%12||12,e,2)}function H(t,e){return _(1+o.Z.count((0,u.Z)(t),t),e,3)}function q(t,e){return _(t.getMilliseconds(),e,3)}function Y(t,e){return q(t,e)+"000"}function W(t,e){return _(t.getMonth()+1,e,2)}function V(t,e){return _(t.getMinutes(),e,2)}function G(t,e){return _(t.getSeconds(),e,2)}function X(t){var e=t.getDay();return 0===e?7:e}function K(t,e){return _(a.OM.count((0,u.Z)(t)-1,t),e,2)}function J(t){var e=t.getDay();return e>=4||0===e?(0,a.bL)(t):a.bL.ceil(t)}function Q(t,e){return t=J(t),_(a.bL.count((0,u.Z)(t),t)+(4===(0,u.Z)(t).getDay()),e,2)}function tt(t){return t.getDay()}function et(t,e){return _(a.wA.count((0,u.Z)(t)-1,t),e,2)}function nt(t,e){return _(t.getFullYear()%100,e,2)}function rt(t,e){return _((t=J(t)).getFullYear()%100,e,2)}function it(t,e){return _(t.getFullYear()%1e4,e,4)}function at(t,e){var n=t.getDay();return _((t=n>=4||0===n?(0,a.bL)(t):a.bL.ceil(t)).getFullYear()%1e4,e,4)}function ot(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+_(e/60|0,"0",2)+_(e%60,"0",2)}function ut(t,e){return _(t.getUTCDate(),e,2)}function st(t,e){return _(t.getUTCHours(),e,2)}function ct(t,e){return _(t.getUTCHours()%12||12,e,2)}function ft(t,e){return _(1+i.Z.count((0,s.Z)(t),t),e,3)}function lt(t,e){return _(t.getUTCMilliseconds(),e,3)}function ht(t,e){return lt(t,e)+"000"}function dt(t,e){return _(t.getUTCMonth()+1,e,2)}function pt(t,e){return _(t.getUTCMinutes(),e,2)}function vt(t,e){return _(t.getUTCSeconds(),e,2)}function gt(t){var e=t.getUTCDay();return 0===e?7:e}function _t(t,e){return _(r.Ox.count((0,s.Z)(t)-1,t),e,2)}function bt(t){var e=t.getUTCDay();return e>=4||0===e?(0,r.hB)(t):r.hB.ceil(t)}function yt(t,e){return t=bt(t),_(r.hB.count((0,s.Z)(t),t)+(4===(0,s.Z)(t).getUTCDay()),e,2)}function mt(t){return t.getUTCDay()}function xt(t,e){return _(r.l6.count((0,s.Z)(t)-1,t),e,2)}function wt(t,e){return _(t.getUTCFullYear()%100,e,2)}function Zt(t,e){return _((t=bt(t)).getUTCFullYear()%100,e,2)}function Dt(t,e){return _(t.getUTCFullYear()%1e4,e,4)}function kt(t,e){var n=t.getUTCDay();return _((t=n>=4||0===n?(0,r.hB)(t):r.hB.ceil(t)).getUTCFullYear()%1e4,e,4)}function Et(){return"+0000"}function At(){return"%"}function jt(t){return+t}function Ct(t){return Math.floor(+t/1e3)}},68603:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,a:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*i.yB)/i.UD}),(function(t){return t.getDate()-1}));const o=826==n.j?a:null;var u=a.range},1514:(t,e,n)=>{"use strict";n.d(e,{Ym:()=>r,yB:()=>i,Y2:()=>a,UD:()=>o,iM:()=>u});var r=1e3,i=6e4,a=36e5,o=864e5,u=6048e5},54076:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,i:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*i.Ym-t.getMinutes()*i.yB)}),(function(t,e){t.setTime(+t+e*i.Y2)}),(function(t,e){return(e-t)/i.Y2}),(function(t){return t.getHours()}));const o=826==n.j?a:null;var u=a.range},11365:(t,e,n)=>{"use strict";if(n.d(e,{JZ:()=>r.Z,U8:()=>i.Z,DG:()=>i.m,GK:()=>i.Z,An:()=>i.m,S1:()=>a.Z,BW:()=>a.m,OL:()=>a.Z,z1:()=>a.m,Z_:()=>o.Z,Xo:()=>o.L,WQ:()=>u.Z,w8:()=>u.i,rr:()=>s.Z,Nu:()=>s.a,NG:()=>c.OM,EN:()=>c.vm,Zy:()=>c.OM,WC:()=>c.vm,Ox:()=>c.wA,ip:()=>c.bJ,YD:()=>c.sy,RA:()=>c.aU,EF:()=>c.zg,S3:()=>c.Ld,Ig:()=>c.bL,Pl:()=>c.$t,y2:()=>c.mC,$N:()=>c.b$,Lq:()=>c.EY,X2:()=>c.Ff,F0:()=>f.Z,K_:()=>f.e,jB:()=>l.Z,HK:()=>l.g,rz:()=>h.Z,NH:()=>h.N,lM:()=>d.Z,Xt:()=>d.X,AN:()=>p.Z,yw:()=>p.y,YF:()=>v.Ox,_T:()=>v.SU,pI:()=>v.Ox,SU:()=>v.SU,l6:()=>v.l6,$3:()=>v.$3,J1:()=>v.J1,DK:()=>v.DK,b3:()=>v.b3,uy:()=>v.uy,hB:()=>v.hB,xj:()=>v.xj,QQ:()=>v.QQ,fz:()=>v.fz,g4:()=>v.g4,Q_:()=>v.Q_,me:()=>g.Z,Ks:()=>g.K,ol:()=>_.Z,DX:()=>_.D}),826==n.j)var r=n(22179);if(826==n.j)var i=n(30356);if(826==n.j)var a=n(52546);if(826==n.j)var o=n(18450);if(826==n.j)var u=n(54076);if(826==n.j)var s=n(68603);if(826==n.j)var c=n(76231);if(826==n.j)var f=n(50690);if(826==n.j)var l=n(97344);if(826==n.j)var h=n(52004);if(826==n.j)var d=n(28239);if(826==n.j)var p=n(12370);if(826==n.j)var v=n(97631);if(826==n.j)var g=n(94758);if(826==n.j)var _=n(2908)},22179:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=new Date,i=new Date;function a(t,e,n,o){function u(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return u.floor=function(e){return t(e=new Date(+e)),e},u.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},u.round=function(t){var e=u(t),n=u.ceil(t);return t-e0))return o;do{o.push(a=new Date(+n)),e(n,i),t(n)}while(a=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(u.count=function(e,a){return r.setTime(+e),i.setTime(+a),t(r),t(i),Math.floor(n(r,i))},u.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?u.filter(o?function(e){return o(e)%t==0}:function(e){return u.count(0,e)%t==0}):u:null}),u}},30356:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,m:()=>o});var r=n(22179),i=(0,r.Z)((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?(0,r.Z)((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):i:null};const a=826==n.j?i:null;var o=i.range},18450:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,L:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*i.Ym)}),(function(t,e){t.setTime(+t+e*i.yB)}),(function(t,e){return(e-t)/i.yB}),(function(t){return t.getMinutes()}));const o=826==n.j?a:null;var u=a.range},50690:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,e:()=>a});var r=(0,n(22179).Z)((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const i=826==n.j?r:null;var a=r.range},52546:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,m:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*i.Ym)}),(function(t,e){return(e-t)/i.Ym}),(function(t){return t.getUTCSeconds()}));const o=826==n.j?a:null;var u=a.range},12370:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,y:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/i.UD}),(function(t){return t.getUTCDate()-1}));const o=826==n.j?a:null;var u=a.range},28239:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,X:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*i.Y2)}),(function(t,e){return(e-t)/i.Y2}),(function(t){return t.getUTCHours()}));const o=826==n.j?a:null;var u=a.range},52004:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,N:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*i.yB)}),(function(t,e){return(e-t)/i.yB}),(function(t){return t.getUTCMinutes()}));const o=826==n.j?a:null;var u=a.range},94758:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,K:()=>a});var r=(0,n(22179).Z)((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const i=826==n.j?r:null;var a=r.range},97631:(t,e,n)=>{"use strict";n.d(e,{Ox:()=>o,l6:()=>u,J1:()=>s,b3:()=>c,hB:()=>f,QQ:()=>l,g4:()=>h,SU:()=>d,$3:()=>p,DK:()=>v,uy:()=>g,xj:()=>_,fz:()=>b,Q_:()=>y});var r=n(22179),i=n(1514);function a(t){return(0,r.Z)((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/i.iM}))}var o=a(0),u=a(1),s=a(2),c=a(3),f=a(4),l=a(5),h=a(6),d=o.range,p=u.range,v=s.range,g=c.range,_=f.range,b=l.range,y=h.range},2908:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,D:()=>o});var r=n(22179),i=(0,r.Z)((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));i.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const a=826==n.j?i:null;var o=i.range},76231:(t,e,n)=>{"use strict";n.d(e,{OM:()=>o,wA:()=>u,sy:()=>s,zg:()=>c,bL:()=>f,mC:()=>l,EY:()=>h,vm:()=>d,bJ:()=>p,aU:()=>v,Ld:()=>g,$t:()=>_,b$:()=>b,Ff:()=>y});var r=n(22179),i=n(1514);function a(t){return(0,r.Z)((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*i.yB)/i.iM}))}var o=a(0),u=a(1),s=a(2),c=a(3),f=a(4),l=a(5),h=a(6),d=o.range,p=u.range,v=s.range,g=c.range,_=f.range,b=l.range,y=h.range},97344:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,g:()=>o});var r=n(22179),i=(0,r.Z)((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));i.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const a=826==n.j?i:null;var o=i.range},48050:(t,e,n)=>{"use strict";if(n.d(e,{zO:()=>r.zO,HT:()=>r.HT,R8:()=>r.R8,Vs:()=>i.Z,FG:()=>a.Z}),826==n.j)var r=n(51852);if(826==n.j)var i=n(58148);if(826==n.j)var a=n(30419)},30419:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(51852);function i(t,e,n){var i=new r.B7,a=e;return null==e?(i.restart(t,e,n),i):(e=+e,n=null==n?(0,r.zO)():+n,i.restart((function r(o){o+=a,i.restart(r,a+=e,n),t(o)}),e,n),i)}},58148:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(51852);function i(t,e,n){var i=new r.B7;return e=null==e?0:+e,i.restart((function(n){i.stop(),t(n+e)}),e,n),i}},51852:(t,e,n)=>{"use strict";n.d(e,{zO:()=>d,B7:()=>v,HT:()=>g,R8:()=>_});var r,i,a=0,o=0,u=0,s=0,c=0,f=0,l="object"==typeof performance&&performance.now?performance:Date,h="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function d(){return c||(h(p),c=l.now()+f)}function p(){c=0}function v(){this._call=this._time=this._next=null}function g(t,e,n){var r=new v;return r.restart(t,e,n),r}function _(){d(),++a;for(var t,e=r;e;)(t=c-e._time)>=0&&e._call.call(null,t),e=e._next;--a}function b(){c=(s=l.now())+f,a=o=0;try{_()}finally{a=0,function(){for(var t,e,n=r,a=1/0;n;)n._call?(a>n._time&&(a=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:r=e);i=t,m(a)}(),c=0}}function y(){var t=l.now(),e=t-s;e>1e3&&(f-=e,s=t)}function m(t){a||(o&&(o=clearTimeout(o)),t-c>24?(t<1/0&&(o=setTimeout(b,t-l.now()-f)),u&&(u=clearInterval(u))):(u||(s=l.now(),u=setInterval(y,1e3)),a=1,h(b)))}v.prototype=g.prototype={constructor:v,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?d():+n)+(null==e?0:+e),this._next||i===this||(i?i._next=this:r=this,i=this),this._call=t,this._time=n,m()},stop:function(){this._call&&(this._call=null,this._time=1/0,m())}}},81321:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},16751:(t,e,n)=>{"use strict";function r(t){return t[0]}function i(t){return t[1]}n.d(e,{x:()=>r,y:()=>i})},4864:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},9103:(t,e,n)=>{"use strict";function r(t,e,n){this.target=t,this.type=e,this.transform=n}n.d(e,{Z:()=>r})},39492:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},71462:(t,e,n)=>{"use strict";n.r(e),n.d(e,{FormatSpecifier:()=>gn.vr,active:()=>kt,arc:()=>li.Nb,area:()=>li.SO,areaRadial:()=>li.am,ascending:()=>i.j2,autoType:()=>Xe.rA,axisBottom:()=>g,axisLeft:()=>_,axisRight:()=>v,axisTop:()=>p,bisect:()=>i.b4,bisectLeft:()=>i.Nw,bisectRight:()=>i.ml,bisector:()=>i.YF,blob:()=>Je.Ik,brush:()=>Qt,brushSelection:()=>Xt,brushX:()=>Kt,brushY:()=>Jt,buffer:()=>Je.f3,chord:()=>se,clientPoint:()=>fi.Eb,cluster:()=>bn.ki,color:()=>Ne.$_,contourDensity:()=>We,contours:()=>Ue,create:()=>fi.Ue,creator:()=>fi.Du,cross:()=>i.kC,csv:()=>Je.gy,csvFormat:()=>Xe.Sf,csvFormatBody:()=>Xe.S,csvFormatRow:()=>Xe.fh,csvFormatRows:()=>Xe.Jb,csvFormatValue:()=>Xe.eX,csvParse:()=>Xe.ue,csvParseRows:()=>Xe.Bj,cubehelix:()=>Ne.K,curveBasis:()=>li.$0,curveBasisClosed:()=>li.Dt,curveBasisOpen:()=>li.WQ,curveBundle:()=>li.tF,curveCardinal:()=>li.YY,curveCardinalClosed:()=>li.Ov,curveCardinalOpen:()=>li.dC,curveCatmullRom:()=>li.zg,curveCatmullRomClosed:()=>li.fG,curveCatmullRomOpen:()=>li.$m,curveLinear:()=>li.c_,curveLinearClosed:()=>li.fx,curveMonotoneX:()=>li.Fd,curveMonotoneY:()=>li.ak,curveNatural:()=>li.Sx,curveStep:()=>li.eA,curveStepAfter:()=>li.js,curveStepBefore:()=>li.iJ,customEvent:()=>fi._H,descending:()=>i.$1,deviation:()=>i.P3,dispatch:()=>Ve.W,drag:()=>Ge.oh,dragDisable:()=>Ge.Kn,dragEnable:()=>Ge.eF,dsv:()=>Je.Ds,dsvFormat:()=>Xe.yv,easeBack:()=>Ke.bW,easeBackIn:()=>Ke.gp,easeBackInOut:()=>Ke.gI,easeBackOut:()=>Ke.ZN,easeBounce:()=>Ke.sf,easeBounceIn:()=>Ke.RK,easeBounceInOut:()=>Ke.hE,easeBounceOut:()=>Ke.qj,easeCircle:()=>Ke.Xe,easeCircleIn:()=>Ke.kO,easeCircleInOut:()=>Ke.sq,easeCircleOut:()=>Ke.te,easeCubic:()=>Ke.LU,easeCubicIn:()=>Ke.HU,easeCubicInOut:()=>Ke.cC,easeCubicOut:()=>Ke.oS,easeElastic:()=>Ke.Az,easeElasticIn:()=>Ke.aM,easeElasticInOut:()=>Ke.H1,easeElasticOut:()=>Ke.Px,easeExp:()=>Ke.Ll,easeExpIn:()=>Ke.uY,easeExpInOut:()=>Ke.nm,easeExpOut:()=>Ke.mf,easeLinear:()=>Ke.Ny,easePoly:()=>Ke.m2,easePolyIn:()=>Ke.Tf,easePolyInOut:()=>Ke.z5,easePolyOut:()=>Ke.Ct,easeQuad:()=>Ke.uw,easeQuadIn:()=>Ke.V_,easeQuadInOut:()=>Ke.Tu,easeQuadOut:()=>Ke.mm,easeSin:()=>Ke.Tl,easeSinIn:()=>Ke.tl,easeSinInOut:()=>Ke.v,easeSinOut:()=>Ke.p4,entries:()=>Se.Z,event:()=>fi.B,extent:()=>i.We,forceCenter:()=>Qe.Z,forceCollide:()=>tn.Z,forceLink:()=>on,forceManyBody:()=>hn,forceRadial:()=>dn.Z,forceSimulation:()=>ln,forceX:()=>pn.Z,forceY:()=>vn.Z,format:()=>gn.WU,formatDefaultLocale:()=>gn.Zq,formatLocale:()=>gn.FF,formatPrefix:()=>gn.jH,formatSpecifier:()=>gn.YQ,geoAlbers:()=>_n.FW,geoAlbersUsa:()=>_n.wk,geoArea:()=>_n.ID,geoAzimuthalEqualArea:()=>_n.Rf,geoAzimuthalEqualAreaRaw:()=>_n.fN,geoAzimuthalEquidistant:()=>_n.aM,geoAzimuthalEquidistantRaw:()=>_n.dz,geoBounds:()=>_n.qT,geoCentroid:()=>_n.cS,geoCircle:()=>_n.ub,geoClipAntimeridian:()=>_n.o6,geoClipCircle:()=>_n.Fh,geoClipExtent:()=>_n.iM,geoClipRectangle:()=>_n.LF,geoConicConformal:()=>_n.tJ,geoConicConformalRaw:()=>_n.W$,geoConicEqualArea:()=>_n.ET,geoConicEqualAreaRaw:()=>_n.SQ,geoConicEquidistant:()=>_n.ah,geoConicEquidistantRaw:()=>_n.nh,geoContains:()=>_n.xk,geoDistance:()=>_n.gD,geoEqualEarth:()=>_n.bf,geoEqualEarthRaw:()=>_n.bw,geoEquirectangular:()=>_n.ES,geoEquirectangularRaw:()=>_n.Hw,geoGnomonic:()=>_n.Bq,geoGnomonicRaw:()=>_n.ot,geoGraticule:()=>_n.S,geoGraticule10:()=>_n.HV,geoIdentity:()=>_n.NL,geoInterpolate:()=>_n.iG,geoLength:()=>_n.Jp,geoMercator:()=>_n.mw,geoMercatorRaw:()=>_n.z,geoNaturalEarth1:()=>_n.li,geoNaturalEarth1Raw:()=>_n.Bh,geoOrthographic:()=>_n.Wv,geoOrthographicRaw:()=>_n.jx,geoPath:()=>_n.l4,geoProjection:()=>_n.OA,geoProjectionMutator:()=>_n.gv,geoRotation:()=>_n.w7,geoStereographic:()=>_n.kn,geoStereographicRaw:()=>_n.PA,geoStream:()=>_n.HZ,geoTransform:()=>_n.jD,geoTransverseMercator:()=>_n.Il,geoTransverseMercatorRaw:()=>_n.GN,gray:()=>Ne.MA,hcl:()=>Ne.Uc,hierarchy:()=>bn.bT,histogram:()=>i.KX,hsl:()=>Ne.Ym,html:()=>Je.dy,image:()=>Je.BH,interpolate:()=>yn.sX,interpolateArray:()=>yn.Ck,interpolateBasis:()=>yn.nH,interpolateBasisClosed:()=>yn.FO,interpolateBlues:()=>ci.sY,interpolateBrBG:()=>ci.yl,interpolateBuGn:()=>ci.pl,interpolateBuPu:()=>ci.hb,interpolateCividis:()=>ci.r1,interpolateCool:()=>ci.vc,interpolateCubehelix:()=>yn.Ji,interpolateCubehelixDefault:()=>ci.yB,interpolateCubehelixLong:()=>yn.tR,interpolateDate:()=>yn.NW,interpolateDiscrete:()=>yn.Tp,interpolateGnBu:()=>ci.Xw,interpolateGreens:()=>ci.M,interpolateGreys:()=>ci.A_,interpolateHcl:()=>yn.JH,interpolateHclLong:()=>yn.Yr,interpolateHsl:()=>yn.US,interpolateHslLong:()=>yn.H,interpolateHue:()=>yn.EP,interpolateInferno:()=>ci.sN,interpolateLab:()=>yn.uU,interpolateMagma:()=>ci.Gi,interpolateNumber:()=>yn.k4,interpolateNumberArray:()=>yn.qN,interpolateObject:()=>yn.IW,interpolateOrRd:()=>ci.RZ,interpolateOranges:()=>ci.n$,interpolatePRGn:()=>ci.nn,interpolatePiYG:()=>ci.qw,interpolatePlasma:()=>ci.iA,interpolatePuBu:()=>ci.GM,interpolatePuBuGn:()=>ci.S7,interpolatePuOr:()=>ci.xN,interpolatePuRd:()=>ci.cU,interpolatePurples:()=>ci.XW,interpolateRainbow:()=>ci.IC,interpolateRdBu:()=>ci.De,interpolateRdGy:()=>ci.PL,interpolateRdPu:()=>ci.A4,interpolateRdYlBu:()=>ci.zJ,interpolateRdYlGn:()=>ci.BT,interpolateReds:()=>ci.bc,interpolateRgb:()=>yn.LX,interpolateRgbBasis:()=>yn.u1,interpolateRgbBasisClosed:()=>yn.F5,interpolateRound:()=>yn.uL,interpolateSinebow:()=>ci.OO,interpolateSpectral:()=>ci.T0,interpolateString:()=>yn.IT,interpolateTransformCss:()=>yn.Yb,interpolateTransformSvg:()=>yn.wL,interpolateTurbo:()=>ci._B,interpolateViridis:()=>ci.V,interpolateWarm:()=>ci.AO,interpolateYlGn:()=>ci.aE,interpolateYlGnBu:()=>ci.Ht,interpolateYlOrBr:()=>ci.Y_,interpolateYlOrRd:()=>ci.cj,interpolateZoom:()=>yn.JX,interrupt:()=>N,interval:()=>pi.FG,isoFormat:()=>di.zh,isoParse:()=>di.ji,json:()=>Je.AV,keys:()=>Fe.Z,lab:()=>Ne.Nn,lch:()=>Ne.tW,line:()=>li.jv,lineRadial:()=>li.XB,linkHorizontal:()=>li.h5,linkRadial:()=>li.M4,linkVertical:()=>li.rR,local:()=>fi.I_,map:()=>xe,matcher:()=>fi.C2,max:()=>i.Fp,mean:()=>i.J6,median:()=>i.C2,merge:()=>i.TS,min:()=>i.VV,mouse:()=>fi.Jz,namespace:()=>fi.uD,namespaces:()=>fi.aC,nest:()=>we,now:()=>pi.zO,pack:()=>bn.P2,packEnclose:()=>bn.O1,packSiblings:()=>bn.jA,pairs:()=>i.X,partition:()=>bn.uK,path:()=>mn.E,permute:()=>i.FO,pie:()=>li.ve,piecewise:()=>yn.sO,pointRadial:()=>li.Hs,polygonArea:()=>xn.mI,polygonCentroid:()=>xn.tO,polygonContains:()=>xn.Q6,polygonHull:()=>xn.WF,polygonLength:()=>xn.NZ,precisionFixed:()=>gn.zB,precisionPrefix:()=>gn.S5,precisionRound:()=>gn.F0,quadtree:()=>wn.T,quantile:()=>i.VR,quantize:()=>yn.q$,radialArea:()=>li.N1,radialLine:()=>li.aJ,randomBates:()=>jn,randomExponential:()=>Cn,randomIrwinHall:()=>An,randomLogNormal:()=>En,randomNormal:()=>kn,randomUniform:()=>Dn,range:()=>i.w6,rgb:()=>Ne.B8,ribbon:()=>_e,scaleBand:()=>zn,scaleDiverging:()=>ii,scaleDivergingLog:()=>ai,scaleDivergingPow:()=>ui,scaleDivergingSqrt:()=>si,scaleDivergingSymlog:()=>oi,scaleIdentity:()=>ar,scaleImplicit:()=>Nn,scaleLinear:()=>ir,scaleLog:()=>pr,scaleOrdinal:()=>Tn,scalePoint:()=>Rn,scalePow:()=>Zr,scaleQuantile:()=>kr,scaleQuantize:()=>Er,scaleSequential:()=>Kr,scaleSequentialLog:()=>Jr,scaleSequentialPow:()=>ti,scaleSequentialQuantile:()=>ni,scaleSequentialSqrt:()=>ei,scaleSequentialSymlog:()=>Qr,scaleSqrt:()=>Dr,scaleSymlog:()=>br,scaleThreshold:()=>Ar,scaleTime:()=>Lr,scaleUtc:()=>Vr,scan:()=>i.Rp,schemeAccent:()=>ci.Mr,schemeBlues:()=>ci.KH,schemeBrBG:()=>ci.QA,schemeBuGn:()=>ci.S1,schemeBuPu:()=>ci.DQ,schemeCategory10:()=>ci.Cn,schemeDark2:()=>ci.Xg,schemeGnBu:()=>ci.AT,schemeGreens:()=>ci.Yo,schemeGreys:()=>ci.bU,schemeOrRd:()=>ci.MX,schemeOranges:()=>ci.P0,schemePRGn:()=>ci.Uh,schemePaired:()=>ci.xH,schemePastel1:()=>ci.rp,schemePastel2:()=>ci.i4,schemePiYG:()=>ci.Lx,schemePuBu:()=>ci.UV,schemePuBuGn:()=>ci.g1,schemePuOr:()=>ci.$K,schemePuRd:()=>ci.F6,schemePurples:()=>ci.DR,schemeRdBu:()=>ci.HW,schemeRdGy:()=>ci.u_,schemeRdPu:()=>ci.zs,schemeRdYlBu:()=>ci.XX,schemeRdYlGn:()=>ci.Kr,schemeReds:()=>ci.zU,schemeSet1:()=>ci.yK,schemeSet2:()=>ci.W1,schemeSet3:()=>ci.UC,schemeSpectral:()=>ci.lq,schemeTableau10:()=>ci.K2,schemeYlGn:()=>ci.GE,schemeYlGnBu:()=>ci.Yi,schemeYlOrBr:()=>ci.Gb,schemeYlOrRd:()=>ci.M7,select:()=>fi.Ys,selectAll:()=>fi.td,selection:()=>fi.f_,selector:()=>fi.nZ,selectorAll:()=>fi.UK,set:()=>Me,shuffle:()=>i.TV,stack:()=>li.kn,stackOffsetDiverging:()=>li.W$,stackOffsetExpand:()=>li.pB,stackOffsetNone:()=>li.HL,stackOffsetSilhouette:()=>li.Ku,stackOffsetWiggle:()=>li.YG,stackOrderAppearance:()=>li.mG,stackOrderAscending:()=>li.$K,stackOrderDescending:()=>li.IX,stackOrderInsideOut:()=>li.FP,stackOrderNone:()=>li.Qx,stackOrderReverse:()=>li.cY,stratify:()=>bn.QP,style:()=>fi.oB,sum:()=>i.Sm,svg:()=>Je.YP,symbol:()=>li.NA,symbolCircle:()=>li.JF,symbolCross:()=>li.tJ,symbolDiamond:()=>li.rZ,symbolSquare:()=>li.m_,symbolStar:()=>li.Hm,symbolTriangle:()=>li.P6,symbolWye:()=>li.n3,symbols:()=>li.uH,text:()=>Je.fL,thresholdFreedmanDiaconis:()=>i.o6,thresholdScott:()=>i.FA,thresholdSturges:()=>i._X,tickFormat:()=>nr,tickIncrement:()=>i.G9,tickStep:()=>i.ly,ticks:()=>i.sd,timeDay:()=>hi.rr,timeDays:()=>hi.Nu,timeFormat:()=>di.i$,timeFormatDefaultLocale:()=>di.Ds,timeFormatLocale:()=>di.Dq,timeFriday:()=>hi.y2,timeFridays:()=>hi.$N,timeHour:()=>hi.WQ,timeHours:()=>hi.w8,timeInterval:()=>hi.JZ,timeMillisecond:()=>hi.U8,timeMilliseconds:()=>hi.DG,timeMinute:()=>hi.Z_,timeMinutes:()=>hi.Xo,timeMonday:()=>hi.Ox,timeMondays:()=>hi.ip,timeMonth:()=>hi.F0,timeMonths:()=>hi.K_,timeParse:()=>di.Z1,timeSaturday:()=>hi.Lq,timeSaturdays:()=>hi.X2,timeSecond:()=>hi.S1,timeSeconds:()=>hi.BW,timeSunday:()=>hi.Zy,timeSundays:()=>hi.WC,timeThursday:()=>hi.Ig,timeThursdays:()=>hi.Pl,timeTuesday:()=>hi.YD,timeTuesdays:()=>hi.RA,timeWednesday:()=>hi.EF,timeWednesdays:()=>hi.S3,timeWeek:()=>hi.NG,timeWeeks:()=>hi.EN,timeYear:()=>hi.jB,timeYears:()=>hi.HK,timeout:()=>pi.Vs,timer:()=>pi.HT,timerFlush:()=>pi.R8,touch:()=>fi.Fq,touches:()=>fi.W4,transition:()=>yt,transpose:()=>i.p4,tree:()=>bn.G_,treemap:()=>bn.pN,treemapBinary:()=>bn.wL,treemapDice:()=>bn.LQ,treemapResquarify:()=>bn.eA,treemapSlice:()=>bn.Km,treemapSliceDice:()=>bn.E_,treemapSquarify:()=>bn.o$,tsv:()=>Je.pv,tsvFormat:()=>Xe.vP,tsvFormatBody:()=>Xe.uH,tsvFormatRow:()=>Xe.Hf,tsvFormatRows:()=>Xe.n5,tsvFormatValue:()=>Xe.sS,tsvParse:()=>Xe.tJ,tsvParseRows:()=>Xe.E0,utcDay:()=>hi.AN,utcDays:()=>hi.yw,utcFormat:()=>di.g0,utcFriday:()=>hi.QQ,utcFridays:()=>hi.fz,utcHour:()=>hi.lM,utcHours:()=>hi.Xt,utcMillisecond:()=>hi.GK,utcMilliseconds:()=>hi.An,utcMinute:()=>hi.rz,utcMinutes:()=>hi.NH,utcMonday:()=>hi.l6,utcMondays:()=>hi.$3,utcMonth:()=>hi.me,utcMonths:()=>hi.Ks,utcParse:()=>di.wp,utcSaturday:()=>hi.g4,utcSaturdays:()=>hi.Q_,utcSecond:()=>hi.OL,utcSeconds:()=>hi.z1,utcSunday:()=>hi.pI,utcSundays:()=>hi.SU,utcThursday:()=>hi.hB,utcThursdays:()=>hi.xj,utcTuesday:()=>hi.J1,utcTuesdays:()=>hi.DK,utcWednesday:()=>hi.b3,utcWednesdays:()=>hi.uy,utcWeek:()=>hi.YF,utcWeeks:()=>hi._T,utcYear:()=>hi.ol,utcYears:()=>hi.DX,values:()=>Be.Z,variance:()=>i.CA,version:()=>r,voronoi:()=>Ji,window:()=>fi.u9,xml:()=>Je.Ls,zip:()=>i.$R,zoom:()=>ha,zoomIdentity:()=>ra,zoomTransform:()=>ia});var r="5.16.0",i=n(58470),a=Array.prototype.slice,o=n(71603),u=1e-6;function s(t){return"translate("+(t+.5)+",0)"}function c(t){return"translate(0,"+(t+.5)+")"}function f(t){return function(e){return+t(e)}}function l(t){var e=Math.max(0,t.bandwidth()-1)/2;return t.round()&&(e=Math.round(e)),function(n){return+t(n)+e}}function h(){return!this.__axis}function d(t,e){var n=[],r=null,i=null,d=6,p=6,v=3,g=1===t||4===t?-1:1,_=4===t||2===t?"x":"y",b=1===t||3===t?s:c;function y(a){var s=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,c=null==i?e.tickFormat?e.tickFormat.apply(e,n):o.Z:i,y=Math.max(d,0)+v,m=e.range(),x=+m[0]+.5,w=+m[m.length-1]+.5,Z=(e.bandwidth?l:f)(e.copy()),D=a.selection?a.selection():a,k=D.selectAll(".domain").data([null]),E=D.selectAll(".tick").data(s,e).order(),A=E.exit(),j=E.enter().append("g").attr("class","tick"),C=E.select("line"),M=E.select("text");k=k.merge(k.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),E=E.merge(j),C=C.merge(j.append("line").attr("stroke","currentColor").attr(_+"2",g*d)),M=M.merge(j.append("text").attr("fill","currentColor").attr(_,g*y).attr("dy",1===t?"0em":3===t?"0.71em":"0.32em")),a!==D&&(k=k.transition(a),E=E.transition(a),C=C.transition(a),M=M.transition(a),A=A.transition(a).attr("opacity",u).attr("transform",(function(t){return isFinite(t=Z(t))?b(t):this.getAttribute("transform")})),j.attr("opacity",u).attr("transform",(function(t){var e=this.parentNode.__axis;return b(e&&isFinite(e=e(t))?e:Z(t))}))),A.remove(),k.attr("d",4===t||2==t?p?"M"+g*p+","+x+"H0.5V"+w+"H"+g*p:"M0.5,"+x+"V"+w:p?"M"+x+","+g*p+"V0.5H"+w+"V"+g*p:"M"+x+",0.5H"+w),E.attr("opacity",1).attr("transform",(function(t){return b(Z(t))})),C.attr(_+"2",g*d),M.attr(_,g*y).text(c),D.filter(h).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",2===t?"start":4===t?"end":"middle"),D.each((function(){this.__axis=Z}))}return y.scale=function(t){return arguments.length?(e=t,y):e},y.ticks=function(){return n=a.call(arguments),y},y.tickArguments=function(t){return arguments.length?(n=null==t?[]:a.call(t),y):n.slice()},y.tickValues=function(t){return arguments.length?(r=null==t?null:a.call(t),y):r&&r.slice()},y.tickFormat=function(t){return arguments.length?(i=t,y):i},y.tickSize=function(t){return arguments.length?(d=p=+t,y):d},y.tickSizeInner=function(t){return arguments.length?(d=+t,y):d},y.tickSizeOuter=function(t){return arguments.length?(p=+t,y):p},y.tickPadding=function(t){return arguments.length?(v=+t,y):v},y}function p(t){return d(1,t)}function v(t){return d(2,t)}function g(t){return d(3,t)}function _(t){return d(4,t)}var b=n(65264),y=n(61062),m=n(69777),x=n(13171),w=n(78011),Z=n(23475),D=n(42637),k=n(54632),E=n(51852),A=n(58148),j=(0,b.Z)("start","end","cancel","interrupt"),C=[];function M(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(s){var c,f,l,h;if(1!==n.state)return u();for(c in i)if((h=i[c]).name===n.name){if(3===h.state)return(0,A.Z)(a);4===h.state?(h.state=6,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[c]):+c0)throw new Error("too late; already scheduled");return n}function B(t,e){var n=S(t,e);if(n.state>3)throw new Error("too late; already running");return n}function S(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function N(t,e){var n,r,i,a=t.__transition,o=!0;if(a){for(i in e=null==e?null:e+"",a)(n=a[i]).name===e?(r=n.state>2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}var T=n(88994),z=n(69998);function O(t,e){var n,r;return function(){var i=B(this,t),a=i.tween;if(a!==n)for(var o=0,u=(r=n=a).length;o=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?F:B;return function(){var o=a(this,t),u=o.on;u!==r&&(i=(r=u).copy()).on(e,n),o.on=i}}var st=n(61566),ct=n(87393),ft=k.ZP.prototype.constructor,lt=n(34675);function ht(t){return function(){this.style.removeProperty(t)}}function dt(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function pt(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&dt(t,a,n)),r}return a._value=e,a}function vt(t){return function(e){this.textContent=t.call(this,e)}}function gt(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&vt(r)),e}return r._value=t,r}var _t=0;function bt(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function yt(t){return(0,k.ZP)().transition(t)}function mt(){return++_t}var xt=k.ZP.prototype;bt.prototype=yt.prototype={constructor:bt,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=(0,st.Z)(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o1&&n.name===e)return new bt([[t]],Dt,e,+r);return null}var Et=n(41989),At=n(14289),jt=n(78459),Ct={name:"drag"},Mt={name:"space"},Ft={name:"handle"},Bt={name:"center"};function St(t){return[+t[0],+t[1]]}function Nt(t){return[St(t[0]),St(t[1])]}function Tt(t){return function(e){return(0,x.Z)(e,w.B.touches,t)}}var zt={name:"x",handles:["w","e"].map(Ht),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Ot={name:"y",handles:["n","s"].map(Ht),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},Rt={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Ht),input:function(t){return null==t?null:Nt(t)},output:function(t){return t}},Pt={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},It={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},Lt={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Ut={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},$t={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Ht(t){return{type:t}}function qt(){return!w.B.ctrlKey&&!w.B.button}function Yt(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function Wt(){return navigator.maxTouchPoints||"ontouchstart"in this}function Vt(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Gt(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}function Xt(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Kt(){return te(zt)}function Jt(){return te(Ot)}function Qt(){return te(Rt)}function te(t){var e,n=Yt,r=qt,i=Wt,a=!0,o=(0,b.Z)("start","brush","end"),u=6;function s(e){var n=e.property("__brush",v).selectAll(".overlay").data([Ht("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",Pt.overlay).merge(n).each((function(){var t=Vt(this).extent;(0,Z.Z)(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([Ht("selection")]).enter().append("rect").attr("class","selection").attr("cursor",Pt.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return Pt[t.type]})),e.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function c(){var t=(0,Z.Z)(this),e=Vt(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-u/2:e[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-u/2:e[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function f(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new l(t,e,n):r}function l(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function h(){if((!e||w.B.touches)&&r.apply(this,arguments)){var n,i,o,u,s,l,h,d,p,v,g,_=this,b=w.B.target.__data__.type,m="selection"===(a&&w.B.metaKey?b="overlay":b)?Ct:a&&w.B.altKey?Bt:Ft,x=t===Ot?null:Ut[b],k=t===zt?null:$t[b],E=Vt(_),A=E.extent,j=E.selection,C=A[0][0],M=A[0][1],F=A[1][0],B=A[1][1],S=0,T=0,z=x&&k&&a&&w.B.shiftKey,O=w.B.touches?Tt(w.B.changedTouches[0].identifier):D.Z,R=O(_),P=R,I=f(_,arguments,!0).beforestart();"overlay"===b?(j&&(p=!0),E.selection=j=[[n=t===Ot?C:R[0],o=t===zt?M:R[1]],[s=t===Ot?F:n,h=t===zt?B:o]]):(n=j[0][0],o=j[0][1],s=j[1][0],h=j[1][1]),i=n,u=o,l=s,d=h;var L=(0,Z.Z)(_).attr("pointer-events","none"),U=L.selectAll(".overlay").attr("cursor",Pt[b]);if(w.B.touches)I.moved=H,I.ended=Y;else{var $=(0,Z.Z)(w.B.view).on("mousemove.brush",H,!0).on("mouseup.brush",Y,!0);a&&$.on("keydown.brush",W,!0).on("keyup.brush",V,!0),(0,y.Z)(w.B.view)}(0,jt.r)(),N(_),c.call(_),I.start()}function H(){var t=O(_);!z||v||g||(Math.abs(t[0]-P[0])>Math.abs(t[1]-P[1])?g=!0:v=!0),P=t,p=!0,(0,jt.Z)(),q()}function q(){var t;switch(S=P[0]-R[0],T=P[1]-R[1],m){case Mt:case Ct:x&&(S=Math.max(C-n,Math.min(F-s,S)),i=n+S,l=s+S),k&&(T=Math.max(M-o,Math.min(B-h,T)),u=o+T,d=h+T);break;case Ft:x<0?(S=Math.max(C-n,Math.min(F-n,S)),i=n+S,l=s):x>0&&(S=Math.max(C-s,Math.min(F-s,S)),i=n,l=s+S),k<0?(T=Math.max(M-o,Math.min(B-o,T)),u=o+T,d=h):k>0&&(T=Math.max(M-h,Math.min(B-h,T)),u=o,d=h+T);break;case Bt:x&&(i=Math.max(C,Math.min(F,n-S*x)),l=Math.max(C,Math.min(F,s+S*x))),k&&(u=Math.max(M,Math.min(B,o-T*k)),d=Math.max(M,Math.min(B,h+T*k)))}l0&&(n=i-S),k<0?h=d-T:k>0&&(o=u-T),m=Mt,U.attr("cursor",Pt.selection),q());break;default:return}(0,jt.Z)()}function V(){switch(w.B.keyCode){case 16:z&&(v=g=z=!1,q());break;case 18:m===Bt&&(x<0?s=l:x>0&&(n=i),k<0?h=d:k>0&&(o=u),m=Ft,q());break;case 32:m===Mt&&(w.B.altKey?(x&&(s=l-S*x,n=i+S*x),k&&(h=d-T*k,o=u+T*k),m=Bt):(x<0?s=l:x>0&&(n=i),k<0?h=d:k>0&&(o=u),m=Ft),U.attr("cursor",Pt[b]),q());break;default:return}(0,jt.Z)()}}function d(){f(this,arguments).moved()}function p(){f(this,arguments).ended()}function v(){var e=this.__brush||{selection:null};return e.extent=Nt(n.apply(this,arguments)),e.dim=t,e}return s.move=function(e,n){e.selection?e.on("start.brush",(function(){f(this,arguments).beforestart().start()})).on("interrupt.brush end.brush",(function(){f(this,arguments).end()})).tween("brush",(function(){var e=this,r=e.__brush,i=f(e,arguments),a=r.selection,o=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),u=(0,m.Z)(a,o);function s(t){r.selection=1===t&&null===o?null:u(t),c.call(e),i.brush()}return null!==a&&null!==o?s:s(1)})):e.each((function(){var e=this,r=arguments,i=e.__brush,a=t.input("function"==typeof n?n.apply(e,r):n,i.extent),o=f(e,r).beforestart();N(e),i.selection=null===a?null:a,c.call(e),o.start().brush().end()}))},s.clear=function(t){s.move(t,null)},l.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(){return this.starting?(this.starting=!1,this.emit("start")):this.emit("brush"),this},brush:function(){return this.emit("brush"),this},end:function(){return 0==--this.active&&(delete this.state.emitter,this.emit("end")),this},emit:function(e){(0,w._H)(new At.Z(s,e,t.output(this.state.selection)),o.apply,o,[e,this.that,this.args])}},s.extent=function(t){return arguments.length?(n="function"==typeof t?t:(0,Et.Z)(Nt(t)),s):n},s.filter=function(t){return arguments.length?(r="function"==typeof t?t:(0,Et.Z)(!!t),s):r},s.touchable=function(t){return arguments.length?(i="function"==typeof t?t:(0,Et.Z)(!!t),s):i},s.handleSize=function(t){return arguments.length?(u=+t,s):u},s.keyModifiers=function(t){return arguments.length?(a=!!t,s):a},s.on=function(){var t=o.on.apply(o,arguments);return t===o?s:t},s}var ee=Math.cos,ne=Math.sin,re=Math.PI,ie=re/2,ae=2*re,oe=Math.max;function ue(t){return function(e,n){return t(e.source.value+e.target.value,n.source.value+n.target.value)}}function se(){var t=0,e=null,n=null,r=null;function a(a){var o,u,s,c,f,l,h=a.length,d=[],p=(0,i.w6)(h),v=[],g=[],_=g.groups=new Array(h),b=new Array(h*h);for(o=0,f=-1;++f=r.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,c,f,l=-1,h=n.length,d=r[i++],p=xe(),v=o();++lr.length)return t;var a,u=i[n-1];return null!=e&&n>=r.length?a=t.entries():(a=[],t.each((function(t,e){a.push({key:e,values:o(t,n)})}))),null!=u?a.sort((function(t,e){return u(t.key,e.key)})):a}return n={object:function(t){return a(t,0,Ze,De)},map:function(t){return a(t,0,ke,Ee)},entries:function(t){return o(a(t,0,ke,Ee),0)},key:function(t){return r.push(t),n},sortKeys:function(t){return i[r.length-1]=t,n},sortValues:function(e){return t=e,n},rollup:function(t){return e=t,n}}}function Ze(){return{}}function De(t,e,n){t[e]=n}function ke(){return xe()}function Ee(t,e,n){t.set(e,n)}function Ae(){}var je=xe.prototype;function Ce(t,e){var n=new Ae;if(t instanceof Ae)t.each((function(t){n.add(t)}));else if(t){var r=-1,i=t.length;if(null==e)for(;++r=r,Le[c<<1].forEach(p);++a=r,Le[s|c<<1].forEach(p);for(Le[c<<0].forEach(p);++o=r,f=n[o*t]>=r,Le[c<<1|f<<2].forEach(p);++a=r,l=f,f=n[o*t+a+1]>=r,Le[s|c<<1|f<<2|l<<3].forEach(p);Le[c|f<<3].forEach(p)}for(a=-1,f=n[o*t]>=r,Le[f<<2].forEach(p);++a=r,Le[f<<2|l<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+a,t[0][1]+o],s=[t[1][0]+a,t[1][1]+o],c=u(r),f=u(s);(e=d[c])?(n=h[f])?(delete d[e.end],delete h[n.start],e===n?(e.ring.push(s),i(e.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete d[e.end],e.ring.push(s),d[e.end=f]=e):(e=h[f])?(n=d[c])?(delete h[e.start],delete d[n.end],e===n?(e.ring.push(s),i(e.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete h[e.start],e.ring.unshift(r),h[e.start=c]=e):h[c]=d[f]={start:c,end:f,ring:[r,s]}}Le[f<<3].forEach(p)}(n,i,(function(t){r(t,n,i),(0,Oe.Z)(t)>0?a.push([t]):o.push(t)})),o.forEach((function(t){for(var e,n=0,r=a.length;n0&&o0&&u0&&i>0))throw new Error("invalid size");return t=r,e=i,a},a.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?(0,Re.Z)(Te.call(t)):(0,Re.Z)(t),a):n},a.smooth=function(t){return arguments.length?(r=t?s:Ie.Z,a):r===s},a}var $e=n(5109);function He(t){return t[0]}function qe(t){return t[1]}function Ye(){return 1}function We(){var t=He,e=qe,n=Ye,r=960,a=500,o=20,u=2,s=3*o,c=r+2*s>>u,f=a+2*s>>u,l=(0,Re.Z)(20);function h(r){var a=new Float32Array(c*f),h=new Float32Array(c*f);r.forEach((function(r,i,o){var l=+t(r,i,o)+s>>u,h=+e(r,i,o)+s>>u,d=+n(r,i,o);l>=0&&l=0&&h>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u),(0,$e._)({width:c,height:f,data:a},{width:c,height:f,data:h},o>>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u),(0,$e._)({width:c,height:f,data:a},{width:c,height:f,data:h},o>>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u);var p=l(a);if(!Array.isArray(p)){var v=(0,i.Fp)(a);p=(0,i.ly)(0,v,p),(p=(0,i.w6)(0,Math.floor(v/p)*p,p)).shift()}return Ue().thresholds(p).size([c,f])(a).map(d)}function d(t){return t.value*=Math.pow(2,-2*u),t.coordinates.forEach(p),t}function p(t){t.forEach(v)}function v(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,u)-s,t[1]=t[1]*Math.pow(2,u)-s}function _(){return c=r+2*(s=3*o)>>u,f=a+2*s>>u,h}return h.x=function(e){return arguments.length?(t="function"==typeof e?e:(0,Re.Z)(+e),h):t},h.y=function(t){return arguments.length?(e="function"==typeof t?t:(0,Re.Z)(+t),h):e},h.weight=function(t){return arguments.length?(n="function"==typeof t?t:(0,Re.Z)(+t),h):n},h.size=function(t){if(!arguments.length)return[r,a];var e=Math.ceil(t[0]),n=Math.ceil(t[1]);if(!(e>=0||e>=0))throw new Error("invalid size");return r=e,a=n,_()},h.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return u=Math.floor(Math.log(t)/Math.LN2),_()},h.thresholds=function(t){return arguments.length?(l="function"==typeof t?t:Array.isArray(t)?(0,Re.Z)(Te.call(t)):(0,Re.Z)(t),h):l},h.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),_()},h}var Ve=n(10961),Ge=n(95520),Xe=n(83611),Ke=n(13756),Je=n(14413),Qe=n(71233),tn=n(47226),en=n(84442),nn=n(43266);function rn(t){return t.index}function an(t,e){var n=t.get(e);if(!n)throw new Error("missing: "+e);return n}function on(t){var e,n,r,i,a,o=rn,u=function(t){return 1/Math.min(i[t.source.index],i[t.target.index])},s=(0,en.Z)(30),c=1;function f(r){for(var i=0,o=t.length;i1?(null==n?u.remove(t):u.set(t,d(n)),e):u.get(t)},find:function(e,n,r){var i,a,o,u,s,c=0,f=t.length;for(null==r?r=1/0:r*=r,c=0;c1?(c.on(t,n),e):c.on(t)}}}function hn(){var t,e,n,r,i=(0,en.Z)(-30),a=1,o=1/0,u=.81;function s(r){var i,a=t.length,o=(0,un.Z)(t,sn,cn).visitAfter(f);for(n=r,i=0;i=o)){(t.data!==e||t.next)&&(0===f&&(d+=(f=(0,nn.Z)())*f),0===l&&(d+=(l=(0,nn.Z)())*l),d1);return t+n*a*Math.sqrt(-2*Math.log(i)/i)}}return n.source=t,n}(Zn),En=function t(e){function n(){var t=kn.source(e).apply(this,arguments);return function(){return Math.exp(t())}}return n.source=t,n}(Zn),An=function t(e){function n(t){return function(){for(var n=0,r=0;rr&&(e=n,n=r,r=e),function(t){return Math.max(n,Math.min(r,t))}}function Yn(t,e,n){var r=t[0],i=t[1],a=e[0],o=e[1];return i2?Wn:Yn,i=a=null,l}function l(e){return isNaN(e=+e)?n:(i||(i=r(o.map(t),u,s)))(t(c(e)))}return l.invert=function(n){return c(e((a||(a=r(u,o.map(t),L.Z)))(n)))},l.domain=function(t){return arguments.length?(o=Bn.call(t,Ln.Z),c===$n||(c=qn(o)),f()):o.slice()},l.range=function(t){return arguments.length?(u=Sn.call(t),f()):u.slice()},l.rangeRound=function(t){return u=Sn.call(t),s=Pn.Z,f()},l.clamp=function(t){return arguments.length?(c=t?qn(o):$n,l):c!==$n},l.interpolate=function(t){return arguments.length?(s=t,f()):s},l.unknown=function(t){return arguments.length?(n=t,l):n},function(n,r){return t=n,e=r,f()}}function Xn(t,e){return Gn()(t,e)}var Kn=n(47681),Jn=n(94735),Qn=n(46973),tr=n(54415),er=n(84418);function nr(t,e,n,r){var a,o=(0,i.ly)(t,e,n);switch((r=(0,Kn.Z)(null==r?",f":r)).type){case"s":var u=Math.max(Math.abs(t),Math.abs(e));return null!=r.precision||isNaN(a=(0,Jn.Z)(o,u))||(r.precision=a),(0,Qn.jH)(r,u);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(a=(0,tr.Z)(o,Math.max(Math.abs(t),Math.abs(e))))||(r.precision=a-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(a=(0,er.Z)(o))||(r.precision=a-2*("%"===r.type))}return(0,Qn.WU)(r)}function rr(t){var e=t.domain;return t.ticks=function(t){var n=e();return(0,i.sd)(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return nr(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var r,a=e(),o=0,u=a.length-1,s=a[o],c=a[u];return c0?(s=Math.floor(s/r)*r,c=Math.ceil(c/r)*r,r=(0,i.G9)(s,c,n)):r<0&&(s=Math.ceil(s*r)/r,c=Math.floor(c*r)/r,r=(0,i.G9)(s,c,n)),r>0?(a[o]=Math.floor(s/r)*r,a[u]=Math.ceil(c/r)*r,e(a)):r<0&&(a[o]=Math.ceil(s*r)/r,a[u]=Math.floor(c*r)/r,e(a)),t},t}function ir(){var t=Xn($n,$n);return t.copy=function(){return Vn(t,ir())},Mn.o.apply(t,arguments),rr(t)}function ar(t){var e;function n(t){return isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Bn.call(e,Ln.Z),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return ar(t).unknown(e)},t=arguments.length?Bn.call(t,Ln.Z):[0,1],rr(n)}var or=n(10070);function ur(t){return Math.log(t)}function sr(t){return Math.exp(t)}function cr(t){return-Math.log(-t)}function fr(t){return-Math.exp(-t)}function lr(t){return isFinite(t)?+("1e"+t):t<0?0:t}function hr(t){return function(e){return-t(-e)}}function dr(t){var e,n,r=t(ur,sr),a=r.domain,o=10;function u(){return e=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),function(e){return Math.log(e)/t})}(o),n=function(t){return 10===t?lr:t===Math.E?Math.exp:function(e){return Math.pow(t,e)}}(o),a()[0]<0?(e=hr(e),n=hr(n),t(cr,fr)):t(ur,sr),r}return r.base=function(t){return arguments.length?(o=+t,u()):o},r.domain=function(t){return arguments.length?(a(t),u()):a()},r.ticks=function(t){var r,u=a(),s=u[0],c=u[u.length-1];(r=c0){for(;dc)break;g.push(h)}}else for(;d=1;--l)if(!((h=f*l)c)break;g.push(h)}}else g=(0,i.sd)(d,p,Math.min(p-d,v)).map(n);return r?g.reverse():g},r.tickFormat=function(t,i){if(null==i&&(i=10===o?".0e":","),"function"!=typeof i&&(i=(0,Qn.WU)(i)),t===1/0)return i;null==t&&(t=10);var a=Math.max(1,o*t/r.ticks().length);return function(t){var r=t/n(Math.round(e(t)));return r*o0?r[i-1]:e[0],i=r?[a[r-1],n]:[a[i-1],a[i]]},u.unknown=function(e){return arguments.length?(t=e,u):u},u.thresholds=function(){return a.slice()},u.copy=function(){return Er().domain([e,n]).range(o).unknown(t)},Mn.o.apply(rr(u),arguments)}function Ar(){var t,e=[.5],n=[0,1],r=1;function a(a){return a<=a?n[(0,i.b4)(e,a,0,r)]:t}return a.domain=function(t){return arguments.length?(e=Sn.call(t),r=Math.min(e.length,n.length-1),a):e.slice()},a.range=function(t){return arguments.length?(n=Sn.call(t),r=Math.min(e.length,n.length-1),a):n.slice()},a.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},a.unknown=function(e){return arguments.length?(t=e,a):t},a.copy=function(){return Ar().domain(e).range(n).unknown(t)},Mn.o.apply(a,arguments)}var jr=n(97344),Cr=n(50690),Mr=n(76231),Fr=n(68603),Br=n(54076),Sr=n(18450),Nr=n(52546),Tr=n(30356),zr=n(49164),Or=31536e6;function Rr(t){return new Date(t)}function Pr(t){return t instanceof Date?+t:+new Date(+t)}function Ir(t,e,n,r,a,o,u,s,c){var f=Xn($n,$n),l=f.invert,h=f.domain,d=c(".%L"),p=c(":%S"),v=c("%I:%M"),g=c("%I %p"),_=c("%a %d"),b=c("%b %d"),y=c("%B"),m=c("%Y"),x=[[u,1,1e3],[u,5,5e3],[u,15,15e3],[u,30,3e4],[o,1,6e4],[o,5,3e5],[o,15,9e5],[o,30,18e5],[a,1,36e5],[a,3,108e5],[a,6,216e5],[a,12,432e5],[r,1,864e5],[r,2,1728e5],[n,1,6048e5],[e,1,2592e6],[e,3,7776e6],[t,1,Or]];function w(i){return(u(i)0)){if(a/=h,h<0){if(a0){if(a>l)return;a>f&&(f=a)}if(a=r-s,h||!(a<0)){if(a/=h,h<0){if(a>l)return;a>f&&(f=a)}else if(h>0){if(a0)){if(a/=d,d<0){if(a0){if(a>l)return;a>f&&(f=a)}if(a=i-c,d||!(a<0)){if(a/=d,d<0){if(a>l)return;a>f&&(f=a)}else if(d>0){if(a0||l<1)||(f>0&&(t[0]=[s+f*h,c+f*d]),l<1&&(t[1]=[s+l*h,c+l*d]),!0)}}}}}function Ai(t,e,n,r,i){var a=t[1];if(a)return!0;var o,u,s=t[0],c=t.left,f=t.right,l=c[0],h=c[1],d=f[0],p=f[1],v=(l+d)/2,g=(h+p)/2;if(p===h){if(v=r)return;if(l>d){if(s){if(s[1]>=i)return}else s=[v,n];a=[v,i]}else{if(s){if(s[1]1)if(l>d){if(s){if(s[1]>=i)return}else s=[(n-u)/o,n];a=[(i-u)/o,i]}else{if(s){if(s[1]=r)return}else s=[e,o*e+u];a=[r,o*r+u]}else{if(s){if(s[0]=-Gi)){var d=s*s+c*c,p=f*f+l*l,v=(l*d-c*p)/h,g=(s*p-f*d)/h,_=Bi.pop()||new Si;_.arc=t,_.site=i,_.x=v+o,_.y=(_.cy=g+u)+Math.sqrt(v*v+g*g),t.circle=_;for(var b=null,y=Yi._;y;)if(_.yVi)u=u.L;else{if(!((i=a-$i(u,o))>Vi)){r>-Vi?(e=u.P,n=u):i>-Vi?(e=u,n=u.N):e=n=u;break}if(!u.R){e=u;break}u=u.R}!function(t){qi[t.index]={site:t,halfedges:[]}}(t);var s=Ri(t);if(Hi.insert(e,s),e||n){if(e===n)return Ti(e),n=Ri(e.site),Hi.insert(s,n),s.edge=n.edge=Zi(e.site,s.site),Ni(e),void Ni(n);if(n){Ti(e),Ti(n);var c=e.site,f=c[0],l=c[1],h=t[0]-f,d=t[1]-l,p=n.site,v=p[0]-f,g=p[1]-l,_=2*(h*g-d*v),b=h*h+d*d,y=v*v+g*g,m=[(g*b-d*y)/_+f,(h*y-v*b)/_+l];ki(n.edge,c,p,m),s.edge=Zi(c,t,null,m),n.edge=Zi(t,p,null,m),Ni(e),Ni(n)}else s.edge=Zi(e.site,s.site)}}function Ui(t,e){var n=t.site,r=n[0],i=n[1],a=i-e;if(!a)return r;var o=t.P;if(!o)return-1/0;var u=(n=o.site)[0],s=n[1],c=s-e;if(!c)return u;var f=u-r,l=1/a-1/c,h=f/c;return l?(-h+Math.sqrt(h*h-2*l*(f*f/(-2*c)-s+c/2+i-a/2)))/l+r:(r+u)/2}function $i(t,e){var n=t.N;if(n)return Ui(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var Hi,qi,Yi,Wi,Vi=1e-6,Gi=1e-12;function Xi(t,e){return e[1]-t[1]||e[0]-t[0]}function Ki(t,e){var n,r,i,a=t.sort(Xi).pop();for(Wi=[],qi=new Array(t.length),Hi=new wi,Yi=new wi;;)if(i=Fi,a&&(!i||a[1]Vi||Math.abs(i[0][1]-i[1][1])>Vi)||delete Wi[a]}(o,u,s,c),function(t,e,n,r){var i,a,o,u,s,c,f,l,h,d,p,v,g=qi.length,_=!0;for(i=0;iVi||Math.abs(v-h)>Vi)&&(s.splice(u,0,Wi.push(Di(o,d,Math.abs(p-t)Vi?[t,Math.abs(l-t)Vi?[Math.abs(h-r)Vi?[n,Math.abs(l-n)Vi?[Math.abs(h-e)=u)return null;var s=t-i.site[0],c=e-i.site[1],f=s*s+c*c;do{i=a.cells[r=o],o=null,i.halfedges.forEach((function(n){var r=a.edges[n],u=r.left;if(u!==i.site&&u||(u=r.right)){var s=t-u[0],c=e-u[1],l=s*s+c*c;lr?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function ha(){var t,e,n=oa,r=ua,i=la,a=ca,o=fa,u=[0,1/0],s=[[-1/0,-1/0],[1/0,1/0]],c=250,f=Qi.Z,l=(0,b.Z)("start","zoom","end"),h=500,d=0;function p(t){t.property("__zoom",sa).on("wheel.zoom",A).on("mousedown.zoom",j).on("dblclick.zoom",C).filter(o).on("touchstart.zoom",M).on("touchmove.zoom",F).on("touchend.zoom touchcancel.zoom",B).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function v(t,e){return(e=Math.max(u[0],Math.min(u[1],e)))===t.k?t:new na(e,t.x,t.y)}function g(t,e,n){var r=e[0]-n[0]*t.k,i=e[1]-n[1]*t.k;return r===t.x&&i===t.y?t:new na(t.k,r,i)}function _(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function m(t,e,n){t.on("start.zoom",(function(){k(this,arguments).start()})).on("interrupt.zoom end.zoom",(function(){k(this,arguments).end()})).tween("zoom",(function(){var t=this,i=arguments,a=k(t,i),o=r.apply(t,i),u=null==n?_(o):"function"==typeof n?n.apply(t,i):n,s=Math.max(o[1][0]-o[0][0],o[1][1]-o[0][1]),c=t.__zoom,l="function"==typeof e?e.apply(t,i):e,h=f(c.invert(u).concat(s/c.k),l.invert(u).concat(s/l.k));return function(t){if(1===t)t=l;else{var e=h(t),n=s/e[2];t=new na(n,u[0]-e[0]*n,u[1]-e[1]*n)}a.zoom(null,t)}}))}function k(t,e,n){return!n&&t.__zooming||new E(t,e)}function E(t,e){this.that=t,this.args=e,this.active=0,this.extent=r.apply(t,e),this.taps=0}function A(){if(n.apply(this,arguments)){var t=k(this,arguments),e=this.__zoom,r=Math.max(u[0],Math.min(u[1],e.k*Math.pow(2,a.apply(this,arguments)))),o=(0,D.Z)(this);if(t.wheel)t.mouse[0][0]===o[0]&&t.mouse[0][1]===o[1]||(t.mouse[1]=e.invert(t.mouse[0]=o)),clearTimeout(t.wheel);else{if(e.k===r)return;t.mouse=[o,e.invert(o)],N(this),t.start()}(0,aa.Z)(),t.wheel=setTimeout(c,150),t.zoom("mouse",i(g(v(e,r),t.mouse[0],t.mouse[1]),t.extent,s))}function c(){t.wheel=null,t.end()}}function j(){if(!e&&n.apply(this,arguments)){var t=k(this,arguments,!0),r=(0,Z.Z)(w.B.view).on("mousemove.zoom",c,!0).on("mouseup.zoom",f,!0),a=(0,D.Z)(this),o=w.B.clientX,u=w.B.clientY;(0,y.Z)(w.B.view),(0,aa.r)(),t.mouse=[a,this.__zoom.invert(a)],N(this),t.start()}function c(){if((0,aa.Z)(),!t.moved){var e=w.B.clientX-o,n=w.B.clientY-u;t.moved=e*e+n*n>d}t.zoom("mouse",i(g(t.that.__zoom,t.mouse[0]=(0,D.Z)(t.that),t.mouse[1]),t.extent,s))}function f(){r.on("mousemove.zoom mouseup.zoom",null),(0,y.D)(w.B.view,t.moved),(0,aa.Z)(),t.end()}}function C(){if(n.apply(this,arguments)){var t=this.__zoom,e=(0,D.Z)(this),a=t.invert(e),o=t.k*(w.B.shiftKey?.5:2),u=i(g(v(t,o),e,a),r.apply(this,arguments),s);(0,aa.Z)(),c>0?(0,Z.Z)(this).transition().duration(c).call(m,u,e):(0,Z.Z)(this).call(p.transform,u)}}function M(){if(n.apply(this,arguments)){var e,r,i,a,o=w.B.touches,u=o.length,s=k(this,arguments,w.B.changedTouches.length===u);for((0,aa.r)(),r=0;r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(60401);function i(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},60401:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function i(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{Z:()=>r,V:()=>i})},10499:(t,e,n)=>{"use strict";function r(t,e){return function(n,r){for(var i=n.length,a=[],o=0,u=t[0],s=0;i>0&&u>0&&(s+u+1>r&&(u=Math.max(1,r-s)),a.push(n.substring(i-=u,i+u)),!((s+=u+1)>r));)u=t[o=(o+1)%t.length];return a.reverse().join(e)}}n.d(e,{Z:()=>r})},47447:(t,e,n)=>{"use strict";function r(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}n.d(e,{Z:()=>r})},30267:(t,e,n)=>{"use strict";if(n.d(e,{y:()=>i,Z:()=>a}),826==n.j)var r=n(60401);var i;function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var a=n[0],o=n[1],u=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,s=a.length;return u===s?a:u>s?a+new Array(u-s+1).join("0"):u>0?a.slice(0,u)+"."+a.slice(u):"0."+new Array(1-u).join("0")+(0,r.V)(t,Math.max(0,e+u-1))[0]}},14473:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,v:()=>a});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function i(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new a({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function a(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}i.prototype=a.prototype,a.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},33123:(t,e,n)=>{"use strict";function r(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}n.d(e,{Z:()=>r})},9985:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(60401),i=n(30267);function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var i=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+i:i.length>a+1?i.slice(0,a+1)+"."+i.slice(a+1):i+new Array(a-i.length+2).join("0")}const o={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:r.Z,e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return a(100*t,e)},r:a,s:i.Z,X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}}},21568:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},68639:(t,e,n)=>{"use strict";n.d(e,{vr:()=>s.v,WU:()=>i,Zq:()=>u,FF:()=>o.Z,jH:()=>a,YQ:()=>s.Z,zB:()=>c.Z,S5:()=>f.Z,F0:()=>l.Z});var r,i,a,o=n(12555);function u(t){return r=(0,o.Z)(t),i=r.format,a=r.formatPrefix,r}u({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});var s=n(14473),c=n(84125),f=n(11491),l=n(76515)},12555:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>d}),826==n.j)var r=n(21074);if(826==n.j)var i=n(10499);if(826==n.j)var a=n(47447);if(826==n.j)var o=n(14473);if(826==n.j)var u=n(33123);if(826==n.j)var s=n(9985);if(826==n.j)var c=n(30267);if(826==n.j)var f=n(21568);var l=Array.prototype.map,h=826==n.j?["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"]:null;function d(t){var e=void 0===t.grouping||void 0===t.thousands?f.Z:(0,i.Z)(l.call(t.grouping,Number),t.thousands+""),n=void 0===t.currency?"":t.currency[0]+"",d=void 0===t.currency?"":t.currency[1]+"",p=void 0===t.decimal?".":t.decimal+"",v=void 0===t.numerals?f.Z:(0,a.Z)(l.call(t.numerals,String)),g=void 0===t.percent?"%":t.percent+"",_=void 0===t.minus?"-":t.minus+"",b=void 0===t.nan?"NaN":t.nan+"";function y(t){var r=(t=(0,o.Z)(t)).fill,i=t.align,a=t.sign,f=t.symbol,l=t.zero,y=t.width,m=t.comma,x=t.precision,w=t.trim,Z=t.type;"n"===Z?(m=!0,Z="g"):s.Z[Z]||(void 0===x&&(x=12),w=!0,Z="g"),(l||"0"===r&&"="===i)&&(l=!0,r="0",i="=");var D="$"===f?n:"#"===f&&/[boxX]/.test(Z)?"0"+Z.toLowerCase():"",k="$"===f?d:/[%p]/.test(Z)?g:"",E=s.Z[Z],A=/[defgprs%]/.test(Z);function j(t){var n,o,s,f=D,d=k;if("c"===Z)d=E(t)+d,t="";else{var g=(t=+t)<0||1/t<0;if(t=isNaN(t)?b:E(Math.abs(t),x),w&&(t=(0,u.Z)(t)),g&&0==+t&&"+"!==a&&(g=!1),f=(g?"("===a?a:_:"-"===a||"("===a?"":a)+f,d=("s"===Z?h[8+c.y/3]:"")+d+(g&&"("===a?")":""),A)for(n=-1,o=t.length;++n(s=t.charCodeAt(n))||s>57){d=(46===s?p+t.slice(n+1):t.slice(n))+d,t=t.slice(0,n);break}}m&&!l&&(t=e(t,1/0));var j=f.length+t.length+d.length,C=j>1)+f+t+d+C.slice(j);break;default:t=C+f+t+d}return v(t)}return x=void 0===x?6:/[gprs]/.test(Z)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x)),j.toString=function(){return t+""},j}return{format:y,formatPrefix:function(t,e){var n=y(((t=(0,o.Z)(t)).type="f",t)),i=3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3))),a=Math.pow(10,-i),u=h[8+i/3];return function(t){return n(a*t)+u}}}}},84125:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},11491:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},76515:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},46506:(t,e,n)=>{t.exports={graphlib:n(71310),layout:n(42529),debug:n(5512),util:{time:n(8783).time,notime:n(8783).notime},version:n(57589)}},85247:(t,e,n)=>{"use strict";var r=n(43294),i=n(38757);t.exports={run:function(t){var e="greedy"===t.graph().acyclicer?i(t,function(t){return function(e){return t.edge(e).weight}}(t)):function(t){var e=[],n={},i={};return r.forEach(t.nodes(),(function a(o){r.has(i,o)||(i[o]=!0,n[o]=!0,r.forEach(t.outEdges(o),(function(t){r.has(n,t.w)?e.push(t):a(t.w)})),delete n[o])})),e}(t);r.forEach(e,(function(e){var n=t.edge(e);t.removeEdge(e),n.forwardName=e.name,n.reversed=!0,t.setEdge(e.w,e.v,n,r.uniqueId("rev"))}))},undo:function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.reversed){t.removeEdge(e);var r=n.forwardName;delete n.reversed,delete n.forwardName,t.setEdge(e.w,e.v,n,r)}}))}}},49654:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n,r,a,o){var u={width:0,height:0,rank:o,borderType:e},s=a[e][o-1],c=i.addDummyNode(t,"border",u,n);a[e][o]=c,t.setParent(c,r),s&&t.setEdge(s,c,{weight:1})}t.exports=function(t){r.forEach(t.children(),(function e(n){var i=t.children(n),o=t.node(n);if(i.length&&r.forEach(i,e),r.has(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(var u=o.minRank,s=o.maxRank+1;u{"use strict";var r=n(43294);function i(t){r.forEach(t.nodes(),(function(e){a(t.node(e))})),r.forEach(t.edges(),(function(e){a(t.edge(e))}))}function a(t){var e=t.width;t.width=t.height,t.height=e}function o(t){t.y=-t.y}function u(t){var e=t.x;t.x=t.y,t.y=e}t.exports={adjust:function(t){var e=t.graph().rankdir.toLowerCase();"lr"!==e&&"rl"!==e||i(t)},undo:function(t){var e=t.graph().rankdir.toLowerCase();"bt"!==e&&"rl"!==e||function(t){r.forEach(t.nodes(),(function(e){o(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,o),r.has(n,"y")&&o(n)}))}(t),"lr"!==e&&"rl"!==e||(function(t){r.forEach(t.nodes(),(function(e){u(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,u),r.has(n,"x")&&u(n)}))}(t),i(t))}}},65199:t=>{function e(){var t={};t._next=t._prev=t,this._sentinel=t}function n(t){t._prev._next=t._next,t._next._prev=t._prev,delete t._next,delete t._prev}function r(t,e){if("_next"!==t&&"_prev"!==t)return e}t.exports=e,e.prototype.dequeue=function(){var t=this._sentinel,e=t._prev;if(e!==t)return n(e),e},e.prototype.enqueue=function(t){var e=this._sentinel;t._prev&&t._next&&n(t),t._next=e._next,e._next._prev=t,e._next=t,t._prev=e},e.prototype.toString=function(){for(var t=[],e=this._sentinel,n=e._prev;n!==e;)t.push(JSON.stringify(n,r)),n=n._prev;return"["+t.join(", ")+"]"}},5512:(t,e,n)=>{var r=n(43294),i=n(8783),a=n(71310).Graph;t.exports={debugOrdering:function(t){var e=i.buildLayerMatrix(t),n=new a({compound:!0,multigraph:!0}).setGraph({});return r.forEach(t.nodes(),(function(e){n.setNode(e,{label:e}),n.setParent(e,"layer"+t.node(e).rank)})),r.forEach(t.edges(),(function(t){n.setEdge(t.v,t.w,{},t.name)})),r.forEach(e,(function(t,e){var i="layer"+e;n.setNode(i,{rank:"same"}),r.reduce(t,(function(t,e){return n.setEdge(t,e,{style:"invis"}),e}))})),n}}},71310:(t,e,n)=>{var r;try{r=n(87377)}catch(t){}r||(r=window.graphlib),t.exports=r},38757:(t,e,n)=>{var r=n(43294),i=n(71310).Graph,a=n(65199);t.exports=function(t,e){if(t.nodeCount()<=1)return[];var n=function(t,e){var n=new i,o=0,u=0;r.forEach(t.nodes(),(function(t){n.setNode(t,{v:t,in:0,out:0})})),r.forEach(t.edges(),(function(t){var r=n.edge(t.v,t.w)||0,i=e(t),a=r+i;n.setEdge(t.v,t.w,a),u=Math.max(u,n.node(t.v).out+=i),o=Math.max(o,n.node(t.w).in+=i)}));var c=r.range(u+o+3).map((function(){return new a})),f=o+1;return r.forEach(n.nodes(),(function(t){s(c,f,n.node(t))})),{graph:n,buckets:c,zeroIdx:f}}(t,e||o),c=function(t,e,n){for(var r,i=[],a=e[e.length-1],o=e[0];t.nodeCount();){for(;r=o.dequeue();)u(t,e,n,r);for(;r=a.dequeue();)u(t,e,n,r);if(t.nodeCount())for(var s=e.length-2;s>0;--s)if(r=e[s].dequeue()){i=i.concat(u(t,e,n,r,!0));break}}return i}(n.graph,n.buckets,n.zeroIdx);return r.flatten(r.map(c,(function(e){return t.outEdges(e.v,e.w)})),!0)};var o=r.constant(1);function u(t,e,n,i,a){var o=a?[]:void 0;return r.forEach(t.inEdges(i.v),(function(r){var i=t.edge(r),u=t.node(r.v);a&&o.push({v:r.v,w:r.w}),u.out-=i,s(e,n,u)})),r.forEach(t.outEdges(i.v),(function(r){var i=t.edge(r),a=r.w,o=t.node(a);o.in-=i,s(e,n,o)})),t.removeNode(i.v),o}function s(t,e,n){n.out?n.in?t[n.out-n.in+e].enqueue(n):t[t.length-1].enqueue(n):t[0].enqueue(n)}},42529:(t,e,n)=>{"use strict";var r=n(43294),i=n(85247),a=n(20450),o=n(64618),u=n(8783).normalizeRanks,s=n(77908),c=n(8783).removeEmptyRanks,f=n(96820),l=n(49654),h=n(25128),d=n(73641),p=n(65784),v=n(8783),g=n(71310).Graph;t.exports=function(t,e){var n=e&&e.debugTiming?v.time:v.notime;n("layout",(function(){var e=n(" buildLayoutGraph",(function(){return function(t){var e=new g({multigraph:!0,compound:!0}),n=E(t.graph());return e.setGraph(r.merge({},b,k(n,_),r.pick(n,y))),r.forEach(t.nodes(),(function(n){var i=E(t.node(n));e.setNode(n,r.defaults(k(i,m),x)),e.setParent(n,t.parent(n))})),r.forEach(t.edges(),(function(n){var i=E(t.edge(n));e.setEdge(n,r.merge({},Z,k(i,w),r.pick(i,D)))})),e}(t)}));n(" runLayout",(function(){!function(t,e){e(" makeSpaceForEdgeLabels",(function(){!function(t){var e=t.graph();e.ranksep/=2,r.forEach(t.edges(),(function(n){var r=t.edge(n);r.minlen*=2,"c"!==r.labelpos.toLowerCase()&&("TB"===e.rankdir||"BT"===e.rankdir?r.width+=r.labeloffset:r.height+=r.labeloffset)}))}(t)})),e(" removeSelfEdges",(function(){!function(t){r.forEach(t.edges(),(function(e){if(e.v===e.w){var n=t.node(e.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e,label:t.edge(e)}),t.removeEdge(e)}}))}(t)})),e(" acyclic",(function(){i.run(t)})),e(" nestingGraph.run",(function(){f.run(t)})),e(" rank",(function(){o(v.asNonCompoundGraph(t))})),e(" injectEdgeLabelProxies",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.width&&n.height){var r=t.node(e.v),i={rank:(t.node(e.w).rank-r.rank)/2+r.rank,e};v.addDummyNode(t,"edge-proxy",i,"_ep")}}))}(t)})),e(" removeEmptyRanks",(function(){c(t)})),e(" nestingGraph.cleanup",(function(){f.cleanup(t)})),e(" normalizeRanks",(function(){u(t)})),e(" assignRankMinMax",(function(){!function(t){var e=0;r.forEach(t.nodes(),(function(n){var i=t.node(n);i.borderTop&&(i.minRank=t.node(i.borderTop).rank,i.maxRank=t.node(i.borderBottom).rank,e=r.max(e,i.maxRank))})),t.graph().maxRank=e}(t)})),e(" removeEdgeLabelProxies",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);"edge-proxy"===n.dummy&&(t.edge(n.e).labelRank=n.rank,t.removeNode(e))}))}(t)})),e(" normalize.run",(function(){a.run(t)})),e(" parentDummyChains",(function(){s(t)})),e(" addBorderSegments",(function(){l(t)})),e(" order",(function(){d(t)})),e(" insertSelfEdges",(function(){!function(t){var e=v.buildLayerMatrix(t);r.forEach(e,(function(e){var n=0;r.forEach(e,(function(e,i){var a=t.node(e);a.order=i+n,r.forEach(a.selfEdges,(function(e){v.addDummyNode(t,"selfedge",{width:e.label.width,height:e.label.height,rank:a.rank,order:i+ ++n,e:e.e,label:e.label},"_se")})),delete a.selfEdges}))}))}(t)})),e(" adjustCoordinateSystem",(function(){h.adjust(t)})),e(" position",(function(){p(t)})),e(" positionSelfEdges",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);if("selfedge"===n.dummy){var r=t.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,u=r.height/2;t.setEdge(n.e,n.label),t.removeNode(e),n.label.points=[{x:i+2*o/3,y:a-u},{x:i+5*o/6,y:a-u},{x:i+o,y:a},{x:i+5*o/6,y:a+u},{x:i+2*o/3,y:a+u}],n.label.x=n.x,n.label.y=n.y}}))}(t)})),e(" removeBorderNodes",(function(){!function(t){r.forEach(t.nodes(),(function(e){if(t.children(e).length){var n=t.node(e),i=t.node(n.borderTop),a=t.node(n.borderBottom),o=t.node(r.last(n.borderLeft)),u=t.node(r.last(n.borderRight));n.width=Math.abs(u.x-o.x),n.height=Math.abs(a.y-i.y),n.x=o.x+n.width/2,n.y=i.y+n.height/2}})),r.forEach(t.nodes(),(function(e){"border"===t.node(e).dummy&&t.removeNode(e)}))}(t)})),e(" normalize.undo",(function(){a.undo(t)})),e(" fixupEdgeLabelCoords",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(r.has(n,"x"))switch("l"!==n.labelpos&&"r"!==n.labelpos||(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset}}))}(t)})),e(" undoCoordinateSystem",(function(){h.undo(t)})),e(" translateGraph",(function(){!function(t){var e=Number.POSITIVE_INFINITY,n=0,i=Number.POSITIVE_INFINITY,a=0,o=t.graph(),u=o.marginx||0,s=o.marginy||0;function c(t){var r=t.x,o=t.y,u=t.width,s=t.height;e=Math.min(e,r-u/2),n=Math.max(n,r+u/2),i=Math.min(i,o-s/2),a=Math.max(a,o+s/2)}r.forEach(t.nodes(),(function(e){c(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.has(n,"x")&&c(n)})),e-=u,i-=s,r.forEach(t.nodes(),(function(n){var r=t.node(n);r.x-=e,r.y-=i})),r.forEach(t.edges(),(function(n){var a=t.edge(n);r.forEach(a.points,(function(t){t.x-=e,t.y-=i})),r.has(a,"x")&&(a.x-=e),r.has(a,"y")&&(a.y-=i)})),o.width=n-e+u,o.height=a-i+s}(t)})),e(" assignNodeIntersects",(function(){!function(t){r.forEach(t.edges(),(function(e){var n,r,i=t.edge(e),a=t.node(e.v),o=t.node(e.w);i.points?(n=i.points[0],r=i.points[i.points.length-1]):(i.points=[],n=o,r=a),i.points.unshift(v.intersectRect(a,n)),i.points.push(v.intersectRect(o,r))}))}(t)})),e(" reversePoints",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);n.reversed&&n.points.reverse()}))}(t)})),e(" acyclic.undo",(function(){i.undo(t)}))}(e,n)})),n(" updateInputGraph",(function(){!function(t,e){r.forEach(t.nodes(),(function(n){var r=t.node(n),i=e.node(n);r&&(r.x=i.x,r.y=i.y,e.children(n).length&&(r.width=i.width,r.height=i.height))})),r.forEach(t.edges(),(function(n){var i=t.edge(n),a=e.edge(n);i.points=a.points,r.has(a,"x")&&(i.x=a.x,i.y=a.y)})),t.graph().width=e.graph().width,t.graph().height=e.graph().height}(t,e)}))}))};var _=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},y=["acyclicer","ranker","rankdir","align"],m=["width","height"],x={width:0,height:0},w=["minlen","weight","width","height","labeloffset"],Z={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},D=["labelpos"];function k(t,e){return r.mapValues(r.pick(t,e),Number)}function E(t){var e={};return r.forEach(t,(function(t,n){e[n.toLowerCase()]=t})),e}},43294:(t,e,n)=>{var r;try{r={cloneDeep:n(9850),constant:n(86874),defaults:n(84573),each:n(79421),filter:n(90882),find:n(55281),flatten:n(35676),forEach:n(59756),forIn:n(20792),has:n(93352),isUndefined:n(84336),last:n(56974),map:n(16760),mapValues:n(34519),max:n(71644),merge:n(98537),min:n(65680),minBy:n(10937),now:n(61100),pick:n(13888),range:n(2689),reduce:n(58215),sortBy:n(829),uniqueId:n(74930),values:n(98346),zipObject:n(46150)}}catch(t){}r||(r=window._),t.exports=r},96820:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n,o,u,s,c){var f=t.children(c);if(f.length){var l=i.addBorderNode(t,"_bt"),h=i.addBorderNode(t,"_bb"),d=t.node(c);t.setParent(l,c),d.borderTop=l,t.setParent(h,c),d.borderBottom=h,r.forEach(f,(function(r){a(t,e,n,o,u,s,r);var i=t.node(r),f=i.borderTop?i.borderTop:r,d=i.borderBottom?i.borderBottom:r,p=i.borderTop?o:2*o,v=f!==d?1:u-s[c]+1;t.setEdge(l,f,{weight:p,minlen:v,nestingEdge:!0}),t.setEdge(d,h,{weight:p,minlen:v,nestingEdge:!0})})),t.parent(c)||t.setEdge(e,l,{weight:0,minlen:u+s[c]})}else c!==e&&t.setEdge(e,c,{weight:0,minlen:n})}t.exports={run:function(t){var e=i.addDummyNode(t,"root",{},"_root"),n=function(t){var e={};function n(i,a){var o=t.children(i);o&&o.length&&r.forEach(o,(function(t){n(t,a+1)})),e[i]=a}return r.forEach(t.children(),(function(t){n(t,1)})),e}(t),o=r.max(r.values(n))-1,u=2*o+1;t.graph().nestingRoot=e,r.forEach(t.edges(),(function(e){t.edge(e).minlen*=u}));var s=function(t){return r.reduce(t.edges(),(function(e,n){return e+t.edge(n).weight}),0)}(t)+1;r.forEach(t.children(),(function(r){a(t,e,u,s,o,n,r)})),t.graph().nodeRankFactor=u},cleanup:function(t){var e=t.graph();t.removeNode(e.nestingRoot),delete e.nestingRoot,r.forEach(t.edges(),(function(e){t.edge(e).nestingEdge&&t.removeEdge(e)}))}}},20450:(t,e,n)=>{"use strict";var r=n(43294),i=n(8783);t.exports={run:function(t){t.graph().dummyChains=[],r.forEach(t.edges(),(function(e){!function(t,e){var n,r,a,o=e.v,u=t.node(o).rank,s=e.w,c=t.node(s).rank,f=e.name,l=t.edge(e),h=l.labelRank;if(c!==u+1){for(t.removeEdge(e),a=0,++u;u{var r=n(43294);t.exports=function(t,e,n){var i,a={};r.forEach(n,(function(n){for(var r,o,u=t.parent(n);u;){if((r=t.parent(u))?(o=a[r],a[r]=u):(o=i,i=u),o&&o!==u)return void e.setEdge(o,u);u=r}}))}},29533:(t,e,n)=>{var r=n(43294);t.exports=function(t,e){return r.map(e,(function(e){var n=t.inEdges(e);if(n.length){var i=r.reduce(n,(function(e,n){var r=t.edge(n),i=t.node(n.v);return{sum:e.sum+r.weight*i.order,weight:e.weight+r.weight}}),{sum:0,weight:0});return{v:e,barycenter:i.sum/i.weight,weight:i.weight}}return{v:e}}))}},64622:(t,e,n)=>{var r=n(43294),i=n(71310).Graph;t.exports=function(t,e,n){var a=function(t){for(var e;t.hasNode(e=r.uniqueId("_root")););return e}(t),o=new i({compound:!0}).setGraph({root:a}).setDefaultNodeLabel((function(e){return t.node(e)}));return r.forEach(t.nodes(),(function(i){var u=t.node(i),s=t.parent(i);(u.rank===e||u.minRank<=e&&e<=u.maxRank)&&(o.setNode(i),o.setParent(i,s||a),r.forEach(t[n](i),(function(e){var n=e.v===i?e.w:e.v,a=o.edge(n,i),u=r.isUndefined(a)?0:a.weight;o.setEdge(n,i,{weight:t.edge(e).weight+u})})),r.has(u,"minRank")&&o.setNode(i,{borderLeft:u.borderLeft[e],borderRight:u.borderRight[e]}))})),o}},6254:(t,e,n)=>{"use strict";var r=n(43294);function i(t,e,n){for(var i=r.zipObject(n,r.map(n,(function(t,e){return e}))),a=r.flatten(r.map(e,(function(e){return r.sortBy(r.map(t.outEdges(e),(function(e){return{pos:i[e.w],weight:t.edge(e).weight}})),"pos")})),!0),o=1;o0;)e%2&&(n+=s[e+1]),s[e=e-1>>1]+=t.weight;c+=t.weight*n}))),c}t.exports=function(t,e){for(var n=0,r=1;r{"use strict";var r=n(43294),i=n(65036),a=n(6254),o=n(83956),u=n(64622),s=n(47897),c=n(71310).Graph,f=n(8783);function l(t,e,n){return r.map(e,(function(e){return u(t,e,n)}))}function h(t,e){var n=new c;r.forEach(t,(function(t){var i=t.graph().root,a=o(t,i,n,e);r.forEach(a.vs,(function(e,n){t.node(e).order=n})),s(t,n,a.vs)}))}function d(t,e){r.forEach(e,(function(e){r.forEach(e,(function(e,n){t.node(e).order=n}))}))}t.exports=function(t){var e=f.maxRank(t),n=l(t,r.range(1,e+1),"inEdges"),o=l(t,r.range(e-1,-1,-1),"outEdges"),u=i(t);d(t,u);for(var s,c=Number.POSITIVE_INFINITY,p=0,v=0;v<4;++p,++v){h(p%2?n:o,p%4>=2),u=f.buildLayerMatrix(t);var g=a(t,u);g{"use strict";var r=n(43294);t.exports=function(t){var e={},n=r.filter(t.nodes(),(function(e){return!t.children(e).length})),i=r.max(r.map(n,(function(e){return t.node(e).rank}))),a=r.map(r.range(i+1),(function(){return[]})),o=r.sortBy(n,(function(e){return t.node(e).rank}));return r.forEach(o,(function n(i){if(!r.has(e,i)){e[i]=!0;var o=t.node(i);a[o.rank].push(i),r.forEach(t.successors(i),n)}})),a}},39953:(t,e,n)=>{"use strict";var r=n(43294);t.exports=function(t,e){var n={};return r.forEach(t,(function(t,e){var i=n[t.v]={indegree:0,in:[],out:[],vs:[t.v],i:e};r.isUndefined(t.barycenter)||(i.barycenter=t.barycenter,i.weight=t.weight)})),r.forEach(e.edges(),(function(t){var e=n[t.v],i=n[t.w];r.isUndefined(e)||r.isUndefined(i)||(i.indegree++,e.out.push(n[t.w]))})),function(t){var e=[];function n(t){return function(e){var n,i,a,o;e.merged||(r.isUndefined(e.barycenter)||r.isUndefined(t.barycenter)||e.barycenter>=t.barycenter)&&(i=e,a=0,o=0,(n=t).weight&&(a+=n.barycenter*n.weight,o+=n.weight),i.weight&&(a+=i.barycenter*i.weight,o+=i.weight),n.vs=i.vs.concat(n.vs),n.barycenter=a/o,n.weight=o,n.i=Math.min(i.i,n.i),i.merged=!0)}}function i(e){return function(n){n.in.push(e),0==--n.indegree&&t.push(n)}}for(;t.length;){var a=t.pop();e.push(a),r.forEach(a.in.reverse(),n(a)),r.forEach(a.out,i(a))}return r.map(r.filter(e,(function(t){return!t.merged})),(function(t){return r.pick(t,["vs","i","barycenter","weight"])}))}(r.filter(n,(function(t){return!t.indegree})))}},83956:(t,e,n)=>{var r=n(43294),i=n(29533),a=n(39953),o=n(11957);t.exports=function t(e,n,u,s){var c=e.children(n),f=e.node(n),l=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,d={};l&&(c=r.filter(c,(function(t){return t!==l&&t!==h})));var p=i(e,c);r.forEach(p,(function(n){if(e.children(n.v).length){var i=t(e,n.v,u,s);d[n.v]=i,r.has(i,"barycenter")&&(a=n,o=i,r.isUndefined(a.barycenter)?(a.barycenter=o.barycenter,a.weight=o.weight):(a.barycenter=(a.barycenter*a.weight+o.barycenter*o.weight)/(a.weight+o.weight),a.weight+=o.weight))}var a,o}));var v=a(p,u);!function(t,e){r.forEach(t,(function(t){t.vs=r.flatten(t.vs.map((function(t){return e[t]?e[t].vs:t})),!0)}))}(v,d);var g=o(v,s);if(l&&(g.vs=r.flatten([l,g.vs,h],!0),e.predecessors(l).length)){var _=e.node(e.predecessors(l)[0]),b=e.node(e.predecessors(h)[0]);r.has(g,"barycenter")||(g.barycenter=0,g.weight=0),g.barycenter=(g.barycenter*g.weight+_.order+b.order)/(g.weight+2),g.weight+=2}return g}},11957:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n){for(var i;e.length&&(i=r.last(e)).i<=n;)e.pop(),t.push(i.vs),n++;return n}t.exports=function(t,e){var n,o=i.partition(t,(function(t){return r.has(t,"barycenter")})),u=o.lhs,s=r.sortBy(o.rhs,(function(t){return-t.i})),c=[],f=0,l=0,h=0;u.sort((n=!!e,function(t,e){return t.barycentere.barycenter?1:n?e.i-t.i:t.i-e.i})),h=a(c,s,h),r.forEach(u,(function(t){h+=t.vs.length,c.push(t.vs),f+=t.barycenter*t.weight,l+=t.weight,h=a(c,s,h)}));var d={vs:r.flatten(c,!0)};return l&&(d.barycenter=f/l,d.weight=l),d}},77908:(t,e,n)=>{var r=n(43294);t.exports=function(t){var e=function(t){var e={},n=0;return r.forEach(t.children(),(function i(a){var o=n;r.forEach(t.children(a),i),e[a]={low:o,lim:n++}})),e}(t);r.forEach(t.graph().dummyChains,(function(n){for(var r=t.node(n),i=r.edgeObj,a=function(t,e,n,r){var i,a,o=[],u=[],s=Math.min(e[n].low,e[r].low),c=Math.max(e[n].lim,e[r].lim);i=n;do{i=t.parent(i),o.push(i)}while(i&&(e[i].low>s||c>e[i].lim));for(a=i,i=r;(i=t.parent(i))!==a;)u.push(i);return{path:o.concat(u.reverse()),lca:a}}(t,e,i.v,i.w),o=a.path,u=a.lca,s=0,c=o[s],f=!0;n!==i.w;){if(r=t.node(n),f){for(;(c=o[s])!==u&&t.node(c).maxRank{"use strict";var r=n(43294),i=n(71310).Graph,a=n(8783);function o(t,e){var n={};return r.reduce(e,(function(e,i){var a=0,o=0,u=e.length,c=r.last(i);return r.forEach(i,(function(e,f){var l=function(t,e){if(t.node(e).dummy)return r.find(t.predecessors(e),(function(e){return t.node(e).dummy}))}(t,e),h=l?t.node(l).order:u;(l||e===c)&&(r.forEach(i.slice(o,f+1),(function(e){r.forEach(t.predecessors(e),(function(r){var i=t.node(r),o=i.order;!(ou)&&s(n,e,c)}))}))}return r.reduce(e,(function(e,n){var a,o=-1,u=0;return r.forEach(n,(function(r,s){if("border"===t.node(r).dummy){var c=t.predecessors(r);c.length&&(a=t.node(c[0]).order,i(n,u,s,o,a),u=s,o=a)}i(n,u,n.length,a,e.length)})),n})),n}function s(t,e,n){if(e>n){var r=e;e=n,n=r}var i=t[e];i||(t[e]=i={}),i[n]=!0}function c(t,e,n){if(e>n){var i=e;e=n,n=i}return r.has(t[e],n)}function f(t,e,n,i){var a={},o={},u={};return r.forEach(e,(function(t){r.forEach(t,(function(t,e){a[t]=t,o[t]=t,u[t]=e}))})),r.forEach(e,(function(t){var e=-1;r.forEach(t,(function(t){var s=i(t);if(s.length)for(var f=((s=r.sortBy(s,(function(t){return u[t]}))).length-1)/2,l=Math.floor(f),h=Math.ceil(f);l<=h;++l){var d=s[l];o[t]===t&&e{"use strict";var r=n(43294),i=n(8783),a=n(91753).positionX;t.exports=function(t){(function(t){var e=i.buildLayerMatrix(t),n=t.graph().ranksep,a=0;r.forEach(e,(function(e){var i=r.max(r.map(e,(function(e){return t.node(e).height})));r.forEach(e,(function(e){t.node(e).y=a+i/2})),a+=i+n}))})(t=i.asNonCompoundGraph(t)),r.forEach(a(t),(function(e,n){t.node(n).x=e}))}},49154:(t,e,n)=>{"use strict";var r=n(43294),i=n(71310).Graph,a=n(85986).slack;function o(t,e){return r.forEach(t.nodes(),(function n(i){r.forEach(e.nodeEdges(i),(function(r){var o=r.v,u=i===o?r.w:o;t.hasNode(u)||a(e,r)||(t.setNode(u,{}),t.setEdge(i,u,{}),n(u))}))})),t.nodeCount()}function u(t,e){return r.minBy(e.edges(),(function(n){if(t.hasNode(n.v)!==t.hasNode(n.w))return a(e,n)}))}function s(t,e,n){r.forEach(t.nodes(),(function(t){e.node(t).rank+=n}))}t.exports=function(t){var e,n,r=new i({directed:!1}),c=t.nodes()[0],f=t.nodeCount();for(r.setNode(c,{});o(r,t){"use strict";var r=n(85986).longestPath,i=n(49154),a=n(57310);t.exports=function(t){switch(t.graph().ranker){case"network-simplex":u(t);break;case"tight-tree":!function(t){r(t),i(t)}(t);break;case"longest-path":o(t);break;default:u(t)}};var o=r;function u(t){a(t)}},57310:(t,e,n)=>{"use strict";var r=n(43294),i=n(49154),a=n(85986).slack,o=n(85986).longestPath,u=n(71310).alg.preorder,s=n(71310).alg.postorder,c=n(8783).simplify;function f(t){t=c(t),o(t);var e,n=i(t);for(d(n),l(n,t);e=v(n);)_(n,t,e,g(n,t,e))}function l(t,e){var n=s(t,t.nodes());n=n.slice(0,n.length-1),r.forEach(n,(function(n){!function(t,e,n){var r=t.node(n).parent;t.edge(n,r).cutvalue=h(t,e,n)}(t,e,n)}))}function h(t,e,n){var i=t.node(n).parent,a=!0,o=e.edge(n,i),u=0;return o||(a=!1,o=e.edge(i,n)),u=o.weight,r.forEach(e.nodeEdges(n),(function(r){var o,s,c=r.v===n,f=c?r.w:r.v;if(f!==i){var l=c===a,h=e.edge(r).weight;if(u+=l?h:-h,o=n,s=f,t.hasEdge(o,s)){var d=t.edge(n,f).cutvalue;u+=l?-d:d}}})),u}function d(t,e){arguments.length<2&&(e=t.nodes()[0]),p(t,{},1,e)}function p(t,e,n,i,a){var o=n,u=t.node(i);return e[i]=!0,r.forEach(t.neighbors(i),(function(a){r.has(e,a)||(n=p(t,e,n,a,i))})),u.low=o,u.lim=n++,a?u.parent=a:delete u.parent,n}function v(t){return r.find(t.edges(),(function(e){return t.edge(e).cutvalue<0}))}function g(t,e,n){var i=n.v,o=n.w;e.hasEdge(i,o)||(i=n.w,o=n.v);var u=t.node(i),s=t.node(o),c=u,f=!1;u.lim>s.lim&&(c=s,f=!0);var l=r.filter(e.edges(),(function(e){return f===b(0,t.node(e.v),c)&&f!==b(0,t.node(e.w),c)}));return r.minBy(l,(function(t){return a(e,t)}))}function _(t,e,n,i){var a=n.v,o=n.w;t.removeEdge(a,o),t.setEdge(i.v,i.w,{}),d(t),l(t,e),function(t,e){var n=r.find(t.nodes(),(function(t){return!e.node(t).parent})),i=u(t,n);i=i.slice(1),r.forEach(i,(function(n){var r=t.node(n).parent,i=e.edge(n,r),a=!1;i||(i=e.edge(r,n),a=!0),e.node(n).rank=e.node(r).rank+(a?i.minlen:-i.minlen)}))}(t,e)}function b(t,e,n){return n.low<=e.lim&&e.lim<=n.lim}t.exports=f,f.initLowLimValues=d,f.initCutValues=l,f.calcCutValue=h,f.leaveEdge=v,f.enterEdge=g,f.exchangeEdges=_},85986:(t,e,n)=>{"use strict";var r=n(43294);t.exports={longestPath:function(t){var e={};r.forEach(t.sources(),(function n(i){var a=t.node(i);if(r.has(e,i))return a.rank;e[i]=!0;var o=r.min(r.map(t.outEdges(i),(function(e){return n(e.w)-t.edge(e).minlen})));return o!==Number.POSITIVE_INFINITY&&null!=o||(o=0),a.rank=o}))},slack:function(t,e){return t.node(e.w).rank-t.node(e.v).rank-t.edge(e).minlen}}},8783:(t,e,n)=>{"use strict";var r=n(43294),i=n(71310).Graph;function a(t,e,n,i){var a;do{a=r.uniqueId(i)}while(t.hasNode(a));return n.dummy=e,t.setNode(a,n),a}function o(t){return r.max(r.map(t.nodes(),(function(e){var n=t.node(e).rank;if(!r.isUndefined(n))return n})))}t.exports={addDummyNode:a,simplify:function(t){var e=(new i).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){var r=e.edge(n.v,n.w)||{weight:0,minlen:1},i=t.edge(n);e.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})})),e},asNonCompoundGraph:function(t){var e=new i({multigraph:t.isMultigraph()}).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){t.children(n).length||e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){e.setEdge(n,t.edge(n))})),e},successorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.outEdges(e),(function(e){n[e.w]=(n[e.w]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},predecessorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.inEdges(e),(function(e){n[e.v]=(n[e.v]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},intersectRect:function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,u=e.y-a,s=t.width/2,c=t.height/2;if(!o&&!u)throw new Error("Not possible to find intersection inside of the rectangle");return Math.abs(u)*s>Math.abs(o)*c?(u<0&&(c=-c),n=c*o/u,r=c):(o<0&&(s=-s),n=s,r=s*u/o),{x:i+n,y:a+r}},buildLayerMatrix:function(t){var e=r.map(r.range(o(t)+1),(function(){return[]}));return r.forEach(t.nodes(),(function(n){var i=t.node(n),a=i.rank;r.isUndefined(a)||(e[a][i.order]=n)})),e},normalizeRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank})));r.forEach(t.nodes(),(function(n){var i=t.node(n);r.has(i,"rank")&&(i.rank-=e)}))},removeEmptyRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank}))),n=[];r.forEach(t.nodes(),(function(r){var i=t.node(r).rank-e;n[i]||(n[i]=[]),n[i].push(r)}));var i=0,a=t.graph().nodeRankFactor;r.forEach(n,(function(e,n){r.isUndefined(e)&&n%a!=0?--i:i&&r.forEach(e,(function(e){t.node(e).rank+=i}))}))},addBorderNode:function(t,e,n,r){var i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),a(t,"border",i,e)},maxRank:o,partition:function(t,e){var n={lhs:[],rhs:[]};return r.forEach(t,(function(t){e(t)?n.lhs.push(t):n.rhs.push(t)})),n},time:function(t,e){var n=r.now();try{return e()}finally{console.log(t+" time: "+(r.now()-n)+"ms")}},notime:function(t,e){return e()}}},57589:t=>{t.exports="0.8.5"},87377:(t,e,n)=>{var r=n(89);t.exports={Graph:r.Graph,json:n(80109),alg:n(577),version:r.version}},95189:(t,e,n)=>{var r=n(60274);t.exports=function(t){var e,n={},i=[];function a(i){r.has(n,i)||(n[i]=!0,e.push(i),r.each(t.successors(i),a),r.each(t.predecessors(i),a))}return r.each(t.nodes(),(function(t){e=[],a(t),e.length&&i.push(e)})),i}},70223:(t,e,n)=>{var r=n(60274);function i(t,e,n,a,o,u){r.has(a,e)||(a[e]=!0,n||u.push(e),r.each(o(e),(function(e){i(t,e,n,a,o,u)})),n&&u.push(e))}t.exports=function(t,e,n){r.isArray(e)||(e=[e]);var a=(t.isDirected()?t.successors:t.neighbors).bind(t),o=[],u={};return r.each(e,(function(e){if(!t.hasNode(e))throw new Error("Graph does not have node: "+e);i(t,e,"post"===n,u,a,o)})),o}},19487:(t,e,n)=>{var r=n(16493),i=n(60274);t.exports=function(t,e,n){return i.transform(t.nodes(),(function(i,a){i[a]=r(t,a,e,n)}),{})}},16493:(t,e,n)=>{var r=n(60274),i=n(70905);t.exports=function(t,e,n,r){return function(t,e,n,r){var a,o,u={},s=new i,c=function(t){var e=t.v!==a?t.v:t.w,r=u[e],i=n(t),c=o.distance+i;if(i<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+t+" Weight: "+i);c0&&(a=s.removeMin(),(o=u[a]).distance!==Number.POSITIVE_INFINITY);)r(a).forEach(c);return u}(t,String(e),n||a,r||function(e){return t.outEdges(e)})};var a=r.constant(1)},24395:(t,e,n)=>{var r=n(60274),i=n(99289);t.exports=function(t){return r.filter(i(t),(function(e){return e.length>1||1===e.length&&t.hasEdge(e[0],e[0])}))}},92077:(t,e,n)=>{var r=n(60274);t.exports=function(t,e,n){return function(t,e,n){var r={},i=t.nodes();return i.forEach((function(t){r[t]={},r[t][t]={distance:0},i.forEach((function(e){t!==e&&(r[t][e]={distance:Number.POSITIVE_INFINITY})})),n(t).forEach((function(n){var i=n.v===t?n.w:n.v,a=e(n);r[t][i]={distance:a,predecessor:t}}))})),i.forEach((function(t){var e=r[t];i.forEach((function(n){var a=r[n];i.forEach((function(n){var r=a[t],i=e[n],o=a[n],u=r.distance+i.distance;u{t.exports={components:n(95189),dijkstra:n(16493),dijkstraAll:n(19487),findCycles:n(24395),floydWarshall:n(92077),isAcyclic:n(67141),postorder:n(53533),preorder:n(78852),prim:n(78492),tarjan:n(99289),topsort:n(69176)}},67141:(t,e,n)=>{var r=n(69176);t.exports=function(t){try{r(t)}catch(t){if(t instanceof r.CycleException)return!1;throw t}return!0}},53533:(t,e,n)=>{var r=n(70223);t.exports=function(t,e){return r(t,e,"post")}},78852:(t,e,n)=>{var r=n(70223);t.exports=function(t,e){return r(t,e,"pre")}},78492:(t,e,n)=>{var r=n(60274),i=n(53099),a=n(70905);t.exports=function(t,e){var n,o=new i,u={},s=new a;function c(t){var r=t.v===n?t.w:t.v,i=s.priority(r);if(void 0!==i){var a=e(t);a0;){if(n=s.removeMin(),r.has(u,n))o.setEdge(n,u[n]);else{if(f)throw new Error("Input graph is not connected: "+t);f=!0}t.nodeEdges(n).forEach(c)}return o}},99289:(t,e,n)=>{var r=n(60274);t.exports=function(t){var e=0,n=[],i={},a=[];function o(u){var s=i[u]={onStack:!0,lowlink:e,index:e++};if(n.push(u),t.successors(u).forEach((function(t){r.has(i,t)?i[t].onStack&&(s.lowlink=Math.min(s.lowlink,i[t].index)):(o(t),s.lowlink=Math.min(s.lowlink,i[t].lowlink))})),s.lowlink===s.index){var c,f=[];do{c=n.pop(),i[c].onStack=!1,f.push(c)}while(u!==c);a.push(f)}}return t.nodes().forEach((function(t){r.has(i,t)||o(t)})),a}},69176:(t,e,n)=>{var r=n(60274);function i(t){var e={},n={},i=[];if(r.each(t.sinks(),(function o(u){if(r.has(n,u))throw new a;r.has(e,u)||(n[u]=!0,e[u]=!0,r.each(t.predecessors(u),o),delete n[u],i.push(u))})),r.size(e)!==t.nodeCount())throw new a;return i}function a(){}t.exports=i,i.CycleException=a,a.prototype=new Error},70905:(t,e,n)=>{var r=n(60274);function i(){this._arr=[],this._keyIndices={}}t.exports=i,i.prototype.size=function(){return this._arr.length},i.prototype.keys=function(){return this._arr.map((function(t){return t.key}))},i.prototype.has=function(t){return r.has(this._keyIndices,t)},i.prototype.priority=function(t){var e=this._keyIndices[t];if(void 0!==e)return this._arr[e].priority},i.prototype.min=function(){if(0===this.size())throw new Error("Queue underflow");return this._arr[0].key},i.prototype.add=function(t,e){var n=this._keyIndices;if(t=String(t),!r.has(n,t)){var i=this._arr,a=i.length;return n[t]=a,i.push({key:t,priority:e}),this._decrease(a),!0}return!1},i.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var t=this._arr.pop();return delete this._keyIndices[t.key],this._heapify(0),t.key},i.prototype.decrease=function(t,e){var n=this._keyIndices[t];if(e>this._arr[n].priority)throw new Error("New priority is greater than current priority. Key: "+t+" Old: "+this._arr[n].priority+" New: "+e);this._arr[n].priority=e,this._decrease(n)},i.prototype._heapify=function(t){var e=this._arr,n=2*t,r=n+1,i=t;n>1].priority{"use strict";var r=n(60274);t.exports=a;var i="\0";function a(t){this._isDirected=!r.has(t,"directed")||t.directed,this._isMultigraph=!!r.has(t,"multigraph")&&t.multigraph,this._isCompound=!!r.has(t,"compound")&&t.compound,this._label=void 0,this._defaultNodeLabelFn=r.constant(void 0),this._defaultEdgeLabelFn=r.constant(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children["\0"]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}function o(t,e){t[e]?t[e]++:t[e]=1}function u(t,e){--t[e]||delete t[e]}function s(t,e,n,i){var a=""+e,o=""+n;if(!t&&a>o){var u=a;a=o,o=u}return a+""+o+""+(r.isUndefined(i)?"\0":i)}function c(t,e,n,r){var i=""+e,a=""+n;if(!t&&i>a){var o=i;i=a,a=o}var u={v:i,w:a};return r&&(u.name=r),u}function f(t,e){return s(t,e.v,e.w,e.name)}a.prototype._nodeCount=0,a.prototype._edgeCount=0,a.prototype.isDirected=function(){return this._isDirected},a.prototype.isMultigraph=function(){return this._isMultigraph},a.prototype.isCompound=function(){return this._isCompound},a.prototype.setGraph=function(t){return this._label=t,this},a.prototype.graph=function(){return this._label},a.prototype.setDefaultNodeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultNodeLabelFn=t,this},a.prototype.nodeCount=function(){return this._nodeCount},a.prototype.nodes=function(){return r.keys(this._nodes)},a.prototype.sources=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._in[e])}))},a.prototype.sinks=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._out[e])}))},a.prototype.setNodes=function(t,e){var n=arguments,i=this;return r.each(t,(function(t){n.length>1?i.setNode(t,e):i.setNode(t)})),this},a.prototype.setNode=function(t,e){return r.has(this._nodes,t)?(arguments.length>1&&(this._nodes[t]=e),this):(this._nodes[t]=arguments.length>1?e:this._defaultNodeLabelFn(t),this._isCompound&&(this._parent[t]=i,this._children[t]={},this._children["\0"][t]=!0),this._in[t]={},this._preds[t]={},this._out[t]={},this._sucs[t]={},++this._nodeCount,this)},a.prototype.node=function(t){return this._nodes[t]},a.prototype.hasNode=function(t){return r.has(this._nodes,t)},a.prototype.removeNode=function(t){var e=this;if(r.has(this._nodes,t)){var n=function(t){e.removeEdge(e._edgeObjs[t])};delete this._nodes[t],this._isCompound&&(this._removeFromParentsChildList(t),delete this._parent[t],r.each(this.children(t),(function(t){e.setParent(t)})),delete this._children[t]),r.each(r.keys(this._in[t]),n),delete this._in[t],delete this._preds[t],r.each(r.keys(this._out[t]),n),delete this._out[t],delete this._sucs[t],--this._nodeCount}return this},a.prototype.setParent=function(t,e){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(r.isUndefined(e))e=i;else{for(var n=e+="";!r.isUndefined(n);n=this.parent(n))if(n===t)throw new Error("Setting "+e+" as parent of "+t+" would create a cycle");this.setNode(e)}return this.setNode(t),this._removeFromParentsChildList(t),this._parent[t]=e,this._children[e][t]=!0,this},a.prototype._removeFromParentsChildList=function(t){delete this._children[this._parent[t]][t]},a.prototype.parent=function(t){if(this._isCompound){var e=this._parent[t];if(e!==i)return e}},a.prototype.children=function(t){if(r.isUndefined(t)&&(t=i),this._isCompound){var e=this._children[t];if(e)return r.keys(e)}else{if(t===i)return this.nodes();if(this.hasNode(t))return[]}},a.prototype.predecessors=function(t){var e=this._preds[t];if(e)return r.keys(e)},a.prototype.successors=function(t){var e=this._sucs[t];if(e)return r.keys(e)},a.prototype.neighbors=function(t){var e=this.predecessors(t);if(e)return r.union(e,this.successors(t))},a.prototype.isLeaf=function(t){return 0===(this.isDirected()?this.successors(t):this.neighbors(t)).length},a.prototype.filterNodes=function(t){var e=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});e.setGraph(this.graph());var n=this;r.each(this._nodes,(function(n,r){t(r)&&e.setNode(r,n)})),r.each(this._edgeObjs,(function(t){e.hasNode(t.v)&&e.hasNode(t.w)&&e.setEdge(t,n.edge(t))}));var i={};function a(t){var r=n.parent(t);return void 0===r||e.hasNode(r)?(i[t]=r,r):r in i?i[r]:a(r)}return this._isCompound&&r.each(e.nodes(),(function(t){e.setParent(t,a(t))})),e},a.prototype.setDefaultEdgeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultEdgeLabelFn=t,this},a.prototype.edgeCount=function(){return this._edgeCount},a.prototype.edges=function(){return r.values(this._edgeObjs)},a.prototype.setPath=function(t,e){var n=this,i=arguments;return r.reduce(t,(function(t,r){return i.length>1?n.setEdge(t,r,e):n.setEdge(t,r),r})),this},a.prototype.setEdge=function(){var t,e,n,i,a=!1,u=arguments[0];"object"==typeof u&&null!==u&&"v"in u?(t=u.v,e=u.w,n=u.name,2===arguments.length&&(i=arguments[1],a=!0)):(t=u,e=arguments[1],n=arguments[3],arguments.length>2&&(i=arguments[2],a=!0)),t=""+t,e=""+e,r.isUndefined(n)||(n=""+n);var f=s(this._isDirected,t,e,n);if(r.has(this._edgeLabels,f))return a&&(this._edgeLabels[f]=i),this;if(!r.isUndefined(n)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(t),this.setNode(e),this._edgeLabels[f]=a?i:this._defaultEdgeLabelFn(t,e,n);var l=c(this._isDirected,t,e,n);return t=l.v,e=l.w,Object.freeze(l),this._edgeObjs[f]=l,o(this._preds[e],t),o(this._sucs[t],e),this._in[e][f]=l,this._out[t][f]=l,this._edgeCount++,this},a.prototype.edge=function(t,e,n){var r=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n);return this._edgeLabels[r]},a.prototype.hasEdge=function(t,e,n){var i=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n);return r.has(this._edgeLabels,i)},a.prototype.removeEdge=function(t,e,n){var r=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n),i=this._edgeObjs[r];return i&&(t=i.v,e=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],u(this._preds[e],t),u(this._sucs[t],e),delete this._in[e][r],delete this._out[t][r],this._edgeCount--),this},a.prototype.inEdges=function(t,e){var n=this._in[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.v===e})):i}},a.prototype.outEdges=function(t,e){var n=this._out[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.w===e})):i}},a.prototype.nodeEdges=function(t,e){var n=this.inEdges(t,e);if(n)return n.concat(this.outEdges(t,e))}},89:(t,e,n)=>{t.exports={Graph:n(53099),version:n(90702)}},80109:(t,e,n)=>{var r=n(60274),i=n(53099);function a(t){return r.map(t.nodes(),(function(e){var n=t.node(e),i=t.parent(e),a={v:e};return r.isUndefined(n)||(a.value=n),r.isUndefined(i)||(a.parent=i),a}))}function o(t){return r.map(t.edges(),(function(e){var n=t.edge(e),i={v:e.v,w:e.w};return r.isUndefined(e.name)||(i.name=e.name),r.isUndefined(n)||(i.value=n),i}))}t.exports={write:function(t){var e={options:{directed:t.isDirected(),multigraph:t.isMultigraph(),compound:t.isCompound()},nodes:a(t),edges:o(t)};return r.isUndefined(t.graph())||(e.value=r.clone(t.graph())),e},read:function(t){var e=new i(t.options).setGraph(t.value);return r.each(t.nodes,(function(t){e.setNode(t.v,t.value),t.parent&&e.setParent(t.v,t.parent)})),r.each(t.edges,(function(t){e.setEdge({v:t.v,w:t.w,name:t.name},t.value)})),e}}},60274:(t,e,n)=>{var r;try{r={clone:n(54004),constant:n(86874),each:n(79421),filter:n(90882),has:n(93352),isArray:n(86152),isEmpty:n(45455),isFunction:n(61049),isUndefined:n(84336),keys:n(90249),map:n(16760),reduce:n(58215),size:n(36402),transform:n(89466),union:n(26139),values:n(98346)}}catch(t){}r||(r=window._),t.exports=r},90702:t=>{t.exports="2.1.8"},39515:(t,e,n)=>{var r=n(38761)(n(37772),"DataView");t.exports=r},89612:(t,e,n)=>{var r=n(52118),i=n(96909),a=n(98138),o=n(4174),u=n(7942);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(3945),i=n(21846),a=n(88028),o=n(72344),u=n(94769);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(38761)(n(37772),"Map");t.exports=r},96738:(t,e,n)=>{var r=n(92411),i=n(36417),a=n(86928),o=n(18052),u=n(24150);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(38761)(n(37772),"Promise");t.exports=r},2143:(t,e,n)=>{var r=n(38761)(n(37772),"Set");t.exports=r},45386:(t,e,n)=>{var r=n(96738),i=n(52842),a=n(52482);function o(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new r;++e{var r=n(80235),i=n(15243),a=n(72858),o=n(4417),u=n(8605),s=n(71418);function c(t){var e=this.__data__=new r(t);this.size=e.size}c.prototype.clear=i,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=u,c.prototype.set=s,t.exports=c},50857:(t,e,n)=>{var r=n(37772).Symbol;t.exports=r},79162:(t,e,n)=>{var r=n(37772).Uint8Array;t.exports=r},93215:(t,e,n)=>{var r=n(38761)(n(37772),"WeakMap");t.exports=r},49432:t=>{t.exports=function(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}},72517:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=0,a=[];++n{var r=n(77832);t.exports=function(t,e){return!(null==t||!t.length)&&r(t,e,0)>-1}},34893:t=>{t.exports=function(t,e,n){for(var r=-1,i=null==t?0:t.length;++r{var r=n(36473),i=n(79631),a=n(86152),o=n(73226),u=n(39045),s=n(77598),c=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=a(t),f=!n&&i(t),l=!n&&!f&&o(t),h=!n&&!f&&!l&&s(t),d=n||f||l||h,p=d?r(t.length,String):[],v=p.length;for(var g in t)!e&&!c.call(t,g)||d&&("length"==g||l&&("offset"==g||"parent"==g)||h&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||u(g,v))||p.push(g);return p}},50343:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n{t.exports=function(t,e){for(var n=-1,r=e.length,i=t.length;++n{t.exports=function(t,e,n,r){var i=-1,a=null==t?0:t.length;for(r&&a&&(n=t[++i]);++i{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n{var r=n(20256)("length");t.exports=r},28582:(t,e,n)=>{var r=n(13940),i=n(41225);t.exports=function(t,e,n){(void 0!==n&&!i(t[e],n)||void 0===n&&!(e in t))&&r(t,e,n)}},60091:(t,e,n)=>{var r=n(13940),i=n(41225),a=Object.prototype.hasOwnProperty;t.exports=function(t,e,n){var o=t[e];a.call(t,e)&&i(o,n)&&(void 0!==n||e in t)||r(t,e,n)}},22218:(t,e,n)=>{var r=n(41225);t.exports=function(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return-1}},67993:(t,e,n)=>{var r=n(752),i=n(90249);t.exports=function(t,e){return t&&r(e,i(e),t)}},55906:(t,e,n)=>{var r=n(752),i=n(18582);t.exports=function(t,e){return t&&r(e,i(e),t)}},13940:(t,e,n)=>{var r=n(83043);t.exports=function(t,e,n){"__proto__"==e&&r?r(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}},18874:(t,e,n)=>{var r=n(86571),i=n(72517),a=n(60091),o=n(67993),u=n(55906),s=n(92175),c=n(51522),f=n(7680),l=n(19987),h=n(13483),d=n(76939),p=n(70940),v=n(99917),g=n(8222),_=n(78725),b=n(86152),y=n(73226),m=n(4714),x=n(29259),w=n(43679),Z=n(90249),D=n(18582),k="[object Arguments]",E="[object Function]",A="[object Object]",j={};j[k]=j["[object Array]"]=j["[object ArrayBuffer]"]=j["[object DataView]"]=j["[object Boolean]"]=j["[object Date]"]=j["[object Float32Array]"]=j["[object Float64Array]"]=j["[object Int8Array]"]=j["[object Int16Array]"]=j["[object Int32Array]"]=j["[object Map]"]=j["[object Number]"]=j[A]=j["[object RegExp]"]=j["[object Set]"]=j["[object String]"]=j["[object Symbol]"]=j["[object Uint8Array]"]=j["[object Uint8ClampedArray]"]=j["[object Uint16Array]"]=j["[object Uint32Array]"]=!0,j["[object Error]"]=j[E]=j["[object WeakMap]"]=!1,t.exports=function t(e,n,C,M,F,B){var S,N=1&n,T=2&n,z=4&n;if(C&&(S=F?C(e,M,F,B):C(e)),void 0!==S)return S;if(!x(e))return e;var O=b(e);if(O){if(S=v(e),!N)return c(e,S)}else{var R=p(e),P=R==E||"[object GeneratorFunction]"==R;if(y(e))return s(e,N);if(R==A||R==k||P&&!F){if(S=T||P?{}:_(e),!N)return T?l(e,u(S,e)):f(e,o(S,e))}else{if(!j[R])return F?e:{};S=g(e,R,N)}}B||(B=new r);var I=B.get(e);if(I)return I;B.set(e,S),w(e)?e.forEach((function(r){S.add(t(r,n,C,r,e,B))})):m(e)&&e.forEach((function(r,i){S.set(i,t(r,n,C,i,e,B))}));var L=O?void 0:(z?T?d:h:T?D:Z)(e);return i(L||e,(function(r,i){L&&(r=e[i=r]),a(S,i,t(r,n,C,i,e,B))})),S}},39413:(t,e,n)=>{var r=n(29259),i=Object.create,a=function(){function t(){}return function(e){if(!r(e))return{};if(i)return i(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();t.exports=a},24303:(t,e,n)=>{var r=n(26548),i=n(92019)(r);t.exports=i},2229:(t,e,n)=>{var r=n(4795);t.exports=function(t,e,n){for(var i=-1,a=t.length;++i{var r=n(24303);t.exports=function(t,e){var n=[];return r(t,(function(t,r,i){e(t,r,i)&&n.push(t)})),n}},21359:t=>{t.exports=function(t,e,n,r){for(var i=t.length,a=n+(r?1:-1);r?a--:++a{var r=n(65067),i=n(95882);t.exports=function t(e,n,a,o,u){var s=-1,c=e.length;for(a||(a=i),u||(u=[]);++s0&&a(f)?n>1?t(f,n-1,a,o,u):r(u,f):o||(u[u.length]=f)}return u}},15308:(t,e,n)=>{var r=n(55463)();t.exports=r},26548:(t,e,n)=>{var r=n(15308),i=n(90249);t.exports=function(t,e){return t&&r(t,e,i)}},13324:(t,e,n)=>{var r=n(17297),i=n(33812);t.exports=function(t,e){for(var n=0,a=(e=r(e,t)).length;null!=t&&n{var r=n(65067),i=n(86152);t.exports=function(t,e,n){var a=e(t);return i(t)?a:r(a,n(t))}},53366:(t,e,n)=>{var r=n(50857),i=n(62107),a=n(37157),o=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":o&&o in Object(t)?i(t):a(t)}},84134:t=>{t.exports=function(t,e){return t>e}},32726:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t,n){return null!=t&&e.call(t,n)}},20187:t=>{t.exports=function(t,e){return null!=t&&e in Object(t)}},77832:(t,e,n)=>{var r=n(21359),i=n(22195),a=n(66024);t.exports=function(t,e,n){return e==e?a(t,e,n):r(t,i,n)}},15183:(t,e,n)=>{var r=n(53366),i=n(15125);t.exports=function(t){return i(t)&&"[object Arguments]"==r(t)}},88746:(t,e,n)=>{var r=n(51952),i=n(15125);t.exports=function t(e,n,a,o,u){return e===n||(null==e||null==n||!i(e)&&!i(n)?e!=e&&n!=n:r(e,n,a,o,t,u))}},51952:(t,e,n)=>{var r=n(86571),i=n(74871),a=n(8703),o=n(17416),u=n(70940),s=n(86152),c=n(73226),f=n(77598),l="[object Arguments]",h="[object Array]",d="[object Object]",p=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,v,g,_){var b=s(t),y=s(e),m=b?h:u(t),x=y?h:u(e),w=(m=m==l?d:m)==d,Z=(x=x==l?d:x)==d,D=m==x;if(D&&c(t)){if(!c(e))return!1;b=!0,w=!1}if(D&&!w)return _||(_=new r),b||f(t)?i(t,e,n,v,g,_):a(t,e,m,n,v,g,_);if(!(1&n)){var k=w&&p.call(t,"__wrapped__"),E=Z&&p.call(e,"__wrapped__");if(k||E){var A=k?t.value():t,j=E?e.value():e;return _||(_=new r),g(A,j,n,v,_)}}return!!D&&(_||(_=new r),o(t,e,n,v,g,_))}},74511:(t,e,n)=>{var r=n(70940),i=n(15125);t.exports=function(t){return i(t)&&"[object Map]"==r(t)}},37036:(t,e,n)=>{var r=n(86571),i=n(88746);t.exports=function(t,e,n,a){var o=n.length,u=o,s=!a;if(null==t)return!u;for(t=Object(t);o--;){var c=n[o];if(s&&c[2]?c[1]!==t[c[0]]:!(c[0]in t))return!1}for(;++o{t.exports=function(t){return t!=t}},6840:(t,e,n)=>{var r=n(61049),i=n(47394),a=n(29259),o=n(87035),u=/^\[object .+?Constructor\]$/,s=Function.prototype,c=Object.prototype,f=s.toString,l=c.hasOwnProperty,h=RegExp("^"+f.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!a(t)||i(t))&&(r(t)?h:u).test(o(t))}},8109:(t,e,n)=>{var r=n(70940),i=n(15125);t.exports=function(t){return i(t)&&"[object Set]"==r(t)}},35522:(t,e,n)=>{var r=n(53366),i=n(61158),a=n(15125),o={};o["[object Float32Array]"]=o["[object Float64Array]"]=o["[object Int8Array]"]=o["[object Int16Array]"]=o["[object Int32Array]"]=o["[object Uint8Array]"]=o["[object Uint8ClampedArray]"]=o["[object Uint16Array]"]=o["[object Uint32Array]"]=!0,o["[object Arguments]"]=o["[object Array]"]=o["[object ArrayBuffer]"]=o["[object Boolean]"]=o["[object DataView]"]=o["[object Date]"]=o["[object Error]"]=o["[object Function]"]=o["[object Map]"]=o["[object Number]"]=o["[object Object]"]=o["[object RegExp]"]=o["[object Set]"]=o["[object String]"]=o["[object WeakMap]"]=!1,t.exports=function(t){return a(t)&&i(t.length)&&!!o[r(t)]}},68286:(t,e,n)=>{var r=n(26423),i=n(74716),a=n(23059),o=n(86152),u=n(65798);t.exports=function(t){return"function"==typeof t?t:null==t?a:"object"==typeof t?o(t)?i(t[0],t[1]):r(t):u(t)}},86411:(t,e,n)=>{var r=n(16001),i=n(54248),a=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return i(t);var e=[];for(var n in Object(t))a.call(t,n)&&"constructor"!=n&&e.push(n);return e}},18390:(t,e,n)=>{var r=n(29259),i=n(16001),a=n(62966),o=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return a(t);var e=i(t),n=[];for(var u in t)("constructor"!=u||!e&&o.call(t,u))&&n.push(u);return n}},17606:t=>{t.exports=function(t,e){return t{var r=n(24303),i=n(67878);t.exports=function(t,e){var n=-1,a=i(t)?Array(t.length):[];return r(t,(function(t,r,i){a[++n]=e(t,r,i)})),a}},26423:(t,e,n)=>{var r=n(37036),i=n(49882),a=n(73477);t.exports=function(t){var e=i(t);return 1==e.length&&e[0][2]?a(e[0][0],e[0][1]):function(n){return n===t||r(n,t,e)}}},74716:(t,e,n)=>{var r=n(88746),i=n(72579),a=n(95041),o=n(21401),u=n(28792),s=n(73477),c=n(33812);t.exports=function(t,e){return o(t)&&u(e)?s(c(t),e):function(n){var o=i(n,t);return void 0===o&&o===e?a(n,t):r(e,o,3)}}},84565:(t,e,n)=>{var r=n(86571),i=n(28582),a=n(15308),o=n(25561),u=n(29259),s=n(18582),c=n(52434);t.exports=function t(e,n,f,l,h){e!==n&&a(n,(function(a,s){if(h||(h=new r),u(a))o(e,n,s,f,t,l,h);else{var d=l?l(c(e,s),a,s+"",e,n,h):void 0;void 0===d&&(d=a),i(e,s,d)}}),s)}},25561:(t,e,n)=>{var r=n(28582),i=n(92175),a=n(6190),o=n(51522),u=n(78725),s=n(79631),c=n(86152),f=n(93746),l=n(73226),h=n(61049),d=n(29259),p=n(97030),v=n(77598),g=n(52434),_=n(63329);t.exports=function(t,e,n,b,y,m,x){var w=g(t,n),Z=g(e,n),D=x.get(Z);if(D)r(t,n,D);else{var k=m?m(w,Z,n+"",t,e,x):void 0,E=void 0===k;if(E){var A=c(Z),j=!A&&l(Z),C=!A&&!j&&v(Z);k=Z,A||j||C?c(w)?k=w:f(w)?k=o(w):j?(E=!1,k=i(Z,!0)):C?(E=!1,k=a(Z,!0)):k=[]:p(Z)||s(Z)?(k=w,s(w)?k=_(w):d(w)&&!h(w)||(k=u(Z))):E=!1}E&&(x.set(Z,k),y(k,Z,b,m,x),x.delete(Z)),r(t,n,k)}}},23813:(t,e,n)=>{var r=n(50343),i=n(13324),a=n(68286),o=n(93401),u=n(27095),s=n(47826),c=n(18477),f=n(23059),l=n(86152);t.exports=function(t,e,n){e=e.length?r(e,(function(t){return l(t)?function(e){return i(e,1===t.length?t[0]:t)}:t})):[f];var h=-1;e=r(e,s(a));var d=o(t,(function(t,n,i){return{criteria:r(e,(function(e){return e(t)})),index:++h,value:t}}));return u(d,(function(t,e){return c(t,e,n)}))}},92602:(t,e,n)=>{var r=n(93759),i=n(95041);t.exports=function(t,e){return r(t,e,(function(e,n){return i(t,n)}))}},93759:(t,e,n)=>{var r=n(13324),i=n(82857),a=n(17297);t.exports=function(t,e,n){for(var o=-1,u=e.length,s={};++o{t.exports=function(t){return function(e){return null==e?void 0:e[t]}}},82952:(t,e,n)=>{var r=n(13324);t.exports=function(t){return function(e){return r(e,t)}}},93228:t=>{var e=Math.ceil,n=Math.max;t.exports=function(t,r,i,a){for(var o=-1,u=n(e((r-t)/(i||1)),0),s=Array(u);u--;)s[a?u:++o]=t,t+=i;return s}},5877:t=>{t.exports=function(t,e,n,r,i){return i(t,(function(t,i,a){n=r?(r=!1,t):e(n,t,i,a)})),n}},36060:(t,e,n)=>{var r=n(23059),i=n(43114),a=n(75251);t.exports=function(t,e){return a(i(t,e,r),t+"")}},82857:(t,e,n)=>{var r=n(60091),i=n(17297),a=n(39045),o=n(29259),u=n(33812);t.exports=function(t,e,n,s){if(!o(t))return t;for(var c=-1,f=(e=i(e,t)).length,l=f-1,h=t;null!=h&&++c{var r=n(86874),i=n(83043),a=n(23059),o=i?function(t,e){return i(t,"toString",{configurable:!0,enumerable:!1,value:r(e),writable:!0})}:a;t.exports=o},27095:t=>{t.exports=function(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}},36473:t=>{t.exports=function(t,e){for(var n=-1,r=Array(t);++n{var r=n(50857),i=n(50343),a=n(86152),o=n(4795),u=r?r.prototype:void 0,s=u?u.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(a(e))return i(e,t)+"";if(o(e))return s?s.call(e):"";var n=e+"";return"0"==n&&1/e==-1/0?"-0":n}},51704:(t,e,n)=>{var r=n(52153),i=/^\s+/;t.exports=function(t){return t?t.slice(0,r(t)+1).replace(i,""):t}},47826:t=>{t.exports=function(t){return function(e){return t(e)}}},67326:(t,e,n)=>{var r=n(45386),i=n(38333),a=n(34893),o=n(59950),u=n(78803),s=n(16909);t.exports=function(t,e,n){var c=-1,f=i,l=t.length,h=!0,d=[],p=d;if(n)h=!1,f=a;else if(l>=200){var v=e?null:u(t);if(v)return s(v);h=!1,f=o,p=new r}else p=e?[]:d;t:for(;++c{var r=n(50343);t.exports=function(t,e){return r(e,(function(e){return t[e]}))}},40509:t=>{t.exports=function(t,e,n){for(var r=-1,i=t.length,a=e.length,o={};++r{t.exports=function(t,e){return t.has(e)}},89419:(t,e,n)=>{var r=n(23059);t.exports=function(t){return"function"==typeof t?t:r}},17297:(t,e,n)=>{var r=n(86152),i=n(21401),a=n(54452),o=n(66188);t.exports=function(t,e){return r(t)?t:i(t,e)?[t]:a(o(t))}},79882:(t,e,n)=>{var r=n(79162);t.exports=function(t){var e=new t.constructor(t.byteLength);return new r(e).set(new r(t)),e}},92175:(t,e,n)=>{t=n.nmd(t);var r=n(37772),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i?r.Buffer:void 0,u=o?o.allocUnsafe:void 0;t.exports=function(t,e){if(e)return t.slice();var n=t.length,r=u?u(n):new t.constructor(n);return t.copy(r),r}},34727:(t,e,n)=>{var r=n(79882);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}},96058:t=>{var e=/\w*$/;t.exports=function(t){var n=new t.constructor(t.source,e.exec(t));return n.lastIndex=t.lastIndex,n}},70169:(t,e,n)=>{var r=n(50857),i=r?r.prototype:void 0,a=i?i.valueOf:void 0;t.exports=function(t){return a?Object(a.call(t)):{}}},6190:(t,e,n)=>{var r=n(79882);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}},27520:(t,e,n)=>{var r=n(4795);t.exports=function(t,e){if(t!==e){var n=void 0!==t,i=null===t,a=t==t,o=r(t),u=void 0!==e,s=null===e,c=e==e,f=r(e);if(!s&&!f&&!o&&t>e||o&&u&&c&&!s&&!f||i&&u&&c||!n&&c||!a)return 1;if(!i&&!o&&!f&&t{var r=n(27520);t.exports=function(t,e,n){for(var i=-1,a=t.criteria,o=e.criteria,u=a.length,s=n.length;++i=s?c:c*("desc"==n[i]?-1:1)}return t.index-e.index}},51522:t=>{t.exports=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n{var r=n(60091),i=n(13940);t.exports=function(t,e,n,a){var o=!n;n||(n={});for(var u=-1,s=e.length;++u{var r=n(752),i=n(80633);t.exports=function(t,e){return r(t,i(t),e)}},19987:(t,e,n)=>{var r=n(752),i=n(12680);t.exports=function(t,e){return r(t,i(t),e)}},24019:(t,e,n)=>{var r=n(37772)["__core-js_shared__"];t.exports=r},97263:(t,e,n)=>{var r=n(36060),i=n(82406);t.exports=function(t){return r((function(e,n){var r=-1,a=n.length,o=a>1?n[a-1]:void 0,u=a>2?n[2]:void 0;for(o=t.length>3&&"function"==typeof o?(a--,o):void 0,u&&i(n[0],n[1],u)&&(o=a<3?void 0:o,a=1),e=Object(e);++r{var r=n(67878);t.exports=function(t,e){return function(n,i){if(null==n)return n;if(!r(n))return t(n,i);for(var a=n.length,o=e?a:-1,u=Object(n);(e?o--:++o{t.exports=function(t){return function(e,n,r){for(var i=-1,a=Object(e),o=r(e),u=o.length;u--;){var s=o[t?u:++i];if(!1===n(a[s],s,a))break}return e}}},98776:(t,e,n)=>{var r=n(68286),i=n(67878),a=n(90249);t.exports=function(t){return function(e,n,o){var u=Object(e);if(!i(e)){var s=r(n,3);e=a(e),n=function(t){return s(u[t],t,u)}}var c=t(e,n,o);return c>-1?u[s?e[c]:c]:void 0}}},82941:(t,e,n)=>{var r=n(93228),i=n(82406),a=n(5707);t.exports=function(t){return function(e,n,o){return o&&"number"!=typeof o&&i(e,n,o)&&(n=o=void 0),e=a(e),void 0===n?(n=e,e=0):n=a(n),o=void 0===o?e{var r=n(2143),i=n(34291),a=n(16909),o=r&&1/a(new r([,-0]))[1]==1/0?function(t){return new r(t)}:i;t.exports=o},83043:(t,e,n)=>{var r=n(38761),i=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=i},74871:(t,e,n)=>{var r=n(45386),i=n(87064),a=n(59950);t.exports=function(t,e,n,o,u,s){var c=1&n,f=t.length,l=e.length;if(f!=l&&!(c&&l>f))return!1;var h=s.get(t),d=s.get(e);if(h&&d)return h==e&&d==t;var p=-1,v=!0,g=2&n?new r:void 0;for(s.set(t,e),s.set(e,t);++p{var r=n(50857),i=n(79162),a=n(41225),o=n(74871),u=n(75179),s=n(16909),c=r?r.prototype:void 0,f=c?c.valueOf:void 0;t.exports=function(t,e,n,r,c,l,h){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return!(t.byteLength!=e.byteLength||!l(new i(t),new i(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return a(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var d=u;case"[object Set]":var p=1&r;if(d||(d=s),t.size!=e.size&&!p)return!1;var v=h.get(t);if(v)return v==e;r|=2,h.set(t,e);var g=o(d(t),d(e),r,c,l,h);return h.delete(t),g;case"[object Symbol]":if(f)return f.call(t)==f.call(e)}return!1}},17416:(t,e,n)=>{var r=n(13483),i=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,a,o,u){var s=1&n,c=r(t),f=c.length;if(f!=r(e).length&&!s)return!1;for(var l=f;l--;){var h=c[l];if(!(s?h in e:i.call(e,h)))return!1}var d=u.get(t),p=u.get(e);if(d&&p)return d==e&&p==t;var v=!0;u.set(t,e),u.set(e,t);for(var g=s;++l{var r=n(35676),i=n(43114),a=n(75251);t.exports=function(t){return a(i(t,void 0,r),t+"")}},51242:(t,e,n)=>{var r="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;t.exports=r},13483:(t,e,n)=>{var r=n(1897),i=n(80633),a=n(90249);t.exports=function(t){return r(t,a,i)}},76939:(t,e,n)=>{var r=n(1897),i=n(12680),a=n(18582);t.exports=function(t){return r(t,a,i)}},27937:(t,e,n)=>{var r=n(98304);t.exports=function(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}},49882:(t,e,n)=>{var r=n(28792),i=n(90249);t.exports=function(t){for(var e=i(t),n=e.length;n--;){var a=e[n],o=t[a];e[n]=[a,o,r(o)]}return e}},38761:(t,e,n)=>{var r=n(6840),i=n(98109);t.exports=function(t,e){var n=i(t,e);return r(n)?n:void 0}},47353:(t,e,n)=>{var r=n(60241)(Object.getPrototypeOf,Object);t.exports=r},62107:(t,e,n)=>{var r=n(50857),i=Object.prototype,a=i.hasOwnProperty,o=i.toString,u=r?r.toStringTag:void 0;t.exports=function(t){var e=a.call(t,u),n=t[u];try{t[u]=void 0;var r=!0}catch(t){}var i=o.call(t);return r&&(e?t[u]=n:delete t[u]),i}},80633:(t,e,n)=>{var r=n(67552),i=n(30981),a=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,u=o?function(t){return null==t?[]:(t=Object(t),r(o(t),(function(e){return a.call(t,e)})))}:i;t.exports=u},12680:(t,e,n)=>{var r=n(65067),i=n(47353),a=n(80633),o=n(30981),u=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)r(e,a(t)),t=i(t);return e}:o;t.exports=u},70940:(t,e,n)=>{var r=n(39515),i=n(10326),a=n(52760),o=n(2143),u=n(93215),s=n(53366),c=n(87035),f="[object Map]",l="[object Promise]",h="[object Set]",d="[object WeakMap]",p="[object DataView]",v=c(r),g=c(i),_=c(a),b=c(o),y=c(u),m=s;(r&&m(new r(new ArrayBuffer(1)))!=p||i&&m(new i)!=f||a&&m(a.resolve())!=l||o&&m(new o)!=h||u&&m(new u)!=d)&&(m=function(t){var e=s(t),n="[object Object]"==e?t.constructor:void 0,r=n?c(n):"";if(r)switch(r){case v:return p;case g:return f;case _:return l;case b:return h;case y:return d}return e}),t.exports=m},98109:t=>{t.exports=function(t,e){return null==t?void 0:t[e]}},1369:(t,e,n)=>{var r=n(17297),i=n(79631),a=n(86152),o=n(39045),u=n(61158),s=n(33812);t.exports=function(t,e,n){for(var c=-1,f=(e=r(e,t)).length,l=!1;++c{var e=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return e.test(t)}},52118:(t,e,n)=>{var r=n(99191);t.exports=function(){this.__data__=r?r(null):{},this.size=0}},96909:t=>{t.exports=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}},98138:(t,e,n)=>{var r=n(99191),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;if(r){var n=e[t];return"__lodash_hash_undefined__"===n?void 0:n}return i.call(e,t)?e[t]:void 0}},4174:(t,e,n)=>{var r=n(99191),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;return r?void 0!==e[t]:i.call(e,t)}},7942:(t,e,n)=>{var r=n(99191);t.exports=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?"__lodash_hash_undefined__":e,this}},99917:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=t.length,r=new t.constructor(n);return n&&"string"==typeof t[0]&&e.call(t,"index")&&(r.index=t.index,r.input=t.input),r}},8222:(t,e,n)=>{var r=n(79882),i=n(34727),a=n(96058),o=n(70169),u=n(6190);t.exports=function(t,e,n){var s=t.constructor;switch(e){case"[object ArrayBuffer]":return r(t);case"[object Boolean]":case"[object Date]":return new s(+t);case"[object DataView]":return i(t,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return u(t,n);case"[object Map]":return new s;case"[object Number]":case"[object String]":return new s(t);case"[object RegExp]":return a(t);case"[object Set]":return new s;case"[object Symbol]":return o(t)}}},78725:(t,e,n)=>{var r=n(39413),i=n(47353),a=n(16001);t.exports=function(t){return"function"!=typeof t.constructor||a(t)?{}:r(i(t))}},95882:(t,e,n)=>{var r=n(50857),i=n(79631),a=n(86152),o=r?r.isConcatSpreadable:void 0;t.exports=function(t){return a(t)||i(t)||!!(o&&t&&t[o])}},39045:t=>{var e=/^(?:0|[1-9]\d*)$/;t.exports=function(t,n){var r=typeof t;return!!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&e.test(t))&&t>-1&&t%1==0&&t{var r=n(41225),i=n(67878),a=n(39045),o=n(29259);t.exports=function(t,e,n){if(!o(n))return!1;var u=typeof e;return!!("number"==u?i(n)&&a(e,n.length):"string"==u&&e in n)&&r(n[e],t)}},21401:(t,e,n)=>{var r=n(86152),i=n(4795),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=function(t,e){if(r(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!i(t))||o.test(t)||!a.test(t)||null!=e&&t in Object(e)}},98304:t=>{t.exports=function(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}},47394:(t,e,n)=>{var r,i=n(24019),a=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!a&&a in t}},16001:t=>{var e=Object.prototype;t.exports=function(t){var n=t&&t.constructor;return t===("function"==typeof n&&n.prototype||e)}},28792:(t,e,n)=>{var r=n(29259);t.exports=function(t){return t==t&&!r(t)}},3945:t=>{t.exports=function(){this.__data__=[],this.size=0}},21846:(t,e,n)=>{var r=n(22218),i=Array.prototype.splice;t.exports=function(t){var e=this.__data__,n=r(e,t);return!(n<0||(n==e.length-1?e.pop():i.call(e,n,1),--this.size,0))}},88028:(t,e,n)=>{var r=n(22218);t.exports=function(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]}},72344:(t,e,n)=>{var r=n(22218);t.exports=function(t){return r(this.__data__,t)>-1}},94769:(t,e,n)=>{var r=n(22218);t.exports=function(t,e){var n=this.__data__,i=r(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this}},92411:(t,e,n)=>{var r=n(89612),i=n(80235),a=n(10326);t.exports=function(){this.size=0,this.__data__={hash:new r,map:new(a||i),string:new r}}},36417:(t,e,n)=>{var r=n(27937);t.exports=function(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e}},86928:(t,e,n)=>{var r=n(27937);t.exports=function(t){return r(this,t).get(t)}},18052:(t,e,n)=>{var r=n(27937);t.exports=function(t){return r(this,t).has(t)}},24150:(t,e,n)=>{var r=n(27937);t.exports=function(t,e){var n=r(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}},75179:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}},73477:t=>{t.exports=function(t,e){return function(n){return null!=n&&n[t]===e&&(void 0!==e||t in Object(n))}}},77777:(t,e,n)=>{var r=n(30733);t.exports=function(t){var e=r(t,(function(t){return 500===n.size&&n.clear(),t})),n=e.cache;return e}},99191:(t,e,n)=>{var r=n(38761)(Object,"create");t.exports=r},54248:(t,e,n)=>{var r=n(60241)(Object.keys,Object);t.exports=r},62966:t=>{t.exports=function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}},4146:(t,e,n)=>{t=n.nmd(t);var r=n(51242),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i&&r.process,u=function(){try{return a&&a.require&&a.require("util").types||o&&o.binding&&o.binding("util")}catch(t){}}();t.exports=u},37157:t=>{var e=Object.prototype.toString;t.exports=function(t){return e.call(t)}},60241:t=>{t.exports=function(t,e){return function(n){return t(e(n))}}},43114:(t,e,n)=>{var r=n(49432),i=Math.max;t.exports=function(t,e,n){return e=i(void 0===e?t.length-1:e,0),function(){for(var a=arguments,o=-1,u=i(a.length-e,0),s=Array(u);++o{var r=n(51242),i="object"==typeof self&&self&&self.Object===Object&&self,a=r||i||Function("return this")();t.exports=a},52434:t=>{t.exports=function(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}},52842:t=>{t.exports=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this}},52482:t=>{t.exports=function(t){return this.__data__.has(t)}},16909:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}},75251:(t,e,n)=>{var r=n(86532),i=n(97787)(r);t.exports=i},97787:t=>{var e=Date.now;t.exports=function(t){var n=0,r=0;return function(){var i=e(),a=16-(i-r);if(r=i,a>0){if(++n>=800)return arguments[0]}else n=0;return t.apply(void 0,arguments)}}},15243:(t,e,n)=>{var r=n(80235);t.exports=function(){this.__data__=new r,this.size=0}},72858:t=>{t.exports=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}},4417:t=>{t.exports=function(t){return this.__data__.get(t)}},8605:t=>{t.exports=function(t){return this.__data__.has(t)}},71418:(t,e,n)=>{var r=n(80235),i=n(10326),a=n(96738);t.exports=function(t,e){var n=this.__data__;if(n instanceof r){var o=n.__data__;if(!i||o.length<199)return o.push([t,e]),this.size=++n.size,this;n=this.__data__=new a(o)}return n.set(t,e),this.size=n.size,this}},66024:t=>{t.exports=function(t,e,n){for(var r=n-1,i=t.length;++r{var r=n(8589),i=n(33880),a=n(35555);t.exports=function(t){return i(t)?a(t):r(t)}},54452:(t,e,n)=>{var r=n(77777),i=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,o=r((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(i,(function(t,n,r,i){e.push(r?i.replace(a,"$1"):n||t)})),e}));t.exports=o},33812:(t,e,n)=>{var r=n(4795);t.exports=function(t){if("string"==typeof t||r(t))return t;var e=t+"";return"0"==e&&1/t==-1/0?"-0":e}},87035:t=>{var e=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return e.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},52153:t=>{var e=/\s/;t.exports=function(t){for(var n=t.length;n--&&e.test(t.charAt(n)););return n}},35555:t=>{var e="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",n="\\ud83c[\\udffb-\\udfff]",r="[^\\ud800-\\udfff]",i="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",o="(?:"+e+"|"+n+")?",u="[\\ufe0e\\ufe0f]?",s=u+o+"(?:\\u200d(?:"+[r,i,a].join("|")+")"+u+o+")*",c="(?:"+[r+e+"?",e,i,a,"[\\ud800-\\udfff]"].join("|")+")",f=RegExp(n+"(?="+n+")|"+c+s,"g");t.exports=function(t){for(var e=f.lastIndex=0;f.test(t);)++e;return e}},54004:(t,e,n)=>{var r=n(18874);t.exports=function(t){return r(t,4)}},9850:(t,e,n)=>{var r=n(18874);t.exports=function(t){return r(t,5)}},86874:t=>{t.exports=function(t){return function(){return t}}},84573:(t,e,n)=>{var r=n(36060),i=n(41225),a=n(82406),o=n(18582),u=Object.prototype,s=u.hasOwnProperty,c=r((function(t,e){t=Object(t);var n=-1,r=e.length,c=r>2?e[2]:void 0;for(c&&a(e[0],e[1],c)&&(r=1);++n{t.exports=n(59756)},41225:t=>{t.exports=function(t,e){return t===e||t!=t&&e!=e}},90882:(t,e,n)=>{var r=n(67552),i=n(98043),a=n(68286),o=n(86152);t.exports=function(t,e){return(o(t)?r:i)(t,a(e,3))}},55281:(t,e,n)=>{var r=n(98776)(n(12982));t.exports=r},12982:(t,e,n)=>{var r=n(21359),i=n(68286),a=n(38101),o=Math.max;t.exports=function(t,e,n){var u=null==t?0:t.length;if(!u)return-1;var s=null==n?0:a(n);return s<0&&(s=o(u+s,0)),r(t,i(e,3),s)}},35676:(t,e,n)=>{var r=n(62034);t.exports=function(t){return null!=t&&t.length?r(t,1):[]}},59756:(t,e,n)=>{var r=n(72517),i=n(24303),a=n(89419),o=n(86152);t.exports=function(t,e){return(o(t)?r:i)(t,a(e))}},20792:(t,e,n)=>{var r=n(15308),i=n(89419),a=n(18582);t.exports=function(t,e){return null==t?t:r(t,i(e),a)}},72579:(t,e,n)=>{var r=n(13324);t.exports=function(t,e,n){var i=null==t?void 0:r(t,e);return void 0===i?n:i}},93352:(t,e,n)=>{var r=n(32726),i=n(1369);t.exports=function(t,e){return null!=t&&i(t,e,r)}},95041:(t,e,n)=>{var r=n(20187),i=n(1369);t.exports=function(t,e){return null!=t&&i(t,e,r)}},23059:t=>{t.exports=function(t){return t}},79631:(t,e,n)=>{var r=n(15183),i=n(15125),a=Object.prototype,o=a.hasOwnProperty,u=a.propertyIsEnumerable,s=r(function(){return arguments}())?r:function(t){return i(t)&&o.call(t,"callee")&&!u.call(t,"callee")};t.exports=s},86152:t=>{var e=Array.isArray;t.exports=e},67878:(t,e,n)=>{var r=n(61049),i=n(61158);t.exports=function(t){return null!=t&&i(t.length)&&!r(t)}},93746:(t,e,n)=>{var r=n(67878),i=n(15125);t.exports=function(t){return i(t)&&r(t)}},73226:(t,e,n)=>{t=n.nmd(t);var r=n(37772),i=n(36330),a=e&&!e.nodeType&&e,o=a&&t&&!t.nodeType&&t,u=o&&o.exports===a?r.Buffer:void 0,s=(u?u.isBuffer:void 0)||i;t.exports=s},45455:(t,e,n)=>{var r=n(86411),i=n(70940),a=n(79631),o=n(86152),u=n(67878),s=n(73226),c=n(16001),f=n(77598),l=Object.prototype.hasOwnProperty;t.exports=function(t){if(null==t)return!0;if(u(t)&&(o(t)||"string"==typeof t||"function"==typeof t.splice||s(t)||f(t)||a(t)))return!t.length;var e=i(t);if("[object Map]"==e||"[object Set]"==e)return!t.size;if(c(t))return!r(t).length;for(var n in t)if(l.call(t,n))return!1;return!0}},61049:(t,e,n)=>{var r=n(53366),i=n(29259);t.exports=function(t){if(!i(t))return!1;var e=r(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}},61158:t=>{t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}},4714:(t,e,n)=>{var r=n(74511),i=n(47826),a=n(4146),o=a&&a.isMap,u=o?i(o):r;t.exports=u},29259:t=>{t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},15125:t=>{t.exports=function(t){return null!=t&&"object"==typeof t}},97030:(t,e,n)=>{var r=n(53366),i=n(47353),a=n(15125),o=Function.prototype,u=Object.prototype,s=o.toString,c=u.hasOwnProperty,f=s.call(Object);t.exports=function(t){if(!a(t)||"[object Object]"!=r(t))return!1;var e=i(t);if(null===e)return!0;var n=c.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&s.call(n)==f}},43679:(t,e,n)=>{var r=n(8109),i=n(47826),a=n(4146),o=a&&a.isSet,u=o?i(o):r;t.exports=u},85505:(t,e,n)=>{var r=n(53366),i=n(86152),a=n(15125);t.exports=function(t){return"string"==typeof t||!i(t)&&a(t)&&"[object String]"==r(t)}},4795:(t,e,n)=>{var r=n(53366),i=n(15125);t.exports=function(t){return"symbol"==typeof t||i(t)&&"[object Symbol]"==r(t)}},77598:(t,e,n)=>{var r=n(35522),i=n(47826),a=n(4146),o=a&&a.isTypedArray,u=o?i(o):r;t.exports=u},84336:t=>{t.exports=function(t){return void 0===t}},90249:(t,e,n)=>{var r=n(1634),i=n(86411),a=n(67878);t.exports=function(t){return a(t)?r(t):i(t)}},18582:(t,e,n)=>{var r=n(1634),i=n(18390),a=n(67878);t.exports=function(t){return a(t)?r(t,!0):i(t)}},56974:t=>{t.exports=function(t){var e=null==t?0:t.length;return e?t[e-1]:void 0}},16760:(t,e,n)=>{var r=n(50343),i=n(68286),a=n(93401),o=n(86152);t.exports=function(t,e){return(o(t)?r:a)(t,i(e,3))}},34519:(t,e,n)=>{var r=n(13940),i=n(26548),a=n(68286);t.exports=function(t,e){var n={};return e=a(e,3),i(t,(function(t,i,a){r(n,i,e(t,i,a))})),n}},71644:(t,e,n)=>{var r=n(2229),i=n(84134),a=n(23059);t.exports=function(t){return t&&t.length?r(t,a,i):void 0}},30733:(t,e,n)=>{var r=n(96738);function i(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError("Expected a function");var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);var o=t.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(i.Cache||r),n}i.Cache=r,t.exports=i},98537:(t,e,n)=>{var r=n(84565),i=n(97263)((function(t,e,n){r(t,e,n)}));t.exports=i},65680:(t,e,n)=>{var r=n(2229),i=n(17606),a=n(23059);t.exports=function(t){return t&&t.length?r(t,a,i):void 0}},10937:(t,e,n)=>{var r=n(2229),i=n(68286),a=n(17606);t.exports=function(t,e){return t&&t.length?r(t,i(e,2),a):void 0}},34291:t=>{t.exports=function(){}},61100:(t,e,n)=>{var r=n(37772);t.exports=function(){return r.Date.now()}},13888:(t,e,n)=>{var r=n(92602),i=n(29097)((function(t,e){return null==t?{}:r(t,e)}));t.exports=i},65798:(t,e,n)=>{var r=n(20256),i=n(82952),a=n(21401),o=n(33812);t.exports=function(t){return a(t)?r(o(t)):i(t)}},2689:(t,e,n)=>{var r=n(82941)();t.exports=r},58215:(t,e,n)=>{var r=n(81207),i=n(24303),a=n(68286),o=n(5877),u=n(86152);t.exports=function(t,e,n){var s=u(t)?r:o,c=arguments.length<3;return s(t,a(e,4),n,c,i)}},36402:(t,e,n)=>{var r=n(86411),i=n(70940),a=n(67878),o=n(85505),u=n(82302);t.exports=function(t){if(null==t)return 0;if(a(t))return o(t)?u(t):t.length;var e=i(t);return"[object Map]"==e||"[object Set]"==e?t.size:r(t).length}},829:(t,e,n)=>{var r=n(62034),i=n(23813),a=n(36060),o=n(82406),u=a((function(t,e){if(null==t)return[];var n=e.length;return n>1&&o(t,e[0],e[1])?e=[]:n>2&&o(e[0],e[1],e[2])&&(e=[e[0]]),i(t,r(e,1),[])}));t.exports=u},30981:t=>{t.exports=function(){return[]}},36330:t=>{t.exports=function(){return!1}},5707:(t,e,n)=>{var r=n(7642);t.exports=function(t){return t?Infinity===(t=r(t))||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}},38101:(t,e,n)=>{var r=n(5707);t.exports=function(t){var e=r(t),n=e%1;return e==e?n?e-n:e:0}},7642:(t,e,n)=>{var r=n(51704),i=n(29259),a=n(4795),o=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,s=/^0o[0-7]+$/i,c=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(a(t))return NaN;if(i(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=i(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=r(t);var n=u.test(t);return n||s.test(t)?c(t.slice(2),n?2:8):o.test(t)?NaN:+t}},63329:(t,e,n)=>{var r=n(752),i=n(18582);t.exports=function(t){return r(t,i(t))}},66188:(t,e,n)=>{var r=n(1054);t.exports=function(t){return null==t?"":r(t)}},89466:(t,e,n)=>{var r=n(72517),i=n(39413),a=n(26548),o=n(68286),u=n(47353),s=n(86152),c=n(73226),f=n(61049),l=n(29259),h=n(77598);t.exports=function(t,e,n){var d=s(t),p=d||c(t)||h(t);if(e=o(e,4),null==n){var v=t&&t.constructor;n=p?d?new v:[]:l(t)&&f(v)?i(u(t)):{}}return(p?r:a)(t,(function(t,r,i){return e(n,t,r,i)})),n}},26139:(t,e,n)=>{var r=n(62034),i=n(36060),a=n(67326),o=n(93746),u=i((function(t){return a(r(t,1,o,!0))}));t.exports=u},74930:(t,e,n)=>{var r=n(66188),i=0;t.exports=function(t){var e=++i;return r(t)+e}},98346:(t,e,n)=>{var r=n(50753),i=n(90249);t.exports=function(t){return null==t?[]:r(t,i(t))}},46150:(t,e,n)=>{var r=n(60091),i=n(40509);t.exports=function(t,e){return i(t||[],e||[],r)}},27808:t=>{t.exports=n;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},a={};function o(t,e){var n,r,o;return e?(o=0<=(t>>>=0)&&t<256)&&(r=a[t])?r:(n=s(t,(0|t)<0?-1:0,!0),o&&(a[t]=n),n):(o=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=s(t,t<0?-1:0,!1),o&&(i[t]=n),n)}function u(t,e){if(isNaN(t))return e?_:g;if(e){if(t<0)return _;if(t>=d)return w}else{if(t<=-p)return Z;if(t+1>=p)return x}return t<0?u(-t,e).neg():s(t%h|0,t/h|0,e)}function s(t,e,r){return new n(t,e,r)}n.fromInt=o,n.fromNumber=u,n.fromBits=s;var c=Math.pow;function f(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return g;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return f(t.substring(1),e,n).neg();for(var i=u(c(n,8)),a=g,o=0;o>>0:this.low},D.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},D.toString=function(t){if((t=t||10)<2||36>>0).toString(t);if((a=s).isZero())return f+o;for(;f.length<6;)f="0"+f;o=""+f+o}},D.getHighBits=function(){return this.high},D.getHighBitsUnsigned=function(){return this.high>>>0},D.getLowBits=function(){return this.low},D.getLowBitsUnsigned=function(){return this.low>>>0},D.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Z)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<=0},D.isOdd=function(){return 1==(1&this.low)},D.isEven=function(){return 0==(1&this.low)},D.equals=function(t){return r(t)||(t=l(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},D.eq=D.equals,D.notEquals=function(t){return!this.eq(t)},D.neq=D.notEquals,D.ne=D.notEquals,D.lessThan=function(t){return this.comp(t)<0},D.lt=D.lessThan,D.lessThanOrEqual=function(t){return this.comp(t)<=0},D.lte=D.lessThanOrEqual,D.le=D.lessThanOrEqual,D.greaterThan=function(t){return this.comp(t)>0},D.gt=D.greaterThan,D.greaterThanOrEqual=function(t){return this.comp(t)>=0},D.gte=D.greaterThanOrEqual,D.ge=D.greaterThanOrEqual,D.compare=function(t){if(r(t)||(t=l(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},D.comp=D.compare,D.negate=function(){return!this.unsigned&&this.eq(Z)?Z:this.not().add(b)},D.neg=D.negate,D.add=function(t){r(t)||(t=l(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,a=65535&this.low,o=t.high>>>16,u=65535&t.high,c=t.low>>>16,f=0,h=0,d=0,p=0;return d+=(p+=a+(65535&t.low))>>>16,h+=(d+=i+c)>>>16,f+=(h+=n+u)>>>16,f+=e+o,s((d&=65535)<<16|(p&=65535),(f&=65535)<<16|(h&=65535),this.unsigned)},D.subtract=function(t){return r(t)||(t=l(t)),this.add(t.neg())},D.sub=D.subtract,D.multiply=function(t){if(this.isZero())return g;if(r(t)||(t=l(t)),e)return s(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return g;if(this.eq(Z))return t.isOdd()?Z:g;if(t.eq(Z))return this.isOdd()?Z:g;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(v)&&t.lt(v))return u(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,a=this.low>>>16,o=65535&this.low,c=t.high>>>16,f=65535&t.high,h=t.low>>>16,d=65535&t.low,p=0,_=0,b=0,y=0;return b+=(y+=o*d)>>>16,_+=(b+=a*d)>>>16,b&=65535,_+=(b+=o*h)>>>16,p+=(_+=i*d)>>>16,_&=65535,p+=(_+=a*h)>>>16,_&=65535,p+=(_+=o*f)>>>16,p+=n*d+i*h+a*f+o*c,s((b&=65535)<<16|(y&=65535),(p&=65535)<<16|(_&=65535),this.unsigned)},D.mul=D.multiply,D.divide=function(t){if(r(t)||(t=l(t)),t.isZero())throw Error("division by zero");var n,i,a;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?s((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?_:g;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return _;if(t.gt(this.shru(1)))return y;a=_}else{if(this.eq(Z))return t.eq(b)||t.eq(m)?Z:t.eq(Z)?b:(n=this.shr(1).div(t).shl(1)).eq(g)?t.isNegative()?b:m:(i=this.sub(t.mul(n)),a=n.add(i.div(t)));if(t.eq(Z))return this.unsigned?_:g;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=g}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(n)/Math.LN2),f=o<=48?1:c(2,o-48),h=u(n),d=h.mul(t);d.isNegative()||d.gt(i);)d=(h=u(n-=f,this.unsigned)).mul(t);h.isZero()&&(h=b),a=a.add(h),i=i.sub(d)}return a},D.div=D.divide,D.modulo=function(t){return r(t)||(t=l(t)),e?s((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},D.mod=D.modulo,D.rem=D.modulo,D.not=function(){return s(~this.low,~this.high,this.unsigned)},D.and=function(t){return r(t)||(t=l(t)),s(this.low&t.low,this.high&t.high,this.unsigned)},D.or=function(t){return r(t)||(t=l(t)),s(this.low|t.low,this.high|t.high,this.unsigned)},D.xor=function(t){return r(t)||(t=l(t)),s(this.low^t.low,this.high^t.high,this.unsigned)},D.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?s(this.low<>>32-t,this.unsigned):s(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):s(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},D.shr=D.shiftRight,D.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?s(this.low>>>t|e<<32-t,e>>>t,this.unsigned):s(32===t?e:e>>>t-32,0,this.unsigned)},D.shru=D.shiftRightUnsigned,D.shr_u=D.shiftRightUnsigned,D.toSigned=function(){return this.unsigned?s(this.low,this.high,!1):this},D.toUnsigned=function(){return this.unsigned?this:s(this.low,this.high,!0)},D.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},D.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},D.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},13917:function(t){t.exports=function(){"use strict";function t(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r={exports:{}};function i(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}r.exports={defaults:{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1},getDefaults:i,changeDefaults:function(t){r.exports.defaults=t}};var a=/[&<>"']/,o=/[&<>"']/g,u=/[<>"']|&(?!#?\w+;)/,s=/[<>"']|&(?!#?\w+;)/g,c={"&":"&","<":"<",">":">",'"':""","'":"'"},f=function(t){return c[t]};var l=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function h(t){return t.replace(l,(function(t,e){return"colon"===(e=e.toLowerCase())?":":"#"===e.charAt(0)?"x"===e.charAt(1)?String.fromCharCode(parseInt(e.substring(2),16)):String.fromCharCode(+e.substring(1)):""}))}var d=/(^|[^\[])\^/g;var p=/[^\w:]/g,v=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;var g={},_=/^[^:]+:\/*[^/]*$/,b=/^([^:]+:)[\s\S]*$/,y=/^([^:]+:\/*[^/]*)[\s\S]*$/;function m(t,e){g[" "+t]||(_.test(t)?g[" "+t]=t+"/":g[" "+t]=x(t,"/",!0));var n=-1===(t=g[" "+t]).indexOf(":");return"//"===e.substring(0,2)?n?e:t.replace(b,"$1")+e:"/"===e.charAt(0)?n?e:t.replace(y,"$1")+e:t+e}function x(t,e,n){var r=t.length;if(0===r)return"";for(var i=0;i=0&&"\\"===n[i];)r=!r;return r?"|":" |"})).split(/ \|/),r=0;if(n.length>e)n.splice(e);else for(;n.length1;)1&e&&(n+=t),e>>=1,t+=t;return n+t},S=r.exports.defaults,N=C,T=j,z=w,O=M;function R(t,e,n){var r=e.href,i=e.title?z(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");return"!"!==t[0].charAt(0)?{type:"link",raw:n,href:r,title:i,text:a}:{type:"image",raw:n,href:r,title:i,text:z(a)}}var P=function(){function t(t){this.options=t||S}var e=t.prototype;return e.space=function(t){var e=this.rules.block.newline.exec(t);if(e)return e[0].length>1?{type:"space",raw:e[0]}:{raw:"\n"}},e.code=function(t){var e=this.rules.block.code.exec(t);if(e){var n=e[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:N(n,"\n")}}},e.fences=function(t){var e=this.rules.block.fences.exec(t);if(e){var n=e[0],r=function(t,e){var n=t.match(/^(\s+)(?:```)/);if(null===n)return e;var r=n[1];return e.split("\n").map((function(t){var e=t.match(/^\s+/);return null===e?t:e[0].length>=r.length?t.slice(r.length):t})).join("\n")}(n,e[3]||"");return{type:"code",raw:n,lang:e[2]?e[2].trim():e[2],text:r}}},e.heading=function(t){var e=this.rules.block.heading.exec(t);if(e){var n=e[2].trim();if(/#$/.test(n)){var r=N(n,"#");this.options.pedantic?n=r.trim():r&&!/ $/.test(r)||(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n}}},e.nptable=function(t){var e=this.rules.block.nptable.exec(t);if(e){var n={type:"table",header:T(e[1].replace(/^ *| *\| *$/g,"")),align:e[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:e[3]?e[3].replace(/\n$/,"").split("\n"):[],raw:e[0]};if(n.header.length===n.align.length){var r,i=n.align.length;for(r=0;r ?/gm,"");return{type:"blockquote",raw:e[0],text:n}}},e.list=function(t){var e=this.rules.block.list.exec(t);if(e){var n,r,i,a,o,u,s,c,f,l=e[0],h=e[2],d=h.length>1,p={type:"list",raw:l,ordered:d,start:d?+h.slice(0,-1):"",loose:!1,items:[]},v=e[0].match(this.rules.block.item),g=!1,_=v.length;i=this.rules.block.listItemStart.exec(v[0]);for(var b=0;b<_;b++){if(l=n=v[b],this.options.pedantic||(f=n.match(new RegExp("\\n\\s*\\n {0,"+(i[0].length-1)+"}\\S")))&&(o=n.length-f.index+v.slice(b+1).join("\n").length,p.raw=p.raw.substring(0,p.raw.length-o),l=n=n.substring(0,f.index),_=b+1),b!==_-1){if(a=this.rules.block.listItemStart.exec(v[b+1]),this.options.pedantic?a[1].length>i[1].length:a[1].length>=i[0].length||a[1].length>3){v.splice(b,2,v[b]+(!this.options.pedantic&&a[1].length/i.test(r[0])&&(e=!1),!n&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?n=!0:n&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(n=!1),{type:this.options.sanitize?"text":"html",raw:r[0],inLink:e,inRawBlock:n,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):z(r[0]):r[0]}},e.link=function(t){var e=this.rules.inline.link.exec(t);if(e){var n=e[2].trim();if(!this.options.pedantic&&/^$/.test(n))return;var r=N(n.slice(0,-1),"\\");if((n.length-r.length)%2==0)return}else{var i=O(e[2],"()");if(i>-1){var a=(0===e[0].indexOf("!")?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,a).trim(),e[3]=""}}var o=e[2],u="";if(this.options.pedantic){var s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);s&&(o=s[1],u=s[3])}else u=e[3]?e[3].slice(1,-1):"";return o=o.trim(),/^$/.test(n)?o.slice(1):o.slice(1,-1)),R(e,{href:o?o.replace(this.rules.inline._escapes,"$1"):o,title:u?u.replace(this.rules.inline._escapes,"$1"):u},e[0])}},e.reflink=function(t,e){var n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){var r=(n[2]||n[1]).replace(/\s+/g," ");if(!(r=e[r.toLowerCase()])||!r.href){var i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return R(n,r,n[0])}},e.emStrong=function(t,e,n){void 0===n&&(n="");var r=this.rules.inline.emStrong.lDelim.exec(t);if(r&&(!r[3]||!n.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/))){var i=r[1]||r[2]||"";if(!i||i&&(""===n||this.rules.inline.punctuation.exec(n))){var a,o,u=r[0].length-1,s=u,c=0,f="*"===r[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,e=e.slice(-1*t.length+u);null!=(r=f.exec(e));)if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6])if(o=a.length,r[3]||r[4])s+=o;else if(!((r[5]||r[6])&&u%3)||(u+o)%3){if(!((s-=o)>0))return o=Math.min(o,o+s+c),Math.min(u,o)%2?{type:"em",raw:t.slice(0,u+r.index+o+1),text:t.slice(1,u+r.index+o)}:{type:"strong",raw:t.slice(0,u+r.index+o+1),text:t.slice(2,u+r.index+o-1)}}else c+=o}}},e.codespan=function(t){var e=this.rules.inline.code.exec(t);if(e){var n=e[2].replace(/\n/g," "),r=/[^ ]/.test(n),i=/^ /.test(n)&&/ $/.test(n);return r&&i&&(n=n.substring(1,n.length-1)),n=z(n,!0),{type:"codespan",raw:e[0],text:n}}},e.br=function(t){var e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}},e.del=function(t){var e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2]}},e.autolink=function(t,e){var n,r,i=this.rules.inline.autolink.exec(t);if(i)return r="@"===i[2]?"mailto:"+(n=z(this.options.mangle?e(i[1]):i[1])):n=z(i[1]),{type:"link",raw:i[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}},e.url=function(t,e){var n;if(n=this.rules.inline.url.exec(t)){var r,i;if("@"===n[2])i="mailto:"+(r=z(this.options.mangle?e(n[0]):n[0]));else{var a;do{a=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(a!==n[0]);r=z(n[0]),i="www."===n[1]?"http://"+r:r}return{type:"link",raw:n[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}},e.inlineText=function(t,e,n){var r,i=this.rules.inline.text.exec(t);if(i)return r=e?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(i[0]):z(i[0]):i[0]:z(this.options.smartypants?n(i[0]):i[0]),{type:"text",raw:i[0],text:r}},t}(),I=E,L=D,U=A,$={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,nptable:I,table:I,lheading:/^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};$.def=L($.def).replace("label",$._label).replace("title",$._title).getRegex(),$.bullet=/(?:[*+-]|\d{1,9}[.)])/,$.item=/^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/,$.item=L($.item,"gm").replace(/bull/g,$.bullet).getRegex(),$.listItemStart=L(/^( *)(bull) */).replace("bull",$.bullet).getRegex(),$.list=L($.list).replace(/bull/g,$.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+$.def.source+")").getRegex(),$._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",$._comment=/|$)/,$.html=L($.html,"i").replace("comment",$._comment).replace("tag",$._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),$.paragraph=L($._paragraph).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.blockquote=L($.blockquote).replace("paragraph",$.paragraph).getRegex(),$.normal=U({},$),$.gfm=U({},$.normal,{nptable:"^ *([^|\\n ].*\\|.*)\\n {0,3}([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)",table:"^ *\\|(.+)\\n {0,3}\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"}),$.gfm.nptable=L($.gfm.nptable).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.gfm.table=L($.gfm.table).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.pedantic=U({},$.normal,{html:L("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",$._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:I,paragraph:L($.normal._paragraph).replace("hr",$.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});var H={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:I,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/\_\_[^_*]*?\*[^_*]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,rDelimUnd:/\*\*[^_*]*?\_[^_*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:I,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~"};H.punctuation=L(H.punctuation).replace(/punctuation/g,H._punctuation).getRegex(),H.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,H.escapedEmSt=/\\\*|\\_/g,H._comment=L($._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),H.emStrong.lDelim=L(H.emStrong.lDelim).replace(/punct/g,H._punctuation).getRegex(),H.emStrong.rDelimAst=L(H.emStrong.rDelimAst,"g").replace(/punct/g,H._punctuation).getRegex(),H.emStrong.rDelimUnd=L(H.emStrong.rDelimUnd,"g").replace(/punct/g,H._punctuation).getRegex(),H._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,H._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,H._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,H.autolink=L(H.autolink).replace("scheme",H._scheme).replace("email",H._email).getRegex(),H._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,H.tag=L(H.tag).replace("comment",H._comment).replace("attribute",H._attribute).getRegex(),H._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,H._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,H._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,H.link=L(H.link).replace("label",H._label).replace("href",H._href).replace("title",H._title).getRegex(),H.reflink=L(H.reflink).replace("label",H._label).getRegex(),H.reflinkSearch=L(H.reflinkSearch,"g").replace("reflink",H.reflink).replace("nolink",H.nolink).getRegex(),H.normal=U({},H),H.pedantic=U({},H.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:L(/^!?\[(label)\]\((.*?)\)/).replace("label",H._label).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",H._label).getRegex()}),H.gfm=U({},H.normal,{escape:L(H.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\.5&&(n="x"+n.toString(16)),r+="&#"+n+";";return r}var Q=function(){function e(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||W,this.options.tokenizer=this.options.tokenizer||new Y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options;var e={block:V.normal,inline:G.normal};this.options.pedantic?(e.block=V.pedantic,e.inline=G.pedantic):this.options.gfm&&(e.block=V.gfm,this.options.breaks?e.inline=G.breaks:e.inline=G.gfm),this.tokenizer.rules=e}e.lex=function(t,n){return new e(n).lex(t)},e.lexInline=function(t,n){return new e(n).inlineTokens(t)};var n,r,i,a=e.prototype;return a.lex=function(t){return t=t.replace(/\r\n|\r/g,"\n").replace(/\t/g," "),this.blockTokens(t,this.tokens,!0),this.inline(this.tokens),this.tokens},a.blockTokens=function(t,e,n){var r,i,a,o;for(void 0===e&&(e=[]),void 0===n&&(n=!0),this.options.pedantic&&(t=t.replace(/^ +$/gm,""));t;)if(r=this.tokenizer.space(t))t=t.substring(r.raw.length),r.type&&e.push(r);else if(r=this.tokenizer.code(t))t=t.substring(r.raw.length),(o=e[e.length-1])&&"paragraph"===o.type?(o.raw+="\n"+r.raw,o.text+="\n"+r.text):e.push(r);else if(r=this.tokenizer.fences(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.heading(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.nptable(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.hr(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.blockquote(t))t=t.substring(r.raw.length),r.tokens=this.blockTokens(r.text,[],n),e.push(r);else if(r=this.tokenizer.list(t)){for(t=t.substring(r.raw.length),a=r.items.length,i=0;i0)for(;null!=(o=this.tokenizer.rules.inline.reflinkSearch.exec(c));)f.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(c=c.slice(0,o.index)+"["+X("a",o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(o=this.tokenizer.rules.inline.blockSkip.exec(c));)c=c.slice(0,o.index)+"["+X("a",o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(o=this.tokenizer.rules.inline.escapedEmSt.exec(c));)c=c.slice(0,o.index)+"++"+c.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);for(;t;)if(u||(s=""),u=!1,i=this.tokenizer.escape(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.tag(t,n,r)){t=t.substring(i.raw.length),n=i.inLink,r=i.inRawBlock;var l=e[e.length-1];l&&"text"===i.type&&"text"===l.type?(l.raw+=i.raw,l.text+=i.text):e.push(i)}else if(i=this.tokenizer.link(t))t=t.substring(i.raw.length),"link"===i.type&&(i.tokens=this.inlineTokens(i.text,[],!0,r)),e.push(i);else if(i=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(i.raw.length);var h=e[e.length-1];"link"===i.type?(i.tokens=this.inlineTokens(i.text,[],!0,r),e.push(i)):h&&"text"===i.type&&"text"===h.type?(h.raw+=i.raw,h.text+=i.text):e.push(i)}else if(i=this.tokenizer.emStrong(t,c,s))t=t.substring(i.raw.length),i.tokens=this.inlineTokens(i.text,[],n,r),e.push(i);else if(i=this.tokenizer.codespan(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.br(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.del(t))t=t.substring(i.raw.length),i.tokens=this.inlineTokens(i.text,[],n,r),e.push(i);else if(i=this.tokenizer.autolink(t,J))t=t.substring(i.raw.length),e.push(i);else if(n||!(i=this.tokenizer.url(t,J))){if(i=this.tokenizer.inlineText(t,r,K))t=t.substring(i.raw.length),"_"!==i.raw.slice(-1)&&(s=i.raw.slice(-1)),u=!0,(a=e[e.length-1])&&"text"===a.type?(a.raw+=i.raw,a.text+=i.text):e.push(i);else if(t){var d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}throw new Error(d)}}else t=t.substring(i.raw.length),e.push(i);return e},n=e,i=[{key:"rules",get:function(){return{block:V,inline:G}}}],(r=null)&&t(n.prototype,r),i&&t(n,i),e}(),tt=r.exports.defaults,et=k,nt=w,rt=function(){function t(t){this.options=t||tt}var e=t.prototype;return e.code=function(t,e,n){var r=(e||"").match(/\S*/)[0];if(this.options.highlight){var i=this.options.highlight(t,r);null!=i&&i!==t&&(n=!0,t=i)}return t=t.replace(/\n$/,"")+"\n",r?'
'+(n?t:nt(t,!0))+"
\n":"
"+(n?t:nt(t,!0))+"
\n"},e.blockquote=function(t){return"
\n"+t+"
\n"},e.html=function(t){return t},e.heading=function(t,e,n,r){return this.options.headerIds?"'+t+"\n":""+t+"\n"},e.hr=function(){return this.options.xhtml?"
\n":"
\n"},e.list=function(t,e,n){var r=e?"ol":"ul";return"<"+r+(e&&1!==n?' start="'+n+'"':"")+">\n"+t+"\n"},e.listitem=function(t){return"
  • "+t+"
  • \n"},e.checkbox=function(t){return" "},e.paragraph=function(t){return"

    "+t+"

    \n"},e.table=function(t,e){return e&&(e=""+e+""),"\n\n"+t+"\n"+e+"
    \n"},e.tablerow=function(t){return"\n"+t+"\n"},e.tablecell=function(t,e){var n=e.header?"th":"td";return(e.align?"<"+n+' align="'+e.align+'">':"<"+n+">")+t+"\n"},e.strong=function(t){return""+t+""},e.em=function(t){return""+t+""},e.codespan=function(t){return""+t+""},e.br=function(){return this.options.xhtml?"
    ":"
    "},e.del=function(t){return""+t+""},e.link=function(t,e,n){if(null===(t=et(this.options.sanitize,this.options.baseUrl,t)))return n;var r='"+n+""},e.image=function(t,e,n){if(null===(t=et(this.options.sanitize,this.options.baseUrl,t)))return n;var r=''+n+'":">")},e.text=function(t){return t},t}(),it=function(){function t(){}var e=t.prototype;return e.strong=function(t){return t},e.em=function(t){return t},e.codespan=function(t){return t},e.del=function(t){return t},e.html=function(t){return t},e.text=function(t){return t},e.link=function(t,e,n){return""+n},e.image=function(t,e,n){return""+n},e.br=function(){return""},t}(),at=function(){function t(){this.seen={}}var e=t.prototype;return e.serialize=function(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")},e.getNextSafeSlug=function(t,e){var n=t,r=0;if(this.seen.hasOwnProperty(n)){r=this.seen[t];do{n=t+"-"+ ++r}while(this.seen.hasOwnProperty(n))}return e||(this.seen[t]=r,this.seen[n]=0),n},e.slug=function(t,e){void 0===e&&(e={});var n=this.serialize(t);return this.getNextSafeSlug(n,e.dryrun)},t}(),ot=rt,ut=it,st=at,ct=r.exports.defaults,ft=Z,lt=Q,ht=function(){function t(t){this.options=t||ct,this.options.renderer=this.options.renderer||new ot,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ut,this.slugger=new st}t.parse=function(e,n){return new t(n).parse(e)},t.parseInline=function(e,n){return new t(n).parseInline(e)};var e=t.prototype;return e.parse=function(t,e){void 0===e&&(e=!0);var n,r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y,m="",x=t.length;for(n=0;n0&&"text"===g.tokens[0].type?(g.tokens[0].text=y+" "+g.tokens[0].text,g.tokens[0].tokens&&g.tokens[0].tokens.length>0&&"text"===g.tokens[0].tokens[0].type&&(g.tokens[0].tokens[0].text=y+" "+g.tokens[0].tokens[0].text)):g.tokens.unshift({type:"text",text:y}):v+=y),v+=this.parse(g.tokens,p),f+=this.renderer.listitem(v,b,_);m+=this.renderer.list(f,h,d);continue;case"html":m+=this.renderer.html(l.text);continue;case"paragraph":m+=this.renderer.paragraph(this.parseInline(l.tokens));continue;case"text":for(f=l.tokens?this.parseInline(l.tokens):l.text;n+1An error occurred:

    "+yt(t.message+"",!0)+"
    ";throw t}}return Zt.options=Zt.setOptions=function(t){return _t(Zt.defaults,t),xt(Zt.defaults),Zt},Zt.getDefaults=mt,Zt.defaults=wt,Zt.use=function(t){var e=_t({},t);if(t.renderer&&function(){var n=Zt.defaults.renderer||new pt,r=function(e){var r=n[e];n[e]=function(){for(var i=arguments.length,a=new Array(i),o=0;oAn error occurred:

    "+yt(t.message+"",!0)+"
    ";throw t}},Zt.Parser=ht,Zt.parser=ht.parse,Zt.Renderer=pt,Zt.TextRenderer=vt,Zt.Lexer=lt,Zt.lexer=lt.lex,Zt.Tokenizer=dt,Zt.Slugger=gt,Zt.parse=Zt,Zt}()},32845:(t,e,n)=>{"use strict";var r={};(0,n(49761).assign)(r,n(79880),n(21380),n(91271)),t.exports=r},79880:(t,e,n)=>{"use strict";var r=n(75789),i=n(49761),a=n(47944),o=n(82950),u=n(20744),s=Object.prototype.toString;function c(t){if(!(this instanceof c))return new c(t);this.options=i.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new u,this.strm.avail_out=0;var n=r.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(0!==n)throw new Error(o[n]);if(e.header&&r.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?a.string2buf(e.dictionary):"[object ArrayBuffer]"===s.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,0!==(n=r.deflateSetDictionary(this.strm,f)))throw new Error(o[n]);this._dict_set=!0}}function f(t,e){var n=new c(e);if(n.push(t,!0),n.err)throw n.msg||o[n.err];return n.result}c.prototype.push=function(t,e){var n,o,u=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?u.input=a.string2buf(t):"[object ArrayBuffer]"===s.call(t)?u.input=new Uint8Array(t):u.input=t,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new i.Buf8(c),u.next_out=0,u.avail_out=c),1!==(n=r.deflate(u,o))&&0!==n)return this.onEnd(n),this.ended=!0,!1;0!==u.avail_out&&(0!==u.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(a.buf2binstring(i.shrinkBuf(u.output,u.next_out))):this.onData(i.shrinkBuf(u.output,u.next_out)))}while((u.avail_in>0||0===u.avail_out)&&1!==n);return 4===o?(n=r.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,0===n):2!==o||(this.onEnd(0),u.avail_out=0,!0)},c.prototype.onData=function(t){this.chunks.push(t)},c.prototype.onEnd=function(t){0===t&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Deflate=c,e.deflate=f,e.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},e.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},21380:(t,e,n)=>{"use strict";var r=n(35020),i=n(49761),a=n(47944),o=n(91271),u=n(82950),s=n(20744),c=n(7357),f=Object.prototype.toString;function l(t){if(!(this instanceof l))return new l(t);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var n=r.inflateInit2(this.strm,e.windowBits);if(n!==o.Z_OK)throw new Error(u[n]);if(this.header=new c,r.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=a.string2buf(e.dictionary):"[object ArrayBuffer]"===f.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=r.inflateSetDictionary(this.strm,e.dictionary))!==o.Z_OK))throw new Error(u[n])}function h(t,e){var n=new l(e);if(n.push(t,!0),n.err)throw n.msg||u[n.err];return n.result}l.prototype.push=function(t,e){var n,u,s,c,l,h=this.strm,d=this.options.chunkSize,p=this.options.dictionary,v=!1;if(this.ended)return!1;u=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?h.input=a.binstring2buf(t):"[object ArrayBuffer]"===f.call(t)?h.input=new Uint8Array(t):h.input=t,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(d),h.next_out=0,h.avail_out=d),(n=r.inflate(h,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&p&&(n=r.inflateSetDictionary(this.strm,p)),n===o.Z_BUF_ERROR&&!0===v&&(n=o.Z_OK,v=!1),n!==o.Z_STREAM_END&&n!==o.Z_OK)return this.onEnd(n),this.ended=!0,!1;h.next_out&&(0!==h.avail_out&&n!==o.Z_STREAM_END&&(0!==h.avail_in||u!==o.Z_FINISH&&u!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(s=a.utf8border(h.output,h.next_out),c=h.next_out-s,l=a.buf2string(h.output,s),h.next_out=c,h.avail_out=d-c,c&&i.arraySet(h.output,h.output,s,c,0),this.onData(l)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(v=!0)}while((h.avail_in>0||0===h.avail_out)&&n!==o.Z_STREAM_END);return n===o.Z_STREAM_END&&(u=o.Z_FINISH),u===o.Z_FINISH?(n=r.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===o.Z_OK):u!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),h.avail_out=0,!0)},l.prototype.onData=function(t){this.chunks.push(t)},l.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=l,e.inflate=h,e.inflateRaw=function(t,e){return(e=e||{}).raw=!0,h(t,e)},e.ungzip=h},49761:(t,e)=>{"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var i in n)r(n,i)&&(t[i]=n[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var i={arraySet:function(t,e,n,r,i){if(e.subarray&&t.subarray)t.set(e.subarray(n,n+r),i);else for(var a=0;a{"use strict";var r=n(49761),i=!0,a=!0;try{String.fromCharCode.apply(null,[0])}catch(t){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){a=!1}for(var o=new r.Buf8(256),u=0;u<256;u++)o[u]=u>=252?6:u>=248?5:u>=240?4:u>=224?3:u>=192?2:1;function s(t,e){if(e<65534&&(t.subarray&&a||!t.subarray&&i))return String.fromCharCode.apply(null,r.shrinkBuf(t,e));for(var n="",o=0;o>>6,e[o++]=128|63&n):n<65536?(e[o++]=224|n>>>12,e[o++]=128|n>>>6&63,e[o++]=128|63&n):(e[o++]=240|n>>>18,e[o++]=128|n>>>12&63,e[o++]=128|n>>>6&63,e[o++]=128|63&n);return e},e.buf2binstring=function(t){return s(t,t.length)},e.binstring2buf=function(t){for(var e=new r.Buf8(t.length),n=0,i=e.length;n4)c[r++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?c[r++]=65533:i<65536?c[r++]=i:(i-=65536,c[r++]=55296|i>>10&1023,c[r++]=56320|1023&i)}return s(c,r)},e.utf8border=function(t,e){var n;for((e=e||t.length)>t.length&&(e=t.length),n=e-1;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+o[t[n]]>e?n:e}},95562:t=>{"use strict";t.exports=function(t,e,n,r){for(var i=65535&t|0,a=t>>>16&65535|0,o=0;0!==n;){n-=o=n>2e3?2e3:n;do{a=a+(i=i+e[r++]|0)|0}while(--o);i%=65521,a%=65521}return i|a<<16|0}},91271:t=>{"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},24299:t=>{"use strict";var e=function(){for(var t,e=[],n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e}();t.exports=function(t,n,r,i){var a=e,o=i+r;t^=-1;for(var u=i;u>>8^a[255&(t^n[u])];return-1^t}},75789:(t,e,n)=>{"use strict";var r,i=n(49761),a=n(69564),o=n(95562),u=n(24299),s=n(82950),c=-2,f=258,l=262,h=103,d=113,p=666;function v(t,e){return t.msg=s[e],e}function g(t){return(t<<1)-(t>4?9:0)}function _(t){for(var e=t.length;--e>=0;)t[e]=0}function b(t){var e=t.state,n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(i.arraySet(t.output,e.pending_buf,e.pending_out,n,t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))}function y(t,e){a._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,b(t.strm)}function m(t,e){t.pending_buf[t.pending++]=e}function x(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function w(t,e){var n,r,i=t.max_chain_length,a=t.strstart,o=t.prev_length,u=t.nice_match,s=t.strstart>t.w_size-l?t.strstart-(t.w_size-l):0,c=t.window,h=t.w_mask,d=t.prev,p=t.strstart+f,v=c[a+o-1],g=c[a+o];t.prev_length>=t.good_match&&(i>>=2),u>t.lookahead&&(u=t.lookahead);do{if(c[(n=e)+o]===g&&c[n+o-1]===v&&c[n]===c[a]&&c[++n]===c[a+1]){a+=2,n++;do{}while(c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&ao){if(t.match_start=e,o=r,r>=u)break;v=c[a+o-1],g=c[a+o]}}}while((e=d[e&h])>s&&0!=--i);return o<=t.lookahead?o:t.lookahead}function Z(t){var e,n,r,a,s,c,f,h,d,p,v=t.w_size;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=v+(v-l)){i.arraySet(t.window,t.window,v,v,0),t.match_start-=v,t.strstart-=v,t.block_start-=v,e=n=t.hash_size;do{r=t.head[--e],t.head[e]=r>=v?r-v:0}while(--n);e=n=v;do{r=t.prev[--e],t.prev[e]=r>=v?r-v:0}while(--n);a+=v}if(0===t.strm.avail_in)break;if(c=t.strm,f=t.window,h=t.strstart+t.lookahead,d=a,p=void 0,(p=c.avail_in)>d&&(p=d),n=0===p?0:(c.avail_in-=p,i.arraySet(f,c.input,c.next_in,p,h),1===c.state.wrap?c.adler=o(c.adler,f,p,h):2===c.state.wrap&&(c.adler=u(c.adler,f,p,h)),c.next_in+=p,c.total_in+=p,p),t.lookahead+=n,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=(t.ins_h<=3&&(t.ins_h=(t.ins_h<=3)if(r=a._tr_tally(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<=3&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-3,r=a._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=(t.ins_h<15&&(u=2,r-=16),a<1||a>9||8!==n||r<8||r>15||e<0||e>9||o<0||o>4)return v(t,c);8===r&&(r=9);var s=new A;return t.state=s,s.strm=t,s.wrap=u,s.gzhead=null,s.w_bits=r,s.w_size=1<t.pending_buf_size-5&&(n=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Z(t),0===t.lookahead&&0===e)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var r=t.block_start+n;if((0===t.strstart||t.strstart>=r)&&(t.lookahead=t.strstart-r,t.strstart=r,y(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-l&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(y(t,!1),t.strm.avail_out),1)})),new E(4,4,8,4,D),new E(4,5,16,8,D),new E(4,6,32,32,D),new E(4,4,16,16,k),new E(8,16,32,32,k),new E(8,16,128,128,k),new E(8,32,128,256,k),new E(32,128,258,1024,k),new E(32,258,258,4096,k)],e.deflateInit=function(t,e){return M(t,e,8,15,8,0)},e.deflateInit2=M,e.deflateReset=C,e.deflateResetKeep=j,e.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?c:(t.state.gzhead=e,0):c},e.deflate=function(t,e){var n,i,o,s;if(!t||!t.state||e>5||e<0)return t?v(t,c):c;if(i=t.state,!t.output||!t.input&&0!==t.avail_in||i.status===p&&4!==e)return v(t,0===t.avail_out?-5:c);if(i.strm=t,n=i.last_flush,i.last_flush=e,42===i.status)if(2===i.wrap)t.adler=0,m(i,31),m(i,139),m(i,8),i.gzhead?(m(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),m(i,255&i.gzhead.time),m(i,i.gzhead.time>>8&255),m(i,i.gzhead.time>>16&255),m(i,i.gzhead.time>>24&255),m(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),m(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(m(i,255&i.gzhead.extra.length),m(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=u(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(m(i,0),m(i,0),m(i,0),m(i,0),m(i,0),m(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),m(i,3),i.status=d);else{var l=8+(i.w_bits-8<<4)<<8;l|=(i.strategy>=2||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(l|=32),l+=31-l%31,i.status=d,x(i,l),0!==i.strstart&&(x(i,t.adler>>>16),x(i,65535&t.adler)),t.adler=1}if(69===i.status)if(i.gzhead.extra){for(o=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending!==i.pending_buf_size));)m(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(73===i.status)if(i.gzhead.name){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexo&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),0===s&&(i.gzindex=0,i.status=91)}else i.status=91;if(91===i.status)if(i.gzhead.comment){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexo&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),0===s&&(i.status=h)}else i.status=h;if(i.status===h&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&b(t),i.pending+2<=i.pending_buf_size&&(m(i,255&t.adler),m(i,t.adler>>8&255),t.adler=0,i.status=d)):i.status=d),0!==i.pending){if(b(t),0===t.avail_out)return i.last_flush=-1,0}else if(0===t.avail_in&&g(e)<=g(n)&&4!==e)return v(t,-5);if(i.status===p&&0!==t.avail_in)return v(t,-5);if(0!==t.avail_in||0!==i.lookahead||0!==e&&i.status!==p){var w=2===i.strategy?function(t,e){for(var n;;){if(0===t.lookahead&&(Z(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,n=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(y(t,!1),0===t.strm.avail_out)?1:2}(i,e):3===i.strategy?function(t,e){for(var n,r,i,o,u=t.window;;){if(t.lookahead<=f){if(Z(t),t.lookahead<=f&&0===e)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(r=u[i=t.strstart-1])===u[++i]&&r===u[++i]&&r===u[++i]){o=t.strstart+f;do{}while(r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&it.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(n=a._tr_tally(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(y(t,!1),0===t.strm.avail_out)?1:2}(i,e):r[i.level].func(i,e);if(3!==w&&4!==w||(i.status=p),1===w||3===w)return 0===t.avail_out&&(i.last_flush=-1),0;if(2===w&&(1===e?a._tr_align(i):5!==e&&(a._tr_stored_block(i,0,0,!1),3===e&&(_(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),b(t),0===t.avail_out))return i.last_flush=-1,0}return 4!==e?0:i.wrap<=0?1:(2===i.wrap?(m(i,255&t.adler),m(i,t.adler>>8&255),m(i,t.adler>>16&255),m(i,t.adler>>24&255),m(i,255&t.total_in),m(i,t.total_in>>8&255),m(i,t.total_in>>16&255),m(i,t.total_in>>24&255)):(x(i,t.adler>>>16),x(i,65535&t.adler)),b(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?0:1)},e.deflateEnd=function(t){var e;return t&&t.state?42!==(e=t.state.status)&&69!==e&&73!==e&&91!==e&&e!==h&&e!==d&&e!==p?v(t,c):(t.state=null,e===d?v(t,-3):0):c},e.deflateSetDictionary=function(t,e){var n,r,a,u,s,f,l,h,d=e.length;if(!t||!t.state)return c;if(2===(u=(n=t.state).wrap)||1===u&&42!==n.status||n.lookahead)return c;for(1===u&&(t.adler=o(t.adler,e,d,0)),n.wrap=0,d>=n.w_size&&(0===u&&(_(n.head),n.strstart=0,n.block_start=0,n.insert=0),h=new i.Buf8(n.w_size),i.arraySet(h,e,d-n.w_size,n.w_size,0),e=h,d=n.w_size),s=t.avail_in,f=t.next_in,l=t.input,t.avail_in=d,t.next_in=0,t.input=e,Z(n);n.lookahead>=3;){r=n.strstart,a=n.lookahead-2;do{n.ins_h=(n.ins_h<{"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},24980:t=>{"use strict";t.exports=function(t,e){var n,r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y,m,x,w,Z,D,k,E;n=t.state,r=t.next_in,k=t.input,i=r+(t.avail_in-5),a=t.next_out,E=t.output,o=a-(e-t.avail_out),u=a+(t.avail_out-257),s=n.dmax,c=n.wsize,f=n.whave,l=n.wnext,h=n.window,d=n.hold,p=n.bits,v=n.lencode,g=n.distcode,_=(1<>>=m=y>>>24,p-=m,0==(m=y>>>16&255))E[a++]=65535&y;else{if(!(16&m)){if(0==(64&m)){y=v[(65535&y)+(d&(1<>>=m,p-=m),p<15&&(d+=k[r++]<>>=m=y>>>24,p-=m,!(16&(m=y>>>16&255))){if(0==(64&m)){y=g[(65535&y)+(d&(1<s){t.msg="invalid distance too far back",n.mode=30;break t}if(d>>>=m,p-=m,w>(m=a-o)){if((m=w-m)>f&&n.sane){t.msg="invalid distance too far back",n.mode=30;break t}if(Z=0,D=h,0===l){if(Z+=c-m,m2;)E[a++]=D[Z++],E[a++]=D[Z++],E[a++]=D[Z++],x-=3;x&&(E[a++]=D[Z++],x>1&&(E[a++]=D[Z++]))}else{Z=a-w;do{E[a++]=E[Z++],E[a++]=E[Z++],E[a++]=E[Z++],x-=3}while(x>2);x&&(E[a++]=E[Z++],x>1&&(E[a++]=E[Z++]))}break}}break}}while(r>3,d&=(1<<(p-=x<<3))-1,t.next_in=r,t.next_out=a,t.avail_in=r{"use strict";var r=n(49761),i=n(95562),a=n(24299),o=n(24980),u=n(50881),s=-2,c=12,f=30;function l(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function h(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new r.Buf32(852),e.distcode=e.distdyn=new r.Buf32(592),e.sane=1,e.back=-1,0):s}function p(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,d(t)):s}function v(t,e){var n,r;return t&&t.state?(r=t.state,e<0?(n=0,e=-e):(n=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?s:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,p(t))):s}function g(t,e){var n,r;return t?(r=new h,t.state=r,r.window=null,0!==(n=v(t,e))&&(t.state=null),n):s}var _,b,y=!0;function m(t){if(y){var e;for(_=new r.Buf32(512),b=new r.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(u(1,t.lens,0,288,_,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;u(2,t.lens,0,32,b,0,t.work,{bits:5}),y=!1}t.lencode=_,t.lenbits=9,t.distcode=b,t.distbits=5}function x(t,e,n,i){var a,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(r.arraySet(o.window,e,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):((a=o.wsize-o.wnext)>i&&(a=i),r.arraySet(o.window,e,n-i,a,o.wnext),(i-=a)?(r.arraySet(o.window,e,n-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=a(n.check,R,2,0),b=0,y=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&b)<<8)+(b>>8))%31){t.msg="incorrect header check",n.mode=f;break}if(8!=(15&b)){t.msg="unknown compression method",n.mode=f;break}if(y-=4,S=8+(15&(b>>>=4)),0===n.wbits)n.wbits=S;else if(S>n.wbits){t.msg="invalid window size",n.mode=f;break}n.dmax=1<>8&1),512&n.flags&&(R[0]=255&b,R[1]=b>>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0,n.mode=3;case 3:for(;y<32;){if(0===g)break t;g--,b+=h[p++]<>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,n.check=a(n.check,R,4,0)),b=0,y=0,n.mode=4;case 4:for(;y<16;){if(0===g)break t;g--,b+=h[p++]<>8),512&n.flags&&(R[0]=255&b,R[1]=b>>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0,n.mode=5;case 5:if(1024&n.flags){for(;y<16;){if(0===g)break t;g--,b+=h[p++]<>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((D=n.length)>g&&(D=g),D&&(n.head&&(S=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),r.arraySet(n.head.extra,h,p,D,S)),512&n.flags&&(n.check=a(n.check,h,D,p)),g-=D,p+=D,n.length-=D),n.length))break t;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===g)break t;D=0;do{S=h[p+D++],n.head&&S&&n.length<65536&&(n.head.name+=String.fromCharCode(S))}while(S&&D>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=c;break;case 10:for(;y<32;){if(0===g)break t;g--,b+=h[p++]<>>=7&y,y-=7&y,n.mode=27;break}for(;y<3;){if(0===g)break t;g--,b+=h[p++]<>>=1)){case 0:n.mode=14;break;case 1:if(m(n),n.mode=20,6===e){b>>>=2,y-=2;break t}break;case 2:n.mode=17;break;case 3:t.msg="invalid block type",n.mode=f}b>>>=2,y-=2;break;case 14:for(b>>>=7&y,y-=7&y;y<32;){if(0===g)break t;g--,b+=h[p++]<>>16^65535)){t.msg="invalid stored block lengths",n.mode=f;break}if(n.length=65535&b,b=0,y=0,n.mode=15,6===e)break t;case 15:n.mode=16;case 16:if(D=n.length){if(D>g&&(D=g),D>_&&(D=_),0===D)break t;r.arraySet(d,h,p,D,v),g-=D,p+=D,_-=D,v+=D,n.length-=D;break}n.mode=c;break;case 17:for(;y<14;){if(0===g)break t;g--,b+=h[p++]<>>=5,y-=5,n.ndist=1+(31&b),b>>>=5,y-=5,n.ncode=4+(15&b),b>>>=4,y-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=f;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,y-=3}for(;n.have<19;)n.lens[P[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,T={bits:n.lenbits},N=u(0,n.lens,0,19,n.lencode,0,n.work,T),n.lenbits=T.bits,N){t.msg="invalid code lengths set",n.mode=f;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=A,y-=A,n.lens[n.have++]=C;else{if(16===C){for(z=A+2;y>>=A,y-=A,0===n.have){t.msg="invalid bit length repeat",n.mode=f;break}S=n.lens[n.have-1],D=3+(3&b),b>>>=2,y-=2}else if(17===C){for(z=A+3;y>>=A)),b>>>=3,y-=3}else{for(z=A+7;y>>=A)),b>>>=7,y-=7}if(n.have+D>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=f;break}for(;D--;)n.lens[n.have++]=S}}if(n.mode===f)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=f;break}if(n.lenbits=9,T={bits:n.lenbits},N=u(1,n.lens,0,n.nlen,n.lencode,0,n.work,T),n.lenbits=T.bits,N){t.msg="invalid literal/lengths set",n.mode=f;break}if(n.distbits=6,n.distcode=n.distdyn,T={bits:n.distbits},N=u(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,T),n.distbits=T.bits,N){t.msg="invalid distances set",n.mode=f;break}if(n.mode=20,6===e)break t;case 20:n.mode=21;case 21:if(g>=6&&_>=258){t.next_out=v,t.avail_out=_,t.next_in=p,t.avail_in=g,n.hold=b,n.bits=y,o(t,Z),v=t.next_out,d=t.output,_=t.avail_out,p=t.next_in,h=t.input,g=t.avail_in,b=n.hold,y=n.bits,n.mode===c&&(n.back=-1);break}for(n.back=0;j=(O=n.lencode[b&(1<>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>M)])>>>16&255,C=65535&O,!(M+(A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=M,y-=M,n.back+=M}if(b>>>=A,y-=A,n.back+=A,n.length=C,0===j){n.mode=26;break}if(32&j){n.back=-1,n.mode=c;break}if(64&j){t.msg="invalid literal/length code",n.mode=f;break}n.extra=15&j,n.mode=22;case 22:if(n.extra){for(z=n.extra;y>>=n.extra,y-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;j=(O=n.distcode[b&(1<>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>M)])>>>16&255,C=65535&O,!(M+(A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=M,y-=M,n.back+=M}if(b>>>=A,y-=A,n.back+=A,64&j){t.msg="invalid distance code",n.mode=f;break}n.offset=C,n.extra=15&j,n.mode=24;case 24:if(n.extra){for(z=n.extra;y>>=n.extra,y-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=f;break}n.mode=25;case 25:if(0===_)break t;if(D=Z-_,n.offset>D){if((D=n.offset-D)>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=f;break}D>n.wnext?(D-=n.wnext,k=n.wsize-D):k=n.wnext-D,D>n.length&&(D=n.length),E=n.window}else E=d,k=v-n.offset,D=n.length;D>_&&(D=_),_-=D,n.length-=D;do{d[v++]=E[k++]}while(--D);0===n.length&&(n.mode=21);break;case 26:if(0===_)break t;d[v++]=n.length,_--,n.mode=21;break;case 27:if(n.wrap){for(;y<32;){if(0===g)break t;g--,b|=h[p++]<{"use strict";var r=n(49761),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],a=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],u=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(t,e,n,s,c,f,l,h){var d,p,v,g,_,b,y,m,x,w=h.bits,Z=0,D=0,k=0,E=0,A=0,j=0,C=0,M=0,F=0,B=0,S=null,N=0,T=new r.Buf16(16),z=new r.Buf16(16),O=null,R=0;for(Z=0;Z<=15;Z++)T[Z]=0;for(D=0;D=1&&0===T[E];E--);if(A>E&&(A=E),0===E)return c[f++]=20971520,c[f++]=20971520,h.bits=1,0;for(k=1;k0&&(0===t||1!==E))return-1;for(z[1]=0,Z=1;Z<15;Z++)z[Z+1]=z[Z]+T[Z];for(D=0;D852||2===t&&F>592)return 1;for(;;){y=Z-C,l[D]b?(m=O[R+l[D]],x=S[N+l[D]]):(m=96,x=0),d=1<>C)+(p-=d)]=y<<24|m<<16|x|0}while(0!==p);for(d=1<>=1;if(0!==d?(B&=d-1,B+=d):B=0,D++,0==--T[Z]){if(Z===E)break;Z=e[n+l[D]]}if(Z>A&&(B&g)!==v){for(0===C&&(C=A),_+=k,M=1<<(j=Z-C);j+C852||2===t&&F>592)return 1;c[v=B&g]=A<<24|j<<16|_-f|0}}return 0!==B&&(c[_+B]=Z-C<<24|64<<16|0),h.bits=A,0}},82950:t=>{"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},69564:(t,e,n)=>{"use strict";var r=n(49761);function i(t){for(var e=t.length;--e>=0;)t[e]=0}var a=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],o=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],s=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],c=new Array(576);i(c);var f=new Array(60);i(f);var l=new Array(512);i(l);var h=new Array(256);i(h);var d=new Array(29);i(d);var p,v,g,_=new Array(30);function b(t,e,n,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=t&&t.length}function y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function m(t){return t<256?l[t]:l[256+(t>>>7)]}function x(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function w(t,e,n){t.bi_valid>16-n?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=n-16):(t.bi_buf|=e<>>=1,n<<=1}while(--e>0);return n>>>1}function k(t,e,n){var r,i,a=new Array(16),o=0;for(r=1;r<=15;r++)a[r]=o=o+n[r-1]<<1;for(i=0;i<=e;i++){var u=t[2*i+1];0!==u&&(t[2*i]=D(a[u]++,u))}}function E(t){var e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function A(t){t.bi_valid>8?x(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function j(t,e,n,r){var i=2*e,a=2*n;return t[i]>1;n>=1;n--)C(t,a,n);i=s;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],C(t,a,1),r=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=r,a[2*i]=a[2*n]+a[2*r],t.depth[i]=(t.depth[n]>=t.depth[r]?t.depth[n]:t.depth[r])+1,a[2*n+1]=a[2*r+1]=i,t.heap[1]=i++,C(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var n,r,i,a,o,u,s=e.dyn_tree,c=e.max_code,f=e.stat_desc.static_tree,l=e.stat_desc.has_stree,h=e.stat_desc.extra_bits,d=e.stat_desc.extra_base,p=e.stat_desc.max_length,v=0;for(a=0;a<=15;a++)t.bl_count[a]=0;for(s[2*t.heap[t.heap_max]+1]=0,n=t.heap_max+1;n<573;n++)(a=s[2*s[2*(r=t.heap[n])+1]+1]+1)>p&&(a=p,v++),s[2*r+1]=a,r>c||(t.bl_count[a]++,o=0,r>=d&&(o=h[r-d]),u=s[2*r],t.opt_len+=u*(a+o),l&&(t.static_len+=u*(f[2*r+1]+o)));if(0!==v){do{for(a=p-1;0===t.bl_count[a];)a--;t.bl_count[a]--,t.bl_count[a+1]+=2,t.bl_count[p]--,v-=2}while(v>0);for(a=p;0!==a;a--)for(r=t.bl_count[a];0!==r;)(i=t.heap[--n])>c||(s[2*i+1]!==a&&(t.opt_len+=(a-s[2*i+1])*s[2*i],s[2*i+1]=a),r--)}}(t,e),k(a,c,t.bl_count)}function B(t,e,n){var r,i,a=-1,o=e[1],u=0,s=7,c=4;for(0===o&&(s=138,c=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=o,o=e[2*(r+1)+1],++u>=7;r<30;r++)for(_[r]=i<<7,t=0;t<1<0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),F(t,t.l_desc),F(t,t.d_desc),o=function(t){var e;for(B(t,t.dyn_ltree,t.l_desc.max_code),B(t,t.dyn_dtree,t.d_desc.max_code),F(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*s[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),i=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=i&&(i=a)):i=a=n+5,n+4<=i&&-1!==e?T(t,e,n,r):4===t.strategy||a===i?(w(t,2+(r?1:0),3),M(t,c,f)):(w(t,4+(r?1:0),3),function(t,e,n,r){var i;for(w(t,e-257,5),w(t,n-1,5),w(t,r-4,4),i=0;i>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&n,t.last_lit++,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(h[n]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.last_lit===t.lit_bufsize-1},e._tr_align=function(t){w(t,2,3),Z(t,256,c),function(t){16===t.bi_valid?(x(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},20744:t=>{"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}}]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/zip.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/zip.js new file mode 100644 index 0000000000000000000000000000000000000000..972e24b264548c2d6d4d495b8327b8b3f4f27a7a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron/dist/zip.js @@ -0,0 +1 @@ +var zip=zip||{};zip.Archive=class{constructor(t){if(this._entries=[],t.length<4||80!=t[0]||75!=t[1])throw new zip.Error("Invalid Zip archive.");let e=null;for(let i=t.length-4;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3]){e=new zip.Reader(t,i+4,t.length);break}if(!e)throw new zip.Error("End of central directory not found.");for(e.skip(12),e.position=e.uint32();e.match([80,75,1,2]);)this._entries.push(new zip.Entry(e))}get entries(){return this._entries}},zip.Entry=class{constructor(t){if(t.uint16(),t.skip(2),this._flags=t.uint16(),1==(1&this._flags))throw new zip.Error("Encrypted entries not supported.");this._compressionMethod=t.uint16(),t.uint32(),t.uint32(),this._compressedSize=t.uint32(),this._size=t.uint32();let e=t.uint16(),i=t.uint16();const s=t.uint16();t.uint16(),t.uint16(),t.uint32();const r=t.uint32();t.skip(e),t.skip(i),t.bytes(s);const n=t.position;if(t.position=r,!t.match([80,75,3,4]))throw new zip.Error("Invalid local file header signature.");t.skip(22),e=t.uint16(),i=t.uint16();const o=t.bytes(e);this._name="";for(const t of o)this._name+=String.fromCharCode(t);t.skip(i),this._compressedData=t.bytes(this._compressedSize),t.position=n}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new zip.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new zip.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new zip.Error("Invalid uncompressed size.");break;default:throw new zip.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},zip.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),zip.HuffmanTree._offsets=zip.HuffmanTree._offsets||new Uint16Array(16)}build(t,e,i){for(let t=0;t<16;++t)this.table[t]=0;for(let s=0;s>>1){case 0:this._inflateUncompressedBlock(e,i);break;case 1:this._inflateBlockData(e,i,zip.HuffmanTree.staticLiteralLengthTree,zip.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(e,s,r),this._inflateBlockData(e,i,s,r);break;default:throw new zip.Error("Unknown block type.")}}while(0==(1&n));return i.merge()}_inflateUncompressedBlock(t,e){for(;t.data>8;)t.position--,t.data-=8;t.data=0;const i=t.uint16();if(i!==(65535&~t.uint16()))throw new zip.Error("Invalid uncompressed block length.");const s=t.bytes(i);e.push(s),i>32768?(e.buffer.set(s.subarray(s.length-32768,s.length),0),e.position=32768):(e.reset(),e.buffer.set(s,e.position),e.position+=s.length)}_decodeTrees(t,e,i){const s=t.bits(5)+257,r=t.bits(5)+1,n=t.bits(4)+4;for(let t=0;t<19;t++)zip.Inflater._lengths[t]=0;for(let e=0;e62464&&(e.position=n,e.push(new Uint8Array(r.subarray(o,n))),n=e.reset(),o=n);let a=t.symbol(i);if(256===a)return e.position=n,e.push(new Uint8Array(r.subarray(o,e.position))),void e.reset();if(a<256)r[n++]=a;else{a-=257;const e=t.bitsBase(zip.Inflater._lengthBits[a],zip.Inflater._lengthBase[a]),i=t.symbol(s);let o=n-t.bitsBase(zip.Inflater._distanceBits[i],zip.Inflater._distanceBase[i]);for(let t=0;t32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(t){this._blocks.push(t)}merge(){let t=0;for(const e of this._blocks)t+=e.length;const e=new Uint8Array(t);let i=0;for(const t of this._blocks)e.set(t,i),i+=t.length;return e}},zip.BitReader=class{constructor(t){this.buffer=t,this.position=0,this.data=0,this.value=0}bits(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,e}bitsBase(t,e){if(0==t)return e;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,i+e}bytes(t){const e=this.buffer.subarray(this.position,this.position+t);return this.position+=t,e}uint16(){const t=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,t}symbol(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,s++,e+=n[s],i-=n[s]}while(i>=0);return this.value=r,this.data-=s,t.symbol[e+i]}},zip.Reader=class{constructor(t,e,i){this._buffer=t,this._position=e,this._end=i}match(t){if(this._position+t.length<=this._end)for(let e=0;e=0?t:this._end+t}peek(){return this._positionthis._end)throw new zip.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new zip.Error("Data not available.");t=void 0===t?this._end:t;const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}uint16(){if(this._position+2>this._end)throw new zip.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}},zip.Error=class extends Error{constructor(t){super(t),this.name="Zip Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Archive=zip.Archive,module.exports.Inflater=zip.Inflater); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1f8a8be17df94d968919398191cdf563a4756979 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-metadata.json @@ -0,0 +1 @@ +[{"name":"InputLayer","schema":{"bindings":[{"name":"layerBindingId","type":"int","src":"layerBindingId"}]}},{"name":"OutputLayer","schema":{"category":"Tensor","bindings":[{"name":"layerBindingId","type":"int","src":"layerBindingId"}]}},{"name":"Pooling2dLayer","schema":{"category":"Pool","attributes":[{"name":"type","type":"string","src":"poolType","src_type":"PoolingAlgorithm"},{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"width","type":"string","src":"poolWidth"},{"name":"height","type":"string","src":"poolHeight"},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"outputShapeRounding","type":"string","src":"outputShapeRounding","src_type":"OutputShapeRounding"},{"name":"paddingMethod","type":"string","src":"paddingMethod","src_type":"PaddingMethod"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ReshapeLayer","schema":{"category":"Shape","attributes":[{"name":"targetShape","type":"string","src":"targetShape"}]}},{"name":"SoftmaxLayer","schema":{"category":"Activation","attributes":[{"name":"beta","type":"float","src":"beta"}]}},{"name":"Convolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dilation","type":"string","src":["dilationX","dilationY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"DepthwiseConvolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dilation","type":"string","src":["dilationX","dilationY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ActivationLayer","schema":{"category":"Activation","attributes":[{"name":"function","type":"string","src":"activationFunction","src_type":"ActivationFunction"},{"name":"a","type":"float","src":"a"},{"name":"b","type":"float","src":"b"}]}},{"name":"PermuteLayer","schema":{"category":"Shape","attributes":[{"name":"dimMappings","type":"string","src":"dimMappings"}]}},{"name":"FullyConnectedLayer","schema":{"category":"Layer","inputs":[{"name":"weights","src":"weights"},{"name":"biases","src":"biases"}],"attributes":[{"name":"transposeWeightsMatrix","type":"bool","src":"transposeWeightsMatrix"}]}},{"name":"ConstantLayer","schema":{"category":"Constant","inputs":[{"name":"input","src":"input"}]}},{"name":"SpaceToBatchNdLayer","schema":{"category":"Layer","attributes":[{"name":"blockShape","type":"string","src":"blockShape"},{"name":"padList","type":"string","src":"padList"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"BatchToSpaceNdLayer","schema":{"category":"Layer","attributes":[{"name":"blockShape","type":"string","src":"blockShape"},{"name":"crops","type":"string","src":"crops"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"DivisionLayer","schema":{"category":"Layer"}},{"name":"MinimumLayer","schema":{"category":"Layer"}},{"name":"EqualLayer","schema":{"category":"Layer"}},{"name":"MaximumLayer","schema":{"category":"Layer"}},{"name":"NormalizationLayer","schema":{"category":"Normalization","attributes":[{"name":"normChannelType","type":"string","src":"normChannelType","src_type":"NormalizationAlgorithmChannel"},{"name":"normMethodType","type":"string","src":"normMethodType","src_type":"NormalizationAlgorithmMethod"},{"name":"normSize","type":"uint","src":"normSize"},{"name":"alpha","type":"float","src":"alpha"},{"name":"beta","type":"float","src":"beta"},{"name":"k","type":"float","src":"k"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"PadLayer","schema":{"category":"Layer","attributes":[{"name":"padList","type":"uint","src":"padList"},{"name":"padValue","type":"float","src":"padValue"}]}},{"name":"RsqrtLayer","schema":{"category":"Layer"}},{"name":"FloorLayer","schema":{"category":"Layer"}},{"name":"BatchNormalizationLayer","schema":{"category":"Normalization","inputs":[{"name":"mean","src":"mean"},{"name":"variance","src":"variance"},{"name":"beta","src":"beta"},{"name":"gamma","src":"gamma"}],"attributes":[{"name":"eps","type":"float","src":"eps"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"GreaterLayer","schema":{"category":"Layer","attributes":[]}},{"name":"ResizeBilinearLayer","schema":{"category":"Layer","attributes":[{"name":"targetWidth","type":"uint","src":"targetWidth"},{"name":"targetHeight","type":"uint","src":"targetHeight"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"SubtractionLayer","schema":{}},{"name":"StridedSliceLayer","schema":{"category":"Tensor","attributes":[{"name":"begin","type":"int","src":"begin"},{"name":"end","type":"int","src":"end"},{"name":"stride","type":"int","src":"stride"},{"name":"beginMask","type":"int","src":"beginMask"},{"name":"endMask","type":"int","src":"endMask"},{"name":"shrinkAxisMask","type":"int","src":"shrinkAxisMask"},{"name":"ellipsisMask","type":"int","src":"ellipsisMask"},{"name":"newAxisMask","type":"int","src":"newAxisMask"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"GatherLayer","schema":{"category":"Tensor"}},{"name":"MeanLayer","schema":{"attributes":[{"name":"axis","type":"uint","src":"axis"},{"name":"keepDims","type":"bool","src":"keepDims"}]}},{"name":"MergerLayer","schema":{"category":"Tensor"}},{"name":"L2NormalizationLayer","schema":{"category":"Normalization","attributes":[{"name":"eps","type":"float","src":"eps"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"SplitterLayer","schema":{"category":"Tensor","attributes":[{"name":"concatAxis","type":"uint","src":"concatAxis"},{"name":"numViews","type":"uint","src":"numViewes"},{"name":"numDimensions","type":"uint","src":"numDimensions"}]}},{"name":"DetectionPostProcessLayer","schema":{"category":"Custom","attributes":[{"name":"maxDetections","type":"uint","src":"maxDetections"},{"name":"maxClassesPerDetection","type":"uint","src":"maxClassesPerDetection"},{"name":"detectionsPerClass","type":"uint","src":"detectionsPerClass"},{"name":"nmsScoreThreshold","type":"float","src":"nmsScoreThreshold"},{"name":"numIouThreshold","type":"float","src":"nmsIouThreshold"},{"name":"numClasses","type":"uint","src":"numClasses"},{"name":"useRegularNms","type":"bool","src":"useRegularNms"},{"name":"scaleX","type":"float","src":"scaleX"},{"name":"scaleY","type":"float","src":"scaleY"},{"name":"scaleW","type":"float","src":"scaleW"},{"name":"scaleH","type":"float","src":"scaleH"}]}},{"name":"LstmLayer","schema":{"category":"Layer","inputs":[{"name":"inputToForgetWeights1","src":"inputToForgetWeights1"},{"name":"inputToCellWeights1","src":"inputToCellWeights1"},{"name":"inputToOutputWeights1","src":"inputToOutputWeights1"},{"name":"recurrentToForgetWeights1","src":"recurrentToForgetWeights1"},{"name":"recurrentToCellWeights1","src":"recurrentToCellWeights1"},{"name":"recurrentToOutputWeights1","src":"recurrentToOutputWeights1"},{"name":"forgetGateBias1","src":"forgetGateBias1"},{"name":"cellBias1","src":"cellBias1"},{"name":"outputGateBias1","src":"outputGateBias1"},{"name":"inputToInputWeights1","src":"inputToInputWeights1"},{"name":"recurrentToInputWeights1","src":"recurrentToInputWeights1"},{"name":"cellToInputWeights1","src":"cellToInputWeights1"},{"name":"inputGateBias1","src":"inputGateBias1"},{"name":"projectionWeights1","src":"projectionWeights1"},{"name":"projectionBias1","src":"projectionBias1"},{"name":"cellToForgetWeights1","src":"cellToForgetWeights1"},{"name":"cellToOutputWeights1","src":"cellToOutputWeights1"},{"name":"inputLayerNormWeights1","src":"inputLayerNormWeights1"},{"name":"forgetLayerNormWeights1","src":"forgetLayerNormWeights1"},{"name":"cellLayerNormWeights1","src":"cellLayerNormWeights1"},{"name":"outputLayerNormWeights1","src":"outputLayerNormWeights1"}],"attributes":[{"name":"activationFunc","type":"uint","src":"activationFunc"},{"name":"clippingThresCell","type":"float","src":"clippingThresCell"},{"name":"clippingThresProj","type":"float","src":"clippingThresProj"},{"name":"cifgEnabled","type":"bool","src":"cifgEnabled"},{"name":"peepholeEnabled","type":"bool","src":"peepholeEnabled"},{"name":"projectionEnabled","type":"bool","src":"projectionEnabled"},{"name":"layerNormEnabled","type":"bool","src":"layerNormEnabled"}]}},{"name":"QuantizeLayer"},{"name":"DequantizeLayer"},{"name":"MergeLayer","schema":{"category":"Layer"}},{"name":"SwitchLayer","schema":{"category":"Layer"}},{"name":"ConcatLayer","schema":{"category":"Tensor","attributes":[{"name":"concatAxis","type":"uint","src":"concatAxis"},{"name":"numViews","type":"uint","src":"numViewes"},{"name":"numDimensions","type":"uint","src":"numDimensions"}]}},{"name":"SpaceToDepthLayer","schema":{"category":"Layer","attributes":[{"name":"blockSize","type":"uint","src":"blockSize"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"PreluLayer","schema":{"category":"Layer"}},{"name":"TransposeConvolution2dLayer","schema":{"category":"Layer","inputs":[{"name":"weight","src":"weights"},{"name":"bias","src":"biases"}],"attributes":[{"name":"padding","type":"string","src":["padTop","padRight","padBottom","padLeft"]},{"name":"stride","type":"string","src":["strideX","strideY"]},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"ResizeLayer","schema":{"category":"Layer","attributes":[{"name":"targetWidth","type":"uint","src":"targetWidth"},{"name":"targetHeight","type":"uint","src":"targetHeight"},{"name":"method","type":"string","src":"method","src_type":"ResizeMethod"},{"name":"dataLayout","type":"string","src":"dataLayout","src_type":"DataLayout"}]}},{"name":"StackLayer","schema":{"category":"Layer","attributes":[{"name":"axis","type":"uint","src":"axis"},{"name":"numInputs","type":"uint","src":"numInputs"},{"name":"inputShape","type":"uint","src":"inputShape"}]}},{"name":"QuantizedLstmLayer","schema":{"category":"Layer","inputs":[{"name":"inputToInputWeights1","src":"inputToInputWeights1"},{"name":"inputToForgetWeights1","src":"inputToForgetWeights1"},{"name":"inputToCellWeights1","src":"inputToCellWeights1"},{"name":"inputToOutputWeights1","src":"inputToOutputWeights1"},{"name":"recurrentToInputWeights1","src":"recurrentToInputWeights1"},{"name":"recurrentToForgetWeights1","src":"recurrentToForgetWeights1"},{"name":"recurrentToCellWeights1","src":"recurrentToCellWeights1"},{"name":"recurrentToOutputWeights1","src":"recurrentToOutputWeights1"},{"name":"inputGateBias1","src":"inputGateBias1"},{"name":"forgetGateBias1","src":"forgetGateBias1"},{"name":"cellBias1","src":"cellBias1"},{"name":"outputGateBias1","src":"outputGateBias1"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-schema.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..cd4479c390d2d37c73357d01bc39bb60f17ea55b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn-schema.js @@ -0,0 +1 @@ +var $root=flatbuffers.get("armnn");$root.armnnSerializer=$root.armnnSerializer||{},$root.armnnSerializer.ActivationFunction={Sigmoid:0,TanH:1,Linear:2,ReLu:3,BoundedReLu:4,SoftReLu:5,LeakyReLu:6,Abs:7,Sqrt:8,Square:9,Elu:10,HardSwish:11},$root.armnnSerializer.ArgMinMaxFunction={Min:0,Max:1},$root.armnnSerializer.DataType={Float16:0,Float32:1,QuantisedAsymm8:2,Signed32:3,Boolean:4,QuantisedSymm16:5,QAsymmU8:6,QSymmS16:7,QAsymmS8:8,QSymmS8:9},$root.armnnSerializer.DataLayout={NHWC:0,NCHW:1},$root.armnnSerializer.ResizeMethod={NearestNeighbor:0,Bilinear:1},$root.armnnSerializer.TensorInfo=class{static decode(e,r){const t=new $root.armnnSerializer.TensorInfo;return t.dimensions=e.typedArray(r,4,Uint32Array),t.dataType=e.int8_(r,6,0),t.quantizationScale=e.float32_(r,8,1),t.quantizationOffset=e.int32_(r,10,0),t.quantizationScales=e.typedArray(r,12,Float32Array),t.quantizationDim=e.uint32_(r,14,0),t.dimensionality=e.uint32_(r,16,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.TensorInfo;return t.dimensions=e.typedArray(r.dimensions,Uint32Array),t.dataType=$root.armnnSerializer.DataType[r.dataType],t.quantizationScale=e.value(r.quantizationScale,1),t.quantizationOffset=e.value(r.quantizationOffset,0),t.quantizationScales=e.typedArray(r.quantizationScales,Float32Array),t.quantizationDim=e.value(r.quantizationDim,0),t.dimensionality=e.value(r.dimensionality,1),t}},$root.armnnSerializer.Connection=class{static decode(e,r){const t=new $root.armnnSerializer.Connection;return t.sourceLayerIndex=e.uint32(r+0),t.outputSlotIndex=e.uint32(r+4),t}static decodeText(e,r){const t=new $root.armnnSerializer.Connection;return t.sourceLayerIndex=r.sourceLayerIndex,t.outputSlotIndex=r.outputSlotIndex,t}},$root.armnnSerializer.ByteData=class{static decode(e,r){const t=new $root.armnnSerializer.ByteData;return t.data=e.typedArray(r,4,Int8Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ByteData;return t.data=e.typedArray(r.data,Int8Array),t}},$root.armnnSerializer.ShortData=class{static decode(e,r){const t=new $root.armnnSerializer.ShortData;return t.data=e.typedArray(r,4,Int16Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ShortData;return t.data=e.typedArray(r.data,Int16Array),t}},$root.armnnSerializer.IntData=class{static decode(e,r){const t=new $root.armnnSerializer.IntData;return t.data=e.typedArray(r,4,Int32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.IntData;return t.data=e.typedArray(r.data,Int32Array),t}},$root.armnnSerializer.LongData=class{static decode(e,r){const t=new $root.armnnSerializer.LongData;return t.data=e.int64s_(r,4),t}static decodeText(e,r){const t=new $root.armnnSerializer.LongData;return t.data=e.array(r.data),t}},$root.armnnSerializer.ConstTensorData=class{static decode(e,r,t){switch(t){case 1:return $root.armnnSerializer.ByteData.decode(e,r);case 2:return $root.armnnSerializer.ShortData.decode(e,r);case 3:return $root.armnnSerializer.IntData.decode(e,r);case 4:return $root.armnnSerializer.LongData.decode(e,r)}}static decodeText(e,r,t){switch(t){case"ByteData":return $root.armnnSerializer.ByteData.decodeText(e,r);case"ShortData":return $root.armnnSerializer.ShortData.decodeText(e,r);case"IntData":return $root.armnnSerializer.IntData.decodeText(e,r);case"LongData":return $root.armnnSerializer.LongData.decodeText(e,r)}}},$root.armnnSerializer.ConstTensor=class{static decode(e,r){const t=new $root.armnnSerializer.ConstTensor;return t.info=e.table(r,4,$root.armnnSerializer.TensorInfo.decode),t.data=e.union(r,6,$root.armnnSerializer.ConstTensorData.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConstTensor;return t.info=e.object(r.info,$root.armnnSerializer.TensorInfo.decodeText),t.data=$root.armnnSerializer.ConstTensorData.decodeText(e,r.data,r.data_type),t}},$root.armnnSerializer.InputSlot=class{static decode(e,r){const t=new $root.armnnSerializer.InputSlot;return t.index=e.uint32_(r,4,0),t.connection=e.struct(r,6,$root.armnnSerializer.Connection.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InputSlot;return t.index=e.value(r.index,0),t.connection=e.object(r.connection,$root.armnnSerializer.Connection.decodeText),t}},$root.armnnSerializer.OutputSlot=class{static decode(e,r){const t=new $root.armnnSerializer.OutputSlot;return t.index=e.uint32_(r,4,0),t.tensorInfo=e.table(r,6,$root.armnnSerializer.TensorInfo.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OutputSlot;return t.index=e.value(r.index,0),t.tensorInfo=e.object(r.tensorInfo,$root.armnnSerializer.TensorInfo.decodeText),t}},$root.armnnSerializer.LayerType={Addition:0,Input:1,Multiplication:2,Output:3,Pooling2d:4,Reshape:5,Softmax:6,Convolution2d:7,DepthwiseConvolution2d:8,Activation:9,Permute:10,FullyConnected:11,Constant:12,SpaceToBatchNd:13,BatchToSpaceNd:14,Division:15,Minimum:16,Equal:17,Maximum:18,Normalization:19,Pad:20,Rsqrt:21,Floor:22,BatchNormalization:23,Greater:24,ResizeBilinear:25,Subtraction:26,StridedSlice:27,Gather:28,Mean:29,Merger:30,L2Normalization:31,Splitter:32,DetectionPostProcess:33,Lstm:34,Quantize:35,Dequantize:36,Merge:37,Switch:38,Concat:39,SpaceToDepth:40,Prelu:41,TransposeConvolution2d:42,Resize:43,Stack:44,QuantizedLstm:45,Abs:46,ArgMinMax:47,Slice:48,DepthToSpace:49,InstanceNormalization:50,LogSoftmax:51,Comparison:52,StandIn:53,ElementwiseUnary:54,Transpose:55,QLstm:56,Fill:57,Rank:58},$root.armnnSerializer.LayerBase=class{static decode(e,r){const t=new $root.armnnSerializer.LayerBase;return t.index=e.uint32_(r,4,0),t.layerName=e.string_(r,6,null),t.layerType=e.uint32_(r,8,0),t.inputSlots=e.tableArray(r,10,$root.armnnSerializer.InputSlot.decode),t.outputSlots=e.tableArray(r,12,$root.armnnSerializer.OutputSlot.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LayerBase;return t.index=e.value(r.index,0),t.layerName=e.value(r.layerName,null),t.layerType=$root.armnnSerializer.LayerType[r.layerType],t.inputSlots=e.objectArray(r.inputSlots,$root.armnnSerializer.InputSlot.decodeText),t.outputSlots=e.objectArray(r.outputSlots,$root.armnnSerializer.OutputSlot.decodeText),t}},$root.armnnSerializer.BindableLayerBase=class{static decode(e,r){const t=new $root.armnnSerializer.BindableLayerBase;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.layerBindingId=e.int32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BindableLayerBase;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.layerBindingId=e.value(r.layerBindingId,0),t}},$root.armnnSerializer.AbsLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AbsLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AbsLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.ActivationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ActivationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ActivationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ActivationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ActivationDescriptor.decodeText),t}},$root.armnnSerializer.ActivationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ActivationDescriptor;return t.activationFunction=e.int8_(r,4,0),t.a=e.float32_(r,6,0),t.b=e.float32_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ActivationDescriptor;return t.activationFunction=$root.armnnSerializer.ActivationFunction[r.activationFunction],t.a=e.value(r.a,0),t.b=e.value(r.b,0),t}},$root.armnnSerializer.AdditionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AdditionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AdditionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.ArgMinMaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ArgMinMaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ArgMinMaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ArgMinMaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ArgMinMaxDescriptor.decodeText),t}},$root.armnnSerializer.ArgMinMaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ArgMinMaxDescriptor;return t.argMinMaxFunction=e.int8_(r,4,0),t.axis=e.int32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ArgMinMaxDescriptor;return t.argMinMaxFunction=$root.armnnSerializer.ArgMinMaxFunction[r.argMinMaxFunction],t.axis=e.value(r.axis,0),t}},$root.armnnSerializer.ComparisonOperation={Equal:0,Greater:1,GreaterOrEqual:2,Less:3,LessOrEqual:4,NotEqual:5},$root.armnnSerializer.ComparisonDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ComparisonDescriptor;return t.operation=e.int8_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ComparisonDescriptor;return t.operation=$root.armnnSerializer.ComparisonOperation[r.operation],t}},$root.armnnSerializer.ComparisonLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ComparisonLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ComparisonDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ComparisonLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ComparisonDescriptor.decodeText),t}},$root.armnnSerializer.ConstantLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ConstantLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.input=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConstantLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.input=e.object(r.input,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.Convolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.Convolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.Convolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.Convolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.Convolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.Convolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.Convolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.dilationX=e.uint32_(r,16,1),t.dilationY=e.uint32_(r,18,1),t.biasEnabled=e.bool_(r,20,!1),t.dataLayout=e.int8_(r,22,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.Convolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.dilationX=e.value(r.dilationX,1),t.dilationY=e.value(r.dilationY,1),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.DepthToSpaceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DepthToSpaceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DepthToSpaceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthToSpaceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DepthToSpaceDescriptor.decodeText),t}},$root.armnnSerializer.DepthToSpaceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DepthToSpaceDescriptor;return t.blockSize=e.uint32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthToSpaceDescriptor;return t.blockSize=e.value(r.blockSize,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.DivisionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DivisionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DivisionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.UnaryOperation={Abs:0,Rsqrt:1,Sqrt:2,Exp:3,Neg:4},$root.armnnSerializer.ElementwiseUnaryDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryDescriptor;return t.operation=e.int8_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryDescriptor;return t.operation=$root.armnnSerializer.UnaryOperation[r.operation],t}},$root.armnnSerializer.ElementwiseUnaryLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ElementwiseUnaryDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ElementwiseUnaryLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ElementwiseUnaryDescriptor.decodeText),t}},$root.armnnSerializer.EqualLayer=class{static decode(e,r){const t=new $root.armnnSerializer.EqualLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.EqualLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.FillLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FillLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.FillDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FillLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.FillDescriptor.decodeText),t}},$root.armnnSerializer.FillDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.FillDescriptor;return t.value=e.float32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.FillDescriptor;return t.value=e.value(r.value,0),t}},$root.armnnSerializer.FloorLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FloorLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FloorLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.FullyConnectedLayer=class{static decode(e,r){const t=new $root.armnnSerializer.FullyConnectedLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.FullyConnectedDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.FullyConnectedLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.FullyConnectedDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.FullyConnectedDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.FullyConnectedDescriptor;return t.biasEnabled=e.bool_(r,4,!1),t.transposeWeightsMatrix=e.bool_(r,6,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.FullyConnectedDescriptor;return t.biasEnabled=e.value(r.biasEnabled,!1),t.transposeWeightsMatrix=e.value(r.transposeWeightsMatrix,!1),t}},$root.armnnSerializer.GatherLayer=class{static decode(e,r){const t=new $root.armnnSerializer.GatherLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.GatherDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.GatherLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.GatherDescriptor.decodeText),t}},$root.armnnSerializer.GatherDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.GatherDescriptor;return t.axis=e.int32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.GatherDescriptor;return t.axis=e.value(r.axis,0),t}},$root.armnnSerializer.GreaterLayer=class{static decode(e,r){const t=new $root.armnnSerializer.GreaterLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.GreaterLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.InputLayer=class{static decode(e,r){const t=new $root.armnnSerializer.InputLayer;return t.base=e.table(r,4,$root.armnnSerializer.BindableLayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InputLayer;return t.base=e.object(r.base,$root.armnnSerializer.BindableLayerBase.decodeText),t}},$root.armnnSerializer.InstanceNormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.InstanceNormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.InstanceNormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.InstanceNormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.InstanceNormalizationDescriptor.decodeText),t}},$root.armnnSerializer.InstanceNormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.InstanceNormalizationDescriptor;return t.gamma=e.float32_(r,4,0),t.beta=e.float32_(r,6,0),t.eps=e.float32_(r,8,0),t.dataLayout=e.int8_(r,10,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.InstanceNormalizationDescriptor;return t.gamma=e.value(r.gamma,0),t.beta=e.value(r.beta,0),t.eps=e.value(r.eps,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.LogSoftmaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.LogSoftmaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.LogSoftmaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LogSoftmaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.LogSoftmaxDescriptor.decodeText),t}},$root.armnnSerializer.LogSoftmaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.LogSoftmaxDescriptor;return t.beta=e.float32_(r,4,1),t.axis=e.int32_(r,6,-1),t}static decodeText(e,r){const t=new $root.armnnSerializer.LogSoftmaxDescriptor;return t.beta=e.value(r.beta,1),t.axis=e.value(r.axis,-1),t}},$root.armnnSerializer.L2NormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.L2NormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.L2NormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.L2NormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.L2NormalizationDescriptor.decodeText),t}},$root.armnnSerializer.L2NormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.L2NormalizationDescriptor;return t.dataLayout=e.int8_(r,4,1),t.eps=e.float32_(r,6,1e-12),t}static decodeText(e,r){const t=new $root.armnnSerializer.L2NormalizationDescriptor;return t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.eps=e.value(r.eps,1e-12),t}},$root.armnnSerializer.MinimumLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MinimumLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MinimumLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MaximumLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MaximumLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MaximumLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MultiplicationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MultiplicationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MultiplicationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.Pooling2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.Pooling2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.Pooling2dDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.Pooling2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.Pooling2dDescriptor.decodeText),t}},$root.armnnSerializer.PoolingAlgorithm={Max:0,Average:1,L2:2},$root.armnnSerializer.OutputShapeRounding={Floor:0,Ceiling:1},$root.armnnSerializer.PaddingMethod={IgnoreValue:0,Exclude:1},$root.armnnSerializer.Pooling2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.Pooling2dDescriptor;return t.poolType=e.int8_(r,4,0),t.padLeft=e.uint32_(r,6,0),t.padRight=e.uint32_(r,8,0),t.padTop=e.uint32_(r,10,0),t.padBottom=e.uint32_(r,12,0),t.poolWidth=e.uint32_(r,14,0),t.poolHeight=e.uint32_(r,16,0),t.strideX=e.uint32_(r,18,0),t.strideY=e.uint32_(r,20,0),t.outputShapeRounding=e.int8_(r,22,0),t.paddingMethod=e.int8_(r,24,0),t.dataLayout=e.int8_(r,26,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.Pooling2dDescriptor;return t.poolType=$root.armnnSerializer.PoolingAlgorithm[r.poolType],t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.poolWidth=e.value(r.poolWidth,0),t.poolHeight=e.value(r.poolHeight,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.outputShapeRounding=$root.armnnSerializer.OutputShapeRounding[r.outputShapeRounding],t.paddingMethod=$root.armnnSerializer.PaddingMethod[r.paddingMethod],t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.QuantizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.SoftmaxLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SoftmaxLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SoftmaxDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SoftmaxLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SoftmaxDescriptor.decodeText),t}},$root.armnnSerializer.SoftmaxDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SoftmaxDescriptor;return t.beta=e.float32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SoftmaxDescriptor;return t.beta=e.value(r.beta,0),t}},$root.armnnSerializer.DepthwiseConvolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DepthwiseConvolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DepthwiseConvolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.DepthwiseConvolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.dilationX=e.uint32_(r,16,1),t.dilationY=e.uint32_(r,18,1),t.biasEnabled=e.bool_(r,20,!1),t.dataLayout=e.int8_(r,22,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.DepthwiseConvolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.dilationX=e.value(r.dilationX,1),t.dilationY=e.value(r.dilationY,1),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.OutputLayer=class{static decode(e,r){const t=new $root.armnnSerializer.OutputLayer;return t.base=e.table(r,4,$root.armnnSerializer.BindableLayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OutputLayer;return t.base=e.object(r.base,$root.armnnSerializer.BindableLayerBase.decodeText),t}},$root.armnnSerializer.ReshapeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ReshapeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ReshapeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ReshapeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ReshapeDescriptor.decodeText),t}},$root.armnnSerializer.ReshapeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ReshapeDescriptor;return t.targetShape=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.ReshapeDescriptor;return t.targetShape=e.typedArray(r.targetShape,Uint32Array),t}},$root.armnnSerializer.PermuteLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PermuteLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.PermuteDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PermuteLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.PermuteDescriptor.decodeText),t}},$root.armnnSerializer.PermuteDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.PermuteDescriptor;return t.dimMappings=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.PermuteDescriptor;return t.dimMappings=e.typedArray(r.dimMappings,Uint32Array),t}},$root.armnnSerializer.SpaceToBatchNdLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SpaceToBatchNdDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SpaceToBatchNdDescriptor.decodeText),t}},$root.armnnSerializer.SpaceToBatchNdDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdDescriptor;return t.blockShape=e.typedArray(r,4,Uint32Array),t.padList=e.typedArray(r,6,Uint32Array),t.dataLayout=e.int8_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToBatchNdDescriptor;return t.blockShape=e.typedArray(r.blockShape,Uint32Array),t.padList=e.typedArray(r.padList,Uint32Array),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.SpaceToDepthLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToDepthLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SpaceToDepthDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToDepthLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SpaceToDepthDescriptor.decodeText),t}},$root.armnnSerializer.SpaceToDepthDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SpaceToDepthDescriptor;return t.blockSize=e.uint32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.SpaceToDepthDescriptor;return t.blockSize=e.value(r.blockSize,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.SubtractionLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SubtractionLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SubtractionLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.BatchToSpaceNdLayer=class{static decode(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.BatchToSpaceNdDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.BatchToSpaceNdDescriptor.decodeText),t}},$root.armnnSerializer.BatchToSpaceNdDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdDescriptor;return t.blockShape=e.typedArray(r,4,Uint32Array),t.crops=e.typedArray(r,6,Uint32Array),t.dataLayout=e.int8_(r,8,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchToSpaceNdDescriptor;return t.blockShape=e.typedArray(r.blockShape,Uint32Array),t.crops=e.typedArray(r.crops,Uint32Array),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.NormalizationAlgorithmChannel={Across:0,Within:1},$root.armnnSerializer.NormalizationAlgorithmMethod={LocalBrightness:0,LocalContrast:1},$root.armnnSerializer.NormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.NormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.NormalizationDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.NormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.NormalizationDescriptor.decodeText),t}},$root.armnnSerializer.NormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.NormalizationDescriptor;return t.normChannelType=e.int8_(r,4,0),t.normMethodType=e.int8_(r,6,0),t.normSize=e.uint32_(r,8,0),t.alpha=e.float32_(r,10,0),t.beta=e.float32_(r,12,0),t.k=e.float32_(r,14,0),t.dataLayout=e.int8_(r,16,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.NormalizationDescriptor;return t.normChannelType=$root.armnnSerializer.NormalizationAlgorithmChannel[r.normChannelType],t.normMethodType=$root.armnnSerializer.NormalizationAlgorithmMethod[r.normMethodType],t.normSize=e.value(r.normSize,0),t.alpha=e.value(r.alpha,0),t.beta=e.value(r.beta,0),t.k=e.value(r.k,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.MeanLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MeanLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.MeanDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MeanLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.MeanDescriptor.decodeText),t}},$root.armnnSerializer.MeanDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.MeanDescriptor;return t.axis=e.typedArray(r,4,Uint32Array),t.keepDims=e.bool_(r,6,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.MeanDescriptor;return t.axis=e.typedArray(r.axis,Uint32Array),t.keepDims=e.value(r.keepDims,!1),t}},$root.armnnSerializer.PadLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PadLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.PadDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PadLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.PadDescriptor.decodeText),t}},$root.armnnSerializer.PadDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.PadDescriptor;return t.padList=e.typedArray(r,4,Uint32Array),t.padValue=e.float32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.PadDescriptor;return t.padList=e.typedArray(r.padList,Uint32Array),t.padValue=e.value(r.padValue,0),t}},$root.armnnSerializer.RsqrtLayer=class{static decode(e,r){const t=new $root.armnnSerializer.RsqrtLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.RsqrtLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.BatchNormalizationLayer=class{static decode(e,r){const t=new $root.armnnSerializer.BatchNormalizationLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.BatchNormalizationDescriptor.decode),t.mean=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.variance=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.beta=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.gamma=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchNormalizationLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.BatchNormalizationDescriptor.decodeText),t.mean=e.object(r.mean,$root.armnnSerializer.ConstTensor.decodeText),t.variance=e.object(r.variance,$root.armnnSerializer.ConstTensor.decodeText),t.beta=e.object(r.beta,$root.armnnSerializer.ConstTensor.decodeText),t.gamma=e.object(r.gamma,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.BatchNormalizationDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.BatchNormalizationDescriptor;return t.eps=e.float32_(r,4,0),t.dataLayout=e.int8_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.BatchNormalizationDescriptor;return t.eps=e.value(r.eps,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.ResizeBilinearLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeBilinearLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ResizeBilinearDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeBilinearLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ResizeBilinearDescriptor.decodeText),t}},$root.armnnSerializer.ResizeBilinearDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeBilinearDescriptor;return t.targetWidth=e.uint32_(r,4,0),t.targetHeight=e.uint32_(r,6,0),t.dataLayout=e.int8_(r,8,0),t.alignCorners=e.bool_(r,10,!1),t.halfPixelCenters=e.bool_(r,12,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeBilinearDescriptor;return t.targetWidth=e.value(r.targetWidth,0),t.targetHeight=e.value(r.targetHeight,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.alignCorners=e.value(r.alignCorners,!1),t.halfPixelCenters=e.value(r.halfPixelCenters,!1),t}},$root.armnnSerializer.SliceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SliceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.SliceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SliceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.SliceDescriptor.decodeText),t}},$root.armnnSerializer.SliceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.SliceDescriptor;return t.begin=e.typedArray(r,4,Uint32Array),t.size=e.typedArray(r,6,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.SliceDescriptor;return t.begin=e.typedArray(r.begin,Uint32Array),t.size=e.typedArray(r.size,Uint32Array),t}},$root.armnnSerializer.StridedSliceLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StridedSliceLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StridedSliceDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StridedSliceLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StridedSliceDescriptor.decodeText),t}},$root.armnnSerializer.StridedSliceDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StridedSliceDescriptor;return t.begin=e.typedArray(r,4,Int32Array),t.end=e.typedArray(r,6,Int32Array),t.stride=e.typedArray(r,8,Int32Array),t.beginMask=e.int32_(r,10,0),t.endMask=e.int32_(r,12,0),t.shrinkAxisMask=e.int32_(r,14,0),t.ellipsisMask=e.int32_(r,16,0),t.newAxisMask=e.int32_(r,18,0),t.dataLayout=e.int8_(r,20,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.StridedSliceDescriptor;return t.begin=e.typedArray(r.begin,Int32Array),t.end=e.typedArray(r.end,Int32Array),t.stride=e.typedArray(r.stride,Int32Array),t.beginMask=e.value(r.beginMask,0),t.endMask=e.value(r.endMask,0),t.shrinkAxisMask=e.value(r.shrinkAxisMask,0),t.ellipsisMask=e.value(r.ellipsisMask,0),t.newAxisMask=e.value(r.newAxisMask,0),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.ConcatLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ConcatLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.OriginsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ConcatLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.OriginsDescriptor.decodeText),t}},$root.armnnSerializer.MergerLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MergerLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.OriginsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MergerLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.OriginsDescriptor.decodeText),t}},$root.armnnSerializer.UintVector=class{static decode(e,r){const t=new $root.armnnSerializer.UintVector;return t.data=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.UintVector;return t.data=e.typedArray(r.data,Uint32Array),t}},$root.armnnSerializer.OriginsDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.OriginsDescriptor;return t.concatAxis=e.uint32_(r,4,0),t.numViews=e.uint32_(r,6,0),t.numDimensions=e.uint32_(r,8,0),t.viewOrigins=e.tableArray(r,10,$root.armnnSerializer.UintVector.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.OriginsDescriptor;return t.concatAxis=e.value(r.concatAxis,0),t.numViews=e.value(r.numViews,0),t.numDimensions=e.value(r.numDimensions,0),t.viewOrigins=e.objectArray(r.viewOrigins,$root.armnnSerializer.UintVector.decodeText),t}},$root.armnnSerializer.ViewsDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ViewsDescriptor;return t.origins=e.table(r,4,$root.armnnSerializer.OriginsDescriptor.decode),t.viewSizes=e.tableArray(r,6,$root.armnnSerializer.UintVector.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ViewsDescriptor;return t.origins=e.object(r.origins,$root.armnnSerializer.OriginsDescriptor.decodeText),t.viewSizes=e.objectArray(r.viewSizes,$root.armnnSerializer.UintVector.decodeText),t}},$root.armnnSerializer.SplitterLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SplitterLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ViewsDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SplitterLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ViewsDescriptor.decodeText),t}},$root.armnnSerializer.DetectionPostProcessLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DetectionPostProcessLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.DetectionPostProcessDescriptor.decode),t.anchors=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DetectionPostProcessLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.DetectionPostProcessDescriptor.decodeText),t.anchors=e.object(r.anchors,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.DetectionPostProcessDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.DetectionPostProcessDescriptor;return t.maxDetections=e.uint32_(r,4,0),t.maxClassesPerDetection=e.uint32_(r,6,0),t.detectionsPerClass=e.uint32_(r,8,0),t.nmsScoreThreshold=e.float32_(r,10,0),t.nmsIouThreshold=e.float32_(r,12,0),t.numClasses=e.uint32_(r,14,0),t.useRegularNms=e.bool_(r,16,!1),t.scaleX=e.float32_(r,18,0),t.scaleY=e.float32_(r,20,0),t.scaleW=e.float32_(r,22,0),t.scaleH=e.float32_(r,24,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.DetectionPostProcessDescriptor;return t.maxDetections=e.value(r.maxDetections,0),t.maxClassesPerDetection=e.value(r.maxClassesPerDetection,0),t.detectionsPerClass=e.value(r.detectionsPerClass,0),t.nmsScoreThreshold=e.value(r.nmsScoreThreshold,0),t.nmsIouThreshold=e.value(r.nmsIouThreshold,0),t.numClasses=e.value(r.numClasses,0),t.useRegularNms=e.value(r.useRegularNms,!1),t.scaleX=e.value(r.scaleX,0),t.scaleY=e.value(r.scaleY,0),t.scaleW=e.value(r.scaleW,0),t.scaleH=e.value(r.scaleH,0),t}},$root.armnnSerializer.LstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.LstmInputParams;return t.inputToForgetWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.inputToInputWeights=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.cellToInputWeights=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,28,$root.armnnSerializer.ConstTensor.decode),t.projectionWeights=e.table(r,30,$root.armnnSerializer.ConstTensor.decode),t.projectionBias=e.table(r,32,$root.armnnSerializer.ConstTensor.decode),t.cellToForgetWeights=e.table(r,34,$root.armnnSerializer.ConstTensor.decode),t.cellToOutputWeights=e.table(r,36,$root.armnnSerializer.ConstTensor.decode),t.inputLayerNormWeights=e.table(r,38,$root.armnnSerializer.ConstTensor.decode),t.forgetLayerNormWeights=e.table(r,40,$root.armnnSerializer.ConstTensor.decode),t.cellLayerNormWeights=e.table(r,42,$root.armnnSerializer.ConstTensor.decode),t.outputLayerNormWeights=e.table(r,44,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmInputParams;return t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToInputWeights=e.object(r.cellToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.projectionWeights=e.object(r.projectionWeights,$root.armnnSerializer.ConstTensor.decodeText),t.projectionBias=e.object(r.projectionBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellToForgetWeights=e.object(r.cellToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToOutputWeights=e.object(r.cellToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputLayerNormWeights=e.object(r.inputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetLayerNormWeights=e.object(r.forgetLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellLayerNormWeights=e.object(r.cellLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.outputLayerNormWeights=e.object(r.outputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.LstmDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.LstmDescriptor;return t.activationFunc=e.uint32_(r,4,0),t.clippingThresCell=e.float32_(r,6,0),t.clippingThresProj=e.float32_(r,8,0),t.cifgEnabled=e.bool_(r,10,!0),t.peepholeEnabled=e.bool_(r,12,!1),t.projectionEnabled=e.bool_(r,14,!1),t.layerNormEnabled=e.bool_(r,16,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmDescriptor;return t.activationFunc=e.value(r.activationFunc,0),t.clippingThresCell=e.value(r.clippingThresCell,0),t.clippingThresProj=e.value(r.clippingThresProj,0),t.cifgEnabled=e.value(r.cifgEnabled,!0),t.peepholeEnabled=e.value(r.peepholeEnabled,!1),t.projectionEnabled=e.value(r.projectionEnabled,!1),t.layerNormEnabled=e.value(r.layerNormEnabled,!1),t}},$root.armnnSerializer.LstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.LstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.LstmDescriptor.decode),t.inputParams=e.table(r,8,$root.armnnSerializer.LstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.LstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.LstmDescriptor.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.LstmInputParams.decodeText),t}},$root.armnnSerializer.QLstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmInputParams;return t.inputToForgetWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.inputToInputWeights=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t.projectionWeights=e.table(r,28,$root.armnnSerializer.ConstTensor.decode),t.projectionBias=e.table(r,30,$root.armnnSerializer.ConstTensor.decode),t.cellToInputWeights=e.table(r,32,$root.armnnSerializer.ConstTensor.decode),t.cellToForgetWeights=e.table(r,34,$root.armnnSerializer.ConstTensor.decode),t.cellToOutputWeights=e.table(r,36,$root.armnnSerializer.ConstTensor.decode),t.inputLayerNormWeights=e.table(r,38,$root.armnnSerializer.ConstTensor.decode),t.forgetLayerNormWeights=e.table(r,40,$root.armnnSerializer.ConstTensor.decode),t.cellLayerNormWeights=e.table(r,42,$root.armnnSerializer.ConstTensor.decode),t.outputLayerNormWeights=e.table(r,44,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmInputParams;return t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.projectionWeights=e.object(r.projectionWeights,$root.armnnSerializer.ConstTensor.decodeText),t.projectionBias=e.object(r.projectionBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellToInputWeights=e.object(r.cellToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToForgetWeights=e.object(r.cellToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellToOutputWeights=e.object(r.cellToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputLayerNormWeights=e.object(r.inputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.forgetLayerNormWeights=e.object(r.forgetLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.cellLayerNormWeights=e.object(r.cellLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t.outputLayerNormWeights=e.object(r.outputLayerNormWeights,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.QLstmDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmDescriptor;return t.cifgEnabled=e.bool_(r,4,!0),t.peepholeEnabled=e.bool_(r,6,!1),t.projectionEnabled=e.bool_(r,8,!1),t.layerNormEnabled=e.bool_(r,10,!1),t.cellClip=e.float32_(r,12,0),t.projectionClip=e.float32_(r,14,0),t.inputIntermediateScale=e.float32_(r,16,0),t.forgetIntermediateScale=e.float32_(r,18,0),t.cellIntermediateScale=e.float32_(r,20,0),t.outputIntermediateScale=e.float32_(r,22,0),t.hiddenStateZeroPoint=e.int32_(r,24,0),t.hiddenStateScale=e.float32_(r,26,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmDescriptor;return t.cifgEnabled=e.value(r.cifgEnabled,!0),t.peepholeEnabled=e.value(r.peepholeEnabled,!1),t.projectionEnabled=e.value(r.projectionEnabled,!1),t.layerNormEnabled=e.value(r.layerNormEnabled,!1),t.cellClip=e.value(r.cellClip,0),t.projectionClip=e.value(r.projectionClip,0),t.inputIntermediateScale=e.value(r.inputIntermediateScale,0),t.forgetIntermediateScale=e.value(r.forgetIntermediateScale,0),t.cellIntermediateScale=e.value(r.cellIntermediateScale,0),t.outputIntermediateScale=e.value(r.outputIntermediateScale,0),t.hiddenStateZeroPoint=e.value(r.hiddenStateZeroPoint,0),t.hiddenStateScale=e.value(r.hiddenStateScale,0),t}},$root.armnnSerializer.QLstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QLstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.QLstmDescriptor.decode),t.inputParams=e.table(r,8,$root.armnnSerializer.QLstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QLstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.QLstmDescriptor.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.QLstmInputParams.decodeText),t}},$root.armnnSerializer.QuantizedLstmInputParams=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizedLstmInputParams;return t.inputToInputWeights=e.table(r,4,$root.armnnSerializer.ConstTensor.decode),t.inputToForgetWeights=e.table(r,6,$root.armnnSerializer.ConstTensor.decode),t.inputToCellWeights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.inputToOutputWeights=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t.recurrentToInputWeights=e.table(r,12,$root.armnnSerializer.ConstTensor.decode),t.recurrentToForgetWeights=e.table(r,14,$root.armnnSerializer.ConstTensor.decode),t.recurrentToCellWeights=e.table(r,16,$root.armnnSerializer.ConstTensor.decode),t.recurrentToOutputWeights=e.table(r,18,$root.armnnSerializer.ConstTensor.decode),t.inputGateBias=e.table(r,20,$root.armnnSerializer.ConstTensor.decode),t.forgetGateBias=e.table(r,22,$root.armnnSerializer.ConstTensor.decode),t.cellBias=e.table(r,24,$root.armnnSerializer.ConstTensor.decode),t.outputGateBias=e.table(r,26,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizedLstmInputParams;return t.inputToInputWeights=e.object(r.inputToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToForgetWeights=e.object(r.inputToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToCellWeights=e.object(r.inputToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputToOutputWeights=e.object(r.inputToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToInputWeights=e.object(r.recurrentToInputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToForgetWeights=e.object(r.recurrentToForgetWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToCellWeights=e.object(r.recurrentToCellWeights,$root.armnnSerializer.ConstTensor.decodeText),t.recurrentToOutputWeights=e.object(r.recurrentToOutputWeights,$root.armnnSerializer.ConstTensor.decodeText),t.inputGateBias=e.object(r.inputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.forgetGateBias=e.object(r.forgetGateBias,$root.armnnSerializer.ConstTensor.decodeText),t.cellBias=e.object(r.cellBias,$root.armnnSerializer.ConstTensor.decodeText),t.outputGateBias=e.object(r.outputGateBias,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.QuantizedLstmLayer=class{static decode(e,r){const t=new $root.armnnSerializer.QuantizedLstmLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.inputParams=e.table(r,6,$root.armnnSerializer.QuantizedLstmInputParams.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.QuantizedLstmLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.inputParams=e.object(r.inputParams,$root.armnnSerializer.QuantizedLstmInputParams.decodeText),t}},$root.armnnSerializer.DequantizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.DequantizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.DequantizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.MergeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.MergeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.MergeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.SwitchLayer=class{static decode(e,r){const t=new $root.armnnSerializer.SwitchLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SwitchLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.PreluLayer=class{static decode(e,r){const t=new $root.armnnSerializer.PreluLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.PreluLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.TransposeConvolution2dLayer=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.TransposeConvolution2dDescriptor.decode),t.weights=e.table(r,8,$root.armnnSerializer.ConstTensor.decode),t.biases=e.table(r,10,$root.armnnSerializer.ConstTensor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.TransposeConvolution2dDescriptor.decodeText),t.weights=e.object(r.weights,$root.armnnSerializer.ConstTensor.decodeText),t.biases=e.object(r.biases,$root.armnnSerializer.ConstTensor.decodeText),t}},$root.armnnSerializer.TransposeConvolution2dDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dDescriptor;return t.padLeft=e.uint32_(r,4,0),t.padRight=e.uint32_(r,6,0),t.padTop=e.uint32_(r,8,0),t.padBottom=e.uint32_(r,10,0),t.strideX=e.uint32_(r,12,0),t.strideY=e.uint32_(r,14,0),t.biasEnabled=e.bool_(r,16,!1),t.dataLayout=e.int8_(r,18,1),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeConvolution2dDescriptor;return t.padLeft=e.value(r.padLeft,0),t.padRight=e.value(r.padRight,0),t.padTop=e.value(r.padTop,0),t.padBottom=e.value(r.padBottom,0),t.strideX=e.value(r.strideX,0),t.strideY=e.value(r.strideY,0),t.biasEnabled=e.value(r.biasEnabled,!1),t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t}},$root.armnnSerializer.TransposeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.TransposeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.TransposeDescriptor.decodeText),t}},$root.armnnSerializer.TransposeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.TransposeDescriptor;return t.dimMappings=e.typedArray(r,4,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.TransposeDescriptor;return t.dimMappings=e.typedArray(r.dimMappings,Uint32Array),t}},$root.armnnSerializer.ResizeLayer=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.ResizeDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.ResizeDescriptor.decodeText),t}},$root.armnnSerializer.ResizeDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.ResizeDescriptor;return t.targetHeight=e.uint32_(r,4,0),t.targetWidth=e.uint32_(r,6,0),t.method=e.int8_(r,8,0),t.dataLayout=e.int8_(r,10,0),t.alignCorners=e.bool_(r,12,!1),t.halfPixelCenters=e.bool_(r,14,!1),t}static decodeText(e,r){const t=new $root.armnnSerializer.ResizeDescriptor;return t.targetHeight=e.value(r.targetHeight,0),t.targetWidth=e.value(r.targetWidth,0),t.method=$root.armnnSerializer.ResizeMethod[r.method],t.dataLayout=$root.armnnSerializer.DataLayout[r.dataLayout],t.alignCorners=e.value(r.alignCorners,!1),t.halfPixelCenters=e.value(r.halfPixelCenters,!1),t}},$root.armnnSerializer.StackLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StackLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StackDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StackLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StackDescriptor.decodeText),t}},$root.armnnSerializer.StackDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StackDescriptor;return t.axis=e.uint32_(r,4,0),t.numInputs=e.uint32_(r,6,0),t.inputShape=e.typedArray(r,8,Uint32Array),t}static decodeText(e,r){const t=new $root.armnnSerializer.StackDescriptor;return t.axis=e.value(r.axis,0),t.numInputs=e.value(r.numInputs,0),t.inputShape=e.typedArray(r.inputShape,Uint32Array),t}},$root.armnnSerializer.StandInDescriptor=class{static decode(e,r){const t=new $root.armnnSerializer.StandInDescriptor;return t.numInputs=e.uint32_(r,4,0),t.numOutputs=e.uint32_(r,6,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.StandInDescriptor;return t.numInputs=e.value(r.numInputs,0),t.numOutputs=e.value(r.numOutputs,0),t}},$root.armnnSerializer.StandInLayer=class{static decode(e,r){const t=new $root.armnnSerializer.StandInLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t.descriptor=e.table(r,6,$root.armnnSerializer.StandInDescriptor.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.StandInLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t.descriptor=e.object(r.descriptor,$root.armnnSerializer.StandInDescriptor.decodeText),t}},$root.armnnSerializer.RankLayer=class{static decode(e,r){const t=new $root.armnnSerializer.RankLayer;return t.base=e.table(r,4,$root.armnnSerializer.LayerBase.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.RankLayer;return t.base=e.object(r.base,$root.armnnSerializer.LayerBase.decodeText),t}},$root.armnnSerializer.Layer=class{static decode(e,r,t){switch(t){case 1:return $root.armnnSerializer.ActivationLayer.decode(e,r);case 2:return $root.armnnSerializer.AdditionLayer.decode(e,r);case 3:return $root.armnnSerializer.BatchToSpaceNdLayer.decode(e,r);case 4:return $root.armnnSerializer.BatchNormalizationLayer.decode(e,r);case 5:return $root.armnnSerializer.ConstantLayer.decode(e,r);case 6:return $root.armnnSerializer.Convolution2dLayer.decode(e,r);case 7:return $root.armnnSerializer.DepthwiseConvolution2dLayer.decode(e,r);case 8:return $root.armnnSerializer.FullyConnectedLayer.decode(e,r);case 9:return $root.armnnSerializer.InputLayer.decode(e,r);case 10:return $root.armnnSerializer.MultiplicationLayer.decode(e,r);case 11:return $root.armnnSerializer.OutputLayer.decode(e,r);case 12:return $root.armnnSerializer.PermuteLayer.decode(e,r);case 13:return $root.armnnSerializer.Pooling2dLayer.decode(e,r);case 14:return $root.armnnSerializer.ReshapeLayer.decode(e,r);case 15:return $root.armnnSerializer.SoftmaxLayer.decode(e,r);case 16:return $root.armnnSerializer.SpaceToBatchNdLayer.decode(e,r);case 17:return $root.armnnSerializer.DivisionLayer.decode(e,r);case 18:return $root.armnnSerializer.MinimumLayer.decode(e,r);case 19:return $root.armnnSerializer.EqualLayer.decode(e,r);case 20:return $root.armnnSerializer.MaximumLayer.decode(e,r);case 21:return $root.armnnSerializer.NormalizationLayer.decode(e,r);case 22:return $root.armnnSerializer.PadLayer.decode(e,r);case 23:return $root.armnnSerializer.RsqrtLayer.decode(e,r);case 24:return $root.armnnSerializer.FloorLayer.decode(e,r);case 25:return $root.armnnSerializer.GreaterLayer.decode(e,r);case 26:return $root.armnnSerializer.ResizeBilinearLayer.decode(e,r);case 27:return $root.armnnSerializer.SubtractionLayer.decode(e,r);case 28:return $root.armnnSerializer.StridedSliceLayer.decode(e,r);case 29:return $root.armnnSerializer.GatherLayer.decode(e,r);case 30:return $root.armnnSerializer.MeanLayer.decode(e,r);case 31:return $root.armnnSerializer.MergerLayer.decode(e,r);case 32:return $root.armnnSerializer.L2NormalizationLayer.decode(e,r);case 33:return $root.armnnSerializer.SplitterLayer.decode(e,r);case 34:return $root.armnnSerializer.DetectionPostProcessLayer.decode(e,r);case 35:return $root.armnnSerializer.LstmLayer.decode(e,r);case 36:return $root.armnnSerializer.QuantizedLstmLayer.decode(e,r);case 37:return $root.armnnSerializer.QuantizeLayer.decode(e,r);case 38:return $root.armnnSerializer.DequantizeLayer.decode(e,r);case 39:return $root.armnnSerializer.MergeLayer.decode(e,r);case 40:return $root.armnnSerializer.SwitchLayer.decode(e,r);case 41:return $root.armnnSerializer.ConcatLayer.decode(e,r);case 42:return $root.armnnSerializer.SpaceToDepthLayer.decode(e,r);case 43:return $root.armnnSerializer.PreluLayer.decode(e,r);case 44:return $root.armnnSerializer.TransposeConvolution2dLayer.decode(e,r);case 45:return $root.armnnSerializer.ResizeLayer.decode(e,r);case 46:return $root.armnnSerializer.StackLayer.decode(e,r);case 47:return $root.armnnSerializer.AbsLayer.decode(e,r);case 48:return $root.armnnSerializer.ArgMinMaxLayer.decode(e,r);case 49:return $root.armnnSerializer.SliceLayer.decode(e,r);case 50:return $root.armnnSerializer.DepthToSpaceLayer.decode(e,r);case 51:return $root.armnnSerializer.InstanceNormalizationLayer.decode(e,r);case 52:return $root.armnnSerializer.LogSoftmaxLayer.decode(e,r);case 53:return $root.armnnSerializer.ComparisonLayer.decode(e,r);case 54:return $root.armnnSerializer.StandInLayer.decode(e,r);case 55:return $root.armnnSerializer.ElementwiseUnaryLayer.decode(e,r);case 56:return $root.armnnSerializer.TransposeLayer.decode(e,r);case 57:return $root.armnnSerializer.QLstmLayer.decode(e,r);case 58:return $root.armnnSerializer.FillLayer.decode(e,r);case 59:return $root.armnnSerializer.RankLayer.decode(e,r)}}static decodeText(e,r,t){switch(t){case"ActivationLayer":return $root.armnnSerializer.ActivationLayer.decodeText(e,r);case"AdditionLayer":return $root.armnnSerializer.AdditionLayer.decodeText(e,r);case"BatchToSpaceNdLayer":return $root.armnnSerializer.BatchToSpaceNdLayer.decodeText(e,r);case"BatchNormalizationLayer":return $root.armnnSerializer.BatchNormalizationLayer.decodeText(e,r);case"ConstantLayer":return $root.armnnSerializer.ConstantLayer.decodeText(e,r);case"Convolution2dLayer":return $root.armnnSerializer.Convolution2dLayer.decodeText(e,r);case"DepthwiseConvolution2dLayer":return $root.armnnSerializer.DepthwiseConvolution2dLayer.decodeText(e,r);case"FullyConnectedLayer":return $root.armnnSerializer.FullyConnectedLayer.decodeText(e,r);case"InputLayer":return $root.armnnSerializer.InputLayer.decodeText(e,r);case"MultiplicationLayer":return $root.armnnSerializer.MultiplicationLayer.decodeText(e,r);case"OutputLayer":return $root.armnnSerializer.OutputLayer.decodeText(e,r);case"PermuteLayer":return $root.armnnSerializer.PermuteLayer.decodeText(e,r);case"Pooling2dLayer":return $root.armnnSerializer.Pooling2dLayer.decodeText(e,r);case"ReshapeLayer":return $root.armnnSerializer.ReshapeLayer.decodeText(e,r);case"SoftmaxLayer":return $root.armnnSerializer.SoftmaxLayer.decodeText(e,r);case"SpaceToBatchNdLayer":return $root.armnnSerializer.SpaceToBatchNdLayer.decodeText(e,r);case"DivisionLayer":return $root.armnnSerializer.DivisionLayer.decodeText(e,r);case"MinimumLayer":return $root.armnnSerializer.MinimumLayer.decodeText(e,r);case"EqualLayer":return $root.armnnSerializer.EqualLayer.decodeText(e,r);case"MaximumLayer":return $root.armnnSerializer.MaximumLayer.decodeText(e,r);case"NormalizationLayer":return $root.armnnSerializer.NormalizationLayer.decodeText(e,r);case"PadLayer":return $root.armnnSerializer.PadLayer.decodeText(e,r);case"RsqrtLayer":return $root.armnnSerializer.RsqrtLayer.decodeText(e,r);case"FloorLayer":return $root.armnnSerializer.FloorLayer.decodeText(e,r);case"GreaterLayer":return $root.armnnSerializer.GreaterLayer.decodeText(e,r);case"ResizeBilinearLayer":return $root.armnnSerializer.ResizeBilinearLayer.decodeText(e,r);case"SubtractionLayer":return $root.armnnSerializer.SubtractionLayer.decodeText(e,r);case"StridedSliceLayer":return $root.armnnSerializer.StridedSliceLayer.decodeText(e,r);case"GatherLayer":return $root.armnnSerializer.GatherLayer.decodeText(e,r);case"MeanLayer":return $root.armnnSerializer.MeanLayer.decodeText(e,r);case"MergerLayer":return $root.armnnSerializer.MergerLayer.decodeText(e,r);case"L2NormalizationLayer":return $root.armnnSerializer.L2NormalizationLayer.decodeText(e,r);case"SplitterLayer":return $root.armnnSerializer.SplitterLayer.decodeText(e,r);case"DetectionPostProcessLayer":return $root.armnnSerializer.DetectionPostProcessLayer.decodeText(e,r);case"LstmLayer":return $root.armnnSerializer.LstmLayer.decodeText(e,r);case"QuantizedLstmLayer":return $root.armnnSerializer.QuantizedLstmLayer.decodeText(e,r);case"QuantizeLayer":return $root.armnnSerializer.QuantizeLayer.decodeText(e,r);case"DequantizeLayer":return $root.armnnSerializer.DequantizeLayer.decodeText(e,r);case"MergeLayer":return $root.armnnSerializer.MergeLayer.decodeText(e,r);case"SwitchLayer":return $root.armnnSerializer.SwitchLayer.decodeText(e,r);case"ConcatLayer":return $root.armnnSerializer.ConcatLayer.decodeText(e,r);case"SpaceToDepthLayer":return $root.armnnSerializer.SpaceToDepthLayer.decodeText(e,r);case"PreluLayer":return $root.armnnSerializer.PreluLayer.decodeText(e,r);case"TransposeConvolution2dLayer":return $root.armnnSerializer.TransposeConvolution2dLayer.decodeText(e,r);case"ResizeLayer":return $root.armnnSerializer.ResizeLayer.decodeText(e,r);case"StackLayer":return $root.armnnSerializer.StackLayer.decodeText(e,r);case"AbsLayer":return $root.armnnSerializer.AbsLayer.decodeText(e,r);case"ArgMinMaxLayer":return $root.armnnSerializer.ArgMinMaxLayer.decodeText(e,r);case"SliceLayer":return $root.armnnSerializer.SliceLayer.decodeText(e,r);case"DepthToSpaceLayer":return $root.armnnSerializer.DepthToSpaceLayer.decodeText(e,r);case"InstanceNormalizationLayer":return $root.armnnSerializer.InstanceNormalizationLayer.decodeText(e,r);case"LogSoftmaxLayer":return $root.armnnSerializer.LogSoftmaxLayer.decodeText(e,r);case"ComparisonLayer":return $root.armnnSerializer.ComparisonLayer.decodeText(e,r);case"StandInLayer":return $root.armnnSerializer.StandInLayer.decodeText(e,r);case"ElementwiseUnaryLayer":return $root.armnnSerializer.ElementwiseUnaryLayer.decodeText(e,r);case"TransposeLayer":return $root.armnnSerializer.TransposeLayer.decodeText(e,r);case"QLstmLayer":return $root.armnnSerializer.QLstmLayer.decodeText(e,r);case"FillLayer":return $root.armnnSerializer.FillLayer.decodeText(e,r);case"RankLayer":return $root.armnnSerializer.RankLayer.decodeText(e,r)}}},$root.armnnSerializer.AnyLayer=class{static decode(e,r){const t=new $root.armnnSerializer.AnyLayer;return t.layer=e.union(r,4,$root.armnnSerializer.Layer.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.AnyLayer;return t.layer=$root.armnnSerializer.Layer.decodeText(e,r.layer,r.layer_type),t}},$root.armnnSerializer.FeatureCompatibilityVersions=class{static decode(e,r){const t=new $root.armnnSerializer.FeatureCompatibilityVersions;return t.bindingIdsScheme=e.uint32_(r,4,0),t}static decodeText(e,r){const t=new $root.armnnSerializer.FeatureCompatibilityVersions;return t.bindingIdsScheme=e.value(r.bindingIdsScheme,0),t}},$root.armnnSerializer.SerializedGraph=class{static identifier(e){return e.identifier("ARMN")}static create(e){return $root.armnnSerializer.SerializedGraph.decode(e,e.root)}static createText(e){return $root.armnnSerializer.SerializedGraph.decodeText(e,e.root)}static decode(e,r){const t=new $root.armnnSerializer.SerializedGraph;return t.layers=e.tableArray(r,4,$root.armnnSerializer.AnyLayer.decode),t.inputIds=e.typedArray(r,6,Int32Array),t.outputIds=e.typedArray(r,8,Int32Array),t.featureVersions=e.table(r,10,$root.armnnSerializer.FeatureCompatibilityVersions.decode),t}static decodeText(e,r){const t=new $root.armnnSerializer.SerializedGraph;return t.layers=e.objectArray(r.layers,$root.armnnSerializer.AnyLayer.decodeText),t.inputIds=e.typedArray(r.inputIds,Int32Array),t.outputIds=e.typedArray(r.outputIds,Int32Array),t.featureVersions=e.object(r.featureVersions,$root.armnnSerializer.FeatureCompatibilityVersions.decodeText),t}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn.js new file mode 100644 index 0000000000000000000000000000000000000000..d86f5dda02bb65f0269e1f03eeedc04b53fd6c08 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/armnn.js @@ -0,0 +1 @@ +var armnn=armnn||{},base=base||require("./base"),flatbuffers=flatbuffers||require("./flatbuffers"),long=long||{Long:require("long")};armnn.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("armnn"==e)return!0;if("json"===e){const e=t.text;if(-1!==e.indexOf('"layers"',0)&&-1!==e.indexOf('"layer_type"',0))return!0}return!1}open(t,e){return e.require("./armnn-schema").then((n=>{armnn.schema=flatbuffers.get("armnn").armnnSerializer;const a=t.identifier;let r=null;try{switch(a.split(".").pop().toLowerCase()){case"armnn":{const e=new flatbuffers.Reader(t.buffer);r=armnn.schema.SerializedGraph.create(e);break}case"json":{const e=new flatbuffers.TextReader(t.text);r=armnn.schema.SerializedGraph.createText(e);break}}}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new armnn.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}return armnn.Metadata.open(e).then((t=>{try{return new armnn.Model(t,r)}catch(t){const e=t&&t.message?t.message:t.toString();throw new new armnn.Error(e.replace(/\.$/,"")+" in '"+a+"'.")}}))}))}},armnn.Model=class{constructor(t,e){this._graphs=[],this._graphs.push(new armnn.Graph(t,e))}get format(){return"Arm NN"}get description(){return""}get graphs(){return this._graphs}},armnn.Graph=class{constructor(t,e){this._name="",this._nodes=[],this._inputs=[],this._outputs=[];const n={};for(let t=0;tt.limit)return r.push("..."),r;switch(t.dataType){case"float16":r.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":r.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"quint8":r.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"qint16":r.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++;break;case"int32":r.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"boolean":r.push(t.data.getInt8(t.index)),t.index+=1,t.count++}}else for(let n=0;nt.limit)return r.push("..."),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}},armnn.TensorType=class{constructor(t){const e=t.dataType;switch(e){case 0:this._dataType="float16";break;case 1:this._dataType="float32";break;case 2:this._dataType="quint8";break;case 3:this._dataType="int32";break;case 4:this._dataType="boolean";break;case 5:this._dataType="qint16";break;case 6:this._dataType="quint8";break;case 7:this._dataType="qint16";break;default:throw new armnn.Error("Unknown data type '"+JSON.stringify(e)+"'.")}this._shape=new armnn.TensorShape(t.dimensions)}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},armnn.TensorShape=class{constructor(t){this._dimensions=Array.from(t)}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},armnn.Metadata=class{static open(t){return armnn.Metadata._metadata?Promise.resolve(armnn.Metadata._metadata):t.request(null,"armnn-metadata.json","utf-8").then((t=>(armnn.Metadata._metadata=new armnn.Metadata(t),armnn.Metadata._metadata))).catch((()=>(armnn.Metadata._metadata=new armnn.Metadata(null),armnn.Metadata._metadata)))}constructor(t){if(this._map={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]}attribute(t,e){const n=this.type(t);if(n){let t=n.attributeMap;if(!t){if(t={},n.attributes)for(const e of n.attributes)t[e.name]=e;n.attributeMap=t}const a=t[e];if(a)return a}return null}},armnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading Arm NN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=armnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/barracuda.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/barracuda.js new file mode 100644 index 0000000000000000000000000000000000000000..2b6b6208aae5693c8f9dc719cb34a3e617797919 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/barracuda.js @@ -0,0 +1 @@ +var barracuda=barracuda||{},base=base||require("./base"),long=long||{Long:require("long")};barracuda.ModelFactory=class{match(t){if("nn"===t.identifier.split(".").pop().toLowerCase()){const e=t.buffer;if(e.length>12&&e[0]<=16&&e.subarray(1,8).every((t=>0==t)))return!0}return!1}open(t){return barracuda.Metadata.open().then((e=>{try{const s=new barracuda.NNModel(t.buffer);return new barracuda.Model(e,s)}catch(e){const s=t.identifier.toLowerCase(),r=e&&e.message?e.message:e.toString();throw new barracuda.Error(r.replace(/\.$/,"")+" in '"+s+"'.")}}))}},barracuda.Model=class{constructor(t,e){this._version=e.version.toString(),this._graphs=[new barracuda.Graph(t,e)]}get format(){return"Barracuda v"+this._version}get graphs(){return this._graphs}},barracuda.Graph=class{constructor(t,e){this._inputs=[],this._outputs=[],this._nodes=[];for(const t of e.inputs)this._inputs.push(new barracuda.Parameter(t.name,[new barracuda.Argument(t.name,new barracuda.TensorType(4,new barracuda.TensorShape(t.shape)))]));for(const t of e.outputs)this._outputs.push(new barracuda.Parameter(t,[new barracuda.Argument(t)]));const s=[],r=new Map;for(const t of e.layers)if(255!==t.type||t.inputs.length>0)s.push(t);else for(const e of t.tensors)r.set(e.name,new barracuda.Tensor(e));for(const e of s)this._nodes.push(new barracuda.Node(t,e,r))}get name(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},barracuda.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},barracuda.Argument=class{constructor(t,e,s){this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},barracuda.Node=class{constructor(t,e,s){this._name=e.name||"",this._metadata=t.type(e.type)||{name:e.type.toString()},this._type=this._metadata.name,this._inputs=[],this._outputs=[],this._attributes=[];const r=Array.prototype.slice.call(this._metadata.inputs||["input"]);if(this._metadata.inputs&&1===this._metadata.inputs.length&&"inputs"===this._metadata.inputs[0])this._inputs.push(new barracuda.Parameter("inputs",e.inputs.map((t=>{const e=s.has(t)?s.get(t):null;return new barracuda.Argument(t,e?e.type:null,e)}))));else if(e.inputs)for(let t=0;t0?r.shift():t.toString(),[new barracuda.Argument(a,i?i.type:null,i)]))}if(e.tensors)for(let t=0;t0?r.shift():t.toString(),[new barracuda.Argument(s.name,a.type,a)]))}if(void 0!==e.inputs&&this._outputs.push(new barracuda.Parameter("output",[new barracuda.Argument(this._name)])),!barracuda.Activation[e.activation])throw new barracuda.Error("Unknown activation '"+e.activation+"'.");"Activation"===this._type?this._type=barracuda.Activation[e.activation]:0!==e.activation&&(this._chain=[new barracuda.Node(t,{type:50,activation:e.activation},s)]);const a=(t,e,s,r)=>{void 0!==s&&(Array.isArray(r)&&Array.isArray(s)&&s.length==r.length&&s.every(((t,e)=>t===r[e]))||"function"==typeof r&&r(s)||r!==s&&this._attributes.push(new barracuda.Attribute(t,e,s)))};a("strides","int32[]",e.strides,[]),a("pads","int32[]",e.pads,(t=>Array.isArray(t)&&(t.every((t=>0===t))||t.every((t=>-1===t))))),a("size","int32[]",e.pool_size,[]),a("alpha","float32",e.alpha,1),a("beta","float32",e.beta,0),a("axis","int32",e.axis,-1)}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}},barracuda.Attribute=class{constructor(t,e,s){this._name=t,this._type=e,this._value=s}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return!0}},barracuda.Tensor=class{constructor(t){this._type=new barracuda.TensorType(t.itemsize,new barracuda.TensorShape(t.shape)),this._data=t.data}get kind(){return""}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape||this._type.shape.dimensions&&0==this._type.shape.dimensions.length)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const s=0==t.shape.length?[1]:t.shape,r=[],a=s[e];if(e==s.length-1)for(let e=0;et.limit)return r.push("..."),r;switch(this._type.dataType){case"float32":r.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++}}else for(let s=0;st.limit)return r.push("..."),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}},barracuda.TensorType=class{constructor(t,e){switch(t){case 4:this._dataType="float32";break;default:throw new barracuda.Error("Unsupported data type size '"+t.toString()+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},barracuda.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},barracuda.NNModel=class{constructor(t){const e=new barracuda.BinaryReader(t);this._version=e.int32(),e.int32(),this._inputs=[];const s=e.int32();for(let t=0;tthis._buffer.length)throw new barracuda.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}bytes(t,e){const s=this._position+t,r=s+e;if(r>this._buffer.length)throw new barracuda.Error("Expected "+(r-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.");return this._buffer.slice(s,r)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int32s(){const t=[],e=this.int32();for(let s=0;s>>3){case 1:e.name=t.string();break;case 2:e.subModules.push($root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32()));break;case 3:e.weight=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 4:e.bias=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 5:e.preModules.push(t.string());break;case 6:e.nextModules.push(t.string());break;case 7:e.moduleType=t.string();break;case 8:t.pair(e.attr,(()=>t.string()),(()=>$root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32())));break;case 9:e.version=t.string();break;case 10:e.train=t.bool();break;case 11:e.namePostfix=t.string();break;case 12:e.id=t.int32();break;case 13:e.inputShape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;case 14:e.outputShape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;case 15:e.hasParameters=t.bool();break;case 16:e.parameters.push($root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32()));break;case 17:e.isMklInt8Enabled=t.bool();break;case 18:e.inputDimMasks=t.int32();break;case 19:e.inputScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;case 20:e.outputDimMasks=t.int32();break;case 21:e.outputScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;case 22:e.weightDimMasks=t.int32();break;case 23:e.weightScales.push($root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.name="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.weight=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.bias=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.moduleType="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.version="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.train=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.namePostfix="",$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.inputShape=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.outputShape=null,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.hasParameters=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.isMklInt8Enabled=!1,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.inputDimMasks=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.outputDimMasks=0,$root.com.intel.analytics.bigdl.serialization.BigDLModule.prototype.weightDimMasks=0,$root.com.intel.analytics.bigdl.serialization.VarFormat={EMPTY_FORMAT:0,DEFAULT:1,ONE_D:2,IN_OUT:3,OUT_IN:4,IN_OUT_KW_KH:5,OUT_IN_KW_KH:6,GP_OUT_IN_KW_KH:7,GP_IN_OUT_KW_KH:8,OUT_IN_KT_KH_KW:9},$root.com.intel.analytics.bigdl.serialization.InitMethodType={EMPTY_INITIALIZATION:0,RANDOM_UNIFORM:1,RANDOM_UNIFORM_PARAM:2,RANDOM_NORMAL:3,ZEROS:4,ONES:5,CONST:6,XAVIER:7,BILINEARFILLER:8},$root.com.intel.analytics.bigdl.serialization.RegularizerType={L1L2Regularizer:0,L1Regularizer:1,L2Regularizer:2},$root.com.intel.analytics.bigdl.serialization.InputDataFormat={NCHW:0,NHWC:1},$root.com.intel.analytics.bigdl.serialization.TensorType={DENSE:0,QUANT:1},$root.com.intel.analytics.bigdl.serialization.InitMethod=class{constructor(){this.data=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.InitMethod,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.methodType=t.int32();break;case 2:e.data=t.doubles(e.data,a);break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.InitMethod.prototype.methodType=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor=class{constructor(){this.size=[],this.stride=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.BigDLTensor,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.datatype=t.int32();break;case 2:e.size=t.array(e.size,(()=>t.int32()),a);break;case 3:e.stride=t.array(e.stride,(()=>t.int32()),a);break;case 4:e.offset=t.int32();break;case 5:e.dimension=t.int32();break;case 6:e.nElements=t.int32();break;case 7:e.isScalar=t.bool();break;case 8:e.storage=$root.com.intel.analytics.bigdl.serialization.TensorStorage.decode(t,t.uint32());break;case 9:e.id=t.int32();break;case 10:e.tensorType=t.int32();break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.offset=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.dimension=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.nElements=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.isScalar=!1,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.storage=null,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.BigDLTensor.prototype.tensorType=0,$root.com.intel.analytics.bigdl.serialization.TensorStorage=class{constructor(){this.float_data=[],this.double_data=[],this.bool_data=[],this.string_data=[],this.int_data=[],this.long_data=[],this.bytes_data=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.TensorStorage,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.datatype=t.int32();break;case 2:e.float_data=t.floats(e.float_data,a);break;case 3:e.double_data=t.doubles(e.double_data,a);break;case 4:e.bool_data=t.array(e.bool_data,(()=>t.bool()),a);break;case 5:e.string_data.push(t.string());break;case 6:e.int_data=t.array(e.int_data,(()=>t.int32()),a);break;case 7:e.long_data=t.array(e.long_data,(()=>t.int64()),a);break;case 8:e.bytes_data.push(t.bytes());break;case 9:e.id=t.int32();break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.TensorStorage.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.TensorStorage.prototype.id=0,$root.com.intel.analytics.bigdl.serialization.Regularizer=class{constructor(){this.regularData=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.Regularizer,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.regularizerType=t.int32();break;case 2:e.regularData=t.doubles(e.regularData,a);break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.Regularizer.prototype.regularizerType=0,$root.com.intel.analytics.bigdl.serialization.DataType={INT32:0,INT64:1,FLOAT:2,DOUBLE:3,STRING:4,BOOL:5,CHAR:6,SHORT:7,BYTES:8,REGULARIZER:9,TENSOR:10,VARIABLE_FORMAT:11,INITMETHOD:12,MODULE:13,NAME_ATTR_LIST:14,ARRAY_VALUE:15,DATA_FORMAT:16,CUSTOM:17,SHAPE:18},$root.com.intel.analytics.bigdl.serialization.AttrValue=class{constructor(){}get value(){return $root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet=$root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet||new Set(["int32Value","int64Value","floatValue","doubleValue","stringValue","boolValue","regularizerValue","tensorValue","variableFormatValue","initMethodValue","bigDLModuleValue","nameAttrListValue","arrayValue","dataFormatValue","customValue","shape"]),Object.keys(this).find((t=>$root.com.intel.analytics.bigdl.serialization.AttrValue.valueSet.has(t)&&null!=this[t]))}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.AttrValue,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.dataType=t.int32();break;case 2:e.subType=t.string();break;case 3:e.int32Value=t.int32();break;case 4:e.int64Value=t.int64();break;case 5:e.floatValue=t.float();break;case 6:e.doubleValue=t.double();break;case 7:e.stringValue=t.string();break;case 8:e.boolValue=t.bool();break;case 9:e.regularizerValue=$root.com.intel.analytics.bigdl.serialization.Regularizer.decode(t,t.uint32());break;case 10:e.tensorValue=$root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32());break;case 11:e.variableFormatValue=t.int32();break;case 12:e.initMethodValue=$root.com.intel.analytics.bigdl.serialization.InitMethod.decode(t,t.uint32());break;case 13:e.bigDLModuleValue=$root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32());break;case 14:e.nameAttrListValue=$root.com.intel.analytics.bigdl.serialization.NameAttrList.decode(t,t.uint32());break;case 15:e.arrayValue=$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.decode(t,t.uint32());break;case 16:e.dataFormatValue=t.int32();break;case 17:e.customValue=$root.google.protobuf.Any.decode(t,t.uint32());break;case 18:e.shape=$root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32());break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.AttrValue.prototype.dataType=0,$root.com.intel.analytics.bigdl.serialization.AttrValue.prototype.subType="",$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue=class{constructor(){this.i32=[],this.i64=[],this.flt=[],this.dbl=[],this.str=[],this.boolean=[],this.Regularizer=[],this.tensor=[],this.variableFormat=[],this.initMethod=[],this.bigDLModule=[],this.nameAttrList=[],this.dataFormat=[],this.custom=[],this.shape=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.size=t.int32();break;case 2:e.datatype=t.int32();break;case 3:e.i32=t.array(e.i32,(()=>t.int32()),a);break;case 4:e.i64=t.array(e.i64,(()=>t.int64()),a);break;case 5:e.flt=t.floats(e.flt,a);break;case 6:e.dbl=t.doubles(e.dbl,a);break;case 7:e.str.push(t.string());break;case 8:e.boolean=t.array(e.boolean,(()=>t.bool()),a);break;case 9:e.Regularizer.push($root.com.intel.analytics.bigdl.serialization.Regularizer.decode(t,t.uint32()));break;case 10:e.tensor.push($root.com.intel.analytics.bigdl.serialization.BigDLTensor.decode(t,t.uint32()));break;case 11:e.variableFormat=t.array(e.variableFormat,(()=>t.int32()),a);break;case 12:e.initMethod.push($root.com.intel.analytics.bigdl.serialization.InitMethod.decode(t,t.uint32()));break;case 13:e.bigDLModule.push($root.com.intel.analytics.bigdl.serialization.BigDLModule.decode(t,t.uint32()));break;case 14:e.nameAttrList.push($root.com.intel.analytics.bigdl.serialization.NameAttrList.decode(t,t.uint32()));break;case 15:e.dataFormat=t.array(e.dataFormat,(()=>t.int32()),a);break;case 16:e.custom.push($root.google.protobuf.Any.decode(t,t.uint32()));break;case 17:e.shape.push($root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.prototype.size=0,$root.com.intel.analytics.bigdl.serialization.AttrValue.ArrayValue.prototype.datatype=0,$root.com.intel.analytics.bigdl.serialization.NameAttrList=class{constructor(){this.attr={}}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.NameAttrList,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.name=t.string();break;case 2:t.pair(e.attr,(()=>t.string()),(()=>$root.com.intel.analytics.bigdl.serialization.AttrValue.decode(t,t.uint32())));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.NameAttrList.prototype.name="",$root.com.intel.analytics.bigdl.serialization.Shape=class{constructor(){this.shapeValue=[],this.shape=[]}static decode(t,a){const e=new $root.com.intel.analytics.bigdl.serialization.Shape,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.shapeType=t.int32();break;case 2:e.ssize=t.int32();break;case 3:e.shapeValue=t.array(e.shapeValue,(()=>t.int32()),a);break;case 4:e.shape.push($root.com.intel.analytics.bigdl.serialization.Shape.decode(t,t.uint32()));break;default:t.skipType(7&a)}}return e}},$root.com.intel.analytics.bigdl.serialization.Shape.prototype.shapeType=0,$root.com.intel.analytics.bigdl.serialization.Shape.prototype.ssize=0,$root.com.intel.analytics.bigdl.serialization.Shape.ShapeType={SINGLE:0,MULTI:1},$root.google={},$root.google.protobuf={},$root.google.protobuf.Any=class{constructor(){}static decode(t,a){const e=new $root.google.protobuf.Any,i=t.next(a);for(;t.end(i);){const a=t.uint32();switch(a>>>3){case 1:e.type_url=t.string();break;case 2:e.value=t.bytes();break;default:t.skipType(7&a)}}return e}},$root.google.protobuf.Any.prototype.type_url="",$root.google.protobuf.Any.prototype.value=new Uint8Array([]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bigdl.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bigdl.js new file mode 100644 index 0000000000000000000000000000000000000000..7387dee91d178e118a44b1a55c097f4adce7a4b7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bigdl.js @@ -0,0 +1 @@ +var bigdl=bigdl||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");bigdl.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"==e||"bigdl"==e){const e=t.tags("pb");if(e.has(2)&&e.has(7)&&e.has(8)&&e.has(9)&&e.has(10)&&e.has(11)&&e.has(12))return!0}}open(t,e){return e.require("./bigdl-proto").then((()=>bigdl.Metadata.open(e).then((a=>{const i=t.identifier;try{bigdl.proto=protobuf.get("bigdl").com.intel.analytics.bigdl.serialization;const e=protobuf.Reader.create(t.buffer),i=bigdl.proto.BigDLModule.decode(e);return new bigdl.Model(a,i)}catch(t){e.exception(t,!1);const a=t&&t.message?t.message:t.toString();throw new bigdl.Error(a.replace(/\.$/,"")+" in '"+i+"'.")}}))))}},bigdl.Model=class{constructor(t,e){this._version=e&&e.version?e.version:"",this._graphs=[new bigdl.Graph(t,e)]}get format(){return"BigDL"+(this._version?" v"+this._version:"")}get graphs(){return this._graphs}},bigdl.Graph=class{constructor(t,e){this._type=e.moduleType,this._inputs=[],this._outputs=[],this._nodes=[],this._loadModule(t,"",e)}_loadModule(t,e,a){switch(a.moduleType){case"com.intel.analytics.bigdl.nn.StaticGraph":this._loadStaticGraph(t,e,a);break;case"com.intel.analytics.bigdl.nn.Sequential":this._loadSequential(t,e,a);break;case"com.intel.analytics.bigdl.nn.Input":this._inputs.push(new bigdl.Parameter(a.name,[new bigdl.Argument(a.name)]));break;default:this._nodes.push(new bigdl.Node(t,e,a))}}_loadSequential(t,e,a){e=e.length>0?e+"."+a.namePostfix:a.namePostfix;for(const i of a.subModules)this._loadModule(t,e,i)}_loadStaticGraph(t,e,a){e=e.length>0?e+"."+a.namePostfix:a.namePostfix;for(const i of a.subModules)this._loadModule(t,e,i)}get groups(){return this._groups||!1}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},bigdl.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},bigdl.Argument=class{constructor(t,e,a){if("string"!=typeof t)throw new bigdl.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=a||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},bigdl.Node=class{constructor(t,e,a){this._metadata=t,this._group=e,this._type=a.moduleType.split(".").pop(),this._name=a.name,this._attributes=[],this._inputs=[],this._outputs=[],this._inputs.push(new bigdl.Parameter("input",a.preModules.map((t=>new bigdl.Argument(t,null,null)))));const i=t.type(this.type),r=i&&i.inputs?i.inputs.slice():[];if(r.shift(),a.weight&&(r.shift(),this._inputs.push(new bigdl.Parameter("weight",[new bigdl.Argument("",null,new bigdl.Tensor(a.weight))]))),a.bias&&(r.shift(),this._inputs.push(new bigdl.Parameter("bias",[new bigdl.Argument("",null,new bigdl.Tensor(a.bias))]))),a.parameters&&a.parameters.length>0)for(const t of a.parameters){const e=r.shift(),a=e?e.name:this._inputs.length.toString();this._inputs.push(new bigdl.Parameter(a,[new bigdl.Argument("",null,new bigdl.Tensor(t))]))}for(const e of Object.keys(a.attr)){const i=a.attr[e];"module_numerics"!==e&&"module_tags"!==e&&(i.dataType!==bigdl.proto.DataType.TENSOR?i.dataType===bigdl.proto.DataType.REGULARIZER&&void 0===i.value||(i.dataType!==bigdl.proto.DataType.ARRAY_VALUE||i.arrayValue.datatype!==bigdl.proto.DataType.TENSOR?this._attributes.push(new bigdl.Attribute(t.attribute(this._type,e),e,i)):this._inputs.push(new bigdl.Parameter(e,i.arrayValue.tensor.map((t=>new bigdl.Argument("",null,new bigdl.Tensor(t))))))):i.value&&this._inputs.push(new bigdl.Parameter(e,[new bigdl.Argument("",null,new bigdl.Tensor(i.tensorValue))])))}const s=this._name||this._type+a.namePostfix;this._outputs.push(new bigdl.Parameter("output",[new bigdl.Argument(s,null,null)]))}get group(){return this._group}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},bigdl.Attribute=class{constructor(t,e,a){switch(this._name=e,a.dataType){case bigdl.proto.DataType.INT32:this._type="int32",this._value=a.int32Value;break;case bigdl.proto.DataType.FLOAT:this._type="float32",this._value=a.floatValue;break;case bigdl.proto.DataType.DOUBLE:this._type="float64",this._value=a.doubleValue;break;case bigdl.proto.DataType.BOOL:this._type="boolean",this._value=a.boolValue;break;case bigdl.proto.DataType.REGULARIZER:this._value=a.value;break;case bigdl.proto.DataType.MODULE:this._value=a.bigDLModule;break;case bigdl.proto.DataType.NAME_ATTR_LIST:this._value=a.nameAttrListValue;break;case bigdl.proto.DataType.ARRAY_VALUE:switch(a.arrayValue.datatype){case bigdl.proto.DataType.INT32:this._type="int32[]",this._value=a.arrayValue.i32;break;case bigdl.proto.DataType.FLOAT:this._type="float32[]",this._value=a.arrayValue.flt;break;case bigdl.proto.DataType.STRING:this._type="string[]",this._value=a.arrayValue.str;break;case bigdl.proto.DataType.TENSOR:this._type="tensor[]",this._value=a.arrayValue.tensor;break;default:throw new bigdl.Error("Unsupported attribute array data type '"+a.arrayValue.datatype+"'.")}break;case bigdl.proto.DataType.DATA_FORMAT:switch(this._dataType="InputDataFormat",a.dataFormatValue){case 0:this._value="NCHW";break;case 1:this._value="NHWC"}break;default:throw new bigdl.Error("Unsupported attribute data type '"+a.dataType+"'.")}}get type(){return""}get name(){return this._name}get value(){return this._value}get visible(){return!0}},bigdl.Tensor=class{constructor(t){this._type=new bigdl.TensorType(t.datatype,new bigdl.TensorShape(t.size))}get kind(){return"Parameter"}get type(){return this._type}get state(){return"Not supported."}get value(){return null}toString(){return""}},bigdl.TensorType=class{constructor(t,e){switch(t){case bigdl.proto.DataType.FLOAT:this._dataType="float32";break;case bigdl.proto.DataType.DOUBLE:this._dataType="float64";break;default:throw new bigdl.Error("Unsupported tensor type '"+t+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},bigdl.TensorShape=class{constructor(t){this._dimensions=t.map((t=>t&&long.Long.isLong(t)?t.toNumber():t))}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},bigdl.Metadata=class{static open(t){return bigdl.Metadata._metadata?Promise.resolve(bigdl.Metadata._metadata):t.request(null,"bigdl-metadata.json","utf-8").then((t=>(bigdl.Metadata._metadata=new bigdl.Metadata(t),bigdl.Metadata._metadata))).catch((()=>(bigdl.Metadata._metadata=new bigdl.Metadata(null),bigdl.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},bigdl.Error=class extends Error{constructor(t){super(t),this.name="Error loading BigDL model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=bigdl.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bson.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bson.js new file mode 100644 index 0000000000000000000000000000000000000000..d17823cebee6fc4de98507e35bd55779f0d8720a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/bson.js @@ -0,0 +1 @@ +var bson={},long=long||{Long:require("long")};bson.Reader=class{constructor(t){this._asciiDecoder=new TextDecoder("ascii"),this._utf8Decoder=new TextDecoder("utf-8"),this._buffer=t,this._position=0,this._view=new DataView(t.buffer,t.byteOffset,t.byteLength)}read(){return this.document()}document(t){const i=this._position,e=this.int32();if(e<5||i+e>this._buffer.length||0!=this._buffer[i+e-1])throw new bson.Reader("Invalid BSON size.");const s=t?[]:{};let n=0;for(;;){const i=this.byte();if(0==i)break;const e=this.cstring();let o=null;switch(i){case 1:o=this.double();break;case 2:o=this.string();break;case 3:o=this.document(!1);break;case 4:o=this.document(!0);break;case 5:o=this.binary();break;case 8:o=this.boolean();break;case 10:o=null;break;case 16:o=this.int32();break;case 17:o=this.uint64();break;case 18:o=this.int64();break;default:throw new bson.Error("Unknown value type '"+i+"'.")}if(t){if(n!==parseInt(e,10))throw new bson.Error("Invalid array index '"+e+"'.");s.push(o),n++}else s[e]=o}return s}cstring(){const t=this._buffer.indexOf(0,this._position),i=this._asciiDecoder.decode(this._buffer.subarray(this._position,t));return this._position=t+1,i}string(){const t=this.int32()+this._position-1,i=this._utf8Decoder.decode(this._buffer.subarray(this._position,t));if(this._position=t,"0x00"!=this.byte())throw new bson.Error("String missing terminal 0.");return i}binary(){const t=this.int32(),i=this.byte(),e=this._buffer.subarray(this._position,this._position+t);switch(this._position+=t,i){case 0:return e;default:throw new bson.Error("Unknown binary subtype '"+i+"'.")}}boolean(){const t=this.byte();switch(t){case 0:return!1;case 1:return!0;default:throw new bson.Error("Invalid boolean value '"+t+"'.")}}byte(){return this._buffer[this._position++]}int32(){const t=this._view.getInt32(this._position,!0);return this._position+=4,t}int64(){const t=this._view.getUint32(this._position,!0),i=this._view.getUint32(this._position+4,!0);return this._position+=8,new long.Long(t,i,!1).toNumber()}uint64(){const t=this._view.getUint32(this._position,!0),i=this._view.getUint32(this._position+4,!0);return this._position+=8,new long.Long(t,i,!0).toNumber()}},bson.Error=class extends Error{constructor(t){super(t),this.name="BSON Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Reader=bson.Reader); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..723d9f6529edec34f229f8386d9602fae4c4db00 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false},{"name":"pad","default":[0]},{"name":"kernel_size","default":[]},{"name":"stride","default":[1]},{"name":"dilation","default":[]},{"name":"group","default":1}]}},{"name":"Deconvolution","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false},{"name":"pad","default":[]},{"name":"kernel_size","default":[]},{"name":"stride","default":[]},{"name":"dilation","default":[]}]}},{"name":"DepthwiseConvolution","schema":{"category":"Layer","attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}],"inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"ConvolutionDepthwise","schema":{"category":"Layer","attributes":[{"name":"pad","default":[0]},{"name":"kernel_size","default":[]},{"name":"stride","default":[1]},{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}],"inputs":[{"name":"input"},{"name":"filter"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"InnerProduct","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"bias_term","visible":false},{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}]}},{"name":"Scale","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"}],"outputs":[{"name":"output"}],"attributes":[{"name":"filler","visible":false},{"name":"bias_term","visible":false},{"name":"bias_filler","visible":false}]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[{"name":"dropout_ratio","default":0.5}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Flatten","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LRN","schema":{"category":"Normalization","attributes":[{"name":"local_size","type":"uint32","default":5},{"name":"alpha","type":"float32","default":0.0001},{"name":"beta","type":"float32","default":0.75}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"BatchNorm","schema":{"category":"Normalization","attributes":[{"name":"use_global_stats","visible":false},{"name":"eps","default":0.00001}],"inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"mean"},{"name":"variance"}],"outputs":[{"name":"output"}]}},{"name":"BN","schema":{"category":"Normalization","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sigmoid","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxLoss","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxWithLoss","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"ContrastiveLossParameter","schema":{"attributes":[{"name":"margin","default":1},{"name":"legacy_version","default":false}]}},{"name":"ReLU","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"PReLU","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"slope"}],"outputs":[{"name":"output"}]}},{"name":"Concat","schema":{"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Split","schema":{"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"Eltwise","schema":{"attributes":[{"name":"operation","default":1}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"category":"Pool","attributes":[{"name":"pool","default":0}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Crop","schema":{"category":"Data","inputs":[{"name":"data"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Data","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"DummyData","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"AnnotatedData","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"HDF5Data","schema":{"category":"Data","outputs":[{"name":"data"}]}},{"name":"ImageData","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"WindowData","schema":{"category":"Data","outputs":[{"name":"data"},{"name":"label"}]}},{"name":"Slice","schema":{"category":"Tensor","attributes":[{"name":"axis","default":1}],"inputs":[{"name":"input"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"EuclideanLoss","schema":{"inputs":[{"name":"predictions"},{"name":"targets"}],"outputs":[{"name":"output"}]}},{"name":"Accuracy","schema":{"inputs":[{"name":"predictions"},{"name":"labels"}],"outputs":[{"name":"output"}]}},{"name":"LSTM","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"h_0"},{"name":"c_0"}],"outputs":[{"name":"output"},{"name":"h_T"},{"name":"c_T"}],"attributes":[{"name":"weight_filler","visible":false},{"name":"bias_filler","visible":false},{"name":"num_output","visible":false}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"data"}],"outputs":[{"name":"reshaped"}]}},{"name":"ColorConv","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Permute","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Parameter","schema":{"outputs":[{"name":"output"}]}},{"name":"Python","schema":{}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..c753282efbb4dc560cd6465bdb8490dbfabd5775 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("caffe");$root.caffe={},$root.caffe.BlobShape=class{constructor(){this.dim=[]}static decode(e,a){const r=new $root.caffe.BlobShape,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.dim=e.array(r.dim,(()=>e.int64()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobShape;for(e.start();!e.end();){const r=e.tag();switch(r){case"dim":e.array(a.dim,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.BlobProto=class{constructor(){this.data=[],this.diff=[],this.double_data=[],this.double_diff=[]}static decode(e,a){const r=new $root.caffe.BlobProto,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 7:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;case 5:r.data=e.floats(r.data,a);break;case 6:r.diff=e.floats(r.diff,a);break;case 8:r.double_data=e.doubles(r.double_data,a);break;case 9:r.double_diff=e.doubles(r.double_diff,a);break;case 1:r.num=e.int32();break;case 2:r.channels=e.int32();break;case 3:r.height=e.int32();break;case 4:r.width=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobProto;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;case"data":e.array(a.data,(()=>e.float()));break;case"diff":e.array(a.diff,(()=>e.float()));break;case"double_data":e.array(a.double_data,(()=>e.float()));break;case"double_diff":e.array(a.double_diff,(()=>e.float()));break;case"num":a.num=e.integer();break;case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.BlobProto.prototype.shape=null,$root.caffe.BlobProto.prototype.num=0,$root.caffe.BlobProto.prototype.channels=0,$root.caffe.BlobProto.prototype.height=0,$root.caffe.BlobProto.prototype.width=0,$root.caffe.BlobProtoVector=class{constructor(){this.blobs=[]}static decode(e,a){const r=new $root.caffe.BlobProtoVector,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BlobProtoVector;for(e.start();!e.end();){const r=e.tag();switch(r){case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.Datum=class{constructor(){this.float_data=[]}static decode(e,a){const r=new $root.caffe.Datum,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.channels=e.int32();break;case 2:r.height=e.int32();break;case 3:r.width=e.int32();break;case 4:r.data=e.bytes();break;case 5:r.label=e.int32();break;case 6:r.float_data=e.floats(r.float_data,a);break;case 7:r.encoded=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.Datum;for(e.start();!e.end();){const r=e.tag();switch(r){case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;case"data":a.data=e.bytes();break;case"label":a.label=e.integer();break;case"float_data":e.array(a.float_data,(()=>e.float()));break;case"encoded":a.encoded=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.Datum.prototype.channels=0,$root.caffe.Datum.prototype.height=0,$root.caffe.Datum.prototype.width=0,$root.caffe.Datum.prototype.data=new Uint8Array([]),$root.caffe.Datum.prototype.label=0,$root.caffe.Datum.prototype.encoded=!1,$root.caffe.FillerParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.FillerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.type=e.string();break;case 2:r.value=e.float();break;case 3:r.min=e.float();break;case 4:r.max=e.float();break;case 5:r.mean=e.float();break;case 6:r.std=e.float();break;case 7:r.sparse=e.int32();break;case 8:r.variance_norm=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.FillerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"type":a.type=e.string();break;case"value":a.value=e.float();break;case"min":a.min=e.float();break;case"max":a.max=e.float();break;case"mean":a.mean=e.float();break;case"std":a.std=e.float();break;case"sparse":a.sparse=e.integer();break;case"variance_norm":a.variance_norm=e.enum($root.caffe.FillerParameter.VarianceNorm);break;default:e.field(r,a)}}return a}},$root.caffe.FillerParameter.prototype.type="constant",$root.caffe.FillerParameter.prototype.value=0,$root.caffe.FillerParameter.prototype.min=0,$root.caffe.FillerParameter.prototype.max=1,$root.caffe.FillerParameter.prototype.mean=0,$root.caffe.FillerParameter.prototype.std=1,$root.caffe.FillerParameter.prototype.sparse=-1,$root.caffe.FillerParameter.prototype.variance_norm=0,$root.caffe.FillerParameter.VarianceNorm={FAN_IN:0,FAN_OUT:1,AVERAGE:2},$root.caffe.NetParameter=class{constructor(){this.input=[],this.input_shape=[],this.input_dim=[],this.layer=[],this.layers=[]}static decode(e,a){const r=new $root.caffe.NetParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 3:r.input.push(e.string());break;case 8:r.input_shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;case 4:r.input_dim=e.array(r.input_dim,(()=>e.int32()),a);break;case 5:r.force_backward=e.bool();break;case 6:r.state=$root.caffe.NetState.decode(e,e.uint32());break;case 7:r.debug_info=e.bool();break;case 100:r.layer.push($root.caffe.LayerParameter.decode(e,e.uint32()));break;case 2:r.layers.push($root.caffe.V1LayerParameter.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"input":e.array(a.input,(()=>e.string()));break;case"input_shape":a.input_shape.push($root.caffe.BlobShape.decodeText(e,!0));break;case"input_dim":e.array(a.input_dim,(()=>e.integer()));break;case"force_backward":a.force_backward=e.boolean();break;case"state":a.state=$root.caffe.NetState.decodeText(e,!0);break;case"debug_info":a.debug_info=e.boolean();break;case"layer":a.layer.push($root.caffe.LayerParameter.decodeText(e,!0));break;case"layers":a.layers.push($root.caffe.V1LayerParameter.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.NetParameter.prototype.name="",$root.caffe.NetParameter.prototype.force_backward=!1,$root.caffe.NetParameter.prototype.state=null,$root.caffe.NetParameter.prototype.debug_info=!1,$root.caffe.SolverParameter=class{constructor(){this.test_net=[],this.test_net_param=[],this.test_state=[],this.test_iter=[],this.stepvalue=[],this.weights=[]}static decode(e,a){const r=new $root.caffe.SolverParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 24:r.net=e.string();break;case 25:r.net_param=$root.caffe.NetParameter.decode(e,e.uint32());break;case 1:r.train_net=e.string();break;case 2:r.test_net.push(e.string());break;case 21:r.train_net_param=$root.caffe.NetParameter.decode(e,e.uint32());break;case 22:r.test_net_param.push($root.caffe.NetParameter.decode(e,e.uint32()));break;case 26:r.train_state=$root.caffe.NetState.decode(e,e.uint32());break;case 27:r.test_state.push($root.caffe.NetState.decode(e,e.uint32()));break;case 3:r.test_iter=e.array(r.test_iter,(()=>e.int32()),a);break;case 4:r.test_interval=e.int32();break;case 19:r.test_compute_loss=e.bool();break;case 32:r.test_initialization=e.bool();break;case 5:r.base_lr=e.float();break;case 6:r.display=e.int32();break;case 33:r.average_loss=e.int32();break;case 7:r.max_iter=e.int32();break;case 36:r.iter_size=e.int32();break;case 8:r.lr_policy=e.string();break;case 9:r.gamma=e.float();break;case 10:r.power=e.float();break;case 11:r.momentum=e.float();break;case 12:r.weight_decay=e.float();break;case 29:r.regularization_type=e.string();break;case 13:r.stepsize=e.int32();break;case 34:r.stepvalue=e.array(r.stepvalue,(()=>e.int32()),a);break;case 35:r.clip_gradients=e.float();break;case 14:r.snapshot=e.int32();break;case 15:r.snapshot_prefix=e.string();break;case 16:r.snapshot_diff=e.bool();break;case 37:r.snapshot_format=e.int32();break;case 17:r.solver_mode=e.int32();break;case 18:r.device_id=e.int32();break;case 20:r.random_seed=e.int64();break;case 40:r.type=e.string();break;case 31:r.delta=e.float();break;case 39:r.momentum2=e.float();break;case 38:r.rms_decay=e.float();break;case 23:r.debug_info=e.bool();break;case 28:r.snapshot_after_train=e.bool();break;case 30:r.solver_type=e.int32();break;case 41:r.layer_wise_reduce=e.bool();break;case 42:r.weights.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SolverParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"net":a.net=e.string();break;case"net_param":a.net_param=$root.caffe.NetParameter.decodeText(e,!0);break;case"train_net":a.train_net=e.string();break;case"test_net":e.array(a.test_net,(()=>e.string()));break;case"train_net_param":a.train_net_param=$root.caffe.NetParameter.decodeText(e,!0);break;case"test_net_param":a.test_net_param.push($root.caffe.NetParameter.decodeText(e,!0));break;case"train_state":a.train_state=$root.caffe.NetState.decodeText(e,!0);break;case"test_state":a.test_state.push($root.caffe.NetState.decodeText(e,!0));break;case"test_iter":e.array(a.test_iter,(()=>e.integer()));break;case"test_interval":a.test_interval=e.integer();break;case"test_compute_loss":a.test_compute_loss=e.boolean();break;case"test_initialization":a.test_initialization=e.boolean();break;case"base_lr":a.base_lr=e.float();break;case"display":a.display=e.integer();break;case"average_loss":a.average_loss=e.integer();break;case"max_iter":a.max_iter=e.integer();break;case"iter_size":a.iter_size=e.integer();break;case"lr_policy":a.lr_policy=e.string();break;case"gamma":a.gamma=e.float();break;case"power":a.power=e.float();break;case"momentum":a.momentum=e.float();break;case"weight_decay":a.weight_decay=e.float();break;case"regularization_type":a.regularization_type=e.string();break;case"stepsize":a.stepsize=e.integer();break;case"stepvalue":e.array(a.stepvalue,(()=>e.integer()));break;case"clip_gradients":a.clip_gradients=e.float();break;case"snapshot":a.snapshot=e.integer();break;case"snapshot_prefix":a.snapshot_prefix=e.string();break;case"snapshot_diff":a.snapshot_diff=e.boolean();break;case"snapshot_format":a.snapshot_format=e.enum($root.caffe.SolverParameter.SnapshotFormat);break;case"solver_mode":a.solver_mode=e.enum($root.caffe.SolverParameter.SolverMode);break;case"device_id":a.device_id=e.integer();break;case"random_seed":a.random_seed=e.integer();break;case"type":a.type=e.string();break;case"delta":a.delta=e.float();break;case"momentum2":a.momentum2=e.float();break;case"rms_decay":a.rms_decay=e.float();break;case"debug_info":a.debug_info=e.boolean();break;case"snapshot_after_train":a.snapshot_after_train=e.boolean();break;case"solver_type":a.solver_type=e.enum($root.caffe.SolverParameter.SolverType);break;case"layer_wise_reduce":a.layer_wise_reduce=e.boolean();break;case"weights":e.array(a.weights,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.SolverParameter.prototype.net="",$root.caffe.SolverParameter.prototype.net_param=null,$root.caffe.SolverParameter.prototype.train_net="",$root.caffe.SolverParameter.prototype.train_net_param=null,$root.caffe.SolverParameter.prototype.train_state=null,$root.caffe.SolverParameter.prototype.test_interval=0,$root.caffe.SolverParameter.prototype.test_compute_loss=!1,$root.caffe.SolverParameter.prototype.test_initialization=!0,$root.caffe.SolverParameter.prototype.base_lr=0,$root.caffe.SolverParameter.prototype.display=0,$root.caffe.SolverParameter.prototype.average_loss=1,$root.caffe.SolverParameter.prototype.max_iter=0,$root.caffe.SolverParameter.prototype.iter_size=1,$root.caffe.SolverParameter.prototype.lr_policy="",$root.caffe.SolverParameter.prototype.gamma=0,$root.caffe.SolverParameter.prototype.power=0,$root.caffe.SolverParameter.prototype.momentum=0,$root.caffe.SolverParameter.prototype.weight_decay=0,$root.caffe.SolverParameter.prototype.regularization_type="L2",$root.caffe.SolverParameter.prototype.stepsize=0,$root.caffe.SolverParameter.prototype.clip_gradients=-1,$root.caffe.SolverParameter.prototype.snapshot=0,$root.caffe.SolverParameter.prototype.snapshot_prefix="",$root.caffe.SolverParameter.prototype.snapshot_diff=!1,$root.caffe.SolverParameter.prototype.snapshot_format=1,$root.caffe.SolverParameter.prototype.solver_mode=1,$root.caffe.SolverParameter.prototype.device_id=0,$root.caffe.SolverParameter.prototype.random_seed=protobuf.Long?protobuf.Long.fromBits(-1,-1,!1):-1,$root.caffe.SolverParameter.prototype.type="SGD",$root.caffe.SolverParameter.prototype.delta=1e-8,$root.caffe.SolverParameter.prototype.momentum2=.999,$root.caffe.SolverParameter.prototype.rms_decay=.99,$root.caffe.SolverParameter.prototype.debug_info=!1,$root.caffe.SolverParameter.prototype.snapshot_after_train=!0,$root.caffe.SolverParameter.prototype.solver_type=0,$root.caffe.SolverParameter.prototype.layer_wise_reduce=!0,$root.caffe.SolverParameter.SnapshotFormat={HDF5:0,BINARYPROTO:1},$root.caffe.SolverParameter.SolverMode={CPU:0,GPU:1},$root.caffe.SolverParameter.SolverType={SGD:0,NESTEROV:1,ADAGRAD:2,RMSPROP:3,ADADELTA:4,ADAM:5},$root.caffe.SolverState=class{constructor(){this.history=[]}static decode(e,a){const r=new $root.caffe.SolverState,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.iter=e.int32();break;case 2:r.learned_net=e.string();break;case 3:r.history.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 4:r.current_step=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SolverState;for(e.start();!e.end();){const r=e.tag();switch(r){case"iter":a.iter=e.integer();break;case"learned_net":a.learned_net=e.string();break;case"history":a.history.push($root.caffe.BlobProto.decodeText(e,!0));break;case"current_step":a.current_step=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SolverState.prototype.iter=0,$root.caffe.SolverState.prototype.learned_net="",$root.caffe.SolverState.prototype.current_step=0,$root.caffe.Phase={TRAIN:0,TEST:1},$root.caffe.NetState=class{constructor(){this.stage=[]}static decode(e,a){const r=new $root.caffe.NetState,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.phase=e.int32();break;case 2:r.level=e.int32();break;case 3:r.stage.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetState;for(e.start();!e.end();){const r=e.tag();switch(r){case"phase":a.phase=e.enum($root.caffe.Phase);break;case"level":a.level=e.integer();break;case"stage":e.array(a.stage,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.NetState.prototype.phase=1,$root.caffe.NetState.prototype.level=0,$root.caffe.NetStateRule=class{constructor(){this.stage=[],this.not_stage=[]}static decode(e,a){const r=new $root.caffe.NetStateRule,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.phase=e.int32();break;case 2:r.min_level=e.int32();break;case 3:r.max_level=e.int32();break;case 4:r.stage.push(e.string());break;case 5:r.not_stage.push(e.string());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.NetStateRule;for(e.start();!e.end();){const r=e.tag();switch(r){case"phase":a.phase=e.enum($root.caffe.Phase);break;case"min_level":a.min_level=e.integer();break;case"max_level":a.max_level=e.integer();break;case"stage":e.array(a.stage,(()=>e.string()));break;case"not_stage":e.array(a.not_stage,(()=>e.string()));break;default:e.field(r,a)}}return a}},$root.caffe.NetStateRule.prototype.phase=0,$root.caffe.NetStateRule.prototype.min_level=0,$root.caffe.NetStateRule.prototype.max_level=0,$root.caffe.ParamSpec=class{constructor(){}static decode(e,a){const r=new $root.caffe.ParamSpec,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.share_mode=e.int32();break;case 3:r.lr_mult=e.float();break;case 4:r.decay_mult=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ParamSpec;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"share_mode":a.share_mode=e.enum($root.caffe.ParamSpec.DimCheckMode);break;case"lr_mult":a.lr_mult=e.float();break;case"decay_mult":a.decay_mult=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ParamSpec.prototype.name="",$root.caffe.ParamSpec.prototype.share_mode=0,$root.caffe.ParamSpec.prototype.lr_mult=1,$root.caffe.ParamSpec.prototype.decay_mult=1,$root.caffe.ParamSpec.DimCheckMode={STRICT:0,PERMISSIVE:1},$root.caffe.LayerParameter=class{constructor(){this.bottom=[],this.top=[],this.loss_weight=[],this.param=[],this.blobs=[],this.propagate_down=[],this.include=[],this.exclude=[]}static decode(e,a){const r=new $root.caffe.LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.type=e.string();break;case 3:r.bottom.push(e.string());break;case 4:r.top.push(e.string());break;case 10:r.phase=e.int32();break;case 5:r.loss_weight=e.floats(r.loss_weight,a);break;case 6:r.param.push($root.caffe.ParamSpec.decode(e,e.uint32()));break;case 7:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 11:r.propagate_down=e.array(r.propagate_down,(()=>e.bool()),a);break;case 8:r.include.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 9:r.exclude.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 100:r.transform_param=$root.caffe.TransformationParameter.decode(e,e.uint32());break;case 101:r.loss_param=$root.caffe.LossParameter.decode(e,e.uint32());break;case 102:r.accuracy_param=$root.caffe.AccuracyParameter.decode(e,e.uint32());break;case 103:r.argmax_param=$root.caffe.ArgMaxParameter.decode(e,e.uint32());break;case 139:r.batch_norm_param=$root.caffe.BatchNormParameter.decode(e,e.uint32());break;case 141:r.bias_param=$root.caffe.BiasParameter.decode(e,e.uint32());break;case 148:r.clip_param=$root.caffe.ClipParameter.decode(e,e.uint32());break;case 104:r.concat_param=$root.caffe.ConcatParameter.decode(e,e.uint32());break;case 105:r.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decode(e,e.uint32());break;case 106:r.convolution_param=$root.caffe.ConvolutionParameter.decode(e,e.uint32());break;case 144:r.crop_param=$root.caffe.CropParameter.decode(e,e.uint32());break;case 107:r.data_param=$root.caffe.DataParameter.decode(e,e.uint32());break;case 108:r.dropout_param=$root.caffe.DropoutParameter.decode(e,e.uint32());break;case 109:r.dummy_data_param=$root.caffe.DummyDataParameter.decode(e,e.uint32());break;case 110:r.eltwise_param=$root.caffe.EltwiseParameter.decode(e,e.uint32());break;case 140:r.elu_param=$root.caffe.ELUParameter.decode(e,e.uint32());break;case 137:r.embed_param=$root.caffe.EmbedParameter.decode(e,e.uint32());break;case 111:r.exp_param=$root.caffe.ExpParameter.decode(e,e.uint32());break;case 135:r.flatten_param=$root.caffe.FlattenParameter.decode(e,e.uint32());break;case 112:r.hdf5_data_param=$root.caffe.HDF5DataParameter.decode(e,e.uint32());break;case 113:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;case 114:r.hinge_loss_param=$root.caffe.HingeLossParameter.decode(e,e.uint32());break;case 115:r.image_data_param=$root.caffe.ImageDataParameter.decode(e,e.uint32());break;case 116:r.infogain_loss_param=$root.caffe.InfogainLossParameter.decode(e,e.uint32());break;case 117:r.inner_product_param=$root.caffe.InnerProductParameter.decode(e,e.uint32());break;case 143:r.input_param=$root.caffe.InputParameter.decode(e,e.uint32());break;case 134:r.log_param=$root.caffe.LogParameter.decode(e,e.uint32());break;case 118:r.lrn_param=$root.caffe.LRNParameter.decode(e,e.uint32());break;case 119:r.memory_data_param=$root.caffe.MemoryDataParameter.decode(e,e.uint32());break;case 120:r.mvn_param=$root.caffe.MVNParameter.decode(e,e.uint32());break;case 145:r.parameter_param=$root.caffe.ParameterParameter.decode(e,e.uint32());break;case 121:r.pooling_param=$root.caffe.PoolingParameter.decode(e,e.uint32());break;case 122:r.power_param=$root.caffe.PowerParameter.decode(e,e.uint32());break;case 131:r.prelu_param=$root.caffe.PReLUParameter.decode(e,e.uint32());break;case 130:r.python_param=$root.caffe.PythonParameter.decode(e,e.uint32());break;case 146:r.recurrent_param=$root.caffe.RecurrentParameter.decode(e,e.uint32());break;case 136:r.reduction_param=$root.caffe.ReductionParameter.decode(e,e.uint32());break;case 123:r.relu_param=$root.caffe.ReLUParameter.decode(e,e.uint32());break;case 133:r.reshape_param=$root.caffe.ReshapeParameter.decode(e,e.uint32());break;case 142:r.scale_param=$root.caffe.ScaleParameter.decode(e,e.uint32());break;case 124:r.sigmoid_param=$root.caffe.SigmoidParameter.decode(e,e.uint32());break;case 125:r.softmax_param=$root.caffe.SoftmaxParameter.decode(e,e.uint32());break;case 132:r.spp_param=$root.caffe.SPPParameter.decode(e,e.uint32());break;case 126:r.slice_param=$root.caffe.SliceParameter.decode(e,e.uint32());break;case 147:r.swish_param=$root.caffe.SwishParameter.decode(e,e.uint32());break;case 127:r.tanh_param=$root.caffe.TanHParameter.decode(e,e.uint32());break;case 128:r.threshold_param=$root.caffe.ThresholdParameter.decode(e,e.uint32());break;case 138:r.tile_param=$root.caffe.TileParameter.decode(e,e.uint32());break;case 129:r.window_data_param=$root.caffe.WindowDataParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"type":a.type=e.string();break;case"bottom":e.array(a.bottom,(()=>e.string()));break;case"top":e.array(a.top,(()=>e.string()));break;case"phase":a.phase=e.enum($root.caffe.Phase);break;case"loss_weight":e.array(a.loss_weight,(()=>e.float()));break;case"param":a.param.push($root.caffe.ParamSpec.decodeText(e,!0));break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"propagate_down":e.array(a.propagate_down,(()=>e.boolean()));break;case"include":a.include.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"exclude":a.exclude.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"transform_param":a.transform_param=$root.caffe.TransformationParameter.decodeText(e,!0);break;case"loss_param":a.loss_param=$root.caffe.LossParameter.decodeText(e,!0);break;case"accuracy_param":a.accuracy_param=$root.caffe.AccuracyParameter.decodeText(e,!0);break;case"argmax_param":a.argmax_param=$root.caffe.ArgMaxParameter.decodeText(e,!0);break;case"batch_norm_param":a.batch_norm_param=$root.caffe.BatchNormParameter.decodeText(e,!0);break;case"bias_param":a.bias_param=$root.caffe.BiasParameter.decodeText(e,!0);break;case"clip_param":a.clip_param=$root.caffe.ClipParameter.decodeText(e,!0);break;case"concat_param":a.concat_param=$root.caffe.ConcatParameter.decodeText(e,!0);break;case"contrastive_loss_param":a.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decodeText(e,!0);break;case"convolution_param":a.convolution_param=$root.caffe.ConvolutionParameter.decodeText(e,!0);break;case"crop_param":a.crop_param=$root.caffe.CropParameter.decodeText(e,!0);break;case"data_param":a.data_param=$root.caffe.DataParameter.decodeText(e,!0);break;case"dropout_param":a.dropout_param=$root.caffe.DropoutParameter.decodeText(e,!0);break;case"dummy_data_param":a.dummy_data_param=$root.caffe.DummyDataParameter.decodeText(e,!0);break;case"eltwise_param":a.eltwise_param=$root.caffe.EltwiseParameter.decodeText(e,!0);break;case"elu_param":a.elu_param=$root.caffe.ELUParameter.decodeText(e,!0);break;case"embed_param":a.embed_param=$root.caffe.EmbedParameter.decodeText(e,!0);break;case"exp_param":a.exp_param=$root.caffe.ExpParameter.decodeText(e,!0);break;case"flatten_param":a.flatten_param=$root.caffe.FlattenParameter.decodeText(e,!0);break;case"hdf5_data_param":a.hdf5_data_param=$root.caffe.HDF5DataParameter.decodeText(e,!0);break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;case"hinge_loss_param":a.hinge_loss_param=$root.caffe.HingeLossParameter.decodeText(e,!0);break;case"image_data_param":a.image_data_param=$root.caffe.ImageDataParameter.decodeText(e,!0);break;case"infogain_loss_param":a.infogain_loss_param=$root.caffe.InfogainLossParameter.decodeText(e,!0);break;case"inner_product_param":a.inner_product_param=$root.caffe.InnerProductParameter.decodeText(e,!0);break;case"input_param":a.input_param=$root.caffe.InputParameter.decodeText(e,!0);break;case"log_param":a.log_param=$root.caffe.LogParameter.decodeText(e,!0);break;case"lrn_param":a.lrn_param=$root.caffe.LRNParameter.decodeText(e,!0);break;case"memory_data_param":a.memory_data_param=$root.caffe.MemoryDataParameter.decodeText(e,!0);break;case"mvn_param":a.mvn_param=$root.caffe.MVNParameter.decodeText(e,!0);break;case"parameter_param":a.parameter_param=$root.caffe.ParameterParameter.decodeText(e,!0);break;case"pooling_param":a.pooling_param=$root.caffe.PoolingParameter.decodeText(e,!0);break;case"power_param":a.power_param=$root.caffe.PowerParameter.decodeText(e,!0);break;case"prelu_param":a.prelu_param=$root.caffe.PReLUParameter.decodeText(e,!0);break;case"python_param":a.python_param=$root.caffe.PythonParameter.decodeText(e,!0);break;case"recurrent_param":a.recurrent_param=$root.caffe.RecurrentParameter.decodeText(e,!0);break;case"reduction_param":a.reduction_param=$root.caffe.ReductionParameter.decodeText(e,!0);break;case"relu_param":a.relu_param=$root.caffe.ReLUParameter.decodeText(e,!0);break;case"reshape_param":a.reshape_param=$root.caffe.ReshapeParameter.decodeText(e,!0);break;case"scale_param":a.scale_param=$root.caffe.ScaleParameter.decodeText(e,!0);break;case"sigmoid_param":a.sigmoid_param=$root.caffe.SigmoidParameter.decodeText(e,!0);break;case"softmax_param":a.softmax_param=$root.caffe.SoftmaxParameter.decodeText(e,!0);break;case"spp_param":a.spp_param=$root.caffe.SPPParameter.decodeText(e,!0);break;case"slice_param":a.slice_param=$root.caffe.SliceParameter.decodeText(e,!0);break;case"swish_param":a.swish_param=$root.caffe.SwishParameter.decodeText(e,!0);break;case"tanh_param":a.tanh_param=$root.caffe.TanHParameter.decodeText(e,!0);break;case"threshold_param":a.threshold_param=$root.caffe.ThresholdParameter.decodeText(e,!0);break;case"tile_param":a.tile_param=$root.caffe.TileParameter.decodeText(e,!0);break;case"window_data_param":a.window_data_param=$root.caffe.WindowDataParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.LayerParameter.prototype.name="",$root.caffe.LayerParameter.prototype.type="",$root.caffe.LayerParameter.prototype.phase=0,$root.caffe.LayerParameter.prototype.transform_param=null,$root.caffe.LayerParameter.prototype.loss_param=null,$root.caffe.LayerParameter.prototype.accuracy_param=null,$root.caffe.LayerParameter.prototype.argmax_param=null,$root.caffe.LayerParameter.prototype.batch_norm_param=null,$root.caffe.LayerParameter.prototype.bias_param=null,$root.caffe.LayerParameter.prototype.clip_param=null,$root.caffe.LayerParameter.prototype.concat_param=null,$root.caffe.LayerParameter.prototype.contrastive_loss_param=null,$root.caffe.LayerParameter.prototype.convolution_param=null,$root.caffe.LayerParameter.prototype.crop_param=null,$root.caffe.LayerParameter.prototype.data_param=null,$root.caffe.LayerParameter.prototype.dropout_param=null,$root.caffe.LayerParameter.prototype.dummy_data_param=null,$root.caffe.LayerParameter.prototype.eltwise_param=null,$root.caffe.LayerParameter.prototype.elu_param=null,$root.caffe.LayerParameter.prototype.embed_param=null,$root.caffe.LayerParameter.prototype.exp_param=null,$root.caffe.LayerParameter.prototype.flatten_param=null,$root.caffe.LayerParameter.prototype.hdf5_data_param=null,$root.caffe.LayerParameter.prototype.hdf5_output_param=null,$root.caffe.LayerParameter.prototype.hinge_loss_param=null,$root.caffe.LayerParameter.prototype.image_data_param=null,$root.caffe.LayerParameter.prototype.infogain_loss_param=null,$root.caffe.LayerParameter.prototype.inner_product_param=null,$root.caffe.LayerParameter.prototype.input_param=null,$root.caffe.LayerParameter.prototype.log_param=null,$root.caffe.LayerParameter.prototype.lrn_param=null,$root.caffe.LayerParameter.prototype.memory_data_param=null,$root.caffe.LayerParameter.prototype.mvn_param=null,$root.caffe.LayerParameter.prototype.parameter_param=null,$root.caffe.LayerParameter.prototype.pooling_param=null,$root.caffe.LayerParameter.prototype.power_param=null,$root.caffe.LayerParameter.prototype.prelu_param=null,$root.caffe.LayerParameter.prototype.python_param=null,$root.caffe.LayerParameter.prototype.recurrent_param=null,$root.caffe.LayerParameter.prototype.reduction_param=null,$root.caffe.LayerParameter.prototype.relu_param=null,$root.caffe.LayerParameter.prototype.reshape_param=null,$root.caffe.LayerParameter.prototype.scale_param=null,$root.caffe.LayerParameter.prototype.sigmoid_param=null,$root.caffe.LayerParameter.prototype.softmax_param=null,$root.caffe.LayerParameter.prototype.spp_param=null,$root.caffe.LayerParameter.prototype.slice_param=null,$root.caffe.LayerParameter.prototype.swish_param=null,$root.caffe.LayerParameter.prototype.tanh_param=null,$root.caffe.LayerParameter.prototype.threshold_param=null,$root.caffe.LayerParameter.prototype.tile_param=null,$root.caffe.LayerParameter.prototype.window_data_param=null,$root.caffe.TransformationParameter=class{constructor(){this.mean_value=[]}static decode(e,a){const r=new $root.caffe.TransformationParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.scale=e.float();break;case 2:r.mirror=e.bool();break;case 3:r.crop_size=e.uint32();break;case 4:r.mean_file=e.string();break;case 5:r.mean_value=e.floats(r.mean_value,a);break;case 6:r.force_color=e.bool();break;case 7:r.force_gray=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TransformationParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"scale":a.scale=e.float();break;case"mirror":a.mirror=e.boolean();break;case"crop_size":a.crop_size=e.integer();break;case"mean_file":a.mean_file=e.string();break;case"mean_value":e.array(a.mean_value,(()=>e.float()));break;case"force_color":a.force_color=e.boolean();break;case"force_gray":a.force_gray=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.TransformationParameter.prototype.scale=1,$root.caffe.TransformationParameter.prototype.mirror=!1,$root.caffe.TransformationParameter.prototype.crop_size=0,$root.caffe.TransformationParameter.prototype.mean_file="",$root.caffe.TransformationParameter.prototype.force_color=!1,$root.caffe.TransformationParameter.prototype.force_gray=!1,$root.caffe.LossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.ignore_label=e.int32();break;case 3:r.normalization=e.int32();break;case 2:r.normalize=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"ignore_label":a.ignore_label=e.integer();break;case"normalization":a.normalization=e.enum($root.caffe.LossParameter.NormalizationMode);break;case"normalize":a.normalize=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.LossParameter.prototype.ignore_label=0,$root.caffe.LossParameter.prototype.normalization=1,$root.caffe.LossParameter.prototype.normalize=!1,$root.caffe.LossParameter.NormalizationMode={FULL:0,VALID:1,BATCH_SIZE:2,NONE:3},$root.caffe.AccuracyParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.AccuracyParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.top_k=e.uint32();break;case 2:r.axis=e.int32();break;case 3:r.ignore_label=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.AccuracyParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"top_k":a.top_k=e.integer();break;case"axis":a.axis=e.integer();break;case"ignore_label":a.ignore_label=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.AccuracyParameter.prototype.top_k=1,$root.caffe.AccuracyParameter.prototype.axis=1,$root.caffe.AccuracyParameter.prototype.ignore_label=0,$root.caffe.ArgMaxParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ArgMaxParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.out_max_val=e.bool();break;case 2:r.top_k=e.uint32();break;case 3:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ArgMaxParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"out_max_val":a.out_max_val=e.boolean();break;case"top_k":a.top_k=e.integer();break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ArgMaxParameter.prototype.out_max_val=!1,$root.caffe.ArgMaxParameter.prototype.top_k=1,$root.caffe.ArgMaxParameter.prototype.axis=0,$root.caffe.ClipParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ClipParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.min=e.float();break;case 2:r.max=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ClipParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"min":a.min=e.float();break;case"max":a.max=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ClipParameter.prototype.min=0,$root.caffe.ClipParameter.prototype.max=0,$root.caffe.ConcatParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ConcatParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 2:r.axis=e.int32();break;case 1:r.concat_dim=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ConcatParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"concat_dim":a.concat_dim=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ConcatParameter.prototype.axis=1,$root.caffe.ConcatParameter.prototype.concat_dim=1,$root.caffe.BatchNormParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.BatchNormParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.use_global_stats=e.bool();break;case 2:r.moving_average_fraction=e.float();break;case 3:r.eps=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BatchNormParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"use_global_stats":a.use_global_stats=e.boolean();break;case"moving_average_fraction":a.moving_average_fraction=e.float();break;case"eps":a.eps=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.BatchNormParameter.prototype.use_global_stats=!1,$root.caffe.BatchNormParameter.prototype.moving_average_fraction=.999,$root.caffe.BatchNormParameter.prototype.eps=1e-5,$root.caffe.BiasParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.BiasParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.num_axes=e.int32();break;case 3:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.BiasParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.BiasParameter.prototype.axis=1,$root.caffe.BiasParameter.prototype.num_axes=1,$root.caffe.BiasParameter.prototype.filler=null,$root.caffe.ContrastiveLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ContrastiveLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.margin=e.float();break;case 2:r.legacy_version=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ContrastiveLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"margin":a.margin=e.float();break;case"legacy_version":a.legacy_version=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.ContrastiveLossParameter.prototype.margin=1,$root.caffe.ContrastiveLossParameter.prototype.legacy_version=!1,$root.caffe.ConvolutionParameter=class{constructor(){this.pad=[],this.kernel_size=[],this.stride=[],this.dilation=[]}static decode(e,a){const r=new $root.caffe.ConvolutionParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.bias_term=e.bool();break;case 3:r.pad=e.array(r.pad,(()=>e.uint32()),a);break;case 4:r.kernel_size=e.array(r.kernel_size,(()=>e.uint32()),a);break;case 6:r.stride=e.array(r.stride,(()=>e.uint32()),a);break;case 18:r.dilation=e.array(r.dilation,(()=>e.uint32()),a);break;case 9:r.pad_h=e.uint32();break;case 10:r.pad_w=e.uint32();break;case 11:r.kernel_h=e.uint32();break;case 12:r.kernel_w=e.uint32();break;case 13:r.stride_h=e.uint32();break;case 14:r.stride_w=e.uint32();break;case 5:r.group=e.uint32();break;case 7:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 8:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 15:r.engine=e.int32();break;case 16:r.axis=e.int32();break;case 17:r.force_nd_im2col=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ConvolutionParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"pad":e.array(a.pad,(()=>e.integer()));break;case"kernel_size":e.array(a.kernel_size,(()=>e.integer()));break;case"stride":e.array(a.stride,(()=>e.integer()));break;case"dilation":e.array(a.dilation,(()=>e.integer()));break;case"pad_h":a.pad_h=e.integer();break;case"pad_w":a.pad_w=e.integer();break;case"kernel_h":a.kernel_h=e.integer();break;case"kernel_w":a.kernel_w=e.integer();break;case"stride_h":a.stride_h=e.integer();break;case"stride_w":a.stride_w=e.integer();break;case"group":a.group=e.integer();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"engine":a.engine=e.enum($root.caffe.ConvolutionParameter.Engine);break;case"axis":a.axis=e.integer();break;case"force_nd_im2col":a.force_nd_im2col=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.ConvolutionParameter.prototype.num_output=0,$root.caffe.ConvolutionParameter.prototype.bias_term=!0,$root.caffe.ConvolutionParameter.prototype.pad_h=0,$root.caffe.ConvolutionParameter.prototype.pad_w=0,$root.caffe.ConvolutionParameter.prototype.kernel_h=0,$root.caffe.ConvolutionParameter.prototype.kernel_w=0,$root.caffe.ConvolutionParameter.prototype.stride_h=0,$root.caffe.ConvolutionParameter.prototype.stride_w=0,$root.caffe.ConvolutionParameter.prototype.group=1,$root.caffe.ConvolutionParameter.prototype.weight_filler=null,$root.caffe.ConvolutionParameter.prototype.bias_filler=null,$root.caffe.ConvolutionParameter.prototype.engine=0,$root.caffe.ConvolutionParameter.prototype.axis=1,$root.caffe.ConvolutionParameter.prototype.force_nd_im2col=!1,$root.caffe.ConvolutionParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.CropParameter=class{constructor(){this.offset=[]}static decode(e,a){const r=new $root.caffe.CropParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.offset=e.array(r.offset,(()=>e.uint32()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.CropParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"offset":e.array(a.offset,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.CropParameter.prototype.axis=2,$root.caffe.DataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.DataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 4:r.batch_size=e.uint32();break;case 7:r.rand_skip=e.uint32();break;case 8:r.backend=e.int32();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 9:r.force_encoded_color=e.bool();break;case 10:r.prefetch=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"rand_skip":a.rand_skip=e.integer();break;case"backend":a.backend=e.enum($root.caffe.DataParameter.DB);break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"force_encoded_color":a.force_encoded_color=e.boolean();break;case"prefetch":a.prefetch=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.DataParameter.prototype.source="",$root.caffe.DataParameter.prototype.batch_size=0,$root.caffe.DataParameter.prototype.rand_skip=0,$root.caffe.DataParameter.prototype.backend=0,$root.caffe.DataParameter.prototype.scale=1,$root.caffe.DataParameter.prototype.mean_file="",$root.caffe.DataParameter.prototype.crop_size=0,$root.caffe.DataParameter.prototype.mirror=!1,$root.caffe.DataParameter.prototype.force_encoded_color=!1,$root.caffe.DataParameter.prototype.prefetch=4,$root.caffe.DataParameter.DB={LEVELDB:0,LMDB:1},$root.caffe.DropoutParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.DropoutParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.dropout_ratio=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DropoutParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"dropout_ratio":a.dropout_ratio=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.DropoutParameter.prototype.dropout_ratio=.5,$root.caffe.DummyDataParameter=class{constructor(){this.data_filler=[],this.shape=[],this.num=[],this.channels=[],this.height=[],this.width=[]}static decode(e,a){const r=new $root.caffe.DummyDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.data_filler.push($root.caffe.FillerParameter.decode(e,e.uint32()));break;case 6:r.shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;case 2:r.num=e.array(r.num,(()=>e.uint32()),a);break;case 3:r.channels=e.array(r.channels,(()=>e.uint32()),a);break;case 4:r.height=e.array(r.height,(()=>e.uint32()),a);break;case 5:r.width=e.array(r.width,(()=>e.uint32()),a);break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.DummyDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"data_filler":a.data_filler.push($root.caffe.FillerParameter.decodeText(e,!0));break;case"shape":a.shape.push($root.caffe.BlobShape.decodeText(e,!0));break;case"num":e.array(a.num,(()=>e.integer()));break;case"channels":e.array(a.channels,(()=>e.integer()));break;case"height":e.array(a.height,(()=>e.integer()));break;case"width":e.array(a.width,(()=>e.integer()));break;default:e.field(r,a)}}return a}},$root.caffe.EltwiseParameter=class{constructor(){this.coeff=[]}static decode(e,a){const r=new $root.caffe.EltwiseParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.operation=e.int32();break;case 2:r.coeff=e.floats(r.coeff,a);break;case 3:r.stable_prod_grad=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.EltwiseParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"operation":a.operation=e.enum($root.caffe.EltwiseParameter.EltwiseOp);break;case"coeff":e.array(a.coeff,(()=>e.float()));break;case"stable_prod_grad":a.stable_prod_grad=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.EltwiseParameter.prototype.operation=1,$root.caffe.EltwiseParameter.prototype.stable_prod_grad=!0,$root.caffe.EltwiseParameter.EltwiseOp={PROD:0,SUM:1,MAX:2},$root.caffe.ELUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ELUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.alpha=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ELUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"alpha":a.alpha=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ELUParameter.prototype.alpha=1,$root.caffe.EmbedParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.EmbedParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.input_dim=e.uint32();break;case 3:r.bias_term=e.bool();break;case 4:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 5:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.EmbedParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"input_dim":a.input_dim=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.EmbedParameter.prototype.num_output=0,$root.caffe.EmbedParameter.prototype.input_dim=0,$root.caffe.EmbedParameter.prototype.bias_term=!0,$root.caffe.EmbedParameter.prototype.weight_filler=null,$root.caffe.EmbedParameter.prototype.bias_filler=null,$root.caffe.ExpParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ExpParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.base=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ExpParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"base":a.base=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ExpParameter.prototype.base=-1,$root.caffe.ExpParameter.prototype.scale=1,$root.caffe.ExpParameter.prototype.shift=0,$root.caffe.FlattenParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.FlattenParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.end_axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.FlattenParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"end_axis":a.end_axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.FlattenParameter.prototype.axis=1,$root.caffe.FlattenParameter.prototype.end_axis=-1,$root.caffe.HDF5DataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HDF5DataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.batch_size=e.uint32();break;case 3:r.shuffle=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HDF5DataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"shuffle":a.shuffle=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.HDF5DataParameter.prototype.source="",$root.caffe.HDF5DataParameter.prototype.batch_size=0,$root.caffe.HDF5DataParameter.prototype.shuffle=!1,$root.caffe.HDF5OutputParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HDF5OutputParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.file_name=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HDF5OutputParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"file_name":a.file_name=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.HDF5OutputParameter.prototype.file_name="",$root.caffe.HingeLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.HingeLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.norm=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.HingeLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"norm":a.norm=e.enum($root.caffe.HingeLossParameter.Norm);break;default:e.field(r,a)}}return a}},$root.caffe.HingeLossParameter.prototype.norm=1,$root.caffe.HingeLossParameter.Norm={L1:1,L2:2},$root.caffe.ImageDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ImageDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 4:r.batch_size=e.uint32();break;case 7:r.rand_skip=e.uint32();break;case 8:r.shuffle=e.bool();break;case 9:r.new_height=e.uint32();break;case 10:r.new_width=e.uint32();break;case 11:r.is_color=e.bool();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 12:r.root_folder=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ImageDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"rand_skip":a.rand_skip=e.integer();break;case"shuffle":a.shuffle=e.boolean();break;case"new_height":a.new_height=e.integer();break;case"new_width":a.new_width=e.integer();break;case"is_color":a.is_color=e.boolean();break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"root_folder":a.root_folder=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.ImageDataParameter.prototype.source="",$root.caffe.ImageDataParameter.prototype.batch_size=1,$root.caffe.ImageDataParameter.prototype.rand_skip=0,$root.caffe.ImageDataParameter.prototype.shuffle=!1,$root.caffe.ImageDataParameter.prototype.new_height=0,$root.caffe.ImageDataParameter.prototype.new_width=0,$root.caffe.ImageDataParameter.prototype.is_color=!0,$root.caffe.ImageDataParameter.prototype.scale=1,$root.caffe.ImageDataParameter.prototype.mean_file="",$root.caffe.ImageDataParameter.prototype.crop_size=0,$root.caffe.ImageDataParameter.prototype.mirror=!1,$root.caffe.ImageDataParameter.prototype.root_folder="",$root.caffe.InfogainLossParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.InfogainLossParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InfogainLossParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.InfogainLossParameter.prototype.source="",$root.caffe.InfogainLossParameter.prototype.axis=1,$root.caffe.InnerProductParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.InnerProductParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.bias_term=e.bool();break;case 3:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 5:r.axis=e.int32();break;case 6:r.transpose=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InnerProductParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"bias_term":a.bias_term=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"axis":a.axis=e.integer();break;case"transpose":a.transpose=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.InnerProductParameter.prototype.num_output=0,$root.caffe.InnerProductParameter.prototype.bias_term=!0,$root.caffe.InnerProductParameter.prototype.weight_filler=null,$root.caffe.InnerProductParameter.prototype.bias_filler=null,$root.caffe.InnerProductParameter.prototype.axis=1,$root.caffe.InnerProductParameter.prototype.transpose=!1,$root.caffe.InputParameter=class{constructor(){this.shape=[]}static decode(e,a){const r=new $root.caffe.InputParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape.push($root.caffe.BlobShape.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.InputParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape.push($root.caffe.BlobShape.decodeText(e,!0));break;default:e.field(r,a)}}return a}},$root.caffe.LogParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LogParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.base=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LogParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"base":a.base=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.LogParameter.prototype.base=-1,$root.caffe.LogParameter.prototype.scale=1,$root.caffe.LogParameter.prototype.shift=0,$root.caffe.LRNParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.LRNParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.local_size=e.uint32();break;case 2:r.alpha=e.float();break;case 3:r.beta=e.float();break;case 4:r.norm_region=e.int32();break;case 5:r.k=e.float();break;case 6:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.LRNParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"local_size":a.local_size=e.integer();break;case"alpha":a.alpha=e.float();break;case"beta":a.beta=e.float();break;case"norm_region":a.norm_region=e.enum($root.caffe.LRNParameter.NormRegion);break;case"k":a.k=e.float();break;case"engine":a.engine=e.enum($root.caffe.LRNParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.LRNParameter.prototype.local_size=5,$root.caffe.LRNParameter.prototype.alpha=1,$root.caffe.LRNParameter.prototype.beta=.75,$root.caffe.LRNParameter.prototype.norm_region=0,$root.caffe.LRNParameter.prototype.k=1,$root.caffe.LRNParameter.prototype.engine=0,$root.caffe.LRNParameter.NormRegion={ACROSS_CHANNELS:0,WITHIN_CHANNEL:1},$root.caffe.LRNParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.MemoryDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.MemoryDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.batch_size=e.uint32();break;case 2:r.channels=e.uint32();break;case 3:r.height=e.uint32();break;case 4:r.width=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.MemoryDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"batch_size":a.batch_size=e.integer();break;case"channels":a.channels=e.integer();break;case"height":a.height=e.integer();break;case"width":a.width=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.MemoryDataParameter.prototype.batch_size=0,$root.caffe.MemoryDataParameter.prototype.channels=0,$root.caffe.MemoryDataParameter.prototype.height=0,$root.caffe.MemoryDataParameter.prototype.width=0,$root.caffe.MVNParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.MVNParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.normalize_variance=e.bool();break;case 2:r.across_channels=e.bool();break;case 3:r.eps=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.MVNParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"normalize_variance":a.normalize_variance=e.boolean();break;case"across_channels":a.across_channels=e.boolean();break;case"eps":a.eps=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.MVNParameter.prototype.normalize_variance=!0,$root.caffe.MVNParameter.prototype.across_channels=!1,$root.caffe.MVNParameter.prototype.eps=1e-9,$root.caffe.ParameterParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ParameterParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ParameterParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.ParameterParameter.prototype.shape=null,$root.caffe.PoolingParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PoolingParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.pool=e.int32();break;case 4:r.pad=e.uint32();break;case 9:r.pad_h=e.uint32();break;case 10:r.pad_w=e.uint32();break;case 2:r.kernel_size=e.uint32();break;case 5:r.kernel_h=e.uint32();break;case 6:r.kernel_w=e.uint32();break;case 3:r.stride=e.uint32();break;case 7:r.stride_h=e.uint32();break;case 8:r.stride_w=e.uint32();break;case 11:r.engine=e.int32();break;case 12:r.global_pooling=e.bool();break;case 13:r.round_mode=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PoolingParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"pool":a.pool=e.enum($root.caffe.PoolingParameter.PoolMethod);break;case"pad":a.pad=e.integer();break;case"pad_h":a.pad_h=e.integer();break;case"pad_w":a.pad_w=e.integer();break;case"kernel_size":a.kernel_size=e.integer();break;case"kernel_h":a.kernel_h=e.integer();break;case"kernel_w":a.kernel_w=e.integer();break;case"stride":a.stride=e.integer();break;case"stride_h":a.stride_h=e.integer();break;case"stride_w":a.stride_w=e.integer();break;case"engine":a.engine=e.enum($root.caffe.PoolingParameter.Engine);break;case"global_pooling":a.global_pooling=e.boolean();break;case"round_mode":a.round_mode=e.enum($root.caffe.PoolingParameter.RoundMode);break;default:e.field(r,a)}}return a}},$root.caffe.PoolingParameter.prototype.pool=0,$root.caffe.PoolingParameter.prototype.pad=0,$root.caffe.PoolingParameter.prototype.pad_h=0,$root.caffe.PoolingParameter.prototype.pad_w=0,$root.caffe.PoolingParameter.prototype.kernel_size=0,$root.caffe.PoolingParameter.prototype.kernel_h=0,$root.caffe.PoolingParameter.prototype.kernel_w=0,$root.caffe.PoolingParameter.prototype.stride=1,$root.caffe.PoolingParameter.prototype.stride_h=0,$root.caffe.PoolingParameter.prototype.stride_w=0,$root.caffe.PoolingParameter.prototype.engine=0,$root.caffe.PoolingParameter.prototype.global_pooling=!1,$root.caffe.PoolingParameter.prototype.round_mode=0,$root.caffe.PoolingParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.PoolingParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.PoolingParameter.RoundMode={CEIL:0,FLOOR:1},$root.caffe.PowerParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PowerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.power=e.float();break;case 2:r.scale=e.float();break;case 3:r.shift=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PowerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"power":a.power=e.float();break;case"scale":a.scale=e.float();break;case"shift":a.shift=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.PowerParameter.prototype.power=1,$root.caffe.PowerParameter.prototype.scale=1,$root.caffe.PowerParameter.prototype.shift=0,$root.caffe.PythonParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PythonParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.module=e.string();break;case 2:r.layer=e.string();break;case 3:r.param_str=e.string();break;case 4:r.share_in_parallel=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PythonParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"module":a.module=e.string();break;case"layer":a.layer=e.string();break;case"param_str":a.param_str=e.string();break;case"share_in_parallel":a.share_in_parallel=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.PythonParameter.prototype.module="",$root.caffe.PythonParameter.prototype.layer="",$root.caffe.PythonParameter.prototype.param_str="",$root.caffe.PythonParameter.prototype.share_in_parallel=!1,$root.caffe.RecurrentParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.RecurrentParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.num_output=e.uint32();break;case 2:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 3:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.debug_info=e.bool();break;case 5:r.expose_hidden=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.RecurrentParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"num_output":a.num_output=e.integer();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"debug_info":a.debug_info=e.boolean();break;case"expose_hidden":a.expose_hidden=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.RecurrentParameter.prototype.num_output=0,$root.caffe.RecurrentParameter.prototype.weight_filler=null,$root.caffe.RecurrentParameter.prototype.bias_filler=null,$root.caffe.RecurrentParameter.prototype.debug_info=!1,$root.caffe.RecurrentParameter.prototype.expose_hidden=!1,$root.caffe.ReductionParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReductionParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.operation=e.int32();break;case 2:r.axis=e.int32();break;case 3:r.coeff=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReductionParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"operation":a.operation=e.enum($root.caffe.ReductionParameter.ReductionOp);break;case"axis":a.axis=e.integer();break;case"coeff":a.coeff=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ReductionParameter.prototype.operation=1,$root.caffe.ReductionParameter.prototype.axis=0,$root.caffe.ReductionParameter.prototype.coeff=1,$root.caffe.ReductionParameter.ReductionOp={SUM:1,ASUM:2,SUMSQ:3,MEAN:4},$root.caffe.ReLUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReLUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.negative_slope=e.float();break;case 2:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReLUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"negative_slope":a.negative_slope=e.float();break;case"engine":a.engine=e.enum($root.caffe.ReLUParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.ReLUParameter.prototype.negative_slope=0,$root.caffe.ReLUParameter.prototype.engine=0,$root.caffe.ReLUParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.ReshapeParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ReshapeParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.shape=$root.caffe.BlobShape.decode(e,e.uint32());break;case 2:r.axis=e.int32();break;case 3:r.num_axes=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ReshapeParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"shape":a.shape=$root.caffe.BlobShape.decodeText(e,!0);break;case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.ReshapeParameter.prototype.shape=null,$root.caffe.ReshapeParameter.prototype.axis=0,$root.caffe.ReshapeParameter.prototype.num_axes=-1,$root.caffe.ScaleParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ScaleParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.num_axes=e.int32();break;case 3:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 4:r.bias_term=e.bool();break;case 5:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ScaleParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"num_axes":a.num_axes=e.integer();break;case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_term":a.bias_term=e.boolean();break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.ScaleParameter.prototype.axis=1,$root.caffe.ScaleParameter.prototype.num_axes=1,$root.caffe.ScaleParameter.prototype.filler=null,$root.caffe.ScaleParameter.prototype.bias_term=!1,$root.caffe.ScaleParameter.prototype.bias_filler=null,$root.caffe.SigmoidParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SigmoidParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SigmoidParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.SigmoidParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.SigmoidParameter.prototype.engine=0,$root.caffe.SigmoidParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.SliceParameter=class{constructor(){this.slice_point=[]}static decode(e,a){const r=new $root.caffe.SliceParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 3:r.axis=e.int32();break;case 2:r.slice_point=e.array(r.slice_point,(()=>e.uint32()),a);break;case 1:r.slice_dim=e.uint32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SliceParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"slice_point":e.array(a.slice_point,(()=>e.integer()));break;case"slice_dim":a.slice_dim=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SliceParameter.prototype.axis=1,$root.caffe.SliceParameter.prototype.slice_dim=1,$root.caffe.SoftmaxParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SoftmaxParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;case 2:r.axis=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SoftmaxParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.SoftmaxParameter.Engine);break;case"axis":a.axis=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.SoftmaxParameter.prototype.engine=0,$root.caffe.SoftmaxParameter.prototype.axis=1,$root.caffe.SoftmaxParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.SwishParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SwishParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.beta=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SwishParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"beta":a.beta=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.SwishParameter.prototype.beta=1,$root.caffe.TanHParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.TanHParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TanHParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"engine":a.engine=e.enum($root.caffe.TanHParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.TanHParameter.prototype.engine=0,$root.caffe.TanHParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.TileParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.TileParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.axis=e.int32();break;case 2:r.tiles=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.TileParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"axis":a.axis=e.integer();break;case"tiles":a.tiles=e.integer();break;default:e.field(r,a)}}return a}},$root.caffe.TileParameter.prototype.axis=1,$root.caffe.TileParameter.prototype.tiles=0,$root.caffe.ThresholdParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.ThresholdParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.threshold=e.float();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.ThresholdParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"threshold":a.threshold=e.float();break;default:e.field(r,a)}}return a}},$root.caffe.ThresholdParameter.prototype.threshold=0,$root.caffe.WindowDataParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.WindowDataParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.source=e.string();break;case 2:r.scale=e.float();break;case 3:r.mean_file=e.string();break;case 4:r.batch_size=e.uint32();break;case 5:r.crop_size=e.uint32();break;case 6:r.mirror=e.bool();break;case 7:r.fg_threshold=e.float();break;case 8:r.bg_threshold=e.float();break;case 9:r.fg_fraction=e.float();break;case 10:r.context_pad=e.uint32();break;case 11:r.crop_mode=e.string();break;case 12:r.cache_images=e.bool();break;case 13:r.root_folder=e.string();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.WindowDataParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"source":a.source=e.string();break;case"scale":a.scale=e.float();break;case"mean_file":a.mean_file=e.string();break;case"batch_size":a.batch_size=e.integer();break;case"crop_size":a.crop_size=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"fg_threshold":a.fg_threshold=e.float();break;case"bg_threshold":a.bg_threshold=e.float();break;case"fg_fraction":a.fg_fraction=e.float();break;case"context_pad":a.context_pad=e.integer();break;case"crop_mode":a.crop_mode=e.string();break;case"cache_images":a.cache_images=e.boolean();break;case"root_folder":a.root_folder=e.string();break;default:e.field(r,a)}}return a}},$root.caffe.WindowDataParameter.prototype.source="",$root.caffe.WindowDataParameter.prototype.scale=1,$root.caffe.WindowDataParameter.prototype.mean_file="",$root.caffe.WindowDataParameter.prototype.batch_size=0,$root.caffe.WindowDataParameter.prototype.crop_size=0,$root.caffe.WindowDataParameter.prototype.mirror=!1,$root.caffe.WindowDataParameter.prototype.fg_threshold=.5,$root.caffe.WindowDataParameter.prototype.bg_threshold=.5,$root.caffe.WindowDataParameter.prototype.fg_fraction=.25,$root.caffe.WindowDataParameter.prototype.context_pad=0,$root.caffe.WindowDataParameter.prototype.crop_mode="warp",$root.caffe.WindowDataParameter.prototype.cache_images=!1,$root.caffe.WindowDataParameter.prototype.root_folder="",$root.caffe.SPPParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.SPPParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.pyramid_height=e.uint32();break;case 2:r.pool=e.int32();break;case 6:r.engine=e.int32();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.SPPParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"pyramid_height":a.pyramid_height=e.integer();break;case"pool":a.pool=e.enum($root.caffe.SPPParameter.PoolMethod);break;case"engine":a.engine=e.enum($root.caffe.SPPParameter.Engine);break;default:e.field(r,a)}}return a}},$root.caffe.SPPParameter.prototype.pyramid_height=0,$root.caffe.SPPParameter.prototype.pool=0,$root.caffe.SPPParameter.prototype.engine=0,$root.caffe.SPPParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.SPPParameter.Engine={DEFAULT:0,CAFFE:1,CUDNN:2},$root.caffe.V1LayerParameter=class{constructor(){this.bottom=[],this.top=[],this.include=[],this.exclude=[],this.blobs=[],this.param=[],this.blob_share_mode=[],this.blobs_lr=[],this.weight_decay=[],this.loss_weight=[]}static decode(e,a){const r=new $root.caffe.V1LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 2:r.bottom.push(e.string());break;case 3:r.top.push(e.string());break;case 4:r.name=e.string();break;case 32:r.include.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 33:r.exclude.push($root.caffe.NetStateRule.decode(e,e.uint32()));break;case 5:r.type=e.int32();break;case 6:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 1001:r.param.push(e.string());break;case 1002:r.blob_share_mode=e.array(r.blob_share_mode,(()=>e.int32()),a);break;case 7:r.blobs_lr=e.floats(r.blobs_lr,a);break;case 8:r.weight_decay=e.floats(r.weight_decay,a);break;case 35:r.loss_weight=e.floats(r.loss_weight,a);break;case 27:r.accuracy_param=$root.caffe.AccuracyParameter.decode(e,e.uint32());break;case 23:r.argmax_param=$root.caffe.ArgMaxParameter.decode(e,e.uint32());break;case 9:r.concat_param=$root.caffe.ConcatParameter.decode(e,e.uint32());break;case 40:r.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decode(e,e.uint32());break;case 10:r.convolution_param=$root.caffe.ConvolutionParameter.decode(e,e.uint32());break;case 11:r.data_param=$root.caffe.DataParameter.decode(e,e.uint32());break;case 12:r.dropout_param=$root.caffe.DropoutParameter.decode(e,e.uint32());break;case 26:r.dummy_data_param=$root.caffe.DummyDataParameter.decode(e,e.uint32());break;case 24:r.eltwise_param=$root.caffe.EltwiseParameter.decode(e,e.uint32());break;case 41:r.exp_param=$root.caffe.ExpParameter.decode(e,e.uint32());break;case 13:r.hdf5_data_param=$root.caffe.HDF5DataParameter.decode(e,e.uint32());break;case 14:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;case 29:r.hinge_loss_param=$root.caffe.HingeLossParameter.decode(e,e.uint32());break;case 15:r.image_data_param=$root.caffe.ImageDataParameter.decode(e,e.uint32());break;case 16:r.infogain_loss_param=$root.caffe.InfogainLossParameter.decode(e,e.uint32());break;case 17:r.inner_product_param=$root.caffe.InnerProductParameter.decode(e,e.uint32());break;case 18:r.lrn_param=$root.caffe.LRNParameter.decode(e,e.uint32());break;case 22:r.memory_data_param=$root.caffe.MemoryDataParameter.decode(e,e.uint32());break;case 34:r.mvn_param=$root.caffe.MVNParameter.decode(e,e.uint32());break;case 19:r.pooling_param=$root.caffe.PoolingParameter.decode(e,e.uint32());break;case 21:r.power_param=$root.caffe.PowerParameter.decode(e,e.uint32());break;case 30:r.relu_param=$root.caffe.ReLUParameter.decode(e,e.uint32());break;case 38:r.sigmoid_param=$root.caffe.SigmoidParameter.decode(e,e.uint32());break;case 39:r.softmax_param=$root.caffe.SoftmaxParameter.decode(e,e.uint32());break;case 31:r.slice_param=$root.caffe.SliceParameter.decode(e,e.uint32());break;case 37:r.tanh_param=$root.caffe.TanHParameter.decode(e,e.uint32());break;case 25:r.threshold_param=$root.caffe.ThresholdParameter.decode(e,e.uint32());break;case 20:r.window_data_param=$root.caffe.WindowDataParameter.decode(e,e.uint32());break;case 36:r.transform_param=$root.caffe.TransformationParameter.decode(e,e.uint32());break;case 42:r.loss_param=$root.caffe.LossParameter.decode(e,e.uint32());break;case 1:r.layer=$root.caffe.V0LayerParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.V1LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"bottom":e.array(a.bottom,(()=>e.string()));break;case"top":e.array(a.top,(()=>e.string()));break;case"name":a.name=e.string();break;case"include":a.include.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"exclude":a.exclude.push($root.caffe.NetStateRule.decodeText(e,!0));break;case"type":a.type=e.enum($root.caffe.V1LayerParameter.LayerType);break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"param":e.array(a.param,(()=>e.string()));break;case"blob_share_mode":e.array(a.blob_share_mode,(()=>e.enum($root.caffe.V1LayerParameter.DimCheckMode)));break;case"blobs_lr":e.array(a.blobs_lr,(()=>e.float()));break;case"weight_decay":e.array(a.weight_decay,(()=>e.float()));break;case"loss_weight":e.array(a.loss_weight,(()=>e.float()));break;case"accuracy_param":a.accuracy_param=$root.caffe.AccuracyParameter.decodeText(e,!0);break;case"argmax_param":a.argmax_param=$root.caffe.ArgMaxParameter.decodeText(e,!0);break;case"concat_param":a.concat_param=$root.caffe.ConcatParameter.decodeText(e,!0);break;case"contrastive_loss_param":a.contrastive_loss_param=$root.caffe.ContrastiveLossParameter.decodeText(e,!0);break;case"convolution_param":a.convolution_param=$root.caffe.ConvolutionParameter.decodeText(e,!0);break;case"data_param":a.data_param=$root.caffe.DataParameter.decodeText(e,!0);break;case"dropout_param":a.dropout_param=$root.caffe.DropoutParameter.decodeText(e,!0);break;case"dummy_data_param":a.dummy_data_param=$root.caffe.DummyDataParameter.decodeText(e,!0);break;case"eltwise_param":a.eltwise_param=$root.caffe.EltwiseParameter.decodeText(e,!0);break;case"exp_param":a.exp_param=$root.caffe.ExpParameter.decodeText(e,!0);break;case"hdf5_data_param":a.hdf5_data_param=$root.caffe.HDF5DataParameter.decodeText(e,!0);break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;case"hinge_loss_param":a.hinge_loss_param=$root.caffe.HingeLossParameter.decodeText(e,!0);break;case"image_data_param":a.image_data_param=$root.caffe.ImageDataParameter.decodeText(e,!0);break;case"infogain_loss_param":a.infogain_loss_param=$root.caffe.InfogainLossParameter.decodeText(e,!0);break;case"inner_product_param":a.inner_product_param=$root.caffe.InnerProductParameter.decodeText(e,!0);break;case"lrn_param":a.lrn_param=$root.caffe.LRNParameter.decodeText(e,!0);break;case"memory_data_param":a.memory_data_param=$root.caffe.MemoryDataParameter.decodeText(e,!0);break;case"mvn_param":a.mvn_param=$root.caffe.MVNParameter.decodeText(e,!0);break;case"pooling_param":a.pooling_param=$root.caffe.PoolingParameter.decodeText(e,!0);break;case"power_param":a.power_param=$root.caffe.PowerParameter.decodeText(e,!0);break;case"relu_param":a.relu_param=$root.caffe.ReLUParameter.decodeText(e,!0);break;case"sigmoid_param":a.sigmoid_param=$root.caffe.SigmoidParameter.decodeText(e,!0);break;case"softmax_param":a.softmax_param=$root.caffe.SoftmaxParameter.decodeText(e,!0);break;case"slice_param":a.slice_param=$root.caffe.SliceParameter.decodeText(e,!0);break;case"tanh_param":a.tanh_param=$root.caffe.TanHParameter.decodeText(e,!0);break;case"threshold_param":a.threshold_param=$root.caffe.ThresholdParameter.decodeText(e,!0);break;case"window_data_param":a.window_data_param=$root.caffe.WindowDataParameter.decodeText(e,!0);break;case"transform_param":a.transform_param=$root.caffe.TransformationParameter.decodeText(e,!0);break;case"loss_param":a.loss_param=$root.caffe.LossParameter.decodeText(e,!0);break;case"layer":a.layer=$root.caffe.V0LayerParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.V1LayerParameter.prototype.name="",$root.caffe.V1LayerParameter.prototype.type=0,$root.caffe.V1LayerParameter.prototype.accuracy_param=null,$root.caffe.V1LayerParameter.prototype.argmax_param=null,$root.caffe.V1LayerParameter.prototype.concat_param=null,$root.caffe.V1LayerParameter.prototype.contrastive_loss_param=null,$root.caffe.V1LayerParameter.prototype.convolution_param=null,$root.caffe.V1LayerParameter.prototype.data_param=null,$root.caffe.V1LayerParameter.prototype.dropout_param=null,$root.caffe.V1LayerParameter.prototype.dummy_data_param=null,$root.caffe.V1LayerParameter.prototype.eltwise_param=null,$root.caffe.V1LayerParameter.prototype.exp_param=null,$root.caffe.V1LayerParameter.prototype.hdf5_data_param=null,$root.caffe.V1LayerParameter.prototype.hdf5_output_param=null,$root.caffe.V1LayerParameter.prototype.hinge_loss_param=null,$root.caffe.V1LayerParameter.prototype.image_data_param=null,$root.caffe.V1LayerParameter.prototype.infogain_loss_param=null,$root.caffe.V1LayerParameter.prototype.inner_product_param=null,$root.caffe.V1LayerParameter.prototype.lrn_param=null,$root.caffe.V1LayerParameter.prototype.memory_data_param=null,$root.caffe.V1LayerParameter.prototype.mvn_param=null,$root.caffe.V1LayerParameter.prototype.pooling_param=null,$root.caffe.V1LayerParameter.prototype.power_param=null,$root.caffe.V1LayerParameter.prototype.relu_param=null,$root.caffe.V1LayerParameter.prototype.sigmoid_param=null,$root.caffe.V1LayerParameter.prototype.softmax_param=null,$root.caffe.V1LayerParameter.prototype.slice_param=null,$root.caffe.V1LayerParameter.prototype.tanh_param=null,$root.caffe.V1LayerParameter.prototype.threshold_param=null,$root.caffe.V1LayerParameter.prototype.window_data_param=null,$root.caffe.V1LayerParameter.prototype.transform_param=null,$root.caffe.V1LayerParameter.prototype.loss_param=null,$root.caffe.V1LayerParameter.prototype.layer=null,$root.caffe.V1LayerParameter.LayerType={NONE:0,ABSVAL:35,ACCURACY:1,ARGMAX:30,BNLL:2,CONCAT:3,CONTRASTIVE_LOSS:37,CONVOLUTION:4,DATA:5,DECONVOLUTION:39,DROPOUT:6,DUMMY_DATA:32,EUCLIDEAN_LOSS:7,ELTWISE:25,EXP:38,FLATTEN:8,HDF5_DATA:9,HDF5_OUTPUT:10,HINGE_LOSS:28,IM2COL:11,IMAGE_DATA:12,INFOGAIN_LOSS:13,INNER_PRODUCT:14,LRN:15,MEMORY_DATA:29,MULTINOMIAL_LOGISTIC_LOSS:16,MVN:34,POOLING:17,POWER:26,RELU:18,SIGMOID:19,SIGMOID_CROSS_ENTROPY_LOSS:27,SILENCE:36,SOFTMAX:20,SOFTMAX_LOSS:21,SPLIT:22,SLICE:33,TANH:23,WINDOW_DATA:24,THRESHOLD:31},$root.caffe.V1LayerParameter.DimCheckMode={STRICT:0,PERMISSIVE:1},$root.caffe.V0LayerParameter=class{constructor(){this.blobs=[],this.blobs_lr=[],this.weight_decay=[]}static decode(e,a){const r=new $root.caffe.V0LayerParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.type=e.string();break;case 3:r.num_output=e.uint32();break;case 4:r.biasterm=e.bool();break;case 5:r.weight_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 6:r.bias_filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 7:r.pad=e.uint32();break;case 8:r.kernelsize=e.uint32();break;case 9:r.group=e.uint32();break;case 10:r.stride=e.uint32();break;case 11:r.pool=e.int32();break;case 12:r.dropout_ratio=e.float();break;case 13:r.local_size=e.uint32();break;case 14:r.alpha=e.float();break;case 15:r.beta=e.float();break;case 22:r.k=e.float();break;case 16:r.source=e.string();break;case 17:r.scale=e.float();break;case 18:r.meanfile=e.string();break;case 19:r.batchsize=e.uint32();break;case 20:r.cropsize=e.uint32();break;case 21:r.mirror=e.bool();break;case 50:r.blobs.push($root.caffe.BlobProto.decode(e,e.uint32()));break;case 51:r.blobs_lr=e.floats(r.blobs_lr,a);break;case 52:r.weight_decay=e.floats(r.weight_decay,a);break;case 53:r.rand_skip=e.uint32();break;case 54:r.det_fg_threshold=e.float();break;case 55:r.det_bg_threshold=e.float();break;case 56:r.det_fg_fraction=e.float();break;case 58:r.det_context_pad=e.uint32();break;case 59:r.det_crop_mode=e.string();break;case 60:r.new_num=e.int32();break;case 61:r.new_channels=e.int32();break;case 62:r.new_height=e.int32();break;case 63:r.new_width=e.int32();break;case 64:r.shuffle_images=e.bool();break;case 65:r.concat_dim=e.uint32();break;case 1001:r.hdf5_output_param=$root.caffe.HDF5OutputParameter.decode(e,e.uint32());break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.V0LayerParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"name":a.name=e.string();break;case"type":a.type=e.string();break;case"num_output":a.num_output=e.integer();break;case"biasterm":a.biasterm=e.boolean();break;case"weight_filler":a.weight_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"bias_filler":a.bias_filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"pad":a.pad=e.integer();break;case"kernelsize":a.kernelsize=e.integer();break;case"group":a.group=e.integer();break;case"stride":a.stride=e.integer();break;case"pool":a.pool=e.enum($root.caffe.V0LayerParameter.PoolMethod);break;case"dropout_ratio":a.dropout_ratio=e.float();break;case"local_size":a.local_size=e.integer();break;case"alpha":a.alpha=e.float();break;case"beta":a.beta=e.float();break;case"k":a.k=e.float();break;case"source":a.source=e.string();break;case"scale":a.scale=e.float();break;case"meanfile":a.meanfile=e.string();break;case"batchsize":a.batchsize=e.integer();break;case"cropsize":a.cropsize=e.integer();break;case"mirror":a.mirror=e.boolean();break;case"blobs":a.blobs.push($root.caffe.BlobProto.decodeText(e,!0));break;case"blobs_lr":e.array(a.blobs_lr,(()=>e.float()));break;case"weight_decay":e.array(a.weight_decay,(()=>e.float()));break;case"rand_skip":a.rand_skip=e.integer();break;case"det_fg_threshold":a.det_fg_threshold=e.float();break;case"det_bg_threshold":a.det_bg_threshold=e.float();break;case"det_fg_fraction":a.det_fg_fraction=e.float();break;case"det_context_pad":a.det_context_pad=e.integer();break;case"det_crop_mode":a.det_crop_mode=e.string();break;case"new_num":a.new_num=e.integer();break;case"new_channels":a.new_channels=e.integer();break;case"new_height":a.new_height=e.integer();break;case"new_width":a.new_width=e.integer();break;case"shuffle_images":a.shuffle_images=e.boolean();break;case"concat_dim":a.concat_dim=e.integer();break;case"hdf5_output_param":a.hdf5_output_param=$root.caffe.HDF5OutputParameter.decodeText(e,!0);break;default:e.field(r,a)}}return a}},$root.caffe.V0LayerParameter.prototype.name="",$root.caffe.V0LayerParameter.prototype.type="",$root.caffe.V0LayerParameter.prototype.num_output=0,$root.caffe.V0LayerParameter.prototype.biasterm=!0,$root.caffe.V0LayerParameter.prototype.weight_filler=null,$root.caffe.V0LayerParameter.prototype.bias_filler=null,$root.caffe.V0LayerParameter.prototype.pad=0,$root.caffe.V0LayerParameter.prototype.kernelsize=0,$root.caffe.V0LayerParameter.prototype.group=1,$root.caffe.V0LayerParameter.prototype.stride=1,$root.caffe.V0LayerParameter.prototype.pool=0,$root.caffe.V0LayerParameter.prototype.dropout_ratio=.5,$root.caffe.V0LayerParameter.prototype.local_size=5,$root.caffe.V0LayerParameter.prototype.alpha=1,$root.caffe.V0LayerParameter.prototype.beta=.75,$root.caffe.V0LayerParameter.prototype.k=1,$root.caffe.V0LayerParameter.prototype.source="",$root.caffe.V0LayerParameter.prototype.scale=1,$root.caffe.V0LayerParameter.prototype.meanfile="",$root.caffe.V0LayerParameter.prototype.batchsize=0,$root.caffe.V0LayerParameter.prototype.cropsize=0,$root.caffe.V0LayerParameter.prototype.mirror=!1,$root.caffe.V0LayerParameter.prototype.rand_skip=0,$root.caffe.V0LayerParameter.prototype.det_fg_threshold=.5,$root.caffe.V0LayerParameter.prototype.det_bg_threshold=.5,$root.caffe.V0LayerParameter.prototype.det_fg_fraction=.25,$root.caffe.V0LayerParameter.prototype.det_context_pad=0,$root.caffe.V0LayerParameter.prototype.det_crop_mode="warp",$root.caffe.V0LayerParameter.prototype.new_num=0,$root.caffe.V0LayerParameter.prototype.new_channels=0,$root.caffe.V0LayerParameter.prototype.new_height=0,$root.caffe.V0LayerParameter.prototype.new_width=0,$root.caffe.V0LayerParameter.prototype.shuffle_images=!1,$root.caffe.V0LayerParameter.prototype.concat_dim=1,$root.caffe.V0LayerParameter.prototype.hdf5_output_param=null,$root.caffe.V0LayerParameter.PoolMethod={MAX:0,AVE:1,STOCHASTIC:2},$root.caffe.PReLUParameter=class{constructor(){}static decode(e,a){const r=new $root.caffe.PReLUParameter,t=e.next(a);for(;e.end(t);){const a=e.uint32();switch(a>>>3){case 1:r.filler=$root.caffe.FillerParameter.decode(e,e.uint32());break;case 2:r.channel_shared=e.bool();break;default:e.skipType(7&a)}}return r}static decodeText(e){const a=new $root.caffe.PReLUParameter;for(e.start();!e.end();){const r=e.tag();switch(r){case"filler":a.filler=$root.caffe.FillerParameter.decodeText(e,!0);break;case"channel_shared":a.channel_shared=e.boolean();break;default:e.field(r,a)}}return a}},$root.caffe.PReLUParameter.prototype.filler=null,$root.caffe.PReLUParameter.prototype.channel_shared=!1; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe.js new file mode 100644 index 0000000000000000000000000000000000000000..3396d443340ff0489750ec2a4f1cd7e3edd0ce5d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe.js @@ -0,0 +1 @@ +var caffe=caffe||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");caffe.ModelFactory=class{match(t){const e=t.identifier,a=e.split(".").pop().toLowerCase();if("caffemodel"==a)return!0;if("pbtxt"==a||"prototxt"==a){if("saved_model.pbtxt"==e||"saved_model.prototxt"==e||e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const a=t.tags("pbtxt");if(a.has("layer")||a.has("layers")||a.has("net")||a.has("train_net")||a.has("net_param"))return!0}if("pt"==a){const e=t.buffer,a=[138,10,108,252,156,70,249,32,106,168,80,25];if(e&&e.length>14&&128==e[0]&&a.every(((t,a)=>t==e[a+2])))return!1;if(e&&e.length>2&&80==e[0]&&75==e[1])return!1;const n=t.tags("pbtxt");if(n.has("layer")||n.has("layers")||n.has("net")||n.has("train_net")||n.has("net_param"))return!0}return!1}open(t,e){return e.require("./caffe-proto").then((()=>(caffe.proto=protobuf.get("caffe").caffe,caffe.Metadata.open(e).then((a=>{const n=t.identifier.split(".").pop();if("pbtxt"==n||"prototxt"==n||"pt"==n){const n=t.tags("pbtxt");if(n.has("net")||n.has("train_net")||n.has("net_param"))try{const n=protobuf.TextReader.create(t.text);n.field=function(t,e){if(!(e instanceof caffe.proto.SolverParameter))throw new Error("Unknown field '"+t+"'"+this.location());e[t]=this.skip()};const r=caffe.proto.SolverParameter.decodeText(n);if(r.net_param)return this._openNetParameter(a,r.net_param,e);if(r.net||r.train_net){let n=r.net||r.train_net;return n=n.split("/").pop(),t.request(n,"utf-8").then((n=>this._openNetParameterText(a,t.identifier,n,e))).catch((t=>{if(t){const e=t&&t.message?t.message:t.toString();throw new caffe.Error("Failed to load '"+n+"' ("+e.replace(/\.$/,"")+").")}}))}}catch(t){}return this._openNetParameterText(a,t.identifier,t.text,e)}return this._openNetParameterBuffer(a,t.identifier,t.buffer,e)})))))}_openNetParameterBuffer(t,e,a,n,r,s){try{const e=protobuf.Reader.create(a),i=caffe.proto.NetParameter.decode(e);return this._openNetParameter(t,i,n,r,s)}catch(t){throw new caffe.Error("File format is not caffe.NetParameter ("+t.message+") in '"+e+"'.")}}_openNetParameterText(t,e,a,n){try{const e=protobuf.TextReader.create(a);e.field=function(t,a){const n=a.constructor.name;if(!t.endsWith("_param")||"LayerParameter"!=n&&"V1LayerParameter"!=n&&"V0LayerParameter"!=n){if(!a.constructor.name.endsWith("Parameter")&&"ParamSpec"!==a.constructor.name)throw new Error("Unknown field '"+t+"'"+this.location());a[t]?(Array.isArray(a[t])||(a[t]=[a[t]]),a[t].push(this.skip())):a[t]=this.skip()}else a[t]=caffe.ModelFactory._decodeText(e)},e.enum=function(t){const e=this.read();if(!Object.prototype.hasOwnProperty.call(t,e)){const t=Number.parseInt(e,10);return Number.isNaN(e-t)?e:t}return t[e]};const r=caffe.proto.NetParameter.decodeText(e);return this._openNetParameter(t,r,n)}catch(t){throw new caffe.Error("File text format is not caffe.NetParameter ("+t.message+") in '"+e+"'.")}}_openNetParameter(t,e,a){try{return new caffe.Model(t,e)}catch(t){throw a.exception(t,!1),new caffe.Error(t.message)}}static _decodeText(t){const e={};for(t.start();!t.end();){const a=t.tag(),n=t.skip();e[a]?(Array.isArray(e[a])||(e[a]=[e[a]]),e[a].push(n)):e[a]=n}return e}},caffe.Model=class{constructor(t,e){this._name=e.name,e.layers&&e.layers.length>0?e.layers.every((t=>Object.prototype.hasOwnProperty.call(t,"layer")))?(this._version=0,e.layer=e.layers):(this._version=1,e.layer=e.layers):e.layer&&e.layer.length>0&&(this._version=2),this._graphs=[];const a=new Set;for(const t of e.layer)for(const e of t.include)void 0!==e.phase&&a.add(e.phase);0===a.size&&a.add(-1);for(const n of a)this._graphs.push(new caffe.Graph(t,n,e,this._version))}get format(){return"Caffe"+(this._version?" v"+this._version.toString():"")}get graphs(){return this._graphs}},caffe.Graph=class{constructor(t,e,a,n){switch(e){case 0:this._phase="TRAIN";break;case 1:this._phase="TEST";break;case-1:this._phase="";break;default:this._phase=e.toString()}this._nodes=[],this._inputs=[],this._outputs=[];for(const t of a.layer)t.input=t.bottom.slice(0),t.output=t.top.slice(0),t.chain=[];const r=[];for(const t of a.layer)(-1===e||t.include.every((t=>t.phase===e)))&&r.push(t);const s={};let i=0;for(const t of r)t.input=t.input.map((t=>s[t]?s[t]:t)),t.output=t.output.map((t=>(s[t]=s[t]?t+"\n"+i.toString():t,s[t]))),i++;const o=new Set;for(const t of r)for(const e of t.output)o.add(e);const c=[];for(const t of r)for(const e of t.input)o.has(e)||c.push(e);const u=[];let p=null,f=null;for(;r.length>0;){let t=r.shift();if(1==t.output.length&&1==t.input.length&&t.output[0].split("\n").shift()==t.input[0].split("\n").shift()&&p&&f==t.output[0].split("\n").shift())p.chain=p.chain||[],p.chain.push(t);else{if(("Input"==t.type||"Data"==t.type)&&0==t.input.length&&1==t.output.length&&t.input_param&&t.input_param.shape&&1==t.input_param.shape.length&&t.input_param.shape[0].dim){const e=new caffe.TensorType(null,new caffe.TensorShape(t.input_param.shape[0].dim));this._inputs.push(new caffe.Parameter(t.output[0],[new caffe.Argument(t.output[0],e)])),t=null}t&&(u.push(t),p=null,f=null,1==t.output.length&&(p=t,f=t.output[0].split("\n").shift()))}}if(a.input)for(let t=0;tt.name===e)))continue;let n=null;if(a.input_shape&&t=r&&(n=new caffe.TensorType(null,new caffe.TensorShape(a.input_dim.slice(r,r+4)))),this._inputs.push(new caffe.Parameter(e,[new caffe.Argument(e,n,null)]))}for(const e of u){const a=new caffe.Node(t,e,n);if(e.chain&&e.chain.length>0)for(const r of e.chain)a.chain.push(new caffe.Node(t,r,n));this._nodes.push(a)}0===this._inputs.length&&1===c.length&&this._inputs.push(new caffe.Parameter(c[0],[new caffe.Argument(c[0],null)]))}get name(){return this._phase}get type(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},caffe.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},caffe.Argument=class{constructor(t,e,a){if("string"!=typeof t)throw new caffe.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=a||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},caffe.Node=class{constructor(t,e,a){switch(this._metadata=t,this._chain=[],this._attributes=[],a){case 0:this._name=e.layer.name,this._type=e.layer.type;break;case 1:{this._name=e.name;const t=e.type;if(void 0===t)this._type="?";else{if(!caffe.Node._typeMap){caffe.Node._typeMap={};const t={BNLL:"BNLL",HDF5:"HDF5",LRN:"LRN",RELU:"ReLU",TANH:"TanH",ARGMAX:"ArgMax",MVN:"MVN",ABSVAL:"AbsVal"};for(const e of Object.keys(caffe.proto.V1LayerParameter.LayerType)){const a=caffe.proto.V1LayerParameter.LayerType[e];caffe.Node._typeMap[a]=e.split("_").map((e=>t[e]||e.substring(0,1)+e.substring(1).toLowerCase())).join("")}}this._type=caffe.Node._typeMap[t]||t.toString()}break}case 2:this._name=e.name,this._type=e.type}let n=[];switch(a){case 0:for(const a of Object.keys(e.layer))"type"!=a&&"name"!=a&&"blobs"!=a&&"blobs_lr"!=a&&this._attributes.push(new caffe.Attribute(t.attribute(this.type,a),a,e.layer[a]));n=e.layer.blobs.map((t=>new caffe.Tensor(t)));break;case 1:case 2:for(const a of Object.keys(e))if(a.endsWith("_param")||"transform_param"==a){const n=e[a];let r=this._type;"Deconvolution"==r&&(r="Convolution");const s=Object.getPrototypeOf(n);for(const e of Object.keys(n)){const a=s[e],r=n[e];r==a||Array.isArray(r)&&Array.isArray(a)&&0==r.length&&0==a.length||this._attributes.push(new caffe.Attribute(t.attribute(this.type,e),e,r))}}e.include&&e.include.length>0&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"include"),"include",e.include)),e.exclude&&e.exclude.length>0&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"exclude"),"exclude",e.exclude)),"Data"==this._type&&e.input_param&&e.input_param.shape&&this._attributes.push(new caffe.Attribute(this._metadata.attribute(this.type,"shape"),"shape",e.input_param.shape)),n=e.blobs.map((t=>new caffe.Tensor(t)))}const r=this._metadata.type(this.type);this._inputs=[];const s=e.input.concat(n);let i=0;if(r&&r.inputs)for(const t of r.inputs)if(i""!==e||"optional"!=t.option)).map((t=>t instanceof caffe.Tensor?new caffe.Argument("",t.type,t):new caffe.Argument(t,null,null))))),i+=e}this._inputs=this._inputs.concat(s.slice(i).map((t=>new caffe.Parameter(i.toString(),[t instanceof caffe.Tensor?new caffe.Argument("",t.type,t):new caffe.Argument(t,null,null)])))),this._outputs=[];const o=e.output;let c=0;if(r&&r.outputs)for(const t of r.outputs)if(cnew caffe.Argument(t,null,null))))),c+=e}this._outputs=this._outputs.concat(o.slice(c).map(((t,e)=>new caffe.Parameter((c+e).toString(),[new caffe.Argument(t,null,null)]))))}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}},caffe.Attribute=class{constructor(t,e,a){if(this._name=e,this._value=a,a instanceof caffe.proto.BlobShape&&(this._value=new caffe.TensorShape(a.dim)),t)if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){const e=t.default;(this._value==e||Array.isArray(this._value)&&Array.isArray(e)&&this._value.length==e.length&&this._value.every(((t,a)=>t==e[a])))&&(this._visible=!1)}}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},caffe.Tensor=class{constructor(t){this._blob=t;let e=[];Object.prototype.hasOwnProperty.call(t,"num")&&Object.prototype.hasOwnProperty.call(t,"channels")&&Object.prototype.hasOwnProperty.call(t,"width")&&Object.prototype.hasOwnProperty.call(t,"height")?(1!=t.num&&e.push(t.num),1!=t.channels&&e.push(t.channels),1!=t.width&&e.push(t.width),1!=t.height&&e.push(t.height)):Object.prototype.hasOwnProperty.call(t,"shape")&&(e=t.shape.dim);let a="?";t.data.length>0?(a="float32",this._data=t.data):t.double_data.length>0&&(a="float64",this._data=t.double_data),this._type=new caffe.TensorType(a,new caffe.TensorShape(e))}get kind(){return"Blob"}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return t.data=this._data,t.dimensions=this.type.shape.dimensions,this._data||(t.state="Tensor data is empty."),t}_decode(t,e){const a=[],n=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return a.push("..."),a;a.push(t.data[t.index]),t.index++,t.count++}else for(let r=0;rt.limit)return a.push("..."),a;a.push(this._decode(t,e+1))}return a}},caffe.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},caffe.TensorShape=class{constructor(t){this._dimensions=t.map((t=>t&&long.Long.isLong(t)?t.toNumber():t))}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},caffe.Metadata=class{static open(t){return caffe.Metadata._metadata?Promise.resolve(caffe.Metadata._metadata):t.request(null,"caffe-metadata.json","utf-8").then((t=>(caffe.Metadata._metadata=new caffe.Metadata(t),caffe.Metadata._metadata))).catch((()=>(caffe.Metadata._metadata=new caffe.Metadata(null),caffe.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},caffe.Error=class extends Error{constructor(t){super(t),this.name="Error loading Caffe model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=caffe.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..072a1ec57b9ae6e7fd010eaf4303dac8f4fed82e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-metadata.json @@ -0,0 +1 @@ +[{"name":"Conv","schema":{"attributes":[{"default":0,"name":"pad"},{"default":1,"name":"stride"},{"name":"exhaustive_search","type":"boolean","visible":false}],"category":"Layer","description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"ConvTranspose","schema":{"attributes":[{"description":"Should the legacy padding be VALID or SAME. When used, pads should not be used.","name":"legacy_pad","option":"optional","type":"int64"},{"description":"Desired kernel size. If left at default the kernel size will be inferred from the input $filter$ blob.","name":"kernels","option":"optional","type":"int64[]"},{"description":"Controls the stride of the kernel as it traverses the input blob.","name":"strides","option":"optional","type":"int64[]"},{"description":"Controls the amount of padding applied to the input feature map before computation.","name":"pads","option":"optional","type":"int64[]"},{"description":"","name":"adjs","option":"optional","type":"int64[]"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"},{"default":0,"description":"","name":"shared_buffer","option":"optional","type":"int64"},{"default":false,"description":"","name":"no_bias","option":"optional","type":"boolean"}],"category":"Layer","description":"\nThe ConvTranspose op takes an input data tensor $X$, an input weight tensor $filter$, and optionally an input bias tensor $bias$. It then computes the transposed convolution, sometimes referred to as deconvolution, and produces a single output tensor $Y$. The hyperparameters of the op such as kernel size, stride, and padding are specified as args. At each stride, the filter is deconvolved with a subset of $X$ and the $bias$ is added. This is done throughout the input data until the output computation is complete.\n\nThe output shapes are computed as follows. The number of channels in the output feature map is the number of kernels specified in the filter blob. The spatial height and width are computed as:\n\n$$H_{out} = (H_{in}-1)*strides[0] - 2*pads[0] + kernels[0]$$\n\n\n$$W_{out} = (W_{in}-1)*strides[1] - 2*pads[1] + kernels[1]$$\n\nNote on the implementation layout: conv_transpose_op_impl.h is the templated implementation of the conv_transpose_op.h file, which is why they are separate files. Also, in the implementation this operator inherits from the *ConvTransposeUnpoolOpBase* operator.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_op.h\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_op.cc\n- https://github.com/pytorch/pytorch/tree/master/caffe2/operators/conv_transpose_unpool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConvTranspose\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernels=[2,2],\n pads=[4,4,4,4],\n strides=[2,2]\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(2,3,5,5).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create filter: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,2,2).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (2, 3, 5, 5)\nFilter shape: (3, 1, 2, 2)\nBias shape: (1,)\nY:\n [[[[0.53606427 0.5775447 ]\n [0.40148795 1.5188271 ]]]\n\n\n [[[1.9903406 3.2794335 ]\n [0.09960175 0.31917763]]]]\n\n```\n\n
    \n\n ","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be operated on.","name":"X"},{"description":"The filter blob, of shape $(M, C_{out}, K_H, K_W)$, containing the filters to be used in the transposed convolution.","name":"filter"},{"description":"The bias blob, of length $C_{out}$, containing the biases for the operation, one bias per output channel. If not passed, biases assumed to be zeros.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the operation.","name":"Y"}],"support_level":"default"}},{"name":"FC","schema":{"attributes":[{"default":1,"description":"Describes the axis of the input data $X$. Defaults to one because in the common case when the input $X$ has shape $(M,K)$, the first axis encodes the batch size.","name":"axis","option":"optional","type":"int64"},{"default":1,"description":"Describes the axis of the input weight matrix $W$. Defaults to one because the first axis most likely describes the batch_size.","name":"axis_w","option":"optional","type":"int64"},{"default":false,"description":"Whether to use float-16 compute kernel.","name":"float16_compute","option":"optional","type":"boolean"}],"category":"Layer","description":"\nThe FC operator computes an output $(Y)$ as a linear combination of the input data blob $(X)$ with a weight blob $(W)$ and bias blob $(b)$. More formally,\n\n$$Y = XW^T+b$$\n\nHere, $X$ is a matrix of shape $(M,K)$, $W$ is a matrix of shape $(N,K)$, $b$ is a vector of length $N$, and $Y$ is a matrix of shape $(M,N)$. $N$ can be thought of as the number of nodes in the layer, $M$ is the batch size, and $K$ is the number of features in an input observation.\n\n*NOTE: $X$ does not need to explicitly be a 2-dimensional matrix, however, if it is not it will be coerced into one. For an arbitrary $n$-dimensional tensor $X$, e.g. $[a_0, a_1, \\ldots ,a_{k-1}, a_k, \\ldots , a_{n-1}]$, where $a_i$ in $N$, and $k$ is the $axis$ arg provided, then $X$ will be coerced into a 2-dimensional tensor with dimensions $[a_0 * \\ldots * a_{k-1}, a_k * \\ldots * a_{n-1}]$. For the default case where axis=1, this means the $X$ tensor will be coerced into a 2D tensor of dimensions $[a_0, a_1 * \\ldots * a_{n-1}]$, where $a_0$ is often the batch size. In this situation, we must have $a_0 = M$ and $a_1 * \\ldots * a_{n-1} = K$. Lastly, even though $b$ is a vector of length $N$, it is copied and resized to shape $(M x N)$ implicitly, then added to each vector in the batch.*\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/fully_connected_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/fully_connected_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\n// In this example, our batch size is 1 (M=1), the input observation will have\n// 6 features (K=6), and the layer will have one hidden node (N=1). The\n// expected output is Y=7.\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FC\",\n [\"X\", \"W\", \"b\"],\n [\"Y\"]\n)\n\n// Create X: MxK\ndata = np.array([1,2,3,4,5,6]).astype(np.float32)\ndata = data[np.newaxis,:]\n\n// Create W: NxK\nweights = np.array(np.array([1,1/2.,1/3.,1/4.,1/5.,1/6.])).astype(np.float32)\nweights = weights[np.newaxis,:]\n\n// Create b: N\nbias = np.array([1.]).astype(np.float32)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"W\", weights)\nworkspace.FeedBlob(\"b\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nY:\n [[7.]]\n\n```\n\n
    \n\n","inputs":[{"description":"Input blob to be coerced into a 2D matrix of shape $(M,K)$, where $M$ is the batch size and $K$ is the number of features in a single observation.","name":"X"},{"description":"Input blob to be coerced into a 2D matrix of shape $(N,K)$ describing a fully connected weight matrix. Here, $K$ is the number of features in a single observation and $N$ is the number of nodes in the FC layer.","name":"W"},{"description":"Input blob containing vector of length $N$ which describes one bias for each node in the layer.","name":"b"}],"outputs":[{"description":"Output blob containing a 2D output matrix of shape $(M,N)$, where $M$ is the batch size and $N$ is the number of nodes in the layer. The output is calculated as $Y=XW^T+b$.","name":"Y"}],"support_level":"default"}},{"name":"Add","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Add\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[1 2]\n [3 4]]\nB:\n[[5 6]\n [7 8]]\nC:\n[[ 6 8]\n [10 12]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"Sum","schema":{"description":"\nElement-wise sum of each of the input tensors. The first input tensor can be used\nin-place as the output tensor, in which case the sum will be done in place and\nresults will be accumulated the first input tensor. All inputs and outputs must\nhave the same shape and data type.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_sum_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sum\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA: [[1. 2.]\n [3. 4.]]\nB: [[5. 6.]\n [7. 8.]]\nC: [[1. 2.]\n [3. 4.]]\n\n```\n\n
    \n\n
    \n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sum\",\n [\"A\", \"B\"],\n [\"A\"], // inplace\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2,5],[8,3,4]]).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.array([[9,5,6],[6,7,8]]).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"A after Sum:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA: [[1. 2. 5.]\n [8. 3. 4.]]\nB: [[9. 5. 6.]\n [6. 7. 8.]]\nA after Sum: [[10. 7. 11.]\n [14. 10. 12.]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First tensor to be added element-wise.","name":"A"},{"description":"*(type: Tensor``)* Second tensor to be added element-wise.","name":"B"},{"description":"First of the input tensors. Can be inplace.","name":"data_0"}],"outputs":[{"description":"*(type: Tensor``)* Sum of A and B.","name":"C"},{"description":"Output tensor. Same dimension as inputs.","name":"sum"}],"support_level":"default"}},{"name":"Mul","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mul\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"B\", np.array([[5,6],[7,8]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[1 2]\n [3 4]]\nB:\n[[5 6]\n [7 8]]\nC:\n[[ 5 12]\n [21 32]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"MatMul","schema":{"attributes":[{"default":1,"description":"Exclusive axis that divides the first and second dimension of matrix `A`.","name":"axis_a","option":"optional","type":"int64"},{"default":1,"description":"Exclusive axis that divides the first and second dimension of matrix `B`.","name":"axis_b","option":"optional","type":"int64"},{"default":0,"description":"Pass 1 to transpose `A` before multiplication and after the dimension adjustment using `axis_a`.","name":"trans_a","option":"optional","type":"int64"},{"default":0,"description":"Pass 1 to transpose `B` before multiplication and after the dimension adjustment using `axis_b`.","name":"trans_b","option":"optional","type":"int64"}],"description":"\nMatrix multiplication $Y = A * B$, where `A` has size (M x K), `B` has size\n(K x N), and `Y` will have a size (M x N). To transpose `A` or `B` before\nmultiplication, pass 1 to the `trans_a` and/or `trans_b` arguments, which\nseparate the first and second dimensions of the respective matrices using\n`axis_a` and `axis_b`.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/matmul_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MatMul\",\n [\"A\", \"B\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"B\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nA: [[1. 8. 3.]\n [6. 4. 4.]\n [5. 4. 7.]]\nB: [[4. 0. 3.]\n [3. 1. 1.]\n [8. 5. 8.]]\nY: [[52. 23. 35.]\n [68. 24. 54.]\n [88. 39. 75.]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* 2D matrix of size (M x K).","name":"A"},{"description":"*(type: Tensor``)* 2D matrix of size (K x N).","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* 2D matrix of size (M x N).","name":"Y"}],"support_level":"default"}},{"name":"Relu","schema":{"attributes":[{"name":"cudnn_exhaustive_search","type":"boolean","visible":false}],"category":"Activation","description":"\nApplies rectified linear unit operation to the input data element-wise. The Relu operation takes one input $X$, produces one output $Y$, and is defined as:\n\n$$Y = max(0,X)$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/relu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/relu_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Relu\",\n [\"X\"],\n [\"Y\"]\n )\n\nworkspace.FeedBlob(\"X\", np.random.randn(4, 4).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-1.4655551 0.64575136 0.7921748 0.4150579 ]\n [ 0.41085166 -0.2837964 0.9881425 -1.9300346 ]\n [ 0.39705405 0.44639114 0.9940703 0.2926532 ]\n [-0.6726489 0.01330667 1.101319 0.33858967]]\n\nY:\n [[0. 0.64575136 0.7921748 0.4150579 ]\n [0.41085166 0. 0.9881425 0. ]\n [0.39705405 0.44639114 0.9940703 0.2926532 ]\n [0. 0.01330667 1.101319 0.33858967]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor with same shape as input","name":"Y"}],"support_level":"default"}},{"name":"Sigmoid","schema":{"category":"Activation","description":"\nApply the Sigmoid function element-wise to the input tensor. This is often used\nas a non-linear activation function in a neural network. The sigmoid function is\ndefined as:\n\n$$Sigmoid(x) = \\frac{1}{1+\\exp(-x)}$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sigmoid_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sigmoid\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"sigmoid:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\ninput: [ 1.5744036 0.31632107 1.7842269 1.4450722 -2.1726978 ]\nsigmoid: [0.8284105 0.57842743 0.85621804 0.80923885 0.10222916]\n\n```\n\n
    \n\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"PRelu","schema":{"category":"Activation","description":"\n\nThe *PRelu* op takes input data tensor $X$, an input slope tensor $slope$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise *PRelu* operation, defined as\n\n$$y=prelu(x) =\\begin{cases}slope * x & x < 0\\\\x & otherwise\\end{cases}$$\n\nNote, is slope is size 1, the value is shared across the channels, otherwise $X$ and $slope$ must be the same shape. See [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://arxiv.org/abs/1502.01852) for more information.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/prelu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/prelu_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"PRelu\",\n [\"X\",\"Slope\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.FeedBlob(\"Slope\", np.array([0.1]).astype(np.float32))\nprint(\"Slope:\\n\", workspace.FetchBlob(\"Slope\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 0.3957382 -0.19725518 -0.26991343]\n [ 1.5513182 -0.27427664 -0.14584002]\n [-0.4121164 0.9292345 0.96426094]]\n\nSlope:\n [0.1]\n\nY:\n [[ 0.3957382 -0.01972552 -0.02699134]\n [ 1.5513182 -0.02742766 -0.014584 ]\n [-0.04121164 0.9292345 0.96426094]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"},{"description":"1D input slope tensor. If `Slope` is of size 1, the value is shared across different channels","name":"Slope"}],"outputs":[{"description":"Output tensor, with same shape as $X$.","name":"Y"}],"support_level":"default"}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Axis of the inputs when coerced to 2D matrix.","name":"axis","option":"optional","type":"int64"}],"category":"Activation","description":"\n\nApplies the Softmax function to an n-dimensional input Tensor rescaling them so\nthat the elements of the n-dimensional output Tensor lie in the range (0,1) and\nsum to 1. The softmax operator is typically the last layer in a classifier network,\nas its output can be interpreted as confidence probabilities of an input belonging\nto each class. The input is a 2-D tensor (Tensor) of size (batch_size x\ninput_feature_dimensions). The output tensor has the same shape and contains the\nsoftmax normalized values of the corresponding input. The softmax function is\ndefined as follows:\n\n$$softmax(x_i) = \\frac{\\exp(x_i)}{\\sum_{j} \\exp(x_j)}$$\n\nThe input does not need to explicitly be a 2D vector; rather, it will be coerced\ninto one. For an arbitrary n-dimensional tensor `X` in\n$[a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}]$, where k is the `axis` provided,\nthen `X` will be coerced into a 2-dimensional tensor with dimensions\n$[(a_0 * ... * a_{k-1}), (a_k * ... * a_{n-1})]$. For the default case where\n`axis`=1, the `X` tensor will be coerced into a 2D tensor of dimensions\n$[a_0, (a_1 * ... * a_{n-1})]$, where $a_0$ is often the batch size. In this\nsituation, we must have $a_0 = N$ and $a_1 * ... * a_{n-1} = D$. Each of these\ndimensions must be matched correctly, or else the operator will throw errors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softmax\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\ninput: [[ 0.0417839 0.61960053 -0.23150268 -0.64389366 -3.0000346 ]]\nsoftmax: [[0.24422921 0.43525138 0.18582782 0.12303016 0.01166145]]\n\n```\n\n
    \n\n\n\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"},{"description":"*(type: Tensor``)* Input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"X"}],"outputs":[{"description":"The softmax normalized output values with the same shape as input tensor.","name":"output"},{"description":"*(type: Tensor``)* The softmax normalized output tensor with the same shape as input tensor.","name":"Y"}],"support_level":"default"}},{"name":"MaxPool","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"name":"pad"},{"name":"cudnn_exhaustive_search","type":"boolean","visible":false}],"category":"Pool","description":"MaxPool \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool","schema":{"category":"Pool","description":"AveragePool \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"SpatialBN","schema":{"attributes":[{"default":0,"description":"If set to nonzero, run spatial batch normalization in test mode.","name":"is_test","type":"int64"},{"default":0.00001,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","option":"optional","type":"float32"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"},{"default":0.9,"description":"Factor used in computing the running mean and variance. e.g., running_mean = running_mean x momentum + mean x (1 - momentum)","name":"momentum","option":"optional","type":"float32"},{"default":1,"description":"Specifies the number of batches to apply normalization on. Requires specifying the optional sums and sumsq inputs that provide statistics across multiple batches from which mean and variance can be determined.","name":"num_batches","option":"optional","type":"int64"}],"category":"Normalization","description":"\nApplies spatial batch normalization to the input tensor as described in the original paper, [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167). Be aware, this operator has two different output sets, depending on the value of *is_test*. According to the paper, the primary operation of spatial batch normalization is:\n\n$$Y = \\frac{X - \\mu_x}{\\sqrt{\\sigma^2_{x} + \\epsilon}}*\\gamma + b$$\n\nIn the equation, $\\mu_x$ is the *mean*, $X$ is the input data, $\\sigma^2_{x}$ is the *var*, $\\epsilon$ is *epsilon*, $\\gamma$ is the *scale*, $b$ is the *bias*, and $Y$ is the output data. The *momentum* arg also affects this calculation in the computation of the running mean and variance. The influence of *momentum* is as follows:\n\n$$running\\_mean = running\\_mean * momentum + mean * (1 - momentum)$$\n\n$$running\\_var = running\\_var * momentum + var * (1 - momentum)$$\n\nOutput when is_test = 0 (train mode): *Y, mean, var, saved_mean, saved_var*\n\nOutput when is_test = 1 (test mode): *Y*\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/spatial_batch_norm_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/spatial_batch_norm_op.h\n\n","inputs":[{"name":"input"},{"description":"The scale as a 1-dimensional tensor of size $C$ to be applied to the output.","name":"scale"},{"description":"The bias as a 1-dimensional tensor of size $C$ to be applied to the output.","name":"bias"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size $C$.","name":"mean"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size $C$.","name":"var"},{"description":"The input 4-dimensional tensor of shape $NCHW$ or $NHWC$ depending on the order parameter.","name":"X"},{"description":"*(optional)* Per-channel sums of elements to be used to determine the mean and variance for this batch.","name":"sums"},{"description":"*(optional)* Per-channel sum of elements squared per channel to be used to determine the variance for this batch.","name":"sumsq"}],"outputs":[{"description":"The output 4-dimensional tensor of the same shape as $X$.","name":"Y"},{"description":"The running mean after the spatial BN operator. Must be in-place with the input *mean*. Should not be used for testing.","name":"mean"},{"description":"The running variance after the spatial BN operator. Must be in-place with the input *var*. Should not be used for testing.","name":"var"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var"}],"support_level":"default"}},{"name":"LRN","schema":{"attributes":[{"default":0,"description":"Amount of neighboring channels to sum over for normalization","name":"size","option":"optional","type":"int64"},{"default":0,"description":"Multiplicative (scaling) factor.","name":"alpha","option":"optional","type":"float32"},{"default":0,"description":"Exponent.","name":"beta","option":"optional","type":"float32"},{"default":1,"description":"Additive factor.","name":"bias","option":"optional","type":"float32"},{"default":0,"description":"Order of blob dimensions.","name":"order","option":"optional","type":"float32"}],"category":"Normalization","description":"\n\n`LRN` applies Local Response Normalization to an input blob. This operation performs\na kind of \"lateral inhibition\" by normalizing over local input regions, where\nnormalization is applied across channels. This operator is typically used to\nnormalize an unbounded activation (such as ReLU). The output shape is the same as\nthe input shape. The `brew` module has a wrapper for this operator for use in a\n`ModelHelper` object.\n\nThe formula for LRN is as follows:\n\n$$b_{c} = a_{c}(bias + \\frac{\\alpha}{n}\\sum_{c'=max(0,c-n/2)}^{min(N-1,c+n/2)} a_{c'}^2 )^{-\\beta}$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/local_response_normalization_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/local_response_normalization_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\"LRN\",\n [\"X\"],\n [\"Y\", \"Y_scale\"],\n size=11,\n alpha=0.001,\n beta=0.5,\n bias=2.0,\n order=\"NHWC\"\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 6, 6, 1).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nprint(\"Y_scale:\\n\", workspace.FetchBlob(\"Y_scale\"))\n```\n\n**Result**\n\n```\nX:\n [[[[ 0.72985137]\n [-0.3753357 ]\n [ 2.7344604 ]\n [-0.5937792 ]\n [ 0.38440478]\n [-2.1659644 ]]\n\n [[-0.92846817]\n [-0.9996144 ]\n [ 0.212943 ]\n [-1.968045 ]\n [-0.77839696]\n [ 0.45492038]]\n\n [[-0.11263168]\n [ 1.9901097 ]\n [ 0.19275683]\n [ 0.15630436]\n [ 0.7536298 ]\n [-0.77339894]]\n\n [[ 0.8353551 ]\n [-0.7784452 ]\n [ 1.779317 ]\n [ 0.22421335]\n [ 1.3846219 ]\n [-3.0546608 ]]\n\n [[ 0.09977621]\n [ 2.2071757 ]\n [ 0.79971045]\n [ 3.563886 ]\n [-0.7169287 ]\n [ 0.77170426]]\n\n [[-1.4296649 ]\n [ 0.19181213]\n [ 0.45961624]\n [-1.0201577 ]\n [ 0.62854475]\n [-0.6395456 ]]]]\n\nY:\n [[[[ 0.5160766 ]\n [-0.26540157]\n [ 1.9332271 ]\n [-0.41986194]\n [ 0.27181432]\n [-1.5314047 ]]\n\n [[-0.6565133 ]\n [-0.7068181 ]\n [ 0.15057328]\n [-1.3914955 ]\n [-0.5504022 ]\n [ 0.32167578]]\n\n [[-0.0796426 ]\n [ 1.4070934 ]\n [ 0.13629955]\n [ 0.11052381]\n [ 0.53288984]\n [-0.5468682 ]]\n\n [[ 0.5906759 ]\n [-0.5504363 ]\n [ 1.2580767 ]\n [ 0.1585426 ]\n [ 0.9790328 ]\n [-2.1595135 ]]\n\n [[ 0.07055242]\n [ 1.5605361 ]\n [ 0.5654725 ]\n [ 2.5193207 ]\n [-0.50693923]\n [ 0.54567 ]]\n\n [[-1.0108787 ]\n [ 0.13563155]\n [ 0.3249962 ]\n [-0.72134334]\n [ 0.44444424]\n [-0.45222285]]]]\nY_scale:\n [[[[2.0000484]\n [2.0000129]\n [2.0006797]\n [2.000032 ]\n [2.0000134]\n [2.0004265]]\n\n [[2.0000784]\n [2.0000908]\n [2.000004 ]\n [2.0003521]\n [2.000055 ]\n [2.0000188]]\n\n [[2.0000012]\n [2.00036 ]\n [2.0000033]\n [2.0000021]\n [2.0000517]\n [2.0000544]]\n\n [[2.0000634]\n [2.000055 ]\n [2.0002878]\n [2.0000045]\n [2.0001743]\n [2.0008483]]\n\n [[2.000001 ]\n [2.000443 ]\n [2.0000582]\n [2.0011547]\n [2.0000467]\n [2.0000541]]\n\n [[2.0001857]\n [2.0000033]\n [2.0000193]\n [2.0000947]\n [2.000036 ]\n [2.0000372]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor (ReLU output).","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"},{"description":"*(type: Tensor``)* Output scale.","name":"Y_scale"}],"support_level":"default"}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"Probability of an element to be zeroed.","name":"ratio","option":"optional","type":"float32"},{"default":0,"description":"If zero (train mode), perform dropout. If non-zero(test mode), Y = X.","name":"is_test","type":"int64"}],"category":"Dropout","description":"\n\n`Dropout` takes one input data tensor (`X`) and produces two tensor outputs, `Y` and\n`mask`. If the `is_test` argument is zero (default=0), the output `Y` will be the input\nwith random elements zeroed. The probability that a given element is zeroed is\ndetermined by the `ratio` argument.\n\nIf the `is_test` argument is set to non-zero, the output `Y` is exactly the same as the\ninput `X`. Note that outputs are scaled by a factor of $\\frac{1}{1-ratio}$ during\ntraining, so that during test time, we can simply compute an identity function. This\nscaling is important because we want the output at test time to equal the expected value\nat training time. Dropout has been proven to be an effective regularization technique to\nprevent overfitting during training.\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dropout_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dropout_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Dropout\",\n [\"X\"],\n [\"Y\"] + [\"mask\"],\n ratio=0.5,\n is_test=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(5, 5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\n```\n\n**Result**\n\n```\nX: [[5. 4. 3. 6. 9.]\n [2. 1. 8. 0. 9.]\n [7. 3. 0. 6. 3.]\n [1. 8. 2. 6. 4.]\n [6. 2. 6. 4. 0.]]\nY: [[ 0. 0. 0. 12. 18.]\n [ 0. 0. 16. 0. 0.]\n [ 0. 0. 0. 12. 6.]\n [ 0. 0. 4. 0. 0.]\n [12. 0. 0. 0. 0.]]\nmask: [[False False False True True]\n [False False True True False]\n [False False True True True]\n [False False True False False]\n [ True False False False False]]\n```\n\n
    \n\n","inputs":[{"description":"The input data as Tensor.","name":"data"},{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"The output.","name":"output"},{"description":"*(type: Tensor``)* The output mask containing boolean values foreach element, signifying which elements are dropped out. If `is_test` isnonzero, this output is not filled.","name":"mask"},{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"Concat","schema":{"attributes":[{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"},{"description":"Order of blob dimensions. Concats on the C dimension.","name":"order","option":"optional","type":"string"},{"description":"Pass non-zero integer to add the axis specified in `axis` to all input tensors.","name":"add_axis","option":"optional","type":"int64"}],"category":"Tensor","description":"\nConcatenate a list of tensors into a single tensor. Similar functionality to\nNumpy's [concatenate](https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html)\nfunction. The `axis` argument specifies what axis along which the arrays will be concatenated.\nWhen set to non-zero (default=0), the `add_axis` argument adds the axis specified in `axis` to\nall input tensors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Concat\",\n [\"X1\", \"X2\"],\n [\"Y\", \"split_info\"],\n axis=0\n)\n\nworkspace.FeedBlob(\"X1\", np.array([[1,2],[3,4]]))\nworkspace.FeedBlob(\"X2\", np.array([[5,6]]))\nprint(\"X1:\", workspace.FetchBlob(\"X1\"))\nprint(\"X2:\", workspace.FetchBlob(\"X2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"split_info:\", workspace.FetchBlob(\"split_info\"))\n\n```\n\n**Result**\n\n```\n\nX1: [[1 2]\n [3 4]]\nX2: [[5 6]]\nY: [[1 2]\n [3 4]\n [5 6]]\nsplit_info: [2 1]\n\n```\n\n
    \n\n
    \n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Concat\",\n [\"X1\", \"X2\"],\n [\"Y\", \"split_info\"],\n add_axis=1,\n axis=3\n)\n\nworkspace.FeedBlob(\"X1\", np.random.randint(10, size=(1, 1, 5, 5))) // NCHW\nworkspace.FeedBlob(\"X2\", np.random.randint(10, size=(1, 1, 5, 5))) // NCHW\nprint(\"X1:\", workspace.FetchBlob(\"X1\"))\nprint(\"X2:\", workspace.FetchBlob(\"X2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"split_info:\", workspace.FetchBlob(\"split_info\"))\n\n```\n\n**Result**\n\n```\n\nX1: [[[[1 8 3 9 0]\n [6 4 6 5 6]\n [3 9 1 9 9]\n [5 1 0 7 7]\n [9 4 0 0 9]]]]\nX2: [[[[7 0 2 6 1]\n [3 9 4 0 3]\n [5 3 8 9 4]\n [3 4 2 1 0]\n [0 8 8 8 1]]]]\nY: [[[[[1 8 3 9 0]\n [7 0 2 6 1]]\n\n [[6 4 6 5 6]\n [3 9 4 0 3]]\n\n [[3 9 1 9 9]\n [5 3 8 9 4]]\n\n [[5 1 0 7 7]\n [3 4 2 1 0]]\n\n [[9 4 0 0 9]\n [0 8 8 8 1]]]]]\nsplit_info: [1 1]\n\n```\n\n
    \n\n ","inputs":[{"name":"inputs","option":"variadic"},{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"*(type: Tensor``)* Concatenated tensor.","name":"concat_result"},{"description":"*(type: Tensor``)* The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"GenerateProposals","schema":{"attributes":[{"description":"(float) spatial scale","name":"spatial_scale","option":"optional"},{"description":"(int) RPN_PRE_NMS_TOP_N","name":"pre_nms_topN","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"post_nms_topN","option":"optional"},{"description":"(float) RPN_NMS_THRESH","name":"nms_thresh","option":"optional"},{"description":"(float) RPN_MIN_SIZE","name":"min_size","option":"optional"},{"description":"bool (default false), Correct bounding box transform coordates, see bbox_transform() in boxes.py Set to true to match the detectron code, set to false for backward compatibility","name":"correct_transform_coords","option":"optional"},{"description":"bool (default true). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_on","option":"optional"},{"description":"int (default -90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_lo","option":"optional"},{"description":"int (default 90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_hi","option":"optional"},{"description":"float (default 1.0 degrees). For RRPN, clip almost horizontal boxes within this threshold of tolerance for backward compatibility. Set to negative value for no clipping.","name":"clip_angle_thresh","option":"optional"}],"description":"\nGenerate bounding box proposals for Faster RCNN. The propoasls are generated for\na list of images based on image score 'score', bounding box regression result\n'deltas' as well as predefined bounding box shapes 'anchors'. Greedy\nnon-maximum suppression is applied to generate the final bounding boxes.\n","inputs":[{"description":"Scores from conv layer, size (img_count, A, H, W)","name":"scores"},{"description":"Bounding box deltas from conv layer, size (img_count, 4 * A, H, W)","name":"bbox_deltas"},{"description":"Image info, size (img_count, 3), format (height, width, scale)","name":"im_info"},{"description":"Bounding box anchors, size (A, 4)","name":"anchors"}],"outputs":[{"description":"Proposals, size (n x 5), format (image_index, x1, y1, x2, y2)","name":"rois"},{"description":"scores of proposals, size (n)","name":"rois_probs"}],"support_level":"default"}},{"name":"RoIAlign","schema":{"attributes":[{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nRegion of Interest (RoI) align operation as used in Mask R-CNN.\n","inputs":[{"description":"4D feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 4 or 5) specifying R RoIs representing: batch index in [0, N - 1], x1, y1, x2, y2. The RoI coordinates are in the coordinate system of the input image. For inputs corresponding to a single image, batch index can be excluded to have just 4 columns.","name":"RoIs"}],"outputs":[{"description":"4D output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"BBoxTransform","schema":{"attributes":[{"description":"vector weights [wx, wy, ww, wh] for the deltas","name":"weights","option":"optional"},{"description":"bool (default true), transform the boxes to the scaled image space after applying the bbox deltas.Set to false to match the detectron code, set to true for keypoint models and for backward compatibility","name":"apply_scale","option":"optional"},{"description":"bool (default false), Correct bounding box transform coordates, see bbox_transform() in boxes.py Set to true to match the detectron code, set to false for backward compatibility","name":"correct_transform_coords","option":"optional"},{"description":"bool (default false). If true, then boxes (rois and deltas) include angle info to handle rotation. The format will be [ctr_x, ctr_y, width, height, angle (in degrees)].","name":"rotated","option":"optional"},{"description":"bool (default true). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_on","option":"optional"},{"description":"int (default -90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_lo","option":"optional"},{"description":"int (default 90 degrees). If set, for rotated boxes, angle is normalized to be within [angle_bound_lo, angle_bound_hi].","name":"angle_bound_hi","option":"optional"},{"description":"float (default 1.0 degrees). For RRPN, clip almost horizontal boxes within this threshold of tolerance for backward compatibility. Set to negative value for no clipping.","name":"clip_angle_thresh","option":"optional"}],"description":"\nTransform proposal bounding boxes to target bounding box using bounding box\n regression deltas.\n","inputs":[{"description":"Bounding box proposals in pixel coordinates, Size (M, 4), format [x1, y1, x2, y2], orSize (M, 5), format [batch_index, x1, y1, x2, y2]. If proposals from multiple images in a batch are present, they should be grouped sequentially and in incremental order.For rotated boxes, this would have an additional angle (in degrees) in the format [, ctr_x, ctr_y, w, h, angle].","name":"rois"},{"description":"bounding box translations and scales,size (M, 4*K), format [dx, dy, dw, dh], K = # classes. For rotated boxes, size (M, 5*K, format [dx, dy, dw, dh, da].","name":"deltas"},{"description":"Image dimensions, size (batch_size, 3), format [img_height, img_width, img_scale]","name":"im_info"}],"outputs":[{"description":"Pixel coordinates of the transformed bounding boxes,Size (M, 4*K), format [x1, y1, x2, y2]. For rotated boxes, size (M, 5*K), format [ctr_x, ctr_y, w, h, angle].","name":"box_out"},{"description":"Tensor of shape (batch_size) with each element denoting the number of RoIs belonging to the corresponding image in batch","name":"roi_batch_splits"}],"support_level":"default"}},{"name":"BoxWithNMSLimit","schema":{"attributes":[{"description":"(float) TEST.SCORE_THRESH","name":"score_thresh","option":"optional"},{"description":"(float) TEST.NMS","name":"nms","option":"optional"},{"description":"(int) TEST.DEECTIONS_PER_IM","name":"detections_per_im","option":"optional"},{"description":"(bool) TEST.SOFT_NMS.ENABLED","name":"soft_nms_enabled","option":"optional"},{"description":"(string) TEST.SOFT_NMS.METHOD","name":"soft_nms_method","option":"optional"},{"description":"(float) TEST.SOFT_NMS.SIGMA","name":"soft_nms_sigma","option":"optional"},{"description":"(float) Lower bound on updated scores to discard boxes","name":"soft_nms_min_score_thres","option":"optional"},{"description":"bool (default false). If true, then boxes (rois and deltas) include angle info to handle rotation. The format will be [ctr_x, ctr_y, width, height, angle (in degrees)].","name":"rotated","option":"optional"}],"description":"\nApply NMS to each class (except background) and limit the number of\nreturned boxes.\n","inputs":[{"description":"Scores, size (count, num_classes)","name":"scores"},{"description":"Bounding box for each class, size (count, num_classes * 4). For rotated boxes, this would have an additional angle (in degrees) in the format [, ctr_x, ctr_y, w, h, angle]. Size: (count, num_classes * 5).","name":"boxes"},{"description":"Tensor of shape (batch_size) with each element denoting the number of RoIs/boxes belonging to the corresponding image in batch. Sum should add up to total count of scores/boxes.","name":"batch_splits"}],"outputs":[{"description":"Filtered scores, size (n)","name":"scores"},{"description":"Filtered boxes, size (n, 4). For rotated boxes, size (n, 5), format [ctr_x, ctr_y, w, h, angle].","name":"boxes"},{"description":"Class id for each filtered score/box, size (n)","name":"classes"},{"description":"Output batch splits for scores/boxes after applying NMS","name":"batch_splits"},{"description":"Optional filtered indices, size (n)","name":"keeps"},{"description":"Optional number of filtered indices per class, size (num_classes)","name":"keeps_size"}],"support_level":"default"}},{"name":"ONNXWhile","schema":{"attributes":[{"description":"Net executed on each iteration","name":"body","option":"optional"},{"description":"Whether to use the trip count input","name":"has_trip_count","option":"optional"},{"description":"Whether to use the condition input","name":"has_cond","option":"optional"},{"description":"Whether to save the scopes across iterations, as in for backprop","name":"save_scopes","option":"optional"},{"description":"Do not create new scopes. Use this only if you're certain there will be no name collision, for example if you're converting from a fully-SSA IR","name":"disable_scopes","option":"optional"}],"description":"\n*** EXPERIMENTAL. This operator is a work-in-progress. No assumption should be\nmade about the stability or correctness of this op. ***\n\nGeneric Looping construct confirming to the ONNX Loop operator spec. This loop\nhas multiple termination conditions:\n\n1. Trip count. Iteration count specified at runtime. Set by specifying the\n input M. Optional. Set to empty string to omit. Note that a static trip\n count (specified at graph construction time) can be specified by passing\n in a constant node for input M.\n2. Loop termination condition. This is an input to the op that determines\n whether to run the first interation and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition\n variable, whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\nOperator inputs defined as (max_trip_count, condition_var). Omitted optional\ninputs are represented as empty string. Concretely, in this caffe2 op an input\nis marked as omitted by setting its 'has_{name}' argument to False.\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n ","inputs":[{"description":"Number of iterations to go out to. Used if the flag has_trip_count is True.","name":"max_trip_count"},{"name":"condition"},{"name":"initial","option":"variadic"},{"description":"Dynamic condition value for the first iteration. For all subsequent iterations, the condition from the body graph is used. This input is used if the flag has_cond is true.","name":"first_iter_condition"}],"outputs":[{"name":"final_and_scan_outputs","option":"variadic"}],"support_level":"default"}},{"name":"Int8Quantize","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"inputs":[{"description":"FP32 Tensor X.","name":"X"},{"description":"Optional scale quantization param computed on activation histogram dataWill overwrite Y_scale argument if specified","name":"Scale qparam"},{"description":"Optionsl zero-point quantization param computed on activation dataWill overwrite Y_zero_point argument if specified","name":"Zero-point qparam"},{"description":"Optional Qparam blob that constans quant param computed on activation histogram dataWill overwrite Y_scale and Y_zero_point argument if specified","name":"Qparam"}],"outputs":[{"description":"Int8 Tensor qX representing X with linear quantization.","name":"Y"}],"support_level":"default"}},{"name":"Int8Conv","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"default":0,"name":"pad"},{"default":1,"name":"stride"}],"category":"Layer","description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \n[Only NHWC order is supported now]Note that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is convolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_op_impl.h is the templated implementation of the conv_op.h file, which is\nwhy they are separate files.\n","inputs":[{"description":"Input data blob from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the NCHW usage. On the other hand, the NHWC Op has a different set of dimension constraints. ","name":"X"},{"description":"The filter blob that will be used in the convolutions; has size (M x C x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution; has size (M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"Int8FC","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Layer","description":"\nComputes the result of passing an input vector X into a fully\nconnected layer with 2D weight matrix W and 1D bias vector b. That is,\nthe layer computes Y = X * W^T + b, where X has size (M x K),\nW has size (N x K), b has size (N), and Y has size (M x N),\nwhere M is often the batch size.\n\n\nNOTE: X does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\nX \\in [a_0, a_1 * ... * a_{n-1}]. Only this case is supported!\nLastly, even though b is a 1D vector of size N, it is copied/resized to\nbe size (M x N) implicitly and added to each vector in the batch.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","inputs":[{"description":"input tensor that's coerced into a 2D matrix of size (MxK) as described above","name":"X"},{"description":"A tensor that is coerced into a 2D blob of size (KxN) containing fully connected weight matrix","name":"W"},{"description":"1D blob containing bias vector","name":"b"},{"description":"Optional scale quantization param computed on activation histogram dataWill overwrite Y_scale argument if specified","name":"Scale qparam"},{"description":"Optionsl zero-point quantization param computed on activation dataWill overwrite Y_zero_point argument if specified","name":"Zero-point qparam"},{"description":"Optional Qparam blob that constans quant param computed on activation histogram dataWill overwrite Y_scale and Y_zero_point argument if specified","name":"Qparam"}],"outputs":[{"description":"2D output tensor","name":"Y"}],"support_level":"default"}},{"name":"Int8AveragePool","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Pool","description":"AveragePool \nconsumes an input blob X and applies average pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Average pooling consisting of averaging all values of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from average pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y"}],"support_level":"default"}},{"name":"Int8Sum","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Int8Softmax","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(int) default to 1; describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","option":"optional"}],"category":"Activation","description":"\nThe operator computes the softmax normalized values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the softmax normalized values of the corresponding input.\n\nX does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\nX \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then X will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the X tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"}],"outputs":[{"description":"The softmax normalized output values with the same shape as input tensor.","name":"output"}],"support_level":"default"}},{"name":"Int8Relu","schema":{"attributes":[{"default":0,"name":"order"},{"default":0,"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"default":0,"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"category":"Activation","description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"AffineChannel","schema":{"category":"Normalization","description":"\nApplies a separate affine transformation to each channel of the input. Useful\nfor replacing spatial batch norm with its equivalent fixed transformation.\n","inputs":[{"description":"Feature map input with order NCHW or NHWC.","name":"X"},{"description":"1D input of shape (C); the c-th element is the scale factor of the affine transformation for the c-th channel of the input.","name":"scale"},{"description":"1D input of shape (C); the c-th element is the bias of the affine transformation for the c-th channel of the input.","name":"bias"}],"outputs":[{"description":"Output with the same order of Input.","name":"Y"}],"support_level":"default"}},{"name":"LearningRateAdaption","schema":{"attributes":[{"description":"the learning rate for performing gradient descent on learning rate lr","name":"lr_alpha","option":"optional"},{"description":"whether to apply normalized lr adaption or not","name":"normalized_lr_adaption","option":"optional"}],"description":"\n Learning Rate Adaption is an operation that perform one iteration of\n gradient descent based on learning rate:\n lr(k) = lr(k-1) - lr_alpha * df(k-1)/dlr,\n where df(k-1)/dlr is the gradient of objective function f on lr, and\n lr_alpha is a learning rate hyperparameter. It can be prove that\n df(k-1)/dlr equals INNERPRODUCT(grad(k-1), -grad(k-2)), where grad(k-1) is\n the grad of f(k-1) on parameters. When the argument\n \"normalized_lr_adaption\" is false, we simply perform the\n following update:\n lr(k) = lr(k-1) - lr_alpha * INNERPRODUCT(grad(k-1), grad(k-2)).\n If we set \"normalized_lr_adaption\" to be true, we do not directly apply\n INNERPRODUCT(grad(k-1), -grad(k-2)) as the grad. Instead, we perform the\n following update:\n lr(k) = lr(k-1) + lr_alpha * cosineSimilarity(grad(k-1), grad(k-2)).\n","inputs":[{"description":"Learning rate","name":"lr"},{"description":"Gradient computed","name":"grad"},{"description":"The effective grad","name":"effgrad"}],"outputs":[{"description":"Updated learning rate","name":"output_lr"}],"support_level":"default"}},{"name":"MeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"CoshGradient","schema":{"description":null,"support_level":"default"}},{"name":"IndexSize","schema":{"description":"\nReturns the number of entries currently present in the index.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"Scalar int64 tensor with number of entries.","name":"items"}],"support_level":"default"}},{"name":"LpPool","schema":{"attributes":[{"description":"(*float*): type of $L_p$ norm to use (default=2.0)","name":"p","option":"optional"},{"description":"(*int*): the size of the window to take a max over","name":"kernel","option":"optional"},{"description":"(*int*): the stride of the window","name":"stride","option":"optional"},{"description":"(*int*): implicit zero padding to be added on both sides","name":"pad","option":"optional"},{"description":"(*int*): parameter that controls the stride of elements in the window","name":"dilation","option":"optional"},{"description":"(*string*): order of blob dimensions (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\n`LpPool` consumes an input blob and applies max pooling across the the blob according to kernel sizes, stride sizes, pad lengths and dilation. $L_p$ pooling consists of taking the $L_p$ norm of a subset of the input tensor according to the kernel size and downsampling the data into the output blob for further processing.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the output blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lp_pool_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LpPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n p=2.0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[[-1.1113514 -1.1173418 -0.1504435 0.1327146 -1.2221841 -0.5654315 ]\n [-1.9209646 -0.04675794 0.8604731 1.2042469 0.28154245 0.38656202]\n [-0.8772837 -0.03264008 0.26222762 0.28526652 0.321102 -2.5891325 ]\n [-0.9248281 1.440776 -0.56832 -0.6017927 1.2262512 -2.1443934 ]\n [ 0.5194415 -1.6858683 0.45221648 0.65029615 -0.8574544 0.8121054 ]\n [ 0.25902653 0.4934758 0.49870652 -0.48134378 -0.9178449 -0.07626943]]]]\n\nY:\n [[[[2.4851248 1.49361 1.4290358]\n [1.9240153 0.9139378 3.5928857]\n [1.8500228 1.0525136 1.4976646]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 8-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Transpose","schema":{"attributes":[{"description":"Order to permute axes of input tensor. Reverses the dimensions by default.","name":"axes","option":"optional"}],"description":"\nTranspose the input tensor by permuting the axes of the input according\nto the `axes` argument. Similar to numpy's\n[transpose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)\nfunction.\n\nFor example, when axes=(1, 0, 2), given an input tensor of shape\n(1, 2, 3), the output shape will be (2, 1, 3).\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/transpose_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Transpose\",\n [\"X\"],\n [\"Y\"],\n axes=(0,3,1,2)\n)\n\nx = np.random.rand(1,32,32,3)\nworkspace.FeedBlob(\"X\", x)\nprint(\"X.shape (NHWC order):\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape (NCHW order):\", workspace.FetchBlob(\"Y\").shape)\n```\n\n**Result**\n\n```\nX.shape (NHWC order): (1, 32, 32, 3)\nY.shape (NCHW order): (1, 3, 32, 32)\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Transposed output.","name":"Y"}],"support_level":"default"}},{"name":"Accuracy","schema":{"attributes":[{"description":"Count as correct by comparing the true label to the top k scoring classes (default 1: only compare to the top scoring class i.e. argmax)","name":"top_k","option":"optional"}],"description":"\nAccuracy takes two inputs- predictions and labels, and returns a float\naccuracy value for the batch. Predictions are expected in the form of 2-D tensor\ncontaining a batch of scores for various classes, and labels are expected in the\n form of 1-D tensor containing true label indices of samples in the batch. If\nthe score for the label index in the predictions is the highest among all\nclasses, it is considered a correct prediction.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing scores","name":"predictions"},{"description":"1-D tensor (Tensor) of size (num_batches) having the indices of true labels","name":"labels"}],"outputs":[{"description":"1-D tensor (Tensor) of size 1 containing accuracy","name":"accuracy"}],"support_level":"default"}},{"name":"TimerEnd","schema":{"description":"\nStop a timer started with **TimerBegin**. Publishes a CAFFE_EVENT.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"support_level":"default"}},{"name":"LengthsRangeFill","schema":{"description":"\nThe *LengthsRangeFill* op takes a single input *lengths* and outputs a single tensor *range_sequence*. For each element of *lengths*, the op appends the range(0,lengths) vector to the end of *range_sequence*. For example, if input=[2,4,1], the output would be [0,1,0,1,2,3,0].\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsRangeFill\",\n [\"lengths\"],\n [\"range_sequence\"],\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([2,4,1]).astype(np.int32))\nprint(\"lengths:\\n\", workspace.FetchBlob(\"lengths\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"range_sequence: \\n\", workspace.FetchBlob(\"range_sequence\"))\n\n```\n\n**Result**\n\n```\n\nlengths:\n [2 4 1]\nrange_sequence:\n [0 1 0 1 2 3 0]\n\n```\n\n
    \n\n","inputs":[{"description":"1D tensor of int32 or int64 segment lengths.","name":"lengths"}],"outputs":[{"description":"1D tensor whose size is the sum of *lengths*","name":"range_sequence"}],"support_level":"default"}},{"name":"AccumulateHistogram","schema":{"attributes":[{"description":"the lower bound value","name":"lower_bound","option":"optional"},{"description":"the upper bound value","name":"upper_bound","option":"optional"},{"description":"number of buckets to use in [lower_bound, upper_bound)","name":"num_buckets","option":"optional"}],"description":"\nThis operator calculate thes histogram of values in input tensor.\nThere're 2 outputs, one for histogram of current input tensor, and another\nfor histogram of the all input tensors accumulated through history.\nThe output would contain num_buckets + 2 values. index[1 ... num_buckets]\nfor values in [lower_bound, upper_bound) interval. And the rest 2 for values\nsmaller than lower_bound or greater than upper_bound respectively.\n","inputs":[{"description":"Input tensor.","name":"X"}],"outputs":[{"description":"Output histogram of the current tensor.","name":"CurHist"},{"description":"Accumulated histogram of the history tensor.","name":"AccHist"}],"support_level":"default"}},{"name":"Int8ConvRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nThe convolution operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \n[Only NHWC order is supported now]Note that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is convolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_op_impl.h is the templated implementation of the conv_op.h file, which is\nwhy they are separate files.\n","inputs":[{"description":"Input data blob from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the NCHW usage. On the other hand, the NHWC Op has a different set of dimension constraints. ","name":"X"},{"description":"The filter blob that will be used in the convolutions; has size (M x C x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution; has size (M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths. Output will go through rectified linear function, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsSum8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsSum operator, where DATA is\nstored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentMean).\n\nThis op is basically Gather and UnsortedSegmentMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"Load","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"default":"","description":"Blobs will be prefixed with this when loading. Useful for avoiding collisions with blobs existing in the workspace. The output blob names specified to this op should include this prefix.","name":"add_prefix","option":"optional","type":"string"},{"default":"","description":"Characters in the provided blob names that match `strip_prefix` will be removed prior to saving. Also, characters that precede `strip_prefix` will be removed. Useful for removing device scope from blob names.","name":"strip_prefix","option":"optional","type":"string"},{"description":"The output path of the db. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db","option":"optional","type":"string"},{"description":"List of paths to dbs to load blobs from. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"dbs","option":"optional","type":"string[]"},{"description":"(type: string)* Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional"},{"default":0,"description":"If nonzero, the blobs are loaded into the device that is specified in the serialized `BlobProto`. Otherwise, the device will be set as the one that the `Load` operator is being run under.","name":"keep_device","option":"optional","type":"int64"},{"default":0,"description":"If nonzero, will load all blobs pointed to by the db to the workspace overwriting/creating blobs as needed.","name":"load_all","option":"optional","type":"int64"},{"default":false,"description":"If True, will allow not loading all the output blobs specified in the outputs.","name":"allow_incomplete","option":"optional","type":"boolean"},{"description":"If set, used instead of output blob names to specify which blobs in the db shall be loaded. Must be the same length as number of output blobs.","name":"source_blob_names","option":"optional","type":"string[]"}],"description":"\nThe Load operator loads a set of serialized blobs from a db or multiple dbs. It\ntakes $[0, \\infty)$ number of inputs and $[0, \\infty)$ number of outputs, using\nthe db keys to match the db entries with the outputs.\n\nIf at least one input is passed, then it is assumed that that input blobs are a\nset of DBReaders to load from. Otherwise the `db` or `dbs` argument is used to load\nblobs from one single db or multiple dbs respectively. `db_type` argument is used\nto specify the type of the input db/dbs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Load\",\n [],\n [\"X\", \"Y\"],\n db=\"test_db\",\n db_type=\"lmdb\"\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: List(DBReader))* [OPTIONAL] List of DBReaders to load from. Can use this instead of the `db`/`dbs` args.","name":"X, Y, ..."}],"support_level":"default"}},{"name":"Exp","schema":{"description":"\nCalculates the exponential of the given input tensor ($exp(x)$), element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/exp_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Exp\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[0.5821691 0.07719802 0.50159824]\n [0.40952456 0.36788362 0.84887683]\n [0.02472685 0.65730894 0.9066397 ]]\nX after running op:\n[[1.7899168 1.080256 1.6513585]\n [1.5061016 1.4446739 2.3370204]\n [1.0250351 1.9295927 2.4759884]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* The exponential of the input tensor computed element-wise.","name":"Y"}],"support_level":"default"}},{"name":"ConvTransposeGradient","schema":{"description":null,"support_level":"default"}},{"name":"LayerNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"SinhGradient","schema":{"description":null,"support_level":"default"}},{"name":"FlattenToVec","schema":{"description":"\n\nThe *FlattenToVec* op flattens the input tensor into a 1-D vector. The op accepts a single input tensor and returns a single output tensor.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FlattenToVec\",\n [\"input\"],\n [\"output\"],\n)\n\nworkspace.FeedBlob(\"input\", np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output: \\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [[ 1. 2. 3.]\n [ 4. 5. 6.]\n [ 7. 8. 9.]\n [10. 11. 12.]]\noutput:\n [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.]\n\n```\n\n
    \n\n","inputs":[{"description":"A tensor of rank >= 1.","name":"input"}],"outputs":[{"description":"A tensor of rank 1 (vector) with the contents of the input tensor.","name":"output"}],"support_level":"default"}},{"name":"Ftrl","schema":{"description":null,"support_level":"default"}},{"name":"UnsortedSegmentMean","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"}],"description":"\nApplies 'Mean' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentMean).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sinh","schema":{"description":"\nCalculates the hyperbolic sine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sinh_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sinh\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.98907769 0.52907848 0.03216429 0.94983935 0.47881418]\nY: [1.15841695 0.5541099 0.03216984 1.09924557 0.49732079]\n\n```\n\n
    \n\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic sine values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"CloseRebatchingQueue","schema":{"description":"\nCloses the Queue.\n","inputs":[{"description":"object representing the queue","name":"queue"}],"support_level":"default"}},{"name":"LpPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"StumpFunc","schema":{"description":"\nConverts each input element into either high_ or low_value\nbased on the given threshold.\n","inputs":[{"description":"tensor of float","name":"X"}],"outputs":[{"description":"tensor of float","name":"Y"}],"support_level":"default"}},{"name":"BooleanMask","schema":{"description":"\nGiven a 1D `data` tensor and a boolean `mask` tensor of the same shape, returns a `masked_data` tensor containing only the elements corresponding to positions where the `mask` is True, and a `masked_indices` tensor containing the indices of the True elements.\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_mask_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanMask\",\n [\"data\", \"mask\"],\n [\"masked_data\", \"masked_indices\"]\n)\n\nworkspace.FeedBlob(\"data\", np.array([1,2,3,4,5,6]))\nworkspace.FeedBlob(\"mask\", np.array([True,False,False,True,True,False]))\nprint(\"data:\", workspace.FetchBlob(\"data\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\nworkspace.RunOperatorOnce(op)\nprint(\"masked_data:\", workspace.FetchBlob(\"masked_data\"))\nprint(\"masked_indices:\", workspace.FetchBlob(\"masked_indices\"))\n\n```\n\n**Result**\n\n```\n\ndata: [1 2 3 4 5 6]\nmask: [ True False False True True False]\nmasked_data: [1 4 5]\nmasked_indices: [0 3 4]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): 1D input tensor","name":"data"},{"description":"(*Tensor``*): tensor of bools which determines the input elements that will be left in the `masked_data` output tensor; same shape as `data`","name":"mask"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as `data` input that contains the masked input tensor","name":"masked_data"},{"description":"(*Tensor``*): 1D tensor of indices of the True elements in the `mask` tensor","name":"masked_indices"}],"support_level":"default"}},{"name":"ReduceFrontMean","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **mean**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the mean operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [mean(1,4), mean(5,1,7), mean(2), mean(9,2)] = [2.5, 4.333, 2, 5.5]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_mean_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontMean\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[5. 0. 9.]\n [4. 1. 1.]\n [9. 0. 8.]]\n\n [[2. 6. 7.]\n [6. 2. 6.]\n [0. 4. 5.]]]\nY: [4.3333335 2.1666667 6.]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"SigmoidCrossEntropyWithLogits","schema":{"attributes":[{"description":"default is false; if enabled, will use the log d trick to avoid the vanishing\ngradients early on; see Goodfellow et. al (2014)","name":"log_D_trick","option":"optional"},{"description":"default is false; if enabled, the model will be allowed to train on an unjoined\ndataset, where some examples might be false negative and might appear\nin the dataset later as (true) positive example.","name":"unjoined_lr_loss","option":"optional"}],"description":"\nGiven two matrices logits and targets, of same shape,\n(batch_size, num_classes), computes the sigmoid cross entropy between the two.\nReturns a tensor of shape (batch_size,) of losses for each example.\n","inputs":[{"description":"matrix of logits for each example and class.","name":"logits"},{"description":"matrix of targets, same shape as logits.","name":"targets"}],"outputs":[{"description":"Vector with the total xentropy for each example.","name":"xentropy"}],"support_level":"default"}},{"name":"CosineEmbeddingCriterionGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResizeLike","schema":{"description":"\nProduces tensor containing data of first input and shape of second input.\n","inputs":[{"description":"Tensor whose data will be copied into the output.","name":"data"},{"description":"Tensor whose shape will be applied to output.","name":"shape_tensor"}],"outputs":[{"description":"Tensor with data of input 0 and shape of input 1.","name":"output"}],"support_level":"default"}},{"name":"HSoftmaxSearch","schema":{"attributes":[{"description":"Serialized TreeProto string containing a tree including all intermidate nodes and leafs. All nodes must have names for correct outputs","name":"tree","option":"optional"},{"description":"beam used for pruning tree. The pruning algorithm is that only children, whose score is smaller than parent's score puls beam, will be propagated.","name":"beam","option":"optional"},{"description":"Number of nodes in outputs","name":"topN","option":"optional"}],"description":"\nHSoftmaxSearch is an operator to generate the most possible paths given a\nwell-trained model and input vector. Greedy algorithm is used for pruning the\nsearch tree.\n","inputs":[{"description":"Input data from previous layer","name":"X"},{"description":"The matrix trained from Softmax Ops","name":"W"},{"description":"The bias trained from Softmax Ops","name":"b"}],"outputs":[{"description":"The name of selected nodes and leafs. For nodes, it will be the name defined in the tree. For leafs, it will be the index of the word in the tree.","name":"Y_names"},{"description":"The corresponding scores of Y_names","name":"Y_scores"}],"support_level":"default"}},{"name":"HSoftmaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"CloneCommonWorld","schema":{"description":"\nClones existing common world.\n","inputs":[{"description":"Existing common world to clone.","name":"existing_comm_world"}],"outputs":[{"description":"A common world for collective operations.","name":"comm_world"}],"support_level":"default"}},{"name":"SortedSegmentRangeMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"LCGradient","schema":{"description":null,"support_level":"default"}},{"name":"SubGradient","schema":{"description":null,"support_level":"default"}},{"name":"PackedInt8BGRANHWCToNCHWCStylizerPreprocess","schema":{"description":null,"support_level":"default"}},{"name":"ConcatBatchMatMulBatchGatherOp","schema":{"description":null,"support_level":"default"}},{"name":"Gather","schema":{"description":"\n\nThe *Gather* op accepts a *DATA* tensor of rank $r >= 1$ and *INDICES* tensor of rank $q$ as inputs. It then gathers entries of the outer-most dimension of *DATA*, indexed by *INDICES*, and concatenate them in an output tensor of rank $q + (r - 1)$.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/gather_op.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/gather_op.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Gather\",\n [\"DATA\", \"INDICES\"],\n [\"OUTPUT\"]\n)\ndata = np.array([[1., 1.2],[2.3, 3.4],[4.5, 5.7]])\nprint(\"DATA:\\n\",data)\n\ninds = np.array([[0, 1],[1, 2]])\nprint(\"INDICES:\\n\",inds)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"DATA\", data.astype(np.float32))\nworkspace.FeedBlob(\"INDICES\", inds.astype(np.int32))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT:\\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [[1. 1.2]\n [2.3 3.4]\n [4.5 5.7]]\nINDICES:\n [[0 1]\n [1 2]]\nOUTPUT:\n [[[1. 1.2]\n [2.3 3.4]]\n\n [[2.3 3.4]\n [4.5 5.7]]]\n\n```\n\n
    \n\n","inputs":[{"description":"Input data tensor of rank $r>=1$","name":"DATA"},{"description":"Input indices tensor of rank $q$. This tensor must contain integers.","name":"INDICES"}],"outputs":[{"description":"Output tensor of rank $q+(r-1)$","name":"OUTPUT"}],"support_level":"default"}},{"name":"KeyValueToMap","schema":{"description":"Convert key and value blob pairs into a map blob","inputs":[{"description":"Blob reference to the key","name":"key blob"},{"description":"Blob reference to the value","name":"value blob"}],"outputs":[{"description":"Blob reference to the map","name":"map blob"}],"support_level":"default"}},{"name":"Unique","schema":{"description":"\nDeduplicates input indices vector and optionally produces reverse remapping.\nThere's no guarantees on the ordering of the output indices.\n","inputs":[{"description":"1D tensor of int32 or int64 indices.","name":"indices"}],"outputs":[{"description":"1D tensor of deduped entries.","name":"unique_indices"},{"description":"(optional) mapping from `indices` to `unique_indices`. This has the same shape as `indices`. Its elements are the indices into `unique_indices` such that `Gather(['unique_indices', 'remapping'])` yields `indices`.","name":"remapping"}],"support_level":"default"}},{"name":"ResizeNearestGradient","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"AveragePut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an average.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"SoftmaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"BatchBucketize","schema":{"description":"\nBucketize the float_features into sparse features.\nThe float_features is a N * D tensor where N is the batch_size, and D is the feature_dim.\nThe indices is a 1D tensor containing the indices of the features that need to be bucketized.\nThe lengths is a 1D tensor that splits the following 'boundaries' argument.\nThe boundaries is a 1D tensor containing the border list for each feature.\n\nWith in each batch, `indices` should not have duplicate number,\nand the number of elements in `indices` should be less than or equal to `D`.\nEach element in `lengths` vector (lengths[`i`]) represents\nthe number of boundaries in the sub border list.\nThe sum of all elements in `lengths` must be equal to the size of `boundaries`.\nIf lengths[0] = 2, the first sub border list is [0.5, 1.0], which separate the\nvalue to (-inf, 0.5], (0,5, 1.0], (1.0, inf). The bucketized feature will have\nthree possible values (i.e. 0, 1, 2).\n\n\nFor example, with input:\n\n float_features = [[1.42, 2.07, 3.19, 0.55, 4.32],\n [4.57, 2.30, 0.84, 4.48, 3.09],\n [0.89, 0.26, 2.41, 0.47, 1.05],\n [0.03, 2.97, 2.43, 4.36, 3.11],\n [2.74, 5.77, 0.90, 2.63, 0.38]]\n indices = [0, 1, 4]\n lengths = [2, 3, 1]\n boundaries = [0.5, 1.0, 1.5, 2.5, 3.5, 2.5]\n\nThe output is:\n\n output =[[2, 1, 1],\n [2, 1, 1],\n [1, 0, 0],\n [0, 2, 1],\n [2, 3, 0]]\n\nafter running this operator.\n","inputs":[{"description":"2-D dense tensor, the second dimension must be greater or equal to the indices dimension","name":"float_features"},{"description":"Flatten tensor, containing the indices of `float_features` to be bucketized. The datatype must be int32.","name":"indices"},{"description":"Flatten tensor, the size must be equal to that of `indices`. The datatype must be int32.","name":"lengths"},{"description":"Flatten tensor, dimension has to match the sum of lengths","name":"boundaries"}],"outputs":[{"description":"2-D dense tensor, with 1st dim = float_features.dim(0), 2nd dim = size(indices)in the arg list, the tensor is of the same data type as `feature`.","name":"bucktized_feat"}],"support_level":"default"}},{"name":"CreateTensorVector","schema":{"description":"Create a std::unique_ptr >","support_level":"default"}},{"name":"UnsortedSegmentSum","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"}],"description":"\nApplies 'Sum' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentSum).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"CreateTreeCursor","schema":{"attributes":[{"description":"A list of strings each one representing a field of the dataset.","name":"fields","option":"optional"}],"description":"\nCreates a cursor to iterate through a list of tensors, where some of those\ntensors contain the lengths in a nested schema. The schema is determined by\nthe `fields` arguments.\n\nFor example, to represent the following schema:\n\n Struct(\n a=Int(),\n b=List(List(Int)),\n c=List(\n Struct(\n c1=String,\n c2=List(Int),\n ),\n ),\n )\n\nthe field list will be:\n [\n \"a\",\n \"b:lengths\",\n \"b:values:lengths\",\n \"b:values:values\",\n \"c:lengths\",\n \"c:c1\",\n \"c:c2:lengths\",\n \"c:c2:values\",\n ]\n\nAnd for the following instance of the struct:\n\n Struct(\n a=3,\n b=[[4, 5], [6, 7, 8], [], [9]],\n c=[\n Struct(c1='alex', c2=[10, 11]),\n Struct(c1='bob', c2=[12]),\n ],\n )\n\nThe values of the fields will be:\n {\n \"a\": [3],\n \"b:lengths\": [4],\n \"b:values:lengths\": [2, 3, 0, 1],\n \"b:values:values\": [4, 5, 6, 7, 8, 9],\n \"c:lengths\": [2],\n \"c:c1\": [\"alex\", \"bob\"],\n \"c:c2:lengths\": [2, 1],\n \"c:c2:values\", [10, 11, 12],\n }\n\nIn general, every field name in the format \"{prefix}:lengths\" defines a domain\n\"{prefix}\", and every subsequent field in the format \"{prefix}:{field}\" will\nbe in that domain, and the length of the domain is provided for each entry of\nthe parent domain. In the example, \"b:lengths\" defines a domain of length 4, so\nevery field under domain \"b\" will have 4 entries.\nThe \"lengths\" field for a given domain must appear before any reference to\nthat domain.\n\nReturns a pointer to an instance of the Cursor, which keeps the current offset\non each of the domains defined by `fields`. Cursor also ensures thread-safety\nsuch that ReadNextBatch and ResetCursor can be used safely in parallel.\n\nA cursor does not contain data per se, so calls to ReadNextBatch actually need\nto pass a list of blobs containing the data to read for each one of the fields.\n","outputs":[{"description":"A blob pointing to an instance of a new TreeCursor.","name":"cursor"}],"support_level":"default"}},{"name":"UnsortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"HasElements","schema":{"description":"\nThe *HasElements* op accepts a single or multiple input tensors, and produces a single boolean output $has\\_elements$. The output is *True* if and only if any of the input tensor has size > 0. Note, this op is the opposite of the *IsEmpty* op.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"HasElements\",\n [\"tensor\"],\n [\"has_elements\"],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"tensor\", np.random.randn(2, 2).astype(np.float32))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"has_elements: \", workspace.FetchBlob(\"has_elements\"),\"\\n\")\n\n// Use an empty tensor\nworkspace.FeedBlob(\"tensor\", np.empty(0))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"has_elements: \", workspace.FetchBlob(\"has_elements\"))\n\n```\n\n**Result**\n\n```\n\ntensor:\n [[ 0.6116506 -0.54433197]\n [ 0.19406661 -0.7338629 ]]\nhas_elements: True\n\ntensor:\n []\nhas_elements: False\n\n```\n\n
    \n\n","inputs":[{"description":"Input data tensor to check for elements.","name":"tensor"},{"description":"List of input data tensors to check for elements.","name":"X1, X2, ..."}],"outputs":[{"description":"Output scalar boolean tensor. True if input has size > 0.","name":"has_elements"}],"support_level":"default"}},{"name":"Int8ConvTranspose","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nThe transposed convolution consumes an input vector, the filter blob, and\nthe bias blob, and computes the output. Note that other parameters, such as\nthe stride and kernel size, or the pads' sizes in each direction are not\nnecessary for input because they are provided by the\nConvTransposeUnpoolOpBase operator. Various dimension checks are done\nimplicitly, and the sizes are specified in the Input docs for this operator.\nAs is expected, the filter is deconvolved with a subset of the\nimage and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nconv_transpose_op_impl.h is the templated implementation of the\nconv_transpose_op.h file, which is why they are separate files.\n ","inputs":[{"description":"Input data blob from previous layer; has size (N x H x W x C), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that NHWC is supported now","name":"X"},{"description":"The filter blob that will be used in the transposed convolution; has size (M x kH x kW x C), where C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the convolution;has size (C). Optional, if not passed, will treat it as all 0.","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the transposed convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"LastNWindowCollector","schema":{"attributes":[{"description":"The number of random samples to append for each positive samples","name":"num_to_collect","option":"optional"}],"description":"\nCollect the last N rows from input data. The purpose is to keep track of data\naccross batches, so for example suppose the LastNWindowCollector is called\nsuccessively with the following input data\n\n [1, 2, 3, 4]\n [5, 6, 7]\n [8, 9, 10, 11]\n\nAnd the number of items is set to 6, then the output after the 3rd call\nwill contain the following elements:\n\n [6, 7, 8, 9, 10, 11]\n\nNo guarantee is made on the ordering of elements in input. So a valid value for\noutput could have been\n\n [11, 10, 9, 8, 7, 6]\n\nAlso, this method works for any order tensor, treating the first dimension as\ninput rows and keeping the last N rows seen as input. So for instance:\n\n [[1, 2], [2, 3], [3, 4], [4, 5]]\n [[5, 6], [6, 7], [7, 8]]\n [[8, 9], [9, 10], [10, 11], [11, 12]]\n\nA possible output would be\n\n [[6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12]]\n\nThis is not thread safe unless a mutex is given.\n","inputs":[{"description":"The buffer for last-N record. Should be initialized to empty tensor","name":"last-N buffer"},{"description":"The cursor pointing to the next position that should be replaced. Should be initialized to 0.","name":"next cursor"},{"description":"tensor to collect from","name":"DATA"},{"description":"(optional) mutex to use to make this thread-safe","name":"MUTEX"},{"description":"","name":"NUM_VISITED"}],"outputs":[{"description":"Data stored in sessions","name":"last-N buffer"},{"description":"Updated input cursor","name":"next cursor"},{"description":"number of records seen so far","name":"NUM_VISITED"}],"support_level":"default"}},{"name":"Bucketize","schema":{"attributes":[{"description":"bucketization boundaries","name":"boundaries","option":"optional"}],"description":"\nThis operator works as bucketize in tensorflow and digitize\nin numpy. It bucketizes the input 'X' based on argument 'boundaries'.\nFor each value x in input 'data', the operator returns index i given\nboundaries[i-1] < x <= boundaries[i].\nIf values in 'data' are beyond the bounds of boundaries, 0 or\nlen(boundaries) is returned as appropriate.\nThe boundaries need to be monotonically increasing.\nFor example\n\nIf data = [2, 4, 1] and boundaries = [0.1, 2.5], then\n\noutput = [1, 2, 1]\n\nIf data = [[2, 3], [4, 1], [2, 5]] and boundaries = [0.1, 2.5], then\n\noutput = [[1, 2], [2, 1], [1, 2]]\n\n","inputs":[{"description":"input tensor","name":"data"}],"outputs":[{"description":"indices of bins given by boundaries to which each valuein data belongs","name":"output"}],"support_level":"default"}},{"name":"HSoftmax","schema":{"attributes":[{"description":"Serialized HierarchyProto string containing list of vocabulary words and their paths from root of hierarchy to the leaf","name":"hierarchy","option":"optional"}],"description":"\nHierarchical softmax is an operator which approximates the softmax operator\nwhile giving significant training speed gains and reasonably comparable\nperformance. In this operator, instead of calculating the probabilities of all\nthe classes, we calculate the probability of each step in the path from root to\nthe target word in the hierarchy.\n\nThe operator takes a 2-D tensor (Tensor) containing a batch of layers, a\nset of parameters represented by the weight matrix and bias terms, and a 1-D\ntensor (Tensor) holding labels, or the indices of the target class. The\nhierarchy has to be specified as an argument to the operator.\n\nThe operator returns a 1-D tensor holding the computed log probability of the\ntarget class and a 2-D tensor of intermediate outputs (from the weight matrix\nand softmax from each step in the path from root to target class) which will be\nused by the gradient operator to compute gradients for all samples in the batch.\n","inputs":[{"description":"Input data from previous layer","name":"X"},{"description":"2D blob containing 'stacked' fully connected weight matrices. Each node in the hierarchy contributes one FC weight matrix if it has children nodes. Dimension is N*D, D is input dimension of data (X), N is sum of all output dimensions, or total number of nodes (excl root)","name":"W"},{"description":"1D blob with N parameters","name":"b"},{"description":"int word_id of the target word","name":"labels"}],"outputs":[{"description":"1-D of log probability outputs, one per sample","name":"Y"},{"description":"Extra blob to store the intermediate FC and softmax outputs for each node in the hierarchical path of a word. The outputs from samples are stored in consecutive blocks in the forward pass and are used in reverse order in the backward gradientOp pass","name":"intermediate_output"}],"support_level":"default"}},{"name":"ReduceFrontWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SpatialSoftmaxWithLoss","schema":{"description":"\nCombined Spatial Softmax and Cross-Entropy loss operator.\nSimilar to SoftmaxWithLoss, this operator computes the spatial softmax\nnormalized values for each layer in the batch of the given input, after which\ncross-entropy loss is computed. This operator is numerically more stable than\nseparate Softmax and CrossEntropy ops. The inputs are a 2-D tensor\n(Tensor) of size (batch_size x input_feature_dimensions) and tensor of\nlabels (ground truth).\nOutput is tensor with the probability for each label in a pixel for each example\n(N x D x W x H) and averaged loss (scalar).\nFor spatial softmax, weighting is by x,y position of the input.\n","inputs":[{"description":"Unscaled log probabilities","name":"logits"},{"description":"Ground truth","name":"labels"},{"description":"Optional blob to be used to weight the samples for the loss. With spatial set, weighting is by x,y of the input","name":"weight_tensor"}],"outputs":[{"description":"Tensor with softmax cross entropy loss","name":"softmax"},{"description":"Average loss","name":"loss"}],"support_level":"default"}},{"name":"SafeDequeueBlobs","schema":{"attributes":[{"description":"(default 1) If > 1, multiple records will be dequeued and tensors for each column will be concatenated. This requires all tensors in the records to be at least 1D, and to have the same inner dimensions.","name":"num_records","option":"optional"}],"description":"\nDequeue the blobs from queue. When the queue is closed and empty, the output\nstatus will be set to true which can be used as exit criteria for execution\nstep.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"outputs":[{"description":"The blob to store the dequeued data","name":"blob"},{"description":"Is set to 0/1 depending on the success of dequeue","name":"status"}],"support_level":"default"}},{"name":"Copy","schema":{"description":"\nCopy input tensor into output, potentially across devices.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/copy_op.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/copy_op.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Copy\",\n [\"input\"],\n [\"output\"]\n)\n\nworkspace.FeedBlob(\"input\", np.random.rand(3,3))\nprint(\"input:\", workspace.FetchBlob(\"input\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output:\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n[[0.16826761 0.68168217 0.55196001]\n [0.19735483 0.34837823 0.69015595]\n [0.09448514 0.57390828 0.37097193]]\noutput:\n[[0.16826761 0.68168217 0.55196001]\n [0.19735483 0.34837823 0.69015595]\n [0.09448514 0.57390828 0.37097193]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): input tensor to copy","name":"input"}],"outputs":[{"description":"(*Tensor*): copy of input tensor","name":"output"}],"support_level":"default"}},{"name":"AveragePool2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeLogMeanExp","schema":{"description":"\nApplies 'LogMeanExp' to each segment of input tensor. In order to allow for more\nefficient implementation of 'LogMeanExp', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nLogMeanExp computes the element-wise log of the mean of exponentials of input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"MergeMultiListFeatureTensors","schema":{"description":"Merge given multi-feature tensors with list features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values","name":"in1_values_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"CountUp","schema":{"description":"\nIncreases count value by 1 and outputs the previous value atomically.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* Count value BEFORE this operation.","name":"previous_count"}],"support_level":"default"}},{"name":"MergeSingleScalarFeatureTensorsGradient","schema":{"description":"Explode multi-feature tensor of scalar features into one or moresingle-feature tensors\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".presence","name":"in1_presence"},{"description":".values_grad","name":".values_grad"}],"outputs":[{"description":"_grad of inputs","name":"in1_grad"}],"support_level":"default"}},{"name":"GFtrl","schema":{"description":null,"support_level":"default"}},{"name":"Acos","schema":{"description":"\nCalculates the arccosine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arccosine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"SoftsignGradient","schema":{"description":"\nCalculates the softsign gradient (sgn(x)/(1+|x|)^2) of the given input tensor\nelement-wise.\n","inputs":[{"description":"1-D input tensor","name":"input"}],"outputs":[{"description":"The softsign gradient (sgn(x)/(1+|x|)^2) values of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"MergeDim","schema":{"description":"\nMerge first two dimensions in a single dimension with size dim(0) * dim(1).\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reshaped tensor.","name":"reshaped"}],"support_level":"default"}},{"name":"Int8ResizeNearest","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"},{"description":"Output dimensions (HxW). If specified this takes precedence over scale values.","name":"output_size","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input Int8 tensor","name":"X"}],"outputs":[{"description":"Output Int8 tensor","name":"Y"}],"support_level":"default"}},{"name":"LC","schema":{"description":"\nThe locally connected operator consumes an input vector, a filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"AcosGradient","schema":{"description":null,"support_level":"default"}},{"name":"IndexHash","schema":{"attributes":[{"description":"seed for the hash function","name":"seed","option":"optional"},{"description":"must be > 0, hashed ids will be modulo this number","name":"modulo","option":"optional"}],"description":"\nThis operator translates a list of indices into a list of hashed indices.\nA seed can be fed as an argument to change the behavior of the hash function.\nIf a modulo is specified, all the hashed indices will be modulo the\nspecified number. All input and output indices are enforced to be positive.\n","inputs":[{"description":"Input feature indices.","name":"Indices"}],"outputs":[{"description":"Hashed feature indices.","name":"HashedIndices"}],"support_level":"default"}},{"name":"GroupNorm","schema":{"attributes":[{"description":"(int) default 32; number of groups used by GN.","name":"num_groups","option":"optional"},{"description":"(float) default 1e-5; small constant added to var.","name":"epsilon","option":"optional"}],"description":"\nGroup Normalization (GN) operation: https://arxiv.org/abs/1803.08494\n","inputs":[{"description":">=4D feature map input of shape (N, C, H, W) or (N, C, T, H, W)","name":"X"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"gamma"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"beta"}],"outputs":[{"description":"The output >=4-dimensional tensor of the same shape as X.","name":"Y"},{"description":"The mean of shape (N, G). For backward usage or reference. Cannot be used as activations.","name":"mean"},{"description":"The std of shape (N, G). For backward usage or reference. Cannot be used as activations.","name":"std"}],"support_level":"default"}},{"name":"ChannelShuffleGradient","schema":{"description":null,"support_level":"default"}},{"name":"DestroyCommonWorld","schema":{"description":"Closes all connections managed by a common world.","inputs":[{"description":"The common world to be destroyed.","name":"common_world"}],"support_level":"default"}},{"name":"Floor","schema":{"description":"\nElement-wise application of the floor function ($y=floor(x)$) to the input\ntensor `X`. Output tensor shape is the same as the input tensor. This\noperator can be used in an in-place fashion by using the same input blob as the\noutput blob.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/floor_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Floor\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.uniform(-10, 10, (5,5))).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[ 3.813361 -1.319647 5.2089314 -4.931328 0.6218652 ]\n [ 7.2757645 5.5552588 5.785643 -2.4790506 -0.41400087]\n [ 1.1541046 -6.933266 3.3754056 1.6569928 -1.7670316 ]\n [-3.4932013 4.891472 1.5530115 -3.2443287 -4.605099 ]\n [-4.574543 -7.360948 5.91305 -8.196495 -5.357458 ]]\nX after running op:\n[[ 3. -2. 5. -5. 0.]\n [ 7. 5. 5. -3. -1.]\n [ 1. -7. 3. 1. -2.]\n [-4. 4. 1. -4. -5.]\n [-5. -8. 5. -9. -6.]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"LengthsPartition","schema":{"attributes":[{"description":"(int, default 0) If set, the operator transforms the first tensor values as floor(X_ij / num_partitions)","name":"pack_first_input","option":"optional"}],"description":"\nLengthsPartition splits the input int tensor into multiple ones according to the\nsecond tensor. The first dimension is expected to be the tensor that describes\nlengths of the elements.\n\nTakes the second input and partitions it to shards according to the remainder of\nvalues modulo the number of partitions. It requires the second tensor to be\na 1D-tensor of the integral type. The first tensor should be 1D-tensor of int32\nthat would represent the lengths of the elements in the input. The number of\npartitions is derived as (num_output / num_input).\n\nIf additional inputs are present they must have the same shape as the first\ninput, optionally with extra trailing dimensions. They will be partitioned\naccordingly to the first input.\n\nOptional arg 'pack_first_input' transforms the first tensor values as\nX_ij / num_partitions.\n\nOutputs are ordered as\nX_0_part_0, X_1_part_0, ..., X_N-1_part_0, X_0_part_1, ..., X_N-1_part_K-1\n","inputs":[{"description":"Input tensor containing data to be partitioned. The number of input tensors might be greater than 1 but must have the same shape as the previous tensors.","name":"input"}],"outputs":[{"description":"Output Partitions. The number of output tensors has to be a multiple of the number of input tensors.","name":"partitions"}],"support_level":"default"}},{"name":"CreateCounter","schema":{"attributes":[{"default":0,"description":"Initial count for the counter, must be >= 0.","name":"init_count","option":"optional","type":"int64"}],"description":"\nCreates a count-down counter with initial value specified by the `init_count`\nargument.\n\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","outputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a new counter.","name":"counter"}],"support_level":"default"}},{"name":"MarginRankingCriterion","schema":{"attributes":[{"description":"The margin value as a float. Default is 1.0.","name":"margin","option":"optional"}],"description":"\nMarginRankingCriterion takes two input data X1 (Tensor),\nX2 (Tensor), and label Y (Tensor) to produce the\nloss (Tensor) where the loss function,\nloss(X1, X2, Y) = max(0, -Y * (X1 - X2) + margin), is applied to\nthe tensor elementwise.\n\nIf y == 1 then it assumed the first input should be ranked higher\n(have a larger value) than the second input, and vice-versa for\ny == -1.\n","inputs":[{"description":"The left input vector as a 1-dim TensorCPU.","name":"X1"},{"description":"The right input vector as a 1-dim TensorCPU.","name":"X2"},{"description":"The label as a 1-dim TensorCPU with int value of 1 or -1.","name":"Y"}],"outputs":[{"description":"The output loss with the same dimensionality as X1.","name":"loss"}],"support_level":"default"}},{"name":"MergeIdLists","schema":{"description":"\nMergeIdLists: Merge multiple ID_LISTs into a single ID_LIST.\n\nAn ID_LIST is a list of IDs (may be ints, often longs) that represents a single\nfeature. As described in https://caffe2.ai/docs/sparse-operations.html, a batch\nof ID_LIST examples is represented as a pair of lengths and values where the\n`lengths` (int32) segment the `values` or ids (int32/int64) into examples.\n\nGiven multiple inputs of the form lengths_0, values_0, lengths_1, values_1, ...\nwhich correspond to lengths and values of ID_LISTs of different features, this\noperator produces a merged ID_LIST that combines the ID_LIST features. The\nfinal merged output is described by a lengths and values vector.\n\nWARNING: The merge makes no guarantee about the relative order of ID_LISTs\nwithin a batch. This can be an issue if ID_LIST are order sensitive.\n","inputs":[{"description":"Lengths of the ID_LISTs batch for first feature","name":"lengths_0"},{"description":"Values of the ID_LISTs batch for first feature","name":"values_0"}],"outputs":[{"description":"Lengths of the merged ID_LISTs batch","name":"merged_lengths"},{"description":"Values of the merged ID_LISTs batch","name":"merged_values"}],"support_level":"default"}},{"name":"SumElements","schema":{"attributes":[{"description":"(*bool*): set to True to compute the average of the elements rather than the sum","name":"average","option":"optional"}],"description":"\nSums the elements of the input tensor. Tensor type must be float32.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nsum_op = core.CreateOperator(\n \"SumElements\",\n [\"X\"],\n [\"Y\"]\n)\n\navg_op = core.CreateOperator(\n \"SumElements\",\n [\"X\"],\n [\"Y\"],\n average=True\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(sum_op)\nprint(\"Y (sum_op):\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(avg_op)\nprint(\"Y (avg_op):\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[7. 2. 5.]\n [9. 4. 2.]\n [1. 2. 5.]]\nY (sum_op): 37.0\nY (avg_op): 4.111111\n\n```\n\n
    \n\n ","inputs":[{"description":"(*Tensor``*): blob pointing to an instance of a counter","name":"X"}],"outputs":[{"description":"(*Tensor``*): Scalar tensor containing the sum (or average)","name":"sum"}],"support_level":"default"}},{"name":"ThresholdedReluGradient","schema":{"description":"\nThresholdedReluGradient takes both Y and dY and uses this to update dX\naccording to the chain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"GivenTensorInt64Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SparseLengthsSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"CountDown","schema":{"description":"\nIf the internal count value > 0, decreases count value by 1 and outputs False,\notherwise outputs True.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: bool)* False unless the internal count is zero.","name":"done"}],"support_level":"default"}},{"name":"ReciprocalGradient","schema":{"description":null,"support_level":"default"}},{"name":"Sqr","schema":{"description":"\nPerforms element-wise squaring ($x^2$) of input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sqr_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sqr\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[4. 6. 2.]\n [0. 1. 6.]\n [9. 2. 7.]]\nY:\n[[16. 36. 4.]\n [ 0. 1. 36.]\n [81. 4. 49.]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"StoreWait","schema":{"attributes":[{"description":"names of the blobs to wait for (optional)","name":"blob_names","option":"optional"}],"description":"\nWait for the specified blob names to be set. The blob names can be passed\neither as an input blob with blob names or as an argument.\n","inputs":[{"description":"unique_ptr","name":"handler"},{"description":"names of the blobs to wait for (optional)","name":"names"}],"support_level":"default"}},{"name":"ColwiseMax","schema":{"description":"\nCompute column-wise max reduction of the input tensor. This op takes one input, $X$, of shape $BxMxN$, where $B$ is the batch size, $M$ is number of rows, and $N$ is number of columns. The output of this op, $Y$, is a matrix of shape $BxN$, with one row for each element of the batch, and the same number of columns as the input tensor.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ColwiseMax\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X, simulating a batch of 2, 4x4 matricies\nX = np.random.randint(0,high=20,size=(2,4,4))\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[17 15 2 6]\n [ 8 12 6 0]\n [ 6 9 7 3]\n [ 4 13 16 13]]\n\n [[ 0 3 4 12]\n [18 1 17 12]\n [ 7 17 13 14]\n [12 17 2 1]]]\nY:\n [[17. 15. 16. 13.]\n [18. 17. 17. 14.]]\n\n```\n\n
    \n\n ","inputs":[{"description":"A tensor of dimensions $B x M x N$ to compute columnwise-max. Here, $B$ is batch size, and $M$ and $N$ are the number of rows and columns of each element of the batch, respectively.","name":"X"}],"outputs":[{"description":"The output tensor of shape $B x N$, where each row represents the column-wise maximums for that element of the input batch.","name":"Y"}],"support_level":"default"}},{"name":"LogFatal","schema":{"description":null,"support_level":"default"}},{"name":"StringIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps string keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"support_level":"default"}},{"name":"CopyRowsToTensor","schema":{"description":"\n This operator takes in a 2d tensor, a list of indices, and a 1d tensor\n with the same width of the 2d tensor. It will replace the rows in 2d\n tensor specified in indices with the 2d tensor. The operator does an\n in-place change to the input tensor.\n Example:\n INPUT_TENSOR = [[1, 2], [3, 4], [5, 6]]\n INDICES = [1]\n ROW = [9, 0]\n OUTPUT_TENSOR = [[1, 2], [9, 0], [5, 6]]\n ","inputs":[{"description":"Input tensor needs to be modified.","name":"input_tensor"},{"description":"Indices of rows need to be copied","name":"indices"},{"description":"1-d tensor that is going to replace the rows","name":"row"}],"outputs":[{"description":"updated tensor","name":"output_tensor"}],"support_level":"default"}},{"name":"MakeTwoClass","schema":{"description":"\nGiven a vector of probabilities, this operator transforms this into a 2-column\n matrix with complimentary probabilities for binary classification. In explicit\n terms, given the vector X, the output Y is vstack(1 - X, X).\n ","inputs":[{"description":"Input vector of probabilities","name":"X"}],"outputs":[{"description":"2-column matrix with complimentary probabilities of X for binary classification","name":"Y"}],"support_level":"default"}},{"name":"Snapshot","schema":{"description":null,"support_level":"default"}},{"name":"NegateGradient","schema":{"description":"\nNegagteGradient operator in forward pass simply copies input to the\noutput, and in backward pass, flips the sign of the output gradient\n","support_level":"default"}},{"name":"Not","schema":{"description":"\nPerforms element-wise negation on input tensor `X`.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n\"Not\",\n[\"X\"],\n[\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3, 3) > 0.5))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[ True False False]\n[False False False]\n[ True True True]]\nY:\n[[False True True]\n[ True True True]\n[False False False]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(Tensor``)* Negated output tensor.","name":"Y"}],"support_level":"default"}},{"name":"PrependDim","schema":{"attributes":[{"description":"Size of the dimension to prepend.","name":"dim_size","option":"optional"}],"description":"\nReshape the tensor by prepending a dimension of fixed size and dividing the\nsize of the next dimension by that amount.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reshaped tensor.","name":"reshaped"}],"support_level":"default"}},{"name":"SendTensor","schema":{"attributes":[{"description":"The rank to send the tensor to.","name":"dst","option":"optional"},{"description":"(int) a tag to send the tensor with.","name":"tag","option":"optional"},{"description":"(bool) if set, only send the content and assume that the receiver has already known the tensor's shape and information.","name":"raw_buffer","option":"optional"}],"description":"\nSends the tensor to another node.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allgathered.","name":"X"},{"description":"An int CPUtensor of size 1 specifying the rank. If given, this overrides the 'to' argument of the op.","name":"dst"},{"description":"An int CPUtensor of size 1 specifying the tag to send the tensor with. This overrides the 'tag' argument of the op.","name":"tag"}],"support_level":"default"}},{"name":"InferenceLSTM","schema":{"attributes":[{"description":"(*long*): number of layers in the lstm stack","name":"num_layers","option":"optional"},{"description":"(*bool*): whether the cells have biases or not","name":"has_biases","option":"optional"},{"description":"(*bool*): whether the batch is at dim 0","name":"batch_first","option":"optional"},{"description":"(*bool*): if bidirectional","name":"bidirectional","option":"optional"}],"description":null,"outputs":[{"description":"the output of the last layer of lstm","name":"output"},{"description":"hidden state at t = seq_len","name":"hidden"},{"description":"cell state at t = seq_len","name":"cell"}],"support_level":"default"}},{"name":"SumElementsInt","schema":{"description":"Sums the integer elements of the input tensor.","inputs":[{"description":"Tensor to sum up","name":"X"}],"outputs":[{"description":"Scalar sum","name":"sum"}],"support_level":"default"}},{"name":"SparseAdagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nGiven inputs (param, moment, indices, grad, lr), runs the dense AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment_1"}],"support_level":"default"}},{"name":"Int8AveragePoolRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"AveragePool \nconsumes an input blob X and applies average pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Average pooling consisting of averaging all values of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from average pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linear function, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"SegmentIdsToRanges","schema":{"description":"\nTransfers a vector of segment ids to a vector of segment ranges. This operation\nsupports non-consecutive segment ids. Segments not appearing in the input vector\nwill have length 0. If the second input is provided, the number of segments =\nthe size of its first dimension. Otherwise, the number of segments = the last\nindex in the first input vector + 1.\n","inputs":[{"description":"1-D int32_t or int64_t tensor of segment ids","name":"segment_ids"},{"description":"if provided, number of segments = the size of its first dimension","name":"data (optional)"}],"outputs":[{"description":"1-D int64_t tensor of segment lengths","name":"lengths"}],"support_level":"default"}},{"name":"CreateCommonWorld","schema":{"attributes":[{"description":"(int) size of the common world.","name":"size","option":"optional"},{"description":"(int) rank of this node in the common world.","name":"rank","option":"optional"}],"description":"\nCreates a common world for communication operators.\n","inputs":[{"description":"Key/value handler for rendezvous (optional).","name":"kv_handler"}],"outputs":[{"description":"A common world for collective operations.","name":"comm_world"}],"support_level":"default"}},{"name":"SliceGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseUnsortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"DBExists","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"description":"Path to the db in question; see the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db_name","option":"optional","type":"string"},{"description":"Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional","type":"string"}],"description":"\nChecks if the db described by the arguments exists.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"DBExists\",\n [],\n [\"exists\"],\n db_name=\"test_db\",\n db_type=\"leveldb\",\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"exists:\", workspace.FetchBlob(\"exists\"))\n\n```\n\n
    \n\n","outputs":[{"description":"*(type: Tensor``)* Scalar boolean output tensor. True if the db exists, else false.","name":"exists"}],"support_level":"default"}},{"name":"ReceiveTensor","schema":{"attributes":[{"description":"(int) he rank to receive the tensor from.","name":"src","option":"optional"},{"description":"(int) a tag to receive the tensor with.","name":"tag","option":"optional"},{"description":"(bool) if set, only send the content and assume that the receiver has already known the tensor's shape and information.","name":"raw_buffer","option":"optional"}],"description":"\nReceives the tensor from another node.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"In-place output. If raw_buffer is specified, Y should have pre-allocated data and type..","name":"Y"},{"description":"An int CPUtensor of size 1 specifying the rank. If given, this overrides the 'from' argument of the op.","name":"src"},{"description":"An int CPUtensor of size 1 specifying the tag to send the tensor with. This overrides the 'tag' argument of the op.","name":"tag"}],"outputs":[{"description":"The received tensor.","name":"Y"},{"description":"The sender that sent the message as a CPUTensor of size 1 and of type int.","name":"src"},{"description":"The tag that the message is sent with as a CPUTensor of size 1 and of type int.","name":"tag"}],"support_level":"default"}},{"name":"SquaredL2DistanceGradient","schema":{"description":null,"support_level":"default"}},{"name":"Swish","schema":{"description":"\nSwish takes one input data (Tensor) and produces one output data\n(Tensor) where the swish function, y = x / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchGatherGradient","schema":{"description":null,"support_level":"default"}},{"name":"LearningRate","schema":{"attributes":[{"description":"(float, required) base learning rate","name":"base_lr","option":"optional"},{"description":"(float, default 1.0) strategy for gamma enforcement","name":"policy","option":"optional"},{"description":"(float, default 1.0) used only for inv policy type","name":"power","option":"optional"},{"description":"(float, default 1.0) momentum of change","name":"gamma","option":"optional"},{"description":"(float, default 1.0) sampling rate on iterations","name":"stepsize","option":"optional"},{"description":"(boolean, default True) in alter policy","name":"active_first","option":"optional"},{"description":"(int64_t, required) in alter policy","name":"active_period","option":"optional"},{"description":"(int64_t, required) in alter policy","name":"inactive_period","option":"optional"},{"description":"(int, default -1) maximum iterations in this training run","name":"max_iter","option":"optional"},{"description":"(int, default 0) number of iterations over which to warmup lr","name":"num_iter","option":"optional"},{"description":"(float, default 0) starting multiplier for learning rate","name":"start_multiplier","option":"optional"},{"description":"(float, default 0) end multiplier for learning rate","name":"end_multiplier","option":"optional"},{"description":"(float, default 0.5) constant multiplier for learning rate","name":"multiplier","option":"optional"},{"description":"(float, default 1) start multiplier for learning rate","name":"multiplier_1","option":"optional"},{"description":"(float, default 1) end multiplier for learning rate","name":"multiplier_2","option":"optional"},{"description":"(int array, default empty) number of iterations for each sub learning rate policy in composite policy","name":"sub_policy_num_iters","option":"optional"},{"description":"","name":"m1","option":"optional"},{"description":"","name":"n1","option":"optional"},{"description":"","name":"m2","option":"optional"},{"description":"","name":"n2","option":"optional"},{"description":"","name":"m3","option":"optional"},{"description":"(float, default 0.005) max learning rate","name":"max_lr","option":"optional"},{"description":"defaults to 0.1","name":"start_warmup_multiplier","option":"optional"},{"description":"defaults to 10000000","name":"constant_warmup_num_iter","option":"optional"},{"description":"defaults to 10000000","name":"linear_warmup_num_iter","option":"optional"},{"description":"defaults to 0.05, part of CompositeCyclicalLRPolicy","name":"cyclical_max_lr","option":"optional"},{"description":"defaults to 1000000, part of CompositeCyclicalLRPolicy","name":"cyclical_step_size","option":"optional"},{"description":"defaults to 0.999, part of CompositeCyclicalLRPolicy","name":"cyclical_decay","option":"optional"},{"description":"defaults to 0.01, part of CompositeCosineLRPolicy","name":"cosine_min_lr","option":"optional"},{"description":"defaults to 0.05, part of CompositeCosineLRPolicy","name":"cosine_max_lr","option":"optional"},{"description":"defaults to 50, part of CompositeCosineLRPolicy","name":"cosine_period","option":"optional"},{"description":"defaults to 1,0, part of CompositeCosineLRPolicy","name":"cosine_t_mult","option":"optional"},{"description":"defaults to 0.99, part of CompositeCosineLRPolicy","name":"cosine_lr_shrink","option":"optional"}],"description":"\nLearning rate is a decreasing function of time. With low learning rates the\nimprovements will be linear. With high learning rates they will start to look\nmore exponential. Learning rate is controlled by the following arguments:\n\n\nRequired:\n `iterations`\n `base_lr`: base learning rate\n `policy`: this controls how the learning rate is applied, options are:\n `fixed`\n `step`: uses `stepsize`, `gamma`\n `exp`: uses `gamma`\n `gate`: uses 'multiplier_1', 'multiplier_2', `num_iter``\n `inv`: uses `gamma`, `power`\n `linearWarmup`: uses `start_multiplier`, `num_iter`\n `constantWarmup`: uses `multiplier`, `num_iter`\n `alter`: uses `active_first`, `active_period`, `inactive_period`\n `hill`: uses those in both `linearWarmup` and `inv`, plus `end_multiplier`\n `composite`: uses `sub_policy_num_iters` and additional args with format\n `cyclic`: uses `max_lr`, `stepsize`\n `cosine`: uses `min_lr`, `max_lr`, `period`, `t_mult`, `lr_shrink`\n `constantThenLinearWarmup`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`\n `compositeCyclical`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`, `cyclical_max_lr`, `cyclical_step_size`, `cyclical_decay`\n `compositeCosine`: uses `start_warmup_multiplier`, `constant_warmup_num_iter`, `linear_warmup_num_iter`, `cosine_max_lr`, `cosine_period`, `cosine_t_mult`, `cosine_lr_shrink`\n sub_policy_{sub_policy_index}_{sub_policy_arg}, for example:\n sub_policy_0_policy: \"exp\", sub_policy_0_gamma: 0.99,\n sub_policy_0_lr_scale: 1.2\n sub_policy_0_policy: \"fixed\", sub_policy_0_lr_scale: 1.0\n sub_policy_num_iters: [1000, 1000]\n\nOptional:\n `stepsize`: defaults to 0\n `max_lr`: defaults to 0.005\n `gamma`: defaults to 0\n `power`: defaults to 0\n `num_iter`: defaults to 0\n `start_multiplier`: defaults to 0\n `multiplier`: defaults to 0.5\n `multiplier_1`: defaults to 1\n `multiplier_2`: defaults to 1\n `m1`: defaults to 0.5, the first piece lr of piece warmup\n `n1`: defaults to 0, iter threshold of the first piece lr\n `m2`: defaults to 0.5, the second piece lr of piece warmup\n `n2`: defaults to 0, iter threshold of the second piece lr\n `m3`: defaults to 0.5, the third piece lr of piece warmup\n `start_warmup_multiplier`: defaults to 0.1, part of constantThenLinearWarmup\n `constant_warmup_num_iter`: defaults to 10000000, part of constantThenLinearWarmup and constantThenLinearWarmup\n `linear_warmup_num_iter`: defaults to 10000000, part of constantThenLinearWarmup, CompositeCyclicalLRPolicy, CompositeCosineLRPolicy\n `cyclical_max_lr`: defaults to 0.05, part of CompositeCyclicalLRPolicy\n `cyclical_step_size`: defaults to 1000000, part of CompositeCyclicalLRPolicy\n `cyclical_decay`: defaults to 1.0, part of CompositeCyclicalLRPolicy\n `cosine_min_lr`:defaults to 0.01, part of CompositeCosineLRPolicy\n `cosine_max_lr`:defaults to 0.05, part of CompositeCosineLRPolicy\n `cosine_period`:defaults to 50, part of CompositeCosineLRPolicy\n `cosine_t_mult`:defaults to 1.0, part of CompositeCosineLRPolicy\n `cosine_lr_shrink`:defaults to 0.99, part of CompositeCosineLRPolicy\n\nUsage:\n train_net.LearningRate(*iterations*, \"*label*\", base_lr=*float*,\n policy=\"policy_name\", stepsize=*int*, gamma=*float*)\n\n\nExample usage:\n train_net.LearningRate(200, \"LR\", base_lr=-0.1,\n policy=\"step\", stepsize=20, gamma=0.9)\n","inputs":[{"description":"description needed","name":"input"}],"outputs":[{"description":"description needed","name":"output"}],"support_level":"default"}},{"name":"PReluGradient","schema":{"description":"\n\nPReluGradient takes both Y and dY and uses this to update dX and dW according\nto the chain rule and derivatives of the rectified linear function.\n\n","support_level":"default"}},{"name":"LengthsMean","schema":{"description":"\nApplies 'Mean' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Mean' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n\n\nThe *LengthsMean* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the mean value in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [mean([2,4]), mean([3,1,2]), mean([10])] = [3,2,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsMean\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 3. 2. 10.]\n\n```\n\n
    \n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"Conv3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CheckCounterDone","schema":{"description":"\nIf the internal count value <= 0, outputs true, otherwise outputs false.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: bool)* True if the internal count is zero or negative, otherwise False.","name":"done"}],"support_level":"default"}},{"name":"LabelCrossEntropyGradient","schema":{"description":null,"support_level":"default"}},{"name":"Adam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nComputes the Adam update (https://arxiv.org/abs/1412.6980) for an\ninput gradient and momentum parameters. Concretely, given inputs\n(param, m1, m2, grad, lr, iters),\n\n t = iters + 1\n correction_multiplier = sqrt(1 - power(beta2, t)) /\n (1 - power(beta1, t))\n m1_o = (beta1 * m1) + (1 - beta1) * grad\n m2_o = (beta2 * m2) + (1 - beta2) * np.square(grad)\n grad_o = correction_multiplier * m1_o / \\\n (sqrt(m2_o) + epsilon)\n param_o = param + lr * grad_o\n\nand returns (param_o, m1_o, m2_o, grad_o), in which grad_o is an optional output\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"FCGradient","schema":{"description":null,"support_level":"default"}},{"name":"IsNaN","schema":{"description":"Returns a new tensor with boolean elements representing if each element is NaN or not.","inputs":[{"description":"Tensor to check for nan","name":"tensor"}],"outputs":[{"description":"Tensor containing a 1 at each location of NaN elements.","name":"output"}],"support_level":"default"}},{"name":"LengthsWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceBackSum","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **sum**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the sum operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [sum(1,5), sum(4,1,8), sum(2)] = [6, 13, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_sum_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackSum\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[2. 7. 7.]\n [1. 1. 0.]\n [9. 7. 2.]]\n\n [[6. 6. 4.]\n [1. 2. 6.]\n [6. 6. 3.]]]]\nY: [[36. 40.]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"LogitGradient","schema":{"attributes":[{"description":"small positive epsilon value, the default is 1e-6.","name":"eps","option":"optional"}],"description":null,"inputs":[{"description":"input float tensor","name":"X"},{"description":"input float tensor","name":"dY"}],"outputs":[{"description":"output float tensor","name":"dX"}],"support_level":"default"}},{"name":"RowwiseMax","schema":{"description":"\nCompute row-wise max reduction of the input tensor. This op takes one input, $X$, of shape $BxMxN$, where $B$ is the batch size, $M$ is number of rows, and $N$ is number of columns. The output of this op, $Y$, is a matrix of shape $BxM$, with one row for each element of the batch, and the same number of columns as the number of rows of the input tensor.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduction_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"RowwiseMax\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X, simulating a batch of 2, 4x4 matricies\nX = np.random.randint(0,high=20,size=(2,4,4))\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[[ 5 12 10 1]\n [ 4 16 2 15]\n [ 5 11 12 15]\n [15 4 17 19]]\n\n [[16 5 5 13]\n [17 2 1 17]\n [18 3 19 5]\n [14 16 10 16]]]\nY:\n [[12. 16. 15. 19.]\n [16. 17. 19. 16.]]\n\n```\n\n
    \n\n ","inputs":[{"description":"A tensor of dimensions $B x M x N$ to compute rowwise-max. Here, $B$ is batch size, and $M$ and $N$ are the number of rows and columns of each element of the batch, respectively.","name":"X"}],"outputs":[{"description":"The output tensor of shape $B x M$, where each row represents the row-wise maximums for that element of the input batch.","name":"Y"}],"support_level":"default"}},{"name":"Fail","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentMean","schema":{"description":"\nApplies 'Mean' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentMean that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceFrontMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"RemoveDataBlocks","schema":{"description":"\nShrink the data tensor by removing data blocks with given zero-based indices in\nthe outermost dimension of the tensor. Indices are not assumed in any order or\nunique but with the range [0, blocks_size). Indices could be empty.\n ","inputs":[{"description":"a N-D data tensor, N >= 1","name":"data"},{"description":"zero-based indices of blocks to be removed","name":"indices"}],"outputs":[{"description":"data after removing data blocks indexed by 'indices'","name":"shrunk data"}],"support_level":"default"}},{"name":"SwapBestPath","schema":{"description":"\nGiven a sequence of indices and a matrix, enforce that these indices have the\nbest columnwise scores\nscore\n","inputs":[{"description":"N*D predictions matrix","name":"predictions"},{"description":"N*1 vector holds the best path indices ","name":"bestPath"}],"outputs":[{"description":"N*D updated predictions matrix","name":"new_predictions"}],"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"StringEndsWith","schema":{"attributes":[{"description":"The suffix to check input strings against.","name":"suffix","option":"optional"}],"description":"\nPerforms the ends-with check on each string in the input tensor.\nReturns tensor of boolean of the same dimension of input.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of bools of same shape as input.","name":"bools"}],"support_level":"default"}},{"name":"While","schema":{"attributes":[{"description":"Net executed on each iteration","name":"loop_net","option":"optional"},{"description":"Net to (re)compute condition value","name":"cond_net","option":"optional"}],"description":"\n'While' control operator, first input is a scalar boolean blob that stores loop's\ncondition value. Accepts 'loop_net' (required) and 'cond_net' (optional) arguments for\nloop's body and condition subnets respectively. If condition subnet is specified,\nit is executed before the first and after each iteration. Subnets are executed in\nthe same workspace as 'While'.\n ","inputs":[{"description":"Scalar boolean condition","name":"condition"}],"support_level":"default"}},{"name":"Range","schema":{"description":"\nGenerates an output tensor within the half-open interval $[start, stop)$ (the interval including start but excluding stop).\n- The `start` input is optional, and defaults to 0 when not set.\n- The `step` input is optional, and defaults to 1 when not set.\n- The type of the `output` tensor is determined by the types of inputs used.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Range\",\n [\"start\", \"stop\", \"step\"],\n [\"output\"]\n)\n\nworkspace.FeedBlob(\"start\", np.array(4, dtype=np.int32))\nworkspace.FeedBlob(\"stop\", np.array(17, dtype=np.int32))\nworkspace.FeedBlob(\"step\", np.array(2, dtype=np.int32))\nprint(\"start:\", workspace.FetchBlob(\"start\"))\nprint(\"stop:\", workspace.FetchBlob(\"stop\"))\nprint(\"step:\", workspace.FetchBlob(\"step\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output:\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\nstart: 4\nstop: 17\nstep: 2\noutput: [ 4 6 8 10 12 14 16]\n\n```\n\n
    \n ","inputs":[{"description":"(*Tensor*): [OPTIONAL] scalar or 1-element tensor containing the start of the interval (inclusive) (default=0)","name":"start"},{"description":"(*Tensor*): scalar or 1-element tensor containing the end of the interval (exclusive)","name":"stop"},{"description":"(*Tensor*): [OPTIONAL] scalar or 1-element tensor specifying the spacing between values (default=1)","name":"step"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as inputs that contains the sequence","name":"output"}],"support_level":"default"}},{"name":"Int8AddRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Performs element-wise binary Add (with no broadcast support). \"\n \"Output will go through rectified linear \"\n \"function, where y = max(0, x).\n","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. It should be of the same size as A.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as A","name":"C"}],"support_level":"default"}},{"name":"SquareRootDivide","schema":{"description":"\nGiven DATA tensor with first dimension N and SCALE vector of the same size N\nproduces an output tensor with same dimensions as DATA. Which consists of DATA\nslices. i-th slice is divided by sqrt(SCALE[i]) elementwise. If SCALE[i] == 0\noutput slice is identical to the input one (no scaling)\n\nExample:\n\n Data = [\n [2.0, 4.0],\n [9.0, 12.0]\n ]\n\n SCALE = [4, 9]\n\n OUTPUT = [\n [1.0, 2.0],\n [3.0, 4.0]\n ]\n\n","support_level":"default"}},{"name":"SortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Sign","schema":{"description":"\nComputes sign for each element of the input: -1, 0 or 1.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n\"Sign\",\n[\"X\"],\n[\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3, 3).astype(np.float32) - np.random.rand(3, 3).astype(np.float32)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[ 0.02816287 0.22408086 -0.30342305]\n[-0.18481976 0.03948995 0.39698976]\n[-0.63304734 -0.6919183 -0.31524038]]\nY:\n[[ 1. 1. -1.]\n[-1. 1. 1.]\n[-1. -1. -1.]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"Xor","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **xor** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Xor\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[ True True True]\n [False False True]\n [False True False]]\nB:\n[[False False False]\n [ True True True]\n [False False False]]\nC:\n[[ True True True]\n [ True True False]\n [False True False]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"SigmoidGradient","schema":{"description":"\nSigmoidGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the sigmoid function.\n","support_level":"default"}},{"name":"MergeMultiScalarFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with scalar features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values_grad","name":"out_values_grad"}],"outputs":[{"description":".values_grad","name":"in1_values_grad"}],"support_level":"default"}},{"name":"Sin","schema":{"description":"\nCalculates the sine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sin_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sin\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.8466114 0.1803606 0.5601509 0.04959291 0.64770824]\nY: [0.74903965 0.17938434 0.5313141 0.04957259 0.60336035]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the sine of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"Log","schema":{"description":"\nCalculates the natural log of the given input tensor ($ln(x)$), element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/log_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Log\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[0.07341351 0.15404125 0.386613 ]\n [0.34090295 0.99727786 0.24141751]\n [0.32016268 0.8724168 0.93515724]]\nX after running op:\n[[-2.6116474 -1.8705349 -0.9503311 ]\n [-1.0761575 -0.00272586 -1.4212275 ]\n [-1.138926 -0.13648799 -0.06704059]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor computed as the natural log of the input tensor computed, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"DenseVectorToIdList","schema":{"description":"\nDenseVectorToIdList: Convert a blob with dense feature into a ID_LIST.\n\nAn ID_LIST is a list of IDs (may be ints, often longs) that represents a single\nfeature. As described in https://caffe2.ai/docs/sparse-operations.html, a batch\nof ID_LIST examples is represented as a pair of lengths and values where the\n`lengths` (int32) segment the `values` or ids (int32/int64) into examples.\n\nInput is a single blob where the first dimension is the batch size and the\nsecond dimension is the length of dense vectors. This operator produces a\nID_LIST where out_values are the indices of non-zero entries\nand out_lengths are the number of non-zeros entries in each row.\n\n","inputs":[{"description":"A data blob of dense vectors","name":"values"}],"outputs":[{"description":"Lengths of the sparse feature","name":"out_lengths"},{"description":"Values of the sparse feature","name":"out_values"}],"support_level":"default"}},{"name":"Reshape","schema":{"attributes":[{"description":"New shape. Do not set if using `new_shape` input.","name":"shape","option":"optional"}],"category":"Shape","description":"\nReshape the input tensor similar to numpy's\n[reshape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html).\n\nTakes a tensor as input and an optional tensor specifying the new shape. When\nthe second input is absent, an extra argument shape must be specified. Outputs\nthe reshaped tensor as well as the original shape.\n\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is going to be copied\nfrom the input tensor.\n\nFor empty tensor, we will set the -1 dimension to be 0 (if one dimension is -1).\nWhen the tensor is empty, dimension of 0 will remain to be 0.\nE.g: data=np.empty(shape=[4, 0]), shape=[0, -1], the output tensor will be\nnp.emtpy(shape=[0, 0])\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reshape_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Reshape\",\n [\"data\"],\n [\"reshaped\", \"old_shape\"],\n shape=(3,2)\n)\n\nworkspace.FeedBlob(\"data\", (np.random.randint(100, size=(6))))\nprint(\"data:\", workspace.FetchBlob(\"data\"))\nworkspace.RunOperatorOnce(op)\nprint(\"reshaped:\", workspace.FetchBlob(\"reshaped\"))\nprint(\"old_shape:\", workspace.FetchBlob(\"old_shape\"))\n```\n\n**Result**\n\n```\ndata: [86 60 85 96 7 37]\nreshaped: [[86 60]\n [85 96]\n [ 7 37]]\nold_shape: [6]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"data"},{"description":"*(type: Tensor``)* [OPTIONAL] Tensor containing new shape.","name":"new_shape"}],"outputs":[{"description":"*(type: Tensor)* Reshaped output tensor.","name":"reshaped"},{"description":"*(type: Tensor``)* Tensor containing old shape of `data`.","name":"old_shape"}],"support_level":"default"}},{"name":"AveragePoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnqueueBlobs","schema":{"description":null,"support_level":"default"}},{"name":"DepthConcat","schema":{"description":"Backward compatible operator name for Concat.","support_level":"default"}},{"name":"GatherPadding","schema":{"attributes":[{"description":"Outer-size of padding present around each range.","name":"padding_width","option":"optional"},{"description":"(Optional) Specifies a different end-padding width.","name":"end_padding_width","option":"optional"}],"description":"\nGather the sum of start and end paddings in a padded input sequence. Used in\norder to compute the gradients of AddPadding w.r.t the padding tensors.\n","inputs":[{"description":"T Padded input data","name":"data_in"},{"description":"(i64) Num of elements in each range. sum(lengths) = N. If not provided, considers all data as a single segment.","name":"lengths"}],"outputs":[{"description":"Sum of all start paddings, or of all paddings if end_padding_sum is not provided.","name":"padding_sum"},{"description":"T Sum of all end paddings, if provided.","name":"end_padding_sum"}],"support_level":"default"}},{"name":"DepthSplit","schema":{"description":"Backward compatible operator name for Split.","support_level":"default"}},{"name":"UnsortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the min of the input tensor's element along the provided axes.\n The resulted tensor has the same rank as the input if keepdims equal True.\n If keepdims equal false, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced output tensor.","name":"reduced"}],"support_level":"default"}},{"name":"StatRegistryExport","schema":{"attributes":[{"description":"(default true) Whether to atomically reset the counters afterwards.","name":"reset","option":"optional"}],"description":null,"inputs":[{"description":"If provided, export values from given StatRegistry.Otherwise, export values from the global singleton StatRegistry.","name":"handle"}],"outputs":[{"description":"1D string tensor with exported key names","name":"keys"},{"description":"1D int64 tensor with exported values","name":"values"},{"description":"The unix timestamp at counter retrieval.","name":"timestamps"}],"support_level":"default"}},{"name":"Free","schema":{"description":"\nFrees the content of the blobs. The input and output blobs should be\none-to-one inplace.","support_level":"default"}},{"name":"FlexibleTopK","schema":{"description":"\nGiven two tensors: X and K,\nretrieve the top K[..., 1] elements from X on the last dimension.\nX is an input tensor of shape [a_1, a_2, ..., a_n, r].\nK is an input tensor of shape [a_1, a_2, ..., a_n, 1],\nwhere for each element, r >= K[..., 1] > 0\nOutput two outputs:\n-Flatten values tensor of shape [ \\sum_i K[i, 1] ] which contains the values of\n the top K[..., 1] elements along the last dimension\n-Flatten indices tensor of shape [ \\sum_i K[i, 1] ] which contains the indices\n of the top K[..., 1] elements, flatten indices from the input tensor).\nThese two outputs should be used with the input K, so that we know which indices\nin X are picked.\n\nGiven two equivalent values, this operator uses the indices along the last dim-\nension as a tiebreaker. That is, the element with the lower index will appear\nfirst.\n ","inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X"},{"description":"Tensor of shape [a_1, a_2, ..., a_n, 1]","name":"K"}],"outputs":[{"description":"Tensor of shape [ \\sum_i K[i, 1] ] containing top K[..., 1] values from the input tensor","name":"Flatten values"},{"description":"Tensor of shape [ \\sum_i K[i, 1] ] containing the indices into the flatten input","name":"Flatten indices"}],"support_level":"default"}},{"name":"ReduceL1","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **L1 norm** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceL1\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[ 2. 7. 6. 4. 5.]\n [ 2. 1. 9. 8. 7.]\n [ 4. 9. 1. 0. 0.]\n [ 6. 4. 0. 8. 1.]\n [ 1. 7. 1. 0. 2.]]\n\n [[ 5. 8. 1. 7. 7.]\n [ 4. 5. 6. 5. 4.]\n [ 1. 9. 6. 6. 3.]\n [ 6. 6. 8. 8. 4.]\n [ 2. 3. 5. 8. 1.]]]]\n\nY:\n[[ 7. 15. 7. 11. 12.]\n [ 6. 6. 15. 13. 11.]\n [ 5. 18. 7. 6. 3.]\n [ 12. 10. 8. 16. 5.]\n [ 3. 10. 6. 8. 3.]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"NumpyTile","schema":{"description":null,"inputs":[{"description":"The input tensor.","name":"data"},{"description":"1-D Tensor specifying how many times to repeat each axis.","name":"repeats"}],"outputs":[{"description":"Tensor that will contain input replicated along the given axis.","name":"tiled_data"}],"support_level":"default"}},{"name":"EluGradient","schema":{"description":"\nEluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"ArgMax","schema":{"attributes":[{"default":-1,"description":"The axis to get argmax.","name":"axis","option":"optional","type":"int64"},{"default":true,"description":"If True (default), the output tensor shape will match the input tensor shape except the `axis` dimension equals 1. Else, the `axis` dimension of the output tensor is removed.","name":"keepdims","option":"optional","type":"boolean"}],"description":"\nRetrieve the argmax of an axis dimension specified by the `axis`\nargument. Given an input tensor and two arguments (`axis` and\n`keepdims`), returns a tensor containing the indices of the largest\nelement along the given axis. If the `keepdims` arg is *True* (default),\nthe shape of the output tensor matches the input tensor except the\n`axis` dimension equals 1. Else, the `axis` dimension of the output\ntensor is removed.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/arg_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ArgMax\",\n [\"X\"],\n [\"Indices\"],\n axis=2,\n keepdims=False\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\n\n```\n\n**Result**\n\n```\nX: [[[4. 9. 6.]\n [6. 6. 1.]\n [9. 5. 4.]]\n\n [[6. 7. 4.]\n [7. 9. 1.]\n [3. 2. 8.]]\n\n [[3. 4. 6.]\n [5. 2. 7.]\n [1. 5. 7.]]]\nIndices: [[1 0 0]\n [1 1 2]\n [2 2 2]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Tensor of indices for the largest values.","name":"Indices"}],"support_level":"default"}},{"name":"IndexGet","schema":{"description":"\nGiven an index handle and a tensor of keys, return an Int tensor of same shape\ncontaining the indices for each of the keys. If the index is frozen, unknown\nentries are given index 0. Otherwise, new entries are added into the index.\nIf an insert is necessary but max_elements has been reached, fail.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"},{"description":"Tensor of keys to be looked up.","name":"keys"}],"outputs":[{"description":"Indices for each of the keys.","name":"indices"}],"support_level":"default"}},{"name":"HeatmapMaxKeypoint","schema":{"description":null,"support_level":"default"}},{"name":"MomentsGradient","schema":{"description":null,"support_level":"default"}},{"name":"L1Distance","schema":{"description":"\nComputes the row-wise L1 Distance between the two input tensors $X$ and $Y$, which is defined as\n\n$$L1Distance(\\mathbf{x},\\mathbf{y}) = \\sum_{i}\\mid x_i - y_i\\mid$$\n\nNote, both inputs must either be 1-dimensional or 2-dimensional and both must have the same shape. The output $Z$ will be 1-dimensional regardless and its length will equal the number of rows in the inputs.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"L1Distance\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\n// Create X\nX = 5*np.ones((1, 4))\nprint(\"X:\\n\",X)\n\n// Create Y\nY = np.ones((1, 4))\nprint(\"Y:\\n\",Y)\n\n// Feed X & Y into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"Y\", Y.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[5. 5. 5. 5.]]\nY:\n [[1. 1. 1. 1.]]\nZ:\n [16.]\n\n```\n\n
    \n\n","inputs":[{"description":"First input tensor. (1D or 2D)","name":"X"},{"description":"Second input tensor. (must have the same shape as $X$)","name":"Y"}],"outputs":[{"description":"1D output tensor. One value for each row of the inputs.","name":"Z"}],"support_level":"default"}},{"name":"Allreduce","schema":{"description":"\nDoes an allreduce operation among the nodes. Currently only Sum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allreduced.","name":"X"}],"outputs":[{"description":"The allreduced tensor, same on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"Onnxifi","schema":{"attributes":[{"description":"(string default=\"\") Serialized ONNX model to be converted to backend representation","name":"onnx_model","option":"optional"},{"description":"Initialization pair indicating the mapping of the name between NetDef and ONNX model","name":"initializers","option":"optional"},{"description":"A list of key/value pairs indicating which input index to look up for real batch size for the given max output batch size","name":"output_resize_hints","option":"optional"}],"description":"\n The Onnxifi operator is a black-box operator to lower the computation to Onnxifi backend\n ","support_level":"default"}},{"name":"Partition","schema":{"attributes":[{"description":"(int, default 0) If set, the operator transforms the first tensor values as floor(X_ij / num_partitions)","name":"pack_first_input","option":"optional"}],"description":"\nSplits the input int tensor into multiple ones according to the first tensor.\n\nTakes the first input and partitions it to shards according to the remainder of\nvalues modulo the number of partitions. It requires that the first tensor is of\nintegral type. The number of partitions is derived as (num_output / num_input).\n\nIf additional inputs are present they must have the same shape as the first\ninput, optionally with extra trailing dimensions. They will be partitioned\naccordingly to the first input.\n\nOptional arg 'pack_first_input' transforms the first tensor values as\nX_ij / num_partitions.\n\nOutputs are ordered as\nX_0_part_0, X_1_part_0, ..., X_N-1_part_0, X_0_part_1, ..., X_N-1_part_K-1\n","inputs":[{"description":"Input tensor containing data to be partitioned. The number of input tensors might be greater than 1 but must have the same shape as the previous tensors.","name":"input"}],"outputs":[{"description":"Output Partitions. The number of output tensors has to be a multiple of the number of input tensors.","name":"partitions"}],"support_level":"default"}},{"name":"LengthsTopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"FlexibleTopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"ThrowException","schema":{"description":null,"support_level":"default"}},{"name":"LengthsMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Tile","schema":{"attributes":[{"description":"(*int*): number of replicas","name":"tiles","option":"optional"},{"description":"(*int*): axis to replicate along","name":"axis","option":"optional"}],"description":"\nConstructs a tensor by tiling a given tensor along a specified axis. This operation creates a new tensor by replicating the input tensor a number of times specified by the `tiles` argument along the `axis` dimension. The output tensor's `axis` dimension has $(X.dims(axis) * tiles)$ elements.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/tile_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Tile\",\n [\"X\", \"tiles\", \"axis\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(5,5)))\nworkspace.FeedBlob(\"tiles\", np.array([5]).astype(np.int32))\nworkspace.FeedBlob(\"axis\", np.array([1]).astype(np.int32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[9 1 7 1 3]\n [2 3 6 2 5]\n [0 9 2 6 4]\n [5 8 1 5 9]\n [2 0 1 3 7]]\nY:\n[[9 1 7 1 3 9 1 7 1 3 9 1 7 1 3 9 1 7 1 3 9 1 7 1 3]\n [2 3 6 2 5 2 3 6 2 5 2 3 6 2 5 2 3 6 2 5 2 3 6 2 5]\n [0 9 2 6 4 0 9 2 6 4 0 9 2 6 4 0 9 2 6 4 0 9 2 6 4]\n [5 8 1 5 9 5 8 1 5 9 5 8 1 5 9 5 8 1 5 9 5 8 1 5 9]\n [2 0 1 3 7 2 0 1 3 7 2 0 1 3 7 2 0 1 3 7 2 0 1 3 7]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): input tensor","name":"X"},{"description":"(*Tensor``*): [OPTIONAL] number of replicas (overrides `tiles` argument)","name":"tiles"},{"description":"(*Tensor``*): [OPTIONAL] axis to replicate along (overrides `axis` argument)","name":"axis"}],"outputs":[{"description":"(*Tensor*): output tensor","name":"Y"}],"support_level":"default"}},{"name":"Asin","schema":{"description":"\nCalculates the arcsine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"SplitByLengths","schema":{"attributes":[{"description":"Which axis to split on","name":"axis","option":"optional"},{"description":"Either NHWC or NCWH, will split on C axis, defaults to NCHW","name":"order","option":"optional"}],"description":"\nSplit a tensor into a list of tensors, given a lengths input, along the specified\n'axis'. If `K` outputs are provided, the op assumes `len(lengths) % K == 0`.\nThe `input` will be split into `K` parts. Each part of length\n`sum(lengths[i*k:i*k+k))`","inputs":[{"description":"The tensor to split","name":"input"},{"description":"The tensor `l_i` indicates the logic block of input.","name":"legnths"}],"support_level":"default"}},{"name":"CreateBlobsQueueDB","schema":{"attributes":[{"description":"(default: -1 (no key)) index of blob for DB key in the BlobsQueue.","name":"key_blob_index","option":"optional"},{"description":"(default: 0) index of blob for DB value in the BlobsQueue.","name":"value_blob_index","option":"optional"},{"description":"(default: 0.0 (no timeout)) Timeout in seconds for reading from the BlobsQueue.","name":"timeout_secs","option":"optional"}],"description":"Create a DBReader from a BlobsQueue","inputs":[{"description":"The shared pointer to a queue containing Blobs.","name":"queue"}],"outputs":[{"description":"The DBReader for the given BlobsQueue","name":"reader"}],"support_level":"default"}},{"name":"GRUUnitGradient","schema":{"attributes":[{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":null,"support_level":"default"}},{"name":"CloseBlobsQueue","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8Sigmoid","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nApply the Sigmoid function element-wise to the input tensor. This is often used\nas a non-linear activation function in a neural network. The sigmoid function is\ndefined as:\n\n$$Sigmoid(x) = \\frac{1}{1+\\exp(-x)}$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sigmoid_op.cc\n","inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input"}],"outputs":[{"description":"The sigmoid normalized output values with the same shape as input tensor.","name":"output"}],"support_level":"default"}},{"name":"GRUUnit","schema":{"attributes":[{"description":"Bool to determine if hidden state is zeroes or passed along for timesteps past the given sequence_length.","name":"drop_states","option":"optional"},{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":"\nGRUUnit computes the activations of a standard GRU,\nin a sequence-length aware fashion.\n\nConcretely, given the (fused) inputs X (TxNxD), the previous hidden\nstate (NxD), and the sequence lengths (N), computes the GRU\nactivations, avoiding computation if the input is invalid (as in, the\nvalue at X[t][n] >= seqLengths[n].\n\n","outputs":[{"description":"The new GRU hidden state calculated by this op.","name":"hidden"}],"support_level":"default"}},{"name":"SortedSegmentSum","schema":{"description":"\nApplies 'Sum' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentSum that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sqrt","schema":{"description":"\nPerforms element-wise square-root ($\\sqrt{x}$) of input tensor $X$.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sqrt_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sqrt\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[8. 3. 3.]\n [4. 0. 0.]\n [1. 2. 5.]]\nY:\n[[2.8284268 1.7320508 1.7320508 ]\n [1.9999999 0. 0. ]\n [0.99999994 1.4142134 2.236068 ]]\n\n```\n\n
    \n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"TTLinearGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseFtrl","schema":{"description":null,"support_level":"default"}},{"name":"LambdaRankNdcgGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseNormalize","schema":{"attributes":[{"description":"A bool variable to control whether to use max norm or constant norm. When use_max_norm = false, constant norm is used so that all the embedding vectors are scaled to have a L2 norm equals to A (see blow argument norm=A). If use_max_norm = true, max norm is used so that embedding is scaled so that its l2 norm is no larger than A. If an embedding's norm is less than A originally, the embedding is left unchanged. The default is True.","name":"use_max_norm","option":"optional"},{"description":"L2 norm of the embedding. The default is 1.0.","name":"norm","option":"optional"}],"description":"\nGiven a sparse matrix, apply max_norm or constant_norm sparse regularization.\n","inputs":[{"description":"Parameters to be normalized","name":"param"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed (optional - not used, this argument is for backwards compatibility)","name":"grad"}],"outputs":[{"description":"Normalized parameters","name":"output_param"}],"support_level":"default"}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.01,"description":"Coefficient of leakage.","name":"alpha","option":"optional","type":"float32"}],"description":"\nThe *LeakyRelu* op takes one input tensor $X$ and an argument $alpha$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise leaky relu operation, defined as\n\n$$y=LeakyRelu(x) =\\begin{cases}\\alpha x & x < 0\\\\x & otherwise\\end{cases}$$\n\nThe default value of *alpha* is 0.01.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/leaky_relu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/leaky_relu_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LeakyRelu\",\n [\"X\"],\n [\"Y\"],\n alpha=0.01\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.91060215 0.09374836 2.1429708 ]\n [-0.748983 0.19164062 -1.5130422 ]\n [-0.29539835 -0.8530696 0.7673204 ]]\n\nY:\n [[-0.00910602 0.09374836 2.1429708 ]\n [-0.00748983 0.19164062 -0.01513042]\n [-0.00295398 -0.0085307 0.7673204 ]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"Output tensor, calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"AddGradient","schema":{"description":null,"support_level":"default"}},{"name":"LeakyReluGradient","schema":{"attributes":[{"description":"Coefficient of leakage","name":"alpha","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ReadRandomBatch","schema":{"attributes":[{"description":"Number of top-level entries to read.","name":"batch_size","option":"optional"},{"description":"(bool) Repeat the dataset indefinitely","name":"loop_over","option":"optional"}],"description":"\nRead the next batch of examples out of the given cursor,\nidx blob, offset matrix and data blobs.\n\nInput(0) is a blob pointing to a TreeCursor,\nInput(1) is a blob pointing to the shuffled idx\nInput(2) is a blob pointing to the offset matrix and\n[Input(3),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nReadRandomBatch is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"idx with a shuffled order.","name":"idx"},{"description":"offset matrix containing length offset info.","name":"offsetsmat"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing the next batch for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"HalfToFloat","schema":{"description":null,"support_level":"default"}},{"name":"ReduceScatter","schema":{"description":"\nDoes reduce-scatter operation among the nodes. Currently only Sum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be reduce-scattered.","name":"X"}],"outputs":[{"description":"The reduced tensor, scattered on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"SeluGradient","schema":{"attributes":[{"description":"(float) default to 1.6732~; affects the activation function itself.This should go with the weight initialization in the paper. See https://arxiv.org/abs/1706.02515","name":"alpha","option":"optional"},{"description":"(float) default to 1.0507~; affects the activation function itself.","name":"scale","option":"optional"}],"description":"\nSeluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the selu function.\n","inputs":[{"description":"input tensor","name":"Y"},{"description":"input tensor","name":"dY"}],"support_level":"default"}},{"name":"LengthsToShape","schema":{"description":"\nThis operator takes a list of $N$ equal integers as input which represent the lengths of $N$ vectors. The output is the calculated shape of the matrix if the $N$ integers were combined into a single matrix.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsToShape\",\n [\"X\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([2,2,2,2,2,2,2,2,2,2])\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.int32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [2 2 2 2 2 2 2 2 2 2]\nY:\n [10 2]\n\n```\n\n
    \n\n ","inputs":[{"description":"List, of length $N$, of equal integers representing the lengths of several vectors.","name":"X"}],"outputs":[{"description":"Vector of length 2 describing the dimensions of the data if the $N$ vectors from the input were combined to a single matrix.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResetCounter","schema":{"attributes":[{"default":0,"description":"Resets counter to this value, must be >= 0.","name":"init_count","option":"optional","type":"int64"}],"description":"\nResets a count-down counter with initial value specified by the `init_count`\nargument.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* [OPTIONAL] count value BEFORE this operation.","name":"previous_value"}],"support_level":"default"}},{"name":"NormalizeGradient","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SparseMomentumSGDUpdate","schema":{"attributes":[{"description":"Momentum hyperparameter.","name":"momentum","option":"optional"},{"description":"(boolean) Whether to use Nesterov Accelerated Gradient.","name":"nesterov","option":"optional"}],"description":"\n\nPerforms a momentum SGD update analogous to MomentumSGDUpdate, but using a\nGradientSlice and indices into the full param and momentum tables. Both param\nand momentum should be in-place (corresponding inputs and outputs should be the\nsame blobs).\n\n\n\n","inputs":[{"description":"GradientSlice with gradients for updated indices.","name":"grad"},{"description":"Momentum blob, same shape as param.","name":"moment"},{"description":"Learning rate.","name":"lr"},{"description":"Full parameter blob.","name":"param"},{"description":"Indices (in first dimension of param) where updates are performed.","name":"indices"}],"outputs":[{"description":"Adjusted gradient.","name":"output_grad"},{"description":"Updated momentum.","name":"output_moment"},{"description":"Updated parameter","name":"output_param"}],"support_level":"default"}},{"name":"AffineChannelGradient","schema":{"description":null,"support_level":"default"}},{"name":"ColwiseMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosGradient","schema":{"description":null,"support_level":"default"}},{"name":"Scatter","schema":{"attributes":[{"default":1,"description":"Which dimension to scatter on.","name":"axis","option":"optional","type":"int64"}],"description":"\nUpdate values of the tensor by overriding current value specified by indices.\n\nWrites all values from the tensor UPDATES into DATA at the indices specified in the INDICES tensor.\nFor each value in DATA, its output index is specified by its index in UPDATES and by the corresponding value in INDICES for the specified axis.\n\nFor a 3-D tensor, DATA is updated as:\n\nDATA[INDICES[i][j][k]][j][k] = UPDATES[i][j][k] # if axis == 0\nDATA[i][INDICES[i][j][k]][k] = UPDATES[i][j][k] # if axis == 1\nDATA[i][j][INDICES[i][j][k]] = UPDATES[i][j][k] # if axis == 2\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"DATA"},{"description":"1-D list of indices on the first dimensionof X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"UPDATES"}],"outputs":[{"description":"The updated output.","name":"OUTPUT"}],"support_level":"default"}},{"name":"MapToKeyValue","schema":{"description":"Convert a map blob into key and value blob pairs","inputs":[{"description":"Blob reference to the map","name":"map blob"}],"outputs":[{"description":"Blob reference to the key","name":"key blob"},{"description":"Blob reference to the value","name":"value blob"}],"support_level":"default"}},{"name":"StringStartsWith","schema":{"attributes":[{"description":"The prefix to check input strings against.","name":"prefix","option":"optional"}],"description":"\nPerforms the starts-with check on each string in the input tensor.\nReturns tensor of boolean of the same dimension of input.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of bools of same shape as input.","name":"bools"}],"support_level":"default"}},{"name":"IndexStore","schema":{"description":"\nStores the keys of this index in a 1-D tensor. Since element 0 is reserved\nfor unknowns, the first element of the output tensor will be element of index 1.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"1-D tensor with elements starting with index 1.","name":"items"}],"support_level":"default"}},{"name":"Im2Col","schema":{"description":"The Im2Col operator from Matlab.","inputs":[{"description":"4-tensor in NCHW or NHWC.","name":"X"}],"outputs":[{"description":"4-tensor. For NCHW: N x (C x kH x kW) x outH x outW.For NHWC: N x outH x outW x (kH x kW x C","name":"Y"}],"support_level":"default"}},{"name":"FCTransposedGradient","schema":{"description":null,"support_level":"default"}},{"name":"AddPadding","schema":{"attributes":[{"description":"Number of copies of padding to add around each range.","name":"padding_width","option":"optional","type":"int64"},{"description":"[OPTIONAL] Specifies a different end-padding width. If this is not set, will use same as `padding_width`.","name":"end_padding_width","option":"optional","type":"int64"}],"description":"\nGiven a partitioned tensor $T$, where the partitions are\ndefined as ranges on its outer-most (slowest varying) dimension $N$,\nreturn a tensor $T<(N + 2 * padding\\_width), D_1, ..., D_n>$ with paddings\nadded to the start and end of each range.\n\nOptionally, different paddings can be provided for beginning and end.\nPaddings provided must be a tensor $T$. If no padding is\nprovided, add zero padding. If no lengths vector is provided, add padding\nonly once, at the start and end of data.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sequence_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AddPadding\",\n [\"X\", \"lengths\"],\n [\"Y\", \"lengths_out\"],\n padding_width=1\n\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,2,2).astype(np.float32)))\nworkspace.FeedBlob(\"lengths\", np.array([3]).astype(np.int32))\n\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"lengths_out:\", workspace.FetchBlob(\"lengths_out\"))\n```\n\n**Result**\n\n```\nX: [[[0.2531572 0.4588472 ]\n [0.45140603 0.61161053]]\n\n [[0.92500854 0.8045306 ]\n [0.03356671 0.30233648]]\n\n [[0.4660227 0.6287745 ]\n [0.79372746 0.08609265]]]\nY: [[[0. 0. ]\n [0. 0. ]]\n\n [[0.2531572 0.4588472 ]\n [0.45140603 0.61161053]]\n\n [[0.92500854 0.8045306 ]\n [0.03356671 0.30233648]]\n\n [[0.4660227 0.6287745 ]\n [0.79372746 0.08609265]]\n\n [[0. 0. ]\n [0. 0. ]]]\nlengths_out: [5]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input data ($T$).","name":"data_in"},{"description":"*(type: Tensor``)* Number of elements in each range. sum(lengths) = N.","name":"lengths"},{"description":"*(type: Tensor``)* [OPTIONAL] Padding data for range start ($T$).","name":"start_padding"},{"description":"*(type: Tensor``)* [OPTIONAL] Padding for range end. If not provided, `start_padding` is used ($T$).","name":"end_padding"}],"outputs":[{"description":"*(type: Tensor)* Padded data tensor ($T$).","name":"data_out"},{"description":"*(type: Tensor``)* [OPTIONAL] Lengths for each padded range.","name":"lengths_out"}],"support_level":"default"}},{"name":"Int8Reshape","schema":{"attributes":[{"description":"New shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nReshape the input tensor similar to numpy.reshape.\n\nIt takes a tensor as input and an optional tensor specifying the new shape.\nWhen the second input is absent, an extra argument `shape` must be specified.\nIt outputs the reshaped tensor as well as the original shape.\n\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is going to be copied\nfrom the input tensor.\n","inputs":[{"description":"An input tensor.","name":"data"},{"description":"New shape.","name":"new_shape"}],"outputs":[{"description":"Reshaped data.","name":"reshaped"},{"description":"Original shape.","name":"old_shape"}],"support_level":"default"}},{"name":"Where","schema":{"description":"\nOperator Where takes three input data (Tensor, Tensor, Tensor) and\nproduces one output data (Tensor) where z = c ? x : y is applied elementwise.\n","inputs":[{"description":"input tensor containing booleans","name":"C"},{"description":"input tensor","name":"X"},{"description":"input tensor","name":"Y"}],"outputs":[{"description":"output tensor","name":"Z"}],"support_level":"default"}},{"name":"GetAllBlobNames","schema":{"attributes":[{"description":"(bool, default true) Whether to include blobs inherited from parent workspaces.","name":"include_shared","option":"optional"}],"description":"\nReturn a 1D tensor of strings containing the names\nof each blob in the active workspace.\n","outputs":[{"description":"1D tensor of strings containing blob names.","name":"blob_names"}],"support_level":"default"}},{"name":"FloatToFusedRandRowwiseQuantized","schema":{"attributes":[{"description":"How many bits to quantize per data (defaults to 8).","name":"bitwidth","option":"optional"},{"description":"random or not (True). False is set up for unittest.","name":"random","option":"optional"}],"description":"\nApplies row-wise stochastic/random quantization by determining the range of\neach row in the input matrix, and then quantize each element to one of two\nclosest discrete levels by randomly drawing Bernoulli distribution.\nThe method is extended from TernGrad [1],\nwhich randomly quantizes gradients to three levels to reduce communication in distributed training.\nThe format of each row (x) in the output matrix is [bitwidth][tail][min][max][data]:\nbitwidth[1 Byte]: bitwidth per data [1, 2, 4 or 8];\ntail[1 Byte]: the number of unused buckets [1-8] (One byte is split to 8/bitwidth buckets and each bucket stores one low-precision data in bitwidth bits);\nmin[4 Bytes]: the minimum floating value min(x);\nmax[4 Bytes]: the maximum floating value max(x);\ndata: quantized data.\nThe quantization is uniform with levels q = min + (max-min)/(2^bitwidth - 1)*[0:1:2^bitwidth].\nDuring stochastic/random quantization x'=Quantize(x), for q_j < x_i <= q_{j+1}, we draw quantization x'_i from Bernoulli distributions with\nP(x'_i = q_{j+1}) = (x_i - q_j)/(q_{j+1} - q_j), and\nP(x'_i = q_j) = (q_{j+1} - x_i)/(q_{j+1} - q_j) where x'_i is the quantized value of x_i.\n[1] proved E{x'_i}=x_i, which is an unbiased approximation. More details are in the paper.\nFor example, suppose targeted bitwidth = 2 and x = [0.3, -1.4, -0.6, 0.9, 1.0],\nthen tail = 3, min = -1.4, max = 1.0 and q = [-1.4, -0.6, 0.2, 1.0].\nx_1 = 0.3 will be quantized to x'_1 = 0.2 with probability 7/8 and to x'_1 = 1.0 with probability 1/8.\nThe storage format of quantized data is: [x'_1|x'_3|x'_5|xxx]-[x'_2|x'_4|xxx|xxx].\nIn general, a input row is split to multiple segments. One segment is a continuous subarray of the row,\nand its length is the number of bytes storing quantized data in the output matrix.\nThe b-th bucket of the i-th byte stores the i-th data of the b-th segment of input row.\n\n[1] Wen, Wei, Cong Xu, Feng Yan, Chunpeng Wu, Yandan Wang, Yiran Chen, and Hai Li.\n\"Terngrad: Ternary gradients to reduce communication in distributed deep learning.\"\nIn Advances in Neural Information Processing Systems, pp. 1508-1518. 2017.\n\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused bitwidth, tail, min, max and quantized data","name":"output"}],"support_level":"default"}},{"name":"PackRNNSequence","schema":{"description":"\nPack values based on the length blob. Each number from length blob represents\nthe corresponding values that need to be packed. The dimension for each pack\nis the same as the maximum number from the length blob (padding with zero is\nimplemented for smaller length value). The overall output dimension is:\nT * N * D, where T is the max number of lengths, N is the size of lengths,\nand D is the dimension of each feature value. The following example shows\nthe input and output of this operator:\n\n\nGiven:\n values = [v1, v2, v3, v4, v5, v6, v7, v8]\n lengths = [2, 3, 1, 2];\n\n\nOutput:\n output = [\n [v1, v3, v6, v7],\n [v2, v4, 0, v8],\n [0, v5, 0, 0 ],\n ]\n\n\nOne application for this operator is the transfer data into the format that is\nused for RNN models. Note that the gradient operator of PackRNNSequence is\nUnpackRNNSequence.\n","inputs":[{"description":"Data tensor, contains a sequence of features","name":"values"},{"description":"lengths with each number representing the pack size.","name":"lengths"}],"outputs":[{"description":"Output tensor after packing","name":"output"}],"support_level":"default"}},{"name":"PadEmptySamples","schema":{"description":"\nPad empty field given lengths and index features,\n\nInput(0) is a blob pointing to the lengths of samples in one batch,\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the features.\n\nPadEmptySamples is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the lengths.","name":"lengths"}],"outputs":[{"description":"Tensor containing lengths with empty sample padded.","name":"out_lengths"}],"support_level":"default"}},{"name":"PadImage","schema":{"description":"\nPadImage pads values around the boundary of an image according to the pad\nvalues and stride sizes defined by the ConvPoolOpBase operator.\n ","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case. ","name":"X"}],"outputs":[{"description":"Output data tensor from padding the H and W dimensions on the tensor. Dimensions will vary based on various pad and stride sizes.","name":"Y"}],"support_level":"default"}},{"name":"Glu","schema":{"description":"\nApplies gated linear unit to the input Tensor X. The output Y is half the size\nof the input X, so if the shape of X is [d1, d2, ..., N] shape of Y will be\n[d1, d2, ..., dn/2] and Y(:dn-1, i) = GLU(X(:dn-1, i), X(:dn-1, i+N/2)) =\nX(dn-1, i) * sigmoid(X(dn-1, i+N/2))\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"Shape","schema":{"attributes":[{"description":"Array of interested axes.If given, this operator only returns the dimensions of the given axes.Otherwise, the operator returns the dimensions of all axes.","name":"axes","option":"optional","type":"int64[]"}],"description":"\nProduce a 1D int64 tensor with the shape of the input tensor.\nIf called with an optional argument `axes`, the result will only\ncontain the dimensions of specified axes.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/shape_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Shape\",\n [\"X\"],\n [\"shape\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(2,3))))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"shape:\", workspace.FetchBlob(\"shape\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[3 2 5]\n [5 7 3]]\nshape: [2 3]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Output tensor containing shape of input tensor.","name":"shape"}],"support_level":"default"}},{"name":"ReservoirSampling","schema":{"attributes":[{"description":"The number of random samples to append for each positive samples","name":"num_to_collect","option":"optional"}],"description":"\nCollect `DATA` tensor into `RESERVOIR` of size `num_to_collect`. `DATA` is\nassumed to be a batch.\n\nIn case where 'objects' may be repeated in data and you only want at most one\ninstance of each 'object' in the reservoir, `OBJECT_ID` can be given for\ndeduplication. If `OBJECT_ID` is given, then you also need to supply additional\nbook-keeping tensors. See input blob documentation for details.\n\nThis operator is thread-safe.\n","inputs":[{"description":"The reservoir; should be initialized to empty tensor","name":"RESERVOIR"},{"description":"Number of examples seen so far; should be initialized to 0","name":"NUM_VISITED"},{"description":"Tensor to collect from. The first dimension is assumed to be batch size. If the object to be collected is represented by multiple tensors, use `PackRecords` to pack them into single tensor.","name":"DATA"},{"description":"Mutex to prevent data race","name":"MUTEX"},{"description":"(Optional, int64) If provided, used for deduplicating object in the reservoir","name":"OBJECT_ID"},{"description":"(Optional) Auxiliary bookkeeping map. This should be created from `CreateMap` with keys of type int64 and values of type int32","name":"OBJECT_TO_POS_MAP_IN"},{"description":"(Optional) Tensor of type int64 used for bookkeeping in deduplication","name":"POS_TO_OBJECT_IN"}],"outputs":[{"description":"Same as the input","name":"RESERVOIR"},{"description":"Same as the input","name":"NUM_VISITED"},{"description":"(Optional) Same as the input","name":"OBJECT_TO_POS_MAP"},{"description":"(Optional) Same as the input","name":"POS_TO_OBJECT"}],"support_level":"default"}},{"name":"BatchBoxCox","schema":{"description":"\nInput `data` is a N * D matrix. Apply box-cox transform for each column.\n`lambda1` and `lambda2` is of size D that defines the hyper-parameters for\nthe transform of each column `x` of the input `data`:\n\n ln(x + lambda2), if lambda1 == 0\n ((x + lambda2)^lambda1 - 1)/lambda1, if lambda1 != 0\n\n","inputs":[{"description":"input float or double N * D matrix","name":"data"},{"description":"tensor of size D with the same type as data","name":"lambda1"},{"description":"tensor of size D with the same type as data","name":"lambda2"}],"outputs":[{"description":"output matrix that applied box-cox transform","name":"output"}],"support_level":"default"}},{"name":"Clip","schema":{"attributes":[{"description":"Minimum value, under which element is replaced by min (default=*numeric_limits::lowest()*).","name":"min","option":"optional","type":"float32"},{"description":"Maximum value, under which element is replaced by max (default=*numeric_limits::max()*).","name":"max","option":"optional","type":"float32"}],"description":"\nThis operator limits the given input within an interval. The interval is\nspecified by the `min` and `max` arguments. They default to\n*numeric_limits::lowest()* and *numeric_limits::max()* respectively. The\nclipping operation can be done in an in-place fashion by using the same output\nblob as the input blob.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/clip_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Clip\",\n [\"X\"],\n [\"Y\"],\n min=20.0,\n max=60.0\n\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(5,5))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\nX: [[45. 16. 59. 99. 48.]\n [12. 44. 46. 82. 28.]\n [ 1. 91. 18. 9. 71.]\n [24. 37. 61. 12. 81.]\n [36. 38. 30. 84. 40.]]\nY: [[45. 20. 59. 60. 48.]\n [20. 44. 46. 60. 28.]\n [20. 60. 20. 20. 60.]\n [24. 37. 60. 20. 60.]\n [36. 38. 30. 60. 40.]]\n```\n\n
    \n\n","inputs":[{"description":"*(Tensor``)* Input tensor within range [*numeric_limits::lowest()*, *numeric_limits::max()*].","name":"X"}],"outputs":[{"description":"*(Tensor``)* Output tensor clipped within range [`min`, `max`].","name":"Y"}],"support_level":"default"}},{"name":"FeedBlob","schema":{"attributes":[{"description":"(string) if provided then we will use this string as the value for theprovided output tensor","name":"value","option":"optional"}],"description":"\nFeedBlobs the content of the blobs. The input and output blobs should be\none-to-one inplace.","support_level":"default"}},{"name":"CreateBlobsQueue","schema":{"description":null,"support_level":"default"}},{"name":"BisectPercentile","schema":{"attributes":[{"description":"1D tensor, which is the concatenation of all sorted raw feature values for all features.","name":"percentile_raw","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_mapping and percentile_raw such that each element in percentile_mapping corresponds to the percentile value of the corresponding raw feature value.","name":"percentile_mapping","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile lower bound of the corresponding raw feature value.","name":"percentile_lower","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile upper bound of the corresponding raw feature value.","name":"percentile_upper","option":"optional"},{"description":"1D tensor. There is one-one mapping between percentile_upper and percentile_raw such that each element in percentile_mapping corresponds to the percentile upper bound of the corresponding raw feature value.","name":"lengths","option":"optional"}],"description":"\n This operator is to map raw feature values into the percentile\n representations based on Bisection for more than one feature.\n\n The input is the bath of input feature values, with the size of (batch_size,\n num_feature), where num_feature = F (F >= 1).\n\n For each feature, we also need additional information regarding the feature\n value distribution.\n There are several vectors to keep data to percentile mappping information\n as arguments (context):\n 1. feature raw values (R)\n 2. feature percentile mapping (P)\n 3. feature percentile lower bound (L)\n 4. feature percentile upper bound (U)\n\n A toy example:\n Suppose the sampled data distribution is as follows:\n 1, 1, 2, 2, 2, 2, 2, 2, 3, 4\n We have the mapping vectors as follows:\n R = [1, 2, 3, 4]\n P = [0.15, 0.55, 0.9, 1.0]\n L = [0.1, 0.3, 0.9, 1.0]\n U = [0.2, 0.8, 0.9, 1.0]\n Where P is computed as (L + U) / 2.\n\n For a given list of feature values, X = [x_0, x_1, ..., x_i, ...], for each\n feature value (x_i) we first apply bisection to find the right index (t),\n such that R[t] <= x_i < R[t+1].\n If x_i = R[t], P[t] is returned;\n otherwise, the interpolation is apply by (R[t], R[t+1]) and (U[t] and L[t]).\n\n As there are F features (F >= 1), we concate all the R_f, P_f, L_f, and\n U_f for each feature f and use an additional input length to keep track of\n the number of points for each set of raw feature value to percentile mapping.\n For example, there are two features:\n R_1 =[0.1, 0.4, 0.5];\n R_2 = [0.3, 1.2];\n We will build R = [0.1, 0.4, 0.5, 0.3, 1.2]; besides, we have\n lengths = [3, 2]\n to indicate the boundaries of the percentile information.\n\n","inputs":[{"description":"Input 2D tensor of floats of size (N, D), where N is the batch size and D is the feature dimension.","name":"raw_values"}],"outputs":[{"description":"2D tensor of output with the same dimensions as the input raw_values.","name":"percentile"}],"support_level":"default"}},{"name":"ReversePackedSegs","schema":{"description":"\nReverse segments in a 3-D tensor (lengths, segments, embeddings,), leaving\npaddings unchanged. This operator is used to reverse input of a recurrent neural\nnetwork to make it a BRNN.\n ","inputs":[{"description":"a 3-D (lengths, segments, embeddings,) tensor.","name":"data"},{"description":"length of each segment.","name":"lengths"}],"outputs":[{"description":"a (lengths, segments, embeddings,) tensor with each segment reversedand paddings unchanged.","name":"reversed data"}],"support_level":"default"}},{"name":"CreateScope","schema":{"description":"\n'CreateScope' operator initializes and outputs empty scope that is used\nby Do operator to store local blobs\n ","support_level":"default"}},{"name":"SpatialSoftmaxWithLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"StoreAdd","schema":{"attributes":[{"description":"key of the counter (required)","name":"blob_name","option":"optional"},{"description":"value that is added (optional, default: 1)","name":"add_value","option":"optional"}],"description":"\nAdd a value to a remote counter. If the key is not set, the store\ninitializes it to 0 and then performs the add operation. The operation\nreturns the resulting counter value.\n","inputs":[{"description":"unique_ptr","name":"handler"}],"outputs":[{"description":"the current value of the counter","name":"value"}],"support_level":"default"}},{"name":"MergeSingleListFeatureTensorsGradient","schema":{"description":"Explode multi-feature tensors with list features into single-feature tensors.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".presence","name":"in1_presence"},{"description":".values.values_grad","name":"out_values_values"}],"outputs":[{"description":".values_grad","name":"out1_values"}],"support_level":"default"}},{"name":"DistributeFpnProposals","schema":{"attributes":[{"description":"(int) ROI_CANONICAL_SCALE","name":"roi_canonical_scale","option":"optional"},{"description":"(int) ROI_CANONICAL_LEVEL","name":"roi_canonical_level","option":"optional"},{"description":"(int) ROI_MAX_LEVEL","name":"roi_max_level","option":"optional"},{"description":"(int) ROI_MIN_LEVEL","name":"roi_min_level","option":"optional"}],"description":"\n...\n","inputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"}],"outputs":[{"description":"RPN proposals for ROI level 2, format (image_index, x1, y1, x2, y2)","name":"rois_fpn2"},{"description":"RPN proposals for ROI level 3, format (image_index, x1, y1, x2, y2)","name":"rois_fpn3"},{"description":"RPN proposals for ROI level 4, format (image_index, x1, y1, x2, y2)","name":"rois_fpn4"},{"description":"RPN proposals for ROI level 5, format (image_index, x1, y1, x2, y2)","name":"rois_fpn5"},{"description":"Permutation on the concatenation of all rois_fpni, i=min...max, such that when applied the RPN RoIs are restored to their original order in the input blobs.","name":"rois_idx_restore"}],"support_level":"default"}},{"name":"CollectRpnProposals","schema":{"attributes":[{"description":"(int) RPN_MAX_LEVEL","name":"rpn_max_level","option":"optional"},{"description":"(int) RPN_MIN_LEVEL","name":"rpn_min_level","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"rpn_post_nms_topN","option":"optional"}],"description":"\n...\n","inputs":[{"description":"RPN proposals for FPN level 2, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn2"},{"description":"RPN proposals for FPN level 3, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn3"},{"description":"RPN proposals for FPN level 4, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn4"},{"description":"RPN proposals for FPN level 5, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn5"},{"description":"RPN proposals for FPN level 6, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn6"},{"description":"RPN objectness probabilities for FPN level 2. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn2"},{"description":"RPN objectness probabilities for FPN level 3. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn3"},{"description":"RPN objectness probabilities for FPN level 4. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn4"},{"description":"RPN objectness probabilities for FPN level 5. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn5"},{"description":"RPN objectness probabilities for FPN level 6. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn6"}],"outputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"}],"support_level":"default"}},{"name":"LengthsMaxWithMainInputAndForwardOutputGradient","schema":{"description":null,"support_level":"default"}},{"name":"MomentumSGDUpdate","schema":{"description":"\n\nPerforms a momentum SGD update for an input gradient and momentum\nparameters. Concretely, given inputs (grad, m, lr, param) and arguments\n(momentum, nesterov), computes:\n\n if not nesterov:\n adjusted_gradient = lr * grad + momentum * m\n param = param - adjusted_gradient\n return (adjusted_gradient, adjusted_gradient, param)\n else:\n m_new = momentum * m + lr * grad\n param = param - ((1 + momentum) * m_new - momentum * m),\n return ((1 + momentum) * m_new - momentum * m, m_new, param)\n\nOutput is (grad, momentum, parameter).\n\nNote the difference to MomentumSGD, which returns a new gradient\nbut does not perform the parameter update.\n\n","support_level":"default"}},{"name":"SparseLengthsIndicesInGradientWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Pow","schema":{"attributes":[{"description":"The exponent of the power function. Do not use if setting exponent via input.","name":"exponent","option":"optional"},{"default":-1,"description":"","name":"axis","option":"optional","type":"int64"},{"default":false,"description":"","name":"broadcast","option":"optional","type":"boolean"}],"description":"\nThe *Pow* op takes an input data tensor $X$ and an exponent parameter *exponent*, which can be a scalar or another tensor. As output, it produces a single output data tensor $Y$, where the function $f(x) = x^{exponent}$ has been applied to $X$ elementwise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Pow\",\n [\"X\", \"exponent\"],\n [\"Y\"],\n broadcast=1\n)\n\nworkspace.FeedBlob(\"X\", np.array([1,2,3,4,5,6]).astype(np.float32))\nprint(\"X: \", workspace.FetchBlob(\"X\"))\n\nworkspace.FeedBlob(\"exponent\", np.array([2]).astype(np.float32))\nprint(\"exponent: \", workspace.FetchBlob(\"exponent\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y: \", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [1. 2. 3. 4. 5. 6.]\nexponent: [2.]\nY: [ 1. 4. 9. 16. 25. 36.]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob to be operated on.","name":"X"},{"description":"Exponent blob containing the exponent(s) for calculation. Do not use if setting exponent via argument.","name":"exponent"}],"outputs":[{"description":"Output data blob with the same shape as the input.","name":"Y"}],"support_level":"default"}},{"name":"Cube","schema":{"description":null,"inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cube of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool2D","schema":{"description":"AveragePool2D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"BitwiseAnd","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_and` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"Mean","schema":{"description":"\nElement-wise mean of an arbitrary number of input tensors. This operation can be\nperformed in-place, by using the first input blob as the output blob. All inputs\nmust have the same shape and data type, and the output will have the same shape\nas the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/mean_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mean\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Mean:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.6035237 0.5305746 0.6298913 ]\n [0.9169737 0.01280353 0.16286302]\n [0.6017664 0.9946255 0.05128575]]\nY:\n[[0.07544111 0.45371833 0.08460239]\n [0.9708728 0.7422064 0.7933344 ]\n [0.97671497 0.3411384 0.73818344]]\nZ:\n[[0.08837954 0.90187573 0.46734726]\n [0.6308827 0.8719029 0.39888734]\n [0.90059936 0.92883426 0.5695987 ]]\nMean:\n[[0.25578147 0.6287229 0.39394698]\n [0.8395764 0.5423043 0.45169494]\n [0.8263602 0.75486606 0.45302266]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with the same dimensions as inputs. Contains the mean values of the input tensors calculated element-wise.","name":"M"}],"support_level":"default"}},{"name":"And","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **and** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"And\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n [[ True False False]\n [False True False]\n [False False True]]\nB:\n [[ True False True]\n [False False False]\n [False False False]]\nC:\n [[ True False False]\n [False False False]\n [False False False]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"GivenTensorFill","schema":{"attributes":[{"description":"The value of the elements to go in the *output* tensor.","name":"values"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"},{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with the data specified by the *value* and *dtype* arguments. The output tensor shape is specified by the *shape* argument. Beware, when using this argument *value* should have a value for every element of the *output*, as missing values will not be initialized automatically. If *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: Do not set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/given_tensor_fill_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/given_tensor_fill_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GivenTensorFill\",\n [],\n [\"out\"],\n values=[1., 2., 3.],\n shape=[3],\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [1. 2. 3.]\n\n```\n\n
    \n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor with desired dimension filled with specified data. If the shape argument is set, this is the shape specified, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"GeluGradient","schema":{"description":null,"support_level":"default"}},{"name":"LayerNorm","schema":{"attributes":[{"description":"(int) default to 1; Describes axis of the inputs. Defaults to one because the 0th axis most likely describes the batch size","name":"axis","option":"optional"},{"description":"(float) default to 0.001. Small value to be added to the stdev when dividing out by that value. This prevents division by zero.","name":"epsilon","option":"optional"},{"description":"(bool) default to False; If true, this op will do affine transformation after normalization.","name":"elementwise_affine","option":"optional"}],"description":"\nComputes layer normalization as described in https://arxiv.org/pdf/1607.06450.pdf.\nGiven an input vector x \\in [a_0, a_1, ...,a_{k-1}, a_k, ..., a_{n-1}],\nthis op treats dimensions a_k through a_{n-1} as feature vectors. For each\nfeature vector, the op contains the mean and standard deviation. Then,\nit returns the normalized values (with respect to the feature vector).\n\nNote that this op does not contain the scale an bias terms described in the\npaper. Simply follow this op with an FC op to add those. Concretely, this op\nimplements:\n\nh = \\frac{1}{\\sigma}(a - \\mu)\nwhere \\mu = \\frac{1}{H}\\sum_{i=1}^{H} a_i\nand \\sigma = \\sqrt{\\frac{1}{H}\\sum_{i=1}^{H}(a_i - \\mu)^2}\nwhere H is the number of hidden units (i.e. product of dimensions from 'axis'\nto the end.)\n","inputs":[{"description":"Input tensor which layer normalization will be applied to","name":"input"},{"description":"scale tensor for elementwise_affine, the shape should be the same as the dimensions of X begin from axis","name":"gamma"},{"description":"bias tensor for elementwise_affine, the shape should be the same as the dimensions of X begin from axis","name":"beta"}],"outputs":[{"description":"Normalized values","name":"output"},{"description":"Mean values for each feature vector","name":"mean"},{"description":"Standard deviations for each feature vector","name":"stddev"}],"support_level":"default"}},{"name":"SortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of input tensor. Segments need to be sorted and\ncontiguous. See also UnsortedSegmentWeightedSum that doesn't have this requirement.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"BernoulliJSD","schema":{"description":"\nComputes the Jensen-Shannon divergence (JSD) between two Bernoulli distributions\nwhere each is parametrized by a single probability.\n","inputs":[{"description":"array of probabilities for target","name":"T"}],"outputs":[{"description":"array of JSD losses","name":"L"}],"support_level":"default"}},{"name":"Cosh","schema":{"description":"\nCalculates the hyperbolic cosine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cosh_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cosh\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.66423494 0.32074615 0.81523746 0.90423071 0.39275789]\nY: [1.22883528 1.05188156 1.35112322 1.43744212 1.07812598]\n\n```\n\n
    \n\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic cosine values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"ReduceFrontWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nReduces the input tensor along the first dimension of the input tensor by\napplying 'WeightedSum'. This op acts in a similar way to SortedSegmentWeightedSum and\nUnsortedSegmentWeightedSum but as if all input slices belong to a single segment.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"}],"outputs":[{"description":"Aggregated tensor","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"UnpackRNNSequence","schema":{"description":"\nThis is the reverse operator for PackRNNSequence. It maps the packed values\nback to sequence values based on the length blob. Each number from length blob\nrepresents the corresponding values that has been grouped. The dimension\nfor each pack is the same as the maximum number from the length blob (padding\nwith zero was implemented for smaller length value). The overall output\ndimension is: M * D, where M is the sum of lengths, and D is the dimension of\neach feature value. The following example shows the input and output of\nthis operator:\n\n\nGiven:\n values = [\n [v1, v3, v6, v7],\n [v2, v4, 0, v8],\n [0, v5, 0, 0 ],\n ]\n lengths = [2, 3, 1, 2]\n\n\nOutput:\n output = [v1, v2, v3, v4, v5, v6, v7, v8];\n\n\nOne application for this operator is the transfer data from the format of RNN\nback to sequence values. Note that the gradient operator of\nUnpackRNNSequence is PackRNNSequence.\n","inputs":[{"description":"Data tensor, contains the packed features","name":"values"},{"description":"lengths with each number representing the pack size.","name":"lengths"}],"outputs":[{"description":"Output tensor before packing","name":"output"}],"support_level":"default"}},{"name":"ScaleBlobs","schema":{"attributes":[{"description":"(float, default 1.0) the scale to apply.","name":"scale","option":"optional"}],"description":"\nScaleBlobs takes one or more input data (Tensor) and produces one\nor more output data (Tensor) whose value is the input data tensor\nscaled element-wise.\n","support_level":"default"}},{"name":"SafeEnqueueBlobs","schema":{"description":"\nEnqueue the blobs into queue. When the queue is closed and full, the output\nstatus will be set to true which can be used as exit criteria for execution\nstep.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"support_level":"default"}},{"name":"UnsortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Alias","schema":{"description":"\nMakes the output and the input share the same underlying storage.\n\nWARNING: in general, in caffe2's operator interface different tensors should\nhave different underlying storage, which is the assumption made by\ncomponents such as the dependency engine and memory optimization. Thus, in\nnormal situations you should not use the AliasOp, especially in a normal\nforward-backward pass.\n\nThe Alias op is provided so one can achieve true asynchrony, such as\nHogwild, in a graph. But make sure you understand all the implications\nsimilar to multi-thread computation before you use it explicitly.\n","inputs":[{"description":"Input tensor whose storage will be shared.","name":"input"}],"outputs":[{"description":"Tensor of same shape as input, sharing its storage.","name":"output"}],"support_level":"default"}},{"name":"ScatterWeightedSum","schema":{"description":"\nSimilar to WeightedSum, computes the weighted sum of several tensors, with\nthe difference that inputs are sliced tensors. The first tensor has to be\nin-place and only slices of it on the first dimension as indexed by INDICES\nwill be updated.\n\nNote: The op pretty much ignores the exact shapes of the input arguments and\ncares only about sizes. It's done for performance consideration to avoid\nunnecessary reshapes. Only first dimension of X_0 is important, let's call it\nN. If M is the total size of X_0 and K is the size of INDICES then X_i is\nassumed to be of shape K x (M / N) regardless of the real shape.\n\nNote: Each update in INDICES is applied independently which means that if\nduplicated elements are present in INDICES the corresponding slice of X_0\nwill be scaled multiple times. Manual collapsing of INDICES is required\nbeforehand if necessary.\n\nNote: Updates are applied sequentially by inputs which might have undesired\nconsequences if the input tensor is accessed concurrently by different op\n(e.g. when doing Hogwild). Other threads might see intermediate results even\non individual slice level, e.g. X_0 scaled by weight_0 but without any\nupdates applied.\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"X_0"},{"description":"Scalar weight for X_0, applied only to slices affected.","name":"Weight_0"},{"description":"1-D list of indices on the first dimension of X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"X_1"},{"description":"Scalar weight for X_1 update","name":"Weight_1"}],"outputs":[{"description":"Has to be exactly the same tensor as the input 0","name":"X_0"}],"support_level":"default"}},{"name":"Int8Flatten","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(Default to 1) Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output","name":"axis","option":"optional"}],"description":"\nFlattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn)\n","inputs":[{"description":"A Int8 tensor of rank >= axis.","name":"input"}],"outputs":[{"description":"A 2D Int8 tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output"}],"support_level":"default"}},{"name":"LRNGradient","schema":{"description":null,"support_level":"default"}},{"name":"MaxPool2D","schema":{"description":"MaxPool2D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Softplus","schema":{"description":"\nSoftplus takes one input data tensor $X$ and produces one output data tensor $Y,$ where the softplus function, $y = ln(e^x + 1)$, is applied to $X$ elementwise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softplus_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softplus_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softplus\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.5380011 0.65190786 0.55673236]\n [-0.16272168 0.5451048 0.30880353]\n [-0.76606876 -0.6238556 -0.40444514]]\n\nY:\n [[0.4598992 1.0713093 1.0097669 ]\n [0.61509246 1.0023911 0.8594219 ]\n [0.38174385 0.42909983 0.5112337 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"Input data blob to be operated on.","name":"X"}],"outputs":[{"description":"Output data blob with same shape as input.","name":"Y"}],"support_level":"default"}},{"name":"ReduceL2","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **L2 norm** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceL2\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[ 8. 0. 2. 5. 1.]\n [ 1. 3. 0. 4. 0.]\n [ 1. 3. 6. 7. 7.]\n [ 6. 9. 8. 4. 6.]\n [ 6. 1. 5. 7. 3.]]\n\n [[ 2. 4. 6. 2. 8.]\n [ 1. 1. 8. 0. 8.]\n [ 5. 9. 0. 3. 2.]\n [ 1. 7. 3. 7. 3.]\n [ 6. 8. 9. 8. 7.]]]]\n\nY:\n[[ 8.24621105 4. 6.3245554 5.38516474 8.06225777]\n [ 1.41421354 3.1622777 8. 4. 8. ]\n [ 5.09901953 9.48683262 6. 7.6157732 7.28010988]\n [ 6.08276272 11.40175438 8.54400349 8.06225777 6.70820379]\n [ 8.48528099 8.06225777 10.29563046 10.63014603 7.6157732 ]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"WallClockTime","schema":{"description":"Time since epoch in nanoseconds.","outputs":[{"description":"The time in nanoseconds.","name":"time"}],"support_level":"default"}},{"name":"Cos","schema":{"description":"\nCalculates the cosine of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cos_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cos\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [0.6816719 0.76771533 0.933932 0.01404487 0.11862425]\nY: [0.7765203 0.71949923 0.5946774 0.99990135 0.9929724 ]\n\n```\n\n
    \n\n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cosine of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"AveragePool1D","schema":{"description":"AveragePool1D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Col2Im","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsPositionalWeightedSum","schema":{"description":"\nVariation of SparseLengthsWeightedSum operator, where, for each row,\nweights are accessed by indices [0..L-1], where L is the length of given row.\nThis is basically a fused operator of LengthsRangeFill + Gather +\nSparseWeightedSum\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of DATA","name":"WEIGHT"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Size","schema":{"description":"\nReturn a 1D tensor of type *int64* that contains the number of elements of the input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/utility_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Size\",\n [\"X\"],\n [\"size\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"size:\", workspace.FetchBlob(\"size\"))\n\nworkspace.ResetWorkspace()\n\nworkspace.FeedBlob(\"X\", (np.random.rand(6,4)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"size:\", workspace.FetchBlob(\"size\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[3 7 0]\n [0 1 6]\n [5 0 8]]\nsize: 9\nX:\n[[0.92017884 0.32115368 0.68692035 0.64135016]\n [0.8723328 0.77830265 0.80688656 0.25524236]\n [0.37970216 0.76407047 0.85689564 0.30692883]\n [0.69352573 0.42531502 0.16415212 0.59209324]\n [0.52684188 0.37094846 0.60670079 0.6489272 ]\n [0.94715906 0.34800557 0.61898769 0.28947359]]\nsize: 24\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor)* Input tensor to calculate number of elements.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* 1D tensor of type int64 that contains the number of elements in the input tensor *X*.","name":"size"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 32-bit float in the second to the last 4 bytes of each\nrow, followed by the bias as a 32-bit float in the next 4 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"NanCheck","schema":{"description":"Identity operator, but checks all values for nan or inf","inputs":[{"description":"Tensor to check for nan/inf","name":"tensor"}],"outputs":[{"description":"Tensor to copy input into if no NaNs or inf. Can be in-place","name":"output"}],"support_level":"default"}},{"name":"CbrtGradient","schema":{"description":null,"support_level":"default"}},{"name":"RowWiseSparseAdagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nGiven inputs (param, moment, indices, grad, lr), runs a modified sparse Adagrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_momwnr), where moment is a 1D tensor with length equal to the number of\nrows in param: shape(moment) == shape(param)[0]. Each element of moment is\napplied to an entire row of param, and the new moment is calculated by adding\nthe average squared sum of gradients across each row. Note that indices must\nalso be a 1D tensor indexing into the rows of param.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment_1"}],"support_level":"default"}},{"name":"GivenTensorDoubleFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"LengthsToRanges","schema":{"description":"\nGiven a vector of segment lengths, calculates offsets of each segment and packs\nthem next to the lengths. For the input vector of length N the output is a Nx2\nmatrix with (offset, lengths) packaged for each segment.\n\nFor example, `[1, 3, 0, 2]` transforms into `[[0, 1], [1, 3], [4, 0], [4, 2]]`.\n","inputs":[{"description":"1D tensor of int32 segment lengths.","name":"lengths"}],"outputs":[{"description":"2D tensor of shape len(lengths) X 2 and the same type as `lengths`","name":"ranges"}],"support_level":"default"}},{"name":"SparseSortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosineEmbeddingCriterion","schema":{"description":"\nCosineEmbeddingCriterion takes two inputs: the similarity value and\nthe label, and computes the elementwise criterion output as\n\n output = 1 - s, if y == 1\n max(0, s - margin), if y == -1\n","inputs":[{"description":"The cosine similarity as a 1-dim TensorCPU.","name":"S"},{"description":"The label as a 1-dim TensorCPU with int value of 1 or -1.","name":"Y"}],"outputs":[{"description":"The output loss with the same dimensionality as S.","name":"loss"}],"support_level":"default"}},{"name":"IsEmpty","schema":{"description":"\nThe *IsEmpty* op accepts a single input $tensor$, and produces a single boolean output $is\\_empty$. The output is *True* if and only if $tensor$ has size == 0.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"IsEmpty\",\n [\"tensor\"],\n [\"is_empty\"],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"tensor\", np.random.randn(2, 2).astype(np.float32))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"is_empty: \", workspace.FetchBlob(\"is_empty\"),\"\\n\")\n\n// Use an empty tensor\nworkspace.FeedBlob(\"tensor\", np.empty(0))\nprint(\"tensor:\\n\", workspace.FetchBlob(\"tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"is_empty: \", workspace.FetchBlob(\"is_empty\"))\n\n```\n\n**Result**\n\n```\n\ntensor:\n [[ 0.26018378 0.6778789 ]\n [-1.3097627 -0.40083608]]\nis_empty: False\n\ntensor:\n []\nis_empty: True\n\n```\n\n
    \n\n","inputs":[{"description":"Input data tensor to check if empty.","name":"tensor"}],"outputs":[{"description":"Output scalar boolean tensor. True if input has size == 0.","name":"is_empty"}],"support_level":"default"}},{"name":"KeySplit","schema":{"description":null,"support_level":"default"}},{"name":"LC1D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 1D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"GenerateProposalsCPP","schema":{"description":null,"support_level":"default"}},{"name":"XavierFill","schema":{"attributes":[{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with values sampled from a uniform distribution with the range determined by the desired shape of the output. Rather, than specifying the range of values manually, the novelty of Xavier Fill is that it automatically scales the range of the distribution it draws from based on the size of the desired output tensor. For more information check out the paper [Understanding the difficulty of training deep feedforward neural networks](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf). The output tensor shape is specified by the *shape* argument. However, if *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: Do not set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"XavierFill\",\n [],\n [\"out\"],\n shape=[3,3],\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [[-0.8412168 0.33207083 -0.88418937]\n [ 0.43059897 -0.8340702 0.07781601]\n [ 0.93261135 -0.24542928 -0.3980782 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor of random values drawn from an automatically scaled uniform distribution, based on the size of the output tensor. If the shape argument is set, this is the shape specified by the shape argument, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"QuantDecode","schema":{"description":"\nDecode inputs using codebook. This is a general LUT operator that returns\ntensors with values from codebook (input 0) based on given indices in\ncodes (input 1 ~ n).\n\n\nExample:\n\n\nInput:\n codebook = [1.5, 2.5, 3.5]\n codes_0 = [0, 1, 1, 2]\n codes_1 = [2, 0, 0]\n\n\nOutput:\n decoded_0 = [1.5, 2.5, 2.5, 3.5]\n decoded_1 = [3.5, 1.5, 1.5]\n","inputs":[{"description":"Codebook in 1d tensor (float)","name":"codebook"},{"description":"Encoded codes 0 (uint8/uint16/int32)","name":"codes_0"},{"description":"Encoded codes 1 if existed (uint8/uint16/int32)","name":"codes_1"},{"description":"Encoded codes n if existed (uint8/uint16/int32)","name":"codes_n"}],"outputs":[{"description":"Decoded tensor for codes_0 (float)","name":"decoded_0"},{"description":"Decoded tensor for codes_1 (float)","name":"decoded_1"},{"description":"Decoded tensor for codes_n (float)","name":"decoded_n"}],"support_level":"default"}},{"name":"ElementwiseLinearGradient","schema":{"description":null,"support_level":"default"}},{"name":"TimerGetAndEnd","schema":{"description":"\nQueries the current time of a timer in nanos, stops the timer publishing a CAFFE_EVENT.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\ntimerbegin_op = core.CreateOperator(\n \"TimerBegin\",\n [],\n [\"timer\"]\n)\n\ntimerget_op = core.CreateOperator(\n \"TimerGet\",\n [\"timer\"],\n [\"nanos\"]\n)\n\ntimerend_op = core.CreateOperator(\n \"TimerEnd\",\n [\"timer\"],\n []\n)\n\ntimergetandend_op = core.CreateOperator(\n \"TimerGetAndEnd\",\n [\"timer\"],\n [\"nanos\"]\n)\n\n// Test TimerBegin/TimerGet/TimerEnd\nworkspace.RunOperatorOnce(timerbegin_op)\nprint(\"timer:\", workspace.FetchBlob(\"timer\"))\nworkspace.RunOperatorOnce(timerget_op)\nprint(\"nanos:\", workspace.FetchBlob(\"nanos\"))\nworkspace.RunOperatorOnce(timerend_op)\n\n\n// Test TimerBegin/TimerGetAndEnd\nworkspace.RunOperatorOnce(timerbegin_op)\nprint(\"timer:\", workspace.FetchBlob(\"timer\"))\nworkspace.RunOperatorOnce(timergetandend_op)\nprint(\"nanos:\", workspace.FetchBlob(\"nanos\"))\n\n```\n\n**Result**\n\n```\n\ntimer: b'timer, a C++ native class of type caffe2::TimerInstance*.'\nnanos: 361140\ntimer: b'timer, a C++ native class of type caffe2::TimerInstance*.'\nnanos: [252250]\n\n```\n\n
    \n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"outputs":[{"description":"(*Tensor``*): scalar tensor containing time in nanoseconds","name":"nanos"}],"support_level":"default"}},{"name":"DivGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"Do","schema":{"attributes":[{"description":"Subnet with blob bindings","name":"net","option":"optional"},{"description":"List of inner net blob names to bind to outer workspace","name":"inner_blobs","option":"optional"},{"description":"Indices of corresponding outer workspace blobs, in order: operator inputs, operator outputs (skipping workspace blobs)","name":"outer_blobs_idx","option":"optional"},{"description":"List of blobs from the forward Do operator workspace needed in backward pass, used in gradient Do operator","name":"saved_fwd_blobs","option":"optional"},{"description":"Whether to reuse workspace or create a new one in a given scope","name":"reuse_workspace","option":"optional"}],"description":"\n'Do' control operator, executes a subnet in a separate workspace.\nLast blobs in the input and output lists should be the same blob created with\nCreateScope op. Arguments 'inner_blobs' and 'outer_blobs_idx' provide a mapping\nbetween selected inner blob names and corresponding outer blob indices.\n ","support_level":"default"}},{"name":"DotProductWithPaddingGradient","schema":{"description":null,"support_level":"default"}},{"name":"UniqueUniformFill","schema":{"attributes":[{"description":"Minimum value, inclusive","name":"min","option":"optional"},{"description":"Maximum value, inclusive","name":"max","option":"optional"},{"description":"The data type for the elements of the output tensor.Strictly must be one of the types from DataType enum in TensorProto.This only supports INT32 and INT64 now. If not set, assume INT32","name":"dtype","option":"optional"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob. Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with uniform samples between min and max (inclusive).\nIf the second input is given, its elements will be excluded from uniform\nsampling. Using the second input will require you to provide shape via the first\ninput.\n","inputs":[{"description":"Input tensor to provide shape information","name":"input"},{"description":"(optional) Avoid elements in this tensor. Elements must be unique.","name":"avoid"}],"outputs":[{"description":"Output tensor of unique uniform samples","name":"output"}],"support_level":"default"}},{"name":"LongIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps int64 keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handler"}],"support_level":"default"}},{"name":"ComputeOffset","schema":{"description":"\nCompute the offsets matrix given cursor and data blobs. Need to be ran at\nbeginning or after reseting cursor\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nComputeOffset is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing offset info for this chunk.","name":"field_0"}],"support_level":"default"}},{"name":"ByteWeightDequant","schema":{"description":null,"support_level":"default"}},{"name":"CopyOnDeviceLike","schema":{"description":"Copy input tensor into output to the specific device.","inputs":[{"description":"The input tensor.","name":"input"},{"description":"Tensor, on which device the copy will be performed.","name":"dst"}],"outputs":[{"description":"Tensor that will contain a copy of the input.","name":"output"}],"support_level":"default"}},{"name":"BatchOneHot","schema":{"description":"\nInput is a matrix tensor. Its first dimension is the batch\nsize. Expand each column of it using one hot encoding. The `lengths` specifies\nthe size of each column after encoding, and the `values` is the dictionary value\nof one-hot encoding for each column. For example\n\n If data = [[2, 3], [4, 1], [2, 5]], lengths = [2, 3],\n and values = [2, 4, 1, 3, 5], then\n\n output = [[1, 0, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 1]]\n","inputs":[{"description":"input tensor matrix","name":"data"},{"description":"the size is the same as the width of the `data`","name":"lengths"},{"description":"one hot encoding dictionary values","name":"values"}],"outputs":[{"description":"output matrix that expands each input column with one hot encoding","name":"output"}],"support_level":"default"}},{"name":"DropoutGrad","schema":{"description":null,"support_level":"default"}},{"name":"MulGradient","schema":{"description":null,"support_level":"default"}},{"name":"MarginRankingCriterionGradient","schema":{"description":"\nMarginRankingCriterionGradient takes both X1, X2, Y and dY and\nuses them to update dX1, and dX2 according to the chain rule\nand derivatives of the loss function.\n","support_level":"default"}},{"name":"CreateMutex","schema":{"description":"Creates an unlocked mutex and returns it in a unique_ptr blob.","outputs":[{"description":"Blob containing a std::unique_ptr.","name":"mutex_ptr"}],"support_level":"default"}},{"name":"Float16UniformFill","schema":{"attributes":[{"description":"Shape of the tensor","name":"shape","option":"optional"},{"description":"Minimim value to generate","name":"min","option":"optional"},{"description":"Maximum value to generate","name":"max","option":"optional"}],"description":"Fills a half float tensor of a specified shape with values from a uniform distribution[min,max]","support_level":"default"}},{"name":"SparseAdadelta","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 0.95, the squared gradient sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nGiven inputs (param, moment, moment_delta, indices, grad, lr),\nruns the dense AdaDelta update on (param, grad, moment[indices],\n moment_delta[indices], lr), and returns (new_param, new_moment,\n new_moment_delta) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Average of squared gradients","name":"moment"},{"description":"Average of squared parameter updates","name":"moment_delta"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated average squared gradient","name":"output_moment"},{"description":"Updated average of squared parameter updates","name":"output_moment_delta"}],"support_level":"default"}},{"name":"FloatToRowwiseQuantized8Bits","schema":{"description":"\nThis operator applies 8Bit row-wise quantization to\ninput tensor and returns quantized tensor. Row wise quantization of\ninput tensor is the following process. We take tensor of size\n(m_1, m_2,...,m_n), n >= 2, reshape it into matrix of size\n(m_1, m_2 x... x m_n) and apply row-wise quantization. After this,\nwe compute scale_i= (min_i - max_i) / 255 and bias_i = min_i for\ni-th row r_i of reshaped matrix, where min_i and max_i -- minimum\nand maximum elements of i-th row, and quantize each element r_{ij} as\n0 <= round(r_ij - bias_i) / scale_i) < 256. Instead of input tensor\nwe obtain uint8 tensor and auxiliary information as scale and bias to\nrestore input tensor (with losses).\n","inputs":[{"description":"input","name":"input"}],"outputs":[{"description":"quantized_input","name":"quantized_input"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i","name":"scale_bias"}],"support_level":"default"}},{"name":"SumRelu","schema":{"description":null,"inputs":[{"description":"First of the input tensors. Can be inplace.","name":"data_0"}],"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum"}],"support_level":"default"}},{"name":"LSTMUnitGradient","schema":{"attributes":[{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":null,"support_level":"default"}},{"name":"AveragePool3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeMean","schema":{"description":"\nApplies 'Mean' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Mean', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computation is done element-wise, so that each element of the output slice corresponds to the average value of the respective elements in the input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"DiagonalFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor.Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape","name":"input_as_shape","option":"optional"}],"description":"\nThe operator fills the diagonal elements of the output tensor (>= 2D)\nwith a constant value specified by the 'value' argument, and others 0. If\nnumber of dimensions of the output tensor is greater than 2, all dimensions\nmust be equal.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message. If the 'dtype' argument is not provided, the data type of\n'value' is used.\n\nThe output tensor shape is specified by the 'shape' argument. If the number of\ninput is 1, the shape will be identical to that of the input at run time with\noptional additional dimensions appended at the end as specified by 'extra_shape'\nargument. In that case the 'shape' argument should not be set.\n\nIf input_as_shape is set to true, then the input should be a 1D tensor\ncontaining the desired output shape (the dimensions specified in extra_shape\nwill also be appended)\n\nNOTE: Currently, it supports data type of float, int32, int64, and bool.\n","inputs":[{"description":"Input tensor (optional) to provide shape information.","name":"input"}],"outputs":[{"description":"Output tensorargument and its type is specified by the 'dtype' argument","name":"output"}],"support_level":"default"}},{"name":"ConcatTensorVector","schema":{"description":"\nConcat Tensors in the std::unique_ptr >\nalong the first dimension.\n ","inputs":[{"description":"std::unique_ptr >","name":"vector of Tensor"}],"outputs":[{"description":"tensor after concatenating","name":"tensor"}],"support_level":"default"}},{"name":"Conv2D","schema":{"description":"\nThe convolution operator consumes an input vector, a 2D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"MultiClassAccuracy","schema":{"description":"\nRespectively compute accuracy score for each class given a number of instances\nand predicted scores of each class for each instance.\n","inputs":[{"description":"2-D float tensor (N,D,) of predicted scores of each class for each data. N is the number of instances, i.e., batch size. D is number of possible classes/labels.","name":"prediction"},{"description":"1-D int tensor (N,) of labels for each instance.","name":"labels"}],"outputs":[{"description":"1-D float tensor (D,) of accuracy for each class. If a class has no instance in the batch, its accuracy score is set to zero.","name":"accuracies"},{"description":"1-D int tensor (D,) of number of instances for each class in the batch.","name":"amounts"}],"support_level":"default"}},{"name":"ReduceL2Gradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseUnsortedSegmentSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentSum).\n\nThis op is basically Gather and UnsortedSegmentSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReduceFrontMax","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **max**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the max operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [max(1,4), max(5,1,7), max(2), max(9,2)] = [4, 7, 2, 9]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_max_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontMax\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[2. 8. 1.]\n [9. 6. 6.]\n [7. 7. 0.]]\n\n [[4. 3. 9.]\n [9. 2. 7.]\n [6. 4. 7.]]]\nY: [9. 8. 9.]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ExpandDims","schema":{"attributes":[{"description":"List of dimensions of *data* to add single dimensional entry.","name":"dims","option":"optional","type":"int64[]"}],"description":"\nThe *ExpandDims* op inserts single-dimensional entries into the shape of the input tensor *data,* and produces a single output tensor *expanded*. The op also takes an argument *dims* with a list of dimensions for where to add the single dimensional entries. If the same blob is provided as input and output, the operation is copy-free. This is the exact inverse operation of *Squeeze*.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ExpandDims\",\n [\"data\"],\n [\"expanded\"],\n dims=[0,1],\n)\n\nworkspace.FeedBlob(\"data\", np.zeros((100,100)).astype(np.float32))\nprint(\"data.shape:\", workspace.FetchBlob(\"data\").shape)\n\nworkspace.RunOperatorOnce(op)\nprint(\"expanded.shape:\", workspace.FetchBlob(\"expanded\").shape)\n\n```\n\n**Result**\n\n```\n\ndata.shape: (100, 100)\nexpanded.shape: (1, 1, 100, 100)\n\n```\n\n
    \n\n\n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"data"}],"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded"}],"support_level":"default"}},{"name":"RowMul","schema":{"description":"\nGiven a matrix A and column vector w, the output is the multiplication of row i\nof A and element i of w, e.g. C[i][j] = A[i][j] * w[i]. This operator should be\ndeprecated when the gradient operator of Mul with broadcast is implemented.\n","inputs":[{"description":"The matrix","name":"mat"},{"description":"The column vector","name":"w"}],"outputs":[{"description":"Output","name":"output"}],"support_level":"default"}},{"name":"BatchMoments","schema":{"description":null,"support_level":"default"}},{"name":"IsMemberOf","schema":{"attributes":[{"description":"List of values to check for membership.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from DataType enum in TensorProto.","name":"dtype","option":"optional"}],"description":"\nThe *IsMemberOf* op takes an input tensor *X* and a list of values as argument, and produces one output data tensor *Y*. The output tensor is the same shape as *X* and contains booleans. The output is calculated as the function *f(x) = x in value* and is applied to *X* elementwise.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/elementwise_logical_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/elementwise_logical_ops.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"IsMemberOf\",\n [\"X\"],\n [\"Y\"],\n value=[0,2,4,6,8],\n)\n\n// Use a not-empty tensor\nworkspace.FeedBlob(\"X\", np.array([0,1,2,3,4,5,6,7,8]).astype(np.int32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y: \\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n// value=[0,2,4,6,8]\n\nX:\n [0 1 2 3 4 5 6 7 8]\nY:\n [ True False True False True False True False True]\n\n```\n\n
    \n\n","inputs":[{"description":"Input tensor of any shape","name":"X"}],"outputs":[{"description":"Output tensor (same size as X containing booleans)","name":"Y"}],"support_level":"default"}},{"name":"MinGradient","schema":{"description":null,"support_level":"default"}},{"name":"RangeFill","schema":{"description":null,"support_level":"default"}},{"name":"ReluN","schema":{"attributes":[{"description":"the cap of output","name":"n","option":"optional"}],"description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = min(max(0, x), n),\nis applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"TanhGradient","schema":{"description":null,"support_level":"default"}},{"name":"CubeGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceTailSum","schema":{"description":"\nReduce the tailing dimensions\n","inputs":[{"description":"The matrix","name":"mat"}],"outputs":[{"description":"Output","name":"output"}],"support_level":"default"}},{"name":"GroupNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"Moments","schema":{"attributes":[{"description":"A list of integers, along which to reduce. If axes is not provided, the op computes the element-wise mean and variance.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the mean and variance of the input tensor's element along the\n provided axes. The resulted tensor has the same rank as the input if keepdims\n equals True.\n If keepdims equals False, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced mean tensor.","name":"mean"},{"description":"Reduced variance tensor.","name":"variance"}],"support_level":"default"}},{"name":"ATen","schema":{"description":null,"support_level":"contribution"}},{"name":"LC1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsToSegmentIds","schema":{"description":"\nGiven a vector of segment lengths (*lengths*) the *LengthsToSegmentIds* op returns a zero-based, consecutive vector of segment ids (*segment_ids*). For example, *lengths=[1, 3, 0, 2]* will produce *segment_ids=[0, 1, 1, 1, 3, 3]*. In general, the inverse operation is *SegmentIdsToLengths*. Notice though that trailing empty sequence lengths can't be properly recovered from segment ids.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.cc\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/utility_ops.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsToSegmentIds\",\n [\"lengths\"],\n [\"segment_ids\"],\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([1, 3, 0, 2]).astype(np.int32))\nprint(\"lengths:\\n\", workspace.FetchBlob(\"lengths\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"segment_ids: \\n\", workspace.FetchBlob(\"segment_ids\"))\n\n```\n\n**Result**\n\n```\n\nlengths:\n [1 3 0 2]\nsegment_ids:\n [0 1 1 1 3 3]\n\n```\n\n
    \n\n","inputs":[{"description":"1D tensor of int32 or int64 segment lengths.","name":"lengths"}],"outputs":[{"description":"1D tensor of length *sum(lengths)*","name":"segment_ids"}],"support_level":"default"}},{"name":"Wngrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nComputes the WnGrad update for an input gradient and accumulated\nhistory. This operator implement the optimization algorithm\nin https://arxiv.org/abs/1803.02865 by Wu, Ward and Bottou.\nConcretely, given inputs (param, grad, seq_b, learning_rate),\ncomputes\n\n new_seq_b = seq_b + 1 / seq_b * norm(grad)^2\n effective_lr = learning_rate / (new_seq_b + epsilon)\n update = learning_rate * grad / (new_seq_b + epsilon)\n new_param = param + update\nand returns (new_param, new_seq_b).\n\nOptionally returns effective_lr and update as well.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Seq_b history","name":"seq_b"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated seq_b","name":"output_seq_b"},{"description":"(optional) Effective learning rate","name":"output_effective_lr"},{"description":"(optional) Actual update that is applied.","name":"output_update"}],"support_level":"default"}},{"name":"Or","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise logical operation **or** (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Or\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", (np.random.rand(3, 3) > 0.5))\nworkspace.FeedBlob(\"B\", (np.random.rand(3, 3) > 0.5))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[False True True]\n [False True True]\n [ True True True]]\nB:\n[[False True False]\n [ True True True]\n [False True False]]\nC:\n[[False True True]\n [ True True True]\n [ True True True]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* First operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of booleans. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"EQ","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise equal to comparison **==** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"EQ\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True False False True True False]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"ErfGradient","schema":{"description":null,"support_level":"default"}},{"name":"ChannelBackpropStats","schema":{"description":"\nGiven an input tensor in NCHW format, the gradient for the output of SpatialBN\nand the per-channel mean and inverse std var vectors for the input, computes the\nper-channel bias and scale gradient to be used during the backward pass for\nsubsequent spatial batch normalization gradient calculation. Typically, the\nresults of this op are subsequently reduced over multiple devices to obtain\nstatistics over a larger batch size in cases where the batch size for a single\nmodel copy is too low to yield the full benefit of batch normalization. The\nresulting bias and scale can then be plugged back into SpatialBNGradient to get\nresults over the larger batch size ","inputs":[{"description":"The input 4-dimensional tensor of shape NCHW","name":"X"},{"description":"The mean saved from the forward pass as a 1-dimensional tensor of size C.","name":"mean"},{"description":"The saved inverse standard deviation as a 1-dimensional tensor of size C.","name":"inv_std"},{"description":"Gradient for the output layer of SpatialBN, here used as input because we are on the backward pass","name":"output_grad"}],"outputs":[{"description":"Gradient for the scale vector","name":"scale_grad"},{"description":"Gradient for the bias vector","name":"bias_grad"}],"support_level":"default"}},{"name":"GatherRangesToDense","schema":{"attributes":[{"description":"Expected lengths for ranges","name":"lengths","option":"optional"},{"description":"The number of observations needed before deciding that the ratio of mismatched ranges is alarming, also determines whether an info sumarizing the empty and mismatch ratio will be printed at the end.","name":"min_observation","option":"optional"},{"description":"An error is raised when ratio of empty ranges exceeds this (default is 1, which means by default no error will be triggered).","name":"max_empty_ratio","option":"optional"},{"description":"An error is raised when ratio of mismatched ranges exceeds this.","name":"max_mismatched_ratio","option":"optional"},{"description":"A log is recorded only after an error is triggered every n times.","name":"log_every_n","option":"optional"}],"description":"\nGiven DATA tensor of rank 1, and RANGES tensor of rank 3, gather values\ncorresponding to each range into a separate output tensor. If the optional input\nKEY tensor is also given, the output will be sorted by KEY for each example.\n\nRANGES dimensions description:\n1: represents list of examples within a batch\n2: represents list features\n3: two values which are start and length or a range (to be applied on DATA)\n\nEach feature has fixed lengths which are passed as lengths argument and a\nseparate tensor will be produced for each feature.\ni.e. DATA.dim(1) = len(lengths) = NumOuptuts.\n\nMissing features (represented by empty ranges) filled with default_value.\n\nExample 1:\n DATA = [1, 2, 3, 4, 5, 6, 7, 8]\n RANGES = [\n [\n [2, 4],\n [0, 2],\n ],\n [\n [0, 0],\n [6, 2],\n ]\n ]\n lengths = [4, 2]\n OUTPUT[0] = [[3, 4, 5, 6], [0, 0, 0, 0]]\n OUTPUT[1] = [[1, 2], [7, 8]]\n\nExample 2 (with KEY):\nDATA = [1, 2, 3, 4, 5, 6, 7, 8]\nKEY = [0, 1, 3, 2, 1, 0, 1, 0]\nRANGES = [\n [\n [2, 4],\n [0, 2],\n ],\n [\n [0, 0],\n [6, 2],\n ]\n]\nlengths = [4, 2]\nOUTPUT[0] = [[6, 5, 4, 3], [0, 0, 0, 0]]\nOUTPUT[1] = [[1, 2], [8, 7]]\n\nContrast Example 2 with Example 1. For each data point per feature, the values\nare sorted by the corresponding KEY.\n","inputs":[{"description":"Tensor of rank 1.","name":"DATA"},{"description":"Tensor of int32/int64 ranges, of dims (N, M, 2). Where N is number of examples and M is a size of each example. Last dimension represents a range in the format (start, lengths)","name":"RANGES"},{"description":"Tensor of rank 1 and type int64.","name":"KEY"}],"outputs":[{"description":"1-D tensor of size sum of range lengths","name":"OUTPUT"}],"support_level":"default"}},{"name":"LambdaRankNdcg","schema":{"description":"\nIt implements the LambdaRank as appeared in Wu, Qiang, et al. \"Adapting boosting\nfor information retrieval measures.\" Information Retrieval 13.3 (2010): 254-270.\n\nThis method heuristically optimizes the NDCG.\n","support_level":"default"}},{"name":"TileGradient","schema":{"description":null,"support_level":"default"}},{"name":"ResetCursor","schema":{"description":"\nResets the offsets for the given TreeCursor. This operation is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"}],"support_level":"default"}},{"name":"SortedSegmentRangeMax","schema":{"description":"\nApplies 'Max' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Max', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMax computation is done element-wise, so that each element of the output slice corresponds to the max value of the respective elements in the input slices. Operation doesn't change the shape of individual blocks. This implementation imitates torch nn.Max operator. If the maximum value occurs more than once, the operator will return the first occurrence of value. When computing the gradient using the backward propagation, the gradient input corresponding to the first occurrence of the maximum value will be used.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"PairWiseLoss","schema":{"description":"\nOperator computes the pair wise loss between all pairs within a batch\n using the logit loss function on the difference in scores between pairs\n","inputs":[{"description":"Input blob from the previous layer, which is almost always the result of a softmax operation; X is a 2D array of size N x 1where N is the batch size. For more info: D. Sculley, Large Scale Learning to Rank. https://www.eecs.tufts.edu/~dsculley/papers/large-scale-rank.pdf","name":"X"},{"description":"Blob containing the labels used to compare the input","name":"label"},{"description":"Optional input blob that contains the lengthsof multiple sessions. The summation of this blob must be equalto the size of blob X. If lengths blob is provided, the outputblob has the same size as lengths blob, and the cross entropyis computed within each session.","name":"lengths"}],"outputs":[{"description":"Output blob after the cross entropy computation","name":"Y"}],"support_level":"default"}},{"name":"NHWC2NCHW","schema":{"description":"\nThe operator switches the order of data in a tensor from NHWC- sample index N,\nheight H, width H and channels C, to the NCHW order (this is for 2D images).\nIn general, this operator switches the order of data in a tensor from N H_1 ...\nH_k C to N C H_1 ... H_k for k-dimensional features, and currently supports\nk=1, 2, and 3.\n","inputs":[{"description":"The input data (Tensor) in the NHWC order.","name":"data"}],"outputs":[{"description":"The output tensor (Tensor) in the NCHW order.","name":"output"}],"support_level":"default"}},{"name":"CreateRebatchingQueue","schema":{"attributes":[{"description":"Number of input tensors the queue will support","name":"num_blobs","option":"optional"},{"description":"Maximal number of elements the queue can hold at any given point","name":"capacity","option":"optional"}],"description":"\nCreates the Queue.\n","outputs":[{"description":"object representing the queue","name":"queue"}],"support_level":"default"}},{"name":"GE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise greater or equal than comparison **>=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True True False True True False]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"SinusoidPositionEncoding","schema":{"attributes":[{"description":"Desired embedding size/number of dimensions -- defaults to 100","name":"embedding_size","option":"optional"},{"description":"Sinusoid tuning parameter -- defaults to 10000","name":"alpha","option":"optional"},{"description":"Amplitude of Sin/Cos output","name":"amplitude","option":"optional"}],"description":"\nCalculates a sinusoid position encoding tensor as described\nin https://arxiv.org/abs/1706.03762. Takes a 2-D tensor\n(of size M x K) of positions as input, the embedding size\nas an argument, and outputs a position encoding tensor of\nsize (M x K x embedding_size). Here M is typically the max\nsequence length and K is typically the batch size.\nThe input tensor must satisfy input[m, 0] == input[m, k] for all k.\n\nEncoded as amplitude * SIN(pos/alpha^(i/embedding_size)) if i is even,\nelse amplitude * COS(pos/alpha^(i/embedding_size)). Here, pos is the position,\nalpha and amplitude are tuning parameters, i is the current dimension for\nthe embedding, and embedding_size is the number of total dimensions in\nthe embedding.\n","inputs":[{"description":"2-D tensor of positions to be encoded","name":"positions"}],"outputs":[{"description":"3-D tensor representing the positional encoding","name":"output"}],"support_level":"default"}},{"name":"SortedSegmentRangeMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"RoIAlignGradient","schema":{"description":null,"inputs":[{"description":"See RoIPoolF.","name":"X"},{"description":"See RoIPoolF.","name":"RoIs"},{"description":"Gradient of forward output 0 (Y)","name":"dY"}],"outputs":[{"description":"Gradient of forward input 0 (X)","name":"dX"}],"support_level":"default"}},{"name":"UnsortedSegmentWeightedSum","schema":{"attributes":[{"description":"Optional int argument specifying the number of output segments and thus the first dimension of the output","name":"num_segments","option":"optional"},{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of input tensor. Segments ids can appear in\narbitrary order (unlike in SortedSegmentWeightedSum).\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector with the same length as the first dimension of DATA that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"BatchMatMul","schema":{"attributes":[{"description":"Pass 1 to transpose the last two dimensions of A before doing multiplication","name":"trans_a","option":"optional"},{"description":"Pass 1 to transpose the last two dimensions of B before doing multiplication","name":"trans_b","option":"optional"},{"description":"Pass 1 to allow broadcasting of dimensions. Behavior is the same as numpy.matmul. Gradient is currently not supported when running in broadcast mode.","name":"broadcast","option":"optional"}],"description":"\nBatch Matrix multiplication Yi = Ai * Bi, where A has shape (dim0, dim1, ... M, K),\nB has shape (dim0, dim1, ... K, N), Y has shape (dim0, dim1, ... M, N) and i ranges\nfrom 0 to (dim0 * dim1 ...) - 1. rank(A) == rank(B) >= 2. In case of A and B being\ntwo dimensional, it behaves like normal matrix multiplication.\n","inputs":[{"description":"tensor of shape (dim0, dim1 ... M, K)","name":"A"},{"description":"tensor of shape (dim0, dim1 ... K, N)","name":"B"}],"outputs":[{"description":"tensor of shape (dim0, dim1 ... M, N)","name":"Y"}],"support_level":"default"}},{"name":"LpNormGradient","schema":{"attributes":[{"description":"Order of the norm in p-norm","name":"p","option":"optional"},{"description":"whehther we calculate norm or averaged_norm.The Lp_averaged_norm(x) is defined asLp_averaged_normgradient(x) = LpNormGradient(x) / size(x)","name":"average","option":"optional"}],"description":"\nGiven one input float tensor X, derivative dout, and produces one output\nfloat tensor dX. dX is the derivative of the Lp norm of tensor X, computed as\ndx = d(sum over |x^p|)/dx, in which p is either 1 or 2(currently only\nsupports l1 and l2 norm) determined by the argument p.\n","inputs":[{"description":"1D input tensor","name":"X"},{"description":"1D input tensor","name":"dout"}],"outputs":[{"description":"1D output tensor","name":"dx"}],"support_level":"default"}},{"name":"DotProduct","schema":{"description":"\nComputes and outputs the dot product of the two input float tensors `X` and `Y`.\nNote that `X` and `Y` must be either 1D or 2D, and they must be the same shape.\nThe output tensor is 1D, which represents either the product of each element in\na respective dimension if the inputs are 1D, or the sum of the products in a\ngiven dimension if the inputs are 2D matrices. Note that the actual dot product\nis a scalar value, which is effectively the sum of the elements in the 1D\noutput tensor.\n\nFor 1D inputs:\nGiven two vectors $X = [x_0, x_1, x_2]$ and $Y = [y_0, y_1, y_2]$; $Z = [x_0 * y_0, x_1 * y_1, x_2 * y_2]$\n\nFor 2D inputs:\nGiven two matrices:\n$$X = [[x_0^0, x_1^0, x_2^0], \\\\ [x_0^1, x_1^1, x_2^1], \\\\ [x_0^2, x_1^2, x_2^2], \\\\ ..., \\\\ [x_0^n, x_1^n, x_2^n]]$$\n\nand\n\n$$Y = [[y_0^0, y_1^0, y_2^0], \\\\ [y_0^1, y_1^1, y_2^1], \\\\ [y_0^2, y_1^2, y_2^2], \\\\ ..., \\\\ [y_0^n, y_1^n, y_2^n]]$$\n\nthen\n\n$$Z = \\biggl[\\Big((x_0^0 * y_0^0) + (x_1^0 * y_1^0) + (x_2^0 * y_2^0)\\Big), \\\\ \\Big((x_0^1 * y_0^1) + (x_1^1 * y_1^1) + (x_2^1 * y_2^1)\\Big), \\\\ \\Big((x_0^2 * y_0^2) + (x_1^2 * y_1^2) + (x_2^2 * y_2^2)\\Big), \\\\ ..., \\\\ \\Big((x_0^n * y_0^n) + (x_1^n * y_1^n) + (x_2^n * y_2^n)\\Big)\\biggr]$$\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"DotProduct\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(20, size=(5)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", np.random.randint(20, size=(5)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Z:\\n\", workspace.FetchBlob(\"X\"))\n\n\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", np.random.randint(10, size=(3,3)).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [ 2. 15. 2. 7. 12.]\nY:\n [ 3. 12. 9. 3. 18.]\nZ:\n [ 2. 15. 2. 7. 12.]\nX:\n [[2. 0. 4.]\n [7. 7. 4.]\n [7. 9. 9.]]\nY:\n [[2. 0. 8.]\n [9. 6. 1.]\n [7. 8. 0.]]\nZ:\n [ 36. 109. 121.]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* 1D or 2D input tensor.","name":"X"},{"description":"*(type: Tensor``)* 1D or 2D input tensor (must have the same shape as X).","name":"Y"}],"outputs":[{"description":"*(type: Tensor``)* 1D output tensor.","name":"Z"}],"support_level":"default"}},{"name":"NGramFromCategorical","schema":{"description":null,"support_level":"default"}},{"name":"Int8Slice","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"List of starting indices","name":"starts","option":"optional"},{"description":"List of ending indices","name":"ends","option":"optional"},{"description":"(Optional) The dimension to slice over. If specified start_idx and end_idx should also be given and it takes precedence over starts and ends","name":"dim","option":"optional"},{"description":"(Optional) The dimension to start slice from. Default is 0","name":"start_idx","option":"optional"},{"description":"(Optional) The dimension to end the slice. Default is -1","name":"end_idx","option":"optional"}],"description":"\nProduces a slice of the input Int8 tensor. Currently, only slicing in a single\ndimension is supported.\nSlices are passed as 2 1D vectors or as two keyword argument lists with starting\nand end indices for each dimension of the input `data` tensor. If a negative\nvalue is passed for any of the start or end indices, it represents the number of\nelements before the end of that dimension. End indices are non-inclusive unless\nnegative (end index -1 means up to and including the last element).\n\n\nExample:\n\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 3]\n\n result = [\n [2, 3],\n [6, 7],\n ]\n","inputs":[{"description":"Int8 Tensor of data to extract slices from.","name":"data"},{"description":"1D tensor: start-indices for each dimension of data.","name":"starts"},{"description":"1D tensor: end-indices for each dimension of data.","name":"ends"}],"outputs":[{"description":"Sliced Int8 data tensor.","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceFrontSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ViterbiPath","schema":{"description":"\nGiven a predictions matrix and a transitions matrix, get the path with the best\nscore\n","inputs":[{"description":"N*D predictions matrix","name":"predictions"},{"description":"D*D transitions matrix","name":"transitions"}],"outputs":[{"description":"N*1 vector holds the best path indices","name":"viterbi_path"}],"support_level":"default"}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce.","name":"axes","option":"optional"},{"description":"Keep the reduced dimension(s) or not, default True keeps the reduced dimension(s).","name":"keepdims","option":"optional"}],"description":"\n Computes the max of the input tensor's element along the provided axes.\n The resulted tensor has the same rank as the input if keepdims equal True.\n If keepdims equal false, then the resulted tensor have the reduced dimension\n pruned.\n","inputs":[{"description":"An input tensor.","name":"data"}],"outputs":[{"description":"Reduced output tensor.","name":"reduced"}],"support_level":"default"}},{"name":"SparseLengthsWeightedMean8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsWeightedMean operator, where\nDATA is stored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of INDICES","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Slice","schema":{"attributes":[{"description":"(*Tuple(int)*): list of starting indices","name":"starts","option":"optional"},{"description":"(*Tuple(int)*): list of ending indices","name":"ends","option":"optional"}],"category":"Tensor","description":"\nProduces a slice of the input tensor.\n\n- Currently, only slicing in a single dimension is supported.\n\n- Start and end indices are either passed as two 1D input tensors or using the `starts` and `ends` arguments.\n\n- If a negative value is passed for any of the start or end indices, it represents the number of elements before the end of that dimension. End indices are non-inclusive unless negative (end index -1 means up to and including the last element).\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/slice_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Slice\",\n [\"X\"],\n [\"Y\"],\n starts=(0,1),\n ends=(-1,3)\n)\n\nworkspace.FeedBlob(\"X\", np.array([[1,2,3,4],[5,6,7,8]]))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[1 2 3 4]\n [5 6 7 8]]\nY:\n[[2 3]\n [6 7]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): tensor to extract slices from","name":"X"},{"description":"(*Tensor``*): 1D tensor of start-indices for each dimension of data","name":"starts"},{"description":"(*Tensor``*): 1D tensor of end-indices for each dimension of data","name":"ends"}],"outputs":[{"description":"(*Tensor*): sliced output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"InstanceNormGradient","schema":{"description":null,"support_level":"default"}},{"name":"UpsampleBilinearGradient","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"SortAndShuffle","schema":{"description":"\nCompute the sorted indices given a field index to sort by and break the sorted\nindices into chunks of shuffle_size * batch_size and shuffle each chunk,\nfinally we shuffle between batches. If sort_by_field_idx is -1 we skip sort.\n\nFor example, we have data sorted as\n1,2,3,4,5,6,7,8,9,10,11,12\n\nand batchSize = 2 and shuffleSize = 3, when we shuffle we get:\n[3,1,4,6,5,2] [12,10,11,8,9,7]\n\nAfter this we will shuffle among different batches with size 2\n[3,1],[4,6],[5,2],[12,10],[11,8],[9,7]\n\nWe may end up with something like\n[9,7],[5,2],[12,10],[4,6],[3,1],[11,8]\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nSortAndShuffle is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing sorted indices.","name":"indices"}],"support_level":"default"}},{"name":"Int8MaxPoolRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"MaxPool \nconsumes an input blob X and applies max pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Max pooling consisting of taking the maximum value of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linearfunction, where y = max(0, x).","name":"Y"}],"support_level":"default"}},{"name":"BitwiseOr","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_or` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"Int8SumRelu","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"MaxPool2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"Percentile","schema":{"description":"\n This operator is used to find percentile representations for raw values, given a sample\n set of raw values, labeled with their corresponding percentiles from the same distribution.\n In particular, this operator takes as input a tensor of floats to find the percentile values\n for, a 2D tensor of floats, where the first column of the tensor represents sampled values,\n and the second column represents the percentile labels, and a tensor of integers lengths.\n\n This lengths tensor is used because the operator works on multiple sets of raw values at the same time. For\n example, for an input:\n original_values=[[3, 5, 3],[5, 1, 6]], lengths = [2, 1, 1], value_to_pct = [[3, 0.2], [5, 0.5], [1, 0.3], [3. 0.6]]\n\n Our operator expects that each column i of the input tensor is sampled from distribution i. Lengths tells\n us that the first two elements in value_to_pct are sampled from distribution 1, the next is from distribution two,\n and the last is from distribution 3. We expect the output of our operator to give us [[0.2, 1.0, 0.6], [0.5, 0.3, 1.0]].\n\n To calculate the percentile of an element, we check to see if its value is already mapped to\n a percentile in value_to_pct. If so, we return that value. If not, we linearly interpolate between\n the two closest values in value_to_pct. If the value is larger than all values in value_to_pct, we\n return 1. If it's smaller than all the values, we return 0.\n\n","inputs":[{"description":"Input 2D tensor of floats, representing the original, raw data to calculate percentiles for.","name":"original_values"},{"description":"Sorted 2D tensor, with 2 columns. Each element in the first column is a float representing the raw value of a sample. Its corresponding element in the next column represents the percentile it maps to.","name":"value_to_pct"},{"description":"1D tensor, representing the length of each distribution. We expect that the sum of elements of this tensor is equal to the total length of value_to_pct.","name":"lengths"}],"outputs":[{"description":"1D tensor of floats, with the same dimensions as the flattened input tensor. Each element of this tensor, percentile_values[i], corresponds to the percentile calculated for original_values[i].","name":"percentile_values"}],"support_level":"default"}},{"name":"MergeSingleListFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with list features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values","name":"in1_values"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"RowwiseMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"rnn_internal_apply_link","schema":{"description":"\nInternal RNN operator.\n","support_level":"default"}},{"name":"MergeSingleScalarFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with scalar features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":"","name":"in1"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values","name":"out_values"}],"support_level":"default"}},{"name":"BRGNCHWCToPackedInt8BGRAStylizerDeprocess","schema":{"description":null,"support_level":"default"}},{"name":"TrimDataset","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nTrim the given dataset inplace, given the dataset blobs and the field specs.\nTrimming happens such that the dataset will contain the largest possible number\nof records that is a multiple of the 'multiple_of' argument.\n","support_level":"default"}},{"name":"PiecewiseLinearTransform","schema":{"attributes":[{"description":"1-D vector of size (prediction_dimensions x (pieces+1)) contain the upper bounds of each piece of linear function. One special case is the first bound is the lower bound of whole piecewise function and we treat it the same as the left most functions. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"bounds","option":"optional"},{"description":"1-D vector of size (prediction_dimensions x pieces) containing the slopes of linear function","name":"slopes","option":"optional"},{"description":"1-D vector of size (prediction_dimensions x pieces) containing the intercepts of linear function","name":"intercepts","option":"optional"},{"description":"If set true, we assume the input is a Nx1 or Nx2 tensor. If it is Nx1 tensor, it is positive predictions. If the input is Nx2 tensor, its first column is negative predictions and second column is positive and negative + positive = 1. We just need one group of piecewise linear functions for the positive predictions.","name":"binary","option":"optional"}],"description":"\nPiecewiseLinearTransform takes inputs -- predictions, a 2-D or 1-D tensor\n(Tensor) of size (batch_size x prediction_dimensions). The piecewise\nlinear functions are stored in bounds, slopes and intercepts. The output tensor\nhas the same shape of input `predictions` and contains the predictions\ntransformed by the piecewise linear functions. Each column of predictions has\nits own piecewise linear transformation functions. Therefore the size of\npiecewise function parameters are pieces x prediction_dimensions, except for\nbinary predictions where only the positive prediction needs them. Note that in\neach piece, low bound is excluded while high bound is included. Also the\npiecewise linear function must be continuous.\n\nNotes\n- If the input is binary predictions (Nx2 or Nx1 tensor), set the binary arg\nto true so that one group of piecewise linear functions is needed (see\ndetails below).\n- The transform parameters (bounds, slopes, intercepts) can be passed either\nthrough args or through input blobs.\n- If we have multiple groups of piecewise linear functions, each group has the\nsame number of pieces.\n- If a prediction is out of the bounds, it is capped to the smallest or largest\nbound.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing scores","name":"predictions"},{"description":"See bounds in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"bounds (optional)"},{"description":"See slopes in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"slopes (optional)"},{"description":"See intercepts in Arg. (bounds, slopes, intercepts) can be passed through either arg or input blobs.","name":"intercepts (optional)"}],"outputs":[{"description":"2-D tensor (Tensor) of size (num_batches x num_classes) containing transformed predictions","name":"transforms"}],"support_level":"default"}},{"name":"CosineSimilarity","schema":{"description":"\nThis op takes two input float tensors of the same size, $X$ and $Y$, and produces one output float tensor , $Z$, calculated as the cosine similarity between $X$ and $Y$. Recall, the cosine similarity between two tensors $X$ and $Y$ is defined as:\n\n$$\\mathbf{Z}=CosineSimilarity(\\mathbf{X},\\mathbf{Y}) = \\frac{\\mathbf{X}\\cdot\\mathbf{Y}}{\\|\\mathbf{X}\\|\\|\\mathbf{Y}\\|} = \\frac{\\sum_n^{i=1}X_iY_i}{\\sqrt{\\sum_n^{i=1}X_i^2}\\sqrt{\\sum_n^{i=1}Y_i^2}}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/distance_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"CosineSimilarity\",\n [\"X\", \"Y\"],\n [\"Z\"]\n)\n\n// Create X\nX = np.random.randn(3, 3)\nprint(\"X:\\n\",X)\n\n// Create Y\nY = np.random.randn(3, 3)\nprint(\"Y:\\n\",Y)\n\n// Feed X & Y into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"Y\", Y.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Z:\\n\", workspace.FetchBlob(\"Z\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-0.42635564 -0.23831588 -0.25515547]\n [ 1.43914719 -1.05613228 1.01717373]\n [ 0.06883105 0.33386519 -1.46648334]]\nY:\n [[-0.90648691 -0.14241514 -1.1070837 ]\n [ 0.92152729 -0.28115511 -0.17756722]\n [-0.88394254 1.34654037 -0.80080998]]\nZ:\n [-1.7849885e-23 1.7849885e-23 -1.0842022e-07]\n\n```\n\n
    \n\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor (must have the same shape as X)","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"ClipTensorByScaling","schema":{"attributes":[{"description":"Threshold to determine whether to scale down the tensor","name":"threshold","option":"optional"}],"description":"\n Clips the input tensor by scaling based on the input value and the threshold.\n The value is usually the (pre-computed) norm of the tensor. If the value is\n larger than the threshold, scaling would be performed in this way:\n\n tensor *= (threshold / value).\n\n An optional input called additional_threshold can be provided which\n will scale the original threshold before it is used. That is,\n the final threshold will become threshold * additional_threshold.\n This op could be used for gradient clipping.\n","inputs":[{"description":"Tensor of floats to be clipped.","name":"input_tensor"},{"description":"Value to be compared against the threshold","name":"val"},{"description":"An optional additional threshold to scale the original threshold","name":"additional_threshold"}],"outputs":[{"description":"Tensor of floats, which is the same size as the input tensor, representing the clipped tensor.","name":"clipped"}],"support_level":"default"}},{"name":"InstanceNorm","schema":{"attributes":[{"default":0.00001,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","option":"optional","type":"float32"},{"default":"NCHW","description":"Specifies the order of the input data blob, where $N$ is batch size, $C$ is number of channels, $H$ is spatial height, and $W$ is spatial width. The only other valid option is \"NHWC\".","name":"order","option":"optional","type":"string"}],"description":"\nThe *InstanceNorm* op applies Instance Normalization over a 4D input as described in [Instance Normalization: The Missing Ingredient for Fast Stylization](https://arxiv.org/abs/1607.08022).\n\n$$output = \\frac{input-\\mu_{input}}{\\sqrt{\\sigma_{input}^2} + \\epsilon}*scale + bias$$\n\nNotice, two of the outputs are optional so there are three output cases for this op. Case 1: output; Case 2: output, saved_mean; Case 3: output, saved_mean, saved_inv_stdev.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/instance_norm_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/instance_norm_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"InstanceNorm\",\n [\"input\", \"scale\", \"bias\"],\n [\"output\"],\n epsilon=1e-5,\n)\n\nworkspace.FeedBlob(\"input\", np.random.randn(2, 1, 3, 3).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"), \"\\n\")\n\nworkspace.FeedBlob(\"scale\", np.array([1.5]).astype(np.float32))\nprint(\"scale: \", workspace.FetchBlob(\"scale\"))\n\nworkspace.FeedBlob(\"bias\", np.array([1.]).astype(np.float32))\nprint(\"bias: \", workspace.FetchBlob(\"bias\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output:\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [[[[ 0.97856593 -1.1832817 -0.2540021 ]\n [-1.3315694 -0.7485018 0.3787225 ]\n [-0.6826597 -1.4637762 0.57116514]]]\n\n\n [[[-0.44948956 0.85544354 -0.9315333 ]\n [-0.37202677 -0.22266895 -0.27194235]\n [ 0.4948163 -0.7296504 1.3393803 ]]]]\n\nscale: [1.5]\nbias: [1.]\noutput:\n [[[[ 3.5017493 -0.3791256 1.2890853 ]\n [-0.6453266 0.40137637 2.4249308 ]\n [ 0.5195738 -0.8826599 2.7703972 ]]]\n\n\n [[[ 0.12639964 2.856744 -0.8821926 ]\n [ 0.28847694 0.60098207 0.49788612]\n [ 2.1021945 -0.45978796 3.869297 ]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"The input 4-dimensional NCHW tensor to be operated on.","name":"input"},{"description":"The input 1-dimensional scale tensor of size *C*.","name":"scale"},{"description":"The input 1-dimensional bias tensor of size *C*.","name":"bias"}],"outputs":[{"description":"The output 4-dimensional tensor of the same shape as input.","name":"output"},{"description":"(Optional) Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean"},{"description":"(Optional) Saved inverse stdev used during training to speed up gradient computation. Should not be used for testing.","name":"saved_inv_stdev"}],"support_level":"default"}},{"name":"RoIAlignRotated","schema":{"attributes":[{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nSimilar to RoIAlign but can handle rotated region proposals.\nBased on https://arxiv.org/abs/1703.01086.\n","inputs":[{"description":"4D feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 5 or 6) specifying R RoIs representing: batch index in [0, N - 1], center_x, center_y, width, height, angle. The RoI coordinates are in the coordinate system of the input image. `angle` should be specified in degrees and represents the RoI rotated counter-clockwise. For inputs corresponding to a single image, batch index can be excluded to have just 5 columns.","name":"RoIs"}],"outputs":[{"description":"4D output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"StringJoin","schema":{"attributes":[{"description":"Delimiter for join (Default: \",\").","name":"delimiter","option":"optional"},{"description":"Axis for the join (either 0 or 1)","name":"axis","option":"optional"}],"description":"\nTakes a 1-D or a 2-D tensor as input and joins elements in each row with the\nprovided delimiter. Output is a 1-D tensor of size equal to the first dimension\nof the input. Each element in the output tensor is a string of concatenated\nelements corresponding to each row in the input tensor. For 1-D input, each\nelement is treated as a row.\n","inputs":[{"description":"1-D or 2-D tensor","name":"input"}],"outputs":[{"description":"1-D tensor of strings created by joining row elements from the input tensor.","name":"strings"}],"support_level":"default"}},{"name":"ConvGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherFused8BitRowwise","schema":{"description":"\nPerform the same operation as Gather, but operating on 8-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\nthe scale and offset).\nDATA needs to have rank 2 and INDICES needs to have rank 1.\n","inputs":[{"description":"uint8 tensor with rank 2 obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA forthe rows that are being gathered","name":"INDICES"}],"outputs":[{"description":"output","name":"OUTPUT"}],"support_level":"default"}},{"name":"Lars","schema":{"attributes":[{"description":"rescaling offset parameter","name":"offset","option":"optional"},{"description":"minimum learning rate for clipping","name":"lr_min","option":"optional"}],"description":"\nImplement Layer-wise Adaptive Rate Scaling (LARS) with clipping. Before adding weight\ndecay, given a parameter tensor X and its gradient dX, the local learning rate\nfor X will be\n\nlocal_lr = trust * norm(X) / ( norm(dX) + wd * norm(X) + offset * norm(X) )\n\n = trust / ( norm(dX) / norm(X) + wd + offset ),\n\nwhere offset is a preset hyper-parameter to avoid numerical issue and trust\nindicates how much we trust the layer to change its parameters during one update.\nIn this implementation, we uses l2 norm and the computed local learning rate is\nclipped based on the upper bound lr_max and the lower bound lr_min:\n\nlocal_lr = min(local_lr, lr_max) and local_lr = max(local_lr, lr_min)\n\n","inputs":[{"description":"Parameter tensor","name":"X"},{"description":"Gradient tensor","name":"dX"},{"description":"Weight decay","name":"wd"},{"description":"Trust","name":"trust"},{"description":"Upper bound of learning rate","name":"lr_max"}],"outputs":[{"description":"Rescaled local learning rate","name":"lr_rescaled"}],"support_level":"default"}},{"name":"MergeMultiMapFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with map features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values.values_grad","name":"in1_values_values_grad"}],"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Tan","schema":{"description":"\nCalculates the tangent of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The tangent of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"BooleanMaskLengths","schema":{"description":"\nGiven a tensor of int32 `lengths` tensor representing segment lengths and a `mask` (boolean) tensor, return the segment lengths of the corresponding segmented tensor after **BooleanMask** is applied.\n\nIf `lengths` tensor is $[a_1, a_2, ..., a_n]$, then length of `mask` tensor must be $a_1 + a_2 + ... + a_n$.\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_mask_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanMaskLengths\",\n [\"lengths\", \"mask\"],\n [\"masked_lengths\"]\n)\n\nworkspace.FeedBlob(\"lengths\", np.array([1,3,2], dtype=np.int32))\nworkspace.FeedBlob(\"mask\", np.array([False,True,True,False,True,True]))\nprint(\"lengths:\", workspace.FetchBlob(\"lengths\"))\nprint(\"mask:\", workspace.FetchBlob(\"mask\"))\nworkspace.RunOperatorOnce(op)\nprint(\"masked_lengths:\", workspace.FetchBlob(\"masked_lengths\"))\n\n```\n\n**Result**\n\n```\n\nlengths: [1 3 2]\nmask: [False True True False True True]\nmasked_lengths: [0 2 2]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor containing segment lengths","name":"lengths"},{"description":"(*Tensor``*): A 1D bool tensor of values to keep.","name":"mask"}],"outputs":[{"description":"(*Tensor``*): 1D tensor of same type as inputs that contains the sequence","name":"masked_lengths"}],"support_level":"default"}},{"name":"Reciprocal","schema":{"description":"\nPerforms element-wise reciprocal ($\\1/x$) of input tensor $X$.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reciprocal_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Reciprocal\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[8. 3. 3.]\n [4. 0. 0.]\n [1. 2. 5.]]\nY:\n[[0.125 0.3333333 0.3333333 ]\n [0.25 inf inf ]\n [1 0.5 0.2 ]]\n\n```\n\n
    \n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"SquaredL2Distance","schema":{"description":"\nGiven two input float tensors X, Y, and produces one output float tensor\nof the L2 difference between X and Y that is computed as ||(X - Y)^2 / 2||.\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor (must have the same shape as X)","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"ArgMin","schema":{"attributes":[{"default":-1,"description":"The axis to get argmin.","name":"axis","option":"optional","type":"int64"},{"default":true,"description":"If True (default), the output tensor shape will match the input tensor shape except the `axis` dimension equals 1. Else, the `axis` dimension of the output tensor is removed.","name":"keepdims","option":"optional","type":"boolean"}],"description":"\nRetrieve the argmin of an axis dimension specified by the `axis`\nargument. Given an input tensor and two arguments (`axis` and\n`keepdims`), returns a tensor containing the indices of the smallest\nelement along the given axis. If the `keepdims` arg is *True* (default),\nthe shape of the output tensor matches the input tensor except the\n`axis` dimension equals 1. Else, the `axis` dimension of the output\ntensor is removed.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/arg_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ArgMin\",\n [\"X\"],\n [\"Indices\"],\n axis=1\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(10, size=(5,5))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\n\n```\n\n**Result**\n\n```\n\nX: [[9. 4. 6. 4. 1.]\n [5. 9. 8. 3. 4.]\n [6. 1. 0. 2. 9.]\n [7. 8. 2. 4. 9.]\n [3. 9. 4. 9. 4.]]\nIndices: [[4]\n [3]\n [2]\n [2]\n [0]]\n\n```\n\n
    \n\n ","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Tensor of indices for the smallest values.","name":"Indices"}],"support_level":"default"}},{"name":"RecurrentNetwork","schema":{"description":"\nRun the input network in a recurrent fashion. This can be used to\nimplement fairly general recurrent neural networks (RNNs).\n\nThe operator proceeds as follows.\n\n- First, initialized the states from the input recurrent states\n- For each timestep T, apply the links (that map offsets from input/output\ntensors into the inputs/outputs for the `step` network)\n- Finally, alias the recurrent states to the specified output blobs.\n\nThis is a fairly special-case meta-operator, and so the implementation\nis somewhat complex. It trades of generality (and frankly usability)\nagainst performance and control (compared to e.g. TF\ndynamic_rnn, Theano scan, etc).\n\nSee the usage examples for a flavor of how to use it.\n","support_level":"default"}},{"name":"Broadcast","schema":{"attributes":[{"description":"(int, default 0) the root to run broadcast from.","name":"root","option":"optional"}],"description":"\nDoes a broadcast operation from the root node to every other node. The tensor\non each node should have been pre-created with the same shape and data type.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be broadcasted.","name":"X"}],"outputs":[{"description":"In-place as input 1.","name":"X"}],"support_level":"default"}},{"name":"PythonDLPackGradient","schema":{"description":null,"support_level":"default"}},{"name":"SpaceToBatch","schema":{"attributes":[{"description":"(*int*): exclusive axis that divides the first and second dimension of matrix `A` (default=0)","name":"pad","option":"optional"},{"description":"(*int*): height/width of spatial blocks to be moved (default=2)","name":"block_size","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; only \"NCHW\" order is currently supported (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\nZero-pads and then rearranges (permutes) blocks of spatial data into batch. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the batch dimension. After the zero-padding is according to the `pad` argument, both height and width of the input must be divisible by the `block_size`. Only \"NCHW\" order is currently supported.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/space_batch_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SpaceToBatch\",\n [\"X\"],\n [\"Y\"],\n pad=2,\n block_size=3\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(1,3,5,5).astype(np.float32))\nprint(\"X.shape:\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape:\", workspace.FetchBlob(\"Y\").shape)\n\n```\n\n**Result**\n\n```\n\nX.shape: (1, 3, 5, 5)\nY.shape: (9, 3, 3, 3)\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor (NCHW order)","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor (NCHW order)","name":"Y"}],"support_level":"default"}},{"name":"BatchToSpace","schema":{"attributes":[{"description":"(*int*): exclusive axis that divides the first and second dimension of matrix `A` (default=0)","name":"pad","option":"optional"},{"description":"(*int*): height/width of spatial blocks to be moved (default=2)","name":"block_size","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; only \"NCHW\" order is currently supported (default=\"NCHW\")","name":"order","option":"optional"}],"description":"\nRearranges (permutes) data from batch into blocks of spatial data, followed by cropping. This is the reverse transformation of `SpaceToBatch`. More specifically, this op outputs a copy of the input tensor where values from the batch dimension are moved in spatial blocks to the height and width dimensions, followed by cropping along the height and width dimensions. Only \"NCHW\" order is currently supported.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/space_batch_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BatchToSpace\",\n [\"X\"],\n [\"Y\"],\n pad=3\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(10,3,32,32).astype(np.float32))\nprint(\"X.shape:\", workspace.FetchBlob(\"X\").shape)\nworkspace.RunOperatorOnce(op)\nprint(\"Y.shape:\", workspace.FetchBlob(\"Y\").shape)\n\n```\n\n**Result**\n\n```\n\nX.shape: (10, 3, 32, 32)\nY.shape: (2, 3, 58, 58)\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor (NCHW order)","name":"X"}],"outputs":[{"description":"(*Tensor``*): output tensor (NCHW order)","name":"Y"}],"support_level":"default"}},{"name":"Erf","schema":{"description":"\nCalculates the arcsine of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"AtomicAppend","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorBoolFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ConvRelu","schema":{"description":null,"support_level":"default"}},{"name":"StumpFuncIndex","schema":{"description":"\nSplit the elements and return the indices based on the given threshold.\n","inputs":[{"description":"tensor of float","name":"X"}],"outputs":[{"description":"tensor of int64 indices for elements below/equal threshold","name":"Index_Low"},{"description":"tensor of int64 indices for elements above threshold","name":"Index_High"}],"support_level":"default"}},{"name":"TopK","schema":{"description":"\nRetrieve the top-K elements of the last dimension. \nGiven an input tensor of shape $(a_1, a_2, ..., a_n, r)$. `k` can be passed as an integer argument or a 1D tensor containing a single integer.\nReturns up to three outputs:\n\n1. Value tensor of shape $(a_1, a_2, ..., a_n, k)$ which contains the values of the top k elements along the last dimension\n2. Index tensor of shape $(a_1, a_2, ..., a_n, k)$ which contains the indices of the top k elements (original indices from the input tensor).\n3. [OPTIONAL] Flattened index tensor of shape $(a_1 * a_2 * ... * a_n * k,)$.\n\nGiven two equivalent values, this operator uses the indices along the last dimension as a tiebreaker. That is, the element with the lower index will appear first.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/top_k.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"TopK\",\n [\"X\"],\n [\"Values\", \"Indices\", \"Flattened_indices\"],\n k=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(3,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Values:\", workspace.FetchBlob(\"Values\"))\nprint(\"Indices:\", workspace.FetchBlob(\"Indices\"))\nprint(\"Flattened_indices:\", workspace.FetchBlob(\"Flattened_indices\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[6. 7. 0.]\n [8. 7. 7.]\n [1. 5. 6.]]\n\n [[0. 6. 1.]\n [2. 8. 4.]\n [1. 2. 9.]]\n\n [[4. 3. 7.]\n [0. 1. 7.]\n [0. 1. 8.]]]\nValues:\n[[[7. 6.]\n [8. 7.]\n [6. 5.]]\n\n [[6. 1.]\n [8. 4.]\n [9. 2.]]\n\n [[7. 4.]\n [7. 1.]\n [8. 1.]]]\nIndices:\n[[[1 0]\n [0 1]\n [2 1]]\n\n [[1 2]\n [1 2]\n [2 1]]\n\n [[2 0]\n [2 1]\n [2 1]]]\nFlattened_indices: [ 1 0 3 4 8 7 10 11 13 14 17 16 20 18 23 22 26 25]\n\n```\n\n
    \n\n ","inputs":[{"description":"(*Tensor``*): input tensor of shape $(a_1, a_2, ..., a_n, r)$","name":"X"},{"description":"(*int*): number of top elements to retrieve","name":"k"}],"outputs":[{"description":"(*Tensor``*): output tensor of shape $(a_1, a_2, ..., a_n, k)$","name":"Values"},{"description":"(*Tensor``*): tensor of indices of shape $(a_1, a_2, ..., a_n, k)$; indices values refer to each element's index in the last dimension of the `X` input tensor","name":"Indices"},{"description":"(*Tensor``*): tensor of indices of shape $(a_1 * a_2 * ... * a_n * k,)$; indices values refer to each element's index in the flattened input tensor `X`","name":"Flattened_indices"}],"support_level":"default"}},{"name":"SpatialBNGradient","schema":{"description":null,"support_level":"default"}},{"name":"ThrowChildThreadException","schema":{"description":null,"support_level":"default"}},{"name":"CheckDatasetConsistency","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nChecks that the given data fields represents a consistent dataset under\nthe schema specified by the `fields` argument. Operator fails if the fields\nare not consistent. If data is consistent, each field's data can be safely\nappended to an existing dataset, keeping it consistent.\n","inputs":[{"description":"Data for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"RoIPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"CreateTextFileReader","schema":{"attributes":[{"description":"Path to the file.","name":"filename","option":"optional"},{"description":"Number of passes over the file.","name":"num_passes","option":"optional"},{"description":"List with type of each field. Type enum is found at core.DataType.","name":"field_types","option":"optional"}],"description":"Create a text file reader. Fields are delimited by .","outputs":[{"description":"Pointer to the created TextFileReaderInstance.","name":"handler"}],"support_level":"default"}},{"name":"StringSuffix","schema":{"attributes":[{"description":"Maximum size of the suffix, in bytes.","name":"length","option":"optional"}],"description":"\nComputes the element-wise string suffix of the string tensor.\nInput strings that are shorter than suffix length will be returned unchanged.\nNOTE: Prefix is computed on number of bytes, which may lead to wrong behavior\nand potentially invalid strings for variable-length encodings such as utf-8.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of std::string containing suffixes for each output.","name":"suffixes"}],"support_level":"default"}},{"name":"Expand","schema":{"description":"\n Broadcast the input tensor to a materialized new tensor using given shape.\n Broadcast rule is similar to \"numpy.array(input) * numpy.ones(shape)\":\n Dimensions are right alignment;\n Two corresponding dimensions must have the same value, or one of them\n equals to 1.\n In order to align with PyTorch's `expand`, `shape` is allowed to have entries\n equal to -1, which means to preserve the size of the corresponding dimension\n in `X` (so it's actually equivalent to equal to 1).\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): expand shape","name":"shape"}],"outputs":[{"description":"(*Tensor``*): expanded tensor","name":"Y"}],"support_level":"default"}},{"name":"Gelu","schema":{"attributes":[{"description":"If true, use y = 0.5x * (1 + tanh(sqrt(2/Pi) * (x + 0.044715x^3))).","name":"fast_gelu","option":"optional"}],"description":"\nRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = xP(X <= x) where X ~ N(0, 1),\nis applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"LpNorm","schema":{"attributes":[{"default":2,"description":"Order of the norm in p-norm.","name":"p","option":"optional","type":"int64"},{"default":false,"description":"Whether we calculate norm or averaged_norm.The Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x)","name":"average","option":"optional","type":"boolean"}],"description":"\nThis op computes the $L_p$ norm of the one dimensional input tensor $X$, and outputs a one dimensional output tensor $Y$. Here, the $L_p$ norm is calculated as\n\n$$L_p(\\mathbf{x}) = \\sum_i x_i^p$$\n\nThis op supports $p$ values of 1 or 2. If the average argument is set, the norm is calculated as Lp_averaged_norm(x) is defined as Lp_averaged_norm(x) = LpNorm(x) / size(x).\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/lpnorm_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LpNorm\",\n [\"X\"],\n [\"Y\"],\n p=2\n)\nX = np.array([5., 2.])\nprint(\"X:\\n\",X)\n\n// Feed X into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [5. 2.]\nY:\n [29.]\n\n```\n\n
    \n\n","inputs":[{"description":"1D Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 8-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8Add","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Performs element-wise binary Add (with no broadcast support).\n","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. It should be of the same size as A.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as A","name":"C"}],"support_level":"default"}},{"name":"AtanGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"GetCursorOffset","schema":{"description":"Get the current offset in the cursor.","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"}],"outputs":[{"description":"Tensor containing the offsets for the cursor.","name":"offsets"}],"support_level":"default"}},{"name":"Int8LeakyRelu","schema":{"attributes":[{"description":"Coefficient of leakage, default value is 0.01","name":"alpha","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nLeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"TanGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceL1Gradient","schema":{"description":null,"support_level":"default"}},{"name":"MergeMultiListFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with list features into many.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values.values_grad","name":"in1_values_values_grad"}],"support_level":"default"}},{"name":"Int8GivenIntTensorFill","schema":{"attributes":[{"description":"Input array of type int32","name":"values","option":"optional"},{"description":"Input tensor shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Creates quantized tensor of type int32 with scale and zero point info.\n","outputs":[{"description":"An Int8TensorCPU with scale and zero point info","name":"Tensor"}],"support_level":"default"}},{"name":"TensorProtosDBInput","schema":{"attributes":[{"description":"(int, default 0) the number of samples in a batch. The default value of 0 means that the operator will attempt to insert the entire data in a single output blob.","name":"batch_size","option":"optional"}],"description":"\nTensorProtosDBInput is a simple input operator that basically reads things\nfrom a db where each key-value pair stores an index as key, and a TensorProtos\nobject as value. These TensorProtos objects should have the same size, and they\nwill be grouped into batches of the given size. The DB Reader is provided as\ninput to the operator and it returns as many output tensors as the size of the\nTensorProtos object. Each output will simply be a tensor containing a batch of\ndata with size specified by the 'batch_size' argument containing data from the\ncorresponding index in the TensorProtos objects in the DB.\n","inputs":[{"description":"A pre-initialized DB reader. Typically, this is obtained by calling CreateDB operator with a db_name and a db_type. The resulting output blob is a DB Reader tensor","name":"data"}],"outputs":[{"description":"The output tensor in which the batches of data are returned. The number of output tensors is equal to the size of (number of TensorProto's in) the TensorProtos objects stored in the DB as values. Each output tensor will be of size specified by the 'batch_size' argument of the operator","name":"output"}],"support_level":"default"}},{"name":"RemovePadding","schema":{"attributes":[{"description":"Outer-size of padding to remove around each range.","name":"padding_width","option":"optional","type":"int64"},{"description":"[OPTIONAL] Specifies a different end-padding width. If this is not set, will use same as `padding_width`.","name":"end_padding_width","option":"optional","type":"int64"}],"description":"\nRemove padding around the edges of each segment of the input data. This is the\nreverse operation of **AddPadding**, and uses the same arguments and conventions\nfor input and output data format.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sequence_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\naddpad_op = core.CreateOperator(\n \"AddPadding\",\n [\"X\", \"lengths_add\"],\n [\"Y\", \"lengths_out_add\"],\n padding_width=1\n)\n\nrmpad_op = core.CreateOperator(\n \"RemovePadding\",\n [\"Y\", \"lengths_rm\"],\n [\"Z\", \"lengths_out_rm\"],\n padding_width=1\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(20, size=(3,5))))\nworkspace.FeedBlob(\"lengths_add\", np.array([3]).astype(np.int32))\nworkspace.FeedBlob(\"lengths_rm\", np.array([5]).astype(np.int32))\n\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(addpad_op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"lengths_out_add:\", workspace.FetchBlob(\"lengths_out_add\"))\n\nworkspace.RunOperatorOnce(rmpad_op)\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nprint(\"lengths_out_rm:\", workspace.FetchBlob(\"lengths_out_rm\"))\n```\n\n**Result**\n\n```\nX: [[17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]]\nY: [[ 0 0 0 0 0]\n [17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]\n [ 0 0 0 0 0]]\nlengths_out_add: [5]\nZ: [[17 19 1 9 1]\n [19 3 5 19 1]\n [16 0 0 0 4]]\nlengths_out_rm: [3]\n```\n\n
    \n\n","inputs":[{"description":"Input tensor ($T$).","name":"data_in"},{"description":"*(type: Tensor``)* Number of elements in each range. sum(lengths) = N. If not provided, considers all data as a single segment.","name":"lengths"}],"outputs":[{"description":"*(type: Tensor)* Padded data tensor ($T$).","name":"data_out"},{"description":"*(type: Tensor``)* [OPTIONAL] Lengths for each padded range.","name":"lengths_out"}],"support_level":"default"}},{"name":"AveragedLoss","schema":{"description":"\nThe *AveragedLoss* op takes a single 1-D input tensor *input* and returns a single output float value *output*. The output represents the average of the values in *input*. This op is commonly used for averaging losses, hence the name, however it does not exclusively operate on losses.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/loss_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/loss_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragedLoss\",\n [\"input\"],\n [\"output\"],\n)\n\nworkspace.FeedBlob(\"input\", np.array([8, 10, 12]).astype(np.float32))\nprint(\"input:\\n\", workspace.FetchBlob(\"input\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"output: \\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\ninput:\n [ 8. 10. 12.]\noutput:\n 10.0\n\n```\n\n
    \n\n\n","inputs":[{"description":"The input data as Tensor","name":"input"}],"outputs":[{"description":"The output tensor of size 1 containing the averaged value.","name":"output"}],"support_level":"default"}},{"name":"ReluGradient","schema":{"description":"\nReluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"TextFileReaderRead","schema":{"attributes":[{"description":"Maximum number of rows to read.","name":"batch_size","option":"optional"}],"description":"Read a batch of rows from the given text file reader instance. Expects the number of fields to be equal to the number of outputs. Each output is a 1D tensor containing the values for the given field for each row. When end of file is reached, returns empty tensors.","inputs":[{"description":"Pointer to an existing TextFileReaderInstance.","name":"handler"}],"support_level":"default"}},{"name":"LengthsTile","schema":{"description":"\nGiven DATA tensor of rank r >= 1, and LENGTHS tensor of rank 1, duplicate each\nentry of the outer-most dimension of DATA according to LENGTHS, and concatenate\nthem in an output tensor of rank r.\n\nExample:\n DATA = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n [6.8, 7.9],\n ]\n LENGTHS = [0, 1, 3, 2]\n OUTPUT = [\n [2.3, 3.4],\n [4.5, 5.7],\n [4.5, 5.7],\n [4.5, 5.7],\n [6.8, 7.9],\n [6.8, 7.9],\n ]\n","inputs":[{"description":"Tensor of rank r >= 1. First dimension must be equal to the size of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Tensor of rank r","name":"OUTPUT"}],"support_level":"default"}},{"name":"Int8ChannelShuffle","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":null,"support_level":"default"}},{"name":"RowWiseSparseAdam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\n Computes a modified Adam Update for the sparse case.\n Given inputs (param, moment1, moment2, indices, grad, lr, iter), runs the\n Adam update on (param, moment1[indices], moment2[indices], lr, iter) and returns\n (new_param, new_moment1, new_moment2), where moment2 is a 1D tensor\n with length equal to the number of rows in param:\n shape(moment2) == shape(param)[0]. Each element of moment2 is\n applied to an entire row of param, and the new moment2 values are\n calculated by averaging across the row.\n\n ","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"Negative","schema":{"description":"\nComputes the element-wise negative of the input.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/negative_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Negative\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3).astype(np.float32)))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[0.83296907 0.61407167 0.32562155]\n [0.59304523 0.03111175 0.29365504]\n [0.09478621 0.5424558 0.73940724]]\nY: [[-0.83296907 -0.61407167 -0.32562155]\n [-0.59304523 -0.03111175 -0.29365504]\n [-0.09478621 -0.5424558 -0.73940724]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* 1D input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* 1D output tensor.","name":"Y"}],"support_level":"default"}},{"name":"StdDevPut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an standard deviation.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"Perplexity","schema":{"description":"\nPerplexity calculates how well a probability distribution predicts a sample.\nPerplexity takes a 1-D tensor containing a batch of probabilities. Each value\nin the tensor belongs to a different sample and represents the probability of\nthe model predicting the true label for that sample. The operator returns a\nsingle (float) perplexity value for the batch.\n","inputs":[{"description":"The input data as Tensor. It contains a batch oftrue label or target probabilities","name":"probabilities"}],"outputs":[{"description":"The output- a single (float) perplexity value for the batch","name":"output"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"OneHot","schema":{"description":"\nThe *OneHot* op accepts two inputs *indices* and *index_size_tensor*, and produces a single output *one_hots*. For each index in *indices* the op creates a one-hot row in *one_hots* of length *index_size_tensor* where all entries are zero except the entry at the index is 1. The size of *one_hots* is *len(indices)* x *index_size_tensor*.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/one_hot_ops.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/one_hot_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"OneHot\",\n [\"indices\", \"index_size_tensor\"],\n [\"one_hots\"],\n)\n\nworkspace.FeedBlob(\"indices\", np.array([0,1,2,3,4]).astype(np.long))\nprint(\"indices:\\n\", workspace.FetchBlob(\"indices\"))\n\nworkspace.FeedBlob(\"index_size_tensor\", np.array([5]).astype(np.long))\nprint(\"index_size_tensor:\\n\", workspace.FetchBlob(\"index_size_tensor\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"one_hots: \\n\", workspace.FetchBlob(\"one_hots\"))\n\n```\n\n**Result**\n\n```\n\nindices:\n [0 1 2 3 4]\nindex_size_tensor:\n [5]\none_hots:\n [[1. 0. 0. 0. 0.]\n [0. 1. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 1.]]\n\n```\n\n
    \n\n","inputs":[{"description":"The active index for each example in the batch.","name":"indices"},{"description":"Scalar with the size of the index. Must be in CPU context","name":"index_size_tensor"}],"outputs":[{"description":"Matrix of size len(indices) x index_size","name":"one_hots"}],"support_level":"default"}},{"name":"MergeSingleMapFeatureTensors","schema":{"attributes":[{"description":"feature ids","name":"feature_ids","option":"optional"}],"description":"Merge given single-feature tensors with map features into one multi-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values","name":"in1_values"},{"description":".presence","name":"in1_presence"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values.lengths","name":"out_values_lengths"},{"description":".values.keys","name":"out_values_keys"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"Cbrt","schema":{"description":null,"inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor calculated as the cbrt of the input tensor, element-wise.","name":"Y"}],"support_level":"default"}},{"name":"TensorVectorSize","schema":{"description":"Get the size of the input vector","inputs":[{"description":"std::unique_ptr >","name":"tensor vector"}],"outputs":[{"description":"int32_t size","name":"size"}],"support_level":"default"}},{"name":"AbsGradient","schema":{"description":null,"support_level":"default"}},{"name":"IncrementPut","schema":{"attributes":[{"description":"(*str*): name of the stat. If not present, then uses name of input blob","name":"name","option":"optional"},{"description":"(*int64_t*): number to multiply input values by (used when inputting floats, as stats can only receive integers","name":"magnitude_expand","option":"optional"},{"description":"(*boolean*): whether or not to clamp inputs to the max inputs allowed","name":"bound","option":"optional"},{"description":"(*float*): Optionally provide a default value for receiving empty tensors","name":"default_value","option":"optional"}],"description":"\n Consume a value and pushes it to the global stat registry as an sum.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_put_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): A scalar tensor, representing any numeric value","name":"value"}],"support_level":"default"}},{"name":"MSRAFill","schema":{"description":null,"support_level":"default"}},{"name":"LC2DGradient","schema":{"description":null,"support_level":"default"}},{"name":"Accumulate","schema":{"attributes":[{"description":"(float, default 1.0) Accumulation multiplier","name":"gamma","option":"optional"}],"description":"\nAccumulate operator accumulates the input tensor to the output tensor. If the\noutput tensor already has the right size, we add to it; otherwise, we first\ninitialize the output tensor to all zeros, and then do accumulation. Any\nfurther calls to the operator, given that no one else fiddles with the output\nin the interim, will do simple accumulations.\nAccumulation is done using Axpby operation as shown:\n Y = 1*X + gamma*Y\nwhere X is the input tensor, Y is the output tensor and gamma is the multiplier\nargument.\n","inputs":[{"description":"The input tensor that has to be accumulated to the output tensor. If the output size is not the same as input size, the output tensor is first reshaped and initialized to zero, and only then, accumulation is done.","name":"input"}],"outputs":[{"description":"Accumulated output tensor","name":"output"}],"support_level":"default"}},{"name":"CheckAtomicBool","schema":{"description":"Copy the value of an atomic to a bool","inputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"}],"outputs":[{"description":"Copy of the value for the atomic","name":"value"}],"support_level":"default"}},{"name":"StatRegistryCreate","schema":{"description":"\nCreate a StatRegistry object that will contain a map of performance counters\nkeyed by name. A StatRegistry is used to gather and retrieve performance\ncounts throughout the caffe2 codebase.\n","outputs":[{"description":"A Blob pointing to the newly created StatRegistry.","name":"handle"}],"support_level":"default"}},{"name":"GT","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise greater than comparison **>** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GT\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False True False False False False]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"SumSqrElements","schema":{"attributes":[{"description":"whether to average or not","name":"average","option":"optional"}],"description":"Sums the squares elements of the input tensor.","inputs":[{"description":"Tensor to sum up","name":"X"}],"outputs":[{"description":"Scalar sum of squares","name":"sum"}],"support_level":"default"}},{"name":"WeightedSample","schema":{"description":"\nThe operator performs sampling based on the input sampling weights for\neach batch. All weights must be non-negative numbers.\nThe input is a 2-D tensor (Tensor) of size (batch_size x weights_dim).\nFor each batch, an index is randomly sampled from the distribution given by\nthe weights of the corresponding batch.\nThe output is a 1-D tensor (Tensor) of size (batch_size x 1) and\ncontains the index(es) of the sampled output.\n","inputs":[{"description":"A 2-D Tensor of size (batch_size x weights_dim).All weights must be non-negative numbers.","name":"sampling_weights"},{"description":"An optional 2-D Tensor of size (batch_size x weights_dim).Its values correspond to the sampling weights.","name":"sampling_values"}],"outputs":[{"description":"The output tensor contains index(es) sampled from distribution givenby the weight vector(s) in the input tensorThe output is a 1-D Tensor of size (batch_size x 1)","name":"sampled_indexes"},{"description":"The output tensor contains value(s) selected by the sampled index(es)It is a 1-D Tensor of size (batch_size x 1)","name":"sampled_values"}],"support_level":"default"}},{"name":"WeightedMultiSampling","schema":{"attributes":[{"description":"number of samples to sample from the input data","name":"num_samples","option":"optional"}],"description":"\nThe operator performs sampling based on the input sampling weights.\nAll weights are cummulative probability thus sorted. The output is\na 1-D tensor (Tensor). If two inputs are given, the second input\nis used to provide shape of the output sample tensor. Otherwise, we use\nargument `num_samples` to determine the number of samples to generate.\n","inputs":[{"description":"An optional 1-D Tensor.Input cumulative sampling probability (such as [0.2, 0.5, 0.8, 1.5]). All weights must be non-negative numbers. Note that the last value of CDF is not necessary 1. If the last value is not 1, all values in sampling_cdf will be scaled by this number.","name":"sampling_cdf"},{"description":"Tensor whose shape will be applied to output.","name":"shape_tensor (optional)"}],"outputs":[{"description":"The output tensor contains indices sampled from distribution givenby the weight vector in the input tensorThe output is a 1-D Tensor of size determined by argument`num_samples` or the second input tensor.","name":"sampled_indexes"}],"support_level":"default"}},{"name":"SwishGradient","schema":{"description":"\nSwishGradient takes X, Y and dY and uses this to update dX according to the\nchain rule and derivatives of the swish function.\n","support_level":"default"}},{"name":"CrossEntropyGradient","schema":{"description":null,"support_level":"default"}},{"name":"LT","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise less than comparison **<** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LT\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False False True False False True]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"Softsign","schema":{"description":"\n*Softsign* takes one input data tensor $X$ and produces one output data $Y,$ where the softsign function, $y = \\frac{x}{1+ |x|}$, is applied to $X$ elementwise. This operation can be done in an in-place fashion too, by providing the same input and output blobs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softsign_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Softsign\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[-1.3060539 0.7242748 -1.9907674 ]\n [-0.64802396 -0.03244735 0.7455406 ]\n [-0.298492 -0.5774271 2.8364444 ]]\n\nY:\n [[-0.5663588 0.420046 -0.6656376 ]\n [-0.39321268 -0.03142761 0.4271116 ]\n [-0.2298759 -0.36605626 0.739342 ]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob to be operated on.","name":"input"}],"outputs":[{"description":"Output data blob with same shape as input","name":"output"}],"support_level":"default"}},{"name":"FloatToHalf","schema":{"description":null,"support_level":"default"}},{"name":"HardSigmoid","schema":{"attributes":[{"description":"float: the slope of the function. Defaults to 0.2","name":"alpha","option":"optional"},{"description":"float: the bias value of the function. Defaults to 0.5","name":"beta","option":"optional"}],"description":"\nApplies hard sigmoid operation to the input data element-wise.\nThe HardSigmoid operation takes one input $X$, produces one output $Y$, and is defined as:\n\n$$Y = max(0,min(1,x * alpha + beta))$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/hard_sigmoid_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/hard_sigmoid_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"HardSigmoid\",\n [\"X\"],\n [\"Y\"],\n alpha = 0.2,\n beta = 0.5,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"input:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"sigmoid:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\ninput: [ 1.5744036 0.31632107 1.7842269 1.4450722 -2.1726978 ]\nhard_sigmoid: [ 0.81488073, 0.56326419, 0.85684538, 0.78901446, 0.06546044]\n\n```\n\n
    \n\n\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor with same shape as input","name":"Y"}],"support_level":"default"}},{"name":"GivenTensorStringFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"UniformIntFill","schema":{"attributes":[{"description":"(*int*): minimum value, inclusive","name":"min","option":"optional"},{"description":"(*int*): maximum value, inclusive","name":"max","option":"optional"},{"description":"(*Tuple(int)*): shape of the output, do not set when `input_as_shape`=1","name":"shape","option":"optional"},{"description":"(*int*): set to 1 to use the first input as shape; `shape` input must be in CPU context","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with int32 samples from uniform distribution [`min`, `max`].\n\n- The range can be defined either by arguments or input blobs. `min` and `max` are inclusive.\n - If the range is given by input blobs, you also need to give the shape as input.\n - When the range is given as arguments, this operator enforces min <= max. When the range is given as inputs, the constraint is not enforced.\n - When the range is given as inputs and max < min, the first dimension of the output is set to 0. This behavior is allowed so that dynamically sampling indices into a dynamically sized tensor is possible.\n- The shape of the output can be given as argument or input.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop_1 = core.CreateOperator(\n \"UniformIntFill\",\n [],\n [\"output\"],\n min=5,\n max=10,\n shape=(3,3)\n)\n\nop_2 = core.CreateOperator(\n \"UniformIntFill\",\n [\"shape\", \"min\", \"max\"],\n [\"output\"],\n input_as_shape=1\n)\n\n// Test arg-based op\nworkspace.RunOperatorOnce(op_1)\nprint(\"output (op_1):\\n\", workspace.FetchBlob(\"output\"))\n\n// Test input-based op\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"shape\", np.array([5,5]))\nworkspace.FeedBlob(\"min\", np.array(13, dtype=np.int32))\nworkspace.FeedBlob(\"max\", np.array(19, dtype=np.int32))\nworkspace.RunOperatorOnce(op_2)\nprint(\"output (op_2):\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\noutput (op_1):\n [[ 6 10 7]\n [ 5 10 6]\n [ 7 5 10]]\noutput (op_2):\n [[19 13 15 13 13]\n [14 17 14 15 15]\n [17 14 19 13 13]\n [17 18 16 13 18]\n [14 15 16 18 16]]\n\n```\n\n
    \n\n ","inputs":[{"description":"(*Tensor``*): 1-D tensor of the shape of the output, must be used with `input_as_shape` argument","name":"shape"},{"description":"(*Tensor``*): scalar tensor containing minimum value, inclusive","name":"min"},{"description":"(*Tensor``*): scalar tensor containing maximum value, inclusive","name":"max"}],"outputs":[{"description":"(*Tensor``*): filled output tensor","name":"output"}],"support_level":"default"}},{"name":"PackRecords","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nGiven a dataset under a schema specified by the `fields` argument, pack all\nthe input tensors into one, where each tensor element represents a row of data\n(batch of size 1). This format allows easier use with the rest of Caffe2\noperators.\n","outputs":[{"description":"One dimensional tensor having a complex type of SharedTensorVectorPtr. In order to reverse it back to the original input it has to be inserted into UnPackRecordsOp.","name":"tensor"}],"support_level":"default"}},{"name":"Conditional","schema":{"description":"\nGiven a 1-D tensor of boolean values, apply conditional operator along the first\ndimension of DataT and DataF and return DataO. Note, DataT and DataF must\nhave the exact same shape and type.\n","inputs":[{"description":"Boolean tensor to select DataT or DataF","name":"Condition"},{"description":"Data to use when True","name":"DataT"},{"description":"Data to use when False","name":"DataF"}],"outputs":[{"description":"Output data after applying ConditionalOp","name":"DataO"}],"support_level":"default"}},{"name":"CopyFromCPUInput","schema":{"description":"\nTake a CPU input tensor and copy it to an output in the current\nContext (GPU or CPU). This may involves cross-device MemCpy.\n","inputs":[{"description":"The input CPU tensor.","name":"input"}],"outputs":[{"description":"either a TensorCUDA or a TensorCPU","name":"output"}],"support_level":"default"}},{"name":"MaxPoolGradient","schema":{"description":null,"support_level":"default"}},{"name":"CollectAndDistributeFpnRpnProposals","schema":{"attributes":[{"description":"(int) ROI_CANONICAL_SCALE","name":"roi_canonical_scale","option":"optional"},{"description":"(int) ROI_CANONICAL_LEVEL","name":"roi_canonical_level","option":"optional"},{"description":"(int) ROI_MAX_LEVEL","name":"roi_max_level","option":"optional"},{"description":"(int) ROI_MIN_LEVEL","name":"roi_min_level","option":"optional"},{"description":"(int) RPN_MAX_LEVEL","name":"rpn_max_level","option":"optional"},{"description":"(int) RPN_MIN_LEVEL","name":"rpn_min_level","option":"optional"},{"description":"(int) RPN_POST_NMS_TOP_N","name":"rpn_post_nms_topN","option":"optional"}],"description":"\nMerge RPN proposals generated at multiple FPN levels and then\ndistribute those proposals to their appropriate FPN levels for Faster RCNN.\nAn anchor at one FPN level may predict an RoI that will map to another level,\nhence the need to redistribute the proposals.\n\nOnly inference is supported. To train, please use the original Python\noperator in Detectron.\n\nInputs and outputs are examples only; if min/max levels change,\nthe number of inputs and outputs, as well as their level numbering,\nwill change.\n","inputs":[{"description":"RPN proposals for FPN level 2, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn2"},{"description":"RPN proposals for FPN level 3, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn3"},{"description":"RPN proposals for FPN level 4, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn4"},{"description":"RPN proposals for FPN level 5, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn5"},{"description":"RPN proposals for FPN level 6, format (image_index, x1, y1, x2, y2). See rpn_rois documentation from GenerateProposals.","name":"rpn_rois_fpn6"},{"description":"RPN objectness probabilities for FPN level 2. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn2"},{"description":"RPN objectness probabilities for FPN level 3. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn3"},{"description":"RPN objectness probabilities for FPN level 4. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn4"},{"description":"RPN objectness probabilities for FPN level 5. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn5"},{"description":"RPN objectness probabilities for FPN level 6. See rpn_roi_probs documentation from GenerateProposals.","name":"rpn_roi_probs_fpn6"}],"outputs":[{"description":"Top proposals limited to rpn_post_nms_topN total, format (image_index, x1, y1, x2, y2)","name":"rois"},{"description":"RPN proposals for ROI level 2, format (image_index, x1, y1, x2, y2)","name":"rois_fpn2"},{"description":"RPN proposals for ROI level 3, format (image_index, x1, y1, x2, y2)","name":"rois_fpn3"},{"description":"RPN proposals for ROI level 4, format (image_index, x1, y1, x2, y2)","name":"rois_fpn4"},{"description":"RPN proposals for ROI level 5, format (image_index, x1, y1, x2, y2)","name":"rois_fpn5"},{"description":"Permutation on the concatenation of all rois_fpni, i=min...max, such that when applied the RPN RoIs are restored to their original order in the input blobs.","name":"rois_idx_restore"}],"support_level":"default"}},{"name":"ScatterAssign","schema":{"description":"\nUpdate slices of the tensor in-place by overriding current value.\n\nNote: The op pretty much ignores the exact shapes of the input arguments and\ncares only about sizes. It's done for performance consideration to avoid\nunnecessary reshapes. Only first dimension of X_0 is important, let's call it\nN. If M is the total size of X_0 and K is the size of INDICES then X_i is\nassumed to be of shape K x (M / N) regardless of the real shape.\n\nNote: Each update in INDICES is applied independently which means that if\nduplicated elements are present in INDICES arbitrary one will win.\n\nCurrently only works on CPU because of access to INDICES.\n","inputs":[{"description":"Tensor to be updated.","name":"DATA"},{"description":"1-D list of indices on the first dimensionof X_0 that need to be updated","name":"INDICES"},{"description":"Update slices, with shape len(INDICES) + shape(X_0)[1:]","name":"SLICES"}],"outputs":[{"description":"Has to be exactly the same tensor as the input 0","name":"DATA"}],"support_level":"default"}},{"name":"FusedRandRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the FloatToFusedRandRowwiseQuantized operator.\nRefer FloatToFusedRandRowwiseQuantized operator for details.\n","inputs":[{"description":"Fused bitwidth, tail, min, max and quantized data","name":"quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_input"}],"support_level":"default"}},{"name":"MergeSingleMapFeatureTensorsGradient","schema":{"description":"Explode given multi-feature tensors with map features into multiple single-feature tensor.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".presence","name":"in1_presence"},{"description":".values.values_grad","name":"out_values_values_grad"}],"outputs":[{"description":".values_grad","name":"in1_values_grad"}],"support_level":"default"}},{"name":"TopKGradient","schema":{"description":null,"support_level":"default"}},{"name":"SinGradient","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorIntFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Int8MaxPool","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"MaxPool \nconsumes an input blob X and applies max pooling across the\nthe blob according to kernel sizes, stride sizes, and pad lengths defined by the\nConvPoolOpBase operator. Max pooling consisting of taking the maximum value of a\nsubset of the input tensor according to the kernel size and downsampling the\ndata into the output blob Y for further processing.\n","inputs":[{"description":"Input data tensor from the previous operator; dimensions depend on whether the NCHW or NHWC operators are being used. For example, in the former, the input has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. The corresponding permutation of dimensions is used in the latter case.","name":"X"}],"outputs":[{"description":"Output data tensor from max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Output will go through rectified linear","name":"Y"}],"support_level":"default"}},{"name":"Int8Dequantize","schema":{"description":null,"inputs":[{"description":"Int8 Tensor qX.","name":"qX"}],"outputs":[{"description":"FP32 Tensor that represents mapped real value of qX.","name":"Y"}],"support_level":"default"}},{"name":"Adagrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 1. If it is in (0, 1), the gradient square sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nComputes the AdaGrad update for an input gradient and accumulated\nhistory. Concretely, given inputs (param, grad, moment, learning_rate),\ncomputes\n\n new_moment = moment + square(grad)\n effective_lr = learning_rate / (sqrt(new_moment) + epsilon)\n update = learning_rate * grad / (sqrt(new_moment) + epsilon)\n new_param = param + update\nand returns (new_param, new_moment).\n\nOptionally returns effective_lr and update as well.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"(optional) Effective learning rate","name":"output_effective_lr"},{"description":"(optional) Actual update that is applied.","name":"output_update"}],"support_level":"default"}},{"name":"ConstantFill","schema":{"attributes":[{"description":"value to populate output tensor with.","name":"value","option":"optional"},{"description":"The data type for the elements of the output tensor. Strictly must be one of the types from *DataType* enum in TensorProto.","name":"dtype","option":"optional","type":"int64"},{"description":"Shape of the output tensor. Cannot pass an input blob and this arg at the same time.","name":"shape","option":"optional"},{"description":"Additional dimensions appended at the end of the shape indicated by the input blob. Cannot set thisargument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nThis operator fills the elements of the output tensor with a constant value\nspecified by the `value` argument.\n\n- The data type is specified by the `dtype` argument\n\n- Currently, the data types supported are *float*, *int32*, *int64*, and *bool*\n\n- If the `dtype` argument is not provided, the data type of `value` is used\n\n- The output tensor shape is either specified by the `shape` argument or will\nmatch the shape of the input tensor if one is provided (if an input tensor is\nprovided, a shape argument should not be set)\n\n- Optional additional dimensions can be appended at the end as specified by\n`extra_shape` argument\n\n- If `input_as_shape` is set to True, the input should be a 1D tensor\ncontaining the desired output shape (the dimensions specified in `extra_shape`\nwill also be appended)\n\n- If a second input V is passed, fill the output with the first element of V\n\nWhen specifying `dtype` argument, use the integer keys from the *DataType* enum\nin TensorProto:\n\n```\nmessage TensorProto {\n ...\n enum DataType {\n UNDEFINED = 0;\n FLOAT = 1; // float\n INT32 = 2; // int\n BYTE = 3; // BYTE, when deserialized, is going to be restored as uint8.\n STRING = 4; // string\n BOOL = 5; // bool\n UINT8 = 6; // uint8_t\n INT8 = 7; // int8_t\n UINT16 = 8; // uint16_t\n INT16 = 9; // int16_t\n INT64 = 10; // int64_t\n FLOAT16 = 12; // at::Half\n DOUBLE = 13; // double\n }\n```\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConstantFill\",\n [],\n [\"Y\"],\n shape=(1,5,5)\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nY: [[[0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0.]]]\n```\n
    \n\n
    \n Example 2 \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ConstantFill\",\n [\"X\"],\n [\"Y\"],\n value=4.0,\n dtype=1,\n extra_shape=(1,2)\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(3,3))).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[86. 30. 84.]\n [34. 51. 9.]\n [29. 86. 59.]]\nY: [[[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]\n\n\n [[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]\n\n\n [[[4. 4.]]\n\n [[4. 4.]]\n\n [[4. 4.]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* [OPTIONAL] Input tensor to provide shape information.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* Output tensor of constant values.","name":"Y"}],"support_level":"default"}},{"name":"FloatToFused8BitRowwiseQuantized","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 8 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.\nFor N-dimensional input tensor, the first N-1 dimensions are interpreted as\nrows and the last dimension is interpreted as a column. For example, an\ninput tensor with dimension 5x2x4 is interpreted as 10 rows and 4 columns.\n)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Conv3D","schema":{"description":"\nThe convolution operator consumes an input vector, a 3D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"LSTMUnit","schema":{"attributes":[{"description":"Bias term to add in while calculating forget gate","name":"forget_bias","option":"optional"},{"description":"When false, the sequence lengths input is left out, and all following inputs are shifted left by one.","name":"sequence_lengths","option":"optional"}],"description":"\nLSTMUnit computes the activations of a standard LSTM (without peephole\nconnections), in a sequence-length aware fashion.\n\nConcretely, given the (fused) inputs X (TxNxD), the previous cell\nstate (NxD), and the sequence lengths (N), computes the LSTM\nactivations, avoiding computation if the input is invalid (as in, the\nvalue at X{t][n] >= seqLengths[n].\n\n","support_level":"default"}},{"name":"SortedSegmentWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherByKey","schema":{"description":"\nInverse operation of Partition.\n\nTakes the original, full 'keys' tensor followed by sharded value tensors,\nand returns the full value tensor, combined using the same hash used in\nPartition.\n","inputs":[{"description":"The first input is the full keys tensor (same as the first input of Partition).","name":"keys"},{"description":"Subsequented inputs are sharded values tensors.","name":"sharded_values"}],"outputs":[{"description":"Reconstructed values tensor.","name":"values"}],"support_level":"default"}},{"name":"ReduceMean","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **mean** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceMean\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[9. 0. 3. 6. 0.]\n [3. 4. 5. 0. 9.]\n [6. 9. 1. 1. 5.]\n [6. 2. 3. 7. 7.]\n [3. 1. 1. 0. 1.]]\n\n [[4. 3. 9. 8. 1.]\n [8. 2. 0. 4. 0.]\n [8. 9. 9. 0. 2.]\n [7. 2. 5. 8. 9.]\n [5. 9. 1. 9. 0.]]]]\nY:\n[[6.5 1.5 6. 7. 0.5]\n [5.5 3. 2.5 2. 4.5]\n [7. 9. 5. 0.5 3.5]\n [6.5 2. 4. 7.5 8. ]\n [4. 5. 1. 4.5 0.5]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"IntIndexCreate","schema":{"attributes":[{"description":"Max number of elements, including the zero entry.","name":"max_elements","option":"optional"}],"description":"\nCreates a dictionary that maps int32 keys to consecutive integers\nfrom 1 to max_elements. Zero is reserved for unknown keys.\n","outputs":[{"description":"Pointer to an Index instance.","name":"handler"}],"support_level":"default"}},{"name":"Div","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Div\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[18,8],[2,9]]))\nworkspace.FeedBlob(\"B\", np.array([[9,2],[3,2]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[18 8]\n [ 2 9]]\nB:\n[[9 2]\n [3 2]]\nC:\n[[2 4]\n [0 4]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"WeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"TimerBegin","schema":{"attributes":[{"description":"(*str*): name of the timer object; if not set use output name","name":"counter_name","option":"optional"}],"description":"\nStart a wallclock timer, returning a scalar tensor containing a pointer to it. The timer is stopped by calling **TimerEnd**.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","outputs":[{"description":"(*Tensor``*): pointer to a timer object","name":"timer"}],"support_level":"default"}},{"name":"UnpackSegments","schema":{"attributes":[{"description":"The pre-defined max_length for the packed segments","name":"max_length","option":"optional"}],"description":"Map N+1 dim tensor to N dim based on length blob","inputs":[{"description":"1-d int/long tensor contains the length in each of the input.","name":"lengths"},{"description":"N+1 dim Tensor.","name":"tensor"}],"outputs":[{"description":"N dim Tensor","name":"packed_tensor"}],"support_level":"default"}},{"name":"ThresholdedRelu","schema":{"attributes":[{"description":"(float) defaults to 1.0.","name":"alpha","option":"optional"}],"description":"\nThresholdedRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = x for x > alpha, y = 0\notherwise, is applied to the tensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D input tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseSortedSegmentSum","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Sum' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentSum that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Checkpoint","schema":{"attributes":[{"description":"(int, default 0) if set, use the db path directly and do not prepend the current root folder of the workspace.","name":"absolute_path","option":"optional"},{"description":"(string) a template string that one can combine with the iteration to create the final db name. For example, \"/home/lonestarr/checkpoint_%08d.db\"","name":"db","option":"optional"},{"description":"(string) the type of the db.","name":"db_type","option":"optional"},{"description":"(int, default 1) the checkpointing is carried out when (iter mod every) is zero.","name":"every","option":"optional"}],"description":"\nThe Checkpoint operator is similar to the Save operator, but allows one to save\nto db every few iterations, with a db name that is appended with the iteration\ncount. It takes [1, infinity) number of inputs and has no output. The first\ninput has to be a TensorCPU of type int and has size 1 (i.e. the iteration\ncounter). This is determined whether we need to do checkpointing.\n","support_level":"default"}},{"name":"LengthsIndicesInGradientMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"MaxPool1D","schema":{"description":"MaxPool1D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"Atan","schema":{"description":"\nCalculates the arctangent of the given input tensor, element-wise.\n","inputs":[{"description":"Input tensor","name":"input"}],"outputs":[{"description":"The arctangent of the input tensor computed element-wise","name":"output"}],"support_level":"default"}},{"name":"PythonDLPack","schema":{"description":null,"support_level":"default"}},{"name":"CTCBeamSearchDecoder","schema":{"attributes":[{"description":"Maximum number of candidates to carry over to next activation step.","name":"beam_width","option":"optional"},{"description":"Probability threshold below which outputs are ignored.","name":"prune_threshold","option":"optional"}],"description":"Prefix beam search decoder for connectionist temporal classification.","inputs":[{"description":"3D float Tensor sized [max_activation_length, batch_size, alphabet_size] of network logits (before softmax application).","name":"INPUTS"},{"description":"(optional) 1D int vector containing sequence lengths, having size [batch_size] seq_len will be set to max_time if not provided.","name":"SEQ_LEN"}],"outputs":[{"description":"Output_len matrix size (batch_size * num_candidates). Each index stores lengths of candidates for its corresponding batch item.","name":"OUTPUT_LEN"},{"description":"Values vector, size (total_decoded_outputs). The flattened vector of final output sequences, in batch order.","name":"VALUES"},{"description":"Probability vector, size (total_decoded_outputs). Each index stores final output probability of its corresponding batch item.","name":"OUTPUT_PROB"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumWithMainInputGradient","schema":{"description":null,"support_level":"default"}},{"name":"WeightedSampleDequeueBlobs","schema":{"attributes":[{"description":"Weights for sampling from multiple queues","name":"weights","option":"optional"},{"description":"The index of the blob (among the output blob list) that will be used to store the index of the table chosen to read the current batch.","name":"table_idx_blob","option":"optional"}],"description":"\nDequeue the blobs from multiple queues. When one of queues is closed and empty,\nthe output status will be set to true which can be used as exit criteria for\nexecution step.\nThe 1st input is the queue and the last output is the status. The rest are\ndata blobs.\n","support_level":"default"}},{"name":"SigmoidCrossEntropyWithLogitsGradient","schema":{"description":null,"support_level":"default"}},{"name":"Int8RoIAlign","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"(float) default 1.0; Spatial scale of the input feature map X relative to the input image. E.g., 0.0625 if X has a stride of 16 w.r.t. the input image.","name":"spatial_scale","option":"optional"},{"description":"(int) default 1; Pooled output Y's height.","name":"pooled_h","option":"optional"},{"description":"(int) default 1; Pooled output Y's width.","name":"pooled_w","option":"optional"},{"description":"(int) default -1; number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height).","name":"sampling_ratio","option":"optional"}],"description":"\nRegion of Interest (RoI) align operation as used in Mask R-CNN.\n","inputs":[{"description":"4D Int8 Tensor feature map input of shape (N, C, H, W).","name":"X"},{"description":"2D input of shape (R, 4 or 5) specifying R RoIs representing: batch index in [0, N - 1], x1, y1, x2, y2. The RoI coordinates are in the coordinate system of the input image. For inputs corresponding to a single image, batch index can be excluded to have just 4 columns.","name":"RoIs"}],"outputs":[{"description":"4D Int8 Tensor output of shape (R, C, pooled_h, pooled_w). The r-th batch element is a pooled feature map cooresponding to the r-th RoI.","name":"Y"}],"support_level":"default"}},{"name":"SortedSegmentRangeLogMeanExpGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsSum","schema":{"description":"\nApplies 'Sum' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Sum' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n\n\nThe *LengthsSum* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the sum in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [sum([2,4]), sum([3,1,2]), sum([10])] = [6,6,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsSum\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 6. 6. 10.]\n\n```\n\n
    \n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"DequeueBlobs","schema":{"attributes":[{"description":"Timeout in secs, default: no timeout","name":"timeout_secs","option":"optional"}],"description":"\n Dequeue the blobs from queue.\n ","inputs":[{"description":"The shared pointer for the BlobsQueue","name":"queue"}],"outputs":[{"description":"The blob to store the dequeued data","name":"blob"}],"support_level":"default"}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Defines alpha parameter used in calculation.","name":"alpha","option":"optional","type":"float32"}],"description":"\n\nThis op implements the exponential linear unit (ELU) activation function as described in [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)](https://arxiv.org/abs/1511.07289). The op takes an input tensor $X$ of arbitrary shape, computes the elementwise elu operation, and returns a vector $Y$ of the same shape as output. The alpha parameter may be passed as an argument, but defaults to 1. The elu operation is defined as\n\n$$y=f(x) =\\begin{cases}\\alpha(e^x-1) & x < 0 \\\\ x & otherwise\\end{cases}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elu_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Elu\",\n [\"X\"],\n [\"Y\"],\n alpha=1.1\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 0.35339102 1.1860217 -0.10710736]\n [-3.1173866 -0.1889988 -0.20330353]\n [ 1.8525308 -0.368949 0.506277 ]]\n\nY:\n [[ 0.35339102 1.1860217 -0.11172786]\n [-1.0513 -0.18943374 -0.20236646]\n [ 1.8525308 -0.33939326 0.506277 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"1D input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"1D input tensor, calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicates up to which input dimensions (exclusive) should be flattened to the outer dimension of the output.","name":"axis","option":"optional","type":"int64"}],"description":"\nFlattens the input tensor into a 2D matrix. If input tensor has shape\n$(d_0, d_1, ..., d_n)$ then the output will have shape\n$\\bigl((d_0 * d_1 * ... * d_{(axis-1)}), (d_{axis} * d_{(axis+1)} * ... * d_n)\\bigr)$.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/flatten_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Flatten\",\n [\"X\"],\n [\"Y\"],\n axis=1\n)\n\nworkspace.FeedBlob(\"X\", np.random.rand(1,3,2,2))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[[[0.53432311 0.23734561]\n [0.56481598 0.52152617]]\n\n [[0.33662627 0.32472711]\n [0.17939016 0.97175851]]\n\n [[0.87226421 0.49045439]\n [0.92470531 0.30935077]]]]\nY: [[0.53432311 0.23734561 0.56481598 0.52152617 0.33662627 0.32472711\n 0.17939016 0.97175851 0.87226421 0.49045439 0.92470531 0.30935077]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input Tensor of rank >= axis.","name":"X"}],"outputs":[{"description":"*(type: Tensor)* A 2D tensor with the contents of the input tensor, with input dimensions up to `axis` flattened to the outer dimension of the output and the remaining input dimensions flattened into the inner dimension of the output.","name":"Y"}],"support_level":"default"}},{"name":"MaxPool1DGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeLogSumExp","schema":{"description":"\nApplies 'LogSumExp' to each segment of input tensor. In order to allow for more\nefficient implementation of 'LogSumExp', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nLogSumExp computes the element-wise log of the sum of exponentials of input slices. Operation doesn't change the shape of individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"SumElementsGradient","schema":{"description":null,"support_level":"default"}},{"name":"RetrieveCount","schema":{"description":"\nRetrieve the current value from the counter as an integer.\n\n Github Links:\n - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/counter_ops.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\ncreatecounter_op = core.CreateOperator(\n \"CreateCounter\",\n [],\n [\"counter\"],\n init_count=5\n)\n\nretrievecount_op = core.CreateOperator(\n \"RetrieveCount\",\n [\"counter\"],\n [\"count\"]\n)\n\ncheckcounterdone_op = core.CreateOperator(\n \"CheckCounterDone\",\n [\"counter\"],\n [\"done\"]\n)\n\ncountup_op = core.CreateOperator(\n \"CountUp\",\n [\"counter\"],\n [\"previous_count\"],\n)\n\ncountdown_op = core.CreateOperator(\n \"CountDown\",\n [\"counter\"],\n [\"done\"],\n)\n\nresetcounter_op = core.CreateOperator(\n \"ResetCounter\",\n [\"counter\"],\n [\"previous_count\"],\n init_count=3\n)\n\n\n// Create counter\nworkspace.RunOperatorOnce(createcounter_op)\nprint(\"'counter' pointer:\", workspace.FetchBlob(\"counter\"))\n\n\n// Retrieve initial counter value\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"Initial 'count':\", workspace.FetchBlob(\"count\"))\n\n\n// Check if counter is done\nworkspace.RunOperatorOnce(checkcounterdone_op)\nprint(\"Initial 'done' value:\", workspace.FetchBlob(\"done\"))\n\n\n// Test CountUp operator\nprint(\"\\nTesting CountUp operator...\")\nfor i in range(5):\n workspace.RunOperatorOnce(countup_op)\n print(\"'previous_count' after CountUp:\", workspace.FetchBlob(\"previous_count\"))\n\nworkspace.RunOperatorOnce(retrievecount_op)\nprint(\"'count' value after CountUp test:\", workspace.FetchBlob(\"count\"))\n\n\n// Test CountDown operator\nprint(\"\\nTesting CountDown operator...\")\nfor i in range(11):\n workspace.RunOperatorOnce(countdown_op)\n workspace.RunOperatorOnce(retrievecount_op)\n print(\"'count' value after CountDown: {}\\t'done' value: {}\".format(workspace.FetchBlob(\"count\"), workspace.FetchBlob(\"done\")))\n```\n\n**Result**\n\n```\n'counter' pointer: counter, a C++ native class of type std::__1::unique_ptr, std::__1::default_delete > >.\nInitial 'count': 5\nInitial 'done' value: False\n\nTesting CountUp operator...\n'previous_count' after CountUp: 5\n'previous_count' after CountUp: 6\n'previous_count' after CountUp: 7\n'previous_count' after CountUp: 8\n'previous_count' after CountUp: 9\n'count' value after CountUp test: 10\n\nTesting CountDown operator...\n'count' value after CountDown: 9 'done' value: False\n'count' value after CountDown: 8 'done' value: False\n'count' value after CountDown: 7 'done' value: False\n'count' value after CountDown: 6 'done' value: False\n'count' value after CountDown: 5 'done' value: False\n'count' value after CountDown: 4 'done' value: False\n'count' value after CountDown: 3 'done' value: False\n'count' value after CountDown: 2 'done' value: False\n'count' value after CountDown: 1 'done' value: False\n'count' value after CountDown: 0 'done' value: False\n'count' value after CountDown: -1 'done' value: True\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* A blob pointing to an instance of a counter.","name":"counter"}],"outputs":[{"description":"*(type: int)* Current count value.","name":"count"}],"support_level":"default"}},{"name":"CopyRowsToTensorGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnsureClipped","schema":{"description":"\nGiven a tensor, apply clip after gradient is applied; when the param is sparse as\nindicated by valid indices and grad, in-place is required\n","inputs":[{"description":"Parameters to be normalized","name":"param"},{"description":"Sparse indices, only needed for sparse param","name":"indices"},{"description":"Gradient computed, only needed for sparse param","name":"grad"}],"outputs":[{"description":"param ensured to be clipped within range","name":"output_param"}],"support_level":"default"}},{"name":"WeightedSigmoidCrossEntropyWithLogits","schema":{"description":"\nGiven three matrices: logits, targets, weights, all of the same shape,\n(batch_size, num_classes), computes the weighted sigmoid cross entropy between\nlogits and targets. Specifically, at each position r,c, this computes\nweights[r, c] * crossentropy(sigmoid(logits[r, c]), targets[r, c]), and then\naverages over each row.\nReturns a tensor of shape (batch_size,) of losses for each example.\n","inputs":[{"description":"matrix of logits for each example and class.","name":"logits"},{"description":"matrix of targets, same shape as logits.","name":"targets"},{"description":"matrix of weights, same shape as logits.","name":"weights"}],"outputs":[{"description":"Vector with the total xentropy for each example.","name":"xentropy"}],"support_level":"default"}},{"name":"IndexLoad","schema":{"attributes":[{"description":"If set, skips the first entry of the tensor. This allows to load tensors that are aligned with an embedding, where the first entry corresponds to the default 0 index entry.","name":"skip_first_entry","option":"optional"}],"description":"\nLoads the index from the given 1-D tensor. Elements in the tensor will be given\nconsecutive indexes starting at 1. Fails if tensor contains repeated elements.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"},{"description":"1-D tensor with elements starting with index 1.","name":"items"}],"outputs":[{"description":"The input handle.","name":"handle"}],"support_level":"default"}},{"name":"BatchDenseToSparse","schema":{"description":"\nThis Op is a inverse of BatchSparseToDenseOp.\nBasically, given a `lengths` vector, a `indices` vector,\nand a dense matrix `dense`, output `value` vector so that, along with\n`lengths` vector and `indices` vector, forms a sparse representation\nof the dense matrix.\n\nA sparse matrix is represented by `lengths` vector, `indices` vector,\nand `values` vector. Each element in `lengths` vector (lengths[`i`]) represents\nthe number of indices in this batch (batch `i`).\nWith in each batch, `indices` should not have duplicate number.\n\nFor example, with input:\n\n lengths = [2, 3, 1]\n indices = [0, 1, 2, 3, 4, 5]\n output = [[6, 7, 0, 0, 0, 0],\n [0, 0, 8, 9, 10, 0],\n [0, 0, 0, 0, 0, 11]]\n\nThe output is:\n\n values = [6, 7, 8, 9, 10, 11]\n\nafter running this operator.\n","inputs":[{"description":"Flatten lengths, Used to break down indices into per batch indices","name":"lengths"},{"description":"Flatten indices, tensor of total size = \\sum lengths, containing the indices ","name":"indices"},{"description":"dense 2-D tensor, first dim = len(lengths), last dim > Any(indices)","name":"dense"}],"outputs":[{"description":"Values, tensor of the same size as `indices` and same data type as dense tensor.","name":"values"}],"support_level":"default"}},{"name":"UniformFill","schema":{"attributes":[{"description":"(*float*): minimum value, inclusive","name":"min","option":"optional"},{"description":"(*float*): maximum value, inclusive","name":"max","option":"optional"},{"description":"(*Tuple(int)*): shape of the output, do not set when `input_as_shape`=1","name":"shape","option":"optional"},{"description":"(*int*): set to 1 to use the first input as shape; `shape` input must be in CPU context","name":"input_as_shape","option":"optional"}],"description":"\nFill the output tensor with float samples from uniform distribution [`min`, `max`].\n\n- The range can be defined either by arguments or input blobs. `min` and `max` are inclusive.\n - If the range is given by input blobs, you also need to give the shape as input.\n - When the range is given as arguments, this operator enforces min <= max. When the range is given as inputs, the constraint is not enforced.\n - When the range is given as inputs and max < min, the first dimension of the output is set to 0. This behavior is allowed so that dynamically sampling indices into a dynamically sized tensor is possible.\n- The shape of the output can be given as argument or input.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop_1 = core.CreateOperator(\n \"UniformFill\",\n [],\n [\"output\"],\n min=5.5,\n max=10.5,\n shape=(3,3)\n)\n\nop_2 = core.CreateOperator(\n \"UniformFill\",\n [\"shape\", \"min\", \"max\"],\n [\"output\"],\n input_as_shape=1\n)\n\n// Test arg-based op\nworkspace.RunOperatorOnce(op_1)\nprint(\"output (op_1):\\n\", workspace.FetchBlob(\"output\"))\n\n// Test input-based op\nworkspace.ResetWorkspace()\nworkspace.FeedBlob(\"shape\", np.array([5,5]))\nworkspace.FeedBlob(\"min\", np.array(13.8, dtype=np.float32))\nworkspace.FeedBlob(\"max\", np.array(19.3, dtype=np.float32))\nworkspace.RunOperatorOnce(op_2)\nprint(\"output (op_2):\\n\", workspace.FetchBlob(\"output\"))\n\n```\n\n**Result**\n\n```\n\noutput (op_1):\n [[8.894862 8.225005 6.7890406]\n [9.588293 7.1072135 7.7234955]\n [8.210596 6.0202913 9.665462 ]]\noutput (op_2):\n [[18.965155 15.603871 15.038921 17.14872 18.134571]\n [18.84237 17.845276 19.214737 16.970337 15.494069]\n [18.754795 16.724329 15.311974 16.962536 18.60965 ]\n [15.186268 15.264773 18.73341 19.077969 14.237255]\n [15.917589 15.844325 16.248466 17.006554 17.502048]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): 1-D tensor of the shape of the output, must be used with `input_as_shape` argument","name":"shape"},{"description":"(*Tensor``*): scalar tensor containing minimum value, inclusive","name":"min"},{"description":"(*Tensor``*): scalar tensor containing maximum value, inclusive","name":"max"}],"outputs":[{"description":"(*Tensor``*): filled output tensor","name":"output"}],"support_level":"default"}},{"name":"ChannelStats","schema":{"description":"\nGiven an input tensor in NCHW format, computes the sum of all elements per\nchannel and the sum of all elements squared per channel. These values can be\nreduced across multiple batches and used to obtain the mean and variance across\nthe full set of batches. Using the new mean and variance as input to SpatialBN\nhas the effect of changing the batch size over which SpatialBN is applied.\n","inputs":[{"description":"The input 4-dimensional tensor of shape NCHW","name":"X"}],"outputs":[{"description":"The output 1-dimensional tensor of size C containing the sum of elements of X per channel.","name":"sum"},{"description":"The output 1-dimensional tensor of size C containing the sum of elements squared per channel.","name":"sumsq"}],"support_level":"default"}},{"name":"FCTransposed","schema":{"description":"\nSame as FC, but weight matrix is supposed to be already pretransposed.\nFCTransposed stands for calling blass with no noTrans, noTrans\n","support_level":"default"}},{"name":"SortedSegmentSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"LC2D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 2D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"RoIPool","schema":{"attributes":[{"description":"If set, run in test mode and skip computation of argmaxes (used for gradient computation). Only one output tensor is produced. (Default: false).","name":"is_test","option":"optional"},{"description":"A StorageOrder string (Default: \"NCHW\").","name":"order","option":"optional"},{"description":"The pooled output height (Default: 1).","name":"pooled_h","option":"optional"},{"description":"The pooled output width (Default: 1).","name":"pooled_w","option":"optional"},{"description":"Multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling (Default: 1.0).","name":"spatial_scale","option":"optional"}],"description":"\nCarries out ROI Pooling for Faster-RCNN.\nDepending on the mode, there are multiple output cases:\n\n Output case #1: Y, argmaxes (train mode)\n Output case #2: Y (test mode)\n","inputs":[{"description":"The input 4-D tensor of data. Only NCHW order is currently supported.","name":"X"},{"description":"RoIs (Regions of Interest) to pool over. Should be a 2-D tensor of shape (num_rois, 5) given as [[batch_id, x1, y1, x2, y2], ...].","name":"rois"}],"outputs":[{"description":"RoI pooled output 4-D tensor of shape (num_rois, channels, pooled_h, pooled_w).","name":"Y"},{"description":"Argmaxes corresponding to indices in X used for gradient computation. Only output if arg \"is_test\" is false.","name":"argmaxes"}],"support_level":"default"}},{"name":"ElementwiseLinear","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs; defaults to one because the 0th axis most likely describes the batch size.","name":"axis","option":"optional","type":"int64"}],"description":"\nThis op computes the elementwise linear combination of a batch of input vectors with a weight vector and bias vector. As input, the op takes an input tensor $X$ of shape $NxD$, a weight vector $w$ of length $D$, and a bias vector $b$ of length $D$. Here, $N$ represents the batch size and $D$ represents the length of the feature vectors. The output, $Y$, is a tensor of shape $NxD$ and is calculated as\n\n$$Y_{ij} = X_{ij}w_j + b_j \\ for \\ i\\in{N}, j\\in{D}$$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_linear_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_linear_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ElementwiseLinear\",\n [\"X\", \"w\", \"b\"],\n [\"Y\"]\n)\n\n// Create X\nX = np.array([[1,2,3,4,5],[6,8,9,16,10]])\nprint(\"X:\\n\",X)\n\n// Create w\nw = np.array([1,1/2.,1/3.,1/4.,1/5.])\nprint(\"w:\\n\",w)\n\n// Create b\nb = np.array([1.,1.,1.,1.,1.])\nprint(\"b:\\n\",b)\n\n\n// Feed X & w & b into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"w\", w.astype(np.float32))\nworkspace.FeedBlob(\"b\", b.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 1 2 3 4 5]\n [ 6 8 9 16 10]]\nw:\n [1. 0.5 0.33333333 0.25 0.2]\nb:\n [1. 1. 1. 1. 1.]\nY:\n [[2. 2. 2. 2. 2.]\n [7. 5. 4. 5. 3.]]\n\n```\n\n
    \n\n ","inputs":[{"description":"2D input tensor of size $NxD$. This input represents the input data to be operated on.","name":"X"},{"description":"1D scaling factors, or weights, of size $D$. This input contains the weights that will be multiplied by the data.","name":"w"},{"description":"1D biases of size $D$. This input contains the biases that will be added to the products of the weights and data.","name":"b"}],"outputs":[{"description":"2D output tensor of size $NxD$. Calculated as described above.","name":"Y"}],"support_level":"default"}},{"name":"LengthsSplit","schema":{"attributes":[{"description":"Number of splits for each element in LENGTHS","name":"n_split","option":"optional"}],"description":"\nGiven input vector LENGTHS, and input n_split, LengthsSplit returns\na single output vector. It \"splits\" each length into n_split values which add\nup to the original length. It will attempt to do equal splits, and if not possible,\nit orders larger values first. If the n_split is larger than the length, zero\npadding will be applied.\n\ne.g. LENGTHS = [9 4 5]\n n_split = 3\n Y = [3 3 3 2 1 1 2 2 1]\n\ne.g. LENGTHS = [2, 1, 2]\n n_split = 3\n Y = [1 1 0 1 0 0 1 1 0]\n","inputs":[{"description":"Mx1 Input tensor denoting INT32 lengths","name":"LENGTHS"},{"description":"(Optional) Number of splits for each element in LENGTHS (overrides argument)","name":"n_split"}],"outputs":[{"description":"(M*n_split)x1 Output vector denoting split lengths","name":"Y"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Sub","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Sub\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([[10,12],[4,14]]))\nworkspace.FeedBlob(\"B\", np.array([[5,16],[1,19]]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[10 12]\n [ 4 14]]\nB:\n[[ 5 16]\n [ 1 19]]\nC:\n[[ 5 -4]\n [ 3 -5]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size as A.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions and type as A.","name":"C"}],"support_level":"default"}},{"name":"Adadelta","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default 0.95, the squared gradient sum is decayed by this factor.","name":"decay","option":"optional"}],"description":"\n\nComputes the AdaDelta update (https://arxiv.org/abs/1212.5701) for an input\ngradient and accumulated history of squared gradients. Concretely, given\ninputs (param, moment, moment_delta, grad, learning_rate), computes:\n\n new_moment = moment * decay + square(grad) * (1 - decay)\n new_grad = sqrt(moment_delta + epsilon) / sqrt(new_moment + epsilon) * grad\n new_param = param + learning_rate * new_grad\n new_moment_delta = moment_delta * decay + square(new_grad) * (1 - decay)\n\nand returns (new_param, new_moment, new_moment_delta).\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Average of squared gradients","name":"moment"},{"description":"Average of squared parameter updates","name":"moment_delta"},{"description":"Gradient computed","name":"grad"},{"description":"Learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated average squared gradient","name":"output_moment"},{"description":"Updated average of squared parameter updates","name":"output_moment_delta"}],"support_level":"default"}},{"name":"If","schema":{"attributes":[{"description":"Net executed when condition is true","name":"then_net","option":"optional"},{"description":"Net executed when condition is false (optional)","name":"else_net","option":"optional"}],"description":"\n'If' control operator, first input is a scalar boolean blob that stores condition\nvalue. Accepts 'then_net' (required) and 'else_net' (optional) arguments for 'then' and\n'else' subnets respectively. Subnets are executed in the same workspace as 'If'.\n ","inputs":[{"description":"Scalar boolean condition","name":"condition"}],"support_level":"default"}},{"name":"IntegralImage","schema":{"description":"\nComputes an integral image, which contains the sum of pixel values within\nan image vertically and horizontally. This integral image can then be used\nwith other detection and tracking techniques.\n","inputs":[{"description":"Images tensor of the form (N, C, H, W)","name":"X"}],"outputs":[{"description":"Integrated image of the form (N, C, H+1, W+1)","name":"Y"}],"support_level":"default"}},{"name":"LengthsWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nApplies 'WeightedSum' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'WeightedSum' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n\n\nThe *LengthsWeightedSum* op takes three inputs *DATA*, *LENGTHS*, and *SCALARS*, and produces a single output *OUTPUT*. The op finds the weighted sum in each of the segments of *DATA*, where segments are defined by their lengths. Before calculating the sums, the input *DATA* is weighted by the contents of *SCALARS*.\nFor example, if $DATA = [2,4,3,1,2,10]$, $SCALARS = [8, 2, 1, 4, 1, 0.6]$, and $LENGTHS = [2,3,1]$, then $OUTPUT = [sum([8*2,2*4]), sum([1*3,4*1,1*2]), sum([0.6*10])] = [24,9,6]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsWeightedSum\",\n [\"DATA\", \"SCALARS\",\"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"SCALARS\", np.array([8, 2, 1, 4, 1, 0.6]).astype(np.float32))\nprint(\"SCALARS:\\n\", workspace.FetchBlob(\"SCALARS\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nSCALARS:\n [8. 2. 1. 4. 1. 0.6]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [24. 9. 6.]\n\n```\n\n
    \n\n\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"Print","schema":{"attributes":[{"description":"(bool) if 1, saves contents to the root folder of the current workspace, appending the tensor contents to a file named after the blob name. Otherwise, logs to stderr.","name":"to_file","option":"optional"},{"description":"(int, default 0) If set, prints the first `limit` elements of tensor. If 0, prints the first `k_limit_default`(1000) elements of tensor","name":"limit","option":"optional"},{"description":"(int, default 1) Print tensor every `every_n` runs","name":"every_n","option":"optional"}],"description":"Logs shape and contents of input tensor to stderr or to a file.","inputs":[{"description":"The tensor to print.","name":"tensor"}],"support_level":"default"}},{"name":"ReduceFrontMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"AsinGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseToDenseMask","schema":{"attributes":[{"description":"list(int) argument with desired ids on the 'dense' output dimension","name":"mask","option":"optional"},{"description":"bool whether to return presence mask, false by default","name":"return_presence_mask","option":"optional"}],"description":"\nConvert sparse representations to dense with given indices.\n\nTransforms a sparse representation of map represented as `indices`\nvector and `values` tensor into a compacted tensor where the first dimension\ncorresponds to each id provided in mask argument. Missing values are filled with\nthe value of `default_value`. After running this op:\n\n output[j, :] = values[i] // where mask[j] == indices[i]\n output[j, ...] = default_value // when mask[j] doesn't appear in indices\n\nIf `lengths` is provided and not empty, and extra \"batch\" dimension is prepended\nto the output.\n\n`values` and `default_value` can have additional matching dimensions, operation\nis performed on the entire subtensor in thise case.\n\nFor example, if `lengths` is supplied and `values` is 1-D vector of floats and\n`default_value` is a float scalar, the output is going to be a float matrix\nof size `len(lengths) X len(mask)`\n","inputs":[{"description":"1-D int32/int64 tensor of concatenated ids of data","name":"indices"},{"description":"Data tensor, first dimension has to match `indices`","name":"values"},{"description":"Default value for the output if the id is not present in `indices`. Must have the same type as `values` and the same shape, but without the first dimension","name":"default_value"},{"description":"Optional lengths to represent a batch of `indices` and `values`.","name":"lengths"}],"outputs":[{"description":"Output tensor of the same type as `values` of shape `[len(lengths), len(mask)] + shape(default_value)` (if `lengths` is not provided the first dimension is omitted)","name":"output"},{"description":"Bool tensor of shape `[len(lengths), len(mask)]` (if `lengths` is not provided the first dimension is omitted). True when a value for given id was present, false otherwise.","name":"presence_mask"}],"support_level":"default"}},{"name":"SparseToDenseMaskGradient","schema":{"description":"\nThe output is the gradient of the input value from SparseToDenseMask. The\ngradient for default_value has not been implemented.\n","support_level":"default"}},{"name":"LC3D","schema":{"description":"\nThe locally connected operator consumes an input vector, a 3D filter blob\nand a bias blob and computes the output. \nNote that other parameters, such as the stride and\nkernel size, or the pads' sizes in each direction are not necessary for input\nbecause they are provided by the ConvPoolOpBase operator. Various dimension\nchecks are done implicitly, and the sizes are specified in the Input docs for\nthis operator. As is expected, the filter is locally connected with a subset of\nthe image and the bias is added; this is done throughout the image data and the\noutput is computed. As a side note on the implementation layout:\nlocally_connected_op_impl.h is the templated implementation of the\nlocally_connected_op.h file, which is why they are separate files.\n","inputs":[{"description":null,"name":null},{"description":"The filter blob that will be used in the locally connected op; has size (YH * YW * M x C x kH x kW) if order == NCHW else (YH * YW * M * KH * KW * C), where YH and YW are the height and width of the output image, C is the number of channels, and kH and kW are the height and width of the kernel.","name":"filter"},{"description":"The 1D bias blob that is added through the locally connected op; has size (YH * YW * M).","name":"bias"}],"outputs":[{"description":"Output data blob that contains the result of the locally connected op.The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y"}],"support_level":"default"}},{"name":"UpsampleBilinear","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using bilinear\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input tensor","name":"X"},{"description":"1D, 2-element, Scales tensor, [height_scale, width_scale]","name":"scales"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"Append","schema":{"description":"\nAppend input `B` to the end of input `A`.\n\n- It is required that this operation run in-place, meaning that the input `A` blob must match the output blob.\n- All except the outer-most dimension must be the same between `A` and `B`.\n- Input `A` may have to be re-allocated in order for accommodate to the new size. Currently, an exponential growth ratio is used in order to ensure amortized constant time complexity.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dataset_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Append\",\n [\"A\", \"B\"],\n [\"A\"],\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(1,3,3)))\nworkspace.FeedBlob(\"B\", np.random.randint(10, size=(2,3,3)))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"A:\", workspace.FetchBlob(\"A\"))\n\n```\n\n**Result**\n\n```\n\nA:\n[[[3 8 7]\n [1 6 6]\n [5 0 6]]]\nB:\n[[[4 3 1]\n [7 9 6]\n [9 4 5]]\n\n [[7 7 4]\n [9 8 7]\n [1 6 6]]]\nA:\n[[[3 8 7]\n [1 6 6]\n [5 0 6]]\n\n [[4 3 1]\n [7 9 6]\n [9 4 5]]\n\n [[7 7 4]\n [9 8 7]\n [1 6 6]]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): base input tensor of shape $(N, d_1, d_2, ..., d_n)$","name":"A"},{"description":"(*Tensor*): second input tensor of shape $(M, d_1, d_2, ..., d_n)$ to be appended to the base","name":"B"}],"outputs":[{"description":"(*Tensor*): output tensor of shape $(N+M, d_1, d_2, ..., d_n)$","name":"A"}],"support_level":"default"}},{"name":"AtomicIter","schema":{"description":"\nSimilar to Iter, but takes a mutex as the first input to make sure that\nupdates are carried out atomically. This can be used in e.g. Hogwild sgd\nalgorithms.\n","inputs":[{"description":"The mutex used to do atomic increment.","name":"mutex"},{"description":"The iter counter as an int64_t TensorCPU.","name":"iter"}],"support_level":"default"}},{"name":"StatRegistryUpdate","schema":{"description":"\nUpdate the given StatRegistry, or the global StatRegistry,\nwith the values of counters for the given keys.\n","inputs":[{"description":"1D string tensor with the key names to update.","name":"keys"},{"description":"1D int64 tensor with the values to update.","name":"values"},{"description":"If provided, update the given StatRegistry. Otherwise, update the global singleton.","name":"handle"}],"support_level":"default"}},{"name":"EnqueueRebatchingQueue","schema":{"attributes":[{"description":"Are we enqueuing a batch or just a single element. By default we enqueue single element.","name":"enqueue_batch","option":"optional"}],"description":"\nEnqueues Tensors into the queue.\nNumber of input tensors should be equal to the number of components passed\nduring creation of the queue.\nIf the Queue is closed this operation will fail.\nIf enqueue_batch argument is set. We will split the input tensors by the\nfirst dimension to produce single queue elements.\n","inputs":[{"description":"object representing the queue","name":"queue"},{"description":"First tensor to enque. ","name":"tensor"}],"support_level":"default"}},{"name":"SparseAdam","schema":{"attributes":[{"description":"Default 0.9","name":"beta1","option":"optional"},{"description":"Default 0.999","name":"beta2","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"Default false","name":"enableRAdam","option":"optional"}],"description":"\n\n Computes the Adam Update for the sparse case.\n Given inputs (param, moment1, moment2, indices, grad, lr, iter), runs the dense\n Adam on (param, moment1[indices], momemnt2[indices], lr, iter) and returns\n (new_param, new_moment1, new_moment2) as in dense case.\n Adam can be customized as Rectified Adam (RAdam) by setting enableRAdam = true.\n\n ","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"First moment history","name":"moment_1"},{"description":"Second moment history","name":"moment_2"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"iteration number","name":"iter"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated first moment","name":"output_moment_1"},{"description":"Updated second moment","name":"output_moment_2"},{"description":"Optional Effective gradient","name":"output_grad"}],"support_level":"default"}},{"name":"NormalizePlanarYUV","schema":{"description":null,"support_level":"default"}},{"name":"EnsureCPUOutput","schema":{"description":"\nThis Op always create TensorCPU output, and may involves cross-device MemCpy.\nUnder CPU Context, this Op takes TensorCPU as input. Under the CUDA Context,\nthis Op accepts either CUDA or CPU Tensor input.\n","inputs":[{"description":"The input CUDA or CPU tensor.","name":"input"}],"outputs":[{"description":"TensorCPU that is a copy of the input.","name":"output"}],"support_level":"default"}},{"name":"FindDuplicateElements","schema":{"description":"\nThe *FindDuplicateElements* op takes a single 1-D tensor *data* as input and returns a single 1-D output tensor *indices*. The output tensor contains the indices of the duplicate elements of the input, excluding the first occurrences. If all elements of *data* are unique, *indices* will be empty.\n\nGithub Links:\n\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/find_duplicate_elements_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/find_duplicate_elements_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"FindDuplicateElements\",\n [\"data\"],\n [\"indices\"],\n)\n\nworkspace.FeedBlob(\"data\", np.array([8,2,1,1,7,8,1]).astype(np.float32))\nprint(\"data:\\n\", workspace.FetchBlob(\"data\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"indices: \\n\", workspace.FetchBlob(\"indices\"))\n\n```\n\n**Result**\n\n```\n\ndata:\n [8. 2. 1. 1. 7. 8. 1.]\nindices:\n [3 5 6]\n\n```\n\n
    \n\n\n ","inputs":[{"description":"a 1-D tensor.","name":"data"}],"outputs":[{"description":"Indices of duplicate elements in data, excluding first occurrences.","name":"indices"}],"support_level":"default"}},{"name":"BernoulliJSDGradient","schema":{"description":null,"support_level":"default"}},{"name":"Conv1D","schema":{"description":"\nThe convolution operator consumes an input vector, a 1D filter blob\nand a bias blob and computes the output. \nThe Conv2D operator computes a 2D convolution operation over an input blob $(X)$, with a filter blob $(filter)$ and a bias blob $(bias)$, and outputs a single output blob $(Y)$. Although there are several options for order, the convention is that the input $(X)$ is a blob of shape $(N,C_{in},H_{in},W_{in})$ and the output $(Y)$ is a blob of shape $(N,C_{out},H_{out},W_{out})$. Here, $N$ is the batch size, $C$ is the number of channels, $H$ is the spatial height, and $W$ is the spatial width. For example, if your input data was a batch of five, 100x120pixel RGB images, $X$ would have shape $(5,3,120,100)$.\n\nThe $filter$ input blob may contain multiple filters and has shape $(M, C_{in}, K_H, K_W)$. Here, $M$ is the number of individual filters contained in the blob, $C_{in}$ is the number of channels of each filter (by convention in 2D convolution it is the same as the number of channels in the input), $K_H$ is the spatial height of the kernel, and $K_W$ is the spatial width of the kernel. The $bias$ blob is a vector of length $M$, where there is one bias for each filter in the $filter$ blob.\n\nGiven the shape of the input blob and the filter blob, we can calculate the shape of the output blob as follows. The number of items in the batch $N$ will stay the same. The number of channels in the output will equal the number of kernels in the filter blob, so $C_{out} = M.$ With stride and pad defined below, the spatial height and width of the output ($H_{out}$ and $W_{out}$) are calculated as\n\n$$H_{out} = \\left \\lfloor{\\frac{H_{in} - K_H + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\n$$W_{out} = \\left \\lfloor{\\frac{W_{in} - K_W + 2*pad}{stride}+1}\\right \\rfloor$$\n\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Conv\",\n [\"X\", \"filter\", \"bias\"],\n [\"Y\"],\n kernel=5,\n pad=1,\n stride=2\n)\n\n// Create X: (N,C,H,W)\ndata = np.random.randn(1,1,8,8).astype(np.float32)\nprint(\"Data shape: \",data.shape)\n\n// Create W: (M,C,Kh,Kw)\nfilters = np.random.randn(3,1,5,5).astype(np.float32)\nprint(\"Filter shape: \",filters.shape)\n\n// Create b: M\nbias = np.array([1.,1.,1.]).astype(np.float32)\nprint(\"Bias shape: \",bias.shape)\n\n// Put the inputs into the workspace\nworkspace.FeedBlob(\"X\", data)\nworkspace.FeedBlob(\"filter\", filters)\nworkspace.FeedBlob(\"bias\", bias)\n\n// Run the operator\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nData shape: (1, 1, 8, 8)\nFilter shape: (3, 1, 5, 5)\nBias shape: (3,)\nY:\n [[[[ 0.6406407 0.8620521 0.56461596]\n [ -1.5042953 -0.79549205 -10.683343 ]\n [ -0.5240259 3.4538248 -3.9564204 ]]\n\n [[ 0.6876496 4.8328524 -1.9525816 ]\n [ 1.2995434 -2.3895378 7.2670045 ]\n [ 3.9929862 1.8126237 5.4699917 ]]\n\n [[ 3.55949 4.7934155 0.76086235]\n [ 3.9588015 -1.3251319 4.413117 ]\n [ -1.5296054 -1.4924102 -3.2552304 ]]]]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input data blob, of shape $(N, C_{in}, H_{in}, W_{in})$, to be convolved with the kernels in the filter blob.","name":"X"},{"description":"The filter blob, of shape $(M, C_{in}, K_H, K_W)$, containing the filters to be convolved with the data.","name":"filter"},{"description":"The bias blob, of length $M$, containing the biases for the convolution, one bias per filter.","name":"bias"}],"outputs":[{"description":"Output data blob, of shape $(N, C_{out}, H_{out}, W_{out})$, that contains the result of the convolution.","name":"Y"}],"support_level":"default"}},{"name":"LengthsPad","schema":{"attributes":[{"description":"The value to pad the data","name":"padding_value","option":"optional"},{"description":"The target length of each segment","name":"target_length","option":"optional"}],"description":"\nGiven DATA tensor of rank r >= 1, and LENGTHS tensor of rank 1, pad each\nsegment in DATA with `value`, so that each segment's length is `target_length`.\nIf will throw, if there is segment of length larger than `target_length`.\n\nExample:\n DATA = [\n [2.3, 3.4],\n [4.5, 5.7],\n [6.8, 7.9],\n ]\n LENGTHS = [0, 1, 1, 1]\n and target_length = 2, padding value = -1.0\n OUTPUT = [\n [-1.0, -1.0],\n [-1.0, -1.0],\n [2.3, 3.4],\n [-1.0, -1.0],\n [4.5, 5.7],\n [-1.0, -1.0],\n [6.8, 7.9],\n [-1.0, -1.0],\n ]\n","inputs":[{"description":"Tensor of rank r >= 1. First dimension must be equal to the size of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Padded DATA tensor","name":"OUTPUT"}],"support_level":"default"}},{"name":"ReadNextBatch","schema":{"attributes":[{"description":"Number of top-level entries to read.","name":"batch_size","option":"optional"}],"description":"\nRead the next batch of examples out of the given cursor and data blobs.\n\nInput(0) is a blob pointing to a TreeCursor, and\n[Input(1),... Input(num_fields)] a list of tensors containing the data for\neach field of the dataset.\n\nReadNextBatch is thread safe.\n","inputs":[{"description":"A blob containing a pointer to the cursor.","name":"cursor"},{"description":"First dataset field","name":"dataset_field_0"}],"outputs":[{"description":"Tensor containing the next batch for field 0.","name":"field_0"}],"support_level":"default"}},{"name":"IntegralImageGradient","schema":{"description":null,"support_level":"default"}},{"name":"Cast","schema":{"attributes":[{"description":"Data type to which the elements of the input tensor are cast. Strictly must be one of the types from *DataType* enum in TensorProto.","name":"to","option":"optional","type":"int64"}],"description":"\nCasts the elements of a given input tensor to a data type specified by the `to`\nargument and returns an output tensor of the same size in the converted type.\nThe `to` argument must be one of the data types specified in the *DataType*\nenum field in the TensorProto message (see below). If the `to` argument is not\nprovided or is not one of the enumerated types in *DataType*, Caffe2 throws an\nEnforce error.\n\nNOTE: Casting from strings is not supported, and casting to strings is only\nsupported on CPU.\n\nTensorProto *DataType* field:\n```\nmessage TensorProto {\n ...\n enum DataType {\n UNDEFINED = 0;\n FLOAT = 1; // float\n INT32 = 2; // int\n BYTE = 3; // BYTE, when deserialized, is going to be restored as uint8.\n STRING = 4; // string\n BOOL = 5; // bool\n UINT8 = 6; // uint8_t\n INT8 = 7; // int8_t\n UINT16 = 8; // uint16_t\n INT16 = 9; // int16_t\n INT64 = 10; // int64_t\n FLOAT16 = 12; // at::Half\n DOUBLE = 13; // double\n }\n```\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/cast_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Cast\",\n [\"X\"],\n [\"Y\"],\n to=2\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32)*10)\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX: [[9.436466 5.8529844 0.54932857]\n [1.1583444 2.9936118 0.22950427]\n [3.9143739 3.4040766 8.905341 ]]\nY: [[9 5 0]\n [1 2 0]\n [3 3 8]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input tensor to be cast.","name":"X"}],"outputs":[{"description":"*(type: Tensor`<'to' type>`)* Output tensor with the same shape as input with type specified by the `to` argument.","name":"Y"}],"support_level":"default"}},{"name":"Barrier","schema":{"description":"\nDoes a barrier operation among the nodes.\n","inputs":[{"description":"The common world.","name":"comm_world"}],"support_level":"default"}},{"name":"SparseToDense","schema":{"description":"\nConvert sparse representations to dense with given indices.\n\nTransforms a sparse representation of map represented as `indices`\nvector and `values` tensor into a compacted tensor where the first dimension\nis determined by the first dimension of the 3rd input if it is given or the\nmax index. Missing values are filled with zeros.\n\nThe op supports duplicated indices and performs summation over corresponding\nvalues. This behavior is useful for converting GradientSlices into dense\nrepresentation.\n\nAfter running this op:\n\n output[indices[i], :] += values[i] // sum over all indices[i] equal to the index\n output[j, ...] = 0 if j not in indices\n","inputs":[{"description":"1-D int32/int64 tensor of concatenated ids of data","name":"indices"},{"description":"Data tensor, first dimension has to match `indices`, basic numeric types are supported","name":"values"},{"description":"Optional: if provided, the first dimension of output is the first dimension of this tensor.","name":"data_to_infer_dim"}],"outputs":[{"description":"Output tensor of the same type as `values` of shape `[len(lengths), len(mask)] + shape(default_value)` (if `lengths` is not provided the first dimension is omitted)","name":"output"}],"support_level":"default"}},{"name":"Iter","schema":{"description":"\nStores a singe integer, that gets incremented on each call to Run().\nUseful for tracking the iteration count during SGD, for example.\n","support_level":"default"}},{"name":"SparseLengthsMean8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsMean operator, where DATA is\nstored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"LE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise less or equal than comparison **<=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\n\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [ True False True True True True]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"Split","schema":{"attributes":[{"description":"(*int*): axis to split on","name":"axis","option":"optional"},{"description":"Pass non-zero integer to remove the axis specified in `axis` to all input tensors.","name":"add_axis","option":"optional","type":"int64"},{"description":"(*Tuple(int)*): length of each output","name":"split","option":"optional"},{"description":"(*string*): order of dimensions of input and output blobs; either \"NCHW\" or \"NHWC\"","name":"order","option":"optional"}],"description":"\nSplit an `input` tensor into a list of tensors, along the axis specified by the `axis` dimension. The lengths of the split can be specified using argument `split` or optional second input blob to the operator. Otherwise, the tensor is split to equal sized parts.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/concat_split_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Split\",\n [\"input\"],\n [\"output_0\",\"output_1\",\"output_2\"],\n split=(3,2,4),\n axis=0\n)\n\nworkspace.FeedBlob(\"input\", np.random.randint(10, size=(9)))\nprint(\"input:\", workspace.FetchBlob(\"input\"))\nworkspace.RunOperatorOnce(op)\nprint(\"output_0:\", workspace.FetchBlob(\"output_0\"))\nprint(\"output_1:\", workspace.FetchBlob(\"output_1\"))\nprint(\"output_2:\", workspace.FetchBlob(\"output_2\"))\n\n```\n\n**Result**\n\n```\n\ninput: [2 2 6 6 6 0 5 7 4]\noutput_0: [2 2 6]\noutput_1: [6 6]\noutput_2: [0 5 7 4]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor*): tensor to split","name":"input"},{"description":"(*Tensor``*): [OPTIONAL] list of output lengths (see also arg `split`)","name":"split"}],"outputs":[{"description":"(*Tensor*): output tensor","name":"[output_0, output_1, ...]"}],"support_level":"default"}},{"name":"LengthsToWeights","schema":{"attributes":[{"description":"n of 1/pow(length,n) for normalization","name":"power","option":"optional"}],"description":"\nSimilar as LengthsToSegmentIds but output vector of segment\nweights derived by lengths. i.e 1/pow(length, power)\n","inputs":[{"description":"1-D int32_t or int64_t tensor of lengths","name":"lengths"}],"outputs":[{"description":"1-D float tensor of weights by length","name":"a vector of weights"}],"support_level":"default"}},{"name":"CreateAtomicBool","schema":{"description":"Create an unique_ptr blob to hold an atomic","outputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"}],"support_level":"default"}},{"name":"RsqrtGradient","schema":{"description":null,"support_level":"default"}},{"name":"GatherRanges","schema":{"description":"\nGiven DATA tensor of rank 1, and RANGES tensor of rank 3, gather\ncorresponding ranges into a 1-D tensor OUTPUT.\n\nRANGES dimentions description:\n1: represents list of examples within a batch\n2: represents list features\n3: two values which are start and length or a range (to be applied on DATA)\n\nAnother output LENGTHS represents each example length within OUTPUT\n\nExample:\n DATA = [1, 2, 3, 4, 5, 6]\n RANGES = [\n [\n [0, 1],\n [2, 2],\n ],\n [\n [4, 1],\n [5, 1],\n ]\n ]\n OUTPUT = [1, 3, 4, 5, 6]\n LENGTHS = [3, 2]\n","inputs":[{"description":"Tensor of rank 1.","name":"DATA"},{"description":"Tensor of int32/int64 ranges, of dims (N, M, 2). Where N is number of examples and M is a size of each example. Last dimension represents a range in the format (start, lengths)","name":"RANGES"}],"outputs":[{"description":"1-D tensor of size sum of range lengths","name":"OUTPUT"},{"description":"1-D tensor of size N with lengths over gathered data for each row in a batch. sum(LENGTHS) == OUTPUT.size()","name":"LENGTHS"}],"support_level":"default"}},{"name":"CrossEntropy","schema":{"description":"\nThis operator computes the cross entropy between a $NxD$ dimensional input data tensor $X$ and a $NxD$ dimensional input label tensor $label$. The op produces a single length $N$ output tensor $Y$. Here, $N$ is considered the batch size and $D$ is the size of each element in the batch. In practice, it is most commonly used at the end of models as a part of the loss computation, after the SoftMax operator and before the AveragedLoss operator. The cross entropy operation is defined as follows\n\n$$Y_i = \\sum_j (label_{ij} * log(X_{ij}))$$\n\nwhere ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"CrossEntropy\",\n [\"X\", \"label\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([[.01, .05, .02, .02, .9],[.03, .1, .42, .05, .4]])\nprint(\"X:\\n\",X)\n\n// Create label: Sample 1-hot ground truth label vectors\nlabel = np.array([[0.,0.,0.,0.,1.],[0.,0.,1.,0.,0.]])\nprint(\"label:\\n\",label)\n\n// Feed X & label into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"label\", label.astype(np.float32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[0.01 0.05 0.02 0.02 0.9 ]\n [0.03 0.1 0.42 0.05 0.4 ]]\nlabel:\n [[0. 0. 0. 0. 1.]\n [0. 0. 1. 0. 0.]]\nY:\n [0.10536055 0.8675006 ]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input tensor which is almost always the result of a softmax operation. $X$ is a 2D array of size $NxD$, where $N$ is the batch size and $D$ is the number of classes.","name":"X"},{"description":"Blob containing the labels used to compare the input. $label$ is the same shape as $X$.","name":"label"}],"outputs":[{"description":"Output blob from the cross entropy computation. $Y$ is 1D length $N$ tensor.","name":"Y"}],"support_level":"default"}},{"name":"ReduceBackMaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReduceBackMean","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **mean**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the mean operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [mean(1,5), mean(4,1,8), mean(2)] = [3, 4.333, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_mean_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackMean\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[5. 9. 0.]\n [8. 4. 0.]\n [2. 2. 4.]]\n\n [[9. 0. 9.]\n [7. 9. 7.]\n [1. 0. 2.]]]]\nY: [[3.7777777 4.888889 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ResizeNearest","schema":{"attributes":[{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\n","inputs":[{"description":"Input tensor","name":"X"},{"description":"1D, 2-element, Scales tensor, [height_scale, width_scale]","name":"scales"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"SparseDropoutWithReplacement","schema":{"attributes":[{"default":0,"description":"Probability of an element to be replaced.","name":"ratio","option":"optional","type":"float32"},{"default":0,"description":"Value elements are replaced with.","name":"replacement_value","option":"optional","type":"int64"}],"description":"\n\n`SparseDropoutWithReplacement` takes a 1-d input tensor and a lengths tensor.\nValues in the Lengths tensor represent how many input elements consitute each\nexample in a given batch. The set of input values for an example will be\nreplaced with the single dropout value with probability given by the `ratio`\nargument.\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SparseDropoutWithReplacement\",\n [\"X\", \"Lengths\"],\n [\"Y\", \"OutputLengths\"],\n ratio=0.5,\n replacement_value=-1\n)\n\nworkspace.FeedBlob(\"X\", np.array([1, 2, 3, 4, 5]).astype(np.int64))\nworkspace.FeedBlob(\"Lengths\", np.array([2, 3]).astype(np.int32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Lengths:\", workspace.FetchBlob(\"Lengths\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"OutputLengths:\", workspace.FetchBlob(\"OutputLengths\"))\n```\n\n**Result**\n\n```\nX: [1, 2, 3, 4, 5]\nLengths: [2, 3]\nY: [1, 2, -1]\nOutputLengths: [2, 1]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor.","name":"X"},{"description":"*(type: Tensor``)* Lengths tensor for input.","name":"Lengths"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"},{"description":"*(type: Tensor``)* Output tensor.","name":"OutputLengths"}],"support_level":"default"}},{"name":"SparseWngrad","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nThis operator implement the optimization algorithm\nin https://arxiv.org/abs/1803.02865 by Wu, Ward and Bottou.\nGiven inputs (param, seq_b, indices, grad, lr), runs the dense WnGrad\nupdate on (param, grad, seq_b, lr), and returns (new_param,\nnew_seq_b) as in the dense case.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"seq_b history","name":"seq_b"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated seq_b","name":"output_seq_b"}],"support_level":"default"}},{"name":"Find","schema":{"attributes":[{"description":"Placeholder for items that are not found","name":"missing_value","option":"optional"}],"description":"\nFinds elements of second input from first input,\noutputting the last (max) index for each query.\nIf query not find, inserts missing_value.\nSee IndexGet() for a version that modifies the index when\nvalues are not found.\n","inputs":[{"description":"Index (integers)","name":"index"},{"description":"Needles / query","name":"query"}],"outputs":[{"description":"Indices of the needles in index or 'missing value'","name":"query_indices"}],"support_level":"default"}},{"name":"BatchBucketOneHot","schema":{"description":"\nInput is a matrix tensor. Its first dimension is the batch\nsize. For each column, bucketize it based on the boundary values and then do\none hot encoding. The `lengths` specifies the number of boundary values for each\ncolumn. The final number of buckets is this number plus 1. This would also be\nthe expanded feature size. `boundaries` specifies all the boundary values.\nNote that each bucket is right-inclusive. That is, given boundary values\n[b1, b2, b3], the buckets are defined as (-int, b1], (b1, b2], (b2, b3], (b3, inf).\nFor example\n\n data = [[2, 3], [4, 1], [2, 5]], lengths = [2, 3],\n If boundaries = [0.1, 2.5, 1, 3.1, 4.5], then\n output = [[0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 1]]\n\n If boundaries = [0.1, 2.5, 1, 1, 3.1], then\n output = [[0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1]]\n\n","inputs":[{"description":"input tensor matrix","name":"data"},{"description":"the size is the same as the width of the `data`","name":"lengths"},{"description":"bucket boundaries","name":"boundaries"}],"outputs":[{"description":"output matrix that expands each input column with one hot encodingbased on the bucketization","name":"output"}],"support_level":"default"}},{"name":"PairWiseLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"ExpandGradient","schema":{"description":null,"support_level":"default"}},{"name":"BatchGather","schema":{"description":"\nBatch gather operation, first dimension in DATA is the batch size.\nGiven DATA tensor of rank r >= 2, and INDICES tensor of rank q >= 1, gather\nentries of the second outer dimension (axis == 1) of DATA indexed by INDICES,\nand concatenate them in an output tensor of rank q + (r - 1).\n\nExample:\n DATA = [\n [1.0, 1.2, 2.4, 4.5],\n [2.3, 3.4, 3.6, 2.3],\n [4.5, 5.7, 1.2, 4.5],\n ]\n INDICES = [0, 2]\n\n OUTPUT = [\n [1.0, 2.4],\n [2.3, 3.6],\n [4.5, 1.2],\n ]\n","inputs":[{"description":"Tensor of rank r >= 2.","name":"DATA"},{"description":"Tensor of int32/int64 indices, of any rank q.","name":"INDICES"}],"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"OUTPUT"}],"support_level":"default"}},{"name":"Float16ConstantFill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","option":"optional"},{"description":"The shape of the output tensor.","name":"shape","option":"optional"}],"description":null,"outputs":[{"description":"Output tensor of constant values specified by 'value'","name":"output"}],"support_level":"default"}},{"name":"SparseSortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentWeightedSum that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"DequeueRebatchingQueue","schema":{"attributes":[{"description":"Number of elements to dequeue. By default we dequeue one element.","name":"num_elements","option":"optional"}],"description":"\nDequeue Tensors from the Queue.\nIf the Queue is closed this might return less elements than asked.\nIf num_elements > 1 the returned elements will be concatenated into one\ntensor per component.\n","inputs":[{"description":"object representing the queue","name":"rebatching_queue"},{"description":"First tensor to enqueue","name":"tensor"}],"support_level":"default"}},{"name":"StoreGet","schema":{"attributes":[{"description":"alternative key for the blob (optional)","name":"blob_name","option":"optional"}],"description":"\nGet a blob from a store. The key is the output blob's name. The key\ncan be overridden by specifying the 'blob_name' argument.\n","inputs":[{"description":"unique_ptr","name":"handler"}],"outputs":[{"description":"data blob","name":"data"}],"support_level":"default"}},{"name":"MergeMultiScalarFeatureTensors","schema":{"description":"Merge given multi-feature tensors with scalar features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values","name":"in1_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values","name":"out_values"}],"support_level":"default"}},{"name":"ReluNGradient","schema":{"attributes":[{"description":"the cap of forward op output","name":"n","option":"optional"}],"description":"\nReluGradient takes both Y and dY and uses this to update dX according to the\nchain rule and derivatives of the rectified linear function.\n","support_level":"default"}},{"name":"PadImageGradient","schema":{"description":null,"support_level":"default"}},{"name":"Assert","schema":{"attributes":[{"description":"(*string*): custom error message to be thrown when the input does not pass assertion","name":"error_msg","option":"optional"}],"description":"\nTakes in a tensor of type *bool*, *int*, *long*, or *long long* and checks if all values are True when coerced into a boolean. In other words, for non-bool types this asserts that all values in the tensor are non-zero. If a value is False after coerced into a boolean, the operator throws an error. Else, if all values are True, nothing is returned. For tracability, a custom error message can be set using the `error_msg` argument.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/assert_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Assert\",\n [\"A\"],\n [],\n error_msg=\"Failed assertion from Assert operator\"\n)\n\nworkspace.FeedBlob(\"A\", np.random.randint(10, size=(3,3)).astype(np.int32))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\ntry:\n workspace.RunOperatorOnce(op)\nexcept RuntimeError:\n print(\"Assertion Failed!\")\nelse:\n print(\"Assertion Passed!\")\n\n```\n\n**Result**\n\n```\n\nA:\n[[7 5 6]\n [1 2 4]\n [5 3 7]]\nAssertion Passed!\n\n```\n\n
    \n\n ","inputs":[{"description":"(*Tensor*): input tensor","name":"X"}],"support_level":"default"}},{"name":"Reduce","schema":{"attributes":[{"description":"(int, default 0) the root to run reduce into.","name":"root","option":"optional"}],"description":"\nDoes a reduce operation from every node to the root node. Currently only\nSum is supported.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be reduced.","name":"X"}],"outputs":[{"description":"The reduced result on root, not set for other nodes.","name":"Y"}],"support_level":"default"}},{"name":"TimerGet","schema":{"description":"\nQueries the current time of a timer object in nanoseconds.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/stats_ops.cc\n\n ","inputs":[{"description":"(*Tensor``*): pointer to a timer object; obtained from **TimerBegin** op","name":"timer"}],"outputs":[{"description":"(*Tensor``*): scalar containing time in nanoseconds","name":"nanos"}],"support_level":"default"}},{"name":"Int8GivenTensorFill","schema":{"attributes":[{"description":"Input array of type char(byte)","name":"values","option":"optional"},{"description":"Input tensor shape","name":"shape","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\n Creates quantized tensor of type char(byte) with scale and zero point info.\n","outputs":[{"description":"An Int8TensorCPU with scale and zero point info","name":"Tensor"}],"support_level":"default"}},{"name":"LengthsIndicesInGradientSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"DotProductWithPadding","schema":{"attributes":[{"description":"the padding value for tensors with smaller dimension","name":"pad_value","option":"optional"},{"description":"whether to replicate the smaller tensor or not","name":"replicate","option":"optional"}],"description":"\nGiven two input float tensors X, Y with different shapes and produces one\noutput float tensor of the dot product between X and Y. We currently support\ntwo kinds of strategies to achieve this. Before doing normal dot_product 1)\npad the smaller tensor (using pad_value) to the same shape as the other one.\n2) replicate the smaller tensor to the same shape as the other one. Note the\nfirst dimension of X, Y must be equal. Only the second dimension of X or Y\ncan be padded.\n","inputs":[{"description":"1D or 2D input tensor","name":"X"},{"description":"1D or 2D input tensor","name":"Y"}],"outputs":[{"description":"1D output tensor","name":"Z"}],"support_level":"default"}},{"name":"MakeTwoClassGradient","schema":{"description":null,"support_level":"default"}},{"name":"HardSigmoidGradient","schema":{"description":"\nHardSigmoidGradient takes both Y and dY as well as an argument alpha and uses\nthis to update dX according to the chain rule and derivatives of the hard\nsigmoid function.\n","support_level":"default"}},{"name":"IndexFreeze","schema":{"description":"\nFreezes the given index, disallowing creation of new index entries.\nShould not be called concurrently with IndexGet.\n","inputs":[{"description":"Pointer to an Index instance.","name":"handle"}],"outputs":[{"description":"The input handle.","name":"handle"}],"support_level":"default"}},{"name":"Scale","schema":{"attributes":[{"description":"(float, default 1.0) the scale to apply.","name":"scale","option":"optional"}],"description":"\nScale takes one input data (Tensor) and produces one output data\n(Tensor) whose value is the input data tensor scaled element-wise.\n","support_level":"default"}},{"name":"APMeter","schema":{"attributes":[{"description":"(int32_t) indicates how many predictions should the op buffer. defaults to 1000","name":"buffer_size","option":"optional"}],"description":"\nAPMeter computes Average Precision for binary or multi-class classification.\nIt takes two inputs: prediction scores P of size (n_samples x n_classes), and\ntrue labels Y of size (n_samples x n_classes). It returns a single float number\nper class for the average precision of that class.\n","inputs":[{"description":"2-D tensor (Tensor) of size (num_samples xnum_classes) containing prediction scores","name":"predictions"},{"description":"2-D tensor (Tensor) of size (num_samples) containing true labels for each sample","name":"labels"}],"outputs":[{"description":"1-D tensor (Tensor) of size num_classes containing average precision for each class","name":"AP"}],"support_level":"default"}},{"name":"Rowwise8BitQuantizedToFloat","schema":{"description":"\nGiven uint8 tensor, quantized using 8bit row-wise\nquantization, and auxiliary scales and biases, this operator\nrestores float tensor in the following way. We take input 8bits tensor\nof size (m_1, m_2, ..., m_n), n >= 2, reshape it into matrix of size\n(m_1, m_2 x... x m_n). We compute element r_{ij} of output matrix as\nr_{ij} * s_i + b_i and after this we reshape this output matrix into\noutput tensor of size (m_1, m_2, ..., m_n).\n","inputs":[{"description":"quantized_input","name":"quantized_input"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":null,"name":null},{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Mod","schema":{"attributes":[{"default":0,"description":"Divisor of the modulo operation (must be >= 1).","name":"divisor","option":"optional","type":"int64"},{"default":false,"description":"If true, sign of output matches divisor, else if false, sign follows dividend.","name":"sign_follow_divisor","option":"optional","type":"boolean"}],"description":"\nElement-wise modulo operation. Each element in the output is the modulo result\nof the corresponding element in the input data. The divisor of the modulo is\nprovided by the `divisor` argument.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/mod_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Mod\",\n [\"X\"],\n [\"Y\"],\n divisor=10\n)\n\nworkspace.FeedBlob(\"X\", (np.random.randint(100, size=(5,5))))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[56 22 43 13 60]\n [ 4 55 58 10 45]\n [64 66 4 3 66]\n [10 36 47 52 78]\n [91 4 36 47 95]]\nX after running op:\n[[6 2 3 3 0]\n [4 5 8 0 5]\n [4 6 4 3 6]\n [0 6 7 2 8]\n [1 4 6 7 5]]\n\n ```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor with int32 or int64 data.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor of data with modulo operation applied.","name":"Y"}],"support_level":"default"}},{"name":"StringPrefix","schema":{"attributes":[{"description":"Maximum size of the prefix, in bytes.","name":"length","option":"optional"}],"description":"\nComputes the element-wise string prefix of the string tensor.\nInput strings that are shorter than prefix length will be returned unchanged.\nNOTE: Prefix is computed on number of bytes, which may lead to wrong behavior\nand potentially invalid strings for variable-length encodings such as utf-8.\n","inputs":[{"description":"Tensor of std::string.","name":"strings"}],"outputs":[{"description":"Tensor of std::string containing prefixes for each input.","name":"prefixes"}],"support_level":"default"}},{"name":"SparseLengthsSumFused8BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n8-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 4-byte scale and 4-byte bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused8BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FileStoreHandlerCreate","schema":{"attributes":[{"description":"base path used by the FileStoreHandler","name":"path","option":"optional"},{"description":"prefix for all keys used by this store","name":"prefix","option":"optional"}],"description":"\nCreates a unique_ptr that uses the filesystem as backing\nstore (typically a filesystem shared between many nodes, such as NFS).\nThis store handler is not built to be fast. Its recommended use is for\nintegration tests and prototypes where extra dependencies are\ncumbersome. Use an ephemeral path to ensure multiple processes or runs\ndon't interfere.\n","outputs":[{"description":"unique_ptr","name":"handler"}],"support_level":"default"}},{"name":"AtomicFetchAdd","schema":{"description":"\nGiven a mutex and two int32 scalar tensors, performs an atomic fetch add\nby mutating the first argument and adding it to the second input\nargument. Returns the updated integer and the value prior to the update.\n","inputs":[{"description":"Blob containing to a unique_ptr","name":"mutex_ptr"},{"description":"Value to be mutated after the sum.","name":"mut_value"},{"description":"Value to add to the first operand.","name":"increment"}],"outputs":[{"description":"Mutated value after sum. Usually same as input 1.","name":"mut_value"},{"description":"Value of the first operand before sum.","name":"fetched_value"}],"support_level":"default"}},{"name":"Tanh","schema":{"description":"\nCalculates the hyperbolic tangent of the given input tensor element-wise. This\noperation can be done in an in-place fashion too, by providing the same input\nand output blobs.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/tanh_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Tanh\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 2.032603 -2.3556721 -0.14955314]\n [ 0.39309832 -1.1020128 -0.92951244]\n [-0.62815386 0.21342885 1.4002231 ]]\n\nX:\n [[ 0.9662601 -0.982175 -0.14844811]\n [ 0.3740282 -0.8012209 -0.73036647]\n [-0.55677974 0.21024609 0.8853999 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"1-D input tensor","name":"input"}],"outputs":[{"description":"The hyperbolic tangent values of the input tensor, computed element-wise","name":"output"}],"support_level":"default"}},{"name":"Python","schema":{"description":null,"support_level":"default"}},{"name":"QuantDecodeGradient","schema":{"description":null,"support_level":"default"}},{"name":"PythonGradient","schema":{"description":null,"support_level":"default"}},{"name":"LengthsWeightedSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of dimensions of *data* to squeeze out.","name":"dims","option":"optional","type":"int64[]"}],"category":"Transform","description":"\nThe *Squeeze* op removes single-dimensional entries from the shape of the input tensor *data,* and produces a single output tensor *squeezed*. The op also takes an argument *dims* with a list of dimensions to squeeze. If the same blob is provided as input and output, the operation is copy-free. This is the exact inverse operation of *ExpandDims* given the same *dims* argument.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/expand_squeeze_dims_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Squeeze\",\n [\"data\"],\n [\"squeezed\"],\n dims=[0,1],\n)\n\nworkspace.FeedBlob(\"data\", np.zeros((1,1,100,100)).astype(np.float32))\nprint(\"data.shape:\", workspace.FetchBlob(\"data\").shape)\n\nworkspace.RunOperatorOnce(op)\nprint(\"squeezed.shape:\", workspace.FetchBlob(\"squeezed\").shape)\n\n```\n\n**Result**\n\n```\n\ndata.shape: (1, 1, 100, 100)\nsqueezed.shape: (100, 100)\n\n```\n\n
    \n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"data"}],"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed"}],"support_level":"default"}},{"name":"NE","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise not equal to comparison **!=** (with limited broadcast support).\n\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"NE\",\n [\"A\", \"B\"],\n [\"C\"],\n)\n\nworkspace.FeedBlob(\"A\", np.array([1, 5, 2, 9, 12, 3]))\nworkspace.FeedBlob(\"B\", np.array([1, 3, 4, 9, 12, 8]))\nprint(\"A:\", workspace.FetchBlob(\"A\"))\nprint(\"B:\", workspace.FetchBlob(\"B\"))\nworkspace.RunOperatorOnce(op)\nprint(\"C:\", workspace.FetchBlob(\"C\"))\n\n```\n\n**Result**\n\n```\nA: [ 1 5 2 9 12 3]\nB: [ 1 3 4 9 12 8]\nC: [False True True False False True]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* First operand, should share the type with the second operand.","name":"A"},{"description":"*(type: Tensor``)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as `A`.","name":"C"}],"support_level":"default"}},{"name":"ReduceSum","schema":{"attributes":[{"description":"(*Tuple(int)*): list of axes to reduce","name":"axes","option":"optional"},{"description":"(*int*): set to 1 to keep the reduced dimension(s) (default=1), else set to 0 to not keep the reduced dimension(s)","name":"keepdims","option":"optional"}],"description":"\nComputes the **sum** of the input tensor's elements along the provided `axes`. The resulting tensor has the same rank as the input if the `keepdims` argument equals 1 (default). If `keepdims` is set to 0, then the `axes` dimensions are pruned.\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceSum\",\n [\"X\"],\n [\"Y\"],\n axes=(0,1),\n keepdims=0\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,5,5)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[5. 3. 7. 9. 5.]\n [4. 5. 1. 8. 3.]\n [1. 0. 9. 7. 6.]\n [7. 5. 0. 3. 1.]\n [6. 4. 4. 8. 3.]]\n\n [[8. 9. 6. 7. 7.]\n [5. 5. 4. 7. 0.]\n [9. 7. 6. 6. 7.]\n [7. 5. 2. 4. 2.]\n [4. 5. 1. 9. 4.]]]]\nY:\n[[13. 12. 13. 16. 12.]\n [ 9. 10. 5. 15. 3.]\n [10. 7. 15. 13. 13.]\n [14. 10. 2. 7. 3.]\n [10. 9. 5. 17. 7.]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"PackSegments","schema":{"attributes":[{"description":"The pre-defined max_length for the packed segments","name":"max_length","option":"optional"},{"description":"Padding number in the packed segments. Use true to pad -infinity, otherwise pad zeros","name":"pad_minf","option":"optional"},{"description":"bool whether to return presence mask, false by default","name":"return_presence_mask","option":"optional"}],"description":"Map N dim tensor to N+1 dim based on length blob. Sequences that are shorter than the longest sequence are padded with zeros.","inputs":[{"description":"1-d int/long tensor contains the length in each of the output.","name":"lengths"},{"description":"N dim Tensor.","name":"tensor"}],"outputs":[{"description":"N + 1 dim Tensorwhere dim(1) is the max length, dim(0) is the batch size.","name":"packed_tensor"},{"description":"2 dim boolean tensor, false where packed_tensor is padded, true otherwise.","name":"presence_mask"}],"support_level":"default"}},{"name":"UnPackRecords","schema":{"attributes":[{"description":"List of strings representing the string names in the formatspecified in the doc for CreateTreeCursor.","name":"fields","option":"optional"}],"description":"\nGiven a packed dataset (packed by the PackRecordsOp) and the `fields` argument\ndescribing the datasets schema, return the original dataset format. Number of\nreturned tensors is equal to the number of fields in the `fields` argument.\n\nThe first input is the packed tensor to be unpacked. Optionally, you can provide\nprototype tensors to give the expected shapes of the output tensors. This is\nhelpful when you expected to unpack empty tensor, e.g., output of a sampling\nprocess.\n","inputs":[{"description":"The tensor to be unpacked","name":"packed_tensor"}],"support_level":"default"}},{"name":"Normalize","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":"\nGiven a matrix, apply L2-normalization along the specified dimension.\n","support_level":"default"}},{"name":"LengthsMax","schema":{"description":"\nApplies 'Max' to each segment of the input tensor. Segments are defined\nby their *LENGTHS*. *LENGTHS* is a vector that maps each of the slices of\n*DATA* to a particular segment. Values belonging to the same segment are\naggregated together and considered for the 'Max' operation.\n\nFor example *LENGTHS = [2, 1]* stands for segments *DATA[0..1]* and *DATA[2]*\n\nThe sum of elements in *LENGTHS* must equal the number of elements in the first\ndimension of *DATA*. The length of *OUTPUT* is equal to the number of input\nsegments, i.e. len(*LENGTHS*).\n\nMax computes the element-wise max of the input slices. Operation doesn't change the shape of the individual blocks.\n\n\nThe *LengthsMax* op takes two inputs *DATA* and *LENGTHS*, and produces a single output *OUTPUT*. The op finds the maximum value in each of the segments of *DATA*, where segments are defined by their lengths.\nFor example, if $DATA = [2,4,3,1,2,10]$ and $LENGTHS = [2,3,1]$ then $OUTPUT = [max([2,4]), max([3,1,2]), max([10])] = [4,3,10]$.\n\nGithub Link:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/segment_reduction_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LengthsMax\",\n [\"DATA\", \"LENGTHS\"],\n [\"OUTPUT\"],\n)\n\nworkspace.FeedBlob(\"DATA\", np.array([2,4,3,1,2,10]).astype(np.float32))\nprint(\"DATA:\\n\", workspace.FetchBlob(\"DATA\"))\n\nworkspace.FeedBlob(\"LENGTHS\", np.array([2,3,1]).astype(np.int32))\nprint(\"LENGTHS:\\n\", workspace.FetchBlob(\"LENGTHS\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"OUTPUT: \\n\", workspace.FetchBlob(\"OUTPUT\"))\n\n```\n\n**Result**\n\n```\n\nDATA:\n [ 2. 4. 3. 1. 2. 10.]\nLENGTHS:\n [2 3 1]\nOUTPUT:\n [ 4. 3. 10.]\n\n```\n\n
    \n\n\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of len(LENGTHS) ","name":"OUTPUT"}],"support_level":"default"}},{"name":"L1DistanceGradient","schema":{"description":null,"support_level":"default"}},{"name":"MomentumSGD","schema":{"description":"\n\nComputes a momentum SGD update for an input gradient and momentum\nparameters. Concretely, given inputs (grad, m, lr) and parameters\n(momentum, nesterov), computes:\n\n if not nesterov:\n adjusted_gradient = lr * grad + momentum * m\n return (adjusted_gradient, adjusted_gradient)\n else:\n m_new = momentum * m + lr * grad\n return ((1 + momentum) * m_new - momentum * m, m_new)\n\nOutput is (grad, momentum)\n\nNote the difference to MomemtumSGDUpdate, which actually performs the\nparameter update (and is thus faster).\n","support_level":"default"}},{"name":"ReduceSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"SortedSegmentRangeSum","schema":{"description":"\nApplies 'Sum' to each segment of input tensor. In order to allow for more\nefficient implementation of 'Sum', the input segments have to be contiguous\nand non-empty.\n\nSEGMENT_IDS is a vector that maps each of the first dimension slices of the\nDATA to a particular group (segment). Values belonging to the same segment are\naggregated together.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nSummation is done element-wise across slices of the input tensor and doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor to be aggregated","name":"DATA"},{"description":"Vector with the same length as the first dimension of DATA and values in the range 0..K-1 and in increasing order that maps each slice of DATA to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated tensor with the first dimension of K and the other dimentsions inherited from DATA","name":"OUTPUT"}],"support_level":"default"}},{"name":"TT","schema":{"attributes":[{"description":"(int[]) Input sizes of cores. Indicates the input size of the individual cores; the size of the input vector X must match the product of the inp_sizes array.","name":"inp_sizes","option":"optional"},{"description":"(int[]) Output sizes of cores. Indicates the output size of the individual cores; the size of the output vector Y must match the product of the out_sizes array.","name":"out_sizes","option":"optional"},{"description":"(int[]) Ranks of cores. Indicates the ranks of the individual cores; lower rank means larger compression, faster computation but reduce accuracy.","name":"tt_ranks","option":"optional"}],"description":"\nThe TT-layer serves as a low-rank decomposition of a fully connected layer. The\ninputs are the same as to a fully connected layer, but the number of parameters\nare greatly reduced and forward computation time can be drastically reduced\nespecially for layers with large weight matrices. The multiplication is computed\nas a product of the input vector with each of the cores that make up the TT\nlayer. Given the input sizes (inp_sizes), output sizes(out_sizes), and the ranks\nof each of the cores (tt_ranks), the ith core will have size:\n\n inp_sizes[i] * tt_ranks[i] * tt_ranks[i + 1] * out_sizes[i].\n\nThe complexity of the computation is dictated by the sizes of inp_sizes,\nout_sizes, and tt_ranks, where there is the trade off between accuracy of the\nlow-rank decomposition and the speed of the computation.\n","inputs":[{"description":"Input tensor from previous layer with size (M x K), where M is the batch size and K is the input size.","name":"X"},{"description":"1D blob containing the bias vector","name":"b"},{"description":"1D blob containing each individual cores with sizes specified above.","name":"cores"}],"outputs":[{"description":"Output tensor from previous layer with size (M x N), where M is the batch size and N is the output size.","name":"Y"}],"support_level":"default"}},{"name":"BitwiseXor","schema":{"attributes":[{"default":0,"description":"Pass 1 to enable broadcasting.","name":"broadcast","option":"optional","type":"int64"},{"default":-1,"description":"Axis to concatenate on. If set, defines the broadcast dimensions.","name":"axis","option":"optional","type":"int64"}],"description":"\nPerforms element-wise bitwise operation `bitwise_xor` (with limited broadcast support).\nBoth input operands should be of type `bool`.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of size 1 (a scalar value), or having its shape as a\ncontiguous subset of the first tensor's shape. The starting of the mutually\nequal shape is specified by the argument \"axis\", and if it is not set, suffix\nmatching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n```\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n```\nArgument `broadcast=1` needs to be passed to enable broadcasting.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/elementwise_ops_schema.cc\n\n","inputs":[{"description":"*(type: Tensor)* First operand.","name":"A"},{"description":"*(type: Tensor)* Second operand. With broadcasting can be of smaller size than `A`. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"*(type: Tensor)* Output tensor. Has same dimensions as input `A`.","name":"C"}],"support_level":"default"}},{"name":"StoreSet","schema":{"attributes":[{"description":"alternative key for the blob (optional)","name":"blob_name","option":"optional"}],"description":"\nSet a blob in a store. The key is the input blob's name and the value\nis the data in that blob. The key can be overridden by specifying the\n'blob_name' argument.\n","inputs":[{"description":"unique_ptr","name":"handler"},{"description":"data blob","name":"data"}],"support_level":"default"}},{"name":"CTCGreedyDecoder","schema":{"attributes":[{"description":"When merge_repeated is true, merge repeated classes in output.","name":"merge_repeated","option":"optional"}],"description":"Greedy decoder for connectionist temporal classification.","inputs":[{"description":"3D float Tensor sized [max_time, batch_size, num_classes]","name":"INPUTS"},{"description":"(optional) 1D int vector containing sequence lengths, having size [batch_size]seq_len will be set to max_time if not provided","name":"SEQ_LEN"}],"outputs":[{"description":"Output_len matrix size (batch). The row store: [decoded_length]","name":"OUTPUT_LEN"},{"description":"Values vector, size (total_decoded_outputs). The vector stores the decoded classes","name":"VALUES"}],"support_level":"default"}},{"name":"SegmentOneHot","schema":{"description":"\nGiven a sequence of indices, segmented by the lengths tensor, returns a matrix\nthat has the elements in each sequence set to 1.0, and 0.0 everywhere else.\n","inputs":[{"description":"Size of each segment.","name":"lengths"},{"description":"Active indices, of size sum(lengths)","name":"indices"},{"description":"Size of the index","name":"index_size_tensor"}],"outputs":[{"description":"Matrix of size len(lengths) x index_size","name":"one_hots"}],"support_level":"default"}},{"name":"Max","schema":{"description":"\nElement-wise max of an arbitrary number of input tensors. This operation can be\nperformed in-place, by using the first input blob as the output blob. All inputs\nmust have the same shape and data type, and the output will have the same shape\nas the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/minmax_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Max\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(3,3)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Max:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.4496477 0.07061381 0.7139333 ]\n [0.83203 0.05970785 0.72786295]\n [0.75988126 0.04601283 0.32820013]]\nY:\n[[0.05683139 0.16872478 0.671098 ]\n [0.70739156 0.09878621 0.03416285]\n [0.34087983 0.94986707 0.67263436]]\nZ:\n[[0.48051122 0.07141234 0.85264146]\n [0.77086854 0.22082241 0.13154659]\n [0.42401117 0.995431 0.4263775 ]]\nMax:\n[[0.48051122 0.16872478 0.85264146]\n [0.83203 0.22082241 0.72786295]\n [0.75988126 0.995431 0.67263436]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as input(s).Contains the maximum valued element at each location.","name":"M"}],"support_level":"default"}},{"name":"MaxPool3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"CreateDB","schema":{"description":null,"support_level":"default"}},{"name":"Rsqrt","schema":{"description":"Computes the element-wise rsqrt of the input.","inputs":[{"description":"ND input tensor","name":"X"}],"outputs":[{"description":"ND output tensor","name":"Y"}],"support_level":"default"}},{"name":"WeightedSum","schema":{"description":"\nElement-wise weighted sum of several data, weight tensor pairs.\nInput should be in the form X_0, weight_0, X_1, weight_1, ... where X_i all\nhave the same shape, and weight_i are size 1 tensors that specifies the weight\nof each vector. Note that if one wants to do in-place computation, it could\nonly be done with X_0 also as the output, but not other X_i.\n","inputs":[{"description":"Weight of the first input in the sum.","name":"weight_0"}],"outputs":[{"description":"Result containing weighted elem-wise sum of inputs.","name":"output"}],"support_level":"default"}},{"name":"NCHW2NHWC","schema":{"description":"\nThe operator switches the order of data in a tensor from NCHW- sample index N,\nchannels C, height H and width W, to the NHWC order (this is for 2D images).\nIn general, this operator switches the order of data in a tensor from N C H_1\n... H_k to N H_1 ... H_k C for k-dimensional features, and currently supports\nk=1, 2, and 3.\n","inputs":[{"description":"The input data (Tensor) in the NCHW order.","name":"data"}],"outputs":[{"description":"The output tensor (Tensor) in the NHWC order.","name":"output"}],"support_level":"default"}},{"name":"GivenTensorByteStringToUInt8Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":"\nThis op fills a uint8 output tensor with the data specified by the *value* argument. The data must previously be serialized as a byte string. The output tensor shape is specified by the *shape* argument. Beware, when using this argument *value* should have a value for every element of the *output*, as missing values will not be initialized automatically. If *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\nThis op allows us to write uint8 tensors to Protobuf as byte strings and read them back as uint8 tensors in order to avoid the Protobuf uint32_t varint encoding size penalty.\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nval = np.array([1, 2, 3], dtype=np.uint8)\nop = core.CreateOperator(\n \"GivenTensorByteStringToUInt8Fill\",\n [],\n [\"out\"],\n values=[val.tobytes()],\n shape=val.shape,\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [1 2 3]\n\n```\n\n
    \n\n","support_level":"default"}},{"name":"LC3DGradient","schema":{"description":null,"support_level":"default"}},{"name":"rnn_internal_accumulate_gradient_input","schema":{"description":"\nInternal RNN operator.\n","support_level":"default"}},{"name":"SumInt","schema":{"description":null,"support_level":"default"}},{"name":"DotProductGradient","schema":{"description":null,"support_level":"default"}},{"name":"MergeMultiMapFeatureTensors","schema":{"description":"Merge given multi-feature tensors with map features into one.\n Single-feature representation:\n - scalar features:\n T\n - list features:\n .lengths int32\n .values T\n - map features:\n .lengths int32\n .keys K\n .values V\n\n Missing values are set to zero, and value presence flag is set accordingly:\n .presence bool\n\n Multi-feature representation:\n - scalar features:\n .lengths int32\n .keys int64\n .values T\n - list features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.values T\n - map features:\n .lengths int32\n .keys int64\n .values.lengths int32\n .values.keys K\n .values.values V\n\n You can read more about representing batches of lists and maps here:\n https://our.intern.facebook.com/intern/dex/caffe2/sparse-operations/\n","inputs":[{"description":".lengths","name":"in1_lengths"},{"description":".keys","name":"in1_keys"},{"description":".values.lengths","name":"in1_values_lengths"},{"description":".values.keys","name":"in1_values_keys"},{"description":".values.values","name":"in1_values_values"}],"outputs":[{"description":".lengths","name":"out_lengths"},{"description":".keys","name":"out_keys"},{"description":".values_lengths","name":"out_values_lengths"},{"description":".values.keys","name":"out_values_keys"},{"description":".values.values","name":"out_values_values"}],"support_level":"default"}},{"name":"SortedSegmentRangeLogSumExpGradient","schema":{"description":null,"support_level":"default"}},{"name":"CosineSimilarityGradient","schema":{"description":null,"support_level":"default"}},{"name":"SoftmaxWithLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"EnforceFinite","schema":{"description":"\nRaise if there is NaN or Inf values in the input tensor.\n","inputs":[{"description":"Input tensor","name":"input"}],"support_level":"default"}},{"name":"AveragePool3D","schema":{"description":"AveragePool3D \nconsumes an input blob and applies average pooling across the the blob according\nto kernel sizes, stride sizes, pad lengths and dilation. Average pooling consists\nof taking the average value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"AveragePool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-0.2883434 0.43498734 0.05417408 1.912558 0.09390241\n -0.33173105]\n [ 1.633709 1.2047161 0.36964908 0.99961185 0.4184147\n 0.9989975 ]\n [ 1.7644193 0.1789665 1.5812988 -0.6038542 -0.36090398\n 0.33195344]\n [ 0.9457722 -0.95174325 -0.78124577 1.2062047 1.1903144\n 0.2586746 ]\n [ 1.252104 0.32645547 1.8073524 -0.78397465 0.9978303\n -0.97614396]\n [ 0.5440196 1.5778259 -0.76750124 0.5051756 0.8838398\n -0.37085298]]]]\n\nY:\n [[[[0.7462672 0.83399826 0.2948959 ]\n [0.4843537 0.3506009 0.35500962]\n [0.9251013 0.19026303 0.13366827]]]]\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"ReduceFrontSum","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **sum**.\n\nCan reduce more than one of the \"first\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the sum operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_1 * d_2 * ... * d_{n})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{0}$ dimension.\n\nFor example, if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1,2]$, then $Y = [sum(1,4), sum(5,1,7), sum(2), sum(9,2)] = [2.5, 4.333, 2, 5.5]$\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_sum_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceFrontSum\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[4. 1. 1.]\n [0. 6. 7.]\n [7. 8. 6.]]\n\n [[5. 7. 7.]\n [0. 1. 6.]\n [2. 9. 0.]]]\nY: [18. 32. 27.]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"ConditionalSetAtomicBool","schema":{"description":"\nSet an atomic to true if the given condition bool variable is true\n ","inputs":[{"description":"Blob containing a unique_ptr>","name":"atomic_bool"},{"description":"Blob containing a bool","name":"condition"}],"support_level":"default"}},{"name":"CollectTensor","schema":{"attributes":[{"description":"The max number of tensors to collect","name":"num_to_collect","option":"optional"}],"description":"\nCollect tensor into tensor vector by reservoir sampling,\nargument num_to_collect indicates the max number of tensors that will be\ncollected. The first half of the inputs are tensor vectors, which are also the\noutputs. The second half of the inputs are the tensors to be collected into each\nvector (in the same order). The input tensors are collected in all-or-none\nmanner. If they are collected, they will be placed at the same index in the\noutput vectors.\n","support_level":"default"}},{"name":"Min","schema":{"description":"\nElement-wise min of an arbitrary number of input tensors. This operation can be performed in-place, by using the first input blob as the output blob. All inputs must have the same shape and data type, and the output will have the same shape as the inputs.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/minmax_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Min\",\n [\"X\", \"Y\", \"Z\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.rand(2,2)).astype(np.float32))\nworkspace.FeedBlob(\"Y\", (np.random.rand(2,2)).astype(np.float32))\nworkspace.FeedBlob(\"Z\", (np.random.rand(2,2)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\nprint(\"Z:\", workspace.FetchBlob(\"Z\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Min:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[0.32731926 0.4939747 ]\n [0.29242373 0.43460014]]\nY:\n[[0.40928316 0.916115 ]\n [0.77526504 0.29339448]]\nZ:\n[[0.7899794 0.90335774]\n [0.82599413 0.2843068 ]]\nMin:\n[[0.32731926 0.4939747 ]\n [0.29242373 0.2843068 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors with the same shape.","name":"X, Y, ..."}],"outputs":[{"description":"*(type: Tensor``)* Output tensor with same dimensions as input(s).Contains the minimum valued element at each location.","name":"M"}],"support_level":"default"}},{"name":"Ceil","schema":{"description":"\nElement-wise application of the ceil function ($y=ceil(x)$) to the input tensor\n`X`. Output tensor shape is the same as the input tensor.\n\nGithub Link:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/ceil_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Ceil\",\n [\"X\"],\n [\"X\"],\n)\n\nworkspace.FeedBlob(\"X\", (np.random.uniform(-10, 10, (5,5))).astype(np.float32))\nprint(\"X before running op:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"X after running op:\", workspace.FetchBlob(\"X\"))\n\n```\n\n**Result**\n\n```\n\nX before running op:\n[[ 8.44598 -6.5098248 -2.2993476 -7.6859694 0.58566964]\n [-7.846551 -0.03689406 6.9362907 -4.0521703 4.4969673 ]\n [ 0.33355865 -7.895527 -8.393201 9.374202 -2.3930092 ]\n [-6.3061996 3.1403487 3.782099 -8.516556 -2.8387244 ]\n [-2.0164998 4.7663913 -3.422966 0.3636999 8.75713 ]]\nX after running op:\n[[ 9. -6. -2. -7. 1.]\n [-7. -0. 7. -4. 5.]\n [ 1. -7. -8. 10. -2.]\n [-6. 4. 4. -8. -2.]\n [-2. 5. -3. 1. 9.]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output tensor.","name":"Y"}],"support_level":"default"}},{"name":"RecurrentNetworkBlobFetcher","schema":{"attributes":[{"description":"Prefix string to prepend extracted blobs.","name":"prefix","option":"optional"}],"description":"\nRetrieves blobs from scratch workspaces (which contain intermediate recurrent\nnetwork computation for each timestep) and puts them in the global\nworkspace under CPUContext.\n","inputs":[{"description":"Name of scratch workspace blob returned by recurrent network.","name":"ScratchWorkspaceBlob"}],"outputs":[{"description":"1D tensor of strings containing extracted blob names.","name":"blob_names"}],"support_level":"default"}},{"name":"Selu","schema":{"attributes":[{"default":1.673263,"description":"Alpha constant in equation.","name":"alpha","option":"optional","type":"float32"},{"default":1.0507,"description":"Scale constant in equation.","name":"scale","option":"optional","type":"float32"}],"description":"\n\nThe *Selu* op takes one input tensor $X$, an argument $alpha$, an argument $scale$, and produces one output tensor $Y$ of the same shape as $X.$ The op performs the element wise *Selu* operation, defined as\n\n$$y=selu(x) =\\begin{cases}scale (\\alpha e^{x} - \\alpha) & x < 0\\\\scale * x & otherwise\\end{cases}$$\n\nThe default value of *alpha* is 1.6732632423543772848170429916717 and the default value of *scale* is 1.0507009873554804934193349852946. See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) for more information.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/selu_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/selu_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Selu\",\n [\"X\"],\n [\"Y\"],\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(3, 3).astype(np.float32))\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[ 1.1613879 -0.27111396 -1.2076733 ]\n [ 1.3442237 -1.0701777 1.2070968 ]\n [ 0.23810555 0.9740916 -1.7872391 ]]\n\nY:\n [[ 1.2202715 -0.4174965 -1.2326177 ]\n [ 1.4123772 -1.1551634 1.2682979 ]\n [ 0.25017774 1.023479 -1.4637551 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"Input tensor of data to be operated on.","name":"X"}],"outputs":[{"description":"Output tensor with same shape as input.","name":"Y"}],"support_level":"default"}},{"name":"DataCouple","schema":{"description":"\n\nA one to one operator that takes an arbitrary number of input and output blobs\nsuch that each input blob is inplace with it's matching output blob. It then proceedes\nto do nothing with each of these operators. This serves two purposes. It can make it\nappear as if a blob has been written to, as well as can tie together different blobs\nin a data dependency\n\n","support_level":"default"}},{"name":"Logit","schema":{"attributes":[{"description":"small positive epsilon value, the default is 1e-6.","name":"eps (optional)","option":"optional"}],"description":"\nElementwise logit transform: logit(x) = log(x / (1 - x)), where x is the\ninput data clampped in (eps, 1-eps).\n","inputs":[{"description":"input float tensor","name":"X"}],"outputs":[{"description":"output float tensor","name":"Y"}],"support_level":"default"}},{"name":"SegmentIdsToLengths","schema":{"description":"\nTransfers a vector of segment ids to a vector of segment lengths. This operation\nsupports non-consecutive segment ids. Segments not appearing in the input vector\nwill have length 0. If the second input is provided, the number of segments =\nthe size of its first dimension. Otherwise, the number of segments = the last\nindex in the first input vector + 1.\n\nIn general, for consecutive, zero-based segment IDs, this is the inverse\noperation of LengthsToSegmentIds, except that a vector of segment IDs\ncannot represent empty segments at the end (if the second input is absent).\n","inputs":[{"description":"1-D int32_t or int64_t tensor of segment ids","name":"segment_ids"},{"description":"if provided, number of segments = the size of its first dimension","name":"data (optional)"}],"outputs":[{"description":"1-D int64_t tensor of segment lengths","name":"lengths"}],"support_level":"default"}},{"name":"YellowFin","schema":{"attributes":[{"description":"Default 0.999","name":"beta","option":"optional"},{"description":"Default 20","name":"curv_win_width","option":"optional"},{"description":"Default 1e-6","name":"epsilon","option":"optional"},{"description":"Default false","name":"nesterov","option":"optional"},{"description":"Default true","name":"zero_debias","option":"optional"}],"description":"\n\nComputes the YellowFin update (https://arxiv.org/abs/1706.03471) and performs\nmomentum SGD optimization step. lr and mu are not being shared between\nparameters. curv_win, g_avg, g2_avg and scalars_memory are just auxiliary\nmemory for computing moving averages (see the publication). Takes arguments\nbeta: coefficient for moving averages,\ncurv_win_width: timeframe when average squared gradient is being stored,\nepsilon: for numerical purposes,\nnesterov and zero_debias for debias of moving average.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Momentum","name":"moment"},{"description":"Learning rate","name":"lr"},{"description":"Momentum coefficient","name":"mu"},{"description":"Memory for latest curvature ranges","name":"curv_win"},{"description":"Moving average of gradient","name":"g_avg"},{"description":"Moving average of squared gradient","name":"g2_avg"},{"description":"Memory for stateful scalars","name":"scalars_memory"},{"description":"Gradient computed","name":"grad"},{"description":"Iteration number","name":"iter"}],"outputs":[{"description":"Parameters to be updated","name":"output_param"},{"description":"Momentum","name":"output_moment"},{"description":"Output learning rate","name":"output_lr"},{"description":"Output momentum coefficient","name":"output_mu"},{"description":"Output memory for latest curvature ranges","name":"output_curv_win"},{"description":"Output moving average of gradient","name":"output_g_avg"},{"description":"Output moving average of squared gradient","name":"output_g2_avg"},{"description":"Output memory for stateful scalars","name":"output_scalars_memory"}],"support_level":"default"}},{"name":"ReduceBackMax","schema":{"attributes":[{"description":"(*int*): number of dimensions to reduce (default=1)","name":"num_reduce_dims","option":"optional"}],"description":"\nReduces the input tensor along the last dimension of the by applying **max**.\n\nCan reduce more than one of the \"last\" dimensions by setting `num_reduce_dim`.\n\nA second (optional) input, `lengths`, can be passed, which enforces that only a subset of the elements are considered in the max operation.\n- If input tensor `X` has shape $(d_0, d_1, d_2, ..., d_n)$, `lengths` must have shape $(d_0 * d_1 * d_2 * ... * d_{n-1})$.\n- The values of the `lengths` tensor determine how many of the values to consider for each vector in the $d_{n-1}$ dimension.\n\nFor example if $X = [[1,5,2,9],[4,1,8,2],[2,7,0,3]]$ and $lengths = [2,3,1]$, then $Y = [max(1,5), max(4,1,8), max(2)] = [5, 8, 2]$\n\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/reduce_front_back_max_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"ReduceBackMax\",\n [\"X\"],\n [\"Y\"],\n num_reduce_dim=2\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(10, size=(1,2,3,3)).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n[[[[2. 5. 1.]\n [6. 1. 9.]\n [8. 5. 9.]]\n\n [[5. 7. 8.]\n [9. 9. 6.]\n [6. 5. 0.]]]]\nY: [[9. 9.]]\n\n```\n\n
    \n\n","inputs":[{"description":"(*Tensor``*): input tensor","name":"X"},{"description":"(*Tensor``*): number of elements in each sample","name":"lengths"}],"outputs":[{"description":"(*Tensor``*): reduced tensor","name":"Y"}],"support_level":"default"}},{"name":"Int8Concat","schema":{"attributes":[{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"},{"description":"Which axis to concat on","name":"axis","option":"optional"},{"description":"Pass 1 to add the axis specified in arg 'axis' to all input tensors","name":"add_axis","option":"optional"}],"description":"Concatenate a list of tensors into a single tensor","outputs":[{"description":"Concatenated tensor","name":"concat_result"},{"description":"The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"Allgather","schema":{"description":"\nDoes an allgather operation among the nodes.\n","inputs":[{"description":"The common world.","name":"comm_world"},{"description":"A tensor to be allgathered.","name":"X"}],"outputs":[{"description":"The allgathered tensor, same on all nodes.","name":"Y"}],"support_level":"default"}},{"name":"RecurrentNetworkGradient","schema":{"description":null,"support_level":"default"}},{"name":"HalfFloatToFused8BitRowwiseQuantized","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 8 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"StopGradient","schema":{"description":"\nStopGradient is a helper operator that does no actual numerical computation,\nand in the gradient computation phase stops the gradient from being computed\nthrough it.\n","support_level":"default"}},{"name":"Summarize","schema":{"attributes":[{"description":"(int, default 0) flag to indicate if the summarized statistics have to be written to a log file.","name":"to_file","option":"optional"}],"description":"\nSummarize computes four statistics of the input tensor (Tensor)- min,\nmax, mean and standard deviation. The output will be written to a 1-D tensor of\nsize 4 if an output tensor is provided. Else, if the argument 'to_file' is\ngreater than 0, the values are written to a log file in the root folder.\n","inputs":[{"description":"The input data as Tensor.","name":"data"}],"outputs":[{"description":"1-D tensor (Tensor) of size 4 containing min, max, mean and standard deviation","name":"output"}],"support_level":"default"}},{"name":"NormalizeL1","schema":{"attributes":[{"description":"axis to normalize","name":"axis","option":"optional"}],"description":"\nGiven a matrix, apply L1-normalization along the specified axis.\n","support_level":"default"}},{"name":"BatchSparseToDense","schema":{"attributes":[{"description":"Optional, output dense last dimension. If both this argument and output_shape_inference are set, it should be consistent with output_shape_inference's last dim","name":"dense_last_dim","option":"optional"},{"description":"Optional, missing values are filled with this value.default_value = 0 when not set","name":"default_value","option":"optional"}],"description":"\nConvert sparse matrix representation into dense matrix.\n\nA sparse matrix is represented by `lengths` vector, `indices` vector,\nand `values` vector. Each element in `lengths` vector (lengths[`i`]) represents\nthe number of indices in this batch (batch `i`).\nWith in each batch, `indices` should not have duplicate number.\n\nFor example, with input:\n\n lengths = [2, 3, 1]\n indices = [0, 1, 2, 3, 4, 5]\n values = [6, 7, 8, 9, 10, 11]\n dense_dim = 6\n default_value = 0\n\nThe output is:\n\n output = [[6, 7, 0, 0, 0, 0],\n [0, 0, 8, 9, 10, 0],\n [0, 0, 0, 0, 0, 11]]\n\nafter running this operator.\n","inputs":[{"description":"Flatten tensor, used to break down indices and values into per batch indices and values.","name":"lengths"},{"description":"Flatten tensor of total size = \\sum lengths, containing the indices ","name":"indices"},{"description":"Data tensor, dimension has to match `indices`","name":"values"},{"description":"Optional, a dense tensor whose shape define the output shape","name":"output_shape_inference"}],"outputs":[{"description":"2-D dense tensor, with 1st dim = len(lengths), 2nd dim = dense_last_dimin the arg list, the tensor is of the same data type as `values`.Missing values are filled with default_value","name":"dense"}],"support_level":"default"}},{"name":"MaxPool3D","schema":{"description":"MaxPool3D \nconsumes an input blob and applies max pooling across the the blob according to\nkernel sizes, stride sizes, pad lengths and dilation. Max pooling consists of\ntaking the maximum value of a subset of the input tensor according to the kernel\nsize and downsampling the data into the output blob for further processing. The\n`brew` module has a wrapper for this operator for use in a `ModelHelper` object.\n\nPooling layers reduce the spatial dimensionality of the input blob. Each of the\noutput blob's dimensions will reduce according to:\n\n$$dim_{out}=\\frac{dim_{in}-kernel+2*pad}{stride}+1$$\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pool_op.cc\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/conv_pool_op_base.h\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"MaxPool\",\n [\"X\"],\n [\"Y\"],\n kernel=2,\n stride=2,\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(1, 1, 6, 6).astype(np.float32)) // NCHW\nprint(\"X:\\n\", workspace.FetchBlob(\"X\"), \"\\n\")\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n```\n\n**Result**\n\n```\nX:\n [[[[-2.8534958e-01 -1.7719941e+00 -8.2277227e-04 1.1088650e+00\n -2.1476576e+00 -3.5070452e-01]\n [-9.0058845e-01 -3.0070004e-01 -1.7907504e+00 -7.1746534e-01\n 1.2798511e+00 -3.2214901e-01]\n [ 1.5806322e+00 1.6845188e+00 -2.6633200e-01 -3.8576153e-01\n -9.6424848e-02 -3.9696163e-01]\n [ 1.2572408e-01 6.3612902e-01 -3.9554062e-01 -6.9735396e-01\n -9.1898698e-01 -1.9609968e-01]\n [-1.1587460e+00 2.4605224e+00 -1.5497679e+00 1.3020347e-01\n -8.1293899e-01 -7.8803545e-01]\n [ 1.4323474e+00 1.3618395e+00 9.8975077e-02 -1.1307785e-01\n 7.2035044e-01 2.7642491e-01]]]]\n\nY:\n [[[[-0.28534958 1.108865 1.2798511 ]\n [ 1.6845188 -0.266332 -0.09642485]\n [ 2.4605224 0.13020347 0.72035044]]]]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input data tensor of shape NCHW or NHWC.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Output data tensor.","name":"Y"}],"support_level":"default"}},{"name":"CreateMap","schema":{"attributes":[{"description":"Key's TensorProto::DataType (default INT32)","name":"key_dtype","option":"optional"},{"description":"Value's TensorProto::DataType (default INT32)","name":"value_dtype","option":"optional"}],"description":"Create an empty map blob","outputs":[{"description":"Blob reference to the map","name":"map blob"}],"support_level":"default"}},{"name":"BatchMomentsGradient","schema":{"description":null,"support_level":"default"}},{"name":"WeightedSigmoidCrossEntropyWithLogitsGradient","schema":{"description":null,"support_level":"default"}},{"name":"RmsProp","schema":{"description":"\nComputes the RMSProp update\n(http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf).\nConcretely, given inputs (grad, mean_squares, mom, lr), computes:\n\n mean_squares_o = mean_squares + (1 - decay) * (square(grad) - mean_squares)\n mom_o = momentum * mom + lr * grad / sqrt(epsilon + mean_squares_o)\n grad_o = mom_o\n\nReturns (grad_o, mean_squares_o, mom_o).\n","support_level":"default"}},{"name":"SoftmaxWithLoss","schema":{"attributes":[{"default":0,"description":"Setting to 1 enables inputting labels as probability distribution.","name":"label_prob","option":"optional","type":"int64"},{"default":1,"description":"Axis of the inputs when coerced to 2D.","name":"axis","option":"optional","type":"int64"},{"description":"Average loss output scaling factor (must be >= 0).","name":"scale","option":"optional","type":"float32"},{"default":"'NCHW'","description":"Order of blob dimensions (only 'NCHW' is supported currently).","name":"order","option":"optional","type":"string"}],"description":"\nCombined Softmax and Cross-Entropy loss operator. The operator first computes the softmax normalized values for each layer in the batch of the given input, then computes cross-entropy loss. This operator is numerically more stable than separate `Softmax` and `CrossEntropy` ops. The inputs are a 2-D tensor `logits` of size (batch_size x input_feature_dimensions), which represents the unscaled log probabilities, and a 1-dimensional integer `labels` tensor for ground truth. An optional third input blob (`weight_tensor`) can be used to weight the samples for the loss, which is useful if the training set is unbalanced. This operator outputs a `softmax` tensor which contains the probability for each label for each example (same shape is `logits` input), and a scalar `loss` value, which is the averaged cross-entropy loss between the softmax probabilities and the ground truth values. Use parameter `label_prob`=1 to enable inputting labels as a probability distribution.\n\nSoftmax cross-entropy loss function:\n\n$$loss(x, class) = -\\log{\\biggl(\\frac{\\exp(x[class])}{\\sum_{j} \\exp(x[j])}\\biggr)} = -x[class] + \\log{\\biggl(\\sum_{j} \\exp(x[j])\\biggr)}$$\n\nor if the `weight_tensor` has been passed:\n\n$$loss(x, class) = weight[class]\\biggl(-x[class] + \\log{\\biggl(\\sum_{j} \\exp(x[j])\\biggr)}\\biggr)$$\n\nThe `logits` input does not need to explicitly be a 2D vector; rather, it will be coerced into one. For an arbitrary n-dimensional tensor `X` in $[a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}]$, where k is the `axis` provided, then `X` will be coerced into a 2-dimensional tensor with dimensions $[(a_0 * ... * a_{k-1}), (a_k * ... * a_{n-1})]$. For the default case where `axis`=1, the `X` tensor will be coerced into a 2D tensor of dimensions $[a_0, (a_1 * ... * a_{n-1})]$, where $a_0$ is often the batch size. In this situation, we must have $a_0 = N$ and $a_1 * ... * a_{n-1} = D$. Each of these dimensions must be matched correctly, or else the operator will throw errors.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/softmax_with_loss_op.cc\n\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SoftmaxWithLoss\",\n [\"logits\", \"labels\"],\n [\"softmax\", \"avgloss\"]\n)\n\nworkspace.FeedBlob(\"logits\", np.random.randn(1, 5).astype(np.float32))\nworkspace.FeedBlob(\"labels\", np.asarray([4]).astype(np.int32))\nprint(\"logits:\", workspace.FetchBlob(\"logits\"))\nprint(\"labels:\", workspace.FetchBlob(\"labels\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"softmax\"))\nprint(\"avgloss:\", workspace.FetchBlob(\"avgloss\"))\n\n```\n\n**Result**\n\n```\n\nlogits: [[-0.3429451 -0.80375195 0.23104447 1.4569176 -0.5268362 ]]\nlabels: [4]\nsoftmax: [[0.09721052 0.0613179 0.17258129 0.58800864 0.0808817 ]]\navgloss: 2.5147676\n\n```\n\n
    \n\n
    \n\n Example 2 \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"SoftmaxWithLoss\",\n [\"logits\", \"labels\"],\n [\"softmax\", \"avgloss\"],\n scale=5.0\n)\n\nworkspace.FeedBlob(\"logits\", np.asarray([[.1, .4, .7, 1.5, .2]]).astype(np.float32))\nworkspace.FeedBlob(\"labels\", np.asarray([4]).astype(np.int32))\nprint(\"logits:\", workspace.FetchBlob(\"logits\"))\nprint(\"labels:\", workspace.FetchBlob(\"labels\"))\nworkspace.RunOperatorOnce(op)\nprint(\"softmax:\", workspace.FetchBlob(\"softmax\"))\nprint(\"avgloss:\", workspace.FetchBlob(\"avgloss\"))\n\n```\n\n**Result**\n\n```\n\nlogits: [[0.1 0.4 0.7 1.5 0.2]]\nlabels: [4]\nsoftmax: [[0.10715417 0.144643 0.19524762 0.4345316 0.11842369]]\navgloss: 10.667433\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor``)* Input tensor.","name":"logits"},{"description":"*(type: Tensor``)* Ground truth label tensor.","name":"labels"},{"description":"*(type: Tensor``)* [OPTIONAL] Blob used to weight the samples for the loss.","name":"weight_tensor"}],"outputs":[{"description":"*(type: Tensor``)* Softmax output tensor.","name":"softmax"},{"description":"*(type: float)* Averaged cross-entropy loss output.","name":"loss"}],"support_level":"default"}},{"name":"VariableLengthSequencePadding","schema":{"description":"\nSuper special-case operator. Used to pad a tensor to mimic pytorch's\npad_packed_sequence.\n\nGiven an input tensor INPUT of size NxBxM and an input tensor LENS\nof size B, where\n\nN = maximum sequence length\nB = batch size\nM = hidden size\n\nset each element of INPUT to zero if it is is past the end of the\ncorresponding sequence (i.e. if LENS[j] > i for an index (i,j,k)).\n\n","support_level":"default"}},{"name":"SparseLengthsMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"SoftplusGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments are defined by their LENGTHS.\n\nThis op is basically Gather and LengthsMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nLENGTHS is a vector that defines slice sizes by first dimension of DATA. Values\nbelonging to the same segment are aggregated together. sum(LENGTHS) has\nto match INDICES size.\n\nThe first dimension of the output is equal to the number of input segment,\ni.e. `len(LENGTHS)`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Non negative vector with sum of elements equal to INDICES length","name":"LENGTHS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"SparseUnsortedSegmentWeightedSum","schema":{"attributes":[{"description":"Produce also gradient for `weights`. For now it's only supported in `Lengths`-based operators","name":"grad_on_weights","option":"optional"}],"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'WeightedSum' to each segment. Segments ids can appear in arbitrary order (unlike in\nSparseSortedSegmentWeightedSum).\n\nThis op is basically Gather and UnsortedSegmentWeightedSum fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nIf `num_segments` argument is passed it would be used as a first dimension for\nthe output. Otherwise, it'd be dynamically calculated from as the max value of\nSEGMENT_IDS plus one. Other output dimensions are inherited from the input\ntensor.\n\nInput slices are first scaled by SCALARS and then summed element-wise. It doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor for the summation","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the number of slices","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Integer vector with the same length as INDICES that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of equal to the number of segments.","name":"OUTPUT"}],"support_level":"default"}},{"name":"EnsureDense","schema":{"description":"\nThis operator converts dense or sparse gradients to dense ones.\nTherefore, sparse gradient can be back propagated to Operators that consume\ndense gradients only (e.g., FCGradient).\n\nThe operator's behaviors:\n\n- In forward, simply pass in place or copy input to the output.\n- In backward, if the gradient passed-in is sparse gradient, change it to dense gradient in linear time; otherwise, simply pass the dense gradient.\n","inputs":[{"description":"Input tensors.","name":"input"}],"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"output"}],"support_level":"default"}},{"name":"LabelCrossEntropy","schema":{"description":"\nThis operator computes the cross entropy between a $NxD$ dimensional input data tensor $X$ and a one dimensional input label tensor $label$. The op produces a single length $N$ output tensor $Y$. Here, $N$ is considered the batch size and $D$ is the size of each element in the batch. In practice, it is most commonly used at the end of models as a part of the loss computation, after the SoftMax operator and before the AveragedLoss operator. The cross entropy operation is defined as follows\n\n$$Y_i = -log(X_{ij})$$\n\nwhere ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nThe difference between *LabelCrossEntropy* and *CrossEntropy* is how the labels are specified. Here, the labels are a length $N$ list of integers, whereas in CrossEntropy the labels are a $NxD$ dimensional matrix of one hot label vectors. However, the results of computation should be the same, as shown in the two examples where ($i$, $j$) is the classifier's prediction of the $j$th class (the correct one), and $i$ is the batch size. Each log has a lower limit for numerical stability.\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/cross_entropy_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"LabelCrossEntropy\",\n [\"X\", \"label\"],\n [\"Y\"]\n)\n\n// Create X: Sample softmax output for 5-class model\nX = np.array([[.01, .05, .02, .02, .9],[.03, .1, .42, .05, .4]])\nprint(\"X:\\n\",X)\n\n// Create label: Sample 1-hot ground truth label vectors\nlabel = np.array([4,2])\nprint(\"label:\\n\",label)\n\n// Feed X & label into workspace\nworkspace.FeedBlob(\"X\", X.astype(np.float32))\nworkspace.FeedBlob(\"label\", label.astype(np.int32))\n\n// Run op\nworkspace.RunOperatorOnce(op)\n\n// Collect Output\nprint(\"Y:\\n\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:\n [[0.01 0.05 0.02 0.02 0.9 ]\n [0.03 0.1 0.42 0.05 0.4 ]]\nlabel:\n [4 2]\nY:\n [0.10536055 0.8675006 ]\n\n```\n\n
    \n\n\n","inputs":[{"description":"Input tensor which is almost always the result of a softmax operation. $X$ is a 2D array of size $NxD$, where $N$ is the batch size and $D$ is the number of classes.","name":"X"},{"description":"Blob containing the labels used to compare the input. $label$ is a length $N$ list of integers, where each element is the integer label for the $n$th element of the batch.","name":"label"}],"outputs":[{"description":"Output blob from the cross entropy computation. $Y$ is 1D length $N$ tensor.","name":"Y"}],"support_level":"default"}},{"name":"BooleanMaskGradient","schema":{"description":null,"support_level":"default"}},{"name":"Save","schema":{"attributes":[{"default":0,"description":"If set to non-zero, save the db directly to the path specified by the `db` arg. If not set (default), prepend the path of the current root folder of the workspace to the path specified by the `db` arg.","name":"absolute_path","option":"optional","type":"int64"},{"default":"","description":"Characters in the provided blob names that match `strip_prefix` will be removed prior to saving. Also, characters that precede `strip_prefix` will be removed. Useful for removing device scope from blob names.","name":"strip_prefix","option":"optional","type":"string"},{"description":"If set, used as blob names instead of original blob names. Must be same length as number of blobs.","name":"blob_name_overrides","option":"optional","type":"string[]"},{"description":"The output path of the db. See the `absolute_path` arg details for options regarding the current root folder of the workspace.","name":"db","option":"optional","type":"string"},{"description":"Type of db to save (options: \"lmdb\", \"leveldb\", \"minidb\").","name":"db_type","option":"optional","type":"string"},{"default":"kDefaultChunkSize","description":"The chunk size to split tensor data into. If not set, caffe2_tensor_chunk_size will be used","name":"chunk_size","option":"optional","type":"string"}],"description":"\nSaves a set of blobs to a db. It takes $[1, \\infty)$ number of inputs and has\nno output. The contents of the inputs are written into the db using the\nsettings specified by the arguments.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/load_save_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Save\",\n [\"X\", \"Y\", \"Z\"],\n [],\n db=\"test_db2\",\n db_type=\"leveldb\",\n blob_name_overrides=[\"x_scores\", \"y_scores\", \"z_scores\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randint(20, size=(5,5)))\nworkspace.FeedBlob(\"Y\", np.random.randint(20, size=(5,5)))\nworkspace.FeedBlob(\"Z\", np.random.randint(20, size=(5,5)))\nworkspace.RunOperatorOnce(op)\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input tensor(s).","name":"X"}],"support_level":"default"}},{"name":"SparseSortedSegmentMean","schema":{"description":"\nPulls in slices of the input tensor, groups them into segments and applies\n'Mean' to each segment. Segments need to be sorted and contiguous. See also\nSparseUnsortedSegmentMean that doesn't have this requirement.\n\nThis op is basically Gather and SortedSegmentMean fused together.\n\nINDICES should contain integers in range 0..N-1 where N is the first dimension\nof DATA. INDICES represent which slices of DATA need to be pulled in.\n\nSEGMENT_IDS is a vector that maps each referenced slice of the DATA to a\nparticular group (segment). Values belonging to the same segment are aggregated\ntogether. SEGMENT_IDS should have the same dimension as INDICES.\n\nThe first dimension of the output is equal to the number of input segments,\ni.e. `SEGMENT_IDS[-1]+1`. Other dimensions are inherited from the input tensor.\n\nMean computes the element-wise mean of the input slices. Operation doesn't change the shape of the individual blocks.\n ","inputs":[{"description":"Input tensor, slices of which are aggregated.","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same length as INDICES and values in the range 0..K-1 and in increasing order that maps each slice of DATA referenced by INDICES to one of the segments","name":"SEGMENT_IDS"}],"outputs":[{"description":"Aggregated output tensor. Has the first dimension of K (the number of segments).","name":"OUTPUT"}],"support_level":"default"}},{"name":"GaussianFill","schema":{"attributes":[{"default":0,"description":"Mean of the distribution to draw from.","name":"mean","option":"optional","type":"float32"},{"default":1,"description":"Standard deviation of the distribution to draw from.","name":"std","option":"optional","type":"float32"},{"description":"Desired shape of the *output* tensor.","name":"shape","option":"optional","type":"int64[]"},{"description":"The additional dimensions appended at the end of the *shape* indicated by the input blob. Cannot set the *extra_shape* argument when there is no input blob.","name":"extra_shape","option":"optional","type":"int64[]"},{"default":false,"description":"set to *True* to use the *input* as shape. First, input must be in CPU context.","name":"input_as_shape","option":"optional","type":"boolean"}],"description":"\nThis op fills an output tensor with samples drawn from a normal distribution specified by the mean and standard deviation arguments. The output tensor shape is specified by the *shape* argument. However, if *input_as_shape* is set to *true*, then the *input* should be a 1D tensor containing the desired output shape (the dimensions specified in *extra_shape* will also be appended). In this case, the *shape* argument should **not** be set.\n\n*Note: cannot set the shape argument and pass in an input at the same time.*\n\nGithub Links:\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.h\n- https://github.com/caffe2/caffe2/blob/master/caffe2/operators/filler_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"GaussianFill\",\n [],\n [\"out\"],\n shape=[3,3],\n mean=2.0,\n std=1.1\n)\n\nworkspace.RunOperatorOnce(op)\nprint(\"Out:\\n\", workspace.FetchBlob(\"out\"))\n\n```\n\n**Result**\n\n```\n\nOut:\n [[1.2084167 2.3336504 2.827349 ]\n [2.7108908 0.9374752 1.7173369 ]\n [0.03320992 2.1775863 1.0894578 ]]\n\n```\n\n
    \n\n","inputs":[{"description":"(Optional) 1D tensor specifying the shape of the output. Must be used with *input_as_shape=True*","name":"input"}],"outputs":[{"description":"Output tensor of random values drawn from a normal distribution. If the shape argument is set, this is the shape specified, and if the *input* exists and *input_as_shape=True*, it is the shape specified by the *input* tensor.","name":"output"}],"support_level":"default"}},{"name":"ReduceMinGradient","schema":{"description":null,"support_level":"default"}},{"name":"GivenTensorInt16Fill","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"values"},{"description":"The shape of the output tensor.Cannot set the shape argument and pass in an input at the same time.","name":"shape","option":"optional"},{"description":"The additional dimensions appended at the end of the shape indicatedby the input blob.Cannot set the extra_shape argument when there is no input blob.","name":"extra_shape","option":"optional"},{"description":"1D tensor containing the desired output shape. First input must be in CPU context.","name":"input_as_shape","option":"optional"}],"description":null,"support_level":"default"}},{"name":"Abs","schema":{"description":"\nCalculates the absolute value of the given input tensor, element-wise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/abs_op.cc\n\n
    \n\n Example \n\n**Code**\n\n```\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"Abs\",\n [\"X\"],\n [\"Y\"]\n)\n\nworkspace.FeedBlob(\"X\", np.random.randn(5).astype(np.float32))\nprint(\"X:\", workspace.FetchBlob(\"X\"))\nworkspace.RunOperatorOnce(op)\nprint(\"Y:\", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX: [ 0.3005476 1.551666 -1.3591481 0.39191285 -0.21866608]\nY: [0.3005476 1.551666 1.3591481 0.39191285 0.21866608]\n\n```\n\n
    \n\n","inputs":[{"description":"*(type: Tensor)* Input tensor.","name":"X"}],"outputs":[{"description":"*(type: Tensor``)* Absolute value of input element-wise.","name":"Y"}],"support_level":"default"}},{"name":"LengthsTopK","schema":{"attributes":[{"description":"the number of top values to return for each segment, if the number of values is smaller than k, the values would be padded with 0 and indices would be padded with -1.","name":"k","option":"optional"}],"description":"\nApply TopK to each segment of the input tensor, where segments are defined by\ntheir LENGTHS, and concatenate them in an output tensor of\nshape=(SIZE(LENGTHs), k). In case there's less than k values in a segment,\nthe output value will be padded by 0, and the corresponding output indices will\nbe padded by -1.\n","inputs":[{"description":"Tensor of rank 1. First dimension must be equal to the sum of lengths","name":"DATA"},{"description":"Tensor of int32 lengths of rank 1","name":"LENGTHS"}],"outputs":[{"description":"Output top k elements for each segment, withshape=(SIZE(lengths), k)","name":"TopKValue"},{"description":"Output indices in DATA corresponding to value in TopKValue","name":"TopKIndices"}],"support_level":"default"}},{"name":"RMACRegions","schema":{"attributes":[{"description":"Number of scales to sample regions at.","name":"scales","option":"optional"},{"description":"Overlap between consecutive regions.","name":"overlap","option":"optional"}],"description":"\nComputes a fixed-grid of RMAC region coordinates at various levels\nas described in https://arxiv.org/abs/1511.05879.\n","inputs":[{"description":"The input 4D tensor of shape NCHW.","name":"X"}],"outputs":[{"description":"The output RMAC regions for all items in the batch. Tensor of shape (N x 5) following the ROIPoolOp format - each row is of the format (batch_index x1 y1 x2 y2) where x1, y1, x2, y2 are the region co-ordinates. Each region is repeated N times corresponding to each item in the batch.","name":"RMAC_REGIONS"}],"support_level":"default"}},{"name":"SumReduceLike","schema":{"attributes":[{"description":"If set, defines the starting dimension for reduction. Args `axis` and `axis_str` cannot be used simultaneously.","name":"axis","option":"optional"},{"description":"If set, it could only be N or C or H or W. `order` arg should also be provided. It defines the reduction dimensions on NCHW or NHWC. Args `axis` and `axis_str` cannot be used simultaneously.","name":"axis_str","option":"optional"},{"description":"Either NHWC or HCWH","name":"order","option":"optional"}],"description":"\nSumReduceLike operator takes 2 tensors as input. It performs reduce sum to the\nfirst input so that the output looks like the second one.\nIt assumes that the first input\nhas more dimensions than the second, and the dimensions of the second input is\nthe contiguous subset of the dimensions of the first.\nFor example, the following tensor shapes are supported:\n\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 2, 5), shape(B) = (2), with axis=0\n ","inputs":[{"description":"First operand, should share the type with the second operand.","name":"A"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B"}],"outputs":[{"description":"Result, has same dimensions and type as B","name":"C"}],"support_level":"default"}},{"name":"MaxGradient","schema":{"description":null,"support_level":"default"}},{"name":"ReplaceNaN","schema":{"attributes":[{"description":"the value to replace NaN, the default is 0","name":"value (optional)","option":"optional"}],"description":"\nReplace the NaN (not a number) element in the input tensor with argument `value`\n","inputs":[{"description":"Input tensor","name":"input"},{"description":"Output tensor","name":"output"}],"support_level":"default"}},{"name":"HasScope","schema":{"description":"\nChecks whether scope blob has any saved scopes left\n ","support_level":"default"}},{"name":"ReduceBackSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"ZeroGradient","schema":{"description":"\nZeroGradient operators doesn't produce any output blobs. One can use\nthis operator to produce 0 gradient for the input blob.\n","support_level":"default"}},{"name":"ReduceBackMeanGradient","schema":{"description":null,"support_level":"default"}},{"name":"ClipGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsWeightedSum8BitsRowwise","schema":{"description":"\nVariation of SparseLengthsWeightedSum operator, where\nDATA is stored using 8bits. DATA was quantized with 8Bit row-wise\nquantization (see doc to FloatToRowwiseQuantized8Bits operator). To\nrestore DATA from 8Bit, we use additional input that stores scales\nand biases.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToRowwiseQuantized8Bits","name":"DATA"},{"description":"Scalar multipliers for the input slices. Must be a vector with the length matching the length of INDICES","name":"SCALARS"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Matrix of floats, each row r_i of which stores a pair s_i, b_i -- scale and bias for i-th row","name":"scale_bias"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HuffmanTreeHierarchy","schema":{"attributes":[{"description":"The number of classes used to build the hierarchy.","name":"num_classes","option":"optional"}],"description":"\nHuffmanTreeHierarchy is an operator to generate huffman tree hierarchy given\nthe input labels. It returns the tree as serialized HierarchyProto\n","inputs":[{"description":"The labels vector","name":"Labels"}],"outputs":[{"description":"Huffman coding hierarchy of the labels","name":"Hierarch"}],"support_level":"default"}},{"name":"ChannelShuffle","schema":{"description":null,"support_level":"default"}},{"name":"AveragedLossGradient","schema":{"description":null,"support_level":"default"}},{"name":"SparseLengthsIndicesInGradientSumGradient","schema":{"description":null,"support_level":"default"}},{"name":"BooleanUnmask","schema":{"description":"\nGiven a series of masks and values, reconstruct values together according to masks. A comprehensive example:\n```\nmask1 = True, False, True, False, False\nvalues1 = 1.0, 3.0\nmask2 = False, True, False, False, False\nvalues2 = 2.0\nmask3 = False, False, False, True, True\nvalues3 = 4.0, 5.0\n```\n\nReconstruct by:\n\n```\noutput = net.BooleanUnmask([mask1, values1, mask2, values2, mask3, values3], [\"output\"])\noutput = 1.0, 2.0, 3.0, 4.0, 5.0\n```\n\nNote that for all mask positions, there must be at least one True. This is not allowed:\n\n```\nmask1 = True, False\nvalues1 = 1.0\nmask2 = False, False\nvalues2 =\n\noutput = net.BooleanUnmask([mask1, values1, mask2, values2], [\"output\"])\n```\n\nIf there are multiple True values for a field, we accept the first value, and no longer expect a value for that location:\n\n```\nmask1 = True, False\nvalues1 = 1.0\nmask2 = True, True\nvalues2 = 2.0\n\noutput = net.BooleanUnmask([mask1, values1, mask2, values2], [\"output\"])\noutput = 1.0, 2.0\n```\n\n*** Note that we alternate `data` and `mask` inputs\n\nGithub Links:\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/boolean_unmask_ops.cc\n\n
    \n\n Example \n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n \"BooleanUnmask\",\n [\"mask1\", \"data1\", \"mask2\", \"data2\"],\n [\"unmasked_data\"]\n)\n\nworkspace.FeedBlob(\"mask1\", np.array([True,False,False,True,True,False]))\nworkspace.FeedBlob(\"data1\", np.array([1,4,5]))\nworkspace.FeedBlob(\"mask2\", np.array([False,True,True,False,False,True]))\nworkspace.FeedBlob(\"data2\", np.array([2,3,6]))\n\nprint(\"data1:\", workspace.FetchBlob(\"data1\"))\nprint(\"mask1:\", workspace.FetchBlob(\"mask1\"))\nprint(\"data2:\", workspace.FetchBlob(\"data2\"))\nprint(\"mask2:\", workspace.FetchBlob(\"mask2\"))\nworkspace.RunOperatorOnce(op)\nprint(\"unmasked_data:\", workspace.FetchBlob(\"unmasked_data\"))\n\n```\n\n**Result**\n\n```\n\ndata1: [1 4 5]\nmask1: [ True False False True True False]\ndata2: [2 3 6]\nmask2: [False True True False False True]\nunmasked_data: [1 2 3 4 5 6]\n\n```\n\n
    \n","inputs":[{"description":"(*Tensor*): 1D input tensor(s)","name":"data"},{"description":"(*Tensor``*): 1D boolean mask tensor(s)","name":"mask"}],"outputs":[{"description":"(*Tensor*): 1D tensor of same type as `data` input that contains the unmasked input tensor","name":"unmasked_data"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedToHalfFloat","schema":{"description":"\nDe-quantizes the result of the\nHalfFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 32-bit float in the second to the last 4 bytes of each\nrow, followed by the bias as a 32-bit float in the next 4 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"LengthsGather","schema":{"description":"\nGather items from sparse tensor. Sparse tensor is described by items and\nlengths. This operator gathers items corresponding to lengths at the given\nindices. This deliberately doesn't return lengths of OUTPUTS so that both lists\nand maps can be supported without special cases. If you need lengths tensor for\n OUTPUT, use `Gather`.\n\nExample:\n ITEMS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n LENGTHS = [0, 2, 3, 1, 4]\n INDICES = [0, 2, 4]\n\n OUTPUT = [2, 3, 4, 6, 7, 8, 9]\n","inputs":[{"description":"items tensor","name":"ITEMS"},{"description":"lengths tensor","name":"LENGTHS"},{"description":"indices into LENGTHS where items should be gathered","name":"INDICES"}],"outputs":[{"description":"1-D tensor containing gathered items","name":"OUTPUT"}],"support_level":"default"}},{"name":"SequenceMask","schema":{"attributes":[{"description":"(string) Mode selection. Possible values: 'sequence', 'upper', 'lower', 'upperdiag', 'lowerdiag'","name":"mode","option":"optional"},{"description":"(int) Beginning axis of row elements. All dimensions to the left will be treated as row indices and those to the right (inclusive) will be treated as column indices in the 2D mask","name":"axis","option":"optional"},{"description":"(bool) operate in gradient mode","name":"grad","option":"optional"},{"description":"(int) radius of windows in window mode","name":"radius","option":"optional"},{"description":"(int) batch dimension of tensor (optional)","name":"batch","option":"optional"},{"description":"(int) used when mask should be repeated for one or more data dimensions (beginning at this axis). (currently only supported for sequence mode without batch argument)","name":"repeat_from_axis","option":"optional"}],"description":"\nMask op designed for use in attention mechanisms for sequence modeling tasks.\nSupports batching: given batch_dim, collapses dims 0 through batch_dim into a\nsingle dimension, e.g. if tensor dims are [4,2,1,3,4] and batch_dim=2, first\ncollapse tensor to [4*2*1,3,4], then mask each batch [i,:,:].\n\n\nTwo current operating modes:\n\n\n1) Given a 2D input tensor and 1D tensor of sequence lengths, for each row i in\nthe input tensor, set elements in that row to -inf if their column index\nj >= sequence_lengths[i]. This mode takes two inputs and argument mode =\n'sequence'\n\n\n2) Triangular mask. Given row index i and column index j, set elements to -inf\ngiven the following conditions:\n\n mode='upper', x_ij = -inf if j < i\n mode='lower', x_ij = -inf if j > i\n mode='upperdiag', x_ij = -inf if j <= i\n mode='lowerdiag', x_ij = -inf if j >= i\n\nThis mode takes one input.\n\n\n3) Window Mask. Given a 2D input tensor and 1D tensor of window centers,\nfor each row i in the input tensor, set elements in that row to -inf\nif their column index j outside [center - radius, center + radius].\nThis mode takes two inputs and argument mode = 'sequence'.\nArgument 'radius' should be provided.\n","inputs":[{"description":"Tensor to apply masking to","name":"input"},{"description":"1D Tensor of sequence lengths for mode #1","name":"sequence_lengths"}],"outputs":[{"description":"Input tensor with masking applied","name":"masked_tensor"}],"support_level":"default"}},{"name":"Int8Transpose","schema":{"attributes":[{"description":"Order to permute axes of input tensor. Reverses the dimensions by default.","name":"axes","option":"optional"},{"description":"Output tensor quantization scale","name":"Y_scale","option":"optional"},{"description":"Output tensor quantization offset","name":"Y_zero_point","option":"optional"}],"description":"\nTranspose the input tensor by permuting the axes of the input according\nto the `axes` argument. Similar to numpy's\n[transpose](https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)\nfunction.\n\nFor example, when axes=(1, 0, 2), given an input tensor of shape\n(1, 2, 3), the output shape will be (2, 1, 3).\n","inputs":[{"description":"Input tensor","name":"X"}],"outputs":[{"description":"Transposed output","name":"Y"}],"support_level":"default"}},{"name":"ResizeNearest3DGradient","schema":{"attributes":[{"description":"Scale along temporal dimension","name":"temporal_scale","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":null,"support_level":"default"}},{"name":"ResizeNearest3D","schema":{"attributes":[{"description":"Scale along temporal dimension","name":"temporal_scale","option":"optional"},{"description":"Scale along width dimension","name":"width_scale","option":"optional"},{"description":"Scale along height dimension","name":"height_scale","option":"optional"}],"description":"\nResizes the spatial dimensions of the input tensor using nearest neighbor\ninterpolation. The `width_scale` and `height_scale` arguments\ncontrol the size of the output, which is given by:\noutput_width = floor(input_width * width_scale)\noutput_height = floor(output_height * height_scale)\nAssumptions:\n - Only resize height and width\n - Both width_scale and height_scale scale are 2\n","inputs":[{"description":"Input tensor","name":"X"}],"outputs":[{"description":"Output tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchPermutation","schema":{"description":"\nBatch permutation of an input tensor X given input indices. First dimension of\nX equals batch size N. The indices stores a be permutation of N.\nThe output Y is a tensor of same shape as X, with data re-ordered according to\nthe indices within the batch size.\n\nExample of batch permutation on a 2-D tensor with batch size 4:\n X = [\n [1, 5, 2, 3, 4, 6, 0],\n [4, 3, 3, 5, 2, 3, 1],\n [2, 2, 3, 6, 0, 0, 1],\n [0, 0, 1, 1, 2, 2, 3]\n ]\n indices = [2, 0, 1, 3]\n Y = [\n [2, 2, 3, 6, 0, 0, 1],\n [1, 5, 2, 3, 4, 6, 0],\n [4, 3, 3, 5, 2, 3, 1],\n [0, 0, 1, 1, 2, 2, 3]\n ]\n\nExample of batch permutation on a 3-D tensor with batch size 4:\n X = [\n [[1, 5, 2], [3, 4, 6, 0]],\n [[4, 3, 3], [5, 2, 3, 1]],\n [[2, 2, 3], [6, 0, 0, 1]],\n [[0, 0, 1], [1, 2, 2, 3]]\n ]\n indices = [2, 0, 1, 3]\n Y = [\n [[2, 2, 3], [6, 0, 0, 1]],\n [[1, 5, 2], [3, 4, 6, 0]],\n [[4, 3, 3], [5, 2, 3, 1]],\n [[0, 0, 1], [1, 2, 2, 3]]\n ]\n","inputs":[{"description":"Input tensor, where 1st dimension equals batch size","name":"X"},{"description":"Input indices of batch to permute","name":"indices"}],"outputs":[{"description":"Output permuted tensor","name":"Y"}],"support_level":"default"}},{"name":"BatchPermutationGradient","schema":{"description":null,"support_level":"default"}},{"name":"AliasWithName","schema":{"attributes":[{"description":"name of the aliasing","name":"name","option":"optional"},{"description":"weather or not to alias forward or backward","name":"is_backward","option":"optional"}],"description":"\nSimilar with AliasOp, storing the alias name as operator argument.\n","inputs":[{"description":"Input tensor whose storage will be shared.","name":"input"}],"outputs":[{"description":"Tensor of same shape as input, sharing its storage.","name":"output"}],"support_level":"default"}},{"name":"RowWiseCounter","schema":{"attributes":[{"description":"Default -1: off","name":"counter_halflife","option":"optional"}],"description":"\n Count the number recent update on rows. Exponential decay is\n applied on the counter with decay rate r, such that\n r^{counter_halflife} = 0.5; If counter_halflife is nonpositive,\n this operator is turned off.\n","inputs":[{"description":"Iter at last update","name":"prev_iter"},{"description":"update counter","name":"update_counter"},{"description":"Sparse indices","name":"indices"},{"description":"current iteration","name":"iter"}],"outputs":[{"description":"Updated iter at last update","name":"output_prev_iter"},{"description":"Output update counter","name":"output_update_counter"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedHalfScaleBiasToHalfFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 16-bit float in the second to the last 2 bytes of each\nrow, followed by the bias as a 16-bit float in the next 2 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"FloatToFused8BitRowwiseQuantizedHalfScaleBias","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 4 bytes\nof each row in the output matrix are a half float storing the scale\nfollowed by another half float containing the scale.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"HalfFloatToFused8BitRowwiseQuantizedHalfScaleBias","schema":{"description":"\nApplies 8-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 8-bit number between 0 and\n255. To later de-quantize values, the scale (range / 255) and offset\n(bias) are stored alongside the data. More precisely, each row contains\nint8 elements for each quantized element, and the last 4 bytes\nof each row in the output matrix are a float storing the scale\nfollowed by another float containing the scale.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Fused8BitRowwiseQuantizedHalfScaleBiasToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused8BitRowwiseQuantized operator. The input is expected to\nencode the scale as a 16-bit float in the second to the last 2 bytes of each\nrow, followed by the bias as a 16-bit float in the next 2 bytes, and the\nquantized values in the preceding bytes of the row. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and bias\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"AtomicFetchAdd64","schema":{"description":"\nLike, AtomicFetchAdd but with int64_t scalar tensors,\nperforms an atomic fetch add\nby mutating the first argument and adding it to the second input\nargument. Returns the updated integer and the value prior to the update.\n","inputs":[{"description":"Blob containing to a unique_ptr","name":"mutex_ptr"},{"description":"Value to be mutated after the sum.","name":"mut_value"},{"description":"Value to add to the first operand.","name":"increment"}],"outputs":[{"description":"Mutated value after sum. Usually same as input 1.","name":"mut_value"},{"description":"Value of the first operand before sum.","name":"fetched_value"}],"support_level":"default"}},{"name":"Quantile","schema":{"attributes":[{"description":"If true (default), apply abs() on the tensor values.","name":"abs","option":"optional"},{"description":"multiplicative tolerance of the quantile_value.","name":"tol","option":"optional"}],"description":"\n Calculate the quantile for the value in the given list of tensors.\n","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"Value at the given quantile","name":"quantile_value"}],"support_level":"default"}},{"name":"SparseLengthsSumFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n2-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FloatToFused4BitRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 4-bit number between 0 and\n15. To later de-quantize values, the scale (range / 15) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 2-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n2-byte fp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"FloatToFused2BitRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 2-bit number between 0 and\n3. To later de-quantize values, the scale (range / 3) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 4-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n2-byte fp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMean4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 4-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMean2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 2-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 2-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused4BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused4BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"SparseLengthsMean8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsMean, but operating on 8-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 4-byte\nfp32 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused4BitRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 4-bit number between 0 and\n15. To later de-quantize values, the scale (range / 15) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSumFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsSum, but operating on\n4-bit rowwise quantized matrices with fused storage (where each row\nstores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused4BitRowwiseQuantizedToHalf","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused4BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 4-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused2BitFakeRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise fake quantization to a tensor of half floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"FloatToFused2BitFakeRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise fake quantization to a tensor of floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"FloatToFused4BitFakeRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise fake quantization to a tensor of floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float32 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"Fused2BitRowwiseQuantizedToFloat","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused2BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float32 data","name":"float_output"}],"support_level":"default"}},{"name":"SparseLengthsSum4BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 4-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and 2-byte fp16 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused2BitRowwiseQuantized","schema":{"description":"\nApplies 2-bit row-wise quantization by determining the range\n(maximum - minimum) and offset (minimum value) of each row in the input\nmatrix, and then scaling each element to an 2-bit number between 0 and\n3. To later de-quantize values, the scale (range / 3) and zero_point\nare stored alongside the data. More precisely, each row first has quantized\nvalues, and then 2-byte fp16 scale and 2-byte zero_offset.)\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsMeanFused2BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsMean, but\noperating on 2-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSumFused4BitRowwise","schema":{"description":"\nPerforms the same operation as SparseLengthsWeightedSum,\nbut operating on 4-bit rowwise quantized matrices with fused storage\n(where each row stores quantized values, and then 2-byte fp16 scale and bias).\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSum8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 8-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 4-byte\nfp32 scale and 4-byte fp32 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsSum2BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsSum, but operating on 2-bit rowwise quantized matrices\nwith fused storage (where each row stores quantized values, and then 2-byte\nfp16 scale and 2-byte fp16 bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused2BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"HalfToFused4BitFakeRowwiseQuantized","schema":{"description":"\nApplies 4-bit row-wise fake quantization to a tensor of half floats.\nThe output looks like an int8 rowwise quantized blob with\nscale and biases in half float.\n","inputs":[{"description":"Float16 input data","name":"input"}],"outputs":[{"description":"Fused scale, bias and quantized data","name":"output"}],"support_level":"default"}},{"name":"SparseLengthsWeightedSum8BitRowwiseSparse","schema":{"description":"\nPerforms SparseLengthsWeightedSum, but operating on 8-bit rowwise quantized\nmatrices with fused storage (where each row stores quantized values, and then\n4-byte fp32 scale and bias), and where rows are pruned.\n","inputs":[{"description":"uint8 tensor obtained with operator FloatToFused4BitRowwiseQuantized","name":"DATA"},{"description":"Integer vector containing indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of DATA","name":"LENGTHS"},{"description":"Vector of weights to scale rows of DATA with before reduction","name":"WEIGHTS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"}],"outputs":[{"description":"output","name":"output"}],"support_level":"default"}},{"name":"Fused2BitRowwiseQuantizedToHalf","schema":{"description":"\nDe-quantizes the result of the\nFloatToFused2BitRowwiseQuantized operator. The input is expected to first have\nquantized values, then 2-byte fp16 scale and 1-byte zero_offset. The output is a\nmatrix containing only the values, but de-quantized. De-quantization is\nperformed by multiplying each value by its row's scale and zero_point\nparameters. The de-quantized values will thus not be exactly equal to\nthe original, un-quantized floating point values.\n","inputs":[{"description":"Fused scale, bias and quantized data","name":"scale_bias_quantized_input"}],"outputs":[{"description":"Float16 data","name":"float16_output"}],"support_level":"default"}},{"name":"WeightScale","schema":{"attributes":[{"description":"Every iteration number to do weight scaling","name":"stepsize","option":"optional"},{"description":"After iter passes this bound, do not perform the weight rescaling","name":"upper_bound_iter","option":"optional"},{"description":"The multiplicative factor applied to weights.","name":"scale","option":"optional"}],"description":"\nEvery `stepsize` iterations, multiply the weights by a constant `scale`:\n nw = w * scale\n","inputs":[{"description":"Current weights","name":"w"},{"description":"Training Iteration","name":"iter"}],"outputs":[{"description":"Updated weights","name":"nw"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsWeightedSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nApproximately fused operator of\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + SparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere's race condition w.r.t. ordering between reading params and writing to\nparam, hence the name Approx.\nThere're auxiliary inputs (aux_param) for which gradient is computed and\nreturns (aux_grad).\nYet additional input (lengths) is for fused\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradients","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsWeightedSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + RowWiseSparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere're auxiliary inputs (aux_param) for which gradient is computed and\nreturns (aux_grad).\nYet additional input (lengths) is for fused SparseLengthsWeightedSumGradient\noperator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"},{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsWeightedSumGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + SparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere're auxiliary inputs (aux_param) for which gradient is computed\nand returns (aux_grad).\nYet additional input (lengths) is for fused\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsWeightedSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nApproximately fused operator of\nSparseLengthsIndicesInGradientWeightedSumWithMainInputGradient\n(gradient of SparseLengthsWeightedSum) + RowWiseSparseAdagrad, where weights are\npositional weights computed with LengthsRangeFill + Gather pattern.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case.\nThere's race condition w.r.t. ordering between reading params and writing to\nparam, hence the name Approx.\nThere're auxiliary inputs (aux_param) for which gradient is computed\nand returns (aux_grad).\nYet additional input (lengths) is for fused SparseLengthsWeightedSumGradient\noperator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Auxiliary parameters to be updated","name":"aux_param"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"},{"description":"Auxiliary gradient","name":"aux_grad"}],"support_level":"default"}},{"name":"SparseLengthsSumSparseLookup","schema":{"description":"\nThis op converts compressed indices of SparseLengthsSum*Sparse to\nuncompressed indices of SparseLengthsSum*. For compressed indices that maps\nto -1. It means it will correspond to a zero row in the uncompressed data.\nTherefore we will remove this indices and adjust the lengths.\n","inputs":[{"description":"Integer vector containing compressed indices of the first dimension of DATA for the slices that are being aggregated","name":"INDICES"},{"description":"Vector with the same sum of elements as the first dimension of INDICES","name":"LENGTHS"},{"description":"Integer vector mapping uncompressed indices to compressed indices","name":"COMPRESSED_INDICES_MAPPING"},{"description":"Vector of weights to scale rows of DATA with before reduction. Same size as INDICES.","name":"WEIGHTS"}],"outputs":[{"description":"Uncompressed indices","name":"output_indices"},{"description":"Adjusted lengths","name":"output_lengths"},{"description":"Adjusted weights","name":"output_weights"}],"support_level":"default"}},{"name":"Storm","schema":{"attributes":[{"description":"Momentum hyperparameter, c in the original paper.","name":"momentum","option":"optional"},{"description":"denominator in adaptive learning rate, w in the original paper.","name":"beta","option":"optional"}],"description":"\n\nComputes the STORM (https://arxiv.org/abs/1905.10018) update for an input\ngradient and accumulated history of gradients. Concretely, given inputs\n(param, moment, grad_sq_sum, grad, lr), computes:\n\n new_grad_sq_sum = grad_sq_sum + norm(grad)^2\n effective_lr = lr / (beta + new_grad_sq_sum)^1/3\n alpha = momentum * square(effective_lr)\n new_moment = grad + (1 - alpha) * (moment - grad)\n new_param = param + effective_lr * new_moment\n\nand returns (new_param, new_moment, new_grad_sq_sum).\n\nNote that due to caffe2 limitation, it is difficult to re-calculate gradient\nin the previous iteration using the current example. We simplied calculation\nfor new_moment by using the gradient from the current iteration.\n\n","inputs":[{"description":"Parameters to be updated.","name":"param"},{"description":"Moment history.","name":"moment"},{"description":"Sum of observed squared gradients.","name":"grad_sq_sum"},{"description":"Gradients computed.","name":"grad"},{"description":"Learning rate, k in the original paper.","name":"lr"}],"outputs":[{"description":"Updated parameters.","name":"output_param"},{"description":"Updated moment.","name":"output_moment"},{"description":"Updated sum of squared gradients.","name":"output_grad_sq_sum"}],"support_level":"default"}},{"name":"SparseStorm","schema":{"attributes":[{"description":"Momentum hyperparameter, c in the original paper.","name":"momentum","option":"optional"},{"description":"denominator in adaptive learning rate, w in the original paper.","name":"beta","option":"optional"}],"description":"\n\nThis operator implement the STORM (https://arxiv.org/abs/1905.10018)\noptimization algorithm. Given inputs (param, moment, grad_sq_sum, grad,\nindices, lr), computes the dense STORM update on (param, moment[indices],\ngrad_sq_sum, grad, lr), and returns (new_param, new_moment, new_grad_sq_sum)\nas in the dense case.\n","inputs":[{"description":"Parameters to be updated.","name":"param"},{"description":"Moment history.","name":"moment"},{"description":"Sum of observed squared gradients.","name":"grad_sq_sum"},{"description":"Gradients computed.","name":"grad"},{"description":"Sparse indices.","name":"indices"},{"description":"Learning rate, k in the original paper.","name":"lr"}],"outputs":[{"description":"Updated parameters.","name":"output_param"},{"description":"Updated moment.","name":"output_moment"},{"description":"Updated sum of squared gradients.","name":"output_grad_sq_sum"}],"support_level":"default"}},{"name":"FbGemmPackTranspose","schema":{"description":"Prepack weight for fbgemm","inputs":[{"description":"col major format weight matrix","name":"X"}],"outputs":[{"description":"Block col major packed format weight matrix","name":"Y"}],"support_level":"default"}},{"name":"FbGemmPack","schema":{"description":"Prepack weight for fbgemm","inputs":[{"description":"row major format weight matrix","name":"X"}],"outputs":[{"description":"Block row major packed format weight matrix","name":"Y"}],"support_level":"default"}},{"name":"FbFCPacked","schema":{"description":"Same as FC,\n but the weight is prepacked as a fbgemm::PackedGemmMatrixFP16","support_level":"default"}},{"name":"Histogram","schema":{"attributes":[{"description":"length-(k + 1) sequence of float values wherein the i-th element represents the inclusive left boundary of the i-th bin for i in [0, k - 1] and the exclusive right boundary of the (i-1)-th bin for i in [1, k].","name":"bin_edges","option":"optional"}],"description":"\n Computes a histogram for values in the given list of tensors.\n For logging activation histograms for post-hoc analyses, consider using the\n HistogramObserver observer.\n For iteratively computing a histogram for all input tensors encountered through\n history, consider using the AccumulateHistogram operator.\n ","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"1D tensor of length k, wherein the i-th element expresses the count of tensor values that fall within range [bin_edges[i], bin_edges[i + 1])","name":"histogram"}],"support_level":"default"}},{"name":"SparseLpRegularizer","schema":{"attributes":[{"description":"Value of p in the Lp regularization to use. The default is 2.0.","name":"p","option":"optional"},{"description":"Value of lambda (multiplier for the regularization term). The default is 1e-5.","name":"reg_lambda","option":"optional"}],"description":"\nGiven a sparse matrix, apply Lp regularization. Currently only L1 and L2 are implemented.\n","inputs":[{"description":"Parameters to be regularized","name":"param"},{"description":"Sparse indices","name":"indices"},{"description":"Gradient computed (optional - not used, this argument is for backwards compatibility)","name":"grad"}],"outputs":[{"description":"Regularized parameters","name":"output_param"}],"support_level":"default"}},{"name":"Int8GenQuantParams","schema":{"description":"Operator wrapper for generating int8 tensor quantization parameters given the input data and quant scheme","inputs":[{"description":"The input data, or last N samples of the output activations.","name":"X"},{"description":"Int8QuantSchemeBlob that specifies the quantization kind and preserve_sparsity options when generating the quant params.","name":"quant_scheme"}],"outputs":[{"description":"Int8QuantParamsBlob that contains the scale and zero_point info in TensorQuantizationParams type.","name":"quant_param"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsSumGradientApprox","schema":{"attributes":[{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsSumGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientSumGradient (gradient of SparseLengthsSum) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientSumGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"MishGradient","schema":{"description":"\nMishGradient takes X, Y and dY and uses this to update dX according to the\nchain rule and derivatives of the Mish function.\n","support_level":"default"}},{"name":"SelfBinningHistogram","schema":{"attributes":[{"description":"Number of bins to use for the histogram. Must be >= 1.","name":"num_bins","option":"optional"},{"description":"A string indicating 'linear' or 'logarithmic' spacing for the bins.","name":"bin_spacing","option":"optional"},{"description":"A float that's used as the starting point for logarithmic spacing. Since logarithmic spacing cannot contain <=0 values this value will be used to represent all such values.","name":"logspace_start","option":"optional"}],"description":"\n Computes a histogram for values in the given list of tensors.\n For logging activation histograms for post-hoc analyses, consider using the\n HistogramObserver observer.\n For iteratively computing a histogram for all input tensors encountered through\n history, consider using the AccumulateHistogram operator.\n ","inputs":[{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"1D tensor of edges of the bins, of dimension [num_bins+1]. The range appears as: [first, ..., last), wherein the i-th element expresses the start of a bin and i+1-th value represents the exclusive end of that bin.","name":"histogram_values"},{"description":"1D tensor of counts of each bin, of dimension [num_bins+1]. It is guaranteed to end with a 0 since the last edge is exclusive.","name":"histogram_counts"}],"support_level":"default"}},{"name":"Mish","schema":{"description":"\nMish takes one input data (Tensor) and produces one output data\n(Tensor) where the Mish function, y = x / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","inputs":[{"description":"1D input tensor","name":"X"}],"outputs":[{"description":"1D output tensor","name":"Y"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsMeanGradientApprox","schema":{"attributes":[{"description":"rounding option: 0 for nearest rounding, 1 for stochastic rounding","name":"round_option","option":"optional"},{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsMeanGradientApprox","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"SparseAdagradFusedWithSparseLengthsMeanGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the sparse AdaGrad\nupdate on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsIndicesInGradientMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}},{"name":"RowWiseSparseAdagradFusedWithSparseLengthsMeanGradient","schema":{"attributes":[{"description":"Default 1e-5","name":"epsilon","option":"optional"}],"description":"\n\nFused operator of\nSparseLengthsIndicesInGradientMeanGradient (gradient of SparseLengthsMean) +\nRowWiseSparseAdagrad.\n\nGiven inputs (param, moment, indices, grad, lr), runs the row-wise sparse\nAdaGrad update on (param, grad, moment[indices], lr), and returns (new_param,\nnew_moment) as in the dense case. Additional input (lengths) is for fused\nSparseLengthsMeanGradient operator.\n\n","inputs":[{"description":"Parameters to be updated","name":"param"},{"description":"Moment history","name":"moment"},{"description":"Integer vector containing indices of the first dimension of param for the slices that are being updated","name":"indices"},{"description":"Gradient computed","name":"grad"},{"description":"learning rate","name":"lr"},{"description":"Non negative vector with sum of elements equal to indices length","name":"lengths"}],"outputs":[{"description":"Updated parameters","name":"output_param"},{"description":"Updated moment","name":"output_moment"}],"support_level":"default"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..559579d5546c75d53e478646f4c3a19d329cb879 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("caffe2");$root.caffe2={},$root.caffe2.ExternalDataProto=class{constructor(){this.strides=[]}static decode(e,t){const o=new $root.caffe2.ExternalDataProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.source_type=e.int32();break;case 2:o.record_id=e.string();break;case 5:o.record_size=e.uint64();break;case 3:o.offset=e.int64();break;case 4:o.strides=e.array(o.strides,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.ExternalDataProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"source_type":t.source_type=e.enum($root.caffe2.ExternalDataProto.SourceType);break;case"record_id":t.record_id=e.string();break;case"record_size":t.record_size=e.integer();break;case"offset":t.offset=e.integer();break;case"strides":e.array(t.strides,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.caffe2.ExternalDataProto.prototype.source_type=0,$root.caffe2.ExternalDataProto.prototype.record_id="",$root.caffe2.ExternalDataProto.prototype.record_size=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.caffe2.ExternalDataProto.prototype.offset=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExternalDataProto.SourceType={INLINE_CONTAINER:0,SIMPLE_FILE:1},$root.caffe2.TensorProto=class{constructor(){this.dims=[],this.float_data=[],this.int32_data=[],this.string_data=[],this.double_data=[],this.int64_data=[]}static decode(e,t){const o=new $root.caffe2.TensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.data_type=e.int32();break;case 12:o.storage_type=e.int32();break;case 3:o.float_data=e.floats(o.float_data,t);break;case 4:o.int32_data=e.array(o.int32_data,(()=>e.int32()),t);break;case 5:o.byte_data=e.bytes();break;case 6:o.string_data.push(e.bytes());break;case 9:o.double_data=e.doubles(o.double_data,t);break;case 10:o.int64_data=e.array(o.int64_data,(()=>e.int64()),t);break;case 13:o.raw_data=e.bytes();break;case 14:o.external_data=$root.caffe2.ExternalDataProto.decode(e,e.uint32());break;case 7:o.name=e.string();break;case 8:o.device_detail=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 11:o.segment=$root.caffe2.TensorProto.Segment.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"storage_type":t.storage_type=e.enum($root.caffe2.TensorProto.StorageType);break;case"float_data":e.array(t.float_data,(()=>e.float()));break;case"int32_data":e.array(t.int32_data,(()=>e.integer()));break;case"byte_data":t.byte_data=e.bytes();break;case"string_data":e.array(t.string_data,(()=>e.bytes()));break;case"double_data":e.array(t.double_data,(()=>e.float()));break;case"int64_data":e.array(t.int64_data,(()=>e.integer()));break;case"raw_data":t.raw_data=e.bytes();break;case"external_data":t.external_data=$root.caffe2.ExternalDataProto.decodeText(e,!0);break;case"name":t.name=e.string();break;case"device_detail":t.device_detail=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"segment":t.segment=$root.caffe2.TensorProto.Segment.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.caffe2.TensorProto.prototype.data_type=1,$root.caffe2.TensorProto.prototype.storage_type=1,$root.caffe2.TensorProto.prototype.byte_data=new Uint8Array([]),$root.caffe2.TensorProto.prototype.raw_data=new Uint8Array([]),$root.caffe2.TensorProto.prototype.external_data=null,$root.caffe2.TensorProto.prototype.name="",$root.caffe2.TensorProto.prototype.device_detail=null,$root.caffe2.TensorProto.prototype.segment=null,$root.caffe2.TensorProto.DataType={UNDEFINED:0,FLOAT:1,INT32:2,BYTE:3,STRING:4,BOOL:5,UINT8:6,INT8:7,UINT16:8,INT16:9,INT64:10,FLOAT16:12,DOUBLE:13,ZERO_COLLISION_HASH:14},$root.caffe2.TensorProto.StorageType={TYPED:1,RAW:2,EXTERNAL:3,NO_CONTENT:4},$root.caffe2.TensorProto.Segment=class{constructor(){}static decode(e,t){const o=new $root.caffe2.TensorProto.Segment,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.begin=e.int64();break;case 2:o.end=e.int64();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"begin"))throw new protobuf.Error("Excepted 'begin'.");if(!Object.prototype.hasOwnProperty.call(o,"end"))throw new protobuf.Error("Excepted 'end'.");return o}static decodeText(e){const t=new $root.caffe2.TensorProto.Segment;for(e.start();!e.end();){const o=e.tag();switch(o){case"begin":t.begin=e.integer();break;case"end":t.end=e.integer();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"begin"))throw new protobuf.Error("Excepted 'begin'.");if(!Object.prototype.hasOwnProperty.call(t,"end"))throw new protobuf.Error("Excepted 'end'.");return t}},$root.caffe2.TensorProto.Segment.prototype.begin=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.TensorProto.Segment.prototype.end=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.QTensorProto=class{constructor(){this.dims=[],this.data=[],this.scales=[],this.biases=[]}static decode(e,t){const o=new $root.caffe2.QTensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.precision=e.int32();break;case 3:o.scale=e.double();break;case 4:o.bias=e.double();break;case 5:o.is_signed=e.bool();break;case 6:o.data=e.array(o.data,(()=>e.int32()),t);break;case 7:o.name=e.string();break;case 8:o.data_type=e.int32();break;case 9:o.scales=e.doubles(o.scales,t);break;case 10:o.biases=e.doubles(o.biases,t);break;case 11:o.axis=e.int32();break;case 12:o.is_multiparam=e.bool();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"precision"))throw new protobuf.Error("Excepted 'precision'.");if(!Object.prototype.hasOwnProperty.call(o,"scale"))throw new protobuf.Error("Excepted 'scale'.");if(!Object.prototype.hasOwnProperty.call(o,"bias"))throw new protobuf.Error("Excepted 'bias'.");if(!Object.prototype.hasOwnProperty.call(o,"is_signed"))throw new protobuf.Error("Excepted 'is_signed'.");return o}static decodeText(e){const t=new $root.caffe2.QTensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"precision":t.precision=e.integer();break;case"scale":t.scale=e.float();break;case"bias":t.bias=e.float();break;case"is_signed":t.is_signed=e.boolean();break;case"data":e.array(t.data,(()=>e.integer()));break;case"name":t.name=e.string();break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"scales":e.array(t.scales,(()=>e.float()));break;case"biases":e.array(t.biases,(()=>e.float()));break;case"axis":t.axis=e.integer();break;case"is_multiparam":t.is_multiparam=e.boolean();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"precision"))throw new protobuf.Error("Excepted 'precision'.");if(!Object.prototype.hasOwnProperty.call(t,"scale"))throw new protobuf.Error("Excepted 'scale'.");if(!Object.prototype.hasOwnProperty.call(t,"bias"))throw new protobuf.Error("Excepted 'bias'.");if(!Object.prototype.hasOwnProperty.call(t,"is_signed"))throw new protobuf.Error("Excepted 'is_signed'.");return t}},$root.caffe2.QTensorProto.prototype.precision=0,$root.caffe2.QTensorProto.prototype.scale=0,$root.caffe2.QTensorProto.prototype.bias=0,$root.caffe2.QTensorProto.prototype.is_signed=!1,$root.caffe2.QTensorProto.prototype.name="",$root.caffe2.QTensorProto.prototype.data_type=2,$root.caffe2.QTensorProto.prototype.axis=0,$root.caffe2.QTensorProto.prototype.is_multiparam=!1,$root.caffe2.TensorProtos=class{constructor(){this.protos=[]}static decode(e,t){const o=new $root.caffe2.TensorProtos,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.protos.push($root.caffe2.TensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorProtos;for(e.start();!e.end();){const o=e.tag();switch(o){case"protos":t.protos.push($root.caffe2.TensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.TensorShape=class{constructor(){this.dims=[],this.unknown_dims=[]}static decode(e,t){const o=new $root.caffe2.TensorShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dims=e.array(o.dims,(()=>e.int64()),t);break;case 2:o.data_type=e.int32();break;case 3:o.unknown_dims=e.array(o.unknown_dims,(()=>e.int32()),t);break;case 4:o.unknown_shape=e.bool();break;case 5:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"dims":e.array(t.dims,(()=>e.integer()));break;case"data_type":t.data_type=e.enum($root.caffe2.TensorProto.DataType);break;case"unknown_dims":e.array(t.unknown_dims,(()=>e.integer()));break;case"unknown_shape":t.unknown_shape=e.boolean();break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorShape.prototype.data_type=1,$root.caffe2.TensorShape.prototype.unknown_shape=!1,$root.caffe2.TensorShape.prototype.name="",$root.caffe2.TensorShapes=class{constructor(){this.shapes=[]}static decode(e,t){const o=new $root.caffe2.TensorShapes,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shapes.push($root.caffe2.TensorShape.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorShapes;for(e.start();!e.end();){const o=e.tag();switch(o){case"shapes":t.shapes.push($root.caffe2.TensorShape.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShape=class{constructor(){this.dim_type=[]}static decode(e,t){const o=new $root.caffe2.TensorBoundShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shape=$root.caffe2.TensorShape.decode(e,e.uint32());break;case 2:o.dim_type=e.array(o.dim_type,(()=>e.int32()),t);break;case 3:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorBoundShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"shape":t.shape=$root.caffe2.TensorShape.decodeText(e,!0);break;case"dim_type":e.array(t.dim_type,(()=>e.enum($root.caffe2.TensorBoundShape.DimType)));break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShape.prototype.shape=null,$root.caffe2.TensorBoundShape.prototype.name="",$root.caffe2.TensorBoundShape.DimType={UNKNOWN:0,CONSTANT:1,BATCH:2,BATCH_OF_FEATURE_MAX:3,BATCH_OF_FEATURE_MAX_DEFAULT:4,FEATURE_MAX:5,FEATURE_MAX_DEFAULT:6},$root.caffe2.TensorBoundShapes=class{constructor(){this.shapes=[]}static decode(e,t){const o=new $root.caffe2.TensorBoundShapes,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.shapes.push($root.caffe2.TensorBoundShape.decode(e,e.uint32()));break;case 2:o.max_batch_size=e.int64();break;case 3:o.max_feature_len=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.TensorBoundShapes;for(e.start();!e.end();){const o=e.tag();switch(o){case"shapes":t.shapes.push($root.caffe2.TensorBoundShape.decodeText(e,!0));break;case"max_batch_size":t.max_batch_size=e.integer();break;case"max_feature_len":t.max_feature_len=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.TensorBoundShapes.prototype.max_batch_size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.TensorBoundShapes.prototype.max_feature_len=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.Argument=class{constructor(){this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.nets=[],this.qtensors=[]}static decode(e,t){const o=new $root.caffe2.Argument,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.f=e.float();break;case 3:o.i=e.int64();break;case 4:o.s=e.bytes();break;case 10:o.t=$root.caffe2.TensorProto.decode(e,e.uint32());break;case 8:o.n=$root.caffe2.NetDef.decode(e,e.uint32());break;case 5:o.floats=e.floats(o.floats,t);break;case 6:o.ints=e.array(o.ints,(()=>e.int64()),t);break;case 7:o.strings.push(e.bytes());break;case 11:o.tensors.push($root.caffe2.TensorProto.decode(e,e.uint32()));break;case 9:o.nets.push($root.caffe2.NetDef.decode(e,e.uint32()));break;case 12:o.qtensors.push($root.caffe2.QTensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.Argument;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"f":t.f=e.float();break;case"i":t.i=e.integer();break;case"s":t.s=e.bytes();break;case"t":t.t=$root.caffe2.TensorProto.decodeText(e,!0);break;case"n":t.n=$root.caffe2.NetDef.decodeText(e,!0);break;case"floats":e.array(t.floats,(()=>e.float()));break;case"ints":e.array(t.ints,(()=>e.integer()));break;case"strings":e.array(t.strings,(()=>e.bytes()));break;case"tensors":t.tensors.push($root.caffe2.TensorProto.decodeText(e,!0));break;case"nets":t.nets.push($root.caffe2.NetDef.decodeText(e,!0));break;case"qtensors":t.qtensors.push($root.caffe2.QTensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.Argument.prototype.name="",$root.caffe2.Argument.prototype.f=0,$root.caffe2.Argument.prototype.i=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.Argument.prototype.s=new Uint8Array([]),$root.caffe2.Argument.prototype.t=null,$root.caffe2.Argument.prototype.n=null,$root.caffe2.DeviceTypeProto={PROTO_CPU:0,PROTO_CUDA:1,PROTO_MKLDNN:2,PROTO_OPENGL:3,PROTO_OPENCL:4,PROTO_IDEEP:5,PROTO_HIP:6,PROTO_FPGA:7,PROTO_MSNPU:8,PROTO_XLA:9,PROTO_COMPILE_TIME_MAX_DEVICE_TYPES:10,PROTO_ONLY_FOR_TEST:20901},$root.caffe2.DeviceOption=class{constructor(){this.extra_info=[]}static decode(e,t){const o=new $root.caffe2.DeviceOption,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device_type=e.int32();break;case 2:o.device_id=e.int32();break;case 3:o.random_seed=e.uint32();break;case 4:o.node_name=e.string();break;case 5:o.numa_node_id=e.int32();break;case 6:o.extra_info.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.DeviceOption;for(e.start();!e.end();){const o=e.tag();switch(o){case"device_type":t.device_type=e.integer();break;case"device_id":t.device_id=e.integer();break;case"random_seed":t.random_seed=e.integer();break;case"node_name":t.node_name=e.string();break;case"numa_node_id":t.numa_node_id=e.integer();break;case"extra_info":e.array(t.extra_info,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.caffe2.DeviceOption.prototype.device_type=0,$root.caffe2.DeviceOption.prototype.device_id=0,$root.caffe2.DeviceOption.prototype.random_seed=0,$root.caffe2.DeviceOption.prototype.node_name="",$root.caffe2.DeviceOption.prototype.numa_node_id=0,$root.caffe2.OperatorDef=class{constructor(){this.input=[],this.output=[],this.arg=[],this.control_input=[]}static decode(e,t){const o=new $root.caffe2.OperatorDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.input.push(e.string());break;case 2:o.output.push(e.string());break;case 3:o.name=e.string();break;case 4:o.type=e.string();break;case 5:o.arg.push($root.caffe2.Argument.decode(e,e.uint32()));break;case 6:o.device_option=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 7:o.engine=e.string();break;case 8:o.control_input.push(e.string());break;case 9:o.is_gradient_op=e.bool();break;case 10:o.debug_info=e.string();break;case 11:o.domain=e.string();break;case 12:o.op_version=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.OperatorDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"input":e.array(t.input,(()=>e.string()));break;case"output":e.array(t.output,(()=>e.string()));break;case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"arg":t.arg.push($root.caffe2.Argument.decodeText(e,!0));break;case"device_option":t.device_option=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"engine":t.engine=e.string();break;case"control_input":e.array(t.control_input,(()=>e.string()));break;case"is_gradient_op":t.is_gradient_op=e.boolean();break;case"debug_info":t.debug_info=e.string();break;case"domain":t.domain=e.string();break;case"op_version":t.op_version=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.OperatorDef.prototype.name="",$root.caffe2.OperatorDef.prototype.type="",$root.caffe2.OperatorDef.prototype.device_option=null,$root.caffe2.OperatorDef.prototype.engine="",$root.caffe2.OperatorDef.prototype.is_gradient_op=!1,$root.caffe2.OperatorDef.prototype.debug_info="",$root.caffe2.OperatorDef.prototype.domain="",$root.caffe2.OperatorDef.prototype.op_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.MapFieldEntry=class{constructor(){}static decode(e,t){const o=new $root.caffe2.MapFieldEntry,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.key=e.string();break;case 2:o.val=e.string();break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"key"))throw new protobuf.Error("Excepted 'key'.");if(!Object.prototype.hasOwnProperty.call(o,"val"))throw new protobuf.Error("Excepted 'val'.");return o}static decodeText(e){const t=new $root.caffe2.MapFieldEntry;for(e.start();!e.end();){const o=e.tag();switch(o){case"key":t.key=e.string();break;case"val":t.val=e.string();break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"key"))throw new protobuf.Error("Excepted 'key'.");if(!Object.prototype.hasOwnProperty.call(t,"val"))throw new protobuf.Error("Excepted 'val'.");return t}},$root.caffe2.MapFieldEntry.prototype.key="",$root.caffe2.MapFieldEntry.prototype.val="",$root.caffe2.BackendOptions=class{constructor(){this.option=[]}static decode(e,t){const o=new $root.caffe2.BackendOptions,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.backend_name=e.string();break;case 2:o.option.push($root.caffe2.MapFieldEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"backend_name"))throw new protobuf.Error("Excepted 'backend_name'.");return o}static decodeText(e){const t=new $root.caffe2.BackendOptions;for(e.start();!e.end();){const o=e.tag();switch(o){case"backend_name":t.backend_name=e.string();break;case"option":t.option.push($root.caffe2.MapFieldEntry.decodeText(e,!0));break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"backend_name"))throw new protobuf.Error("Excepted 'backend_name'.");return t}},$root.caffe2.BackendOptions.prototype.backend_name="",$root.caffe2.PartitionInfo=class{constructor(){this.device_id=[],this.backend_options=[]}static decode(e,t){const o=new $root.caffe2.PartitionInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.device_id=e.array(o.device_id,(()=>e.int32()),t);break;case 3:o.extra_info=e.string();break;case 4:o.backend_options.push($root.caffe2.BackendOptions.decode(e,e.uint32()));break;default:e.skipType(7&t)}}if(!Object.prototype.hasOwnProperty.call(o,"name"))throw new protobuf.Error("Excepted 'name'.");return o}static decodeText(e){const t=new $root.caffe2.PartitionInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"device_id":e.array(t.device_id,(()=>e.integer()));break;case"extra_info":t.extra_info=e.string();break;case"backend_options":t.backend_options.push($root.caffe2.BackendOptions.decodeText(e,!0));break;default:e.field(o,t)}}if(!Object.prototype.hasOwnProperty.call(t,"name"))throw new protobuf.Error("Excepted 'name'.");return t}},$root.caffe2.PartitionInfo.prototype.name="",$root.caffe2.PartitionInfo.prototype.extra_info="",$root.caffe2.NetDef=class{constructor(){this.op=[],this.arg=[],this.external_input=[],this.external_output=[],this.partition_info=[]}static decode(e,t){const o=new $root.caffe2.NetDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.op.push($root.caffe2.OperatorDef.decode(e,e.uint32()));break;case 3:o.type=e.string();break;case 4:o.num_workers=e.int32();break;case 5:o.device_option=$root.caffe2.DeviceOption.decode(e,e.uint32());break;case 6:o.arg.push($root.caffe2.Argument.decode(e,e.uint32()));break;case 7:o.external_input.push(e.string());break;case 8:o.external_output.push(e.string());break;case 9:o.partition_info.push($root.caffe2.PartitionInfo.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.NetDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"op":t.op.push($root.caffe2.OperatorDef.decodeText(e,!0));break;case"type":t.type=e.string();break;case"num_workers":t.num_workers=e.integer();break;case"device_option":t.device_option=$root.caffe2.DeviceOption.decodeText(e,!0);break;case"arg":t.arg.push($root.caffe2.Argument.decodeText(e,!0));break;case"external_input":e.array(t.external_input,(()=>e.string()));break;case"external_output":e.array(t.external_output,(()=>e.string()));break;case"partition_info":t.partition_info.push($root.caffe2.PartitionInfo.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.NetDef.prototype.name="",$root.caffe2.NetDef.prototype.type="",$root.caffe2.NetDef.prototype.num_workers=0,$root.caffe2.NetDef.prototype.device_option=null,$root.caffe2.ExecutionStep=class{constructor(){this.substep=[],this.network=[]}static decode(e,t){const o=new $root.caffe2.ExecutionStep,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.substep.push($root.caffe2.ExecutionStep.decode(e,e.uint32()));break;case 3:o.network.push(e.string());break;case 4:o.num_iter=e.int64();break;case 5:o.criteria_network=e.string();break;case 7:o.report_net=e.string();break;case 8:o.report_interval=e.int32();break;case 11:o.run_every_ms=e.int64();break;case 6:o.concurrent_substeps=e.bool();break;case 9:o.should_stop_blob=e.string();break;case 10:o.only_once=e.bool();break;case 12:o.create_workspace=e.bool();break;case 13:o.num_concurrent_instances=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.ExecutionStep;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"substep":t.substep.push($root.caffe2.ExecutionStep.decodeText(e,!0));break;case"network":e.array(t.network,(()=>e.string()));break;case"num_iter":t.num_iter=e.integer();break;case"criteria_network":t.criteria_network=e.string();break;case"report_net":t.report_net=e.string();break;case"report_interval":t.report_interval=e.integer();break;case"run_every_ms":t.run_every_ms=e.integer();break;case"concurrent_substeps":t.concurrent_substeps=e.boolean();break;case"should_stop_blob":t.should_stop_blob=e.string();break;case"only_once":t.only_once=e.boolean();break;case"create_workspace":t.create_workspace=e.boolean();break;case"num_concurrent_instances":t.num_concurrent_instances=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.ExecutionStep.prototype.name="",$root.caffe2.ExecutionStep.prototype.num_iter=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExecutionStep.prototype.criteria_network="",$root.caffe2.ExecutionStep.prototype.report_net="",$root.caffe2.ExecutionStep.prototype.report_interval=0,$root.caffe2.ExecutionStep.prototype.run_every_ms=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.caffe2.ExecutionStep.prototype.concurrent_substeps=!1,$root.caffe2.ExecutionStep.prototype.should_stop_blob="",$root.caffe2.ExecutionStep.prototype.only_once=!1,$root.caffe2.ExecutionStep.prototype.create_workspace=!1,$root.caffe2.ExecutionStep.prototype.num_concurrent_instances=0,$root.caffe2.PlanDef=class{constructor(){this.network=[],this.execution_step=[]}static decode(e,t){const o=new $root.caffe2.PlanDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.network.push($root.caffe2.NetDef.decode(e,e.uint32()));break;case 3:o.execution_step.push($root.caffe2.ExecutionStep.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.PlanDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"network":t.network.push($root.caffe2.NetDef.decodeText(e,!0));break;case"execution_step":t.execution_step.push($root.caffe2.ExecutionStep.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.caffe2.PlanDef.prototype.name="",$root.caffe2.BlobProto=class{constructor(){}static decode(e,t){const o=new $root.caffe2.BlobProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.type=e.string();break;case 3:o.tensor=$root.caffe2.TensorProto.decode(e,e.uint32());break;case 4:o.content=e.bytes();break;case 5:o.qtensor=$root.caffe2.QTensorProto.decode(e,e.uint32());break;case 6:o.content_num_chunks=e.int32();break;case 7:o.content_chunk_id=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.BlobProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"tensor":t.tensor=$root.caffe2.TensorProto.decodeText(e,!0);break;case"content":t.content=e.bytes();break;case"qtensor":t.qtensor=$root.caffe2.QTensorProto.decodeText(e,!0);break;case"content_num_chunks":t.content_num_chunks=e.integer();break;case"content_chunk_id":t.content_chunk_id=e.integer();break;default:e.field(o,t)}}return t}},$root.caffe2.BlobProto.prototype.name="",$root.caffe2.BlobProto.prototype.type="",$root.caffe2.BlobProto.prototype.tensor=null,$root.caffe2.BlobProto.prototype.content=new Uint8Array([]),$root.caffe2.BlobProto.prototype.qtensor=null,$root.caffe2.BlobProto.prototype.content_num_chunks=0,$root.caffe2.BlobProto.prototype.content_chunk_id=0,$root.caffe2.DBReaderProto=class{constructor(){}static decode(e,t){const o=new $root.caffe2.DBReaderProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.source=e.string();break;case 3:o.db_type=e.string();break;case 4:o.key=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.caffe2.DBReaderProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"source":t.source=e.string();break;case"db_type":t.db_type=e.string();break;case"key":t.key=e.string();break;default:e.field(o,t)}}return t}},$root.caffe2.DBReaderProto.prototype.name="",$root.caffe2.DBReaderProto.prototype.source="",$root.caffe2.DBReaderProto.prototype.db_type="",$root.caffe2.DBReaderProto.prototype.key=""; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2.js new file mode 100644 index 0000000000000000000000000000000000000000..bbaa522e292a0efcc084edbb69ad96d911046571 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/caffe2.js @@ -0,0 +1 @@ +var caffe2=caffe2||{},protobuf=protobuf||require("./protobuf");caffe2.ModelFactory=class{match(t){const e=t.identifier.toLowerCase(),n=e.split(".").pop().toLowerCase();if("pb"==n){if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb")||e.startsWith("predict_net")||e.startsWith("init_net"))return!0;const n=t.tags("pb");if(n.size>0&&n.has(1)&&0==n.get(1)&&n.has(2)&&0==n.get(2)&&n.has(9)&&2==n.get(9))return!1;if(n.size>0&&Array.from(n.values()).some((t=>5===t)))return!1;if(!(!(n.size>0)||n.has(1)&&2!==n.get(1)||n.has(2)&&2!==n.get(2)||n.has(7)&&2!==n.get(7)||n.has(8)&&2!==n.get(8))){const e=t.buffer;if(e.length>3&&10==e[0]){const t=e[1];if(t<64&&e.length>2+t+1&&e.slice(2,2+t).every((t=>t>=32&&t<=127))&&18==e[2+t])return!0}if(e.length>3&&18==e[0])return!0}}if("pbtxt"==n||"prototxt"==n){if(e.endsWith("predict_net"))return!0;if(t.tags("pbtxt").has("op"))return"ops.pbtxt"!==t.identifier||-1===t.text.indexOf(" attr {")}return!1}open(t,e){return e.require("./caffe2-proto").then((()=>caffe2.Metadata.open(e).then((n=>{const a=t.identifier,i=a.split("."),s=i.pop().toLowerCase(),r=i.join(".");if("pbtxt"==s||"prototxt"==s){const i=(t,i)=>{let s=null,r=null;try{caffe2.proto=protobuf.get("caffe2").caffe2;const e=protobuf.TextReader.create(t);e.field=function(t,e){if(!(e instanceof caffe2.proto.DeviceOption))throw new Error("Unknown field '"+t+"'"+this.location());e[t]=this.skip()},s=caffe2.proto.NetDef.decodeText(e)}catch(t){throw new caffe2.Error("File text format is not caffe2.NetDef ("+t.message+") in '"+a+"'.")}try{caffe2.proto=protobuf.get("caffe2").caffe2,r="string"==typeof i?caffe2.proto.NetDef.decodeText(protobuf.TextReader.create(i)):caffe2.proto.NetDef.decode(protobuf.Reader.create(i))}catch(t){}try{return new caffe2.Model(n,s,r)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new caffe2.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}};return r.toLowerCase().endsWith("init_net")||r.toLowerCase().startsWith("init_net")?t.request(a.replace("init_net","predict_net"),"utf-8").then((e=>i(e,t.text))).catch((()=>i(t.text,null))):r.toLowerCase().endsWith("predict_net")||r.toLowerCase().startsWith("predict_net")?t.request(a.replace("predict_net","init_net").replace(/\.pbtxt/,".pb"),null).then((e=>i(t.text,e))).catch((()=>t.request(a.replace("predict_net","init_net"),"utf-8").then((e=>i(t.text,e))).catch((()=>i(t.text,null))))):t.request(r+"_init.pb",null).then((e=>i(t.text,e))).catch((()=>i(t.text,null)))}{const i=(t,i)=>{let s=null,r=null;try{caffe2.proto=protobuf.get("caffe2").caffe2;const e=protobuf.Reader.create(t);s=caffe2.proto.NetDef.decode(e)}catch(t){throw new caffe2.Error("File format is not caffe2.NetDef ("+t.message+") in '"+a+"'.")}try{if(i){caffe2.proto=protobuf.get("caffe2").caffe2;const t=protobuf.Reader.create(i);r=caffe2.proto.NetDef.decode(t)}}catch(t){}try{return new caffe2.Model(n,s,r)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new caffe2.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}};return r.toLowerCase().endsWith("init_net")?t.request(r.replace(/init_net$/,"")+"predict_net."+s,null).then((e=>i(e,t.buffer))).catch((()=>i(t.buffer,null))):r.toLowerCase().endsWith("_init")?t.request(r.replace(/_init$/,"")+"."+s,null).then((e=>i(e,t.buffer))).catch((()=>i(t.buffer,null))):r.toLowerCase().endsWith("predict_net")||r.toLowerCase().startsWith("predict_net")?t.request(a.replace("predict_net","init_net"),null).then((e=>i(t.buffer,e))).catch((()=>i(t.buffer,null))):t.request(r+"_init."+s,null).then((e=>i(t.buffer,e))).catch((()=>i(t.buffer,null)))}}))))}},caffe2.Model=class{constructor(t,e,n){this._domain=e.domain||null;const a=new caffe2.Graph(t,e,n);this._graphs=[a]}get format(){return"Caffe2"}get domain(){return this._domain}get graphs(){return this._graphs}},caffe2.Graph=class{constructor(t,e,n){this._name=e.name||"",this._type=e.type||"",this._nodes=[];const a=new Map;for(const t of e.external_input)a.set(t,{});if(n)for(const t of n.op)if(t.output&&1==t.output.length){const e=t.output[0];a.has(e)||a.set(e,{});const n=a.get(e);for(const e of t.arg)n[e.name]=e;switch(t.type){case"GivenTensorFill":n.dataType="float32";break;case"GivenTensorDoubleFill":n.dataType="float64";break;case"GivenTensorBoolFill":n.dataType="boolean";break;case"GivenTensorByteStringToUInt8Fill":n.dataType="uint8";break;case"GivenTensorInt16Fill":case"GivenTensorSInt16Fill":n.dataType="int16";break;case"GivenTensorIntFill":n.dataType="int32";break;case"GivenTensorInt64Fill":n.dataType="int64";break;case"GivenTensorStringFill":n.dataType="string";break;case"Int8GivenIntTensorFill":n.dataType="int32";break;case"Int8GivenTensorFill":n.dataType="int8";break;case"XavierFill":case"ConstantFill":break;default:throw new caffe2.Error("Unknown init op '"+t.type+"'.")}n.values&&n.values.floats&&(1!==n.values.floats.length||0!==n.values.floats[0])&&(n.input=!1)}const i={};let s=0;for(const t of e.op)t.input=t.input.map((t=>i[t]?i[t]:t)),t.output=t.output.map((t=>{if(i[t]){const e=t+"\n"+s.toString();return i[t]=e,e}return i[t]=t,t})),s++;let r=null,o=null;for(const n of e.op){const e=new caffe2.Node(t,n,a);1==n.input.length&&n.output.length>=1&&n.input[0].split("\n").shift()==n.output[0].split("\n").shift()&&r&&o==n.input[0].split("\n").shift()?r.chain.push(e):(this._nodes.push(e),r=null,o=null,1==n.output.length&&(r=e,o=n.output[0].split("\n").shift()))}this._inputs=[];for(const t of e.external_input){if(e.external_input.length>1){const e=a.get(t);if(e&&!1===e.input)continue}this._inputs.push(new caffe2.Parameter(t,[new caffe2.Argument(t,null,null)]))}this._outputs=[];for(const t of e.external_output)this._outputs.push(new caffe2.Parameter(t,[new caffe2.Argument(t,null,null)]))}get name(){return this._name}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}toString(){return"graph("+this.name+")"}},caffe2.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},caffe2.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new caffe2.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get quantization(){return this._initializer?this._initializer.quantization:null}get initializer(){return this._initializer}},caffe2.Node=class{constructor(t,e,n){this._name=e.name||"",this._device=e.engine||"",this._metadata=t,this._type=e.type,this._chain=[],this._attributes=[];for(const n of e.arg)this._attributes.push(new caffe2.Attribute(t,t.attribute(this._type,n.name),n));const a=t.type(this._type),i=e.input,s=e.output,r={};let o=0;for(const t of i){if(o>0&&n.has(t)){const e=n.get(t);r[t]=new caffe2.Tensor(t,e),e.input=!1}o++}for(const t of s)n.has(t)&&(n.get(t).input=!1);this._inputs=[];let u=0;if(a&&a.inputs){for(const t of a.inputs)if(u""!=e||"optional"!=t.option)).map((t=>new caffe2.Argument(t,null,r[t])));this._inputs.push(new caffe2.Parameter(t.name,n)),u+=e}}else this._inputs=this._inputs.concat(i.slice(u).map(((t,e)=>{const n=u+e==0?"input":(u+e).toString();return new caffe2.Parameter(n,[new caffe2.Argument(t,null,r[t])])})));this._outputs=[];let f=0;if(a&&a.outputs){for(const t of a.outputs)if(fnew caffe2.Argument(t)));this._outputs.push(new caffe2.Parameter(t.name,n)),f+=e}}else this._outputs=this._outputs.concat(s.slice(f).map(((t,e)=>{const n=f+e==0?"output":(f+e).toString();return new caffe2.Parameter(n,[new caffe2.Argument(t,null,null)])})))}get name(){return this._name||""}get device(){return this._device||""}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}},caffe2.Attribute=class{constructor(t,e,n){if(this._name=n.name,n.floats&&n.floats.length>0?this._value=n.floats:n.ints&&n.ints.length>0?this._value=n.ints:n.nets&&n.nets.length>0?(this._value=n.nets.map((e=>new caffe2.Graph(t,e,null))),this._type="graph[]"):n.n?(this._value=new caffe2.Graph(t,n.n,null),this._type="graph"):(n.i,this._value=n.i),e&&Object.prototype.hasOwnProperty.call(e,"type")&&(this._type=e.type,"boolean"==this._type))switch(this._value){case 1:this._value=!0;break;case 0:this._value=!1}e&&(Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible||Object.prototype.hasOwnProperty.call(e,"default")&&(this._value==e.default||this._value&&this._value.toString()==e.default.toString()))&&(this._visible=!1)}get name(){return this._name}get type(){return this._type||null}get value(){return this._value}get visible(){return 0!=this._visible}},caffe2.Tensor=class{constructor(t,e){this._name=t;const n=e.shape&&e.shape.ints?e.shape.ints:null;this._type=new caffe2.TensorType(e.dataType,new caffe2.TensorShape(n)),this._values=e.values||null,this._scale=e.Y_scale?e.Y_scale.f:0,this._zeroPoint=e.Y_zero_point?e.Y_zero_point.i:0}get name(){return this._name}get type(){return this._type}get kind(){return"Initializer"}get quantization(){return 0!=this._scale||0!=this._zeroPoint?this._scale.toString()+" * "+(0==this._zeroPoint?"q":"(q - "+this._zeroPoint.toString()+")"):null}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return caffe2.Tensor._stringify(e,""," ")}_context(){const t={state:null,index:0,count:0};if(!this._values)return t.state="Tensor data is empty.",t;if(void 0===this._values.floats)return t.state="Tensor data is too large to load in Chrome.",t;switch(this._type.dataType){case"float32":t.data=this._values.floats;break;case"boolean":t.data=this._values.ints;break;case"int8":t.data=new Int8Array(this._values.s);break;case"int32":t.data=this._values.ints;break;default:return t.state="Unknown data type.",t}return t.shape=this._type.shape.dimensions,t.dataType=this._type.dataType,t}_decode(t,e){const n=[],a=t.shape[e];if(e==t.shape.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"float32":n.push(t.data[t.index]);break;case"boolean":n.push(0!=t.data[t.index]);break;case"int8":case"int32":n.push(t.data[t.index]);break;default:t.state="Unknown data type."}t.index++,t.count++}else for(let i=0;it.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return n}static _stringify(t,e,n){if(Array.isArray(t)){const a=[];a.push(e+"[");const i=t.map((t=>caffe2.Tensor._stringify(t,e+n,n)));return i.length>0&&a.push(i.join(",\n")),a.push(e+"]"),a.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},caffe2.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType||"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},caffe2.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},caffe2.Metadata=class{static open(t){return caffe2.Metadata._metadata?Promise.resolve(caffe2.Metadata._metadata):t.request(null,"caffe2-metadata.json","utf-8").then((t=>(caffe2.Metadata._metadata=new caffe2.Metadata(t),caffe2.Metadata._metadata))).catch((()=>(caffe2.Metadata._metadata=new caffe2.Metadata(null),caffe2.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},caffe2.Error=class extends Error{constructor(t){super(t),this.name="Error loading Caffe2 model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=caffe2.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..86402d4440238fa827e1d6f2707da01c351f064e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-metadata.json @@ -0,0 +1 @@ +[{"name":"Negate","schema":{"operator":0,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sigmoid","schema":{"category":"Activation","operator":1,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Tanh","schema":{"category":"Activation","operator":2,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ReLU","schema":{"category":"Activation","operator":3,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"RectifiedLinear","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Exp","schema":{"operator":4,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Log","schema":{"operator":5,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Sqrt","schema":{"operator":6,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Floor","schema":{"operator":7,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Abs","schema":{"operator":8}},{"name":"Reciprocal","schema":{"operator":9,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Softmax","schema":{"category":"Activation","operator":10,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Hardmax","schema":{"category":"Activation","operator":11}},{"name":"TransposeAxes","schema":{"category":"Activation","operator":12}},{"name":"TransposeDimensions","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Where","schema":{"operator":13,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Slice","schema":{"category":"Tensor","operator":14,"inputs":[{"name":"input"},{"name":"begin"},{"name":"end"}],"outputs":[{"name":"output"}]}},{"name":"Dropout","schema":{"category":"Dropout","operator":15,"attributes":[{"name":"rngSeed","visible":false},{"name":"rngOffset","visible":false}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Reshape","schema":{"category":"Shape","operator":16,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"MaxPooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"AveragePooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"category":"Pool","operator":17,"attributes":[{"name":"transpose","default":false},{"name":"includePad","default":false},{"name":"ceilOutDim","default":false},{"name":"autoPadding","default":[false,null]},{"name":"sharing","default":[true,null]},{"name":"strides","default":[1,null]},{"name":"lowerPad","default":[0,null]},{"name":"upperPad","default":[0,null]},{"name":"outputShape","default":0},{"name":"maxTempMemSizeInSamples","default":0},{"name":"poolingType","type":"PoolingType","default":"Max"},{"name":"poolKind","type":"PoolKind","default":"None"},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SumAll","schema":{"operator":18}},{"name":"Plus","schema":{"operator":19,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Minus","schema":{"operator":20,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"ElementTimes","schema":{"operator":21,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Equal","schema":{"operator":22,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"NotEqual","schema":{"operator":23,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Less","schema":{"operator":24,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"LessEqual","schema":{"operator":25,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Greater","schema":{"operator":26,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"GreaterEqual","schema":{"operator":27,"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"PackedIndex","schema":{"operator":28,"inputs":[{"name":"source"},{"name":"index"}],"outputs":[{"name":"output"}]}},{"name":"GatherPacked","schema":{"operator":29,"inputs":[{"name":"index"},{"name":"source"}],"outputs":[{"name":"output"}]}},{"name":"ScatterPacked","schema":{"operator":30}},{"name":"Times","schema":{"operator":31,"attributes":[{"name":"outputRank","default":1},{"name":"inferInputRankToMap","visible":false,"default":-1}],"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"TransposeTimes","schema":{"operator":32}},{"name":"Convolution","schema":{"category":"Layer","operator":33,"attributes":[{"name":"transpose","default":false},{"name":"maxTempMemSizeInSamples","default":0},{"name":"dilation","default":[1,null]},{"name":"outputShape","default":0},{"name":"sharing","default":[true,null]},{"name":"strides","default":[1,null]},{"name":"includePad","default":false},{"name":"ceilOutDim","default":false},{"name":"autoPadding","default":[true,null]},{"name":"lowerPad","default":[0,null]},{"name":"upperPad","default":[0,null]},{"name":"convolution2D","visible":false},{"name":"poolKind","type":"PoolKind","default":"None"},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"},{"name":"W"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"SquaredError","schema":{"operator":34}},{"name":"CrossEntropyWithSoftmax","schema":{"operator":35,"outputs":[{"name":"output"}]}},{"name":"ClassificationError","schema":{"operator":36,"outputs":[{"name":"output"}]}},{"name":"PastValue","schema":{"operator":37,"attributes":[{"name":"offset","type":"uint32","default":1}],"inputs":[{"name":"input"},{"name":"initialState"}],"outputs":[{"name":"output"}]}},{"name":"FutureValue","schema":{"operator":38,"attributes":[{"name":"offset","type":"uint32","default":1}],"inputs":[{"name":"input"},{"name":"initialState"}],"outputs":[{"name":"output"}]}},{"name":"ReduceElements","schema":{"operator":39,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"BatchNormalization","schema":{"category":"Normalization","operator":40,"attributes":[{"name":"disableRegularization","default":false},{"name":"useCuDNNEngine","visible":false},{"name":"useCntkEngine","visible":false},{"name":"runCountUntied","visible":false},{"name":"epsilon","default":0.00001},{"name":"normalizationTimeConstant","default":0},{"name":"disableRegularization","default":false},{"name":"blendTimeConstant","default":0},{"name":"imageLayoutKind","type":"ImageLayoutKind","visible":false}],"inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"},{"name":"mean"},{"name":"variance"},{"name":"count"}],"outputs":[{"name":"output"}]}},{"name":"Clip","schema":{"operator":41}},{"name":"Select","schema":{"operator":42}},{"name":"Splice","schema":{"category":"Tensor","operator":43,"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Combine","schema":{"category":"Tensor","operator":44,"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"RandomSample","schema":{"operator":45}},{"name":"RandomSampleInclusionFrequency","schema":{"operator":46}},{"name":"ROIPooling","schema":{"operator":47,"category":"Pool","attributes":[{"name":"spatialScale","default":0.0625},{"name":"poolKind","type":"PoolKind","default":"None"}],"inputs":[{"name":"inputs"},{"name":"ROIs"}],"outputs":[{"name":"outputs"}]}},{"name":"Logistic","schema":{"operator":48}},{"name":"OptimizedRNNStack","schema":{"operator":49}},{"name":"ReconcileDynamicAxis","schema":{"operator":50}},{"name":"LogSoftmax","schema":{"operator":51}},{"name":"LogPlus","schema":{"operator":52}},{"name":"CosDistance","schema":{"operator":53}},{"name":"Sin","schema":{"operator":54}},{"name":"Cos","schema":{"operator":55}},{"name":"Pass","schema":{"operator":56}},{"name":"Block","schema":{"operator":57}},{"name":"Unpooling","schema":{"operator":58}},{"name":"LambdaRank","schema":{"operator":59}},{"name":"NDCG","schema":{"operator":60}},{"name":"EditDistanceError","schema":{"operator":61}},{"name":"NoOp","schema":{"operator":62,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LabelsToGraph","schema":{"operator":63}},{"name":"StopGradient","schema":{"operator":64}},{"name":"ELU","schema":{"operator":65}},{"name":"ForwardBackward","schema":{"operator":66}},{"name":"CosDistanceWithNegativeSamples","schema":{"operator":67}},{"name":"OneHot","schema":{"operator":68}},{"name":"Pow","schema":{"operator":69}},{"name":"ToSequence","schema":{"operator":70}},{"name":"ToSequenceLike","schema":{"operator":71}},{"name":"UnpackSequence","schema":{"operator":72}},{"name":"Assign","schema":{"operator":73}},{"name":"Gather","schema":{"operator":74}},{"name":"StableSigmoid","schema":{"operator":75,"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"RandomDistribution","schema":{"operator":76}},{"name":"Sinh","schema":{"operator":77}},{"name":"Cosh","schema":{"operator":78}},{"name":"UnpackBatch","schema":{"operator":79}},{"name":"ToBatch","schema":{"operator":80}},{"name":"Asin","schema":{"operator":81}},{"name":"Acos","schema":{"operator":82}},{"name":"Pad","schema":{"operator":83,"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Crop","schema":{"operator":84,"category":"Data"}},{"name":"Atanh","schema":{"operator":85}},{"name":"Asinh","schema":{"operator":86}},{"name":"TopK","schema":{"operator":87,"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Squeeze","schema":{"operator":88,"category":"Transform"}},{"name":"ConstantOp","schema":{"operator":89}},{"name":"LatticeSequenceWithSoftmax","schema":{"operator":90}},{"name":"Cast","schema":{"operator":91}},{"name":"EyeLikeOp","schema":{"operator":92}},{"name":"CustomProxyOp","schema":{"operator":93}},{"name":"StraightThrough","schema":{"operator":94}},{"name":"Tan","schema":{"operator":95}},{"name":"Atan","schema":{"operator":96}},{"name":"ConvolutionSequenceShape","schema":{"operator":97}},{"name":"Function:Dense","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"W"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"Function:Convolution","schema":{"category":"Layer","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:ConvolutionTranspose","schema":{"category":"Layer","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:Softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:linear","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"scale"},{"name":"b"}],"outputs":[{"name":"output"}]}},{"name":"Function:lrn","schema":{"category":"Normalization","outputs":[{"name":"output"}]}},{"name":"Function:PReLU","schema":{"category":"Activation","inputs":[{"name":"x"},{"name":"axis"},{"name":"slope"}],"outputs":[{"name":"y"}]}},{"name":"Function:ElementDivide","schema":{"inputs":[{"name":"A"},{"name":"B"}],"outputs":[{"name":"C"}]}},{"name":"Function:BatchNormalization","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"scale"},{"name":"bias"},{"name":"mean"},{"name":"variance"},{"name":"count"}],"outputs":[{"name":"output"}]}},{"name":"Function:MaxPooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:AveragePooling","schema":{"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:Dropout","schema":{"category":"Dropout","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Function:LSTM","schema":{"category":"Layer","inputs":[{"name":"0"},{"name":"1"},{"name":"2"},{"name":"b"},{"name":"W"},{"name":"H"}]}},{"name":"Mean","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"InvStdDev","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..08f0bd87fb1ff8bcbf5cfb3780b640b55dbf8708 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("cntk");$root.CNTK={},$root.CNTK.proto={},$root.CNTK.proto.NDShape=class{constructor(){this.shape_dim=[]}static decode(o,t){const e=new $root.CNTK.proto.NDShape,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.shape_dim=o.array(e.shape_dim,(()=>o.uint64()),t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Axis=class{constructor(){}static decode(o,t){const e=new $root.CNTK.proto.Axis,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.static_axis_idx=o.int32();break;case 2:e.name=o.string();break;case 3:e.is_ordered_dynamic_axis=o.bool();break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Axis.prototype.static_axis_idx=0,$root.CNTK.proto.Axis.prototype.name="",$root.CNTK.proto.Axis.prototype.is_ordered_dynamic_axis=!1,$root.CNTK.proto.NDArrayView=class{constructor(){}get values(){return $root.CNTK.proto.NDArrayView.valuesSet=$root.CNTK.proto.NDArrayView.valuesSet||new Set(["float_values","double_values","bytes_value","sint32_values"]),Object.keys(this).find((o=>$root.CNTK.proto.NDArrayView.valuesSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.data_type=o.int32();break;case 2:e.storage_format=o.int32();break;case 3:e.shape=$root.CNTK.proto.NDShape.decode(o,o.uint32());break;case 4:e.float_values=$root.CNTK.proto.NDArrayView.FloatValues.decode(o,o.uint32());break;case 5:e.double_values=$root.CNTK.proto.NDArrayView.DoubleValues.decode(o,o.uint32());break;case 6:e.bytes_value=$root.CNTK.proto.NDArrayView.BytesValue.decode(o,o.uint32());break;case 7:e.sint32_values=$root.CNTK.proto.NDArrayView.IntValues.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.prototype.data_type=0,$root.CNTK.proto.NDArrayView.prototype.storage_format=0,$root.CNTK.proto.NDArrayView.prototype.shape=null,$root.CNTK.proto.NDArrayView.DataType={Unknown:0,Float:1,Double:2,Float16:4,Int8:5,Int16:6},$root.CNTK.proto.NDArrayView.StorageFormat={Dense:0,SparseCSC:1,SparseBlockCol:2},$root.CNTK.proto.NDArrayView.FloatValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.FloatValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.floats(e.value,t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.DoubleValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.DoubleValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.doubles(e.value,t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.BytesValue=class{constructor(){}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.BytesValue,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.bytes();break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.NDArrayView.BytesValue.prototype.value=new Uint8Array([]),$root.CNTK.proto.NDArrayView.IntValues=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.NDArrayView.IntValues,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value=o.array(e.value,(()=>o.sint32()),t);break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Vector=class{constructor(){this.value=[]}static decode(o,t){const e=new $root.CNTK.proto.Vector,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.value.push($root.CNTK.proto.DictionaryValue.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Dictionary=class{constructor(){this.data={}}static decode(o,t){const e=new $root.CNTK.proto.Dictionary,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.version=o.uint64();break;case 2:o.pair(e.data,(()=>o.string()),(()=>$root.CNTK.proto.DictionaryValue.decode(o,o.uint32())));break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.Dictionary.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CNTK.proto.DictionaryValue=class{constructor(){}get value(){return $root.CNTK.proto.DictionaryValue.valueSet=$root.CNTK.proto.DictionaryValue.valueSet||new Set(["bool_value","int_value","size_t_value","float_value","double_value","string_value","nd_shape_value","axis_value","vector_value","dictionary_value","nd_array_view_value"]),Object.keys(this).find((o=>$root.CNTK.proto.DictionaryValue.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.CNTK.proto.DictionaryValue,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.version=o.uint64();break;case 2:e.value_type=o.int32();break;case 3:e.bool_value=o.bool();break;case 4:e.int_value=o.int32();break;case 5:e.size_t_value=o.uint64();break;case 6:e.float_value=o.float();break;case 7:e.double_value=o.double();break;case 8:e.string_value=o.string();break;case 9:e.nd_shape_value=$root.CNTK.proto.NDShape.decode(o,o.uint32());break;case 10:e.axis_value=$root.CNTK.proto.Axis.decode(o,o.uint32());break;case 11:e.vector_value=$root.CNTK.proto.Vector.decode(o,o.uint32());break;case 12:e.dictionary_value=$root.CNTK.proto.Dictionary.decode(o,o.uint32());break;case 13:e.nd_array_view_value=$root.CNTK.proto.NDArrayView.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}},$root.CNTK.proto.DictionaryValue.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CNTK.proto.DictionaryValue.prototype.value_type=0,$root.CNTK.proto.DictionaryValue.Type={None:0,Bool:1,Int:2,SizeT:3,Float:4,Double:5,String:6,NDShape:7,Axis:8,Vector:9,Dictionary:10,NDArrayView:11}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk.js new file mode 100644 index 0000000000000000000000000000000000000000..982be67c1cb007c58c5078c0d40ad6fee7b280a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/cntk.js @@ -0,0 +1 @@ +var cntk=cntk||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf"),cntk_v1={},cntk_v2=null;cntk.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"==e||"cmf"==e||"dnn"==e||"cntk"==e){const e=t.buffer,n=[138,10,108,252,156,70,249,32,106,168,80,25];if(e&&e.length>14&&128==e[0]&&n.every(((t,n)=>t==e[n+2])))return!1;if(e&&e.length>=8&&66==e[0]&&0==e[1]&&67==e[2]&&0==e[3]&&78==e[4]&&0==e[5]&&0==e[6]&&0==e[7])return!0;const i=t.tags("pb");return 0===i.get(1)&&2===i.get(2)}}open(t,e){return e.require("./cntk-proto").then((()=>{let n=0,i=null;try{const e=t.buffer;e&&e.length>=8&&66==e[0]&&0==e[1]&&67==e[2]&&0==e[3]&&78==e[4]&&0==e[5]&&0==e[6]&&0==e[7]&&(i=new cntk_v1.ComputationNetwork(e),n=1)}catch(e){throw new cntk.Error("File format is not CNTK v1 ("+e.message+") in '"+t.identifier+"'.")}try{if(!i){(cntk_v2=protobuf.get("cntk").CNTK.proto).PoolingType={0:"Max",1:"Average"};const e=protobuf.Reader.create(t.buffer),s=cntk_v2.Dictionary.decode(e);i=cntk.ModelFactory._convertDictionary(s),n=2}}catch(e){throw new cntk.Error("File format is not cntk.Dictionary ("+e.message+") in '"+t.identifier+"'.")}return cntk.Metadata.open(e).then((t=>{try{return new cntk.Model(t,n,i)}catch(t){throw new cntk.Error(t.message)}}))}))}static _convertDictionary(t){const e={};for(const n of Object.keys(t.data).filter((t=>"version"!=t)))e[n]=cntk.ModelFactory._convertDictionaryValue(t.data[n]);return e}static _convertDictionaryValue(t){switch(t.value_type){case cntk_v2.DictionaryValue.Type.Bool:return t.bool_value;case cntk_v2.DictionaryValue.Type.Int:return t.int_value;case cntk_v2.DictionaryValue.Type.SizeT:return t.size_t_value;case cntk_v2.DictionaryValue.Type.Float:return t.float_value;case cntk_v2.DictionaryValue.Type.Double:return t.double_value;case cntk_v2.DictionaryValue.Type.String:return t.string_value;case cntk_v2.DictionaryValue.Type.Vector:return cntk.ModelFactory._convertVectorValue(t.vector_value);case cntk_v2.DictionaryValue.Type.NDShape:return t.nd_shape_value;case cntk_v2.DictionaryValue.Type.Axis:return t.axis_value;case cntk_v2.DictionaryValue.Type.Dictionary:return cntk.ModelFactory._convertDictionary(t.dictionary_value);case cntk_v2.DictionaryValue.Type.NDArrayView:return t.nd_array_view_value}throw new cntk.Error("Unknown dictionary value type '"+t.value_type.toString()+"'.")}static _convertVectorValue(t){return t.value.map((t=>cntk.ModelFactory._convertDictionaryValue(t)))}},cntk.Model=class{constructor(t,e,n){switch(e){case 1:this._format="CNTK v1"+(n.version?"."+n.version.toString():"");break;case 2:this._format="CNTK v2"}this._graphs=[],this._graphs.push(new cntk.Graph(t,e,n))}get graphs(){return this._graphs}get format(){return this._format}},cntk.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[],this._functions=[];const i={};switch(e){case 1:for(const t of Object.keys(n.nodes)){const s=n.nodes[t];switch(s.__type__){case"InputValue":this._inputs.push(new cntk.Parameter(s.name,[new cntk.Argument(e,s)]));break;case"LearnableParameter":i[s.name]=new cntk.Argument(e,s)}}for(const s of Object.keys(n.nodes)){const o=n.nodes[s];"InputValue"!=o.__type__&&"LearnableParameter"!=o.__type__&&this._nodes.push(new cntk.Node(t,e,o,i))}if(n.output)for(const t of n.output)this._outputs.push(new cntk.Parameter(t,[new cntk.Argument(e,t)]));break;case 2:{const s=new Map;for(const t of n.primitive_functions)s.set(t.uid,t);for(const t of n.inputs){const n=new cntk.Argument(e,t);if(i[t.uid]=n,0==t.kind){const e=t.name||t.uid;this._inputs.push(new cntk.Parameter(e,[n]))}}for(const o of n.primitive_functions)if(57==o.op&&o.block_function_composite){const n=[o.block_function_composite.root],a=[];for(;n.length>0;){const o=n.shift();if(s.has(o)){const r=s.get(o);a.push(new cntk.Node(t,e,r,i)),s.delete(o);for(let t=0;t=3&&(e.pop(),"Output"==e.pop()&&n.push(e.join("_")))}}}const r=[],u=[o.block_function_composite.root];this._functions.push(new cntk.Function(o.block_function_op_name,a,r,u))}for(const o of n.primitive_functions)s.has(o.uid)&&this._nodes.push(new cntk.Node(t,e,o,i));break}default:throw new cntk.Error("Unsupported graph version '"+e+"'.")}}get nodes(){return this._nodes}get functions(){return this._functions}get inputs(){return this._inputs}get outputs(){return this._outputs}},cntk.Function=class{constructor(t,e,n,i){this._name=t,this._inputs=n,this._outputs=i,this._nodes=e}get name(){return this._name}get description(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},cntk.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},cntk.Argument=class{constructor(t,e){if("string"==typeof e)this._name=e;else switch(t){case 1:switch(e.__type__){case"InputValue":this._name=e.name,this._type=new cntk.TensorType(t,e.precision,e.sampleLayout),this._initializer=null;break;case"LearnableParameter":this._name=e.name,this._type=null,this._initializer=new cntk.Tensor(t,e)}break;case 2:e.value?(this._name=e.name||e.uid,this._type=null,this._initializer=new cntk.Tensor(t,e)):(this._name=e.uid,this._type=new cntk.TensorType(t,e.data_type,e.shape),this._initializer=null)}}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get description(){return""}get initializer(){return this._initializer}},cntk.Node=class{constructor(t,e,n,i){this._metadata=t,this._attributes=[],this._inputs=[],this._outputs=[];let s=[],o=[];const a=[];switch(e){case 1:this._type=n.__type__,this._name=n.name;for(const e of Object.keys(n))"__type__"!=e&&"name"!=e&&"inputs"!=e&&"precision"!=e&&this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n[e]));s=n.inputs.map((t=>i[t]?i[t]:new cntk.Argument(e,t))),o=[new cntk.Argument(e,this._name)];break;case 2:{this._name=n.name||n.uid||null;const r=n.uid;if(57==n.op)this._type="Block",n.block_function_op_name&&(this._type=n.block_function_op_name,this._function=!0);else if(Object.prototype.hasOwnProperty.call(n,"op"))this._type=this._metadata.name(n.op),null==this.type&&(this._type=n.op?n.op.toString():"?");else if(this._type=n.type,n.user_defined_state)for(const e of Object.keys(n.user_defined_state))this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n.user_defined_state[e]));if(n.attributes)for(const e of Object.keys(n.attributes))this._attributes.push(new cntk.Attribute(t.attribute(this._type,e),e,n.attributes[e]));for(const t of n.inputs){const n=i[t];n?n.initializer?a.push(n):s.push(n):s.push(new cntk.Argument(e,t))}o.push(new cntk.Argument(e,r+"_Output_0")),s=s.concat(a);break}}let r=0;const u=this._metadata.type(this._function?"Function:"+this._type:this._type);if(u&&u.inputs)for(const t of u.inputs)if(rnew cntk.Parameter((r+e).toString(),[t]))));let c=0;if(u&&u.outputs)for(const t of u.outputs)if(cnew cntk.Parameter(c.toString(),[t]))))}get name(){return this._name}get type(){return this._type}get function(){return this._function||!1}get metadata(){return this._metadata.type(this._function?"Function:"+this._type:this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},cntk.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,this._type=null,cntk_v1&&this._value instanceof cntk_v1.TensorShape&&(this._value=new cntk.TensorShape(1,n),this._type="shape"),cntk_v2&&this._value instanceof cntk_v2.NDShape&&(this._value=new cntk.TensorShape(2,n),this._type="shape"),cntk_v2&&this._value instanceof cntk_v2.Axis){const t={__type__:"Axis"};for(const e of Object.keys(n).filter((t=>"name"!==t)))t[e]=n[e];this._value=t}if(t){if(t.type){this._type=t.type;const e=cntk_v1[this._type]||cntk_v2[this._type];e&&e[this._value]&&(this._value=e[this._value])}if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){let e=t.default;if("function"==typeof(n=this._value)&&(n=n()),"shape"==this._type&&(n=n.dimensions),n==e)this._visible=!1;else if(Array.isArray(n)&&Array.isArray(e)){if(e=e.slice(0,e.length),e.length>1&&null==e[e.length-1])for(e.pop();e.lengtht==e[n]))&&(this._visible=!1)}}}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},cntk.Tensor=class{constructor(t,e){switch(t){case 1:"LearnableParameter"==e.__type__&&(this._name=e.name||null,this._type=new cntk.TensorType(t,e.precision,e.sampleLayout));break;case 2:this._name=e.name||e.uid||null,this._type=new cntk.TensorType(t,e.data_type,e.shape),this._value=e.value}}get name(){return this._name}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;const e=this._value;if(!e)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float32":e.float_values&&e.float_values.value&&e.float_values.value.length>0?t.data=e.float_values.value:t.state="Tensor data is empty.";break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){let n=t.shape;0==t.shape.length&&(n=[1]);const i=[],s=n[e];if(e==n.length-1)for(let e=0;et.limit)return i.push("..."),i;i.push(t.data[t.index++]),t.count++}else for(let n=0;nt.limit)return i.push("..."),i;i.push(this._decode(t,e+1))}return 0==t.shape.length?i[0]:i}},cntk.TensorType=class{constructor(t,e,n){switch(this._dataType="?",t){case 1:switch(e){case"float":this._dataType="float32";break;case"double":this._dataType="float64";break;case"half":this._dataType="float16";break;case"":this._dataType="float32"}this._shape=new cntk.TensorShape(t,n);break;case 2:switch(long.Long.isLong(e)&&(e=e.toNumber()),e){case 1:this._dataType="float32"}this._shape=new cntk.TensorShape(t,n)}}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},cntk.TensorShape=class{constructor(t,e){switch(t){case 1:this._dimensions=e.dims;break;case 2:this._dimensions=e.shape_dim.map((t=>-1==t.low&&-1==t.high&&1==t.unsigned?-1:t&&long.Long.isLong(t)?t.toNumber():t))}}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},cntk.Metadata=class{static open(t){return cntk.Metadata._metadata?Promise.resolve(cntk.Metadata._metadata):t.request(null,"cntk-metadata.json","utf-8").then((t=>(cntk.Metadata._metadata=new cntk.Metadata(t),cntk.Metadata._metadata))).catch((()=>(cntk.Metadata._metadata=new cntk.Metadata(null),cntk.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},this._typeMap={},t){const e=JSON.parse(t);if(e)for(const t of e)if(t.name&&t.schema){const e=t.name,n=t.schema;n.name=e,this._map[e]=n,Object.prototype.hasOwnProperty.call(n,"operator")&&(this._typeMap[n.operator.toString()]=e)}}}name(t){return this._typeMap[t]||null}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},cntk_v1.ComputationNetwork=class{constructor(t){const e=new cntk_v1.Reader(t);e.assert("BCN"),e.assert("BVersion"),this.version=e.uint64(),e.assert("EVersion");const n=e.uint64();e.assert("BNodeList");const i={Minus:function(){},Plus:function(){},GreaterEqual:function(){},Equal:function(){},NotEqual:function(){},Exp:function(){},Log:function(){},Reciprocal:function(){},ElementTimes:function(){},ClassificationError:function(){},RectifiedLinear:function(){},InputValue:function(t,e){this.rows=t.uint64(),this.cols=t.uint64(),this.sampleLayout=new cntk_v1.TensorShape(t,!0),this.dynamicAxisNodeName="",e>=8&&1==t.uint32()&&(this.dynamicAxisNodeName=t.string()),this.learningRateMultiplier=0,e>=10&&(this.learningRateMultiplier=t.float32())},LearnableParameter:function(t,e){if(!(e>=3))throw new cntk.Error("LeanableParameter reader implemented.");this.learningRateMultiplier=t.float32(),this.sampleLayout=new cntk_v1.TensorShape(t),this.value=new cntk_v1.Matrix(t)},CrossEntropyWithSoftmax:function(t){this.evalMode=t.uint32(),this.evalMode>2&&(this.evalMode=0,t.skip(-4))},Times:function(t,e){this.outputRank=e>=3?t.uint64():1,this.inferInputRankToMap=e>=12?t.int32():-1},Dropout:function(t,e){e>=16&&(this.rngSeed=16==e?t.uint32():t.uint64(),this.rngOffset=t.uint64())},ConvolutionBase:function(t,e){e>=5&&(this.kernelShape=new cntk_v1.TensorShape(t),this.mapCount=new cntk_v1.TensorShape(t),this.strides=new cntk_v1.TensorShape(t),this.sharing=t.booleans(t.uint64()),this.autoPadding=t.booleans(t.uint64()),this.lowerPad=new cntk_v1.TensorShape(t),this.upperPad=new cntk_v1.TensorShape(t),this.poolKind=t.enum(),this.imageLayoutKind=t.enum(),this.maxTempMemSizeInSamples=t.uint64()),e>=9&&(this.transpose=t.boolean()),e>=20&&(this.outputShape=new cntk_v1.TensorShape(t)),e>=21&&(this.ceilOutDim=t.boolean()),e>=23&&(this.includePad=t.boolean())},Convolution:function(t,e){i.ConvolutionBase.apply(this,[t,e]),e<5?(this.kernelShape=new cntk_v1.TensorShape([t.uint64(),t.uint64(),1]),this.strides=new cntk_v1.TensorShape([t.uint64(),t.uint64(),1]),this.mapCount=new cntk_v1.TensorShape([t.uint32()]),this.imageLayoutKind=t.enum(),this.autoPadding=[t.boolean()],this.maxTempMemSizeInSamples=t.uint64(),this.poolKind="None",this.convolution2D=!0,this.sharing=[!0],this.lowerPad=new cntk_v1.TensorShape([0]),this.upperPad=new cntk_v1.TensorShape([0])):(this.convolution2D=t.boolean(),this.dilation=e>=18?new cntk_v1.TensorShape(t):new cntk_v1.TensorShape([1]))},Pooling:function(t,e){i.ConvolutionBase.apply(this,[t,e])},PoolingBase:function(t){this.imageLayoutKind=t.enum(),this.windowWidth=t.uint32(),this.windowHeight=t.uint64(),this.horizontalSubsample=t.uint64(),this.verticalSubsample=t.uint64()},MaxPooling:function(t,e){i.PoolingBase.apply(this,[t,e])},ROIPooling:function(t,e){this.roiOutputShape=new cntk_v1.TensorShape(t),this.poolKind=e<26?"Max":t.enum(),this.spatialScale=e<26?.0625:t.float64()},Reshape:function(t){this.beginDimParameter=t.uint32(),this.endDimParameter=t.uint32(),this.replacementSampleLayout=new cntk_v1.TensorShape(t)},ReduceElements:function(t,e){let n=1;e>=27&&(n=t.uint32()),this.axes=[];for(let e=0;e=24&&(this.keepDimensions=t.boolean())},BatchNormalization:function(t,e){let n=0;if(e>=6)this.spatial=t.boolean(),this.normalizationTimeConstant=t.float64(),this.blendTimeConstant=t.float64(),this.imageLayoutKind=t.enum(),e>=13?this.runCountUntied=19!=e?t.uint64():t.boolean()?0:"SIZE_MAX":n=t.uint64(),this.epsilon=t.float64(),this.useCntkEngine=t.boolean();else{const e=t.int32(),i=t.int32();if(i>e||e<65537||i>65540)throw new cntk.Error("BatchNormalization version not supported.");this.eval=t.boolean(),this.spatial=t.boolean(),e>=65540?this.normalizationTimeConstant=t.float64():t.float64(),e>=65538&&(this.imageLayoutKind=t.enum(),n=t.uint64()),e>=65539&&(this.epsilon=t.float64(),this.useCntkEngine=t.boolean())}e<13&&(this.runCountUntied=16*n,this.convertRunningVariancePending=!0)},Tanh:function(){},Sigmoid:function(){},Logistic:function(){},SquareError:function(){},ErrorPrediction:function(){},RowStack:function(t,e){this.spliceDim=e>=3?t.int32():1},Slice:function(t,e){let n=1;e>=22&&(n=t.int32()),this.index=[],this.axis=[],this.strideMultiplier=[];for(let i=0;i=3&&this.axis.push(t.int32()),e>=27&&this.strideMultiplier.push(t.int32())},PastValue:function(t,e){if(this.timeStep=t.int32(),e>3)this.sampleLayout=new cntk_v1.TensorShape(t,!1);else{const e=t.uint64();t.uint64(),this.sampleLayout=new cntk_v1.TensorShape([e],!0)}e>=2&&(this.initialStateValue=t.int32())},FutureValue:function(t,e){if(this.timeStep=t.int32(),e>3)this.sampleLayout=new cntk_v1.TensorShape(t,!1);else{const e=t.uint64();t.uint64(),this.sampleLayout=new cntk_v1.TensorShape([e],!0)}e>=2&&(this.initialStateValue=t.int32())},TransposeDimensions:function(t,e){if(e>=3){if(this.axis1=t.int32(),this.axis2=t.int32(),e>=25&&0==this.axis1&&0==this.axis2){const e=t.uint64();this.perm=[];for(let n=0;n=7?e.string():"";if("float"!=t&&"double"!=t&&"half"!=t&&""!=t)throw new cntk.Error("Invalid precision format '"+t+"'.");const n={__type__:e.string()};n.name=e.string(),n.precision=t;const o=i[n.__type__];if(!o)throw new cntk.Error("Unknown node type '"+n.__type__+"'.");o.apply(n,[e,this.version]),s.push(n),this.nodes[n.name]=n}e.assert("ENodeList"),e.assert("BRelation");for(let t=0;t1&&o.splice(0,0,o.pop()),n.inputs=o}e.assert("ERelation"),e.assert("BRootNodes"),e.match("BFeatureNodes")&&(this.feature=e.strings(e.uint64()),e.assert("EFeatureNodes")),e.match("BLabelNodes")&&(this.label=e.strings(e.uint64()),e.assert("ELabelNodes")),e.match("BCriterionNodes")&&(this.criterion=e.strings(e.uint64()),e.assert("ECriterionNodes")),0==this.criterion.length&&e.match("BCriteriaNodes")&&(this.criterion=e.strings(e.uint64()),e.assert("ECriteriaNodes")),e.match("BNodesReqMultiSeqHandling")&&(e.strings(e.uint64()),e.assert("ENodesReqMultiSeqHandling")),e.match("BEvalNodes")&&(this.eval=e.strings(e.uint64()),e.assert("EEvalNodes")),e.match("BOutputNodes")&&(this.output=e.strings(e.uint64()),e.assert("EOutputNodes")),e.match("BPairNodes")&&(this.pair=e.strings(e.uint64()),e.assert("EPairNodes")),e.assert("ERootNodes"),e.assert("ECN")}},cntk_v1.Reader=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0}match(t){const e=this._position;for(let n=0;nthis._buffer.length)throw new cntk.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}boolean(){return 0!=this.byte()}booleans(t){const e=[];for(let n=0;n65536)throw new cntk_v1.Error("Value not in 48-bit range.");return e<<32|t}float32(){const t=this._position;return this.skip(4),this._dataView.getFloat32(t,!0)}float64(){const t=this._position;return this.skip(8),this._dataView.getFloat64(t,!0)}string(){let t="",e=this.uint16();for(;0!=e;)t+=String.fromCharCode(e),e=this.uint16();return t}strings(t){const e=[];for(let n=0;n0&&(i=t.uint32()),e&&0==i){const e=t.uint32();this.dims.push(t.uint32()),this.dims.push(n),this.dims.push(e)}else{n>0&&this.dims.push(i);for(let e=1;e>>3){case 1:t.models.push($root.CoreML.Specification.Model.decode(e,e.uint32()));break;case 2:t.names.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineClassifier=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PipelineClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineClassifier.prototype.pipeline=null,$root.CoreML.Specification.PipelineRegressor=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PipelineRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PipelineRegressor.prototype.pipeline=null,$root.CoreML.Specification.FeatureDescription=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FeatureDescription,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 2:t.shortDescription=e.string();break;case 3:t.type=$root.CoreML.Specification.FeatureType.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureDescription.prototype.name="",$root.CoreML.Specification.FeatureDescription.prototype.shortDescription="",$root.CoreML.Specification.FeatureDescription.prototype.type=null,$root.CoreML.Specification.Metadata=class{constructor(){this.userDefined={}}static decode(e,o){const t=new $root.CoreML.Specification.Metadata,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shortDescription=e.string();break;case 2:t.versionString=e.string();break;case 3:t.author=e.string();break;case 4:t.license=e.string();break;case 100:e.pair(t.userDefined,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Metadata.prototype.shortDescription="",$root.CoreML.Specification.Metadata.prototype.versionString="",$root.CoreML.Specification.Metadata.prototype.author="",$root.CoreML.Specification.Metadata.prototype.license="",$root.CoreML.Specification.ModelDescription=class{constructor(){this.input=[],this.output=[],this.trainingInput=[]}static decode(e,o){const t=new $root.CoreML.Specification.ModelDescription,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 10:t.output.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 11:t.predictedFeatureName=e.string();break;case 12:t.predictedProbabilitiesName=e.string();break;case 50:t.trainingInput.push($root.CoreML.Specification.FeatureDescription.decode(e,e.uint32()));break;case 100:t.metadata=$root.CoreML.Specification.Metadata.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ModelDescription.prototype.predictedFeatureName="",$root.CoreML.Specification.ModelDescription.prototype.predictedProbabilitiesName="",$root.CoreML.Specification.ModelDescription.prototype.metadata=null,$root.CoreML.Specification.SerializedModel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SerializedModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.identifier=e.string();break;case 2:t.model=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SerializedModel.prototype.identifier="",$root.CoreML.Specification.SerializedModel.prototype.model=new Uint8Array([]),$root.CoreML.Specification.Model=class{constructor(){}get Type(){return $root.CoreML.Specification.Model.TypeSet=$root.CoreML.Specification.Model.TypeSet||new Set(["pipelineClassifier","pipelineRegressor","pipeline","glmRegressor","supportVectorRegressor","treeEnsembleRegressor","neuralNetworkRegressor","bayesianProbitRegressor","glmClassifier","supportVectorClassifier","treeEnsembleClassifier","neuralNetworkClassifier","kNearestNeighborsClassifier","neuralNetwork","itemSimilarityRecommender","customModel","linkedModel","oneHotEncoder","imputer","featureVectorizer","dictVectorizer","scaler","categoricalMapping","normalizer","arrayFeatureExtractor","nonMaximumSuppression","identity","textClassifier","wordTagger","visionFeaturePrint","soundAnalysisPreprocessing","gazetteer","wordEmbedding","serializedModel"]),Object.keys(this).find((e=>$root.CoreML.Specification.Model.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Model,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.specificationVersion=e.int32();break;case 2:t.description=$root.CoreML.Specification.ModelDescription.decode(e,e.uint32());break;case 10:t.isUpdatable=e.bool();break;case 200:t.pipelineClassifier=$root.CoreML.Specification.PipelineClassifier.decode(e,e.uint32());break;case 201:t.pipelineRegressor=$root.CoreML.Specification.PipelineRegressor.decode(e,e.uint32());break;case 202:t.pipeline=$root.CoreML.Specification.Pipeline.decode(e,e.uint32());break;case 300:t.glmRegressor=$root.CoreML.Specification.GLMRegressor.decode(e,e.uint32());break;case 301:t.supportVectorRegressor=$root.CoreML.Specification.SupportVectorRegressor.decode(e,e.uint32());break;case 302:t.treeEnsembleRegressor=$root.CoreML.Specification.TreeEnsembleRegressor.decode(e,e.uint32());break;case 303:t.neuralNetworkRegressor=$root.CoreML.Specification.NeuralNetworkRegressor.decode(e,e.uint32());break;case 304:t.bayesianProbitRegressor=$root.CoreML.Specification.BayesianProbitRegressor.decode(e,e.uint32());break;case 400:t.glmClassifier=$root.CoreML.Specification.GLMClassifier.decode(e,e.uint32());break;case 401:t.supportVectorClassifier=$root.CoreML.Specification.SupportVectorClassifier.decode(e,e.uint32());break;case 402:t.treeEnsembleClassifier=$root.CoreML.Specification.TreeEnsembleClassifier.decode(e,e.uint32());break;case 403:t.neuralNetworkClassifier=$root.CoreML.Specification.NeuralNetworkClassifier.decode(e,e.uint32());break;case 404:t.kNearestNeighborsClassifier=$root.CoreML.Specification.KNearestNeighborsClassifier.decode(e,e.uint32());break;case 500:t.neuralNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 501:t.itemSimilarityRecommender=$root.CoreML.Specification.ItemSimilarityRecommender.decode(e,e.uint32());break;case 555:t.customModel=$root.CoreML.Specification.CustomModel.decode(e,e.uint32());break;case 556:t.linkedModel=$root.CoreML.Specification.LinkedModel.decode(e,e.uint32());break;case 600:t.oneHotEncoder=$root.CoreML.Specification.OneHotEncoder.decode(e,e.uint32());break;case 601:t.imputer=$root.CoreML.Specification.Imputer.decode(e,e.uint32());break;case 602:t.featureVectorizer=$root.CoreML.Specification.FeatureVectorizer.decode(e,e.uint32());break;case 603:t.dictVectorizer=$root.CoreML.Specification.DictVectorizer.decode(e,e.uint32());break;case 604:t.scaler=$root.CoreML.Specification.Scaler.decode(e,e.uint32());break;case 606:t.categoricalMapping=$root.CoreML.Specification.CategoricalMapping.decode(e,e.uint32());break;case 607:t.normalizer=$root.CoreML.Specification.Normalizer.decode(e,e.uint32());break;case 609:t.arrayFeatureExtractor=$root.CoreML.Specification.ArrayFeatureExtractor.decode(e,e.uint32());break;case 610:t.nonMaximumSuppression=$root.CoreML.Specification.NonMaximumSuppression.decode(e,e.uint32());break;case 900:t.identity=$root.CoreML.Specification.Identity.decode(e,e.uint32());break;case 2e3:t.textClassifier=$root.CoreML.Specification.CoreMLModels.TextClassifier.decode(e,e.uint32());break;case 2001:t.wordTagger=$root.CoreML.Specification.CoreMLModels.WordTagger.decode(e,e.uint32());break;case 2002:t.visionFeaturePrint=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.decode(e,e.uint32());break;case 2003:t.soundAnalysisPreprocessing=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.decode(e,e.uint32());break;case 2004:t.gazetteer=$root.CoreML.Specification.CoreMLModels.Gazetteer.decode(e,e.uint32());break;case 2005:t.wordEmbedding=$root.CoreML.Specification.CoreMLModels.WordEmbedding.decode(e,e.uint32());break;case 3e3:t.serializedModel=$root.CoreML.Specification.SerializedModel.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Model.prototype.specificationVersion=0,$root.CoreML.Specification.Model.prototype.description=null,$root.CoreML.Specification.Model.prototype.isUpdatable=!1,$root.CoreML.Specification.CoreMLModels={},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint=class{constructor(){}get VisionFeaturePrintType(){return $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet||new Set(["scene","objects"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.VisionFeaturePrintTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 20:t.scene=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.decode(e,e.uint32());break;case 21:t.objects=$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.version=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.prototype.version=0,$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Scene.SceneVersion={SCENE_VERSION_INVALID:0,SCENE_VERSION_1:1},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects=class{constructor(){this.output=[]}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.version=e.int32();break;case 100:t.output.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.prototype.version=0,$root.CoreML.Specification.CoreMLModels.VisionFeaturePrint.Objects.ObjectsVersion={OBJECTS_VERSION_INVALID:0,OBJECTS_VERSION_1:1},$root.CoreML.Specification.CoreMLModels.TextClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet=$root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet||new Set(["stringClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.TextClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.TextClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.language="",$root.CoreML.Specification.CoreMLModels.TextClassifier.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.WordTagger=class{constructor(){}get Tags(){return $root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet=$root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet||new Set(["stringTags"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.WordTagger.TagsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.WordTagger,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 20:t.tokensOutputFeatureName=e.string();break;case 21:t.tokenTagsOutputFeatureName=e.string();break;case 22:t.tokenLocationsOutputFeatureName=e.string();break;case 23:t.tokenLengthsOutputFeatureName=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringTags=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.language="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokensOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenTagsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenLocationsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.tokenLengthsOutputFeatureName="",$root.CoreML.Specification.CoreMLModels.WordTagger.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.Gazetteer=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet=$root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet||new Set(["stringClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.Gazetteer.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.Gazetteer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;case 200:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.language="",$root.CoreML.Specification.CoreMLModels.Gazetteer.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.WordEmbedding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.WordEmbedding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.revision=e.uint32();break;case 10:t.language=e.string();break;case 100:t.modelParameterData=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.revision=0,$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.language="",$root.CoreML.Specification.CoreMLModels.WordEmbedding.prototype.modelParameterData=new Uint8Array([]),$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing=class{constructor(){}get SoundAnalysisPreprocessingType(){return $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet||new Set(["vggish"]),Object.keys(this).find((e=>$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.SoundAnalysisPreprocessingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 20:t.vggish=$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.StringToInt64Map=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.StringToInt64Map,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.string()),(()=>e.int64()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64ToStringMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.Int64ToStringMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.int64()),(()=>e.string()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringToDoubleMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.StringToDoubleMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.string()),(()=>e.double()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64ToDoubleMap=class{constructor(){this.map={}}static decode(e,o){const t=new $root.CoreML.Specification.Int64ToDoubleMap,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:e.pair(t.map,(()=>e.int64()),(()=>e.double()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.StringVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector.push(e.string());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Vector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.Int64Vector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.array(t.vector,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FloatVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.FloatVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.floats(t.vector,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleVector=class{constructor(){this.vector=[]}static decode(e,o){const t=new $root.CoreML.Specification.DoubleVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vector=e.doubles(t.vector,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Range=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Int64Range,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minValue=e.int64();break;case 2:t.maxValue=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Range.prototype.minValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.Int64Range.prototype.maxValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.Int64Set=class{constructor(){this.values=[]}static decode(e,o){const t=new $root.CoreML.Specification.Int64Set,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.values=e.array(t.values,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DoubleRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minValue=e.double();break;case 2:t.maxValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleRange.prototype.minValue=0,$root.CoreML.Specification.DoubleRange.prototype.maxValue=0,$root.CoreML.Specification.Int64FeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Int64FeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DoubleFeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DoubleFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.StringFeatureType=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StringFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SizeRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SizeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.lowerBound=e.uint64();break;case 2:t.upperBound=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SizeRange.prototype.lowerBound=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SizeRange.prototype.upperBound=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType=class{constructor(){}get SizeFlexibility(){return $root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet=$root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet||new Set(["enumeratedSizes","imageSizeRange"]),Object.keys(this).find((e=>$root.CoreML.Specification.ImageFeatureType.SizeFlexibilitySet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.width=e.int64();break;case 2:t.height=e.int64();break;case 21:t.enumeratedSizes=$root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes.decode(e,e.uint32());break;case 31:t.imageSizeRange=$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.decode(e,e.uint32());break;case 3:t.colorSpace=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.prototype.width=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType.prototype.height=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ImageFeatureType.prototype.colorSpace=0,$root.CoreML.Specification.ImageFeatureType.ColorSpace={INVALID_COLOR_SPACE:0,GRAYSCALE:10,RGB:20,BGR:30},$root.CoreML.Specification.ImageFeatureType.ImageSize=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.ImageSize,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.width=e.uint64();break;case 2:t.height=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSize.prototype.width=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ImageFeatureType.ImageSize.prototype.height=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes=class{constructor(){this.sizes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.EnumeratedImageSizes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.sizes.push($root.CoreML.Specification.ImageFeatureType.ImageSize.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSizeRange=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ImageFeatureType.ImageSizeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.widthRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;case 2:t.heightRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.prototype.widthRange=null,$root.CoreML.Specification.ImageFeatureType.ImageSizeRange.prototype.heightRange=null,$root.CoreML.Specification.ArrayFeatureType=class{constructor(){this.shape=[]}get ShapeFlexibility(){return $root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet=$root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet||new Set(["enumeratedShapes","shapeRange"]),Object.keys(this).find((e=>$root.CoreML.Specification.ArrayFeatureType.ShapeFlexibilitySet.has(e)&&null!=this[e]))}get defaultOptionalValue(){return $root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet=$root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet||new Set(["intDefaultValue","floatDefaultValue","doubleDefaultValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.ArrayFeatureType.defaultOptionalValueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.int64()),o);break;case 2:t.dataType=e.int32();break;case 21:t.enumeratedShapes=$root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes.decode(e,e.uint32());break;case 31:t.shapeRange=$root.CoreML.Specification.ArrayFeatureType.ShapeRange.decode(e,e.uint32());break;case 41:t.intDefaultValue=e.int32();break;case 51:t.floatDefaultValue=e.float();break;case 61:t.doubleDefaultValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.prototype.dataType=0,$root.CoreML.Specification.ArrayFeatureType.ArrayDataType={INVALID_ARRAY_DATA_TYPE:0,FLOAT32:65568,DOUBLE:65600,INT32:131104},$root.CoreML.Specification.ArrayFeatureType.Shape=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.Shape,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes=class{constructor(){this.shapes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.EnumeratedShapes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shapes.push($root.CoreML.Specification.ArrayFeatureType.Shape.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArrayFeatureType.ShapeRange=class{constructor(){this.sizeRanges=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureType.ShapeRange,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.sizeRanges.push($root.CoreML.Specification.SizeRange.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DictionaryFeatureType=class{constructor(){}get KeyType(){return $root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet=$root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet||new Set(["int64KeyType","stringKeyType"]),Object.keys(this).find((e=>$root.CoreML.Specification.DictionaryFeatureType.KeyTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DictionaryFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64KeyType=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 2:t.stringKeyType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceFeatureType=class{constructor(){}get Type(){return $root.CoreML.Specification.SequenceFeatureType.TypeSet=$root.CoreML.Specification.SequenceFeatureType.TypeSet||new Set(["int64Type","stringType"]),Object.keys(this).find((e=>$root.CoreML.Specification.SequenceFeatureType.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SequenceFeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64Type=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 3:t.stringType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;case 101:t.sizeRange=$root.CoreML.Specification.SizeRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceFeatureType.prototype.sizeRange=null,$root.CoreML.Specification.FeatureType=class{constructor(){}get Type(){return $root.CoreML.Specification.FeatureType.TypeSet=$root.CoreML.Specification.FeatureType.TypeSet||new Set(["int64Type","doubleType","stringType","imageType","multiArrayType","dictionaryType","sequenceType"]),Object.keys(this).find((e=>$root.CoreML.Specification.FeatureType.TypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.FeatureType,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.int64Type=$root.CoreML.Specification.Int64FeatureType.decode(e,e.uint32());break;case 2:t.doubleType=$root.CoreML.Specification.DoubleFeatureType.decode(e,e.uint32());break;case 3:t.stringType=$root.CoreML.Specification.StringFeatureType.decode(e,e.uint32());break;case 4:t.imageType=$root.CoreML.Specification.ImageFeatureType.decode(e,e.uint32());break;case 5:t.multiArrayType=$root.CoreML.Specification.ArrayFeatureType.decode(e,e.uint32());break;case 6:t.dictionaryType=$root.CoreML.Specification.DictionaryFeatureType.decode(e,e.uint32());break;case 7:t.sequenceType=$root.CoreML.Specification.SequenceFeatureType.decode(e,e.uint32());break;case 1e3:t.isOptional=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureType.prototype.isOptional=!1,$root.CoreML.Specification.ArrayFeatureExtractor=class{constructor(){this.extractIndex=[]}static decode(e,o){const t=new $root.CoreML.Specification.ArrayFeatureExtractor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.extractIndex=e.array(t.extractIndex,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor=class{constructor(){this.features=[]}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfFeatures=e.uint32();break;case 2:t.bias=$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.decode(e,e.uint32());break;case 3:t.features.push($root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight.decode(e,e.uint32()));break;case 10:t.regressionInputFeatureName=e.string();break;case 11:t.optimismInputFeatureName=e.string();break;case 12:t.samplingScaleInputFeatureName=e.string();break;case 13:t.samplingTruncationInputFeatureName=e.string();break;case 20:t.meanOutputFeatureName=e.string();break;case 21:t.varianceOutputFeatureName=e.string();break;case 22:t.pessimisticProbabilityOutputFeatureName=e.string();break;case 23:t.sampledProbabilityOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.prototype.numberOfFeatures=0,$root.CoreML.Specification.BayesianProbitRegressor.prototype.bias=null,$root.CoreML.Specification.BayesianProbitRegressor.prototype.regressionInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.optimismInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.samplingScaleInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.samplingTruncationInputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.meanOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.varianceOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.pessimisticProbabilityOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.prototype.sampledProbabilityOutputFeatureName="",$root.CoreML.Specification.BayesianProbitRegressor.Gaussian=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.Gaussian,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mean=e.double();break;case 2:t.precision=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.prototype.mean=0,$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.prototype.precision=0,$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureValue=e.uint32();break;case 2:t.featureWeight=$root.CoreML.Specification.BayesianProbitRegressor.Gaussian.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.prototype.featureValue=0,$root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.prototype.featureWeight=null,$root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight=class{constructor(){this.weights=[]}static decode(e,o){const t=new $root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureId=e.uint32();break;case 2:t.weights.push($root.CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BayesianProbitRegressor.FeatureWeight.prototype.featureId=0,$root.CoreML.Specification.CategoricalMapping=class{constructor(){}get MappingType(){return $root.CoreML.Specification.CategoricalMapping.MappingTypeSet=$root.CoreML.Specification.CategoricalMapping.MappingTypeSet||new Set(["stringToInt64Map","int64ToStringMap"]),Object.keys(this).find((e=>$root.CoreML.Specification.CategoricalMapping.MappingTypeSet.has(e)&&null!=this[e]))}get ValueOnUnknown(){return $root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet=$root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet||new Set(["strValue","int64Value"]),Object.keys(this).find((e=>$root.CoreML.Specification.CategoricalMapping.ValueOnUnknownSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalMapping,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringToInt64Map=$root.CoreML.Specification.StringToInt64Map.decode(e,e.uint32());break;case 2:t.int64ToStringMap=$root.CoreML.Specification.Int64ToStringMap.decode(e,e.uint32());break;case 101:t.strValue=e.string();break;case 102:t.int64Value=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomModel=class{constructor(){this.parameters={}}static decode(e,o){const t=new $root.CoreML.Specification.CustomModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.className=e.string();break;case 30:e.pair(t.parameters,(()=>e.string()),(()=>$root.CoreML.Specification.CustomModel.CustomModelParamValue.decode(e,e.uint32())));break;case 40:t.description=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomModel.prototype.className="",$root.CoreML.Specification.CustomModel.prototype.description="",$root.CoreML.Specification.CustomModel.CustomModelParamValue=class{constructor(){}get value(){return $root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet=$root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet||new Set(["doubleValue","stringValue","intValue","longValue","boolValue","bytesValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.CustomModel.CustomModelParamValue.valueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CustomModel.CustomModelParamValue,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.doubleValue=e.double();break;case 20:t.stringValue=e.string();break;case 30:t.intValue=e.int32();break;case 40:t.longValue=e.int64();break;case 50:t.boolValue=e.bool();break;case 60:t.bytesValue=e.bytes();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DictVectorizer=class{constructor(){}get Map(){return $root.CoreML.Specification.DictVectorizer.MapSet=$root.CoreML.Specification.DictVectorizer.MapSet||new Set(["stringToIndex","int64ToIndex"]),Object.keys(this).find((e=>$root.CoreML.Specification.DictVectorizer.MapSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DictVectorizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringToIndex=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 2:t.int64ToIndex=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer=class{constructor(){this.inputList=[]}static decode(e,o){const t=new $root.CoreML.Specification.FeatureVectorizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputList.push($root.CoreML.Specification.FeatureVectorizer.InputColumn.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer.InputColumn=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FeatureVectorizer.InputColumn,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputColumn=e.string();break;case 2:t.inputDimensions=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FeatureVectorizer.InputColumn.prototype.inputColumn="",$root.CoreML.Specification.FeatureVectorizer.InputColumn.prototype.inputDimensions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GLMRegressor=class{constructor(){this.weights=[],this.offset=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.weights.push($root.CoreML.Specification.GLMRegressor.DoubleArray.decode(e,e.uint32()));break;case 2:t.offset=e.doubles(t.offset,o);break;case 3:t.postEvaluationTransform=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMRegressor.prototype.postEvaluationTransform=0,$root.CoreML.Specification.GLMRegressor.DoubleArray=class{constructor(){this.value=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMRegressor.DoubleArray,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.doubles(t.value,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMRegressor.PostEvaluationTransform={NoTransform:0,Logit:1,Probit:2},$root.CoreML.Specification.GLMClassifier=class{constructor(){this.weights=[],this.offset=[]}get ClassLabels(){return $root.CoreML.Specification.GLMClassifier.ClassLabelsSet=$root.CoreML.Specification.GLMClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.GLMClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.GLMClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.weights.push($root.CoreML.Specification.GLMClassifier.DoubleArray.decode(e,e.uint32()));break;case 2:t.offset=e.doubles(t.offset,o);break;case 3:t.postEvaluationTransform=e.int32();break;case 4:t.classEncoding=e.int32();break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMClassifier.prototype.postEvaluationTransform=0,$root.CoreML.Specification.GLMClassifier.prototype.classEncoding=0,$root.CoreML.Specification.GLMClassifier.DoubleArray=class{constructor(){this.value=[]}static decode(e,o){const t=new $root.CoreML.Specification.GLMClassifier.DoubleArray,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.doubles(t.value,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GLMClassifier.PostEvaluationTransform={Logit:0,Probit:1},$root.CoreML.Specification.GLMClassifier.ClassEncoding={ReferenceClass:0,OneVsRest:1},$root.CoreML.Specification.KNearestNeighborsClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet=$root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}get DefaultClassLabel(){return $root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet=$root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet||new Set(["defaultStringLabel","defaultInt64Label"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.DefaultClassLabelSet.has(e)&&null!=this[e]))}get WeightingScheme(){return $root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet=$root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet||new Set(["uniformWeighting","inverseDistanceWeighting"]),Object.keys(this).find((e=>$root.CoreML.Specification.KNearestNeighborsClassifier.WeightingSchemeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.KNearestNeighborsClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nearestNeighborsIndex=$root.CoreML.Specification.NearestNeighborsIndex.decode(e,e.uint32());break;case 3:t.numberOfNeighbors=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 110:t.defaultStringLabel=e.string();break;case 111:t.defaultInt64Label=e.int64();break;case 200:t.uniformWeighting=$root.CoreML.Specification.UniformWeighting.decode(e,e.uint32());break;case 210:t.inverseDistanceWeighting=$root.CoreML.Specification.InverseDistanceWeighting.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.KNearestNeighborsClassifier.prototype.nearestNeighborsIndex=null,$root.CoreML.Specification.KNearestNeighborsClassifier.prototype.numberOfNeighbors=null,$root.CoreML.Specification.NearestNeighborsIndex=class{constructor(){this.floatSamples=[]}get IndexType(){return $root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet=$root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet||new Set(["linearIndex","singleKdTreeIndex"]),Object.keys(this).find((e=>$root.CoreML.Specification.NearestNeighborsIndex.IndexTypeSet.has(e)&&null!=this[e]))}get DistanceFunction(){return $root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet=$root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet||new Set(["squaredEuclideanDistance"]),Object.keys(this).find((e=>$root.CoreML.Specification.NearestNeighborsIndex.DistanceFunctionSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NearestNeighborsIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfDimensions=e.int32();break;case 2:t.floatSamples.push($root.CoreML.Specification.FloatVector.decode(e,e.uint32()));break;case 100:t.linearIndex=$root.CoreML.Specification.LinearIndex.decode(e,e.uint32());break;case 110:t.singleKdTreeIndex=$root.CoreML.Specification.SingleKdTreeIndex.decode(e,e.uint32());break;case 200:t.squaredEuclideanDistance=$root.CoreML.Specification.SquaredEuclideanDistance.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NearestNeighborsIndex.prototype.numberOfDimensions=0,$root.CoreML.Specification.UniformWeighting=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UniformWeighting,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.InverseDistanceWeighting=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.InverseDistanceWeighting,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LinearIndex=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinearIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SingleKdTreeIndex=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SingleKdTreeIndex,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.leafSize=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SingleKdTreeIndex.prototype.leafSize=0,$root.CoreML.Specification.SquaredEuclideanDistance=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SquaredEuclideanDistance,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Int64Parameter=class{constructor(){}get AllowedValues(){return $root.CoreML.Specification.Int64Parameter.AllowedValuesSet=$root.CoreML.Specification.Int64Parameter.AllowedValuesSet||new Set(["range","set"]),Object.keys(this).find((e=>$root.CoreML.Specification.Int64Parameter.AllowedValuesSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Int64Parameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.int64();break;case 10:t.range=$root.CoreML.Specification.Int64Range.decode(e,e.uint32());break;case 11:t.set=$root.CoreML.Specification.Int64Set.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Int64Parameter.prototype.defaultValue=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.DoubleParameter=class{constructor(){}get AllowedValues(){return $root.CoreML.Specification.DoubleParameter.AllowedValuesSet=$root.CoreML.Specification.DoubleParameter.AllowedValuesSet||new Set(["range"]),Object.keys(this).find((e=>$root.CoreML.Specification.DoubleParameter.AllowedValuesSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.DoubleParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.double();break;case 10:t.range=$root.CoreML.Specification.DoubleRange.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DoubleParameter.prototype.defaultValue=0,$root.CoreML.Specification.StringParameter=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StringParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StringParameter.prototype.defaultValue="",$root.CoreML.Specification.BoolParameter=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BoolParameter,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.defaultValue=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BoolParameter.prototype.defaultValue=!1,$root.CoreML.Specification.Identity=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Identity,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Imputer=class{constructor(){}get ImputedValue(){return $root.CoreML.Specification.Imputer.ImputedValueSet=$root.CoreML.Specification.Imputer.ImputedValueSet||new Set(["imputedDoubleValue","imputedInt64Value","imputedStringValue","imputedDoubleArray","imputedInt64Array","imputedStringDictionary","imputedInt64Dictionary"]),Object.keys(this).find((e=>$root.CoreML.Specification.Imputer.ImputedValueSet.has(e)&&null!=this[e]))}get ReplaceValue(){return $root.CoreML.Specification.Imputer.ReplaceValueSet=$root.CoreML.Specification.Imputer.ReplaceValueSet||new Set(["replaceDoubleValue","replaceInt64Value","replaceStringValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.Imputer.ReplaceValueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Imputer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.imputedDoubleValue=e.double();break;case 2:t.imputedInt64Value=e.int64();break;case 3:t.imputedStringValue=e.string();break;case 4:t.imputedDoubleArray=$root.CoreML.Specification.DoubleVector.decode(e,e.uint32());break;case 5:t.imputedInt64Array=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 6:t.imputedStringDictionary=$root.CoreML.Specification.StringToDoubleMap.decode(e,e.uint32());break;case 7:t.imputedInt64Dictionary=$root.CoreML.Specification.Int64ToDoubleMap.decode(e,e.uint32());break;case 11:t.replaceDoubleValue=e.double();break;case 12:t.replaceInt64Value=e.int64();break;case 13:t.replaceStringValue=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkMultiArrayShapeMapping={RANK5_ARRAY_MAPPING:0,EXACT_ARRAY_MAPPING:1},$root.CoreML.Specification.NeuralNetworkImageShapeMapping={RANK5_IMAGE_MAPPING:0,RANK4_IMAGE_MAPPING:1},$root.CoreML.Specification.NeuralNetwork=class{constructor(){this.layers=[],this.preprocessing=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetwork,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetwork.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetwork.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetwork.prototype.updateParams=null,$root.CoreML.Specification.NeuralNetworkImageScaler=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkImageScaler,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.channelScale=e.float();break;case 20:t.blueBias=e.float();break;case 21:t.greenBias=e.float();break;case 22:t.redBias=e.float();break;case 30:t.grayBias=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.channelScale=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.blueBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.greenBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.redBias=0,$root.CoreML.Specification.NeuralNetworkImageScaler.prototype.grayBias=0,$root.CoreML.Specification.NeuralNetworkMeanImage=class{constructor(){this.meanImage=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkMeanImage,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.meanImage=e.floats(t.meanImage,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkPreprocessing=class{constructor(){}get preprocessor(){return $root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet=$root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet||new Set(["scaler","meanImage"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkPreprocessing.preprocessorSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkPreprocessing,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.featureName=e.string();break;case 10:t.scaler=$root.CoreML.Specification.NeuralNetworkImageScaler.decode(e,e.uint32());break;case 11:t.meanImage=$root.CoreML.Specification.NeuralNetworkMeanImage.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkPreprocessing.prototype.featureName="",$root.CoreML.Specification.ActivationReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationLeakyReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationLeakyReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationLeakyReLU.prototype.alpha=0,$root.CoreML.Specification.ActivationTanh=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationTanh,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationScaledTanh=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationScaledTanh,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationScaledTanh.prototype.alpha=0,$root.CoreML.Specification.ActivationScaledTanh.prototype.beta=0,$root.CoreML.Specification.ActivationSigmoid=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSigmoid,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationLinear=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationLinear,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationLinear.prototype.alpha=0,$root.CoreML.Specification.ActivationLinear.prototype.beta=0,$root.CoreML.Specification.ActivationSigmoidHard=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSigmoidHard,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationSigmoidHard.prototype.alpha=0,$root.CoreML.Specification.ActivationSigmoidHard.prototype.beta=0,$root.CoreML.Specification.ActivationPReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationPReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationPReLU.prototype.alpha=null,$root.CoreML.Specification.ActivationELU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationELU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationELU.prototype.alpha=0,$root.CoreML.Specification.ActivationThresholdedReLU=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationThresholdedReLU,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationThresholdedReLU.prototype.alpha=0,$root.CoreML.Specification.ActivationSoftsign=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSoftsign,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationSoftplus=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationSoftplus,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ActivationParametricSoftplus=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ActivationParametricSoftplus,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 2:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ActivationParametricSoftplus.prototype.alpha=null,$root.CoreML.Specification.ActivationParametricSoftplus.prototype.beta=null,$root.CoreML.Specification.ActivationParams=class{constructor(){}get NonlinearityType(){return $root.CoreML.Specification.ActivationParams.NonlinearityTypeSet=$root.CoreML.Specification.ActivationParams.NonlinearityTypeSet||new Set(["linear","ReLU","leakyReLU","thresholdedReLU","PReLU","tanh","scaledTanh","sigmoid","sigmoidHard","ELU","softsign","softplus","parametricSoftplus"]),Object.keys(this).find((e=>$root.CoreML.Specification.ActivationParams.NonlinearityTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ActivationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 5:t.linear=$root.CoreML.Specification.ActivationLinear.decode(e,e.uint32());break;case 10:t.ReLU=$root.CoreML.Specification.ActivationReLU.decode(e,e.uint32());break;case 15:t.leakyReLU=$root.CoreML.Specification.ActivationLeakyReLU.decode(e,e.uint32());break;case 20:t.thresholdedReLU=$root.CoreML.Specification.ActivationThresholdedReLU.decode(e,e.uint32());break;case 25:t.PReLU=$root.CoreML.Specification.ActivationPReLU.decode(e,e.uint32());break;case 30:t.tanh=$root.CoreML.Specification.ActivationTanh.decode(e,e.uint32());break;case 31:t.scaledTanh=$root.CoreML.Specification.ActivationScaledTanh.decode(e,e.uint32());break;case 40:t.sigmoid=$root.CoreML.Specification.ActivationSigmoid.decode(e,e.uint32());break;case 41:t.sigmoidHard=$root.CoreML.Specification.ActivationSigmoidHard.decode(e,e.uint32());break;case 50:t.ELU=$root.CoreML.Specification.ActivationELU.decode(e,e.uint32());break;case 60:t.softsign=$root.CoreML.Specification.ActivationSoftsign.decode(e,e.uint32());break;case 70:t.softplus=$root.CoreML.Specification.ActivationSoftplus.decode(e,e.uint32());break;case 71:t.parametricSoftplus=$root.CoreML.Specification.ActivationParametricSoftplus.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Tensor=class{constructor(){this.dimValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.Tensor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.rank=e.uint32();break;case 2:t.dimValue=e.array(t.dimValue,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Tensor.prototype.rank=0,$root.CoreML.Specification.NeuralNetworkLayer=class{constructor(){this.input=[],this.output=[],this.inputTensor=[],this.outputTensor=[]}get layer(){return $root.CoreML.Specification.NeuralNetworkLayer.layerSet=$root.CoreML.Specification.NeuralNetworkLayer.layerSet||new Set(["convolution","pooling","activation","innerProduct","embedding","batchnorm","mvn","l2normalize","softmax","lrn","crop","padding","upsample","resizeBilinear","cropResize","unary","add","multiply","average","scale","bias","max","min","dot","reduce","loadConstant","reshape","flatten","permute","concat","split","sequenceRepeat","reorganizeData","slice","simpleRecurrent","gru","uniDirectionalLSTM","biDirectionalLSTM","custom","copy","branch","loop","loopBreak","loopContinue","rangeStatic","rangeDynamic","clip","ceil","floor","sign","round","exp2","sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","asinh","acosh","atanh","erf","gelu","equal","notEqual","lessThan","lessEqual","greaterThan","greaterEqual","logicalOr","logicalXor","logicalNot","logicalAnd","modBroadcastable","minBroadcastable","maxBroadcastable","addBroadcastable","powBroadcastable","divideBroadcastable","floorDivBroadcastable","multiplyBroadcastable","subtractBroadcastable","tile","stack","gather","scatter","gatherND","scatterND","softmaxND","gatherAlongAxis","scatterAlongAxis","reverse","reverseSeq","splitND","concatND","transpose","sliceStatic","sliceDynamic","slidingWindows","topK","argMin","argMax","embeddingND","batchedMatmul","getShape","loadConstantND","fillLike","fillStatic","fillDynamic","broadcastToLike","broadcastToStatic","broadcastToDynamic","squeeze","expandDims","flattenTo2D","reshapeLike","reshapeStatic","reshapeDynamic","rankPreservingReshape","constantPad","randomNormalLike","randomNormalStatic","randomNormalDynamic","randomUniformLike","randomUniformStatic","randomUniformDynamic","randomBernoulliLike","randomBernoulliStatic","randomBernoulliDynamic","categoricalDistribution","reduceL1","reduceL2","reduceMax","reduceMin","reduceSum","reduceProd","reduceMean","reduceLogSum","reduceSumSquare","reduceLogSumExp","whereNonZero","matrixBandPart","lowerTriangular","upperTriangular","whereBroadcastable","layerNormalization","NonMaximumSuppression","oneHot","cumSum","clampedReLU","argSort","pooling3d","globalPooling3d","sliceBySize","convolution3d"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkLayer.layerSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 2:t.input.push(e.string());break;case 3:t.output.push(e.string());break;case 4:t.inputTensor.push($root.CoreML.Specification.Tensor.decode(e,e.uint32()));break;case 5:t.outputTensor.push($root.CoreML.Specification.Tensor.decode(e,e.uint32()));break;case 10:t.isUpdatable=e.bool();break;case 100:t.convolution=$root.CoreML.Specification.ConvolutionLayerParams.decode(e,e.uint32());break;case 120:t.pooling=$root.CoreML.Specification.PoolingLayerParams.decode(e,e.uint32());break;case 130:t.activation=$root.CoreML.Specification.ActivationParams.decode(e,e.uint32());break;case 140:t.innerProduct=$root.CoreML.Specification.InnerProductLayerParams.decode(e,e.uint32());break;case 150:t.embedding=$root.CoreML.Specification.EmbeddingLayerParams.decode(e,e.uint32());break;case 160:t.batchnorm=$root.CoreML.Specification.BatchnormLayerParams.decode(e,e.uint32());break;case 165:t.mvn=$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.decode(e,e.uint32());break;case 170:t.l2normalize=$root.CoreML.Specification.L2NormalizeLayerParams.decode(e,e.uint32());break;case 175:t.softmax=$root.CoreML.Specification.SoftmaxLayerParams.decode(e,e.uint32());break;case 180:t.lrn=$root.CoreML.Specification.LRNLayerParams.decode(e,e.uint32());break;case 190:t.crop=$root.CoreML.Specification.CropLayerParams.decode(e,e.uint32());break;case 200:t.padding=$root.CoreML.Specification.PaddingLayerParams.decode(e,e.uint32());break;case 210:t.upsample=$root.CoreML.Specification.UpsampleLayerParams.decode(e,e.uint32());break;case 211:t.resizeBilinear=$root.CoreML.Specification.ResizeBilinearLayerParams.decode(e,e.uint32());break;case 212:t.cropResize=$root.CoreML.Specification.CropResizeLayerParams.decode(e,e.uint32());break;case 220:t.unary=$root.CoreML.Specification.UnaryFunctionLayerParams.decode(e,e.uint32());break;case 230:t.add=$root.CoreML.Specification.AddLayerParams.decode(e,e.uint32());break;case 231:t.multiply=$root.CoreML.Specification.MultiplyLayerParams.decode(e,e.uint32());break;case 240:t.average=$root.CoreML.Specification.AverageLayerParams.decode(e,e.uint32());break;case 245:t.scale=$root.CoreML.Specification.ScaleLayerParams.decode(e,e.uint32());break;case 250:t.bias=$root.CoreML.Specification.BiasLayerParams.decode(e,e.uint32());break;case 260:t.max=$root.CoreML.Specification.MaxLayerParams.decode(e,e.uint32());break;case 261:t.min=$root.CoreML.Specification.MinLayerParams.decode(e,e.uint32());break;case 270:t.dot=$root.CoreML.Specification.DotProductLayerParams.decode(e,e.uint32());break;case 280:t.reduce=$root.CoreML.Specification.ReduceLayerParams.decode(e,e.uint32());break;case 290:t.loadConstant=$root.CoreML.Specification.LoadConstantLayerParams.decode(e,e.uint32());break;case 300:t.reshape=$root.CoreML.Specification.ReshapeLayerParams.decode(e,e.uint32());break;case 301:t.flatten=$root.CoreML.Specification.FlattenLayerParams.decode(e,e.uint32());break;case 310:t.permute=$root.CoreML.Specification.PermuteLayerParams.decode(e,e.uint32());break;case 320:t.concat=$root.CoreML.Specification.ConcatLayerParams.decode(e,e.uint32());break;case 330:t.split=$root.CoreML.Specification.SplitLayerParams.decode(e,e.uint32());break;case 340:t.sequenceRepeat=$root.CoreML.Specification.SequenceRepeatLayerParams.decode(e,e.uint32());break;case 345:t.reorganizeData=$root.CoreML.Specification.ReorganizeDataLayerParams.decode(e,e.uint32());break;case 350:t.slice=$root.CoreML.Specification.SliceLayerParams.decode(e,e.uint32());break;case 400:t.simpleRecurrent=$root.CoreML.Specification.SimpleRecurrentLayerParams.decode(e,e.uint32());break;case 410:t.gru=$root.CoreML.Specification.GRULayerParams.decode(e,e.uint32());break;case 420:t.uniDirectionalLSTM=$root.CoreML.Specification.UniDirectionalLSTMLayerParams.decode(e,e.uint32());break;case 430:t.biDirectionalLSTM=$root.CoreML.Specification.BiDirectionalLSTMLayerParams.decode(e,e.uint32());break;case 500:t.custom=$root.CoreML.Specification.CustomLayerParams.decode(e,e.uint32());break;case 600:t.copy=$root.CoreML.Specification.CopyLayerParams.decode(e,e.uint32());break;case 605:t.branch=$root.CoreML.Specification.BranchLayerParams.decode(e,e.uint32());break;case 615:t.loop=$root.CoreML.Specification.LoopLayerParams.decode(e,e.uint32());break;case 620:t.loopBreak=$root.CoreML.Specification.LoopBreakLayerParams.decode(e,e.uint32());break;case 625:t.loopContinue=$root.CoreML.Specification.LoopContinueLayerParams.decode(e,e.uint32());break;case 635:t.rangeStatic=$root.CoreML.Specification.RangeStaticLayerParams.decode(e,e.uint32());break;case 640:t.rangeDynamic=$root.CoreML.Specification.RangeDynamicLayerParams.decode(e,e.uint32());break;case 660:t.clip=$root.CoreML.Specification.ClipLayerParams.decode(e,e.uint32());break;case 665:t.ceil=$root.CoreML.Specification.CeilLayerParams.decode(e,e.uint32());break;case 670:t.floor=$root.CoreML.Specification.FloorLayerParams.decode(e,e.uint32());break;case 680:t.sign=$root.CoreML.Specification.SignLayerParams.decode(e,e.uint32());break;case 685:t.round=$root.CoreML.Specification.RoundLayerParams.decode(e,e.uint32());break;case 700:t.exp2=$root.CoreML.Specification.Exp2LayerParams.decode(e,e.uint32());break;case 710:t.sin=$root.CoreML.Specification.SinLayerParams.decode(e,e.uint32());break;case 715:t.cos=$root.CoreML.Specification.CosLayerParams.decode(e,e.uint32());break;case 720:t.tan=$root.CoreML.Specification.TanLayerParams.decode(e,e.uint32());break;case 730:t.asin=$root.CoreML.Specification.AsinLayerParams.decode(e,e.uint32());break;case 735:t.acos=$root.CoreML.Specification.AcosLayerParams.decode(e,e.uint32());break;case 740:t.atan=$root.CoreML.Specification.AtanLayerParams.decode(e,e.uint32());break;case 750:t.sinh=$root.CoreML.Specification.SinhLayerParams.decode(e,e.uint32());break;case 755:t.cosh=$root.CoreML.Specification.CoshLayerParams.decode(e,e.uint32());break;case 760:t.tanh=$root.CoreML.Specification.TanhLayerParams.decode(e,e.uint32());break;case 770:t.asinh=$root.CoreML.Specification.AsinhLayerParams.decode(e,e.uint32());break;case 775:t.acosh=$root.CoreML.Specification.AcoshLayerParams.decode(e,e.uint32());break;case 780:t.atanh=$root.CoreML.Specification.AtanhLayerParams.decode(e,e.uint32());break;case 790:t.erf=$root.CoreML.Specification.ErfLayerParams.decode(e,e.uint32());break;case 795:t.gelu=$root.CoreML.Specification.GeluLayerParams.decode(e,e.uint32());break;case 815:t.equal=$root.CoreML.Specification.EqualLayerParams.decode(e,e.uint32());break;case 820:t.notEqual=$root.CoreML.Specification.NotEqualLayerParams.decode(e,e.uint32());break;case 825:t.lessThan=$root.CoreML.Specification.LessThanLayerParams.decode(e,e.uint32());break;case 827:t.lessEqual=$root.CoreML.Specification.LessEqualLayerParams.decode(e,e.uint32());break;case 830:t.greaterThan=$root.CoreML.Specification.GreaterThanLayerParams.decode(e,e.uint32());break;case 832:t.greaterEqual=$root.CoreML.Specification.GreaterEqualLayerParams.decode(e,e.uint32());break;case 840:t.logicalOr=$root.CoreML.Specification.LogicalOrLayerParams.decode(e,e.uint32());break;case 845:t.logicalXor=$root.CoreML.Specification.LogicalXorLayerParams.decode(e,e.uint32());break;case 850:t.logicalNot=$root.CoreML.Specification.LogicalNotLayerParams.decode(e,e.uint32());break;case 855:t.logicalAnd=$root.CoreML.Specification.LogicalAndLayerParams.decode(e,e.uint32());break;case 865:t.modBroadcastable=$root.CoreML.Specification.ModBroadcastableLayerParams.decode(e,e.uint32());break;case 870:t.minBroadcastable=$root.CoreML.Specification.MinBroadcastableLayerParams.decode(e,e.uint32());break;case 875:t.maxBroadcastable=$root.CoreML.Specification.MaxBroadcastableLayerParams.decode(e,e.uint32());break;case 880:t.addBroadcastable=$root.CoreML.Specification.AddBroadcastableLayerParams.decode(e,e.uint32());break;case 885:t.powBroadcastable=$root.CoreML.Specification.PowBroadcastableLayerParams.decode(e,e.uint32());break;case 890:t.divideBroadcastable=$root.CoreML.Specification.DivideBroadcastableLayerParams.decode(e,e.uint32());break;case 895:t.floorDivBroadcastable=$root.CoreML.Specification.FloorDivBroadcastableLayerParams.decode(e,e.uint32());break;case 900:t.multiplyBroadcastable=$root.CoreML.Specification.MultiplyBroadcastableLayerParams.decode(e,e.uint32());break;case 905:t.subtractBroadcastable=$root.CoreML.Specification.SubtractBroadcastableLayerParams.decode(e,e.uint32());break;case 920:t.tile=$root.CoreML.Specification.TileLayerParams.decode(e,e.uint32());break;case 925:t.stack=$root.CoreML.Specification.StackLayerParams.decode(e,e.uint32());break;case 930:t.gather=$root.CoreML.Specification.GatherLayerParams.decode(e,e.uint32());break;case 935:t.scatter=$root.CoreML.Specification.ScatterLayerParams.decode(e,e.uint32());break;case 940:t.gatherND=$root.CoreML.Specification.GatherNDLayerParams.decode(e,e.uint32());break;case 945:t.scatterND=$root.CoreML.Specification.ScatterNDLayerParams.decode(e,e.uint32());break;case 950:t.softmaxND=$root.CoreML.Specification.SoftmaxNDLayerParams.decode(e,e.uint32());break;case 952:t.gatherAlongAxis=$root.CoreML.Specification.GatherAlongAxisLayerParams.decode(e,e.uint32());break;case 954:t.scatterAlongAxis=$root.CoreML.Specification.ScatterAlongAxisLayerParams.decode(e,e.uint32());break;case 960:t.reverse=$root.CoreML.Specification.ReverseLayerParams.decode(e,e.uint32());break;case 965:t.reverseSeq=$root.CoreML.Specification.ReverseSeqLayerParams.decode(e,e.uint32());break;case 975:t.splitND=$root.CoreML.Specification.SplitNDLayerParams.decode(e,e.uint32());break;case 980:t.concatND=$root.CoreML.Specification.ConcatNDLayerParams.decode(e,e.uint32());break;case 985:t.transpose=$root.CoreML.Specification.TransposeLayerParams.decode(e,e.uint32());break;case 995:t.sliceStatic=$root.CoreML.Specification.SliceStaticLayerParams.decode(e,e.uint32());break;case 1e3:t.sliceDynamic=$root.CoreML.Specification.SliceDynamicLayerParams.decode(e,e.uint32());break;case 1005:t.slidingWindows=$root.CoreML.Specification.SlidingWindowsLayerParams.decode(e,e.uint32());break;case 1015:t.topK=$root.CoreML.Specification.TopKLayerParams.decode(e,e.uint32());break;case 1020:t.argMin=$root.CoreML.Specification.ArgMinLayerParams.decode(e,e.uint32());break;case 1025:t.argMax=$root.CoreML.Specification.ArgMaxLayerParams.decode(e,e.uint32());break;case 1040:t.embeddingND=$root.CoreML.Specification.EmbeddingNDLayerParams.decode(e,e.uint32());break;case 1045:t.batchedMatmul=$root.CoreML.Specification.BatchedMatMulLayerParams.decode(e,e.uint32());break;case 1065:t.getShape=$root.CoreML.Specification.GetShapeLayerParams.decode(e,e.uint32());break;case 1070:t.loadConstantND=$root.CoreML.Specification.LoadConstantNDLayerParams.decode(e,e.uint32());break;case 1080:t.fillLike=$root.CoreML.Specification.FillLikeLayerParams.decode(e,e.uint32());break;case 1085:t.fillStatic=$root.CoreML.Specification.FillStaticLayerParams.decode(e,e.uint32());break;case 1090:t.fillDynamic=$root.CoreML.Specification.FillDynamicLayerParams.decode(e,e.uint32());break;case 1100:t.broadcastToLike=$root.CoreML.Specification.BroadcastToLikeLayerParams.decode(e,e.uint32());break;case 1105:t.broadcastToStatic=$root.CoreML.Specification.BroadcastToStaticLayerParams.decode(e,e.uint32());break;case 1110:t.broadcastToDynamic=$root.CoreML.Specification.BroadcastToDynamicLayerParams.decode(e,e.uint32());break;case 1120:t.squeeze=$root.CoreML.Specification.SqueezeLayerParams.decode(e,e.uint32());break;case 1125:t.expandDims=$root.CoreML.Specification.ExpandDimsLayerParams.decode(e,e.uint32());break;case 1130:t.flattenTo2D=$root.CoreML.Specification.FlattenTo2DLayerParams.decode(e,e.uint32());break;case 1135:t.reshapeLike=$root.CoreML.Specification.ReshapeLikeLayerParams.decode(e,e.uint32());break;case 1140:t.reshapeStatic=$root.CoreML.Specification.ReshapeStaticLayerParams.decode(e,e.uint32());break;case 1145:t.reshapeDynamic=$root.CoreML.Specification.ReshapeDynamicLayerParams.decode(e,e.uint32());break;case 1150:t.rankPreservingReshape=$root.CoreML.Specification.RankPreservingReshapeLayerParams.decode(e,e.uint32());break;case 1155:t.constantPad=$root.CoreML.Specification.ConstantPaddingLayerParams.decode(e,e.uint32());break;case 1170:t.randomNormalLike=$root.CoreML.Specification.RandomNormalLikeLayerParams.decode(e,e.uint32());break;case 1175:t.randomNormalStatic=$root.CoreML.Specification.RandomNormalStaticLayerParams.decode(e,e.uint32());break;case 1180:t.randomNormalDynamic=$root.CoreML.Specification.RandomNormalDynamicLayerParams.decode(e,e.uint32());break;case 1190:t.randomUniformLike=$root.CoreML.Specification.RandomUniformLikeLayerParams.decode(e,e.uint32());break;case 1195:t.randomUniformStatic=$root.CoreML.Specification.RandomUniformStaticLayerParams.decode(e,e.uint32());break;case 1200:t.randomUniformDynamic=$root.CoreML.Specification.RandomUniformDynamicLayerParams.decode(e,e.uint32());break;case 1210:t.randomBernoulliLike=$root.CoreML.Specification.RandomBernoulliLikeLayerParams.decode(e,e.uint32());break;case 1215:t.randomBernoulliStatic=$root.CoreML.Specification.RandomBernoulliStaticLayerParams.decode(e,e.uint32());break;case 1220:t.randomBernoulliDynamic=$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.decode(e,e.uint32());break;case 1230:t.categoricalDistribution=$root.CoreML.Specification.CategoricalDistributionLayerParams.decode(e,e.uint32());break;case 1250:t.reduceL1=$root.CoreML.Specification.ReduceL1LayerParams.decode(e,e.uint32());break;case 1255:t.reduceL2=$root.CoreML.Specification.ReduceL2LayerParams.decode(e,e.uint32());break;case 1260:t.reduceMax=$root.CoreML.Specification.ReduceMaxLayerParams.decode(e,e.uint32());break;case 1265:t.reduceMin=$root.CoreML.Specification.ReduceMinLayerParams.decode(e,e.uint32());break;case 1270:t.reduceSum=$root.CoreML.Specification.ReduceSumLayerParams.decode(e,e.uint32());break;case 1275:t.reduceProd=$root.CoreML.Specification.ReduceProdLayerParams.decode(e,e.uint32());break;case 1280:t.reduceMean=$root.CoreML.Specification.ReduceMeanLayerParams.decode(e,e.uint32());break;case 1285:t.reduceLogSum=$root.CoreML.Specification.ReduceLogSumLayerParams.decode(e,e.uint32());break;case 1290:t.reduceSumSquare=$root.CoreML.Specification.ReduceSumSquareLayerParams.decode(e,e.uint32());break;case 1295:t.reduceLogSumExp=$root.CoreML.Specification.ReduceLogSumExpLayerParams.decode(e,e.uint32());break;case 1313:t.whereNonZero=$root.CoreML.Specification.WhereNonZeroLayerParams.decode(e,e.uint32());break;case 1315:t.matrixBandPart=$root.CoreML.Specification.MatrixBandPartLayerParams.decode(e,e.uint32());break;case 1320:t.lowerTriangular=$root.CoreML.Specification.LowerTriangularLayerParams.decode(e,e.uint32());break;case 1325:t.upperTriangular=$root.CoreML.Specification.UpperTriangularLayerParams.decode(e,e.uint32());break;case 1330:t.whereBroadcastable=$root.CoreML.Specification.WhereBroadcastableLayerParams.decode(e,e.uint32());break;case 1350:t.layerNormalization=$root.CoreML.Specification.LayerNormalizationLayerParams.decode(e,e.uint32());break;case 1400:t.NonMaximumSuppression=$root.CoreML.Specification.NonMaximumSuppressionLayerParams.decode(e,e.uint32());break;case 1450:t.oneHot=$root.CoreML.Specification.OneHotLayerParams.decode(e,e.uint32());break;case 1455:t.cumSum=$root.CoreML.Specification.CumSumLayerParams.decode(e,e.uint32());break;case 1460:t.clampedReLU=$root.CoreML.Specification.ClampedReLULayerParams.decode(e,e.uint32());break;case 1461:t.argSort=$root.CoreML.Specification.ArgSortLayerParams.decode(e,e.uint32());break;case 1465:t.pooling3d=$root.CoreML.Specification.Pooling3DLayerParams.decode(e,e.uint32());break;case 1466:t.globalPooling3d=$root.CoreML.Specification.GlobalPooling3DLayerParams.decode(e,e.uint32());break;case 1470:t.sliceBySize=$root.CoreML.Specification.SliceBySizeLayerParams.decode(e,e.uint32());break;case 1471:t.convolution3d=$root.CoreML.Specification.Convolution3DLayerParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkLayer.prototype.name="",$root.CoreML.Specification.NeuralNetworkLayer.prototype.isUpdatable=!1,$root.CoreML.Specification.BranchLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BranchLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.ifBranch=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 2:t.elseBranch=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BranchLayerParams.prototype.ifBranch=null,$root.CoreML.Specification.BranchLayerParams.prototype.elseBranch=null,$root.CoreML.Specification.LoopLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.maxLoopIterations=e.uint64();break;case 2:t.conditionVar=e.string();break;case 3:t.conditionNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;case 4:t.bodyNetwork=$root.CoreML.Specification.NeuralNetwork.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoopLayerParams.prototype.maxLoopIterations=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LoopLayerParams.prototype.conditionVar="",$root.CoreML.Specification.LoopLayerParams.prototype.conditionNetwork=null,$root.CoreML.Specification.LoopLayerParams.prototype.bodyNetwork=null,$root.CoreML.Specification.LoopBreakLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopBreakLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LoopContinueLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LoopContinueLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CopyLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CopyLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GreaterThanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GreaterThanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GreaterThanLayerParams.prototype.alpha=0,$root.CoreML.Specification.GreaterEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GreaterEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GreaterEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.LessThanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LessThanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LessThanLayerParams.prototype.alpha=0,$root.CoreML.Specification.LessEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LessEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LessEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.EqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.NotEqualLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NotEqualLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NotEqualLayerParams.prototype.alpha=0,$root.CoreML.Specification.LogicalAndLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalAndLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalOrLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalOrLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalXorLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalXorLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.LogicalNotLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LogicalNotLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.BorderAmounts=class{constructor(){this.borderAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.BorderAmounts,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.borderAmounts.push($root.CoreML.Specification.BorderAmounts.EdgeSizes.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BorderAmounts.EdgeSizes=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BorderAmounts.EdgeSizes,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.startEdgeSize=e.uint64();break;case 2:t.endEdgeSize=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BorderAmounts.EdgeSizes.prototype.startEdgeSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BorderAmounts.EdgeSizes.prototype.endEdgeSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ValidPadding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ValidPadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.paddingAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ValidPadding.prototype.paddingAmounts=null,$root.CoreML.Specification.SamePadding=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SamePadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.asymmetryMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SamePadding.prototype.asymmetryMode=0,$root.CoreML.Specification.SamePadding.SamePaddingMode={BOTTOM_RIGHT_HEAVY:0,TOP_LEFT_HEAVY:1},$root.CoreML.Specification.SamplingMode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SamplingMode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.samplingMethod=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SamplingMode.prototype.samplingMethod=0,$root.CoreML.Specification.SamplingMode.Method={STRICT_ALIGN_ENDPOINTS_MODE:0,ALIGN_ENDPOINTS_MODE:1,UPSAMPLE_MODE:2,ROI_ALIGN_MODE:3},$root.CoreML.Specification.BoxCoordinatesMode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BoxCoordinatesMode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.boxMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BoxCoordinatesMode.prototype.boxMode=0,$root.CoreML.Specification.BoxCoordinatesMode.Coordinates={CORNERS_HEIGHT_FIRST:0,CORNERS_WIDTH_FIRST:1,CENTER_SIZE_HEIGHT_FIRST:2,CENTER_SIZE_WIDTH_FIRST:3},$root.CoreML.Specification.WeightParams=class{constructor(){this.floatValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.WeightParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.floatValue=e.floats(t.floatValue,o);break;case 2:t.float16Value=e.bytes();break;case 30:t.rawValue=e.bytes();break;case 31:t.int8RawValue=e.bytes();break;case 40:t.quantization=$root.CoreML.Specification.QuantizationParams.decode(e,e.uint32());break;case 50:t.isUpdatable=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.WeightParams.prototype.float16Value=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.rawValue=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.int8RawValue=new Uint8Array([]),$root.CoreML.Specification.WeightParams.prototype.quantization=null,$root.CoreML.Specification.WeightParams.prototype.isUpdatable=!1,$root.CoreML.Specification.QuantizationParams=class{constructor(){}get QuantizationType(){return $root.CoreML.Specification.QuantizationParams.QuantizationTypeSet=$root.CoreML.Specification.QuantizationParams.QuantizationTypeSet||new Set(["linearQuantization","lookupTableQuantization"]),Object.keys(this).find((e=>$root.CoreML.Specification.QuantizationParams.QuantizationTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.QuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numberOfBits=e.uint64();break;case 101:t.linearQuantization=$root.CoreML.Specification.LinearQuantizationParams.decode(e,e.uint32());break;case 102:t.lookupTableQuantization=$root.CoreML.Specification.LookUpTableQuantizationParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.QuantizationParams.prototype.numberOfBits=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LinearQuantizationParams=class{constructor(){this.scale=[],this.bias=[]}static decode(e,o){const t=new $root.CoreML.Specification.LinearQuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.scale=e.floats(t.scale,o);break;case 2:t.bias=e.floats(t.bias,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LookUpTableQuantizationParams=class{constructor(){this.floatValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.LookUpTableQuantizationParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.floatValue=e.floats(t.floatValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConvolutionLayerParams=class{constructor(){this.kernelSize=[],this.stride=[],this.dilationFactor=[],this.outputShape=[]}get ConvolutionPaddingType(){return $root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet=$root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet||new Set(["valid","same"]),Object.keys(this).find((e=>$root.CoreML.Specification.ConvolutionLayerParams.ConvolutionPaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.ConvolutionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.outputChannels=e.uint64();break;case 2:t.kernelChannels=e.uint64();break;case 10:t.nGroups=e.uint64();break;case 20:t.kernelSize=e.array(t.kernelSize,(()=>e.uint64()),o);break;case 30:t.stride=e.array(t.stride,(()=>e.uint64()),o);break;case 40:t.dilationFactor=e.array(t.dilationFactor,(()=>e.uint64()),o);break;case 50:t.valid=$root.CoreML.Specification.ValidPadding.decode(e,e.uint32());break;case 51:t.same=$root.CoreML.Specification.SamePadding.decode(e,e.uint32());break;case 60:t.isDeconvolution=e.bool();break;case 70:t.hasBias=e.bool();break;case 90:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 91:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConvolutionLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.kernelChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.nGroups=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ConvolutionLayerParams.prototype.isDeconvolution=!1,$root.CoreML.Specification.ConvolutionLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.ConvolutionLayerParams.prototype.weights=null,$root.CoreML.Specification.ConvolutionLayerParams.prototype.bias=null,$root.CoreML.Specification.Convolution3DLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.Convolution3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.outputChannels=e.int32();break;case 2:t.inputChannels=e.int32();break;case 10:t.nGroups=e.int32();break;case 20:t.kernelDepth=e.int32();break;case 21:t.kernelHeight=e.int32();break;case 22:t.kernelWidth=e.int32();break;case 31:t.strideDepth=e.int32();break;case 32:t.strideHeight=e.int32();break;case 33:t.strideWidth=e.int32();break;case 40:t.dilationDepth=e.int32();break;case 41:t.dilationHeight=e.int32();break;case 42:t.dilationWidth=e.int32();break;case 50:t.hasBias=e.bool();break;case 60:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 61:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 70:t.paddingType=e.int32();break;case 80:t.customPaddingFront=e.int32();break;case 81:t.customPaddingBack=e.int32();break;case 82:t.customPaddingTop=e.int32();break;case 83:t.customPaddingBottom=e.int32();break;case 84:t.customPaddingLeft=e.int32();break;case 85:t.customPaddingRight=e.int32();break;case 86:t.isDeconvolution=e.bool();break;case 87:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Convolution3DLayerParams.prototype.outputChannels=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.inputChannels=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.nGroups=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.kernelWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.strideWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationDepth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationHeight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.dilationWidth=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.Convolution3DLayerParams.prototype.weights=null,$root.CoreML.Specification.Convolution3DLayerParams.prototype.bias=null,$root.CoreML.Specification.Convolution3DLayerParams.prototype.paddingType=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingFront=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingBack=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingTop=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingBottom=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingLeft=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.customPaddingRight=0,$root.CoreML.Specification.Convolution3DLayerParams.prototype.isDeconvolution=!1,$root.CoreML.Specification.Convolution3DLayerParams.PaddingType={CUSTOM:0,VALID:1,SAME:2},$root.CoreML.Specification.InnerProductLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.InnerProductLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputChannels=e.uint64();break;case 2:t.outputChannels=e.uint64();break;case 10:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 22:t.int8DynamicQuantize=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.InnerProductLayerParams.prototype.inputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.InnerProductLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.InnerProductLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.InnerProductLayerParams.prototype.weights=null,$root.CoreML.Specification.InnerProductLayerParams.prototype.bias=null,$root.CoreML.Specification.InnerProductLayerParams.prototype.int8DynamicQuantize=!1,$root.CoreML.Specification.EmbeddingLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EmbeddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputDim=e.uint64();break;case 2:t.outputChannels=e.uint64();break;case 10:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EmbeddingLayerParams.prototype.inputDim=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingLayerParams.prototype.outputChannels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.EmbeddingLayerParams.prototype.weights=null,$root.CoreML.Specification.EmbeddingLayerParams.prototype.bias=null,$root.CoreML.Specification.EmbeddingNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.EmbeddingNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vocabSize=e.uint64();break;case 2:t.embeddingSize=e.uint64();break;case 3:t.hasBias=e.bool();break;case 20:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.vocabSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.embeddingSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.weights=null,$root.CoreML.Specification.EmbeddingNDLayerParams.prototype.bias=null,$root.CoreML.Specification.BatchnormLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BatchnormLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.channels=e.uint64();break;case 5:t.computeMeanVar=e.bool();break;case 6:t.instanceNormalization=e.bool();break;case 10:t.epsilon=e.float();break;case 15:t.gamma=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 16:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 17:t.mean=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 18:t.variance=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchnormLayerParams.prototype.channels=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchnormLayerParams.prototype.computeMeanVar=!1,$root.CoreML.Specification.BatchnormLayerParams.prototype.instanceNormalization=!1,$root.CoreML.Specification.BatchnormLayerParams.prototype.epsilon=0,$root.CoreML.Specification.BatchnormLayerParams.prototype.gamma=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.beta=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.mean=null,$root.CoreML.Specification.BatchnormLayerParams.prototype.variance=null,$root.CoreML.Specification.PoolingLayerParams=class{constructor(){this.kernelSize=[],this.stride=[]}get PoolingPaddingType(){return $root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet=$root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet||new Set(["valid","same","includeLastPixel"]),Object.keys(this).find((e=>$root.CoreML.Specification.PoolingLayerParams.PoolingPaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.PoolingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 10:t.kernelSize=e.array(t.kernelSize,(()=>e.uint64()),o);break;case 20:t.stride=e.array(t.stride,(()=>e.uint64()),o);break;case 30:t.valid=$root.CoreML.Specification.ValidPadding.decode(e,e.uint32());break;case 31:t.same=$root.CoreML.Specification.SamePadding.decode(e,e.uint32());break;case 32:t.includeLastPixel=$root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding.decode(e,e.uint32());break;case 50:t.avgPoolExcludePadding=e.bool();break;case 60:t.globalPooling=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PoolingLayerParams.prototype.type=0,$root.CoreML.Specification.PoolingLayerParams.prototype.avgPoolExcludePadding=!1,$root.CoreML.Specification.PoolingLayerParams.prototype.globalPooling=!1,$root.CoreML.Specification.PoolingLayerParams.PoolingType={MAX:0,AVERAGE:1,L2:2},$root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding=class{constructor(){this.paddingAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.PoolingLayerParams.ValidCompletePadding,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.paddingAmounts=e.array(t.paddingAmounts,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Pooling3DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Pooling3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 2:t.kernelDepth=e.int32();break;case 3:t.kernelHeight=e.int32();break;case 4:t.kernelWidth=e.int32();break;case 5:t.strideDepth=e.int32();break;case 6:t.strideHeight=e.int32();break;case 7:t.strideWidth=e.int32();break;case 15:t.paddingType=e.int32();break;case 8:t.customPaddingFront=e.int32();break;case 9:t.customPaddingBack=e.int32();break;case 10:t.customPaddingTop=e.int32();break;case 11:t.customPaddingBottom=e.int32();break;case 12:t.customPaddingLeft=e.int32();break;case 13:t.customPaddingRight=e.int32();break;case 14:t.countExcludePadding=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Pooling3DLayerParams.prototype.type=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelDepth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelHeight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.kernelWidth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideDepth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideHeight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.strideWidth=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.paddingType=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingFront=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingBack=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingTop=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingBottom=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingLeft=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.customPaddingRight=0,$root.CoreML.Specification.Pooling3DLayerParams.prototype.countExcludePadding=!1,$root.CoreML.Specification.Pooling3DLayerParams.PoolingType3D={MAX:0,AVERAGE:1},$root.CoreML.Specification.Pooling3DLayerParams.Pooling3DPaddingType={CUSTOM:0,VALID:1,SAME:2},$root.CoreML.Specification.GlobalPooling3DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GlobalPooling3DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GlobalPooling3DLayerParams.prototype.type=0,$root.CoreML.Specification.GlobalPooling3DLayerParams.GlobalPoolingType3D={MAX:0,AVERAGE:1},$root.CoreML.Specification.PaddingLayerParams=class{constructor(){}get PaddingType(){return $root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet=$root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet||new Set(["constant","reflection","replication"]),Object.keys(this).find((e=>$root.CoreML.Specification.PaddingLayerParams.PaddingTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.constant=$root.CoreML.Specification.PaddingLayerParams.PaddingConstant.decode(e,e.uint32());break;case 2:t.reflection=$root.CoreML.Specification.PaddingLayerParams.PaddingReflection.decode(e,e.uint32());break;case 3:t.replication=$root.CoreML.Specification.PaddingLayerParams.PaddingReplication.decode(e,e.uint32());break;case 10:t.paddingAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PaddingLayerParams.prototype.paddingAmounts=null,$root.CoreML.Specification.PaddingLayerParams.PaddingConstant=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingConstant,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PaddingLayerParams.PaddingConstant.prototype.value=0,$root.CoreML.Specification.PaddingLayerParams.PaddingReflection=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingReflection,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.PaddingLayerParams.PaddingReplication=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PaddingLayerParams.PaddingReplication,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ConcatLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ConcatLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 100:t.sequenceConcat=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConcatLayerParams.prototype.sequenceConcat=!1,$root.CoreML.Specification.LRNLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LRNLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;case 3:t.localSize=e.uint64();break;case 4:t.k=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LRNLayerParams.prototype.alpha=0,$root.CoreML.Specification.LRNLayerParams.prototype.beta=0,$root.CoreML.Specification.LRNLayerParams.prototype.localSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LRNLayerParams.prototype.k=0,$root.CoreML.Specification.SoftmaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SoftmaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SplitLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SplitLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nOutputs=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SplitLayerParams.prototype.nOutputs=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.AddLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AddLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.AddLayerParams.prototype.alpha=0,$root.CoreML.Specification.MultiplyLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MultiplyLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MultiplyLayerParams.prototype.alpha=0,$root.CoreML.Specification.UnaryFunctionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UnaryFunctionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.type=e.int32();break;case 2:t.alpha=e.float();break;case 3:t.epsilon=e.float();break;case 4:t.shift=e.float();break;case 5:t.scale=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.type=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.alpha=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.epsilon=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.shift=0,$root.CoreML.Specification.UnaryFunctionLayerParams.prototype.scale=0,$root.CoreML.Specification.UnaryFunctionLayerParams.Operation={SQRT:0,RSQRT:1,INVERSE:2,POWER:3,EXP:4,LOG:5,ABS:6,THRESHOLD:7},$root.CoreML.Specification.UpsampleLayerParams=class{constructor(){this.scalingFactor=[],this.fractionalScalingFactor=[]}static decode(e,o){const t=new $root.CoreML.Specification.UpsampleLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.scalingFactor=e.array(t.scalingFactor,(()=>e.uint64()),o);break;case 7:t.fractionalScalingFactor=e.floats(t.fractionalScalingFactor,o);break;case 5:t.mode=e.int32();break;case 6:t.linearUpsampleMode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UpsampleLayerParams.prototype.mode=0,$root.CoreML.Specification.UpsampleLayerParams.prototype.linearUpsampleMode=0,$root.CoreML.Specification.UpsampleLayerParams.InterpolationMode={NN:0,BILINEAR:1},$root.CoreML.Specification.UpsampleLayerParams.LinearUpsampleMode={DEFAULT:0,ALIGN_CORNERS_TRUE:1,ALIGN_CORNERS_FALSE:2},$root.CoreML.Specification.ResizeBilinearLayerParams=class{constructor(){this.targetSize=[]}static decode(e,o){const t=new $root.CoreML.Specification.ResizeBilinearLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetSize=e.array(t.targetSize,(()=>e.uint64()),o);break;case 2:t.mode=$root.CoreML.Specification.SamplingMode.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ResizeBilinearLayerParams.prototype.mode=null,$root.CoreML.Specification.CropResizeLayerParams=class{constructor(){this.targetSize=[]}static decode(e,o){const t=new $root.CoreML.Specification.CropResizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetSize=e.array(t.targetSize,(()=>e.uint64()),o);break;case 2:t.normalizedCoordinates=e.bool();break;case 3:t.mode=$root.CoreML.Specification.SamplingMode.decode(e,e.uint32());break;case 4:t.boxIndicesMode=$root.CoreML.Specification.BoxCoordinatesMode.decode(e,e.uint32());break;case 5:t.spatialScale=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CropResizeLayerParams.prototype.normalizedCoordinates=!1,$root.CoreML.Specification.CropResizeLayerParams.prototype.mode=null,$root.CoreML.Specification.CropResizeLayerParams.prototype.boxIndicesMode=null,$root.CoreML.Specification.CropResizeLayerParams.prototype.spatialScale=0,$root.CoreML.Specification.BiasLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.BiasLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BiasLayerParams.prototype.bias=null,$root.CoreML.Specification.ScaleLayerParams=class{constructor(){this.shapeScale=[],this.shapeBias=[]}static decode(e,o){const t=new $root.CoreML.Specification.ScaleLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shapeScale=e.array(t.shapeScale,(()=>e.uint64()),o);break;case 2:t.scale=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 3:t.hasBias=e.bool();break;case 4:t.shapeBias=e.array(t.shapeBias,(()=>e.uint64()),o);break;case 5:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScaleLayerParams.prototype.scale=null,$root.CoreML.Specification.ScaleLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.ScaleLayerParams.prototype.bias=null,$root.CoreML.Specification.LoadConstantLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LoadConstantLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.data=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoadConstantLayerParams.prototype.data=null,$root.CoreML.Specification.L2NormalizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.L2NormalizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.epsilon=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.L2NormalizeLayerParams.prototype.epsilon=0,$root.CoreML.Specification.FlattenLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FlattenLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenLayerParams.prototype.mode=0,$root.CoreML.Specification.FlattenLayerParams.FlattenOrder={CHANNEL_FIRST:0,CHANNEL_LAST:1},$root.CoreML.Specification.ReshapeLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReshapeLayerParams.prototype.mode=0,$root.CoreML.Specification.ReshapeLayerParams.ReshapeOrder={CHANNEL_FIRST:0,CHANNEL_LAST:1},$root.CoreML.Specification.PermuteLayerParams=class{constructor(){this.axis=[]}static decode(e,o){const t=new $root.CoreML.Specification.PermuteLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.array(t.axis,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReorganizeDataLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReorganizeDataLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;case 2:t.blockSize=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReorganizeDataLayerParams.prototype.mode=0,$root.CoreML.Specification.ReorganizeDataLayerParams.prototype.blockSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ReorganizeDataLayerParams.ReorganizationType={SPACE_TO_DEPTH:0,DEPTH_TO_SPACE:1,PIXEL_SHUFFLE:2},$root.CoreML.Specification.SliceLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SliceLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.startIndex=e.int64();break;case 2:t.endIndex=e.int64();break;case 3:t.stride=e.uint64();break;case 4:t.axis=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceLayerParams.prototype.startIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceLayerParams.prototype.endIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceLayerParams.prototype.stride=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SliceLayerParams.prototype.axis=0,$root.CoreML.Specification.SliceLayerParams.SliceAxis={CHANNEL_AXIS:0,HEIGHT_AXIS:1,WIDTH_AXIS:2},$root.CoreML.Specification.ReduceLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;case 2:t.epsilon=e.float();break;case 3:t.axis=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLayerParams.prototype.mode=0,$root.CoreML.Specification.ReduceLayerParams.prototype.epsilon=0,$root.CoreML.Specification.ReduceLayerParams.prototype.axis=0,$root.CoreML.Specification.ReduceLayerParams.ReduceOperation={SUM:0,AVG:1,PROD:2,LOGSUM:3,SUMSQUARE:4,L1:5,L2:6,MAX:7,MIN:8,ARGMAX:9},$root.CoreML.Specification.ReduceLayerParams.ReduceAxis={CHW:0,HW:1,C:2,H:3,W:4},$root.CoreML.Specification.CropLayerParams=class{constructor(){this.offset=[]}static decode(e,o){const t=new $root.CoreML.Specification.CropLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.cropAmounts=$root.CoreML.Specification.BorderAmounts.decode(e,e.uint32());break;case 5:t.offset=e.array(t.offset,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CropLayerParams.prototype.cropAmounts=null,$root.CoreML.Specification.AverageLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AverageLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DotProductLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DotProductLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.cosineSimilarity=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DotProductLayerParams.prototype.cosineSimilarity=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MeanVarianceNormalizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.acrossChannels=e.bool();break;case 2:t.normalizeVariance=e.bool();break;case 3:t.epsilon=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.acrossChannels=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.normalizeVariance=!1,$root.CoreML.Specification.MeanVarianceNormalizeLayerParams.prototype.epsilon=0,$root.CoreML.Specification.SequenceRepeatLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SequenceRepeatLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nRepetitions=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SequenceRepeatLayerParams.prototype.nRepetitions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SimpleRecurrentLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activation=$root.CoreML.Specification.ActivationParams.decode(e,e.uint32());break;case 15:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVector=e.bool();break;case 30:t.weightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 31:t.recursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 32:t.biasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.activation=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.hasBiasVector=!1,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.weightMatrix=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.recursionMatrix=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.biasVector=null,$root.CoreML.Specification.SimpleRecurrentLayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.GRULayerParams=class{constructor(){this.activations=[]}static decode(e,o){const t=new $root.CoreML.Specification.GRULayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activations.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVectors=e.bool();break;case 30:t.updateGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 31:t.resetGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 32:t.outputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 50:t.updateGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 51:t.resetGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 52:t.outputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 70:t.updateGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 71:t.resetGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 72:t.outputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GRULayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GRULayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.GRULayerParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.GRULayerParams.prototype.hasBiasVectors=!1,$root.CoreML.Specification.GRULayerParams.prototype.updateGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateWeightMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.updateGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateRecursionMatrix=null,$root.CoreML.Specification.GRULayerParams.prototype.updateGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.resetGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.outputGateBiasVector=null,$root.CoreML.Specification.GRULayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.LSTMParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LSTMParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.sequenceOutput=e.bool();break;case 20:t.hasBiasVectors=e.bool();break;case 30:t.forgetBias=e.bool();break;case 40:t.hasPeepholeVectors=e.bool();break;case 50:t.coupledInputAndForgetGate=e.bool();break;case 60:t.cellClipThreshold=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LSTMParams.prototype.sequenceOutput=!1,$root.CoreML.Specification.LSTMParams.prototype.hasBiasVectors=!1,$root.CoreML.Specification.LSTMParams.prototype.forgetBias=!1,$root.CoreML.Specification.LSTMParams.prototype.hasPeepholeVectors=!1,$root.CoreML.Specification.LSTMParams.prototype.coupledInputAndForgetGate=!1,$root.CoreML.Specification.LSTMParams.prototype.cellClipThreshold=0,$root.CoreML.Specification.LSTMWeightParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LSTMWeightParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 2:t.forgetGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 3:t.blockInputWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 4:t.outputGateWeightMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 20:t.inputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 21:t.forgetGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 22:t.blockInputRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 23:t.outputGateRecursionMatrix=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 40:t.inputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 41:t.forgetGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 42:t.blockInputBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 43:t.outputGateBiasVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 60:t.inputGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 61:t.forgetGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 62:t.outputGatePeepholeVector=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateWeightMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateRecursionMatrix=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.blockInputBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGateBiasVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.inputGatePeepholeVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.forgetGatePeepholeVector=null,$root.CoreML.Specification.LSTMWeightParams.prototype.outputGatePeepholeVector=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams=class{constructor(){this.activations=[]}static decode(e,o){const t=new $root.CoreML.Specification.UniDirectionalLSTMLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activations.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.params=$root.CoreML.Specification.LSTMParams.decode(e,e.uint32());break;case 20:t.weightParams=$root.CoreML.Specification.LSTMWeightParams.decode(e,e.uint32());break;case 100:t.reverseInput=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.params=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.weightParams=null,$root.CoreML.Specification.UniDirectionalLSTMLayerParams.prototype.reverseInput=!1,$root.CoreML.Specification.BiDirectionalLSTMLayerParams=class{constructor(){this.activationsForwardLSTM=[],this.activationsBackwardLSTM=[],this.weightParams=[]}static decode(e,o){const t=new $root.CoreML.Specification.BiDirectionalLSTMLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.inputVectorSize=e.uint64();break;case 2:t.outputVectorSize=e.uint64();break;case 10:t.activationsForwardLSTM.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 11:t.activationsBackwardLSTM.push($root.CoreML.Specification.ActivationParams.decode(e,e.uint32()));break;case 15:t.params=$root.CoreML.Specification.LSTMParams.decode(e,e.uint32());break;case 20:t.weightParams.push($root.CoreML.Specification.LSTMWeightParams.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.inputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.outputVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BiDirectionalLSTMLayerParams.prototype.params=null,$root.CoreML.Specification.CustomLayerParams=class{constructor(){this.weights=[],this.parameters={}}static decode(e,o){const t=new $root.CoreML.Specification.CustomLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.className=e.string();break;case 20:t.weights.push($root.CoreML.Specification.WeightParams.decode(e,e.uint32()));break;case 30:e.pair(t.parameters,(()=>e.string()),(()=>$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.decode(e,e.uint32())));break;case 40:t.description=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CustomLayerParams.prototype.className="",$root.CoreML.Specification.CustomLayerParams.prototype.description="",$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue=class{constructor(){}get value(){return $root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet=$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet||new Set(["doubleValue","stringValue","intValue","longValue","boolValue"]),Object.keys(this).find((e=>$root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue.valueSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.CustomLayerParams.CustomLayerParamValue,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.doubleValue=e.double();break;case 20:t.stringValue=e.string();break;case 30:t.intValue=e.int32();break;case 40:t.longValue=e.int64();break;case 50:t.boolValue=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TransposeLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.TransposeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchedMatMulLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BatchedMatMulLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.transposeA=e.bool();break;case 2:t.transposeB=e.bool();break;case 5:t.weightMatrixFirstDimension=e.uint64();break;case 6:t.weightMatrixSecondDimension=e.uint64();break;case 7:t.hasBias=e.bool();break;case 8:t.weights=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 9:t.bias=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 10:t.int8DynamicQuantize=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.transposeA=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.transposeB=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weightMatrixFirstDimension=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weightMatrixSecondDimension=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.hasBias=!1,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.weights=null,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.bias=null,$root.CoreML.Specification.BatchedMatMulLayerParams.prototype.int8DynamicQuantize=!1,$root.CoreML.Specification.ConcatNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ConcatNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConcatNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SoftmaxNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SoftmaxNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SoftmaxNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReverseLayerParams=class{constructor(){this.reverseDim=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReverseLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.reverseDim=e.array(t.reverseDim,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReverseSeqLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReverseSeqLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.batchAxis=e.int64();break;case 2:t.sequenceAxis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReverseSeqLayerParams.prototype.batchAxis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReverseSeqLayerParams.prototype.sequenceAxis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.LoadConstantNDLayerParams=class{constructor(){this.shape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LoadConstantNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shape=e.array(t.shape,(()=>e.uint64()),o);break;case 2:t.data=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LoadConstantNDLayerParams.prototype.data=null,$root.CoreML.Specification.FillLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FillLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillLikeLayerParams.prototype.value=0,$root.CoreML.Specification.FillStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.FillStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;case 2:t.targetShape=e.array(t.targetShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillStaticLayerParams.prototype.value=0,$root.CoreML.Specification.FillDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FillDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FillDynamicLayerParams.prototype.value=0,$root.CoreML.Specification.WhereBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.WhereBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CosLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CosLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.TanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AsinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AsinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AcosLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AcosLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AtanLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AtanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SinhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SinhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.CoshLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CoshLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.TanhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TanhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AsinhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AsinhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AcoshLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AcoshLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AtanhLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AtanhLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.PowBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PowBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.Exp2LayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Exp2LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.WhereNonZeroLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.WhereNonZeroLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MatrixBandPartLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MatrixBandPartLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.numLower=e.int64();break;case 2:t.numUpper=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MatrixBandPartLayerParams.prototype.numLower=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.MatrixBandPartLayerParams.prototype.numUpper=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.UpperTriangularLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.UpperTriangularLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.k=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.UpperTriangularLayerParams.prototype.k=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.LowerTriangularLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LowerTriangularLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.k=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LowerTriangularLayerParams.prototype.k=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.BroadcastToLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.BroadcastToStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.BroadcastToDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.BroadcastToDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.AddBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AddBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MaxBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MaxBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MinBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MinBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ModBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ModBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.FloorDivBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FloorDivBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SubtractBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SubtractBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.MultiplyBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MultiplyBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.DivideBroadcastableLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.DivideBroadcastableLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GatherLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GatherLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterMode={SCATTER_UPDATE:0,SCATTER_ADD:1,SCATTER_SUB:2,SCATTER_MUL:3,SCATTER_DIV:4,SCATTER_MAX:5,SCATTER_MIN:6},$root.CoreML.Specification.ScatterLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterLayerParams.prototype.mode=0,$root.CoreML.Specification.GatherNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ScatterNDLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterNDLayerParams.prototype.mode=0,$root.CoreML.Specification.GatherAlongAxisLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GatherAlongAxisLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GatherAlongAxisLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterAlongAxisLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ScatterAlongAxisLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ScatterAlongAxisLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ScatterAlongAxisLayerParams.prototype.mode=0,$root.CoreML.Specification.StackLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.StackLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.StackLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RankPreservingReshapeLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RankPreservingReshapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConstantPaddingLayerParams=class{constructor(){this.padAmounts=[]}static decode(e,o){const t=new $root.CoreML.Specification.ConstantPaddingLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.value=e.float();break;case 2:t.padAmounts=e.array(t.padAmounts,(()=>e.uint64()),o);break;case 3:t.padToGivenOutputSizeMode=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ConstantPaddingLayerParams.prototype.value=0,$root.CoreML.Specification.ConstantPaddingLayerParams.prototype.padToGivenOutputSizeMode=!1,$root.CoreML.Specification.RandomNormalLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalLikeLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomNormalStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;case 4:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalStaticLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomNormalDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomNormalDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.mean=e.float();break;case 3:t.stdDev=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.mean=0,$root.CoreML.Specification.RandomNormalDynamicLayerParams.prototype.stdDev=0,$root.CoreML.Specification.RandomUniformLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformLikeLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomUniformStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;case 4:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformStaticLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomUniformDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomUniformDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.minVal=e.float();break;case 3:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.minVal=0,$root.CoreML.Specification.RandomUniformDynamicLayerParams.prototype.maxVal=0,$root.CoreML.Specification.RandomBernoulliLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliLikeLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliLikeLayerParams.prototype.prob=0,$root.CoreML.Specification.RandomBernoulliStaticLayerParams=class{constructor(){this.outputShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;case 3:t.outputShape=e.array(t.outputShape,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliStaticLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliStaticLayerParams.prototype.prob=0,$root.CoreML.Specification.RandomBernoulliDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RandomBernoulliDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.prob=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.RandomBernoulliDynamicLayerParams.prototype.prob=0,$root.CoreML.Specification.CategoricalDistributionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalDistributionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.seed=e.int64();break;case 2:t.numSamples=e.int64();break;case 3:t.isLogits=e.bool();break;case 4:t.eps=e.float();break;case 5:t.temperature=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.seed=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.numSamples=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.isLogits=!1,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.eps=0,$root.CoreML.Specification.CategoricalDistributionLayerParams.prototype.temperature=0,$root.CoreML.Specification.ReduceL1LayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceL1LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceL1LayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceL1LayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceL2LayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceL2LayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceL2LayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceL2LayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMaxLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMaxLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMaxLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMinLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMinLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMinLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceSumLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceSumLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceSumLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceProdLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceProdLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceProdLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceProdLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceMeanLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceMeanLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceMeanLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceMeanLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceLogSumLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLogSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLogSumLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceLogSumLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceSumSquareLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceSumSquareLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceSumSquareLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceSumSquareLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ReduceLogSumExpLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReduceLogSumExpLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.keepDims=e.bool();break;case 3:t.reduceAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReduceLogSumExpLayerParams.prototype.keepDims=!1,$root.CoreML.Specification.ReduceLogSumExpLayerParams.prototype.reduceAll=!1,$root.CoreML.Specification.ExpandDimsLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.ExpandDimsLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenTo2DLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FlattenTo2DLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.FlattenTo2DLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ReshapeStaticLayerParams=class{constructor(){this.targetShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.targetShape=e.array(t.targetShape,(()=>e.int64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ReshapeLikeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeLikeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ReshapeDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ReshapeDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SqueezeLayerParams=class{constructor(){this.axes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SqueezeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axes=e.array(t.axes,(()=>e.int64()),o);break;case 2:t.squeezeAll=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SqueezeLayerParams.prototype.squeezeAll=!1,$root.CoreML.Specification.TopKLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TopKLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.K=e.uint64();break;case 3:t.useBottomK=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TopKLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.TopKLayerParams.prototype.K=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TopKLayerParams.prototype.useBottomK=!1,$root.CoreML.Specification.ArgMaxLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgMaxLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.removeDim=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgMaxLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgMaxLayerParams.prototype.removeDim=!1,$root.CoreML.Specification.ArgMinLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgMinLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.removeDim=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgMinLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgMinLayerParams.prototype.removeDim=!1,$root.CoreML.Specification.SplitNDLayerParams=class{constructor(){this.splitSizes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SplitNDLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.numSplits=e.uint64();break;case 3:t.splitSizes=e.array(t.splitSizes,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SplitNDLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SplitNDLayerParams.prototype.numSplits=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.CeilLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CeilLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.RoundLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RoundLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.FloorLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.FloorLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.SignLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SignLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ClipLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ClipLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.minVal=e.float();break;case 2:t.maxVal=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ClipLayerParams.prototype.minVal=0,$root.CoreML.Specification.ClipLayerParams.prototype.maxVal=0,$root.CoreML.Specification.SliceStaticLayerParams=class{constructor(){this.beginIds=[],this.beginMasks=[],this.endIds=[],this.endMasks=[],this.strides=[],this.squeezeMasks=[]}static decode(e,o){const t=new $root.CoreML.Specification.SliceStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.beginIds=e.array(t.beginIds,(()=>e.int64()),o);break;case 2:t.beginMasks=e.array(t.beginMasks,(()=>e.bool()),o);break;case 3:t.endIds=e.array(t.endIds,(()=>e.int64()),o);break;case 4:t.endMasks=e.array(t.endMasks,(()=>e.bool()),o);break;case 5:t.strides=e.array(t.strides,(()=>e.int64()),o);break;case 6:t.squeezeMasks=e.array(t.squeezeMasks,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceDynamicLayerParams=class{constructor(){this.beginMasks=[],this.endIds=[],this.endMasks=[],this.strides=[],this.squeezeMasks=[]}static decode(e,o){const t=new $root.CoreML.Specification.SliceDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.beginMasks=e.array(t.beginMasks,(()=>e.bool()),o);break;case 3:t.endIds=e.array(t.endIds,(()=>e.int64()),o);break;case 4:t.endMasks=e.array(t.endMasks,(()=>e.bool()),o);break;case 5:t.strides=e.array(t.strides,(()=>e.int64()),o);break;case 6:t.squeezeMasks=e.array(t.squeezeMasks,(()=>e.bool()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TileLayerParams=class{constructor(){this.reps=[]}static decode(e,o){const t=new $root.CoreML.Specification.TileLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.reps=e.array(t.reps,(()=>e.uint64()),o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GetShapeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GetShapeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.ErfLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ErfLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.GeluLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.GeluLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.mode=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.GeluLayerParams.prototype.mode=0,$root.CoreML.Specification.GeluLayerParams.GeluMode={EXACT:0,TANH_APPROXIMATION:1,SIGMOID_APPROXIMATION:2},$root.CoreML.Specification.RangeStaticLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RangeStaticLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.endValue=e.float();break;case 2:t.startValue=e.float();break;case 3:t.stepSizeValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RangeStaticLayerParams.prototype.endValue=0,$root.CoreML.Specification.RangeStaticLayerParams.prototype.startValue=0,$root.CoreML.Specification.RangeStaticLayerParams.prototype.stepSizeValue=0,$root.CoreML.Specification.RangeDynamicLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RangeDynamicLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.startValue=e.float();break;case 3:t.stepSizeValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RangeDynamicLayerParams.prototype.startValue=0,$root.CoreML.Specification.RangeDynamicLayerParams.prototype.stepSizeValue=0,$root.CoreML.Specification.SlidingWindowsLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SlidingWindowsLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.windowSize=e.uint64();break;case 3:t.step=e.uint64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.windowSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.SlidingWindowsLayerParams.prototype.step=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.LayerNormalizationLayerParams=class{constructor(){this.normalizedShape=[]}static decode(e,o){const t=new $root.CoreML.Specification.LayerNormalizationLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.normalizedShape=e.array(t.normalizedShape,(()=>e.int64()),o);break;case 2:t.eps=e.float();break;case 3:t.gamma=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;case 4:t.beta=$root.CoreML.Specification.WeightParams.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.eps=0,$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.gamma=null,$root.CoreML.Specification.LayerNormalizationLayerParams.prototype.beta=null,$root.CoreML.Specification.NonMaximumSuppressionLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppressionLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.iouThreshold=e.float();break;case 2:t.scoreThreshold=e.float();break;case 3:t.maxBoxes=e.uint64();break;case 4:t.perClassSuppression=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.iouThreshold=0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.scoreThreshold=0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.maxBoxes=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.NonMaximumSuppressionLayerParams.prototype.perClassSuppression=!1,$root.CoreML.Specification.ClampedReLULayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ClampedReLULayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.float();break;case 2:t.beta=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ClampedReLULayerParams.prototype.alpha=0,$root.CoreML.Specification.ClampedReLULayerParams.prototype.beta=0,$root.CoreML.Specification.ArgSortLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ArgSortLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.descending=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ArgSortLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.ArgSortLayerParams.prototype.descending=!1,$root.CoreML.Specification.SliceBySizeLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SliceBySizeLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 2:t.size=e.int64();break;case 3:t.axis=e.int64();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SliceBySizeLayerParams.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.SliceBySizeLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.NeuralNetworkClassifier=class{constructor(){this.layers=[],this.preprocessing=[]}get ClassLabels(){return $root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet=$root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.NeuralNetworkClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 200:t.labelProbabilityLayerName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkClassifier.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.updateParams=null,$root.CoreML.Specification.NeuralNetworkClassifier.prototype.labelProbabilityLayerName="",$root.CoreML.Specification.OneHotLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.OneHotLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.oneHotVectorSize=e.uint64();break;case 2:t.axis=e.int64();break;case 3:t.onValue=e.float();break;case 4:t.offValue=e.float();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.OneHotLayerParams.prototype.oneHotVectorSize=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.OneHotLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.OneHotLayerParams.prototype.onValue=0,$root.CoreML.Specification.OneHotLayerParams.prototype.offValue=0,$root.CoreML.Specification.CumSumLayerParams=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CumSumLayerParams,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.axis=e.int64();break;case 2:t.excludeFinalSum=e.bool();break;case 3:t.reverse=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CumSumLayerParams.prototype.axis=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.CoreML.Specification.CumSumLayerParams.prototype.excludeFinalSum=!1,$root.CoreML.Specification.CumSumLayerParams.prototype.reverse=!1,$root.CoreML.Specification.NeuralNetworkRegressor=class{constructor(){this.layers=[],this.preprocessing=[]}static decode(e,o){const t=new $root.CoreML.Specification.NeuralNetworkRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.layers.push($root.CoreML.Specification.NeuralNetworkLayer.decode(e,e.uint32()));break;case 2:t.preprocessing.push($root.CoreML.Specification.NeuralNetworkPreprocessing.decode(e,e.uint32()));break;case 5:t.arrayInputShapeMapping=e.int32();break;case 6:t.imageInputShapeMapping=e.int32();break;case 10:t.updateParams=$root.CoreML.Specification.NetworkUpdateParameters.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NeuralNetworkRegressor.prototype.arrayInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkRegressor.prototype.imageInputShapeMapping=0,$root.CoreML.Specification.NeuralNetworkRegressor.prototype.updateParams=null,$root.CoreML.Specification.NetworkUpdateParameters=class{constructor(){this.lossLayers=[]}static decode(e,o){const t=new $root.CoreML.Specification.NetworkUpdateParameters,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.lossLayers.push($root.CoreML.Specification.LossLayer.decode(e,e.uint32()));break;case 2:t.optimizer=$root.CoreML.Specification.Optimizer.decode(e,e.uint32());break;case 3:t.epochs=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 10:t.shuffle=$root.CoreML.Specification.BoolParameter.decode(e,e.uint32());break;case 20:t.seed=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NetworkUpdateParameters.prototype.optimizer=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.epochs=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.shuffle=null,$root.CoreML.Specification.NetworkUpdateParameters.prototype.seed=null,$root.CoreML.Specification.LossLayer=class{constructor(){}get LossLayerType(){return $root.CoreML.Specification.LossLayer.LossLayerTypeSet=$root.CoreML.Specification.LossLayer.LossLayerTypeSet||new Set(["categoricalCrossEntropyLossLayer","meanSquaredErrorLossLayer"]),Object.keys(this).find((e=>$root.CoreML.Specification.LossLayer.LossLayerTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.LossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.name=e.string();break;case 10:t.categoricalCrossEntropyLossLayer=$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.decode(e,e.uint32());break;case 11:t.meanSquaredErrorLossLayer=$root.CoreML.Specification.MeanSquaredErrorLossLayer.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LossLayer.prototype.name="",$root.CoreML.Specification.CategoricalCrossEntropyLossLayer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.CategoricalCrossEntropyLossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input=e.string();break;case 2:t.target=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.prototype.input="",$root.CoreML.Specification.CategoricalCrossEntropyLossLayer.prototype.target="",$root.CoreML.Specification.MeanSquaredErrorLossLayer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.MeanSquaredErrorLossLayer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.input=e.string();break;case 2:t.target=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.MeanSquaredErrorLossLayer.prototype.input="",$root.CoreML.Specification.MeanSquaredErrorLossLayer.prototype.target="",$root.CoreML.Specification.Optimizer=class{constructor(){}get OptimizerType(){return $root.CoreML.Specification.Optimizer.OptimizerTypeSet=$root.CoreML.Specification.Optimizer.OptimizerTypeSet||new Set(["sgdOptimizer","adamOptimizer"]),Object.keys(this).find((e=>$root.CoreML.Specification.Optimizer.OptimizerTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Optimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 10:t.sgdOptimizer=$root.CoreML.Specification.SGDOptimizer.decode(e,e.uint32());break;case 11:t.adamOptimizer=$root.CoreML.Specification.AdamOptimizer.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SGDOptimizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SGDOptimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.learningRate=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 2:t.miniBatchSize=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 3:t.momentum=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SGDOptimizer.prototype.learningRate=null,$root.CoreML.Specification.SGDOptimizer.prototype.miniBatchSize=null,$root.CoreML.Specification.SGDOptimizer.prototype.momentum=null,$root.CoreML.Specification.AdamOptimizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.AdamOptimizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.learningRate=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 2:t.miniBatchSize=$root.CoreML.Specification.Int64Parameter.decode(e,e.uint32());break;case 3:t.beta1=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 4:t.beta2=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;case 5:t.eps=$root.CoreML.Specification.DoubleParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.AdamOptimizer.prototype.learningRate=null,$root.CoreML.Specification.AdamOptimizer.prototype.miniBatchSize=null,$root.CoreML.Specification.AdamOptimizer.prototype.beta1=null,$root.CoreML.Specification.AdamOptimizer.prototype.beta2=null,$root.CoreML.Specification.AdamOptimizer.prototype.eps=null,$root.CoreML.Specification.Normalizer=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.Normalizer,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.normType=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Normalizer.prototype.normType=0,$root.CoreML.Specification.Normalizer.NormType={LMax:0,L1:1,L2:2},$root.CoreML.Specification.OneHotEncoder=class{constructor(){}get CategoryType(){return $root.CoreML.Specification.OneHotEncoder.CategoryTypeSet=$root.CoreML.Specification.OneHotEncoder.CategoryTypeSet||new Set(["stringCategories","int64Categories"]),Object.keys(this).find((e=>$root.CoreML.Specification.OneHotEncoder.CategoryTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.OneHotEncoder,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.stringCategories=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 2:t.int64Categories=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 10:t.outputSparse=e.bool();break;case 11:t.handleUnknown=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.OneHotEncoder.prototype.outputSparse=!1,$root.CoreML.Specification.OneHotEncoder.prototype.handleUnknown=0,$root.CoreML.Specification.OneHotEncoder.HandleUnknown={ErrorOnUnknown:0,IgnoreUnknown:1},$root.CoreML.Specification.Scaler=class{constructor(){this.shiftValue=[],this.scaleValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.Scaler,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.shiftValue=e.doubles(t.shiftValue,o);break;case 2:t.scaleValue=e.doubles(t.scaleValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression=class{constructor(){}get SuppressionMethod(){return $root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet=$root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet||new Set(["pickTop"]),Object.keys(this).find((e=>$root.CoreML.Specification.NonMaximumSuppression.SuppressionMethodSet.has(e)&&null!=this[e]))}get ClassLabels(){return $root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet=$root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.NonMaximumSuppression.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppression,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.pickTop=$root.CoreML.Specification.NonMaximumSuppression.PickTop.decode(e,e.uint32());break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 110:t.iouThreshold=e.double();break;case 111:t.confidenceThreshold=e.double();break;case 200:t.confidenceInputFeatureName=e.string();break;case 201:t.coordinatesInputFeatureName=e.string();break;case 202:t.iouThresholdInputFeatureName=e.string();break;case 203:t.confidenceThresholdInputFeatureName=e.string();break;case 210:t.confidenceOutputFeatureName=e.string();break;case 211:t.coordinatesOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression.prototype.iouThreshold=0,$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceThreshold=0,$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.coordinatesInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.iouThresholdInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceThresholdInputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.confidenceOutputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.prototype.coordinatesOutputFeatureName="",$root.CoreML.Specification.NonMaximumSuppression.PickTop=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.NonMaximumSuppression.PickTop,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.perClass=e.bool();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.NonMaximumSuppression.PickTop.prototype.perClass=!1,$root.CoreML.Specification.LinearKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinearKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();e.skipType(7&o)}return t}},$root.CoreML.Specification.RBFKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.RBFKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.gamma=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.RBFKernel.prototype.gamma=0,$root.CoreML.Specification.PolyKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.PolyKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.degree=e.int32();break;case 2:t.c=e.double();break;case 3:t.gamma=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.PolyKernel.prototype.degree=0,$root.CoreML.Specification.PolyKernel.prototype.c=0,$root.CoreML.Specification.PolyKernel.prototype.gamma=0,$root.CoreML.Specification.SigmoidKernel=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SigmoidKernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.gamma=e.double();break;case 2:t.c=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SigmoidKernel.prototype.gamma=0,$root.CoreML.Specification.SigmoidKernel.prototype.c=0,$root.CoreML.Specification.Kernel=class{constructor(){}get kernel(){return $root.CoreML.Specification.Kernel.kernelSet=$root.CoreML.Specification.Kernel.kernelSet||new Set(["linearKernel","rbfKernel","polyKernel","sigmoidKernel"]),Object.keys(this).find((e=>$root.CoreML.Specification.Kernel.kernelSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.Kernel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linearKernel=$root.CoreML.Specification.LinearKernel.decode(e,e.uint32());break;case 2:t.rbfKernel=$root.CoreML.Specification.RBFKernel.decode(e,e.uint32());break;case 3:t.polyKernel=$root.CoreML.Specification.PolyKernel.decode(e,e.uint32());break;case 4:t.sigmoidKernel=$root.CoreML.Specification.SigmoidKernel.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseNode=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.SparseNode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.index=e.int32();break;case 2:t.value=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseNode.prototype.index=0,$root.CoreML.Specification.SparseNode.prototype.value=0,$root.CoreML.Specification.SparseVector=class{constructor(){this.nodes=[]}static decode(e,o){const t=new $root.CoreML.Specification.SparseVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nodes.push($root.CoreML.Specification.SparseNode.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SparseSupportVectors=class{constructor(){this.vectors=[]}static decode(e,o){const t=new $root.CoreML.Specification.SparseSupportVectors,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vectors.push($root.CoreML.Specification.SparseVector.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DenseVector=class{constructor(){this.values=[]}static decode(e,o){const t=new $root.CoreML.Specification.DenseVector,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.values=e.doubles(t.values,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.DenseSupportVectors=class{constructor(){this.vectors=[]}static decode(e,o){const t=new $root.CoreML.Specification.DenseSupportVectors,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.vectors.push($root.CoreML.Specification.DenseVector.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.Coefficients=class{constructor(){this.alpha=[]}static decode(e,o){const t=new $root.CoreML.Specification.Coefficients,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.alpha=e.doubles(t.alpha,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorRegressor=class{constructor(){}get supportVectors(){return $root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet=$root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet||new Set(["sparseSupportVectors","denseSupportVectors"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorRegressor.supportVectorsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SupportVectorRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.kernel=$root.CoreML.Specification.Kernel.decode(e,e.uint32());break;case 2:t.sparseSupportVectors=$root.CoreML.Specification.SparseSupportVectors.decode(e,e.uint32());break;case 3:t.denseSupportVectors=$root.CoreML.Specification.DenseSupportVectors.decode(e,e.uint32());break;case 4:t.coefficients=$root.CoreML.Specification.Coefficients.decode(e,e.uint32());break;case 5:t.rho=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorRegressor.prototype.kernel=null,$root.CoreML.Specification.SupportVectorRegressor.prototype.coefficients=null,$root.CoreML.Specification.SupportVectorRegressor.prototype.rho=0,$root.CoreML.Specification.SupportVectorClassifier=class{constructor(){this.numberOfSupportVectorsPerClass=[],this.coefficients=[],this.rho=[],this.probA=[],this.probB=[]}get supportVectors(){return $root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet=$root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet||new Set(["sparseSupportVectors","denseSupportVectors"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorClassifier.supportVectorsSet.has(e)&&null!=this[e]))}get ClassLabels(){return $root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet=$root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.SupportVectorClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.SupportVectorClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.kernel=$root.CoreML.Specification.Kernel.decode(e,e.uint32());break;case 2:t.numberOfSupportVectorsPerClass=e.array(t.numberOfSupportVectorsPerClass,(()=>e.int32()),o);break;case 3:t.sparseSupportVectors=$root.CoreML.Specification.SparseSupportVectors.decode(e,e.uint32());break;case 4:t.denseSupportVectors=$root.CoreML.Specification.DenseSupportVectors.decode(e,e.uint32());break;case 5:t.coefficients.push($root.CoreML.Specification.Coefficients.decode(e,e.uint32()));break;case 6:t.rho=e.doubles(t.rho,o);break;case 7:t.probA=e.doubles(t.probA,o);break;case 8:t.probB=e.doubles(t.probB,o);break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.SupportVectorClassifier.prototype.kernel=null,$root.CoreML.Specification.TreeEnsemblePostEvaluationTransform={NoTransform:0,Classification_SoftMax:1,Regression_Logistic:2,Classification_SoftMaxWithZeroClassReference:3},$root.CoreML.Specification.TreeEnsembleParameters=class{constructor(){this.nodes=[],this.basePredictionValue=[]}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.nodes.push($root.CoreML.Specification.TreeEnsembleParameters.TreeNode.decode(e,e.uint32()));break;case 2:t.numPredictionDimensions=e.uint64();break;case 3:t.basePredictionValue=e.doubles(t.basePredictionValue,o);break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.prototype.numPredictionDimensions=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode=class{constructor(){this.evaluationInfo=[]}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters.TreeNode,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeId=e.uint64();break;case 2:t.nodeId=e.uint64();break;case 3:t.nodeBehavior=e.int32();break;case 10:t.branchFeatureIndex=e.uint64();break;case 11:t.branchFeatureValue=e.double();break;case 12:t.trueChildNodeId=e.uint64();break;case 13:t.falseChildNodeId=e.uint64();break;case 14:t.missingValueTracksTrueChild=e.bool();break;case 20:t.evaluationInfo.push($root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.decode(e,e.uint32()));break;case 30:t.relativeHitRate=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.treeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0;$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.nodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.nodeBehavior=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.branchFeatureIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.branchFeatureValue=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.trueChildNodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.falseChildNodeId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.missingValueTracksTrueChild=!1,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.prototype.relativeHitRate=0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.TreeNodeBehavior={BranchOnValueLessThanEqual:0,BranchOnValueLessThan:1,BranchOnValueGreaterThanEqual:2,BranchOnValueGreaterThan:3,BranchOnValueEqual:4,BranchOnValueNotEqual:5,LeafNode:6},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.evaluationIndex=e.uint64();break;case 2:t.evaluationValue=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.prototype.evaluationIndex=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.TreeEnsembleParameters.TreeNode.EvaluationInfo.prototype.evaluationValue=0,$root.CoreML.Specification.TreeEnsembleClassifier=class{constructor(){}get ClassLabels(){return $root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet=$root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet||new Set(["stringClassLabels","int64ClassLabels"]),Object.keys(this).find((e=>$root.CoreML.Specification.TreeEnsembleClassifier.ClassLabelsSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleClassifier,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeEnsemble=$root.CoreML.Specification.TreeEnsembleParameters.decode(e,e.uint32());break;case 2:t.postEvaluationTransform=e.int32();break;case 100:t.stringClassLabels=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 101:t.int64ClassLabels=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleClassifier.prototype.treeEnsemble=null,$root.CoreML.Specification.TreeEnsembleClassifier.prototype.postEvaluationTransform=0,$root.CoreML.Specification.TreeEnsembleRegressor=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.TreeEnsembleRegressor,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.treeEnsemble=$root.CoreML.Specification.TreeEnsembleParameters.decode(e,e.uint32());break;case 2:t.postEvaluationTransform=e.int32();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.TreeEnsembleRegressor.prototype.treeEnsemble=null,$root.CoreML.Specification.TreeEnsembleRegressor.prototype.postEvaluationTransform=0,$root.CoreML.Specification.ItemSimilarityRecommender=class{constructor(){this.itemItemSimilarities=[]}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemItemSimilarities.push($root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.decode(e,e.uint32()));break;case 2:t.itemStringIds=$root.CoreML.Specification.StringVector.decode(e,e.uint32());break;case 3:t.itemInt64Ids=$root.CoreML.Specification.Int64Vector.decode(e,e.uint32());break;case 10:t.itemInputFeatureName=e.string();break;case 11:t.numRecommendationsInputFeatureName=e.string();break;case 12:t.itemRestrictionInputFeatureName=e.string();break;case 13:t.itemExclusionInputFeatureName=e.string();break;case 20:t.recommendedItemListOutputFeatureName=e.string();break;case 21:t.recommendedItemScoreOutputFeatureName=e.string();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemStringIds=null,$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemInt64Ids=null,$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.numRecommendationsInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemRestrictionInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.itemExclusionInputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.recommendedItemListOutputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.prototype.recommendedItemScoreOutputFeatureName="",$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemId=e.uint64();break;case 2:t.similarityScore=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.prototype.itemId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.prototype.similarityScore=0,$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems=class{constructor(){this.similarItemList=[]}static decode(e,o){const t=new $root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.itemId=e.uint64();break;case 2:t.similarItemList.push($root.CoreML.Specification.ItemSimilarityRecommender.ConnectedItem.decode(e,e.uint32()));break;case 3:t.itemScoreAdjustment=e.double();break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.prototype.itemId=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.CoreML.Specification.ItemSimilarityRecommender.SimilarItems.prototype.itemScoreAdjustment=0,$root.CoreML.Specification.LinkedModel=class{constructor(){}get LinkType(){return $root.CoreML.Specification.LinkedModel.LinkTypeSet=$root.CoreML.Specification.LinkedModel.LinkTypeSet||new Set(["linkedModelFile"]),Object.keys(this).find((e=>$root.CoreML.Specification.LinkedModel.LinkTypeSet.has(e)&&null!=this[e]))}static decode(e,o){const t=new $root.CoreML.Specification.LinkedModel,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linkedModelFile=$root.CoreML.Specification.LinkedModelFile.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LinkedModelFile=class{constructor(){}static decode(e,o){const t=new $root.CoreML.Specification.LinkedModelFile,r=e.next(o);for(;e.end(r);){const o=e.uint32();switch(o>>>3){case 1:t.linkedModelFileName=$root.CoreML.Specification.StringParameter.decode(e,e.uint32());break;case 2:t.linkedModelSearchPath=$root.CoreML.Specification.StringParameter.decode(e,e.uint32());break;default:e.skipType(7&o)}}return t}},$root.CoreML.Specification.LinkedModelFile.prototype.linkedModelFileName=null,$root.CoreML.Specification.LinkedModelFile.prototype.linkedModelSearchPath=null; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/coreml.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/coreml.js new file mode 100644 index 0000000000000000000000000000000000000000..b267622a1d12cd3b2ef1644232074d6cdee8c3b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/coreml.js @@ -0,0 +1 @@ +var coreml=coreml||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");coreml.ModelFactory=class{match(e){return"mlmodel"==e.identifier.split(".").pop().toLowerCase()}open(e,t){return t.require("./coreml-proto").then((()=>{const i=e.identifier;let r=null;try{coreml.proto=protobuf.get("coreml").CoreML.Specification;const t=protobuf.Reader.create(e.buffer);r=coreml.proto.Model.decode(t)}catch(e){throw new coreml.Error("File format is not coreml.Model ("+e.message+") in '"+i+"'.")}return coreml.Metadata.open(t).then((e=>{try{return new coreml.Model(e,r)}catch(e){t.exception(e,!1);const r=e&&e.message?e.message:e.toString();throw new coreml.Error(r.replace(/\.$/,"")+" in '"+i+"'.")}}))}))}},coreml.Model=class{constructor(e,t){if(this._specificationVersion=t.specificationVersion,this._graphs=[new coreml.Graph(e,t)],t.description&&t.description.metadata){const i=t.description.metadata;i.versionString&&(this._version=i.versionString),i.author&&(this._author=i.author),i.shortDescription&&(this._description=i.shortDescription),i.license&&(this._license=i.license),e.userDefined&&Object.keys(i.userDefined).length}}get format(){return"Core ML v"+this._specificationVersion.toString()}get version(){return this._version||null}get description(){return this._description||null}get author(){return this._author||null}get license(){return this._license||null}get graphs(){return this._graphs}},coreml.Graph=class{constructor(e,t){this._metadata=e,this._description=t.description,this._groups=!1,this._inputs=[],this._outputs=[],this._nodes=[],this._description&&(this._inputs=this._description.input.map((e=>{const t=new coreml.Argument(e.name,coreml.Graph._formatFeatureType(e.type),e.shortDescription,null);return new coreml.Parameter(e.name,!0,[t])})),this._outputs=this._description.output.map((e=>{const t=new coreml.Argument(e.name,coreml.Graph._formatFeatureType(e.type),e.shortDescription,null);return new coreml.Parameter(e.name,!0,[t])}))),this._type=this._loadModel(t,{},"")}get name(){return""}get type(){return this._type}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get groups(){return this._groups}_updateOutput(e,t){for(const i of this._nodes)for(const r of i.outputs)for(const i of r.arguments)i.name===e&&(i.name=t);return t}_updateClassifierOutput(e,t){let i=t.labelProbabilityLayerName;if(!i&&this._nodes.length>0){const e=this._nodes.slice(-1).pop();e&&1==e.outputs.length&&1==e.outputs[0].arguments.length&&(i=e.outputs[0].arguments[0].name)}let r=this._description.predictedFeatureName,s=this._description.predictedProbabilitiesName;if((r||s)&&i&&t.ClassLabels){r=r||"?",s=s||"?";const e=this._updateOutput(i,i+":labelProbabilityLayerName"),a=t.ClassLabels;this._nodes.push(new coreml.Node(this._metadata,this._group,a,null,"",t[a],[e],[s,r]))}}_updatePreprocessing(e,t,i){if(i&&i.length>0){const r=this._description.input[0].name,s=[];for(const e of this._nodes)e.inputs.some((e=>e.arguments.some((e=>e.name==r))))&&s.push(e);let a=r,n=0;for(const s of i){const i=s.featureName?s.featureName:a;a=r+":"+n.toString(),this._createNode(e,t,s.preprocessor,null,"",s[s.preprocessor],[i],[a]),n++}for(const e of s)for(const t of e.inputs)for(const e of t.arguments)e.name===r&&(e.name=a)}}_loadModel(e,t,i){this._groups=this._groups|i.length>0;const r=e&&e.description&&e.description.metadata&&e.description.metadata.shortDescription?e.description.metadata.shortDescription:"";switch(e.Type){case"neuralNetworkClassifier":{const s=e.neuralNetworkClassifier;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updateClassifierOutput(i,s),this._updatePreprocessing(t,i,s.preprocessing),"Neural Network Classifier"}case"neuralNetwork":{const s=e.neuralNetwork;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updatePreprocessing(t,i,s.preprocessing),"Neural Network"}case"neuralNetworkRegressor":{const s=e.neuralNetworkRegressor;for(const e of s.layers)this._createNode(t,i,e.layer,e.name,r,e[e.layer],e.input,e.output);return this._updatePreprocessing(t,i,s),"Neural Network Regressor"}case"pipeline":for(let r=0;re.name)),e.description.output.map((e=>e.name))),"Item Similarity Recommender";case"linkedModel":return this._createNode(t,i,"linkedModel",null,r,e.linkedModel.linkedModelFile,[e.description.input[0].name],[e.description.output[0].name]),"Linked Model";case"customModel":return this._createNode(t,i,"customModel",null,r,{className:e.customModel.className,parameters:e.customModel.parameters},[e.description.input[0].name],[e.description.output[0].name]),"customModel"}throw new coreml.Error("Unknown model type '"+JSON.stringify(Object.keys(e))+"'.")}_createNode(e,t,i,r,s,a,n,o){n=n.map((t=>e[t]?e[t].argument:t)),o=o.map((t=>{if(e[t]){e[t].counter++;const i=t+"\n"+e[t].counter.toString();return e[t].argument=i,i}return e[t]={argument:t,counter:0},t}));const u=new coreml.Node(this._metadata,t,i,r,s,a,n,o);return this._nodes.push(u),u}static _formatFeatureType(e){let t="?";if(e){switch(e.Type){case"multiArrayType":{let i=new coreml.TensorShape([]);e.multiArrayType.shape&&e.multiArrayType.shape.length>0&&(i=new coreml.TensorShape(e.multiArrayType.shape));let r="?";switch(e.multiArrayType.dataType){case coreml.proto.ArrayFeatureType.ArrayDataType.FLOAT32:r="float32";break;case coreml.proto.ArrayFeatureType.ArrayDataType.INT32:r="int32";break;case coreml.proto.ArrayFeatureType.ArrayDataType.DOUBLE:r="float64"}t=new coreml.TensorType(r,i);break}case"stringType":t=new coreml.TensorType("string");break;case"doubleType":t=new coreml.TensorType("float64");break;case"int64Type":t=new coreml.TensorType("int64");break;case"dictionaryType":t=new coreml.MapType(e.dictionaryType.KeyType.replace("KeyType",""),"float64");break;case"imageType":t=new coreml.ImageType(e.imageType.colorSpace,e.imageType.width,e.imageType.height)}e.isOptional&&(t=new coreml.OptionalType(t))}return t}static _formatFeatureDescriptionList(e){return e.map((e=>e.name))}},coreml.Parameter=class{constructor(e,t,i){this._name=e,this._visible=t,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},coreml.Argument=class{constructor(e,t,i,r){if("string"!=typeof e)throw new coreml.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t,this._description=i||null,this._initializer=r||null}get name(){return this._name}set name(e){this._name=e}get type(){return this._initializer?this._initializer.type:this._type}get description(){return this._description}get quantization(){return this._initializer?this._initializer.quantization:null}get initializer(){return this._initializer}},coreml.Node=class{constructor(e,t,i,r,s,a,n,o){if(this._metadata=e,t&&(this._group=t),!i)throw new Error("Undefined node type.");this._type=i,this._name=r||"",this._description=s||"",this._attributes=[];const u=[];if(a){const t=this._initialize(a,u);for(const i of Object.keys(a))if(!t[i]){const t=e.attribute(this.type,i);this._attributes.push(new coreml.Attribute(t,i,a[i]))}}this._inputs=this._metadata.getInputs(this._type,n).map((e=>new coreml.Parameter(e.name,!0,e.arguments.map((e=>new coreml.Argument(e.name,e.type,null,null)))))),this._inputs=this._inputs.concat(u),this._outputs=o.map(((e,t)=>{const i=this._metadata.getOutputName(this._type,t);return new coreml.Parameter(i,!0,[new coreml.Argument(e,null,null,null)])}))}get type(){return this._type}get name(){return this._name}get description(){return this._description}get metadata(){return this._metadata.type(this.type)}get group(){return this._group?this._group:null}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}_initialize(e,t){switch(this._type){case"convolution":{const i=[e.outputChannels,e.kernelChannels,e.kernelSize[0],e.kernelSize[1]];return e.isDeconvolution&&(i[0]=e.kernelChannels,i[1]=Math.floor(e.outputChannels/(0!=e.nGroups?e.nGroups:1))),this._initializer(t,"Weights","weights",i,e.weights),e.hasBias&&this._initializer(t,"Weights","bias",[e.outputChannels],e.bias),{weights:!0,bias:e.hasBias}}case"innerProduct":return this._initializer(t,"Weights","weights",[e.outputChannels,e.inputChannels],e.weights),e.hasBias&&this._initializer(t,"Weights","bias",[e.outputChannels],e.bias),{weights:!0,bias:e.hasBias};case"batchnorm":return this._initializer(t,"Weights","gamma",[e.channels],e.gamma),this._initializer(t,"Weights","beta",[e.channels],e.beta),e.mean&&this._initializer(t,"Weights","mean",[e.channels],e.mean),e.variance&&this._initializer(t,"Weights","variance",[e.channels],e.variance),{gamma:!0,beta:!0,mean:!0,variance:!0};case"embedding":return this._initializer(t,"Weights","weights",[e.inputDim,e.outputChannels],e.weights),{weights:!0};case"loadConstant":return this._initializer(t,"Weights","data",e.shape,e.data),{data:!0};case"scale":return this._initializer(t,"Weights","scale",e.shapeScale,e.scale),e.hasBias&&this._initializer(t,"Weights","bias",e.shapeBias,e.bias),{scale:!0,bias:e.hasBias};case"bias":return this._initializer(t,"Weights","bias",e.shape,e.bias),{bias:!0};case"simpleRecurrent":return this._initializer(t,"Weights","weights",[e.outputVectorSize,e.inputVectorSize],e.weightMatrix),this._initializer(t,"Weights","recurrent",[e.outputVectorSize,e.inputVectorSize],e.recursionMatrix),e.hasBiasVectors&&this._initializer(t,"Weights","bias",[e.outputVectorSize],e.biasVector),{weightMatrix:!0,recursionMatrix:!0,biasVector:e.hasBiasVectors};case"gru":{const i=[e.outputVectorSize,e.outputVectorSize],r=[e.outputVectorSize,e.inputVectorSize],s=[e.outputVectorSize];return this._initializer(t,"Weights","updateGateWeightMatrix",r,e.updateGateWeightMatrix),this._initializer(t,"Weights","resetGateWeightMatrix",r,e.resetGateWeightMatrix),this._initializer(t,"Weights","outputGateWeightMatrix",r,e.outputGateWeightMatrix),this._initializer(t,"Weights","updateGateRecursionMatrix",i,e.updateGateRecursionMatrix),this._initializer(t,"Weights","resetGateRecursionMatrix",i,e.resetGateRecursionMatrix),this._initializer(t,"Weights","outputGateRecursionMatrix",i,e.outputGateRecursionMatrix),e.hasBiasVectors&&(this._initializer(t,"Weights","updateGateBiasVector",s,e.updateGateBiasVector),this._initializer(t,"Weights","resetGateBiasVector",s,e.resetGateBiasVector),this._initializer(t,"Weights","outputGateBiasVector",s,e.outputGateBiasVector)),{updateGateWeightMatrix:!0,resetGateWeightMatrix:!0,outputGateWeightMatrix:!0,updateGateRecursionMatrix:!0,resetGateRecursionMatrix:!0,outputGateRecursionMatrix:!0,updateGateBiasVector:e.hasBiasVectors,resetGateBiasVector:e.hasBiasVectors,outputGateBiasVector:e.hasBiasVectors}}case"uniDirectionalLSTM":case"biDirectionalLSTM":{const i="uniDirectionalLSTM"==this._type?1:2,r=[e.outputVectorSize,e.inputVectorSize],s=[e.outputVectorSize];for(let a=0;a0;)e=e[t.shift()];e&&e[this._value]&&(this._value=e[this.value])}Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible?this._visible=!1:Object.prototype.hasOwnProperty.call(e,"default")&&(Array.isArray(i)&&(i=i.map((e=>e&&long.Long.isLong(e)?e.toNumber():e))),JSON.stringify(e.default)==JSON.stringify(i)&&(this._visible=!1))}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},coreml.Tensor=class{constructor(e,t,i,r){this._kind=e,this._name=t,this._data=null;let s="?";r&&(r.floatValue&&r.floatValue.length>0?(this._data=r.floatValue,s="float32"):r.float16Value&&r.float16Value.length>0?(this._data=r.float16Value,s="float16"):r.rawValue&&r.rawValue.length>0&&(r.quantization?(this._data=r.rawValue,s="uint"+r.quantization.numberOfBits.toString()):i=[]),this._quantization=r.quantization||null),this._type=new coreml.TensorType(s,new coreml.TensorShape(i))}get name(){return this._name}get kind(){return this._kind}get type(){return this._type}get quantization(){if(this._quantization){if(this._quantization.lookupTableQuantization&&this._quantization.lookupTableQuantization.floatValue&&this._quantization.lookupTableQuantization.floatValue.length>0){const e=[];for(const t of Object.keys(this._quantization.lookupTableQuantization.floatValue))e.push(t.toString()+" = "+this._quantization.lookupTableQuantization.floatValue[t].toString());return e.join("; ")}return"?"}return null}get state(){return this._context().state}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);return JSON.stringify(t,null,4)}_context(){const e={state:null,index:0,count:0};if(e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,!this._data)return e.state="Tensor data is empty.",e;switch(e.dataType){case"float32":e.data=this._data;break;case"float16":e.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:this._quantization?(e.dataType="quantization",e.bits=long.Long.isLong(this._quantization.numberOfBits)?this._quantization.numberOfBits.toNumber():this._quantization.numberOfBits,e.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength)):e.state="Tensor data type is not implemented."}return e}_decode(e,t){const i=[],r=e.dimensions[t];if(t==e.dimensions.length-1)for(let t=0;te.limit)return i.push("..."),i;switch(e.dataType){case"float32":i.push(this._data[e.index]),e.index++;break;case"float16":i.push(e.data.getFloat16(e.index,!0)),e.index+=2;break;case"quantization":i.push(e.data.getBits(e.index,e.bits)),e.index++}e.count++}else for(let s=0;se.limit)return i.push("..."),i;i.push(this._decode(e,t+1))}return i}},coreml.TensorType=class{constructor(e,t){this._dataType=e,this._shape=t||new coreml.TensorShape([])}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},coreml.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((e=>e.toString())).join(",")+"]":""}},coreml.MapType=class{constructor(e,t){this._keyType=e,this._valueType=t}get keyType(){return this._keyType}get valueType(){return this._valueType}toString(){return"map<"+this._keyType+","+this._valueType.toString()+">"}},coreml.ImageType=class{constructor(e,t,i){switch(this._colorSpace="?",e){case coreml.proto.ImageFeatureType.ColorSpace.GRAYSCALE:this._colorSpace="Grayscale";break;case coreml.proto.ImageFeatureType.ColorSpace.RGB:this._colorSpace="RGB";break;case coreml.proto.ImageFeatureType.ColorSpace.BGR:this._colorSpace="BGR"}this._width=t,this._height=i}toString(){return"image<"+this._colorSpace+","+this._width.toString()+"x"+this._height.toString()+">"}},coreml.OptionalType=class{constructor(e){this._type=e}toString(){return this._type.toString()+"?"}},coreml.Metadata=class{static open(e){return coreml.Metadata._metadata?Promise.resolve(coreml.Metadata._metadata):e.request(null,"coreml-metadata.json","utf-8").then((e=>(coreml.Metadata._metadata=new coreml.Metadata(e),coreml.Metadata._metadata))).catch((()=>(coreml.Metadata._metadata=new coreml.Metadata(null),coreml.Metadata._metadata)))}constructor(e){if(this._map=new Map,this._attributeCache=new Map,this._inputCache={},e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.get(e)}attribute(e,t){const i=e+":"+t;if(!this._attributeCache.has(i)){const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const i of t.attributes)this._attributeCache.set(e+":"+i.name,i);this._attributeCache.has(i)||this._attributeCache.set(i,null)}return this._attributeCache.get(i)}getInputSchema(e,t){let i=this._inputCache[e];if(!i){i={};const t=this.type(e);if(t&&t.inputs&&t.inputs.length>0)for(const e of t.inputs)i[e.name]=e;this._inputCache[e]=i}return i[t]||null}getInputs(e,t){const i=[],r=this._map[e];let s=0;for(;s{const s=t.identifier,n=s.split(".");n.pop();const o=n.join(".");return t.request(o+".weights",null).then((n=>this._openModel(e,s,t.text,n))).catch((()=>this._openModel(e,s,t.text,null)))}))}_openModel(t,e,s,n){try{return new darknet.Model(t,s,n?new darknet.Weights(n):null)}catch(t){const s=t&&t.message?t.message:t.toString();throw new darknet.Error(s.replace(/\.$/,"")+" in '"+e+"'.")}}},darknet.Model=class{constructor(t,e,s){this._graphs=[],this._graphs.push(new darknet.Graph(t,e,s))}get format(){return"Darknet"}get graphs(){return this._graphs}},darknet.Graph=class{constructor(t,e,s){this._inputs=[],this._outputs=[],this._nodes=[];const n=[];let o=null;const u=e.split("\n");let a=0;for(;u.length>0;){a++;const t=u.shift(),e=t.replace(/\s/g,"");if(e.length>0)switch(e[0]){case"#":case";":break;case"[":o={},o.line=a,o.type="]"===e[e.length-1]?e.substring(1,e.length-1):e.substring(1),o.options={},n.push(o);break;default:if(!o||e[0]<32||e[0]>126)throw new darknet.Error("Invalid cfg '"+t.replace(/[^\x20-\x7E]+/g,"").trim()+"' at line "+a.toString()+".");if(o){const s=e.indexOf("=");if(s<0)throw new darknet.Error("Invalid cfg '"+t.replace(/[^\x20-\x7E]+/g,"").trim()+"' at line "+a.toString()+".");const n=e.substring(0,s),u=e.substring(s+1);o.options[n]=u}}}const r=(t,e,s)=>{let n=t[e];if("string"==typeof n&&n.startsWith("$")){const t=n.substring(1);n=g.has(t)?g.get(t):n}if(void 0!==n){const s=parseInt(n,10);if(!Number.isInteger(s))throw new darknet.Error("Invalid int option '"+JSON.stringify(t[e])+"'.");return s}return s},i=(t,e,s)=>{const n=t[e];return void 0!==n?n:s},h=(t,e)=>{if(t.some((t=>0===t||void 0===t||isNaN(t))))throw new darknet.Error("Invalid tensor shape '"+JSON.stringify(t)+"' in '"+e+"'.");return new darknet.TensorShape(t)},l=(t,e,n)=>{const o=s?s.bytes(4*e.reduce(((t,e)=>t*e))):null,u=new darknet.TensorType("float32",h(e,"load_weights")),a=new darknet.Tensor(u,o),r=new darknet.Argument("",null,a);return new darknet.Parameter(t,!1!==n,[r])},p=(t,e,s)=>{t.weights.push(l(e+"scale",[s],""===e)),t.weights.push(l(e+"mean",[s],""===e)),t.weights.push(l(e+"variance",[s],""===e))},c=(t,e,s,n,o,u,a,r,i,c,_,w)=>{t.out_w=Math.floor((s+2*_-r)/i)+1,t.out_h=Math.floor((n+2*_-r)/c)+1,t.out_c=u,t.out=t.out_w*t.out_h*t.out_c,t.weights.push(l(e+"biases",[u],""===e)),w&&p(t,e,u),t.weights.push(l(e+"weights",[Math.floor(o/a),u,r,r],""===e)),t.outputs[0].type=new darknet.TensorType("float32",h([t.out_w,t.out_h,t.out_c],"make_convolutional_layer"))},_=(t,e,s,n,o)=>{t.out_h=1,t.out_w=1,t.out_c=n,t.out=n,t.weights.push(l(e+"biases",[n],""===e)),o&&p(t,e,n),t.weights.push(l(e+"weights",[s,n],""===e)),t.outputs[0].type=new darknet.TensorType("float32",h([n],"make_connected_layer"))},w={},g=new Map,d=n.shift();switch(d.type){case"net":case"network":w.h=r(d.options,"height",0),w.w=r(d.options,"width",0),w.c=r(d.options,"channels",0),w.inputs=r(d.options,"inputs",w.h*w.w*w.c);for(const t of Object.keys(d.options))g.set(t,d.options[t])}const y=w.w&&w.h&&w.c?new darknet.TensorType("float32",h([w.w,w.h,w.c],"params-if")):new darknet.TensorType("float32",h([w.inputs],"params-else")),f="input";if(w.arguments=[new darknet.Argument(f,y,null)],this._inputs.push(new darknet.Parameter(f,!0,w.arguments)),0===n.length)throw new darknet.Error("Config file has no sections.");let m=!0;for(let t=0;tNumber.parseInt(t.trim(),10))):[];for(let s of e){s=s<0?t+s:s;const e=n[s].layer;e&&u.inputs.push(e.outputs[0])}delete o.from;break}case"sam":case"scale_channels":{let e=r(o,"from",0);e=e<0?t+e:e;const s=n[e].layer;s&&u.inputs.push(s.outputs[0]),delete o.from;break}case"route":{u.inputs=[],u.layers=[];const e=o.layers?o.layers.split(",").map((t=>Number.parseInt(t.trim(),10))):[];for(let s=0;s>1:r(o,"padding",0);let h=r(o,"stride_x",-1),l=r(o,"stride_y",-1);if(h<1||l<1){const t=r(o,"stride",1);h=h<1?t:h,l=l<1?t:l}const p=r(o,"groups",1),_=r(o,"batch_normalize",0),g=i(o,"activation","logistic");c(u,"",w.w,w.h,w.c,n,p,s,h,l,a,_),"logistic"!==g&&e.chain.push({type:g});break}case"connected":{const t=r(o,"output",1),s=r(o,"batch_normalize",0),n=i(o,"activation","logistic");_(u,"",w.inputs,t,s),"logistic"!==n&&e.chain.push({type:n});break}case"local":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before avgpool layer must output image.");const s=r(o,"filters",1),n=r(o,"size",1),a=r(o,"stride",1),p=r(o,"pad",0),c=i(o,"activation","logistic");u.out_h=Math.floor((w.h-(p?1:n))/a)+1,u.out_w=Math.floor((w.w-(p?1:n))/a)+1,u.out_c=s,u.out=u.out_w*u.out_h*u.out_c,u.weights.push(l("weights",[w.c,s,n,n,u.out_h*u.out_w])),u.weights.push(l("biases",[u.out_w*u.out_h*u.out_c])),u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"local")),"logistic"!==c&&e.chain.push({type:c});break}case"batchnorm":u.out_h=w.h,u.out_w=w.w,u.out_c=w.c,u.out=u.in,p(s,e,"",u.out),u.outputs[0].type=new darknet.TensorType("float32",h([u.ouputs],"batchnorm"));break;case"activation":u.out_h=w.h,u.out_w=w.w,u.out_c=w.c,u.out=u.in,u.outputs[0].type=new darknet.TensorType("float32",h([u.ouputs],"activation"));break;case"max":case"maxpool":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before maxpool layer must output image.");const e=r(o,"antialiasing",0),s=r(o,"stride",1),n=r(o,"stride_x",s),a=r(o,"stride_y",s),i=e?1:n,l=e?1:a,p=r(o,"size",s),_=r(o,"padding",p-1),g=r(o,"out_channels",1);if(r(o,"maxpool_depth",0)?(u.out_c=g,u.out_w=w.w,u.out_h=w.h):(u.out_w=Math.floor((w.w+_-p)/i)+1,u.out_h=Math.floor((w.h+_-p)/l)+1,u.out_c=w.c),e){const t=2===e?2:3,s=2===e?0:Math.floor(t/3);u.input_layer={weights:[],outputs:u.outputs},c(u.input_layer,"",u.out_h,u.out_w,u.out_c,u.out_c,u.out_c,t,n,a,s,0),u.out_w=u.input_layer.out_w,u.out_h=u.input_layer.out_h,u.out_c=u.input_layer.out_c}else u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"maxpool"));u.out=u.out_w*u.out_h*u.out_c;break}case"avgpool":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before avgpool layer must output image.");u.out_w=1,u.out_h=1,u.out_c=w.c,u.out=u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"avgpool"));break}case"crnn":{const t=r(o,"size",3),e=r(o,"stride",1),s=r(o,"output",1),n=r(o,"hidden",1),a=r(o,"groups",1),i=r(o,"pad",0)?t>>1:r(o,"padding",0),h=r(o,"batch_normalize",0);u.input_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},c(u.input_layer,"input_",w.h,w.w,w.c,n,a,t,e,e,i,h),u.self_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},c(u.self_layer,"self_",w.h,w.w,n,n,a,t,e,e,i,h),u.output_layer={weights:[],outputs:u.outputs},c(u.output_layer,"output_",w.h,w.w,n,s,a,t,e,e,i,h),u.weights=u.weights.concat(u.input_layer.weights),u.weights=u.weights.concat(u.self_layer.weights),u.weights=u.weights.concat(u.output_layer.weights),u.out_h=u.output_layer.out_h,u.out_w=u.output_layer.out_w,u.out_c=s,u.out=u.output_layer.out;break}case"rnn":{const t=r(o,"output",1),e=r(o,"hidden",1),s=r(o,"batch_normalize",0),n=w.inputs;u.input_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_layer,"input_",n,e,s),u.self_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.self_layer,"self_",e,e,s),u.output_layer={weights:[],outputs:u.outputs},_(u.output_layer,"output_",e,t,s),u.weights=u.weights.concat(u.input_layer.weights),u.weights=u.weights.concat(u.self_layer.weights),u.weights=u.weights.concat(u.output_layer.weights),u.out_w=1,u.out_h=1,u.out_c=t,u.out=t;break}case"gru":{const t=w.inputs,e=r(o,"output",1),s=r(o,"batch_normalize",0);u.input_z_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_z_layer,"input_z",t,e,s),u.state_z_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_z_layer,"state_z",e,e,s),u.input_r_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_r_layer,"input_r",t,e,s),u.state_r_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_r_layer,"state_r",e,e,s),u.input_h_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.input_h_layer,"input_h",t,e,s),u.state_h_layer={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.state_h_layer,"state_h",e,e,s),u.weights=u.weights.concat(u.input_z_layer.weights),u.weights=u.weights.concat(u.state_z_layer.weights),u.weights=u.weights.concat(u.input_r_layer.weights),u.weights=u.weights.concat(u.state_r_layer.weights),u.weights=u.weights.concat(u.input_h_layer.weights),u.weights=u.weights.concat(u.state_h_layer.weights),u.out=e,u.outputs[0].type=new darknet.TensorType("float32",h([e],"gru"));break}case"lstm":{const t=w.inputs,e=r(o,"output",1),n=r(o,"batch_normalize",0);u.uf={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.uf,"uf_",t,e,n),u.ui={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.ui,"ui_",t,e,n),u.ug={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.ug,"ug_",t,e,n),u.uo={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.uo,"uo_",t,e,n),u.wf={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wf,"wf_",e,e,n),u.wi={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wi,"wi_",e,e,n),u.wg={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wg,"wg_",e,e,n),u.wo={weights:[],outputs:[new darknet.Argument("",null,null)]},_(u.wo,"wo_",e,e,n),u.weights=u.weights.concat(u.uf.weights),u.weights=u.weights.concat(u.ui.weights),u.weights=u.weights.concat(u.ug.weights),u.weights=u.weights.concat(u.uo.weights),u.weights=u.weights.concat(u.wf.weights),u.weights=u.weights.concat(u.wi.weights),u.weights=u.weights.concat(u.wg.weights),u.weights=u.weights.concat(u.wo.weights),u.out_w=1,u.out_h=1,u.out_c=e,u.out=e,u.outputs[0].type=new darknet.TensorType("float32",h([e],"lstm")),s=null;break}case"softmax":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"softmax"));break;case"dropout":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"dropout"));break;case"upsample":{const t=r(o,"stride",2);u.out_w=w.w*t,u.out_h=w.h*t,u.out_c=w.c,u.out=u.out_w*u.out_h*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"upsample"));break}case"crop":{const t=u.inputs[0].type.shape.dimensions;if(t[0]!==w.w||t[1]!==w.h||t[2]!==w.c)throw new darknet.Error("Layer before crop layer must output image.");const e=r(o,"crop_height",1),s=r(o,"crop_width",1);u.out_w=s,u.out_h=e,u.out_c=w.c,u.out=u.out_w*u.out_h*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"crop"));break}case"yolo":{const t=r(o,"classes",20),e=r(o,"num",1);u.out_h=w.h,u.out_w=w.w,u.out_c=e*(t+4+1),u.out=u.out_h*u.out_w*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"yolo"));break}case"Gaussian_yolo":{const t=r(o,"classes",20),e=r(o,"num",1);u.out_h=w.h,u.out_w=w.w,u.out_c=e*(t+8+1),u.out=u.out_h*u.out_w*u.out_c,u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"Gaussian_yolo"));break}case"region":{const t=r(o,"coords",4),e=r(o,"classes",20),s=r(o,"num",1);u.out=w.h*w.w*s*(e+t+1),u.outputs[0].type=new darknet.TensorType("float32",h([w.h,w.w,s,e+t+1],"region"));break}case"cost":u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"cost"));break;case"reorg":{const t=r(o,"stride",1),e=r(o,"reverse",0),s=r(o,"extra",0);e?(u.out_w=w.w*t,u.out_h=w.h*t,u.out_c=Math.floor(w.c/(t*t))):(u.out_w=Math.floor(w.w/t),u.out_h=Math.floor(w.h/t),u.out_c=w.c*(t*t)),u.out=u.out_h*u.out_w*u.out_c,s&&(u.out_w=0,u.out_h=0,u.out_c=0,u.out=w.h*w.w*w.c+s),u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"reorg"));break}case"route":{const t=[].concat(u.layers),e=r(o,"groups",1);u.out=0;for(const s of t)u.out+=s.outputs/e;if(t.length>0){const s=t.shift();for(u.out_w=s.out_w,u.out_h=s.out_h,u.out_c=s.out_c/e;t.length>0;){const e=t.shift();if(e.out_w!==s.out_w||e.out_h!==s.out_h){m=!1;break}u.out_c+=e.out_c}m&&(u.outputs[0].type=new darknet.TensorType("float32",h([u.out_w,u.out_h,u.out_c],"route")))}else m=!1;m||(u.out_h=0,u.out_w=0,u.out_c=0);break}case"shortcut":case"scale_channels":case"sam":{const t=i(o,"activation","linear");u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.w*w.h*w.c,u.outputs[0].type=new darknet.TensorType("float32",h([w.w,w.h,w.c],"shortcut|scale_channels|sam")),"linear"!==t&&e.chain.push({type:t});break}case"detection":u.out_w=w.w,u.out_h=w.h,u.out_c=w.c,u.out=w.inputs,u.outputs[0].type=new darknet.TensorType("float32",h([u.out],"detection"));break;default:m=!1}w.h=u.out_h,w.w=u.out_w,w.c=u.out_c,w.inputs=u.out,w.last=e}w.arguments=u.outputs}for(let e=0;e0&&this._inputs.push(new darknet.Parameter(n.inputs.length<=1?"input":"inputs",!0,n.inputs)),n&&n.weights&&n.weights.length>0&&(this._inputs=this._inputs.concat(n.weights)),n&&n.outputs&&n.outputs.length>0&&this._outputs.push(new darknet.Parameter(n.outputs.length<=1?"output":"outputs",!0,n.outputs)),s.chain)for(const n of s.chain)this._chain.push(new darknet.Node(t,e,n,""));const o=s.options;if(o)for(const e of Object.keys(o))this._attributes.push(new darknet.Attribute(t.attribute(this._type,e),e,o[e]))}get name(){return this._name}get location(){return this._location}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}},darknet.Attribute=class{constructor(t,e,s){if(this._name=e,this._value=s,t){switch(this._type=t.type||"",this._type){case"int32":{const t=parseInt(this._value,10);Number.isInteger(t)&&(this._value=t);break}case"float32":{const t=parseFloat(this._value);isNaN(t)||(this._value=t);break}case"int32[]":{const t=this._value.split(",").map((t=>parseInt(t.trim(),10)));t.every((t=>Number.isInteger(t)))&&(this._value=t);break}}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&this._value==t.default)&&(this._visible=!1)}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},darknet.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Tensor"}get name(){return""}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={};return this._data?(t.state=null,t.position=0,t.count=0,t.dataView=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dimensions=this.type.shape.dimensions,t):(t.state="Tensor data is empty.",t)}_decode(t,e){const s=[],n=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return s.push("..."),s;s.push(t.dataView.getFloat32(t.position,!0)),t.position+=4,t.count++}else for(let o=0;ot.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return s}},darknet.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this._dataType||"?")+this._shape.toString()}},darknet.TensorShape=class{constructor(t){if(t.some((t=>0===t||void 0===t||isNaN(t))))throw new darknet.Error("Invalid tensor shape '"+JSON.stringify(t)+"'.");this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},darknet.Weights=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0;const e=this.int32(),s=this.int32(),n=this.int32();if(this._seen=10*e+s>=2?this.int64():this.int32(),e>1e3||s>1e3)throw new darknet.Error("Unsupported transpose weights file version '"+[e,s,n].join(".")+"'.")}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int64(){const t=this.int32(),e=this.int32();return new long.Long(t,e,!0).toNumber()}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new darknet.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}validate(){if(this._position!==this._buffer.length)throw new darknet.Error("Invalid weights size.")}},darknet.Metadata=class{static open(t){return darknet.Metadata._metadata?Promise.resolve(darknet.Metadata._metadata):t.request(null,"darknet-metadata.json","utf-8").then((t=>(darknet.Metadata._metadata=new darknet.Metadata(t),darknet.Metadata._metadata))).catch((()=>(darknet.Metadata._metadata=new darknet.Metadata(null),darknet.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeMap=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)if(t&&t.name&&t.schema){if(this._map.has(t.name))throw new darknet.Error("Duplicate metadata key '"+t.name+"'.");t.schema.name=t.name,this._map.set(t.name,t.schema)}}}type(t){return this._map.get(t)||null}attribute(t,e){const s=t+":"+e;if(!this._attributeMap.has(s)){this._attributeMap.set(s,null);const e=this.type(t);if(e&&e.attributes)for(const s of e.attributes)this._attributeMap.set(t+":"+s.name,s)}return this._attributeMap.get(s)}},darknet.Error=class extends Error{constructor(t){super(t),this.name="Error loading Darknet model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=darknet.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..646ce4d993b6239b2f208ad12b2710bf1ff86d52 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j-metadata.json @@ -0,0 +1 @@ +[{"name":"Dense","schema":{"category":"Layer","attributes":[]}},{"name":"Output","schema":{"category":"Layer","attributes":[]}},{"name":"Convolution","schema":{"category":"Layer","attributes":[{"name":"dilation"},{"name":"kernelSize"},{"name":"padding"}]}},{"name":"SeparableConvolution2D","schema":{"category":"Layer","attributes":[]}},{"name":"BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"eps"},{"name":"gamma"},{"name":"decay"}]}},{"name":"Sigmoid","schema":{"category":"Activation","attributes":[]}},{"name":"LReLU","schema":{"category":"Activation","attributes":[]}},{"name":"ReLU","schema":{"category":"Activation","attributes":[]}},{"name":"TanH","schema":{"category":"Activation","attributes":[]}},{"name":"Softmax","schema":{"category":"Activation","attributes":[]}},{"name":"Merge","schema":{"category":"Tensor","attributes":[]}},{"name":"Upsampling2D","schema":{"category":"Layer","attributes":[]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[]}},{"name":"GlobalPooling","schema":{"category":"Pool","attributes":[]}},{"name":"Subsampling","schema":{"category":"Layer","attributes":[]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j.js new file mode 100644 index 0000000000000000000000000000000000000000..854345a94072a77f8f4fbefe6f60c9e368c917ba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/dl4j.js @@ -0,0 +1 @@ +var dl4j=dl4j||{},long=long||{Long:require("long")};dl4j.ModelFactory=class{match(t){return!!("zip"===t.identifier.toLowerCase().split(".").pop().toLowerCase()&&t.entries("zip").length>0&&dl4j.ModelFactory._openContainer(t))}open(t,e){const n=t.identifier;try{const s=dl4j.ModelFactory._openContainer(t),r=JSON.parse(s.configuration);return dl4j.Metadata.open(e).then((t=>{try{return new dl4j.Model(t,r,s.coefficients)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new dl4j.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}}))}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();return Promise.reject(new dl4j.Error(s.replace(/\.$/,"")+" in '"+n+"'."))}}static _openContainer(t){const e=t.entries("zip"),n=e.filter((t=>"configuration.json"===t.name));if(1!=n.length)return null;let s=null;try{s=new TextDecoder("utf-8").decode(n[0].data)}catch(t){return null}if(-1===s.indexOf('"vertices"')&&-1===s.indexOf('"confs"'))return null;const r=e.filter((t=>"coefficients.bin"===t.name));return r.length>1?null:{configuration:s,coefficients:1==r.length?r[0].data:[]}}},dl4j.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new dl4j.Graph(t,e,n))}get format(){return"Deeplearning4j"}get graphs(){return this._graphs}},dl4j.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new dl4j.NDArrayReader(n).dataType;if(e.networkInputs)for(const t of e.networkInputs)this._inputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,null)]));if(e.networkOutputs)for(const t of e.networkOutputs)this._outputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,null)]));let r=null;if(e.vertices)for(const n in e.vertices){const i=dl4j.Node._object(e.vertices[n]);r=e.vertexInputs[n];let a=[],o=null;switch(i.__type__){case"LayerVertex":o=dl4j.Node._object(i.layerConf.layer),a=i.layerConf.variables;break;case"MergeVertex":o={__type__:"Merge",layerName:n};break;case"ElementWiseVertex":o={__type__:"ElementWise",layerName:n,op:i.op};break;case"PreprocessorVertex":o={__type__:"Preprocessor",layerName:n};break;default:throw new dl4j.Error("Unsupported vertex class '"+i["@class"]+"'.")}this._nodes.push(new dl4j.Node(t,o,r,s,a))}if(e.confs){r=["input"],this._inputs.push(new dl4j.Parameter("input",!0,[new dl4j.Argument("input",null,null)]));for(const n of e.confs){const e=dl4j.Node._object(n.layer);this._nodes.push(new dl4j.Node(t,e,r,s,n.variables)),r=[e.layerName]}this._outputs.push(new dl4j.Parameter("output",!0,[new dl4j.Argument(r[0],null,null)]))}}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},dl4j.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},dl4j.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new dl4j.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e,this._initializer=n}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},dl4j.Node=class{constructor(t,e,n,s,r){if(this._metadata=t,this._type=e.__type__,this._name=e.layerName||"",this._inputs=[],this._outputs=[],this._attributes=[],n&&n.length>0){const t=n.map((t=>new dl4j.Argument(t,null,null)));this._inputs.push(new dl4j.Parameter(t.length<2?"input":"inputs",!0,t))}if(r)for(const t of r){let n=null;switch(this._type){case"Convolution":switch(t){case"W":n=new dl4j.Tensor(s,e.kernelSize.concat([e.nin,e.nout]));break;case"b":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"SeparableConvolution2D":switch(t){case"W":n=new dl4j.Tensor(s,e.kernelSize.concat([e.nin,e.nout]));break;case"pW":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"Output":case"Dense":switch(t){case"W":n=new dl4j.Tensor(s,[e.nout,e.nin]);break;case"b":n=new dl4j.Tensor(s,[e.nout]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}break;case"BatchNormalization":n=new dl4j.Tensor(s,[e.nin]);break;default:throw new dl4j.Error("Unknown '"+this._type+"' variable '"+t+"'.")}this._inputs.push(new dl4j.Parameter(t,!0,[new dl4j.Argument(t,null,n)]))}this._name&&this._outputs.push(new dl4j.Parameter("output",!0,[new dl4j.Argument(this._name,null,null)]));let i=e;if(e.activationFn){const n=dl4j.Node._object(e.activationFn);"ActivationIdentity"!==n.__type__&&"Identity"!==n.__type__&&(n.__type__.startsWith("Activation")&&(n.__type__=n.__type__.substring("Activation".length)),"Activation"==this._type?(this._type=n.__type__,i=n):(this._chain=this._chain||[],this._chain.push(new dl4j.Node(t,n,[],null,null))))}for(const e in i){switch(e){case"__type__":case"constraints":case"layerName":case"activationFn":case"idropout":case"hasBias":continue}this._attributes.push(new dl4j.Attribute(t.attribute(this._type,e),e,i[e]))}if(e.idropout&&1!==dl4j.Node._object(e.idropout).p)throw new dl4j.Error("Layer 'idropout' not implemented.")}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}get chain(){return this._chain}static _object(t){let e={};if(t["@class"]){e=t;let n=t["@class"].split(".").pop();n.endsWith("Layer")&&(n=n.substring(0,n.length-5)),delete t["@class"],e.__type__=n}else{let n=Object.keys(t)[0];e=t[n],n.length>0&&(n=n[0].toUpperCase()+n.substring(1)),e.__type__=n}return e}},dl4j.Attribute=class{constructor(t,e,n){this._name=e,this._value=n,this._visible=!1,t&&t.visible&&(this._visible=!0)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return this._visible}},dl4j.Tensor=class{constructor(t,e){this._type=new dl4j.TensorType(t,new dl4j.TensorShape(e))}get type(){return this._type}get state(){return"Not implemented."}},dl4j.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},dl4j.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},dl4j.Metadata=class{static open(t){return dl4j.Metadata.textDecoder=dl4j.Metadata.textDecoder||new TextDecoder("utf-8"),dl4j.Metadata._metadata?Promise.resolve(dl4j.Metadata._metadata):t.request(null,"dl4j-metadata.json","utf-8").then((t=>(dl4j.Metadata._metadata=new dl4j.Metadata(t),dl4j.Metadata._metadata))).catch((()=>(dl4j.Metadata._metadata=new dl4j.Metadata(null),dl4j.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t&&t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},dl4j.NDArrayReader=class{constructor(t){const e=new dl4j.BinaryReader(t);dl4j.NDArrayReader._header(e);const n=dl4j.NDArrayReader._header(e);this._dataType=n.type}get dataType(){return this._dataType}static _header(t){const e={};switch(e.alloc=t.string(),e.length=0,e.alloc){case"DIRECT":case"HEAP":case"JAVACPP":e.length=t.int32();break;case"LONG_SHAPE":case"MIXED_DATA_TYPES":e.length=t.int64()}switch(e.type=t.string(),e.type){case"INT":e.type="int32",e.itemsize=4;break;case"FLOAT":e.type="float32",e.itemsize=4}return e.data=t.bytes(e.itemsize*e.length),e}},dl4j.BinaryReader=class{constructor(t){this._buffer=t,this._position=0}bytes(t){const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}string(){const t=this._buffer[this._position++]<<8|this._buffer[this._position++],e=this.bytes(t);return new TextDecoder("ascii").decode(e)}int32(){return this._buffer[this._position++]<<24|this._buffer[this._position++]<<16|this._buffer[this._position++]<<8|this._buffer[this._position++]}int64(){const t=this.int32(),e=this.int32();return new long.Long(t,e,!0).toNumber()}},dl4j.Error=class extends Error{constructor(t){super(t),this.name="Error loading Deeplearning4j model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=dl4j.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/flatbuffers.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/flatbuffers.js new file mode 100644 index 0000000000000000000000000000000000000000..882e63fca1d772daa5f6ba9fb4db4701eca2e03a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/flatbuffers.js @@ -0,0 +1 @@ +var flatbuffers={},long=long||{Long:require("long")};flatbuffers.get=t=>(flatbuffers._map=flatbuffers._map||new Map,flatbuffers._map.has(t)||flatbuffers._map.set(t,{}),flatbuffers._map.get(t)),flatbuffers.Long=long.Long,flatbuffers.Reader=class{constructor(t){this._buffer=t,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength)}get root(){return this.int32(this._position)+this._position}identifier(t){if(4!==t.length)throw new flatbuffers.Error("File identifier must be 4 characters in length.");for(let r=0;r<4;r++)if(t.charCodeAt(r)!=this.int8(this._position+4+r))return!1;return!0}bool(t){return!!this.int8(t)}bool_(t,r,e){return(r=this._offset(t,r))?this.bool(t+r):e}int8(t){return this.uint8(t)<<24>>24}int8_(t,r,e){return(r=this._offset(t,r))?this.int8(t+r):e}uint8(t){return this._buffer[t]}uint8_(t,r,e){return(r=this._offset(t,r))?this.uint8(t+r):e}int16(t){return this._dataView.getInt16(t,!0)}int16_(t,r,e){return(r=this._offset(t,r))?this.int16(t+r):e}uint16(t){return this._dataView.getUint16(t,!0)}uint16_(t,r,e){return(r=this._offset(t,r))?this.uint16(t+r):e}int32(t){return this._dataView.getInt32(t,!0)}int32_(t,r,e){return(r=this._offset(t,r))?this.int32(t+r):e}uint32(t){return this._dataView.getUint32(t,!0)}uint32_(t,r,e){return(r=this._offset(t,r))?this.int32(t+r):e}int64(t){return new flatbuffers.Long(this.int32(t),this.int32(t+4))}uint64(t){return new flatbuffers.Long(this.uint32(t),this.uint32(t+4))}float32(t){return this._dataView.getFloat32(t,!0)}float32_(t,r,e){return(r=this._offset(t,r))?this.float32(t+r):e}float64(t){return this._dataView.getFloat64(t,!0)}float64_(t,r,e){return(r=this._offset(t,r))?this.float64(t+r):e}string(t,r){t+=this.int32(t);const e=this.int32(t);var i="",n=0;if(t+=4,1===r)return this._buffer.subarray(t,t+e);for(;n>10),56320+(1023&s)))}return i}string_(t,r,e){return(r=this._offset(t,r))?this.string(t+r):e}bools_(t,r){if(r=this._offset(t,r)){const e=this._length(t+r);r=this._vector(t+r);const i=new Array(e);for(let t=0;t>3)),this.uint32(r+(t>>3)+4),!1);return i}return[]}strings_(t,r){if(r=this._offset(t,r)){const e=this._length(t+r);r=this._vector(t+r);const i=new Array(e);for(let t=0;t{let r=null;const o=t.identifier;try{const e=new a.Reader(t.buffer).read(),o=flux.ModelFactory._backref(e,e);if(r=o.model,!r)throw new flux.Error("File does not contain Flux model.")}catch(t){const e=t&&t.message?t.message:t.toString();throw new flux.Error(e.replace(/\.$/,"")+" in '"+o+"'.")}return flux.Metadata.open(e).then((t=>{try{return new flux.Model(t,r)}catch(t){const e=t&&t.message?t.message:t.toString();throw new flux.Error(e.replace(/\.$/,"")+" in '"+o+"'.")}}))}))}static _backref(t,e){if(Array.isArray(t))for(let a=0;a(flux.Metadata._metadata=new flux.Metadata(t),flux.Metadata._metadata))).catch((()=>(flux.Metadata._metadata=new flux.Metadata(null),flux.Metadata._metadatas)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let a=this._attributeCache[t];if(!a){a={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)a[t.name]=t;this._attributeCache[t]=a}return a[e]||null}},flux.Error=class extends Error{constructor(t){super(t),this.name="Flux Error"}},module&&module.exports&&(module.exports.ModelFactory=flux.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/gzip.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/gzip.js new file mode 100644 index 0000000000000000000000000000000000000000..66788e5257ed8d5c291ed04bb6c07798083105de --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/gzip.js @@ -0,0 +1 @@ +var gzip=gzip||{};gzip.Archive=class{constructor(t){if(this._entries=[],t.length<18||31!=t[0]||139!=t[1])throw new gzip.Error("Invalid gzip archive.");const i=new gzip.Reader(t,0,t.length);this._entries.push(new gzip.Entry(i))}get entries(){return this._entries}},gzip.Entry=class{constructor(t){if(!t.match([31,139]))throw new gzip.Error("Invalid gzip signature.");const i=t.byte();if(8!=i)throw new gzip.Error("Invalid compression method '"+i.toString()+"'.");const s=t.byte();if(t.uint32(),t.byte(),t.byte(),0!=(4&s)){const i=t.uint16();t.skip(i)}0!=(8&s)&&(this._name=t.string()),0!=(16&s)&&t.string(),0!=(1&s)&&t.uint16();const n=t.bytes();if("object"==typeof process&&"object"==typeof process.versions&&void 0!==process.versions.node?this._data=require("zlib").inflateRawSync(n):"undefined"!=typeof pako?this._data=pako.inflateRaw(n):this._data=new require("./zip").Inflater().inflateRaw(n),t.position=-8,t.uint32(),t.uint32()!=this._data.length)throw new gzip.Error("Invalid size.")}get name(){return this._name}get data(){return this._data}},gzip.Reader=class{constructor(t,i,s){this._buffer=t,this._position=i,this._end=s}match(t){if(this._position+t.length<=this._end)for(let i=0;i=0?t:this._end+t}skip(t){if(this._position+t>this._end)throw new gzip.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new gzip.Error("Data not available.");t=void 0===t?this._end:t;const i=this._buffer.subarray(this._position,this._position+t);return this._position+=t,i}byte(){if(this._position+1>this._end)throw new gzip.Error("Data not available.");const t=this._buffer[this._position];return this._position++,t}uint16(){if(this._position+2>this._end)throw new gzip.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}string(){let t="";const i=this._buffer.indexOf(0,this._position);if(i<0)throw new gzip.Error("End of string not found.");for(;this._position0&&(this._indexedStorageInternalNodeK=e.uint16(),this.seek(2)),this._baseAddress=e.offset(),e.offset(),this._endOfFileAddress=e.offset(),e.offset(),0!=this._baseAddress)throw new hdf5.Error("Base address is not zero.");const t=new hdf5.SymbolTableEntry(e);this._rootGroup=new hdf5.Group(e,t,null,this._globalHeap,"","");break}case 2:case 3:{e.initialize(),e.byte(),this._baseAddress=e.offset(),this._superBlockExtensionAddress=e.offset(),this._endOfFileAddress=e.offset();const t=new hdf5.DataObjectHeader(e.at(e.offset()));this._rootGroup=new hdf5.Group(e,null,t,this._globalHeap,"","");break}default:throw new hdf5.Error("Unsupported Superblock version "+s+".")}}get rootGroup(){return this._rootGroup}},hdf5.Group=class{constructor(t,e,s,i,a,r){this._reader=t,this._entry=e,this._dataObjectHeader=s,this._globalHeap=i,this._name=r,this._path="/"==a?a+r:a+"/"+r}get name(){return this._name}get path(){return this._path}group(t){this._decodeGroups();const e=t.indexOf("/");if(-1!=e){const s=t.substring(e+1),i=t.substring(0,e),a=this.group(i);if(null!=a)return a.group(s)}else{const e=this._groupMap[t];if(e)return e}return null}get groups(){return this._decodeGroups(),this._groups}attribute(t){return this._decodeDataObject(),this._attributes[t]}get attributes(){return this._decodeDataObject(),this._attributes}get value(){return this._decodeDataObject(),this._value}_decodeDataObject(){if(this._dataObjectHeader||(this._dataObjectHeader=new hdf5.DataObjectHeader(this._reader.at(this._entry.objectHeaderAddress))),!this._attributes){this._attributes={};for(const t of this._dataObjectHeader.attributes){const e=t.name,s=t.decodeValue(this._globalHeap);this._attributes[e]=s}this._value=null;const t=this._dataObjectHeader.datatype,e=this._dataObjectHeader.dataspace,s=this._dataObjectHeader.dataLayout,i=this._dataObjectHeader.filterPipeline;t&&e&&s&&(this._value=new hdf5.Variable(this._reader,this._globalHeap,t,e,s,i))}}_decodeGroups(){if(!this._groups)if(this._groupMap={},this._groups=[],this._entry){if(this._entry.treeAddress||this._entry.heapAddress){const t=new hdf5.Heap(this._reader.at(this._entry.heapAddress)),e=new hdf5.Tree(this._reader.at(this._entry.treeAddress));for(const s of e.nodes)for(const e of s.entries){const s=t.getString(e.linkNameOffset),i=new hdf5.Group(this._reader,e,null,this._globalHeap,this._path,s);this._groups.push(i),this._groupMap[s]=i}}}else{this._decodeDataObject();for(const t of this._dataObjectHeader.links)if(Object.prototype.hasOwnProperty.call(t,"objectHeaderAddress")){const e=t.name,s=new hdf5.DataObjectHeader(this._reader.at(t.objectHeaderAddress)),i=new hdf5.Group(this._reader,null,s,this._globalHeap,this._path,e);this._groups.push(i),this._groupMap[e]=i}}}},hdf5.Variable=class{constructor(t,e,s,i,a,r){this._reader=t,this._globalHeap=e,this._datatype=s,this._dataspace=i,this._dataLayout=a,this._filterPipeline=r}get type(){return this._datatype.type}get littleEndian(){return this._datatype.littleEndian}get shape(){return this._dataspace.shape}get value(){const t=this.data;if(t){const e=new hdf5.Reader(t),s=this._dataspace.read(this._datatype,e);return this._dataspace.decode(this._datatype,s,s,this._globalHeap)}return null}get data(){switch(this._dataLayout.layoutClass){case 1:if(this._dataLayout.address)return this._reader.at(this._dataLayout.address).bytes(this._dataLayout.size);break;case 2:{const t=new hdf5.Tree(this._reader.at(this._dataLayout.address),this._dataLayout.dimensionality);if(2==this._dataLayout.dimensionality&&1==this._dataspace.shape.length){let e=this._dataLayout.datasetElementSize;for(let t=0;tthis._buffer.length)throw new hdf5.Error("Expected "+(this._position+this._offset-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}int8(){const t=this._offset;return this.skip(1),this._dataView.getInt8(this._position+t)}byte(){const t=this._offset;return this.skip(1),this._dataView.getUint8(this._position+t)}bytes(t){const e=this._offset;return this.skip(t),this._buffer.subarray(this._position+e,this._position+this._offset)}int16(){const t=this._offset;return this.skip(2),this._dataView.getInt16(this._position+t,!0)}uint16(){const t=this._offset;return this.skip(2),this._dataView.getUint16(this._position+t,!0)}int32(){const t=this._offset;return this.skip(4),this._dataView.getInt32(this._position+t,!0)}uint32(){const t=this._offset;return this.skip(4),this._dataView.getUint32(this._position+t,!0)}int64(){const t=this._offset;this.skip(8);const e=this._dataView.getUint32(this._position+t,!0),s=this._dataView.getUint32(this._position+t+4,!0);return new long.Long(e,s,!1).toNumber()}uint64(){const t=this._offset;this.skip(8);const e=this._dataView.getUint32(this._position+t,!0),s=this._dataView.getUint32(this._position+t+4,!0);return new long.Long(e,s,!0).toNumber()}uint(t){switch(t){case 0:return this.byte();case 1:return this.uint16();case 2:return this.uint32();case 3:return this.uint64()}}float16(){const t=this._offset;this.skip(2);const e=this._dataView.getUint16(this._position+t,!0),s=(32768&e)>>15,i=(31744&e)>>10,a=1023&e;return 0==i?(s?-1:1)*Math.pow(2,-14)*(a/Math.pow(2,10)):31==i?a?NaN:1/0*(s?-1:1):(s?-1:1)*Math.pow(2,i-15)*(1+a/Math.pow(2,10))}float32(){const t=this._offset;return this.skip(4),this._dataView.getFloat32(this._position+t,!0)}float64(){const t=this._offset;return this.skip(8),this._dataView.getFloat64(this._position+t,!0)}string(t,e){if(!t||-1==t){let e=this._position+this._offset;for(;0!=this._buffer[e];)e++;t=e-this._position-this._offset+1}const s=this.bytes(t);return hdf5.Reader.decode(s,e)}static decode(t,e){let s="";return"utf-8"==e?(hdf5.Reader._utf8Decoder||(hdf5.Reader._utf8Decoder=new TextDecoder("utf-8")),s=hdf5.Reader._utf8Decoder.decode(t)):(hdf5.Reader._asciiDecoder||(hdf5.Reader._asciiDecoder=new TextDecoder("ascii")),s=hdf5.Reader._asciiDecoder.decode(t)),s.replace(/\0/g,"")}offset(){switch(this._offsetSize){case 8:{const t=this.uint32(),e=this.uint32();if(4294967295===t&&4294967295===e)return;return new long.Long(t,e,!0).toNumber()}case 4:{const t=this.uint32();if(4294967295===t)return;return t}}throw new hdf5.Error("Unsupported offset size '"+this._offsetSize+"'.")}length(){switch(this._lengthSize){case 8:{const t=this.uint32(),e=this.uint32();if(4294967295===t&&4294967295===e)return;return new long.Long(t,e,!0).toNumber()}case 4:{const t=this.uint32();if(4294967295===t)return;return t}}throw new hdf5.Error("Unsupported length size '"+this._lengthSize+"'.")}at(t){const e=new hdf5.Reader(null);return e._buffer=this._buffer,e._dataView=this._dataView,e._position=t,e._offset=0,e._offsetSize=this._offsetSize,e._lengthSize=this._lengthSize,e}clone(){const t=new hdf5.Reader(this._buffer,this._position);return t._buffer=this._buffer,t._dataView=this._dataView,t._position=this._position,t._offset=this._offset,t._offsetSize=this._offsetSize,t._lengthSize=this._lengthSize,t}align(t){this._offset%t!=0&&(this._offset=(Math.floor(this._offset/t)+1)*t)}match(t){if(this._position+this._offset+t.length>this._buffer.length)return!1;const e=this._offset,s=this.bytes(t.length);for(let i=0;i=i)&&this.continuations.length>0){const e=this.continuations.shift();t=t.at(e.offset),i=e.offset+e.length}else t.align(8)}break}case 2:{const e=t.byte();0!=(32&e)&&(t.uint32(),t.uint32(),t.uint32(),t.uint32()),0!=(16&e)&&(t.uint16(),t.uint16());const s=t.uint(3&e);let i=!0,a=t.position+s;for(;i&&t.position=a)&&this.continuations.length>0){const e=this.continuations.shift();if(t=t.at(e.offset),a=e.offset+e.length,!t.match("OCHK"))throw new hdf5.Error("Invalid continuation block signature.");i=!0}}break}default:throw new hdf5.Error("Unsupported data object header version '"+e+"'.")}}_readMessage(t,e,s,i){switch(e){case 0:return!1;case 1:this.dataspace=4!=s||1!=i?new hdf5.Dataspace(t.clone()):null;break;case 2:this.linkInfo=new hdf5.LinkInfo(t.clone());break;case 3:this.datatype=new hdf5.Datatype(t.clone());break;case 4:case 5:this.fillValue=new hdf5.FillValue(t.clone(),e);break;case 6:this.links.push(new hdf5.Link(t.clone()));break;case 8:this.dataLayout=new hdf5.DataLayout(t.clone());break;case 10:this.groupInfo=new hdf5.GroupInfo(t.clone());break;case 11:this.filterPipeline=new hdf5.FilterPipeline(t.clone());break;case 12:this.attributes.push(new hdf5.Attribute(t.clone()));break;case 13:this.comment=t.string(-1,"ascii");break;case 16:this.continuations.push(new hdf5.ObjectHeaderContinuation(t.clone()));break;case 17:this.symbolTable=new hdf5.SymbolTable(t.clone());break;case 14:case 18:this.objectModificationTime=new hdf5.ObjectModificationTime(t.clone(),e);break;case 21:this.attributeInfo=new hdf5.AttributeInfo(t.clone());break;default:throw new hdf5.Error("Unsupported message type '"+e+"'.")}return t.skip(s),!0}},hdf5.Message=class{constructor(t,e,s){this._type=t,this._data=e,this._flags=s}},hdf5.Dataspace=class{constructor(t){this._sizes=[];const e=t.byte();switch(e){case 1:this._dimensions=t.byte(),this._flags=t.byte(),t.skip(1),t.skip(4);for(let e=0;e>4;switch(this._class=15&e,s){case 1:case 2:switch(this._flags=t.byte()|t.byte()<<8|t.byte()<<16,this._size=t.uint32(),this._class){case 0:this._bitOffset=t.uint16(),this._bitPrecision=t.uint16();break;case 8:{this._base=new hdf5.Datatype(t),this._names=[],this._values=[];const e=65535&this._flags;for(let s=0;s>8&15){case 0:return hdf5.Reader.decode(t.bytes(this._size),"ascii");case 1:return hdf5.Reader.decode(t.bytes(this._size),"utf-8")}throw new hdf5.Error("Unsupported character encoding.");case 5:return t.bytes(this._size);case 9:return{length:t.uint32(),globalHeapID:new hdf5.GlobalHeapID(t)}}throw new hdf5.Error("Unsupported datatype class '"+this._class+"'.")}decode(t,e){switch(this._class){case 0:case 1:case 3:case 5:return t;case 9:{const s=e.get(t.globalHeapID);if(null!=s){switch(this._flags>>8&15){case 0:return hdf5.Reader.decode(s.data,"ascii");case 1:return hdf5.Reader.decode(s.data,"utf-8")}throw new hdf5.Error("Unsupported character encoding.")}break}default:throw new hdf5.Error("Unsupported datatype class '"+this._class+"'.")}return null}},hdf5.FillValue=class{constructor(t,e){switch(e){case 4:{const e=t.uint32();this.data=t.bytes(e);break}case 5:default:{const e=t.byte();switch(e){case 1:case 2:{t.byte(),t.byte();const s=t.byte();if(1===e||1===s){const e=t.uint32();this.data=t.bytes(e)}break}default:throw new hdf5.Error("Unsupported fill value version '"+e+"'.")}break}}}},hdf5.Link=class{constructor(t){const e=t.byte();switch(e){case 1:{const e=t.byte();this.type=0!=(8&e)?t.byte():0,0!=(4&e)&&(this.creationOrder=t.uint32());const s=0!=(16&e)&&1==t.byte()?"utf-8":"ascii";switch(this.name=t.string(t.uint(3&e),s),this.type){case 0:this.objectHeaderAddress=t.offset()}break}default:throw new hdf5.Error("Unsupported link message version '"+e+"'.")}}},hdf5.DataLayout=class{constructor(t){const e=t.byte();switch(e){case 1:case 2:switch(this.dimensionality=t.byte(),this.layoutClass=t.byte(),t.skip(5),this.layoutClass){case 1:this.address=t.offset(),this.dimensionSizes=[];for(let e=0;e{var e,t={63332:(e,t,s)=>{var n=s(32845),i=i||{};i.Archive=class{constructor(e){if(this._entries=[],e.length<18||31!=e[0]||139!=e[1])throw new i.Error("Invalid gzip archive.");const t=new i.Reader(e,0,e.length);this._entries.push(new i.Entry(t))}get entries(){return this._entries}},i.Entry=class{constructor(e){if(!e.match([31,139]))throw new i.Error("Invalid gzip signature.");const t=e.byte();if(8!=t)throw new i.Error("Invalid compression method '"+t.toString()+"'.");const o=e.byte();if(e.uint32(),e.byte(),e.byte(),0!=(4&o)){const t=e.uint16();e.skip(t)}0!=(8&o)&&(this._name=e.string()),0!=(16&o)&&e.string(),0!=(1&o)&&e.uint16();const r=e.bytes();if("object"==typeof process&&"object"==typeof process.versions&&void 0!==process.versions.node?this._data=s(83260).inflateRawSync(r):this._data=void 0!==n?n.inflateRaw(r):new s(71681).Inflater().inflateRaw(r),e.position=-8,e.uint32(),e.uint32()!=this._data.length)throw new i.Error("Invalid size.")}get name(){return this._name}get data(){return this._data}},i.Reader=class{constructor(e,t,s){this._buffer=e,this._position=t,this._end=s}match(e){if(this._position+e.length<=this._end)for(let t=0;t=0?e:this._end+e}skip(e){if(this._position+e>this._end)throw new i.Error("Data not available.");this._position+=e}bytes(e){if(this._position+e>this._end)throw new i.Error("Data not available.");e=void 0===e?this._end:e;const t=this._buffer.subarray(this._position,this._position+e);return this._position+=e,t}byte(){if(this._position+1>this._end)throw new i.Error("Data not available.");const e=this._buffer[this._position];return this._position++,e}uint16(){if(this._position+2>this._end)throw new i.Error("Data not available.");const e=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,e}uint32(){return this.uint16()|this.uint16()<<16}string(){let e="";const t=this._buffer.indexOf(0,this._position);if(t<0)throw new i.Error("End of string not found.");for(;this._position{var n=n||{},i=i||{Long:s(27808)};n.get=e=>(n._map=n._map||new Map,n._map.has(e)||n._map.set(e,{}),n._map.get(e)),n.Reader=class{constructor(e){this._buffer=e,this._length=e.length,this._position=0,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._decoder=new TextDecoder("utf-8")}static create(e){return new n.Reader(e)}next(e){return void 0===e?this._length:this._position+e}end(e){return this._positionthis._length)throw this._indexOutOfRangeError(e);return this._position+=e,this._buffer.slice(t,s)}uint32(){let e=4294967295;if(e=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return e;if(e=(e|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return e;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const e=this._position;return this._position+=4,this._dataView.getFloat32(e,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const e=this._position;return this._position+=8,this._dataView.getFloat64(e,!0)}array(e,t,s){if(2==(7&s)){const s=this.uint32()+this._position;for(;this._position0)throw new n.Error("Invalid packed float array.");const t=this.uint32(),s=this._position+t,i=t>>>2;e=t>1048576?new Float32Array(i):new Array(i);let o=this._position;for(let t=0;t0)throw new n.Error("Invalid packed float array.");const t=this.uint32(),s=this._position+t,i=t>>>3;e=t>1048576?new Float64Array(i):new Array(i);let o=this._position;for(let t=0;tthis._length)throw this._indexOutOfRangeError(e);this._position+=e}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw new n.Error("invalid wire type "+e+" at offset "+this._position)}}pair(e,t,s){this.skip(),this._position++;const i="object"==typeof t?n.LongBits.hash(t()):t();this._position++;const o=s();e[i]=o}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const e=this._readFixed32();this._position+=4;const t=this._readFixed32();return new n.LongBits(e,t)}_readLongVarint(){const e=new n.LongBits(0,0);let t=0;if(!(this._length-this._position>4)){for(;t<3;++t){if(this._position>=this._length)throw this._indexOutOfRangeError();if(e.lo=(e.lo|(127&this._buffer[this._position])<<7*t)>>>0,this._buffer[this._position++]<128)return e}return e.lo=(e.lo|(127&this._buffer[this._position++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this._buffer[this._position])<<7*t)>>>0,this._buffer[this._position++]<128)return e;if(e.lo=(e.lo|(127&this._buffer[this._position])<<28)>>>0,e.hi=(e.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return e;if(t=0,this._length-this._position>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this._buffer[this._position])<<7*t+3)>>>0,this._buffer[this._position++]<128)return e}else for(;t<5;++t){if(this._position>=this._length)throw this._indexOutOfRangeError();if(e.hi=(e.hi|(127&this._buffer[this._position])<<7*t+3)>>>0,this._buffer[this._position++]<128)return e}throw new n.Error("Invalid varint encoding.")}_indexOutOfRangeError(e){return RangeError("index out of range: "+this._position+" + "+(e||1)+" > "+this._length)}},n.TextReader=class{constructor(e){this._text=e,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(e){return new n.TextReader(e)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const e=this.peek();return this._depth>0&&"}"===e?(this.expect("}"),this.match(";"),this._depth--,!0):""===e}tag(){const e=this.read(),t=this.peek();return"["!==t&&"{"!==t&&this.expect(":"),e}assert(e){const t=this.tag();if(t!==e)throw new n.Error("Unexpected '"+t+"' instead of '"+e+"'"+this.location())}integer(){const e=this.read(),t=Number.parseInt(e,10);if(Number.isNaN(e-t))throw new n.Error("Couldn't parse integer '"+e+"'"+this.location());return this.semicolon(),t}float(){let e=this.read();if(e.startsWith("nan"))return NaN;if(e.startsWith("inf"))return 1/0;if(e.startsWith("-inf"))return-1/0;e.endsWith("f")&&(e=e.substring(0,e.length-1));const t=Number.parseFloat(e);if(Number.isNaN(e-t))throw new n.Error("Couldn't parse float '"+e+"'"+this.location());return this.semicolon(),t}string(){const e=this.read();if(e.length<2)throw new n.Error("String is too short"+this.location());const t=e[0];if("'"!==t&&'"'!==t)throw new n.Error("String is not in quotes"+this.location());if(t!==e[e.length-1])throw new n.Error("String quotes do not match"+this.location());const s=e.substring(1,e.length-1);return this.semicolon(),s}boolean(){const e=this.read();switch(e){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new n.Error("Couldn't parse boolean '"+e+"'"+this.location())}bytes(){const e=this.string();let t=0,s=0;const i=e.length,o=new Uint8Array(i);for(;t=i)throw new n.Error("Unexpected end of bytes string"+this.location());switch(r=e.charCodeAt(t++),r){case 39:o[s++]=39;break;case 92:o[s++]=92;break;case 34:o[s++]=34;break;case 114:o[s++]=13;break;case 110:o[s++]=10;break;case 116:o[s++]=9;break;case 98:o[s++]=8;break;case 88:case 120:for(let r=0;r<2;r++){if(t>=i)throw new n.Error("Unexpected end of bytes string"+this.location());let r=e.charCodeAt(t++);if(r=r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r>=48&&r<=57?r-48:-1,-1===r)throw new n.Error("Unexpected hex digit '"+r+"' in bytes string"+this.location());o[s]=o[s]<<4|r}s++;break;default:if(r<48||r>57)throw new n.Error("Unexpected character '"+r+"' in bytes string"+this.location());t--;for(let r=0;r<3;r++){if(t>=i)throw new n.Error("Unexpected end of bytes string"+this.location());const r=e.charCodeAt(t++);if(r<48||r>57)throw new n.Error("Unexpected octal digit '"+r+"' in bytes string"+this.location());o[s]=o[s]<<3|r-48}s++}}}return o.slice(0,s)}enum(e){const t=this.read();if(!Object.prototype.hasOwnProperty.call(e,t)){const e=Number.parseInt(t,10);if(!Number.isNaN(t-e))return this.semicolon(),e;throw new n.Error("Couldn't parse enum '"+t+"'"+this.location())}return this.semicolon(),e[t]}any(e){if(this.match("[")){this.read();const t=this._position,s=this._text.indexOf("]",t);if(-1===s||s>=this.next)throw new n.Error("End of Any type_url not found"+this.location());return e.type_url=this._text.substring(t,s),this._position=s+1,e.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(e,t,s){let n,i;for(this.start();!this.end();)switch(this.tag()){case"key":n=t();break;case"value":i=s()}e[n]=i}array(e,t){if(this.first())for(;!this.last();)e.push(t()),this.next();else e.push(t())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const e=this.peek();","!==e?"]"!==e&&this.handle(e):this.read()}skip(){let e=this.peek();if("{"===e){const t=this._position,s=this._depth;for(this.start();!this.end()||s=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let e=this._text[this._position];if("["===e&&this._position+2="a"&&t<="z"||t>="A"&&t<="Z")for(e++;e="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"."===t||"/"===t)&&"]"===t)return this._token=this._text.substring(this._position,e),this._token}if("{"===e||"}"===e||":"===e||"["===e||","===e||"]"===e||";"===e)return this._token=e,this._token;let t=this._position+1;if(e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e||"$"===e){for(;t="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"+"===e||"-"===e);)t++;return this._token=this._text.substring(this._position,t),this._token}if(e>="0"&&e<="9"||"-"===e||"+"===e||"."===e){for(;t="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"+"===e||"-"===e||"."===e);)t++;return this._token=this._text.substring(this._position,t),this._token}if('"'===e||"'"===e){const s=e;for(;t>>0,this.hi=t>>>0}toLong(e){return n.Long?new n.Long(0|this.lo,0|this.hi,e):{low:0|this.lo,high:0|this.hi,unsigned:e}}toNumber(e){if(!e&&this.hi>>>31){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return e||(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}from(e){if("number"==typeof e)return n.LongBits.fromNumber(e);if("string"==typeof e||e instanceof String){if(!n.Long)return n.LongBits.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new n.LongBits(e.low>>>0,e.high>>>0):n.LongBits.zero}hash(e){return e?n.LongBits.from(e).toHash():"\0\0\0\0\0\0\0\0"}},n.LongBits.zero=new n.LongBits(0,0),n.LongBits.zero.toNumber=function(){return 0},n.LongBits.zero.zzDecode=function(){return this},n.Error=class extends Error{constructor(e){super(e),this.name="Protocol Buffer Error",this.message=e}},"object"==typeof e.exports&&(e.exports.Reader=n.Reader,e.exports.TextReader=n.TextReader,e.exports.Error=n.Error,e.exports.Long=n.Long,e.exports.get=n.get)},499:e=>{var t=t||{};t.Archive=class{constructor(e){this._entries=[];const s=new t.Reader(e,0,e.length);for(;s.peek()&&(this._entries.push(new t.Entry(s)),!s.match(512,0)););}get entries(){return this._entries}},t.Entry=class{constructor(e){const s=e.bytes(512);e.skip(-512);let n=0;for(let e=0;e=148&&e<156?32:s[e];this._name=e.string(100),e.string(8),e.string(8),e.string(8);const i=parseInt(e.string(12).trim(),8);e.string(12);const o=parseInt(e.string(8).trim(),8);if(isNaN(o)||n!=o)throw new t.Error("Invalid tar archive.");e.string(1),e.string(100),e.bytes(255),this._data=e.bytes(i),e.bytes(i%512!=0?512-i%512:0)}get name(){return this._name}get data(){return this._data}},t.Reader=class{constructor(e){this._buffer=e,this._position=0,this._end=e.length}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new t.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}peek(){return this._positione==t)))&&(this._position+=e,!0)}bytes(e){const t=this._position;return this.skip(e),this._buffer.subarray(t,this._position)}string(e){const t=this.bytes(e);let s=0,n="";for(let i=0;i{var n=n||{},i=i||s(46506);n.Renderer=class{constructor(e,t){this._document=e,this._svgElement=t}render(e){const t=this.createElement("g");t.setAttribute("id","clusters"),t.setAttribute("class","clusters"),this._svgElement.appendChild(t);const s=this.createElement("g");s.setAttribute("id","edge-paths"),s.setAttribute("class","edge-paths"),this._svgElement.appendChild(s);const o=this.createElement("g");o.setAttribute("id","edge-labels"),o.setAttribute("class","edge-labels"),this._svgElement.appendChild(o);const r=this.createElement("g");r.setAttribute("id","nodes"),r.setAttribute("class","nodes"),this._svgElement.appendChild(r);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t),n=this.createElement("g");s.id&&n.setAttribute("id",s.id),n.setAttribute("class",Object.prototype.hasOwnProperty.call(s,"class")?"node "+s.class:"node"),n.style.opacity=0;const i=this.createElement("g");i.appendChild(s.label),n.appendChild(i),r.appendChild(n);const o=s.label.getBBox(),a=-o.width/2,h=-o.height/2;i.setAttribute("transform","translate("+a+","+h+")"),s.width=o.width,s.height=o.height,s.element=n}for(const t of e.edges()){const s=e.edge(t);if(s.label){const e=this.createElement("tspan");e.setAttribute("xml:space","preserve"),e.setAttribute("dy","1em"),e.setAttribute("x","1"),e.appendChild(this._document.createTextNode(s.label));const t=this.createElement("text");t.appendChild(e);const n=this.createElement("g");n.appendChild(t);const i=this.createElement("g");i.style.opacity=0,i.setAttribute("class","edge-label"),i.appendChild(n),o.appendChild(i);const r=n.getBBox(),a=-r.width/2,h=-r.height/2;n.setAttribute("transform","translate("+a+","+h+")"),s.width=r.width,s.height=r.height,s.labelElement=i}}i.layout(e);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);s.element.setAttribute("transform","translate("+s.x+","+s.y+")"),s.element.style.opacity=1,delete s.element}for(const t of e.edges()){const s=e.edge(t);s.labelElement&&(s.labelElement.setAttribute("transform","translate("+s.x+","+s.y+")"),s.labelElement.style.opacity=1,delete s.labelElement)}const a=this.createElement("defs");s.appendChild(a);const h=this.createElement("marker");h.setAttribute("id","arrowhead-vee"),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX",9),h.setAttribute("refY",5),h.setAttribute("markerUnits","strokeWidth"),h.setAttribute("markerWidth",8),h.setAttribute("markerHeight",6),h.setAttribute("orient","auto"),a.appendChild(h);const c=this.createElement("path");c.setAttribute("d","M 0 0 L 10 5 L 0 10 L 4 5 z"),c.style.setProperty("stroke-width",1),c.style.setProperty("stroke-dasharray","1,0"),h.appendChild(c);for(const t of e.edges()){const i=e.edge(t),o=n.Renderer._computeCurvePath(i,e.node(t.v),e.node(t.w)),r=this.createElement("path");r.setAttribute("class",Object.prototype.hasOwnProperty.call(i,"class")?"edge-path "+i.class:"edge-path"),r.setAttribute("d",o),r.setAttribute("marker-end","url(#arrowhead-vee)"),i.id&&r.setAttribute("id",i.id),s.appendChild(r)}for(const s of e.nodes())if(e.children(s).length>0){const n=e.node(s),i=this.createElement("g");i.setAttribute("class","cluster"),i.setAttribute("transform","translate("+n.x+","+n.y+")");const o=this.createElement("rect");o.setAttribute("x",-n.width/2),o.setAttribute("y",-n.height/2),o.setAttribute("width",n.width),o.setAttribute("height",n.height),n.rx&&o.setAttribute("rx",n.rx),n.ry&&o.setAttribute("ry",n.ry),i.appendChild(o),t.appendChild(i)}}createElement(e){return this._document.createElementNS("http://www.w3.org/2000/svg",e)}static _computeCurvePath(e,t,s){const i=e.points.slice(1,e.points.length-1);i.unshift(n.Renderer.intersectRect(t,i[0])),i.push(n.Renderer.intersectRect(s,i[i.length-1]));const a=new o,h=new r(a);for(let e=0;eMath.abs(i)*c?(o<0&&(c=-c),r=0===o?0:c*i/o,a=c):(i<0&&(h=-h),r=h,a=0===i?0:h*o/i),{x:s+r,y:n+a}}},n.NodeElement=class{constructor(e){this._document=e,this._blocks=[]}block(e){switch(this._block=null,e){case"header":this._block=new n.NodeElement.Header(this._document);break;case"list":this._block=new n.NodeElement.List(this._document)}return this._blocks.push(this._block),this._block}format(e){const t=this.createElement("g");e.appendChild(t);let s=0,i=0;const o=[];for(const e of this._blocks)o.push(i),e.layout(t),sthis._width&&(this._width=t)}}get width(){return this._width}get height(){return this._height}update(e,t,s,i,o){const r=s-this._width;let a,h,c;for(a=0;a{var n=s(32845),i=i||{};i.Archive=class{constructor(e){if(this._entries=[],e.length<4||80!=e[0]||75!=e[1])throw new i.Error("Invalid Zip archive.");let t=null;for(let s=e.length-4;s>=0;s--)if(80===e[s]&&75===e[s+1]&&5===e[s+2]&&6===e[s+3]){t=new i.Reader(e,s+4,e.length);break}if(!t)throw new i.Error("End of central directory not found.");for(t.skip(12),t.position=t.uint32();t.match([80,75,1,2]);)this._entries.push(new i.Entry(t))}get entries(){return this._entries}},i.Entry=class{constructor(e){if(e.uint16(),e.skip(2),this._flags=e.uint16(),1==(1&this._flags))throw new i.Error("Encrypted entries not supported.");this._compressionMethod=e.uint16(),e.uint32(),e.uint32(),this._compressedSize=e.uint32(),this._size=e.uint32();let t=e.uint16(),s=e.uint16();const n=e.uint16();e.uint16(),e.uint16(),e.uint32();const o=e.uint32();e.skip(t),e.skip(s),e.bytes(n);const r=e.position;if(e.position=o,!e.match([80,75,3,4]))throw new i.Error("Invalid local file header signature.");e.skip(22),t=e.uint16(),s=e.uint16();const a=e.bytes(t);this._name="";for(const e of a)this._name+=String.fromCharCode(e);e.skip(s),this._compressedData=e.bytes(this._compressedSize),e.position=r}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new i.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new i.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new i.Error("Invalid uncompressed size.");break;default:throw new i.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},i.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),i.HuffmanTree._offsets=i.HuffmanTree._offsets||new Uint16Array(16)}build(e,t,s){for(let e=0;e<16;++e)this.table[e]=0;for(let n=0;n>>1){case 0:this._inflateUncompressedBlock(t,o);break;case 1:this._inflateBlockData(t,o,i.HuffmanTree.staticLiteralLengthTree,i.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(t,r,a),this._inflateBlockData(t,o,r,a);break;default:throw new i.Error("Unknown block type.")}}while(0==(1&h));return o.merge()}_inflateUncompressedBlock(e,t){for(;e.data>8;)e.position--,e.data-=8;e.data=0;const s=e.uint16();if(s!==(65535&~e.uint16()))throw new i.Error("Invalid uncompressed block length.");const n=e.bytes(s);t.push(n),s>32768?(t.buffer.set(n.subarray(n.length-32768,n.length),0),t.position=32768):(t.reset(),t.buffer.set(n,t.position),t.position+=n.length)}_decodeTrees(e,t,s){const n=e.bits(5)+257,o=e.bits(5)+1,r=e.bits(4)+4;for(let e=0;e<19;e++)i.Inflater._lengths[e]=0;for(let t=0;t62464&&(t.position=r,t.push(new Uint8Array(o.subarray(a,r))),r=t.reset(),a=r);let h=e.symbol(s);if(256===h)return t.position=r,t.push(new Uint8Array(o.subarray(a,t.position))),void t.reset();if(h<256)o[r++]=h;else{h-=257;const t=e.bitsBase(i.Inflater._lengthBits[h],i.Inflater._lengthBase[h]),s=e.symbol(n);let a=r-e.bitsBase(i.Inflater._distanceBits[s],i.Inflater._distanceBase[s]);for(let e=0;e32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(e){this._blocks.push(e)}merge(){let e=0;for(const t of this._blocks)e+=t.length;const t=new Uint8Array(e);let s=0;for(const e of this._blocks)t.set(e,s),s+=e.length;return t}},i.BitReader=class{constructor(e){this.buffer=e,this.position=0,this.data=0,this.value=0}bits(e){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-e;return this.value>>>=e,this.data-=e,t}bitsBase(e,t){if(0==e)return t;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-e;return this.value>>>=e,this.data-=e,s+t}bytes(e){const t=this.buffer.subarray(this.position,this.position+e);return this.position+=e,t}uint16(){const e=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,e}symbol(e){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,n++,t+=o[n],s-=o[n]}while(s>=0);return this.value=i,this.data-=n,e.symbol[t+s]}},i.Reader=class{constructor(e,t,s){this._buffer=e,this._position=t,this._end=s}match(e){if(this._position+e.length<=this._end)for(let t=0;t=0?e:this._end+e}peek(){return this._positionthis._end)throw new i.Error("Data not available.");this._position+=e}bytes(e){if(this._position+e>this._end)throw new i.Error("Data not available.");e=void 0===e?this._end:e;const t=this._buffer.subarray(this._position,this._position+e);return this._position+=e,t}uint16(){if(this._position+2>this._end)throw new i.Error("Data not available.");const e=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,e}uint32(){return this.uint16()|this.uint16()<<16}},i.Error=class extends Error{constructor(e){super(e),this.name="Zip Error"}},"object"==typeof e.exports&&(e.exports.Archive=i.Archive,e.exports.Inflater=i.Inflater)},68138:(e,t,s)=>{const n=s(68513),i=s(24137),o=class{constructor(){window.eval=()=>{throw new Error("window.eval() not supported.")},this._document=window.document,this._meta={};for(const e of Array.from(this._document.getElementsByTagName("meta")))e.content&&(this._meta[e.name]=this._meta[e.name]||[],this._meta[e.name].push(e.content));this._type=this._meta.type?this._meta.type[0]:"Browser",this._version=this._meta.version?this._meta.version[0]:null,this._ready=!1}get document(){return this._document}get version(){return this._version}get type(){return this._type}initialize(e){return this._view=e,Promise.resolve()}start(){window.addEventListener("message",(e=>{const t=e.data;if(t){const e=t.type,s=t.data;switch(e){case"change-files":return this._changeFiles(s);case"zoom-in":return this._view.zoomIn();case"zoom-out":return this._view.zoomOut();case"select-item":return this._view.selectItem(s);case"toggle-Language":return this._view.toggleLanguage(s);case"isAlt":return this._view.changeAlt(s);case"zoom-reset":return this._view.resetZoom();case"toggle-attributes":return this._view.toggleAttributes(s);case"toggle-initializers":return this._view.toggleInitializers(s);case"toggle-names":return this._view.toggleNames(s);case"toggle-KeepData":return this._view.toggleKeepData(s);case"toggle-direction":return this._view.toggleDirection(s);case"toggle-theme":return this._view.toggleTheme(s);case"export":return this._view.export(`${document.title}.${s}`);case"change-graph":return this._view.changeGraph(s);case"change-allGraph":return this._view.changeAllGrap(s);case"change-select":return this._view.changeSelect(s);case"search":return this._view.find(s);case"select":return this._view.select(s);case"show-model-properties":return this._view.showModelProperties();case"show-node-documentation":return this._view.showNodeDocumentation(s);case"show2":return this._view._reload();case"ready":return this._ready?this.status("ready"):void 0}}}),!1),this._ready=!0,this.status("ready")}message(e,t){window.parent&&window.parent.postMessage({type:e,data:t},"*")}status(e){this.message("status",e)}selectNodeId(e){console.log("节点点击事件触发了",e),this.message("nodeId",e)}selectItems(e){console.log("节点点击事件触发了",e),this.message("selectItem",e)}error(e,t){this.message("error",("Error"===e?"":e+" ")+t)}reload(){this.view._reload()}confirm(e,t){const s=confirm(e+" "+t);return s||this.message("cancel"),s}require(e){const t=this._url(e+".js");return window.__modules__=window.__modules__||{},window.__modules__[t]?Promise.resolve(window.__exports__[t]):new Promise(((s,n)=>{window.module={exports:{}};const i=document.createElement("script");i.setAttribute("id",e),i.setAttribute("type","text/javascript"),i.setAttribute("src",t),i.onload=()=>{const t=window.module.exports;delete window.module,window.__modules__[e]=t,s(t)},i.onerror=e=>{delete window.module,n(new Error("The script '"+e.target.src+"' failed to load."))},this.document.head.appendChild(i)}))}save(e,t,s,n){n(s+"."+t)}export(e,t){const s=this.document.createElement("a");s.download=e,s.href=URL.createObjectURL(t),this.document.body.appendChild(s),s.click(),this.document.body.removeChild(s)}request(e,t,s){const n=e?e+"/"+t:this._url(t);return this._request(n,null,s)}_changeFiles(e){if(console.log("files2",e),e&&e?.length){if(console.log("files.length",e.length),!(e=Array.from(e)).find((e=>this._view.accept(e.name))))return void this.error("Error opening file.","Cannot open file "+e[0].name);this._open(e.find((e=>this._view.accept(e.name))),e)}}_request(e,t,s,n){return new Promise(((i,o)=>{const r=new XMLHttpRequest;s||(r.responseType="arraybuffer"),n&&(r.timeout=n);const a=t=>{const s=new Error("The web request failed with status code "+t+" at '"+e+"'.");return s.type="error",s.url=e,s};if(r.onload=()=>{200==r.status?"arraybuffer"==r.responseType?i(new Uint8Array(r.response)):i(r.responseText):o(a(r.status))},r.onerror=e=>{const t=a(r.status);t.type=e.type,o(t)},r.ontimeout=()=>{r.abort();const t=new Error("The web request timed out in '"+e+"'.");t.type="timeout",t.url=e,o(t)},r.open("GET",e,!0),t)for(const e of Object.keys(t))r.setRequestHeader(e,t[e]);r.send()}))}_url(e){let t=e;if(window&&window.location&&window.location.href){let s=window.location.href.split("?").shift();s.endsWith(".html")&&(s=s.split("/").slice(0,-1).join("/")),s.endsWith("/")&&(s=s.slice(0,-1)),t=s+"/"+e}return t}_open(e,t){this.status("loading");const s=new r(e,t);s.open().then((()=>this._view.open(s).then((e=>(this._view.actived&&this.status("rendered"),this.document.title=t[0].name,e))))).catch((e=>{this.error(e.name,e.message)}))}};if("undefined"==typeof TextDecoder&&(TextDecoder=function(e){this._encoding=e},TextDecoder.prototype.decode=function(e){let t="";const s=e.length;let n=0;switch(this._encoding){case"utf-8":for(;n>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=String.fromCharCode(s);break;case 12:case 13:{const i=e[n++];t+=String.fromCharCode((31&s)<<6|63&i);break}case 14:{const i=e[n++],o=e[n++];t+=String.fromCharCode((15&s)<<12|(63&i)<<6|(63&o)<<0);break}}}break;case"ascii":for(;n=55296&&i<=56319){if(r===t){n[s+=1]=239,n[s+=1]=191,n[s+=1]=189;break}if(o=e.charCodeAt(r),!(o>=56320&&o<=57343)){n[s+=1]=239,n[s+=1]=191,n[s+=1]=189;continue}if(i=1024*(i-55296)+o-56320+65536,r+=1,i>65535){n[s+=1]=240|i>>>18,n[s+=1]=128|i>>>12&63,n[s+=1]=128|i>>>6&63,n[s+=1]=128|63&i;continue}}i<=127?n[s+=1]=0|i:i<=2047?(n[s+=1]=192|i>>>6,n[s+=1]=128|63&i):(n[s+=1]=224|i>>>12,n[s+=1]=128|i>>>6&63,n[s+=1]=128|63&i)}return"undefined"!=typeof Uint8Array?new Uint8Array(n.buffer.slice(0,s+1)):n.length===s+1?n:n.slice(0,s+1)},TextEncoder.prototype.toString=function(){return"[object TextEncoder]"};try{Object.defineProperty(TextEncoder.prototype,"encoding",{get:function(){if(Object.prototype.isPrototypeOf.call(TextEncoder.prototype,this))return"utf-8";throw TypeError("Illegal invocation")}})}catch(e){TextEncoder.prototype.encoding="utf-8"}"undefined"!=typeof Symbol&&(TextEncoder.prototype[Symbol.toStringTag]="TextEncoder")}"undefined"==typeof URLSearchParams&&(URLSearchParams=function(e){const t=e=>e.replace(/[ +]/g,"%20").replace(/(%[a-f0-9]{2})+/gi,(e=>decodeURIComponent(e)));if(this._dict={},"string"==typeof e){const s=(e=0===e.indexOf("?")?e.substring(1):e).split("&");for(const e of s){const s=e.indexOf("="),n=t(s>-1?e.substring(0,s):e),i=s>-1?t(e.substring(s+1)):"";Object.prototype.hasOwnProperty.call(this._dict,n)||(this._dict[n]=[]),this._dict[n].push(i)}}},URLSearchParams.prototype.get=function(e){return Object.prototype.hasOwnProperty.call(this._dict,e)?this._dict[e][0]:null}),HTMLCanvasElement.prototype.toBlob||(HTMLCanvasElement.prototype.toBlob=function(e,t,s){setTimeout((()=>{const n=atob(this.toDataURL(t,s).split(",")[1]),i=n.length,o=new Uint8Array(i);for(let e=0;e{this._buffer=e}))}request(e,t){const s=this._blobs[e];return s?new Promise(((n,i)=>{const o=new FileReader;o.onload=e=>{n(t?e.target.result:new Uint8Array(e.target.result))},o.onerror=t=>{let s="";switch((t=t||window.event).target.error.code){case t.target.error.NOT_FOUND_ERR:s="File not found '"+e+"'.";break;case t.target.error.NOT_READABLE_ERR:s="File not readable '"+e+"'.";break;case t.target.error.SECURITY_ERR:s="File access denied '"+e+"'.";break;default:s="File read '"+t.target.error.code.toString()+"' error '"+e+"'."}i(new Error(s))},"utf-8"===t?o.readAsText(s,t):o.readAsArrayBuffer(s)})):Promise.reject(new Error("File not found '"+e+"'."))}}const a=function(e){let t=e.lastIndexOf("/");return e.substring(t+1,e.length)}(document.referrer);console.log("hash",a),window.__view__="static_graph"===a||"x2paddle"===a?new i.View(new o):new n.View(new o)},42473:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>n});const n={leaf_nodes:[{name:"layer",schema:{category:"container"}},{name:"layerlist",schema:{category:"container"}},{name:"parameterlist",schema:{category:"container"}},{name:"layerdict",schema:{category:"container"}},{name:"conv1d",schema:{category:"conv"}},{name:"conv1dtranspose",schema:{category:"conv"}},{name:"conv2d",schema:{category:"conv"}},{name:"conv2dtranspose",schema:{category:"conv"}},{name:"conv3d",schema:{category:"conv"}},{name:"conv3dtranspose",schema:{category:"conv"}},{name:"adaptiveavgpool1d",schema:{category:"pool"}},{name:"adaptiveavgpool2d",schema:{category:"pool"}},{name:"adaptiveavgpool3d",schema:{category:"pool"}},{name:"adaptivemaxpool1d",schema:{category:"pool"}},{name:"adaptivemaxpool2d",schema:{category:"pool"}},{name:"adaptivemaxpool3d",schema:{category:"pool"}},{name:"avgpool1d",schema:{category:"pool"}},{name:"avgpool2d",schema:{category:"pool"}},{name:"avgpool3d",schema:{category:"pool"}},{name:"maxpool1d",schema:{category:"pool"}},{name:"maxpool2d",schema:{category:"pool"}},{name:"maxpool3d",schema:{category:"pool"}},{name:"maxunpool1d",schema:{category:"pool"}},{name:"maxunpool2d",schema:{category:"pool"}},{name:"maxunpool3d",schema:{category:"pool"}},{name:"pad1d",schema:{category:"pad"}},{name:"pad2d",schema:{category:"pad"}},{name:"pad3d",schema:{category:"pad"}},{name:"zeropad2d",schema:{category:"pad"}},{name:"celu",schema:{category:"activation"}},{name:"elu",schema:{category:"activation"}},{name:"gelu",schema:{category:"activation"}},{name:"hardshrink",schema:{category:"activation"}},{name:"hardsigmoid",schema:{category:"activation"}},{name:"hardswish",schema:{category:"activation"}},{name:"hardtanh",schema:{category:"activation"}},{name:"leakyrelu",schema:{category:"activation"}},{name:"logsigmoid",schema:{category:"activation"}},{name:"logsoftmax",schema:{category:"activation"}},{name:"maxout",schema:{category:"activation"}},{name:"prelu",schema:{category:"activation"}},{name:"relu",schema:{category:"activation"}},{name:"relu6",schema:{category:"activation"}},{name:"selu",schema:{category:"activation"}},{name:"sigmoid",schema:{category:"activation"}},{name:"silu",schema:{category:"activation"}},{name:"softmax",schema:{category:"activation"}},{name:"softplus",schema:{category:"activation"}},{name:"softshrink",schema:{category:"activation"}},{name:"softsign",schema:{category:"activation"}},{name:"swish",schema:{category:"activation"}},{name:"mish",schema:{category:"activation"}},{name:"tanh",schema:{category:"activation"}},{name:"tanhshrink",schema:{category:"activation"}},{name:"thresholdedrelu",schema:{category:"activation"}},{name:"batchnorm",schema:{category:"normalization"}},{name:"batchnorm1d",schema:{category:"normalization"}},{name:"batchnorm2d",schema:{category:"normalization"}},{name:"batchnorm3d",schema:{category:"normalization"}},{name:"groupnorm",schema:{category:"normalization"}},{name:"instancenorm1d",schema:{category:"normalization"}},{name:"instancenorm2d",schema:{category:"normalization"}},{name:"instancenorm3d",schema:{category:"normalization"}},{name:"layernorm",schema:{category:"normalization"}},{name:"localresponsenorm",schema:{category:"normalization"}},{name:"spectralnorm",schema:{category:"normalization"}},{name:"syncbatchnorm",schema:{category:"normalization"}},{name:"alphadropout",schema:{category:"normalization"}},{name:"dropout",schema:{category:"normalization"}},{name:"dropout2d",schema:{category:"normalization"}},{name:"dropout3d",schema:{category:"normalization"}},{name:"birnn",schema:{category:"sequence"}},{name:"gru",schema:{category:"sequence"}},{name:"grucell",schema:{category:"sequence"}},{name:"lstm",schema:{category:"sequence"}},{name:"lstmcell",schema:{category:"sequence"}},{name:"rnn",schema:{category:"sequence"}},{name:"rnncellbase",schema:{category:"sequence"}},{name:"simplernn",schema:{category:"sequence"}},{name:"simplernncell",schema:{category:"sequence"}},{name:"multiheadattention",schema:{category:"sequence"}},{name:"transformer",schema:{category:"sequence"}},{name:"transformerdecoder",schema:{category:"sequence"}},{name:"transformerdecoderlayer",schema:{category:"sequence"}},{name:"transformerencoder",schema:{category:"sequence"}},{name:"transformerencoderlayer",schema:{category:"sequence"}},{name:"linear",schema:{category:"sequence"}},{name:"embedding",schema:{category:"sequence"}},{name:"bceloss",schema:{category:"tensor"}},{name:"bcewithlogitsloss",schema:{category:"tensor"}},{name:"crossentropyloss",schema:{category:"tensor"}},{name:"ctcloss",schema:{category:"tensor"}},{name:"hsigmoidloss",schema:{category:"tensor"}},{name:"kldivloss",schema:{category:"tensor"}},{name:"l1loss",schema:{category:"tensor"}},{name:"marginrankingloss",schema:{category:"tensor"}},{name:"mseloss",schema:{category:"tensor"}},{name:"nllloss",schema:{category:"tensor"}},{name:"smoothl1loss",schema:{category:"tensor"}},{name:"pixelshuffle",schema:{category:"shape"}},{name:"upsample",schema:{category:"shape"}},{name:"upsamplingbilinear2d",schema:{category:"shape"}},{name:"upsamplingnearest2d",schema:{category:"shape"}},{name:"clipgradbyglobalnorm",schema:{category:"shape"}},{name:"clipgradbynorm",schema:{category:"shape"}},{name:"clipgradbyvalue",schema:{category:"shape"}},{name:"beamsearchdecoder",schema:{category:"shape"}},{name:"cosinesimilarity",schema:{category:"shape"}},{name:"dynamic_decode",schema:{category:"shape"}},{name:"flatten",schema:{category:"shape"}},{name:"pairwisedistance",schema:{category:"shape"}},{name:"identity",schema:{category:"shape"}},{name:"unfold",schema:{category:"shape"}},{name:"fold",schema:{category:"shape"}},{name:"conv2d_grad",schema:{category:"conv"}},{name:"conv2d_transpose_grad",schema:{category:"conv"}},{name:"depthwise_conv2d_transpose",schema:{category:"conv"}},{name:"depthwise_conv2d_transpose_grad",schema:{category:"conv"}},{name:"deformable_conv_grad",schema:{category:"conv"}},{name:"depthwise_conv2d",schema:{category:"conv"}},{name:"deformable_conv",schema:{category:"conv"}},{name:"conv2d_transpose",schema:{category:"conv"}},{name:"depthwise_conv2d_grad",schema:{category:"conv"}},{name:"pool2d",schema:{category:"pool"}},{name:"pool2d_grad",schema:{category:"pool"}},{name:"max_pool2d_with_index",schema:{category:"pool"}},{name:"max_pool2d_with_index_grad",schema:{category:"pool"}},{name:"pad3d_grad",schema:{category:"pad"}},{name:"relu6_grad",schema:{category:"activation"}},{name:"leaky_relu",schema:{category:"activation"}},{name:"leaky_relu_grad",schema:{category:"activation"}},{name:"hard_sigmoid",schema:{category:"activation"}},{name:"hard_sigmoid_grad",schema:{category:"activation"}},{name:"sigmoid_grad",schema:{category:"activation"}},{name:"batch_norm",schema:{category:"normalization"}},{name:"batch_norm_grad",schema:{category:"normalization"}},{name:"sync_batch_norm",schema:{category:"normalization"}},{name:"sync_batch_norm_grad",schema:{category:"normalization"}},{name:"norm_grad",schema:{category:"normalization"}},{name:"p_norm",schema:{category:"normalization"}},{name:"p_norm_grad",schema:{category:"normalization"}},{name:"group_norm_grad",schema:{category:"normalization"}},{name:"squared_l2_norm",schema:{category:"normalization"}},{name:"squared_l2_norm_grad",schema:{category:"normalization"}},{name:"group_norm",schema:{category:"normalization"}},{name:"norm",schema:{category:"normalization"}},{name:"rnn_grad",schema:{category:"sequence"}},{name:"sequence_mask",schema:{category:"sequence"}},{name:"one_hot",schema:{category:"sequence"}},{name:"one_hot_v2",schema:{category:"sequence"}},{name:"bce_loss",schema:{category:"tensor"}},{name:"bce_loss_grad",schema:{category:"tensor"}},{name:"huber_loss",schema:{category:"tensor"}},{name:"huber_loss_grad",schema:{category:"tensor"}},{name:"log_loss",schema:{category:"tensor"}},{name:"log_loss_grad",schema:{category:"tensor"}},{name:"smooth_l1_loss",schema:{category:"tensor"}},{name:"smooth_l1_loss_grad",schema:{category:"tensor"}},{name:"elementwise_add",schema:{category:"tensor"}},{name:"elementwise_add_grad",schema:{category:"tensor"}},{name:"cumsum",schema:{category:"tensor"}},{name:"clip",schema:{category:"tensor"}},{name:"clip_grad",schema:{category:"tensor"}},{name:"greater_equal",schema:{category:"tensor"}},{name:"greater_than",schema:{category:"tensor"}},{name:"less_equal",schema:{category:"tensor"}},{name:"logical_and",schema:{category:"tensor"}},{name:"logical_or",schema:{category:"tensor"}},{name:"momentum",schema:{category:"tensor"}},{name:"reduce_max",schema:{category:"tensor"}},{name:"reduce_mean",schema:{category:"tensor"}},{name:"reduce_prod",schema:{category:"tensor"}},{name:"seed",schema:{category:"tensor"}},{name:"sigmoid_cross_entropy_with_logits",schema:{category:"tensor"}},{name:"label_smooth",schema:{category:"tensor"}},{name:"where_index",schema:{category:"tensor"}},{name:"is_empty",schema:{category:"tensor"}},{name:"sigmoid_cross_entropy_with_logits_grad",schema:{category:"tensor"}},{name:"target_assign",schema:{category:"tensor"}},{name:"gradient_accumulator",schema:{category:"tensor"}},{name:"size",schema:{category:"tensor"}},{name:"where",schema:{category:"tensor"}},{name:"elementwise_pow_grad",schema:{category:"tensor"}},{name:"argsort",schema:{category:"tensor"}},{name:"argsort_grad",schema:{category:"tensor"}},{name:"rmsprop",schema:{category:"tensor"}},{name:"atan",schema:{category:"tensor"}},{name:"atan_grad",schema:{category:"tensor"}},{name:"flatten_contiguous_range",schema:{category:"tensor"}},{name:"crop",schema:{category:"tensor"}},{name:"eye",schema:{category:"tensor"}},{name:"matmul",schema:{category:"tensor"}},{name:"set_value",schema:{category:"tensor"}},{name:"exp",schema:{category:"tensor"}},{name:"exp_grad",schema:{category:"tensor"}},{name:"square_grad",schema:{category:"tensor"}},{name:"log_softmax",schema:{category:"tensor"}},{name:"log_softmax_grad",schema:{category:"tensor"}},{name:"matmul_grad",schema:{category:"tensor"}},{name:"assign_value",schema:{category:"tensor"}},{name:"top_k_v2",schema:{category:"tensor"}},{name:"arg_max",schema:{category:"tensor"}},{name:"cos",schema:{category:"tensor"}},{name:"sin",schema:{category:"tensor"}},{name:"index_sample",schema:{category:"shape"}},{name:"squeeze_grad",schema:{category:"shape"}},{name:"squeeze2_grad",schema:{category:"shape"}},{name:"stack_grad",schema:{category:"shape"}},{name:"tril_triu",schema:{category:"shape"}},{name:"unstack",schema:{category:"shape"}},{name:"unstack_grad",schema:{category:"shape"}},{name:"bilinear_interp_v2",schema:{category:"shape"}},{name:"bilinear_interp_v2_grad",schema:{category:"shape"}},{name:"nearest_interp_v2",schema:{category:"shape"}},{name:"nearest_interp_v2_grad",schema:{category:"shape"}},{name:"randperm",schema:{category:"shape"}},{name:"sampling_id",schema:{category:"shape"}},{name:"bipartite_match",schema:{category:"shape"}},{name:"box_coder",schema:{category:"shape"}},{name:"density_prior_box",schema:{category:"shape"}},{name:"distribute_fpn_proposals",schema:{category:"shape"}},{name:"generate_proposals_v2",schema:{category:"shape"}},{name:"meshgrid",schema:{category:"shape"}},{name:"mine_hard_examples",schema:{category:"shape"}},{name:"yolo_box",schema:{category:"shape"}},{name:"warpctc",schema:{category:"shape"}},{name:"warpctc_grad",schema:{category:"shape"}},{name:"iou_similarity",schema:{category:"shape"}},{name:"split",schema:{category:"shape"}},{name:"flatten2",schema:{category:"shape"}},{name:"flatten2_grad",schema:{category:"shape"}},{name:"masked_select_grad",schema:{category:"shape"}},{name:"strided_slice",schema:{category:"shape"}},{name:"prior_box",schema:{category:"shape"}},{name:"elementwise_max_grad",schema:{category:"shape"}},{name:"not_equal",schema:{category:"shape"}},{name:"strided_slice_grad",schema:{category:"shape"}},{name:"fill_any_like",schema:{category:"shape"}},{name:"hard_swish",schema:{category:"shape"}},{name:"hard_swish_grad",schema:{category:"shape"}},{name:"expand_v2",schema:{category:"shape"}},{name:"expand_v2_grad",schema:{category:"shape"}},{name:"flatten_contiguous_range_grad",schema:{category:"shape"}},{name:"gather_nd",schema:{category:"shape"}},{name:"gather_nd_grad",schema:{category:"shape"}},{name:"reciprocal",schema:{category:"shape"}},{name:"reciprocal_grad",schema:{category:"shape"}},{name:"index_select",schema:{category:"shape"}},{name:"roi_align",schema:{category:"shape"}},{name:"roi_align_grad",schema:{category:"shape"}},{name:"reduce_mean_grad",schema:{category:"shape"}},{name:"masked_select",schema:{category:"shape"}},{name:"index_select_grad",schema:{category:"shape"}},{name:"elementwise_min_grad",schema:{category:"shape"}},{name:"fill_constant_batch_size_like",schema:{category:"shape"}},{name:"unsqueeze2_grad",schema:{category:"shape"}},{name:"unique",schema:{category:"shape"}},{name:"expand_as_v2",schema:{category:"shape"}},{name:"tile",schema:{category:"shape"}},{name:"nearest_interp_grad",schema:{category:"shape"}}],non_leaf_nodes:[{name:"Layer",schema:{category:"container"}},{name:"LayerList",schema:{category:"container"}},{name:"ParameterList",schema:{category:"container"}},{name:"LayerDict",schema:{category:"container"}},{name:"Conv1D",schema:{category:"conv"}},{name:"Conv1DTranspose",schema:{category:"conv"}},{name:"Conv2D",schema:{category:"conv"}},{name:"Conv2DTranspose",schema:{category:"conv"}},{name:"Conv3D",schema:{category:"conv"}},{name:"Conv3DTranspose",schema:{category:"conv"}},{name:"AdaptiveAvgPool1D",schema:{category:"pool"}},{name:"AdaptiveAvgPool2D",schema:{category:"pool"}},{name:"AdaptiveAvgPool3D",schema:{category:"pool"}},{name:"AdaptiveMaxPool1D",schema:{category:"pool"}},{name:"AdaptiveMaxPool2D",schema:{category:"pool"}},{name:"AdaptiveMaxPool3D",schema:{category:"pool"}},{name:"AvgPool1D",schema:{category:"pool"}},{name:"AvgPool2D",schema:{category:"pool"}},{name:"AvgPool3D",schema:{category:"pool"}},{name:"MaxPool1D",schema:{category:"pool"}},{name:"MaxPool2D",schema:{category:"pool"}},{name:"MaxPool3D",schema:{category:"pool"}},{name:"MaxUnPool1D",schema:{category:"pool"}},{name:"MaxUnPool2D",schema:{category:"pool"}},{name:"MaxUnPool3D",schema:{category:"pool"}},{name:"Pad1D",schema:{category:"pad"}},{name:"Pad2D",schema:{category:"pad"}},{name:"Pad3D",schema:{category:"pad"}},{name:"ZeroPad2D",schema:{category:"pad"}},{name:"CELU",schema:{category:"activation"}},{name:"ELU",schema:{category:"activation"}},{name:"GELU",schema:{category:"activation"}},{name:"Hardshrink",schema:{category:"activation"}},{name:"Hardsigmoid",schema:{category:"activation"}},{name:"Hardswish",schema:{category:"activation"}},{name:"Hardtanh",schema:{category:"activation"}},{name:"LeakyReLU",schema:{category:"activation"}},{name:"LogSigmoid",schema:{category:"activation"}},{name:"LogSoftmax",schema:{category:"activation"}},{name:"Maxout",schema:{category:"activation"}},{name:"PReLU",schema:{category:"activation"}},{name:"ReLU",schema:{category:"activation"}},{name:"ReLU6",schema:{category:"activation"}},{name:"SELU",schema:{category:"activation"}},{name:"Sigmoid",schema:{category:"activation"}},{name:"Silu",schema:{category:"activation"}},{name:"Softmax",schema:{category:"activation"}},{name:"Softplus",schema:{category:"activation"}},{name:"Softshrink",schema:{category:"activation"}},{name:"Softsign",schema:{category:"activation"}},{name:"Swish",schema:{category:"activation"}},{name:"Mish",schema:{category:"activation"}},{name:"Tanh",schema:{category:"activation"}},{name:"Tanhshrink",schema:{category:"activation"}},{name:"ThresholdedReLU",schema:{category:"activation"}},{name:"BatchNorm",schema:{category:"normalization"}},{name:"BatchNorm1D",schema:{category:"normalization"}},{name:"BatchNorm2D",schema:{category:"normalization"}},{name:"BatchNorm3D",schema:{category:"normalization"}},{name:"GroupNorm",schema:{category:"normalization"}},{name:"InstanceNorm1D",schema:{category:"normalization"}},{name:"InstanceNorm2D",schema:{category:"normalization"}},{name:"InstanceNorm3D",schema:{category:"normalization"}},{name:"LayerNorm",schema:{category:"normalization"}},{name:"LocalResponseNorm",schema:{category:"normalization"}},{name:"SpectralNorm",schema:{category:"normalization"}},{name:"SyncBatchNorm",schema:{category:"normalization"}},{name:"AlphaDropout",schema:{category:"normalization"}},{name:"Dropout",schema:{category:"normalization"}},{name:"Dropout2D",schema:{category:"normalization"}},{name:"Dropout3D",schema:{category:"normalization"}},{name:"BiRNN",schema:{category:"sequence"}},{name:"GRU",schema:{category:"sequence"}},{name:"GRUCell",schema:{category:"sequence"}},{name:"LSTM",schema:{category:"sequence"}},{name:"LSTMCell",schema:{category:"sequence"}},{name:"RNN",schema:{category:"sequence"}},{name:"RNNCellBase",schema:{category:"sequence"}},{name:"SimpleRNN",schema:{category:"sequence"}},{name:"SimpleRNNCell",schema:{category:"sequence"}},{name:"MultiHeadAttention",schema:{category:"sequence"}},{name:"Transformer",schema:{category:"sequence"}},{name:"TransformerDecoder",schema:{category:"sequence"}},{name:"TransformerDecoderLayer",schema:{category:"sequence"}},{name:"TransformerEncoder",schema:{category:"sequence"}},{name:"TransformerEncoderLayer",schema:{category:"sequence"}},{name:"Linear",schema:{category:"sequence"}},{name:"Embedding",schema:{category:"sequence"}},{name:"BCELoss",schema:{category:"tensor"}},{name:"BCEWithLogitsLoss",schema:{category:"tensor"}},{name:"CrossEntropyLoss",schema:{category:"tensor"}},{name:"CTCLoss",schema:{category:"tensor"}},{name:"HSigmoidLoss",schema:{category:"tensor"}},{name:"KLDivLoss",schema:{category:"tensor"}},{name:"L1Loss",schema:{category:"tensor"}},{name:"MarginRankingLoss",schema:{category:"tensor"}},{name:"MSELoss",schema:{category:"tensor"}},{name:"NLLLoss",schema:{category:"tensor"}},{name:"SmoothL1Loss",schema:{category:"tensor"}},{name:"PixelShuffle",schema:{category:"shape"}},{name:"Upsample",schema:{category:"shape"}},{name:"UpsamplingBilinear2D",schema:{category:"shape"}},{name:"UpsamplingNearest2D",schema:{category:"shape"}},{name:"ClipGradByGlobalNorm",schema:{category:"shape"}},{name:"ClipGradByNorm",schema:{category:"shape"}},{name:"ClipGradByValue",schema:{category:"shape"}},{name:"BeamSearchDecoder",schema:{category:"shape"}},{name:"CosineSimilarity",schema:{category:"shape"}},{name:"dynamic_decode",schema:{category:"shape"}},{name:"Flatten",schema:{category:"shape"}},{name:"PairwiseDistance",schema:{category:"shape"}},{name:"Identity",schema:{category:"shape"}},{name:"Unfold",schema:{category:"shape"}},{name:"Fold",schema:{category:"shape"}}]}},74872:(e,t,s)=>{const n={},i={Long:s(27808)},o=s(13917);n.NodeSidebar=class{constructor(e,t){this._host=e,this._node=t,this._properties=[],this._attributes=[],this._inputs=[],this._outputs=[],t.type&&this._addProperty("type",new n.ValueTextView(this._host,t.type,{documentation:!!t.metadata})),t.name&&this._addProperty("name",new n.ValueTextView(this._host,t.name)),t.location&&this._addProperty("location",new n.ValueTextView(this._host,t.location)),t.domain&&this._addProperty("domain",new n.ValueTextView(this._host,t.domain)),t.description&&this._addProperty("description",new n.ValueTextView(this._host,t.description)),t.device&&this._addProperty("device",new n.ValueTextView(this._host,t.device));const s=t.attributes;if(s&&s.length>0){const e=t.attributes.slice();e.sort(((e,t)=>{const s=e.name.toUpperCase(),n=t.name.toUpperCase();return sn?1:0}));for(const t of e)this._addAttribute(t.name,t)}const i=t.inputs;if(i&&i.length>0)for(const e of i)this._addInput(e.name,e);const o=t.outputs;if(o&&o.length>0)for(const e of o)this._addOutput(e.name,e)}render(){return{properties:this._properties,groups:[{name:"attributes",properties:this._attributes},{name:"inputs",properties:this._inputs},{name:"outputs",properties:this._outputs}]}}_addProperty(e,t){const s=new n.NameValueView(this._host,e,t);this._properties.push(s.render())}_addAttribute(e,t){const s=new n.NameValueView(this._host,e,new r(this._host,t));this._attributes.push(s.render())}_addInput(e,t){if(t.arguments.length>0){const s=new n.ParameterView(this._host,t),i=new n.NameValueView(this._host,e,s);this._inputs.push(i.render())}}_addOutput(e,t){if(t.arguments.length>0){const s=new n.ParameterView(this._host,t),i=new n.NameValueView(this._host,e,s);this._outputs.push(i.render())}}static formatAttributeValue(e,t,s){if("function"==typeof e)return e();if(e&&i.Long.isLong(e))return e.toString();if(Number.isNaN(e))return"NaN";switch(t){case"shape":return e.toString();case"shape[]":return e?e.map((e=>e.toString())).join(", "):"(null)";case"graph":return e.toString();case"graph[]":return e?e.map((e=>e.toString())).join(", "):"(null)";case"tensor":return e&&e.type&&e.type.shape&&e.type.shape.dimensions&&0==e.type.shape.dimensions.length?e.toString():"[...]"}if("string"==typeof e&&(!t||"string"!=t))return s?'"'+e+'"':e;if(Array.isArray(e)){if(0==e.length)return s?"[]":"";let t=!1;e.length>1e3&&(e=e.slice(0,1e3),t=!0);const o=e.map((e=>e&&i.Long.isLong(e)?e.toString():Number.isNaN(e)?"NaN":n.NodeSidebar.formatAttributeValue(e,null,!0)));return t&&o.push("…"),s?["[",o.join(", "),"]"].join(" "):o.join(", ")}if(null===e)return s?"null":"";if(void 0===e)return"undefined";if(e!==Object(e))return e.toString();const o=[],r=Object.keys(e).filter((e=>!e.startsWith("__")&&!e.endsWith("__")));if(1==r.length)o.push(n.NodeSidebar.formatAttributeValue(e[Object.keys(e)[0]],null,!0));else for(const t of r)o.push(t+": "+n.NodeSidebar.formatAttributeValue(e[t],null,!0));let a=e.__type__;if(!a&&e.constructor.name&&"Object"!==e.constructor.name&&(a=e.constructor.name),a)return a+(0==o.length?"()":["(",o.join(", "),")"].join(""));switch(o.length){case 0:return s?"()":"";case 1:return o[0];default:return s?["(",o.join(", "),")"].join(" "):o.join(", ")}}},n.NameValueView=class{constructor(e,t,s){this._host=e,this._name=t,this._value=s,this._element={name:t,values:s.render()}}get name(){return this._name}render(){return this._element}},n.ValueTextView=class{constructor(e,t,s){this._host=e,this._elements=[],this._elements.push(Object.assign({value:t},s))}render(){return this._elements}};class r{constructor(e,t){this._host=e,this._attribute=t,this._element={},t.type&&(this._element.children=this.renderChildren());let s=n.NodeSidebar.formatAttributeValue(this._attribute.value,this._attribute.type);s&&s.length>1e3&&(s=s.substring(0,1e3)+"…"),this._element.value=s||" "}render(){return[this._element]}renderChildren(){const e=[];this._host.document.createElement("div").className="sidebar-view-item-value-line-border";const t=this._attribute.type,s=this._attribute.value;"tensor"==t&&s&&s.type?e.push({name:"type",value:s.type.toString(),type:"code"}):e.push({name:"type",value:this._attribute.type,type:"code"});const n=this._attribute.description;if(n&&e.push({value:n}),"tensor"==this._attribute.type&&s){const t=s.state;e.push({value:t||s.toString(),type:"raw"})}return e}}n.ParameterView=class{constructor(e,t){this._list=t,this._elements=[],this._items=[];for(const s of t.arguments){const t=new n.ArgumentView(e,s);this._items.push(t),this._elements.push(t.render())}}render(){return this._elements}},n.ArgumentView=class{constructor(e,t){this._host=e,this._argument=t,this._element={};const s=t.initializer,n=t.quantization;(t.type||s||n)&&(this._element.children=this.renderChildren());let i=this._argument.name||"";if(this._hasId=!!i,s&&!this._hasId)this._element.name="kind",this._element.value=s.kind;else{if("string"!=typeof i)throw new Error("Invalid argument identifier '"+JSON.stringify(i)+"'.");i=i.split("\n").shift(),this._element.name="name",this._element.value=i||" "}}render(){return this._element}renderChildren(){const e=[];let t="?",s=null;this._argument.type&&(t=this._argument.type.toString(),s=this._argument.type.denotation||null),t&&e.push({name:"type",value:t,type:"code"}),s&&e.push({name:"denotation",value:s,type:"code"});const n=this._argument.description;n&&e.push({name:"description",value:n});const i=this._argument.quantization;i&&e.push({name:"quantization",value:i}),this._argument.location&&e.push({name:"location",value:this._argument.location});const o=this._argument.initializer;if(o){o.reference&&e.push({name:"reference",value:this._argument.reference});const t=o.state;let s="";try{s=t||o.toString()}catch(e){s=e.toString(),this._host.exception(e,!1)}e.push({value:s,type:"raw"})}return e}},n.ModelSidebar=class{constructor(e,t,s){this._host=e,this._model=t,this._properties=[],this._groups=[],this._model.format&&this._addProperty("format",new n.ValueTextView(this._host,this._model.format)),this._model.producer&&this._addProperty("producer",new n.ValueTextView(this._host,this._model.producer)),this._model.source&&this._addProperty("source",new n.ValueTextView(this._host,this._model.source)),this._model.name&&this._addProperty("name",new n.ValueTextView(this._host,this._model.name)),this._model.version&&this._addProperty("version",new n.ValueTextView(this._host,this._model.version)),this._model.description&&this._addProperty("description",new n.ValueTextView(this._host,this._model.description)),this._model.author&&this._addProperty("author",new n.ValueTextView(this._host,this._model.author)),this._model.company&&this._addProperty("company",new n.ValueTextView(this._host,this._model.company)),this._model.license&&this._addProperty("license",new n.ValueTextView(this._host,this._model.license)),this._model.domain&&this._addProperty("domain",new n.ValueTextView(this._host,this._model.domain)),this._model.imports&&this._addProperty("imports",new n.ValueTextView(this._host,this._model.imports)),this._model.runtime&&this._addProperty("runtime",new n.ValueTextView(this._host,this._model.runtime));const i=this._model.metadata;if(i)for(const e of i)this._addProperty(e.name,new n.ValueTextView(this._host,e.value));if(this._model&&this._addProperty("subgraph",new n.ValueTextView(this._host,s.name)),s){if(s.version&&this._addProperty("version",new n.ValueTextView(this._host,s.version)),s.type&&this._addProperty("type",new n.ValueTextView(this._host,s.type)),s.tags&&this._addProperty("tags",new n.ValueTextView(this._host,s.tags)),s.description&&this._addProperty("description",new n.ValueTextView(this._host,s.description)),s.inputs.length)for(const e of s.inputs)this._addGroupProperty("inputs",e.name,e);if(s.outputs.length)for(const e of s.outputs)this._addGroupProperty("outputs",e.name,e)}}render(){return{properties:this._properties,groups:this._groups}}_addGroupProperty(e,t,s){const n=this._groups.find((t=>t.name===e));n?n.properties.push(this._addArgument(t,s)):this._groups.push({name:e,properties:[this._addArgument(t,s)]})}_addProperty(e,t){const s=new n.NameValueView(this._host,e,t);this._properties.push(s.render())}_addArgument(e,t){const s=new n.ParameterView(this._host,t);return new n.NameValueView(this._host,e,s).render()}},n.DocumentationSidebar=class{constructor(e,t){this._host=e,this._metadata=t}render(){return n.DocumentationSidebar.formatDocumentation(this._metadata)}static formatDocumentation(e){if(e){if((e=JSON.parse(JSON.stringify(e))).summary&&(e.summary=o(e.summary)),e.description&&(e.description=o(e.description)),e.attributes)for(const t of e.attributes)t.description&&(t.description=o(t.description));if(e.inputs)for(const t of e.inputs)t.description&&(t.description=o(t.description));if(e.outputs)for(const t of e.outputs)t.description&&(t.description=o(t.description));if(e.references)for(const t of e.references)t&&(t.description=o(t.description));return e}return""}},n.FindSidebar=class{constructor(e,t,s){this._host=e,this._graphElement=t,this._graph=s}static selection(e,t){const s=[],n=e.id,i=t.getElementById("nodes");if(i){let e=i.firstChild;for(;e;)e.id==n&&s.push(e),e=e.nextSibling}const o=t.getElementById("clusters");if(o){let e=o.firstChild;for(;e;)e.id==n&&s.push(e),e=e.nextSibling}const r=t.getElementById("edge-paths");if(r){let e=r.firstChild;for(;e;)e.id===n&&s.push(e),e=e.nextSibling}let a=t.getElementById(n);if(a)for(;a.parentElement;)if(a=a.parentElement,a.id&&a.id.startsWith("node-")){s.push(a);break}return s.length>0?s:null}static selection2(e,t){const s=[],n=e.id,i=t.getElementById("nodes");if(i){let e=i.firstChild;for(;e;)e.id==n&&s.push(e),e=e.nextSibling}const o=t.getElementById("clusters");if(o){let e=o.firstChild;for(;e;)e.id==n&&s.push(e),e=e.nextSibling}const r=t.getElementById("edge-paths");if(r){let t=r.firstChild;for(;t;)t.id===n&&(e.fromnode&&t.getAttribute("fromnode")===e.fromnode&&s.push(t),e.tonode&&t.getAttribute("tonode")===e.tonode&&s.push(t)),t=t.nextSibling}let a=t.getElementById(n);if(a)for(;a.parentElement;)if(a=a.parentElement,a.id&&a.id.startsWith("node-")){s.push(a);break}return s.length>0?s:null}update(e){const t=e.toLowerCase(),s=new Set,n=new Set,i=[];for(const e of this._graph.nodes){const o=[];for(const s of e.inputs)for(const e of s.arguments)e.name&&-1!=e.name.toLowerCase().indexOf(t)&&!n.has(e.name)&&(e.initializer||(i.push({type:"input",name:e.name.split("\n").shift(),id:"edge-"+e.name}),n.add(e.name)));const r=e.name;console.log("name",e);const a=e.type;!s.has(r)&&r&&(-1!=r.toLowerCase().indexOf(t)||a&&-1!=a.toLowerCase().indexOf(t))&&(i.push({type:"node",name:r,id:"node-"+r}),s.add(r));for(const e of o)i.push({type:"initializer",name:e.name,id:"initializer-"+e.name})}for(const e of this._graph.nodes)for(const s of e.outputs)for(const e of s.arguments)e.name&&-1!=e.name.toLowerCase().indexOf(t)&&!n.has(e.name)&&(i.push({type:"output",name:e.name.split("\n").shift(),id:"edge-"+e.name}),n.add(e.name));return{text:e,result:i}}},"object"==typeof e.exports&&(e.exports.Sidebar=n.Sidebar,e.exports.ModelSidebar=n.ModelSidebar,e.exports.NodeSidebar=n.NodeSidebar,e.exports.DocumentationSidebar=n.DocumentationSidebar,e.exports.FindSidebar=n.FindSidebar)},74913:(e,t,s)=>{var n=n||{},i=i||s(46506);n.Renderer=class{constructor(e,t,s){this._document=e.document,this._svgElement=t,this._host=e,this._view=s}render(e){let t=null,s=null,o=null,r=null;t=this.createElement("g"),t.setAttribute("id","clusters"),t.setAttribute("class","clusters"),this._svgElement.appendChild(t),s=this.createElement("g"),s.setAttribute("id","edge-paths"),s.setAttribute("class","edge-paths"),this._svgElement.appendChild(s),o=this.createElement("g"),o.setAttribute("id","edge-labels"),o.setAttribute("class","edge-labels"),this._svgElement.appendChild(o),r=this.createElement("g"),r.setAttribute("id","nodes"),r.setAttribute("class","nodes"),this._svgElement.appendChild(r);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);if(this._view._nodes.hasOwnProperty(s.id)){r.appendChild(this._view._nodes[s.id]);const e=this._view._nodes[s.id].getBBox();s.width=e.width,s.height=e.height,s.element=this._view._nodes[s.id]}else{const e=this.createElement("g");s.id&&e.setAttribute("id",s.id),e.setAttribute("class",Object.prototype.hasOwnProperty.call(s,"class")?"node "+s.class:"node"),e.style.opacity=0;const t=this.createElement("g");t.appendChild(s.label),e.appendChild(t),r.appendChild(e);const n=s.label.getBBox(),i=-n.width/2,o=-n.height/2;t.setAttribute("transform","translate("+i+","+o+")"),s.width=n.width,s.height=n.height,s.element=e}}for(const t of e.edges()){const s=e.edge(t);if(s.label){const e=this.createElement("tspan");e.setAttribute("xml:space","preserve"),e.setAttribute("dy","1em"),e.setAttribute("x","1"),e.appendChild(this._document.createTextNode(s.label));const t=this.createElement("text");t.appendChild(e);const n=this.createElement("g");n.appendChild(t);const i=this.createElement("g");i.style.opacity=0,i.setAttribute("class","edge-label"),i.appendChild(n),o.appendChild(i);const r=n.getBBox(),a=-r.width/2,h=-r.height/2;n.setAttribute("transform","translate("+a+","+h+")"),s.width=r.width,s.height=r.height,s.labelElement=i}}i.layout(e);for(const t of e.nodes())if(0==e.children(t).length){const s=e.node(t);s.element.setAttribute("transform","translate("+s.x+","+s.y+")"),s.element.style.opacity=1,delete s.element}for(const t of e.edges()){const s=e.edge(t);s.labelElement&&(s.labelElement.setAttribute("transform","translate("+s.x+","+s.y+")"),s.labelElement.style.opacity=1,delete s.labelElement)}const a=this.createElement("defs");s.appendChild(a);const h=this.createElement("marker");h.setAttribute("id","arrowhead-vee"),h.setAttribute("viewBox","0 0 10 10"),h.setAttribute("refX",9),h.setAttribute("refY",5),h.setAttribute("markerUnits","strokeWidth"),h.setAttribute("markerWidth",8),h.setAttribute("markerHeight",6),h.setAttribute("orient","auto"),a.appendChild(h);const c=this.createElement("path");c.setAttribute("d","M 0 0 L 10 5 L 0 10 L 4 5 z"),c.style.setProperty("stroke-width",1),c.style.setProperty("stroke-dasharray","1,0"),h.appendChild(c);for(const t of e.edges()){const i=e.edge(t),o=n.Renderer._computeCurvePath(i,e.node(t.v),e.node(t.w)),r=this.createElement("path");r.setAttribute("class",Object.prototype.hasOwnProperty.call(i,"class")?"edge-path "+i.class:"edge-path"),r.setAttribute("d",o),r.setAttribute("marker-end","url(#arrowhead-vee)"),i.id&&r.setAttribute("id",i.id),i.fromnode&&r.setAttribute("fromnode",i.fromnode),i.tonode&&r.setAttribute("tonode",i.tonode),s.appendChild(r)}const l=[];for(const t of e.nodes())Number(t)||0===Number(t)||l.push(t);const m=l.sort(((e,t)=>e.split("/").length-t.split("/").length));for(const s of m)if(e.children(s).length>0){const i=e.node(s);if(this._view._clusters.hasOwnProperty(i.id)){const e=this._view._clusters.hasOwnProperty(i.id);e.setAttribute("transform","translate("+i.x+","+i.y+")"),e.firstChild.setAttribute("x",-i.width/2),e.firstChild.setAttribute("y",-i.height/2),e.firstChild.setAttribute("width",i.width+10),e.firstChild.setAttribute("height",i.height+10)}else{const e=this.createElement("g");e.setAttribute("class","cluster"),e.setAttribute("id",`node-${s}`),e.setAttribute("transform","translate("+i.x+","+i.y+")");const o=this.createElement("rect"),r=this.createElement("tspan"),a=this.createElement("circle"),h=this.createElement("tspan");a.setAttribute("r","6.5"),a.setAttribute("cx",i.width/2-20+7.5+10),a.setAttribute("cy",-i.height/2+5+7.5),h.setAttribute("x",i.width/2-15+9),h.setAttribute("y",-i.height/2+1.3),h.setAttribute("xml:space","preserve"),h.setAttribute("dy","1em"),h.setAttribute("font-size","16px"),h.setAttribute("class","button-text"),a.setAttribute("class","clusterButton"),r.setAttribute("xml:space","preserve"),r.setAttribute("dy","1em"),r.setAttribute("x",0),r.setAttribute("y",-i.height/2+5),r.setAttribute("text-anchor","middle");let c="";for(const e of this._host._view._allGraph.nodes)e.name===i.nodeId&&(c=e.show_name.split("/")[e.show_name.split("/").length-1]);r.appendChild(this._document.createTextNode(c)),h.appendChild(this._document.createTextNode("-"));const l=this.createElement("text");l.appendChild(r);const m=this.createElement("text");m.appendChild(h),o.setAttribute("class",i.classList.join(" ")),o.setAttribute("x",-i.width/2),o.setAttribute("y",-i.height/2),o.setAttribute("width",i.width+10),o.setAttribute("height",i.height+10);const d=this.createElement("path");d.setAttribute("class",["cluster","border"].join(" ")),d.setAttribute("d",n.NodeElement.roundedRect(-i.width/2,-i.height/2,i.width+10,i.height+10,!0,!0,!0,!0)),e.addEventListener("click",(()=>{this._view.select({id:`node-${s}`,name:s,type:"node"})})),m.addEventListener("click",(()=>{this._host.selectNodeId({nodeId:i.nodeId,expand:i.expand,isKeepData:i.isKeepData}),this._host.selectItems({id:`node-${i.nodeId}`,name:i.nodeId,type:"node"})})),o.addEventListener("click",(()=>{if(this._view.isCtrl){for(const e of this._view._allGraph.nodes)if(e.name===i.nodeId){for(const t of this._view.non_graphMetadatas)t.name===e.type&&("zh"===this._view.Language?window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`):window.open(`https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/${t.name}_en.html`));return void this._view.showNodeProperties(e)}}else for(const e of this._view._allGraph.nodes)if(e.name===i.nodeId)return void this._view.showNodeProperties(e)})),i.rx&&o.setAttribute("rx",i.rx),i.ry&&o.setAttribute("ry",i.ry),e.appendChild(o),e.appendChild(l),e.appendChild(a),e.appendChild(m),e.appendChild(d),t.appendChild(e)}}}createElement(e){return this._document.createElementNS("http://www.w3.org/2000/svg",e)}static _computeCurvePath(e,t,s){const i=e.points.slice(1,e.points.length-1);i.unshift(n.Renderer.intersectRect(t,i[0])),i.push(n.Renderer.intersectRect(s,i[i.length-1]));const a=new o,h=new r(a);for(let e=0;eMath.abs(i)*c?(o<0&&(c=-c),r=0===o?0:c*i/o,a=c):(i<0&&(h=-h),r=h,a=0===i?0:h*o/i),{x:s+r,y:n+a}}},n.NodeElement=class{constructor(e){this._document=e,this._blocks=[]}block(e){switch(this._block=null,e){case"header":this._block=new n.NodeElement.Header(this._document);break;case"list":this._block=new n.NodeElement.List(this._document)}return this._blocks.push(this._block),this._block}format(e){const t=this.createElement("g");e.appendChild(t);let s=0,i=0;const o=[];for(const e of this._blocks)o.push(i),e.layout(t),sthis._width&&(this._width=t)}}get width(){return this._width}get height(){return this._height}update(e,t,s,i,o){const r=s-this._width;let a,h,c;for(a=0;a{const n=s(71681),i=s(63332),o=s(499),r=s(81600),a=s(71462),h=s(46506),c=s(74913),l=s(74872),m={},d=s(42473),{style:p}=s(71462);m.View=class{constructor(e){this._host=e,this._host.initialize(this).then((()=>{this.typeLayer={},this.Language="zh",this.graphMetadatas=[],this.non_graphMetadatas=[],this.isCtrl=!1,this._clusters={},this._nodeName={},this._nodes={},this._model=null,this._selection=[],this._selectItem=null,this._host.start(),this._showAttributes=!1,this._showInitializers=!0,this._showNames=!1,this._KeepData=!1,this._showHorizontal=!1,this._modelFactoryService=new m.ModelFactoryService(this._host),this._graphNodes={}})).catch((e=>{this.error(e.message,e)}))}cut(){this._host.document.execCommand("cut")}copy(){this._host.document.execCommand("copy")}paste(){this._host.document.execCommand("paste")}selectAll(){this._host.document.execCommand("selectall")}find(e){if(this._activeGraph){this.clearSelection();const t=document.getElementById("canvas");if(this._allGraph){const s=new l.FindSidebar(this._host,t,this._allGraph);this._host.message("search",s.update(e))}else{const s=new l.FindSidebar(this._host,t,this._activeGraph);this._host.message("search",s.update(e))}}}toggleAttributes(e){(null==e||e^this._showAttributes)&&(this._showAttributes=null==e?!this._showAttributes:e,this._nodes={},this._clusters={},this._reload())}get showAttributes(){return this._showAttributes}toggleInitializers(e){(null==e||e^this._showInitializers)&&(this._showInitializers=null==e?!this._showInitializers:e,this._nodes={},this._clusters={},this._reload())}get showInitializers(){return this._showInitializers}toggleNames(e){(null==e||e^this._showNames)&&(this._showNames=null==e?!this._showNames:e,this._nodes={},this._clusters={},this._reload())}toggleKeepData(e){(null==e||e^this._KeepData)&&(this._KeepData=null==e?!this._KeepData:e)}toggleLanguage(e){this.Language=e}get showNames(){return this._showNames}get KeepData(){return this._KeepData}toggleDirection(e){(null==e||e^this._showHorizontal)&&(this._showHorizontal=null==e?!this._showHorizontal:e,this._reload())}get showHorizontal(){return this._showHorizontal}toggleTheme(e){this._host.document.body.className=e}_reload(){this._host.status("loading"),this._model&&this._activeGraph&&this._updateGraph2(this._model,this._activeGraph).catch((e=>{e&&this.error("Graph update failed.",e)}))}_timeout(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}zoomIn(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),1.2)}zoomOut(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),.8)}selectItem(e){this._selectItem=e}resetZoom(){this._zoom&&this._zoom.scaleTo(a.select(this._host.document.getElementById("canvas")),1)}select(e){if(this.clearSelection(),"node"===e.type)for(const t of this._allGraph.nodes)if(t.name===e.name){this.showNodeProperties(t);break}const t=document.getElementById("canvas"),s=l.FindSidebar.selection(e,t);if(s&&s.length>0){const e=this._host.document.getElementById("canvas"),t=e.getBoundingClientRect();let n=0,i=0;for(const e of s){e.classList.add("select"),this._selection.push(e);const t=e.transform.baseVal.consolidate(),s=e.getBBox(),o=t?t.matrix.e:s.x+s.width/2,r=t?t.matrix.f:s.y+s.height/2;n+=o,i+=r}n/=s.length,i/=s.length,this._zoom.transform(a.select(e),a.zoomIdentity.translate(t.width/2-n,t.height/2-i))}}select2(e){const t=document.getElementById("canvas"),s=l.FindSidebar.selection2(e,t);if(s&&s.length>0)for(const e of s)this._selection.push(e),e.classList.add("select")}clearSelection(){for(;this._selection.length>0;)this._selection.pop().classList.remove("select")}error(e,t){this._host.error(e,t.toString())}accept(e){return this._modelFactoryService.accept(e)}open(e){return this._timeout(2).then((()=>this._modelFactoryService.open(e).then((e=>this._timeout(20).then((()=>{console.log("model.graphs.length",e.graphs.length);const t=e.graphs.length>0?e.graphs[0]:null;return this._host.message("opened",{graphs:e.graphs.map((e=>e.name||"")),selected:t&&(t.name||"")}),this._updateGraph2(t)}))))))}changeAlt(e){this.isCtrl=e,console.log("isCtrl",this.isCtrl)}keydown(){this._host.document.onkeydown=e=>{"MetaLeft"!==e.code&&"MetaRight"!==e.code&&"ControlLeft"!==e.code&&"AltLeft"!==e.code&&"AltRight"!==e.code||(this.isCtrl=!0)},this._host.document.onkeyup=e=>{"MetaLeft"!==e.code&&"MetaRight"!==e.code&&"ControlLeft"!==e.code&&"AltLeft"!==e.code&&"AltRight"!==e.code||(this.isCtrl=!1)}}changeGraph(e){this._updateActiveGraph(e)}changeAllGrap(e){this._allGraph=e;for(const t of e.nodes)this._nodeName[t.name]=t}changeSelect(e){this._selectItem=e}_updateActiveGraph(e){e&&(this._host.status("loading"),this._timeout(200).then((()=>this._updateGraph(e).catch((e=>{e&&this.error("Graph update failed.",e)})))))}_updateGraph(e){return this._timeout(100).then((()=>e&&e!=this._activeGraph&&e.nodes.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?")?null:this.renderGraph(e,e).then((()=>(this._model=e,this._activeGraph=e,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{this._host.status("rendered")})).finally((()=>{throw e}))))))}_updateGraph2(e){return this._timeout(100).then((()=>{if(e&&e!=this._activeGraph){this._selectItem=null;const t=e.nodes;if(console.log("graphs",e),console.log("nodes.length",t),t.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?"))return null}return this.renderGraph(e,e).then((()=>(this._model=e,this._activeGraph=e,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{this._host.status("rendered")})).finally((()=>{throw e}))))}))}jumpRoute(e){if(console.log("node",e),e.is_leaf){if(console.log("isCtrl",this.isCtrl),this.isCtrl)for(const t of this._allGraph.nodes)if(t.name===e.name)for(const t of this.non_graphMetadatas)console.log("type",t.name.toLowerCase(),e.type),t.name.toLowerCase()===e.type&&("zh"===this.Language?window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`):window.open(`https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/${t.name}_en.html`))}else if(this.isCtrl)for(const t of this._allGraph.nodes)if(t.name===e.name)for(const t of this.non_graphMetadatas)t.name===e.type&&window.open(`https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/nn/${t.name}_cn.html`)}renderGraph(e,t){try{this.keydown(),this.graphMetadatas=d.default.leaf_nodes,this.non_graphMetadatas=d.default.non_leaf_nodes;const s={};for(const e of d.default.non_leaf_nodes)s[e.name]=!0;this.typeLayer=s;const n=this._host.document.getElementById("canvas");for(;n.lastChild;)n.removeChild(n.lastChild);if(t){this._zoom=null,n.style.position="absolute",n.style.margin="0";const s=!0,i={nodesep:65,ranksep:60};this._showHorizontal&&(i.rankdir="LR");const o=new h.graphlib.Graph({compound:s});o.setGraph(i),o.setDefaultEdgeLabel((()=>({})));let r=0;const m={},p={},g={};let _=(new Date).getTime(),f=t.nodes;if(f.length>1500&&(i.ranker="longest-path"),s)for(const e of f){let t=e.name.split("/");for(t.pop(),console.log("path.length",t.length);t.length>0;){const e=t.join("/");t.pop(),e&&(g[e]=t.join("/"))}}for(const t of f){let i=null;document.getElementById(`node-${t.name}`)||(i=new c.NodeElement(this._host.document));const a=(t,s,n)=>{if(!document.getElementById(`node-${s.name}`)){const n=t.block("header"),i=["node-item-type"],o=s.type;if(s.is_leaf)for(const e of this.graphMetadatas)s.type===e.name&&e.schema.category&&i.push("node-item-type-"+e.schema.category.toLowerCase());else for(const e of this.non_graphMetadatas)s.type===e.name&&e.schema.category&&i.push("node-item-type-"+e.schema.category.toLowerCase());if("string"!=typeof o||!o.split)throw new u("Unknown node type '"+JSON.stringify(o)+"' in '"+e.format+"'.");const r=s.name.split("/")[s.name.split("/").length-1],a=this.showNames&&s.name?r:o.split(".").pop(),h=this.showNames&&s.name?o:r;n.add(null,i,a,h,(()=>{this.jumpRoute(s),this.showNodeProperties(s),this.select({id:`node-${s.name}`,name:s.name,type:"node"});const e=s.inputs;for(const t of e)for(const e of t.arguments)""==e.name||e.initializer||this.select2({id:`edge-${e.name}`,name:e.name,type:"input",tonode:s.name});let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)""!=t.name&&this.select2({id:`edge-${t.name}`,name:t.name,type:"input",fromnode:s.name})}));const c=["node-item-buttons"];s.is_leaf||n.add(null,c,"+",null,(()=>{this._host.selectNodeId({nodeId:s.name,expand:!0}),this._host.selectItems({id:`node-${s.name}`,name:s.name,type:"node"})}));const m=[];let d=!1;if(this._showInitializers)for(const e of s.inputs)e.visible&&1==e.arguments.length&&null!=e.arguments[0].initializer&&m.push(e),(!e.visible||e.arguments.length>1)&&e.arguments.some((e=>null!=e.initializer))&&(d=!0);let p=[];const g=s.attributes;if(this.showAttributes&&g&&(p=g.filter((e=>e.visible)).slice(),p.sort(((e,t)=>{const s=e.name.toUpperCase(),n=t.name.toUpperCase();return sn?1:0}))),m.length>0||d||p.length>0){const e=t.block("list");e.handler=()=>{this.jumpRoute(s),this.showNodeProperties(s),this.select({id:`node-${s.name}`,name:s.name,type:"node"});const e=s.inputs;for(const t of e)for(const e of t.arguments)""==e.name||e.initializer||this.select2({id:`edge-${e.name}`,name:e.name,type:"input",tonode:s.name});let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)""!=t.name&&this.select2({id:`edge-${t.name}`,name:t.name,type:"input",fromnode:s.name})};for(const t of m){const s=t.arguments[0],n=s.type;let i="",o="";n&&n.shape&&n.shape.dimensions&&Object.prototype.hasOwnProperty.call(n.shape.dimensions,"length")&&(i="〈"+n.shape.dimensions.map((e=>e||"?")).join("×")+"〉",0==n.shape.dimensions.length&&s.initializer&&!s.initializer.state&&(i=s.initializer.toString(),i&&i.length>10&&(i=i.substring(0,10)+"…"),o=" = ")),e.add("initializer-"+s.name,t.name,i,n?n.toString():"",o)}d&&e.add(null,"〈…〉","",null,"");for(const t of p)if(t.visible){let s=l.NodeSidebar.formatAttributeValue(t.value,t.type);s&&s.length>25&&(s=s.substring(0,25)+"…"),e.add(null,t.name,s,t.type," = ")}}}if(n){const e=s.inputs;for(const t of e)for(const e of t.arguments)if(""!=e.name&&!e.initializer){let n=m[e.name];n||(n={from:null,to:[]},m[e.name]=n),n.to.push({node:r,name:t.name,nodename:s.name})}let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)if(""!=t.name){let n=m[t.name];n||(n={from:null,to:[]},m[t.name]=n),n.from={node:r,name:e.name,type:t.type,nodename:s.name}}}if(s.chain&&s.chain.length>0)for(const e of s.chain)a(t,e,!1);s.inner&&a(t,s.inner,!1)};if(a(i,t,!0),t.controlDependencies&&t.controlDependencies.length>0)for(const e of t.controlDependencies){let s=m[e];s||(s={from:null,to:[]},m[e]=s),s.to.push({node:r,name:e,controlDependency:!0,nodename:t.name})}const h=t.name;document.getElementById(`node-${t.name}`)?o.setNode(r,{label:"node-"+h,id:"node-"+h}):h?o.setNode(r,{label:i.format(n),id:"node-"+h}):(o.setNode(r,{label:i.format(n),id:"node-"+_.toString()}),_++);const f=this._KeepData,y=(e,t)=>{const s=d.default.non_leaf_nodes,n=["clusterGroup"],i=t.show_name.split("/")[t.show_name.split("/").length-1];if(this._nodeName[e])for(const t of s)if(this._nodeName[e].type===t.name){n.push(`clusterGroup-${t.schema.category.toLowerCase()}`);break}let r=["clusterGroup"];if(n.length>1&&(r=["clusterGroup",n[1]]),!p[e]){o.setNode(e,{rx:10,ry:10,nodeId:e,showName:i,expand:!1,classList:r,isKeepData:f}),p[e]=!0;const s=g[e];s&&(y(s,t),o.setParent(e,s))}};if(s){let e=t.name.split("/");e.pop();let s=e.join("/");if(s&&s.length>0){if(!Object.prototype.hasOwnProperty.call(g,s)){const e=s.lastIndexOf("/");-1!=e?(s=s.substring(0,e),Object.prototype.hasOwnProperty.call(g,s)||(s=null)):s=null}s&&(y(s,t),o.setParent(r,s))}}this._graphNodes[t.name]=i,r++}for(const e of t.inputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.from={node:r,type:t.type}}const t=e.arguments.map((e=>e.type||"")).join("\n");let s=e.name||"";s.length>16&&(s=s.split("/").pop());const i=new c.NodeElement(this._host.document);i.block("header").add(null,["graph-item-input"],s,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:i.format(n),class:"graph-input"})}for(const e of t.outputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.to.push({node:r})}const t=e.arguments.map((e=>e.type||"")).join("\n");let s=e.name||"";s.length>16&&(s=s.split("/").pop());const i=new c.NodeElement(this._host.document);i.block("header").add(null,["graph-item-output"],s,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:i.format(n)})}for(const e of Object.keys(m)){const t=m[e];if(null!=t.from)for(const s of t.to){let n="";const i=t.from.type;i&&i.shape&&i.shape.dimensions&&i.shape.dimensions.length>0&&(n=i.shape.dimensions.join("×")),this._showNames&&(n=e.split("\n").shift()),s.controlDependency?o.setEdge(t.from.node,s.node,{label:n,id:"edge-"+e,arrowhead:"vee",class:"edge-path-control-dependency",fromnode:t.from.nodename,tonode:s.nodename}):o.setEdge(t.from.node,s.node,{label:n,id:"edge-"+e,arrowhead:"vee",fromnode:t.from.nodename,tonode:s.nodename})}}const y=this._host.document.createElementNS("http://www.w3.org/2000/svg","rect");y.setAttribute("id","background"),y.setAttribute("width","100%"),y.setAttribute("height","100%"),y.setAttribute("fill","none"),y.setAttribute("pointer-events","all"),n.appendChild(y);const b=this._host.document.createElementNS("http://www.w3.org/2000/svg","g");b.setAttribute("id","origin"),n.appendChild(b);let w=null;return w=a.select(n),y.addEventListener("click",(()=>{this.clearSelection()})),this._zoom=a.zoom(),this._zoom(w),this._zoom.scaleExtent([.01,2]),this._zoom.on("zoom",(()=>{b.setAttribute("transform",a.event.transform.toString())})),this._zoom.transform(w,a.zoomIdentity),this._timeout(200).then((()=>{new c.Renderer(this._host,b,this).render(o),console.log("graphRenderer.render(g)",o);for(const e of document.getElementById("clusters").children)this._clusters[e.getAttribute("id")]=e;for(const e of document.getElementById("nodes").children)this._nodes[e.getAttribute("id")]=e;const e=n.getElementsByClassName("graph-input"),t=n.getBoundingClientRect();if(e&&e.length>0)if(this._selectItem)this.select(this._selectItem);else{const s=[],n=[];for(let t=0;te==n[0]))&&(i=s.reduce(((e,t)=>e+t))/s.length);const r=t.width/(this._showHorizontal?4:2)-i,h=t.height/(this._showHorizontal?2:4)-o;this._zoom.transform(w,a.zoomIdentity.translate(r,h))}else this._selectItem?this.select(this._selectItem):this._zoom.transform(w,a.zoomIdentity.translate((t.width-o.graph().width)/2,(t.height-o.graph().height)/2))}))}return Promise.resolve()}catch(e){return Promise.reject(e)}}applyStyleSheet(e,t){let s=[];for(let e=0;e{const s=Math.max(c,l),n=2*s>24e3?24e3/s:2,i=this._host.document.createElement("canvas");i.width=Math.ceil(c*n),i.height=Math.ceil(l*n);const o=i.getContext("2d");o.scale(n,n),o.drawImage(t,0,0),this._host.document.body.removeChild(t),i.toBlob((t=>{if(t)this._host.export(e,t);else{const e=new Error;e.name="Error exporting image.",e.message="Image may be too large to render as PNG.",this._host.exception(e,!1),this._host.error(e.name,e.message)}}),"image/png")},t.src="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(m))),this._host.document.body.insertBefore(t,this._host.document.body.firstChild)}}}showModelProperties(){if(this._model){const e=new l.ModelSidebar(this._host,this._model,this._activeGraph);this._host.message("show-model-properties",e.render())}}showNodeProperties(e){if(e){const t=new l.NodeSidebar(this._host,e);this._host.message("show-node-properties",{...t.render(),metadata:e.metadata})}}showNodeDocumentation(e){const t=e.metadata;if(t){const e=new l.DocumentationSidebar(this._host,t);this._host.message("show-node-documentation",e.render())}}};class u extends Error{constructor(e,t){super(e),this.name="Error loading model.",this.telemetry=t}}class g{constructor(e){this._context=e,this._tags=new Map,this._entries=new Map}request(e,t){return this._context.request(e,t)}get identifier(){return this._context.identifier}get buffer(){return this._context.buffer}get text(){return this._text||(this._text=new TextDecoder("utf-8").decode(this.buffer)),this._text}entries(e){let t=this._entries.get(e);if(!t){t=[];try{const s=this.buffer;switch(e){case"zip":s&&s.length>2&&80==s[0]&&75==s[1]&&(t=new n.Archive(s).entries);break;case"tar":if(s.length>=512){let e=0;for(let t=0;t<512;t++)e+=t>=148&&t<156?32:s[t];let n="";for(let e=148;e<156&&0!==s[e];e++)n+=String.fromCharCode(s[e]);n=parseInt(n,8),isNaN(n)||e!=n||(t=new o.Archive(s).entries)}}}catch(e){t=[]}this._entries.set(e,t)}return t}tags(e){let t=this._tags.get(e);if(!t){t=new Map;try{switch(e){case"pbtxt":{const e=this.buffer,s=e.length;if(!(s>=3&&239===e[0]&&187===e[1]&&191===e[2]||s>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]||s>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]||s>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3]||s>=2&&254===e[0]&&255===e[1]||s>=2&&255===e[0]&&254===e[1])&&e.subarray(0,Math.min(1024,s)).some((e=>e<7||e>14&&e<32)))break;const n=r.TextReader.create(this.text);for(n.start(!1);!n.end(!1);){const e=n.tag();t.set(e,!0),n.skip()}break}case"pb":{const e=new Set([0,1,2,3,5]),s=r.Reader.create(this.buffer),n=s.next();for(;s.pos>>3,7&n),!e.has(7&n)){t=new Map;break}try{s.skipType(7&n)}catch(e){t=new Map;break}}break}}}catch(e){t=new Map}this._tags.set(e,t)}return t}}class _{constructor(e,t,s,n){if(this._entries={},e)for(const n of e)if(n.name.startsWith(t)){const e=n.name.substring(t.length);s.length>0&&s.indexOf("/")<0&&(this._entries[e]=n)}this._identifier=s.substring(t.length),this._buffer=n}request(e,t){const s=this._entries[e];if(!s)return Promise.reject(new Error("File not found."));const n=t?new TextDecoder(t).decode(s.data):s.data;return Promise.resolve(n)}get identifier(){return this._identifier}get buffer(){return this._buffer}}class f extends Error{constructor(e){super(e),this.name="Error loading archive."}}m.ModelFactoryService=class{constructor(e){this._host=e,this._extensions=[],this.register("./onnx",[".onnx",".pb",".pbtxt",".prototxt"]),this.register("./mxnet",[".mar",".model",".json",".params"]),this.register("./keras",[".h5",".hd5",".hdf5",".keras",".json",".model",".pb",".pth"]),this.register("./coreml",[".mlmodel"]),this.register("./caffe",[".caffemodel",".pbtxt",".prototxt",".pt"]),this.register("./caffe2",[".pb",".pbtxt",".prototxt"]),this.register("./pytorch",[".pt",".pth",".pt1",".pkl",".h5",".t7",".model",".dms",".tar",".ckpt",".bin",".pb",".zip"]),this.register("./torch",[".t7"]),this.register("./tflite",[".tflite",".lite",".tfl",".bin",".pb",".tmfile",".h5",".model",".json"]),this.register("./tf",[".pb",".meta",".pbtxt",".prototxt",".json",".index",".ckpt"]),this.register("./mediapipe",[".pbtxt"]),this.register("./uff",[".uff",".pb",".trt",".pbtxt",".uff.txt"]),this.register("./sklearn",[".pkl",".pickle",".joblib",".model",".meta",".pb",".pt",".h5"]),this.register("./cntk",[".model",".cntk",".cmf",".dnn"]),this.register("./paddle",[".paddle",".pdmodel","__model__"]),this.register("./armnn",[".armnn"]),this.register("./bigdl",[".model",".bigdl"]),this.register("./darknet",[".cfg",".model"]),this.register("./mnn",[".mnn"]),this.register("./ncnn",[".param",".bin",".cfg.ncnn",".weights.ncnn"]),this.register("./tnn",[".tnnproto",".tnnmodel"]),this.register("./tengine",[".tmfile"]),this.register("./barracuda",[".nn"]),this.register("./openvino",[".xml",".bin"]),this.register("./flux",[".bson"]),this.register("./npz",[".npz",".h5",".hd5",".hdf5"]),this.register("./dl4j",[".zip"]),this.register("./mlnet",[".zip"])}register(e,t){for(const s of t)this._extensions.push({extension:s,id:e})}open(e){return this._openSignature(e).then((e=>this._openArchive(e).then((e=>{const t=(e=new g(e)).identifier,s=t.split(".").pop().toLowerCase(),n=this._filter(e);if(0==n.length)throw new u("Unsupported file extension '."+s+"'.");const i=[];let o=!1;const r=()=>{if(n.length>0){const t=n.shift();return this._host.require(t).then((s=>{if(!s.ModelFactory)throw new u("Failed to load module '"+t+"'.");const n=new s.ModelFactory;return n.match(e)?(o++,n.open(e,this._host).then((e=>e)).catch((e=>(i.push(e),r())))):r()}))}{if(o){if(1==i.length)throw i[0];throw new u(i.map((e=>e.message)).join("\n"))}const n=new Set(["natives_blob.bin","v8_context_snapshot.bin","snapshot_blob.bin","image_net_labels.json","package.json","models.json","LICENSE.meta","input_0.pb","output_0.pb"]).has(t),r=e.buffer,a=Array.from(r.subarray(0,Math.min(16,r.length))).map((e=>(e<16?"0":"")+e.toString(16))).join("");throw new u("Unsupported file content ("+a+") for extension '."+s+"' in '"+t+"'.",!n)}};return r()}))))}_openArchive(e){let t,s=null,r=e.identifier,a=e.buffer;try{if(t=r.split(".").pop().toLowerCase(),("gz"==t||"tgz"==t)&&(s=new i.Archive(a),1==s.entries.length)){const e=s.entries[0];e.name?r=e.name:(r=r.substring(0,r.lastIndexOf(".")),"tgz"==t&&(r+=".tar")),a=e.data}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new f(t.replace(/\.$/,"")+" in '"+r+"'."))}try{switch(t=r.split(".").pop().toLowerCase(),t){case"tar":{const e=[138,10,108,252,156,70,249,32,106,168,80,25];(!a||a.length<14||128!=a[0]||!e.every(((e,t)=>e==a[t+2])))&&(s=new o.Archive(a));break}case"zip":if(s=new n.Archive(a),s.entries.some((e=>"version"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"data.pkl"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e);if(s.entries.some((e=>"coefficients.bin"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"configuration.json"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e)}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new f(t.replace(/\.$/,"")+" in '"+r+"'."))}if(!s)return Promise.resolve(e);try{const n={};for(const e of s.entries)-1!=e.name.indexOf("/")?n[e.name.split("/").shift()+"/"]=!0:n["/"]=!0;"tar"==t&&delete n["PaxHeader/"];let i=1==Object.keys(n).length?Object.keys(n)[0]:"";i="/"==i?"":i;let o=[];const r=s.entries.slice(),a=()=>{if(r.length>0){const e=r.shift();if(e.name.startsWith(i)){const t=e.name.substring(i.length);if(t.length>0&&t.indexOf("/")<0&&!t.startsWith(".")){const t=new g(new _(null,i,e.name,e.data));let s=this._filter(t);const n=()=>{if(s.length>0){const i=s.shift();return this._host.require(i).then((r=>{if(!r.ModelFactory)throw new f("Failed to load module '"+i+"'.",null);return(new r.ModelFactory).match(t)&&(o.push(e),s=[]),n()}))}return a()};return n()}}return a()}{if(0==o.length)return Promise.resolve(e);if(2==o.length&&o.some((e=>e.name.endsWith(".params")))&&o.some((e=>e.name.endsWith("-symbol.json")))&&(o=o.filter((e=>e.name.endsWith(".params")))),o.length>1)return Promise.reject(new f("Archive contains multiple model files."));const t=o[0];return Promise.resolve(new g(new _(s.entries,i,t.name,t.data)))}};return a()}catch(e){return Promise.reject(new f(e.message))}}accept(e){e=e.toLowerCase();for(const t of this._extensions)if(e.endsWith(t.extension))return!0;return!!(e.endsWith(".zip")||e.endsWith(".tar")||e.endsWith(".tar.gz")||e.endsWith(".tgz"))}_filter(e){const t=e.identifier.toLowerCase(),s=this._extensions.filter((e=>t.endsWith(e.extension))).map((e=>e.id));return Array.from(new Set(s))}_openSignature(e){const t=e.buffer;if(0===e.buffer.length)return Promise.reject(new u("File has no content.",!0));const s=[{name:"ELF executable",value:/^\x7FELF/},{name:"Git LFS header",value:/^version https:\/\/git-lfs.github.com\/spec\/v1\n/},{name:"Git LFS header",value:/^oid sha256:/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"Unity metadata",value:/^fileFormatVersion:/},{name:"Vulkan SwiftShader ICD manifest",value:/^{\s*"file_format_version":\s*"1.0.0"\s*,\s*"ICD":/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*id:/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*name:/},{name:"Python source code",value:/^\s*import sys, types, os;/}],n=(new TextDecoder).decode(t.subarray(0,Math.min(1024,t.length)));for(const e of s)if(n.match(e.value))return Promise.reject(new u("Invalid file content. File contains "+e.name+".",!0));return Promise.resolve(e)}},"object"==typeof e.exports&&(e.exports.View=m.View,e.exports.ModelFactoryService=m.ModelFactoryService)},24137:(e,t,s)=>{const n=s(71681),i=s(63332),o=s(499),r=s(81600),a=s(71462),h=s(46506),c=s(19684),l=s(74872),m={View:class{constructor(e){this._host=e,this._host.initialize(this).then((()=>{this._model=null,this._selection=[],this._host.start(),this._showAttributes=!1,this._showInitializers=!0,this._showNames=!1,this._showHorizontal=!1,this._modelFactoryService=new m.ModelFactoryService(this._host)})).catch((e=>{this.error(e.message,e)}))}cut(){this._host.document.execCommand("cut")}copy(){this._host.document.execCommand("copy")}paste(){this._host.document.execCommand("paste")}selectAll(){this._host.document.execCommand("selectall")}find(e){if(this._activeGraph){this.clearSelection();const t=document.getElementById("canvas"),s=new l.FindSidebar(this._host,t,this._activeGraph);this._host.message("search",s.update(e))}}toggleAttributes(e){(null==e||e^this._showAttributes)&&(this._showAttributes=null==e?!this._showAttributes:e,this._reload())}get showAttributes(){return this._showAttributes}toggleInitializers(e){(null==e||e^this._showInitializers)&&(this._showInitializers=null==e?!this._showInitializers:e,this._reload())}get showInitializers(){return this._showInitializers}toggleNames(e){(null==e||e^this._showNames)&&(this._showNames=null==e?!this._showNames:e,this._reload())}get showNames(){return this._showNames}toggleDirection(e){(null==e||e^this._showHorizontal)&&(this._showHorizontal=null==e?!this._showHorizontal:e,this._reload())}get showHorizontal(){return this._showHorizontal}toggleTheme(e){this._host.document.body.className=e}_reload(){this._host.status("loading"),this._model&&this._activeGraph&&this._updateGraph(this._model,this._activeGraph).catch((e=>{e&&this.error("Graph update failed.",e)}))}_timeout(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}zoomIn(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),1.2)}zoomOut(){this._zoom&&this._zoom.scaleBy(a.select(this._host.document.getElementById("canvas")),.8)}resetZoom(){this._zoom&&this._zoom.scaleTo(a.select(this._host.document.getElementById("canvas")),1)}select(e){this.clearSelection();const t=document.getElementById("canvas"),s=l.FindSidebar.selection(e,t);if(s&&s.length>0){const e=this._host.document.getElementById("canvas"),t=e.getBoundingClientRect();let n=0,i=0;for(const e of s){e.classList.add("select"),this._selection.push(e);const t=e.transform.baseVal.consolidate(),s=e.getBBox(),o=t?t.matrix.e:s.x+s.width/2,r=t?t.matrix.f:s.y+s.height/2;n+=o,i+=r}n/=s.length,i/=s.length,this._zoom.transform(a.select(e),a.zoomIdentity.translate(t.width/2-n,t.height/2-i))}}clearSelection(){for(;this._selection.length>0;)this._selection.pop().classList.remove("select")}error(e,t){this._host.error(e,t.toString())}accept(e){return this._modelFactoryService.accept(e)}open(e){return this._timeout(2).then((()=>this._modelFactoryService.open(e).then((e=>this._timeout(20).then((()=>{const t=e.graphs.length>0?e.graphs[0]:null;return this._host.message("opened",{graphs:e.graphs.map((e=>e.name||"")),selected:t&&(t.name||"")}),this._updateGraph(e,t)}))))))}changeGraph(e){this._updateActiveGraph(e)}_updateActiveGraph(e){if(this._model){const t=this._model,s=t.graphs.filter((t=>e==t.name)).shift();s&&(this._host.status("loading"),this._timeout(200).then((()=>this._updateGraph(t,s).catch((e=>{e&&this.error("Graph update failed.",e)})))))}}_updateGraph(e,t){return this._timeout(100).then((()=>t&&t!=this._activeGraph&&t.nodes.length>1400&&!this._host.confirm("Large model detected.","This graph contains a large number of nodes and might take a long time to render. Do you want to continue?")?null:this.renderGraph(e,t).then((()=>(this._model=e,this._activeGraph=t,this._host.status("rendered"),this._model))).catch((e=>this.renderGraph(this._model,this._activeGraph).then((()=>{throw this._host.status("rendered"),e})).catch((()=>{throw e}))))))}renderGraph(e,t){try{const s=this._host.document.getElementById("canvas");for(;s.lastChild;)s.removeChild(s.lastChild);if(t){this._zoom=null,s.style.position="absolute",s.style.margin="0";const n=t.groups,i={nodesep:25,ranksep:20};this._showHorizontal&&(i.rankdir="LR");const o=new h.graphlib.Graph({compound:n});o.setGraph(i),o.setDefaultEdgeLabel((()=>({})));let r=0;const m={},p={},u={};let g=(new Date).getTime();const _=t.nodes;if(_.length>1500&&(i.ranker="longest-path"),n)for(const e of _)if(e.group){const t=e.group.split("/");for(;t.length>0;){const e=t.join("/");t.pop(),u[e]=t.join("/")}}for(const t of _){const i=new c.NodeElement(this._host.document),a=(t,s,n)=>{const i=t.block("header"),o=["node-item-type"],h=s.metadata,c=h&&h.category?h.category:"";c&&o.push("node-item-type-"+c.toLowerCase());const p=s.type;if("string"!=typeof p||!p.split)throw new d("Unknown node type '"+JSON.stringify(p)+"' in '"+e.format+"'.");const u=this.showNames&&s.name?s.name:p.split(".").pop(),g=this.showNames&&s.name?p:s.name;i.add(null,o,u,g,(()=>{this.showNodeProperties(s)})),s.function&&i.add(null,["node-item-function"],"+",null,(()=>{}));const _=[];let f=!1;if(this._showInitializers)for(const e of s.inputs)e.visible&&1==e.arguments.length&&null!=e.arguments[0].initializer&&_.push(e),(!e.visible||e.arguments.length>1)&&e.arguments.some((e=>null!=e.initializer))&&(f=!0);let y=[];const b=s.attributes;if(this.showAttributes&&b&&(y=b.filter((e=>e.visible)).slice(),y.sort(((e,t)=>{const s=e.name.toUpperCase(),n=t.name.toUpperCase();return sn?1:0}))),_.length>0||f||y.length>0){const e=t.block("list");e.handler=()=>{this.showNodeProperties(s)};for(const t of _){const s=t.arguments[0],n=s.type;let i="",o="";n&&n.shape&&n.shape.dimensions&&Object.prototype.hasOwnProperty.call(n.shape.dimensions,"length")&&(i="〈"+n.shape.dimensions.map((e=>e||"?")).join("×")+"〉",0==n.shape.dimensions.length&&s.initializer&&!s.initializer.state&&(i=s.initializer.toString(),i&&i.length>10&&(i=i.substring(0,10)+"…"),o=" = ")),e.add("initializer-"+s.name,t.name,i,n?n.toString():"",o)}f&&e.add(null,"〈…〉","",null,"");for(const t of y)if(t.visible){let s=l.NodeSidebar.formatAttributeValue(t.value,t.type);s&&s.length>25&&(s=s.substring(0,25)+"…"),e.add(null,t.name,s,t.type," = ")}}if(n){const e=s.inputs;for(const t of e)for(const e of t.arguments)if(""!=e.name&&!e.initializer){let s=m[e.name];s||(s={from:null,to:[]},m[e.name]=s),s.to.push({node:r,name:t.name})}let t=s.outputs;if(s.chain&&s.chain.length>0){const e=s.chain[s.chain.length-1].outputs;e.length>0&&(t=e)}for(const e of t)for(const t of e.arguments)if(""!=t.name){let s=m[t.name];s||(s={from:null,to:[]},m[t.name]=s),s.from={node:r,name:e.name,type:t.type}}}if(s.chain&&s.chain.length>0)for(const e of s.chain)a(t,e,!1);s.inner&&a(t,s.inner,!1)};if(a(i,t,!0),t.controlDependencies&&t.controlDependencies.length>0)for(const e of t.controlDependencies){let t=m[e];t||(t={from:null,to:[]},m[e]=t),t.to.push({node:r,name:e,controlDependency:!0})}const h=t.name;h?o.setNode(r,{label:i.format(s),id:"node-"+h}):(o.setNode(r,{label:i.format(s),id:"node-"+g.toString()}),g++);const _=function(e){if(!p[e]){o.setNode(e,{rx:5,ry:5}),p[e]=!0;const t=u[e];t&&(_(t),o.setParent(e,t))}};if(n){let e=t.group;if(e&&e.length>0){if(!Object.prototype.hasOwnProperty.call(u,e)){const t=e.lastIndexOf("/");-1!=t?(e=e.substring(0,t),Object.prototype.hasOwnProperty.call(u,e)||(e=null)):e=null}e&&(_(e),o.setParent(r,e))}}r++}for(const e of t.inputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.from={node:r,type:t.type}}const t=e.arguments.map((e=>e.type||"")).join("\n");let n=e.name||"";n.length>16&&(n=n.split("/").pop());const i=new c.NodeElement(this._host.document);i.block("header").add(null,["graph-item-input"],n,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:i.format(s),class:"graph-input"})}for(const e of t.outputs){for(const t of e.arguments){let e=m[t.name];e||(e={from:null,to:[]},m[t.name]=e),e.to.push({node:r})}const t=e.arguments.map((e=>e.type||"")).join("\n");let n=e.name||"";n.length>16&&(n=n.split("/").pop());const i=new c.NodeElement(this._host.document);i.block("header").add(null,["graph-item-output"],n,t,(()=>{this.showModelProperties()})),o.setNode(r++,{label:i.format(s)})}for(const e of Object.keys(m)){const t=m[e];if(null!=t.from)for(const s of t.to){let n="";const i=t.from.type;i&&i.shape&&i.shape.dimensions&&i.shape.dimensions.length>0&&(n=i.shape.dimensions.join("×")),this._showNames&&(n=e.split("\n").shift()),s.controlDependency?o.setEdge(t.from.node,s.node,{label:n,id:"edge-"+e,arrowhead:"vee",class:"edge-path-control-dependency"}):o.setEdge(t.from.node,s.node,{label:n,id:"edge-"+e,arrowhead:"vee"})}}const f=this._host.document.createElementNS("http://www.w3.org/2000/svg","rect");f.setAttribute("id","background"),f.setAttribute("width","100%"),f.setAttribute("height","100%"),f.setAttribute("fill","none"),f.setAttribute("pointer-events","all"),s.appendChild(f);const y=this._host.document.createElementNS("http://www.w3.org/2000/svg","g");y.setAttribute("id","origin"),s.appendChild(y);let b=null;return b=a.select(s),this._zoom=a.zoom(),this._zoom(b),this._zoom.scaleExtent([.1,2]),this._zoom.on("zoom",(()=>{y.setAttribute("transform",a.event.transform.toString())})),this._zoom.transform(b,a.zoomIdentity),this._timeout(20).then((()=>{new c.Renderer(this._host.document,y).render(o);const e=s.getElementsByClassName("graph-input"),t=s.getBoundingClientRect();if(e&&e.length>0){const s=[],n=[];for(let t=0;te==n[0]))&&(i=s.reduce(((e,t)=>e+t))/s.length);const r=t.width/(this._showHorizontal?4:2)-i,h=t.height/(this._showHorizontal?2:4)-o;this._zoom.transform(b,a.zoomIdentity.translate(r,h))}else this._zoom.transform(b,a.zoomIdentity.translate((t.width-o.graph().width)/2,(t.height-o.graph().height)/2))}))}return Promise.resolve()}catch(e){return Promise.reject(e)}}applyStyleSheet(e,t){let s=[];for(let e=0;e{const s=Math.max(c,l),n=2*s>24e3?24e3/s:2,i=this._host.document.createElement("canvas");i.width=Math.ceil(c*n),i.height=Math.ceil(l*n);const o=i.getContext("2d");o.scale(n,n),o.drawImage(t,0,0),this._host.document.body.removeChild(t),i.toBlob((t=>{if(t)this._host.export(e,t);else{const e=new Error;e.name="Error exporting image.",e.message="Image may be too large to render as PNG.",this._host.exception(e,!1),this._host.error(e.name,e.message)}}),"image/png")},t.src="data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(m))),this._host.document.body.insertBefore(t,this._host.document.body.firstChild)}}}showModelProperties(){if(this._model){const e=new l.ModelSidebar(this._host,this._model,this._activeGraph);this._host.message("show-model-properties",e.render())}}showNodeProperties(e){if(e){const t=new l.NodeSidebar(this._host,e);this._host.message("show-node-properties",{...t.render(),metadata:e.metadata})}}showNodeDocumentation(e){const t=e.metadata;if(t){const e=new l.DocumentationSidebar(this._host,t);this._host.message("show-node-documentation",e.render())}}}};class d extends Error{constructor(e,t){super(e),this.name="Error loading model.",this.telemetry=t}}class p{constructor(e){this._context=e,this._tags=new Map,this._entries=new Map}request(e,t){return this._context.request(e,t)}get identifier(){return this._context.identifier}get buffer(){return this._context.buffer}get text(){return this._text||(this._text=new TextDecoder("utf-8").decode(this.buffer)),this._text}entries(e){let t=this._entries.get(e);if(!t){t=[];try{const s=this.buffer;switch(e){case"zip":s&&s.length>2&&80==s[0]&&75==s[1]&&(t=new n.Archive(s).entries);break;case"tar":if(s.length>=512){let e=0;for(let t=0;t<512;t++)e+=t>=148&&t<156?32:s[t];let n="";for(let e=148;e<156&&0!==s[e];e++)n+=String.fromCharCode(s[e]);n=parseInt(n,8),isNaN(n)||e!=n||(t=new o.Archive(s).entries)}}}catch(e){t=[]}this._entries.set(e,t)}return t}tags(e){let t=this._tags.get(e);if(!t){t=new Map;try{switch(e){case"pbtxt":{const e=this.buffer,s=e.length;if(!(s>=3&&239===e[0]&&187===e[1]&&191===e[2]||s>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]||s>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]||s>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3]||s>=2&&254===e[0]&&255===e[1]||s>=2&&255===e[0]&&254===e[1])&&e.subarray(0,Math.min(1024,s)).some((e=>e<7||e>14&&e<32)))break;const n=r.TextReader.create(this.text);for(n.start(!1);!n.end(!1);){const e=n.tag();t.set(e,!0),n.skip()}break}case"pb":{const e=new Set([0,1,2,3,5]),s=r.Reader.create(this.buffer),n=s.next();for(;s.pos>>3,7&n),!e.has(7&n)){t=new Map;break}try{s.skipType(7&n)}catch(e){t=new Map;break}}break}}}catch(e){t=new Map}this._tags.set(e,t)}return t}}class u{constructor(e,t,s,n){if(this._entries={},e)for(const n of e)if(n.name.startsWith(t)){const e=n.name.substring(t.length);s.length>0&&s.indexOf("/")<0&&(this._entries[e]=n)}this._identifier=s.substring(t.length),this._buffer=n}request(e,t){const s=this._entries[e];if(!s)return Promise.reject(new Error("File not found."));const n=t?new TextDecoder(t).decode(s.data):s.data;return Promise.resolve(n)}get identifier(){return this._identifier}get buffer(){return this._buffer}}class g extends Error{constructor(e){super(e),this.name="Error loading archive."}}m.ModelFactoryService=class{constructor(e){this._host=e,this._extensions=[],this.register("./onnx",[".onnx",".pb",".pbtxt",".prototxt"]),this.register("./mxnet",[".mar",".model",".json",".params"]),this.register("./keras",[".h5",".hd5",".hdf5",".keras",".json",".model",".pb",".pth"]),this.register("./coreml",[".mlmodel"]),this.register("./caffe",[".caffemodel",".pbtxt",".prototxt",".pt"]),this.register("./caffe2",[".pb",".pbtxt",".prototxt"]),this.register("./pytorch",[".pt",".pth",".pt1",".pkl",".h5",".t7",".model",".dms",".tar",".ckpt",".bin",".pb",".zip"]),this.register("./torch",[".t7"]),this.register("./tflite",[".tflite",".lite",".tfl",".bin",".pb",".tmfile",".h5",".model",".json"]),this.register("./tf",[".pb",".meta",".pbtxt",".prototxt",".json",".index",".ckpt"]),this.register("./mediapipe",[".pbtxt"]),this.register("./uff",[".uff",".pb",".trt",".pbtxt",".uff.txt"]),this.register("./sklearn",[".pkl",".pickle",".joblib",".model",".meta",".pb",".pt",".h5"]),this.register("./cntk",[".model",".cntk",".cmf",".dnn"]),this.register("./paddle",[".paddle",".pdmodel","__model__"]),this.register("./armnn",[".armnn"]),this.register("./bigdl",[".model",".bigdl"]),this.register("./darknet",[".cfg",".model"]),this.register("./mnn",[".mnn"]),this.register("./ncnn",[".param",".bin",".cfg.ncnn",".weights.ncnn"]),this.register("./tnn",[".tnnproto",".tnnmodel"]),this.register("./tengine",[".tmfile"]),this.register("./barracuda",[".nn"]),this.register("./openvino",[".xml",".bin"]),this.register("./flux",[".bson"]),this.register("./npz",[".npz",".h5",".hd5",".hdf5"]),this.register("./dl4j",[".zip"]),this.register("./mlnet",[".zip"])}register(e,t){for(const s of t)this._extensions.push({extension:s,id:e})}open(e){return this._openSignature(e).then((e=>this._openArchive(e).then((e=>{const t=(e=new p(e)).identifier,s=t.split(".").pop().toLowerCase(),n=this._filter(e);if(0==n.length)throw new d("Unsupported file extension '."+s+"'.");const i=[];let o=!1;const r=()=>{if(n.length>0){const t=n.shift();return this._host.require(t).then((s=>{if(!s.ModelFactory)throw new d("Failed to load module '"+t+"'.");const n=new s.ModelFactory;return n.match(e)?(o++,n.open(e,this._host).then((e=>e)).catch((e=>(i.push(e),r())))):r()}))}{if(o){if(1==i.length)throw i[0];throw new d(i.map((e=>e.message)).join("\n"))}const n=new Set(["natives_blob.bin","v8_context_snapshot.bin","snapshot_blob.bin","image_net_labels.json","package.json","models.json","LICENSE.meta","input_0.pb","output_0.pb"]).has(t),r=e.buffer,a=Array.from(r.subarray(0,Math.min(16,r.length))).map((e=>(e<16?"0":"")+e.toString(16))).join("");throw new d("Unsupported file content ("+a+") for extension '."+s+"' in '"+t+"'.",!n)}};return r()}))))}_openArchive(e){let t,s=null,r=e.identifier,a=e.buffer;try{if(t=r.split(".").pop().toLowerCase(),("gz"==t||"tgz"==t)&&(s=new i.Archive(a),1==s.entries.length)){const e=s.entries[0];e.name?r=e.name:(r=r.substring(0,r.lastIndexOf(".")),"tgz"==t&&(r+=".tar")),a=e.data}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new g(t.replace(/\.$/,"")+" in '"+r+"'."))}try{switch(t=r.split(".").pop().toLowerCase(),t){case"tar":{const e=[138,10,108,252,156,70,249,32,106,168,80,25];(!a||a.length<14||128!=a[0]||!e.every(((e,t)=>e==a[t+2])))&&(s=new o.Archive(a));break}case"zip":if(s=new n.Archive(a),s.entries.some((e=>"version"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"data.pkl"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e);if(s.entries.some((e=>"coefficients.bin"===e.name.split("/").pop().split("\\").pop()))&&s.entries.some((e=>"configuration.json"===e.name.split("/").pop().split("\\").pop())))return Promise.resolve(e)}}catch(e){const t=e&&e.message?e.message:e.toString();return Promise.reject(new g(t.replace(/\.$/,"")+" in '"+r+"'."))}if(!s)return Promise.resolve(e);try{const n={};for(const e of s.entries)-1!=e.name.indexOf("/")?n[e.name.split("/").shift()+"/"]=!0:n["/"]=!0;"tar"==t&&delete n["PaxHeader/"];let i=1==Object.keys(n).length?Object.keys(n)[0]:"";i="/"==i?"":i;let o=[];const r=s.entries.slice(),a=()=>{if(r.length>0){const e=r.shift();if(e.name.startsWith(i)){const t=e.name.substring(i.length);if(t.length>0&&t.indexOf("/")<0&&!t.startsWith(".")){const t=new p(new u(null,i,e.name,e.data));let s=this._filter(t);const n=()=>{if(s.length>0){const i=s.shift();return this._host.require(i).then((r=>{if(!r.ModelFactory)throw new g("Failed to load module '"+i+"'.",null);return(new r.ModelFactory).match(t)&&(o.push(e),s=[]),n()}))}return a()};return n()}}return a()}{if(0==o.length)return Promise.resolve(e);if(2==o.length&&o.some((e=>e.name.endsWith(".params")))&&o.some((e=>e.name.endsWith("-symbol.json")))&&(o=o.filter((e=>e.name.endsWith(".params")))),o.length>1)return Promise.reject(new g("Archive contains multiple model files."));const t=o[0];return Promise.resolve(new p(new u(s.entries,i,t.name,t.data)))}};return a()}catch(e){return Promise.reject(new g(e.message))}}accept(e){e=e.toLowerCase();for(const t of this._extensions)if(e.endsWith(t.extension))return!0;return!!(e.endsWith(".zip")||e.endsWith(".tar")||e.endsWith(".tar.gz")||e.endsWith(".tgz"))}_filter(e){const t=e.identifier.toLowerCase(),s=this._extensions.filter((e=>t.endsWith(e.extension))).map((e=>e.id));return Array.from(new Set(s))}_openSignature(e){const t=e.buffer;if(0===e.buffer.length)return Promise.reject(new d("File has no content.",!0));const s=[{name:"ELF executable",value:/^\x7FELF/},{name:"Git LFS header",value:/^version https:\/\/git-lfs.github.com\/spec\/v1\n/},{name:"Git LFS header",value:/^oid sha256:/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"HTML markup",value:/^\s*/},{name:"Unity metadata",value:/^fileFormatVersion:/},{name:"Vulkan SwiftShader ICD manifest",value:/^{\s*"file_format_version":\s*"1.0.0"\s*,\s*"ICD":/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*id:/},{name:"StringIntLabelMapProto data",value:/^item\s*{\r?\n\s*name:/},{name:"Python source code",value:/^\s*import sys, types, os;/}],n=(new TextDecoder).decode(t.subarray(0,Math.min(1024,t.length)));for(const e of s)if(n.match(e.value))return Promise.reject(new d("Invalid file content. File contains "+e.name+".",!0));return Promise.resolve(e)}},"object"==typeof e.exports&&(e.exports.View=m.View,e.exports.ModelFactoryService=m.ModelFactoryService)},83260:()=>{}},s={};function n(e){var i=s[e];if(void 0!==i)return i.exports;var o=s[e]={id:e,loaded:!1,exports:{}};return t[e].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}n.m=t,e=[],n.O=(t,s,i,o)=>{if(!s){var r=1/0;for(l=0;l=o)&&Object.keys(n.O).every((e=>n.O[e](s[h])))?s.splice(h--,1):(a=!1,o0&&e[l-1][2]>o;l--)e[l]=e[l-1];e[l]=[s,i,o]},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),n.j=826,(()=>{var e={826:0};n.O.j=t=>0===e[t];var t=(t,s)=>{var i,o,[r,a,h]=s,c=0;if(r.some((t=>0!==e[t]))){for(i in a)n.o(a,i)&&(n.m[i]=a[i]);if(h)var l=h(n)}for(t&&t(s);cn(68138)));i=n.O(i)})(); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..671c9dad3dc8661ddfcf93dbf1876fe1a334bacb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html @@ -0,0 +1 @@ +
    \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html.proxy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html.proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..2c58aab400af9896f0a77288e99e5892232df2e3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/index.html.proxy.js @@ -0,0 +1 @@ +export default"/__snowpack__/link/packages/netron2/dist/index.html"; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..e6f00d784e5e1b34b3e494dfb402ab6c4a65559d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras-metadata.json @@ -0,0 +1 @@ +[{"name":"Bidirectional","schema":{"attributes":[{"default":"concat","description":"Mode by which outputs of the forward and backward RNNs will be\n combined. One of {'sum', 'mul', 'concat', 'ave', None}. If None, the\n outputs will not be combined, they will be returned as a list. Default\n value is 'concat'.","name":"merge_mode"},{"description":"`keras.layers.RNN` instance, such as `keras.layers.LSTM` or\n `keras.layers.GRU`. It could also be a `keras.layers.Layer` instance\n that meets the following criteria:\n 1. Be a sequence-processing layer (accepts 3D+ inputs).\n 2. Have a `go_backwards`, `return_sequences` and `return_state`\n attribute (with the same semantics as for the `RNN` class).\n 3. Have an `input_spec` attribute.\n 4. Implement serialization via `get_config()` and `from_config()`.\n Note that the recommended way to create new RNN layers is to write a\n custom RNN cell and use it with `keras.layers.RNN`, instead of\n subclassing `keras.layers.Layer` directly.","name":"layer"},{"description":"Initial weights to load in the Bidirectional model\n","name":"weights"},{"description":"Optional `keras.layers.RNN`, or `keras.layers.Layer`\n instance to be used to handle backwards input processing.\n If `backward_layer` is not provided, the layer instance passed as the\n `layer` argument will be used to generate the backward layer\n automatically.\n Note that the provided `backward_layer` layer should have properties\n matching those of the `layer` argument, in particular it should have the\n same values for `stateful`, `return_states`, `return_sequence`, etc.\n In addition, `backward_layer` and `layer` should have different\n `go_backwards` argument values.\n A `ValueError` will be raised if these requirements are not met.","name":"backward_layer"}],"category":"Wrapper","description":"Bidirectional wrapper for RNNs.","examples":[{"code":"model = Sequential()\nmodel.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10)))\nmodel.add(Bidirectional(LSTM(10)))\nmodel.add(Dense(5))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\n # With custom backward layer\n model = Sequential()\n forward_layer = LSTM(10, return_sequences=True)\n backward_layer = LSTM(10, activation='relu', return_sequences=True,\n go_backwards=True)\n model.add(Bidirectional(forward_layer, backward_layer=backward_layer,\n input_shape=(5, 10)))\n model.add(Dense(5))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"TimeDistributed","schema":{"attributes":[{"description":"a `tf.keras.layers.Layer` instance.","name":"layer"}],"category":"Wrapper","description":"This wrapper allows to apply a layer to every temporal slice of an input.\n\nThe input should be at least 3D, and the dimension of index one\nwill be considered to be the temporal dimension.\n\nConsider a batch of 32 video samples, where each sample is a 128x128 RGB image\nwith `channels_last` data format, across 10 timesteps.\nThe batch input shape is `(32, 10, 128, 128, 3)`.\n\nYou can then use `TimeDistributed` to apply a `Conv2D` layer to each of the\n10 timesteps, independently:\n\n```\n>>> inputs = tf.keras.Input(shape=(10, 128, 128, 3))\n>>> conv_2d_layer = tf.keras.layers.Conv2D(64, (3, 3))\n>>> outputs = tf.keras.layers.TimeDistributed(conv_2d_layer)(inputs)\n>>> outputs.shape\nTensorShape([None, 10, 126, 126, 64])\n```","inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Activation","schema":{"attributes":[{"description":"Activation function, such as `tf.nn.relu`, or string name of\n built-in activation function, such as \"relu\".","name":"activation"}],"category":"Activation","description":"Applies an activation function to an output.","examples":[{"code":">>> layer = tf.keras.layers.Activation('relu')\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.Activation(tf.nn.relu)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ReLU","schema":{"attributes":[{"description":"Float >= 0. Maximum activation value. Default to None, which\n means unlimited.","name":"max_value"},{"description":"Float >= 0. Negative slope coefficient. Default to 0.","name":"negative_slope"},{"description":"Float. Threshold value for thresholded activation. Default to 0.","name":"threshold"}],"category":"Activation","description":"Rectified Linear Unit activation function.\n\nWith default values, it returns element-wise `max(x, 0)`.\n\nOtherwise, it follows:\n\n```\n f(x) = max_value if x >= max_value\n f(x) = x if threshold <= x < max_value\n f(x) = negative_slope * (x - threshold) otherwise\n```","examples":[{"code":">>> layer = tf.keras.layers.ReLU()\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.ReLU(max_value=1.0)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 1.0]\n>>> layer = tf.keras.layers.ReLU(negative_slope=1.0)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-3.0, -1.0, 0.0, 2.0]\n>>> layer = tf.keras.layers.ReLU(threshold=1.5)\n>>> output = layer([-3.0, -1.0, 1.0, 2.0])\n>>> list(output.numpy())\n[0.0, 0.0, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LeakyReLU","schema":{"attributes":[{"description":"Float >= 0. Negative slope coefficient. Default to 0.3.","name":"alpha"}],"category":"Activation","description":"Leaky version of a Rectified Linear Unit.\n\nIt allows a small gradient when the unit is not active:\n\n```\n f(x) = alpha * x if x < 0\n f(x) = x if x >= 0\n```","examples":[{"code":">>> layer = tf.keras.layers.LeakyReLU()\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-0.9, -0.3, 0.0, 2.0]\n>>> layer = tf.keras.layers.LeakyReLU(alpha=0.1)\n>>> output = layer([-3.0, -1.0, 0.0, 2.0])\n>>> list(output.numpy())\n[-0.3, -0.1, 0.0, 2.0]"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the batch axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Rectifier Nonlinearities Improve Neural Network Acoustic Models]( https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf)"}]}},{"name":"PReLU","schema":{"attributes":[{"description":"Initializer function for the weights.","name":"alpha_initializer"},{"description":"Regularizer for the weights.","name":"alpha_regularizer","visible":false},{"description":"Constraint for the weights.","name":"alpha_constraint"},{"description":"The axes along which to share learnable\n parameters for the activation function.\n For example, if the incoming feature maps\n are from a 2D convolution\n with output shape `(batch, height, width, channels)`,\n and you wish to share parameters across space\n so that each filter only has one set of parameters,\n set `shared_axes=[1, 2]`.","name":"shared_axes"}],"category":"Activation","description":"Parametric Rectified Linear Unit.\n\nIt follows:\n\n```\n f(x) = alpha * x for x < 0\n f(x) = x for x >= 0\n```\n\nwhere `alpha` is a learned array with the same shape as x.","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"},{"name":"params"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://arxiv.org/abs/1502.01852)"}]}},{"name":"ELU","schema":{"attributes":[{"description":"Scale for the negative factor.","name":"alpha"}],"category":"Activation","description":"Exponential Linear Unit.\n\nIt follows:\n\n```\n f(x) = alpha * (exp(x) - 1.) for x < 0\n f(x) = x for x >= 0\n```","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)](https://arxiv.org/abs/1511.07289v1)"}]}},{"name":"ThresholdedReLU","schema":{"attributes":[{"description":"Float >= 0. Threshold location of activation.","name":"theta"}],"category":"Activation","description":"Thresholded Rectified Linear Unit.\n\nIt follows:\n\n```\n f(x) = x for x > theta\n f(x) = 0 otherwise`\n```","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as the input.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Zero-Bias Autoencoders and the Benefits of Co-Adapting Features]( https://arxiv.org/abs/1402.3337)"}]}},{"name":"MaxPooling1D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"},{"default":"valid","description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":[2,2],"description":"Integer, size of the max pooling window.","name":"pool_size"},{"default":[2,2],"description":"Integer, or None. Specifies how much the pooling window moves\n for each pooling step.\n If None, it will default to `pool_size`.","name":"strides"}],"category":"Pool","description":"Max pooling operation for 1D temporal data.\n\nDownsamples the input representation by taking the maximum value over the\nwindow defined by `pool_size`. The window is shifted by `strides`. The\nresulting output when using \"valid\" padding option has a shape of:\n`output_shape = (input_shape - pool_size + 1) / strides)`\n\nThe resulting output shape when using the \"same\" padding option is:\n`output_shape = input_shape / strides`\n\nFor example, for strides=1 and padding=\"valid\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=1, padding='valid')\n>>> max_pool_1d(x)\n\n```\n\nFor example, for strides=2 and padding=\"valid\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=2, padding='valid')\n>>> max_pool_1d(x)\n\n```\n\nFor example, for strides=1 and padding=\"same\":\n\n```\n>>> x = tf.constant([1., 2., 3., 4., 5.])\n>>> x = tf.reshape(x, [1, 5, 1])\n>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n... strides=1, padding='same')\n>>> max_pool_1d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"MaxPooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"default":"valid","description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":[2,2],"description":"integer or tuple of 2 integers,\n window size over which to take the maximum.\n `(2, 2)` will take the max value over a 2x2 pooling window.\n If only one integer is specified, the same window length\n will be used for both dimensions.","name":"pool_size"},{"default":[2,2],"description":"Integer, tuple of 2 integers, or None.\n Strides values. Specifies how far the pooling window moves\n for each pooling step. If None, it will default to `pool_size`.","name":"strides"}],"category":"Pool","description":"Max pooling operation for 2D spatial data.\n\nDownsamples the input representation by taking the maximum value over the\nwindow defined by `pool_size` for each dimension along the features axis.\nThe window is shifted by `strides` in each dimension. The resulting output\nwhen using \"valid\" padding option has a shape(number of rows or columns) of:\n`output_shape = (input_shape - pool_size + 1) / strides)`\n\nThe resulting output shape when using the \"same\" padding option is:\n`output_shape = input_shape / strides`\n\nFor example, for stride=(1,1) and padding=\"valid\":\n\n```\n>>> x = tf.constant([[1., 2., 3.],\n... [4., 5., 6.],\n... [7., 8., 9.]])\n>>> x = tf.reshape(x, [1, 3, 3, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='valid')\n>>> max_pool_2d(x)\n\n```\n\nFor example, for stride=(2,2) and padding=\"valid\":\n\n```\n>>> x = tf.constant([[1., 2., 3., 4.],\n... [5., 6., 7., 8.],\n... [9., 10., 11., 12.]])\n>>> x = tf.reshape(x, [1, 3, 4, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='valid')\n>>> max_pool_2d(x)\n\n \nUsage Example:\n```\n\n```\n>>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]],\n... [[2.], [2.], [3.], [2.]],\n... [[4.], [1.], [1.], [1.]],\n... [[2.], [2.], [1.], [4.]]]]) \n>>> output = tf.constant([[[[1], [0]],\n... [[0], [1]]]]) \n>>> model = tf.keras.models.Sequential()\n>>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), \n... input_shape=(4,4,1)))\n>>> model.compile('adam', 'mean_squared_error')\n>>> model.predict(input_image, steps=1)\narray([[[[2.],\n [4.]],\n [[4.],\n [4.]]]], dtype=float32)\n```\n\nFor example, for stride=(1,1) and padding=\"same\":\n\n```\n>>> x = tf.constant([[1., 2., 3.],\n... [4., 5., 6.],\n... [7., 8., 9.]])\n>>> x = tf.reshape(x, [1, 3, 3, 1])\n>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n... strides=(1, 1), padding='same')\n>>> max_pool_2d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"MaxPooling3D","schema":{"attributes":[{"description":"Tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.","name":"pool_size"},{"description":"tuple of 3 integers, or None. Strides values.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Max pooling operation for 3D data (spatial or spatio-temporal).","inputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling1D","schema":{"attributes":[{"default":"channels_last","name":"data_format"},{"description":"Integer. Upsampling factor.","name":"size"}],"category":"Layer","description":"Upsampling layer for 1D inputs.\n\nRepeats each temporal step `size` times along the time axis.","examples":[{"code":">>> input_shape = (2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n>>> y = tf.keras.layers.UpSampling1D(size=2)(x)\n>>> print(y)\ntf.Tensor(\n [[[ 0 1 2]\n [ 0 1 2]\n [ 3 4 5]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 6 7 8]\n [ 9 10 11]\n [ 9 10 11]]], shape=(2, 4, 3), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape: `(batch_size, steps, features)`.","name":"input"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, upsampled_steps, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Int, or tuple of 2 integers.\n The upsampling factors for rows and columns.","name":"size"},{"description":"A string, one of `nearest` or `bilinear`.","name":"interpolation"}],"category":"Layer","description":"Upsampling layer for 2D inputs.\n\nRepeats the rows and columns of the data\nby `size[0]` and `size[1]` respectively.","examples":[{"code":">>> input_shape = (2, 2, 1, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[[ 0 1 2]]\n [[ 3 4 5]]]\n [[[ 6 7 8]]\n [[ 9 10 11]]]]\n>>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x)\n>>> print(y)\ntf.Tensor(\n [[[[ 0 1 2]\n [ 0 1 2]]\n [[ 3 4 5]\n [ 3 4 5]]]\n [[[ 6 7 8]\n [ 6 7 8]]\n [[ 9 10 11]\n [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_rows, upsampled_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_rows, upsampled_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"UpSampling3D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Int, or tuple of 3 integers.\n The upsampling factors for dim1, dim2 and dim3.","name":"size"}],"category":"Layer","description":"Upsampling layer for 3D inputs.\n\nRepeats the 1st, 2nd and 3rd dimensions\nof the data by `size[0]`, `size[1]` and `size[2]` respectively.","examples":[{"code":">>> input_shape = (2, 1, 2, 1, 3)\n>>> x = tf.constant(1, shape=input_shape)\n>>> y = tf.keras.layers.UpSampling3D(size=2)(x)\n>>> print(y.shape)\n(2, 2, 4, 2, 3)"}],"inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, dim1, dim2, dim3, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, dim1, dim2, dim3)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding1D","schema":{"attributes":[{"description":"Int, or tuple of int (length 2), or dictionary.\n - If int:\n How many zeros to add at the beginning and end of\n the padding dimension (axis 1).\n - If tuple of int (length 2):\n How many zeros to add at the beginning and the end of\n the padding dimension (`(left_pad, right_pad)`).","name":"padding"}],"category":"Tensor","description":"Zero-padding layer for 1D input (e.g. temporal sequence).","examples":[{"code":">>> input_shape = (2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n>>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x)\n>>> print(y)\ntf.Tensor(\n [[[ 0 0 0]\n [ 0 0 0]\n [ 0 1 2]\n [ 3 4 5]\n [ 0 0 0]\n [ 0 0 0]]\n [[ 0 0 0]\n [ 0 0 0]\n [ 6 7 8]\n [ 9 10 11]\n [ 0 0 0]\n [ 0 0 0]]], shape=(2, 6, 3), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape `(batch_size, axis_to_pad, features)`","name":"input"}],"outputs":[{"description":"3D tensor with shape `(batch_size, padded_axis, features)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding2D","schema":{"attributes":[{"description":"Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_height_pad, symmetric_width_pad)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_pad, bottom_pad), (left_pad, right_pad))`","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Tensor","description":"Zero-padding layer for 2D input (e.g. picture).\n\nThis layer can add rows and columns of zeros\nat the top, bottom, left and right side of an image tensor.","examples":[{"code":">>> input_shape = (1, 1, 2, 2)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[[0 1]\n [2 3]]]]\n>>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x)\n>>> print(y)\ntf.Tensor(\n [[[[0 0]\n [0 0]\n [0 0]\n [0 0]]\n [[0 0]\n [0 1]\n [2 3]\n [0 0]]\n [[0 0]\n [0 0]\n [0 0]\n [0 0]]]], shape=(1, 3, 4, 2), dtype=int64)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, padded_rows, padded_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, padded_rows, padded_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"ZeroPadding3D","schema":{"attributes":[{"description":"Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 3 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`.\n - If tuple of 3 tuples of 2 ints:\n interpreted as\n `((left_dim1_pad, right_dim1_pad), (left_dim2_pad,\n right_dim2_pad), (left_dim3_pad, right_dim3_pad))`","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Tensor","description":"Zero-padding layer for 3D data (spatial or spatio-temporal).","examples":[{"code":">>> input_shape = (1, 1, 2, 2, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x)\n>>> print(y.shape)\n(1, 5, 6, 6, 3)"}],"inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_pad, second_axis_to_pad,\n third_axis_to_pad)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_padded_axis, second_padded_axis,\n third_axis_to_pad)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalMaxPooling1D","schema":{"attributes":[{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Global max pooling operation for 1D temporal data.\n\nDownsamples the input representation by taking the maximum value over\nthe time dimension.\n\nFor example:\n\n```\n>>> x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])\n>>> x = tf.reshape(x, [3, 3, 1])\n>>> x\n\n>>> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D()\n>>> max_pool_1d(x)\n\n```","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n- If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalMaxPooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Global max pooling operation for spatial data.","examples":[{"code":">>> input_shape = (2, 4, 5, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalMaxPool2D()(x)\n>>> print(y.shape)\n(2, 3)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, channels)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalAveragePooling1D","schema":{"attributes":[{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Global average pooling operation for temporal data.","examples":[{"code":">>> input_shape = (2, 3, 4)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalAveragePooling1D()(x)\n>>> print(y.shape)\n(2, 4)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n- If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"GlobalAveragePooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Pool","description":"Global average pooling operation for spatial data.","examples":[{"code":">>> input_shape = (2, 4, 5, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.GlobalAveragePooling2D()(x)\n>>> print(y.shape)\n(2, 3)"}],"inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"2D tensor with shape `(batch_size, channels)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling1D","schema":{"attributes":[{"description":"Integer, size of the average pooling windows.","name":"pool_size"},{"description":"Integer, or None. Factor by which to downscale.\n E.g. 2 will halve the input.\n If None, it will default to `pool_size`.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.","name":"data_format"}],"category":"Pool","description":"Average pooling for temporal data.","inputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n- If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling2D","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"integer or tuple of 2 integers,\n factors by which to downscale (vertical, horizontal).\n `(2, 2)` will halve the input in both spatial dimension.\n If only one integer is specified, the same window length\n will be used for both dimensions.","name":"pool_size"},{"description":"Integer, tuple of 2 integers, or None.\n Strides values.\n If None, it will default to `pool_size`.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"}],"category":"Pool","description":"Average pooling operation for spatial data.","inputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n- If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"AveragePooling3D","schema":{"attributes":[{"description":"tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.","name":"pool_size"},{"description":"tuple of 3 integers, or None. Strides values.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"description":"Average pooling operation for 3D data (spatial or spatio-temporal).","inputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`","name":"input"}],"outputs":[{"description":"- If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n- If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"BatchNormalization","schema":{"attributes":[{"default":-1,"description":"Integer, the axis that should be normalized (typically the features\n axis). For instance, after a `Conv2D` layer with\n `data_format=\"channels_first\"`, set `axis=1` in `BatchNormalization`.","name":"axis"},{"default":0.001,"description":"Small float added to variance to avoid dividing by zero.","name":"epsilon"},{"default":0.99,"description":"Momentum for the moving average.","name":"momentum"},{"default":true,"description":"If True, multiply by `gamma`. If False, `gamma` is not used. When the\n next layer is linear (also e.g. `nn.relu`), this can be disabled since the\n scaling will be done by the next layer.","name":"scale","type":"boolean"},{"default":true,"description":"If True, add offset of `beta` to normalized tensor. If False, `beta`\n is ignored.","name":"center"},{"default":{"class_name":"Ones","config":{}},"description":"Initializer for the gamma weight.","name":"gamma_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the moving mean.","name":"moving_mean_initializer","visible":false},{"default":{"class_name":"Ones","config":{}},"description":"Initializer for the moving variance.","name":"moving_variance_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the beta weight.","name":"beta_initializer","visible":false},{"description":"Optional regularizer for the beta weight.","name":"beta_regularizer","visible":false},{"description":"Optional regularizer for the gamma weight.","name":"gamma_regularizer","visible":false},{"description":"Optional constraint for the beta weight.","name":"beta_constraint"},{"description":"Optional constraint for the gamma weight.","name":"gamma_constraint"},{"description":"Whether to use [Batch Renormalization](\n https://arxiv.org/abs/1702.03275). This adds extra variables during\n training. The inference is the same for either value of this parameter.","name":"renorm"},{"description":"A dictionary that may map keys 'rmax', 'rmin', 'dmax' to\n scalar `Tensors` used to clip the renorm correction. The correction `(r,\n d)` is used as `corrected_value = normalized_value * r + d`, with `r`\n clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin,\n dmax are set to inf, 0, inf, respectively.","name":"renorm_clipping"},{"description":"Momentum used to update the moving means and standard\n deviations with renorm. Unlike `momentum`, this affects training and\n should be neither too small (which would add noise) nor too large (which\n would give stale estimates). Note that `momentum` is still applied to get\n the means and variances for inference.","name":"renorm_momentum"},{"description":"if `True`, use a faster, fused implementation, or raise a ValueError\n if the fused implementation cannot be used. If `None`, use the faster\n implementation if possible. If False, do not used the fused\n implementation.","name":"fused"},{"description":"Boolean, if `True` the variables will be marked as trainable.","name":"trainable"},{"description":"An `int`. By default, `virtual_batch_size` is `None`,\n which means batch normalization is performed across the whole batch. When\n `virtual_batch_size` is not `None`, instead perform \"Ghost Batch\n Normalization\", which creates virtual sub-batches which are each\n normalized separately (with shared gamma, beta, and moving statistics).\n Must divide the actual batch size during execution.","name":"virtual_batch_size"},{"description":"A function taking the `Tensor` containing the (dynamic) shape of\n the input tensor and returning a pair (scale, bias) to apply to the\n normalized values (before gamma and beta), only during training. For\n example, if axis==-1,\n `adjustment = lambda shape: (\n tf.random.uniform(shape[-1:], 0.93, 1.07),\n tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized\n value by up to 7% up or down, then shift the result by up to 0.1\n (with independent scaling and bias for each feature but shared\n across all examples), and finally apply gamma and/or beta. If\n `None`, no adjustment is applied. Cannot be specified if\n virtual_batch_size is specified.","name":"adjustment"}],"category":"Normalization","description":"Normalize and scale inputs or activations.\n\nNormalize the activations of the previous layer at each batch,\ni.e. applies a transformation that maintains the mean activation\nclose to 0 and the activation standard deviation close to 1.\n\nBatch normalization differs from other layers in several key aspects:\n\n1) Adding BatchNormalization with `training=True` to a model causes the\nresult of one example to depend on the contents of all other examples in a\nminibatch. Be careful when padding batches or masking examples, as these can\nchange the minibatch statistics and affect other examples.\n\n2) Updates to the weights (moving statistics) are based on the forward pass\nof a model rather than the result of gradient computations.\n\n3) When performing inference using a model containing batch normalization, it\nis generally (though not always) desirable to use accumulated statistics\nrather than mini-batch statistics. This is accomplished by passing\n`training=False` when calling the model, or using `model.predict`.","inputs":[{"description":"Same shape as input.\n\n\n**About setting `layer.trainable = False` on a `BatchNormalization layer:**\n\nThe meaning of setting `layer.trainable = False` is to freeze the layer,\ni.e. its internal state will not change during training:\nits trainable weights will not be updated\nduring `fit()` or `train_on_batch()`, and its state updates will not be run.\n\nUsually, this does not necessarily mean that the layer is run in inference\nmode (which is normally controlled by the `training` argument that can\nbe passed when calling a layer). \"Frozen state\" and \"inference mode\"\nare two separate concepts.\n\nHowever, in the case of the `BatchNormalization` layer, **setting\n`trainable = False` on the layer means that the layer will be\nsubsequently run in inference mode** (meaning that it will use\nthe moving mean and the moving variance to normalize the current batch,\nrather than using the mean and variance of the current batch).\n\nThis behavior has been introduced in TensorFlow 2.0, in order\nto enable `layer.trainable = False` to produce the most commonly\nexpected behavior in the convnet fine-tuning use case.\n\nNote that:\n - This behavior only occurs as of TensorFlow 2.0. In 1.*,\n setting `layer.trainable = False` would freeze the layer but would\n not switch it to inference mode.\n - Setting `trainable` on an model containing other layers will\n recursively set the `trainable` value of all inner layers.\n - If the value of the `trainable`\n attribute is changed after calling `compile()` on a model,\n the new value doesn't take effect for this model\n until `compile()` is called again.\n \n\nNormalization equations:\n Consider the intermediate activations \\(x\\) of a mini-batch of size\n \\\\(m\\\\):\n\n We can compute the mean and variance of the batch\n\n \\\\({\\mu_B} = \\frac{1}{m} \\sum_{i=1}^{m} {x_i}\\\\)\n\n \\\\({\\sigma_B^2} = \\frac{1}{m} \\sum_{i=1}^{m} ({x_i} - {\\mu_B})^2\\\\)\n\n and then compute a normalized \\\\(x\\\\), including a small factor\n \\\\({\\epsilon}\\\\) for numerical stability.\n\n \\\\(\\hat{x_i} = \\frac{x_i - \\mu_B}{\\sqrt{\\sigma_B^2 + \\epsilon}}\\\\)\n\n And finally \\\\(\\hat{x}\\) is linearly transformed by \\({\\gamma}\\\\)\n and \\\\({\\beta}\\\\), which are learned parameters:\n\n \\\\({y_i} = {\\gamma * \\hat{x_i} + \\beta}\\\\)","name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"moving_mean"},{"name":"moving_variance"}],"outputs":[{"description":"\nSame shape as input.\n","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167)"}]}},{"name":"BatchNorm","schema":{"attributes":[{"default":-1,"name":"axis"},{"default":0.001,"name":"epsilon"},{"default":0.99,"name":"momentum"},{"default":true,"name":"scale"},{"default":true,"name":"center"},{"default":{"class_name":"Ones","config":{}},"name":"gamma_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"name":"moving_mean_initializer","visible":false},{"default":{"class_name":"Ones","config":{}},"name":"moving_variance_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"name":"beta_initializer","visible":false},{"name":"beta_regularizer","visible":false},{"name":"gamma_regularizer","visible":false},{"name":"beta_constraint"},{"name":"gamma_constraint"}],"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"running_mean"},{"name":"running_std"}],"outputs":[{"name":"output"}]}},{"name":"ActivityRegularization","schema":{"attributes":[{"description":"L1 regularization factor (positive float).","name":"l1"},{"description":"L2 regularization factor (positive float).","name":"l2"}],"description":"Layer that applies an update to the cost function based input activity.","inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same shape as input.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Masking","schema":{"attributes":[{"description":"Either None or mask value to skip\n","name":"mask_value"}],"description":"Masks a sequence by using a mask value to skip timesteps.\n\nFor each timestep in the input tensor (dimension #1 in the tensor),\nif all values in the input tensor at that timestep\nare equal to `mask_value`, then the timestep will be masked (skipped)\nin all downstream layers (as long as they support masking).\n\nIf any downstream layer does not support masking yet receives such\nan input mask, an exception will be raised.","examples":[{"code":"samples, timesteps, features = 32, 10, 8\ninputs = np.random.random([samples, timesteps, features]).astype(np.float32)\ninputs[:, 3, :] = 0.\ninputs[:, 5, :] = 0.\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Masking(mask_value=0.,\n input_shape=(timesteps, features)))\nmodel.add(tf.keras.layers.LSTM(32))\n\noutput = model(inputs)\n# The time step 3 and 5 will be skipped from LSTM calculation.","summary":"Consider a Numpy data array `x` of shape `(samples, timesteps, features)`,\nto be fed to an LSTM layer. You want to mask timestep #3 and #5 because you\nlack data for these timesteps. You can:\n- Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.`\n- Insert a `Masking` layer with `mask_value=0.` before the LSTM layer:"}],"package":"tensorflow.keras.layers"}},{"name":"Dense","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","type":"boolean"},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"}],"category":"Layer","description":"Just your regular densely-connected NN layer.\n\n`Dense` implements the operation:\n`output = activation(dot(input, kernel) + bias)`\nwhere `activation` is the element-wise activation function\npassed as the `activation` argument, `kernel` is a weights matrix\ncreated by the layer, and `bias` is a bias vector created by the layer\n(only applicable if `use_bias` is `True`).\n\nNote: If the input to the layer has a rank greater than 2, then `Dense`\ncomputes the dot product between the `inputs` and the `kernel` along the\nlast axis of the `inputs` and axis 1 of the `kernel` (using `tf.tensordot`).\nFor example, if input has dimensions `(batch_size, d0, d1)`,\nthen we create a `kernel` with shape `(d1, units)`, and the `kernel` operates\nalong axis 2 of the `input`, on every sub-tensor of shape `(1, 1, d1)`\n(there are `batch_size * d0` such sub-tensors).\nThe output in this case will have shape `(batch_size, d0, units)`.\n\nBesides, layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":">>> # Create a `Sequential` model and add a Dense layer as the first layer.\n>>> model = tf.keras.models.Sequential()\n>>> model.add(tf.keras.Input(shape=(16,)))\n>>> model.add(tf.keras.layers.Dense(32, activation='relu'))\n>>> # Now the model will take as input arrays of shape (None, 16)\n>>> # and output arrays of shape (None, 32).\n>>> # Note that after the first layer, you don't need to specify\n>>> # the size of the input anymore:\n>>> model.add(tf.keras.layers.Dense(32))\n>>> model.output_shape\n(None, 32)"}],"inputs":[{"description":"N-D tensor with shape: `(batch_size, ..., input_dim)`.\nThe most common situation would be\na 2D input with shape `(batch_size, input_dim)`.","name":"input","type":"T"},{"name":"kernel","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"description":"N-D tensor with shape: `(batch_size, ..., units)`.\nFor instance, for a 2D input with shape `(batch_size, input_dim)`,\nthe output would have shape `(batch_size, units)`.","name":"output","type":"T"}],"package":"tensorflow.keras.layers"}},{"name":"LocallyConnected1D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.","name":"kernel_size"},{"description":"An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"Currently only supports `\"valid\"` (case-insensitive).\n `\"same\"` may be supported in the future.\n `\"valid\"` means no padding.","name":"padding"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias"},{"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\")..","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, length)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"implementation mode, either `1`, `2`, or `3`.\n `1` loops over input spatial locations to perform the forward pass.\n It is memory-efficient but performs a lot of (small) ops.\n\n `2` stores layer weights in a dense but sparsely-populated 2D matrix\n and implements the forward pass as a single matrix-multiply. It uses\n a lot of RAM but performs few (large) ops.\n\n `3` stores layer weights in a sparse tensor and implements the forward\n pass as a single sparse matrix-multiply.\n\n How to choose:\n\n `1`: large, dense models,\n `2`: small models,\n `3`: large, sparse models,\n\n where \"large\" stands for large input/output activations\n (i.e. many `filters`, `input_filters`, large `input_size`,\n `output_size`), and \"sparse\" stands for few connections between inputs\n and outputs, i.e. small ratio\n `filters * input_filters * kernel_size / (input_size * strides)`,\n where inputs to and outputs of the layer are assumed to have shapes\n `(input_size, input_filters)`, `(output_size, filters)`\n respectively.\n\n It is recommended to benchmark each in the setting of interest to pick\n the most efficient one (in terms of speed and memory usage). Correct\n choice of implementation can lead to dramatic speed improvements (e.g.\n 50X), potentially at the expense of RAM.\n\n Also, only `padding=\"valid\"` is supported by `implementation=1`.","name":"implementation"}],"category":"Layer","description":"Locally-connected layer for 1D inputs.\n\nThe `LocallyConnected1D` layer works similarly to\nthe `Conv1D` layer, except that weights are unshared,\nthat is, a different set of filters is applied at each different patch\nof the input.\n\nNote: layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":" # apply a unshared weight convolution 1d of length 3 to a sequence with\n # 10 timesteps, with 64 output filters\n model = Sequential()\n model.add(LocallyConnected1D(64, 3, input_shape=(10, 32)))\n # now model.output_shape == (None, 8, 64)\n # add a new conv1d on top\n model.add(LocallyConnected1D(32, 3))\n # now model.output_shape == (None, 6, 32)"}],"inputs":[{"description":"3D tensor with shape: `(batch_size, steps, input_dim)`","name":"input"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, new_steps, filters)`\n`steps` value might have changed due to padding or strides.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LocallyConnected2D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"strides"},{"description":"Currently only support `\"valid\"` (case-insensitive).\n `\"same\"` will be supported in future.\n `\"valid\"` means no padding.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix.","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").","name":"activity_regularizer"},{"description":"Constraint function applied to the kernel matrix.","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint"},{"description":"implementation mode, either `1`, `2`, or `3`.\n `1` loops over input spatial locations to perform the forward pass.\n It is memory-efficient but performs a lot of (small) ops.\n\n `2` stores layer weights in a dense but sparsely-populated 2D matrix\n and implements the forward pass as a single matrix-multiply. It uses\n a lot of RAM but performs few (large) ops.\n\n `3` stores layer weights in a sparse tensor and implements the forward\n pass as a single sparse matrix-multiply.\n\n How to choose:\n\n `1`: large, dense models,\n `2`: small models,\n `3`: large, sparse models,\n\n where \"large\" stands for large input/output activations\n (i.e. many `filters`, `input_filters`, large `np.prod(input_size)`,\n `np.prod(output_size)`), and \"sparse\" stands for few connections\n between inputs and outputs, i.e. small ratio\n `filters * input_filters * np.prod(kernel_size) / (np.prod(input_size)\n * np.prod(strides))`, where inputs to and outputs of the layer are\n assumed to have shapes `input_size + (input_filters,)`,\n `output_size + (filters,)` respectively.\n\n It is recommended to benchmark each in the setting of interest to pick\n the most efficient one (in terms of speed and memory usage). Correct\n choice of implementation can lead to dramatic speed improvements (e.g.\n 50X), potentially at the expense of RAM.\n\n Also, only `padding=\"valid\"` is supported by `implementation=1`.","name":"implementation"}],"category":"Layer","description":"Locally-connected layer for 2D inputs.\n\nThe `LocallyConnected2D` layer works similarly\nto the `Conv2D` layer, except that weights are unshared,\nthat is, a different set of filters is applied at each\ndifferent patch of the input.\n\nNote: layer attributes cannot be modified after the layer has been called\nonce (except the `trainable` attribute).","examples":[{"code":" # apply a 3x3 unshared weights convolution with 64 output filters on a\n 32x32 image\n # with `data_format=\"channels_last\"`:\n model = Sequential()\n model.add(LocallyConnected2D(64, (3, 3), input_shape=(32, 32, 3)))\n # now model.output_shape == (None, 30, 30, 64)\n # notice that this layer will consume (30*30)*(3*3*3*64) + (30*30)*64\n parameters\n\n # add a 3x3 unshared weights convolution on top, with 32 output filters:\n model.add(LocallyConnected2D(32, (3, 3)))\n # now model.output_shape == (None, 28, 28, 32)"}],"inputs":[{"description":"4D tensor with shape:\n`(samples, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(samples, rows, cols, channels)` if data_format='channels_last'.","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n`(samples, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(samples, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"LSTM","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":"hard_sigmoid","description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"description":"Boolean (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix, used for\n the linear transformation of the inputs. Default: `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel` weights\n matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":true,"description":"Boolean (default `True`). If True, add 1 to the bias of\n the forget gate at initialization. Setting it to true will also force\n `bias_initializer=\"zeros\"`. This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).","name":"unit_forget_bias"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint","visible":false},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint","visible":false},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"default":1,"description":"Implementation mode, either 1 or 2. Mode 1 will structure\n its operations as a larger number of smaller dot products and additions,\n whereas mode 2 will batch them into fewer, larger operations. These modes\n will have different performance profiles on different hardware and for\n different applications. Default: 2.","name":"implementation"},{"default":false,"description":"Boolean. Whether to return the last output. in the output\n sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state in addition to the\n output. Default: `False`.","name":"return_state"},{"default":false,"description":"Boolean (default `False`). If True, process the input sequence\n backwards and return the reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default `False`). If True, the last state for each sample\n at index i in a batch will be used as initial state for the sample of\n index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default `False`). If True, the network will be unrolled,\n else a symbolic loop will be used. Unrolling can speed-up a RNN, although\n it tends to be more memory-intensive. Unrolling is only suitable for short\n sequences.","name":"unroll"},{"description":"`orthogonal`.","name":"Default"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `[timesteps, batch, feature]`, whereas in the False case, it will be\n `[batch, timesteps, feature]`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"}],"category":"Layer","description":"Long Short-Term Memory layer - Hochreiter 1997.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nBased on available runtime hardware and constraints, this layer\nwill choose different implementations (cuDNN-based or pure-TensorFlow)\nto maximize the performance. If a GPU is available and all\nthe arguments to the layer meet the requirement of the CuDNN kernel\n(see below for details), the layer will use a fast cuDNN implementation.\n\nThe requirements to use the cuDNN implementation are:\n\n1. `activation` == `tanh`\n2. `recurrent_activation` == `sigmoid`\n3. `recurrent_dropout` == 0\n4. `unroll` is `False`\n5. `use_bias` is `True`\n6. Inputs, if use masking, are strictly right-padded.\n7. Eager execution is enabled in the outermost context.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> lstm = tf.keras.layers.LSTM(4)\n>>> output = lstm(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> lstm = tf.keras.layers.LSTM(4, return_sequences=True, return_state=True)\n>>> whole_seq_output, final_memory_state, final_carry_state = lstm(inputs)\n>>> print(whole_seq_output.shape)\n(32, 10, 4)\n>>> print(final_memory_state.shape)\n(32, 4)\n>>> print(final_carry_state.shape)\n(32, 4)\n```","inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Long short-term memory](http://www.bioinf.jku.at/publications/older/2604.pdf)"},{"description":"[Learning to forget: Continual prediction with LSTM](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015)"},{"description":"[Supervised sequence labeling with recurrent neural networks](http://www.cs.toronto.edu/~graves/preprint.pdf)"},{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](https://arxiv.org/abs/1512.05287)"}]}},{"name":"GRU","schema":{"attributes":[{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":"hard_sigmoid","description":"Activation function to use\n for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Orthogonal","config":{"gain":1,"seed":null}},"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent\n state. Default: `orthogonal`.","name":"recurrent_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":1,"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications. Default: 2.","name":"implementation"},{"default":false,"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state in addition to the\n output. Default: `False`.","name":"return_state"},{"default":false,"description":"Boolean (default `False`).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.","name":"unroll"},{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"sigmoid (`sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"Default"},{"description":"GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\",\n True = \"after\" (default and CuDNN compatible).","name":"reset_after"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `[timesteps, batch, feature]`, whereas in the False case, it will be\n `[batch, timesteps, feature]`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"}],"category":"Layer","description":"Gated Recurrent Unit - Cho et al. 2014.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nBased on available runtime hardware and constraints, this layer\nwill choose different implementations (cuDNN-based or pure-TensorFlow)\nto maximize the performance. If a GPU is available and all\nthe arguments to the layer meet the requirement of the CuDNN kernel\n(see below for details), the layer will use a fast cuDNN implementation.\n\nThe requirements to use the cuDNN implementation are:\n\n1. `activation` == `tanh`\n2. `recurrent_activation` == `sigmoid`\n3. `recurrent_dropout` == 0\n4. `unroll` is `False`\n5. `use_bias` is `True`\n6. `reset_after` is `True`\n7. Inputs, if use masking, are strictly right-padded.\n8. Eager execution is enabled in the outermost context.\n\nThere are two variants of the GRU implementation. The default one is based on\n[v3](https://arxiv.org/abs/1406.1078v3) and has reset gate applied to hidden\nstate before matrix multiplication. The other one is based on\n[original](https://arxiv.org/abs/1406.1078v1) and has the order reversed.\n\nThe second variant is compatible with CuDNNGRU (GPU-only) and allows\ninference on CPU. Thus it has separate biases for `kernel` and\n`recurrent_kernel`. To use this variant, set `'reset_after'=True` and\n`recurrent_activation='sigmoid'`.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> gru = tf.keras.layers.GRU(4)\n>>> output = gru(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> gru = tf.keras.layers.GRU(4, return_sequences=True, return_state=True)\n>>> whole_sequence_output, final_state = gru(inputs)\n>>> print(whole_sequence_output.shape)\n(32, 10, 4)\n>>> print(final_state.shape)\n(32, 4)\n```","inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation](https://arxiv.org/abs/1406.1078)"},{"description":"[On the Properties of Neural Machine Translation: Encoder-Decoder Approaches](https://arxiv.org/abs/1409.1259)"},{"description":"[Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling](https://arxiv.org/abs/1412.3555v1)"},{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](https://arxiv.org/abs/1512.05287)"}]}},{"name":"ConvLSTM2D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of n integers, specifying the\n dimensions of the convolution window.","name":"kernel_size"},{"description":"An integer or tuple/list of n integers,\n specifying the strides of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"One of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, time, ..., channels)`\n while `channels_first` corresponds to\n inputs with shape `(batch, time, channels, ...)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"An integer or tuple/list of n integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"description":"Activation function to use.\n By default hyperbolic tangent activation function is applied\n (`tanh(x)`).","name":"activation"},{"description":"Activation function to use\n for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector.","name":"bias_initializer","visible":false},{"description":"Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Use in combination with `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et al., 2015](\n http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)","name":"unit_forget_bias"},{"description":"Regularizer function applied to\n the `kernel` weights matrix.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix.","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix.","name":"recurrent_constraint","visible":false},{"description":"Constraint function applied to the bias vector.","name":"bias_constraint","visible":false},{"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. (default False)","name":"return_sequences"},{"description":"Boolean (default False).\n If True, process the input sequence backwards.","name":"go_backwards"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.","name":"dropout"},{"description":"Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.","name":"recurrent_dropout"},{"description":"Boolean Whether to return the last state\n in addition to the output. (default False)","name":"return_state"}],"description":"Convolutional LSTM.\n\nIt is similar to an LSTM layer, but the input transformations\nand recurrent transformations are both convolutional.","inputs":[{"description":"- If data_format='channels_first'\n 5D tensor with shape:\n `(samples, time, channels, rows, cols)`\n- If data_format='channels_last'\n 5D tensor with shape:\n `(samples, time, rows, cols, channels)`","name":"input"}],"outputs":[{"description":"- If `return_state`: a list of tensors. The first tensor is\n the output. The remaining tensors are the last states,\n each 4D tensor with shape:\n `(samples, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, new_rows, new_cols, filters)`\n if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n- If `return_sequences`: 5D tensor with shape:\n `(samples, timesteps, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 5D tensor with shape:\n `(samples, timesteps, new_rows, new_cols, filters)`\n if data_format='channels_last'.\n- Else, 4D tensor with shape:\n `(samples, filters, new_rows, new_cols)`\n if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, new_rows, new_cols, filters)`\n if data_format='channels_last'.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) (the current implementation does not include the feedback loop on the cells output)."}]}},{"name":"CuDNNGRU","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n (see [initializers](https://keras.io/initializers)).","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n (see [initializers](https://keras.io/initializers)).","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector\n (see [initializers](https://keras.io/initializers)).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector\n (see [regularizer](https://keras.io/regularizers)).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the `kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"kernel_constraint"},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector\n (see [constraints](https://keras.io/constraints)).","name":"bias_constraint"},{"description":"Boolean. Whether to return the last output.\n in the output sequence, or the full sequence.","name":"return_sequences"},{"description":"Boolean. Whether to return the last state\n in addition to the output.","name":"return_state"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n","name":"stateful"}],"description":"Fast GRU implementation backed by [CuDNN](https://developer.nvidia.com/cudnn).\n\nCan only be run on GPU, with the TensorFlow backend.\n"}},{"name":"CuDNNLSTM","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n (see [initializers](https://keras.io/initializers)).","name":"kernel_initializer"},{"description":"Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n (see [initializers](https://keras.io/initializers)).","name":"recurrent_initializer"},{"description":"Initializer for the bias vector\n (see [initializers](https://keras.io/initializers)).","name":"bias_initializer"},{"description":"Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Setting it to true will also force `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et al. (2015)](\n http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).","name":"unit_forget_bias"},{"description":"Regularizer function applied to\n the `kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"kernel_regularizer"},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix\n (see [regularizer](https://keras.io/regularizers)).","name":"recurrent_regularizer"},{"description":"Regularizer function applied to the bias vector\n (see [regularizer](https://keras.io/regularizers)).","name":"bias_regularizer"},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer"},{"description":"Constraint function applied to\n the `kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"kernel_constraint"},{"description":"Constraint function applied to\n the `recurrent_kernel` weights matrix\n (see [constraints](https://keras.io/constraints)).","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector\n (see [constraints](https://keras.io/constraints)).","name":"bias_constraint"},{"description":"Boolean. Whether to return the last output.\n in the output sequence, or the full sequence.","name":"return_sequences"},{"description":"Boolean. Whether to return the last state\n in addition to the output.","name":"return_state"},{"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n","name":"stateful"}],"description":"Fast LSTM implementation with [CuDNN](https://developer.nvidia.com/cudnn).\n\nCan only be run on GPU, with the TensorFlow backend.\n"}},{"name":"SimpleRNN","schema":{"attributes":[{"default":false,"description":"Boolean. Whether to return the last output\n in the output sequence, or the full sequence. Default: `False`.","name":"return_sequences"},{"default":false,"description":"Boolean. Whether to return the last state\n in addition to the output. Default: `False`","name":"return_state"},{"default":false,"description":"Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.","name":"unroll"},{"default":"tanh","description":"Activation function to use.","name":"activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"default":{"class_name":"Orthogonal","config":{"gain":1,"seed":null}},"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for the linear transformation of the inputs.","name":"dropout"},{"default":0,"description":"Float between 0 and 1.\n Fraction of the units to drop for the linear transformation of the\n recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\"). Default: `None`.","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"description":"0.","name":"Default"}],"category":"Layer","description":"Fully-connected RNN where the output is to be fed back to input.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.","examples":[{"code":"inputs = np.random.random([32, 10, 8]).astype(np.float32)\nsimple_rnn = tf.keras.layers.SimpleRNN(4)\n\noutput = simple_rnn(inputs) # The output has shape `[32, 4]`.\n\nsimple_rnn = tf.keras.layers.SimpleRNN(\n 4, return_sequences=True, return_state=True)\n\n# whole_sequence_output has shape `[32, 10, 4]`.\n# final_state has shape `[32, 4]`.\nwhole_sequence_output, final_state = simple_rnn(inputs)"}],"inputs":[{"name":"input"},{"name":"kernel"},{"name":"recurrent_kernel"},{"name":"bias"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"RNN","schema":{"attributes":[{"default":false,"description":"Boolean (default `False`). Whether to return the last\n output in the output sequence, or the full sequence.","name":"return_sequences"},{"default":false,"description":"Boolean (default `False`). Whether to return the last state\n in addition to the output.","name":"return_state"},{"default":false,"description":"Boolean (default `False`).\n If True, process the input sequence backwards and return the\n reversed sequence.","name":"go_backwards"},{"default":false,"description":"Boolean (default `False`). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.","name":"stateful"},{"default":false,"description":"Boolean (default `False`).\n If True, the network will be unrolled, else a symbolic loop will be used.\n Unrolling can speed-up a RNN, although it tends to be more\n memory-intensive. Unrolling is only suitable for short sequences.","name":"unroll"},{"description":"A RNN cell instance or a list of RNN cell instances.\n A RNN cell is a class that has:\n - A `call(input_at_t, states_at_t)` method, returning\n `(output_at_t, states_at_t_plus_1)`. The call method of the\n cell can also take the optional argument `constants`, see\n section \"Note on passing external constants\" below.\n - A `state_size` attribute. This can be a single integer\n (single state) in which case it is the size of the recurrent\n state. This can also be a list/tuple of integers (one size per state).\n The `state_size` can also be TensorShape or tuple/list of\n TensorShape, to represent high dimension state.\n - A `output_size` attribute. This can be a single integer or a\n TensorShape, which represent the shape of the output. For backward\n compatible reason, if this attribute is not available for the\n cell, the value will be inferred by the first element of the\n `state_size`.\n - A `get_initial_state(inputs=None, batch_size=None, dtype=None)`\n method that creates a tensor meant to be fed to `call()` as the\n initial state, if the user didn't specify any initial state via other\n means. The returned initial state should have a shape of\n [batch_size, cell.state_size]. The cell might choose to create a\n tensor full of zeros, or full of other values based on the cell's\n implementation.\n `inputs` is the input tensor to the RNN layer, which should\n contain the batch size as its shape[0], and also dtype. Note that\n the shape[0] might be `None` during the graph construction. Either\n the `inputs` or the pair of `batch_size` and `dtype` are provided.\n `batch_size` is a scalar tensor that represents the batch size\n of the inputs. `dtype` is `tf.DType` that represents the dtype of\n the inputs.\n For backward compatible reason, if this method is not implemented\n by the cell, the RNN layer will create a zero filled tensor with the\n size of [batch_size, cell.state_size].\n In the case that `cell` is a list of RNN cell instances, the cells\n will be stacked on top of each other in the RNN, resulting in an\n efficient stacked RNN.","name":"cell"},{"description":"dimensionality of the input (integer).\n This argument (or alternatively,\n the keyword argument `input_shape`)\n is required when using this layer as the first layer in a model.","name":"input_dim"},{"description":"Length of input sequences, to be specified\n when it is constant.\n This argument is required if you are going to connect\n `Flatten` then `Dense` layers upstream\n (without it, the shape of the dense outputs cannot be computed).\n Note that if the recurrent layer is not the first layer\n in your model, you would need to specify the input length\n at the level of the first layer\n (e.g. via the `input_shape` argument)\n","name":"input_length"},{"description":"The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `(timesteps, batch, ...)`, whereas in the False case, it will be\n `(batch, timesteps, ...)`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.","name":"time_major"},{"description":"Boolean (default `False`).\n Whether the output should use zeros for the masked timesteps. Note that\n this field is only used when `return_sequences` is True and mask is\n provided. It can useful if you want to reuse the raw output sequence of\n the RNN without interference from the masked timesteps, eg, merging\n bidirectional RNNs.","name":"zero_output_for_mask"}],"category":"Layer","description":"Base class for recurrent layers.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.","examples":[{"code":"# First, let's define a RNN Cell, as a layer subclass.\n\nclass MinimalRNNCell(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(MinimalRNNCell, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.built = True\n\n def call(self, inputs, states):\n prev_output = states[0]\n h = K.dot(inputs, self.kernel)\n output = h + K.dot(prev_output, self.recurrent_kernel)\n return output, [output]\n\n# Let's use this cell in a RNN layer:\n\ncell = MinimalRNNCell(32)\nx = keras.Input((None, 5))\nlayer = RNN(cell)\ny = layer(x)\n\n# Here's how to use the cell to build a stacked RNN:\n\ncells = [MinimalRNNCell(32), MinimalRNNCell(64)]\nx = keras.Input((None, 5))\nlayer = RNN(cells)\ny = layer(x)"}],"inputs":[{"description":"N-D tensor with shape `[batch_size, timesteps, ...]` or\n`[timesteps, batch_size, ...]` when time_major is True.","name":"input"}],"outputs":[{"description":"- If `return_state`: a list of tensors. The first tensor is\n the output. The remaining tensors are the last states,\n each with shape `[batch_size, state_size]`, where `state_size` could\n be a high dimension tensor shape.\n - If `return_sequences`: N-D tensor with shape\n `[batch_size, timesteps, output_size]`, where `output_size` could\n be a high dimension tensor shape, or\n `[timesteps, batch_size, output_size]` when `time_major` is True.\n - Else, N-D tensor with shape `[batch_size, output_size]`, where\n `output_size` could be a high dimension tensor shape.\n\nMasking:\n This layer supports masking for input data with a variable number\n of timesteps. To introduce masks to your data,\n use an [tf.keras.layers.Embedding] layer with the `mask_zero` parameter\n set to `True`.\n\nNote on using statefulness in RNNs:\n You can set RNN layers to be 'stateful', which means that the states\n computed for the samples in one batch will be reused as initial states\n for the samples in the next batch. This assumes a one-to-one mapping\n between samples in different successive batches.\n\n To enable statefulness:\n - Specify `stateful=True` in the layer constructor.\n - Specify a fixed batch size for your model, by passing\n If sequential model:\n `batch_input_shape=(...)` to the first layer in your model.\n Else for functional model with 1 or more Input layers:\n `batch_shape=(...)` to all the first layers in your model.\n This is the expected shape of your inputs\n *including the batch size*.\n It should be a tuple of integers, e.g. `(32, 10, 100)`.\n - Specify `shuffle=False` when calling `fit()`.\n\n To reset the states of your model, call `.reset_states()` on either\n a specific layer, or on your entire model.\n\nNote on specifying the initial state of RNNs:\n You can specify the initial state of RNN layers symbolically by\n calling them with the keyword argument `initial_state`. The value of\n `initial_state` should be a tensor or list of tensors representing\n the initial state of the RNN layer.\n\n You can specify the initial state of RNN layers numerically by\n calling `reset_states` with the keyword argument `states`. The value of\n `states` should be a numpy array or list of numpy arrays representing\n the initial state of the RNN layer.\n\nNote on passing external constants to RNNs:\n You can pass \"external\" constants to the cell using the `constants`\n keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This\n requires that the `cell.call` method accepts the same keyword argument\n `constants`. Such constants can be used to condition the cell\n transformation on additional static inputs (not changing over time),\n a.k.a. an attention mechanism.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"SimpleRNNCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Activation function to use.","name":"activation"},{"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"`orthogonal`.","name":"Default"}],"description":"Cell class for SimpleRNN.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.SimpleRNN` processes the whole sequence.","examples":[{"code":"inputs = np.random.random([32, 10, 8]).astype(np.float32)\nrnn = tf.keras.layers.RNN(tf.keras.layers.SimpleRNNCell(4))\n\noutput = rnn(inputs) # The output has shape `[32, 4]`.\n\nrnn = tf.keras.layers.RNN(\n tf.keras.layers.SimpleRNNCell(4),\n return_sequences=True,\n return_state=True)\n\n# whole_sequence_output has shape `[32, 10, 4]`.\n# final_state has shape `[32, 4]`.\nwhole_sequence_output, final_state = rnn(inputs)"}],"package":"tensorflow.keras.layers"}},{"name":"GRUCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"Activation function to use. Default: hyperbolic tangent\n (`tanh`). If you pass None, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).","name":"activation"},{"description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs. Default:\n `glorot_uniform`.","name":"kernel_initializer","visible":false},{"description":"Initializer for the `recurrent_kernel`\n weights matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer","visible":false},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the\n `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer","visible":false},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the\n linear transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 (default) will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications. Default: 2.","name":"implementation"},{"description":"`orthogonal`.","name":"Default"},{"description":"GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\",\n True = \"after\" (default and CuDNN compatible).","name":"reset_after"}],"description":"Cell class for the GRU layer.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.GRU` processes the whole sequence.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> rnn = tf.keras.layers.RNN(tf.keras.layers.GRUCell(4))\n>>> output = rnn(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> rnn = tf.keras.layers.RNN(\n... tf.keras.layers.GRUCell(4),\n... return_sequences=True,\n... return_state=True)\n>>> whole_sequence_output, final_state = rnn(inputs)\n>>> print(whole_sequence_output.shape)\n(32, 10, 4)\n>>> print(final_state.shape)\n(32, 4)\n```","package":"tensorflow.keras.layers"}},{"name":"LSTMCell","schema":{"attributes":[{"description":"Positive integer, dimensionality of the output space.","name":"units"},{"description":"`a(x) = x`).","name":"activation"},{"description":"Activation function to use for the recurrent step.","name":"recurrent_activation"},{"default":true,"description":"Boolean, (default `True`), whether the layer uses a bias vector.","name":"use_bias"},{"description":"Initializer for the `kernel` weights matrix, used for\n the linear transformation of the inputs. Default: `glorot_uniform`.","name":"kernel_initializer"},{"description":"Initializer for the `recurrent_kernel` weights\n matrix, used for the linear transformation of the recurrent state.","name":"recurrent_initializer"},{"description":"Initializer for the bias vector. Default: `zeros`.","name":"bias_initializer"},{"description":"Boolean (default `True`). If True, add 1 to the bias of\n the forget gate at initialization. Setting it to true will also force\n `bias_initializer=\"zeros\"`. This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)","name":"unit_forget_bias"},{"description":"Regularizer function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_regularizer"},{"description":"Regularizer function applied to\n the `recurrent_kernel` weights matrix. Default: `None`.","name":"recurrent_regularizer"},{"description":"Regularizer function applied to the bias vector. Default:\n `None`.","name":"bias_regularizer"},{"description":"Constraint function applied to the `kernel` weights\n matrix. Default: `None`.","name":"kernel_constraint"},{"description":"Constraint function applied to the `recurrent_kernel`\n weights matrix. Default: `None`.","name":"recurrent_constraint"},{"description":"Constraint function applied to the bias vector. Default:\n `None`.","name":"bias_constraint"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs. Default: 0.","name":"dropout"},{"default":0,"description":"Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state. Default: 0.","name":"recurrent_dropout"},{"description":"Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of smaller dot\n products and additions, whereas mode 2 (default) will batch them into\n fewer, larger operations. These modes will have different performance\n profiles on different hardware and for different applications. Default: 2.","name":"implementation"},{"description":"`orthogonal`.","name":"Default"}],"description":"Cell class for the LSTM layer.\n\nSee [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)\nfor details about the usage of RNN API.\n\nThis class processes one step within the whole time sequence input, whereas\n`tf.keras.layer.LSTM` processes the whole sequence.\n\nFor example:\n\n```\n>>> inputs = tf.random.normal([32, 10, 8])\n>>> rnn = tf.keras.layers.RNN(tf.keras.layers.LSTMCell(4))\n>>> output = rnn(inputs)\n>>> print(output.shape)\n(32, 4)\n>>> rnn = tf.keras.layers.RNN(\n... tf.keras.layers.LSTMCell(4),\n... return_sequences=True,\n... return_state=True)\n>>> whole_seq_output, final_memory_state, final_carry_state = rnn(inputs)\n>>> print(whole_seq_output.shape)\n(32, 10, 4)\n>>> print(final_memory_state.shape)\n(32, 4)\n>>> print(final_carry_state.shape)\n(32, 4)\n```","package":"tensorflow.keras.layers"}},{"name":"StackedRNNCells","schema":{"attributes":[{"description":"List of RNN cell instances.","name":"cells"}],"description":"Wrapper allowing a stack of RNN cells to behave as a single cell.\n\nUsed to implement efficient stacked RNNs.","examples":[{"code":"batch_size = 3\nsentence_max_length = 5\nn_features = 2\nnew_shape = (batch_size, sentence_max_length, n_features)\nx = tf.constant(np.reshape(np.arange(30), new_shape), dtype = tf.float32)\n\nrnn_cells = [tf.keras.layers.LSTMCell(128) for _ in range(2)]\nstacked_lstm = tf.keras.layers.StackedRNNCells(rnn_cells)\nlstm_layer = tf.keras.layers.RNN(stacked_lstm)\n\nresult = lstm_layer(x)"}],"package":"tensorflow.keras.layers"}},{"name":"Conv1D","schema":{"attributes":[{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":"valid","description":"One of `\"valid\"`, `\"same\"` or `\"causal\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.\n `\"causal\"` results in causal (dilated) convolutions, e.g. `output[t]`\n does not depend on `input[t+1:]`. Useful when modeling temporal data\n where the model should not violate the temporal order.\n See [WaveNet: A Generative Model for Raw Audio, section\n 2.1](https://arxiv.org/abs/1609.03499).","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.","name":"data_format"},{"default":[1],"description":"An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"default":[1],"description":"an integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (\n see `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.","name":"kernel_size"},{"description":"Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (\n see `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved\n separately with `filters / groups` filters. The output is the\n concatenation of all the `groups` results along the channel axis.\n Input channels and `filters` must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"1D convolution layer (e.g. temporal convolution).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input over a single spatial (or temporal) dimension\nto produce a tensor of outputs.\nIf `use_bias` is True, a bias vector is created and added to the outputs.\nFinally, if `activation` is not `None`,\nit is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide an `input_shape` argument\n(tuple of integers or `None`, e.g.\n`(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,\nor `(None, 128)` for variable-length sequences of 128-dimensional vectors.","examples":[{"code":">>> # The inputs are 128-length vectors with 10 timesteps, and the batch size\n>>> # is 4.\n>>> input_shape = (4, 10, 128)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv1D(\n... 32, 3, activation='relu',input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 8, 32)"},{"code":">>> # With extended batch shape [4, 7] (e.g. weather data where batch\n>>> # dimensions correspond to spatial location and the third dimension\n>>> # corresponds to time.)\n>>> input_shape = (4, 7, 10, 128)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv1D(\n... 32, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 8, 32)"}],"inputs":[{"description":"3+D tensor with shape: `batch_shape + (steps, input_dim)`","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"3+D tensor with shape: `batch_shape + (new_steps, filters)`\n `steps` value might have changed due to padding or strides.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `(batch_size, height, width, channels)` while\n `channels_first` corresponds to inputs with shape `(batch_size, channels,\n height, width)`. It defaults to the `image_data_format` value found in\n your Keras config file at `~/.keras/keras.json`. If you never set it, then\n it will be `channels_last`.","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying the strides of\n the convolution along the height and width. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"an integer or tuple/list of 2 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the height\n and width of the 2D convolution window. Can be a single integer to specify\n the same value for all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint","visible":false},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint","visible":false},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"2D convolution layer (e.g. spatial convolution over images).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28 RGB images with `channels_last` and the batch\n>>> # size is 4.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 2)"},{"code":">>> # With `dilation_rate` as 2.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 24, 24, 2)"},{"code":">>> # With `padding` as \"same\".\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', padding=\"same\", input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 28, 28, 2)"},{"code":">>> # With extended batch shape [4, 7]:\n>>> input_shape = (4, 7, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 2)"}],"inputs":[{"description":"4+D tensor with shape: `batch_shape + (channels, rows, cols)` if\n `data_format='channels_first'`\nor 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if\n `data_format='channels_last'`.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if\n`data_format='channels_first'` or 4+D tensor with shape: `batch_shape +\n (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows`\n and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv3D","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 3 integers, specifying the depth,\n height and width of the 3D convolution window. Can be a single integer to\n specify the same value for all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 3 integers, specifying the strides of\n the convolution along each spatial dimension. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `batch_shape + (spatial_dim1, spatial_dim2,\n spatial_dim3, channels)` while `channels_first` corresponds to inputs with\n shape `batch_shape + (channels, spatial_dim1, spatial_dim2,\n spatial_dim3)`. It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`. If you never set it, then it\n will be \"channels_last\".","name":"data_format"},{"description":"an integer or tuple/list of 3 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"3D convolution layer (e.g. spatial convolution over volumes).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes\nwith a single channel,\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28x28 volumes with a single channel, and the\n>>> # batch size is 4\n>>> input_shape =(4, 28, 28, 28, 1)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv3D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 26, 2)"},{"code":">>> # With extended batch shape [4, 7], e.g. a batch of 4 videos of 3D frames,\n>>> # with 7 frames per video.\n>>> input_shape = (4, 7, 28, 28, 28, 1)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv3D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 26, 2)"}],"inputs":[{"description":"5+D tensor with shape: `batch_shape + (channels, conv_dim1, conv_dim2,\n conv_dim3)` if data_format='channels_first'\nor 5+D tensor with shape: `batch_shape + (conv_dim1, conv_dim2, conv_dim3,\n channels)` if data_format='channels_last'.","name":"input"}],"outputs":[{"description":"5+D tensor with shape: `batch_shape + (filters, new_conv_dim1,\n new_conv_dim2, new_conv_dim3)` if data_format='channels_first'\nor 5+D tensor with shape: `batch_shape + (new_conv_dim1, new_conv_dim2,\n new_conv_dim3, filters)` if data_format='channels_last'. `new_conv_dim1`,\n `new_conv_dim2` and `new_conv_dim3` values might have changed due to\n padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Conv2DTranspose","schema":{"attributes":[{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"description":"an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.","name":"dilation_rate"},{"description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (\n see `keras.initializers`).","name":"kernel_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"description":"Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (\n see `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"},{"description":"An integer or tuple/list of 2 integers,\n specifying the amount of padding along the height and width\n of the output tensor.\n Can be a single integer to specify the same value for all\n spatial dimensions.\n The amount of output padding along a given dimension must be\n lower than the stride along that same dimension.\n If set to `None` (default), the output shape is inferred.","name":"output_padding"}],"category":"Layer","description":"Transposed convolution layer (sometimes called Deconvolution).\n\nThe need for transposed convolutions generally arises\nfrom the desire to use a transformation going in the opposite direction\nof a normal convolution, i.e., from something that has the shape of the\noutput of some convolution to something that has the shape of its input\nwhile maintaining a connectivity pattern that is compatible with\nsaid convolution.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","inputs":[{"description":"4D tensor with shape:\n`(batch_size, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, rows, cols, channels)` if data_format='channels_last'.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4D tensor with shape:\n`(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.\nIf `output_padding` is specified:\n```\nnew_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] +\noutput_padding[0])\nnew_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] +\noutput_padding[1])\n```","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1)"},{"description":"[Deconvolutional Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf)"}]}},{"name":"Cropping1D","schema":{"attributes":[{"description":"Int or tuple of int (length 2)\n How many units should be trimmed off at the beginning and end of\n the cropping dimension (axis 1).\n If a single int is provided, the same value will be used for both.","name":"cropping"}],"category":"Shape","description":"Cropping layer for 1D input (e.g. temporal sequence).\n\nIt crops along the time dimension (axis 1).","examples":[{"code":">>> input_shape = (2, 3, 2)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> print(x)\n[[[ 0 1]\n [ 2 3]\n [ 4 5]]\n [[ 6 7]\n [ 8 9]\n [10 11]]]\n>>> y = tf.keras.layers.Cropping1D(cropping=1)(x)\n>>> print(y)\ntf.Tensor(\n [[[2 3]]\n [[8 9]]], shape=(2, 1, 2), dtype=int64)"}],"inputs":[{"description":"3D tensor with shape `(batch_size, axis_to_crop, features)`","name":"input"}],"outputs":[{"description":"3D tensor with shape `(batch_size, cropped_axis, features)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Cropping2D","schema":{"attributes":[{"description":"Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric cropping values for height and width:\n `(symmetric_height_crop, symmetric_width_crop)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_crop, bottom_crop), (left_crop, right_crop))`","name":"cropping"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Cropping layer for 2D input (e.g. picture).\n\nIt crops along spatial dimensions, i.e. height and width.","examples":[{"code":">>> input_shape = (2, 28, 28, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x)\n>>> print(y.shape)\n(2, 24, 20, 3)"}],"inputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`","name":"input"}],"outputs":[{"description":"4D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, cropped_rows, cropped_cols, channels)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, cropped_rows, cropped_cols)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Cropping3D","schema":{"attributes":[{"description":"Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to depth, height, and width.\n - If tuple of 3 ints: interpreted as two different\n symmetric cropping values for depth, height, and width:\n `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`.\n - If tuple of 3 tuples of 2 ints: interpreted as\n `((left_dim1_crop, right_dim1_crop), (left_dim2_crop,\n right_dim2_crop), (left_dim3_crop, right_dim3_crop))`","name":"cropping"},{"description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Cropping layer for 3D data (e.g. spatial or spatio-temporal).\n\n Examples:\n\n```\n>>> input_shape = (2, 28, 28, 10, 3)\n>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n>>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x)\n>>> print(y.shape)\n(2, 24, 20, 6, 3)\n```","inputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_crop, second_axis_to_crop,\n third_axis_to_crop)`","name":"input"}],"outputs":[{"description":"5D tensor with shape:\n- If `data_format` is `\"channels_last\"`:\n `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis,\n depth)`\n- If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_cropped_axis, second_cropped_axis,\n third_cropped_axis)`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"SeparableConv2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.","name":"dilation_rate"},{"default":1,"description":"The number of depthwise convolution output channels\n for each input channel.\n The total number of depthwise convolution output\n channels will be equal to `filters_in * depth_multiplier`.","name":"depth_multiplier"},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the pointwise kernel matrix (\n see `keras.initializers`).","name":"pointwise_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the depthwise kernel matrix (\n see `keras.initializers`).","name":"depthwise_initializer","visible":false},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (\n see `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to\n the depthwise kernel matrix (see `keras.regularizers`).","name":"depthwise_regularizer","visible":false},{"description":"Regularizer function applied to\n the pointwise kernel matrix (see `keras.regularizers`).","name":"pointwise_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (\n see `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to\n the depthwise kernel matrix (\n see `keras.constraints`).","name":"depthwise_constraint","visible":false},{"description":"Constraint function applied to\n the pointwise kernel matrix (\n see `keras.constraints`).","name":"pointwise_constraint"},{"description":"Constraint function applied to the bias vector (\n see `keras.constraints`).","name":"bias_constraint"}],"category":"Layer","description":"Depthwise separable 2D convolution.\n\nSeparable convolutions consist of first performing\na depthwise spatial convolution\n(which acts on each input channel separately)\nfollowed by a pointwise convolution which mixes the resulting\noutput channels. The `depth_multiplier` argument controls how many\noutput channels are generated per input channel in the depthwise step.\n\nIntuitively, separable convolutions can be understood as\na way to factorize a convolution kernel into two smaller kernels,\nor as an extreme version of an Inception block.","inputs":[{"description":"4D tensor with shape:\n`(batch_size, channels, rows, cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, rows, cols, channels)` if data_format='channels_last'.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4D tensor with shape:\n`(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\nor 4D tensor with shape:\n`(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n`rows` and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Convolution2D","schema":{"attributes":[{"default":"linear","description":"Activation function to use. If you don't specify anything, no\n activation is applied (see `keras.activations`).","name":"activation"},{"default":"valid","description":"one of `\"valid\"` or `\"same\"` (case-insensitive).\n `\"valid\"` means no padding. `\"same\"` results in padding evenly to \n the left/right or up/down of the input such that output has the same \n height/width dimension as the input.","name":"padding"},{"default":true,"description":"Boolean, whether the layer uses a bias vector.","name":"use_bias","visible":false},{"default":"channels_last","description":"A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs. `channels_last` corresponds\n to inputs with shape `(batch_size, height, width, channels)` while\n `channels_first` corresponds to inputs with shape `(batch_size, channels,\n height, width)`. It defaults to the `image_data_format` value found in\n your Keras config file at `~/.keras/keras.json`. If you never set it, then\n it will be `channels_last`.","name":"data_format"},{"default":[1,1],"description":"An integer or tuple/list of 2 integers, specifying the strides of\n the convolution along the height and width. Can be a single integer to\n specify the same value for all spatial dimensions. Specifying any stride\n value != 1 is incompatible with specifying any `dilation_rate` value != 1.","name":"strides"},{"default":[1,1],"description":"an integer or tuple/list of 2 integers, specifying the\n dilation rate to use for dilated convolution. Can be a single integer to\n specify the same value for all spatial dimensions. Currently, specifying\n any `dilation_rate` value != 1 is incompatible with specifying any stride\n value != 1.","name":"dilation_rate"},{"default":1,"name":"depth_multiplier"},{"default":{"class_name":"Zeros","config":{}},"description":"Initializer for the bias vector (see\n `keras.initializers`).","name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"description":"Initializer for the `kernel` weights matrix (see\n `keras.initializers`).","name":"kernel_initializer","visible":false},{"description":"Integer, the dimensionality of the output space (i.e. the number of\n output filters in the convolution).","name":"filters"},{"description":"An integer or tuple/list of 2 integers, specifying the height\n and width of the 2D convolution window. Can be a single integer to specify\n the same value for all spatial dimensions.","name":"kernel_size"},{"description":"Regularizer function applied to the `kernel` weights\n matrix (see `keras.regularizers`).","name":"kernel_regularizer","visible":false},{"description":"Regularizer function applied to the bias vector (see\n `keras.regularizers`).","name":"bias_regularizer","visible":false},{"description":"Regularizer function applied to the output of the\n layer (its \"activation\") (see `keras.regularizers`).","name":"activity_regularizer","visible":false},{"description":"Constraint function applied to the kernel matrix (see\n `keras.constraints`).","name":"kernel_constraint"},{"description":"Constraint function applied to the bias vector (see\n `keras.constraints`).","name":"bias_constraint"},{"description":"A positive integer specifying the number of groups in which the\n input is split along the channel axis. Each group is convolved separately\n with `filters / groups` filters. The output is the concatenation of all\n the `groups` results along the channel axis. Input channels and `filters`\n must both be divisible by `groups`.","name":"groups"}],"category":"Layer","description":"2D convolution layer (e.g. spatial convolution over images).\n\nThis layer creates a convolution kernel that is convolved\nwith the layer input to produce a tensor of\noutputs. If `use_bias` is True,\na bias vector is created and added to the outputs. Finally, if\n`activation` is not `None`, it is applied to the outputs as well.\n\nWhen using this layer as the first layer in a model,\nprovide the keyword argument `input_shape`\n(tuple of integers, does not include the sample axis),\ne.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\nin `data_format=\"channels_last\"`.","examples":[{"code":">>> # The inputs are 28x28 RGB images with `channels_last` and the batch\n>>> # size is 4.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 26, 26, 2)"},{"code":">>> # With `dilation_rate` as 2.\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 24, 24, 2)"},{"code":">>> # With `padding` as \"same\".\n>>> input_shape = (4, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', padding=\"same\", input_shape=input_shape[1:])(x)\n>>> print(y.shape)\n(4, 28, 28, 2)"},{"code":">>> # With extended batch shape [4, 7]:\n>>> input_shape = (4, 7, 28, 28, 3)\n>>> x = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Conv2D(\n... 2, 3, activation='relu', input_shape=input_shape[2:])(x)\n>>> print(y.shape)\n(4, 7, 26, 26, 2)"}],"inputs":[{"description":"4+D tensor with shape: `batch_shape + (channels, rows, cols)` if\n `data_format='channels_first'`\nor 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if\n `data_format='channels_last'`.","name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"description":"4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if\n`data_format='channels_first'` or 4+D tensor with shape: `batch_shape +\n (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows`\n and `cols` values might have changed due to padding.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"DepthwiseConv2D","schema":{"attributes":[{"default":"linear","name":"activation"},{"default":"valid","name":"padding"},{"default":true,"name":"use_bias","visible":false},{"default":"channels_last","name":"data_format"},{"default":[1,1],"name":"strides"},{"default":[1,1],"name":"dilation_rate"},{"default":{"class_name":"Zeros","config":{}},"name":"bias_initializer","visible":false},{"default":{"class_name":"VarianceScaling","config":{"distribution":"uniform","mode":"fan_avg","scale":1,"seed":null}},"name":"depthwise_initializer","visible":false},{"default":1,"name":"depth_multiplier"}],"category":"Layer","inputs":[{"name":"input"},{"name":"kernel"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"Concatenate","schema":{"attributes":[{"description":"Axis along which to concatenate.","name":"axis"},{"description":"standard layer keyword arguments.\n","name":"**kwargs"}],"category":"Tensor","description":"Layer that concatenates a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape except\nfor the concatenation axis, and returns a single tensor that is the\nconcatenation of all inputs.\n\n```\n>>> x = np.arange(20).reshape(2, 2, 5)\n>>> print(x)\n[[[ 0 1 2 3 4]\n [ 5 6 7 8 9]]\n [[10 11 12 13 14]\n [15 16 17 18 19]]]\n>>> y = np.arange(20, 30).reshape(2, 1, 5)\n>>> print(y)\n[[[20 21 22 23 24]]\n [[25 26 27 28 29]]]\n>>> tf.keras.layers.Concatenate(axis=1)([x, y])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> concatted = tf.keras.layers.Concatenate()([x1, x2])\n>>> concatted.shape\nTensorShape([5, 16])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Average","schema":{"category":"Tensor","description":"Layer that averages a list of inputs element-wise.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).","examples":[{"code":">>> x1 = np.ones((2, 2))\n>>> x2 = np.zeros((2, 2))\n>>> y = tf.keras.layers.Average()([x1, x2])\n>>> y.numpy().tolist()\n[[0.5, 0.5], [0.5, 0.5]]"},{"code":">>> input1 = tf.keras.layers.Input(shape=(16,))\n>>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1)\n>>> input2 = tf.keras.layers.Input(shape=(32,))\n>>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2)\n>>> avg = tf.keras.layers.Average()([x1, x2])\n>>> out = tf.keras.layers.Dense(4)(avg)\n>>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out)","summary":"Usage in a functional model:"}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Maximum","schema":{"category":"Tensor","description":"Layer that computes the maximum (element-wise) a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).\n\n```\n>>> tf.keras.layers.Maximum()([np.arange(5).reshape(5, 1),\n... np.arange(5, 10).reshape(5, 1)])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> maxed = tf.keras.layers.Maximum()([x1, x2])\n>>> maxed.shape\nTensorShape([5, 8])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Dot","schema":{"attributes":[{"description":"Integer or tuple of integers,\n axis or axes along which to take the dot product.","name":"axes"},{"description":"Whether to L2-normalize samples along the\n dot product axis before taking the dot product.\n If set to True, then the output of the dot product\n is the cosine proximity between the two samples.","name":"normalize"},{"description":"Standard layer keyword arguments.\n","name":"**kwargs"}],"description":"Layer that computes a dot product between samples in two tensors.\n\nE.g. if applied to a list of two tensors `a` and `b` of shape\n`(batch_size, n)`, the output will be a tensor of shape `(batch_size, 1)`\nwhere each entry `i` will be the dot product between\n`a[i]` and `b[i]`.\n\n```\n>>> x = np.arange(10).reshape(1, 5, 2)\n>>> print(x)\n[[[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]]\n>>> y = np.arange(10, 20).reshape(1, 2, 5)\n>>> print(y)\n[[[10 11 12 13 14]\n [15 16 17 18 19]]]\n>>> tf.keras.layers.Dot(axes=(1, 2))([x, y])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> dotted = tf.keras.layers.Dot(axes=1)([x1, x2])\n>>> dotted.shape\nTensorShape([5, 1])\n```","inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}],"package":"tensorflow.keras.layers"}},{"name":"Flatten","schema":{"attributes":[{"default":"channels_last","description":"A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, ..., channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, ...)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".","name":"data_format"}],"category":"Shape","description":"Flattens the input. Does not affect the batch size.\n\nNote: If inputs are shaped `(batch,)` without a feature axis, then\nflattening adds an extra channel dimension and output shape is `(batch, 1)`.","examples":[{"code":">>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Conv2D(64, 3, 3, input_shape=(3, 32, 32)))\n>>> model.output_shape\n(None, 1, 10, 64)"},{"code":">>> model.add(Flatten())\n>>> model.output_shape\n(None, 640)"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Reshape","schema":{"attributes":[{"description":"target shape. Tuple of integers.\n Does not include the batch axis.\n","name":"target_shape"}],"category":"Shape","description":"Layer that reshapes inputs into the given shape.","examples":[{"code":">>> # as first layer in a Sequential model\n>>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,)))\n>>> # model.output_shape == (None, 3, 4), `None` is the batch size.\n>>> model.output_shape\n(None, 3, 4)"},{"code":">>> # as intermediate layer in a Sequential model\n>>> model.add(tf.keras.layers.Reshape((6, 2)))\n>>> model.output_shape\n(None, 6, 2)"},{"code":">>> # also supports shape inference using `-1` as dimension\n>>> model.add(tf.keras.layers.Reshape((-1, 2, 2)))\n>>> model.output_shape\n(None, 3, 2, 2)"}],"inputs":[{"description":"Arbitrary, although all dimensions in the input shape must be known/fixed.\nUse the keyword argument `input_shape` (tuple of integers, does not include\nthe samples/batch size axis) when using this layer as the first layer\nin a model.","name":"input"}],"outputs":[{"description":"`(batch_size,) + target_shape`","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Permute","schema":{"attributes":[{"description":"Tuple of integers. Permutation pattern does not include the\n samples dimension. Indexing starts at 1.\n For instance, `(2, 1)` permutes the first and second dimensions\n of the input.","name":"dims"}],"category":"Shape","description":"Permutes the dimensions of the input according to a given pattern.\n\nUseful e.g. connecting RNNs and convnets.","examples":[{"code":"model = Sequential()\nmodel.add(Permute((2, 1), input_shape=(10, 64)))\n# now: model.output_shape == (None, 64, 10)\n# note: `None` is the batch dimension"}],"inputs":[{"description":"Arbitrary. Use the keyword argument `input_shape`\n(tuple of integers, does not include the samples axis)\nwhen using this layer as the first layer in a model.","name":"input"}],"outputs":[{"description":"Same as the input shape, but with the dimensions re-ordered according\nto the specified pattern.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"RepeatVector","schema":{"attributes":[{"description":"Integer, repetition factor.","name":"n"}],"category":"Shape","description":"Repeats the input n times.","examples":[{"code":"model = Sequential()\nmodel.add(Dense(32, input_dim=32))\n# now: model.output_shape == (None, 32)\n# note: `None` is the batch dimension\n\nmodel.add(RepeatVector(3))\n# now: model.output_shape == (None, 3, 32)"}],"inputs":[{"description":"2D tensor of shape `(num_samples, features)`.","name":"input"}],"outputs":[{"description":"3D tensor of shape `(num_samples, n, features)`.","name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Dropout","schema":{"attributes":[{"description":"Float between 0 and 1. Fraction of the input units to drop.","name":"rate"},{"description":"1D integer tensor representing the shape of the\n binary dropout mask that will be multiplied with the input.\n For instance, if your inputs have shape\n `(batch_size, timesteps, features)` and\n you want the dropout mask to be the same for all timesteps,\n you can use `noise_shape=(batch_size, 1, features)`.","name":"noise_shape"},{"description":"A Python integer to use as random seed.","name":"seed"}],"category":"Dropout","description":"Applies Dropout to the input.\n\nThe Dropout layer randomly sets input units to 0 with a frequency of `rate`\nat each step during training time, which helps prevent overfitting.\nInputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over\nall inputs is unchanged.\n\nNote that the Dropout layer only applies when `training` is set to True\nsuch that no values are dropped during inference. When using `model.fit`,\n`training` will be appropriately set to True automatically, and in other\ncontexts, you can set the kwarg explicitly to True when calling the layer.\n\n(This is in contrast to setting `trainable=False` for a Dropout layer.\n`trainable` does not affect the layer's behavior, as Dropout does\nnot have any variables/weights that can be frozen during training.)\n\n```\n>>> tf.random.set_seed(0)\n>>> layer = tf.keras.layers.Dropout(.2, input_shape=(2,))\n>>> data = np.arange(10).reshape(5, 2).astype(np.float32)\n>>> print(data)\n[[0. 1.]\n [2. 3.]\n [4. 5.]\n [6. 7.]\n [8. 9.]]\n>>> outputs = layer(data, training=True)\n>>> print(outputs)\ntf.Tensor(\n[[ 0. 1.25]\n [ 2.5 3.75]\n [ 5. 6.25]\n [ 7.5 8.75]\n [10. 0. ]], shape=(5, 2), dtype=float32)\n```","inputs":[{"name":"input"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[Dropout: A Simple Way to Prevent Neural Networks from Overfitting]( http://www.jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf)"}]}},{"name":"Embedding","schema":{"attributes":[{"default":false,"description":"Boolean, whether or not the input value 0 is a special \"padding\"\n value that should be masked out.\n This is useful when using recurrent layers\n which may take variable length input.\n If this is `True`, then all subsequent layers\n in the model need to support masking or an exception will be raised.\n If mask_zero is set to True, as a consequence, index 0 cannot be\n used in the vocabulary (input_dim should equal size of\n vocabulary + 1).","name":"mask_zero"},{"default":{"class_name":"RandomUniform","config":{"maxval":0.05,"minval":-0.05,"seed":null}},"description":"Initializer for the `embeddings`\n matrix (see `keras.initializers`).","name":"embeddings_initializer","visible":false},{"description":"Integer. Size of the vocabulary,\n i.e. maximum integer index + 1.","name":"input_dim"},{"description":"Integer. Dimension of the dense embedding.","name":"output_dim"},{"description":"Regularizer function applied to\n the `embeddings` matrix (see `keras.regularizers`).","name":"embeddings_regularizer","visible":false},{"description":"Constraint function applied to\n the `embeddings` matrix (see `keras.constraints`).","name":"embeddings_constraint"},{"description":"Length of input sequences, when it is constant.\n This argument is required if you are going to connect\n `Flatten` then `Dense` layers upstream\n (without it, the shape of the dense outputs cannot be computed).","name":"input_length"},{"description":"Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](https://keras.io/regularizers)).","name":"activity_regularizer"}],"category":"Transform","description":"Turns positive integers (indexes) into dense vectors of fixed size.\n\ne.g. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]`\n\nThis layer can only be used as the first layer in a model.","examples":[{"code":">>> model = tf.keras.Sequential()\n>>> model.add(tf.keras.layers.Embedding(1000, 64, input_length=10))\n>>> # The model will take as input an integer matrix of size (batch,\n>>> # input_length), and the largest integer (i.e. word index) in the input\n>>> # should be no larger than 999 (vocabulary size).\n>>> # Now model.output_shape is (None, 10, 64), where `None` is the batch\n>>> # dimension.\n>>> input_array = np.random.randint(1000, size=(32, 10))\n>>> model.compile('rmsprop', 'mse')\n>>> output_array = model.predict(input_array)\n>>> print(output_array.shape)\n(32, 10, 64)"}],"inputs":[{"description":"2D tensor with shape: `(batch_size, input_length)`.","name":"input"},{"name":"embeddings"}],"outputs":[{"description":"3D tensor with shape: `(batch_size, input_length, output_dim)`.","name":"output"}],"package":"tensorflow.keras.layers","references":[{"description":"[A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](http://arxiv.org/abs/1512.05287)"}]}},{"name":"Add","schema":{"description":"Layer that adds a list of inputs.\n\nIt takes as input a list of tensors,\nall of the same shape, and returns\na single tensor (also of the same shape).","examples":[{"code":">>> input_shape = (2, 3, 4)\n>>> x1 = tf.random.normal(input_shape)\n>>> x2 = tf.random.normal(input_shape)\n>>> y = tf.keras.layers.Add()([x1, x2])\n>>> print(y.shape)\n(2, 3, 4)"},{"code":">>> input1 = tf.keras.layers.Input(shape=(16,))\n>>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1)\n>>> input2 = tf.keras.layers.Input(shape=(32,))\n>>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2)\n>>> # equivalent to `added = tf.keras.layers.add([x1, x2])`\n>>> added = tf.keras.layers.Add()([x1, x2])\n>>> out = tf.keras.layers.Dense(4)(added)\n>>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out)","summary":"Used in a functional model:"}],"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Subtract","schema":{"description":"Layer that subtracts two inputs.\n\nIt takes as input a list of tensors of size 2,\nboth of the same shape, and returns a single tensor, (inputs[0] - inputs[1]),\nalso of the same shape.","examples":[{"code":" import keras\n\n input1 = keras.layers.Input(shape=(16,))\n x1 = keras.layers.Dense(8, activation='relu')(input1)\n input2 = keras.layers.Input(shape=(32,))\n x2 = keras.layers.Dense(8, activation='relu')(input2)\n # Equivalent to subtracted = keras.layers.subtract([x1, x2])\n subtracted = keras.layers.Subtract()([x1, x2])\n\n out = keras.layers.Dense(4)(subtracted)\n model = keras.models.Model(inputs=[input1, input2], outputs=out)"}],"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}],"package":"tensorflow.keras.layers"}},{"name":"Multiply","schema":{"description":"Layer that multiplies (element-wise) a list of inputs.\n\nIt takes as input a list of tensors, all of the same shape, and returns\na single tensor (also of the same shape).\n\n```\n>>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1),\n... np.arange(5, 10).reshape(5, 1)])\n\n```\n\n```\n>>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2))\n>>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2))\n>>> multiplied = tf.keras.layers.Multiply()([x1, x2])\n>>> multiplied.shape\nTensorShape([5, 8])\n```","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"package":"tensorflow.keras.layers"}},{"name":"Lambda","schema":{"attributes":[{"description":"The function to be evaluated. Takes input tensor as first\n argument.","name":"function"},{"description":"Expected output shape from function. This argument can be\n inferred if not explicitly provided. Can be a tuple or function. If a\n tuple, it only specifies the first dimension onward;\n sample dimension is assumed either the same as the input: `output_shape =\n (input_shape[0], ) + output_shape` or, the input is `None` and\n the sample dimension is also `None`: `output_shape = (None, ) +\n output_shape` If a function, it specifies the entire shape as a function\n of the\n input shape: `output_shape = f(input_shape)`","name":"output_shape"},{"description":"Optional dictionary of keyword arguments to be passed to the\n function.","name":"arguments"},{"description":"Either None (indicating no masking) or a callable with the same\n signature as the `compute_mask` layer method, or a tensor that will be\n returned as output mask regardless of what the input is.","name":"mask"}],"description":"Wraps arbitrary expressions as a `Layer` object.\n\nThe `Lambda` layer exists so that arbitrary TensorFlow functions\ncan be used when constructing `Sequential` and Functional API\nmodels. `Lambda` layers are best suited for simple operations or\nquick experimentation. For more advanced use cases, follow\n[this guide](https://www.tensorflow.org/guide/keras/custom_layers_and_models)\nfor subclassing `tf.keras.layers.Layer`.\n\nThe main reason to subclass `tf.keras.layers.Layer` instead of using a\n`Lambda` layer is saving and inspecting a Model. `Lambda` layers\nare saved by serializing the Python bytecode, whereas subclassed\nLayers can be saved via overriding their `get_config` method. Overriding\n`get_config` improves the portability of Models. Models that rely on\nsubclassed Layers are also often easier to visualize and reason about.","examples":[{"code":"# add a x -> x^2 layer\nmodel.add(Lambda(lambda x: x ** 2))"},{"code":"# add a layer that returns the concatenation\n# of the positive part of the input and\n# the opposite of the negative part\n\ndef antirectifier(x):\n x -= K.mean(x, axis=1, keepdims=True)\n x = K.l2_normalize(x, axis=1)\n pos = K.relu(x)\n neg = K.relu(-x)\n return K.concatenate([pos, neg], axis=1)\n\nmodel.add(Lambda(antirectifier))"}],"inputs":[{"description":"Arbitrary. Use the keyword argument input_shape (tuple of\nintegers, does not include the samples axis) when using this layer as the\nfirst layer in a model.","name":"inputs","option":"variadic"}],"outputs":[{"description":"Specified by `output_shape` argument","name":"output"}],"package":"tensorflow.keras.layers"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras.js new file mode 100644 index 0000000000000000000000000000000000000000..7bd57012b6d0b907187b3db8f5680c758c868d3d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/keras.js @@ -0,0 +1 @@ +var keras=keras||{},base=base||require("./base"),long=long||{Long:require("long")};keras.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("h5"===s||"hd5"===s||"hdf5"===s||"keras"===s||"model"===s||"pb"==s||"pth"==s){const e=t.buffer,s=[137,72,68,70,13,10,26,10];return e&&e.length>s.length&&s.every(((t,s)=>t===e[s]))}if("json"==s&&!e.endsWith("-symbol.json")){const e=t.text;if(-1==e.indexOf('"mxnet_version":',0))try{let t=keras.JsonParser.parse(e);if(t&&t.nodes&&t.arg_nodes&&t.heads)return!1;if(t&&t.modelTopology&&(t=t.modelTopology),t&&t.model_config&&(t=t.model_config),t&&t.class_name)return!0;if(t&&Array.isArray(t)&&t.every((t=>Array.isArray(t.weights)&&Array.isArray(t.paths))))return!0}catch(t){}}return!1}open(t,e){return e.require("./hdf5").then((s=>{let r="Keras",n="",i="",a=null,o=null;const h=t.identifier,u=new keras.Weights;try{switch(h.split(".").pop().toLowerCase()){case"keras":case"h5":case"hd5":case"hdf5":case"model":case"pb":case"pth":if(o=new s.File(t.buffer).rootGroup,o.attribute("model_config")||o.attribute("layer_names")){const t=o.attribute("model_config");t&&(a=keras.JsonParser.parse(t)),i=o.attribute("backend")||"";const e=o.attribute("keras_version")||"";r+=e?" v"+e:"";let s=o.group("model_weights");if(!s&&o.attribute("layer_names")&&(s=o),s){s=new keras.Group(s);for(const t of s.attribute("layer_names")){const e=s.group(t);if(e){const s=e.attribute("weight_names");if(s&&s.length>0)for(const r of s){const s=e.group(r);if(s&&s.value){const e=s.value,n=new keras.Tensor(r,e.type,e.shape,e.littleEndian,e.data,"");if(a)u.add(t,n);else{const e=r.split("/");e.pop();const s=0==e.length||e[0]!==t?[t].concat(e).join("/"):e.join("/");u.add(s,n)}}}}}}}else{const t=new Set(["nb_layers"]);if(0!==Object.keys(o.attributes).filter((e=>!t.has(e))).length||null!==o.value)throw new keras.Error("File format is not HDF5 Weights");if(r="HDF5 Weights",0===Object.keys(o.attributes).length&&null===o.value&&1==o.groups.length&&o.groups[0]&&0===Object.keys(o.groups[0].attributes).length&&null===o.groups[0].value&&(o=o.groups[0]),o.groups.every((t=>0===Object.keys(t.attributes).length&&0==t.groups.length&&null!==t.value)))for(const t of o.groups){const e=t.value,s=new keras.Tensor(t.name,e.type,e.shape,e.littleEndian,"string"===e.type?e.value:e.data);u.add("",s)}else if(o.groups.every((t=>0===Object.keys(t.attributes).length&&null===t.value)))for(const t of o.groups){const e=t.attributes.name||t.name;for(const s of t.groups){if(0!==Object.keys(s.attributes).length||0!==s.groups.length)throw new keras.Error("Group format is not HDF5 tensor variable.");const t=s.value;if(!t)throw new keras.Error("Variable value is not HDF5 tensor.");const r=e?[e,s.name].join("/"):e.name,n=new keras.Tensor(r,t.type,t.shape,t.littleEndian,"string"===t.type?t.value:t.data);u.add(e,n)}}else{if(!o.groups.every((t=>null===t.value&&t.groups.every((t=>0===Object.keys(t.attributes).length&&null!==t.value)))))throw new keras.Error("Module group format is not HDF5 Weights");for(const t of o.groups){const e=t.attributes.name||t.name;for(const s of t.groups){if(0!==Object.keys(s.attributes).length||0!==s.groups.length)throw new keras.Error("Variable format is not HDF5 Weights");const t=s.value;if(!t)throw new keras.Error("Variable value is not HDF5 Weights");const r=e?[e,s.name].join("/"):e.name,n=new keras.Tensor(r,t.type,t.shape,t.littleEndian,"string"===t.type?t.value:t.data);u.add(e,n)}}}}break;case"json":{const e=keras.JsonParser.parse(t.text);if(e&&Array.isArray(e)&&e.every((t=>Array.isArray(t.weights)&&Array.isArray(t.paths)))){r="TensorFlow.js Weights",o={};for(const t of e)for(const e of t.weights){const s=new keras.Tensor(e.name,e.dtype,e.shape,!1,null,t.paths.join(";")),r=e.name.split("/");r.pop();const n=r.join("/");u.add(n,s)}}else{if(e.keras_version){const t=e.keras_version;r+=t?" v"+t:""}if(e.backend&&(i=e.backend),a=e,a&&a.modelTopology){i=a.modelTopology.backend;const t=a.modelTopology.keras_version;r+=t?" v"+t:"",r="TensorFlow.js "+(a.format?a.format:r),n=a.convertedBy||a.generatedBy||"";for(const t of a.weightsManifest)for(const e of t.weights){const s=new keras.Tensor(e.name,e.dtype,e.shape,!1,null,t.paths.join(";"));u.add("",s)}a=a.modelTopology}a.model_config&&(a=a.model_config)}break}}}catch(t){const e=t&&t.message?t.message:t.toString();throw new keras.Error(e.replace(/\.$/,"")+" in '"+h+"'.")}if(!o&&!a)throw new keras.Error("'model_config' is not present.");if(!o&&!a.class_name)throw new keras.Error("'class_name' is not present.");return keras.Metadata.open(e).then((t=>{try{return new keras.Model(t,r,n,i,a,u)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new keras.Error(s.replace(/\.$/,"")+" in '"+h+"'.")}}))}))}},keras.Model=class{constructor(t,e,s,r,n,i){this._format=e,this._backend=r,this._producer=s,this._graphs=[new keras.Graph(t,n,i)]}get name(){return null}get description(){return null}get format(){return this._format}get producer(){return this._producer}get runtime(){return this._backend}get graphs(){return this._graphs}},keras.Graph=class{constructor(t,e,s){if(this._metadata=t,this._inputs=[],this._outputs=[],this._nodes=[],this._groups=!1,e)switch(this._name=e.name||(e.config&&e.config.name?e.config.name:""),e.class_name){case"AllCNN":case"Sequential":this._loadSequential(e.config,s,"",null,null);break;case"Functional":case"Model":this._loadModel(e.config,s,"",null,null);break;default:throw new keras.Error("'"+e.class_name+"' is not supported.")}else if(s)for(const e of s.keys())if(s.get("",e).length<=6){const r=new keras.Node(t,"Weights",{name:e},[],[],"",s);this._nodes.push(r)}}get name(){return this._name}get groups(){return!!this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}_loadModel(t,e,s,r,n){s&&(this._groups=!0);const i=new Map;if(t.layers){for(const e of t.layers)e.name&&(i.has(e.name)||(i.set(e.name,e),e._inputs=[],e._outputs=[]));for(const e of t.layers)if(e.inbound_nodes)for(const t of e.inbound_nodes)for(const s of t){let t=s[0];const r=i.get(t);if(r){const e=s[2];for(0!=e&&(t+=":"+e.toString());e>=r._outputs.length;)r._outputs.push("");r._outputs[e]=t}e._inputs.push(t)}}const a=t.input_layers;if(a)for(let e=0;et===s?r[e]:t)))}else this._inputs.push(new keras.Parameter(s,!0,[new keras.Argument(s,n,null)]))}const o=new Map,h=t.output_layers;if(h)for(let t=0;t=r._outputs.length;)r._outputs.push("");r._outputs[t]=s}a&&this._outputs.push(new keras.Parameter(s,!0,[new keras.Argument(s,null,null)]))}if(t.layers)for(const r of t.layers)i.has(r.name)&&this._loadNode(r,r._inputs,r._outputs,e,s,o)}_loadSequential(t,e,s,r,n){s&&(this._groups=!0);const i="input";let a=null,o=i,h=0;const u=t.layers?t.layers:t;for(const t of u){let i=h.toString(),l=[o];0==h&&(r&&r.length>0?l=[r[0]]:a=this._getInputType(t)),h++,t.config&&t.config.name&&(i=t.config.name),o=i;let c=[o];h==u.length&&n&&n.length>0&&(c=[n[0]],o=null),this._loadNode(t,l,c,e,s)}r||this._inputs.push(new keras.Parameter(i,!0,[new keras.Argument(i,a,null)])),o&&this._outputs.push(new keras.Parameter(o,!0,[new keras.Argument(o,null,null)]))}_loadNode(t,e,s,r,n,i){const a=t.class_name;switch(a){case"Sequential":{const i=t.name||(t.config?t.config.name:"");this._loadSequential(t.config,r,(n?n+"/":"")+i,e,s);break}case"Model":{const i=t.name||(t.config?t.config.name:"");this._loadModel(t.config,r,(n?n+"/":"")+i,e,s);break}default:{e=e.map((t=>i&&i.has(t)?i.get(t):t));const o=new keras.Node(this._metadata,a,t.config,e,s,n,r);this._nodes.push(o);break}}}_getInputType(t){if(t&&t.config){let e="?",s=[];const r=t.config;return r.dtype&&(e=r.dtype,delete r.dtype),r.batch_input_shape&&(s=r.batch_input_shape.map((t=>null==t?"?":t)),delete r.batch_input_shape),new keras.TensorType(e,new keras.TensorShape(s))}return null}},keras.Parameter=class{constructor(t,e,s){this._name=t,this._visible=e,this._arguments=s}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},keras.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new keras.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},keras.Node=class{constructor(t,e,s,r,n,i,a){this._group=i||"",this._metadata=t,this._type=e;const o=s&&s.name?s.name:"";this._name=(this._group?this._group+"/":"")+o,this._inputs=[],this._outputs=[],this._attributes=[];let h=[o];if(("Bidirectional"==e||"TimeDistributed"==e)&&s&&s.layer){const t=s.layer;delete s.layer,this._inner=new keras.Node(this._metadata,t.class_name,t.config,[],[],null,null),"Bidirectional"==e&&t.config.name&&(h=[o+"/forward_"+t.config.name,o+"/backward_"+t.config.name],i||(i=o))}const u={};if(a)for(const t of h)for(const e of a.get(i,t))r.push(e.name),u[e.name]=e;if(s)for(const e of Object.keys(s)){const r=s[e];"name"!=e&&null!=r&&this._attributes.push(new keras.Attribute(t.attribute(this.type,e),e,r))}const l=this._metadata.type(this.type),c=this.inner?this.inner.type:null,p=c?this._metadata.type(c):null;let _=0;for(;r.length>0;){let t=!1,n=null,i=!0;if(p&&0!=_)switch(e){case"Bidirectional":{let t=_;p&&p.inputs&&(tnew keras.Argument(t,null,u[t])));if(!n&&1==a.length&&a[0].initializer&&a[0].initializer.name)if(1===h.length&&""===h[0])n=a[0].initializer.name;else{const t=a[0].initializer.name.split("/").pop().split(":").shift().split("_"),e=t.pop(),s=t.length>0?[t.pop(),e].join("_"):"";n=new Set(["recurrent_kernel","running_mean","running_std","moving_mean","moving_variance","depthwise_filter","pointwise_filter"]).has(s)?s:e}this._inputs.push(new keras.Parameter(n||_.toString(),i,a)),_++}this._outputs=n.map(((t,e)=>{const s=l&&l.outputs&&et.limit)return r.push(null),r;switch(t.dataType){case"float16":r.push(t.data.getFloat16(t.index,i)),t.index+=2;break;case"float32":r.push(t.data.getFloat32(t.index,i)),t.index+=4;break;case"float64":r.push(t.data.getFloat64(t.index,i)),t.index+=8;break;case"boolean":r.push(0!==t.data.getInt8(t.index)),t.index+=1;break;case"uint8":r.push(t.data.getUint8(t.index)),t.index+=1;break;case"int64":r.push(new long.Long(t.data.getUint32(t.index+(i?0:4),i),t.data.getUint32(t.index+ +(i?4:0),i),!1)),t.index+=8;break;case"string":r.push(t.data[t.index]),t.index++}t.count++}else for(let s=0;st.limit)return r.push(null),r;r.push(this._decode(t,e+1))}return 0==t.shape.length?r[0]:r}static _stringify(t,e,s){if(Array.isArray(t)){const r=[];r.push(e+"[");const n=t.map((t=>keras.Tensor._stringify(t,e+s,s)));return n.length>0&&r.push(n.join(",\n")),r.push(e+"]"),r.join("\n")}return null===t?e+"...":"string"==typeof t?e+'"'+t+'"':t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},keras.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},keras.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},keras.Metadata=class{static open(t){return keras.Metadata._metadata?Promise.resolve(keras.Metadata._metadata):t.request(null,"keras-metadata.json","utf-8").then((t=>(keras.Metadata._metadata=new keras.Metadata(t),keras.Metadata._metadata))).catch((()=>(keras.Metadata._metadata=new keras.Metadata(null),keras.Metadata._metadatas)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema))}}type(t){return this._map.get(t)}attribute(t,e){const s=t+":"+e;if(!this._attributeCache.has(s)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const s of e.attributes)this._attributeCache.set(t+":"+s.name,s);this._attributeCache.has(s)||this._attributeCache.set(s,null)}return this._attributeCache.get(s)}},keras.Group=class{constructor(t){this._group=t}attribute(t){let e=this._group.attribute(t);if(!e&&this._group.attribute(t+"0")){let s=0;for(e=[];;){const r=this._group.attribute(t+s.toString());if(!r)break;e=e.concat(r),s++}}return e}group(t){const e=this._group.group(t);return e?new keras.Group(e):null}get value(){return this._group.value}},keras.JsonParser=class{static parse(t){if(t&&(-1!==t.indexOf("NaN")||-1!==t.indexOf("Infinity")))try{return JSON.parse(t)}catch(e){try{return new keras.JsonParser(t)._read()}catch(t){}}return JSON.parse(t)}constructor(t){this._text=t,this._position=0,this._ch=" ",this._escape={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"}}_read(){const t=this._value();return this._whitespace(),this._ch&&this._error("Syntax error"),t}_next(){return this._ch=this._text.charAt(this._position++)}_expect(t){for(let e=0;e="0"&&this._ch<="9";)t+=this._ch,this._next();if("."===this._ch)for(t+=".";this._next()&&this._ch>="0"&&this._ch<="9";)t+=this._ch;if("e"===this._ch||"E"===this._ch)for(t+=this._ch,this._next(),"-"!==this._ch&&"+"!==this._ch||(t+=this._ch,this._next());this._ch>="0"&&this._ch<="9";)t+=this._ch,this._next();return+t}_string(){let t,e,s,r="";if('"'===this._ch)for(;this._next();){if('"'===this._ch)return this._next(),r;if("\\"===this._ch)if(this._next(),"u"===this._ch){for(s=0,e=0;e<4&&(t=parseInt(this._next(),16),isFinite(t));e++)s=16*s+t;r+=String.fromCharCode(s)}else{if(!this._escape[this._ch])break;r+=this._escape[this._ch]}else r+=this._ch}this._error("Invalid string")}_literal(){switch(this._ch){case"t":return this._expect("true"),!0;case"f":return this._expect("false"),!1;case"n":return this._expect("null"),null;case"N":return this._expect("NaN"),NaN;case"I":return this._expect("Infinity"),1/0}this._error("Unexpected '"+this._ch+"'")}_array(){const t=[];if("["===this._ch){if(this._expect("["),this._whitespace(),"]"===this._ch)return this._expect("]"),t;for(;this._ch;){if(t.push(this._value()),this._whitespace(),"]"===this._ch)return this._expect("]"),t;this._expect(","),this._whitespace()}}this._error("Invalid array")}_object(){let t;const e={};if("{"===this._ch){if(this._expect("{"),this._whitespace(),"}"===this._ch)return this._expect("}"),e;for(;this._ch;){if(t=this._string(),this._whitespace(),this._expect(":"),Object.hasOwnProperty.call(e,t)&&this._error('Duplicate key "'+t+'"'),e[t]=this._value(),this._whitespace(),"}"===this._ch)return this._expect("}"),e;this._expect(","),this._whitespace()}}this._error("Invalid object")}_value(){switch(this._whitespace(),this._ch){case"{":return this._object();case"[":return this._array();case'"':return this._string();case"-":return this._number();default:return this._ch>="0"&&this._ch<="9"?this._number():this._literal()}}_error(t){throw new Error(t+" at "+this._position+".")}},keras.Weights=class{constructor(){this._map=new Map}add(t,e){this._map.has(t)||this._map.set(t,[]),this._map.get(t).push(e)}get(t,e){if(t){const s=this._map.get(t.split("/").shift());if(s){const r=s.filter((t=>t.name.startsWith(e+"/")));if(r.length>0)return r;const n=s.filter((s=>s.name.startsWith(t+"/"+e+"/")));if(n.length>0)return n}}else{const s=this._map.get(e);if(s&&s.length>0)return s;const r=this._map.get("");if(r&&r.length>0){const s=r.filter((s=>s.name.startsWith((t?t+"/":"")+e+"/")));if(s.length>0)return s}}return[]}keys(){return this._map.keys()}},keras.Error=class extends Error{constructor(t){super(t),this.name="Error loading Keras model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=keras.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mediapipe.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mediapipe.js new file mode 100644 index 0000000000000000000000000000000000000000..c31ce0e061988385099059f2a75d9e71481321b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mediapipe.js @@ -0,0 +1 @@ +var mediapipe=mediapipe||{},protobuf=protobuf||require("./protobuf");mediapipe.ModelFactory=class{match(t){if("pbtxt"===t.identifier.split(".").pop().toLowerCase()){const e=t.tags("pbtxt"),i=t.text;if(e.has("node")&&(-1!==i.indexOf("input_stream:")||-1!==i.indexOf("input_side_packet:")||-1!==i.indexOf("output_stream:")))return!0}return!1}open(t,e){const i=t.identifier;try{const e=protobuf.TextReader.create(t.text),i=new mediapipe.Object(e);return Promise.resolve(new mediapipe.Model(i))}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();return Promise.reject(new mediapipe.Error(s.replace(/\.$/,"")+" in '"+i+"'."))}}},mediapipe.Model=class{constructor(t){this._graphs=[new mediapipe.Graph(t)]}get format(){return"MediaPipe"}get graphs(){return this._graphs}},mediapipe.Graph=class{constructor(t){if(this._inputs=[],this._outputs=[],this._nodes=[],t){if(t.input_stream){const e=Array.isArray(t.input_stream)?t.input_stream:[t.input_stream];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._inputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.output_stream){const e=Array.isArray(t.output_stream)?t.output_stream:[t.output_stream];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._outputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.input_side_packet){const e=Array.isArray(t.input_side_packet)?t.input_side_packet:[t.input_side_packet];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._inputs.push(new mediapipe.Parameter(s,[new mediapipe.Argument(s,i,null)]))}}if(t.output_side_packet){const e=Array.isArray(t.output_side_packet)?t.output_side_packet:[t.output_side_packet];for(const t of e){const e=t.split(":"),i=e.length>1?e.shift():"",s=e.shift();this._outputs.push(new mediapipe.Parameter(t,[new mediapipe.Argument(s,i,null)]))}}if(t.node){const e=Array.isArray(t.node)?t.node:[t.node];for(const t of e)this._nodes.push(new mediapipe.Node(t))}}}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},mediapipe.Node=class{constructor(t){if(this._type=t.calculator||"?",this._type=this._type.replace(/Calculator$/,""),this._inputs=[],this._outputs=[],this._attributes=[],t.input_stream){const e=[],i=Array.isArray(t.input_stream)?t.input_stream:[t.input_stream];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._inputs.push(new mediapipe.Parameter("input_stream",e))}if(t.output_stream){const e=[],i=Array.isArray(t.output_stream)?t.output_stream:[t.output_stream];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._outputs.push(new mediapipe.Parameter("output_stream",e))}if(t.input_side_packet){const e=[],i=Array.isArray(t.input_side_packet)?t.input_side_packet:[t.input_side_packet];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._inputs.push(new mediapipe.Parameter("input_side_packet",e))}if(t.output_side_packet){const e=[],i=Array.isArray(t.output_side_packet)?t.output_side_packet:[t.output_side_packet];for(const t of i){const i=t.split(":"),s=i.length>1?i.shift():"",r=i.shift();e.push(new mediapipe.Argument(r,s,null))}this._outputs.push(new mediapipe.Parameter("output_side_packet",e))}const e=t.options||t.node_options||null;if(e)for(const t of Object.keys(e)){if("__type__"===t)continue;const i=e[t];this._attributes.push(new mediapipe.Attribute(t,i))}}get name(){return""}get type(){return this._type}get metadata(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mediapipe.Attribute=class{constructor(t,e){this._name=t,this._value=e}get name(){return this._name}get value(){return this._value}get visible(){return!0}},mediapipe.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mediapipe.Argument=class{constructor(t,e,i){if("string"!=typeof t)throw new mediapipe.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=i||null}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get initializer(){return this._initializer}},mediapipe.Object=class{constructor(t){t.start();let e=!1;const i=t.peek();i.startsWith("[")&&i.endsWith("]")&&(this.__type__=t.read().substring(0,i.length-1),t.match(":"),t.start(),e=!0);const s=new Set;for(;!t.end();){var r=t.tag(),p=t.peek(),n=null;if("{"===p)n=new mediapipe.Object(t);else if(p.startsWith('"')&&p.endsWith('"'))n=t.read().substring(1,p.length-1);else if("true"===p||"false"===p)n=t.read();else if(t.first())for(n=[];!t.last();){const e=t.read();isNaN(e)||n.push(parseFloat(e))}else n=isNaN(p)?t.read():parseFloat(t.read());!this[r]||Array.isArray(this[r])&&!s.has(r)||(this[r]=[this[r]],s.delete(r)),this[r]?this[r].push(n):(Array.isArray(n)&&s.add(r),this[r]=n)}e&&t.expect("}")}},mediapipe.Error=class extends Error{constructor(t){super(t),this.name="Error loading MediaPipe model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mediapipe.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5b70a93fb9c04be0af3f95e68cfc5b79ca7fcf17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet-metadata.json @@ -0,0 +1 @@ +[{"name":"ImageLoaderTransform","schema":{"description":"Load images from files.","attributes":[{"name":"ImageFolder","type":"string","description":"Folder where to search for images"}]}},{"name":"ImageScalerTransform","schema":{"description":"Scales an image to specified dimensions using one of the three scale types: isotropic with padding, isotropic with cropping or anisotropic. In case of isotropic padding, transparent color is used to pad resulting image.","attributes":[{"name":"Width"},{"name":"Height"},{"name":"Resizing","type":"ImageResizingTransformer.ResizingKind"},{"name":"Anchor","type":"ImageResizingTransformer.Anchor"}]}},{"name":"ImagePixelExtractor","schema":{"description":"Scales an image to specified dimensions using one of the three scale types: isotropic with padding, isotropic with cropping or anisotropic. In case of isotropic padding, transparent color is used to pad resulting image.","attributes":[{"name":"ColorsToExtract","type":"ImagePixelExtractingTransformer.ColorBits"},{"name":"OrderOfExtraction","type":"ImagePixelExtractingTransformer.ColorsOrder"},{"name":"Planes","type":"uint8"},{"name":"OutputAsFloatArray","type":"boolean"},{"name":"OffsetImage","type":"float32"},{"name":"ScaleImage","type":"float32"},{"name":"InterleavePixelColors","type":"boolean"}]}},{"name":"TensorFlowTransform","schema":{"description":"Transforms the data using the TensorFlow model.","attributes":[{"name":"IsFrozen","type":"boolean"},{"name":"AddBatchDimensionInput","type":"boolean"}]}},{"name":"TextNormalizerTransform","schema":{"description":"A text normalization transform that allows normalizing text case, removing diacritical marks, punctuation marks and/or numbers. The transform operates on text input as well as vector of tokens/text (vector of ReadOnlyMemory).","attributes":[{"name":"CaseMode","type":"TextNormalizingTransformer.CaseMode"},{"name":"KeepDiacritics","type":"boolean"},{"name":"KeepPunctuations","type":"boolean"},{"name":"KeepNumbers","type":"boolean"}]}},{"name":"CharToken","schema":{"description":"Character-oriented tokenizer where text is considered a sequence of characters.","attributes":[{"name":"UseMarkerChars","type":"boolean"},{"name":"IsSeparatorStartEnd","type":"boolean"}]}},{"name":"ConcatTransform","schema":{"category":"Tensor","description":"Concatenates one or more columns of the same item type."}},{"name":"CopyTransform","schema":{"category":"Tensor","description":"Duplicates columns from the dataset."}},{"name":"SSAModel","schema":{"attributes":[{"name":"UseMarkerChars","type":"boolean"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet.js new file mode 100644 index 0000000000000000000000000000000000000000..e8bb9c4b0ee1b17f19de32efbf8828919042b3c5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mlnet.js @@ -0,0 +1 @@ +var mlnet=mlnet||{},zip=zip||require("./zip");mlnet.ModelFactory=class{match(e){if("zip"===e.identifier.split(".").pop().toLowerCase()){const t=e.entries("zip");if(t.length>0){const e=new Set(["TransformerChain","Predictor"]);if(t.some((t=>e.has(t.name.split("\\").shift().split("/").shift()))))return!0}}return!1}open(e,t){const s=e.identifier;return mlnet.Metadata.open(t).then((t=>{try{const s=new mlnet.ModelReader(e.entries("zip"));return new mlnet.Model(t,s)}catch(e){const t=e&&e.message?e.message:e.toString();throw new mlnet.Error(t.replace(/\.$/,"")+" in '"+s+"'.")}}))}},mlnet.Model=class{constructor(e,t){this._format="ML.NET",t.version&&t.version.length>0&&(this._format+=" v"+t.version),this._graphs=[],this._graphs.push(new mlnet.Graph(e,t))}get format(){return this._format}get graphs(){return this._graphs}},mlnet.Graph=class{constructor(e,t){if(this._inputs=[],this._outputs=[],this._nodes=[],this._groups=!1,t.schema&&t.schema.inputs)for(const e of t.schema.inputs)this._inputs.push(new mlnet.Parameter(e.name,[new mlnet.Argument(e.name,new mlnet.TensorType(e.type))]));const s=new Map;t.dataLoaderModel&&this._loadTransformer(e,s,"",t.dataLoaderModel),t.predictor&&this._loadTransformer(e,s,"",t.predictor),t.transformerChain&&this._loadTransformer(e,s,"",t.transformerChain)}_loadTransformer(e,t,s,r){switch(r.__type__){case"TransformerChain":case"Text":this._loadChain(e,t,r.__name__,r.chain);break;default:this._createNode(e,t,s,r)}}_loadChain(e,t,s,r){this._groups=!0;const n=s.split("/").splice(1).join("/");for(const s of r)this._loadTransformer(e,t,n,s)}_createNode(e,t,s,r){if(r.inputs&&r.outputs){for(const e of r.inputs)e.name=t[e.name]?t[e.name].argument:e.name;for(const e of r.outputs)if(t[e.name]){t[e.name].counter++;const s=e.name+"\n"+t[e.name].counter.toString();t[e.name].argument=s,e.name=s}else t[e.name]={argument:e.name,counter:0}}this._nodes.push(new mlnet.Node(e,s,r))}get groups(){return this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},mlnet.Parameter=class{constructor(e,t){this._name=e,this._arguments=t}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mlnet.Argument=class{constructor(e,t){if("string"!=typeof e)throw new mlnet.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t}get name(){return this._name}get type(){return this._type}},mlnet.Node=class{constructor(e,t,s){if(this._metadata=e,this._group=t,this._name=s.__name__,this._type=s.__type__,this._inputs=[],this._outputs=[],this._attributes=[],s.inputs){let e=0;for(const t of s.inputs)this._inputs.push(new mlnet.Parameter(e.toString(),[new mlnet.Argument(t.name)])),e++}if(s.outputs){let e=0;for(const t of s.outputs)this._outputs.push(new mlnet.Parameter(e.toString(),[new mlnet.Argument(t.name)])),e++}for(const t of Object.keys(s).filter((e=>!e.startsWith("_")&&"inputs"!==e&&"outputs"!==e))){const r=e.attribute(this._type,this._name);this._attributes.push(new mlnet.Attribute(r,t,s[t]))}}get group(){return this._group}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mlnet.Attribute=class{constructor(e,t,s){if(this._name=t,this._value=s,e&&(e.type&&(this._type=e.type),this._type)){let e=mlnet;const t=this._type.split(".");for(;e&&t.length>0;)e=e[t.shift()];if(e){mlnet.Attribute._reverseMap=mlnet.Attribute._reverseMap||{};let t=mlnet.Attribute._reverseMap[this._type];if(!t){t={};for(const s of Object.keys(e))t[e[s.toString()]]=s;mlnet.Attribute._reverseMap[this._type]=t}Object.prototype.hasOwnProperty.call(t,this._value)&&(this._value=t[this._value])}}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return!0}},mlnet.TensorType=class{constructor(e){if(mlnet.TensorType._map=mlnet.TensorType._map||new Map([["Byte","uint8"],["Boolean","boolean"],["Single","float32"],["Double","float64"],["UInt32","uint32"],["TextSpan","string"]]),this._dataType="?",this._shape=new mlnet.TensorShape(null),mlnet.TensorType._map.has(e.name))this._dataType=mlnet.TensorType._map.get(e.name);else if("VBuffer"==e.name){if(!mlnet.TensorType._map.has(e.itemType.name))throw new mlnet.Error("Unknown data type '"+e.itemType.name+"'.");this._dataType=mlnet.TensorType._map.get(e.itemType.name),this._shape=new mlnet.TensorShape(e.dims)}else{if("Key2"!=e.name)throw new mlnet.Error("Unknown data type '"+e.name+"'.");this._dataType="key2"}}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},mlnet.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},mlnet.Metadata=class{static open(e){return mlnet.Metadata._metadata?Promise.resolve(mlnet.Metadata._metadata):e.request(null,"mlnet-metadata.json","utf-8").then((e=>(mlnet.Metadata._metadata=new mlnet.Metadata(e),mlnet.Metadata._metadata))).catch((()=>(mlnet.Metadata._metadata=new mlnet.Metadata(null),mlnet.Metadata._metadatas)))}constructor(e){if(this._map={},this._attributeCache={},e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map[e.name]=e.schema)}}type(e){return this._map[e]||null}attribute(e,t){let s=this._attributeCache[e];if(!s){s={};const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const e of t.attributes)s[e.name]=e;this._attributeCache[e]=s}return s[t]||null}},mlnet.ModelReader=class{constructor(e){const t=new mlnet.ComponentCatalog;t.register("AffineNormExec",mlnet.AffineNormSerializationUtils),t.register("AnomalyPredXfer",mlnet.AnomalyPredictionTransformer),t.register("BinaryPredXfer",mlnet.BinaryPredictionTransformer),t.register("BinaryLoader",mlnet.BinaryLoader),t.register("CaliPredExec",mlnet.CalibratedPredictor),t.register("CdfNormalizeFunction",mlnet.CdfColumnFunction),t.register("CharToken",mlnet.TokenizingByCharactersTransformer),t.register("ChooseColumnsTransform",mlnet.ColumnSelectingTransformer),t.register("ClusteringPredXfer",mlnet.ClusteringPredictionTransformer),t.register("ConcatTransform",mlnet.ColumnConcatenatingTransformer),t.register("CopyTransform",mlnet.ColumnCopyingTransformer),t.register("ConvertTransform",mlnet.TypeConvertingTransformer),t.register("CSharpTransform",mlnet.CSharpTransform),t.register("DropColumnsTransform",mlnet.DropColumnsTransform),t.register("FAFMPredXfer",mlnet.FieldAwareFactorizationMachinePredictionTransformer),t.register("FastForestBinaryExec",mlnet.FastForestClassificationPredictor),t.register("FastTreeBinaryExec",mlnet.FastTreeBinaryModelParameters),t.register("FastTreeTweedieExec",mlnet.FastTreeTweedieModelParameters),t.register("FastTreeRankerExec",mlnet.FastTreeRankingModelParameters),t.register("FastTreeRegressionExec",mlnet.FastTreeRegressionModelParameters),t.register("FeatWCaliPredExec",mlnet.FeatureWeightsCalibratedModelParameters),t.register("FieldAwareFactMacPredict",mlnet.FieldAwareFactorizationMachineModelParameters),t.register("GcnTransform",mlnet.LpNormNormalizingTransformer),t.register("GenericScoreTransform",mlnet.GenericScoreTransform),t.register("IidChangePointDetector",mlnet.IidChangePointDetector),t.register("IidSpikeDetector",mlnet.IidSpikeDetector),t.register("ImageClassificationTrans",mlnet.ImageClassificationTransformer),t.register("ImageClassificationPred",mlnet.ImageClassificationModelParameters),t.register("ImageLoaderTransform",mlnet.ImageLoadingTransformer),t.register("ImageScalerTransform",mlnet.ImageResizingTransformer),t.register("ImagePixelExtractor",mlnet.ImagePixelExtractingTransformer),t.register("KeyToValueTransform",mlnet.KeyToValueMappingTransformer),t.register("KeyToVectorTransform",mlnet.KeyToVectorMappingTransformer),t.register("KMeansPredictor",mlnet.KMeansModelParameters),t.register("LinearRegressionExec",mlnet.LinearRegressionModelParameters),t.register("LightGBMRegressionExec",mlnet.LightGbmRegressionModelParameters),t.register("LightGBMBinaryExec",mlnet.LightGbmBinaryModelParameters),t.register("Linear2CExec",mlnet.LinearBinaryModelParameters),t.register("LinearModelStats",mlnet.LinearModelParameterStatistics),t.register("MaFactPredXf",mlnet.MatrixFactorizationPredictionTransformer),t.register("MFPredictor",mlnet.MatrixFactorizationModelParameters),t.register("MulticlassLinear",mlnet.LinearMulticlassModelParameters),t.register("MultiClassLRExec",mlnet.MaximumEntropyModelParameters),t.register("MultiClassNaiveBayesPred",mlnet.NaiveBayesMulticlassModelParameters),t.register("MultiClassNetPredictor",mlnet.MultiClassNetPredictor),t.register("MulticlassPredXfer",mlnet.MulticlassPredictionTransformer),t.register("NgramTransform",mlnet.NgramExtractingTransformer),t.register("NgramHashTransform",mlnet.NgramHashingTransformer),t.register("NltTokenizeTransform",mlnet.NltTokenizeTransform),t.register("Normalizer",mlnet.NormalizingTransformer),t.register("NormalizeTransform",mlnet.NormalizeTransform),t.register("OnnxTransform",mlnet.OnnxTransformer),t.register("OptColTransform",mlnet.OptionalColumnTransform),t.register("OVAExec",mlnet.OneVersusAllModelParameters),t.register("pcaAnomExec",mlnet.PcaModelParameters),t.register("PcaTransform",mlnet.PrincipalComponentAnalysisTransformer),t.register("PipeDataLoader",mlnet.CompositeDataLoader),t.register("PlattCaliExec",mlnet.PlattCalibrator),t.register("PMixCaliPredExec",mlnet.ParameterMixingCalibratedModelParameters),t.register("PoissonRegressionExec",mlnet.PoissonRegressionModelParameters),t.register("ProtonNNMCPred",mlnet.ProtonNNMCPred),t.register("RegressionPredXfer",mlnet.RegressionPredictionTransformer),t.register("RowToRowMapper",mlnet.RowToRowMapperTransform),t.register("SsaForecasting",mlnet.SsaForecastingTransformer),t.register("SSAModel",mlnet.AdaptiveSingularSpectrumSequenceModelerInternal),t.register("SelectColumnsTransform",mlnet.ColumnSelectingTransformer),t.register("StopWordsTransform",mlnet.StopWordsTransform),t.register("TensorFlowTransform",mlnet.TensorFlowTransformer),t.register("TermLookupTransform",mlnet.ValueMappingTransformer),t.register("TermTransform",mlnet.ValueToKeyMappingTransformer),t.register("TermManager",mlnet.TermManager),t.register("Text",mlnet.TextFeaturizingEstimator),t.register("TextLoader",mlnet.TextLoader),t.register("TextNormalizerTransform",mlnet.TextNormalizingTransformer),t.register("TokenizeTextTransform",mlnet.WordTokenizingTransformer),t.register("TransformerChain",mlnet.TransformerChain),t.register("ValueMappingTransformer",mlnet.ValueMappingTransformer),t.register("XGBoostMulticlass",mlnet.XGBoostMulticlass);const s=new mlnet.ModelHeader(t,e,"",null),r=s.openText("TrainingInfo/Version.txt");r&&(this.version=r.split(" ").shift().split("\r").shift());const n=s.openBinary("Schema");n&&(this.schema=new mlnet.BinaryLoader(null,n).schema);const i=s.open("TransformerChain");i&&(this.transformerChain=i);const o=s.open("DataLoaderModel");o&&(this.dataLoaderModel=o);const a=s.open("Predictor");a&&(this.predictor=a)}},mlnet.ComponentCatalog=class{constructor(){this._map=new Map}register(e,t){this._map.set(e,t)}create(e,t){if(!this._map.has(e))throw new mlnet.Error("Unknown loader signature '"+e+"'.");const s=this._map.get(e);return Reflect.construct(s,[t])}},mlnet.ModelHeader=class{constructor(e,t,s,r){if(this._entries=t,this._catalog=e,this._directory=s,r){const e=new mlnet.Reader(r),t=new TextDecoder("ascii");e.assert("ML\0MODEL"),this.versionWritten=e.uint32(),this.versionReadable=e.uint32();const s=e.uint64();e.uint64();const n=e.uint64(),i=e.uint64(),o=e.uint64();e.uint64(),this.modelSignature=t.decode(e.bytes(8)),this.modelVersionWritten=e.uint32(),this.modelVersionReadable=e.uint32(),this.loaderSignature=t.decode(e.bytes(24).filter((e=>0!=e))),this.loaderSignatureAlt=t.decode(e.bytes(24).filter((e=>0!=e)));const a=e.uint64();e.uint64();const l=e.uint64(),m=e.uint32();if(0!=n&&0!=o){e.position=n;const t=i>>3,s=[];let r=0;for(let n=0;n>1;let n="";for(let s=0;s0?this._directory+"/":this._directory)+e)+"/Model.key",s=this._entries.find((e=>e.name==t||e.name==t.replace(/\//g,"\\")));if(s){const t=new mlnet.ModelHeader(this._catalog,this._entries,e,s.data),r=this._catalog.create(t.loaderSignature,t);return r.__type__=r.__type__||t.loaderSignature,r.__name__=e,r}return null}openBinary(e){const t=this._directory.length>0?this._directory+"/":this._directory;e=t+e;const s=this._entries.find((t=>t.name==e||t.name==e.replace(/\//g,"\\")));return s?new mlnet.Reader(s.data):null}openText(e){const t=this._directory.length>0?this._directory+"/":this._directory;e=t+e;const s=this._entries.find((t=>t.name.split("\\").join("/")==e));return s?(new TextDecoder).decode(s.data):null}check(e,t,s){return e===this.modelSignature&&t>=this.modelVersionReadable&&s<=this.modelVersionWritten}},mlnet.Reader=class{constructor(e){this._buffer=e,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._position=0}set position(e){this._position=e}get position(){return this._position}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new mlnet.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}match(e){const t=this._position;for(let s=0;s1048576)throw new mlnet.Error("Value not in 48-bit range.");return 4294967296*t+e}float32(){const e=this._position;return this.skip(4),this._dataView.getFloat32(e,!0)}float32s(e){const t=[];for(let s=0;s=65538&&(this.Threads=e.reader.int32(),this.GeneratedRowIndexName=e.string(null)),this.ShuffleBlocks=e.modelVersionWritten>=65539?e.reader.float64():4,t=e.openBinary("Schema.idv")),t.assert("CML\0DVB\0"),t.bytes(8),t.bytes(8);const s=t.uint64(),r=t.int64();t.int64();const n=t.int32();t.position=r,t.assert("\0BVD\0LMC"),t.position=s,this.schema={},this.schema.inputs=[];for(let e=0;e=65539){const s=t.int32();for(let r=0;r=65538)for(let r=0;r=65538)for(;;){const r=t.int32();if(-1==r)break;s[r]=e.string()}}if(s>1)throw new mlnet.Error("");this.outputs=[];for(let e=0;e0&&this._featureHistogram.push(t.int32s(this._featureCount));this._absentFeaturesLogProb=t.float64s(this._labelHistogram.length)}},mlnet.LinearModelParameters=class extends mlnet.ModelParametersBase{constructor(e){super(e);const t=e.reader;this.Bias=t.float32(),t.int32(),this.Indices=t.int32s(t.int32()),this.Weights=t.float32s(t.int32())}},mlnet.LinearBinaryModelParameters=class extends mlnet.LinearModelParameters{constructor(e){super(e),e.modelVersionWritten>131073&&(this.Statistics=e.open("ModelStats"))}},mlnet.ModelStatisticsBase=class{constructor(e){const t=e.reader;this.ParametersCount=t.int32(),this.TrainingExampleCount=t.int64(),this.Deviance=t.float32(),this.NullDeviance=t.float32()}},mlnet.LinearModelParameterStatistics=class extends mlnet.ModelStatisticsBase{constructor(e){super(e);const t=e.reader;if(e.modelVersionWritten<65538&&!t.boolean())return;const s=t.float32s(this.ParametersCount);t.int32()==this.ParametersCount||(this.stdErrorIndices=t.int32s(this.ParametersCount)),this._coeffStdError=s,this._bias=t.float32();const r=t.byte(),n=t.int32(),i=t.float32s(n);r?this._weights=i:this.weightsIndices=t.int32s(n)}},mlnet.LinearMulticlassModelParametersBase=class extends mlnet.ModelParametersBase{constructor(e){super(e);const t=e.reader,s=t.int32(),r=t.int32();if(this.Biases=t.float32s(r),0==t.int32()){t.int32(),t.int32(),this.Weights=[];for(let e=0;e=65538;s.NgramLength=t.int32(),s.SkipLength=t.int32(),r&&(s.Weighting=t.int32()),s.NonEmptyLevels=t.booleans(s.NgramLength),s.NgramMap=new mlnet.SequencePool(t),r&&(s.InvDocFreqs=t.float64s(t.int32()))}},mlnet.NgramHashingTransformer=class extends mlnet.RowToRowTransformerBase{constructor(e){super(e);const t=e.modelVersionWritten<65539,s=e.reader;t&&s.int32(),this.inputs=[],this.outputs=[];const r=s.int32();if(t);else for(let t=0;t>1&5),r=(3&r)+(r>>2&3),s.Planes=255&r,s.OutputAsFloatArray=t.boolean(),s.OffsetImage=t.float32(),s.ScaleImage=t.float32(),s.InterleavePixelColors=t.boolean()}},mlnet.ImagePixelExtractingTransformer.ColorBits={Alpha:1,Red:2,Green:4,Blue:8,Rgb:14,All:15},mlnet.ImagePixelExtractingTransformer.ColorsOrder={ARGB:1,ARBG:2,ABRG:3,ABGR:4,AGRB:5,AGBR:6},mlnet.NormalizingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e);const t=e.reader;this.Options=[];for(let s=0;se.toString())).join(",")+"]":""),l="Normalizer_"+("00"+s).slice(-3),m=e.open(l);this.Options.push({type:a,func:m})}}},mlnet.KeyToValueMappingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e)}},mlnet.ValueToKeyMappingTransformer=class extends mlnet.OneToOneTransformerBase{constructor(e){super(e);const t=e.reader;if(e.modelVersionWritten>=65539)this.textMetadata=t.booleans(this.outputs.length+this.inputs.length);else{this.textMetadata=[];for(let e=0;e=65538))throw new mlnet.Error("Unsupported TermManager version.");for(let s=0;s=65538&&(t=e.string(),s=e.string(null)),r.push([t,s])}this.chain=[];for(let t=0;t65537?t.int32():1;this.inputs=[];for(let t=0;t65537?t.int32():1;this.outputs=[];for(let t=0;t65548){const s=t.int32();this.LoadedCustomShapeInfos=[];for(let r=0;r=65538)||t.boolean(),this.AddBatchDimensionInput=!(e.modelVersionReadable>=65539)||t.boolean();const s=t.int32();this.inputs=[];for(let t=0;t=65538?t.int32():1;this.outputs=[];for(let t=0;t=65538?t.int32():this.Dimensionality,r=s=this.VerDefaultValueSerialized,r=e.modelVersionWritten>=this.VerCategoricalSplitSerialized;this.TrainedEnsemble=new mlnet.InternalTreeEnsemble(e,s,r),this.InnerOptions=e.string(null),e.modelVersionWritten>=this.verNumFeaturesSerialized&&(this.NumFeatures=t.int32())}},mlnet.InternalTreeEnsemble=class{constructor(e,t,s){const r=e.reader;this.Trees=[];const n=r.int32();for(let i=0;i0){this.CategoricalSplitFeatures=[],this.CategoricalSplitFeatureRanges=[];for(const t of e)this.CategoricalSplitFeatures[t]=r.int32s(r.int32()),this.CategoricalSplitFeatureRanges[t]=r.int32s(2)}}this.Thresholds=r.uint32s(r.int32()),this.RawThresholds=r.float32s(r.int32()),this.DefaultValueForMissing=t?r.float32s(r.int32()):null,this.LeafValues=r.float64s(r.int32()),this.SplitGain=r.float64s(r.int32()),this.GainPValue=r.float64s(r.int32()),this.PreviousLeafValue=r.float64s(r.int32())}},mlnet.InternalTreeEnsemble.TreeType={Regression:0,Affine:1,FastForest:2},mlnet.TreeEnsembleModelParametersBasedOnRegressionTree=class extends mlnet.TreeEnsembleModelParameters{constructor(e){super(e)}},mlnet.FastTreeTweedieModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65537}get VerDefaultValueSerialized(){return 65538}get VerCategoricalSplitSerialized(){return 65539}},mlnet.FastTreeRankingModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FastTreeBinaryModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FastTreeRegressionModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.LightGbmRegressionModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.LightGbmBinaryModelParameters=class extends mlnet.TreeEnsembleModelParametersBasedOnRegressionTree{constructor(e){super(e)}get VerNumFeaturesSerialized(){return 65538}get VerDefaultValueSerialized(){return 65540}get VerCategoricalSplitSerialized(){return 65541}},mlnet.FeatureWeightsCalibratedModelParameters=class extends mlnet.ValueMapperCalibratedModelParametersBase{constructor(e){super(e)}},mlnet.FastTreePredictionWrapper=class{constructor(){}},mlnet.FastForestClassificationPredictor=class extends mlnet.FastTreePredictionWrapper{constructor(e){super(e)}},mlnet.PlattCalibrator=class{constructor(e){const t=e.reader;this.ParamA=t.float64(),this.ParamB=t.float64()}},mlnet.Codec=class{constructor(e){this.name=e.string();const t=e.leb128(),s=e.bytes(t);switch(e=new mlnet.Reader(s),this.name){case"Boolean":case"Single":case"Double":case"Byte":case"Int32":case"UInt32":case"Int64":case"TextSpan":break;case"VBuffer":this.itemType=new mlnet.Codec(e),this.dims=e.int32s(e.int32());break;case"Key":case"Key2":this.itemType=new mlnet.Codec(e),this.count=e.uint64();break;default:throw new mlnet.Error("Unknown codec '"+this.name+"'.")}}read(e,t){const s=[];switch(this.name){case"Single":for(let r=0;r=65538&&(this._state=t.float32s(t.int32())),this.ShouldComputeForecastIntervals=t.byte(),this._observationNoiseVariance=t.float32(),this._autoregressionNoiseVariance=t.float32(),this._observationNoiseMean=t.float32(),this._autoregressionNoiseMean=t.float32(),e.modelVersionReadable>=65538&&(this._nextPrediction=t.float32()),this._maxRank=t.int32(),this._shouldStablize=t.byte(),this._shouldMaintainInfo=t.byte(),this._maxTrendRatio=t.float64(),s&&(this._wTrans=t.float32s(t.int32()),this._y=t.float32s(t.int32())),this._buffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t)}},mlnet.SequentialForecastingTransformBase=class extends mlnet.SequentialTransformerBase{constructor(e){super(e);const t=e.reader;this._outputLength=t.int32()}},mlnet.SsaForecastingBaseWrapper=class extends mlnet.SequentialForecastingTransformBase{constructor(e){super(e);const t=e.reader;this.IsAdaptive=t.boolean(),this.Horizon=t.int32(),this.ConfidenceLevel=t.float32(),this.WindowedBuffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t),this.InitialWindowedBuffer=mlnet.TimeSeriesUtils.deserializeFixedSizeQueueSingle(t),this.Model=e.open("SSA")}},mlnet.SsaForecastingTransformer=class extends mlnet.SsaForecastingBaseWrapper{constructor(e){super(e)}},mlnet.ColumnSelectingTransformer=class{constructor(e){const t=e.reader;if(e.check("DRPCOLST",65538,65538))throw new mlnet.Error("'LoadDropColumnsTransform' not supported.");if(e.check("CHSCOLSF",65537,65537)){t.int32(),this.KeepHidden=this._getHiddenOption(t.byte());const s=t.int32();this.inputs=[];for(let r=0;rmnn.Metadata.open(t).then((n=>{const a=e.identifier;try{mnn.schema=flatbuffers.get("mnn").MNN;const t=new flatbuffers.Reader(e.buffer),a=mnn.schema.Net.create(t);return new mnn.Model(n,a)}catch(e){t.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new mnn.Error(n.replace(/\.$/,"")+" in '"+a+"'.")}}))))}},mnn.Model=class{constructor(e,t){switch(t.sourceType){case mnn.schema.NetSource.CAFFE:this._source="Caffe";break;case mnn.schema.NetSource.TENSORFLOW:this._source="TensorFlow";break;case mnn.schema.NetSource.TFLITE:this._source="TensorFlow Lite";break;case mnn.schema.NetSource.ONNX:this._source="ONNX"}this._graphs=[new mnn.Graph(e,t)]}get format(){return"MNN v2"}get source(){return this._source||""}get graphs(){return this._graphs}},mnn.Graph=class{constructor(e,t){this._nodes=[],this._inputs=[],this._outputs=[];const n=new Set;for(let a=0;a0&&this._buildAttributes(e,i,t,this._attributes)}}_buildTensor(e,t,n,a){this._inputs.push(new mnn.Parameter(t,!0,[new mnn.Argument("",null,new mnn.Tensor("Weight",new mnn.TensorType(e,new mnn.TensorShape(n)),a))]))}_buildAttributes(e,t,n,a){if(t)for(const s of Object.keys(t)){if(n&&n.has(s))continue;const i=t[s];if(Object.keys(mnn.schema).find((e=>mnn.schema[e].prototype&&i instanceof mnn.schema[e])))this._buildAttributes(e,i,null,a);else if(i){const t=e.attribute(this.type,s);a.push(new mnn.Attribute(t,s,i))}}}get type(){return this._type}get name(){return this._name}get domain(){return null}get metadata(){return this._metadata.type(this.type)}get group(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chains}get attributes(){return this._attributes}},mnn.Attribute=class{constructor(e,t,n,a){if(this._type=null,this._value=ArrayBuffer.isView(n)?Array.from(n):n,this._name=t,this._visible=a,e&&e.type){this._type=e.type;const t=mnn.schema[this._type+"Name"];t&&(this._value=t[this._value])}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},mnn.Parameter=class{constructor(e,t,n){this._name=e,this._visible=t,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},mnn.Argument=class{constructor(e,t,n){this._name=e,this._type=t||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},mnn.Tensor=class{constructor(e,t,n){this._kind=e,this._type=t,this._data=n.slice(0)}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);return JSON.stringify(t,null,4)}_context(){const e={state:null};return this._data&&0!==this._data.length?(e.index=0,e.count=0,e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,e.data=this._data,e):(e.state="Tensor data is empty.",e)}_decode(e,t){let n=e.dimensions;0==n.length&&(n=[1]);const a=[],s=n[t];if(t==n.length-1)for(let t=0;te.limit)return a.push("..."),a;a.push(e.data[e.index]),e.index++,e.count++}else for(let n=0;ne.limit)return a.push("..."),a;a.push(this._decode(e,t+1))}return 0==e.dimensions.length?a[0]:a}},mnn.TensorType=class{constructor(e,t){switch(e){case mnn.schema.DataType.DT_INVALID:this._dataType="?";break;case mnn.schema.DataType.DT_FLOAT:this._dataType="float32";break;case mnn.schema.DataType.DT_DOUBLE:this._dataType="float64";break;case mnn.schema.DataType.DT_INT32:this._dataType="int32";break;case mnn.schema.DataType.DT_UINT8:this._dataType="uint8";break;case mnn.schema.DataType.DT_INT16:this._dataType="int16";break;case mnn.schema.DataType.DT_INT8:this._dataType="int8";break;case mnn.schema.DataType.DT_STRING:this._dataType="string";break;case mnn.schema.DataType.DT_COMPLEX64:this._dataType="complex64";break;case mnn.schema.DataType.DT_INT64:this._dataType="int64";break;case mnn.schema.DataType.DT_BOOL:this._dataType="boolean";break;case mnn.schema.DataType.DT_QINT8:this._dataType="qint8";break;case mnn.schema.DataType.DT_QUINT8:this._dataType="quint8";break;case mnn.schema.DataType.DT_QINT32:this._dataType="qint32";break;case mnn.schema.DataType.DT_BFLOAT16:this._dataType="bfloat16";break;case mnn.schema.DataType.DT_QINT16:this._dataType="qint16";break;case mnn.schema.DataType.DT_QUINT16:this._dataType="quint16";break;case mnn.schema.DataType.DT_UINT16:this._dataType="uint16";break;case mnn.schema.DataType.DT_COMPLEX128:this._dataType="complex128";break;case mnn.schema.DataType.DT_HALF:this._dataType="float16";break;case mnn.schema.DataType.DT_RESOURCE:this._dataType="resource";break;case mnn.schema.DataType.DT_VARIANT:this._dataType="variant";break;default:throw new mnn.Error("Unknown data type '"+JSON.stringify(e)+"'.")}this._shape=t}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},mnn.TensorShape=class{constructor(e){this._dimensions=Array.from(e)}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length>0?"["+this._dimensions.map((e=>e?e.toString():"?")).join(",")+"]":""}},mnn.Metadata=class{static open(e){return mnn.Metadata._metadata?Promise.resolve(mnn.Metadata._metadata):e.request(null,"mnn-metadata.json","utf-8").then((e=>(mnn.Metadata._metadata=new mnn.Metadata(e),mnn.Metadata._metadata))).catch((()=>(mnn.Metadata._metadata=new mnn.Metadata(null),mnn.Metadata._metadata)))}constructor(e){if(this._map=new Map,e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.has(e)?this._map.get(e):null}attribute(e,t){const n=this.type(e);if(n){let e=n.attributeMap;if(!e){if(e={},n.attributes)for(const t of n.attributes)e[t.name]=t;n.attributeMap=e}const a=e[t];if(a)return a}return null}},mnn.Utility=class{static enum(e,t){const n=e&&mnn.schema?mnn.schema[e]:void 0;if(n){if(mnn.Utility._enumKeyMap=mnn.Utility._enumKeyMap||new Map,!mnn.Utility._enumKeyMap.has(e)){const t=new Map;for(const e of Object.keys(n))t.set(n[e],e);mnn.Utility._enumKeyMap.set(e,t)}const a=mnn.Utility._enumKeyMap.get(e);if(a.has(t))return a.get(t)}return t}},mnn.Error=class extends Error{constructor(e){super(e),this.name="Error loading MNN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0ccc4bade96f31cc62762bbe777ffd8deb9c02cb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"attributes":[{"default":false,"name":"cudnn_off","type":"boolean"},{"default":"off","name":"cudnn_tune"},{"default":[1,null],"name":"dilate","type":"int32[]"},{"name":"kernel","type":"int32[]"},{"visible":false,"name":"no_bias","type":"boolean"},{"type":"int32","default":1,"name":"num_group"},{"type":"int32","name":"num_filter"},{"default":[0,null],"name":"pad","type":"int32[]"},{"default":[1,null],"name":"stride","type":"int32[]"},{"type":"int32","default":"1024","name":"workspace"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias","option":"optional"}],"outputs":[{"name":"output"}]}},{"name":"Deconvolution","schema":{"attributes":[{"visible":false,"name":"no_bias"},{"default":"1","name":"num_group"},{"type":"int32","default":"1024","name":"workspace"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"FullyConnected","schema":{"attributes":[{"type":"boolean","default":true,"name":"flatten"},{"type":"boolean","visible":false,"name":"no_bias"},{"type":"int32","name":"num_hidden"}],"category":"Layer","inputs":[{"name":"input"},{"name":"weight"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"Dropout","schema":{"category":"Dropout","attributes":[{"type":"float32","default":0.5,"name":"p"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LRN","schema":{"category":"Normalization","attributes":[{"name":"alpha","type":"float32","default":0.0001},{"name":"beta","type":"float32","default":0.75},{"name":"knorm","type":"float32","default":2},{"name":"nsize","type":"int32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxOutput","schema":{"attributes":[{"default":"1","name":"grad_scale"},{"default":"-1","name":"ignore_label"},{"default":false,"name":"multi_output"},{"default":"null","name":"normalization"},{"default":false,"name":"out_grad"},{"default":"0","name":"smooth_alpha"},{"default":false,"name":"use_ignore"},{"default":false,"name":"preserve_shape"}],"category":"Activation","inputs":[{"name":"input"},{"name":"label"}],"outputs":[{"name":"output"}]}},{"name":"SoftmaxActivation","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LeakyReLU","schema":{"category":"Activation","inputs":[{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}]}},{"name":"Activation","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pooling","schema":{"attributes":[{"default":false,"name":"cudnn_off"},{"default":false,"name":"global_pool"},{"name":"kernel","type":"int32[]"},{"default":[0,null],"name":"pad","type":"int32[]"},{"default":"valid","name":"pooling_convention"},{"default":"max","name":"pool_type"},{"default":[1,null],"name":"stride","type":"int32[]"}],"category":"Pool","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Flatten","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Concat","schema":{"attributes":[{"default":"1","name":"dim"},{"visible":false,"name":"num_args"}],"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"SliceChannel","schema":{"inputs":[{"name":"inputs"}],"outputs":[{"name":"outputs","option":"variadic"}]}},{"name":"_Plus","schema":{"inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"elemwise_add","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"elemwise_sub","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"elemwise_div","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"BatchNorm","schema":{"attributes":[{"type":"int32","default":1,"name":"axis"},{"type":"float64","default":0.001,"name":"eps"},{"type":"float32","default":0.9,"name":"momentum"},{"type":"boolean","default":true,"name":"fix_gamma"},{"type":"boolean","default":false,"name":"use_global_stats"}],"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"mean"},{"name":"variance"}],"outputs":[{"name":"output"}]}},{"name":"CuDNNBatchNorm","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"}],"outputs":[{"name":"output"}]}},{"name":"ElementWiseSum","schema":{"category":"Normalization","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Embedding","schema":{"category":"Transform","attributes":[{"type":"int32","name":"input_dim"},{"type":"int32","name":"output_dim"}],"inputs":[{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}]}},{"name":"RNN","schema":{"category":"Layer","attributes":[{"type":"boolean","name":"bidirectional","default":false},{"name":"lstm_parameters","visible":false},{"type":"int32","name":"num_layers"},{"type":"boolean","default":false,"name":"state_outputs"},{"type":"int32","name":"state_size"},{"type":"float32","name":"p","default":0}],"inputs":[{"name":"input"},{"name":"state_0"},{"name":"state_1"}],"outputs":[{"name":"output"}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_minus_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_rminus_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_mul_scalar","schema":{"attributes":[{"name":"scalar","type":"float32"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"broadcast_mul","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"broadcast_add","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"broadcast_div","schema":{"inputs":[{"name":"lhs"},{"name":"rhs"}],"outputs":[{"name":"out"}]}},{"name":"_copy","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_minus_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_mul_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"slice_axis","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Pad","schema":{"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"relu","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"softmax","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_linalg_gemm2","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"},{"name":"bias"}],"outputs":[{"name":"output"}]}},{"name":"_zeros","schema":{"category":"Constant","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_sub","schema":{"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}]}},{"name":"_mul","schema":{"inputs":[{"name":"x"},{"name":"y"}],"outputs":[{"name":"z"}]}},{"name":"MakeLoss","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"transpose","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"sum","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"square","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"sqrt","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"mean","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"log","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"_plus_scalar","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet.js new file mode 100644 index 0000000000000000000000000000000000000000..c742213b7c5b0b6497b212d1c5c5c94d53f399e6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/mxnet.js @@ -0,0 +1 @@ +var mxnet=mxnet||{},long=long||{Long:require("long")},zip=zip||require("./zip"),ndarray=ndarray||{};mxnet.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if("model"===e||"mar"===e){if(t.entries("zip").length>0)return!0}else if("json"==e){const e=t.text;if(-1!=e.indexOf('"nodes":',0))try{const t=JSON.parse(e);if(t&&t.nodes&&t.arg_nodes&&t.heads)return!0}catch(t){}}else if("params"==e){const e=t.buffer,n=[18,1,0,0,0,0,0,0];if(e&&e.length>n.length&&n.every(((t,n)=>t==e[n])))return!0}return!1}open(t,e){const n=t.identifier,s=t.identifier.split(".").pop().toLowerCase();let r=null,a=null,i=null,o=null;switch(s){case"json":try{return r=JSON.parse(t.text),r&&r.nodes&&r.nodes.some((t=>t&&"tvm_op"==t.op))&&(i="TVM"),o=mxnet.ModelFactory._basename(n,"json","symbol"),o?t.request(o+"-0000.params",null).then((t=>this._openModel(n,i,null,r,null,t,e))).catch((()=>this._openModel(n,i,null,r,null,a,e))):this._openModel(n,i,null,r,null,null,e)}catch(t){throw e.exception(t,!1),new mxnet.Error(t.message),null}case"params":return a=t.buffer,o=mxnet.ModelFactory._basename(t.identifier,"params"),o?t.request(o+"-symbol.json","utf-8").then((t=>(r=JSON.parse(t),r&&r.nodes&&r.nodes.some((t=>t&&"tvm_op"==t.op))&&(i="TVM"),this._openModel(n,i,null,r,null,a,e)))).catch((()=>this._openModel(n,i,null,null,null,a,e))):this._openModel(n,i,null,null,null,a,e);case"mar":case"model":{const s=new Map;try{for(const e of t.entries("zip"))s.set(e.name,e)}catch(t){throw new mxnet.Error("Failed to decompress Zip archive. "+t.message)}let o=s.get(s.has("MANIFEST.json")?"MANIFEST.json":"MAR-INF/MANIFEST.json"),h="";if(!o){const e=Array.from(s.keys()).filter((t=>t.endsWith("/"))).filter((t=>s.get(t+"MANIFEST.json")));if(1!=e.length)throw new mxnet.Error("Manifest not found in '"+t.identifier+"'.");h=e[0],o=s.get(h+"MANIFEST.json")}const l=new TextDecoder("utf-8");let u=null;try{u=JSON.parse(l.decode(o.data))}catch(t){throw new mxnet.Error("Failed to read manifest. "+t.message)}let p=null,d=null,c=null,m=null;if(u.Model){if(p=u.Model["Model-Format"],p&&"MXNet-Symbolic"!=p)throw new mxnet.Error("Model format '"+p+"' not supported.");if(i="MXNet Model Server",u["Model-Archive-Version"]&&(i+=" v"+u["Model-Archive-Version"].toString()),!u.Model.Symbol)throw new mxnet.Error("Manifest does not contain symbol entry.");d=s.get(h+u.Model.Symbol),u.Model.Signature&&(c=s.get(h+u.Model.Signature)),u.Model.Parameters&&(m=s.get(h+u.Model.Parameters))}else{if(!u.model)throw new mxnet.Error("Manifest does not contain model.");if(i="MXNet Model Archive",u.specificationVersion&&(i+=" v"+u.specificationVersion.toString()),u.model.modelName){d=s.get(h+u.model.modelName+"-symbol.json");let t=null;for(t of Array.from(s.keys()))if(t=t.substring(h.length),t.endsWith(".params")&&t.startsWith(u.model.modelName)){m=s.get(t);break}if(!d&&!m)for(t of Object.keys(s))if(t=t.substring(h.length),t.endsWith(".params")){m=s.get(t);break}}}if(!d&&!m)throw new mxnet.Error("Model does not contain symbol entry.");try{d&&(r=JSON.parse(l.decode(d.data)))}catch(t){throw new mxnet.Error("Failed to load symbol entry."+t.message)}m&&(a=m.data);let _=null;try{c&&(_=JSON.parse(l.decode(c.data)))}catch(t){}try{return this._openModel(n,i,u,r,_,a,e)}catch(t){const e=t&&t.message?t.message:t.toString();throw new mxnet.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}}default:throw new mxnet.Error("Unsupported file extension.")}}_openModel(t,e,n,s,r,a,i){return mxnet.Metadata.open(i).then((o=>{const h=new Map;if(a)try{const t=new ndarray.Stream(a);for(const e of Object.keys(t.arrays)){const n=e.startsWith("arg:")||e.startsWith("aux:")?e.substring(4):e;h.set(n,t.arrays[e])}}catch(t){}try{return new mxnet.Model(o,e,n,s,r,h)}catch(e){i.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new mxnet.Error(n.replace(/\.$/,"")+" in '"+t+"'.")}}))}static _basename(t,e,n){const s=t.split(".");if(s.length>=2&&s.pop().toLowerCase()===e){const t=s.join(".").split("-");if(t.length>=2){const e=t.pop();if(n){if(e!=n)return null}else for(let t=0;t="0"&&n<="9"||n>="A"&&n<="Z"||n>="a"&&n<="z"))return null}return t.join("-")}}return null}},mxnet.Model=class{constructor(t,e,n,s,r,a){if(!s&&!a)throw new mxnet.Error("JSON symbol data not available.");if(s){if(!Object.prototype.hasOwnProperty.call(s,"nodes"))throw new mxnet.Error("JSON file does not contain an MXNet 'nodes' property.");if(!Object.prototype.hasOwnProperty.call(s,"arg_nodes"))throw new mxnet.Error("JSON file does not contain an MXNet 'arg_nodes' property.");if(!Object.prototype.hasOwnProperty.call(s,"heads"))throw new mxnet.Error("JSON file does not contain an MXNet 'heads' property.")}if(n){if(n.Model&&n.Model["Model-Name"]&&(this._name=n.Model["Model-Name"]),n.Model&&n.Model.Description&&this._name!=n.Model.Description&&(this._description=n.Model.Description),n.Engine&&n.Engine.MXNet){const t=mxnet.Model._convert_version(n.Engine.MXNet);this._runtime="MXNet v"+(t||n.Engine.MXNet.toString())}if(n.License&&(this._license=n.License),n.model&&n.model.modelName&&(this._name=n.model.modelName),n.model&&n.model.modelVersion&&(this._version=n.model.modelVersion),n.model&&n.model.modelName&&this._name!=n.model.description&&(this._description=n.model.description),n.runtime&&(this._runtime=n.runtime),n.engine&&n.engine.engineName){const t=n.engine.engineVersion?n.engine.engineName+" "+n.engine.engineVersion:n.engine.engineName;this._runtime=this._runtime?this._runtime+" ("+t+")":t}n.publisher&&n.publisher.author&&(this._author=n.publisher.author,n.publisher.email&&(this._author=this._author+" <"+n.publisher.email+">")),n.license&&(this._license=n.license)}if(this._format=e,!this._format&&s&&s.attrs&&s.attrs.mxnet_version){const t=mxnet.Model._convert_version(s.attrs.mxnet_version);t&&(this._format="MXNet v"+t)}this._format||(this._format="MXNet"),this._graphs=[],this._graphs.push(new mxnet.Graph(t,n,s,r,a))}get format(){return this._format}get name(){return this._name}get version(){return this._version}get description(){return this._description}get author(){return this._author}get license(){return this._license}get runtime(){return this._runtime}get graphs(){return this._graphs}static _convert_version(t){if(Array.isArray(t)&&2==t.length&&"int"==t[0]){const e=Math.floor(t[1]/1e4)%100,n=Math.floor(t[1]/100)%100,s=Math.floor(t[1])%100;return[e.toString(),n.toString(),s.toString()].join(".")}return null}},mxnet.Graph=class{constructor(t,e,n,s,r){this._metadata=t,this._nodes=[],this._inputs=[],this._outputs=[];const a=new Map;if(r)for(const t of r){const e=t[0],n=t[1];a.set(e,new mxnet.Tensor("Initializer",e,new mxnet.TensorType(n.dataType,new mxnet.TensorShape(n.shape.dimensions)),n.data))}if(n){const t=n.nodes,e={};if(s&&s.inputs)for(const t of s.inputs)e[t.data_name]=t;const r={};if(s&&s.outputs)for(const t of s.outputs)r[t.data_name]=t;for(const e of t)e.outputs=[];for(const e of t)e.inputs=e.inputs.map((e=>mxnet.Graph._updateOutput(t,e)));const i={};for(const e of t)for(const t of e.outputs)i[t]=(i[t]||0)+1;const o={};for(const e of n.arg_nodes)o[e]=e!o[e])))this._nodes.push(new mxnet.Node(this._metadata,e,o,h,a));for(const t of Object.keys(o)){const n=o[t];if(n&&(!n.inputs||0==n.inputs.length)&&n.outputs&&1==n.outputs.length){const t=n.outputs[0],s=n.name;let r=null;const a=e[s];a&&a.data_shape&&(r=new mxnet.TensorType(-1,new mxnet.TensorShape(a.data_shape))),this._inputs.push(new mxnet.Parameter(s,[new mxnet.Argument("["+t.join(",")+"]",r)]))}}}else if(r){let e=null;const n=[];let s=Object.keys(r).every((t=>-1!=t.indexOf("_")))?"_":"";if(0==s.length&&(s=Object.keys(r).every((t=>-1!=t.indexOf(".")))?".":""),!(s.length>0))throw new mxnet.Error("Unsupported key format in params.");{const t={};for(const a of Object.keys(r)){const r=a.split(s);let i=r.pop();(a.endsWith("moving_mean")||a.endsWith("moving_var"))&&(i=[r.pop(),i].join(s));const o=r.join(s);e=t[o],e||(e={name:o,op:"Weights",params:[]},t[o]=e,n.push(e)),t[o].params.push({name:i,id:a})}}for(e of n)this._nodes.push(new mxnet.Node(t,e,{},{},r))}}get name(){return""}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}static _updateOutput(t,e){const n=e[0],s=t[n],r=e[1];if(s)for(;r>=s.outputs.length;)s.outputs.push([n,s.outputs.length]);return[n,r]}},mxnet.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},mxnet.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new mxnet.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._initializer?this._initializer.name:this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},mxnet.Node=class{constructor(t,e,n,s,r){this._metadata=t,this._type=e.op,this._name=e.name,this._attributes=[],this._inputs=[],this._outputs=[];const a=e.attrs||e.attr||e.param;if(a){"tvm_op"==this._type&&a.func_name&&(this._type=a.func_name);for(const t of Object.keys(a))"tvm_op"!=this._type&&"func_name"!=t&&this._attributes.push(new mxnet.Attribute(this._metadata,this.type,t,a[t]))}let i=null;const o=t.type(this.type);if(e.inputs){let a=e.inputs;"RNN"==this._type&&(a=a.map((t=>{const e=t[0],s=n[e];return s&&"null"==s.op&&s.name&&s.name.endsWith("_parameters")&&s.attr&&s.attr.__init__?(this._attributes.push(new mxnet.Attribute(this._metadata,this.type,s.name,s.attr.__init__)),delete n[e],null):t})),a=a.filter((t=>null!=t)));const h={};for(const e of a){const a="["+e.join(",")+"]";if(i=s[a],!i){const s=e[0],a=n[s];if(a&&a.name&&(!a.inputs||0==a.inputs.length)&&a.outputs&&1==a.outputs.length)if(i=r.get(a.name)||null,i)delete n[s];else{let e=this._name;if(e.endsWith("_fwd")&&(e=e.slice(0,-3)),a.name&&(a.name.startsWith(e+"_")||a.name.startsWith(e+"."))){let e=-1,r=[];if(a.attrs&&a.attrs.__dtype__&&a.attrs.__shape__)try{e=parseInt(a.attrs.__dtype__),r=JSON.parse("["+a.attrs.__shape__.replace("(","").replace(")","").split(" ").join("").split(",").map((t=>t||'"?"')).join(",")+"]")}catch(t){}let o=null;o=-1!==e||r.length>0?new mxnet.TensorType(e,new mxnet.TensorShape(r)):new mxnet.TensorType(-1,new mxnet.TensorShape(null)),i=new mxnet.Tensor("Initializer",a.name,o,null),delete n[s]}}}i&&(h[a]=i,s[a]=i)}let l=0;if(o&&o.inputs)for(const t of o.inputs)if(l{const n="["+t.join(",")+"]";return new mxnet.Parameter((l+e).toString(),[new mxnet.Argument(n,null,h[n])])}))))}if(e.outputs){const t=e.outputs;let n=0;if(o&&o.outputs)for(const e of o.outputs)if(nnew mxnet.Parameter((n+e).toString(),[new mxnet.Argument("["+t.join(",")+"]",null,null)])))))}if(e.params)for(const t of e.params)this._inputs.push(new mxnet.Parameter(t.name,[new mxnet.Argument(t.id,null,r.get(t.id)||null)]))}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},mxnet.Attribute=class{constructor(t,e,n,s){let r;this._name=n,this._value=s;const a=t.attribute(e,n);if(a&&a.type)switch(a.type){case"boolean":switch(s){case"True":this._value=!0;break;case"False":this._value=!1}break;case"int32":r=Number.parseInt(this._value,10),this._value=Number.isNaN(this._value-r)?s:r;break;case"float32":case"float64":r=Number.parseFloat(this._value),this._value=Number.isNaN(this._value-r)?s:r;break;case"int32[]":if(this._value.length>2&&this._value.startsWith("(")&&this._value.endsWith(")")){let t=[];const e=this._value.substring(1,this._value.length-1).split(",").map((t=>t.trim())).map((t=>t.endsWith("L")?t.substring(0,t.length-1):t));for(const n of e)r=Number.parseInt(n,10),Number.isNaN(n-r)?t=null:null!=t&&t.push(r);null!=t&&(this._value=t)}}if(a)if(Object.prototype.hasOwnProperty.call(a,"visible")&&!a.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(a,"default")){let t=a.default;if(this._value==t)this._visible=!1;else if(Array.isArray(this._value)&&Array.isArray(t)){if(t=t.slice(0,t.length),t.length>1&&null==t[t.length-1])for(t.pop();t.lengthe==t[n]))&&(this._visible=!1)}}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},mxnet.Tensor=class{constructor(t,e,n,s){this._kind=t,this._name=e,this._type=n,this._data=s}get kind(){return"Initializer"}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return this._data?this._type||"?"!==this._type.dataType?this._type.shape.length<1?(t.state="Tensor has unknown shape.",t):(t.dataType=this._type.dataType,t.dimensions=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t):(t.state="Tensor has no data type.",t):(t.state="Tensor data is empty.",t)}_decode(t,e){const n=[],s=t.dimensions[e];if(e==t.dimensions.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"float32":n.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float64":n.push(t.data.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case"float16":n.push(mxnet.Tensor._decodeNumberFromFloat16(t.data.getUint16(t.index,!0))),t.index+=2,t.count++;break;case"uint8":n.push(t.data.getUint8(t.index,!0)),t.index+=1,t.count++;break;case"int32":n.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int8":n.push(t.data.getInt8(t.index,!0)),t.index+=1,t.count++;break;case"int64":n.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++}}else for(let r=0;rt.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return n}static _decodeNumberFromFloat16(t){const e=(32768&t)>>15,n=(31744&t)>>10,s=1023&t;return 0==n?(e?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==n?s?NaN:1/0*(e?-1:1):(e?-1:1)*Math.pow(2,n-15)*(1+s/Math.pow(2,10))}},mxnet.TensorType=class{constructor(t,e){switch(t){case 0:this._dataType="float32";break;case 1:this._dataType="float64";break;case 2:this._dataType="float16";break;case 3:this._dataType="uint8";break;case 4:this._dataType="int32";break;case 5:this._dataType="int8";break;case 6:this._dataType="int64";break;case-1:this._dataType="?";break;default:throw new mxnet.Error("Unknown type '"+t+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},mxnet.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},mxnet.Metadata=class{static open(t){return mxnet.Metadata._metadata?Promise.resolve(mxnet.Metadata._metadata):t.request(null,"mxnet-metadata.json","utf-8").then((t=>(mxnet.Metadata._metadata=new mxnet.Metadata(t),mxnet.Metadata._metadata))).catch((()=>(mxnet.Metadata._metadata=new mxnet.Metadata(null),mxnet.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]||null}attribute(t,e){let n=this._attributeCache[t];if(!n){n={};const e=this.type(t);if(e&&e.attributes)for(const t of e.attributes)n[t.name]=t;this._attributeCache[t]=n}return n[e]||null}},mxnet.Error=class extends Error{constructor(t){super(t),this.name="Error loading MXNet model."}},ndarray.Stream=class{constructor(t){this._arrays={};const e=new ndarray.Reader(t);if(!e.checkSignature([18,1,0,0,0,0,0,0]))throw new ndarray.Error("Invalid signature.");if(!e.checkSignature([0,0,0,0,0,0,0,0]))throw new ndarray.Error("Invalid reserved block.");const n=[];for(let t=e.uint64();t>0;t--)n.push(new ndarray.Array(e));const s=new TextDecoder("ascii"),r=[];for(let t=e.uint64();t>0;t--){const t=s.decode(e.read(e.uint64()));r.push(t)}if(r.length!=n.length)throw new ndarray.Error("Label count mismatch.");for(let t=0;t0&&(this.sshape=new ndarray.Shape(t,!0)),this._shape=new ndarray.Shape(t,!0),0==this._shape.dimensions.length)return;if(this._context=new ndarray.Context(t),this._dataType=t.uint32(),e>0)throw new ndarray.Error("Not implemented.");const n=(this._dataTypet*e))}},ndarray.Context=class{constructor(t){this._deviceType=t.uint32(),this._deviceId=t.uint32()}},ndarray.Reader=class{constructor(t){this._buffer=t,this._position=0,this._end=t.length}checkSignature(t){if(this._position+t.length<=this._end)for(let e=0;ethis._end)throw new ndarray.Error("Data not available.");const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}uint16(){if(this._position+2>this._end)throw new ndarray.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}uint64(){const t=this.uint32();if(0!=this.uint32())throw new ndarray.Error("Large int64 value.");return t}},ndarray.Error=class extends Error{constructor(t){super(t),this.name="NDArray Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=mxnet.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..88f491c553cf439b7daf396b8a49ee1b5dfd4eb9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn-metadata.json @@ -0,0 +1 @@ +[{"name":"AbsVal","schema":{"operator":0}},{"name":"ArgMax","schema":{"operator":1}},{"name":"BatchNorm","schema":{"operator":2,"category":"Normalization","attributes":[{"name":"channels","type":"int32","default":0},{"name":"eps","type":"float32","default":0}]}},{"name":"Bias","schema":{"operator":3,"category":"Layer","attributes":[{"name":"bias_data_size","default":0,"visible":false}]}},{"name":"BNLL","schema":{"operator":4}},{"name":"Concat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Convolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"dilation_w","type":"int32","default":1},{"name":"stride_w","type":"int32","default":1},{"name":"pad_w","type":"int32","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","type":"int32","default":0,"visible":false},{"name":"group","type":"int32","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","type":"int32","default":0},{"name":"dilation_h","type":"int32","default":1},{"name":"stride_h","type":"int32","default":1},{"name":"pad_h","type":"int32","default":0}]}},{"name":"Crop","schema":{"operator":7,"category":"Data","attributes":[{"name":"woffset","default":0},{"name":"hoffset","default":0},{"name":"coffset","default":0},{"name":"outw","default":0},{"name":"outh","default":0},{"name":"outc","default":0}]}},{"name":"Deconvolution","schema":{"operator":8,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"Dropout","schema":{"operator":9,"category":"Dropout","attributes":[{"name":"scale","type":"float32","default":1}]}},{"name":"Eltwise","schema":{"operator":10,"attributes":[{"name":"op_type","default":0},{"name":"coeffs","default":[]}],"inputs":[{"name":"inputs","option":"variadic"}]}},{"name":"ELU","schema":{"operator":11}},{"name":"Embed","schema":{"operator":12,"category":"Transform","attributes":[{"name":"num_output","default":0},{"name":"input_dim","default":0},{"name":"bias_term","default":0},{"name":"weight_data_size","default":0}]}},{"name":"Exp","schema":{"operator":13}},{"name":"Flatten","schema":{"operator":14,"category":"Shape"}},{"name":"InnerProduct","schema":{"operator":15,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":""},{"name":""},{"name":""},{"name":""},{"name":""},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":0}]}},{"name":"Input","schema":{"operator":16}},{"name":"Exp","schema":{"operator":17}},{"name":"LRN","schema":{"operator":18,"category":"Normalization","attributes":[{"name":"region_type","default":0},{"name":"local_size","default":5},{"name":"alpha","default":1},{"name":"beta","default":0.75},{"name":"bias","default":1}]}},{"name":"Exp","schema":{"operator":19}},{"name":"MVN","schema":{"operator":20}},{"name":"Pooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pooling_type","default":0},{"name":"kernel_w","default":0},{"name":"stride_w","default":1},{"name":"pad_left","default":0},{"name":"global_pooling","default":0},{"name":"pad_mode","default":0},{"name":""},{"name":""},{"name":""},{"name":""},{"name":""},{"name":"kernel_h","default":0},{"name":"stride_h","default":1},{"name":"pad_top","default":0},{"name":"pad_right","default":0},{"name":"pad_bottom","default":0}]}},{"name":"Power","schema":{"operator":22}},{"name":"PReLU","schema":{"operator":23,"category":"Activation","attributes":[{"name":"num_slope","type":"int32","default":0,"visible":false}]}},{"name":"Proposal","schema":{"operator":24}},{"name":"Reducation","schema":{"operator":25}},{"name":"ReLU","schema":{"operator":26,"category":"Activation","attributes":[{"name":"slope","type":"float32","default":0}]}},{"name":"Reshape","schema":{"operator":27,"category":"Shape","attributes":[{"name":"w","default":-233},{"name":"h","default":-233},{"name":"c","default":-233},{"name":"permute","default":0}]}},{"name":"ROIPooling","schema":{"operator":28}},{"name":"Scale","schema":{"operator":29,"category":"Layer","attributes":[{"name":"scale_data_size","default":0,"visible":false},{"name":"bias_term","default":0,"visible":false}]}},{"name":"Sigmoid","schema":{"operator":30,"category":"Activation"}},{"name":"Slice","schema":{"operator":31,"category":"Tensor","attributes":[{"name":"slices","default":[]},{"name":"axis","default":0}]}},{"name":"Softmax","schema":{"operator":32,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0},{"name":"fixbug0","type":"int32","default":0}]}},{"name":"Split","schema":{"operator":33,"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output","option":"variadic"}]}},{"name":"SPP","schema":{"operator":34,"category":"Activation"}},{"name":"TanH","schema":{"operator":35,"category":"Activation"}},{"name":"Threshold","schema":{"operator":36}},{"name":"Tile","schema":{"operator":37}},{"name":"RNN","schema":{"operator":38,"category":"Layer"}},{"name":"LSTM","schema":{"operator":39,"category":"Layer"}},{"name":"BinaryOp","schema":{"operator":40,"attributes":[{"name":"op_type","type":"int32","default":0},{"name":"with_scalar","type":"int32","default":0},{"name":"b","type":"float32","default":0}]}},{"name":"UnaryOp","schema":{"operator":41}},{"name":"ConvolutionDepthWise","schema":{"operator":42,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"Padding","schema":{"operator":43}},{"name":"Squeeze","schema":{"operator":44}},{"name":"ExpandDims","schema":{"operator":45}},{"name":"Normalize","schema":{"operator":46}},{"name":"Permute","schema":{"operator":47,"category":"Shape","attributes":[{"name":"order_type","default":0}]}},{"name":"PriorBox","schema":{"operator":48,"attributes":[{"name":"min_sizes","default":[]},{"name":"max_sizes","default":[]},{"name":"aspect_ratios","default":[]},{"name":"varainces0","type":"float32","default":0},{"name":"varainces1","type":"float32","default":0},{"name":"varainces2","type":"float32","default":0},{"name":"varainces3","type":"float32","default":0},{"name":"flip","default":1},{"name":"clip","default":0},{"name":"image_width","default":0},{"name":"image_height","default":0},{"name":"step_width","default":-233},{"name":"step_height","default":-233},{"name":"offset","default":0}]}},{"name":"DetectionOutput","schema":{"operator":49,"attributes":[{"name":"num_class","default":0},{"name":"nms_threshold","default":0.05},{"name":"nms_top_k","default":300},{"name":"keep_top_k","default":100},{"name":"confidence_threshold","default":0.5},{"name":"varainces0","default":0.1},{"name":"varainces1","default":0.1},{"name":"varainces2","default":0.2},{"name":"varainces3","default":0.2}]}},{"name":"Interp","schema":{"operator":50}},{"name":"DeconvolutionDepthWise","schema":{"operator":51,"category":"Layer","attributes":[{"name":"num_output","default":0},{"name":"kernel_w","default":0},{"name":"dilation_w","default":1},{"name":"stride_w","default":1},{"name":"pad_w","default":0},{"name":"bias_term","default":0,"visible":false},{"name":"weight_data_size","default":0,"visible":false},{"name":"group","default":0},{"name":"int8_scale_term","default":0},{"name":"activation_type","default":0},{"name":"activation_params","default":[]},{"name":"kernel_h","default":0},{"name":"dilation_h","default":1},{"name":"stride_h","default":1},{"name":"pad_h","default":0}]}},{"name":"ShuffleChannel","schema":{"operator":52,"attributes":[{"name":"group","default":1}]}},{"name":"InstanceNorm","schema":{"operator":53}},{"name":"Clip","schema":{"operator":54}},{"name":"Reorg","schema":{"operator":55}},{"name":"YoloDetectionOutput","schema":{"operator":56,"attributes":[{"name":"num_class","type":"int32","default":20},{"name":"num_box","type":"int32","default":5},{"name":"confidence_threshold","type":"float32","default":0.01},{"name":"nms_threshold","type":"float32","default":0.45},{"name":"biases"}],"inputs":[{"name":"input","option":"variadic"}]}},{"name":"Quantize","schema":{"operator":57}},{"name":"Dequantize","schema":{"operator":58}},{"name":"Yolov3DetectionOutput","schema":{"operator":59,"attributes":[{"name":"num_class","type":"int32","default":20},{"name":"num_box","type":"int32","default":5},{"name":"confidence_threshold","type":"float32","default":0.01},{"name":"nms_threshold","type":"float32","default":0.45},{"name":"biases","type":"float32[]"},{"name":"mask","type":"float32[]"},{"name":"anchors_scale","type":"float32[]"}],"inputs":[{"name":"input","option":"variadic"}]}},{"name":"PSROIPooling","schema":{"operator":60}},{"name":"ROIAlign","schema":{"operator":61}},{"name":"Packing","schema":{"operator":62}},{"name":"Requantize","schema":{"operator":63}},{"name":"Cast","schema":{"operator":64}},{"name":"HardSigmoid","schema":{"operator":65,"category":"Activation"}},{"name":"SELU","schema":{"operator":66,"category":"Activation"}},{"name":"ReLU6","schema":{"category":"Activation"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn.js new file mode 100644 index 0000000000000000000000000000000000000000..8178ab0f4992bae6b40934475b3ad106dde86b0e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/ncnn.js @@ -0,0 +1 @@ +var ncnn=ncnn||{},base=base||require("./base");ncnn.ModelFactory=class{match(t){const e=t.identifier.toLowerCase();if(e.endsWith(".param")||e.endsWith(".cfg.ncnn")){let e=t.text;if(e=e.substring(0,Math.min(e.length,32)),"7767517"===e.split("\n").shift().trim())return!0}if(e.endsWith(".param.bin")){const e=t.buffer;if(e.length>4&&7767517==(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0)return!0}if(e.endsWith(".bin")||e.endsWith(".weights.ncnn")){if("snapshot_blob.bin"==e||"v8_context_snapshot.bin"===e)return!1;const n=t.buffer;if(n.length>4){const t=(n[0]|n[1]<<8|n[2]<<16|n[3]<<24)>>>0;if(0===t||1===t||19950407===t||871224===t||180310===t)return!0}}return!1}open(t,e){return ncnn.Metadata.open(e).then((e=>{const n=t.identifier.toLowerCase(),s=(t,s)=>{try{return new ncnn.Model(e,t,s)}catch(t){const e=t&&t.message?t.message:t.toString();throw new ncnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}};let i=null;if(n.endsWith(".param")||n.endsWith(".cfg.ncnn"))return n.endsWith(".param")?i=t.identifier.substring(0,t.identifier.length-6)+".bin":n.endsWith(".cfg.ncnn")&&(i=t.identifier.substring(0,t.identifier.length-9)+".weights.ncnn"),t.request(i,null).then((e=>s(t.text,e))).catch((()=>s(t.text,null)));if(n.endsWith(".param.bin"))return i=t.identifier.substring(0,t.identifier.length-10)+".bin",t.request(i,null).then((e=>s(t.buffer,e))).catch((()=>s(t.buffer,null)));if(n.endsWith(".bin")||n.endsWith(".weights.ncnn")){let e=null;return n.endsWith("bin")?e=t.identifier.substring(0,t.identifier.length-4)+".param":n.endsWith(".weights.ncnn")&&(e=t.identifier.substring(0,t.identifier.length-13)+".cfg.ncnn"),t.request(e,"utf-8").then((e=>s(e,t.buffer))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new ncnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}}))}},ncnn.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new ncnn.Graph(t,e,n))}get format(){return"ncnn"}get graphs(){return this._graphs}},ncnn.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new ncnn.BlobReader(n),i=("string"==typeof e?new ncnn.TextParamReader(e):new ncnn.BinaryParamReader(t,e)).layers;for(const e of i)if("Input"==e.type){const t=e.attributes.map((t=>isNaN(parseInt(t.value,10))?t.value:parseInt(t.value,10))),n=new ncnn.TensorShape(t),s=new ncnn.TensorType("float32",n);this._inputs.push(new ncnn.Parameter(e.name,!0,e.outputs.map((t=>new ncnn.Argument(t,s,null)))))}else this._nodes.push(new ncnn.Node(t,s,e))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},ncnn.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},ncnn.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new ncnn.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},ncnn.Node=class{constructor(t,e,n){this._metadata=t,this._inputs=[],this._outputs=[],this._attributes=[],this._type=n.type,this._name=n.name;const s=t.operator(this._type);s&&(this._type=s);const i=t.type(this._type),a=i&&i.attributes?i&&i.attributes:[];for(const t of n.attributes){const e=a[t.key];this._attributes.push(new ncnn.Attribute(e,t.key,t.value))}const r=n.inputs;let o=0;if(i&&i.inputs)for(const t of i.inputs)if(o""!=e||"optional"!=t.option)).map((t=>new ncnn.Argument(t,null,null)));this._inputs.push(new ncnn.Parameter(t.name,!0,n)),o+=e}this._inputs=this._inputs.concat(r.slice(o).map(((t,e)=>{const n=o+e==0?"input":(o+e).toString();return new ncnn.Parameter(n,!0,[new ncnn.Argument(t,null,null)])})));const h=n.outputs;let u=0;if(i&&i.outputs)for(const t of i.outputs)if(unew ncnn.Argument(t,null,null)));this._outputs.push(new ncnn.Parameter(t.name,!0,n)),u+=e}switch(this._outputs=this._outputs.concat(h.slice(u).map(((t,e)=>{const n=u+e==0?"output":(u+e).toString();return new ncnn.Parameter(n,!0,[new ncnn.Argument(t,null,null)])}))),this._type){case"BatchNorm":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"slope",[t],"float32"),this._weight(e,"mean",[t],"float32"),this._weight(e,"variance",[t],"float32"),this._weight(e,"bias",[t],"float32");break}case"InnerProduct":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[2]||0,10);this._weight(e,"weight",[t,s/t]),"1"==n.attr[1]&&this._weight(e,"bias",[t],"float32");break}case"Bias":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"bias",[t],"float32");break}case"Embed":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[3]||0,10);this._weight(e,"weight",[s]),"1"==n.attr[2]&&this._weight(e,"bias",[t],"float32");break}case"Convolution":case"ConvolutionDepthWise":case"Deconvolution":case"DeconvolutionDepthWise":{const t=parseInt(n.attr[0]||0,10),s=parseInt(n.attr[1]||0,10),i=parseInt(n.attr[11]||s,10),a=parseInt(n.attr[6]||0,10);this._weight(e,"weight",[t,a/(t*s*i),s,i]),"1"==n.attr[5]&&this._weight(e,"bias",[t],"float32");break}case"Dequantize":if("1"==n.attr[1]){const t=parseInt(n.attr[2]||0,10);this._weight(e,"bias",[t],"float32")}break;case"Requantize":if("1"==n.attr[2]){const t=parseInt(n.attr[3]||0,10);this._weight(e,"bias",[t],"float32")}break;case"InstanceNorm":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"gamma",[t],"float32"),this._weight(e,"beta",[t],"float32");break}case"Scale":{const t=parseInt(n.attr[0]||0,10);-233!=t&&(this._weight(e,"scale",[t],"float32"),"1"==n.attr[1]&&this._weight(e,"bias",[t],"float32"));break}case"Normalize":{const t=parseInt(n.attr[3]||0,10);this._weight(e,"scale",[t],"float32");break}case"PReLU":{const t=parseInt(n.attr[0]||0,10);this._weight(e,"slope",[t],"float32");break}}}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_weight(t,e,n,s){const i=t.read(n,s);s=i?i.dataType||"?":s||"?";const a=i?i.data:null;this._inputs.push(new ncnn.Parameter(e,!0,[new ncnn.Argument("",null,new ncnn.Tensor(new ncnn.TensorType(s,new ncnn.TensorShape(n)),a))]))}},ncnn.Attribute=class{constructor(t,e,n){if(this._type="",this._name=e,this._value=n,t){switch(this._name=t.name,t.type&&(this._type=t.type),this._type){case"int32":this._value=parseInt(this._value,10);break;case"float32":this._value=parseFloat(this._value);break;case"float32[]":this._value=this._value.map((t=>parseFloat(t)))}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1)}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},ncnn.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Weight"}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},ncnn.TensorType=class{constructor(t,e){this._dataType=t||"?",this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},ncnn.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},ncnn.Metadata=class{static open(t){return ncnn.Metadata._metadata?Promise.resolve(ncnn.Metadata._metadata):t.request(null,"ncnn-metadata.json","utf-8").then((t=>(ncnn.Metadata._metadata=new ncnn.Metadata(t),ncnn.Metadata._metadata))).catch((()=>(ncnn.Metadata._metadata=new ncnn.Metadata(null),ncnn.Metadata._metadatas)))}constructor(t){if(this._operatorMap=new Map,this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema),Object.prototype.hasOwnProperty.call(t.schema,"operator")&&this._operatorMap.set(t.schema.operator,t.name))}}operator(t){return this._operatorMap.get(t)}type(t){return this._map.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},ncnn.TextParamReader=class{constructor(t){const e=t.split(/\r?\n/);if("7767517"!==e.shift())throw new ncnn.Error("Invalid signature.");if(2!==e.shift().split(" ").length)throw new ncnn.Error("Invalid header count.");const n=[];for(;e.length>0;){const t=e.shift().trim();if(t.length>0){const e=t.split(" ").filter((t=>0!=t.length)),s={};s.type=e.shift(),s.name=e.shift();const i=parseInt(e.shift(),10),a=parseInt(e.shift(),10);s.inputs=e.splice(0,i),s.outputs=e.splice(0,a),s.attr={},s.attributes=[];for(const t of e){const e=t.split("=");if(2===e.length){let t=e[0].trim(),n=e[1].trim();const i=parseInt(t,10);i<0&&(n=n.split(",").map((t=>t.trim())),n.shift(),t=(-(i+23300)).toString()),s.attr[t]=n,s.attributes.push({key:t,value:n})}}n.push(s)}}this._layers=n}get layers(){return this._layers}},ncnn.BinaryParamReader=class{constructor(t,e){const n=new ncnn.BinaryReader(e);if(7767517!==n.int32())throw new ncnn.Error("Invalid signature.");const s=n.int32();n.int32();const i=[];for(let e=0;ethis._buffer.length)throw new ncnn.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}},ncnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading ncnn model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=ncnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/npz.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/npz.js new file mode 100644 index 0000000000000000000000000000000000000000..dd4f89b758f92803da553e2aac5a661d74103f31 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/npz.js @@ -0,0 +1 @@ +var npz=npz||{},long=long||{Long:require("long")};npz.ModelFactory=class{match(t){if("npz"===t.identifier.split(".").pop().toLowerCase()){const e=t.entries("zip");return e.length>0&&e.every((t=>t.name.endsWith(".npy")))}return!1}open(t,e){return e.require("./numpy").then((n=>e.require("./pickle").then((e=>{const i=t.identifier;try{const i=[],s=new Map,a=new Map,r=new Map;a.set("_codecs.encode",(function(t){return t})),r.set("numpy.core.multiarray._reconstruct",(function(t,e,n){this.subtype=t,this.shape=e,this.dtype=n,this.__setstate__=function(t){this.version=t[0],this.shape=t[1],this.typecode=t[2],this.is_f_order=t[3],this.rawdata=t[4]},this.__read__=function(t){const e={};e.__type__=this.subtype,e.dtype=this.typecode,e.shape=this.shape;let n=e.dtype.itemsize;for(let t=0;t{if(a.has(t))return a.get(t).apply(null,e);const n={__type__:t};if(!r.has(t))throw new npz.Error("Unknown function '"+t+"'.");return r.get(t).apply(n,e),n},o=new Map([["i1","int8"],["i2","int16"],["i4","int32"],["i8","int64"],["u1","uint8"],["u2","uint16"],["u4","uint32"],["u8","uint64"],["f2","float16"],["f4","float32"],["f8","float64"]]);for(const a of t.entries("zip")){if(!a.name.endsWith(".npy"))throw new npz.Error("Invalid file name '"+a.name+"'.");const t=a.name.replace(/\.npy$/,"").split("/"),r=t.pop(),p=t.length>=2?t.join("/"):"";if(!s.has(p)){const t={name:p,parameters:[]};i.push(t),s.set(p,t)}const u=s.get(p);let d=new n.Array(a.data);if("|"===d.byteOrder){if("O"!==d.dataType)throw new npz.Error("Invalid data type '"+d.dataType+"'.");d={dataType:new e.Unpickler(d.data).load(h).dtype.name,shape:null,data:null,byteOrder:"|"}}u.parameters.push({name:r,dataType:o.has(d.dataType)?o.get(d.dataType):d.dataType,shape:d.shape,data:d.data,byteOrder:d.byteOrder})}return new npz.Model(i,"NumPy Zip")}catch(t){const e=t&&t.message?t.message:t.toString();throw new npz.Error(e.replace(/\.$/,"")+" in '"+i+"'.")}}))))}},npz.Model=class{constructor(t,e){this._format=e,this._graphs=[],this._graphs.push(new npz.Graph(t))}get format(){return this._format}get graphs(){return this._graphs}},npz.Graph=class{constructor(t){this._nodes=[];for(const e of t)this._nodes.push(new npz.Node(e))}get inputs(){return[]}get outputs(){return[]}get nodes(){return this._nodes}},npz.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},npz.Argument=class{constructor(t,e){if("string"!=typeof t)throw new npz.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._initializer=e||null}get name(){return this._name}get type(){return this._initializer.type}get initializer(){return this._initializer}},npz.Node=class{constructor(t){this._name=t.name,this._inputs=[];for(const e of t.parameters){const t=this._name?[this._name,e.name].join("/"):e.name,n=new npz.Tensor(t,e.dataType,e.shape,e.data,e.byteOrder);this._inputs.push(new npz.Parameter(e.name,[new npz.Argument(t,n)]))}}get type(){return"Module"}get name(){return this._name}get metadata(){return null}get inputs(){return this._inputs}get outputs(){return[]}get attributes(){return[]}},npz.Tensor=class{constructor(t,e,n,i,s){this._name=t,this._type=new npz.TensorType(e,new npz.TensorShape(n)),this._shape=n,this._data=i,this._byteOrder=s}get kind(){return""}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return npz.Tensor._stringify(e,""," ")}_context(){const t={index:0,count:0,state:null};if("<"!==this._byteOrder&&">"!==this._byteOrder)return t.state="Tensor byte order is not supported.",t;if(this._reference)return t.state="Tensor reference not implemented.",t;if(!this._data||0==this._data.length)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":t.itemSize=2;break;case"float32":t.itemSize=4;break;case"float64":t.itemSize=8;break;case"int8":t.itemSize=1;break;case"int16":t.itemSize=2;break;case"int32":t.itemSize=4;break;case"int64":t.itemSize=8;break;case"uint8":t.itemSize=1;break;case"uint16":t.itemSize=2;break;case"uint32":t.itemSize=4;break;default:return t.state="Tensor data type is not supported.",t}return t.dimensions=this._type.shape.dimensions,t.dataType=this._type.dataType,t.littleEndian="<"==this._byteOrder,t.data=this._data,t.rawData=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t}_decode(t,e){const n=t.littleEndian,i=0==t.dimensions.length?[1]:t.dimensions,s=[],a=i[e];if(e==i.length-1)for(let e=0;et.limit)return s.push("..."),s;if(t.rawData){switch(t.dataType){case"float16":s.push(t.rawData.getFloat16(t.index,n));break;case"float32":s.push(t.rawData.getFloat32(t.index,n));break;case"float64":s.push(t.rawData.getFloat64(t.index,n));break;case"int8":s.push(t.rawData.getInt8(t.index,n));break;case"int16":s.push(t.rawData.getInt16(t.index,n));break;case"int32":s.push(t.rawData.getInt32(t.index,n));break;case"int64":s.push(long.Long.fromBytes(t.data.subarray(t.index,t.index+8),!0,n));break;case"uint8":s.push(t.rawData.getUint8(t.index,n));break;case"uint16":s.push(t.rawData.getUint16(t.index,n));break;case"uint32":s.push(t.rawData.getUint32(t.index,n))}t.index+=t.itemSize,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.dimensions.length?s[0]:s}static _stringify(t,e,n){if(Array.isArray(t)){const i=[];i.push(e+"[");const s=t.map((t=>npz.Tensor._stringify(t,e+n,n)));return s.length>0&&i.push(s.join(",\n")),i.push(e+"]"),i.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},npz.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType||"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},npz.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},npz.Error=class extends Error{constructor(t){super(t),this.name="Error loading Chainer model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=npz.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/numpy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/numpy.js new file mode 100644 index 0000000000000000000000000000000000000000..ca88fd6a83f69a4aceaa67afbc4086c67b8ab1d4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/numpy.js @@ -0,0 +1 @@ +var numpy=numpy||{};numpy.Array=class{constructor(t){if(t){const e=new numpy.Reader(t),r=[147,78,85,77,80,89];if(!e.bytes(6).every(((t,e)=>t==r[e])))throw new numpy.Error("Invalid signature.");const s=e.byte(),i=e.byte();if(1!==s&&0!==i)throw new numpy.Error("Invalid version '"+[s,i].join(".")+"'.");const a=JSON.parse(e.string().trim().replace(/'/g,'"').replace("False","false").replace("(","[").replace(/,*\),*/g,"]"));if(a.fortran_order)throw new numpy.Error("Fortran order is not supported.'");if(!a.descr||a.descr.length<2)throw new numpy.Error("Missing property 'descr'.");if(!a.shape)throw new numpy.Error("Missing property 'shape'.");switch(this._shape=a.shape,this._byteOrder=a.descr[0],this._byteOrder){case"|":this._dataType=a.descr.substring(1),this._data=e.bytes(e.size-e.position);break;case">":case"<":{if(3!==a.descr.length)throw new numpy.Error("Unsupported data type '"+a.descr+"'.");this._dataType=a.descr.substring(1);const t=parseInt(a.descr[2],10)*this._shape.reduce(((t,e)=>t*e),1);this._data=e.bytes(t);break}default:throw new numpy.Error("Unsupported data type '"+a.descr+"'.")}}}get data(){return this._data}set data(t){this._data=t}get dataType(){return this._dataType}set dataType(t){this._dataType=t}get shape(){return this._shape}set shape(t){this._shape=t}get byteOrder(){return this._byteOrder}set byteOrder(t){this._byteOrder=t}toBuffer(){const t=new numpy.Writer;t.bytes([147,78,85,77,80,89]),t.byte(1),t.byte(0);const e={itemSize:1,position:0,dataType:this._dataType,byteOrder:this._byteOrder||"<",shape:this._shape,descr:""};if("<"!==e.byteOrder&&">"!==e.byteOrder)throw new numpy.Error("Unknown byte order '"+this._byteOrder+"'.");if(2!==e.dataType.length||"f"!==e.dataType[0]&&"i"!==e.dataType[0]&&"u"!==e.dataType[0])throw new numpy.Error("Unsupported data type '"+this._dataType+"'.");e.itemSize=parseInt(e.dataType[1],10);let r="";switch(this._shape.length){case 0:throw new numpy.Error("Invalid shape.");case 1:r="("+this._shape[0].toString()+",)";break;default:r="("+this._shape.map((t=>t.toString())).join(", ")+")"}let s="{ "+["'descr': '"+e.byteOrder+e.dataType+"'","'fortran_order': False","'shape': "+r].join(", ")+" }";s+=" ".repeat(16-(s.length+2+8+1&15))+"\n",t.string(s);const i=e.itemSize*this._shape.reduce(((t,e)=>t*e));return e.data=new Uint8Array(i),e.dataView=new DataView(e.data.buffer,e.data.byteOffset,i),numpy.Array._encodeDimension(e,this._data,0),t.bytes(e.data),t.toBuffer()}static _encodeDimension(t,e,r){const s=t.shape[r],i="<"===t.byteOrder;if(r==t.shape.length-1)for(let r=0;r>8&255])}bytes(t){const e=new Uint8Array(t.length);for(let r=0;r) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Abs","schema":{"description":"Absolute takes one input data (Tensor) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Abs","schema":{"description":"Absolute takes one input data (Tensor) and produces one output data\n(Tensor) where the absolute is, y = abs(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Abs',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = abs(x)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_abs')","summary":"abs"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Acos","schema":{"description":"Calculates the arccosine (inverse of cosine) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Acos',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arccos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acos_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32)\ny = np.arccos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acos')","summary":"acos"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arccosine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Acosh","schema":{"description":"Calculates the hyperbolic arccosine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Acosh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([10, np.e, 1]).astype(np.float32)\ny = np.arccosh(x) # expected output [2.99322295, 1.65745449, 0.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_acosh_example')\n\nx = np.random.uniform(1.0, 10.0, (3, 4, 5)).astype(np.float32)\ny = np.arccosh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_acosh')","summary":"acosh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arccosine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Adagrad","schema":{"attributes":[{"description":"The decay factor of learning rate after one update.The effective learning rate is computed by r = R / (1 + T * decay_factor). Default to 0 so that increasing update counts doesn't reduce the learning rate.","name":"decay_factor","required":false,"type":"float32"},{"default":9.999999974752427e-7,"description":"Small scalar to avoid dividing by zero.","name":"epsilon","required":false,"type":"float32"},{"description":"Regularization coefficient in 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient","required":false,"type":"float32"}],"description":"Compute one iteration of ADAGRAD, a stochastic gradient based optimization\n algorithm. This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. As you can imagine, ADAGRAD requires\n some parameters:\n \n - The initial learning-rate \"R\".\n - The update count \"T\". That is, the number of training iterations conducted.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A learning-rate decay factor \"decay_factor\".\n - A small constant \"epsilon\" to avoid dividing-by-zero. \n\n At each ADAGRAD iteration, the optimized tensors are moved along a direction\n computed based on their estimated gradient and accumulated squared gradient. Assume\n that only a single tensor \"X\" is updated by this operator. We need the value of \"X\",\n its gradient \"G\", and its accumulated squared gradient \"H\". Therefore, variables in\n this operator's input list are sequentially \"R\", \"T\", \"X\", \"G\", and \"H\". Other\n parameters are given as attributes because they are usually constants. Also, the\n corresponding output tensors are the new value of \"X\" (called \"X_new\"), and then\n the new accumulated squared gradient (called \"H_new\"). Those outputs are computed\n from the given inputs following the pseudo code below.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise arithmetic operations with\n numpy-style broadcasting support. The pseudo code to compute those outputs is:\n\n // Compute a scalar learning-rate factor. At the first update of X, T is generally\n // 0 (0-based update index) or 1 (1-based update index).\n r = R / (1 + T * decay_factor);\n\n // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.\n G_regularized = norm_coefficient * X + G;\n\n // Compute new accumulated squared gradient.\n H_new = H + G_regularized * G_regularized;\n\n // Compute the adaptive part of per-coordinate learning rate. Note that Sqrt(...)\n // computes element-wise square-root.\n H_adaptive = Sqrt(H_new) + epsilon\n\n // Compute the new value of \"X\".\n X_new = X - r * G_regularized / H_adaptive;\n\n If one assign this operators to optimize multiple inputs, for example, \"X_1\" and \"X_2\", the same\n pseudo code may be extended to handle all tensors jointly. More specifically, we can view \"X\" as a\n concatenation of \"X_1\" and \"X_2\" (of course, their gradient and accumulate gradient should\n be concatenated too) and then just reuse the entire pseudo code.\n\n Note that ADAGRAD was first proposed in http://jmlr.org/papers/volume12/duchi11a/duchi11a.pdf.\n In that reference paper, this operator is a special case of the Figure 1's composite mirror\n descent update.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nepsilon = 1e-5\ndecay_factor = 0.1\n\n# Create operator.\nnode = onnx.helper.make_node('Adagrad',\n inputs=['R', 'T', 'X', 'G', 'H'],\n outputs=['X_new', 'H_new'],\n norm_coefficient=norm_coefficient,\n epsilon=epsilon,\n decay_factor=decay_factor,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.0], dtype=np.float32)\ng = np.array([-1.0], dtype=np.float32)\nh = np.array([2.0], dtype=np.float32)\n\n# Compute expected outputs of Adagrad.\nx_new, h_new = apply_adagrad(r, t, x, g, h,\n norm_coefficient, epsilon, decay_factor)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, h],\n outputs=[x_new, h_new], name='test_adagrad',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adagrad"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nepsilon = 1e-5\ndecay_factor = 0.1\n\nnode = onnx.helper.make_node('Adagrad',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'H1_new', 'H2_new'],\n norm_coefficient=norm_coefficient,\n epsilon=epsilon,\n decay_factor=decay_factor,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nh1 = np.array([2.0], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nh2 = np.array([4.0, 1.0], dtype=np.float32)\n\n# Compute expected outputs of Adagrad.\nx1_new, h1_new = apply_adagrad(r, t, x1, g1, h1,\n norm_coefficient, epsilon, decay_factor)\nx2_new, h2_new = apply_adagrad(r, t, x2, g2, h2,\n norm_coefficient, epsilon, decay_factor)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, h1, h2],\n outputs=[x1_new, x2_new, h1_new, h2_new], name='test_adagrad_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adagrad_multiple"}],"inputs":[{"description":"The initial learning rate.","name":"R","type":"T1"},{"description":"The update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"The current values of optimized tensors, followed by their respective gradients, followed by their respective accumulated squared gradients.For example, if two tensor \"X_1\" and \"X_2\" are optimized, The input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", accumulated squared gradient of \"X_1\", accumulated squared gradient of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"Updated values of optimized tensors, followed by their updated values of accumulated squared gradients. For example, if two tensor \"X_1\" and \"X_2\" are optimized, the output list would be [new value of \"X_1,\" new value of \"X_2\" new accumulated squared gradient of \"X_1\", new accumulated squared gradient of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T3"}]}},{"name":"Adam","schema":{"attributes":[{"default":0.8999999761581421,"description":"Coefficient of previously accumulated gradient in running average. Default to 0.9.","name":"alpha","required":false,"type":"float32"},{"default":0.9990000128746033,"description":"Coefficient of previously accumulated squared-gradient in running average. Default to 0.999.","name":"beta","required":false,"type":"float32"},{"default":9.999999974752427e-7,"description":"Small scalar to avoid dividing by zero.","name":"epsilon","required":false,"type":"float32"},{"description":"Regularization coefficient of 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient","required":false,"type":"float32"},{"description":"Regularization coefficient of 0.5 * norm_coefficient * ||X||_2^2. Default to 0, which means no regularization.","name":"norm_coefficient_post","required":false,"type":"float32"}],"description":"Compute one iteration of Adam, a stochastic gradient based optimization\n algorithm. This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. First of all, Adam requires\n some parameters:\n \n - The learning-rate \"R\".\n - The update count \"T\". That is, the number of training iterations conducted.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A small constant \"epsilon\" to avoid dividing-by-zero. \n - Two coefficients, \"alpha\" and \"beta\".\n\n At each Adam iteration, the optimized tensors are moved along a direction\n computed based on their exponentially-averaged historical gradient and\n exponentially-averaged historical squared gradient. Assume that only a tensor\n \"X\" is being optimized. The rest of required information is\n \n - the value of \"X\",\n - \"X\"'s gradient (denoted by \"G\"),\n - \"X\"'s exponentially-averaged historical gradient (denoted by \"V\"), and\n - \"X\"'s exponentially-averaged historical squared gradient (denoted by \"H\").\n\n Some of those parameters are passed into this operator as input tensors and others\n are stored as this operator's attributes. Specifically, this operator's input tensor\n list is [\"R\", \"T\", \"X\", \"G\", \"V\", \"H\"]. That is, \"R\" is the first input, \"T\" is\n the second input, and so on. Other parameters are given as attributes because they\n are constants. Moreover, the corresponding output tensors are \n \n - the new value of \"X\" (called \"X_new\"),\n - the new exponentially-averaged historical gradient (denoted by \"V_new\"), and\n - the new exponentially-averaged historical squared gradient (denoted by \"H_new\").\n\n Those outputs are computed following the pseudo code below.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise arithmetic operations with\n numpy-style broadcasting support. The pseudo code to compute those outputs is:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.\n G_regularized = norm_coefficient * X + G\n\n // Update exponentially-averaged historical gradient.\n V_new = alpha * V + (1 - alpha) * G_regularized\n\n // Update exponentially-averaged historical squared gradient.\n H_new = beta * H + (1 - beta) * G_regularized * G_regularized\n\n // Compute the element-wise square-root of H_new. V_new will be element-wisely\n // divided by H_sqrt for a better update direction.\n H_sqrt = Sqrt(H_new) + epsilon\n\n // Compute learning-rate. Note that \"alpha**T\"/\"beta**T\" is alpha's/beta's T-th power.\n R_adjusted = T > 0 ? R * Sqrt(1 - beta**T) / (1 - alpha**T) : R\n\n // Compute new value of \"X\".\n X_new = X - R_adjusted * V_new / H_sqrt\n\n // Post-update regularization.\n X_final = (1 - norm_coefficient_post) * X_new \n\n If there are multiple inputs to be optimized, the pseudo code will be applied\n independently to each of them.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.1\nepsilon = 1e-7\n\n# Create operator.\nnode = onnx.helper.make_node('Adam',\n inputs=['R', 'T', 'X', 'G', 'V', 'H'],\n outputs=['X_new', 'V_new', 'H_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n epsilon=epsilon,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\nh = np.array([0.1, 0.1], dtype=np.float32)\n\n# Compute expected outputs of Adam.\nx_new, v_new, h_new = apply_adam(r, t, x, g, v, h,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v, h],\n outputs=[x_new, v_new, h_new], name='test_adam',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adam"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.85\nepsilon = 1e-2\n\nnode = onnx.helper.make_node('Adam',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'V1', 'V2',\n 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'V1_new', 'V2_new',\n 'H1_new', 'H2_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nv1 = np.array([2.0], dtype=np.float32)\nh1 = np.array([0.5], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nv2 = np.array([4.0, 1.0], dtype=np.float32)\nh2 = np.array([1.0, 10.0], dtype=np.float32)\n\n# Compute expected outputs of Adam.\nx1_new, v1_new, h1_new = apply_adam(r, t, x1, g1, v1, h1,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\nx2_new, v2_new, h2_new = apply_adam(r, t, x2, g2, v2, h2,\n norm_coefficient, 0.0, alpha, beta,\n epsilon)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2, h1, h2],\n outputs=[x1_new, x2_new, v1_new, v2_new, h1_new, h2_new],\n name='test_adam_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"adam_multiple"}],"inputs":[{"description":"The initial learning rate.","name":"R","type":"T1"},{"description":"The update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"The tensors to be optimized, followed by their respective gradients, followed by their respective accumulated gradients (aka momentum), followed by their respective accumulated squared gradients. For example, to optimize tensors \"X_1\" and \"X_2,\", the input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", accumulated gradient of \"X_1\", accumulated gradient of \"X_2\", accumulated squared gradient of \"X_1\", accumulated squared gradient of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"New values of optimized tensors, followed by their respective new accumulated gradients, followed by their respective new accumulated squared gradients. For example, if two tensors \"X_1\" and \"X_2\" are optimized, the outputs list would be [new value of \"X_1\", new value of \"X_2\", new accumulated gradient of \"X_1\", new accumulated gradient of \"X_2\", new accumulated squared gradient of \"X_1\", new accumulated squared gradient of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T3"}]}},{"name":"Add","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary addition (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"description":"Performs element-wise binary addition (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Add","schema":{"description":"Performs element-wise binary addition (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add')","summary":"add"},{"code":"node = onnx.helper.make_node(\n 'Add',\n inputs=['x', 'y'],\n outputs=['sum'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nexpect(node, inputs=[x, y], outputs=[x + y],\n name='test_add_bcast')","summary":"add_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"And","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `and` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and4d')","summary":"and"},{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v4d')","summary":"and_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"And","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `and` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and4d')","summary":"and"},{"code":"node = onnx.helper.make_node(\n 'And',\n inputs=['x', 'y'],\n outputs=['and'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_and(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_and_bcast4v4d')","summary":"and_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices.","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the\nprovided axis. The resulted tensor has the same rank as the input if keepdims equal 1.\nIf keepdims equal 0, then the resulted tensor have the reduced dimension pruned.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the max \nis selected if the max appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMax","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the max elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the max \nis selected if the max appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# result: [[1], [1]]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmax_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0], [1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# result: [[0, 1]]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMax',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 1]]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmax_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmax_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices.","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the\nprovided axis. The resulted tensor has the same rank as the input if keepdims equal 1.\nIf keepdims equal 0, then the resulted tensor have the reduced dimension pruned.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the min \nis selected if the min appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArgMin","schema":{"attributes":[{"description":"The axis in which to compute the arg indices. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"},{"description":"Whether to select the last index or the first index if the {name} appears in multiple indices, default is False (first index).","name":"select_last_index","required":false,"type":"int64"}],"description":"Computes the indices of the min elements of the input tensor's element along the \nprovided axis. The resulting tensor has the same rank as the input if keepdims equal 1. \nIf keepdims equal 0, then the resulting tensor have the reduced dimension pruned. \nIf select_last_index is True (default False), the index of the last occurrence of the min \nis selected if the min appears more than once in the input. Otherwise the index of the \nfirst occurrence is selected.\nThe type of the output tensor is integer.","domain":"ai.onnx","examples":[{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims)\n\n# The content of result is : [[0], [0]]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random')","summary":"default_axes_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n keepdims=keepdims,\n select_last_index=True)\n\n# result: [[0, 0]]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [1, 3, 4]\nresult = argmin_use_numpy_select_last_index(data, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_default_axis_random_select_last_index')","summary":"default_axes_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random')","summary":"keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 1, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_keepdims_random_select_last_index')","summary":"keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1], [0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random')","summary":"negative_axis_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = -1\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1], [0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 3, 1]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_negative_axis_keepdims_random_select_last_index')","summary":"negative_axis_keepdims_select_last_index"},{"code":"data = np.array([[2, 1], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims)\n# The content of result is : [[1, 0]]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random')","summary":"no_keepdims"},{"code":"data = np.array([[2, 2], [3, 10]], dtype=np.float32)\naxis = 1\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ArgMin',\n inputs=['data'],\n outputs=['result'],\n axis=axis,\n keepdims=keepdims,\n select_last_index=True)\n# result: [[1, 0]]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_example_select_last_index')\n\ndata = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)\n# result's shape: [2, 4]\nresult = argmin_use_numpy_select_last_index(data, axis=axis, keepdims=keepdims)\nexpect(node, inputs=[data], outputs=[result], name='test_argmin_no_keepdims_random_select_last_index')","summary":"no_keepdims_select_last_index"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor with integer data type.","name":"reduced","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"ArrayFeatureExtractor","schema":{"description":"Select elements of the input tensor based on the indices passed.
    \n The indices are applied to the last axes of the tensor.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be selected","name":"X","type":"T"},{"description":"The indices, based on 0 as the first index of any dimension.","name":"Y","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Selected output data as an array","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)","tensor(string)"],"description":"The input must be a tensor of a numeric type or string. The output will be of the same tensor type.","type_param_str":"T"}]}},{"name":"Asin","schema":{"description":"Calculates the arcsine (inverse of sine) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Asin',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arcsin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asin_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32)\ny = np.arcsin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asin')","summary":"asin"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arcsine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Asinh","schema":{"description":"Calculates the hyperbolic arcsine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Asinh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.arcsinh(x) # expected output [-0.88137358, 0., 0.88137358]\nexpect(node, inputs=[x], outputs=[y],\n name='test_asinh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.arcsinh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_asinh')","summary":"asinh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arcsine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Atan","schema":{"description":"Calculates the arctangent (inverse of tangent) of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Atan',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.arctan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atan_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.arctan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atan')","summary":"atan"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The arctangent of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Atanh","schema":{"description":"Calculates the hyperbolic arctangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Atanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-0.5, 0, 0.5]).astype(np.float32)\ny = np.arctanh(x) # expected output [-0.54930615, 0., 0.54930615]\nexpect(node, inputs=[x], outputs=[y],\n name='test_atanh_example')\n\nx = np.random.uniform(0.0, 1.0, (3, 4, 5)).astype(np.float32)\ny = np.arctanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_atanh')","summary":"atanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic arctangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"AveragePool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.","name":"count_include_pad","required":false,"type":"int64"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"AveragePool consumes an input tensor X and applies average pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n average pooling consisting of computing the average on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_1d_default')","summary":"averagepool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [6, 7.5],\n [12, 13.5]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_ceil')","summary":"averagepool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_default')","summary":"averagepool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads')","summary":"averagepool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2],\n count_include_pad=1,\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = 2\npad_top = 2\npad_right = 2\npad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=0)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG', count_include_pad=1)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_pads_count_include_pad')","summary":"averagepool_2d_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 7.5, 8, 8.5, 9],\n [9.5, 10, 10.5, 11, 11.5],\n [12, 12.5, 13, 13.5, 14],\n [14.5, 15, 15.5, 16, 16.5],\n [17, 17.5, 18, 18.5, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads')","summary":"averagepool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2],\n count_include_pad=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[2.5200, 3.6000, 4.8000, 4.0800, 3.2400],\n [4.5600, 6.4000, 8.4000, 7.0400, 5.5200],\n [7.2000, 10.0000, 13.0000, 10.8000, 8.4000],\n [6.9600, 9.6000, 12.4000, 10.2400, 7.9200],\n [6.1200, 8.4000, 10.8000, 8.8800, 6.8400]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_pads_count_include_pad')","summary":"averagepool_2d_precomputed_pads_count_include_pad"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 5.5, 7],\n [11.5, 13, 14.5],\n [19, 20.5, 22]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_same_upper')","summary":"averagepool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[4, 6],\n [14, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_precomputed_strides')","summary":"averagepool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_lower')","summary":"averagepool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_same_upper')","summary":"averagepool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_2d_strides')","summary":"averagepool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'AveragePool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'AVG')\n\nexpect(node, inputs=[x], outputs=[y], name='test_averagepool_3d_default')","summary":"averagepool_3d_default"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":true,"type":"int64[]"},{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"},{"description":"If set to nonzero, run spatial batch normalization in test mode, default is 0.","name":"is_test","required":false,"type":"int64"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum), default is 0.9f.","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across all spatial elements If false, compute the mean and variance across per feature.Default is 1.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n ","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"The input 4-dimensional tensor of shape NCHW.","name":"X","type":"T"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"scale","type":"T"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"B","type":"T"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size C.","name":"mean","type":"T"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size C.","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output 4-dimensional tensor of the same shape as X.","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator. Must be in-place with the input mean. Should not be used for testing.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator. Must be in-place with the input var. Should not be used for testing.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"},{"description":"If set to nonzero, run spatial batch normalization in test mode, default is 0.","name":"is_test","required":false,"type":"int64"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum), default is 0.9f.","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across all spatial elements If false, compute the mean and variance across per feature.Default is 1.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"},{"description":"The scale as a 1-dimensional tensor of size C to be applied to the output.","name":"scale","type":"T"},{"description":"The bias as a 1-dimensional tensor of size C to be applied to the output.","name":"B","type":"T"},{"description":"The running mean (training) or the estimated mean (testing) as a 1-dimensional tensor of size C.","name":"mean","type":"T"},{"description":"The running variance (training) or the estimated variance (testing) as a 1-dimensional tensor of size C.","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X.","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator. Must be in-place with the input mean. Should not be used for testing.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator. Must be in-place with the input var. Should not be used for testing.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation. Should not be used for testing.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation. Should not be used for testing.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum).","name":"momentum","required":false,"type":"float32"},{"default":1,"description":"If true, compute the mean and variance across per activation. If false, compute the mean and variance across per feature over each mini-batch.","name":"spatial","required":false,"type":"int64"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\n https://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\n there are multiple cases for the number of outputs, which we list below:\n \n Output case #1: Y, mean, var, saved_mean, saved_var (training mode)\n Output case #2: Y (test mode)\n This operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"},{"description":"If spatial is true, the dimension of scale is (C). If spatial is false, the dimensions of scale are (C x D1 x ... x Dn)","name":"scale","type":"T"},{"description":"If spatial is true, the dimension of bias is (C). If spatial is false, the dimensions of bias are (C x D1 x ... x Dn)","name":"B","type":"T"},{"description":"If spatial is true, the dimension of the running mean (training) or the estimated mean (testing) is (C). If spatial is false, the dimensions of the running mean (training) or the estimated mean (testing) are (C x D1 x ... x Dn).","name":"mean","type":"T"},{"description":"If spatial is true, the dimension of the running variance(training) or the estimated variance (testing) is (C). If spatial is false, the dimensions of the running variance(training) or the estimated variance (testing) are (C x D1 x ... x Dn).","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"BatchNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"},{"default":0.8999999761581421,"description":"Factor used in computing the running mean and variance.e.g., running_mean = running_mean * momentum + mean * (1 - momentum).","name":"momentum","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out batch normalization as described in the paper\nhttps://arxiv.org/abs/1502.03167. Depending on the mode it is being run,\nthere are multiple cases for the number of outputs, which we list below:\n\nOutput case #1: Y, mean, var, saved_mean, saved_var (training mode)\nOutput case #2: Y (test mode)\n\nFor previous (depreciated) non-spatial cases, implementors are suggested\nto flatten the input shape to (N x C*D1*D2 ..*Dn) before a BatchNormalization Op.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"def _batchnorm_test_mode(x, s, bias, mean, var, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n mean = mean.reshape(-1, *dim_ones)\n var = var.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\nmean = np.array([0, 3]).astype(np.float32)\nvar = np.array([1, 1.5]).astype(np.float32)\ny = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nmean = np.random.randn(3).astype(np.float32)\nvar = np.random.rand(3).astype(np.float32)\nepsilon = 1e-2\ny = _batchnorm_test_mode(x, s, bias, mean, var, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'BatchNormalization',\n inputs=['x', 's', 'bias', 'mean', 'var'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias, mean, var], outputs=[y],\n name='test_batchnorm_epsilon')","summary":"batchnormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size, C is the number of channels. Statistics are computed for every channel of C over N and D1 to Dn dimensions. For image data, input dimensions become (N x C x H x W). The op also accepts single dimension input of size N in which case C is assumed to be 1","name":"X","type":"T"},{"description":"Scale tensor of shape (C).","name":"scale","type":"T"},{"description":"Bias tensor of shape (C).","name":"B","type":"T"},{"description":"running (training) or estimated (testing) mean tensor of shape (C).","name":"mean","type":"T"},{"description":"running (training) or estimated (testing) variance tensor of shape (C).","name":"var","type":"T"}],"max_input":5,"max_output":5,"min_input":5,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as X","name":"Y","type":"T"},{"description":"The running mean after the BatchNormalization operator.","name":"mean","option":"optional","type":"T"},{"description":"The running variance after the BatchNormalization operator.","name":"var","option":"optional","type":"T"},{"description":"Saved mean used during training to speed up gradient computation.","name":"saved_mean","option":"optional","type":"T"},{"description":"Saved variance used during training to speed up gradient computation.","name":"saved_var","option":"optional","type":"T"}],"outputs_range":"1 - 5","since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Binarizer","schema":{"attributes":[{"description":"Values greater than this are mapped to 1, others to 0.","name":"threshold","required":false,"type":"float32"}],"description":"Maps the values of the input tensor to either 0 or 1, element-wise, based on the outcome of a comparison against a threshold value.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be binarized","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Binarized output data","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type. The output will be of the same tensor type.","type_param_str":"T"}]}},{"name":"BitShift","schema":{"attributes":[{"description":"Direction of moving bits. It can be either \"RIGHT\" (for right shift) or \"LEFT\" (for left shift).","name":"direction","required":true,"type":"string"}],"description":"Bitwise shift operator performs element-wise operation. For each input element, if the\n attribute \"direction\" is \"RIGHT\", this operator moves its binary representation toward\n the right side so that the input value is effectively decreased. If the attribute \"direction\"\n is \"LEFT\", bits of binary representation moves toward the left side, which results the\n increase of its actual value. The input X is the tensor to be shifted and another input\n Y specifies the amounts of shifting. For example, if \"direction\" is \"Right\", X is [1, 4],\n and S is [1, 1], the corresponding output Z would be [0, 2]. If \"direction\" is \"LEFT\" with\n X=[1, 2] and S=[1, 2], the corresponding output Y would be [2, 8].\n \n Because this operator supports Numpy-style broadcasting, X's and Y's shapes are\n not necessarily identical.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint16)\ny = np.array([1, 2, 3]).astype(np.uint16)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint16')","summary":"left_unit16"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint32)\ny = np.array([1, 2, 3]).astype(np.uint32)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint32')","summary":"left_unit32"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint64)\ny = np.array([1, 2, 3]).astype(np.uint64)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint64')","summary":"left_unit64"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"LEFT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint8)\ny = np.array([1, 2, 3]).astype(np.uint8)\nz = x << y # expected output [32, 16, 8]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_left_uint8')","summary":"left_unit8"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint16)\ny = np.array([1, 2, 3]).astype(np.uint16)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint16')","summary":"right_unit16"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint32)\ny = np.array([1, 2, 3]).astype(np.uint32)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint32')","summary":"right_unit32"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint64)\ny = np.array([1, 2, 3]).astype(np.uint64)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint64')","summary":"right_unit64"},{"code":"node = onnx.helper.make_node(\n 'BitShift',\n inputs=['x', 'y'],\n outputs=['z'],\n direction=\"RIGHT\"\n)\n\nx = np.array([16, 4, 1]).astype(np.uint8)\ny = np.array([1, 2, 3]).astype(np.uint8)\nz = x >> y # expected output [8, 1, 0]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_bitshift_right_uint8')","summary":"right_unit8"}],"inputs":[{"description":"First operand, input to be shifted.","name":"X","type":"T"},{"description":"Second operand, amounts of shift.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Z","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)"],"description":"Constrain input and output types to integer tensors.","type_param_str":"T"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"string"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\nNOTE: Casting to and from strings is not supported yet.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Casting from strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Casting to strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\nNOTE: Casting to and from strings is not supported yet.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Casting from strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Casting to strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\n\nCasting from string tensor in plain (e.g., \"3.14\" and \"1000\") and scientific numeric representations\n(e.g., \"1e-5\" and \"1E8\") to float types is supported. For example, converting string \"100.5\" to an integer may\nresult 100. There are some string literals reserved for special floating-point values;\n\"+INF\" (and \"INF\"), \"-INF\", and \"NaN\" are positive infinity, negative infinity, and not-a-number, respectively.\nAny string which can exactly match \"+INF\" in a case-insensitive way would be mapped to positive infinite. Similarly,\nthis case-insensitive rule is applied to \"INF\" and \"NaN\". When casting from numeric tensors\nto string tensors, plain floating-point representation (such as \"314.15926\") would be used. \nConverting non-numerical-literal string such as \"Hello World!\" is an undefined behavior. Cases \nof converting string representing floating-point arithmetic value, such as \"2.718\", to INT is an undefined behavior.\n\nConversion from a numerical type to any numerical type is always allowed.\nUser must be aware of precision loss and value change caused by range difference between two types.\nFor example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting\nan integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)"],"description":"Constrain input types. Casting from complex is not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)"],"description":"Constrain output types. Casting to complex is not supported.","type_param_str":"T2"}]}},{"name":"Cast","schema":{"attributes":[{"description":"The data type to which the elements of the input tensor are cast. Strictly must be one of the types from DataType enum in TensorProto","name":"to","required":true,"type":"int64"}],"description":"The operator casts the elements of a given input tensor to a data type\nspecified by the 'to' argument and returns an output tensor of the same size in\nthe converted type. The 'to' argument must be one of the data types specified\nin the 'DataType' enum field in the TensorProto message.\n\nCasting from string tensor in plain (e.g., \"3.14\" and \"1000\") and scientific numeric representations\n(e.g., \"1e-5\" and \"1E8\") to float types is supported. For example, converting string \"100.5\" to an integer may\nresult 100. There are some string literals reserved for special floating-point values;\n\"+INF\" (and \"INF\"), \"-INF\", and \"NaN\" are positive infinity, negative infinity, and not-a-number, respectively.\nAny string which can exactly match \"+INF\" in a case-insensitive way would be mapped to positive infinite. Similarly,\nthis case-insensitive rule is applied to \"INF\" and \"NaN\". When casting from numeric tensors\nto string tensors, plain floating-point representation (such as \"314.15926\") would be used. \nConverting non-numerical-literal string such as \"Hello World!\" is an undefined behavior. Cases \nof converting string representing floating-point arithmetic value, such as \"2.718\", to INT is an undefined behavior.\n\nConversion from a numerical type to any numerical type is always allowed.\nUser must be aware of precision loss and value change caused by range difference between two types.\nFor example, a 64-bit float 3.1415926459 may be round to a 32-bit float 3.141592. Similarly, converting\nan integer 36 to Boolean may produce 1 because we truncate bits which can't be stored in the targeted type.\n","domain":"ai.onnx","examples":[{"code":"shape = (3, 4)\ntest_cases = [\n ('FLOAT', 'FLOAT16'),\n ('FLOAT', 'DOUBLE'),\n ('FLOAT16', 'FLOAT'),\n ('FLOAT16', 'DOUBLE'),\n ('DOUBLE', 'FLOAT'),\n ('DOUBLE', 'FLOAT16'),\n ('FLOAT', 'STRING'),\n ('STRING', 'FLOAT'),\n ('FLOAT', 'BFLOAT16'),\n ('BFLOAT16', 'FLOAT'),\n]\n\nfor from_type, to_type in test_cases:\n input_type = None\n output_type = None\n if 'BFLOAT16' == from_type or 'BFLOAT16' == to_type:\n np_fp32 = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.float32)\n little_endisan = sys.byteorder == 'little'\n np_uint16_view = np_fp32.view(dtype=np.uint16)\n np_bfp16 = np_uint16_view[1::2] if little_endisan else np_uint16_view[0::2]\n if 'BFLOAT16' == to_type:\n assert from_type == 'FLOAT'\n input = np_fp32.reshape([3, 4])\n output = np_bfp16.reshape([3, 4])\n input_type = int(TensorProto.FLOAT)\n output_type = int(TensorProto.BFLOAT16)\n else:\n assert to_type == 'FLOAT'\n input = np_bfp16.reshape([3, 4])\n #convert bfloat to FLOAT\n np_fp32_zeros = np.zeros((len(np_bfp16) * 2,), dtype=np.uint16)\n if little_endisan:\n np_fp32_zeros[1::2] = np_bfp16\n else:\n np_fp32_zeros[0::2] = np_bfp16\n np_fp32_from_bfloat = np_fp32_zeros.view(dtype=np.float32)\n output = np_fp32_from_bfloat.reshape([3, 4])\n input_type = int(TensorProto.BFLOAT16)\n output_type = int(TensorProto.FLOAT)\n elif 'STRING' != from_type:\n input = np.random.random_sample(shape).astype(\n TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, from_type)])\n if ('STRING' == to_type):\n # Converting input to str, then give it np.object dtype for generating script\n ss = []\n for i in input.flatten():\n s = str(i).encode('utf-8')\n su = s.decode('utf-8')\n ss.append(su)\n\n output = np.array(ss).astype(np.object).reshape([3, 4])\n else:\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n else:\n input = np.array([u'0.47892547', u'0.48033667', u'0.49968487', u'0.81910545',\n u'0.47031248', u'0.816468', u'0.21087195', u'0.7229038',\n u'NaN', u'INF', u'+INF', u'-INF'], dtype=np.dtype(np.object)).reshape([3, 4])\n output = input.astype(TENSOR_TYPE_TO_NP_TYPE[getattr(TensorProto, to_type)])\n node = onnx.helper.make_node(\n 'Cast',\n inputs=['input'],\n outputs=['output'],\n to=getattr(TensorProto, to_type),\n )\n if input_type and output_type:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type,\n input_types=[input_type],\n output_types=[output_type])\n else:\n expect(node, inputs=[input], outputs=[output],\n name='test_cast_' + from_type + '_to_' + to_type)","summary":"cast"}],"inputs":[{"description":"Input tensor to be cast.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with the same shape as input with type specified by the 'to' argument","name":"output","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)","tensor(bfloat16)"],"description":"Constrain input types. Casting from complex is not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)","tensor(string)","tensor(bfloat16)"],"description":"Constrain output types. Casting to complex is not supported.","type_param_str":"T2"}]}},{"name":"CastMap","schema":{"attributes":[{"default":"TO_FLOAT","description":"A string indicating the desired element type of the output tensor, one of 'TO_FLOAT', 'TO_STRING', 'TO_INT64'.","name":"cast_to","required":false,"type":"string"},{"default":"DENSE","description":"Indicates whether to only output as many values as are in the input (dense), or position the input based on using the key of the map as the index of the output (sparse).
    One of 'DENSE', 'SPARSE'.","name":"map_form","required":false,"type":"string"},{"default":1,"description":"If the value of map_form is 'SPARSE,' this attribute indicates the total length of the output tensor.","name":"max_map","required":false,"type":"int64"}],"description":"Converts a map to a tensor.
    The map key must be an int64 and the values will be ordered\n in ascending order based on this key.
    The operator supports dense packing or sparse packing.\n If using sparse packing, the key cannot exceed the max_map-1 value.\n","domain":"ai.onnx.ml","inputs":[{"description":"The input map that is to be cast to a tensor","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A tensor representing the same data as the input map, ordered by their keys","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["map(int64, string)","map(int64, float)"],"description":"The input must be an integer map to either string or float.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(float)","tensor(int64)"],"description":"The output is a 1-D tensor of string, float, or integer.","type_param_str":"T2"}]}},{"name":"CategoryMapper","schema":{"attributes":[{"description":"The integers of the map. This sequence must be the same length as the 'cats_strings' sequence.","name":"cats_int64s","required":false,"type":"int64[]"},{"description":"The strings of the map. This sequence must be the same length as the 'cats_int64s' sequence","name":"cats_strings","required":false,"type":"string[]"},{"default":-1,"description":"An integer to use when an input string value is not found in the map.
    One and only one of the 'default_*' attributes must be defined.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string to use when an input integer value is not found in the map.
    One and only one of the 'default_*' attributes must be defined.","name":"default_string","required":false,"type":"string"}],"description":"Converts strings to integers and vice versa.
    \n Two sequences of equal length are used to map between integers and strings,\n with strings and integers at the same index detailing the mapping.
    \n Each operator converts either integers to strings or strings to integers, depending \n on which default value attribute is provided. Only one default value attribute\n should be defined.
    \n If the string default value is set, it will convert integers to strings.\n If the int default value is set, it will convert strings to integers.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input data","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data. If strings are input, the output values are integers, and vice versa.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The input must be a tensor of strings or integers, either [N,C] or [C].","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output is a tensor of strings or integers. Its shape will be the same as the input shape.","type_param_str":"T2"}]}},{"name":"Ceil","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Ceil","schema":{"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Ceil","schema":{"description":"Ceil takes one input data (Tensor) and produces one output data\n(Tensor) where the ceil is, y = ceil(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Ceil',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2]).astype(np.float32)\ny = np.ceil(x) # expected output [-1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.ceil(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_ceil')","summary":"ceil"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Celu","schema":{"attributes":[{"default":1,"description":"The Alpha value in Celu formula which control the shape of the unit. The default value is 1.0.","name":"alpha","required":false,"type":"float32"}],"description":"Continuously Differentiable Exponential Linear Units:\nPerform the linear unit element-wise on the input tensor X\nusing formula: \n\n```\nmax(0,x) + min(0,alpha*(exp(x/alpha)-1))\n```\n","domain":"ai.onnx","examples":[{"code":"alpha = 2.0\nnode = onnx.helper.make_node(\n 'Celu',\n inputs=['X'],\n outputs=['Y'],\n alpha=alpha,\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\npositive_input = np.maximum(0, input_data)\nnegative_input = np.minimum(0, alpha * (np.exp(input_data / alpha) - 1))\nexpected_output = positive_input + negative_input\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_celu')","summary":"celu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)"],"description":"Constrain input and output types to float32 tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"Maximum value, above which element is replaced by max","name":"max","required":false,"type":"float32"},{"description":"Minimum value, under which element is replaced by min","name":"min","required":false,"type":"float32"}],"description":"Clip operator limits the given input within an interval. The interval is\nspecified with arguments 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max() respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"attributes":[{"default":3.4028234663852886e+38,"description":"Maximum value, above which element is replaced by max","name":"max","required":false,"type":"float32"},{"default":-3.4028234663852886e+38,"description":"Minimum value, under which element is replaced by min","name":"min","required":false,"type":"float32"}],"description":"Clip operator limits the given input within an interval. The interval is\nspecified with arguments 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max() respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Clip","schema":{"description":"Clip operator limits the given input within an interval. The interval is\nspecified by the inputs 'min' and 'max'. They default to\nnumeric_limits::lowest() and numeric_limits::max(), respectively.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nx = np.array([-2, 0, 2]).astype(np.float32)\nmin_val = np.float32(-1)\nmax_val = np.float32(1)\ny = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, max_val)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip')\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min', 'max'],\n outputs=['y'],\n)\n\nmin_val = np.float32(-5)\nmax_val = np.float32(5)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_inbounds')\n\nx = np.array([-6, 0, 6]).astype(np.float32)\ny = np.array([-5, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_outbounds')\n\nx = np.array([-1, 0, 6]).astype(np.float32)\ny = np.array([-1, 0, 5]).astype(np.float32)\nexpect(node, inputs=[x, min_val, max_val], outputs=[y],\n name='test_clip_splitbounds')","summary":"clip"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, min_val, np.inf)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.float32(0)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, -np.inf, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-1, 0, 1]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_inbounds')","summary":"clip_default"},{"code":"node = onnx.helper.make_node(\n 'Clip',\n inputs=['x', 'min'],\n outputs=['y'],\n)\nmin_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, min_val, np.iinfo(np.int8).max)\nexpect(node, inputs=[x, min_val], outputs=[y],\n name='test_clip_default_int8_min')\n\nno_min = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, 'max'],\n outputs=['y'],\n)\nmax_val = np.int8(0)\nx = np.random.randn(3, 4, 5).astype(np.int8)\ny = np.clip(x, np.iinfo(np.int8).min, max_val)\nexpect(node, inputs=[x, max_val], outputs=[y],\n name='test_clip_default_int8_max')\n\nno_max = \"\" # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Clip',\n inputs=['x', no_min, no_max],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.int8)\ny = np.array([-1, 0, 1]).astype(np.int8)\nexpect(node, inputs=[x], outputs=[y],\n name='test_clip_default_int8_inbounds')","summary":"clip_default_int8"}],"inputs":[{"description":"Input tensor whose elements to be clipped","name":"input","type":"T"},{"description":"Minimum value, under which element is replaced by min. It must be a scalar(tensor of empty shape).","name":"min","option":"optional","type":"T"},{"description":"Maximum value, above which element is replaced by max. It must be a scalar(tensor of empty shape).","name":"max","option":"optional","type":"T"}],"inputs_range":"1 - 3","max_input":3,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with clipped input elements","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Compress","schema":{"attributes":[{"description":"(Optional) Axis along which to take slices. If not specified, input is flattened before elements being selected.","name":"axis","required":false,"type":"int64"}],"description":"Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index.\n In case axis is not provided, input is flattened before elements are selected.\n Compress behaves like numpy.compress: https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=0,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 1])\noutput = np.compress(condition, input, axis=0)\n#print(output)\n#[[ 3. 4.]\n# [ 5. 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_0')","summary":"compress_0"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=1)\n#print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_1')","summary":"compress_1"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 0, 0, 1])\noutput = np.compress(condition, input)\n#print(output)\n#[ 2., 5.]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_default_axis')","summary":"compress_default_axis"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=-1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=-1)\n# print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_negative_axis')","summary":"compress_negative_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"input","type":"T"},{"description":"Rank 1 tensor of booleans to indicate which slices or data elements to be selected. Its length can be less than the input length alone the axis or the flattened input size if axis is not specified. In such cases data slices or elements exceeding the condition length are discarded.","name":"condition","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank r if axis is specified. Otherwise output is a Tensor of rank 1.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains to boolean tensors.","type_param_str":"T1"}]}},{"name":"Compress","schema":{"attributes":[{"description":"(Optional) Axis along which to take slices. If not specified, input is flattened before elements being selected. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"Selects slices from an input tensor along a given axis where condition evaluates to True for each axis index.\n In case axis is not provided, input is flattened before elements are selected.\n Compress behaves like numpy.compress: https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=0,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 1])\noutput = np.compress(condition, input, axis=0)\n#print(output)\n#[[ 3. 4.]\n# [ 5. 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_0')","summary":"compress_0"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=1)\n#print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_1')","summary":"compress_1"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1, 0, 0, 1])\noutput = np.compress(condition, input)\n#print(output)\n#[ 2., 5.]\n\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_default_axis')","summary":"compress_default_axis"},{"code":"node = onnx.helper.make_node(\n 'Compress',\n inputs=['input', 'condition'],\n outputs=['output'],\n axis=-1,\n)\ninput = np.array([[1, 2], [3, 4], [5, 6]]).astype(np.float32)\ncondition = np.array([0, 1])\noutput = np.compress(condition, input, axis=-1)\n# print(output)\n#[[ 2.]\n# [ 4.]\n# [ 6.]]\nexpect(node, inputs=[input, condition.astype(np.bool)], outputs=[output],\n name='test_compress_negative_axis')","summary":"compress_negative_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"input","type":"T"},{"description":"Rank 1 tensor of booleans to indicate which slices or data elements to be selected. Its length can be less than the input length along the axis or the flattened input size if axis is not specified. In such cases data slices or elements exceeding the condition length are discarded.","name":"condition","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank r if axis is specified. Otherwise output is a Tensor of rank 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains to boolean tensors.","type_param_str":"T1"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. Default value is 1.","name":"axis","required":false,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":4,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. A negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(inputs)..","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor. All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Concat","schema":{"attributes":[{"description":"Which axis to concat on. A negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(inputs)..","name":"axis","required":true,"type":"int64"}],"category":"Tensor","description":"Concatenate a list of tensors into a single tensor. All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.","domain":"ai.onnx","examples":[{"code":"test_cases = {\n '1d': ([1, 2],\n [3, 4]),\n '2d': ([[1, 2], [3, 4]],\n [[5, 6], [7, 8]]),\n '3d': ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]],\n [[[9, 10], [11, 12]], [[13, 14], [15, 16]]])\n} # type: Dict[Text, Sequence[Any]]\n\nfor test_case, values_ in test_cases.items():\n values = [np.asarray(v, dtype=np.float32) for v in values_]\n for i in range(len(values[0].shape)):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_' + str(i))\n\n for i in range(-len(values[0].shape), 0):\n in_args = ['value' + str(k) for k in range(len(values))]\n node = onnx.helper.make_node(\n 'Concat',\n inputs=[s for s in in_args],\n outputs=['output'],\n axis=i\n )\n output = np.concatenate(values, i)\n expect(node, inputs=[v for v in values], outputs=[output],\n name='test_concat_' + test_case + '_axis_negative_' + str(abs(i)))","summary":"concat"}],"inputs":[{"description":"List of tensors for concatenation","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"ConcatFromSequence","schema":{"attributes":[{"description":"Which axis to concat on. Accepted range in `[-r, r - 1]`, where `r` is the rank of input tensors. When `new_axis` is 1, accepted range is `[-r - 1, r]`. ","name":"axis","required":true,"type":"int64"},{"description":"Insert and concatenate on a new axis or not, default 0 means do not insert new axis.","name":"new_axis","required":false,"type":"int64"}],"description":"Concatenate a sequence of tensors into a single tensor.\nAll input tensors must have the same shape, except for the dimension size of the axis to concatenate on.\nBy default 'new_axis' is 0, the behavior is similar to numpy.concatenate.\nWhen 'new_axis' is 1, the behavior is similar to numpy.stack.\n","domain":"ai.onnx","inputs":[{"description":"Sequence of tensors for concatenation","name":"input_sequence","type":"S"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Concatenated tensor","name":"concat_result","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain input types to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain output types to any tensor type.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","required":true,"type":"tensor"}],"category":"Constant","description":"A constant tensor.","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor.","name":"value","required":true,"type":"tensor"}],"category":"Constant","description":"A constant tensor.","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"}],"category":"Constant","description":"A constant tensor. Exactly one of the two attributes, either value or sparse_value,\nmust be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"},{"description":"The value for the sole element for the scalar, float32, output tensor.","name":"value_float","required":false,"type":"float32"},{"description":"The values for the elements for the 1D, float32, output tensor.","name":"value_floats","required":false,"type":"float32[]"},{"description":"The value for the sole element for the scalar, int64, output tensor.","name":"value_int","required":false,"type":"int64"},{"description":"The values for the elements for the 1D, int64, output tensor.","name":"value_ints","required":false,"type":"int64[]"},{"description":"The value for the sole element for the scalar, UTF-8 string, output tensor.","name":"value_string","required":false,"type":"string"},{"description":"The values for the elements for the 1D, UTF-8 string, output tensor.","name":"value_strings","required":false,"type":"string[]"}],"category":"Constant","description":"This operator produces a constant tensor. Exactly one of the provided attributes, either value, sparse_value,\nor value_* must be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Constant","schema":{"attributes":[{"description":"The value for the elements of the output tensor in sparse format.","name":"sparse_value","required":false},{"description":"The value for the elements of the output tensor.","name":"value","required":false,"type":"tensor"},{"description":"The value for the sole element for the scalar, float32, output tensor.","name":"value_float","required":false,"type":"float32"},{"description":"The values for the elements for the 1D, float32, output tensor.","name":"value_floats","required":false,"type":"float32[]"},{"description":"The value for the sole element for the scalar, int64, output tensor.","name":"value_int","required":false,"type":"int64"},{"description":"The values for the elements for the 1D, int64, output tensor.","name":"value_ints","required":false,"type":"int64[]"},{"description":"The value for the sole element for the scalar, UTF-8 string, output tensor.","name":"value_string","required":false,"type":"string"},{"description":"The values for the elements for the 1D, UTF-8 string, output tensor.","name":"value_strings","required":false,"type":"string[]"}],"category":"Constant","description":"This operator produces a constant tensor. Exactly one of the provided attributes, either value, sparse_value,\nor value_* must be specified.\n","domain":"ai.onnx","examples":[{"code":"values = np.random.randn(5, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=['values'],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=onnx.TensorProto.FLOAT,\n dims=values.shape,\n vals=values.flatten().astype(float),\n ),\n)\n\nexpect(node, inputs=[], outputs=[values],\n name='test_constant')","summary":"constant"}],"max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor containing the same value of the provided tensor.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"ConstantOfShape","schema":{"attributes":[{"description":"(Optional) The value of the output elements.Should be a one-element tensor. If not specified, it defaults to a tensor of value 0 and datatype float32","name":"value","required":false,"type":"tensor"}],"description":"Generate a tensor with given value and shape.\n","domain":"ai.onnx","examples":[{"code":"x = np.array([4, 3, 2]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.FLOAT,\n [1], [1])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\n\ny = np.ones(x, dtype=np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_float_ones')","summary":"float_ones"},{"code":"x = np.array([0, ]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.INT32,\n [1], [0])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\ny = np.zeros(x, dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_int_shape_zero')","summary":"int32_shape_zero"},{"code":"x = np.array([10, 6]).astype(np.int64)\ntensor_value = onnx.helper.make_tensor(\"value\", onnx.TensorProto.INT32,\n [1], [0])\nnode = onnx.helper.make_node(\n 'ConstantOfShape',\n inputs=['x'],\n outputs=['y'],\n value=tensor_value,\n)\ny = np.zeros(x, dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_constantofshape_int_zeros')","summary":"int32_zeros"}],"inputs":[{"description":"1D tensor. The shape of the expected output tensor. If empty tensor is given, the output would be a scalar. All values must be >= 0.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of shape specified by 'input'.If attribute 'value' is specified, the value and datatype of the output tensor is taken from 'value'.If attribute 'value' is not specified, the value in the output defaults to 0, and the datatype defaults to float32.","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types to be numerics.","type_param_str":"T2"}]}},{"name":"Conv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution operator consumes an input tensor and a filter, and\ncomputes the output.","domain":"ai.onnx","examples":[{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[1, 1, 1, 1],\n)\ny_with_padding = np.array([[[[12., 21., 27., 33., 24.], # (1, 1, 5, 5) output tensor\n [33., 54., 63., 72., 51.],\n [63., 99., 108., 117., 81.],\n [93., 144., 153., 162., 111.],\n [72., 111., 117., 123., 84.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_basic_conv_with_padding')\n\n# Convolution without padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[0, 0, 0, 0],\n)\ny_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor\n [99., 108., 117.],\n [144., 153., 162.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_basic_conv_without_padding')","summary":"conv"},{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 7, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with strides=2 and padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 1, 1, 1],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_padding = np.array([[[[12., 27., 24.], # (1, 1, 4, 3) output tensor\n [63., 108., 81.],\n [123., 198., 141.],\n [112., 177., 124.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_conv_with_strides_padding')\n\n# Convolution with strides=2 and no padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[0, 0, 0, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_without_padding = np.array([[[[54., 72.], # (1, 1, 3, 2) output tensor\n [144., 162.],\n [234., 252.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_conv_with_strides_no_padding')\n\n# Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor)\nnode_with_asymmetric_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 0, 1, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_asymmetric_padding = np.array([[[[21., 33.], # (1, 1, 4, 2) output tensor\n [99., 117.],\n [189., 207.],\n [171., 183.]]]]).astype(np.float32)\nexpect(node_with_asymmetric_padding, inputs=[x, W], outputs=[y_with_asymmetric_padding],\n name='test_conv_with_strides_and_asymmetric_padding')","summary":"conv_with_strides"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Conv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults is 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults is 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution operator consumes an input tensor and a filter, and\ncomputes the output.","domain":"ai.onnx","examples":[{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 5, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[1, 1, 1, 1],\n)\ny_with_padding = np.array([[[[12., 21., 27., 33., 24.], # (1, 1, 5, 5) output tensor\n [33., 54., 63., 72., 51.],\n [63., 99., 108., 117., 81.],\n [93., 144., 153., 162., 111.],\n [72., 111., 117., 123., 84.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_basic_conv_with_padding')\n\n# Convolution without padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n # Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1\n pads=[0, 0, 0, 0],\n)\ny_without_padding = np.array([[[[54., 63., 72.], # (1, 1, 3, 3) output tensor\n [99., 108., 117.],\n [144., 153., 162.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_basic_conv_without_padding')","summary":"conv"},{"code":"\nx = np.array([[[[0., 1., 2., 3., 4.], # (1, 1, 7, 5) input tensor\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.],\n [20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.]]]]).astype(np.float32)\nW = np.array([[[[1., 1., 1.], # (1, 1, 3, 3) tensor for convolution weights\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\n# Convolution with strides=2 and padding\nnode_with_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 1, 1, 1],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_padding = np.array([[[[12., 27., 24.], # (1, 1, 4, 3) output tensor\n [63., 108., 81.],\n [123., 198., 141.],\n [112., 177., 124.]]]]).astype(np.float32)\nexpect(node_with_padding, inputs=[x, W], outputs=[y_with_padding],\n name='test_conv_with_strides_padding')\n\n# Convolution with strides=2 and no padding\nnode_without_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[0, 0, 0, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_without_padding = np.array([[[[54., 72.], # (1, 1, 3, 2) output tensor\n [144., 162.],\n [234., 252.]]]]).astype(np.float32)\nexpect(node_without_padding, inputs=[x, W], outputs=[y_without_padding],\n name='test_conv_with_strides_no_padding')\n\n# Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor)\nnode_with_asymmetric_padding = onnx.helper.make_node(\n 'Conv',\n inputs=['x', 'W'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[1, 0, 1, 0],\n strides=[2, 2], # Default values for other attributes: dilations=[1, 1], groups=1\n)\ny_with_asymmetric_padding = np.array([[[[21., 33.], # (1, 1, 4, 2) output tensor\n [99., 117.],\n [189., 207.],\n [171., 183.]]]]).astype(np.float32)\nexpect(node_with_asymmetric_padding, inputs=[x, W], outputs=[y_with_asymmetric_padding],\n name='test_conv_with_strides_and_asymmetric_padding')","summary":"conv_with_strides"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ConvInteger","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into. default is 1.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input 'w'.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0.The value represent the number of pixels added to the beginning and end part of the corresponding axis.`pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number ofpixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaultsto 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The integer convolution operator consumes an input tensor, its zero-point, a filter, and its zero-point,\nand computes the output. The production MUST never overflow. The accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"\nx = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10]).astype(np.uint8).reshape((1, 1, 3, 3))\nx_zero_point = np.uint8(1)\nw = np.array([1, 1, 1, 1]).astype(np.uint8).reshape((1, 1, 2, 2))\n\ny = np.array([12, 16, 24, 28]).astype(np.int32).reshape(1, 1, 2, 2)\n\n# ConvInteger without padding\nconvinteger_node = onnx.helper.make_node('ConvInteger',\n inputs=['x', 'w', 'x_zero_point'],\n outputs=['y'])\n\nexpect(convinteger_node, inputs=[x, w, x_zero_point], outputs=[y],\n name='test_basic_convinteger')\n\n# ConvInteger with padding\ny_with_padding = np.array([1, 3, 5, 3, 5, 12, 16, 9, 11, 24, 28, 15, 7, 15, 17, 9]).astype(np.int32).reshape((1, 1, 4, 4))\n\nconvinteger_node_with_padding = onnx.helper.make_node('ConvInteger',\n inputs=['x', 'w', 'x_zero_point'],\n outputs=['y'],\n pads=[1, 1, 1, 1],)\n\nexpect(convinteger_node_with_padding, inputs=[x, w, x_zero_point], outputs=[y_with_padding],\n name='test_convinteger_with_padding')","summary":"convinteger"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"x","type":"T1"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"w","type":"T2"},{"description":"Zero point tensor for input 'x'. It's optional and default value is 0. It's a scalar, which means a per-tensor/layer quantization.","name":"x_zero_point","option":"optional","type":"T1"},{"description":"Zero point tensor for input 'w'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M)","name":"w_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 4","max_input":4,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input x and its zero point data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input w and its zero point data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain output y data type to 32-bit integer tensor.","type_param_str":"T3"}]}},{"name":"ConvTranspose","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"The zero-padding added to one side of the output. This is also called adjs/adjustment in some frameworks.","name":"output_padding","required":false,"type":"int64[]"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If output_shape is specified pads values are ignored. See doc for details for equations to generate pads","name":"output_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution transpose operator consumes an input tensor and a filter,\nand computes the output.\n\nIf the pads parameter is provided the shape of the output is calculated via the following equation:\n\n output_shape[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - pads[start_i] - pads[end_i]\n\noutput_shape can also be explicitly specified in which case pads values are auto generated using these equations:\n\n total_padding[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]\n If (auto_pads != SAME_UPPER): pads[start_i] = total_padding[i]/2; pads[end_i] = total_padding[i] - (total_padding[i]/2)\n Else: pads[start_i] = total_padding[i] - (total_padding[i]/2); pads[end_i] = (total_padding[i]/2).\n\n ","domain":"ai.onnx","examples":[{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[0., 1., 3., 3., 2.], # (1, 2, 5, 5)\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]],\n\n [[0., 1., 3., 3., 2.],\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose')","summary":"convtranspose"},{"code":"x = np.array([[[0., 1., 2.]]]).astype(np.float32) # (1, 1, 3)\n\nW = np.array([[[1., 1., 1.], # (1, 2, 3)\n [1., 1., 1.]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[0., 1., 3., 3., 2.], # (1, 2, 5)\n [0., 1., 3., 3., 2.]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_1d')","summary":"convtranspose_1d"},{"code":"x = np.array([[[[[0., 1., 2., 3., 4.], # (1, 1, 3, 4, 5)\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.]],\n [[20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.],\n [35., 36., 37., 38., 39.]],\n [[40., 41., 42., 43., 44.],\n [45., 46., 47., 48., 49.],\n [50., 51., 52., 53., 54.],\n [55., 56., 57., 58., 59.]]]]]).astype(np.float32)\n\nW = np.array([[[[[1., 1., 1.], # (1, 2, 3, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]],\n [[[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[[0., 1., 3., 6., 9., 7., 4.], # (1, 2, 5, 6, 7)\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]],\n\n [[[0., 1., 3., 6., 9., 7., 4.],\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_3d')","summary":"convtranspose_3d"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\ny = np.array([[[[0., 0., 1., 1., 3., 2., 2., 0.], # (1, 2, 10, 8)\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]],\n\n [[0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_shape=[10, 8])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_output_shape')\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_padding=[1, 1])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pad')\n\nnode = onnx.helper.make_node(\n 'ConvTranspose', ['X', 'W'], ['Y'],\n name='test',\n strides=[3, 2],\n output_shape=[10, 8],\n kernel_shape=[3, 3],\n output_padding=[1, 1]\n)\nexpect(node, inputs=[x, W], outputs=[y],\n name='test_convtranspose_kernel_shape')","summary":"convtranspose_attributes"},{"code":"x = np.array([[[[3., 8., 1.], # (1, 1, 3, 3)\n [9., 5., 7.],\n [3., 2., 6.]]]]).astype(np.float32)\nW = np.array([[[[7., 2.], # (1, 1, 2, 2)\n [1., 9.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"], dilations=[2, 2])\n\ny = np.array([[[[21., 56., 13., 16., 2.], # [1, 1, 5, 5]\n [63., 35., 67., 10., 14.],\n [24., 22., 76., 76., 21.],\n [9., 5., 88., 45., 63.],\n [3., 2., 33., 18., 54.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_dilations')","summary":"convtranspose_dilations"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n pads=[1, 2, 1, 2])\n\ny = np.array([[[[1., 1., 3.], # (1, 2, 7, 3)\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]],\n\n [[1., 1., 3.],\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pads')","summary":"convtranspose_pads"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn)","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn), where (k1 x k2 x ... x kn) is the dimension of the kernel. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, pad lengths and group count. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ConvTranspose","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input W.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Additional elements added to the side with higher coordinate indices in the output. Each padding value in \"output_padding\" must be less than the corresponding stride/dilation dimension. By default, this attribute is a zero vector. Note that this attribute doesn't directly affect the computed output values. It only controls the selection of the computed values, so changing this attribute only adds or removes output elements. If \"output_shape\" is explicitly provided, \"output_padding\" does not contribute additional size to \"output_shape\" but participates in the computation of the needed padding amount. This is also called adjs or adjustment in some frameworks.","name":"output_padding","required":false,"type":"int64[]"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If output_shape is specified pads values are ignored. See doc for details for equations to generate pads","name":"output_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Layer","description":"The convolution transpose operator consumes an input tensor and a filter,\nand computes the output.\n\nIf the pads parameter is provided the shape of the output is calculated via the following equation:\n\n output_shape[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - pads[start_i] - pads[end_i]\n\noutput_shape can also be explicitly specified in which case pads values are auto generated using these equations:\n\n total_padding[i] = stride[i] * (input_size[i] - 1) + output_padding[i] + ((kernel_shape[i] - 1) * dilations[i] + 1) - output_shape[i]\n If (auto_pads != SAME_UPPER): pads[start_i] = total_padding[i]/2; pads[end_i] = total_padding[i] - (total_padding[i]/2)\n Else: pads[start_i] = total_padding[i] - (total_padding[i]/2); pads[end_i] = (total_padding[i]/2).\n\n ","domain":"ai.onnx","examples":[{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[0., 1., 3., 3., 2.], # (1, 2, 5, 5)\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]],\n\n [[0., 1., 3., 3., 2.],\n [3., 8., 15., 12., 7.],\n [9., 21., 36., 27., 15.],\n [9., 20., 33., 24., 13.],\n [6., 13., 21., 15., 8.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose')","summary":"convtranspose"},{"code":"x = np.array([[[0., 1., 2.]]]).astype(np.float32) # (1, 1, 3)\n\nW = np.array([[[1., 1., 1.], # (1, 2, 3)\n [1., 1., 1.]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[0., 1., 3., 3., 2.], # (1, 2, 5)\n [0., 1., 3., 3., 2.]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_1d')","summary":"convtranspose_1d"},{"code":"x = np.array([[[[[0., 1., 2., 3., 4.], # (1, 1, 3, 4, 5)\n [5., 6., 7., 8., 9.],\n [10., 11., 12., 13., 14.],\n [15., 16., 17., 18., 19.]],\n [[20., 21., 22., 23., 24.],\n [25., 26., 27., 28., 29.],\n [30., 31., 32., 33., 34.],\n [35., 36., 37., 38., 39.]],\n [[40., 41., 42., 43., 44.],\n [45., 46., 47., 48., 49.],\n [50., 51., 52., 53., 54.],\n [55., 56., 57., 58., 59.]]]]]).astype(np.float32)\n\nW = np.array([[[[[1., 1., 1.], # (1, 2, 3, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]],\n [[[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"])\n\ny = np.array([[[[[0., 1., 3., 6., 9., 7., 4.], # (1, 2, 5, 6, 7)\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]],\n\n [[[0., 1., 3., 6., 9., 7., 4.],\n [5., 12., 21., 27., 33., 24., 13.],\n [15., 33., 54., 63., 72., 51., 27.],\n [30., 63., 99., 108., 117., 81., 42.],\n [25., 52., 81., 87., 93., 64., 33.],\n [15., 31., 48., 51., 54., 37., 19.]],\n\n [[20., 42., 66., 72., 78., 54., 28.],\n [50., 104., 162., 174., 186., 128., 66.],\n [90., 186., 288., 306., 324., 222., 114.],\n [120., 246., 378., 396., 414., 282., 144.],\n [90., 184., 282., 294., 306., 208., 106.],\n [50., 102., 156., 162., 168., 114., 58.]],\n\n [[60., 123., 189., 198., 207., 141., 72.],\n [135., 276., 423., 441., 459., 312., 159.],\n [225., 459., 702., 729., 756., 513., 261.],\n [270., 549., 837., 864., 891., 603., 306.],\n [195., 396., 603., 621., 639., 432., 219.],\n [105., 213., 324., 333., 342., 231., 117.]],\n\n [[60., 122., 186., 192., 198., 134., 68.],\n [130., 264., 402., 414., 426., 288., 146.],\n [210., 426., 648., 666., 684., 462., 234.],\n [240., 486., 738., 756., 774., 522., 264.],\n [170., 344., 522., 534., 546., 368., 186.],\n [90., 182., 276., 282., 288., 194., 98.]],\n\n [[40., 81., 123., 126., 129., 87., 44.],\n [85., 172., 261., 267., 273., 184., 93.],\n [135., 273., 414., 423., 432., 291., 147.],\n [150., 303., 459., 468., 477., 321., 162.],\n [105., 212., 321., 327., 333., 224., 113.],\n [55., 111., 168., 171., 174., 117., 59.]]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_3d')","summary":"convtranspose_3d"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\ny = np.array([[[[0., 0., 1., 1., 3., 2., 2., 0.], # (1, 2, 10, 8)\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]],\n\n [[0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [0., 0., 1., 1., 3., 2., 2., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [3., 3., 7., 4., 9., 5., 5., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [6., 6., 13., 7., 15., 8., 8., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_shape=[10, 8])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_output_shape')\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n output_padding=[1, 1])\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pad')\n\nnode = onnx.helper.make_node(\n 'ConvTranspose', ['X', 'W'], ['Y'],\n name='test',\n strides=[3, 2],\n output_shape=[10, 8],\n kernel_shape=[3, 3],\n output_padding=[1, 1]\n)\nexpect(node, inputs=[x, W], outputs=[y],\n name='test_convtranspose_kernel_shape')","summary":"convtranspose_attributes"},{"code":"x = np.array([[[[3., 8., 1.], # (1, 1, 3, 3)\n [9., 5., 7.],\n [3., 2., 6.]]]]).astype(np.float32)\nW = np.array([[[[7., 2.], # (1, 1, 2, 2)\n [1., 9.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"], dilations=[2, 2])\n\ny = np.array([[[[21., 56., 13., 16., 2.], # [1, 1, 5, 5]\n [63., 35., 67., 10., 14.],\n [24., 22., 76., 76., 21.],\n [9., 5., 88., 45., 63.],\n [3., 2., 33., 18., 54.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_dilations')","summary":"convtranspose_dilations"},{"code":"x = np.array([[[[0., 1., 2.], # (1, 1, 3, 3)\n [3., 4., 5.],\n [6., 7., 8.]]]]).astype(np.float32)\n\nW = np.array([[[[1., 1., 1.], # (1, 2, 3, 3)\n [1., 1., 1.],\n [1., 1., 1.]],\n [[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]]]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\"ConvTranspose\", [\"X\", \"W\"], [\"Y\"],\n strides=[3, 2],\n pads=[1, 2, 1, 2])\n\ny = np.array([[[[1., 1., 3.], # (1, 2, 7, 3)\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]],\n\n [[1., 1., 3.],\n [1., 1., 3.],\n [7., 4., 9.],\n [7., 4., 9.],\n [7., 4., 9.],\n [13., 7., 15.],\n [13., 7., 15.]]]]).astype(np.float32)\n\nexpect(node, inputs=[x, W], outputs=[y], name='test_convtranspose_pads')","summary":"convtranspose_pads"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn)","name":"X","type":"T"},{"description":"The weight tensor that will be used in the convolutions; has size (C x M/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the weight shape will be (C x M/group x k1 x k2 x ... x kn), where (k1 x k2 x ... x kn) is the dimension of the kernel. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"W","type":"T"},{"description":"Optional 1D bias to be added to the convolution, has size of M.","name":"B","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, pad lengths and group count. The number of channels in the output should be equal to W.shape[1] * group (assuming zero based indices of the shape array)","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Cos","schema":{"description":"Calculates the cosine of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Cos',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.cos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cos_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.cos(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cos')","summary":"cos"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The cosine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Cosh","schema":{"description":"Calculates the hyperbolic cosine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Cosh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.cosh(x) # expected output [1.54308069, 1., 1.54308069]\nexpect(node, inputs=[x], outputs=[y],\n name='test_cosh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.cosh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_cosh')","summary":"cosh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic cosine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"CumSum","schema":{"attributes":[{"description":"If set to 1 will return exclusive sum in which the top element is not included. In other terms, if set to 1, the j-th output element would be the sum of the first (j-1) elements. Otherwise, it would be the sum of the first j elements.","name":"exclusive","required":false,"type":"int64"},{"description":"If set to 1 will perform the sums in reverse direction.","name":"reverse","required":false,"type":"int64"}],"description":"Performs cumulative sum of the input elements along the given axis.\nBy default, it will do the sum inclusively meaning the first element is copied as is.\nThrough an `exclusive` attribute, this behavior can change to exclude the first element.\nIt can also perform summation in the opposite direction of the axis. For that, set `reverse` attribute to 1.\n\nExample:\n```\ninput_x = [1, 2, 3]\naxis=0\noutput = [1, 3, 6]\nexclusive=1\noutput = [0, 1, 3]\nexclusive=0\nreverse=1\noutput = [6, 5, 3]\nexclusive=1\nreverse=1\noutput = [5, 3, 0]\n```\n ","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y']\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([1., 3., 6., 10., 15.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d')","summary":"cumsum_1d"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n exclusive=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([0., 1., 3., 6., 10.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_exclusive')","summary":"cumsum_1d_exclusive"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n reverse=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([15., 14., 12., 9., 5.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_reverse')","summary":"cumsum_1d_reverse"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n reverse=1\n)\nx = np.array([1., 2., 3., 4., 5.]).astype(np.float64)\naxis = np.array([0]).astype(np.int32)\ny = np.array([14., 12., 9., 5., 0.]).astype(np.float64)\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_1d_reverse_exclusive')","summary":"cumsum_1d_reverse_exclusive"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([0]).astype(np.int32)\ny = np.array([1., 2., 3., 5., 7., 9.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_axis_0')","summary":"cumsum_2d_axis_0"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([1]).astype(np.int32)\ny = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_axis_1')","summary":"cumsum_2d_axis_1"},{"code":"node = onnx.helper.make_node(\n 'CumSum',\n inputs=['x', 'axis'],\n outputs=['y'],\n)\nx = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float64).reshape((2, 3))\naxis = np.array([-1]).astype(np.int32)\ny = np.array([1., 3., 6., 4., 9., 15.]).astype(np.float64).reshape((2, 3))\nexpect(node, inputs=[x, axis], outputs=[y],\n name='test_cumsum_2d_negative_axis')","summary":"cumsum_2d_negative_axis"}],"inputs":[{"description":"An input tensor that is to be processed.","name":"x","type":"T"},{"description":"(Optional) A 0-D tensor. Must be in the range [-rank(x), rank(x)-1]. Negative value means counting dimensions from the back.","name":"axis","type":"T2"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same type as 'x' with cumulative sums of the x's elements","name":"y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float)","tensor(double)"],"description":"Input can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"axis tensor can be int32 or int64 only","type_param_str":"T2"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"},{"default":"DCR","description":"DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order.","name":"mode","required":false,"type":"string"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions. By default, `mode` = `DCR`.\nIn the DCR mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: depth, column, and then row. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w])\n\ntmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2])\n\ny = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize])\n\n\nIn the CRD mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: column, row, and the depth. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, c // (blocksize ** 2), blocksize, blocksize, h, w])\n\ntmp = np.transpose(tmp, [0, 1, 4, 2, 5, 3])\n\ny = np.reshape(tmp, [b, c // (blocksize ** 2), h * blocksize, w * blocksize])\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DepthToSpace","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"},{"default":"DCR","description":"DCR (default) for depth-column-row order re-arrangement. Use CRD for column-row-depth order.","name":"mode","required":false,"type":"string"}],"description":"DepthToSpace rearranges (permutes) data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of\nthe input tensor where values from the depth dimension are moved in spatial blocks to the height\nand width dimensions. By default, `mode` = `DCR`.\nIn the DCR mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: depth, column, and then row. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w])\n\ntmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2])\n\ny = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize])\n\n\nIn the CRD mode, elements along the depth dimension from the input tensor are rearranged in the\nfollowing order: column, row, and the depth. The output y is computed from the input x as below:\n\nb, c, h, w = x.shape\n\ntmp = np.reshape(x, [b, c // (blocksize ** 2), blocksize, blocksize, h, w])\n\ntmp = np.transpose(tmp, [0, 1, 4, 2, 5, 3])\n\ny = np.reshape(tmp, [b, c // (blocksize ** 2), h * blocksize, w * blocksize])\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='CRD'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 9., 1., 10., 2., 11.],\n [18., 27., 19., 28., 20., 29.],\n [3., 12., 4., 13., 5., 14.],\n [21., 30., 22., 31., 23., 32.]],\n [[36., 45., 37., 46., 38., 47.],\n [54., 63., 55., 64., 56., 65.],\n [39., 48., 40., 49., 41., 50.],\n [57., 66., 58., 67., 59., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_crd_mode_example')","summary":"crd_mode_example"},{"code":"node = onnx.helper.make_node(\n 'DepthToSpace',\n inputs=['x'],\n outputs=['y'],\n blocksize=2,\n mode='DCR'\n)\n\n# (1, 8, 2, 3) input tensor\nx = np.array([[[[0., 1., 2.],\n [3., 4., 5.]],\n [[9., 10., 11.],\n [12., 13., 14.]],\n [[18., 19., 20.],\n [21., 22., 23.]],\n [[27., 28., 29.],\n [30., 31., 32.]],\n [[36., 37., 38.],\n [39., 40., 41.]],\n [[45., 46., 47.],\n [48., 49., 50.]],\n [[54., 55., 56.],\n [57., 58., 59.]],\n [[63., 64., 65.],\n [66., 67., 68.]]]]).astype(np.float32)\n\n# (1, 2, 4, 6) output tensor\ny = np.array([[[[0., 18., 1., 19., 2., 20.],\n [36., 54., 37., 55., 38., 56.],\n [3., 21., 4., 22., 5., 23.],\n [39., 57., 40., 58., 41., 59.]],\n [[9., 27., 10., 28., 11., 29.],\n [45., 63., 46., 64., 47., 65.],\n [12., 30., 13., 31., 14., 32.],\n [48., 66., 49., 67., 50., 68.]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_depthtospace_example')","summary":"default_mode_example"}],"inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C/(blocksize * blocksize), H * blocksize, W * blocksize].","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"DequantizeLinear","schema":{"description":"The linear dequantization operator. It consumes a quantized tensor, a scale, a zero point to compute the full precision tensor.\nThe dequantization formula is y = (x - x_zero_point) * x_scale. 'x_scale' and 'x_zero_point' must have same shape.\n'x_zero_point' and 'x' must have same type. 'x' and 'y' must have same shape. In the case of dequantizing int32,\nthere's no zero point (zero point is supposed to be 0).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# 1-D tensor zero point and scale of size equal to axis 1 of the input tensor\nx = np.array([[[[3, 89],\n [34, 200],\n [74, 59]],\n\n [[5, 24],\n [24, 87],\n [32, 13]],\n\n [[245, 99],\n [4, 142],\n [121, 102]], ], ], dtype=np.uint8)\nx_scale = np.array([2, 4, 5], dtype=np.float32)\nx_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x.astype(np.float32) - x_zero_point.reshape(1, 3, 1, 1).astype(np.float32)) * x_scale.reshape(1, 3, 1, 1)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# scalar zero point and scale\nx = np.array([0, 3, 128, 255]).astype(np.uint8)\nx_scale = np.float32(2)\nx_zero_point = np.uint8(128)\ny = np.array([-256, -250, 0, 254], dtype=np.float32)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear')","summary":"dequantizelinear"}],"inputs":[{"description":"N-D quantized input tensor to be de-quantized.","name":"x","type":"T"},{"description":"Scale for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point for input 'x'. It's a scalar, which means a per-tensor/layer quantization. It's optional. 0 is the default value when it's not specified.","name":"x_zero_point","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D full precision output tensor. It has same shape as input 'x'.","name":"y","type":"tensor(float)"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)","tensor(int32)"],"description":"Constrain 'x_zero_point' and 'x' to 8-bit/32-bit integer tensor.","type_param_str":"T"}]}},{"name":"DequantizeLinear","schema":{"attributes":[{"default":1,"description":"(Optional) The axis of the dequantizing dimension of the input tensor. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input)","name":"axis","required":false,"type":"int64"}],"description":"The linear dequantization operator. It consumes a quantized tensor, a scale, and a zero point to compute the full precision tensor.\nThe dequantization formula is y = (x - x_zero_point) * x_scale. 'x_scale' and 'x_zero_point' must have same shape, and can be either a scalar\nfor per-tensor / per layer quantization, or a 1-D tensor for per-axis quantizations.\n'x_zero_point' and 'x' must have same type. 'x' and 'y' must have same shape. In the case of dequantizing int32,\nthere's no zero point (zero point is supposed to be 0).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# 1-D tensor zero point and scale of size equal to axis 1 of the input tensor\nx = np.array([[[[3, 89],\n [34, 200],\n [74, 59]],\n\n [[5, 24],\n [24, 87],\n [32, 13]],\n\n [[245, 99],\n [4, 142],\n [121, 102]], ], ], dtype=np.uint8)\nx_scale = np.array([2, 4, 5], dtype=np.float32)\nx_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x.astype(np.float32) - x_zero_point.reshape(1, 3, 1, 1).astype(np.float32)) * x_scale.reshape(1, 3, 1, 1)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('DequantizeLinear',\n inputs=['x', 'x_scale', 'x_zero_point'],\n outputs=['y'],)\n\n# scalar zero point and scale\nx = np.array([0, 3, 128, 255]).astype(np.uint8)\nx_scale = np.float32(2)\nx_zero_point = np.uint8(128)\ny = np.array([-256, -250, 0, 254], dtype=np.float32)\n\nexpect(node, inputs=[x, x_scale, x_zero_point], outputs=[y],\n name='test_dequantizelinear')","summary":"dequantizelinear"}],"inputs":[{"description":"N-D quantized input tensor to be de-quantized.","name":"x","type":"T"},{"description":"Scale for input 'x'. It can be a scalar, which means a per-tensor/layer dequantization, or a 1-D tensor for per-axis dequantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point for input 'x'. It can be a scalar, which means a per-tensor/layer dequantization, or a 1-D tensor for per-axis dequantization. It's optional. 0 is the default value when it's not specified.","name":"x_zero_point","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D full precision output tensor. It has same shape as input 'x'.","name":"y","type":"tensor(float)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)","tensor(int32)"],"description":"Constrain 'x_zero_point' and 'x' to 8-bit/32-bit integer tensor.","type_param_str":"T"}]}},{"name":"Det","schema":{"description":"Det calculates determinant of a square matrix or batches of square matrices.\nDet takes one input tensor of shape `[*, M, M]`, where `*` is zero or more batch dimensions,\nand the inner-most 2 dimensions form square matrices.\nThe output is a tensor of shape `[*]`, containing the determinants of all input submatrices.\ne.g., When the input is 2-D, the output is a scalar(shape is empty: `[]`).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Det',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.arange(4).reshape(2, 2).astype(np.float32)\ny = np.linalg.det(x) # expect -2\nexpect(node, inputs=[x], outputs=[y],\n name='test_det_2d')","summary":"2d"},{"code":"node = onnx.helper.make_node(\n 'Det',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]]]).astype(np.float32)\ny = np.linalg.det(x) # expect array([-2., -3., -8.])\nexpect(node, inputs=[x], outputs=[y],\n name='test_det_nd')","summary":"nd"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to floating-point tensors.","type_param_str":"T"}]}},{"name":"DictVectorizer","schema":{"attributes":[{"description":"An integer vocabulary array.
    One and only one of the vocabularies must be defined.","name":"int64_vocabulary","required":false,"type":"int64[]"},{"description":"A string vocabulary array.
    One and only one of the vocabularies must be defined.","name":"string_vocabulary","required":false,"type":"string[]"}],"description":"Uses an index mapping to convert a dictionary to an array.
    \n Given a dictionary, each key is looked up in the vocabulary attribute corresponding to\n the key type. The index into the vocabulary array at which the key is found is then\n used to index the output 1-D tensor 'Y' and insert into it the value found in the dictionary 'X'.
    \n The key type of the input map must correspond to the element type of the defined vocabulary attribute.\n Therefore, the output array will be equal in length to the index mapping vector parameter.\n All keys in the input dictionary must be present in the index mapping vector.\n For each item in the input dictionary, insert its value in the output array.\n Any keys not present in the input dictionary, will be zero in the output array.
    \n For example: if the ``string_vocabulary`` parameter is set to ``[\"a\", \"c\", \"b\", \"z\"]``,\n then an input of ``{\"a\": 4, \"c\": 8}`` will produce an output of ``[4, 8, 0, 0]``.\n ","domain":"ai.onnx.ml","inputs":[{"description":"A dictionary.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 1-D tensor holding values from the input dictionary.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["map(string, int64)","map(int64, string)","map(int64, float)","map(int64, double)","map(string, float)","map(string, double)"],"description":"The input must be a map from strings or integers to either strings or a numeric type. The key and value types cannot be the same.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)","tensor(float)","tensor(double)","tensor(string)"],"description":"The output will be a tensor of the value type of the input map. It's shape will be [1,C], where C is the length of the input dictionary.","type_param_str":"T2"}]}},{"name":"Div","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary division (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"description":"Performs element-wise binary division (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Div","schema":{"description":"Performs element-wise binary division (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([3, 4]).astype(np.float32)\ny = np.array([1, 2]).astype(np.float32)\nz = x / y # expected output [3., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(3, 4, 5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div')","summary":"div"},{"code":"node = onnx.helper.make_node(\n 'Div',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.rand(5).astype(np.float32) + 1.0\nz = x / y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_div_bcast')","summary":"div_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"(int, default 0) if nonzero, run dropout in test mode where the output is simply Y = X.","name":"is_test","required":false,"type":"int64"},{"default":0.5,"description":"(float, default 0.5) the ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask. If is_test is nonzero, this output is not filled.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(int, default 0) if nonzero, run dropout in test mode where the output is simply Y = X.","name":"is_test","required":false,"type":"int64"},{"default":0.5,"description":"(float, default 0.5) the ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask. If is_test is nonzero, this output is not filled.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"The ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input data (Tensor) and produces two Tensor outputs,\noutput (Tensor) and mask (Tensor). Depending on whether it is in\ntest mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Dropout","schema":{"attributes":[{"default":0.5,"description":"The ratio of random dropout","name":"ratio","required":false,"type":"float32"}],"category":"Dropout","description":"Dropout takes one input floating tensor and produces two tensor outputs,\noutput (floating tensor) and mask (`Tensor`). Depending on whether it is\nin test mode or not, the output Y will either be a random dropout, or a simple\ncopy of the input. Note that our implementation of Dropout does scaling in\nthe training phase, so during testing nothing needs to be done.\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T1"}],"outputs_range":"1 - 2","since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output mask types to boolean tensors.","type_param_str":"T1"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"int64"}],"category":"Dropout","description":"Dropout takes an input floating-point tensor, an optional input ratio (floating-point scalar) and an optional input training_mode (boolean scalar). It produces two tensor outputs,\noutput (floating-point tensor) and mask (optional `Tensor`). If `training_mode` is true then the output Y will be a random dropout;\nNote that this Dropout scales the masked input data by the following equation, so to convert the trained model into inference mode,\nthe user can simply not pass `training_mode` input or set it to false.\n```\noutput = scale * data * mask,\n```\nwhere\n```\nscale = 1. / (1. - ratio).\n```\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"},{"description":"The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.","name":"ratio","option":"optional","type":"T1"},{"description":"If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.","name":"training_mode","option":"optional","type":"T2"}],"inputs_range":"1 - 3","max_input":3,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T2"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input 'ratio' types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output 'mask' types to boolean tensors.","type_param_str":"T2"}]}},{"name":"Dropout","schema":{"attributes":[{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"int64"}],"category":"Dropout","description":"Dropout takes an input floating-point tensor, an optional input ratio (floating-point scalar) and an optional input training_mode (boolean scalar). It produces two tensor outputs,\noutput (floating-point tensor) and mask (optional `Tensor`). If `training_mode` is true then the output Y will be a random dropout;\nNote that this Dropout scales the masked input data by the following equation, so to convert the trained model into inference mode,\nthe user can simply not pass `training_mode` input or set it to false.\n```\noutput = scale * data * mask,\n```\nwhere\n```\nscale = 1. / (1. - ratio).\n```\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x)\nexpect(node, inputs=[x], outputs=[y], name='test_dropout_default')","summary":"default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, return_mask=True)\nexpect(node, inputs=[x], outputs=[y, z], name='test_dropout_default_mask')","summary":"default_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny, z = dropout(x, r, return_mask=True)\nexpect(node, inputs=[x, r], outputs=[y, z], name='test_dropout_default_mask_ratio')","summary":"default_mask_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_default_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"default_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r'],\n outputs=['y'],\n seed=seed\n)\n\nr = np.float32(0.1)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = dropout(x, r)\nexpect(node, inputs=[x, r], outputs=[y], name='test_dropout_default_ratio')","summary":"default_ratio"},{"code":"node = onnx.helper.make_node(\n 'Dropout',\n inputs=['x'],\n outputs=['y'],\n ratio=.2,\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x\nexpect(node, inputs=[x], outputs=[y],\n name='test_dropout_random_old', opset_imports=[helper.make_opsetid(\"\", 11)])","summary":"random_old"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout')","summary":"training"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_default')","summary":"training_default"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.5)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_default_mask')","summary":"training_default_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny = dropout(x, r, training_mode=t)\nexpect(node, inputs=[x, r, t], outputs=[y], name='test_training_dropout_zero_ratio')","summary":"training_default_zero_ratio"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.0)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_zero_ratio_mask')","summary":"training_default_zero_ratio_mask"},{"code":"seed = np.int64(0)\nnode = onnx.helper.make_node(\n 'Dropout',\n inputs=['x', 'r', 't'],\n outputs=['y', 'z'],\n seed=seed\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nr = np.float32(0.75)\nt = np.bool_(True)\ny, z = dropout(x, r, training_mode=t, return_mask=True)\nexpect(node, inputs=[x, r, t], outputs=[y, z], name='test_training_dropout_mask')","summary":"training_ratio_mask"}],"inputs":[{"description":"The input data as Tensor.","name":"data","type":"T"},{"description":"The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.","name":"ratio","option":"optional","type":"T1"},{"description":"If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.","name":"training_mode","option":"optional","type":"T2"}],"inputs_range":"1 - 3","max_input":3,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"},{"description":"The output mask.","name":"mask","option":"optional","type":"T2"}],"outputs_range":"1 - 2","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input 'ratio' types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output 'mask' types to boolean tensors.","type_param_str":"T2"}]}},{"name":"DynamicQuantizeLinear","schema":{"description":"A Function to fuse calculation for Scale, Zero Point and FP32->8Bit convertion of FP32 Input data.\nOutputs Scale, ZeroPoint and Quantized Input for a given FP32 Input.\nScale is calculated as:\n```\n y_scale = (max(x) - min(x))/(qmax - qmin)\n * where qmax and qmin are max and min values for quantization range .i.e [0, 255] in case of uint8\n * data range is adjusted to include 0.\n```\nZero point is calculated as:\n```\nintermediate_zero_point = qmin - min(x)/y_scale\ny_zero_point = cast(round(saturate(itermediate_zero_point)))\n* where qmax and qmin are max and min values for quantization range .i.e [0, 255] in case of uint8\n* for saturation, it saturates to [0, 255] if it's uint8, or [-127, 127] if it's int8. Right now only uint8 is supported.\n* rounding to nearest ties to even.\n```\nData quantization formula is:\n```\ny = saturate (round (x / y_scale) + y_zero_point)\n* for saturation, it saturates to [0, 255] if it's uint8, or [-127, 127] if it's int8. Right now only uint8 is supported.\n* rounding to nearest ties to even.\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('DynamicQuantizeLinear',\n inputs=['x'],\n outputs=['y', 'y_scale', 'y_zero_point'],\n)\n\n# expected scale 0.0196078438 and zero point 153\nX = np.array([0, 2, -3, -2.5, 1.34, 0.5]).astype(np.float32)\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear')\n\n# expected scale 0.0156862754 and zero point 255\nX = np.array([-1.0, -2.1, -1.3, -2.5, -3.34, -4.0]).astype(np.float32)\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear_max_adjusted')\n\nX = np.array([1, 2.1, 1.3, 2.5,\n 3.34, 4.0, 1.5, 2.6,\n 3.9, 4.0, 3.0, 2.345]).astype(np.float32).reshape((3, 4))\n\n# expected scale 0.0156862754 and zero point 0\nx_min = np.minimum(0, np.min(X))\nx_max = np.maximum(0, np.max(X))\nY_Scale = np.float32((x_max - x_min) / (255 - 0)) # uint8 -> [0, 255]\nY_ZeroPoint = np.clip(round((0 - x_min) / Y_Scale), 0, 255).astype(np.uint8)\nY = np.clip(np.round(X / Y_Scale) + Y_ZeroPoint, 0, 255).astype(np.uint8)\n\nexpect(node, inputs=[X], outputs=[Y, Y_Scale, Y_ZeroPoint],\n name='test_dynamicquantizelinear_min_adjusted')","summary":"dynamicquantizelinear"}],"inputs":[{"description":"Input tensor","name":"x","type":"T1"}],"max_input":1,"max_output":3,"min_input":1,"min_output":3,"outputs":[{"description":"Quantized output tensor","name":"y","type":"T2"},{"description":"Output scale. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Output zero point. It's a scalar, which means a per-tensor/layer quantization.","name":"y_zero_point","type":"T2"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)"],"description":"Constrain 'x' to float tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit unsigned integer tensor.","type_param_str":"T2"}]}},{"name":"Einsum","schema":{"attributes":[{"description":"Einsum expression string.","name":"equation","required":true,"type":"string"}],"description":"An einsum of the form ```term1, term2 -> output-term``` produces an output tensor using the following equation\n\n```output[output-term] = reduce-sum( input1[term1] * input2[term] )```\n\nwhere the reduce-sum performs a summation over all the indices occurring in in the input terms (term1, term2)\nthat do not occur in the output-term.\n\nThe Einsum operator evaluates algebraic tensor operations on a sequence of tensors, using the Einstein summation\nconvention. The equation string contains a comma-separated sequence of lower case letters. Each term corresponds to\nan operand tensor, and the characters within the terms correspond to operands dimensions.\n\nThis sequence may be followed by \"->\" to separate the left and right hand side of the equation.\nIf the equation contains \"->\" followed by the right-hand side, the explicit (not classical) form of the Einstein\nsummation is performed, and the right-hand side indices indicate output tensor dimensions. In other cases,\noutput indices are (implicitly) set to the alphabetically sorted sequence of indices appearing exactly once in the\nequation.\n\nWhen a dimension character is repeated in the left-hand side, it represents summation along the dimension.\n\nThe equation may contain ellipsis (\"...\") to enable broadcasting. Ellipsis must indicate a fixed number of dimensions.\nSpecifically, every occurrence of ellipsis in the equation must represent the same number of dimensions.\nThe right-hand side may contain exactly one ellipsis. In implicit mode, the ellipsis dimensions are set to the\nbeginning of the output. The equation string may contain space (U+0020) character.\n","domain":"ai.onnx","examples":[{"code":"Eqn = '...ii ->...i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 5, 5)\nZ = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Z], name='test_einsum_batch_diagonal')","summary":"einsum_batch_diagonal"},{"code":"Eqn = 'bij, bjk -> bik'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x', 'y'],\n outputs=['z'],\n equation=Eqn\n)\n\nX = np.random.randn(5, 2, 3)\nY = np.random.randn(5, 3, 4)\nZ = einsum_reference_implementation(Eqn, (X, Y))\n\nexpect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_batch_matmul')","summary":"einsum_batch_matmul"},{"code":"Eqn = 'i,i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x', 'y'],\n outputs=['z'],\n equation=Eqn\n)\n\nX = np.random.randn(5)\nY = np.random.randn(5)\nZ = einsum_reference_implementation(Eqn, (X, Y))\n\nexpect(node, inputs=[X, Y], outputs=[Z], name='test_einsum_inner_prod')","summary":"einsum_inner_prod"},{"code":"Eqn = 'ij->i'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 4)\nZ = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Z], name='test_einsum_sum')","summary":"einsum_sum"},{"code":"Eqn = 'ij->ji'\nnode = onnx.helper.make_node(\n 'Einsum',\n inputs=['x'],\n outputs=['y'],\n equation=Eqn\n)\n\nX = np.random.randn(3, 4)\nY = einsum_reference_implementation(Eqn, (X,))\n\nexpect(node, inputs=[X], outputs=[Y], name='test_einsum_transpose')","summary":"einsum_transpose"}],"inputs":[{"description":"Operands","name":"Inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numerical tensor types.","type_param_str":"T"}]}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Coefficient of ELU default to 1.0.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Elu takes one input data (Tensor) and produces one output data\n(Tensor) where the function `f(x) = alpha * (exp(x) - 1.) for x <\n0`, `f(x) = x for x >= 0`., is applied to the tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-1.2642411, 0., 1.]\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu')","summary":"elu"},{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_default')","summary":"elu_default"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Elu","schema":{"attributes":[{"default":1,"description":"Coefficient of ELU.","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"Elu takes one input data (Tensor) and produces one output data\n(Tensor) where the function `f(x) = alpha * (exp(x) - 1.) for x <\n0`, `f(x) = x for x >= 0`., is applied to the tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-1.2642411, 0., 1.]\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu')","summary":"elu"},{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'Elu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_elu_default')","summary":"elu_default"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Equal","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)"],"description":"Constrains input to integral tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)"],"description":"Constrains input to integral tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Equal","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal')","summary":"equal"},{"code":"node = onnx.helper.make_node(\n 'Equal',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = (np.random.randn(3, 4, 5) * 10).astype(np.int32)\ny = (np.random.randn(5) * 10).astype(np.int32)\nz = np.equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_equal_bcast')","summary":"equal_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Erf","schema":{"description":"Computes the error function of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Erf',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\ny = np.vectorize(math.erf)(x).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_erf')","summary":"erf"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The error function of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Erf","schema":{"description":"Computes the error function of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Erf',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\ny = np.vectorize(math.erf)(x).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_erf')","summary":"erf"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The error function of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Exp","schema":{"description":"Calculates the exponential of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Exp',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.exp(x) # expected output [0.36787945, 1., 2.71828175]\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.exp(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_exp')","summary":"exp"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The exponential of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Expand","schema":{"description":"Broadcast the input tensor following the given shape and the broadcast rule.\nThe broadcast rule is similar to numpy.array(input) * numpy.ones(shape):\nDimensions are right alignment;\nTwo corresponding dimension must have the same value, or one of them is equal to 1.\nAlso, this operator is similar to numpy.broadcast_to(input, shape),\nbut the major difference is numpy.broadcast_to() does not allow shape to be smaller than input.size().\nIt is possible that the output.shape is not equal to shape, when some dimensions in shape is equal to 1,\nor the shape.ndim < input.shape.ndim.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nnew_shape = [2, 1, 6]\nexpanded = data * np.ones(new_shape, dtype=np.float32)\n#print(expanded)\n#[[[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]],\n#\n# [[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_changed')","summary":"dim_changed"},{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\nnew_shape = [3, 4]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nexpanded = np.tile(data, 4)\n#print(expanded)\n#[[1., 1., 1., 1.],\n# [2., 2., 2., 2.],\n# [3., 3., 3., 3.]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_unchanged')","summary":"dim_unchanged"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"},{"description":"A 1-D tensor indicates the shape you want to expand to, following the broadcast rule","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"output","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensors.","type_param_str":"T"}]}},{"name":"Expand","schema":{"description":"Broadcast the input tensor following the given shape and the broadcast rule.\nThe broadcast rule is similar to numpy.array(input) * numpy.ones(shape):\nDimensions are right alignment;\nTwo corresponding dimension must have the same value, or one of them is equal to 1.\nAlso, this operator is similar to numpy.broadcast_to(input, shape),\nbut the major difference is numpy.broadcast_to() does not allow shape to be smaller than input.size().\nIt is possible that the output.shape is not equal to shape, when some dimensions in shape is equal to 1,\nor the shape.ndim < input.shape.ndim.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nnew_shape = [2, 1, 6]\nexpanded = data * np.ones(new_shape, dtype=np.float32)\n#print(expanded)\n#[[[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]],\n#\n# [[1., 1., 1., 1., 1., 1.],\n# [2., 2., 2., 2., 2., 2.],\n# [3., 3., 3., 3., 3., 3.]]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_changed')","summary":"dim_changed"},{"code":"node = onnx.helper.make_node(\n 'Expand',\n inputs=['data', 'new_shape'],\n outputs=['expanded'],\n)\nshape = [3, 1]\nnew_shape = [3, 4]\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[1.], [2.], [3.]]\nexpanded = np.tile(data, 4)\n#print(expanded)\n#[[1., 1., 1., 1.],\n# [2., 2., 2., 2.],\n# [3., 3., 3., 3.]]\nnew_shape = np.array(new_shape, dtype=np.int64)\nexpect(node, inputs=[data, new_shape], outputs=[expanded],\n name='test_expand_dim_unchanged')","summary":"dim_unchanged"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"},{"description":"A 1-D tensor indicates the shape you want to expand to, following the broadcast rule","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensors.","type_param_str":"T"}]}},{"name":"EyeLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor. If not specified,the data type of the input tensor T1 is used. If input tensor T1 is also notspecified, then type defaults to 'float'.","name":"dtype","required":false,"type":"int64"},{"description":"(Optional) Index of the diagonal to be populated with ones. Default is 0. If T2 is the output, this op sets T2[i, i+k] = 1. k = 0 populates the main diagonal, k > 0 populates an upper diagonal, and k < 0 populates a lower diagonal.","name":"k","required":false,"type":"int64"}],"description":"Generate a 2D tensor (matrix) with ones on the diagonal and zeros everywhere else. Only 2D\ntensors are supported, i.e. input T1 must be of rank 2. The shape of the output tensor is the\nsame as the input tensor. The data type can be specified by the 'dtype' argument. If\n'dtype' is not specified, then the type of input tensor is used. By default, the main diagonal\nis populated with ones, but attribute 'k' can be used to populate upper or lower diagonals.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message and be valid as an output type.\n","domain":"ai.onnx","examples":[{"code":"shape = (4, 5)\noff_diagonal_offset = 1\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n k=off_diagonal_offset,\n dtype=onnx.TensorProto.FLOAT,\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_populate_off_main_diagonal')","summary":"populate_off_main_diagonal"},{"code":"shape = (3, 4)\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n dtype=onnx.TensorProto.DOUBLE,\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], dtype=np.float64)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_with_dtype')","summary":"with_dtype"},{"code":"shape = (4, 4)\nnode = onnx.helper.make_node(\n 'EyeLike',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.random.randint(0, 100, size=shape, dtype=np.int32)\ny = np.eye(shape[0], shape[1], dtype=np.int32)\nexpect(node, inputs=[x], outputs=[y], name='test_eyelike_without_dtype')","summary":"without_dtype"}],"inputs":[{"description":"2D input tensor to copy shape, and optionally, type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, same shape as input tensor T1.","name":"output","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain input types. Strings and complex are not supported.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(bool)"],"description":"Constrain output types. Strings and complex are not supported.","type_param_str":"T2"}]}},{"name":"FeatureVectorizer","schema":{"attributes":[{"description":"The size of each input in the input list","name":"inputdimensions","required":false,"type":"int64[]"}],"description":"Concatenates input tensors into one continuous output.
    \n All input shapes are 2-D and are concatenated along the second dimention. 1-D tensors are treated as [1,C].\n Inputs are copied to the output maintaining the order of the input arguments.
    \n All inputs must be integers or floats, while the output will be all floating point values.\n","domain":"ai.onnx.ml","inputs":[{"description":"An ordered collection of tensors, all with the same element type.","name":"X","option":"variadic","type":"T1"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output array, elements ordered as the inputs.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float)","tensor(double)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T1"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [0, R], where R is the rank of the input tensor. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [0, R], where R is the rank of the input tensor. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Flatten","schema":{"attributes":[{"default":1,"description":"Indicate up to which input dimensions (exclusive) should be flattened to the outer dimension of the output. The value for axis must be in the range [-r, r], where r is the rank of the input tensor. Negative value means counting dimensions from the back. When axis = 0, the shape of the output tensor is (1, (d_0 X d_1 ... d_n), where the shape of the input tensor is (d_0, d_1, ... d_n). ","name":"axis","required":false,"type":"int64"}],"category":"Shape","description":"Flattens the input tensor into a 2D matrix. If input tensor has shape\n(d_0, d_1, ... d_n) then the output will have shape\n(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(len(shape)):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (1, -1) if i == 0 else (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_axis' + str(i))","summary":"flatten"},{"code":"shape = (2, 3, 4, 5)\na = np.random.random_sample(shape).astype(np.float32)\n\nfor i in range(-len(shape), 0):\n node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'],\n axis=i,\n )\n\n new_shape = (np.prod(shape[0:i]).astype(int), -1)\n b = np.reshape(a, new_shape)\n expect(node, inputs=[a], outputs=[b],\n name='test_flatten_negative_axis' + str(abs(i)))","summary":"flatten_negative_axis"},{"code":"node = onnx.helper.make_node(\n 'Flatten',\n inputs=['a'],\n outputs=['b'], # Default value for axis: axis=1\n)\n\nshape = (5, 4, 3, 2)\na = np.random.random_sample(shape).astype(np.float32)\nnew_shape = (5, 24)\nb = np.reshape(a, new_shape)\nexpect(node, inputs=[a], outputs=[b],\n name='test_flatten_default_axis')","summary":"flatten_with_default_axis"}],"inputs":[{"description":"A tensor of rank >= axis.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"A 2D tensor with the contents of the input tensor, with input dimensions up to axis flattened to the outer dimension of the output and remaining input dimensions flattened into the inner dimension of the output.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output to all tensor types.","type_param_str":"T"}]}},{"name":"Floor","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Floor","schema":{"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Floor","schema":{"description":"Floor takes one input data (Tensor) and produces one output data\n(Tensor) where the floor is, y = floor(x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Floor',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1.5, 1.2, 2]).astype(np.float32)\ny = np.floor(x) # expected output [-2., 1., 2.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.floor(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_floor')","summary":"floor"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"foward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*Rz + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*Rr + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*Rh + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*Rh + Rbh) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":2,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"When computing the output of the hidden gate, apply the linear transformation before multiplying by the output of the reset gate.","name":"linear_before_reset","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*Rz + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*Rr + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*Rh + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*Rh + Rbh) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":3,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"GRU","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 2 (or 4 if bidirectional) activation functions for update, reset, and hidden gates. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"When computing the output of the hidden gate, apply the linear transformation before multiplying by the output of the reset gate.","name":"linear_before_reset","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer GRU. This operator is usually supported via some custom\nimplementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`z` - update gate\n\n`r` - reset gate\n\n`h` - hidden gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[zrh]` - W parameter weight matrix for update, reset, and hidden gates\n\n`R[zrh]` - R recurrence weight matrix for update, reset, and hidden gates\n\n`Wb[zrh]` - W bias vectors for update, reset, and hidden gates\n\n`Rb[zrh]` - R bias vectors for update, reset, and hidden gates\n\n`WB[zrh]` - W parameter weight matrix for backward update, reset, and hidden gates\n\n`RB[zrh]` - R recurrence weight matrix for backward update, reset, and hidden gates\n\n`WBb[zrh]` - W bias vectors for backward update, reset, and hidden gates\n\n`RBb[zrh]` - R bias vectors for backward update, reset, and hidden gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh):\n\n - zt = f(Xt*(Wz^T) + Ht-1*(Rz^T) + Wbz + Rbz)\n\n - rt = f(Xt*(Wr^T) + Ht-1*(Rr^T) + Wbr + Rbr)\n\n - ht = g(Xt*(Wh^T) + (rt (.) Ht-1)*(Rh^T) + Rbh + Wbh) # default, when linear_before_reset = 0\n\n - ht = g(Xt*(Wh^T) + (rt (.) (Ht-1*(Rh^T) + Rbh)) + Wbh) # when linear_before_reset != 0\n\n - Ht = (1 - zt) (.) ht + zt (.) Ht-1\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 5\nweight_scale = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\ngru = GRU_Helper(X=input, W=W, R=R)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_gru_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 3\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\nnumber_of_gates = 3\n\nnode = onnx.helper.make_node(\n 'GRU',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, number_of_gates * hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, number_of_gates * hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nR_B = np.random.randn(1, number_of_gates * hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\ngru = GRU_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = gru.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_gru_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[zrh]` and `WB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[zrh]` and `RB[zrh]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 3*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for the gates. Concatenation of `[Wb[zrh], Rb[zrh]]` and `[WBb[zrh], RBb[zrh]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 6*hidden_size]`. Optional: If not specified - assumed to be 0","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1]","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\nExample 1:\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\n\naxis = 0 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\naxis = 1 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[j_{0}, k, j_{1}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Gather","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"category":"Transform","description":"Given `data` tensor of rank r >= 1, and `indices` tensor of rank q, gather\nentries of the axis dimension of `data` (by default outer-most one as axis=0) indexed by `indices`, and concatenates\nthem in an output tensor of rank q + (r - 1).\n\naxis = 0 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n indices = [\n [0, 1],\n [1, 2],\n ]\n output = [\n [\n [1.0, 1.2],\n [2.3, 3.4],\n ],\n [\n [2.3, 3.4],\n [4.5, 5.7],\n ],\n ]\n```\naxis = 1 :\n\nLet\nk = indices[i_{0}, ..., i_{q-1}]\nThen\noutput[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[j_{0}, k, j_{1}, ..., j_{r-2}]\n\n```\n data = [\n [1.0, 1.2, 1.9],\n [2.3, 3.4, 3.9],\n [4.5, 5.7, 5.9],\n ]\n indices = [\n [0, 2],\n ]\n axis = 1,\n output = [\n [\n [1.0, 1.9],\n [2.3, 3.9],\n [4.5, 5.9],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_0')","summary":"gather_0"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=1,\n)\ndata = np.random.randn(5, 4, 3, 2).astype(np.float32)\nindices = np.array([0, 1, 3])\ny = np.take(data, indices, axis=1)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_1')","summary":"gather_1"},{"code":"node = onnx.helper.make_node(\n 'Gather',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=0,\n)\ndata = np.arange(10).astype(np.float32)\nindices = np.array([0, -9, -10])\ny = np.take(data, indices, axis=0)\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_negative_indices')","summary":"gather_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of any rank q. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + (r - 1).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherElements","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"GatherElements takes two inputs `data` and `indices` of the same rank r >= 1\nand an optional attribute `axis` that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). It is an indexing operation\nthat produces its output by indexing into the input data tensor at index\npositions determined by elements of the `indices` tensor.\nIts output shape is the same as the shape of `indices` and consists of one value\n(gathered from the `data`) for each element in `indices`.\n\nFor instance, in the 3-D case (r = 3), the output produced is determined\nby the following equations: \n```\n out[i][j][k] = input[index[i][j][k]][j][k] if axis = 0,\n out[i][j][k] = input[i][index[i][j][k]][k] if axis = 1,\n out[i][j][k] = input[i][j][index[i][j][k]] if axis = 2,\n```\n\nThis operator is also the inverse of ScatterElements. It is similar to Torch's gather operation.\n\nExample 1:\n```\n data = [\n [1, 2],\n [3, 4],\n ]\n indices = [\n [0, 0],\n [1, 0],\n ]\n axis = 1\n output = [\n [\n [1, 1],\n [4, 3],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n ]\n indices = [\n [1, 2, 0],\n [2, 0, 0],\n ]\n axis = 0\n output = [\n [\n [4, 8, 3],\n [7, 2, 3],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2],\n [3, 4]], dtype=np.float32)\nindices = np.array([[0, 0],\n [1, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[1, 1],\n# [4, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_0')","summary":"gather_elements_0"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[1, 2, 0],\n [2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[4, 8, 3],\n# [7, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_1')","summary":"gather_elements_1"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[-1, -2, 0],\n [-2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[7, 5, 3],\n# [4, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_negative_indices')","summary":"gather_elements_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, with the same rank r as the input. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of the same shape as indices.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherElements","schema":{"attributes":[{"description":"Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"GatherElements takes two inputs `data` and `indices` of the same rank r >= 1\nand an optional attribute `axis` that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). It is an indexing operation\nthat produces its output by indexing into the input data tensor at index\npositions determined by elements of the `indices` tensor.\nIts output shape is the same as the shape of `indices` and consists of one value\n(gathered from the `data`) for each element in `indices`.\n\nFor instance, in the 3-D case (r = 3), the output produced is determined\nby the following equations: \n```\n out[i][j][k] = input[index[i][j][k]][j][k] if axis = 0,\n out[i][j][k] = input[i][index[i][j][k]][k] if axis = 1,\n out[i][j][k] = input[i][j][index[i][j][k]] if axis = 2,\n```\n\nThis operator is also the inverse of ScatterElements. It is similar to Torch's gather operation.\n\nExample 1:\n```\n data = [\n [1, 2],\n [3, 4],\n ]\n indices = [\n [0, 0],\n [1, 0],\n ]\n axis = 1\n output = [\n [\n [1, 1],\n [4, 3],\n ],\n ]\n```\nExample 2:\n```\n data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n ]\n indices = [\n [1, 2, 0],\n [2, 0, 0],\n ]\n axis = 0\n output = [\n [\n [4, 8, 3],\n [7, 2, 3],\n ],\n ]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2],\n [3, 4]], dtype=np.float32)\nindices = np.array([[0, 0],\n [1, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[1, 1],\n# [4, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_0')","summary":"gather_elements_0"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[1, 2, 0],\n [2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[4, 8, 3],\n# [7, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_1')","summary":"gather_elements_1"},{"code":"axis = 0\nnode = onnx.helper.make_node(\n 'GatherElements',\n inputs=['data', 'indices'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=np.float32)\nindices = np.array([[-1, -2, 0],\n [-2, 0, 0]], dtype=np.int32)\n\ny = gather_elements(data, indices, axis)\n# print(y) produces\n# [[7, 5, 3],\n# [4, 2, 3]]\n\nexpect(node, inputs=[data, indices.astype(np.int64)], outputs=[y],\n name='test_gather_elements_negative_indices')","summary":"gather_elements_negative_indices"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, with the same rank r as the input. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of the same shape as indices.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"GatherND","schema":{"description":"Given `data` tensor of rank `r` >= 1, and `indices` tensor of rank `q` >= 1, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r` (inclusive) \n\n3) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r` => error condition\n\n2) If `indices_shape[-1] == r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor\n containing 1-D tensors of dimension `r`. Let us think of each such `r` ranked tensor as `indices_slice`. \n Each *scalar value* corresponding to `data[indices_slice]` is filled into the corresponding location of the `(q-1)`-dimensional tensor \n to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r`, since the rank of `indices` is `q`, `indices` can be thought of as a `(q-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r`. Let us think of each such tensors as `indices_slice`. \n Each *tensor slice* corresponding to `data[indices_slice , :]` is filled into the corresponding location of the `(q-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, and 4 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"GatherND","schema":{"attributes":[{"description":"The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:]","name":"batch_dims","required":false,"type":"int64"}],"description":"Given `data` tensor of rank `r` >= 1, `indices` tensor of rank `q` >= 1, and `batch_dims` integer `b`, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1 - b`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\n`batch_dims` (denoted as `b`) is an integer indicating the number of batch dimensions, i.e the leading `b` number of dimensions of \n`data` tensor and `indices` are representing the batches, and the gather starts from the `b+1` dimension. \n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The first `b` dimensions of the shape of `indices` tensor and `data` tensor must be equal.\n\n3) b < min(q, r) is to be honored.\n\n4) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r-b` (inclusive) \n\n5) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r-b` => error condition\n\n2) If `indices_shape[-1] == r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensors\n containing 1-D tensors of dimension `r-b`, where `N` is an integer equals to the product of 1 and all the elements in the batch dimensions \n of the indices_shape. Let us think of each such `r-b` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[0:b-1,indices_slice]` \n is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r-b`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding \n to `data[0:b-1, indices_slice , :]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, 4 and 5 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n`Example 5`\n\n batch_dims = 1\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"GatherND","schema":{"attributes":[{"description":"The number of batch dimensions. The gather of indexing starts from dimension of data[batch_dims:]","name":"batch_dims","required":false,"type":"int64"}],"description":"Given `data` tensor of rank `r` >= 1, `indices` tensor of rank `q` >= 1, and `batch_dims` integer `b`, this operator gathers \nslices of `data` into an output tensor of rank `q + r - indices_shape[-1] - 1 - b`.\n\n`indices` is an q-dimensional integer tensor, best thought of as a `(q-1)`-dimensional tensor of index-tuples into `data`, \nwhere each element defines a slice of `data`\n\n`batch_dims` (denoted as `b`) is an integer indicating the number of batch dimensions, i.e the leading `b` number of dimensions of \n`data` tensor and `indices` are representing the batches, and the gather starts from the `b+1` dimension. \n\nSome salient points about the inputs' rank and shape:\n \n1) r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks `r` and `q`\n\n2) The first `b` dimensions of the shape of `indices` tensor and `data` tensor must be equal.\n\n3) b < min(q, r) is to be honored.\n\n4) The `indices_shape[-1]` should have a value between 1 (inclusive) and rank `r-b` (inclusive) \n\n5) All values in `indices` are expected to be within bounds [-s, s-1] along axis of size `s` (i.e.) `-data_shape[i] <= indices[...,i] <= data_shape[i] - 1`.\n It is an error if any of the index values are out of bounds.\n\nThe output is computed as follows:\n\nThe output tensor is obtained by mapping each index-tuple in the `indices` tensor to the corresponding slice of the input `data`.\n \n1) If `indices_shape[-1] > r-b` => error condition\n\n2) If `indices_shape[-1] == r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensors\n containing 1-D tensors of dimension `r-b`, where `N` is an integer equals to the product of 1 and all the elements in the batch dimensions \n of the indices_shape. Let us think of each such `r-b` ranked tensor as `indices_slice`. Each *scalar value* corresponding to `data[0:b-1,indices_slice]` \n is filled into the corresponding location of the `(q-b-1)`-dimensional tensor to form the `output` tensor (Example 1 below)\n\n3) If `indices_shape[-1] < r-b`, since the rank of `indices` is `q`, `indices` can be thought of as `N` `(q-b-1)`-dimensional tensor\n containing 1-D tensors of dimension `< r-b`. Let us think of each such tensors as `indices_slice`. Each *tensor slice* corresponding \n to `data[0:b-1, indices_slice , :]` is filled into the corresponding location of the `(q-b-1)`-dimensional tensor \n to form the `output` tensor (Examples 2, 3, 4 and 5 below)\n\nThis operator is the inverse of `ScatterND`.\n\n`Example 1`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[0,0],[1,1]] # indices_shape = [2, 2]\n\n output = [0,3] # output_shape = [2]\n\n`Example 2`\n\n batch_dims = 0\n\n data = [[0,1],[2,3]] # data_shape = [2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[0,1]] # output_shape = [2, 2]\n\n`Example 3`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[0,1],[1,0]] # indices_shape = [2, 2]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n`Example 4`\n\n batch_dims = 0\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[[0,1]],[[1,0]]] # indices_shape = [2, 1, 2]\n\n output = [[[2,3]],[[4,5]]] # output_shape = [2, 1, 2] \n\n`Example 5`\n\n batch_dims = 1\n\n data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2]\n\n indices = [[1],[0]] # indices_shape = [2, 1]\n\n output = [[2,3],[4,5]] # output_shape = [2, 2] \n\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)\nindices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_float32')","summary":"float32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n)\n\ndata = np.array([[0, 1], [2, 3]], dtype=np.int32)\nindices = np.array([[0, 0], [1, 1]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 0)\nexpected_output = np.array([0, 3], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32')","summary":"int32"},{"code":"node = onnx.helper.make_node(\n 'GatherND',\n inputs=['data', 'indices'],\n outputs=['output'],\n batch_dims=1,\n)\n\ndata = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)\nindices = np.array([[1], [0]], dtype=np.int64)\noutput = gather_nd_impl(data, indices, 1)\nexpected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)\nassert (np.array_equal(output, expected_output))\nexpect(node, inputs=[data, indices], outputs=[output],\n name='test_gathernd_example_int32_batch_dim1')","summary":"int32_batchdim_1"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1. All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B, the default value is 1.0.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C, the default value is 1.0.","name":"beta","required":false,"type":"float32"},{"description":"Whether C should be broadcasted","name":"broadcast","required":false,"type":"int64"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\nCompute Y = alpha * A * B + beta * C, where input tensor A has\ndimension (M X K), input tensor B has dimension (K X N), input tensor C and\noutput tensor Y have dimension (M X N).\nIf attribute broadcast is non-zero, input tensor C will be broadcasted to match\nthe dimension requirement. A will be transposed before doing the computation\nif attribute transA is non-zero, same for B and transB.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A","name":"A","type":"T"},{"description":"Input tensor B","name":"B","type":"T"},{"description":"Input tensor C, can be inplace.","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B, the default value is 1.0.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C, the default value is 1.0.","name":"beta","required":false,"type":"float32"},{"description":"Whether C should be broadcasted","name":"broadcast","required":false,"type":"int64"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\nCompute Y = alpha * A * B + beta * C, where input tensor A has\ndimension (M X K), input tensor B has dimension (K X N), input tensor C and\noutput tensor Y have dimension (M X N).\nIf attribute broadcast is non-zero, input tensor C will be broadcasted to match\nthe dimension requirement. A will be transposed before doing the computation\nif attribute transA is non-zero, same for B and transB.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A","name":"A","type":"T"},{"description":"Input tensor B","name":"B","type":"T"},{"description":"Input tensor C","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor.","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Input tensor C. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Input tensor C. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Optional input tensor C. If not specified, the computation is done as if C is a scalar 0. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Gemm","schema":{"attributes":[{"default":1,"description":"Scalar multiplier for the product of input tensors A * B.","name":"alpha","required":false,"type":"float32"},{"default":1,"description":"Scalar multiplier for input tensor C.","name":"beta","required":false,"type":"float32"},{"description":"Whether A should be transposed","name":"transA","required":false,"type":"int64"},{"description":"Whether B should be transposed","name":"transB","required":false,"type":"int64"}],"category":"Layer","description":"General Matrix multiplication:\nhttps://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3\n\nA' = transpose(A) if transA else A\n\nB' = transpose(B) if transB else B\n\nCompute Y = alpha * A' * B' + beta * C, where input tensor A has shape (M, K) or (K, M),\ninput tensor B has shape (K, N) or (N, K), input tensor C is broadcastable to shape (M, N),\nand output tensor Y has shape (M, N). A will be transposed before doing the\ncomputation if attribute transA is non-zero, same for B and transB.\nThis operator supports **unidirectional broadcasting** (tensor C should be unidirectional broadcastable to tensor A * B); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.25,\n beta=0.35,\n transA=1,\n transB=1\n)\na = np.random.ranf([4, 3]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.random.ranf([1, 5]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_all_attributes')","summary":"all_attributes"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n alpha=0.5\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, alpha=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_alpha')","summary":"alpha"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n beta=0.5\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, beta=0.5)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_beta')","summary":"beta"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.random.ranf([3, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_matrix_bias')","summary":"default_matrix_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b'],\n outputs=['y']\n)\na = np.random.ranf([2, 10]).astype(np.float32)\nb = np.random.ranf([10, 3]).astype(np.float32)\ny = gemm_reference_implementation(a, b)\nexpect(node, inputs=[a, b], outputs=[y],\n name='test_gemm_default_no_bias')","summary":"default_no_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 3]).astype(np.float32)\nb = np.random.ranf([3, 4]).astype(np.float32)\nc = np.array(3.14).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_scalar_bias')","summary":"default_scalar_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 7]).astype(np.float32)\nb = np.random.ranf([7, 3]).astype(np.float32)\nc = np.random.ranf([1]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_single_elem_vector_bias')","summary":"default_single_elem_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([2, 7]).astype(np.float32)\nb = np.random.ranf([7, 4]).astype(np.float32)\nc = np.random.ranf([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_vector_bias')","summary":"default_vector_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y']\n)\na = np.random.ranf([3, 5]).astype(np.float32)\nb = np.random.ranf([5, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_default_zero_bias')","summary":"default_zero_bias"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transA=1\n)\na = np.random.ranf([6, 3]).astype(np.float32)\nb = np.random.ranf([6, 4]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transA=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeA')","summary":"transposeA"},{"code":"node = onnx.helper.make_node(\n 'Gemm',\n inputs=['a', 'b', 'c'],\n outputs=['y'],\n transB=1\n)\na = np.random.ranf([3, 6]).astype(np.float32)\nb = np.random.ranf([4, 6]).astype(np.float32)\nc = np.zeros([1, 4]).astype(np.float32)\ny = gemm_reference_implementation(a, b, c, transB=1)\nexpect(node, inputs=[a, b, c], outputs=[y],\n name='test_gemm_transposeB')","summary":"transposeB"}],"inputs":[{"description":"Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.","name":"A","type":"T"},{"description":"Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.","name":"B","type":"T"},{"description":"Optional input tensor C. If not specified, the computation is done as if C is a scalar 0. The shape of C should be unidirectional broadcastable to (M, N).","name":"C","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of shape (M, N).","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(bfloat16)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"GlobalAveragePool","schema":{"category":"Pool","description":"GlobalAveragePool consumes an input tensor X and applies average pooling across\n the values in the same channel. This is equivalent to AveragePool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'GlobalAveragePool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(1, 3, 5, 5).astype(np.float32)\nspatial_shape = np.ndim(x) - 2\ny = np.average(x, axis=tuple(range(spatial_shape, spatial_shape + 2)))\nfor _ in range(spatial_shape):\n y = np.expand_dims(y, -1)\nexpect(node, inputs=[x], outputs=[y], name='test_globalaveragepool')","summary":"globalaveragepool"},{"code":"\nnode = onnx.helper.make_node(\n 'GlobalAveragePool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n]]]).astype(np.float32)\ny = np.array([[[[5]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_globalaveragepool_precomputed')","summary":"globalaveragepool_precomputed"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalLpPool","schema":{"attributes":[{"default":2,"description":"p value of the Lp norm used to pool over the input data, default is 2.0.","name":"p","required":false,"type":"float32"}],"category":"Pool","description":"GlobalLpPool consumes an input tensor X and applies lp pool pooling across the\n the values in the same channel. This is equivalent to LpPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimension are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. Dimensions will be N x C x 1 x 1","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalLpPool","schema":{"attributes":[{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"}],"category":"Pool","description":"GlobalLpPool consumes an input tensor X and applies lp pool pooling across\n the values in the same channel. This is equivalent to LpPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"GlobalMaxPool","schema":{"category":"Pool","description":"GlobalMaxPool consumes an input tensor X and applies max pooling across\n the values in the same channel. This is equivalent to MaxPool with kernel size\n equal to the spatial dimension of input tensor.","domain":"ai.onnx","examples":[{"code":"\nnode = onnx.helper.make_node(\n 'GlobalMaxPool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(1, 3, 5, 5).astype(np.float32)\nspatial_shape = np.ndim(x) - 2\ny = np.max(x, axis=tuple(range(spatial_shape, spatial_shape + 2)))\nfor _ in range(spatial_shape):\n y = np.expand_dims(y, -1)\nexpect(node, inputs=[x], outputs=[y], name='test_globalmaxpool')","summary":"globalmaxpool"},{"code":"\nnode = onnx.helper.make_node(\n 'GlobalMaxPool',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[[\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n]]]).astype(np.float32)\ny = np.array([[[[9]]]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y], name='test_globalmaxpool_precomputed')","summary":"globalmaxpool_precomputed"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. The first two dimensions of output shape are the same as the input (N x C), while the other dimensions are all 1.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Gradient","schema":{"attributes":[{"description":"Input tensor names of the differentiated sub-graph. It contains only the necessary differentiated inputs of a (sub-)graph. Variables (usually called intermediate variables) that can be generated from inputs cannot be included in this attribute.","name":"xs","required":true,"type":"string[]"},{"description":"The targeted tensor. It can be viewed as the output of the differentiated function. The attribute \"xs\" and attribute \"zs\" are the minimal independent variable set that determines the value of \"y\".","name":"y","required":true,"type":"string"},{"description":"Input tensor names of the differentiated sub-graph. It contains only the necessary non-differentiated inputs of a (sub-)graph. Variables (usually called intermediate variables) that can be generated from inputs cannot be included in this attribute.","name":"zs","required":false,"type":"string[]"}],"description":"Gradient operator computes the partial derivatives of a specific tensor w.r.t.\nsome other tensors. This operator is widely used in gradient-based training\nalgorithms. To illustrate its use, let's consider a computation graph,\n\n```\nX -----.\n |\n v\nW --> Conv --> H --> Gemm --> Y\n ^\n |\n Z\n```\n\n, where W and Z are trainable tensors. Note that operators' attributes are\nomitted for the sake of simplicity. Let dY/dW (dY/dZ) be the gradient of\nY with respect to W (Z). The user can compute gradient by inserting Gradient\noperator to form another graph shown below.\n\n```\nW --> Conv --> H --> Gemm --> Y\n| ^ ^\n| | |\n| X Z\n| | |\n| | .----------'\n| | | (W/Z/X is the 1st/2nd/3rd input of Gradient as shown in\n| | | \"xs\" followed by \"zs\")\n| v v\n'---> Gradient(xs=[\"W\", \"Z\"], zs=[\"X\"], y=\"Y\")\n | |\n | '-----------------------------------> dY/dW (1st output of Gradient)\n |\n '---------------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nBy definition, the tensor \"y\" is a function of independent variables in \"xs\"\nand \"zs\". Since we only compute the gradient of \"y\" w.r.t. the differentiable\nvariables in \"xs\", this Gradient only outputs dY/dW and dY/dZ. Note that \"H\"\ncannot appear in \"xs\" and \"zs\". The reason is that \"H\" can be determined by\ntensors \"W\" and \"X\" and therefore \"H\" is not an independent variable.\n\nAll outputs are optional. If needed, for example, user can assign an empty\nstring to the 1st output name of that Gradient to skip the generation of dY/dW.\nNote that the concept of optional outputs can also be found in ONNX's RNN, GRU,\nand LSTM.\n\nGradient operator can compute derivative against intermediate tensors. For\nexample, the gradient of Y with respect to H can be done via\n\n```\nW --> Conv --> H --> Gemm --> Y\n ^ | ^\n | | |\n X | Z\n .-------' |\n | .----------'\n | | (H/Z is the 1st/2nd input of Gradient as shown in \"xs\")\n v v\n Gradient(xs=[\"H\", \"Z\"], y=\"Y\")\n | |\n | '-----------------------------------> dY/dH (1st output of Gradient)\n |\n '---------------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nIt is possible to represent high-order differentiation using Gradient operators.\nFor example, given the following linear model:\n\n```\nW --> Gemm --> Y --> Loss --> O\n ^ ^\n | |\n X L\n```\n\nTo compute the 2nd order derivative of O with respect to W (denoted by\nd^2O/dW^2), one can do\n\n```\nW --> Gemm --> Y --> Loss --> O\n| ^ ^\n| | |\n| X .------------L\n| | | |\n| | | v\n+------+-+> Gradient(xs=[\"X\", \"W\"], zs=[\"L\"], y=\"O\") ---> dO/dX (1st output of Gradient)\n| | | |\n| | | '---> dO/dW (2nd output of Gradient)\n| v v\n'---> Gradient(xs=[\"X\", \"W\"], zs=[\"L\"], y=\"dO/dW\") ---> d(dO/dW)dX (1st output of\n | Gradient)\n |\n |\n '---> d^2O/dW^2 (2nd output of Gradient)\n```\n\nThe tensors named in attributes \"xs\", \"zs\", and \"y\" define the differentiated\ncomputation graph, and the inputs to Gradient node define the values at\nwhich the gradient is computed. We can feed different tensors to the identified\ngraph. For example, one can compute the gradient of Y with respect to H at \na specific value of H, H_1, by providing that value as an input to the Gradient\nnode.\n\n```\nW --> Conv --> H --> Gemm --> Y\n ^ ^\n | |\n X Z\n\n Z_1 (2nd input of Gradient)\n |\n v\nH_1 --> Gradient(xs=[\"H\", \"Z\"], y=\"Y\") ---> dY/dH when H = H_1 and Y = Y_1.\n |\n '------------------------------> dY/dZ (2nd output of Gradient)\n```\n\nWhen the inputs of Gradient are the tensors named in \"xs\" and \"zs\", the\ncomputation can be optimized. More specifically, intermediate variables in\nforward pass can be reused if the gradient is computed via reverse-mode\nauto-differentiation.\n\n","domain":"ai.onnx.preview.training","examples":[{"code":"add_node = onnx.helper.make_node('Add',\n ['a', 'b'], ['c'], name='my_add')\ngradient_node = onnx.helper.make_node(\n 'Gradient', ['a', 'b'],\n ['dc_da', 'dc_db'], name='my_gradient',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN,\n xs=['a', 'b'], y='c')\n\na = np.array(1.0).astype(np.float32)\nb = np.array(2.0).astype(np.float32)\nc = a + b\n# dc / da = d(a+b) / da = 1\ndc_da = np.array(1).astype(np.float32)\n# db / db = d(a+b) / db = 1\ndc_db = np.array(1).astype(np.float32)\n\ngraph = onnx.helper.make_graph(\n nodes=[add_node, gradient_node],\n name='GradientOfAdd',\n inputs=[\n onnx.helper.make_tensor_value_info('a', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('b', onnx.TensorProto.FLOAT,\n [])],\n outputs=[\n onnx.helper.make_tensor_value_info('c', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('dc_da',\n onnx.TensorProto.FLOAT, []),\n onnx.helper.make_tensor_value_info('dc_db',\n onnx.TensorProto.FLOAT, [])])\nopsets = [\n onnx.helper.make_operatorsetid(ONNX_DOMAIN, 12),\n onnx.helper.make_operatorsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)]\nmodel = onnx.helper.make_model(\n graph,\n producer_name='backend-test',\n opset_imports=opsets)\nexpect(model, inputs=[a, b], outputs=[c, dc_da, dc_db],\n name='test_gradient_of_add')","summary":"gradient_scalar_add"},{"code":"add_node = onnx.helper.make_node('Add',\n ['a', 'b'], ['c'], name='my_add')\nmul_node = onnx.helper.make_node('Mul',\n ['c', 'a'], ['d'], name='my_mul')\ngradient_node = onnx.helper.make_node(\n 'Gradient', ['a', 'b'],\n ['dd_da', 'dd_db'], name='my_gradient',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN,\n xs=['a', 'b'], y='d')\n\na = np.array(1.0).astype(np.float32)\nb = np.array(2.0).astype(np.float32)\nc = a + b\n# d = a * c = a * (a + b)\nd = a * c\n# dd / da = d(a*a+a*b) / da = 2 * a + b\ndd_da = (2 * a + b).astype(np.float32)\n# dd / db = d(a*a+a*b) / db = a\ndd_db = a\n\ngraph = onnx.helper.make_graph(\n nodes=[add_node, mul_node, gradient_node],\n name='GradientOfTwoOperators',\n inputs=[\n onnx.helper.make_tensor_value_info('a', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('b', onnx.TensorProto.FLOAT,\n [])],\n outputs=[\n onnx.helper.make_tensor_value_info('d', onnx.TensorProto.FLOAT,\n []),\n onnx.helper.make_tensor_value_info('dd_da',\n onnx.TensorProto.FLOAT, []),\n onnx.helper.make_tensor_value_info('dd_db',\n onnx.TensorProto.FLOAT, [])])\n\nopsets = [\n onnx.helper.make_operatorsetid(ONNX_DOMAIN, 12),\n onnx.helper.make_operatorsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)]\nmodel = onnx.helper.make_model(graph,\n producer_name='backend-test',\n opset_imports=opsets)\nexpect(model, inputs=[a, b], outputs=[d, dd_da, dd_db],\n name='test_gradient_of_add_and_mul')","summary":"gradient_scalar_add_and_mul"}],"inputs":[{"description":"The values fed into graph identified by the attributes. The i-th input is the value of the i-th tensor specified in the concatenated list of the attribute \"xs\" and the attribute \"zs\". For example, if xs=[\"A\", \"B\"] and zs=[\"C\"], the first input is used as the value of symbol \"A\" and the 3rd input is substituted for all the occurrences of \"C\".","name":"Inputs","option":"variadic","type":"T1"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"The gradient of the tensor specified by the attribute \"y\" with respect to each of tensors specified in the attribute \"xs\". The i-th output is the gradient of \"y\" with respect to the i-th tensor specified in the attribute \"xs\".","name":"Outputs","option":"variadic","type":"T2"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Allow outputs to be any kind of tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Allow inputs to be any kind of floating-point tensor.","type_param_str":"T2"}]}},{"name":"GraphCall","schema":{"attributes":[{"description":"The invoked graph's name. The only allowed value is the name of the inference graph, which is stored in \"ModelProto.graph.name\" in the ONNX model format.","name":"graph_name","required":true,"type":"string"}],"description":"The GraphCall operator invokes a graph inside TrainingInfoProto's\nalgorithm field. The GraphCall inputs and outputs are bound to those of\ninvoked graph by position. If a graph input has an initializer, that input\nis considered optional. All graph outputs are optional.\n\nBelow Python syntax is used for describing dictionary and list.\n\nAssume that ModelProto's graph field has\n- name: \"MyInferenceGraph\"\n- input: [\"X\", \"W\", \"Z\"]\n- initializer: [W]\n- output: [\"Y\"]\n\nas visualized below for inference.\n\n```\nX -----.\n |\n v\nW --> Conv --> H --> Gemm --> Y\n ^\n |\n Z\n```\n\nAssume that the training algorithm contains\n\n- inputs: [\"X_1\", \"Z_1\", \"C\"]\n- initializer: [T]\n- outputs: [\"W_new\"]\n\nwith a dictionary\n\n- update_binding: {\"W\": \"W_new\", \"T\": \"T_new\"}\n\nInside the training algorithm graph, one can invoke the inference\ngraph via adding a GraphCall node with\n\n- inputs: [\"X_1\", \"W\", Z_1\"]\n- outputs: [\"Y_1\"]\n- an attribute graph_name=\"MyInferenceGraph\",\n\nThe initializers, \"W\" and \"T\" in this case, in update_binding\nare considered globally-visible and mutable variables, which\ncan be used as inputs of operators in the training graph.\n\nAn example training algorithm graph may look like\n\n```\n.-------- W (a global and mutable variable from\n| | the inference graph)\n| |\n| .-----'-----------.\n| | |\n| | v\n| | .-- X_1 --> GraphCall(graph_name=\"MyInferenceGraph\")\n| | | | |\n| | | | |\n| | | Z_1 -----' |\n| | | | V\n| | | | Y_1 ---> Loss ---> O\n| | | | ^\n| | | | |\n| | `--. | C\n| | | | |\n| | | | .----------------'\n| | | | |\n| | v v v\n| `--> Gradient(xs=[\"W\"], zs=[\"X_1\", \"Z_1\", \"C\"], y=\"O\")\n| |\n| v\n| dO_dW (gradient of W) 1 (a scalar one)\n| | |\n| V v\n| Div <--- T ------------> Add ---> T_new\n| | (T is the number of training iterations.\n| | T is also globally visible and mutable.)\n| v\n`-----> Sub ----> W_new\n```\n\nwhere Loss is a dummy node which computes the minimized objective function.\n\nThe variable \"W\" is an optional input in the called graph.\nIf the user omits it, the input list of GraphCall becomes [\"X_1\", \"\", \"Z_1\"].\nIn this case, from the view of computation graph, the Conv operator invoked by\nGraphCall's may be still connected the global \"W\" variable and therefore the\nstructure of the computation graph is unchanged.\n","domain":"ai.onnx.preview.training","inputs":[{"description":"Inputs fed to the invoked graph. The i-th input here goes to the i-th input of the invoked graph. To omit an optional input in this field, the user can drop it or use an empty string.","name":"Inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"The outputs generated by the called graph. Its i-th value is bound to the i-th output of the called graph. Similar to the inputs, all outputs are optional.","name":"Outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Allow inputs and outputs to be any kind of tensor.","type_param_str":"T"}]}},{"name":"Greater","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Greater","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `greater` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal')","summary":"greater"},{"code":"node = onnx.helper.make_node(\n 'Greater',\n inputs=['x', 'y'],\n outputs=['greater'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_bcast')","summary":"greater_broadcast"},{"code":"node = onnx.helper.make_node(\n 'GreaterOrEqual',\n inputs=['x', 'y'],\n outputs=['greater_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.greater_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_greater_equal_bcast')","summary":"greater_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"GreaterOrEqual","schema":{"description":"Returns the tensor resulted from performing the `greater_equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"HardSigmoid","schema":{"attributes":[{"default":0.20000000298023224,"description":"Value of alpha default to 0.2","name":"alpha","required":false,"type":"float32"},{"default":0.5,"description":"Value of beta default to 0.5","name":"beta","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"HardSigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the HardSigmoid function, y = max(0, min(1, alpha * x + beta)),\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n alpha=0.5,\n beta=0.6\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid')","summary":"hardsigmoid"},{"code":"default_alpha = 0.2\ndefault_beta = 0.5\nnode = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * default_alpha + default_beta, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_default')","summary":"hardsigmoid_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"HardSigmoid","schema":{"attributes":[{"default":0.20000000298023224,"description":"Value of alpha.","name":"alpha","required":false,"type":"float32"},{"default":0.5,"description":"Value of beta.","name":"beta","required":false,"type":"float32"}],"category":"Activation","description":"HardSigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the HardSigmoid function, y = max(0, min(1, alpha * x + beta)),\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n alpha=0.5,\n beta=0.6\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * 0.5 + 0.6, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid')","summary":"hardsigmoid"},{"code":"default_alpha = 0.2\ndefault_beta = 0.5\nnode = onnx.helper.make_node(\n 'HardSigmoid',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x * default_alpha + default_beta, 0, 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardsigmoid_default')","summary":"hardsigmoid_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Hardmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"description":"The operator computes the hardmax (1 for the first maximum value, and 0 for all others) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the hardmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_example')\n\n# For multiple occurrences of the maximal values, the first occurrence is selected for one-hot output\nx = np.array([[3, 3, 3, 1]]).astype(np.float32)\ny = np.array([[1, 0, 0, 0]]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_one_hot')","summary":"hardmax"},{"code":"def hardmax_2d(x): # type: (np.ndarray) -> np.ndarray\n return np.eye(x.shape[1], dtype=x.dtype)[np.argmax(x, axis=1)]\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = hardmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = hardmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Hardmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = hardmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_hardmax_negative_axis')","summary":"hardmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Identity","schema":{"description":"Identity operator","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Identity',\n inputs=['x'],\n outputs=['y'],\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data], outputs=[data],\n name='test_identity')","summary":"identity"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor to copy input into.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Identity","schema":{"description":"Identity operator","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Identity',\n inputs=['x'],\n outputs=['y'],\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data], outputs=[data],\n name='test_identity')","summary":"identity"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor to copy input into.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"If","schema":{"attributes":[{"description":"Graph to run if condition is false. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the then_branch.","name":"else_branch","required":true,"type":"graph"},{"description":"Graph to run if condition is true. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the else_branch.","name":"then_branch","required":true,"type":"graph"}],"description":"If conditional","domain":"ai.onnx","inputs":[{"description":"Condition for the if","name":"cond","type":"B"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Values that are live-out to the enclosing scope. The return values in the `then_branch` and `else_branch` must be of the same shape and same data type.","name":"outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(bool)"],"description":"Only bool","type_param_str":"B"}]}},{"name":"If","schema":{"attributes":[{"description":"Graph to run if condition is false. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the then_branch.","name":"else_branch","required":true,"type":"graph"},{"description":"Graph to run if condition is true. Has N outputs: values you wish to be live-out to the enclosing scope. The number of outputs must match the number of outputs in the else_branch.","name":"then_branch","required":true,"type":"graph"}],"description":"If conditional","domain":"ai.onnx","inputs":[{"description":"Condition for the if","name":"cond","type":"B"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Values that are live-out to the enclosing scope. The return values in the `then_branch` and `else_branch` must be of the same data type. The `then_branch` and `else_branch` may produce tensors with the same element type and different shapes. If corresponding outputs from the then-branch and the else-branch have static shapes S1 and S2, then the shape of the corresponding output variable of the if-node (if present) must be compatible with both S1 and S2 as it represents the union of both possible shapes.For example, if in a model file, the the first output of `then_branch` is typed float tensor with shape [2] and the first output of `else_branch` is another float tensor with shape [3], If's first output should have (a) no shape set, or (b) a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) a shape of rank 1 with a unique `dim_param`. In contrast, the first output cannot have the shape [2] since [2] and [3] are not compatible.","name":"outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(bool)"],"description":"Only bool","type_param_str":"B"}]}},{"name":"Imputer","schema":{"attributes":[{"description":"Value(s) to change to","name":"imputed_value_floats","required":false,"type":"float32[]"},{"description":"Value(s) to change to.","name":"imputed_value_int64s","required":false,"type":"int64[]"},{"description":"A value that needs replacing.","name":"replaced_value_float","required":false,"type":"float32"},{"description":"A value that needs replacing.","name":"replaced_value_int64","required":false,"type":"int64"}],"description":"Replaces inputs that equal one value with another, leaving all other elements alone.
    \n This operator is typically used to replace missing values in situations where they have a canonical\n representation, such as -1, 0, NaN, or some extreme value.
    \n One and only one of imputed_value_floats or imputed_value_int64s should be defined -- floats if the input tensor\n holds floats, integers if the input tensor holds integers. The imputed values must all fit within the\n width of the tensor element type. One and only one of the replaced_value_float or replaced_value_int64 should be defined,\n which one depends on whether floats or integers are being processed.
    \n The imputed_value attribute length can be 1 element, or it can have one element per input feature.
    In other words, if the input tensor has the shape [*,F], then the length of the attribute array may be 1 or F. If it is 1, then it is broadcast along the last dimension and applied to each feature.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be processed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Imputed output data","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type, either [N,C] or [C]. The output type will be of the same tensor type and shape.","type_param_str":"T"}]}},{"name":"InstanceNormalization","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero, default is 1e-5f.","name":"epsilon","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out instance normalization as described in the paper\nhttps://arxiv.org/abs/1607.08022.\n\ny = scale * (x - mean) / sqrt(variance + epsilon) + B,\nwhere mean and variance are computed per instance per channel.\n\n","domain":"ai.onnx","examples":[{"code":"def _instancenorm_test_mode(x, s, bias, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n axis = tuple(range(2, dims_x))\n mean = np.mean(x, axis=axis, keepdims=True)\n var = np.var(x, axis=axis, keepdims=True)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\ny = _instancenorm_test_mode(x, s, bias).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nepsilon = 1e-2\ny = _instancenorm_test_mode(x, s, bias, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_epsilon')","summary":"instancenormalization"}],"inputs":[{"description":"The input 4-dimensional tensor of shape NCHW.","name":"input","type":"T"},{"description":"The input 1-dimensional scale tensor of size C.","name":"scale","type":"T"},{"description":"The input 1-dimensional bias tensor of size C.","name":"B","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"The output 4-dimensional tensor of the same shape as input.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"InstanceNormalization","schema":{"attributes":[{"default":0.000009999999747378752,"description":"The epsilon value to use to avoid division by zero.","name":"epsilon","required":false,"type":"float32"}],"category":"Normalization","description":"Carries out instance normalization as described in the paper\nhttps://arxiv.org/abs/1607.08022.\n\ny = scale * (x - mean) / sqrt(variance + epsilon) + B,\nwhere mean and variance are computed per instance per channel.\n\n","domain":"ai.onnx","examples":[{"code":"def _instancenorm_test_mode(x, s, bias, epsilon=1e-5): # type: ignore\n dims_x = len(x.shape)\n axis = tuple(range(2, dims_x))\n mean = np.mean(x, axis=axis, keepdims=True)\n var = np.var(x, axis=axis, keepdims=True)\n dim_ones = (1,) * (dims_x - 2)\n s = s.reshape(-1, *dim_ones)\n bias = bias.reshape(-1, *dim_ones)\n return s * (x - mean) / np.sqrt(var + epsilon) + bias\n\n# input size: (1, 2, 1, 3)\nx = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)\ns = np.array([1.0, 1.5]).astype(np.float32)\nbias = np.array([0, 1]).astype(np.float32)\ny = _instancenorm_test_mode(x, s, bias).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n)\n\n# output size: (1, 2, 1, 3)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_example')\n\n# input size: (2, 3, 4, 5)\nx = np.random.randn(2, 3, 4, 5).astype(np.float32)\ns = np.random.randn(3).astype(np.float32)\nbias = np.random.randn(3).astype(np.float32)\nepsilon = 1e-2\ny = _instancenorm_test_mode(x, s, bias, epsilon).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'InstanceNormalization',\n inputs=['x', 's', 'bias'],\n outputs=['y'],\n epsilon=epsilon,\n)\n\n# output size: (2, 3, 4, 5)\nexpect(node, inputs=[x, s, bias], outputs=[y],\n name='test_instancenorm_epsilon')","summary":"instancenormalization"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"input","type":"T"},{"description":"The input 1-dimensional scale tensor of size C.","name":"scale","type":"T"},{"description":"The input 1-dimensional bias tensor of size C.","name":"B","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"The output tensor of the same shape as input.","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"IsInf","schema":{"attributes":[{"default":1,"description":"(Optional) Whether map negative infinity to true. Default to 1 so that negative infinity induces true. Set this attribute to 0 if negative infinity should be mapped to false.","name":"detect_negative","required":false,"type":"int64"},{"default":1,"description":"(Optional) Whether map positive infinity to true. Default to 1 so that positive infinity induces true. Set this attribute to 0 if positive infinity should be mapped to false.","name":"detect_positive","required":false,"type":"int64"}],"description":"Map infinity to true and other values to false.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n )\n\nx = np.array([-1.2, np.nan, np.inf, 2.8, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isinf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf')","summary":"infinity"},{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n detect_positive=0\n )\n\nx = np.array([-1.7, np.nan, np.inf, -3.6, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isneginf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf_negative')","summary":"negative_infinity_only"},{"code":"node = onnx.helper.make_node('IsInf',\n inputs=['x'],\n outputs=['y'],\n detect_negative=0\n )\n\nx = np.array([-1.7, np.nan, np.inf, 3.6, np.NINF, np.inf],\n dtype=np.float32)\ny = np.isposinf(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isinf_positive')","summary":"positive_infinity_only"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"IsNaN","schema":{"description":"Returns which elements of the input are NaN.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'IsNaN',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([3.0, np.nan, 4.0, np.nan], dtype=np.float32)\ny = np.isnan(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isnan')","summary":"isnan"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"IsNaN","schema":{"description":"Returns which elements of the input are NaN.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'IsNaN',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([3.0, np.nan, 4.0, np.nan], dtype=np.float32)\ny = np.isnan(x)\nexpect(node, inputs=[x], outputs=[y], name='test_isnan')","summary":"isnan"}],"inputs":[{"description":"input","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrain output types to boolean tensors.","type_param_str":"T2"}]}},{"name":"LRN","schema":{"attributes":[{"default":0.00009999999747378752,"description":"Scaling parameter.","name":"alpha","required":false,"type":"float32"},{"default":0.75,"description":"The exponent.","name":"beta","required":false,"type":"float32"},{"default":1,"description":"","name":"bias","required":false,"type":"float32"},{"description":"The number of channels to sum over","name":"size","required":true,"type":"int64"}],"category":"Normalization","description":"Local Response Normalization proposed in the [AlexNet paper](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf).\nIt normalizes over local input regions.\nThe local region is defined across the channels. For an element X[n, c, d1, ..., dk] in a tensor\nof shape (N x C x D1 x D2, ..., Dk), its region is\n{X[n, i, d1, ..., dk] | max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2))}.\n\nsquare_sum[n, c, d1, ..., dk] = sum(X[n, i, d1, ..., dk] ^ 2),\nwhere max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2)).\n\nY[n, c, d1, ..., dk] = X[n, c, d1, ..., dk] / (bias + alpha / size * square_sum[n, c, d1, ..., dk] ) ^ beta\n","domain":"ai.onnx","examples":[{"code":"alpha = 0.0001\nbeta = 0.75\nbias = 1.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n size=3\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn_default')","summary":"default"},{"code":"alpha = 0.0002\nbeta = 0.5\nbias = 2.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha,\n beta=beta,\n bias=bias,\n size=nsize\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn')","summary":"lrn"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, which has the shape and type as input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LRN","schema":{"attributes":[{"default":0.00009999999747378752,"description":"Scaling parameter.","name":"alpha","required":false,"type":"float32"},{"default":0.75,"description":"The exponent.","name":"beta","required":false,"type":"float32"},{"default":1,"description":"","name":"bias","required":false,"type":"float32"},{"description":"The number of channels to sum over","name":"size","required":true,"type":"int64"}],"category":"Normalization","description":"Local Response Normalization proposed in the [AlexNet paper](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf).\nIt normalizes over local input regions.\nThe local region is defined across the channels. For an element X[n, c, d1, ..., dk] in a tensor\nof shape (N x C x D1 x D2, ..., Dk), its region is\n{X[n, i, d1, ..., dk] | max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2))}.\n\nsquare_sum[n, c, d1, ..., dk] = sum(X[n, i, d1, ..., dk] ^ 2),\nwhere max(0, c - floor((size - 1) / 2)) <= i <= min(C - 1, c + ceil((size - 1) / 2)).\n\nY[n, c, d1, ..., dk] = X[n, c, d1, ..., dk] / (bias + alpha / size * square_sum[n, c, d1, ..., dk] ) ^ beta\n","domain":"ai.onnx","examples":[{"code":"alpha = 0.0001\nbeta = 0.75\nbias = 1.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n size=3\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn_default')","summary":"default"},{"code":"alpha = 0.0002\nbeta = 0.5\nbias = 2.0\nnsize = 3\nnode = onnx.helper.make_node(\n 'LRN',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha,\n beta=beta,\n bias=bias,\n size=nsize\n)\nx = np.random.randn(5, 5, 5, 5).astype(np.float32)\nsquare_sum = np.zeros((5, 5, 5, 5)).astype(np.float32)\nfor n, c, h, w in np.ndindex(x.shape):\n square_sum[n, c, h, w] = sum(x[n,\n max(0, c - int(math.floor((nsize - 1) / 2))):min(5, c + int(math.ceil((nsize - 1) / 2)) + 1),\n h,\n w] ** 2)\ny = x / ((bias + (alpha / nsize) * square_sum) ** beta)\nexpect(node, inputs=[x], outputs=[y],\n name='test_lrn')","summary":"lrn"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor, which has the shape and type as input tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LSTM","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"Couple the input and forget gates if 1, default 0.","name":"input_forget","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer LSTM. This operator is usually supported via some\ncustom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`o` - output gate\n\n`f` - forget gate\n\n`c` - cell gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates\n\n`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates\n\n`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates\n\n`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates\n\n`P[iof]` - P peephole weight vector for input, output, and forget gates\n\n`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates\n\n`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates\n\n`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates\n\n`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates\n\n`PB[iof]` - P peephole weight vector for backward input, output, and forget gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh, h=Tanh):\n\n - it = f(Xt*(Wi^T) + Ht-1*Ri + Pi (.) Ct-1 + Wbi + Rbi)\n\n - ft = f(Xt*(Wf^T) + Ht-1*Rf + Pf (.) Ct-1 + Wbf + Rbf)\n\n - ct = g(Xt*(Wc^T) + Ht-1*Rc + Wbc + Rbc)\n\n - Ct = ft (.) Ct-1 + it (.) ct\n\n - ot = f(Xt*(Wo^T) + Ht-1*Ro + Po (.) Ct + Wbo + Rbo)\n\n - Ht = ot (.) h(Ct)\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_lstm_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 4\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), 1)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3., 4.], [5., 6., 7., 8.]]]).astype(np.float32)\n\ninput_size = 4\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\nnumber_of_peepholes = 3\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B', 'sequence_lens', 'initial_h', 'initial_c', 'P'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\n# Initializing Inputs\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\nB = np.zeros((1, 2 * number_of_gates * hidden_size)).astype(np.float32)\nseq_lens = np.repeat(input.shape[0], input.shape[1]).astype(np.int32)\ninit_h = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\ninit_c = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\nP = weight_scale * np.ones((1, number_of_peepholes * hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B, P=P, initial_c=init_c, initial_h=init_h)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B, seq_lens, init_h, init_c, P], outputs=[Y_h.astype(np.float32)],\n name='test_lstm_with_peepholes')","summary":"peepholes"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, 4*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 4*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"},{"description":"Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_c","option":"optional","type":"T"},{"description":"The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.","name":"P","option":"optional","type":"T"}],"inputs_range":"3 - 8","max_input":8,"max_output":3,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"},{"description":"The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_c","option":"optional","type":"T"}],"outputs_range":"0 - 3","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"LSTM","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"Couple the input and forget gates if 1.","name":"input_forget","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer LSTM. This operator is usually supported via some\ncustom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`o` - output gate\n\n`f` - forget gate\n\n`c` - cell gate\n\n`t` - time step (t-1 means previous time step)\n\n`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates\n\n`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates\n\n`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates\n\n`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates\n\n`P[iof]` - P peephole weight vector for input, output, and forget gates\n\n`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates\n\n`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates\n\n`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates\n\n`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates\n\n`PB[iof]` - P peephole weight vector for backward input, output, and forget gates\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Sigmoid, g=Tanh, h=Tanh):\n\n - it = f(Xt*(Wi^T) + Ht-1*(Ri^T) + Pi (.) Ct-1 + Wbi + Rbi)\n\n - ft = f(Xt*(Wf^T) + Ht-1*(Rf^T) + Pf (.) Ct-1 + Wbf + Rbf)\n\n - ct = g(Xt*(Wc^T) + Ht-1*(Rc^T) + Wbc + Rbc)\n\n - Ct = ft (.) Ct-1 + it (.) ct\n\n - ot = f(Xt*(Wo^T) + Ht-1*(Ro^T) + Po (.) Ct + Wbo + Rbo)\n\n - Ht = ot (.) h(Ct)\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_lstm_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 4\nweight_scale = 0.1\ncustom_bias = 0.1\nnumber_of_gates = 4\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, number_of_gates * hidden_size)).astype(np.float32)\nR_B = np.zeros((1, number_of_gates * hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), 1)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_lstm_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3., 4.], [5., 6., 7., 8.]]]).astype(np.float32)\n\ninput_size = 4\nhidden_size = 3\nweight_scale = 0.1\nnumber_of_gates = 4\nnumber_of_peepholes = 3\n\nnode = onnx.helper.make_node(\n 'LSTM',\n inputs=['X', 'W', 'R', 'B', 'sequence_lens', 'initial_h', 'initial_c', 'P'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\n# Initializing Inputs\nW = weight_scale * np.ones((1, number_of_gates * hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, number_of_gates * hidden_size, hidden_size)).astype(np.float32)\nB = np.zeros((1, 2 * number_of_gates * hidden_size)).astype(np.float32)\nseq_lens = np.repeat(input.shape[0], input.shape[1]).astype(np.int32)\ninit_h = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\ninit_c = np.zeros((1, input.shape[1], hidden_size)).astype(np.float32)\nP = weight_scale * np.ones((1, number_of_peepholes * hidden_size)).astype(np.float32)\n\nlstm = LSTM_Helper(X=input, W=W, R=R, B=B, P=P, initial_c=init_c, initial_h=init_h)\n_, Y_h = lstm.step()\nexpect(node, inputs=[input, W, R, B, seq_lens, init_h, init_c, P], outputs=[Y_h.astype(np.float32)],\n name='test_lstm_with_peepholes')","summary":"peepholes"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, 4*hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 4*hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"},{"description":"Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_c","option":"optional","type":"T"},{"description":"The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.","name":"P","option":"optional","type":"T"}],"inputs_range":"3 - 8","max_input":8,"max_output":3,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"},{"description":"The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_c","option":"optional","type":"T"}],"outputs_range":"0 - 3","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"LabelEncoder","schema":{"attributes":[{"description":"A list of labels.","name":"classes_strings","required":false,"type":"string[]"},{"default":-1,"description":"An integer to use when an input string value is not found in the map.
    One and only one of the 'default_*' attributes must be defined.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string to use when an input integer value is not found in the map.
    One and only one of the 'default_*' attributes must be defined.","name":"default_string","required":false,"type":"string"}],"description":"Converts strings to integers and vice versa.
    \n If the string default value is set, it will convert integers to strings.\n If the int default value is set, it will convert strings to integers.
    \n Each operator converts either integers to strings or strings to integers, depending \n on which default value attribute is provided. Only one default value attribute\n should be defined.
    \n When converting from integers to strings, the string is fetched from the\n 'classes_strings' list, by simple indexing.
    \n When converting from strings to integers, the string is looked up in the list\n and the index at which it is found is used as the converted value.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input data.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data. If strings are input, the output values are integers, and vice versa.","name":"Y","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The input type must be a tensor of integers or strings, of any shape.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, and will have the same shape as the input.","type_param_str":"T2"}]}},{"name":"LabelEncoder","schema":{"attributes":[{"description":"A float.","name":"default_float","required":false,"type":"float32"},{"default":-1,"description":"An integer.","name":"default_int64","required":false,"type":"int64"},{"default":"_Unused","description":"A string.","name":"default_string","required":false,"type":"string"},{"description":"A list of floats.","name":"keys_floats","required":false,"type":"float32[]"},{"description":"A list of ints.","name":"keys_int64s","required":false,"type":"int64[]"},{"description":"A list of strings. One and only one of 'keys_*'s should be set.","name":"keys_strings","required":false,"type":"string[]"},{"description":"A list of floats.","name":"values_floats","required":false,"type":"float32[]"},{"description":"A list of ints.","name":"values_int64s","required":false,"type":"int64[]"},{"description":"A list of strings. One and only one of 'value_*'s should be set.","name":"values_strings","required":false,"type":"string[]"}],"description":"Maps each element in the input tensor to another value.
    \n The mapping is determined by the two parallel attributes, 'keys_*' and\n 'values_*' attribute. The i-th value in the specified 'keys_*' attribute\n would be mapped to the i-th value in the specified 'values_*' attribute. It\n implies that input's element type and the element type of the specified\n 'keys_*' should be identical while the output type is identical to the\n specified 'values_*' attribute. If an input element can not be found in the\n specified 'keys_*' attribute, the 'default_*' that matches the specified\n 'values_*' attribute may be used as its output value.
    \n Let's consider an example which maps a string tensor to an integer tensor.\n Assume and 'keys_strings' is [\"Amy\", \"Sally\"], 'values_int64s' is [5, 6],\n and 'default_int64' is '-1'. The input [\"Dori\", \"Amy\", \"Amy\", \"Sally\",\n \"Sally\"] would be mapped to [-1, 5, 5, 6, 6].
    \n Since this operator is an one-to-one mapping, its input and output shapes\n are the same. Notice that only one of 'keys_*'/'values_*' can be set.
    \n For key look-up, bit-wise comparison is used so even a float NaN can be\n mapped to a value in 'values_*' attribute.
    \n","domain":"ai.onnx.ml","inputs":[{"description":"Input data. It can be either tensor or scalar.","name":"X","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data.","name":"Y","type":"T2"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(float)"],"description":"The input type is a tensor of any shape.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(float)"],"description":"Output type is determined by the specified 'values_*' attribute.","type_param_str":"T2"}]}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.009999999776482582,"description":"Coefficient of leakage default to 0.01.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"LeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=0.1\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-0.1, 0., 1.]\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu')","summary":"leakyrelu"},{"code":"default_alpha = 0.01\nnode = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_default')","summary":"leakyrelu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.009999999776482582,"description":"Coefficient of leakage.","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"LeakyRelu takes input data (Tensor) and an argument alpha, and produces one\noutput data (Tensor) where the function `f(x) = alpha * x for x < 0`,\n`f(x) = x for x >= 0`, is applied to the data tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=0.1\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-0.1, 0., 1.]\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu')","summary":"leakyrelu"},{"code":"default_alpha = 0.01\nnode = onnx.helper.make_node(\n 'LeakyRelu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha\nexpect(node, inputs=[x], outputs=[y],\n name='test_leakyrelu_default')","summary":"leakyrelu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Less","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Less","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `less` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal')","summary":"less"},{"code":"node = onnx.helper.make_node(\n 'Less',\n inputs=['x', 'y'],\n outputs=['less'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_bcast')","summary":"less_broadcast"},{"code":"node = onnx.helper.make_node(\n 'LessOrEqual',\n inputs=['x', 'y'],\n outputs=['less_equal'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = np.less_equal(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_less_equal_bcast')","summary":"less_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"LessOrEqual","schema":{"description":"Returns the tensor resulted from performing the `less_equal` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input types to all numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"LinearClassifier","schema":{"attributes":[{"description":"Class labels when using integer labels. One and only one 'classlabels' attribute must be defined.","name":"classlabels_ints","required":false,"type":"int64[]"},{"description":"Class labels when using string labels. One and only one 'classlabels' attribute must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"A collection of weights of the model(s).","name":"coefficients","required":true,"type":"float32[]"},{"description":"A collection of intercepts.","name":"intercepts","required":false,"type":"float32[]"},{"description":"Indicates whether to do OvR or multinomial (0=OvR is the default).","name":"multi_class","required":false,"type":"int64"},{"default":"NONE","description":"Indicates the transform to apply to the scores vector.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"}],"description":"Linear classifier\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be classified.","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Classification outputs (one class per example).","name":"Y","type":"T2"},{"description":"Classification scores ([N,E] - one score for each class and example","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type, and of of shape [N,C] or [C]. In the latter case, it will be treated as [1,C]","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output will be a tensor of strings or integers.","type_param_str":"T2"}]}},{"name":"LinearRegressor","schema":{"attributes":[{"description":"Weights of the model(s).","name":"coefficients","required":false,"type":"float32[]"},{"description":"Weights of the intercepts, if used.","name":"intercepts","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the regression output vector.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"default":1,"description":"The total number of regression targets, 1 if not defined.","name":"targets","required":false,"type":"int64"}],"description":"Generalized linear regression evaluation.
    \n If targets is set to 1 (default) then univariate regression is performed.
    \n If targets is set to M then M sets of coefficients must be passed in as a sequence\n and M results will be output for each input n in N.
    \n The coefficients array is of length n, and the coefficients for each target are contiguous.\n Intercepts are optional but if provided must match the number of targets.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be regressed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Regression outputs (one per target, per example).","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Log","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Log","schema":{"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Log","schema":{"description":"Calculates the natural log of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Log',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 10]).astype(np.float32)\ny = np.log(x) # expected output [0., 2.30258512]\nexpect(node, inputs=[x], outputs=[y],\n name='test_log_example')\n\nx = np.exp(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.log(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_log')","summary":"log"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The natural log of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LogSoftmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the logsoftmax (log of softmax) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the logsoftmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[-2.40760589, -1.40760589, -0.40760589]]\ny = x - np.log(np.sum(np.exp(x), axis=1))\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_example_1')","summary":"logsoftmax"},{"code":"def logsoftmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return x - max_x - np.log(np.sum(exp_x, axis=1).reshape((-1, 1)))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[-3.4401896, -2.4401896, -1.44018972, -0.44018969],\n# [-3.4401896, -2.4401896, -1.44018972, -0.44018969]]\ny = logsoftmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = logsoftmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = logsoftmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'LogSoftmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = logsoftmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_logsoftmax_negative_axis')","summary":"logsoftmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Loop","schema":{"attributes":[{"description":"The graph run each iteration. It has 2+N inputs: (iteration_num, condition, loop carried dependencies...). It has 1+N+K outputs: (condition, loop carried dependencies..., scan_outputs...). Each scan_output is created by concatenating the value of the specified output value at the end of each iteration of the loop. It is an error if the dimensions or data type of these scan_outputs change across loop iterations.","name":"body","required":true,"type":"graph"}],"description":"Generic Looping construct. This loop has multiple termination conditions:\n\n1) Trip count. Iteration count specified at runtime. Set by\n specifying the input M. Optional. Set to empty string to omit.\n Note that a static trip count (specified at graph construction time) can be\n specified by passing in a constant node for input M.\n2) Loop termination condition. This is an input to the op that determines\n whether to run the first iteration and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition variable,\n whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\n Operator inputs defined as (max_trip_count, condition_var).\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n\n\n*Sample usage - cond as well as trip count*\n\n graph predict-net {\n %a = Constant[value = ]()\n %b = Constant[value = ]()\n %keepgoing = Constant[value = ]()\n %max_trip_count = Constant[value = ]()\n %keepgoing_out, %b_out, %user_defined_vals = Loop[body = ](%max_trip_count, %keepgoing, %b)\n return\n }\n\n graph body-net (\n %i[INT32, scalar]\n %keepgoing[BOOL, scalar]\n %b[INT32, scalar]\n ) {\n %my_local = Add(%a, %b)\n %b_out = Sub(%a, %b)\n %keepgoing_out = Greater(%my_local, %b_out)\n %user_defined_vals = Add(%b, %b)\n return %keepgoing_out, %b_out, %user_defined_vals\n }\n\n*Sample equivalent C code*\n\n {\n /* User-defined code (enclosing scope) */\n int a = 3, b = 6;\n bool keepgoing = true; // Analogous to input cond\n /* End user-defined code */\n\n /* Implicitly-defined code */\n const int max_trip_count = 10; // Analogous to input M\n int user_defined_vals[]; // Imagine this is resizable\n /* End implicitly-defined code */\n for (int i=0; i < max_trip_count && keepgoing; ++i) {\n /* User-defined code (loop body) */\n int my_local = a + b; // Reading values in the enclosing scope is fine\n b = a - b; // writes fine if we specify b as a loop-carried dependency\n keepgoing = my_local > b; // keepgoing is a loop-carried dependency\n user_defined_vals[i] = b + b;\n /* End user-defined code */\n }\n // my_local = 123; // Can't do this. my_local was defined in the the body\n\n // These below values are live-out from the loop and therefore accessible\n b_out; user_defined_vals; keepgoing_out;\n }\n\nThere are several things of note in this code snippet:\n\n1) Values from the enclosing scope (i.e. variable a here) are in scope and can\n be referenced in the inputs of the loop.\n2) Any variables which you wish to make available in the enclosing scope (i.e.\n the variables b and keepgoing) must be declared as either loop-carried\n dependencies (both at the op inputs and output and at the body net input and\n output) or scan_outputs.\n3) Values created in the body cannot be accessed in the enclosing scope.\n\nNote that the semantics of this op support \"diagonal\" or \"wavefront\" execution.\n(See Step 3 here for an example:\nhttps://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).\nFrontends should emit multi-layer RNNs as a series of While operators (with\ntime being the inner looping dimension), with each successive layer consuming\nthe scan_outputs from the previous layer, possibly going through several\npoint-wise operators (e.g. dropout, residual connections, linear layer).\n","domain":"ai.onnx","inputs":[{"description":"A maximum trip-count for the loop specified at runtime. Optional. Pass empty string to skip.","name":"M","option":"optional","type":"I"},{"description":"A boolean termination condition. Optional. Pass empty string to skip.","name":"cond","option":"optional","type":"B"},{"description":"The initial values of any loop-carried dependencies (values that change across loop iterations)","name":"v_initial","option":"variadic","type":"V"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"Final N loop carried dependency values then K scan_outputs","name":"v_final_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(int64)"],"description":"tensor of int64, which should be a scalar.","type_param_str":"I"},{"allowed_type_strs":["tensor(bool)"],"description":"tensor of bool, which should be a scalar.","type_param_str":"B"}]}},{"name":"Loop","schema":{"attributes":[{"description":"The graph run each iteration. It has 2+N inputs: (iteration_num, condition, loop carried dependencies...). It has 1+N+K outputs: (condition, loop carried dependencies..., scan_outputs...). Each scan_output is created by concatenating the value of the specified output value at the end of each iteration of the loop. It is an error if the dimensions or data type of these scan_outputs change across loop iterations.","name":"body","required":true,"type":"graph"}],"description":"Generic Looping construct. This loop has multiple termination conditions:\n\n1) Trip count. Iteration count specified at runtime. Set by\n specifying the input M. Optional. Set to empty string to omit.\n Note that a static trip count (specified at graph construction time) can be\n specified by passing in a constant node for input M.\n2) Loop termination condition. This is an input to the op that determines\n whether to run the first iteration and also a loop-carried dependency for\n the body graph. The body graph must yield a value for the condition variable,\n whether this input is provided or not.\n\nThis table summarizes the operating modes of this operator with equivalent\nC-style code:\n\n Operator inputs defined as (max_trip_count, condition_var).\n\n input (\"\", \"\"):\n for (int i=0; ; ++i) {\n cond = ... // Note this value is ignored, but is required in the body\n }\n\n input (\"\", cond) // Note this is analogous to a while loop\n bool cond = ...;\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (\"\", 1) // Note this is analogous to a do-while loop\n bool cond = true\n for (int i=0; cond; ++i) {\n cond = ...;\n }\n\n input (trip_count, \"\") // Note this is analogous to a for loop\n int trip_count = ...\n for (int i=0; i < trip_count; ++i) {\n cond = ...; // ignored\n }\n\n input (trip_count, cond)\n int trip_count = ...;\n bool cond = ...;\n for (int i=0; i < trip_count && cond; ++i) {\n cond = ...;\n }\n\n\n*Sample usage - cond as well as trip count*\n\n graph predict-net {\n %a = Constant[value = ]()\n %b = Constant[value = ]()\n %keepgoing = Constant[value = ]()\n %max_trip_count = Constant[value = ]()\n %keepgoing_out, %b_out, %user_defined_vals = Loop[body = ](%max_trip_count, %keepgoing, %b)\n return\n }\n\n graph body-net (\n %i[INT32, scalar] // iteration number\n %keepgoing_in[BOOL, scalar] // incoming loop-termination-condition; not used\n %b_in[INT32, scalar] // incoming value of loop-carried-dependency b\n ) {\n %my_local = Add(%a, %b_in)\n %b_out = Sub(%a, %b_in) // outgoing value of loop-carried-dependency b\n %keepgoing_out = Greater(%my_local, %b_out) // outgoing loop-termination-condition\n %user_defined_val = Add(%b_in, %b_in) // scan-output value to be accumulated\n return %keepgoing_out, %b_out, %user_defined_val\n }\n\n*Sample equivalent C code*\n\n {\n /* User-defined code (enclosing scope) */\n int a = 3, b = 6;\n bool keepgoing = true; // Analogous to input cond\n /* End user-defined code */\n\n /* Implicitly-defined code */\n const int max_trip_count = 10; // Analogous to input M\n int user_defined_vals[]; // Imagine this is resizable\n /* End implicitly-defined code */\n /* initialize loop-carried variables and scan-output variables */\n bool keepgoing_out = keepgoing\n int b_out = b\n\n for (int i=0; i < max_trip_count && keepgoing_out; ++i) {\n /* Implicitly-defined code: bind actual parameter values\n to formal parameter variables of loop-body */\n bool keepgoing_in = keepgoing_out; \n bool b_in = b_out;\n\n /* User-defined code (loop body) */\n int my_local = a + b_in; // Reading value \"a\" from the enclosing scope is fine\n b_out = a - b_in;\n keepgoing_out = my_local > b_out; \n user_defined_val = b_in + b_in; // b_in and b_out are different variables\n /* End user-defined code */\n\n /* Implicitly defined-code */\n user_defined_vals[i] = user_defined_val // accumulate scan-output values\n }\n // int t = my_local; // Can't do this. my_local is not accessible here.\n\n // The values below are bound to the output variables of the loop and therefore accessible\n // b_out; user_defined_vals; keepgoing_out;\n }\n\nThere are several things of note in this code snippet:\n\n1) Values from the enclosing scope (i.e. variable \"a\" here) are in scope and can\n be referenced in the inputs of the loop.\n2) Any values computed in the loop body that needs to be used in a subsequent\n iteration or after the loop are modelled using a pair of variables in the loop-body,\n consisting of an input variable (eg., b_in) and an output variable (eg., b_out).\n These are referred to as loop-carried dependences. The loop operation node\n supplies the input value of the input variable for the first iteration, and\n returns the output value of the output variable produced by the final\n iteration.\n3) Scan_output variables are used to implicitly concatenate values computed across\n all the iterations. In the above example, the value of user_defined_val computed\n over all iterations are concatenated and returned as the value of user_defined_vals\n after the loop.\n4) Values created in the body cannot be accessed in the enclosing scope,\n except using the mechanism described above.\n\nNote that the semantics of this op support \"diagonal\" or \"wavefront\" execution.\n(See Step 3 here for an example:\nhttps://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).\nFrontends should emit multi-layer RNNs as a series of While operators (with\ntime being the inner looping dimension), with each successive layer consuming\nthe scan_outputs from the previous layer, possibly going through several\npoint-wise operators (e.g. dropout, residual connections, linear layer).\n\nThe input/output of subgraph (produced by loop node) matching is based on order instead of name. The implementation will figure out the names based on this order.\n","domain":"ai.onnx","inputs":[{"description":"A maximum trip-count for the loop specified at runtime. Optional. Pass empty string to skip.","name":"M","option":"optional","type":"I"},{"description":"A boolean termination condition. Optional. Pass empty string to skip.","name":"cond","option":"optional","type":"B"},{"description":"The initial values of any loop-carried dependencies (values that change across loop iterations)","name":"v_initial","option":"variadic","type":"V"}],"inputs_range":"2 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":2,"min_output":1,"outputs":[{"description":"Final N loop carried dependency values then K scan_outputs","name":"v_final_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"},{"allowed_type_strs":["tensor(int64)"],"description":"tensor of int64, which should be a scalar.","type_param_str":"I"},{"allowed_type_strs":["tensor(bool)"],"description":"tensor of bool, which should be a scalar.","type_param_str":"B"}]}},{"name":"LpNormalization","schema":{"attributes":[{"default":-1,"description":"The axis on which to apply normalization, -1 mean last axis.","name":"axis","required":false,"type":"int64"},{"default":2,"description":"The order of the normalization, only 1 or 2 are supported.","name":"p","required":false,"type":"int64"}],"category":"Normalization","description":"Given a matrix, apply Lp-normalization along the provided axis.\n","domain":"ai.onnx","inputs":[{"description":"Input matrix","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Matrix after normalization","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding. DEPRECATION NOTE: auto_pad is only intended to support legacy uses, and for framework authors, one is explicitly encouraged to use explicit padding specified in the pads attribute.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":false,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data, default is 2.0.","name":"p","required":false,"type":"float32"},{"description":"Padding for the beginning and ending along each axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across the\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimension are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"LpPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"default":2,"description":"p value of the Lp norm used to pool over the input data.","name":"p","required":false,"type":"int64"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"LpPool consumes an input tensor X and applies Lp pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n Lp pooling consisting of computing the Lp norm on all values of a subset\n of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing.","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from Lp pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes.","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"MatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MatMul',\n inputs=['a', 'b'],\n outputs=['c'],\n)\n\n# 2d\na = np.random.randn(3, 4).astype(np.float32)\nb = np.random.randn(4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_2d')\n\n# 3d\na = np.random.randn(2, 3, 4).astype(np.float32)\nb = np.random.randn(2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_3d')\n\n# 4d\na = np.random.randn(1, 2, 3, 4).astype(np.float32)\nb = np.random.randn(1, 2, 4, 3).astype(np.float32)\nc = np.matmul(a, b)\nexpect(node, inputs=[a, b], outputs=[c],\n name='test_matmul_4d')","summary":"matmul"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T"},{"description":"N-dimensional matrix B","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(bfloat16)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"MatMulInteger","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html.\nThe production MUST never overflow. The accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('MatMulInteger',\n inputs=['A', 'B', 'a_zero_point', 'b_zero_point'],\n outputs=['Y'],)\n\nA = np.array([[11, 7, 3],\n [10, 6, 2],\n [9, 5, 1],\n [8, 4, 0], ], dtype=np.uint8)\n\na_zero_point = np.array([12], dtype=np.uint8)\n\nB = np.array([[1, 4],\n [2, 5],\n [3, 6], ], dtype=np.uint8)\n\nb_zero_point = np.array([0], dtype=np.uint8)\n\noutput = np.array([[-38, -83],\n [-44, -98],\n [-50, -113],\n [-56, -128], ], dtype=np.int32)\n\nexpect(node, inputs=[A, B, a_zero_point, b_zero_point], outputs=[output],\n name='test_matmulinteger')","summary":"matmulinteger"}],"inputs":[{"description":"N-dimensional matrix A","name":"A","type":"T1"},{"description":"N-dimensional matrix B","name":"B","type":"T2"},{"description":"Zero point tensor for input 'A'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-row quantization. If it's a 1-D tensor, its number of elements should be equal to the number of rows of input 'A'.","name":"a_zero_point","option":"optional","type":"T1"},{"description":"Zero point tensor for input 'B'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.","name":"b_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 4","max_input":4,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Matrix multiply results from A * B","name":"Y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input A data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input B data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain output Y data type as 32-bit integer tensor.","type_param_str":"T3"}]}},{"name":"Max","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise max of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for Max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"max","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for Max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"max","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Max","schema":{"description":"Element-wise max of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 3]).astype(np.float32)\nresult = np.array([3, 5, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_max_example')\n\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_max_one_input')\n\nresult = np.maximum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_two_inputs')","summary":"max"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([3, 4, 4]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Max',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_max_{0}'.format(np.dtype(op_dtype).name))","summary":"max_all_numeric_types"}],"inputs":[{"description":"List of tensors for max.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"max","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)\n\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad.\n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxPool","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"Whether to use ceil or floor (default) to compute the output shape.","name":"ceil_mode","required":false,"type":"int64"},{"description":"Dilation value along each spatial axis of filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"The storage order of the tensor. 0 is row major, and 1 is column major.","name":"storage_order","required":false,"type":"int64"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"category":"Pool","description":"MaxPool consumes an input tensor X and applies max pooling across\n the tensor according to kernel sizes, stride sizes, and pad lengths.\n max pooling consisting of computing the max on all values of a\n subset of the input tensor according to the kernel size and downsampling the\n data into the output tensor Y for further processing. The output spatial shape will be following:\n ```\n output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n or\n ```\n output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1)) / strides_spatial_shape[i] + 1)\n ```\n if ceil_mode is enabled\n\n ```\n * pad_shape[i] is sum of pads along axis i\n ```\n\n `auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:\n ```\n VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) + 1) / strides_spatial_shape[i])\n SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])\n ```\n And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:\n ```\n pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + ((kernel_spatial_shape[i] - 1) * dilations[i] + 1) - input_spatial_shape[i]\n ```\n The output of each pooling window is maximum number of elements exclude pad. \n ","domain":"ai.onnx","examples":[{"code":"\"\"\"\ninput_shape: [1, 3, 32]\noutput_shape: [1, 3, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2],\n)\nx = np.random.randn(1, 3, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2]\nstrides = [1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_1d_default')","summary":"maxpool_1d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n ceil_mode=True\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_ceil')","summary":"maxpool_2d_ceil"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_default')","summary":"maxpool_2d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 4, 4]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[1, 1],\n dilations=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]]).astype(np.float32)\ny = np.array([[[\n [11, 12],\n [15, 16]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_dilations')","summary":"maxpool_2d_dilations"},{"code":"\"\"\"\ninput_shape: [1, 3, 28, 28]\noutput_shape: [1, 3, 30, 30]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n pads=[2, 2, 2, 2]\n)\nx = np.random.randn(1, 3, 28, 28).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (3, 3)\nstrides = (1, 1)\npad_bottom = pad_top = pad_right = pad_left = 2\npad_shape = [pad_top + pad_bottom, pad_left + pad_right]\nout_shape = get_output_shape('VALID', np.add(x_shape[2:], pad_shape), kernel_shape, strides)\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_pads')","summary":"maxpool_2d_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_pads')","summary":"maxpool_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 3, 3]\npad_shape: [2, 2] -> [1, 1, 1, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[3, 3],\n strides=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9, 10],\n [17, 19, 20],\n [22, 24, 25]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_same_upper')","summary":"maxpool_2d_precomputed_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_precomputed_strides')","summary":"maxpool_2d_precomputed_strides"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [1, 0, 1, 0] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_LOWER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_LOWER', x_shape[2:], kernel_shape, strides, out_shape)\npad_bottom = pad_shape[0] // 2\npad_top = pad_shape[0] - pad_bottom\npad_right = pad_shape[1] // 2\npad_left = pad_shape[1] - pad_right\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_lower')","summary":"maxpool_2d_same_lower"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 32, 32]\npad_shape: [1, 1] -> [0, 1, 0, 1] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2],\n auto_pad='SAME_UPPER'\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (2, 2)\nstrides = (1, 1)\nout_shape = get_output_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides)\npad_shape = get_pad_shape('SAME_UPPER', x_shape[2:], kernel_shape, strides, out_shape)\npad_top = pad_shape[0] // 2\npad_bottom = pad_shape[0] - pad_top\npad_left = pad_shape[1] // 2\npad_right = pad_shape[1] - pad_left\npadded = np.pad(x, ((0, 0), (0, 0), (pad_top, pad_bottom), (pad_left, pad_right)), mode='constant',\n constant_values=np.nan)\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, pad_shape, 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_same_upper')","summary":"maxpool_2d_same_upper"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32]\noutput_shape: [1, 3, 10, 10]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n strides=[3, 3]\n)\nx = np.random.randn(1, 3, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = (5, 5)\nstrides = (3, 3)\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, (0, 0), 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_strides')","summary":"maxpool_2d_strides"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.uint8)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.uint8)\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_2d_uint8')","summary":"maxpool_2d_uint8"},{"code":"\"\"\"\ninput_shape: [1, 3, 32, 32, 32]\noutput_shape: [1, 3, 31, 31, 31]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y'],\n kernel_shape=[2, 2, 2],\n)\nx = np.random.randn(1, 3, 32, 32, 32).astype(np.float32)\nx_shape = np.shape(x)\nkernel_shape = [2, 2, 2]\nstrides = [1, 1, 1]\nout_shape = get_output_shape('VALID', x_shape[2:], kernel_shape, strides)\npadded = x\ny = pool(padded, x_shape, kernel_shape, strides, out_shape, [0, 0, 0], 'MAX')\n\nexpect(node, inputs=[x], outputs=[y], name='test_maxpool_3d_default')","summary":"maxpool_3d_default"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 5, 5]\npad_shape: [4, 4] -> [2, 2, 2, 2] by axis\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[5, 5],\n pads=[2, 2, 2, 2]\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[\n [13, 14, 15, 15, 15],\n [18, 19, 20, 20, 20],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25],\n [23, 24, 25, 25, 25]]]]).astype(np.float32)\nz = np.array([[[\n [12, 13, 14, 14, 14],\n [17, 18, 19, 19, 19],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24],\n [22, 23, 24, 24, 24]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_pads')","summary":"maxpool_with_argmax_2d_precomputed_pads"},{"code":"\"\"\"\ninput_shape: [1, 1, 5, 5]\noutput_shape: [1, 1, 2, 2]\n\"\"\"\nnode = onnx.helper.make_node(\n 'MaxPool',\n inputs=['x'],\n outputs=['y', 'z'],\n kernel_shape=[2, 2],\n strides=[2, 2],\n storage_order=1\n)\nx = np.array([[[\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n [16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25],\n]]]).astype(np.float32)\ny = np.array([[[[7, 9],\n [17, 19]]]]).astype(np.float32)\nz = np.array([[[[6, 16],\n [8, 18]]]]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y, z], name='test_maxpool_with_argmax_2d_precomputed_strides')","summary":"maxpool_with_argmax_2d_precomputed_strides"}],"inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":1,"outputs":[{"description":"Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used","name":"Y","type":"T"},{"description":"Indices tensor from max pooling across the input tensor. The dimensions of indices are the same as output tensor. The values in indices of are the indices of the selected values during pooling. The indices are computed as flatten 1-D tensor, and the indices do not consider padding. So the values in indices are in [0, N x C x D1 x ... x Dn).","name":"Indices","option":"optional","type":"I"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(int8)","tensor(uint8)"],"description":"Constrain input and output types to float and 8 bit tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"MaxRoiPool","schema":{"attributes":[{"description":"ROI pool output shape (height, width).","name":"pooled_shape","required":true,"type":"int64[]"},{"default":1,"description":"Multiplicative spatial scale factor to translate ROI coordinates from their input scale to the scale used when pooling.","name":"spatial_scale","required":false,"type":"float32"}],"category":"Pool","description":"ROI max pool consumes an input tensor X and region of interests (RoIs) to\n apply max pooling across each RoI, to produce output 4-D tensor of shape\n (num_rois, channels, pooled_shape[0], pooled_shape[1]).","domain":"ai.onnx","inputs":[{"description":"Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data.","name":"X","type":"T"},{"description":"RoIs (Regions of Interest) to pool over. Should be a 2-D tensor of shape (num_rois, 5) given as [[batch_id, x1, y1, x2, y2], ...].","name":"rois","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"RoI pooled output 4-D tensor of shape (num_rois, channels, pooled_shape[0], pooled_shape[1]).","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MaxUnpool","schema":{"attributes":[{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"MaxUnpool essentially computes the partial inverse of the MaxPool op.\n The input information to this op is typically the the output information from a MaxPool op. The first\n input tensor X is the tensor that needs to be unpooled, which is typically the pooled tensor (first output)\n from MaxPool. The second input tensor, I, contains the indices to the (locally maximal) elements corrsponding\n to the elements in the first input tensor X. Input tensor I is typically the second output of the MaxPool op.\n The third (optional) input is a tensor that specifies the output size of the unpooling operation.\n\nMaxUnpool is intended to do 'partial' inverse of the MaxPool op. 'Partial' because all the non-maximal\n values from the original input to MaxPool are set to zero in the output of the MaxUnpool op. Pooling\n the result of an unpooling operation should give back the original input to the unpooling op.\n\nMaxUnpool can produce the same output size for several input sizes, which makes unpooling op ambiguous.\n The third input argument, output_size, is meant to disambiguate the op and produce output tensor of\n known/predictable size.\n\nIn addition to the inputs, MaxUnpool takes three attributes, namely kernel_shape, strides, and pads,\n which define the exact unpooling op. The attributes typically have the same values as the corrsponding\n pooling op that the unpooling op is trying to invert.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI', 'output_shape'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[5, 6],\n [7, 8]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\noutput_shape = np.array((1, 1, 5, 5), dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0, 0],\n [0, 5, 0, 6, 0],\n [0, 0, 0, 0, 0],\n [0, 7, 0, 8, 0],\n [0, 0, 0, 0, 0]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI, output_shape], outputs=[y], name='test_maxunpool_export_with_output_shape')","summary":"with_output_shape"},{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[1, 2],\n [3, 4]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0],\n [0, 1, 0, 2],\n [0, 0, 0, 0],\n [0, 3, 0, 4]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI], outputs=[y], name='test_maxunpool_export_without_output_shape')","summary":"without_output_shape"}],"inputs":[{"description":"Input data tensor that has to be unpooled. This tensor is typically the first output of the MaxPool op.Dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non-image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T1"},{"description":"Input data tensor containing the indices corresponding to elements in the first input tensor X.This tensor is typically the second output of the MaxPool op.Dimensions must be the same as input tensor X. The indices are linear, i.e. computed considering the tensor as flattened 1-D tensor, assuming row-major storage. Also, the linear indices should not consider padding. So the values in indices are in the range [0, N x C x D1 x ... x Dn).","name":"I","type":"T2"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If 'output_shape' is specified, 'pads' values are ignored.","name":"output_shape","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the unpooling.","name":"output","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"T2"}]}},{"name":"MaxUnpool","schema":{"attributes":[{"description":"The size of the kernel along each axis.","name":"kernel_shape","required":true,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"MaxUnpool essentially computes the partial inverse of the MaxPool op.\n The input information to this op is typically the the output information from a MaxPool op. The first\n input tensor X is the tensor that needs to be unpooled, which is typically the pooled tensor (first output)\n from MaxPool. The second input tensor, I, contains the indices to the (locally maximal) elements corrsponding\n to the elements in the first input tensor X. Input tensor I is typically the second output of the MaxPool op.\n The third (optional) input is a tensor that specifies the output size of the unpooling operation.\n\nMaxUnpool is intended to do 'partial' inverse of the MaxPool op. 'Partial' because all the non-maximal\n values from the original input to MaxPool are set to zero in the output of the MaxUnpool op. Pooling\n the result of an unpooling operation should give back the original input to the unpooling op.\n\nMaxUnpool can produce the same output size for several input sizes, which makes unpooling op ambiguous.\n The third input argument, output_size, is meant to disambiguate the op and produce output tensor of\n known/predictable size.\n\nIn addition to the inputs, MaxUnpool takes three attributes, namely kernel_shape, strides, and pads,\n which define the exact unpooling op. The attributes typically have the same values as the corrsponding\n pooling op that the unpooling op is trying to invert.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI', 'output_shape'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[5, 6],\n [7, 8]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\noutput_shape = np.array((1, 1, 5, 5), dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0, 0],\n [0, 5, 0, 6, 0],\n [0, 0, 0, 0, 0],\n [0, 7, 0, 8, 0],\n [0, 0, 0, 0, 0]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI, output_shape], outputs=[y], name='test_maxunpool_export_with_output_shape')","summary":"with_output_shape"},{"code":"node = onnx.helper.make_node(\n 'MaxUnpool',\n inputs=['xT', 'xI'],\n outputs=['y'],\n kernel_shape=[2, 2],\n strides=[2, 2]\n)\nxT = np.array([[[[1, 2],\n [3, 4]]]], dtype=np.float32)\nxI = np.array([[[[5, 7],\n [13, 15]]]], dtype=np.int64)\ny = np.array([[[[0, 0, 0, 0],\n [0, 1, 0, 2],\n [0, 0, 0, 0],\n [0, 3, 0, 4]]]], dtype=np.float32)\nexpect(node, inputs=[xT, xI], outputs=[y], name='test_maxunpool_export_without_output_shape')","summary":"without_output_shape"}],"inputs":[{"description":"Input data tensor that has to be unpooled. This tensor is typically the first output of the MaxPool op.Dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non-image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"X","type":"T1"},{"description":"Input data tensor containing the indices corresponding to elements in the first input tensor X.This tensor is typically the second output of the MaxPool op.Dimensions must be the same as input tensor X. The indices are linear, i.e. computed considering the tensor as flattened 1-D tensor, assuming row-major storage. Also, the linear indices should not consider padding. So the values in indices are in the range [0, N x C x D1 x ... x Dn).","name":"I","type":"T2"},{"description":"The shape of the output can be explicitly set which will cause pads values to be auto generated. If 'output_shape' is specified, 'pads' values are ignored.","name":"output_shape","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the unpooling.","name":"output","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"T2"}]}},{"name":"Mean","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise mean of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for Mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"mean","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for Mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"mean","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"mean","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mean","schema":{"description":"Element-wise mean of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([2, 3, 4]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_mean_example')\n\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_mean_one_input')\n\nresult = np.divide(np.add(data_0, data_1), 2.)\nnode = onnx.helper.make_node(\n 'Mean',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_mean_two_inputs')","summary":"mean"}],"inputs":[{"description":"List of tensors for mean.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"mean","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"MeanVarianceNormalization","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to caculate along axes [0,2,3] for calculating mean and variance along each channel. Two variables with the same C-coordinate are associated with the same mean and variance.","name":"axes","required":false,"type":"int64[]"}],"description":"A MeanVarianceNormalization Function: Perform mean variance normalization\n on the input tensor X using formula:
    ``` (X-EX)/sqrt(E(X-EX)^2) ```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MeanVarianceNormalization',\n inputs=['X'],\n outputs=['Y']\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\ndata_mean = np.mean(input_data, axis=(0, 2, 3), keepdims=1)\ndata_mean_squared = np.power(data_mean, 2)\ndata_squared = np.power(input_data, 2)\ndata_squared_mean = np.mean(data_squared, axis=(0, 2, 3), keepdims=1)\nstd = np.sqrt(data_squared_mean - data_mean_squared)\nexpected_output = (input_data - data_mean) / (std + 1e-9)\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_mvn')","summary":"meanvariancenormalization"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"MeanVarianceNormalization","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to caculate along axes [0,2,3] for calculating mean and variance along each channel. Two variables with the same C-coordinate are associated with the same mean and variance.","name":"axes","required":false,"type":"int64[]"}],"description":"A MeanVarianceNormalization Function: Perform mean variance normalization\n on the input tensor X using formula:
    ``` (X-EX)/sqrt(E(X-EX)^2) ```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'MeanVarianceNormalization',\n inputs=['X'],\n outputs=['Y']\n)\n\ninput_data = np.array([[[[0.8439683], [0.5665144], [0.05836735]],\n [[0.02916367], [0.12964272], [0.5060197]],\n [[0.79538304], [0.9411346], [0.9546573]]],\n [[[0.17730942], [0.46192095], [0.26480448]],\n [[0.6746842], [0.01665257], [0.62473077]],\n [[0.9240844], [0.9722341], [0.11965699]]],\n [[[0.41356155], [0.9129373], [0.59330076]],\n [[0.81929934], [0.7862604], [0.11799799]],\n [[0.69248444], [0.54119414], [0.07513223]]]], dtype=np.float32)\n\n# Calculate expected output data\ndata_mean = np.mean(input_data, axis=(0, 2, 3), keepdims=1)\ndata_mean_squared = np.power(data_mean, 2)\ndata_squared = np.power(input_data, 2)\ndata_squared_mean = np.mean(data_squared, axis=(0, 2, 3), keepdims=1)\nstd = np.sqrt(data_squared_mean - data_mean_squared)\nexpected_output = (input_data - data_mean) / (std + 1e-9)\n\nexpect(node, inputs=[input_data], outputs=[expected_output],\n name='test_mvn')","summary":"meanvariancenormalization"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise min of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for Min","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"min","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for Min","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"min","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Min","schema":{"description":"Element-wise min of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 2, 1]).astype(np.float32)\ndata_1 = np.array([1, 4, 4]).astype(np.float32)\ndata_2 = np.array([2, 5, 0]).astype(np.float32)\nresult = np.array([1, 2, 0]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_min_example')\n\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_min_one_input')\n\nresult = np.minimum(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_two_inputs')","summary":"min"},{"code":"for op_dtype in all_numeric_dtypes:\n data_0 = np.array([3, 2, 1]).astype(op_dtype)\n data_1 = np.array([1, 4, 4]).astype(op_dtype)\n result = np.array([1, 2, 1]).astype(op_dtype)\n node = onnx.helper.make_node(\n 'Min',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_min_{0}'.format(np.dtype(op_dtype).name))","summary":"min_all_numeric_types"}],"inputs":[{"description":"List of tensors for min.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"min","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"}]}},{"name":"Mod","schema":{"attributes":[{"description":"Whether the operator should behave like fmod (default=0 meaning it will do integer mods); Set this to 1 to force fmod treatment","name":"fmod","required":false,"type":"int64"}],"description":"Performs element-wise binary modulus (with Numpy-style broadcasting support). \n The sign of the remainder is the same as that of the Divisor.\n \n Mod operator can also behave like C fmod() or numpy.fmod. In this case, the sign of the remainder however, will be the same as the Dividend \n (in contrast to integer mod). To force a behavior like numpy.fmod() an 'fmod' Attribute is provided.\n This attribute is set to 0 by default causing the behavior to be like integer mod. \n Setting this attribute to 1 causes the remainder to be calculated similar to that of numpy.fmod().\n\n If the input type is floating point, then `fmod` attribute must be set to 1.\n \n In case of dividend being zero, the results will be platform dependent.\n\n This operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.arange(0, 30).reshape([3, 2, 5])\ny = np.array([7])\nz = np.mod(x, y)\nz\n# array([[[0, 1, 2, 3, 4],\n# [5, 6, 0, 1, 2]],\n\n# [[3, 4, 5, 6, 0],\n# [1, 2, 3, 4, 5]],\n\n# [[6, 0, 1, 2, 3],\n# [4, 5, 6, 0, 1]]], dtype=int32)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_broadcast')","summary":"mod_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.fmod(x, y) # expected output [ 0, 1, 5, 0, -1, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_int64_fmod')","summary":"mod_int64_fmod"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float16)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float16)\nz = np.fmod(x, y) # expected output [-0.10156, 0.3984 , 5. , 0.10156, -0.3984 , 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float16')","summary":"mod_mixed_sign_float16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float32)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float32)\nz = np.fmod(x, y) # expected output [-0.10000038, 0.39999962, 5. , 0.10000038, -0.39999962, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float32')","summary":"mod_mixed_sign_float32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float64)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float64)\nz = np.fmod(x, y) # expected output [-0.1, 0.4, 5. , 0.1, -0.4, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float64')","summary":"mod_mixed_sign_float64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int16)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int16)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int16')","summary":"mod_mixed_sign_int16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int32)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int32)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int32')","summary":"mod_mixed_sign_int32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int64')","summary":"mod_mixed_sign_int64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int8)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int8)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int8')","summary":"mod_mixed_sign_int8"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint16)\ny = np.array([2, 3, 8]).astype(np.uint16)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint16')","summary":"mod_uint16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint32)\ny = np.array([2, 3, 8]).astype(np.uint32)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint32')","summary":"mod_uint32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint64)\ny = np.array([2, 3, 8]).astype(np.uint64)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint64')","summary":"mod_uint64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint8)\ny = np.array([2, 3, 8]).astype(np.uint8)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint8')","summary":"mod_uint8"}],"inputs":[{"description":"Dividend tensor","name":"A","type":"T"},{"description":"Divisor tensor","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Remainder tensor","name":"C","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mod","schema":{"attributes":[{"description":"Whether the operator should behave like fmod (default=0 meaning it will do integer mods); Set this to 1 to force fmod treatment","name":"fmod","required":false,"type":"int64"}],"description":"Performs element-wise binary modulus (with Numpy-style broadcasting support). \n The sign of the remainder is the same as that of the Divisor.\n \n Mod operator can also behave like C fmod() or numpy.fmod. In this case, the sign of the remainder however, will be the same as the Dividend \n (in contrast to integer mod). To force a behavior like numpy.fmod() an 'fmod' Attribute is provided.\n This attribute is set to 0 by default causing the behavior to be like integer mod. \n Setting this attribute to 1 causes the remainder to be calculated similar to that of numpy.fmod().\n\n If the input type is floating point, then `fmod` attribute must be set to 1.\n \n In case of dividend being zero, the results will be platform dependent.\n\n This operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.arange(0, 30).reshape([3, 2, 5])\ny = np.array([7])\nz = np.mod(x, y)\nz\n# array([[[0, 1, 2, 3, 4],\n# [5, 6, 0, 1, 2]],\n\n# [[3, 4, 5, 6, 0],\n# [1, 2, 3, 4, 5]],\n\n# [[6, 0, 1, 2, 3],\n# [4, 5, 6, 0, 1]]], dtype=int32)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_broadcast')","summary":"mod_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.fmod(x, y) # expected output [ 0, 1, 5, 0, -1, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_int64_fmod')","summary":"mod_int64_fmod"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float16)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float16)\nz = np.fmod(x, y) # expected output [-0.10156, 0.3984 , 5. , 0.10156, -0.3984 , 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float16')","summary":"mod_mixed_sign_float16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float32)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float32)\nz = np.fmod(x, y) # expected output [-0.10000038, 0.39999962, 5. , 0.10000038, -0.39999962, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float32')","summary":"mod_mixed_sign_float32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n fmod=1\n)\n\nx = np.array([-4.3, 7.2, 5.0, 4.3, -7.2, 8.0]).astype(np.float64)\ny = np.array([2.1, -3.4, 8.0, -2.1, 3.4, 5.0]).astype(np.float64)\nz = np.fmod(x, y) # expected output [-0.1, 0.4, 5. , 0.1, -0.4, 3.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_float64')","summary":"mod_mixed_sign_float64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int16)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int16)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int16')","summary":"mod_mixed_sign_int16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int32)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int32)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int32')","summary":"mod_mixed_sign_int32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int64)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int64)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int64')","summary":"mod_mixed_sign_int64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([-4, 7, 5, 4, -7, 8]).astype(np.int8)\ny = np.array([2, -3, 8, -2, 3, 5]).astype(np.int8)\nz = np.mod(x, y) # expected output [ 0, -2, 5, 0, 2, 3]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_mixed_sign_int8')","summary":"mod_mixed_sign_int8"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint16)\ny = np.array([2, 3, 8]).astype(np.uint16)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint16')","summary":"mod_uint16"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint32)\ny = np.array([2, 3, 8]).astype(np.uint32)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint32')","summary":"mod_uint32"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint64)\ny = np.array([2, 3, 8]).astype(np.uint64)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint64')","summary":"mod_uint64"},{"code":"node = onnx.helper.make_node(\n 'Mod',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([4, 7, 5]).astype(np.uint8)\ny = np.array([2, 3, 8]).astype(np.uint8)\nz = np.mod(x, y) # expected output [0, 1, 5]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mod_uint8')","summary":"mod_uint8"}],"inputs":[{"description":"Dividend tensor","name":"A","type":"T"},{"description":"Divisor tensor","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Remainder tensor","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Momentum","schema":{"attributes":[{"description":"The decay factor of momentum. It should be a scalar.","name":"alpha","required":true,"type":"float32"},{"description":"The coefficient of gradient in computing new momentum. It should be a scalar.","name":"beta","required":true,"type":"float32"},{"description":"Its value should be either \"nesterov\" or \"standard\". The value \"nesterov\" leads to the use of Nesterov's momentum while \"standard\" invokes stochastic gradient method using standard momentum","name":"mode","required":true,"type":"string"},{"description":"Coefficient of 0.5 * norm_coefficient * ||X||^2.","name":"norm_coefficient","required":true,"type":"float32"}],"description":"Compute one iteration of stochastic gradient update with momentum.\n This operator can conduct the optimization of multiple tensor variables.\n\n Let's define the behavior of this operator. As you can imagine, SG with momentum requires\n several parameters:\n \n - The learning-rate \"R\".\n - The update count \"T\". That is, the number of conducted training iterations. It should\n be zero in the first training iteration.\n - A L2-norm regularization coefficient \"norm_coefficient\".\n - A decay coefficient of previous accumulated gradient (i.e., momentum) \"alpha\".\n - The scaling coefficient of current gradient \"beta\".\n - An attribute to choose either standard momentum or Nesterov's momentum \"mode\" should\n be used.\n\n For the sake of simplicity, assume that there is only one tensor (called \"X\") to be optimized.\n Other necessary inputs are \"X\"'s gradient (called \"G\") and \"X\"'s momentum (called \"V\"). This\n Momentum operator maps all these inputs to the new value of \"X\" (called \"X_new\") and its new\n momentum (called \"V_new\").\n \n This operator supports two different momentum algorithms. Set the attribute \"mode\" to\n \"nesterov\" if Nesterov's momentum is desired. Otherwise, set the attribute \"model\" to\n \"standard\" to use standard momentum. Computation details are described subsequently.\n\n Let \"+\", \"-\", \"*\", and \"/\" are all element-wise operations with numpy-style broadcasting.\n\n Pseudo code for SG with standard momentum:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared\n // values of all elements in X.\n G_regularized = norm_coefficient * X + G\n\n // In the first training iteration, beta should always be 1.\n beta_adjusted = T > 0 ? beta : 1\n\n // Compute the current momentum based on previous momentum and the current gradient.\n V_new = alpha * V + beta_adjusted * G_regularized\n\n // Update X.\n X_new = X - R * V_new\n\n Pseudo code for SG with Nesterov's momentum:\n\n // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared\n // values of all elements in X.\n G_regularized = norm_coefficient * X + G;\n\n // In the first training iteration, beta should always be 1.\n beta_adjusted = T > 0 ? beta : 1\n\n // Compute the current momentum based on previous momentum and the current gradient.\n V_new = alpha * V + beta_adjusted * G_regularized;\n\n // Compute final update direction and then update X.\n X_new = X - R * (G_regularized + alpha * V_new)\n\n If one assign this operators to optimize multiple inputs, for example, \"X_1\" and \"X_2\". The same\n pseudo code would be extended to handle all tensors jointly. More specifically, we can view \"X\" as a\n concatenation of \"X_1\" and \"X_2\" (of course, their gradient and accumulate gradient should\n be concatenated too) and then our pseudo code becomes applicable.\n","domain":"ai.onnx.preview.training","examples":[{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.1\n\n# Create operator.\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X', 'G', 'V'],\n outputs=['X_new', 'V_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='standard',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx_new, v_new = apply_momentum(r, t, x, g, v,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v],\n outputs=[x_new, v_new], name='test_momentum',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"momentum"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.001\nalpha = 0.95\nbeta = 0.85\n\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X1', 'X2',\n 'G1', 'G2', 'H1', 'H2'],\n outputs=['X1_new', 'X2_new',\n 'V1_new', 'V2_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='standard',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\n\nx1 = np.array([1.0], dtype=np.float32)\ng1 = np.array([-1.0], dtype=np.float32)\nv1 = np.array([2.0], dtype=np.float32)\n\nx2 = np.array([1.0, 2.0], dtype=np.float32)\ng2 = np.array([-1.0, -3.0], dtype=np.float32)\nv2 = np.array([4.0, 1.0], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx1_new, v1_new = apply_momentum(r, t, x1, g1, v1,\n norm_coefficient, alpha, beta)\nx2_new, v2_new = apply_momentum(r, t, x2, g2, v2,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x1, x2, g1, g2, v1, v2],\n outputs=[x1_new, x2_new, v1_new, v2_new], name='test_momentum_multiple',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"momentum_multiple"},{"code":"# Define operator attributes.\nnorm_coefficient = 0.01\nalpha = 0.95\nbeta = 1.0\n\n# Create operator.\nnode = onnx.helper.make_node('Momentum',\n inputs=['R', 'T', 'X', 'G', 'V'],\n outputs=['X_new', 'V_new'],\n norm_coefficient=norm_coefficient,\n alpha=alpha,\n beta=beta,\n mode='nesterov',\n domain=AI_ONNX_PREVIEW_TRAINING_DOMAIN\n )\n\n# Define operator inputs.\nr = np.array(0.1, dtype=np.float32) # scalar\nt = np.array(0, dtype=np.int64) # scalar\nx = np.array([1.2, 2.8], dtype=np.float32)\ng = np.array([-0.94, -2.5], dtype=np.float32)\nv = np.array([1.7, 3.6], dtype=np.float32)\n\n# Compute expected outputs of Momentum.\nx_new, v_new = apply_nesterov(r, t, x, g, v,\n norm_coefficient, alpha, beta)\n\n# Check results.\nexpect(node, inputs=[r, t, x, g, v],\n outputs=[x_new, v_new], name='test_nesterov_momentum',\n opset_imports=[onnx.helper.make_opsetid(AI_ONNX_PREVIEW_TRAINING_DOMAIN, 1)])","summary":"nesterov_momentum"}],"inputs":[{"description":"The learning rate.","name":"R","type":"T1"},{"description":"Update count of \"X\". It should be a scalar.","name":"T","type":"T2"},{"description":"It sequentially contains the current values of optimized tensors, then their gradient tensors, and finally their momentum tensors. For example, if two tensors \"X_1\" and \"X_2\" are optimized, The expected input list would be [\"X_1\", \"X_2\", gradient of \"X_1\", gradient of \"X_2\", momentum of \"X_1\", momentum of \"X_2\"].","name":"inputs","option":"variadic","type":"T3"}],"inputs_range":"3 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":3,"min_output":1,"outputs":[{"description":"It sequentially contains the new values of optimized tensors and then the new values of their momentum tensors. For example, if two tensors \"X_1\" and \"X_2\" are optimized, the output list would be [new value of \"X_1,\" new value of \"X_2\" new momentum of \"X_1\", new momentum of \"X_2\"].","name":"outputs","option":"variadic","type":"T3"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float scalars.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain input types to 64-bit integer scalars.","type_param_str":"T2"},{"allowed_type_strs":["tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T3"}]}},{"name":"Mul","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary multiplication (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"description":"Performs element-wise binary multiplication (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Mul","schema":{"description":"Performs element-wise binary multiplication (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = x * y # expected output [4., 10., 18.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul')","summary":"mul"},{"code":"node = onnx.helper.make_node(\n 'Mul',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x * y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_mul_bcast')","summary":"mul_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Multinomial","schema":{"attributes":[{"default":6,"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use int32.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Number of times to sample.","name":"sample_size","required":false,"type":"int64"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor of samples from a multinomial distribution according to the probabilities\nof each of the possible outcomes.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor with shape [batch_size, class_size], where class_size is the number of all possible outcomes. Each value along the axis zero represents the unnormalized log-probability of each corresponding outcome in a batch.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor with shape [batch_size, sample_size], where sample_size is the number of times to sample. Each value along the axis zero represents the outcome of the corresponding sample in a batch.","name":"output","type":"T2"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain output types to integral tensors.","type_param_str":"T2"}]}},{"name":"Neg","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Neg","schema":{"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)","tensor(int8)","tensor(int16)","tensor(int64)","tensor(float16)","tensor(double)"],"description":"Constrain input and output types to signed numeric tensors.","type_param_str":"T"}]}},{"name":"Neg","schema":{"description":"Neg takes one input data (Tensor) and produces one output data\n(Tensor) where each element flipped sign, y = -x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Neg',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.negative(x) # expected output [4., -2.],\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.negative(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_neg')","summary":"neg"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)","tensor(int8)","tensor(int16)","tensor(int64)","tensor(float16)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to signed numeric tensors.","type_param_str":"T"}]}},{"name":"NegativeLogLikelihoodLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean (default). 'none': the output is the loss for each sample. 'sum': the output will be summed. 'mean': the sum of the output will be divided by the sum of applied weights.","name":"reduction","required":false,"type":"string"}],"description":"A NegativeLogLikelihoodLoss operator computes (weighted) negative log likelihood loss.\nIts \"input\" tensor has the shape of (N, C, d1, d2, ..., dk) where k >= 0.\nThe \"input\" tensor contains log-probabilities for input[n, :, d_1, d_2,..., d_k] being in a class of [0, C).\nThe operator's \"target\" input tensor has the shape of (N, d1, d2, ..., dk). It encodes class labels (one of C classes)\nor it may contain a special value (indicated by an attribute ignore_index) for N x d1 x d2 x ... x dk samples.\nThe loss value for input[n, :, d_1, d_2,...d_k] being classified as class c = target[n][d_1][d_2]...[d_k] is computed as:\n\n loss[n][d_1][d_2]...[d_k] = -input[n][c][d_1][d_2]...[d_k].\n\nWhen an optional \"weight\" is provided, the sample loss is calculated as:\n\n loss[n][d_1][d_2]...[d_k] = -input[n][c][d_1][d_2]...[d_k] * weight[c].\n\nloss is zero for the case when target-value equals ignore_index.\n \n loss[n][d_1][d_2]...[d_k] = 0, when target[n][d_1][d_2]...[d_k] = ignore_index\n\nIf \"reduction\" attribute is set to \"none\", the operator's output will be the above loss with shape (N, d1, d2, ..., dk).\nIf \"reduction\" attribute is set to \"mean\" (the default attribute value), the output loss is (weight) averaged:\n\n mean(loss), if \"weight\" is not provided,\n\nor if weight is provided,\n\n sum(loss) / sum(weight[target[n][d_1][d_2]...[d_k]]]), for all samples.\n\nIf \"reduction\" attribute is set to \"sum\", the output is a scalar:\n sum(loss).\n\nSee also https://pytorch.org/docs/stable/nn.html#torch.nn.NLLLoss.\n\nExample 1:\n\n // negative log likelihood loss, \"none\" reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n\n loss = np.zeros((N, d1))\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1]\n\n // print(loss)\n // [[-3. -2.]\n // [-0. -2.]]\n\nExample 2:\n\n // weighted negative log likelihood loss, sum reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n weight = [0.2, 0.3, 0.1]\n loss = np.zeros((N, d1))\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1] * weight[c]\n\n loss = np.sum(loss)\n // print(loss)\n // -1.1\n\nExample 3:\n\n // weighted negative log likelihood loss, mean reduction\n N, C, d1 = 2, 3, 2\n input = [[[1.0, 2.0], [2.0, 2.0], [3.0, 2.0]],\n [[0.0, 1.0], [2.0, 2.0], [1.0, 2]]]\n target = [[2, 1], [0, 2]]\n weight = [0.2, 0.3, 0.1]\n loss = np.zeros((N, d1))\n weight_total = 0\n for n in range(N):\n for d_1 in range(d1):\n c = target[n][d_1]\n loss[n][d_1] = -input[n][c][d_1] * weight[c]\n weight_total = weight_total + weight[c]\n\n loss = np.sum(loss) / weight_total\n // print(loss)\n // -1.57\n","domain":"ai.onnx","examples":[{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C = 3, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, ))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NC')","summary":"input_shape_is_NC"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1')","summary":"input_shape_is_NCd1"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\ntarget[0][0] = np.int64(1)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_ii')","summary":"input_shape_is_NCd1_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1))\ntarget[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_weight')","summary":"input_shape_is_NCd1_weight"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, d1 = 3, 5, 2\nnp.random.seed(0)\ninput = np.random.rand(N, C, d1).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, d1))\ntarget[0][0] = np.int64(1)\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1_weight_ii')","summary":"input_shape_is_NCd1_weight_ii"},{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2')","summary":"input_shape_is_NCd1d2"},{"code":"reduction = 'mean'\nignore_index = np.int64(1)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\ntarget[0][0][0] = np.int64(1)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_no_weight_reduction_mean_ii')","summary":"input_shape_is_NCd1d2_no_weight_reduction_mean_ii"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_reduction_mean')","summary":"input_shape_is_NCd1d2_reduction_mean"},{"code":"reduction = 'sum'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=None, reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_reduction_sum')","summary":"input_shape_is_NCd1d2_reduction_sum"},{"code":"reduction = 'none'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight')","summary":"input_shape_is_NCd1d2_with_weight"},{"code":"reduction = 'mean'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_mean')","summary":"input_shape_is_NCd1d2_with_weight_reduction_mean"},{"code":"reduction = 'sum'\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_sum')","summary":"input_shape_is_NCd1d2_with_weight_reduction_sum"},{"code":"reduction = 'sum'\nignore_index = np.int64(0)\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index\n)\n\nN, C, dim1, dim2 = 3, 5, 6, 6\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2))\ntarget[0][0][0] = np.int64(0)\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input, target, weight=weight, reduction=reduction, ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2_with_weight_reduction_sum_ii')","summary":"input_shape_is_NCd1d2_with_weight_reduction_sum_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\ntarget[0][0][0][0] = -5\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\ninput = np.random.rand(N, C).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N))\ntarget[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target', 'weight'],\n outputs=['loss'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[input, target, weight], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node(\n 'NegativeLogLikelihoodLoss',\n inputs=['input', 'target'],\n outputs=['loss'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\ninput = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\ntarget = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nnegative_log_likelihood_loss = compute_negative_log_likelihood_loss(input,\n target,\n reduction=reduction)\n\nexpect(node, inputs=[input, target], outputs=[negative_log_likelihood_loss],\n name='test_nllloss_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"}],"inputs":[{"description":"Input tensor of shape (N, C) or (N, C, d1, d2, ..., dk).","name":"input","type":"T"},{"description":"Target tensor of shape (N) or (N, d1, d2, ..., dk). Target element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the target values should either be in the range [0, C) or have the value ignore_index.","name":"target","type":"Tind"},{"description":"Optional rescaling weight tensor. If given, it has to be a tensor of size C. Otherwise, it is treated as if having all ones.","name":"weight","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"The negative log likelihood loss","name":"loss","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input, weight, and output types to floating-point tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"NonMaxSuppression","schema":{"attributes":[{"description":"Integer indicate the format of the box data. The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Mostly used for TF models. 1 - the box data is supplied as [x_center, y_center, width, height]. Mostly used for Pytorch models.","name":"center_point_box","required":false,"type":"int64"}],"description":"Filter out boxes that have high intersection-over-union (IOU) overlap with previously selected boxes.\nBounding boxes with score less than score_threshold are removed. Bounding box format is indicated by attribute center_point_box.\nNote that this algorithm is agnostic to where the origin is in the coordinate system and more generally is invariant to\northogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system\nresult in the same boxes being selected by the algorithm.\nThe selected_indices output is a set of integers indexing into the input collection of bounding boxes representing the selected boxes.\nThe bounding box coordinates corresponding to the selected indices can then be obtained using the Gather or GatherND operation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices'],\n center_point_box=1\n)\nboxes = np.array([[\n [0.5, 0.5, 1.0, 1.0],\n [0.5, 0.6, 1.0, 1.0],\n [0.5, 0.4, 1.0, 1.0],\n [0.5, 10.5, 1.0, 1.0],\n [0.5, 10.6, 1.0, 1.0],\n [0.5, 100.5, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_center_point_box_format')","summary":"nonmaxsuppression_center_point_box_format"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [1.0, 1.0, 0.0, 0.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, 0.9, 1.0, -0.1],\n [0.0, 10.0, 1.0, 11.0],\n [1.0, 10.1, 0.0, 11.1],\n [1.0, 101.0, 0.0, 100.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_flipped_coordinates')","summary":"nonmaxsuppression_flipped_coordinates"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_identical_boxes')","summary":"nonmaxsuppression_identical_boxes"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_limit_output_size')","summary":"nonmaxsuppression_limit_output_size"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_single_box')","summary":"nonmaxsuppression_single_box"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU')","summary":"nonmaxsuppression_suppress_by_IOU"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.4]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU_and_scores')","summary":"nonmaxsuppression_suppress_by_IOU_and_scores"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]],\n [[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]],\n [[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [1, 0, 3], [1, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_batches')","summary":"nonmaxsuppression_two_batches"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3],\n [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 1, 3], [0, 1, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_classes')","summary":"nonmaxsuppression_two_classes"}],"inputs":[{"description":"An input tensor with shape [num_batches, spatial_dimension, 4]. The single box data format is indicated by center_point_box.","name":"boxes","type":"tensor(float)"},{"description":"An input tensor with shape [num_batches, num_classes, spatial_dimension]","name":"scores","type":"tensor(float)"},{"description":"Integer representing the maximum number of boxes to be selected per batch per class. It is a scalar. Default to 0, which means no output.","name":"max_output_boxes_per_class","option":"optional","type":"tensor(int64)"},{"description":"Float representing the threshold for deciding whether boxes overlap too much with respect to IOU. It is scalar. Value range [0, 1]. Default to 0.","name":"iou_threshold","option":"optional","type":"tensor(float)"},{"description":"Float representing the threshold for deciding when to remove boxes based on score. It is a scalar.","name":"score_threshold","option":"optional","type":"tensor(float)"}],"inputs_range":"2 - 5","max_input":5,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"selected indices from the boxes tensor. [num_selected_indices, 3], the selected index format is [batch_index, class_index, box_index].","name":"selected_indices","type":"tensor(int64)"}],"since_version":10,"support_level":"common"}},{"name":"NonMaxSuppression","schema":{"attributes":[{"description":"Integer indicate the format of the box data. The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Mostly used for TF models. 1 - the box data is supplied as [x_center, y_center, width, height]. Mostly used for Pytorch models.","name":"center_point_box","required":false,"type":"int64"}],"description":"Filter out boxes that have high intersection-over-union (IOU) overlap with previously selected boxes.\nBounding boxes with score less than score_threshold are removed. Bounding box format is indicated by attribute center_point_box.\nNote that this algorithm is agnostic to where the origin is in the coordinate system and more generally is invariant to\northogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system\nresult in the same boxes being selected by the algorithm.\nThe selected_indices output is a set of integers indexing into the input collection of bounding boxes representing the selected boxes.\nThe bounding box coordinates corresponding to the selected indices can then be obtained using the Gather or GatherND operation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices'],\n center_point_box=1\n)\nboxes = np.array([[\n [0.5, 0.5, 1.0, 1.0],\n [0.5, 0.6, 1.0, 1.0],\n [0.5, 0.4, 1.0, 1.0],\n [0.5, 10.5, 1.0, 1.0],\n [0.5, 10.6, 1.0, 1.0],\n [0.5, 100.5, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_center_point_box_format')","summary":"nonmaxsuppression_center_point_box_format"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [1.0, 1.0, 0.0, 0.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, 0.9, 1.0, -0.1],\n [0.0, 10.0, 1.0, 11.0],\n [1.0, 10.1, 0.0, 11.1],\n [1.0, 101.0, 0.0, 100.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_flipped_coordinates')","summary":"nonmaxsuppression_flipped_coordinates"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_identical_boxes')","summary":"nonmaxsuppression_identical_boxes"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_limit_output_size')","summary":"nonmaxsuppression_limit_output_size"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_single_box')","summary":"nonmaxsuppression_single_box"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 0, 5]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU')","summary":"nonmaxsuppression_suppress_by_IOU"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([3]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.4]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_suppress_by_IOU_and_scores')","summary":"nonmaxsuppression_suppress_by_IOU_and_scores"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]],\n [[0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]],\n [[0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [1, 0, 3], [1, 0, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_batches')","summary":"nonmaxsuppression_two_batches"},{"code":"node = onnx.helper.make_node(\n 'NonMaxSuppression',\n inputs=['boxes', 'scores', 'max_output_boxes_per_class', 'iou_threshold', 'score_threshold'],\n outputs=['selected_indices']\n)\nboxes = np.array([[\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.1, 1.0, 1.1],\n [0.0, -0.1, 1.0, 0.9],\n [0.0, 10.0, 1.0, 11.0],\n [0.0, 10.1, 1.0, 11.1],\n [0.0, 100.0, 1.0, 101.0]\n]]).astype(np.float32)\nscores = np.array([[[0.9, 0.75, 0.6, 0.95, 0.5, 0.3],\n [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]]]).astype(np.float32)\nmax_output_boxes_per_class = np.array([2]).astype(np.int64)\niou_threshold = np.array([0.5]).astype(np.float32)\nscore_threshold = np.array([0.0]).astype(np.float32)\nselected_indices = np.array([[0, 0, 3], [0, 0, 0], [0, 1, 3], [0, 1, 0]]).astype(np.int64)\n\nexpect(node, inputs=[boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold], outputs=[selected_indices], name='test_nonmaxsuppression_two_classes')","summary":"nonmaxsuppression_two_classes"}],"inputs":[{"description":"An input tensor with shape [num_batches, spatial_dimension, 4]. The single box data format is indicated by center_point_box.","name":"boxes","type":"tensor(float)"},{"description":"An input tensor with shape [num_batches, num_classes, spatial_dimension]","name":"scores","type":"tensor(float)"},{"description":"Integer representing the maximum number of boxes to be selected per batch per class. It is a scalar. Default to 0, which means no output.","name":"max_output_boxes_per_class","option":"optional","type":"tensor(int64)"},{"description":"Float representing the threshold for deciding whether boxes overlap too much with respect to IOU. It is scalar. Value range [0, 1]. Default to 0.","name":"iou_threshold","option":"optional","type":"tensor(float)"},{"description":"Float representing the threshold for deciding when to remove boxes based on score. It is a scalar.","name":"score_threshold","option":"optional","type":"tensor(float)"}],"inputs_range":"2 - 5","max_input":5,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"selected indices from the boxes tensor. [num_selected_indices, 3], the selected index format is [batch_index, class_index, box_index].","name":"selected_indices","type":"tensor(int64)"}],"since_version":11,"support_level":"common"}},{"name":"NonZero","schema":{"description":"Returns the indices of the elements that are non-zero\n (in row-major order - by dimension).\n NonZero behaves similar to numpy.nonzero:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonZero',\n inputs=['condition'],\n outputs=['result'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nresult = np.array((np.nonzero(condition))) # expected output [[0, 1, 1], [0, 0, 1]]\nexpect(node, inputs=[condition], outputs=[result],\n name='test_nonzero_example')","summary":"nonzero"}],"inputs":[{"description":"input","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"tensor(int64)"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to all tensor types.","type_param_str":"T"}]}},{"name":"NonZero","schema":{"description":"Returns the indices of the elements that are non-zero\n (in row-major order - by dimension).\n NonZero behaves similar to numpy.nonzero:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'NonZero',\n inputs=['condition'],\n outputs=['result'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nresult = np.array((np.nonzero(condition))) # expected output [[0, 1, 1], [0, 0, 1]]\nexpect(node, inputs=[condition], outputs=[result],\n name='test_nonzero_example')","summary":"nonzero"}],"inputs":[{"description":"input","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"output","name":"Y","type":"tensor(int64)"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to all tensor types.","type_param_str":"T"}]}},{"name":"Normalizer","schema":{"attributes":[{"default":"MAX","description":"One of 'MAX,' 'L1,' 'L2'","name":"norm","required":false,"type":"string"}],"description":"Normalize the input. There are three normalization modes, which have the corresponding formulas,\n defined using element-wise infix operators '/' and '^' and tensor-wide functions 'max' and 'sum':
    \n
    \n Max: Y = X / max(X)
    \n L1: Y = X / sum(X)
    \n L2: Y = sqrt(X^2 / sum(X^2)}
    \n In all modes, if the divisor is zero, Y == X.\n
    \n For batches, that is, [N,C] tensors, normalization is done along the C axis. In other words, each row\n of the batch is normalized independently.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be encoded, a tensor of shape [N,C] or [C]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Encoded output data","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Not","schema":{"category":"Logic","description":"Returns the negation of the input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Not',\n inputs=['x'],\n outputs=['not'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nexpect(node, inputs=[x], outputs=[np.logical_not(x)],\n name='test_not_4d')","summary":"not"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input/output to boolean tensors.","type_param_str":"T"}]}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"(Optional) Axis along which one-hot representation in added. Default: axis=-1. axis=-1 means that the additional dimension will be inserted as the innermost/last dimension in the output tensor.","name":"axis","required":false,"type":"int64"}],"description":"Produces a one-hot tensor based on inputs.\n The locations represented by the index values in the 'indices' input tensor will have 'on_value'\n and the other locations will have 'off_value' in the output tensor, where 'on_value' and 'off_value'\n are specified as part of required input argument 'values', which is a two-element tensor of format\n [off_value, on_value]. The rank of the output tensor will be one greater than the rank of the\n input tensor. The additional dimension is for one-hot representation. The additional dimension will\n be inserted at the position specified by 'axis'. If 'axis' is not specified then then additional\n dimension will be inserted as the innermost dimension, i.e. axis=-1. The size of the additional\n dimension is specified by required scalar input 'depth'. The type of the output tensor is the same\n as the type of the 'values' input. Any entries in the 'indices' input tensor with values outside\n the range [0, depth) will result in one-hot representation with all 'off_value' values in the\n output tensor.\n","domain":"ai.onnx","examples":[{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_axis')","summary":"with_axis"},{"code":"axisValue = -2\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_negative_axis')","summary":"with_negative_axis"},{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([0, -7, -8], dtype=np.int64)\n\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_negative_indices')","summary":"with_negative_indices"},{"code":"on_value = 5\noff_value = 2\noutput_type = np.int32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y']\n)\nindices = np.array([0, 7, 8], dtype=np.int64)\ndepth = np.float32(12)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_without_axis')","summary":"without_axis"}],"inputs":[{"description":"Input tensor containing indices. The values must be non-negative integers. Any entries in the 'indices' input tensor with values outside the range [0, depth) will result in one-hot representation with all 'off_value' values in the output tensor.In case 'indices' is of non-integer type, the values will be casted to int64 before use.","name":"indices","type":"T1"},{"description":"Scalar specifying the number of classes in one-hot tensor. This is also the size of the one-hot dimension (specified by 'axis' attribute) added on in the output tensor. The values in the 'indices' input tensor are expected to be in the range [0, depth). In case 'depth' is of non-integer type, it will be casted to int64 before use.","name":"depth","type":"T2"},{"description":"Rank 1 tensor containing exactly two elements, in the format [off_value, on_value], where 'on_value' is the value used for filling locations specified in 'indices' input tensor, and 'off_value' is the value used for filling locations other than those specified in 'indices' input tensor. ","name":"values","type":"T3"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank one greater than input tensor 'indices', i.e. rank(output) = rank(indices) + 1. The data type for the elements of the output tensor is the same as the type of input 'values' is used.","name":"output","type":"T3"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T2"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T3"}]}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"(Optional) Axis along which one-hot representation in added. Default: axis=-1. axis=-1 means that the additional dimension will be inserted as the innermost/last dimension in the output tensor. Negative value means counting dimensions from the back. Accepted range is [-r-1, r] where r = rank(indices).","name":"axis","required":false,"type":"int64"}],"description":"Produces a one-hot tensor based on inputs.\n The locations represented by the index values in the 'indices' input tensor will have 'on_value'\n and the other locations will have 'off_value' in the output tensor, where 'on_value' and 'off_value'\n are specified as part of required input argument 'values', which is a two-element tensor of format\n [off_value, on_value]. The rank of the output tensor will be one greater than the rank of the\n input tensor. The additional dimension is for one-hot representation. The additional dimension will\n be inserted at the position specified by 'axis'. If 'axis' is not specified then then additional\n dimension will be inserted as the innermost dimension, i.e. axis=-1. The size of the additional\n dimension is specified by required scalar input 'depth'. The type of the output tensor is the same\n as the type of the 'values' input. Any entries in the 'indices' input tensor with values outside\n the range [-depth, depth-1] will result in one-hot representation with all 'off_value' values in the\n output tensor.\n\n when axis = 0:\n output[input[i, j, k], i, j, k] = 1 for all i, j, k and 0 otherwise.\n\n when axis = -1:\n output[i, j, k, input[i, j, k]] = 1 for all i, j, k and 0 otherwise.\n\n","domain":"ai.onnx","examples":[{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_axis')","summary":"with_axis"},{"code":"axisValue = -2\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([[1, 9],\n [2, 4]], dtype=np.float32)\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_with_negative_axis')","summary":"with_negative_axis"},{"code":"axisValue = 1\non_value = 3\noff_value = 1\noutput_type = np.float32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y'],\n axis=axisValue\n)\nindices = np.array([0, -7, -8], dtype=np.int64)\n\ndepth = np.array([10], dtype=np.float32)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, axis=axisValue, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_negative_indices')","summary":"with_negative_indices"},{"code":"on_value = 5\noff_value = 2\noutput_type = np.int32\nnode = onnx.helper.make_node(\n 'OneHot',\n inputs=['indices', 'depth', 'values'],\n outputs=['y']\n)\nindices = np.array([0, 7, 8], dtype=np.int64)\ndepth = np.float32(12)\nvalues = np.array([off_value, on_value], dtype=output_type)\ny = one_hot(indices, depth, dtype=output_type)\ny = y * (on_value - off_value) + off_value\nexpect(node, inputs=[indices, depth, values], outputs=[y], name='test_onehot_without_axis')","summary":"without_axis"}],"inputs":[{"description":"Input tensor containing indices. Any entries in the 'indices' input tensor with values outside the range [-depth, depth-1] will result in one-hot representation with all 'off_value' values in the output tensor.In case 'indices' is of non-integer type, the values will be casted to int64 before use.","name":"indices","type":"T1"},{"description":"Scalar specifying the number of classes in one-hot tensor. This is also the size of the one-hot dimension (specified by 'axis' attribute) added on in the output tensor. The values in the 'indices' input tensor are expected to be in the range [-depth, depth-1]. In case 'depth' is of non-integer type, it will be casted to int64 before use.","name":"depth","type":"T2"},{"description":"Rank 1 tensor containing exactly two elements, in the format [off_value, on_value], where 'on_value' is the value used for filling locations specified in 'indices' input tensor, and 'off_value' is the value used for filling locations other than those specified in 'indices' input tensor. ","name":"values","type":"T3"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank one greater than input tensor 'indices', i.e. rank(output) = rank(indices) + 1. The data type for the elements of the output tensor is the same as the type of input 'values' is used.","name":"output","type":"T3"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T2"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T3"}]}},{"name":"OneHotEncoder","schema":{"attributes":[{"description":"List of categories, ints.
    One and only one of the 'cats_*' attributes must be defined.","name":"cats_int64s","required":false,"type":"int64[]"},{"description":"List of categories, strings.
    One and only one of the 'cats_*' attributes must be defined.","name":"cats_strings","required":false,"type":"string[]"},{"default":1,"description":"If true and category is not present, will return all zeros; if false and a category if not found, the operator will fail.","name":"zeros","required":false,"type":"int64"}],"description":"Replace each input element with an array of ones and zeros, where a single\n one is placed at the index of the category that was passed in. The total category count \n will determine the size of the extra dimension of the output array Y.
    \n For example, if we pass a tensor with a single value of 4, and a category count of 8, \n the output will be a tensor with ``[0,0,0,0,1,0,0,0]``.
    \n This operator assumes every input feature is from the same set of categories.
    \n If the input is a tensor of float, int32, or double, the data will be cast\n to integers and the cats_int64s category list will be used for the lookups.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be encoded.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Encoded output data, having one more dimension than X.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int64)","tensor(int32)","tensor(float)","tensor(double)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Or","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `or` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or4d')","summary":"or"},{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v4d')","summary":"or_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Or","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `or` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or4d')","summary":"or"},{"code":"node = onnx.helper.make_node(\n 'Or',\n inputs=['x', 'y'],\n outputs=['or'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_or(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_or_bcast4v4d')","summary":"or_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"PRelu","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. If `Slope` is of size 1, the value is sharedacross different channels","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. If `Slope` is of size 1, the value is sharedacross different channels","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\nThis operator supports **unidirectional broadcasting** (tensor slope should be unidirectional broadcastable to input tensor X); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. The shape of slope can be smaller then first input X; if so, its shape must be unidirectional broadcastable to X","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"PRelu","schema":{"category":"Activation","description":"PRelu takes input data (Tensor) and slope tensor as input, and produces one\noutput data (Tensor) where the function `f(x) = slope * x for x < 0`,\n`f(x) = x for x >= 0`., is applied to the data tensor elementwise.\nThis operator supports **unidirectional broadcasting** (tensor slope should be unidirectional broadcastable to input tensor X); for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_example')","summary":"prelu"},{"code":"node = onnx.helper.make_node(\n 'PRelu',\n inputs=['x', 'slope'],\n outputs=['y'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\nslope = np.random.randn(5).astype(np.float32)\ny = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope\n\nexpect(node, inputs=[x, slope], outputs=[y],\n name='test_prelu_broadcast')","summary":"prelu_broadcast"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"},{"description":"Slope tensor. The shape of slope can be smaller then first input X; if so, its shape must be unidirectional broadcastable to X","name":"slope","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)"],"description":"Constrain input and output types to float/int tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Three modes: constant(default), reflect, edge","name":"mode","required":false,"type":"string"},{"description":"List of integers indicate the padding element count at the beginning and end of each axis, for 2D it is the number of pixel. `paddings` rank should be double of the input's rank. `paddings` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.","name":"paddings","required":true,"type":"int64[]"},{"description":"One float, indicates the value to be filled, default is 0","name":"value","required":false,"type":"float32"}],"category":"Tensor","description":"Given `data` tensor, paddings, mode, and value.\nExample:\n Insert 0 paddings to the beginning of the second dimension.\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n paddings = [0, 0, 2, 0]\n output = [\n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Three modes: constant(default), reflect, edge","name":"mode","required":false,"type":"string"},{"description":"List of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D it is the number of pixels. `pads` rank should be double of the input's rank. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.","name":"pads","required":true,"type":"int64[]"},{"description":"One float, indicates the value to be filled.","name":"value","required":false,"type":"float32"}],"category":"Tensor","description":"Given `data` tensor, pads, mode, and value.\nExample:\n Insert 0 pads to the beginning of the second dimension.\n data = [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ]\n pads = [0, 2, 0, 0]\n output = [\n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Supported modes: `constant`(default), `reflect`, `edge`","name":"mode","required":false,"type":"string"}],"category":"Tensor","description":"Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, \na padded tensor (`output`) is generated.\n\nThe three supported `modes` are (similar to corresponding modes supported by `numpy.pad`):\n\n1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0)\n\n2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis\n\n3) `edge` - pads with the edge values of array\n\n\nExample 1 (`constant` mode):\n Insert 0 pads to the beginning of the second dimension.\n\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'constant'\n\n constant_value = 0.0\n\n output = \n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ]\n\n\nExample 2 (`reflect` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'reflect'\n\n output = \n [\n [1.0, 1.2, 1.0, 1.2],\n [2.3, 3.4, 2.3, 3.4],\n [4.5, 5.7, 4.5, 5.7],\n ]\n\n\nExample 3 (`edge` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'edge'\n\n output = \n [\n [1.0, 1.0, 1.0, 1.2],\n [2.3, 2.3, 2.3, 3.4],\n [4.5, 4.5, 4.5, 5.7],\n ]\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"},{"description":"Tensor of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. `pads` should be a 1D tensor of shape [2 * input_rank]. `pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], where xi_begin is the number of pad values added at the beginning of axis `i` and xi_end, the number of pad values added at the end of axis `i`.","name":"pads","type":"tensor(int64)"},{"description":"(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0).","name":"constant_value","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input and output to only numeric types.","type_param_str":"T"}]}},{"name":"Pad","schema":{"attributes":[{"default":"constant","description":"Supported modes: `constant`(default), `reflect`, `edge`","name":"mode","required":false,"type":"string"}],"category":"Tensor","description":"Given a tensor containing the data to be padded (`data`), a tensor containing the number of start and end pad values for axis (`pads`), (optionally) a `mode`, and (optionally) `constant_value`, \na padded tensor (`output`) is generated.\n\nThe three supported `modes` are (similar to corresponding modes supported by `numpy.pad`):\n\n1) `constant`(default) - pads with a given constant value as specified by `constant_value` (which defaults to 0)\n\n2) `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis\n\n3) `edge` - pads with the edge values of array\n\n\nExample 1 (`constant` mode):\n Insert 0 pads to the beginning of the second dimension.\n\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'constant'\n\n constant_value = 0.0\n\n output = \n [\n [0.0, 0.0, 1.0, 1.2],\n [0.0, 0.0, 2.3, 3.4],\n [0.0, 0.0, 4.5, 5.7],\n ]\n\n\nExample 2 (`reflect` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'reflect'\n\n output = \n [\n [1.0, 1.2, 1.0, 1.2],\n [2.3, 3.4, 2.3, 3.4],\n [4.5, 5.7, 4.5, 5.7],\n ]\n\n\nExample 3 (`edge` mode):\n data = \n [\n [1.0, 1.2],\n [2.3, 3.4],\n [4.5, 5.7],\n ] \n\n pads = [0, 2, 0, 0]\n\n mode = 'edge'\n\n output = \n [\n [1.0, 1.0, 1.0, 1.2],\n [2.3, 2.3, 2.3, 3.4],\n [4.5, 4.5, 4.5, 5.7],\n ]\n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads', 'value'],\n outputs=['y'],\n mode='constant'\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\npads = np.array([0, 0, 1, 3, 0, 0, 2, 4]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\nvalue = np.float32(1.2)\ny = pad_impl(\n x,\n pads,\n 'constant',\n 1.2\n)\n\nexpect(node, inputs=[x, pads, value], outputs=[y],\n name='test_constant_pad')","summary":"constant_pad"},{"code":"for mode in ['edge', 'reflect']:\n node = onnx.helper.make_node(\n 'Pad',\n inputs=['x', 'pads'],\n outputs=['y'],\n mode=mode\n )\n x = np.random.randn(1, 3, 4, 5).astype(np.int32)\n pads = np.array([0, 0, 1, 1, 0, 0, 1, 1]).astype(np.int64) # pad order [x1_begin, x2_begin, ..., x1_end, x2_end, ...]\n y = pad_impl(\n x,\n pads,\n mode\n )\n\n expect(node, inputs=[x, pads], outputs=[y],\n name='test_{}_pad'.format(mode))","summary":"reflection_and_edge_pad"}],"inputs":[{"description":"Input tensor.","name":"data","type":"T"},{"description":"Tensor of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. `pads` should be a 1D tensor of shape [2 * input_rank]. `pads` format should be: [x1_begin, x2_begin,...,x1_end, x2_end,...], where xi_begin is the number of pad values added at the beginning of axis `i` and xi_end, the number of pad values added at the end of axis `i`.","name":"pads","type":"tensor(int64)"},{"description":"(Optional) A scalar value to be used if the mode chosen is `constant` (by default it is 0).","name":"constant_value","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor after padding.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrains input and output to only numeric types.","type_param_str":"T"}]}},{"name":"Pow","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"Input tensor of any shape, base of the exponent.","name":"X","type":"T"},{"description":"Input tensor of any shape broadcastable to X shape, the exponent component.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input X and output types to float/int tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input Y types to float/int tensors.","type_param_str":"T1"}]}},{"name":"Pow","schema":{"description":"Pow takes input data (Tensor) and exponent Tensor, and\nproduces one output data (Tensor) where the function `f(x) = x^exponent`,\nis applied to the data tensor elementwise.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_example')\n\nx = np.arange(60).reshape(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow')","summary":"pow"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array(2).astype(np.float32)\nz = pow(x, y) # expected output [1., 4., 9.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_scalar')\n\nnode = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\nx = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)\ny = np.array([1, 2, 3]).astype(np.float32)\n# expected output [[1, 4, 27], [4, 25, 216]]\nz = pow(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_bcast_array')","summary":"pow_broadcast"},{"code":"node = onnx.helper.make_node(\n 'Pow',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int64')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_int32')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.float32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_float32')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint64)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint64')\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([4, 5, 6]).astype(np.uint32)\nz = pow(x, y) # expected output [1., 32., 729.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_float32_uint32')\n\nx = np.array([1, 2, 3]).astype(np.int64)\ny = np.array([4, 5, 6]).astype(np.int64)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int64_int64')\n\nx = np.array([1, 2, 3]).astype(np.int32)\ny = np.array([4, 5, 6]).astype(np.int32)\nz = pow(x, y) # expected output [1, 32, 729]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_pow_types_int32_int32')","summary":"types"}],"inputs":[{"description":"First operand, base of the exponent.","name":"X","type":"T"},{"description":"Second operand, power of the exponent.","name":"Y","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor (same size as X)","name":"Z","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input X and output types to float/int tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input Y types to float/int tensors.","type_param_str":"T1"}]}},{"name":"QLinearConv","schema":{"attributes":[{"default":"NOTSET","description":"auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.","name":"auto_pad","required":false,"type":"string"},{"description":"dilation value along each spatial axis of the filter. If not present, the dilation defaults to 1 along each spatial axis.","name":"dilations","required":false,"type":"int64[]"},{"default":1,"description":"number of groups input channels and output channels are divided into. default is 1.","name":"group","required":false,"type":"int64"},{"description":"The shape of the convolution kernel. If not present, should be inferred from input 'w'.","name":"kernel_shape","required":false,"type":"int64[]"},{"description":"Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0.The value represent the number of pixels added to the beginning and end part of the corresponding axis.`pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number ofpixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaultsto 0 along start and end of each spatial axis.","name":"pads","required":false,"type":"int64[]"},{"description":"Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.","name":"strides","required":false,"type":"int64[]"}],"description":"The convolution operator consumes a quantized input tensor, its scale and zero point,\na quantized filter, its scale and zero point, and output's scale and zero point,\nand computes the quantized output. Each scale and zero-point pair must have same shape.\nIt means they must be either scalars (per tensor) or 1-D tensors (per output channel).\nEach input or output and its related zero point must have same type.\nWhen bias is present it must be quantized using scale = input scale * weight scale and \nzero point as 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QLinearConv',\n inputs=['x', 'x_scale', 'x_zero_point', 'w', 'w_scale', 'w_zero_point', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[255, 174, 162, 25, 203, 168, 58],\n [15, 59, 237, 95, 129, 0, 64],\n [56, 242, 153, 221, 168, 12, 166],\n [232, 178, 186, 195, 237, 162, 237],\n [188, 39, 124, 77, 80, 102, 43],\n [127, 230, 21, 83, 41, 40, 134],\n [255, 154, 92, 141, 42, 148, 247], ], dtype=np.uint8).reshape((1, 1, 7, 7))\n\nx_scale = np.float32(0.00369204697)\nx_zero_point = np.uint8(132)\n\nw = np.array([0], dtype=np.uint8).reshape((1, 1, 1, 1))\n\nw_scale = np.array([0.00172794575], dtype=np.float32)\nw_zero_point = np.array([255], dtype=np.uint8)\n\ny_scale = np.float32(0.00162681262)\ny_zero_point = np.uint8(123)\n\noutput = np.array([[0, 81, 93, 230, 52, 87, 197],\n [240, 196, 18, 160, 126, 255, 191],\n [199, 13, 102, 34, 87, 243, 89],\n [23, 77, 69, 60, 18, 93, 18],\n [67, 216, 131, 178, 175, 153, 212],\n [128, 25, 234, 172, 214, 215, 121],\n [0, 101, 163, 114, 213, 107, 8], ], dtype=np.uint8).reshape((1, 1, 7, 7))\n\nexpect(node, inputs=[x, x_scale, x_zero_point, w, w_scale, w_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearconv')","summary":"qlinearconv"}],"inputs":[{"description":"Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].","name":"x","type":"T1"},{"description":"Scale tensor for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_scale","type":"tensor(float)"},{"description":"Zero point tensor for input 'x'. It's a scalar, which means a per-tensor/layer quantization.","name":"x_zero_point","type":"T1"},{"description":"The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. X.shape[1] == (W.shape[1] * group) == C (assuming zero based indices for the shape array). Or in other words FILTER_IN_CHANNEL should be equal to DATA_CHANNEL. ","name":"w","type":"T2"},{"description":"Scale tensor for input 'w'. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M).","name":"w_scale","type":"tensor(float)"},{"description":"Zero point tensor for input 'w'. It could be a scalar or a 1-D tensor, which means a per-tensor/layer or per output channel quantization. If it's a 1-D tensor, its number of elements should be equal to the number of output channels (M).","name":"w_zero_point","type":"T2"},{"description":"Scale tensor for output 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point tensor for output 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_zero_point","type":"T3"},{"description":"Optional 1D bias to be added to the convolution, has size of M. Bias must be quantized using scale = x_scale * w_scale and zero_point = 0","name":"B","option":"optional","type":"T4"}],"inputs_range":"8 - 9","max_input":9,"max_output":1,"min_input":8,"min_output":1,"outputs":[{"description":"Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain filter type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain output type to 8-bit integer tensor.","type_param_str":"T3"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain bias type to 32-bit integer tensor.","type_param_str":"T4"}]}},{"name":"QLinearMatMul","schema":{"description":"Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html.\nIt consumes two quantized input tensors, their scales and zero points, scale and zero point of output, and computes the quantized output.\nThe quantization formula is y = saturate((x / y_scale) + y_zero_point). For (x / y_scale), it is rounding to nearest ties to even.\nRefer to https://en.wikipedia.org/wiki/Rounding for details. Scale and zero point must have same shape.\nThey must be either scalar (per tensor) or 1-D tensor (per row for 'a' and per column for 'b'). If scale and zero point are 1-D tensor,\nthe number of elements of scale and zero point tensor of input 'a' and output 'y' should be equal to the number of rows of input 'a',\nand the number of elements of scale and zero point tensor of input 'b' should be equal to the number of columns of input 'b'.\nProduction must never overflow, and accumulation may overflow if and only if in 32 bits.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QLinearMatMul',\n inputs=['a', 'a_scale', 'a_zero_point', 'b', 'b_scale', 'b_zero_point', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\n#2D\na = np.array([[208, 236, 0, 238],\n [3, 214, 255, 29], ], dtype=np.uint8)\n\na_scale = np.array([0.0066], dtype=np.float32)\na_zero_point = np.array([113], dtype=np.uint8)\n\nb = np.array([[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]], dtype=np.uint8)\n\nb_scale = np.array([0.00705], dtype=np.float32)\nb_zero_point = np.array([114], dtype=np.uint8)\n\ny_scale = np.array([0.0107], dtype=np.float32)\ny_zero_point = np.array([118], dtype=np.uint8)\n\noutput = np.array([[168, 115, 255],\n [1, 66, 151], ], dtype=np.uint8)\n\nexpect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearmatmul_2D')\n\n#3D\na = np.array([[[208, 236, 0, 238],\n [3, 214, 255, 29]],\n [[208, 236, 0, 238],\n [3, 214, 255, 29]]], dtype=np.uint8)\n\na_scale = np.array([0.0066], dtype=np.float32)\na_zero_point = np.array([113], dtype=np.uint8)\n\nb = np.array([[[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]],\n [[152, 51, 244],\n [60, 26, 255],\n [0, 127, 246],\n [127, 254, 247]]], dtype=np.uint8)\n\nb_scale = np.array([0.00705], dtype=np.float32)\nb_zero_point = np.array([114], dtype=np.uint8)\n\ny_scale = np.array([0.0107], dtype=np.float32)\ny_zero_point = np.array([118], dtype=np.uint8)\n\noutput = np.array([[[168, 115, 255],\n [1, 66, 151]],\n [[168, 115, 255],\n [1, 66, 151]]], dtype=np.uint8)\n\nexpect(node, inputs=[a, a_scale, a_zero_point, b, b_scale, b_zero_point, y_scale, y_zero_point], outputs=[output],\n name='test_qlinearmatmul_3D')","summary":"qlinearmatmul"}],"inputs":[{"description":"N-dimensional quantized matrix a","name":"a","type":"T1"},{"description":"scale of quantized input a","name":"a_scale","type":"tensor(float)"},{"description":"zero point of quantized input a","name":"a_zero_point","type":"T1"},{"description":"N-dimensional quantized matrix b","name":"b","type":"T2"},{"description":"scale of quantized input b","name":"b_scale","type":"tensor(float)"},{"description":"zero point of quantized input b","name":"b_zero_point","type":"T2"},{"description":"scale of quantized output y","name":"y_scale","type":"tensor(float)"},{"description":"zero point of quantized output y","name":"y_zero_point","type":"T3"}],"max_input":8,"max_output":1,"min_input":8,"min_output":1,"outputs":[{"description":"Quantized matrix multiply results from a * b","name":"y","type":"T3"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input a and its zero point data type to 8-bit integer tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain input b and its zero point data type to 8-bit integer tensor.","type_param_str":"T2"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain output y and its zero point data type to 8-bit integer tensor.","type_param_str":"T3"}]}},{"name":"QuantizeLinear","schema":{"description":"The linear per-tensor/layer quantization operator. It consumes a high precision tensor, a scale, a zero point to compute the low precision / quantized tensor.\nThe quantization formula is y = saturate ((x / y_scale) + y_zero_point). For saturation, it saturates to [0, 255] if it's uint8, or [-128, 127] if it's int8.\nFor (x / y_scale), it's rounding to nearest ties to even. Refer to https://en.wikipedia.org/wiki/Rounding for details. 'y_zero_point' and 'y' must have same type.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[[[-162, 10],\n [-100, 232],\n [-20, -50]],\n\n [[-76, 0],\n [0, 252],\n [32, -44]],\n\n [[245, -485],\n [-960, -270],\n [-375, -470]], ], ], dtype=np.float32)\ny_scale = np.array([2, 4, 5], dtype=np.float32)\ny_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x / y_scale.reshape(1, 3, 1, 1) + y_zero_point.reshape(1, 3, 1, 1)).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([0, 2, 3, 1000, -254, -1000]).astype(np.float32)\ny_scale = np.float32(2)\ny_zero_point = np.uint8(128)\ny = np.array([128, 129, 130, 255, 1, 0]).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear')","summary":"quantizelinear"}],"inputs":[{"description":"N-D full precision Input tensor to be quantized.","name":"x","type":"T1"},{"description":"Scale for doing quantization to get 'y'. It's a scalar, which means a per-tensor/layer quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point for doing quantization to get 'y'. It's a scalar, which means a per-tensor/layer quantization. Default value is uint8 typed 0 if it's not specified.","name":"y_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D quantized output tensor. It has same shape as input 'x'.","name":"y","type":"T2"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)"],"description":"Constrain 'x' to float or int32 tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit integer tensor.","type_param_str":"T2"}]}},{"name":"QuantizeLinear","schema":{"attributes":[{"default":1,"description":"(Optional) The axis of the quantization dimension of the input tensor. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input)","name":"axis","required":false,"type":"int64"}],"description":"The linear quantization operator. It consumes a high precision tensor, a scale, and a zero point to compute the low precision / quantized tensor. The scale factor can be a scalar\n(per-tensor/layer quantization), or a 1-D tensor for per-axis quantization. The quantization formula is y = saturate ((x / y_scale) + y_zero_point).\nFor saturation, it saturates to [0, 255] if it's uint8, or [-128, 127] if it's int8.\nFor (x / y_scale), it's rounding to nearest ties to even. Refer to https://en.wikipedia.org/wiki/Rounding for details. 'y_zero_point' and 'y' must have same type.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([[[[-162, 10],\n [-100, 232],\n [-20, -50]],\n\n [[-76, 0],\n [0, 252],\n [32, -44]],\n\n [[245, -485],\n [-960, -270],\n [-375, -470]], ], ], dtype=np.float32)\ny_scale = np.array([2, 4, 5], dtype=np.float32)\ny_zero_point = np.array([84, 24, 196], dtype=np.uint8)\ny = (x / y_scale.reshape(1, 3, 1, 1) + y_zero_point.reshape(1, 3, 1, 1)).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear_axis')","summary":"axis"},{"code":"node = onnx.helper.make_node('QuantizeLinear',\n inputs=['x', 'y_scale', 'y_zero_point'],\n outputs=['y'],)\n\nx = np.array([0, 2, 3, 1000, -254, -1000]).astype(np.float32)\ny_scale = np.float32(2)\ny_zero_point = np.uint8(128)\ny = np.array([128, 129, 130, 255, 1, 0]).astype(np.uint8)\n\nexpect(node, inputs=[x, y_scale, y_zero_point], outputs=[y],\n name='test_quantizelinear')","summary":"quantizelinear"}],"inputs":[{"description":"N-D full precision Input tensor to be quantized.","name":"x","type":"T1"},{"description":"Scale for doing quantization to get 'y'. It can be a scalar, which means per-tensor/layer quantization, or a 1-D Tensor for per-axis quantization.","name":"y_scale","type":"tensor(float)"},{"description":"Zero point for doing quantization to get 'y'. It can be a scalar, which means a per-tensor/layer quantization, or a 1-D tensor for per-axis quantization. Default value is uint8 typed 0 if it's not specified.","name":"y_zero_point","option":"optional","type":"T2"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D quantized output tensor. It has same shape as input 'x'.","name":"y","type":"T2"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(int32)"],"description":"Constrain 'x' to float or int32 tensor.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int8)","tensor(uint8)"],"description":"Constrain 'y_zero_point' and 'y' to 8-bit integer tensor.","type_param_str":"T2"}]}},{"name":"RNN","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"One (or two if bidirectional) activation function for input gate. The activation function must be one of the activation functions specified above. Optional: Default `Tanh` if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"},{"description":"The sequence output for the hidden is optional if 0. Default 0.","name":"output_sequence","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer simple RNN. This operator is usually supported\nvia some custom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`t` - time step (t-1 means previous time step)\n\n`Wi` - W parameter weight matrix for input gate\n\n`Ri` - R recurrence weight matrix for input gate\n\n`Wbi` - W parameter bias vector for input gate\n\n`Rbi` - R parameter bias vector for input gate\n\n`WBi` - W parameter weight matrix for backward input gate\n\n`RBi` - R recurrence weight matrix for backward input gate\n\n`WBbi` - WR bias vectors for backward input gate\n\n`RBbi` - RR bias vectors for backward input gate\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Tanh):\n\n - Ht = f(Xt*(Wi^T) + Ht-1*Ri + Wbi + Rbi)\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 4\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\nrnn = RNN_Helper(X=input, W=W, R=R)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\ncustom_bias = 0.1\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, hidden_size)).astype(np.float32)\nR_B = np.zeros((1, hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)],\n name='test_simple_rnn_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, hidden_size).astype(np.float32)\nR_B = np.random.randn(1, hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_rnn_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for input gate. Concatenation of `Wi` and `WBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `Ri` and `RBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` and `[WBbi, RBbi]` (if bidirectional). The tensor has shape `[num_directions, 2*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. It is optional if `output_sequence` is 0.","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"RNN","schema":{"attributes":[{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.","name":"activation_alpha","required":false,"type":"float32[]"},{"description":"Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.","name":"activation_beta","required":false,"type":"float32[]"},{"description":"One (or two if bidirectional) activation function for input gate. The activation function must be one of the activation functions specified above. Optional: Default `Tanh` if not specified.","name":"activations","required":false,"type":"string[]"},{"description":"Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.","name":"clip","required":false,"type":"float32"},{"default":"forward","description":"Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.","name":"direction","required":false,"type":"string"},{"description":"Number of neurons in the hidden layer","name":"hidden_size","required":false,"type":"int64"}],"category":"Layer","description":"Computes an one-layer simple RNN. This operator is usually supported\nvia some custom implementation such as CuDNN.\n\nNotations:\n\n`X` - input tensor\n\n`i` - input gate\n\n`t` - time step (t-1 means previous time step)\n\n`Wi` - W parameter weight matrix for input gate\n\n`Ri` - R recurrence weight matrix for input gate\n\n`Wbi` - W parameter bias vector for input gate\n\n`Rbi` - R parameter bias vector for input gate\n\n`WBi` - W parameter weight matrix for backward input gate\n\n`RBi` - R recurrence weight matrix for backward input gate\n\n`WBbi` - WR bias vectors for backward input gate\n\n`RBbi` - RR bias vectors for backward input gate\n\n`H` - Hidden state\n\n`num_directions` - 2 if direction == bidirectional else 1\n\nActivation functions:\n\n Relu(x) - max(0, x)\n\n Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})\n\n Sigmoid(x) - 1/(1 + e^{-x})\n\n (NOTE: Below are optional)\n\n Affine(x) - alpha*x + beta\n\n LeakyRelu(x) - x if x >= 0 else alpha * x\n\n ThresholdedRelu(x) - x if x >= alpha else 0\n\n ScaledTanh(x) - alpha*Tanh(beta*x)\n\n HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)\n\n Elu(x) - x if x >= 0 else alpha*(e^x - 1)\n\n Softsign(x) - x/(1 + |x|)\n\n Softplus(x) - log(1 + e^x)\n\nEquations (Default: f=Tanh):\n\n - Ht = f(Xt*(Wi^T) + Ht-1*(Ri^T) + Wbi + Rbi)\nThis operator has **optional** inputs/outputs. See [the doc](https://github.com/onnx/onnx/blob/master/docs/IR.md) for more details about the representation of optional arguments. An empty string may be used in the place of an actual argument's name to indicate a missing argument. Trailing optional arguments (those not followed by an argument that is present) may also be simply omitted.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[[1., 2.], [3., 4.], [5., 6.]]]).astype(np.float32)\n\ninput_size = 2\nhidden_size = 4\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\nrnn = RNN_Helper(X=input, W=W, R=R)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R], outputs=[Y_h.astype(np.float32)], name='test_simple_rnn_defaults')","summary":"defaults"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\ncustom_bias = 0.1\nweight_scale = 0.1\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = weight_scale * np.ones((1, hidden_size, input_size)).astype(np.float32)\nR = weight_scale * np.ones((1, hidden_size, hidden_size)).astype(np.float32)\n\n# Adding custom bias\nW_B = custom_bias * np.ones((1, hidden_size)).astype(np.float32)\nR_B = np.zeros((1, hidden_size)).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)],\n name='test_simple_rnn_with_initial_bias')","summary":"initial_bias"},{"code":"input = np.array([[[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]],\n [[10., 11., 12.], [13., 14., 15.], [16., 17., 18.]]]).astype(np.float32)\n\ninput_size = 3\nhidden_size = 5\n\nnode = onnx.helper.make_node(\n 'RNN',\n inputs=['X', 'W', 'R', 'B'],\n outputs=['', 'Y'],\n hidden_size=hidden_size\n)\n\nW = np.random.randn(1, hidden_size, input_size).astype(np.float32)\nR = np.random.randn(1, hidden_size, hidden_size).astype(np.float32)\n\n# Adding custom bias\nW_B = np.random.randn(1, hidden_size).astype(np.float32)\nR_B = np.random.randn(1, hidden_size).astype(np.float32)\nB = np.concatenate((W_B, R_B), axis=1)\n\nrnn = RNN_Helper(X=input, W=W, R=R, B=B)\n_, Y_h = rnn.step()\nexpect(node, inputs=[input, W, R, B], outputs=[Y_h.astype(np.float32)], name='test_rnn_seq_length')","summary":"seq_length"}],"inputs":[{"description":"The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.","name":"X","type":"T"},{"description":"The weight tensor for input gate. Concatenation of `Wi` and `WBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, input_size]`.","name":"W","type":"T"},{"description":"The recurrence weight tensor. Concatenation of `Ri` and `RBi` (if bidirectional). The tensor has shape `[num_directions, hidden_size, hidden_size]`.","name":"R","type":"T"},{"description":"The bias tensor for input gate. Concatenation of `[Wbi, Rbi]` and `[WBbi, RBbi]` (if bidirectional). The tensor has shape `[num_directions, 2*hidden_size]`. Optional: If not specified - assumed to be 0.","name":"B","option":"optional","type":"T"},{"description":"Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.","name":"sequence_lens","option":"optional","type":"T1"},{"description":"Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.","name":"initial_h","option":"optional","type":"T"}],"inputs_range":"3 - 6","max_input":6,"max_output":2,"min_input":3,"min_output":0,"outputs":[{"description":"A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`. ","name":"Y","option":"optional","type":"T"},{"description":"The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.","name":"Y_h","option":"optional","type":"T"}],"outputs_range":"0 - 2","since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)"],"description":"Constrain seq_lens to integer tensor.","type_param_str":"T1"}]}},{"name":"RandomNormal","schema":{"attributes":[{"default":1,"description":"The data type for the elements of the output tensor. Default is TensorProto::FLOAT.","name":"dtype","required":false,"type":"int64"},{"description":"The mean of the normal distribution.","name":"mean","required":false,"type":"float32"},{"default":1,"description":"The standard deviation of the normal distribution.","name":"scale","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"},{"description":"The shape of the output tensor.","name":"shape","required":true,"type":"int64[]"}],"description":"Generate a tensor with random values drawn from a normal distribution. The shape\nof the tensor is specified by the `shape` argument and the parameter of the normal distribution\nspecified by `mean` and `scale`.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from normal distribution","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"RandomNormalLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use the data type of the input tensor.","name":"dtype","required":false,"type":"int64"},{"description":"The mean of the normal distribution.","name":"mean","required":false,"type":"float32"},{"default":1,"description":"The standard deviation of the normal distribution.","name":"scale","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor with random values drawn from a normal distribution.\nThe shape of the output tensor is copied from the shape of the input tensor,\nand the parameters of the normal distribution are specified by `mean` and `scale`.\n\nThe data type is specified by the 'dtype' argument, or copied from the input tensor if not provided.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message, and be valid as an output type.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor to copy shape and optionally type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from normal distribution","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T2"}]}},{"name":"RandomUniform","schema":{"attributes":[{"default":1,"description":"The data type for the elements of the output tensor. If not specified, default is TensorProto::FLOAT.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Upper boundary of the output values.","name":"high","required":false,"type":"float32"},{"description":"Lower boundary of the output values.","name":"low","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"},{"description":"The shape of the output tensor.","name":"shape","required":true,"type":"int64[]"}],"description":"Generate a tensor with random values drawn from a uniform distribution. The shape\nof the tensor is specified by the `shape` argument and the range by `low` and `high`.\n\nThe data type is specified by the 'dtype' argument. The 'dtype' argument must\nbe one of the data types specified in the 'DataType' enum field in the\nTensorProto message.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from uniform distribution","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T"}]}},{"name":"RandomUniformLike","schema":{"attributes":[{"description":"(Optional) The data type for the elements of the output tensor, if not specified, we will use the data type of the input tensor.","name":"dtype","required":false,"type":"int64"},{"default":1,"description":"Upper boundary of the output values.","name":"high","required":false,"type":"float32"},{"description":"Lower boundary of the output values.","name":"low","required":false,"type":"float32"},{"description":"(Optional) Seed to the random generator, if not specified we will auto generate one.","name":"seed","required":false,"type":"float32"}],"description":"Generate a tensor with random values drawn from a uniform distribution.\nThe shape of the output tensor is copied from the shape of the input tensor,\nand the parameters of the uniform distribution are specified by `low` and `high`.\n\nThe data type is specified by the 'dtype' argument, or copied from the input tensor if not provided.\nThe 'dtype' argument must be one of the data types specified in the 'DataType' enum field in the\nTensorProto message and be valid as an output type.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor to copy shape and optionally type information from.","name":"input","type":"T1"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of random values drawn from uniform distribution","name":"output","type":"T2"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to float tensors.","type_param_str":"T2"}]}},{"name":"Range","schema":{"description":"Generate a tensor containing a sequence of numbers that begin at `start` and extends by increments of `delta`\nup to `limit` (exclusive).\n\nThe number of elements in the output of range is computed as below-\n\n`number_of_elements = max( ceil( (limit - start) / delta ) , 0 )`\n\nThe pseudocode determining the contents of the output is shown below-\n\n`for(int i=0; i) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reciprocal","schema":{"description":"Reciprocal takes one input data (Tensor) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reciprocal","schema":{"description":"Reciprocal takes one input data (Tensor) and produces one output data\n(Tensor) where the reciprocal is, y = 1/x, is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Reciprocal',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-4, 2]).astype(np.float32)\ny = np.reciprocal(x) # expected output [-0.25, 0.5],\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal_example')\n\nx = np.random.rand(3, 4, 5).astype(np.float32) + 0.5\ny = np.reciprocal(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_reciprocal')","summary":"reciprocal"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL1","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L1 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 7.], [11., 15.], [19., 23.]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL1',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3.], [7.]], [[11.], [15.]], [[19.], [23.]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(a=np.abs(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l1_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceL2","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the L2 norm of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n#print(reduced)\n#[[[25.49509757]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=axes, keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[2.23606798, 5.],\n# [7.81024968, 10.63014581],\n# [13.45362405, 16.2788206]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n#print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n#print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_l2_keep_dims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceL2',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)\n# print(data)\n#[[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]\n\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[[2.23606798], [5.]]\n# [[7.81024968], [10.63014581]]\n# [[13.45362405], [16.2788206 ]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sqrt(np.sum(\n a=np.square(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_l2_negative_axes_keep_dims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, keepdims=True))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_default')","summary":"keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[-2]\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(-2), keepdims=True))\n# print(reduced)\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_negative_axes')","summary":"negative_axes_keepdims"},{"code":"node = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[2, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_desc_axes')\n\nnode = onnx.helper.make_node(\n 'ReduceLogSum',\n inputs=['data'],\n outputs=[\"reduced\"],\n axes=[0, 1],\n keepdims=0\n)\ndata = np.random.ranf([3, 4, 5]).astype(np.float32)\nreduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_asc_axes')","summary":"nokeepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceLogSumExp","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the log sum exponent of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[60.00671387]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=axes,\n keepdims=keepdims == 1))\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n# print(reduced)\n#[[20., 2.31326175]\n# [40.00004578, 2.31326175]\n# [60.00671387, 2.31326175]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(\n np.exp(data), axis=tuple(axes), keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceLogSumExp',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims\n)\n\ndata = np.array(\n [[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]],\n dtype=np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n# print(reduced)\n# [[[20., 2.31326175]]\n# [[40.00004578, 2.31326175]]\n# [[60.00671387, 2.31326175]]]\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.double)\nreduced = np.log(np.sum(np.exp(data),\n axis=tuple(axes),\n keepdims=keepdims == 1))\n\nexpect(node, inputs=[data], outputs=[reduced],\n name='test_reduce_log_sum_exp_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMax","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the max of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n[[[60.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdim_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[20., 2.]\n# [40., 2.]\n# [60., 2.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMax',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[20., 2.]]\n# [[40., 2.]]\n# [[60., 2.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.maximum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_max_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMean","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the mean of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[18.25]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[12.5, 1.5]\n# [35., 1.5]\n# [57.5, 1.5]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMean',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n# [[[12.5, 1.5]]\n# [[35., 1.5]]\n# [[57.5, 1.5]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceMin","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the min of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceMin',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[5., 1.]\n# [30., 1.]\n# [55., 1.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceMin', inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[5., 1.]]\n# [[30., 1.]]\n# [[55., 1.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.minimum.reduce(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_min_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)","tensor(uint8)","tensor(int8)"],"description":"Constrain input and output types to high-precision and 8 bit numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceProd","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the product of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[4.790016e+08]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=axes, keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[3., 8.]\n# [35., 48.]\n# [99., 120.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceProd',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[3., 8.]]\n# [[35., 48.]]\n# [[99., 120.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.prod(data, axis=tuple(axes), keepdims=keepdims == 1)\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_prod_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSum","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[78.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[4., 6.]\n# [12., 14.]\n# [20., 22.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSum',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[4., 6.]]\n# [[12., 14.]]\n# [[20., 22.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(data, axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"ReduceSumSquare","schema":{"attributes":[{"description":"A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"},{"default":1,"description":"Keep the reduced dimension or not, default 1 mean keep reduced dimension.","name":"keepdims","required":false,"type":"int64"}],"description":"Computes the sum square of the input tensor's element along the provided axes. The resulted\ntensor has the same rank as the input if keepdims equal 1. If keepdims equal 0, then\nthe resulted tensor have the reduced dimension pruned.\n\nThe above behavior is similar to numpy, with the exception that numpy default keepdims to\nFalse instead of True.","domain":"ai.onnx","examples":[{"code":"shape = [3, 2, 2]\naxes = None\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n#print(reduced)\n#[[[650.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=axes, keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_default_axes_keepdims_random')","summary":"default_axes_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 0\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[10., 20.]\n# [74., 100.]\n# [202., 244.]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_do_not_keepdims_random')","summary":"do_not_keepdims"},{"code":"shape = [3, 2, 2]\naxes = [1]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n#print(reduced)\n#[[[10., 20.]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_keepdims_random')","summary":"keepdims"},{"code":"shape = [3, 2, 2]\naxes = [-2]\nkeepdims = 1\n\nnode = onnx.helper.make_node(\n 'ReduceSumSquare',\n inputs=['data'],\n outputs=['reduced'],\n axes=axes,\n keepdims=keepdims)\n\ndata = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n# print(reduced)\n#[[[10., 20.s]]\n# [[74., 100.]]\n# [[202., 244.]]]\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_example')\n\nnp.random.seed(0)\ndata = np.random.uniform(-10, 10, shape).astype(np.float32)\nreduced = np.sum(np.square(data), axis=tuple(axes), keepdims=keepdims == 1)\n\nexpect(node, inputs=[data], outputs=[reduced], name='test_reduce_sum_square_negative_axes_keepdims_random')","summary":"negative_axes_keepdims"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reduced output tensor.","name":"reduced","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Relu","schema":{"category":"Activation","description":"Relu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = max(0, x), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Relu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_relu')","summary":"relu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"description":"New shape","name":"shape","required":false,"type":"int64[]"}],"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nIt takes a tensor as input and an argument `shape`. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nFirst input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"},{"description":"Specified shape for output.","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":5,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","description":"Reshape the input tensor similar to numpy.reshape.\nFirst input is the data tensor, second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.\nAt most one dimension of the new shape can be -1. In this case, the value is\ninferred from the size of the tensor and the remaining dimensions. A dimension\ncould also be 0, in which case the actual dimension value is unchanged (i.e. taken\nfrom the input tensor).","domain":"ai.onnx","examples":[{"code":"original_shape = [2, 3, 4]\ntest_cases = {\n 'reordered_all_dims': np.array([4, 2, 3], dtype=np.int64),\n 'reordered_last_dims': np.array([2, 4, 3], dtype=np.int64),\n 'reduced_dims': np.array([2, 12], dtype=np.int64),\n 'extended_dims': np.array([2, 3, 2, 2], dtype=np.int64),\n 'one_dim': np.array([24], dtype=np.int64),\n 'negative_dim': np.array([2, -1, 2], dtype=np.int64),\n 'negative_extended_dims': np.array([-1, 2, 3, 4], dtype=np.int64),\n 'zero_dim': np.array([2, 0, 4, 1], dtype=np.int64),\n 'zero_and_negative_dim': np.array([2, 0, 1, -1], dtype=np.int64),\n}\ndata = np.random.random_sample(original_shape).astype(np.float32)\n\nfor test_name, shape in test_cases.items():\n node = onnx.helper.make_node(\n 'Reshape',\n inputs=['data', 'shape'],\n outputs=['reshaped'],\n )\n\n reshaped = reshape_reference_implementation(data, shape)\n\n expect(node, inputs=[data, shape], outputs=[reshaped],\n name='test_reshape_' + test_name)","summary":"reshape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"},{"description":"Specified shape for output.","name":"shape","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Reshaped data.","name":"reshaped","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Resize","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"description":"Resize the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Resize","schema":{"attributes":[{"default":"half_pixel","description":"\nThis attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
    \n\nThe coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. \nDenote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input \"roi\", scale = length_resized / length_original,
    \n\nif coordinate_transformation_mode is \"half_pixel\",
    \nx_original = (x_resized + 0.5) / scale - 0.5,
    \n\nif coordinate_transformation_mode is \"pytorch_half_pixel\",
    \nx_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
    \n\nif coordinate_transformation_mode is \"align_corners\",
    \nx_original = x_resized * (length_original - 1) / (length_resized - 1),
    \n\nif coordinate_transformation_mode is \"asymmetric\",
    \nx_original = x_resized / scale,
    \n\nif coordinate_transformation_mode is \"tf_half_pixel_for_nn\",
    \nx_original = (x_resized + 0.5) / scale,
    \n\nif coordinate_transformation_mode is \"tf_crop_and_resize\",
    \nx_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).","name":"coordinate_transformation_mode","required":false,"type":"string"},{"default":-0.75,"description":"The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75 (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. This attribute is valid only if \"mode\" is \"cubic\".","name":"cubic_coeff_a","required":false,"type":"float32"},{"description":"If set to 1, the weight of sampling locations outside the tensor will be set to 0 and the weight will be renormalized so that their sum is 1.0. The default value is 0.","name":"exclude_outside","required":false,"type":"int64"},{"description":"When coordinate_transformation_mode is \"tf_crop_and_resize\" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f.","name":"extrapolation_value","required":false,"type":"float32"},{"default":"nearest","description":"Three interpolation modes: nearest (default), linear and cubic. The \"linear\" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). The \"cubic\" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor).","name":"mode","required":false,"type":"string"},{"default":"round_prefer_floor","description":"Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \"nearest\" pixel in input tensor from x_original, so this attribute is valid only if \"mode\" is \"nearest\".","name":"nearest_mode","required":false,"type":"string"}],"description":"Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \\\"sizes\\\" is not specified.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T1"},{"description":"1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \"tf_crop_and_resize\"","name":"roi","type":"T2"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified. If 'size' is needed, the user can use an empty string as the name of 'scales' in this operator's input list.","name":"scales","type":"tensor(float)"},{"description":"The size of the output tensor. The number of elements of 'sizes' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified.","name":"sizes","option":"optional","type":"tensor(int64)"}],"inputs_range":"3 - 4","max_input":4,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T1"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain roi type to float or double.","type_param_str":"T2"}]}},{"name":"Resize","schema":{"attributes":[{"default":"half_pixel","description":"\nThis attribute describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor.
    \n\nThe coordinate of each dimension is transformed individually. Let's describe a case using axis x as an example. \nDenote x_resized as the coordinate of axis x in the resized tensor, x_original as the coordinate of axis x in the original tensor, length_original as the length of the original tensor in axis x, length_resized as the length of the resized tensor in axis x, roi_x = (start_x, end_x) of the axis x in input \"roi\", scale = length_resized / length_original,
    \n\nif coordinate_transformation_mode is \"half_pixel\",
    \nx_original = (x_resized + 0.5) / scale - 0.5,
    \n\nif coordinate_transformation_mode is \"pytorch_half_pixel\",
    \nx_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0,
    \n\nif coordinate_transformation_mode is \"align_corners\",
    \nx_original = x_resized * (length_original - 1) / (length_resized - 1),
    \n\nif coordinate_transformation_mode is \"asymmetric\",
    \nx_original = x_resized / scale,
    \n\nif coordinate_transformation_mode is \"tf_half_pixel_for_nn\",
    \nx_original = (x_resized + 0.5) / scale,
    \n\nif coordinate_transformation_mode is \"tf_crop_and_resize\",
    \nx_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1) : 0.5 * (start_x + end_x) * (length_original - 1).","name":"coordinate_transformation_mode","required":false,"type":"string"},{"default":-0.75,"description":"The coefficient 'a' used in cubic interpolation. Two common choice are -0.5 (in some cases of TensorFlow) and -0.75 (in PyTorch). Check out Equation (4) in https://ieeexplore.ieee.org/document/1163711 for the details. This attribute is valid only if \"mode\" is \"cubic\".","name":"cubic_coeff_a","required":false,"type":"float32"},{"description":"If set to 1, the weight of sampling locations outside the tensor will be set to 0 and the weight will be renormalized so that their sum is 1.0. The default value is 0.","name":"exclude_outside","required":false,"type":"int64"},{"description":"When coordinate_transformation_mode is \"tf_crop_and_resize\" and x_original is outside the range [0, length_original - 1], this value is used as the corresponding output value. Default is 0.0f.","name":"extrapolation_value","required":false,"type":"float32"},{"default":"nearest","description":"Three interpolation modes: nearest (default), linear and cubic. The \"linear\" mode includes linear interpolation for 1D tensor and N-linear interpolation for N-D tensor (for example, bilinear interpolation for 2D tensor). The \"cubic\" mode includes cubic interpolation for 1D tensor and N-cubic interpolation for N-D tensor (for example, bicubic interpolation for 2D tensor).","name":"mode","required":false,"type":"string"},{"default":"round_prefer_floor","description":"Four modes: round_prefer_floor (default, as known as round half down), round_prefer_ceil (as known as round half up), floor, ceil. Only used by nearest interpolation. It indicates how to get \"nearest\" pixel in input tensor from x_original, so this attribute is valid only if \"mode\" is \"nearest\".","name":"nearest_mode","required":false,"type":"string"}],"description":"Resize the input tensor. In general, it calculates every value in the output tensor as a weighted average of neighborhood (a.k.a. sampling locations) in the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * (roi_end - roi_start) * scale) if input \\\"sizes\\\" is not specified.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.47119141 2.78125 4.08251953]\n# [ 6.71142578 8.02148438 9.32275391]\n# [11.91650391 13.2265625 14.52783203]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic')","summary":"resize_downsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1.36812675 2.6695014 4.0133367 ]\n# [ 6.57362535 7.875 9.2188353 ]\n# [11.94896657 13.25034122 14.59417652]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_downsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.8, 0.8], dtype=np.float32)\n\n# [[[[ 1. 2.39519159 3.79038317]\n# [ 6.58076634 7.97595793 9.37114951]\n# [12.16153268 13.55672427 14.95191585]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_cubic_align_corners')","summary":"resize_downsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[2.6666665 4.3333331]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear')","summary":"resize_downsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.142857]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_linear_align_corners')","summary":"resize_downsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 0.6, 0.6], dtype=np.float32)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_downsample_scales_nearest')","summary":"resize_downsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 1.63078704 3.00462963 4.37847222]\n# [ 7.12615741 8.5 9.87384259]\n# [12.62152778 13.99537037 15.36921296]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_cubic')","summary":"resize_downsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='pytorch_half_pixel'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 1], dtype=np.int64)\n\n# [[[[ 1.6666666]\n# [ 7. ]\n# [12.333333 ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, output_size=sizes, coordinate_transformation_mode='pytorch_half_pixel').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_linear_pytorch_half_pixel')","summary":"resize_downsample_sizes_linear_pytorch_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 1, 3], dtype=np.int64)\n\n# [[[[1. 3.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest')","summary":"resize_downsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='tf_half_pixel_for_nn'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 2], dtype=np.int64)\n\n# [[[[ 6. 8.]\n# [10. 12.]\n# [14. 16.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes, coordinate_transformation_mode='tf_half_pixel_for_nn').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_downsample_sizes_nearest_tf_half_pixel_for_nn')","summary":"resize_downsample_sizes_nearest_tf_half_pixel_for_nn"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 0.6, 0.8], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 7.9 8.2 ]\n# [ 8.8 9.1 9.400001 ]\n# [10. 10.3 10.6 ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='tf_crop_and_resize',\n extrapolation_value=10.0\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\n# Note: for some rois, the result may be different with that of TF for inaccurate floating point\nroi = np.array([0, 0, 0.4, 0.6, 1, 1, 1.2, 1.7], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 3, 3], dtype=np.int64)\n\n# [[[[ 7.6000004 10. 10. ]\n# [12.400001 10. 10. ]\n# [10. 10. 10. ]]]]\noutput = interpolate_nd(data, linear_coeffs, output_size=sizes, roi=roi,\n coordinate_transformation_mode='tf_crop_and_resize', extrapolation_value=10.0).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_tf_crop_and_resize')","summary":"resize_tf_crop_and_resize_extrapolation_value"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.47265625 0.76953125 1.24609375 1.875 2.28125\n# 2.91015625 3.38671875 3.68359375]\n# [ 1.66015625 1.95703125 2.43359375 3.0625 3.46875\n# 4.09765625 4.57421875 4.87109375]\n# [ 3.56640625 3.86328125 4.33984375 4.96875 5.375\n# 6.00390625 6.48046875 6.77734375]\n# [ 6.08203125 6.37890625 6.85546875 7.484375 7.890625\n# 8.51953125 8.99609375 9.29296875]\n# [ 7.70703125 8.00390625 8.48046875 9.109375 9.515625\n# 10.14453125 10.62109375 10.91796875]\n# [10.22265625 10.51953125 10.99609375 11.625 12.03125\n# 12.66015625 13.13671875 13.43359375]\n# [12.12890625 12.42578125 12.90234375 13.53125 13.9375\n# 14.56640625 15.04296875 15.33984375]\n# [13.31640625 13.61328125 14.08984375 14.71875 15.125\n# 15.75390625 16.23046875 16.52734375]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic')","summary":"resize_upsample_scales_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n cubic_coeff_a=-0.5,\n exclude_outside=True\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 0.55882353 0.81494204 1.35698249 1.89705882 2.39705882\n# 2.93713516 3.47917561 3.73529412]\n# [ 1.58329755 1.83941606 2.38145651 2.92153285 3.42153285\n# 3.96160918 4.50364964 4.75976814]\n# [ 3.75145936 4.00757787 4.54961832 5.08969466 5.58969466\n# 6.12977099 6.67181144 6.92792995]\n# [ 5.91176471 6.16788321 6.70992366 7.25 7.75\n# 8.29007634 8.83211679 9.08823529]\n# [ 7.91176471 8.16788321 8.70992366 9.25 9.75\n# 10.29007634 10.83211679 11.08823529]\n# [10.07207005 10.32818856 10.87022901 11.41030534 11.91030534\n# 12.45038168 12.99242213 13.24854064]\n# [12.24023186 12.49635036 13.03839082 13.57846715 14.07846715\n# 14.61854349 15.16058394 15.41670245]\n# [13.26470588 13.52082439 14.06286484 14.60294118 15.10294118\n# 15.64301751 16.18505796 16.44117647]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.5), scale_factors=scales,\n exclude_outside=True).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_A_n0p5_exclude_outside')","summary":"resize_upsample_scales_cubic_A_n0p5_exclude_outside"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[ 1. 1.34110787 1.80029155 2.32944606 2.67055394\n# 3.19970845 3.65889213 4. ]\n# [ 2.36443149 2.70553936 3.16472303 3.69387755 4.03498542\n# 4.56413994 5.02332362 5.36443149]\n# [ 4.20116618 4.54227405 5.00145773 5.53061224 5.87172012\n# 6.40087464 6.86005831 7.20116618]\n# [ 6.31778426 6.65889213 7.1180758 7.64723032 7.98833819\n# 8.51749271 8.97667638 9.31778426]\n# [ 7.68221574 8.02332362 8.48250729 9.01166181 9.35276968\n# 9.8819242 10.34110787 10.68221574]\n# [ 9.79883382 10.13994169 10.59912536 11.12827988 11.46938776\n# 11.99854227 12.45772595 12.79883382]\n# [11.63556851 11.97667638 12.43586006 12.96501458 13.30612245\n# 13.83527697 14.29446064 14.63556851]\n# [13. 13.34110787 13.80029155 14.32944606 14.67055394\n# 15.19970845 15.65889213 16. ]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_align_corners')","summary":"resize_upsample_scales_cubic_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='cubic',\n coordinate_transformation_mode='asymmetric'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\nroi = np.array([], dtype=np.float32)\n\n# [[[[ 1. 1.40625 2. 2.5 3. 3.59375 4.\n# 4.09375]\n# [ 2.625 3.03125 3.625 4.125 4.625 5.21875 5.625\n# 5.71875]\n# [ 5. 5.40625 6. 6.5 7. 7.59375 8.\n# 8.09375]\n# [ 7. 7.40625 8. 8.5 9. 9.59375 10.\n# 10.09375]\n# [ 9. 9.40625 10. 10.5 11. 11.59375 12.\n# 12.09375]\n# [11.375 11.78125 12.375 12.875 13.375 13.96875 14.375\n# 14.46875]\n# [13. 13.40625 14. 14.5 15. 15.59375 16.\n# 16.09375]\n# [13.375 13.78125 14.375 14.875 15.375 15.96875 16.375\n# 16.46875]]]]\noutput = interpolate_nd(data, lambda x: cubic_coeffs(x, A=-0.75), scale_factors=scales,\n coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_cubic_asymmetric')","summary":"resize_upsample_scales_cubic_asymmetric"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.25 1.75 2. ]\n# [1.5 1.75 2.25 2.5 ]\n# [2.5 2.75 3.25 3.5 ]\n# [3. 3.25 3.75 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear')","summary":"resize_upsample_scales_linear"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='linear',\n coordinate_transformation_mode='align_corners'\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 2.0], dtype=np.float32)\n\n# [[[[1. 1.33333333 1.66666667 2. ]\n# [1.66666667 2. 2.33333333 2.66666667]\n# [2.33333333 2.66666667 3. 3.33333333]\n# [3. 3.33333333 3.66666667 4. ]]]]\noutput = interpolate_nd(\n data, linear_coeffs, scale_factors=scales, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_linear_align_corners')","summary":"resize_upsample_scales_linear_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\n# [[[[1. 1. 1. 2. 2. 2.]\n# [1. 1. 1. 2. 2. 2.]\n# [3. 3. 3. 4. 4. 4.]\n# [3. 3. 3. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, scale_factors=scales).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales], outputs=[output],\n name='test_resize_upsample_scales_nearest')","summary":"resize_upsample_scales_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='cubic',\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 9, 10], dtype=np.int64)\n\n# [[[[ 0.45507922 0.64057922 0.97157922 1.42257922 1.90732922\n# 2.22332922 2.70807922 3.15907922 3.49007922 3.67557922]\n# [ 1.39437963 1.57987963 1.91087963 2.36187963 2.84662963\n# 3.16262963 3.64737963 4.09837963 4.42937963 4.61487963]\n# [ 2.95130693 3.13680693 3.46780693 3.91880693 4.40355693\n# 4.71955693 5.20430693 5.65530693 5.98630693 6.17180693]\n# [ 5.20525069 5.39075069 5.72175069 6.17275069 6.65750069\n# 6.97350069 7.45825069 7.90925069 8.24025069 8.42575069]\n# [ 6.88975 7.07525 7.40625 7.85725 8.342\n# 8.658 9.14275 9.59375 9.92475 10.11025 ]\n# [ 8.57424931 8.75974931 9.09074931 9.54174931 10.02649931\n# 10.34249931 10.82724931 11.27824931 11.60924931 11.79474931]\n# [10.82819307 11.01369307 11.34469307 11.79569307 12.28044307\n# 12.59644307 13.08119307 13.53219307 13.86319307 14.04869307]\n# [12.38512037 12.57062037 12.90162037 13.35262037 13.83737037\n# 14.15337037 14.63812037 15.08912037 15.42012037 15.60562037]\n# [13.32442078 13.50992078 13.84092078 14.29192078 14.77667078\n# 15.09267078 15.57742078 16.02842078 16.35942078 16.54492078]]]]\noutput = interpolate_nd(\n data, cubic_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_cubic')","summary":"resize_upsample_sizes_cubic"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 7, 8], dtype=np.int64)\n\n# [[[[1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [1. 1. 1. 1. 2. 2. 2. 2.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]\n# [3. 3. 3. 3. 4. 4. 4. 4.]]]]\noutput = interpolate_nd(\n data, nearest_coeffs, output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest')","summary":"resize_upsample_sizes_nearest"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='half_pixel',\n nearest_mode='ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='ceil'), output_size=sizes).astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_ceil_half_pixel')","summary":"resize_upsample_sizes_nearest_ceil_half_pixel"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='align_corners',\n nearest_mode='floor'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 1. 1. 1. 2. 2. 3. 3. 4.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 5. 5. 5. 6. 6. 7. 7. 8.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [ 9. 9. 9. 10. 10. 11. 11. 12.]\n# [13. 13. 13. 14. 14. 15. 15. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='floor'), output_size=sizes, coordinate_transformation_mode='align_corners').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_floor_align_corners')","summary":"resize_upsample_sizes_nearest_floor_align_corners"},{"code":"node = onnx.helper.make_node(\n 'Resize',\n inputs=['X', 'roi', 'scales', 'sizes'],\n outputs=['Y'],\n mode='nearest',\n coordinate_transformation_mode='asymmetric',\n nearest_mode='round_prefer_ceil'\n)\n\ndata = np.array([[[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]]], dtype=np.float32)\n\nroi = np.array([], dtype=np.float32)\nscales = np.array([], dtype=np.float32)\nsizes = np.array([1, 1, 8, 8], dtype=np.int64)\n\n# [[[[ 1. 2. 2. 3. 3. 4. 4. 4.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 5. 6. 6. 7. 7. 8. 8. 8.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [ 9. 10. 10. 11. 11. 12. 12. 12.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]\n# [13. 14. 14. 15. 15. 16. 16. 16.]]]]\noutput = interpolate_nd(\n data, lambda x: nearest_coeffs(x, mode='round_prefer_ceil'),\n output_size=sizes, coordinate_transformation_mode='asymmetric').astype(np.float32)\n\nexpect(node, inputs=[data, roi, scales, sizes], outputs=[output],\n name='test_resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric')","summary":"resize_upsample_sizes_nearest_round_prefer_ceil_asymmetric"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T1"},{"description":"1-D tensor given as [start1, ..., startN, end1, ..., endN], where N is the rank of X. The RoIs' coordinates are normalized in the coordinate system of the input image. It only takes effect when coordinate_transformation_mode is \"tf_crop_and_resize\"","name":"roi","type":"T2"},{"description":"The scale array along each dimension. It takes value greater than 0. If it's less than 1, it's sampling down, otherwise, it's upsampling. The number of elements of 'scales' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified. If 'size' is needed, the user can use an empty string as the name of 'scales' in this operator's input list.","name":"scales","type":"tensor(float)"},{"description":"The size of the output tensor. The number of elements of 'sizes' should be the same as the rank of input 'X'. Only one of 'scales' and 'sizes' can be specified.","name":"sizes","option":"optional","type":"tensor(int64)"}],"inputs_range":"3 - 4","max_input":4,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T1"},{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain roi type to float or double.","type_param_str":"T2"}]}},{"name":"ReverseSequence","schema":{"attributes":[{"default":1,"description":"(Optional) Specify which axis is batch axis. Must be one of 1 (default), or 0.","name":"batch_axis","required":false,"type":"int64"},{"description":"(Optional) Specify which axis is time axis. Must be one of 0 (default), or 1.","name":"time_axis","required":false,"type":"int64"}],"description":"Reverse batch of sequences having different lengths specified by `sequence_lens`.\n\nFor each slice i iterating on batch axis, the operator reverses the first sequence_lens[i] elements on time axis,\nand copies elements whose index's beyond sequence_lens[i] to the output. So the output slice i contains reversed\nsequences on the first sequence_lens[i] elements, then have original values copied for the other elements.\n\nExample 1:\n input = [[0.0, 4.0, 8.0, 12.0],\n [1.0, 5.0, 9.0, 13.0],\n [2.0, 6.0, 10.0, 14.0],\n [3.0, 7.0, 11.0, 15.0]]\n sequence_lens = [4, 3, 2, 1]\n time_axis = 0\n batch_axis = 1\n\n output = [[3.0, 6.0, 9.0, 12.0],\n [2.0, 5.0, 8.0, 13.0],\n [1.0, 4.0, 10.0, 14.0],\n [0.0, 7.0, 11.0, 15.0]]\n\nExample 2:\n input = [[0.0, 1.0, 2.0, 3.0 ],\n [4.0, 5.0, 6.0, 7.0 ],\n [8.0, 9.0, 10.0, 11.0],\n [12.0, 13.0, 14.0, 15.0]]\n sequence_lens = [1, 2, 3, 4]\n time_axis = 1\n batch_axis = 0\n\n output = [[0.0, 1.0, 2.0, 3.0 ],\n [5.0, 4.0, 6.0, 7.0 ],\n [10.0, 9.0, 8.0, 11.0],\n [15.0, 14.0, 13.0, 12.0]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ReverseSequence',\n inputs=['x', 'sequence_lens'],\n outputs=['y'],\n time_axis=1,\n batch_axis=0,\n)\nx = np.array([[0.0, 1.0, 2.0, 3.0],\n [4.0, 5.0, 6.0, 7.0],\n [8.0, 9.0, 10.0, 11.0],\n [12.0, 13.0, 14.0, 15.0]], dtype=np.float32)\nsequence_lens = np.array([1, 2, 3, 4], dtype=np.int64)\n\ny = np.array([[0.0, 1.0, 2.0, 3.0],\n [5.0, 4.0, 6.0, 7.0],\n [10.0, 9.0, 8.0, 11.0],\n [15.0, 14.0, 13.0, 12.0]], dtype=np.float32)\n\nexpect(node, inputs=[x, sequence_lens], outputs=[y],\n name='test_reversesequence_batch')","summary":"reversesequence_batch"},{"code":"node = onnx.helper.make_node(\n 'ReverseSequence',\n inputs=['x', 'sequence_lens'],\n outputs=['y'],\n time_axis=0,\n batch_axis=1,\n)\nx = np.array([[0.0, 4.0, 8.0, 12.0],\n [1.0, 5.0, 9.0, 13.0],\n [2.0, 6.0, 10.0, 14.0],\n [3.0, 7.0, 11.0, 15.0]], dtype=np.float32)\nsequence_lens = np.array([4, 3, 2, 1], dtype=np.int64)\n\ny = np.array([[3.0, 6.0, 9.0, 12.0],\n [2.0, 5.0, 8.0, 13.0],\n [1.0, 4.0, 10.0, 14.0],\n [0.0, 7.0, 11.0, 15.0]], dtype=np.float32)\n\nexpect(node, inputs=[x, sequence_lens], outputs=[y],\n name='test_reversesequence_time')","summary":"reversesequence_time"}],"inputs":[{"description":"Tensor of rank r >= 2.","name":"input","type":"T"},{"description":"Tensor specifying lengths of the sequences in a batch. It has shape `[batch_size]`.","name":"sequence_lens","type":"tensor(int64)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Tensor with same shape of input.","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"}]}},{"name":"RoiAlign","schema":{"attributes":[{"default":"avg","description":"The pooling method. Two modes are supported: 'avg' and 'max'. Default is 'avg'.","name":"mode","required":false,"type":"string"},{"default":1,"description":"default 1; Pooled output Y's height.","name":"output_height","required":false,"type":"int64"},{"default":1,"description":"default 1; Pooled output Y's width.","name":"output_width","required":false,"type":"int64"},{"description":"Number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If == 0, then an adaptive number of grid points are used (computed as ceil(roi_width / output_width), and likewise for height). Default is 0.","name":"sampling_ratio","required":false,"type":"int64"},{"default":1,"description":"Multiplicative spatial scale factor to translate ROI coordinates from their input spatial scale to the scale used when pooling, i.e., spatial scale of the input feature map X relative to the input image. E.g.; default is 1.0f. ","name":"spatial_scale","required":false,"type":"float32"}],"description":"Region of Interest (RoI) align operation described in the\n[Mask R-CNN paper](https://arxiv.org/abs/1703.06870).\nRoiAlign consumes an input tensor X and region of interests (rois)\nto apply pooling across each RoI; it produces a 4-D tensor of shape\n(num_rois, C, output_height, output_width).\n\nRoiAlign is proposed to avoid the misalignment by removing\nquantizations while converting from original image into feature\nmap and from feature map into RoI feature; in each ROI bin,\nthe value of the sampled locations are computed directly\nthrough bilinear interpolation.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n \"RoiAlign\",\n inputs=[\"X\", \"rois\", \"batch_indices\"],\n outputs=[\"Y\"],\n spatial_scale=1.0,\n output_height=5,\n output_width=5,\n sampling_ratio=2,\n)\n\nX = np.array(\n [\n [\n [\n [\n 0.2764,\n 0.7150,\n 0.1958,\n 0.3416,\n 0.4638,\n 0.0259,\n 0.2963,\n 0.6518,\n 0.4856,\n 0.7250,\n ],\n [\n 0.9637,\n 0.0895,\n 0.2919,\n 0.6753,\n 0.0234,\n 0.6132,\n 0.8085,\n 0.5324,\n 0.8992,\n 0.4467,\n ],\n [\n 0.3265,\n 0.8479,\n 0.9698,\n 0.2471,\n 0.9336,\n 0.1878,\n 0.4766,\n 0.4308,\n 0.3400,\n 0.2162,\n ],\n [\n 0.0206,\n 0.1720,\n 0.2155,\n 0.4394,\n 0.0653,\n 0.3406,\n 0.7724,\n 0.3921,\n 0.2541,\n 0.5799,\n ],\n [\n 0.4062,\n 0.2194,\n 0.4473,\n 0.4687,\n 0.7109,\n 0.9327,\n 0.9815,\n 0.6320,\n 0.1728,\n 0.6119,\n ],\n [\n 0.3097,\n 0.1283,\n 0.4984,\n 0.5068,\n 0.4279,\n 0.0173,\n 0.4388,\n 0.0430,\n 0.4671,\n 0.7119,\n ],\n [\n 0.1011,\n 0.8477,\n 0.4726,\n 0.1777,\n 0.9923,\n 0.4042,\n 0.1869,\n 0.7795,\n 0.9946,\n 0.9689,\n ],\n [\n 0.1366,\n 0.3671,\n 0.7011,\n 0.6234,\n 0.9867,\n 0.5585,\n 0.6985,\n 0.5609,\n 0.8788,\n 0.9928,\n ],\n [\n 0.5697,\n 0.8511,\n 0.6711,\n 0.9406,\n 0.8751,\n 0.7496,\n 0.1650,\n 0.1049,\n 0.1559,\n 0.2514,\n ],\n [\n 0.7012,\n 0.4056,\n 0.7879,\n 0.3461,\n 0.0415,\n 0.2998,\n 0.5094,\n 0.3727,\n 0.5482,\n 0.0502,\n ],\n ]\n ]\n ],\n dtype=np.float32,\n)\nbatch_indices = np.array([0, 0, 0], dtype=np.int64)\nrois = np.array([[0, 0, 9, 9], [0, 5, 4, 9], [5, 5, 9, 9]], dtype=np.float32)\n# (num_rois, C, output_height, output_width)\nY = np.array(\n [\n [\n [\n [0.4664, 0.4466, 0.3405, 0.5688, 0.6068],\n [0.3714, 0.4296, 0.3835, 0.5562, 0.3510],\n [0.2768, 0.4883, 0.5222, 0.5528, 0.4171],\n [0.4713, 0.4844, 0.6904, 0.4920, 0.8774],\n [0.6239, 0.7125, 0.6289, 0.3355, 0.3495],\n ]\n ],\n [\n [\n [0.3022, 0.4305, 0.4696, 0.3978, 0.5423],\n [0.3656, 0.7050, 0.5165, 0.3172, 0.7015],\n [0.2912, 0.5059, 0.6476, 0.6235, 0.8299],\n [0.5916, 0.7389, 0.7048, 0.8372, 0.8893],\n [0.6227, 0.6153, 0.7097, 0.6154, 0.4585],\n ]\n ],\n [\n [\n [0.2384, 0.3379, 0.3717, 0.6100, 0.7601],\n [0.3767, 0.3785, 0.7147, 0.9243, 0.9727],\n [0.5749, 0.5826, 0.5709, 0.7619, 0.8770],\n [0.5355, 0.2566, 0.2141, 0.2796, 0.3600],\n [0.4365, 0.3504, 0.2887, 0.3661, 0.2349],\n ]\n ],\n ],\n dtype=np.float32,\n)\n\nexpect(node, inputs=[X, rois, batch_indices], outputs=[Y], name=\"test_roialign\")","summary":"roialign"}],"inputs":[{"description":"Input data tensor from the previous operator; 4-D feature map of shape (N, C, H, W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data.","name":"X","type":"T1"},{"description":"RoIs (Regions of Interest) to pool over; rois is 2-D input of shape (num_rois, 4) given as [[x1, y1, x2, y2], ...]. The RoIs' coordinates are in the coordinate system of the input image. Each coordinate set has a 1:1 correspondence with the 'batch_indices' input.","name":"rois","type":"T1"},{"description":"1-D tensor of shape (num_rois,) with each element denoting the index of the corresponding image in the batch.","name":"batch_indices","type":"T2"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"RoI pooled output, 4-D tensor of shape (num_rois, C, output_height, output_width). The r-th batch element Y[r-1] is a pooled feature map corresponding to the r-th RoI X[r-1].","name":"Y","type":"T1"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain types to float tensors.","type_param_str":"T1"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain types to int tensors.","type_param_str":"T2"}]}},{"name":"Round","schema":{"description":"Round takes one input Tensor and rounds the values, element-wise, meaning\nit finds the nearest integer for each value.\nIn case of halfs, the rule is to round them to the nearest even integer.\nThe output tensor has the same shape and type as the input.\n\nExamples:\n```\nround([0.9]) = [1.0]\nround([2.5]) = [2.0]\nround([2.3]) = [2.0]\nround([1.5]) = [2.0]\nround([-4.5]) = [-4.0]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Round',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([0.1, 0.5, 0.9, 1.2, 1.5,\n 1.8, 2.3, 2.5, 2.7, -1.1,\n -1.5, -1.9, -2.2, -2.5, -2.8]).astype(np.float32)\ny = np.array([0., 0., 1., 1., 2.,\n 2., 2., 2., 3., -1.,\n -2., -2., -2., -2., -3.]).astype(np.float32) # expected output\nexpect(node, inputs=[x], outputs=[y],\n name='test_round')","summary":"round"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SVMClassifier","schema":{"attributes":[{"description":"Class labels if using integer labels.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_ints","required":false,"type":"int64[]"},{"description":"Class labels if using string labels.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"","name":"coefficients","required":false,"type":"float32[]"},{"description":"List of 3 elements containing gamma, coef0, and degree, in that order. Zero if unused for the kernel.","name":"kernel_params","required":false,"type":"float32[]"},{"default":"LINEAR","description":"The kernel type, one of 'LINEAR,' 'POLY,' 'RBF,' 'SIGMOID'.","name":"kernel_type","required":false,"type":"string"},{"default":"NONE","description":"Indicates the transform to apply to the score.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"description":"First set of probability coefficients.","name":"prob_a","required":false,"type":"float32[]"},{"description":"Second set of probability coefficients. This array must be same size as prob_a.
    If these are provided then output Z are probability estimates, otherwise they are raw scores.","name":"prob_b","required":false,"type":"float32[]"},{"description":"","name":"rho","required":false,"type":"float32[]"},{"description":"","name":"support_vectors","required":false,"type":"float32[]"},{"description":"","name":"vectors_per_class","required":false,"type":"int64[]"}],"description":"Support Vector Machine classifier\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be classified.","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Classification outputs (one class per example).","name":"Y","type":"T2"},{"description":"Class scores (one per class per example), if prob_a and prob_b are provided they are probabilities for each class, otherwise they are raw scores.","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type, either [C] or [N,C].","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, depending on which of the the classlabels_* attributes is used. Its size will match the bactch size of the input.","type_param_str":"T2"}]}},{"name":"SVMRegressor","schema":{"attributes":[{"description":"Support vector coefficients.","name":"coefficients","required":false,"type":"float32[]"},{"description":"List of 3 elements containing gamma, coef0, and degree, in that order. Zero if unused for the kernel.","name":"kernel_params","required":false,"type":"float32[]"},{"default":"LINEAR","description":"The kernel type, one of 'LINEAR,' 'POLY,' 'RBF,' 'SIGMOID'.","name":"kernel_type","required":false,"type":"string"},{"description":"The number of support vectors.","name":"n_supports","required":false,"type":"int64"},{"description":"Flag indicating whether the regression is a one-class SVM or not.","name":"one_class","required":false,"type":"int64"},{"default":"NONE","description":"Indicates the transform to apply to the score.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT.'","name":"post_transform","required":false,"type":"string"},{"description":"","name":"rho","required":false,"type":"float32[]"},{"description":"Chosen support vectors","name":"support_vectors","required":false,"type":"float32[]"}],"description":"Support Vector Machine regression prediction and one-class SVM anomaly detection.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be regressed.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Regression outputs (one score per target per example).","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type, either [C] or [N,C].","type_param_str":"T"}]}},{"name":"Scaler","schema":{"attributes":[{"description":"First, offset by this.
    Can be length of features in an [N,F] tensor or length 1, in which case it applies to all features, regardless of dimension count.","name":"offset","required":false,"type":"float32[]"},{"description":"Second, multiply by this.
    Can be length of features in an [N,F] tensor or length 1, in which case it applies to all features, regardless of dimension count.
    Must be same length as 'offset'","name":"scale","required":false,"type":"float32[]"}],"description":"Rescale input data, for example to standardize features by removing the mean and scaling to unit variance.\n","domain":"ai.onnx.ml","inputs":[{"description":"Data to be scaled.","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Scaled output data.","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"directions","required":false,"type":"int64[]"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops). All these tensors are required to\nhave the same shape in each iteration of the loop (a restriction imposed to enable efficient\nmemory allocation). Many common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs).\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe operation supports batching, and the batch-axis is required to be 0.\nWhen multiple scan_input tensors are used, they must all have the same batch-size,\nand they must all have the same maximum-sequence-length (the dimensionality of the\nsequence axis or scan axis). The sequence axis or scan axis is required to be 1.\n\nThe operation has an optional sequence_lens input (of shape [BATCH_SIZE]) to\nallow variable length sequences of length <= the maximum-sequence-length. If this\ninput is not specified, all sequences are assumed to be of length equal to\nmaximum-sequence-length. For variable length input sequences, the scan_outputs\nwill consist of a sequence of same length as the input, padded to the\nmaximum-sequence-length.\n\nThe optional attribute directions can be used to scan a sequence in the reverse direction.\nIf this attribute is omitted, all sequences are scanned in the forward direction.\nA bidirectional scan be performed by specifying the same tensor input twice in the\nscan_inputs, once with a forward direction, and once with a backward direction.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body\n > (sequence_lengths, init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // T.shape[0] denotes the batch-size of T\n // The batch-size of scan_1, ..., scan_m are all required to be equal\n batch_size = scan_1.shape[0];\n\n // scan_i.shape[1] denotes the (max) sequence-length of scan_i\n // scan_i.shape[1] is required to be equal to scan_j.shape[1] for all i,j.\n max_sequence_length = scan_1.shape[1];\n\n for (int batch = 0; batch < batch_size; ++batch) {\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n N = (sequence_lengths specified) ? sequence_lengths[batch] : max_sequence_length;\n\n // execute loop\n for (int t = 0; t < N; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = (scan_1[batch])[t];\n ... ;\n si_m = (scan_m[batch])[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n // accumulate the outputs for this batch:\n bst_1[batch] = st_1; ..., bst_n[batch] = st_n;\n // Note scan-outputs will have size max_sequence_length, but only first N values will be meaningful.\n // The remaining values have an undefined value.\n b_scan_out_1[batch] = scan_out_1; ...; b_scan_out_k[batch] = scan_out_k;\n }\n return bst_1, ..., bst_n, b_scan_out_1, ..., b_scan_out_k;\n\n\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ... \n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](\"\", %H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n \n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Optional tensor specifying lengths of the sequences in a batch. If this input is not specified, all sequences are assumed to be of the maximum sequence length (the dimension of the sequence axis of the scan_input tensors).","name":"sequence_lens","option":"optional","type":"I"},{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"2 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":2,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"},{"description":"An optional list of M flags. The i-th element of the list specifies the axis to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will be used as the scan axis for every scan_input.","name":"scan_input_axes","required":false,"type":"int64[]"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"scan_input_directions","required":false,"type":"int64[]"},{"description":"An optional list of K flags. The i-th element of the list specifies the axis for the i-th scan_output. The scan outputs are accumulated along the specified axis. If omitted, 0 will be used as the scan axis for every scan_output.","name":"scan_output_axes","required":false,"type":"int64[]"},{"description":"An optional list of K flags, one for each scan_output. The i-th element of the list specifies whether the i-th scan_output should be constructed by appending or prepending a new value in each iteration: 0 indicates appending and 1 indicates prepending. If omitted, all scan_output tensors will be produced by appending a value in each iteration.","name":"scan_output_directions","required":false,"type":"int64[]"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops).\nMany common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs). All the output tensors (state_variables as\nwell as scan_output_element tensors) are required to have the same shape in each iteration\nof the loop (a restriction imposed to enable efficient memory allocation).\n\nNote that the iterated element passed to the body subgraph does not have a sequence\naxis. It will have a rank one less than the rank of the corresponding scan_input.\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe optional attribute scan_input_directions specifies the direction (forward or backward)\nfor each scan input. If this attribute is omitted, all sequences are scanned in the forward\ndirection. A bidirectional scan may be performed by specifying the same tensor input twice\nin the scan_inputs, once with a forward direction, and once with a backward direction.\n\nThe scan_output of the operation is produced by concatenating the scan_output_element\nvalues produced by the body in each iteration. The optional attribute scan_output_directions\nspecifies the direction in which scan_output is constructed (by appending or prepending the\nscan_output_element to scan_output in each iteration) for each scan_output. If this attribute\nis omitted, the scan_output_element is appended to the scan_output in each iteration.\n\nThe optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.\nIf omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the\nbatch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.\nNote that scanning a non-zero axis may be less efficient than scanning axis zero.\n\nThe optional attribute scan_output_axes specifies the axis along which the scan_outputs\nare accumulated for each scan_output. For example, if axis 1 is the time axis (to be\nscanned) for both inputs and outputs, specify a scan_input axis and scan_output axis\nvalue of 1.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body,\n scan_input_axes = [axis_1, ..., axis_m]\n > (init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i\n // scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.\n sequence_length = scan_1.shape[axis_1];\n\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n\n // execute loop\n for (int t = 0; t < sequence_length; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = scan_1[t];\n ... ;\n si_m = scan_m[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n\n return st_1, ..., st_n, scan_out_1, ..., scan_out_k;\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ...\n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](%H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n\n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scan","schema":{"attributes":[{"description":"The graph run each iteration. It has N+M inputs: (loop state variables..., scan_input_elts...). It has N+K outputs: (loop state variables..., scan_output_elts...). Each scan_output is created by concatenating the value of the specified scan_output_elt value at the end of each iteration of the loop. It is an error if the dimensions of these values change across loop iterations.","name":"body","required":true,"type":"graph"},{"description":"An attribute specifying the number of scan_inputs M. ","name":"num_scan_inputs","required":true,"type":"int64"},{"description":"An optional list of M flags. The i-th element of the list specifies the axis to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will be used as the scan axis for every scan_input. Negative value for an axis means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"scan_input_axes","required":false,"type":"int64[]"},{"description":"An optional list of M flags. The i-th element of the list specifies the direction to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 indicates reverse direction. If omitted, all scan_input tensors will be scanned in the forward direction.","name":"scan_input_directions","required":false,"type":"int64[]"},{"description":"An optional list of K flags. The i-th element of the list specifies the axis for the i-th scan_output. The scan outputs are accumulated along the specified axis. If omitted, 0 will be used as the scan axis for every scan_output. Negative value for an axis means counting dimensions from the back. Accepted range is [-r, r-1].","name":"scan_output_axes","required":false,"type":"int64[]"},{"description":"An optional list of K flags, one for each scan_output. The i-th element of the list specifies whether the i-th scan_output should be constructed by appending or prepending a new value in each iteration: 0 indicates appending and 1 indicates prepending. If omitted, all scan_output tensors will be produced by appending a value in each iteration.","name":"scan_output_directions","required":false,"type":"int64[]"}],"description":"Scan can be used to iterate over one or more scan_input tensors,\nconstructing zero or more scan_output tensors. It combines ideas from general recurrences,\nfunctional programming constructs such as scan, fold, map, and zip and is intended to enable\ngeneralizations of RNN-like constructs for sequence-to-sequence processing.\nOther tensors (referred to as state_variables here) can be used to carry a state\nwhen iterating from one element to another (similar to hidden-state in RNNs, also referred\nto as loop-carried dependences in the context of loops).\nMany common usages involve a single scan_input tensor (where functionality\nsimilar to scan, fold and map can be obtained). When more than one scan_input is used,\na behavior similar to zip is obtained.\n\nThe attribute body must be a graph, specifying the computation to be performed in\nevery iteration. It takes as input the current values of the state_variables and\nthe current iterated element of the scan_inputs. It must return the (updated) values\nof the state_variables and zero or more scan_output_element tensors. The values of the\nscan_output_element tensors are concatenated over all the iterations to produce the\nscan_output values of the scan construct (similar to the concatenated intermediate\nhidden-state values of RNN-like constructs). All the output tensors (state_variables as\nwell as scan_output_element tensors) are required to have the same shape in each iteration\nof the loop (a restriction imposed to enable efficient memory allocation).\n\nNote that the iterated element passed to the body subgraph does not have a sequence\naxis. It will have a rank one less than the rank of the corresponding scan_input.\n\nThe scan operation returns the final values of the state_variables as well as the\nscan_outputs.\n\nThe optional attribute scan_input_directions specifies the direction (forward or backward)\nfor each scan input. If this attribute is omitted, all sequences are scanned in the forward\ndirection. A bidirectional scan may be performed by specifying the same tensor input twice\nin the scan_inputs, once with a forward direction, and once with a backward direction.\n\nThe scan_output of the operation is produced by concatenating the scan_output_element\nvalues produced by the body in each iteration. The optional attribute scan_output_directions\nspecifies the direction in which scan_output is constructed (by appending or prepending the\nscan_output_element to scan_output in each iteration) for each scan_output. If this attribute\nis omitted, the scan_output_element is appended to the scan_output in each iteration.\n\nThe optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.\nIf omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the\nbatch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.\nNote that scanning a non-zero axis may be less efficient than scanning axis zero.\n\nThe optional attribute scan_output_axes specifies the axis along which the scan_outputs\nare accumulated for each scan_output. For example, if axis 1 is the time axis (to be\nscanned) for both inputs and outputs, specify a scan_input axis and scan_output axis\nvalue of 1.\n\nNote that because of the ONNX restriction that only the last parameter of an operator can\nbe variadic, the initial-states and scan-inputs are listed together as one input parameter.\nSimilarly, the final-states and scan-outputs are listed together as one output parameter.\nThe attribute num_scan_inputs indicates the number M of scan-inputs.\n\nThe behavior of\n\n Scan <\n num_scan_inputs = m,\n body = loop-body,\n scan_input_axes = [axis_1, ..., axis_m]\n > (init_1, ..., init_n, scan_1, ..., scan_m)\n\nis equivalent to the following pseudo-code:\n\n // scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i\n // scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.\n sequence_length = scan_1.shape[axis_1];\n\n // initialize state-variables\n st_1 = init_1; ... st_n = init_n;\n // initialize scan-output variables: [] denotes an empty tensor\n scan_out_1 = []; ...; scan_out_k = [];\n // identify number of iterations:\n\n // execute loop\n for (int t = 0; t < sequence_length; ++t) {\n // generate the scan-input elements: the notation T[t] indicates the sub-tensor\n // of rank one less than T obtained by indexing T at position t along axis k.\n si_1 = scan_1[t];\n ... ;\n si_m = scan_m[t];\n // execute loop-body\n st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)\n // accumulate the scan-output elements\n scan_out_1 = Concat(scan_out_1, so_1); ... ; scan_out_k = Concat(scan_out_k, so_k);\n }\n\n return st_1, ..., st_n, scan_out_1, ..., scan_out_k;\n\n*Sample usage: Encoding RNN using a Scan*\n\nThe following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,\nrecurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can\nbe encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes\n%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these\nvalues are computed in the outer graph, they need to be passed in as extra state_variables.\n\n graph rnn-encoding {\n %H_0 = ... \n %X = ...\n %Y_h, %Y = Scan[body = , num_scan_inputs=1](%H_0, %X)\n return %Y, %Y_h\n }\n\n graph rnn-cell-1 (\n %H_tminus1[FLOAT, tensor]\n %X_t[FLOAT, tensor]\n ) {\n %Wi = ...\n %Ri = ...\n %Wbi = ...\n %Rbi = ...\n %t1 = X_t * (Wi^T)\n %t2 = H_tminus1*(Ri^T)\n %t3 = Add(%t1, %t2)\n %t4 = Add(%t3, %Wbi)\n %t5 = Add(%t4, %Rbi)\n %Ht = Tanh(%t5)\n %Accumulate = Identity(%Ht)\n return %Ht, %Accumulate\n }\n\n","domain":"ai.onnx","examples":[{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nno_sequence_lens = '' # optional input, not supplied\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=[no_sequence_lens, 'initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for batch-size 1, sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((1, 2))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((1, 3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((1, 2))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((1, 3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 8)])","summary":"scan_8"},{"code":"# Given an input sequence [x1, ..., xN], sum up its elements using a scan\n# returning the final state (x1+x2+...+xN) as well the scan_output\n# [x1, x1+x2, ..., x1+x2+...+xN]\n#\n# create graph to represent scan body\nsum_in = onnx.helper.make_tensor_value_info('sum_in', onnx.TensorProto.FLOAT, [2])\nnext = onnx.helper.make_tensor_value_info('next', onnx.TensorProto.FLOAT, [2])\nsum_out = onnx.helper.make_tensor_value_info('sum_out', onnx.TensorProto.FLOAT, [2])\nscan_out = onnx.helper.make_tensor_value_info('scan_out', onnx.TensorProto.FLOAT, [2])\nadd_node = onnx.helper.make_node(\n 'Add',\n inputs=['sum_in', 'next'],\n outputs=['sum_out']\n)\nid_node = onnx.helper.make_node(\n 'Identity',\n inputs=['sum_out'],\n outputs=['scan_out']\n)\nscan_body = onnx.helper.make_graph(\n [add_node, id_node],\n 'scan_body',\n [sum_in, next],\n [sum_out, scan_out]\n)\n# create scan op node\nnode = onnx.helper.make_node(\n 'Scan',\n inputs=['initial', 'x'],\n outputs=['y', 'z'],\n num_scan_inputs=1,\n body=scan_body\n)\n# create inputs for sequence-length 3, inner dimension 2\ninitial = np.array([0, 0]).astype(np.float32).reshape((2,))\nx = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32).reshape((3, 2))\n# final state computed = [1 + 3 + 5, 2 + 4 + 6]\ny = np.array([9, 12]).astype(np.float32).reshape((2,))\n# scan-output computed\nz = np.array([1, 2, 4, 6, 9, 12]).astype(np.float32).reshape((3, 2))\n\nexpect(node, inputs=[initial, x], outputs=[y, z],\n name='test_scan9_sum', opset_imports=[onnx.helper.make_opsetid(\"\", 9)])","summary":"scan_9"}],"inputs":[{"description":"Initial values of the loop's N state variables followed by M scan_inputs","name":"initial_state_and_scan_inputs","option":"variadic","type":"V"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"Final values of the loop's N state variables followed by K scan_outputs","name":"final_state_and_scan_outputs","option":"variadic","type":"V"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(int64)"],"description":"Int64 tensor","type_param_str":"I"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"All Tensor types","type_param_str":"V"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1]","name":"axis","required":false,"type":"int64"}],"description":"Given `data`, `updates` and `indices` input tensors of rank r >= 1, write the values provided by `updates` \ninto the first input, `data`, along `axis` dimension of `data` (by default outer-most one as axis=0) at corresponding `indices`. \nFor each entry in `updates`, the target index in `data` is specified by corresponding entry in `indices`\nfor dimension = axis, and index in source for dimension != axis. For instance, in a 2-D tensor case,\ndata[indices[i][j]][j] = updates[i][j] if axis = 0, or data[i][indices[i][j]] = updates[i][j] if axis = 1,\nwhere i and j are loop counters from 0 up to the respective size in `updates` - 1.\nExample 1:\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\nExample 2:\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input).","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"This operator is deprecated. Please use ScatterElements, which provides the same functionality.\n\nScatter takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Scatter","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"This operator is deprecated. Please use ScatterElements, which provides the same functionality.\n\nScatter takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter(data, indices, updates, axis=axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_with_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_with_axis"},{"code":"node = onnx.helper.make_node(\n 'Scatter',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_without_axis', opset_imports=[helper.make_opsetid(\"\", 10)])","summary":"scatter_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterElements","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"ScatterElements takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_axis')","summary":"scatter_elements_with_axis"},{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, -3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 2.1, 4.0, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_negative_indices')","summary":"scatter_elements_with_negative_indices"},{"code":"node = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_without_axis')","summary":"scatter_elements_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterElements","schema":{"attributes":[{"description":"Which axis to scatter on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axis","required":false,"type":"int64"}],"description":"ScatterElements takes three inputs `data`, `updates`, and `indices` of the same\nrank r >= 1 and an optional attribute axis that identifies an axis of `data`\n(by default, the outer-most axis, that is axis 0). The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value\nto values specified by `updates` at specific index positions specified by\n`indices`. Its output shape is the same as the shape of `data`.\n\nFor each entry in `updates`, the target index in `data` is obtained by combining\nthe corresponding entry in `indices` with the index of the entry itself: the\nindex-value for dimension = axis is obtained from the value of the corresponding\nentry in `indices` and the index-value for dimension != axis is obtained from the\nindex of the entry itself.\n\nFor instance, in a 2-D tensor case, the update corresponding to the [i][j] entry\nis performed as below:\n```\n output[indices[i][j]][j] = updates[i][j] if axis = 0, \n output[i][indices[i][j]] = updates[i][j] if axis = 1,\n```\n\nThis operator is the inverse of GatherElements. It is similar to Torch's Scatter operation.\n\nExample 1:\n```\n data = [\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0],\n ]\n indices = [\n [1, 0, 2],\n [0, 2, 1],\n ]\n updates = [\n [1.0, 1.1, 1.2],\n [2.0, 2.1, 2.2],\n ]\n output = [\n [2.0, 1.1, 0.0]\n [1.0, 0.0, 2.2]\n [0.0, 2.1, 1.2]\n ]\n```\nExample 2:\n```\n data = [[1.0, 2.0, 3.0, 4.0, 5.0]]\n indices = [[1, 3]]\n updates = [[1.1, 2.1]]\n axis = 1\n output = [[1.0, 1.1, 3.0, 2.1, 5.0]]\n```\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, 3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 3.0, 2.1, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_axis')","summary":"scatter_elements_with_axis"},{"code":"axis = 1\nnode = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n axis=axis,\n)\ndata = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=np.float32)\nindices = np.array([[1, -3]], dtype=np.int64)\nupdates = np.array([[1.1, 2.1]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates, axis)\n# print(y) produces\n# [[1.0, 1.1, 2.1, 4.0, 5.0]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_with_negative_indices')","summary":"scatter_elements_with_negative_indices"},{"code":"node = onnx.helper.make_node(\n 'ScatterElements',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.zeros((3, 3), dtype=np.float32)\nindices = np.array([[1, 0, 2], [0, 2, 1]], dtype=np.int64)\nupdates = np.array([[1.0, 1.1, 1.2], [2.0, 2.1, 2.2]], dtype=np.float32)\n\ny = scatter_elements(data, indices, updates)\n# print(y) produces\n# [[2.0, 1.1, 0.0],\n# [1.0, 0.0, 2.2],\n# [0.0, 2.1, 1.2]]\n\nexpect(node, inputs=[data, indices, updates], outputs=[y],\n name='test_scatter_elements_without_axis')","summary":"scatter_elements_without_axis"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of int32/int64 indices, of r >= 1 (same rank as input). All index values are expected to be within bounds [-s, s-1] along axis of size s. It is an error if any of the index values are out of bounds.","name":"indices","type":"Tind"},{"description":"Tensor of rank r >=1 (same rank and shape as indices)","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1 (same rank as input).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input and output types can be of any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"ScatterND","schema":{"description":"ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1,\nand `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value to values\nspecified by `updates` at specific index positions specified by `indices`. Its output shape\nis the same as the shape of `data`. Note that `indices` should not have duplicate entries.\nThat is, two or more `updates` for the same index-location is not supported.\n\n`indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`.\n `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`.\nHence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an\nupdate to a single element of the tensor. When k is less than rank(data) each update entry specifies an\nupdate to a slice of the tensor.\n\n`updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the\nfirst (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape.\nThe remaining dimensions of `updates` correspond to the dimensions of the\nreplacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor,\ncorresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates`\nmust equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation\nof shapes.\n\nThe `output` is calculated via the following equation:\n\n output = np.copy(data)\n update_indices = indices.shape[:-1]\n for idx in np.ndindex(update_indices):\n output[indices[idx]] = updates[idx]\n\nThe order of iteration in the above loop is not specified.\nIn particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2].\nThis ensures that the output value does not depend on the iteration order.\n\nThis operator is the inverse of GatherND.\n\nExample 1:\n```\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n indices = [[4], [3], [1], [7]]\n updates = [9, 10, 11, 12]\n output = [1, 11, 3, 10, 9, 6, 7, 12]\n```\n\nExample 2:\n```\n data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n indices = [[0], [2]]\n updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]]\n output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ScatterND',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.array(\n [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\nindices = np.array([[0], [2]], dtype=np.int64)\nupdates = np.array(\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32)\n# Expecting output as np.array(\n# [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n# [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n# [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n# [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\noutput = scatter_nd_impl(data, indices, updates)\nexpect(node, inputs=[data, indices, updates], outputs=[output],\n name='test_scatternd')","summary":"scatternd"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1.","name":"indices","type":"tensor(int64)"},{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"ScatterND","schema":{"description":"ScatterND takes three inputs `data` tensor of rank r >= 1, `indices` tensor of rank q >= 1,\nand `updates` tensor of rank q + r - indices.shape[-1] - 1. The output of the operation\nis produced by creating a copy of the input `data`, and then updating its value to values\nspecified by `updates` at specific index positions specified by `indices`. Its output shape\nis the same as the shape of `data`. Note that `indices` should not have duplicate entries.\nThat is, two or more `updates` for the same index-location is not supported.\n\n`indices` is an integer tensor. Let k denote indices.shape[-1], the last dimension in the shape of `indices`.\n `indices` is treated as a (q-1)-dimensional tensor of k-tuples, where each k-tuple is a partial-index into `data`.\nHence, k can be a value at most the rank of `data`. When k equals rank(data), each update entry specifies an\nupdate to a single element of the tensor. When k is less than rank(data) each update entry specifies an\nupdate to a slice of the tensor.\n\n`updates` is treated as a (q-1)-dimensional tensor of replacement-slice-values. Thus, the\nfirst (q-1) dimensions of updates.shape must match the first (q-1) dimensions of indices.shape.\nThe remaining dimensions of `updates` correspond to the dimensions of the\nreplacement-slice-values. Each replacement-slice-value is a (r-k) dimensional tensor,\ncorresponding to the trailing (r-k) dimensions of `data`. Thus, the shape of `updates`\nmust equal indices.shape[0:q-1] ++ data.shape[k:r-1], where ++ denotes the concatenation\nof shapes.\n\nThe `output` is calculated via the following equation:\n\n output = np.copy(data)\n update_indices = indices.shape[:-1]\n for idx in np.ndindex(update_indices):\n output[indices[idx]] = updates[idx]\n\nThe order of iteration in the above loop is not specified.\nIn particular, indices should not have duplicate entries: that is, if idx1 != idx2, then indices[idx1] != indices[idx2].\nThis ensures that the output value does not depend on the iteration order.\n\nThis operator is the inverse of GatherND.\n\nExample 1:\n```\n data = [1, 2, 3, 4, 5, 6, 7, 8]\n indices = [[4], [3], [1], [7]]\n updates = [9, 10, 11, 12]\n output = [1, 11, 3, 10, 9, 6, 7, 12]\n```\n\nExample 2:\n```\n data = [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n indices = [[0], [2]]\n updates = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]]\n output = [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]]\n```\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'ScatterND',\n inputs=['data', 'indices', 'updates'],\n outputs=['y'],\n)\ndata = np.array(\n [[[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]],\n [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\nindices = np.array([[0], [2]], dtype=np.int64)\nupdates = np.array(\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]], dtype=np.float32)\n# Expecting output as np.array(\n# [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n# [[1, 2, 3, 4], [5, 6, 7, 8], [8, 7, 6, 5], [4, 3, 2, 1]],\n# [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]],\n# [[8, 7, 6, 5], [4, 3, 2, 1], [1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.float32)\noutput = scatter_nd_impl(data, indices, updates)\nexpect(node, inputs=[data, indices, updates], outputs=[output],\n name='test_scatternd')","summary":"scatternd"}],"inputs":[{"description":"Tensor of rank r >= 1.","name":"data","type":"T"},{"description":"Tensor of rank q >= 1.","name":"indices","type":"tensor(int64)"},{"description":"Tensor of rank q + r - indices_shape[-1] - 1.","name":"updates","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of rank r >= 1.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to any tensor type.","type_param_str":"T"}]}},{"name":"Selu","schema":{"attributes":[{"default":1.673200011253357,"description":"Coefficient of SELU default to 1.6732.","name":"alpha","required":false,"type":"float32"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"},{"default":1.0506999492645264,"description":"Coefficient of SELU default to 1.0507.","name":"gamma","required":false,"type":"float32"}],"category":"Activation","description":"Selu takes one input data (Tensor) and produces one output data\n(Tensor) where the scaled exponential linear unit function,\n`y = gamma * (alpha * e^x - alpha) for x <= 0`, `y = gamma * x for x > 0`,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0,\n gamma=3.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-3.79272318, 0., 3.]\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu')","summary":"selu"},{"code":"default_alpha = 1.67326319217681884765625\ndefault_gamma = 1.05070102214813232421875\nnode = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * default_gamma + \\\n (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha * default_gamma\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_default')","summary":"selu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Selu","schema":{"attributes":[{"default":1.6732631921768188,"description":"Coefficient of SELU default to 1.67326319217681884765625 (i.e., float32 approximation of 1.6732632423543772848170429916717).","name":"alpha","required":false,"type":"float32"},{"default":1.0507010221481323,"description":"Coefficient of SELU default to 1.05070102214813232421875 (i.e., float32 approximation of 1.0507009873554804934193349852946).","name":"gamma","required":false,"type":"float32"}],"category":"Activation","description":"Selu takes one input data (Tensor) and produces one output data\n(Tensor) where the scaled exponential linear unit function,\n`y = gamma * (alpha * e^x - alpha) for x <= 0`, `y = gamma * x for x > 0`,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n alpha=2.0,\n gamma=3.0\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\n# expected output [-3.79272318, 0., 3.]\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * 3.0 + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0 * 3.0\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu')","summary":"selu"},{"code":"default_alpha = 1.67326319217681884765625\ndefault_gamma = 1.05070102214813232421875\nnode = onnx.helper.make_node(\n 'Selu',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, 0, np.inf) * default_gamma + \\\n (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha * default_gamma\nexpect(node, inputs=[x], outputs=[y],\n name='test_selu_default')","summary":"selu_default"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SequenceAt","schema":{"description":"Outputs a tensor copy from the tensor at 'position' in 'input_sequence'.\nAccepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Position of the tensor in the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","type":"I"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor at the specified position in the input sequence.","name":"tensor","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceConstruct","schema":{"description":"Construct a tensor sequence containing 'inputs' tensors.\nAll tensors in 'inputs' must have the same data type.\n","domain":"ai.onnx","inputs":[{"description":"Tensors.","name":"inputs","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Sequence enclosing the input tensors.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input types to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to any tensor type.","type_param_str":"S"}]}},{"name":"SequenceEmpty","schema":{"attributes":[{"description":"(Optional) The data type of the tensors in the output sequence. The default type is 'float'.","name":"dtype","required":false,"type":"int64"}],"description":"Construct an empty tensor sequence, with given data type.\n","domain":"ai.onnx","max_input":0,"max_output":1,"min_input":0,"min_output":1,"outputs":[{"description":"Empty sequence.","name":"output","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to any tensor type.","type_param_str":"S"}]}},{"name":"SequenceErase","schema":{"description":"Outputs a tensor sequence that removes the tensor at 'position' from 'input_sequence'.\nAccepted range for 'position' is in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n'position' is optional, by default it erases the last tensor from 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Position of the tensor in the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n - 1]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","option":"optional","type":"I"}],"inputs_range":"1 - 2","max_input":2,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output sequence that has the tensor at the specified position removed.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceInsert","schema":{"description":"Outputs a tensor sequence that inserts 'tensor' into 'input_sequence' at 'position'.\n'tensor' must have the same data type as 'input_sequence'.\nAccepted range for 'position' is in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'.\nNegative value means counting positions from the back.\n'position' is optional, by default it inserts 'tensor' to the back of 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"},{"description":"Input tensor to be inserted into the input sequence.","name":"tensor","type":"T"},{"description":"Position in the sequence where the new tensor is inserted. It is optional and default is to insert to the back of the sequence. Negative value means counting positions from the back. Accepted range in `[-n, n]`, where `n` is the number of tensors in 'input_sequence'. It is an error if any of the index values are out of bounds. It must be a scalar(tensor of empty shape).","name":"position","option":"optional","type":"I"}],"inputs_range":"2 - 3","max_input":3,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output sequence that contains the inserted tensor at given position.","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain to any tensor type.","type_param_str":"T"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain position to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"SequenceLength","schema":{"description":"Produces a scalar(tensor of empty shape) containing the number of tensors in 'input_sequence'.\n","domain":"ai.onnx","inputs":[{"description":"Input sequence.","name":"input_sequence","type":"S"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Length of input sequence. It must be a scalar(tensor of empty shape).","name":"length","type":"I"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain to any tensor type.","type_param_str":"S"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to integral tensor. It must be a scalar(tensor of empty shape).","type_param_str":"I"}]}},{"name":"Shape","schema":{"description":"Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shape',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array([\n 2, 3,\n]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.shape).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape')","summary":"shape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Shape of the input tensor","name":"shape","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor.","type_param_str":"T1"}]}},{"name":"Shape","schema":{"description":"Takes a tensor as input and outputs an 1D int64 tensor containing the shape of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shape',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array([\n 2, 3,\n]).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.shape).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_shape')","summary":"shape"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Shape of the input tensor","name":"shape","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor.","type_param_str":"T1"}]}},{"name":"Shrink","schema":{"attributes":[{"description":"The bias value added to output. Default is 0.","name":"bias","required":false,"type":"float32"},{"default":0.5,"description":"The lambd value for the Shrink formulation. Default is 0.5.","name":"lambd","required":false,"type":"float32"}],"description":"Shrink takes one input data (Tensor) and produces one Tensor output,\nhaving same datatype and shape with input. It has two attributes, lambd and\nbias. The formula of this operator is: If x < -lambd, y = x + bias;\nIf x > lambd, y = x - bias; Otherwise, y = 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Shrink',\n inputs=['x'],\n outputs=['y'],\n lambd=1.5,\n)\nX = np.arange(-2.0, 2.1, dtype=np.float32)\nY = np.array([-2, 0, 0, 0, 2], dtype=np.float32)\nexpect(node, inputs=[X], outputs=[Y],\n name='test_shrink_hard')","summary":"hard_shrink"},{"code":"node = onnx.helper.make_node(\n 'Shrink',\n inputs=['x'],\n outputs=['y'],\n lambd=1.5,\n bias=1.5,\n)\nX = np.arange(-2.0, 2.1, dtype=np.float32)\nY = np.array([-0.5, 0, 0, 0, 0.5], dtype=np.float32)\nexpect(node, inputs=[X], outputs=[Y],\n name='test_shrink_soft')","summary":"soft_shrink"}],"inputs":[{"description":"The input data as Tensor.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrains input to only numeric types.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sigmoid","schema":{"category":"Activation","description":"Sigmoid takes one input data (Tensor) and produces one output data\n(Tensor) where the sigmoid function, y = 1 / (1 + exp(-x)), is applied to the\ntensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sigmoid',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x))) # expected output [0.26894143, 0.5, 0.7310586]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = 1.0 / (1.0 + np.exp(np.negative(x)))\nexpect(node, inputs=[x], outputs=[y],\n name='test_sigmoid')","summary":"sigmoid"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sign","schema":{"description":"Calculate the sign of the given input tensor element-wise.\nIf input > 0, output 1. if input < 0, output -1. if input == 0, output 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array(range(-5, 6)).astype(np.float32)\ny = np.sign(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sign')","summary":"sign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sign of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Sign","schema":{"description":"Calculate the sign of the given input tensor element-wise.\nIf input > 0, output 1. if input < 0, output -1. if input == 0, output 0.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array(range(-5, 6)).astype(np.float32)\ny = np.sign(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sign')","summary":"sign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sign of the input tensor computed element-wise. It has the same shape and type of the input.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to all numeric tensors.","type_param_str":"T"}]}},{"name":"Sin","schema":{"description":"Calculates the sine of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sin',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.sin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sin_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.sin(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sin')","summary":"sin"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The sine of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sinh","schema":{"description":"Calculates the hyperbolic sine of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sinh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.sinh(x) # expected output [-1.17520118, 0., 1.17520118]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sinh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.sinh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sinh')","summary":"sinh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic sine values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Size","schema":{"description":"Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Size',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array(6).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.size).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size')","summary":"size"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Total number of elements of the input tensor","name":"size","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor, which should be a scalar though.","type_param_str":"T1"}]}},{"name":"Size","schema":{"description":"Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Size',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([\n [1, 2, 3],\n [4, 5, 6],\n]).astype(np.float32)\ny = np.array(6).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.array(x.size).astype(np.int64)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_size')","summary":"size"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Total number of elements of the input tensor","name":"size","type":"T1"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input tensor can be of arbitrary type.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain output to int64 tensor, which should be a scalar though.","type_param_str":"T1"}]}},{"name":"Slice","schema":{"attributes":[{"description":"Axes that `starts` and `ends` apply to. It's optional. If not present, will be treated as [0, 1, ..., len(`starts`) - 1].","name":"axes","required":false,"type":"int64[]"},{"description":"Ending indices (exclusive) of corresponding axis in axes`","name":"ends","required":true,"type":"int64[]"},{"description":"Starting indices of corresponding axis in `axes`","name":"starts","required":true,"type":"int64[]"}],"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `axes`, `starts` and `ends` attributes to specify the start and end\ndimension for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represent number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX`.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n result = [\n [5, 6, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represent number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX`.\nIf a negative value is passed for step, it represents slicing backward.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to.","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Default to 1. ","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represents number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX` \nwhen sclicing forward and 'INT_MIN' when slicing backward.\nIf a negative value is passed for step, it represents slicing backward. \nHowever step value cannot be 0.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Negative value means slicing backward. 'steps' cannot be 0. Defaults to 1.","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Slice","schema":{"category":"Tensor","description":"Produces a slice of the input tensor along multiple axes. Similar to numpy:\nhttps://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\nSlices uses `starts`, `ends`, `axes` and `steps` inputs to specify the start and end\ndimension and step for each axis in the list of axes, it uses this information to\nslice the input `data` tensor. If a negative value is passed for any of the\nstart or end indices, it represents number of elements before the end of that\ndimension. If the value passed to start or end is larger than the `n` (the\nnumber of elements in this dimension), it represents `n`. For slicing to the\nend of a dimension with unknown size, it is recommended to pass in `INT_MAX` \nwhen sclicing forward and 'INT_MIN' when slicing backward.\nIf a negative value is passed for step, it represents slicing backward. \nHowever step value cannot be 0.\nIf `axes` are omitted, they are set to `[0, ..., ndim-1]`.\nIf `steps` are omitted, they are set to `[1, ..., 1]` of length `len(starts)`\nExample 1:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n steps = [1, 2]\n result = [\n [5, 7],\n ]\nExample 2:\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n ]\n starts = [0, 1]\n ends = [-1, 1000]\n result = [\n [2, 3, 4],\n ]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\ny = x[0:3, 0:10]\nstarts = np.array([0, 0], dtype=np.int64)\nends = np.array([3, 10], dtype=np.int64)\naxes = np.array([0, 1], dtype=np.int64)\nsteps = np.array([1, 1], dtype=np.int64)\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice')","summary":"slice"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends], outputs=[y],\n name='test_slice_default_axes')","summary":"slice_default_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_default_steps')","summary":"slice_default_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_end_out_of_bounds')","summary":"slice_end_out_of_bounds"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0], dtype=np.int64)\nends = np.array([-1], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 0:-1]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg')","summary":"slice_neg"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([20, 10, 4], dtype=np.int64)\nends = np.array([0, 0, 1], dtype=np.int64)\naxes = np.array([0, 1, 2], dtype=np.int64)\nsteps = np.array([-1, -3, -2])\ny = x[20:0:-1, 10:0:-3, 4:1:-2]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_neg_steps')","summary":"slice_neg_steps"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([0, 0, 3], dtype=np.int64)\nends = np.array([20, 10, 4], dtype=np.int64)\naxes = np.array([0, -2, -1], dtype=np.int64)\ny = x[:, :, 3:4]\n\nexpect(node, inputs=[x, starts, ends, axes], outputs=[y],\n name='test_slice_negative_axes')","summary":"slice_negative_axes"},{"code":"node = onnx.helper.make_node(\n 'Slice',\n inputs=['x', 'starts', 'ends', 'axes', 'steps'],\n outputs=['y'],\n)\n\nx = np.random.randn(20, 10, 5).astype(np.float32)\nstarts = np.array([1000], dtype=np.int64)\nends = np.array([1000], dtype=np.int64)\naxes = np.array([1], dtype=np.int64)\nsteps = np.array([1], dtype=np.int64)\ny = x[:, 1000:1000]\n\nexpect(node, inputs=[x, starts, ends, axes, steps], outputs=[y],\n name='test_slice_start_out_of_bounds')","summary":"slice_start_out_of_bounds"}],"inputs":[{"description":"Tensor of data to extract slices from.","name":"data","type":"T"},{"description":"1-D tensor of starting indices of corresponding axis in `axes`","name":"starts","type":"Tind"},{"description":"1-D tensor of ending indices (exclusive) of corresponding axis in `axes`","name":"ends","type":"Tind"},{"description":"1-D tensor of axes that `starts` and `ends` apply to. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","option":"optional","type":"Tind"},{"description":"1-D tensor of slice step of corresponding axis in `axes`. Negative value means slicing backward. 'steps' cannot be 0. Defaults to 1.","name":"steps","option":"optional","type":"Tind"}],"inputs_range":"3 - 5","max_input":5,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Sliced data tensor.","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain indices to integer types","type_param_str":"Tind"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input. The input is a 2-D tensor (Tensor) of size\n(batch_size x input_feature_dimensions). The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n\nInput does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softmax","schema":{"attributes":[{"default":1,"description":"Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"}],"category":"Activation","description":"The operator computes the softmax (normalized exponential) values for each layer in the batch\n of the given input.\n\nThe input does not need to explicitly be a 2D vector; rather, it will be\ncoerced into one. For an arbitrary n-dimensional tensor\ninput \\in [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] and k is\nthe axis provided, then input will be coerced into a 2-dimensional tensor with\ndimensions [a_0 * ... * a_{k-1}, a_k * ... * a_{n-1}]. For the default\ncase where axis=1, this means the input tensor will be coerced into a 2D tensor\nof dimensions [a_0, a_1 * ... * a_{n-1}], where a_0 is often the batch size.\nIn this situation, we must have a_0 = N and a_1 * ... * a_{n-1} = D.\nEach of these dimensions must be matched correctly, or else the operator\nwill throw errors. The output tensor has the same shape\nand contains the softmax values of the corresponding input.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nx = np.array([[-1, 0, 1]]).astype(np.float32)\n# expected output [[0.09003058, 0.24472848, 0.66524094]]\ny = np.exp(x) / np.sum(np.exp(x), axis=1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_example')","summary":"softmax"},{"code":"def softmax_2d(x): # type: (np.ndarray) -> np.ndarray\n max_x = np.max(x, axis=1).reshape((-1, 1))\n exp_x = np.exp(x - max_x)\n return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))\n\nx = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)\n# expected output [[0.0320586, 0.08714432, 0.23688284, 0.64391428],\n# [0.0320586, 0.08714432, 0.23688284, 0.64391428]]\ny = softmax_2d(x)\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_large_number')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=0,\n)\ny = softmax_2d(x.reshape(1, 60)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_0')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=1,\n)\ny = softmax_2d(x.reshape(3, 20)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_1')\n\n# default axis is 1\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_default_axis')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=2,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_axis_2')\n\nnode = onnx.helper.make_node(\n 'Softmax',\n inputs=['x'],\n outputs=['y'],\n axis=-1,\n)\ny = softmax_2d(x.reshape(12, 5)).reshape(3, 4, 5)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softmax_negative_axis')","summary":"softmax_axis"}],"inputs":[{"description":"The input tensor that's coerced into a 2D matrix of size (NxD) as described above.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output values with the same shape as input tensor (the original size without coercion).","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SoftmaxCrossEntropyLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean(default). 'none': no reduction will be applied, 'sum': the output will be summed. 'mean': the sum of the output will be divided by the number of elements in the output.","name":"reduction","required":false,"type":"string"}],"description":"Loss function that measures the softmax cross entropy\nbetween 'scores' and 'labels'.\nThis operator first computes a loss tensor whose shape is identical to the labels input.\nIf the input is 2-D with shape (N, C), the loss tensor may be a N-element vector L = (l_1, l_2, ..., l_N).\nIf the input is N-D tensor with shape (N, C, D1, D2, ..., Dk),\nthe loss tensor L may have (N, D1, D2, ..., Dk) as its shape and L[i,][j_1][j_2]...[j_k] denotes a scalar element in L.\nAfter L is available, this operator can optionally do a reduction operator.\n\nshape(scores): (N, C) where C is the number of classes, or (N, C, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\nshape(labels): (N) where each value is 0 <= labels[i] <= C-1, or (N, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\n\nThe loss for one sample, l_i, can caculated as follows:\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk], where i is the index of classes.\nor\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk] * weights[c], if 'weights' is provided.\n\nloss is zero for the case when label-value equals ignore_index.\n l[i][d1][d2]...[dk] = 0, when labels[n][d1][d2]...[dk] = ignore_index\n\nwhere:\n p = Softmax(scores)\n y = Log(p)\n c = labels[i][d1][d2]...[dk]\n\nFinally, L is optionally reduced:\nIf reduction = 'none', the output is L with shape (N, D1, D2, ..., Dk).\nIf reduction = 'sum', the output is scalar: Sum(L).\nIf reduction = 'mean', the output is scalar: ReduceMean(L), or if weight is provided: ReduceSum(L) / ReduceSum(W),\nwhere tensor W is of shape (N, D1, D2, ..., Dk) and W[n][d1][d2]...[dk] = weights[labels[i][d1][d2]...[dk]].\n","domain":"ai.onnx","examples":[{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1_mean_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1_mean_weight_negative_ii_log_prob"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_none_no_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii_log_prob"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_sum_weight_high_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii_log_prob"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_mean_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_none_no_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean')","summary":"softmaxcrossentropy_mean"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, y)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[sce], name='test_sce_mean_3d')","summary":"softmaxcrossentropy_mean_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, y, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[loss, log_prob], name='test_sce_mean_3d_log_prob')","summary":"softmaxcrossentropy_mean_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_log_prob')","summary":"softmaxcrossentropy_mean_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii')","summary":"softmaxcrossentropy_mean_no_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_3d')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_4d')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight')","summary":"softmaxcrossentropy_mean_weights"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii')","summary":"softmaxcrossentropy_mean_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_3d')","summary":"softmaxcrossentropy_mean_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_4d')","summary":"softmaxcrossentropy_mean_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_log_prob')","summary":"softmaxcrossentropy_mean_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_none')","summary":"softmaxcrossentropy_none"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_none_log_prob')","summary":"softmaxcrossentropy_none_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_none_weights')","summary":"softmaxcrossentropy_none_weights"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_none_weights_log_prob')","summary":"softmaxcrossentropy_none_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='sum')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_sum')","summary":"softmaxcrossentropy_sum"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='sum', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_sum_log_prob')","summary":"softmaxcrossentropy_sum_log_prob"}],"inputs":[{"description":"The predicted outputs with shape [batch_size, class_size], or [batch_size, class_size, D1, D2 , ..., Dk], where K is the number of dimensions.","name":"scores","type":"T"},{"description":"The ground truth output tensor, with shape [batch_size], or [batch_size, D1, D2, ..., Dk], where K is the number of dimensions. Labels element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the label values should either be in the range [0, C) or have the value ignore_index.","name":"labels","type":"Tind"},{"description":"A manual rescaling weight given to each class. If given, it has to be a 1D Tensor assigning weight to each of the classes. Otherwise, it is treated as if having all ones.","name":"weights","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":2,"min_input":2,"min_output":1,"outputs":[{"description":"Weighted loss float Tensor. If reduction is 'none', this has the shape of [batch_size], or [batch_size, D1, D2, ..., Dk] in case of K-dimensional loss. Otherwise, it is a scalar.","name":"output","type":"T"},{"description":"Log probability tensor. If the output of softmax is prob, its value is log(prob).","name":"log_prob","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":12,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"SoftmaxCrossEntropyLoss","schema":{"attributes":[{"description":"Specifies a target value that is ignored and does not contribute to the input gradient. It's an optional value.","name":"ignore_index","required":false,"type":"int64"},{"default":"mean","description":"Type of reduction to apply to loss: none, sum, mean(default). 'none': no reduction will be applied, 'sum': the output will be summed. 'mean': the sum of the output will be divided by the number of elements in the output.","name":"reduction","required":false,"type":"string"}],"description":"Loss function that measures the softmax cross entropy\nbetween 'scores' and 'labels'.\nThis operator first computes a loss tensor whose shape is identical to the labels input.\nIf the input is 2-D with shape (N, C), the loss tensor may be a N-element vector L = (l_1, l_2, ..., l_N).\nIf the input is N-D tensor with shape (N, C, D1, D2, ..., Dk),\nthe loss tensor L may have (N, D1, D2, ..., Dk) as its shape and L[i,][j_1][j_2]...[j_k] denotes a scalar element in L.\nAfter L is available, this operator can optionally do a reduction operator.\n\nshape(scores): (N, C) where C is the number of classes, or (N, C, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\nshape(labels): (N) where each value is 0 <= labels[i] <= C-1, or (N, D1, D2,..., Dk),\n with K >= 1 in case of K-dimensional loss.\n\nThe loss for one sample, l_i, can caculated as follows:\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk], where i is the index of classes.\nor\n l[i][d1][d2]...[dk] = -y[i][c][d1][d2]..[dk] * weights[c], if 'weights' is provided.\n\nloss is zero for the case when label-value equals ignore_index.\n l[i][d1][d2]...[dk] = 0, when labels[n][d1][d2]...[dk] = ignore_index\n\nwhere:\n p = Softmax(scores)\n y = Log(p)\n c = labels[i][d1][d2]...[dk]\n\nFinally, L is optionally reduced:\nIf reduction = 'none', the output is L with shape (N, D1, D2, ..., Dk).\nIf reduction = 'sum', the output is scalar: Sum(L).\nIf reduction = 'mean', the output is scalar: ReduceMean(L), or if weight is provided: ReduceSum(L) / ReduceSum(W),\nwhere tensor W is of shape (N, D1, D2, ..., Dk) and W[n][d1][d2]...[dk] = weights[labels[i][d1][d2]...[dk]].\n","domain":"ai.onnx","examples":[{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1_mean_weight_negative_ii')","summary":"input_shape_is_NCd1_mean_weight_negative_ii"},{"code":"reduction = 'mean'\nignore_index = np.int64(-1)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1 = 3, 5, 6\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1))\nlabels[0][0] = -1\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1_mean_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1_mean_weight_negative_ii_log_prob"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3_none_no_weight_negative_ii')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii"},{"code":"reduction = 'none'\nignore_index = np.int64(-5)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C, dim1, dim2, dim3 = 3, 5, 6, 6, 5\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3))\nlabels[0][0][0][0] = -5\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_none_no_weight_negative_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_none_no_weight_negative_ii_log_prob"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3_sum_weight_high_ii')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii"},{"code":"reduction = 'sum'\nignore_index = np.int64(10)\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\nN, C = 3, 5\nnp.random.seed(0)\nx = np.random.rand(N, C).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N))\nlabels[0] = 10\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n ignore_index=ignore_index,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3_sum_weight_high_ii_log_prob')","summary":"input_shape_is_NCd1d2d3_sum_weight_high_ii_log_prob"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nsce = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels, weight], outputs=[sce], name='test_sce_NCd1d2d3d4d5_mean_weight')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight"},{"code":"reduction = 'mean'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\nweight = np.random.rand(C).astype(np.float32)\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n weight=weight,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels, weight], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_mean_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_mean_weight_log_prob"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nsce = softmaxcrossentropy(x,\n labels,\n reduction=reduction)\n\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_NCd1d2d3d4d5_none_no_weight')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight"},{"code":"reduction = 'none'\n\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\nN, C, dim1, dim2, dim3, dim4, dim5 = 3, 5, 6, 6, 5, 3, 4\nnp.random.seed(0)\nx = np.random.rand(N, C, dim1, dim2, dim3, dim4, dim5).astype(np.float32)\nlabels = np.random.randint(0, high=C, size=(N, dim1, dim2, dim3, dim4, dim5))\n\nloss, log_prob = softmaxcrossentropy(x,\n labels,\n reduction=reduction,\n get_log_prob=True)\n\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_NCd1d2d3d4d5_none_no_weight_log_prob')","summary":"input_shape_is_NCd1d2d3d4d5_none_no_weight_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean')","summary":"softmaxcrossentropy_mean"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, y)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[sce], name='test_sce_mean_3d')","summary":"softmaxcrossentropy_mean_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\ny = np.random.randint(0, high=5, size=(3, 2))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, y, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, y], outputs=[loss, log_prob], name='test_sce_mean_3d_log_prob')","summary":"softmaxcrossentropy_mean_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_log_prob')","summary":"softmaxcrossentropy_mean_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii')","summary":"softmaxcrossentropy_mean_no_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_3d')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_mean_no_weight_ii_4d')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(2)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_mean_no_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_no_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight')","summary":"softmaxcrossentropy_mean_weights"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii')","summary":"softmaxcrossentropy_mean_weights_ii"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_3d')","summary":"softmaxcrossentropy_mean_weights_ii_3d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(1)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2))\nlabels[0][0] = np.int64(1)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_3d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_3d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_mean_weight_ii_4d')","summary":"softmaxcrossentropy_mean_weights_ii_4d"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(2)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5, 2, 7).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, 2, 7))\nlabels[0][0][0] = np.int64(2)\nweights = np.array([0.2, 0.3, 0.6, 0.1, 0.5], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction=reduction, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_4d_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_4d_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\nignore_index = np.int64(0)\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction,\n ignore_index=ignore_index)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nlabels[0] = np.int64(0)\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, ignore_index=ignore_index, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_ii_log_prob')","summary":"softmaxcrossentropy_mean_weights_ii_log_prob"},{"code":"# Define operator attributes.\nreduction = 'mean'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_mean_weight_log_prob')","summary":"softmaxcrossentropy_mean_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_none')","summary":"softmaxcrossentropy_none"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_none_log_prob')","summary":"softmaxcrossentropy_none_log_prob"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, weight=weights, reduction='none')\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[sce], name='test_sce_none_weights')","summary":"softmaxcrossentropy_none_weights"},{"code":"# Define operator attributes.\nreduction = 'none'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y', 'w'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\nweights = np.array([0.9, 0.7, 0.8, 0.9, 0.9], dtype=np.float32)\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, weight=weights, reduction='none', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels, weights], outputs=[loss, log_prob], name='test_sce_none_weights_log_prob')","summary":"softmaxcrossentropy_none_weights_log_prob"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nsce = softmaxcrossentropy(x, labels, reduction='sum')\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[sce], name='test_sce_sum')","summary":"softmaxcrossentropy_sum"},{"code":"# Define operator attributes.\nreduction = 'sum'\n\n# Create operator.\nnode = onnx.helper.make_node('SoftmaxCrossEntropyLoss',\n inputs=['x', 'y'],\n outputs=['z', 'log_prob'],\n reduction=reduction)\n\n# Define operator inputs.\nnp.random.seed(0)\nx = np.random.rand(3, 5).astype(np.float32)\nlabels = np.random.randint(0, high=5, size=(3, ))\n\n# Compute SoftmaxCrossEntropyLoss\nloss, log_prob = softmaxcrossentropy(x, labels, reduction='sum', get_log_prob=True)\n\n# Check results\nexpect(node, inputs=[x, labels], outputs=[loss, log_prob], name='test_sce_sum_log_prob')","summary":"softmaxcrossentropy_sum_log_prob"}],"inputs":[{"description":"The predicted outputs with shape [batch_size, class_size], or [batch_size, class_size, D1, D2 , ..., Dk], where K is the number of dimensions.","name":"scores","type":"T"},{"description":"The ground truth output tensor, with shape [batch_size], or [batch_size, D1, D2, ..., Dk], where K is the number of dimensions. Labels element value shall be in range of [0, C). If ignore_index is specified, it may have a value outside [0, C) and the label values should either be in the range [0, C) or have the value ignore_index.","name":"labels","type":"Tind"},{"description":"A manual rescaling weight given to each class. If given, it has to be a 1D Tensor assigning weight to each of the classes. Otherwise, it is treated as if having all ones.","name":"weights","option":"optional","type":"T"}],"inputs_range":"2 - 3","max_input":3,"max_output":2,"min_input":2,"min_output":1,"outputs":[{"description":"Weighted loss float Tensor. If reduction is 'none', this has the shape of [batch_size], or [batch_size, D1, D2, ..., Dk] in case of K-dimensional loss. Otherwise, it is a scalar.","name":"output","type":"T"},{"description":"Log probability tensor. If the output of softmax is prob, its value is log(prob).","name":"log_prob","option":"optional","type":"T"}],"outputs_range":"1 - 2","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain target to integer types","type_param_str":"Tind"}]}},{"name":"Softplus","schema":{"category":"Activation","description":"Softplus takes one input data (Tensor) and produces one output data\n(Tensor) where the softplus function, y = ln(exp(x) + 1), is applied to\nthe tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softplus',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.log(np.exp(x) + 1) # expected output [0.31326166, 0.69314718, 1.31326163]\nexpect(node, inputs=[x], outputs=[y],\n name='test_softplus_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.log(np.exp(x) + 1)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softplus')","summary":"softplus"}],"inputs":[{"description":"1D input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"1D input tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Softsign","schema":{"category":"Activation","description":"Calculates the softsign (x/(1+|x|)) of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Softsign',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.array([-0.5, 0, 0.5]).astype(np.float32)\nexpect(node, inputs=[x], outputs=[y],\n name='test_softsign_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = x / (1 + np.abs(x))\nexpect(node, inputs=[x], outputs=[y],\n name='test_softsign')","summary":"softsign"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The softsign (x/(1+|x|)) values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"SpaceToDepth","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"SpaceToDepth rearranges blocks of spatial data into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the height and width dimensions\nare moved to the depth dimension.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C * blocksize * blocksize, H/blocksize, W/blocksize].","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"SpaceToDepth","schema":{"attributes":[{"description":"Blocks of [blocksize, blocksize] are moved.","name":"blocksize","required":true,"type":"int64"}],"description":"SpaceToDepth rearranges blocks of spatial data into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the height and width dimensions\nare moved to the depth dimension.\n","domain":"ai.onnx","inputs":[{"description":"Input tensor of [N,C,H,W], where N is the batch axis, C is the channel or depth, H is the height and W is the width.","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor of [N, C * blocksize * blocksize, H/blocksize, W/blocksize].","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on","name":"axis","required":false,"type":"int64"},{"description":"length of each output","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. The lengths of the split can be specified using argument 'axis' or\noptional second input blob to the operator. Otherwise, the tensor is split\nto equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"},{"description":"Optional list of output lengths (see also arg 'split')","name":"split","option":"optional","type":"T"}],"inputs_range":"1 - 2","max_input":2,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs...","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. ","name":"axis","required":false,"type":"int64"},{"description":"length of each output","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":2,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"description":"length of each output. Values should be >= 0.","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"description":"length of each output. Values should be >= 0.","name":"split","required":false,"type":"int64[]"}],"category":"Tensor","description":"Split a tensor into a list of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\nOtherwise, the tensor is split to equal sized parts.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n axis=0\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_1d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=0,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_1d')","summary":"1d"},{"code":"input = np.array([[1., 2., 3., 4., 5., 6.],\n [7., 8., 9., 10., 11., 12.]]).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1\n)\n\nexpected_outputs = [np.array([[1., 2., 3.], [7., 8., 9.]]).astype(np.float32),\n np.array([[4., 5., 6.], [10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_2d')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n axis=1,\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([[1., 2.], [7., 8.]]).astype(np.float32),\n np.array([[3., 4., 5., 6.], [9., 10., 11., 12.]]).astype(np.float32)]\n\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_2d')","summary":"2d"},{"code":"input = np.array([1., 2., 3., 4., 5., 6.]).astype(np.float32)\n\n# If axis is not specified, split is applied on default axis 0\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3']\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4.]).astype(np.float32), np.array([5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_equal_parts_default_axis')\n\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2'],\n split=[2, 4]\n)\n\nexpected_outputs = [np.array([1., 2.]).astype(np.float32), np.array([3., 4., 5., 6.]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_variable_parts_default_axis')","summary":"default_values"},{"code":"input = np.array([]).astype(np.float32)\n\n# Split emtpy tensor to tensors of size zero\nnode = onnx.helper.make_node(\n 'Split',\n inputs=['input'],\n outputs=['output_1', 'output_2', 'output_3'],\n split=[0, 0, 0]\n)\n\nexpected_outputs = [np.array([]).astype(np.float32), np.array([]).astype(np.float32), np.array([]).astype(np.float32)]\nexpect(node, inputs=[input], outputs=[y for y in expected_outputs], name='test_split_zero_size_splits')","summary":"zero_size_splits"}],"inputs":[{"description":"The tensor to split","name":"input","type":"T"}],"max_input":1,"max_output":2147483647,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming list of tensors after splitting","name":"outputs","option":"variadic","type":"T"}],"outputs_range":"1 - ∞","since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"SplitToSequence","schema":{"attributes":[{"description":"Which axis to split on. A negative value means counting dimensions from the back. Accepted range is [-rank, rank-1].","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Keep the split dimension or not. Default 1, which means we keep split dimension. If input 'split' is specified, this attribute is ignored.","name":"keepdims","required":false,"type":"int64"}],"description":"Split a tensor into a sequence of tensors, along the specified\n'axis'. Lengths of the parts can be specified using argument 'split'.\n'split' must contain only positive numbers.\n'split' is either a scalar (tensor of empty shape), or a 1-D tensor.\nIf 'split' is a scalar, then 'input' will be split into equally sized chunks(if possible).\nLast chunk will be smaller if the 'input' size along the given axis 'axis' is not divisible\nby 'split'.\nOtherwise, the tensor is split into 'size(split)' chunks, with lengths of the parts on 'axis'\nspecified in 'split'. In this scenario, the sum of entries in 'split' must be equal to the\ndimension size of input tensor on 'axis'.\n","domain":"ai.onnx","inputs":[{"description":"The tensor to split","name":"input","type":"T"},{"description":"Length of each output. It can be either a scalar(tensor of empty shape), or a 1-D tensor. All values must be >= 0. ","name":"split","option":"optional","type":"I"}],"inputs_range":"1 - 2","max_input":2,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"One or more outputs forming a sequence of tensors after splitting","name":"output_sequence","type":"S"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int32)","tensor(int64)"],"description":"Constrain split size to integral tensor.","type_param_str":"I"},{"allowed_type_strs":["seq(tensor(uint8))","seq(tensor(uint16))","seq(tensor(uint32))","seq(tensor(uint64))","seq(tensor(int8))","seq(tensor(int16))","seq(tensor(int32))","seq(tensor(int64))","seq(tensor(float16))","seq(tensor(float))","seq(tensor(double))","seq(tensor(string))","seq(tensor(bool))","seq(tensor(complex64))","seq(tensor(complex128))"],"description":"Constrain output types to all tensor types.","type_param_str":"S"}]}},{"name":"Sqrt","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sqrt","schema":{"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sqrt","schema":{"description":"Square root takes one input data (Tensor) and produces one output data\n(Tensor) where the square root is, y = x^0.5, is applied to\nthe tensor elementwise. If x is negative, then it will return NaN.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sqrt',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([1, 4, 9]).astype(np.float32)\ny = np.sqrt(x) # expected output [1., 2., 3.]\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt_example')\n\nx = np.abs(np.random.randn(3, 4, 5).astype(np.float32))\ny = np.sqrt(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_sqrt')","summary":"sqrt"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of non-negative integers, indicate the dimensions to squeeze.","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to squeeze. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Squeeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to squeeze. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).","name":"axes","required":false,"type":"int64[]"}],"category":"Transform","description":"Remove single-dimensional entries from the shape of a tensor.\nTakes a parameter `axes` with a list of axes to squeeze.\nIf `axes` is not provided, all the single dimensions will be removed from\nthe shape. If an axis is selected with shape entry not equal to one, an error is raised.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[0],\n)\nx = np.random.randn(1, 3, 4, 5).astype(np.float32)\ny = np.squeeze(x, axis=0)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze')","summary":"squeeze"},{"code":"node = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.squeeze(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_squeeze_negative_axes')","summary":"squeeze_negative_axes"}],"inputs":[{"description":"Tensors with at least max(dims) dimensions.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"squeezed","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"StringNormalizer","schema":{"attributes":[{"default":"NONE","description":"string enum that cases output to be lowercased/uppercases/unchanged. Valid values are \"LOWER\", \"UPPER\", \"NONE\". Default is \"NONE\"","name":"case_change_action","required":false,"type":"string"},{"description":"Boolean. Whether the identification of stop words in X is case-sensitive. Default is false","name":"is_case_sensitive","required":false,"type":"int64"},{"description":"Environment dependent string that denotes the locale according to which output strings needs to be upper/lowercased.Default en_US or platform specific equivalent as decided by the implementation.","name":"locale","required":false,"type":"string"},{"description":"List of stop words. If not set, no word would be removed from X.","name":"stopwords","required":false,"type":"string[]"}],"description":"StringNormalization performs string operations for basic cleaning.\nThis operator has only one input (denoted by X) and only one output\n(denoted by Y). This operator first examines the elements in the X,\nand removes elements specified in \"stopwords\" attribute.\nAfter removing stop words, the intermediate result can be further lowercased,\nuppercased, or just returned depending the \"case_change_action\" attribute.\nThis operator only accepts [C]- and [1, C]-tensor.\nIf all elements in X are dropped, the output will be the empty value of string tensor with shape [1]\nif input shape is [C] and shape [1, 1] if input shape is [1, C].\n","domain":"ai.onnx","examples":[{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'tuesday', u'wednesday', u'thursday']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='LOWER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_lower')","summary":"monday_casesensintive_lower"},{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'tuesday', u'wednesday', u'thursday']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_nochangecase')","summary":"monday_casesensintive_nochangecase"},{"code":"input = np.array([u'monday', u'tuesday', u'wednesday', u'thursday']).astype(np.object)\noutput = np.array([u'TUESDAY', u'WEDNESDAY', u'THURSDAY']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_casesensintive_upper')","summary":"monday_casesensintive_upper"},{"code":"input = np.array([u'monday', u'monday']).astype(np.object)\noutput = np.array([u'']).astype(np.object)\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n is_case_sensitive=1,\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_empty_output')","summary":"monday_empty_output"},{"code":"input = np.array([u'Monday', u'tuesday', u'wednesday', u'Monday', u'tuesday', u'wednesday']).astype(np.object).reshape([1, 6])\n\n# It does upper case cecedille, accented E\n# and german umlaut but fails\n# with german eszett\noutput = np.array([u'TUESDAY', u'WEDNESDAY', u'TUESDAY', u'WEDNESDAY']).astype(np.object).reshape([1, 4])\nstopwords = [u'monday']\n\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n case_change_action='UPPER',\n stopwords=stopwords\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_export_monday_insensintive_upper_twodim')","summary":"monday_insensintive_upper_twodim"},{"code":"input = np.array([u'monday', u'tuesday']).astype(np.object)\noutput = input\n\n# No stopwords. This is a NOOP\nnode = onnx.helper.make_node(\n 'StringNormalizer',\n inputs=['x'],\n outputs=['y'],\n is_case_sensitive=1,\n)\nexpect(node, inputs=[input], outputs=[output], name='test_strnormalizer_nostopwords_nochangecase')","summary":"nostopwords_nochangecase"}],"inputs":[{"description":"UTF-8 strings to normalize","name":"X","type":"tensor(string)"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"UTF-8 Normalized strings","name":"Y","type":"tensor(string)"}],"since_version":10,"support_level":"common"}},{"name":"Sub","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"},{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Performs element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions. See doc for details.","name":"axis","required":false,"type":"int64"},{"description":"Pass 1 to enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"description":"Performs element-wise binary subtraction (with limited broadcast support).\n\nIf necessary the right-hand-side argument will be broadcasted to match the\nshape of left-hand-side argument. When broadcasting is specified, the second\ntensor can either be of element size 1 (including a scalar tensor and any\ntensor with rank equal to or smaller than the first tensor), or having its\nshape as a contiguous subset of the first tensor's shape. The starting of the\nmutually equal shape is specified by the argument \"axis\", and if it is not set,\nsuffix matching is assumed. 1-dim expansion doesn't work yet.\n\nFor example, the following tensor shapes are supported (with broadcast=1):\n\n shape(A) = (2, 3, 4, 5), shape(B) = (,), i.e. B is a scalar tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (1, 1), i.e. B is an 1-element tensor\n shape(A) = (2, 3, 4, 5), shape(B) = (5,)\n shape(A) = (2, 3, 4, 5), shape(B) = (4, 5)\n shape(A) = (2, 3, 4, 5), shape(B) = (3, 4), with axis=1\n shape(A) = (2, 3, 4, 5), shape(B) = (2), with axis=0\n\nAttribute `broadcast=1` needs to be passed to enable broadcasting.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand, should share the type with the second operand.","name":"A","type":"T"},{"description":"Second operand. With broadcasting can be of smaller size than A. If broadcasting is disabled it should be of the same size.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same dimensions and type as A","name":"C","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"description":"Performs element-wise binary subtraction (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sub","schema":{"description":"Performs element-wise binary subtraction (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.array([1, 2, 3]).astype(np.float32)\ny = np.array([3, 2, 1]).astype(np.float32)\nz = x - y # expected output [-2., 0., 2.]\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(3, 4, 5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub')","summary":"sub"},{"code":"node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n)\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.random.randn(5).astype(np.float32)\nz = x - y\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')","summary":"sub_broadcast"}],"inputs":[{"description":"First operand.","name":"A","type":"T"},{"description":"Second operand.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result, has same element type as two inputs","name":"C","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint32)","tensor(uint64)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to high-precision numeric tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"description":"Element-wise sum of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for Sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors. All inputs and outputs must\nhave the same shape and data type.\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for Sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor. Same dimension as inputs.","name":"sum","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"sum","type":"T"}],"since_version":8,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Sum","schema":{"description":"Element-wise sum of each of the input tensors (with Numpy-style broadcasting support).\nAll inputs and outputs must have the same data type.\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"data_0 = np.array([3, 0, 2]).astype(np.float32)\ndata_1 = np.array([1, 3, 4]).astype(np.float32)\ndata_2 = np.array([2, 6, 6]).astype(np.float32)\nresult = np.array([6, 9, 12]).astype(np.float32)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\nresult = np.add(data_0, data_1)\nnode = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n)\nexpect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')","summary":"sum"}],"inputs":[{"description":"List of tensors for sum.","name":"data_0","option":"variadic","type":"T"}],"inputs_range":"1 - ∞","max_input":2147483647,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor.","name":"sum","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tan","schema":{"description":"Calculates the tangent of the given input tensor, element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tan',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tan_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tan(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tan')","summary":"tan"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The tangent of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"attributes":[{"description":"legacy optimization attribute.","name":"consumed_inputs","required":false,"type":"int64[]"}],"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"1-D input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","description":"Calculates the hyperbolic tangent of the given input tensor element-wise.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tanh',\n inputs=['x'],\n outputs=['y'],\n)\n\nx = np.array([-1, 0, 1]).astype(np.float32)\ny = np.tanh(x) # expected output [-0.76159418, 0., 0.76159418]\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.tanh(x)\nexpect(node, inputs=[x], outputs=[y],\n name='test_tanh')","summary":"tanh"}],"inputs":[{"description":"Input tensor","name":"input","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The hyperbolic tangent values of the input tensor computed element-wise","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)","tensor(bfloat16)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"TfIdfVectorizer","schema":{"attributes":[{"description":"Maximum n-gram length. If this value is 3, 3-grams will be used to generate the output.","name":"max_gram_length","required":true,"type":"int64"},{"description":"Maximum number of items (integers/strings) to be skipped when constructing an n-gram from X. If max_skip_count=1, min_gram_length=2, max_gram_length=3, this operator may generate 2-grams with skip_count=0 and skip_count=1, and 3-grams with skip_count=0 and skip_count=1","name":"max_skip_count","required":true,"type":"int64"},{"description":"Minimum n-gram length. If this value is 2 and max_gram_length is 3, output may contain counts of 2-grams and 3-grams.","name":"min_gram_length","required":true,"type":"int64"},{"description":"The weighting criteria. It can be one of \"TF\" (term frequency), \"IDF\" (inverse document frequency), and \"TFIDF\" (the combination of TF and IDF)","name":"mode","required":true,"type":"string"},{"description":"The starting indexes of 1-grams, 2-grams, and so on in pool. It is useful when determining the boundary between two consecutive collections of n-grams. For example, if ngram_counts is [0, 17, 36], the first index (zero-based) of 1-gram/2-gram/3-gram in pool are 0/17/36. This format is essentially identical to CSR (or CSC) sparse matrix format, and we choose to use this due to its popularity.","name":"ngram_counts","required":true,"type":"int64[]"},{"description":"list of int64s (type: AttributeProto::INTS). This list is parallel to the specified 'pool_*' attribute. The i-th element in ngram_indexes indicate the coordinate of the i-th n-gram in the output tensor.","name":"ngram_indexes","required":true,"type":"int64[]"},{"description":"List of int64 n-grams learned from the training set. Either this or pool_strings attributes must be present but not both. It's an 1-D tensor starting with the collections of all 1-grams and ending with the collections of n-grams. The i-th element in pool stores the n-gram that should be mapped to coordinate ngram_indexes[i] in the output vector.","name":"pool_int64s","required":false,"type":"int64[]"},{"description":"List of strings n-grams learned from the training set. Either this or pool_int64s attributes must be present but not both. It's an 1-D tensor starting with the collections of all 1-grams and ending with the collections of n-grams. The i-th element in pool stores the n-gram that should be mapped to coordinate ngram_indexes[i] in the output vector.","name":"pool_strings","required":false,"type":"string[]"},{"description":"list of floats. This attribute stores the weight of each n-gram in pool. The i-th element in weights is the weight of the i-th n-gram in pool. Its length equals to the size of ngram_indexes. By default, weights is an all-one tensor.This attribute is used when mode is \"IDF\" or \"TFIDF\" to scale the associated word counts.","name":"weights","required":false,"type":"float32[]"}],"description":"This transform extracts n-grams from the input sequence and save them as a vector. Input can\nbe either a 1-D or 2-D tensor. For 1-D input, output is the n-gram representation of that input.\nFor 2-D input, the output is also a 2-D tensor whose i-th row is the n-gram representation of the i-th input row.\nMore specifically, if input shape is [C], the corresponding output shape would be [max(ngram_indexes) + 1].\nIf input shape is [N, C], this operator produces a [N, max(ngram_indexes) + 1]-tensor.\n\nIn contrast to standard n-gram extraction, here, the indexes of extracting an n-gram from the original\nsequence are not necessarily consecutive numbers. The discontinuity between indexes are controlled by the number of skips.\nIf the number of skips is 2, we should skip two tokens when scanning through the original sequence.\nLet's consider an example. Assume that input sequence is [94, 17, 36, 12, 28] and the number of skips is 2.\nThe associated 2-grams are [94, 12] and [17, 28] respectively indexed by [0, 3] and [1, 4].\nIf the number of skips becomes 0, the 2-grams generated are [94, 17], [17, 36], [36, 12], [12, 28]\nindexed by [0, 1], [1, 2], [2, 3], [3, 4], respectively.\n\nThe output vector (denoted by Y) stores the count of each n-gram;\nY[ngram_indexes[i]] indicates the times that the i-th n-gram is found. The attribute ngram_indexes is used to determine the mapping\nbetween index i and the corresponding n-gram's output coordinate. If pool_int64s is [94, 17, 17, 36], ngram_indexes is [1, 0],\nngram_counts=[0, 0], then the Y[0] (first element in Y) and Y[1] (second element in Y) are the counts of [17, 36] and [94, 17],\nrespectively. An n-gram which cannot be found in pool_strings/pool_int64s should be ignored and has no effect on the output.\nNote that we may consider all skips up to S when generating the n-grams.\n\nThe examples used above are true if mode is \"TF\". If mode is \"IDF\", all the counts larger than 1 would be truncated to 1 and\nthe i-th element in weights would be used to scale (by multiplication) the count of the i-th n-gram in pool. If mode is \"TFIDF\",\nthis operator first computes the counts of all n-grams and then scale them by the associated values in the weights attribute.\n\nOnly one of pool_strings and pool_int64s can be set. If pool_int64s is set, the input should be an integer tensor.\nIf pool_strings is set, the input must be a string tensor.\n","domain":"ai.onnx","examples":[{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip0')","summary":"tf_batch_onlybigrams_skip0"},{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 1., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_onlybigrams_skip5')","summary":"tf_batch_onlybigrams_skip5"},{"code":"input = np.array([[1, 1, 3, 3, 3, 7], [8, 6, 7, 5, 6, 8]]).astype(np.int32)\noutput = np.array([[0., 3., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 1., 1., 1.]]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=1,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_batch_uniandbigrams_skip5')","summary":"tf_batch_uniandbigrams_skip5"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 0., 0., 0., 1., 1., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_only_bigrams_skip0')","summary":"tf_only_bigrams_skip0"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([1., 1., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 0]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2]).astype(np.int64)\npool_int64s = np.array([ # unigrams none\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=0,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_levelempty')","summary":"tf_onlybigrams_levelempty"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 0., 0., 0., 1., 3., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=2,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_onlybigrams_skip5')","summary":"tf_onlybigrams_skip5"},{"code":"input = np.array([1, 1, 3, 3, 3, 7, 8, 6, 7, 5, 6, 8]).astype(np.int32)\noutput = np.array([0., 3., 1., 0., 1., 3., 1.]).astype(np.float32)\n\nngram_counts = np.array([0, 4]).astype(np.int64)\nngram_indexes = np.array([0, 1, 2, 3, 4, 5, 6]).astype(np.int64)\npool_int64s = np.array([2, 3, 5, 4, # unigrams\n 5, 6, 7, 8, 6, 7]).astype(np.int64) # bigrams\n\nhelper = TfIdfVectorizerHelper(\n mode='TF',\n min_gram_length=1,\n max_gram_length=2,\n max_skip_count=5,\n ngram_counts=ngram_counts,\n ngram_indexes=ngram_indexes,\n pool_int64s=pool_int64s\n)\nnode = helper.make_node_noweights()\nexpect(node, inputs=[input], outputs=[output], name='test_tfidfvectorizer_tf_uniandbigrams_skip5')","summary":"tf_uniandbigrams_skip5"}],"inputs":[{"description":"Input for n-gram extraction","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Ngram results","name":"Y","type":"T1"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(string)","tensor(int32)","tensor(int64)"],"description":"Input is ether string UTF-8 or int32/int64","type_param_str":"T"},{"allowed_type_strs":["tensor(float)"],"description":"1-D tensor of floats","type_param_str":"T1"}]}},{"name":"ThresholdedRelu","schema":{"attributes":[{"default":1,"description":"Threshold value","name":"alpha","required":false,"type":"float32"}],"category":"Activation","description":"ThresholdedRelu takes one input data (Tensor) and produces one output data\n(Tensor) where the rectified linear function, y = x for x > alpha, y = 0 otherwise,\nis applied to the tensor elementwise.\n","domain":"ai.onnx","examples":[{"code":"default_alpha = 1.0\nnode = onnx.helper.make_node(\n 'ThresholdedRelu',\n inputs=['x'],\n outputs=['y']\n)\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, default_alpha, np.inf)\ny[y == default_alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu_default')","summary":"default"},{"code":"alpha = 2.0\nnode = onnx.helper.make_node(\n 'ThresholdedRelu',\n inputs=['x'],\n outputs=['y'],\n alpha=alpha\n)\n\nx = np.array([-1.5, 0., 1.2, 2.0, 2.2]).astype(np.float32)\ny = np.clip(x, alpha, np.inf) # expected output [0., 0., 0., 0., 2.2]\ny[y == alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu_example')\n\nx = np.random.randn(3, 4, 5).astype(np.float32)\ny = np.clip(x, alpha, np.inf)\ny[y == alpha] = 0\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_thresholdedrelu')","summary":"thresholdedrelu"}],"inputs":[{"description":"Input tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Output tensor","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Repeat the elements of a tensor along an axis.","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"Number of repeated copies to make of the input tensor.","name":"tiles","type":"T"},{"description":"Axis along which to repeat.","name":"axis","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Output tensor of same shape and type as input.","name":"output","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain tiles and axis's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Constructs a tensor by tiling a given tensor.\nThis is the same as function `tile` in Numpy, but no broadcast.\nFor example A = [[1, 2], [3, 4]], B = [1, 2], tile(A, B) = [[1, 2, 1, 2], [3, 4, 3, 4]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"1D int64 tensor of the same length as input's dimension number, includes numbers of repeated copies along input's dimensions.","name":"repeats","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same dimension and type as tensor input. output_dim[i] = input_dim[i] * repeats[i]","name":"output","type":"T"}],"since_version":6,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain repeat's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"Tile","schema":{"category":"Shape","description":"Constructs a tensor by tiling a given tensor.\nThis is the same as function `tile` in Numpy, but no broadcast.\nFor example A = [[1, 2], [3, 4]], B = [1, 2], tile(A, B) = [[1, 2, 1, 2], [3, 4, 3, 4]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.random.rand(2, 3, 4, 5).astype(np.float32)\n\nrepeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64)\n\nz = np.tile(x, repeats)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile')","summary":"tile"},{"code":"node = onnx.helper.make_node(\n 'Tile',\n inputs=['x', 'y'],\n outputs=['z']\n)\n\nx = np.array([\n [0, 1],\n [2, 3]\n], dtype=np.float32)\n\nrepeats = np.array([2, 2], dtype=np.int64)\n\nz = np.array([\n [0, 1, 0, 1],\n [2, 3, 2, 3],\n [0, 1, 0, 1],\n [2, 3, 2, 3]\n], dtype=np.float32)\n\nexpect(node,\n inputs=[x, repeats],\n outputs=[z],\n name='test_tile_precomputed')","summary":"tile_precomputed"}],"inputs":[{"description":"Input tensor of any shape.","name":"input","type":"T"},{"description":"1D int64 tensor of the same length as input's dimension number, includes numbers of repeated copies along input's dimensions.","name":"repeats","type":"T1"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Output tensor of the same dimension and type as tensor input. output_dim[i] = input_dim[i] * repeats[i]","name":"output","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain repeat's type to int64 tensors.","type_param_str":"T1"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort.","name":"axis","required":false,"type":"int64"},{"description":"Number of top elements to retrieve","name":"k","required":true,"type":"int64"}],"description":"Retrieve the top-K elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort.","name":"axis","required":false,"type":"int64"}],"description":"Retrieve the top-K elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\n \nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"},{"description":"A 1-D tensor containing a single positive value corresponding to the number of top elements to retrieve","name":"K","type":"tensor(int64)"}],"max_input":2,"max_output":2,"min_input":2,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to float tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"TopK","schema":{"attributes":[{"default":-1,"description":"Dimension on which to do the sort. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"Whether to return the top-K largest or smallest elements.","name":"largest","required":false,"type":"int64"},{"default":1,"description":"Whether to return the elements in sorted order.","name":"sorted","required":false,"type":"int64"}],"description":"Retrieve the top-K largest or smallest elements along a specified axis. Given an input tensor of\nshape [a_1, a_2, ..., a_n, r] and integer argument k, return two outputs:\n -Value tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n]\n which contains the values of the top k elements along the specified axis\n -Index tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] which\n contains the indices of the top k elements (original indices from the input\n tensor).\n\nIf \"largest\" is 1 (the default value) then the k largest elements are returned.\nIf \"sorted\" is 1 (the default value) then the resulting k elements will be sorted.\nIf \"sorted\" is 0, order of returned 'Values' and 'Indices' are undefined.\n\nGiven two equivalent values, this operator uses the indices along the axis as\n a tiebreaker. That is, the element with the lower index will appear first.\n","domain":"ai.onnx","examples":[{"code":"axis = 1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n#print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k')","summary":"top_k"},{"code":"axis = -1\nlargest = 1\n\nk = 3\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis\n)\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n# print(values_ref)\n#[[ 3. 2. 1.]\n# [ 7. 6. 5.]\n# [11. 10. 9.]]\n# print(indices_ref)\n#[[3 2 1]\n# [3 2 1]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_negative_axis')","summary":"top_k_negative_axis"},{"code":"axis = 1\nlargest = 0\nsorted = 1\nk = 3\n\nnode = onnx.helper.make_node(\n 'TopK',\n inputs=['x', 'k'],\n outputs=['values', 'indices'],\n axis=axis,\n largest=largest,\n sorted=sorted\n)\n\nX = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [11, 10, 9, 8],\n], dtype=np.float32)\nK = np.array([k], dtype=np.int64)\nvalues_ref, indices_ref = topk_sorted_implementation(X, k, axis, largest)\n\n#print(values_ref)\n#[[ 0. 1. 2.]\n# [ 4. 5. 6.]\n# [ 8. 9. 10.]]\n#print(indices_ref)\n#[[0 1 2]\n# [0 1 2]\n# [3 2 1]]\n\nexpect(node, inputs=[X, K], outputs=[values_ref, indices_ref],\n name='test_top_k_smallest')","summary":"top_k_smallest"}],"inputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_n, r]","name":"X","type":"T"},{"description":"A 1-D tensor containing a single positive value corresponding to the number of top elements to retrieve","name":"K","type":"tensor(int64)"}],"max_input":2,"max_output":2,"min_input":2,"min_output":2,"outputs":[{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing top K values from the input tensor","name":"Values","type":"T"},{"description":"Tensor of shape [a_1, a_2, ..., a_{axis-1}, k, a_{axis+1}, ... a_n] containing the corresponding input tensor indices for the top K values.","name":"Indices","type":"I"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain input and output types to numeric tensors.","type_param_str":"T"},{"allowed_type_strs":["tensor(int64)"],"description":"Constrain index tensor to int64","type_param_str":"I"}]}},{"name":"Transpose","schema":{"attributes":[{"description":"A list of integers. By default, reverse the dimensions, otherwise permute the axes according to the values given.","name":"perm","required":false,"type":"int64[]"}],"category":"Transform","description":"Transpose the input tensor similar to numpy.transpose. For example, when\nperm=(1, 0, 2), given an input tensor of shape (1, 2, 3), the output shape\nwill be (2, 1, 3).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\npermutations = list(itertools.permutations(np.arange(len(shape))))\n\nfor i in range(len(permutations)):\n node = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed'],\n perm=permutations[i]\n )\n transposed = np.transpose(data, permutations[i])\n expect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_all_permutations_' + str(i))","summary":"all_permutations"},{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed']\n)\n\ntransposed = np.transpose(data)\nexpect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_default')","summary":"default"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Transposed output.","name":"transposed","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Transpose","schema":{"attributes":[{"description":"A list of integers. By default, reverse the dimensions, otherwise permute the axes according to the values given.","name":"perm","required":false,"type":"int64[]"}],"category":"Transform","description":"Transpose the input tensor similar to numpy.transpose. For example, when\nperm=(1, 0, 2), given an input tensor of shape (1, 2, 3), the output shape\nwill be (2, 1, 3).\n","domain":"ai.onnx","examples":[{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\npermutations = list(itertools.permutations(np.arange(len(shape))))\n\nfor i in range(len(permutations)):\n node = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed'],\n perm=permutations[i]\n )\n transposed = np.transpose(data, permutations[i])\n expect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_all_permutations_' + str(i))","summary":"all_permutations"},{"code":"shape = (2, 3, 4)\ndata = np.random.random_sample(shape).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Transpose',\n inputs=['data'],\n outputs=['transposed']\n)\n\ntransposed = np.transpose(data)\nexpect(node, inputs=[data], outputs=[transposed],\n name='test_transpose_default')","summary":"default"}],"inputs":[{"description":"An input tensor.","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Transposed output.","name":"transposed","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"TreeEnsembleClassifier","schema":{"attributes":[{"description":"Base values for classification, added to final class score; the size must be the same as the classes or can be left unassigned (assumed 0)","name":"base_values","required":false,"type":"float32[]"},{"description":"The index of the class list that each weight is for.","name":"class_ids","required":false,"type":"int64[]"},{"description":"node id that this weight is for.","name":"class_nodeids","required":false,"type":"int64[]"},{"description":"The id of the tree that this node is in.","name":"class_treeids","required":false,"type":"int64[]"},{"description":"The weight for the class in class_id.","name":"class_weights","required":false,"type":"float32[]"},{"description":"Class labels if using integer labels.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_int64s","required":false,"type":"int64[]"},{"description":"Class labels if using string labels.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"},{"description":"Child node if expression is false.","name":"nodes_falsenodeids","required":false,"type":"int64[]"},{"description":"Feature id for each node.","name":"nodes_featureids","required":false,"type":"int64[]"},{"description":"Popularity of each node, used for performance and may be omitted.","name":"nodes_hitrates","required":false,"type":"float32[]"},{"description":"For each node, define what to do in the presence of a missing value: if a value is missing (NaN), use the 'true' or 'false' branch based on the value in this array.
    This attribute may be left undefined, and the defalt value is false (0) for all nodes.","name":"nodes_missing_value_tracks_true","required":false,"type":"int64[]"},{"description":"The node kind, that is, the comparison to make at the node. There is no comparison to make at a leaf node.
    One of 'BRANCH_LEQ', 'BRANCH_LT', 'BRANCH_GTE', 'BRANCH_GT', 'BRANCH_EQ', 'BRANCH_NEQ', 'LEAF'","name":"nodes_modes","required":false,"type":"string[]"},{"description":"Node id for each node. Ids may restart at zero for each tree, but it not required to.","name":"nodes_nodeids","required":false,"type":"int64[]"},{"description":"Tree id for each node.","name":"nodes_treeids","required":false,"type":"int64[]"},{"description":"Child node if expression is true.","name":"nodes_truenodeids","required":false,"type":"int64[]"},{"description":"Thresholds to do the splitting on for each node.","name":"nodes_values","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the score.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT.'","name":"post_transform","required":false,"type":"string"}],"description":"Tree Ensemble classifier. Returns the top class for each of N inputs.
    \n The attributes named 'nodes_X' form a sequence of tuples, associated by \n index into the sequences, which must all be of equal length. These tuples\n define the nodes.
    \n Similarly, all fields prefixed with 'class_' are tuples of votes at the leaves.\n A leaf may have multiple votes, where each vote is weighted by\n the associated class_weights index.
    \n One and only one of classlabels_strings or classlabels_int64s\n will be defined. The class_ids are indices into this list.\n","domain":"ai.onnx.ml","inputs":[{"description":"Input of shape [N,F]","name":"X","type":"T1"}],"max_input":1,"max_output":2,"min_input":1,"min_output":2,"outputs":[{"description":"N, Top class for each point","name":"Y","type":"T2"},{"description":"The class score for each class, for each point, a tensor of shape [N,E].","name":"Z","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T1"},{"allowed_type_strs":["tensor(string)","tensor(int64)"],"description":"The output type will be a tensor of strings or integers, depending on which of the the classlabels_* attributes is used.","type_param_str":"T2"}]}},{"name":"TreeEnsembleRegressor","schema":{"attributes":[{"default":"SUM","description":"Defines how to aggregate leaf values within a target.
    One of 'AVERAGE,' 'SUM,' 'MIN,' 'MAX.'","name":"aggregate_function","required":false,"type":"string"},{"description":"Base values for classification, added to final class score; the size must be the same as the classes or can be left unassigned (assumed 0)","name":"base_values","required":false,"type":"float32[]"},{"description":"The total number of targets.","name":"n_targets","required":false,"type":"int64"},{"description":"Child node if expression is false","name":"nodes_falsenodeids","required":false,"type":"int64[]"},{"description":"Feature id for each node.","name":"nodes_featureids","required":false,"type":"int64[]"},{"description":"Popularity of each node, used for performance and may be omitted.","name":"nodes_hitrates","required":false,"type":"float32[]"},{"description":"For each node, define what to do in the presence of a NaN: use the 'true' (if the attribute value is 1) or 'false' (if the attribute value is 0) branch based on the value in this array.
    This attribute may be left undefined and the defalt value is false (0) for all nodes.","name":"nodes_missing_value_tracks_true","required":false,"type":"int64[]"},{"description":"The node kind, that is, the comparison to make at the node. There is no comparison to make at a leaf node.
    One of 'BRANCH_LEQ', 'BRANCH_LT', 'BRANCH_GTE', 'BRANCH_GT', 'BRANCH_EQ', 'BRANCH_NEQ', 'LEAF'","name":"nodes_modes","required":false,"type":"string[]"},{"description":"Node id for each node. Node ids must restart at zero for each tree and increase sequentially.","name":"nodes_nodeids","required":false,"type":"int64[]"},{"description":"Tree id for each node.","name":"nodes_treeids","required":false,"type":"int64[]"},{"description":"Child node if expression is true","name":"nodes_truenodeids","required":false,"type":"int64[]"},{"description":"Thresholds to do the splitting on for each node.","name":"nodes_values","required":false,"type":"float32[]"},{"default":"NONE","description":"Indicates the transform to apply to the score.
    One of 'NONE,' 'SOFTMAX,' 'LOGISTIC,' 'SOFTMAX_ZERO,' or 'PROBIT'","name":"post_transform","required":false,"type":"string"},{"description":"The index of the target that each weight is for","name":"target_ids","required":false,"type":"int64[]"},{"description":"The node id of each weight","name":"target_nodeids","required":false,"type":"int64[]"},{"description":"The id of the tree that each node is in.","name":"target_treeids","required":false,"type":"int64[]"},{"description":"The weight for each target","name":"target_weights","required":false,"type":"float32[]"}],"description":"Tree Ensemble regressor. Returns the regressed values for each input in N.
    \n All args with nodes_ are fields of a tuple of tree nodes, and\n it is assumed they are the same length, and an index i will decode the\n tuple across these inputs. Each node id can appear only once\n for each tree id.
    \n All fields prefixed with target_ are tuples of votes at the leaves.
    \n A leaf may have multiple votes, where each vote is weighted by\n the associated target_weights index.
    \n All trees must have their node ids start at 0 and increment by 1.
    \n Mode enum is BRANCH_LEQ, BRANCH_LT, BRANCH_GTE, BRANCH_GT, BRANCH_EQ, BRANCH_NEQ, LEAF\n","domain":"ai.onnx.ml","inputs":[{"description":"Input of shape [N,F]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"N classes","name":"Y","type":"tensor(float)"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(float)","tensor(double)","tensor(int64)","tensor(int32)"],"description":"The input type must be a tensor of a numeric type.","type_param_str":"T"}]}},{"name":"Unique","schema":{"attributes":[{"description":"(Optional) The dimension to apply unique. If not specified, the unique elements of the flattened input are returned. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).","name":"axis","required":false,"type":"int64"},{"default":1,"description":"(Optional) Whether to sort the unique elements in ascending order before returning as output. Must be one of 0, or 1 (default).","name":"sorted","required":false,"type":"int64"}],"description":"Find the unique elements of a tensor. When an optional attribute 'axis' is provided, unique subtensors sliced along the 'axis' are returned. \nOtherwise the input tensor is flattened and unique values of the flattened tensor are returned. \n\nThis operator returns the unique values or sliced unique subtensors of the input tensor and three optional outputs. \nThe first output tensor 'Y' contains all unique values or subtensors of the input. \nThe second optional output tensor 'indices' contains indices of 'Y' elements' first occurance in 'X'.. \nThe third optional output tensor 'inverse_indices' contains, for elements of 'X', its corresponding indices in 'Y'. \". \nThe fourth optional output tensor 'counts' contains the count of each element of 'Y' in the input. \n\nOutputs are either sorted in ascending order or optionally in the order of the first occurrence of the values in the input. \n\nhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html\n\nExample 1:\n input_X = [2, 1, 1, 3, 4, 3]\n attribute_sorted = 0\n attribute_axis = None\n output_Y = [2, 1, 3, 4]\n output_indices = [0, 1, 3, 4]\n output_inverse_indices = [0, 1, 1, 2, 3, 2]\n output_counts = [1, 2, 2, 1]\n\nExample 2:\n input_X = [[1, 3], [2, 3]]\n attribute_sorted = 1\n attribute_axis = None\n output_Y = [1, 2, 3]\n output_indices = [0, 2, 1]\n output_inverse_indices = [0, 2, 1, 2]\n output_counts = [1, 1, 2]\n\nExample 3:\n input_X = [[1, 0, 0], [1, 0, 0], [2, 3, 4]]\n attribute_sorted = 1\n attribute_axis = 0\n output_Y = [[1, 0, 0], [2, 3, 4]]\n output_indices = [0, 2]\n output_inverse_indices = [0, 0, 1]\n output_counts = [2, 1]\n\nExample 4:\n input_x = [[[1., 1.], [0., 1.], [2., 1.], [0., 1.]], \n [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]]\n attribute_sorted = 1\n attribute_axis = 1\n\n intermediate data are presented below for better understanding: \n \n there are 4 subtensors sliced along axis 1 of input_x (shape = (2, 4, 2)):\n A: [[1, 1], [1, 1]], \n [[0, 1], [0, 1]], \n [[2, 1], [2, 1]], \n [[0, 1], [0, 1]].\n \n there are 3 unique subtensors: \n [[1, 1], [1, 1]], \n [[0, 1], [0, 1]], \n [[2, 1], [2, 1]].\n \n sorted unique subtensors:\n B: [[0, 1], [0, 1]], \n [[1, 1], [1, 1]], \n [[2, 1], [2, 1]].\n \n output_Y is constructed from B:\n [[[0. 1.], [1. 1.], [2. 1.]], \n [[0. 1.], [1. 1.], [2. 1.]]]\n\n output_indices is to map from B to A:\n [1, 0, 2]\n \n output_inverse_indices is to map from A to B:\n [1, 0, 2, 0]\n\n output_counts = [2 1 1]\n","domain":"ai.onnx","examples":[{"code":"node_not_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=0\n)\n# numpy unique does not retain original order (it sorts the output unique values)\n# https://github.com/numpy/numpy/issues/8621\n# we need to recover unsorted output and indices\nx = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True)\n\n# prepare index mapping from sorted to unsorted\nargsorted_indices = np.argsort(indices)\ninverse_indices_map = {i: si for i, si in zip(argsorted_indices, np.arange(len(argsorted_indices)))}\n\nindices = indices[argsorted_indices]\ny = np.take(x, indices, axis=0)\ninverse_indices = np.asarray([inverse_indices_map[i] for i in inverse_indices], dtype=np.int64)\ncounts = counts[argsorted_indices]\n# print(y)\n# [2.0, 1.0, 3.0, 4.0]\n# print(indices)\n# [0 1 3 4]\n# print(inverse_indices)\n# [0, 1, 1, 2, 3, 2]\n# print(counts)\n# [1, 2, 2, 1]\n\nexpect(node_not_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_not_sorted_without_axis')","summary":"not_sorted_without_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=0\n)\n\nx = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=0)\n# print(y)\n# [[1. 0. 0.]\n# [2. 3. 4.]]\n# print(indices)\n# [0 2]\n# print(inverse_indices)\n# [0 0 1]\n# print(counts)\n# [2 1]\n\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis')","summary":"sorted_with_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=1\n)\n\nx = np.array([[[1., 1.], [0., 1.], [2., 1.], [0., 1.]],\n [[1., 1.], [0., 1.], [2., 1.], [0., 1.]]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=1)\n# print(y)\n# [[[0. 1.]\n# [1. 1.]\n# [2. 1.]]\n# [[0. 1.]\n# [1. 1.]\n# [2. 1.]]]\n# print(indices)\n# [1 0 2]\n# print(inverse_indices)\n# [1 0 2 0]\n# print(counts)\n# [2 1 1]\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_axis_3d')","summary":"sorted_with_axis_3d"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts'],\n sorted=1,\n axis=-1\n)\n\nx = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 3]], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True, axis=-1)\n# print(y)\n# [[0. 1.]\n# [0. 1.]\n# [3. 2.]]\n# print(indices)\n# [1 0]\n# print(inverse_indices)\n# [1 0 0]\n# print(counts)\n# [2 1]\n\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_with_negative_axis')","summary":"sorted_with_negative_axis"},{"code":"node_sorted = onnx.helper.make_node(\n 'Unique',\n inputs=['X'],\n outputs=['Y', 'indices', 'inverse_indices', 'counts']\n)\n\nx = np.array([2.0, 1.0, 1.0, 3.0, 4.0, 3.0], dtype=np.float32)\ny, indices, inverse_indices, counts = np.unique(x, True, True, True)\nexpect(node_sorted, inputs=[x], outputs=[y, indices, inverse_indices, counts], name='test_unique_sorted_without_axis')","summary":"sorted_without_axis"}],"inputs":[{"description":"A N-D input tensor that is to be processed.","name":"X","type":"T"}],"max_input":1,"max_output":4,"min_input":1,"min_output":1,"outputs":[{"description":"A tensor of the same type as 'X' containing all the unique values or subtensors sliced along a provided 'axis' in 'X', either sorted or maintained in the same order they occur in input 'X'","name":"Y","type":"T"},{"description":"A 1-D INT64 tensor containing indices of 'Y' elements' first occurance in 'X'. When 'axis' is provided, it contains indices to subtensors in input 'X' on the 'axis'. When 'axis' is not provided, it contains indices to values in the flattened input tensor. ","name":"indices","option":"optional","type":"tensor(int64)"},{"description":"A 1-D INT64 tensor containing, for elements of 'X', its corresponding indices in 'Y'. When 'axis' is provided, it contains indices to subtensors in output 'Y' on the 'axis'. When 'axis' is not provided, it contains indices to values in output 'Y'. ","name":"inverse_indices","option":"optional","type":"tensor(int64)"},{"description":"A 1-D INT64 tensor containing the count of each element of 'Y' in input 'X'","name":"counts","option":"optional","type":"tensor(int64)"}],"outputs_range":"1 - 4","since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Input can be of any tensor type.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of non-negative integers, indicate the dimensions to be inserted","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of a tensor.\nTakes one required argument `axes`, a list of dimensions that will be inserted.\nDimension indices in `axes` are as seen in the output tensor. For example:\n Given a tensor such that tensor with shape [3, 4, 5], then\n Unsqueeze(tensor, axes=[0, 4]) has shape [1, 3, 4, 5, 1]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to be inserted. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(expanded).","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of an input tensor (`data`).\nTakes one required argument `axes` - which contains a list of dimension indices and this operator will insert a dimension of value `1` into the corresponding index of the output tensor (`expanded`).\n\nFor example:\n Given an input tensor (`data`) of shape [3, 4, 5], then\n Unsqueeze(data, axes=[0, 4]) outputs a tensor (`expanded`) containing same data as `data` but with shape [1, 3, 4, 5, 1].\n\nThe attribute `axes` should not contain any duplicate entries. It is an error if it contains duplicates.\nThe rank of the output tensor (`output_rank`) is the rank of the input tensor (`data`) plus the number of values in `axes`.\nEach value in `axes` should be within the (inclusive) range [-output_rank , output_rank - 1]. \nThe order of values in `axes` does not matter and can come in any order. \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":11,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Unsqueeze","schema":{"attributes":[{"description":"List of integers indicating the dimensions to be inserted. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(expanded).","name":"axes","required":true,"type":"int64[]"}],"category":"Transform","description":"Insert single-dimensional entries to the shape of an input tensor (`data`).\nTakes one required argument `axes` - which contains a list of dimension indices and this operator will insert a dimension of value `1` into the corresponding index of the output tensor (`expanded`).\n\nFor example:\n Given an input tensor (`data`) of shape [3, 4, 5], then\n Unsqueeze(data, axes=[0, 4]) outputs a tensor (`expanded`) containing same data as `data` but with shape [1, 3, 4, 5, 1].\n\nThe attribute `axes` should not contain any duplicate entries. It is an error if it contains duplicates.\nThe rank of the output tensor (`output_rank`) is the rank of the input tensor (`data`) plus the number of values in `axes`.\nEach value in `axes` should be within the (inclusive) range [-output_rank , output_rank - 1]. \nThe order of values in `axes` does not matter and can come in any order. \n\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[-2],\n)\nx = np.random.randn(1, 3, 1, 5).astype(np.float32)\ny = np.expand_dims(x, axis=-2)\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_negative_axes')","summary":"unsqueeze_negative_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nfor i in range(x.ndim):\n node = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[i],\n )\n y = np.expand_dims(x, axis=i)\n\n expect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_axis_' + str(i))","summary":"unsqueeze_one_axis"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[2, 4, 5],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_three_axes')","summary":"unsqueeze_three_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[1, 4],\n)\ny = np.expand_dims(x, axis=1)\ny = np.expand_dims(y, axis=4)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_two_axes')","summary":"unsqueeze_two_axes"},{"code":"x = np.random.randn(3, 4, 5).astype(np.float32)\n\nnode = onnx.helper.make_node(\n 'Unsqueeze',\n inputs=['x'],\n outputs=['y'],\n axes=[5, 4, 2],\n)\ny = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=4)\ny = np.expand_dims(y, axis=5)\n\nexpect(node, inputs=[x], outputs=[y],\n name='test_unsqueeze_unsorted_axes')","summary":"unsqueeze_unsorted_axes"}],"inputs":[{"description":"Original tensor","name":"data","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"Reshaped tensor with same data as input.","name":"expanded","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"description":"The scale along height dimension. It takes value greater than or equal to 1.","name":"height_scale","required":true,"type":"float32"},{"default":"nearest","description":"Two interpolation modes: nearest(default), bilinear","name":"mode","required":false,"type":"string"},{"description":"The scale along width dimension. It takes value greater than or equal to 1.","name":"width_scale","required":true,"type":"float32"}],"category":"Data","description":"Upsample the input tensor.\nThe width and height of the output tensor are:\n output_width = floor(input_width * width_scale),\n output_height = floor(input_height * height_scale).\nExample:\n Given `data` tensor, width_scale, height_scale, mode,\n Upsample the input 4-D tensor in nearest mode:\n data = [[[\n [1, 2],\n [3, 4]\n ]]]\n width_scale = 2\n height_scale = 2\n mode = \"nearest\"\n output = [[[\n [1, 1, 2, 2],\n [1, 1, 2, 2],\n [3, 3, 4, 4],\n [3, 3, 4, 4]\n ]]]\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"4-D tensor, [N,C,H,W]","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"4-D tensor after resizing, [N,C,H,W]","name":"Y","type":"T"}],"since_version":1,"support_level":"experimental","type_constraints":[{"allowed_type_strs":["tensor(bool)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)"],"description":"Constrain output types to bool, int32, int64, float16, float, double tensors.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","required":true,"type":"float32[]"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":10,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Upsample","schema":{"attributes":[{"default":"nearest","description":"Two interpolation modes: nearest (default), and linear (including bilinear, trilinear, etc)","name":"mode","required":false,"type":"string"}],"category":"Data","description":"Upsample the input tensor.\nEach dimension value of the output tensor is:\n output_dimension = floor(input_dimension * scale).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Upsample',\n inputs=['X', 'scales'],\n outputs=['Y'],\n mode='nearest',\n)\n\ndata = np.array([[[\n [1, 2],\n [3, 4],\n]]], dtype=np.float32)\n\nscales = np.array([1.0, 1.0, 2.0, 3.0], dtype=np.float32)\n\noutput = np.array([[[\n [1, 1, 1, 2, 2, 2],\n [1, 1, 1, 2, 2, 2],\n [3, 3, 3, 4, 4, 4],\n [3, 3, 3, 4, 4, 4],\n]]], dtype=np.float32)\n\nexpect(node, inputs=[data, scales], outputs=[output],\n name='test_upsample_nearest', opset_imports=[helper.make_opsetid(\"\", 9)])","summary":"nearest"}],"inputs":[{"description":"N-D tensor","name":"X","type":"T"},{"description":"The scale array along each dimension. It takes value greater than or equal to 1. The number of elements of 'scales' should be the same as the rank of input 'X'.","name":"scales","type":"tensor(float)"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"N-D tensor after resizing","name":"Y","type":"T"}],"since_version":13,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(bfloat16)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input 'X' and output 'Y' to all tensor types.","type_param_str":"T"}]}},{"name":"Where","schema":{"description":"Return elements, either from X or Y, depending on condition\n (with Numpy-style broadcasting support).\n Where behaves like numpy.where with three parameters:\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Where',\n inputs=['condition', 'x', 'y'],\n outputs=['z'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nx = np.array([[1, 2], [3, 4]], dtype=np.int64)\ny = np.array([[9, 8], [7, 6]], dtype=np.int64)\nz = np.where(condition, x, y) # expected output [[1, 8], [3, 4]]\nexpect(node, inputs=[condition, x, y], outputs=[z],\n name='test_where_long_example')","summary":"long"},{"code":"node = onnx.helper.make_node(\n 'Where',\n inputs=['condition', 'x', 'y'],\n outputs=['z'],\n)\n\ncondition = np.array([[1, 0], [1, 1]], dtype=np.bool)\nx = np.array([[1, 2], [3, 4]], dtype=np.float32)\ny = np.array([[9, 8], [7, 6]], dtype=np.float32)\nz = np.where(condition, x, y) # expected output [[1, 8], [3, 4]]\nexpect(node, inputs=[condition, x, y], outputs=[z],\n name='test_where_example')","summary":"where"}],"inputs":[{"description":"When True (nonzero), yield X, otherwise yield Y","name":"condition","type":"B"},{"description":"values selected at indices where condition is True","name":"X","type":"T"},{"description":"values selected at indices where condition is False","name":"Y","type":"T"}],"max_input":3,"max_output":1,"min_input":3,"min_output":1,"outputs":[{"description":"Tensor of shape equal to the broadcasted shape of condition, X, and Y.","name":"output","type":"T"}],"since_version":9,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrain to boolean tensors.","type_param_str":"B"},{"allowed_type_strs":["tensor(uint8)","tensor(uint16)","tensor(uint32)","tensor(uint64)","tensor(int8)","tensor(int16)","tensor(int32)","tensor(int64)","tensor(float16)","tensor(float)","tensor(double)","tensor(string)","tensor(bool)","tensor(complex64)","tensor(complex128)"],"description":"Constrain input and output types to all tensor types.","type_param_str":"T"}]}},{"name":"Xor","schema":{"attributes":[{"description":"If set, defines the broadcast dimensions.","name":"axis","required":false,"type":"int64"},{"description":"Enable broadcasting","name":"broadcast","required":false,"type":"int64"}],"category":"Logic","description":"Returns the tensor resulted from performing the `xor` logical operation\nelementwise on the input tensors `A` and `B`.\n\nIf broadcasting is enabled, the right-hand-side argument will be broadcasted\nto match the shape of left-hand-side argument. See the doc of `Add` for a\ndetailed description of the broadcasting rules.\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor4d')","summary":"xor"},{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v4d')","summary":"xor_broadcast"}],"inputs":[{"description":"Left input tensor for the logical operator.","name":"A","type":"T"},{"description":"Right input tensor for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"Xor","schema":{"category":"Logic","description":"Returns the tensor resulted from performing the `xor` logical operation\nelementwise on the input tensors `A` and `B` (with Numpy-style broadcasting support).\n\nThis operator supports **multidirectional (i.e., Numpy-style) broadcasting**; for more details please check [the doc](https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md).\n","domain":"ai.onnx","examples":[{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 2d\nx = (np.random.randn(3, 4) > 0).astype(np.bool)\ny = (np.random.randn(3, 4) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor2d')\n\n# 3d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor3d')\n\n# 4d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor4d')","summary":"xor"},{"code":"node = onnx.helper.make_node(\n 'Xor',\n inputs=['x', 'y'],\n outputs=['xor'],\n)\n\n# 3d vs 1d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v1d')\n\n# 3d vs 2d\nx = (np.random.randn(3, 4, 5) > 0).astype(np.bool)\ny = (np.random.randn(4, 5) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast3v2d')\n\n# 4d vs 2d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v2d')\n\n# 4d vs 3d\nx = (np.random.randn(3, 4, 5, 6) > 0).astype(np.bool)\ny = (np.random.randn(4, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v3d')\n\n# 4d vs 4d\nx = (np.random.randn(1, 4, 1, 6) > 0).astype(np.bool)\ny = (np.random.randn(3, 1, 5, 6) > 0).astype(np.bool)\nz = np.logical_xor(x, y)\nexpect(node, inputs=[x, y], outputs=[z],\n name='test_xor_bcast4v4d')","summary":"xor_broadcast"}],"inputs":[{"description":"First input operand for the logical operator.","name":"A","type":"T"},{"description":"Second input operand for the logical operator.","name":"B","type":"T"}],"max_input":2,"max_output":1,"min_input":2,"min_output":1,"outputs":[{"description":"Result tensor.","name":"C","type":"T1"}],"since_version":7,"support_level":"common","type_constraints":[{"allowed_type_strs":["tensor(bool)"],"description":"Constrains input to boolean tensor.","type_param_str":"T"},{"allowed_type_strs":["tensor(bool)"],"description":"Constrains output to boolean tensor.","type_param_str":"T1"}]}},{"name":"ZipMap","schema":{"attributes":[{"description":"The keys when using int keys.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_int64s","required":false,"type":"int64[]"},{"description":"The keys when using string keys.
    One and only one of the 'classlabels_*' attributes must be defined.","name":"classlabels_strings","required":false,"type":"string[]"}],"description":"Creates a map from the input and the attributes.
    \n The values are provided by the input tensor, while the keys are specified by the attributes.\n Must provide keys in either classlabels_strings or classlabels_int64s (but not both).
    \n The columns of the tensor correspond one-by-one to the keys specified by the attributes. There must be as many columns as keys.
    \n","domain":"ai.onnx.ml","inputs":[{"description":"The input values","name":"X","type":"tensor(float)"}],"max_input":1,"max_output":1,"min_input":1,"min_output":1,"outputs":[{"description":"The output map","name":"Z","type":"T"}],"since_version":1,"support_level":"common","type_constraints":[{"allowed_type_strs":["seq(map(string, float))","seq(map(int64, float))"],"description":"The output will be a sequence of string or integer maps to float.","type_param_str":"T"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..04388872ab836940bd9b29fca9be599296cf3d41 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("onnx");$root.onnx={},$root.onnx.Version={_START_VERSION:0,IR_VERSION_2017_10_10:1,IR_VERSION_2017_10_30:2,IR_VERSION_2017_11_3:3,IR_VERSION_2019_1_22:4,IR_VERSION_2019_3_18:5,IR_VERSION_2019_9_19:6,IR_VERSION:7},$root.onnx.AttributeProto=class{constructor(){this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparse_tensors=[]}static decode(o,t){const e=new $root.onnx.AttributeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 21:e.ref_attr_name=o.string();break;case 13:e.doc_string=o.string();break;case 20:e.type=o.int32();break;case 2:e.f=o.float();break;case 3:e.i=o.int64();break;case 4:e.s=o.bytes();break;case 5:e.t=$root.onnx.TensorProto.decode(o,o.uint32());break;case 6:e.g=$root.onnx.GraphProto.decode(o,o.uint32());break;case 22:e.sparse_tensor=$root.onnx.SparseTensorProto.decode(o,o.uint32());break;case 7:e.floats=o.floats(e.floats,t);break;case 8:e.ints=o.array(e.ints,(()=>o.int64()),t);break;case 9:e.strings.push(o.bytes());break;case 10:e.tensors.push($root.onnx.TensorProto.decode(o,o.uint32()));break;case 11:e.graphs.push($root.onnx.GraphProto.decode(o,o.uint32()));break;case 23:e.sparse_tensors.push($root.onnx.SparseTensorProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.AttributeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"ref_attr_name":t.ref_attr_name=o.string();break;case"doc_string":t.doc_string=o.string();break;case"type":t.type=o.enum($root.onnx.AttributeProto.AttributeType);break;case"f":t.f=o.float();break;case"i":t.i=o.integer();break;case"s":t.s=o.bytes();break;case"t":t.t=$root.onnx.TensorProto.decodeText(o,!0);break;case"g":t.g=$root.onnx.GraphProto.decodeText(o,!0);break;case"sparse_tensor":t.sparse_tensor=$root.onnx.SparseTensorProto.decodeText(o,!0);break;case"floats":o.array(t.floats,(()=>o.float()));break;case"ints":o.array(t.ints,(()=>o.integer()));break;case"strings":o.array(t.strings,(()=>o.bytes()));break;case"tensors":t.tensors.push($root.onnx.TensorProto.decodeText(o,!0));break;case"graphs":t.graphs.push($root.onnx.GraphProto.decodeText(o,!0));break;case"sparse_tensors":t.sparse_tensors.push($root.onnx.SparseTensorProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.AttributeProto.prototype.name="",$root.onnx.AttributeProto.prototype.ref_attr_name="",$root.onnx.AttributeProto.prototype.doc_string="",$root.onnx.AttributeProto.prototype.type=0,$root.onnx.AttributeProto.prototype.f=0,$root.onnx.AttributeProto.prototype.i=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.AttributeProto.prototype.s=new Uint8Array([]),$root.onnx.AttributeProto.prototype.t=null,$root.onnx.AttributeProto.prototype.g=null,$root.onnx.AttributeProto.prototype.sparse_tensor=null,$root.onnx.AttributeProto.AttributeType={UNDEFINED:0,FLOAT:1,INT:2,STRING:3,TENSOR:4,GRAPH:5,SPARSE_TENSOR:11,FLOATS:6,INTS:7,STRINGS:8,TENSORS:9,GRAPHS:10,SPARSE_TENSORS:12},$root.onnx.ValueInfoProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.ValueInfoProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 2:e.type=$root.onnx.TypeProto.decode(o,o.uint32());break;case 3:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.ValueInfoProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"type":t.type=$root.onnx.TypeProto.decodeText(o,!0);break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.ValueInfoProto.prototype.name="",$root.onnx.ValueInfoProto.prototype.type=null,$root.onnx.ValueInfoProto.prototype.doc_string="",$root.onnx.NodeProto=class{constructor(){this.input=[],this.output=[],this.attribute=[]}static decode(o,t){const e=new $root.onnx.NodeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.input.push(o.string());break;case 2:e.output.push(o.string());break;case 3:e.name=o.string();break;case 4:e.op_type=o.string();break;case 7:e.domain=o.string();break;case 5:e.attribute.push($root.onnx.AttributeProto.decode(o,o.uint32()));break;case 6:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.NodeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"input":o.array(t.input,(()=>o.string()));break;case"output":o.array(t.output,(()=>o.string()));break;case"name":t.name=o.string();break;case"op_type":t.op_type=o.string();break;case"domain":t.domain=o.string();break;case"attribute":t.attribute.push($root.onnx.AttributeProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.NodeProto.prototype.name="",$root.onnx.NodeProto.prototype.op_type="",$root.onnx.NodeProto.prototype.domain="",$root.onnx.NodeProto.prototype.doc_string="",$root.onnx.TrainingInfoProto=class{constructor(){this.initialization_binding=[],this.update_binding=[]}static decode(o,t){const e=new $root.onnx.TrainingInfoProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.initialization=$root.onnx.GraphProto.decode(o,o.uint32());break;case 2:e.algorithm=$root.onnx.GraphProto.decode(o,o.uint32());break;case 3:e.initialization_binding.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 4:e.update_binding.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TrainingInfoProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"initialization":t.initialization=$root.onnx.GraphProto.decodeText(o,!0);break;case"algorithm":t.algorithm=$root.onnx.GraphProto.decodeText(o,!0);break;case"initialization_binding":t.initialization_binding.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"update_binding":t.update_binding.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TrainingInfoProto.prototype.initialization=null,$root.onnx.TrainingInfoProto.prototype.algorithm=null,$root.onnx.ModelProto=class{constructor(){this.opset_import=[],this.metadata_props=[],this.training_info=[]}static decode(o,t){const e=new $root.onnx.ModelProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.ir_version=o.int64();break;case 8:e.opset_import.push($root.onnx.OperatorSetIdProto.decode(o,o.uint32()));break;case 2:e.producer_name=o.string();break;case 3:e.producer_version=o.string();break;case 4:e.domain=o.string();break;case 5:e.model_version=o.int64();break;case 6:e.doc_string=o.string();break;case 7:e.graph=$root.onnx.GraphProto.decode(o,o.uint32());break;case 14:e.metadata_props.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 20:e.training_info.push($root.onnx.TrainingInfoProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.ModelProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"ir_version":t.ir_version=o.integer();break;case"opset_import":t.opset_import.push($root.onnx.OperatorSetIdProto.decodeText(o,!0));break;case"producer_name":t.producer_name=o.string();break;case"producer_version":t.producer_version=o.string();break;case"domain":t.domain=o.string();break;case"model_version":t.model_version=o.integer();break;case"doc_string":t.doc_string=o.string();break;case"graph":t.graph=$root.onnx.GraphProto.decodeText(o,!0);break;case"metadata_props":t.metadata_props.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"training_info":t.training_info.push($root.onnx.TrainingInfoProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.ModelProto.prototype.ir_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.ModelProto.prototype.producer_name="",$root.onnx.ModelProto.prototype.producer_version="",$root.onnx.ModelProto.prototype.domain="",$root.onnx.ModelProto.prototype.model_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.ModelProto.prototype.doc_string="",$root.onnx.ModelProto.prototype.graph=null,$root.onnx.StringStringEntryProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.StringStringEntryProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.key=o.string();break;case 2:e.value=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.StringStringEntryProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"key":t.key=o.string();break;case"value":t.value=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.StringStringEntryProto.prototype.key="",$root.onnx.StringStringEntryProto.prototype.value="",$root.onnx.TensorAnnotation=class{constructor(){this.quant_parameter_tensor_names=[]}static decode(o,t){const e=new $root.onnx.TensorAnnotation,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.tensor_name=o.string();break;case 2:e.quant_parameter_tensor_names.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorAnnotation;for(o.start();!o.end();){const e=o.tag();switch(e){case"tensor_name":t.tensor_name=o.string();break;case"quant_parameter_tensor_names":t.quant_parameter_tensor_names.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TensorAnnotation.prototype.tensor_name="",$root.onnx.GraphProto=class{constructor(){this.node=[],this.initializer=[],this.sparse_initializer=[],this.input=[],this.output=[],this.value_info=[],this.quantization_annotation=[]}static decode(o,t){const e=new $root.onnx.GraphProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.node.push($root.onnx.NodeProto.decode(o,o.uint32()));break;case 2:e.name=o.string();break;case 5:e.initializer.push($root.onnx.TensorProto.decode(o,o.uint32()));break;case 15:e.sparse_initializer.push($root.onnx.SparseTensorProto.decode(o,o.uint32()));break;case 10:e.doc_string=o.string();break;case 11:e.input.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 12:e.output.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 13:e.value_info.push($root.onnx.ValueInfoProto.decode(o,o.uint32()));break;case 14:e.quantization_annotation.push($root.onnx.TensorAnnotation.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.GraphProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"node":t.node.push($root.onnx.NodeProto.decodeText(o,!0));break;case"name":t.name=o.string();break;case"initializer":t.initializer.push($root.onnx.TensorProto.decodeText(o,!0));break;case"sparse_initializer":t.sparse_initializer.push($root.onnx.SparseTensorProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;case"input":t.input.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"output":t.output.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"value_info":t.value_info.push($root.onnx.ValueInfoProto.decodeText(o,!0));break;case"quantization_annotation":t.quantization_annotation.push($root.onnx.TensorAnnotation.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.GraphProto.prototype.name="",$root.onnx.GraphProto.prototype.doc_string="",$root.onnx.TensorProto=class{constructor(){this.dims=[],this.float_data=[],this.int32_data=[],this.string_data=[],this.int64_data=[],this.external_data=[],this.double_data=[],this.uint64_data=[]}static decode(o,t){const e=new $root.onnx.TensorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dims=o.array(e.dims,(()=>o.int64()),t);break;case 2:e.data_type=o.int32();break;case 3:e.segment=$root.onnx.TensorProto.Segment.decode(o,o.uint32());break;case 4:e.float_data=o.floats(e.float_data,t);break;case 5:e.int32_data=o.array(e.int32_data,(()=>o.int32()),t);break;case 6:e.string_data.push(o.bytes());break;case 7:e.int64_data=o.array(e.int64_data,(()=>o.int64()),t);break;case 8:e.name=o.string();break;case 12:e.doc_string=o.string();break;case 9:e.raw_data=o.bytes();break;case 13:e.external_data.push($root.onnx.StringStringEntryProto.decode(o,o.uint32()));break;case 14:e.data_location=o.int32();break;case 10:e.double_data=o.doubles(e.double_data,t);break;case 11:e.uint64_data=o.array(e.uint64_data,(()=>o.uint64()),t);break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"dims":o.array(t.dims,(()=>o.integer()));break;case"data_type":t.data_type=o.integer();break;case"segment":t.segment=$root.onnx.TensorProto.Segment.decodeText(o,!0);break;case"float_data":o.array(t.float_data,(()=>o.float()));break;case"int32_data":o.array(t.int32_data,(()=>o.integer()));break;case"string_data":o.array(t.string_data,(()=>o.bytes()));break;case"int64_data":o.array(t.int64_data,(()=>o.integer()));break;case"name":t.name=o.string();break;case"doc_string":t.doc_string=o.string();break;case"raw_data":t.raw_data=o.bytes();break;case"external_data":t.external_data.push($root.onnx.StringStringEntryProto.decodeText(o,!0));break;case"data_location":t.data_location=o.enum($root.onnx.TensorProto.DataLocation);break;case"double_data":o.array(t.double_data,(()=>o.float()));break;case"uint64_data":o.array(t.uint64_data,(()=>o.integer()));break;default:o.field(e,t)}}return t}},$root.onnx.TensorProto.prototype.data_type=0,$root.onnx.TensorProto.prototype.segment=null,$root.onnx.TensorProto.prototype.name="",$root.onnx.TensorProto.prototype.doc_string="",$root.onnx.TensorProto.prototype.raw_data=new Uint8Array([]),$root.onnx.TensorProto.prototype.data_location=0,$root.onnx.TensorProto.DataType={UNDEFINED:0,FLOAT:1,UINT8:2,INT8:3,UINT16:4,INT16:5,INT32:6,INT64:7,STRING:8,BOOL:9,FLOAT16:10,DOUBLE:11,UINT32:12,UINT64:13,COMPLEX64:14,COMPLEX128:15,BFLOAT16:16},$root.onnx.TensorProto.Segment=class{constructor(){}static decode(o,t){const e=new $root.onnx.TensorProto.Segment,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.begin=o.int64();break;case 2:e.end=o.int64();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorProto.Segment;for(o.start();!o.end();){const e=o.tag();switch(e){case"begin":t.begin=o.integer();break;case"end":t.end=o.integer();break;default:o.field(e,t)}}return t}},$root.onnx.TensorProto.Segment.prototype.begin=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.TensorProto.Segment.prototype.end=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.TensorProto.DataLocation={DEFAULT:0,EXTERNAL:1},$root.onnx.SparseTensorProto=class{constructor(){this.dims=[]}static decode(o,t){const e=new $root.onnx.SparseTensorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.values=$root.onnx.TensorProto.decode(o,o.uint32());break;case 2:e.indices=$root.onnx.TensorProto.decode(o,o.uint32());break;case 3:e.dims=o.array(e.dims,(()=>o.int64()),t);break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.SparseTensorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"values":t.values=$root.onnx.TensorProto.decodeText(o,!0);break;case"indices":t.indices=$root.onnx.TensorProto.decodeText(o,!0);break;case"dims":o.array(t.dims,(()=>o.integer()));break;default:o.field(e,t)}}return t}},$root.onnx.SparseTensorProto.prototype.values=null,$root.onnx.SparseTensorProto.prototype.indices=null,$root.onnx.TensorShapeProto=class{constructor(){this.dim=[]}static decode(o,t){const e=new $root.onnx.TensorShapeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dim.push($root.onnx.TensorShapeProto.Dimension.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorShapeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"dim":t.dim.push($root.onnx.TensorShapeProto.Dimension.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.TensorShapeProto.Dimension=class{constructor(){}get value(){return $root.onnx.TensorShapeProto.Dimension.valueSet=$root.onnx.TensorShapeProto.Dimension.valueSet||new Set(["dim_value","dim_param"]),Object.keys(this).find((o=>$root.onnx.TensorShapeProto.Dimension.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.onnx.TensorShapeProto.Dimension,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.dim_value=o.int64();break;case 2:e.dim_param=o.string();break;case 3:e.denotation=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TensorShapeProto.Dimension;for(o.start();!o.end();){const e=o.tag();switch(e){case"dim_value":t.dim_value=o.integer();break;case"dim_param":t.dim_param=o.string();break;case"denotation":t.denotation=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TensorShapeProto.Dimension.prototype.denotation="",$root.onnx.TypeProto=class{constructor(){}get value(){return $root.onnx.TypeProto.valueSet=$root.onnx.TypeProto.valueSet||new Set(["tensor_type","sequence_type","map_type","sparse_tensor_type","opaque_type"]),Object.keys(this).find((o=>$root.onnx.TypeProto.valueSet.has(o)&&null!=this[o]))}static decode(o,t){const e=new $root.onnx.TypeProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.tensor_type=$root.onnx.TypeProto.Tensor.decode(o,o.uint32());break;case 4:e.sequence_type=$root.onnx.TypeProto.Sequence.decode(o,o.uint32());break;case 5:e.map_type=$root.onnx.TypeProto.Map.decode(o,o.uint32());break;case 8:e.sparse_tensor_type=$root.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break;case 7:e.opaque_type=$root.onnx.TypeProto.Opaque.decode(o,o.uint32());break;case 6:e.denotation=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"tensor_type":t.tensor_type=$root.onnx.TypeProto.Tensor.decodeText(o,!0);break;case"sequence_type":t.sequence_type=$root.onnx.TypeProto.Sequence.decodeText(o,!0);break;case"map_type":t.map_type=$root.onnx.TypeProto.Map.decodeText(o,!0);break;case"sparse_tensor_type":t.sparse_tensor_type=$root.onnx.TypeProto.SparseTensor.decodeText(o,!0);break;case"opaque_type":t.opaque_type=$root.onnx.TypeProto.Opaque.decodeText(o,!0);break;case"denotation":t.denotation=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.prototype.denotation="",$root.onnx.TypeProto.Tensor=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Tensor,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=o.int32();break;case 2:e.shape=$root.onnx.TensorShapeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Tensor;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=o.integer();break;case"shape":t.shape=$root.onnx.TensorShapeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Tensor.prototype.elem_type=0,$root.onnx.TypeProto.Tensor.prototype.shape=null,$root.onnx.TypeProto.Sequence=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Sequence,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=$root.onnx.TypeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Sequence;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=$root.onnx.TypeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Sequence.prototype.elem_type=null,$root.onnx.TypeProto.Map=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Map,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.key_type=o.int32();break;case 2:e.value_type=$root.onnx.TypeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Map;for(o.start();!o.end();){const e=o.tag();switch(e){case"key_type":t.key_type=o.integer();break;case"value_type":t.value_type=$root.onnx.TypeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Map.prototype.key_type=0,$root.onnx.TypeProto.Map.prototype.value_type=null,$root.onnx.TypeProto.SparseTensor=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.SparseTensor,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.elem_type=o.int32();break;case 2:e.shape=$root.onnx.TensorShapeProto.decode(o,o.uint32());break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.SparseTensor;for(o.start();!o.end();){const e=o.tag();switch(e){case"elem_type":t.elem_type=o.integer();break;case"shape":t.shape=$root.onnx.TensorShapeProto.decodeText(o,!0);break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.SparseTensor.prototype.elem_type=0,$root.onnx.TypeProto.SparseTensor.prototype.shape=null,$root.onnx.TypeProto.Opaque=class{constructor(){}static decode(o,t){const e=new $root.onnx.TypeProto.Opaque,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.domain=o.string();break;case 2:e.name=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.TypeProto.Opaque;for(o.start();!o.end();){const e=o.tag();switch(e){case"domain":t.domain=o.string();break;case"name":t.name=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.TypeProto.Opaque.prototype.domain="",$root.onnx.TypeProto.Opaque.prototype.name="",$root.onnx.OperatorSetIdProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.OperatorSetIdProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.domain=o.string();break;case 2:e.version=o.int64();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorSetIdProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"domain":t.domain=o.string();break;case"version":t.version=o.integer();break;default:o.field(e,t)}}return t}},$root.onnx.OperatorSetIdProto.prototype.domain="",$root.onnx.OperatorSetIdProto.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorStatus={EXPERIMENTAL:0,STABLE:1},$root.onnx.FunctionProto=class{constructor(){this.input=[],this.output=[],this.attribute=[],this.node=[],this.opset_import=[]}static decode(o,t){const e=new $root.onnx.FunctionProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.name=o.string();break;case 2:e.since_version=o.int64();break;case 3:e.status=o.int32();break;case 4:e.input.push(o.string());break;case 5:e.output.push(o.string());break;case 6:e.attribute.push(o.string());break;case 7:e.node.push($root.onnx.NodeProto.decode(o,o.uint32()));break;case 8:e.doc_string=o.string();break;case 9:e.opset_import.push($root.onnx.OperatorSetIdProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.FunctionProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"name":t.name=o.string();break;case"since_version":t.since_version=o.integer();break;case"status":t.status=o.enum($root.onnx.OperatorStatus);break;case"input":o.array(t.input,(()=>o.string()));break;case"output":o.array(t.output,(()=>o.string()));break;case"attribute":o.array(t.attribute,(()=>o.string()));break;case"node":t.node.push($root.onnx.NodeProto.decodeText(o,!0));break;case"doc_string":t.doc_string=o.string();break;case"opset_import":t.opset_import.push($root.onnx.OperatorSetIdProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.FunctionProto.prototype.name="",$root.onnx.FunctionProto.prototype.since_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.FunctionProto.prototype.status=0,$root.onnx.FunctionProto.prototype.doc_string="",$root.onnx.OperatorProto=class{constructor(){}static decode(o,t){const e=new $root.onnx.OperatorProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.op_type=o.string();break;case 2:e.since_version=o.int64();break;case 3:e.status=o.int32();break;case 10:e.doc_string=o.string();break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"op_type":t.op_type=o.string();break;case"since_version":t.since_version=o.integer();break;case"status":t.status=o.enum($root.onnx.OperatorStatus);break;case"doc_string":t.doc_string=o.string();break;default:o.field(e,t)}}return t}},$root.onnx.OperatorProto.prototype.op_type="",$root.onnx.OperatorProto.prototype.since_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorProto.prototype.status=0,$root.onnx.OperatorProto.prototype.doc_string="",$root.onnx.OperatorSetProto=class{constructor(){this.operator=[],this.functions=[]}static decode(o,t){const e=new $root.onnx.OperatorSetProto,r=o.next(t);for(;o.end(r);){const t=o.uint32();switch(t>>>3){case 1:e.magic=o.string();break;case 2:e.ir_version=o.int64();break;case 3:e.ir_version_prerelease=o.string();break;case 7:e.ir_build_metadata=o.string();break;case 4:e.domain=o.string();break;case 5:e.opset_version=o.int64();break;case 6:e.doc_string=o.string();break;case 8:e.operator.push($root.onnx.OperatorProto.decode(o,o.uint32()));break;case 9:e.functions.push($root.onnx.FunctionProto.decode(o,o.uint32()));break;default:o.skipType(7&t)}}return e}static decodeText(o){const t=new $root.onnx.OperatorSetProto;for(o.start();!o.end();){const e=o.tag();switch(e){case"magic":t.magic=o.string();break;case"ir_version":t.ir_version=o.integer();break;case"ir_version_prerelease":t.ir_version_prerelease=o.string();break;case"ir_build_metadata":t.ir_build_metadata=o.string();break;case"domain":t.domain=o.string();break;case"opset_version":t.opset_version=o.integer();break;case"doc_string":t.doc_string=o.string();break;case"operator":t.operator.push($root.onnx.OperatorProto.decodeText(o,!0));break;case"functions":t.functions.push($root.onnx.FunctionProto.decodeText(o,!0));break;default:o.field(e,t)}}return t}},$root.onnx.OperatorSetProto.prototype.magic="",$root.onnx.OperatorSetProto.prototype.ir_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorSetProto.prototype.ir_version_prerelease="",$root.onnx.OperatorSetProto.prototype.ir_build_metadata="",$root.onnx.OperatorSetProto.prototype.domain="",$root.onnx.OperatorSetProto.prototype.opset_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.onnx.OperatorSetProto.prototype.doc_string=""; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx.js new file mode 100644 index 0000000000000000000000000000000000000000..88f7000b8f8444922b13a5c3c58363c1a7f6937e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/onnx.js @@ -0,0 +1 @@ +var onnx=onnx||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");onnx.ModelFactory=class{match(t){const e=t.identifier,n=e.split(".").pop().toLowerCase();if("onnx"==n)return!0;if("pb"==n){if(e.endsWith("saved_model.pb"))return!1;if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb"))return!1;const n=t.tags("pb");return!(0===n.size||n.size>0&&n.has(1)&&0===n.get(1)&&n.has(2)&&0===n.get(2)&&n.has(9)&&2===n.get(9)||n.size>0&&Array.from(n.values()).some((t=>5===t))||n.has(1)&&0!=n.get(1)||n.has(2)&&2!=n.get(2)||n.has(3)&&2!=n.get(3)||n.has(4)&&2!=n.get(4)||n.has(5)&&0!=n.get(5)||n.has(6)&&2!=n.get(6)||n.has(8)&&2!=n.get(8)||n.has(14)&&2!=n.get(14)||!n.has(7)||2!=n.get(7))}if("pbtxt"===n||"prototxt"===n||"model"===n){if(e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const o=t.tags("pbtxt");if(o.has("ir_version"))return!0;if(o.has("graph")&&"model"!==n)return!0}return!1}open(t,e){return e.require("./onnx-proto").then((()=>{let n=null;const o=t.identifier,a=o.split(".").pop().toLowerCase();if("pbtxt"==a||"prototxt"==a)try{onnx.proto=protobuf.get("onnx").onnx;const e=protobuf.TextReader.create(t.text);n=onnx.proto.ModelProto.decodeText(e)}catch(t){throw new onnx.Error("File text format is not onnx.ModelProto ("+t.message+") in '"+o+"'.")}else try{onnx.proto=protobuf.get("onnx").onnx;const e=protobuf.Reader.create(t.buffer);n=onnx.proto.ModelProto.decode(e)}catch(t){throw new onnx.Error("File format is not onnx.ModelProto ("+t.message+") in '"+o+"'.")}return onnx.Metadata.open(e).then((t=>{try{return new onnx.Model(t,n)}catch(t){e.exception(t,!1);const n=t&&t.message?t.message:t.toString();throw new onnx.Error(n.replace(/\.$/,"")+" in '"+o+"'.")}}))}))}},onnx.Model=class{constructor(t,e){this._graphs=[],this._irVersion=e.ir_version,this._producerName=e.producer_name,this._producerVersion=e.producer_version,this._domain=e.domain,this._modelVersion=e.model_version,this._description=e.doc_string,this._metadata=[],this._imports=null;const n={};if(e.opset_import&&e.opset_import.length>0){const t=[];for(const o of e.opset_import){let e=o.domain||"ai.onnx";const a=e+" v"+o.version;t.includes(a)||t.push(a),e="ai.onnx"==e?"":e,(!n[e]||n[e]>o.version)&&(n[e]=o.version)}this._imports=t.join(", ")}0==Object.keys(n).length&&(n[""]=1,n["ai.onnx.ml"]=1);let o="";if(e.metadata_props){const t={};for(const n of e.metadata_props)switch(n.key){case"author":this._author=n.value;break;case"company":this._company=n.value;break;case"converted_from":this._converted_from=n.value;break;case"license":this._license=n.value;break;case"license_url":this._licenseUrl=n.value;break;case"Image.BitmapPixelFormat":case"Image.ColorSpaceGamma":case"Image.NominalPixelRange":t[n.key]=n.value;break;default:this._metadata.push({name:n.key,value:n.value})}o=[t["Image.BitmapPixelFormat"],t["Image.ColorSpaceGamma"],t["Image.NominalPixelRange"]].filter((t=>t))}if(this._graphs=[],e&&e.graph){const a=new onnx.GraphMetadata(t,n),r=new onnx.Graph(a,o,e.graph);this._graphs.push(r)}}get format(){return"ONNX"+(this._irVersion?" v"+this._irVersion.toString():"")}get imports(){return this._imports}get producer(){const t=[];return this._producerName&&t.push(this._producerName),this._producerVersion&&this._producerVersion.length>0&&t.push(this._producerVersion),t.length>0?t.join(" "):null}get domain(){return this._domain||null}get description(){return this._description||null}get author(){return this._author||null}get company(){return this._company||null}get source(){return this._converted_from||null}get license(){const t=[];return this._license&&this._license.length>0&&t.push(this._license),this._licenseUrl&&this._licenseUrl.length>0&&t.push(""+this._licenseUrl+""),t.length>0?t:null}get metadata(){return this._metadata}get graphs(){return this._graphs}},onnx.Graph=class{constructor(t,e,n){if(this._node="",this._description="",this._nodes=[],this._inputs=[],this._outputs=[],n){this._name=n.name||null,this._description=n.doc_string||"";const o=new Map;for(const t of n.initializer)o.set(t.name,new onnx.Tensor(t,"Initializer"));const a=[],r=new Map,s=new Map;for(const t of n.node){for(const e of t.input)r.set(e,r.has(e)?r.get(e)+1:1);for(const e of t.output)s.set(e,r.has(e)?r.get(e)+1:1)}for(const t of n.input)r.delete(t);for(const t of n.output)s.delete(t);for(const t of n.node){let e=!1;if("Constant"==t.op_type&&0==t.input.length&&1==t.output.length){const n=t.output[0];if(r.has(n)&&1==r.get(n)&&s.has(n)&&1==s.get(n)&&1==t.attribute.length){const a=t.attribute[0];a&&"value"==a.name&&a.t&&(o.set(n,new onnx.Tensor(a.t,"Constant")),e=!0)}}e||a.push(t)}const i=new Map;for(const t of n.quantization_annotation){const e={};for(const n of t.quant_parameter_tensor_names)e[n.key]=n.value;i.set(t.tensor_name,e)}const p=new Map,h=(t,e,n,o,a)=>{if(!p.has(t)){e=o?o.type:e?onnx.Utility.formatType(e,a):null;const r=i.get(t);p.set(t,new onnx.Argument(t,e,o,r,n))}return p.get(t)};for(const t of n.value_info)h(t.name,t.type,t.doc_string,o.get(t.name),e);for(const t of n.input){const n=h(t.name,t.type,t.doc_string,o.get(t.name),e);o.has(t.name)||this._inputs.push(new onnx.Parameter(t.name,[n]))}for(const t of n.output){const n=h(t.name,t.type,t.doc_string,o.get(t.name),e);this._outputs.push(new onnx.Parameter(t.name,[n]))}for(const n of a){let a=[];const r=t.type(n.op_type);if(n.input&&n.input.length>0){let t=0;if(r&&r.inputs){for(const s of r.inputs)if(th(t,null,null,o.get(t),e)));t+=r,a.push(new onnx.Parameter(s.name,i))}}else a=a.concat(n.input.slice(t).map(((n,o)=>new onnx.Parameter((t+o).toString(),[h(n,null,null,null,e)]))))}let s=[];if(n.output&&n.output.length>0){let t=0;if(r&&r.outputs){for(const o of r.outputs)if(th(t,null,null,null,e)));t+=a,s.push(new onnx.Parameter(o.name,r))}}else s=s.concat(n.output.slice(t).map(((n,o)=>new onnx.Parameter((t+o).toString(),[h(n,null,null,null,e)]))))}this._nodes.push(new onnx.Node(t,e,n.op_type,n.domain,n.name,n.doc_string,n.attribute,a,s))}}}get name(){return this._name}get description(){return this._description}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}toString(){return"graph("+this.name+")"}},onnx.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},onnx.Argument=class{constructor(t,e,n,o,a){if("string"!=typeof t)throw new onnx.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null,this._annotation=o,this._description=a||""}get name(){return this._name}get type(){return this._type}get description(){return this._description}get quantization(){return this._annotation?Object.keys(this._annotation).map((t=>t+": "+this._annotation[t])).join(", "):null}get initializer(){return this._initializer}},onnx.Node=class{constructor(t,e,n,o,a,r,s,i,p){this._metadata=t,this._type=n,this._domain=o||"",this._name=a||"",this._description=r||"",this._inputs=i,this._outputs=p,this._attributes=(s||[]).map((t=>new onnx.Attribute(this._metadata,e,this.type,t)))}get type(){return this._type}get name(){return this._name}get description(){return this._description}get metadata(){return this._metadata.type(this._type)}get domain(){return this._domain}get group(){return null}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},onnx.Attribute=class{constructor(t,e,n,o){this._name=o.name,this._description=o.doc_string||"",this._type=null,this._value=null;const a=t.attribute(n,o.name);if(!this._type)if(Object.prototype.hasOwnProperty.call(o,"type")){if(!onnx.Attribute._attributeTypeMap){const t={};t[onnx.proto.AttributeProto.AttributeType.UNDEFINED]="undefined",t[onnx.proto.AttributeProto.AttributeType.FLOAT]="float32",t[onnx.proto.AttributeProto.AttributeType.INT]="int64",t[onnx.proto.AttributeProto.AttributeType.STRING]="string",t[onnx.proto.AttributeProto.AttributeType.TENSOR]="tensor",t[onnx.proto.AttributeProto.AttributeType.GRAPH]="graph",t[onnx.proto.AttributeProto.AttributeType.FLOATS]="float32",t[onnx.proto.AttributeProto.AttributeType.INTS]="int64[]",t[onnx.proto.AttributeProto.AttributeType.STRINGS]="string[]",t[onnx.proto.AttributeProto.AttributeType.TENSORS]="tensor[]",t[onnx.proto.AttributeProto.AttributeType.GRAPHS]="graph[]",onnx.Attribute._attributeTypeMap=t}const t=onnx.Attribute._attributeTypeMap[o.type];this._type=t||onnx.Attribute._attributeTypeMap[onnx.proto.AttributeProto.AttributeType.UNDEFINED]}else a&&a.type&&(this._type=a.type);if(o.ints&&o.ints.length>0)this._value=o.ints;else if(o.floats&&o.floats.length>0)this._value=o.floats;else if(o.strings&&o.strings.length>0)this._value=o.strings.map((t=>onnx.Utility.decodeText(t)));else if(o.graphs&&o.graphs.length>0)this._value=o.graphs.map((n=>new onnx.Graph(t,e,n))),this._type="graph[]";else if(o.s&&o.s.length>0)switch(n){case"Int8GivenTensorFill":this._value=Array.from(o.s);break;default:this._value=onnx.Utility.decodeText(o.s)}else Object.prototype.hasOwnProperty.call(o,"f")?this._value=o.f:Object.prototype.hasOwnProperty.call(o,"i")?this._value=o.i:Object.prototype.hasOwnProperty.call(o,"t")?(this._type="tensor",this._value=new onnx.Tensor(o.t).value):Object.prototype.hasOwnProperty.call(o,"g")&&(this._type="graph",this._value=new onnx.Graph(t,e,o.g));a&&Object.prototype.hasOwnProperty.call(a,"default")&&a.default&&this._value==a.default&&(this._visible=!1)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get description(){return this._description}get visible(){return 0!=this._visible}},onnx.Tensor=class{constructor(t,e){if(this._tensor=t,this._name=t.name||"",this._kind=e||null,this._type=new onnx.TensorType(this._tensor.data_type,new onnx.TensorShape(this._tensor.dims.map((t=>t))),null),this._tensor.data_type==onnx.proto.TensorProto.DataType.FLOAT16&&this._tensor.int32_data&&this._tensor.int32_data.length>0){const t=new Uint8Array(this._tensor.int32_data.length<<1),e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=this._tensor.int32_data;for(let t=0;t0?t.data=this._tensor.float_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.DOUBLE:this._tensor.double_data&&this._tensor.double_data.length>0?t.data=this._tensor.double_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.FLOAT16:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.BOOL:case onnx.proto.TensorProto.DataType.INT8:case onnx.proto.TensorProto.DataType.UINT8:case onnx.proto.TensorProto.DataType.INT16:case onnx.proto.TensorProto.DataType.UINT16:case onnx.proto.TensorProto.DataType.INT32:this._tensor.int32_data&&this._tensor.int32_data.length>0?t.data=this._tensor.int32_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.UINT32:this._tensor.uint64_data&&this._tensor.uint64_data.length>0?t.data=this._tensor.uint64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.INT64:this._tensor.int64_data&&this._tensor.int64_data.length>0?t.data=this._tensor.int64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;case onnx.proto.TensorProto.DataType.UINT64:this._tensor.uint64_data&&this._tensor.uint64_data.length>0?t.data=this._tensor.uint64_data:this._tensor.raw_data&&this._tensor.raw_data.length>0?t.rawData=new DataView(this._tensor.raw_data.buffer,this._tensor.raw_data.byteOffset,this._tensor.raw_data.byteLength):t.state="Tensor data is empty.";break;default:t.state="Tensor data type is not implemented."}return t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],o=[],a=n[e];if(e==n.length-1)for(let e=0;et.limit)return o.push("..."),o;if(t.data){let e=t.data[t.index++];switch(this._tensor.data_type){case onnx.proto.TensorProto.DataType.BOOL:e=0!==e}o.push(e),t.count++}else if(t.rawData)switch(this._tensor.data_type){case onnx.proto.TensorProto.DataType.FLOAT16:o.push(t.rawData.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.FLOAT:o.push(t.rawData.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.DOUBLE:o.push(t.rawData.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.INT8:o.push(t.rawData.getInt8(t.index,!0)),t.index++,t.count++;break;case onnx.proto.TensorProto.DataType.UINT8:o.push(t.rawData.getUint8(t.index,!0)),t.index++,t.count++;break;case onnx.proto.TensorProto.DataType.INT16:o.push(t.rawData.getInt16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.UINT16:o.push(t.rawData.getUint16(t.index,!0)),t.index+=2,t.count++;break;case onnx.proto.TensorProto.DataType.INT32:o.push(t.rawData.getInt32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.UINT32:o.push(t.rawData.getUint32(t.index,!0)),t.index+=4,t.count++;break;case onnx.proto.TensorProto.DataType.INT64:o.push(new long.Long(t.rawData.getUint32(t.index,!0),t.rawData.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.UINT64:o.push(new long.Long(t.rawData.getUint32(t.index,!0),t.rawData.getUint32(t.index+4,!0),!0)),t.index+=8,t.count++;break;case onnx.proto.TensorProto.DataType.BOOL:o.push(0!==t.rawData.getInt8(t.index,!0)),t.index+=1,t.count++}}else for(let n=0;nt.limit)return o.push("..."),o;o.push(this._decode(t,e+1))}return 0==t.shape.length?o[0]:o}static _stringify(t,e,n){if(Array.isArray(t)){const o=[];o.push(e+"[");const a=t.map((t=>onnx.Tensor._stringify(t,e+n,n)));return a.length>0&&o.push(a.join(",\n")),o.push(e+"]"),o.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},onnx.TensorType=class{constructor(t,e,n){this._dataType=onnx.Utility.formatElementType(t),this._shape=e,this._denotation=n||null}get dataType(){return this._dataType}get shape(){return this._shape}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},onnx.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},onnx.SequenceType=class{constructor(t,e){this._elementType=t,this._denotation=e}get elementType(){return this._elementType}get dennotation(){return this._dennotation}toString(){return"sequence<"+this._elementType.toString()+">"}},onnx.MapType=class{constructor(t,e,n){this._keyType=onnx.Utility.formatElementType(t),this._valueType=e,this._denotation=n}get keyType(){return this._keyType}get valueType(){return this._valueType}get denotation(){return this._denotation}toString(){return"map<"+this._keyType+","+this._valueType.toString()+">"}},onnx.OpaqueType=class{constructor(t,e){this._domain=t,this._name=e}toString(){return"opaque<"+(this._domain?this._domain+".":"")+this._name+">"}},onnx.GraphMetadata=class{constructor(t,e){this._metadata=t,this._imports=e,this._cache=new Map,this._attributeCache=new Map}type(t){return this._cache.has(t)||this._cache.set(t,this._metadata.type(t,this._imports)),this._cache.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},onnx.Metadata=class{static open(t){return onnx.Metadata._metadata?Promise.resolve(onnx.Metadata._metadata):t.request(null,"onnx-metadata.json","utf-8").then((t=>(onnx.Metadata._metadata=new onnx.Metadata(t),onnx.Metadata._metadata))).catch((()=>(onnx.Metadata._metadata=new onnx.Metadata(null),onnx.Metadata._metadata)))}constructor(t){if(this._map={},t){const e=JSON.parse(t);if(e)for(const t of e)if(t.name&&t.schema){const e=t.name;t.schema.name=e,this._map[e]=this._map[e]||[],this._map[e].push(t.schema)}}}type(t,e){let n=null;const o=this._map[t];if(o){let t=-1;for(const a of o){const o=e["ai.onnx"===a.domain?"":a.domain],r=a.since_version;o>=r&&tt.dim_param?t.dim_param:t.dim_value))),new onnx.TensorType(t.tensor_type.elem_type,new onnx.TensorShape(e),n)}case"map_type":return new onnx.MapType(t.map_type.key_type,onnx.Utility.formatType(t.map_type.value_type,e),n);case"sequence_type":return new onnx.SequenceType(onnx.Utility.formatType(t.sequence_type.elem_type,e),n);case"opaque_type":return new onnx.OpaqueType(t.opaque_type.domain,t.opaque_type.name)}return null}},onnx.Error=class extends Error{constructor(t){super(t),this.name="Error loading ONNX model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=onnx.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..24c510288ee20a492493b1c2d73265aa89630d02 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino-metadata.json @@ -0,0 +1 @@ +[{"name":"Convolution","schema":{"attributes":[{"default":[1,null],"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32[]"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":[1,null],"name":"strides","type":"int32[]"},{"default":0,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":0,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":"int32"},{"default":0,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":0,"name":"pad-r","type":"int32"},{"default":0,"name":"pad-b","type":"int32"},{"default":[1,1],"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32[]"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":1,"description":" *output* is a number of output feature maps per whole output (when *group* > 1, *output* still matches the number of output features regardless of *group* value). For example, *output* equals 1 means that there is 1 output feature map in a layer.","name":"output","option":"required","type":"int32","visible":false},{"default":1,"description":" *group* denotes the number of groups to which *output* and *input* should be split. For example, *group* equal 1 means that all the filters are applied to full input (usual convolution), *group* equals 2 means that both *input* and *output* channels are separated into 2 groups and *i-th output* group is connected to *i-th input* group channels. *group* equals number of output feature maps denotes depth-wise separable convolution ([Reference](https://medium.com/towards-data-science/types-of-convolutions-in-deep-learning-717013397f4d#6f51)).","name":"group","option":"required","type":"int32"},{"default":1,"description":" *dilation* denotes the distance in width and height between elements (weights) in the filter. For example, *dilation* equal \"1,1\" means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation* equal \"2,2\" means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation","option":"required","type":"int32"},{"default":1,"name":"dilation-x","type":"int32"},{"default":[1,null],"name":"dilations","type":"int32[]"},{"default":"same_upper","name":"auto_pad"},{"default":[0,null],"name":"pads_begin","type":"int32[]"},{"default":[0,null],"name":"pads_end","type":"int32[]"},{"default":1,"description":" *dilation-y* denotes the distance in height between elements (weights) in the filter. For example, *dilation-y* equal 1 means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation-y* equal 2 means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation-y","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/convolution.html)
    **Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#conv)\n**Parameters**: *Convolution* layer parameters should be specified in the `convolution_data` node, which is a child of the layer node.\n**Weights Layout** Weights layout is GOIYX, which means that *X* is changing the fastest, then *Y*, then *Input*, *Output*, then *Group*.\n**Mathematical Formulation**\n* For the convolutional layer, the number of output features in each dimension is calculated using the formula:\n\\f[\nn_{out} = \\left ( \\frac{n_{in} + 2p - k}{s} \\right ) + 1\n\\f]\n* The receptive field in each layer is calculated using the formulas:\n * Jump in the output feature map:\n \\f[\n j_{out} = j_{in} * s\n \\f]\n * Size of the receptive field of output feature:\n \\f[\n r_{out} = r_{in} + ( k - 1 ) * j_{in}\n \\f]\n * Center position of the receptive field of the first output feature:\n \\f[\n start_{out} = start_{in} + ( \\frac{k - 1}{2} - p ) * j_{in}\n \\f]\n * Output is calculated using the following formula:\n \\f[\n out = \\sum_{i = 0}^{n}w_{i}x_{i} + b\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n \n \n```","inputs":[{"name":"inputs","option":"variadic"},{"description":"*(type: Tensor``)* List of input tensors.","name":"X1, X2, ..."}],"outputs":[{"description":"*(type: Tensor``)* Concatenated tensor.","name":"concat_result"},{"description":"*(type: Tensor``)* The dimensions of the inputs.","name":"split_info"}],"support_level":"default"}},{"name":"BinaryConvolution","schema":{"category":"Layer"}},{"name":"Pooling","schema":{"attributes":[{"default":[1,null],"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32[]"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":[1,null],"name":"strides","type":"int32[]"},{"default":1,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":0,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":"int32"},{"default":0,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":0,"name":"pad-r","type":"int32"},{"default":0,"name":"pad-b","type":"int32"},{"default":[0,null],"name":"pads_begin","type":"int32[]"},{"default":[0,null],"name":"pads_end","type":"int32[]"},{"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32[]"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":"max","description":" *pool-method* is a type of pooling strategy for values.","name":"pool-method","option":"required","type":""},{"default":false,"description":" *exclude-pad* is a type of pooling strategy for values in the padding area. For example, if *exclude-pad* is \"true\", zero-values in the padding are not used.","name":"exclude-pad","option":"required","type":"boolean"},{"default":"ceil","description":" *rounding_type* is a type of rounding to be applied.","name":"rounding-type","option":"required","type":"\n * *ceil*\n * *floor*"}],"category":"Pool","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/pooling.html)\n**Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#pool)\n**Parameters**: Specify pooling layer parameters in the `pooling_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n* For *max pool-method*:\n \\f[\n output_{j} = MAX\\{ x_{0}, ... x_{i}\\}\n \\f]\n* For *avg pool-method*:\n \\f[\n output_{j} = \\frac{\\sum_{i = 0}^{n}x_{i}}{n}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ROIPooling","schema":{"attributes":[{"default":1,"description":" *pooled_h* is a height of the ROI output feature map. For example, *pooled_h* equal 6 means that the height of the output of *ROIpooling* is 6.","name":"pooled_h","option":"required","type":"int32"},{"default":1,"description":" *pooled_w* is a width of the ROI output feature map. For example, *pooled_w* equal 6 means that the width of the output of *ROIpooling* is 6.","name":"pooled_w","option":"required","type":"int32"},{"default":1,"description":" *spatial_scale* is a ratio of the input feature map over the input image size.","name":"spatial_scale","option":"required","type":" positive floating point value"}],"category":"Layer","description":"**Short description**: It is a *pooling layer* with *max* pooling strategy (see *max* option in the *Pooling layer* parameters description). It is used over feature maps of non-uniform sizes and outputs another feature map of a fixed size.\n**Detailed description**: [deepsense.io reference](https://blog.deepsense.ai/region-of-interest-pooling-explained/)\n**Parameters**: Specify *ROIPooling* layer parameters in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\noutput_{j} = MAX\\{ x_{0}, ... x_{i}\\}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"FullyConnected","schema":{"attributes":[{"default":1,"description":" *out-size* is a length of the output vector. For example, *out-size* equal 4096 means that the output vector length is 4096.","name":"out-size","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/innerproduct.html)\n**Detailed description**: [Reference](http://cs231n.github.io/convolutional-networks/#fc)\n**Parameters**: Specify *FullyConnected* layer parameters in the `fc_data` node, which is a child of the layer node.\n**Weights Layout** OI, which means that Input is changing the fastest, then Output.\n**Mathematical Formulation**\n* If previous layer is *FullyConnected*:\n \\f[\n y_{i} = f( z_{i} ) \\quad with \\quad z_{i} = \\sum_{j=1}^{m_{1}^{( l-1 )}}w_{i,j}^{( l )}y_{i}^{ ( l -1 )}\n \\f]\n* Otherwise:\n \\f[\n y_{i} = f( z_{i} ) \\quad with \\quad z_{i}^{ ( l )} = \\sum_{j=1}^{m_{1}^{( l-1 )}}\\sum_{r=1}^{m_{2}^{ ( l-1 )}}\\sum_{s=1}^{m_{3}^{ ( l-1 )}}w_{i,j,r,s}^{ ( l )} ( Y_{i}^{ (l-1) })_{r,s}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n \n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ReLU","schema":{"attributes":[{"default":0,"description":" *negative_slope* is a multiplier, which is used if the unit is not active (that is negative). For example, *negative_slope* equal 0.1 means that an inactive unit value would be multiplied by 0.1 and this is the [Leaky ReLU](https://keras.io/layers/advanced-activations/#leakyrelu). If *negative_slope* is equal to 0, this is the usual *ReLU*.","name":"negative_slope","option":"required","type":"float64"}],"category":"Activation","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/relu.html)\n**Detailed description**: [Reference](https://github.com/Kulbear/deep-learning-nano-foundation/wiki/ReLU-and-Softmax-Activation-Functions#rectified-linear-units)\n**Parameters**: *ReLU* layer parameters can be (not mandatory) specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\nY_{i}^{( l )} = max(0, Y_{i}^{( l - 1 )})\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Activation","schema":{"attributes":[{"description":" *type* represents particular activation function. For example, *type* equal *sigmoid* means that neurons of this layer have a sigmoid activation function.","name":"type","option":"required"},{"default":1,"name":"alpha","type":"float32"}],"category":"Activation","description":"**Short description**: *Activation* layer represents an activation function of each neuron in a layer, which is used to add non-linearity to the computational flow.\n**Detailed description**: [Reference](https://medium.com/the-theory-of-everything/understanding-activation-functions-in-neural-networks-9491262884e0)\n**Parameters**: *Activation layer* parameters should be specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n* Sigmoid function:\n \\f[\n f( x ) = \\frac{1}{1+e^{-x}}\n \\f]\n* Tahn function:\n \\f[\n f ( x ) = \\frac{2}{1+e^{-2x}} - 1 = 2sigmoid(2x) - 1\n \\f]\n*\tElu function:\n\t\\f[\n f(x) = \\left\\{\\begin{array}{ll}\n\t\te^{x} - 1 \\quad \\mbox{if } x < 0 \\\\\n\t\tx \\quad \\mbox{if } x \\geq 0\n\t\\end{array}\\right.\n\t\\f]\n*\tRelu6 function:\n\t\\f[\n f(x) = min(max(0, x), 6)\n\t\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"SoftMax","schema":{"attributes":[{"description":" *axis* represents the axis of which the *SoftMax* is calculated. *axis* equal 1 is a default value.","name":"axis","option":"required","type":"int32"}],"category":"Activation","description":"**Short description**: [Reference](https://github.com/Kulbear/deep-learning-nano-foundation/wiki/ReLU-and-Softmax-Activation-Functions#softmax)\n**Detailed description**: [Reference](http://cs231n.github.io/linear-classify/#softmax)\n**Parameters**: *SoftMax* layer parameters can be (not mandatory) specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\ny_{c} = \\frac{e^{Z_{c}}}{\\sum_{d=1}^{C}e^{Z_{d}}}\n\\f]\nwhere \\f$C\\f$ is a number of classes\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Deconvolution","schema":{"attributes":[{"default":1,"description":" *stride* is a distance (in pixels) to slide the filter on the feature map over the (x, y) axis. For example, *stride* equal \"1,1\" means sliding the filter 1 pixel at a time over the (x, y) axis.","name":"stride","option":"required","type":"int32"},{"default":1,"description":" *stride-x* is a distance (in pixels) to slide the filter on the feature map over the x axis. For example, *stride-x* equal 1 means sliding the filter 1 pixel at a time over the x axis.","name":"stride-x","option":"required","type":"int32"},{"default":1,"description":" *stride-y* is a distance (in pixels) to slide the filter on the feature map over the y axis. For example, *stride-y* equal 1 means sliding the filter 1 pixel at a time over the y axis.","name":"stride-y","option":"required","type":"int32"},{"default":1,"description":" *pad* is a number of pixels to add to the left and top of the input. For example, *pad* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad","option":"required","type":"int32"},{"default":1,"description":" *pad-x* is a number of pixels to add to the left of the input. For example, *pad-x* equal 1 means adding 1 pixel to the left of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-x","option":"required","type":" int32"},{"default":1,"description":" *pad-y* is a number of pixels to add to the top of the input. For example, *pad-y* equal 1 means adding 1 pixel to the top of the input. Right and bottom padding should be calculated from the expected output width (height).","name":"pad-y","option":"required","type":"int32"},{"default":1,"description":" *kernel* is a width and height of each filter. For example, *kernel* equal 3 (3, 3) means that each filter has width and height equal to 3.","name":"kernel","option":"required","type":"int32"},{"default":1,"description":" *kernel-x* is a width of each filter. For example, *kernel* equal 3 means that each filter has width equal to 3.","name":"kernel-x","option":"required","type":"int32"},{"default":1,"description":" *kernel-y* is a height of each filter. For example, *kernel-y* equal 3 means that each filter has height equal to 3.","name":"kernel-y","option":"required","type":"int32"},{"default":1,"description":" *output* is a number of output feature maps per whole output (when *group* > 1, *output* still matches the number of output features regardless of *group* value). For example, *output* equals 1 means that there is 1 output feature map in a layer.","name":"output","option":"required","type":"int32"},{"default":1,"description":" *group* denotes the number of groups to which *output* and *input* should be split. For example, *group* equal 1 means that all the filters are applied to full input (usual convolution), *group* equals 2 means that both *input* and *output* channels are separated into 2 groups and *i-th output* group is connected to *i-th input* group channels. *group* equals number of output feature maps denotes depth-wise separable convolution ([Reference](https://medium.com/towards-data-science/types-of-convolutions-in-deep-learning-717013397f4d#6f51)).","name":"group","option":"required","type":"int32"},{"default":1,"description":" *dilation* denotes the distance in width and height between elements (weights) in the filter. For example, *dilation* equal \"1,1\" means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation* equal \"2,2\" means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation","option":"required","type":"int32"},{"default":1,"description":" *dilation-y* denotes the distance in height between elements (weights) in the filter. For example, *dilation-y* equal 1 means that all the elements in the filter are neighbors, so it is the same as for the usual convolution. *dilation-y* equal 2 means that all the elements in the filter are matched not to adjacent elements in the input matrix, but to those that are adjacent with distance 1.","name":"dilation-y","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *Deconvolution* layer is applied for upsampling the output to the higher image resolution.\n**Detailed description**: [Reference](https://distill.pub/2016/deconv-checkerboard/)\n**Parameters**: *Deconvolution* layer parameters should be specified in the `deconvolution_data` node, which is a child of the layer node.\n**Parameters**: *Convolution* layer parameters should be specified in the `convolution_data` node, which is a child of the layer node.\n**Weights Layout** Weights layout is the following: GOIYX, which means that *X* is changing the fastest, then *Y*, then *Input*, *Output*, then *Group*.\n**Mathematical Formulation**\n*Deconvolution* is also called transpose convolution and performs operation, reverse to convolution.\nThe number of output features for each dimensions is calculated:\n\\f[S_{o}=stride(S_{i} - 1 ) + S_{f} - 2pad \\f]\nWhere \\f$S\\f$ is size of output, input and filter.\nOutput is calculated in the same way as for convolution layer:\n\\f[out = \\sum_{i = 0}^{n}w_{i}x_{i} + b\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Norm","schema":{"attributes":[{"default":1,"description":" *alpha* represents the scaling parameter for the normalizing sum. For example, *alpha* equal 0.0001 means that the normalizing sum is multiplied by 0.0001.","name":"alpha","option":"required","type":" floating point positive number"},{"default":1,"description":" *beta* represents the exponent for the normalizing sum. For example, *beta* equal 0.75 means that the normalizing sum is raised to the power of 0.75.","name":"beta","option":"required","type":" floating point positive number"},{"default":1,"description":" *region* represents strategy of local regions extension. For example, *region* equal *across* means that the normalizing sum is performed over adjacent channels.","name":"region","option":"required","type":""},{"default":1,"description":" *local-size* represents the side length of the region to be used for the normalization sum or number of channels depending on the strategy specified in the *region* parameter. For example, *local-size* equal 5 for the across strategy means application of sum across 5 adjacent channels.","name":"local-size","option":"required","type":" positive integer bigger than zero"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/lrn.html)\n**Detailed description**: [Reference](http://yeephycho.github.io/2016/08/03/Normalizations-in-neural-networks/#Local-Response-Normalization-LRN)\n**Parameters**: *Norm* layer parameters should be specified in the `norm_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[o_{i} = \\left( 1 + \\left( \\frac{\\alpha}{n} \\right)\\sum_{i}x_{i}^{2} \\right)^{\\beta}\\f]\nWhere \\f$n\\f$ is the size of each local region.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Concat","schema":{"attributes":[{"description":" *axis* is the number of axis over which input blobs are concatenated. For example, *axis* equal 1 means that input blobs are concatenated over the first axis.","name":"axis","option":"required","type":"int32"}],"category":"Tensor","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/concat.html)\n**Parameters**: *Concat* layer parameters should be specified in the `concat_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Axis* parameter specifies a blob dimension to concat values. For example, for two input blobs *B1xC1xH1xW1* and *B2xC2xh4xW2* if axis: 1, output blob is****: *B1xC1+C2xH1xW1*. This is only possible if *B1=B2*, *H1=H4*, *W1=W2*.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Split","schema":{"attributes":[{"name":"axis","type":"int32"}],"category":"Tensor","description":"**Short description**: *Split* layer splits the input into several output groups. Group sizes are denoted by the number and the size of output ports.\n**Detailed description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/split.html)\n**Parameters**: *None*\n**Mathematical Formulation**\nSplits input blob among children. For example, blob is *BxC+CxHxW* and there are two children. Then, output blob is *BxCxHxW*.\n**Example**\n\n```html\n\n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Reshape","schema":{"attributes":[{"default":1,"description":" *axis* is the number of the starting axis for reshape. For example, *axis* equal 1 means that *Reshape* replaces dimensions starting from the next after the first dimension.","name":"axis","option":"required","type":"int32"},{"description":" *dim* is a set of numbers separated with comma, which denote the dimensions of output blob. For example, *dim* equal 88,1,71 means that output blob gets following dimensions: first dimension equals 88, second dimension equals 1, third dimension equals 71. For more information, refer to the **Description** block. If *dim* is equal to two numbers, it performs [flattening](http://caffe.berkeleyvision.org/tutorial/layers/flatten.html).","name":"dim","option":"required","type":"int32[]"},{"default":1,"description":" *num_axes* is the number of dimensions to be replaced with a reshaped blob starting from the dimension number specified in *axis* property. For example, *num_axes* equal 2 means that 2 dimensions are replaced with reshaped blob.","name":"num_axes","option":"required","type":"int32"}],"category":"Shape","description":"**Short description**: *Reshape* layer changes dimensions of the input blob according to the specified order. Input blob volume is equal to output blob volume, where volume is the product of dimensions.\n**Detailed description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/reshape.html)\n**Parameters**: *Reshape* layer parameters should be specified in the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nIf you want to reshape input blob *BxCxHxW* into *Bx1x(C*H)xW*, the *dim* parameters of your layer should be:\n```html\n layer {\n name: \"reshape\"\n type: \"Reshape\"\n bottom: \"input\"\n top: \"output\"\n reshape_param {\n shape {\n dim: 0 # copy the dimension from below\n dim: 1\n dim: -1 # infer it from the other dimensions\n dim: 0\n }\n }\n }\n```\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Eltwise","schema":{"attributes":[{"default":"sum","description":" *operation* is the simple mathematical operation to be performed over inputs. For example, *operation* equal *mul* means that input blobs are multiplied.","name":"operation","option":"required","type":"string"}],"description":"**Short description**: *Eltwise* layer performs element-wise operation, which is specified in parameters, over given inputs.\n**Parameters**: *Eltwise* layer parameters should be specified in the `elementwise_data` node, which is placed as a child of the layer node.\n**Mathematical Formulation** *Eltwise* accepts 2 inputs of any number of dimensions - from 1 to 4, however, it is required for both of them to have absolutely same dimensions. The produced blob is also of the same dimension as each of its parents\n*Eltwise* does the following with the input blobs:\n\\f[\no_{i} = f(b_{i}^{1}, b_{i}^{2})\n\\f]\nwhere \\f$b_{i}^{1}\\f$ - first blob \\f$i\\f$-th element, \\f$b_{i}^{2}\\f$ - second blob \\f$i\\f$-th element, \\f$o_{i}\\f$ - output blob \\f$i\\f$-th element, \\f$f(a, b)\\f$ - is a function that performs an operation over its two arguments \\f$a, b\\f$.\n* For *sum* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = a + b\n \\f]\n* For *mul* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = a * b\n \\f]\n* For *max* operation, \\f$f(a, b)\\f$ is defined as\n \\f[\n f(a,b) = \\left\\{\\begin{array}{ll}\n\t\ta \\quad \\mbox{if } a \\geq b \\\\\n\t\tb \\quad \\mbox{if } b > a\n\t\\end{array}\\right. \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ScaleShift","schema":{"category":"Layer","attributes":[],"description":"**Short description**: *ScaleShift* layer performs linear transformation of the input blobs. Weights denote scaling parameter, biases - a shift.\n**Parameters**: *ScaleShift* layer does not have additional parameters.\n**Mathematical Formulation**\n\\f[\no_{i} =\\gamma b_{i} + \\beta\n\\f]\n**Example**\n\n```\n\n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Crop","schema":{"attributes":[{"default":1,"description":" *axis* is a number of a dimension to be used for cropping. For example, *axis* equal to 1 means that cropping is performed over the first dimension.","name":"axis","option":"required","type":" a list of unique integers, where each element is greater than or equal to 0 and less than input shape length."},{"default":1,"description":" *offset* denotes the starting point for crop in the input blob. For example, *offset* equal to 2 means that crop is starting from the second value in the given axis.","name":"offset","option":"required","type":" a list of integers of the length equal to the length of *axis* attribute. In the list, `offset[i]` is greater than or equal to 0 and less than or equal to `input_shape[axis[i]] - crop_size[axis[i]]`, where `crop_size` is the shape of the second input."}],"category":"Data","description":"**Short description**: *Crop* layer changes selected dimensions of the input blob according to the specified parameters.\n**Parameters**: *Crop* layer parameters should be specified in `data` section, which is placed as a child of the layer node. Due to various representation of Crop attributes in existing frameworks, this layer can be described in three independent ways: *Crop* **Type 1** layer takes two input blobs, and the shape of the second blob specifies the *Crop* size. The layer has two attributes: *axis* and *offset*. Crop layer takes two input blobs, and the shape of the second blob specifies the *Crop* size. The *Crop* layer of this type supports shape inference.\n**Inputs**\n* **1**: Multidimensional input blob *(for example, NCHW, NCH, or NC)*\n* **2**: Shape of this input will be used for crop\n**Example**\n\n```html\n\n \n \n \n 1\n 21\n 44\n 44\n \n \n 1\n 21\n 34\n 34\n \n \n \n \n 1\n 21\n 34\n 34\n \n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"BatchNormalization","schema":{"attributes":[{"default":1,"description":" *epsilon* is the number to be added to the variance to avoid division by zero when normalizing the value. For example, *epsilon* equal 0.001 means that 0.001 is added to the variance.","name":"epsilon","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/batchnorm.html)\n**Detailed description**: [Reference](https://kratzert.github.io/2016/02/12/understanding-the-gradient-flow-through-the-batch-normalization-layer.html)\n**Parameters**: *BatchNormalization* layer parameters should be specified as the `batch_norm_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*BatchNormalization* is the normalization of the output in each hidden layer.\n* **Input**: Values of \\f$x\\f$ over a mini-batch:\n \\f[\n \\beta = \\{ x_{1...m} \\}\n \\f]\n* **Parameters to learn**: \\f$ \\gamma, \\beta\\f$\n* **Output**:\n \\f[\n \\{ o_{i} = BN_{\\gamma, \\beta} ( b_{i} ) \\}\n \\f]\n* **Mini-batch mean**:\n \\f[\n \\mu_{\\beta} \\leftarrow \\frac{1}{m}\\sum_{i=1}^{m}b_{i}\n \\f]\n* **Mini-batch variance**:\n \\f[\n \\sigma_{\\beta }^{2}\\leftarrow \\frac{1}{m}\\sum_{i=1}^{m} ( b_{i} - \\mu_{\\beta} )^{2}\n \\f]\n* **Normalize**:\n \\f[\n \\hat{b_{i}} \\leftarrow \\frac{b_{i} - \\mu_{\\beta}}{\\sqrt{\\sigma_{\\beta }^{2} + \\epsilon }}\n \\f]\n* **Scale and shift**:\n \\f[\n o_{i} \\leftarrow \\gamma\\hat{b_{i}} + \\beta = BN_{\\gamma ,\\beta } ( b_{i} )\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Normalize","schema":{"attributes":[{"default":1,"description":" *across_spatial* is a flag that denotes if normalization is performed over CHW or HW. For example, *across_spatial* equals 0 means that normalization is not shared across channels.","name":"across_spatial","option":"required","type":"\n * 0\n * 1 - not supported"},{"default":1,"description":" *channel_shared* is a flag that denotes if scale parameters are shared across channels. For example, *channel_shared* equal 0 means that scale parameters are not shared across channels.","name":"channel_shared","option":"required","type":"\n * 0 - scale parameters are not shared across channels\n * 1 - not supported"},{"default":1,"description":" *eps* is the epsilon used to avoid division by zero when normalizing the value. For example, *eps* equals 0.001 means that 0.001 is used if all the values in normalization are equal to zero.","name":"eps","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: *Normalize* layer performs l-p normalization of 1 of input blob.\n**Parameters**: *Normalize* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\no_{i} = \\sum_{i}^{H*W}\\frac{\\left ( n*C*H*W \\right )* scale}{\\sqrt{\\sum_{i=0}^{C*H*W}\\left ( n*C*H*W \\right )^{2}}}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Tile","schema":{"attributes":[{"default":1,"description":" *axis* is the index of the axis to tile. For example, *axis* equals 3 means that fourth axis is used for tiling.","name":"axis","option":"required","type":"int32"},{"description":" *tiles* is a size of the specified axis in the output blob. For example, *tiles* equal 88 means that output blob gets 88 copies of data from specified axis.","name":"tiles","option":"required","type":"int32"}],"description":"**Short description**: *Tile* layer extends input blob with copies of data along specific axis.\n**Detailed description**: [Reference](http://caffe.help/manual/layers/tile.html)\n**Parameters**: *Tile* layer parameters should be specified as the `tile_data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Tile* extends input blobs and filling in output blobs following rules:\n\\f[\nout_i=input_i[inner\\_dim*t]\n\\f]\n\\f[\nt \\in \\left ( 0, \\quad tiles \\right )\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Permute","schema":{"attributes":[{"description":" *order* is the set of dimensions indexes for output blob. For example, *order* equal 0,2,3,1 means that the output blob has following dimensions: first dimension from the input blob, third dimension from the input blob, fourth dimension from the input blob, second dimension from the input blob.","name":"order","option":"required","type":"int32[]"}],"category":"Shape","description":"**Short description**: *Permute* layer performs reordering of input blob dimensions.\n**Detailed description**: [Reference](http://caffe.help/manual/layers/tile.html)\n**Parameters**: *Permute* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Permute* layer performs reordering input blob. Source indexes and destination indexes are bound by formula:\n\\f[\nsrc\\_ind_{offset} = n * ordered[1] * ordered[2] * ordered[3] + (h * ordered[3] + w)\n\\f]\n\\f[\nn \\in ( 0, order[0] )\n\\f]\n\\f[\nh \\in ( 0, order[2] )\n\\f]\n\\f[\nw \\in ( 0, order[3] )\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PriorBox","schema":{"attributes":[{"name":"min_size","option":"required","type":"float32"},{"name":"max_size","option":"required","type":"float32"},{"default":1,"description":" *aspect_ratio* is a variance of aspect ratios. Duplicate values are ignored. For example, *aspect_ratio* equal 2.000000,3.000000 means that for the first box aspect_ratio is equal to 2 and for the second box - 3.","name":"aspect_ratio","option":"required","type":"float32"},{"default":false,"description":" *flip* is a flag that denotes that each *aspect_ratio* is duplicated and flipped. For example, *flip* equals 1 and *aspect_ratio* equals 3 mean that aspect_ratio is equal to 1/3.","name":"flip","option":"required","type":"boolean"},{"default":false,"description":" *clip* is a flag that denotes if each value in the output blob is within [0,1]. For example, *clip* equal 1 means that each value in the output blob is within [0,1].","name":"clip","option":"required","type":"boolean"},{"description":" *step* is a distance between box centers. For example, *step* equal 85 means that the distance between neighborhood prior boxes centers is 85.","name":"step","option":"required","type":"float32"},{"default":0.5,"description":" *offset* is a shift of box respectively to top left corner. For example, *offset* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"offset","option":"required","type":"float32"},{"description":" *variance* denotes a variance of adjusting bounding boxes. For example, *variance* equals 85 means that the shift of neighborhood prior boxes centers is 85.","name":"variance","option":"required","type":"float32[]"},{"default":1,"description":" *scale_all_sizes* is a flag that denotes type of inference. For example, *scale_all_sizes* equals 0 means that priorbox layer is inferd in MXNet-like manner. In particular, *max_size* parameter is ignored.","name":"scale_all_sizes","option":"required","type":"int32"}],"description":"**Short description**: *PriorBox* layer generates prior boxes of specified sizes and aspect ratios across all dimensions.\n**Parameters**: *PriorBox* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**:\n*PriorBox* computes coordinates of prior boxes by following:\n1. First calculates *center_x* and *center_y* of prior box:\n \\f[\n W \\equiv Width \\quad Of \\quad Image\n \\f]\n \\f[\n H \\equiv Height \\quad Of \\quad Image\n \\f]\n * If step equals 0:\n \\f[\n center_x=(w+0.5)\n \\f]\n \\f[\n center_y=(h+0.5)\n \\f]\n * else:\n \\f[\n center_x=(w+offset)*step\n \\f]\n \\f[\n center_y=(h+offset)*step\n \\f]\n \\f[\n w \\subset \\left( 0, W \\right )\n \\f]\n \\f[\n h \\subset \\left( 0, H \\right )\n \\f]\n2. Then, for each \\f$ s \\subset \\left( 0, min_sizes \\right ) \\f$ calculates coordinates of priorboxes:\n \\f[\n xmin = \\frac{\\frac{center_x - s}{2}}{W}\n \\f]\n \\f[\n ymin = \\frac{\\frac{center_y - s}{2}}{H}\n \\f]\n \\f[\n xmax = \\frac{\\frac{center_x + s}{2}}{W}\n \\f]\n \\f[\n ymin = \\frac{\\frac{center_y + s}{2}}{H}\n \\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"SimplerNMS","schema":{"attributes":[{"default":1,"description":" *pre_nms_topn (post_nms_topn)* is the quantity of bounding boxes before (after) applying NMS operation. For example, *pre_nms_topn (post_nms_topn)* equals 15 means that the minimum (maximum) box size is 15.","name":"pre_nms_topn (post_nms_topn)","option":"required","type":"int32"},{"default":1,"description":" *cls_threshold* is the minimum value of the proposal to be taken into consideration. For example, *cls_threshold* equal 0.5 means that all boxes with prediction probability less than 0.5 are filtered out.","name":"cls_threshold","option":"required","type":"float32"},{"default":1,"description":" *iou_threshold* is the minimum ratio of boxes overlapping to be taken into consideration. For example, *iou_threshold* equal 0.7 means that all boxes with overlapping ratio less than 0.7 are filtered out.","name":"iou_threshold","option":"required","type":"float32"},{"default":1,"description":" *feat_stride* is the step size to slide over boxes (in pixels). For example, *feat_stride* equal 16 means that all boxes are analyzed with the slide 16.","name":"feat_stride","option":"required","type":"int32"},{"default":1,"description":" *min_bbox_size* is the minimum size of box to be taken into consideration. For example, *min_bbox_size* equal 35 means that all boxes with box size less than 35 are filtered out.","name":"min_bbox_size","option":"required","type":"int32"},{"default":1,"description":" *scale* is array of scales for anchor boxes generating.","name":"scale","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *SimplerNMS* layer performs filtering of bounding boxes and outputs only those with the highest confidence of prediction.\n**Parameters**: *SimplerNMS* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*SimplerNMS* accepts three inputs with four dimensions. Produced blob has two dimensions, the first one equals *post_nms_topn*.\n*SimplerNMS* does the following with the input blob:\n1. Generates initial anchor boxes. Left top corner of all boxes is (0, 0). Width and height of boxes are calculated based on scaled (according to the scale parameter) default widths and heights\n2. For each point in the first input blob:\n * pins anchor boxes to picture according to the second input blob, which contains four deltas for each box: for x and y of center, for width, and for height\n * finds out score in the first input blob\n3. Filters out boxes with size less than *min_bbox_size.*\n4. Sorts all proposals (*box, score*) by score from highest to lowest\n5. Takes top *pre_nms_topn* proposals\n6. Calculates intersections for boxes and filters out all with \\f$intersection/union > iou\\_threshold\\f$\n7. Takes top *post_nms_topn* proposals\n8. Returns top proposals\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"DetectionOutput","schema":{"attributes":[{"default":1,"description":" number of classes to be predicted","name":"num_classes","option":"required","type":"int32"},{"default":1,"description":" background label id. If there is no background class, set it to -1.","name":"background_label_id","option":"required","type":"int32"},{"default":1,"description":" maximum number of results to be kept on NMS stage","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if \"true\", variance is encoded in target. Otherwise, we need to adjust the predicted offset accordingly.","name":"variance_encoded_in_target","option":"required","type":" logical values"},{"default":1,"description":" number of total bboxes to be kept per image after NMS step. -1 means keeping all bboxes after NMS step.","name":"keep_top_k","option":"required","type":"int32"},{"default":1,"description":null,"name":"num_orient_classes","option":"required","type":"int32"},{"default":1,"description":" type of coding method for bounding boxes. caffe.PriorBoxParameter.CENTER_SIZE and others.","name":"code_type","option":"required","type":"int32"},{"default":1,"description":" bounding boxes are shared among different classes.","name":"share_location","option":"required","type":" logical values"},{"default":1,"description":null,"name":"interpolate_orientation","option":"required","type":"int32"},{"default":1,"description":" threshold to be used in NMS stage","name":"nms_threshold","option":"required","type":"float32"},{"default":1,"description":" only consider detections whose confidences are larger than a threshold. If not provided, consider all boxes.","name":"confidence_threshold","option":"required","type":"float32"}],"description":"**Short description**: *DetectionOutput* layer performs non-maximum suppression to generate the detection output using information on location and confidence predictions.\n**Detailed description**: [Reference](https://arxiv.org/pdf/1512.02325.pdf)\n**Parameters**: *DetectionOutput* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nAt each feature map cell, *DetectionOutput* predicts the offsets relative to the default box shapes in the cell, as well as the per-class scores that indicate the presence of a class instance in each of those boxes. Specifically, for each box out of k at a given location, *DetectionOutput* computes class scores and the four offsets relative to the original default box shape. This results in a total of \\f$(c + 4)k\\f$ filters that are applied around each location in the feature map, yielding \\f$(c + 4)kmn\\f$ outputs for a m × n feature map.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Memory","schema":{"attributes":[{"default":1,"description":" *id* is the id of the pair of *Memory* layers. For example, *id* equals r_27-28 means that layers with id 27 and 28 are in one pair.","name":"id","option":"required","type":"int32"},{"default":1,"description":" *index* represents if the given layer is input or output. For example, *index* equal 0 means this layer is output one.","name":"index","option":"required","type":"int32"},{"default":1,"description":" *size* represents the size of the group. For example, *size* equals 2 means this group is a pair.","name":"size","option":"required","type":"int32"}],"description":"**Short description**: *Memory* layer represents delay layer in terms of LSTM terminology. To read more about LSTM topologies please refer this [link](http://colah.github.io/posts/2015-08-Understanding-LSTMs).\n**Detailed description**: *Memory* layer saves state between two infer requests. In the topology, it is the single layer, however, in the Intermediate Representation, it is always represented as a pair of **Memory** layers. One of these layers does not have outputs and another does not have inputs (in terms of the Intermediate Representation).\n**Parameters**: *Memory* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Memory* save data from the input blob.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Clamp","schema":{"attributes":[{"default":0,"description":" *min* is the lower bound of values in the output shape. Any value in the input shape that is smaller than the bound, is replaced by the *min* value. For example, *min* equal 10 means that any value in the input shape that is smaller than the bound, is replaced by 10.","name":"min","option":"required","type":"int32"},{"default":1,"description":" *max* is the upper bound of values in the output shape. Any value in the input shape that is greater than the bound, is replaced by the *max* value. For example, *max* equals 50 means that any value in the input shape that is greater than the bound, is replaced by 50.","name":"max","option":"required","type":"int32"}],"description":"**Short description**: *Clamp* layer represents clipping activation operation.\n**Detailed description**: [Reference](https://www.tensorflow.org/versions/r1.2/api_docs/MO_DG/prepare_model/python/tf/clip_by_value)\n**Parameters**: *Clamp* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Clamp* generally does the following with the input blobs:\n\\f[\nout_i=\\left\\{\\begin{array}{ll}\n\tmax\\_value \\quad \\mbox{if } \\quad input_i>max\\_value \\\\\n\tmin\\_value \\quad \\mbox{if } \\quad input_i\n\\end{array}\\right.\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ArgMax","schema":{"attributes":[{"default":1,"description":" if *out_max_val* equals 1, output is a vector of pairs *(max_ind, max_val)*, unless axis is set. Then output is *max_val* along the specified axis.","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if *out_max_val* equals 1, output is a vector of pairs *(max_ind, max_val)*, unless axis is set. Then output is *max_val* along the specified axis.","name":"top_k","option":"required","type":"int32"},{"default":1,"description":" if set, maximizes along the specified axis, else maximizes the flattened trailing dimensions for each index of the first / num dimension.","name":"axis","option":"required","type":"int32"}],"description":"**Short description**: *ArgMax* layer compute the index of the *K* maximum values for each datum across all dimensions *CxHxW*.\n**Detailed description**: Intended for use after a classification layer to produce a prediction. If parameter *out_max_val* is set to \"true\", output is a vector of pairs *(max_ind, max_val)* for each image. The *axis* parameter specifies an axis along which to maximize.\n**Parameters**: *ArgMax* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*ArgMax* generally does the following with the input blobs:\n\\f[\no_{i} = \\left\\{\nx| x \\in S \\wedge \\forall y \\in S : f(y) \\leq f(x)\n\\right\\}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PSROIPooling","schema":{"attributes":[{"default":1,"description":" pooled output channel number","name":"output_dim","option":"required","type":"int32"},{"default":1,"description":" number of groups to encode position-sensitive score maps","name":"group_size","option":"required","type":"int32"},{"default":1,"description":" multiplicative spatial scale factor to translate ROI coordinates from their input scale to the scale used when pooling","name":"spatial_scale","option":"required","type":"float32"}],"category":"Pool","description":"**Short description**: *PSROIPooling* layer compute position-sensitive max pooling on regions of interest specified by input, takes as input N position-sensitive score maps and a list of R regions of interest.\n**Detailed description**: [Reference](https://arxiv.org/pdf/1703.06211.pdf)\n**Parameters**: *PSRoiPooling* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nThe output value for \\f$(i, j)\\f$-th bin is obtained by summation from one score map \\f$x_{i,j}\\f$ corresponding to that bin. In short, the difference from *RoIPooling* is that a general feature map \\f$x\\f$ is replaced by a specific positive-sensitive score map \\f$x_{i,j}\\f$.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"GRN","schema":{"attributes":[{"default":1,"description":" *bias* is added to the variance.","name":"bias","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: *GRN* is Global Response Normalization with L2 norm (across channels only).\n**Parameters**: GRN layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*GRN* computes L2 norm by channels for input blob. *GRN* generally does the following with the input blob:\n\\f[\noutput_{i} = \\frac{input_{i}}{\\sqrt{\\sum_{i}^{C} input_{i}}}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PReLU","schema":{"attributes":[{"default":1,"description":" *channel_shared* shows if negative slope shared across channels or not.","name":"channel_shared","option":"required","type":"int32"},{"description":" *filler_type* defines initialization type for negative slope.","name":"filler_type","option":"required","type":"string"},{"default":1,"description":" *filler_value* defines the value in constant filler.","name":"filler_value","option":"required","type":"int32"},{"default":1,"description":" *min(max)* defines the minimal(maximal) value in uniform filler.","name":"min(max)","option":"required","type":"int32"},{"default":1,"description":" *mean* defines the mean value in Gaussian filler.","name":"mean","option":"required","type":"int32"}],"category":"Activation","description":"**Short description**: *PReLU* is the Parametric Rectifier Linear Unit. The difference from *ReLU* is that negative slopes can vary across channels.\n**Parameters**: *PReLU* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*PReLU* accepts one input with four dimensions. The produced blob has the same dimensions as input.\n*PReLU* does the following with the input blob:\n\\f[\no_{i} = max(0, x_{i}) + w_{i} * min(0,x_{i})\n\\f]\nwhere \\f$w_{i}\\f$ is from weights blob.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"RegionYolo","schema":{"attributes":[{"default":1,"description":" *coords* is num coordinates for each region","name":"coords","option":"required","type":"int32"},{"default":1,"description":" *classes* is num classes for each region","name":"classes","option":"required","type":"int32"},{"default":1,"description":" *num* is number of regions","name":"num","option":"required","type":"int32"},{"default":1,"description":" *do_softmax* is a flag which specifies the method of infer","name":"do_softmax","option":"required","type":"int32"},{"default":1,"description":" *anchors* coordinates regions","name":"anchors","option":"required","type":"float32[]"},{"default":1,"description":" *mask* specifies which anchors to use","name":"mask","option":"required","type":"int32"},{"default":1,"description":" *mask* specifies which anchors to use","name":"mask","option":"required","type":"int32"},{"default":1,"description":" *axis* is the number of the dimension from which flattening is performed. For example, *axis* equals 1 means that flattening is started from the 1st dimension.","name":"axis","option":"required","type":"int32"},{"default":1,"description":" *end_axis* is the number of the dimension on which flattening is ended. For example, *end_axis* equals -1 means that flattening is performed till the last dimension.","name":"end_axis","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *RegionYolo* computes coordinates of regions with probability for each class.\n**Detailed description**: [Reference][p_yolo]\n**Parameters**: *RegionYolo* layer parameters should be specified as the `data` node, which is a child of the `layer` node.\n**Example**\n\n```html\n\n \n ... \n ... \n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"ReorgYolo","schema":{"attributes":[{"default":1,"description":" *stride* is distance of cut throws in output blobs.","name":"stride","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *ReorgYolo* reorganizes input blob taking into account strides.\n**Detailed description**: [Reference][p_yolo]\n**Parameters**: *ReorgYolo* layer parameters should be specified as the `data` node, which is a child of the `layer` node.\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"PriorBoxClustered","schema":{"attributes":[{"description":" *width* is a parameter that specifies desired boxes widths in pixels.","name":"width","option":"required","type":"float32[]"},{"name":"height","option":"required","type":"float32[]"},{"default":false,"description":" *clip* is a flag that denotes if each value in the output blob is within [0,1]. For example, *clip* equal 1 means that each value in the output blob is within [0,1].","name":"clip","option":"required","type":"boolean"},{"default":false,"description":" *flip* is a flag that denotes whether the list of boxes is augmented with the flipped ones.","name":"flip","option":"required","type":"boolean"},{"description":" *step* is a distance between box centers. For example, *step* equal 85 means that the distance between neighborhood prior boxes centers is 85.","name":"step","option":"required","type":"float32"},{"name":"step_w","option":"required","type":"float32"},{"name":"step_h","option":"required","type":"float32"},{"default":1,"description":" *offset* is a shift of box respectively to top left corner. For example, *offset* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"offset","option":"required","type":"float32"},{"description":" *variance* denotes a variance of adjusting bounding boxes. For example, *variance* equal 85 means that the shift of neighborhood prior boxes centers is 85.","name":"variance","option":"required","type":"float32[]"},{"description":" *img_h* specifies height of input image. These parameters are calculated unless provided explicitly.","name":"img_h","option":"required","type":"float32"},{"name":"img_w","option":"required","type":"float32"}],"description":"**Short description**: *PriorBoxClustered* layer generates prior boxes of specified sizes.\n**Parameters**: *PriorBoxClustered* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*PriorBoxClustered* computes coordinates of prior boxes by following:\n1. Calculates the *center_x* and *center_y* of prior box:\n \\f[\n W \\equiv Width \\quad Of \\quad Image\n \\f]\n \\f[\n H \\equiv Height \\quad Of \\quad Image\n \\f]\n \\f[\n center_x=(w+offset)*step\n \\f]\n \\f[\n center_y=(h+offset)*step\n \\f]\n \\f[\n w \\subset \\left( 0, W \\right )\n \\f]\n \\f[\n h \\subset \\left( 0, H \\right )\n \\f]\n2. For each \\f$s \\subset \\left( 0, W \\right )\\f$ calculates the prior boxes coordinates:\n \\f[\n xmin = \\frac{center_x - \\frac{width_s}{2}}{W}\n \\f]\n\t\\f[\n\tymin = \\frac{center_y - \\frac{height_s}{2}}{H}\n\t\\f]\n\t\\f[\n\txmax = \\frac{center_x - \\frac{width_s}{2}}{W}\n\t\\f]\n\t\\f[\n\tymax = \\frac{center_y - \\frac{height_s}{2}}{H}\n\t\\f]\nIf *clip* is defined, the coordinates of prior boxes are recalculated with the formula:\n\\f$coordinate = \\min(\\max(coordinate,0), 1)\\f$\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"MVN","schema":{"attributes":[{"default":1,"description":" *across_channels* is a flag that denotes if mean values are shared across channels. For example, *across_channels* equal 0 means that mean values are not shared across channels.","name":"across_channels","option":"required","type":"int32"},{"default":1,"description":" *normalize_variance* is a flag that denotes whether to perform variance normalization.","name":"normalize_variance","option":"required","type":"int32"},{"default":1,"description":" *eps* is the number to be added to the variance to avoid division by zero when normalizing the value. For example, *epsilon* equal 0.001 means that 0.001 is added to the variance.","name":"eps","option":"required","type":"float32"}],"category":"Normalization","description":"**Short description**: [Reference](http://caffe.berkeleyvision.org/tutorial/layers/mvn.html)\n**Parameters**: *MVN* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*MVN* subtracts mean from the input blob:\n\\f[\no_{i} = i_{i} - \\frac{\\sum{i_{k}}}{C * H * W}\n\\f]\nIf *normalize_variance* is set to 1, the output blob is divided by variance:\n\\f[\no_{i}=\\frac{o_{i}}{\\sum \\sqrt {o_{k}^2}+\\epsilon}\n\\f]\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"CTCGreadyDecoder","schema":{"attributes":[{"default":1,"description":" *ctc_merge_repeated* is a flag for collapsing the repeated labels during the ctc calculation.","name":"ctc_merge_repeated","option":"required","type":"int32"}],"category":"Layer","description":"**Short description**: *CTCGreadyDecoder* performs greedy decoding on the logits given in input (best path).\n**Detailed description**: [Reference](https://www.tensorflow.org/api_docs/python/tf/nn/ctc_greedy_decoder)\n**Parameters**: *CTCGreadyDecoder* layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\nGiven an input sequence \\f$X\\f$ of length \\f$T\\f$, *CTCGreadyDecoder* assumes the probability of a length \\f$T\\f$ character sequence \\f$C\\f$ is given by\n\\f[\np(C|X) = \\prod_{t=1}^{T} p(c_{t}|X)\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Proposal","schema":{"attributes":[{"default":1,"description":" *pre_nms_topn (post_nms_topn)* is the quantity of bounding boxes before (after) applying NMS operation. For example, *pre_nms_topn (post_nms_topn)* equal 15 means that the minimum (maximum) box size is 15.","name":"pre_nms_topn (post_nms_topn)","option":"required","type":"int32"},{"default":1,"description":" *nms_thresh* is the minimum value of the proposal to be taken into consideration. For example, *nms_thresh* equal 0.5 means that all boxes with prediction probability less than 0.5 are filtered out.","name":"nms_thresh","option":"required","type":"float32"},{"default":1,"description":" *feat_stride* is the step size to slide over boxes (in pixels). For example, *feat_stride* equal 16 means that all boxes are analyzed with the slide 16.","name":"feat_stride","option":"required","type":"int32"},{"default":1,"description":" *min_size* is the minimum size of box to be taken into consideration. For example, *min_size* equal 35 means that all boxes with box size less than 35 are filtered out.","name":"min_size","option":"required","type":"int32"},{"default":1,"description":" *ratio* is the ratios for anchor generation.","name":"ratio","option":"required","type":"float32[]"},{"default":1,"description":" *ratio* is the ratios for anchor generation.","name":"ratio","option":"required","type":"float32[]"},{"default":1,"description":" *scale* is the scales for anchor generation.","name":"scale","option":"required","type":"float32[]"}],"category":"Layer","description":"**Short description**: *Proposal* layer performs filtering of only those bounding boxes and outputs with the highest confidence of prediction.\n**Parameters**: Proposal layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n*Proposal* layer accepts three inputs with four dimensions. The produced blob has two dimensions: first one equals *batch_size * post_nms_topn*.\n*Proposal* does the following with the input blob:\n1. Generates initial anchor boxes Left top corner of all boxes in (0, 0). Width and height of boxes are calculated from *base_size* with scale and ratio parameters\n2. For each point in the first input blob:\n * pins anchor boxes to the image according to the second input blob that contains four deltas for each box: for *x* and *y* of center, for *width* and for *height*\n * finds out score in the first input blob\n3. Filters out boxes with size less than *min_size*\n4. Sorts all proposals (*box*, *score*) by score from highest to lowest\n5. Takes top *pre_nms_topn* proposals\n6. Calculates intersections for boxes and filter out all with \\f$intersection/union > nms\\_thresh\\f$\n7. Takes top *post_nms_topn* proposals\n8. Returns top proposals\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Resample","schema":{"attributes":[{"default":1,"description":" *type* parameter specifies type of blob interpolation.","name":"type","option":"required","type":"\n * *LINEAR* - linear blob interpolation\n * *CUBIC* - cubic blob interpolation\n * *NEAREST* - nearest-neighbor blob interpolation"},{"default":1,"description":" *antialias* is a flag that denotes whether to perform anti-aliasing.","name":"antialias","option":"required","type":"\n * 0 - anti-aliasing is not performed\n * 1 - anti-aliasing is performed"}],"category":"Layer","description":"**Short description**: *Resample* layer scales the input blob by the specified parameters.\n**Parameters**: Resample layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Example**\n\n```html\n\n \n \n ...\n \n \n ...\n \n​\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Power","schema":{"attributes":[],"description":"**Short description**: *Power* layer computes the output as (shift + scale * x) ^ power for each input element x.\n**Parameters**: Power layer parameters should be specified as the `data` node, which is a child of the layer node.\n**Mathematical Formulation**\n\\f[\np = (shift + scale * x)^{power}\n\\f]\n**Example**\n\n```html\n\n \n ... \n ... \n\n```","inputs":null,"outputs":null,"support_level":"default"}},{"name":"Flatten","schema":{"category":"Shape","attributes":[{"name":"axis","type":"int32"},{"name":"end_axis","type":"int32","default":-1}]}},{"name":"Pad","schema":{"category":"Tensor","attributes":[{"name":"pad_value","type":"float32"},{"name":"pads_begin","type":"int32[]"},{"name":"pads_end","type":"int32[]"},{"name":"pad_mode"}]}},{"name":"GRUCell","schema":{"category":"Layer"}},{"name":"LSTMCell","schema":{"category":"Layer"}},{"name":"MaxPool","schema":{"category":"Pool"}},{"name":"Transpose","schema":{"category":"Transform"}},{"name":"Squeeze","schema":{"category":"Transform"}},{"name":"Unsqueeze","schema":{"category":"Transform"}},{"name":"Gather","schema":{"category":"Transform"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino.js new file mode 100644 index 0000000000000000000000000000000000000000..5b2a3972d3615afc7cf8b386d2cfb9da3762ec47 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/openvino.js @@ -0,0 +1 @@ +var openvino=openvino||{},base=base||require("./base"),long=long||{Long:require("long")};openvino.ModelFactory=class{match(t){const e=t.identifier,n=e.split(".").pop().toLowerCase();if("xml"===n&&t.text.includes("6&&s.every(((t,e)=>t==n[e])))return!1;if(n.length>4){const t=n[0]|n[1]<<8|n[2]<<16|n[3]<<24;if(0===t||1===t||19950407===t||871224===t||180310===t)return!1}return!0}return!1}open(t,e){const n=t.identifier;switch(n.split(".").pop().toLowerCase()){case"xml":return t.request(n.substring(0,n.length-4)+".bin",null).then((s=>this._openModel(n,e,t.text,s))).catch((()=>this._openModel(n,e,t.text,null)));case"bin":return t.request(n.substring(0,n.length-4)+".xml","utf-8").then((s=>this._openModel(n,e,s,t.buffer))).catch((t=>{e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new openvino.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}))}}_openModel(t,e,n,s){return openvino.Metadata.open(e).then((i=>{try{let o=!1;const a=new DOMParser({errorHandler:()=>{o=!0}}).parseFromString(n,"text/xml");if(o||null==a.documentElement||a.getElementsByTagName("parsererror").length>0)throw new openvino.Error("File format is not OpenVINO.");if(!a.documentElement||"net"!=a.documentElement.nodeName)throw new openvino.Error("File format is not OpenVINO IR.");const r=openvino.XmlReader.read(a.documentElement),u=new openvino.Model(i,r,s);return r.disconnectedLayers&&e.exception(new openvino.Error("Graph contains not connected layers "+JSON.stringify(r.disconnectedLayers)+" in '"+t+"'.")),u}catch(n){e.exception(n,!1);const s=n&&n.message?n.message:n.toString();throw new openvino.Error(s.replace(/\.$/,"")+" in '"+t+"'.")}}))}},openvino.Model=class{constructor(t,e,n){this._name=e.name||"",this._graphs=[new openvino.Graph(t,e,n)]}get name(){return this._name}get format(){return"OpenVINO IR"}get graphs(){return this._graphs}},openvino.Graph=class{constructor(t,e,n){this._name=e.name||"",this._nodes=[],this._inputs=[],this._outputs=[],this._arguments={};for(const s of this._const(e.layers,e.edges)){const i=s.inputs.map((t=>this._argument(s.id,s.precision,t,e.edges))),o=s.outputs.map((t=>this._argument(s.id,t.precision||s.precision,t,null)));switch(s.type){case"Input":{const t=s.name||"";this._inputs.push(new openvino.Parameter(t,o));break}default:this._nodes.push(new openvino.Node(this,t,n,s,i,o))}}this._replaceTensorIteratorWithSubgraph(t,n,e.layers,e.edges),delete this._arguments;const s=new Set;for(const t of this._nodes)for(const e of t.outputs)for(const t of e.arguments)s.add(t.name);for(const t of this.inputs)for(const e of t.arguments)s.add(e.name);const i=new Set;for(const t of this._nodes)for(const e of t.inputs)for(const n of e.arguments)n.initializer||s.has(n.name)||i.add(t);0!==i.size&&(e.disconnectedLayers=Array.from(i).map((t=>t.name)))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}_argument(t,e,n,s){let i=t+":"+n.id;s&&(i=s[i]);let o=this._arguments[i];if(!o){const t=0==n.dims.length?null:new openvino.TensorShape(n.dims);o=new openvino.Argument(i,new openvino.TensorType(e,t),null)}return o}_replaceTensorIteratorWithSubgraph(t,e,n,s){const i=n.filter((t=>"TensorIterator"===t.type));for(const n of i){const i=n.id,o=this._nodes.find((t=>t._id===i)),a=n.body.layers,r=n.body.edges,u=n.back_edges,p=Object.assign({},r,u),l=n.port_map;for(const n of this._const(a,p,u)){const s=n.inputs.map((t=>this._argument(n.id,n.precision,t,p))),o=n.outputs.map((t=>this._argument(n.id,n.precision||t.precision,t,null))),a=new openvino.Node(this,t,e,n,s,o);a._id=i+"_"+n.id;for(const t of a._inputs)for(const e of t.arguments)e.name&&(e._name=i+"_"+e.name);for(const t of a._outputs)for(const e of t.arguments)e.name&&(e._name=i+"_"+e.name);this._nodes.push(a)}for(const t of l.input){const e=this._nodes.find((e=>e._id===i+"_"+t.internal_layer_id)),n=s[i+":"+t.external_port_id];if(n){const t=n.split(":"),s=t[0],i=t[1];if(this._nodes.find((t=>t._id===s))){if(!e._inputs)throw new openvino.Error("Tensor Iterator node with name '"+e._id+"' does not have inputs.");const t=s+":"+i,n=e._inputs.find((t=>Boolean(t.arguments.find((t=>!t.name)))));if(n){const e=n._arguments.find((t=>!t._name));e&&(e._name=t)}else e._inputs.push(new openvino.Parameter((e._inputs.length+1).toString(),[new openvino.Argument(t,null,null)]))}else{const t=o._inputs.find((t=>"input"===t._name));if(!t)return;const n=e._inputs.find((t=>Boolean(t.arguments.find((t=>!t.name)))));if(n){const e=n.arguments.find((t=>!t.name));e&&(e._name=t.arguments[0].name)}}}}for(const t of l.output){const e=this._nodes.find((e=>e._id===`${i}_${t.internal_layer_id}`)),n=i+":"+t.external_port_id,o=Object.keys(s).filter((t=>s[t]===n));for(const t of o){const n=t.split(":")[0],s=this._nodes.find((t=>t._id===n));if(s._inputs&&(!s._inputs||0!==s._inputs.length)&&e._outputs&&e._outputs[0])for(const t of s._inputs)for(const n of t._arguments){if(!n.name||n.name&&n.name.split(":")[0]!==i)continue;const t=e.outputs[0].arguments[0].name.split(":")[1];n._name=e.id+":"+t}}}this._nodes=this._nodes.filter((t=>t.id!==n.id))}}_const(t,e,n){const s=[];n=n||{},t=t.slice();for(const e of t){if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length&&0===e.blobs.length&&e.data&&e.data.length>3){const t={};for(const n of e.data)t[n.name]=n.value;if(t.element_type&&t.offset&&t.size){const n=t.element_type;let s=null;switch(n){case"f16":s="FP16";break;case"f32":s="FP32";break;default:s=n.toUpperCase()}const i=t.shape?t.shape.split(",").map((t=>parseInt(t.trim(),10))):null;e.data=[],e.blobs.push({name:"custom",precision:s,offset:parseInt(t.offset,10),size:parseInt(t.size,10),shape:i})}}"Const"===e.type&&1===e.blobs.length&&!e.blobs[0].shape&&0===e.inputs.length&&1===e.outputs.length&&e.outputs[0].dims&&(e.blobs[0].shape=e.outputs[0].dims)}const i=new Map;for(const e of t)if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length){const t=e.id+":"+e.outputs[0].id;i.set(t,{layer:e,counter:0})}for(const t of Object.keys(e)){const n=e[t];i.has(n)&&i.get(n).counter++}if(n)for(const t of Object.keys(n)){const e=n[t];i.has(e)&&i.get(e).counter++}for(const t of i)1!==t[1].counter&&i.delete(t[0]);for(const s of t)if(0===s.blobs.length)for(let t=s.inputs.length-1;t>0;t--){const o=s.inputs[t],a=s.id+":"+o.id,r=e[a]||n[a];if(!i.has(r))break;const u=i.get(r).layer,p=u.blobs[0];p&&(p.id=u.name||u.id,p.kind="Const",s.blobs.push(p),s.inputs.splice(t,1),i.get(r).layer=null,i.get(r).delete=!0)}for(;t.length>0;){const e=t.shift();if("Const"===e.type&&0===e.inputs.length&&1===e.outputs.length){const t=e.id+":"+e.outputs[0].id;if(i.has(t)&&i.get(t).delete)continue}s.push(e)}return s}},openvino.Node=class{constructor(t,e,n,s,i,o){this._metadata=e,this._type=s.type,this._name=s.name||"",this._id=s.id,this._inputs=[],this._outputs=[],this._initializers=[],this._attributes=[];const a=s.precision;let r=0;for(const t of i){const e=0==r?"input":r.toString();this._inputs.push(new openvino.Parameter(e,[t])),r++}let u=0;for(const t of o){const e=0==u?"output":u.toString();this._outputs.push(new openvino.Parameter(e,[t])),u++}const p={};for(const t of s.data){p[t.name]=t.value;const n=e.attribute(this.type,t.name);this._attributes.push(new openvino.Attribute(n,t.name,t.value))}for(const t of s.blobs){const e=t.name,s=t.offset,i=t.size,o=n&&s+i<=n.length?n.slice(s,s+i):null;let r=t.shape||null;const u=t.kind||"Blob",l=t.id||"",h=t.precision||a,c={FP16:2,FP32:4,I8:1,I16:2,I32:4,I64:8,U8:1,U16:2,U32:4,U64:8}[h];if(c)switch(this._type+":"+e){case"FullyConnected:weights":{const t=parseInt(p["out-size"],10);r=[i/(t*c),t];break}case"FullyConnected:biases":r=[parseInt(p["out-size"],10)];break;case"Convolution:weights":case"Deconvolution:weights":{const t=this.inputs[0].arguments[0].type.shape.dimensions[1],e=parseInt(p.group||"1",10),n=p["kernel-x"]&&p["kernel-y"]?[parseInt(p["kernel-x"],10),parseInt(p["kernel-y"],10)]:p.kernel.split(",").map((t=>parseInt(t.trim(),10))),s=parseInt(p.output,10);r=[Math.floor(t/e),s].concat(n);break}case"ScaleShift:weights":case"ScaleShift:biases":case"Convolution:biases":case"Normalize:weights":case"PReLU:weights":r=[Math.floor(i/c)];break;case"Const:custom":this._outputs.length>0&&this._outputs[0].arguments.length>0&&this._outputs[0].arguments[0].type&&this._outputs[0].arguments[0].type.shape&&this._outputs[0].arguments[0].type.shape.dimensions&&(r=this._outputs[0].arguments[0].type.shape.dimensions)}const d=r?new openvino.TensorShape(r):null;this._initializers.push(new openvino.Parameter(e,[new openvino.Argument(l,null,new openvino.Tensor(h,d,o,u))]))}}get id(){return this._id}get name(){return this._name}get device(){return this._device||""}get type(){return this._type}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs.concat(this._initializers)}get outputs(){return this._outputs}},openvino.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},openvino.Argument=class{constructor(t,e,n){this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},openvino.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,t){if(Object.prototype.hasOwnProperty.call(t,"type"))switch(this._type=t.type,t.type){case"boolean":switch(n){case"1":case"true":this._value=!0;break;case"0":case"false":this._value=!1}break;case"int32":{const t=Number.parseInt(this._value,10);this._value=Number.isNaN(this._value-t)?n:t;break}case"float32":case"float64":{const t=Number.parseFloat(this._value);this._value=Number.isNaN(this._value-t)?n:t;break}case"int32[]":if(this._value.length>2){let t=[];this._value.split(",").map((e=>{e=e.trim();const n=Number.parseInt(e,10);Number.isNaN(e-n)?t=null:null!=t&&t.push(n)})),null!=t&&(this._value=t)}break;case"float32[]":if(this._value.length>2){let t=[];this._value.split(",").map((e=>{e=e.trim();const n=Number.parseFloat(e);Number.isNaN(e-n)?t=null:null!=t&&t.push(n)})),null!=t&&(this._value=t)}}if(Object.prototype.hasOwnProperty.call(t,"visible")&&0==t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")){let e=t.default;if(this._value==e)this._visible=!1;else if(Array.isArray(this._value)&&Array.isArray(e)){if(e=e.slice(0,e.length),e.length>1&&null==e[e.length-1])for(e.pop();e.lengtht==e[n]))&&(this._visible=!1)}}}}get name(){return this._name}get value(){return this._value}get type(){return this._type}get visible(){return 0!=this._visible}},openvino.Tensor=class{constructor(t,e,n,s){this._data=n,this._type=new openvino.TensorType(t,e),this._kind=s}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return openvino.Tensor._stringify(e,""," ")}_context(){const t={state:null};return this._data?this._type.shape?(t.index=0,t.count=0,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t):(t.state="Tensor shape is not defined.",t):(t.state="Tensor data is empty.",t)}_decode(t,e){const n=0==t.shape.length?[1]:t.shape,s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"int8":s.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":s.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"uint8":s.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"uint16":s.push(t.data.getUint16(t.index,!0)),t.index+=2,t.count++;break;case"uint32":s.push(t.data.getUint32(t.index,!0)),t.index+=4,t.count++;break;case"uint64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!0)),t.index+=8,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}static _stringify(t,e,n){if(Array.isArray(t)){const s=[];s.push(e+"[");const i=t.map((t=>openvino.Tensor._stringify(t,e+n,n)));return i.length>0&&s.push(i.join(",\n")),s.push(e+"]"),s.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},openvino.TensorType=class{constructor(t,e){switch(t=t?t.toLowerCase():t){case"f16":case"fp16":this._dataType="float16";break;case"f32":case"fp32":this._dataType="float32";break;case"i8":this._dataType="int8";break;case"i16":this._dataType="int16";break;case"i32":this._dataType="int32";break;case"i64":this._dataType="int64";break;case"u1":this._dataType="boolean";break;case"u8":this._dataType="uint8";break;case"u16":this._dataType="uint16";break;case"u32":this._dataType="uint32";break;case"u64":this._dataType="uint64";break;case"bool":this._dataType="boolean";break;case"":case null:this._dataType="?";break;default:throw new openvino.Error("Unknown precision '"+JSON.stringify(t)+"'.")}this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return null==this._shape?this.dataType+"[?]":this.dataType+this._shape.toString()}},openvino.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},openvino.Metadata=class{static open(t){return openvino.Metadata._metadata?Promise.resolve(openvino.Metadata._metadata):t.request(null,"openvino-metadata.json","utf-8").then((t=>(openvino.Metadata._metadata=new openvino.Metadata(t),openvino.Metadata._metadata))).catch((()=>(openvino.Metadata._metadata=new openvino.Metadata(null),openvino.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeMap=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)if(t&&t.name&&t.schema){if(this._map.has(t.name))throw new openvino.Error("Duplicate metadata key '"+t.name+"'.");t.schema.name=t.name,this._map.set(t.name,t.schema)}}}type(t){return this._map.get(t)||null}attribute(t,e){const n=t+":"+e;if(!this._attributeMap.has(n)){this._attributeMap.set(n,null);const e=this.type(t);if(e&&e.attributes)for(const n of e.attributes)this._attributeMap.set(t+":"+n.name,n)}return this._attributeMap.get(n)}},openvino.XmlReader=class{static read(t){const e=(t,e)=>{const n=[];let s=t.firstChild;for(;null!=s;)1==s.nodeType&&s.nodeName==e&&n.push(s),s=s.nextSibling;return n},n=(t,n)=>{const s=e(t,n);if(s.length>1)throw new openvino.Error("Element '"+t.nodeName+"' has multiple '"+n+"' elements.");return s.length>0?s[0]:null},s=(t,s)=>{const i=n(t,s);return i?e(i,"port").map((t=>({id:t.getAttribute("id"),precision:t.getAttribute("precision"),dims:Array.prototype.slice.call(t.getElementsByTagName("dim")).map((t=>parseInt(t.textContent.trim(),10)))}))):[]},i=t=>{const a=n(t,"layers");return a?e(a,"layer").map((t=>{const e=n(t,"data"),a=n(t,"blobs"),r={id:t.getAttribute("id"),name:t.getAttribute("name"),type:t.getAttribute("type"),precision:t.getAttribute("precision"),data:e?Array.from(e.attributes).map((t=>({name:t.name,value:t.value}))):[],blobs:a?Array.from(a.childNodes).filter((t=>1===t.nodeType)).map((t=>({name:t.nodeName,precision:t.getAttribute("precision"),offset:parseInt(t.getAttribute("offset"),10),size:parseInt(t.getAttribute("size"),10)}))):[],inputs:s(t,"input"),outputs:s(t,"output")};if("TensorIterator"===r.type){r.back_edges=o(t,"back_edges");const e=n(t,"body");e&&(r.body={layers:i(e),edges:o(e)});const s=n(t,"port_map");if(s){r.port_map={input:[],output:[]};for(const t of Array.from(s.childNodes).filter((t=>1===t.nodeType))){const e={axis:t.getAttribute("axis"),external_port_id:t.getAttribute("external_port_id"),internal_layer_id:t.getAttribute("internal_layer_id"),internal_port_id:t.getAttribute("internal_port_id")};switch(t.nodeName){case"input":r.port_map.input.push(e);break;case"output":r.port_map.output.push(e)}}}}return r})):[]},o=(t,s)=>{const i={},o=n(t,s||"edges");if(o)for(const t of e(o,"edge")){const e=t.getAttribute("from-layer"),n=t.getAttribute("from-port");i[t.getAttribute("to-layer")+":"+t.getAttribute("to-port")]=e+":"+n}return i};return{name:t.getAttribute("name"),batch:t.getAttribute("batch"),version:t.getAttribute("version"),layers:i(t),edges:o(t)}}},openvino.Error=class extends Error{constructor(t){super(t),this.name="Error loading OpenVINO model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=openvino.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9a16703f3c40386abe6db2e5e168c66aa23a427e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-metadata.json @@ -0,0 +1 @@ +[{"name":"conv2d","schema":{"category":"Layer","attributes":[{"name":"workspace_size_MB","default":4096},{"name":"fuse_residual_connection","default":false},{"name":"fuse_eltwise","default":false},{"name":"fuse_relu","default":false},{"name":"data_format","default":"AnyLayout"},{"name":"groups","default":1},{"name":"paddings","default":[0,0]},{"name":"dilations","default":[1,1]},{"name":"strides","default":[1,1]}]}},{"name":"depthwise_conv2d","schema":{"category":"Layer","attributes":[{"name":"workspace_size_MB","default":4096},{"name":"fuse_residual_connection","default":false},{"name":"data_format","default":"AnyLayout"},{"name":"groups","default":1},{"name":"fuse_relu","default":false}]}},{"name":"relu","schema":{"category":"Activation"}},{"name":"softmax","schema":{"category":"Activation","attributes":[{"name":"data_format","default":"AnyLayout"}]}},{"name":"batch_norm","schema":{"category":"Normalization","attributes":[{"name":"momentum","default":0.8999999761581421},{"name":"epsilon","default":0.000009999999747378752},{"name":"fuse_with_relu","default":false},{"name":"data_layout","default":"NCHW"}]}},{"name":"pool2d","schema":{"category":"Pool","attributes":[{"name":"data_format","default":"AnyLayout"},{"name":"ceil_mode","default":false},{"name":"global_pooling","default":false},{"name":"exclusive","default":true},{"name":"pooling_type","default":"max"},{"name":"paddings","default":[0,0]}]}},{"name":"elementwise_add","schema":{"attributes":[{"name":"axis","default":-1}]}},{"name":"concat","schema":{"category":"Tensor"}},{"name":"reshape","schema":{"category":"Shape"}},{"name":"reshape2","schema":{"category":"Shape"}},{"name":"lrn","schema":{"category":"Normalization","attributes":[{"name":"alpha","default":0.00009999999747378752},{"name":"beta","default":0.75},{"name":"k","default":1}]}},{"name":"pad2d","schema":{"category":"Tensor"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..8efbe3e9c82920e4e9197e421694d0e76cb1b2ec --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("paddle");$root.paddle={},$root.paddle.framework={},$root.paddle.framework.proto={},$root.paddle.framework.proto.Version=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.Version,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.version=o.int64();break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.Version.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.paddle.framework.proto.AttrType={INT:0,FLOAT:1,STRING:2,INTS:3,FLOATS:4,STRINGS:5,BOOLEAN:6,BOOLEANS:7,BLOCK:8,LONG:9,BLOCKS:10,LONGS:11},$root.paddle.framework.proto.OpDesc=class{constructor(){this.inputs=[],this.outputs=[],this.attrs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 3:e.type=o.string();break;case 1:e.inputs.push($root.paddle.framework.proto.OpDesc.Var.decode(o,o.uint32()));break;case 2:e.outputs.push($root.paddle.framework.proto.OpDesc.Var.decode(o,o.uint32()));break;case 4:e.attrs.push($root.paddle.framework.proto.OpDesc.Attr.decode(o,o.uint32()));break;case 5:e.is_target=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.OpDesc.prototype.type="",$root.paddle.framework.proto.OpDesc.prototype.is_target=!1,$root.paddle.framework.proto.OpDesc.Attr=class{constructor(){this.ints=[],this.floats=[],this.strings=[],this.bools=[],this.blocks_idx=[],this.longs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc.Attr,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=o.int32();break;case 3:e.i=o.int32();break;case 4:e.f=o.float();break;case 5:e.s=o.string();break;case 6:e.ints=o.array(e.ints,(()=>o.int32()),r);break;case 7:e.floats=o.floats(e.floats,r);break;case 8:e.strings.push(o.string());break;case 10:e.b=o.bool();break;case 11:e.bools=o.array(e.bools,(()=>o.bool()),r);break;case 12:e.block_idx=o.int32();break;case 13:e.l=o.int64();break;case 14:e.blocks_idx=o.array(e.blocks_idx,(()=>o.int32()),r);break;case 15:e.longs=o.array(e.longs,(()=>o.int64()),r);break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.OpDesc.Attr.prototype.name="",$root.paddle.framework.proto.OpDesc.Attr.prototype.type=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.i=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.f=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.s="",$root.paddle.framework.proto.OpDesc.Attr.prototype.b=!1,$root.paddle.framework.proto.OpDesc.Attr.prototype.block_idx=0,$root.paddle.framework.proto.OpDesc.Attr.prototype.l=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.paddle.framework.proto.OpDesc.Var=class{constructor(){this.arguments=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpDesc.Var,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.parameter=o.string();break;case 2:e.arguments.push(o.string());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"parameter"))throw new protobuf.Error("Excepted 'parameter'.");return e}},$root.paddle.framework.proto.OpDesc.Var.prototype.parameter="",$root.paddle.framework.proto.OpProto=class{constructor(){this.inputs=[],this.outputs=[],this.attrs=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.type=o.string();break;case 2:e.inputs.push($root.paddle.framework.proto.OpProto.Var.decode(o,o.uint32()));break;case 3:e.outputs.push($root.paddle.framework.proto.OpProto.Var.decode(o,o.uint32()));break;case 4:e.attrs.push($root.paddle.framework.proto.OpProto.Attr.decode(o,o.uint32()));break;case 5:e.comment=o.string();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.prototype.type="",$root.paddle.framework.proto.OpProto.prototype.comment="",$root.paddle.framework.proto.OpProto.Var=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto.Var,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.comment=o.string();break;case 3:e.duplicable=o.bool();break;case 4:e.intermediate=o.bool();break;case 5:e.dispensable=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.Var.prototype.name="",$root.paddle.framework.proto.OpProto.Var.prototype.comment="",$root.paddle.framework.proto.OpProto.Var.prototype.duplicable=!1,$root.paddle.framework.proto.OpProto.Var.prototype.intermediate=!1,$root.paddle.framework.proto.OpProto.Var.prototype.dispensable=!1,$root.paddle.framework.proto.OpProto.Attr=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpProto.Attr,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=o.int32();break;case 3:e.comment=o.string();break;case 4:e.generated=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");if(!Object.prototype.hasOwnProperty.call(e,"comment"))throw new protobuf.Error("Excepted 'comment'.");return e}},$root.paddle.framework.proto.OpProto.Attr.prototype.name="",$root.paddle.framework.proto.OpProto.Attr.prototype.type=0,$root.paddle.framework.proto.OpProto.Attr.prototype.comment="",$root.paddle.framework.proto.OpProto.Attr.prototype.generated=!1,$root.paddle.framework.proto.VarType=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.type=o.int32();break;case 2:e.selected_rows=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 3:e.lod_tensor=$root.paddle.framework.proto.VarType.LoDTensorDesc.decode(o,o.uint32());break;case 4:e.tensor_array=$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.decode(o,o.uint32());break;case 5:e.reader=$root.paddle.framework.proto.VarType.ReaderDesc.decode(o,o.uint32());break;case 7:e.tuple=$root.paddle.framework.proto.VarType.Tuple.decode(o,o.uint32());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.VarType.prototype.type=0,$root.paddle.framework.proto.VarType.prototype.selected_rows=null,$root.paddle.framework.proto.VarType.prototype.lod_tensor=null,$root.paddle.framework.proto.VarType.prototype.tensor_array=null,$root.paddle.framework.proto.VarType.prototype.reader=null,$root.paddle.framework.proto.VarType.prototype.tuple=null,$root.paddle.framework.proto.VarType.Type={BOOL:0,INT16:1,INT32:2,INT64:3,FP16:4,FP32:5,FP64:6,SIZE_T:19,UINT8:20,INT8:21,LOD_TENSOR:7,SELECTED_ROWS:8,FEED_MINIBATCH:9,FETCH_LIST:10,STEP_SCOPES:11,LOD_RANK_TABLE:12,LOD_TENSOR_ARRAY:13,PLACE_LIST:14,READER:15,RAW:17,TUPLE:18},$root.paddle.framework.proto.VarType.TensorDesc=class{constructor(){this.dims=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.TensorDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.data_type=o.int32();break;case 2:e.dims=o.array(e.dims,(()=>o.int64()),r);break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"data_type"))throw new protobuf.Error("Excepted 'data_type'.");return e}},$root.paddle.framework.proto.VarType.TensorDesc.prototype.data_type=0,$root.paddle.framework.proto.VarType.LoDTensorDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.LoDTensorDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.tensor=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 2:e.lod_level=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"tensor"))throw new protobuf.Error("Excepted 'tensor'.");return e}},$root.paddle.framework.proto.VarType.LoDTensorDesc.prototype.tensor=null,$root.paddle.framework.proto.VarType.LoDTensorDesc.prototype.lod_level=0,$root.paddle.framework.proto.VarType.LoDTensorArrayDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.LoDTensorArrayDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.tensor=$root.paddle.framework.proto.VarType.TensorDesc.decode(o,o.uint32());break;case 2:e.lod_level=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"tensor"))throw new protobuf.Error("Excepted 'tensor'.");return e}},$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.prototype.tensor=null,$root.paddle.framework.proto.VarType.LoDTensorArrayDesc.prototype.lod_level=0,$root.paddle.framework.proto.VarType.ReaderDesc=class{constructor(){this.lod_tensor=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.ReaderDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.lod_tensor.push($root.paddle.framework.proto.VarType.LoDTensorDesc.decode(o,o.uint32()));break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.VarType.Tuple=class{constructor(){this.element_type=[]}static decode(o,r){const e=new $root.paddle.framework.proto.VarType.Tuple,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.element_type=o.array(e.element_type,(()=>o.int32()),r);break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.VarDesc=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.VarDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.name=o.string();break;case 2:e.type=$root.paddle.framework.proto.VarType.decode(o,o.uint32());break;case 3:e.persistable=o.bool();break;case 4:e.need_check_feed=o.bool();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"name"))throw new protobuf.Error("Excepted 'name'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.VarDesc.prototype.name="",$root.paddle.framework.proto.VarDesc.prototype.type=null,$root.paddle.framework.proto.VarDesc.prototype.persistable=!1,$root.paddle.framework.proto.VarDesc.prototype.need_check_feed=!1,$root.paddle.framework.proto.BlockDesc=class{constructor(){this.vars=[],this.ops=[]}static decode(o,r){const e=new $root.paddle.framework.proto.BlockDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.idx=o.int32();break;case 2:e.parent_idx=o.int32();break;case 3:e.vars.push($root.paddle.framework.proto.VarDesc.decode(o,o.uint32()));break;case 4:e.ops.push($root.paddle.framework.proto.OpDesc.decode(o,o.uint32()));break;case 5:e.forward_block_idx=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"idx"))throw new protobuf.Error("Excepted 'idx'.");if(!Object.prototype.hasOwnProperty.call(e,"parent_idx"))throw new protobuf.Error("Excepted 'parent_idx'.");return e}},$root.paddle.framework.proto.BlockDesc.prototype.idx=0,$root.paddle.framework.proto.BlockDesc.prototype.parent_idx=0,$root.paddle.framework.proto.BlockDesc.prototype.forward_block_idx=-1,$root.paddle.framework.proto.CompatibleInfo=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.CompatibleInfo,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.version=o.string();break;case 2:e.type=o.int32();break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"version"))throw new protobuf.Error("Excepted 'version'.");if(!Object.prototype.hasOwnProperty.call(e,"type"))throw new protobuf.Error("Excepted 'type'.");return e}},$root.paddle.framework.proto.CompatibleInfo.prototype.version="",$root.paddle.framework.proto.CompatibleInfo.prototype.type=0,$root.paddle.framework.proto.CompatibleInfo.Type={COMPATIBLE:0,DEFINITELY_NOT:1,POSSIBLE:2,BUG_FIX:3,PRECISION_CHANGE:4},$root.paddle.framework.proto.OpCompatibleMap=class{constructor(){this.pair=[]}static decode(o,r){const e=new $root.paddle.framework.proto.OpCompatibleMap,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.pair.push($root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.decode(o,o.uint32()));break;case 2:e.default_required_version=o.string();break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.OpCompatibleMap.prototype.default_required_version="",$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair=class{constructor(){}static decode(o,r){const e=new $root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.op_name=o.string();break;case 2:e.compatible_info=$root.paddle.framework.proto.CompatibleInfo.decode(o,o.uint32());break;default:o.skipType(7&r)}}if(!Object.prototype.hasOwnProperty.call(e,"op_name"))throw new protobuf.Error("Excepted 'op_name'.");if(!Object.prototype.hasOwnProperty.call(e,"compatible_info"))throw new protobuf.Error("Excepted 'compatible_info'.");return e}},$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.prototype.op_name="",$root.paddle.framework.proto.OpCompatibleMap.OpCompatiblePair.prototype.compatible_info=null,$root.paddle.framework.proto.ProgramDesc=class{constructor(){this.blocks=[]}static decode(o,r){const e=new $root.paddle.framework.proto.ProgramDesc,t=o.next(r);for(;o.end(t);){const r=o.uint32();switch(r>>>3){case 1:e.blocks.push($root.paddle.framework.proto.BlockDesc.decode(o,o.uint32()));break;case 4:e.version=$root.paddle.framework.proto.Version.decode(o,o.uint32());break;case 3:e.op_compatible_map=$root.paddle.framework.proto.OpCompatibleMap.decode(o,o.uint32());break;default:o.skipType(7&r)}}return e}},$root.paddle.framework.proto.ProgramDesc.prototype.version=null,$root.paddle.framework.proto.ProgramDesc.prototype.op_compatible_map=null; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle.js new file mode 100644 index 0000000000000000000000000000000000000000..d73321262416cc347633456a746c1ffdfb7b3a21 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/paddle.js @@ -0,0 +1 @@ +var paddle=paddle||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");paddle.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();return"__model__"===e||"paddle"===s||"pdmodel"===s}open(t,e){return e.require("./paddle-proto").then((()=>{let s=null;const a=t.identifier;try{paddle.proto=protobuf.get("paddle").paddle.framework.proto;const e=protobuf.Reader.create(t.buffer);s=paddle.proto.ProgramDesc.decode(e)}catch(t){throw new paddle.Error("File format is not paddle.ProgramDesc ("+t.message+") in '"+a+"'.")}return paddle.Metadata.open(e).then((a=>{try{const e=new Set;for(const t of s.blocks){const s=new Set;for(const e of t.vars)e.persistable&&e.type&&e.type.type!=paddle.proto.VarType.Type.FETCH_LIST&&e.type.type!=paddle.proto.VarType.Type.FEED_MINIBATCH&&s.add(e.name);for(const a of t.ops)for(const t of a.inputs)for(const a of t.arguments)s.has(a)&&e.add(a)}const r=Array.from(e).map((e=>t.request(e,null)));return Promise.all(r).then((t=>{const r=new Map,n=Array.from(e);for(let e=0;enew paddle.Model(a,s,new Map)))}catch(t){throw e.exception(t,!1),new paddle.Error(t.message)}}))}))}},paddle.Model=class{constructor(t,e,s){this._graphs=e.blocks.map((e=>new paddle.Graph(t,e,s)))}get graphs(){return this._graphs}get format(){return"PaddlePaddle"}},paddle.Graph=class{constructor(t,e,s){this._nodes=[],this._inputs=[],this._outputs=[],this._name=`blocks[${e.idx}]`;const a=new Map;for(const t of e.vars){const e=t.type&&t.type.type&&t.type.lod_tensor&&t.type.lod_tensor.tensor?new paddle.TensorType(t.type.lod_tensor.tensor):null,r=t.persistable&&t.type&&t.type.type!=paddle.proto.VarType.Type.FETCH_LIST&&t.type.type!=paddle.proto.VarType.Type.FEED_MINIBATCH?new paddle.Tensor(e,s.get(t.name)):null;a.set(t.name,new paddle.Argument(t.name,e,r))}const r={};for(let t=0;tr[t]?r[t]:t));for(const s of e.ops[t].outputs)s.arguments=s.arguments.map((e=>{if(r[e]){const s=e+"\n"+t.toString();return r[e]=s,s}return r[e]=e,e}))}for(const t of e.ops){for(const e of t.inputs)for(const t of e.arguments){const e=t;a.has(e)||a.set(e,new paddle.Argument(e,null,null))}for(const e of t.outputs)for(const t of e.arguments){const e=t;a.has(e)||a.set(e,new paddle.Argument(e,null,null))}}let n=null,i=null;for(const s of e.ops)if("feed"==s.type){const t=s.attrs.filter((t=>"col"==t.name))[0].i.toString();this._inputs.push(new paddle.Parameter(t,s.outputs[0].arguments.map((t=>a.get(t)))))}else if("fetch"==s.type){const t=s.attrs.filter((t=>"col"==t.name))[0].i.toString();this._outputs.push(new paddle.Parameter(t,s.inputs[0].arguments.map((t=>a.get(t)))))}else{const e=new paddle.Node(t,s,a);1==s.inputs.length&&1==s.inputs[0].arguments.length&&s.outputs.length>=1&&1==s.outputs[0].arguments.length&&s.inputs[0].arguments[0].split("\n").shift()==s.outputs[0].arguments[0].split("\n").shift()&&n&&i==s.inputs[0].arguments[0].split("\n").shift()?n.chain.push(e):(this._nodes.push(e),n=null,i=null,1==s.outputs.length&&1==s.outputs[0].arguments.length&&(n=e,i=s.outputs[0].arguments[0].split("\n").shift()))}}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},paddle.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},paddle.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new paddle.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type?this._type:this._initializer?this._initializer.type:null}get initializer(){return this._initializer}},paddle.Node=class{constructor(t,e,s){this._metadata=t,this._type=e.type,this._attributes=[],this._inputs=[],this._outputs=[],this._chain=[];for(const s of e.attrs){const e=t.attribute(this._type,this._name);this._attributes.push(new paddle.Attribute(e,s))}for(const t of e.inputs)t.arguments.length>0&&this._inputs.push(new paddle.Parameter(t.parameter,t.arguments.map((t=>s.get(t)))));for(const t of e.outputs)t.arguments.length>0&&this._outputs.push(new paddle.Parameter(t.parameter,t.arguments.map((t=>s.get(t)))));this._update(this._inputs,"X"),this._update(this._inputs,"Input"),this._update(this._outputs,"Y"),this._update(this._outputs,"Out")}get type(){return this._type}get name(){return""}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}_update(t,e){let s=null;for(let a=0;at==e[s])))&&(this._visible=!1)}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},paddle.Tensor=class{constructor(t,e){if(this._type=t,e&&e.length>20&&e.slice(0,16).every((t=>0===t))){const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(16,!0);this._data=e.slice(20+t)}}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return paddle.Tensor._stringify(e,""," ")}_context(){const t={index:0,count:0,state:null};if(!this._data)return t.state="Tensor data is empty.",t;if(!this._type)return t.state="Tensor has no data type.",t;switch(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.view=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t.dataType){case"float32":case"int32":case"int64":break;default:t.state="Tensor data type '"+t.dataType+"' is not implemented."}return t}_decode(t,e){const s=0!==t.shape.length?t.shape:[1],a=[],r=s[e];if(e==s.length-1)for(let e=0;et.limit)return a.push("..."),a;switch(t.dataType){case"float32":a.push(t.view.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"int32":a.push(t.view.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":a.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++}}else for(let s=0;st.limit)return a.push("..."),a;a.push(this._decode(t,e+1))}return 0==t.shape.length?a[0]:a}static _stringify(t,e,s){if(Array.isArray(t)){const a=[];a.push(e+"[");const r=t.map((t=>paddle.Tensor._stringify(t,e+s,s)));return r.length>0&&a.push(r.join(",\n")),a.push(e+"]"),a.join("\n")}return"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},paddle.TensorType=class{constructor(t){switch(t.data_type){case paddle.proto.VarType.Type.INT32:this._dataType="int32";break;case paddle.proto.VarType.Type.INT64:this._dataType="int64";break;case paddle.proto.VarType.Type.FP32:this._dataType="float32";break;case paddle.proto.VarType.Type.FP64:this._dataType="float64";break;default:this._dataType="?"}this._shape=new paddle.TensorShape(t.dims)}get dataType(){return this._dataType}get shape(){return this._shape}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},paddle.TensorShape=class{constructor(t){t=t.map((t=>t.toNumber())),this._dimensions=t.map((t=>-1!=t?t:"?"))}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},paddle.Metadata=class{static open(t){return paddle.Metadata._metadata?Promise.resolve(paddle.Metadata._metadata):t.request(null,"paddle-metadata.json","utf-8").then((t=>(paddle.Metadata._metadata=new paddle.Metadata(t),paddle.Metadata._metadata))).catch((()=>(paddle.Metadata._metadata=new paddle.Metadata(null),paddle.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]||null}attribute(t,e){let s=this._attributeCache[t];if(!s){s={};const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const t of e.attributes)s[t.name]=t;this._attributeCache[t]=s}return s[e]||null}},paddle.Error=class extends Error{constructor(t){super(t),this.name="Error loading PaddlePaddle model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=paddle.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/pickle.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/pickle.js new file mode 100644 index 0000000000000000000000000000000000000000..c4714eea288526ea65caed42b228b4311dc49ddb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/pickle.js @@ -0,0 +1 @@ +var pickle=pickle||{};pickle.Unpickler=class{constructor(e){this._reader=new pickle.Reader(e,0)}load(e,s){const t=this._reader,p=[];let i=[];const o=new Map;for(;t.position5)throw new pickle.Error("Unsupported protocol version '"+e+"'.");break}case pickle.OpCode.GLOBAL:i.push([t.line(),t.line()].join("."));break;case pickle.OpCode.STACK_GLOBAL:i.push([i.pop(),i.pop()].reverse().join("."));break;case pickle.OpCode.PUT:{const e=parseInt(t.line(),10);o.set(e,i[i.length-1]);break}case pickle.OpCode.OBJ:{const s=i;i=p.pop(),i.push(e(s.pop(),s));break}case pickle.OpCode.GET:{const e=parseInt(t.line(),10);i.push(o.get(e));break}case pickle.OpCode.POP:i.pop();break;case pickle.OpCode.POP_MARK:i=p.pop();break;case pickle.OpCode.DUP:i.push(i[i.length-1]);break;case pickle.OpCode.PERSID:i.push(s(t.line()));break;case pickle.OpCode.BINPERSID:i.push(s(i.pop()));break;case pickle.OpCode.REDUCE:{const s=i.pop(),t=i.pop();i.push(e(t,s));break}case pickle.OpCode.NEWOBJ:{const s=i.pop(),t=i.pop();i.push(e(t,s));break}case pickle.OpCode.BINGET:i.push(o.get(t.byte()));break;case pickle.OpCode.LONG_BINGET:i.push(o.get(t.uint32()));break;case pickle.OpCode.BINPUT:o.set(t.byte(),i[i.length-1]);break;case pickle.OpCode.LONG_BINPUT:o.set(t.uint32(),i[i.length-1]);break;case pickle.OpCode.BININT:i.push(t.int32());break;case pickle.OpCode.BININT1:i.push(t.byte());break;case pickle.OpCode.LONG:i.push(parseInt(t.line(),10));break;case pickle.OpCode.BININT2:i.push(t.uint16());break;case pickle.OpCode.BINBYTES:i.push(t.bytes(t.int32()));break;case pickle.OpCode.SHORT_BINBYTES:i.push(t.bytes(t.byte()));break;case pickle.OpCode.FLOAT:i.push(parseFloat(t.line()));break;case pickle.OpCode.BINFLOAT:i.push(t.float64());break;case pickle.OpCode.INT:{const e=t.line();"01"==e?i.push(!0):"00"==e?i.push(!1):i.push(parseInt(e,10));break}case pickle.OpCode.EMPTY_LIST:case pickle.OpCode.EMPTY_TUPLE:case pickle.OpCode.EMPTY_SET:i.push([]);break;case pickle.OpCode.ADDITEMS:{const e=i;i=p.pop();const s=i[i.length-1];for(let t=0;t=t)p[o++]=s;else switch(s=e.charCodeAt(i++),s){case 39:p[o++]=39;break;case 92:p[o++]=92;break;case 34:p[o++]=34;break;case 114:p[o++]=13;break;case 110:p[o++]=10;break;case 116:p[o++]=9;break;case 98:p[o++]=8;break;case 88:case 120:{const s=i-1,c=o;for(let a=0;a<2;a++){if(i>=t){i=s,o=c,p[o]=92;break}let a=e.charCodeAt(i++);if(a=a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:a>=48&&a<=57?a-48:-1,-1===a){i=s,o=c,p[o]=92;break}p[o]=p[o]<<4|a}o++;break}default:if(s<48||s>57)p[o++]=92,p[o++]=s;else{i--;const s=i,c=o;for(let a=0;a<3;a++){if(i>=t){i=s,o=c,p[o]=92;break}const a=e.charCodeAt(i++);if(a<48||a>57){i=s,o=c,p[o]=92;break}p[o]=p[o]<<3|a-48}o++}}}return p.slice(0,o)}},pickle.OpCode={MARK:40,EMPTY_TUPLE:41,STOP:46,POP:48,POP_MARK:49,DUP:50,BINBYTES:66,SHORT_BINBYTES:67,FLOAT:70,BINFLOAT:71,INT:73,BININT:74,BININT1:75,LONG:76,BININT2:77,NONE:78,PERSID:80,BINPERSID:81,REDUCE:82,STRING:83,BINSTRING:84,SHORT_BINSTRING:85,UNICODE:86,BINUNICODE:88,EMPTY_LIST:93,APPEND:97,BUILD:98,GLOBAL:99,DICT:100,APPENDS:101,GET:103,BINGET:104,LONG_BINGET:106,LIST:108,OBJ:111,PUT:112,BINPUT:113,LONG_BINPUT:114,SETITEM:115,TUPLE:116,SETITEMS:117,EMPTY_DICT:125,PROTO:128,NEWOBJ:129,TUPLE1:133,TUPLE2:134,TUPLE3:135,NEWTRUE:136,NEWFALSE:137,LONG1:138,LONG4:139,SHORT_BINUNICODE:140,BINUNICODE8:141,BINBYTES8:142,EMPTY_SET:143,ADDITEMS:144,FROZENSET:145,NEWOBJ_EX:146,STACK_GLOBAL:147,MEMOIZE:148,FRAME:149},pickle.Reader=class{constructor(e){e&&(this._buffer=e,this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._position=0),pickle.Reader._utf8Decoder=pickle.Reader._utf8Decoder||new TextDecoder("utf-8"),pickle.Reader._asciiDecoder=pickle.Reader._asciiDecoder||new TextDecoder("ascii")}get length(){return this._buffer.byteLength}get position(){return this._position}byte(){const e=this._position;return this.skip(1),this._dataView.getUint8(e)}bytes(e){const s=this._position;return this.skip(e),this._buffer.subarray(s,this._position)}uint16(){const e=this.position;return this.skip(2),this._dataView.getUint16(e,!0)}int32(){const e=this.position;return this.skip(4),this._dataView.getInt32(e,!0)}uint32(){const e=this.position;return this.skip(4),this._dataView.getUint32(e,!0)}float32(){const e=this.position;return this.skip(4),this._dataView.getFloat32(e,!0)}float64(){const e=this.position;return this.skip(8),this._dataView.getFloat64(e,!0)}skip(e){if(this._position+=e,this._position>this._buffer.length)throw new pickle.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}string(e,s){const t=this.bytes(e);return"utf-8"==s?pickle.Reader._utf8Decoder.decode(t):pickle.Reader._asciiDecoder.decode(t)}line(){const e=this._buffer.indexOf(10,this._position);if(-1==e)throw new pickle.Error("Could not find end of line.");const s=e-this._position,t=this.string(s,"ascii");return this.skip(1),t}},pickle.Error=class extends Error{constructor(e){super(e),this.name="Unpickle Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Unpickler=pickle.Unpickler); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/protobuf.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/protobuf.js new file mode 100644 index 0000000000000000000000000000000000000000..05ddc6f56e22aadab680651a5cc5dfb84201b804 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/protobuf.js @@ -0,0 +1 @@ +var protobuf=protobuf||{},long=long||{Long:require("long")};protobuf.get=t=>(protobuf._map=protobuf._map||new Map,protobuf._map.has(t)||protobuf._map.set(t,{}),protobuf._map.get(t)),protobuf.Reader=class{constructor(t){this._buffer=t,this._length=t.length,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._decoder=new TextDecoder("utf-8")}static create(t){return new protobuf.Reader(t)}next(t){return void 0===t?this._length:this._position+t}end(t){return this._positionthis._length)throw this._indexOutOfRangeError(t);return this._position+=t,this._buffer.slice(i,o)}uint32(){let t=4294967295;if(t=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return t;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=4,this._dataView.getFloat32(t,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=8,this._dataView.getFloat64(t,!0)}array(t,i,o){if(2==(7&o)){const o=this.uint32()+this._position;for(;this._position0)throw new protobuf.Error("Invalid packed float array.");const i=this.uint32(),o=this._position+i,s=i>>>2;t=i>1048576?new Float32Array(s):new Array(s);let e=this._position;for(let i=0;i0)throw new protobuf.Error("Invalid packed float array.");const i=this.uint32(),o=this._position+i,s=i>>>3;t=i>1048576?new Float64Array(s):new Array(s);let e=this._position;for(let i=0;ithis._length)throw this._indexOutOfRangeError(t);this._position+=t}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw new protobuf.Error("invalid wire type "+t+" at offset "+this._position)}}pair(t,i,o){this.skip(),this._position++;const s="object"==typeof i?protobuf.LongBits.hash(i()):i();this._position++;const e=o();t[s]=e}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const t=this._readFixed32();this._position+=4;const i=this._readFixed32();return new protobuf.LongBits(t,i)}_readLongVarint(){const t=new protobuf.LongBits(0,0);let i=0;if(!(this._length-this._position>4)){for(;i<3;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t}return t.lo=(t.lo|(127&this._buffer[this._position++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t;if(t.lo=(t.lo|(127&this._buffer[this._position])<<28)>>>0,t.hi=(t.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return t;if(i=0,this._length-this._position>4){for(;i<5;++i)if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}else for(;i<5;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}throw new protobuf.Error("Invalid varint encoding.")}_indexOutOfRangeError(t){return RangeError("index out of range: "+this._position+" + "+(t||1)+" > "+this._length)}},protobuf.TextReader=class{constructor(t){this._text=t,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(t){return new protobuf.TextReader(t)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const t=this.peek();return this._depth>0&&"}"===t?(this.expect("}"),this.match(";"),this._depth--,!0):""===t}tag(){const t=this.read(),i=this.peek();return"["!==i&&"{"!==i&&this.expect(":"),t}assert(t){const i=this.tag();if(i!==t)throw new protobuf.Error("Unexpected '"+i+"' instead of '"+t+"'"+this.location())}integer(){const t=this.read(),i=Number.parseInt(t,10);if(Number.isNaN(t-i))throw new protobuf.Error("Couldn't parse integer '"+t+"'"+this.location());return this.semicolon(),i}float(){let t=this.read();if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;t.endsWith("f")&&(t=t.substring(0,t.length-1));const i=Number.parseFloat(t);if(Number.isNaN(t-i))throw new protobuf.Error("Couldn't parse float '"+t+"'"+this.location());return this.semicolon(),i}string(){const t=this.read();if(t.length<2)throw new protobuf.Error("String is too short"+this.location());const i=t[0];if("'"!==i&&'"'!==i)throw new protobuf.Error("String is not in quotes"+this.location());if(i!==t[t.length-1])throw new protobuf.Error("String quotes do not match"+this.location());const o=t.substring(1,t.length-1);return this.semicolon(),o}boolean(){const t=this.read();switch(t){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new protobuf.Error("Couldn't parse boolean '"+t+"'"+this.location())}bytes(){const t=this.string();let i=0,o=0;const s=t.length,e=new Uint8Array(s);for(;i=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());switch(r=t.charCodeAt(i++),r){case 39:e[o++]=39;break;case 92:e[o++]=92;break;case 34:e[o++]=34;break;case 114:e[o++]=13;break;case 110:e[o++]=10;break;case 116:e[o++]=9;break;case 98:e[o++]=8;break;case 88:case 120:for(let r=0;r<2;r++){if(i>=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());let r=t.charCodeAt(i++);if(r=r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r>=48&&r<=57?r-48:-1,-1===r)throw new protobuf.Error("Unexpected hex digit '"+r+"' in bytes string"+this.location());e[o]=e[o]<<4|r}o++;break;default:if(r<48||r>57)throw new protobuf.Error("Unexpected character '"+r+"' in bytes string"+this.location());i--;for(let r=0;r<3;r++){if(i>=s)throw new protobuf.Error("Unexpected end of bytes string"+this.location());const r=t.charCodeAt(i++);if(r<48||r>57)throw new protobuf.Error("Unexpected octal digit '"+r+"' in bytes string"+this.location());e[o]=e[o]<<3|r-48}o++}}}return e.slice(0,o)}enum(t){const i=this.read();if(!Object.prototype.hasOwnProperty.call(t,i)){const t=Number.parseInt(i,10);if(!Number.isNaN(i-t))return this.semicolon(),t;throw new protobuf.Error("Couldn't parse enum '"+i+"'"+this.location())}return this.semicolon(),t[i]}any(t){if(this.match("[")){this.read();const i=this._position,o=this._text.indexOf("]",i);if(-1===o||o>=this.next)throw new protobuf.Error("End of Any type_url not found"+this.location());return t.type_url=this._text.substring(i,o),this._position=o+1,t.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(t,i,o){let s,e;for(this.start();!this.end();)switch(this.tag()){case"key":s=i();break;case"value":e=o()}t[s]=e}array(t,i){if(this.first())for(;!this.last();)t.push(i()),this.next();else t.push(i())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const t=this.peek();","!==t?"]"!==t&&this.handle(t):this.read()}skip(){let t=this.peek();if("{"===t){const i=this._position,o=this._depth;for(this.start();!this.end()||o=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let t=this._text[this._position];if("["===t&&this._position+2="a"&&i<="z"||i>="A"&&i<="Z")for(t++;t="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||"."===i||"/"===i)&&"]"===i)return this._token=this._text.substring(this._position,t),this._token}if("{"===t||"}"===t||":"===t||"["===t||","===t||"]"===t||";"===t)return this._token=t,this._token;let i=this._position+1;if(t>="a"&&t<="z"||t>="A"&&t<="Z"||"_"===t||"$"===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if(t>="0"&&t<="9"||"-"===t||"+"===t||"."===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t||"."===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if('"'===t||"'"===t){const o=t;for(;i>>0,this.hi=i>>>0}toLong(t){return protobuf.Long?new protobuf.Long(0|this.lo,0|this.hi,t):{low:0|this.lo,high:0|this.hi,unsigned:t}}toNumber(t){if(!t&&this.hi>>>31){const t=1+~this.lo>>>0;let i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}from(t){if("number"==typeof t)return protobuf.LongBits.fromNumber(t);if("string"==typeof t||t instanceof String){if(!protobuf.Long)return protobuf.LongBits.fromNumber(parseInt(t,10));t=protobuf.Long.fromString(t)}return t.low||t.high?new protobuf.LongBits(t.low>>>0,t.high>>>0):protobuf.LongBits.zero}hash(t){return t?protobuf.LongBits.from(t).toHash():"\0\0\0\0\0\0\0\0"}},protobuf.LongBits.zero=new protobuf.LongBits(0,0),protobuf.LongBits.zero.toNumber=function(){return 0},protobuf.LongBits.zero.zzDecode=function(){return this},protobuf.Error=class extends Error{constructor(t){super(t),this.name="Protocol Buffer Error",this.message=t}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Reader=protobuf.Reader,module.exports.TextReader=protobuf.TextReader,module.exports.Error=protobuf.Error,module.exports.Long=protobuf.Long,module.exports.get=protobuf.get); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/python.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/python.js new file mode 100644 index 0000000000000000000000000000000000000000..49e461c4c18def2afac95d5fddd66c928df956d5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/python.js @@ -0,0 +1 @@ +var python=python||{};python.Parser=class{constructor(e,t){this._tokenizer=new python.Tokenizer(e,t),python.Parser._precedence||(python.Parser._precedence={or:2,and:3,not:4,in:5,instanceof:5,is:5,"<":5,">":5,"<=":5,">=":5,"<>":5,"==":5,"!=":5,"|":6,"^":7,"&":8,"<<":9,">>":9,"+":10,"-":10,"*":11,"@":11,"/":11,"//":11,"%":11,"~":13,"**":14})}parse(){const e=this._node("program");for(e.body=[];!this._tokenizer.match("eof");){const t=this._parseStatement();if(t)e.body.push(t);else if(!(this._tokenizer.eat("\n")||this._tokenizer.eat(";")||"eof"==this._tokenizer.peek().type||this._tokenizer.eat("indent")&&"eof"==this._tokenizer.peek().type))throw new python.Error("Unknown statement"+this._tokenizer.location())}return e}_parseSuite(){const e=this._node("block");e.statements=[];let t=null;if(this._tokenizer.eat("\n")){if(this._tokenizer.eat("indent"))for(;!this._tokenizer.eat("eof")&&!this._tokenizer.eat("dedent");)if(!this._tokenizer.eat(";"))if(t=this._parseStatement(),t)e.statements.push(t);else if(!this._tokenizer.eat("\n")&&!this._tokenizer.match("dedent")&&!this._tokenizer.match("eof"))throw new python.Error("Empty statement"+this._tokenizer.location())}else if(!this._tokenizer.eat("eof")){for(;!this._tokenizer.match("\n")&&!this._tokenizer.match("eof")&&!this._tokenizer.match("dedent");)if(!this._tokenizer.eat(";")){if(t=this._parseStatement(),!t)throw new python.Error("Empty statement"+this._tokenizer.location());e.statements.push(t)}this._tokenizer.eat("\n")}return e}_parseStatement(){let e=this._node();if(e=this._eat("id","break"),e)return e;if(e=this._eat("id","continue"),e)return e;if(e=this._eat("id","return"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","raise"),e)return e.exception=this._parseExpression(-1,["from"]),this._tokenizer.eat("id","from")?e.from=this._parseExpression():this._tokenizer.eat(",")&&(e.exception=[e.exception],e.exception.push(this._parseExpression()),this._tokenizer.eat(",")&&e.exception.push(this._parseExpression())),e;if(e=this._eat("id","assert"),e){for(e.condition=this._parseExpression();this._tokenizer.eat(",");)e.condition={type:"list",value:[e.condition]},e.condition.value.push(this._parseExpression());return e}if(e=this._eat("id","exec"),e){if(e.variable=this._parseExpression(-1,["in"]),this._tokenizer.eat("in"))do{e.target=e.target||[],e.target.push(this._parseExpression(-1,["in"],!1))}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","global"),e){e.variable=[];do{e.variable.push(this._parseName())}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","nonlocal"),e){e.variable=[];do{e.variable.push(this._parseName())}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","import"),e){e.modules=[];do{const t=this._node("module");t.name=this._parseExpression(-1,[],!1),this._tokenizer.eat("id","as")&&(t.as=this._parseExpression(-1,[],!1)),e.modules.push(t)}while(this._tokenizer.eat(","));return e}if(e=this._eat("id","from"),e){const t=this._tokenizer.peek();t&&Array.from(t.type).every((e=>"."==e))?(e.from=this._eat(t.type),e.from.expression=this._parseExpression()):e.from=this._parseExpression(),this._tokenizer.expect("id","import"),e.import=[];const i=this._tokenizer.eat("(");do{const t=this._node();t.symbol=this._parseExpression(-1,[],!1),this._tokenizer.eat("id","as")&&(t.as=this._parseExpression(-1,[],!1)),e.import.push(t)}while(this._tokenizer.eat(","));return i&&this._tokenizer.expect(")"),e}if(e=this._eat("id","class"),e)return e.name=this._parseName().value,"("===this._tokenizer.peek().value&&(e.base=this._parseArguments()),this._tokenizer.expect(":"),e.body=this._parseSuite(),e;const t=this._eat("id","async");if(t&&!this._tokenizer.match("id","def")&&!this._tokenizer.match("id","with")&&!this._tokenizer.match("id","for"))throw new python.Error("Expected 'def', 'with' or 'for'"+this._tokenizer.location());if(e=this._eat("id","def"),e)return t&&(e.async=t),e.name=this._parseName().value,this._tokenizer.expect("("),e.parameters=this._parseParameters(")"),this._tokenizer.eat("->")&&(e.returnType=this._parseType()),this._tokenizer.expect(":"),e.body=this._parseSuite(),e;if(e=this._eat("id","del"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","print"),e)return e.expression=this._parseExpression(-1,[],!0),e;if(e=this._eat("id","if"),e){e.condition=this._parseExpression(),this._tokenizer.expect(":"),e.then=this._parseSuite();let t=e;for(this._tokenizer.eat("\n");this._tokenizer.eat("id","elif");)t.else=this._node("if"),t=t.else,t.condition=this._parseExpression(),this._tokenizer.expect(":"),t.then=this._parseSuite(),this._tokenizer.eat("\n");return this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),t.else=this._parseSuite()),e}if(e=this._eat("id","while"),e)return e.condition=this._parseExpression(),this._tokenizer.expect(":"),e.body=this._parseSuite(),this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),e.else=this._parseSuite()),e;if(e=this._eat("id","pass"),e)return e;if(e=this._eat("id","for"),e){for(e.variable=[],e.variable.push(this._parseExpression(-1,["in"]));this._tokenizer.eat(",");){if(this._tokenizer.match("id","in")){e.variable.push({});break}e.variable.push(this._parseExpression(-1,["in"]))}for(this._tokenizer.expect("id","in"),e.target=[],e.target.push(this._parseExpression());this._tokenizer.eat(",");){if(this._tokenizer.match(":")){e.target.push({});break}e.target.push(this._parseExpression(-1,["in"]))}return this._tokenizer.expect(":"),e.body=this._parseSuite(),this._tokenizer.eat("id","else")&&(this._tokenizer.expect(":"),e.else=this._parseSuite()),e}if(e=this._eat("id","with"),e){t&&(e.async=t),e.item=[];do{const t=this._node();t.type="with_item",t.expression=this._parseExpression(),this._tokenizer.eat("id","as")&&(t.variable=this._parseExpression()),e.item.push(t)}while(this._tokenizer.eat(","));return this._tokenizer.expect(":"),e.body=this._parseSuite(),e}if(e=this._eat("id","try"),e){for(this._tokenizer.expect(":"),e.body=this._parseSuite(),e.except=[];this._tokenizer.match("id","except");){const t=this._node("except");for(this._tokenizer.expect("id","except"),t.clause=[],t.clause.push(this._parseExpression());this._tokenizer.eat(",");){if(this._tokenizer.match(":")||this._tokenizer.match("as")){t.clause.push({});break}t.clause.push(this._parseExpression())}this._tokenizer.eat("id","as")&&(t.variable=this._parseExpression()),this._tokenizer.expect(":"),t.body=this._parseSuite(),e.except.push(t)}return this._tokenizer.match("id","else")&&(e.else=this._node("else"),this._tokenizer.expect("id","else"),this._tokenizer.expect(":"),e.else.body=this._parseSuite()),this._tokenizer.match("id","finally")&&(e.finally=this._node("finally"),this._tokenizer.expect("id","finally"),this._tokenizer.expect(":"),e.finally.body=this._parseSuite()),e}if(this._tokenizer.match("@")){if(e=this._node("decorator"),this._tokenizer.expect("@"),e.value=this._parseExpression(),!e.value||"call"!==e.value.type&&"id"!==e.value.type&&"."!==e.value.type)throw new python.Error("Invalid decorator"+this._tokenizer.location());return e}const i=this._parseExpression(-1,[],!0);if(i){if("id"==i.type&&this._tokenizer.eat(":"))return e=this._node("var"),e.name=i.value,e.location=i.location,e.variableType=this._parseExpression(-1,["="]),this._tokenizer.eat("=")&&(e.initializer=this._parseExpression()),e;let t=!1;switch(i.type){case"=":case":=":case"==":case"!=":case"+=":case"-=":case"*=":case"@=":case"/=":case"//=":case"**=":case"&=":case"|=":case"%=":case">>=":case"<<=":case">>":case"<<":case">=":case"<=":case"<":case">":case"%":case"^=":case"...":case"call":case"assert":case"raise":case"string":case"list":case"var":case".":case"[]":case"yield":case"+":case"-":case"*":case"**":case"@":case"/":case"//":case"~":case"&":case"^":case"|":case"not":case"id":case"number":case"in":case"and":case"or":case"if":case"for":case"tuple":case"lambda":case"await":t=!0}if(t)return i;throw new python.Error("Unhandled expression"+this._tokenizer.location())}return null}_parseExpression(e,t,i){e=e||-1;const s=new Set(t),n=[];for(;;){let r=this._node();const o=this._tokenizer.peek();if(1==n.length&&s.has(o.value))break;const h=python.Parser._precedence[o.value];if(h&&h>=e){if(this._tokenizer.read(),r.type=o.value,"id"!=o.type||"in"!==o.value&&"not"!==o.value){if("~"==o.value){r.type="~",r.expression=this._parseExpression(h,t,!1!==i),n.push(r);continue}"id"==o.type&&"is"==o.value&&this._tokenizer.eat("id","not")&&(r.type="is not")}else if("in"===o.value)r.type="in";else{if(!this._tokenizer.eat("id","in")){r.type="not",r.expression=this._parseExpression(h,t,!1!==i),n.push(r);continue}r.type="not in"}r.left=n.pop(),r.right=this._parseExpression(h,t,!1!==i),n.push(r);continue}if(this._tokenizer.eat(":=")){r.type=":=",r.target=n.pop(),r.expression=this._parseExpression(-1,t,!1!==i),n.push(r);continue}if(this._tokenizer.eat("=")){r.type="=",r.target=n.pop(),r.expression=this._parseExpression(-1,t,!1!==i),n.push(r);continue}switch(o.type){case"-=":case"**=":case"*=":case"//=":case"/=":case"&=":case"%=":case"^=":case"+=":case"<<=":case">>=":case"|=":case"@=":r=this._node(o.type),this._tokenizer.expect(o.type),r.target=n.pop(),r.expression=this._parseExpression(-1,t,!0),n.push(r);continue}if(r=this._eat("id","if"),r){r.then=n.pop(),r.condition=this._parseExpression(),this._tokenizer.expect("id","else"),r.else=this._parseExpression(),n.push(r);continue}for(;this._tokenizer.match("id","for")||this._tokenizer.match("id","async");){const e=this._eat("id","async");if(e&&!this._tokenizer.match("id","for"))throw new python.Error("Expected 'for'"+this._tokenizer.location());if(r=this._eat("id","for"),r){for(e&&(r.async=e),r.expression=n.pop(),r.variable=this._parseExpression(-1,["in"],!0),this._tokenizer.expect("id","in"),r.target=this._parseExpression(-1,["for","if"],!0);this._tokenizer.eat("id","if");)r.condition=r.condition||[],r.condition.push(this._parseExpression(-1,["for","if"]));n.push(r)}}if(r=this._eat("id","lambda"),r){r.parameters=this._parseParameters(":"),r.body=this._parseExpression(-1,t,!1),n.push(r);continue}if(r=this._eat("id","yield"),r){if(this._tokenizer.eat("id","from"))r.from=this._parseExpression(-1,[],!0);else{r.expression=[];do{r.expression.push(this._parseExpression(-1,[],!1))}while(this._tokenizer.eat(","))}n.push(r);continue}if(r=this._eat("id","await"),r){r.expression=this._parseExpression(e,t,i),n.push(r);continue}if(r=this._eat("."),r){this._tokenizer.eat("\n"),r.target=n.pop(),r.member=this._parseName(),n.push(r);continue}if("("===this._tokenizer.peek().value){if(0==n.length){r=this._node("tuple");const e=this._parseArguments();1==e.length?n.push(e[0]):(r.value=e,n.push(r))}else r=this._node("call"),r.target=n.pop(),r.arguments=this._parseArguments(),n.push(r);continue}if("["===this._tokenizer.peek().value){0==n.length?n.push(this._parseExpressions()):(r=this._node("[]"),r.target=n.pop(),r.arguments=this._parseSlice(),n.push(r));continue}if("{"==this._tokenizer.peek().value){n.push(this._parseDictOrSetMaker());continue}r=this._node();const a=this._parseLiteral();if(a){n.length>0&&"number"==a.type&&(a.value.startsWith("-")||a.value.startsWith("+"))?(r.type=a.value.substring(0,1),a.value=a.value.substring(1),r.left=n.pop(),r.right=a,n.push(r)):1==n.length&&"string"==a.type&&"string"==n[0].type?n[0].value+=a.value:n.push(a);continue}if(this._tokenizer.peek().keyword)break;if(r=this._eat("..."),r){n.push(r);continue}const _=this._parseName();if(!_){if(!0===i&&1==n.length&&this._tokenizer.eat(",")){if("tuple"===n[0].type?r=n[0]:(r=this._node("tuple"),r.value=[n.pop()],n.push(r)),"="===this._tokenizer.peek().value)continue;if(!this._tokenizer.match("=")&&!s.has(this._tokenizer.peek().value)){const s=t.slice(0).concat([",","="]),n=this._parseExpression(e,s,i);if(n){r.value.push(n);continue}}break}break}n.push(_)}if(1==n.length)return n.pop();if(0!=n.length)throw new python.Error("Unexpected expression"+this._tokenizer.location());return null}_parseDictOrSetMaker(){const e=[];this._tokenizer.expect("{");let t=!0;for(;!this._tokenizer.eat("}");){const i=this._parseExpression(-1,[],!1);if(null==i)throw new python.Error("Expected expression"+this._tokenizer.location());if(this._tokenizer.eat(":")||(t=!1),t){const t=this._parseExpression(-1,[],!1);if(null==t)throw new python.Error("Expected expression"+this._tokenizer.location());e.push({type:"pair",key:i,value:t})}else e.push(i);if(this._tokenizer.eat(","),this._tokenizer.eat("\n"),this._tokenizer.eat("}"))break}return t?{type:"dict",value:e}:{type:"set",value:e}}_parseExpressions(){const e=[];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");){const t=this._parseExpression();if(null==t)throw new python.Error("Expected expression"+this._tokenizer.location());for(e.push(t),this._tokenizer.eat(",");this._tokenizer.eat("\n"););if(this._tokenizer.eat("]"))break}return{type:"list",value:e}}_parseSlice(){let e={type:"::"},t=[];const i=["start","stop","step"];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");)if(this._tokenizer.eat(":"))e[i.shift()]={type:"list",value:t},t=[];else if(!this._tokenizer.eat(",")&&"]"!=this._tokenizer.peek().value){const e=this._parseExpression();if(null==e)throw new python.Error("Expected expression"+this._tokenizer.location());t.push(e)}return t.length>0&&(e[i.shift()]={type:"list",value:t}),!e.start||e.stop||e.step||(e=e.start),e}_parseName(){const e=this._tokenizer.peek();return"id"!=e.type||e.keyword?null:(this._tokenizer.read(),e)}_parseLiteral(){const e=this._tokenizer.peek();return"string"==e.type||"number"==e.type||"boolean"==e.type?(this._tokenizer.read(),e):null}_parseTypeArguments(){const e=[];for(this._tokenizer.expect("[");!this._tokenizer.eat("]");){const t=this._parseType();if(null==t)throw new python.Error("Expected type "+this._tokenizer.location());if(e.push(t),!this._tokenizer.eat(",")){this._tokenizer.expect("]");break}}return e}_parseType(){const e=this._node();return e.type="type",e.name=this._parseExpression(-1,["[","="]),e.name?("["===this._tokenizer.peek().value&&(e.arguments=this._parseTypeArguments()),e):null}_parseParameter(e){const t=this._node("parameter");if(this._tokenizer.eat("/"))return t.name="/",t;this._tokenizer.eat("**")&&(t.parameterType="**"),this._tokenizer.eat("*")&&(t.parameterType="*");const i=this._parseName();return null!==i?(t.name=i.value,":"!==e&&this._tokenizer.eat(":")&&(t.parameterType=this._parseType()),this._tokenizer.eat("=")&&(t.initializer=this._parseExpression()),t):null}_parseParameters(e){const t=[];for(;!this._tokenizer.eat(e);)if(this._tokenizer.eat("\n"),this._tokenizer.eat("(")?t.push(this._parseParameters(")")):t.push(this._parseParameter(e)),this._tokenizer.eat("\n"),!this._tokenizer.eat(",")){this._tokenizer.expect(e);break}return t}_parseArguments(){const e=[];for(this._tokenizer.expect("(");!this._tokenizer.eat(")");){if(this._tokenizer.eat("\n"))continue;const t=this._parseExpression(-1,[],!1);if(null==t)throw new python.Error("Expected expression "+this._tokenizer.location());if(e.push(t),!this._tokenizer.eat(",")){this._tokenizer.eat("\n"),this._tokenizer.expect(")");break}}return e}_node(e){const t={};return t.location=this._tokenizer.location(),e&&(t.type=e),t}_eat(e,t){if(this._tokenizer.match(e,t)){const i=this._node("id"===e?t:e);return this._tokenizer.expect(e,t),i}return null}},python.Tokenizer=class{constructor(e,t){if(this._text=e,this._file=t,this._position=0,this._lineStart=0,this._line=0,this._token={type:"",value:""},this._brackets=0,this._indentation=[],this._outdent=0,!python.Tokenizer._whitespace){python.Tokenizer._whitespace=new RegExp("[ ᠎ -    \ufeff]");const e="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",t="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‌‍‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_";python.Tokenizer._identifierStart=new RegExp("["+e+"]"),python.Tokenizer._identifierChar=new RegExp("["+e+t+"]")}}peek(){return this._cache||(this._token=this._tokenize(this._token),this._cache=!0),this._token}read(){this._cache||(this._token=this._tokenize(this._token));const e=this._position+this._token.value.length;for(;this._position=5760&&python.Tokenizer._whitespace.test(e)}}static _isNewline(e){switch(e){case"\n":case"\r":case"\u2028":case"\u2029":return!0}return!1}static _isIdentifierStartChar(e){return e<"A"?"$"===e:e<="Z"||(e<"a"?"_"===e:e<="z"||e.charCodeAt(0)>=170&&python.Tokenizer._identifierStart.test(e))}static _isIdentifierChar(e){return e<"0"?"$"===e:e<="9"||!(e<"A")&&(e<="Z"||(e<"a"?"_"===e:e<="z"||e.charCodeAt(0)>=170&&python.Tokenizer._identifierChar.test(e)))}static _isDecimal(e){return e>="0"&&e<="9"||"_"===e}static _isHex(e){return python.Tokenizer._isDecimal(e)||e>="a"&&e<="f"||e>="A"&&e<="F"||"_"===e}static _isOctal(e){return e>="0"&&e<="7"||"_"===e}static _isBinary(e){return"0"===e||"1"===e||"_"===e}_get(e){return e>=this._text.length?"\0":this._text[e]}_skipLine(){for(;this._position0&&python.Tokenizer._isNewline(e)))break;this._position=this._newLine(this._position),this._lineStart=this._position,this._line++}}}_newLine(e){return"\n"===this._get(e)&&"\r"===this._get(e+1)||"\r"===this._get(e)&&"\n"===this._get(e+1)?e+2:e+1}_tokenize(e){if("\n"!==this._token.type&&this._skipWhitespace(),"dedent"===this._token.type&&(this._indentation.pop(),this._outdent--,this._outdent>0))return{type:"dedent",value:""};if("\n"==e.type){let e="",t=this._position;for(;t0){const t=this._indentation.length>0?this._indentation[this._indentation.length-1]:"";if(e.length>t.length)i="indent",this._indentation.push(e);else if(e.length>0&&e.length=0&&e.length=this._text.length)return{type:"eof",value:""};this._indentation.length>0&&(i="dedent",this._outdent=this._indentation.length)}switch(i){case"indent":case"dedent":return{type:i,value:e}}}if(this._position>=this._text.length)return{type:"eof",value:""};const t=this._get(this._position),i=this._string();if(i)return i;switch(t){case"(":case"[":case"{":return this._brackets++,{type:t,value:t};case")":case"]":case"}":if(0===this._brackets)throw new python.Error("Unexpected '"+t+"'"+this.location);return this._brackets--,{type:t,value:t};case",":case";":case"?":return{type:t,value:t};default:{const e=this._number();if(e)return e;if("."===t){let e=this._position+1;for(;"."===this._get(e);)e++;const t=this._text.substring(this._position,e);return{type:t,value:t}}const i=this._identifier();if(i)return i;const s=this._operator();if(s)return s;break}}if("."===t)return{type:t,value:t};if("\\"===t)return{type:"\\",value:t};if(python.Tokenizer._isNewline(t))return{type:"\n",value:this._text.substring(this._position,this._newLine(this._position))};throw new python.Error("Unexpected token '"+t+"'"+this.location())}_number(){let e=this._get(this._position);const t="-"===e||"+"===e?1:0;let i=this._position+t;if(e=this._get(i),"0"===e){let e=0;const t=this._get(i+1);if("x"!==t&&"X"!==t||!python.Tokenizer._isHex(this._get(i+2)))if("b"!==t&&"B"!==t||!python.Tokenizer._isBinary(this._get(i+2)))if("o"!==t&&"O"!==t||!python.Tokenizer._isOctal(this._get(i+2))){if(t>="0"&&t<="7"){for(i++;python.Tokenizer._isOctal(this._get(i));)i+=1;"l"!==this._get(i)&&"L"!==this._get(i)||(i+=1),e=8}}else{for(i+=2;python.Tokenizer._isOctal(this._get(i));)i++;e=8}else{for(i+=2;python.Tokenizer._isBinary(this._get(i));)i++;e=2}else{for(i+=2;python.Tokenizer._isHex(this._get(i));)i+=1;"l"!==this._get(i)&&"L"!==this._get(i)||(i+=1),e=16}if(e>0&&"."!==this._get(i)){const t=this._text.substring(this._position,i),s=-1!==t.indexOf("_")?t.split("_").join(""):t;if(!isNaN(parseInt(s,e)))return{type:"number",value:t}}}i=this._position+t;let s=!1;if(this._get(i)>="1"&&this._get(i)<="9"){for(;python.Tokenizer._isDecimal(this._get(i));)i++;e=this._get(i).toLowerCase(),s="."!==e&&"e"!==e}if("0"===this._get(i)&&(i++,e=this._get(i).toLowerCase(),s=!python.Tokenizer._isDecimal(e)&&"."!==e&&"e"!==e&&"j"!==e),s){if("j"===this._get(i)||"J"===this._get(i)||"l"===this._get(i)||"L"===this._get(i))return{type:"number",value:this._text.substring(this._position,i+1)};const e=this._text.substring(this._position,i);if(!isNaN(parseInt(e,10)))return{type:"number",value:e}}if(i=this._position+t,this._get(i)>="0"&&this._get(i)<="9"||"."===this._get(i)&&this._get(i+1)>="0"&&this._get(i+1)<="9"){for(;python.Tokenizer._isDecimal(this._get(i));)i++;for("."===this._get(i)&&i++;python.Tokenizer._isDecimal(this._get(i));)i++;if(i>this._position+t)if("e"===this._get(i)||"E"===this._get(i))if(i++,"-"!=this._get(i)&&"+"!=this._get(i)||i++,python.Tokenizer._isDecimal(this._get(i)))for(;python.Tokenizer._isDecimal(this._get(i));)i++;else i=this._position;else for(;python.Tokenizer._isDecimal(this._get(i));)i++;if(i>this._position+t){if("j"===this._get(i)||"J"===this._get(i))return{type:"number",value:this._text.substring(this._position,i+1)};const e=this._text.substring(this._position,i),t=-1!=e.indexOf("_")?e.split("_").join(""):e;if(!isNaN(parseFloat(t)))return{type:"number",value:e}}}return null}_identifier(){let e=this._position;if(python.Tokenizer._isIdentifierStartChar(this._get(e)))for(e++;python.Tokenizer._isIdentifierChar(this._get(e));)e++;if(e>this._position){const t=this._text.substring(this._position,e);return{type:"id",value:t,keyword:python.Tokenizer._isKeyword(t)}}return null}_operator(){let e=0;const t=this._get(this._position),i=this._get(this._position+1),s=this._get(this._position+2);switch(t){case"+":case"&":case"|":case"^":case"=":case"!":case"%":case"~":e="="===i?2:1;break;case"-":e="="===i||">"===i?2:1;break;case"*":e="*"===i?"="===s?3:2:"="===i?2:1;break;case"/":e="/"===i?"="===s?3:2:"="===i?2:1;break;case"<":e=">"===i?2:"<"===i?"="===s?3:2:"="===i?2:1;break;case">":e=">"===i?"="===s?3:2:"="===i?2:1;break;case"@":e="="===i?2:1;break;case":":e="="===i?2:1}if(e>0){const t=this._text.substring(this._position,this._position+e);return{type:t,value:t}}return null}_string(){let e=this._position,t=-1;if("'"===this._get(e)||'"'===this._get(e))t="";else if("'"===this._get(e+1)||'"'===this._get(e+1)){const i=this._get(e);switch(i.toLowerCase()){case"b":case"f":case"r":case"u":t=i}}else if("'"===this._get(e+2)||'"'===this._get(e+2)){const e=this._text.substr(this._position,2);switch(e.toLowerCase()){case"br":case"fr":case"rb":case"rf":case"ur":t=e}}if(t.length>=0){e+=t.length;let i="",s=0;const n=this._get(e),r=this._get(e+1),o=this._get(e+2);switch(n){case"'":i=n,s="'"===r&&"'"===o?3:1;break;case'"':i=n,s='"'===r&&'"'===o?3:1}if(e+=s,1==s)for(;ee.require("./python").then((r=>pytorch.Metadata.open(e).then((o=>{try{const i=pytorch.Container.open(t,o,s,r,((t,s)=>{const r=t&&t.message?t.message:t.toString();e.exception(new pytorch.Error(r.replace(/\.$/,"")+" in '"+n+"'."),s)}));return new pytorch.Model(o,i)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new pytorch.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}}))))))}},pytorch.Model=class{constructor(t,e){this._format=e.format,this._producer=e.producer||"",this._graphs=[new pytorch.Graph(t,e)]}get format(){return this._format}get graphs(){return this._graphs}},pytorch.Graph=class{constructor(t,e){if(this._nodes=[],this._inputs=[],this._outputs=[],this._groups=!0,this._littleEndian=e.littleEndian,e.format.startsWith("TorchScript ")){this._name=e.name;const n=e.trace(),s=new Map;if(e.data){const t=[e.data];for(;t.length>0;){const e=t.shift();for(const n of Object.keys(e))if("__module__"!==n&&"__name__"!==n&&"__parent__"!==n){const r=e[n];if(!Array.isArray(r)&&r===Object(r))if(pytorch.Utility.isTensor(r)){const t=r;t.__parent__=e,!t.initializer&&t.storage&&(t.initializer=new pytorch.Tensor(t.name,t,!0)),t.__variable__&&1===t.__count__&&s.set(t.__variable__,t)}else r&&r.__module__&&r.__name__&&(r.__parent__=e,r.__id__||(r.__id__=n),t.push(r))}}}if(n){if(e.inputs)for(const t of e.inputs)this._inputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]));if(e.outputs)for(const t of e.outputs)this._outputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]));if(e.nodes)for(const n of e.nodes){const e={type:n.type,node:n};this._nodes.push(new pytorch.Node(t,"",e,s))}}e.data&&this._loadScriptModule(t,e,e.data,s)}else if(e.data){const n=e.data;this._type=n.__module__&&n.__name__?n.__module__+"."+n.__name__:"";const s="data";this._inputs.push(new pytorch.Parameter(s,!0,[new pytorch.Argument(s,null,null)]));const r=this._loadModule(t,e.data,[],[s]);for(const t of r)this._outputs.push(new pytorch.Parameter(t,!0,[new pytorch.Argument(t,null,null)]))}else if(e.state)for(const n of e.state){const e=n.attributes||[],s=n.states.map((t=>new pytorch.Parameter(t.name,!0,t.arguments.map((t=>{const e=new pytorch.Tensor(t.id,t.value,this._littleEndian);return new pytorch.Argument(t.id,null,e)}))))),r={name:n.name,type:n.type||"torch.nn.Module",attributes:e,inputs:s,outputs:[]};this._nodes.push(new pytorch.Node(t,"",r,null))}}_loadModule(t,e,n,s){if(e.__module__&&"torch.nn.modules.container"===!e.__module__&&(!e._modules||0==e._modules.length))return this._createNode(n,"",e,s),[];if(!e._modules)throw new pytorch.Error("Module does not contain modules.");for(const r of e._modules){const e=r[0],o=r[1];if(r&&o)switch(o.__module__+"."+o.__name__){case"torch.nn.modules.container.Sequential":n.push(e),s=this._loadModule(t,o,n,s),n.pop(e);break;case"torchvision.models.densenet._Transition":case"torchvision.models.resnet.Bottleneck":case"torchvision.models.densenet._DenseBlock":case"torchvision.models.densenet._DenseLayer":case"torchvision.models.inception.BasicConv2d":case"torchvision.models.inception.InceptionAux":case"torchvision.models.inception.InceptionA":case"torchvision.models.inception.InceptionB":case"torchvision.models.inception.InceptionC":case"torchvision.models.inception.InceptionD":case"torchvision.models.inception.InceptionE":n.push(e),s=[this._createNode(t,n,e,o,s,this._littleEndian).name],n.pop(e);break;default:s=[this._createNode(t,n,e,o,s).name]}}return s}_createNode(t,e,n,s,r){const o=s.__module__+"."+s.__name__,i=t.type(o);let a=[{name:"input"}];i&&i.inputs&&i.inputs.length>0&&(a=i.inputs.slice());const c=[new pytorch.Parameter(a.shift().name,!0,r.map((t=>new pytorch.Argument(t,null,null))))],_=s._parameters||s._buffers||[];for(const t of _){const e=t[0],n=t[1];let s=!0,r="";if(a.length>0){const t=a.shift();r=t.name,s=!1!==t.visible}if(t&&n&&(n.data||n.storage)){let t=null;n.data?t=new pytorch.Tensor("",n.data,this._littleEndian):n.storage&&(t=new pytorch.Tensor("",n,this._littleEndian)),c.push(new pytorch.Parameter(r||e,s,[new pytorch.Argument("",null,t)]))}}const u=e.join("/"),h=u?u+"/"+n:n,l=[new pytorch.Parameter("output",!0,[new pytorch.Argument(h,null,null)])],p=[];for(const t of Object.keys(s))t.startsWith("_")||p.push({name:t,value:s[t]});const d={name:h,type:o,attributes:p,inputs:c,outputs:l},m=new pytorch.Node(t,u,d,{});return this._nodes.push(m),m}_loadScriptModule(t,e,n,s){if(n){if(pytorch.Graph._getParameters(n).length>0&&!n.__hide__){const e={module:n};this._nodes.push(new pytorch.Node(t,"",e,s))}const r=pytorch.Graph._getSubmodules(n);for(const n of r)this._loadScriptModule(t,e,n,s)}}static _getParameters(t){const e=[];if(t&&t.__module__&&t.__name__)for(const n of Object.keys(t))if(pytorch.Utility.isTensor(t[n])){const s=t[n];s.__id__=n,e.push(s)}return e}static _getSubmodules(t){const e=[];if(t&&t.__module__&&t.__name__)for(const n of Object.keys(t))if(!n.startsWith("__")){const s=t[n];s&&s.__module__&&s.__name__&&!pytorch.Utility.isTensor(s)&&e.push(s)}return e}get type(){return this._type}get name(){return this._name}get groups(){return this._groups}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},pytorch.Parameter=class{constructor(t,e,n){this._name=t,this._visible=e,this._arguments=n}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},pytorch.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new pytorch.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e,this._initializer=n}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},pytorch.Node=class{constructor(t,e,n,s){if(this._metadata=t,this._group=e||"",this._name=n.name||"",n.module||n.node){this._attributes=[],this._inputs=[],this._outputs=[];let e=n.module;if(e){this._type="torch.nn.modules.module.Module";for(const t of pytorch.Graph._getParameters(e))this._inputs.push(new pytorch.Parameter(t.__id__,!0,[new pytorch.Argument("",null,t.initializer||null)])),t.__variable__&&this._outputs.push(new pytorch.Parameter(t.__id__,!0,[new pytorch.Argument(t.__variable__,null,null)]))}if(n.node){this._type=n.type;const r=t.type(this._type);e=null;let o=!0,i=0;for(const t of n.node.inputs){for(const n of t){const t=s.get(n.id);if(t){if(!t.__parent__||null!=e&&e!=t.__parent__){o=!1;break}e=t.__parent__,i++}}if(!o)break}if(e)if(pytorch.Graph._getParameters(e).filter((t=>"num_batches_tracked"!==t.__id__)).length==i&&o){e.__hide__=!0;for(const t of n.node.inputs)for(const e of t){const t=s.get(e.id);t&&t.initializer&&(e.initializer=t.initializer)}}else e=null;for(let t=0;tt&&(e=r.inputs[t].name),this._inputs.push(new pytorch.Parameter(e,!0,n.node.inputs[t].map((t=>new pytorch.Argument(t.id,null,t.initializer||null)))))}for(let t=0;tt&&(e=r.outputs[t].name),this._outputs.push(new pytorch.Parameter(e,!0,n.node.outputs[t].map((t=>new pytorch.Argument(t.id,null,null)))))}for(const e of n.node.attributes){const n=e.name,s=e.value,r=t.attribute(this._type,n);this._attributes.push(new pytorch.Attribute(r,n,s))}}if(e&&e.__id__){let t=e;for(this._name=t.__id__;null!=t.__parent__&&(t=t.__parent__,t.__parent__||t.__id__);)this._name=[t.__id__,this._name].join(".")}}else this._type=n.type,this._inputs=n.inputs,this._outputs=n.outputs,this._attributes=n.attributes.map((e=>{const n=t.attribute(this._type,e.name);return new pytorch.Attribute(n,e.name,e.value)}))}get name(){return this._name}get group(){return this._group}get type(){const t=this._type.indexOf(":");return-1===t?this._type:this._type.substring(0,t)}get metadata(){return this._metadata.type(this._type)}get function(){return this._type.startsWith("torch.nn.modules.")&&"torch.nn.modules.module.Module"!==this._type}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},pytorch.Attribute=class{constructor(t,e,n){if(this._name=e,this._value=n,"training"===this._name)return this._visible=!1,void(this._type="boolean");if(n&&n.type)switch(n.type){case"number":case"string":case"boolean":case"id":this._value=n.value}if(t){switch(Object.prototype.hasOwnProperty.call(t,"type")&&(this._type=t.type),this._type){case"boolean":"False"==this._value?this._value=!1:"True"==this._value&&(this._value=!0);break;case"int32":case"int64":"number"!=typeof this._value&&"string"==typeof this._value&&(this._value=parseInt(this._value,10));break;case"float32":case"float64":"number"!=typeof this._value&&"string"==typeof this._value&&(this._value=parseFloat(this._value));break;case"int32[]":case"int64[]":switch(this._value.type){case"list":this._value=this._value.value.map((t=>{if("number"===t.type){const e=parseInt(t.value,10);if(!Number.isNaN(t.value-e))return e}return t}))}}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(JSON.stringify(t.default)==JSON.stringify(this._value)||Array.isArray(this._value)&&!Array.isArray(t.default)&&this.value.every((e=>e==t.default))))&&(this._visible=!1)}Array.isArray(n)&&n.length>0&&n.every((t=>t&&t.__module__&&t.__module__.startsWith("torch.nn")))&&(this._value="?")}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},pytorch.Tensor=class{constructor(t,e,n){this._name=t||"",this._type=new pytorch.TensorType(e.storage.dataType,new pytorch.TensorShape(e.size)),this._data=e.storage.data,this._littleEndian=n}get kind(){return"Tensor"}get name(){return this._name}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return pytorch.Tensor._stringify(e,""," ")}_context(){const t={state:null,index:0,count:0};if(!this._type.dataType)return t.state="Tensor has no data type.",t;switch(this._type.dataType){case"uint8":case"qint8":case"int8":case"int16":case"int32":case"int64":case"float16":case"float32":case"float64":break;default:return t.state="Tensor data type '"+this._type.dataType+"' is not supported.",t}return this._type.shape?this._data?(t.data=this._data,t.dataType=this._type.dataType,t.dimensions=this._type.shape.dimensions,t.dataView=new DataView(t.data.buffer,t.data.byteOffset,t.data.byteLength),t):(t.state="Tensor data is empty.",t):(t.state="Tensor has no dimensions.",t)}_decode(t,e){const n=[],s=0==t.dimensions.length?[1]:t.dimensions,r=s[e];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"uint8":n.push(t.dataView.getUint8(t.index,this._littleEndian)),t.index++,t.count++;break;case"qint8":case"int8":n.push(t.dataView.getInt8(t.index,this._littleEndian)),t.index++,t.count++;break;case"int16":n.push(t.dataView.getInt16(t.index,this._littleEndian)),t.index+=2,t.count++;break;case"int32":n.push(t.dataView.getInt32(t.index,this._littleEndian)),t.index+=4,t.count++;break;case"int64":n.push(new long.Long(t.dataView.getUint32(t.index,!0),t.dataView.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":n.push(t.dataView.getFloat16(t.index,this._littleEndian)),t.index+=2,t.count++;break;case"float32":n.push(t.dataView.getFloat32(t.index,this._littleEndian)),t.index+=4,t.count++;break;case"float64":n.push(t.dataView.getFloat64(t.index,this._littleEndian)),t.index+=8,t.count++}}else for(let s=0;st.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return 0==t.dimensions.length?n[0]:n}static _stringify(t,e,n){if(Array.isArray(t)){const s=[];s.push(e+"[");const r=t.map((t=>pytorch.Tensor._stringify(t,e+n,n)));return r.length>0&&s.push(r.join(",\n")),s.push(e+"]"),s.join("\n")}return t&&long.Long.isLong(t)?e+t.toString():"string"==typeof t?e+t:t==1/0?e+"Infinity":t==-1/0?e+"-Infinity":isNaN(t)?e+"NaN":e+t.toString()}},pytorch.TensorType=class{constructor(t,e){this._dataType=t,this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},pytorch.TensorShape=class{constructor(t){this._dimensions=t||[]}get dimensions(){return this._dimensions}toString(){return this._dimensions&&this._dimensions.length>0?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},pytorch.Metadata=class{static open(t){return pytorch.Metadata._metadata?Promise.resolve(pytorch.Metadata._metadata):t.request(null,"pytorch-metadata.json","utf-8").then((t=>(pytorch.Metadata._metadata=new pytorch.Metadata(t),pytorch.Metadata._metadata))).catch((()=>(pytorch.Metadata._metadata=new pytorch.Metadata(null),pytorch.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e){t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema));const e=t.name.indexOf(":");if(-1!==e){const n=t.name.substring(0,e);this._map.has(n)||this._map.set(n,[]),this._map.get(n).push(t.name)}}}}type(t){const e=this._map.get(t);return e?Array.isArray(e)?e.map((t=>this._map.get(t))):e:null}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){this._attributeCache.set(n,null);const e=this.type(t);if(e){if(e.inputs)for(const n of e.inputs)this._attributeCache.set(t+":"+n.name,n);if(e.attributes)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n)}}return this._attributeCache.get(n)}},pytorch.Error=class extends Error{constructor(t){super(t),this.name="Error loading PyTorch model."}},pytorch.Execution=class{constructor(t,e,n){const s=this;this._python=t,this._sources=e,this._exceptionCallback=n,this._utf8Decoder=new TextDecoder("utf-8"),this._unknownNameMap=new Set,this._knownPackageMap=new Set(["torch","torchvision","collections","__builtin__","_codecs","argparse","numpy"]),this._packages=new Map,this._context=new pytorch.Execution.Context,this._context.scope.builtins={},this._context.scope.builtins.type={__module__:"builtins",__name__:"type"},this._context.scope.builtins.module={__module__:"builtins",__name__:"module",__class__:this._context.scope.builtins.type},this._context.scope.builtins.function={__module__:"builtins",__name__:"function",__class__:this._context.scope.builtins.type},this._context.scope.builtins.method={__module__:"builtins",__name__:"method",__class__:this._context.scope.builtins.type},this._context.scope.builtins.dict={__module__:"builtins",__name__:"dict",__class__:this._context.scope.builtins.type},this._context.scope.builtins.list={__module__:"builtins",__name__:"list",__class__:this._context.scope.builtins.type},this._context.scope.builtins.str={__module__:"builtins",__name__:"str",__class__:this._context.scope.builtins.type},this._context.scope.builtins.tuple={__module__:"builtins",__name__:"tuple",__class__:this._context.scope.builtins.type},this._context.scope.typing={__name__:"typing",__class__:this._context.scope.builtins.module},this._context.scope.typing._GenericAlias={__module__:"typing",__name__:"_GenericAlias",__class__:this._context.scope.builtins.type},this._context.scope.typing._SpecialForm={__module__:"typing",__name__:"_SpecialForm",__class__:this._context.scope.builtins.type},this._context.scope.typing._VariadicGenericAlias={__module__:"typing",__name__:"_VariadicGenericAlias",__class__:this._context.scope.builtins.type},this._context.scope.typing.Dict={__module__:"typing",__name__:"Dict",__class__:this._context.scope.typing._VariadicGenericAlias,__origin__:this._context.scope.builtins.dict},this._context.scope.typing.List={__module__:"typing",__name__:"List",__class__:this._context.scope.typing._GenericAlias,__origin__:this._context.scope.builtins.list},this._context.scope.typing.Optional={__module__:"typing",__class__:this._context.scope.typing._SpecialForm},this._context.scope.typing.Tuple={__module__:"typing",__name__:"Tuple",__class__:this._context.scope.typing._GenericAlias,__origin__:this._context.scope.builtins.tuple},this._context.scope.torch={__name__:"torch",__class__:this._context.scope.builtins.module},this._context.scope.torch.Tensor={__module__:"torch",__name__:"Tensor",__class__:this._context.scope.builtins.type},this._registerConstructor("argparse.Namespace",(function(t){this.args=t})),this._registerConstructor("torch.autograd.variable.Variable",(function(){})),this._registerConstructor("torch.backends.cudnn.rnn.Unserializable",(function(){})),this._registerConstructor("torch.device",(function(t,e){this.type=t,e&&(this.index=e)})),this._registerConstructor("torch.distributions.multivariate_normal.MultivariateNormal",(function(){})),this._registerConstructor("torch.nn.backends.thnn._get_thnn_function_backend",(function(){})),this._registerConstructor("torch.nn.intrinsic.modules.fused.ConvReLU2d",(function(){})),this._registerConstructor("torch.nn.modules.activation.CELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.ELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.GELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.GLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.Hardtanh",(function(){})),this._registerConstructor("torch.nn.modules.activation.LeakyReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.LogSigmoid",(function(){})),this._registerConstructor("torch.nn.modules.activation.LogSoftmax",(function(){})),this._registerConstructor("torch.nn.modules.activation.MultiheadAttention",(function(){})),this._registerConstructor("torch.nn.modules.activation.ReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.ReLU6",(function(){})),this._registerConstructor("torch.nn.modules.activation.PReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.RReLU",(function(){})),this._registerConstructor("torch.nn.modules.activation.SELU",(function(){})),this._registerConstructor("torch.nn.modules.activation.Sigmoid",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softmax",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softmax2d",(function(){})),this._registerConstructor("torch.nn.modules.activation.Softplus",(function(){})),this._registerConstructor("torch.nn.modules.activation.Tanh",(function(){})),this._registerConstructor("torch.nn.modules.activation.Threshold",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm1d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm2d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.BatchNorm3d",(function(){})),this._registerConstructor("torch.nn.modules.batchnorm.SyncBatchNorm",(function(){})),this._registerConstructor("torch.nn.modules.container.ModuleDict",(function(){})),this._registerConstructor("torch.nn.modules.container.ModuleList",(function(){})),this._registerConstructor("torch.nn.modules.container.ParameterList",(function(){})),this._registerConstructor("torch.nn.modules.container.Sequential",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv1d",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv2d",(function(){})),this._registerConstructor("torch.nn.modules.conv.Conv3d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose1d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose2d",(function(){})),this._registerConstructor("torch.nn.modules.conv.ConvTranspose3d",(function(){})),this._registerConstructor("torch.nn.modules.distance.CosineSimilarity",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout2d",(function(){})),this._registerConstructor("torch.nn.modules.dropout.Dropout3d",(function(){})),this._registerConstructor("torch.nn.modules.fold.Unfold",(function(){})),this._registerConstructor("torch.nn.modules.flatten.Flatten",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm1d",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm2d",(function(){})),this._registerConstructor("torch.nn.modules.instancenorm.InstanceNorm3d",(function(){})),this._registerConstructor("torch.nn.modules.linear.Linear",(function(){})),this._registerConstructor("torch.nn.modules.linear.Identity",(function(){})),this._registerConstructor("torch.nn.modules.loss.BCELoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.BCEWithLogitsLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.CrossEntropyLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.L1Loss",(function(){})),this._registerConstructor("torch.nn.modules.loss.MSELoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.NLLLoss",(function(){})),this._registerConstructor("torch.nn.modules.loss.SmoothL1Loss",(function(){})),this._registerConstructor("torch.nn.modules.normalization.CrossMapLRN2d",(function(){})),this._registerConstructor("torch.nn.modules.normalization.GroupNorm",(function(){})),this._registerConstructor("torch.nn.modules.normalization.LayerNorm",(function(){})),this._registerConstructor("torch.nn.modules.normalization.LocalResponseNorm",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReflectionPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReflectionPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ReplicationPad3d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ZeroPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad1d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad2d",(function(){})),this._registerConstructor("torch.nn.modules.padding.ConstantPad3d",(function(){})),this._registerConstructor("torch.nn.modules.pixelshuffle.PixelShuffle",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveAvgPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AdaptiveMaxPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.AvgPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.FractionalMaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxPool3d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool1d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool2d",(function(){})),this._registerConstructor("torch.nn.modules.pooling.MaxUnpool3d",(function(){})),this._registerConstructor("torch.nn.modules.rnn.GRU",(function(){})),this._registerConstructor("torch.nn.modules.rnn.GRUCell",(function(){})),this._registerConstructor("torch.nn.modules.rnn.LSTM",(function(){})),this._registerConstructor("torch.nn.modules.rnn.LSTMCell",(function(){})),this._registerConstructor("torch.nn.modules.rnn.RNN",(function(){})),this._registerConstructor("torch.nn.modules.sparse.Embedding",(function(){})),this._registerConstructor("torch.nn.modules.sparse.EmbeddingBag",(function(){})),this._registerConstructor("torch.nn.modules.transformer.TransformerEncoder",(function(){})),this._registerConstructor("torch.nn.modules.transformer.TransformerEncoderLayer",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.Upsample",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.UpsamplingBilinear2d",(function(){})),this._registerConstructor("torch.nn.modules.upsampling.UpsamplingNearest2d",(function(){})),this._registerConstructor("torch.nn.parallel.data_parallel.DataParallel",(function(){})),this._registerConstructor("torch.nn.parallel.distributed.DistributedDataParallel",(function(){})),this._registerConstructor("torch.nn.parameter.Parameter",(function(t,e){this.data=t,this.requires_grad=e})),this._registerConstructor("torch.nn.quantized.modules.functional_modules.FloatFunctional",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNorm",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNormStateDictHook",(function(){})),this._registerConstructor("torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook",(function(){})),this._registerConstructor("torch.nn.utils.weight_norm.WeightNorm",(function(){})),this._registerConstructor("torch.optim.adam.Adam",(function(){})),this._registerConstructor("torch.optim.adagrad.Adagrad",(function(){})),this._registerConstructor("torch.optim.lr_scheduler.MultiStepLR",(function(){})),this._registerConstructor("torch.optim.lr_scheduler.StepLR",(function(){})),this._registerConstructor("torch.optim.rmsprop.RMSprop",(function(){})),this._registerConstructor("torch.optim.sgd.SGD",(function(){})),this._registerConstructor("torch.quantization.stubs.DeQuantStub",(function(){})),this._registerConstructor("torch.quantization.stubs.QuantStub",(function(){})),this._registerConstructor("torchvision.datasets.folder.ImageFolder",(function(){})),this._registerConstructor("torchvision.models.alexnet.AlexNet",(function(){})),this._registerConstructor("torchvision.models.densenet.DenseNet",(function(){})),this._registerConstructor("torchvision.models.densenet._DenseBlock",(function(){})),this._registerConstructor("torchvision.models.densenet._DenseLayer",(function(){})),this._registerConstructor("torchvision.models.densenet._Transition",(function(){})),this._registerConstructor("torchvision.models.detection._utils.BalancedPositiveNegativeSampler",(function(){})),this._registerConstructor("torchvision.models.detection._utils.BoxCoder",(function(){})),this._registerConstructor("torchvision.models.detection._utils.Matcher",(function(){})),this._registerConstructor("torchvision.models.detection.backbone_utils.BackboneWithFPN",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.FasterRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.FastRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.faster_rcnn.TwoMLPHead",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads",(function(){})),this._registerConstructor("torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNN",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNNHeads",(function(){})),this._registerConstructor("torchvision.models.detection.mask_rcnn.MaskRCNNPredictor",(function(){})),this._registerConstructor("torchvision.models.detection.roi_heads.RoIHeads",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.AnchorGenerator",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.RegionProposalNetwork",(function(){})),this._registerConstructor("torchvision.models.detection.rpn.RPNHead",(function(){})),this._registerConstructor("torchvision.models.detection.transform.GeneralizedRCNNTransform",(function(){})),this._registerConstructor("torchvision.models.googlenet.BasicConv2d",(function(){})),this._registerConstructor("torchvision.models.googlenet.GoogLeNet",(function(){})),this._registerConstructor("torchvision.models.googlenet.Inception",(function(){})),this._registerConstructor("torchvision.models.inception.BasicConv2d",(function(){})),this._registerConstructor("torchvision.models.inception.Inception3",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionAux",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionA",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionB",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionC",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionD",(function(){})),this._registerConstructor("torchvision.models.inception.InceptionE",(function(){})),this._registerConstructor("torchvision.models.mobilenet.ConvBNReLU",(function(){})),this._registerConstructor("torchvision.models.mobilenet.MobileNetV2",(function(){})),this._registerConstructor("torchvision.models.mobilenet.InvertedResidual",(function(){})),this._registerConstructor("torchvision.models.resnet.Bottleneck",(function(){})),this._registerConstructor("torchvision.models.resnet.BasicBlock",(function(){})),this._registerConstructor("torchvision.models.quantization.resnet.QuantizableBottleneck",(function(){})),this._registerConstructor("torchvision.models.quantization.resnet.QuantizableResNet",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPP",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPPConv",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.ASPPPooling",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.DeepLabHead",(function(){})),this._registerConstructor("torchvision.models.segmentation.deeplabv3.DeepLabV3",(function(){})),this._registerConstructor("torchvision.models.segmentation.fcn.FCN",(function(){})),this._registerConstructor("torchvision.models.segmentation.fcn.FCNHead",(function(){})),this._registerConstructor("torchvision.models.shufflenetv2.ShuffleNetV2",(function(){})),this._registerConstructor("torchvision.models.shufflenetv2.InvertedResidual",(function(){})),this._registerConstructor("torchvision.models.squeezenet.Fire",(function(){})),this._registerConstructor("torchvision.models.squeezenet.SqueezeNet",(function(){})),this._registerConstructor("torchvision.models.resnet.ResNet",(function(){})),this._registerConstructor("torchvision.models.vgg.VGG",(function(){})),this._registerConstructor("torchvision.models.video.resnet.BasicBlock",(function(){})),this._registerConstructor("torchvision.models.video.resnet.BasicStem",(function(){})),this._registerConstructor("torchvision.models.video.resnet.Conv3DNoTemporal",(function(){})),this._registerConstructor("torchvision.models.video.resnet.Conv3DSimple",(function(){})),this._registerConstructor("torchvision.models.video.resnet.VideoResNet",(function(){})),this._registerConstructor("torchvision.models._utils.IntermediateLayerGetter",(function(){})),this._registerConstructor("torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork",(function(){})),this._registerConstructor("torchvision.ops.feature_pyramid_network.LastLevelMaxPool",(function(){})),this._registerConstructor("torchvision.ops.misc.ConvTranspose2d",(function(){})),this._registerConstructor("torchvision.ops.misc.FrozenBatchNorm2d",(function(){})),this._registerConstructor("torchvision.ops.poolers.LevelMapper",(function(){})),this._registerConstructor("torchvision.ops.poolers.MultiScaleRoIAlign",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Compose",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Normalize",(function(){})),this._registerConstructor("torchvision.transforms.transforms.Resize",(function(){})),this._registerConstructor("torchvision.transforms.transforms.ToTensor",(function(){})),this._registerConstructor("torch.ByteStorage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="uint8"})),this._registerConstructor("torch.CharStorage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="int8"})),this._registerConstructor("torch.ShortStorage",(function(t){this.size=t,this.dataTypeSize=2,this.dataType="int16"})),this._registerConstructor("torch.IntStorage",(function(t){this.size=t,this.dataTypeSize=4,this.dataType="int32"})),this._registerConstructor("torch.LongStorage",(function(t){this.size=t,this.dataTypeSize=8,this.dataType="int64"})),this._registerConstructor("torch.HalfStorage",(function(t){this.size=t,this.dataTypeSize=2,this.dataType="float16"})),this._registerConstructor("torch.FloatStorage",(function(t){this.size=t,this.dataTypeSize=4,this.dataType="float32"})),this._registerConstructor("torch.DoubleStorage",(function(t){this.size=t,this.dataTypeSize=8,this.dataType="float64"})),this._registerConstructor("torch.QInt8Storage",(function(t){this.size=t,this.dataTypeSize=1,this.dataType="qint8"})),this._registerConstructor("torch.FloatTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.DoubleTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.cuda.FloatTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("torch.cuda.DoubleTensor",(function(){this.__setstate__=function(t){this.storage=t[0],this.storage_offset=t[1],this.size=t[2],this.stride=t[3]}})),this._registerConstructor("numpy.dtype",(function(t,e,n){switch(t){case"i1":this.name="int8",this.itemsize=1;break;case"i2":this.name="int16",this.itemsize=2;break;case"i4":this.name="int32",this.itemsize=4;break;case"i8":this.name="int64",this.itemsize=8;break;case"b1":case"u1":this.name="uint8",this.itemsize=1;break;case"u2":this.name="uint16",this.itemsize=2;break;case"u4":this.name="uint32",this.itemsize=4;break;case"u8":this.name="uint64",this.itemsize=8;break;case"f4":this.name="float32",this.itemsize=4;break;case"f8":this.name="float64",this.itemsize=8;break;default:if(t.startsWith("V"))this.itemsize=Number(t.substring(1)),this.name="void"+(8*this.itemsize).toString();else if(t.startsWith("O"))this.itemsize=Number(t.substring(1)),this.name="object";else if(t.startsWith("S"))this.itemsize=Number(t.substring(1)),this.name="string";else if(t.startsWith("U"))this.itemsize=Number(t.substring(1)),this.name="string";else{if(!t.startsWith("M"))throw new pytorch.Error("Unknown dtype '"+t.toString()+"'.");this.itemsize=Number(t.substring(1)),this.name="datetime"}}this.align=e,this.copy=n,this.__setstate__=function(t){switch(t.length){case 8:this.version=t[0],this.byteorder=t[1],this.subarray=t[2],this.names=t[3],this.fields=t[4],this.elsize=t[5],this.alignment=t[6],this.int_dtypeflags=t[7];break;default:throw new pytorch.Error("Unknown numpy.dtype setstate length '"+t.length.toString()+"'.")}}})),this._registerConstructor("numpy.core.multiarray._reconstruct",(function(t,e,n){this.subtype=t,this.shape=e,this.dtype=n,this.__setstate__=function(t){this.version=t[0],this.shape=t[1],this.typecode=t[2],this.is_f_order=t[3],this.rawdata=t[4]},this.__read__=function(t){const e={},n=this.subtype.split(".");e.__name__=n.pop(),e.__module__=n.join("."),e.dtype=this.typecode,e.shape=this.shape;let s=e.dtype.itemsize;for(let t=0;t0&&te?1+(t-1-e)/(0-n):0})),this._registerFunction("torch._unwrap_optional",(function(t){return t})),this._registerFunction("torch.add",(function(t,e){if("number"==typeof t&&"number"==typeof e)return t*e;throw new pytorch.Error("Unknown torch.add expression type.")})),this._registerFunction("torch.append",(function(t,e){return t.push(e),e})),this._registerFunction("torch.dict",(function(t){if(t)throw new pytorch.Error("'torch.dict' arguments not supported.");return{}})),this._registerFunction("torch.dim",(function(t){return t&&t.size?t.size.length:0})),this._registerFunction("torch.eq",(function(t,e){if("string"==typeof t&&"string"==typeof e)return t===e;if("number"==typeof t&&"number"==typeof e)return t===e;throw new pytorch.Error("Unknown 'torch.eq' expression type.")})),this._registerFunction("torch.floordiv",(function(){})),this._registerFunction("torch.gt",(function(t,e){if("number"==typeof t&&"number"==typeof e&&!isNaN(t)&&!isNaN(e))return t>e;if(isNaN(t)&&!isNaN(e))return!0;throw new pytorch.Error("Unknown 'torch.gt' expression type.")})),this._registerFunction("torch.jit._pickle.build_boollist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_doublelist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_intlist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_tensorlist",(function(t){return t})),this._registerFunction("torch.jit._pickle.build_tensor_from_id",(function(t){return t})),this._registerFunction("torch.jit._pickle.restore_type_tag",(function(t){return t})),this._registerFunction("torch.keys",(function(t){return Object.keys(t)})),this._registerFunction("torch.len",(function(t){return t?t.length:NaN})),this._registerFunction("torch.le",(function(t,e){if("number"==typeof t&&"number"==typeof e)return!isNaN(t)&&!isNaN(e)&&t<=e;throw new pytorch.Error("Unknown 'torch.le' expression type.")})),this._registerFunction("torch.list",(function(t){return t})),this._registerFunction("torch.list_with_default",(function(t){return t})),this._registerFunction("torch.lt",(function(t,e){if("number"==typeof t&&"number"==typeof e)return t=0&&et[e]))})),this._registerFunction("torch.warn",(function(){})),this._registerFunction("uninitialized",(function(t){if(t&&"typing"===t.__module__&&"Tuple"===t.__name__)return[];if(t&&"typing"===t.__module__&&"List"===t.__name__)return[];if(t&&"typing"===t.__module__&&"Dict"===t.__name__)return{};if(t&&"torch"===t.__module__&&"Tensor"===t.__name__)return{__module__:t.__module__,__name__:t.__name__};throw new pytorch.Error("Unsupported uninitialized argument '"+JSON.stringify(t)+"'.")}))}get context(){return this._context}parse(t){const e=this._sources[t];if(e){const n=this._utf8Decoder.decode(e),s=new this._python.Parser(n,t).parse();if(!s)throw new pytorch.Error("Module '"+t+"' parse error.");return s}return null}package(t,e,n){if(this._python&&!this._packages.has(t)){e=e||"code/"+t.split(".").join("/")+".py";const s=this.parse(e);if(s){let r=this._context.getx(t);void 0===r&&(r={},this._context.setx(t,r)),r.__class__=this._context.scope.builtins.module,r.__name__=t,r.__file__=e,this._packages.set(t,r);const o=this._context.push(r);if(this._block(s.body,o),n)return s}}return this._packages.get(t)}type(t){const e=this._context.getx(t);if(void 0!==e)return e;const n=t.split("."),s=n.pop(),r=n.join("."),o=this.package(r);return o?o[s]:null}invoke(t,e){const n=this.type(t);if(n){if(n.__class__===this._context.scope.builtins.type){const t={};return t.__proto__=n,t.__init__&&"function"==typeof t.__init__&&t.__init__.apply(t,e),t}if(n.__class__===this._context.scope.builtins.function)return n.__call__?n.__call__(e):n.apply(null,e)}this._raiseUnkownName(t);const s=t.split("."),r=s.pop();return{__module__:s.join("."),__name__:r}}call(t,e,n,s){const r=this._target(t,s),o=n.map((t=>this.expression(t,s)));if(!r||null!==e&&!r[e]){const n=pytorch.Utility.target(t)+"."+e;if(this.type(n))return this.invoke(n,o);throw new pytorch.Error("Unsupported function '"+n+"'.")}const i=e?r[e]:r;if(i.__class__===this._context.scope.builtins.type){const t={};return t.__proto__=i,t.__init__&&"function"==typeof t.__init__&&t.__init__.apply(t,n),t}if(i.__class__===this._context.scope.builtins.function&&i.__call__)return i.__call__(o);if(i.__class__===this._context.scope.builtins.method&&i.__call__)return i.__call__([r].concat(o));if("function"==typeof i)return i.apply(r,o);throw new pytorch.Error("Unsupported call expression.")}apply(t,e,n){const s=Array.prototype.slice.call(e);n=n.push();for(const e of t.parameters)n.set(e.name,s.shift());return this._block(t.body.statements,n)}_block(t,e){for(t=Array.prototype.slice.call(t);t.length>0;){const n=t.shift();switch(n.type){case"pass":break;case"return":return this.expression(n.expression,e);case"def":{const t=e.get("__name__"),s=this,r=e.get("__class__");let o=null;if(r===this._context.scope.builtins.type)o=this._context.scope.builtins.method;else{if(r!==this._context.scope.builtins.module)throw new pytorch.Error("Invalid function scope.");o=this._context.scope.builtins.function}const i={__class__:o,__globals__:e,__module__:t,__name__:n.name,__code__:n,__call__:function(t){return s.apply(this.__code__,t,this.__globals__)}};e.set(n.name,i);break}case"class":{const t={__class__:this._context.scope.builtins.type,__module__:e.get("__name__"),__name__:n.name};e.set(n.name,t),e=e.push(t),this._block(n.body.statements,e),e=e.pop();break}case"var":e.set(n.name,void 0);break;case"=":this.expression(n,e);break;case"if":{const s=this.expression(n.condition,e);if(!0===s||s){t=n.then.statements.concat(t);break}if(!1===s){t=n.else.statements.concat(t);break}throw new pytorch.Error("Unknown condition.")}case"for":if(1==n.target.length&&1===n.variable.length&&"id"===n.variable[0].type){const s=this.expression(n.target[0],e),r=n.variable[0];let o=[];for(const t of s)o.push({type:"=",target:r,expression:{type:"number",value:t}}),o=o.concat(n.body.statements);t=o.concat(t);break}throw new pytorch.Error("Unsupported 'for' statement.");case"call":this.expression(n,e);break;case"import":for(const t of n.modules){const n=pytorch.Utility.target(t.name),s=this.package(n);t.as&&e.set(t.as,s)}break;default:throw new pytorch.Error("Unknown statement '"+n.type+"'.")}}}expression(t,e){const n=e.getx("self");switch(t.type){case"=":{const n=t.target;if("id"===n.type)return void e.set(n.value,this.expression(t.expression,e));if("[]"===n.type){if("id"===n.target.type&&"list"===n.arguments.type&&1===n.arguments.value.length){const s=this.expression(n.arguments.value[0],e);return"__annotations__"===n.target.value&&e.set(n.target.value,e.get(n.target.value)||{}),void(e.get(n.target.value)[s]=this.expression(t.expression,e))}}else{if("."===n.type&&"id"===n.member.type)return void(this.expression(n.target,e)[n.member.value]=this.expression(t.expression,e));if("tuple"===n.type){const s=this.expression(t.expression,e);if(n.value.length==s.length&&n.value.every((t=>"id"===t.type))){for(let t=0;tthis.expression(t,e)));case"string":return t.value.substring(1,t.value.length-1);case"number":return Number(t.value);case"[]":{if("id"===t.target.type&&"list"===t.arguments.type&&1===t.arguments.value.length&&e.get(t.target.value)){const n=this.expression(t.arguments.value[0],e);return e.get(t.target.value)[n]}const n=this.expression(t.target,e);if(n&&"list"===t.arguments.type&&(n.__class__===this.context.scope.typing._VariadicGenericAlias||n.__class__===this.context.scope.typing._GenericAlias||n.__class__===this.context.scope.typing._SpecialForm)){const s=Object.assign({},n);return s.__args__=t.arguments.value.map((t=>this.expression(t,e))),s}if("list"===t.arguments.type&&1===t.arguments.value.length)return n[this.expression(t.arguments.value[0],e)];break}case".":if("id"==t.member.type)return this._target(t.target,e)[t.member.value];throw new pytorch.Error("Unsupported field expression.");case"call":return"id"===t.target.type&&"annotate"===t.target.value&&2===t.arguments.length||"id"===t.target.type&&"unchecked_cast"===t.target.value&&2===t.arguments.length?this.expression(t.arguments[1],e):"."===t.target.type?this.call(t.target.target,t.target.member.value,t.arguments,e):this.call(t.target,null,t.arguments,e);case"id":{switch(t.value){case"self":return n;case"None":return null;case"True":return!0;case"False":return!1}const s=this._context.scope.builtins[t.value]||this._context.scope.typing[t.value]||this._context.scope.torch[t.value];return!s||s.__class__!==this._context.scope.builtins.type&&s.__class__!==this._context.scope.typing._VariadicGenericAlias&&s.__class__!==this._context.scope.typing._GenericAlias&&s.__class__!==this._context.scope.typing._SpecialForm?e.get(t.value):s}case"tuple":return t.value.map((t=>this.expression(t,e)))}throw new pytorch.Error("Unknown expression '"+t.type+"'.")}_target(t,e){let n=t,s="";for(;;){if("."!==n.type||!n.member||"id"!==n.member.type){if("id"===n.type&&"self"!==n.value&&"CONSTANTS"!==n.value){s=n.value+s;break}s=null;break}s="."+n.member.value+s,n=n.target}if(s){let t=e.getx(s);if(!t&&(t=this.package(s),!t))throw new pytorch.Error("Failed to resolve module '"+s+"'.");return t}return this.expression(t,e)}_registerFunction(t,e){if(this._context.getx(t))throw new pytorch.Error("Function '"+t+"' is already registered.");const n=t.split(".");e.__class__=this._context.scope.builtins.function,e.__name__=n.pop(),e.__module__=n.join("."),this._context.setx(t,e)}_registerConstructor(t,e){if(this._context.getx(t))throw new pytorch.Error("Constructor '"+t+"' is already registered.");const n=t.split("."),s=n.pop(),r=n.join("."),o={__class__:this._context.scope.builtins.type,__name__:s,__module__:r,__init__:function(){e.apply(this,arguments)}};this._context.setx(t,o)}_raiseUnkownName(t){t&&!this._unknownNameMap.has(t)&&(this._unknownNameMap.add(t),this._knownPackageMap.has(t.split(".").shift())&&this._exceptionCallback(new pytorch.Error("Unknown function '"+t+"'."),!1))}},pytorch.Execution.Context=class{constructor(t,e){this._parent=t||null,this._scope=e||{}}push(t){return new pytorch.Execution.Context(this,t)}pop(){return this._parent}get scope(){return this._scope}set(t,e){this._scope[t]=e}get(t){return t in this._scope?this._scope[t]:this._parent?this._parent.get(t):void 0}setx(t,e){const n=t.split(".");if(1==n.length)this.set(n[0],e);else{let t=this.get(n[0]);for(t||(t={},this.set(n[0],t)),n.shift();n.length>1;){const e=n.shift();t[e]=t[e]||{},t=t[e]}t[n[0]]=e}}getx(t){const e=t.split(".");let n=this.get(e[0]);if(n){for(e.shift();e.length>0&&n[e[0]];)n=n[e[0]],e.shift();if(0===e.length)return n}}},pytorch.Container=class{static open(t,e,n,s,r){if(t.entries("zip").some((t=>"model.json"===t.name||"data.pkl"===t.name||t.name.endsWith("/model.json")||t.name.endsWith("/data.pkl"))))return new pytorch.Container.Zip(t.entries("zip"),e,n,s,r);const o=t.buffer;return o&&o.length>14&&128==o[0]&&o[1]<16&&[138,10,108,252,156,70,249,32,106,168,80,25].every(((t,e)=>t==o[e+2]))?new pytorch.Container.Pickle(o,n,r):t.entries("tar").some((t=>"pickle"==t.name))?new pytorch.Container.Tar(t.entries("tar"),n,r):null}},pytorch.Container.Tar=class{constructor(t,e,n){this._entries=t,this._pickle=e,this._exceptionCallack=n}get format(){return"PyTorch v0.1.1"}get data(){return this._unpickle(),this._data}get state(){return this._unpickle(),this._state}get littleEndian(){return this._unpickle(),this._littleEndian}_unpickle(){if(!this._entries)return;this._data=null,this._state=null,this._littleEndian=!0;const t=new pytorch.Execution(null,[],this._exceptionCallback),e={};for(const t of this._entries)switch(t.name){case"sys_info":e.sys_info=t.data;break;case"pickle":e.pickle=t.data;break;case"storages":e.storages=t.data;break;case"tensors":e.tensors=t.data}if(this._exceptionCallback=null,this._entries=null,e.sys_info){const n=new this._pickle.Unpickler(e.sys_info).load(((e,n)=>t.invoke(e,n)));if(1e3!=n.protocol_version)throw new pytorch.Error("Unsupported protocol version '"+n.protocol_version+"'.");if(n.type_sizes&&(n.type_sizes.int&&4!=n.type_sizes.int||n.type_sizes.long&&4!=n.type_sizes.long||n.type_sizes.short&&2!=n.type_sizes.short))throw new pytorch.Error("Unsupported type sizes.");this._littleEndian=n.little_endian}const n={};if(e.storages){const s=new this._pickle.Unpickler(e.storages),r=s.load(((e,n)=>t.invoke(e,n)));for(let e=0;et.invoke(e,n)));for(let e=0;en[t];let r=new this._pickle.Unpickler(e.pickle).load(((e,n)=>t.invoke(e,n)),s);if(r){if(!(r instanceof Map)){const t=new Map;for(const e of Object.keys(r))t.set(e,r[e]);r=t}this._state=[];const t={};if(r instanceof Map)for(const e of r){const n=e[0],s=e[1];if(!n||!s){this._state=null;break}const r={};if(r.id=n,r.value=null,s&&"torch.nn.parameter"===s.__module__&&"Parameter"===s.__name__?r.value=s[0]:pytorch.Utility.isTensor(s)&&(r.value=s),!r.value){this._state=null;break}const o=r.id.split(".");if(o.length<2){this._state=null;break}r.name=o.pop();const i=o.join(".");let a=t[i];a||(a={},a.name=i,a.states=[],t[i]=a,this._state.push(a)),a.states.push({name:r.name,arguments:[r]})}}}}},pytorch.Container.Pickle=class{constructor(t,e,n){this._buffer=t,this._pickle=e,this._exceptionCallback=n}get format(){return"PyTorch v0.1.10"}get data(){return this._unpickle(),this._data}get state(){return this._unpickle(),this._state}get littleEndian(){return this._unpickle(),this._littleEndian}_unpickle(){if(!this._buffer)return;const t=new pytorch.Execution(null,[],this._exceptionCallback),e=new this._pickle.Unpickler(this._buffer);this._buffer=null,this._pickle=null,this._exceptionCallback=null,e.load();const n=e.load();if(1001!=n)throw new pytorch.Error("Unsupported protocol version '"+n+"'.");const s=e.load();if(1001!=s.protocol_version)throw new pytorch.Error("Unsupported protocol version '"+s.protocol_version+"'.");if(s.type_sizes&&(s.type_sizes.int&&4!=s.type_sizes.int||s.type_sizes.long&&4!=s.type_sizes.long||s.type_sizes.short&&2!=s.type_sizes.short))throw new pytorch.Error("Unsupported type sizes.");this._littleEndian=s.little_endian;const r=new Map,o=new Map,i=e.load(((e,n)=>t.invoke(e,n)),(e=>{const n=e.shift(),s=e;switch(n){case"module":{const t=s[0],e=s[2];return r.set(t,e),s[0]}case"storage":{const e=s.shift(),n=s.shift();s.shift();const r=s.shift(),i=s.shift();if(!o.has(n)){const s=t.invoke(e,[r]);o.set(n,s)}if(i){const t=i.shift();if(i.shift(),i.shift(),!o.has(t)){const e=null;o.set(t,e)}return o.get(t)}return o.get(n)}}throw new pytorch.Error("Unknown persistent load type '"+n+"'.")}));if(!i)throw new pytorch.Error("File format is not PyTorch.");const a=e.load();for(const t of a){const n=o.get(t);if(long.Long.fromBytesLE(e.read(8),!1).toNumber()!=n.size)throw new pytorch.Error("Storage size mismatch.");n.data=e.read(n.dataTypeSize*n.size)}if(this._data=this._findRootModule(i),this._data||(this._state=this._findStateDict(i)),!this._data&&!this._state&&"None"!==i)throw new pytorch.Error("File does not contain root module or state dictionary.")}_findRootModule(t){const e=[t,t.model,t.net];for(const t of e)if(t&&t._modules)return t;return null}_findStateDict(t){if(!t)return null;if(t.encoder&&Array.isArray(t.encoder)&&t.decoder&&Array.isArray(t.decoder)&&!t.state_dict&&(t=t.encoder.concat(t.decoder)),t instanceof Map){const e={};for(const n of t){const t=n[0],s=n[1];e[t]=s}t=e}const e=[t.state_dict,t.state,t.model_state,t.model,t.model_state_dict,t.net_dict,t.params,t.generator,t.discriminator,t.g_state,t.network,t.net,t.netG,t.net_states,t.state_dict_stylepredictor,t.state_dict_ghiasi,t];for(const t of e){let e=null;if(e=e||this._convertStateDictList(t),e=e||this._convertStateDictMap(t),e=e||this._convertStateDictGroupMap(t),e)return e}return null}_convertStateDictList(t){if(t&&Array.isArray(t)&&t.every((t=>t.__module__&&t.__name__&&Object.keys(t).filter((e=>pytorch.Utility.isTensor(t[e]).length>0))))){const e=[];for(const n of t){const t={type:n.__module__+"."+n.__name__,states:[],attributes:[]};for(const e of Object.keys(n)){const s=n[e];pytorch.Utility.isTensor(s)?t.states.push({name:e,arguments:[{id:"",value:s}]}):t.attributes.push({name:e,value:s})}e.push(t)}return e}if(!t||Array.isArray(t)||t instanceof Map||(t=new Map(Object.keys(t).map((e=>[e,t[e]])))),t&&t instanceof Map){for(const e of t){const t=e[0],n=e[1];if(!t||!n)return null;if(!pytorch.Utility.isTensor(n)&&!(t.endsWith("._packed_params.dtype")||t.endsWith("._packed_params._packed_params")&&Array.isArray(n)&&n.every((t=>pytorch.Utility.isTensor(t)))))return null}const e=new Map;for(const n of t){const t=n[0],s=n[1];if(null!==s){let n="",r="";if(t.endsWith("_packed_params.dtype"))r="_packed_params.dtype",n=t.substring(0,t.length-r.length-1);else if(t.endsWith("_packed_params._packed_params")&&Array.isArray(s))r="_packed_params._packed_params",n=t.substring(0,t.length-r.length-1);else{let e=t.split(".");e.length<2&&(e=["",e[0]]),r=e.pop(),n=e.join(".")}e.has(n)||e.set(n,{name:n,states:[],attributes:[]});const o=e.get(n);switch(r){case"_packed_params.dtype":o.attributes.push({name:r,value:s});break;case"_packed_params._packed_params":o.states.push({name:r,arguments:s.map((t=>({id:"",value:t})))});break;default:if(o.states.push({name:r,arguments:[{id:t,value:s}]}),""==o.name&&o.states.length>4)return null}}}return e.values()}return null}_convertStateDictMap(t){if(!t||Array.isArray(t))return null;const e=[],n={};for(const s in t){const r=s.split(".");if(r.length<1)return null;const o={};if(o.id=s,o.name=r.pop(),o.value=t[s],o.value&&"torch.nn.parameter"===o.value.__module__&&"Parameter"===o.value.__name__&&pytorch.Utility.isTensor(o.value.data)&&(o.value=o.value.data),!pytorch.Utility.isTensor(o.value))return null;const i=r.join(".");let a=n[i];a||(a={},a.name=i,a.states=[],n[i]=a,e.push(a)),a.states.push({name:o.name,arguments:[o]})}return e}_convertStateDictGroupMap(t){if(!t||Array.isArray(t))return null;const e=[],n={};for(const s in t){let r=n[s];r||(r={},r.name=s,r.states=[],r.attributes=[],n[s]=r,e.push(r));const o=t[s];if(!o)return null;if(o instanceof Map)for(const t of o){const e=t[0],n=t[1];if(!e)return null;if(n&&!pytorch.Utility.isTensor(n))return null;const o={id:s+"."+e,value:n};r.states.push({name:e,arguments:[o]})}else{if(o instanceof Uint8Array)return null;if(Object(o)!==o)return null;{let t=!1;for(const e in o){const n=o[e];if(pytorch.Utility.isTensor(n)){const o={id:s+"."+e,value:n};r.states.push({name:e,arguments:[o]}),t=!0}else if(n!==Object(n))r.attributes.push({name:e,value:n});else{if(!n||!n.data||"torch.nn.parameter"!==n.__module__||"Parameter"!==n.__name__)return null;{const o={id:s+"."+e,value:n.data};r.states.push({name:e,arguments:[o]}),t=!0}}}if(!t)return null}}}return e}},pytorch.Container.Zip=class{constructor(t,e,n,s,r){this._entries=t,this._metadata=e,this._pickle=n,this._python=s,this._exceptionCallback=r;const o=this._entries.find((t=>"model.json"==t.name||"data.pkl"==t.name||t.name.endsWith("/model.json")||t.name.endsWith("/data.pkl")));if(!o)throw new pytorch.Error("PyTorch Zip container does not contain 'data.pkl' or 'model.json'.");const i=o.name.lastIndexOf("/");this._prefix=-1===i?"":o.name.substring(0,i+1),this._utf8Decoder=new TextDecoder("utf-8")}get format(){if(void 0===this._format)if(this._entry("model.json"))this._format=this._entry("attributes.pkl")?"TorchScript v1.1":"TorchScript v1.0";else if(this._entry("data.pkl")){const t=this._entry("version"),e=t?this._utf8Decoder.decode(t.data).split("\n").shift():"",n={1:"v1.3",2:"v1.4",3:"v1.6",4:"v1.7"}[e];n||this._exceptionCallback(new pytorch.Error("Unsupported PyTorch Zip version '"+e+"'.")),this._format=(this._entry("constants.pkl")?"TorchScript":"PyTorch")+" "+(n||"v-"+e.toString())}return this._format}get producer(){return this.data?this._producer:""}get name(){return this._name}get data(){if(void 0===this._data){this._data=null;const t=this._entry("data.pkl");if(t&&t.data)this._data=this._unpickle(t.data,this._storage("data"));else{const t=this._entry("model.json");if(t){const e=JSON.parse(this._utf8Decoder.decode(t.data));this._producer=e.producerName+(e.producerVersion?" v"+e.producerVersion:""),this._data=e.mainModule||{},this._name=this._data.name||"",this._data.torchscriptArena&&(this._torchscriptArena=this._data.torchscriptArena.key);const n=[this._data],s=new Map;for(const t of this._entries)s.set(t.name,t.data);const r=new Map([["FLOAT","Float"],["FLOAT16","Half"],["DOUBLE","Double"],["INT8","Char"],["INT32","Int"],["INT64","Long"]]);this._constants=e.tensors||[];for(const t of this._constants){const e=this._prefix+t.data.key;if(!r.has(t.dataType))throw new pytorch.Error("Unknown tensor data type '"+t.dataType+"'.");const n=r.get(t.dataType);t.__module__="torch",t.__name__="Tensor",t.name=t.data.key,t.size=t.dims?t.dims.map((t=>parseInt(t,10))):null,t.storage=this.execution.invoke("torch."+n+"Storage",[t.size]),t.storage.data=s.get(e)}for(;n.length>0;){const t=n.shift();if(t.__module__||t.__name__||(t.__module__="torch.nn.modules.module",t.__name__="Module"),t.name&&(t.__id__=t.name),t.submodules){for(const e of t.submodules)t[e.name]=e,e.__parent__=t,n.push(e);delete t.submodules}let e=[];t.parameters&&(e=e.concat(t.parameters),delete t.parameters),t.arguments&&(e=e.concat(t.arguments),delete t.arguments);for(const n of e){const e=this._constants[n.tensorId];t[n.name]=e,n.__module__&&n.__name__||(n.__module__="torch",n.__name__="Tensor")}}}}}return this._data}get constants(){if(void 0===this._constants){this._constants=[];const t=this._entry("constants.pkl");t&&t.data&&(this._constants=this._unpickle(t.data,this._storage("constants")))}return this._constants}get execution(){if(void 0===this._execution){this._types=new Map;const t={};for(const e of this._entries)if(e.name.startsWith(this._prefix+"code")){const n=e.name.substring(this._prefix.length);if(t[n])throw new pytorch.Error("Duplicate source file '"+n+"'.");t[n]=e.data}this._execution=new pytorch.Container.Zip.Execution(this._python,t,this._exceptionCallback,this._metadata);const e={};for(let t=0;te.name==this._prefix+t))}_unpickle(t,e){const n=new Map;return new this._pickle.Unpickler(t).load(((t,e)=>this.execution.invoke(t,e)),(t=>{const s=t.shift();if("storage"!==s)throw new pytorch.Error("Unknown persistent load type '"+s+"'.");const r=t.shift(),o=t.shift();t.shift();const i=t.shift();let a=null;n.has(o)?a=n.get(o):(a=this.execution.invoke(r,[i]),a.data=e.get(o),n.set(o,a));const c=t.shift();if(c){const t=c.shift();c.shift(),c.shift();let e=null;return n.has(t)?e=n.get(o):(e=null,n.set(t,e)),e}return a}))}_storage(t){const e=new Map,n=this._prefix+t+"/";for(const t of this._entries)if(t.name.startsWith(n)){const s=t.name.substring(n.length);e.set(s,t.data)}return e}_type(t){if(!this._types.has(t)){const e=t.split("."),n=e.pop(),s="code/"+e.join("/")+".py",r=this.execution.parse(s);if(r)for(const e of r.body)if("class"===e.type&&e.name==n){this._types.set(t,e);break}}return this._types.get(t)}trace(){if(this._inputs=[],this._outputs=[],this.execution.reset(),this._torchscriptArena){const t=this.execution.parse(this._torchscriptArena);for(const e of t.body)if("def"==e.type){const t=this,n=this.execution.context,s={__class__:this.execution.context.scope.builtins.function,__name__:e.name,__code__:e,__call__:function(e){return t.execution.apply(this.__code__,e,n)}};this.data[e.name]=s}}if(this.data.forward){const t=[this.data];if(this.data.forward.__code__&&this.data.forward.__code__.parameters)for(const e of this.data.forward.__code__.parameters)if("self"!==e.name){const n=e.parameterType;"type"===n.type&&n.name.type&&("Tensor"===n.name.value&&(this._inputs.push(e.name),t.push({__module__:"torch",__name__:"Tensor",__variable__:e.name,__origin__:"trace-input-tensor"})),"Tuple"===n.name.value&&n.arguments.every((t=>"type"===t.type&&"id"===t.name.type&&"Tensor"===t.name.value))&&(this._inputs.push(e.name),t.push(n.arguments.map((()=>({__module__:"torch",__name__:"Tensor",__variable__:e.name,__origin__:"trace-input-tuple"}))))),"List"===n.name.value&&n.arguments.every((t=>"type"===t.type&&"id"===t.name.type&&"Tensor"===t.name.value))&&(this._inputs.push(e.name),t.push([{__module__:"torch",__name__:"Tensor",__variable__:e.name,size:[NaN,NaN],__origin__:"trace-input-list"}])))}const e=this.data.forward.__call__(t),n=Array.isArray(e)?e:[e];for(const t of n)pytorch.Utility.isTensor(t)&&this._outputs.push(t.__variable__);return this._nodes=this.execution.nodes,!0}throw new pytorch.Error("Module 'forward' not implemented.")}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},pytorch.Container.Zip.Execution=class extends pytorch.Execution{constructor(t,e,n,s){super(t,e,n),this._metadata=s,this.reset()}reset(){this._nodes=[],this._variableIndex=0}get nodes(){return this._nodes}call(t,e,n,s){let r=pytorch.Utility.target(t),o=null;if(r&&r+"."+e=="ops.prim.NumToTensor"&&1===n.length&&"call"===n[0].type&&"id"==n[0].target.member.type){const t=n[0];r=pytorch.Utility.target(t.target.target),n=t.arguments,e=t.target.member.value,o=["int64"]}if(r){const t=r+"."+e;let i=this._metadata.type(t);if(i){Array.isArray(i)||(i=[i]);const e=n.map((t=>"="===t.type&&t.target&&"id"===t.target.type?this.expression(t.expression,s):this.expression(t,s)));for(const r of i){const i=Array.prototype.slice.call(n),a=Array.prototype.slice.call(e),c={type:r.name,inputs:[],attributes:[],outputs:[]},_=[];let u=!1;const h=Array.prototype.slice.call(r.inputs||[]).concat(Array.prototype.slice.call(r.attributes||[]));for(;h.length>0&&a.length>0;){if(i.every((t=>"="===t.type&&t.target&&"id"===t.target.type))&&h.every((t=>"tensor"!==t.type&&"tensor[]"!==t.type))){const t=new Map;for(const e of h)t.set(e.name,e);for(;i.length>0;){const e=i.shift(),n=a.shift(),s=t.get(e.target.value);if(!s){u=!0;break}if(!pytorch.Utility.isType(n,s.type)){if(s.optional)continue;u=!0;break}c.attributes.push({name:s.name,value:n})}continue}if(u)break;const t=h.shift();switch(t.type){case"tensor":{let e=a[0];if(Array.isArray(e)||!pytorch.Utility.isTensor(e)&&null!==e){if(t.optional){void 0===e&&(i.shift(),a.shift());continue}u=!0;break}i.shift(),a.shift(),null===e&&(e={}),e.__variable__||(e.__variable__=this._variable());const n=[];n.push({id:e.__variable__}),_.push(e),c.inputs.push(n);break}case"tensor[]":{const e=a[0];if(!Array.isArray(e)||!e.every((t=>pytorch.Utility.isTensor(t)||null===t))){if(t.optional)continue;u=!0;break}i.shift(),a.shift();const n=[];for(let t of e)null===t&&(t={}),t.__variable__||(t.__variable__=this._variable()),n.push({id:t.__variable__}),_.push(t);c.inputs.push(n);break}default:{const e=i[0],n=a[0];if(!pytorch.Utility.isType(n,t.type)){if(t.optional)continue;u=!0;break}if("="===e.type)throw new pytorch.Error("Expected named argument.");i.shift(),a.shift(),c.attributes.push({name:t.name,value:n});break}}if(u)break}if(u)continue;const l=[];for(const e of r.outputs)switch(e.type){case"tensor":{const e={__module__:"torch",__name__:"Tensor",__origin__:"invoke-output-"+t};switch(t){case"torch.cat":case"torch.conv2d":case"torch.dropout":case"torch.flatten":case"torch.max_pool2d":case"torch.quantize_per_tensor":case"torch.relu_":case"torch.hardtanh_":case"torch.slice":e.size=[NaN,NaN,NaN,NaN];break;case"torch.conv3d":e.size=[NaN,NaN,NaN,NaN,NaN];break;case"torch.embedding":e.size=[NaN,NaN,NaN];break;case"torch.ones":case"torch.zeros":case"torch.zeros_like":e.size=this.expression(n[0],s)}e.__variable__=this._variable(),l.push(e),c.outputs.push([{id:e.__variable__}]);break}case"tensor[]":{let e=1;switch(t){case"torch.chunk":e=c.attributes.filter((t=>"chunks"==t.name))[0].value}const n=[],s=[];for(let r=0;r1?l:l[0]}}}}return super.call(t,e,n,s)}_variable(){return this._variableIndex++,this._variableIndex.toString()}},pytorch.ScalarType={uint8:0,int8:1,int16:2,int32:3,int64:4,float16:5,float32:6,float64:7,complex32:8,complex64:9,complex128:10,boolean:11,qint8:12,quint8:13,qint32:14,bfloat16:15},pytorch.MemoryFormat={Contiguous:0,Preserve:1,ChannelsLast:2,ChannelsLast3d:3},pytorch.Layout={Strided:0,Sparse:1,Mkldnn:2},pytorch.Utility=class{static target(t){return"id"==t.type?t.value:"."==t.type?pytorch.Utility.target(t.target)+"."+pytorch.Utility.target(t.member):null}static isTensor(t){return t&&("torch"===t.__module__||"torch.cuda"===t.__module__)&&t.__name__&&t.__name__.endsWith("Tensor")}static isType(t,e){switch(e){case"tensor":return!Array.isArray(t)&&(pytorch.Utility.isTensor(t)||null===t);case"tensor[]":return Array.isArray(t)&&t.length>0&&t.every((t=>pytorch.Utility.isTensor(t)||null===t));case"boolean":return!0===t||!1===t;case"int64":return Number.isInteger(t)||isNaN(t);case"int64[]":return Array.isArray(t)&&t.every((t=>Number.isInteger(t)||Number.isNaN(t)||void 0===t));case"float32":case"float64":return null!==t&&t!==Object(t);case"Layout":case"ScalarType":case"MemoryFormat":return Number.isInteger(t);case"Device":return null===t||t===Object(t);case"scalar":return null!==t||t!==Object(t)}return!0}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=pytorch.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/shim.90c09599987168babbcd.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/shim.90c09599987168babbcd.js new file mode 100644 index 0000000000000000000000000000000000000000..865cec0d1383f7a5f2812a4a6ae6c0a6733d0cc6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/shim.90c09599987168babbcd.js @@ -0,0 +1 @@ +(()=>{var t,i={87958:()=>{if("undefined"!=typeof window&&void 0!==window.Long&&(window.long={Long:window.Long}),DataView.prototype.getFloat16||(DataView.prototype.getFloat16=function(t,i){const e=this.getUint16(t,i),s=(31744&e)>>10;let r=1023&e;return r=0==s?r/1024*6103515625e-14:31==s?r?NaN:1/0:DataView.__float16_pow[s]*(1+r/1024),32768&e?-r:r},DataView.__float16_pow={1:1/16384,2:1/8192,3:1/4096,4:1/2048,5:1/1024,6:1/512,7:1/256,8:1/128,9:1/64,10:1/32,11:1/16,12:1/8,13:1/4,14:.5,15:1,16:2,17:4,18:8,19:16,20:32,21:64,22:128,23:256,24:512,25:1024,26:2048,27:4096,28:8192,29:16384,30:32768,31:65536}),!DataView.prototype.setFloat16){DataView.prototype.setFloat16=function(t,i,e){DataView.__float16_float[0]=i;const s=(i=DataView.__float16_int[0])>>>23&255,r=8388607&i,n=i>>>16&32768|DataView.__float16_base[s]|r>>DataView.__float16_shift[s];this.setUint16(t,n,e)},DataView.__float16_float=new Float32Array(1),DataView.__float16_int=new Uint32Array(DataView.__float16_float.buffer,0,DataView.__float16_float.length),DataView.__float16_base=new Uint32Array(256),DataView.__float16_shift=new Uint32Array(256);for(let t=0;t<256;++t){const i=t-127;i<-27?(DataView.__float16_base[t]=0,DataView.__float16_shift[t]=24):i<-14?(DataView.__float16_base[t]=1024>>-i-14,DataView.__float16_shift[t]=-i-1):i<=15?(DataView.__float16_base[t]=i+15<<10,DataView.__float16_shift[t]=13):i<128?(DataView.__float16_base[t]=31744,DataView.__float16_shift[t]=24):(DataView.__float16_base[t]=31744,DataView.__float16_shift[t]=13)}}DataView.prototype.getBits||(DataView.prototype.getBits=function(t,i){if(t*=i,i>(this.byteLength<<3)-t)throw new RangeError;let e=0,s=0;for(;s>3)>>8-n-r&~(255<{var s={},r=r||{Long:e(27808)};s.get=t=>(s._map=s._map||new Map,s._map.has(t)||s._map.set(t,{}),s._map.get(t)),s.Long=r.Long,s.Reader=class{constructor(t){this._buffer=t,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength)}get root(){return this.int32(this._position)+this._position}identifier(t){if(4!==t.length)throw new s.Error("File identifier must be 4 characters in length.");for(let i=0;i<4;i++)if(t.charCodeAt(i)!=this.int8(this._position+4+i))return!1;return!0}bool(t){return!!this.int8(t)}bool_(t,i,e){return(i=this._offset(t,i))?this.bool(t+i):e}int8(t){return this.uint8(t)<<24>>24}int8_(t,i,e){return(i=this._offset(t,i))?this.int8(t+i):e}uint8(t){return this._buffer[t]}uint8_(t,i,e){return(i=this._offset(t,i))?this.uint8(t+i):e}int16(t){return this._dataView.getInt16(t,!0)}int16_(t,i,e){return(i=this._offset(t,i))?this.int16(t+i):e}uint16(t){return this._dataView.getUint16(t,!0)}uint16_(t,i,e){return(i=this._offset(t,i))?this.uint16(t+i):e}int32(t){return this._dataView.getInt32(t,!0)}int32_(t,i,e){return(i=this._offset(t,i))?this.int32(t+i):e}uint32(t){return this._dataView.getUint32(t,!0)}uint32_(t,i,e){return(i=this._offset(t,i))?this.int32(t+i):e}int64(t){return new s.Long(this.int32(t),this.int32(t+4))}uint64(t){return new s.Long(this.uint32(t),this.uint32(t+4))}float32(t){return this._dataView.getFloat32(t,!0)}float32_(t,i,e){return(i=this._offset(t,i))?this.float32(t+i):e}float64(t){return this._dataView.getFloat64(t,!0)}float64_(t,i,e){return(i=this._offset(t,i))?this.float64(t+i):e}string(t,i){t+=this.int32(t);const e=this.int32(t);var s="",r=0;if(t+=4,1===i)return this._buffer.subarray(t,t+e);for(;r>10),56320+(1023&n)))}return s}string_(t,i,e){return(i=this._offset(t,i))?this.string(t+i):e}bools_(t,i){if(i=this._offset(t,i)){const e=this._length(t+i);i=this._vector(t+i);const s=new Array(e);for(let t=0;t>3)),this.uint32(i+(t>>3)+4),!1);return r}return[]}strings_(t,i){if(i=this._offset(t,i)){const e=this._length(t+i);i=this._vector(t+i);const s=new Array(e);for(let t=0;t{var s=s||{},r=r||{Long:e(27808)};s.get=t=>(s._map=s._map||new Map,s._map.has(t)||s._map.set(t,{}),s._map.get(t)),s.Reader=class{constructor(t){this._buffer=t,this._length=t.length,this._position=0,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._decoder=new TextDecoder("utf-8")}static create(t){return new s.Reader(t)}next(t){return void 0===t?this._length:this._position+t}end(t){return this._positionthis._length)throw this._indexOutOfRangeError(t);return this._position+=t,this._buffer.slice(i,e)}uint32(){let t=4294967295;if(t=(127&this._buffer[this._position])>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<7)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<14)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(127&this._buffer[this._position])<<21)>>>0,this._buffer[this._position++]<128)return t;if(t=(t|(15&this._buffer[this._position])<<28)>>>0,this._buffer[this._position++]<128)return t;if((this._position+=5)>this._length)throw this._position=this._length,this._indexOutOfRangeError(10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)|0}int64(){return this._readLongVarint().toLong(!1)}uint64(){return this._readLongVarint().toLong(!0)}sint64(){return this._readLongVarint().zzDecode().toLong(!1)}fixed64(){return this._readFixed64().toLong(!0)}sfixed64(){return this._readFixed64().toLong(!1)}fixed32(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);return this._position+=4,this._readFixed32()}sfixed32(){return 0|this.fixed32()}float(){if(this._position+4>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=4,this._dataView.getFloat32(t,!0)}double(){if(this._position+8>this._length)throw this._indexOutOfRangeError(4);const t=this._position;return this._position+=8,this._dataView.getFloat64(t,!0)}array(t,i,e){if(2==(7&e)){const e=this.uint32()+this._position;for(;this._position0)throw new s.Error("Invalid packed float array.");const i=this.uint32(),e=this._position+i,r=i>>>2;t=i>1048576?new Float32Array(r):new Array(r);let n=this._position;for(let i=0;i0)throw new s.Error("Invalid packed float array.");const i=this.uint32(),e=this._position+i,r=i>>>3;t=i>1048576?new Float64Array(r):new Array(r);let n=this._position;for(let i=0;ithis._length)throw this._indexOutOfRangeError(t);this._position+=t}else do{if(this._position>=this._length)throw this._indexOutOfRangeError()}while(128&this._buffer[this._position++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw new s.Error("invalid wire type "+t+" at offset "+this._position)}}pair(t,i,e){this.skip(),this._position++;const r="object"==typeof i?s.LongBits.hash(i()):i();this._position++;const n=e();t[r]=n}_readFixed32(){return(this._buffer[this._position-4]|this._buffer[this._position-3]<<8|this._buffer[this._position-2]<<16|this._buffer[this._position-1]<<24)>>>0}_readFixed64(){if(this._position+8>this._length)throw this._indexOutOfRangeError(8);this._position+=4;const t=this._readFixed32();this._position+=4;const i=this._readFixed32();return new s.LongBits(t,i)}_readLongVarint(){const t=new s.LongBits(0,0);let i=0;if(!(this._length-this._position>4)){for(;i<3;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t}return t.lo=(t.lo|(127&this._buffer[this._position++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this._buffer[this._position])<<7*i)>>>0,this._buffer[this._position++]<128)return t;if(t.lo=(t.lo|(127&this._buffer[this._position])<<28)>>>0,t.hi=(t.hi|(127&this._buffer[this._position])>>4)>>>0,this._buffer[this._position++]<128)return t;if(i=0,this._length-this._position>4){for(;i<5;++i)if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}else for(;i<5;++i){if(this._position>=this._length)throw this._indexOutOfRangeError();if(t.hi=(t.hi|(127&this._buffer[this._position])<<7*i+3)>>>0,this._buffer[this._position++]<128)return t}throw new s.Error("Invalid varint encoding.")}_indexOutOfRangeError(t){return RangeError("index out of range: "+this._position+" + "+(t||1)+" > "+this._length)}},s.TextReader=class{constructor(t){this._text=t,this._position=0,this._lineEnd=-1,this._lineStart=0,this._line=-1,this._depth=0,this._arrayDepth=0,this._token=""}static create(t){return new s.TextReader(t)}start(){this._depth>0&&this.expect("{"),this._depth++}end(){const t=this.peek();return this._depth>0&&"}"===t?(this.expect("}"),this.match(";"),this._depth--,!0):""===t}tag(){const t=this.read(),i=this.peek();return"["!==i&&"{"!==i&&this.expect(":"),t}assert(t){const i=this.tag();if(i!==t)throw new s.Error("Unexpected '"+i+"' instead of '"+t+"'"+this.location())}integer(){const t=this.read(),i=Number.parseInt(t,10);if(Number.isNaN(t-i))throw new s.Error("Couldn't parse integer '"+t+"'"+this.location());return this.semicolon(),i}float(){let t=this.read();if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;t.endsWith("f")&&(t=t.substring(0,t.length-1));const i=Number.parseFloat(t);if(Number.isNaN(t-i))throw new s.Error("Couldn't parse float '"+t+"'"+this.location());return this.semicolon(),i}string(){const t=this.read();if(t.length<2)throw new s.Error("String is too short"+this.location());const i=t[0];if("'"!==i&&'"'!==i)throw new s.Error("String is not in quotes"+this.location());if(i!==t[t.length-1])throw new s.Error("String quotes do not match"+this.location());const e=t.substring(1,t.length-1);return this.semicolon(),e}boolean(){const t=this.read();switch(t){case"true":case"True":case"1":return this.semicolon(),!0;case"false":case"False":case"0":return this.semicolon(),!1}throw new s.Error("Couldn't parse boolean '"+t+"'"+this.location())}bytes(){const t=this.string();let i=0,e=0;const r=t.length,n=new Uint8Array(r);for(;i=r)throw new s.Error("Unexpected end of bytes string"+this.location());switch(o=t.charCodeAt(i++),o){case 39:n[e++]=39;break;case 92:n[e++]=92;break;case 34:n[e++]=34;break;case 114:n[e++]=13;break;case 110:n[e++]=10;break;case 116:n[e++]=9;break;case 98:n[e++]=8;break;case 88:case 120:for(let o=0;o<2;o++){if(i>=r)throw new s.Error("Unexpected end of bytes string"+this.location());let o=t.charCodeAt(i++);if(o=o>=65&&o<=70?o-55:o>=97&&o<=102?o-87:o>=48&&o<=57?o-48:-1,-1===o)throw new s.Error("Unexpected hex digit '"+o+"' in bytes string"+this.location());n[e]=n[e]<<4|o}e++;break;default:if(o<48||o>57)throw new s.Error("Unexpected character '"+o+"' in bytes string"+this.location());i--;for(let o=0;o<3;o++){if(i>=r)throw new s.Error("Unexpected end of bytes string"+this.location());const o=t.charCodeAt(i++);if(o<48||o>57)throw new s.Error("Unexpected octal digit '"+o+"' in bytes string"+this.location());n[e]=n[e]<<3|o-48}e++}}}return n.slice(0,e)}enum(t){const i=this.read();if(!Object.prototype.hasOwnProperty.call(t,i)){const t=Number.parseInt(i,10);if(!Number.isNaN(i-t))return this.semicolon(),t;throw new s.Error("Couldn't parse enum '"+i+"'"+this.location())}return this.semicolon(),t[i]}any(t){if(this.match("[")){this.read();const i=this._position,e=this._text.indexOf("]",i);if(-1===e||e>=this.next)throw new s.Error("End of Any type_url not found"+this.location());return t.type_url=this._text.substring(i,e),this._position=e+1,t.value=this.skip().substring(1),this.expect("}"),this.match(";"),!0}return!1}pair(t,i,e){let s,r;for(this.start();!this.end();)switch(this.tag()){case"key":s=i();break;case"value":r=e()}t[s]=r}array(t,i){if(this.first())for(;!this.last();)t.push(i()),this.next();else t.push(i())}first(){return!!this.match("[")&&(this._arrayDepth++,!0)}last(){return!!this.match("]")&&(this._arrayDepth--,!0)}next(){const t=this.peek();","!==t?"]"!==t&&this.handle(t):this.read()}skip(){let t=this.peek();if("{"===t){const i=this._position,e=this._depth;for(this.start();!this.end()||e=this._lineEnd;){if(this._lineStart=this._lineEnd+1,this._position=this._lineStart,this._position>=this._text.length)return!1;this._lineEnd=this._text.indexOf("\n",this._position),-1===this._lineEnd&&(this._lineEnd=this._text.length),this._line++}switch(this._text[this._position]){case" ":case"\r":case"\t":this._position++;break;case"#":this._position=this._lineEnd;break;default:return!0}}}tokenize(){if(!this.whitespace())return this._token="",this._token;let t=this._text[this._position];if("["===t&&this._position+2="a"&&i<="z"||i>="A"&&i<="Z")for(t++;t="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||"."===i||"/"===i)&&"]"===i)return this._token=this._text.substring(this._position,t),this._token}if("{"===t||"}"===t||":"===t||"["===t||","===t||"]"===t||";"===t)return this._token=t,this._token;let i=this._position+1;if(t>="a"&&t<="z"||t>="A"&&t<="Z"||"_"===t||"$"===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if(t>="0"&&t<="9"||"-"===t||"+"===t||"."===t){for(;i="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t||"+"===t||"-"===t||"."===t);)i++;return this._token=this._text.substring(this._position,i),this._token}if('"'===t||"'"===t){const e=t;for(;i>>0,this.hi=i>>>0}toLong(t){return s.Long?new s.Long(0|this.lo,0|this.hi,t):{low:0|this.lo,high:0|this.hi,unsigned:t}}toNumber(t){if(!t&&this.hi>>>31){const t=1+~this.lo>>>0;let i=~this.hi>>>0;return t||(i=i+1>>>0),-(t+4294967296*i)}return this.lo+4294967296*this.hi}toHash(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}from(t){if("number"==typeof t)return s.LongBits.fromNumber(t);if("string"==typeof t||t instanceof String){if(!s.Long)return s.LongBits.fromNumber(parseInt(t,10));t=s.Long.fromString(t)}return t.low||t.high?new s.LongBits(t.low>>>0,t.high>>>0):s.LongBits.zero}hash(t){return t?s.LongBits.from(t).toHash():"\0\0\0\0\0\0\0\0"}},s.LongBits.zero=new s.LongBits(0,0),s.LongBits.zero.toNumber=function(){return 0},s.LongBits.zero.zzDecode=function(){return this},s.Error=class extends Error{constructor(t){super(t),this.name="Protocol Buffer Error",this.message=t}},"object"==typeof t.exports&&(t.exports.Reader=s.Reader,t.exports.TextReader=s.TextReader,t.exports.Error=s.Error,t.exports.Long=s.Long,t.exports.get=s.get)},71681:(t,i,e)=>{var s=e(32845),r=r||{};r.Archive=class{constructor(t){if(this._entries=[],t.length<4||80!=t[0]||75!=t[1])throw new r.Error("Invalid Zip archive.");let i=null;for(let e=t.length-4;e>=0;e--)if(80===t[e]&&75===t[e+1]&&5===t[e+2]&&6===t[e+3]){i=new r.Reader(t,e+4,t.length);break}if(!i)throw new r.Error("End of central directory not found.");for(i.skip(12),i.position=i.uint32();i.match([80,75,1,2]);)this._entries.push(new r.Entry(i))}get entries(){return this._entries}},r.Entry=class{constructor(t){if(t.uint16(),t.skip(2),this._flags=t.uint16(),1==(1&this._flags))throw new r.Error("Encrypted entries not supported.");this._compressionMethod=t.uint16(),t.uint32(),t.uint32(),this._compressedSize=t.uint32(),this._size=t.uint32();let i=t.uint16(),e=t.uint16();const s=t.uint16();t.uint16(),t.uint16(),t.uint32();const n=t.uint32();t.skip(i),t.skip(e),t.bytes(s);const o=t.position;if(t.position=n,!t.match([80,75,3,4]))throw new r.Error("Invalid local file header signature.");t.skip(22),i=t.uint16(),e=t.uint16();const h=t.bytes(i);this._name="";for(const t of h)this._name+=String.fromCharCode(t);t.skip(e),this._compressedData=t.bytes(this._compressedSize),t.position=o}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new r.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new r.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new r.Error("Invalid uncompressed size.");break;default:throw new r.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},r.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),r.HuffmanTree._offsets=r.HuffmanTree._offsets||new Uint16Array(16)}build(t,i,e){for(let t=0;t<16;++t)this.table[t]=0;for(let s=0;s>>1){case 0:this._inflateUncompressedBlock(i,n);break;case 1:this._inflateBlockData(i,n,r.HuffmanTree.staticLiteralLengthTree,r.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(i,o,h),this._inflateBlockData(i,n,o,h);break;default:throw new r.Error("Unknown block type.")}}while(0==(1&a));return n.merge()}_inflateUncompressedBlock(t,i){for(;t.data>8;)t.position--,t.data-=8;t.data=0;const e=t.uint16();if(e!==(65535&~t.uint16()))throw new r.Error("Invalid uncompressed block length.");const s=t.bytes(e);i.push(s),e>32768?(i.buffer.set(s.subarray(s.length-32768,s.length),0),i.position=32768):(i.reset(),i.buffer.set(s,i.position),i.position+=s.length)}_decodeTrees(t,i,e){const s=t.bits(5)+257,n=t.bits(5)+1,o=t.bits(4)+4;for(let t=0;t<19;t++)r.Inflater._lengths[t]=0;for(let i=0;i62464&&(i.position=o,i.push(new Uint8Array(n.subarray(h,o))),o=i.reset(),h=o);let a=t.symbol(e);if(256===a)return i.position=o,i.push(new Uint8Array(n.subarray(h,i.position))),void i.reset();if(a<256)n[o++]=a;else{a-=257;const i=t.bitsBase(r.Inflater._lengthBits[a],r.Inflater._lengthBase[a]),e=t.symbol(s);let h=o-t.bitsBase(r.Inflater._distanceBits[e],r.Inflater._distanceBase[e]);for(let t=0;t32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(t){this._blocks.push(t)}merge(){let t=0;for(const i of this._blocks)t+=i.length;const i=new Uint8Array(t);let e=0;for(const t of this._blocks)i.set(t,e),e+=t.length;return i}},r.BitReader=class{constructor(t){this.buffer=t,this.position=0,this.data=0,this.value=0}bits(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,i}bitsBase(t,i){if(0==t)return i;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,e+i}bytes(t){const i=this.buffer.subarray(this.position,this.position+t);return this.position+=t,i}uint16(){const t=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,t}symbol(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,s++,i+=n[s],e-=n[s]}while(e>=0);return this.value=r,this.data-=s,t.symbol[i+e]}},r.Reader=class{constructor(t,i,e){this._buffer=t,this._position=i,this._end=e}match(t){if(this._position+t.length<=this._end)for(let i=0;i=0?t:this._end+t}peek(){return this._positionthis._end)throw new r.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new r.Error("Data not available.");t=void 0===t?this._end:t;const i=this._buffer.subarray(this._position,this._position+t);return this._position+=t,i}uint16(){if(this._position+2>this._end)throw new r.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}},r.Error=class extends Error{constructor(t){super(t),this.name="Zip Error"}},"object"==typeof t.exports&&(t.exports.Archive=r.Archive,t.exports.Inflater=r.Inflater)},27918:(t,i,e)=>{window.base=e(87958),window.flatbuffers=e(45570),window.long={Long:e(27808)},window.protobuf=e(81600),window.zip=e(71681)},83260:()=>{}},e={};function s(t){var r=e[t];if(void 0!==r)return r.exports;var n=e[t]={id:t,loaded:!1,exports:{}};return i[t].call(n.exports,n,n.exports,s),n.loaded=!0,n.exports}s.m=i,t=[],s.O=(i,e,r,n)=>{if(!e){var o=1/0;for(l=0;l=n)&&Object.keys(s.O).every((t=>s.O[t](e[a])))?e.splice(a--,1):(h=!1,n0&&t[l-1][2]>n;l--)t[l]=t[l-1];t[l]=[e,r,n]},s.d=(t,i)=>{for(var e in i)s.o(i,e)&&!s.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:i[e]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),s.o=(t,i)=>Object.prototype.hasOwnProperty.call(t,i),s.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},s.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),s.j=307,(()=>{var t={307:0};s.O.j=i=>0===t[i];var i=(i,e)=>{var r,n,[o,h,a]=e,f=0;if(o.some((i=>0!==t[i]))){for(r in h)s.o(h,r)&&(s.m[r]=h[r]);if(a)var l=a(s)}for(i&&i(e);fs(27918)));r=s.O(r)})(); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..724c4c12977a5f819f1a30141d542df5033b3833 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn-metadata.json @@ -0,0 +1 @@ +[{"name":"sklearn.preprocessing.Binarizer","schema":{"attributes":[{"default":true,"description":"set to False to perform inplace binarization and avoid a copy (if\nthe input is already a numpy array or a scipy.sparse CSR matrix).\n","name":"copy","option":"optional","type":"boolean"},{"default":0,"description":"Feature values below or equal to this are replaced by 0, above it by 1.\nThreshold may not be less than 0 for operations on sparse matrices.\n","name":"threshold","option":"optional","type":"float32"}],"description":"Binarize data (set feature values to 0 or 1) according to a threshold\n\nValues greater than the threshold map to 1, while values less than\nor equal to the threshold map to 0. With the default threshold of 0,\nonly positive values map to 1.\n\nBinarization is a common operation on text count data where the\nanalyst can decide to only consider the presence or absence of a\nfeature rather than a quantified number of occurrences for instance.\n\nIt can also be used as a pre-processing step for estimators that\nconsider boolean random variables (e.g. modelled using the Bernoulli\ndistribution in a Bayesian setting).\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.preprocessing.MultiLabelBinarizer","schema":{"attributes":[{"description":"Indicates an ordering for the class labels.\nAll entries should be unique (cannot contain duplicate classes).\n","name":"classes","option":"optional"},{"description":"Set to true if output binary array is desired in CSR sparse format\n","name":"sparse_output"}],"description":"Transform between iterable of iterables and a multilabel format\n\nAlthough a list of sets or tuples is a very intuitive format for multilabel\ndata, it is unwieldy to process. This transformer converts between this\nintuitive format and the supported multilabel format: a (samples x classes)\nbinary matrix indicating the presence of a class label.\n"}},{"name":"sklearn.preprocessing.LabelEncoder","schema":{"description":"Encode target labels with value between 0 and n_classes-1.\n\nThis transformer should be used to encode target values, *i.e.* `y`, and\nnot the input `X`.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.12\n"}},{"name":"sklearn.svm.classes.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","type":"int32"},{"description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","type":"float32"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","type":"boolean"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","type":"boolean"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.svm.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","option":"optional","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel","option":"optional","type":"string"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","option":"optional","type":"int32"},{"default":"auto","description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma","option":"optional","type":"float32"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","option":"optional","type":"float32"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","option":"optional","type":"boolean"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","option":"optional","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","option":"optional","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","option":"optional","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight","option":"optional"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","option":"optional","type":"int32"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","option":"optional","type":"boolean"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.svm.SVC","schema":{"attributes":[{"default":1,"description":"Regularization parameter. The strength of the regularization is\ninversely proportional to C. Must be strictly positive. The penalty\nis a squared l2 penalty.\n","name":"C","option":"optional","type":"float32"},{"default":"rbf","description":"Specifies the kernel type to be used in the algorithm.\nIt must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or\na callable.\nIf none is given, 'rbf' will be used. If a callable is given it is\nused to pre-compute the kernel matrix from data matrices; that matrix\nshould be an array of shape ``(n_samples, n_samples)``.\n","name":"kernel","option":"optional","type":"string"},{"default":3,"description":"Degree of the polynomial kernel function ('poly').\nIgnored by all other kernels.\n","name":"degree","option":"optional","type":"int32"},{"default":"auto","description":"Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n- if ``gamma='scale'`` (default) is passed then it uses\n1 / (n_features * X.var()) as value of gamma,\n- if 'auto', uses 1 / n_features.\n\n.. versionchanged:: 0.22\nThe default value of ``gamma`` changed from 'auto' to 'scale'.\n","name":"gamma","option":"optional","type":"float32"},{"default":0,"description":"Independent term in kernel function.\nIt is only significant in 'poly' and 'sigmoid'.\n","name":"coef0","option":"optional","type":"float32"},{"default":true,"description":"Whether to use the shrinking heuristic.\nSee the :ref:`User Guide `.\n","name":"shrinking","option":"optional","type":"boolean"},{"default":false,"description":"Whether to enable probability estimates. This must be enabled prior\nto calling `fit`, will slow down that method as it internally uses\n5-fold cross-validation, and `predict_proba` may be inconsistent with\n`predict`. Read more in the :ref:`User Guide `.\n","name":"probability","option":"optional","type":"boolean"},{"default":0.001,"description":"Tolerance for stopping criterion.\n","name":"tol","option":"optional","type":"float32"},{"default":200,"description":"Specify the size of the kernel cache (in MB).\n","name":"cache_size","option":"optional","type":"float32"},{"default":null,"description":"Set the parameter C of class i to class_weight[i]*C for\nSVC. If not given, all classes are supposed to have\nweight one.\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n","name":"class_weight","option":"optional"},{"default":false,"description":"Enable verbose output. Note that this setting takes advantage of a\nper-process runtime setting in libsvm that, if enabled, may not work\nproperly in a multithreaded context.\n","name":"verbose","type":"boolean"},{"default":-1,"description":"Hard limit on iterations within solver, or -1 for no limit.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"ovr","description":"Whether to return a one-vs-rest ('ovr') decision function of shape\n(n_samples, n_classes) as all other classifiers, or the original\none-vs-one ('ovo') decision function of libsvm which has shape\n(n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n('ovo') is always used as multi-class strategy. The parameter is\nignored for binary classification.\n\n.. versionchanged:: 0.19\ndecision_function_shape is 'ovr' by default.\n\n.. versionadded:: 0.17\n*decision_function_shape='ovr'* is recommended.\n\n.. versionchanged:: 0.17\nDeprecated *decision_function_shape='ovo' and None*.\n","name":"decision_function_shape"},{"default":null,"description":"Controls the pseudo random number generation for shuffling the data for\nprobability estimates. Ignored when `probability` is False.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","option":"optional"},{"default":false,"description":"If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n:term:`predict` will break ties according to the confidence values of\n:term:`decision_function`; otherwise the first class among the tied\nclasses is returned. Please note that breaking ties comes at a\nrelatively high computational cost compared to a simple predict.\n\n.. versionadded:: 0.22\n","name":"break_ties","option":"optional","type":"boolean"}],"description":"C-Support Vector Classification.\n\nThe implementation is based on libsvm. The fit time scales at least\nquadratically with the number of samples and may be impractical\nbeyond tens of thousands of samples. For large datasets\nconsider using :class:`sklearn.svm.LinearSVC` or\n:class:`sklearn.linear_model.SGDClassifier` instead, possibly after a\n:class:`sklearn.kernel_approximation.Nystroem` transformer.\n\nThe multiclass support is handled according to a one-vs-one scheme.\n\nFor details on the precise mathematical formulation of the provided\nkernel functions and how `gamma`, `coef0` and `degree` affect each\nother, see the corresponding section in the narrative documentation:\n:ref:`svm_kernels`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.linear_model._logistic.LogisticRegression","schema":{"attributes":[{"default":"l2","description":"Used to specify the norm used in the penalization. The 'newton-cg',\n'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\nonly supported by the 'saga' solver. If 'none' (not supported by the\nliblinear solver), no regularization is applied.\n\n.. versionadded:: 0.19\nl1 penalty with SAGA solver (allowing 'multinomial' + L1)\n","name":"penalty"},{"default":false,"description":"Dual or primal formulation. Dual formulation is only implemented for\nl2 penalty with liblinear solver. Prefer dual=False when\nn_samples > n_features.\n","name":"dual","type":"boolean"},{"default":0.0001,"description":"Tolerance for stopping criteria.\n","name":"tol","type":"float32"},{"default":1,"description":"Inverse of regularization strength; must be a positive float.\nLike in support vector machines, smaller values specify stronger\nregularization.\n","name":"C","type":"float32"},{"default":true,"description":"Specifies if a constant (a.k.a. bias or intercept) should be\nadded to the decision function.\n","name":"fit_intercept","type":"boolean"},{"default":1,"description":"Useful only when the solver 'liblinear' is used\nand self.fit_intercept is set to True. In this case, x becomes\n[x, self.intercept_scaling],\ni.e. a \"synthetic\" feature with constant value equal to\nintercept_scaling is appended to the instance vector.\nThe intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\nNote! the synthetic feature weight is subject to l1/l2 regularization\nas all other features.\nTo lessen the effect of regularization on synthetic feature weight\n(and therefore on the intercept) intercept_scaling has to be increased.\n","name":"intercept_scaling","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one.\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n\n.. versionadded:: 0.17\n*class_weight='balanced'*\n","name":"class_weight"},{"default":null,"description":"Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\ndata. See :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":"lbfgs","description":"\nAlgorithm to use in the optimization problem.\n\n- For small datasets, 'liblinear' is a good choice, whereas 'sag' and\n'saga' are faster for large ones.\n- For multiclass problems, only 'newton-cg', 'sag', 'saga' and 'lbfgs'\nhandle multinomial loss; 'liblinear' is limited to one-versus-rest\nschemes.\n- 'newton-cg', 'lbfgs', 'sag' and 'saga' handle L2 or no penalty\n- 'liblinear' and 'saga' also handle L1 penalty\n- 'saga' also supports 'elasticnet' penalty\n- 'liblinear' does not support setting ``penalty='none'``\n\nNote that 'sag' and 'saga' fast convergence is only guaranteed on\nfeatures with approximately the same scale. You can\npreprocess the data with a scaler from sklearn.preprocessing.\n\n.. versionadded:: 0.17\nStochastic Average Gradient descent solver.\n.. versionadded:: 0.19\nSAGA solver.\n.. versionchanged:: 0.22\nThe default solver changed from 'liblinear' to 'lbfgs' in 0.22.\n","name":"solver"},{"default":100,"description":"Maximum number of iterations taken for the solvers to converge.\n","name":"max_iter","type":"int32"},{"default":"auto","description":"If the option chosen is 'ovr', then a binary problem is fit for each\nlabel. For 'multinomial' the loss minimised is the multinomial loss fit\nacross the entire probability distribution, *even when the data is\nbinary*. 'multinomial' is unavailable when solver='liblinear'.\n'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\nand otherwise selects 'multinomial'.\n\n.. versionadded:: 0.18\nStochastic Average Gradient descent solver for 'multinomial' case.\n.. versionchanged:: 0.22\nDefault changed from 'ovr' to 'auto' in 0.22.\n","name":"multi_class"},{"default":0,"description":"For the liblinear and lbfgs solvers set verbose to any positive\nnumber for verbosity.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to True, reuse the solution of the previous call to fit as\ninitialization, otherwise, just erase the previous solution.\nUseless for liblinear solver. See :term:`the Glossary `.\n\n.. versionadded:: 0.17\n*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Number of CPU cores used when parallelizing over classes if\nmulti_class='ovr'\". This parameter is ignored when the ``solver`` is\nset to 'liblinear' regardless of whether 'multi_class' is specified or\nnot. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors.\nSee :term:`Glossary ` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\nused if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\nto using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\nto using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\ncombination of L1 and L2.\n","name":"l1_ratio","type":"float32"}],"description":"\nLogistic Regression (aka logit, MaxEnt) classifier.\n\nIn the multiclass case, the training algorithm uses the one-vs-rest (OvR)\nscheme if the 'multi_class' option is set to 'ovr', and uses the\ncross-entropy loss if the 'multi_class' option is set to 'multinomial'.\n(Currently the 'multinomial' option is supported only by the 'lbfgs',\n'sag', 'saga' and 'newton-cg' solvers.)\n\nThis class implements regularized logistic regression using the\n'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note\nthat regularization is applied by default**. It can handle both dense\nand sparse input. Use C-ordered arrays or CSR matrices containing 64-bit\nfloats for optimal performance; any other input format will be converted\n(and copied).\n\nThe 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization\nwith primal formulation, or no regularization. The 'liblinear' solver\nsupports both L1 and L2 regularization, with a dual formulation only for\nthe L2 penalty. The Elastic-Net regularization is only supported by the\n'saga' solver.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.linear_model.LogisticRegression","schema":{"attributes":[{"default":"l2","description":"Used to specify the norm used in the penalization. The 'newton-cg',\n'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\nonly supported by the 'saga' solver. If 'none' (not supported by the\nliblinear solver), no regularization is applied.\n\n.. versionadded:: 0.19\nl1 penalty with SAGA solver (allowing 'multinomial' + L1)\n","name":"penalty","option":"optional"},{"default":false,"description":"Dual or primal formulation. Dual formulation is only implemented for\nl2 penalty with liblinear solver. Prefer dual=False when\nn_samples > n_features.\n","name":"dual","option":"optional","type":"boolean"},{"default":0.0001,"description":"Tolerance for stopping criteria.\n","name":"tol","option":"optional","type":"float32"},{"default":1,"description":"Inverse of regularization strength; must be a positive float.\nLike in support vector machines, smaller values specify stronger\nregularization.\n","name":"C","option":"optional","type":"float32"},{"default":true,"description":"Specifies if a constant (a.k.a. bias or intercept) should be\nadded to the decision function.\n","name":"fit_intercept","option":"optional","type":"boolean"},{"default":1,"description":"Useful only when the solver 'liblinear' is used\nand self.fit_intercept is set to True. In this case, x becomes\n[x, self.intercept_scaling],\ni.e. a \"synthetic\" feature with constant value equal to\nintercept_scaling is appended to the instance vector.\nThe intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\nNote! the synthetic feature weight is subject to l1/l2 regularization\nas all other features.\nTo lessen the effect of regularization on synthetic feature weight\n(and therefore on the intercept) intercept_scaling has to be increased.\n","name":"intercept_scaling","option":"optional","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one.\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n\n.. versionadded:: 0.17\n*class_weight='balanced'*\n","name":"class_weight","option":"optional"},{"default":null,"description":"Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\ndata. See :term:`Glossary ` for details.\n","name":"random_state","option":"optional","type":"int32"},{"default":"lbfgs","description":"\nAlgorithm to use in the optimization problem.\n\n- For small datasets, 'liblinear' is a good choice, whereas 'sag' and\n'saga' are faster for large ones.\n- For multiclass problems, only 'newton-cg', 'sag', 'saga' and 'lbfgs'\nhandle multinomial loss; 'liblinear' is limited to one-versus-rest\nschemes.\n- 'newton-cg', 'lbfgs', 'sag' and 'saga' handle L2 or no penalty\n- 'liblinear' and 'saga' also handle L1 penalty\n- 'saga' also supports 'elasticnet' penalty\n- 'liblinear' does not support setting ``penalty='none'``\n\nNote that 'sag' and 'saga' fast convergence is only guaranteed on\nfeatures with approximately the same scale. You can\npreprocess the data with a scaler from sklearn.preprocessing.\n\n.. versionadded:: 0.17\nStochastic Average Gradient descent solver.\n.. versionadded:: 0.19\nSAGA solver.\n.. versionchanged:: 0.22\nThe default solver changed from 'liblinear' to 'lbfgs' in 0.22.\n","name":"solver","option":"optional"},{"default":100,"description":"Maximum number of iterations taken for the solvers to converge.\n","name":"max_iter","option":"optional","type":"int32"},{"default":"auto","description":"If the option chosen is 'ovr', then a binary problem is fit for each\nlabel. For 'multinomial' the loss minimised is the multinomial loss fit\nacross the entire probability distribution, *even when the data is\nbinary*. 'multinomial' is unavailable when solver='liblinear'.\n'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\nand otherwise selects 'multinomial'.\n\n.. versionadded:: 0.18\nStochastic Average Gradient descent solver for 'multinomial' case.\n.. versionchanged:: 0.22\nDefault changed from 'ovr' to 'auto' in 0.22.\n","name":"multi_class","option":"optional"},{"default":0,"description":"For the liblinear and lbfgs solvers set verbose to any positive\nnumber for verbosity.\n","name":"verbose","option":"optional","type":"int32"},{"default":false,"description":"When set to True, reuse the solution of the previous call to fit as\ninitialization, otherwise, just erase the previous solution.\nUseless for liblinear solver. See :term:`the Glossary `.\n\n.. versionadded:: 0.17\n*warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.\n","name":"warm_start","option":"optional","type":"boolean"},{"default":null,"description":"Number of CPU cores used when parallelizing over classes if\nmulti_class='ovr'\". This parameter is ignored when the ``solver`` is\nset to 'liblinear' regardless of whether 'multi_class' is specified or\nnot. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors.\nSee :term:`Glossary ` for more details.\n","name":"n_jobs","option":"optional","type":"int32"},{"default":null,"description":"The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\nused if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\nto using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\nto using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\ncombination of L1 and L2.\n","name":"l1_ratio","option":"optional","type":"float32"}],"description":"\nLogistic Regression (aka logit, MaxEnt) classifier.\n\nIn the multiclass case, the training algorithm uses the one-vs-rest (OvR)\nscheme if the 'multi_class' option is set to 'ovr', and uses the\ncross-entropy loss if the 'multi_class' option is set to 'multinomial'.\n(Currently the 'multinomial' option is supported only by the 'lbfgs',\n'sag', 'saga' and 'newton-cg' solvers.)\n\nThis class implements regularized logistic regression using the\n'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note\nthat regularization is applied by default**. It can handle both dense\nand sparse input. Use C-ordered arrays or CSR matrices containing 64-bit\nfloats for optimal performance; any other input format will be converted\n(and copied).\n\nThe 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization\nwith primal formulation, or no regularization. The 'liblinear' solver\nsupports both L1 and L2 regularization, with a dual formulation only for\nthe L2 penalty. The Elastic-Net regularization is only supported by the\n'saga' solver.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.naive_bayes.BernoulliNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter\n(0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":"0.0","description":"Threshold for binarizing (mapping to booleans) of sample features.\nIf None, input is presumed to already consist of binary vectors.\n","name":"binarize","option":"optional"},{"default":true,"description":"Whether to learn class prior probabilities or not.\nIf false, a uniform prior will be used.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. If specified the priors are not\nadjusted according to the data.\n","name":"class_prior","option":"optional"}],"description":"Naive Bayes classifier for multivariate Bernoulli models.\n\nLike MultinomialNB, this classifier is suitable for discrete data. The\ndifference is that while MultinomialNB works with occurrence counts,\nBernoulliNB is designed for binary/boolean features.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.naive_bayes.ComplementNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":true,"description":"Only used in edge case with a single class in the training set.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. Not used.\n","name":"class_prior","option":"optional"},{"default":false,"description":"Whether or not a second normalization of the weights is performed. The\ndefault behavior mirrors the implementations found in Mahout and Weka,\nwhich do not follow the full algorithm described in Table 9 of the\npaper.\n","name":"norm","option":"optional","type":"boolean"}],"description":"The Complement Naive Bayes classifier described in Rennie et al. (2003).\n\nThe Complement Naive Bayes classifier was designed to correct the \"severe\nassumptions\" made by the standard Multinomial Naive Bayes classifier. It is\nparticularly suited for imbalanced data sets.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n"}},{"name":"sklearn.naive_bayes.MultinomialNB","schema":{"attributes":[{"default":1,"description":"Additive (Laplace/Lidstone) smoothing parameter\n(0 for no smoothing).\n","name":"alpha","option":"optional","type":"float32"},{"default":true,"description":"Whether to learn class prior probabilities or not.\nIf false, a uniform prior will be used.\n","name":"fit_prior","option":"optional","type":"boolean"},{"default":null,"description":"Prior probabilities of the classes. If specified the priors are not\nadjusted according to the data.\n","name":"class_prior","option":"optional"}],"description":"\nNaive Bayes classifier for multinomial models\n\nThe multinomial Naive Bayes classifier is suitable for classification with\ndiscrete features (e.g., word counts for text classification). The\nmultinomial distribution normally requires integer feature counts. However,\nin practice, fractional counts such as tf-idf may also work.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neighbors.KNeighborsClassifier","schema":{"attributes":[{"default":5,"description":"Number of neighbors to use by default for :meth:`kneighbors` queries.\n","name":"n_neighbors","option":"optional","type":"int32"},{"default":"uniform","description":"weight function used in prediction. Possible values:\n\n- 'uniform' : uniform weights. All points in each neighborhood\nare weighted equally.\n- 'distance' : weight points by the inverse of their distance.\nin this case, closer neighbors of a query point will have a\ngreater influence than neighbors which are further away.\n- [callable] : a user-defined function which accepts an\narray of distances, and returns an array of the same shape\ncontaining the weights.\n","name":"weights","option":"optional"},{"default":"auto","description":"Algorithm used to compute the nearest neighbors:\n\n- 'ball_tree' will use :class:`BallTree`\n- 'kd_tree' will use :class:`KDTree`\n- 'brute' will use a brute-force search.\n- 'auto' will attempt to decide the most appropriate algorithm\nbased on the values passed to :meth:`fit` method.\n\nNote: fitting on sparse input will override the setting of\nthis parameter, using brute force.\n","name":"algorithm","option":"optional"},{"default":30,"description":"Leaf size passed to BallTree or KDTree. This can affect the\nspeed of the construction and query, as well as the memory\nrequired to store the tree. The optimal value depends on the\nnature of the problem.\n","name":"leaf_size","option":"optional","type":"int32"},{"default":2,"description":"Power parameter for the Minkowski metric. When p = 1, this is\nequivalent to using manhattan_distance (l1), and euclidean_distance\n(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.\n","name":"p","option":"optional","type":"int32"},{"default":"minkowski","description":"the distance metric to use for the tree. The default metric is\nminkowski, and with p=2 is equivalent to the standard Euclidean\nmetric. See the documentation of :class:`DistanceMetric` for a\nlist of available metrics.\nIf metric is \"precomputed\", X is assumed to be a distance matrix and\nmust be square during fit. X may be a :term:`sparse graph`,\nin which case only \"nonzero\" elements may be considered neighbors.\n","name":"metric"},{"default":null,"description":"Additional keyword arguments for the metric function.\n","name":"metric_params","option":"optional"},{"default":null,"description":"The number of parallel jobs to run for neighbors search.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\nDoesn't affect :meth:`fit` method.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"Classifier implementing the k-nearest neighbors vote.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neighbors.KNeighborsRegressor","schema":{"attributes":[{"default":5,"description":"Number of neighbors to use by default for :meth:`kneighbors` queries.\n","name":"n_neighbors","option":"optional","type":"int32"},{"description":"weight function used in prediction. Possible values:\n\n- 'uniform' : uniform weights. All points in each neighborhood\nare weighted equally.\n- 'distance' : weight points by the inverse of their distance.\nin this case, closer neighbors of a query point will have a\ngreater influence than neighbors which are further away.\n- [callable] : a user-defined function which accepts an\narray of distances, and returns an array of the same shape\ncontaining the weights.\n\nUniform weights are used by default.\n","name":"weights"},{"default":"auto","description":"Algorithm used to compute the nearest neighbors:\n\n- 'ball_tree' will use :class:`BallTree`\n- 'kd_tree' will use :class:`KDTree`\n- 'brute' will use a brute-force search.\n- 'auto' will attempt to decide the most appropriate algorithm\nbased on the values passed to :meth:`fit` method.\n\nNote: fitting on sparse input will override the setting of\nthis parameter, using brute force.\n","name":"algorithm","option":"optional"},{"default":30,"description":"Leaf size passed to BallTree or KDTree. This can affect the\nspeed of the construction and query, as well as the memory\nrequired to store the tree. The optimal value depends on the\nnature of the problem.\n","name":"leaf_size","option":"optional","type":"int32"},{"default":2,"description":"Power parameter for the Minkowski metric. When p = 1, this is\nequivalent to using manhattan_distance (l1), and euclidean_distance\n(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.\n","name":"p","option":"optional","type":"int32"},{"default":"minkowski","description":"the distance metric to use for the tree. The default metric is\nminkowski, and with p=2 is equivalent to the standard Euclidean\nmetric. See the documentation of :class:`DistanceMetric` for a\nlist of available metrics.\nIf metric is \"precomputed\", X is assumed to be a distance matrix and\nmust be square during fit. X may be a :term:`sparse graph`,\nin which case only \"nonzero\" elements may be considered neighbors.\n","name":"metric"},{"default":null,"description":"Additional keyword arguments for the metric function.\n","name":"metric_params","option":"optional"},{"default":null,"description":"The number of parallel jobs to run for neighbors search.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\nDoesn't affect :meth:`fit` method.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"Regression based on k-nearest neighbors.\n\nThe target is predicted by local interpolation of the targets\nassociated of the nearest neighbors in the training set.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.9\n"}},{"name":"sklearn.linear_model.LassoLars","schema":{"attributes":[{"default":1,"description":"Constant that multiplies the penalty term. Defaults to 1.0.\n``alpha = 0`` is equivalent to an ordinary least square, solved\nby :class:`LinearRegression`. For numerical reasons, using\n``alpha = 0`` with the LassoLars object is not advised and you\nshould prefer the LinearRegression object.\n","name":"alpha","type":"float32"},{"default":true,"description":"whether to calculate the intercept for this model. If set\nto false, no intercept will be used in calculations\n(i.e. data is expected to be centered).\n","name":"fit_intercept","type":"boolean"},{"default":"False","description":"Sets the verbosity amount\n","name":"verbose","option":"optional"},{"default":true,"description":"This parameter is ignored when ``fit_intercept`` is set to False.\nIf True, the regressors X will be normalized before regression by\nsubtracting the mean and dividing by the l2-norm.\nIf you wish to standardize, please use\n:class:`sklearn.preprocessing.StandardScaler` before calling ``fit``\non an estimator with ``normalize=False``.\n","name":"normalize","option":"optional","type":"boolean"},{"default":"auto","description":"Whether to use a precomputed Gram matrix to speed up\ncalculations. If set to ``'auto'`` let us decide. The Gram\nmatrix can also be passed as argument.\n","name":"precompute","type":"boolean"},{"default":500,"description":"Maximum number of iterations to perform.\n","name":"max_iter","option":"optional","type":"int32"},{"description":"The machine-precision regularization in the computation of the\nCholesky diagonal factors. Increase this for very ill-conditioned\nsystems. Unlike the ``tol`` parameter in some iterative\noptimization-based algorithms, this parameter does not control\nthe tolerance of the optimization.\nBy default, ``np.finfo(np.float).eps`` is used.\n","name":"eps","option":"optional","type":"float32"},{"default":true,"description":"If True, X will be copied; else, it may be overwritten.\n","name":"copy_X","option":"optional","type":"boolean"},{"default":true,"description":"If ``True`` the full path is stored in the ``coef_path_`` attribute.\nIf you compute the solution for a large problem or many targets,\nsetting ``fit_path`` to ``False`` will lead to a speedup, especially\nwith a small alpha.\n","name":"fit_path","type":"boolean"},{"default":false,"description":"Restrict coefficients to be >= 0. Be aware that you might want to\nremove fit_intercept which is set True by default.\nUnder the positive restriction the model coefficients will not converge\nto the ordinary-least-squares solution for small values of alpha.\nOnly coefficients up to the smallest alpha value (``alphas_[alphas_ >\n0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso\nalgorithm are typically in congruence with the solution of the\ncoordinate descent Lasso estimator.\n","name":"positive","type":"boolean"},{"default":null,"description":"Upper bound on a uniform noise parameter to be added to the\n`y` values, to satisfy the model's assumption of\none-at-a-time computations. Might help with stability.\n","name":"jitter","type":"float32"},{"description":"Determines random number generation for jittering. Pass an int\nfor reproducible output across multiple function calls.\nSee :term:`Glossary `. Ignored if `jitter` is None.\n","name":"random_state"}],"description":"Lasso model fit with Least Angle Regression a.k.a. Lars\n\nIt is a Linear Model trained with an L1 prior as regularizer.\n\nThe optimization objective for Lasso is::\n\n(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition._pca.PCA","schema":{"attributes":[{"description":"Number of components to keep.\nif n_components is not set all components are kept::\n\nn_components == min(n_samples, n_features)\n\nIf ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's\nMLE is used to guess the dimension. Use of ``n_components == 'mle'``\nwill interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.\n\nIf ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the\nnumber of components such that the amount of variance that needs to be\nexplained is greater than the percentage specified by n_components.\n\nIf ``svd_solver == 'arpack'``, the number of components must be\nstrictly less than the minimum of n_features and n_samples.\n\nHence, the None case results in::\n\nn_components == min(n_samples, n_features) - 1\n","name":"n_components"},{"default":true,"description":"If False, data passed to fit are overwritten and running\nfit(X).transform(X) will not yield the expected results,\nuse fit_transform(X) instead.\n","name":"copy","type":"boolean"},{"default":false,"description":"When True (False by default) the `components_` vectors are multiplied\nby the square root of n_samples and then divided by the singular values\nto ensure uncorrelated outputs with unit component-wise variances.\n\nWhitening will remove some information from the transformed signal\n(the relative variance scales of the components) but can sometime\nimprove the predictive accuracy of the downstream estimators by\nmaking their data respect some hard-wired assumptions.\n","name":"whiten","option":"optional","type":"boolean"},{"description":"If auto :\nThe solver is selected by a default policy based on `X.shape` and\n`n_components`: if the input data is larger than 500x500 and the\nnumber of components to extract is lower than 80% of the smallest\ndimension of the data, then the more efficient 'randomized'\nmethod is enabled. Otherwise the exact full SVD is computed and\noptionally truncated afterwards.\nIf full :\nrun exact full SVD calling the standard LAPACK solver via\n`scipy.linalg.svd` and select the components by postprocessing\nIf arpack :\nrun SVD truncated to n_components calling ARPACK solver via\n`scipy.sparse.linalg.svds`. It requires strictly\n0 < n_components < min(X.shape)\nIf randomized :\nrun randomized SVD by the method of Halko et al.\n\n.. versionadded:: 0.18.0\n","name":"svd_solver"},{"default":".0","description":"Tolerance for singular values computed by svd_solver == 'arpack'.\n\n.. versionadded:: 0.18.0\n","name":"tol","option":"optional"},{"default":"auto","description":"Number of iterations for the power method computed by\nsvd_solver == 'randomized'.\n\n.. versionadded:: 0.18.0\n","name":"iterated_power"},{"default":null,"description":"Used when ``svd_solver`` == 'arpack' or 'randomized'. Pass an int\nfor reproducible results across multiple function calls.\nSee :term:`Glossary `.\n\n.. versionadded:: 0.18.0\n","name":"random_state","type":"int32"}],"description":"Principal component analysis (PCA).\n\nLinear dimensionality reduction using Singular Value Decomposition of the\ndata to project it to a lower dimensional space. The input data is centered\nbut not scaled for each feature before applying the SVD.\n\nIt uses the LAPACK implementation of the full SVD or a randomized truncated\nSVD by the method of Halko et al. 2009, depending on the shape of the input\ndata and the number of components to extract.\n\nIt can also use the scipy.sparse.linalg ARPACK implementation of the\ntruncated SVD.\n\nNotice that this class does not support sparse input. See\n:class:`TruncatedSVD` for an alternative with sparse data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition.PCA","schema":{"attributes":[{"description":"Number of components to keep.\nif n_components is not set all components are kept::\n\nn_components == min(n_samples, n_features)\n\nIf ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's\nMLE is used to guess the dimension. Use of ``n_components == 'mle'``\nwill interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.\n\nIf ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the\nnumber of components such that the amount of variance that needs to be\nexplained is greater than the percentage specified by n_components.\n\nIf ``svd_solver == 'arpack'``, the number of components must be\nstrictly less than the minimum of n_features and n_samples.\n\nHence, the None case results in::\n\nn_components == min(n_samples, n_features) - 1\n","name":"n_components"},{"default":true,"description":"If False, data passed to fit are overwritten and running\nfit(X).transform(X) will not yield the expected results,\nuse fit_transform(X) instead.\n","name":"copy","type":"boolean"},{"default":false,"description":"When True (False by default) the `components_` vectors are multiplied\nby the square root of n_samples and then divided by the singular values\nto ensure uncorrelated outputs with unit component-wise variances.\n\nWhitening will remove some information from the transformed signal\n(the relative variance scales of the components) but can sometime\nimprove the predictive accuracy of the downstream estimators by\nmaking their data respect some hard-wired assumptions.\n","name":"whiten","option":"optional","type":"boolean"},{"description":"If auto :\nThe solver is selected by a default policy based on `X.shape` and\n`n_components`: if the input data is larger than 500x500 and the\nnumber of components to extract is lower than 80% of the smallest\ndimension of the data, then the more efficient 'randomized'\nmethod is enabled. Otherwise the exact full SVD is computed and\noptionally truncated afterwards.\nIf full :\nrun exact full SVD calling the standard LAPACK solver via\n`scipy.linalg.svd` and select the components by postprocessing\nIf arpack :\nrun SVD truncated to n_components calling ARPACK solver via\n`scipy.sparse.linalg.svds`. It requires strictly\n0 < n_components < min(X.shape)\nIf randomized :\nrun randomized SVD by the method of Halko et al.\n\n.. versionadded:: 0.18.0\n","name":"svd_solver","type":"string"},{"default":".0","description":"Tolerance for singular values computed by svd_solver == 'arpack'.\n\n.. versionadded:: 0.18.0\n","name":"tol","option":"optional"},{"default":"auto","description":"Number of iterations for the power method computed by\nsvd_solver == 'randomized'.\n\n.. versionadded:: 0.18.0\n","name":"iterated_power"},{"default":null,"description":"Used when ``svd_solver`` == 'arpack' or 'randomized'. Pass an int\nfor reproducible results across multiple function calls.\nSee :term:`Glossary `.\n\n.. versionadded:: 0.18.0\n","name":"random_state","option":"optional","type":"int32"}],"description":"Principal component analysis (PCA).\n\nLinear dimensionality reduction using Singular Value Decomposition of the\ndata to project it to a lower dimensional space. The input data is centered\nbut not scaled for each feature before applying the SVD.\n\nIt uses the LAPACK implementation of the full SVD or a randomized truncated\nSVD by the method of Halko et al. 2009, depending on the shape of the input\ndata and the number of components to extract.\n\nIt can also use the scipy.sparse.linalg ARPACK implementation of the\ntruncated SVD.\n\nNotice that this class does not support sparse input. See\n:class:`TruncatedSVD` for an alternative with sparse data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.calibration.CalibratedClassifierCV","schema":{"attributes":[{"description":"The classifier whose output need to be calibrated to provide more\naccurate `predict_proba` outputs.\n","name":"base_estimator"},{"description":"The method to use for calibration. Can be 'sigmoid' which\ncorresponds to Platt's method (i.e. a logistic regression model) or\n'isotonic' which is a non-parametric approach. It is not advised to\nuse isotonic calibration with too few calibration samples\n``(<<1000)`` since it tends to overfit.\n","name":"method"},{"description":"Determines the cross-validation splitting strategy.\nPossible inputs for cv are:\n\n- None, to use the default 5-fold cross-validation,\n- integer, to specify the number of folds.\n- :term:`CV splitter`,\n- An iterable yielding (train, test) splits as arrays of indices.\n\nFor integer/None inputs, if ``y`` is binary or multiclass,\n:class:`sklearn.model_selection.StratifiedKFold` is used. If ``y`` is\nneither binary nor multiclass, :class:`sklearn.model_selection.KFold`\nis used.\n\nRefer :ref:`User Guide ` for the various\ncross-validation strategies that can be used here.\n\nIf \"prefit\" is passed, it is assumed that `base_estimator` has been\nfitted already and all data is used for calibration.\n\n.. versionchanged:: 0.22\n``cv`` default value if None changed from 3-fold to 5-fold.\n","name":"cv","option":"optional","type":"int32"}],"description":"Probability calibration with isotonic regression or logistic regression.\n\nThe calibration is based on the :term:`decision_function` method of the\n`base_estimator` if it exists, else on :term:`predict_proba`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.feature_extraction.text.CountVectorizer","schema":{"attributes":[{"default":"content","description":"If 'filename', the sequence passed as an argument to fit is\nexpected to be a list of filenames that need reading to fetch\nthe raw content to analyze.\n\nIf 'file', the sequence items must have a 'read' method (file-like\nobject) that is called to fetch the bytes in memory.\n\nOtherwise the input is expected to be a sequence of items that\ncan be of type string or byte.\n","name":"input","type":"string"},{"default":"utf-8","description":"If bytes or files are given to analyze, this encoding is used to\ndecode.\n","name":"encoding","type":"string"},{"default":"strict","description":"Instruction on what to do if a byte sequence is given to analyze that\ncontains characters not of the given `encoding`. By default, it is\n'strict', meaning that a UnicodeDecodeError will be raised. Other\nvalues are 'ignore' and 'replace'.\n","name":"decode_error"},{"default":null,"description":"Remove accents and perform other character normalization\nduring the preprocessing step.\n'ascii' is a fast method that only works on characters that have\nan direct ASCII mapping.\n'unicode' is a slightly slower method that works on any characters.\nNone (default) does nothing.\n\nBoth 'ascii' and 'unicode' use NFKD normalization from\n:func:`unicodedata.normalize`.\n","name":"strip_accents"},{"default":true,"description":"Convert all characters to lowercase before tokenizing.\n","name":"lowercase","type":"boolean"},{"default":null,"description":"Override the preprocessing (string transformation) stage while\npreserving the tokenizing and n-grams generation steps.\nOnly applies if ``analyzer is not callable``.\n","name":"preprocessor"},{"default":null,"description":"Override the string tokenization step while preserving the\npreprocessing and n-grams generation steps.\nOnly applies if ``analyzer == 'word'``.\n","name":"tokenizer"},{"default":"None","description":"If 'english', a built-in stop word list for English is used.\nThere are several known issues with 'english' and you should\nconsider an alternative (see :ref:`stop_words`).\n\nIf a list, that list is assumed to contain stop words, all of which\nwill be removed from the resulting tokens.\nOnly applies if ``analyzer == 'word'``.\n\nIf None, no stop words will be used. max_df can be set to a value\nin the range [0.7, 1.0) to automatically detect and filter stop\nwords based on intra corpus document frequency of terms.\n","name":"stop_words","type":"string"},{"description":"Regular expression denoting what constitutes a \"token\", only used\nif ``analyzer == 'word'``. The default regexp select tokens of 2\nor more alphanumeric characters (punctuation is completely ignored\nand always treated as a token separator).\n","name":"token_pattern","type":"string"},{"default":"(1, 1)","description":"The lower and upper boundary of the range of n-values for different\nword n-grams or char n-grams to be extracted. All values of n such\nsuch that min_n <= n <= max_n will be used. For example an\n``ngram_range`` of ``(1, 1)`` means only unigrams, ``(1, 2)`` means\nunigrams and bigrams, and ``(2, 2)`` means only bigrams.\nOnly applies if ``analyzer is not callable``.\n","name":"ngram_range"},{"default":"word","description":"Whether the feature should be made of word n-gram or character\nn-grams.\nOption 'char_wb' creates character n-grams only from text inside\nword boundaries; n-grams at the edges of words are padded with space.\n\nIf a callable is passed it is used to extract the sequence of features\nout of the raw, unprocessed input.\n\n.. versionchanged:: 0.21\n\nSince v0.21, if ``input`` is ``filename`` or ``file``, the data is\nfirst read from the file and then passed to the given callable\nanalyzer.\n","name":"analyzer","type":"string"},{"default":"1.0","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly higher than the given threshold (corpus-specific\nstop words).\nIf float, the parameter represents a proportion of documents, integer\nabsolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"max_df"},{"default":"1","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly lower than the given threshold. This value is also\ncalled cut-off in the literature.\nIf float, the parameter represents a proportion of documents, integer\nabsolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"min_df"},{"default":null,"description":"If not None, build a vocabulary that only consider the top\nmax_features ordered by term frequency across the corpus.\n\nThis parameter is ignored if vocabulary is not None.\n","name":"max_features","type":"int32"},{"default":null,"description":"Either a Mapping (e.g., a dict) where keys are terms and values are\nindices in the feature matrix, or an iterable over terms. If not\ngiven, a vocabulary is determined from the input documents. Indices\nin the mapping should not be repeated and should not have any gap\nbetween 0 and the largest index.\n","name":"vocabulary","option":"optional"},{"default":false,"description":"If True, all non zero counts are set to 1. This is useful for discrete\nprobabilistic models that model binary events rather than integer\ncounts.\n","name":"binary","type":"boolean"},{"default":"np.int64","description":"Type of the matrix returned by fit_transform() or transform().\n","name":"dtype","option":"optional"}],"description":"Convert a collection of text documents to a matrix of token counts\n\nThis implementation produces a sparse representation of the counts using\nscipy.sparse.csr_matrix.\n\nIf you do not provide an a-priori dictionary and you do not use an analyzer\nthat does some kind of feature selection then the number of features will\nbe equal to the vocabulary size found by analyzing the data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.feature_extraction.text.TfidfVectorizer","schema":{"attributes":[{"default":"content","description":"If 'filename', the sequence passed as an argument to fit is\nexpected to be a list of filenames that need reading to fetch\nthe raw content to analyze.\n\nIf 'file', the sequence items must have a 'read' method (file-like\nobject) that is called to fetch the bytes in memory.\n\nOtherwise the input is expected to be a sequence of items that\ncan be of type string or byte.\n","name":"input","type":"string"},{"default":"utf-8","description":"If bytes or files are given to analyze, this encoding is used to\ndecode.\n","name":"encoding","type":"string"},{"default":"strict","description":"Instruction on what to do if a byte sequence is given to analyze that\ncontains characters not of the given `encoding`. By default, it is\n'strict', meaning that a UnicodeDecodeError will be raised. Other\nvalues are 'ignore' and 'replace'.\n","name":"decode_error"},{"default":null,"description":"Remove accents and perform other character normalization\nduring the preprocessing step.\n'ascii' is a fast method that only works on characters that have\nan direct ASCII mapping.\n'unicode' is a slightly slower method that works on any characters.\nNone (default) does nothing.\n\nBoth 'ascii' and 'unicode' use NFKD normalization from\n:func:`unicodedata.normalize`.\n","name":"strip_accents"},{"default":true,"description":"Convert all characters to lowercase before tokenizing.\n","name":"lowercase","type":"boolean"},{"default":null,"description":"Override the preprocessing (string transformation) stage while\npreserving the tokenizing and n-grams generation steps.\nOnly applies if ``analyzer is not callable``.\n","name":"preprocessor"},{"default":null,"description":"Override the string tokenization step while preserving the\npreprocessing and n-grams generation steps.\nOnly applies if ``analyzer == 'word'``.\n","name":"tokenizer"},{"description":"Whether the feature should be made of word or character n-grams.\nOption 'char_wb' creates character n-grams only from text inside\nword boundaries; n-grams at the edges of words are padded with space.\n\nIf a callable is passed it is used to extract the sequence of features\nout of the raw, unprocessed input.\n\n.. versionchanged:: 0.21\n\nSince v0.21, if ``input`` is ``filename`` or ``file``, the data is\nfirst read from the file and then passed to the given callable\nanalyzer.\n","name":"analyzer"},{"default":null,"description":"If a string, it is passed to _check_stop_list and the appropriate stop\nlist is returned. 'english' is currently the only supported string\nvalue.\nThere are several known issues with 'english' and you should\nconsider an alternative (see :ref:`stop_words`).\n\nIf a list, that list is assumed to contain stop words, all of which\nwill be removed from the resulting tokens.\nOnly applies if ``analyzer == 'word'``.\n\nIf None, no stop words will be used. max_df can be set to a value\nin the range [0.7, 1.0) to automatically detect and filter stop\nwords based on intra corpus document frequency of terms.\n","name":"stop_words"},{"description":"Regular expression denoting what constitutes a \"token\", only used\nif ``analyzer == 'word'``. The default regexp selects tokens of 2\nor more alphanumeric characters (punctuation is completely ignored\nand always treated as a token separator).\n","name":"token_pattern","type":"string"},{"default":"(1, 1)","description":"The lower and upper boundary of the range of n-values for different\nn-grams to be extracted. All values of n such that min_n <= n <= max_n\nwill be used. For example an ``ngram_range`` of ``(1, 1)`` means only\nunigrams, ``(1, 2)`` means unigrams and bigrams, and ``(2, 2)`` means\nonly bigrams.\nOnly applies if ``analyzer is not callable``.\n","name":"ngram_range"},{"default":"1.0","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly higher than the given threshold (corpus-specific\nstop words).\nIf float in range [0.0, 1.0], the parameter represents a proportion of\ndocuments, integer absolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"max_df"},{"default":"1","description":"When building the vocabulary ignore terms that have a document\nfrequency strictly lower than the given threshold. This value is also\ncalled cut-off in the literature.\nIf float in range of [0.0, 1.0], the parameter represents a proportion\nof documents, integer absolute counts.\nThis parameter is ignored if vocabulary is not None.\n","name":"min_df"},{"default":null,"description":"If not None, build a vocabulary that only consider the top\nmax_features ordered by term frequency across the corpus.\n\nThis parameter is ignored if vocabulary is not None.\n","name":"max_features","type":"int32"},{"default":null,"description":"Either a Mapping (e.g., a dict) where keys are terms and values are\nindices in the feature matrix, or an iterable over terms. If not\ngiven, a vocabulary is determined from the input documents.\n","name":"vocabulary","option":"optional"},{"default":false,"description":"If True, all non-zero term counts are set to 1. This does not mean\noutputs will have only 0/1 values, only that the tf term in tf-idf\nis binary. (Set idf and normalization to False to get 0/1 outputs).\n","name":"binary","type":"boolean"},{"default":"float64","description":"Type of the matrix returned by fit_transform() or transform().\n","name":"dtype","option":"optional"},{"default":"l2","description":"Each output row will have unit norm, either:\n* 'l2': Sum of squares of vector elements is 1. The cosine\nsimilarity between two vectors is their dot product when l2 norm has\nbeen applied.\n* 'l1': Sum of absolute values of vector elements is 1.\nSee :func:`preprocessing.normalize`.\n","name":"norm"},{"default":true,"description":"Enable inverse-document-frequency reweighting.\n","name":"use_idf","type":"boolean"},{"default":true,"description":"Smooth idf weights by adding one to document frequencies, as if an\nextra document was seen containing every term in the collection\nexactly once. Prevents zero divisions.\n","name":"smooth_idf","type":"boolean"},{"default":false,"description":"Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).\n","name":"sublinear_tf","type":"boolean"}],"description":"Convert a collection of raw documents to a matrix of TF-IDF features.\n\nEquivalent to :class:`CountVectorizer` followed by\n:class:`TfidfTransformer`.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"lightgbm.sklearn.LGBMRegressor","schema":{"attributes":[{"default":"gbdt","name":"boosting_type","type":"string"},{"default":null,"name":"class_weight"},{"default":1,"name":"colsample_bytree"},{"default":0.05,"name":"learning_rate"},{"default":-1,"name":"max_depth"},{"default":20,"name":"min_child_samples"},{"default":0.001,"name":"min_child_weight"},{"default":0,"name":"min_split_gain"},{"default":100,"name":"n_estimators"},{"default":-1,"name":"n_jobs"},{"default":31,"name":"num_leaves"},{"default":null,"name":"random_state"},{"default":0,"name":"reg_alpha"},{"default":0,"name":"reg_lambda"},{"default":true,"name":"silent","type":"boolean"},{"default":200000,"name":"subsample_for_bin"},{"default":0,"name":"subsample_freq"},{"default":1,"name":"subsample"}]}},{"name":"lightgbm.sklearn.LGBMClassifier","schema":{"attributes":[{"default":"gbdt","name":"boosting_type","type":"string"},{"default":null,"name":"class_weight"},{"default":1,"name":"colsample_bytree"},{"default":0.05,"name":"learning_rate"},{"default":-1,"name":"max_depth"},{"default":20,"name":"min_child_samples"},{"default":0.001,"name":"min_child_weight"},{"default":0,"name":"min_split_gain"},{"default":100,"name":"n_estimators"},{"default":-1,"name":"n_jobs"},{"default":31,"name":"num_leaves"},{"default":null,"name":"random_state"},{"default":0,"name":"reg_alpha"},{"default":0,"name":"reg_lambda"},{"default":true,"name":"silent","type":"boolean"},{"default":200000,"name":"subsample_for_bin"},{"default":0,"name":"subsample_freq"},{"default":1,"name":"subsample"}]}},{"name":"lightgbm.basic.Booster","schema":{"attributes":[{"default":-1,"name":"best_iteration"},{"default":false,"name":"network"},{"default":null,"name":"train_set"},{"default":false,"name":"stride"},{"default":null,"name":"model_file"},{"default":null,"name":"params"},{"default":null,"name":"pandas_categorical"}]}},{"name":"sklearn.linear_model.LinearRegression","schema":{"attributes":[{"default":true,"description":"Whether to calculate the intercept for this model. If set\nto False, no intercept will be used in calculations\n(i.e. data is expected to be centered).\n","name":"fit_intercept","option":"optional","type":"boolean"},{"default":false,"description":"This parameter is ignored when ``fit_intercept`` is set to False.\nIf True, the regressors X will be normalized before regression by\nsubtracting the mean and dividing by the l2-norm.\nIf you wish to standardize, please use\n:class:`sklearn.preprocessing.StandardScaler` before calling ``fit`` on\nan estimator with ``normalize=False``.\n","name":"normalize","option":"optional","type":"boolean"},{"default":true,"description":"If True, X will be copied; else, it may be overwritten.\n","name":"copy_X","option":"optional","type":"boolean"},{"default":null,"description":"The number of jobs to use for the computation. This will only provide\nspeedup for n_targets > 1 and sufficient large problems.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n","name":"n_jobs","option":"optional","type":"int32"}],"description":"\nOrdinary least squares Linear Regression.\n\nLinearRegression fits a linear model with coefficients w = (w1, ..., wp)\nto minimize the residual sum of squares between the observed targets in\nthe dataset, and the targets predicted by the linear approximation.\n"}},{"name":"sklearn.pipeline.FeatureUnion","schema":{"attributes":[{"description":"List of transformer objects to be applied to the data. The first\nhalf of each tuple is the name of the transformer.\n\n.. versionchanged:: 0.22\nDeprecated `None` as a transformer in favor of 'drop'.\n","name":"transformer_list"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n\n.. versionchanged:: v0.20\n`n_jobs` default changed from 1 to None\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Multiplicative weights for features per transformer.\nKeys are transformer names, values the weights.\n","name":"transformer_weights"},{"default":false,"description":"If True, the time elapsed while fitting each transformer will be\nprinted as it is completed.\n","name":"verbose","type":"boolean"}],"description":"Concatenates results of multiple transformer objects.\n\nThis estimator applies a list of transformer objects in parallel to the\ninput data, then concatenates the results. This is useful to combine\nseveral feature extraction mechanisms into a single transformer.\n\nParameters of the transformers may be set using its name and the parameter\nname separated by a '__'. A transformer may be replaced entirely by\nsetting the parameter with its name to another transformer,\nor removed by setting to 'drop'.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.13\n"}},{"name":"sklearn.compose._column_transformer.ColumnTransformer","schema":{"attributes":[{"description":"List of (name, transformer, columns) tuples specifying the\ntransformer objects to be applied to subsets of the data.\n\nname : str\nLike in Pipeline and FeatureUnion, this allows the transformer and\nits parameters to be set using ``set_params`` and searched in grid\nsearch.\ntransformer : {'drop', 'passthrough'} or estimator\nEstimator must support :term:`fit` and :term:`transform`.\nSpecial-cased strings 'drop' and 'passthrough' are accepted as\nwell, to indicate to drop the columns or to pass them through\nuntransformed, respectively.\ncolumns : str, array-like of str, int, array-like of int, array-like of bool, slice or callable\nIndexes the data on its second axis. Integers are interpreted as\npositional columns, while strings can reference DataFrame columns\nby name. A scalar string or int should be used where\n``transformer`` expects X to be a 1d array-like (vector),\notherwise a 2d array will be passed to the transformer.\nA callable is passed the input data `X` and can return any of the\nabove. To select multiple columns by name or dtype, you can use\n:obj:`make_column_selector`.\n","name":"transformers"},{"description":"By default, only the specified columns in `transformers` are\ntransformed and combined in the output, and the non-specified\ncolumns are dropped. (default of ``'drop'``).\nBy specifying ``remainder='passthrough'``, all remaining columns that\nwere not specified in `transformers` will be automatically passed\nthrough. This subset of columns is concatenated with the output of\nthe transformers.\nBy setting ``remainder`` to be an estimator, the remaining\nnon-specified columns will use the ``remainder`` estimator. The\nestimator must support :term:`fit` and :term:`transform`.\nNote that using this feature requires that the DataFrame columns\ninput at :term:`fit` and :term:`transform` have identical order.\n","name":"remainder"},{"default":0.3,"description":"If the output of the different transformers contains sparse matrices,\nthese will be stacked as a sparse matrix if the overall density is\nlower than this value. Use ``sparse_threshold=0`` to always return\ndense. When the transformed output consists of all dense data, the\nstacked result will be dense, and this keyword will be ignored.\n","name":"sparse_threshold","type":"float32"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Multiplicative weights for features per transformer. The output of the\ntransformer is multiplied by these weights. Keys are transformer names,\nvalues the weights.\n","name":"transformer_weights"},{"default":false,"description":"If True, the time elapsed while fitting each transformer will be\nprinted as it is completed.\n","name":"verbose","type":"boolean"}],"description":"Applies transformers to columns of an array or pandas DataFrame.\n\nThis estimator allows different columns or column subsets of the input\nto be transformed separately and the features generated by each transformer\nwill be concatenated to form a single feature space.\nThis is useful for heterogeneous or columnar data, to combine several\nfeature extraction mechanisms or transformations into a single transformer.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n"}},{"name":"sklearn.preprocessing._encoders.OneHotEncoder","schema":{"attributes":[{"description":"Categories (unique values) per feature:\n\n- 'auto' : Determine categories automatically from the training data.\n- list : ``categories[i]`` holds the categories expected in the ith\ncolumn. The passed categories should not mix strings and numeric\nvalues within a single feature, and should be sorted in case of\nnumeric values.\n\nThe used categories can be found in the ``categories_`` attribute.\n\n.. versionadded:: 0.20\n","name":"categories"},{"description":"Specifies a methodology to use to drop one of the categories per\nfeature. This is useful in situations where perfectly collinear\nfeatures cause problems, such as when feeding the resulting data\ninto a neural network or an unregularized regression.\n\nHowever, dropping one category breaks the symmetry of the original\nrepresentation and can therefore induce a bias in downstream models,\nfor instance for penalized linear classification or regression models.\n\n- None : retain all features (the default).\n- 'first' : drop the first category in each feature. If only one\ncategory is present, the feature will be dropped entirely.\n- 'if_binary' : drop the first category in each feature with two\ncategories. Features with 1 or more than 2 categories are\nleft intact.\n- array : ``drop[i]`` is the category in feature ``X[:, i]`` that\nshould be dropped.\n","name":"drop"},{"default":true,"description":"Will return sparse matrix if set True else will return an array.\n","name":"sparse","type":"boolean"},{"default":"np.float","description":"Desired dtype of output.\n","name":"dtype"},{"default":"error","description":"Whether to raise an error or ignore if an unknown categorical feature\nis present during transform (default is to raise). When this parameter\nis set to 'ignore' and an unknown category is encountered during\ntransform, the resulting one-hot encoded columns for this feature\nwill be all zeros. In the inverse transform, an unknown category\nwill be denoted as None.\n","name":"handle_unknown"}],"description":"\nEncode categorical features as a one-hot numeric array.\n\nThe input to this transformer should be an array-like of integers or\nstrings, denoting the values taken on by categorical (discrete) features.\nThe features are encoded using a one-hot (aka 'one-of-K' or 'dummy')\nencoding scheme. This creates a binary column for each category and\nreturns a sparse matrix or dense array (depending on the ``sparse``\nparameter)\n\nBy default, the encoder derives the categories based on the unique values\nin each feature. Alternatively, you can also specify the `categories`\nmanually.\n\nThis encoding is needed for feeding categorical data to many scikit-learn\nestimators, notably linear models and SVMs with the standard kernels.\n\nNote: a one-hot encoding of y labels should use a LabelBinarizer\ninstead.\n\nRead more in the :ref:`User Guide `.\n\n.. versionchanged:: 0.20\n"}},{"name":"sklearn.feature_selection._univariate_selection.SelectKBest","schema":{"attributes":[{"description":"Function taking two arrays X and y, and returning a pair of arrays\n(scores, pvalues) or a single array with scores.\nDefault is f_classif (see below \"See also\"). The default function only\nworks with classification tasks.\n\n.. versionadded:: 0.18\n","name":"score_func"},{"default":"10","description":"Number of top features to select.\nThe \"all\" option bypasses selection, for use in a parameter search.\n","name":"k","option":"optional"}],"description":"Select features according to the k highest scores.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.impute._base.SimpleImputer","schema":{"attributes":[{"description":"The placeholder for the missing values. All occurrences of\n`missing_values` will be imputed. For pandas' dataframes with\nnullable integer dtypes with missing values, `missing_values`\nshould be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.\n","name":"missing_values"},{"default":"mean","description":"The imputation strategy.\n\n- If \"mean\", then replace missing values using the mean along\neach column. Can only be used with numeric data.\n- If \"median\", then replace missing values using the median along\neach column. Can only be used with numeric data.\n- If \"most_frequent\", then replace missing using the most frequent\nvalue along each column. Can be used with strings or numeric data.\n- If \"constant\", then replace missing values with fill_value. Can be\nused with strings or numeric data.\n\n.. versionadded:: 0.20\nstrategy=\"constant\" for fixed value imputation.\n","name":"strategy","type":"string"},{"default":null,"description":"When strategy == \"constant\", fill_value is used to replace all\noccurrences of missing_values.\nIf left to the default, fill_value will be 0 when imputing numerical\ndata and \"missing_value\" for strings or object data types.\n","name":"fill_value"},{"default":0,"description":"Controls the verbosity of the imputer.\n","name":"verbose","type":"int32"},{"default":true,"description":"If True, a copy of X will be created. If False, imputation will\nbe done in-place whenever possible. Note that, in the following cases,\na new copy will always be made, even if `copy=False`:\n\n- If X is not an array of floating values;\n- If X is encoded as a CSR matrix;\n- If add_indicator=True.\n","name":"copy","type":"boolean"},{"default":false,"description":"If True, a :class:`MissingIndicator` transform will stack onto output\nof the imputer's transform. This allows a predictive estimator\nto account for missingness despite imputation. If a feature has no\nmissing values at fit/train time, the feature won't appear on\nthe missing indicator even if there are missing values at\ntransform/test time.\n","name":"add_indicator","type":"boolean"}],"description":"Imputation transformer for completing missing values.\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.20\n`SimpleImputer` replaces the previous `sklearn.preprocessing.Imputer`\nestimator which is now removed.\n"}},{"name":"sklearn.model_selection._search.GridSearchCV","schema":{"attributes":[{"description":"This is assumed to implement the scikit-learn estimator interface.\nEither estimator needs to provide a ``score`` function,\nor ``scoring`` must be passed.\n","name":"estimator"},{"description":"Dictionary with parameters names (`str`) as keys and lists of\nparameter settings to try as values, or a list of such\ndictionaries, in which case the grids spanned by each dictionary\nin the list are explored. This enables searching over any sequence\nof parameter settings.\n","name":"param_grid"},{"default":null,"description":"A single str (see :ref:`scoring_parameter`) or a callable\n(see :ref:`scoring`) to evaluate the predictions on the test set.\n\nFor evaluating multiple metrics, either give a list of (unique) strings\nor a dict with names as keys and callables as values.\n\nNOTE that when using custom scorers, each scorer should return a single\nvalue. Metric functions returning a list/array of values can be wrapped\ninto multiple scorers that return one value each.\n\nSee :ref:`multimetric_grid_search` for an example.\n\nIf None, the estimator's score method is used.\n","name":"scoring"},{"default":null,"description":"Number of jobs to run in parallel.\n``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n``-1`` means using all processors. See :term:`Glossary `\nfor more details.\n\n.. versionchanged:: v0.20\n`n_jobs` default changed from 1 to None\n","name":"n_jobs","type":"int32"},{"description":"Controls the number of jobs that get dispatched during parallel\nexecution. Reducing this number can be useful to avoid an\nexplosion of memory consumption when more jobs get dispatched\nthan CPUs can process. This parameter can be:\n\n- None, in which case all the jobs are immediately\ncreated and spawned. Use this for lightweight and\nfast-running jobs, to avoid delays due to on-demand\nspawning of the jobs\n\n- An int, giving the exact number of total jobs that are\nspawned\n\n- A str, giving an expression as a function of n_jobs,\nas in '2*n_jobs'\n","name":"pre_dispatch"},{"default":false,"description":"If True, return the average score across folds, weighted by the number\nof samples in each test set. In this case, the data is assumed to be\nidentically distributed across the folds, and the loss minimized is\nthe total loss per sample, and not the mean loss across the folds.\n\n.. deprecated:: 0.22\nParameter ``iid`` is deprecated in 0.22 and will be removed in 0.24\n","name":"iid","type":"boolean"},{"default":null,"description":"Determines the cross-validation splitting strategy.\nPossible inputs for cv are:\n\n- None, to use the default 5-fold cross validation,\n- integer, to specify the number of folds in a `(Stratified)KFold`,\n- :term:`CV splitter`,\n- An iterable yielding (train, test) splits as arrays of indices.\n\nFor integer/None inputs, if the estimator is a classifier and ``y`` is\neither binary or multiclass, :class:`StratifiedKFold` is used. In all\nother cases, :class:`KFold` is used.\n\nRefer :ref:`User Guide ` for the various\ncross-validation strategies that can be used here.\n\n.. versionchanged:: 0.22\n``cv`` default value if None changed from 3-fold to 5-fold.\n","name":"cv","type":"int32"},{"default":true,"description":"Refit an estimator using the best found parameters on the whole\ndataset.\n\nFor multiple metric evaluation, this needs to be a `str` denoting the\nscorer that would be used to find the best parameters for refitting\nthe estimator at the end.\n\nWhere there are considerations other than maximum score in\nchoosing a best estimator, ``refit`` can be set to a function which\nreturns the selected ``best_index_`` given ``cv_results_``. In that\ncase, the ``best_estimator_`` and ``best_params_`` will be set\naccording to the returned ``best_index_`` while the ``best_score_``\nattribute will not be available.\n\nThe refitted estimator is made available at the ``best_estimator_``\nattribute and permits using ``predict`` directly on this\n``GridSearchCV`` instance.\n\nAlso for multiple metric evaluation, the attributes ``best_index_``,\n``best_score_`` and ``best_params_`` will only be available if\n``refit`` is set and all of them will be determined w.r.t this specific\nscorer.\n\nSee ``scoring`` parameter to know more about multiple metric\nevaluation.\n\n.. versionchanged:: 0.20\nSupport for callable added.\n","name":"refit","type":"boolean"},{"description":"Controls the verbosity: the higher, the more messages.\n","name":"verbose","type":"int32"},{"description":"Value to assign to the score if an error occurs in estimator fitting.\nIf set to 'raise', the error is raised. If a numeric value is given,\nFitFailedWarning is raised. This parameter does not affect the refit\nstep, which will always raise the error.\n","name":"error_score"},{"default":false,"description":"If ``False``, the ``cv_results_`` attribute will not include training\nscores.\nComputing training scores is used to get insights on how different\nparameter settings impact the overfitting/underfitting trade-off.\nHowever computing the scores on the training set can be computationally\nexpensive and is not strictly required to select the parameters that\nyield the best generalization performance.\n\n.. versionadded:: 0.19\n\n.. versionchanged:: 0.21\nDefault value was changed from ``True`` to ``False``\n\n","name":"return_train_score","type":"boolean"}],"description":"Exhaustive search over specified parameter values for an estimator.\n\nImportant members are fit, predict.\n\nGridSearchCV implements a \"fit\" and a \"score\" method.\nIt also implements \"predict\", \"predict_proba\", \"decision_function\",\n\"transform\" and \"inverse_transform\" if they are implemented in the\nestimator used.\n\nThe parameters of the estimator used to apply these methods are optimized\nby cross-validated grid-search over a parameter grid.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.decomposition._truncated_svd.TruncatedSVD","schema":{"attributes":[{"default":2,"description":"Desired dimensionality of output data.\nMust be strictly less than the number of features.\nThe default value is useful for visualisation. For LSA, a value of\n100 is recommended.\n","name":"n_components","type":"int32"},{"default":"randomized","description":"SVD solver to use. Either \"arpack\" for the ARPACK wrapper in SciPy\n(scipy.sparse.linalg.svds), or \"randomized\" for the randomized\nalgorithm due to Halko (2009).\n","name":"algorithm","type":"string"},{"default":5,"description":"Number of iterations for randomized SVD solver. Not used by ARPACK. The\ndefault is larger than the default in\n:func:`~sklearn.utils.extmath.randomized_svd` to handle sparse\nmatrices that may have large slowly decaying spectrum.\n","name":"n_iter","option":"optional","type":"int32"},{"default":null,"description":"Used during randomized svd. Pass an int for reproducible results across\nmultiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","type":"int32"},{"description":"Tolerance for ARPACK. 0 means machine precision. Ignored by randomized\nSVD solver.\n","name":"tol","option":"optional","type":"float32"}],"description":"Dimensionality reduction using truncated SVD (aka LSA).\n\nThis transformer performs linear dimensionality reduction by means of\ntruncated singular value decomposition (SVD). Contrary to PCA, this\nestimator does not center the data before computing the singular value\ndecomposition. This means it can work with sparse matrices\nefficiently.\n\nIn particular, truncated SVD works on term count/tf-idf matrices as\nreturned by the vectorizers in :mod:`sklearn.feature_extraction.text`. In\nthat context, it is known as latent semantic analysis (LSA).\n\nThis estimator supports two algorithms: a fast randomized SVD solver, and\na \"naive\" algorithm that uses ARPACK as an eigensolver on `X * X.T` or\n`X.T * X`, whichever is more efficient.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.ensemble.forest.RandomForestClassifier","schema":{"attributes":[{"default":100,"description":"The number of trees in the forest.\n\n.. versionchanged:: 0.22\nThe default value of ``n_estimators`` changed from 10 to 100\nin 0.22.\n","name":"n_estimators","type":"int32"},{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\nNote: this parameter is tree-specific.\n","name":"criterion"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":"\"auto\"","description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)` (same as \"auto\").\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features"},{"default":null,"description":"Grow trees with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":null,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n\n","name":"min_impurity_split","type":"float32"},{"default":true,"description":"Whether bootstrap samples are used when building trees. If False, the\nwhole dataset is used to build each tree.\n","name":"bootstrap","type":"boolean"},{"default":false,"description":"Whether to use out-of-bag samples to estimate\nthe generalization accuracy.\n","name":"oob_score","type":"boolean"},{"default":null,"description":"The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,\n:meth:`decision_path` and :meth:`apply` are all parallelized over the\ntrees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors. See :term:`Glossary\n` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Controls both the randomness of the bootstrapping of the samples used\nwhen building trees (if ``bootstrap=True``) and the sampling of the\nfeatures to consider when looking for the best split at each node\n(if ``max_features < n_features``).\nSee :term:`Glossary ` for details.\n","name":"random_state"},{"default":0,"description":"Controls the verbosity when fitting and predicting.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to ``True``, reuse the solution of the previous call to fit\nand add more estimators to the ensemble, otherwise, just fit a whole\nnew forest. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nThe \"balanced_subsample\" mode is the same as \"balanced\" except that\nweights are computed based on the bootstrap sample for every tree\ngrown.\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"},{"default":null,"description":"If bootstrap is True, the number of samples to draw from X\nto train each base estimator.\n\n- If None (default), then draw `X.shape[0]` samples.\n- If int, then draw `max_samples` samples.\n- If float, then draw `max_samples * X.shape[0]` samples. Thus,\n`max_samples` should be in the interval `(0, 1)`.\n\n.. versionadded:: 0.22\n","name":"max_samples"}],"description":"\nA random forest classifier.\n\nA random forest is a meta estimator that fits a number of decision tree\nclassifiers on various sub-samples of the dataset and uses averaging to\nimprove the predictive accuracy and control over-fitting.\nThe sub-sample size is controlled with the `max_samples` parameter if\n`bootstrap=True` (default), otherwise the whole dataset is used to build\neach tree.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.ensemble.weight_boosting.AdaBoostClassifier","schema":{"attributes":[{"default":null,"description":"The base estimator from which the boosted ensemble is built.\nSupport for sample weighting is required, as well as proper\n``classes_`` and ``n_classes_`` attributes. If ``None``, then\nthe base estimator is ``DecisionTreeClassifier(max_depth=1)``.\n","name":"base_estimator"},{"default":50,"description":"The maximum number of estimators at which boosting is terminated.\nIn case of perfect fit, the learning procedure is stopped early.\n","name":"n_estimators","type":"int32"},{"default":1,"description":"Learning rate shrinks the contribution of each classifier by\n``learning_rate``. There is a trade-off between ``learning_rate`` and\n``n_estimators``.\n","name":"learning_rate","type":"float32"},{"default":"SAMME.R","description":"If 'SAMME.R' then use the SAMME.R real boosting algorithm.\n``base_estimator`` must support calculation of class probabilities.\nIf 'SAMME' then use the SAMME discrete boosting algorithm.\nThe SAMME.R algorithm typically converges faster than SAMME,\nachieving a lower test error with fewer boosting iterations.\n","name":"algorithm"},{"default":null,"description":"Controls the random seed given at each `base_estimator` at each\nboosting iteration.\nThus, it is only used when `base_estimator` exposes a `random_state`.\nPass an int for reproducible output across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state"}],"description":"An AdaBoost classifier.\n\nAn AdaBoost [1] classifier is a meta-estimator that begins by fitting a\nclassifier on the original dataset and then fits additional copies of the\nclassifier on the same dataset but where the weights of incorrectly\nclassified instances are adjusted such that subsequent classifiers focus\nmore on difficult cases.\n\nThis class implements the algorithm known as AdaBoost-SAMME [2].\n\nRead more in the :ref:`User Guide `.\n\n.. versionadded:: 0.14\n"}},{"name":"sklearn.ensemble.forest.ExtraTreesClassifier","schema":{"attributes":[{"default":100,"description":"The number of trees in the forest.\n\n.. versionchanged:: 0.22\nThe default value of ``n_estimators`` changed from 10 to 100\nin 0.22.\n","name":"n_estimators","type":"int32"},{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\n","name":"criterion"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":"\"auto\"","description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)`.\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features"},{"default":null,"description":"Grow trees with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":null,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n","name":"min_impurity_split","type":"float32"},{"default":false,"description":"Whether bootstrap samples are used when building trees. If False, the\nwhole dataset is used to build each tree.\n","name":"bootstrap","type":"boolean"},{"default":false,"description":"Whether to use out-of-bag samples to estimate\nthe generalization accuracy.\n","name":"oob_score","type":"boolean"},{"default":null,"description":"The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,\n:meth:`decision_path` and :meth:`apply` are all parallelized over the\ntrees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\ncontext. ``-1`` means using all processors. See :term:`Glossary\n` for more details.\n","name":"n_jobs","type":"int32"},{"default":null,"description":"Controls 3 sources of randomness:\n\n- the bootstrapping of the samples used when building trees\n(if ``bootstrap=True``)\n- the sampling of the features to consider when looking for the best\nsplit at each node (if ``max_features < n_features``)\n- the draw of the splits for each of the `max_features`\n\nSee :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":0,"description":"Controls the verbosity when fitting and predicting.\n","name":"verbose","type":"int32"},{"default":false,"description":"When set to ``True``, reuse the solution of the previous call to fit\nand add more estimators to the ensemble, otherwise, just fit a whole\nnew forest. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf not given, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nThe \"balanced_subsample\" mode is the same as \"balanced\" except that\nweights are computed based on the bootstrap sample for every tree\ngrown.\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"},{"default":null,"description":"If bootstrap is True, the number of samples to draw from X\nto train each base estimator.\n\n- If None (default), then draw `X.shape[0]` samples.\n- If int, then draw `max_samples` samples.\n- If float, then draw `max_samples * X.shape[0]` samples. Thus,\n`max_samples` should be in the interval `(0, 1)`.\n\n.. versionadded:: 0.22\n","name":"max_samples"}],"description":"\nAn extra-trees classifier.\n\nThis class implements a meta estimator that fits a number of\nrandomized decision trees (a.k.a. extra-trees) on various sub-samples\nof the dataset and uses averaging to improve the predictive accuracy\nand control over-fitting.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.neural_network.multilayer_perceptron.MLPRegressor","schema":{"attributes":[{"default":"(100,)","description":"The ith element represents the number of neurons in the ith\nhidden layer.\n","name":"hidden_layer_sizes"},{"default":"relu","description":"Activation function for the hidden layer.\n\n- 'identity', no-op activation, useful to implement linear bottleneck,\nreturns f(x) = x\n\n- 'logistic', the logistic sigmoid function,\nreturns f(x) = 1 / (1 + exp(-x)).\n\n- 'tanh', the hyperbolic tan function,\nreturns f(x) = tanh(x).\n\n- 'relu', the rectified linear unit function,\nreturns f(x) = max(0, x)\n","name":"activation"},{"default":"adam","description":"The solver for weight optimization.\n\n- 'lbfgs' is an optimizer in the family of quasi-Newton methods.\n\n- 'sgd' refers to stochastic gradient descent.\n\n- 'adam' refers to a stochastic gradient-based optimizer proposed by\nKingma, Diederik, and Jimmy Ba\n\nNote: The default solver 'adam' works pretty well on relatively\nlarge datasets (with thousands of training samples or more) in terms of\nboth training time and validation score.\nFor small datasets, however, 'lbfgs' can converge faster and perform\nbetter.\n","name":"solver"},{"default":0.0001,"description":"L2 penalty (regularization term) parameter.\n","name":"alpha","type":"float32"},{"default":"auto","description":"Size of minibatches for stochastic optimizers.\nIf the solver is 'lbfgs', the classifier will not use minibatch.\nWhen set to \"auto\", `batch_size=min(200, n_samples)`\n","name":"batch_size","type":"int32"},{"default":"constant","description":"Learning rate schedule for weight updates.\n\n- 'constant' is a constant learning rate given by\n'learning_rate_init'.\n\n- 'invscaling' gradually decreases the learning rate ``learning_rate_``\nat each time step 't' using an inverse scaling exponent of 'power_t'.\neffective_learning_rate = learning_rate_init / pow(t, power_t)\n\n- 'adaptive' keeps the learning rate constant to\n'learning_rate_init' as long as training loss keeps decreasing.\nEach time two consecutive epochs fail to decrease training loss by at\nleast tol, or fail to increase validation score by at least tol if\n'early_stopping' is on, the current learning rate is divided by 5.\n\nOnly used when solver='sgd'.\n","name":"learning_rate"},{"default":"0.001","description":"The initial learning rate used. It controls the step-size\nin updating the weights. Only used when solver='sgd' or 'adam'.\n","name":"learning_rate_init"},{"default":"0.5","description":"The exponent for inverse scaling learning rate.\nIt is used in updating effective learning rate when the learning_rate\nis set to 'invscaling'. Only used when solver='sgd'.\n","name":"power_t"},{"default":200,"description":"Maximum number of iterations. The solver iterates until convergence\n(determined by 'tol') or this number of iterations. For stochastic\nsolvers ('sgd', 'adam'), note that this determines the number of epochs\n(how many times each data point will be used), not the number of\ngradient steps.\n","name":"max_iter","type":"int32"},{"default":true,"description":"Whether to shuffle samples in each iteration. Only used when\nsolver='sgd' or 'adam'.\n","name":"shuffle","type":"boolean"},{"default":null,"description":"Determines random number generation for weights and bias\ninitialization, train-test split if early stopping is used, and batch\nsampling when solver='sgd' or 'adam'.\nPass an int for reproducible results across multiple function calls.\nSee :term:`Glossary `.\n","name":"random_state","type":"int32"},{"default":0.0001,"description":"Tolerance for the optimization. When the loss or score is not improving\nby at least ``tol`` for ``n_iter_no_change`` consecutive iterations,\nunless ``learning_rate`` is set to 'adaptive', convergence is\nconsidered to be reached and training stops.\n","name":"tol","type":"float32"},{"default":false,"description":"Whether to print progress messages to stdout.\n","name":"verbose","type":"boolean"},{"default":false,"description":"When set to True, reuse the solution of the previous\ncall to fit as initialization, otherwise, just erase the\nprevious solution. See :term:`the Glossary `.\n","name":"warm_start","type":"boolean"},{"default":0.9,"description":"Momentum for gradient descent update. Should be between 0 and 1. Only\nused when solver='sgd'.\n","name":"momentum","type":"float32"},{"default":true,"description":"Whether to use Nesterov's momentum. Only used when solver='sgd' and\nmomentum > 0.\n","name":"nesterovs_momentum","type":"boolean"},{"default":false,"description":"Whether to use early stopping to terminate training when validation\nscore is not improving. If set to true, it will automatically set\naside 10% of training data as validation and terminate training when\nvalidation score is not improving by at least ``tol`` for\n``n_iter_no_change`` consecutive epochs.\nOnly effective when solver='sgd' or 'adam'\n","name":"early_stopping","type":"boolean"},{"default":0.1,"description":"The proportion of training data to set aside as validation set for\nearly stopping. Must be between 0 and 1.\nOnly used if early_stopping is True\n","name":"validation_fraction","type":"float32"},{"default":0.9,"description":"Exponential decay rate for estimates of first moment vector in adam,\nshould be in [0, 1). Only used when solver='adam'\n","name":"beta_1","type":"float32"},{"default":0.999,"description":"Exponential decay rate for estimates of second moment vector in adam,\nshould be in [0, 1). Only used when solver='adam'\n","name":"beta_2","type":"float32"},{"default":1e-8,"description":"Value for numerical stability in adam. Only used when solver='adam'\n","name":"epsilon","type":"float32"},{"default":10,"description":"Maximum number of epochs to not meet ``tol`` improvement.\nOnly effective when solver='sgd' or 'adam'\n\n.. versionadded:: 0.20\n","name":"n_iter_no_change","type":"int32"},{"default":15000,"description":"Only used when solver='lbfgs'. Maximum number of function calls.\nThe solver iterates until convergence (determined by 'tol'), number\nof iterations reaches max_iter, or this number of function calls.\nNote that number of function calls will be greater than or equal to\nthe number of iterations for the MLPRegressor.\n\n.. versionadded:: 0.22\n","name":"max_fun","type":"int32"}],"description":"Multi-layer Perceptron regressor.\n\nThis model optimizes the squared-loss using LBFGS or stochastic gradient\ndescent.\n\n.. versionadded:: 0.18\n"}},{"name":"sklearn.discriminant_analysis.LinearDiscriminantAnalysis","schema":{"attributes":[{"default":"svd","description":"Solver to use, possible values:\n- 'svd': Singular value decomposition (default).\nDoes not compute the covariance matrix, therefore this solver is\nrecommended for data with a large number of features.\n- 'lsqr': Least squares solution, can be combined with shrinkage.\n- 'eigen': Eigenvalue decomposition, can be combined with shrinkage.\n","name":"solver"},{"description":"Shrinkage parameter, possible values:\n- None: no shrinkage (default).\n- 'auto': automatic shrinkage using the Ledoit-Wolf lemma.\n- float between 0 and 1: fixed shrinkage parameter.\n\nNote that shrinkage works only with 'lsqr' and 'eigen' solvers.\n","name":"shrinkage"},{"default":null,"description":"The class prior probabilities. By default, the class proportions are\ninferred from the training data.\n","name":"priors"},{"default":null,"description":"Number of components (<= min(n_classes - 1, n_features)) for\ndimensionality reduction. If None, will be set to\nmin(n_classes - 1, n_features). This parameter only affects the\n`transform` method.\n","name":"n_components","type":"int32"},{"default":false,"description":"If True, explicitely compute the weighted within-class covariance\nmatrix when solver is 'svd'. The matrix is always computed\nand stored for the other solvers.\n\n.. versionadded:: 0.17\n","name":"store_covariance","type":"boolean"},{"default":0.0001,"description":"Absolute threshold for a singular value of X to be considered\nsignificant, used to estimate the rank of X. Dimensions whose\nsingular values are non-significant are discarded. Only used if\nsolver is 'svd'.\n\n.. versionadded:: 0.17\n","name":"tol","type":"float32"}],"description":"Linear Discriminant Analysis\n\nA classifier with a linear decision boundary, generated by fitting class\nconditional densities to the data and using Bayes' rule.\n\nThe model fits a Gaussian density to each class, assuming that all classes\nshare the same covariance matrix.\n\nThe fitted model can also be used to reduce the dimensionality of the input\nby projecting it to the most discriminative directions, using the\n`transform` method.\n\n.. versionadded:: 0.17\n*LinearDiscriminantAnalysis*.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.preprocessing._data.StandardScaler","schema":{"attributes":[{"default":true,"description":"If False, try to avoid a copy and do inplace scaling instead.\nThis is not guaranteed to always work inplace; e.g. if the data is\nnot a NumPy array or scipy.sparse CSR matrix, a copy may still be\nreturned.\n","name":"copy","option":"optional","type":"boolean"},{"default":true,"description":"If True, center the data before scaling.\nThis does not work (and will raise an exception) when attempted on\nsparse matrices, because centering them entails building a dense\nmatrix which in common use cases is likely to be too large to fit in\nmemory.\n","name":"with_mean","type":"boolean"},{"default":true,"description":"If True, scale the data to unit variance (or equivalently,\nunit standard deviation).\n","name":"with_std","type":"boolean"}],"description":"Standardize features by removing the mean and scaling to unit variance\n\nThe standard score of a sample `x` is calculated as:\n\nz = (x - u) / s\n\nwhere `u` is the mean of the training samples or zero if `with_mean=False`,\nand `s` is the standard deviation of the training samples or one if\n`with_std=False`.\n\nCentering and scaling happen independently on each feature by computing\nthe relevant statistics on the samples in the training set. Mean and\nstandard deviation are then stored to be used on later data using\n:meth:`transform`.\n\nStandardization of a dataset is a common requirement for many\nmachine learning estimators: they might behave badly if the\nindividual features do not more or less look like standard normally\ndistributed data (e.g. Gaussian with 0 mean and unit variance).\n\nFor instance many elements used in the objective function of\na learning algorithm (such as the RBF kernel of Support Vector\nMachines or the L1 and L2 regularizers of linear models) assume that\nall features are centered around 0 and have variance in the same\norder. If a feature has a variance that is orders of magnitude larger\nthat others, it might dominate the objective function and make the\nestimator unable to learn from other features correctly as expected.\n\nThis scaler can also be applied to sparse CSR or CSC matrices by passing\n`with_mean=False` to avoid breaking the sparsity structure of the data.\n\nRead more in the :ref:`User Guide `.\n"}},{"name":"sklearn.tree.tree.DecisionTreeClassifier","schema":{"attributes":[{"default":"\"gini\"","description":"The function to measure the quality of a split. Supported criteria are\n\"gini\" for the Gini impurity and \"entropy\" for the information gain.\n","name":"criterion"},{"default":"\"best\"","description":"The strategy used to choose the split at each node. Supported\nstrategies are \"best\" to choose the best split and \"random\" to choose\nthe best random split.\n","name":"splitter"},{"default":null,"description":"The maximum depth of the tree. If None, then nodes are expanded until\nall leaves are pure or until all leaves contain less than\nmin_samples_split samples.\n","name":"max_depth","type":"int32"},{"default":"2","description":"The minimum number of samples required to split an internal node:\n\n- If int, then consider `min_samples_split` as the minimum number.\n- If float, then `min_samples_split` is a fraction and\n`ceil(min_samples_split * n_samples)` are the minimum\nnumber of samples for each split.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_split"},{"default":"1","description":"The minimum number of samples required to be at a leaf node.\nA split point at any depth will only be considered if it leaves at\nleast ``min_samples_leaf`` training samples in each of the left and\nright branches. This may have the effect of smoothing the model,\nespecially in regression.\n\n- If int, then consider `min_samples_leaf` as the minimum number.\n- If float, then `min_samples_leaf` is a fraction and\n`ceil(min_samples_leaf * n_samples)` are the minimum\nnumber of samples for each node.\n\n.. versionchanged:: 0.18\nAdded float values for fractions.\n","name":"min_samples_leaf"},{"default":0,"description":"The minimum weighted fraction of the sum total of weights (of all\nthe input samples) required to be at a leaf node. Samples have\nequal weight when sample_weight is not provided.\n","name":"min_weight_fraction_leaf","type":"float32"},{"default":null,"description":"The number of features to consider when looking for the best split:\n\n- If int, then consider `max_features` features at each split.\n- If float, then `max_features` is a fraction and\n`int(max_features * n_features)` features are considered at each\nsplit.\n- If \"auto\", then `max_features=sqrt(n_features)`.\n- If \"sqrt\", then `max_features=sqrt(n_features)`.\n- If \"log2\", then `max_features=log2(n_features)`.\n- If None, then `max_features=n_features`.\n\nNote: the search for a split does not stop until at least one\nvalid partition of the node samples is found, even if it requires to\neffectively inspect more than ``max_features`` features.\n","name":"max_features","type":"int32"},{"default":null,"description":"Controls the randomness of the estimator. The features are always\nrandomly permuted at each split, even if ``splitter`` is set to\n``\"best\"``. When ``max_features < n_features``, the algorithm will\nselect ``max_features`` at random at each split before finding the best\nsplit among them. But the best found split may vary across different\nruns, even if ``max_features=n_features``. That is the case, if the\nimprovement of the criterion is identical for several splits and one\nsplit has to be selected at random. To obtain a deterministic behaviour\nduring fitting, ``random_state`` has to be fixed to an integer.\nSee :term:`Glossary ` for details.\n","name":"random_state","type":"int32"},{"default":null,"description":"Grow a tree with ``max_leaf_nodes`` in best-first fashion.\nBest nodes are defined as relative reduction in impurity.\nIf None then unlimited number of leaf nodes.\n","name":"max_leaf_nodes","type":"int32"},{"default":0,"description":"A node will be split if this split induces a decrease of the impurity\ngreater than or equal to this value.\n\nThe weighted impurity decrease equation is the following::\n\nN_t / N * (impurity - N_t_R / N_t * right_impurity\n- N_t_L / N_t * left_impurity)\n\nwhere ``N`` is the total number of samples, ``N_t`` is the number of\nsamples at the current node, ``N_t_L`` is the number of samples in the\nleft child, and ``N_t_R`` is the number of samples in the right child.\n\n``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,\nif ``sample_weight`` is passed.\n\n.. versionadded:: 0.19\n","name":"min_impurity_decrease","type":"float32"},{"default":0,"description":"Threshold for early stopping in tree growth. A node will split\nif its impurity is above the threshold, otherwise it is a leaf.\n\n.. deprecated:: 0.19\n``min_impurity_split`` has been deprecated in favor of\n``min_impurity_decrease`` in 0.19. The default value of\n``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it\nwill be removed in 0.25. Use ``min_impurity_decrease`` instead.\n","name":"min_impurity_split","type":"float32"},{"default":null,"description":"Weights associated with classes in the form ``{class_label: weight}``.\nIf None, all classes are supposed to have weight one. For\nmulti-output problems, a list of dicts can be provided in the same\norder as the columns of y.\n\nNote that for multioutput (including multilabel) weights should be\ndefined for each class of every column in its own dict. For example,\nfor four-class multilabel classification weights should be\n[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of\n[{1:1}, {2:5}, {3:1}, {4:1}].\n\nThe \"balanced\" mode uses the values of y to automatically adjust\nweights inversely proportional to class frequencies in the input data\nas ``n_samples / (n_classes * np.bincount(y))``\n\nFor multi-output, the weights of each column of y will be multiplied.\n\nNote that these weights will be multiplied with sample_weight (passed\nthrough the fit method) if sample_weight is specified.\n","name":"class_weight"},{"default":"deprecated","description":"This parameter is deprecated and will be removed in v0.24.\n\n.. deprecated:: 0.22\n","name":"presort"},{"default":"0.0","description":"Complexity parameter used for Minimal Cost-Complexity Pruning. The\nsubtree with the largest cost complexity that is smaller than\n``ccp_alpha`` will be chosen. By default, no pruning is performed. See\n:ref:`minimal_cost_complexity_pruning` for details.\n\n.. versionadded:: 0.22\n","name":"ccp_alpha"}],"description":"A decision tree classifier.\n\nRead more in the :ref:`User Guide `.\n"}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn.js new file mode 100644 index 0000000000000000000000000000000000000000..493509379375ec8aff36e8df6716c58ce1ce2542 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/sklearn.js @@ -0,0 +1 @@ +var sklearn=sklearn||{},long=long||{Long:require("long")},zip=zip||require("./zip");sklearn.ModelFactory=class{match(e){const t=e.identifier.split(".").pop().toLowerCase();if(-1!==["pkl","pickle","joblib","model","meta","pb","pt","h5"].indexOf(t)){const t=e.buffer;if(t){const e=[138,10,108,252,156,70,249,32,106,168,80,25];if(t.length>14&&128==t[0]&&e.every(((e,n)=>e==t[n+2])))return!1;if(t.length>1&&46===t[t.length-1])return!0;if(t.length>2&&128===t[0]&&t[1]<5)return!0}}if(-1!==["pkl","joblib"].indexOf(t)){const t=e.buffer;if(t&&t.length>0&&120==t[0])return!0}return!1}open(e,t){return t.require("./pickle").then((n=>{const s=e.identifier;return sklearn.Metadata.open(t).then((r=>{try{const i=new sklearn.Container(e.buffer,n,((e,n)=>{const r=e&&e.message?e.message:e.toString();t.exception(new sklearn.Error(r.replace(/\.$/,"")+" in '"+s+"'."),n)}));if(!i.weights&&!i.data)throw new sklearn.Error("No root object.");return new sklearn.Model(r,i.data,i.weights)}catch(e){t.exception(e,!1);const n=e&&e.message?e.message:e.toString();throw new sklearn.Error(n.replace(/\.$/,"")+" in '"+s+"'.")}}))}))}},sklearn.Model=class{constructor(e,t,n){const s=Array.isArray(t)?t:[t],r=Array.from(new Set(s.map((e=>{if(e&&e.__module__){if(e.__module__.startsWith("sklearn."))return"scikit-learn"+(e._sklearn_version?" v"+e._sklearn_version.toString():"");if(e.__module__.startsWith("xgboost."))return"XGBoost"+(e._sklearn_version?" v"+e._sklearn_version.toString():"");if(e.__module__.startsWith("nolearn.lasagne."))return"Lasagne";if(e.__module__.startsWith("gensim."))return"gensim"}return"Pickle"}))).values());if(r.length>1)throw new sklearn.Error("Invalid array format '"+JSON.stringify(r)+"'.");this._format=r[0],this._graphs=s.map(((t,s)=>new sklearn.Graph(e,s,t,n)))}get format(){return this._format}get graphs(){return this._graphs}},sklearn.Graph=class{constructor(e,t,n,s){if(this._name=t.toString(),this._metadata=e,this._nodes=[],this._groups=!1,n)this._process("","",n,["data"]);else if(s instanceof Map){const e=new Map,t=[];for(const n of s){const s=n[0],r=s.split("_"),i=n[1],a=r.length>1?r.pop():"?",o=r.join("_");let l=e.get(o);l||(l={id:o,arrays:[]},t.push(l),e.set(o,l)),l.arrays.push({key:s,name:a,value:i})}this._nodes=this._nodes.concat(t.map((e=>{const t=e.arrays.map((e=>new sklearn.Parameter(e.name,[new sklearn.Argument(e.key,null,new sklearn.Tensor(e.key,e.value))])));return new sklearn.Node(this._metadata,"",e.id,{__module__:"sklearn._",__name__:"Weights"},t,[])})))}}_process(e,t,n,s){switch([n.__module__,n.__name__].join(".")){case"sklearn.pipeline.Pipeline":{this._groups=!0,t=t||"pipeline";const r=this._concat(e,t);for(const e of n.steps)s=this._process(r,e[0],e[1],s);return s}case"sklearn.pipeline.FeatureUnion":{this._groups=!0;let r=[];t=t||"union";const i=this._concat(e,t),a=this._concat(e,t);this._add(a,i,n,s,[i]);for(const e of n.transformer_list)r=r.concat(this._process(a,e[0],e[1],[i]));return r}case"sklearn.compose._column_transformer.ColumnTransformer":{this._groups=!0,t=t||"transformer";const r=this._concat(e,t),i=this._concat(e,t);let a=[];this._add(i,r,n,s,[r]);for(const e of n.transformers)a=a.concat(this._process(i,e[0],e[1],[r]));return a}default:{const r=this._concat(e,t);return this._add(e,r,n,s,[r]),[r]}}}_add(e,t,n,s,r){const i=[];for(const e of Object.keys(n))if(!e.startsWith("_")){const t=n[e];sklearn.Utility.isTensor(t)&&i.push(new sklearn.Tensor(e,t))}s=(s=s.map((e=>new sklearn.Parameter(e,[new sklearn.Argument(e,null,null)])))).concat(i.map((e=>new sklearn.Parameter(e.name,[new sklearn.Argument("",null,e)])))),r=r.map((e=>new sklearn.Parameter(e,[new sklearn.Argument(e,null,null)]))),this._nodes.push(new sklearn.Node(this._metadata,e,t,n,s,r))}_concat(e,t){return""===e?t:`${e}/${t}`}get name(){return this._name}get groups(){return this._groups}get inputs(){return[]}get outputs(){return[]}get nodes(){return this._nodes}},sklearn.Parameter=class{constructor(e,t){this._name=e,this._arguments=t}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},sklearn.Argument=class{constructor(e,t,n){if("string"!=typeof e)throw new sklearn.Error("Invalid argument identifier '"+JSON.stringify(e)+"'.");this._name=e,this._type=t||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},sklearn.Node=class{constructor(e,t,n,s,r,i){this._metadata=e,this._group=t||"",this._name=n||"",this._type=s.__module__&&s.__name__?s.__module__+"."+s.__name__:s.__name__?s.__name__:"Object",this._inputs=r,this._outputs=i,this._attributes=[],this._initializers=[];for(const t of Object.keys(s))if(!t.startsWith("_")){const n=s[t];if(n&&!Array.isArray(n)&&n===Object(n)&&sklearn.Utility.isTensor(n))this._initializers.push(new sklearn.Tensor(t,n));else{const s=e.attribute(this._type,t);this._attributes.push(new sklearn.Attribute(s,t,n))}}}get type(){return this._type}get name(){return this._name}get group(){return this._group?this._group:null}get metadata(){return this._metadata.type(this._type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},sklearn.Attribute=class{constructor(e,t,n){this._name=t,this._value=n,e&&(Object.prototype.hasOwnProperty.call(e,"option")&&"optional"==e.option&&null==this._value||Object.prototype.hasOwnProperty.call(e,"visible")&&!e.visible||Object.prototype.hasOwnProperty.call(e,"default")&&sklearn.Attribute._isEquivalent(e.default,this._value))&&(this._visible=!1)}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}static _isEquivalent(e,t){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!=e)return t!=t;const n=typeof e;if("function"!==n&&"object"!==n&&"object"!=typeof t)return!1;const s=toString.call(e);if(s!==toString.call(t))return!1;switch(s){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Array]":{let n=e.length;if(n!==t.length)return!1;for(;n--;)if(!sklearn.Attribute._isEquivalent(e[n],t[n]))return!1;return!0}}const r=Object.keys(e);let i=r.length;if(Object.keys(t).length!=i)return!1;for(;i--;){const n=r[i];if(!Object.prototype.hasOwnProperty.call(t,n)||!sklearn.Attribute._isEquivalent(e[n],t[n]))return!1}return!0}},sklearn.Tensor=class{constructor(e,t){if(this._name=e,!sklearn.Utility.isTensor(t)){const e=[t.__module__,t.__name__].join(".");throw new sklearn.Error("Unknown tensor type '"+e+"'.")}this._kind="Array",this._type=new sklearn.TensorType(t.dtype.name,new sklearn.TensorShape(t.shape)),this._data=t.data}get name(){return this._name}get type(){return this._type}get kind(){return this._kind}get state(){return this._context().state||null}get value(){const e=this._context();return e.state?null:(e.limit=Number.MAX_SAFE_INTEGER,this._decode(e,0))}toString(){const e=this._context();if(e.state)return"";e.limit=1e4;const t=this._decode(e,0);switch(this._type.dataType){case"int64":case"uint64":return sklearn.Tensor._stringify(t,""," ")}return JSON.stringify(t,null,4)}_context(){const e={index:0,count:0,state:null};if(!this._type)return e.state="Tensor has no data type.",e;if(!this._data)return e.state="Tensor is data is empty.",e;switch(e.dataType=this._type.dataType,e.dimensions=this._type.shape.dimensions,e.dataType){case"float32":case"float64":case"int32":case"uint32":case"int64":case"uint64":e.rawData=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:return e.state="Tensor data type '"+e.dataType+"' is not implemented.",e}return e}_decode(e,t){const n=[],s=e.dimensions[t];if(t==e.dimensions.length-1)for(let t=0;te.limit)return n.push("..."),n;switch(e.dataType){case"float32":n.push(e.rawData.getFloat32(e.index,!0)),e.index+=4,e.count++;break;case"float64":n.push(e.rawData.getFloat64(e.index,!0)),e.index+=8,e.count++;break;case"int32":n.push(e.rawData.getInt32(e.index,!0)),e.index+=4,e.count++;break;case"uint32":n.push(e.rawData.getUint32(e.index,!0)),e.index+=4,e.count++;break;case"int64":n.push(new long.Long(e.rawData.getUint32(e.index,!0),e.rawData.getUint32(e.index+4,!0),!1)),e.index+=8,e.count++;break;case"uint64":n.push(new long.Long(e.rawData.getUint32(e.index,!0),e.rawData.getUint32(e.index+4,!0),!0)),e.index+=8,e.count++}}else for(let r=0;re.limit)return n.push("..."),n;n.push(this._decode(e,t+1))}return n}static _stringify(e,t,n){if(Array.isArray(e)){const s=[];s.push("[");const r=e.map((e=>sklearn.Tensor._stringify(e,t+n,n)));return r.length>0&&s.push(r.join(",\n")),s.push("]"),s.join("\n")}return t+e.toString()}},sklearn.TensorType=class{constructor(e,t){this._dataType=e,this._shape=t}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},sklearn.TensorShape=class{constructor(e){this._dimensions=e}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((e=>e.toString())).join(",")+"]":""}},sklearn.Metadata=class{static open(e){return sklearn.Metadata._metadata?Promise.resolve(sklearn.Metadata._metadata):e.request(null,"sklearn-metadata.json","utf-8").then((e=>(sklearn.Metadata._metadata=new sklearn.Metadata(e),sklearn.Metadata._metadata))).catch((()=>(sklearn.Metadata._metadata=new sklearn.Metadata(null),sklearn.Metadata._metadata)))}constructor(e){if(this._map=new Map,this._attributeCache=new Map,e){const t=JSON.parse(e);if(t)for(const e of t)e.name&&e.schema&&(e.schema.name=e.name,this._map.set(e.name,e.schema))}}type(e){return this._map.get(e)}attribute(e,t){const n=e+":"+t;if(!this._attributeCache.has(n)){const t=this.type(e);if(t&&t.attributes&&t.attributes.length>0)for(const n of t.attributes)this._attributeCache.set(e+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},sklearn.Container=class{constructor(e,t,n){e.length>0&&120==e[0]&&(e=(new zip.Inflater).inflate(e));const s=new t.Unpickler(e),r={},i={};r["numpy.dtype"]=function(e,t,n){switch(e){case"i1":this.name="int8",this.itemsize=1;break;case"i2":this.name="int16",this.itemsize=2;break;case"i4":this.name="int32",this.itemsize=4;break;case"i8":this.name="int64",this.itemsize=8;break;case"u1":this.name="uint8",this.itemsize=1;break;case"u2":this.name="uint16",this.itemsize=2;break;case"u4":this.name="uint32",this.itemsize=4;break;case"u8":this.name="uint64",this.itemsize=8;break;case"f2":this.name="float16",this.itemsize=2;break;case"f4":this.name="float32",this.itemsize=4;break;case"f8":this.name="float64",this.itemsize=8;break;case"b1":this.name="int8",this.itemsize=1;break;default:if(e.startsWith("V"))this.itemsize=Number(e.substring(1)),this.name="void"+(8*this.itemsize).toString();else if(e.startsWith("O"))this.itemsize=Number(e.substring(1)),this.name="object";else if(e.startsWith("S"))this.itemsize=Number(e.substring(1)),this.name="string";else if(e.startsWith("U"))this.itemsize=Number(e.substring(1)),this.name="string";else{if(!e.startsWith("M"))throw new sklearn.Error("Unknown dtype '"+e.toString()+"'.");this.itemsize=Number(e.substring(1)),this.name="datetime"}}this.align=t,this.copy=n,this.__setstate__=function(e){switch(e.length){case 8:this.version=e[0],this.byteorder=e[1],this.subarray=e[2],this.names=e[3],this.fields=e[4],this.elsize=e[5],this.alignment=e[6],this.int_dtypeflags=e[7];break;default:throw new sklearn.Error("Unknown numpy.dtype setstate length '"+e.length.toString()+"'.")}}},r["numpy.core.multiarray._reconstruct"]=function(e,t,n){this.subtype=e,this.shape=t,this.dtype=n,this.__setstate__=function(e){this.version=e[0],this.shape=e[1],this.typecode=e[2],this.is_f_order=e[3],this.rawdata=e[4]},this.__read__=function(e){const t={};sklearn.Utility.applyType(t,this.subtype),t.dtype=this.typecode,t.shape=this.shape;const n=t.shape&&t.shape.length>0?t.shape.reduce(((e,t)=>e*t)):1,s=t.dtype.itemsize*n;if("string"==typeof this.rawdata){if(t.data=e.unescape(this.rawdata,s),t.data.length!=s)throw new sklearn.Error("Invalid string array data size.")}else t.data=this.rawdata;return t}},r["joblib.numpy_pickle.NumpyArrayWrapper"]=function(){this.__setstate__=function(e){this.subclass=e.subclass,this.dtype=e.dtype,this.shape=e.shape,this.order=e.order,this.allow_mmap=e.allow_mmap},this.__read__=function(e){if("object"==this.dtype.name)return e.load(l,null);{const t=this.dtype.itemsize*this.shape.reduce(((e,t)=>e*t));this.data=e.read(t)}const t={dtype:this.dtype,shape:this.shape,data:this.data};return sklearn.Utility.applyType(t,this.subclass),t}},r["gensim.models.doc2vec.Doctag"]=function(){},r["gensim.models.doc2vec.Doc2Vec"]=function(){},r["gensim.models.doc2vec.Doc2VecTrainables"]=function(){},r["gensim.models.doc2vec.Doc2VecVocab"]=function(){},r["gensim.models.fasttext.FastText"]=function(){},r["gensim.models.fasttext.FastTextTrainables"]=function(){},r["gensim.models.fasttext.FastTextVocab"]=function(){},r["gensim.models.fasttext.FastTextKeyedVectors"]=function(){},r["gensim.models.keyedvectors.Doc2VecKeyedVectors"]=function(){},r["gensim.models.keyedvectors.Vocab"]=function(){},r["gensim.models.keyedvectors.Word2VecKeyedVectors"]=function(){},r["gensim.models.phrases.Phrases"]=function(){},r["gensim.models.tfidfmodel.TfidfModel"]=function(){},r["gensim.models.word2vec.Vocab"]=function(){},r["gensim.models.word2vec.Word2Vec"]=function(){},r["lightgbm.sklearn.LGBMRegressor"]=function(){},r["lightgbm.sklearn.LGBMClassifier"]=function(){},r["lightgbm.basic.Booster"]=function(){},r["nolearn.lasagne.base.BatchIterator"]=function(){},r["nolearn.lasagne.base.Layers"]=function(){},r["nolearn.lasagne.base.NeuralNet"]=function(){},r["nolearn.lasagne.base.TrainSplit"]=function(){},r["nolearn.lasagne.handlers.PrintLayerInfo"]=function(){},r["nolearn.lasagne.handlers.PrintLog"]=function(){},r["sklearn.calibration._CalibratedClassifier"]=function(){},r["sklearn.calibration._SigmoidCalibration"]=function(){},r["sklearn.calibration.CalibratedClassifierCV​"]=function(){},r["sklearn.compose._column_transformer.ColumnTransformer"]=function(){},r["sklearn.compose._target.TransformedTargetRegressor"]=function(){},r["sklearn.cluster._dbscan.DBSCAN"]=function(){},r["sklearn.cluster._kmeans.KMeans"]=function(){},r["sklearn.decomposition._pca.PCA"]=function(){},r["sklearn.decomposition.PCA"]=function(){},r["sklearn.decomposition.pca.PCA"]=function(){},r["sklearn.decomposition._truncated_svd.TruncatedSVD"]=function(){},r["sklearn.decomposition.truncated_svd.TruncatedSVD"]=function(){},r["sklearn.discriminant_analysis.LinearDiscriminantAnalysis"]=function(){},r["sklearn.dummy.DummyClassifier"]=function(){},r["sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper"]=r["joblib.numpy_pickle.NumpyArrayWrapper"],r["sklearn.externals.joblib.numpy_pickle.NDArrayWrapper"]=function(){},r["sklearn.ensemble._bagging.BaggingClassifier"]=function(){},r["sklearn.ensemble._forest.RandomForestRegressor"]=function(){},r["sklearn.ensemble._forest.RandomForestClassifier"]=function(){},r["sklearn.ensemble._forest.ExtraTreesClassifier"]=function(){},r["sklearn.ensemble._gb_losses.BinomialDeviance"]=function(){},r["sklearn.ensemble._gb_losses.MultinomialDeviance"]=function(){},r["sklearn.ensemble._gb.GradientBoostingClassifier"]=function(){},r["sklearn.ensemble._iforest.IsolationForest"]=function(){},r["sklearn.ensemble._voting.VotingClassifier"]=function(){},r["sklearn.ensemble.forest.RandomForestClassifier"]=function(){},r["sklearn.ensemble.forest.RandomForestRegressor"]=function(){},r["sklearn.ensemble.forest.ExtraTreesClassifier"]=function(){},r["sklearn.ensemble.gradient_boosting.BinomialDeviance"]=function(){},r["sklearn.ensemble.gradient_boosting.GradientBoostingClassifier"]=function(){},r["sklearn.ensemble.gradient_boosting.LogOddsEstimator"]=function(){},r["sklearn.ensemble.gradient_boosting.MultinomialDeviance"]=function(){},r["sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator"]=function(){},r["sklearn.ensemble.weight_boosting.AdaBoostClassifier"]=function(){},r["sklearn.feature_extraction._hashing.FeatureHasher"]=function(){},r["sklearn.feature_extraction.text.CountVectorizer"]=function(){},r["sklearn.feature_extraction.text.HashingVectorizer"]=function(){},r["sklearn.feature_extraction.text.TfidfTransformer"]=function(){},r["sklearn.feature_extraction.text.TfidfVectorizer"]=function(){},r["sklearn.feature_selection._univariate_selection.SelectKBest"]=function(){},r["sklearn.feature_selection._univariate_selection.SelectPercentile"]=function(){},r["sklearn.feature_selection.univariate_selection.SelectKBest"]=function(){},r["sklearn.feature_selection.variance_threshold.VarianceThreshold"]=function(){},r["sklearn.impute._base.SimpleImputer"]=function(){},r["sklearn.impute.SimpleImputer"]=function(){},r["sklearn.linear_model._base.LinearRegression"]=function(){},r["sklearn.linear_model._coordinate_descent.ElasticNet"]=function(){},r["sklearn.linear_model.base.LinearRegression"]=function(){},r["sklearn.linear_model.sgd_fast.Hinge"]=function(){},r["sklearn.linear_model.LogisticRegression"]=function(){},r["sklearn.linear_model.logistic.LogisticRegression"]=function(){},r["sklearn.linear_model._logistic.LogisticRegression"]=function(){},r["sklearn.linear_model.LassoLars​"]=function(){},r["sklearn.linear_model.ridge.Ridge"]=function(){},r["sklearn.linear_model.sgd_fast.Log"]=function(){},r["sklearn.linear_model.stochastic_gradient.SGDClassifier"]=function(){},r["sklearn.metrics.scorer._PredictScorer"]=function(){},r["sklearn.model_selection._search.GridSearchCV"]=function(){},r["sklearn.naive_bayes.BernoulliNB"]=function(){},r["sklearn.naive_bayes.ComplementNB"]=function(){},r["sklearn.naive_bayes.GaussianNB"]=function(){},r["sklearn.naive_bayes.MultinomialNB"]=function(){},r["sklearn.neighbors.classification.KNeighborsClassifier"]=function(){},r["sklearn.neighbors.dist_metrics.newObj"]=function(){},r["sklearn.neighbors.kd_tree.newObj"]=function(){},r["sklearn.neighbors.KNeighborsClassifier"]=function(){},r["sklearn.neighbors.KNeighborsRegressor"]=function(){},r["sklearn.neighbors.regression.KNeighborsRegressor"]=function(){},r["sklearn.neighbors.unsupervised.NearestNeighbors"]=function(){},r["sklearn.neural_network._multilayer_perceptron.MLPClassifier"]=function(){},r["sklearn.neural_network._multilayer_perceptron.MLPRegressor"]=function(){},r["sklearn.neural_network._stochastic_optimizers.AdamOptimizer"]=function(){},r["sklearn.neural_network._stochastic_optimizers.SGDOptimizer"]=function(){},r["sklearn.neural_network.rbm.BernoulliRBM"]=function(){},r["sklearn.neural_network.multilayer_perceptron.MLPClassifier"]=function(){},r["sklearn.neural_network.multilayer_perceptron.MLPRegressor"]=function(){},r["sklearn.neural_network.stochastic_gradient.SGDClassifier"]=function(){},r["sklearn.pipeline.Pipeline"]=function(){},r["sklearn.pipeline.FeatureUnion"]=function(){},r["sklearn.preprocessing._data.PolynomialFeatures"]=function(){},r["sklearn.preprocessing._data.RobustScaler"]=function(){},r["sklearn.preprocessing._data.StandardScaler"]=function(){},r["sklearn.preprocessing._discretization.KBinsDiscretizer"]=function(){},r["sklearn.preprocessing._encoders.OneHotEncoder"]=function(){},r["sklearn.preprocessing._function_transformer.FunctionTransformer"]=function(){},r["sklearn.preprocessing._label.LabelBinarizer"]=function(){},r["sklearn.preprocessing._label.LabelEncoder"]=function(){},r["sklearn.preprocessing.data.Binarizer"]=function(){},r["sklearn.preprocessing.data.MaxAbsScaler"]=function(){},r["sklearn.preprocessing.data.MinMaxScaler"]=function(){},r["sklearn.preprocessing.data.Normalizer"]=function(){},r["sklearn.preprocessing.data.OneHotEncoder"]=function(){},r["sklearn.preprocessing.data.PolynomialFeatures"]=function(){},r["sklearn.preprocessing.data.PowerTransformer"]=function(){},r["sklearn.preprocessing.data.RobustScaler"]=function(){},r["sklearn.preprocessing.data.QuantileTransformer"]=function(){},r["sklearn.preprocessing.data.StandardScaler"]=function(){},r["sklearn.preprocessing.imputation.Imputer"]=function(){},r["sklearn.preprocessing.label.LabelBinarizer"]=function(){},r["sklearn.preprocessing.label.LabelEncoder"]=function(){},r["sklearn.preprocessing.label.MultiLabelBinarizer"]=function(){},r["sklearn.svm._classes.SVC"]=function(){},r["sklearn.svm.classes.LinearSVC"]=function(){},r["sklearn.svm.classes.SVC"]=function(){},r["sklearn.svm.classes.SVR"]=function(){},r["sklearn.tree._classes.DecisionTreeClassifier"]=function(){},r["sklearn.tree._classes.DecisionTreeRegressor"]=function(){},r["sklearn.tree._classes.ExtraTreeClassifier"]=function(){},r["sklearn.tree._classes.ExtraTreeRegressor"]=function(){},r["sklearn.tree._tree.Tree"]=function(e,t,n){this.n_features=e,this.n_classes=t,this.n_outputs=n,this.__setstate__=function(e){this.max_depth=e.max_depth,this.node_count=e.node_count,this.nodes=e.nodes,this.values=e.values}},r["sklearn.tree.tree.DecisionTreeClassifier"]=function(){},r["sklearn.tree.tree.DecisionTreeRegressor"]=function(){},r["sklearn.tree.tree.ExtraTreeClassifier"]=function(){},r["sklearn.utils.deprecation.DeprecationDict"]=function(){},r["xgboost.compat.XGBoostLabelEncoder"]=function(){},r["xgboost.core.Booster"]=function(){},r["xgboost.sklearn.XGBClassifier"]=function(){},r["xgboost.sklearn.XGBRegressor"]=function(){},i["copy_reg._reconstructor"]=function(e,t,n){if("__builtin__.object"==t){const t={};return sklearn.Utility.applyType(t,e),t}if("__builtin__.tuple"==t)return n;throw new sklearn.Error("Unknown base type '"+t+"'.")},i["numpy.core.multiarray.scalar"]=function(e,t){let n=t;if("string"==typeof t||t instanceof String){n=new Uint8Array(t.length);for(let e=0;e{const s=i[e];if(s)return s.apply(null,t);const l={};sklearn.Utility.applyType(l,e);const c=r[e];return c?c.apply(l,t):e&&!a.has(e)&&(a.add(e),o.has(e.split(".").shift())&&n(new sklearn.Error("Unknown function '"+e+"'."),!1)),l};this._data=s.load(l,null),this._data&&(this._weights=function(e){for(const t of e)if(t&&!Array.isArray(t)){const e=new Map;for(const n in t){const s=t[n];if("weight_order"!=n&&"lr"!=n){if(!n||!sklearn.Utility.isTensor(s))return null;e.set(n,s)}}return e}for(const t of e)if(t&&Array.isArray(t)){const e=new Map;for(let n=0;n=148&&t<156?32:r[t];this._name=t.string(100),t.string(8),t.string(8),t.string(8);const s=parseInt(t.string(12).trim(),8);t.string(12);const i=parseInt(t.string(8).trim(),8);if(isNaN(i)||e!=i)throw new tar.Error("Invalid tar archive.");t.string(1),t.string(100),t.bytes(255),this._data=t.bytes(s),t.bytes(s%512!=0?512-s%512:0)}get name(){return this._name}get data(){return this._data}},tar.Reader=class{constructor(t){this._buffer=t,this._position=0,this._end=t.length}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new tar.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}peek(){return this._positiont==r)))&&(this._position+=t,!0)}bytes(t){const r=this._position;return this.skip(t),this._buffer.subarray(r,this._position)}string(t){const r=this.bytes(t);let e=0,s="";for(let i=0;i4&&(i[0]|i[1]<<8)<4)return!0}return!1}open(t,i){return tengine.Metadata.open(i).then((i=>{const e=t.identifier.toLowerCase();try{const e=t.buffer,s=e[0]|e[1]<<8,n=e[2]|e[3]<<8;if(2!==s)throw new tengine.Error("Unsupported format version 'v"+s.toString()+"."+n.toString()+"'.");return new tengine.Model(i,e)}catch(t){const i=t&&t.message?t.message:t.toString();throw new tengine.Error(i.replace(/\.$/,"")+" in '"+e+"'.")}}))}},tengine.Model=class{constructor(t,i){const e=new tengine.ModelFileReader(i);this._version=e.version,this._source=e.source,this._graphs=e.graphs.map((i=>new tengine.Graph(t,i)))}get format(){return"Tengine v"+this._version}get source(){return this._source}get graphs(){return this._graphs}},tengine.Graph=class{constructor(t,i){this._name=i.id.toString(),this._inputs=[],this._outputs=[],this._nodes=[];const e=i.tensors.map((t=>new tengine.Argument(t)));for(const t of i.inputs){const i=e[t];this._inputs.push(new tengine.Parameter(i.name,!0,[i]))}for(const t of i.outputs){const i=e[t];i.type&&i.type.shape&&i.type.shape.dimensions&&0==i.type.shape.dimensions.length&&null!==i.initializer||this._outputs.push(new tengine.Parameter(i.name,!0,[i]))}for(const s of i.nodes)"INPUT"!==s.type&&this._nodes.push(new tengine.Node(t,s,e))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},tengine.Parameter=class{constructor(t,i,e){this._name=t,this._visible=i,this._arguments=e}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},tengine.Argument=class{constructor(t){this._name=t.name,this._type=new tengine.TensorType(t.dataType,new tengine.TensorShape(t.dims)),this._initializer=2===t.type?new tengine.Tensor(this._type,t.buffer):null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get quantization(){return null}get initializer(){return this._initializer}},tengine.Node=class{constructor(t,i,e){this._metadata=t,this._name=i.name,this._type=i.type+(i.version&&1!==i.version?":"+i.version.toString():""),this._inputs=[],this._outputs=[],this._attributes=[];const s=t.type(this._type);for(let t=0;t""!=i||"optional"!=t.option)).map((t=>e[t]));this._inputs.push(new tengine.Parameter(t.name,!0,s)),a+=i}}else this._inputs=this._inputs.concat(n.slice(a).map(((t,i)=>{const s=a+i==0?"input":(a+i).toString();return new tengine.Parameter(s,!0,[e[t]])})));const r=i.outputs;let o=0;if(s&&s.outputs){for(const t of s.outputs)if(oe[t]));this._outputs.push(new tengine.Parameter(t.name,!0,s)),o+=i}}else this._outputs=this._outputs.concat(r.slice(o).map(((t,i)=>{const s=o+i==0?"output":(o+i).toString();return new tengine.Parameter(s,!0,[e[t]])})))}get type(){return this._type.split(":")[0]}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}},tengine.Attribute=class{constructor(t,i,e){this._type="",this._name=i,this._value=e,t&&(this._name=t.name,t.type&&(this._type=t.type),(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1))}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},tengine.Tensor=class{constructor(t,i,e){this._type=t,this._data=i,this._kind=e}get kind(){return this._kind}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const i=this._decode(t,0);return JSON.stringify(i,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape||this._type.shape.dimensions&&0==this._type.shape.dimensions.length)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"int8":case"uint8":case"float16":case"float32":case"int32":case"int16":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,i){const e=0==t.shape.length?[1]:t.shape,s=[],n=e[i];if(i==e.length-1)for(let i=0;it.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"int8":s.push(t.data.getInt8(t.index,!0)),t.index+=1,t.count++;break;case"uint8":s.push(t.data.getUint8(t.index,!0)),t.index+=1,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int16":s.push(t.data.getInt16(t.index,!0)),t.index+=2,t.count++}}else for(let e=0;et.limit)return s.push("..."),s;s.push(this._decode(t,i+1))}return 0==t.shape.length?s[0]:s}},tengine.TensorType=class{constructor(t,i){switch(t){case 0:this._dataType="float32";break;case 1:this._dataType="float16";break;case 2:this._dataType="int8";break;case 3:this._dataType="uint8";break;case 4:this._dataType="int32";break;case 5:this._dataType="int16";break;default:throw new tengine.Error("Unknown data type'"+t+"'.")}this._shape=i}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},tengine.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},tengine.Metadata=class{static open(t){return tengine.Metadata._metadata?Promise.resolve(tengine.Metadata._metadata):t.request(null,"tengine-metadata.json","utf-8").then((t=>(tengine.Metadata._metadata=new tengine.Metadata(t),tengine.Metadata._metadata))).catch((()=>(tengine.Metadata._metadata=new tengine.Metadata(null),tengine.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const i=JSON.parse(t);if(i)for(const t of i)if(t.name&&t.schema){t.schema.name=t.name;const i=t.name+(t.version&&1!==t.version?":"+t.version.toString():"");this._map[i]=t.schema}}}type(t){return this._map[t]||null}attribute(t,i){let e=this._attributeCache[t];if(!e){e={};const i=this.type(t);if(i&&i.attributes&&i.attributes.length>0)for(const t of i.attributes)e[t.name]=t;this._attributeCache[t]=e}return e[i]||null}},tengine.ModelFileReader=class{constructor(t){const i=new Map,e=(t,e,s,n)=>{i.set(t.toString()+":"+e.toString(),{name:s,params:n})};e(0,1,"Accuracy",[]),e(1,1,"BatchNormalization",["f","f","i"]),e(2,1,"BilinearResize",["f","f","i"]),e(3,1,"Concat",["i"]),e(4,1,"Const",[]),e(5,1,"Convolution",["i","i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(6,1,"DeConvolution",["i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(7,1,"DetectionOutput",["i","i","i","f","f"]),e(8,1,"DropOut",[]),e(9,1,"Eltwise",["i","i"]),e(10,1,"Flatten",["i"]),e(11,1,"FullyConnected",["i"]),e(12,1,"INPUT",[]),e(13,1,"LRN",["i","f","f","i","f"]),e(14,1,"Normalize",["i","i"]),e(15,1,"Permute",["i","i","i","i","i"]),e(16,1,"Pooling",["i","i","i","i","i","i","i","i","i","i","i"]),e(17,1,"Prelu",[]),e(18,1,"PriorBox",["f[]","f[]","f[]","f[]","i","i","i","i","i","f","f","f","i","i"]),e(19,1,"Region",["i","i","i","i","f","f","f[]"]),e(20,1,"ReLU",["f"]),e(21,1,"ReLU6",[]),e(22,1,"Reorg",["i"]),e(23,1,"Reshape",["i","i","i","i","i","i"]),e(23,2,"Reshape",["i","i","i[]"]),e(24,1,"RoiPooling",["i","i","f"]),e(25,1,"RPN",["f[]","f[]","i","i","i","i","i","f","anchors"]),e(26,1,"Scale",["i","i","i"]),e(27,1,"Slice",["i","i[]","i[]","i[]","i","i","i","i","i"]),e(28,1,"SoftMax",["i"]),e(29,1,"Split",["i","i","boolean","boolean","i[]"]),e(30,1,"DetectionPostProcess",["i","i","f","f","i","f[]"]),e(31,1,"Gemm",["f","f","i","i"]),e(32,1,"Generic",["i","i","string"]),e(33,1,"Logistic",[]),e(34,1,"LSTM",["f","f","i","i","i","i","i","i","i","i","i","i","i","i","i","i","i","i"]),e(35,1,"RNN",["f","i","i","i","i","i","i","i","i","i"]),e(36,1,"TanH",[]),e(37,1,"Sigmoid",[]),e(38,1,"Squeeze",["i","i","i","i"]),e(39,1,"FusedbnScaleRelu",[]),e(40,1,"Pad",["i","i","i","i","i","i","i","i","i","f"]),e(41,1,"StridedSlice",["i","i","i","i","i","i","i","i","i","i","i","i"]),e(42,1,"ArgMax",["i"]),e(43,1,"ArgMin",["i"]),e(44,1,"TopKV2",["i","i"]),e(45,1,"Reduction",["i","i","i","i","i","i"]),e(46,1,"Max",[]),e(47,1,"Min",[]),e(48,1,"GRU",["f","i","i","i","i","i","i","i","i","i"]),e(49,1,"Addn","i"),e(50,1,"SwapAxis",["i","i"]),e(51,1,"Upsample",["f"]),e(52,1,"SpaceToBatchND",["i","i","i","i","i","i"]),e(53,1,"BatchToSpaceND",["i","i","i","i","i","i"]),e(54,1,"Resize",["f","f","i"]),e(55,1,"ShuffleChannel",["i"]),e(56,1,"Crop",["i","i","i","i","i","i","boolean","i","i"]),e(57,1,"ROIAlign",["i","i","f"]),e(58,1,"Psroipooling",["i","i","f","i"]),e(59,1,"Unary",["i"]),e(60,1,"Expanddims",["i"]),e(61,1,"Bias",["i"]),e(62,1,"Noop",[]),e(63,1,"Threshold",["f"]),e(64,1,"Hardsigmoid",["f","f"]),e(65,1,"Embed",["f","f","f","f"]),e(66,1,"InstanceNorm",["f"]),e(67,1,"MVN",["i","i","f"]),e(68,1,"Absval",[]),e(69,1,"Cast",["i","i"]),e(70,1,"HardSwish",["f","f"]),e(71,1,"Interp",["i","i","f","f","i"]),e(72,1,"SELU",["f","f"]),e(73,1,"ELU",["f"]),e(74,1,"BroadMul",[]),e(75,1,"Logical",["i"]),e(76,1,"Gather",["i","i"]),e(77,1,"Transpose",["i[]"]),e(78,1,"Comparison",["i"]),e(79,1,"SpaceToDepth",["i"]),e(80,1,"DepthToSpace",["i"]),e(81,1,"Reverse",[]),e(82,1,"SparseToDense",["i","i","i"]),e(83,1,"Ceil",[]),e(84,1,"SquaredDifference",[]),e(85,1,"Round",[]),e(86,1,"ZerosLike",[]),e(87,1,"Clip",["f","f"]),e(88,1,"MatMul",[]),e(89,1,"ReduceL2",["i","i"]),e(90,1,"Unsqueeze",["i[]"]),e(91,1,"Num",[]);const s=new tengine.BinaryReader(t);this._majorVersion=s.uint16(),this._minorVersion=s.uint16(),this._compileVersion=s.uint16(),s.skip(2),s.seek(s.uint32()),this._originalFormat=s.int32(),this._subFormat=s.int32(),this._graphs=[];const n=s.uint32s();for(const t of n){s.seek(t);const e={};e.id=s.int32(),e.graphLayout=s.int32(),e.originalLayout=s.int32(),e.inputs=s.uint32s(),e.outputs=s.uint32s();const n=s.uint32s(),a=s.uint32s(),r=s.uint32s();e.name=s.string(),e.nodes=[],e.tensors=[],this._graphs.push(e);for(const t of n){s.seek(t);const n={};n.id=s.int32(),n.inputs=s.uint32s(),n.outputs=s.uint32s();const a=s.int32();n.name=s.string();const r=s.uint32s();n.dynamicShape=!!s.boolean(),s.seek(a),n.version=s.int32();const o=s.int32(),h=s.uint32(),u=o.toString()+":"+n.version.toString(),p=i.has(u)?i.get(u):null;n.type=p?p.name:o.toString();const c=p?p.params:[];if(n.params=[],h){s.seek(h);for(const t of c)switch("boolean"!==t&&s.align(4),t){case"i":n.params.push(s.int32());break;case"f":n.params.push(s.float32());break;case"i[]":n.params.push(s.int32s());break;case"f[]":n.params.push(s.float32s());break;case"boolean":n.params.push(s.boolean());break;case"string":n.params.push(s.string());break;case"anchors":n.params.push(s.anchors(4));break;default:throw new tengine.Error("Unsupported param type '"+t+"' in '"+n.type+"'.")}}"Slice"===n.type&&(n.params[6]=5==this._originalFormat?n.params[6]:0),n.attributes=[];for(const t of r){s.seek(t);const i=s.string(),e=s.string(),a=s.int32();n.attributes.push({name:i,value:e,type:a})}"Const"!==n.type&&e.nodes.push(n)}const o=[];for(const t of r){s.seek(t);const i=s.uint32();s.seek(s.int32()),o.push(s.bytes(i))}for(const t of a){s.seek(t);const i={};i.id=s.int32(),i.buffer=o[s.int32()],i.dims=s.int32s(),i.name=s.string();const n=s.int32();i.layout=s.int32(),i.type=s.int32(),i.dataType=s.int32(),n&&(s.seek(n),i.quantparams={zeroPoint:s.int32(),scale:s.float32(),width:s.int32()}),e.tensors.push(i)}for(const t of e.nodes)if("Convolution"===t.type)switch(e.graphLayout){case 0:t.params[6]=e.tensors[t.inputs[1]].dims[1];break;case 1:t.params[6]=e.tensors[t.inputs[1]].dims[3]}}}get version(){return this._majorVersion+"."+this._minorVersion}get source(){switch(this._originalFormat){case 0:return"";case 1:return"Tengine";case 2:return"Caffe";case 3:return"ONNX";case 4:return"MXNet";case 5:return"TensorFlow";case 6:return"TensorFlow Lite";case 7:return"Darknet";case 8:return"DLA v"+this._subFormat;default:throw new tengine.Error("Unknown source '"+this._originalFormat.toString()+"'.")}}get graphs(){return this._graphs}},tengine.BinaryReader=class{constructor(t){this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0}seek(t){if(this._position=t,this._position>this._buffer.length)throw new tengine.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}skip(t){if(this._position+=t,this._position>this._buffer.length)throw new tengine.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}align(t){this._position%t!=0&&this.skip(t-this._position%t)}bytes(t){const i=this._position;return this.skip(t),this._buffer.slice(i,this._position)}byte(){return this.skip(1),this._dataView.getUint8(this._position)}boolean(){return 0==this.byte()}uint16(){const t=this._position;return this.skip(2),this._dataView.getUint16(t,!0)}uint32(){const t=this._position;return this.skip(4),this._dataView.getUint32(t,!0)}uint32s(){const t=[],i=this.uint32();if(i){const e=this._position;this.seek(i);const s=this.uint32();for(let i=0;i [nan nan 0. 0.62236255 5.9914584 9.903487 inf]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic cosine of x element-wise."}},{"name":"Add","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"*NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x + y element-wise."}},{"name":"AddManySparseToTensorsMap","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` created by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` created by this op.\nIf blank, the new Operation's unique name is used.","name":"shared_name","type":"string"}],"description":"A `SparseTensor` of rank `R` is represented by three tensors: `sparse_indices`,\n`sparse_values`, and `sparse_shape`, where\n\n```sparse_indices.shape[1] == sparse_shape.shape[0] == R```\n\nAn `N`-minibatch of `SparseTensor` objects is represented as a `SparseTensor`\nhaving a first `sparse_indices` column taking values between `[0, N)`, where\nthe minibatch size `N == sparse_shape[0]`.\n\nThe input `SparseTensor` must have rank `R` greater than 1, and the first\ndimension is treated as the minibatch dimension. Elements of the `SparseTensor`\nmust be sorted in increasing order of this first dimension. The stored\n`SparseTensor` objects pointed to by each row of the output `sparse_handles`\nwill have rank `R-1`.\n\nThe `SparseTensor` values can then be read out as part of a minibatch by passing\nthe given keys as vector elements to `TakeManySparseFromTensorsMap`. To ensure\nthe correct `SparseTensorsMap` is accessed, ensure that the same\n`container` and `shared_name` are passed to that Op. If no `shared_name`\nis provided here, instead use the *name* of the Operation created by calling\n`AddManySparseToTensorsMap` as the `shared_name` passed to\n`TakeManySparseFromTensorsMap`. Ensure the Operations are colocated.","inputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.\n`sparse_indices[:, 0]` must be ordered values in `[0, N)`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.\nThe minibatch size `N == sparse_shape[0]`.","name":"sparse_shape","type":9}],"outputs":[{"description":"1-D. The handles of the `SparseTensor` now stored in the\n`SparseTensorsMap`. Shape: `[N]`.","name":"sparse_handles","type":9}],"summary":"Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles."}},{"name":"AddN","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `variant`.","name":"T","type":"type"}],"description":" Inputs must be of same size and shape.\n\n ```python\n x = [9, 7, 10]\n tf.math.add_n(x) ==> 26\n ```","inputs":[{"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"sum","typeAttr":"T"}],"summary":"Add all input tensors element wise."}},{"name":"AddSparseToTensorsMap","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` created by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` created by this op.\nIf blank, the new Operation's unique name is used.","name":"shared_name","type":"string"}],"description":"A `SparseTensor` is represented by three tensors: `sparse_indices`,\n`sparse_values`, and `sparse_shape`.\n\nThis operator takes the given `SparseTensor` and adds it to a container\nobject (a `SparseTensorsMap`). A unique key within this container is generated\nin the form of an `int64`, and this is the value that is returned.\n\nThe `SparseTensor` can then be read out as part of a minibatch by passing\nthe key as a vector element to `TakeManySparseFromTensorsMap`. To ensure\nthe correct `SparseTensorsMap` is accessed, ensure that the same\n`container` and `shared_name` are passed to that Op. If no `shared_name`\nis provided here, instead use the *name* of the Operation created by calling\n`AddSparseToTensorsMap` as the `shared_name` passed to\n`TakeManySparseFromTensorsMap`. Ensure the Operations are colocated.","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"description":"0-D. The handle of the `SparseTensor` now stored in the\n`SparseTensorsMap`.","name":"sparse_handle","type":9}],"summary":"Add a `SparseTensor` to a `SparseTensorsMap` return its handle."}},{"name":"AddV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x + y element-wise."}},{"name":"AdjustContrast","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"images","typeAttr":"T"},{"name":"contrast_factor","type":1},{"name":"min_value","type":1},{"name":"max_value","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Deprecated. Disallowed in GraphDef version >= 2."}},{"name":"AdjustContrastv2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last 3 dimensions are\ninterpreted as `[height, width, channels]`. The other dimensions only\nrepresent a collection of images, such as `[batch, height, width, channels].`\n\nContrast is adjusted independently for each channel of each image.\n\nFor each channel, the Op first computes the mean of the image pixels in the\nchannel and then adjusts each component of each pixel to\n`(x - mean) * contrast_factor + mean`.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float multiplier for adjusting contrast.","name":"contrast_factor","type":1}],"outputs":[{"description":"The contrast-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the contrast of one or more images."}},{"name":"AdjustHue","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last dimension is\ninterpreted as channels, and must be three.\n\nThe input image is considered in the RGB colorspace. Conceptually, the RGB\ncolors are first mapped into HSV. A delta is then applied all the hue values,\nand then remapped back to RGB colorspace.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float delta to add to the hue.","name":"delta","type":1}],"outputs":[{"description":"The hue-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the hue of one or more images."}},{"name":"AdjustSaturation","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"`images` is a tensor of at least 3 dimensions. The last dimension is\ninterpreted as channels, and must be three.\n\nThe input image is considered in the RGB colorspace. Conceptually, the RGB\ncolors are first mapped into HSV. A scale is then applied all the saturation\nvalues, and then remapped back to RGB colorspace.","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","typeAttr":"T"},{"description":"A float scale to add to the saturation.","name":"scale","type":1}],"outputs":[{"description":"The hue-adjusted image or images.","name":"output","typeAttr":"T"}],"summary":"Adjust the saturation of one or more images."}},{"name":"All","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","type":10},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","type":10}],"summary":"Computes the \"logical and\" of elements across dimensions of a tensor."}},{"name":"AllCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to produce.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"AllToAll","schema":{"attributes":[{"description":"The type of elements to be exchanged. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"description":"The dimension number to concatenate.","name":"concat_dimension","type":"int64"},{"description":"The dimension number to split.","name":"split_dimension","type":"int64"},{"description":"The number of splits, this number must equal to the sub-group\nsize(group_assignment.get_shape()[1])","name":"split_count","type":"int64"}],"description":"On each replica, the input is split into `split_count` blocks along\n`split_dimension` and send to the other replicas given group_assignment. After\nreceiving `split_count` - 1 blocks from other replicas, we concatenate the\nblocks along `concat_dimension` as the output.\n\nFor example, suppose there are 2 TPU replicas:\nreplica 0 receives input: `[[A, B]]`\nreplica 1 receives input: `[[C, D]]`\n\ngroup_assignment=`[[0, 1]]`\nconcat_dimension=0\nsplit_dimension=1\nsplit_count=2\n\nreplica 0's output: `[[A], [C]]`\nreplica 1's output: `[[B], [D]]`","inputs":[{"description":"The local input to the sum.","name":"input","typeAttr":"T"},{"description":"An int32 tensor with shape\n[num_groups, num_replicas_per_group]. `group_assignment[i]` represents the\nreplica ids in the ith subgroup.","name":"group_assignment","type":3}],"outputs":[{"description":"The exchanged result.","name":"output","typeAttr":"T"}],"summary":"An Op to exchange data across TPU replicas."}},{"name":"Angle","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the argument of each element in `input`. All elements in\n`input` must be complex numbers of the form \\\\(a + bj\\\\), where *a*\nis the real part and *b* is the imaginary part.\n\nThe argument returned by this operation is of the form \\\\(atan2(b, a)\\\\).\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.angle(input) ==> [2.0132, 1.056]\n```\n\n@compatibility(numpy)\nEquivalent to np.angle.\n@end_compatibility","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the argument of a complex number."}},{"name":"AnonymousIterator","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\" or\n\"IteratorGetNext\" op. In contrast to Iterator, AnonymousIterator prevents\nresource sharing by name, and does not keep a reference to the resource\ncontainer.","name":"handle","type":20}],"summary":"A container for an iterator resource."}},{"name":"AnonymousIteratorV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\" or\n\"IteratorGetNext\" op. In contrast to Iterator, AnonymousIterator prevents\nresource sharing by name, and does not keep a reference to the resource\ncontainer.","name":"handle","type":20},{"description":"A variant deleter that should be passed into the op that deletes the iterator.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"AnonymousMemoryCache","schema":{"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"AnonymousMultiDeviceIterator","schema":{"attributes":[{"minimum":1,"name":"devices","type":"string[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to a multi device iterator that can be passed to a\n\"MultiDeviceIteratorGetNextFromShard\" op. In contrast to MultiDeviceIterator,\nAnonymousIterator prevents resource sharing by name, and does not keep a\nreference to the resource container.","name":"handle","type":20},{"description":"A variant deleter that should be passed into the op that deletes the iterator.","name":"deleter","type":21}],"summary":"A container for a multi device iterator resource."}},{"name":"AnonymousRandomSeedGenerator","schema":{"inputs":[{"name":"seed","type":9},{"name":"seed2","type":9}],"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"AnonymousSeedGenerator","schema":{"inputs":[{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"reshuffle","type":10}],"outputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"Any","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","type":10},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","type":10}],"summary":"Computes the \"logical or\" of elements across dimensions of a tensor."}},{"name":"ApplyAdaMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nv_t <- max(beta2 * v_{t-1}, abs(g))\nvariable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"v","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AdaMax algorithm."}},{"name":"ApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var, accum and update_accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum = rho() * accum + (1 - rho()) * grad.square();\nupdate = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad;\nupdate_accum = rho() * update_accum + (1 - rho()) * update.square();\nvar -= update;","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum_update","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adadelta scheme."}},{"name":"ApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_accumulator","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_squared_accumulator","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the proximal adagrad scheme."}},{"name":"ApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ApplyAdam","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, uses the nesterov update.","name":"use_nesterov","type":"boolean"}],"description":"$$lr_t := \\text{learning\\_rate} * \\sqrt{1 - beta_2^t} / (1 - beta_1^t)$$\n$$m_t := beta_1 * m_{t-1} + (1 - beta_1) * g$$\n$$v_t := beta_2 * v_{t-1} + (1 - beta_2) * g * g$$\n$$variable := variable - lr_t * m_t / (\\sqrt{v_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"v","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ApplyAddSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- (alpha + sign_decay * sign(g) *sign(m)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\n\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nmg <- rho * mg_{t-1} + (1-rho) * grad\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mg","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"accum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"grad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad * grad\nlinear += grad_with_shrinkage -\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ApplyGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' by subtracting 'alpha' * 'delta' from it."}},{"name":"ApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ApplyPowerSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"m","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"logbase","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum += grad * grad\nprox_v = var - lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' and '*accum' according to FOBOS with Adagrad learning rate."}},{"name":"ApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"prox_v = var - alpha * delta\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ApproximateEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":0.000009999999747378752,"name":"tolerance","type":"float32"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of abs(x-y) < tolerance element-wise."}},{"name":"ArgMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"Note that in case of ties the identity of the return value is not guaranteed.\n\nUsage:\n ```python\n import tensorflow as tf\n a = [1, 10, 26.9, 2.8, 166.32, 62.3]\n b = tf.math.argmax(input = a)\n c = tf.keras.backend.eval(b)\n # c = 4\n # here a[4] = 166.32 which is the largest element of a across axis 0\n ```","inputs":[{"name":"input","typeAttr":"T"},{"description":"int32 or int64, must be in the range `[-rank(input), rank(input))`.\nDescribes which dimension of the input Tensor to reduce across. For vectors,\nuse dimension = 0.","name":"dimension","typeAttr":"Tidx"}],"outputs":[{"name":"output","typeAttr":"output_type"}],"summary":"Returns the index with the largest value across dimensions of a tensor."}},{"name":"ArgMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"Note that in case of ties the identity of the return value is not guaranteed.\n\nUsage:\n ```python\n import tensorflow as tf\n a = [1, 10, 26.9, 2.8, 166.32, 62.3]\n b = tf.math.argmin(input = a)\n c = tf.keras.backend.eval(b)\n # c = 0\n # here a[0] = 1 which is the smallest element of a across axis 0\n ```","inputs":[{"name":"input","typeAttr":"T"},{"description":"int32 or int64, must be in the range `[-rank(input), rank(input))`.\nDescribes which dimension of the input Tensor to reduce across. For vectors,\nuse dimension = 0.","name":"dimension","typeAttr":"Tidx"}],"outputs":[{"name":"output","typeAttr":"output_type"}],"summary":"Returns the index with the smallest value across dimensions of a tensor."}},{"name":"AsString","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `float32`, `float64`, `bool`.","name":"T","type":"type"},{"default":-1,"description":"The post-decimal precision to use for floating point numbers.\nOnly used if precision > -1.","name":"precision","type":"int64"},{"default":false,"description":"Use scientific notation for floating point numbers.","name":"scientific","type":"boolean"},{"default":false,"description":"Use shortest representation (either scientific or standard) for\nfloating point numbers.","name":"shortest","type":"boolean"},{"default":-1,"description":"Pad pre-decimal numbers to this width.\nApplies to both floating point and integer numbers.\nOnly used if width > -1.","name":"width","type":"int64"},{"default":"","description":"The value to pad if width > -1. If empty, pads with spaces.\nAnother typical value is '0'. String cannot be longer than 1 character.","name":"fill","type":"string"}],"description":"Supports many numeric types and boolean.\n\nFor Unicode, see the\n[https://www.tensorflow.org/tutorials/representation/unicode](Working with Unicode text)\ntutorial.\n\nExamples:\n\n>>> tf.strings.as_string([3, 2])\n\n>>> tf.strings.as_string([3.1415926, 2.71828], precision=2).numpy()\narray([b'3.14', b'2.72'], dtype=object)","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":7}],"summary":"Converts each entry in the given tensor to strings."}},{"name":"Asin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The `tf.math.asin` operation returns the inverse of `tf.math.sin`, such that\nif `y = tf.math.sin(x)` then, `x = tf.math.asin(y)`.\n\n**Note**: The output of `tf.math.asin` will lie within the invertible range\nof sine, i.e [-pi/2, pi/2].\n\nFor example:\n\n```python\n# Note: [1.047, 0.785] ~= [(pi/3), (pi/4)]\nx = tf.constant([1.047, 0.785])\ny = tf.math.sin(x) # [0.8659266, 0.7068252]\n\ntf.math.asin(y) # [1.047, 0.785] = x\n```\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the trignometric inverse sine of x element-wise."}},{"name":"Asinh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes inverse hyperbolic sine\n for every element in the tensor. Both input and output has a range of\n `[-inf, inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -2, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.asinh(x) ==> [-inf -1.4436355 -0.4812118 0.8813736 1.0159732 5.991471 9.903487 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic sine of x element-wise."}},{"name":"Assert","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"},{"default":3,"description":"Print this many entries of each tensor.","name":"summarize","type":"int64"}],"description":"If `condition` evaluates to false, print the list of tensors in `data`.\n`summarize` determines how many entries of the tensors to print.","inputs":[{"description":"The condition to evaluate.","name":"condition","type":10},{"description":"The tensors to print out when condition is false.","name":"data","typeListAttr":"T"}],"summary":"Asserts that the given condition is true."}},{"name":"AssertCardinalityDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"cardinality","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"AssertNextDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"This transformation checks whether the camel-case names (i.e. \"FlatMap\", not\n\"flat_map\") of the transformations following this transformation match the list\nof names in the `transformations` argument. If there is a mismatch, the\ntransformation raises an exception.\n\nThe check occurs when iterating over the contents of the dataset, which\nmeans that the check happens *after* any static optimizations are applied\nto the dataset graph.","inputs":[{"description":"A variant tensor representing the input dataset.\n`AssertNextDataset` passes through the outputs of its input dataset.","name":"input_dataset","type":21},{"description":"A `tf.string` vector `tf.Tensor` identifying the transformations that are\nexpected to happen next.","name":"transformations","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"A transformation that asserts which transformations happen next."}},{"name":"Assign","schema":{"attributes":[{"name":"T","type":"type"},{"default":true,"description":"If true, the operation will validate that the shape\nof 'value' matches the shape of the Tensor being assigned to. If false,\n'ref' will take on the shape of 'value'.","name":"validate_shape","type":"boolean"},{"default":true,"description":"If True, the assignment will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"category":"Control","description":"This operation outputs \"ref\" after the assignment is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node. May be uninitialized.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be assigned to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been reset.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by assigning 'value' to it."}},{"name":"AssignAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the addition will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation outputs \"ref\" after the update is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be added to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been updated.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by adding 'value' to it."}},{"name":"AssignAddVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to\nsee the incremented value or a subsequent newer one.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value by which the variable will be incremented.","name":"value","typeAttr":"dtype"}],"summary":"Adds a value to the current value of a variable."}},{"name":"AssignSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation outputs \"ref\" after the update is done.\nThis makes it easier to chain operations that need to use the reset value.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"The value to be subtracted to the variable.","name":"value","typeAttr":"T"}],"outputs":[{"description":"= Same as \"ref\". Returned as a convenience for operations that want\nto use the new value after the variable has been updated.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Update 'ref' by subtracting 'value' from it."}},{"name":"AssignSubVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to\nsee the decremented value or a subsequent newer one.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value by which the variable will be incremented.","name":"value","typeAttr":"dtype"}],"summary":"Subtracts a value from the current value of a variable."}},{"name":"AssignVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"Any ReadVariableOp with a control dependency on this op is guaranteed to return\nthis value or a subsequent newer value of the variable.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20},{"description":"the value to set the new tensor to use.","name":"value","typeAttr":"dtype"}],"summary":"Assigns a new value to a variable."}},{"name":"Atan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The `tf.math.atan` operation returns the inverse of `tf.math.tan`, such that\nif `y = tf.math.tan(x)` then, `x = tf.math.atan(y)`.\n\n**Note**: The output of `tf.math.atan` will lie within the invertible range\nof tan, i.e (-pi/2, pi/2).\n\nFor example:\n\n```python\n# Note: [1.047, 0.785] ~= [(pi/3), (pi/4)]\nx = tf.constant([1.047, 0.785])\ny = tf.math.tan(x) # [1.731261, 0.99920404]\n\ntf.math.atan(y) # [1.047, 0.785] = x\n```\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the trignometric inverse tangent of x element-wise."}},{"name":"Atan2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"This is the angle \\( \\theta \\in [-\\pi, \\pi] \\) such that\n\\[ x = r \\cos(\\theta) \\]\nand\n\\[ y = r \\sin(\\theta) \\]\nwhere \\(r = \\sqrt(x^2 + y^2) \\).","inputs":[{"name":"y","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes arctangent of `y/x` element-wise, respecting signs of the arguments."}},{"name":"Atanh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes inverse hyperbolic tangent\n for every element in the tensor. Input range is `[-1,1]` and output range is\n `[-inf, inf]`. If input is `-1`, output will be `-inf` and if the\n input is `1`, output will be `inf`. Values outside the range will have\n `nan` as output.\n\n ```python\n x = tf.constant([-float(\"inf\"), -1, -0.5, 1, 0, 0.5, 10, float(\"inf\")])\n tf.math.atanh(x) ==> [nan -inf -0.54930615 inf 0. 0.54930615 nan nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes inverse hyperbolic tangent of x element-wise."}},{"name":"AudioSpectrogram","schema":{"attributes":[{"description":"How wide the input window is in samples. For the highest efficiency\nthis should be a power of two, but other values are accepted.","name":"window_size","type":"int64"},{"description":"How widely apart the center of adjacent sample windows should be.","name":"stride","type":"int64"},{"default":false,"description":"Whether to return the squared magnitude or just the\nmagnitude. Using squared magnitude can avoid extra calculations.","name":"magnitude_squared","type":"boolean"}],"description":"Spectrograms are a standard way of representing audio information as a series of\nslices of frequency information, one slice for each window of time. By joining\nthese together into a sequence, they form a distinctive fingerprint of the sound\nover time.\n\nThis op expects to receive audio data as an input, stored as floats in the range\n-1 to 1, together with a window width in samples, and a stride specifying how\nfar to move the window between slices. From this it generates a three\ndimensional output. The first dimension is for the channels in the input, so a\nstereo audio input would have two here for example. The second dimension is time,\nwith successive frequency slices. The third dimension has an amplitude value for\neach frequency during that time slice.\n\nThis means the layout when converted and saved as an image is rotated 90 degrees\nclockwise from a typical spectrogram. Time is descending down the Y axis, and\nthe frequency decreases from left to right.\n\nEach value in the result represents the square root of the sum of the real and\nimaginary parts of an FFT on the current window of samples. In this way, the\nlowest dimension represents the power of each frequency in the current window,\nand adjacent windows are concatenated in the next dimension.\n\nTo get a more intuitive and visual look at what this operation does, you can run\ntensorflow/examples/wav_to_spectrogram to read in an audio file and save out the\nresulting spectrogram as a PNG image.","inputs":[{"description":"Float representation of audio data.","name":"input","type":1}],"outputs":[{"description":"3D representation of the audio frequencies as an image.","name":"spectrogram","type":1}],"summary":"Produces a visualization of audio data over time."}},{"name":"AudioSummary","schema":{"attributes":[{"description":"The sample rate of the signal in hertz.","name":"sample_rate","type":"float32"},{"default":3,"description":"Max number of batch elements to generate audio for.","minimum":1,"name":"max_outputs","type":"int64"}],"description":"The summary has up to `max_outputs` summary values containing audio. The\naudio is built from `tensor` which must be 3-D with shape `[batch_size,\nframes, channels]` or 2-D with shape `[batch_size, frames]`. The values are\nassumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_outputs` is 1, the summary value tag is '*tag*/audio'.\n* If `max_outputs` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"2-D of shape `[batch_size, frames]`.","name":"tensor","type":1}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with audio."}},{"name":"AudioSummaryV2","schema":{"attributes":[{"default":3,"description":"Max number of batch elements to generate audio for.","minimum":1,"name":"max_outputs","type":"int64"}],"description":"The summary has up to `max_outputs` summary values containing audio. The\naudio is built from `tensor` which must be 3-D with shape `[batch_size,\nframes, channels]` or 2-D with shape `[batch_size, frames]`. The values are\nassumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_outputs` is 1, the summary value tag is '*tag*/audio'.\n* If `max_outputs` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"2-D of shape `[batch_size, frames]`.","name":"tensor","type":1},{"description":"The sample rate of the signal in hertz.","name":"sample_rate","type":1}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with audio."}},{"name":"AutoShardDataset","schema":{"attributes":[{"default":0,"name":"auto_shard_policy","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that shards the input dataset by num_workers, returning a\nsharded dataset for the index-th worker. This attempts to automatically shard\na dataset by examining the Dataset graph and inserting a shard op before the\ninputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset).\n\nThis dataset will throw a NotFound error if we cannot shard the dataset\nautomatically.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of workers to distribute this dataset across.","name":"num_workers","type":9},{"description":"A scalar representing the index of the current worker out of num_workers.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shards the input dataset."}},{"name":"AvgPool","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `value`.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of `value`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Pool","description":"Each entry in `output` is the mean of the corresponding size `ksize`\nwindow in `value`.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The average pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs average pooling on the input."}},{"name":"AvgPool3D","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Each entry in `output` is the mean of the corresponding size `ksize` window in\n`value`.","inputs":[{"description":"Shape `[batch, depth, rows, cols, channels]` tensor to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The average pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs 3D average pooling on the input."}},{"name":"AvgPool3DGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input dimensions.","name":"orig_input_shape","type":3},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"The backprop for input.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of average pooling function."}},{"name":"AvgPoolGrad","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of the input.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"1-D. Shape of the original input to `avg_pool`.","name":"orig_input_shape","type":3},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t.\nthe output of `avg_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `avg_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the average pooling function."}},{"name":"BandedTriangularSolve","schema":{"attributes":[{"default":true,"name":"lower","type":"boolean"},{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"Barrier","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. Each shape must be 1 in the\nfirst dimension. The length of this attr must be the same as the length of\ncomponent_types.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The capacity of the barrier. The default capacity is MAX_INT32,\nwhich is the largest capacity of the underlying queue.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this barrier is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this barrier will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"A barrier represents a key-value map, where each key is a string, and\neach value is a tuple of tensors.\n\nAt runtime, the barrier contains 'complete' and 'incomplete'\nelements. A complete element has defined tensors for all components of\nits value tuple, and may be accessed using BarrierTakeMany. An\nincomplete element has some undefined components in its value tuple,\nand may be updated using BarrierInsertMany.","outputs":[{"description":"The handle to the barrier.","isRef":true,"name":"handle","type":7}],"summary":"Defines a barrier that persists across different graph executions."}},{"name":"BarrierClose","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the barrier's queue will be canceled. InsertMany will fail, even\nif no new key is introduced.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more new elements will be inserted in the\ngiven barrier. Subsequent InsertMany that try to introduce a new key will fail.\nSubsequent InsertMany operations that just add missing components to already\nexisting elements will continue to succeed. Subsequent TakeMany operations will\ncontinue to succeed if sufficient completed elements remain in the barrier.\nSubsequent TakeMany operations that would block will fail immediately.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"summary":"Closes the given barrier."}},{"name":"BarrierIncompleteSize","schema":{"inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of incomplete elements (i.e. those with some of their value\ncomponents not set) in the barrier.","name":"size","type":3}],"summary":"Computes the number of incomplete elements in the given barrier."}},{"name":"BarrierInsertMany","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The component of the barrier elements that is being assigned.","name":"component_index","type":"int64"}],"description":"If a key is not found in the barrier, this operation will create a new\nincomplete element. If a key is found in the barrier, and the element\nalready has a value at component_index, this operation will fail with\nINVALID_ARGUMENT, and leave the barrier in an undefined state.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7},{"description":"A one-dimensional tensor of keys, with length n.","name":"keys","type":7},{"description":"An any-dimensional tensor of values, which are associated with the\nrespective keys. The 0th dimension must have length n.","name":"values","typeAttr":"T"}],"summary":"For each key, assigns the respective value to the specified component."}},{"name":"BarrierReadySize","schema":{"inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of complete elements (i.e. those with all of their value\ncomponents set) in the barrier.","name":"size","type":3}],"summary":"Computes the number of complete elements in the given barrier."}},{"name":"BarrierTakeMany","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":false,"description":"Allow to return less than num_elements items if barrier is\nalready closed.","name":"allow_small_batch","type":"boolean"},{"default":false,"name":"wait_for_incomplete","type":"boolean"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation concatenates completed-element component tensors along\nthe 0th dimension to make a single component tensor.\n\nElements come out of the barrier when they are complete, and in the order\nin which they were placed into the barrier. The indices output provides\ninformation about the batch in which each element was originally inserted\ninto the barrier.","inputs":[{"description":"The handle to a barrier.","isRef":true,"name":"handle","type":7},{"description":"A single-element tensor containing the number of elements to\ntake.","name":"num_elements","type":3}],"outputs":[{"description":"A one-dimensional tensor of indices, with length num_elems.\nThese indices refer to the batch in which the values were placed into the\nbarrier (starting with MIN_LONG and increasing with each BarrierInsertMany).","name":"indices","type":9},{"description":"A one-dimensional tensor of keys, with length num_elements.","name":"keys","type":7},{"description":"One any-dimensional tensor per component in a barrier element. All\nvalues have length num_elements in the 0th dimension.","name":"values","typeListAttr":"component_types"}],"summary":"Takes the given number of completed elements from a barrier."}},{"name":"Batch","schema":{"attributes":[{"name":"num_batch_threads","type":"int64"},{"name":"max_batch_size","type":"int64"},{"default":10,"name":"max_enqueued_batches","type":"int64"},{"name":"batch_timeout_micros","type":"int64"},{"default":[],"name":"allowed_batch_sizes","type":"int64[]"},{"name":"grad_timeout_micros","type":"int64"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"default":"","name":"batching_queue","type":"string"},{"minimum":1,"name":"T","type":"type[]"}],"description":"When many instances of this Op are being run concurrently with the same\ncontainer/shared_name in the same device, some will output zero-shaped Tensors\nand others will output Tensors of size up to max_batch_size.\n\nAll Tensors in in_tensors are batched together (so, for example, labels and\nfeatures should be batched with a single instance of this operation.\n\nEach invocation of batch emits an `id` scalar which will be used to identify\nthis particular invocation when doing unbatch or its gradient.\n\nEach op which emits a non-empty batch will also emit a non-empty batch_index\nTensor, which, is a [K, 3] matrix where each row contains the invocation's id,\nstart, and length of elements of each set of Tensors present in batched_tensors.\n\nBatched tensors are concatenated along the first dimension, and all tensors in\nin_tensors must have the first dimension of the same size.\n\nin_tensors: The tensors to be batched.\nnum_batch_threads: Number of scheduling threads for processing batches of work.\n Determines the number of batches processed in parallel.\nmax_batch_size: Batch sizes will never be bigger than this.\nbatch_timeout_micros: Maximum number of microseconds to wait before outputting\n an incomplete batch.\nallowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does\n nothing. Otherwise, supplies a list of batch sizes, causing the op to pad\n batches up to one of those sizes. The entries must increase monotonically, and\n the final entry must equal max_batch_size.\ngrad_timeout_micros: The timeout to use for the gradient. See Unbatch.\nbatched_tensors: Either empty tensors or a batch of concatenated Tensors.\nbatch_index: If out_tensors is non-empty, has information to invert it.\ncontainer: Controls the scope of sharing of this batch.\nid: always contains a scalar with a unique ID for this invocation of Batch.\nshared_name: Concurrently running instances of batch in the same device with the\n same container and shared_name will batch their elements together. If left\n empty, the op name will be used as the shared name.\nT: the types of tensors to be batched.","inputs":[{"name":"in_tensors","typeListAttr":"T"}],"outputs":[{"name":"batched_tensors","typeListAttr":"T"},{"name":"batch_index","type":9},{"name":"id","type":9}],"summary":"Batches all input tensors nondeterministically."}},{"name":"BatchCholesky","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchCholeskyGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"l","typeAttr":"T"},{"name":"grad","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches `batch_size` elements from `input_dataset`."}},{"name":"BatchDatasetV2","schema":{"attributes":[{"default":false,"name":"parallel_copy","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a batch.","name":"batch_size","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches `batch_size` elements from `input_dataset`."}},{"name":"BatchFFT","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFFT2D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFFT3D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchFunction","schema":{"attributes":[{"name":"f","type":"function"},{"description":"Number of scheduling threads for processing batches of work.\nDetermines the number of batches processed in parallel.","name":"num_batch_threads","type":"int64"},{"description":"Batch sizes will never be bigger than this.","name":"max_batch_size","type":"int64"},{"description":"Maximum number of microseconds to wait before outputting\nan incomplete batch.","name":"batch_timeout_micros","type":"int64"},{"default":10,"description":"Maximum number of batches enqueued. Default: 10.","name":"max_enqueued_batches","type":"int64"},{"default":[],"description":"Optional list of allowed batch sizes. If left empty, does\nnothing. Otherwise, supplies a list of batch sizes, causing the op to pad\nbatches up to one of those sizes. The entries must increase monotonically.\nIf enable_large_batch_splitting is false (i.e., large-input-split is not\nenabled) the final entry must equal max_batch_size.","name":"allowed_batch_sizes","type":"int64[]"},{"default":"","description":"Controls the scope of sharing of this batch.","name":"container","type":"string"},{"default":"","description":"Concurrently running instances of batch in the same device with the\nsame container and shared_name will batch their elements together. If left\nempty, the op name will be used as the shared name.","name":"shared_name","type":"string"},{"default":"","name":"batching_queue","type":"string"},{"description":"the types of tensors to be batched.","minimum":1,"name":"Tin","type":"type[]"},{"description":"the types of the captured tensors.","minimum":0,"name":"Tcaptured","type":"type[]"},{"description":"the types of the output tensors.","minimum":1,"name":"Tout","type":"type[]"},{"default":false,"description":"input with a large size (i.e., larger than the largest value of\n`allowed_batch_sizes`) will be splitted into multiple batches with batch size.","name":"enable_large_batch_splitting","type":"boolean"}],"description":"So, for example, in the following code\n\n ```python\n\n # This input will be captured.\n y = tf.placeholder_with_default(1.0, shape=[])\n\n @tf.Defun(tf.float32)\n def computation(a):\n return tf.matmul(a, a) + y\n\n b = gen_batch_ops.batch_function(\n f=computation\n in_tensors=[a],\n captured_tensors=computation.captured_inputs,\n Tout=[o.type for o in computation.definition.signature.output_arg],\n num_batch_threads=1,\n max_batch_size=10,\n batch_timeout_micros=100000, # 100ms\n allowed_batch_sizes=[3, 10],\n batching_queue=\"\")\n\nIf more than one session.run call is simultaneously trying to compute `b`\nthe values of `a` will be gathered, non-deterministically concatenated\nalong the first axis, and only one thread will run the computation.\n\nAssumes that all arguments of the function are Tensors which will be batched\nalong their first dimension.\n\nArguments that are captured, are not batched. The session.run call which does\nthe concatenation, will use the values of the captured tensors available to it.\nTherefore, typical uses of captured tensors should involve values which remain\nunchanged across session.run calls. Inference is a good example of this.\n\nSparseTensor is not supported. The return value of the decorated function\nmust be a Tensor or a list/tuple of Tensors.","inputs":[{"description":"The tensors to be batched.","name":"in_tensors","typeListAttr":"Tin"},{"description":"The tensors which are captured in the function, and don't need\nto be batched.","name":"captured_tensors","typeListAttr":"Tcaptured"}],"outputs":[{"description":"The output tensors.","name":"out_tensors","typeListAttr":"Tout"}],"summary":"Batches all the inputs tensors to the computation done by the function."}},{"name":"BatchIFFT","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchIFFT2D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchIFFT3D","schema":{"inputs":[{"name":"input","type":8}],"outputs":[{"name":"output","type":8}]}},{"name":"BatchMatMul","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":false,"description":"If `True`, adjoint the slices of `x`. Defaults to `False`.","name":"adj_x","type":"boolean"},{"default":false,"description":"If `True`, adjoint the slices of `y`. Defaults to `False`.","name":"adj_y","type":"boolean"}],"description":"Multiplies all slices of `Tensor` `x` and `y` (each slice can be\nviewed as an element of a batch), and arranges the individual results\nin a single output tensor of the same batch size. Each of the\nindividual slices can optionally be adjointed (to adjoint a matrix\nmeans to transpose and conjugate it) before multiplication by setting\nthe `adj_x` or `adj_y` flag to `True`, which are by default `False`.\n\nThe input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]`\nand `[..., r_y, c_y]`.\n\nThe output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where:\n\n r_o = c_x if adj_x else r_x\n c_o = r_y if adj_y else c_y\n\nIt is computed as:\n\n output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :])","inputs":[{"description":"2-D or higher with shape `[..., r_x, c_x]`.","name":"x","typeAttr":"T"},{"description":"2-D or higher with shape `[..., r_y, c_y]`.","name":"y","typeAttr":"T"}],"outputs":[{"description":"3-D or higher with shape `[..., r_o, c_o]`","name":"output","typeAttr":"T"}],"summary":"Multiplies slices of two tensors in batches."}},{"name":"BatchMatMulV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":false,"description":"If `True`, adjoint the slices of `x`. Defaults to `False`.","name":"adj_x","type":"boolean"},{"default":false,"description":"If `True`, adjoint the slices of `y`. Defaults to `False`.","name":"adj_y","type":"boolean"}],"description":"Multiplies all slices of `Tensor` `x` and `y` (each slice can be\nviewed as an element of a batch), and arranges the individual results\nin a single output tensor of the same batch size. Each of the\nindividual slices can optionally be adjointed (to adjoint a matrix\nmeans to transpose and conjugate it) before multiplication by setting\nthe `adj_x` or `adj_y` flag to `True`, which are by default `False`.\n\nThe input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]`\nand `[..., r_y, c_y]`.\n\nThe output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where:\n\n r_o = c_x if adj_x else r_x\n c_o = r_y if adj_y else c_y\n\nIt is computed as:\n\n output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :])\n\n*NOTE*: `BatchMatMulV2` supports broadcasting in the batch dimensions. More\nabout broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).\n","inputs":[{"description":"2-D or higher with shape `[..., r_x, c_x]`.","name":"x","typeAttr":"T"},{"description":"2-D or higher with shape `[..., r_y, c_y]`.","name":"y","typeAttr":"T"}],"outputs":[{"description":"3-D or higher with shape `[..., r_o, c_o]`","name":"output","typeAttr":"T"}],"summary":"Multiplies slices of two tensors in batches."}},{"name":"BatchMatrixBandPart","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"},{"name":"num_lower","type":9},{"name":"num_upper","type":9}],"outputs":[{"name":"band","typeAttr":"T"}]}},{"name":"BatchMatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixDiag","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixDiagPart","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"diagonal","typeAttr":"T"}]}},{"name":"BatchMatrixInverse","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSetDiag","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"},{"name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSolve","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixSolveLs","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"},{"default":true,"name":"fast","type":"boolean"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"},{"name":"l2_regularizer","type":2}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchMatrixTriangularSolve","schema":{"attributes":[{"default":true,"name":"lower","type":"boolean"},{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"matrix","typeAttr":"T"},{"name":"rhs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchNormWithGlobalNormalization","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"category":"Normalization","description":"This op is deprecated. Prefer `tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"T"},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"T"},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"T"},{"description":"A 1D beta Tensor with size matching the last dimension of t.\nAn offset to be added to the normalized tensor.","name":"beta","typeAttr":"T"},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this tensor will be multiplied\nwith the normalized tensor.","name":"gamma","typeAttr":"T"}],"outputs":[{"name":"result","typeAttr":"T"}],"summary":"Batch normalization."}},{"name":"BatchNormWithGlobalNormalizationGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"description":"This op is deprecated. See `tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"T"},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"T"},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"T"},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this Tensor will be multiplied\nwith the normalized Tensor.","name":"gamma","typeAttr":"T"},{"description":"4D backprop Tensor.","name":"backprop","typeAttr":"T"}],"outputs":[{"description":"4D backprop tensor for input.","name":"dx","typeAttr":"T"},{"description":"1D backprop tensor for mean.","name":"dm","typeAttr":"T"},{"description":"1D backprop tensor for variance.","name":"dv","typeAttr":"T"},{"description":"1D backprop tensor for beta.","name":"db","typeAttr":"T"},{"description":"1D backprop tensor for gamma.","name":"dg","typeAttr":"T"}],"summary":"Gradients for batch normalization."}},{"name":"BatchSelfAdjointEig","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"BatchSelfAdjointEigV2","schema":{"attributes":[{"default":true,"name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"e","typeAttr":"T"},{"name":"v","typeAttr":"T"}]}},{"name":"BatchSvd","schema":{"attributes":[{"default":true,"name":"compute_uv","type":"boolean"},{"default":false,"name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"s","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"v","typeAttr":"T"}]}},{"name":"BatchToSpace","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":2,"name":"block_size","type":"int64"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"This is a legacy version of the more general BatchToSpaceND.\n\nRearranges (permutes) data from batch into blocks of spatial data, followed by\ncropping. This is the reverse transformation of SpaceToBatch. More specifically,\nthis op outputs a copy of the input tensor where values from the `batch`\ndimension are moved in spatial blocks to the `height` and `width` dimensions,\nfollowed by cropping along the `height` and `width` dimensions.","inputs":[{"description":"4-D tensor with shape\n`[batch*block_size*block_size, height_pad/block_size, width_pad/block_size,\n depth]`. Note that the batch size of the input tensor must be divisible by\n`block_size * block_size`.","name":"input","typeAttr":"T"},{"description":"2-D tensor of non-negative integers with shape `[2, 2]`. It specifies\nhow many elements to crop from the intermediate result across the spatial\ndimensions as follows:\n\n crops = [[crop_top, crop_bottom], [crop_left, crop_right]]","name":"crops","typeAttr":"Tidx"}],"outputs":[{"description":"4-D with shape `[batch, height, width, depth]`, where:\n\n height = height_pad - crop_top - crop_bottom\n width = width_pad - crop_left - crop_right\n\nThe attr `block_size` must be greater than one. It indicates the block size.\n\nSome examples:\n\n(1) For the following input of shape `[4, 1, 1, 1]` and block_size of 2:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\n(2) For the following input of shape `[4, 1, 1, 3]` and block_size of 2:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 3]` and value:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[4, 2, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\nThe output tensor has shape `[1, 4, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\n(4) For the following input of shape `[8, 1, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],\n [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]\n```\n\nThe output tensor has shape `[2, 2, 4, 1]` and value:\n\n```\nx = [[[[1], [3]], [[5], [7]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```","name":"output","typeAttr":"T"}],"summary":"BatchToSpace for 4-D tensors of type T."}},{"name":"BatchToSpaceND","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tblock_shape","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tcrops","type":"type"}],"description":"This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of shape\n`block_shape + [batch]`, interleaves these blocks back into the grid defined by\nthe spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as\nthe input. The spatial dimensions of this intermediate result are then\noptionally cropped according to `crops` to produce the output. This is the\nreverse of SpaceToBatch. See below for a precise description.","inputs":[{"description":"N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`,\nwhere spatial_shape has M dimensions.","name":"input","typeAttr":"T"},{"description":"1-D with shape `[M]`, all values must be >= 1.","name":"block_shape","typeAttr":"Tblock_shape"},{"description":"2-D with shape `[M, 2]`, all values must be >= 0.\n `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input\n dimension `i + 1`, which corresponds to spatial dimension `i`. It is\n required that\n `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`.\n\nThis operation is equivalent to the following steps:\n\n1. Reshape `input` to `reshaped` of shape:\n [block_shape[0], ..., block_shape[M-1],\n batch / prod(block_shape),\n input_shape[1], ..., input_shape[N-1]]\n\n2. Permute dimensions of `reshaped` to produce `permuted` of shape\n [batch / prod(block_shape),\n\n input_shape[1], block_shape[0],\n ...,\n input_shape[M], block_shape[M-1],\n\n input_shape[M+1], ..., input_shape[N-1]]\n\n3. Reshape `permuted` to produce `reshaped_permuted` of shape\n [batch / prod(block_shape),\n\n input_shape[1] * block_shape[0],\n ...,\n input_shape[M] * block_shape[M-1],\n\n input_shape[M+1],\n ...,\n input_shape[N-1]]\n\n4. Crop the start and end of dimensions `[1, ..., M]` of\n `reshaped_permuted` according to `crops` to produce the output of shape:\n [batch / prod(block_shape),\n\n input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1],\n ...,\n input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1],\n\n input_shape[M+1], ..., input_shape[N-1]]\n\nSome examples:\n\n(1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\n(2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\nThe output tensor has shape `[1, 2, 2, 3]` and value:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\nThe output tensor has shape `[1, 4, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\n(4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and\n `crops = [[0, 0], [2, 0]]`:\n\n```\nx = [[[[0], [1], [3]]], [[[0], [9], [11]]],\n [[[0], [2], [4]]], [[[0], [10], [12]]],\n [[[0], [5], [7]]], [[[0], [13], [15]]],\n [[[0], [6], [8]]], [[[0], [14], [16]]]]\n```\n\nThe output tensor has shape `[2, 2, 4, 1]` and value:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```","name":"crops","typeAttr":"Tcrops"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"BatchToSpace for N-D tensors of type T."}},{"name":"BesselI0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI0e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselI1e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselJ0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselJ1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK0e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselK1e","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselY0","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"BesselY1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Betainc","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The regularized incomplete beta integral is defined as:\n\n\n\\\\(I_x(a, b) = \\frac{B(x; a, b)}{B(a, b)}\\\\)\n\nwhere\n\n\n\\\\(B(x; a, b) = \\int_0^x t^{a-1} (1 - t)^{b-1} dt\\\\)\n\n\nis the incomplete beta function and \\\\(B(a, b)\\\\) is the *complete*\nbeta function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"b","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the regularized incomplete beta integral \\\\(I_x(a, b)\\\\)."}},{"name":"BiasAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the bias tensor will be added to the last dimension\nof the value tensor.\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\nThe tensor will be added to \"in_channels\", the third-to-the-last\n dimension. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"}],"category":"Layer","description":"This is a special case of `tf.add` where `bias` is restricted to be 1-D.\nBroadcasting is supported, so `value` may have any number of dimensions.","inputs":[{"description":"Any number of dimensions.","name":"value","typeAttr":"T"},{"description":"1-D with size the last dimension of `value`.","name":"bias","typeAttr":"T"}],"outputs":[{"description":"Broadcasted sum of `value` and `bias`.","name":"output","typeAttr":"T"}],"summary":"Adds `bias` to `value`."}},{"name":"BiasAddGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the bias tensor will be added to the last dimension\nof the value tensor.\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\nThe tensor will be added to \"in_channels\", the third-to-the-last\n dimension. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"}],"description":"It accumulates all the values from out_backprop into the feature dimension.\nFor NHWC data format, the feature dimension is the last. For NCHW data format,\nthe feature dimension is the third-to-last.","inputs":[{"description":"Any number of dimensions.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"1-D with size the feature dimension of `out_backprop`.","name":"output","typeAttr":"T"}],"summary":"The backward operation for \"BiasAdd\" on the \"bias\" tensor."}},{"name":"BiasAddV1","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This is a deprecated version of BiasAdd and will be soon removed.\n\nThis is a special case of `tf.add` where `bias` is restricted to be 1-D.\nBroadcasting is supported, so `value` may have any number of dimensions.","inputs":[{"description":"Any number of dimensions.","name":"value","typeAttr":"T"},{"description":"1-D with size the last dimension of `value`.","name":"bias","typeAttr":"T"}],"outputs":[{"description":"Broadcasted sum of `value` and `bias`.","name":"output","typeAttr":"T"}],"summary":"Adds `bias` to `value`."}},{"name":"Bincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"int32 `Tensor`.","name":"arr","type":3},{"description":"non-negative int32 scalar `Tensor`.","name":"size","type":3},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size`. The counts or summed weights for\neach value in the range [0, size).","name":"bins","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"Bitcast","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`.","name":"T","type":"type"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`.","name":"type","type":"type"}],"description":"Given a tensor `input`, this operation returns a tensor that has the same buffer\ndata as `input` with datatype `type`.\n\nIf the input datatype `T` is larger than the output datatype `type` then the\nshape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)].\n\nIf `T` is smaller than `type`, the operator requires that the rightmost\ndimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from\n[..., sizeof(`type`)/sizeof(`T`)] to [...].\n\ntf.bitcast() and tf.cast() work differently when real dtype is casted as a complex dtype\n(e.g. tf.complex64 or tf.complex128) as tf.cast() make imaginary part 0 while tf.bitcast()\ngives module error.\nFor example,\n\nExample 1:\n\n>>> a = [1., 2., 3.]\n>>> equality_bitcast = tf.bitcast(a, tf.complex128)\nTraceback (most recent call last):\n...\nInvalidArgumentError: Cannot bitcast from 1 to 18 [Op:Bitcast]\n>>> equality_cast = tf.cast(a, tf.complex128)\n>>> print(equality_cast)\ntf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128)\n\nExample 2:\n\n>>> tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8)\n\n\nExample 3:\n\n>>> x = [1., 2., 3.]\n>>> y = [0., 2., 3.]\n>>> equality= tf.equal(x,y)\n>>> equality_cast = tf.cast(equality,tf.float32)\n>>> equality_bitcast = tf.bitcast(equality_cast,tf.uint8)\n>>> print(equality)\ntf.Tensor([False True True], shape=(3,), dtype=bool)\n>>> print(equality_cast)\ntf.Tensor([0. 1. 1.], shape=(3,), dtype=float32)\n>>> print(equality_bitcast)\ntf.Tensor(\n [[ 0 0 0 0]\n [ 0 0 128 63]\n [ 0 0 128 63]], shape=(3, 4), dtype=uint8)\n\n*NOTE*: Bitcast is implemented as a low-level cast, so machines with different\nendian orderings will give different results.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"type"}],"summary":"Bitcasts a tensor from one type to another without copying data."}},{"name":"BitwiseAnd","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are set in both `x` and `y`. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([0, 0, 3, 10], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_and(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise AND of `x` and `y`."}},{"name":"BitwiseOr","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are set in `x`, `y` or both. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([5, 5, 7, 15], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_or(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise OR of `x` and `y`."}},{"name":"BitwiseXor","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The result will have those bits set, that are different in `x` and `y`. The\ncomputation is performed on the underlying representations of `x` and `y`.\n\nFor example:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64,\n tf.uint8, tf.uint16, tf.uint32, tf.uint64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([0, 5, 3, 14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n exp = tf.constant([5, 5, 4, 5], dtype=tf.float32)\n\n res = bitwise_ops.bitwise_xor(lhs, rhs)\n tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE\n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise XOR of `x` and `y`."}},{"name":"BlockLSTM","schema":{"attributes":[{"default":1,"description":"The forget gate bias.","name":"forget_bias","type":"float32"},{"default":3,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This is equivalent to applying LSTMBlockCell in a loop, like so:\n\n```python\nfor x1 in unpack(x):\n i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock(\n x1, cs_prev, h_prev, w, wci, wcf, wco, b)\n cs_prev = cs1\n h_prev = h1\n i.append(i1)\n cs.append(cs1)\n f.append(f1)\n o.append(o1)\n ci.append(ci1)\n co.append(co1)\n h.append(h1)\nreturn pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h)\n```","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for all the time steps."}},{"name":"BlockLSTMGrad","schema":{"attributes":[{"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of LSTMBlock.","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of x to be back-propped.","name":"x_grad","typeAttr":"T"},{"description":"The gradient of cs_prev to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The gradient of h_prev to be back-propped.","name":"h_prev_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"w_grad","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"b_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for the entire time sequence."}},{"name":"BlockLSTMGradV2","schema":{"attributes":[{"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of BlockLSTMV2.","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of x to be back-propped.","name":"x_grad","typeAttr":"T"},{"description":"The gradient of cs_prev to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The gradient of h_prev to be back-propped.","name":"h_prev_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"w_grad","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"},{"description":"The gradient for w to be back-propped.","name":"b_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for the entire time sequence."}},{"name":"BlockLSTMV2","schema":{"attributes":[{"default":0,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This is equivalent to applying LSTMBlockCell in a loop, like so:\n\n```python\nfor x1 in unpack(x):\n i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock(\n x1, cs_prev, h_prev, w, wci, wcf, wco, b)\n cs_prev = cs1\n h_prev = h1\n i.append(i1)\n cs.append(cs1)\n f.append(f1)\n o.append(o1)\n ci.append(ci1)\n co.append(co1)\n h.append(h1)\nreturn pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h)\n\nNote that unlike LSTMBlockCell (and BlockLSTM) which uses ICFO gate layout,\nthis op uses IFCO. So in order for the following snippet to be equivalent\nall gate-related outputs should be reordered.\n```","inputs":[{"description":"Maximum time length actually used by this input. Outputs are padded\nwith zeros beyond this length.","name":"seq_len_max","type":9},{"description":"The sequence input to the LSTM, shape (timelen, batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the initial cell state.","name":"cs_prev","typeAttr":"T"},{"description":"Initial output of cell (to be used for peephole).","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate over the whole time sequence.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh over the whole time sequence.","name":"cs","typeAttr":"T"},{"description":"The forget gate over the whole time sequence.","name":"f","typeAttr":"T"},{"description":"The output gate over the whole time sequence.","name":"o","typeAttr":"T"},{"description":"The cell input over the whole time sequence.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh over the whole time sequence.","name":"co","typeAttr":"T"},{"description":"The output h vector over the whole time sequence.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for all the time steps."}},{"name":"BoostedTreesAggregateStats","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated for each node, feature dimension id and bucket.","inputs":[{"description":"int32; Rank 1 Tensor containing node ids for each example, shape [batch_size].","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example.","name":"hessians","type":1},{"description":"int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]).","name":"feature","type":3}],"outputs":[{"description":"output Rank 4 Tensor (shape=[splits, feature_dimension, buckets, logits_dimension + hessian_dimension])\ncontaining accumulated stats for each node, feature dimension and bucket.","name":"stats_summary","type":1}],"summary":"Aggregates the summary of accumulated stats for the batch."}},{"name":"BoostedTreesBucketize","schema":{"attributes":[{"description":"inferred int; number of features.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that returns a list of float tensors, where each tensor represents the\nbucketized values for a single feature.","inputs":[{"description":"float; List of Rank 1 Tensor each containing float values for a single feature.","name":"float_values","numberAttr":"num_features","type":1},{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a single\nfeature.","name":"bucket_boundaries","numberAttr":"num_features","type":1}],"outputs":[{"description":"int; List of Rank 1 Tensors each containing the bucketized values for a single feature.","name":"buckets","numberAttr":"num_features","type":3}],"summary":"Bucketize each feature based on bucket boundaries."}},{"name":"BoostedTreesCalculateBestFeatureSplit","schema":{"attributes":[{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"},{"default":"inequality","description":"A string indicating if this Op should perform inequality split or equality split. Must be one of the following: `inequality`, `equality`.","name":"split_type","type":"string"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature.\nThe first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summary","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids","type":3},{"description":"A Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains","type":1},{"description":"A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds","type":3},{"description":"A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesCalculateBestFeatureSplitV2","schema":{"attributes":[{"description":"inferred from the size of `stats_summary_list`; the number of total features.","minimum":1,"name":"num_features","type":"int64"},{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A list of Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature.\nThe first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summaries_list","numberAttr":"num_features","type":1},{"description":"A Rank 1 tensor indicating if this Op should perform inequality split or equality split per feature.","name":"split_types","type":7},{"description":"Rank 1 tensor with ids for each feature. This is the real id of the feature.","name":"candidate_feature_ids","type":3},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids","type":3},{"description":"A Rank 1 tensor indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains","type":1},{"description":"A Rank 1 tensors indicating the best feature id for each node. See above for details like shapes and sizes.","name":"feature_ids","type":3},{"description":"A Rank 1 tensors indicating the best feature dimension for each feature to split for certain nodes if the feature is multi-dimension. See above for details like shapes and sizes.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds","type":3},{"description":"A Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensors indicating the which direction to go if data is missing. See above for details like shapes and sizes.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for each node. However, if no split is found, then no split information is returned for that node."}},{"name":"BoostedTreesCalculateBestGainsPerFeature","schema":{"attributes":[{"description":"the number of nodes that can be split in the whole tree. Used as a dimension of output tensors.","minimum":1,"name":"max_splits","type":"int64"},{"description":"inferred from the size of `stats_summary_list`; the number of total features.","minimum":1,"name":"num_features","type":"int64"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe length of output lists are all of the same length, `num_features`.\nThe output shapes are compatible in a way that the first dimension of all tensors of all lists are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used.","name":"stats_summary_list","numberAttr":"num_features","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"An output list of Rank 1 tensors indicating possible split node ids for each feature. The length of the list is num_features, but each tensor has different size as each feature provides different possible nodes. See above for details like shapes and sizes.","name":"node_ids_list","numberAttr":"num_features","type":3},{"description":"An output list of Rank 1 tensors indicating the best gains for each feature to split for certain nodes. See above for details like shapes and sizes.","name":"gains_list","numberAttr":"num_features","type":1},{"description":"An output list of Rank 1 tensors indicating the bucket id to compare with (as a threshold) for split in each node. See above for details like shapes and sizes.","name":"thresholds_list","numberAttr":"num_features","type":3},{"description":"A list of Rank 2 tensors indicating the contribution of the left nodes when branching from parent nodes (given by the tensor element in the output node_ids_list) to the left direction by the given threshold for each feature. This value will be used to make the left node value by adding to the parent node value. Second dimension size is 1 for 1-dimensional logits, but would be larger for multi-class problems. See above for details like shapes and sizes.","name":"left_node_contribs_list","numberAttr":"num_features","type":1},{"description":"A list of Rank 2 tensors, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs_list","numberAttr":"num_features","type":1}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesCenterBias","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20},{"description":"A tensor with shape=[logits_dimension] with mean of gradients for a first node.","name":"mean_gradients","type":1},{"description":"A tensor with shape=[logits_dimension] mean of hessians for a first node.","name":"mean_hessians","type":1},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1}],"outputs":[{"description":"Bool, whether to continue bias centering.","name":"continue_centering","type":10}],"summary":"Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering."}},{"name":"BoostedTreesCreateEnsemble","schema":{"inputs":[{"description":"Handle to the tree ensemble resource to be created.","name":"tree_ensemble_handle","type":20},{"description":"Token to use as the initial value of the resource stamp.","name":"stamp_token","type":9},{"description":"Serialized proto of the tree ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Creates a tree ensemble model and returns a handle to it."}},{"name":"BoostedTreesCreateQuantileStreamResource","schema":{"attributes":[{"default":1099511627776,"description":"int; The maximum number of data points that can be fed to the stream.","name":"max_elements","type":"int64"}],"inputs":[{"description":"resource; Handle to quantile stream resource.","name":"quantile_stream_resource_handle","type":20},{"description":"float; The required approximation error of the stream resource.","name":"epsilon","type":1},{"description":"int; The number of streams managed by the resource that shares the same epsilon.","name":"num_streams","type":9}],"summary":"Create the Resource for Quantile Streams."}},{"name":"BoostedTreesDeserializeEnsemble","schema":{"description":"ensemble.","inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20},{"description":"Token to use as the new value of the resource stamp.","name":"stamp_token","type":9},{"description":"Serialized proto of the ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Deserializes a serialized tree ensemble config and replaces current tree"}},{"name":"BoostedTreesEnsembleResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a BoostedTreesEnsembleResource"}},{"name":"BoostedTreesExampleDebugOutputs","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for constructing the protos in\nexamples_debug_outputs_serialized.","name":"logits_dimension","type":"int64"}],"description":"It traverses all the trees and computes debug metrics for individual examples,\nsuch as getting split feature ids and logits after each split along the decision\npath used to compute directional feature contributions.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Output rank 1 Tensor containing a proto serialized as a string for each example.","name":"examples_debug_outputs_serialized","type":7}],"summary":"Debugging/model interpretability outputs for each example."}},{"name":"BoostedTreesFlushQuantileSummaries","schema":{"attributes":[{"minimum":0,"name":"num_features","type":"int64"}],"description":"An op that outputs a list of quantile summaries of a quantile stream resource.\nEach summary Tensor is rank 2, containing summaries (value, weight, min_rank,\nmax_rank) for a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"name":"summaries","numberAttr":"num_features","type":1}],"summary":"Flush the quantile summaries from each quantile stream resource."}},{"name":"BoostedTreesGetEnsembleStates","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"Stamp token of the tree ensemble resource.","name":"stamp_token","type":9},{"description":"The number of trees in the tree ensemble resource.","name":"num_trees","type":3},{"description":"The number of trees that were finished successfully.","name":"num_finalized_trees","type":3},{"description":"The number of layers we attempted to build (but not necessarily succeeded).","name":"num_attempted_layers","type":3},{"description":"Rank size 2 tensor that contains start and end ids of the nodes in the latest\nlayer.","name":"last_layer_nodes_range","type":3}],"summary":"Retrieves the tree ensemble resource stamp token, number of trees and growing statistics."}},{"name":"BoostedTreesMakeQuantileSummaries","schema":{"attributes":[{"description":"int; Inferred from the size of float_values.\nThe number of float features.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that takes a list of tensors (one tensor per feature) and outputs the\nquantile summaries for each tensor.","inputs":[{"description":"float; List of Rank 1 Tensors each containing values for a single feature.","name":"float_values","numberAttr":"num_features","type":1},{"description":"float; Rank 1 Tensor with weights per instance.","name":"example_weights","type":1},{"description":"float; The required maximum approximation error.","name":"epsilon","type":1}],"outputs":[{"description":"float; List of Rank 2 Tensors each containing the quantile summary\n(value, weight, min_rank, max_rank) of a single feature.","name":"summaries","numberAttr":"num_features","type":1}],"summary":"Makes the summary of quantiles for the batch."}},{"name":"BoostedTreesMakeStatsSummary","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature.","minimum":1,"name":"num_buckets","type":"int64"},{"description":"int; inferred from the size of bucketized_features_list; the number of features.","minimum":1,"name":"num_features","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated into the corresponding node and bucket for each example.","inputs":[{"description":"int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer.","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians.","name":"hessians","type":1},{"description":"int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column).","name":"bucketized_features_list","numberAttr":"num_features","type":3}],"outputs":[{"description":"output Rank 4 Tensor (shape=[#features, #splits, #buckets, 2]) containing accumulated stats put into the corresponding node and bucket. The first index of 4th dimension refers to gradients, and the second to hessians.","name":"stats_summary","type":1}],"summary":"Makes the summary of accumulated stats for the batch."}},{"name":"BoostedTreesPredict","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for partial logits\nshape.","name":"logits_dimension","type":"int64"}],"description":"computes the logits. It is designed to be used during prediction.\nIt traverses all the trees and calculates the final score for each instance.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Output rank 2 Tensor containing logits for each example.","name":"logits","type":1}],"summary":"Runs multiple additive regression ensemble predictors on input instances and"}},{"name":"BoostedTreesQuantileStreamResourceAddSummaries","schema":{"attributes":[{"minimum":0,"name":"num_features","type":"int64"}],"description":"An op that adds a list of quantile summaries to a quantile stream resource. Each\nsummary Tensor is rank 2, containing summaries (value, weight, min_rank, max_rank)\nfor a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"string; List of Rank 2 Tensor each containing the summaries for a single feature.","name":"summaries","numberAttr":"num_features","type":1}],"summary":"Add the quantile summaries to each quantile stream resource."}},{"name":"BoostedTreesQuantileStreamResourceDeserialize","schema":{"attributes":[{"description":"inferred int; number of features to get bucket boundaries for.","minimum":1,"name":"num_streams","type":"int64"}],"description":"An op that deserializes bucket boundaries and are boundaries ready flag into current QuantileAccumulator.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a feature.","name":"bucket_boundaries","numberAttr":"num_streams","type":1}],"summary":"Deserialize bucket boundaries and ready flag into current QuantileAccumulator."}},{"name":"BoostedTreesQuantileStreamResourceFlush","schema":{"attributes":[{"default":false,"description":"bool; If True, the output will be the num_quantiles for each stream where the ith\nentry is the ith quantile of the input with an approximation error of epsilon.\nDuplicate values may be present.\nIf False, the output will be the points in the histogram that we got which roughly\ntranslates to 1/epsilon boundaries and without any duplicates.\nDefault to False.","name":"generate_quantiles","type":"boolean"}],"description":"An op that flushes the summaries for a quantile stream resource.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20},{"description":"int; approximate number of buckets unless using generate_quantiles.","name":"num_buckets","type":9}],"summary":"Flush the summaries for a quantile stream resource."}},{"name":"BoostedTreesQuantileStreamResourceGetBucketBoundaries","schema":{"attributes":[{"description":"inferred int; number of features to get bucket boundaries for.","minimum":0,"name":"num_features","type":"int64"}],"description":"An op that returns a list of float tensors for a quantile stream resource. Each\ntensor is Rank 1 containing bucket boundaries for a single feature.","inputs":[{"description":"resource handle referring to a QuantileStreamResource.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"description":"float; List of Rank 1 Tensors each containing the bucket boundaries for a feature.","name":"bucket_boundaries","numberAttr":"num_features","type":1}],"summary":"Generate the bucket boundaries for each feature based on accumulated summaries."}},{"name":"BoostedTreesQuantileStreamResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a BoostedTreesQuantileStreamResource."}},{"name":"BoostedTreesSerializeEnsemble","schema":{"inputs":[{"description":"Handle to the tree ensemble.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"Stamp token of the tree ensemble resource.","name":"stamp_token","type":9},{"description":"Serialized proto of the ensemble.","name":"tree_ensemble_serialized","type":7}],"summary":"Serializes the tree ensemble to a proto."}},{"name":"BoostedTreesSparseAggregateStats","schema":{"attributes":[{"description":"int; the maximum number of splits possible in the whole tree.","minimum":1,"name":"max_splits","type":"int64"},{"description":"int; equals to the maximum possible value of bucketized feature + 1.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The summary stats contains gradients and hessians accumulated for each node, bucket and dimension id.","inputs":[{"description":"int32; Rank 1 Tensor containing node ids for each example, shape [batch_size].","name":"node_ids","type":3},{"description":"float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example.","name":"gradients","type":1},{"description":"float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example.","name":"hessians","type":1},{"description":"int32; Rank 2 indices of feature sparse Tensors (shape=[number of sparse entries, 2]).\nNumber of sparse entries across all instances from the batch. The first value is\nthe index of the instance, the second is dimension of the feature. The second axis\ncan only have 2 values, i.e., the input dense version of Tensor can only be matrix.","name":"feature_indices","type":3},{"description":"int32; Rank 1 values of feature sparse Tensors (shape=[number of sparse entries]).\nNumber of sparse entries across all instances from the batch. The first value is\nthe index of the instance, the second is dimension of the feature.","name":"feature_values","type":3},{"description":"int32; Rank 1 dense shape of feature sparse Tensors (shape=[2]).\nThe first axis can only have 2 values, [batch_size, feature_dimension].","name":"feature_shape","type":3}],"outputs":[{"description":"int32; Rank 2 indices of summary sparse Tensors (shape=[number of non zero statistics, 4])\nThe second axis can only be 4 including node id, feature dimension, bucket id, and statistics_dimension.\nstatistics_dimension = logits_dimension + hessian_dimension.","name":"stats_summary_indices","type":3},{"description":"output Rank 1 Tensor (shape=[number of non zero statistics])","name":"stats_summary_values","type":1},{"description":"output Rank 1 Tensor (shape=[4])\nThe tensor has following 4 values: [max_splits, feature_dimension, num_buckets, statistics_dimension],\nwhere statistics_dimension = gradient_dimension + hessian_dimension. gradient_dimension\nis the same as label_dimension, i.e., the output space. hessian_dimension can be the same\nas logits dimension when diagonal hessian is used, or label_dimension^2 when full\nhessian is used.","name":"stats_summary_shape","type":3}],"summary":"Aggregates the summary of accumulated stats for the batch."}},{"name":"BoostedTreesSparseCalculateBestFeatureSplit","schema":{"attributes":[{"description":"The dimension of logit, i.e., number of classes.","minimum":1,"name":"logits_dimension","type":"int64"},{"default":"inequality","description":"A string indicating if this Op should perform inequality split or equality split. Must be one of the following: `inequality`.","name":"split_type","type":"string"}],"description":"The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.\n\nIt is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split.\n\nIn this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features).\n\nThe output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature.","inputs":[{"description":"A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive).","name":"node_id_range","type":3},{"description":"A Rank 2 int64 tensor of dense shape [N, 4] (N specifies the number of non-zero values) for accumulated stats summary (gradient/hessian) per node per bucket for each feature. The second dimension contains node id, feature dimension, bucket id, and stats dim.\nstats dim is the sum of logits dimension and hessian dimension, hessian dimension can either be logits dimension if diagonal hessian is used, or logits dimension^2 if full hessian is used.","name":"stats_summary_indices","type":3},{"description":"A Rank 1 float tensor of dense shape [N] (N specifies the number of non-zero values), which supplies the values for each element in summary_indices.","name":"stats_summary_values","type":1},{"description":"A Rank 1 float tensor of dense shape [4], which specifies the dense shape of the sparse tensor, which is [num tree nodes, feature dimensions, num buckets, stats dim].","name":"stats_summary_shape","type":3},{"description":"l1 regularization factor on leaf weights, per instance based.","name":"l1","type":1},{"description":"l2 regularization factor on leaf weights, per instance based.","name":"l2","type":1},{"description":"adjustment to the gain, per leaf based.","name":"tree_complexity","type":1},{"description":"minimum avg of hessians in a node before required for the node to be considered for splitting.","name":"min_node_weight","type":1}],"outputs":[{"description":"A Rank 1 tensor indicating possible node ids that can be split.","name":"node_ids","type":3},{"description":"A Rank 1 tensor indicating the best gains to split each node.","name":"gains","type":1},{"description":"A Rank 1 tensor indicating the best feature dimension for each feature to split for each node.","name":"feature_dimensions","type":3},{"description":"A Rank 1 tensor indicating the bucket id to compare with (as a threshold) for split in each node.","name":"thresholds","type":3},{"description":"A Rank 2 tensor indicating the contribution of the left nodes when branching from parent nodes to the left direction by the given threshold for each feature.\nThis value will be used to make the left node value by adding to the parent node value. Second dimension size is logits dimension.","name":"left_node_contribs","type":1},{"description":"A Rank 2 tensor, with the same shape/conditions as left_node_contribs_list, but just that the value is for the right node.","name":"right_node_contribs","type":1},{"description":"A Rank 1 tensor indicating which direction to go if data is missing.\nInequality with default left returns 0, inequality with default right returns 1, equality with default right returns 2.","name":"split_with_default_directions","type":7}],"summary":"Calculates gains for each feature and returns the best possible split information for the feature."}},{"name":"BoostedTreesTrainingPredict","schema":{"attributes":[{"description":"Inferred.","minimum":1,"name":"num_bucketized_features","type":"int64"},{"description":"scalar, dimension of the logits, to be used for partial logits\nshape.","name":"logits_dimension","type":"int64"}],"description":"computes the update to cached logits. It is designed to be used during training.\nIt traverses the trees starting from cached tree id and cached node id and\ncalculates the updates to be pushed to the cache.","inputs":[{"name":"tree_ensemble_handle","type":20},{"description":"Rank 1 Tensor containing cached tree ids which is the starting\ntree of prediction.","name":"cached_tree_ids","type":3},{"description":"Rank 1 Tensor containing cached node id which is the starting\nnode of prediction.","name":"cached_node_ids","type":3},{"description":"A list of rank 1 Tensors containing bucket id for each\nfeature.","name":"bucketized_features","numberAttr":"num_bucketized_features","type":3}],"outputs":[{"description":"Rank 2 Tensor containing logits update (with respect to cached\nvalues stored) for each example.","name":"partial_logits","type":1},{"description":"Rank 1 Tensor containing new tree ids for each example.","name":"tree_ids","type":3},{"description":"Rank 1 Tensor containing new node ids in the new tree_ids.","name":"node_ids","type":3}],"summary":"Runs multiple additive regression ensemble predictors on input instances and"}},{"name":"BoostedTreesUpdateEnsemble","schema":{"attributes":[{"description":"0-No pruning, 1-Pre-pruning, 2-Post-pruning.","minimum":0,"name":"pruning_mode","type":"int64"},{"description":"Number of features that have best splits returned. INFERRED.","minimum":0,"name":"num_features","type":"int64"}],"description":"or by starting a new tree.","inputs":[{"description":"Handle to the ensemble variable.","name":"tree_ensemble_handle","type":20},{"description":"Rank 1 tensor with ids for each feature. This is the real id of\nthe feature that will be used in the split.","name":"feature_ids","type":3},{"description":"List of rank 1 tensors representing the nodes for which this feature\nhas a split.","name":"node_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the gains for each of the feature's\nsplit.","name":"gains","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the thesholds for each of the\nfeature's split.","name":"thresholds","numberAttr":"num_features","type":3},{"description":"List of rank 2 tensors with left leaf contribs for each of\nthe feature's splits. Will be added to the previous node values to constitute\nthe values of the left nodes.","name":"left_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 2 tensors with right leaf contribs for each\nof the feature's splits. Will be added to the previous node values to constitute\nthe values of the right nodes.","name":"right_node_contribs","numberAttr":"num_features","type":1},{"description":"Max depth of the tree to build.","name":"max_depth","type":3},{"description":"shrinkage const for each new tree.","name":"learning_rate","type":1}],"summary":"Updates the tree ensemble by either adding a layer to the last tree being grown"}},{"name":"BoostedTreesUpdateEnsembleV2","schema":{"attributes":[{"description":"Number of features that have best splits returned. INFERRED.","minimum":0,"name":"num_features","type":"int64"},{"default":1,"description":"scalar, dimension of the logits","name":"logits_dimension","type":"int64"},{"default":1,"description":"Number of groups of split information to process, where a group contains feature\nids that are processed together in BoostedTreesCalculateBestFeatureSplitOpV2.\nINFERRED.","minimum":1,"name":"num_groups","type":"int64"}],"description":"or by starting a new tree.","inputs":[{"description":"Handle to the ensemble variable.","name":"tree_ensemble_handle","type":20},{"description":"Rank 1 tensor with ids for each feature. This is the real id of\nthe feature that will be used in the split.","name":"feature_ids","numberAttr":"num_groups","type":3},{"description":"List of rank 1 tensors representing the dimension in each feature.","name":"dimension_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the nodes for which this feature\nhas a split.","name":"node_ids","numberAttr":"num_features","type":3},{"description":"List of rank 1 tensors representing the gains for each of the feature's\nsplit.","name":"gains","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the thesholds for each of the\nfeature's split.","name":"thresholds","numberAttr":"num_features","type":3},{"description":"List of rank 2 tensors with left leaf contribs for each of\nthe feature's splits. Will be added to the previous node values to constitute\nthe values of the left nodes.","name":"left_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 2 tensors with right leaf contribs for each\nof the feature's splits. Will be added to the previous node values to constitute\nthe values of the right nodes.","name":"right_node_contribs","numberAttr":"num_features","type":1},{"description":"List of rank 1 tensors representing the split type for each feature.","name":"split_types","numberAttr":"num_features","type":7},{"description":"Max depth of the tree to build.","name":"max_depth","type":3},{"description":"shrinkage const for each new tree.","name":"learning_rate","type":1},{"description":"0-No pruning, 1-Pre-pruning, 2-Post-pruning.","name":"pruning_mode","type":3}],"summary":"Updates the tree ensemble by adding a layer to the last tree being grown"}},{"name":"BroadcastArgs","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the\nbroadcasted shape. `s0`, `s1` and `r0` are all integer vectors.","inputs":[{"name":"s0","typeAttr":"T"},{"name":"s1","typeAttr":"T"}],"outputs":[{"name":"r0","typeAttr":"T"}],"summary":"Return the shape of s0 op s1 with broadcast."}},{"name":"BroadcastGradientArgs","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This is typically used by gradient computations for a broadcasting operation.","inputs":[{"name":"s0","typeAttr":"T"},{"name":"s1","typeAttr":"T"}],"outputs":[{"name":"r0","typeAttr":"T"},{"name":"r1","typeAttr":"T"}],"summary":"Return the reduction indices for computing gradients of s0 op s1 with broadcast."}},{"name":"BroadcastTo","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Broadcasting is the process of making arrays to have compatible shapes\nfor arithmetic operations. Two shapes are compatible if for each\ndimension pair they are either equal or one of them is one. When trying\nto broadcast a Tensor to a shape, it starts with the trailing dimensions,\nand works its way forward.\n\nFor example,\n\n>>> x = tf.constant([1, 2, 3])\n>>> y = tf.broadcast_to(x, [3, 3])\n>>> print(y)\ntf.Tensor(\n [[1 2 3]\n [1 2 3]\n [1 2 3]], shape=(3, 3), dtype=int32)\n\nIn the above example, the input Tensor with the shape of `[1, 3]`\nis broadcasted to output Tensor with shape of `[3, 3]`.\n\nWhen doing broadcasted operations such as multiplying a tensor\nby a scalar, broadcasting (usually) confers some time or space\nbenefit, as the broadcasted tensor is never materialized.\n\nHowever, `broadcast_to` does not carry with it any such benefits.\nThe newly-created tensor takes the full memory of the broadcasted\nshape. (In a graph context, `broadcast_to` might be fused to\nsubsequent operation and then be optimized away, however.)","inputs":[{"description":"A Tensor to broadcast.","name":"input","typeAttr":"T"},{"description":"An 1-D `int` Tensor. The shape of the desired output.","name":"shape","typeAttr":"Tidx"}],"outputs":[{"description":"A Tensor.","name":"output","typeAttr":"T"}],"summary":"Broadcast an array for a compatible shape."}},{"name":"Bucketize","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"description":"A sorted list of floats gives the boundary of the buckets.","name":"boundaries","type":"float32[]"}],"description":"For example, if the inputs are\n boundaries = [0, 10, 100]\n input = [[-5, 10000]\n [150, 10]\n [5, 100]]\n\nthen the output will be\n output = [[0, 3]\n [3, 2]\n [1, 3]]","inputs":[{"description":"Any shape of Tensor contains with int or float type.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Same shape with 'input', each value of input replaced with bucket index.\n\n@compatibility(numpy)\nEquivalent to np.digitize.\n@end_compatibility","name":"output","type":3}],"summary":"Bucketizes 'input' based on 'boundaries'."}},{"name":"BytesProducedStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the bytes size of each element of `input_dataset` in a StatsAggregator."}},{"name":"CSRSparseMatrixComponents","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"This op is meant only for debugging / testing, and its interface is not expected\nto be stable.","inputs":[{"description":"A batched CSRSparseMatrix.","name":"csr_sparse_matrix","type":21},{"description":"The index in `csr_sparse_matrix`'s batch.","name":"index","type":3}],"outputs":[{"description":"An array containing CSR matrix row pointers.","name":"row_ptrs","type":3},{"description":"An array containing CSR matrix column indices.","name":"col_inds","type":3},{"description":"An array containing CSR matrix nonzero values.","name":"values","typeAttr":"type"}],"summary":"Reads out the CSR components at batch `index`."}},{"name":"CSRSparseMatrixToDense","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"A batched CSRSparseMatrix.","name":"sparse_input","type":21}],"outputs":[{"description":"A dense tensor.","name":"dense_output","typeAttr":"type"}],"summary":"Convert a (possibly batched) CSRSparseMatrix to dense."}},{"name":"CSRSparseMatrixToSparseTensor","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_matrix","type":21}],"outputs":[{"description":"SparseTensor indices.","name":"indices","type":9},{"description":"SparseTensor values.","name":"values","typeAttr":"type"},{"description":"SparseTensor dense shape.","name":"dense_shape","type":9}],"summary":"Converts a (possibly batched) CSRSparesMatrix to a SparseTensor."}},{"name":"CSVDataset","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"}],"outputs":[{"name":"handle","type":21}]}},{"name":"CSVDatasetV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"},{"name":"exclude_cols","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"CTCBeamSearchDecoder","schema":{"attributes":[{"description":"A scalar >= 0 (beam search beam width).","minimum":1,"name":"beam_width","type":"int64"},{"description":"A scalar >= 0, <= beam_width (controls output size).","minimum":1,"name":"top_paths","type":"int64"},{"default":true,"description":"If true, merge repeated classes in output.","name":"merge_repeated","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"A note about the attribute merge_repeated: For the beam search decoder,\nthis means that if consecutive entries in a beam are the same, only\nthe first of these is emitted. That is, when the top path is \"A B B B B\",\n\"A B\" is returned if merge_repeated = True but \"A B B B B\" is\nreturned if merge_repeated = False.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"A vector containing sequence lengths, size `(batch)`.","name":"sequence_length","type":3}],"outputs":[{"description":"A list (length: top_paths) of indices matrices. Matrix j,\nsize `(total_decoded_outputs[j] x 2)`, has indices of a\n`SparseTensor`. The rows store: [batch, time].","name":"decoded_indices","numberAttr":"top_paths","type":9},{"description":"A list (length: top_paths) of values vectors. Vector j,\nsize `(length total_decoded_outputs[j])`, has the values of a\n`SparseTensor`. The vector stores the decoded classes for beam j.","name":"decoded_values","numberAttr":"top_paths","type":9},{"description":"A list (length: top_paths) of shape vector. Vector j,\nsize `(2)`, stores the shape of the decoded `SparseTensor[j]`.\nIts values are: `[batch_size, max_decoded_length[j]]`.","name":"decoded_shape","numberAttr":"top_paths","type":9},{"description":"A matrix, shaped: `(batch_size x top_paths)`. The\nsequence log-probabilities.","name":"log_probability","typeAttr":"T"}],"summary":"Performs beam search decoding on the logits given in input."}},{"name":"CTCGreedyDecoder","schema":{"attributes":[{"default":false,"description":"If True, merge repeated classes in output.","name":"merge_repeated","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"A note about the attribute merge_repeated: if enabled, when\nconsecutive logits' maximum indices are the same, only the first of\nthese is emitted. Labeling the blank '*', the sequence \"A B B * B B\"\nbecomes \"A B B\" if merge_repeated = True and \"A B B B B\" if\nmerge_repeated = False.\n\nRegardless of the value of merge_repeated, if the maximum index of a given\ntime and batch corresponds to the blank, index `(num_classes - 1)`, no new\nelement is emitted.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"A vector containing sequence lengths, size `(batch_size)`.","name":"sequence_length","type":3}],"outputs":[{"description":"Indices matrix, size `(total_decoded_outputs x 2)`,\nof a `SparseTensor`. The rows store: [batch, time].","name":"decoded_indices","type":9},{"description":"Values vector, size: `(total_decoded_outputs)`,\nof a `SparseTensor`. The vector stores the decoded classes.","name":"decoded_values","type":9},{"description":"Shape vector, size `(2)`, of the decoded SparseTensor.\nValues are: `[batch_size, max_decoded_length]`.","name":"decoded_shape","type":9},{"description":"Matrix, size `(batch_size x 1)`, containing sequence\nlog-probabilities.","name":"log_probability","typeAttr":"T"}],"summary":"Performs greedy decoding on the logits given in inputs."}},{"name":"CTCLoss","schema":{"attributes":[{"default":false,"description":"Scalar, if true then repeated labels are\ncollapsed prior to the CTC calculation.","name":"preprocess_collapse_repeated","type":"boolean"},{"default":true,"description":"Scalar. If set to false, *during* CTC calculation\nrepeated non-blank labels will not be merged and are interpreted as\nindividual labels. This is a simplified version of CTC.","name":"ctc_merge_repeated","type":"boolean"},{"default":false,"description":"Scalar. If set to true, during CTC\ncalculation, items that have longer output sequences than input sequences\nare skipped: they don't contribute to the loss term and have zero-gradient.","name":"ignore_longer_outputs_than_inputs","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"the gradient. This class performs the softmax operation for you, so inputs\nshould be e.g. linear projections of outputs by an LSTM.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits.","name":"inputs","typeAttr":"T"},{"description":"The indices of a `SparseTensor`.\n`labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for\n`(batch b, time t)`.","name":"labels_indices","type":9},{"description":"The values (labels) associated with the given batch and time.","name":"labels_values","type":3},{"description":"A vector containing sequence lengths (batch).","name":"sequence_length","type":3}],"outputs":[{"description":"A vector (batch) containing log-probabilities.","name":"loss","typeAttr":"T"},{"description":"The gradient of `loss`. 3-D, shape:\n`(max_time x batch_size x num_classes)`.","name":"gradient","typeAttr":"T"}],"summary":"Calculates the CTC Loss (log probability) for each batch entry. Also calculates"}},{"name":"CTCLossV2","schema":{"attributes":[{"default":false,"description":"Scalar, if true then repeated labels are\ncollapsed prior to the CTC calculation.","name":"preprocess_collapse_repeated","type":"boolean"},{"default":true,"description":"Scalar. If set to false, *during* CTC calculation\nrepeated non-blank labels will not be merged and are interpreted as\nindividual labels. This is a simplified version of CTC.","name":"ctc_merge_repeated","type":"boolean"},{"default":false,"description":"Scalar. If set to true, during CTC\ncalculation, items that have longer output sequences than input sequences\nare skipped: they don't contribute to the loss term and have zero-gradient.","name":"ignore_longer_outputs_than_inputs","type":"boolean"}],"description":"the gradient. This class performs the softmax operation for you, so inputs\nshould be e.g. linear projections of outputs by an LSTM.","inputs":[{"description":"3-D, shape: `(max_time x batch_size x num_classes)`, the logits. Default blank\nlabel is 0 rather num_classes - 1.","name":"inputs","type":1},{"description":"The indices of a `SparseTensor`.\n`labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for\n`(batch b, time t)`.","name":"labels_indices","type":9},{"description":"The values (labels) associated with the given batch and time.","name":"labels_values","type":3},{"description":"A vector containing sequence lengths (batch).","name":"sequence_length","type":3}],"outputs":[{"description":"A vector (batch) containing log-probabilities.","name":"loss","type":1},{"description":"The gradient of `loss`. 3-D, shape:\n`(max_time x batch_size x num_classes)`.","name":"gradient","type":1}],"summary":"Calculates the CTC Loss (log probability) for each batch entry. Also calculates"}},{"name":"CacheDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"A CacheDataset will iterate over the input_dataset, and store tensors. If the\ncache already exists, the cache will be used. If the cache is inappropriate\n(e.g. cannot be opened, contains tensors of the wrong shape / size), an error\nwill the returned when used.","inputs":[{"name":"input_dataset","type":21},{"description":"A path on the filesystem where we should cache the dataset. Note: this\nwill be a directory.","name":"filename","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that caches elements from `input_dataset`."}},{"name":"CacheDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"filename","type":7},{"name":"cache","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"Case","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A list of functions each of which takes 'inputs' and returns a list of\n tensors, whose types are the same as what every other branch returns.","minimum":1,"name":"branches","type":"function[]"},{"default":[],"name":"output_shapes","type":"shape[]"}],"description":" An n-way switch statement, implementing the following:\n ```\n switch (branch_index) {\n case 0:\n output = branches[0](input);\n break;\n case 1:\n output = branches[1](input);\n break;\n ...\n case [[nbranches-1]]:\n default:\n output = branches[nbranches-1](input);\n break;\n }\n ```","inputs":[{"description":"The branch selector, an int32 Tensor.","name":"branch_index","type":3},{"description":"A list of input tensors passed to the branch function.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"An n-way switch statement which calls a single branch function."}},{"name":"Cast","schema":{"attributes":[{"name":"SrcT","type":"type"},{"name":"DstT","type":"type"},{"default":false,"name":"Truncate","type":"boolean"}],"inputs":[{"name":"x","typeAttr":"SrcT"}],"outputs":[{"name":"y","typeAttr":"DstT"}],"summary":"Cast x of type SrcT to y of DstT."}},{"name":"Ceil","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise smallest integer not less than x."}},{"name":"CheckNumerics","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Prefix of the error message.","name":"message","type":"string"}],"description":"When run, reports an `InvalidArgument` error if `tensor` has any values\nthat are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is.","inputs":[{"name":"tensor","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Checks a tensor for NaN and Inf values."}},{"name":"CheckNumericsV2","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Prefix of the error message.","name":"message","type":"string"}],"description":"When run, reports an `InvalidArgument` error if `tensor` has any values\nthat are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is.\nUnlike CheckNumerics (V1), CheckNumericsV2 distinguishes -Inf and +Inf in the\nerrors it throws.","inputs":[{"name":"tensor","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Checks a tensor for NaN, -Inf and +Inf values."}},{"name":"Cholesky","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices.\n\nThe input has to be symmetric and positive definite. Only the lower-triangular\npart of the input will be used for this operation. The upper-triangular part\nwill not be read.\n\nThe output is a tensor of the same shape as the input\ncontaining the Cholesky decompositions for all input submatrices `[..., :, :]`.\n\n**Note**: The gradient computation on GPU is faster for large matrices but\nnot for large batch dimensions when the submatrices are small. In this\ncase it might be faster to use the CPU.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.","name":"output","typeAttr":"T"}],"summary":"Computes the Cholesky decomposition of one or more square matrices."}},{"name":"CholeskyGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"For an explanation see \"Differentiation of the Cholesky algorithm\" by\nIain Murray http://arxiv.org/abs/1602.07527.","inputs":[{"description":"Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`.\nAlgorithm depends only on lower triangular part of the innermost matrices of\nthis tensor.","name":"l","typeAttr":"T"},{"description":"df/dl where f is some scalar function. Shape is `[..., M, M]`.\nAlgorithm depends only on lower triangular part of the innermost matrices of\nthis tensor.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Symmetrized version of df/dA . Shape is `[..., M, M]`","name":"output","typeAttr":"T"}],"summary":"Computes the reverse mode backpropagated gradient of the Cholesky algorithm."}},{"name":"ChooseFastestBranchDataset","schema":{"attributes":[{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"num_elements_per_branch","type":"int64"},{"minimum":1,"name":"branches","type":"function[]"},{"minimum":1,"name":"other_arguments_lengths","type":"int64[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"ratio_numerator","type":9},{"name":"ratio_denominator","type":9},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}]}},{"name":"ChooseFastestDataset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"num_experiments","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ClipByValue","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Given a tensor `t`, this operation returns a tensor of the same type and\nshape as `t` with its values clipped to `clip_value_min` and `clip_value_max`.\nAny values less than `clip_value_min` are set to `clip_value_min`. Any values\ngreater than `clip_value_max` are set to `clip_value_max`.","inputs":[{"description":"A `Tensor`.","name":"t","typeAttr":"T"},{"description":"A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape\nas `t`. The minimum value to clip by.","name":"clip_value_min","typeAttr":"T"},{"description":"A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape\nas `t`. The maximum value to clip by.","name":"clip_value_max","typeAttr":"T"}],"outputs":[{"description":"A clipped `Tensor` with the same shape as input 't'.","name":"output","typeAttr":"T"}],"summary":"Clips tensor values to a specified min and max."}},{"name":"CloseSummaryWriter","schema":{"inputs":[{"name":"writer","type":20}]}},{"name":"CollectiveBcastRecv","schema":{"attributes":[{"description":"Must be one of the following: `bool`, `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Receives a tensor value broadcast from another device."}},{"name":"CollectiveBcastSend","schema":{"attributes":[{"description":"Must be one of the following: `bool`, `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Broadcasts a tensor value to one or more other devices."}},{"name":"CollectiveGather","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"name":"shape","type":"shape"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Mutually accumulates multiple tensors of identical type and shape."}},{"name":"CollectivePermute","schema":{"attributes":[{"description":"The type of elements to be exchanged. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Each instance supplies its own input.\n\nFor example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing\nsource_target_pairs=`[[0,1],[1,2],[2,3],[3,0]]` gets the outputs:\n`[D, A, B, C]`.","inputs":[{"description":"The local input to be permuted. Currently only supports float and\nbfloat16.","name":"input","typeAttr":"T"},{"description":"A tensor with shape [num_pairs, 2].","name":"source_target_pairs","type":3}],"outputs":[{"description":"The permuted input.","name":"output","typeAttr":"T"}],"summary":"An Op to permute tensors across replicated TPU instances."}},{"name":"CollectiveReduce","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"group_size","type":"int64"},{"name":"group_key","type":"int64"},{"name":"instance_key","type":"int64"},{"description":"Must be one of the following: `Min`, `Max`, `Mul`, `Add`.","name":"merge_op","type":"string"},{"description":"Must be one of the following: `Id`, `Div`.","name":"final_op","type":"string"},{"name":"subdiv_offsets","type":"int64[]"},{"default":[],"name":"wait_for","type":"int64[]"},{"default":"auto","name":"communication_hint","type":"string"},{"default":0,"name":"timeout_seconds","type":"float32"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Mutually reduces multiple tensors of identical type and shape."}},{"name":"CombinedNonMaxSuppression","schema":{"attributes":[{"default":false,"description":"If false, the output nmsed boxes, scores and classes\nare padded/clipped to `max_total_size`. If true, the\noutput nmsed boxes, scores and classes are padded to be of length\n`max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in\nwhich case it is clipped to `max_total_size`. Defaults to false.","name":"pad_per_class","type":"boolean"},{"default":true,"description":"If true, assume the box coordinates are between [0, 1] and clip the output boxes\nif they fall beyond [0, 1]. If false, do not do clipping and output the box\ncoordinates as it is.","name":"clip_boxes","type":"boolean"}],"description":"This operation performs non_max_suppression on the inputs per batch, across\nall classes.\nPrunes away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Also note that\nthis algorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is the final boxes, scores and classes tensor\nreturned after performing non_max_suppression.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then\nsame boxes are used for all classes otherwise, if `q` is equal to number of\nclasses, class-specific boxes are used.","name":"boxes","type":1},{"description":"A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]`\nrepresenting a single score corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression per class","name":"max_output_size_per_class","type":3},{"description":"A scalar representing maximum number of boxes retained over all classes.","name":"max_total_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","type":1},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","type":1}],"outputs":[{"description":"A [batch_size, max_detections, 4] float32 tensor\ncontaining the non-max suppressed boxes.","name":"nmsed_boxes","type":1},{"description":"A [batch_size, max_detections] float32 tensor\ncontaining the scores for the boxes.","name":"nmsed_scores","type":1},{"description":"A [batch_size, max_detections] float32 tensor\ncontaining the classes for the boxes.","name":"nmsed_classes","type":1},{"description":"A [batch_size] int32 tensor indicating the number of\nvalid detections per batch item. Only the top num_detections[i] entries in\nnms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the\nentries are zero paddings.","name":"valid_detections","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"CompareAndBitpack","schema":{"attributes":[{"description":"The type of the input and threshold. Must be one of the following: `bool`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Each comparison returns a boolean `true` (if `input_value > threshold`)\nor and `false` otherwise.\n\nThis operation is useful for Locality-Sensitive-Hashing (LSH) and other\nalgorithms that use hashing approximations of cosine and `L2` distances;\ncodes can be generated from an input via:\n\n```python\ncodebook_size = 50\ncodebook_bits = codebook_size * 32\ncodebook = tf.get_variable('codebook', [x.shape[-1].value, codebook_bits],\n dtype=x.dtype,\n initializer=tf.orthogonal_initializer())\ncodes = compare_and_threshold(tf.matmul(x, codebook), threshold=0.)\ncodes = tf.bitcast(codes, tf.int32) # go from uint8 to int32\n# now codes has shape x.shape[:-1] + [codebook_size]\n```\n\n**NOTE**: Currently, the innermost dimension of the tensor must be divisible\nby 8.\n\nGiven an `input` shaped `[s0, s1, ..., s_n]`, the output is\na `uint8` tensor shaped `[s0, s1, ..., s_n / 8]`.","inputs":[{"description":"Values to compare against `threshold` and bitpack.","name":"input","typeAttr":"T"},{"description":"Threshold to compare against.","name":"threshold","typeAttr":"T"}],"outputs":[{"description":"The bitpacked comparisons.","name":"output","type":4}],"summary":"Compare values of `input` to `threshold` and pack resulting bits into a `uint8`."}},{"name":"Complex","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tout","type":"type"}],"description":"Given a tensor `real` representing the real part of a complex number, and a\ntensor `imag` representing the imaginary part of a complex number, this\noperation returns complex numbers elementwise of the form \\\\(a + bj\\\\), where\n*a* represents the `real` part and *b* represents the `imag` part.\n\nThe input tensors `real` and `imag` must have the same shape.\n\nFor example:\n\n```\n# tensor 'real' is [2.25, 3.25]\n# tensor `imag` is [4.75, 5.75]\ntf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]]\n```","inputs":[{"name":"real","typeAttr":"T"},{"name":"imag","typeAttr":"T"}],"outputs":[{"name":"out","typeAttr":"Tout"}],"summary":"Converts two real numbers to a complex number."}},{"name":"ComplexAbs","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `x` of complex numbers, this operation returns a tensor of type\n`float` or `double` that is the absolute value of each element in `x`. All\nelements in `x` must be complex numbers of the form \\\\(a + bj\\\\). The absolute\nvalue is computed as \\\\( \\sqrt{a^2 + b^2}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"Tout"}],"summary":"Computes the complex absolute value of a tensor."}},{"name":"CompressElement","schema":{"attributes":[{"minimum":1,"name":"input_types","type":"type[]"}],"inputs":[{"name":"components","typeListAttr":"input_types"}],"outputs":[{"name":"compressed","type":21}],"summary":"Compresses a dataset element."}},{"name":"ComputeAccidentalHits","schema":{"attributes":[{"description":"Number of true labels per context.","name":"num_true","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"When doing log-odds NCE, the result of this op should be passed through a\nSparseToDense op, then added to the logits of the sampled candidates. This has\nthe effect of 'removing' the sampled labels that match the true labels by\nmaking the classifier sure that they are sampled labels.","inputs":[{"description":"The true_classes output of UnpackSparseLabels.","name":"true_classes","type":9},{"description":"The sampled_candidates output of CandidateSampler.","name":"sampled_candidates","type":9}],"outputs":[{"description":"A vector of indices corresponding to rows of true_candidates.","name":"indices","type":3},{"description":"A vector of IDs of positions in sampled_candidates that match a true_label\nfor the row with the corresponding index in indices.","name":"ids","type":9},{"description":"A vector of the same length as indices and ids, in which each element\nis -FLOAT_MAX.","name":"weights","type":1}],"summary":"Computes the ids of the positions in sampled_candidates that match true_labels."}},{"name":"ComputeBatchSize","schema":{"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"batch_size","type":9}],"summary":"Computes the static batch size of a dataset sans partial batches."}},{"name":"Concat","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"inputs":[{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [0, rank(values)).","name":"concat_dim","type":3},{"description":"The `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"}],"summary":"Concatenates tensors along one dimension."}},{"name":"ConcatOffset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"}],"description":"For example:\n\n```\n# 'x' is [2, 2, 7]\n# 'y' is [2, 3, 7]\n# 'z' is [2, 5, 7]\nconcat_offset(2, [x, y, z]) => [0, 0, 0], [0, 2, 0], [0, 5, 0]\n```\n\nThis is typically used by gradient computations for a concat operation.","inputs":[{"description":"The dimension along which to concatenate.","name":"concat_dim","type":3},{"description":"The `N` int32 vectors representing shape of tensors being concatenated.","name":"shape","numberAttr":"N","type":3}],"outputs":[{"description":"The `N` int32 vectors representing the starting offset\nof input tensors within the concatenated output.","name":"offset","numberAttr":"N","type":3}],"summary":"Computes offsets of concat inputs within its output."}},{"name":"ConcatV2","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"category":"Tensor","inputs":[{"description":"List of `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [-rank(values), rank(values)).","name":"axis","typeAttr":"Tidx"}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"}],"summary":"Concatenates tensors along one dimension."}},{"name":"ConcatenateDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"another_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that concatenates `input_dataset` with `another_dataset`."}},{"name":"ConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values, can be [], in which case shape is unknown.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the\ngiven name across multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.","outputs":[{"description":"The handle to the accumulator.","isRef":true,"name":"handle","type":7}],"summary":"A conditional accumulator for aggregating gradients."}},{"name":"ConfigureDistributedTPU","schema":{"attributes":[{"default":"","description":"Reserved. Do not use.","name":"embedding_config","type":"string"},{"default":"","description":"Serialized tensorflow.tpu.TPUEmbeddingConfiguration that\ndescribes the embedding lookups of the program.","name":"tpu_embedding_config","type":"string"},{"default":false,"description":"Reserved. Do not use.","name":"is_global_init","type":"boolean"},{"default":false,"name":"enable_whole_mesh_compilations","type":"boolean"},{"default":true,"name":"compilation_failure_closes_chips","type":"boolean"}],"outputs":[{"description":"A serialized tensorflow.tpu.TopologyProto that describes the TPU\ntopology.","name":"topology","type":7}],"summary":"Sets up the centralized structures for a distributed TPU system."}},{"name":"ConfigureTPUEmbedding","schema":{"attributes":[{"description":"Serialized tensorflow.tpu.TPUEmbeddingConfiguration that\ndescribes the embedding lookups of the program.","name":"config","type":"string"}],"summary":"Sets up TPUEmbedding in a distributed TPU system."}},{"name":"Conj","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`, `variant`.","name":"T","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ncomplex numbers that are the complex conjugate of each element in `input`. The\ncomplex numbers in `input` must be of the form \\\\(a + bj\\\\), where *a* is the\nreal part and *b* is the imaginary part.\n\nThe complex conjugate returned by this operation is of the form \\\\(a - bj\\\\).\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the complex conjugate of a complex number."}},{"name":"ConjugateTranspose","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tperm","type":"type"}],"description":"The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy:\n `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]`\n `y[i,j,k,...,s,t,u] == conj(x[perm[i], perm[j], perm[k],...,perm[s], perm[t], perm[u]])`","inputs":[{"name":"x","typeAttr":"T"},{"name":"perm","typeAttr":"Tperm"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Shuffle dimensions of x according to a permutation and conjugate the result."}},{"name":"Const","schema":{"attributes":[{"description":"Attr `value` is the tensor to return.","name":"value","type":"tensor"},{"name":"dtype","type":"type"}],"category":"Constant","outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Returns a constant tensor."}},{"name":"ConsumeMutexLock","schema":{"description":"This op exists to consume a tensor created by `MutexLock` (other than\ndirect control dependencies). It should be the only that consumes the tensor,\nand will raise an error if it is not. Its only purpose is to keep the\nmutex lock tensor alive until it is consumed by this op.\n\n**NOTE**: This operation must run on the same device as its input. This may\nbe enforced via the `colocate_with` mechanism.","inputs":[{"description":"A tensor returned by `MutexLock`.","name":"mutex_lock","type":21}],"summary":"This op consumes a lock created by `MutexLock`."}},{"name":"ControlTrigger","schema":{"description":"Only useful as a placeholder for control edges.","summary":"Does nothing. Serves as a control trigger for scheduling."}},{"name":"Conv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`.","name":"T","type":"type"},{"description":"1-D tensor of length 4. The stride of the sliding window for each\ndimension of `input`. The dimension order is determined by the value of\n`data_format`, see below for details.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"category":"Layer","description":"Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\nand a filter / kernel tensor of shape\n`[filter_height, filter_width, in_channels, out_channels]`, this op\nperforms the following:\n\n1. Flattens the filter to a 2-D matrix with shape\n `[filter_height * filter_width * in_channels, output_channels]`.\n2. Extracts image patches from the input tensor to form a *virtual*\n tensor of shape `[batch, out_height, out_width,\n filter_height * filter_width * in_channels]`.\n3. For each patch, right-multiplies the filter matrix and the image patch\n vector.\n\nIn detail, with the default NHWC format,\n\n output[b, i, j, k] =\n sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *\n filter[di, dj, q, k]\n\nMust have `strides[0] = strides[3] = 1`. For the most common case of the same\nhorizontal and vertices strides, `strides = [1, stride, stride, 1]`.","inputs":[{"description":"A 4-D tensor. The dimension order is interpreted according to the value\nof `data_format`, see below for details.","name":"input","typeAttr":"T"},{"description":"A 4-D tensor of shape\n`[filter_height, filter_width, in_channels, out_channels]`","name":"filter","typeAttr":"T"}],"outputs":[{"description":"A 4-D tensor. The dimension order is determined by the value of\n`data_format`, see below for details.","name":"output","typeAttr":"T"}],"summary":"Computes a 2-D convolution given 4-D `input` and `filter` tensors."}},{"name":"Conv2DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution. Must be in the same order as the dimension specified with\nformat.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 4-D\n`[filter_height, filter_width, in_channels, out_channels]` tensor.","name":"filter_sizes","type":3},{"description":"4-D with shape `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.\nthe `filter` input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of convolution with respect to the filter."}},{"name":"Conv2DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution. Must be in the same order as the dimension specified with\nformat.","name":"strides","type":"int64[]"},{"default":true,"name":"use_cudnn_on_gpu","type":"boolean"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"description":"If `padding` is `\"EXPLICIT\"`, the list of explicit padding amounts. For the ith\ndimension, the amount of padding inserted before and after the dimension is\n`explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If\n`padding` is not `\"EXPLICIT\"`, `explicit_paddings` must be empty.","name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"An integer vector representing the shape of `input`,\nwhere `input` is a 4-D `[batch, height, width, channels]` tensor.","name":"input_sizes","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`. Gradient\nw.r.t. the input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of convolution with respect to the input."}},{"name":"Conv3D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"description":"In signal processing, cross-correlation is a measure of similarity of\ntwo waveforms as a function of a time-lag applied to one of them. This\nis also known as a sliding dot product or sliding inner-product.\n\nOur Conv3D implements a form of cross-correlation.","inputs":[{"description":"Shape `[batch, in_depth, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[filter_depth, filter_height, filter_width, in_channels,\nout_channels]`. `in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes a 3-D convolution given 5-D `input` and `filter` tensors."}},{"name":"Conv3DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1,1],"name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the filter."}},{"name":"Conv3DBackpropFilterV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 5-D\n`[filter_depth, filter_height, filter_width, in_channels, out_channels]`\ntensor.","name":"filter_sizes","type":3},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the filter."}},{"name":"Conv3DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1,1],"name":"dilations","type":"int64[]"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, in_channels]`.","name":"input","typeAttr":"T"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the input."}},{"name":"Conv3DBackpropInputV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1,1],"description":"1-D tensor of length 5. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"inputs":[{"description":"An integer vector representing the tensor shape of `input`,\nwhere `input` is a 5-D\n`[batch, depth, rows, cols, in_channels]` tensor.","name":"input_sizes","typeAttr":"Tshape"},{"description":"Shape `[depth, rows, cols, in_channels, out_channels]`.\n`in_channels` must match between `input` and `filter`.","name":"filter","typeAttr":"T"},{"description":"Backprop signal of shape `[batch, out_depth, out_rows, out_cols,\nout_channels]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the gradients of 3-D convolution with respect to the input."}},{"name":"Copy","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"A list of debug op spec (op, url, gated_grpc) for attached debug\nops. Each element of the list has the format\n;;, wherein gated_grpc is boolean represented\nas 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n\"DebugIdentity;file:///tmp/tfdbg_1;0\".","name":"debug_ops_spec","type":"string[]"}],"description":"Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the\ndevice on which the tensor is allocated.\nN.B.: If the all downstream attached debug ops are disabled given the current\ngRPC gating status, the output will simply forward the input tensor without\ndeep-copying. See the documentation of Debug* ops for more details.\n\nUnlike the CopyHost Op, this op does not have HostMemory constraint on its\ninput or output.","inputs":[{"description":"Input tensor.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Copy a tensor from CPU-to-CPU or GPU-to-GPU."}},{"name":"CopyHost","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"The name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"A list of debug op spec (op, url, gated_grpc) for attached debug\nops. Each element of the list has the format\n;;, wherein gated_grpc is boolean represented\nas 0/1. E.g., \"DebugIdentity;grpc://foo:3333;1\",\n\"DebugIdentity;file:///tmp/tfdbg_1;0\".","name":"debug_ops_spec","type":"string[]"}],"description":"Performs CPU-to-CPU deep-copying of tensor.\nN.B.: If the all downstream attached debug ops are disabled given the current\ngRPC gating status, the output will simply forward the input tensor without\ndeep-copying. See the documentation of Debug* ops for more details.\n\nUnlike the Copy Op, this op has HostMemory constraint on its input or output.","inputs":[{"description":"Input tensor.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Copy a tensor to host."}},{"name":"Cos","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes cosine of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `[-1,1]`. If input lies outside the boundary, `nan`\n is returned.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.cos(x) ==> [nan -0.91113025 0.87758255 0.5403023 0.36235774 0.48718765 -0.95215535 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes cos of x element-wise."}},{"name":"Cosh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic cosine of every\n element in the tensor. Input range is `[-inf, inf]` and output range\n is `[1, inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 2, 10, float(\"inf\")])\n tf.math.cosh(x) ==> [inf 4.0515420e+03 1.1276259e+00 1.5430807e+00 1.8106556e+00 3.7621956e+00 1.1013233e+04 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic cosine of x element-wise."}},{"name":"CountUpTo","schema":{"attributes":[{"description":"If incrementing ref would bring it above limit, instead generates an\n'OutOfRange' error.","name":"limit","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Should be from a scalar `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"}],"outputs":[{"description":"A copy of the input before increment. If nothing else modifies the\ninput, the values produced will all be distinct.","name":"output","typeAttr":"T"}],"summary":"Increments 'ref' until it reaches 'limit'."}},{"name":"CreateSummaryDbWriter","schema":{"inputs":[{"name":"writer","type":20},{"name":"db_uri","type":7},{"name":"experiment_name","type":7},{"name":"run_name","type":7},{"name":"user_name","type":7}]}},{"name":"CreateSummaryFileWriter","schema":{"inputs":[{"name":"writer","type":20},{"name":"logdir","type":7},{"name":"max_queue","type":3},{"name":"flush_millis","type":3},{"name":"filename_suffix","type":7}]}},{"name":"CropAndResize","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the sampling method for resizing. It can be either\n`\"bilinear\"` or `\"nearest\"` and default to `\"bilinear\"`. Currently two sampling\nmethods are supported: Bilinear and Nearest Neighbor. Must be one of the following: `bilinear`, `nearest`.","name":"method","type":"string"},{"default":0,"description":"Value used for extrapolation, when applicable.","name":"extrapolation_value","type":"float32"}],"description":"Extracts crops from the input image tensor and resizes them using bilinear\nsampling or nearest neighbor sampling (possibly with aspect ratio change) to a\ncommon output size specified by `crop_size`. This is more general than the\n`crop_to_bounding_box` op which extracts a fixed size slice from the input image\nand does not allow resizing or aspect ratio change.\n\nReturns a tensor with `crops` from the input `image` at positions defined at the\nbounding box locations in `boxes`. The cropped boxes are all resized (with\nbilinear or nearest neighbor interpolation) to a fixed\n`size = [crop_height, crop_width]`. The result is a 4-D tensor\n`[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned.\nIn particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical\nresults to using `tf.image.resize_bilinear()` or\n`tf.image.resize_nearest_neighbor()`(depends on the `method` argument) with\n`align_corners=True`.","inputs":[{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.\nBoth `image_height` and `image_width` need to be positive.","name":"image","typeAttr":"T"},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3},{"description":"A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All\ncropped image patches are resized to this size. The aspect ratio of the image\ncontent is not preserved. Both `crop_height` and `crop_width` need to be\npositive.","name":"crop_size","type":3}],"outputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"crops","type":1}],"summary":"Extracts crops from the input image tensor and resizes them."}},{"name":"CropAndResizeGradBoxes","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the interpolation method. Only 'bilinear' is\nsupported for now. Must be one of the following: `bilinear`.","name":"method","type":"string"}],"inputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"grads","type":1},{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.\nBoth `image_height` and `image_width` need to be positive.","name":"image","typeAttr":"T"},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3}],"outputs":[{"description":"A 2-D tensor of shape `[num_boxes, 4]`.","name":"output","type":1}],"summary":"Computes the gradient of the crop_and_resize op wrt the input boxes tensor."}},{"name":"CropAndResizeGradImage","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float16`, `float64`.","name":"T","type":"type"},{"default":"bilinear","description":"A string specifying the interpolation method. Only 'bilinear' is\nsupported for now. Must be one of the following: `bilinear`, `nearest`.","name":"method","type":"string"}],"inputs":[{"description":"A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`.","name":"grads","type":1},{"description":"A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor\nspecifies the coordinates of a box in the `box_ind[i]` image and is specified\nin normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of\n`y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the\n`[0, 1]` interval of normalized image height is mapped to\n`[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in\nwhich case the sampled crop is an up-down flipped version of the original\nimage. The width dimension is treated similarly. Normalized coordinates\noutside the `[0, 1]` range are allowed, in which case we use\n`extrapolation_value` to extrapolate the input image values.","name":"boxes","type":1},{"description":"A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`.\nThe value of `box_ind[i]` specifies the image that the `i`-th box refers to.","name":"box_ind","type":3},{"description":"A 1-D tensor with value `[batch, image_height, image_width, depth]`\ncontaining the original image size. Both `image_height` and `image_width` need\nto be positive.","name":"image_size","type":3}],"outputs":[{"description":"A 4-D tensor of shape `[batch, image_height, image_width, depth]`.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of the crop_and_resize op wrt the input image tensor."}},{"name":"Cross","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"`a` and `b` must be the same shape; they can either be simple 3-element vectors,\nor any shape where the innermost dimension is 3. In the latter case, each pair\nof corresponding 3-element vectors is cross-multiplied independently.","inputs":[{"description":"A tensor containing 3-element vectors.","name":"a","typeAttr":"T"},{"description":"Another tensor, of same type and shape as `a`.","name":"b","typeAttr":"T"}],"outputs":[{"description":"Pairwise cross product of the vectors in `a` and `b`.","name":"product","typeAttr":"T"}],"summary":"Compute the pairwise cross product."}},{"name":"CrossReplicaSum","schema":{"attributes":[{"description":"The type of elements to be summed. Must be one of the following: `bfloat16`, `float32`, `int32`, `uint32`.","name":"T","type":"type"}],"description":"Each instance supplies its own input.\n\nFor example, suppose there are 8 TPU instances: `[A, B, C, D, E, F, G, H]`.\nPassing group_assignment=`[[0,2,4,6],[1,3,5,7]]` sets `A, C, E, G` as group 0,\nand `B, D, F, H` as group 1. Thus we get the outputs:\n`[A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H]`.","inputs":[{"description":"The local input to the sum.","name":"input","typeAttr":"T"},{"description":"An int32 tensor with shape\n[num_groups, num_replicas_per_group]. `group_assignment[i]` represents the\nreplica ids in the ith subgroup.","name":"group_assignment","type":3}],"outputs":[{"description":"The sum of all the distributed inputs.","name":"output","typeAttr":"T"}],"summary":"An Op to sum inputs across replicated TPU instances."}},{"name":"CudnnRNN","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":true,"name":"is_training","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is false.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"}],"summary":"A RNN backed by cuDNN."}},{"name":"CudnnRNNBackprop","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Compute the backprop of both data and weights in a RNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\nreserve_space: The same reserve_space produced in for forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNN."}},{"name":"CudnnRNNBackpropV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Compute the backprop of both data and weights in a RNN. Takes an extra\n \"host_reserved\" inupt than CudnnRNNBackprop, which is used to determine RNN\n cudnnRNNAlgo_t and cudnnMathType_t.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\nreserve_space: The same reserve_space produced in the forward operation.\nhost_reserved: The same host_reserved produced in the forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNN."}},{"name":"CudnnRNNBackpropV3","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"},{"default":true,"name":"time_major","type":"boolean"}],"description":"Compute the backprop of both data and weights in a RNN. Takes an extra\n \"sequence_lengths\" input than CudnnRNNBackprop.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, input_size]. If time_major is false, the shape is\n [batch_size, seq_length, input_size].\ninput_h: If time_major is true, this is a 3-D tensor with the shape of\n [num_layer * dir, batch_size, num_units]. If time_major is false, the shape\n is [batch_size, num_layer * dir, num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\nsequence_lengths: a vector of lengths of each input sequence.\noutput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, dir * num_units]. If time_major is false, the\n shape is [batch_size, seq_length, dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\noutput_backprop: A 3-D tensor with the same shape as output in the forward pass.\noutput_h_backprop: A 3-D tensor with the same shape as output_h in the forward\n pass.\noutput_c_backprop: A 3-D tensor with the same shape as output_c in the forward\n pass.\ntime_major: Indicates whether the input/output format is time major or batch\n major.\nreserve_space: The same reserve_space produced in the forward operation.\ninput_backprop: The backprop to input in the forward pass. Has the same shape\n as input.\ninput_h_backprop: The backprop to input_h in the forward pass. Has the same\n shape as input_h.\ninput_c_backprop: The backprop to input_c in the forward pass. Has the same\n shape as input_c.\nparams_backprop: The backprop to the params buffer in the forward pass. Has the\n same shape as params.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"sequence_lengths","type":3},{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"output_backprop","typeAttr":"T"},{"name":"output_h_backprop","typeAttr":"T"},{"name":"output_c_backprop","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"outputs":[{"name":"input_backprop","typeAttr":"T"},{"name":"input_h_backprop","typeAttr":"T"},{"name":"input_c_backprop","typeAttr":"T"},{"name":"params_backprop","typeAttr":"T"}],"summary":"Backprop step of CudnnRNNV3."}},{"name":"CudnnRNNCanonicalToParams","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Writes a set of weights into the opaque params buffer so they can be used in\nupcoming training or inferences.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nnum_params: number of parameter sets for all layers.\n Each layer may contain multiple parameter sets, with each set consisting of\n a weight matrix and a bias vector.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"weights","numberAttr":"num_params","typeAttr":"T"},{"name":"biases","numberAttr":"num_params","typeAttr":"T"}],"outputs":[{"name":"params","typeAttr":"T"}],"summary":"Converts CudnnRNN params from canonical form to usable form."}},{"name":"CudnnRNNCanonicalToParamsV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params_weights","type":"int64"},{"minimum":1,"name":"num_params_biases","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Writes a set of weights into the opaque params buffer so they can be used in\nupcoming training or inferences.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nnum_params_weights: number of weight parameter matrix for all layers.\nnum_params_biases: number of bias parameter vector for all layers.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nnum_proj: The output dimensionality for the projection matrices. If None or 0,\n no projection is performed.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"weights","numberAttr":"num_params_weights","typeAttr":"T"},{"name":"biases","numberAttr":"num_params_biases","typeAttr":"T"}],"outputs":[{"name":"params","typeAttr":"T"}],"summary":"Converts CudnnRNN params from canonical form to usable form. It supports the projection in LSTM."}},{"name":"CudnnRNNParamsSize","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Return the params size that can be used by the Cudnn RNN model. Subsequent\nweight allocation and initialization should use this size.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nparams_size: The size of the params buffer that should be allocated and\n initialized for this RNN model. Note that this params buffer may not be\n compatible across GPUs. Please use CudnnRNNParamsWeights and\n CudnnRNNParamsBiases to save and restore them in a way that is compatible\n across different runs.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3}],"outputs":[{"name":"params_size","typeAttr":"S"}],"summary":"Computes size of weights that can be used by a Cudnn RNN model."}},{"name":"CudnnRNNParamsToCanonical","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"}],"description":"Retrieves a set of weights from the opaque params buffer that can be saved and\nrestored in a way compatible with future runs.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nnum_params: number of parameter sets for all layers.\n Each layer may contain multiple parameter sets, with each set consisting of\n a weight matrix and a bias vector.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"weights","numberAttr":"num_params","typeAttr":"T"},{"name":"biases","numberAttr":"num_params","typeAttr":"T"}],"summary":"Retrieves CudnnRNN params in canonical form."}},{"name":"CudnnRNNParamsToCanonicalV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"minimum":1,"name":"num_params_weights","type":"int64"},{"minimum":1,"name":"num_params_biases","type":"int64"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"}],"description":"Retrieves a set of weights from the opaque params buffer that can be saved and\nrestored in a way compatible with future runs.\n\nNote that the params buffer may not be compatible across different GPUs. So any\nsave and restoration should be converted to and from the canonical weights and\nbiases.\n\nnum_layers: Specifies the number of layers in the RNN model.\nnum_units: Specifies the size of the hidden state.\ninput_size: Specifies the size of the input state.\nnum_params_weights: number of weight parameter matrix for all layers.\nnum_params_biases: number of bias parameter vector for all layers.\nweights: the canonical form of weights that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nbiases: the canonical form of biases that can be used for saving\n and restoration. They are more likely to be compatible across different\n generations.\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicate whether there is a linear projection between the input and\n The actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used.\n dir = (direction == bidirectional) ? 2 : 1\ndropout: dropout probability. When set to 0., dropout is disabled.\nseed: the 1st part of a seed to initialize dropout.\nseed2: the 2nd part of a seed to initialize dropout.\nnum_proj: The output dimensionality for the projection matrices. If None or 0,\n no projection is performed.","inputs":[{"name":"num_layers","type":3},{"name":"num_units","type":3},{"name":"input_size","type":3},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"weights","numberAttr":"num_params_weights","typeAttr":"T"},{"name":"biases","numberAttr":"num_params_biases","typeAttr":"T"}],"summary":"Retrieves CudnnRNN params in canonical form. It supports the projection in LSTM."}},{"name":"CudnnRNNV2","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":true,"name":"is_training","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer. Produces one extra output \"host_reserved\" than CudnnRNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: A 3-D tensor with the shape of [seq_length, batch_size, input_size].\ninput_h: A 3-D tensor with the shape of [num_layer * dir, batch_size,\n num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\noutput: A 3-D tensor with the shape of [seq_length, batch_size,\n dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is true.\nhost_reserved: An opaque tensor that can be used in backprop calculation. It is\n only produced if is_training is true. It is output on host memory rather than\n device memory.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"summary":"A RNN backed by cuDNN."}},{"name":"CudnnRNNV3","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lstm","description":"Must be one of the following: `rnn_relu`, `rnn_tanh`, `lstm`, `gru`.","name":"rnn_mode","type":"string"},{"default":"linear_input","description":"Must be one of the following: `linear_input`, `skip_input`, `auto_select`.","name":"input_mode","type":"string"},{"default":"unidirectional","description":"Must be one of the following: `unidirectional`, `bidirectional`.","name":"direction","type":"string"},{"default":0,"name":"dropout","type":"float32"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":0,"name":"num_proj","type":"int64"},{"default":true,"name":"is_training","type":"boolean"},{"default":true,"name":"time_major","type":"boolean"}],"description":"Computes the RNN from the input and initial states, with respect to the params\nbuffer. Accepts one extra input \"sequence_lengths\" than CudnnRNN.\n\nrnn_mode: Indicates the type of the RNN model.\ninput_mode: Indicates whether there is a linear projection between the input and\n the actual computation before the first layer. 'skip_input' is only allowed\n when input_size == num_units; 'auto_select' implies 'skip_input' when\n input_size == num_units; otherwise, it implies 'linear_input'.\ndirection: Indicates whether a bidirectional model will be used. Should be\n \"unidirectional\" or \"bidirectional\".\ndropout: Dropout probability. When set to 0., dropout is disabled.\nseed: The 1st part of a seed to initialize dropout.\nseed2: The 2nd part of a seed to initialize dropout.\ninput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, input_size]. If time_major is false, the shape is\n [batch_size, seq_length, input_size].\ninput_h: If time_major is true, this is a 3-D tensor with the shape of\n [num_layer * dir, batch_size, num_units]. If time_major is false, the shape\n is [batch_size, num_layer * dir, num_units].\ninput_c: For LSTM, a 3-D tensor with the shape of\n [num_layer * dir, batch, num_units]. For other models, it is ignored.\nparams: A 1-D tensor that contains the weights and biases in an opaque layout.\n The size must be created through CudnnRNNParamsSize, and initialized\n separately. Note that they might not be compatible across different\n generations. So it is a good idea to save and restore\nsequence_lengths: a vector of lengths of each input sequence.\noutput: If time_major is true, this is a 3-D tensor with the shape of\n [seq_length, batch_size, dir * num_units]. If time_major is false, the\n shape is [batch_size, seq_length, dir * num_units].\noutput_h: The same shape has input_h.\noutput_c: The same shape as input_c for LSTM. An empty tensor for other models.\nis_training: Indicates whether this operation is used for inference or\n training.\ntime_major: Indicates whether the input/output format is time major or batch\n major.\nreserve_space: An opaque tensor that can be used in backprop calculation. It\n is only produced if is_training is true.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_h","typeAttr":"T"},{"name":"input_c","typeAttr":"T"},{"name":"params","typeAttr":"T"},{"name":"sequence_lengths","type":3}],"outputs":[{"name":"output","typeAttr":"T"},{"name":"output_h","typeAttr":"T"},{"name":"output_c","typeAttr":"T"},{"name":"reserve_space","typeAttr":"T"},{"name":"host_reserved","type":6}],"summary":"A RNN backed by cuDNN."}},{"name":"Cumprod","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumprod.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumprod, which means that the first\nelement of the input is identical to the first element of the output:\n\n```python\ntf.cumprod([a, b, c]) # => [a, a * b, a * b * c]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumprod is\nperformed instead:\n\n```python\ntf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b]\n```\n\nBy setting the `reverse` kwarg to `True`, the cumprod is performed in the\nopposite direction:\n\n```python\ntf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c]\n```\n\nThis is more efficient than using separate `tf.reverse` ops.\n\nThe `reverse` and `exclusive` kwargs can also be combined:\n\n```python\ntf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1]\n```","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float32`, `float64`,\n`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n`complex128`, `qint8`, `quint8`, `qint32`, `half`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative product of the tensor `x` along `axis`."}},{"name":"Cumsum","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumsum.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumsum, which means that the first\nelement of the input is identical to the first element of the output:\n\n```python\ntf.cumsum([a, b, c]) # => [a, a + b, a + b + c]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumsum is\nperformed instead:\n\n```python\ntf.cumsum([a, b, c], exclusive=True) # => [0, a, a + b]\n```\n\nBy setting the `reverse` kwarg to `True`, the cumsum is performed in the\nopposite direction:\n\n```python\ntf.cumsum([a, b, c], reverse=True) # => [a + b + c, b + c, c]\n```\n\nThis is more efficient than using separate `tf.reverse` ops.\n\nThe `reverse` and `exclusive` kwargs can also be combined:\n\n```python\ntf.cumsum([a, b, c], exclusive=True, reverse=True) # => [b + c, c, 0]\n```","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float32`, `float64`,\n`int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`,\n`complex128`, `qint8`, `quint8`, `qint32`, `half`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative sum of the tensor `x` along `axis`."}},{"name":"CumulativeLogsumexp","schema":{"attributes":[{"default":false,"description":"If `True`, perform exclusive cumulative log-sum-exp.","name":"exclusive","type":"boolean"},{"default":false,"description":"A `bool` (default: False).","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"By default, this op performs an inclusive cumulative log-sum-exp,\nwhich means that the first\nelement of the input is identical to the first element of the output:\n```python\ntf.math.cumulative_logsumexp([a, b, c]) # => [a, log(exp(a) + exp(b)), log(exp(a) + exp(b) + exp(c))]\n```\n\nBy setting the `exclusive` kwarg to `True`, an exclusive cumulative log-sum-exp is\nperformed instead:\n```python\ntf.cumulative_logsumexp([a, b, c], exclusive=True) # => [-inf, a, log(exp(a) * exp(b))]\n```\nNote that the neutral element of the log-sum-exp operation is `-inf`,\nhowever, for performance reasons, the minimal value representable by the\nfloating point type is used instead.\n\nBy setting the `reverse` kwarg to `True`, the cumulative log-sum-exp is performed in the\nopposite direction.","inputs":[{"description":"A `Tensor`. Must be one of the following types: `float16`, `float32`, `float64`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: 0). Must be in the range\n`[-rank(x), rank(x))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"name":"out","typeAttr":"T"}],"summary":"Compute the cumulative product of the tensor `x` along `axis`."}},{"name":"DataFormatDimMap","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"NHWC","description":"source data format.","name":"src_format","type":"string"},{"default":"NCHW","description":"destination data format.","name":"dst_format","type":"string"}],"description":"the source data format.","inputs":[{"description":"A Tensor with each element as a dimension index in source data format.\nMust be in the range [-4, 4).","name":"x","typeAttr":"T"}],"outputs":[{"description":"A Tensor with each element as a dimension index in destination data format.","name":"y","typeAttr":"T"}],"summary":"Returns the dimension index in the destination data format given the one in"}},{"name":"DataFormatVecPermute","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"NHWC","description":"source data format.","name":"src_format","type":"string"},{"default":"NCHW","description":"destination data format.","name":"dst_format","type":"string"}],"description":"one in the source data format.","inputs":[{"description":"Vector of size 4 or Tensor of shape (4, 2) in source data format.","name":"x","typeAttr":"T"}],"outputs":[{"description":"Vector of size 4 or Tensor of shape (4, 2) in destination data format.","name":"y","typeAttr":"T"}],"summary":"Returns the permuted vector/tensor in the destination data format given the"}},{"name":"DataServiceDataset","schema":{"attributes":[{"default":-1,"name":"task_refresh_interval_hint_ms","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"dataset_id","type":9},{"name":"processing_mode","type":7},{"name":"address","type":7},{"name":"protocol","type":7},{"name":"job_name","type":7},{"name":"max_outstanding_requests","type":9},{"name":"iteration_counter","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that reads data from the tf.data service."}},{"name":"DatasetCardinality","schema":{"description":"Returns the cardinality of `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return cardinality for.","name":"input_dataset","type":21}],"outputs":[{"description":"The cardinality of `input_dataset`. Named constants are used to represent\ninfinite and unknown cardinality.","name":"cardinality","type":9}],"summary":"Returns the cardinality of `input_dataset`."}},{"name":"DatasetFromGraph","schema":{"description":"Creates a dataset from the provided `graph_def`.","inputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph_def","type":7}],"outputs":[{"description":"A variant tensor representing the dataset.","name":"handle","type":21}],"summary":"Creates a dataset from the given `graph_def`."}},{"name":"DatasetToGraph","schema":{"attributes":[{"default":[],"minimum":0,"name":"stateful_whitelist","type":"string[]"},{"default":false,"name":"allow_stateful","type":"boolean"},{"default":false,"name":"strip_device_assignment","type":"boolean"}],"description":"Returns a graph representation for `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return the graph representation for.","name":"input_dataset","type":21}],"outputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph","type":7}],"summary":"Returns a serialized GraphDef representing `input_dataset`."}},{"name":"DatasetToGraphV2","schema":{"attributes":[{"default":0,"name":"external_state_policy","type":"int64"},{"default":false,"name":"strip_device_assignment","type":"boolean"}],"description":"Returns a graph representation for `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return the graph representation for.","name":"input_dataset","type":21}],"outputs":[{"description":"The graph representation of the dataset (as serialized GraphDef).","name":"graph","type":7}],"summary":"Returns a serialized GraphDef representing `input_dataset`."}},{"name":"DatasetToSingleElement","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to a dataset that contains a single element.","name":"dataset","type":21}],"outputs":[{"description":"The components of the single element of `input`.","name":"components","typeListAttr":"output_types"}],"summary":"Outputs the single element from the given dataset."}},{"name":"DatasetToTFRecord","schema":{"inputs":[{"description":"A variant tensor representing the dataset to write.","name":"input_dataset","type":21},{"description":"A scalar string tensor representing the filename to use.","name":"filename","type":7},{"description":"A scalar string tensor containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7}],"summary":"Writes the given dataset to the given file using the TFRecord format."}},{"name":"Dawsn","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"DebugGradientIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This op is hidden from public in Python. It is used by TensorFlow Debugger to\nregister gradient tensors for gradient debugging.\nThis op operates on non-reference-type tensors.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Identity op for gradient debugging."}},{"name":"DebugGradientRefIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This op is hidden from public in Python. It is used by TensorFlow Debugger to\nregister gradient tensors for gradient debugging.\nThis op operates on reference-type tensors.","inputs":[{"isRef":true,"name":"input","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output","typeAttr":"T"}],"summary":"Identity op for gradient debugging."}},{"name":"DebugIdentity","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"Name of the device on which the tensor resides.","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011","name":"debug_urls","type":"string[]"},{"default":false,"description":"Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Provides an identity mapping of the non-Ref type input tensor for debugging.","inputs":[{"description":"Input tensor, non-Reference type","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Provides an identity mapping of the non-Ref type input tensor for debugging."}},{"name":"DebugIdentityV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"A tfdbg-generated ID for the context that the op belongs to,\n e.g., a concrete compiled tf.function.","name":"tfdbg_context_id","type":"string"},{"default":"","description":"Optional. Name of the op that the debug op is concerned with.\n Used only for single-tensor trace.","name":"op_name","type":"string"},{"default":-1,"description":"Optional. Output slot index of the tensor that the debug op\n is concerned with. Used only for single-tensor trace.","name":"output_slot","type":"int64"},{"default":-1,"description":"TensorDebugMode enum value. See debug_event.proto for details.","name":"tensor_debug_mode","type":"int64"},{"default":[],"description":"List of URLs to debug targets, e.g., file:///foo/tfdbg_dump.","name":"debug_urls","type":"string[]"},{"default":1000,"name":"circular_buffer_size","type":"int64"},{"default":"","name":"tfdbg_run_id","type":"string"}],"description":"Provides an identity mapping from input to output, while writing the content of\nthe input tensor by calling DebugEventsWriter.\n\nThe semantics of the input tensor depends on tensor_debug_mode. In typical\nusage, the input tensor comes directly from the user computation only when\ngraph_debug_mode is FULL_TENSOR (see protobuf/debug_event.proto for a\nlist of all the possible values of graph_debug_mode). For the other debug modes,\nthe input tensor should be produced by an additional op or subgraph that\ncomputes summary information about one or more tensors.","inputs":[{"description":"Input tensor, non-Reference type","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Debug Identity V2 Op."}},{"name":"DebugNanCount","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.","name":"debug_urls","type":"string[]"},{"default":false,"description":" Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Counts number of NaNs in the input tensor, for debugging.","inputs":[{"description":"Input tensor, non-Reference type.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":9}],"summary":"Debug NaN Value Counter Op."}},{"name":"DebugNumericSummary","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","name":"device_name","type":"string"},{"default":"","description":"Name of the input tensor.","name":"tensor_name","type":"string"},{"default":[],"description":"List of URLs to debug targets, e.g.,\n file:///foo/tfdbg_dump, grpc:://localhost:11011.","name":"debug_urls","type":"string[]"},{"default":"-NaN","description":"(float) The lower bound <= which values will be included in the\n generalized -inf count. Default: -inf.","name":"lower_bound","type":"float32"},{"default":"NaN","description":"(float) The upper bound >= which values will be included in the\n generalized +inf count. Default: +inf.","name":"upper_bound","type":"float32"},{"default":false,"description":"(bool) Do not send data to the debug URLs unless at least one\n of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and\n inf counts) is non-zero.","name":"mute_if_healthy","type":"boolean"},{"default":false,"description":"Whether this op will be gated. If any of the debug_urls of this\n debug node is of the grpc:// scheme, when the value of this attribute is set\n to True, the data will not actually be sent via the grpc stream unless this\n debug op has been enabled at the debug_url. If all of the debug_urls of this\n debug node are of the grpc:// scheme and the debug op is enabled at none of\n them, the output will be an empty Tensor.","name":"gated_grpc","type":"boolean"}],"description":"Provide a basic summary of numeric value types, range and distribution.\n\noutput: A double tensor of shape [14 + nDimensions], where nDimensions is the\n number of dimensions of the tensor's shape. The elements of output are:\n [0]: is initialized (1.0) or not (0.0).\n [1]: total number of elements\n [2]: NaN element count\n [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by\n default.\n [4]: negative element count (excluding -inf), if lower_bound is the default\n -inf. Otherwise, this is the count of elements > lower_bound and < 0.\n [5]: zero element count\n [6]: positive element count (excluding +inf), if upper_bound is the default\n +inf. Otherwise, this is the count of elements < upper_bound and > 0.\n [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by\n default.\nOutput elements [1:8] are all zero, if the tensor is uninitialized.\n [8]: minimum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: +inf.\n [9]: maximum of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: -inf.\n [10]: mean of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [11]: variance of all non-inf and non-NaN elements.\n If uninitialized or no such element exists: NaN.\n [12]: Data type of the tensor encoded as an enum integer. See the DataType\n proto for more details.\n [13]: Number of dimensions of the tensor (ndims).\n [14+]: Sizes of the dimensions.\n","inputs":[{"description":"Input tensor, non-Reference type.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":2}],"summary":"Debug Numeric Summary Op."}},{"name":"DebugNumericSummaryV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Optional. The type of the output. Can be float32 or float64 (default: float32). Must be one of the following: `float32`, `float64`.","name":"output_dtype","type":"type"},{"name":"T","type":"type"},{"default":-1,"description":"Tensor debug mode: the mode in which the input tensor is summarized\n by the op. See the TensorDebugMode enum in\n tensorflow/core/protobuf/debug_event.proto for details.\n\nSupported values:\n 2 (CURT_HEALTH): Output a float32/64 tensor of shape [2]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is a bit which is set to 1 if the input tensor has an\n infinity or nan value, or zero otherwise.\n\n 3 (CONCISE_HEALTH): Output a float32/64 tensor of shape [5]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The\n remaining four slots are the total number of elements, -infs,\n +infs, and nans in the input tensor respectively.\n\n 4 (FULL_HEALTH): Output a float32/64 tensor of shape [11]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The remaining elements hold the total number of elements, -infs,\n +infs, nans, negative finite numbers, zeros, and positive finite\n numbers in the input tensor respectively.\n\n 5 (SHAPE): Output a float32/64 tensor of shape [10]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 3rd element holds the rank of the tensor. The 4th element holds\n the number of elements within the tensor. Finally the remaining 6\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated.\n\n 6 (FULL_NUMERICS): Output a float32/64 tensor of shape [22]. The 1st\n element is the tensor_id, if provided, and -1 otherwise. The 2nd\n element is the device_id, if provided, and -1 otherwise. The 3rd\n element holds the datatype value of the input tensor as according\n to the enumerated type in tensorflow/core/framework/types.proto.\n The 4th element holds the rank of the tensor. The 5th to 11th\n elements hold the shape of the tensor. If the rank of the tensor\n is lower than 6, the shape is right padded with zeros. If the rank\n is greater than 6, the head of the shape is truncated. The 12th to\n 18th elements hold the number of elements, -infs, +infs, nans,\n denormal floats, negative finite numbers, zeros, and positive\n finite numbers in the input tensor respectively. The final four\n elements hold the min value, max value, mean, and variance of the\n input tensor.\n\n 8 (REDUCE_INF_NAN_THREE_SLOTS): Output a float32/64 tensor of shape\n [3]. The 1st element is -inf if any elements of the input tensor\n is -inf, or zero otherwise. The 2nd element is +inf if any elements\n of the input tensor is +inf, or zero otherwise. The 3rd element is\n nan if any element of the input tensor is nan, or zero otherwise.","name":"tensor_debug_mode","type":"int64"},{"default":-1,"description":"Optional. An integer identifier for the tensor being summarized by this op.","name":"tensor_id","type":"int64"}],"description":"Computes a numeric summary of the input tensor. The shape of the output\ndepends on the tensor_debug_mode attribute.\nThis op is used internally by TensorFlow Debugger (tfdbg) v2.","inputs":[{"description":"Input tensor, to be summarized by the op.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"output_dtype"}],"summary":"Debug Numeric Summary V2 Op."}},{"name":"DecodeAndCropJpeg","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":1,"description":"Downscaling ratio.","name":"ratio","type":"int64"},{"default":true,"description":"If true use a slower but nicer upscaling of the\nchroma planes (yuv420/422 only).","name":"fancy_upscaling","type":"boolean"},{"default":false,"description":"If true try to recover an image from truncated input.","name":"try_recover_truncated","type":"boolean"},{"default":1,"description":"The minimum required fraction of lines before a truncated\ninput is accepted.","name":"acceptable_fraction","type":"float32"},{"default":"","description":"string specifying a hint about the algorithm used for\ndecompression. Defaults to \"\" which maps to a system-specific\ndefault. Currently valid values are [\"INTEGER_FAST\",\n\"INTEGER_ACCURATE\"]. The hint may be ignored (e.g., the internal\njpeg library changes to a version that does not have that specific\noption.)","name":"dct_method","type":"string"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the JPEG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n\nIf needed, the JPEG-encoded image is transformed to match the requested number\nof color channels.\n\nThe attr `ratio` allows downscaling the image by an integer factor during\ndecoding. Allowed values are: 1, 2, 4, and 8. This is much faster than\ndownscaling the image later.\n\n\nIt is equivalent to a combination of decode and crop, but much faster by only\ndecoding partial jpeg image.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7},{"description":"1-D. The crop window: [crop_y, crop_x, crop_height, crop_width].","name":"crop_window","type":3}],"outputs":[{"description":"3-D with shape `[height, width, channels]`..","name":"image","type":4}],"summary":"Decode and Crop a JPEG-encoded image to a uint8 tensor."}},{"name":"DecodeBase64","schema":{"description":"Input may or may not have padding at the end. See EncodeBase64 for padding.\nWeb-safe means that input must use - and _ instead of + and /.","inputs":[{"description":"Base64 strings to decode.","name":"input","type":7}],"outputs":[{"description":"Decoded strings.","name":"output","type":7}],"summary":"Decode web-safe base64-encoded strings."}},{"name":"DecodeBmp","schema":{"attributes":[{"default":0,"name":"channels","type":"int64"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the BMP-encoded image.\n* 3: output an RGB image.\n* 4: output an RGBA image.","inputs":[{"description":"0-D. The BMP-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`. RGB order","name":"image","type":4}],"summary":"Decode the first frame of a BMP-encoded image to a uint8 tensor."}},{"name":"DecodeCSV","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"OUT_TYPE","type":"type[]"},{"default":",","description":"char delimiter to separate fields in a record.","name":"field_delim","type":"string"},{"default":true,"description":"If false, treats double quotation marks as regular\ncharacters inside of the string fields (ignoring RFC 4180, Section 2,\nBullet 5).","name":"use_quote_delim","type":"boolean"},{"default":"","description":"Additional string to recognize as NA/NaN.","name":"na_value","type":"string"},{"default":[],"name":"select_cols","type":"int64[]"}],"description":"RFC 4180 format is expected for the CSV records.\n(https://tools.ietf.org/html/rfc4180)\nNote that we allow leading and trailing spaces with int or float field.","inputs":[{"description":"Each string is a record/row in the csv and all records should have\nthe same format.","name":"records","type":7},{"description":"One tensor per column of the input record, with either a\nscalar default value for that column or an empty vector if the column is\nrequired.","name":"record_defaults","typeListAttr":"OUT_TYPE"}],"outputs":[{"description":"Each tensor will have the same shape as records.","name":"output","typeListAttr":"OUT_TYPE"}],"summary":"Convert CSV records to tensors. Each column maps to one tensor."}},{"name":"DecodeCompressed","schema":{"attributes":[{"default":"","description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":"string"}],"description":"This op decompresses each element of the `bytes` input `Tensor`, which\nis assumed to be compressed using the given `compression_type`.\n\nThe `output` is a string `Tensor` of the same shape as `bytes`,\neach element containing the decompressed data from the corresponding\nelement in `bytes`.","inputs":[{"description":"A Tensor of string which is compressed.","name":"bytes","type":7}],"outputs":[{"description":"A Tensor with the same shape as input `bytes`, uncompressed\nfrom bytes.","name":"output","type":7}],"summary":"Decompress strings."}},{"name":"DecodeGif","schema":{"description":"GIF images with frame or transparency compression are not supported.\nOn Linux and MacOS systems, convert animated GIFs from compressed to\nuncompressed by running:\n\n convert $src.gif -coalesce $dst.gif\n\nThis op also supports decoding JPEGs and PNGs, though it is cleaner to use\n`tf.io.decode_image`.","inputs":[{"description":"0-D. The GIF-encoded image.","name":"contents","type":7}],"outputs":[{"description":"4-D with shape `[num_frames, height, width, 3]`. RGB channel order.","name":"image","type":4}],"summary":"Decode the frame(s) of a GIF-encoded image to a uint8 tensor."}},{"name":"DecodeImage","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":{"type":"type","value":4},"description":"The desired DType of the returned Tensor. Must be one of the following: `uint8`, `uint16`, `float32`.","name":"dtype","type":"type"},{"default":true,"description":"Controls the output shape of the returned op. If True, the returned op will\nproduce a 3-D tensor for PNG, JPEG, and BMP files; and a 4-D tensor for all\nGIFs, whether animated or not. If, False, the returned op will produce a 3-D\ntensor for all file types and will truncate animated GIFs to the first frame.","name":"expand_animations","type":"boolean"}],"description":"Detects whether an image is a BMP, GIF, JPEG, or PNG, and performs the\nappropriate operation to convert the input bytes string into a Tensor of type\ndtype.\n\n*NOTE*: decode_gif returns a 4-D array [num_frames, height, width, 3], as\nopposed to decode_bmp, decode_jpeg and decode_png, which return 3-D arrays\n[height, width, num_channels]. Make sure to take this into account when\nconstructing your graph if you are intermixing GIF files with BMP, JPEG, and/or\nPNG files. Alternately, set the expand_animations argument of this function to\nFalse, in which case the op will return 3-dimensional tensors and will truncate\nanimated GIF files to the first frame.","inputs":[{"description":"0-D. The encoded image bytes.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]` or 4-D with shape\n`[frame, height, width, channels]`..","name":"image","typeAttr":"dtype"}],"summary":"Function for decode_bmp, decode_gif, decode_jpeg, and decode_png."}},{"name":"DecodeJSONExample","schema":{"description":"This op translates a tensor containing Example records, encoded using\nthe [standard JSON\nmapping](https://developers.google.com/protocol-buffers/docs/proto3#json),\ninto a tensor containing the same records encoded as binary protocol\nbuffers. The resulting tensor can then be fed to any of the other\nExample-parsing ops.","inputs":[{"description":"Each string is a JSON object serialized according to the JSON\nmapping of the Example proto.","name":"json_examples","type":7}],"outputs":[{"description":"Each string is a binary Example protocol buffer corresponding\nto the respective element of `json_examples`.","name":"binary_examples","type":7}],"summary":"Convert JSON-encoded Example records to binary protocol buffer strings."}},{"name":"DecodeJpeg","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":1,"description":"Downscaling ratio.","name":"ratio","type":"int64"},{"default":true,"description":"If true use a slower but nicer upscaling of the\nchroma planes (yuv420/422 only).","name":"fancy_upscaling","type":"boolean"},{"default":false,"description":"If true try to recover an image from truncated input.","name":"try_recover_truncated","type":"boolean"},{"default":1,"description":"The minimum required fraction of lines before a truncated\ninput is accepted.","name":"acceptable_fraction","type":"float32"},{"default":"","description":"string specifying a hint about the algorithm used for\ndecompression. Defaults to \"\" which maps to a system-specific\ndefault. Currently valid values are [\"INTEGER_FAST\",\n\"INTEGER_ACCURATE\"]. The hint may be ignored (e.g., the internal\njpeg library changes to a version that does not have that specific\noption.)","name":"dct_method","type":"string"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the JPEG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n\nIf needed, the JPEG-encoded image is transformed to match the requested number\nof color channels.\n\nThe attr `ratio` allows downscaling the image by an integer factor during\ndecoding. Allowed values are: 1, 2, 4, and 8. This is much faster than\ndownscaling the image later.\n\n\nThis op also supports decoding PNGs and non-animated GIFs since the interface is\nthe same, though it is cleaner to use `tf.io.decode_image`.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`..","name":"image","type":4}],"summary":"Decode a JPEG-encoded image to a uint8 tensor."}},{"name":"DecodePaddedRaw","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`.","name":"out_type","type":"type"},{"default":true,"description":"Whether the input `input_bytes` is in little-endian order. Ignored for\n`out_type` values that are stored in a single byte, like `uint8`","name":"little_endian","type":"boolean"}],"inputs":[{"description":"Tensor of string to be decoded.","name":"input_bytes","type":7},{"description":"Length in bytes for each element of the decoded output. Must be a multiple\nof the size of the output type.","name":"fixed_length","type":3}],"outputs":[{"description":"A Tensor with one more dimension than the input `bytes`. The added dimension\nwill have size equal to the length of the elements of `bytes` divided by the\nnumber of bytes to represent `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Reinterpret the bytes of a string as a vector of numbers."}},{"name":"DecodePng","schema":{"attributes":[{"default":0,"description":"Number of color channels for the decoded image.","name":"channels","type":"int64"},{"default":{"type":"type","value":4},"description":"Must be one of the following: `uint8`, `uint16`.","name":"dtype","type":"type"}],"description":"The attr `channels` indicates the desired number of color channels for the\ndecoded image.\n\nAccepted values are:\n\n* 0: Use the number of channels in the PNG-encoded image.\n* 1: output a grayscale image.\n* 3: output an RGB image.\n* 4: output an RGBA image.\n\nIf needed, the PNG-encoded image is transformed to match the requested number\nof color channels.\n\nThis op also supports decoding JPEGs and non-animated GIFs since the interface\nis the same, though it is cleaner to use `tf.io.decode_image`.","inputs":[{"description":"0-D. The PNG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","typeAttr":"dtype"}],"summary":"Decode a PNG-encoded image to a uint8 or uint16 tensor."}},{"name":"DecodeProtoV2","schema":{"attributes":[{"description":"Name of the proto message type to decode.","name":"message_type","type":"string"},{"description":"List of strings containing proto field names. An extension field can be decoded\nby using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME.","name":"field_names","type":"string[]"},{"description":"List of TF types to use for the respective field in field_names.","minimum":0,"name":"output_types","type":"type[]"},{"default":"local://","description":"Either the special value `local://` or a path to a file containing\na serialized `FileDescriptorSet`.","name":"descriptor_source","type":"string"},{"default":"binary","description":"Either `binary` or `text`.","name":"message_format","type":"string"},{"default":false,"description":"Whether to sanitize the result or not.","name":"sanitize","type":"boolean"}],"description":"The `decode_proto` op extracts fields from a serialized protocol buffers\nmessage into tensors. The fields in `field_names` are decoded and converted\nto the corresponding `output_types` if possible.\n\nA `message_type` name must be provided to give context for the field names.\nThe actual message descriptor can be looked up either in the linked-in\ndescriptor pool or a filename provided by the caller using the\n`descriptor_source` attribute.\n\nEach output tensor is a dense tensor. This means that it is padded to hold\nthe largest number of repeated elements seen in the input minibatch. (The\nshape is also padded by one to prevent zero-sized dimensions). The actual\nrepeat counts for each example in the minibatch can be found in the `sizes`\noutput. In many cases the output of `decode_proto` is fed immediately into\ntf.squeeze if missing values are not a concern. When using tf.squeeze, always\npass the squeeze dimension explicitly to avoid surprises.\n\nFor the most part, the mapping between Proto field types and TensorFlow dtypes\nis straightforward. However, there are a few special cases:\n\n- A proto field that contains a submessage or group can only be converted\nto `DT_STRING` (the serialized submessage). This is to reduce the complexity\nof the API. The resulting string can be used as input to another instance of\nthe decode_proto op.\n\n- TensorFlow lacks support for unsigned integers. The ops represent uint64\ntypes as a `DT_INT64` with the same twos-complement bit pattern (the obvious\nway). Unsigned int32 values can be represented exactly by specifying type\n`DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in\nthe `output_types` attribute.\n\nBoth binary and text proto serializations are supported, and can be\nchosen using the `format` attribute.\n\nThe `descriptor_source` attribute selects the source of protocol\ndescriptors to consult when looking up `message_type`. This may be:\n\n- An empty string or \"local://\", in which case protocol descriptors are\ncreated for C++ (not Python) proto definitions linked to the binary.\n\n- A file, in which case protocol descriptors are created from the file,\nwhich is expected to contain a `FileDescriptorSet` serialized as a string.\nNOTE: You can build a `descriptor_source` file using the `--descriptor_set_out`\nand `--include_imports` options to the protocol compiler `protoc`.\n\n- A \"bytes://\", in which protocol descriptors are created from ``,\nwhich is expected to be a `FileDescriptorSet` serialized as a string.","inputs":[{"description":"Tensor of serialized protos with shape `batch_shape`.","name":"bytes","type":7}],"outputs":[{"description":"Tensor of int32 with shape `[batch_shape, len(field_names)]`.\nEach entry is the number of values found for the corresponding field.\nOptional fields may have 0 or 1 values.","name":"sizes","type":3},{"description":"List of tensors containing values for the corresponding field.\n`values[i]` has datatype `output_types[i]`\nand shape `[batch_shape, max(sizes[...,i])]`.","name":"values","typeListAttr":"output_types"}],"summary":"The op extracts fields from a serialized protocol buffers message into tensors."}},{"name":"DecodeRaw","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`, `complex64`, `complex128`, `bool`.","name":"out_type","type":"type"},{"default":true,"description":"Whether the input `bytes` are in little-endian order.\nIgnored for `out_type` values that are stored in a single byte like\n`uint8`.","name":"little_endian","type":"boolean"}],"inputs":[{"description":"All the elements must have the same length.","name":"bytes","type":7}],"outputs":[{"description":"A Tensor with one more dimension than the input `bytes`. The\nadded dimension will have size equal to the length of the elements\nof `bytes` divided by the number of bytes to represent `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Reinterpret the bytes of a string as a vector of numbers."}},{"name":"DecodeWav","schema":{"attributes":[{"default":-1,"description":"Number of sample channels wanted.","name":"desired_channels","type":"int64"},{"default":-1,"description":"Length of audio requested.","name":"desired_samples","type":"int64"}],"description":"The -32768 to 32767 signed 16-bit values will be scaled to -1.0 to 1.0 in float.\n\nWhen desired_channels is set, if the input contains fewer channels than this\nthen the last channel will be duplicated to give the requested number, else if\nthe input has more channels than requested then the additional channels will be\nignored.\n\nIf desired_samples is set, then the audio will be cropped or padded with zeroes\nto the requested length.\n\nThe first output contains a Tensor with the content of the audio samples. The\nlowest dimension will be the number of channels, and the second will be the\nnumber of samples. For example, a ten-sample-long stereo WAV file should give an\noutput shape of [10, 2].","inputs":[{"description":"The WAV-encoded audio, usually from a file.","name":"contents","type":7}],"outputs":[{"description":"2-D with shape `[length, channels]`.","name":"audio","type":1},{"description":"Scalar holding the sample rate found in the WAV header.","name":"sample_rate","type":3}],"summary":"Decode a 16-bit PCM WAV file to a float tensor."}},{"name":"DeepCopy","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The source tensor of type `T`.","name":"x","typeAttr":"T"}],"outputs":[{"description":" y: A `Tensor` of type `T`. A copy of `x`. Guaranteed that `y`\n is not an alias of `x`.","name":"y","typeAttr":"T"}],"summary":"Makes a copy of `x`."}},{"name":"DeleteIterator","schema":{"inputs":[{"description":"A handle to the iterator to delete.","name":"handle","type":20},{"description":"A variant deleter.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"DeleteMemoryCache","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteMultiDeviceIterator","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"}],"inputs":[{"description":"A handle to the multi device iterator to delete.","name":"multi_device_iterator","type":20},{"description":"A list of iterator handles (unused). This is added so that automatic control dependencies get added during function tracing that ensure this op runs after all the dependent iterators are deleted.","name":"iterators","numberAttr":"N","type":20},{"description":"A variant deleter.","name":"deleter","type":21}],"summary":"A container for an iterator resource."}},{"name":"DeleteRandomSeedGenerator","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteSeedGenerator","schema":{"inputs":[{"name":"handle","type":20},{"name":"deleter","type":21}]}},{"name":"DeleteSessionTensor","schema":{"inputs":[{"description":"The handle for a tensor stored in the session state.","name":"handle","type":7}],"summary":"Delete the tensor specified by its handle in the session."}},{"name":"DenseBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"1D or 2D int `Tensor`.","name":"input","typeAttr":"Tidx"},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"DenseCountSparseOutput","schema":{"attributes":[{"description":"Dtype of the input values tensor. Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing data to count.","name":"values","typeAttr":"T"},{"description":"A Tensor of the same shape as indices containing per-index weight values. May\nalso be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.","name":"output_dense_shape","type":9}],"summary":"Performs sparse-output bin counting for a tf.tensor input."}},{"name":"DenseToCSRSparseMatrix","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"description":"A Dense tensor.","name":"dense_input","typeAttr":"T"},{"description":"Indices of nonzero elements.","name":"indices","type":9}],"outputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_output","type":21}],"summary":"Converts a dense tensor to a (possibly batched) CSRSparseMatrix."}},{"name":"DenseToDenseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set1","typeAttr":"T"},{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set2","typeAttr":"T"}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of 2 `Tensor` inputs."}},{"name":"DenseToSparseBatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to an input dataset. Must have a single component.","name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A vector representing the dense shape of each row in the produced\nSparseTensor. The shape may be partially specified, using `-1` to indicate\nthat a particular dimension should use the maximum size of all batch elements.","name":"row_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches input elements into a SparseTensor."}},{"name":"DenseToSparseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nInput `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`,\nand `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same\nas `set1`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set2`\nindices.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"`Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`.\nDimension `n` contains values in a set, duplicates are allowed but ignored.","name":"set1","typeAttr":"T"},{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set2_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set2_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must\nbe the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the\nmax set size across `n-1` dimensions.","name":"set2_shape","type":9}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of `Tensor` and `SparseTensor`."}},{"name":"DepthToSpace","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The size of the spatial block, same as in Space2Depth.","minimum":2,"name":"block_size","type":"int64"},{"default":"NHWC","description":"Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"description":"Rearranges data from depth into blocks of spatial data.\nThis is the reverse transformation of SpaceToDepth. More specifically,\nthis op outputs a copy of the input tensor where values from the `depth`\ndimension are moved in spatial blocks to the `height` and `width` dimensions.\nThe attr `block_size` indicates the input block size and how the data is moved.\n\n * Chunks of data of size `block_size * block_size` from depth are rearranged\n into non-overlapping blocks of size `block_size x block_size`\n * The width the output tensor is `input_depth * block_size`, whereas the\n height is `input_height * block_size`.\n * The Y, X coordinates within each block of the output image are determined\n by the high order component of the input channel index.\n * The depth of the input tensor must be divisible by\n `block_size * block_size`.\n\nThe `data_format` attr specifies the layout of the input and output tensors\nwith the following options:\n \"NHWC\": `[ batch, height, width, channels ]`\n \"NCHW\": `[ batch, channels, height, width ]`\n \"NCHW_VECT_C\":\n `qint8 [ batch, channels / 4, height, width, 4 ]`\n\nIt is useful to consider the operation as transforming a 6-D Tensor.\ne.g. for data_format = NHWC,\n Each element in the input tensor can be specified via 6 coordinates,\n ordered by decreasing memory layout significance as:\n n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates\n within the input image, bX, bY means coordinates\n within the output block, oC means output channels).\n The output would be the input transposed to the following layout:\n n,iY,bY,iX,bX,oC\n\nThis operation is useful for resizing the activations between convolutions\n(but keeping all data), e.g. instead of pooling. It is also useful for training\npurely convolutional models.\n\nFor example, given an input of shape `[1, 1, 1, 4]`, data_format = \"NHWC\" and\nblock_size = 2:\n\n```\nx = [[[[1, 2, 3, 4]]]]\n\n```\n\nThis operation will output a tensor of shape `[1, 2, 2, 1]`:\n\n```\n [[[[1], [2]],\n [[3], [4]]]]\n```\n\nHere, the input has a batch of 1 and each batch element has shape `[1, 1, 4]`,\nthe corresponding output will have 2x2 elements and will have a depth of\n1 channel (1 = `4 / (block_size * block_size)`).\nThe output element shape is `[2, 2, 1]`.\n\nFor an input tensor with larger depth, here of shape `[1, 1, 1, 12]`, e.g.\n\n```\nx = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]\n```\n\nThis operation, for block size of 2, will return the following tensor of shape\n`[1, 2, 2, 3]`\n\n```\n [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n\n```\n\nSimilarly, for the following input of shape `[1 2 2 4]`, and a block size of 2:\n\n```\nx = [[[[1, 2, 3, 4],\n [5, 6, 7, 8]],\n [[9, 10, 11, 12],\n [13, 14, 15, 16]]]]\n```\n\nthe operator will return the following tensor of shape `[1 4 4 1]`:\n\n```\nx = [[[ [1], [2], [5], [6]],\n [ [3], [4], [7], [8]],\n [ [9], [10], [13], [14]],\n [ [11], [12], [15], [16]]]]\n\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"DepthToSpace for tensors of type T."}},{"name":"DepthwiseConv2dNative","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"category":"Layer","description":"Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\nand a filter / kernel tensor of shape\n`[filter_height, filter_width, in_channels, channel_multiplier]`, containing\n`in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies\na different filter to each input channel (expanding from 1 channel to\n`channel_multiplier` channels for each), then concatenates the results\ntogether. Thus, the output has `in_channels * channel_multiplier` channels.\n\n```\nfor k in 0..in_channels-1\n for q in 0..channel_multiplier-1\n output[b, i, j, k * channel_multiplier + q] =\n sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] *\n filter[di, dj, k, q]\n```\n\nMust have `strides[0] = strides[3] = 1`. For the most common case of the same\nhorizontal and vertices strides, `strides = [1, stride, stride, 1]`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors."}},{"name":"DepthwiseConv2dNativeBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"4-D with shape based on `data_format`. For example, if\n`data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height,\nin_width, in_channels]` tensor.","name":"input","typeAttr":"T"},{"description":"An integer vector representing the tensor shape of `filter`,\nwhere `filter` is a 4-D\n`[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor.","name":"filter_sizes","type":3},{"description":"4-D with shape based on `data_format`.\nFor example, if `data_format` is 'NHWC' then\nout_backprop shape is `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`. Gradient w.r.t.\nthe `filter` input of the convolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of depthwise convolution with respect to the filter."}},{"name":"DepthwiseConv2dNativeBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\nof the convolution.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`, `EXPLICIT`.","name":"padding","type":"string"},{"default":[],"name":"explicit_paddings","type":"int64[]"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each filter\nelement on that dimension. The dimension order is determined by the value of\n`data_format`, see above for details. Dilations in the batch and depth\ndimensions must be 1.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"An integer vector representing the shape of `input`, based\non `data_format`. For example, if `data_format` is 'NHWC' then\n `input` is a 4-D `[batch, height, width, channels]` tensor.","name":"input_sizes","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, depthwise_multiplier]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape based on `data_format`.\nFor example, if `data_format` is 'NHWC' then\nout_backprop shape is `[batch, out_height, out_width, out_channels]`.\nGradients w.r.t. the output of the convolution.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape according to `data_format`. For example, if\n`data_format` is 'NHWC', output shape is `[batch, in_height,\nin_width, in_channels]`. Gradient w.r.t. the input of the\nconvolution.","name":"output","typeAttr":"T"}],"summary":"Computes the gradients of depthwise convolution with respect to the input."}},{"name":"Dequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":"MIN_COMBINED","description":"Must be one of the following: `MIN_COMBINED`, `MIN_FIRST`, `SCALED`.","name":"mode","type":"string"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"},{"default":{"type":"type","value":1},"description":"Type of the output tensor. Currently Dequantize supports float and bfloat16.\nIf 'dtype' is 'bfloat16', it only supports 'MIN_COMBINED' mode. Must be one of the following: `bfloat16`, `float32`.","name":"dtype","type":"type"}],"category":"Tensor","description":"[min_range, max_range] are scalar floats that specify the range for\nthe output. The 'mode' attribute controls exactly which calculations are\nused to convert the float values to their quantized equivalents.\n\nIn 'MIN_COMBINED' mode, each value of the tensor will undergo the following:\n\n```\nif T == qint8: in[i] += (range(T) + 1)/ 2.0\nout[i] = min_range + (in[i]* (max_range - min_range) / range(T))\n```\nhere `range(T) = numeric_limits::max() - numeric_limits::min()`\n\n*MIN_COMBINED Mode Example*\n\nIf the input comes from a QuantizedRelu6, the output type is\nquint8 (range of 0-255) but the possible range of QuantizedRelu6 is\n0-6. The min_range and max_range values are therefore 0.0 and 6.0.\nDequantize on quint8 will take each value, cast to float, and multiply\nby 6 / 255.\nNote that if quantizedtype is qint8, the operation will additionally add\neach value by 128 prior to casting.\n\nIf the mode is 'MIN_FIRST', then this approach is used:\n\n```c++\nnum_discrete_values = 1 << (# of bits in T)\nrange_adjust = num_discrete_values / (num_discrete_values - 1)\nrange = (range_max - range_min) * range_adjust\nrange_scale = range / num_discrete_values\nconst double offset_input = static_cast(input) - lowest_quantized;\nresult = range_min + ((input - numeric_limits::min()) * range_scale)\n```\n\nIf the mode is `SCALED`, dequantization is performed by multiplying each\ninput value by a scaling_factor. (Thus an input of 0 always maps to 0.0).\n\nThe scaling_factor is determined from `min_range`, `max_range`, and\n`narrow_range` in a way that is compatible with `QuantizeAndDequantize{V2|V3}`\nand `QuantizeV2`, using the following algorithm:\n\n```c++\n\n const int min_expected_T = std::numeric_limits::min() +\n (narrow_range ? 1 : 0);\n const int max_expected_T = std::numeric_limits::max();\n const float max_expected_T = std::numeric_limits::max();\n\n const float scale_factor =\n (std::numeric_limits::min() == 0) ? (max_range / max_expected_T)\n : std::max(min_range / min_expected_T,\n max_range / max_expected_T);\n```","inputs":[{"name":"input","typeAttr":"T"},{"description":"The minimum scalar value possibly produced for the input.","name":"min_range","type":1},{"description":"The maximum scalar value possibly produced for the input.","name":"max_range","type":1}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Dequantize the 'input' tensor into a float or bfloat16 Tensor."}},{"name":"DeserializeIterator","schema":{"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20},{"description":"A variant tensor storing the state of the iterator contained in the\nresource.","name":"serialized","type":21}],"summary":"Converts the given variant tensor to an iterator and stores it in the given resource."}},{"name":"DeserializeManySparse","schema":{"attributes":[{"description":"The `dtype` of the serialized `SparseTensor` objects.","name":"dtype","type":"type"}],"description":"The input `serialized_sparse` must be a string matrix of shape `[N x 3]` where\n`N` is the minibatch size and the rows correspond to packed outputs of\n`SerializeSparse`. The ranks of the original `SparseTensor` objects\nmust all match. When the final `SparseTensor` is created, it has rank one\nhigher than the ranks of the incoming `SparseTensor` objects\n(they have been concatenated along a new row dimension).\n\nThe output `SparseTensor` object's shape values for all dimensions but the\nfirst are the max across the input `SparseTensor` objects' shape values\nfor the corresponding dimensions. Its first shape value is `N`, the minibatch\nsize.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the serialized input is a `[2 x 3]` matrix representing two\noriginal `SparseTensor` objects:\n\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n\nand\n\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n\nthen the final deserialized `SparseTensor` will be:\n\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]","inputs":[{"description":"2-D, The `N` serialized `SparseTensor` objects.\nMust have 3 columns.","name":"serialized_sparse","type":7}],"outputs":[{"name":"sparse_indices","type":9},{"name":"sparse_values","typeAttr":"dtype"},{"name":"sparse_shape","type":9}],"summary":"Deserialize and concatenate `SparseTensors` from a serialized minibatch."}},{"name":"DeserializeSparse","schema":{"attributes":[{"description":"The `dtype` of the serialized `SparseTensor` objects.","name":"dtype","type":"type"},{"default":{"type":"type","value":7},"description":"Must be one of the following: `string`, `variant`.","name":"Tserialized","type":"type"}],"description":"The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where\nthe last dimension stores serialized `SparseTensor` objects and the other N\ndimensions (N >= 0) correspond to a batch. The ranks of the original\n`SparseTensor` objects must all match. When the final `SparseTensor` is\ncreated, its rank is the rank of the incoming `SparseTensor` objects plus N;\nthe sparse tensors have been concatenated along new dimensions, one for each\nbatch.\n\nThe output `SparseTensor` object's shape values for the original dimensions\nare the max across the input `SparseTensor` objects' shape values for the\ncorresponding dimensions. The new dimensions match the size of the batch.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the serialized input is a `[2 x 3]` matrix representing two\noriginal `SparseTensor` objects:\n\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n\nand\n\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n\nthen the final deserialized `SparseTensor` will be:\n\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]","inputs":[{"description":"The serialized `SparseTensor` objects. The last dimension\nmust have 3 columns.","name":"serialized_sparse","typeAttr":"Tserialized"}],"outputs":[{"name":"sparse_indices","type":9},{"name":"sparse_values","typeAttr":"dtype"},{"name":"sparse_shape","type":9}],"summary":"Deserialize `SparseTensor` objects."}},{"name":"DestroyResourceOp","schema":{"attributes":[{"default":true,"description":"whether to ignore the error when the resource\ndoesn't exist.","name":"ignore_lookup_error","type":"boolean"}],"description":"All subsequent operations using the resource will result in a NotFound\nerror status.","inputs":[{"description":"handle to the resource to delete.","name":"resource","type":20}],"summary":"Deletes the resource specified by the handle."}},{"name":"DestroyTemporaryVariable","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Name of the temporary variable, usually the name of the matching\n'TemporaryVariable' op.","name":"var_name","type":"string"}],"description":"Sets output to the value of the Tensor pointed to by 'ref', then destroys\nthe temporary variable called 'var_name'.\nAll other uses of 'ref' *must* have executed before this op.\nThis is typically achieved by chaining the ref through each assign op, or by\nusing control dependencies.\n\nOutputs the final value of the tensor pointed to by 'ref'.","inputs":[{"description":"A reference to the temporary variable tensor.","isRef":true,"name":"ref","typeAttr":"T"}],"outputs":[{"name":"value","typeAttr":"T"}],"summary":"Destroys the temporary variable and returns its final value."}},{"name":"DeviceIndex","schema":{"attributes":[{"name":"device_names","type":"string[]"}],"description":"Given a list of device names, this operation returns the index of the device\nthis op runs. The length of the list is returned in two cases:\n(1) Device does not exist in the given device list.\n(2) It is in XLA compilation.","outputs":[{"name":"index","type":3}],"summary":"Return the index of device the op runs."}},{"name":"Diag","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Given a `diagonal`, this operation returns a tensor with the `diagonal` and\neverything else padded with zeros. The diagonal is computed as follows:\n\nAssume `diagonal` has dimensions [D1,..., Dk], then the output is a tensor of\nrank 2k with dimensions [D1,..., Dk, D1,..., Dk] where:\n\n`output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]` and 0 everywhere else.\n\nFor example:\n\n```\n# 'diagonal' is [1, 2, 3, 4]\ntf.diag(diagonal) ==> [[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]]\n```","inputs":[{"description":"Rank k tensor where k is at most 1.","name":"diagonal","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns a diagonal tensor with a given diagonal values."}},{"name":"DiagPart","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"This operation returns a tensor with the `diagonal` part\nof the `input`. The `diagonal` part is computed as follows:\n\nAssume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a\ntensor of rank `k` with dimensions `[D1,..., Dk]` where:\n\n`diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`.\n\nFor example:\n\n```\n# 'input' is [[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]]\n\ntf.diag_part(input) ==> [1, 2, 3, 4]\n```","inputs":[{"description":"Rank k tensor where k is even and not zero.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal.","name":"diagonal","typeAttr":"T"}],"summary":"Returns the diagonal part of the tensor."}},{"name":"Digamma","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"`Gamma(x)`), element-wise.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes Psi, the derivative of Lgamma (the log of the absolute value of"}},{"name":"Dilation2D","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The input stride for atrous morphological dilation. Must be:\n`[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"The `input` tensor has shape `[batch, in_height, in_width, depth]` and the\n`filter` tensor has shape `[filter_height, filter_width, depth]`, i.e., each\ninput channel is processed independently of the others with its own structuring\nfunction. The `output` tensor has shape\n`[batch, out_height, out_width, depth]`. The spatial dimensions of the output\ntensor depend on the `padding` algorithm. We currently only support the default\n\"NHWC\" `data_format`.\n\nIn detail, the grayscale morphological 2-D dilation is the max-sum correlation\n(for consistency with `conv2d`, we use unmirrored filters):\n\n output[b, y, x, c] =\n max_{dy, dx} input[b,\n strides[1] * y + rates[1] * dy,\n strides[2] * x + rates[2] * dx,\n c] +\n filter[dy, dx, c]\n\nMax-pooling is a special case when the filter has size equal to the pooling\nkernel size and contains all zeros.\n\nNote on duality: The dilation of `input` by the `filter` is equal to the\nnegation of the erosion of `-input` by the reflected `filter`.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"output","typeAttr":"T"}],"summary":"Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors."}},{"name":"Dilation2DBackpropFilter","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension of\nthe input tensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"1-D of length 4. The input stride for atrous morphological dilation.\nMust be: `[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter_backprop","typeAttr":"T"}],"summary":"Computes the gradient of morphological 2-D dilation with respect to the filter."}},{"name":"Dilation2DBackpropInput","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"1-D of length 4. The stride of the sliding window for each dimension of\nthe input tensor. Must be: `[1, stride_height, stride_width, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"1-D of length 4. The input stride for atrous morphological dilation.\nMust be: `[1, rate_height, rate_width, 1]`.","minimum":4,"name":"rates","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"input","typeAttr":"T"},{"description":"3-D with shape `[filter_height, filter_width, depth]`.","name":"filter","typeAttr":"T"},{"description":"4-D with shape `[batch, out_height, out_width, depth]`.","name":"out_backprop","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, in_height, in_width, depth]`.","name":"in_backprop","typeAttr":"T"}],"summary":"Computes the gradient of morphological 2-D dilation with respect to the input."}},{"name":"DirectedInterleaveDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A dataset of scalar `DT_INT64` elements that determines which of the\n`N` data inputs should produce the next output element.","name":"selector_input_dataset","type":21},{"description":"`N` datasets with the same type that will be interleaved according to\nthe values of `selector_input_dataset`.","name":"data_input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A substitute for `InterleaveDataset` on a fixed list of `N` datasets."}},{"name":"Div","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Div` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise."}},{"name":"DivNoNan","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n*NOTE*: `DivNoNan` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if the denominator is zero."}},{"name":"DrawBoundingBoxes","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float16`.","name":"T","type":"type"}],"description":"Outputs a copy of `images` but draws on top of the pixels zero or more bounding\nboxes specified by the locations in `boxes`. The coordinates of the each\nbounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example, if an image is 100 x 200 pixels (height x width) and the bounding\nbox is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of\nthe bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates).\n\nParts of the bounding box may fall outside the image.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`. A batch of images.","name":"images","typeAttr":"T"},{"description":"3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding\nboxes.","name":"boxes","type":1}],"outputs":[{"description":"4-D with the same shape as `images`. The batch of input images with\nbounding boxes drawn on the images.","name":"output","typeAttr":"T"}],"summary":"Draw bounding boxes on a batch of images."}},{"name":"DrawBoundingBoxesV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float16`.","name":"T","type":"type"}],"description":"Outputs a copy of `images` but draws on top of the pixels zero or more bounding\nboxes specified by the locations in `boxes`. The coordinates of the each\nbounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example, if an image is 100 x 200 pixels (height x width) and the bounding\nbox is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of\nthe bounding box will be `(40, 10)` to `(100, 50)` (in (x,y) coordinates).\n\nParts of the bounding box may fall outside the image.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`. A batch of images.","name":"images","typeAttr":"T"},{"description":"3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding\nboxes.","name":"boxes","type":1},{"description":"2-D. A list of RGBA colors to cycle through for the boxes.","name":"colors","type":1}],"outputs":[{"description":"4-D with the same shape as `images`. The batch of input images with\nbounding boxes drawn on the images.","name":"output","typeAttr":"T"}],"summary":"Draw bounding boxes on a batch of images."}},{"name":"DummyIterationCounter","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DummyMemoryCache","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DummySeedGenerator","schema":{"outputs":[{"name":"handle","type":20}]}},{"name":"DynamicPartition","schema":{"attributes":[{"description":"The number of partitions to output.","minimum":1,"name":"num_partitions","type":"int64"},{"name":"T","type":"type"}],"description":"For each index tuple `js` of size `partitions.ndim`, the slice `data[js, ...]`\nbecomes part of `outputs[partitions[js]]`. The slices with `partitions[js] = i`\nare placed in `outputs[i]` in lexicographic order of `js`, and the first\ndimension of `outputs[i]` is the number of entries in `partitions` equal to `i`.\nIn detail,\n\n```python\n outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]\n\n outputs[i] = pack([data[js, ...] for js if partitions[js] == i])\n```\n\n`data.shape` must start with `partitions.shape`.\n\nFor example:\n\n```python\n # Scalar partitions.\n partitions = 1\n num_partitions = 2\n data = [10, 20]\n outputs[0] = [] # Empty with shape [0, 2]\n outputs[1] = [[10, 20]]\n\n # Vector partitions.\n partitions = [0, 0, 1, 1, 0]\n num_partitions = 2\n data = [10, 20, 30, 40, 50]\n outputs[0] = [10, 20, 50]\n outputs[1] = [30, 40]\n```\n\nSee `dynamic_stitch` for an example on how to merge partitions back.\n\n
    \n\n
    ","inputs":[{"name":"data","typeAttr":"T"},{"description":"Any shape. Indices in the range `[0, num_partitions)`.","name":"partitions","type":3}],"outputs":[{"name":"outputs","numberAttr":"num_partitions","typeAttr":"T"}],"summary":"Partitions `data` into `num_partitions` tensors using indices from `partitions`."}},{"name":"DynamicStitch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Builds a merged tensor such that\n\n```python\n merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]\n```\n\nFor example, if each `indices[m]` is scalar or vector, we have\n\n```python\n # Scalar indices:\n merged[indices[m], ...] = data[m][...]\n\n # Vector indices:\n merged[indices[m][i], ...] = data[m][i, ...]\n```\n\nEach `data[i].shape` must start with the corresponding `indices[i].shape`,\nand the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we\nmust have `data[i].shape = indices[i].shape + constant`. In terms of this\n`constant`, the output shape is\n\n merged.shape = [max(indices)] + constant\n\nValues are merged in order, so if an index appears in both `indices[m][i]` and\n`indices[n][j]` for `(m,i) < (n,j)` the slice `data[n][j]` will appear in the\nmerged result. If you do not need this guarantee, ParallelDynamicStitch might\nperform better on some devices.\n\nFor example:\n\n```python\n indices[0] = 6\n indices[1] = [4, 1]\n indices[2] = [[5, 2], [0, 3]]\n data[0] = [61, 62]\n data[1] = [[41, 42], [11, 12]]\n data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]\n merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],\n [51, 52], [61, 62]]\n```\n\nThis method can be used to merge partitions created by `dynamic_partition`\nas illustrated on the following example:\n\n```python\n # Apply function (increments x_i) on elements for which a certain condition\n # apply (x_i != -1 in this example).\n x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4])\n condition_mask=tf.not_equal(x,tf.constant(-1.))\n partitioned_data = tf.dynamic_partition(\n x, tf.cast(condition_mask, tf.int32) , 2)\n partitioned_data[1] = partitioned_data[1] + 1.0\n condition_indices = tf.dynamic_partition(\n tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)\n x = tf.dynamic_stitch(condition_indices, partitioned_data)\n # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain\n # unchanged.\n```\n\n
    \n\n
    ","inputs":[{"name":"indices","numberAttr":"N","type":3},{"name":"data","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"merged","typeAttr":"T"}],"summary":"Interleave the values from the `data` tensors into a single tensor."}},{"name":"EagerPyFunc","schema":{"attributes":[{"name":"token","type":"string"},{"default":false,"name":"is_async","type":"boolean"},{"minimum":0,"name":"Tin","type":"type[]"},{"minimum":0,"name":"Tout","type":"type[]"}],"description":"semantics of the input, output, and attributes are the same as those for\nPyFunc.","inputs":[{"name":"input","typeListAttr":"Tin"}],"outputs":[{"name":"output","typeListAttr":"Tout"}],"summary":"Eagerly executes a python function to compute func(input)->output. The"}},{"name":"EditDistance","schema":{"attributes":[{"default":true,"description":"boolean (if true, edit distances are normalized by length of truth).\n\nThe output is:","name":"normalize","type":"boolean"},{"name":"T","type":"type"}],"description":"The inputs are variable-length sequences provided by SparseTensors\n (hypothesis_indices, hypothesis_values, hypothesis_shape)\nand\n (truth_indices, truth_values, truth_shape).\n\nThe inputs are:","inputs":[{"description":"The indices of the hypothesis list SparseTensor.\nThis is an N x R int64 matrix.","name":"hypothesis_indices","type":9},{"description":"The values of the hypothesis list SparseTensor.\nThis is an N-length vector.","name":"hypothesis_values","typeAttr":"T"},{"description":"The shape of the hypothesis list SparseTensor.\nThis is an R-length vector.","name":"hypothesis_shape","type":9},{"description":"The indices of the truth list SparseTensor.\nThis is an M x R int64 matrix.","name":"truth_indices","type":9},{"description":"The values of the truth list SparseTensor.\nThis is an M-length vector.","name":"truth_values","typeAttr":"T"},{"description":"truth indices, vector.","name":"truth_shape","type":9}],"outputs":[{"description":"A dense float tensor with rank R - 1.\n\nFor the example input:\n\n // hypothesis represents a 2x1 matrix with variable-length values:\n // (0,0) = [\"a\"]\n // (1,0) = [\"b\"]\n hypothesis_indices = [[0, 0, 0],\n [1, 0, 0]]\n hypothesis_values = [\"a\", \"b\"]\n hypothesis_shape = [2, 1, 1]\n\n // truth represents a 2x2 matrix with variable-length values:\n // (0,0) = []\n // (0,1) = [\"a\"]\n // (1,0) = [\"b\", \"c\"]\n // (1,1) = [\"a\"]\n truth_indices = [[0, 1, 0],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0]]\n truth_values = [\"a\", \"b\", \"c\", \"a\"]\n truth_shape = [2, 2, 2]\n normalize = true\n\nThe output will be:\n\n // output is a 2x2 matrix with edit distances normalized by truth lengths.\n output = [[inf, 1.0], // (0,0): no truth, (0,1): no hypothesis\n [0.5, 1.0]] // (1,0): addition, (1,1): no hypothesis","name":"output","type":1}],"summary":"Computes the (possibly normalized) Levenshtein Edit Distance."}},{"name":"Eig","schema":{"attributes":[{"default":true,"description":"If `True` then eigenvectors will be computed and returned in `v`.\nOtherwise, only the eigenvalues will be computed.","name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"},{"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tout","type":"type"}],"description":"Computes the eigenvalues and (optionally) right eigenvectors of each inner matrix in\n`input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues\nare sorted in non-decreasing order.\n\n```python\n# a is a tensor.\n# e is a tensor of eigenvalues.\n# v is a tensor of eigenvectors.\ne, v = eig(a)\ne = eig(a, compute_v=False)\n```","inputs":[{"description":"`Tensor` input of shape `[N, N]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Eigenvalues. Shape is `[N]`.","name":"e","typeAttr":"Tout"},{"description":"Eigenvectors. Shape is `[N, N]`.","name":"v","typeAttr":"Tout"}],"summary":"Computes the eigen decomposition of one or more square matrices."}},{"name":"Einsum","schema":{"attributes":[{"description":"String describing the Einstein Summation operation; in the format of np.einsum.","name":"equation","type":"string"},{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Implements generalized Tensor contraction and reduction. Each input Tensor must\nhave a corresponding input subscript appearing in the comma-separated left-hand\nside of the equation. The right-hand side of the equation consists of the\noutput subscript. The input subscripts and the output subscript should consist\nof zero or more named axis labels and at most one ellipsis (`...`).\n\nThe named axis labels may be any single character other than those having\nspecial meaning, namely `,.->`. The behavior of this Op is undefined if it\nreceives an ill-formatted equation; since the validation is done at\ngraph-building time, we omit format validation checks at runtime.\n\nNote: This Op is *not* intended to be called by the user; instead users should\ncall `tf.einsum` directly. It is a hidden Op used by `tf.einsum`.\n\nOperations are applied to the input(s) according to the following rules:\n\n (a) Generalized Diagonals: For input dimensions corresponding to axis labels\n appearing more than once in the same input subscript, we take the\n generalized (`k`-dimensional) diagonal.\n For example, in the equation `iii->i` with input shape `[3, 3, 3]`, the\n generalized diagonal would consist of `3` elements at indices `(0, 0, 0)`,\n `(1, 1, 1)` and `(2, 2, 2)` to create a Tensor of shape `[3]`.\n\n (b) Reduction: Axes corresponding to labels appearing only in one input\n subscript but not in the output subscript are summed over prior to Tensor\n contraction.\n For example, in the equation `ab,bc->b`, the axis labels `a` and `c` are\n the reduction axis labels.\n\n (c) Batch Dimensions: Axes corresponding to labels appearing in each of the\n input subscripts and also in the output subscript make up the batch\n dimensions in Tensor contraction. Unnamed axis labels corresponding to\n ellipsis (`...`) also correspond to batch dimensions.\n For example, for the equation denoting batch matrix multiplication,\n `bij,bjk->bik`, the axis label `b` corresponds to a batch dimension.\n\n (d) Contraction: In case of binary einsum, axes corresponding to labels\n appearing in two different inputs (and not in the output) are contracted\n against each other.\n Considering the batch matrix multiplication equation again\n (`bij,bjk->bik`), the contracted axis label is `j`.\n\n (e) Expand Diagonal: If the output subscripts contain repeated (explicit) axis\n labels, the opposite operation of (a) is applied. For example, in the\n equation `i->iii`, and input shape `[3]`, the output of shape `[3, 3, 3]`\n are all zeros, except for the (generalized) diagonal which is populated\n with values from the input.\n Note: This operation is not supported by `np.einsum` or `tf.einsum`; it is\n provided to enable computing the symbolic gradient of `tf.einsum`.\n\nThe output subscripts must contain only labels appearing in at least one of the\ninput subscripts. Furthermore, all dimensions mapping to the same axis label\nmust be equal.\n\nAny of the input and output subscripts may contain at most a single ellipsis\n(`...`). These ellipsis are mapped against dimensions not corresponding to any\nnamed axis label. If two inputs contain ellipsis, then they are broadcasted\naccording to standard NumPy broadcasting\n[rules](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).\n\nThe broadcasted dimensions are placed in the corresponding location of the\nellipsis in the output subscript. If the broadcasted dimensions are non-empty\nand the output subscripts do not contain ellipsis, then an InvalidArgument error\nis raised.\n\n@compatibility(numpy)\nSimilar to [`numpy.einsum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html).\n\nComparison with `numpy.einsum`:\n\n * This Op only supports unary and binary forms of `numpy.einsum`.\n * This Op does not support implicit form. (i.e. equations without `->`).\n * This Op also supports repeated indices in the output subscript, which is not\n supported by `numpy.einsum`.\n@end_compatibility\n","inputs":[{"description":"List of 1 or 2 Tensors.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Output Tensor with shape depending upon `equation`.","name":"output","typeAttr":"T"}],"summary":"Tensor contraction according to Einstein summation convention."}},{"name":"Elu","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","description":"See [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)\n](http://arxiv.org/abs/1511.07289)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes exponential linear: `exp(features) - 1` if < 0, `features` otherwise."}},{"name":"EluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Elu operation.","name":"gradients","typeAttr":"T"},{"description":"The outputs of the corresponding Elu operation.","name":"outputs","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients * (outputs + 1)` if outputs < 0,\n`gradients` otherwise.","name":"backprops","typeAttr":"T"}],"summary":"Computes gradients for the exponential linear (Elu) operation."}},{"name":"Empty","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":false,"description":"If True, initialize the returned tensor with the default value of dtype. Otherwise, the implementation is free not to initializethe tensor's content.","name":"init","type":"boolean"}],"inputs":[{"description":"1-D. Represents the shape of the output tensor.","name":"shape","type":3}],"outputs":[{"description":"A `Tensor` of type `T`.","name":"output","typeAttr":"dtype"}],"summary":"Creates a tensor with the given shape.\n\nThis operation creates a tensor of `shape` and `dtype`."}},{"name":"EmptyTensorList","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"All list elements must be tensors of dtype element_dtype and shape compatible\nwith element_shape.\n\nhandle: an empty tensor list.\nelement_dtype: the type of elements in the list.\nelement_shape: a shape compatible with that of elements in the list.","inputs":[{"name":"element_shape","typeAttr":"shape_type"},{"name":"max_num_elements","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"Creates and returns an empty tensor list."}},{"name":"EncodeBase64","schema":{"attributes":[{"default":false,"description":"Bool whether padding is applied at the ends.","name":"pad","type":"boolean"}],"description":"Refer to the following article for more information on base64 format:\nen.wikipedia.org/wiki/Base64. Base64 strings may have padding with '=' at the\nend so that the encoded has length multiple of 4. See Padding section of the\nlink above.\n\nWeb-safe means that the encoder uses - and _ instead of + and /.","inputs":[{"description":"Strings to be encoded.","name":"input","type":7}],"outputs":[{"description":"Input strings encoded in base64.","name":"output","type":7}],"summary":"Encode strings into web-safe base64 format."}},{"name":"EncodeJpeg","schema":{"attributes":[{"default":"","description":"Per pixel image format. Must be one of the following: ``, `grayscale`, `rgb`.","name":"format","type":"string"},{"default":95,"description":"Quality of the compression from 0 to 100 (higher is better and slower).","name":"quality","type":"int64"},{"default":false,"description":"If True, create a JPEG that loads progressively (coarse to fine).","name":"progressive","type":"boolean"},{"default":false,"description":"If True, spend CPU/RAM to reduce size with no quality change.","name":"optimize_size","type":"boolean"},{"default":true,"description":"See http://en.wikipedia.org/wiki/Chroma_subsampling.","name":"chroma_downsampling","type":"boolean"},{"default":"in","description":"Unit used to specify `x_density` and `y_density`:\npixels per inch (`'in'`) or centimeter (`'cm'`). Must be one of the following: `in`, `cm`.","name":"density_unit","type":"string"},{"default":300,"description":"Horizontal pixels per density unit.","name":"x_density","type":"int64"},{"default":300,"description":"Vertical pixels per density unit.","name":"y_density","type":"int64"},{"default":"","description":"If not empty, embed this XMP metadata in the image header.","name":"xmp_metadata","type":"string"}],"description":"`image` is a 3-D uint8 Tensor of shape `[height, width, channels]`.\n\nThe attr `format` can be used to override the color format of the encoded\noutput. Values can be:\n\n* `''`: Use a default format based on the number of channels in the image.\n* `grayscale`: Output a grayscale JPEG image. The `channels` dimension\n of `image` must be 1.\n* `rgb`: Output an RGB JPEG image. The `channels` dimension\n of `image` must be 3.\n\nIf `format` is not specified or is the empty string, a default format is picked\nin function of the number of channels in `image`:\n\n* 1: Output a grayscale image.\n* 3: Output an RGB image.","inputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","type":4}],"outputs":[{"description":"0-D. JPEG-encoded image.","name":"contents","type":7}],"summary":"JPEG-encode an image."}},{"name":"EncodeJpegVariableQuality","schema":{"description":"`image` is a 3-D uint8 Tensor of shape `[height, width, channels]`.\n`quality` is an int32 jpeg compression quality value between 0 and 100.\n","inputs":[{"description":"Images to adjust. At least 3-D.","name":"images","type":4},{"description":"An int quality to encode to.","name":"quality","type":3}],"outputs":[{"description":"0-D. JPEG-encoded image.","name":"contents","type":7}],"summary":"JPEG encode input image with provided compression quality."}},{"name":"EncodePng","schema":{"attributes":[{"default":-1,"description":"Compression level.","name":"compression","type":"int64"},{"default":{"type":"type","value":4},"description":"Must be one of the following: `uint8`, `uint16`.","name":"T","type":"type"}],"description":"`image` is a 3-D uint8 or uint16 Tensor of shape `[height, width, channels]`\nwhere `channels` is:\n\n* 1: for grayscale.\n* 2: for grayscale + alpha.\n* 3: for RGB.\n* 4: for RGBA.\n\nThe ZLIB compression level, `compression`, can be -1 for the PNG-encoder\ndefault or a value from 0 to 9. 9 is the highest compression level, generating\nthe smallest output, but is slower.","inputs":[{"description":"3-D with shape `[height, width, channels]`.","name":"image","typeAttr":"T"}],"outputs":[{"description":"0-D. PNG-encoded image.","name":"contents","type":7}],"summary":"PNG-encode an image."}},{"name":"EncodeProto","schema":{"attributes":[{"description":"List of strings containing proto field names.","name":"field_names","type":"string[]"},{"description":"Name of the proto message type to decode.","name":"message_type","type":"string"},{"default":"local://","name":"descriptor_source","type":"string"},{"description":"The input types.","minimum":1,"name":"Tinput_types","type":"type[]"}],"description":"The types of the tensors in `values` must match the schema for the fields\nspecified in `field_names`. All the tensors in `values` must have a common\nshape prefix, *batch_shape*.\n\nThe `sizes` tensor specifies repeat counts for each field. The repeat count\n(last dimension) of a each tensor in `values` must be greater than or equal\nto corresponding repeat count in `sizes`.\n\nA `message_type` name must be provided to give context for the field names.\nThe actual message descriptor can be looked up either in the linked-in\ndescriptor pool or a filename provided by the caller using the\n`descriptor_source` attribute.\n\nFor the most part, the mapping between Proto field types and TensorFlow dtypes\nis straightforward. However, there are a few special cases:\n\n- A proto field that contains a submessage or group can only be converted\nto `DT_STRING` (the serialized submessage). This is to reduce the complexity\nof the API. The resulting string can be used as input to another instance of\nthe decode_proto op.\n\n- TensorFlow lacks support for unsigned integers. The ops represent uint64\ntypes as a `DT_INT64` with the same twos-complement bit pattern (the obvious\nway). Unsigned int32 values can be represented exactly by specifying type\n`DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in\nthe `output_types` attribute.\n\nThe `descriptor_source` attribute selects the source of protocol\ndescriptors to consult when looking up `message_type`. This may be:\n\n- An empty string or \"local://\", in which case protocol descriptors are\ncreated for C++ (not Python) proto definitions linked to the binary.\n\n- A file, in which case protocol descriptors are created from the file,\nwhich is expected to contain a `FileDescriptorSet` serialized as a string.\nNOTE: You can build a `descriptor_source` file using the `--descriptor_set_out`\nand `--include_imports` options to the protocol compiler `protoc`.\n\n- A \"bytes://\", in which protocol descriptors are created from ``,\nwhich is expected to be a `FileDescriptorSet` serialized as a string.","inputs":[{"description":"Tensor of int32 with shape `[batch_shape, len(field_names)]`.","name":"sizes","type":3},{"description":"List of tensors containing values for the corresponding field.","name":"values","typeListAttr":"Tinput_types"}],"outputs":[{"description":"Tensor of serialized protos with shape `batch_shape`.","name":"bytes","type":7}],"summary":"The op serializes protobuf messages provided in the input tensors."}},{"name":"EncodeWav","schema":{"description":"This operation will generate a string suitable to be saved out to create a .wav\naudio file. It will be encoded in the 16-bit PCM format. It takes in float\nvalues in the range -1.0f to 1.0f, and any outside that value will be clamped to\nthat range.\n\n`audio` is a 2-D float Tensor of shape `[length, channels]`.\n`sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100).","inputs":[{"description":"2-D with shape `[length, channels]`.","name":"audio","type":1},{"description":"Scalar containing the sample frequency.","name":"sample_rate","type":3}],"outputs":[{"description":"0-D. WAV-encoded file contents.","name":"contents","type":7}],"summary":"Encode audio data using the WAV file format."}},{"name":"EnqueueTPUEmbeddingIntegerBatch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A list of 1D tensors, one for each embedding table, containing the\nindices into the tables.","name":"batch","numberAttr":"N","type":3},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"An op that enqueues a list of input batch tensors to TPUEmbedding."}},{"name":"EnqueueTPUEmbeddingRaggedTensorBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"},{"description":"A list of integers specifying the identifier of the embedding table\n(offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the\ncorresponding input. The ith input is looked up using table_ids[i]. The size\nof the table_ids list must be equal to that of sample_indices,\nembedding_indices and aggregation_weights.","name":"table_ids","type":"int64[]"},{"default":[],"name":"max_sequence_lengths","type":"int64[]"}],"description":"sample_splits[i], embedding_indices[i] and aggregation_weights[i] correspond\nto the ith feature. table_ids[i] indicates which embedding table to look up ith\nfeature.\n\nThe tensors at corresponding positions in two of the input lists,\nembedding_indices and aggregation_weights, must have the same shape, i.e. rank 1\nwith dim_size() equal to the total number of lookups into the table described by\nthe corresponding feature.","inputs":[{"description":"A list of rank 1 Tensors specifying the break points for splitting\nembedding_indices and aggregation_weights into rows.\nIt corresponds to ids.row_splits in embedding_lookup(), when ids is a\nRaggedTensor.","name":"sample_splits","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.\nIt corresponds to ids.values in embedding_lookup(), when ids is a RaggedTensor.","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per training example\naggregation weights. It corresponds to the values field of a RaggedTensor\nwith the same row_splits as ids in embedding_lookup(), when ids is a\nRaggedTensor.","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"Eases the porting of code that uses tf.nn.embedding_lookup()."}},{"name":"EnqueueTPUEmbeddingSparseBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"}],"description":"This Op eases the porting of code that uses embedding_lookup_sparse(),\nalthough some Python preprocessing of the SparseTensor arguments to\nembedding_lookup_sparse() is required to produce the arguments to this Op,\nsince only a single EnqueueTPUEmbeddingSparseBatch Op is allowed per training\nstep.\n\nThe tensors at corresponding positions in the three input lists\nmust have the same shape, i.e. rank 1 with dim_size() equal to the total\nnumber of lookups into the table described by the corresponding table_id.","inputs":[{"description":"A list of rank 1 Tensors specifying the training example and\nfeature to which the corresponding embedding_indices and aggregation_weights\nvalues belong. sample_indices[i] must equal b * nf + f, where nf is the\nnumber of features from the corresponding table, f is in [0, nf), and\nb is in [0, batch size).","name":"sample_indices","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per sample -- i.e. per\n(training example, feature) -- aggregation weights.","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"An op that enqueues TPUEmbedding input indices from a SparseTensor."}},{"name":"EnqueueTPUEmbeddingSparseTensorBatch","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T1","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T2","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"T3","type":"type"},{"minimum":1,"name":"N","type":"int64"},{"default":-1,"description":"The TPU device to use. Should be >= 0 and less than the number\nof TPU cores in the task on which the node is placed.","name":"device_ordinal","type":"int64"},{"default":[],"description":"A list of string scalars, one for each embedding table that specify\nhow to normalize the embedding activations after weighted summation.\nSupported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have\nthe sum of the weights be 0 for 'mean' or the sum of the squared weights be\n0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for\nall tables.","name":"combiners","type":"string[]"},{"description":"A list of integers specifying the identifier of the embedding table\n(offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the\ncorresponding input. The ith input is looked up using table_ids[i]. The size\nof the table_ids list must be equal to that of sample_indices,\nembedding_indices and aggregation_weights.","name":"table_ids","type":"int64[]"},{"default":[],"name":"max_sequence_lengths","type":"int64[]"}],"description":"sample_indices[i], embedding_indices[i] and aggregation_weights[i] correspond\nto the ith feature. table_ids[i] indicates which embedding table to look up ith\nfeature.\n\nThe tensors at corresponding positions in the three input lists (sample_indices,\nembedding_indices and aggregation_weights) must have the same shape, i.e. rank 1\nwith dim_size() equal to the total number of lookups into the table described by\nthe corresponding feature.","inputs":[{"description":"A list of rank 1 Tensors specifying the training example to\nwhich the corresponding embedding_indices and aggregation_weights values\nbelong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse().","name":"sample_indices","numberAttr":"N","typeAttr":"T1"},{"description":"A list of rank 1 Tensors, indices into the embedding tables.\nIt corresponds to sp_ids.values in embedding_lookup_sparse().","name":"embedding_indices","numberAttr":"N","typeAttr":"T2"},{"description":"A list of rank 1 Tensors containing per training example\naggregation weights. It corresponds to sp_weights.values in\nembedding_lookup_sparse().","name":"aggregation_weights","numberAttr":"N","typeAttr":"T3"},{"description":"A string input that overrides the mode specified in the\nTPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference',\n'training', 'backward_pass_only'}. When set to 'unspecified', the mode set\nin TPUEmbeddingConfiguration is used, otherwise mode_override is used.","name":"mode_override","type":7}],"summary":"Eases the porting of code that uses tf.nn.embedding_lookup_sparse()."}},{"name":"EnsureShape","schema":{"attributes":[{"description":"The expected (possibly partially specified) shape of the input tensor.","name":"shape","type":"shape"},{"name":"T","type":"type"}],"description":"Raises an error if the input tensor's shape does not match the specified shape.\nReturns the input tensor otherwise.","inputs":[{"description":"A tensor, whose shape is to be validated.","name":"input","typeAttr":"T"}],"outputs":[{"description":"A tensor with the same shape and contents as the input tensor or value.","name":"output","typeAttr":"T"}],"summary":"Ensures that the tensor's shape matches the expected shape."}},{"name":"Enter","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the child frame.","name":"frame_name","type":"string"},{"default":false,"description":"If true, the output is constant within the child frame.","name":"is_constant","type":"boolean"},{"default":10,"description":"The number of iterations allowed to run in parallel.","name":"parallel_iterations","type":"int64"}],"description":"This op is used together with `Exit` to create loops in the graph.\nThe unique `frame_name` is used by the `Executor` to identify frames. If\n`is_constant` is true, `output` is a constant in the child frame; otherwise\nit may be changed in the child frame. At most `parallel_iterations` iterations\nare run in parallel in the child frame.","inputs":[{"description":"The tensor to be made available to the child frame.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Creates or finds a child frame, and makes `data` available to the child frame."}},{"name":"Equal","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `uint16`, `uint32`, `uint64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"incompatible_shape_error","type":"boolean"}],"description":"*NOTE*: `Equal` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\n```python\nx = tf.constant([2, 4])\ny = tf.constant(2)\ntf.math.equal(x, y) ==> array([True, False])\n\nx = tf.constant([2, 4])\ny = tf.constant([2, 4])\ntf.math.equal(x, y) ==> array([True, True])\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x == y) element-wise."}},{"name":"Erf","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the Gauss error function of `x` element-wise."}},{"name":"Erfc","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the complementary error function of `x` element-wise."}},{"name":"Erfinv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"EuclideanNorm","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the euclidean norm of elements across dimensions of a tensor."}},{"name":"Exit","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Exit makes its input `data` available to the parent frame.","inputs":[{"description":"The tensor to be made available to the parent frame.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Exits the current frame to its parent frame."}},{"name":"Exp","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" This function computes the exponential of every element in the input tensor.\n i.e. `exp(x)` or `e^(x)`, where `x` is the input tensor.\n `e` denotes Euler's number and is approximately equal to 2.718281.\n Output is positive for any real input.\n\n ```python\n x = tf.constant(2.0)\n tf.math.exp(x) ==> 7.389056\n\n x = tf.constant([2.0, 8.0])\n tf.math.exp(x) ==> array([7.389056, 2980.958], dtype=float32)\n ```\n\n For complex numbers, the exponential value is calculated as follows:\n\n ```\n e^(x+iy) = e^x * e^iy = e^x * (cos y + i sin y)\n ```\n\n Let's consider complex number 1+1j as an example.\n e^1 * (cos 1 + i sin 1) = 2.7182818284590 * (0.54030230586+0.8414709848j)\n\n ```python\n x = tf.constant(1 + 1j)\n tf.math.exp(x) ==> 1.4686939399158851+2.2873552871788423j\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes exponential of x element-wise. \\\\(y = e^x\\\\)."}},{"name":"ExpandDims","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tdim","type":"type"}],"description":"Given a tensor `input`, this operation inserts a dimension of 1 at the\ndimension index `dim` of `input`'s shape. The dimension index `dim` starts at\nzero; if you specify a negative number for `dim` it is counted backward from\nthe end.\n\nThis operation is useful if you want to add a batch dimension to a single\nelement. For example, if you have a single image of shape `[height, width,\nchannels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`,\nwhich will make the shape `[1, height, width, channels]`.\n\nOther examples:\n\n```\n# 't' is a tensor of shape [2]\nshape(expand_dims(t, 0)) ==> [1, 2]\nshape(expand_dims(t, 1)) ==> [2, 1]\nshape(expand_dims(t, -1)) ==> [2, 1]\n\n# 't2' is a tensor of shape [2, 3, 5]\nshape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]\nshape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]\nshape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]\n```\n\nThis operation requires that:\n\n`-1-input.dims() <= dim <= input.dims()`\n\nThis operation is related to `squeeze()`, which removes dimensions of\nsize 1.","inputs":[{"name":"input","typeAttr":"T"},{"description":"0-D (scalar). Specifies the dimension index at which to\nexpand the shape of `input`. Must be in the range\n`[-rank(input) - 1, rank(input)]`.","name":"dim","typeAttr":"Tdim"}],"outputs":[{"description":"Contains the same data as `input`, but its shape has an additional\ndimension of size 1 added.","name":"output","typeAttr":"T"}],"summary":"Inserts a dimension of 1 into a tensor's shape."}},{"name":"ExperimentalAssertNextDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"transformations","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalAutoShardDataset","schema":{"attributes":[{"default":0,"name":"auto_shard_policy","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that shards the input dataset by num_workers, returning a\nsharded dataset for the index-th worker. This attempts to automatically shard\na dataset by examining the Dataset graph and inserting a shard op before the\ninputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset).\n\nThis dataset will throw a NotFound error if we cannot shard the dataset\nautomatically.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of workers to distribute this dataset across.","name":"num_workers","type":9},{"description":"A scalar representing the index of the current worker out of num_workers.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shards the input dataset."}},{"name":"ExperimentalBytesProducedStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the bytes size of each element of `input_dataset` in a StatsAggregator."}},{"name":"ExperimentalCSVDataset","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`, `string`.","minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7},{"name":"compression_type","type":7},{"name":"buffer_size","type":9},{"name":"header","type":10},{"name":"field_delim","type":7},{"name":"use_quote_delim","type":10},{"name":"na_value","type":7},{"name":"select_cols","type":9},{"name":"record_defaults","typeListAttr":"output_types"}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalChooseFastestDataset","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"num_experiments","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalDatasetCardinality","schema":{"description":"Returns the cardinality of `input_dataset`.","inputs":[{"description":"A variant tensor representing the dataset to return cardinality for.","name":"input_dataset","type":21}],"outputs":[{"description":"The cardinality of `input_dataset`. Named constants are used to represent\ninfinite and unknown cardinality.","name":"cardinality","type":9}],"summary":"Returns the cardinality of `input_dataset`."}},{"name":"ExperimentalDatasetToTFRecord","schema":{"inputs":[{"description":"A variant tensor representing the dataset to write.","name":"input_dataset","type":21},{"description":"A scalar string tensor representing the filename to use.","name":"filename","type":7},{"description":"A scalar string tensor containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7}],"summary":"Writes the given dataset to the given file using the TFRecord format."}},{"name":"ExperimentalDenseToSparseBatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A handle to an input dataset. Must have a single component.","name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A vector representing the dense shape of each row in the produced\nSparseTensor. The shape may be partially specified, using `-1` to indicate\nthat a particular dimension should use the maximum size of all batch elements.","name":"row_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches input elements into a SparseTensor."}},{"name":"ExperimentalDirectedInterleaveDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A dataset of scalar `DT_INT64` elements that determines which of the\n`N` data inputs should produce the next output element.","name":"selector_input_dataset","type":21},{"description":"`N` datasets with the same type that will be interleaved according to\nthe values of `selector_input_dataset`.","name":"data_input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A substitute for `InterleaveDataset` on a fixed list of `N` datasets."}},{"name":"ExperimentalGroupByReducerDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"description":"A function mapping a key of type DT_INT64, concatenated with\n`init_func_other_arguments` to the initial reducer state.","name":"init_func","type":"function"},{"description":"A function mapping the current reducer state and an element of `input_dataset`,\nconcatenated with `reduce_func_other_arguments` to a new reducer state.","name":"reduce_func","type":"function"},{"description":"A function mapping the final reducer state to an output element.","name":"finalize_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tinit_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that computes a group-by on `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `key_func`.","name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `init_func`.","name":"init_func_other_arguments","typeListAttr":"Tinit_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `reduce_func`.","name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `finalize_func`.","name":"finalize_func_other_arguments","typeListAttr":"Tfinalize_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a group-by on `input_dataset`."}},{"name":"ExperimentalGroupByWindowDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"name":"reduce_func","type":"function"},{"name":"window_size_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Twindow_size_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"// TODO(mrry): Support non-int64 keys.","inputs":[{"name":"input_dataset","type":21},{"name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"name":"window_size_func_other_arguments","typeListAttr":"Twindow_size_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a windowed group-by on `input_dataset`."}},{"name":"ExperimentalIgnoreErrorsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the elements of `input_dataset` ignoring errors."}},{"name":"ExperimentalIteratorGetDevice","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"name":"device","type":7}],"summary":"Returns the name of the device on which `resource` has been placed."}},{"name":"ExperimentalLMDBDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"filenames","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalLatencyStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the latency of producing `input_dataset` elements in a StatsAggregator."}},{"name":"ExperimentalMapAndBatchDataset","schema":{"attributes":[{"description":"A function to apply to the outputs of `input_dataset`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Creates a dataset that applies `f` to the outputs of `input_dataset` and then\nbatches `batch_size` of them.\n\nUnlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `batch_size * num_parallel_batches` copies of `f` in parallel.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when building a closure\nfor `f`.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"A scalar representing the number of elements to accumulate in a\nbatch. It determines the number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"batch_size","type":9},{"description":"A scalar representing the maximum number of parallel invocations of the `map_fn`\nfunction. Applying the `map_fn` on consecutive input elements in parallel has\nthe potential to improve input pipeline throughput.","name":"num_parallel_calls","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that fuses mapping with batching."}},{"name":"ExperimentalMapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ExperimentalMatchingFilesDataset","schema":{"inputs":[{"name":"patterns","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalMaxIntraOpParallelismDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the maximum intra-op parallelism to use.","name":"max_intra_op_parallelism","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that overrides the maximum intra-op parallelism."}},{"name":"ExperimentalNonSerializableDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalParallelInterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! This dataset is not deterministic!","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9},{"name":"sloppy","type":10},{"name":"buffer_output_elements","type":9},{"name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ExperimentalParseExampleDataset","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ExperimentalPrivateThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the number of threads to use for the private threadpool.","name":"num_threads","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalRandomDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar seed for the random number generator. If either seed or\nseed2 is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a Dataset that returns pseudorandom numbers."}},{"name":"ExperimentalRebatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_fallback","type":"boolean"}],"description":"Creates a dataset that changes the batch size of the dataset to current batch\nsize // num_replicas.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of replicas to distribute this batch across. As\na result of this transformation the current batch size would end up being\ndivided by this parameter.","name":"num_replicas","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"ExperimentalScanDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset successively reduces `f` over the elements of `input_dataset`."}},{"name":"ExperimentalSetStatsAggregatorDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"stats_aggregator","type":20},{"name":"tag","type":7},{"name":"counter_prefix","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalSleepDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"sleep_microseconds","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"ExperimentalSlidingWindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements in the\nsliding window.","name":"window_size","type":9},{"description":"A scalar representing the steps moving the sliding window\nforward in one iteration. It must be positive.","name":"window_shift","type":9},{"description":"A scalar representing the stride of the input elements of the sliding window.\nIt must be positive.","name":"window_stride","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that passes a sliding window over `input_dataset`."}},{"name":"ExperimentalSqlDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"The database type. Currently, the only supported type is 'sqlite'.","name":"driver_name","type":7},{"description":"A connection string to connect to the database.","name":"data_source_name","type":7},{"description":"A SQL query to execute.","name":"query","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that executes a SQL query and emits rows of the result set."}},{"name":"ExperimentalStatsAggregatorHandle","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}],"summary":"Creates a statistics manager resource."}},{"name":"ExperimentalStatsAggregatorSummary","schema":{"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"summary","type":7}],"summary":"Produces a summary of any statistics recorded by the given statistics manager."}},{"name":"ExperimentalTakeWhileDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that stops iteration when predicate` is false."}},{"name":"ExperimentalThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A resource produced by the ThreadPoolHandle op.","name":"thread_pool","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalThreadPoolHandle","schema":{"attributes":[{"description":"The number of threads in the thread pool.","name":"num_threads","type":"int64"},{"default":1,"description":"The maximum degree of parallelism to use within operations that execute on this\nthreadpool.","name":"max_intra_op_parallelism","type":"int64"},{"description":"A human-readable name for the threads that may be visible in some\nvisualizations.\nthreadpool.","name":"display_name","type":"string"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"description":"A resource that can be consumed by one or more ExperimentalThreadPoolDataset\nops.","name":"handle","type":20}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ExperimentalUnbatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A dataset that splits the elements of its input into multiple elements."}},{"name":"ExperimentalUniqueDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the unique elements of `input_dataset`."}},{"name":"Expint","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Expm1","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" i.e. `exp(x) - 1` or `e^(x) - 1`, where `x` is the input tensor.\n `e` denotes Euler's number and is approximately equal to 2.718281.\n\n ```python\n x = tf.constant(2.0)\n tf.math.expm1(x) ==> 6.389056\n\n x = tf.constant([2.0, 8.0])\n tf.math.expm1(x) ==> array([6.389056, 2979.958], dtype=float32)\n\n x = tf.constant(1 + 1j)\n tf.math.expm1(x) ==> (0.46869393991588515+2.2873552871788423j)\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes `exp(x) - 1` element-wise."}},{"name":"ExtractGlimpse","schema":{"attributes":[{"default":true,"description":"indicates if the offset coordinates are centered relative to\nthe image, in which case the (0, 0) offset is relative to the center\nof the input images. If false, the (0,0) offset corresponds to the\nupper left corner of the input images.","name":"centered","type":"boolean"},{"default":true,"description":"indicates if the offset coordinates are normalized.","name":"normalized","type":"boolean"},{"default":true,"description":"indicates if the noise should be generated using a\nuniform distribution or a Gaussian distribution.","name":"uniform_noise","type":"boolean"},{"default":"uniform","description":"indicates if the noise should `uniform`, `gaussian`, or\n`zero`. The default is `uniform` which means the the noise type\nwill be decided by `uniform_noise`.","name":"noise","type":"string"}],"description":"Returns a set of windows called glimpses extracted at location\n`offsets` from the input tensor. If the windows only partially\noverlaps the inputs, the non overlapping areas will be filled with\nrandom noise.\n\nThe result is a 4-D tensor of shape `[batch_size, glimpse_height,\nglimpse_width, channels]`. The channels and batch dimensions are the\nsame as that of the input tensor. The height and width of the output\nwindows are specified in the `size` parameter.\n\nThe argument `normalized` and `centered` controls how the windows are built:\n\n* If the coordinates are normalized but not centered, 0.0 and 1.0\n correspond to the minimum and maximum of each height and width\n dimension.\n* If the coordinates are both normalized and centered, they range from\n -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper\n left corner, the lower right corner is located at (1.0, 1.0) and the\n center is at (0, 0).\n* If the coordinates are not normalized they are interpreted as\n numbers of pixels.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, height, width, channels]`.","name":"input","type":1},{"description":"A 1-D tensor of 2 elements containing the size of the glimpses\nto extract. The glimpse height must be specified first, following\nby the glimpse width.","name":"size","type":3},{"description":"A 2-D integer tensor of shape `[batch_size, 2]` containing\nthe y, x locations of the center of each window.","name":"offsets","type":1}],"outputs":[{"description":"A tensor representing the glimpses `[batch_size,\nglimpse_height, glimpse_width, channels]`.","name":"glimpse","type":1}],"summary":"Extracts a glimpse from the input tensor."}},{"name":"ExtractGlimpseV2","schema":{"attributes":[{"default":true,"description":"indicates if the offset coordinates are centered relative to\nthe image, in which case the (0, 0) offset is relative to the center\nof the input images. If false, the (0,0) offset corresponds to the\nupper left corner of the input images.","name":"centered","type":"boolean"},{"default":true,"description":"indicates if the offset coordinates are normalized.","name":"normalized","type":"boolean"},{"default":true,"description":"indicates if the noise should be generated using a\nuniform distribution or a Gaussian distribution.","name":"uniform_noise","type":"boolean"},{"default":"uniform","description":"indicates if the noise should `uniform`, `gaussian`, or\n`zero`. The default is `uniform` which means the the noise type\nwill be decided by `uniform_noise`.","name":"noise","type":"string"}],"description":"Returns a set of windows called glimpses extracted at location\n`offsets` from the input tensor. If the windows only partially\noverlaps the inputs, the non overlapping areas will be filled with\nrandom noise.\n\nThe result is a 4-D tensor of shape `[batch_size, glimpse_height,\nglimpse_width, channels]`. The channels and batch dimensions are the\nsame as that of the input tensor. The height and width of the output\nwindows are specified in the `size` parameter.\n\nThe argument `normalized` and `centered` controls how the windows are built:\n\n* If the coordinates are normalized but not centered, 0.0 and 1.0\n correspond to the minimum and maximum of each height and width\n dimension.\n* If the coordinates are both normalized and centered, they range from\n -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper\n left corner, the lower right corner is located at (1.0, 1.0) and the\n center is at (0, 0).\n* If the coordinates are not normalized they are interpreted as\n numbers of pixels.","inputs":[{"description":"A 4-D float tensor of shape `[batch_size, height, width, channels]`.","name":"input","type":1},{"description":"A 1-D tensor of 2 elements containing the size of the glimpses\nto extract. The glimpse height must be specified first, following\nby the glimpse width.","name":"size","type":3},{"description":"A 2-D integer tensor of shape `[batch_size, 2]` containing\nthe y, x locations of the center of each window.","name":"offsets","type":1}],"outputs":[{"description":"A tensor representing the glimpses `[batch_size,\nglimpse_height, glimpse_width, channels]`.","name":"glimpse","type":1}],"summary":"Extracts a glimpse from the input tensor."}},{"name":"ExtractImagePatches","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `images`.","minimum":4,"name":"ksizes","type":"int64[]"},{"description":"How far the centers of two consecutive patches are in\nthe images. Must be: `[1, stride_rows, stride_cols, 1]`.","minimum":4,"name":"strides","type":"int64[]"},{"description":"Must be: `[1, rate_rows, rate_cols, 1]`. This is the\ninput stride, specifying how far two consecutive patch samples are in the\ninput. Equivalent to extracting patches with\n`patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by\nsubsampling them spatially by a factor of `rates`. This is equivalent to\n`rate` in dilated (a.k.a. Atrous) convolutions.","minimum":4,"name":"rates","type":"int64[]"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`, `bool`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D Tensor with shape `[batch, in_rows, in_cols, depth]`.","name":"images","typeAttr":"T"}],"outputs":[{"description":"4-D Tensor with shape `[batch, out_rows, out_cols, ksize_rows *\nksize_cols * depth]` containing image patches with size\n`ksize_rows x ksize_cols x depth` vectorized in the \"depth\" dimension. Note\n`out_rows` and `out_cols` are the dimensions of the output patches.","name":"patches","typeAttr":"T"}],"summary":"Extract `patches` from `images` and put them in the \"depth\" output dimension."}},{"name":"ExtractJpegShape","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"(Optional) The output type of the operation (int32 or int64).\nDefaults to int32. Must be one of the following: `int32`, `int64`.","name":"output_type","type":"type"}],"description":"This op only parses the image header, so it is much faster than DecodeJpeg.","inputs":[{"description":"0-D. The JPEG-encoded image.","name":"contents","type":7}],"outputs":[{"description":"1-D. The image shape with format [height, width, channels].","name":"image_shape","typeAttr":"output_type"}],"summary":"Extract the shape information of a JPEG-encoded image."}},{"name":"ExtractVolumePatches","schema":{"attributes":[{"description":"The size of the sliding window for each dimension of `input`.","minimum":5,"name":"ksizes","type":"int64[]"},{"description":"1-D of length 5. How far the centers of two consecutive patches are in\n`input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use.\n\nThe size-related attributes are specified as follows:\n\n```python\nksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1]\nstrides = [1, stride_planes, strides_rows, strides_cols, 1]\n``` Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"5-D Tensor with shape `[batch, out_planes, out_rows, out_cols,\nksize_planes * ksize_rows * ksize_cols * depth]` containing patches\nwith size `ksize_planes x ksize_rows x ksize_cols x depth` vectorized\nin the \"depth\" dimension. Note `out_planes`, `out_rows` and `out_cols`\nare the dimensions of the output patches.","name":"patches","typeAttr":"T"}],"summary":"Extract `patches` from `input` and put them in the `\"depth\"` output dimension. 3D extension of `extract_image_patches`."}},{"name":"FFT","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 1-dimensional discrete Fourier transform over the inner-most\ndimension of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Fast Fourier transform."}},{"name":"FFT2D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 2-dimensional discrete Fourier transform over the inner-most\n2 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"2D fast Fourier transform."}},{"name":"FFT3D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 3-dimensional discrete Fourier transform over the inner-most 3\ndimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"3D fast Fourier transform."}},{"name":"FIFOQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"FIFOQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"Fact","schema":{"outputs":[{"name":"fact","type":7}],"summary":"Output a fact about factorials."}},{"name":"FakeParam","schema":{"attributes":[{"description":"The type of the output.","name":"dtype","type":"type"},{"description":" The purported shape of the output. This is only used for shape inference;\n the output will not necessarily have this shape. Can be a partial shape.","name":"shape","type":"shape"}],"outputs":[{"description":" \\\"Fake\\\" output value. This should not be consumed by another op.","name":"output","typeAttr":"dtype"}],"summary":" This op is used as a placeholder in If branch functions. It doesn't provide a\n valid output when run, so must either be removed (e.g. replaced with a\n function input) or guaranteed not to be used (e.g. if mirroring an\n intermediate output needed for the gradient computation of the other branch)."}},{"name":"FakeQuantWithMinMaxArgs","schema":{"attributes":[{"default":-6,"name":"min","type":"float32"},{"default":6,"name":"max","type":"float32"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Attributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nQuantization is called fake since the output is still in floating point.","inputs":[{"name":"inputs","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type."}},{"name":"FakeQuantWithMinMaxArgsGradient","schema":{"attributes":[{"default":-6,"name":"min","type":"float32"},{"default":6,"name":"max","type":"float32"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxArgs operation.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxArgs operation.","name":"inputs","type":1}],"outputs":[{"description":"Backpropagated gradients below the FakeQuantWithMinMaxArgs operation:\n`gradients * (inputs >= min && inputs <= max)`.","name":"backprops","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxArgs operation."}},{"name":"FakeQuantWithMinMaxVars","schema":{"attributes":[{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Fake-quantize the `inputs` tensor of type float via global float scalars\n`min` and `max` to `outputs` tensor of same shape as `inputs`.\n\nAttributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nThis operation has a gradient and thus allows for training `min` and `max`\nvalues.","inputs":[{"name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor of type float via global float scalars"}},{"name":"FakeQuantWithMinMaxVarsGradient","schema":{"attributes":[{"default":8,"description":"The bitwidth of the quantization; between 2 and 8, inclusive.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether to quantize into 2^num_bits - 1 distinct values.","name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxVars operation.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxVars operation.\nmin, max: Quantization interval, scalar floats.","name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"Backpropagated gradients w.r.t. inputs:\n`gradients * (inputs >= min && inputs <= max)`.","name":"backprops_wrt_input","type":1},{"description":"Backpropagated gradients w.r.t. min parameter:\n`sum(gradients * (inputs < min))`.","name":"backprop_wrt_min","type":1},{"description":"Backpropagated gradients w.r.t. max parameter:\n`sum(gradients * (inputs > max))`.","name":"backprop_wrt_max","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxVars operation."}},{"name":"FakeQuantWithMinMaxVarsPerChannel","schema":{"attributes":[{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"narrow_range","type":"boolean"}],"description":"Fake-quantize the `inputs` tensor of type float per-channel and one of the\nshapes: `[d]`, `[b, d]` `[b, h, w, d]` via per-channel floats `min` and `max`\nof shape `[d]` to `outputs` tensor of same shape as `inputs`.\n\nAttributes\n\n* `[min; max]` define the clamping range for the `inputs` data.\n* `inputs` values are quantized into the quantization range (\n`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]`\nwhen it is true) and then de-quantized and output as floats in `[min; max]`\ninterval.\n* `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive.\n\nBefore quantization, `min` and `max` values are adjusted with the following\nlogic.\nIt is suggested to have `min <= 0 <= max`. If `0` is not in the range of values,\nthe behavior can be unexpected:\n\n* If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`.\n* If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`.\n* If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `,\n`min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`.\n\nThis operation has a gradient and thus allows for training `min` and `max`\nvalues.","inputs":[{"name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"name":"outputs","type":1}],"summary":"Fake-quantize the 'inputs' tensor of type float via per-channel floats"}},{"name":"FakeQuantWithMinMaxVarsPerChannelGradient","schema":{"attributes":[{"default":8,"description":"The bitwidth of the quantization; between 2 and 16, inclusive.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether to quantize into 2^num_bits - 1 distinct values.","name":"narrow_range","type":"boolean"}],"inputs":[{"description":"Backpropagated gradients above the FakeQuantWithMinMaxVars operation,\nshape one of: `[d]`, `[b, d]`, `[b, h, w, d]`.","name":"gradients","type":1},{"description":"Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape\n same as `gradients`.\nmin, max: Quantization interval, floats of shape `[d]`.","name":"inputs","type":1},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"Backpropagated gradients w.r.t. inputs, shape same as\n`inputs`:\n `gradients * (inputs >= min && inputs <= max)`.","name":"backprops_wrt_input","type":1},{"description":"Backpropagated gradients w.r.t. min parameter, shape `[d]`:\n`sum_per_d(gradients * (inputs < min))`.","name":"backprop_wrt_min","type":1},{"description":"Backpropagated gradients w.r.t. max parameter, shape `[d]`:\n`sum_per_d(gradients * (inputs > max))`.","name":"backprop_wrt_max","type":1}],"summary":"Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation."}},{"name":"FakeQueue","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated. Do not use."}},{"name":"Fill","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"index_type","type":"type"}],"description":"This operation creates a tensor of shape `dims` and fills it with `value`.\n\nFor example:\n\n```\n# Output tensor has shape [2, 3].\nfill([2, 3], 9) ==> [[9, 9, 9]\n [9, 9, 9]]\n```\n\n`tf.fill` differs from `tf.constant` in a few ways:\n\n* `tf.fill` only supports scalar contents, whereas `tf.constant` supports\n Tensor values.\n* `tf.fill` creates an Op in the computation graph that constructs the actual\n Tensor value at runtime. This is in contrast to `tf.constant` which embeds\n the entire Tensor into the graph with a `Const` node.\n* Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes\n based on other runtime Tensors, unlike `tf.constant`.","inputs":[{"description":"1-D. Represents the shape of the output tensor.","name":"dims","typeAttr":"index_type"},{"description":"0-D (scalar). Value to fill the returned tensor.\n\n@compatibility(numpy)\nEquivalent to np.full\n@end_compatibility","name":"value","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Creates a tensor filled with a scalar value."}},{"name":"FilterByLastComponentDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"output","type":21}],"summary":"Creates a dataset containing elements of first component of `input_dataset` having true in the last component."}},{"name":"FilterDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset containing elements of `input_dataset` matching `predicate`."}},{"name":"Fingerprint","schema":{"attributes":[{"description":"This can be a POD-type or string type.","name":"T","type":"type"}],"description":"Generates fingerprint values of `data`.\n\nFingerprint op considers the first dimension of `data` as the batch dimension,\nand `output[i]` contains the fingerprint value generated from contents in\n`data[i, ...]` for all `i`.\n\nFingerprint op writes fingerprint values as byte arrays. For example, the\ndefault method `farmhash64` generates a 64-bit fingerprint value at a time.\nThis 8-byte value is written out as an `uint8` array of size 8, in little-endian\norder.\n\nFor example, suppose that `data` has data type `DT_INT32` and shape (2, 3, 4),\nand that the fingerprint method is `farmhash64`. In this case, the output shape\nis (2, 8), where 2 is the batch dimension size of `data`, and 8 is the size of\neach fingerprint value in bytes. `output[0, :]` is generated from 12 integers in\n`data[0, :, :]` and similarly `output[1, :]` is generated from other 12 integers\nin `data[1, :, :]`.\n\nNote that this op fingerprints the raw underlying buffer, and it does not\nfingerprint Tensor's metadata such as data type and/or shape. For example, the\nfingerprint values are invariant under reshapes and bitcasts as long as the\nbatch dimension remain the same:\n\n```\nFingerprint(data) == Fingerprint(Reshape(data, ...))\nFingerprint(data) == Fingerprint(Bitcast(data, ...))\n```\n\nFor string data, one should expect `Fingerprint(data) !=\nFingerprint(ReduceJoin(data))` in general.","inputs":[{"description":"Must have rank 1 or higher.","name":"data","typeAttr":"T"},{"description":"Fingerprint method used by this op. Currently available method is\n`farmhash::fingerprint64`.","name":"method","type":7}],"outputs":[{"description":"A two-dimensional `Tensor` of type `tf.uint8`. The first dimension equals to\n`data`'s first dimension, and the second dimension size depends on the\nfingerprint algorithm.","name":"fingerprint","type":4}],"summary":"Generates fingerprint values."}},{"name":"FixedLengthRecordDataset","schema":{"inputs":[{"description":"A scalar or a vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar representing the number of bytes to skip at the\nbeginning of a file.","name":"header_bytes","type":9},{"description":"A scalar representing the number of bytes in each record.","name":"record_bytes","type":9},{"description":"A scalar representing the number of bytes to skip at the end\nof a file.","name":"footer_bytes","type":9},{"description":"A scalar representing the number of bytes to buffer. Must be > 0.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the records from one or more binary files."}},{"name":"FixedLengthRecordDatasetV2","schema":{"inputs":[{"name":"filenames","type":7},{"name":"header_bytes","type":9},{"name":"record_bytes","type":9},{"name":"footer_bytes","type":9},{"name":"buffer_size","type":9},{"name":"compression_type","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"FixedLengthRecordReader","schema":{"attributes":[{"default":0,"description":"Number of bytes in the header, defaults to 0.","name":"header_bytes","type":"int64"},{"description":"Number of bytes in the record.","name":"record_bytes","type":"int64"},{"default":0,"description":"Number of bytes in the footer, defaults to 0.","name":"footer_bytes","type":"int64"},{"default":0,"description":"Number of bytes to hop before each read. Default of 0 means using\nrecord_bytes.","name":"hop_bytes","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs fixed-length records from a file."}},{"name":"FixedLengthRecordReaderV2","schema":{"attributes":[{"default":0,"description":"Number of bytes in the header, defaults to 0.","name":"header_bytes","type":"int64"},{"description":"Number of bytes in the record.","name":"record_bytes","type":"int64"},{"default":0,"description":"Number of bytes in the footer, defaults to 0.","name":"footer_bytes","type":"int64"},{"default":0,"description":"Number of bytes to hop before each read. Default of 0 means using\nrecord_bytes.","name":"hop_bytes","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","description":"The type of encoding for the file. Currently ZLIB and GZIP\nare supported. Defaults to none.","name":"encoding","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs fixed-length records from a file."}},{"name":"FixedUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":"","description":"Each valid line in this file (which should have a CSV-like format)\ncorresponds to a valid word ID. IDs are in sequential order, starting from\nnum_reserved_ids. The last entry in each line is expected to be a value\ncorresponding to the count or relative probability. Exactly one of vocab_file\nand unigrams needs to be passed to this op.","name":"vocab_file","type":"string"},{"default":1,"description":"The distortion is used to skew the unigram probability distribution.\nEach weight is first raised to the distortion's power before adding to the\ninternal unigram distribution. As a result, distortion = 1.0 gives regular\nunigram sampling (as defined by the vocab file), and distortion = 0.0 gives\na uniform distribution.","name":"distortion","type":"float32"},{"default":0,"description":"Optionally some reserved IDs can be added in the range [0,\n..., num_reserved_ids) by the users. One use case is that a special unknown\nword token is used as ID 0. These IDs will have a sampling probability of 0.","name":"num_reserved_ids","type":"int64"},{"default":1,"description":"A sampler can be used to sample from a subset of the original range\nin order to speed up the whole computation through parallelism. This parameter\n(together with 'shard') indicates the number of partitions that are being\nused in the overall computation.","minimum":1,"name":"num_shards","type":"int64"},{"default":0,"description":"A sampler can be used to sample from a subset of the original range\nin order to speed up the whole computation through parallelism. This parameter\n(together with 'num_shards') indicates the particular partition number of a\nsampler op, when partitioning is being used.","minimum":0,"name":"shard","type":"int64"},{"default":[],"description":"A list of unigram counts or probabilities, one per ID in sequential\norder. Exactly one of vocab_file and unigrams should be passed to this op.","name":"unigrams","type":"float32[]"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"A unigram sampler could use a fixed unigram distribution read from a\nfile or passed in as an in-memory array instead of building up the distribution\nfrom data on the fly. There is also an option to skew the distribution by\napplying a distortion power to the weights.\n\nThe vocabulary file should be in CSV-like format, with the last field\nbeing the weight associated with the word.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"FlatMapDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Unlike MapDataset, the `f` in FlatMapDataset is expected to return a\nDataset variant, and FlatMapDataset will flatten successive results\ninto a single Dataset.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Floor","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise largest integer not greater than x."}},{"name":"FloorDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `FloorDiv` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x // y element-wise."}},{"name":"FloorMod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `uint64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"true, this follows Python semantics in that the result here is consistent\nwith a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`.\n\n*NOTE*: `FloorMod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. When `x < 0` xor `y < 0` is"}},{"name":"FlushSummaryWriter","schema":{"inputs":[{"name":"writer","type":20}]}},{"name":"For","schema":{"attributes":[{"description":"A list of dtypes.","minimum":0,"name":"T","type":"type[]"},{"description":" A function that takes a list of tensors (int32, T) and returns another\n list of tensors (T).","name":"body","type":"function"}],"inputs":[{"description":"The lower bound. An int32","name":"start","type":3},{"description":"The upper bound. An int32","name":"limit","type":3},{"description":"The increment. An int32","name":"delta","type":3},{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":" ```python\n output = input;\n for i in range(start, limit, delta)\n output = body(i, output);\n ```"}},{"name":"FractionalAvgPool","schema":{"attributes":[{"description":"Pooling ratio for each dimension of `value`, currently only\nsupports row and col dimension and should be >= 1.0. For example, a valid\npooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements\nmust be 1.0 because we don't allow pooling on batch and channels\ndimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions\nrespectively.","minimum":4,"name":"pooling_ratio","type":"float32[]"},{"default":false,"description":"When set to True, generates the pooling sequence in a\npseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin\nGraham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for\ndifference between pseudorandom and random.","name":"pseudo_random","type":"boolean"},{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [41/3, 26/3] for fractional avg pooling.","name":"overlapping","type":"boolean"},{"default":false,"description":"When set to True, a fixed pooling region will be used when\niterating over a FractionalAvgPool node in the computation graph. Mainly used\nin unit test to make FractionalAvgPool deterministic.","name":"deterministic","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Fractional average pooling is similar to Fractional max pooling in the pooling\nregion generation step. The only difference is that after pooling regions are\ngenerated, a mean operation is performed instead of a max operation in each\npooling region.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"output tensor after fractional avg pooling.","name":"output","typeAttr":"T"},{"description":"row pooling sequence, needed to calculate gradient.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, needed to calculate gradient.","name":"col_pooling_sequence","type":9}],"summary":"Performs fractional average pooling on the input."}},{"name":"FractionalAvgPoolGrad","schema":{"attributes":[{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [41/3, 26/3] for fractional avg pooling.","name":"overlapping","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Unlike FractionalMaxPoolGrad, we don't need to find arg_max for\nFractionalAvgPoolGrad, we just need to evenly back-propagate each element of\nout_backprop to those indices that form the same pooling cell. Therefore, we\njust need to know the shape of original input tensor, instead of the whole\ntensor.","inputs":[{"description":"Original input tensor shape for `fractional_avg_pool`","name":"orig_input_tensor_shape","type":9},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients\nw.r.t. the output of `fractional_avg_pool`.","name":"out_backprop","typeAttr":"T"},{"description":"row pooling sequence, form pooling region with\ncol_pooling_sequence.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, form pooling region with\nrow_pooling sequence.","name":"col_pooling_sequence","type":9}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `fractional_avg_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradient of the FractionalAvgPool function."}},{"name":"FractionalMaxPool","schema":{"attributes":[{"description":"Pooling ratio for each dimension of `value`, currently only\nsupports row and col dimension and should be >= 1.0. For example, a valid\npooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements\nmust be 1.0 because we don't allow pooling on batch and channels\ndimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions\nrespectively.","minimum":4,"name":"pooling_ratio","type":"float32[]"},{"default":false,"description":"When set to True, generates the pooling sequence in a\npseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin\nGraham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for\ndifference between pseudorandom and random.","name":"pseudo_random","type":"boolean"},{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [20, 16] for fractional max pooling.","name":"overlapping","type":"boolean"},{"default":false,"description":"When set to True, a fixed pooling region will be used when\niterating over a FractionalMaxPool node in the computation graph. Mainly used\nin unit test to make FractionalMaxPool deterministic.","name":"deterministic","type":"boolean"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"description":"Fractional max pooling is slightly different than regular max pooling. In\nregular max pooling, you downsize an input set by taking the maximum value of\nsmaller N x N subsections of the set (often 2x2), and try to reduce the set by\na factor of N, where N is an integer. Fractional max pooling, as you might\nexpect from the word \"fractional\", means that the overall reduction ratio N\ndoes not have to be an integer.\n\nThe sizes of the pooling regions are generated randomly but are fairly uniform.\nFor example, let's look at the height dimension, and the constraints on the\nlist of rows that will be pool boundaries.\n\nFirst we define the following:\n\n1. input_row_length : the number of rows from the input set\n2. output_row_length : which will be smaller than the input\n3. alpha = input_row_length / output_row_length : our reduction ratio\n4. K = floor(alpha)\n5. row_pooling_sequence : this is the result list of pool boundary rows\n\nThen, row_pooling_sequence should satisfy:\n\n1. a[0] = 0 : the first value of the sequence is 0\n2. a[end] = input_row_length : the last value of the sequence is the size\n3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size\n4. length(row_pooling_sequence) = output_row_length+1\n\nFor more details on fractional max pooling, see this paper:\n[Benjamin Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071)","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"output tensor after fractional max pooling.","name":"output","typeAttr":"T"},{"description":"row pooling sequence, needed to calculate gradient.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, needed to calculate gradient.","name":"col_pooling_sequence","type":9}],"summary":"Performs fractional max pooling on the input."}},{"name":"FractionalMaxPoolGrad","schema":{"attributes":[{"default":false,"description":"When set to True, it means when pooling, the values at the boundary\nof adjacent pooling cells are used by both cells. For example:\n\n`index 0 1 2 3 4`\n\n`value 20 5 16 3 7`\n\nIf the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice.\nThe result would be [20, 16] for fractional max pooling.","name":"overlapping","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Original input for `fractional_max_pool`","name":"orig_input","typeAttr":"T"},{"description":"Original output for `fractional_max_pool`","name":"orig_output","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients\nw.r.t. the output of `fractional_max_pool`.","name":"out_backprop","typeAttr":"T"},{"description":"row pooling sequence, form pooling region with\ncol_pooling_sequence.","name":"row_pooling_sequence","type":9},{"description":"column pooling sequence, form pooling region with\nrow_pooling sequence.","name":"col_pooling_sequence","type":9}],"outputs":[{"description":"4-D. Gradients w.r.t. the input of `fractional_max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradient of the FractionalMaxPool function."}},{"name":"FresnelCos","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"FresnelSin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"FusedBatchNorm","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float32`.","name":"T","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"T"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"T"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"T"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"T"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"T"}],"summary":"Batch normalization."}},{"name":"FusedBatchNormGrad","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float32`.","name":"T","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"T"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"T"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"T"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"T"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_3","typeAttr":"T"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_4","typeAttr":"T"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormGradV2","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","type":1},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"U"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"U"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_3","typeAttr":"U"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_4","typeAttr":"U"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormGradV3","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":"NHWC","description":"The data format for y_backprop, x, x_backprop.\nEither \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for the gradient with respect to y.","name":"y_backprop","typeAttr":"T"},{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","type":1},{"description":"When is_training is True, a 1D Tensor for the computed batch\nmean to be reused in gradient computation. When is_training is\nFalse, a 1D Tensor for the population mean to be reused in both\n1st and 2nd order gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for the computed batch\nvariance (inverted variance in the cuDNN case) to be reused in\ngradient computation. When is_training is False, a 1D Tensor\nfor the population variance to be reused in both 1st and 2nd\norder gradient computation.","name":"reserve_space_2","typeAttr":"U"},{"description":"When is_training is True, a 1D Tensor for some intermediate results to be reused\nin gradient computation. When is_training is False, a dummy empty Tensor will be\ncreated.","name":"reserve_space_3","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for the gradient with respect to x.","name":"x_backprop","typeAttr":"T"},{"description":"A 1D Tensor for the gradient with respect to scale.","name":"scale_backprop","typeAttr":"U"},{"description":"A 1D Tensor for the gradient with respect to offset.","name":"offset_backprop","typeAttr":"U"},{"description":"Unused placeholder to match the mean input in FusedBatchNorm.","name":"reserve_space_4","typeAttr":"U"},{"description":"Unused placeholder to match the variance input\nin FusedBatchNorm.","name":"reserve_space_5","typeAttr":"U"}],"summary":"Gradient for batch normalization."}},{"name":"FusedBatchNormV2","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"U"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"U"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"U"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"U"}],"summary":"Batch normalization."}},{"name":"FusedBatchNormV3","schema":{"attributes":[{"description":"The data type for the elements of input and output Tensors. Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"description":"The data type for the scale, offset, mean, and variance. Must be one of the following: `float32`.","name":"U","type":"type"},{"default":0.00009999999747378752,"description":"A small float number added to the variance of x.","name":"epsilon","type":"float32"},{"default":1,"name":"exponential_avg_factor","type":"float32"},{"default":"NHWC","description":"The data format for x and y. Either \"NHWC\" (default) or \"NCHW\". Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":true,"description":"A bool value to indicate the operation is for training (default)\nor inference.","name":"is_training","type":"boolean"}],"category":"Normalization","description":"Note that the size of 4D Tensors are defined by either \"NHWC\" or \"NCHW\".\nThe size of 1D Tensors matches the dimension C of the 4D Tensors.","inputs":[{"description":"A 4D Tensor for input data.","name":"x","typeAttr":"T"},{"description":"A 1D Tensor for scaling factor, to scale the normalized x.","name":"scale","typeAttr":"U"},{"description":"A 1D Tensor for offset, to shift to the normalized x.","name":"offset","typeAttr":"U"},{"description":"A 1D Tensor for population mean. Used for inference only;\nmust be empty for training.","name":"mean","typeAttr":"U"},{"description":"A 1D Tensor for population variance. Used for inference only;\nmust be empty for training.","name":"variance","typeAttr":"U"}],"outputs":[{"description":"A 4D Tensor for output data.","name":"y","typeAttr":"T"},{"description":"A 1D Tensor for the computed batch mean, to be used by TensorFlow\nto compute the running mean.","name":"batch_mean","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance, to be used by\nTensorFlow to compute the running variance.","name":"batch_variance","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch mean, to be reused\nin the gradient computation.","name":"reserve_space_1","typeAttr":"U"},{"description":"A 1D Tensor for the computed batch variance (inverted variance\nin the cuDNN case), to be reused in the gradient computation.","name":"reserve_space_2","typeAttr":"U"},{"description":"A 1D Tensor for some intermediate results, to be reused in the gradient\ncomputation for better efficiency.","name":"reserve_space_3","typeAttr":"U"}],"summary":"Batch normalization."}},{"name":"FusedPadConv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"description":"Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`. Must be in the same order as the dimension specified with format.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"Similar to FusedResizeAndPadConv2d, this op allows for an optimized\nimplementation where the spatial padding transformation stage is fused with the\nim2col lookup, but in this case without the bilinear filtering required for\nresizing. Fusing the padding prevents the need to write out the intermediate\nresults as whole tensors, reducing memory pressure, and we can get some latency\ngains by merging the transformation calculations.\nThe data_format attribute for Conv2D isn't supported by this op, and 'NHWC'\norder is used instead.\nInternally this op uses a single per-graph scratch buffer, which means that it\nwill block if multiple versions are being run in parallel. This is because this\noperator is primarily an optimization to minimize memory usage.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Performs a padding as a preprocess during a convolution."}},{"name":"FusedResizeAndPadConv2D","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"resize_align_corners","type":"boolean"},{"description":"Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"},{"description":"1-D of length 4. The stride of the sliding window for each dimension\nof `input`. Must be in the same order as the dimension specified with format.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"description":"It's often possible to do spatial transformations more efficiently as part of\nthe packing stage of a convolution, so this op allows for an optimized\nimplementation where these stages are fused together. This prevents the need to\nwrite out the intermediate results as whole tensors, reducing memory pressure,\nand we can get some latency gains by merging the transformation calculations.\nThe data_format attribute for Conv2D isn't supported by this op, and defaults to\n'NHWC' order.\nInternally this op uses a single per-graph scratch buffer, which means that it\nwill block if multiple versions are being run in parallel. This is because this\noperator is primarily an optimization to minimize memory usage.","inputs":[{"description":"4-D with shape `[batch, in_height, in_width, in_channels]`.","name":"input","typeAttr":"T"},{"description":"A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","type":3},{"description":"4-D with shape\n`[filter_height, filter_width, in_channels, out_channels]`.","name":"filter","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Performs a resize and padding as a preprocess during a convolution."}},{"name":"GRUBlockCell","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"}],"description":"Args\n x: Input to the GRU cell.\n h_prev: State input from the previous GRU cell.\n w_ru: Weight matrix for the reset and update gate.\n w_c: Weight matrix for the cell connection gate.\n b_ru: Bias vector for the reset and update gate.\n b_c: Bias vector for the cell connection gate.\n\nReturns\n r: Output of the reset gate.\n u: Output of the update gate.\n c: Output of the cell connection gate.\n h: Current state of the GRU cell.\n\nNote on notation of the variables:\n\nConcatenation of a and b is represented by a_b\nElement-wise dot product of a and b is represented by ab\nElement-wise dot product is represented by \\circ\nMatrix multiplication is represented by *\n\nBiases are initialized with :\n`b_ru` - constant_initializer(1.0)\n`b_c` - constant_initializer(0.0)\n\nThis kernel op implements the following mathematical equations:\n\n```\nx_h_prev = [x, h_prev]\n\n[r_bar u_bar] = x_h_prev * w_ru + b_ru\n\nr = sigmoid(r_bar)\nu = sigmoid(u_bar)\n\nh_prevr = h_prev \\circ r\n\nx_h_prevr = [x h_prevr]\n\nc_bar = x_h_prevr * w_c + b_c\nc = tanh(c_bar)\n\nh = (1-u) \\circ c + u \\circ h_prev\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"h_prev","typeAttr":"T"},{"name":"w_ru","typeAttr":"T"},{"name":"w_c","typeAttr":"T"},{"name":"b_ru","typeAttr":"T"},{"name":"b_c","typeAttr":"T"}],"outputs":[{"name":"r","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"c","typeAttr":"T"},{"name":"h","typeAttr":"T"}],"summary":"Computes the GRU cell forward propagation for 1 time step."}},{"name":"GRUBlockCellGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"}],"description":"Args\n x: Input to the GRU cell.\n h_prev: State input from the previous GRU cell.\n w_ru: Weight matrix for the reset and update gate.\n w_c: Weight matrix for the cell connection gate.\n b_ru: Bias vector for the reset and update gate.\n b_c: Bias vector for the cell connection gate.\n r: Output of the reset gate.\n u: Output of the update gate.\n c: Output of the cell connection gate.\n d_h: Gradients of the h_new wrt to objective function.\n\nReturns\n d_x: Gradients of the x wrt to objective function.\n d_h_prev: Gradients of the h wrt to objective function.\n d_c_bar Gradients of the c_bar wrt to objective function.\n d_r_bar_u_bar Gradients of the r_bar & u_bar wrt to objective function.\n\nThis kernel op implements the following mathematical equations:\n\nNote on notation of the variables:\n\nConcatenation of a and b is represented by a_b\nElement-wise dot product of a and b is represented by ab\nElement-wise dot product is represented by \\circ\nMatrix multiplication is represented by *\n\nAdditional notes for clarity:\n\n`w_ru` can be segmented into 4 different matrices.\n```\nw_ru = [w_r_x w_u_x\n w_r_h_prev w_u_h_prev]\n```\nSimilarly, `w_c` can be segmented into 2 different matrices.\n```\nw_c = [w_c_x w_c_h_prevr]\n```\nSame goes for biases.\n```\nb_ru = [b_ru_x b_ru_h]\nb_c = [b_c_x b_c_h]\n```\nAnother note on notation:\n```\nd_x = d_x_component_1 + d_x_component_2\n\nwhere d_x_component_1 = d_r_bar * w_r_x^T + d_u_bar * w_r_x^T\nand d_x_component_2 = d_c_bar * w_c_x^T\n\nd_h_prev = d_h_prev_component_1 + d_h_prevr \\circ r + d_h \\circ u\nwhere d_h_prev_componenet_1 = d_r_bar * w_r_h_prev^T + d_u_bar * w_r_h_prev^T\n```\n\nMathematics behind the Gradients below:\n```\nd_c_bar = d_h \\circ (1-u) \\circ (1-c \\circ c)\nd_u_bar = d_h \\circ (h-c) \\circ u \\circ (1-u)\n\nd_r_bar_u_bar = [d_r_bar d_u_bar]\n\n[d_x_component_1 d_h_prev_component_1] = d_r_bar_u_bar * w_ru^T\n\n[d_x_component_2 d_h_prevr] = d_c_bar * w_c^T\n\nd_x = d_x_component_1 + d_x_component_2\n\nd_h_prev = d_h_prev_component_1 + d_h_prevr \\circ r + u\n```\nBelow calculation is performed in the python wrapper for the Gradients\n(not in the gradient kernel.)\n```\nd_w_ru = x_h_prevr^T * d_c_bar\n\nd_w_c = x_h_prev^T * d_r_bar_u_bar\n\nd_b_ru = sum of d_r_bar_u_bar along axis = 0\n\nd_b_c = sum of d_c_bar along axis = 0\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"h_prev","typeAttr":"T"},{"name":"w_ru","typeAttr":"T"},{"name":"w_c","typeAttr":"T"},{"name":"b_ru","typeAttr":"T"},{"name":"b_c","typeAttr":"T"},{"name":"r","typeAttr":"T"},{"name":"u","typeAttr":"T"},{"name":"c","typeAttr":"T"},{"name":"d_h","typeAttr":"T"}],"outputs":[{"name":"d_x","typeAttr":"T"},{"name":"d_h_prev","typeAttr":"T"},{"name":"d_c_bar","typeAttr":"T"},{"name":"d_r_bar_u_bar","typeAttr":"T"}],"summary":"Computes the GRU cell back-propagation for 1 time step."}},{"name":"Gather","schema":{"attributes":[{"default":true,"name":"validate_indices","type":"boolean"},{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `indices.shape + params.shape[1:]` where:\n\n```python\n # Scalar indices\n output[:, ..., :] = params[indices, :, ... :]\n\n # Vector indices\n output[i, :, ..., :] = params[indices[i], :, ... :]\n\n # Higher rank indices\n output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]\n```\n\nIf `indices` is a permutation and `len(indices) == params.shape[0]` then\nthis operation will permute `params` accordingly.\n\n`validate_indices`: DEPRECATED. If this operation is assigned to CPU, values in\n`indices` are always validated to be within range. If assigned to GPU,\nout-of-bound indices result in safe but unspecified behavior, which may include\nraising an error.\n\n
    \n\n
    ","inputs":[{"name":"params","typeAttr":"Tparams"},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` according to `indices`."}},{"name":"GatherNd","schema":{"attributes":[{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` is a K-dimensional integer tensor, best thought of as a\n(K-1)-dimensional tensor of indices into `params`, where each element defines a\nslice of `params`:\n\n output[\\\\(i_0, ..., i_{K-2}\\\\)] = params[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n\nWhereas in `tf.gather` `indices` defines slices into the `axis`\ndimension of `params`, in `tf.gather_nd`, `indices` defines slices into the\nfirst `N` dimensions of `params`, where `N = indices.shape[-1]`.\n\nThe last dimension of `indices` can be at most the rank of\n`params`:\n\n indices.shape[-1] <= params.rank\n\nThe last dimension of `indices` corresponds to elements\n(if `indices.shape[-1] == params.rank`) or slices\n(if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]`\nof `params`. The output tensor has shape\n\n indices.shape[:-1] + params.shape[indices.shape[-1]:]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, a 0 is stored in the\ncorresponding output value.\n\nSome examples below.\n\nSimple indexing into a matrix:\n\n```python\n indices = [[0, 0], [1, 1]]\n params = [['a', 'b'], ['c', 'd']]\n output = ['a', 'd']\n```\n\nSlice indexing into a matrix:\n\n```python\n indices = [[1], [0]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['c', 'd'], ['a', 'b']]\n```\n\nIndexing into a 3-tensor:\n\n```python\n indices = [[1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['a1', 'b1'], ['c1', 'd1']]]\n\n\n indices = [[0, 1], [1, 0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n\n indices = [[0, 0, 1], [1, 0, 1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = ['b0', 'b1']\n```\n\nBatched indexing into a matrix:\n\n```python\n indices = [[[0, 0]], [[0, 1]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['a'], ['b']]\n```\n\nBatched slice indexing into a matrix:\n\n```python\n indices = [[[1]], [[0]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [[['c', 'd']], [['a', 'b']]]\n```\n\nBatched indexing into a 3-tensor:\n\n```python\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[[['a1', 'b1'], ['c1', 'd1']]],\n [[['a0', 'b0'], ['c0', 'd0']]]]\n\n indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0'], ['a1', 'b1']],\n [['a0', 'b0'], ['c1', 'd1']]]\n\n\n indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['b0', 'b1'], ['d0', 'c1']]\n```\n\nSee also `tf.gather` and `tf.batch_gather`.","inputs":[{"description":"The tensor from which to gather values.","name":"params","typeAttr":"Tparams"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Values from `params` gathered from indices given by `indices`, with\nshape `indices.shape[:-1] + params.shape[indices.shape[-1]:]`.","name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` into a Tensor with shape specified by `indices`."}},{"name":"GatherV2","schema":{"attributes":[{"default":0,"name":"batch_dims","type":"int64"},{"name":"Tparams","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `params.shape[:axis] +\nindices.shape[batch_dims:] + params.shape[axis + 1:]` where:\n\n```python\n # Scalar indices (output is rank(params) - 1).\n output[a_0, ..., a_n, b_0, ..., b_n] =\n params[a_0, ..., a_n, indices, b_0, ..., b_n]\n\n # Vector indices (output is rank(params)).\n output[a_0, ..., a_n, i, b_0, ..., b_n] =\n params[a_0, ..., a_n, indices[i], b_0, ..., b_n]\n\n # Higher rank indices (output is rank(params) + rank(indices) - 1).\n output[a_0, ..., a_n, i, ..., j, b_0, ... b_n] =\n params[a_0, ..., a_n, indices[i, ..., j], b_0, ..., b_n]\n```\n\n
    \n\n
    \n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, a 0 is stored in the\ncorresponding output value.\n\nSee also `tf.batch_gather` and `tf.gather_nd`.","inputs":[{"description":"The tensor from which to gather values. Must be at least rank\n`axis + 1`.","name":"params","typeAttr":"Tparams"},{"description":"Index tensor. Must be in range `[0, params.shape[axis])`.","name":"indices","typeAttr":"Tindices"},{"description":"The axis in `params` to gather `indices` from. Defaults to the first\ndimension. Supports negative indexes.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"Values from `params` gathered from indices given by `indices`, with\nshape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]`.","name":"output","typeAttr":"Tparams"}],"summary":"Gather slices from `params` axis `axis` according to `indices`."}},{"name":"GenerateBoundingBoxProposals","schema":{"attributes":[{"default":300,"description":"An integer. Maximum number of rois in the output.","name":"post_nms_topn","type":"int64"}],"description":" The op selects top `pre_nms_topn` scoring boxes, decodes them with respect to anchors,\n applies non-maximal suppression on overlapping boxes with higher than\n `nms_threshold` intersection-over-union (iou) value, discarding boxes where shorter\n side is less than `min_size`.\n Inputs:\n `scores`: A 4D tensor of shape [Batch, Height, Width, Num Anchors] containing the scores per anchor at given position\n `bbox_deltas`: is a tensor of shape [Batch, Height, Width, 4 x Num Anchors] boxes encoded to each anchor\n `anchors`: A 1D tensor of shape [4 x Num Anchors], representing the anchors.\n Outputs:\n `rois`: output RoIs, a 3D tensor of shape [Batch, post_nms_topn, 4], padded by 0 if less than post_nms_topn candidates found.\n `roi_probabilities`: probability scores of each roi in 'rois', a 2D tensor of shape [Batch,post_nms_topn], padded with 0 if needed, sorted by scores.","inputs":[{"description":"A 4-D float tensor of shape `[num_images, height, width, num_achors]` containing scores of the boxes for given anchors, can be unsorted.","name":"scores","type":1},{"description":"A 4-D float tensor of shape `[num_images, height, width, 4 x num_anchors]`. encoding boxes with respec to each anchor.\nCoordinates are given in the form [dy, dx, dh, dw].","name":"bbox_deltas","type":1},{"description":"A 2-D float tensor of shape `[num_images, 5]` containing image information Height, Width, Scale.","name":"image_info","type":1},{"description":"A 2-D float tensor of shape `[num_anchors, 4]` describing the anchor boxes. Boxes are formatted in the form [y1, x1, y2, x2].","name":"anchors","type":1},{"description":"A scalar float tensor for non-maximal-suppression threshold.","name":"nms_threshold","type":1},{"description":"A scalar int tensor for the number of top scoring boxes to be used as input.","name":"pre_nms_topn","type":3},{"description":"A scalar float tensor. Any box that has a smaller size than min_size will be discarded.","name":"min_size","type":1}],"outputs":[{"description":"A 3-D float tensor of shape `[num_images,post_nms_topn,4]` representing the selected\nregion of interest boxes. Sorted in descending order in scores.","name":"rois","type":1},{"description":"A 2-D float tensor of shape `[num_images, post_nms_topn]` representing the score of the\nregion of interest box in `rois` tensor at the same index.","name":"roi_probabilities","type":1}],"summary":"This op produces Region of Interests from given bounding boxes(bbox_deltas) encoded wrt anchors according to eq.2 in arXiv:1506.01497"}},{"name":"GenerateVocabRemapping","schema":{"attributes":[{"description":"How many entries into the new vocab file to start reading.","minimum":0,"name":"new_vocab_offset","type":"int64"},{"description":"Number of entries in the new vocab file to remap.","minimum":0,"name":"num_new_vocab","type":"int64"},{"default":-1,"description":"Number of entries in the old vocab file to consider. If -1,\nuse the entire old vocabulary.","minimum":-1,"name":"old_vocab_size","type":"int64"}],"description":"length `num_new_vocab`, where `remapping[i]` contains the row number in the old\nvocabulary that corresponds to row `i` in the new vocabulary (starting at line\n`new_vocab_offset` and up to `num_new_vocab` entities), or `-1` if entry `i`\nin the new vocabulary is not in the old vocabulary. The old vocabulary is\nconstrained to the first `old_vocab_size` entries if `old_vocab_size` is not the\ndefault value of -1.\n\n`num_vocab_offset` enables\nuse in the partitioned variable case, and should generally be set through\nexamining partitioning info. The format of the files should be a text file,\nwith each line containing a single entity within the vocabulary.\n\nFor example, with `new_vocab_file` a text file containing each of the following\nelements on a single line: `[f0, f1, f2, f3]`, old_vocab_file = [f1, f0, f3],\n`num_new_vocab = 3, new_vocab_offset = 1`, the returned remapping would be\n`[0, -1, 2]`.\n\nThe op also returns a count of how many entries in the new vocabulary\nwere present in the old vocabulary, which is used to calculate the number of\nvalues to initialize in a weight matrix remapping\n\nThis functionality can be used to remap both row vocabularies (typically,\nfeatures) and column vocabularies (typically, classes) from TensorFlow\ncheckpoints. Note that the partitioning logic relies on contiguous vocabularies\ncorresponding to div-partitioned variables. Moreover, the underlying remapping\nuses an IndexTable (as opposed to an inexact CuckooTable), so client code should\nuse the corresponding index_table_from_file() as the FeatureColumn framework\ndoes (as opposed to tf.feature_to_id(), which uses a CuckooTable).","inputs":[{"description":"Path to the new vocab file.","name":"new_vocab_file","type":7},{"description":"Path to the old vocab file.","name":"old_vocab_file","type":7}],"outputs":[{"description":"A Tensor of length num_new_vocab where the element at index i\nis equal to the old ID that maps to the new ID i. This element is -1 for any\nnew ID that is not found in the old vocabulary.","name":"remapping","type":9},{"description":"Number of new vocab entries found in old vocab.","name":"num_present","type":3}],"summary":"Given a path to new and old vocabulary files, returns a remapping Tensor of"}},{"name":"GeneratorDataset","schema":{"attributes":[{"name":"init_func","type":"function"},{"name":"next_func","type":"function"},{"name":"finalize_func","type":"function"},{"minimum":0,"name":"Tinit_func_args","type":"type[]"},{"minimum":0,"name":"Tnext_func_args","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_args","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"init_func_other_args","typeListAttr":"Tinit_func_args"},{"name":"next_func_other_args","typeListAttr":"Tnext_func_args"},{"name":"finalize_func_other_args","typeListAttr":"Tfinalize_func_args"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that invokes a function to generate elements."}},{"name":"GetSessionHandle","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be stored.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The handle for the tensor stored in the session state, represented\nas a string.","name":"handle","type":7}],"summary":"Store the input tensor in the state of the current session."}},{"name":"GetSessionHandleV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be stored.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The handle for the tensor stored in the session state, represented\nas a ResourceHandle object.","name":"handle","type":20}],"summary":"Store the input tensor in the state of the current session."}},{"name":"GetSessionTensor","schema":{"attributes":[{"description":"The type of the output value.","name":"dtype","type":"type"}],"inputs":[{"description":"The handle for a tensor stored in the session state.","name":"handle","type":7}],"outputs":[{"description":"The tensor for the given handle.","name":"value","typeAttr":"dtype"}],"summary":"Get the value of the tensor specified by its handle."}},{"name":"Greater","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `Greater` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 2, 5])\ntf.math.greater(x, y) ==> [False, True, True]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.greater(x, y) ==> [False, False, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x > y) element-wise."}},{"name":"GreaterEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `GreaterEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6, 7])\ny = tf.constant([5, 2, 5, 10])\ntf.math.greater_equal(x, y) ==> [True, True, True, False]\n\nx = tf.constant([5, 4, 6, 7])\ny = tf.constant([5])\ntf.math.greater_equal(x, y) ==> [True, False, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x >= y) element-wise."}},{"name":"GroupByReducerDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"description":"A function mapping a key of type DT_INT64, concatenated with\n`init_func_other_arguments` to the initial reducer state.","name":"init_func","type":"function"},{"description":"A function mapping the current reducer state and an element of `input_dataset`,\nconcatenated with `reduce_func_other_arguments` to a new reducer state.","name":"reduce_func","type":"function"},{"description":"A function mapping the final reducer state to an output element.","name":"finalize_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tinit_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Tfinalize_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that computes a group-by on `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `key_func`.","name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `init_func`.","name":"init_func_other_arguments","typeListAttr":"Tinit_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `reduce_func`.","name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `finalize_func`.","name":"finalize_func_other_arguments","typeListAttr":"Tfinalize_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a group-by on `input_dataset`."}},{"name":"GroupByWindowDataset","schema":{"attributes":[{"description":"A function mapping an element of `input_dataset`, concatenated\nwith `key_func_other_arguments` to a scalar value of type DT_INT64.","name":"key_func","type":"function"},{"name":"reduce_func","type":"function"},{"name":"window_size_func","type":"function"},{"minimum":0,"name":"Tkey_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Treduce_func_other_arguments","type":"type[]"},{"minimum":0,"name":"Twindow_size_func_other_arguments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"// TODO(mrry): Support non-int64 keys.","inputs":[{"name":"input_dataset","type":21},{"name":"key_func_other_arguments","typeListAttr":"Tkey_func_other_arguments"},{"name":"reduce_func_other_arguments","typeListAttr":"Treduce_func_other_arguments"},{"name":"window_size_func_other_arguments","typeListAttr":"Twindow_size_func_other_arguments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that computes a windowed group-by on `input_dataset`."}},{"name":"GuaranteeConst","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The runtime is then free to make optimizations based on this.\n\nOnly accepts value typed tensors as inputs and rejects resource variable handles\nas input.\n\nReturns the input tensor without modification.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Gives a guarantee to the TF runtime that the input tensor is a constant."}},{"name":"HSVToRGB","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a tensor of the same shape as the `images` tensor, containing the RGB\nvalue of the pixels. The output is only well defined if the value in `images`\nare in `[0,1]`.\n\nSee `rgb_to_hsv` for a description of the HSV encoding.","inputs":[{"description":"1-D or higher rank. HSV data to convert. Last dimension must be size 3.","name":"images","typeAttr":"T"}],"outputs":[{"description":"`images` converted to RGB.","name":"output","typeAttr":"T"}],"summary":"Convert one or more images from HSV to RGB."}},{"name":"HashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a hash table, specifying the type of its keys and values.\nBefore using the table you will have to initialize it. After initialization the\ntable will be immutable.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates a non-initialized hash table."}},{"name":"HashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a hash table, specifying the type of its keys and values.\nBefore using the table you will have to initialize it. After initialization the\ntable will be immutable.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates a non-initialized hash table."}},{"name":"HistogramFixedWidth","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"dtype","type":"type"}],"description":"Given the tensor `values`, this operation returns a rank 1 histogram counting\nthe number of entries in `values` that fall into every bin. The bins are\nequal width and determined by the arguments `value_range` and `nbins`.\n\n```python\n# Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)\nnbins = 5\nvalue_range = [0.0, 5.0]\nnew_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]\n\nwith tf.get_default_session() as sess:\n hist = tf.histogram_fixed_width(new_values, value_range, nbins=5)\n variables.global_variables_initializer().run()\n sess.run(hist) => [2, 1, 1, 0, 2]\n```","inputs":[{"description":"Numeric `Tensor`.","name":"values","typeAttr":"T"},{"description":"Shape [2] `Tensor` of same `dtype` as `values`.\nvalues <= value_range[0] will be mapped to hist[0],\nvalues >= value_range[1] will be mapped to hist[-1].","name":"value_range","typeAttr":"T"},{"description":"Scalar `int32 Tensor`. Number of histogram bins.","name":"nbins","type":3}],"outputs":[{"description":"A 1-D `Tensor` holding histogram of values.","name":"out","typeAttr":"dtype"}],"summary":"Return histogram of values."}},{"name":"HistogramSummary","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The generated\n[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\nhas one summary value containing a histogram for `values`.\n\nThis op reports an `InvalidArgument` error if any value is not finite.","inputs":[{"description":"Scalar. Tag to use for the `Summary.Value`.","name":"tag","type":7},{"description":"Any shape. Values to use to build the histogram.","name":"values","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a histogram."}},{"name":"HostConst","schema":{"attributes":[{"description":"Attr `value` is the tensor to return.","name":"value","type":"tensor"},{"name":"dtype","type":"type"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Returns a constant tensor on the host. Only for writing C++ tests."}},{"name":"IFFT","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 1-dimensional discrete Fourier transform over the\ninner-most dimension of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its inverse 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse fast Fourier transform."}},{"name":"IFFT2D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 2-dimensional discrete Fourier transform over the\ninner-most 2 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse 2D fast Fourier transform."}},{"name":"IFFT3D","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 3-dimensional discrete Fourier transform over the\ninner-most 3 dimensions of `input`.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"}],"outputs":[{"description":"A complex tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their inverse 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Inverse 3D fast Fourier transform."}},{"name":"IRFFT","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 1-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most dimension of `input`.\n\nThe inner-most dimension of `input` is assumed to be the result of `RFFT`: the\n`fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If\n`fft_length` is not provided, it is computed from the size of the inner-most\ndimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to\ncompute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong the axis `IRFFT` is computed on, if `fft_length / 2 + 1` is smaller\nthan the corresponding dimension of `input`, the dimension is cropped. If it is\nlarger, the dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [1]. The FFT length.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length` samples of its inverse\n 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse real-valued fast Fourier transform."}},{"name":"IRFFT2D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 2-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 2 dimensions of `input`.\n\nThe inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`:\nThe inner-most dimension contains the `fft_length / 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 2 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong each axis `IRFFT2D` is computed on, if `fft_length` (or\n`fft_length / 2 + 1` for the inner-most dimension) is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [2]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft2\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse 2D real-valued fast Fourier transform."}},{"name":"IRFFT3D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the inverse 3-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 3 dimensions of `input`.\n\nThe inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`:\nThe inner-most dimension contains the `fft_length / 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 3 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\nAlong each axis `IRFFT3D` is computed on, if `fft_length` (or\n`fft_length / 2 + 1` for the inner-most dimension) is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A complex tensor.","name":"input","typeAttr":"Tcomplex"},{"description":"An int32 tensor of shape [3]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A float32 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 3D real Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.irfftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Treal"}],"summary":"Inverse 3D real-valued fast Fourier transform."}},{"name":"Identity","schema":{"attributes":[{"name":"T","type":"type"}],"category":"Control","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a tensor with the same shape and contents as the input tensor or value."}},{"name":"IdentityN","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"tensors.\n\nThis op can be used to override the gradient for complicated functions. For\nexample, suppose y = f(x) and we wish to apply a custom function g for backprop\nsuch that dx = g(dy). In Python,\n\n```python\nwith tf.get_default_graph().gradient_override_map(\n {'IdentityN': 'OverrideGradientWithG'}):\n y, _ = identity_n([f(x), x])\n\n@tf.RegisterGradient('OverrideGradientWithG')\ndef ApplyG(op, dy, _):\n return [None, g(dy)] # Do not backprop to f(x).\n```","inputs":[{"name":"input","typeListAttr":"T"}],"outputs":[{"name":"output","typeListAttr":"T"}],"summary":"Returns a list of tensors with the same shapes and contents as the input"}},{"name":"IdentityReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue strings in a Queue. ReaderRead will take the front\nwork string and output (work, work).","outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the queued work as both the key and value."}},{"name":"IdentityReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue strings in a Queue. ReaderRead will take the front\nwork string and output (work, work).","outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the queued work as both the key and value."}},{"name":"If","schema":{"attributes":[{"name":"Tcond","type":"type"},{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what else_branch returns.","name":"then_branch","type":"function"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what then_branch returns.","name":"else_branch","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":" A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n `True` and zero means False; if the scalar is a string, non-empty\n means `True` and empty means `False`. If the tensor is not a scalar,\n being empty means False and being non-empty means True.","name":"cond","typeAttr":"Tcond"},{"description":"A list of input tensors.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"output = cond ? then_branch(input) : else_branch(input)"}},{"name":"Igamma","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The lower regularized incomplete Gamma function is defined as:\n\n\n\\\\(P(a, x) = gamma(a, x) / Gamma(a) = 1 - Q(a, x)\\\\)\n\nwhere\n\n\\\\(gamma(a, x) = \\\\int_{0}^{x} t^{a-1} exp(-t) dt\\\\)\n\nis the lower incomplete Gamma function.\n\nNote, above `Q(a, x)` (`Igammac`) is the upper regularized complete\nGamma function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the lower regularized incomplete Gamma function `P(a, x)`."}},{"name":"IgammaGradA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient of `igamma(a, x)` wrt `a`."}},{"name":"Igammac","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The upper regularized incomplete Gamma function is defined as:\n\n\\\\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\\\)\n\nwhere\n\n\\\\(Gamma(a, x) = int_{x}^{\\infty} t^{a-1} exp(-t) dt\\\\)\n\nis the upper incomplete Gama function.\n\nNote, above `P(a, x)` (`Igamma`) is the lower regularized complete\nGamma function.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the upper regularized incomplete Gamma function `Q(a, x)`."}},{"name":"IgnoreErrorsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the elements of `input_dataset` ignoring errors."}},{"name":"Imag","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the imaginary part of each element in `input`. All\nelements in `input` must be complex numbers of the form \\\\(a + bj\\\\), where *a*\nis the real part and *b* is the imaginary part returned by this operation.\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.imag(input) ==> [4.75, 5.75]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the imaginary part of a complex number."}},{"name":"ImageProjectiveTransformV2","schema":{"attributes":[{"description":"Input dtype. Must be one of the following: `uint8`, `int32`, `int64`, `float16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Interpolation method, \"NEAREST\" or \"BILINEAR\".","name":"interpolation","type":"string"},{"default":"CONSTANT","description":"Fill mode, \"REFLECT\", \"WRAP\", or \"CONSTANT\".","name":"fill_mode","type":"string"}],"description":"If one row of `transforms` is `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps\nthe *output* point `(x, y)` to a transformed *input* point\n`(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where\n`k = c0 x + c1 y + 1`. If the transformed point lays outside of the input\nimage, the output pixel is set to 0.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"dtype"},{"description":"2-D Tensor, `[batch, 8]` or `[1, 8]` matrix, where each row corresponds to a 3 x 3\nprojective transformation matrix, with the last entry assumed to be 1. If there\nis one row, the same transformation will be applied to all images.","name":"transforms","type":1},{"description":"1-D Tensor [new_height, new_width].","name":"output_shape","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"transformed_images","typeAttr":"dtype"}],"summary":"Applies the given transform to each of the images."}},{"name":"ImageSummary","schema":{"attributes":[{"default":3,"description":"Max number of batch elements to generate images for.","minimum":1,"name":"max_images","type":"int64"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `uint8`, `float32`, `float16`, `float64`.","name":"T","type":"type"},{"default":{"type":"tensor","value":"?"},"description":"Color to use for pixels with non-finite values.","name":"bad_color","type":"tensor"}],"description":"The summary has up to `max_images` summary values containing images. The\nimages are built from `tensor` which must be 4-D with shape `[batch_size,\nheight, width, channels]` and where `channels` can be:\n\n* 1: `tensor` is interpreted as Grayscale.\n* 3: `tensor` is interpreted as RGB.\n* 4: `tensor` is interpreted as RGBA.\n\nThe images have the same number of channels as the input tensor. For float\ninput, the values are normalized one image at a time to fit in the range\n`[0, 255]`. `uint8` values are unchanged. The op uses two different\nnormalization algorithms:\n\n* If the input values are all positive, they are rescaled so the largest one\n is 255.\n\n* If any input value is negative, the values are shifted so input value 0.0\n is at 127. They are then rescaled so that either the smallest value is 0,\n or the largest one is 255.\n\nThe `tag` argument is a scalar `Tensor` of type `string`. It is used to\nbuild the `tag` of the summary values:\n\n* If `max_images` is 1, the summary value tag is '*tag*/image'.\n* If `max_images` is greater than 1, the summary value tags are\n generated sequentially as '*tag*/image/0', '*tag*/image/1', etc.\n\nThe `bad_color` argument is the color to use in the generated images for\nnon-finite input values. It is a `uint8` 1-D tensor of length `channels`.\nEach element must be in the range `[0, 255]` (It represents the value of a\npixel in the output image). Non-finite values in the input tensor are\nreplaced by this tensor in the output image. The default value is the color\nred.","inputs":[{"description":"Scalar. Used to build the `tag` attribute of the summary values.","name":"tag","type":7},{"description":"4-D of shape `[batch_size, height, width, channels]` where\n`channels` is 1, 3, or 4.","name":"tensor","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with images."}},{"name":"ImmutableConst","schema":{"attributes":[{"description":"Type of the returned tensor.","name":"dtype","type":"type"},{"description":"Shape of the returned tensor.","name":"shape","type":"shape"},{"description":"Name of readonly memory region used by the tensor, see\nNewReadOnlyMemoryRegionFromFile in tensorflow::Env.","name":"memory_region_name","type":"string"}],"description":"The current implementation memmaps the tensor from a file.","outputs":[{"name":"tensor","typeAttr":"dtype"}],"summary":"Returns immutable tensor from memory region."}},{"name":"ImportEvent","schema":{"inputs":[{"name":"writer","type":20},{"name":"event","type":7}]}},{"name":"InTopK","schema":{"attributes":[{"description":"Number of top elements to look at for computing precision.","name":"k","type":"int64"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the\nprediction for the target class is among the top `k` predictions among\nall predictions for example `i`. Note that the behavior of `InTopK` differs\nfrom the `TopK` op in its handling of ties; if multiple classes have the\nsame prediction value and straddle the top-`k` boundary, all of those\nclasses are considered to be in the top `k`.\n\nMore formally, let\n\n \\\\(predictions_i\\\\) be the predictions for all classes for example `i`,\n \\\\(targets_i\\\\) be the target class for example `i`,\n \\\\(out_i\\\\) be the output for example `i`,\n\n$$out_i = predictions_{i, targets_i} \\in TopKIncludingTies(predictions_i)$$","inputs":[{"description":"A `batch_size` x `classes` tensor.","name":"predictions","type":1},{"description":"A `batch_size` vector of class ids.","name":"targets","typeAttr":"T"}],"outputs":[{"description":"Computed Precision at `k` as a `bool Tensor`.","name":"precision","type":10}],"summary":"Says whether the targets are in the top `K` predictions."}},{"name":"InTopKV2","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the\nprediction for the target class is among the top `k` predictions among\nall predictions for example `i`. Note that the behavior of `InTopK` differs\nfrom the `TopK` op in its handling of ties; if multiple classes have the\nsame prediction value and straddle the top-`k` boundary, all of those\nclasses are considered to be in the top `k`.\n\nMore formally, let\n\n \\\\(predictions_i\\\\) be the predictions for all classes for example `i`,\n \\\\(targets_i\\\\) be the target class for example `i`,\n \\\\(out_i\\\\) be the output for example `i`,\n\n$$out_i = predictions_{i, targets_i} \\in TopKIncludingTies(predictions_i)$$","inputs":[{"description":"A `batch_size` x `classes` tensor.","name":"predictions","type":1},{"description":"A `batch_size` vector of class ids.","name":"targets","typeAttr":"T"},{"description":"Number of top elements to look at for computing precision.","name":"k","typeAttr":"T"}],"outputs":[{"description":"Computed precision at `k` as a `bool Tensor`.","name":"precision","type":10}],"summary":"Says whether the targets are in the top `K` predictions."}},{"name":"InfeedDequeue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor.","name":"shape","type":"shape"}],"outputs":[{"description":"A tensor that will be provided using the infeed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"InfeedDequeueTuple","schema":{"attributes":[{"description":"The element types of each element in `outputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `outputs`.","name":"shapes","type":"shape[]"}],"outputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"outputs","typeListAttr":"dtypes"}],"summary":"Fetches multiple values from infeed as an XLA tuple."}},{"name":"InfeedEnqueue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence.\nIf a layout attribute is passed, but its values are all -1, the layout will\nbe computed by the infeed operation.","name":"layout","type":"int64[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A tensor that will be provided using the infeed mechanism.","name":"input","typeAttr":"dtype"}],"summary":"An op which feeds a single Tensor value into the computation."}},{"name":"InfeedEnqueuePrelinearizedBuffer","schema":{"attributes":[{"default":-1,"description":"The TPU device to use. This should be -1 when the Op is running on a TPU device\nand = 0 when the Op is running on the CPU device.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A variant tensor representing linearized output.","name":"input","type":21}],"summary":"An op which enqueues prelinearized buffer into TPU infeed."}},{"name":"InfeedEnqueueTuple","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `inputs`.","name":"shapes","type":"shape[]"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence for\nall the tuple shapes, in the order the shapes appear in the \"shapes\" input.\nThe layout elements for a sub-shape can be set to -1, in which case the\ncorresponding layout will be computed by the infeed operation.","name":"layouts","type":"int64[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"inputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"inputs","typeListAttr":"dtypes"}],"summary":"Feeds multiple Tensor values into the computation as an XLA tuple."}},{"name":"InitializeTable","schema":{"attributes":[{"name":"Tkey","type":"type"},{"name":"Tval","type":"type"}],"inputs":[{"description":"Handle to a table which will be initialized.","isRef":true,"name":"table_handle","type":7},{"description":"Keys of type Tkey.","name":"keys","typeAttr":"Tkey"},{"description":"Values of type Tval.","name":"values","typeAttr":"Tval"}],"summary":"Table initializer that takes two tensors for keys and values respectively."}},{"name":"InitializeTableFromDataset","schema":{"inputs":[{"name":"table_handle","type":20},{"name":"dataset","type":21}]}},{"name":"InitializeTableFromTextFile","schema":{"attributes":[{"description":"Column index in a line to get the table `key` values from.","minimum":-2,"name":"key_index","type":"int64"},{"description":"Column index that represents information of a line to get the table\n`value` values from.","minimum":-2,"name":"value_index","type":"int64"},{"default":-1,"description":"Number of elements of the file, use -1 if unknown.","minimum":-1,"name":"vocab_size","type":"int64"},{"default":"\t","description":"Delimiter to separate fields in a line.","name":"delimiter","type":"string"}],"description":"It inserts one key-value pair into the table for each line of the file.\nThe key and value is extracted from the whole line content, elements from the\nsplit line based on `delimiter` or the line number (starting from zero).\nWhere to extract the key and value from a line is specified by `key_index` and\n`value_index`.\n\n- A value of -1 means use the line number(starting from zero), expects `int64`.\n- A value of -2 means use the whole line content, expects `string`.\n- A value >= 0 means use the index (starting at zero) of the split line based\n on `delimiter`.","inputs":[{"description":"Handle to a table which will be initialized.","isRef":true,"name":"table_handle","type":7},{"description":"Filename of a vocabulary text file.","name":"filename","type":7}],"summary":"Initializes a table from a text file."}},{"name":"InitializeTableFromTextFileV2","schema":{"attributes":[{"description":"Column index in a line to get the table `key` values from.","minimum":-2,"name":"key_index","type":"int64"},{"description":"Column index that represents information of a line to get the table\n`value` values from.","minimum":-2,"name":"value_index","type":"int64"},{"default":-1,"description":"Number of elements of the file, use -1 if unknown.","minimum":-1,"name":"vocab_size","type":"int64"},{"default":"\t","description":"Delimiter to separate fields in a line.","name":"delimiter","type":"string"}],"description":"It inserts one key-value pair into the table for each line of the file.\nThe key and value is extracted from the whole line content, elements from the\nsplit line based on `delimiter` or the line number (starting from zero).\nWhere to extract the key and value from a line is specified by `key_index` and\n`value_index`.\n\n- A value of -1 means use the line number(starting from zero), expects `int64`.\n- A value of -2 means use the whole line content, expects `string`.\n- A value >= 0 means use the index (starting at zero) of the split line based\n on `delimiter`.","inputs":[{"description":"Handle to a table which will be initialized.","name":"table_handle","type":20},{"description":"Filename of a vocabulary text file.","name":"filename","type":7}],"summary":"Initializes a table from a text file."}},{"name":"InitializeTableV2","schema":{"attributes":[{"name":"Tkey","type":"type"},{"name":"Tval","type":"type"}],"inputs":[{"description":"Handle to a table which will be initialized.","name":"table_handle","type":20},{"description":"Keys of type Tkey.","name":"keys","typeAttr":"Tkey"},{"description":"Values of type Tval.","name":"values","typeAttr":"Tval"}],"summary":"Table initializer that takes two tensors for keys and values respectively."}},{"name":"InplaceAdd","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A `Tensor` of type T.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":" Adds v into specified rows of x.\n\n Computes y = x; y[i, :] += v; return y."}},{"name":"InplaceSub","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A `Tensor` of type T.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":" Subtracts `v` into specified rows of `x`.\n\n Computes y = x; y[i, :] -= v; return y."}},{"name":"InplaceUpdate","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Computes `x[i, :] = v; return x`.\n\nOriginally this function is mutative however for compilation we make this\noperation create / operate on a copy of `x`.","inputs":[{"description":"A tensor of type `T`.","name":"x","typeAttr":"T"},{"description":"A vector. Indices into the left-most dimension of `x`.","name":"i","type":3},{"description":"A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size.","name":"v","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` of type T. An alias of `x`. The content of `y` is undefined if there are duplicates in `i`.","name":"y","typeAttr":"T"}],"summary":"Updates specified rows 'i' with values 'v'."}},{"name":"InterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Unlike MapDataset, the `f` in InterleaveDataset is expected to return\na Dataset variant, and InterleaveDataset will flatten successive\nresults into a single Dataset. Unlike FlatMapDataset,\nInterleaveDataset will interleave sequences of up to `block_length`\nconsecutive elements from `cycle_length` input elements.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Inv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the reciprocal of x element-wise."}},{"name":"InvGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the inverse of `x` wrt its input."}},{"name":"Invert","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Flip each bit of supported types. For example, type `int8` (decimal 2) binary 00000010 becomes (decimal -3) binary 11111101.\nThis operation is performed on each element of the tensor argument `x`.\n\nExample:\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\n\n# flip 2 (00000010) to -3 (11111101)\ntf.assert_equal(-3, bitwise_ops.invert(2))\n\ndtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,\n dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]\n\ninputs = [0, 5, 3, 14]\nfor dtype in dtype_list:\n # Because of issues with negative numbers, let's test this indirectly.\n # 1. invert(a) and a = 0\n # 2. invert(a) or a = invert(0)\n input_tensor = tf.constant([0, 5, 3, 14], dtype=dtype)\n not_a_and_a, not_a_or_a, not_0 = [bitwise_ops.bitwise_and(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.bitwise_or(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.invert(\n tf.constant(0, dtype=dtype))]\n\n expected = tf.constant([0, 0, 0, 0], dtype=tf.float32)\n tf.assert_equal(tf.cast(not_a_and_a, tf.float32), expected)\n\n expected = tf.cast([not_0] * 4, tf.float32)\n tf.assert_equal(tf.cast(not_a_or_a, tf.float32), expected)\n\n # For unsigned dtypes let's also check the result directly.\n if dtype.is_unsigned:\n inverted = bitwise_ops.invert(input_tensor)\n expected = tf.constant([dtype.max - x for x in inputs], dtype=tf.float32)\n tf.assert_equal(tf.cast(inverted, tf.float32), tf.cast(expected, tf.float32))\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Invert (flip) each bit of supported types; for example, type `uint8` value 01010101 becomes 10101010."}},{"name":"InvertPermutation","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"This operation computes the inverse of an index permutation. It takes a 1-D\ninteger tensor `x`, which represents the indices of a zero-based array, and\nswaps each value with its index position. In other words, for an output tensor\n`y` and an input tensor `x`, this operation computes the following:\n\n`y[x[i]] = i for i in [0, 1, ..., len(x) - 1]`\n\nThe values must include 0. There can be no duplicate values or negative values.\n\nFor example:\n\n```\n# tensor `x` is [3, 4, 0, 2, 1]\ninvert_permutation(x) ==> [2, 4, 3, 0, 1]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"}],"summary":"Computes the inverse permutation of a tensor."}},{"name":"IsBoostedTreesEnsembleInitialized","schema":{"inputs":[{"description":"Handle to the tree ensemble resource.","name":"tree_ensemble_handle","type":20}],"outputs":[{"description":"output boolean on whether it is initialized or not.","name":"is_initialized","type":10}],"summary":"Checks whether a tree ensemble has been initialized."}},{"name":"IsBoostedTreesQuantileStreamResourceInitialized","schema":{"description":"An Op that checks if quantile stream resource is initialized.","inputs":[{"description":"resource; The reference to quantile stream resource handle.","name":"quantile_stream_resource_handle","type":20}],"outputs":[{"description":"bool; True if the resource is initialized, False otherwise.","name":"is_initialized","type":10}],"summary":"Checks whether a quantile stream has been initialized."}},{"name":"IsFinite","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isfinite\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, 4.8, 6.8, np.inf, np.nan])\ntf.math.is_finite(x) ==> [True, True, True, False, False]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are finite."}},{"name":"IsInf","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isinf\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, np.inf, 6.8, np.inf])\ntf.math.is_inf(x) ==> [False, True, False, True]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are Inf."}},{"name":"IsNan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"@compatibility(numpy)\nEquivalent to np.isnan\n@end_compatibility\n\nExample:\n\n```python\nx = tf.constant([5.0, np.nan, 6.8, np.nan, np.inf])\ntf.math.is_nan(x) ==> [False, True, False, True, False]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":10}],"summary":"Returns which elements of x are NaN."}},{"name":"IsVariableInitialized","schema":{"attributes":[{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"}],"description":"Outputs boolean scalar indicating whether the tensor has been initialized.","inputs":[{"description":"Should be from a `Variable` node. May be uninitialized.","isRef":true,"name":"ref","typeAttr":"dtype"}],"outputs":[{"name":"is_initialized","type":10}],"summary":"Checks whether a tensor has been initialized."}},{"name":"Iterator","schema":{"attributes":[{"name":"shared_name","type":"string"},{"name":"container","type":"string"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"A handle to the iterator that can be passed to a \"MakeIterator\"\nor \"IteratorGetNext\" op.","name":"handle","type":20}],"summary":"A container for an iterator resource."}},{"name":"IteratorFromStringHandle","schema":{"attributes":[{"default":[],"description":"If specified, defines the type of each tuple component in an\nelement produced by the resulting iterator.","minimum":0,"name":"output_types","type":"type[]"},{"default":[],"description":"If specified, defines the shape of each tuple component in an\nelement produced by the resulting iterator.","minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A string representation of the given handle.","name":"string_handle","type":7}],"outputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"summary":"Converts the given string representing a handle to an iterator to a resource."}},{"name":"IteratorFromStringHandleV2","schema":{"attributes":[{"default":[],"minimum":0,"name":"output_types","type":"type[]"},{"default":[],"minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"string_handle","type":7}],"outputs":[{"name":"resource_handle","type":20}]}},{"name":"IteratorGetDevice","schema":{"inputs":[{"name":"resource","type":20}],"outputs":[{"name":"device","type":7}],"summary":"Returns the name of the device on which `resource` has been placed."}},{"name":"IteratorGetNext","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Gets the next output from the given iterator ."}},{"name":"IteratorGetNextAsOptional","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"optional","type":21}],"summary":"Gets the next output from the given iterator as an Optional variant."}},{"name":"IteratorGetNextSync","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"This operation is a synchronous version IteratorGetNext. It should only be used\nin situations where the iterator does not block the calling thread, or where\nthe calling thread is not a member of the thread pool used to execute parallel\noperations (e.g. in eager mode).","inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Gets the next output from the given iterator."}},{"name":"IteratorToStringHandle","schema":{"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"outputs":[{"description":"A string representation of the given handle.","name":"string_handle","type":7}],"summary":"Converts the given `resource_handle` representing an iterator to a string."}},{"name":"IteratorV2","schema":{"attributes":[{"name":"shared_name","type":"string"},{"name":"container","type":"string"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"name":"handle","type":20}]}},{"name":"KMC2ChainInitialization","schema":{"description":"Entries in distances are assumed to be squared distances of candidate points to\nthe already sampled centers in the seed set. The op constructs one Markov chain\nof the k-MC^2 algorithm and returns the index of one candidate point to be added\nas an additional cluster center.","inputs":[{"description":"Vector with squared distances to the closest previously sampled cluster center\nfor each candidate point.","name":"distances","type":1},{"description":"Scalar. Seed for initializing the random number generator.","name":"seed","type":9}],"outputs":[{"description":"Scalar with the index of the sampled point.","name":"index","type":9}],"summary":"Returns the index of a data point that should be added to the seed set."}},{"name":"KmeansPlusPlusInitialization","schema":{"description":"Rows of points are assumed to be input points. One row is selected at random.\nSubsequent rows are sampled with probability proportional to the squared L2\ndistance from the nearest row selected thus far till num_to_sample rows have\nbeen sampled.","inputs":[{"description":"Matrix of shape (n, d). Rows are assumed to be input points.","name":"points","type":1},{"description":"Scalar. The number of rows to sample. This value must not be larger than n.","name":"num_to_sample","type":9},{"description":"Scalar. Seed for initializing the random number generator.","name":"seed","type":9},{"description":"Scalar. For each row that is sampled, this parameter\nspecifies the number of additional points to draw from the current\ndistribution before selecting the best. If a negative value is specified, a\nheuristic is used to sample O(log(num_to_sample)) additional points.","name":"num_retries_per_sample","type":9}],"outputs":[{"description":"Matrix of shape (num_to_sample, d). The sampled rows.","name":"samples","type":1}],"summary":"Selects num_to_sample rows of input using the KMeans++ criterion."}},{"name":"KthOrderStatistic","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"implementation uses a binary search requiring exactly 32 passes over\nthe input data. The running time is linear with respect to input\nsize. The median-of-medians algorithm is probably faster, but is\ndifficult to implement efficiently in XLA. The implementation imposes\na total ordering on floats. The ordering is consistent with the usual\npartial order. Positive NaNs are greater than positive\ninfinity. Negative NaNs are less than negative infinity. NaNs with\ndistinct payloads are treated as distinct. Subnormal numbers are\npreserved (not flushed to zero). Positive infinity is greater than all\nnumbers. Negative infinity is less than all numbers. Positive is\ngreater than negative zero. There are less than k values greater than\nthe kth order statistic. There are at least k values greater than or\nequal to the Kth order statistic. The semantics are not the same as\ntop_k_unique.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Computes the Kth order statistic of a data set. The current"}},{"name":"L2Loss","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Computes half the L2 norm of a tensor without the `sqrt`:\n\n output = sum(t ** 2) / 2","inputs":[{"description":"Typically 2-D, but may have any dimensions.","name":"t","typeAttr":"T"}],"outputs":[{"description":"0-D.","name":"output","typeAttr":"T"}],"summary":"L2 Loss."}},{"name":"LMDBDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The Lightning Memory-Mapped Database Manager, or LMDB, is an embedded binary\nkey-value database. This dataset can read the contents of LMDB database files,\nthe names of which generally have the `.mdb` suffix.\n\nEach output element consists of a key-value pair represented as a pair of\nscalar string `Tensor`s, where the first `Tensor` contains the key and the\nsecond `Tensor` contains the value.\n\nLMDB uses different file formats on big- and little-endian machines.\n`LMDBDataset` can only read files in the format of the host machine.","inputs":[{"description":"A scalar or a vector containing the name(s) of the binary file(s) to be\nread.","name":"filenames","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the key-value pairs in one or more LMDB files."}},{"name":"LMDBReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the records from a LMDB file."}},{"name":"LRN","schema":{"attributes":[{"default":5,"description":"0-D. Half-width of the 1-D normalization window.","name":"depth_radius","type":"int64"},{"default":1,"description":"An offset (usually positive to avoid dividing by 0).","name":"bias","type":"float32"},{"default":1,"description":"A scale factor, usually positive.","name":"alpha","type":"float32"},{"default":0.5,"description":"An exponent.","name":"beta","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"category":"Normalization","description":"The 4-D `input` tensor is treated as a 3-D array of 1-D vectors (along the last\ndimension), and each vector is normalized independently. Within a given vector,\neach component is divided by the weighted, squared sum of inputs within\n`depth_radius`. In detail,\n\n sqr_sum[a, b, c, d] =\n sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2)\n output = input / (bias + alpha * sqr_sum) ** beta\n\nFor details, see [Krizhevsky et al., ImageNet classification with deep\nconvolutional neural networks (NIPS 2012)](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks).","inputs":[{"description":"4-D.","name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Local Response Normalization."}},{"name":"LRNGrad","schema":{"attributes":[{"default":5,"description":"A depth radius.","name":"depth_radius","type":"int64"},{"default":1,"description":"An offset (usually > 0 to avoid dividing by 0).","name":"bias","type":"float32"},{"default":1,"description":"A scale factor, usually positive.","name":"alpha","type":"float32"},{"default":0.5,"description":"An exponent.","name":"beta","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input_grads","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input_image","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`.","name":"output_image","typeAttr":"T"}],"outputs":[{"description":"The gradients for LRN.","name":"output","typeAttr":"T"}],"summary":"Gradients for Local Response Normalization."}},{"name":"LSTMBlockCell","schema":{"attributes":[{"default":1,"description":"The forget gate bias.","name":"forget_bias","type":"float32"},{"default":3,"description":"Value to clip the 'cs' value to.","name":"cell_clip","type":"float32"},{"default":false,"description":"Whether to use peephole weights.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"category":"Layer","description":"This implementation uses 1 weight matrix and 1 bias vector, and there's an\noptional peephole connection.\n\nThis kernel op implements the following mathematical equations:\n\n```python\nxh = [x, h_prev]\n[i, f, ci, o] = xh * w + b\nf = f + forget_bias\n\nif not use_peephole:\n wci = wcf = wco = 0\n\ni = sigmoid(cs_prev * wci + i)\nf = sigmoid(cs_prev * wcf + f)\nci = tanh(ci)\n\ncs = ci .* i + cs_prev .* f\ncs = clip(cs, cell_clip)\n\no = sigmoid(cs * wco + o)\nco = tanh(cs)\nh = co .* o\n```","inputs":[{"description":"The input to the LSTM cell, shape (batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"Value of the cell state at previous time step.","name":"cs_prev","typeAttr":"T"},{"description":"Output of the previous cell at previous time step.","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"}],"outputs":[{"description":"The input gate.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh.","name":"cs","typeAttr":"T"},{"description":"The forget gate.","name":"f","typeAttr":"T"},{"description":"The output gate.","name":"o","typeAttr":"T"},{"description":"The cell input.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh.","name":"co","typeAttr":"T"},{"description":"The output h vector.","name":"h","typeAttr":"T"}],"summary":"Computes the LSTM cell forward propagation for 1 time step."}},{"name":"LSTMBlockCellGrad","schema":{"attributes":[{"description":"Whether the cell uses peephole connections.","name":"use_peephole","type":"boolean"},{"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"}],"description":"This implementation is to be used in conjunction of LSTMBlockCell.","inputs":[{"description":"The input to the LSTM cell, shape (batch_size, num_inputs).","name":"x","typeAttr":"T"},{"description":"The previous cell state.","name":"cs_prev","typeAttr":"T"},{"description":"The previous h state.","name":"h_prev","typeAttr":"T"},{"description":"The weight matrix.","name":"w","typeAttr":"T"},{"description":"The weight matrix for input gate peephole connection.","name":"wci","typeAttr":"T"},{"description":"The weight matrix for forget gate peephole connection.","name":"wcf","typeAttr":"T"},{"description":"The weight matrix for output gate peephole connection.","name":"wco","typeAttr":"T"},{"description":"The bias vector.","name":"b","typeAttr":"T"},{"description":"The input gate.","name":"i","typeAttr":"T"},{"description":"The cell state before the tanh.","name":"cs","typeAttr":"T"},{"description":"The forget gate.","name":"f","typeAttr":"T"},{"description":"The output gate.","name":"o","typeAttr":"T"},{"description":"The cell input.","name":"ci","typeAttr":"T"},{"description":"The cell after the tanh.","name":"co","typeAttr":"T"},{"description":"The current gradient of cs.","name":"cs_grad","typeAttr":"T"},{"description":"The gradient of h vector.","name":"h_grad","typeAttr":"T"}],"outputs":[{"description":"The gradient of cs to be back-propped.","name":"cs_prev_grad","typeAttr":"T"},{"description":"The derivative wrt to [i, cs, f, o].","name":"dicfo","typeAttr":"T"},{"description":"The gradient for wci to be back-propped.","name":"wci_grad","typeAttr":"T"},{"description":"The gradient for wcf to be back-propped.","name":"wcf_grad","typeAttr":"T"},{"description":"The gradient for wco to be back-propped.","name":"wco_grad","typeAttr":"T"}],"summary":"Computes the LSTM cell backward propagation for 1 timestep."}},{"name":"LatencyStatsDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"tag","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Records the latency of producing `input_dataset` elements in a StatsAggregator."}},{"name":"LeakyRelu","schema":{"attributes":[{"default":0.20000000298023224,"name":"alpha","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear: `max(features, features * alpha)`."}},{"name":"LeakyReluGrad","schema":{"attributes":[{"default":0.20000000298023224,"name":"alpha","type":"float32"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding LeakyRelu operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding LeakyRelu operation,\nOR the outputs of that operation (both work equivalently).","name":"features","typeAttr":"T"}],"outputs":[{"description":"`gradients * (features > 0) + alpha * gradients * (features <= 0)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear gradients for a LeakyRelu operation."}},{"name":"LearnedUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"LeftShift","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If `y` is negative, or greater than or equal to the width of `x` in bits the\nresult is implementation defined.\n\nExample:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\nimport numpy as np\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([-1, -5, -3, -14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n\n left_shift_result = bitwise_ops.left_shift(lhs, rhs)\n\n print(left_shift_result)\n\n# This will print:\n# tf.Tensor([ -32 -5 -128 0], shape=(4,), dtype=int8)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int16)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int32)\n# tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int64)\n\nlhs = np.array([-2, 64, 101, 32], dtype=np.int8)\nrhs = np.array([-1, -5, -3, -14], dtype=np.int8)\nbitwise_ops.left_shift(lhs, rhs)\n# \n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise left-shift of `x` and `y`."}},{"name":"LegacyParallelInterleaveDatasetV2","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","name":"deterministic","type":"string"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! This dataset is not deterministic!","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"name":"cycle_length","type":9},{"name":"block_length","type":9},{"name":"buffer_output_elements","type":9},{"name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"Less","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `Less` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.less(x, y) ==> [False, True, False]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 6, 7])\ntf.math.less(x, y) ==> [False, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x < y) element-wise."}},{"name":"LessEqual","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*NOTE*: `LessEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\nExample:\n\n```python\nx = tf.constant([5, 4, 6])\ny = tf.constant([5])\ntf.math.less_equal(x, y) ==> [True, True, False]\n\nx = tf.constant([5, 4, 6])\ny = tf.constant([5, 6, 6])\ntf.math.less_equal(x, y) ==> [True, True, True]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x <= y) element-wise."}},{"name":"Lgamma","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":" For positive numbers, this function computes log((input - 1)!) for every element in the tensor.\n `lgamma(5) = log((5-1)!) = log(4!) = log(24) = 3.1780539`\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 4.5, -4, -5.6])\ntf.math.lgamma(x) ==> [inf, 0.5723649, 0., 2.4537368, inf, -4.6477685]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the log of the absolute value of `Gamma(x)` element-wise."}},{"name":"LinSpace","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"A sequence of `num` evenly-spaced values are generated beginning at `start`.\nIf `num > 1`, the values in the sequence increase by `stop - start / num - 1`,\nso that the last one is exactly `stop`.\n\nFor example:\n\n```\ntf.linspace(10.0, 12.0, 3, name=\"linspace\") => [ 10.0 11.0 12.0]\n```","inputs":[{"description":"0-D tensor. First entry in the range.","name":"start","typeAttr":"T"},{"description":"0-D tensor. Last entry in the range.","name":"stop","typeAttr":"T"},{"description":"0-D tensor. Number of values to generate.","name":"num","typeAttr":"Tidx"}],"outputs":[{"description":"1-D. The generated values.","name":"output","typeAttr":"T"}],"summary":"Generates values in an interval."}},{"name":"ListDiff","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"Given a list `x` and a list `y`, this operation returns a list `out` that\nrepresents all values that are in `x` but not in `y`. The returned list `out`\nis sorted in the same order that the numbers appear in `x` (duplicates are\npreserved). This operation also returns a list `idx` that represents the\nposition of each `out` element in `x`. In other words:\n\n`out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]`\n\nFor example, given this input:\n\n```\nx = [1, 2, 3, 4, 5, 6]\ny = [1, 3, 5]\n```\n\nThis operation would return:\n\n```\nout ==> [2, 4, 6]\nidx ==> [1, 3, 5]\n```","inputs":[{"description":"1-D. Values to keep.","name":"x","typeAttr":"T"},{"description":"1-D. Values to remove.","name":"y","typeAttr":"T"}],"outputs":[{"description":"1-D. Values present in `x` but not in `y`.","name":"out","typeAttr":"T"},{"description":"1-D. Positions of `x` values preserved in `out`.","name":"idx","typeAttr":"out_idx"}],"summary":"Computes the difference between two lists of numbers or strings."}},{"name":"LoadAndRemapMatrix","schema":{"attributes":[{"description":"Number of rows (length of the 1st dimension) in the output matrix.","minimum":0,"name":"num_rows","type":"int64"},{"description":"Number of columns (length of the 2nd dimension) in the output matrix.","minimum":1,"name":"num_cols","type":"int64"},{"default":-1,"description":"The maximum number of rows to load from the checkpoint at\nonce. If less than or equal to 0, the entire matrix will be loaded into\nmemory. Setting this arg trades increased disk reads for lower memory usage.","name":"max_rows_in_memory","type":"int64"}],"description":"at `ckpt_path` and potentially reorders its rows and columns using the\nspecified remappings.\n\nMost users should use one of the wrapper initializers (such as\n`tf.contrib.framework.load_and_remap_matrix_initializer`) instead of this\nfunction directly.\n\nThe remappings are 1-D tensors with the following properties:\n\n* `row_remapping` must have exactly `num_rows` entries. Row `i` of the output\n matrix will be initialized from the row corresponding to index\n `row_remapping[i]` in the old `Tensor` from the checkpoint.\n* `col_remapping` must have either 0 entries (indicating that no column\n reordering is needed) or `num_cols` entries. If specified, column `j` of the\n output matrix will be initialized from the column corresponding to index\n `col_remapping[j]` in the old `Tensor` from the checkpoint.\n* A value of -1 in either of the remappings signifies a \"missing\" entry. In that\n case, values from the `initializing_values` tensor will be used to fill that\n missing row or column. If `row_remapping` has `r` missing entries and\n `col_remapping` has `c` missing entries, then the following condition must be\n true:\n\n`(r * num_cols) + (c * num_rows) - (r * c) == len(initializing_values)`\n\nThe remapping tensors can be generated using the GenerateVocabRemapping op.\n\nAs an example, with row_remapping = [1, 0, -1], col_remapping = [0, 2, -1],\ninitializing_values = [0.5, -0.5, 0.25, -0.25, 42], and w(i, j) representing\nthe value from row i, column j of the old tensor in the checkpoint, the output\nmatrix will look like the following:\n\n[[w(1, 0), w(1, 2), 0.5],\n [w(0, 0), w(0, 2), -0.5],\n [0.25, -0.25, 42]]","inputs":[{"description":"Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from\nwhich the old matrix `Tensor` will be loaded.","name":"ckpt_path","type":7},{"description":"Name of the 2-D `Tensor` to load from checkpoint.","name":"old_tensor_name","type":7},{"description":"An int `Tensor` of row remappings (generally created by\n`generate_vocab_remapping`). Even if no row remapping is needed, this must\nstill be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted\nindex-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`).","name":"row_remapping","type":9},{"description":"An int `Tensor` of column remappings (generally created by\n`generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping\nis to be done (e.g. column ordering is the same).","name":"col_remapping","type":9},{"description":"A float `Tensor` containing values to fill in for cells\nin the output matrix that are not loaded from the checkpoint. Length must be\nexactly the same as the number of missing / new cells.","name":"initializing_values","type":1}],"outputs":[{"description":"Output matrix containing existing values loaded from the\ncheckpoint, and with any missing values filled in from initializing_values.","name":"output_matrix","type":1}],"summary":"Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint"}},{"name":"LoadDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"compression","type":"string"},{"name":"reader_func","type":"function"},{"minimum":0,"name":"Treader_func_args","type":"type[]"}],"inputs":[{"name":"path","type":7},{"name":"reader_func_other_args","typeListAttr":"Treader_func_args"}],"outputs":[{"name":"handle","type":21}]}},{"name":"LoadTPUEmbeddingADAMParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Value of velocities used in the ADAM optimization algorithm.","name":"velocities","type":1}],"summary":"Load ADAM embedding parameters."}},{"name":"LoadTPUEmbeddingADAMParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Value of velocities used in the ADAM optimization algorithm.","name":"velocities","type":1},{"description":"Value of gradient_accumulators used in the ADAM optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load ADAM embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingAdadeltaParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Value of updates used in the Adadelta optimization algorithm.","name":"updates","type":1}],"summary":"Load Adadelta embedding parameters."}},{"name":"LoadTPUEmbeddingAdadeltaParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Value of updates used in the Adadelta optimization algorithm.","name":"updates","type":1},{"description":"Value of gradient_accumulators used in the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Adadelta parameters with debug support."}},{"name":"LoadTPUEmbeddingAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Load Adagrad embedding parameters."}},{"name":"LoadTPUEmbeddingAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Value of gradient_accumulators used in the Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Adagrad embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingCenteredRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the centered RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the centered RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the centered RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Value of mg used in the centered RMSProp optimization algorithm.","name":"mg","type":1}],"summary":"Load centered RMSProp embedding parameters."}},{"name":"LoadTPUEmbeddingFTRLParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Value of linears used in the FTRL optimization algorithm.","name":"linears","type":1}],"summary":"Load FTRL embedding parameters."}},{"name":"LoadTPUEmbeddingFTRLParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Value of linears used in the FTRL optimization algorithm.","name":"linears","type":1},{"description":"Value of gradient_accumulators used in the FTRL optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load FTRL embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingMDLAdagradLightParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the MDL Adagrad Light optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the MDL Adagrad Light optimization algorithm.","name":"accumulators","type":1},{"description":"Value of weights used in the MDL Adagrad Light optimization algorithm.","name":"weights","type":1},{"description":"Value of benefits used in the MDL Adagrad Light optimization algorithm.","name":"benefits","type":1}],"summary":"Load MDL Adagrad Light embedding parameters."}},{"name":"LoadTPUEmbeddingMomentumParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the Momentum optimization algorithm.","name":"momenta","type":1}],"summary":"Load Momentum embedding parameters."}},{"name":"LoadTPUEmbeddingMomentumParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Value of momenta used in the Momentum optimization algorithm.","name":"momenta","type":1},{"description":"Value of gradient_accumulators used in the Momentum optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load Momentum embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingProximalAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the proximal Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Load proximal Adagrad embedding parameters."}},{"name":"LoadTPUEmbeddingProximalAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Value of accumulators used in the proximal Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Value of gradient_accumulators used in the proximal Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load proximal Adagrad embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingProximalYogiParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"inputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1}]}},{"name":"LoadTPUEmbeddingProximalYogiParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"inputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1},{"name":"gradient_accumulators","type":1}]}},{"name":"LoadTPUEmbeddingRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the RMSProp optimization algorithm.","name":"mom","type":1}],"summary":"Load RMSProp embedding parameters."}},{"name":"LoadTPUEmbeddingRMSPropParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Value of ms used in the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Value of mom used in the RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Value of gradient_accumulators used in the RMSProp optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load RMSProp embedding parameters with debug support."}},{"name":"LoadTPUEmbeddingStochasticGradientDescentParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the stochastic gradient descent optimization algorithm.","name":"parameters","type":1}],"summary":"Load SGD embedding parameters."}},{"name":"LoadTPUEmbeddingStochasticGradientDescentParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that loads optimization parameters into HBM for embedding. Must be\npreceded by a ConfigureTPUEmbeddingHost op that sets up the correct\nembedding table configuration. For example, this op is used to install\nparameters that are loaded from a checkpoint before a training loop is\nexecuted.","inputs":[{"description":"Value of parameters used in the stochastic gradient descent optimization algorithm.","name":"parameters","type":1},{"description":"Value of gradient_accumulators used in the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Load SGD embedding parameters."}},{"name":"Log","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\log_e x\\\\).\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 5])\ntf.math.log(x) ==> [-inf, -0.6931472, 0. , 1.609438]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes natural logarithm of x element-wise."}},{"name":"Log1p","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\log_e (1 + x)\\\\).\n\nExample:\n\n```python\nx = tf.constant([0, 0.5, 1, 5])\ntf.math.log1p(x) ==> [0., 0.4054651, 0.6931472, 1.7917595]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes natural logarithm of (1 + x) element-wise."}},{"name":"LogMatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"one or more square matrices.\n\nThe input is a tensor of shape `[N, M, M]` whose inner-most 2 dimensions\nform square matrices. The outputs are two tensors containing the signs and\nabsolute values of the log determinants for all N input submatrices\n`[..., :, :]` such that the determinant = sign*exp(log_abs_determinant).\nThe log_abs_determinant is computed as det(P)*sum(log(diag(LU))) where LU\nis the LU decomposition of the input and P is the corresponding\npermutation matrix.","inputs":[{"description":"Shape is `[N, M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The signs of the log determinants of the inputs. Shape is `[N]`.","name":"sign","typeAttr":"T"},{"description":"The logs of the absolute values of the determinants\nof the N input matrices. Shape is `[N]`.","name":"log_abs_determinant","typeAttr":"T"}],"summary":"Computes the sign and the log of the absolute value of the determinant of"}},{"name":"LogSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"For each batch `i` and class `j` we have\n\n logsoftmax[i, j] = logits[i, j] - log(sum(exp(logits[i])))","inputs":[{"description":"2-D with shape `[batch_size, num_classes]`.","name":"logits","typeAttr":"T"}],"outputs":[{"description":"Same shape as `logits`.","name":"logsoftmax","typeAttr":"T"}],"summary":"Computes log softmax activations."}},{"name":"LogUniformCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a log-uniform distribution."}},{"name":"LogicalAnd","schema":{"description":"*NOTE*: `LogicalAnd` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","type":10},{"name":"y","type":10}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of x AND y element-wise."}},{"name":"LogicalNot","schema":{"inputs":[{"description":"A `Tensor` of type `bool`.","name":"x","type":10}],"outputs":[{"description":"A `Tensor` of type `bool` with the same shape as `x`. The logical negation of `x`.","name":"y","type":10}],"summary":"Returns the truth value of `NOT x` element-wise."}},{"name":"LogicalOr","schema":{"description":"*NOTE*: `LogicalOr` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","type":10},{"name":"y","type":10}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of x OR y element-wise."}},{"name":"LookupTableExport","schema":{"attributes":[{"name":"Tkeys","type":"type"},{"name":"Tvalues","type":"type"}],"inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7}],"outputs":[{"description":"Vector of all keys present in the table.","name":"keys","typeAttr":"Tkeys"},{"description":"Tensor of all values in the table. Indexed in parallel with `keys`.","name":"values","typeAttr":"Tvalues"}],"summary":"Outputs all keys and values in the table."}},{"name":"LookupTableExportV2","schema":{"attributes":[{"name":"Tkeys","type":"type"},{"name":"Tvalues","type":"type"}],"inputs":[{"description":"Handle to the table.","name":"table_handle","type":20}],"outputs":[{"description":"Vector of all keys present in the table.","name":"keys","typeAttr":"Tkeys"},{"description":"Tensor of all values in the table. Indexed in parallel with `keys`.","name":"values","typeAttr":"Tvalues"}],"summary":"Outputs all keys and values in the table."}},{"name":"LookupTableFind","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table.\nThe output `values` is of the type of the table values.\n\nThe scalar `default_value` is the value output for keys not present in the\ntable. It must also be of the same type as the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"name":"default_value","typeAttr":"Tout"}],"outputs":[{"description":"Same shape as `keys`. Values found in the table, or `default_values`\nfor missing keys.","name":"values","typeAttr":"Tout"}],"summary":"Looks up keys in a table, outputs the corresponding values."}},{"name":"LookupTableFindV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table.\nThe output `values` is of the type of the table values.\n\nThe scalar `default_value` is the value output for keys not present in the\ntable. It must also be of the same type as the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"name":"default_value","typeAttr":"Tout"}],"outputs":[{"description":"Same shape as `keys`. Values found in the table, or `default_values`\nfor missing keys.","name":"values","typeAttr":"Tout"}],"summary":"Looks up keys in a table, outputs the corresponding values."}},{"name":"LookupTableImport","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Replaces the contents of the table with the specified keys and values."}},{"name":"LookupTableImportV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Replaces the contents of the table with the specified keys and values."}},{"name":"LookupTableInsert","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Updates the table to associates keys with values."}},{"name":"LookupTableInsertV2","schema":{"attributes":[{"name":"Tin","type":"type"},{"name":"Tout","type":"type"}],"description":"The tensor `keys` must be of the same type as the keys of the table.\nThe tensor `values` must be of the type of the table values.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys to look up.","name":"keys","typeAttr":"Tin"},{"description":"Values to associate with keys.","name":"values","typeAttr":"Tout"}],"summary":"Updates the table to associates keys with values."}},{"name":"LookupTableRemoveV2","schema":{"attributes":[{"name":"Tin","type":"type"}],"description":"The tensor `keys` must of the same type as the keys of the table. Keys not\nalready in the table are silently ignored.","inputs":[{"description":"Handle to the table.","name":"table_handle","type":20},{"description":"Any shape. Keys of the elements to remove.","name":"keys","typeAttr":"Tin"}],"summary":"Removes keys and its associated values from a table."}},{"name":"LookupTableSize","schema":{"inputs":[{"description":"Handle to the table.","isRef":true,"name":"table_handle","type":7}],"outputs":[{"description":"Scalar that contains number of elements in the table.","name":"size","type":9}],"summary":"Computes the number of elements in the given table."}},{"name":"LookupTableSizeV2","schema":{"inputs":[{"description":"Handle to the table.","name":"table_handle","type":20}],"outputs":[{"description":"Scalar that contains number of elements in the table.","name":"size","type":9}],"summary":"Computes the number of elements in the given table."}},{"name":"LoopCond","schema":{"description":"This operator represents the loop termination condition used by the\n\"pivot\" switches of a loop.","inputs":[{"description":"A boolean scalar, representing the branch predicate of the Switch op.","name":"input","type":10}],"outputs":[{"description":"The same tensor as `input`.","name":"output","type":10}],"summary":"Forwards the input to the output."}},{"name":"LowerBound","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"Each set of rows with the same index in (sorted_inputs, values) is treated\nindependently. The resulting row is the equivalent of calling\n`np.searchsorted(sorted_inputs, values, side='left')`.\n\nThe result is not a global index to the entire\n`Tensor`, but rather just the index in the last dimension.\n\nA 2-D example:\n sorted_sequence = [[0, 3, 9, 9, 10],\n [1, 2, 3, 4, 5]]\n values = [[2, 4, 9],\n [0, 2, 6]]\n\n result = LowerBound(sorted_sequence, values)\n\n result == [[1, 2, 2],\n [0, 1, 5]]","inputs":[{"description":"2-D Tensor where each row is ordered.","name":"sorted_inputs","typeAttr":"T"},{"description":"2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains\nthe values that will be searched for in `sorted_search_values`.","name":"values","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `values`. It contains the first scalar index\ninto the last dimension where values can be inserted without changing the\nordered property.","name":"output","typeAttr":"out_type"}],"summary":"Applies lower_bound(sorted_search_values, values) along each row."}},{"name":"Lu","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"output_idx_type","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices.\n\nThe input has to be invertible.\n\nThe output consists of two tensors LU and P containing the LU decomposition\nof all input submatrices `[..., :, :]`. LU encodes the lower triangular and\nupper triangular factors.\n\nFor each input submatrix of shape `[M, M]`, L is a lower triangular matrix of\nshape `[M, M]` with unit diagonal whose entries correspond to the strictly lower\ntriangular part of LU. U is a upper triangular matrix of shape `[M, M]` whose\nentries correspond to the upper triangular part, including the diagonal, of LU.\n\nP represents a permutation matrix encoded as a list of indices each between `0`\nand `M-1`, inclusive. If P_mat denotes the permutation matrix corresponding to\nP, then the L, U and P satisfies P_mat * input = L * U.","inputs":[{"description":"A tensor of shape `[..., M, M]` whose inner-most 2 dimensions form matrices of\nsize `[M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"A tensor of shape `[..., M, M]` whose strictly lower triangular part denotes the\nlower triangular factor `L` with unit diagonal, and whose upper triangular part\ndenotes the upper triangular factor `U`.","name":"lu","typeAttr":"T"},{"description":"Permutation of the rows encoded as a list of indices in `0..M-1`. Shape is\n`[..., M]`.\n@compatibility(scipy)\nSimilar to `scipy.linalg.lu`, except the triangular factors `L` and `U` are\npacked into a single tensor, the permutation is applied to `input` instead of\nthe right hand side and the permutation `P` is returned as a list of indices\ninstead of a permutation matrix.\n@end_compatibility","name":"p","typeAttr":"output_idx_type"}],"summary":"Computes the LU decomposition of one or more square matrices."}},{"name":"MakeIterator","schema":{"description":"This operation may be executed multiple times. Each execution will reset the\niterator in `iterator` to the first element of `dataset`.","inputs":[{"name":"dataset","type":21},{"name":"iterator","type":20}],"summary":"Makes a new iterator from the given `dataset` and stores it in `iterator`."}},{"name":"MakeUnique","schema":{"description":"their initial value. Never returns a sub-normal number. Never returns\nzero. The sign of each input element is always identical to the sign\nof the corresponding output element. Behavior for infinite elements is\nundefined. Behavior for subnormal elements is undefined.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"output","type":1}],"summary":"Make all elements in the non-Batch dimension unique, but \\\"close\\\" to"}},{"name":"MapAndBatchDataset","schema":{"attributes":[{"description":"A function to apply to the outputs of `input_dataset`.","name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Creates a dataset that applies `f` to the outputs of `input_dataset` and then\nbatches `batch_size` of them.\n\nUnlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `batch_size * num_parallel_batches` copies of `f` in parallel.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when building a closure\nfor `f`.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"A scalar representing the number of elements to accumulate in a\nbatch. It determines the number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"batch_size","type":9},{"description":"A scalar representing the maximum number of parallel invocations of the `map_fn`\nfunction. Applying the `map_fn` on consecutive input elements in parallel has\nthe potential to improve input pipeline throughput.","name":"num_parallel_calls","type":9},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that fuses mapping with batching."}},{"name":"MapClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"MapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"MapDefun","schema":{"attributes":[{"description":"A list of types.","minimum":1,"name":"Targuments","type":"type[]"},{"default":[],"description":"A list of types.","minimum":0,"name":"Tcaptured","type":"type[]"},{"description":"A list of types.","minimum":1,"name":"output_types","type":"type[]"},{"description":"A list of shapes.","minimum":1,"name":"output_shapes","type":"shape[]"},{"name":"f","type":"function"},{"default":1,"name":"max_intra_op_parallelism","type":"int64"}],"inputs":[{"description":" A list of tensors whose types are `Targuments`, corresponding to the inputs\n the function should be mapped over.","name":"arguments","typeListAttr":"Targuments"},{"description":" A list of tensors whose types are `Tcaptured`, corresponding to the captured\n inputs of the defun.","name":"captured_inputs","typeListAttr":"Tcaptured"}],"outputs":[{"description":" A list of output tensors whose types are `output_types` and whose dimensions\n 0 are the same as the dimensions 0 of the tensors in `arguments`, and whose\n remaining dimensions correspond to those in `output_shapes`.","name":"output","typeListAttr":"output_types"}],"summary":" Maps a function on the list of tensors unpacked from arguments on dimension 0.\n The function given by `f` is assumed to be stateless, and is executed\n concurrently on all the slices; up to batch_size (i.e. the size of the 0th\n dimension of each argument) functions will be scheduled at once.\n\n The `max_intra_op_parallelism` attr, which defaults to 1, can be used to\n limit the intra op parallelism. To limit inter-op parallelism, a user can\n set a private threadpool on the dataset using `tf.data.Options`'s\n `ThreadingOptions`.\n\n Note that this op is not exposed to users directly, but is invoked in tf.data\n rewrites."}},{"name":"MapIncompleteSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of incomplete elements in the underlying container."}},{"name":"MapPeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain this key\nthis op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified key. If the"}},{"name":"MapSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"MapStage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"minimum":1,"name":"fake_dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"inputs":[{"description":"int64","name":"key","type":9},{"name":"indices","type":3},{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"fake_dtypes"}],"summary":"Stage (key, values) in the underlying container which behaves like a hashtable."}},{"name":"MapUnstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain this key, the op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the values associated with the key"}},{"name":"MapUnstageNoKey","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain elements, the op will block until it does.","inputs":[{"name":"indices","type":3}],"outputs":[{"name":"key","type":9},{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns a random (key, value)"}},{"name":"MatMul","schema":{"attributes":[{"default":false,"description":"If true, \"a\" is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, \"b\" is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of\n\"a\" (after being transposed if transpose_a is true) must match the\nouter dimension of \"b\" (after being transposed if transposed_b is\ntrue).\n\n*Note*: The default kernel implementation for MatMul on GPUs uses\ncublas.","inputs":[{"name":"a","typeAttr":"T"},{"name":"b","typeAttr":"T"}],"outputs":[{"name":"product","typeAttr":"T"}],"summary":"Multiply the matrix \"a\" by the matrix \"b\"."}},{"name":"MatchingFiles","schema":{"description":"Note that this routine only supports wildcard characters in the\nbasename portion of the pattern, not in the directory portion.\nNote also that the order of filenames returned is deterministic.","inputs":[{"description":"Shell wildcard pattern(s). Scalar or vector of type string.","name":"pattern","type":7}],"outputs":[{"description":"A vector of matching filenames.","name":"filenames","type":7}],"summary":"Returns the set of files matching one or more glob patterns."}},{"name":"MatchingFilesDataset","schema":{"inputs":[{"name":"patterns","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"MatrixBandPart","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tindex","type":"type"}],"description":"The `band` part is computed as follows:\nAssume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a\ntensor with the same shape where\n\n`band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n\nThe indicator function\n\n`in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) &&\n (num_upper < 0 || (n-m) <= num_upper)`.\n\nFor example:\n\n```\n# if 'input' is [[ 0, 1, 2, 3]\n [-1, 0, 1, 2]\n [-2, -1, 0, 1]\n [-3, -2, -1, 0]],\n\ntf.matrix_band_part(input, 1, -1) ==> [[ 0, 1, 2, 3]\n [-1, 0, 1, 2]\n [ 0, -1, 0, 1]\n [ 0, 0, -1, 0]],\n\ntf.matrix_band_part(input, 2, 1) ==> [[ 0, 1, 0, 0]\n [-1, 0, 1, 0]\n [-2, -1, 0, 1]\n [ 0, -2, -1, 0]]\n```\n\nUseful special cases:\n\n```\n tf.matrix_band_part(input, 0, -1) ==> Upper triangular part.\n tf.matrix_band_part(input, -1, 0) ==> Lower triangular part.\n tf.matrix_band_part(input, 0, 0) ==> Diagonal.\n```","inputs":[{"description":"Rank `k` tensor.","name":"input","typeAttr":"T"},{"description":"0-D tensor. Number of subdiagonals to keep. If negative, keep entire\nlower triangle.","name":"num_lower","typeAttr":"Tindex"},{"description":"0-D tensor. Number of superdiagonals to keep. If negative, keep\nentire upper triangle.","name":"num_upper","typeAttr":"Tindex"}],"outputs":[{"description":"Rank `k` tensor of the same shape as input. The extracted banded tensor.","name":"band","typeAttr":"T"}],"summary":"Copy a tensor setting everything outside a central band in each innermost matrix to zero."}},{"name":"MatrixDeterminant","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor containing the determinants\nfor all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[...]`.","name":"output","typeAttr":"T"}],"summary":"Computes the determinant of one or more square matrices."}},{"name":"MatrixDiag","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given a `diagonal`, this operation returns a tensor with the `diagonal` and\neverything else padded with zeros. The diagonal is computed as follows:\n\nAssume `diagonal` has `k` dimensions `[I, J, K, ..., N]`, then the output is a\ntensor of rank `k+1` with dimensions [I, J, K, ..., N, N]` where:\n\n`output[i, j, k, ..., m, n] = 1{m=n} * diagonal[i, j, k, ..., n]`.\n\nFor example:\n\n```\n# 'diagonal' is [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nand diagonal.shape = (2, 4)\n\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]],\n [[5, 0, 0, 0]\n [0, 6, 0, 0]\n [0, 0, 7, 0]\n [0, 0, 0, 8]]]\n\nwhich has shape (2, 4, 4)\n```","inputs":[{"description":"Rank `k`, where `k >= 1`.","name":"diagonal","typeAttr":"T"}],"outputs":[{"description":"Rank `k+1`, with `output.shape = diagonal.shape + [diagonal.shape[-1]]`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with a given batched diagonal values."}},{"name":"MatrixDiagPart","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This operation returns a tensor with the `diagonal` part\nof the batched `input`. The `diagonal` part is computed as follows:\n\nAssume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a\ntensor of rank `k - 1` with dimensions `[I, J, K, ..., min(M, N)]` where:\n\n`diagonal[i, j, k, ..., n] = input[i, j, k, ..., n, n]`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\n# 'input' is [[[1, 0, 0, 0]\n [0, 2, 0, 0]\n [0, 0, 3, 0]\n [0, 0, 0, 4]],\n [[5, 0, 0, 0]\n [0, 6, 0, 0]\n [0, 0, 7, 0]\n [0, 0, 0, 8]]]\n\nand input.shape = (2, 4, 4)\n\ntf.matrix_diag_part(input) ==> [[1, 2, 3, 4], [5, 6, 7, 8]]\n\nwhich has shape (2, 4)\n```","inputs":[{"description":"Rank `k` tensor where `k >= 2`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s) having shape\n`diagonal.shape = input.shape[:-2] + [min(input.shape[-2:])]`.","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagPartV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n`input`.\n\nAssume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\nLet `max_diag_len` be the maximum length among all diagonals to be extracted,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\nLet `num_diags` be the number of diagonals to extract,\n`num_diags = k[1] - k[0] + 1`.\n\nIf `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n`[I, J, ..., L, max_diag_len]` and values:\n\n```\ndiagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\nOtherwise, the output tensor has rank `r` with dimensions\n`[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n```\ndiagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `d = k[1] - m`, `y = max(-d, 0)`, and `x = max(d, 0)`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\ninput = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n# A main diagonal from each batch.\ntf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n# A superdiagonal from each batch.\ntf.matrix_diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n# A tridiagonal band from each batch.\ntf.matrix_diag_part(input, k = (-1, 1))\n ==> [[[2, 7, 6], # Output shape: (2, 3, 3)\n [1, 6, 7],\n [5, 8, 0]],\n [[4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n# Padding value = 9\ntf.matrix_diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[4, 9, 9], # Output shape: (2, 3, 3)\n [3, 8, 9],\n [2, 7, 6]],\n [[2, 9, 9],\n [3, 4, 9],\n [4, 3, 8]]]\n```","inputs":[{"description":"Rank `r` tensor where `r >= 2`.","name":"input","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The value to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s).","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagPartV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n`input`.\n\nAssume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\nLet `max_diag_len` be the maximum length among all diagonals to be extracted,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\nLet `num_diags` be the number of diagonals to extract,\n`num_diags = k[1] - k[0] + 1`.\n\nIf `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n`[I, J, ..., L, max_diag_len]` and values:\n\n```\ndiagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\nOtherwise, the output tensor has rank `r` with dimensions\n`[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n```\ndiagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n```\nwhere `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nThe input must be at least a matrix.\n\nFor example:\n\n```\ninput = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n# A main diagonal from each batch.\ntf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n# A superdiagonal from each batch.\ntf.matrix_diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n# A band from each batch.\ntf.matrix_diag_part(input, k = (-1, 2))\n ==> [[[0, 3, 8], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [5, 8, 0]],\n [[0, 3, 4],\n [4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n# LEFT_RIGHT alignment.\ntf.matrix_diag_part(input, k = (-1, 2), align=\"LEFT_RIGHT\")\n ==> [[[3, 8, 0], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [0, 5, 8]],\n [[3, 4, 0],\n [4, 3, 8],\n [5, 2, 7],\n [0, 1, 6]]]\n\n# max_diag_len can be shorter than the main diagonal.\ntf.matrix_diag_part(input, k = (-2, -1))\n ==> [[[5, 8],\n [9, 0]],\n [[1, 6],\n [5, 0]]]\n\n# padding_value = 9\ntf.matrix_diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[9, 9, 4], # Output shape: (2, 3, 3)\n [9, 3, 8],\n [2, 7, 6]],\n [[9, 9, 2],\n [9, 3, 4],\n [4, 3, 8]]]\n\n```","inputs":[{"description":"Rank `r` tensor where `r >= 2`.","name":"input","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The value to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"The extracted diagonal(s).","name":"diagonal","typeAttr":"T"}],"summary":"Returns the batched diagonal part of a batched tensor."}},{"name":"MatrixDiagV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\ndiagonals of a matrix, with everything else padded with `padding`. `num_rows`\nand `num_cols` specify the dimension of the innermost matrix of the output. If\nboth are not specified, the op assumes the innermost matrix is square and infers\nits size from `k` and the innermost dimension of `diagonal`. If only one of them\nis specified, the op assumes the unspecified value is the smallest possible\nbased on other criteria.\n\nLet `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has\nrank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one\ndiagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank\n`r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\nThe second innermost dimension of `diagonal` has double meaning.\nWhen `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size\n[I, J, ..., M], and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n```\n\nOtherwise, `M` is treated as the number of diagonals for the matrix in the\nsame batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`.\n\nFor example:\n\n```\n# The main diagonal.\ndiagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n# A superdiagonal (per batch).\ndiagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3)\n [4, 5, 0]],\n [[6, 7, 9],\n [9, 1, 0]]])\ntf.matrix_diag(diagonals, k = (-1, 0))\n ==> [[[1, 0, 0], # Output shape: (2, 3, 3)\n [4, 2, 0],\n [0, 5, 3]],\n [[6, 0, 0],\n [9, 7, 0],\n [0, 1, 9]]]\n\n# Rectangular matrix.\ndiagonal = np.array([1, 2]) # Input shape: (2)\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n# Rectangular matrix with inferred num_cols and padding_value = 9.\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n```","inputs":[{"description":"Rank `r`, where `r >= 1`","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The number of rows of the output matrix. If it is not provided, the op assumes\nthe output matrix is a square matrix and infers the matrix size from k and the\ninnermost dimension of `diagonal`.","name":"num_rows","type":3},{"description":"The number of columns of the output matrix. If it is not provided, the op\nassumes the output matrix is a square matrix and infers the matrix size from\nk and the innermost dimension of `diagonal`.","name":"num_cols","type":3},{"description":"The number to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"Has rank `r+1` when `k` is an integer or `k[0] == k[1]`, rank `r` otherwise.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with given batched diagonal values."}},{"name":"MatrixDiagV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\ndiagonals of a matrix, with everything else padded with `padding`. `num_rows`\nand `num_cols` specify the dimension of the innermost matrix of the output. If\nboth are not specified, the op assumes the innermost matrix is square and infers\nits size from `k` and the innermost dimension of `diagonal`. If only one of them\nis specified, the op assumes the unspecified value is the smallest possible\nbased on other criteria.\n\nLet `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has\nrank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one\ndiagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank\n`r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\nThe second innermost dimension of `diagonal` has double meaning.\nWhen `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size\n[I, J, ..., M], and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n```\n\nOtherwise, `M` is treated as the number of diagonals for the matrix in the\nsame batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n```\nwhere `d = n - m`, `diag_index = [k] - d`, and\n`index_in_diag = n - max(d, 0) + offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nFor example:\n\n```\n# The main diagonal.\ndiagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\ntf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n# A superdiagonal (per batch).\ndiagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n# A tridiagonal band (per batch).\ndiagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 2, 3],\n [6, 7, 9],\n [9, 1, 0]]])\ntf.matrix_diag(diagonals, k = (-1, 1))\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n# LEFT_RIGHT alignment.\ndiagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [0, 4, 5]],\n [[2, 3, 0],\n [6, 7, 9],\n [0, 9, 1]]])\ntf.matrix_diag(diagonals, k = (-1, 1), align=\"LEFT_RIGHT\")\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n# Rectangular matrix.\ndiagonal = np.array([1, 2]) # Input shape: (2)\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n# Rectangular matrix with inferred num_cols and padding_value = 9.\ntf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n\n```","inputs":[{"description":"Rank `r`, where `r >= 1`","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3},{"description":"The number of rows of the output matrix. If it is not provided, the op assumes\nthe output matrix is a square matrix and infers the matrix size from k and the\ninnermost dimension of `diagonal`.","name":"num_rows","type":3},{"description":"The number of columns of the output matrix. If it is not provided, the op\nassumes the output matrix is a square matrix and infers the matrix size from\nk and the innermost dimension of `diagonal`.","name":"num_cols","type":3},{"description":"The number to fill the area outside the specified diagonal band with.\nDefault is 0.","name":"padding_value","typeAttr":"T"}],"outputs":[{"description":"Has rank `r+1` when `k` is an integer or `k[0] == k[1]`, rank `r` otherwise.","name":"output","typeAttr":"T"}],"summary":"Returns a batched diagonal tensor with given batched diagonal values."}},{"name":"MatrixExponential","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Deprecated, use python implementation tf.linalg.matrix_exponential."}},{"name":"MatrixInverse","schema":{"attributes":[{"default":false,"name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the inverse for all input submatrices `[..., :, :]`.\n\nThe op uses LU decomposition with partial pivoting to compute the inverses.\n\nIf a matrix is not invertible there is no guarantee what the op does. It\nmay detect the condition and raise an exception or it may simply return a\ngarbage result.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(numpy)\nEquivalent to np.linalg.inv\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes)."}},{"name":"MatrixLogarithm","schema":{"attributes":[{"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n\\\\(log(exp(A)) = A\\\\)\n\nThis op is only defined for complex matrices. If A is positive-definite and\nreal, then casting to a complex matrix, taking the logarithm and casting back\nto a real matrix will give the correct result.\n\nThis function computes the matrix logarithm using the Schur-Parlett algorithm.\nDetails of the algorithm can be found in Section 11.6.2 of:\nNicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008.\nISBN 978-0-898716-46-7.\n\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the exponential for all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(scipy)\nEquivalent to scipy.linalg.logm\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the matrix logarithm of one or more square matrices:"}},{"name":"MatrixSetDiag","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the main diagonal of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\nThe output is computed as follows:\n\nAssume `input` has `k+1` dimensions `[I, J, K, ..., M, N]` and `diagonal` has\n`k` dimensions `[I, J, K, ..., min(M, N)]`. Then the output is a\ntensor of rank `k+1` with dimensions `[I, J, K, ..., M, N]` where:\n\n * `output[i, j, k, ..., m, n] = diagonal[i, j, k, ..., n]` for `m == n`.\n * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`.","inputs":[{"description":"Rank `k+1`, where `k >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `k`, where `k >= 1`.","name":"diagonal","typeAttr":"T"}],"outputs":[{"description":"Rank `k+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSetDiagV2","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the specified diagonals of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\n`input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n`k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\nOtherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n`num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n`max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\nThe output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\nIf `k` is scalar or `k[0] == k[1]`:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\n\nOtherwise,\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`.\n\nFor example:\n\n```\n# The main diagonal.\ninput = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\ndiagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_set_diag(diagonal) ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n# A superdiagonal (per batch).\ntf.matrix_set_diag(diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[1, 2, 3], # Diagonal shape: (2, 2, 3)\n [4, 5, 0]],\n [[6, 1, 2],\n [3, 4, 0]]])\ntf.matrix_set_diag(diagonals, k = (-1, 0))\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [4, 2, 7, 7],\n [0, 5, 3, 7]],\n [[6, 7, 7, 7],\n [3, 1, 7, 7],\n [7, 4, 2, 7]]]\n\n```","inputs":[{"description":"Rank `r+1`, where `r >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`.\n`k >= 1`.","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3}],"outputs":[{"description":"Rank `r+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSetDiagV3","schema":{"attributes":[{"name":"T","type":"type"},{"default":"RIGHT_LEFT","description":"Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is\na string specifying how superdiagonals and subdiagonals should be aligned,\nrespectively. There are four possible alignments: \"RIGHT_LEFT\" (default),\n\"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\" aligns superdiagonals\nto the right (left-pads the row) and subdiagonals to the left (right-pads the\nrow). It is the packing format LAPACK uses. cuSPARSE uses \"LEFT_RIGHT\", which is\nthe opposite alignment. Must be one of the following: `LEFT_RIGHT`, `RIGHT_LEFT`, `LEFT_LEFT`, `RIGHT_RIGHT`.","name":"align","type":"string"}],"description":"Given `input` and `diagonal`, this operation returns a tensor with the\nsame shape and values as `input`, except for the specified diagonals of the\ninnermost matrices. These will be overwritten by the values in `diagonal`.\n\n`input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n`k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\nOtherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n`num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n`max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n`max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\nThe output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\nIf `k` is scalar or `k[0] == k[1]`:\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\n\nOtherwise,\n\n```\noutput[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n```\nwhere `d = n - m`, `diag_index = k[1] - d`, and\n`index_in_diag = n - max(d, 0) + offset`.\n\n`offset` is zero except when the alignment of the diagonal is to the right.\n```\noffset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n```\nwhere `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\nFor example:\n\n```\n# The main diagonal.\ninput = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\ndiagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\ntf.matrix_set_diag(input, diagonal)\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n# A superdiagonal (per batch).\ntf.matrix_set_diag(input, diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n# A band of diagonals.\ndiagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 1, 2],\n [5, 6, 4],\n [6, 1, 2],\n [3, 4, 0]]])\ntf.matrix_set_diag(input, diagonals, k = (-1, 2))\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n# LEFT_RIGHT alignment.\ndiagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [0, 4, 5]],\n [[1, 2, 0],\n [5, 6, 4],\n [6, 1, 2],\n [0, 3, 4]]])\ntf.matrix_set_diag(input, diagonals, k = (-1, 2), align=\"LEFT_RIGHT\")\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n```","inputs":[{"description":"Rank `r+1`, where `r >= 1`.","name":"input","typeAttr":"T"},{"description":"Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`.\n`k >= 1`.","name":"diagonal","typeAttr":"T"},{"description":"Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main\ndiagonal, and negative value means subdiagonals. `k` can be a single integer\n(for a single diagonal) or a pair of integers specifying the low and high ends\nof a matrix band. `k[0]` must not be larger than `k[1]`.","name":"k","type":3}],"outputs":[{"description":"Rank `r+1`, with `output.shape = input.shape`.","name":"output","typeAttr":"T"}],"summary":"Returns a batched matrix tensor with new batched diagonal values."}},{"name":"MatrixSolve","schema":{"attributes":[{"default":false,"description":"Boolean indicating whether to solve with `matrix` or its (block-wise)\nadjoint.","name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"`Matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. `Rhs` is a tensor of shape `[..., M, K]`. The `output` is\na tensor shape `[..., M, K]`. If `adjoint` is `False` then each output matrix\nsatisfies `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`.\nIf `adjoint` is `True` then each output matrix satisfies\n`adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves systems of linear equations."}},{"name":"MatrixSolveLs","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"fast","type":"boolean"}],"description":"`matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform real or complex matrices of size `[M, N]`. `Rhs` is a tensor of the same\ntype as `matrix` and shape `[..., M, K]`.\nThe output is a tensor shape `[..., N, K]` where each output matrix solves\neach of the equations\n`matrix[..., :, :]` * `output[..., :, :]` = `rhs[..., :, :]`\nin the least squares sense.\n\nWe use the following notation for (complex) matrix and right-hand sides\nin the batch:\n\n`matrix`=\\\\(A \\in \\mathbb{C}^{m \\times n}\\\\),\n`rhs`=\\\\(B \\in \\mathbb{C}^{m \\times k}\\\\),\n`output`=\\\\(X \\in \\mathbb{C}^{n \\times k}\\\\),\n`l2_regularizer`=\\\\(\\lambda \\in \\mathbb{R}\\\\).\n\nIf `fast` is `True`, then the solution is computed by solving the normal\nequations using Cholesky decomposition. Specifically, if \\\\(m \\ge n\\\\) then\n\\\\(X = (A^H A + \\lambda I)^{-1} A^H B\\\\), which solves the least-squares\nproblem \\\\(X = \\mathrm{argmin}_{Z \\in \\Re^{n \\times k} } ||A Z - B||_F^2 + \\lambda ||Z||_F^2\\\\).\nIf \\\\(m \\lt n\\\\) then `output` is computed as\n\\\\(X = A^H (A A^H + \\lambda I)^{-1} B\\\\), which (for \\\\(\\lambda = 0\\\\)) is the\nminimum-norm solution to the under-determined linear system, i.e.\n\\\\(X = \\mathrm{argmin}_{Z \\in \\mathbb{C}^{n \\times k} } ||Z||_F^2 \\\\),\nsubject to \\\\(A Z = B\\\\). Notice that the fast path is only numerically stable\nwhen \\\\(A\\\\) is numerically full rank and has a condition number\n\\\\(\\mathrm{cond}(A) \\lt \\frac{1}{\\sqrt{\\epsilon_{mach} } }\\\\) or \\\\(\\lambda\\\\) is\nsufficiently large.\n\nIf `fast` is `False` an algorithm based on the numerically robust complete\northogonal decomposition is used. This computes the minimum-norm\nleast-squares solution, even when \\\\(A\\\\) is rank deficient. This path is\ntypically 6-7 times slower than the fast path. If `fast` is `False` then\n`l2_regularizer` is ignored.","inputs":[{"description":"Shape is `[..., M, N]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"},{"description":"Scalar tensor.\n\n@compatibility(numpy)\nEquivalent to np.linalg.lstsq\n@end_compatibility","name":"l2_regularizer","type":2}],"outputs":[{"description":"Shape is `[..., N, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves one or more linear least-squares problems."}},{"name":"MatrixSquareRoot","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"matmul(sqrtm(A), sqrtm(A)) = A\n\nThe input matrix should be invertible. If the input matrix is real, it should\nhave no eigenvalues which are real and negative (pairs of complex conjugate\neigenvalues are allowed).\n\nThe matrix square root is computed by first reducing the matrix to\nquasi-triangular form with the real Schur decomposition. The square root\nof the quasi-triangular matrix is then computed directly. Details of\nthe algorithm can be found in: Nicholas J. Higham, \"Computing real\nsquare roots of a real matrix\", Linear Algebra Appl., 1987.\n\nThe input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices. The output is a tensor of the same shape as the input\ncontaining the matrix square root for all input submatrices `[..., :, :]`.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, M]`.\n\n@compatibility(scipy)\nEquivalent to scipy.linalg.sqrtm\n@end_compatibility","name":"output","typeAttr":"T"}],"summary":"Computes the matrix square root of one or more square matrices:"}},{"name":"MatrixTriangularSolve","schema":{"attributes":[{"default":true,"description":"Boolean indicating whether the innermost matrices in `matrix` are\nlower or upper triangular.","name":"lower","type":"boolean"},{"default":false,"description":"Boolean indicating whether to solve with `matrix` or its (block-wise)\n adjoint.\n\n@compatibility(numpy)\nEquivalent to scipy.linalg.solve_triangular\n@end_compatibility","name":"adjoint","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"\n`matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form\nsquare matrices. If `lower` is `True` then the strictly upper triangular part\nof each inner-most matrix is assumed to be zero and not accessed.\nIf `lower` is False then the strictly lower triangular part of each inner-most\nmatrix is assumed to be zero and not accessed.\n`rhs` is a tensor of shape `[..., M, N]`.\n\nThe output is a tensor of shape `[..., M, N]`. If `adjoint` is\n`True` then the innermost matrices in `output` satisfy matrix equations\n`matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`.\nIf `adjoint` is `False` then the strictly then the innermost matrices in\n`output` satisfy matrix equations\n`adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`.\n\nNote, the batch shapes for the inputs only need to broadcast.\n\nExample:\n```python\n\na = tf.constant([[3, 0, 0, 0],\n [2, 1, 0, 0],\n [1, 0, 1, 0],\n [1, 1, 1, 1]], dtype=tf.float32)\n\nb = tf.constant([[4],\n [2],\n [4],\n [2]], dtype=tf.float32)\n\nx = tf.linalg.triangular_solve(a, b, lower=True)\nx\n# \n\n# in python3 one can use `a@x`\ntf.matmul(a, x)\n# \n```","inputs":[{"description":"Shape is `[..., M, M]`.","name":"matrix","typeAttr":"T"},{"description":"Shape is `[..., M, K]`.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M, K]`.","name":"output","typeAttr":"T"}],"summary":"Solves systems of linear equations with upper or lower triangular matrices by backsubstitution."}},{"name":"Max","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum of elements across dimensions of a tensor."}},{"name":"MaxIntraOpParallelismDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the maximum intra-op parallelism to use.","name":"max_intra_op_parallelism","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that overrides the maximum intra-op parallelism."}},{"name":"MaxPool","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"category":"Pool","inputs":[{"description":"4-D input to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs max pooling on the input."}},{"name":"MaxPool3D","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"}],"inputs":[{"description":"Shape `[batch, depth, rows, cols, channels]` tensor to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs 3D max pooling on the input."}},{"name":"MaxPool3DGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`.","name":"TInput","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"TInput"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"TInput"},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients of 3D max pooling function."}},{"name":"MaxPool3DGradGrad","schema":{"attributes":[{"description":"1-D tensor of length 5. The size of the window for each dimension of\nthe input tensor. Must have `ksize[0] = ksize[4] = 1`.","minimum":5,"name":"ksize","type":"int64[]"},{"description":"1-D tensor of length 5. The stride of the sliding window for each\ndimension of `input`. Must have `strides[0] = strides[4] = 1`.","minimum":5,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NDHWC","description":"The data format of the input and output data. With the\ndefault format \"NDHWC\", the data is stored in the order of:\n [batch, in_depth, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCDHW\", the data storage order is:\n [batch, in_channels, in_depth, in_height, in_width]. Must be one of the following: `NDHWC`, `NCDHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"Output backprop of shape `[batch, depth, rows, cols, channels]`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGrad","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients w.r.t. the output of `max_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolGradGrad","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients of gradients w.r.t. the input of `max_pool`.","name":"grad","typeAttr":"T"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradGradV2","schema":{"attributes":[{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients of gradients w.r.t. the input of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"Gradients of gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradGradWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input.","name":"input","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the\ninput of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The indices of the maximum values chosen for each output of `max_pool`.","name":"argmax","typeAttr":"Targmax"}],"outputs":[{"description":"Gradients of gradients w.r.t. the input of `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes second-order gradients of the maxpooling function."}},{"name":"MaxPoolGradV2","schema":{"attributes":[{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`.","name":"data_format","type":"string"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"orig_input","typeAttr":"T"},{"description":"The original output tensor.","name":"orig_output","typeAttr":"T"},{"description":"4-D. Gradients w.r.t. the output of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"Gradients w.r.t. the input to `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolGradWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The original input.","name":"input","typeAttr":"T"},{"description":"4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the\noutput of `max_pool`.","name":"grad","typeAttr":"T"},{"description":"The indices of the maximum values chosen for each output of `max_pool`.","name":"argmax","typeAttr":"Targmax"}],"outputs":[{"description":"Gradients w.r.t. the input of `max_pool`.","name":"output","typeAttr":"T"}],"summary":"Computes gradients of the maxpooling function."}},{"name":"MaxPoolV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`.","name":"T","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":"NHWC","description":"Specify the data format of the input and output data. With the\ndefault format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\nAlternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width]. Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"category":"Pool","inputs":[{"description":"4-D input to pool over.","name":"input","typeAttr":"T"},{"description":"The size of the window for each dimension of the input tensor.","name":"ksize","type":3},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","name":"strides","type":3}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"}],"summary":"Performs max pooling on the input."}},{"name":"MaxPoolWithArgmax","schema":{"attributes":[{"description":"The size of the window for each dimension of the input tensor.","minimum":4,"name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the\ninput tensor.","minimum":4,"name":"strides","type":"int64[]"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Targmax","type":"type"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":false,"description":"Whether to include batch dimension in flattened index of `argmax`.","name":"include_batch_in_index","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The indices in `argmax` are flattened, so that a maximum value at position\n`[b, y, x, c]` becomes flattened index:\n`(y * width + x) * channels + c` if `include_batch_in_index` is False;\n`((b * height + y) * width + x) * channels + c` if `include_batch_in_index` is True.\n\nThe indices returned are always in `[0, height) x [0, width)` before flattening,\neven if padding is involved and the mathematically correct answer is outside\n(either negative or too large). This is a bug, but fixing it is difficult to do\nin a safe backwards compatible way, especially due to flattening.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`. Input to pool over.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The max pooled output tensor.","name":"output","typeAttr":"T"},{"description":"4-D. The flattened indices of the max values chosen for each output.","name":"argmax","typeAttr":"Targmax"}],"summary":"Performs max pooling on the input and outputs both max values and indices."}},{"name":"Maximum","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"*NOTE*: `Maximum` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns the max of x and y (i.e. x > y ? x : y) element-wise."}},{"name":"Mean","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the mean of elements across dimensions of a tensor."}},{"name":"Merge","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"description":"`Merge` waits for at least one of the tensors in `inputs` to become available.\nIt is usually combined with `Switch` to implement branching.\n\n`Merge` forwards the first tensor to become available to `output`, and sets\n`value_index` to its index in `inputs`.","inputs":[{"description":"The input tensors, exactly one of which will become available.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Will be set to the available input tensor.","name":"output","typeAttr":"T"},{"description":"The index of the chosen input tensor in `inputs`.","name":"value_index","type":3}],"summary":"Forwards the value of an available tensor from `inputs` to `output`."}},{"name":"MergeSummary","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"}],"description":"This op creates a\n[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)\nprotocol buffer that contains the union of all the values in the input\nsummaries.\n\nWhen the Op is run, it reports an `InvalidArgument` error if multiple values\nin the summaries to merge use the same tag.","inputs":[{"description":"Can be of any shape. Each must contain serialized `Summary` protocol\nbuffers.","name":"inputs","numberAttr":"N","type":7}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Merges summaries."}},{"name":"MergeV2Checkpoints","schema":{"attributes":[{"default":true,"description":"see above.","name":"delete_old_dirs","type":"boolean"}],"description":"result is one logical checkpoint, with one physical metadata file and renamed\ndata files.\n\nIntended for \"grouping\" multiple checkpoints in a sharded checkpoint setup.\n\nIf delete_old_dirs is true, attempts to delete recursively the dirname of each\npath in the input checkpoint_prefixes. This is useful when those paths are non\nuser-facing temporary locations.","inputs":[{"description":"prefixes of V2 checkpoints to merge.","name":"checkpoint_prefixes","type":7},{"description":"scalar. The desired final prefix. Allowed to be the same\nas one of the checkpoint_prefixes.","name":"destination_prefix","type":7}],"summary":"V2 format specific: merges the metadata files of sharded checkpoints. The"}},{"name":"Mfcc","schema":{"attributes":[{"default":4000,"description":"The highest frequency to use when calculating the\nceptstrum.","name":"upper_frequency_limit","type":"float32"},{"default":20,"description":"The lowest frequency to use when calculating the\nceptstrum.","name":"lower_frequency_limit","type":"float32"},{"default":40,"description":"Resolution of the Mel bank used internally.","name":"filterbank_channel_count","type":"int64"},{"default":13,"description":"How many output channels to produce per time slice.","name":"dct_coefficient_count","type":"int64"}],"description":"Mel Frequency Cepstral Coefficients are a way of representing audio data that's\nbeen effective as an input feature for machine learning. They are created by\ntaking the spectrum of a spectrogram (a 'cepstrum'), and discarding some of the\nhigher frequencies that are less significant to the human ear. They have a long\nhistory in the speech recognition world, and https://en.wikipedia.org/wiki/Mel-frequency_cepstrum\nis a good resource to learn more.","inputs":[{"description":"Typically produced by the Spectrogram op, with magnitude_squared\nset to true.","name":"spectrogram","type":1},{"description":"How many samples per second the source audio used.","name":"sample_rate","type":3}],"outputs":[{"name":"output","type":1}],"summary":"Transforms a spectrogram into a form that's useful for speech recognition."}},{"name":"Min","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum of elements across dimensions of a tensor."}},{"name":"Minimum","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int16`, `int32`, `int64`.","name":"T","type":"type"}],"description":"*NOTE*: `Minimum` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns the min of x and y (i.e. x < y ? x : y) element-wise."}},{"name":"MirrorPad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"description":"Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions\ndo not include the borders, while in symmetric mode the padded regions\ndo include the borders. For example, if `input` is `[1, 2, 3]` and `paddings`\nis `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and\nit is `[1, 2, 3, 3, 2]` in symmetric mode. Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"}],"description":"This operation pads a `input` with mirrored values according to the `paddings`\nyou specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is\nthe rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many values to add before the contents of `input` in that dimension, and\n`paddings[D, 1]` indicates how many values to add after the contents of `input`\nin that dimension. Both `paddings[D, 0]` and `paddings[D, 1]` must be no greater\nthan `input.dim_size(D)` (or `input.dim_size(D) - 1`) if `copy_border` is true\n(if false, respectively).\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 2, 3], [4, 5, 6]].\n# 'paddings' is [[1, 1]], [2, 2]].\n# 'mode' is SYMMETRIC.\n# rank of 't' is 2.\npad(t, paddings) ==> [[2, 1, 1, 2, 3, 3, 2]\n [2, 1, 1, 2, 3, 3, 2]\n [5, 4, 4, 5, 6, 6, 5]\n [5, 4, 4, 5, 6, 6, 5]]\n```","inputs":[{"description":"The input tensor to be padded.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"description":"The padded tensor.","name":"output","typeAttr":"T"}],"summary":"Pads a tensor with mirrored values."}},{"name":"MirrorPadGrad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"description":"The mode used in the `MirrorPad` op. Must be one of the following: `REFLECT`, `SYMMETRIC`.","name":"mode","type":"string"}],"description":"This operation folds the padded areas of `input` by `MirrorPad` according to the\n`paddings` you specify. `paddings` must be the same as `paddings` argument\ngiven to the corresponding `MirrorPad` op.\n\nThe folded size of each dimension D of the output is:\n\n`input.dim_size(D) - paddings(D, 0) - paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 2, 3], [4, 5, 6], [7, 8, 9]].\n# 'paddings' is [[0, 1]], [0, 1]].\n# 'mode' is SYMMETRIC.\n# rank of 't' is 2.\npad(t, paddings) ==> [[ 1, 5]\n [11, 28]]\n```","inputs":[{"description":"The input tensor to be folded.","name":"input","typeAttr":"T"},{"description":"A two-column matrix specifying the padding sizes. The number of\nrows must be the same as the rank of `input`.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"description":"The folded tensor.","name":"output","typeAttr":"T"}],"summary":"Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor."}},{"name":"MlirPassthroughOp","schema":{"attributes":[{"name":"mlir_module","type":"string"},{"minimum":0,"name":"Tinputs","type":"type[]"},{"minimum":0,"name":"Toutputs","type":"type[]"}],"description":"This operation does not have an associated kernel and is not intended to be\nexecuted in a regular TensorFlow session. Instead it is intended to be used for\ntesting or for special case where a user intends to pass custom MLIR computation\nthrough a TensorFlow graph with the intent of having custom tooling processing\nit downstream (when targeting a different environment, like TensorFlow lite for\nexample).\nThe MLIR module is expected to have a main() function that will be used as an\nentry point. The inputs to the operations will be passed as argument to the\nmain() function and the returned values of the main function mapped to the\noutputs.\nExample usage:\n\n```\nimport tensorflow as tf\nfrom tensorflow.compiler.mlir.tensorflow.gen_mlir_passthrough_op import mlir_passthrough_op\n\nmlir_module = '''python\nfunc @main(%arg0 : tensor<10xf32>, %arg1 : tensor<10xf32>) -> tensor<10x10xf32> {\n %add = \"magic.op\"(%arg0, %arg1) : (tensor<10xf32>, tensor<10xf32>) -> tensor<10x10xf32>\n return %ret : tensor<10x10xf32>\n}\n'''\n\n@tf.function\ndef foo(x, y):\n return mlir_passthrough_op([x, y], mlir_module, Toutputs=[tf.float32])\n\ngraph_def = foo.get_concrete_function(tf.TensorSpec([10], tf.float32), tf.TensorSpec([10], tf.float32)).graph.as_graph_def()\n```","inputs":[{"name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"name":"outputs","typeListAttr":"Toutputs"}],"summary":"Wraps an arbitrary MLIR computation expressed as a module with a main() function."}},{"name":"Mod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `float16`, `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"the result here is consistent with a truncating divide. E.g.\n`tf.truncatediv(x, y) * y + truncate_mod(x, y) = x`.\n\n*NOTE*: `Mod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. This emulates C semantics in that"}},{"name":"ModelDataset","schema":{"attributes":[{"default":0,"name":"algorithm","type":"int64"},{"default":0,"name":"cpu_budget","type":"int64"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Identity transformation that models performance.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Identity transformation that models performance."}},{"name":"Mul","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `Mul` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x * y element-wise."}},{"name":"MulNoNan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `MulNoNan` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x * y element-wise. Returns zero if y is zero, even if x if infinite or NaN."}},{"name":"MultiDeviceIterator","schema":{"attributes":[{"description":"A list of devices the iterator works across.","minimum":1,"name":"devices","type":"string[]"},{"description":"If non-empty, this resource will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"},{"description":"If non-empty, this resource is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"}],"outputs":[{"description":"Handle to the resource created.","name":"handle","type":20}],"summary":"Creates a MultiDeviceIterator resource."}},{"name":"MultiDeviceIteratorFromStringHandle","schema":{"attributes":[{"default":[],"description":"The type list for the return values.","minimum":0,"name":"output_types","type":"type[]"},{"default":[],"description":"The list of shapes being produced.","minimum":0,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"String representing the resource.","name":"string_handle","type":7}],"outputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20}],"summary":"Generates a MultiDeviceIterator resource from its provided string handle."}},{"name":"MultiDeviceIteratorGetNextFromShard","schema":{"attributes":[{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20},{"description":"Integer representing which shard to fetch data for.","name":"shard_num","type":3},{"description":"Which incarnation of the MultiDeviceIterator is running.","name":"incarnation_id","type":9}],"outputs":[{"description":"Result of the get_next on the dataset.","name":"components","typeListAttr":"output_types"}],"summary":"Gets next element for the provided shard number."}},{"name":"MultiDeviceIteratorInit","schema":{"inputs":[{"description":"Dataset to be iterated upon.","name":"dataset","type":21},{"description":"A MultiDeviceIteratorResource.","name":"multi_device_iterator","type":20},{"description":"The maximum size of the host side per device buffer to keep.","name":"max_buffer_size","type":9}],"outputs":[{"description":"An int64 indicating which incarnation of the MultiDeviceIterator\nis running.","name":"incarnation_id","type":9}],"summary":"Initializes the multi device iterator with the given dataset."}},{"name":"MultiDeviceIteratorToStringHandle","schema":{"inputs":[{"description":"A MultiDeviceIterator resource.","name":"multi_device_iterator","type":20}],"outputs":[{"description":"A string representing the resource.","name":"string_handle","type":7}],"summary":"Produces a string handle for the given MultiDeviceIterator."}},{"name":"Multinomial","schema":{"attributes":[{"default":0,"description":"If either seed or seed2 is set to be non-zero, the internal random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_dtype","type":"type"}],"inputs":[{"description":"2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]`\nrepresents the unnormalized log probabilities for all classes.","name":"logits","typeAttr":"T"},{"description":"0-D. Number of independent samples to draw for each row slice.","name":"num_samples","type":3}],"outputs":[{"description":"2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]`\ncontains the drawn class labels with range `[0, num_classes)`.","name":"output","typeAttr":"output_dtype"}],"summary":"Draws samples from a multinomial distribution."}},{"name":"MutableDenseHashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of each value.","name":"value_shape","type":"shape"},{"default":131072,"description":"The initial number of hash table buckets. Must be a power\nto 2.","name":"initial_num_buckets","type":"int64"},{"default":0.800000011920929,"description":"The maximum ratio between number of entries and number of\nbuckets before growing the table. Must be between 0 and 1.","name":"max_load_factor","type":"float32"}],"description":"It uses \"open addressing\" with quadratic reprobing to resolve\ncollisions.\n\nThis op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","inputs":[{"description":"The key used to represent empty key buckets internally. Must not\nbe used in insert or lookup operations.","name":"empty_key","typeAttr":"key_dtype"}],"outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table that uses tensors as the backing store."}},{"name":"MutableDenseHashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of each value.","name":"value_shape","type":"shape"},{"default":131072,"description":"The initial number of hash table buckets. Must be a power\nto 2.","name":"initial_num_buckets","type":"int64"},{"default":0.800000011920929,"description":"The maximum ratio between number of entries and number of\nbuckets before growing the table. Must be between 0 and 1.","name":"max_load_factor","type":"float32"}],"description":"It uses \"open addressing\" with quadratic reprobing to resolve\ncollisions.\n\nThis op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","inputs":[{"description":"The key used to represent empty key buckets internally. Must not\nbe used in insert or lookup operations.","name":"empty_key","typeAttr":"key_dtype"},{"name":"deleted_key","typeAttr":"key_dtype"}],"outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table that uses tensors as the backing store."}},{"name":"MutableHashTable","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableOfTensors","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"value_shape","type":"shape"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a vector. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","isRef":true,"name":"table_handle","type":7}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableOfTensorsV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"value_shape","type":"shape"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a vector. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table."}},{"name":"MutableHashTableV2","schema":{"attributes":[{"default":"","description":"If non-empty, this table is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this table is shared under the given name across\nmultiple sessions.","name":"shared_name","type":"string"},{"default":false,"description":"If true and shared_name is empty, the table is shared\nusing the node name.","name":"use_node_name_sharing","type":"boolean"},{"description":"Type of the table keys.","name":"key_dtype","type":"type"},{"description":"Type of the table values.","name":"value_dtype","type":"type"}],"description":"This op creates a mutable hash table, specifying the type of its keys and\nvalues. Each value must be a scalar. Data can be inserted into the table using\nthe insert operations. It does not support the initialization operation.","outputs":[{"description":"Handle to a table.","name":"table_handle","type":20}],"summary":"Creates an empty hash table."}},{"name":"MutexLock","schema":{"description":"is alive, any other request to use `MutexLock` with this mutex will wait.\n\nThis is particularly useful for creating a critical section when used in\nconjunction with `MutexLockIdentity`:\n\n```python\n\nmutex = mutex_v2(\n shared_name=handle_name, container=container, name=name)\n\ndef execute_in_critical_section(fn, *args, **kwargs):\n lock = gen_resource_variable_ops.mutex_lock(mutex)\n\n with ops.control_dependencies([lock]):\n r = fn(*args, **kwargs)\n\n with ops.control_dependencies(nest.flatten(r)):\n with ops.colocate_with(mutex):\n ensure_lock_exists = mutex_lock_identity(lock)\n\n # Make sure that if any element of r is accessed, all of\n # them are executed together.\n r = nest.map_structure(tf.identity, r)\n\n with ops.control_dependencies([ensure_lock_exists]):\n return nest.map_structure(tf.identity, r)\n```\n\nWhile `fn` is running in the critical section, no other functions which wish to\nuse this critical section may run.\n\nOften the use case is that two executions of the same graph, in parallel,\nwish to run `fn`; and we wish to ensure that only one of them executes\nat a time. This is especially important if `fn` modifies one or more\nvariables at a time.\n\nIt is also useful if two separate functions must share a resource, but we\nwish to ensure the usage is exclusive.","inputs":[{"description":"The mutex resource to lock.","name":"mutex","type":20}],"outputs":[{"description":"A tensor that keeps a shared pointer to a lock on the mutex;\nwhen the Tensor is destroyed, the use count on the shared pointer is decreased\nby 1. When it reaches 0, the lock is released.","name":"mutex_lock","type":21}],"summary":"Locks a mutex resource. The output is the lock. So long as the lock tensor"}},{"name":"MutexV2","schema":{"attributes":[{"default":"","description":"If non-empty, this variable is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this variable is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The mutex resource.","name":"resource","type":20}],"summary":"Creates a Mutex resource that can be locked by `MutexLock`."}},{"name":"NcclAllReduce","schema":{"attributes":[{"description":"Must be one of the following: `min`, `max`, `prod`, `sum`.","name":"reduction","type":"string"},{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"num_devices","type":"int64"},{"name":"shared_name","type":"string"}],"description":"Outputs a tensor containing the reduction across all input tensors passed to ops\nwithin the same `shared_name.\n\nThe graph should be constructed so if one op runs with shared_name value `c`,\nthen `num_devices` ops will run with shared_name value `c`. Failure to do so\nwill cause the graph execution to fail to complete.\n\ninput: the input to the reduction\ndata: the value of the reduction across all `num_devices` devices.\nreduction: the reduction operation to perform.\nnum_devices: The number of devices participating in this reduction.\nshared_name: Identifier that shared between ops of the same reduction.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Outputs a tensor containing the reduction across all input tensors."}},{"name":"NcclBroadcast","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"name":"shape","type":"shape"}],"description":"Sends `input` to all devices that are connected to the output.\n\nThe graph should be constructed so that all ops connected to the output have a\nvalid device assignment, and the op itself is assigned one of these devices.\n\ninput: The input to the broadcast.\noutput: The same as input.\nshape: The shape of the input tensor.\n","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Sends `input` to all devices that are connected to the output."}},{"name":"NcclReduce","schema":{"attributes":[{"description":"Must be one of the following: `min`, `max`, `prod`, `sum`.","name":"reduction","type":"string"},{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"minimum":1,"name":"num_devices","type":"int64"}],"description":"Reduces `input` from `num_devices` using `reduction` to a single device.\n\nThe graph should be constructed so that all inputs have a valid device\nassignment, and the op itself is assigned one of these devices.\n\ninput: The input to the reduction.\ndata: the value of the reduction across all `num_devices` devices.\nreduction: the reduction operation to perform.","inputs":[{"name":"input","numberAttr":"num_devices","typeAttr":"T"}],"outputs":[{"name":"data","typeAttr":"T"}],"summary":"Reduces `input` from `num_devices` using `reduction` to a single device."}},{"name":"Ndtri","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"NearestNeighbors","schema":{"description":"Rows of points are assumed to be input points. Rows of centers are assumed to be\nthe list of candidate centers. For each point, the k centers that have least L2\ndistance to it are computed.","inputs":[{"description":"Matrix of shape (n, d). Rows are assumed to be input points.","name":"points","type":1},{"description":"Matrix of shape (m, d). Rows are assumed to be centers.","name":"centers","type":1},{"description":"Number of nearest centers to return for each point. If k is larger than m, then\nonly m centers are returned.","name":"k","type":9}],"outputs":[{"description":"Matrix of shape (n, min(m, k)). Each row contains the indices of the centers\nclosest to the corresponding point, ordered by increasing distance.","name":"nearest_center_indices","type":9},{"description":"Matrix of shape (n, min(m, k)). Each row contains the squared L2 distance to the\ncorresponding center in nearest_center_indices.","name":"nearest_center_distances","type":1}],"summary":"Selects the k nearest centers for each point."}},{"name":"Neg","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = -x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes numerical negative value element-wise."}},{"name":"NegTrain","schema":{"attributes":[{"description":"Count of words in the vocabulary.","name":"vocab_count","type":"int64[]"},{"description":"Number of negative samples per example.","name":"num_negative_samples","type":"int64"}],"inputs":[{"description":"input word embedding.","isRef":true,"name":"w_in","type":1},{"description":"output word embedding.","isRef":true,"name":"w_out","type":1},{"description":"A vector of word ids.","name":"examples","type":3},{"description":"A vector of word ids.","name":"labels","type":3},{"name":"lr","type":1}],"summary":"Training via negative sampling."}},{"name":"NextAfter","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float64`, `float32`.","name":"T","type":"type"}],"description":"This operation returns the same result as the C++ std::nextafter function.\n\nIt can also return a subnormal number.\n\n@compatibility(cpp)\nEquivalent to C++ std::nextafter function.\n@end_compatibility","inputs":[{"name":"x1","typeAttr":"T"},{"name":"x2","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the next representable value of `x1` in the direction of `x2`, element-wise."}},{"name":"NextIteration","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be made available to the next iteration.","name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","name":"output","typeAttr":"T"}],"summary":"Makes its input available to the next iteration."}},{"name":"NoOp","schema":{"summary":"Does nothing. Only useful as a placeholder for control edges."}},{"name":"NonDeterministicInts","schema":{"attributes":[{"default":{"type":"type","value":9},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Non-deterministic integer values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Non-deterministically generates some integers."}},{"name":"NonMaxSuppression","schema":{"attributes":[{"default":0.5,"description":"A float representing the threshold for deciding whether boxes\noverlap too much with respect to IOU.","name":"iou_threshold","type":"float32"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Note that this\nalgorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression(\n boxes, scores, max_output_size, iou_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","type":1},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system. Note that this\nalgorithm is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\n\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV3","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV4","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T_threshold","type":"type"},{"default":false,"description":"If true, the output `selected_indices` is padded to be of length\n`max_output_size`. Defaults to false.","name":"pad_to_max_output_size","type":"boolean"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T_threshold"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T_threshold"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3},{"description":"A 0-D integer tensor representing the number of valid elements in\n`selected_indices`, with the valid elements appearing first.","name":"valid_outputs","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionV5","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `float32`.","name":"T","type":"type"},{"default":false,"description":"If true, the output `selected_indices` is padded to be of length\n`max_output_size`. Defaults to false.","name":"pad_to_max_output_size","type":"boolean"}],"description":"pruning away boxes that have high intersection-over-union (IOU) overlap\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. Bounding boxes are supplied as\n[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any\ndiagonal pair of box corners and the coordinates can be provided as normalized\n(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm\nis agnostic to where the origin is in the coordinate system and more\ngenerally is invariant to orthogonal transformations and translations\nof the coordinate system; thus translating or reflections of the coordinate\nsystem result in the same boxes being selected by the algorithm.\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n selected_indices = tf.image.non_max_suppression_v2(\n boxes, scores, max_output_size, iou_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)\nThis op also supports a Soft-NMS (with Gaussian weighting) mode (c.f.\nBodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\nof other overlapping boxes instead of directly causing them to be pruned.\nTo enable this Soft-NMS mode, set the `soft_nms_sigma` parameter to be\nlarger than 0.","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, 4]`.","name":"boxes","typeAttr":"T"},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","typeAttr":"T"},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too much with respect to IOU.","name":"iou_threshold","typeAttr":"T"},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","typeAttr":"T"},{"description":"A 0-D float tensor representing the sigma parameter for Soft NMS; see Bodla et\nal (c.f. https://arxiv.org/abs/1704.04503). When `soft_nms_sigma=0.0` (which\nis default), we fall back to standard (hard) NMS.","name":"soft_nms_sigma","typeAttr":"T"}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3},{"description":"A 1-D float tensor of shape `[M]` representing the corresponding\nscores for each selected box, where `M <= max_output_size`. Scores only differ\nfrom corresponding input scores when using Soft NMS (i.e. when\n`soft_nms_sigma>0`)","name":"selected_scores","typeAttr":"T"},{"description":"A 0-D integer tensor representing the number of valid elements in\n`selected_indices`, with the valid elements appearing first.","name":"valid_outputs","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonMaxSuppressionWithOverlaps","schema":{"description":"pruning away boxes that have high overlaps\nwith previously selected boxes. Bounding boxes with score less than\n`score_threshold` are removed. N-by-n overlap values are supplied as square matrix,\nwhich allows for defining a custom overlap criterium (eg. intersection over union,\nintersection over area, etc.).\n\nThe output of this operation is a set of integers indexing into the input\ncollection of bounding boxes representing the selected boxes. The bounding\nbox coordinates corresponding to the selected indices can then be obtained\nusing the `tf.gather operation`. For example:\n\n selected_indices = tf.image.non_max_suppression_with_overlaps(\n overlaps, scores, max_output_size, overlap_threshold, score_threshold)\n selected_boxes = tf.gather(boxes, selected_indices)","inputs":[{"description":"A 2-D float tensor of shape `[num_boxes, num_boxes]` representing\nthe n-by-n box overlap values.","name":"overlaps","type":1},{"description":"A 1-D float tensor of shape `[num_boxes]` representing a single\nscore corresponding to each box (each row of boxes).","name":"scores","type":1},{"description":"A scalar integer tensor representing the maximum number of\nboxes to be selected by non max suppression.","name":"max_output_size","type":3},{"description":"A 0-D float tensor representing the threshold for deciding whether\nboxes overlap too.","name":"overlap_threshold","type":1},{"description":"A 0-D float tensor representing the threshold for deciding when to remove\nboxes based on score.","name":"score_threshold","type":1}],"outputs":[{"description":"A 1-D integer tensor of shape `[M]` representing the selected\nindices from the boxes tensor, where `M <= max_output_size`.","name":"selected_indices","type":3}],"summary":"Greedily selects a subset of bounding boxes in descending order of score,"}},{"name":"NonSerializableDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}]}},{"name":"NotEqual","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `uint16`, `uint32`, `uint64`, `complex64`, `quint8`, `qint8`, `qint32`, `string`, `bool`, `complex128`.","name":"T","type":"type"},{"default":true,"name":"incompatible_shape_error","type":"boolean"}],"description":"*NOTE*: `NotEqual` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","type":10}],"summary":"Returns the truth value of (x != y) element-wise."}},{"name":"NthElement","schema":{"attributes":[{"default":false,"description":"When set to True, find the nth-largest value in the vector and vice\nversa.","name":"reverse","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the entries which is the nth-smallest\nvalue in the vector and outputs their values as scalar tensor.\n\nFor matrices (resp. higher rank input), computes the entries which is the\nnth-smallest value in each row (resp. vector along the last dimension). Thus,\n\n values.shape = input.shape[:-1]","inputs":[{"description":"1-D or higher with last dimension at least `n+1`.","name":"input","typeAttr":"T"},{"description":"0-D. Position of sorted vector to select along the last dimension (along\neach row for matrices). Valid range of n is `[0, input.shape[:-1])`","name":"n","type":3}],"outputs":[{"description":"The `n`-th order statistic along each last dimensional slice.","name":"values","typeAttr":"T"}],"summary":"Finds values of the `n`-th order statistic for the last dimension."}},{"name":"OneHot","schema":{"attributes":[{"default":-1,"description":"The axis to fill (default: -1, a new inner-most axis).","name":"axis","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `uint8`, `int32`, `int64`.","name":"TI","type":"type"}],"description":"The locations represented by indices in `indices` take value `on_value`,\nwhile all other locations take value `off_value`.\n\nIf the input `indices` is rank `N`, the output will have rank `N+1`,\nThe new axis is created at dimension `axis` (default: the new axis is\nappended at the end).\n\nIf `indices` is a scalar the output shape will be a vector of length `depth`.\n\nIf `indices` is a vector of length `features`, the output shape will be:\n```\n features x depth if axis == -1\n depth x features if axis == 0\n```\n\nIf `indices` is a matrix (batch) with shape `[batch, features]`,\nthe output shape will be:\n```\n batch x features x depth if axis == -1\n batch x depth x features if axis == 1\n depth x batch x features if axis == 0\n```\n\n\nExamples\n=========\n\nSuppose that\n```\n indices = [0, 2, -1, 1]\n depth = 3\n on_value = 5.0\n off_value = 0.0\n axis = -1\n```\n\nThen output is `[4 x 3]`:\n```\noutput =\n [5.0 0.0 0.0] // one_hot(0)\n [0.0 0.0 5.0] // one_hot(2)\n [0.0 0.0 0.0] // one_hot(-1)\n [0.0 5.0 0.0] // one_hot(1)\n```\n\nSuppose that\n```\n indices = [0, 2, -1, 1]\n depth = 3\n on_value = 0.0\n off_value = 3.0\n axis = 0\n```\n\nThen output is `[3 x 4]`:\n```\noutput =\n [0.0 3.0 3.0 3.0]\n [3.0 3.0 3.0 0.0]\n [3.0 3.0 3.0 3.0]\n [3.0 0.0 3.0 3.0]\n// ^ one_hot(0)\n// ^ one_hot(2)\n// ^ one_hot(-1)\n// ^ one_hot(1)\n```\n\nSuppose that\n```\n indices = [[0, 2], [1, -1]]\n depth = 3\n on_value = 1.0\n off_value = 0.0\n axis = -1\n```\n\nThen output is `[2 x 2 x 3]`:\n```\noutput =\n [\n [1.0, 0.0, 0.0] // one_hot(0)\n [0.0, 0.0, 1.0] // one_hot(2)\n ][\n [0.0, 1.0, 0.0] // one_hot(1)\n [0.0, 0.0, 0.0] // one_hot(-1)\n ]\n```","inputs":[{"description":"A tensor of indices.","name":"indices","typeAttr":"TI"},{"description":"A scalar defining the depth of the one hot dimension.","name":"depth","type":3},{"description":"A scalar defining the value to fill in output when `indices[j] = i`.","name":"on_value","typeAttr":"T"},{"description":"A scalar defining the value to fill in output when `indices[j] != i`.","name":"off_value","typeAttr":"T"}],"outputs":[{"description":"The one-hot tensor.","name":"output","typeAttr":"T"}],"summary":"Returns a one-hot tensor."}},{"name":"OneShotIterator","schema":{"attributes":[{"description":"A function of type `() -> DT_VARIANT`, where the returned\nDT_VARIANT is a dataset.","name":"dataset_factory","type":"function"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"A one-shot iterator bundles the logic for defining the dataset and\nthe state of the iterator in a single op, which allows simple input\npipelines to be defined without an additional initialization\n(\"MakeIterator\") step.\n\nOne-shot iterators have the following limitations:\n\n* They do not support parameterization: all logic for creating the underlying\n dataset must be bundled in the `dataset_factory` function.\n* They are not resettable. Once a one-shot iterator reaches the end of its\n underlying dataset, subsequent \"IteratorGetNext\" operations on that\n iterator will always produce an `OutOfRange` error.\n\nFor greater flexibility, use \"Iterator\" and \"MakeIterator\" to define\nan iterator using an arbitrary subgraph, which may capture tensors\n(including fed values) as parameters, and which may be reset multiple\ntimes by rerunning \"MakeIterator\".","outputs":[{"description":"A handle to the iterator that can be passed to an \"IteratorGetNext\"\nop.","name":"handle","type":20}],"summary":"Makes a \"one-shot\" iterator that can be iterated only once."}},{"name":"OnesLike","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`, `complex128`, `bool`.","name":"T","type":"type"}],"inputs":[{"description":"a tensor of type T.","name":"x","typeAttr":"T"}],"outputs":[{"description":"a tensor of the same shape and type as x but filled with ones.","name":"y","typeAttr":"T"}],"summary":"Returns a tensor of ones with the same shape and type as x."}},{"name":"OptimizeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":[],"name":"optimization_configs","type":"string[]"}],"description":"Creates a dataset by applying optimizations to `input_dataset`.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A `tf.string` vector `tf.Tensor` identifying optimizations to use.","name":"optimizations","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset by applying optimizations to `input_dataset`."}},{"name":"OptionalFromValue","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"optional","type":21}],"summary":"Constructs an Optional variant from a tuple of tensors."}},{"name":"OptionalGetValue","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"optional","type":21}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Returns the value stored in an Optional variant or raises an error if none exists."}},{"name":"OptionalHasValue","schema":{"inputs":[{"name":"optional","type":21}],"outputs":[{"name":"has_value","type":10}],"summary":"Returns true if and only if the given Optional variant has a value."}},{"name":"OptionalNone","schema":{"outputs":[{"name":"optional","type":21}],"summary":"Creates an Optional variant with no value."}},{"name":"OrderedMapClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"OrderedMapIncompleteSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of incomplete elements in the underlying container."}},{"name":"OrderedMapPeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain this key\nthis op will block until it does. This Op is optimized for\nperformance.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified key. If the"}},{"name":"OrderedMapSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"OrderedMapStage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"minimum":1,"name":"fake_dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"description":"associative container. Elements are ordered by key.","inputs":[{"description":"int64","name":"key","type":9},{"name":"indices","type":3},{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"fake_dtypes"}],"summary":"Stage (key, values) in the underlying container which behaves like a ordered"}},{"name":"OrderedMapUnstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"from the underlying container. If the underlying container\ndoes not contain this key, the op will block until it does.","inputs":[{"name":"key","type":9},{"name":"indices","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the values associated with the key"}},{"name":"OrderedMapUnstageNoKey","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"key from the underlying container. If the underlying container\ndoes not contain elements, the op will block until it does.","inputs":[{"name":"indices","type":3}],"outputs":[{"name":"key","type":9},{"name":"values","typeListAttr":"dtypes"}],"summary":"Op removes and returns the (key, value) element with the smallest"}},{"name":"OutfeedDequeue","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"description":"This operation will block indefinitely until data is available.","outputs":[{"description":"A tensor that will be read from the device outfeed.","name":"output","typeAttr":"dtype"}],"summary":"Retrieves a single tensor from the computation outfeed."}},{"name":"OutfeedDequeueTuple","schema":{"attributes":[{"description":"The element types of each element in `outputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `outputs`.","name":"shapes","type":"shape[]"},{"default":-1,"description":"The TPU device to use. This should be -1 when the Op\nis running on a TPU device, and >= 0 when the Op is running on the CPU\ndevice.","name":"device_ordinal","type":"int64"}],"description":"This operation will block indefinitely until data is available. Output `i`\ncorresponds to XLA tuple element `i`.","outputs":[{"description":"A list of tensors that will be read from the outfeed.","name":"outputs","typeListAttr":"dtypes"}],"summary":"Retrieve multiple values from the computation outfeed."}},{"name":"OutfeedEnqueue","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"description":"A tensor that will be inserted into the outfeed queue.","name":"input","typeAttr":"dtype"}],"summary":"Enqueue a Tensor on the computation outfeed."}},{"name":"OutfeedEnqueueTuple","schema":{"attributes":[{"minimum":1,"name":"dtypes","type":"type[]"}],"inputs":[{"description":"A list of tensors that will be inserted into the outfeed queue as an\nXLA tuple.","name":"inputs","typeListAttr":"dtypes"}],"summary":"Enqueue multiple Tensor values on the computation outfeed."}},{"name":"Pack","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"Dimension along which to pack. Negative values wrap around, so the\nvalid range is `[-(R+1), R+1)`.","name":"axis","type":"int64"}],"description":"Packs the `N` tensors in `values` into a tensor with rank one higher than each\ntensor in `values`, by packing them along the `axis` dimension.\nGiven a list of tensors of shape `(A, B, C)`;\n\nif `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`.\nif `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`.\nEtc.\n\nFor example:\n\n```\n# 'x' is [1, 4]\n# 'y' is [2, 5]\n# 'z' is [3, 6]\npack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim.\npack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]]\n```\n\nThis is the opposite of `unpack`.","inputs":[{"description":"Must be of same shape and type.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The packed tensor.","name":"output","typeAttr":"T"}],"summary":"Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor."}},{"name":"Pad","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"category":"Tensor","description":"This operation pads a `input` with zeros according to the `paddings` you\nspecify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the\nrank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many zeros to add before the contents of `input` in that dimension, and\n`paddings[D, 1]` indicates how many zeros to add after the contents of `input`\nin that dimension.\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 1], [2, 2]]\n# 'paddings' is [[1, 1], [2, 2]]\n# rank of 't' is 2\npad(t, paddings) ==> [[0, 0, 0, 0, 0, 0]\n [0, 0, 1, 1, 0, 0]\n [0, 0, 2, 2, 0, 0]\n [0, 0, 0, 0, 0, 0]]\n```\n","inputs":[{"name":"input","typeAttr":"T"},{"name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Pads a tensor with zeros."}},{"name":"PadV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"description":"This operation pads `input` according to the `paddings` and `constant_values`\nyou specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is\nthe rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates\nhow many padding values to add before the contents of `input` in that dimension,\nand `paddings[D, 1]` indicates how many padding values to add after the contents\nof `input` in that dimension. `constant_values` is a scalar tensor of the same\ntype as `input` that indicates the value to use for padding `input`.\n\nThe padded size of each dimension D of the output is:\n\n`paddings(D, 0) + input.dim_size(D) + paddings(D, 1)`\n\nFor example:\n\n```\n# 't' is [[1, 1], [2, 2]]\n# 'paddings' is [[1, 1], [2, 2]]\n# 'constant_values' is 0\n# rank of 't' is 2\npad(t, paddings) ==> [[0, 0, 0, 0, 0, 0]\n [0, 0, 1, 1, 0, 0]\n [0, 0, 2, 2, 0, 0]\n [0, 0, 0, 0, 0, 0]]\n```","inputs":[{"name":"input","typeAttr":"T"},{"name":"paddings","typeAttr":"Tpaddings"},{"name":"constant_values","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Pads a tensor."}},{"name":"PaddedBatchDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A list of int64 tensors representing the desired padded shapes\nof the corresponding output components. These shapes may be partially\nspecified, using `-1` to indicate that a particular dimension should be\npadded to the maximum size of all batch elements.","name":"padded_shapes","numberAttr":"N","type":9},{"description":"A list of scalars containing the padding value to use for\neach of the outputs.","name":"padding_values","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches and pads `batch_size` elements from the input."}},{"name":"PaddedBatchDatasetV2","schema":{"attributes":[{"default":false,"name":"parallel_copy","type":"boolean"},{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements to accumulate in a\nbatch.","name":"batch_size","type":9},{"description":"A list of int64 tensors representing the desired padded shapes\nof the corresponding output components. These shapes may be partially\nspecified, using `-1` to indicate that a particular dimension should be\npadded to the maximum size of all batch elements.","name":"padded_shapes","numberAttr":"N","type":9},{"description":"A list of scalars containing the padding value to use for\neach of the outputs.","name":"padding_values","typeListAttr":"Toutput_types"},{"description":"A scalar representing whether the last batch should be dropped in case its size\nis smaller than desired.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that batches and pads `batch_size` elements from the input."}},{"name":"PaddingFIFOQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types.\nShapes of fixed rank but variable size are allowed by setting\nany shape dimension to -1. In this case, the inputs' shape may vary along\nthe given dimension, and DequeueMany will pad the given dimension with\nzeros up to the maximum shape of all elements in the given batch.\nIf the length of this attr is 0, different queue elements may have\ndifferent ranks and shapes, but only one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Variable-size shapes are allowed by setting the corresponding shape dimensions\nto 0 in the shape attr. In this case DequeueMany will pad up to the maximum\nsize of any given element in the minibatch. See below for details.","outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"PaddingFIFOQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types.\nShapes of fixed rank but variable size are allowed by setting\nany shape dimension to -1. In this case, the inputs' shape may vary along\nthe given dimension, and DequeueMany will pad the given dimension with\nzeros up to the maximum shape of all elements in the given batch.\nIf the length of this attr is 0, different queue elements may have\ndifferent ranks and shapes, but only one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Variable-size shapes are allowed by setting the corresponding shape dimensions\nto 0 in the shape attr. In this case DequeueMany will pad up to the maximum\nsize of any given element in the minibatch. See below for details.","outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements in first-in first-out order."}},{"name":"ParallelConcat","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"description":"the final shape of the result; should be equal to the shapes of any input\nbut with the number of input values in the first dimension.","name":"shape","type":"shape"}],"description":"The input tensors are all required to have size 1 in the first dimension.\n\nFor example:\n\n```\n# 'x' is [[1, 4]]\n# 'y' is [[2, 5]]\n# 'z' is [[3, 6]]\nparallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim.\n```\n\nThe difference between concat and parallel_concat is that concat requires all\nof the inputs be computed before the operation will begin but doesn't require\nthat the input shapes be known during graph construction. Parallel concat\nwill copy pieces of the input into the output as they become available, in\nsome situations this can provide a performance benefit.","inputs":[{"description":"Tensors to be concatenated. All must have size 1 in the first dimension\nand same shape.","name":"values","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The concatenated tensor.","name":"output","typeAttr":"T"}],"summary":"Concatenates a list of `N` tensors along the first dimension."}},{"name":"ParallelDynamicStitch","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Builds a merged tensor such that\n\n```python\n merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]\n```\n\nFor example, if each `indices[m]` is scalar or vector, we have\n\n```python\n # Scalar indices:\n merged[indices[m], ...] = data[m][...]\n\n # Vector indices:\n merged[indices[m][i], ...] = data[m][i, ...]\n```\n\nEach `data[i].shape` must start with the corresponding `indices[i].shape`,\nand the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we\nmust have `data[i].shape = indices[i].shape + constant`. In terms of this\n`constant`, the output shape is\n\n merged.shape = [max(indices)] + constant\n\nValues may be merged in parallel, so if an index appears in both `indices[m][i]`\nand `indices[n][j]`, the result may be invalid. This differs from the normal\nDynamicStitch operator that defines the behavior in that case.\n\nFor example:\n\n```python\n indices[0] = 6\n indices[1] = [4, 1]\n indices[2] = [[5, 2], [0, 3]]\n data[0] = [61, 62]\n data[1] = [[41, 42], [11, 12]]\n data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]\n merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],\n [51, 52], [61, 62]]\n```\n\nThis method can be used to merge partitions created by `dynamic_partition`\nas illustrated on the following example:\n\n```python\n # Apply function (increments x_i) on elements for which a certain condition\n # apply (x_i != -1 in this example).\n x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4])\n condition_mask=tf.not_equal(x,tf.constant(-1.))\n partitioned_data = tf.dynamic_partition(\n x, tf.cast(condition_mask, tf.int32) , 2)\n partitioned_data[1] = partitioned_data[1] + 1.0\n condition_indices = tf.dynamic_partition(\n tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)\n x = tf.dynamic_stitch(condition_indices, partitioned_data)\n # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain\n # unchanged.\n```\n\n
    \n\n
    ","inputs":[{"name":"indices","numberAttr":"N","type":3},{"name":"data","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"merged","typeAttr":"T"}],"summary":"Interleave the values from the `data` tensors into a single tensor."}},{"name":"ParallelInterleaveDataset","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, with the exception\nthat if retrieving the next value from a dataset would cause the requester to\nblock, it will skip that input dataset. This dataset is especially useful\nwhen loading data from a variable-latency datastores (e.g. HDFS, GCS), as it\nallows the training step to proceed so long as some data is available.\n\n!! WARNING !! If the `sloppy` parameter is set to `True`, the operation of this\ndataset will not be deterministic!\n\nThis dataset has been superseded by `ParallelInterleaveDatasetV2`. New code\nshould use `ParallelInterleaveDatasetV2`.\n\nThe Python API `tf.data.experimental.parallel_interleave` creates instances of\nthis op. `tf.data.experimental.parallel_interleave` is a deprecated API.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDataset` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"If `True`, return elements as they become available, even if that means returning\nthese elements in a non-deterministic order. Sloppy operation may result in better\nperformance in the presence of stragglers, but the dataset will still block if\nall of its open streams are blocked.\nIf `False`, always return elements in a deterministic order.","name":"sloppy","type":10},{"description":"The number of elements each iterator being interleaved should buffer (similar\nto the `.prefetch()` transformation for each interleaved iterator).","name":"buffer_output_elements","type":9},{"description":"Determines the number of iterators to prefetch, allowing buffers to warm up and\ndata to be pre-fetched without blocking the main thread.","name":"prefetch_input_elements","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV2","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`,\nwhich can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV3","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the interleave is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can either set the `deterministic`\nattribute to \"false\", or leave it as \"default\" and set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`.\nThis can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelInterleaveDatasetV4","schema":{"attributes":[{"description":"A function mapping elements of `input_dataset`, concatenated with\n`other_arguments`, to a Dataset variant that contains elements matching\n`output_types` and `output_shapes`.","name":"f","type":"function"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the interleave is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"description":"Types of the elements of `other_arguments`.","minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The resulting dataset is similar to the `InterleaveDataset`, except that the\ndataset will fetch records from the interleaved datasets in parallel.\n\nThe `tf.data` Python API creates instances of this op from\n`Dataset.interleave()` when the `num_parallel_calls` parameter of that method\nis set to any value other than `None`.\n\nBy default, the output of this dataset will be deterministic, which may result\nin the dataset blocking if the next data item to be returned isn't available.\nIn order to avoid head-of-line blocking, one can either set the `deterministic`\nattribute to \"false\", or leave it as \"default\" and set the\n`experimental_deterministic` parameter of `tf.data.Options` to `False`.\nThis can improve performance at the expense of non-determinism.","inputs":[{"description":"Dataset that produces a stream of arguments for the function `f`.","name":"input_dataset","type":21},{"description":"Additional arguments to pass to `f` beyond those produced by `input_dataset`.\nEvaluated once when the dataset is instantiated.","name":"other_arguments","typeListAttr":"Targuments"},{"description":"Number of datasets (each created by applying `f` to the elements of\n`input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a\nround-robin fashion.","name":"cycle_length","type":9},{"description":"Number of elements at a time to produce from each interleaved invocation of a\ndataset returned by `f`.","name":"block_length","type":9},{"description":"The number of elements each iterator being interleaved should buffer (similar\nto the `.prefetch()` transformation for each interleaved iterator).","name":"buffer_output_elements","type":9},{"description":"Determines the number of iterators to prefetch, allowing buffers to warm up and\ndata to be pre-fetched without blocking the main thread.","name":"prefetch_input_elements","type":9},{"description":"Determines the number of threads that should be used for fetching data from\ninput datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE`\nconstant can be used to indicate that the level of parallelism should be autotuned.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelMapDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":false,"name":"sloppy","type":"boolean"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Unlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `num_parallel_calls` copies of `f` in parallel.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"description":"The number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"num_parallel_calls","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParallelMapDatasetV2","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"},{"default":"default","name":"deterministic","type":"string"},{"default":false,"name":"preserve_cardinality","type":"boolean"}],"description":"Unlike a \"MapDataset\", which applies `f` sequentially, this dataset invokes up\nto `num_parallel_calls` copies of `f` in parallel.","inputs":[{"name":"input_dataset","type":21},{"name":"other_arguments","typeListAttr":"Targuments"},{"description":"The number of concurrent invocations of `f` that process\nelements from `input_dataset` in parallel.","name":"num_parallel_calls","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that applies `f` to the outputs of `input_dataset`."}},{"name":"ParameterizedTruncatedNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"scalar which applies to the entire output, or a vector of length shape[0] which\nstores the parameters for each batch.","inputs":[{"description":"The shape of the output tensor. Batches are indexed by the 0th dimension.","name":"shape","typeAttr":"T"},{"description":"The mean parameter of each batch.","name":"means","typeAttr":"dtype"},{"description":"The standard deviation parameter of each batch. Must be greater than 0.","name":"stdevs","typeAttr":"dtype"},{"description":"The minimum cutoff. May be -infinity.","name":"minvals","typeAttr":"dtype"},{"description":"The maximum cutoff. May be +infinity, and must be more than the minval\nfor each batch.","name":"maxvals","typeAttr":"dtype"}],"outputs":[{"description":"A matrix of shape num_batches x samples_per_batch, filled with random\ntruncated normal values using the parameters for each row.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution. The parameters may each be a"}},{"name":"ParseExample","schema":{"attributes":[{"minimum":0,"name":"Nsparse","type":"int64"},{"minimum":0,"name":"Ndense","type":"int64"},{"description":"A list of Nsparse types; the data types of data in each Feature\ngiven in sparse_keys.\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"A list of Ndense shapes; the shapes of data in each Feature\ngiven in dense_keys.\nThe number of elements in the Feature corresponding to dense_key[j]\nmust always equal dense_shapes[j].NumEntries().\nIf dense_shapes[j] == (D0, D1, ..., DN) then the shape of output\nTensor dense_values[j] will be (|serialized|, D0, D1, ..., DN):\nThe dense outputs are just the inputs row-stacked by batch.\nThis works for dense_shapes[j] = (-1, D1, ..., DN). In this case\nthe shape of the output Tensor dense_values[j] will be\n(|serialized|, M, D1, .., DN), where M is the maximum number of blocks\nof elements of length D1 * .... * DN, across all minibatch entries\nin the input. Any minibatch entry with less than M blocks of elements of\nlength D1 * ... * DN will be padded with the corresponding default_value\nscalar element along the second dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing a batch of binary serialized Example protos.","name":"serialized","type":7},{"description":"A vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) names for the\ncorresponding serialized protos. These are purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no names are available.\nIf non-empty, this vector must be the same length as \"serialized\".","name":"names","type":7},{"description":"A list of Nsparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with sparse values.","name":"sparse_keys","numberAttr":"Nsparse","type":7},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples' features associated with dense values.","name":"dense_keys","numberAttr":"Ndense","type":7},{"description":"A list of Ndense Tensors (some may be empty).\ndense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"Nsparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"Nsparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"}],"summary":"Transforms a vector of brain.Example protos (as strings) into typed tensors."}},{"name":"ParseExampleDataset","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"sloppy","type":"boolean"},{"default":[],"minimum":0,"name":"ragged_keys","type":"string[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ParseExampleDatasetV2","schema":{"attributes":[{"description":"A list of string keys in the examples features.\nThe results for these keys will be returned as `SparseTensor` objects.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"A list of Ndense string Tensors (scalars).\nThe keys expected in the Examples features associated with dense values.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `DTypes` of the same length as `sparse_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of DTypes of the same length as `dense_keys`.\nOnly `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),\nand `tf.string` (`BytesList`) are supported.\n Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"List of tuples with the same length as `dense_keys`.\nThe shape of the data for each dense feature referenced by `dense_keys`.\nRequired for any input tensors identified by `dense_keys`. Must be\neither fully defined, or may contain an unknown first dimension.\nAn unknown first dimension means the feature is treated as having\na variable number of blocks, and the output shape along this dimension\nis considered unknown at graph build time. Padding is applied for\nminibatch elements smaller than the maximum number of blocks for the\ngiven feature along this dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"},{"description":"The type list for the return values.","minimum":1,"name":"output_types","type":"type[]"},{"description":"The list of shapes being produced.","minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"default","description":"A string indicating the op-level determinism to use. Deterministic controls\nwhether the dataset is allowed to return elements out of order if the next\nelement to be returned isn't available, but a later element is. Options are\n\"true\", \"false\", and \"default\". \"default\" indicates that determinism should be\ndecided by the `experimental_deterministic` parameter of `tf.data.Options`.","name":"deterministic","type":"string"},{"default":[],"minimum":0,"name":"ragged_keys","type":"string[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"num_parallel_calls","type":9},{"description":"A dict mapping string keys to `Tensor`s.\nThe keys of the dict must match the dense_keys of the feature.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"handle","type":21}],"summary":"Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features."}},{"name":"ParseExampleV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"The number of sparse keys.","minimum":0,"name":"num_sparse","type":"int64"},{"description":"A list of `num_sparse` types; the data types of data in each Feature\ngiven in sparse_keys.\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"A list of `num_ragged` types; the data types of data in each Feature\ngiven in ragged_keys (where `num_ragged = sparse_keys.size()`).\nCurrently the ParseExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"ragged_value_types","type":"type[]"},{"description":"A list of `num_ragged` types; the data types of row_splits in each Feature\ngiven in ragged_keys (where `num_ragged = sparse_keys.size()`).\nMay be DT_INT32 or DT_INT64. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"ragged_split_types","type":"type[]"},{"description":"A list of `num_dense` shapes; the shapes of data in each Feature\ngiven in dense_keys (where `num_dense = dense_keys.size()`).\nThe number of elements in the Feature corresponding to dense_key[j]\nmust always equal dense_shapes[j].NumEntries().\nIf dense_shapes[j] == (D0, D1, ..., DN) then the shape of output\nTensor dense_values[j] will be (|serialized|, D0, D1, ..., DN):\nThe dense outputs are just the inputs row-stacked by batch.\nThis works for dense_shapes[j] = (-1, D1, ..., DN). In this case\nthe shape of the output Tensor dense_values[j] will be\n(|serialized|, M, D1, .., DN), where M is the maximum number of blocks\nof elements of length D1 * .... * DN, across all minibatch entries\nin the input. Any minibatch entry with less than M blocks of elements of\nlength D1 * ... * DN will be padded with the corresponding default_value\nscalar element along the second dimension.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar or vector containing binary serialized Example protos.","name":"serialized","type":7},{"description":"A tensor containing the names of the serialized protos.\nCorresponds 1:1 with the `serialized` tensor.\nMay contain, for example, table key (descriptive) names for the\ncorresponding serialized protos. These are purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no names are available.\nIf non-empty, this tensor must have the same shape as \"serialized\".","name":"names","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with sparse values.","name":"sparse_keys","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with dense values.","name":"dense_keys","type":7},{"description":"Vector of strings.\nThe keys expected in the Examples' features associated with ragged values.","name":"ragged_keys","type":7},{"description":"A list of Tensors (some may be empty). Corresponds 1:1 with `dense_keys`.\ndense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"num_sparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"num_sparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"},{"name":"ragged_values","typeListAttr":"ragged_value_types"},{"name":"ragged_row_splits","typeListAttr":"ragged_split_types"}],"summary":"Transforms a vector of tf.Example protos (as strings) into typed tensors."}},{"name":"ParseSequenceExample","schema":{"attributes":[{"description":"A vector listing the\nFeatureList keys which may be missing from the SequenceExamples. If the\nassociated FeatureList is missing, it is treated as empty. By default,\nany FeatureList not listed in this vector must exist in the SequenceExamples.","minimum":0,"name":"feature_list_dense_missing_assumed_empty","type":"string[]"},{"description":"A list of Ncontext_sparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with context_sparse\nvalues.","minimum":0,"name":"context_sparse_keys","type":"string[]"},{"description":"A list of Ncontext_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' context features associated with\ndense values.","minimum":0,"name":"context_dense_keys","type":"string[]"},{"description":"A list of Nfeature_list_sparse string Tensors\n(scalars). The keys expected in the FeatureLists associated with sparse\nvalues.","minimum":0,"name":"feature_list_sparse_keys","type":"string[]"},{"description":"A list of Nfeature_list_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","minimum":0,"name":"feature_list_dense_keys","type":"string[]"},{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Ncontext_dense","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing binary serialized SequenceExample protos.","name":"serialized","type":7},{"description":"A vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no name is available.","name":"debug_name","type":7},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"},{"name":"feature_list_dense_lengths","numberAttr":"Nfeature_list_dense","type":9}],"summary":"Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors."}},{"name":"ParseSequenceExampleV2","schema":{"attributes":[{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"RaggedTensor.value dtypes for the ragged context features. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_ragged_value_types","type":"type[]"},{"default":[],"description":"RaggedTensor.row_split dtypes for the ragged context features. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"context_ragged_split_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"RaggedTensor.value dtypes for the ragged FeatureList features. Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_ragged_value_types","type":"type[]"},{"default":[],"description":"RaggedTensor.row_split dtypes for the ragged FeatureList features. Must be one of the following: `int32`, `int64`.","minimum":0,"name":"feature_list_ragged_split_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar or vector containing binary serialized SequenceExample protos.","name":"serialized","type":7},{"description":"A scalar or vector containing the names of the serialized protos.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty vector if no name is available.","name":"debug_name","type":7},{"description":"The keys expected in the Examples' features associated with context_sparse\nvalues.","name":"context_sparse_keys","type":7},{"description":"The keys expected in the SequenceExamples' context features associated with\ndense values.","name":"context_dense_keys","type":7},{"description":"The keys expected in the Examples' features associated with context_ragged\nvalues.","name":"context_ragged_keys","type":7},{"description":"The keys expected in the FeatureLists associated with sparse values.","name":"feature_list_sparse_keys","type":7},{"description":"The keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","name":"feature_list_dense_keys","type":7},{"description":"The keys expected in the FeatureLists associated with ragged values.","name":"feature_list_ragged_keys","type":7},{"description":"A vector corresponding 1:1 with feature_list_dense_keys, indicating which\nfeatures may be missing from the SequenceExamples. If the associated\nFeatureList is missing, it is treated as empty.","name":"feature_list_dense_missing_assumed_empty","type":10},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"context_ragged_values","typeListAttr":"context_ragged_value_types"},{"name":"context_ragged_row_splits","typeListAttr":"context_ragged_split_types"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"},{"name":"feature_list_dense_lengths","numberAttr":"Nfeature_list_dense","type":9},{"name":"feature_list_ragged_values","typeListAttr":"feature_list_ragged_value_types"},{"name":"feature_list_ragged_outer_splits","typeListAttr":"feature_list_ragged_split_types"},{"name":"feature_list_ragged_inner_splits","typeListAttr":"feature_list_ragged_split_types"}],"summary":"Transforms a vector of tf.io.SequenceExample protos (as strings) into\ntyped tensors."}},{"name":"ParseSingleExample","schema":{"attributes":[{"description":"The number of sparse features to be parsed from the example. This\nmust match the lengths of `sparse_keys` and `sparse_types`.","minimum":0,"name":"num_sparse","type":"int64"},{"description":"A list of `num_sparse` strings.\nThe keys expected in the Examples' features associated with sparse values.","minimum":0,"name":"sparse_keys","type":"string[]"},{"description":"The keys expected in the Examples' features associated with dense\nvalues.","minimum":0,"name":"dense_keys","type":"string[]"},{"description":"A list of `num_sparse` types; the data types of data in each\nFeature given in sparse_keys.\nCurrently the ParseSingleExample op supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"The data types of data in each Feature given in dense_keys.\nThe length of this list must match the length of `dense_keys`.\nCurrently the ParseSingleExample op supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tdense","type":"type[]"},{"description":"The shapes of data in each Feature given in dense_keys.\nThe length of this list must match the length of `dense_keys`. The\nnumber of elements in the Feature corresponding to dense_key[j] must\nalways equal dense_shapes[j].NumEntries(). If dense_shapes[j] ==\n(D0, D1, ..., DN) then the shape of output Tensor dense_values[j]\nwill be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1,\n..., DN), the shape of the output Tensor dense_values[j] will be (M,\nD1, .., DN), where M is the number of blocks of elements of length\nD1 * .... * DN, in the input.","minimum":0,"name":"dense_shapes","type":"shape[]"}],"inputs":[{"description":"A vector containing a batch of binary serialized Example protos.","name":"serialized","type":7},{"description":"A list of Tensors (some may be empty), whose length matches\nthe length of `dense_keys`. dense_defaults[j] provides default values\nwhen the example's feature_map lacks dense_key[j]. If an empty Tensor is\nprovided for dense_defaults[j], then the Feature dense_keys[j] is required.\nThe input type is inferred from dense_defaults[j], even when it's empty.\nIf dense_defaults[j] is not empty, and dense_shapes[j] is fully defined,\nthen the shape of dense_defaults[j] must match that of dense_shapes[j].\nIf dense_shapes[j] has an undefined major dimension (variable strides dense\nfeature), dense_defaults[j] must contain a single element:\nthe padding element.","name":"dense_defaults","typeListAttr":"Tdense"}],"outputs":[{"name":"sparse_indices","numberAttr":"num_sparse","type":9},{"name":"sparse_values","typeListAttr":"sparse_types"},{"name":"sparse_shapes","numberAttr":"num_sparse","type":9},{"name":"dense_values","typeListAttr":"Tdense"}],"summary":"Transforms a tf.Example proto (as a string) into typed tensors."}},{"name":"ParseSingleSequenceExample","schema":{"attributes":[{"default":0,"minimum":0,"name":"Ncontext_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Ncontext_dense","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_sparse","type":"int64"},{"default":0,"minimum":0,"name":"Nfeature_list_dense","type":"int64"},{"default":[],"description":"A list of Ncontext_sparse types; the data types of data in\neach context Feature given in context_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"context_sparse_types","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"Tcontext_dense","type":"type[]"},{"default":[],"description":"Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_dense_types","type":"type[]"},{"default":[],"description":"A list of Ncontext_dense shapes; the shapes of data in\neach context Feature given in context_dense_keys.\nThe number of elements in the Feature corresponding to context_dense_key[j]\nmust always equal context_dense_shapes[j].NumEntries().\nThe shape of context_dense_values[j] will match context_dense_shapes[j].","minimum":0,"name":"context_dense_shapes","type":"shape[]"},{"default":[],"description":"A list of Nfeature_list_sparse types; the data types\nof data in each FeatureList given in feature_list_sparse_keys.\nCurrently the ParseSingleSequenceExample supports DT_FLOAT (FloatList),\nDT_INT64 (Int64List), and DT_STRING (BytesList). Must be one of the following: `float32`, `int64`, `string`.","minimum":0,"name":"feature_list_sparse_types","type":"type[]"},{"default":[],"description":"A list of Nfeature_list_dense shapes; the shapes of\ndata in each FeatureList given in feature_list_dense_keys.\nThe shape of each Feature in the FeatureList corresponding to\nfeature_list_dense_key[j] must always equal\nfeature_list_dense_shapes[j].NumEntries().","minimum":0,"name":"feature_list_dense_shapes","type":"shape[]"}],"inputs":[{"description":"A scalar containing a binary serialized SequenceExample proto.","name":"serialized","type":7},{"description":"A vector listing the\nFeatureList keys which may be missing from the SequenceExample. If the\nassociated FeatureList is missing, it is treated as empty. By default,\nany FeatureList not listed in this vector must exist in the SequenceExample.","name":"feature_list_dense_missing_assumed_empty","type":7},{"description":"A list of Ncontext_sparse string Tensors (scalars).\nThe keys expected in the Examples' features associated with context_sparse\nvalues.","name":"context_sparse_keys","numberAttr":"Ncontext_sparse","type":7},{"description":"A list of Ncontext_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' context features associated with\ndense values.","name":"context_dense_keys","numberAttr":"Ncontext_dense","type":7},{"description":"A list of Nfeature_list_sparse string Tensors\n(scalars). The keys expected in the FeatureLists associated with sparse\nvalues.","name":"feature_list_sparse_keys","numberAttr":"Nfeature_list_sparse","type":7},{"description":"A list of Nfeature_list_dense string Tensors (scalars).\nThe keys expected in the SequenceExamples' feature_lists associated\nwith lists of dense values.","name":"feature_list_dense_keys","numberAttr":"Nfeature_list_dense","type":7},{"description":"A list of Ncontext_dense Tensors (some may be empty).\ncontext_dense_defaults[j] provides default values\nwhen the SequenceExample's context map lacks context_dense_key[j].\nIf an empty Tensor is provided for context_dense_defaults[j],\nthen the Feature context_dense_keys[j] is required.\nThe input type is inferred from context_dense_defaults[j], even when it's\nempty. If context_dense_defaults[j] is not empty, its shape must match\ncontext_dense_shapes[j].","name":"context_dense_defaults","typeListAttr":"Tcontext_dense"},{"description":"A scalar containing the name of the serialized proto.\nMay contain, for example, table key (descriptive) name for the\ncorresponding serialized proto. This is purely useful for debugging\npurposes, and the presence of values here has no effect on the output.\nMay also be an empty scalar if no name is available.","name":"debug_name","type":7}],"outputs":[{"name":"context_sparse_indices","numberAttr":"Ncontext_sparse","type":9},{"name":"context_sparse_values","typeListAttr":"context_sparse_types"},{"name":"context_sparse_shapes","numberAttr":"Ncontext_sparse","type":9},{"name":"context_dense_values","typeListAttr":"Tcontext_dense"},{"name":"feature_list_sparse_indices","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_sparse_values","typeListAttr":"feature_list_sparse_types"},{"name":"feature_list_sparse_shapes","numberAttr":"Nfeature_list_sparse","type":9},{"name":"feature_list_dense_values","typeListAttr":"feature_list_dense_types"}],"summary":"Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors."}},{"name":"ParseTensor","schema":{"attributes":[{"description":"The type of the serialized tensor. The provided type must match the\ntype of the serialized tensor and no implicit conversion will take place.","name":"out_type","type":"type"}],"inputs":[{"description":"A scalar string containing a serialized TensorProto proto.","name":"serialized","type":7}],"outputs":[{"description":"A Tensor of type `out_type`.","name":"output","typeAttr":"out_type"}],"summary":"Transforms a serialized tensorflow.TensorProto proto into a Tensor."}},{"name":"PartitionedCall","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'args', a list of tensors, and returns 'output',\n another list of tensors. Input and output types are specified by 'Tin'\n and 'Tout'. The function body of f will be placed and partitioned across\n devices, setting this op apart from the regular Call op.","name":"f","type":"function"},{"default":"","name":"config","type":"string"},{"default":"","name":"config_proto","type":"string"},{"default":"","name":"executor_type","type":"string"}],"inputs":[{"description":"A list of input tensors.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"returns `f(inputs)`, where `f`'s body is placed and partitioned."}},{"name":"Placeholder","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"(Optional) The shape of the tensor. If the shape has 0 dimensions, the\nshape is unconstrained.","name":"shape","type":"shape"}],"description":"N.B. This operation will fail with an error if it is executed. It is\nintended as a way to represent a value that will always be fed, and to\nprovide attrs that enable the fed value to be checked at runtime.","outputs":[{"description":"A placeholder tensor that must be replaced using the feed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"PlaceholderV2","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The shape of the tensor. The shape can be any partially-specified\nshape. To be unconstrained, pass in a shape with unknown rank.","name":"shape","type":"shape"}],"description":"N.B. This operation will fail with an error if it is executed. It is\nintended as a way to represent a value that will always be fed, and to\nprovide attrs that enable the fed value to be checked at runtime.","outputs":[{"description":"A placeholder tensor that must be replaced using the feed mechanism.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op for a value that will be fed into the computation."}},{"name":"PlaceholderWithDefault","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"description":"The (possibly partial) shape of the tensor.","name":"shape","type":"shape"}],"inputs":[{"description":"The default value to produce when `output` is not fed.","name":"input","typeAttr":"dtype"}],"outputs":[{"description":"A placeholder tensor that defaults to `input` if it is not fed.","name":"output","typeAttr":"dtype"}],"summary":"A placeholder op that passes through `input` when its output is not fed."}},{"name":"Polygamma","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The polygamma function is defined as:\n\n\n\\\\(\\psi^{(a)}(x) = \\frac{d^a}{dx^a} \\psi(x)\\\\)\n\nwhere \\\\(\\psi(x)\\\\) is the digamma function.\nThe polygamma function is defined only for non-negative integer orders \\\\a\\\\.","inputs":[{"name":"a","typeAttr":"T"},{"name":"x","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the polygamma function \\\\(\\psi^{(n)}(x)\\\\)."}},{"name":"PopulationCount","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"For each entry in `x`, calculates the number of `1` (on) bits in the binary\nrepresentation of that entry.\n\n**NOTE**: It is more efficient to first `tf.bitcast` your tensors into\n`int32` or `int64` and perform the bitcount on the result, than to feed in\n8- or 16-bit inputs and then aggregate the resulting counts.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","type":4}],"summary":"Computes element-wise population count (a.k.a. popcount, bitsum, bitcount)."}},{"name":"Pow","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float16`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Given a tensor `x` and a tensor `y`, this operation computes \\\\(x^y\\\\) for\ncorresponding elements in `x` and `y`. For example:\n\n```\n# tensor 'x' is [[2, 2]], [3, 3]]\n# tensor 'y' is [[8, 16], [2, 3]]\ntf.pow(x, y) ==> [[256, 65536], [9, 27]]\n```","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the power of one value to another."}},{"name":"PrefetchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":0,"name":"slack_period","type":"int64"},{"default":true,"name":"legacy_autotune","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"description":"The maximum number of elements to buffer in an iterator over\nthis dataset.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that asynchronously prefetches elements from `input_dataset`."}},{"name":"Prelinearize","schema":{"attributes":[{"description":"The type of elements in the tensor.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The shape of the tensor.","name":"shape","type":"shape"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence. If a layout\nattribute is passed but its values are all -1 the layout will be computed by\nthe infeed operation.","name":"layout","type":"int64[]"}],"inputs":[{"description":"A tensor that will be linearized.","name":"input","typeAttr":"dtype"}],"outputs":[{"name":"output","type":21}],"summary":"An op which linearizes one Tensor value to an opaque variant tensor."}},{"name":"PrelinearizeTuple","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":1,"name":"dtypes","type":"type[]"},{"description":"The shapes of each tensor in `inputs`.","name":"shapes","type":"shape[]"},{"default":[],"description":"A vector holding the requested layout in minor-to-major sequence for all the\ntuple shapes in the order the shapes appear in the \"shapes\" input. The layout\nelements for a sub-shape can be set to -1 in which case the corresponding layout\nwill be computed by the infeed operation.","name":"layouts","type":"int64[]"}],"inputs":[{"description":"A list of tensors that will be provided using the infeed mechanism.","name":"inputs","typeListAttr":"dtypes"}],"outputs":[{"name":"output","type":21}],"summary":"An op which linearizes multiple Tensor values to an opaque variant tensor."}},{"name":"PreventGradient","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"Will be printed in the error when anyone tries to differentiate\nthis operation.","name":"message","type":"string"}],"description":"When executed in a graph, this op outputs its input tensor as-is.\n\nWhen building ops to compute gradients, the TensorFlow gradient system\nwill return an error when trying to lookup the gradient of this op,\nbecause no gradient must ever be registered for this function. This\nop exists to prevent subtle bugs from silently returning unimplemented\ngradients in some corner cases.","inputs":[{"description":"any tensor.","name":"input","typeAttr":"T"}],"outputs":[{"description":"the same input tensor.","name":"output","typeAttr":"T"}],"summary":"An identity op that triggers an error if a gradient is requested."}},{"name":"Print","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":0,"name":"U","type":"type[]"},{"default":"","description":"A string, prefix of the error message.","name":"message","type":"string"},{"default":-1,"description":"Only log `first_n` number of times. -1 disables logging.","name":"first_n","type":"int64"},{"default":3,"description":"Only print this many entries of each tensor.","name":"summarize","type":"int64"}],"description":"Passes `input` through to `output` and prints `data` when evaluating.","inputs":[{"description":"The tensor passed to `output`","name":"input","typeAttr":"T"},{"description":"A list of tensors to print out when op is evaluated.","name":"data","typeListAttr":"U"}],"outputs":[{"description":"= The unmodified `input` tensor","name":"output","typeAttr":"T"}],"summary":"Prints a list of tensors."}},{"name":"PrintV2","schema":{"attributes":[{"default":"stderr","description":"A string specifying the output stream or logging level to print to.","name":"output_stream","type":"string"},{"default":"\n","name":"end","type":"string"}],"description":"Prints a string scalar to the desired output_stream.","inputs":[{"description":"The string scalar to print.","name":"input","type":7}],"summary":"Prints a string scalar."}},{"name":"PriorityQueue","schema":{"attributes":[{"default":[],"description":"The type of each component in a value.","minimum":0,"name":"component_types","type":"type[]"},{"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Note that the PriorityQueue requires the first component of any element\nto be a scalar int64, in addition to the other elements declared by\ncomponent_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue\nand DequeueMany) on a PriorityQueue will all require (resp. output) one extra\nentry in their input (resp. output) lists.","outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that produces elements sorted by the first component value."}},{"name":"PriorityQueueV2","schema":{"attributes":[{"default":[],"description":"The type of each component in a value.","minimum":0,"name":"component_types","type":"type[]"},{"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"description":"Note that the PriorityQueue requires the first component of any element\nto be a scalar int64, in addition to the other elements declared by\ncomponent_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue\nand DequeueMany) on a PriorityQueue will all require (resp. output) one extra\nentry in their input (resp. output) lists.","outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that produces elements sorted by the first component value."}},{"name":"PrivateThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"Identifies the number of threads to use for the private threadpool.","name":"num_threads","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"Prod","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the product of elements across dimensions of a tensor."}},{"name":"PyFunc","schema":{"attributes":[{"description":"A token representing a registered python function in this address space.","name":"token","type":"string"},{"description":"Data types of the inputs to the op.","minimum":0,"name":"Tin","type":"type[]"},{"description":"Data types of the outputs from the op.\nThe length of the list specifies the number of outputs.","minimum":0,"name":"Tout","type":"type[]"}],"description":"This operation is considered stateful. For a stateless version, see\nPyFuncStateless.","inputs":[{"description":"List of Tensors that will provide input to the Op.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"The outputs from the Op.","name":"output","typeListAttr":"Tout"}],"summary":"Invokes a python function to compute func(input)->output."}},{"name":"PyFuncStateless","schema":{"attributes":[{"name":"token","type":"string"},{"minimum":0,"name":"Tin","type":"type[]"},{"minimum":0,"name":"Tout","type":"type[]"}],"inputs":[{"name":"input","typeListAttr":"Tin"}],"outputs":[{"name":"output","typeListAttr":"Tout"}],"summary":"A stateless version of PyFunc."}},{"name":"Qr","schema":{"attributes":[{"default":false,"description":"If true, compute full-sized `q` and `r`. If false\n(the default), compute only the leading `P` columns of `q`.","name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the QR decomposition of each inner matrix in `tensor` such that\n`tensor[..., :, :] = q[..., :, :] * r[..., :,:])`\n\n```python\n# a is a tensor.\n# q is a tensor of orthonormal matrices.\n# r is a tensor of upper triangular matrices.\nq, r = qr(a)\nq_full, r_full = qr(a, full_matrices=True)\n```","inputs":[{"description":"A tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Orthonormal basis for range of `a`. If `full_matrices` is `False` then\nshape is `[..., M, P]`; if `full_matrices` is `True` then shape is\n`[..., M, M]`.","name":"q","typeAttr":"T"},{"description":"Triangular factor. If `full_matrices` is `False` then shape is\n`[..., P, N]`. If `full_matrices` is `True` then shape is `[..., M, N]`.","name":"r","typeAttr":"T"}],"summary":"Computes the QR decompositions of one or more matrices."}},{"name":"QuantizeAndDequantize","schema":{"attributes":[{"default":true,"name":"signed_input","type":"boolean"},{"default":8,"name":"num_bits","type":"int64"},{"default":false,"name":"range_given","type":"boolean"},{"default":0,"name":"input_min","type":"float32"},{"default":0,"name":"input_max","type":"float32"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Use QuantizeAndDequantizeV2 instead."}},{"name":"QuantizeAndDequantizeV2","schema":{"attributes":[{"default":true,"description":"Whether the quantization is signed or unsigned. (actually this parameter should\nhave been called `signed_output`)","name":"signed_input","type":"boolean"},{"default":8,"description":"The bitwidth of the quantization.","name":"num_bits","type":"int64"},{"default":false,"description":"Whether the range is given or should be determined from the `input` tensor.","name":"range_given","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"HALF_TO_EVEN","description":"The 'round_mode' attribute controls which rounding tie-breaking algorithm is\nused when rounding float values to their quantized equivalents. The following\nrounding modes are currently supported:\n\n* HALF_TO_EVEN: this is the default round_mode.\n* HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5\n rounds up to -7.\n Must be one of the following: `HALF_TO_EVEN`, `HALF_UP`.","name":"round_mode","type":"string"},{"default":false,"description":"If True, then the absolute value of the quantized minimum value is the same as\nthe quantized maximum value, instead of 1 greater.\ni.e. for 8 bit quantization, the minimum value is -127 instead of -128.","name":"narrow_range","type":"boolean"},{"default":-1,"description":"If specified, this axis is treated as a channel or slice axis, and a separate\nquantization range is used for each channel or slice along this axis.","name":"axis","type":"int64"}],"description":"This op simulates the precision loss from the quantized forward pass by:\n\n1. Quantizing the tensor to fixed point numbers, which should match the target\n quantization method when it is used in inference.\n2. Dequantizing it back to floating point numbers for the following ops, most\n likely matmul.\n\nThere are different ways to quantize. This version uses only scaling, so 0.0\nmaps to 0.\n\nFrom the specified 'num_bits' in the quantized output type, it determines\nminimum and maximum representable quantized values.\n\ne.g.\n\n* [-128, 127] for signed, num_bits = 8, or\n* [0, 255] for unsigned, num_bits = 8.\n\nIf range_given == False, the initial input_min, input_max will be determined\nautomatically as the minimum and maximum values in the input tensor, otherwise\nthe specified values of input_min, input_max are used.\n\nNote: If the input_min, input_max are specified, they do not need to equal the\nactual minimum and maximum values in the tensor. e.g. in some cases it may be\nbeneficial to specify these values such that the low probability extremes of the\ninput distribution are clipped.\n\nThis op determines the maximum scale_factor that would map the initial\n[input_min, input_max] range to a range that lies within the representable\nquantized range.\n\nIt determines the scale from one of input_min and input_max, then updates the\nother one to maximize the representable range.\n\ne.g.\n\n* if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0,\n 5.0]: it would use a scale_factor of -128 / -10.0 = 12.8 In this case, it\n would update input_max to be 127 / 12.8 = 9.921875\n* if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0,\n 10.0]: it would use a scale_factor of 127 / 10.0 = 12.7 In this case, it\n would update input_min to be 128.0 / 12.7 = -10.07874\n* if the output is unsigned, input_min is forced to be 0, and only the\n specified input_max is used.\n\nAfter determining the scale_factor and updating the input range, it applies the\nfollowing to each value in the 'input' tensor.\n\noutput = round(clamp(value, input_min, input_max) * scale_factor) / scale_factor.\n\nThe above round function rounds the value based on the given round_mode.\n","inputs":[{"description":"Tensor to quantize and then dequantize.","name":"input","typeAttr":"T"},{"description":"If `range_given == True`, this specifies the minimum input value that needs to\nbe represented, otherwise it is determined from the min value of the `input`\ntensor.","name":"input_min","typeAttr":"T"},{"description":"If `range_given == True`, this specifies the maximum input value that needs to\nbe represented, otherwise it is determined from the max value of the `input`\ntensor.","name":"input_max","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Quantizes then dequantizes a tensor."}},{"name":"QuantizeAndDequantizeV3","schema":{"attributes":[{"default":true,"name":"signed_input","type":"boolean"},{"default":true,"name":"range_given","type":"boolean"},{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"}],"description":"This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a\ntensor, so its value can change during training.","inputs":[{"name":"input","typeAttr":"T"},{"name":"input_min","typeAttr":"T"},{"name":"input_max","typeAttr":"T"},{"name":"num_bits","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Quantizes then dequantizes a tensor."}},{"name":"QuantizeDownAndShrinkRange","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the output. Should be a lower bit depth than Tinput. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"actual distribution of the values to maximize the usage of the lower bit depth\nand adjusting the output min and max ranges accordingly.\n\n[input_min, input_max] are scalar floats that specify the range for the float\ninterpretation of the 'input' data. For example, if input_min is -1.0f and\ninput_max is 1.0f, and we are dealing with quint16 quantized data, then a 0\nvalue in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f.\n\nThis operator tries to squeeze as much precision as possible into an output with\na lower bit depth by calculating the actual min and max values found in the\ndata. For example, maybe that quint16 input has no values lower than 16,384 and\nnone higher than 49,152. That means only half the range is actually needed, all\nthe float interpretations are between -0.5f and 0.5f, so if we want to compress\nthe data into a quint8 output, we can use that range rather than the theoretical\n-1.0f to 1.0f that is suggested by the input min and max.\n\nIn practice, this is most useful for taking output from operations like\nQuantizedMatMul that can produce higher bit-depth outputs than their inputs and\nmay have large potential output ranges, but in practice have a distribution of\ninput values that only uses a small fraction of the possible range. By feeding\nthat output into this operator, we can reduce it from 32 bits down to 8 with\nminimal loss of accuracy.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"output_max","type":1}],"summary":"Convert the quantized 'input' tensor into a lower-precision 'output', using the"}},{"name":"QuantizeV2","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":"MIN_COMBINED","description":"Must be one of the following: `MIN_COMBINED`, `MIN_FIRST`, `SCALED`.","name":"mode","type":"string"},{"default":"HALF_AWAY_FROM_ZERO","description":"Must be one of the following: `HALF_AWAY_FROM_ZERO`, `HALF_TO_EVEN`.","name":"round_mode","type":"string"},{"default":false,"name":"narrow_range","type":"boolean"},{"default":-1,"name":"axis","type":"int64"},{"default":0.009999999776482582,"name":"ensure_minimum_range","type":"float32"}],"description":"[min_range, max_range] are scalar floats that specify the range for\nthe 'input' data. The 'mode' attribute controls exactly which calculations are\nused to convert the float values to their quantized equivalents. The\n'round_mode' attribute controls which rounding tie-breaking algorithm is used\nwhen rounding float values to their quantized equivalents.\n\nIn 'MIN_COMBINED' mode, each value of the tensor will undergo the following:\n\n```\nout[i] = (in[i] - min_range) * range(T) / (max_range - min_range)\nif T == qint8: out[i] -= (range(T) + 1) / 2.0\n```\n\nhere `range(T) = numeric_limits::max() - numeric_limits::min()`\n\n*MIN_COMBINED Mode Example*\n\nAssume the input is type float and has a possible range of [0.0, 6.0] and the\noutput type is quint8 ([0, 255]). The min_range and max_range values should be\nspecified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each\nvalue of the input by 255/6 and cast to quint8.\n\nIf the output type was qint8 ([-128, 127]), the operation will additionally\nsubtract each value by 128 prior to casting, so that the range of values aligns\nwith the range of qint8.\n\nIf the mode is 'MIN_FIRST', then this approach is used:\n\n```\nnum_discrete_values = 1 << (# of bits in T)\nrange_adjust = num_discrete_values / (num_discrete_values - 1)\nrange = (range_max - range_min) * range_adjust\nrange_scale = num_discrete_values / range\nquantized = round(input * range_scale) - round(range_min * range_scale) +\n numeric_limits::min()\nquantized = max(quantized, numeric_limits::min())\nquantized = min(quantized, numeric_limits::max())\n```\n\nThe biggest difference between this and MIN_COMBINED is that the minimum range\nis rounded first, before it's subtracted from the rounded value. With\nMIN_COMBINED, a small bias is introduced where repeated iterations of quantizing\nand dequantizing will introduce a larger and larger error.\n\n*SCALED mode Example*\n\n`SCALED` mode matches the quantization approach used in\n`QuantizeAndDequantize{V2|V3}`.\n\nIf the mode is `SCALED`, the quantization is performed by multiplying each\ninput value by a scaling_factor.\nThe scaling_factor is determined from `min_range` and `max_range` to be as large\nas possible such that the range from `min_range` to `max_range` is representable\nwithin values of type T.\n\n```c++\n\n const int min_T = std::numeric_limits::min();\n const int max_T = std::numeric_limits::max();\n const float max_float = std::numeric_limits::max();\n\n const float scale_factor_from_min_side =\n (min_T * min_range > 0) ? min_T / min_range : max_float;\n const float scale_factor_from_max_side =\n (max_T * max_range > 0) ? max_T / max_range : max_float;\n\n const float scale_factor = std::min(scale_factor_from_min_side,\n scale_factor_from_max_side);\n```\n\nWe next use the scale_factor to adjust min_range and max_range as follows:\n\n```c++\n min_range = min_T / scale_factor;\n max_range = max_T / scale_factor;\n```\n\n\ne.g. if T = qint8, and initially min_range = -10, and max_range = 9, we would\ncompare -128/-10.0 = 12.8 to 127/9.0 = 14.11, and set scaling_factor = 12.8\nIn this case, min_range would remain -10, but max_range would be adjusted to\n127 / 12.8 = 9.921875\n\nSo we will quantize input values in the range (-10, 9.921875) to (-128, 127).\n\nThe input tensor can now be quantized by clipping values to the range\n`min_range` to `max_range`, then multiplying by scale_factor as follows:\n\n```c++\nresult = round(min(max_range, max(min_range, input)) * scale_factor)\n```\n\nThe adjusted `min_range` and `max_range` are returned as outputs 2 and 3 of\nthis operation. These outputs should be used as the range for any further\ncalculations.\n\n\n*narrow_range (bool) attribute*\n\nIf true, we do not use the minimum quantized value.\ni.e. for int8 the quantized output, it would be restricted to the range\n-127..127 instead of the full -128..127 range.\nThis is provided for compatibility with certain inference backends.\n(Only applies to SCALED mode)\n\n\n*axis (int) attribute*\n\nAn optional `axis` attribute can specify a dimension index of the input tensor,\nsuch that quantization ranges will be calculated and applied separately for each\nslice of the tensor along that dimension. This is useful for per-channel\nquantization.\n\nIf axis is specified, min_range and max_range\n\nif `axis`=None, per-tensor quantization is performed as normal.\n\n\n*ensure_minimum_range (float) attribute*\n\nEnsures the minimum quantization range is at least this value.\nThe legacy default value for this is 0.01, but it is strongly suggested to\nset it to 0 for new uses.\n","inputs":[{"name":"input","type":1},{"description":"The minimum value of the quantization range. This value may be adjusted by the\nop depending on other parameters. The adjusted value is written to `output_min`.\nIf the `axis` attribute is specified, this must be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"min_range","type":1},{"description":"The maximum value of the quantization range. This value may be adjusted by the\nop depending on other parameters. The adjusted value is written to `output_max`.\nIf the `axis` attribute is specified, this must be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"max_range","type":1}],"outputs":[{"description":"The quantized data produced from the float input.","name":"output","typeAttr":"T"},{"description":"The final quantization range minimum, used to clip input values before scaling\nand rounding them to quantized values.\nIf the `axis` attribute is specified, this will be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"output_min","type":1},{"description":"The final quantization range maximum, used to clip input values before scaling\nand rounding them to quantized values.\nIf the `axis` attribute is specified, this will be a 1-D tensor whose size\nmatches the `axis` dimension of the input and output tensors.","name":"output_max","type":1}],"summary":"Quantize the 'input' tensor of type float to 'output' tensor of type 'T'."}},{"name":"QuantizedAdd","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"}],"inputs":[{"name":"x","typeAttr":"T1"},{"name":"y","typeAttr":"T2"},{"description":"The float value that the lowest quantized `x` value represents.","name":"min_x","type":1},{"description":"The float value that the highest quantized `x` value represents.","name":"max_x","type":1},{"description":"The float value that the lowest quantized `y` value represents.","name":"min_y","type":1},{"description":"The float value that the highest quantized `y` value represents.","name":"max_y","type":1}],"outputs":[{"name":"z","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_z","type":1},{"description":"The float value that the highest quantized output value represents.\n\n*NOTE*: `QuantizedAdd` supports limited forms of broadcasting. More about\nbroadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","name":"max_z","type":1}],"summary":"Returns x + y element-wise, working on quantized buffers."}},{"name":"QuantizedAvgPool","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.\nThe length must be 4 to match the number of dimensions of the input.","name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. The length must be 4 to match the number of dimensions of the input.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"input","typeAttr":"T"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Produces the average pool of the input tensor for quantized types."}},{"name":"QuantizedBatchNormWithGlobalNormalization","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"description":"A bool indicating whether the resulted tensor\nneeds to be multiplied with gamma.","name":"scale_after_normalization","type":"boolean"}],"description":"This op is deprecated and will be removed in the future. Prefer\n`tf.nn.batch_normalization`.","inputs":[{"description":"A 4D input Tensor.","name":"t","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized input.","name":"t_min","type":1},{"description":"The value represented by the highest quantized input.","name":"t_max","type":1},{"description":"A 1D mean Tensor with size matching the last dimension of t.\nThis is the first output from tf.nn.moments,\nor a saved moving average thereof.","name":"m","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized mean.","name":"m_min","type":1},{"description":"The value represented by the highest quantized mean.","name":"m_max","type":1},{"description":"A 1D variance Tensor with size matching the last dimension of t.\nThis is the second output from tf.nn.moments,\nor a saved moving average thereof.","name":"v","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized variance.","name":"v_min","type":1},{"description":"The value represented by the highest quantized variance.","name":"v_max","type":1},{"description":"A 1D beta Tensor with size matching the last dimension of t.\nAn offset to be added to the normalized tensor.","name":"beta","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized offset.","name":"beta_min","type":1},{"description":"The value represented by the highest quantized offset.","name":"beta_max","type":1},{"description":"A 1D gamma Tensor with size matching the last dimension of t.\nIf \"scale_after_normalization\" is true, this tensor will be multiplied\nwith the normalized tensor.","name":"gamma","typeAttr":"Tinput"},{"description":"The value represented by the lowest quantized gamma.","name":"gamma_min","type":1},{"description":"The value represented by the highest quantized gamma.","name":"gamma_max","type":1}],"outputs":[{"name":"result","typeAttr":"out_type"},{"name":"result_min","type":1},{"name":"result_max","type":1}],"summary":"Quantized Batch normalization."}},{"name":"QuantizedBiasAdd","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"Broadcasts the values of bias on dimensions 0..N-2 of 'input'.","inputs":[{"name":"input","typeAttr":"T1"},{"description":"A 1D bias Tensor with size matching the last dimension of 'input'.","name":"bias","typeAttr":"T2"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the lowest quantized bias value represents.","name":"min_bias","type":1},{"description":"The float value that the highest quantized bias value represents.","name":"max_bias","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Adds Tensor 'bias' to Tensor 'input' for Quantized types."}},{"name":"QuantizedConcat","schema":{"attributes":[{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"inputs":[{"description":"0-D. The dimension along which to concatenate. Must be in the\nrange [0, rank(values)).","name":"concat_dim","type":3},{"description":"The `N` Tensors to concatenate. Their ranks and types must match,\nand their sizes must match in all dimensions except `concat_dim`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"The minimum scalar values for each of the input tensors.","name":"input_mins","numberAttr":"N","type":1},{"description":"The maximum scalar values for each of the input tensors.","name":"input_maxes","numberAttr":"N","type":1}],"outputs":[{"description":"A `Tensor` with the concatenation of values stacked along the\n`concat_dim` dimension. This tensor's shape matches that of `values` except\nin `concat_dim` where it has the sum of the sizes.","name":"output","typeAttr":"T"},{"description":"The float value that the minimum quantized output value represents.","name":"output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"output_max","type":1}],"summary":"Concatenates quantized tensors along one dimension."}},{"name":"QuantizedConv2D","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"The stride of the sliding window for each dimension of the input\ntensor.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"1-D tensor of length 4. The dilation factor for each dimension of\n`input`. If set to k > 1, there will be k-1 skipped cells between each\nfilter element on that dimension. The dimension order is determined by the\nvalue of `data_format`, see above for details. Dilations in the batch and\ndepth dimensions must be 1.","name":"dilations","type":"int64[]"}],"description":"The inputs are quantized tensors where the lowest value represents the real\nnumber of the associated minimum, and the highest represents the maximum.\nThis means that you can only interpret the quantized output in the same way, by\ntaking the returned minimum and maximum values into account.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"filter's input_depth dimension must match input's depth dimensions.","name":"filter","typeAttr":"Tfilter"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the lowest quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the highest quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Computes a 2D convolution given quantized 4D input and filter tensors."}},{"name":"QuantizedConv2DAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":11},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DPerChannel","schema":{"attributes":[{"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The quantized type of filter tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The quantized type of output tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"list of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"list of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The minimum value of the input tensor","name":"min_input","type":1},{"description":"The maximum value of the input tensor.","name":"max_input","type":1},{"description":"The minimum value of the filter tensor.","name":"min_filter","type":1},{"description":"The maximum value of the filter tensor.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The minimum value of the final output tensor.","name":"min_output","type":1},{"description":"The maximum value of the final output tensor.","name":"max_output","type":1}],"summary":"Computes QuantizedConv2D per channel."}},{"name":"QuantizedConv2DWithBias","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":11},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSignedSumAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tsummand","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1},{"name":"summand","typeAttr":"Tsummand"},{"name":"min_summand","type":1},{"name":"max_summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSumAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","type":1},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedConv2DWithBiasSumAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tsummand","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"name":"input","typeAttr":"Tinput"},{"name":"filter","typeAttr":"Tfilter"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_input","type":1},{"name":"max_input","type":1},{"name":"min_filter","type":1},{"name":"max_filter","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1},{"name":"summand","typeAttr":"Tsummand"},{"name":"min_summand","type":1},{"name":"max_summand","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"name":"min_output","type":1},{"name":"max_output","type":1}]}},{"name":"QuantizedDepthwiseConv2D","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D."}},{"name":"QuantizedDepthwiseConv2DWithBias","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","type":1},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias."}},{"name":"QuantizedDepthwiseConv2DWithBiasAndRelu","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"default":{"type":"type","value":13},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","type":1},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias and Relu."}},{"name":"QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the filter. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tfilter","type":"type"},{"description":"The type of the bias. Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"The type of the output. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"},{"description":"List of stride values.","name":"strides","type":"int64[]"},{"description":"Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"},{"default":[1,1,1,1],"description":"List of dilation values.","name":"dilations","type":"int64[]"},{"default":[],"name":"padding_list","type":"int64[]"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"Tinput"},{"description":"The original filter tensor.","name":"filter","typeAttr":"Tfilter"},{"description":"The original bias tensor.","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the minimum quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"max_input","type":1},{"description":"The float value that the minimum quantized filter value represents.","name":"min_filter","type":1},{"description":"The float value that the maximum quantized filter value represents.","name":"max_filter","type":1},{"description":"The minimum float value of the output tensor.","name":"min_freezed_output","type":1},{"description":"The maximum float value of the output tensor.","name":"max_freezed_output","type":1}],"outputs":[{"description":"The output tensor.","name":"output","typeAttr":"out_type"},{"description":"The float value that the minimum quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"max_output","type":1}],"summary":"Computes quantized depthwise Conv2D with Bias, Relu and Requantize."}},{"name":"QuantizedInstanceNorm","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":false,"description":"If True, `given_y_min` and `given_y_min`\nand `given_y_max` are used as the output range. Otherwise,\nthe implementation computes the output range.","name":"output_range_given","type":"boolean"},{"default":0,"description":"Output in `y_min` if `output_range_given` is True.","name":"given_y_min","type":"float32"},{"default":0,"description":"Output in `y_max` if `output_range_given` is True.","name":"given_y_max","type":"float32"},{"default":0.000009999999747378752,"description":"A small float number to avoid dividing by 0.","name":"variance_epsilon","type":"float32"},{"default":0.0010000000474974513,"description":"Minimum value of `y_max - y_min`","name":"min_separation","type":"float32"}],"inputs":[{"description":"A 4D input Tensor.","name":"x","typeAttr":"T"},{"description":"The value represented by the lowest quantized input.","name":"x_min","type":1},{"description":"The value represented by the highest quantized input.","name":"x_max","type":1}],"outputs":[{"description":"A 4D Tensor.","name":"y","typeAttr":"T"},{"description":"The value represented by the lowest quantized output.","name":"y_min","type":1},{"description":"The value represented by the highest quantized output.","name":"y_max","type":1}],"summary":"Quantized Instance normalization."}},{"name":"QuantizedMatMul","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":{"type":"type","value":12},"description":"The type of output produced by activation function\nfollowing this operation. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tactivation","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of\n`a` (after being transposed if `transpose_a` is non-zero) must match the\nouter dimension of `b` (after being transposed if `transposed_b` is\nnon-zero).","inputs":[{"description":"Must be a two-dimensional tensor.","name":"a","typeAttr":"T1"},{"description":"Must be a two-dimensional tensor.","name":"b","typeAttr":"T2"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b`."}},{"name":"QuantizedMatMulWithBias","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Performs a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd."}},{"name":"QuantizedMatMulWithBiasAndDequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"description":"Must be one of the following: `float32`.","name":"Toutput","type":"type"},{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"inputs":[{"name":"a","typeAttr":"T1"},{"name":"b","typeAttr":"T2"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_a","type":1},{"name":"max_a","type":1},{"name":"min_b","type":1},{"name":"max_b","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"}]}},{"name":"QuantizedMatMulWithBiasAndRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`. Then do\nrelu activation to get non-negative result.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching with inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","type":1},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd and relu fusion."}},{"name":"QuantizedMatMulWithBiasAndReluAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"description":"If true, `a` is transposed before multiplication.","name":"transpose_a","type":"boolean"},{"default":false,"description":"If true, `b` is transposed before multiplication.","name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Input data quantization mode. Either MIN_FIRST(default) or SCALED. Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"description":"The inputs must be two-dimensional matrices and 1D bias vector. And the inner\ndimension of `a` (after being transposed if `transpose_a` is non-zero) must\nmatch the outer dimension of `b` (after being transposed if `transposed_b` is\nnon-zero). Then do broadcast add operation with bias values on the matrix\nmultiplication result. The bias size must match inner dimension of `b`. Then do\nrelu activation to get non-negative result. Then do requantize operation to get\nfinal uint8 result.","inputs":[{"description":"A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`.","name":"a","typeAttr":"T1"},{"description":"A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`.","name":"b","typeAttr":"T2"},{"description":"A 1D bias tensor with size matching with inner dimension of `b` (after being\ntransposed if `transposed_b` is non-zero).","name":"bias","typeAttr":"Tbias"},{"description":"The float value that the lowest quantized `a` value represents.","name":"min_a","type":1},{"description":"The float value that the highest quantized `a` value represents.","name":"max_a","type":1},{"description":"The float value that the lowest quantized `b` value represents.","name":"min_b","type":1},{"description":"The float value that the highest quantized `b` value represents.","name":"max_b","type":1},{"description":"The float value that the highest quantized output value after requantize.","name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_out","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_out","type":1}],"summary":"Perform a quantized matrix multiplication of `a` by the matrix `b` with bias\nadd and relu and requantize fusion."}},{"name":"QuantizedMatMulWithBiasAndRequantize","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"description":"Must be one of the following: `float32`, `qint32`.","name":"Tbias","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"},{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":"MIN_FIRST","description":"Must be one of the following: `MIN_FIRST`, `SCALED`.","name":"input_quant_mode","type":"string"}],"inputs":[{"name":"a","typeAttr":"T1"},{"name":"b","typeAttr":"T2"},{"name":"bias","typeAttr":"Tbias"},{"name":"min_a","type":1},{"name":"max_a","type":1},{"name":"min_b","type":1},{"name":"max_b","type":1},{"name":"min_freezed_output","type":1},{"name":"max_freezed_output","type":1}],"outputs":[{"name":"out","typeAttr":"Toutput"},{"name":"min_out","type":1},{"name":"max_out","type":1}]}},{"name":"QuantizedMaxPool","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The size of the window for each dimension of the input tensor.\nThe length must be 4 to match the number of dimensions of the input.","name":"ksize","type":"int64[]"},{"description":"The stride of the sliding window for each dimension of the input\ntensor. The length must be 4 to match the number of dimensions of the input.","name":"strides","type":"int64[]"},{"description":"The type of padding algorithm to use. Must be one of the following: `SAME`, `VALID`.","name":"padding","type":"string"}],"inputs":[{"description":"The 4D (batch x rows x cols x depth) Tensor to MaxReduce over.","name":"input","typeAttr":"T"},{"description":"The float value that the lowest quantized input value represents.","name":"min_input","type":1},{"description":"The float value that the highest quantized input value represents.","name":"max_input","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"The float value that the lowest quantized output value represents.","name":"min_output","type":1},{"description":"The float value that the highest quantized output value represents.","name":"max_output","type":1}],"summary":"Produces the max pool of the input tensor for quantized types."}},{"name":"QuantizedMul","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T1","type":"type"},{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T2","type":"type"},{"default":{"type":"type","value":13},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Toutput","type":"type"}],"inputs":[{"name":"x","typeAttr":"T1"},{"name":"y","typeAttr":"T2"},{"description":"The float value that the lowest quantized `x` value represents.","name":"min_x","type":1},{"description":"The float value that the highest quantized `x` value represents.","name":"max_x","type":1},{"description":"The float value that the lowest quantized `y` value represents.","name":"min_y","type":1},{"description":"The float value that the highest quantized `y` value represents.","name":"max_y","type":1}],"outputs":[{"name":"z","typeAttr":"Toutput"},{"description":"The float value that the lowest quantized output value represents.","name":"min_z","type":1},{"description":"The float value that the highest quantized output value represents.\n\n*NOTE*: `QuantizedMul` supports limited forms of broadcasting. More about\nbroadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","name":"max_z","type":1}],"summary":"Returns x * y element-wise, working on quantized buffers."}},{"name":"QuantizedRelu","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear: `max(features, 0)`"}},{"name":"QuantizedRelu6","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)`"}},{"name":"QuantizedReluX","schema":{"attributes":[{"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"default":{"type":"type","value":12},"description":"Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"name":"features","typeAttr":"Tinput"},{"name":"max_value","type":1},{"description":"The float value that the lowest quantized value represents.","name":"min_features","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_features","type":1}],"outputs":[{"description":"Has the same output shape as \"features\".","name":"activations","typeAttr":"out_type"},{"description":"The float value that the lowest quantized value represents.","name":"min_activations","type":1},{"description":"The float value that the highest quantized value represents.","name":"max_activations","type":1}],"summary":"Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)`"}},{"name":"QuantizedReshape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"description":"```","inputs":[{"name":"tensor","typeAttr":"T"},{"description":"Defines the shape of the output tensor.","name":"shape","typeAttr":"Tshape"},{"description":"The minimum value of the input.","name":"input_min","type":1},{"description":"The maximum value of the input.","name":"input_max","type":1}],"outputs":[{"name":"output","typeAttr":"T"},{"description":"This value is copied from input_min.","name":"output_min","type":1},{"description":"This value is copied from input_max.","name":"output_max","type":1}],"summary":"Reshapes a quantized tensor as per the Reshape op."}},{"name":"QuantizedResizeBilinear","schema":{"attributes":[{"description":"Must be one of the following: `quint8`, `qint32`, `float32`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images and output images must be quantized types.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3},{"name":"min","type":1},{"name":"max","type":1}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","typeAttr":"T"},{"name":"out_min","type":1},{"name":"out_max","type":1}],"summary":"Resize quantized `images` to `size` using quantized bilinear interpolation."}},{"name":"QueueClose","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the given queue will be canceled.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more elements will be enqueued in the\ngiven queue. Subsequent Enqueue(Many) operations will fail.\nSubsequent Dequeue(Many) operations will continue to succeed if\nsufficient elements remain in the queue. Subsequent Dequeue(Many)\noperations that would block will fail immediately.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"summary":"Closes the given queue."}},{"name":"QueueCloseV2","schema":{"attributes":[{"default":false,"description":"If true, all pending enqueue requests that are\nblocked on the given queue will be canceled.","name":"cancel_pending_enqueues","type":"boolean"}],"description":"This operation signals that no more elements will be enqueued in the\ngiven queue. Subsequent Enqueue(Many) operations will fail.\nSubsequent Dequeue(Many) operations will continue to succeed if\nsufficient elements remain in the queue. Subsequent Dequeue(Many)\noperations that would block will fail immediately.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"summary":"Closes the given queue."}},{"name":"QueueDequeue","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation has k outputs, where k is the number of components\nin the tuples stored in the given queue, and output i is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until an element\nhas been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues a tuple of one or more tensors from the given queue."}},{"name":"QueueDequeueMany","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"If the queue is closed and there are fewer than `n` elements, then an\nOutOfRange error is returned.\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until `n` elements\nhave been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueManyV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"If the queue is closed and there are fewer than `n` elements, then an\nOutOfRange error is returned.\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until `n` elements\nhave been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueUpTo","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation is not supported by all queues. If a queue does not support\nDequeueUpTo, then an Unimplemented error is returned.\n\nIf the queue is closed and there are more than 0 but less than `n`\nelements remaining, then instead of returning an OutOfRange error like\nQueueDequeueMany, less than `n` elements are returned immediately. If\nthe queue is closed and there are 0 elements left in the queue, then\nan OutOfRange error is returned just like in QueueDequeueMany.\nOtherwise the behavior is identical to QueueDequeueMany:\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size `n` in the 0th dimension.\n\nThis operation has k outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueUpToV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue has fewer than n elements, this operation\nwill block for up to timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation is not supported by all queues. If a queue does not support\nDequeueUpTo, then an Unimplemented error is returned.\n\nIf the queue is closed and there are more than 0 but less than `n`\nelements remaining, then instead of returning an OutOfRange error like\nQueueDequeueMany, less than `n` elements are returned immediately. If\nthe queue is closed and there are 0 elements left in the queue, then\nan OutOfRange error is returned just like in QueueDequeueMany.\nOtherwise the behavior is identical to QueueDequeueMany:\n\nThis operation concatenates queue-element component tensors along the\n0th dimension to make a single component tensor. All of the components\nin the dequeued tuple will have size n in the 0th dimension.\n\nThis operation has `k` outputs, where `k` is the number of components in\nthe tuples stored in the given queue, and output `i` is the ith\ncomponent of the dequeued tuple.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"The number of tuples to dequeue.","name":"n","type":3}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues `n` tuples of one or more tensors from the given queue."}},{"name":"QueueDequeueV2","schema":{"attributes":[{"description":"The type of each component in a tuple.","minimum":1,"name":"component_types","type":"type[]"},{"default":-1,"description":"If the queue is empty, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation has k outputs, where k is the number of components\nin the tuples stored in the given queue, and output i is the ith\ncomponent of the dequeued tuple.\n\nN.B. If the queue is empty, this operation will block until an element\nhas been dequeued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"description":"One or more tensors that were dequeued as a tuple.","name":"components","typeListAttr":"component_types"}],"summary":"Dequeues a tuple of one or more tensors from the given queue."}},{"name":"QueueEnqueue","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is full, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"The components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelement has been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"One or more tensors from which the enqueued tensors should be taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues a tuple of one or more tensors in the given queue."}},{"name":"QueueEnqueueMany","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is too full, this operation will block for up\nto timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation slices each component tensor along the 0th dimension to\nmake multiple queue elements. All of the tuple components must have the\nsame size in the 0th dimension.\n\nThe components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelements have been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7},{"description":"One or more tensors from which the enqueued tensors should\nbe taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues zero or more tuples of one or more tensors in the given queue."}},{"name":"QueueEnqueueManyV2","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is too full, this operation will block for up\nto timeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"This operation slices each component tensor along the 0th dimension to\nmake multiple queue elements. All of the tuple components must have the\nsame size in the 0th dimension.\n\nThe components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelements have been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"One or more tensors from which the enqueued tensors should\nbe taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues zero or more tuples of one or more tensors in the given queue."}},{"name":"QueueEnqueueV2","schema":{"attributes":[{"minimum":1,"name":"Tcomponents","type":"type[]"},{"default":-1,"description":"If the queue is full, this operation will block for up to\ntimeout_ms milliseconds.\nNote: This option is not supported yet.","name":"timeout_ms","type":"int64"}],"description":"The components input has k elements, which correspond to the components of\ntuples stored in the given queue.\n\nN.B. If the queue is full, this operation will block until the given\nelement has been enqueued (or 'timeout_ms' elapses, if specified).","inputs":[{"description":"The handle to a queue.","name":"handle","type":20},{"description":"One or more tensors from which the enqueued tensors should be taken.","name":"components","typeListAttr":"Tcomponents"}],"summary":"Enqueues a tuple of one or more tensors in the given queue."}},{"name":"QueueIsClosed","schema":{"description":"This operation returns true if the queue is closed and false if the queue\nis open.","inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"name":"is_closed","type":10}],"summary":"Returns true if queue is closed."}},{"name":"QueueIsClosedV2","schema":{"description":"This operation returns true if the queue is closed and false if the queue\nis open.","inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"name":"is_closed","type":10}],"summary":"Returns true if queue is closed."}},{"name":"QueueSize","schema":{"inputs":[{"description":"The handle to a queue.","isRef":true,"name":"handle","type":7}],"outputs":[{"description":"The number of elements in the given queue.","name":"size","type":3}],"summary":"Computes the number of elements in the given queue."}},{"name":"QueueSizeV2","schema":{"inputs":[{"description":"The handle to a queue.","name":"handle","type":20}],"outputs":[{"description":"The number of elements in the given queue.","name":"size","type":3}],"summary":"Computes the number of elements in the given queue."}},{"name":"RFFT","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 1-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most dimension of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the\n`fft_length / 2 + 1` unique components of the FFT: the zero-frequency term,\nfollowed by the `fft_length / 2` positive-frequency terms.\n\nAlong the axis `RFFT` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [1]. The FFT length.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length / 2 + 1` unique\n frequency components of its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"Real-valued fast Fourier transform."}},{"name":"RFFT2D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 2-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 2 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the\n`fft_length / 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length / 2`\npositive-frequency terms.\n\nAlong each axis `RFFT2D` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [2]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform. The\n inner-most dimension contains `fft_length / 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft2\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"2D real-valued fast Fourier transform."}},{"name":"RFFT3D","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Treal","type":"type"},{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"Tcomplex","type":"type"}],"description":"Computes the 3-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 3 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the\n`fft_length / 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length / 2`\npositive-frequency terms.\n\nAlong each axis `RFFT3D` is computed on, if `fft_length` is smaller than the\ncorresponding dimension of `input`, the dimension is cropped. If it is larger,\nthe dimension is padded with zeros.","inputs":[{"description":"A float32 tensor.","name":"input","typeAttr":"Treal"},{"description":"An int32 tensor of shape [3]. The FFT length for each dimension.","name":"fft_length","type":3}],"outputs":[{"description":"A complex64 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the their 3D Fourier transform. The\n inner-most dimension contains `fft_length / 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfftn with 3 dimensions.\n@end_compatibility","name":"output","typeAttr":"Tcomplex"}],"summary":"3D real-valued fast Fourier transform."}},{"name":"RGBToHSV","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Outputs a tensor of the same shape as the `images` tensor, containing the HSV\nvalue of the pixels. The output is only well defined if the value in `images`\nare in `[0,1]`.\n\n`output[..., 0]` contains hue, `output[..., 1]` contains saturation, and\n`output[..., 2]` contains value. All HSV values are in `[0,1]`. A hue of 0\ncorresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue.\n\nUsage Example:\n\n>>> blue_image = tf.stack([\n... tf.zeros([5,5]),\n... tf.zeros([5,5]),\n... tf.ones([5,5])],\n... axis=-1)\n>>> blue_hsv_image = tf.image.rgb_to_hsv(blue_image)\n>>> blue_hsv_image[0,0].numpy()\narray([0.6666667, 1. , 1. ], dtype=float32)\n","inputs":[{"description":"1-D or higher rank. RGB data to convert. Last dimension must be size 3.","name":"images","typeAttr":"T"}],"outputs":[{"description":"`images` converted to HSV.","name":"output","typeAttr":"T"}],"summary":"Converts one or more images from RGB to HSV."}},{"name":"RaggedBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"1D int64 `Tensor`.","name":"splits","type":9},{"description":"2D int `Tensor`.","name":"values","typeAttr":"Tidx"},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `input`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"RaggedCountSparseOutput","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing the row splits of the ragged tensor to count.","name":"splits","type":9},{"description":"Tensor containing values of the sparse tensor to count.","name":"values","typeAttr":"T"},{"description":"A Tensor of the same shape as indices containing per-index weight values.\nMay also be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.\n END\n }\n attr {\n name: \"T\"\n description: <\n```\n\nThe input tensors `starts`, `limits`, and `deltas` may be scalars or vectors.\nThe vector inputs must all have the same size. Scalar inputs are broadcast\nto match the size of the vector inputs.","inputs":[{"description":"The starts of each range.","name":"starts","typeAttr":"T"},{"description":"The limits of each range.","name":"limits","typeAttr":"T"},{"description":"The deltas of each range.","name":"deltas","typeAttr":"T"}],"outputs":[{"description":"The `row_splits` for the returned `RaggedTensor`.","name":"rt_nested_splits","typeAttr":"Tsplits"},{"description":"The `flat_values` for the returned `RaggedTensor`.","name":"rt_dense_values","typeAttr":"T"}],"summary":"Returns a `RaggedTensor` containing the specified sequences of numbers."}},{"name":"RaggedTensorFromVariant","schema":{"attributes":[{"description":"The ragged rank of each encoded `RaggedTensor` component in the input. If set to\n-1, this is inferred as `output_ragged_rank` - `rank(encoded_ragged)`","minimum":-1,"name":"input_ragged_rank","type":"int64"},{"description":"The expected ragged rank of the output `RaggedTensor`. The following must hold:\n`output_ragged_rank = rank(encoded_ragged) + input_ragged_rank`.","minimum":0,"name":"output_ragged_rank","type":"int64"},{"name":"Tvalues","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"Decodes the given `variant` Tensor and returns a `RaggedTensor`. The input\ncould be a scalar, meaning it encodes a single `RaggedTensor` with ragged_rank\n`output_ragged_rank`. It could also have an arbitrary rank, in which case each\nelement is decoded into a `RaggedTensor` with ragged_rank `input_ragged_rank`\nand these are then stacked according to the input shape to output a single\n`RaggedTensor` with ragged_rank `output_ragged_rank`. Each `variant` element in\nthe input Tensor is decoded by retrieving from the element a 1-D `variant`\nTensor with `input_ragged_rank + 1` Tensors, corresponding to the splits and\nvalues of the decoded `RaggedTensor`. If `input_ragged_rank` is -1, then it is\ninferred as `output_ragged_rank` - `rank(encoded_ragged)`. See\n`RaggedTensorToVariant` for the corresponding encoding logic.\n","inputs":[{"description":"A `variant` Tensor containing encoded `RaggedTensor`s.","name":"encoded_ragged","type":21}],"outputs":[{"description":"A list of one or more Tensors representing the splits of the output\n`RaggedTensor`.","name":"output_nested_splits","numberAttr":"output_ragged_rank","typeAttr":"Tsplits"},{"description":"A Tensor representing the values of the output `RaggedTensor`.","name":"output_dense_values","typeAttr":"Tvalues"}],"summary":"Decodes a `variant` Tensor into a `RaggedTensor`."}},{"name":"RaggedTensorToSparse","schema":{"attributes":[{"description":"The ragged rank of the input RaggedTensor. `rt_nested_splits` should contain\nthis number of ragged-splits tensors. This value should equal\n`input.ragged_rank`.","minimum":1,"name":"RAGGED_RANK","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"input=ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits)\noutput=SparseTensor(indices=sparse_indices, values=sparse_values,\n dense_shape=sparse_dense_shape)","inputs":[{"description":"The `row_splits` for the `RaggedTensor`.","name":"rt_nested_splits","numberAttr":"RAGGED_RANK","typeAttr":"Tsplits"},{"description":"The `flat_values` for the `RaggedTensor`.","name":"rt_dense_values","typeAttr":"T"}],"outputs":[{"description":"The indices for the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"The values of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"`sparse_dense_shape` is a tight bounding box of the input `RaggedTensor`.","name":"sparse_dense_shape","type":9}],"summary":"Converts a `RaggedTensor` into a `SparseTensor` with the same values."}},{"name":"RaggedTensorToTensor","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int64`, `int32`.","name":"Tindex","type":"type"},{"description":"Must be one of the following: `int64`, `int32`.","name":"Tshape","type":"type"},{"minimum":1,"name":"num_row_partition_tensors","type":"int64"},{"description":"The types of the row partition tensors. At present, these can be:\n* \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n* \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n* \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceeded by \"FIRST_DIM_SIZE\".\nThe tensors are in the order of the dimensions.","name":"row_partition_types","type":"string[]"}],"description":"The `ragged_to_dense` op creates a dense tensor from a list of row partition\ntensors, a value vector, and default values. If the shape is unspecified, the\nminimal shape required to contain all the elements in the ragged tensor (the\nnatural shape) will be used. If some dimensions are left unspecified, then the\nsize of the natural shape is used in that dimension.\n\nThe default_value will be broadcast to the output shape. After that, the values\nfrom the ragged tensor overwrite the default values. Note that the default_value\nmust have less dimensions than the value.\n\nThe row partition tensors are in the order of the dimensions.\nAt present, the types can be:\n* \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n* \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n* \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n is preceded by \"FIRST_DIM_SIZE\".","inputs":[{"description":"The desired shape of the the output tensor. If left unspecified (empty),\nthe minimal shape required to contain all the elements in the ragged tensor\n(the natural shape) will be used. If some dimensions are left unspecified, then\nthe size of the natural shape is used in that dimension.\n\nNote that dense dimensions cannot be modified by the shape argument. Trying to\nchange the size of a dense dimension will cause the op to fail.\nExamples:\nnatural shape: [4, 5, 6]\nshape: -1\noutput shape: [4, 5, 6]\n\nnatural shape: [4, 5, 6]\nshape: [3, -1, 2]\noutput shape: [3, 5, 2]\n\nnatural shape: [4, 5, 6]\nshape: [3, 7, 2]\noutput shape: [3, 7, 2]\n","name":"shape","typeAttr":"Tshape"},{"description":"A 1D tensor representing the values of the ragged tensor.","name":"values","typeAttr":"T"},{"description":"The default_value when the shape is larger than the ragged tensor. The\ndefault_value is broadcast until it is the shape of the output tensor, and\nthen overwritten by values in the ragged tensor. The default value must be\ncompatible with this broadcast operation, and must have fewer dimensions than\nthe value tensor.","name":"default_value","typeAttr":"T"},{"name":"row_partition_tensors","numberAttr":"num_row_partition_tensors","typeAttr":"Tindex"}],"outputs":[{"description":"The resulting dense tensor.","name":"result","typeAttr":"T"}],"summary":"Create a dense tensor from a ragged tensor, possibly altering its shape."}},{"name":"RaggedTensorToVariant","schema":{"attributes":[{"minimum":0,"name":"RAGGED_RANK","type":"int64"},{"name":"Tvalues","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"},{"description":"A `bool` denoting whether the input is a batched `RaggedTensor`.","name":"batched_input","type":"boolean"}],"description":"\nEncodes the given `RaggedTensor` and returns a `variant` Tensor. If\n`batched_input` is True, then input `RaggedTensor` is unbatched along the\nzero-th dimension, each component `RaggedTensor` is encoded into a scalar\n`variant` Tensor, and these are stacked to return a 1-D `variant` Tensor.\nIf `batched_input` is False, then the input `RaggedTensor` is encoded as is and\na scalar `variant` Tensor is returned. A `RaggedTensor` is encoded by first\ncreating a 1-D `variant` Tensor with `ragged_rank + 1` elements, containing the\nsplits and values Tensors of the `RaggedTensor`. Then the 1-D `variant` Tensor\nis wrapped in a scalar `variant` Tensor. See `RaggedTensorFromVariant` for the\ncorresponding decoding logic.\n","inputs":[{"description":"A list of one or more Tensors representing the splits of the input\n`RaggedTensor`.","name":"rt_nested_splits","numberAttr":"RAGGED_RANK","typeAttr":"Tsplits"},{"description":"A Tensor representing the values of the input `RaggedTensor`.","name":"rt_dense_values","typeAttr":"Tvalues"}],"outputs":[{"description":"A `variant` Tensor that containing encoded `RaggedTensor`.","name":"encoded_ragged","type":21}],"summary":"Encodes a `RaggedTensor` into a `variant` Tensor."}},{"name":"RandomCrop","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"`size` is a 1-D int64 tensor with 2 elements representing the crop height and\nwidth. The values must be non negative.\n\nThis Op picks a random location in `image` and crops a `height` by `width`\nrectangle from that location. The random location is picked so the cropped\narea will fit inside the original image.","inputs":[{"description":"3-D of shape `[height, width, channels]`.","name":"image","typeAttr":"T"},{"description":"1-D of length 2 containing: `crop_height`, `crop_width`..","name":"size","type":9}],"outputs":[{"description":"3-D of shape `[crop_height, crop_width, channels].`","name":"output","typeAttr":"T"}],"summary":"Randomly crop `image`."}},{"name":"RandomDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a Dataset that returns a stream of uniformly distributed\npseudorandom 64-bit signed integers.\n\nIn the TensorFlow Python API, you can instantiate this dataset via the\nclass `tf.data.experimental.RandomDataset`.\n\nInstances of this dataset are also created as a result of the\n`hoist_random_uniform` static optimization. Whether this optimization is\nperformed is determined by the `experimental_optimization.hoist_random_uniform`\noption of `tf.data.Options`.","inputs":[{"description":"A scalar seed for the random number generator. If either seed or\nseed2 is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a Dataset that returns pseudorandom numbers."}},{"name":"RandomGamma","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"This op uses the algorithm by Marsaglia et al. to acquire samples via\ntransformation-rejection from pairs of uniform and normal random variables.\nSee http://dl.acm.org/citation.cfm?id=358414","inputs":[{"description":"1-D integer tensor. Shape of independent samples to draw from each\ndistribution described by the shape parameters given in alpha.","name":"shape","typeAttr":"S"},{"description":"A tensor in which each scalar is a \"shape\" parameter describing the\nassociated gamma distribution.","name":"alpha","typeAttr":"T"}],"outputs":[{"description":"A tensor with shape `shape + shape(alpha)`. Each slice\n`[:, ..., :, i0, i1, ...iN]` contains the samples drawn for\n`alpha[i0, i1, ...iN]`. The dtype of the output matches the dtype of alpha.","name":"output","typeAttr":"T"}],"summary":"Outputs random values from the Gamma distribution(s) described by alpha."}},{"name":"RandomGammaGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"alpha","typeAttr":"T"},{"name":"sample","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes the derivative of a Gamma random sample w.r.t. `alpha`."}},{"name":"RandomPoisson","schema":{"attributes":[{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"description":"Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"}],"inputs":[{"name":"shape","typeAttr":"S"},{"name":"rate","typeAttr":"dtype"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Use RandomPoissonV2 instead."}},{"name":"RandomPoissonV2","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"R","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"description":"This op uses two algorithms, depending on rate. If rate >= 10, then\nthe algorithm by Hormann is used to acquire samples via\ntransformation-rejection.\nSee http://www.sciencedirect.com/science/article/pii/0167668793909974.\n\nOtherwise, Knuth's algorithm is used to acquire samples via multiplying uniform\nrandom variables.\nSee Donald E. Knuth (1969). Seminumerical Algorithms. The Art of Computer\nProgramming, Volume 2. Addison Wesley","inputs":[{"description":"1-D integer tensor. Shape of independent samples to draw from each\ndistribution described by the shape parameters given in rate.","name":"shape","typeAttr":"S"},{"description":"A tensor in which each scalar is a \"rate\" parameter describing the\nassociated poisson distribution.","name":"rate","typeAttr":"R"}],"outputs":[{"description":"A tensor with shape `shape + shape(rate)`. Each slice\n`[:, ..., :, i0, i1, ...iN]` contains the samples drawn for\n`rate[i0, i1, ...iN]`.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from the Poisson distribution(s) described by rate."}},{"name":"RandomShuffle","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"name":"T","type":"type"}],"description":" The tensor is shuffled along dimension 0, such that each `value[j]` is mapped\n to one and only one `output[i]`. For example, a mapping that might occur for a\n 3x2 tensor is:\n\n```\n[[1, 2], [[5, 6],\n [3, 4], ==> [1, 2],\n [5, 6]] [3, 4]]\n```","inputs":[{"description":"The tensor to be shuffled.","name":"value","typeAttr":"T"}],"outputs":[{"description":"A tensor of same shape and type as `value`, shuffled along its first\ndimension.","name":"output","typeAttr":"T"}],"summary":"Randomly shuffles a tensor along its first dimension."}},{"name":"RandomShuffleQueue","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":0,"description":"Dequeue will block unless there would be this\nmany elements after the dequeue or the queue is closed. This\nensures a minimum level of mixing of elements.","name":"min_after_dequeue","type":"int64"},{"default":0,"description":"If either seed or seed2 is set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","isRef":true,"name":"handle","type":7}],"summary":"A queue that randomizes the order of elements."}},{"name":"RandomShuffleQueueV2","schema":{"attributes":[{"description":"The type of each component in a value.","minimum":1,"name":"component_types","type":"type[]"},{"default":[],"description":"The shape of each component in a value. The length of this attr must\nbe either 0 or the same as the length of component_types. If the length of\nthis attr is 0, the shapes of queue elements are not constrained, and\nonly one element may be dequeued at a time.","minimum":0,"name":"shapes","type":"shape[]"},{"default":-1,"description":"The upper bound on the number of elements in this queue.\nNegative numbers mean no limit.","name":"capacity","type":"int64"},{"default":0,"description":"Dequeue will block unless there would be this\nmany elements after the dequeue or the queue is closed. This\nensures a minimum level of mixing of elements.","name":"min_after_dequeue","type":"int64"},{"default":0,"description":"If either seed or seed2 is set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, a random seed is used.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":"","description":"If non-empty, this queue is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this queue will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to the queue.","name":"handle","type":20}],"summary":"A queue that randomizes the order of elements."}},{"name":"RandomStandardNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution."}},{"name":"RandomUniform","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with uniform random values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a uniform distribution."}},{"name":"RandomUniformInt","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tout","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values are uniform integers in the range `[minval, maxval)`.\nThe lower bound `minval` is included in the range, while the upper bound\n`maxval` is excluded.\n\nThe random integers are slightly biased unless `maxval - minval` is an exact\npower of two. The bias is small for values of `maxval - minval` significantly\nsmaller than the range of the output (either `2^32` or `2^64`).","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"0-D. Inclusive lower bound on the generated integers.","name":"minval","typeAttr":"Tout"},{"description":"0-D. Exclusive upper bound on the generated integers.","name":"maxval","typeAttr":"Tout"}],"outputs":[{"description":"A tensor of the specified shape filled with uniform random integers.","name":"output","typeAttr":"Tout"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"Range","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"This operation creates a sequence of numbers that begins at `start` and\nextends by increments of `delta` up to but not including `limit`.\n\nFor example:\n\n```\n# 'start' is 3\n# 'limit' is 18\n# 'delta' is 3\ntf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]\n```","inputs":[{"description":"0-D (scalar). First entry in the sequence.","name":"start","typeAttr":"Tidx"},{"description":"0-D (scalar). Upper limit of sequence, exclusive.","name":"limit","typeAttr":"Tidx"},{"description":"0-D (scalar). Optional. Default is 1. Number that increments `start`.","name":"delta","typeAttr":"Tidx"}],"outputs":[{"description":"1-D.","name":"output","typeAttr":"Tidx"}],"summary":"Creates a sequence of numbers."}},{"name":"RangeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"corresponds to start in python's xrange().","name":"start","type":9},{"description":"corresponds to stop in python's xrange().","name":"stop","type":9},{"description":"corresponds to step in python's xrange().","name":"step","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset with a range of values. Corresponds to python's xrange."}},{"name":"Rank","schema":{"attributes":[{"name":"T","type":"type"}],"description":"This operation returns an integer representing the rank of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\n# shape of tensor 't' is [2, 2, 3]\nrank(t) ==> 3\n```\n\n**Note**: The rank of a tensor is not the same as the rank of a matrix. The rank\nof a tensor is the number of indices required to uniquely select each element\nof the tensor. Rank is also known as \"order\", \"degree\", or \"ndims.\"","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":3}],"summary":"Returns the rank of a tensor."}},{"name":"ReadFile","schema":{"inputs":[{"name":"filename","type":7}],"outputs":[{"name":"contents","type":7}],"summary":"Reads and outputs the entire contents of the input filename."}},{"name":"ReadVariableOp","schema":{"attributes":[{"description":"the dtype of the value.","name":"dtype","type":"type"}],"description":"The tensor returned by this operation is immutable.\n\nThe value returned by this operation is guaranteed to be influenced by all the\nwrites on which this operation depends directly or indirectly, and to not be\ninfluenced by any of the writes which depend directly or indirectly on this\noperation.","inputs":[{"description":"handle to the resource in which to store the variable.","name":"resource","type":20}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Reads the value of a variable."}},{"name":"ReaderNumRecordsProduced","schema":{"description":"This is the same as the number of ReaderRead executions that have\nsucceeded.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"records_produced","type":9}],"summary":"Returns the number of records this Reader has produced."}},{"name":"ReaderNumRecordsProducedV2","schema":{"description":"This is the same as the number of ReaderRead executions that have\nsucceeded.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"records_produced","type":9}],"summary":"Returns the number of records this Reader has produced."}},{"name":"ReaderNumWorkUnitsCompleted","schema":{"inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"units_completed","type":9}],"summary":"Returns the number of work units this Reader has finished processing."}},{"name":"ReaderNumWorkUnitsCompletedV2","schema":{"inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"units_completed","type":9}],"summary":"Returns the number of work units this Reader has finished processing."}},{"name":"ReaderRead","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7},{"description":"Handle to a Queue, with string work items.","isRef":true,"name":"queue_handle","type":7}],"outputs":[{"description":"A scalar.","name":"key","type":7},{"description":"A scalar.","name":"value","type":7}],"summary":"Returns the next record (key, value pair) produced by a Reader."}},{"name":"ReaderReadUpTo","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).\nIt may return less than `num_records` even before the last batch.","inputs":[{"description":"Handle to a `Reader`.","isRef":true,"name":"reader_handle","type":7},{"description":"Handle to a `Queue`, with string work items.","isRef":true,"name":"queue_handle","type":7},{"description":"number of records to read from `Reader`.","name":"num_records","type":9}],"outputs":[{"description":"A 1-D tensor.","name":"keys","type":7},{"description":"A 1-D tensor.","name":"values","type":7}],"summary":"Returns up to `num_records` (key, value) pairs produced by a Reader."}},{"name":"ReaderReadUpToV2","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).\nIt may return less than `num_records` even before the last batch.","inputs":[{"description":"Handle to a `Reader`.","name":"reader_handle","type":20},{"description":"Handle to a `Queue`, with string work items.","name":"queue_handle","type":20},{"description":"number of records to read from `Reader`.","name":"num_records","type":9}],"outputs":[{"description":"A 1-D tensor.","name":"keys","type":7},{"description":"A 1-D tensor.","name":"values","type":7}],"summary":"Returns up to `num_records` (key, value) pairs produced by a Reader."}},{"name":"ReaderReadV2","schema":{"description":"Will dequeue from the input queue if necessary (e.g. when the\nReader needs to start reading from a new file since it has finished\nwith the previous file).","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20},{"description":"Handle to a Queue, with string work items.","name":"queue_handle","type":20}],"outputs":[{"description":"A scalar.","name":"key","type":7},{"description":"A scalar.","name":"value","type":7}],"summary":"Returns the next record (key, value pair) produced by a Reader."}},{"name":"ReaderReset","schema":{"inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"Restore a Reader to its initial clean state."}},{"name":"ReaderResetV2","schema":{"inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"summary":"Restore a Reader to its initial clean state."}},{"name":"ReaderRestoreState","schema":{"description":"Not all Readers support being restored, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7},{"description":"Result of a ReaderSerializeState of a Reader with type\nmatching reader_handle.","name":"state","type":7}],"summary":"Restore a reader to a previously saved state."}},{"name":"ReaderRestoreStateV2","schema":{"description":"Not all Readers support being restored, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20},{"description":"Result of a ReaderSerializeState of a Reader with type\nmatching reader_handle.","name":"state","type":7}],"summary":"Restore a reader to a previously saved state."}},{"name":"ReaderSerializeState","schema":{"description":"Not all Readers support being serialized, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","isRef":true,"name":"reader_handle","type":7}],"outputs":[{"name":"state","type":7}],"summary":"Produce a string tensor that encodes the state of a Reader."}},{"name":"ReaderSerializeStateV2","schema":{"description":"Not all Readers support being serialized, so this can produce an\nUnimplemented error.","inputs":[{"description":"Handle to a Reader.","name":"reader_handle","type":20}],"outputs":[{"name":"state","type":7}],"summary":"Produce a string tensor that encodes the state of a Reader."}},{"name":"Real","schema":{"attributes":[{"default":{"type":"type","value":8},"description":"Must be one of the following: `complex64`, `complex128`.","name":"T","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`.","name":"Tout","type":"type"}],"description":"Given a tensor `input` of complex numbers, this operation returns a tensor of\ntype `float` that is the real part of each element in `input`. All elements in\n`input` must be complex numbers of the form \\\\(a + bj\\\\), where *a* is the real\n part returned by this operation and *b* is the imaginary part.\n\nFor example:\n\n```\n# tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j]\ntf.real(input) ==> [-2.25, 3.25]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"Tout"}],"summary":"Returns the real part of a complex number."}},{"name":"RealDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"If `x` and `y` are reals, this will return the floating-point division.\n\n*NOTE*: `Div` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise for real types."}},{"name":"RebatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_fallback","type":"boolean"}],"description":"Creates a dataset that changes the batch size of the dataset to current batch\nsize // num_workers.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A scalar representing the number of replicas to distribute this batch across. As\na result of this transformation the current batch size would end up being\ndivided by this parameter.","name":"num_replicas","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"RebatchDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"Creates a dataset that rebatches elements from `input_dataset` into new batch\nsizes.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A vector of integers representing the size of batches to produce. These values\nare cycled through in order.","name":"batch_sizes","type":9},{"name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that changes the batch size."}},{"name":"Reciprocal","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / x\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes the reciprocal of x element-wise."}},{"name":"ReciprocalGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the inverse of `x` wrt its input."}},{"name":"RecordInput","schema":{"attributes":[{"description":"Glob pattern for the data files.","name":"file_pattern","type":"string"},{"default":301,"description":"Random seeds used to produce randomized records.","name":"file_random_seed","type":"int64"},{"default":0,"description":"Shifts the list of files after the list is randomly\nshuffled.","name":"file_shuffle_shift_ratio","type":"float32"},{"default":10000,"description":"The randomization shuffling buffer.","name":"file_buffer_size","type":"int64"},{"default":16,"description":"How many sstables are opened and concurrently iterated over.","name":"file_parallelism","type":"int64"},{"default":32,"description":"The batch size.","name":"batch_size","type":"int64"},{"default":"","description":"The type of compression for the file. Currently ZLIB and\nGZIP are supported. Defaults to none.","name":"compression_type","type":"string"}],"outputs":[{"description":"A tensor of shape [batch_size].","name":"records","type":7}],"summary":"Emits randomized records."}},{"name":"Recv","schema":{"attributes":[{"name":"tensor_type","type":"type"},{"description":"The name of the tensor to receive.","name":"tensor_name","type":"string"},{"description":"The name of the device sending the tensor.","name":"send_device","type":"string"},{"description":"The current incarnation of send_device.","name":"send_device_incarnation","type":"int64"},{"description":"The name of the device receiving the tensor.","name":"recv_device","type":"string"},{"default":false,"description":"If set to true, this indicates that the node was added\nto the graph as a result of a client-side feed or fetch of Tensor data,\nin which case the corresponding send or recv is expected to be managed\nlocally by the caller.","name":"client_terminated","type":"boolean"}],"outputs":[{"description":"The tensor to receive.","name":"tensor","typeAttr":"tensor_type"}],"summary":"Receives the named tensor from send_device on recv_device."}},{"name":"RecvTPUEmbeddingActivations","schema":{"attributes":[{"description":"The number of output activation tensors, equal to the number of\nembedding tables in the model.","minimum":1,"name":"num_outputs","type":"int64"},{"description":"Serialized TPUEmbeddingConfiguration proto.","name":"config","type":"string"}],"description":"The TPU system performs the embedding lookups and aggregations specified by\nthe arguments to TPUEmbeddingEnqueue(Integer/Sparse/SparseTensor)Batch. The\nresults of these aggregations are visible to the Tensorflow Graph as the\noutputs of a RecvTPUEmbeddingActivations op. This op returns a list containing\none Tensor of activations per table specified in the model. There can be at\nmost one RecvTPUEmbeddingActivations op in the TPU graph.","outputs":[{"description":"A TensorList of embedding activations containing one Tensor per\nembedding table in the model.","name":"outputs","numberAttr":"num_outputs","type":1}],"summary":"An op that receives embedding activations on the TPU."}},{"name":"ReduceDataset","schema":{"attributes":[{"description":"A function that maps `(old_state, input_element)` to `new_state`. It must take\ntwo arguments and return a nested structures of tensors. The structure of\n`new_state` must match the structure of `initial_state`.","name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"use_inter_op_parallelism","type":"boolean"}],"inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"A nested structure of tensors, representing the initial state of the\ntransformation.","name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Reduces the input dataset to a singleton using a reduce function."}},{"name":"ReduceJoin","schema":{"attributes":[{"default":false,"description":"If `True`, retain reduced dimensions with length `1`.","name":"keep_dims","type":"boolean"},{"default":"","description":"The separator to use when joining.","name":"separator","type":"string"}],"description":"Computes the string join across dimensions in the given string Tensor of shape\n`[\\\\(d_0, d_1, ..., d_{n-1}\\\\)]`. Returns a new Tensor created by joining the input\nstrings with the given separator (default: empty string). Negative indices are\ncounted backwards from the end, with `-1` being equivalent to `n - 1`. If\nindices are not specified, joins across all dimensions beginning from `n - 1`\nthrough `0`.\n\nFor example:\n\n```python\n# tensor `a` is [[\"a\", \"b\"], [\"c\", \"d\"]]\ntf.reduce_join(a, 0) ==> [\"ac\", \"bd\"]\ntf.reduce_join(a, 1) ==> [\"ab\", \"cd\"]\ntf.reduce_join(a, -2) = tf.reduce_join(a, 0) ==> [\"ac\", \"bd\"]\ntf.reduce_join(a, -1) = tf.reduce_join(a, 1) ==> [\"ab\", \"cd\"]\ntf.reduce_join(a, 0, keep_dims=True) ==> [[\"ac\", \"bd\"]]\ntf.reduce_join(a, 1, keep_dims=True) ==> [[\"ab\"], [\"cd\"]]\ntf.reduce_join(a, 0, separator=\".\") ==> [\"a.c\", \"b.d\"]\ntf.reduce_join(a, [0, 1]) ==> \"acbd\"\ntf.reduce_join(a, [1, 0]) ==> \"abcd\"\ntf.reduce_join(a, []) ==> [[\"a\", \"b\"], [\"c\", \"d\"]]\ntf.reduce_join(a) = tf.reduce_join(a, [1, 0]) ==> \"abcd\"\n```","inputs":[{"description":"The input to be joined. All reduced indices must have non-zero size.","name":"inputs","type":7},{"description":"The dimensions to reduce over. Dimensions are reduced in the\norder specified. Omitting `reduction_indices` is equivalent to passing\n`[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported.","name":"reduction_indices","type":3}],"outputs":[{"description":"Has shape equal to that of the input with reduced dimensions removed or\nset to `1` depending on `keep_dims`.","name":"output","type":7}],"summary":"Joins a string Tensor across the given dimensions."}},{"name":"RefEnter","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the child frame.","name":"frame_name","type":"string"},{"default":false,"description":"If true, the output is constant within the child frame.","name":"is_constant","type":"boolean"},{"default":10,"description":"The number of iterations allowed to run in parallel.","name":"parallel_iterations","type":"int64"}],"description":"The unique `frame_name` is used by the `Executor` to identify frames. If\n`is_constant` is true, `output` is a constant in the child frame; otherwise\nit may be changed in the child frame. At most `parallel_iterations` iterations\nare run in parallel in the child frame.","inputs":[{"description":"The tensor to be made available to the child frame.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Creates or finds a child frame, and makes `data` available to the child frame."}},{"name":"RefExit","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Exit makes its input `data` available to the parent frame.","inputs":[{"description":"The tensor to be made available to the parent frame.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Exits the current frame to its parent frame."}},{"name":"RefIdentity","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"input","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output","typeAttr":"T"}],"summary":"Return the same ref tensor as the input ref tensor."}},{"name":"RefMerge","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"description":"`Merge` waits for at least one of the tensors in `inputs` to become available.\nIt is usually combined with `Switch` to implement branching.\n\n`Merge` forwards the first tensor for become available to `output`, and sets\n`value_index` to its index in `inputs`.","inputs":[{"description":"The input tensors, exactly one of which will become available.","isRef":true,"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"Will be set to the available input tensor.","isRef":true,"name":"output","typeAttr":"T"},{"description":"The index of the chosen input tensor in `inputs`.","name":"value_index","type":3}],"summary":"Forwards the value of an available tensor from `inputs` to `output`."}},{"name":"RefNextIteration","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The tensor to be made available to the next iteration.","isRef":true,"name":"data","typeAttr":"T"}],"outputs":[{"description":"The same tensor as `data`.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Makes its input available to the next iteration."}},{"name":"RefSelect","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"N","type":"int64"}],"inputs":[{"description":"A scalar that determines the input that gets selected.","name":"index","type":3},{"description":"A list of ref tensors, one of which will be forwarded to `output`.","isRef":true,"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"The forwarded tensor.","isRef":true,"name":"output","typeAttr":"T"}],"summary":"Forwards the `index`th element of `inputs` to `output`."}},{"name":"RefSwitch","schema":{"attributes":[{"name":"T","type":"type"}],"description":"If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise,\nthe data goes to `output_false`.\n\nSee also `Switch` and `Merge`.","inputs":[{"description":"The ref tensor to be forwarded to the appropriate output.","isRef":true,"name":"data","typeAttr":"T"},{"description":"A scalar that specifies which output port will receive data.","name":"pred","type":10}],"outputs":[{"description":"If `pred` is false, data will be forwarded to this output.","isRef":true,"name":"output_false","typeAttr":"T"},{"description":"If `pred` is true, data will be forwarded to this output.","isRef":true,"name":"output_true","typeAttr":"T"}],"summary":"Forwards the ref tensor `data` to the output port determined by `pred`."}},{"name":"RegexFullMatch","schema":{"description":"The input is a string tensor of any shape. The pattern is a scalar\nstring tensor which is applied to every element of the input tensor.\nThe boolean values (True or False) of the output tensor indicate\nif the input matches the regex pattern provided.\n\nThe pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)\n\nExamples:\n\n>>> tf.strings.regex_full_match([\"TF lib\", \"lib TF\"], \".*lib$\")\n\n>>> tf.strings.regex_full_match([\"TF lib\", \"lib TF\"], \".*TF$\")\n","inputs":[{"description":"A string tensor of the text to be processed.","name":"input","type":7},{"description":"A scalar string tensor containing the regular expression to match the input.","name":"pattern","type":7}],"outputs":[{"description":"A bool tensor with the same shape as `input`.","name":"output","type":10}],"summary":"Check if the input matches the regex pattern."}},{"name":"RegexReplace","schema":{"attributes":[{"default":true,"description":"If True, the replacement is global (that is, all matches of the `pattern` regular\nexpression in each input string are rewritten), otherwise the `rewrite`\nsubstitution is only made for the first `pattern` match.","name":"replace_global","type":"boolean"}],"description":"It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"The text to be processed.","name":"input","type":7},{"description":"The regular expression to be matched in the `input` strings.","name":"pattern","type":7},{"description":"The rewrite string to be substituted for the `pattern` expression where it is\nmatched in the `input` strings.","name":"rewrite","type":7}],"outputs":[{"description":"The text after applying pattern match and rewrite substitution.","name":"output","type":7}],"summary":"Replaces matches of the `pattern` regular expression in `input` with the\nreplacement string provided in `rewrite`."}},{"name":"RegisterDataset","schema":{"attributes":[{"name":"external_state_policy","type":"int64"}],"inputs":[{"name":"dataset","type":21},{"name":"address","type":7},{"name":"protocol","type":7}],"outputs":[{"name":"dataset_id","type":9}],"summary":"Registers a dataset with the tf.data service."}},{"name":"Relu","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`, `qint8`.","name":"T","type":"type"}],"category":"Activation","description":"See: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)\nExample usage:\n>>> tf.nn.relu([-2., 0., -0., 3.]).numpy()\narray([ 0., 0., -0., 3.], dtype=float32)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear: `max(features, 0)`."}},{"name":"Relu6","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"category":"Activation","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes rectified linear 6: `min(max(features, 0), 6)`."}},{"name":"Relu6Grad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Relu6 operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding Relu6 operation, or\nits output; using either one produces the same result.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients:\n`gradients * (features > 0) * (features < 6)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear 6 gradients for a Relu6 operation."}},{"name":"ReluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Relu operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding Relu operation, OR\nthe outputs of that operation (both work equivalently).","name":"features","typeAttr":"T"}],"outputs":[{"description":"`gradients * (features > 0)`.","name":"backprops","typeAttr":"T"}],"summary":"Computes rectified linear gradients for a Relu operation."}},{"name":"RemoteCall","schema":{"attributes":[{"description":"The type list for the arguments.","minimum":1,"name":"Tin","type":"type[]"},{"description":"The type list for the return values.","minimum":1,"name":"Tout","type":"type[]"},{"description":"The function to run remotely.","name":"f","type":"function"}],"inputs":[{"description":"A fully specified device name where we want to run the function.","name":"target","type":7},{"description":"A list of arguments for the function.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"Runs function `f` on a remote device indicated by `target`."}},{"name":"RemoteFusedGraphExecute","schema":{"attributes":[{"minimum":0,"name":"Tinputs","type":"type[]"},{"minimum":0,"name":"Toutputs","type":"type[]"},{"description":"Serialized protocol buffer\nof RemoteFusedGraphExecuteInfo which contains graph specifications.","name":"serialized_remote_fused_graph_execute_info","type":"string"}],"description":"The graph specifications(such as graph itself, input tensors and output names)\nare stored as a serialized protocol buffer of RemoteFusedGraphExecuteInfo\nas serialized_remote_fused_graph_execute_info.\nThe specifications will be passed to a dedicated registered\nremote fused graph executor. The executor will send the graph specifications\nto a remote processor and execute that graph. The execution results\nwill be passed to consumer nodes as outputs of this node.","inputs":[{"description":"Arbitrary number of tensors with arbitrary data types","name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"description":"Arbitrary number of tensors with arbitrary data types","name":"outputs","typeListAttr":"Toutputs"}],"summary":"Execute a sub graph on a remote processor."}},{"name":"RepeatDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of times that `input_dataset` should\nbe repeated. A value of `-1` indicates that it should be repeated infinitely.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the outputs of `input_dataset` `count` times."}},{"name":"RequantizationRange","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"}],"description":"Given a quantized tensor described by `(input, input_min, input_max)`, outputs a\nrange that covers the actual values present in that tensor. This op is typically\nused to produce the `requested_output_min` and `requested_output_max` for\n`Requantize`.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1}],"outputs":[{"description":"The computed min output.","name":"output_min","type":1},{"description":"the computed max output.","name":"output_max","type":1}],"summary":"Computes a range that covers the actual values present in a quantized tensor."}},{"name":"RequantizationRangePerChannel","schema":{"attributes":[{"default":{"type":"type","value":13},"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"description":"The maximum value of the output that needs to be clipped.\nExample: set this to 6 for Relu6.","name":"clip_value_max","type":"float32"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"T"},{"description":"The minimum value of the input tensor","name":"input_min","type":1},{"description":"The maximum value of the input tensor.","name":"input_max","type":1}],"outputs":[{"description":"The minimum value of the final output tensor","name":"output_min","type":1},{"description":"The maximum value of the final output tensor.","name":"output_max","type":1}],"summary":"Computes requantization range per channel."}},{"name":"Requantize","schema":{"attributes":[{"description":"The type of the input. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"Tinput","type":"type"},{"description":"The type of the output. Should be a lower bit depth than Tinput. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"description":"Converts the quantized `input` tensor into a lower-precision `output`, using the\noutput range specified with `requested_output_min` and `requested_output_max`.\n\n`[input_min, input_max]` are scalar floats that specify the range for the float\ninterpretation of the `input` data. For example, if `input_min` is -1.0f and\n`input_max` is 1.0f, and we are dealing with `quint16` quantized data, then a 0\nvalue in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f.","inputs":[{"name":"input","typeAttr":"Tinput"},{"description":"The float value that the minimum quantized input value represents.","name":"input_min","type":1},{"description":"The float value that the maximum quantized input value represents.","name":"input_max","type":1},{"description":"The float value that the minimum quantized output value represents.","name":"requested_output_min","type":1},{"description":"The float value that the maximum quantized output value represents.","name":"requested_output_max","type":1}],"outputs":[{"name":"output","typeAttr":"out_type"},{"description":"The requested_output_min value is copied into this output.","name":"output_min","type":1},{"description":"The requested_output_max value is copied into this output.","name":"output_max","type":1}],"summary":"Converts the quantized `input` tensor into a lower-precision `output`."}},{"name":"RequantizePerChannel","schema":{"attributes":[{"default":{"type":"type","value":13},"description":"The quantized type of input tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"T","type":"type"},{"default":{"type":"type","value":12},"description":"The quantized type of output tensor that needs to be converted. Must be one of the following: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`.","name":"out_type","type":"type"}],"inputs":[{"description":"The original input tensor.","name":"input","typeAttr":"T"},{"description":"The minimum value of the input tensor","name":"input_min","type":1},{"description":"The maximum value of the input tensor.","name":"input_max","type":1},{"description":"The minimum value of the output tensor requested.","name":"requested_output_min","type":1},{"description":"The maximum value of the output tensor requested.","name":"requested_output_max","type":1}],"outputs":[{"description":"Output tensor.","name":"output","typeAttr":"out_type"},{"description":"The minimum value of the final output tensor","name":"output_min","type":1},{"description":"The maximum value of the final output tensor.","name":"output_max","type":1}],"summary":"Requantizes input with min and max values known per channel."}},{"name":"Reshape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tshape","type":"type"}],"category":"Shape","description":"Given `tensor`, this operation returns a tensor that has the same values\nas `tensor` with shape `shape`.\n\nIf one component of 1-D tensor `shape` is the special value -1, the size of that\ndimension is computed so that the total size remains constant. In particular, a\n`shape` of `[-1]` flattens into 1-D. At most one component of `shape` may be\nunknown.\n\nThe `shape` must be 1-D and the operation returns a tensor with shape\n`shape` filled with the values of `tensor`. In this case, the number of elements\nimplied by `shape` must be the same as the number of elements in `tensor`.\n\nIt is an error if `shape` is not 1-D.\n\nFor example:\n\n```\n# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# tensor 't' has shape [9]\nreshape(t, [3, 3]) ==> [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n# tensor 't' is [[[1, 1], [2, 2]],\n# [[3, 3], [4, 4]]]\n# tensor 't' has shape [2, 2, 2]\nreshape(t, [2, 4]) ==> [[1, 1, 2, 2],\n [3, 3, 4, 4]]\n\n# tensor 't' is [[[1, 1, 1],\n# [2, 2, 2]],\n# [[3, 3, 3],\n# [4, 4, 4]],\n# [[5, 5, 5],\n# [6, 6, 6]]]\n# tensor 't' has shape [3, 2, 3]\n# pass '[-1]' to flatten 't'\nreshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]\n\n# -1 can also be used to infer the shape\n\n# -1 is inferred to be 9:\nreshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 2:\nreshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]]\n# -1 is inferred to be 3:\nreshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]]]\n\n# tensor 't' is [7]\n# shape `[]` reshapes to a scalar\nreshape(t, []) ==> 7\n```","inputs":[{"name":"tensor","typeAttr":"T"},{"description":"Defines the shape of the output tensor.","name":"shape","typeAttr":"Tshape"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Reshapes a tensor."}},{"name":"ResizeArea","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"}],"description":"Input images can be of different types but output images are always float.\n\nThe range of pixel values for the output image might be slightly different\nfrom the range for the input image because of limited numerical precision.\nTo guarantee an output range, for example `[0.0, 1.0]`, apply\n`tf.clip_by_value` to the output.\n\nEach output pixel is computed by first transforming the pixel's footprint into\nthe input tensor and then averaging the pixels that intersect the footprint. An\ninput pixel's contribution to the average is weighted by the fraction of its\narea that intersects the footprint. This is the same as OpenCV's INTER_AREA.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using area interpolation."}},{"name":"ResizeBicubic","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images can be of different types but output images are always float.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using bicubic interpolation."}},{"name":"ResizeBicubicGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","type":1},{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`,\nThe image tensor that was resized.","name":"original_image","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`.\nGradients with respect to the input image. Input image must have been\nfloat or double.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of bicubic interpolation."}},{"name":"ResizeBilinear","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"description":"Input images can be of different types but output images are always float.","inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","type":1}],"summary":"Resize `images` to `size` using bilinear interpolation."}},{"name":"ResizeBilinearGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `bfloat16`, `float16`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","type":1},{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`,\nThe image tensor that was resized.","name":"original_image","typeAttr":"T"}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`.\nGradients with respect to the input image. Input image must have been\nfloat or double.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of bilinear interpolation."}},{"name":"ResizeNearestNeighbor","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `float16`, `float32`, `float64`, `bfloat16`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and output tensors are\naligned, preserving the values at the corner pixels. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"images","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The\nnew size for the images.","name":"size","type":3}],"outputs":[{"description":"4-D with shape\n`[batch, new_height, new_width, channels]`.","name":"resized_images","typeAttr":"T"}],"summary":"Resize `images` to `size` using nearest neighbor interpolation."}},{"name":"ResizeNearestNeighborGrad","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int32`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"If true, the centers of the 4 corner pixels of the input and grad tensors are\naligned. Defaults to false.","name":"align_corners","type":"boolean"},{"default":false,"name":"half_pixel_centers","type":"boolean"}],"inputs":[{"description":"4-D with shape `[batch, height, width, channels]`.","name":"grads","typeAttr":"T"},{"description":"= A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The\noriginal input size.","name":"size","type":3}],"outputs":[{"description":"4-D with shape `[batch, orig_height, orig_width, channels]`. Gradients\nwith respect to the input image.","name":"output","typeAttr":"T"}],"summary":"Computes the gradient of nearest neighbor interpolation."}},{"name":"ResourceAccumulatorApplyGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"Does not add if local_step is lesser than the accumulator's global_step.","inputs":[{"description":"The handle to a accumulator.","name":"handle","type":20},{"description":"The local_step value at which the gradient was computed.","name":"local_step","type":9},{"description":"A tensor of the gradient to be accumulated.","name":"gradient","typeAttr":"dtype"}],"summary":"Applies a gradient to a given accumulator."}},{"name":"ResourceAccumulatorNumAccumulated","schema":{"inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20}],"outputs":[{"description":"The number of gradients aggregated in the given accumulator.","name":"num_accumulated","type":3}],"summary":"Returns the number of gradients aggregated in the given accumulators."}},{"name":"ResourceAccumulatorSetGlobalStep","schema":{"description":"Logs warning if the accumulator's value is already higher than\nnew_global_step.","inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20},{"description":"The new global_step value to set.","name":"new_global_step","type":9}],"summary":"Updates the accumulator with a new value for global_step."}},{"name":"ResourceAccumulatorTakeGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"The op blocks until sufficient (i.e., more than num_required)\ngradients have been accumulated. If the accumulator has already\naggregated more than num_required gradients, it returns the average of\nthe accumulated gradients. Also automatically increments the recorded\nglobal_step in the accumulator by 1, and resets the aggregate to 0.","inputs":[{"description":"The handle to an accumulator.","name":"handle","type":20},{"description":"Number of gradients required before we return an aggregate.","name":"num_required","type":3}],"outputs":[{"description":"The average of the accumulated gradients.","name":"average","typeAttr":"dtype"}],"summary":"Extracts the average gradient in the given ConditionalAccumulator."}},{"name":"ResourceApplyAdaMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nv_t <- max(beta2 * v_{t-1}, abs(g))\nvariable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon)","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AdaMax algorithm."}},{"name":"ResourceApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var, accum and update_accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum = rho() * accum + (1 - rho()) * grad.square();\nupdate = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad;\nupdate_accum = rho() * update_accum + (1 - rho()) * update.square();\nvar -= update;","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"accum_update","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adadelta scheme."}},{"name":"ResourceApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ResourceApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"gradient_accumulator","type":20},{"description":"Should be from a Variable().","name":"gradient_squared_accumulator","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"summary":"Update '*var' according to the proximal adagrad scheme."}},{"name":"ResourceApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"accum += grad * grad\nvar -= lr * grad * (1 / (sqrt(accum) + epsilon))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the adagrad scheme."}},{"name":"ResourceApplyAdam","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, uses the nesterov update.","name":"use_nesterov","type":"boolean"}],"description":"$$\\text{lr}_t := \\mathrm{learning_rate} * \\sqrt{1 - \\beta_2^t} / (1 - \\beta_1^t)$$\n$$m_t := \\beta_1 * m_{t-1} + (1 - \\beta_1) * g$$\n$$v_t := \\beta_2 * v_{t-1} + (1 - \\beta_2) * g * g$$\n$$\\text{variable} := \\text{variable} - \\text{lr}_t * m_t / (\\sqrt{v_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ResourceApplyAdamWithAmsgrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, m, and v tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"$$\\text{lr}_t := \\mathrm{learning_rate} * \\sqrt{1 - \\beta_2^t} / (1 - \\beta_1^t)$$\n$$m_t := \\beta_1 * m_{t-1} + (1 - \\beta_1) * g$$\n$$v_t := \\beta_2 * v_{t-1} + (1 - \\beta_2) * g * g$$\n$$\\hat{v}_t := max{\\hat{v}_{t-1}, v_t}$$\n$$\\text{variable} := \\text{variable} - \\text{lr}_t * m_t / (\\sqrt{\\hat{v}_t} + \\epsilon)$$","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Should be from a Variable().","name":"v","type":20},{"description":"Should be from a Variable().","name":"vhat","type":20},{"description":"Must be a scalar.","name":"beta1_power","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta2_power","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta1","typeAttr":"T"},{"description":"Momentum factor. Must be a scalar.","name":"beta2","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the Adam algorithm."}},{"name":"ResourceApplyAddSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- (alpha + sign_decay * sign(g) *sign(m)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ResourceApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\n\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nmg <- rho * mg_{t-1} + (1-rho) * grad\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"mg","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ResourceApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"accum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"grad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad_with_shrinkage * grad_with_shrinkage\nlinear += grad_with_shrinkage +\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceApplyGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"summary":"Update '*var' by subtracting 'alpha' * 'delta' from it."}},{"name":"ResourceApplyKerasMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar + momentum * accum, so in the end, the var you get is actually\nvar + momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum - lr * grad\nvar += accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ResourceApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update '*var' according to the momentum scheme."}},{"name":"ResourceApplyPowerSign","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var and m tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"m_t <- beta1 * m_{t-1} + (1 - beta1) * g\nupdate <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g\nvariable <- variable - lr_t * update","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"m","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Must be a scalar.","name":"logbase","typeAttr":"T"},{"description":"Must be a scalar.","name":"sign_decay","typeAttr":"T"},{"description":"Must be a scalar.","name":"beta","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the AddSign update."}},{"name":"ResourceApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"accum += grad * grad\nprox_v = var - lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' and '*accum' according to FOBOS with Adagrad learning rate."}},{"name":"ResourceApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"prox_v = var - alpha * delta\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The change.","name":"delta","typeAttr":"T"}],"summary":"Update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ResourceApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ResourceConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values, can be [], in which case shape is unknown.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the\ngiven name across multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.\nThis is a resource version of ConditionalAccumulator that will work in TF2.0\nwith tf.cond version 2.","outputs":[{"description":"The handle to the accumulator.","name":"handle","type":20}],"summary":"A conditional accumulator for aggregating gradients."}},{"name":"ResourceCountUpTo","schema":{"attributes":[{"description":"If incrementing ref would bring it above limit, instead generates an\n'OutOfRange' error.","name":"limit","type":"int64"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"inputs":[{"description":"Should be from a scalar `Variable` node.","name":"resource","type":20}],"outputs":[{"description":"A copy of the input before increment. If nothing else modifies the\ninput, the values produced will all be distinct.","name":"output","typeAttr":"T"}],"summary":"Increments variable pointed to by 'resource' until it reaches 'limit'."}},{"name":"ResourceGather","schema":{"attributes":[{"default":0,"name":"batch_dims","type":"int64"},{"default":true,"name":"validate_indices","type":"boolean"},{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"`indices` must be an integer tensor of any dimension (usually 0-D or 1-D).\nProduces an output tensor with shape `indices.shape + params.shape[1:]` where:\n\n```python\n # Scalar indices\n output[:, ..., :] = params[indices, :, ... :]\n\n # Vector indices\n output[i, :, ..., :] = params[indices[i], :, ... :]\n\n # Higher rank indices\n output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]\n```","inputs":[{"name":"resource","type":20},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"dtype"}],"summary":"Gather slices from the variable pointed to by `resource` according to `indices`."}},{"name":"ResourceGatherNd","schema":{"attributes":[{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"name":"resource","type":20},{"name":"indices","typeAttr":"Tindices"}],"outputs":[{"name":"output","typeAttr":"dtype"}]}},{"name":"ResourceScatterAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] += updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] += updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Adds sparse updates to the variable referenced by `resource`."}},{"name":"ResourceScatterDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] /= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] /= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Divides sparse updates into the variable referenced by `resource`."}},{"name":"ResourceScatterMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = max(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions are combined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Reduces sparse updates into the variable referenced by `resource` using the `max` operation."}},{"name":"ResourceScatterMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = min(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions are combined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Reduces sparse updates into the variable referenced by `resource` using the `min` operation."}},{"name":"ResourceScatterMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] *= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] *= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Multiplies sparse updates into the variable referenced by `resource`."}},{"name":"ResourceScatterNdAdd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that addition would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True)\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nadd = tf.scatter_nd_add(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(add)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse addition to individual values or slices in a Variable."}},{"name":"ResourceScatterNdMax","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues whose element wise max is taken with ref","name":"updates","typeAttr":"T"}]}},{"name":"ResourceScatterNdMin","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues whose element wise min is taken with ref.","name":"updates","typeAttr":"T"}]}},{"name":"ResourceScatterNdSub","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to subtract 4 scattered elements from a rank-1 tensor\nwith 8 elements. In Python, that subtraction would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True)\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nsub = tf.scatter_nd_sub(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(sub)\n```\n\nThe resulting update to ref would look like this:\n\n [1, -9, 3, -6, -4, 6, 7, -4]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse subtraction to individual values or slices in a Variable."}},{"name":"ResourceScatterNdUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n```\n\nFor example, say we want to update 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that update would look like this:\n\n```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n update = tf.scatter_nd_update(ref, indices, updates)\n with tf.Session() as sess:\n print sess.run(update)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A resource handle. Must be from a VarHandleOp.","name":"ref","type":20},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"summary":"Applies sparse `updates` to individual values or slices within a given"}},{"name":"ResourceScatterSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] -= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] -= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...]\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Subtracts sparse updates from the variable referenced by `resource`."}},{"name":"ResourceScatterUpdate","schema":{"attributes":[{"name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] = updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]","inputs":[{"description":"Should be from a `Variable` node.","name":"resource","type":20},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"dtype"}],"summary":"Assigns sparse updates to the variable referenced by `resource`."}},{"name":"ResourceSparseApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":": Should be from a Variable().","name":"accum_update","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"var: Should be from a Variable()."}},{"name":"ResourceSparseApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"ResourceSparseApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"gradient_accumulator","type":20},{"description":"Should be from a Variable().","name":"gradient_squared_accumulator","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"summary":"Update entries in '*var' and '*accum' according to the proximal adagrad scheme."}},{"name":"ResourceSparseApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nvar -= lr * grad * (1 / sqrt(accum))","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"ResourceSparseApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"mg","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"ResourceSparseApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\naccum_new = accum + grad * grad\nlinear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceSparseApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\ngrad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad_with_shrinkage * grad_with_shrinkage\nlinear += grad_with_shrinkage +\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Should be from a Variable().","name":"linear","type":20},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"ResourceSparseApplyKerasMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar + momentum * accum, so in the end, the var you get is actually\nvar + momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\naccum = accum * momentum - lr * grad\nvar += accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"ResourceSparseApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\naccum = accum * momentum + grad\nvar -= lr * accum","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"ResourceSparseApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\naccum += grad * grad\nprox_v = var\nprox_v -= lr * grad * (1 / sqrt(accum))\nvar = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"accum","type":20},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Sparse update entries in '*var' and '*accum' according to FOBOS algorithm."}},{"name":"ResourceSparseApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var as follows:\nprox_v = var - alpha * grad\nvar = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"summary":"Sparse update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"ResourceSparseApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\nms <- rho * ms_{t-1} + (1-rho) * grad * grad\nmom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)\nvar <- var - mom","inputs":[{"description":"Should be from a Variable().","name":"var","type":20},{"description":"Should be from a Variable().","name":"ms","type":20},{"description":"Should be from a Variable().","name":"mom","type":20},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"ResourceStridedSliceAssign","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the variable\n`ref` that are selected by the slice parameters. The slice parameters\n`begin, `end`, `strides`, etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s\nshape must be exactly the shape produced by the slice of `ref`.","inputs":[{"name":"ref","type":20},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `ref`."}},{"name":"Restore","schema":{"attributes":[{"description":"The type of the tensor to be restored.","name":"dt","type":"type"},{"default":-1,"description":"Index of file to open first if multiple files match\n`file_pattern`.","name":"preferred_shard","type":"int64"}],"description":"Reads a tensor stored in one or several files. If there are several files (for\ninstance because a tensor was saved as slices), `file_pattern` may contain\nwildcard symbols (`*` and `?`) in the filename portion only, not in the\ndirectory portion.\n\nIf a `file_pattern` matches several files, `preferred_shard` can be used to hint\nin which file the requested tensor is likely to be found. This op will first\nopen the file at index `preferred_shard` in the list of matching files and try\nto restore tensors from that file. Only if some tensors or tensor slices are\nnot found in that first file, then the Op opens all the files. Setting\n`preferred_shard` to match the value passed as the `shard` input\nof a matching `Save` Op may speed up Restore. This attribute only affects\nperformance, not correctness. The default value -1 means files are processed in\norder.\n\nSee also `RestoreSlice`.","inputs":[{"description":"Must have a single element. The pattern of the files from\nwhich we read the tensor.","name":"file_pattern","type":7},{"description":"Must have a single element. The name of the tensor to be\nrestored.","name":"tensor_name","type":7}],"outputs":[{"description":"The restored tensor.","name":"tensor","typeAttr":"dt"}],"summary":"Restores a tensor from checkpoint files."}},{"name":"RestoreSlice","schema":{"attributes":[{"description":"The type of the tensor to be restored.","name":"dt","type":"type"},{"default":-1,"description":"Index of file to open first if multiple files match\n`file_pattern`. See the documentation for `Restore`.","name":"preferred_shard","type":"int64"}],"description":"This is like `Restore` except that restored tensor can be listed as filling\nonly a slice of a larger tensor. `shape_and_slice` specifies the shape of the\nlarger tensor and the slice that the restored tensor covers.\n\nThe `shape_and_slice` input has the same format as the\nelements of the `shapes_and_slices` input of the `SaveSlices` op.","inputs":[{"description":"Must have a single element. The pattern of the files from\nwhich we read the tensor.","name":"file_pattern","type":7},{"description":"Must have a single element. The name of the tensor to be\nrestored.","name":"tensor_name","type":7},{"description":"Scalar. The shapes and slice specifications to use when\nrestoring a tensors.","name":"shape_and_slice","type":7}],"outputs":[{"description":"The restored tensor.","name":"tensor","typeAttr":"dt"}],"summary":"Restores a tensor from checkpoint files."}},{"name":"RestoreV2","schema":{"attributes":[{"description":"shape {N}. The list of expected dtype for the tensors. Must match\nthose stored in the checkpoint.","minimum":1,"name":"dtypes","type":"type[]"}],"description":"For backward compatibility with the V1 format, this Op currently allows\nrestoring from a V1 checkpoint as well:\n - This Op first attempts to find the V2 index file pointed to by \"prefix\", and\n if found proceed to read it as a V2 checkpoint;\n - Otherwise the V1 read path is invoked.\nRelying on this behavior is not recommended, as the ability to fall back to read\nV1 might be deprecated and eventually removed.\n\nBy default, restores the named tensors in full. If the caller wishes to restore\nspecific slices of stored tensors, \"shape_and_slices\" should be non-empty\nstrings and correspondingly well-formed.\n\nCallers must ensure all the named tensors are indeed stored in the checkpoint.","inputs":[{"description":"Must have a single element. The prefix of a V2 checkpoint.","name":"prefix","type":7},{"description":"shape {N}. The names of the tensors to be restored.","name":"tensor_names","type":7},{"description":"shape {N}. The slice specs of the tensors to be restored.\nEmpty strings indicate that they are non-partitioned tensors.","name":"shape_and_slices","type":7}],"outputs":[{"description":"shape {N}. The restored tensors, whose shapes are read from the\ncheckpoint directly.","name":"tensors","typeListAttr":"dtypes"}],"summary":"Restores tensors from a V2 checkpoint."}},{"name":"RetrieveTPUEmbeddingADAMParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Parameter velocities updated by the ADAM optimization algorithm.","name":"velocities","type":1}],"summary":"Retrieve ADAM embedding parameters."}},{"name":"RetrieveTPUEmbeddingADAMParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the ADAM optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the ADAM optimization algorithm.","name":"momenta","type":1},{"description":"Parameter velocities updated by the ADAM optimization algorithm.","name":"velocities","type":1},{"description":"Parameter gradient_accumulators updated by the ADAM optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve ADAM embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingAdadeltaParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter updates updated by the Adadelta optimization algorithm.","name":"updates","type":1}],"summary":"Retrieve Adadelta embedding parameters."}},{"name":"RetrieveTPUEmbeddingAdadeltaParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adadelta optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adadelta optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter updates updated by the Adadelta optimization algorithm.","name":"updates","type":1},{"description":"Parameter gradient_accumulators updated by the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Adadelta embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Retrieve Adagrad embedding parameters."}},{"name":"RetrieveTPUEmbeddingAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter gradient_accumulators updated by the Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Adagrad embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingCenteredRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the centered RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the centered RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the centered RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Parameter mg updated by the centered RMSProp optimization algorithm.","name":"mg","type":1}],"summary":"Retrieve centered RMSProp embedding parameters."}},{"name":"RetrieveTPUEmbeddingFTRLParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter linears updated by the FTRL optimization algorithm.","name":"linears","type":1}],"summary":"Retrieve FTRL embedding parameters."}},{"name":"RetrieveTPUEmbeddingFTRLParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the FTRL optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the FTRL optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter linears updated by the FTRL optimization algorithm.","name":"linears","type":1},{"description":"Parameter gradient_accumulators updated by the FTRL optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve FTRL embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingMDLAdagradLightParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the MDL Adagrad Light optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the MDL Adagrad Light optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter weights updated by the MDL Adagrad Light optimization algorithm.","name":"weights","type":1},{"description":"Parameter benefits updated by the MDL Adagrad Light optimization algorithm.","name":"benefits","type":1}],"summary":"Retrieve MDL Adagrad Light embedding parameters."}},{"name":"RetrieveTPUEmbeddingMomentumParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the Momentum optimization algorithm.","name":"momenta","type":1}],"summary":"Retrieve Momentum embedding parameters."}},{"name":"RetrieveTPUEmbeddingMomentumParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the Momentum optimization algorithm.","name":"parameters","type":1},{"description":"Parameter momenta updated by the Momentum optimization algorithm.","name":"momenta","type":1},{"description":"Parameter gradient_accumulators updated by the Momentum optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve Momentum embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingProximalAdagradParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the proximal Adagrad optimization algorithm.","name":"accumulators","type":1}],"summary":"Retrieve proximal Adagrad embedding parameters."}},{"name":"RetrieveTPUEmbeddingProximalAdagradParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the proximal Adagrad optimization algorithm.","name":"parameters","type":1},{"description":"Parameter accumulators updated by the proximal Adagrad optimization algorithm.","name":"accumulators","type":1},{"description":"Parameter gradient_accumulators updated by the proximal Adagrad optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve proximal Adagrad embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingProximalYogiParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"outputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1}]}},{"name":"RetrieveTPUEmbeddingProximalYogiParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"outputs":[{"name":"parameters","type":1},{"name":"v","type":1},{"name":"m","type":1},{"name":"gradient_accumulators","type":1}]}},{"name":"RetrieveTPUEmbeddingRMSPropParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the RMSProp optimization algorithm.","name":"mom","type":1}],"summary":"Retrieve RMSProp embedding parameters."}},{"name":"RetrieveTPUEmbeddingRMSPropParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the RMSProp optimization algorithm.","name":"parameters","type":1},{"description":"Parameter ms updated by the RMSProp optimization algorithm.","name":"ms","type":1},{"description":"Parameter mom updated by the RMSProp optimization algorithm.","name":"mom","type":1},{"description":"Parameter gradient_accumulators updated by the RMSProp optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve RMSProp embedding parameters with debug support."}},{"name":"RetrieveTPUEmbeddingStochasticGradientDescentParameters","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the stochastic gradient descent optimization algorithm.","name":"parameters","type":1}],"summary":"Retrieve SGD embedding parameters."}},{"name":"RetrieveTPUEmbeddingStochasticGradientDescentParametersGradAccumDebug","schema":{"attributes":[{"default":-1,"name":"table_id","type":"int64"},{"default":"","name":"table_name","type":"string"},{"name":"num_shards","type":"int64"},{"name":"shard_id","type":"int64"},{"default":"","name":"config","type":"string"}],"description":"An op that retrieves optimization parameters from embedding to host\nmemory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up\nthe correct embedding table configuration. For example, this op is\nused to retrieve updated parameters before saving a checkpoint.","outputs":[{"description":"Parameter parameters updated by the stochastic gradient descent optimization algorithm.","name":"parameters","type":1},{"description":"Parameter gradient_accumulators updated by the Adadelta optimization algorithm.","name":"gradient_accumulators","type":1}],"summary":"Retrieve SGD embedding parameters with debug support."}},{"name":"Reverse","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"Given a `tensor`, and a `bool` tensor `dims` representing the dimensions\nof `tensor`, this operation reverses each dimension i of `tensor` where\n`dims[i]` is `True`.\n\n`tensor` can have up to 8 dimensions. The number of dimensions\nof `tensor` must equal the number of elements in `dims`. In other words:\n\n`rank(tensor) = size(dims)`\n\nFor example:\n\n```\n# tensor 't' is [[[[ 0, 1, 2, 3],\n# [ 4, 5, 6, 7],\n# [ 8, 9, 10, 11]],\n# [[12, 13, 14, 15],\n# [16, 17, 18, 19],\n# [20, 21, 22, 23]]]]\n# tensor 't' shape is [1, 2, 3, 4]\n\n# 'dims' is [False, False, False, True]\nreverse(t, dims) ==> [[[[ 3, 2, 1, 0],\n [ 7, 6, 5, 4],\n [ 11, 10, 9, 8]],\n [[15, 14, 13, 12],\n [19, 18, 17, 16],\n [23, 22, 21, 20]]]]\n\n# 'dims' is [False, True, False, False]\nreverse(t, dims) ==> [[[[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]\n [[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]]]]\n\n# 'dims' is [False, False, True, False]\nreverse(t, dims) ==> [[[[8, 9, 10, 11],\n [4, 5, 6, 7],\n [0, 1, 2, 3]]\n [[20, 21, 22, 23],\n [16, 17, 18, 19],\n [12, 13, 14, 15]]]]\n```","inputs":[{"description":"Up to 8-D.","name":"tensor","typeAttr":"T"},{"description":"1-D. The dimensions to reverse.","name":"dims","type":10}],"outputs":[{"description":"The same shape as `tensor`.","name":"output","typeAttr":"T"}],"summary":"Reverses specific dimensions of a tensor."}},{"name":"ReverseSequence","schema":{"attributes":[{"description":"The dimension which is partially reversed.","name":"seq_dim","type":"int64"},{"default":0,"description":"The dimension along which reversal is performed.","name":"batch_dim","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlen","type":"type"}],"description":"This op first slices `input` along the dimension `batch_dim`, and for each\nslice `i`, reverses the first `seq_lengths[i]` elements along\nthe dimension `seq_dim`.\n\nThe elements of `seq_lengths` must obey `seq_lengths[i] <= input.dims[seq_dim]`,\nand `seq_lengths` must be a vector of length `input.dims[batch_dim]`.\n\nThe output slice `i` along dimension `batch_dim` is then given by input\nslice `i`, with the first `seq_lengths[i]` slices along dimension\n`seq_dim` reversed.\n\nFor example:\n\n```\n# Given this:\nbatch_dim = 0\nseq_dim = 1\ninput.dims = (4, 8, ...)\nseq_lengths = [7, 2, 3, 5]\n\n# then slices of input are reversed on seq_dim, but only up to seq_lengths:\noutput[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...]\noutput[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...]\noutput[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...]\noutput[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...]\n\n# while entries past seq_lens are copied through:\noutput[0, 7:, :, ...] = input[0, 7:, :, ...]\noutput[1, 2:, :, ...] = input[1, 2:, :, ...]\noutput[2, 3:, :, ...] = input[2, 3:, :, ...]\noutput[3, 2:, :, ...] = input[3, 2:, :, ...]\n```\n\nIn contrast, if:\n\n```\n# Given this:\nbatch_dim = 2\nseq_dim = 0\ninput.dims = (8, ?, 4, ...)\nseq_lengths = [7, 2, 3, 5]\n\n# then slices of input are reversed on seq_dim, but only up to seq_lengths:\noutput[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...]\noutput[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...]\noutput[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...]\noutput[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...]\n\n# while entries past seq_lens are copied through:\noutput[7:, :, 0, :, ...] = input[7:, :, 0, :, ...]\noutput[2:, :, 1, :, ...] = input[2:, :, 1, :, ...]\noutput[3:, :, 2, :, ...] = input[3:, :, 2, :, ...]\noutput[2:, :, 3, :, ...] = input[2:, :, 3, :, ...]\n```","inputs":[{"description":"The input to reverse.","name":"input","typeAttr":"T"},{"description":"1-D with length `input.dims(batch_dim)` and\n`max(seq_lengths) <= input.dims(seq_dim)`","name":"seq_lengths","typeAttr":"Tlen"}],"outputs":[{"description":"The partially reversed input. It has the same shape as `input`.","name":"output","typeAttr":"T"}],"summary":"Reverses variable length slices."}},{"name":"ReverseV2","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`, `string`.","name":"T","type":"type"}],"description":"NOTE `tf.reverse` has now changed behavior in preparation for 1.0.\n`tf.reverse_v2` is currently an alias that will be deprecated before TF 1.0.\n\nGiven a `tensor`, and a `int32` tensor `axis` representing the set of\ndimensions of `tensor` to reverse. This operation reverses each dimension\n`i` for which there exists `j` s.t. `axis[j] == i`.\n\n`tensor` can have up to 8 dimensions. The number of dimensions specified\nin `axis` may be 0 or more entries. If an index is specified more than\nonce, a InvalidArgument error is raised.\n\nFor example:\n\n```\n# tensor 't' is [[[[ 0, 1, 2, 3],\n# [ 4, 5, 6, 7],\n# [ 8, 9, 10, 11]],\n# [[12, 13, 14, 15],\n# [16, 17, 18, 19],\n# [20, 21, 22, 23]]]]\n# tensor 't' shape is [1, 2, 3, 4]\n\n# 'dims' is [3] or 'dims' is [-1]\nreverse(t, dims) ==> [[[[ 3, 2, 1, 0],\n [ 7, 6, 5, 4],\n [ 11, 10, 9, 8]],\n [[15, 14, 13, 12],\n [19, 18, 17, 16],\n [23, 22, 21, 20]]]]\n\n# 'dims' is '[1]' (or 'dims' is '[-3]')\nreverse(t, dims) ==> [[[[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]\n [[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]]]]\n\n# 'dims' is '[2]' (or 'dims' is '[-2]')\nreverse(t, dims) ==> [[[[8, 9, 10, 11],\n [4, 5, 6, 7],\n [0, 1, 2, 3]]\n [[20, 21, 22, 23],\n [16, 17, 18, 19],\n [12, 13, 14, 15]]]]\n```","inputs":[{"description":"Up to 8-D.","name":"tensor","typeAttr":"T"},{"description":"1-D. The indices of the dimensions to reverse. Must be in the range\n`[-rank(tensor), rank(tensor))`.","name":"axis","typeAttr":"Tidx"}],"outputs":[{"description":"The same shape as `tensor`.","name":"output","typeAttr":"T"}],"summary":"Reverses specific dimensions of a tensor."}},{"name":"RightShift","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Performs a logical shift for unsigned integer types, and an arithmetic shift\nfor signed integer types.\n\nIf `y` is negative, or greater than or equal to than the width of `x` in bits\nthe result is implementation defined.\n\nExample:\n\n```python\nimport tensorflow as tf\nfrom tensorflow.python.ops import bitwise_ops\nimport numpy as np\ndtype_list = [tf.int8, tf.int16, tf.int32, tf.int64]\n\nfor dtype in dtype_list:\n lhs = tf.constant([-1, -5, -3, -14], dtype=dtype)\n rhs = tf.constant([5, 0, 7, 11], dtype=dtype)\n\n right_shift_result = bitwise_ops.right_shift(lhs, rhs)\n\n print(right_shift_result)\n\n# This will print:\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int8)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int16)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int32)\n# tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int64)\n\nlhs = np.array([-2, 64, 101, 32], dtype=np.int8)\nrhs = np.array([-1, -5, -3, -14], dtype=np.int8)\nbitwise_ops.right_shift(lhs, rhs)\n# \n```\n","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Elementwise computes the bitwise right-shift of `x` and `y`."}},{"name":"Rint","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"If the result is midway between two representable values,\nthe even representable is chosen.\nFor example:\n\n```\nrint(-1.5) ==> -2.0\nrint(0.5000001) ==> 1.0\nrint([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) ==> [-2., -2., -0., 0., 2., 2., 2.]\n```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns element-wise integer closest to x."}},{"name":"RngSkip","schema":{"description":"The state of the RNG after\n`rng_skip(n)` will be the same as that after `stateful_uniform([n])`\n(or any other distribution). The actual increment added to the\ncounter is an unspecified implementation detail.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The amount of advancement.","name":"delta","type":9}],"summary":"Advance the counter of a counter-based RNG."}},{"name":"Roll","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tshift","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"}],"description":"The elements are shifted positively (towards larger indices) by the offset of\n`shift` along the dimension of `axis`. Negative `shift` values will shift\nelements in the opposite direction. Elements that roll passed the last position\nwill wrap around to the first and vice versa. Multiple shifts along multiple\naxes may be specified.\n\nFor example:\n\n```\n# 't' is [0, 1, 2, 3, 4]\nroll(t, shift=2, axis=0) ==> [3, 4, 0, 1, 2]\n\n# shifting along multiple dimensions\n# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\nroll(t, shift=[1, -2], axis=[0, 1]) ==> [[7, 8, 9, 5, 6], [2, 3, 4, 0, 1]]\n\n# shifting along the same axis multiple times\n# 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]\nroll(t, shift=[2, -3], axis=[1, 1]) ==> [[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]\n```","inputs":[{"name":"input","typeAttr":"T"},{"description":"Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which\nelements are shifted positively (towards larger indices) along the dimension\nspecified by `axis[i]`. Negative shifts will roll the elements in the opposite\ndirection.","name":"shift","typeAttr":"Tshift"},{"description":"Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift\n`shift[i]` should occur. If the same axis is referenced more than once, the\ntotal shift for that axis will be the sum of all the shifts that belong to that\naxis.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"Has the same shape and size as the input. The elements are shifted\npositively (towards larger indices) by the offsets of `shift` along the\ndimensions of `axis`.","name":"output","typeAttr":"T"}],"summary":"Rolls the elements of a tensor along an axis."}},{"name":"Round","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Rounds half to even. Also known as bankers rounding. If you want to round\naccording to the current system rounding mode use std::cint.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Rounds the values of a tensor to the nearest integer, element-wise."}},{"name":"Rpc","schema":{"attributes":[{"default":"","description":"RPC protocol to use. Empty string means use the default protocol.\nOptions include 'grpc'.","name":"protocol","type":"string"},{"default":true,"description":"`boolean`. If `true` (default), then failures to connect\n(i.e., the server does not immediately respond) cause an RPC failure.","name":"fail_fast","type":"boolean"},{"default":0,"description":"`int`. If `0` (default), then the kernel will run the RPC\nrequest and only time out if the RPC deadline passes or the session times out.\nIf this value is greater than `0`, then the op will raise an exception if\nthe RPC takes longer than `timeout_in_ms`.","name":"timeout_in_ms","type":"int64"}],"description":"This op asynchronously performs either a single RPC request, or a batch\nof requests. RPC requests are defined by three main parameters:\n\n - `address` (the host+port or BNS address of the request)\n - `method` (the RPC method name for the request)\n - `request` (the serialized proto string, or vector of strings,\n of the RPC request argument).\n\nFor example, if you have an RPC service running on port localhost:2345,\nand its interface is configured with the following proto declaration:\n\n```\nservice MyService {\n rpc MyMethod(MyRequestProto) returns (MyResponseProto) {\n }\n};\n```\n\nthen call this op with arguments:\n\n```\naddress = \"localhost:2345\"\nmethod = \"MyService/MyMethod\"\n```\n\nThe `request` tensor is a string tensor representing serialized `MyRequestProto`\nstrings; and the output string tensor `response` will have the same shape\nand contain (upon successful completion) corresponding serialized\n`MyResponseProto` strings.\n\nFor example, to send a single, empty, `MyRequestProto`, call\nthis op with `request = \"\"`. To send 5 **parallel** empty requests,\ncall this op with `request = [\"\", \"\", \"\", \"\", \"\"]`.\n\nMore generally, one can create a batch of `MyRequestProto` serialized protos\nfrom regular batched tensors using the `encode_proto` op, and convert\nthe response `MyResponseProto` serialized protos to batched tensors\nusing the `decode_proto` op.\n\n**NOTE** Working with serialized proto strings is faster than instantiating\nactual proto objects in memory, so no performance degradation is expected\ncompared to writing custom kernels for this workflow.\n\nIf the connection fails or the remote worker returns an error\nstatus, the op reraises this exception locally.\n\nSee the `TryRpc` op if you prefer to handle RPC failures manually in the graph.","inputs":[{"description":"`0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `method` and `request`.","name":"address","type":7},{"description":"`0-D` or `1-D`. The method address on the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `request`.","name":"method","type":7},{"description":"`0-D` or `1-D`. Serialized proto strings: the rpc request argument.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `method`.","name":"request","type":7}],"outputs":[{"description":"Same shape as `request`. Serialized proto strings: the rpc responses.","name":"response","type":7}],"summary":"Perform batches of RPC requests."}},{"name":"Rsqrt","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = 1 / \\sqrt{x}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes reciprocal of square root of x element-wise."}},{"name":"RsqrtGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * -0.5 * y^3`, where `y = rsqrt(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the rsqrt of `x` wrt its input."}},{"name":"SampleDistortedBoundingBox","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"},{"default":0,"description":"If either `seed` or `seed2` are set to non-zero, the random number\ngenerator is seeded by the given `seed`. Otherwise, it is seeded by a random\nseed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":0.10000000149011612,"description":"The cropped area of the image must contain at least this\nfraction of any bounding box supplied. The value of this parameter should be\nnon-negative. In the case of 0, the cropped area does not need to overlap\nany of the bounding boxes supplied.","name":"min_object_covered","type":"float32"},{"default":[0.75,1.3300000429153442],"description":"The cropped area of the image must have an aspect ratio =\nwidth / height within this range.","name":"aspect_ratio_range","type":"float32[]"},{"default":[0.05000000074505806,1],"description":"The cropped area of the image must contain a fraction of the\nsupplied image within this range.","name":"area_range","type":"float32[]"},{"default":100,"description":"Number of attempts at generating a cropped region of the image\nof the specified constraints. After `max_attempts` failures, return the entire\nimage.","name":"max_attempts","type":"int64"},{"default":false,"description":"Controls behavior if no bounding boxes supplied.\nIf true, assume an implicit bounding box covering the whole input. If false,\nraise an error.","name":"use_image_if_no_bounding_boxes","type":"boolean"}],"description":"Bounding box annotations are often supplied in addition to ground-truth labels\nin image recognition or object localization tasks. A common technique for\ntraining such a system is to randomly distort an image while preserving\nits content, i.e. *data augmentation*. This Op outputs a randomly distorted\nlocalization of an object, i.e. bounding box, given an `image_size`,\n`bounding_boxes` and a series of constraints.\n\nThe output of this Op is a single bounding box that may be used to crop the\noriginal image. The output is returned as 3 tensors: `begin`, `size` and\n`bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the\nimage. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize\nwhat the bounding box looks like.\n\nBounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example,\n\n```python\n # Generate a single distorted bounding box.\n begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bounding_boxes)\n\n # Draw the bounding box in an image summary.\n image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),\n bbox_for_draw)\n tf.summary.image('images_with_box', image_with_box)\n\n # Employ the bounding box to distort the image.\n distorted_image = tf.slice(image, begin, size)\n```\n\nNote that if no bounding box information is available, setting\n`use_image_if_no_bounding_boxes = true` will assume there is a single implicit\nbounding box covering the whole image. If `use_image_if_no_bounding_boxes` is\nfalse and no bounding boxes are supplied, an error is raised.","inputs":[{"description":"1-D, containing `[height, width, channels]`.","name":"image_size","typeAttr":"T"},{"description":"3-D with shape `[batch, N, 4]` describing the N bounding boxes\nassociated with the image.","name":"bounding_boxes","type":1}],"outputs":[{"description":"1-D, containing `[offset_height, offset_width, 0]`. Provide as input to\n`tf.slice`.","name":"begin","typeAttr":"T"},{"description":"1-D, containing `[target_height, target_width, -1]`. Provide as input to\n`tf.slice`.","name":"size","typeAttr":"T"},{"description":"3-D with shape `[1, 1, 4]` containing the distorted bounding box.\nProvide as input to `tf.image.draw_bounding_boxes`.","name":"bboxes","type":1}],"summary":"Generate a single randomly distorted bounding box for an image."}},{"name":"SampleDistortedBoundingBoxV2","schema":{"attributes":[{"description":"Must be one of the following: `uint8`, `int8`, `int16`, `int32`, `int64`.","name":"T","type":"type"},{"default":0,"description":"If either `seed` or `seed2` are set to non-zero, the random number\ngenerator is seeded by the given `seed`. Otherwise, it is seeded by a random\nseed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"default":[0.75,1.3300000429153442],"description":"The cropped area of the image must have an aspect ratio =\nwidth / height within this range.","name":"aspect_ratio_range","type":"float32[]"},{"default":[0.05000000074505806,1],"description":"The cropped area of the image must contain a fraction of the\nsupplied image within this range.","name":"area_range","type":"float32[]"},{"default":100,"description":"Number of attempts at generating a cropped region of the image\nof the specified constraints. After `max_attempts` failures, return the entire\nimage.","name":"max_attempts","type":"int64"},{"default":false,"description":"Controls behavior if no bounding boxes supplied.\nIf true, assume an implicit bounding box covering the whole input. If false,\nraise an error.","name":"use_image_if_no_bounding_boxes","type":"boolean"}],"description":"Bounding box annotations are often supplied in addition to ground-truth labels\nin image recognition or object localization tasks. A common technique for\ntraining such a system is to randomly distort an image while preserving\nits content, i.e. *data augmentation*. This Op outputs a randomly distorted\nlocalization of an object, i.e. bounding box, given an `image_size`,\n`bounding_boxes` and a series of constraints.\n\nThe output of this Op is a single bounding box that may be used to crop the\noriginal image. The output is returned as 3 tensors: `begin`, `size` and\n`bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the\nimage. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize\nwhat the bounding box looks like.\n\nBounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The\nbounding box coordinates are floats in `[0.0, 1.0]` relative to the width and\nheight of the underlying image.\n\nFor example,\n\n```python\n # Generate a single distorted bounding box.\n begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bounding_boxes)\n\n # Draw the bounding box in an image summary.\n image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),\n bbox_for_draw)\n tf.summary.image('images_with_box', image_with_box)\n\n # Employ the bounding box to distort the image.\n distorted_image = tf.slice(image, begin, size)\n```\n\nNote that if no bounding box information is available, setting\n`use_image_if_no_bounding_boxes = true` will assume there is a single implicit\nbounding box covering the whole image. If `use_image_if_no_bounding_boxes` is\nfalse and no bounding boxes are supplied, an error is raised.","inputs":[{"description":"1-D, containing `[height, width, channels]`.","name":"image_size","typeAttr":"T"},{"description":"3-D with shape `[batch, N, 4]` describing the N bounding boxes\nassociated with the image.","name":"bounding_boxes","type":1},{"description":"The cropped area of the image must contain at least this\nfraction of any bounding box supplied. The value of this parameter should be\nnon-negative. In the case of 0, the cropped area does not need to overlap\nany of the bounding boxes supplied.","name":"min_object_covered","type":1}],"outputs":[{"description":"1-D, containing `[offset_height, offset_width, 0]`. Provide as input to\n`tf.slice`.","name":"begin","typeAttr":"T"},{"description":"1-D, containing `[target_height, target_width, -1]`. Provide as input to\n`tf.slice`.","name":"size","typeAttr":"T"},{"description":"3-D with shape `[1, 1, 4]` containing the distorted bounding box.\nProvide as input to `tf.image.draw_bounding_boxes`.","name":"bboxes","type":1}],"summary":"Generate a single randomly distorted bounding box for an image."}},{"name":"SamplingDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"There is no transformation in the `tf.data` Python API for creating this dataset.\nInstead, it is created as a result of the `filter_with_random_uniform_fusion`\nstatic optimization. Whether this optimization is performed is determined by the\n`experimental_optimization.filter_with_random_uniform_fusion` option of\n`tf.data.Options`.","inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the sample rate. Each element of `input_dataset` is\nretained with this probability, independent of all other elements.","name":"rate","type":1},{"description":"A scalar representing seed of random number generator.","name":"seed","type":9},{"description":"A scalar representing seed2 of random number generator.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that takes a Bernoulli sample of the contents of another dataset."}},{"name":"Save","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"The size of `tensor_names` must match the number of tensors in `data`. `data[i]`\nis written to `filename` with name `tensor_names[i]`.\n\nSee also `SaveSlices`.","inputs":[{"description":"Must have a single element. The name of the file to which we write\nthe tensor.","name":"filename","type":7},{"description":"Shape `[N]`. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"`N` tensors to save.","name":"data","typeListAttr":"T"}],"summary":"Saves the input tensors to disk."}},{"name":"SaveDataset","schema":{"attributes":[{"default":"","name":"compression","type":"string"},{"name":"shard_func","type":"function"},{"default":true,"name":"use_shard_func","type":"boolean"},{"minimum":0,"name":"Tshard_func_args","type":"type[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"path","type":7},{"name":"shard_func_other_args","typeListAttr":"Tshard_func_args"}]}},{"name":"SaveSlices","schema":{"attributes":[{"minimum":1,"name":"T","type":"type[]"}],"description":"This is like `Save` except that tensors can be listed in the saved file as being\na slice of a larger tensor. `shapes_and_slices` specifies the shape of the\nlarger tensor and the slice that this tensor covers. `shapes_and_slices` must\nhave as many elements as `tensor_names`.\n\nElements of the `shapes_and_slices` input must either be:\n\n* The empty string, in which case the corresponding tensor is\n saved normally.\n* A string of the form `dim0 dim1 ... dimN-1 slice-spec` where the\n `dimI` are the dimensions of the larger tensor and `slice-spec`\n specifies what part is covered by the tensor to save.\n\n`slice-spec` itself is a `:`-separated list: `slice0:slice1:...:sliceN-1`\nwhere each `sliceI` is either:\n\n* The string `-` meaning that the slice covers all indices of this dimension\n* `start,length` where `start` and `length` are integers. In that\n case the slice covers `length` indices starting at `start`.\n\nSee also `Save`.","inputs":[{"description":"Must have a single element. The name of the file to which we write the\ntensor.","name":"filename","type":7},{"description":"Shape `[N]`. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"Shape `[N]`. The shapes and slice specifications to use when\nsaving the tensors.","name":"shapes_and_slices","type":7},{"description":"`N` tensors to save.","name":"data","typeListAttr":"T"}],"summary":"Saves input tensors slices to disk."}},{"name":"SaveV2","schema":{"attributes":[{"minimum":1,"name":"dtypes","type":"type[]"}],"description":"By default, saves the named tensors in full. If the caller wishes to save\nspecific slices of full tensors, \"shape_and_slices\" should be non-empty strings\nand correspondingly well-formed.","inputs":[{"description":"Must have a single element. The prefix of the V2 checkpoint to which we\nwrite the tensors.","name":"prefix","type":7},{"description":"shape {N}. The names of the tensors to be saved.","name":"tensor_names","type":7},{"description":"shape {N}. The slice specs of the tensors to be saved.\nEmpty strings indicate that they are non-partitioned tensors.","name":"shape_and_slices","type":7},{"description":"`N` tensors to save.","name":"tensors","typeListAttr":"dtypes"}],"summary":"Saves tensors in V2 checkpoint format."}},{"name":"ScalarSummary","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The input `tags` and `values` must have the same shape. The generated summary\nhas a summary value for each tag-value pair in `tags` and `values`.","inputs":[{"description":"Tags for the summary.","name":"tags","type":7},{"description":"Same shape as `tags. Values for the summary.","name":"values","typeAttr":"T"}],"outputs":[{"description":"Scalar. Serialized `Summary` protocol buffer.","name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with scalar values."}},{"name":"ScaleAndTranslate","schema":{"attributes":[{"description":"Must be one of the following: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"},{"default":"lanczos3","name":"kernel_type","type":"string"},{"default":true,"name":"antialias","type":"boolean"}],"inputs":[{"name":"images","typeAttr":"T"},{"name":"size","type":3},{"name":"scale","type":1},{"name":"translation","type":1}],"outputs":[{"name":"resized_images","type":1}]}},{"name":"ScaleAndTranslateGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`.","name":"T","type":"type"},{"default":"lanczos3","name":"kernel_type","type":"string"},{"default":true,"name":"antialias","type":"boolean"}],"inputs":[{"name":"grads","typeAttr":"T"},{"name":"original_image","typeAttr":"T"},{"name":"scale","type":1},{"name":"translation","type":1}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"ScanDataset","schema":{"attributes":[{"name":"f","type":"function"},{"minimum":1,"name":"Tstate","type":"type[]"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":false,"name":"preserve_cardinality","type":"boolean"},{"default":true,"name":"use_default_device","type":"boolean"}],"inputs":[{"name":"input_dataset","type":21},{"name":"initial_state","typeListAttr":"Tstate"},{"name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset successively reduces `f` over the elements of `input_dataset`."}},{"name":"ScatterAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the addition will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] += updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] += updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to add to `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Adds sparse updates to a variable reference."}},{"name":"ScatterDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the operation will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] /= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] /= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions divide.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of values that `ref` is divided by.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Divides a variable reference by sparse updates."}},{"name":"ScatterMax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the update will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = max(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions combine.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to reduce into `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Reduces sparse updates into a variable reference using the `max` operation."}},{"name":"ScatterMin","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the update will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n # Scalar indices\n ref[indices, ...] = min(ref[indices, ...], updates[...])\n\n # Vector indices (for each i)\n ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...])\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...])\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions combine.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to reduce into `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Reduces sparse updates into a variable reference using the `min` operation."}},{"name":"ScatterMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the operation will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] *= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] *= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their contributions multiply.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to multiply to `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Multiplies sparse updates into a variable reference."}},{"name":"ScatterNd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Creates a new tensor by applying sparse `updates` to individual values or\nslices within a tensor (initially zero for numeric, empty for string) of\nthe given `shape` according to indices. This operator is the inverse of the\n`tf.gather_nd` operator which extracts values or slices from a given tensor.\n\nThis operation is similar to tensor_scatter_add, except that the tensor is\nzero-initialized. Calling `tf.scatter_nd(indices, values, shape)` is identical\nto `tensor_scatter_add(tf.zeros(shape, values.dtype), indices, values)`\n\nIf `indices` contains duplicates, then their updates are accumulated (summed).\n\n**WARNING**: The order in which updates are applied is nondeterministic, so the\noutput will be nondeterministic if `indices` contains duplicates -- because\nof some numerical approximation issues, numbers summed in different order\nmay yield different results.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of scatter is to insert individual elements in a tensor by\nindex. For example, say we want to insert 4 scattered elements in a rank-1\ntensor with 8 elements.\n\n
    \n\n
    \n\nIn Python, this scatter operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n shape = tf.constant([8])\n scatter = tf.scatter_nd(indices, updates, shape)\n print(scatter)\n```\n\nThe resulting tensor would look like this:\n\n [0, 11, 0, 10, 9, 0, 0, 12]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\n
    \n\n
    \n\nIn Python, this scatter operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n shape = tf.constant([4, 4, 4])\n scatter = tf.scatter_nd(indices, updates, shape)\n print(scatter)\n```\n\nThe resulting tensor would look like this:\n\n [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],\n [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]],\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"},{"description":"1-D. The shape of the resulting tensor.","name":"shape","typeAttr":"Tindices"}],"outputs":[{"description":"A new tensor with the given shape and updates applied according\nto the indices.","name":"output","typeAttr":"T"}],"summary":"Scatter `updates` into a new tensor according to `indices`."}},{"name":"ScatterNdAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that addition would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nadd = tf.scatter_nd_add(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(add)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse addition to individual values or slices in a Variable."}},{"name":"ScatterNdMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Computes element-wise maximum."}},{"name":"ScatterNdMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Computes element-wise minimum."}},{"name":"ScatterNdNonAliasingAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"from `updates` according to indices `indices`. The updates are non-aliasing:\n`input` is only modified in-place if no other operations will use it.\nOtherwise, a copy of `input` is made. This operation has a gradient with\nrespect to both `input` and `updates`.\n\n`input` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `input`.\nIt must be shape \\\\([d_0, ..., d_{Q-2}, K]\\\\) where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or `(P-K)`-dimensional slices\n(if `K < P`) along the `K`th dimension of `input`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n$$[d_0, ..., d_{Q-2}, input.shape[K], ..., input.shape[P-1]].$$\n\nFor example, say we want to add 4 scattered elements to a rank-1 tensor to 8\nelements. In Python, that addition would look like this:\n\n input = tf.constant([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n output = tf.scatter_nd_non_aliasing_add(input, indices, updates)\n with tf.Session() as sess:\n print(sess.run(output))\n\nThe resulting value `output` would look like this:\n\n [1, 13, 3, 14, 14, 6, 7, 20]\n\nSee `tf.scatter_nd` for more details about how to make updates to slices.","inputs":[{"description":"A Tensor.","name":"input","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: `int32`, `int64`.\nA tensor of indices into `input`.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto add to `input`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `input`, containing values of `input`\nupdated with `updates`.","name":"output","typeAttr":"T"}],"summary":"Applies sparse addition to `input` using individual values or slices"}},{"name":"ScatterNdSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"within a given variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n```\n[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]\n```\n\nFor example, say we want to subtract 4 scattered elements from a rank-1 tensor\nwith 8 elements. In Python, that subtraction would look like this:\n\n```python\nref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\nindices = tf.constant([[4], [3], [1], [7]])\nupdates = tf.constant([9, 10, 11, 12])\nsub = tf.scatter_nd_sub(ref, indices, updates)\nwith tf.Session() as sess:\n print sess.run(sub)\n```\n\nThe resulting update to ref would look like this:\n\n [1, -9, 3, -6, -4, 6, 7, -4]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated values\nto subtract from ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse subtraction to individual values or slices in a Variable."}},{"name":"ScatterNdUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"An optional bool. Defaults to True. If True, the assignment will\nbe protected by a lock; otherwise the behavior is undefined,\nbut may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"variable according to `indices`.\n\n`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n`indices` must be integer tensor, containing indices into `ref`.\nIt must be shape \\\\([d_0, ..., d_{Q-2}, K]\\\\) where `0 < K <= P`.\n\nThe innermost dimension of `indices` (with length `K`) corresponds to\nindices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\ndimension of `ref`.\n\n`updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n$$[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].$$\n\nFor example, say we want to update 4 scattered elements to a rank-1 tensor to\n8 elements. In Python, that update would look like this:\n\n```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n update = tf.scatter_nd_update(ref, indices, updates)\n with tf.Session() as sess:\n print sess.run(update)\n```\n\nThe resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\nSee `tf.scatter_nd` for more details about how to make updates to\nslices.\n\nSee also `tf.scatter_update` and `tf.batch_scatter_update`.","inputs":[{"description":"A mutable Tensor. Should be from a Variable node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A Tensor. Must be one of the following types: int32, int64.\nA tensor of indices into ref.","name":"indices","typeAttr":"Tindices"},{"description":"A Tensor. Must have the same type as ref. A tensor of updated\nvalues to add to ref.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"Same as ref. Returned as a convenience for operations that want to\nuse the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse `updates` to individual values or slices within a given"}},{"name":"ScatterSub","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"```python\n # Scalar indices\n ref[indices, ...] -= updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] -= updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nDuplicate entries are handled correctly: if multiple `indices` reference\nthe same location, their (negated) contributions add.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    ","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to subtract from `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Subtracts sparse updates to a variable reference."}},{"name":"ScatterUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":true,"description":"If True, the assignment will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"This operation computes\n\n```python\n # Scalar indices\n ref[indices, ...] = updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] = updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]\n```\n\nThis operation outputs `ref` after the update is done.\nThis makes it easier to chain operations that need to use the reset value.\n\nIf values in `ref` is to be updated more than once, because there are\nduplicate entries in `indices`, the order at which the updates happen\nfor each value is undefined.\n\nRequires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.\n\n
    \n\n
    \n\nSee also `tf.batch_scatter_update` and `tf.scatter_nd_update`.","inputs":[{"description":"Should be from a `Variable` node.","isRef":true,"name":"ref","typeAttr":"T"},{"description":"A tensor of indices into the first dimension of `ref`.","name":"indices","typeAttr":"Tindices"},{"description":"A tensor of updated values to store in `ref`.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"= Same as `ref`. Returned as a convenience for operations that want\nto use the updated values after the update is done.","isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Applies sparse updates to a variable reference."}},{"name":"SdcaFprint","schema":{"inputs":[{"description":"vector of strings to compute fingerprints on.","name":"input","type":7}],"outputs":[{"description":"a (N,2) shaped matrix where N is the number of elements in the input\nvector. Each row contains the low and high parts of the fingerprint.","name":"output","type":9}],"summary":"Computes fingerprints of the input strings."}},{"name":"SdcaOptimizer","schema":{"attributes":[{"description":"Type of the primal loss. Currently SdcaSolver supports logistic,\nsquared and hinge losses. Must be one of the following: `logistic_loss`, `squared_loss`, `hinge_loss`, `smooth_hinge_loss`, `poisson_loss`.","name":"loss_type","type":"string"},{"default":false,"description":"Whether to use Adaptive SDCA for the inner loop.","name":"adaptative","type":"boolean"},{"description":"Number of sparse feature groups to train on.","minimum":0,"name":"num_sparse_features","type":"int64"},{"description":"Number of sparse feature groups with values\nassociated with it, otherwise implicitly treats values as 1.0.","minimum":0,"name":"num_sparse_features_with_values","type":"int64"},{"description":"Number of dense feature groups to train on.","minimum":0,"name":"num_dense_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength.","name":"l2","type":"float32"},{"description":"Number of partitions of the global loss function.","minimum":1,"name":"num_loss_partitions","type":"int64"},{"description":"Number of iterations per mini-batch.","minimum":1,"name":"num_inner_iterations","type":"int64"}],"description":"linear models with L1 + L2 regularization. As global optimization objective is\nstrongly-convex, the optimizer optimizes the dual objective at each step. The\noptimizer applies each update one example at a time. Examples are sampled\nuniformly, and the optimizer is learning rate free and enjoys linear convergence\nrate.\n\n[Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
    \nShai Shalev-Shwartz, Tong Zhang. 2012\n\n$$Loss Objective = \\sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$\n\n[Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
    \nChenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan,\nPeter Richtarik, Martin Takac. 2015\n\n[Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
    \nDominik Csiba, Zheng Qu, Peter Richtarik. 2015","inputs":[{"description":"a list of vectors which contain example indices.","name":"sparse_example_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contain feature indices.","name":"sparse_feature_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contains feature value\nassociated with each feature group.","name":"sparse_feature_values","numberAttr":"num_sparse_features_with_values","type":1},{"description":"a list of matrices which contains the dense feature values.","name":"dense_features","numberAttr":"num_dense_features","type":1},{"description":"a vector which contains the weight associated with each\nexample.","name":"example_weights","type":1},{"description":"a vector which contains the label/target associated with each\nexample.","name":"example_labels","type":1},{"description":"a list of vectors where each value is the indices which has\ncorresponding weights in sparse_weights. This field maybe omitted for the\ndense approach.","name":"sparse_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors where each value is the weight associated with\na sparse feature group.","name":"sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the weights associated\nwith a dense feature group.","name":"dense_weights","numberAttr":"num_dense_features","type":1},{"description":"a list of vectors containing the example state data.","name":"example_state_data","type":1}],"outputs":[{"description":"a list of vectors containing the updated example state\ndata.","name":"out_example_state_data","type":1},{"description":"a list of vectors where each value is the delta\nweights associated with a sparse feature group.","name":"out_delta_sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the delta\nweights associated with a dense feature group.","name":"out_delta_dense_weights","numberAttr":"num_dense_features","type":1}],"summary":"Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for"}},{"name":"SdcaOptimizerV2","schema":{"attributes":[{"description":"Type of the primal loss. Currently SdcaSolver supports logistic,\nsquared and hinge losses. Must be one of the following: `logistic_loss`, `squared_loss`, `hinge_loss`, `smooth_hinge_loss`, `poisson_loss`.","name":"loss_type","type":"string"},{"default":false,"description":"Whether to use Adaptive SDCA for the inner loop.","name":"adaptive","type":"boolean"},{"description":"Number of sparse feature groups to train on.","minimum":0,"name":"num_sparse_features","type":"int64"},{"description":"Number of sparse feature groups with values\nassociated with it, otherwise implicitly treats values as 1.0.","minimum":0,"name":"num_sparse_features_with_values","type":"int64"},{"description":"Number of dense feature groups to train on.","minimum":0,"name":"num_dense_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength.","name":"l2","type":"float32"},{"description":"Number of partitions of the global loss function.","minimum":1,"name":"num_loss_partitions","type":"int64"},{"description":"Number of iterations per mini-batch.","minimum":1,"name":"num_inner_iterations","type":"int64"}],"description":"linear models with L1 + L2 regularization. As global optimization objective is\nstrongly-convex, the optimizer optimizes the dual objective at each step. The\noptimizer applies each update one example at a time. Examples are sampled\nuniformly, and the optimizer is learning rate free and enjoys linear convergence\nrate.\n\n[Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
    \nShai Shalev-Shwartz, Tong Zhang. 2012\n\n$$Loss Objective = \\sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$\n\n[Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
    \nChenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan,\nPeter Richtarik, Martin Takac. 2015\n\n[Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
    \nDominik Csiba, Zheng Qu, Peter Richtarik. 2015","inputs":[{"description":"a list of vectors which contain example indices.","name":"sparse_example_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contain feature indices.","name":"sparse_feature_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors which contains feature value\nassociated with each feature group.","name":"sparse_feature_values","numberAttr":"num_sparse_features_with_values","type":1},{"description":"a list of matrices which contains the dense feature values.","name":"dense_features","numberAttr":"num_dense_features","type":1},{"description":"a vector which contains the weight associated with each\nexample.","name":"example_weights","type":1},{"description":"a vector which contains the label/target associated with each\nexample.","name":"example_labels","type":1},{"description":"a list of vectors where each value is the indices which has\ncorresponding weights in sparse_weights. This field maybe omitted for the\ndense approach.","name":"sparse_indices","numberAttr":"num_sparse_features","type":9},{"description":"a list of vectors where each value is the weight associated with\na sparse feature group.","name":"sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the weights associated\nwith a dense feature group.","name":"dense_weights","numberAttr":"num_dense_features","type":1},{"description":"a list of vectors containing the example state data.","name":"example_state_data","type":1}],"outputs":[{"description":"a list of vectors containing the updated example state\ndata.","name":"out_example_state_data","type":1},{"description":"a list of vectors where each value is the delta\nweights associated with a sparse feature group.","name":"out_delta_sparse_weights","numberAttr":"num_sparse_features","type":1},{"description":"a list of vectors where the values are the delta\nweights associated with a dense feature group.","name":"out_delta_dense_weights","numberAttr":"num_dense_features","type":1}],"summary":"Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for"}},{"name":"SdcaShrinkL1","schema":{"attributes":[{"description":"Number of feature groups to apply shrinking step.","minimum":0,"name":"num_features","type":"int64"},{"description":"Symmetric l1 regularization strength.","name":"l1","type":"float32"},{"description":"Symmetric l2 regularization strength. Should be a positive float.","name":"l2","type":"float32"}],"inputs":[{"description":"a list of vectors where each value is the weight associated with a\nfeature group.","isRef":true,"name":"weights","numberAttr":"num_features","type":1}],"summary":"Applies L1 regularization shrink step on the parameters."}},{"name":"SegmentMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\max_j(data_j)\\\\) where `max` is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the max is empty for a given segment ID `i`, `output[i] = 0`.\n\n
    \n\n
    \n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_max(c, tf.constant([0, 0, 1]))\n# ==> [[4, 3, 3, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum along segments of a tensor."}},{"name":"SegmentMean","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\frac{\\sum_j data_j}{N}\\\\) where `mean` is\nover `j` such that `segment_ids[j] == i` and `N` is the total number of\nvalues summed.\n\nIf the mean is empty for a given segment ID `i`, `output[i] = 0`.\n\n
    \n\n
    \n\nFor example:\n\n```\nc = tf.constant([[1.0,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_mean(c, tf.constant([0, 0, 1]))\n# ==> [[2.5, 2.5, 2.5, 2.5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along segments of a tensor."}},{"name":"SegmentMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\min_j(data_j)\\\\) where `min` is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the min is empty for a given segment ID `i`, `output[i] = 0`.\n\n
    \n\n
    \n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_min(c, tf.constant([0, 0, 1]))\n# ==> [[1, 2, 2, 1],\n# [5, 6, 7, 8]]\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum along segments of a tensor."}},{"name":"SegmentProd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\prod_j data_j\\\\) where the product is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the product is empty for a given segment ID `i`, `output[i] = 1`.\n\n
    \n\n
    \n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_prod(c, tf.constant([0, 0, 1]))\n# ==> [[4, 6, 6, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the product along segments of a tensor."}},{"name":"SegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output_i = \\sum_j data_j\\\\) where sum is over `j` such\nthat `segment_ids[j] == i`.\n\nIf the sum is empty for a given segment ID `i`, `output[i] = 0`.\n\n
    \n\n
    \n\nFor example:\n\n```\nc = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]])\ntf.segment_sum(c, tf.constant([0, 0, 1]))\n# ==> [[5, 5, 5, 5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor whose size is equal to the size of `data`'s\nfirst dimension. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tindices"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along segments of a tensor."}},{"name":"Select","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The `t`, and `e` tensors must all have the same shape, and the\noutput will also have that shape.\n\nThe `condition` tensor must be a scalar if `t` and `e` are scalars.\nIf `t` and `e` are vectors or higher rank, then `condition` must be either a\nscalar, a vector with size matching the first dimension of `t`, or must have\nthe same shape as `t`.\n\nThe `condition` tensor acts as a mask that chooses, based on the value at each\nelement, whether the corresponding element / row in the output should be\ntaken from `t` (if true) or `e` (if false).\n\nIf `condition` is a vector and `t` and `e` are higher rank matrices, then\nit chooses which row (outer dimension) to copy from `t` and `e`.\nIf `condition` has the same shape as `t` and `e`, then it chooses which\nelement to copy from `t` and `e`.\n\nFor example:\n\n```python\n# 'condition' tensor is [[True, False]\n# [False, True]]\n# 't' is [[1, 2],\n# [3, 4]]\n# 'e' is [[5, 6],\n# [7, 8]]\nselect(condition, t, e) # => [[1, 6], [7, 4]]\n\n\n# 'condition' tensor is [True, False]\n# 't' is [[1, 2],\n# [3, 4]]\n# 'e' is [[5, 6],\n# [7, 8]]\nselect(condition, t, e) ==> [[1, 2],\n [7, 8]]\n\n```","inputs":[{"name":"condition","type":10},{"description":"= A `Tensor` which may have the same shape as `condition`.\nIf `condition` is rank 1, `t` may have higher rank,\nbut its first dimension must match the size of `condition`.","name":"t","typeAttr":"T"},{"description":"= A `Tensor` with the same type and shape as `t`.","name":"e","typeAttr":"T"}],"outputs":[{"description":"= A `Tensor` with the same type and shape as `t` and `e`.","name":"output","typeAttr":"T"}],"summary":"Selects elements from `t` or `e`, depending on `condition`."}},{"name":"SelectV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"condition","type":10},{"name":"t","typeAttr":"T"},{"name":"e","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}]}},{"name":"SelfAdjointEig","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `float16`.","name":"T","type":"type"}],"description":"The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\nform square matrices, with the same constraints as the single matrix\nSelfAdjointEig.\n\nThe result is a [..., M+1, M] matrix with [..., 0,:] containing the\neigenvalues, and subsequent [...,1:, :] containing the eigenvectors. The eigenvalues\nare sorted in non-decreasing order.","inputs":[{"description":"Shape is `[..., M, M]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Shape is `[..., M+1, M]`.","name":"output","typeAttr":"T"}],"summary":"Computes the Eigen Decomposition of a batch of square self-adjoint matrices."}},{"name":"SelfAdjointEigV2","schema":{"attributes":[{"default":true,"description":"If `True` then eigenvectors will be computed and returned in `v`.\nOtherwise, only the eigenvalues will be computed.","name":"compute_v","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the eigenvalues and (optionally) eigenvectors of each inner matrix in\n`input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues\nare sorted in non-decreasing order.\n\n```python\n# a is a tensor.\n# e is a tensor of eigenvalues.\n# v is a tensor of eigenvectors.\ne, v = self_adjoint_eig(a)\ne = self_adjoint_eig(a, compute_v=False)\n```","inputs":[{"description":"`Tensor` input of shape `[N, N]`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Eigenvalues. Shape is `[N]`.","name":"e","typeAttr":"T"},{"description":"Eigenvectors. Shape is `[N, N]`.","name":"v","typeAttr":"T"}],"summary":"Computes the eigen decomposition of one or more square self-adjoint matrices."}},{"name":"Selu","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"if < 0, `scale * features` otherwise.\n\nTo be used together with\n`initializer = tf.variance_scaling_initializer(factor=1.0, mode='FAN_IN')`.\nFor correct dropout, use `tf.contrib.nn.alpha_dropout`.\n\nSee [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)","inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)`"}},{"name":"SeluGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding Selu operation.","name":"gradients","typeAttr":"T"},{"description":"The outputs of the corresponding Selu operation.","name":"outputs","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients * (outputs + scale * alpha)`\nif outputs < 0, `scale * gradients` otherwise.","name":"backprops","typeAttr":"T"}],"summary":"Computes gradients for the scaled exponential linear (Selu) operation."}},{"name":"Send","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The name of the tensor to send.","name":"tensor_name","type":"string"},{"description":"The name of the device sending the tensor.","name":"send_device","type":"string"},{"description":"The current incarnation of send_device.","name":"send_device_incarnation","type":"int64"},{"description":"The name of the device receiving the tensor.","name":"recv_device","type":"string"},{"default":false,"description":"If set to true, this indicates that the node was added\nto the graph as a result of a client-side feed or fetch of Tensor data,\nin which case the corresponding send or recv is expected to be managed\nlocally by the caller.","name":"client_terminated","type":"boolean"}],"inputs":[{"description":"The tensor to send.","name":"tensor","typeAttr":"T"}],"summary":"Sends the named tensor from send_device to recv_device."}},{"name":"SendTPUEmbeddingGradients","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":0,"minimum":0,"name":"NN","type":"int64"},{"description":"Serialized TPUEmbeddingConfiguration proto.","name":"config","type":"string"}],"inputs":[{"description":"A TensorList of gradients with which to update embedding tables.\nThis argument has the same length and shapes as the return value of\nRecvTPUEmbeddingActivations, but contains gradients of the model's loss\nwith respect to the embedding activations. The embedding tables are updated\nfrom these gradients via the optimizer specified in the TPU embedding\nconfiguration given to tpu.initialize_system.","name":"inputs","numberAttr":"N","type":1},{"description":"A TensorList of float32 scalars, one for each dynamic learning\nrate tag: see the comments in\n//third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto.\nMultiple tables can share the same dynamic learning rate tag as specified\nin the configuration. If the learning rates for all tables are constant,\nthis list should be empty.","name":"learning_rates","numberAttr":"NN","type":1}],"summary":"Performs gradient updates of embedding tables."}},{"name":"SerializeIterator","schema":{"attributes":[{"default":0,"name":"external_state_policy","type":"int64"}],"inputs":[{"description":"A handle to an iterator resource.","name":"resource_handle","type":20}],"outputs":[{"description":"A variant tensor storing the state of the iterator contained in the\nresource.","name":"serialized","type":21}],"summary":"Converts the given `resource_handle` representing an iterator to a variant tensor."}},{"name":"SerializeManySparse","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":7},"description":"The `dtype` to use for serialization; the supported types are `string`\n(default) and `variant`. Must be one of the following: `string`, `variant`.","name":"out_type","type":"type"}],"description":"The `SparseTensor` must have rank `R` greater than 1, and the first dimension\nis treated as the minibatch dimension. Elements of the `SparseTensor`\nmust be sorted in increasing order of this first dimension. The serialized\n`SparseTensor` objects going into each row of `serialized_sparse` will have\nrank `R-1`.\n\nThe minibatch size `N` is extracted from `sparse_shape[0]`.","inputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"name":"serialized_sparse","typeAttr":"out_type"}],"summary":"Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object."}},{"name":"SerializeSparse","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":7},"description":"The `dtype` to use for serialization; the supported types are `string`\n(default) and `variant`. Must be one of the following: `string`, `variant`.","name":"out_type","type":"type"}],"inputs":[{"description":"2-D. The `indices` of the `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the `SparseTensor`.","name":"sparse_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`.","name":"sparse_shape","type":9}],"outputs":[{"name":"serialized_sparse","typeAttr":"out_type"}],"summary":"Serialize a `SparseTensor` into a `[3]` `Tensor` object."}},{"name":"SerializeTensor","schema":{"attributes":[{"description":"The type of the input tensor.","name":"T","type":"type"}],"inputs":[{"description":"A Tensor of type `T`.","name":"tensor","typeAttr":"T"}],"outputs":[{"description":"A serialized TensorProto proto of the input tensor.","name":"serialized","type":7}],"summary":"Transforms a Tensor into a serialized TensorProto proto."}},{"name":"SetSize","schema":{"attributes":[{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"Input `set` is a `SparseTensor` represented by `set_indices`, `set_values`,\nand `set_shape`. The last dimension contains values in a set, duplicates are\nallowed but ignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set`\nindices.","inputs":[{"description":"2D `Tensor`, indices of a `SparseTensor`.","name":"set_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`.","name":"set_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`.","name":"set_shape","type":9}],"outputs":[{"description":"For `set` ranked `n`, this is a `Tensor` with rank `n-1`, and the same 1st\n`n-1` dimensions as `set`. Each value is the number of unique elements in\nthe corresponding `[0...n-1]` dimension of `set`.","name":"size","type":3}],"summary":"Number of unique elements along last dimension of input `set`."}},{"name":"SetStatsAggregatorDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"stats_aggregator","type":20},{"name":"tag","type":7},{"name":"counter_prefix","type":7}],"outputs":[{"name":"handle","type":21}]}},{"name":"Shape","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns a 1-D integer tensor representing the shape of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\nshape(t) ==> [2, 2, 3]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the shape of a tensor."}},{"name":"ShapeN","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns N 1-D integer tensors representing shape of `input[i]s`.","inputs":[{"name":"input","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"output","numberAttr":"N","typeAttr":"out_type"}],"summary":"Returns shape of tensors."}},{"name":"ShardDataset","schema":{"attributes":[{"default":false,"name":"require_non_empty","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"An integer representing the number of shards operating in parallel.","name":"num_shards","type":9},{"description":"An integer representing the current worker index.","name":"index","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a `Dataset` that includes only 1/`num_shards` of this dataset."}},{"name":"ShardedFilename","schema":{"description":" %s-%05d-of-%05d, basename, shard, num_shards.","inputs":[{"name":"basename","type":7},{"name":"shard","type":3},{"name":"num_shards","type":3}],"outputs":[{"name":"filename","type":7}],"summary":"Generate a sharded filename. The filename is printf formatted as"}},{"name":"ShardedFilespec","schema":{"inputs":[{"name":"basename","type":7},{"name":"num_shards","type":3}],"outputs":[{"name":"filename","type":7}],"summary":"Generate a glob pattern matching all sharded file names."}},{"name":"ShuffleAndRepeatDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":true,"name":"reshuffle_each_iteration","type":"boolean"}],"description":"pseudorandomly.","inputs":[{"name":"input_dataset","type":21},{"description":"The number of output elements to buffer in an iterator over\nthis dataset. Compare with the `min_after_dequeue` attr when creating a\n`RandomShuffleQueue`.","name":"buffer_size","type":9},{"description":"A scalar seed for the random number generator. If either `seed` or\n`seed2` is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9},{"description":"A scalar representing the number of times the underlying dataset\nshould be repeated. The default is `-1`, which results in infinite repetition.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shuffles and repeats elements from `input_dataset`"}},{"name":"ShuffleAndRepeatDatasetV2","schema":{"attributes":[{"default":true,"name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"count","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShuffleDataset","schema":{"attributes":[{"default":true,"description":"If true, each iterator over this dataset will be given\na different pseudorandomly generated seed, based on a sequence seeded by the\n`seed` and `seed2` inputs. If false, each iterator will be given the same\nseed, and repeated iteration over this dataset will yield the exact same\nsequence of results.","name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"The number of output elements to buffer in an iterator over\nthis dataset. Compare with the `min_after_dequeue` attr when creating a\n`RandomShuffleQueue`.","name":"buffer_size","type":9},{"description":"A scalar seed for the random number generator. If either `seed` or\n`seed2` is set to be non-zero, the random number generator is seeded\nby the given seed. Otherwise, a random seed is used.","name":"seed","type":9},{"description":"A second scalar seed to avoid seed collision.","name":"seed2","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that shuffles elements from `input_dataset` pseudorandomly."}},{"name":"ShuffleDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShuffleDatasetV3","schema":{"attributes":[{"default":true,"name":"reshuffle_each_iteration","type":"boolean"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"buffer_size","type":9},{"name":"seed","type":9},{"name":"seed2","type":9},{"name":"seed_generator","type":20}],"outputs":[{"name":"handle","type":21}]}},{"name":"ShutdownDistributedTPU","schema":{"description":"The op returns an error if no system is running.","summary":"Shuts down a running distributed TPU system."}},{"name":"Sigmoid","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"category":"Activation","description":"Specifically, `y = 1 / (1 + exp(-x))`.","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes sigmoid of `x` element-wise."}},{"name":"SigmoidGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * y * (1 - y)`, where `y = sigmoid(x)`, and\n`dy` is the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient of the sigmoid of `x` wrt its input."}},{"name":"Sign","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"`y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`.\n\nFor complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`.\n\nExample usage:\n>>> tf.math.sign([0., 2., -3.])\n","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Returns an element-wise indication of the sign of a number."}},{"name":"Sin","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes sine of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `[-1,1]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10, float(\"inf\")])\n tf.math.sin(x) ==> [nan -0.4121185 -0.47942555 0.84147096 0.9320391 -0.87329733 -0.54402107 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes sine of x element-wise."}},{"name":"Sinh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic sine of every\n element in the tensor. Input range is `[-inf,inf]` and output range\n is `[-inf,inf]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 2, 10, float(\"inf\")])\n tf.math.sinh(x) ==> [-inf -4.0515420e+03 -5.2109528e-01 1.1752012e+00 1.5094614e+00 3.6268604e+00 1.1013232e+04 inf]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic sine of x element-wise."}},{"name":"Size","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns an integer representing the number of elements in\n`input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1,, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]\nsize(t) ==> 12\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the size of a tensor."}},{"name":"SkipDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements from the `input_dataset`\nthat should be skipped. If count is -1, skips everything.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that skips `count` elements from the `input_dataset`."}},{"name":"Skipgram","schema":{"attributes":[{"description":"The corpus's text file name.","name":"filename","type":"string"},{"description":"The size of produced batch.","name":"batch_size","type":"int64"},{"default":5,"description":"The number of words to predict to the left and right of the target.","name":"window_size","type":"int64"},{"default":5,"description":"The minimum number of word occurrences for it to be included in the\nvocabulary.","name":"min_count","type":"int64"},{"default":0.0010000000474974513,"description":"Threshold for word occurrence. Words that appear with higher\nfrequency will be randomly down-sampled. Set to 0 to disable.","name":"subsample","type":"float32"}],"outputs":[{"description":"A vector of words in the corpus.","name":"vocab_word","type":7},{"description":"Frequencies of words. Sorted in the non-ascending order.","name":"vocab_freq","type":3},{"description":"Number of words per epoch in the data file.","name":"words_per_epoch","type":9},{"description":"The current epoch number.","name":"current_epoch","type":3},{"description":"The total number of words processed so far.","name":"total_words_processed","type":9},{"description":"A vector of word ids.","name":"examples","type":3},{"description":"A vector of word ids.","name":"labels","type":3}],"summary":"Parses a text file and creates a batch of examples."}},{"name":"SleepDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"name":"sleep_microseconds","type":9}],"outputs":[{"name":"handle","type":21}]}},{"name":"Slice","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"}],"category":"Tensor","description":"The output tensor is a tensor with dimensions described by 'size'\nwhose values are extracted from 'input' starting at the offsets in\n'begin'.\n\n*Requirements*:\n 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n)","inputs":[{"name":"input","typeAttr":"T"},{"description":"begin[i] specifies the offset into the 'i'th dimension of\n'input' to slice from.","name":"begin","typeAttr":"Index"},{"description":"size[i] specifies the number of elements of the 'i'th dimension\nof 'input' to slice. If size[i] is -1, all remaining elements in dimension\ni are included in the slice (i.e. this is equivalent to setting\nsize[i] = input.dim_size(i) - begin[i]).","name":"size","typeAttr":"Index"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a slice from 'input'."}},{"name":"SlidingWindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements in the\nsliding window.","name":"window_size","type":9},{"description":"A scalar representing the steps moving the sliding window\nforward in one iteration. It must be positive.","name":"window_shift","type":9},{"description":"A scalar representing the stride of the input elements of the sliding window.\nIt must be positive.","name":"window_stride","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that passes a sliding window over `input_dataset`."}},{"name":"Snapshot","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns a copy of the input tensor."}},{"name":"SnapshotDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","name":"compression","type":"string"},{"default":"","name":"reader_path_prefix","type":"string"},{"default":"","name":"writer_path_prefix","type":"string"},{"default":10737418240,"name":"shard_size_bytes","type":"int64"},{"default":86400,"name":"pending_snapshot_expiry_seconds","type":"int64"},{"default":1,"name":"num_reader_threads","type":"int64"},{"default":1,"name":"reader_buffer_size","type":"int64"},{"default":1,"name":"num_writer_threads","type":"int64"},{"default":1,"name":"writer_buffer_size","type":"int64"},{"default":false,"name":"shuffle_on_read","type":"boolean"},{"default":0,"name":"seed","type":"int64"},{"default":0,"name":"seed2","type":"int64"},{"default":"auto","name":"mode","type":"string"},{"default":"","name":"snapshot_name","type":"string"}],"description":"This dataset attempts to determine whether a valid snapshot exists at the\n`snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`.\nIf not, it will run the preprocessing pipeline as usual, and write out a\nsnapshot of the data processed for future use.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"The path we should write snapshots to / read snapshots from.","name":"path","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that will write to / read from a snapshot."}},{"name":"SnapshotDatasetV2","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"default":"","description":"The type of compression to be applied to the saved snapshot files.","name":"compression","type":"string"},{"description":"Optional. A function to control how to read data from snapshot shards.","name":"reader_func","type":"function"},{"description":"Optional. A function to control how to shard data when writing a snapshot.","name":"shard_func","type":"function"},{"minimum":0,"name":"Treader_func_args","type":"type[]"},{"minimum":0,"name":"Tshard_func_args","type":"type[]"}],"description":"This dataset attempts to determine whether a valid snapshot exists at the\n`snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`.\nIf not, it will run the preprocessing pipeline as usual, and write out a\nsnapshot of the data processed for future use.","inputs":[{"description":"A variant tensor representing the input dataset.","name":"input_dataset","type":21},{"description":"The path we should write snapshots to / read snapshots from.","name":"path","type":7},{"name":"reader_func_other_args","typeListAttr":"Treader_func_args"},{"name":"shard_func_other_args","typeListAttr":"Tshard_func_args"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that will write to / read from a snapshot."}},{"name":"SobolSample","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the sample. One of: `float32` or `float64`. Must be one of the following: `float32`, `float64`.","name":"dtype","type":"type"}],"description":"Creates a Sobol sequence with `num_results` samples. Each sample has dimension\n`dim`. Skips the first `skip` samples.","inputs":[{"description":"Positive scalar `Tensor` representing each sample's dimension.","name":"dim","type":3},{"description":"Positive scalar `Tensor` of dtype int32. The number of Sobol points to return\nin the output.","name":"num_results","type":3},{"description":"Positive scalar `Tensor` of dtype int32. The number of initial points of the\nSobol sequence to skip.","name":"skip","type":3}],"outputs":[{"description":"`Tensor` of samples from Sobol sequence with `shape` [num_results, dim].","name":"samples","typeAttr":"dtype"}],"summary":"Generates points from the Sobol sequence."}},{"name":"Softmax","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"category":"Activation","description":"For each batch `i` and class `j` we have\n\n $$softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))$$","inputs":[{"description":"2-D with shape `[batch_size, num_classes]`.","name":"logits","typeAttr":"T"}],"outputs":[{"description":"Same shape as `logits`.","name":"softmax","typeAttr":"T"}],"summary":"Computes softmax activations."}},{"name":"SoftmaxCrossEntropyWithLogits","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"Inputs are the logits, not probabilities.","inputs":[{"description":"batch_size x num_classes matrix","name":"features","typeAttr":"T"},{"description":"batch_size x num_classes matrix\nThe caller must ensure that each batch of labels represents a valid\nprobability distribution.","name":"labels","typeAttr":"T"}],"outputs":[{"description":"Per example loss (batch_size vector).","name":"loss","typeAttr":"T"},{"description":"backpropagated gradients (batch_size x num_classes matrix).","name":"backprop","typeAttr":"T"}],"summary":"Computes softmax cross entropy cost and gradients to backpropagate."}},{"name":"Softplus","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes softplus: `log(exp(features) + 1)`."}},{"name":"SoftplusGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding softplus operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding softplus operation.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients / (1 + exp(-features))`.","name":"backprops","typeAttr":"T"}],"summary":"Computes softplus gradients for a softplus operation."}},{"name":"Softsign","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"features","typeAttr":"T"}],"outputs":[{"name":"activations","typeAttr":"T"}],"summary":"Computes softsign: `features / (abs(features) + 1)`."}},{"name":"SoftsignGrad","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"description":"The backpropagated gradients to the corresponding softsign operation.","name":"gradients","typeAttr":"T"},{"description":"The features passed as input to the corresponding softsign operation.","name":"features","typeAttr":"T"}],"outputs":[{"description":"The gradients: `gradients / (1 + abs(features)) ** 2`.","name":"backprops","typeAttr":"T"}],"summary":"Computes softsign gradients for a softsign operation."}},{"name":"SpaceToBatch","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"},{"minimum":2,"name":"block_size","type":"int64"}],"description":"This is a legacy version of the more general SpaceToBatchND.\n\nZero-pads and then rearranges (permutes) blocks of spatial data into batch.\nMore specifically, this op outputs a copy of the input tensor where values from\nthe `height` and `width` dimensions are moved to the `batch` dimension. After\nthe zero-padding, both `height` and `width` of the input must be divisible by the\nblock size.","inputs":[{"description":"4-D with shape `[batch, height, width, depth]`.","name":"input","typeAttr":"T"},{"description":"2-D tensor of non-negative integers with shape `[2, 2]`. It specifies\n the padding of the input with zeros across the spatial dimensions as follows:\n\n paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]\n\n The effective spatial dimensions of the zero-padded input tensor will be:\n\n height_pad = pad_top + height + pad_bottom\n width_pad = pad_left + width + pad_right\n\nThe attr `block_size` must be greater than one. It indicates the block size.\n\n * Non-overlapping blocks of size `block_size x block size` in the height and\n width dimensions are rearranged into the batch dimension at each location.\n * The batch of the output tensor is `batch * block_size * block_size`.\n * Both height_pad and width_pad must be divisible by block_size.\n\nThe shape of the output will be:\n\n [batch*block_size*block_size, height_pad/block_size, width_pad/block_size,\n depth]\n\nSome examples:\n\n(1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 1]` and value:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\n(2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 3]` and value:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[4, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\n(4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[8, 1, 2, 1]` and value:\n\n```\nx = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],\n [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]\n```\n\nAmong others, this operation is useful for reducing atrous convolution into\nregular convolution.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToBatch for 4-D tensors of type T."}},{"name":"SpaceToBatchND","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tblock_shape","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tpaddings","type":"type"}],"description":"This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into a\ngrid of blocks of shape `block_shape`, and interleaves these blocks with the\n\"batch\" dimension (0) such that in the output, the spatial dimensions\n`[1, ..., M]` correspond to the position within the grid, and the batch\ndimension combines both the position within a spatial block and the original\nbatch position. Prior to division into blocks, the spatial dimensions of the\ninput are optionally zero padded according to `paddings`. See below for a\nprecise description.","inputs":[{"description":"N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`,\nwhere spatial_shape has `M` dimensions.","name":"input","typeAttr":"T"},{"description":"1-D with shape `[M]`, all values must be >= 1.","name":"block_shape","typeAttr":"Tblock_shape"},{"description":"2-D with shape `[M, 2]`, all values must be >= 0.\n `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension\n `i + 1`, which corresponds to spatial dimension `i`. It is required that\n `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`.\n\nThis operation is equivalent to the following steps:\n\n1. Zero-pad the start and end of dimensions `[1, ..., M]` of the\n input according to `paddings` to produce `padded` of shape `padded_shape`.\n\n2. Reshape `padded` to `reshaped_padded` of shape:\n\n [batch] +\n [padded_shape[1] / block_shape[0],\n block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1],\n block_shape[M-1]] +\n remaining_shape\n\n3. Permute dimensions of `reshaped_padded` to produce\n `permuted_reshaped_padded` of shape:\n\n block_shape +\n [batch] +\n [padded_shape[1] / block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1]] +\n remaining_shape\n\n4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch\n dimension, producing an output tensor of shape:\n\n [batch * prod(block_shape)] +\n [padded_shape[1] / block_shape[0],\n ...,\n padded_shape[M] / block_shape[M-1]] +\n remaining_shape\n\nSome examples:\n\n(1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [2]], [[3], [4]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 1]` and value:\n\n```\n[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]\n```\n\n(2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThe output tensor has shape `[4, 1, 1, 3]` and value:\n\n```\n[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]\n```\n\n(3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and\n `paddings = [[0, 0], [0, 0]]`:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[4, 2, 2, 1]` and value:\n\n```\nx = [[[[1], [3]], [[9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n```\n\n(4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and\n paddings = `[[0, 0], [2, 0]]`:\n\n```\nx = [[[[1], [2], [3], [4]],\n [[5], [6], [7], [8]]],\n [[[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n```\n\nThe output tensor has shape `[8, 1, 3, 1]` and value:\n\n```\nx = [[[[0], [1], [3]]], [[[0], [9], [11]]],\n [[[0], [2], [4]]], [[[0], [10], [12]]],\n [[[0], [5], [7]]], [[[0], [13], [15]]],\n [[[0], [6], [8]]], [[[0], [14], [16]]]]\n```\n\nAmong others, this operation is useful for reducing atrous convolution into\nregular convolution.","name":"paddings","typeAttr":"Tpaddings"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToBatch for N-D tensors of type T."}},{"name":"SpaceToDepth","schema":{"attributes":[{"name":"T","type":"type"},{"description":"The size of the spatial block.","minimum":2,"name":"block_size","type":"int64"},{"default":"NHWC","description":"Must be one of the following: `NHWC`, `NCHW`, `NCHW_VECT_C`.","name":"data_format","type":"string"}],"description":"Rearranges blocks of spatial data, into depth. More specifically,\nthis op outputs a copy of the input tensor where values from the `height`\nand `width` dimensions are moved to the `depth` dimension.\nThe attr `block_size` indicates the input block size.\n\n * Non-overlapping blocks of size `block_size x block size` are rearranged\n into depth at each location.\n * The depth of the output tensor is `block_size * block_size * input_depth`.\n * The Y, X coordinates within each block of the input become the high order\n component of the output channel index.\n * The input tensor's height and width must be divisible by block_size.\n\nThe `data_format` attr specifies the layout of the input and output tensors\nwith the following options:\n \"NHWC\": `[ batch, height, width, channels ]`\n \"NCHW\": `[ batch, channels, height, width ]`\n \"NCHW_VECT_C\":\n `qint8 [ batch, channels / 4, height, width, 4 ]`\n\nIt is useful to consider the operation as transforming a 6-D Tensor.\ne.g. for data_format = NHWC,\n Each element in the input tensor can be specified via 6 coordinates,\n ordered by decreasing memory layout significance as:\n n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates\n within the output image, bX, bY means coordinates\n within the input block, iC means input channels).\n The output would be a transpose to the following layout:\n n,oY,oX,bY,bX,iC\n\nThis operation is useful for resizing the activations between convolutions\n(but keeping all data), e.g. instead of pooling. It is also useful for training\npurely convolutional models.\n\nFor example, given an input of shape `[1, 2, 2, 1]`, data_format = \"NHWC\" and\nblock_size = 2:\n\n```\nx = [[[[1], [2]],\n [[3], [4]]]]\n```\n\nThis operation will output a tensor of shape `[1, 1, 1, 4]`:\n\n```\n[[[[1, 2, 3, 4]]]]\n```\n\nHere, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`,\nthe corresponding output will have a single element (i.e. width and height are\nboth 1) and will have a depth of 4 channels (1 * block_size * block_size).\nThe output element shape is `[1, 1, 4]`.\n\nFor an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g.\n\n```\nx = [[[[1, 2, 3], [4, 5, 6]],\n [[7, 8, 9], [10, 11, 12]]]]\n```\n\nThis operation, for block_size of 2, will return the following tensor of shape\n`[1, 1, 1, 12]`\n\n```\n[[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]\n```\n\nSimilarly, for the following input of shape `[1 4 4 1]`, and a block size of 2:\n\n```\nx = [[[[1], [2], [5], [6]],\n [[3], [4], [7], [8]],\n [[9], [10], [13], [14]],\n [[11], [12], [15], [16]]]]\n```\n\nthe operator will return the following tensor of shape `[1 2 2 4]`:\n\n```\nx = [[[[1, 2, 3, 4],\n [5, 6, 7, 8]],\n [[9, 10, 11, 12],\n [13, 14, 15, 16]]]]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"SpaceToDepth for tensors of type T."}},{"name":"SparseAccumulatorApplyGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"Boolean indicating whether gradient_shape is unknown, in which\ncase the input is ignored during validation.","name":"has_known_shape","type":"boolean"}],"description":"Does not add if local_step is smaller than the accumulator's\nglobal_step.","inputs":[{"description":"The handle to a accumulator.","isRef":true,"name":"handle","type":7},{"description":"The local_step value at which the sparse gradient was computed.","name":"local_step","type":9},{"description":"Indices of the sparse gradient to be accumulated. Must be a\nvector.","name":"gradient_indices","type":9},{"description":"Values are the non-zero slices of the gradient, and must have\nthe same first dimension as indices, i.e., the nnz represented by indices and\nvalues must be consistent.","name":"gradient_values","typeAttr":"dtype"},{"description":"Shape of the sparse gradient to be accumulated.","name":"gradient_shape","type":9}],"summary":"Applies a sparse gradient to a given accumulator."}},{"name":"SparseAccumulatorTakeGradient","schema":{"attributes":[{"description":"The data type of accumulated gradients. Needs to correspond to the type\nof the accumulator. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"}],"description":"The op will blocks until sufficient (i.e., more than num_required)\ngradients have been accumulated. If the accumulator has already\naggregated more than num_required gradients, it will return its\naverage of the accumulated gradients. Also automatically increments\nthe recorded global_step in the accumulator by 1, and resets the\naggregate to 0.","inputs":[{"description":"The handle to a SparseConditionalAccumulator.","isRef":true,"name":"handle","type":7},{"description":"Number of gradients required before we return an aggregate.","name":"num_required","type":3}],"outputs":[{"description":"Indices of the average of the accumulated sparse gradients.","name":"indices","type":9},{"description":"Values of the average of the accumulated sparse gradients.","name":"values","typeAttr":"dtype"},{"description":"Shape of the average of the accumulated sparse gradients.","name":"shape","type":9}],"summary":"Extracts the average sparse gradient in a SparseConditionalAccumulator."}},{"name":"SparseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"Treal","type":"type"}],"description":"The input `SparseTensor` objects' indices are assumed ordered in standard\nlexicographic order. If this is not the case, before this step run\n`SparseReorder` to restore index ordering.\n\nBy default, if two values sum to zero at some index, the output `SparseTensor`\nwould still include that particular location in its index, storing a zero in the\ncorresponding value slot. To override this, callers can specify `thresh`,\nindicating that if the sum has a magnitude strictly smaller than `thresh`, its\ncorresponding value and index would then not be included. In particular,\n`thresh == 0` (default) means everything is kept and actual thresholding happens\nonly for a positive value.\n\nIn the following shapes, `nnz` is the count after taking `thresh` into account.","inputs":[{"description":"2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix.","name":"a_indices","type":9},{"description":"1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector.","name":"a_shape","type":9},{"description":"2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix.","name":"b_indices","type":9},{"description":"1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector.","name":"b_values","typeAttr":"T"},{"description":"1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector.","name":"b_shape","type":9},{"description":"0-D. The magnitude threshold that determines if an output value/index\npair takes space.","name":"thresh","typeAttr":"Treal"}],"outputs":[{"name":"sum_indices","type":9},{"name":"sum_values","typeAttr":"T"},{"name":"sum_shape","type":9}],"summary":"Adds two `SparseTensor` objects to produce another `SparseTensor`."}},{"name":"SparseAddGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The SparseAdd op calculates A + B, where A, B, and the sum are all represented\nas `SparseTensor` objects. This op takes in the upstream gradient w.r.t.\nnon-empty values of the sum, and outputs the gradients w.r.t. the non-empty\nvalues of A and B.","inputs":[{"description":"1-D with shape `[nnz(sum)]`. The gradient with respect to\nthe non-empty values of the sum.","name":"backprop_val_grad","typeAttr":"T"},{"description":"2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`.","name":"a_indices","type":9},{"description":"2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`.","name":"b_indices","type":9},{"description":"2-D. The `indices` of the sum `SparseTensor`, size\n`[nnz(sum), ndims]`.","name":"sum_indices","type":9}],"outputs":[{"description":"1-D with shape `[nnz(A)]`. The gradient with respect to the\nnon-empty values of A.","name":"a_val_grad","typeAttr":"T"},{"description":"1-D with shape `[nnz(B)]`. The gradient with respect to the\nnon-empty values of B.","name":"b_val_grad","typeAttr":"T"}],"summary":"The gradient operator for the SparseAdd op."}},{"name":"SparseApplyAdadelta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":": Should be from a Variable().","isRef":true,"name":"accum_update","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay factor. Must be a scalar.","name":"rho","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"var: Should be from a Variable()."}},{"name":"SparseApplyAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$var -= lr * grad * (1 / sqrt(accum))$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"SparseApplyAdagradDA","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_accumulator","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"gradient_squared_accumulator","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Training step number. Must be a scalar.","name":"global_step","type":9}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update entries in '*var' and '*accum' according to the proximal adagrad scheme."}},{"name":"SparseApplyAdagradV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":true,"name":"update_slots","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$var -= lr * grad * (1 / sqrt(accum))$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Constant factor. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the adagrad scheme."}},{"name":"SparseApplyCenteredRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, mg, ms, and mom tensors is\nprotected by a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"The centered RMSProp algorithm uses an estimate of the centered second moment\n(i.e., the variance) for normalization, as opposed to regular RMSProp, which\nuses the (uncentered) second moment. This often helps with training, but is\nslightly more expensive in terms of computation and memory.\n\nNote that in dense implementation of this algorithm, mg, ms, and mom will\nupdate even if the grad is zero, but in this sparse implementation, mg, ms,\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nmean_grad = decay * mean_grad + (1-decay) * gradient\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2)\n\n$$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$\n$$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$\n$$var <- var - mom$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mg","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the centered RMSProp algorithm."}},{"name":"SparseApplyFtrl","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\n$$accum_new = accum + grad * grad$$\n$$linear += grad + (accum_{new}^{-lr_{power}} - accum^{-lr_{power}} / lr * var$$\n$$quadratic = 1.0 / (accum_{new}^{lr_{power}} * lr) + 2 * l2$$\n$$var = (sign(linear) * l1 - linear) / quadratic\\ if\\ |linear| > l1\\ else\\ 0.0$$\n$$accum = accum_{new}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"SparseApplyFtrlV2","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"name":"multiply_linear_by_lr","type":"boolean"}],"description":"That is for rows we have grad for, we update var, accum and linear as follows:\ngrad_with_shrinkage = grad + 2 * l2_shrinkage * var\naccum_new = accum + grad * grad\nlinear += grad_with_shrinkage -\n (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var\nquadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2\nvar = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0\naccum = accum_new","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"linear","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 shrinkage regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"name":"l2_shrinkage","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr_power","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' according to the Ftrl-proximal scheme."}},{"name":"SparseApplyMomentum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var and accum tensors will be protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"},{"default":false,"description":"If `True`, the tensor passed to compute grad will be\nvar - lr * momentum * accum, so in the end, the var you get is actually\nvar - lr * momentum * accum.","name":"use_nesterov","type":"boolean"}],"description":"Set use_nesterov = True if you want to use Nesterov momentum.\n\nThat is for rows we have grad for, we update var and accum as follows:\n\n$$accum = accum * momentum + grad$$\n$$var -= lr * accum$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"},{"description":"Momentum. Must be a scalar.","name":"momentum","typeAttr":"T"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update relevant entries in '*var' and '*accum' according to the momentum scheme."}},{"name":"SparseApplyProximalAdagrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, updating of the var and accum tensors will be protected by\na lock; otherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var and accum as follows:\n$$accum += grad * grad$$\n$$prox_v = var$$\n$$prox_v -= lr * grad * (1 / sqrt(accum))$$\n$$var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"accum","typeAttr":"T"},{"description":"Learning rate. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Sparse update entries in '*var' and '*accum' according to FOBOS algorithm."}},{"name":"SparseApplyProximalGradientDescent","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If True, the subtraction will be protected by a lock;\notherwise the behavior is undefined, but may exhibit less contention.","name":"use_locking","type":"boolean"}],"description":"That is for rows we have grad for, we update var as follows:\n$$prox_v = var - alpha * grad$$\n$$var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"alpha","typeAttr":"T"},{"description":"L1 regularization. Must be a scalar.","name":"l1","typeAttr":"T"},{"description":"L2 regularization. Must be a scalar.","name":"l2","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var and accum.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Sparse update '*var' as FOBOS algorithm with fixed learning rate."}},{"name":"SparseApplyRMSProp","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"If `True`, updating of the var, ms, and mom tensors is protected\nby a lock; otherwise the behavior is undefined, but may exhibit less\ncontention.","name":"use_locking","type":"boolean"}],"description":"Note that in dense implementation of this algorithm, ms and mom will\nupdate even if the grad is zero, but in this sparse implementation, ms\nand mom will not update in iterations during which the grad is zero.\n\nmean_square = decay * mean_square + (1-decay) * gradient ** 2\nDelta = learning_rate * gradient / sqrt(mean_square + epsilon)\n\n$$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$\n$$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$\n$$var <- var - mom$$","inputs":[{"description":"Should be from a Variable().","isRef":true,"name":"var","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"ms","typeAttr":"T"},{"description":"Should be from a Variable().","isRef":true,"name":"mom","typeAttr":"T"},{"description":"Scaling factor. Must be a scalar.","name":"lr","typeAttr":"T"},{"description":"Decay rate. Must be a scalar.","name":"rho","typeAttr":"T"},{"name":"momentum","typeAttr":"T"},{"description":"Ridge term. Must be a scalar.","name":"epsilon","typeAttr":"T"},{"description":"The gradient.","name":"grad","typeAttr":"T"},{"description":"A vector of indices into the first dimension of var, ms and mom.","name":"indices","typeAttr":"Tindices"}],"outputs":[{"description":"Same as \"var\".","isRef":true,"name":"out","typeAttr":"T"}],"summary":"Update '*var' according to the RMSProp algorithm."}},{"name":"SparseBincount","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"description":"Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"T","type":"type"},{"default":false,"description":"bool; Whether the kernel should count the appearance or number of occurrences.","name":"binary_output","type":"boolean"}],"description":"Outputs a vector with length `size` and the same dtype as `weights`. If\n`weights` are empty, then index `i` stores the number of times the value `i` is\ncounted in `arr`. If `weights` are non-empty, then index `i` stores the sum of\nthe value in `weights` at each index where the corresponding value in `arr` is\n`i`.\n\nValues in `arr` outside of the range [0, size) are ignored.","inputs":[{"description":"2D int64 `Tensor`.","name":"indices","type":9},{"description":"1D int `Tensor`.","name":"values","typeAttr":"Tidx"},{"description":"1D int64 `Tensor`.","name":"dense_shape","type":9},{"description":"non-negative int scalar `Tensor`.","name":"size","typeAttr":"Tidx"},{"description":"is an int32, int64, float32, or float64 `Tensor` with the same\nshape as `input`, or a length-0 `Tensor`, in which case it acts as all weights\nequal to 1.","name":"weights","typeAttr":"T"}],"outputs":[{"description":"1D `Tensor` with length equal to `size` or 2D `Tensor` with [batch_size, `size`].\nThe counts or summed weights for each value in the range [0, size).","name":"output","typeAttr":"T"}],"summary":"Counts the number of occurrences of each value in an integer array."}},{"name":"SparseConcat","schema":{"attributes":[{"description":"Dimension to concatenate along. Must be in range [-rank, rank),\nwhere rank is the number of dimensions in each input `SparseTensor`.","name":"concat_dim","type":"int64"},{"minimum":2,"name":"N","type":"int64"},{"name":"T","type":"type"}],"description":"Concatenation is with respect to the dense versions of these sparse tensors.\nIt is assumed that each input is a `SparseTensor` whose elements are ordered\nalong increasing dimension number.\n\nAll inputs' shapes must match, except for the concat dimension. The\n`indices`, `values`, and `shapes` lists must have the same length.\n\nThe output shape is identical to the inputs', except along the concat\ndimension, where it is the sum of the inputs' sizes along that dimension.\n\nThe output elements will be resorted to preserve the sort order along\nincreasing dimension number.\n\nThis op runs in `O(M log M)` time, where `M` is the total number of non-empty\nvalues across all inputs. This is due to the need for an internal sort in\norder to concatenate efficiently across an arbitrary dimension.\n\nFor example, if `concat_dim = 1` and the inputs are\n\n sp_inputs[0]: shape = [2, 3]\n [0, 2]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n sp_inputs[1]: shape = [2, 4]\n [0, 1]: \"d\"\n [0, 2]: \"e\"\n\nthen the output will be\n\n shape = [2, 7]\n [0, 2]: \"a\"\n [0, 4]: \"d\"\n [0, 5]: \"e\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\nGraphically this is equivalent to doing\n\n [ a] concat [ d e ] = [ a d e ]\n [b c ] [ ] [b c ]","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. Non-empty values of each `SparseTensor`.","name":"values","numberAttr":"N","typeAttr":"T"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated `SparseTensor`.","name":"output_values","typeAttr":"T"},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Concatenates a list of `SparseTensor` along the specified dimension."}},{"name":"SparseConditionalAccumulator","schema":{"attributes":[{"description":"The type of the value being accumulated. Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"description":"The shape of the values.","name":"shape","type":"shape"},{"default":"","description":"If non-empty, this accumulator is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this accumulator will be shared under the given name\nacross multiple sessions.","name":"shared_name","type":"string"},{"default":"MEAN","description":"Must be one of the following: `MEAN`, `SUM`.","name":"reduction_type","type":"string"}],"description":"The accumulator accepts gradients marked with local_step greater or\nequal to the most recent global_step known to the accumulator. The\naverage can be extracted from the accumulator, provided sufficient\ngradients have been accumulated. Extracting the average automatically\nresets the aggregate to 0, and increments the global_step recorded by\nthe accumulator.","outputs":[{"description":"The handle to the accumulator.","isRef":true,"name":"handle","type":7}],"summary":"A conditional accumulator for aggregating sparse gradients."}},{"name":"SparseCountSparseOutput","schema":{"attributes":[{"description":"Dtype of the input values tensor. Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":-1,"description":"Minimum value to count. Can be set to -1 for no minimum.","minimum":-1,"name":"minlength","type":"int64"},{"default":-1,"description":"Maximum value to count. Can be set to -1 for no maximum.","minimum":-1,"name":"maxlength","type":"int64"},{"description":"Whether to output the number of occurrences of each value or 1.","name":"binary_output","type":"boolean"},{"description":"Dtype of the output values tensor. Must be one of the following: `int32`, `int64`, `float32`, `float64`.","name":"output_type","type":"type"}],"description":" Counts the number of times each value occurs in the input.","inputs":[{"description":"Tensor containing the indices of the sparse tensor to count.","name":"indices","type":9},{"description":"Tensor containing values of the sparse tensor to count.","name":"values","typeAttr":"T"},{"description":"Tensor containing the dense shape of the sparse tensor to count.","name":"dense_shape","type":9},{"description":"A Tensor of the same shape as indices containing per-index weight values.\nMay also be the empty tensor if no weights are used.","name":"weights","typeAttr":"output_type"}],"outputs":[{"description":"Indices tensor for the resulting sparse tensor object.","name":"output_indices","type":9},{"description":"Values tensor for the resulting sparse tensor object.","name":"output_values","typeAttr":"output_type"},{"description":"Shape tensor for the resulting sparse tensor object.","name":"output_dense_shape","type":9}],"summary":"Performs sparse-output bin counting for a sparse tensor input."}},{"name":"SparseCross","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"If true, returns the hash of the cross instead of the string.\nThis will allow us avoiding string manipulations.","name":"hashed_output","type":"boolean"},{"description":"It is used if hashed_output is true.\noutput = hashed_value%num_buckets if num_buckets > 0 else hashed_value.","minimum":0,"name":"num_buckets","type":"int64"},{"description":"Specify the hash_key that will be used by the `FingerprintCat64`\nfunction to combine the crosses fingerprints.","name":"hash_key","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","name":"out_type","type":"type"},{"description":"Must be one of the following: `int64`, `string`.","name":"internal_type","type":"type"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","typeAttr":"out_type"},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseCrossHashed","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"},{"description":"It is used if hashed_output is true.\noutput = hashed_value%num_buckets if num_buckets > 0 else hashed_value.","name":"num_buckets","type":9},{"description":"boolean, if true, siphash with salt will be used instead of farmhash.","name":"strong_hash","type":10},{"description":"Specify the salt that will be used by the siphash function.","name":"salt","type":9}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","type":9},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseCrossV2","schema":{"attributes":[{"minimum":0,"name":"N","type":"int64"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"sparse_types","type":"type[]"},{"description":"Must be one of the following: `int64`, `string`.","minimum":0,"name":"dense_types","type":"type[]"}],"description":"The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each\nrepresenting features of one feature column. It outputs a 2D `SparseTensor` with\nthe batchwise crosses of these features.\n\nFor example, if the inputs are\n\n inputs[0]: SparseTensor with shape = [2, 2]\n [0, 0]: \"a\"\n [1, 0]: \"b\"\n [1, 1]: \"c\"\n\n inputs[1]: SparseTensor with shape = [2, 1]\n [0, 0]: \"d\"\n [1, 0]: \"e\"\n\n inputs[2]: Tensor [[\"f\"], [\"g\"]]\n\nthen the output will be\n\n shape = [2, 2]\n [0, 0]: \"a_X_d_X_f\"\n [1, 0]: \"b_X_e_X_g\"\n [1, 1]: \"c_X_e_X_g\"\n\nif hashed_output=true then the output will be\n\n shape = [2, 2]\n [0, 0]: FingerprintCat64(\n Fingerprint64(\"f\"), FingerprintCat64(\n Fingerprint64(\"d\"), Fingerprint64(\"a\")))\n [1, 0]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"b\")))\n [1, 1]: FingerprintCat64(\n Fingerprint64(\"g\"), FingerprintCat64(\n Fingerprint64(\"e\"), Fingerprint64(\"c\")))","inputs":[{"description":"2-D. Indices of each input `SparseTensor`.","name":"indices","numberAttr":"N","type":9},{"description":"1-D. values of each `SparseTensor`.","name":"values","typeListAttr":"sparse_types"},{"description":"1-D. Shapes of each `SparseTensor`.","name":"shapes","numberAttr":"N","type":9},{"description":"2-D. Columns represented by dense `Tensor`.","name":"dense_inputs","typeListAttr":"dense_types"},{"description":"string used when joining a list of string inputs, can be used as separator later.","name":"sep","type":7}],"outputs":[{"description":"2-D. Indices of the concatenated `SparseTensor`.","name":"output_indices","type":9},{"description":"1-D. Non-empty values of the concatenated or hashed\n`SparseTensor`.","name":"output_values","type":7},{"description":"1-D. Shape of the concatenated `SparseTensor`.","name":"output_shape","type":9}],"summary":"Generates sparse cross from a list of sparse and dense tensors."}},{"name":"SparseDenseCwiseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"(1) Broadcasts the dense side to have the same shape as the sparse side, if\n eligible;\n(2) Then, only the dense values pointed to by the indices of the SparseTensor\n participate in the cwise addition.\n\nBy these rules, the result is a logical SparseTensor with exactly the same\nindices and shape, but possibly with different non-zero values. The output of\nthis Op is the resultant non-zero values.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Adds up a SparseTensor and a dense Tensor, using these special rules:"}},{"name":"SparseDenseCwiseDiv","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"*Limitation*: this Op only broadcasts the dense side to the sparse side, but not\nthe other direction.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Component-wise divides a SparseTensor by a dense Tensor."}},{"name":"SparseDenseCwiseMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"The output locations corresponding to the implicitly zero elements in the sparse\ntensor will be zero (i.e., will not take up storage space), regardless of the\ncontents of the dense tensor (even if it's +/-INF and that INF*0 == NaN).\n\n*Limitation*: this Op only broadcasts the dense side to the sparse side, but not\nthe other direction.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9},{"description":"`R`-D. The dense Tensor operand.","name":"dense","typeAttr":"T"}],"outputs":[{"description":"1-D. The `N` values that are operated on.","name":"output","typeAttr":"T"}],"summary":"Component-wise multiplies a SparseTensor by a dense Tensor."}},{"name":"SparseFillEmptyRows","schema":{"attributes":[{"name":"T","type":"type"}],"description":"The input `SparseTensor` is represented via the tuple of inputs\n(`indices`, `values`, `dense_shape`). The output `SparseTensor` has the\nsame `dense_shape` but with indices `output_indices` and values\n`output_values`.\n\nThis op inserts a single entry for every row that doesn't have any values.\nThe index is created as `[row, 0, ..., 0]` and the inserted value\nis `default_value`.\n\nFor example, suppose `sp_input` has shape `[5, 6]` and non-empty values:\n\n [0, 1]: a\n [0, 3]: b\n [2, 0]: c\n [3, 1]: d\n\nRows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values:\n\n [0, 1]: a\n [0, 3]: b\n [1, 0]: default_value\n [2, 0]: c\n [3, 1]: d\n [4, 0]: default_value\n\nThe output `SparseTensor` will be in row-major order and will have the\nsame shape as the input.\n\nThis op also returns an indicator vector shaped `[dense_shape[0]]` such that\n\n empty_row_indicator[i] = True iff row i was an empty row.\n\nAnd a reverse index map vector shaped `[indices.shape[0]]` that is used during\nbackpropagation,\n\n reverse_index_map[j] = out_j s.t. indices[j, :] == output_indices[out_j, :]","inputs":[{"description":"2-D. the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D. the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. the shape of the sparse tensor.","name":"dense_shape","type":9},{"description":"0-D. default value to insert into location `[row, 0, ..., 0]`\n for rows missing from the input sparse tensor.\noutput indices: 2-D. the indices of the filled sparse tensor.","name":"default_value","typeAttr":"T"}],"outputs":[{"name":"output_indices","type":9},{"description":"1-D. the values of the filled sparse tensor.","name":"output_values","typeAttr":"T"},{"description":"1-D. whether the dense row was missing in the\ninput sparse tensor.","name":"empty_row_indicator","type":10},{"description":"1-D. a map from the input indices to the output indices.","name":"reverse_index_map","type":9}],"summary":"Fills empty rows in the input 2-D `SparseTensor` with a default value."}},{"name":"SparseFillEmptyRowsGrad","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Takes vectors reverse_index_map, shaped `[N]`, and grad_values,\nshaped `[N_full]`, where `N_full >= N` and copies data into either\n`d_values` or `d_default_value`. Here `d_values` is shaped `[N]` and\n`d_default_value` is a scalar.\n\n d_values[j] = grad_values[reverse_index_map[j]]\n d_default_value = sum_{k : 0 .. N_full - 1} (\n grad_values[k] * 1{k not in reverse_index_map})","inputs":[{"description":"1-D. The reverse index map from SparseFillEmptyRows.","name":"reverse_index_map","type":9},{"description":"1-D. The gradients from backprop.","name":"grad_values","typeAttr":"T"}],"outputs":[{"description":"1-D. The backprop into values.","name":"d_values","typeAttr":"T"},{"description":"0-D. The backprop into default_value.","name":"d_default_value","typeAttr":"T"}],"summary":"The gradient of SparseFillEmptyRows."}},{"name":"SparseMatMul","schema":{"attributes":[{"default":false,"name":"transpose_a","type":"boolean"},{"default":false,"name":"transpose_b","type":"boolean"},{"default":false,"name":"a_is_sparse","type":"boolean"},{"default":false,"name":"b_is_sparse","type":"boolean"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `bfloat16`.","name":"Ta","type":"type"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `bfloat16`.","name":"Tb","type":"type"}],"description":"The inputs must be two-dimensional matrices and the inner dimension of \"a\" must\nmatch the outer dimension of \"b\". Both \"a\" and \"b\" must be `Tensor`s not\n`SparseTensor`s. This op is optimized for the case where at least one of \"a\" or\n\"b\" is sparse, in the sense that they have a large proportion of zero values.\nThe breakeven for using this versus a dense matrix multiply on one platform was\n30% zero values in the sparse matrix.\n\nThe gradient computation of this operation will only take advantage of sparsity\nin the input gradient when that gradient comes from a Relu.","inputs":[{"name":"a","typeAttr":"Ta"},{"name":"b","typeAttr":"Tb"}],"outputs":[{"name":"product","type":1}],"summary":"Multiply matrix \"a\" by matrix \"b\"."}},{"name":"SparseMatrixAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"The gradients of SparseMatrixAdd outputs with respect to alpha and beta are not\ncurrently defined (TensorFlow will return zeros for these entries).","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A CSRSparseMatrix.","name":"b","type":21},{"description":"A constant scalar.","name":"alpha","typeAttr":"T"},{"description":"A constant scalar.","name":"beta","typeAttr":"T"}],"outputs":[{"description":"A CSRSparseMatrix.","name":"c","type":21}],"summary":"Sparse addition of two CSR matrices, C = alpha * A + beta * B."}},{"name":"SparseMatrixMatMul","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"description":"Indicates whether `a` should be transposed.","name":"transpose_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be transposed.","name":"transpose_b","type":"boolean"},{"default":false,"description":"Indicates whether `a` should be conjugate-transposed.","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be conjugate-transposed.","name":"adjoint_b","type":"boolean"},{"default":false,"description":"Transposes the product of `a` and `b`.","name":"transpose_output","type":"boolean"},{"default":false,"description":"Conjugates the product of `a` and `b`.","name":"conjugate_output","type":"boolean"}],"description":"Returns a dense matrix.\nFor inputs A and B, where A is CSR and B is dense; this op returns a dense C;\n\nIf transpose_output is false, returns:\n```\n C = A . B\n```\n\nIf transpose_output is `true`, returns:\n```\n C = transpose(A . B) = transpose(B) . transpose(A)\n```\nwhere the transposition is performed along the two innermost (matrix)\ndimensions.\n\nIf conjugate_output is `true`, returns:\n```\n C = conjugate(A . B) = conjugate(A) . conjugate(B)\n```\n\nIf both conjugate_output and transpose_output are `true`, returns:\n```\n C = conjugate(transpose(A . B)) = conjugate(transpose(B)) .\n conjugate(transpose(A))\n```","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A dense tensor.","name":"b","typeAttr":"T"}],"outputs":[{"description":"A dense output tensor.","name":"output","typeAttr":"T"}],"summary":"Matrix-multiplies a sparse matrix with a dense matrix."}},{"name":"SparseMatrixMul","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Returns a sparse matrix.\n\nThe dense tensor `b` may be either a scalar; otherwise `a` must be a rank-3\n`SparseMatrix`; in this case `b` must be shaped `[batch_size, 1, 1]` and the\nmultiply operation broadcasts.\n\n**NOTE** even if `b` is zero, the sparsity structure of the output does not\nchange.","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A dense tensor.","name":"b","typeAttr":"T"}],"outputs":[{"description":"A dense output tensor.","name":"output","type":21}],"summary":"Element-wise multiplication of a sparse matrix with a dense tensor."}},{"name":"SparseMatrixNNZ","schema":{"inputs":[{"description":"A CSRSparseMatrix.","name":"sparse_matrix","type":21}],"outputs":[{"description":"The number of nonzeroes of `sparse_matrix`.","name":"nnz","type":3}],"summary":"Returns the number of nonzeroes of `sparse_matrix`."}},{"name":"SparseMatrixOrderingAMD","schema":{"description":"Computes the Approximate Minimum Degree (AMD) ordering for a sparse matrix.\n\nThe returned permutation may be used to permute the rows and columns of the\ngiven sparse matrix. This typically results in permuted sparse matrix's sparse\nCholesky (or other decompositions) in having fewer zero fill-in compared to\ndecomposition of the original matrix.\n\nThe input sparse matrix may have rank 2 or rank 3. The output Tensor,\nrepresenting would then have rank 1 or 2 respectively, with the same batch\nshape as the input.\n\nEach component of the input sparse matrix must represent a square symmetric\nmatrix; only the lower triangular part of the matrix is read. The values of the\nsparse matrix does not affect the returned permutation, only the sparsity\npattern of the sparse matrix is used. Hence, a single AMD ordering may be\nreused for the Cholesky decompositions of sparse matrices with the same sparsity\npattern but with possibly different values.\n\nEach batch component of the output permutation represents a permutation of `N`\nelements, where the input sparse matrix components each have `N` rows. That is,\nthe component contains each of the integers `{0, .. N-1}` exactly once. The\n`i`th element represents the row index that the `i`th row maps to.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]])\n a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32)\n a_dense_shape = [4, 4]\n\n with tf.Session() as sess:\n # Define (COO format) SparseTensor over Numpy array.\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix.\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n\n # Obtain the AMD Ordering for the CSR SparseMatrix.\n ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix)\n\n ordering_amd_value = sess.run(ordering_amd)\n```\n\n`ordering_amd_value` stores the AMD ordering: `[1 2 3 0]`.\n\ninput: A `CSRSparseMatrix`.","inputs":[{"description":"A `CSRSparseMatrix`.","name":"input","type":21}],"outputs":[{"description":"The Approximate Minimum Degree (AMD) ordering of `input`.","name":"output","type":3}],"summary":"Computes the Approximate Minimum Degree (AMD) ordering of `input`."}},{"name":"SparseMatrixSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"type","type":"type"}],"description":"Calculate the softmax of the innermost dimensions of a SparseMatrix.\n\nMissing values are treated as `-inf` (i.e., logits of zero probability); and\nthe output has the same sparsity structure as the input (though missing values\nin the output may now be treated as having probability zero).","inputs":[{"description":"A CSRSparseMatrix.","name":"logits","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"softmax","type":21}],"summary":"Calculates the softmax of a CSRSparseMatrix."}},{"name":"SparseMatrixSoftmaxGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"type","type":"type"}],"inputs":[{"description":"A CSRSparseMatrix.","name":"softmax","type":21},{"description":"The gradient of `softmax`.","name":"grad_softmax","type":21}],"outputs":[{"description":"The output gradient.","name":"gradient","type":21}],"summary":"Calculates the gradient of the SparseMatrixSoftmax op."}},{"name":"SparseMatrixSparseCholesky","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"Computes the Sparse Cholesky decomposition of a sparse matrix, with the given\nfill-in reducing permutation.\n\nThe input sparse matrix and the fill-in reducing permutation `permutation` must\nhave compatible shapes. If the sparse matrix has rank 3; with the batch\ndimension `B`, then the `permutation` must be of rank 2; with the same batch\ndimension `B`. There is no support for broadcasting.\n\nFurthermore, each component vector of `permutation` must be of length `N`,\ncontaining each of the integers {0, 1, ..., N - 1} exactly once, where `N` is\nthe number of rows of each component of the sparse matrix.\n\nEach component of the input sparse matrix must represent a symmetric positive\ndefinite (SPD) matrix; although only the lower triangular part of the matrix is\nread. If any individual component is not SPD, then an InvalidArgument error is\nthrown.\n\nThe returned sparse matrix has the same dense shape as the input sparse matrix.\nFor each component `A` of the input sparse matrix, the corresponding output\nsparse matrix represents `L`, the lower triangular Cholesky factor satisfying\nthe following identity:\n\n```\n A = L * Lt\n```\n\nwhere Lt denotes the transpose of L (or its conjugate transpose, if `type` is\n`complex64` or `complex128`).\n\nThe `type` parameter denotes the type of the matrix elements. The supported\ntypes are: `float32`, `float64`, `complex64` and `complex128`.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]])\n a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32)\n a_dense_shape = [4, 4]\n\n with tf.Session() as sess:\n # Define (COO format) SparseTensor over Numpy array.\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix.\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n\n # Obtain the Sparse Cholesky factor using AMD Ordering for reducing zero\n # fill-in (number of structural non-zeros in the sparse Cholesky factor).\n ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix)\n cholesky_sparse_matrices = (\n sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(\n sparse_matrix, ordering_amd, type=tf.float32))\n\n # Convert the CSRSparseMatrix Cholesky factor to a dense Tensor\n dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n cholesky_sparse_matrices, tf.float32)\n\n # Evaluate the dense Tensor value.\n dense_cholesky_value = sess.run(dense_cholesky)\n```\n\n`dense_cholesky_value` stores the dense Cholesky factor:\n\n```\n [[ 1. 0. 0. 0.]\n [ 0. 1.41 0. 0.]\n [ 0. 0.70 1.58 0.]\n [ 0. 0. 0. 2.]]\n```\n\n\ninput: A `CSRSparseMatrix`.\npermutation: A `Tensor`.\ntype: The type of `input`.","inputs":[{"description":"A `CSRSparseMatrix`.","name":"input","type":21},{"description":"A fill-in reducing permutation matrix.","name":"permutation","type":3}],"outputs":[{"description":"The sparse Cholesky decompsition of `input`.","name":"output","type":21}],"summary":"Computes the sparse Cholesky decomposition of `input`."}},{"name":"SparseMatrixSparseMatMul","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"},{"default":false,"description":"Indicates whether `a` should be transposed.","name":"transpose_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be transposed.","name":"transpose_b","type":"boolean"},{"default":false,"description":"Indicates whether `a` should be conjugate-transposed.","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Indicates whether `b` should be conjugate-transposed.","name":"adjoint_b","type":"boolean"}],"description":"Performs a matrix multiplication of a sparse matrix `a` with a sparse matrix\n`b`; returns a sparse matrix `a * b`, unless either `a` or `b` is transposed or\nadjointed.\n\nEach matrix may be transposed or adjointed (conjugated and transposed)\naccording to the Boolean parameters `transpose_a`, `adjoint_a`, `transpose_b`\nand `adjoint_b`. At most one of `transpose_a` or `adjoint_a` may be True.\nSimilarly, at most one of `transpose_b` or `adjoint_b` may be True.\n\nThe inputs must have compatible shapes. That is, the inner dimension of `a`\nmust be equal to the outer dimension of `b`. This requirement is adjusted\naccording to whether either `a` or `b` is transposed or adjointed.\n\nThe `type` parameter denotes the type of the matrix elements. Both `a` and `b`\nmust have the same type. The supported types are: `float32`, `float64`,\n`complex64` and `complex128`.\n\nBoth `a` and `b` must have the same rank. Broadcasting is not supported. If they\nhave rank 3, each batch of 2D CSRSparseMatrices within `a` and `b` must have the\nsame dense shape.\n\nThe sparse matrix product may have numeric (non-structural) zeros.\nTODO(anudhyan): Consider adding a boolean attribute to control whether to prune\nzeros.\n\nUsage example:\n\n```python\n from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\n\n a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])\n a_values = np.array([1.0, 5.0, -1.0, -2.0], np.float32)\n a_dense_shape = [4, 5]\n\n b_indices = np.array([[0, 0], [3, 0], [3, 1]])\n b_values = np.array([2.0, 7.0, 8.0], np.float32)\n b_dense_shape = [5, 3]\n\n with tf.Session() as sess:\n # Define (COO format) Sparse Tensors over Numpy arrays\n a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape)\n b_st = tf.sparse.SparseTensor(b_indices, b_values, b_dense_shape)\n\n # Convert SparseTensors to CSR SparseMatrix\n a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n a_st.indices, a_st.values, a_st.dense_shape)\n b_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n b_st.indices, b_st.values, b_st.dense_shape)\n\n # Compute the CSR SparseMatrix matrix multiplication\n c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(\n a=a_sm, b=b_sm, type=tf.float32)\n\n # Convert the CSR SparseMatrix product to a dense Tensor\n c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n c_sm, tf.float32)\n # Evaluate the dense Tensor value\n c_sm_dense_value = sess.run(c_sm_dense)\n```\n\n`c_sm_dense_value` stores the dense matrix product:\n\n```\n [[ 2. 0. 0.]\n [ 0. 0. 0.]\n [ 35. 40. 0.]\n [ -4. 0. 0.]]\n```\n\na: A `CSRSparseMatrix`.\nb: A `CSRSparseMatrix` with the same type and rank as `a`.\ntype: The type of both `a` and `b`.\ntranspose_a: If True, `a` transposed before multiplication.\ntranspose_b: If True, `b` transposed before multiplication.\nadjoint_a: If True, `a` adjointed before multiplication.\nadjoint_b: If True, `b` adjointed before multiplication.","inputs":[{"description":"A CSRSparseMatrix.","name":"a","type":21},{"description":"A CSRSparseMatrix.","name":"b","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"c","type":21}],"summary":"Sparse-matrix-multiplies two CSR matrices `a` and `b`."}},{"name":"SparseMatrixTranspose","schema":{"attributes":[{"default":false,"description":"Indicates whether `input` should be conjugated.","name":"conjugate","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"description":"Transposes the inner (matrix) dimensions of a SparseMatrix and optionally\nconjugates its values.","inputs":[{"description":"A CSRSparseMatrix.","name":"input","type":21}],"outputs":[{"description":"A CSRSparseMatrix.","name":"output","type":21}],"summary":"Transposes the inner (matrix) dimensions of a CSRSparseMatrix."}},{"name":"SparseMatrixZeros","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"type","type":"type"}],"inputs":[{"description":"The desired matrix shape.","name":"dense_shape","type":9}],"outputs":[{"description":"An empty CSR matrix with shape `dense_shape`.","name":"sparse_matrix","type":21}],"summary":"Creates an all-zeros CSRSparseMatrix with shape `dense_shape`."}},{"name":"SparseReduceMax","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_max()`. In particular, this Op also returns a dense `Tensor`\ninstead of a sparse one.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"description":"`R-K`-D. The reduced Tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the max of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceMaxSparse","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_max()`. In contrast to SparseReduceMax, this Op returns a\nSparseTensor.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"name":"output_indices","type":9},{"name":"output_values","typeAttr":"T"},{"name":"output_shape","type":9}],"summary":"Computes the max of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceSum","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor`\ninstead of a sparse one.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"description":"`R-K`-D. The reduced Tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the sum of elements across dimensions of a SparseTensor."}},{"name":"SparseReduceSumSparse","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This Op takes a SparseTensor and is the sparse counterpart to\n`tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a\nSparseTensor.\n\nReduces `sp_input` along the dimensions given in `reduction_axes`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained\nwith length 1.\n\nIf `reduction_axes` has no entries, all dimensions are reduced, and a tensor\nwith a single element is returned. Additionally, the axes can be negative,\nwhich are interpreted according to the indexing rules in Python.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9},{"description":"1-D. Length-`K` vector containing the reduction axes.","name":"reduction_axes","type":3}],"outputs":[{"name":"output_indices","type":9},{"name":"output_values","typeAttr":"T"},{"name":"output_shape","type":9}],"summary":"Computes the sum of elements across dimensions of a SparseTensor."}},{"name":"SparseReorder","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Note that by convention, all sparse ops preserve the canonical ordering along\nincreasing dimension number. The only time ordering can be violated is during\nmanual manipulation of the indices and values vectors to add entries.\n\nReordering does not affect the shape of the SparseTensor.\n\nIf the tensor has rank `R` and `N` non-empty values, `input_indices` has\nshape `[N, R]`, input_values has length `N`, and input_shape has length `R`.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, possibly not in canonical ordering.","name":"input_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `input_indices`.","name":"input_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"input_shape","type":9}],"outputs":[{"description":"2-D. `N x R` matrix with the same indices as input_indices, but\nin canonical row-major ordering.","name":"output_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `output_indices`.","name":"output_values","typeAttr":"T"}],"summary":"Reorders a SparseTensor into the canonical, row-major ordering."}},{"name":"SparseReshape","schema":{"description":"This operation has the same semantics as reshape on the represented dense\ntensor. The `input_indices` are recomputed based on the requested `new_shape`.\n\nIf one component of `new_shape` is the special value -1, the size of that\ndimension is computed so that the total dense size remains constant. At\nmost one component of `new_shape` can be -1. The number of dense elements\nimplied by `new_shape` must be the same as the number of dense elements\noriginally implied by `input_shape`.\n\nReshaping does not affect the order of values in the SparseTensor.\n\nIf the input tensor has rank `R_in` and `N` non-empty values, and `new_shape`\nhas length `R_out`, then `input_indices` has shape `[N, R_in]`,\n`input_shape` has length `R_in`, `output_indices` has shape `[N, R_out]`, and\n`output_shape` has length `R_out`.","inputs":[{"description":"2-D. `N x R_in` matrix with the indices of non-empty values in a\nSparseTensor.","name":"input_indices","type":9},{"description":"1-D. `R_in` vector with the input SparseTensor's dense shape.","name":"input_shape","type":9},{"description":"1-D. `R_out` vector with the requested new dense shape.","name":"new_shape","type":9}],"outputs":[{"description":"2-D. `N x R_out` matrix with the updated indices of non-empty\nvalues in the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. `R_out` vector with the full dense shape of the output\nSparseTensor. This is the same as `new_shape` but with any -1 dimensions\nfilled in.","name":"output_shape","type":9}],"summary":"Reshapes a SparseTensor to represent values in a new dense shape."}},{"name":"SparseSegmentMean","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"See `tf.sparse.segment_sum` for usage examples.\n\nLike `SegmentMean`, but `segment_ids` can have rank less than `data`'s first\ndimension, selecting a subset of dimension 0, specified by `indices`.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along sparse segments of a tensor."}},{"name":"SparseSegmentMeanGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Returns tensor \"output\" with same shape as grad, except for dimension 0 whose\nvalue is output_dim0.","inputs":[{"description":"gradient propagated to the SparseSegmentMean op.","name":"grad","typeAttr":"T"},{"description":"indices passed to the corresponding SparseSegmentMean op.","name":"indices","typeAttr":"Tidx"},{"description":"segment_ids passed to the corresponding SparseSegmentMean op.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"dimension 0 of \"data\" passed to SparseSegmentMean op.","name":"output_dim0","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients for SparseSegmentMean."}},{"name":"SparseSegmentMeanWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the mean along sparse segments of a tensor."}},{"name":"SparseSegmentSqrtN","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"N is the size of the segment being reduced.\n\nSee `tf.sparse.segment_sum` for usage examples.\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor divided by the sqrt of N."}},{"name":"SparseSegmentSqrtNGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Returns tensor \"output\" with same shape as grad, except for dimension 0 whose\nvalue is output_dim0.","inputs":[{"description":"gradient propagated to the SparseSegmentSqrtN op.","name":"grad","typeAttr":"T"},{"description":"indices passed to the corresponding SparseSegmentSqrtN op.","name":"indices","typeAttr":"Tidx"},{"description":"segment_ids passed to the corresponding SparseSegmentSqrtN op.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"dimension 0 of \"data\" passed to SparseSegmentSqrtN op.","name":"output_dim0","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Computes gradients for SparseSegmentSqrtN."}},{"name":"SparseSegmentSqrtNWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"N is the size of the segment being reduced.\n\nLike `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor divided by the sqrt of N."}},{"name":"SparseSegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nLike `SegmentSum`, but `segment_ids` can have rank less than `data`'s first\ndimension, selecting a subset of dimension 0, specified by `indices`.\n\nFor example:\n\n```python\nc = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\n# Select two rows, one segment.\ntf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))\n# => [[0 0 0 0]]\n\n# Select two rows, two segment.\ntf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1]))\n# => [[ 1 2 3 4]\n# [-1 -2 -3 -4]]\n\n# Select all rows, two segments.\ntf.sparse_segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1]))\n# => [[0 0 0 0]\n# [5 6 7 8]]\n\n# Which is equivalent to:\ntf.segment_sum(c, tf.constant([0, 0, 1]))\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `k`, the number of segments.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor."}},{"name":"SparseSegmentSumWithNumSegments","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsegmentids","type":"type"}],"description":"Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is\nmissing, the `output` tensor at that position will be zeroed.\n\nRead\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/sparse#Segmentation)\nfor an explanation of segments.\n\nFor example:\n\n```python\nc = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])\n\ntf.sparse_segment_sum_with_num_segments(\n c, tf.constant([0, 1]), tf.constant([0, 0]), num_segments=3)\n# => [[0 0 0 0]\n# [0 0 0 0]\n# [0 0 0 0]]\n\ntf.sparse_segment_sum_with_num_segments(c,\n tf.constant([0, 1]),\n tf.constant([0, 2],\n num_segments=4))\n# => [[ 1 2 3 4]\n# [ 0 0 0 0]\n# [-1 -2 -3 -4]\n# [ 0 0 0 0]]\n```","inputs":[{"name":"data","typeAttr":"T"},{"description":"A 1-D tensor. Has same rank as `segment_ids`.","name":"indices","typeAttr":"Tidx"},{"description":"A 1-D tensor. Values should be sorted and can be repeated.","name":"segment_ids","typeAttr":"Tsegmentids"},{"description":"Should equal the number of distinct segment IDs.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for dimension 0 which\nhas size `num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along sparse segments of a tensor."}},{"name":"SparseSlice","schema":{"attributes":[{"name":"T","type":"type"}],"description":"For example, if the input is\n\n input_tensor = shape = [2, 7]\n [ a d e ]\n [b c ]\n\nGraphically the output tensors are:\n\n sparse_slice([0, 0], [2, 4]) = shape = [2, 4]\n [ a ]\n [b c ]\n\n sparse_slice([0, 4], [2, 3]) = shape = [2, 3]\n [ d e ]\n [ ]","inputs":[{"description":"2-D tensor represents the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D tensor represents the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. tensor represents the shape of the sparse tensor.","name":"shape","type":9},{"description":"1-D. tensor represents the start of the slice.","name":"start","type":9},{"description":"1-D. tensor represents the size of the slice.\noutput indices: A list of 1-D tensors represents the indices of the output\nsparse tensors.","name":"size","type":9}],"outputs":[{"name":"output_indices","type":9},{"description":"A list of 1-D tensors represents the values of the output sparse\ntensors.","name":"output_values","typeAttr":"T"},{"description":"A list of 1-D tensors represents the shape of the output sparse\ntensors.","name":"output_shape","type":9}],"summary":"Slice a `SparseTensor` based on the `start` and `size`."}},{"name":"SparseSliceGrad","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"This op takes in the upstream gradient w.r.t. non-empty values of\nthe sliced `SparseTensor`, and outputs the gradients w.r.t.\nthe non-empty values of input `SparseTensor`.","inputs":[{"description":"1-D. The gradient with respect to\nthe non-empty values of the sliced `SparseTensor`.","name":"backprop_val_grad","typeAttr":"T"},{"description":"2-D. The `indices` of the input `SparseTensor`.","name":"input_indices","type":9},{"description":"1-D. tensor represents the start of the slice.","name":"input_start","type":9},{"description":"2-D. The `indices` of the sliced `SparseTensor`.","name":"output_indices","type":9}],"outputs":[{"description":"1-D. The gradient with respect to the non-empty values of input `SparseTensor`.","name":"val_grad","typeAttr":"T"}],"summary":"The gradient operator for the SparseSlice op."}},{"name":"SparseSoftmax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The inputs represent an N-D SparseTensor with logical shape `[..., B, C]`\n(where `N >= 2`), and with indices sorted in the canonical lexicographic order.\n\nThis op is equivalent to applying the normal `tf.nn.softmax()` to each innermost\nlogical submatrix with shape `[B, C]`, but with the catch that *the implicitly\nzero elements do not participate*. Specifically, the algorithm is equivalent\nto the following:\n\n (1) Applies `tf.nn.softmax()` to a densified view of each innermost submatrix\n with shape `[B, C]`, along the size-C dimension;\n (2) Masks out the original implicitly-zero locations;\n (3) Renormalizes the remaining elements.\n\nHence, the `SparseTensor` result has exactly the same non-zero indices and\nshape.","inputs":[{"description":"2-D. `NNZ x R` matrix with the indices of non-empty values in a\nSparseTensor, in canonical ordering.","name":"sp_indices","type":9},{"description":"1-D. `NNZ` non-empty values corresponding to `sp_indices`.","name":"sp_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"sp_shape","type":9}],"outputs":[{"description":"1-D. The `NNZ` values for the result `SparseTensor`.","name":"output","typeAttr":"T"}],"summary":"Applies softmax to a batched N-D `SparseTensor`."}},{"name":"SparseSoftmaxCrossEntropyWithLogits","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlabels","type":"type"}],"description":"Unlike `SoftmaxCrossEntropyWithLogits`, this operation does not accept\na matrix of label probabilities, but rather a single label per row\nof features. This label is considered to have probability 1.0 for the\ngiven row.\n\nInputs are the logits, not probabilities.","inputs":[{"description":"batch_size x num_classes matrix","name":"features","typeAttr":"T"},{"description":"batch_size vector with values in [0, num_classes).\nThis is the label for the given minibatch entry.","name":"labels","typeAttr":"Tlabels"}],"outputs":[{"description":"Per example loss (batch_size vector).","name":"loss","typeAttr":"T"},{"description":"backpropagated gradients (batch_size x num_classes matrix).","name":"backprop","typeAttr":"T"}],"summary":"Computes softmax cross entropy cost and gradients to backpropagate."}},{"name":"SparseSparseMaximum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Assumes the two SparseTensors have the same shape, i.e., no broadcasting.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, in the canonical lexicographic ordering.","name":"a_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `a_indices`.","name":"a_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"a_shape","type":9},{"description":"counterpart to `a_indices` for the other operand.","name":"b_indices","type":9},{"description":"counterpart to `a_values` for the other operand; must be of the same dtype.","name":"b_values","typeAttr":"T"},{"description":"counterpart to `a_shape` for the other operand; the two shapes must be equal.","name":"b_shape","type":9}],"outputs":[{"description":"2-D. The indices of the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. The values of the output SparseTensor.","name":"output_values","typeAttr":"T"}],"summary":"Returns the element-wise max of two SparseTensors."}},{"name":"SparseSparseMinimum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"Assumes the two SparseTensors have the same shape, i.e., no broadcasting.","inputs":[{"description":"2-D. `N x R` matrix with the indices of non-empty values in a\nSparseTensor, in the canonical lexicographic ordering.","name":"a_indices","type":9},{"description":"1-D. `N` non-empty values corresponding to `a_indices`.","name":"a_values","typeAttr":"T"},{"description":"1-D. Shape of the input SparseTensor.","name":"a_shape","type":9},{"description":"counterpart to `a_indices` for the other operand.","name":"b_indices","type":9},{"description":"counterpart to `a_values` for the other operand; must be of the same dtype.","name":"b_values","typeAttr":"T"},{"description":"counterpart to `a_shape` for the other operand; the two shapes must be equal.","name":"b_shape","type":9}],"outputs":[{"description":"2-D. The indices of the output SparseTensor.","name":"output_indices","type":9},{"description":"1-D. The values of the output SparseTensor.","name":"output_values","typeAttr":"T"}],"summary":"Returns the element-wise min of two SparseTensors."}},{"name":"SparseSplit","schema":{"attributes":[{"description":"The number of ways to split.","minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"}],"description":"If the `shape[split_dim]` is not an integer multiple of `num_split`. Slices\n`[0 : shape[split_dim] % num_split]` gets one extra dimension.\nFor example, if `split_dim = 1` and `num_split = 2` and the input is\n\n input_tensor = shape = [2, 7]\n [ a d e ]\n [b c ]\n\nGraphically the output tensors are:\n\n output_tensor[0] = shape = [2, 4]\n [ a ]\n [b c ]\n\n output_tensor[1] = shape = [2, 3]\n [ d e ]\n [ ]","inputs":[{"description":"0-D. The dimension along which to split. Must be in the range\n`[0, rank(shape))`.","name":"split_dim","type":9},{"description":"2-D tensor represents the indices of the sparse tensor.","name":"indices","type":9},{"description":"1-D tensor represents the values of the sparse tensor.","name":"values","typeAttr":"T"},{"description":"1-D. tensor represents the shape of the sparse tensor.\noutput indices: A list of 1-D tensors represents the indices of the output\nsparse tensors.","name":"shape","type":9}],"outputs":[{"name":"output_indices","numberAttr":"num_split","type":9},{"description":"A list of 1-D tensors represents the values of the output sparse\ntensors.","name":"output_values","numberAttr":"num_split","typeAttr":"T"},{"description":"A list of 1-D tensors represents the shape of the output sparse\ntensors.","name":"output_shape","numberAttr":"num_split","type":9}],"summary":"Split a `SparseTensor` into `num_split` tensors along one dimension."}},{"name":"SparseTensorDenseAdd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This Op does not require `a_indices` be sorted in standard lexicographic order.","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`.","name":"a_indices","typeAttr":"Tindices"},{"description":"1-D. The `values` of the `SparseTensor`, with shape `[nnz]`.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`.","name":"a_shape","typeAttr":"Tindices"},{"description":"`ndims`-D Tensor. With shape `a_shape`.","name":"b","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`."}},{"name":"SparseTensorDenseMatMul","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":false,"description":"Use the adjoint of A in the matrix multiply. If A is complex, this\nis transpose(conj(A)). Otherwise it's transpose(A).","name":"adjoint_a","type":"boolean"},{"default":false,"description":"Use the adjoint of B in the matrix multiply. If B is complex, this\nis transpose(conj(B)). Otherwise it's transpose(B).","name":"adjoint_b","type":"boolean"}],"description":"No validity checking is performed on the indices of A. However, the following\ninput format is recommended for optimal behavior:\n\nif adjoint_a == false:\n A should be sorted in lexicographically increasing order. Use SparseReorder\n if you're not sure.\nif adjoint_a == true:\n A should be sorted in order of increasing dimension 1 (i.e., \"column major\"\n order instead of \"row major\" order).","inputs":[{"description":"2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix.","name":"a_indices","typeAttr":"Tindices"},{"description":"1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector.","name":"a_values","typeAttr":"T"},{"description":"1-D. The `shape` of the `SparseTensor`, size `[2]` Vector.","name":"a_shape","type":9},{"description":"2-D. A dense Matrix.","name":"b","typeAttr":"T"}],"outputs":[{"name":"product","typeAttr":"T"}],"summary":"Multiply SparseTensor (of rank 2) \"A\" by dense matrix \"B\"."}},{"name":"SparseTensorSliceDataset","schema":{"attributes":[{"name":"Tvalues","type":"type"}],"inputs":[{"name":"indices","type":9},{"name":"values","typeAttr":"Tvalues"},{"name":"dense_shape","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that splits a SparseTensor into elements row-wise."}},{"name":"SparseTensorToCSRSparseMatrix","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"description":"SparseTensor indices.","name":"indices","type":9},{"description":"SparseTensor values.","name":"values","typeAttr":"T"},{"description":"SparseTensor dense shape.","name":"dense_shape","type":9}],"outputs":[{"description":"A (possibly batched) CSRSparseMatrix.","name":"sparse_matrix","type":21}],"summary":"Converts a SparseTensor to a (possibly batched) CSRSparseMatrix."}},{"name":"SparseToDense","schema":{"attributes":[{"default":true,"description":"If true, indices are checked to make sure they are sorted in\nlexicographic order and that there are no repeats.","name":"validate_indices","type":"boolean"},{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"Builds an array `dense` with shape `output_shape` such that\n\n```\n# If sparse_indices is scalar\ndense[i] = (i == sparse_indices ? sparse_values : default_value)\n\n# If sparse_indices is a vector, then for each i\ndense[sparse_indices[i]] = sparse_values[i]\n\n# If sparse_indices is an n by d matrix, then for each i in [0, n)\ndense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i]\n```\n\nAll other values in `dense` are set to `default_value`. If `sparse_values` is a\nscalar, all sparse indices are set to this single value.\n\nIndices should be sorted in lexicographic order, and indices must not\ncontain any repeats. If `validate_indices` is true, these properties\nare checked during execution.","inputs":[{"description":"0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete\nindex where `sparse_values[i]` will be placed.","name":"sparse_indices","typeAttr":"Tindices"},{"description":"1-D. Shape of the dense output tensor.","name":"output_shape","typeAttr":"Tindices"},{"description":"1-D. Values corresponding to each row of `sparse_indices`,\nor a scalar value to be used for all sparse indices.","name":"sparse_values","typeAttr":"T"},{"description":"Scalar value to set for indices not specified in\n`sparse_indices`.","name":"default_value","typeAttr":"T"}],"outputs":[{"description":"Dense output tensor of shape `output_shape`.","name":"dense","typeAttr":"T"}],"summary":"Converts a sparse representation into a dense tensor."}},{"name":"SparseToSparseSetOperation","schema":{"attributes":[{"name":"set_operation","type":"string"},{"default":true,"name":"validate_indices","type":"boolean"},{"description":"Must be one of the following: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`.","name":"T","type":"type"}],"description":"See SetOperationOp::SetOperationFromContext for values of `set_operation`.\n\nIf `validate_indices` is `True`, `SparseToSparseSetOperation` validates the\norder and range of `set1` and `set2` indices.\n\nInput `set1` is a `SparseTensor` represented by `set1_indices`, `set1_values`,\nand `set1_shape`. For `set1` ranked `n`, 1st `n-1` dimensions must be the same\nas `set2`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nInput `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`,\nand `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same\nas `set1`. Dimension `n` contains values in a set, duplicates are allowed but\nignored.\n\nIf `validate_indices` is `True`, this op validates the order and range of `set1`\nand `set2` indices.\n\nOutput `result` is a `SparseTensor` represented by `result_indices`,\n`result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this\nhas rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth`\ndimension contains the result of `set_operation` applied to the corresponding\n`[0...n-1]` dimension of `set`.","inputs":[{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set1_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set1_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must\nbe the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the\nmax set size across `0...n-1` dimensions.","name":"set1_shape","type":9},{"description":"2D `Tensor`, indices of a `SparseTensor`. Must be in row-major\norder.","name":"set2_indices","type":9},{"description":"1D `Tensor`, values of a `SparseTensor`. Must be in row-major\norder.","name":"set2_values","typeAttr":"T"},{"description":"1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must\nbe the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the\nmax set size across `0...n-1` dimensions.","name":"set2_shape","type":9}],"outputs":[{"description":"2D indices of a `SparseTensor`.","name":"result_indices","type":9},{"description":"1D values of a `SparseTensor`.","name":"result_values","typeAttr":"T"},{"description":"1D `Tensor` shape of a `SparseTensor`. `result_shape[0...n-1]` is\nthe same as the 1st `n-1` dimensions of `set1` and `set2`, `result_shape[n]`\nis the max result set size across all `0...n-1` dimensions.","name":"result_shape","type":9}],"summary":"Applies set operation along last dimension of 2 `SparseTensor` inputs."}},{"name":"Spence","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}]}},{"name":"Split","schema":{"attributes":[{"description":"The number of ways to split. Must evenly divide\n`value.shape[split_dim]`.","minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"}],"category":"Tensor","inputs":[{"description":"0-D. The dimension along which to split. Must be in the range\n`[-rank(value), rank(value))`.","name":"split_dim","type":3},{"description":"The tensor to split.","name":"value","typeAttr":"T"}],"outputs":[{"description":"They are identically shaped tensors, whose shape matches that of `value`\nexcept along `split_dim`, where their sizes are\n`values.shape[split_dim] / num_split`.","name":"output","numberAttr":"num_split","typeAttr":"T"}],"summary":"Splits a tensor into `num_split` tensors along one dimension."}},{"name":"SplitV","schema":{"attributes":[{"minimum":1,"name":"num_split","type":"int64"},{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tlen","type":"type"}],"inputs":[{"description":"The tensor to split.","name":"value","typeAttr":"T"},{"description":"list containing the sizes of each output tensor along the split\ndimension. Must sum to the dimension of value along split_dim.\nCan contain one -1 indicating that dimension is to be inferred.","name":"size_splits","typeAttr":"Tlen"},{"description":"0-D. The dimension along which to split. Must be in the range\n`[-rank(value), rank(value))`.","name":"split_dim","type":3}],"outputs":[{"description":"Tensors whose shape matches that of `value`\nexcept along `split_dim`, where their sizes are\n`size_splits[i]`.","name":"output","numberAttr":"num_split","typeAttr":"T"}],"summary":"Splits a tensor into `num_split` tensors along one dimension."}},{"name":"SqlDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":"The database type. Currently, the only supported type is 'sqlite'.","name":"driver_name","type":7},{"description":"A connection string to connect to the database.","name":"data_source_name","type":7},{"description":"A SQL query to execute.","name":"query","type":7}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that executes a SQL query and emits rows of the result set."}},{"name":"Sqrt","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = \\sqrt{x} = x^{1/2}\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes square root of x element-wise."}},{"name":"SqrtGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * 0.5 / y`, where `y = sqrt(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the sqrt of `x` wrt its input."}},{"name":"Square","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"I.e., \\\\(y = x * x = x^2\\\\).","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes square of x element-wise."}},{"name":"SquaredDifference","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"*NOTE*: `SquaredDifference` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns conj(x - y)(x - y) element-wise."}},{"name":"Squeeze","schema":{"attributes":[{"name":"T","type":"type"},{"default":[],"description":"If specified, only squeezes the dimensions listed. The dimension\nindex starts at 0. It is an error to squeeze a dimension that is not 1. Must\nbe in the range `[-rank(input), rank(input))`.","minimum":0,"name":"squeeze_dims","type":"int64[]"}],"category":"Shape","description":"Given a tensor `input`, this operation returns a tensor of the same type with\nall dimensions of size 1 removed. If you don't want to remove all size 1\ndimensions, you can remove specific size 1 dimensions by specifying\n`squeeze_dims`.\n\nFor example:\n\n```\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t)) ==> [2, 3]\n```\n\nOr, to remove specific size 1 dimensions:\n\n```\n# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\nshape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]\n```","inputs":[{"description":"The `input` to squeeze.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Contains the same data as `input`, but has one or more dimensions of\nsize 1 removed.","name":"output","typeAttr":"T"}],"summary":"Removes dimensions of size 1 from the shape of a tensor."}},{"name":"Stack","schema":{"attributes":[{"name":"elem_type","type":"type"},{"default":"","name":"stack_name","type":"string"}],"outputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated, use StackV2."}},{"name":"StackClose","schema":{"inputs":[{"isRef":true,"name":"handle","type":7}],"summary":"Deprecated, use StackCloseV2."}},{"name":"StackCloseV2","schema":{"inputs":[{"description":"The handle to a stack.","name":"handle","type":20}],"summary":"Delete the stack from its resource container."}},{"name":"StackPop","schema":{"attributes":[{"name":"elem_type","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7}],"outputs":[{"name":"elem","typeAttr":"elem_type"}],"summary":"Deprecated, use StackPopV2."}},{"name":"StackPopV2","schema":{"attributes":[{"description":"The type of the elem that is popped.","name":"elem_type","type":"type"}],"inputs":[{"description":"The handle to a stack.","name":"handle","type":20}],"outputs":[{"description":"The tensor that is popped from the top of the stack.","name":"elem","typeAttr":"elem_type"}],"summary":"Pop the element at the top of the stack."}},{"name":"StackPush","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"name":"swap_memory","type":"boolean"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"elem","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Deprecated, use StackPushV2."}},{"name":"StackPushV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":false,"description":"Swap `elem` to CPU. Default to false.","name":"swap_memory","type":"boolean"}],"inputs":[{"description":"The handle to a stack.","name":"handle","type":20},{"description":"The tensor to be pushed onto the stack.","name":"elem","typeAttr":"T"}],"outputs":[{"description":"The same tensor as the input 'elem'.","name":"output","typeAttr":"T"}],"summary":"Push an element onto the stack."}},{"name":"StackV2","schema":{"attributes":[{"description":"The type of the elements on the stack.","name":"elem_type","type":"type"},{"default":"","description":"Overrides the name used for the temporary stack resource. Default\nvalue is the name of the 'Stack' op (which is guaranteed unique).","name":"stack_name","type":"string"}],"inputs":[{"description":"The maximum size of the stack if non-negative. If negative, the stack\nsize is unlimited.","name":"max_size","type":3}],"outputs":[{"description":"The handle to the stack.","name":"handle","type":20}],"summary":"A stack that produces elements in first-in last-out order."}},{"name":"Stage","schema":{"attributes":[{"default":0,"description":"Maximum number of elements in the Staging Area. If > 0, inserts\non the container will block when the capacity is reached.","minimum":0,"name":"capacity","type":"int64"},{"default":0,"description":"The maximum number of bytes allowed for Tensors in the Staging Area.\nIf > 0, inserts will block until sufficient space is available.","minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","description":"If non-empty, this queue is placed in the given container. Otherwise,\na default container is used.","name":"container","type":"string"},{"default":"","description":"It is necessary to match this name to the matching Unstage Op.","name":"shared_name","type":"string"}],"description":"The basic functionality of this Op is similar to a queue with many\nfewer capabilities and options. This Op is optimized for performance.","inputs":[{"description":"a list of tensors\ndtypes A list of data types that inserted values should adhere to.","name":"values","typeListAttr":"dtypes"}],"summary":"Stage values similar to a lightweight Enqueue."}},{"name":"StageClear","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"summary":"Op removes all elements in the underlying container."}},{"name":"StagePeek","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"underlying container does not contain sufficient elements\nthis op will block until it does. This Op is optimized for\nperformance.","inputs":[{"name":"index","type":3}],"outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op peeks at the values at the specified index. If the"}},{"name":"StageSize","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"size","type":3}],"summary":"Op returns the number of elements in the underlying container."}},{"name":"StatefulPartitionedCall","schema":{"attributes":[{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'args', a list of tensors, and returns 'output',\n another list of tensors. Input and output types are specified by 'Tin'\n and 'Tout'. The function body of f will be placed and partitioned across\n devices, setting this op apart from the regular Call op. This op is\n stateful.","name":"f","type":"function"},{"default":"","name":"config","type":"string"},{"default":"","name":"config_proto","type":"string"},{"default":"","name":"executor_type","type":"string"}],"inputs":[{"description":"A list of input tensors.","name":"args","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"returns `f(inputs)`, where `f`'s body is placed and partitioned."}},{"name":"StatefulRandomBinomial","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"inputs":[{"name":"resource","type":20},{"name":"algorithm","type":9},{"name":"shape","typeAttr":"S"},{"name":"counts","typeAttr":"T"},{"name":"probs","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"dtype"}]}},{"name":"StatefulStandardNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2'"}},{"name":"StatefulStandardNormalV2","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"A tensor of the specified shape filled with random normal values.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a normal distribution."}},{"name":"StatefulTruncatedNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a truncated normal distribution."}},{"name":"StatefulUniform","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a uniform distribution."}},{"name":"StatefulUniformFullInt","schema":{"attributes":[{"default":{"type":"type","value":23},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values are uniform integers covering the whole range of `dtype`.","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"StatefulUniformInt","schema":{"attributes":[{"default":{"type":"type","value":9},"description":"The type of the output.","name":"dtype","type":"type"},{"default":{"type":"type","value":9},"name":"shape_dtype","type":"type"}],"description":"The generated values are uniform integers in the range `[minval, maxval)`.\nThe lower bound `minval` is included in the range, while the upper bound\n`maxval` is excluded.\n\nThe random integers are slightly biased unless `maxval - minval` is an exact\npower of two. The bias is small for values of `maxval - minval` significantly\nsmaller than the range of the output (either `2^32` or `2^64`).","inputs":[{"description":"The handle of the resource variable that stores the state of the RNG.","name":"resource","type":20},{"description":"The RNG algorithm.","name":"algorithm","type":9},{"description":"The shape of the output tensor.","name":"shape","typeAttr":"shape_dtype"},{"description":"Minimum value (inclusive, scalar).","name":"minval","typeAttr":"dtype"},{"description":"Maximum value (exclusive, scalar).","name":"maxval","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random integers from a uniform distribution."}},{"name":"StatelessIf","schema":{"attributes":[{"name":"Tcond","type":"type"},{"description":"A list of input types.","minimum":0,"name":"Tin","type":"type[]"},{"description":"A list of output types.","minimum":0,"name":"Tout","type":"type[]"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what else_branch returns.","name":"then_branch","type":"function"},{"description":" A function that takes 'inputs' and returns a list of tensors, whose\n types are the same as what then_branch returns.","name":"else_branch","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"}],"inputs":[{"description":" A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n `True` and zero means False; if the scalar is a string, non-empty\n means `True` and empty means `False`. If the tensor is not a scalar,\n being empty means False and being non-empty means True.\n\n This should only be used when the if then/else body functions do not\n have stateful ops.","name":"cond","typeAttr":"Tcond"},{"description":"A list of input tensors.","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"A list of return values.","name":"output","typeListAttr":"Tout"}],"summary":"output = cond ? then_branch(input) : else_branch(input)"}},{"name":"StatelessMultinomial","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"output_dtype","type":"type"}],"inputs":[{"description":"2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]`\nrepresents the unnormalized log probabilities for all classes.","name":"logits","typeAttr":"T"},{"description":"0-D. Number of independent samples to draw for each row slice.","name":"num_samples","type":3},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"2-D Tensor with shape `[batch_size, num_samples]`. Each slice `[i, :]`\ncontains the drawn class labels with range `[0, num_classes)`.","name":"output","typeAttr":"output_dtype"}],"summary":"Draws samples from a multinomial distribution."}},{"name":"StatelessParameterizedTruncatedNormal","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"}],"inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"S"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The mean parameter of each batch.","name":"means","typeAttr":"dtype"},{"description":"The standard deviation parameter of each batch. Must be greater than 0.","name":"stddevs","typeAttr":"dtype"},{"description":"The minimum cutoff. May be -infinity.","name":"minvals","typeAttr":"dtype"},{"description":"The maximum cutoff. May be +infinity, and must be more than the minval\nfor each batch.","name":"maxvals","typeAttr":"dtype"}],"outputs":[{"description":"The outputs are truncated normal samples and are a deterministic function of\n`shape`, `seed`, `minvals`, `maxvals`, `means` and `stddevs`.","name":"output","typeAttr":"dtype"}]}},{"name":"StatelessRandomBinomial","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"S","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"},{"default":{"type":"type","value":2},"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"}],"description":"Outputs random values from a binomial distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, `counts`, and `probs`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"S"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The counts of the binomial distribution. Must be broadcastable with `probs`,\nand broadcastable with the rightmost dimensions of `shape`.","name":"counts","typeAttr":"T"},{"description":"The probability of success for the binomial distribution. Must be broadcastable\nwith `counts` and broadcastable with the rightmost dimensions of `shape`.","name":"probs","typeAttr":"T"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a binomial distribution."}},{"name":"StatelessRandomGammaV2","schema":{"attributes":[{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"Outputs random values from a gamma distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, and `alpha`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The concentration of the gamma distribution. Shape must match the rightmost\ndimensions of `shape`.","name":"alpha","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a gamma distribution."}},{"name":"StatelessRandomNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values will have mean 0 and standard deviation 1.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom values from a normal distribution."}},{"name":"StatelessRandomPoisson","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"Rtype","type":"type"},{"description":"The type of the output. Must be one of the following: `float16`, `float32`, `float64`, `int32`, `int64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"Outputs random values from a Poisson distribution.\n\nThe outputs are a deterministic function of `shape`, `seed`, and `lam`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"The rate of the Poisson distribution. Shape must match the rightmost dimensions\nof `shape`.","name":"lam","typeAttr":"Rtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random numbers from a Poisson distribution."}},{"name":"StatelessRandomUniform","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[0, 1)`. The\nlower bound 0 is included in the range, while the upper bound 1 is excluded.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random values from a uniform distribution."}},{"name":"StatelessRandomUniformFullInt","schema":{"attributes":[{"default":{"type":"type","value":23},"description":"The type of the output. Must be one of the following: `int32`, `int64`, `uint32`, `uint64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`, `uint32`, `uint64`.","name":"Tseed","type":"type"}],"description":"The generated values are uniform integers covering the whole range of `dtype`.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random integers from a uniform distribution."}},{"name":"StatelessRandomUniformInt","schema":{"attributes":[{"description":"The type of the output. Must be one of the following: `int32`, `int64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a uniform distribution in the range `[minval, maxval)`.\n\nThe outputs are a deterministic function of `shape`, `seed`, `minval`, and `maxval`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"},{"description":"Minimum value (inclusive, scalar).","name":"minval","typeAttr":"dtype"},{"description":"Maximum value (exclusive, scalar).","name":"maxval","typeAttr":"dtype"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom random integers from a uniform distribution."}},{"name":"StatelessTruncatedNormal","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tseed","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.\n\nThe outputs are a deterministic function of `shape` and `seed`.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"},{"description":"2 seeds (shape [2]).","name":"seed","typeAttr":"Tseed"}],"outputs":[{"description":"Random values with specified shape.","name":"output","typeAttr":"dtype"}],"summary":"Outputs deterministic pseudorandom values from a truncated normal distribution."}},{"name":"StatelessWhile","schema":{"attributes":[{"description":"dtype in use.","minimum":0,"name":"T","type":"type[]"},{"description":" A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.\n\n This should only be used when the while condition and body functions\n do not have stateful ops.","name":"cond","type":"function"},{"description":" A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.","name":"body","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"},{"default":10,"name":"parallel_iterations","type":"int64"}],"inputs":[{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":"output = input; While (Cond(output)) { output = Body(output) }"}},{"name":"StaticRegexFullMatch","schema":{"attributes":[{"description":"The regular expression to match the input.","name":"pattern","type":"string"}],"description":"The input is a string tensor of any shape. The pattern is the\nregular expression to be matched with every element of the input tensor.\nThe boolean values (True or False) of the output tensor indicate\nif the input matches the regex pattern provided.\n\nThe pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"A string tensor of the text to be processed.","name":"input","type":7}],"outputs":[{"description":"A bool tensor with the same shape as `input`.","name":"output","type":10}],"summary":"Check if the input matches the regex pattern."}},{"name":"StaticRegexReplace","schema":{"attributes":[{"description":"The regular expression to match the input.","name":"pattern","type":"string"},{"description":"The rewrite to be applied to the matched expression.","name":"rewrite","type":"string"},{"default":true,"description":"If True, the replacement is global, otherwise the replacement\nis done only on the first match.","name":"replace_global","type":"boolean"}],"description":"It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax)","inputs":[{"description":"The text to be processed.","name":"input","type":7}],"outputs":[{"description":"The text after applying pattern and rewrite.","name":"output","type":7}],"summary":"Replaces the match of pattern in input with rewrite."}},{"name":"StatsAggregatorHandle","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}],"summary":"Creates a statistics manager resource."}},{"name":"StatsAggregatorHandleV2","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"handle","type":20}]}},{"name":"StatsAggregatorSetSummaryWriter","schema":{"inputs":[{"name":"stats_aggregator","type":20},{"name":"summary","type":20}],"summary":"Set a summary_writer_interface to record statistics using given stats_aggregator."}},{"name":"StatsAggregatorSummary","schema":{"inputs":[{"name":"iterator","type":20}],"outputs":[{"name":"summary","type":7}],"summary":"Produces a summary of any statistics recorded by the given statistics manager."}},{"name":"StopGradient","schema":{"attributes":[{"name":"T","type":"type"}],"description":"When executed in a graph, this op outputs its input tensor as-is.\n\nWhen building ops to compute gradients, this op prevents the contribution of\nits inputs to be taken into account. Normally, the gradient generator adds ops\nto a graph to compute the derivatives of a specified 'loss' by recursively\nfinding out inputs that contributed to its computation. If you insert this op\nin the graph it inputs are masked from the gradient generator. They are not\ntaken into account for computing gradients.\n\nThis is useful any time you want to compute a value with TensorFlow but need\nto pretend that the value was a constant. Some examples include:\n\n* The *EM* algorithm where the *M-step* should not involve backpropagation\n through the output of the *E-step*.\n* Contrastive divergence training of Boltzmann machines where, when\n differentiating the energy function, the training must not backpropagate\n through the graph that generated the samples from the model.\n* Adversarial training, where no backprop should happen through the adversarial\n example generation process.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Stops gradient computation."}},{"name":"StridedSlice","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"description":"a bitmask where a bit i being 1 means to ignore the begin\nvalue and instead use the largest interval possible. At runtime\nbegin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or\n`[-1, n-1]` if `stride[i] < 0`","name":"begin_mask","type":"int64"},{"default":0,"description":"analogous to `begin_mask`","name":"end_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` being 1 means the `i`th\nposition is actually an ellipsis. One bit at most can be 1.\nIf `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)`\nis provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis\nimplicitly creates as many range specifications as necessary to fully\nspecify the sliced range for every dimension. For example for a 4-dimensional\ntensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`.","name":"ellipsis_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` being 1 means the `i`th\nspecification creates a new shape 1 dimension. For example\n`foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor.","name":"new_axis_mask","type":"int64"},{"default":0,"description":"a bitmask where bit `i` implies that the `i`th\nspecification should shrink the dimensionality. begin and end\nmust imply a slice of size 1 in the dimension. For example in\npython one might do `foo[:, 3, :]` which would result in\n`shrink_axis_mask` being 2.","name":"shrink_axis_mask","type":"int64"}],"category":"Tensor","description":"Note, most python users will want to use the Python `Tensor.__getitem__`\nor `Variable.__getitem__` rather than this op directly.\n\nThe goal of this op is to produce a new tensor with a subset of\nthe elements from the `n` dimensional `input` tensor. The subset is chosen using\na sequence of `m` sparse range specifications encoded into the arguments\nof this function. Note, in some cases\n`m` could be equal to `n`, but this need not be the case. Each\nrange specification entry can be one of the following:\n\n- An ellipsis (...). Ellipses are used to imply zero or more\n dimensions of full-dimension selection and are produced using\n `ellipsis_mask`. For example, `foo[...]` is the identity slice.\n\n- A new axis. This is used to insert a new shape=1 dimension and is\n produced using `new_axis_mask`. For example, `foo[:, ...]` where\n `foo` is shape `(3, 4)` produces a `(1, 3, 4)` tensor.\n\n\n- A range `begin:end:stride`. This is used to specify how much to choose from\n a given dimension. `stride` can be any integer but 0. `begin` is an integer\n which represents the index of the first value to select while `end` represents\n the index of the last value to select. The number of values selected in each\n dimension is `end - begin` if `stride > 0` and `begin - end` if `stride < 0`.\n `begin` and `end` can be negative where `-1` is the last element, `-2` is\n the second to last. `begin_mask` controls whether to replace the explicitly\n given `begin` with an implicit effective value of `0` if `stride > 0` and\n `-1` if `stride < 0`. `end_mask` is analogous but produces the number\n required to create the largest open interval. For example, given a shape\n `(3,)` tensor `foo[:]`, the effective `begin` and `end` are `0` and `3`. Do\n not assume this is equivalent to `foo[0:-1]` which has an effective `begin`\n and `end` of `0` and `2`. Another example is `foo[-2::-1]` which reverses the\n first dimension of a tensor while dropping the last two (in the original\n order elements). For example `foo = [1,2,3,4]; foo[-2::-1]` is `[4,3]`.\n\n- A single index. This is used to keep only elements that have a given\n index. For example (`foo[2, :]` on a shape `(5,6)` tensor produces a\n shape `(6,)` tensor. This is encoded in `begin` and `end` and\n `shrink_axis_mask`.\n\nEach conceptual range specification is encoded in the op's argument. This\nencoding is best understand by considering a non-trivial example. In\nparticular,\n`foo[1, 2:4, None, ..., :-3:-1, :]` will be encoded as\n\n```\nbegin = [1, 2, x, x, 0, x] # x denotes don't care (usually 0)\nend = [2, 4, x, x, -3, x]\nstrides = [1, 1, x, x, -1, 1]\nbegin_mask = 1<<4 | 1<<5 = 48\nend_mask = 1<<5 = 32\nellipsis_mask = 1<<3 = 8\nnew_axis_mask = 1<<2 = 4\nshrink_axis_mask = 1<<0 = 1\n```\n\nIn this case if `foo.shape` is (5, 5, 5, 5, 5, 5) the final shape of\nthe slice becomes (2, 1, 5, 5, 2, 5).\nLet us walk step by step through each argument specification.\n\n1. The first argument in the example slice is turned into `begin = 1` and\n`end = begin + 1 = 2`. To disambiguate from the original spec `2:4` we\nalso set the appropriate bit in `shrink_axis_mask`.\n\n2. `2:4` is contributes 2, 4, 1 to begin, end, and stride. All masks have\nzero bits contributed.\n\n3. None is a synonym for `tf.newaxis`. This means insert a dimension of size 1\ndimension in the final shape. Dummy values are contributed to begin,\nend and stride, while the new_axis_mask bit is set.\n\n4. `...` grab the full ranges from as many dimensions as needed to\nfully specify a slice for every dimension of the input shape.\n\n5. `:-3:-1` shows the use of negative indices. A negative index `i` associated\nwith a dimension that has shape `s` is converted to a positive index\n`s + i`. So `-1` becomes `s-1` (i.e. the last element). This conversion\nis done internally so begin, end and strides receive x, -3, and -1.\nThe appropriate begin_mask bit is set to indicate the start range is the\nfull range (ignoring the x).\n\n6. `:` indicates that the entire contents of the corresponding dimension\nis selected. This is equivalent to `::` or `0::1`. begin, end, and strides\nreceive 0, 0, and 1, respectively. The appropriate bits in `begin_mask` and\n`end_mask` are also set.\n\n*Requirements*:\n `0 != strides[i] for i in [0, m)`\n `ellipsis_mask must be a power of two (only one ellipsis)`","inputs":[{"name":"input","typeAttr":"T"},{"description":"`begin[k]` specifies the offset into the `k`th range specification.\nThe exact dimension this corresponds to will be determined by context.\nOut-of-bounds values will be silently clamped. If the `k`th bit of\n`begin_mask` then `begin[k]` is ignored and the full range of the\nappropriate dimension is used instead. Negative values causes indexing\nto start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`.","name":"begin","typeAttr":"Index"},{"description":"`end[i]` is like `begin` with the exception that `end_mask` is\nused to determine full ranges.","name":"end","typeAttr":"Index"},{"description":"`strides[i]` specifies the increment in the `i`th specification\nafter extracting a given element. Negative indices will reverse\nthe original order. Out or range values are\nclamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0`","name":"strides","typeAttr":"Index"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Return a strided slice from `input`."}},{"name":"StridedSliceAssign","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the variable\n`ref` that are selected by the slice parameters. The slice parameters\n`begin`, `end`, `strides`, etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s\nshape must be exactly the shape produced by the slice of `ref`.","inputs":[{"isRef":true,"name":"ref","typeAttr":"T"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"outputs":[{"isRef":true,"name":"output_ref","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `ref`."}},{"name":"StridedSliceGrad","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"Since `StridedSlice` cuts out pieces of its `input` which is size\n`shape`, its gradient will have the same shape (which is passed here\nas `shape`). The gradient will be zero in any element that the slice\ndoes not select.\n\nArguments are the same as StridedSliceGrad with the exception that\n`dy` is the input gradient to be propagated and `shape` is the\nshape of `StridedSlice`'s `input`.","inputs":[{"name":"shape","typeAttr":"Index"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the gradient of `StridedSlice`."}},{"name":"StringFormat","schema":{"attributes":[{"minimum":0,"name":"T","type":"type[]"},{"default":"%s","description":"A string, the template to format tensor summaries into.","name":"template","type":"string"},{"default":"%s","description":"A string, at each placeholder in the template a subsequent tensor summary will be inserted.","name":"placeholder","type":"string"},{"default":3,"description":"When formatting the tensor summaries print the first and last summarize entries of each tensor dimension.","name":"summarize","type":"int64"}],"description":"Formats a string template using a list of tensors, pretty-printing tensor summaries.","inputs":[{"description":"The list of tensors to format into the placeholder string.","name":"inputs","typeListAttr":"T"}],"outputs":[{"description":"= The resulting string scalar.","name":"output","type":7}],"summary":"Formats a string template using a list of tensors."}},{"name":"StringJoin","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"default":"","description":"string, an optional join separator.","name":"separator","type":"string"}],"description":"with the given separator (default is an empty separator).\n\nExamples:\n\n>>> s = [\"hello\", \"world\", \"tensorflow\"]\n>>> tf.strings.join(s, \" \")\n","inputs":[{"description":"A list of string tensors. The tensors must all have the same shape,\nor be scalars. Scalars may be mixed in; these will be broadcast to the shape\nof non-scalar inputs.","name":"inputs","numberAttr":"N","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Joins the strings in the given list of string tensors into one tensor;"}},{"name":"StringLength","schema":{"attributes":[{"default":"BYTE","description":"The unit that is counted to compute string length. One of: `\"BYTE\"` (for\nthe number of bytes in each string) or `\"UTF8_CHAR\"` (for the number of UTF-8\nencoded Unicode code points in each string). Results are undefined\nif `unit=UTF8_CHAR` and the `input` strings do not contain structurally\nvalid UTF-8. Must be one of the following: `BYTE`, `UTF8_CHAR`.","name":"unit","type":"string"}],"description":"Computes the length of each string given in the input tensor.\n\n>>> strings = tf.constant(['Hello','TensorFlow', '\\U0001F642'])\n>>> tf.strings.length(strings).numpy() # default counts bytes\narray([ 5, 10, 4], dtype=int32)\n>>> tf.strings.length(strings, unit=\"UTF8_CHAR\").numpy()\narray([ 5, 10, 1], dtype=int32)\n","inputs":[{"description":"The strings for which to compute the length for each element.","name":"input","type":7}],"outputs":[{"description":"Integer tensor that has the same shape as `input`. The output contains the\nelement-wise string lengths of `input`.","name":"output","type":3}],"summary":"String lengths of `input`."}},{"name":"StringLower","schema":{"attributes":[{"default":"","name":"encoding","type":"string"}],"description":"Example:\n\n>>> tf.strings.lower(\"CamelCase string and ALL CAPS\")\n\n","inputs":[{"name":"input","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Converts all uppercase characters into their respective lowercase replacements."}},{"name":"StringNGrams","schema":{"attributes":[{"description":"The string to append between elements of the token. Use \"\" for no separator.","name":"separator","type":"string"},{"description":"The sizes of the ngrams to create.","minimum":0,"name":"ngram_widths","type":"int64[]"},{"description":"The string to use to pad the left side of the ngram sequence. Only used if\npad_width != 0.","name":"left_pad","type":"string"},{"description":"The string to use to pad the right side of the ngram sequence. Only used if\npad_width != 0.","name":"right_pad","type":"string"},{"description":"The number of padding elements to add to each side of each\nsequence. Note that padding will never be greater than 'ngram_widths'-1\nregardless of this value. If `pad_width=-1`, then add `max(ngram_widths)-1`\nelements.","name":"pad_width","type":"int64"},{"name":"preserve_short_sequences","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"This op accepts a ragged tensor with 1 ragged dimension containing only\nstrings and outputs a ragged tensor with 1 ragged dimension containing ngrams\nof that string, joined along the innermost axis.","inputs":[{"description":"The values tensor of the ragged string tensor to make ngrams out of. Must be a\n1D string tensor.","name":"data","type":7},{"description":"The splits tensor of the ragged string tensor to make ngrams out of.","name":"data_splits","typeAttr":"Tsplits"}],"outputs":[{"description":"The values tensor of the output ngrams ragged tensor.","name":"ngrams","type":7},{"description":"The splits tensor of the output ngrams ragged tensor.","name":"ngrams_splits","typeAttr":"Tsplits"}],"summary":"Creates ngrams from ragged string data."}},{"name":"StringSplit","schema":{"attributes":[{"default":true,"description":"A `bool`. If `True`, skip the empty strings from the result.","name":"skip_empty","type":"boolean"}],"description":"Let N be the size of source (typically N will be the batch size). Split each\nelement of `input` based on `delimiter` and return a `SparseTensor`\ncontaining the splitted tokens. Empty tokens are ignored.\n\n`delimiter` can be empty, or a string of split characters. If `delimiter` is an\n empty string, each element of `input` is split into individual single-byte\n character strings, including splitting of UTF-8 multibyte sequences. Otherwise\n every character of `delimiter` is a potential split point.\n\nFor example:\n N = 2, input[0] is 'hello world' and input[1] is 'a b c', then the output\n will be\n\n indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n shape = [2, 3]\n values = ['hello', 'world', 'a', 'b', 'c']","inputs":[{"description":"1-D. Strings to split.","name":"input","type":7},{"description":"0-D. Delimiter characters (bytes), or empty string.","name":"delimiter","type":7}],"outputs":[{"description":"A dense matrix of int64 representing the indices of the sparse tensor.","name":"indices","type":9},{"description":"A vector of strings corresponding to the splited values.","name":"values","type":7},{"description":"a length-2 vector of int64 representing the shape of the sparse\ntensor, where the first value is N and the second value is the maximum number\nof tokens in a single input entry.","name":"shape","type":9}],"summary":"Split elements of `input` based on `delimiter` into a `SparseTensor`."}},{"name":"StringSplitV2","schema":{"attributes":[{"default":-1,"description":"An `int`. If `maxsplit > 0`, limit of the split of the result.","name":"maxsplit","type":"int64"}],"description":"Let N be the size of source (typically N will be the batch size). Split each\nelement of `source` based on `sep` and return a `SparseTensor`\ncontaining the split tokens. Empty tokens are ignored.\n\nFor example, N = 2, source[0] is 'hello world' and source[1] is 'a b c',\nthen the output will be\n```\nst.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\nst.shape = [2, 3]\nst.values = ['hello', 'world', 'a', 'b', 'c']\n```\n\nIf `sep` is given, consecutive delimiters are not grouped together and are\ndeemed to delimit empty strings. For example, source of `\"1<>2<><>3\"` and\nsep of `\"<>\"` returns `[\"1\", \"2\", \"\", \"3\"]`. If `sep` is None or an empty\nstring, consecutive whitespace are regarded as a single separator, and the\nresult will contain no empty strings at the startor end if the string has\nleading or trailing whitespace.\n\nNote that the above mentioned behavior matches python's str.split.","inputs":[{"description":"`1-D` string `Tensor`, the strings to split.","name":"input","type":7},{"description":"`0-D` string `Tensor`, the delimiter character.","name":"sep","type":7}],"outputs":[{"name":"indices","type":9},{"name":"values","type":7},{"name":"shape","type":9}],"summary":"Split elements of `source` based on `sep` into a `SparseTensor`."}},{"name":"StringStrip","schema":{"inputs":[{"description":"A string `Tensor` of any shape.","name":"input","type":7}],"outputs":[{"description":"A string `Tensor` of the same shape as the input.\n\nExamples:\n\n>>> tf.strings.strip([\"\\nTensorFlow\", \" The python library \"]).numpy()\narray([b'TensorFlow', b'The python library'], dtype=object)","name":"output","type":7}],"summary":"Strip leading and trailing whitespaces from the Tensor."}},{"name":"StringToHashBucket","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The hash function is deterministic on the content of the string within the\nprocess.\n\nNote that the hash function may change from time to time.\nThis functionality will be deprecated and it's recommended to use\n`tf.string_to_hash_bucket_fast()` or `tf.string_to_hash_bucket_strong()`.","inputs":[{"name":"string_tensor","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToHashBucketFast","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"}],"description":"The hash function is deterministic on the content of the string within the\nprocess and will never change. However, it is not suitable for cryptography.\nThis function may be used when CPU time is scarce and inputs are trusted or\nunimportant. There is a risk of adversaries constructing inputs that all hash\nto the same bucket. To prevent this problem, use a strong hash function with\n`tf.string_to_hash_bucket_strong`.\n\nExamples:\n\n>>> tf.strings.to_hash_bucket_fast([\"Hello\", \"TensorFlow\", \"2.x\"], 3).numpy()\narray([0, 2, 2])","inputs":[{"description":"The strings to assign a hash bucket.","name":"input","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToHashBucketStrong","schema":{"attributes":[{"description":"The number of buckets.","minimum":1,"name":"num_buckets","type":"int64"},{"description":"The key used to seed the hash function, passed as a list of two uint64\nelements.","name":"key","type":"int64[]"}],"description":"The hash function is deterministic on the content of the string within the\nprocess. The hash function is a keyed hash function, where attribute `key`\ndefines the key of the hash function. `key` is an array of 2 elements.\n\nA strong hash is important when inputs may be malicious, e.g. URLs with\nadditional components. Adversaries could try to make their inputs hash to the\nsame bucket for a denial-of-service attack or to skew the results. A strong\nhash can be used to make it difficult to find inputs with a skewed hash value\ndistribution over buckets. This requires that the hash function is\nseeded by a high-entropy (random) \"key\" unknown to the adversary.\n\nThe additional robustness comes at a cost of roughly 4x higher compute\ntime than `tf.string_to_hash_bucket_fast`.\n\nExamples:\n\n>>> tf.strings.to_hash_bucket_strong([\"Hello\", \"TF\"], 3, [1, 2]).numpy()\narray([2, 0])","inputs":[{"description":"The strings to assign a hash bucket.","name":"input","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","type":9}],"summary":"Converts each string in the input Tensor to its hash mod by a number of buckets."}},{"name":"StringToNumber","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"The numeric type to interpret each string in `string_tensor` as. Must be one of the following: `float32`, `float64`, `int32`, `int64`.","name":"out_type","type":"type"}],"description":"(Note that int32 overflow results in an error while float overflow\nresults in a rounded value.)\n\nExample:\n\n>>> strings = [\"5.0\", \"3.0\", \"7.0\"]\n>>> tf.strings.to_number(strings)\n\n","inputs":[{"name":"string_tensor","type":7}],"outputs":[{"description":"A Tensor of the same shape as the input `string_tensor`.","name":"output","typeAttr":"out_type"}],"summary":"Converts each string in the input Tensor to the specified numeric type."}},{"name":"StringUpper","schema":{"attributes":[{"default":"","name":"encoding","type":"string"}],"description":"Example:\n\n>>> tf.strings.upper(\"CamelCase string and ALL CAPS\")\n\n","inputs":[{"name":"input","type":7}],"outputs":[{"name":"output","type":7}],"summary":"Converts all lowercase characters into their respective uppercase replacements."}},{"name":"Sub","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `uint32`.","name":"T","type":"type"}],"description":"*NOTE*: `Sub` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x - y element-wise."}},{"name":"Substr","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"},{"default":"BYTE","description":"The unit that is used to create the substring. One of: `\"BYTE\"` (for\ndefining position and length by bytes) or `\"UTF8_CHAR\"` (for the UTF-8\nencoded Unicode code points). The default is `\"BYTE\"`. Results are undefined if\n`unit=UTF8_CHAR` and the `input` strings do not contain structurally valid\nUTF-8. Must be one of the following: `BYTE`, `UTF8_CHAR`.","name":"unit","type":"string"}],"description":"For each string in the input `Tensor`, creates a substring starting at index\n`pos` with a total length of `len`.\n\nIf `len` defines a substring that would extend beyond the length of the input\nstring, or if `len` is negative, then as many characters as possible are used.\n\nA negative `pos` indicates distance within the string backwards from the end.\n\nIf `pos` specifies an index which is out of range for any of the input strings,\nthen an `InvalidArgumentError` is thrown.\n\n`pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on\nOp creation.\n\n*NOTE*: `Substr` supports broadcasting up to two dimensions. More about\nbroadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n\n---\n\nExamples\n\nUsing scalar `pos` and `len`:\n\n```python\ninput = [b'Hello', b'World']\nposition = 1\nlength = 3\n\noutput = [b'ell', b'orl']\n```\n\nUsing `pos` and `len` with same shape as `input`:\n\n```python\ninput = [[b'ten', b'eleven', b'twelve'],\n [b'thirteen', b'fourteen', b'fifteen'],\n [b'sixteen', b'seventeen', b'eighteen']]\nposition = [[1, 2, 3],\n [1, 2, 3],\n [1, 2, 3]]\nlength = [[2, 3, 4],\n [4, 3, 2],\n [5, 5, 5]]\n\noutput = [[b'en', b'eve', b'lve'],\n [b'hirt', b'urt', b'te'],\n [b'ixtee', b'vente', b'hteen']]\n```\n\nBroadcasting `pos` and `len` onto `input`:\n\n```\ninput = [[b'ten', b'eleven', b'twelve'],\n [b'thirteen', b'fourteen', b'fifteen'],\n [b'sixteen', b'seventeen', b'eighteen'],\n [b'nineteen', b'twenty', b'twentyone']]\nposition = [1, 2, 3]\nlength = [1, 2, 3]\n\noutput = [[b'e', b'ev', b'lve'],\n [b'h', b'ur', b'tee'],\n [b'i', b've', b'hte'],\n [b'i', b'en', b'nty']]\n```\n\nBroadcasting `input` onto `pos` and `len`:\n\n```\ninput = b'thirteen'\nposition = [1, 5, 7]\nlength = [3, 2, 1]\n\noutput = [b'hir', b'ee', b'n']\n```\n\nRaises:\n\n * `ValueError`: If the first argument cannot be converted to a\n Tensor of `dtype string`.\n * `InvalidArgumentError`: If indices are out of range.\n * `ValueError`: If `pos` and `len` are not the same shape.\n","inputs":[{"description":"Tensor of strings","name":"input","type":7},{"description":"Scalar defining the position of first character in each substring","name":"pos","typeAttr":"T"},{"description":"Scalar defining the number of characters to include in each substring","name":"len","typeAttr":"T"}],"outputs":[{"description":"Tensor of substrings","name":"output","type":7}],"summary":"Return substrings from `Tensor` of strings."}},{"name":"Sum","schema":{"attributes":[{"default":false,"description":"If true, retain reduced dimensions with length 1.","name":"keep_dims","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"Reduces `input` along the dimensions given in `reduction_indices`. Unless\n`keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in\n`reduction_indices`. If `keep_dims` is true, the reduced dimensions are\nretained with length 1.","inputs":[{"description":"The tensor to reduce.","name":"input","typeAttr":"T"},{"description":"The dimensions to reduce. Must be in the range\n`[-rank(input), rank(input))`.","name":"reduction_indices","typeAttr":"Tidx"}],"outputs":[{"description":"The reduced tensor.","name":"output","typeAttr":"T"}],"summary":"Computes the sum of elements across dimensions of a tensor."}},{"name":"SummaryWriter","schema":{"attributes":[{"default":"","name":"shared_name","type":"string"},{"default":"","name":"container","type":"string"}],"outputs":[{"name":"writer","type":20}]}},{"name":"Svd","schema":{"attributes":[{"default":true,"description":"If true, left and right singular vectors will be\ncomputed and returned in `u` and `v`, respectively.\nIf false, `u` and `v` are not set and should never referenced.","name":"compute_uv","type":"boolean"},{"default":false,"description":"If true, compute full-sized `u` and `v`. If false\n(the default), compute only the leading `P` singular vectors.\nIgnored if `compute_uv` is `False`.","name":"full_matrices","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `float16`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Computes the SVD of each inner matrix in `input` such that\n`input[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])`\n\n```python\n# a is a tensor containing a batch of matrices.\n# s is a tensor of singular values for each matrix.\n# u is the tensor containing the left singular vectors for each matrix.\n# v is the tensor containing the right singular vectors for each matrix.\ns, u, v = svd(a)\ns, _, _ = svd(a, compute_uv=False)\n```","inputs":[{"description":"A tensor of shape `[..., M, N]` whose inner-most 2 dimensions\nform matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"Singular values. Shape is `[..., P]`.","name":"s","typeAttr":"T"},{"description":"Left singular vectors. If `full_matrices` is `False` then shape is\n`[..., M, P]`; if `full_matrices` is `True` then shape is\n`[..., M, M]`. Undefined if `compute_uv` is `False`.","name":"u","typeAttr":"T"},{"description":"Left singular vectors. If `full_matrices` is `False` then shape is\n`[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`.\nUndefined if `compute_uv` is false.","name":"v","typeAttr":"T"}],"summary":"Computes the singular value decompositions of one or more matrices."}},{"name":"Switch","schema":{"attributes":[{"name":"T","type":"type"}],"description":"If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise,\nthe data goes to `output_false`.\n\nSee also `RefSwitch` and `Merge`.","inputs":[{"description":"The tensor to be forwarded to the appropriate output.","name":"data","typeAttr":"T"},{"description":"A scalar that specifies which output port will receive data.","name":"pred","type":10}],"outputs":[{"description":"If `pred` is false, data will be forwarded to this output.","name":"output_false","typeAttr":"T"},{"description":"If `pred` is true, data will be forwarded to this output.","name":"output_true","typeAttr":"T"}],"summary":"Forwards `data` to the output port determined by `pred`."}},{"name":"SymbolicGradient","schema":{"attributes":[{"description":"the type list for the input list.","minimum":1,"name":"Tin","type":"type[]"},{"description":"the type list for the input list.","minimum":1,"name":"Tout","type":"type[]"},{"description":"The function we want to compute the gradient for.\n\nThe function 'f' must be a numerical function which takes N inputs and\nproduces M outputs. Its gradient function 'g', which is computed by\nthis SymbolicGradient op is a function taking N + M inputs and\nproduces N outputs.\n\nI.e. if we have\n (y1, y2, ..., y_M) = f(x1, x2, ..., x_N),\nthen, g is\n (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N,\n dL/dy1, dL/dy2, ..., dL/dy_M),\n\nwhere L is a scalar-value function of (x1, x2, ..., xN) (e.g., the\nloss function). dL/dx_i is the partial derivative of L with respect\nto x_i.\n\n(Needs some math expert to say the comment above better.)","name":"f","type":"function"}],"inputs":[{"description":"a list of input tensors of size N + M;","name":"input","typeListAttr":"Tin"}],"outputs":[{"description":"a list of output tensors of size N;","name":"output","typeListAttr":"Tout"}],"summary":"Computes the gradient function for function f via backpropagation."}},{"name":"TFRecordDataset","schema":{"inputs":[{"description":"A scalar or vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7},{"description":"A scalar representing the number of bytes to buffer. A value of\n0 means no buffering will be performed.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the records from one or more TFRecord files."}},{"name":"TFRecordReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","name":"compression_type","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the records from a TensorFlow Records file."}},{"name":"TFRecordReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"},{"default":"","name":"compression_type","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the records from a TensorFlow Records file."}},{"name":"TPUCompilationResult","schema":{"description":"This operation returns the result of a TPU compilation as a serialized\nCompilationResultProto, which holds a status and an error message if an error\noccurred during compilation.","outputs":[{"name":"output","type":7}],"summary":"Returns the result of a TPU compilation."}},{"name":"TPUCompile","schema":{"attributes":[{"minimum":0,"name":"num_computations","type":"int64"},{"name":"function","type":"function"},{"name":"metadata","type":"string"},{"minimum":0,"name":"NumDynamicShapes","type":"int64"},{"minimum":0,"name":"Tguaranteed_constants","type":"type[]"}],"description":"For the internal use of the distributed TPU compiler.\n\n'num_computations' is the number of computations to be compiled.\n'function' is a function containing the computation to compile.\n'dynamic_shapes' contains dynamic shapes of arguments whose shapes were not\nknown statically at TPUReplication rewrite time.\n'guaranteed_constants' is a list of tensors which have been guaranteed to not\nchange their values during the session lifetime. These contain tensors marked as\nconstant using the GuaranteeConstOp.\n'metadata' is a serialized TPUCompileMetadataProto describing\nthe shapes and types of the inputs to the computation, as well as a mapping onto\nthe TPU pod topology.\nEach 'program' output is a string key that is passed to the _TPUExecute op and\nused to look up the program in the compilation cache.\n'may_modify_variables' indicates whether variables may be modified.","inputs":[{"name":"dynamic_shapes","numberAttr":"NumDynamicShapes","type":9},{"name":"guaranteed_constants","typeListAttr":"Tguaranteed_constants"}],"outputs":[{"name":"compilation_status","type":7},{"name":"program","numberAttr":"num_computations","type":7},{"name":"may_modify_variables","numberAttr":"num_computations","type":10}],"summary":"Compiles a computations for execution on one or more TPU devices."}},{"name":"TPUCompileSucceededAssert","schema":{"description":"device during failure to ensure all pending device interactions fail.\n\n'compilation_status' is a serialized CompilationResultProto.","inputs":[{"name":"compilation_status","type":7}],"summary":"Asserts that compilation succeeded. This op produces no output and closes the"}},{"name":"TPUEmbeddingActivations","schema":{"attributes":[{"description":"The id of the table in the embedding layer configuration from which\nthese activations were computed.","minimum":0,"name":"table_id","type":"int64"},{"description":"Identifier of the set of embedding indices which produced these\nactivations.","minimum":0,"name":"lookup_id","type":"int64"}],"description":"This op simply returns its first input, which is assumed to have been sliced\nfrom the Tensors returned by TPUEmbeddingDequeueActivations. The presence of\nthis op, and its first argument being a trainable Variable, enables automatic\ndifferentiation of graphs containing embeddings via the TPU Embedding Python\nlibraries.","inputs":[{"description":"A trainable variable, enabling optimizers to find this op.","name":"embedding_variable","type":1},{"description":"The embedding activations Tensor to return.","name":"sliced_activations","type":1}],"outputs":[{"name":"output","type":1}],"summary":"An op enabling differentiation of TPU Embeddings."}},{"name":"TPUExecute","schema":{"attributes":[{"minimum":0,"name":"Targs","type":"type[]"},{"minimum":0,"name":"Tresults","type":"type[]"}],"description":"For the internal use of the distributed TPU compiler.","inputs":[{"name":"args","typeListAttr":"Targs"},{"name":"key","type":7}],"outputs":[{"name":"results","typeListAttr":"Tresults"}],"summary":"Op that loads and executes a TPU program on a TPU device."}},{"name":"TPUExecuteAndUpdateVariables","schema":{"attributes":[{"minimum":0,"name":"Targs","type":"type[]"},{"minimum":0,"name":"Tresults","type":"type[]"},{"minimum":0,"name":"device_var_reads_indices","type":"int64[]"},{"minimum":0,"name":"device_var_updates_indices","type":"int64[]"}],"description":"It (optionally) reads device variables, loads and executes a TPU program on a\nTPU device, and then (optionally) in-place updates variables using the program\noutputs, as specified in attributes device_var_reads_indices (program input\nindices from directly reading variables) and device_var_updates_indices (program\noutput indices used to update variables, -1 means no-update/read-only). Such\nprogram outputs are consumed by these variables will not appear in the op\noutput. For the internal use of the distributed TPU compiler.","inputs":[{"name":"args","typeListAttr":"Targs"},{"name":"key","type":7}],"outputs":[{"name":"results","typeListAttr":"Tresults"}],"summary":"Op that executes a program with optional in-place variable updates."}},{"name":"TPUOrdinalSelector","schema":{"description":"This Op produces a set of TPU cores (for warm-up) or a single TPU core\n(for regular inference) to execute the TPU program on. The output is\nconsumed by TPUPartitionedCall.","outputs":[{"description":"A vector 1 or more TPU cores.","name":"device_ordinals","type":3}],"summary":"A TPU core selector Op."}},{"name":"TPUPartitionedCall","schema":{"attributes":[{"description":"The types of the arguments to the function.","minimum":0,"name":"Tin","type":"type[]"},{"description":"The types of the outputs of the function.","minimum":0,"name":"Tout","type":"type[]"},{"description":"The function to call.","name":"f","type":"function"},{"default":0,"name":"autotuner_thresh","type":"int64"}],"inputs":[{"description":"The arguments to the function.","name":"args","typeListAttr":"Tin"},{"description":"The TPU device ordinal to run the function on.","name":"device_ordinal","type":3}],"outputs":[{"description":"The output of the function call.","name":"output","typeListAttr":"Tout"}],"summary":"Calls a function placed on a specified TPU device."}},{"name":"TPUPartitionedInput","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"An integer describles which dimension is partitioned. -1 means\nthose inputs are replicated.","name":"partition_dim","type":"int64"}],"inputs":[{"description":"A list of partitioned inputs which must have the same shape.","name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"description":"A handle which represents the full shape of partitioned tensors.","name":"output","typeAttr":"T"}],"summary":"An op that groups a list of partitioned inputs together. This op"}},{"name":"TPUPartitionedOutput","schema":{"attributes":[{"name":"T","type":"type"},{"minimum":1,"name":"num_splits","type":"int64"},{"default":0,"description":"An integer describles which dimension is partitioned.","name":"partition_dim","type":"int64"}],"description":"outputs outside the XLA computation.","inputs":[{"description":"A tensor which represents the full shape of partitioned tensors.","name":"inputs","typeAttr":"T"}],"outputs":[{"description":"A list of partitioned inputs which must have the same shape.","name":"output","numberAttr":"num_splits","typeAttr":"T"}],"summary":"An op that demultiplexes a tensor to be sharded by XLA to a list of partitioned"}},{"name":"TPUReplicateMetadata","schema":{"attributes":[{"description":"Number of replicas of the computation","minimum":0,"name":"num_replicas","type":"int64"},{"default":1,"description":"Number of cores per replica. Used for model parallelism.","name":"num_cores_per_replica","type":"int64"},{"default":"","description":"TopologyProto indicating the topology of the TPU pod slice.","name":"topology","type":"string"},{"default":true,"description":"Whether to place the computation on the TPU.","name":"use_tpu","type":"boolean"},{"default":[],"description":"The assignment of devices for the computation.","name":"device_assignment","type":"int64[]"},{"default":[],"description":"DEPRECATED. Use num_cores_per_replica instead.","name":"computation_shape","type":"int64[]"},{"default":[],"name":"host_compute_core","type":"string[]"},{"default":[],"name":"padding_map","type":"string[]"},{"default":"STEP_MARK_AT_ENTRY","name":"step_marker_location","type":"string"},{"default":false,"name":"allow_soft_placement","type":"boolean"},{"default":false,"name":"use_spmd_for_xla_partitioning","type":"boolean"}],"description":"This operation holds the metadata common to operations of a `tpu.replicate()` computation subgraph.","summary":"Metadata indicating how the TPU computation should be replicated."}},{"name":"TPUReplicatedInput","schema":{"attributes":[{"minimum":1,"name":"N","type":"int64"},{"name":"T","type":"type"},{"default":false,"name":"is_mirrored_variable","type":"boolean"},{"default":-1,"name":"index","type":"int64"},{"default":false,"name":"is_packed","type":"boolean"}],"description":"This operation holds a replicated input to a `tpu.replicate()` computation subgraph.\nEach replicated input has the same shape and type alongside the output.\n\nFor example:\n```\n%a = \"tf.opA\"()\n%b = \"tf.opB\"()\n%replicated_input = \"tf.TPUReplicatedInput\"(%a, %b)\n%computation = \"tf.Computation\"(%replicated_input)\n```\nThe above computation has a replicated input of two replicas.","inputs":[{"name":"inputs","numberAttr":"N","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Connects N inputs to an N-way replicated TPU computation."}},{"name":"TPUReplicatedOutput","schema":{"attributes":[{"minimum":1,"name":"num_replicas","type":"int64"},{"name":"T","type":"type"}],"description":"This operation holds a replicated output from a `tpu.replicate()` computation subgraph.\nEach replicated output has the same shape and type alongside the input.\n\nFor example:\n```\n%computation = \"tf.Computation\"()\n%replicated_output:2 = \"tf.TPUReplicatedOutput\"(%computation)\n```\nThe above computation has a replicated output of two replicas.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"outputs","numberAttr":"num_replicas","typeAttr":"T"}],"summary":"Connects N outputs from an N-way replicated TPU computation."}},{"name":"TakeDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A scalar representing the number of elements from the `input_dataset`\nthat should be taken. A value of `-1` indicates that all of `input_dataset`\nis taken.","name":"count","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains `count` elements from the `input_dataset`."}},{"name":"TakeManySparseFromTensorsMap","schema":{"attributes":[{"description":"The `dtype` of the `SparseTensor` objects stored in the\n`SparseTensorsMap`.","name":"dtype","type":"type"},{"default":"","description":"The container name for the `SparseTensorsMap` read by this op.","name":"container","type":"string"},{"default":"","description":"The shared name for the `SparseTensorsMap` read by this op.\nIt should not be blank; rather the `shared_name` or unique Operation name\nof the Op that created the original `SparseTensorsMap` should be used.","name":"shared_name","type":"string"}],"description":"The input `sparse_handles` must be an `int64` matrix of shape `[N, 1]` where\n`N` is the minibatch size and the rows correspond to the output handles of\n`AddSparseToTensorsMap` or `AddManySparseToTensorsMap`. The ranks of the\noriginal `SparseTensor` objects that went into the given input ops must all\nmatch. When the final `SparseTensor` is created, it has rank one\nhigher than the ranks of the incoming `SparseTensor` objects\n(they have been concatenated along a new row dimension on the left).\n\nThe output `SparseTensor` object's shape values for all dimensions but the\nfirst are the max across the input `SparseTensor` objects' shape values\nfor the corresponding dimensions. Its first shape value is `N`, the minibatch\nsize.\n\nThe input `SparseTensor` objects' indices are assumed ordered in\nstandard lexicographic order. If this is not the case, after this\nstep run `SparseReorder` to restore index ordering.\n\nFor example, if the handles represent an input, which is a `[2, 3]` matrix\nrepresenting two original `SparseTensor` objects:\n\n```\n index = [ 0]\n [10]\n [20]\n values = [1, 2, 3]\n shape = [50]\n```\n\nand\n\n```\n index = [ 2]\n [10]\n values = [4, 5]\n shape = [30]\n```\n\nthen the final `SparseTensor` will be:\n\n```\n index = [0 0]\n [0 10]\n [0 20]\n [1 2]\n [1 10]\n values = [1, 2, 3, 4, 5]\n shape = [2 50]\n```","inputs":[{"description":"1-D, The `N` serialized `SparseTensor` objects.\nShape: `[N]`.","name":"sparse_handles","type":9}],"outputs":[{"description":"2-D. The `indices` of the minibatch `SparseTensor`.","name":"sparse_indices","type":9},{"description":"1-D. The `values` of the minibatch `SparseTensor`.","name":"sparse_values","typeAttr":"dtype"},{"description":"1-D. The `shape` of the minibatch `SparseTensor`.","name":"sparse_shape","type":9}],"summary":"Read `SparseTensors` from a `SparseTensorsMap` and concatenate them."}},{"name":"TakeWhileDataset","schema":{"attributes":[{"description":"A function returning a scalar boolean.","name":"predicate","type":"function"},{"minimum":0,"name":"Targuments","type":"type[]"},{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"description":"The `predicate` function must return a scalar boolean and accept the\nfollowing arguments:\n\n* One tensor for each component of an element of `input_dataset`.\n* One tensor for each value in `other_arguments`.","inputs":[{"name":"input_dataset","type":21},{"description":"A list of tensors, typically values that were captured when\nbuilding a closure for `predicate`.","name":"other_arguments","typeListAttr":"Targuments"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that stops iteration when predicate` is false."}},{"name":"Tan","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes tangent of every\n element in the tensor. Input range is `(-inf, inf)` and\n output range is `(-inf, inf)`. If input lies outside the boundary, `nan`\n is returned.\n\n ```python\n x = tf.constant([-float(\"inf\"), -9, -0.5, 1, 1.2, 200, 10000, float(\"inf\")])\n tf.math.tan(x) ==> [nan 0.45231566 -0.5463025 1.5574077 2.572152 -1.7925274 0.32097113 nan]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes tan of x element-wise."}},{"name":"Tanh","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Given an input tensor, this function computes hyperbolic tangent of every\n element in the tensor. Input range is `[-inf, inf]` and\n output range is `[-1,1]`.\n\n ```python\n x = tf.constant([-float(\"inf\"), -5, -0.5, 1, 1.2, 2, 3, float(\"inf\")])\n tf.math.tanh(x) ==> [-1. -0.99990916 -0.46211717 0.7615942 0.8336547 0.9640276 0.9950547 1.]\n ```","inputs":[{"name":"x","typeAttr":"T"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Computes hyperbolic tangent of `x` element-wise."}},{"name":"TanhGrad","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Specifically, `grad = dy * (1 - y*y)`, where `y = tanh(x)`, and `dy`\nis the corresponding input gradient.","inputs":[{"name":"y","typeAttr":"T"},{"name":"dy","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Computes the gradient for the tanh of `x` wrt its input."}},{"name":"TemporaryVariable","schema":{"attributes":[{"description":"The shape of the variable tensor.","name":"shape","type":"shape"},{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"},{"default":"","description":"Overrides the name used for the temporary variable resource. Default\nvalue is the name of the 'TemporaryVariable' op (which is guaranteed unique).","name":"var_name","type":"string"}],"description":"This is an experimental op for internal use only and it is possible to use this\nop in unsafe ways. DO NOT USE unless you fully understand the risks.\n\nIt is the caller's responsibility to ensure that 'ref' is eventually passed to a\nmatching 'DestroyTemporaryVariable' op after all other uses have completed.\n\nOutputs a ref to the tensor state so it may be read or modified.\n\n E.g.\n var = state_ops._temporary_variable([1, 2], types.float_)\n var_name = var.op.name\n var = state_ops.assign(var, [[4.0, 5.0]])\n var = state_ops.assign_add(var, [[6.0, 7.0]])\n final = state_ops._destroy_temporary_variable(var, var_name=var_name)","outputs":[{"description":"A reference to the variable tensor.","isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Returns a tensor that may be mutated, but only persists within a single step."}},{"name":"TensorArray","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":false,"name":"dynamic_size","type":"boolean"},{"default":true,"name":"clear_after_read","type":"boolean"},{"default":"","name":"tensor_array_name","type":"string"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"name":"size","type":3}],"outputs":[{"isRef":true,"name":"handle","type":7}]}},{"name":"TensorArrayClose","schema":{"inputs":[{"isRef":true,"name":"handle","type":7}]}},{"name":"TensorArrayCloseV2","schema":{"inputs":[{"name":"handle","type":7}],"summary":"Deprecated. Use TensorArrayCloseV3"}},{"name":"TensorArrayCloseV3","schema":{"description":"This enables the user to close and release the resource in the middle\nof a step/run.","inputs":[{"description":"The handle to a TensorArray (output of TensorArray or TensorArrayGrad).","name":"handle","type":20}],"summary":"Delete the TensorArray from its resource container."}},{"name":"TensorArrayConcat","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape_except0","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"},{"name":"lengths","type":9}]}},{"name":"TensorArrayConcatV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape_except0","type":"shape"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"},{"name":"lengths","type":9}],"summary":"Deprecated. Use TensorArrayConcatV3"}},{"name":"TensorArrayConcatV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known,\nexcluding the first dimension. Used to validate the shapes of\nTensorArray elements. If this shape is not fully specified, concatenating\nzero-size TensorArrays is an error.","name":"element_shape_except0","type":"shape"}],"description":"Takes `T` elements of shapes\n\n ```\n (n0 x d0 x d1 x ...), (n1 x d0 x d1 x ...), ..., (n(T-1) x d0 x d1 x ...)\n ```\n\nand concatenates them into a Tensor of shape:\n\n ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)```\n\nAll elements must have the same shape (excepting the first dimension).","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"All of the elements in the TensorArray, concatenated along the first\naxis.","name":"value","typeAttr":"dtype"},{"description":"A vector of the row sizes of the original T elements in the\nvalue output. In the example above, this would be the values:\n`(n1, n2, ..., n(T-1))`.","name":"lengths","type":9}],"summary":"Concat the elements from the TensorArray into value `value`."}},{"name":"TensorArrayGather","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"indices","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayGatherV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"name":"handle","type":7},{"name":"indices","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Deprecated. Use TensorArrayGatherV3"}},{"name":"TensorArrayGatherV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known. Used to\nvalidate the shapes of TensorArray elements. If this shape is not\nfully specified, gathering zero-size TensorArrays is an error.","name":"element_shape","type":"shape"}],"description":"All elements selected by `indices` must have the same shape.","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The locations in the TensorArray from which to read tensor elements.","name":"indices","type":3},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"All of the elements in the TensorArray, concatenated along a new\naxis (the new dimension 0).","name":"value","typeAttr":"dtype"}],"summary":"Gather specific elements from the TensorArray into output `value`."}},{"name":"TensorArrayGrad","schema":{"attributes":[{"name":"source","type":"string"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"isRef":true,"name":"grad_handle","type":7}]}},{"name":"TensorArrayGradV2","schema":{"attributes":[{"name":"source","type":"string"}],"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"grad_handle","type":7}],"summary":"Deprecated. Use TensorArrayGradV3"}},{"name":"TensorArrayGradV3","schema":{"attributes":[{"description":"The gradient source string, used to decide which gradient TensorArray\nto return.","name":"source","type":"string"}],"description":"If the given TensorArray gradient already exists, returns a reference to it.\n\nLocks the size of the original TensorArray by disabling its dynamic size flag.\n\n**A note about the input flow_in:**\n\nThe handle flow_in forces the execution of the gradient lookup to occur\nonly after certain other operations have occurred. For example, when\nthe forward TensorArray is dynamically sized, writes to this TensorArray\nmay resize the object. The gradient TensorArray is statically sized based\non the size of the forward TensorArray when this operation executes.\nFurthermore, the size of the forward TensorArray is frozen by this call.\nAs a result, the flow is used to ensure that the call to generate the gradient\nTensorArray only happens after all writes are executed.\n\nIn the case of dynamically sized TensorArrays, gradient computation should\nonly be performed on read operations that have themselves been chained via\nflow to occur only after all writes have executed. That way the final size\nof the forward TensorArray is known when this operation is called.\n\n**A note about the source attribute:**\n\nTensorArray gradient calls use an accumulator TensorArray object. If\nmultiple gradients are calculated and run in the same session, the multiple\ngradient nodes may accidentally flow through the same accumulator TensorArray.\nThis double counts and generally breaks the TensorArray gradient flow.\n\nThe solution is to identify which gradient call this particular\nTensorArray gradient is being called in. This is performed by identifying\na unique string (e.g. \"gradients\", \"gradients_1\", ...) from the input\ngradient Tensor's name. This string is used as a suffix when creating\nthe TensorArray gradient object here (the attribute `source`).\n\nThe attribute `source` is added as a suffix to the forward TensorArray's\nname when performing the creation / lookup, so that each separate gradient\ncalculation gets its own TensorArray accumulator.","inputs":[{"description":"The handle to the forward TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"name":"grad_handle","type":20},{"name":"flow_out","type":1}],"summary":"Creates a TensorArray for storing the gradients of values in the given handle."}},{"name":"TensorArrayGradWithShape","schema":{"attributes":[{"description":"The gradient source string, used to decide which gradient TensorArray\nto return.","name":"source","type":"string"}],"description":"Similar to TensorArrayGradV3. However it creates an accumulator with an\nexpanded shape compared to the input TensorArray whose gradient is being\ncomputed. This enables multiple gradients for the same TensorArray to be\ncalculated using the same accumulator.","inputs":[{"description":"The handle to the forward TensorArray.","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1},{"description":"An int32 vector representing a shape. Elements in the gradient accumulator will\nhave shape which is this shape_to_prepend value concatenated with shape of the\nelements in the TensorArray corresponding to the input handle.","name":"shape_to_prepend","type":3}],"outputs":[{"name":"grad_handle","type":20},{"name":"flow_out","type":1}],"summary":"Creates a TensorArray for storing multiple gradients of values in the given handle."}},{"name":"TensorArrayPack","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayRead","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"index","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}]}},{"name":"TensorArrayReadV2","schema":{"attributes":[{"name":"dtype","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"index","type":3},{"name":"flow_in","type":1}],"outputs":[{"name":"value","typeAttr":"dtype"}],"summary":"Deprecated. Use TensorArrayReadV3"}},{"name":"TensorArrayReadV3","schema":{"attributes":[{"description":"The type of the elem that is returned.","name":"dtype","type":"type"}],"inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"name":"index","type":3},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"The tensor that is read from the TensorArray.","name":"value","typeAttr":"dtype"}],"summary":"Read an element from the TensorArray into output `value`."}},{"name":"TensorArrayScatter","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"indices","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayScatterV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"indices","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArrayScatterV3"}},{"name":"TensorArrayScatterV3","schema":{"attributes":[{"name":"T","type":"type"}],"description":"`indices` must be a vector, its length must match the first dim of `value`.","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The locations at which to write the tensor elements.","name":"indices","type":3},{"description":"The concatenated tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Scatter the data from the input value into specific TensorArray elements."}},{"name":"TensorArraySize","schema":{"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"size","type":3}]}},{"name":"TensorArraySizeV2","schema":{"inputs":[{"name":"handle","type":7},{"name":"flow_in","type":1}],"outputs":[{"name":"size","type":3}],"summary":"Deprecated. Use TensorArraySizeV3"}},{"name":"TensorArraySizeV3","schema":{"inputs":[{"description":"The handle to a TensorArray (output of TensorArray or TensorArrayGrad).","name":"handle","type":20},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"The current size of the TensorArray.","name":"size","type":3}],"summary":"Get the current size of the TensorArray."}},{"name":"TensorArraySplit","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"lengths","type":9},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArraySplitV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"lengths","type":9},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArraySplitV3"}},{"name":"TensorArraySplitV3","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Assuming that `lengths` takes on values\n\n ```(n0, n1, ..., n(T-1))```\n\nand that `value` has shape\n\n ```(n0 + n1 + ... + n(T-1) x d0 x d1 x ...)```,\n\nthis splits values into a TensorArray with T tensors.\n\nTensorArray index t will be the subtensor of values with starting position\n\n ```(n0 + n1 + ... + n(t-1), 0, 0, ...)```\n\nand having size\n\n ```nt x d0 x d1 x ...```","inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The concatenated tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"The vector of lengths, how to split the rows of value into the\nTensorArray.","name":"lengths","type":9},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Split the data from the input value into TensorArray elements."}},{"name":"TensorArrayUnpack","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayV2","schema":{"attributes":[{"name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"},{"default":false,"name":"dynamic_size","type":"boolean"},{"default":true,"name":"clear_after_read","type":"boolean"},{"default":"","name":"tensor_array_name","type":"string"}],"inputs":[{"name":"size","type":3}],"outputs":[{"name":"handle","type":7}],"summary":"Deprecated. Use TensorArrayV3"}},{"name":"TensorArrayV3","schema":{"attributes":[{"description":"The type of the elements on the tensor_array.","name":"dtype","type":"type"},{"default":{"type":"shape","value":"?"},"description":"The expected shape of an element, if known. Used to\nvalidate the shapes of TensorArray elements. If this shape is not\nfully specified, gathering zero-size TensorArrays is an error.","name":"element_shape","type":"shape"},{"default":false,"description":"A boolean that determines whether writes to the TensorArray\nare allowed to grow the size. By default, this is not allowed.","name":"dynamic_size","type":"boolean"},{"default":true,"description":"If true (default), Tensors in the TensorArray are cleared\nafter being read. This disables multiple read semantics but allows early\nrelease of memory.","name":"clear_after_read","type":"boolean"},{"default":false,"description":"If true (default is false), then all\nelements in the TensorArray will be expected to have have identical shapes.\nThis allows certain behaviors, like dynamically checking for\nconsistent shapes on write, and being able to fill in properly\nshaped zero tensors on stack -- even if the element_shape attribute\nis not fully defined.","name":"identical_element_shapes","type":"boolean"},{"default":"","description":"Overrides the name used for the temporary tensor_array\nresource. Default value is the name of the 'TensorArray' op (which\nis guaranteed unique).","name":"tensor_array_name","type":"string"}],"description":"Write data via Write and read via Read or Pack.","inputs":[{"description":"The size of the array.","name":"size","type":3}],"outputs":[{"description":"The handle to the TensorArray.","name":"handle","type":20},{"description":"A scalar used to control gradient flow.","name":"flow","type":1}],"summary":"An array of Tensors of given size."}},{"name":"TensorArrayWrite","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"isRef":true,"name":"handle","type":7},{"name":"index","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}]}},{"name":"TensorArrayWriteV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"handle","type":7},{"name":"index","type":3},{"name":"value","typeAttr":"T"},{"name":"flow_in","type":1}],"outputs":[{"name":"flow_out","type":1}],"summary":"Deprecated. Use TensorArrayGradV3"}},{"name":"TensorArrayWriteV3","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"The handle to a TensorArray.","name":"handle","type":20},{"description":"The position to write to inside the TensorArray.","name":"index","type":3},{"description":"The tensor to write to the TensorArray.","name":"value","typeAttr":"T"},{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_in","type":1}],"outputs":[{"description":"A float scalar that enforces proper chaining of operations.","name":"flow_out","type":1}],"summary":"Push an element onto the tensor_array."}},{"name":"TensorDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits `components` as a tuple of tensors once."}},{"name":"TensorForestCreateTreeVariable","schema":{"inputs":[{"description":"Handle to the tree resource to be created.","name":"tree_handle","type":20},{"description":"Serialized proto string of the boosted_trees.Tree.","name":"tree_config","type":7}],"summary":"Creates a tree resource and returns a handle to it."}},{"name":"TensorForestTreeDeserialize","schema":{"inputs":[{"description":"Handle to the tree resource to be restored.","name":"tree_handle","type":20},{"description":"Serialied proto string of the boosted_trees.Tree proto.","name":"tree_config","type":7}],"summary":"Deserializes a proto into the tree handle"}},{"name":"TensorForestTreeIsInitializedOp","schema":{"inputs":[{"description":"Handle to the tree.","name":"tree_handle","type":20}],"outputs":[{"description":"Whether the tree is initialized.","name":"is_initialized","type":10}],"summary":"Checks whether a tree has been initialized."}},{"name":"TensorForestTreePredict","schema":{"attributes":[{"description":"Scalar, dimension of the logits.","name":"logits_dimension","type":"int64"}],"inputs":[{"description":"Handle to the tree resource.","name":"tree_handle","type":20},{"description":"Rank 2 dense features tensor.","name":"dense_features","type":1}],"outputs":[{"description":"The logits predictions from the tree for each instance in the batch.","name":"logits","type":1}],"summary":"Output the logits for the given input data"}},{"name":"TensorForestTreeResourceHandleOp","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a TensorForestTreeResource"}},{"name":"TensorForestTreeSerialize","schema":{"inputs":[{"description":"Handle to the tree resource to be serialized.","name":"tree_handle","type":20}],"outputs":[{"description":"Serialied proto string of the tree resource.","name":"tree_config","type":7}],"summary":"Serializes the tree handle to a proto"}},{"name":"TensorForestTreeSize","schema":{"inputs":[{"description":"Handle to the tree resource.","name":"tree_handle","type":20}],"outputs":[{"description":"The size of the tree.","name":"tree_size","type":3}],"summary":"Get the number of nodes in a tree"}},{"name":"TensorListConcat","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"default":{"type":"shape","value":"?"},"name":"element_shape","type":"shape"}],"description":"Requires that all tensors have the same shape except the first dimension.\n\ninput_handle: The input list.\ntensor: The concated result.\nlengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient.\n","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"lengths","type":9}],"summary":"Concats all tensors in the list along the 0th dimension."}},{"name":"TensorListConcatLists","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_a","type":21},{"name":"input_b","type":21}],"outputs":[{"name":"output","type":21}]}},{"name":"TensorListConcatV2","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Requires that all tensors have the same shape except the first dimension.\n\ninput_handle: The input list.\nelement_shape: The shape of the uninitialized elements in the list. If the first\n dimension is not -1, it is assumed that all list elements have the same\n leading dim.\nleading_dims: The list of leading dims of uninitialized list elements. Used if\n the leading dim of input_handle.element_shape or the element_shape input arg\n is not already set.\ntensor: The concated result.\nlengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient.\n","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","typeAttr":"shape_type"},{"name":"leading_dims","type":9}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"lengths","type":9}],"summary":"Concats all tensors in the list along the 0th dimension."}},{"name":"TensorListElementShape","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":" input_handle: the list\n element_shape: the shape of elements of the list","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"element_shape","typeAttr":"shape_type"}],"summary":"The shape of the elements of the given list, as a tensor."}},{"name":"TensorListFromTensor","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each tensor in the result list corresponds to one row of the input tensor.\n\ntensor: The input tensor.\noutput_handle: The list.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"element_shape","typeAttr":"shape_type"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList which, when stacked, has the value of `tensor`."}},{"name":"TensorListGather","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Each row in the produced Tensor corresponds to the element in the TensorList\nspecified by the given index (see `tf.gather`).\n\ninput_handle: The input tensor list.\nindices: The indices used to index into the list.\nvalues: The tensor.","inputs":[{"name":"input_handle","type":21},{"name":"indices","type":3},{"name":"element_shape","type":3}],"outputs":[{"name":"values","typeAttr":"element_dtype"}],"summary":"Creates a Tensor by indexing into the TensorList."}},{"name":"TensorListGetItem","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_handle","type":21},{"name":"index","type":3},{"name":"element_shape","type":3}],"outputs":[{"name":"item","typeAttr":"element_dtype"}]}},{"name":"TensorListLength","schema":{"description":"input_handle: the input list\nlength: the number of tensors in the list","inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"length","type":3}],"summary":"Returns the number of tensors in the input tensor list."}},{"name":"TensorListPopBack","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Fails if the list is empty.\n\ninput_handle: the input list\ntensor: the withdrawn last element of the list\nelement_dtype: the type of elements in the list\nelement_shape: the shape of the output tensor","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","type":3}],"outputs":[{"name":"output_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"summary":"Returns the last element of the input list as well as a list with all but that element."}},{"name":"TensorListPushBack","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"tensor: The tensor to put on the list.\ninput_handle: The old list.\noutput_handle: A list with the elements of the old list followed by tensor.\nelement_dtype: the type of elements in the list.\nelement_shape: a shape compatible with that of elements in the list.","inputs":[{"name":"input_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Returns a list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`."}},{"name":"TensorListPushBackBatch","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"inputs":[{"name":"input_handles","type":21},{"name":"tensor","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handles","type":21}]}},{"name":"TensorListReserve","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"element_shape: the shape of the future elements of the list\nnum_elements: the number of elements to reserve\nhandle: the output list\nelement_dtype: the desired type of elements in the list.","inputs":[{"name":"element_shape","typeAttr":"shape_type"},{"name":"num_elements","type":3}],"outputs":[{"name":"handle","type":21}],"summary":"List of the given size with empty elements."}},{"name":"TensorListResize","schema":{"description":"\ninput_handle: the input list\nsize: size of the output list\n","inputs":[{"name":"input_handle","type":21},{"name":"size","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Resizes the list."}},{"name":"TensorListScatter","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ntensor: The input tensor.\nindices: The indices used to index into the list.\nelement_shape: The shape of the elements in the list (can be less specified than\n the shape of the tensor).\noutput_handle: The TensorList.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3},{"name":"element_shape","typeAttr":"shape_type"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList by indexing into a Tensor."}},{"name":"TensorListScatterIntoExistingList","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ninput_handle: The list to scatter into.\ntensor: The input tensor.\nindices: The indices used to index into the list.\noutput_handle: The TensorList.","inputs":[{"name":"input_handle","type":21},{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Scatters tensor at indices in an input list."}},{"name":"TensorListScatterV2","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"Each member of the TensorList corresponds to one row of the input tensor,\nspecified by the given index (see `tf.gather`).\n\ntensor: The input tensor.\nindices: The indices used to index into the list.\nelement_shape: The shape of the elements in the list (can be less specified than\n the shape of the tensor).\nnum_elements: The size of the output list. Must be large enough to accommodate\n the largest index in indices. If -1, the list is just large enough to include\n the largest index in indices.\noutput_handle: The TensorList.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"indices","type":3},{"name":"element_shape","typeAttr":"shape_type"},{"name":"num_elements","type":3}],"outputs":[{"name":"output_handle","type":21}],"summary":"Creates a TensorList by indexing into a Tensor."}},{"name":"TensorListSetItem","schema":{"attributes":[{"name":"element_dtype","type":"type"}],"description":"input_handle: the list\nindex: the position in the list to which the tensor will be assigned\nitem: the element to be assigned to that position\noutput_handle: the new list, with the element in the proper position\n","inputs":[{"name":"input_handle","type":21},{"name":"index","type":3},{"name":"item","typeAttr":"element_dtype"}],"outputs":[{"name":"output_handle","type":21}],"summary":"Sets the index-th position of the list to contain the given tensor."}},{"name":"TensorListSplit","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"shape_type","type":"type"}],"description":"list[i] corresponds to lengths[i] tensors from the input tensor.\nThe tensor must have rank at least 1 and contain exactly sum(lengths) elements.\n\ntensor: The input tensor.\nelement_shape: A shape compatible with that of elements in the tensor.\nlengths: Vector of sizes of the 0th dimension of tensors in the list.\noutput_handle: The list.","inputs":[{"name":"tensor","typeAttr":"element_dtype"},{"name":"element_shape","typeAttr":"shape_type"},{"name":"lengths","type":9}],"outputs":[{"name":"output_handle","type":21}],"summary":"Splits a tensor into a list."}},{"name":"TensorListStack","schema":{"attributes":[{"name":"element_dtype","type":"type"},{"default":-1,"name":"num_elements","type":"int64"}],"description":"Requires that all tensors have the same shape.\n\ninput_handle: the input list\ntensor: the gathered result\nnum_elements: optional. If not -1, the number of elements in the list.\n","inputs":[{"name":"input_handle","type":21},{"name":"element_shape","type":3}],"outputs":[{"name":"tensor","typeAttr":"element_dtype"}],"summary":"Stacks all tensors in the list."}},{"name":"TensorScatterAdd","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by adding sparse `updates` to the passed\nin `tensor`.\nThis operation is very similar to `tf.scatter_nd_add`, except that the updates\nare added onto an existing tensor (as opposed to a variable). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`tensor.shape`. The last dimension of `indices` can be at most the rank of\n`tensor.shape`:\n\n indices.shape[-1] <= tensor.shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = tensor.shape.rank`) or slices\n(if `indices.shape[-1] < tensor.shape.rank`) along dimension\n`indices.shape[-1]` of `tensor.shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + tensor.shape[indices.shape[-1]:]\n\nThe simplest form of tensor_scatter_add is to add individual elements to a\ntensor by index. For example, say we want to add 4 elements in a rank-1\ntensor with 8 elements.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n tensor = tf.ones([8], dtype=tf.int32)\n updated = tf.tensor_scatter_nd_add(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [1, 12, 1, 11, 10, 1, 1, 13]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n tensor = tf.ones([4, 4, 4],dtype=tf.int32)\n updated = tf.tensor_scatter_nd_add(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [[[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],\n [[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor and updates added according to the indices.","name":"output","typeAttr":"T"}],"summary":"Adds sparse `updates` to an existing tensor according to `indices`."}},{"name":"TensorScatterMax","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"description":"Tensor to update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor whose values are element-wise maximum between tensor and updates according to the indices.","name":"output","typeAttr":"T"}]}},{"name":"TensorScatterMin","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"inputs":[{"description":"Tensor to update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor whose values are element-wise minimum between tensor and updates according to the indices.","name":"output","typeAttr":"T"}]}},{"name":"TensorScatterSub","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by subtracting sparse `updates` from the\npassed in `tensor`.\nThis operation is very similar to `tf.scatter_nd_sub`, except that the updates\nare subtracted from an existing tensor (as opposed to a variable). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of tensor_scatter_sub is to subtract individual elements\nfrom a tensor by index. For example, say we want to insert 4 scattered elements\nin a rank-1 tensor with 8 elements.\n\nIn Python, this scatter subtract operation would look like this:\n\n```python\n indices = tf.constant([[4], [3], [1], [7]])\n updates = tf.constant([9, 10, 11, 12])\n tensor = tf.ones([8], dtype=tf.int32)\n updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [1, -10, 1, -9, -8, 1, 1, -11]\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter add operation would look like this:\n\n```python\n indices = tf.constant([[0], [2]])\n updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]],\n [[5, 5, 5, 5], [6, 6, 6, 6],\n [7, 7, 7, 7], [8, 8, 8, 8]]])\n tensor = tf.ones([4, 4, 4],dtype=tf.int32)\n updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)\n print(updated)\n```\n\nThe resulting tensor would look like this:\n\n [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],\n [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],\n [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor copied from tensor and updates subtracted according to the indices.","name":"output","typeAttr":"T"}],"summary":"Subtracts sparse `updates` from an existing tensor according to `indices`."}},{"name":"TensorScatterUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"}],"description":"This operation creates a new tensor by applying sparse `updates` to the passed\nin `tensor`.\nThis operation is very similar to `tf.scatter_nd`, except that the updates are\nscattered onto an existing tensor (as opposed to a zero-tensor). If the memory\nfor the existing tensor cannot be re-used, a copy is made and updated.\n\nIf `indices` contains duplicates, then their updates are accumulated (summed).\n\n**WARNING**: The order in which updates are applied is nondeterministic, so the\noutput will be nondeterministic if `indices` contains duplicates -- because\nof some numerical approximation issues, numbers summed in different order\nmay yield different results.\n\n`indices` is an integer tensor containing indices into a new tensor of shape\n`shape`. The last dimension of `indices` can be at most the rank of `shape`:\n\n indices.shape[-1] <= shape.rank\n\nThe last dimension of `indices` corresponds to indices into elements\n(if `indices.shape[-1] = shape.rank`) or slices\n(if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of\n`shape`. `updates` is a tensor with shape\n\n indices.shape[:-1] + shape[indices.shape[-1]:]\n\nThe simplest form of scatter is to insert individual elements in a tensor by\nindex. For example, say we want to insert 4 scattered elements in a rank-1\ntensor with 8 elements.\n\n
    \n\n
    \n\nIn Python, this scatter operation would look like this:\n\n >>> indices = tf.constant([[4], [3], [1], [7]])\n >>> updates = tf.constant([9, 10, 11, 12])\n >>> tensor = tf.ones([8], dtype=tf.int32)\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates))\n tf.Tensor([ 1 11 1 10 9 1 1 12], shape=(8,), dtype=int32)\n\nWe can also, insert entire slices of a higher rank tensor all at once. For\nexample, if we wanted to insert two slices in the first dimension of a\nrank-3 tensor with two matrices of new values.\n\nIn Python, this scatter operation would look like this:\n\n >>> indices = tf.constant([[0], [2]])\n >>> updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],\n ... [7, 7, 7, 7], [8, 8, 8, 8]],\n ... [[5, 5, 5, 5], [6, 6, 6, 6],\n ... [7, 7, 7, 7], [8, 8, 8, 8]]])\n >>> tensor = tf.ones([4, 4, 4], dtype=tf.int32)\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates).numpy())\n [[[5 5 5 5]\n [6 6 6 6]\n [7 7 7 7]\n [8 8 8 8]]\n [[1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]]\n [[5 5 5 5]\n [6 6 6 6]\n [7 7 7 7]\n [8 8 8 8]]\n [[1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]\n [1 1 1 1]]]\n\nNote that on CPU, if an out of bound index is found, an error is returned.\nOn GPU, if an out of bound index is found, the index is ignored.","inputs":[{"description":"Tensor to copy/update.","name":"tensor","typeAttr":"T"},{"description":"Index tensor.","name":"indices","typeAttr":"Tindices"},{"description":"Updates to scatter into output.","name":"updates","typeAttr":"T"}],"outputs":[{"description":"A new tensor with the given shape and updates applied according\nto the indices.","name":"output","typeAttr":"T"}],"summary":"Scatter `updates` into an existing tensor according to `indices`."}},{"name":"TensorSliceDataset","schema":{"attributes":[{"minimum":1,"name":"Toutput_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"components","typeListAttr":"Toutput_types"}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits each dim-0 slice of `components` once."}},{"name":"TensorStridedSliceUpdate","schema":{"attributes":[{"name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Index","type":"type"},{"default":0,"name":"begin_mask","type":"int64"},{"default":0,"name":"end_mask","type":"int64"},{"default":0,"name":"ellipsis_mask","type":"int64"},{"default":0,"name":"new_axis_mask","type":"int64"},{"default":0,"name":"shrink_axis_mask","type":"int64"}],"description":"The values of `value` are assigned to the positions in the tensor `input` that\nare selected by the slice parameters. The slice parameters `begin` `end`\n`strides` etc. work exactly as in `StridedSlice`.\n\nNOTE this op currently does not support broadcasting and so `value`'s shape\nmust be exactly the shape produced by the slice of `input`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"begin","typeAttr":"Index"},{"name":"end","typeAttr":"Index"},{"name":"strides","typeAttr":"Index"},{"name":"value","typeAttr":"T"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Assign `value` to the sliced l-value reference of `input`."}},{"name":"TensorSummary","schema":{"attributes":[{"name":"T","type":"type"},{"default":"","description":"A json-encoded SummaryDescription proto.","name":"description","type":"string"},{"default":[],"description":"An unused list of strings.","name":"labels","type":"string[]"},{"default":"","description":"An unused string.","name":"display_name","type":"string"}],"description":"This op is being phased out in favor of TensorSummaryV2, which lets callers pass\na tag as well as a serialized SummaryMetadata proto string that contains\nplugin-specific data. We will keep this op to maintain backwards compatibility.","inputs":[{"description":"A tensor to serialize.","name":"tensor","typeAttr":"T"}],"outputs":[{"name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a tensor."}},{"name":"TensorSummaryV2","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"A string attached to this summary. Used for organization in TensorBoard.","name":"tag","type":7},{"description":"A tensor to serialize.","name":"tensor","typeAttr":"T"},{"description":"A serialized SummaryMetadata proto. Contains plugin\ndata.","name":"serialized_summary_metadata","type":7}],"outputs":[{"name":"summary","type":7}],"summary":"Outputs a `Summary` protocol buffer with a tensor and per-plugin data."}},{"name":"TextLineDataset","schema":{"inputs":[{"description":"A scalar or a vector containing the name(s) of the file(s) to be\nread.","name":"filenames","type":7},{"description":"A scalar containing either (i) the empty string (no\ncompression), (ii) \"ZLIB\", or (iii) \"GZIP\".","name":"compression_type","type":7},{"description":"A scalar containing the number of bytes to buffer.","name":"buffer_size","type":9}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that emits the lines of one or more text files."}},{"name":"TextLineReader","schema":{"attributes":[{"default":0,"description":"Number of lines to skip from the beginning of every file.","name":"skip_header_lines","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the lines of a file delimited by '\\n'."}},{"name":"TextLineReaderV2","schema":{"attributes":[{"default":0,"description":"Number of lines to skip from the beginning of every file.","name":"skip_header_lines","type":"int64"},{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the lines of a file delimited by '\\n'."}},{"name":"ThreadPoolDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"A resource produced by the ThreadPoolHandle op.","name":"thread_pool","type":20}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ThreadPoolHandle","schema":{"attributes":[{"description":"The number of threads in the thread pool.","name":"num_threads","type":"int64"},{"default":1,"description":"The maximum degree of parallelism to use within operations that execute on this\nthreadpool.","name":"max_intra_op_parallelism","type":"int64"},{"description":"A human-readable name for the threads that may be visible in some\nvisualizations.\nthreadpool.","name":"display_name","type":"string"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"outputs":[{"description":"A resource that can be consumed by one or more ExperimentalThreadPoolDataset\nops.","name":"handle","type":20}],"summary":"Creates a dataset that uses a custom thread pool to compute `input_dataset`."}},{"name":"ThreadUnsafeUnigramCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a learned unigram distribution."}},{"name":"Tile","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tmultiples","type":"type"}],"description":"This operation creates a new tensor by replicating `input` `multiples` times.\nThe output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements,\nand the values of `input` are replicated `multiples[i]` times along the 'i'th\ndimension. For example, tiling `[a b c d]` by `[2]` produces\n`[a b c d a b c d]`.\n\n>>> a = tf.constant([[1,2,3],[4,5,6]], tf.int32)\n>>> b = tf.constant([1,2], tf.int32)\n>>> tf.tile(a, b)\n\n>>> c = tf.constant([2,1], tf.int32)\n>>> tf.tile(a, c)\n\n>>> d = tf.constant([2,2], tf.int32)\n>>> tf.tile(a, d)\n","inputs":[{"description":"1-D or higher.","name":"input","typeAttr":"T"},{"description":"1-D. Length must be the same as the number of dimensions in `input`","name":"multiples","typeAttr":"Tmultiples"}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Constructs a tensor by tiling a given tensor."}},{"name":"TileGrad","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Since `Tile` takes an input and repeats the input `multiples` times\nalong each dimension, `TileGrad` takes in `multiples` and aggregates\neach repeated tile of `input` into `output`.","inputs":[{"name":"input","typeAttr":"T"},{"name":"multiples","type":3}],"outputs":[{"name":"output","typeAttr":"T"}],"summary":"Returns the gradient of `Tile`."}},{"name":"Timestamp","schema":{"description":"Returns the timestamp as a `float64` for seconds since the Unix epoch.\n\nNote: the timestamp is computed when the op is executed, not when it is added\nto the graph.","outputs":[{"name":"ts","type":2}],"summary":"Provides the time since epoch in seconds."}},{"name":"ToBool","schema":{"attributes":[{"name":"T","type":"type"}],"description":"Converts a tensor to a scalar predicate with the following rules:\n\n- For 0D tensors, truthiness is determined by comparing against a \"zero\"\n value. For numerical types it is the obvious zero. For strings it is the\n empty string.\n\n- For >0D tensors, truthiness is determined by looking at the number of\n elements. If has zero elements, then the result is false. Otherwise the\n result is true.\n\nThis matches the behavior of If and While for determining if a tensor counts\nas true/false for a branch condition.","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"output","type":10}],"summary":"Converts a tensor to a scalar predicate."}},{"name":"TopK","schema":{"attributes":[{"description":"Number of top elements to look for along the last dimension (along each\nrow for matrices).","minimum":0,"name":"k","type":"int64"},{"default":true,"description":"If true the resulting `k` elements will be sorted by the values in\ndescending order.","name":"sorted","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the `k` largest entries in the vector\nand outputs their values and indices as vectors. Thus `values[j]` is the\n`j`-th largest entry in `input`, and its index is `indices[j]`.\n\nFor matrices (resp. higher rank input), computes the top `k` entries in each\nrow (resp. vector along the last dimension). Thus,\n\n values.shape = indices.shape = input.shape[:-1] + [k]\n\nIf two elements are equal, the lower-index element appears first.\n\nIf `k` varies dynamically, use `TopKV2` below.","inputs":[{"description":"1-D or higher with last dimension at least `k`.","name":"input","typeAttr":"T"}],"outputs":[{"description":"The `k` largest elements along each last dimensional slice.","name":"values","typeAttr":"T"},{"description":"The indices of `values` within the last dimension of `input`.","name":"indices","type":3}],"summary":"Finds values and indices of the `k` largest elements for the last dimension."}},{"name":"TopKUnique","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"running time is proportional to the product of K and the input\nsize. Sorting the whole array is more efficient for sufficiently large\nvalues of K. The median-of-medians algorithm is probably faster, but\ndifficult to implement efficiently in XLA. If there are fewer than K\nunique numbers (not NANs), the results are padded with negative\ninfinity. NaNs are never returned. Subnormal numbers are flushed to\nzero. If an element appears at multiple indices, the highest index is\nreturned. If a TopK element never appears in the input due to padding\nvalues, the indices are padded with negative one. If a padding value\nappears in the input and padding is needed, the highest index of the\npadding value will be returned. The semantics are not the same as\nkth_order_statistic.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"topk","type":1},{"name":"topk_indices","type":3}],"summary":"Returns the TopK unique values in the array in sorted order. The"}},{"name":"TopKV2","schema":{"attributes":[{"default":true,"description":"If true the resulting `k` elements will be sorted by the values in\ndescending order.","name":"sorted","type":"boolean"},{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"description":"If the input is a vector (rank-1), finds the `k` largest entries in the vector\nand outputs their values and indices as vectors. Thus `values[j]` is the\n`j`-th largest entry in `input`, and its index is `indices[j]`.\n\nFor matrices (resp. higher rank input), computes the top `k` entries in each\nrow (resp. vector along the last dimension). Thus,\n\n values.shape = indices.shape = input.shape[:-1] + [k]\n\nIf two elements are equal, the lower-index element appears first.","inputs":[{"description":"1-D or higher with last dimension at least `k`.","name":"input","typeAttr":"T"},{"description":"0-D. Number of top elements to look for along the last dimension (along each\nrow for matrices).","name":"k","type":3}],"outputs":[{"description":"The `k` largest elements along each last dimensional slice.","name":"values","typeAttr":"T"},{"description":"The indices of `values` within the last dimension of `input`.","name":"indices","type":3}],"summary":"Finds values and indices of the `k` largest elements for the last dimension."}},{"name":"TopKWithUnique","schema":{"attributes":[{"name":"k","type":"int64"}],"description":"of MakeUnique and TopKUnique. The returned top-K will have its lower bits\nreplaced by iota, thus it will be close to the original value but not exactly\nthe same. The running time is proportional to the product of K and the input\nsize. NaNs are never returned. Subnormal numbers are flushed to zero.","inputs":[{"name":"input","type":1}],"outputs":[{"name":"topk","type":1},{"name":"topk_indices","type":3}],"summary":"Returns the TopK values in the array in sorted order. This is a combination"}},{"name":"Transpose","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tperm","type":"type"}],"description":"The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy:\n `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]`","inputs":[{"name":"x","typeAttr":"T"},{"name":"perm","typeAttr":"Tperm"}],"outputs":[{"name":"y","typeAttr":"T"}],"summary":"Shuffle dimensions of x according to a permutation."}},{"name":"TridiagonalMatMul","schema":{"attributes":[{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Calculates product of two matrices, where left matrix is a tridiagonal matrix.","inputs":[{"description":"Tensor of shape `[..., 1, M]`, representing superdiagonals of\ntri-diagonal matrices to the left of multiplication. Last element is ignored.","name":"superdiag","typeAttr":"T"},{"description":"Tensor of shape `[..., 1, M]`, representing main diagonals of tri-diagonal\nmatrices to the left of multiplication.","name":"maindiag","typeAttr":"T"},{"description":"Tensor of shape `[..., 1, M]`, representing subdiagonals of tri-diagonal\nmatrices to the left of multiplication. First element is ignored.","name":"subdiag","typeAttr":"T"},{"description":"Tensor of shape `[..., M, N]`, representing MxN matrices to the right of\nmultiplication.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Tensor of shape `[..., M, N]` containing the product.","name":"output","typeAttr":"T"}],"summary":"Calculate product with tridiagonal matrix."}},{"name":"TridiagonalSolve","schema":{"attributes":[{"default":true,"description":"Whether to apply partial pivoting. Partial pivoting makes the procedure more\nstable, but slower.","name":"partial_pivoting","type":"boolean"},{"description":"Must be one of the following: `float64`, `float32`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":" Solves tridiagonal systems of equations.\n Supports batch dimensions and multiple right-hand sides per each left-hand\n side.\n On CPU, solution is computed via Gaussian elimination with or without partial\n pivoting, depending on `partial_pivoting` attribute. On GPU, Nvidia's cuSPARSE\n library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv\n Partial pivoting is not yet supported by XLA backends.","inputs":[{"description":"Tensor of shape `[..., 3, M]` whose innermost 2 dimensions represent the\ntridiagonal matrices with three rows being the superdiagonal, diagonals, and\nsubdiagonals, in order. The last element of the superdiagonal and the first\nelement of the subdiagonal is ignored.","name":"diagonals","typeAttr":"T"},{"description":"Tensor of shape `[..., M, K]`, representing K right-hand sides per each\nleft-hand side.","name":"rhs","typeAttr":"T"}],"outputs":[{"description":"Tensor of shape `[..., M, K]` containing the solutions","name":"output","typeAttr":"T"}],"summary":"Solves tridiagonal systems of equations."}},{"name":"TruncateDiv","schema":{"attributes":[{"description":"Must be one of the following: `bfloat16`, `float16`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`.","name":"T","type":"type"}],"description":"Truncation designates that negative numbers will round fractional quantities\ntoward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different\nthan Python semantics. See `FloorDiv` for a division function that matches\nPython Semantics.\n\n*NOTE*: `TruncateDiv` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns x / y element-wise for integer types."}},{"name":"TruncateMod","schema":{"attributes":[{"description":"Must be one of the following: `int32`, `int64`, `bfloat16`, `float16`, `float32`, `float64`.","name":"T","type":"type"}],"description":"the result here is consistent with a truncating divide. E.g. `truncate(x / y) *\ny + truncate_mod(x, y) = x`.\n\n*NOTE*: `TruncateMod` supports broadcasting. More about broadcasting\n[here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)","inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns element-wise remainder of division. This emulates C semantics in that"}},{"name":"TruncatedNormal","schema":{"attributes":[{"default":0,"description":"If either `seed` or `seed2` are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"A second seed to avoid seed collision.","name":"seed2","type":"int64"},{"description":"The type of the output. Must be one of the following: `float16`, `bfloat16`, `float32`, `float64`.","name":"dtype","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"T","type":"type"}],"description":"The generated values follow a normal distribution with mean 0 and standard\ndeviation 1, except that values whose magnitude is more than 2 standard\ndeviations from the mean are dropped and re-picked.","inputs":[{"description":"The shape of the output tensor.","name":"shape","typeAttr":"T"}],"outputs":[{"description":"A tensor of the specified shape filled with random truncated normal\nvalues.","name":"output","typeAttr":"dtype"}],"summary":"Outputs random values from a truncated normal distribution."}},{"name":"TryRpc","schema":{"attributes":[{"default":"","description":"RPC protocol to use. Empty string means use the default protocol.\nOptions include 'grpc'.","name":"protocol","type":"string"},{"default":true,"description":"`boolean`. If `true` (default), then failures to connect\n(i.e., the server does not immediately respond) cause an RPC failure.","name":"fail_fast","type":"boolean"},{"default":0,"description":"`int`. If `0` (default), then the kernel will run the RPC\nrequest and only time out if the RPC deadline passes or the session times out.\nIf this value is greater than `0`, then the op will raise an exception if\nthe RPC takes longer than `timeout_in_ms`.","name":"timeout_in_ms","type":"int64"}],"description":"This op asynchronously performs either a single RPC request, or a batch\nof requests. RPC requests are defined by three main parameters:\n\n - `address` (the host+port or BNS address of the request)\n - `method` (the method name for the request)\n - `request` (the serialized proto string, or vector of strings,\n of the RPC request argument).\n\nFor example, if you have an RPC service running on port localhost:2345,\nand its interface is configured with the following proto declaration:\n\n```\nservice MyService {\n rpc MyMethod(MyRequestProto) returns (MyResponseProto) {\n }\n};\n```\n\nthen call this op with arguments:\n\n```\naddress = \"localhost:2345\"\nmethod = \"MyService/MyMethod\"\n```\n\nThe `request` tensor is a string tensor representing serialized `MyRequestProto`\nstrings; and the output string tensor `response` will have the same shape\nand contain (upon successful completion) corresponding serialized\n`MyResponseProto` strings.\n\nFor example, to send a single, empty, `MyRequestProto`, call\nthis op with `request = \"\"`. To send 5 **parallel** empty requests,\ncall this op with `request = [\"\", \"\", \"\", \"\", \"\"]`.\n\nMore generally, one can create a batch of `MyRequestProto` serialized protos\nfrom regular batched tensors using the `encode_proto` op, and convert\nthe response `MyResponseProto` serialized protos to batched tensors\nusing the `decode_proto` op.\n\n**NOTE** Working with serialized proto strings is faster than instantiating\nactual proto objects in memory, so no performance degradation is expected\ncompared to writing custom kernels for this workflow.\n\nUnlike the standard `Rpc` op, if the connection fails or the remote worker\nreturns an error status, this op does **not** reraise the exception.\nInstead, the `status_code` and `status_message` entry for the corresponding RPC\ncall is set with the error returned from the RPC call. The `response` tensor\nwill contain valid response values for those minibatch entries whose RPCs did\nnot fail; the rest of the entries will have empty strings.","inputs":[{"description":"`0-D` or `1-D`. The address (i.e. host_name:port) of the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `method` and `request`.","name":"address","type":7},{"description":"`0-D` or `1-D`. The method address on the RPC server.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `request`.","name":"method","type":7},{"description":"`0-D` or `1-D`. Serialized proto strings: the rpc request argument.\nIf this tensor has more than 1 element, then multiple parallel rpc requests\nare sent. This argument broadcasts with `address` and `method`.","name":"request","type":7}],"outputs":[{"description":"Same shape as `request`. Serialized proto strings: the rpc responses.","name":"response","type":7},{"description":"Same shape as `request`. Values correspond to tensorflow Status enum codes.","name":"status_code","type":3},{"description":"Same shape as `request`. Values correspond to Status messages\nreturned from the RPC calls.","name":"status_message","type":7}],"summary":"Perform batches of RPC requests."}},{"name":"Unbatch","schema":{"attributes":[{"name":"timeout_micros","type":"int64"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"name":"T","type":"type"}],"description":"An instance of Unbatch either receives an empty batched_tensor, in which case it\nasynchronously waits until the values become available from a concurrently\nrunning instance of Unbatch with the same container and shared_name, or receives\na non-empty batched_tensor in which case it finalizes all other concurrently\nrunning instances and outputs its own element from the batch.\n\nbatched_tensor: The possibly transformed output of Batch. The size of the first\n dimension should remain unchanged by the transformations for the operation to\n work.\nbatch_index: The matching batch_index obtained from Batch.\nid: The id scalar emitted by Batch.\nunbatched_tensor: The Tensor corresponding to this execution.\ntimeout_micros: Maximum amount of time (in microseconds) to wait to receive the\n batched input tensor associated with a given invocation of the op.\ncontainer: Container to control resource sharing.\nshared_name: Instances of Unbatch with the same container and shared_name are\n assumed to possibly belong to the same batch. If left empty, the op name will\n be used as the shared name.","inputs":[{"name":"batched_tensor","typeAttr":"T"},{"name":"batch_index","type":9},{"name":"id","type":9}],"outputs":[{"name":"unbatched_tensor","typeAttr":"T"}],"summary":"Reverses the operation of Batch for a single output Tensor."}},{"name":"UnbatchDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"A dataset that splits the elements of its input into multiple elements."}},{"name":"UnbatchGrad","schema":{"attributes":[{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"},{"name":"T","type":"type"}],"description":"Acts like Batch but using the given batch_index index of batching things as they\nbecome available. This ensures that the gradients are propagated back in the\nsame session which did the forward pass.\n\noriginal_input: The input to the Unbatch operation this is the gradient of.\nbatch_index: The batch_index given to the Unbatch operation this is the gradient\nof.\ngrad: The downstream gradient.\nid: The id scalar emitted by Batch.\nbatched_grad: The return value, either an empty tensor or the batched gradient.\ncontainer: Container to control resource sharing.\nshared_name: Instances of UnbatchGrad with the same container and shared_name\n are assumed to possibly belong to the same batch. If left empty, the op name\n will be used as the shared name.","inputs":[{"name":"original_input","typeAttr":"T"},{"name":"batch_index","type":9},{"name":"grad","typeAttr":"T"},{"name":"id","type":9}],"outputs":[{"name":"batched_grad","typeAttr":"T"}],"summary":"Gradient of Unbatch."}},{"name":"UncompressElement","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"compressed","type":21}],"outputs":[{"name":"components","typeListAttr":"output_types"}],"summary":"Uncompresses a compressed dataset element."}},{"name":"UnicodeDecode","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"The character codepoints for all strings are returned using a single vector\n`char_values`, with strings expanded to characters in row-major order.\n\nThe `row_splits` tensor indicates where the codepoints for\neach input string begin and end within the `char_values` tensor.\nIn particular, the values for the `i`th\nstring (in row-major order) are stored in the slice\n`[row_splits[i]:row_splits[i+1]]`. Thus:\n\n* `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th\n character in the `i`th string (in row-major order).\n* `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th\n string (in row-major order).","inputs":[{"description":"The text to be decoded. Can have any shape. Note that the output is flattened\nto a vector of char values.","name":"input","type":7}],"outputs":[{"description":"A 1D int32 tensor containing the row splits.","name":"row_splits","typeAttr":"Tsplits"},{"description":"A 1D int32 Tensor containing the decoded codepoints.","name":"char_values","type":3}],"summary":"Decodes each string in `input` into a sequence of Unicode code points."}},{"name":"UnicodeDecodeWithOffsets","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"The character codepoints for all strings are returned using a single vector\n`char_values`, with strings expanded to characters in row-major order.\nSimilarly, the character start byte offsets are returned using a single vector\n`char_to_byte_starts`, with strings expanded in row-major order.\n\nThe `row_splits` tensor indicates where the codepoints and start offsets for\neach input string begin and end within the `char_values` and\n`char_to_byte_starts` tensors. In particular, the values for the `i`th\nstring (in row-major order) are stored in the slice\n`[row_splits[i]:row_splits[i+1]]`. Thus:\n\n* `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th\n character in the `i`th string (in row-major order).\n* `char_to_bytes_starts[row_splits[i]+j]` is the start byte offset for the `j`th\n character in the `i`th string (in row-major order).\n* `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th\n string (in row-major order).","inputs":[{"description":"The text to be decoded. Can have any shape. Note that the output is flattened\nto a vector of char values.","name":"input","type":7}],"outputs":[{"description":"A 1D int32 tensor containing the row splits.","name":"row_splits","typeAttr":"Tsplits"},{"description":"A 1D int32 Tensor containing the decoded codepoints.","name":"char_values","type":3},{"description":"A 1D int32 Tensor containing the byte index in the input string where each\ncharacter in `char_values` starts.","name":"char_to_byte_starts","type":9}],"summary":"Decodes each string in `input` into a sequence of Unicode code points."}},{"name":"UnicodeEncode","schema":{"attributes":[{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `ignore`, `replace`, `strict`.","name":"errors","type":"string"},{"description":"Unicode encoding of the output strings. Valid encodings are: `\"UTF-8\",\n\"UTF-16-BE\", and \"UTF-32-BE\"`. Must be one of the following: `UTF-8`, `UTF-16-BE`, `UTF-32-BE`.","name":"output_encoding","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD (U+65533).","name":"replacement_char","type":"int64"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Tsplits","type":"type"}],"description":"Returns a vector of strings, where `output[i]` is constructed by encoding the\nUnicode codepoints in `input_values[input_splits[i]:input_splits[i+1]]`\nusing `output_encoding`.\n\n---\n\nExample:\n\n```\ninput_values = [72, 101, 108, 108, 111, 87, 111, 114, 108, 100]\ninput_splits = [0, 5, 10]\noutput_encoding = 'UTF-8'\n\noutput = ['Hello', 'World']\n```","inputs":[{"description":"A 1D tensor containing the unicode codepoints that should be encoded.","name":"input_values","type":3},{"description":"A 1D tensor specifying how the unicode codepoints should be split into strings.\nIn particular, `output[i]` is constructed by encoding the codepoints in the\nslice `input_values[input_splits[i]:input_splits[i+1]]`.","name":"input_splits","typeAttr":"Tsplits"}],"outputs":[{"description":"The 1-D Tensor of strings encoded from the provided unicode codepoints.","name":"output","type":7}],"summary":"Encode a tensor of ints into unicode strings."}},{"name":"UnicodeScript","schema":{"description":"This operation converts Unicode code points to script codes corresponding to\neach code point. Script codes correspond to International Components for\nUnicode (ICU) UScriptCode values. See http://icu-project.org/apiref/icu4c/uscript_8h.html.\nReturns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will\nmatch input shape.\n\nExamples:\n\n>>> tf.strings.unicode_script([1, 31, 38])\n","inputs":[{"description":"A Tensor of int32 Unicode code points.","name":"input","type":3}],"outputs":[{"description":"A Tensor of int32 script codes corresponding to each input code point.","name":"output","type":3}],"summary":"Determine the script codes of a given tensor of Unicode integer code points."}},{"name":"UnicodeTranscode","schema":{"attributes":[{"description":"Text encoding of the input strings. This is any of the encodings supported\nby ICU ucnv algorithmic converters. Examples: `\"UTF-16\", \"US ASCII\", \"UTF-8\"`.","name":"input_encoding","type":"string"},{"description":"The unicode encoding to use in the output. Must be one of\n`\"UTF-8\", \"UTF-16-BE\", \"UTF-32-BE\"`. Multi-byte encodings will be big-endian. Must be one of the following: `UTF-8`, `UTF-16-BE`, `UTF-32-BE`.","name":"output_encoding","type":"string"},{"default":"replace","description":"Error handling policy when there is invalid formatting found in the input.\nThe value of 'strict' will cause the operation to produce a InvalidArgument\nerror on any invalid input formatting. A value of 'replace' (the default) will\ncause the operation to replace any invalid formatting in the input with the\n`replacement_char` codepoint. A value of 'ignore' will cause the operation to\nskip any invalid formatting in the input and produce no corresponding output\ncharacter. Must be one of the following: `strict`, `replace`, `ignore`.","name":"errors","type":"string"},{"default":65533,"description":"The replacement character codepoint to be used in place of any invalid\nformatting in the input when `errors='replace'`. Any valid unicode codepoint may\nbe used. The default value is the default unicode replacement character is\n0xFFFD or U+65533.)\n\nNote that for UTF-8, passing a replacement character expressible in 1 byte, such\nas ' ', will preserve string alignment to the source since invalid bytes will be\nreplaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte\nreplacement character will preserve byte alignment to the source.","name":"replacement_char","type":"int64"},{"default":false,"description":"Whether to replace the C0 control characters (00-1F) with the\n`replacement_char`. Default is false.","name":"replace_control_characters","type":"boolean"}],"description":"The input is a string tensor of any shape. The output is a string tensor of\nthe same shape containing the transcoded strings. Output strings are always\nvalid unicode. If the input contains invalid encoding positions, the\n`errors` attribute sets the policy for how to deal with them. If the default\nerror-handling policy is used, invalid formatting will be substituted in the\noutput by the `replacement_char`. If the errors policy is to `ignore`, any\ninvalid encoding positions in the input are skipped and not included in the\noutput. If it set to `strict` then any invalid formatting will result in an\nInvalidArgument error.\n\nThis operation can be used with `output_encoding = input_encoding` to enforce\ncorrect formatting for inputs even if they are already in the desired encoding.\n\nIf the input is prefixed by a Byte Order Mark needed to determine encoding\n(e.g. if the encoding is UTF-16 and the BOM indicates big-endian), then that\nBOM will be consumed and not emitted into the output. If the input encoding\nis marked with an explicit endianness (e.g. UTF-16-BE), then the BOM is\ninterpreted as a non-breaking-space and is preserved in the output (including\nalways for UTF-8).\n\nThe end result is that if the input is marked as an explicit endianness the\ntranscoding is faithful to all codepoints in the source. If it is not marked\nwith an explicit endianness, the BOM is not considered part of the string itself\nbut as metadata, and so is not preserved in the output.\n\nExamples:\n\n>>> tf.strings.unicode_transcode([\"Hello\", \"TensorFlow\", \"2.x\"], \"UTF-8\", \"UTF-16-BE\")\n\n>>> tf.strings.unicode_transcode([\"A\", \"B\", \"C\"], \"US ASCII\", \"UTF-8\").numpy()\narray([b'A', b'B', b'C'], dtype=object)","inputs":[{"description":"The text to be processed. Can have any shape.","name":"input","type":7}],"outputs":[{"description":"A string tensor containing unicode text encoded using `output_encoding`.","name":"output","type":7}],"summary":"Transcode the input text from a source encoding to a destination encoding."}},{"name":"UniformCandidateSampler","schema":{"attributes":[{"description":"Number of true labels per context.","minimum":1,"name":"num_true","type":"int64"},{"description":"Number of candidates to randomly sample.","minimum":1,"name":"num_sampled","type":"int64"},{"description":"If unique is true, we sample with rejection, so that all sampled\ncandidates in a batch are unique. This requires some approximation to\nestimate the post-rejection sampling probabilities.","name":"unique","type":"boolean"},{"description":"The sampler will sample integers from the interval [0, range_max).","minimum":1,"name":"range_max","type":"int64"},{"default":0,"description":"If either seed or seed2 are set to be non-zero, the random number\ngenerator is seeded by the given seed. Otherwise, it is seeded by a\nrandom seed.","name":"seed","type":"int64"},{"default":0,"description":"An second seed to avoid seed collision.","name":"seed2","type":"int64"}],"description":"See explanations of candidate sampling and the data formats at\ngo/candidate-sampling.\n\nFor each batch, this op picks a single set of sampled candidate labels.\n\nThe advantages of sampling candidates per-batch are simplicity and the\npossibility of efficient dense matrix multiplication. The disadvantage is that\nthe sampled candidates must be chosen independently of the context and of the\ntrue labels.","inputs":[{"description":"A batch_size * num_true matrix, in which each row contains the\nIDs of the num_true target_classes in the corresponding original label.","name":"true_classes","type":9}],"outputs":[{"description":"A vector of length num_sampled, in which each element is\nthe ID of a sampled candidate.","name":"sampled_candidates","type":9},{"description":"A batch_size * num_true matrix, representing\nthe number of times each candidate is expected to occur in a batch\nof sampled candidates. If unique=true, then this is a probability.","name":"true_expected_count","type":1},{"description":"A vector of length num_sampled, for each sampled\ncandidate representing the number of times the candidate is expected\nto occur in a batch of sampled candidates. If unique=true, then this is a\nprobability.","name":"sampled_expected_count","type":1}],"summary":"Generates labels for candidate sampling with a uniform distribution."}},{"name":"Unique","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation returns a tensor `y` containing all of the unique elements of `x`\nsorted in the same order that they occur in `x`; `x` does not need to be sorted.\nThis operation also returns a tensor `idx` the same size as `x` that contains\nthe index of each value of `x` in the unique output `y`. In other words:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nExamples:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx = unique(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\n```\n\n```\n# tensor 'x' is [4, 5, 1, 2, 3, 3, 4, 5]\ny, idx = unique(x)\ny ==> [4, 5, 1, 2, 3]\nidx ==> [0, 1, 2, 3, 4, 4, 0, 1]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"},{"description":"1-D.","name":"idx","typeAttr":"out_idx"}],"summary":"Finds unique elements in a 1-D tensor."}},{"name":"UniqueDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that contains the unique elements of `input_dataset`."}},{"name":"UniqueV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation either returns a tensor `y` containing unique elements\nalong the `axis` of a tensor. The returned unique elements is sorted\nin the same order as they occur along `axis` in `x`.\nThis operation also returns a tensor `idx` that is the same size as\nthe number of the elements in `x` along the `axis` dimension. It\ncontains the index in the unique output `y`.\nIn other words, for an `1-D` tensor `x` with `axis = None:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx = unique(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\n```\n\nFor an `2-D` tensor `x` with `axis = 0`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx = unique(x, axis=0)\ny ==> [[1, 0, 0],\n [2, 0, 0]]\nidx ==> [0, 0, 1]\n```\n\nFor an `2-D` tensor `x` with `axis = 1`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx = unique(x, axis=1)\ny ==> [[1, 0],\n [1, 0],\n [2, 0]]\nidx ==> [0, 1, 1]\n```","inputs":[{"description":"A `Tensor`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: None). The axis of the Tensor to\nfind the unique elements.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"A `Tensor`. Unique elements along the `axis` of `Tensor` x.","name":"y","typeAttr":"T"},{"description":"A 1-D Tensor. Has the same type as x that contains the index of each\nvalue of x in the output y.","name":"idx","typeAttr":"out_idx"}],"summary":"Finds unique elements along an axis of a tensor."}},{"name":"UniqueWithCounts","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation returns a tensor `y` containing all of the unique elements of `x`\nsorted in the same order that they occur in `x`. This operation also returns a\ntensor `idx` the same size as `x` that contains the index of each value of `x`\nin the unique output `y`. Finally, it returns a third tensor `count` that\ncontains the count of each element of `y` in `x`. In other words:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx, count = unique_with_counts(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\ncount ==> [2, 1, 3, 1, 2]\n```","inputs":[{"description":"1-D.","name":"x","typeAttr":"T"}],"outputs":[{"description":"1-D.","name":"y","typeAttr":"T"},{"description":"1-D.","name":"idx","typeAttr":"out_idx"},{"description":"1-D.","name":"count","typeAttr":"out_idx"}],"summary":"Finds unique elements in a 1-D tensor."}},{"name":"UniqueWithCountsV2","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":9},"description":"Must be one of the following: `int32`, `int64`.","name":"Taxis","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_idx","type":"type"}],"description":"This operation either returns a tensor `y` containing unique elements\nalong the `axis` of a tensor. The returned unique elements is sorted\nin the same order as they occur along `axis` in `x`.\nThis operation also returns a tensor `idx` and a tensor `count`\nthat are the same size as the number of the elements in `x` along the\n`axis` dimension. The `idx` contains the index in the unique output `y`\nand the `count` contains the count in the unique output `y`.\nIn other words, for an `1-D` tensor `x` with `axis = None:\n\n`y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]`\n\nFor example:\n\n```\n# tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8]\ny, idx, count = unique_with_counts(x)\ny ==> [1, 2, 4, 7, 8]\nidx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]\ncount ==> [2, 1, 3, 1, 2]\n```\n\nFor an `2-D` tensor `x` with `axis = 0`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx, count = unique_with_counts(x, axis=0)\ny ==> [[1, 0, 0],\n [2, 0, 0]]\nidx ==> [0, 0, 1]\ncount ==> [2, 1]\n```\n\nFor an `2-D` tensor `x` with `axis = 1`:\n\n```\n# tensor 'x' is [[1, 0, 0],\n# [1, 0, 0],\n# [2, 0, 0]]\ny, idx, count = unique_with_counts(x, axis=1)\ny ==> [[1, 0],\n [1, 0],\n [2, 0]]\nidx ==> [0, 1, 1]\ncount ==> [1, 2]\n```","inputs":[{"description":"A `Tensor`.","name":"x","typeAttr":"T"},{"description":"A `Tensor` of type `int32` (default: None). The axis of the Tensor to\nfind the unique elements.","name":"axis","typeAttr":"Taxis"}],"outputs":[{"description":"A `Tensor`. Unique elements along the `axis` of `Tensor` x.","name":"y","typeAttr":"T"},{"description":"A 1-D Tensor. Has the same type as x that contains the index of each\nvalue of x in the output y.","name":"idx","typeAttr":"out_idx"},{"description":"A 1-D Tensor. The count of each value of x in the output y.","name":"count","typeAttr":"out_idx"}],"summary":"Finds unique elements along an axis of a tensor."}},{"name":"Unpack","schema":{"attributes":[{"minimum":0,"name":"num","type":"int64"},{"name":"T","type":"type"},{"default":0,"description":"Dimension along which to unpack. Negative values wrap around, so the\nvalid range is `[-R, R)`.","name":"axis","type":"int64"}],"description":"Unpacks `num` tensors from `value` by chipping it along the `axis` dimension.\nFor example, given a tensor of shape `(A, B, C, D)`;\n\nIf `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]`\n and each tensor in `output` will have shape `(B, C, D)`. (Note that the\n dimension unpacked along is gone, unlike `split`).\n\nIf `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]`\n and each tensor in `output` will have shape `(A, C, D)`.\nEtc.\n\nThis is the opposite of `pack`.","inputs":[{"description":"1-D or higher, with `axis` dimension size equal to `num`.","name":"value","typeAttr":"T"}],"outputs":[{"description":"The list of tensors unpacked from `value`.","name":"output","numberAttr":"num","typeAttr":"T"}],"summary":"Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors."}},{"name":"UnravelIndex","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tidx","type":"type"}],"description":"\nExample:\n\n```\ny = tf.unravel_index(indices=[2, 5, 7], dims=[3, 3])\n# 'dims' represent a hypothetical (3, 3) tensor of indices:\n# [[0, 1, *2*],\n# [3, 4, *5*],\n# [6, *7*, 8]]\n# For each entry from 'indices', this operation returns\n# its coordinates (marked with '*'), such as\n# 2 ==> (0, 2)\n# 5 ==> (1, 2)\n# 7 ==> (2, 1)\ny ==> [[0, 1, 2], [2, 2, 1]]\n```\n\n@compatibility(numpy)\nEquivalent to np.unravel_index\n@end_compatibility","inputs":[{"description":"An 0-D or 1-D `int` Tensor whose elements are indices into the\nflattened version of an array of dimensions dims.","name":"indices","typeAttr":"Tidx"},{"description":"An 1-D `int` Tensor. The shape of the array to use for unraveling\nindices.","name":"dims","typeAttr":"Tidx"}],"outputs":[{"description":"An 2-D (or 1-D if indices is 0-D) tensor where each row has the\nsame shape as the indices array.","name":"output","typeAttr":"Tidx"}],"summary":"Converts an array of flat indices into a tuple of coordinate arrays."}},{"name":"UnsortedSegmentJoin","schema":{"attributes":[{"default":"","description":"The separator to use when joining.","name":"separator","type":"string"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Computes the string join along segments of a tensor.\nGiven `segment_ids` with rank `N` and `data` with rank `N+M`:\n\n `output[i, k1...kM] = strings.join([data[j1...jN, k1...kM])`\n\nwhere the join is over all [j1...jN] such that segment_ids[j1...jN] = i.\nStrings are joined in row-major order.\n\nFor example:\n\n```python\ninputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']]\noutput_array = string_ops.unsorted_segment_join(inputs=inputs,\n segment_ids=[1, 0, 1],\n num_segments=2,\n separator=':'))\n# output_array ==> [['Y', '6', '6'], ['Y:p', 'q:G', 'c:a']]\n\n\ninputs = ['this', 'is', 'a', 'test']\noutput_array = string_ops.unsorted_segment_join(inputs=inputs,\n segment_ids=[0, 0, 0, 0],\n num_segments=1,\n separator=':'))\n# output_array ==> ['this:is:a:test']\n```","inputs":[{"description":"The input to be joined.","name":"inputs","type":7},{"description":"A tensor whose shape is a prefix of data.shape. Negative segment ids are not\nsupported.","name":"segment_ids","typeAttr":"Tindices"},{"description":"A scalar.","name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"name":"output","type":7}],"summary":"Joins the elements of `inputs` based on `segment_ids`."}},{"name":"UnsortedSegmentMax","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the maximum such that:\n\n\\\\(output_i = \\max_{j...} data[j...]\\\\) where max is over tuples `j...` such\nthat `segment_ids[j...] == i`.\n\nIf the maximum is empty for a given segment ID `i`, it outputs the smallest\npossible value for the specific numeric type,\n`output[i] = numeric_limits::lowest()`.\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.\n\n
    \n\n
    \n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_max(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 4, 3, 3, 4],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the maximum along segments of a tensor."}},{"name":"UnsortedSegmentMin","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the minimum such that:\n\n\\\\(output_i = \\min_{j...} data_[j...]\\\\) where min is over tuples `j...` such\nthat `segment_ids[j...] == i`.\n\nIf the minimum is empty for a given segment ID `i`, it outputs the largest\npossible value for the specific numeric type,\n`output[i] = numeric_limits::max()`.\n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_min(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 1, 2, 2, 1],\n# [5, 6, 7, 8]]\n```\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the minimum along segments of a tensor."}},{"name":"UnsortedSegmentProd","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nThis operator is similar to the unsorted segment sum operator found\n[(here)](../../../api_docs/python/math_ops.md#UnsortedSegmentSum).\nInstead of computing the sum over segments, it computes the product of all\nentries belonging to a segment such that:\n\n\\\\(output_i = \\prod_{j...} data[j...]\\\\) where the product is over tuples\n`j...` such that `segment_ids[j...] == i`.\n\nFor example:\n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_prod(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 4, 6, 6, 4],\n# [5, 6, 7, 8]]\n```\n\nIf there is no entry for a given segment ID `i`, it outputs 1.\n\nIf the given segment ID `i` is negative, then the corresponding value is\ndropped, and will not be included in the result.","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the product along segments of a tensor."}},{"name":"UnsortedSegmentSum","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"},{"description":"Must be one of the following: `int32`, `int64`.","name":"Tindices","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"Tnumsegments","type":"type"}],"description":"Read\n[the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation)\nfor an explanation of segments.\n\nComputes a tensor such that\n\\\\(output[i] = \\sum_{j...} data[j...]\\\\) where the sum is over tuples `j...` such\nthat `segment_ids[j...] == i`. Unlike `SegmentSum`, `segment_ids`\nneed not be sorted and need not cover all values in the full\nrange of valid values.\n\nIf the sum is empty for a given segment ID `i`, `output[i] = 0`.\nIf the given segment ID `i` is negative, the value is dropped and will not be\nadded to the sum of the segment.\n\n`num_segments` should equal the number of distinct segment IDs.\n\n
    \n\n
    \n\n``` python\nc = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]])\ntf.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2)\n# ==> [[ 5, 5, 5, 5],\n# [5, 6, 7, 8]]\n```\n","inputs":[{"name":"data","typeAttr":"T"},{"description":"A tensor whose shape is a prefix of `data.shape`.","name":"segment_ids","typeAttr":"Tindices"},{"name":"num_segments","typeAttr":"Tnumsegments"}],"outputs":[{"description":"Has same shape as data, except for the first `segment_ids.rank`\ndimensions, which are replaced with a single dimension which has size\n`num_segments`.","name":"output","typeAttr":"T"}],"summary":"Computes the sum along segments of a tensor."}},{"name":"Unstage","schema":{"attributes":[{"default":0,"minimum":0,"name":"capacity","type":"int64"},{"default":0,"minimum":0,"name":"memory_limit","type":"int64"},{"minimum":1,"name":"dtypes","type":"type[]"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"description":"The basic functionality is similar to dequeue with many fewer\ncapabilities and options. This Op is optimized for performance.","outputs":[{"name":"values","typeListAttr":"dtypes"}],"summary":"Op is similar to a lightweight Dequeue."}},{"name":"UnwrapDatasetVariant","schema":{"inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"output_handle","type":21}]}},{"name":"UpperBound","schema":{"attributes":[{"name":"T","type":"type"},{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"Each set of rows with the same index in (sorted_inputs, values) is treated\nindependently. The resulting row is the equivalent of calling\n`np.searchsorted(sorted_inputs, values, side='right')`.\n\nThe result is not a global index to the entire\n`Tensor`, but rather just the index in the last dimension.\n\nA 2-D example:\n sorted_sequence = [[0, 3, 9, 9, 10],\n [1, 2, 3, 4, 5]]\n values = [[2, 4, 9],\n [0, 2, 6]]\n\n result = UpperBound(sorted_sequence, values)\n\n result == [[1, 2, 4],\n [0, 2, 5]]","inputs":[{"description":"2-D Tensor where each row is ordered.","name":"sorted_inputs","typeAttr":"T"},{"description":"2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains\nthe values that will be searched for in `sorted_search_values`.","name":"values","typeAttr":"T"}],"outputs":[{"description":"A `Tensor` with the same shape as `values`. It contains the last scalar index\ninto the last dimension where values can be inserted without changing the\nordered property.","name":"output","typeAttr":"out_type"}],"summary":"Applies upper_bound(sorted_search_values, values) along each row."}},{"name":"VarHandleOp","schema":{"attributes":[{"default":"","description":"the container this variable is placed in.","name":"container","type":"string"},{"default":"","description":"the name by which this variable is referred to.","name":"shared_name","type":"string"},{"description":"the type of this variable. Must agree with the dtypes\nof all ops using this variable.","name":"dtype","type":"type"},{"description":"The (possibly partially specified) shape of this variable.","name":"shape","type":"shape"},{"default":[],"description":"DEPRECATED. The allowed devices containing the resource variable. Set when the\noutput ResourceHandle represents a per-replica/partitioned resource variable.","name":"allowed_devices","type":"string[]"}],"outputs":[{"name":"resource","type":20}],"summary":"Creates a handle to a Variable resource."}},{"name":"VarIsInitializedOp","schema":{"inputs":[{"description":"the input resource handle.","name":"resource","type":20}],"outputs":[{"description":"a scalar boolean which is true if the variable has been\ninitialized.","name":"is_initialized","type":10}],"summary":"Checks whether a resource handle-based variable has been initialized."}},{"name":"Variable","schema":{"attributes":[{"name":"shape","type":"shape"},{"name":"dtype","type":"type"},{"default":"","name":"container","type":"string"},{"default":"","name":"shared_name","type":"string"}],"category":"Control","outputs":[{"isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Use VariableV2 instead."}},{"name":"VariableShape","schema":{"attributes":[{"default":{"type":"type","value":3},"description":"Must be one of the following: `int32`, `int64`.","name":"out_type","type":"type"}],"description":"This operation returns a 1-D integer tensor representing the shape of `input`.\n\nFor example:\n\n```\n# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]\nshape(t) ==> [2, 2, 3]\n```","inputs":[{"name":"input","type":20}],"outputs":[{"name":"output","typeAttr":"out_type"}],"summary":"Returns the shape of the variable pointed to by `resource`."}},{"name":"VariableV2","schema":{"attributes":[{"description":"The shape of the variable tensor.","name":"shape","type":"shape"},{"description":"The type of elements in the variable tensor.","name":"dtype","type":"type"},{"default":"","description":"If non-empty, this variable is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this variable is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"category":"Control","description":"Outputs a ref to the tensor state so it may be read or modified.\nTODO(zhifengc/mrry): Adds a pointer to a more detail document\nabout sharing states in tensorflow.","outputs":[{"description":"A reference to the variable tensor.","isRef":true,"name":"ref","typeAttr":"dtype"}],"summary":"Holds state in the form of a tensor that persists across steps."}},{"name":"Where","schema":{"attributes":[{"default":{"type":"type","value":10},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `float16`, `uint32`, `uint64`, `bool`.","name":"T","type":"type"}],"description":"This operation returns the coordinates of true elements in `input`. The\ncoordinates are returned in a 2-D tensor where the first dimension (rows)\nrepresents the number of true elements, and the second dimension (columns)\nrepresents the coordinates of the true elements. Keep in mind, the shape of\nthe output tensor can vary depending on how many true values there are in\n`input`. Indices are output in row-major order.\n\nFor example:\n\n```\n# 'input' tensor is [[True, False]\n# [True, False]]\n# 'input' has two true values, so output has two coordinates.\n# 'input' has rank of 2, so coordinates have two indices.\nwhere(input) ==> [[0, 0],\n [1, 0]]\n\n# `input` tensor is [[[True, False]\n# [True, False]]\n# [[False, True]\n# [False, True]]\n# [[False, False]\n# [False, True]]]\n# 'input' has 5 true values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n\n# `input` tensor is [[[1.5, 0.0]\n# [-0.5, 0.0]]\n# [[0.0, 0.25]\n# [0.0, 0.75]]\n# [[0.0, 0.0]\n# [0.0, 0.01]]]\n# 'input' has 5 nonzero values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n\n# `input` tensor is [[[1.5 + 0.0j, 0.0 + 0.0j]\n# [0.0 + 0.5j, 0.0 + 0.0j]]\n# [[0.0 + 0.0j, 0.25 + 1.5j]\n# [0.0 + 0.0j, 0.75 + 0.0j]]\n# [[0.0 + 0.0j, 0.0 + 0.0j]\n# [0.0 + 0.0j, 0.01 + 0.0j]]]\n# 'input' has 5 nonzero magnitude values, so output has 5 coordinates.\n# 'input' has rank of 3, so coordinates have three indices.\nwhere(input) ==> [[0, 0, 0],\n [0, 1, 0],\n [1, 0, 1],\n [1, 1, 1],\n [2, 1, 1]]\n```","inputs":[{"name":"input","typeAttr":"T"}],"outputs":[{"name":"index","type":9}],"summary":"Returns locations of nonzero / true values in a tensor."}},{"name":"While","schema":{"attributes":[{"description":"dtype in use.","minimum":0,"name":"T","type":"type[]"},{"description":" A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.","name":"cond","type":"function"},{"description":" A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.","name":"body","type":"function"},{"default":[],"name":"output_shapes","type":"shape[]"},{"default":10,"name":"parallel_iterations","type":"int64"}],"inputs":[{"description":"A list of input tensors whose types are T.","name":"input","typeListAttr":"T"}],"outputs":[{"description":"A list of output tensors whose types are T.","name":"output","typeListAttr":"T"}],"summary":"output = input; While (Cond(output)) { output = Body(output) }"}},{"name":"WholeFileReader","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue filenames in a Queue. The output of ReaderRead will\nbe a filename (key) and the contents of that file (value).","outputs":[{"description":"The handle to reference the Reader.","isRef":true,"name":"reader_handle","type":7}],"summary":"A Reader that outputs the entire contents of a file as a value."}},{"name":"WholeFileReaderV2","schema":{"attributes":[{"default":"","description":"If non-empty, this reader is placed in the given container.\nOtherwise, a default container is used.","name":"container","type":"string"},{"default":"","description":"If non-empty, this reader is named in the given bucket\nwith this shared_name. Otherwise, the node name is used instead.","name":"shared_name","type":"string"}],"description":"To use, enqueue filenames in a Queue. The output of ReaderRead will\nbe a filename (key) and the contents of that file (value).","outputs":[{"description":"The handle to reference the Reader.","name":"reader_handle","type":20}],"summary":"A Reader that outputs the entire contents of a file as a value."}},{"name":"WindowDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"}],"inputs":[{"name":"input_dataset","type":21},{"description":"An integer scalar, representing the number of elements\nof the input dataset to combine into a window. Must be positive.","name":"size","type":9},{"description":"An integer scalar, representing the number of input elements\nby which the window moves in each iteration. Defaults to `size`.\nMust be positive.","name":"shift","type":9},{"description":"An integer scalar, representing the stride of the input elements\nin the sliding window. Must be positive. The default value of 1 means\n\"retain every input element\".","name":"stride","type":9},{"description":"A Boolean scalar, representing whether the last window should be\ndropped if its size is smaller than `window_size`.","name":"drop_remainder","type":10}],"outputs":[{"name":"handle","type":21}],"summary":" Combines (nests of) input elements into a dataset of (nests of) windows.\n\n A \"window\" is a finite dataset of flat elements of size `size` (or possibly\n fewer if there are not enough input elements to fill the window and\n `drop_remainder` evaluates to false).\n\n The `shift` argument determines the number of input elements by which\n the window moves on each iteration. The first element in the `k`th window\n will be element\n\n ```\n 1 + (k-1) * shift\n ```\n\n of the input dataset. In particular, the first element of the first window\n will always be the first element of the input dataset. \n\n If the `stride` parameter is greater than 1, then each window will skip\n `(stride - 1)` input elements between each element that appears in the\n window. Output windows will still contain `size` elements regardless of\n the value of `stride`.\n\n The `stride` argument determines the stride of the input elements, and the\n `shift` argument determines the shift of the window.\n\n For example, letting `{...}` to represent a Dataset:\n\n - `tf.data.Dataset.range(7).window(2)` produces\n `{{0, 1}, {2, 3}, {4, 5}, {6}}`\n - `tf.data.Dataset.range(7).window(3, 2, 1, True)` produces\n `{{0, 1, 2}, {2, 3, 4}, {4, 5, 6}}`\n - `tf.data.Dataset.range(7).window(3, 1, 2, True)` produces\n `{{0, 2, 4}, {1, 3, 5}, {2, 4, 6}}`\n\n Note that when the `window` transformation is applied to a dataset of\n nested elements, it produces a dataset of nested windows.\n\n For example:\n\n - `tf.data.Dataset.from_tensor_slices((range(4), range(4))).window(2)`\n produces `{({0, 1}, {0, 1}), ({2, 3}, {2, 3})}`\n - `tf.data.Dataset.from_tensor_slices({\"a\": range(4)}).window(2)`\n produces `{{\"a\": {0, 1}}, {\"a\": {2, 3}}}`"}},{"name":"WorkerHeartbeat","schema":{"description":"Heartbeats may be sent periodically to indicate the coordinator is still active,\nto retrieve the current worker status and to expedite shutdown when necessary.","inputs":[{"description":"A string tensor containing a serialized WorkerHeartbeatRequest","name":"request","type":7}],"outputs":[{"description":"A string tensor containing a serialized WorkerHeartbeatResponse","name":"response","type":7}],"summary":"Worker heartbeat op."}},{"name":"WrapDatasetVariant","schema":{"inputs":[{"name":"input_handle","type":21}],"outputs":[{"name":"output_handle","type":21}]}},{"name":"WriteAudioSummary","schema":{"attributes":[{"default":3,"minimum":1,"name":"max_outputs","type":"int64"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"tensor","type":1},{"name":"sample_rate","type":1}]}},{"name":"WriteFile","schema":{"description":"creates directory if not existing.","inputs":[{"description":"scalar. The name of the file to which we write the contents.","name":"filename","type":7},{"description":"scalar. The content to be written to the output file.","name":"contents","type":7}],"summary":"Writes contents to the file at input filename. Creates file and recursively"}},{"name":"WriteGraphSummary","schema":{"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","type":7}]}},{"name":"WriteHistogramSummary","schema":{"attributes":[{"default":{"type":"type","value":1},"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"values","typeAttr":"T"}]}},{"name":"WriteImageSummary","schema":{"attributes":[{"default":3,"minimum":1,"name":"max_images","type":"int64"},{"default":{"type":"type","value":1},"description":"Must be one of the following: `uint8`, `float32`, `float16`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"tensor","typeAttr":"T"},{"name":"bad_color","type":4}]}},{"name":"WriteRawProtoSummary","schema":{"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","type":7}]}},{"name":"WriteScalarSummary","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `float16`, `uint32`, `uint64`.","name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tag","type":7},{"name":"value","typeAttr":"T"}]}},{"name":"WriteSummary","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"name":"writer","type":20},{"name":"step","type":9},{"name":"tensor","typeAttr":"T"},{"name":"tag","type":7},{"name":"summary_metadata","type":7}]}},{"name":"Xdivy","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x / y otherwise, elementwise."}},{"name":"XlaHostCompute","schema":{"attributes":[{"description":"The element types of each element in `inputs`.","minimum":0,"name":"Tinputs","type":"type[]"},{"description":"The element types of each element in `outputs`.","minimum":0,"name":"Toutputs","type":"type[]"},{"description":"A list of names of HostCompute computations that must be\nsequenced before this computation.","minimum":0,"name":"ancestors","type":"string[]"},{"description":"If shape_inference_graph is empty, a list of the shapes of `outputs`.","minimum":0,"name":"shapes","type":"shape[]"},{"description":"If non-empty, a serialized GraphDef representing a graph\nthat must be analyzed at compile time to determine the shapes of the outputs.","name":"shape_inference_graph","type":"function"},{"description":"A unique identifier for this region used to match up host transfers.","name":"key","type":"string"},{"default":1000000,"description":"Estimated duration of the host computation in nanoseconds.","name":"cost_estimate_ns","type":"int64"},{"default":0,"description":"Default core to use for host to device transfers.","name":"tpu_core","type":"int64"}],"inputs":[{"description":"A list of tensors that will be sent to the host.","name":"inputs","typeListAttr":"Tinputs"}],"outputs":[{"description":"A list of tensors that will be returned to the device.","name":"outputs","typeListAttr":"Toutputs"}],"summary":"A pseudo-op to represent host-side computation in an XLA program."}},{"name":"XlaRecvFromHost","schema":{"attributes":[{"name":"Toutput","type":"type"},{"name":"shape","type":"shape"},{"name":"key","type":"string"}],"outputs":[{"name":"output","typeAttr":"Toutput"}]}},{"name":"XlaSendToHost","schema":{"attributes":[{"name":"Tinput","type":"type"},{"name":"key","type":"string"}],"inputs":[{"name":"input","typeAttr":"Tinput"}]}},{"name":"Xlog1py","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x * log1p(y) otherwise, elementwise."}},{"name":"Xlogy","schema":{"attributes":[{"description":"Must be one of the following: `float16`, `float32`, `float64`, `complex64`, `complex128`.","name":"T","type":"type"}],"inputs":[{"name":"x","typeAttr":"T"},{"name":"y","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Returns 0 if x == 0, and x * log(y) otherwise, elementwise."}},{"name":"ZerosLike","schema":{"attributes":[{"name":"T","type":"type"}],"inputs":[{"description":"a tensor of type T.","name":"x","typeAttr":"T"}],"outputs":[{"description":"a tensor of the same shape and type as x but filled with zeros.","name":"y","typeAttr":"T"}],"summary":"Returns a tensor of zeros with the same shape and type as x."}},{"name":"Zeta","schema":{"attributes":[{"description":"Must be one of the following: `float32`, `float64`.","name":"T","type":"type"}],"description":"The Hurwitz zeta function is defined as:\n\n\n\\\\(\\zeta(x, q) = \\sum_{n=0}^{\\infty} (q + n)^{-x}\\\\)","inputs":[{"name":"x","typeAttr":"T"},{"name":"q","typeAttr":"T"}],"outputs":[{"name":"z","typeAttr":"T"}],"summary":"Compute the Hurwitz zeta function \\\\(\\zeta(x, q)\\\\)."}},{"name":"ZipDataset","schema":{"attributes":[{"minimum":1,"name":"output_types","type":"type[]"},{"minimum":1,"name":"output_shapes","type":"shape[]"},{"description":"The length of `input_datasets`","minimum":1,"name":"N","type":"int64"}],"description":"The elements of the resulting dataset are created by zipping corresponding\nelements from each of the input datasets.\n\nThe size of the resulting dataset will match the size of the smallest input\ndataset, and no error will be raised if input datasets have different sizes.","inputs":[{"description":"List of `N` variant Tensors representing datasets to be zipped together.","name":"input_datasets","numberAttr":"N","type":21}],"outputs":[{"name":"handle","type":21}],"summary":"Creates a dataset that zips together `input_datasets`."}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..3d9412c09eb9cd118e7f7c64a14444fafd7a6bc4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("tf");$root.tensorflow={},$root.tensorflow.SavedModel=class{constructor(){this.meta_graphs=[]}static decode(e,t){const o=new $root.tensorflow.SavedModel,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.saved_model_schema_version=e.int64();break;case 2:o.meta_graphs.push($root.tensorflow.MetaGraphDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedModel;for(e.start();!e.end();){const o=e.tag();switch(o){case"saved_model_schema_version":t.saved_model_schema_version=e.integer();break;case"meta_graphs":t.meta_graphs.push($root.tensorflow.MetaGraphDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedModel.prototype.saved_model_schema_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.MetaGraphDef=class{constructor(){this.collection_def={},this.signature_def={},this.asset_file_def=[]}static decode(e,t){const o=new $root.tensorflow.MetaGraphDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta_info_def=$root.tensorflow.MetaGraphDef.MetaInfoDef.decode(e,e.uint32());break;case 2:o.graph_def=$root.tensorflow.GraphDef.decode(e,e.uint32());break;case 3:o.saver_def=$root.tensorflow.SaverDef.decode(e,e.uint32());break;case 4:e.pair(o.collection_def,(()=>e.string()),(()=>$root.tensorflow.CollectionDef.decode(e,e.uint32())));break;case 5:e.pair(o.signature_def,(()=>e.string()),(()=>$root.tensorflow.SignatureDef.decode(e,e.uint32())));break;case 6:o.asset_file_def.push($root.tensorflow.AssetFileDef.decode(e,e.uint32()));break;case 7:o.object_graph_def=$root.tensorflow.SavedObjectGraph.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.MetaGraphDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta_info_def":t.meta_info_def=$root.tensorflow.MetaGraphDef.MetaInfoDef.decodeText(e,!0);break;case"graph_def":t.graph_def=$root.tensorflow.GraphDef.decodeText(e,!0);break;case"saver_def":t.saver_def=$root.tensorflow.SaverDef.decodeText(e,!0);break;case"collection_def":e.pair(t.collection_def,(()=>e.string()),(()=>$root.tensorflow.CollectionDef.decodeText(e,!0)));break;case"signature_def":e.pair(t.signature_def,(()=>e.string()),(()=>$root.tensorflow.SignatureDef.decodeText(e,!0)));break;case"asset_file_def":t.asset_file_def.push($root.tensorflow.AssetFileDef.decodeText(e,!0));break;case"object_graph_def":t.object_graph_def=$root.tensorflow.SavedObjectGraph.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.MetaGraphDef.prototype.meta_info_def=null,$root.tensorflow.MetaGraphDef.prototype.graph_def=null,$root.tensorflow.MetaGraphDef.prototype.saver_def=null,$root.tensorflow.MetaGraphDef.prototype.object_graph_def=null,$root.tensorflow.MetaGraphDef.MetaInfoDef=class{constructor(){this.tags=[],this.function_aliases={}}static decode(e,t){const o=new $root.tensorflow.MetaGraphDef.MetaInfoDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta_graph_version=e.string();break;case 2:o.stripped_op_list=$root.tensorflow.OpList.decode(e,e.uint32());break;case 3:o.any_info=$root.google.protobuf.Any.decode(e,e.uint32());break;case 4:o.tags.push(e.string());break;case 5:o.tensorflow_version=e.string();break;case 6:o.tensorflow_git_version=e.string();break;case 7:o.stripped_default_attrs=e.bool();break;case 8:e.pair(o.function_aliases,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.MetaGraphDef.MetaInfoDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta_graph_version":t.meta_graph_version=e.string();break;case"stripped_op_list":t.stripped_op_list=$root.tensorflow.OpList.decodeText(e,!0);break;case"any_info":t.any_info=$root.google.protobuf.Any.decodeText(e,!0);break;case"tags":e.array(t.tags,(()=>e.string()));break;case"tensorflow_version":t.tensorflow_version=e.string();break;case"tensorflow_git_version":t.tensorflow_git_version=e.string();break;case"stripped_default_attrs":t.stripped_default_attrs=e.boolean();break;case"function_aliases":e.pair(t.function_aliases,(()=>e.string()),(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.meta_graph_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.stripped_op_list=null,$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.any_info=null,$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.tensorflow_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.tensorflow_git_version="",$root.tensorflow.MetaGraphDef.MetaInfoDef.prototype.stripped_default_attrs=!1,$root.tensorflow.CollectionDef=class{constructor(){}get kind(){return $root.tensorflow.CollectionDef.kindSet=$root.tensorflow.CollectionDef.kindSet||new Set(["node_list","bytes_list","int64_list","float_list","any_list"]),Object.keys(this).find((e=>$root.tensorflow.CollectionDef.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.CollectionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node_list=$root.tensorflow.CollectionDef.NodeList.decode(e,e.uint32());break;case 2:o.bytes_list=$root.tensorflow.CollectionDef.BytesList.decode(e,e.uint32());break;case 3:o.int64_list=$root.tensorflow.CollectionDef.Int64List.decode(e,e.uint32());break;case 4:o.float_list=$root.tensorflow.CollectionDef.FloatList.decode(e,e.uint32());break;case 5:o.any_list=$root.tensorflow.CollectionDef.AnyList.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"node_list":t.node_list=$root.tensorflow.CollectionDef.NodeList.decodeText(e,!0);break;case"bytes_list":t.bytes_list=$root.tensorflow.CollectionDef.BytesList.decodeText(e,!0);break;case"int64_list":t.int64_list=$root.tensorflow.CollectionDef.Int64List.decodeText(e,!0);break;case"float_list":t.float_list=$root.tensorflow.CollectionDef.FloatList.decodeText(e,!0);break;case"any_list":t.any_list=$root.tensorflow.CollectionDef.AnyList.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.NodeList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.NodeList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.NodeList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.BytesList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.BytesList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push(e.bytes());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.BytesList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.bytes()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.Int64List=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.Int64List,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value=e.array(o.value,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.Int64List;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.FloatList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.FloatList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value=e.floats(o.value,t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.FloatList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":e.array(t.value,(()=>e.float()));break;default:e.field(o,t)}}return t}},$root.tensorflow.CollectionDef.AnyList=class{constructor(){this.value=[]}static decode(e,t){const o=new $root.tensorflow.CollectionDef.AnyList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.value.push($root.google.protobuf.Any.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.CollectionDef.AnyList;for(e.start();!e.end();){const o=e.tag();switch(o){case"value":t.value.push($root.google.protobuf.Any.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo=class{constructor(){}get encoding(){return $root.tensorflow.TensorInfo.encodingSet=$root.tensorflow.TensorInfo.encodingSet||new Set(["name","coo_sparse","composite_tensor"]),Object.keys(this).find((e=>$root.tensorflow.TensorInfo.encodingSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.TensorInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 4:o.coo_sparse=$root.tensorflow.TensorInfo.CooSparse.decode(e,e.uint32());break;case 5:o.composite_tensor=$root.tensorflow.TensorInfo.CompositeTensor.decode(e,e.uint32());break;case 2:o.dtype=e.int32();break;case 3:o.tensor_shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"coo_sparse":t.coo_sparse=$root.tensorflow.TensorInfo.CooSparse.decodeText(e,!0);break;case"composite_tensor":t.composite_tensor=$root.tensorflow.TensorInfo.CompositeTensor.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"tensor_shape":t.tensor_shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.prototype.dtype=0,$root.tensorflow.TensorInfo.prototype.tensor_shape=null,$root.tensorflow.TensorInfo.CooSparse=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorInfo.CooSparse,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values_tensor_name=e.string();break;case 2:o.indices_tensor_name=e.string();break;case 3:o.dense_shape_tensor_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo.CooSparse;for(e.start();!e.end();){const o=e.tag();switch(o){case"values_tensor_name":t.values_tensor_name=e.string();break;case"indices_tensor_name":t.indices_tensor_name=e.string();break;case"dense_shape_tensor_name":t.dense_shape_tensor_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.CooSparse.prototype.values_tensor_name="",$root.tensorflow.TensorInfo.CooSparse.prototype.indices_tensor_name="",$root.tensorflow.TensorInfo.CooSparse.prototype.dense_shape_tensor_name="",$root.tensorflow.TensorInfo.CompositeTensor=class{constructor(){this.components=[]}static decode(e,t){const o=new $root.tensorflow.TensorInfo.CompositeTensor,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_spec=$root.tensorflow.TypeSpecProto.decode(e,e.uint32());break;case 2:o.components.push($root.tensorflow.TensorInfo.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorInfo.CompositeTensor;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_spec":t.type_spec=$root.tensorflow.TypeSpecProto.decodeText(e,!0);break;case"components":t.components.push($root.tensorflow.TensorInfo.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorInfo.CompositeTensor.prototype.type_spec=null,$root.tensorflow.SignatureDef=class{constructor(){this.inputs={},this.outputs={}}static decode(e,t){const o=new $root.tensorflow.SignatureDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.inputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decode(e,e.uint32())));break;case 2:e.pair(o.outputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decode(e,e.uint32())));break;case 3:o.method_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SignatureDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"inputs":e.pair(t.inputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decodeText(e,!0)));break;case"outputs":e.pair(t.outputs,(()=>e.string()),(()=>$root.tensorflow.TensorInfo.decodeText(e,!0)));break;case"method_name":t.method_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SignatureDef.prototype.method_name="",$root.tensorflow.AssetFileDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.AssetFileDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.tensor_info=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:o.filename=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AssetFileDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"tensor_info":t.tensor_info=$root.tensorflow.TensorInfo.decodeText(e,!0);break;case"filename":t.filename=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.AssetFileDef.prototype.tensor_info=null,$root.tensorflow.AssetFileDef.prototype.filename="",$root.tensorflow.GraphDef=class{constructor(){this.node=[]}static decode(e,t){const o=new $root.tensorflow.GraphDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:o.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 3:o.version=e.int32();break;case 2:o.library=$root.tensorflow.FunctionDefLibrary.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.GraphDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"node":t.node.push($root.tensorflow.NodeDef.decodeText(e,!0));break;case"versions":t.versions=$root.tensorflow.VersionDef.decodeText(e,!0);break;case"version":t.version=e.integer();break;case"library":t.library=$root.tensorflow.FunctionDefLibrary.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.GraphDef.prototype.versions=null,$root.tensorflow.GraphDef.prototype.version=0,$root.tensorflow.GraphDef.prototype.library=null,$root.tensorflow.FunctionDefLibrary=class{constructor(){this.function=[],this.gradient=[]}static decode(e,t){const o=new $root.tensorflow.FunctionDefLibrary,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.function.push($root.tensorflow.FunctionDef.decode(e,e.uint32()));break;case 2:o.gradient.push($root.tensorflow.GradientDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDefLibrary;for(e.start();!e.end();){const o=e.tag();switch(o){case"function":t.function.push($root.tensorflow.FunctionDef.decodeText(e,!0));break;case"gradient":t.gradient.push($root.tensorflow.GradientDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionDef=class{constructor(){this.attr={},this.arg_attr={},this.resource_arg_unique_id={},this.node_def=[],this.ret={},this.control_ret={}}static decode(e,t){const o=new $root.tensorflow.FunctionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.signature=$root.tensorflow.OpDef.decode(e,e.uint32());break;case 5:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;case 7:e.pair(o.arg_attr,(()=>e.uint32()),(()=>$root.tensorflow.FunctionDef.ArgAttrs.decode(e,e.uint32())));break;case 8:e.pair(o.resource_arg_unique_id,(()=>e.uint32()),(()=>e.uint32()));break;case 3:o.node_def.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:e.pair(o.ret,(()=>e.string()),(()=>e.string()));break;case 6:e.pair(o.control_ret,(()=>e.string()),(()=>e.string()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"signature":t.signature=$root.tensorflow.OpDef.decodeText(e,!0);break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;case"arg_attr":e.pair(t.arg_attr,(()=>e.integer()),(()=>$root.tensorflow.FunctionDef.ArgAttrs.decodeText(e,!0)));break;case"resource_arg_unique_id":e.pair(t.resource_arg_unique_id,(()=>e.integer()),(()=>e.uint32()));break;case"node_def":t.node_def.push($root.tensorflow.NodeDef.decodeText(e,!0));break;case"ret":e.pair(t.ret,(()=>e.string()),(()=>e.string()));break;case"control_ret":e.pair(t.control_ret,(()=>e.string()),(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionDef.prototype.signature=null,$root.tensorflow.FunctionDef.ArgAttrs=class{constructor(){this.attr={}}static decode(e,t){const o=new $root.tensorflow.FunctionDef.ArgAttrs,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionDef.ArgAttrs;for(e.start();!e.end();){const o=e.tag();switch(o){case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.GradientDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.GradientDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.function_name=e.string();break;case 2:o.gradient_func=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.GradientDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"function_name":t.function_name=e.string();break;case"gradient_func":t.gradient_func=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.GradientDef.prototype.function_name="",$root.tensorflow.GradientDef.prototype.gradient_func="",$root.tensorflow.AttrValue=class{constructor(){}get value(){return $root.tensorflow.AttrValue.valueSet=$root.tensorflow.AttrValue.valueSet||new Set(["s","i","f","b","type","shape","tensor","list","func","placeholder"]),Object.keys(this).find((e=>$root.tensorflow.AttrValue.valueSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.AttrValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.s=e.bytes();break;case 3:o.i=e.int64();break;case 4:o.f=e.float();break;case 5:o.b=e.bool();break;case 6:o.type=e.int32();break;case 7:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 8:o.tensor=$root.tensorflow.TensorProto.decode(e,e.uint32());break;case 1:o.list=$root.tensorflow.AttrValue.ListValue.decode(e,e.uint32());break;case 10:o.func=$root.tensorflow.NameAttrList.decode(e,e.uint32());break;case 9:o.placeholder=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AttrValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"s":t.s=e.bytes();break;case"i":t.i=e.integer();break;case"f":t.f=e.float();break;case"b":t.b=e.boolean();break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"tensor":t.tensor=$root.tensorflow.TensorProto.decodeText(e,!0);break;case"list":t.list=$root.tensorflow.AttrValue.ListValue.decodeText(e,!0);break;case"func":t.func=$root.tensorflow.NameAttrList.decodeText(e,!0);break;case"placeholder":t.placeholder=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.AttrValue.ListValue=class{constructor(){this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[]}static decode(e,t){const o=new $root.tensorflow.AttrValue.ListValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.s.push(e.bytes());break;case 3:o.i=e.array(o.i,(()=>e.int64()),t);break;case 4:o.f=e.floats(o.f,t);break;case 5:o.b=e.array(o.b,(()=>e.bool()),t);break;case 6:o.type=e.array(o.type,(()=>e.int32()),t);break;case 7:o.shape.push($root.tensorflow.TensorShapeProto.decode(e,e.uint32()));break;case 8:o.tensor.push($root.tensorflow.TensorProto.decode(e,e.uint32()));break;case 9:o.func.push($root.tensorflow.NameAttrList.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.AttrValue.ListValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"s":e.array(t.s,(()=>e.bytes()));break;case"i":e.array(t.i,(()=>e.integer()));break;case"f":e.array(t.f,(()=>e.float()));break;case"b":e.array(t.b,(()=>e.boolean()));break;case"type":e.array(t.type,(()=>e.enum($root.tensorflow.DataType)));break;case"shape":t.shape.push($root.tensorflow.TensorShapeProto.decodeText(e,!0));break;case"tensor":t.tensor.push($root.tensorflow.TensorProto.decodeText(e,!0));break;case"func":t.func.push($root.tensorflow.NameAttrList.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.NameAttrList=class{constructor(){this.attr={}}static decode(e,t){const o=new $root.tensorflow.NameAttrList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NameAttrList;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.NameAttrList.prototype.name="",$root.tensorflow.TensorProto=class{constructor(){this.half_val=[],this.float_val=[],this.double_val=[],this.int_val=[],this.string_val=[],this.scomplex_val=[],this.int64_val=[],this.bool_val=[],this.dcomplex_val=[],this.resource_handle_val=[],this.variant_val=[],this.uint32_val=[],this.uint64_val=[]}static decode(e,t){const o=new $root.tensorflow.TensorProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.tensor_shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.version_number=e.int32();break;case 4:o.tensor_content=e.bytes();break;case 13:o.half_val=e.array(o.half_val,(()=>e.int32()),t);break;case 5:o.float_val=e.floats(o.float_val,t);break;case 6:o.double_val=e.doubles(o.double_val,t);break;case 7:o.int_val=e.array(o.int_val,(()=>e.int32()),t);break;case 8:o.string_val.push(e.bytes());break;case 9:o.scomplex_val=e.floats(o.scomplex_val,t);break;case 10:o.int64_val=e.array(o.int64_val,(()=>e.int64()),t);break;case 11:o.bool_val=e.array(o.bool_val,(()=>e.bool()),t);break;case 12:o.dcomplex_val=e.doubles(o.dcomplex_val,t);break;case 14:o.resource_handle_val.push($root.tensorflow.ResourceHandleProto.decode(e,e.uint32()));break;case 15:o.variant_val.push($root.tensorflow.VariantTensorDataProto.decode(e,e.uint32()));break;case 16:o.uint32_val=e.array(o.uint32_val,(()=>e.uint32()),t);break;case 17:o.uint64_val=e.array(o.uint64_val,(()=>e.uint64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"tensor_shape":t.tensor_shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"version_number":t.version_number=e.integer();break;case"tensor_content":t.tensor_content=e.bytes();break;case"half_val":e.array(t.half_val,(()=>e.integer()));break;case"float_val":e.array(t.float_val,(()=>e.float()));break;case"double_val":e.array(t.double_val,(()=>e.float()));break;case"int_val":e.array(t.int_val,(()=>e.integer()));break;case"string_val":e.array(t.string_val,(()=>e.bytes()));break;case"scomplex_val":e.array(t.scomplex_val,(()=>e.float()));break;case"int64_val":e.array(t.int64_val,(()=>e.integer()));break;case"bool_val":e.array(t.bool_val,(()=>e.boolean()));break;case"dcomplex_val":e.array(t.dcomplex_val,(()=>e.float()));break;case"resource_handle_val":t.resource_handle_val.push($root.tensorflow.ResourceHandleProto.decodeText(e,!0));break;case"variant_val":t.variant_val.push($root.tensorflow.VariantTensorDataProto.decodeText(e,!0));break;case"uint32_val":e.array(t.uint32_val,(()=>e.integer()));break;case"uint64_val":e.array(t.uint64_val,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorProto.prototype.dtype=0,$root.tensorflow.TensorProto.prototype.tensor_shape=null,$root.tensorflow.TensorProto.prototype.version_number=0,$root.tensorflow.TensorProto.prototype.tensor_content=new Uint8Array([]),$root.tensorflow.VariantTensorDataProto=class{constructor(){this.tensors=[]}static decode(e,t){const o=new $root.tensorflow.VariantTensorDataProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_name=e.string();break;case 2:o.metadata=e.bytes();break;case 3:o.tensors.push($root.tensorflow.TensorProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VariantTensorDataProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_name":t.type_name=e.string();break;case"metadata":t.metadata=e.bytes();break;case"tensors":t.tensors.push($root.tensorflow.TensorProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.VariantTensorDataProto.prototype.type_name="",$root.tensorflow.VariantTensorDataProto.prototype.metadata=new Uint8Array([]),$root.tensorflow.ResourceHandleProto=class{constructor(){this.dtypes_and_shapes=[]}static decode(e,t){const o=new $root.tensorflow.ResourceHandleProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device=e.string();break;case 2:o.container=e.string();break;case 3:o.name=e.string();break;case 4:o.hash_code=e.uint64();break;case 5:o.maybe_type_name=e.string();break;case 6:o.dtypes_and_shapes.push($root.tensorflow.ResourceHandleProto.DtypeAndShape.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ResourceHandleProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"device":t.device=e.string();break;case"container":t.container=e.string();break;case"name":t.name=e.string();break;case"hash_code":t.hash_code=e.integer();break;case"maybe_type_name":t.maybe_type_name=e.string();break;case"dtypes_and_shapes":t.dtypes_and_shapes.push($root.tensorflow.ResourceHandleProto.DtypeAndShape.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.ResourceHandleProto.prototype.device="",$root.tensorflow.ResourceHandleProto.prototype.container="",$root.tensorflow.ResourceHandleProto.prototype.name="",$root.tensorflow.ResourceHandleProto.prototype.hash_code=protobuf.Long?protobuf.Long.fromBits(0,0,!0):0,$root.tensorflow.ResourceHandleProto.prototype.maybe_type_name="",$root.tensorflow.ResourceHandleProto.DtypeAndShape=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.ResourceHandleProto.DtypeAndShape,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ResourceHandleProto.DtypeAndShape;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.ResourceHandleProto.DtypeAndShape.prototype.dtype=0,$root.tensorflow.ResourceHandleProto.DtypeAndShape.prototype.shape=null,$root.tensorflow.TensorShapeProto=class{constructor(){this.dim=[]}static decode(e,t){const o=new $root.tensorflow.TensorShapeProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.dim.push($root.tensorflow.TensorShapeProto.Dim.decode(e,e.uint32()));break;case 3:o.unknown_rank=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorShapeProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dim":t.dim.push($root.tensorflow.TensorShapeProto.Dim.decodeText(e,!0));break;case"unknown_rank":t.unknown_rank=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorShapeProto.prototype.unknown_rank=!1,$root.tensorflow.TensorShapeProto.Dim=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorShapeProto.Dim,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.size=e.int64();break;case 2:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorShapeProto.Dim;for(e.start();!e.end();){const o=e.tag();switch(o){case"size":t.size=e.integer();break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorShapeProto.Dim.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.TensorShapeProto.Dim.prototype.name="",$root.tensorflow.DataType={DT_INVALID:0,DT_FLOAT:1,DT_DOUBLE:2,DT_INT32:3,DT_UINT8:4,DT_INT16:5,DT_INT8:6,DT_STRING:7,DT_COMPLEX64:8,DT_INT64:9,DT_BOOL:10,DT_QINT8:11,DT_QUINT8:12,DT_QINT32:13,DT_BFLOAT16:14,DT_QINT16:15,DT_QUINT16:16,DT_UINT16:17,DT_COMPLEX128:18,DT_HALF:19,DT_RESOURCE:20,DT_VARIANT:21,DT_UINT32:22,DT_UINT64:23,DT_FLOAT_REF:101,DT_DOUBLE_REF:102,DT_INT32_REF:103,DT_UINT8_REF:104,DT_INT16_REF:105,DT_INT8_REF:106,DT_STRING_REF:107,DT_COMPLEX64_REF:108,DT_INT64_REF:109,DT_BOOL_REF:110,DT_QINT8_REF:111,DT_QUINT8_REF:112,DT_QINT32_REF:113,DT_BFLOAT16_REF:114,DT_QINT16_REF:115,DT_QUINT16_REF:116,DT_UINT16_REF:117,DT_COMPLEX128_REF:118,DT_HALF_REF:119,DT_RESOURCE_REF:120,DT_VARIANT_REF:121,DT_UINT32_REF:122,DT_UINT64_REF:123},$root.tensorflow.NodeDef=class{constructor(){this.input=[],this.attr={}}static decode(e,t){const o=new $root.tensorflow.NodeDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.op=e.string();break;case 3:o.input.push(e.string());break;case 4:o.device=e.string();break;case 5:e.pair(o.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decode(e,e.uint32())));break;case 6:o.experimental_debug_info=$root.tensorflow.NodeDef.ExperimentalDebugInfo.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NodeDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"op":t.op=e.string();break;case"input":e.array(t.input,(()=>e.string()));break;case"device":t.device=e.string();break;case"attr":e.pair(t.attr,(()=>e.string()),(()=>$root.tensorflow.AttrValue.decodeText(e,!0)));break;case"experimental_debug_info":t.experimental_debug_info=$root.tensorflow.NodeDef.ExperimentalDebugInfo.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.NodeDef.prototype.name="",$root.tensorflow.NodeDef.prototype.op="",$root.tensorflow.NodeDef.prototype.device="",$root.tensorflow.NodeDef.prototype.experimental_debug_info=null,$root.tensorflow.NodeDef.ExperimentalDebugInfo=class{constructor(){this.original_node_names=[],this.original_func_names=[]}static decode(e,t){const o=new $root.tensorflow.NodeDef.ExperimentalDebugInfo,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.original_node_names.push(e.string());break;case 2:o.original_func_names.push(e.string());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NodeDef.ExperimentalDebugInfo;for(e.start();!e.end();){const o=e.tag();switch(o){case"original_node_names":e.array(t.original_node_names,(()=>e.string()));break;case"original_func_names":e.array(t.original_func_names,(()=>e.string()));break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef=class{constructor(){this.input_arg=[],this.output_arg=[],this.control_output=[],this.attr=[]}static decode(e,t){const o=new $root.tensorflow.OpDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.input_arg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 3:o.output_arg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 20:o.control_output.push(e.string());break;case 4:o.attr.push($root.tensorflow.OpDef.AttrDef.decode(e,e.uint32()));break;case 8:o.deprecation=$root.tensorflow.OpDeprecation.decode(e,e.uint32());break;case 5:o.summary=e.string();break;case 6:o.description=e.string();break;case 18:o.is_commutative=e.bool();break;case 16:o.is_aggregate=e.bool();break;case 17:o.is_stateful=e.bool();break;case 19:o.allows_uninitialized_input=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"input_arg":t.input_arg.push($root.tensorflow.OpDef.ArgDef.decodeText(e,!0));break;case"output_arg":t.output_arg.push($root.tensorflow.OpDef.ArgDef.decodeText(e,!0));break;case"control_output":e.array(t.control_output,(()=>e.string()));break;case"attr":t.attr.push($root.tensorflow.OpDef.AttrDef.decodeText(e,!0));break;case"deprecation":t.deprecation=$root.tensorflow.OpDeprecation.decodeText(e,!0);break;case"summary":t.summary=e.string();break;case"description":t.description=e.string();break;case"is_commutative":t.is_commutative=e.boolean();break;case"is_aggregate":t.is_aggregate=e.boolean();break;case"is_stateful":t.is_stateful=e.boolean();break;case"allows_uninitialized_input":t.allows_uninitialized_input=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.prototype.name="",$root.tensorflow.OpDef.prototype.deprecation=null,$root.tensorflow.OpDef.prototype.summary="",$root.tensorflow.OpDef.prototype.description="",$root.tensorflow.OpDef.prototype.is_commutative=!1,$root.tensorflow.OpDef.prototype.is_aggregate=!1,$root.tensorflow.OpDef.prototype.is_stateful=!1,$root.tensorflow.OpDef.prototype.allows_uninitialized_input=!1,$root.tensorflow.OpDef.ArgDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDef.ArgDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.description=e.string();break;case 3:o.type=e.int32();break;case 4:o.type_attr=e.string();break;case 5:o.number_attr=e.string();break;case 6:o.type_list_attr=e.string();break;case 16:o.is_ref=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef.ArgDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"description":t.description=e.string();break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"type_attr":t.type_attr=e.string();break;case"number_attr":t.number_attr=e.string();break;case"type_list_attr":t.type_list_attr=e.string();break;case"is_ref":t.is_ref=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.ArgDef.prototype.name="",$root.tensorflow.OpDef.ArgDef.prototype.description="",$root.tensorflow.OpDef.ArgDef.prototype.type=0,$root.tensorflow.OpDef.ArgDef.prototype.type_attr="",$root.tensorflow.OpDef.ArgDef.prototype.number_attr="",$root.tensorflow.OpDef.ArgDef.prototype.type_list_attr="",$root.tensorflow.OpDef.ArgDef.prototype.is_ref=!1,$root.tensorflow.OpDef.AttrDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDef.AttrDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.type=e.string();break;case 3:o.default_value=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 4:o.description=e.string();break;case 5:o.has_minimum=e.bool();break;case 6:o.minimum=e.int64();break;case 7:o.allowed_values=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDef.AttrDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"type":t.type=e.string();break;case"default_value":t.default_value=$root.tensorflow.AttrValue.decodeText(e,!0);break;case"description":t.description=e.string();break;case"has_minimum":t.has_minimum=e.boolean();break;case"minimum":t.minimum=e.integer();break;case"allowed_values":t.allowed_values=$root.tensorflow.AttrValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDef.AttrDef.prototype.name="",$root.tensorflow.OpDef.AttrDef.prototype.type="",$root.tensorflow.OpDef.AttrDef.prototype.default_value=null,$root.tensorflow.OpDef.AttrDef.prototype.description="",$root.tensorflow.OpDef.AttrDef.prototype.has_minimum=!1,$root.tensorflow.OpDef.AttrDef.prototype.minimum=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.OpDef.AttrDef.prototype.allowed_values=null,$root.tensorflow.OpDeprecation=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.OpDeprecation,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.version=e.int32();break;case 2:o.explanation=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpDeprecation;for(e.start();!e.end();){const o=e.tag();switch(o){case"version":t.version=e.integer();break;case"explanation":t.explanation=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.OpDeprecation.prototype.version=0,$root.tensorflow.OpDeprecation.prototype.explanation="",$root.tensorflow.OpList=class{constructor(){this.op=[]}static decode(e,t){const o=new $root.tensorflow.OpList,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.op.push($root.tensorflow.OpDef.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.OpList;for(e.start();!e.end();){const o=e.tag();switch(o){case"op":t.op.push($root.tensorflow.OpDef.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.VersionDef=class{constructor(){this.bad_consumers=[]}static decode(e,t){const o=new $root.tensorflow.VersionDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.producer=e.int32();break;case 2:o.min_consumer=e.int32();break;case 3:o.bad_consumers=e.array(o.bad_consumers,(()=>e.int32()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VersionDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"producer":t.producer=e.integer();break;case"min_consumer":t.min_consumer=e.integer();break;case"bad_consumers":e.array(t.bad_consumers,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.VersionDef.prototype.producer=0,$root.tensorflow.VersionDef.prototype.min_consumer=0,$root.tensorflow.SavedObjectGraph=class{constructor(){this.nodes=[],this.concrete_functions={}}static decode(e,t){const o=new $root.tensorflow.SavedObjectGraph,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.nodes.push($root.tensorflow.SavedObject.decode(e,e.uint32()));break;case 2:e.pair(o.concrete_functions,(()=>e.string()),(()=>$root.tensorflow.SavedConcreteFunction.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedObjectGraph;for(e.start();!e.end();){const o=e.tag();switch(o){case"nodes":t.nodes.push($root.tensorflow.SavedObject.decodeText(e,!0));break;case"concrete_functions":e.pair(t.concrete_functions,(()=>e.string()),(()=>$root.tensorflow.SavedConcreteFunction.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedObject=class{constructor(){this.children=[],this.slot_variables=[],this.saveable_objects={}}get kind(){return $root.tensorflow.SavedObject.kindSet=$root.tensorflow.SavedObject.kindSet||new Set(["user_object","asset","function","variable","bare_concrete_function","constant","resource"]),Object.keys(this).find((e=>$root.tensorflow.SavedObject.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.SavedObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decode(e,e.uint32()));break;case 3:o.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decode(e,e.uint32()));break;case 4:o.user_object=$root.tensorflow.SavedUserObject.decode(e,e.uint32());break;case 5:o.asset=$root.tensorflow.SavedAsset.decode(e,e.uint32());break;case 6:o.function=$root.tensorflow.SavedFunction.decode(e,e.uint32());break;case 7:o.variable=$root.tensorflow.SavedVariable.decode(e,e.uint32());break;case 8:o.bare_concrete_function=$root.tensorflow.SavedBareConcreteFunction.decode(e,e.uint32());break;case 9:o.constant=$root.tensorflow.SavedConstant.decode(e,e.uint32());break;case 10:o.resource=$root.tensorflow.SavedResource.decode(e,e.uint32());break;case 11:e.pair(o.saveable_objects,(()=>e.string()),(()=>$root.tensorflow.SaveableObject.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"children":t.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decodeText(e,!0));break;case"slot_variables":t.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decodeText(e,!0));break;case"user_object":t.user_object=$root.tensorflow.SavedUserObject.decodeText(e,!0);break;case"asset":t.asset=$root.tensorflow.SavedAsset.decodeText(e,!0);break;case"function":t.function=$root.tensorflow.SavedFunction.decodeText(e,!0);break;case"variable":t.variable=$root.tensorflow.SavedVariable.decodeText(e,!0);break;case"bare_concrete_function":t.bare_concrete_function=$root.tensorflow.SavedBareConcreteFunction.decodeText(e,!0);break;case"constant":t.constant=$root.tensorflow.SavedConstant.decodeText(e,!0);break;case"resource":t.resource=$root.tensorflow.SavedResource.decodeText(e,!0);break;case"saveable_objects":e.pair(t.saveable_objects,(()=>e.string()),(()=>$root.tensorflow.SaveableObject.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedUserObject=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedUserObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.identifier=e.string();break;case 2:o.version=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 3:o.metadata=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedUserObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"identifier":t.identifier=e.string();break;case"version":t.version=$root.tensorflow.VersionDef.decodeText(e,!0);break;case"metadata":t.metadata=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedUserObject.prototype.identifier="",$root.tensorflow.SavedUserObject.prototype.version=null,$root.tensorflow.SavedUserObject.prototype.metadata="",$root.tensorflow.SavedAsset=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedAsset,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.asset_file_def_index=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedAsset;for(e.start();!e.end();){const o=e.tag();switch(o){case"asset_file_def_index":t.asset_file_def_index=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedAsset.prototype.asset_file_def_index=0,$root.tensorflow.SavedFunction=class{constructor(){this.concrete_functions=[]}static decode(e,t){const o=new $root.tensorflow.SavedFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.concrete_functions.push(e.string());break;case 2:o.function_spec=$root.tensorflow.FunctionSpec.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"concrete_functions":e.array(t.concrete_functions,(()=>e.string()));break;case"function_spec":t.function_spec=$root.tensorflow.FunctionSpec.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedFunction.prototype.function_spec=null,$root.tensorflow.SavedConcreteFunction=class{constructor(){this.bound_inputs=[]}static decode(e,t){const o=new $root.tensorflow.SavedConcreteFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.bound_inputs=e.array(o.bound_inputs,(()=>e.int32()),t);break;case 3:o.canonicalized_input_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 4:o.output_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedConcreteFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"bound_inputs":e.array(t.bound_inputs,(()=>e.integer()));break;case"canonicalized_input_signature":t.canonicalized_input_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"output_signature":t.output_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedConcreteFunction.prototype.canonicalized_input_signature=null,$root.tensorflow.SavedConcreteFunction.prototype.output_signature=null,$root.tensorflow.SavedBareConcreteFunction=class{constructor(){this.argument_keywords=[]}static decode(e,t){const o=new $root.tensorflow.SavedBareConcreteFunction,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.concrete_function_name=e.string();break;case 2:o.argument_keywords.push(e.string());break;case 3:o.allowed_positional_arguments=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedBareConcreteFunction;for(e.start();!e.end();){const o=e.tag();switch(o){case"concrete_function_name":t.concrete_function_name=e.string();break;case"argument_keywords":e.array(t.argument_keywords,(()=>e.string()));break;case"allowed_positional_arguments":t.allowed_positional_arguments=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedBareConcreteFunction.prototype.concrete_function_name="",$root.tensorflow.SavedBareConcreteFunction.prototype.allowed_positional_arguments=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.SavedConstant=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedConstant,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.operation=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedConstant;for(e.start();!e.end();){const o=e.tag();switch(o){case"operation":t.operation=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedConstant.prototype.operation="",$root.tensorflow.SavedVariable=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedVariable,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.trainable=e.bool();break;case 4:o.synchronization=e.int32();break;case 5:o.aggregation=e.int32();break;case 6:o.name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedVariable;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"trainable":t.trainable=e.boolean();break;case"synchronization":t.synchronization=e.enum($root.tensorflow.VariableSynchronization);break;case"aggregation":t.aggregation=e.enum($root.tensorflow.VariableAggregation);break;case"name":t.name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedVariable.prototype.dtype=0,$root.tensorflow.SavedVariable.prototype.shape=null,$root.tensorflow.SavedVariable.prototype.trainable=!1,$root.tensorflow.SavedVariable.prototype.synchronization=0,$root.tensorflow.SavedVariable.prototype.aggregation=0,$root.tensorflow.SavedVariable.prototype.name="",$root.tensorflow.FunctionSpec=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.FunctionSpec,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.fullargspec=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 2:o.is_method=e.bool();break;case 5:o.input_signature=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.FunctionSpec;for(e.start();!e.end();){const o=e.tag();switch(o){case"fullargspec":t.fullargspec=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"is_method":t.is_method=e.boolean();break;case"input_signature":t.input_signature=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.FunctionSpec.prototype.fullargspec=null,$root.tensorflow.FunctionSpec.prototype.is_method=!1,$root.tensorflow.FunctionSpec.prototype.input_signature=null,$root.tensorflow.SavedResource=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedResource,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.device=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedResource;for(e.start();!e.end();){const o=e.tag();switch(o){case"device":t.device=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedResource.prototype.device="",$root.tensorflow.SaveableObject=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SaveableObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 2:o.save_function=e.int32();break;case 3:o.restore_function=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaveableObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"save_function":t.save_function=e.integer();break;case"restore_function":t.restore_function=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.SaveableObject.prototype.save_function=0,$root.tensorflow.SaveableObject.prototype.restore_function=0,$root.tensorflow.VariableSynchronization={VARIABLE_SYNCHRONIZATION_AUTO:0,VARIABLE_SYNCHRONIZATION_NONE:1,VARIABLE_SYNCHRONIZATION_ON_WRITE:2,VARIABLE_SYNCHRONIZATION_ON_READ:3},$root.tensorflow.VariableAggregation={VARIABLE_AGGREGATION_NONE:0,VARIABLE_AGGREGATION_SUM:1,VARIABLE_AGGREGATION_MEAN:2,VARIABLE_AGGREGATION_ONLY_FIRST_REPLICA:3},$root.tensorflow.VariableDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.VariableDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.variable_name=e.string();break;case 6:o.initial_value_name=e.string();break;case 2:o.initializer_name=e.string();break;case 3:o.snapshot_name=e.string();break;case 4:o.save_slice_info_def=$root.tensorflow.SaveSliceInfoDef.decode(e,e.uint32());break;case 5:o.is_resource=e.bool();break;case 7:o.trainable=e.bool();break;case 8:o.synchronization=e.int32();break;case 9:o.aggregation=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.VariableDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"variable_name":t.variable_name=e.string();break;case"initial_value_name":t.initial_value_name=e.string();break;case"initializer_name":t.initializer_name=e.string();break;case"snapshot_name":t.snapshot_name=e.string();break;case"save_slice_info_def":t.save_slice_info_def=$root.tensorflow.SaveSliceInfoDef.decodeText(e,!0);break;case"is_resource":t.is_resource=e.boolean();break;case"trainable":t.trainable=e.boolean();break;case"synchronization":t.synchronization=e.enum($root.tensorflow.VariableSynchronization);break;case"aggregation":t.aggregation=e.enum($root.tensorflow.VariableAggregation);break;default:e.field(o,t)}}return t}},$root.tensorflow.VariableDef.prototype.variable_name="",$root.tensorflow.VariableDef.prototype.initial_value_name="",$root.tensorflow.VariableDef.prototype.initializer_name="",$root.tensorflow.VariableDef.prototype.snapshot_name="",$root.tensorflow.VariableDef.prototype.save_slice_info_def=null,$root.tensorflow.VariableDef.prototype.is_resource=!1,$root.tensorflow.VariableDef.prototype.trainable=!1,$root.tensorflow.VariableDef.prototype.synchronization=0,$root.tensorflow.VariableDef.prototype.aggregation=0,$root.tensorflow.SaveSliceInfoDef=class{constructor(){this.full_shape=[],this.var_offset=[],this.var_shape=[]}static decode(e,t){const o=new $root.tensorflow.SaveSliceInfoDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.full_name=e.string();break;case 2:o.full_shape=e.array(o.full_shape,(()=>e.int64()),t);break;case 3:o.var_offset=e.array(o.var_offset,(()=>e.int64()),t);break;case 4:o.var_shape=e.array(o.var_shape,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaveSliceInfoDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"full_name":t.full_name=e.string();break;case"full_shape":e.array(t.full_shape,(()=>e.integer()));break;case"var_offset":e.array(t.var_offset,(()=>e.integer()));break;case"var_shape":e.array(t.var_shape,(()=>e.integer()));break;default:e.field(o,t)}}return t}},$root.tensorflow.SaveSliceInfoDef.prototype.full_name="",$root.tensorflow.StructuredValue=class{constructor(){}get kind(){return $root.tensorflow.StructuredValue.kindSet=$root.tensorflow.StructuredValue.kindSet||new Set(["none_value","float64_value","int64_value","string_value","bool_value","tensor_shape_value","tensor_dtype_value","tensor_spec_value","type_spec_value","bounded_tensor_spec_value","list_value","tuple_value","dict_value","named_tuple_value"]),Object.keys(this).find((e=>$root.tensorflow.StructuredValue.kindSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.StructuredValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.none_value=$root.tensorflow.NoneValue.decode(e,e.uint32());break;case 11:o.float64_value=e.double();break;case 12:o.int64_value=e.sint64();break;case 13:o.string_value=e.string();break;case 14:o.bool_value=e.bool();break;case 31:o.tensor_shape_value=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 32:o.tensor_dtype_value=e.int32();break;case 33:o.tensor_spec_value=$root.tensorflow.TensorSpecProto.decode(e,e.uint32());break;case 34:o.type_spec_value=$root.tensorflow.TypeSpecProto.decode(e,e.uint32());break;case 35:o.bounded_tensor_spec_value=$root.tensorflow.BoundedTensorSpecProto.decode(e,e.uint32());break;case 51:o.list_value=$root.tensorflow.ListValue.decode(e,e.uint32());break;case 52:o.tuple_value=$root.tensorflow.TupleValue.decode(e,e.uint32());break;case 53:o.dict_value=$root.tensorflow.DictValue.decode(e,e.uint32());break;case 54:o.named_tuple_value=$root.tensorflow.NamedTupleValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.StructuredValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"none_value":t.none_value=$root.tensorflow.NoneValue.decodeText(e,!0);break;case"float64_value":t.float64_value=e.float();break;case"int64_value":t.int64_value=e.integer();break;case"string_value":t.string_value=e.string();break;case"bool_value":t.bool_value=e.boolean();break;case"tensor_shape_value":t.tensor_shape_value=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"tensor_dtype_value":t.tensor_dtype_value=e.enum($root.tensorflow.DataType);break;case"tensor_spec_value":t.tensor_spec_value=$root.tensorflow.TensorSpecProto.decodeText(e,!0);break;case"type_spec_value":t.type_spec_value=$root.tensorflow.TypeSpecProto.decodeText(e,!0);break;case"bounded_tensor_spec_value":t.bounded_tensor_spec_value=$root.tensorflow.BoundedTensorSpecProto.decodeText(e,!0);break;case"list_value":t.list_value=$root.tensorflow.ListValue.decodeText(e,!0);break;case"tuple_value":t.tuple_value=$root.tensorflow.TupleValue.decodeText(e,!0);break;case"dict_value":t.dict_value=$root.tensorflow.DictValue.decodeText(e,!0);break;case"named_tuple_value":t.named_tuple_value=$root.tensorflow.NamedTupleValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.NoneValue=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.NoneValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();e.skipType(7&t)}return o}static decodeText(e){const t=new $root.tensorflow.NoneValue;for(e.start();!e.end();){const o=e.tag();e.field(o,t)}return t}},$root.tensorflow.ListValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.ListValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values.push($root.tensorflow.StructuredValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.ListValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"values":t.values.push($root.tensorflow.StructuredValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TupleValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.TupleValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.values.push($root.tensorflow.StructuredValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TupleValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"values":t.values.push($root.tensorflow.StructuredValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.DictValue=class{constructor(){this.fields={}}static decode(e,t){const o=new $root.tensorflow.DictValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:e.pair(o.fields,(()=>e.string()),(()=>$root.tensorflow.StructuredValue.decode(e,e.uint32())));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.DictValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"fields":e.pair(t.fields,(()=>e.string()),(()=>$root.tensorflow.StructuredValue.decodeText(e,!0)));break;default:e.field(o,t)}}return t}},$root.tensorflow.PairValue=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.PairValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.key=e.string();break;case 2:o.value=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.PairValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"key":t.key=e.string();break;case"value":t.value=$root.tensorflow.StructuredValue.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.PairValue.prototype.key="",$root.tensorflow.PairValue.prototype.value=null,$root.tensorflow.NamedTupleValue=class{constructor(){this.values=[]}static decode(e,t){const o=new $root.tensorflow.NamedTupleValue,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.values.push($root.tensorflow.PairValue.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.NamedTupleValue;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"values":t.values.push($root.tensorflow.PairValue.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.NamedTupleValue.prototype.name="",$root.tensorflow.TensorSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TensorSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.dtype=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSpecProto.prototype.name="",$root.tensorflow.TensorSpecProto.prototype.shape=null,$root.tensorflow.TensorSpecProto.prototype.dtype=0,$root.tensorflow.BoundedTensorSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.BoundedTensorSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.dtype=e.int32();break;case 4:o.minimum=$root.tensorflow.TensorProto.decode(e,e.uint32());break;case 5:o.maximum=$root.tensorflow.TensorProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BoundedTensorSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"minimum":t.minimum=$root.tensorflow.TensorProto.decodeText(e,!0);break;case"maximum":t.maximum=$root.tensorflow.TensorProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.BoundedTensorSpecProto.prototype.name="",$root.tensorflow.BoundedTensorSpecProto.prototype.shape=null,$root.tensorflow.BoundedTensorSpecProto.prototype.dtype=0,$root.tensorflow.BoundedTensorSpecProto.prototype.minimum=null,$root.tensorflow.BoundedTensorSpecProto.prototype.maximum=null,$root.tensorflow.TypeSpecProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TypeSpecProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_spec_class=e.int32();break;case 2:o.type_state=$root.tensorflow.StructuredValue.decode(e,e.uint32());break;case 3:o.type_spec_class_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TypeSpecProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"type_spec_class":t.type_spec_class=e.enum($root.tensorflow.TypeSpecProto.TypeSpecClass);break;case"type_state":t.type_state=$root.tensorflow.StructuredValue.decodeText(e,!0);break;case"type_spec_class_name":t.type_spec_class_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TypeSpecProto.prototype.type_spec_class=0,$root.tensorflow.TypeSpecProto.prototype.type_state=null,$root.tensorflow.TypeSpecProto.prototype.type_spec_class_name="",$root.tensorflow.TypeSpecProto.TypeSpecClass={UNKNOWN:0,SPARSE_TENSOR_SPEC:1,INDEXED_SLICES_SPEC:2,RAGGED_TENSOR_SPEC:3,TENSOR_ARRAY_SPEC:4,DATA_DATASET_SPEC:5,DATA_ITERATOR_SPEC:6,OPTIONAL_SPEC:7,PER_REPLICA_SPEC:8,VARIABLE_SPEC:9,ROW_PARTITION_SPEC:10},$root.tensorflow.TrackableObjectGraph=class{constructor(){this.nodes=[]}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.nodes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph;for(e.start();!e.end();){const o=e.tag();switch(o){case"nodes":t.nodes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject=class{constructor(){this.children=[],this.attributes=[],this.slot_variables=[]}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decode(e,e.uint32()));break;case 2:o.attributes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.decode(e,e.uint32()));break;case 3:o.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject;for(e.start();!e.end();){const o=e.tag();switch(o){case"children":t.children.push($root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.decodeText(e,!0));break;case"attributes":t.attributes.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.decodeText(e,!0));break;case"slot_variables":t.slot_variables.push($root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.node_id=e.int32();break;case 2:o.local_name=e.string();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference;for(e.start();!e.end();){const o=e.tag();switch(o){case"node_id":t.node_id=e.integer();break;case"local_name":t.local_name=e.string();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.prototype.node_id=0,$root.tensorflow.TrackableObjectGraph.TrackableObject.ObjectReference.prototype.local_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.full_name=e.string();break;case 3:o.checkpoint_key=e.string();break;case 4:o.optional_restore=e.bool();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"full_name":t.full_name=e.string();break;case"checkpoint_key":t.checkpoint_key=e.string();break;case"optional_restore":t.optional_restore=e.boolean();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.full_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.checkpoint_key="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SerializedTensor.prototype.optional_restore=!1,$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.original_variable_node_id=e.int32();break;case 2:o.slot_name=e.string();break;case 3:o.slot_variable_node_id=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference;for(e.start();!e.end();){const o=e.tag();switch(o){case"original_variable_node_id":t.original_variable_node_id=e.integer();break;case"slot_name":t.slot_name=e.string();break;case"slot_variable_node_id":t.slot_variable_node_id=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.original_variable_node_id=0,$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.slot_name="",$root.tensorflow.TrackableObjectGraph.TrackableObject.SlotVariableReference.prototype.slot_variable_node_id=0,$root.tensorflow.SaverDef=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SaverDef,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.filename_tensor_name=e.string();break;case 2:o.save_tensor_name=e.string();break;case 3:o.restore_op_name=e.string();break;case 4:o.max_to_keep=e.int32();break;case 5:o.sharded=e.bool();break;case 6:o.keep_checkpoint_every_n_hours=e.float();break;case 7:o.version=e.int32();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SaverDef;for(e.start();!e.end();){const o=e.tag();switch(o){case"filename_tensor_name":t.filename_tensor_name=e.string();break;case"save_tensor_name":t.save_tensor_name=e.string();break;case"restore_op_name":t.restore_op_name=e.string();break;case"max_to_keep":t.max_to_keep=e.integer();break;case"sharded":t.sharded=e.boolean();break;case"keep_checkpoint_every_n_hours":t.keep_checkpoint_every_n_hours=e.float();break;case"version":t.version=e.enum($root.tensorflow.SaverDef.CheckpointFormatVersion);break;default:e.field(o,t)}}return t}},$root.tensorflow.SaverDef.prototype.filename_tensor_name="",$root.tensorflow.SaverDef.prototype.save_tensor_name="",$root.tensorflow.SaverDef.prototype.restore_op_name="",$root.tensorflow.SaverDef.prototype.max_to_keep=0,$root.tensorflow.SaverDef.prototype.sharded=!1,$root.tensorflow.SaverDef.prototype.keep_checkpoint_every_n_hours=0,$root.tensorflow.SaverDef.prototype.version=0,$root.tensorflow.SaverDef.CheckpointFormatVersion={LEGACY:0,V1:1,V2:2},$root.tensorflow.BundleHeaderProto=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.BundleHeaderProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.num_shards=e.int32();break;case 2:o.endianness=e.int32();break;case 3:o.version=$root.tensorflow.VersionDef.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BundleHeaderProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"num_shards":t.num_shards=e.integer();break;case"endianness":t.endianness=e.enum($root.tensorflow.BundleHeaderProto.Endianness);break;case"version":t.version=$root.tensorflow.VersionDef.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.BundleHeaderProto.prototype.num_shards=0,$root.tensorflow.BundleHeaderProto.prototype.endianness=0,$root.tensorflow.BundleHeaderProto.prototype.version=null,$root.tensorflow.BundleHeaderProto.Endianness={LITTLE:0,BIG:1},$root.tensorflow.BundleEntryProto=class{constructor(){this.slices=[]}static decode(e,t){const o=new $root.tensorflow.BundleEntryProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.dtype=e.int32();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.shard_id=e.int32();break;case 4:o.offset=e.int64();break;case 5:o.size=e.int64();break;case 6:o.crc32c=e.fixed32();break;case 7:o.slices.push($root.tensorflow.TensorSliceProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.BundleEntryProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"dtype":t.dtype=e.enum($root.tensorflow.DataType);break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"shard_id":t.shard_id=e.integer();break;case"offset":t.offset=e.integer();break;case"size":t.size=e.integer();break;case"crc32c":t.crc32c=e.integer();break;case"slices":t.slices.push($root.tensorflow.TensorSliceProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.BundleEntryProto.prototype.dtype=0,$root.tensorflow.BundleEntryProto.prototype.shape=null,$root.tensorflow.BundleEntryProto.prototype.shard_id=0,$root.tensorflow.BundleEntryProto.prototype.offset=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.BundleEntryProto.prototype.size=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.BundleEntryProto.prototype.crc32c=0,$root.tensorflow.TensorSliceProto=class{constructor(){this.extent=[]}static decode(e,t){const o=new $root.tensorflow.TensorSliceProto,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.extent.push($root.tensorflow.TensorSliceProto.Extent.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSliceProto;for(e.start();!e.end();){const o=e.tag();switch(o){case"extent":t.extent.push($root.tensorflow.TensorSliceProto.Extent.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSliceProto.Extent=class{constructor(){}get has_length(){return $root.tensorflow.TensorSliceProto.Extent.has_lengthSet=$root.tensorflow.TensorSliceProto.Extent.has_lengthSet||new Set(["length"]),Object.keys(this).find((e=>$root.tensorflow.TensorSliceProto.Extent.has_lengthSet.has(e)&&null!=this[e]))}static decode(e,t){const o=new $root.tensorflow.TensorSliceProto.Extent,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.start=e.int64();break;case 2:o.length=e.int64();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.TensorSliceProto.Extent;for(e.start();!e.end();){const o=e.tag();switch(o){case"start":t.start=e.integer();break;case"length":t.length=e.integer();break;default:e.field(o,t)}}return t}},$root.tensorflow.TensorSliceProto.Extent.prototype.start=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.tensorflow.SavedSliceMeta=class{constructor(){this.slice=[]}static decode(e,t){const o=new $root.tensorflow.SavedSliceMeta,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.shape=$root.tensorflow.TensorShapeProto.decode(e,e.uint32());break;case 3:o.type=e.int32();break;case 4:o.slice.push($root.tensorflow.TensorSliceProto.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedSliceMeta;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"shape":t.shape=$root.tensorflow.TensorShapeProto.decodeText(e,!0);break;case"type":t.type=e.enum($root.tensorflow.DataType);break;case"slice":t.slice.push($root.tensorflow.TensorSliceProto.decodeText(e,!0));break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedSliceMeta.prototype.name="",$root.tensorflow.SavedSliceMeta.prototype.shape=null,$root.tensorflow.SavedSliceMeta.prototype.type=0,$root.tensorflow.SavedTensorSliceMeta=class{constructor(){this.tensor=[]}static decode(e,t){const o=new $root.tensorflow.SavedTensorSliceMeta,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.tensor.push($root.tensorflow.SavedSliceMeta.decode(e,e.uint32()));break;case 2:o.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedTensorSliceMeta;for(e.start();!e.end();){const o=e.tag();switch(o){case"tensor":t.tensor.push($root.tensorflow.SavedSliceMeta.decodeText(e,!0));break;case"versions":t.versions=$root.tensorflow.VersionDef.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedTensorSliceMeta.prototype.versions=null,$root.tensorflow.SavedSlice=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedSlice,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.name=e.string();break;case 2:o.slice=$root.tensorflow.TensorSliceProto.decode(e,e.uint32());break;case 3:o.data=$root.tensorflow.TensorProto.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedSlice;for(e.start();!e.end();){const o=e.tag();switch(o){case"name":t.name=e.string();break;case"slice":t.slice=$root.tensorflow.TensorSliceProto.decodeText(e,!0);break;case"data":t.data=$root.tensorflow.TensorProto.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedSlice.prototype.name="",$root.tensorflow.SavedSlice.prototype.slice=null,$root.tensorflow.SavedSlice.prototype.data=null,$root.tensorflow.SavedTensorSlices=class{constructor(){}static decode(e,t){const o=new $root.tensorflow.SavedTensorSlices,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.meta=$root.tensorflow.SavedTensorSliceMeta.decode(e,e.uint32());break;case 2:o.data=$root.tensorflow.SavedSlice.decode(e,e.uint32());break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.tensorflow.SavedTensorSlices;for(e.start();!e.end();){const o=e.tag();switch(o){case"meta":t.meta=$root.tensorflow.SavedTensorSliceMeta.decodeText(e,!0);break;case"data":t.data=$root.tensorflow.SavedSlice.decodeText(e,!0);break;default:e.field(o,t)}}return t}},$root.tensorflow.SavedTensorSlices.prototype.meta=null,$root.tensorflow.SavedTensorSlices.prototype.data=null,$root.google={},$root.google.protobuf={},$root.google.protobuf.Any=class{constructor(){}static decode(e,t){const o=new $root.google.protobuf.Any,r=e.next(t);for(;e.end(r);){const t=e.uint32();switch(t>>>3){case 1:o.type_url=e.string();break;case 2:o.value=e.bytes();break;default:e.skipType(7&t)}}return o}static decodeText(e){const t=new $root.google.protobuf.Any;if(e.start(),e.any(t))return t;for(;!e.end();){const o=e.tag();switch(o){case"type_url":t.type_url=e.string();break;case"value":t.value=e.bytes();break;default:e.field(o,t)}}return t}},$root.google.protobuf.Any.prototype.type_url="",$root.google.protobuf.Any.prototype.value=new Uint8Array([]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf.js new file mode 100644 index 0000000000000000000000000000000000000000..b6c571adcb991fe33eac59eeedd39308cd4deca5 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tf.js @@ -0,0 +1 @@ +var tf=tf||{},long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");tf.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("meta"===s&&0!==t.tags("pb").size)return!0;if("pbtxt"===s||"prototxt"===s){if(e.endsWith("predict_net.pbtxt")||e.endsWith("predict_net.prototxt")||e.endsWith("init_net.pbtxt")||e.endsWith("init_net.prototxt"))return!1;const s=t.tags("pbtxt");if(s.has("input_stream")||s.has("output_stream"))return!1;if(s.has("node")||s.has("saved_model_schema_version")||s.has("meta_graphs")||s.has("graph_def"))return!0}if("pb"===s||"pbtxt"===s||"prototxt"===s){if(e.endsWith("predict_net.pb")||e.endsWith("init_net.pb"))return!1;if("tfhub_module.pb"==e){const e=t.buffer;if(e&&2==e.length&&8==e[0]&&3==e[1])return!1}const s=t.tags("pb");if(0===s.size){const e=t.tags("pbtxt");if(e.has("input_stream")||e.has("output_stream"))return!1;if(e.has("node")||e.has("saved_model_schema_version")||e.has("meta_graphs")||e.has("graph_def"))return!0}else{if(s.has(1)&&0===s.get(1)&&s.has(2)&&0===s.get(2)&&s.has(9)&&2===s.get(9))return!1;if(!Array.from(s.values()).some((t=>5===t)))return!0}}if("json"===s)try{const e=JSON.parse(t.text);if(e&&e.format&&"graph-model"===e.format&&e.modelTopology)return!0}catch(t){}if(("index"===s||"ckpt"===s)&&t.buffer.length>8){const e=t.buffer.subarray(t.buffer.length-8,t.buffer.length),s=[87,251,128,139,36,117,71,219];if(e.every(((t,e)=>t===s[e])))return!0}return!1}open(t,e){return e.require("./tf-proto").then((()=>{tf.proto=protobuf.get("tf").tensorflow;let s=null,n=null,o=null;const r=t.identifier,a=r.split(".").pop().toLowerCase();switch(a){case"ckpt":case"index":return tf.ModelFactory._openBundle(t,e);case"json":try{const e=JSON.parse(t.text),r=new tf.proto.GraphDef,a=new tf.proto.MetaGraphDef;a.graph_def=r,s=new tf.proto.SavedModel,s.meta_graphs.push(a);for(const t of e.modelTopology.node)r.node.push(t),t.input=t.input||[];n="TensorFlow.js "+e.format,o=e.convertedBy||e.generatedBy||""}catch(t){throw new tf.Error("File text format is not TensorFlow.js graph-model ("+t.message+") in '"+r+"'.")}break;default:{const e=t.tags("pbtxt");if(e.has("node")||e.has("saved_model_schema_version")||e.has("meta_graphs")||e.has("graph_def")){if(e.has("saved_model_schema_version")||e.has("meta_graphs"))try{(r.endsWith("saved_model.pbtxt")||r.endsWith("saved_model.prototxt"))&&(s=tf.proto.SavedModel.decodeText(protobuf.TextReader.create(t.text)),n="TensorFlow Saved Model",s&&Object.prototype.hasOwnProperty.call(s,"saved_model_schema_version")&&(n=n+" v"+s.saved_model_schema_version.toString()))}catch(t){throw new tf.Error("File text format is not tensorflow.SavedModel ("+t.message+") in '"+r+"'.")}else if(e.has("graph_def"))try{if(!s){const e=tf.proto.MetaGraphDef.decodeText(protobuf.TextReader.create(t.text));s=new tf.proto.SavedModel,s.meta_graphs.push(e),n="TensorFlow MetaGraph"}}catch(t){throw new tf.Error("File text format is not tensorflow.MetaGraphDef ("+t.message+") in '"+r+"'.")}else if(e.has("node"))try{const e=tf.proto.GraphDef.decodeText(protobuf.TextReader.create(t.text)),o=new tf.proto.MetaGraphDef;o.graph_def=e,s=new tf.proto.SavedModel,s.meta_graphs.push(o),n="TensorFlow Graph"}catch(t){throw new tf.Error("File text format is not tensorflow.GraphDef ("+t.message+") in '"+r+"'.")}}else{try{if(r.endsWith("saved_model.pb")){const e=protobuf.Reader.create(t.buffer);s=tf.proto.SavedModel.decode(e),n="TensorFlow Saved Model",s&&Object.prototype.hasOwnProperty.call(s,"saved_model_schema_version")&&(n=n+" v"+s.saved_model_schema_version.toString())}}catch(e){const s=t.buffer;if(s.length>3&&8==s[0]&&1==s[1]&&18==s[2])throw new tf.Error("File format is not tensorflow.SavedModel ("+e.message+") in '"+r+"'.")}try{if(!s&&"meta"==a){const e=protobuf.Reader.create(t.buffer),o=tf.proto.MetaGraphDef.decode(e);s=new tf.proto.SavedModel,s.meta_graphs.push(o),n="TensorFlow MetaGraph"}}catch(t){throw new tf.Error("File format is not tensorflow.MetaGraphDef ("+t.message+") in '"+r+"'.")}try{if(!s){const e=protobuf.Reader.create(t.buffer),o=tf.proto.GraphDef.decode(e),r=new tf.proto.MetaGraphDef;r.graph_def=o,s=new tf.proto.SavedModel,s.meta_graphs.push(r),n="TensorFlow Graph"}}catch(t){throw new tf.Error("File format is not tensorflow.GraphDef ("+t.message+") in '"+r+"'.")}}s&&s.meta_graphs&&s.meta_graphs.length>0&&s.meta_graphs[0].meta_info_def&&Object.prototype.hasOwnProperty.call(s.meta_graphs[0].meta_info_def,"tensorflow_version")&&(o="TensorFlow v"+s.meta_graphs[0].meta_info_def.tensorflow_version);break}}return tf.Metadata.open(e).then((a=>{if(1===s.meta_graphs.length&&s.meta_graphs[0].object_graph_def&&s.meta_graphs[0].object_graph_def.nodes&&s.meta_graphs[0].object_graph_def.nodes.length>0){const r="variables/variables.index";return t.request(r,null).then((i=>tf.TensorBundle.open(i,r,t,e).then((t=>tf.ModelFactory._openModel(r,e,a,s,n,o,t))))).catch((()=>tf.ModelFactory._openModel(r,e,a,s,n,o,null)))}return tf.ModelFactory._openModel(r,e,a,s,n,o,null)}))}))}static _openModel(t,e,s,n,o,r,a){try{return new tf.Model(s,n,o,r,a)}catch(s){e.exception(s,!1);const n=s&&s.message?s.message:s.toString();throw new tf.Error(n.replace(/\.$/,"")+" in '"+t+"'.")}}static _openBundle(t,e){return tf.Metadata.open(e).then((s=>{const n=t.identifier;return tf.TensorBundle.open(t.buffer,n,t,e).then((t=>new tf.Model(s,null,"TensorFlow Tensor Bundle v"+t.format.toString(),null,t))).catch((t=>{e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new tf.Error(s.replace(/\.$/,"")+" in '"+n+"'.")}))}))}},tf.Model=class{constructor(t,e,s,n,o){if(this._format=s,this._producer=n||"",this._graphs=[],e){for(let s=0;s1?s.toString():"-",this._graphs.push(new tf.Graph(t,n,r,o))}const s=[],n=[...this._graphs];for(;n.length>0;){const t=n.shift();s.push(t);for(const e of t.functions)n.push(e)}this._graphs=s}else this._graphs.push(new tf.Graph(t,null,"",o))}get format(){return this._format}get producer(){return this._producer}get description(){return null}get graphs(){return this._graphs}},tf.Graph=class{constructor(t,e,s,n){if(this._metadata=t,this._version=null,this._name=s,this._inputs=[],this._outputs=[],this._nodes=[],this._functions=[],e&&e.graph_def){this._metadata=new tf.GraphMetadata(t,e.meta_info_def);const s=e.graph_def;s.versions?this._version="v"+s.versions.producer.toString():s.version?this._version=s.version:e.meta_info_def&&e.meta_info_def.tensorflow_version&&(this._version=e.meta_info_def.tensorflow_version),e.meta_info_def&&e.meta_info_def.tags&&(this._tags=e.meta_info_def.tags.join(", "));const n=s.node;if(n){const t={};this._namespaces={};for(const e of n){const s=e.name;if(t[s]=e,"Const"!=e.op){const t=s.lastIndexOf("/");if(-1!=t){const e=s.substring(0,t);this._namespaces[e]=!0}}e.output=[]}for(const e of n){const s=e.input;e.input=[],e.controlDependencies=[];for(const n of s){const s=n.split(":",2),o=s[0],r=1==s.length?0:parseInt(s[1]);let a=o.startsWith("^")?o.substring(1):o;const i=t[a];if(a=0==r?a:a+":"+r.toString(),o.startsWith("^")?e.controlDependencies.push(a):e.input.push(a),i){for(let t=i.output.length;t<=r;t++)i.output.push("");i.output[r]=a}}}this._nodeOutputCountMap={};for(const t of n){for(const e of t.input)this._nodeOutputCountMap[e]=(this._nodeOutputCountMap[e]||0)+1;for(const e of t.controlDependencies)this._nodeOutputCountMap[e]=(this._nodeOutputCountMap[e]||0)+1}const e={};for(const t of n)if("Const"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&this._checkSingleOutput(t)){const s=t.attr.value;if(s&&Object.prototype.hasOwnProperty.call(s,"tensor")){const n=t.output[0];n&&(e[n]=new tf.Tensor(s.tensor,t.name,"Constant"))}}for(const t of n)if("Identity"==t.op&&1==t.input.length&&0==t.controlDependencies.length&&this._checkSingleOutput(t)){const s=t.input[0],n=e[s];n&&(e[s]="-",n.kind="Identity Constant",e[t.output[0]]=n)}const s={};for(const t of n)if("Placeholder"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&1==t.output.length){const e=t.attr.dtype,n=t.attr.shape;if(e&&e.type&&n&&n.shape){const o=new tf.TensorType(e.type,n.shape),r=new tf.Argument(t.output[0],o,null);s[t.output[0]]=new tf.Parameter(t.name,[r])}}this._inputs=Object.keys(s).map((t=>s[t]));for(const t of n){const n=t.name;e[n]||s[n]||this._nodes.push(new tf.Node(this,t,t.op,t.name,e,null))}}if(s.library){const t=s.library.function;for(const e of t)this._functions.push(new tf.Function(this,e,this._metadata))}}else if(n){const t=[],e=new Map;for(const s of n.tensors){const o=s.name.split("/");if(2===n.format){if("_CHECKPOINTABLE_OBJECT_GRAPH"===s.name||s.name.startsWith("optimizer/")||s.name.startsWith("keras_api/metrics/")||s.name.endsWith("/ExponentialMovingAverage")||-1!==s.name.indexOf(".OPTIMIZER_SLOT"))continue;s.name.endsWith("/.ATTRIBUTES/VARIABLE_VALUE")&&(o.pop(),o.pop())}const r=o.pop(),a=o.join("/");e.has(a)||(t.push(a),e.set(a,[])),e.get(a).push({name:r,value:s})}for(const s of t)this._nodes.push(new tf.Node(this,null,"Node",s,null,e.get(s)))}}get name(){return this._name}get version(){return this._version}get tags(){return this._tags}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get metadata(){return this._metadata}get namespaces(){return this._namespaces}get functions(){return this._functions}_checkSingleOutput(t){if(1!=t.output.length)return!1;const e=t.output[0];return 1==this._nodeOutputCountMap[e]}},tf.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},tf.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new tf.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},tf.Function=class{constructor(t,e,s){this._name=e.signature.name,this._version=null,this._tags=null,this._inputs=[],this._outputs=[],this._nodes=[],this._metadata=s,this._namespaces={},this._functions=[];const n=e.signature.input_arg;if(n)for(const t of n){const e=new tf.Argument(t.name,new tf.TensorType(t.type,null),null);this._inputs.push(new tf.Parameter(t.name,[e]))}const o={};for(const t of Object.keys(e.ret)){const s=e.ret[t].split(":",2);o[t]=s[0]}const r={},a=e.signature.output_arg;if(a)for(const t of a){const e=o[t.name];this._outputs.push(new tf.Parameter(t.name,[new tf.Argument(e,new tf.TensorType(t.type,null),null)])),r[e]=t.name}const i=e.node_def;if(i){const t={};for(const e of i){const s=e.name;if(t[s]=e,"Const"!=e.op){const t=s.lastIndexOf("/");if(-1!=t){const e=s.substring(0,t);this._namespaces[e]=!0}}e.output=[]}for(const e of i){const s=e.input;e.input=[],e.controlDependencies=[];for(const n of s){const s=n.split(":",3),o=s[0],r=1==s.length?0:parseInt(s[s.length-1]);let a=o.startsWith("^")?o.substring(1):o;const i=t[a];if(a=0==r?a:a+":"+r.toString(),o.startsWith("^")?e.controlDependencies.push(a):e.input.push(a),i){for(let t=i.output.length;t<=r;t++)i.output.push("");i.output[r]=a}}r[e.name]&&e.output.push(e.name)}const e={};for(const t of i){for(const s of t.input)e[s]=(e[s]||0)+1;for(const s of t.controlDependencies)e[s]=(e[s]||0)+1}const s={};for(const t of i)if("Const"==t.op&&0==t.input.length&&0==t.controlDependencies.length&&tf.Function._checkSingleOutput(t,e)){const e=t.attr.value;if(e&&Object.prototype.hasOwnProperty.call(e,"tensor")){const n=t.output[0];n&&(s[n]=new tf.Tensor(e.tensor,t.name,"Constant"))}}for(const t of i)if("Identity"==t.op&&1==t.input.length&&0==t.controlDependencies.length&&tf.Function._checkSingleOutput(t,e)){const e=t.input[0],n=s[e];n&&(s[e]="-",n.kind="Identity Constant",s[t.output[0]]=n)}for(const t of i)s[t.name]||this._nodes.push(new tf.Node(this,t,t.op,t.name,s,null))}}get name(){return this._name}get version(){return this._version}get tags(){return this._tags}get groups(){return!1}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get metadata(){return this._metadata}get namespaces(){return this._namespaces}get functions(){return this._functions}static _checkSingleOutput(t,e){return 1==t.output.length&&1==e[t.output[0]]}},tf.Node=class{constructor(t,e,s,n,o,r){if(this._graph=t,this._type=s,this._name=n,this._attributes=[],this._inputs=[],this._outputs=[],e){Object.prototype.hasOwnProperty.call(e,"device")&&(this._device=e.device);const s=t.metadata;if(e.attr)for(const t of Object.keys(e.attr)){const n=s.attribute(this._type,t),o=!s.getAttributeVisibleMap(this._type)[t];this._attributes.push(new tf.Attribute(n,t,e.attr[t],o))}const n=s.type(this._type);let r=0;const a=e.input.filter((t=>!t.startsWith("^")));if(n&&n.inputs)for(const t of n.inputs){let s=1;if(t.numberAttr){const n=e.attr[t.numberAttr];n&&n.i&&(s=n.i)}else if(t.typeListAttr){const n=e.attr[t.typeListAttr];n&&n.list&&n.list.type&&(s=n.list.type.length)}const n=a.slice(r,r+s).map((t=>new tf.Argument(t,null,o[t])));this._inputs.push(new tf.Parameter(t.name,n)),r+=s}this._inputs=this._inputs.concat(a.slice(r).map(((t,e)=>new tf.Parameter((r+e).toString(),[new tf.Argument(t,null,o[t])]))));let i=0;const p=e.output;if(n&&n.outputs)for(const t of n.outputs){let s=1;if(t.numberAttr){const n=e.attr[t.numberAttr];n&&n.i&&(s=n.i)}else if(t.typeListAttr){const n=e.attr[t.typeListAttr];n&&n.list&&n.list.type&&(s=n.list.type.length)}const n=p.slice(i,i+s).map((t=>new tf.Argument(t,null,null)));this._outputs.push(new tf.Parameter(t.name,n)),i+=s}this._outputs=this._outputs.concat(p.slice(i).map(((t,e)=>new tf.Parameter((i+e).toString(),[new tf.Argument(t,null,null)])))),this._controlDependencies=e.controlDependencies}else if(r)for(const t of r)this._inputs.push(new tf.Parameter(t.name,[new tf.Argument(t.value.name,null,t.value)]))}get type(){return this._type}get name(){return this._name}get device(){return this._device||null}get group(){const t=this._name;if(this._graph.namespaces[t])return t;const e=t.lastIndexOf("/");if(-1!=e){const s=t.substring(0,e);if(this._graph.namespaces[s])return s}return""}get description(){return""}get domain(){return null}get metadata(){return this._graph.metadata.type(this.type)}get inputs(){return this._inputs}get outputs(){return this._outputs}get controlDependencies(){return this._controlDependencies}get attributes(){return this._attributes}},tf.Attribute=class{constructor(t,e,s,n){switch(this._name=e,this._value=null,this._type=null,Object.prototype.hasOwnProperty.call(s,"tensor")?(this._type="tensor",this._value=new tf.Tensor(s.tensor)):t&&t.type&&(this._type=t.type),s.value){case"type":this._type="type",this._value=tf.Tensor.formatDataType(s.type);break;case"i":this._value=s.i;break;case"f":this._value=s.f;break;case"b":this._value=s.b;break;case"shape":this._type="shape",this._value=new tf.TensorShape(s.shape);break;case"s":this._value=tf.Utility.decodeText(s.s);break;case"func":{const t=s.func;this._type="function",this._value=t.name;break}case"list":{const t=s.list;t.s&&t.s.length>0?this._value=t.s.map((t=>tf.Utility.decodeText(t))):t.i&&t.i.length>0?this._value=t.i:t.f&&t.f.length>0?this._value=t.f:t.type&&t.type.length>0?(this._type="type[]",this._value=t.type.map((t=>tf.Tensor.formatDataType(t)))):t.shape&&t.shape.length>0?(this._type="shape[]",this._value=t.shape.map((t=>new tf.TensorShape(t)))):this._value=[];break}}if(t)if(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible)this._visible=!1;else if(Object.prototype.hasOwnProperty.call(t,"default")&&(!Array.isArray(this._value)||Array.isArray(t.default)||this._value.length===t.default.length)){let e=this._value,s=t.default;if("float32"===this._type){const t=new Float32Array(1);t[0]=e,e=t[0],t[0]=s,s=t[0]}const n=tf.GraphMetadata._formatAttributeValue(e),o=tf.GraphMetadata._formatAttributeValue(s);JSON.stringify(n)==JSON.stringify(o)&&(this._visible=!1)}"_output_shapes"==e&&(this._visible=!1,this._type="shape[]"),"_class"==e&&(this._visible=!1),!1===n&&(this._visible=!1)}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},tf.Tensor=class{constructor(t,e,s){this._type=new tf.TensorType(t.dtype,t.tensor_shape||t.tensorShape),this._name=e,this._kind=s||null,this._tensor=t}get name(){return this._name}get type(){return this._type}get kind(){return this._kind}set kind(t){this._kind=t}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0,size:1};if(!this._tensor.dtype)return t.state="Tensor has no data type.",t;const e=this._tensor.tensor_shape||this._tensor.tensorShape;if(!e||!e.dim)return t.state="Tensor has no dimensions.",t;for(const s of e.dim)t.size=t.size*(s.size?s.size:0);switch(this._tensor.dtype){case"DT_FLOAT":case tf.proto.DataType.DT_FLOAT:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):this._tensor.float_val&&this._tensor.float_val.length==t.size?t.data=this._tensor.float_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_QINT8:case tf.proto.DataType.DT_QUINT8:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_INT32:case tf.proto.DataType.DT_UINT32:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.rawData=new DataView(this._tensor.tensor_content.buffer,this._tensor.tensor_content.byteOffset,this._tensor.tensor_content.byteLength):this._tensor.int_val&&this._tensor.int_val.length==t.size?t.data=this._tensor.int_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_STRING:this._tensor.tensor_content&&this._tensor.tensor_content.length>0?t.state="Tensor data type is not implemented.":this._tensor.string_val&&this._tensor.string_val.length==t.size?t.data=this._tensor.string_val:t.state="Tensor data is empty.";break;case tf.proto.DataType.DT_BOOL:t.state="Tensor data type 'bool' is not implemented.";break;default:t.state="Tensor data type '"+this._tensor.dtype+"' is not implemented."}return t.shape=e.dim.map((t=>t.size)),t}_decode(t,e){let s=t.shape;0==s.length&&(s=[1]);const n=[],o=s[e];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;if(t.data){const e=t.data[t.index++];n.push(this._tensor.dtype==tf.proto.DataType.DT_STRING?tf.Utility.decodeText(e):e),t.count++}else if(t.rawData)switch(this._tensor.dtype){case tf.proto.DataType.DT_FLOAT:n.push(t.rawData.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_INT32:n.push(t.rawData.getInt32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_UINT32:n.push(t.rawData.getUint32(t.index,!0)),t.index+=4,t.count++;break;case tf.proto.DataType.DT_QINT8:n.push(t.rawData.getInt8(t.index,!0)),t.index+=1,t.count++;break;case tf.proto.DataType.DT_QUINT8:n.push(t.rawData.getUint8(t.index,!0)),t.index+=1,t.count++}}else for(let r=0;rt.limit)return n.push("..."),n;n.push(this._decode(t,e+1,s))}return 0==t.shape.length?n[0]:n}static formatDataType(t){if(!tf.Tensor.dataType){tf.Tensor.dataType={};for(let t of Object.keys(tf.proto.DataType)){const e=tf.proto.DataType[t];t=t.startsWith("DT_")?t.substring(3):t,tf.Tensor.dataType[e]=t.toLowerCase()}tf.Tensor.dataType[tf.proto.DataType.DT_HALF]="float16",tf.Tensor.dataType[tf.proto.DataType.DT_FLOAT]="float32",tf.Tensor.dataType[tf.proto.DataType.DT_DOUBLE]="float64",tf.Tensor.dataType.DT_FLOAT="float32"}return tf.Tensor.dataType[t]||"?"}},tf.TensorType=class{constructor(t,e){this._dtype=t,this._shape=new tf.TensorShape(e)}get dataType(){return this._dtype?tf.Tensor.formatDataType(this._dtype):"?"}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},tf.TensorShape=class{constructor(t){this._shape=t}get dimensions(){return this._shape&&this._shape.dim?this._shape.unknown_rank?null:0==this._shape.dim.length?[]:1!=this._shape.dim.length||this._shape.dim[0].size?this._shape.dim.map((t=>t.size&&-1!=t.size?t.size:"?")):[0]:null}toString(){return this._shape&&this._shape.dim?this._shape.unknown_rank?"[-]":0==this._shape.dim.length?"":1!=this._shape.dim.length||this._shape.dim[0].size?"["+this._shape.dim.map((t=>t.size&&-1!=t.size?t.size.toString():"?")).join(",")+"]":"[0]":"?"}},tf.TensorBundle=class{static open(t,e,s,n){const o=e.toLowerCase().endsWith(".index")?2:1;if(t.length<=48)throw new tf.Error("Invalid index file size.");const r=new tf.TensorBundle.BinaryReader(t,n);r.seek(-8);const a=[87,251,128,139,36,117,71,219];if(!r.bytes(8).every(((t,e)=>t===a[e])))throw new tf.Error("Invalid table signature.");r.seek(-48),r.varint64(),r.varint64();const i=r.varint64(),p=r.varint64();r.seek(i);const h=r.clone(p),u=r.byte();if(0!==u)throw new tf.Error("Unsupported block compression '"+u+"'.");h.seek(-4);const f=h.int32();h.seek(-4-4*f);const l=[];for(let t=0;tnew tf.TensorBundle(o,_,t))).catch((t=>(n.exception(t,!1),new tf.TensorBundle(o,_,null))))}constructor(t,e,s){switch(this._format=t,this._tensors=[],t){case 1:{const t=e.get(""),s=protobuf.Reader.create(t),n=tf.proto.SavedTensorSlices.decode(s),o=new Map;for(const t of e)if(""!==t[0]&&"global_step"!==t[0]){const e=protobuf.Reader.create(t[1]),s=tf.proto.SavedTensorSlices.decode(e),n=s.data.name,r=s.data.data;if(o.has(n)){const t=o.get(n);null!==t&&(r[t.key]&&r[t.key].length>0?t.value=t.value.concat(r[t.key]):o.set(n,null))}else if(r.tensor_content&&r.tensor_content.length>0)o.set(n,{key:"tensor_content",value:r.tensor_content});else{const t=Object.keys(r).filter((t=>t.endsWith("_val")&&r[t]&&r[t].length>0));o.set(n,1==t.length?{key:t[0],value:r[t[0]]}:null)}}for(const t of n.meta.tensor)if("global_step"!==t.name){const e=new tf.proto.TensorProto;e.dtype=t.type,e.tensor_shape=t.shape;const s=o.get(t.name);s&&(e[s.key]=s.value),this._tensors.push(new tf.Tensor(e,t.name,null))}break}case 2:e.forEach(((t,e)=>{if(""!==e){const n=protobuf.Reader.create(t),o=tf.proto.BundleEntryProto.decode(n),r=new tf.proto.TensorProto;r.dtype=o.dtype,r.tensor_shape=o.shape;const a=o.offset instanceof long.Long?o.offset.toNumber():o.offset,i=o.size instanceof long.Long?o.size.toNumber():o.size;s&&(r.tensor_content=s[o.shard_id].slice(a,a+i)),this._tensors.push(new tf.Tensor(r,e,null))}}))}}get format(){return this._format}get tensors(){return this._tensors}},tf.TensorBundle.BinaryReader=class{constructor(t){t&&(this._buffer=t,this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._position=0,this._start=0,this._end=this._buffer.length)}seek(t){if(this._position=t>=0?this._start+t:this._end+t,this._position>this._end)throw new tf.Error("Expected "+(this._position-this._end)+" more bytes. The file might be corrupted. Unexpected end of file.")}skip(t){if(this._position+=t,this._position>this._end)throw new tf.Error("Expected "+(this._position-this._end)+" more bytes. The file might be corrupted. Unexpected end of file.")}end(){return this._position>=this._end}clone(t){const e=new tf.TensorBundle.BinaryReader;return e._buffer=this._buffer,e._dataView=this._dataView,e._start=this._position,e._position=this._position,this.skip(t),e._end=this._position,e}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}byte(){const t=this._position;return this.skip(1),this._dataView.getUint8(t)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}varint32(){return this.varint64()}varint64(){let t=0;for(let e=0;e<=63;e+=7){const s=this.byte();if(!(128&s)){t|=s<0)for(const t of e.attributes)s[t.name]=t;this._attributeCache[t]=s}return s[e]||null}getAttributeVisibleMap(t){const e=this.type(t);if(e){let t=e.__visisbleAttributeMap__;if(!t){if(t={},e.inputs)for(const s of e.inputs)s.typeAttr?t[s.typeAttr]=!0:s.typeListAttr&&(t[s.typeListAttr]=!0),s.numberAttr&&(t[s.numberAttr]=!0);if(e.outputs)for(const s of e.outputs)s.typeAttr?t[s.typeAttr]=!0:s.typeListAttr&&(t[s.typeListAttr]=!0),s.numberAttr&&(t[s.numberAttr]=!0);e.__visisbleAttributeMap__=t}return t}return{}}static _formatAttributeValue(t){if(null==t)return null;if(t&&long.Long.isLong(t)&&(t=t.toNumber()),Array.isArray(t))return t.map((t=>tf.GraphMetadata._formatAttributeValue(t)));if(t===Object(t))switch(t.type){case"type":return tf.Tensor.formatDataType(t.value);case"shape":case"tensor":return t.value}return"string"==typeof t?'"'+t+'"':t.toString()}},tf.Metadata=class{static open(t){return tf.Metadata._metadata?Promise.resolve(tf.Metadata._metadata):t.request(null,"tf-metadata.json","utf-8").then((t=>(tf.Metadata._metadata=new tf.Metadata(t),tf.Metadata._metadata))).catch((()=>(tf.Metadata._metadata=new tf.Metadata(null),tf.Metadata._metadata)))}constructor(t){if(this._map={},t&&t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map[t.name]=t.schema)}}type(t){return this._map[t]}},tf.Utility=class{static decodeText(t){return"string"==typeof t?t:0===t.length?"":(tf.Utility._utf8Decoder=tf.Utility._utf8Decoder||new TextDecoder("utf-8"),tf.Utility._utf8Decoder.decode(t))}},tf.Error=class extends Error{constructor(t){super(t),this.name="Error loading TensorFlow model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tf.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..2ffb8b80bcdcbbef7f32c2abb47af43cf6ed6510 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-metadata.json @@ -0,0 +1 @@ +[{"name":"Conv2D","schema":{"category":"Layer","inputs":[{"name":"input","description":"4D tensor"},{"name":"filter"},{"name":"bias","description":"(optional)"}],"outputs":[{"name":"output","description":"result of 2D convolution of the input tensor"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME","description":"`SAME`|`VALID`"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE","description":"`NONE`|`RELU`|`RELU6`"},{"name":"stride_w","type":"int32","default":1,"description":"stride of the filter window"},{"name":"stride_h","type":"int32","default":1,"description":"stride of the filter window"},{"name":"dilation_w_factor","type":"int32","default":1},{"name":"dilation_h_factor","type":"int32","default":1}]}},{"name":"LSTM","schema":{"category":"Layer","inputs":[{"name":"input","type":"T","description":"Input tensor."},{"name":"input_input_weights","type":"T","option":"optional","description":"Input to input weights tensor.","visible":false},{"name":"input_forget_weights","type":"T","description":"Input to forget weights tensor.","visible":false},{"name":"input_cell_weights","type":"T","description":"Input to cell weights tensor.","visible":false},{"name":"input_output_weights","type":"T","description":"Input to output weights tensor.","visible":false},{"name":"recurrent_input_weights","type":"T","option":"optional","description":"Recurrent to input weights tensor.","visible":false},{"name":"recurrent_forget_weights","type":"T","description":"Recurrent to forget weights tensor.","visible":false},{"name":"recurrent_cell_weights","type":"T","description":"Recurrent to cell weights tensor.","visible":false},{"name":"recurrent_output_weights","type":"T","description":"Recurrent to output weights tensor.","visible":false},{"name":"cell_input_weights","type":"T","option":"optional","description":"Cell to input weights tensor.","visible":false},{"name":"cell_forget_weights","type":"T","option":"optional","description":"Cell to forget weights tensor.","visible":false},{"name":"cell_output_weights","type":"T","option":"optional","description":"Cell to output weights tensor.","visible":false},{"name":"input_bias","type":"T","option":"optional","description":"Input gate bias tensor.","visible":false},{"name":"forget_bias","type":"T","description":"Forget gate bias tensor.","visible":false},{"name":"cell_bias","type":"T","description":"Cell gate bias tensor.","visible":false},{"name":"output_bias","type":"T","description":"Output gate bias tensor.","visible":false},{"name":"projection_weights","type":"T","option":"optional","description":"Projection weights tensor.","visible":false},{"name":"projection_bias","type":"T","option":"optional","description":"Projection bias tensor.","visible":false}],"outputs":[{"name":"scratch","type":"T"},{"name":"output_state","type":"T"},{"name":"cell_state","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"cell_clip","type":"float32","default":0},{"name":"proj_clip","type":"float32","default":0},{"name":"kernel_type","type":"LSTMKernelType","default":"FULL"}]}},{"name":"RNN","schema":{"category":"Layer","inputs":[{"name":"X","type":"T"},{"name":"W","type":"T"},{"name":"R","type":"T"},{"name":"b","type":"T"}],"outputs":[{"name":"hidden","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"FullyConnected","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"weights","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"weights_format","type":"FullyConnectedOptionsWeightsFormat","default":"DEFAULT"},{"name":"keep_num_dims","type":"boolean"}]}},{"name":"DepthwiseConv2D","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"weights","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32","default":1},{"name":"stride_h","type":"int32","default":1},{"name":"depth_multiplier","type":"int32","default":1},{"name":"dilation_w_factor","type":"int32","default":1},{"name":"dilation_h_factor","type":"int32","default":1}]}},{"name":"AveragePool2D","schema":{"category":"Pool","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"},{"name":"filter_width","type":"int32"},{"name":"filter_height","type":"int32"}]}},{"name":"Softmax","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"LogSoftmax","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Relu","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Relu6","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Prelu","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"},{"name":"slope","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Tanh","schema":{"category":"Activation","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}]}},{"name":"Reshape","schema":{"category":"Shape","attributes":[{"name":"new_shape","type":"shape"}],"inputs":[{"name":"data","type":"T"},{"name":"shape","type":"T"}],"outputs":[{"name":"reshaped","type":"T"}]}},{"name":"MaxPool2D","schema":{"category":"Pool","inputs":[{"name":"input","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"padding","type":"Padding","default":"SAME"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"},{"name":"filter_width","type":"int32"},{"name":"filter_height","type":"int32"}]}},{"name":"LSHProjection","schema":{"inputs":[{"name":"hash"},{"name":"input"},{"name":"weight"}],"outputs":[{"name":"output"}],"attributes":[{"name":"type","type":"LSHProjectionType"}]}},{"name":"Normalize","schema":{"category":"Normalization","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"LocalResponseNormalization","schema":{"category":"Normalization","attributes":[{"name":"radius","type":"int32","default":5},{"name":"bias","type":"float32","default":1},{"name":"alpha","type":"float32","default":1},{"name":"beta","type":"float32","default":0.5}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Predict","schema":{"inputs":[{"name":"hashes"},{"name":"keys"},{"name":"labels"},{"name":"weights"}],"outputs":[{"name":"label"},{"name":"weight"}]}},{"name":"HashtableLookup","schema":{"inputs":[{"name":"key"},{"name":"keys"},{"name":"values"}],"outputs":[{"name":"value"},{"name":"hits"}]}},{"name":"ExtractFeatures","schema":{"inputs":[{"name":"ngrams"}],"outputs":[{"name":"features"},{"name":"weights"}]}},{"name":"SkipGram","schema":{"inputs":[{"name":"inputs"}],"outputs":[{"name":"ngrams"}]}},{"name":"Concatenation","schema":{"category":"Tensor","inputs":[{"name":"inputs","option":"variadic"}],"outputs":[{"name":"output"}],"attributes":[{"name":"axis","type":"int32"},{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Pad","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"paddings"}],"outputs":[{"name":"output"}]}},{"name":"Split","schema":{"category":"Tensor","inputs":[{"name":"axis"},{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Squeeze","schema":{"category":"Transform","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"StridedSlice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"end"},{"name":"strides"}],"outputs":[{"name":"output"}]}},{"name":"SVDF","schema":{"category":"Layer","inputs":[{"name":"input","type":"T"},{"name":"feature","type":"T"},{"name":"time","type":"T"},{"name":"bias","type":"T"}],"outputs":[{"name":"state","type":"T"},{"name":"output","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Add","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Sub","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Mul","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Div","schema":{"inputs":[{"name":"A","type":"T"},{"name":"B","type":"T"}],"outputs":[{"name":"C","type":"T"}],"attributes":[{"name":"fused_activation_function","type":"ActivationFunctionType","default":"NONE"}]}},{"name":"Sum","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"ReduceMax","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"ReduceMin","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"Mean","schema":{"inputs":[{"name":"input","type":"T"},{"name":"axis","type":"T"}],"outputs":[{"name":"output","type":"T"}],"attributes":[{"name":"keep_dims","type":"boolean"}]}},{"name":"Logistic","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ResizeBilinear","schema":{"attributes":[{"name":"align_corners","default":false}],"inputs":[{"name":"input"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Gather","schema":{"attributes":[{"name":"axis","default":0}],"inputs":[{"name":"input"},{"name":"positions"}],"outputs":[{"name":"output"}]}},{"name":"Cast","schema":{"attributes":[{"name":"in_data_type","type":"TensorType"},{"name":"out_data_type","type":"TensorType"}],"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"ArgMax","schema":{"attributes":[{"name":"output_type","type":"TensorType"}]}},{"name":"ArgMin","schema":{"attributes":[{"name":"output_type","type":"TensorType"}]}},{"name":"TransposeConv","schema":{"category":"Layer","attributes":[{"name":"padding","type":"Padding"},{"name":"stride_w","type":"int32"},{"name":"stride_h","type":"int32"}],"inputs":[{"name":"output_shape"},{"name":"weights"},{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Shape","schema":{"attributes":[{"name":"out_type","type":"TensorType"}]}},{"name":"Unique","schema":{"attributes":[{"name":"idx_out_type","type":"TensorType","default":"int32"}]}},{"name":"Slice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"size"}],"outputs":[{"name":"output"}]}},{"name":"Transpose","schema":{"category":"Transform","inputs":[{"name":"input"},{"name":"perm"}],"outputs":[{"name":"output"}]}},{"name":"Quantize","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Dequantize","schema":{"inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}},{"name":"Minimum","schema":{"inputs":[{"name":"input1"},{"name":"input2"}],"outputs":[{"name":"output"}]}},{"name":"Maximum","schema":{"inputs":[{"name":"input1"},{"name":"input2"}],"outputs":[{"name":"output"}]}},{"name":"HardSwish","schema":{"category":"Activation","inputs":[{"name":"input"}],"outputs":[{"name":"output"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-schema.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-schema.js new file mode 100644 index 0000000000000000000000000000000000000000..85baa44a6b4f070d2028f15481c894a764e6f1ae --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite-schema.js @@ -0,0 +1 @@ +var $root=flatbuffers.get("tflite");$root.tflite=$root.tflite||{},$root.tflite.TensorType={FLOAT32:0,FLOAT16:1,INT32:2,UINT8:3,INT64:4,STRING:5,BOOL:6,INT16:7,COMPLEX64:8,INT8:9,FLOAT64:10,COMPLEX128:11},$root.tflite.CustomQuantization=class{static decode(t,e){const o=new $root.tflite.CustomQuantization;return o.custom=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.CustomQuantization;return o.custom=t.typedArray(e.custom,Uint8Array),o}},$root.tflite.QuantizationDetails=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.CustomQuantization.decode(t,e)}}static decodeText(t,e,o){switch(o){case"CustomQuantization":return $root.tflite.CustomQuantization.decodeText(t,e)}}},$root.tflite.QuantizationParameters=class{static decode(t,e){const o=new $root.tflite.QuantizationParameters;return o.min=t.typedArray(e,4,Float32Array),o.max=t.typedArray(e,6,Float32Array),o.scale=t.typedArray(e,8,Float32Array),o.zero_point=t.int64s_(e,10),o.details=t.union(e,12,$root.tflite.QuantizationDetails.decode),o.quantized_dimension=t.int32_(e,16,0),o}static decodeText(t,e){const o=new $root.tflite.QuantizationParameters;return o.min=t.typedArray(e.min,Float32Array),o.max=t.typedArray(e.max,Float32Array),o.scale=t.typedArray(e.scale,Float32Array),o.zero_point=t.array(e.zero_point),o.details=$root.tflite.QuantizationDetails.decodeText(t,e.details,e.details_type),o.quantized_dimension=t.value(e.quantized_dimension,0),o}},$root.tflite.DimensionType={DENSE:0,SPARSE_CSR:1},$root.tflite.Int32Vector=class{static decode(t,e){const o=new $root.tflite.Int32Vector;return o.values=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Int32Vector;return o.values=t.typedArray(e.values,Int32Array),o}},$root.tflite.Uint16Vector=class{static decode(t,e){const o=new $root.tflite.Uint16Vector;return o.values=t.typedArray(e,4,Uint16Array),o}static decodeText(t,e){const o=new $root.tflite.Uint16Vector;return o.values=t.typedArray(e.values,Uint16Array),o}},$root.tflite.Uint8Vector=class{static decode(t,e){const o=new $root.tflite.Uint8Vector;return o.values=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.Uint8Vector;return o.values=t.typedArray(e.values,Uint8Array),o}},$root.tflite.SparseIndexVector=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.Int32Vector.decode(t,e);case 2:return $root.tflite.Uint16Vector.decode(t,e);case 3:return $root.tflite.Uint8Vector.decode(t,e)}}static decodeText(t,e,o){switch(o){case"Int32Vector":return $root.tflite.Int32Vector.decodeText(t,e);case"Uint16Vector":return $root.tflite.Uint16Vector.decodeText(t,e);case"Uint8Vector":return $root.tflite.Uint8Vector.decodeText(t,e)}}},$root.tflite.DimensionMetadata=class{static decode(t,e){const o=new $root.tflite.DimensionMetadata;return o.format=t.int8_(e,4,0),o.dense_size=t.int32_(e,6,0),o.array_segments=t.union(e,8,$root.tflite.SparseIndexVector.decode),o.array_indices=t.union(e,12,$root.tflite.SparseIndexVector.decode),o}static decodeText(t,e){const o=new $root.tflite.DimensionMetadata;return o.format=$root.tflite.DimensionType[e.format],o.dense_size=t.value(e.dense_size,0),o.array_segments=$root.tflite.SparseIndexVector.decodeText(t,e.array_segments,e.array_segments_type),o.array_indices=$root.tflite.SparseIndexVector.decodeText(t,e.array_indices,e.array_indices_type),o}},$root.tflite.SparsityParameters=class{static decode(t,e){const o=new $root.tflite.SparsityParameters;return o.traversal_order=t.typedArray(e,4,Int32Array),o.block_map=t.typedArray(e,6,Int32Array),o.dim_metadata=t.tableArray(e,8,$root.tflite.DimensionMetadata.decode),o}static decodeText(t,e){const o=new $root.tflite.SparsityParameters;return o.traversal_order=t.typedArray(e.traversal_order,Int32Array),o.block_map=t.typedArray(e.block_map,Int32Array),o.dim_metadata=t.objectArray(e.dim_metadata,$root.tflite.DimensionMetadata.decodeText),o}},$root.tflite.Tensor=class{static decode(t,e){const o=new $root.tflite.Tensor;return o.shape=t.typedArray(e,4,Int32Array),o.type=t.int8_(e,6,0),o.buffer=t.uint32_(e,8,0),o.name=t.string_(e,10,null),o.quantization=t.table(e,12,$root.tflite.QuantizationParameters.decode),o.is_variable=t.bool_(e,14,!1),o.sparsity=t.table(e,16,$root.tflite.SparsityParameters.decode),o.shape_signature=t.typedArray(e,18,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Tensor;return o.shape=t.typedArray(e.shape,Int32Array),o.type=$root.tflite.TensorType[e.type],o.buffer=t.value(e.buffer,0),o.name=t.value(e.name,null),o.quantization=t.object(e.quantization,$root.tflite.QuantizationParameters.decodeText),o.is_variable=t.value(e.is_variable,!1),o.sparsity=t.object(e.sparsity,$root.tflite.SparsityParameters.decodeText),o.shape_signature=t.typedArray(e.shape_signature,Int32Array),o}},$root.tflite.BuiltinOperator={ADD:0,AVERAGE_POOL_2D:1,CONCATENATION:2,CONV_2D:3,DEPTHWISE_CONV_2D:4,DEPTH_TO_SPACE:5,DEQUANTIZE:6,EMBEDDING_LOOKUP:7,FLOOR:8,FULLY_CONNECTED:9,HASHTABLE_LOOKUP:10,L2_NORMALIZATION:11,L2_POOL_2D:12,LOCAL_RESPONSE_NORMALIZATION:13,LOGISTIC:14,LSH_PROJECTION:15,LSTM:16,MAX_POOL_2D:17,MUL:18,RELU:19,RELU_N1_TO_1:20,RELU6:21,RESHAPE:22,RESIZE_BILINEAR:23,RNN:24,SOFTMAX:25,SPACE_TO_DEPTH:26,SVDF:27,TANH:28,CONCAT_EMBEDDINGS:29,SKIP_GRAM:30,CALL:31,CUSTOM:32,EMBEDDING_LOOKUP_SPARSE:33,PAD:34,UNIDIRECTIONAL_SEQUENCE_RNN:35,GATHER:36,BATCH_TO_SPACE_ND:37,SPACE_TO_BATCH_ND:38,TRANSPOSE:39,MEAN:40,SUB:41,DIV:42,SQUEEZE:43,UNIDIRECTIONAL_SEQUENCE_LSTM:44,STRIDED_SLICE:45,BIDIRECTIONAL_SEQUENCE_RNN:46,EXP:47,TOPK_V2:48,SPLIT:49,LOG_SOFTMAX:50,DELEGATE:51,BIDIRECTIONAL_SEQUENCE_LSTM:52,CAST:53,PRELU:54,MAXIMUM:55,ARG_MAX:56,MINIMUM:57,LESS:58,NEG:59,PADV2:60,GREATER:61,GREATER_EQUAL:62,LESS_EQUAL:63,SELECT:64,SLICE:65,SIN:66,TRANSPOSE_CONV:67,SPARSE_TO_DENSE:68,TILE:69,EXPAND_DIMS:70,EQUAL:71,NOT_EQUAL:72,LOG:73,SUM:74,SQRT:75,RSQRT:76,SHAPE:77,POW:78,ARG_MIN:79,FAKE_QUANT:80,REDUCE_PROD:81,REDUCE_MAX:82,PACK:83,LOGICAL_OR:84,ONE_HOT:85,LOGICAL_AND:86,LOGICAL_NOT:87,UNPACK:88,REDUCE_MIN:89,FLOOR_DIV:90,REDUCE_ANY:91,SQUARE:92,ZEROS_LIKE:93,FILL:94,FLOOR_MOD:95,RANGE:96,RESIZE_NEAREST_NEIGHBOR:97,LEAKY_RELU:98,SQUARED_DIFFERENCE:99,MIRROR_PAD:100,ABS:101,SPLIT_V:102,UNIQUE:103,CEIL:104,REVERSE_V2:105,ADD_N:106,GATHER_ND:107,COS:108,WHERE:109,RANK:110,ELU:111,REVERSE_SEQUENCE:112,MATRIX_DIAG:113,QUANTIZE:114,MATRIX_SET_DIAG:115,ROUND:116,HARD_SWISH:117,IF:118,WHILE:119,NON_MAX_SUPPRESSION_V4:120,NON_MAX_SUPPRESSION_V5:121,SCATTER_ND:122,SELECT_V2:123,DENSIFY:124,SEGMENT_SUM:125,BATCH_MATMUL:126},$root.tflite.BuiltinOptions=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.Conv2DOptions.decode(t,e);case 2:return $root.tflite.DepthwiseConv2DOptions.decode(t,e);case 3:return $root.tflite.ConcatEmbeddingsOptions.decode(t,e);case 4:return $root.tflite.LSHProjectionOptions.decode(t,e);case 5:return $root.tflite.Pool2DOptions.decode(t,e);case 6:return $root.tflite.SVDFOptions.decode(t,e);case 7:return $root.tflite.RNNOptions.decode(t,e);case 8:return $root.tflite.FullyConnectedOptions.decode(t,e);case 9:return $root.tflite.SoftmaxOptions.decode(t,e);case 10:return $root.tflite.ConcatenationOptions.decode(t,e);case 11:return $root.tflite.AddOptions.decode(t,e);case 12:return $root.tflite.L2NormOptions.decode(t,e);case 13:return $root.tflite.LocalResponseNormalizationOptions.decode(t,e);case 14:return $root.tflite.LSTMOptions.decode(t,e);case 15:return $root.tflite.ResizeBilinearOptions.decode(t,e);case 16:return $root.tflite.CallOptions.decode(t,e);case 17:return $root.tflite.ReshapeOptions.decode(t,e);case 18:return $root.tflite.SkipGramOptions.decode(t,e);case 19:return $root.tflite.SpaceToDepthOptions.decode(t,e);case 20:return $root.tflite.EmbeddingLookupSparseOptions.decode(t,e);case 21:return $root.tflite.MulOptions.decode(t,e);case 22:return $root.tflite.PadOptions.decode(t,e);case 23:return $root.tflite.GatherOptions.decode(t,e);case 24:return $root.tflite.BatchToSpaceNDOptions.decode(t,e);case 25:return $root.tflite.SpaceToBatchNDOptions.decode(t,e);case 26:return $root.tflite.TransposeOptions.decode(t,e);case 27:return $root.tflite.ReducerOptions.decode(t,e);case 28:return $root.tflite.SubOptions.decode(t,e);case 29:return $root.tflite.DivOptions.decode(t,e);case 30:return $root.tflite.SqueezeOptions.decode(t,e);case 31:return $root.tflite.SequenceRNNOptions.decode(t,e);case 32:return $root.tflite.StridedSliceOptions.decode(t,e);case 33:return $root.tflite.ExpOptions.decode(t,e);case 34:return $root.tflite.TopKV2Options.decode(t,e);case 35:return $root.tflite.SplitOptions.decode(t,e);case 36:return $root.tflite.LogSoftmaxOptions.decode(t,e);case 37:return $root.tflite.CastOptions.decode(t,e);case 38:return $root.tflite.DequantizeOptions.decode(t,e);case 39:return $root.tflite.MaximumMinimumOptions.decode(t,e);case 40:return $root.tflite.ArgMaxOptions.decode(t,e);case 41:return $root.tflite.LessOptions.decode(t,e);case 42:return $root.tflite.NegOptions.decode(t,e);case 43:return $root.tflite.PadV2Options.decode(t,e);case 44:return $root.tflite.GreaterOptions.decode(t,e);case 45:return $root.tflite.GreaterEqualOptions.decode(t,e);case 46:return $root.tflite.LessEqualOptions.decode(t,e);case 47:return $root.tflite.SelectOptions.decode(t,e);case 48:return $root.tflite.SliceOptions.decode(t,e);case 49:return $root.tflite.TransposeConvOptions.decode(t,e);case 50:return $root.tflite.SparseToDenseOptions.decode(t,e);case 51:return $root.tflite.TileOptions.decode(t,e);case 52:return $root.tflite.ExpandDimsOptions.decode(t,e);case 53:return $root.tflite.EqualOptions.decode(t,e);case 54:return $root.tflite.NotEqualOptions.decode(t,e);case 55:return $root.tflite.ShapeOptions.decode(t,e);case 56:return $root.tflite.PowOptions.decode(t,e);case 57:return $root.tflite.ArgMinOptions.decode(t,e);case 58:return $root.tflite.FakeQuantOptions.decode(t,e);case 59:return $root.tflite.PackOptions.decode(t,e);case 60:return $root.tflite.LogicalOrOptions.decode(t,e);case 61:return $root.tflite.OneHotOptions.decode(t,e);case 62:return $root.tflite.LogicalAndOptions.decode(t,e);case 63:return $root.tflite.LogicalNotOptions.decode(t,e);case 64:return $root.tflite.UnpackOptions.decode(t,e);case 65:return $root.tflite.FloorDivOptions.decode(t,e);case 66:return $root.tflite.SquareOptions.decode(t,e);case 67:return $root.tflite.ZerosLikeOptions.decode(t,e);case 68:return $root.tflite.FillOptions.decode(t,e);case 69:return $root.tflite.BidirectionalSequenceLSTMOptions.decode(t,e);case 70:return $root.tflite.BidirectionalSequenceRNNOptions.decode(t,e);case 71:return $root.tflite.UnidirectionalSequenceLSTMOptions.decode(t,e);case 72:return $root.tflite.FloorModOptions.decode(t,e);case 73:return $root.tflite.RangeOptions.decode(t,e);case 74:return $root.tflite.ResizeNearestNeighborOptions.decode(t,e);case 75:return $root.tflite.LeakyReluOptions.decode(t,e);case 76:return $root.tflite.SquaredDifferenceOptions.decode(t,e);case 77:return $root.tflite.MirrorPadOptions.decode(t,e);case 78:return $root.tflite.AbsOptions.decode(t,e);case 79:return $root.tflite.SplitVOptions.decode(t,e);case 80:return $root.tflite.UniqueOptions.decode(t,e);case 81:return $root.tflite.ReverseV2Options.decode(t,e);case 82:return $root.tflite.AddNOptions.decode(t,e);case 83:return $root.tflite.GatherNdOptions.decode(t,e);case 84:return $root.tflite.CosOptions.decode(t,e);case 85:return $root.tflite.WhereOptions.decode(t,e);case 86:return $root.tflite.RankOptions.decode(t,e);case 87:return $root.tflite.ReverseSequenceOptions.decode(t,e);case 88:return $root.tflite.MatrixDiagOptions.decode(t,e);case 89:return $root.tflite.QuantizeOptions.decode(t,e);case 90:return $root.tflite.MatrixSetDiagOptions.decode(t,e);case 91:return $root.tflite.HardSwishOptions.decode(t,e);case 92:return $root.tflite.IfOptions.decode(t,e);case 93:return $root.tflite.WhileOptions.decode(t,e);case 94:return $root.tflite.DepthToSpaceOptions.decode(t,e);case 95:return $root.tflite.NonMaxSuppressionV4Options.decode(t,e);case 96:return $root.tflite.NonMaxSuppressionV5Options.decode(t,e);case 97:return $root.tflite.ScatterNdOptions.decode(t,e);case 98:return $root.tflite.SelectV2Options.decode(t,e);case 99:return $root.tflite.DensifyOptions.decode(t,e);case 100:return $root.tflite.SegmentSumOptions.decode(t,e);case 101:return $root.tflite.BatchMatMulOptions.decode(t,e)}}static decodeText(t,e,o){switch(o){case"Conv2DOptions":return $root.tflite.Conv2DOptions.decodeText(t,e);case"DepthwiseConv2DOptions":return $root.tflite.DepthwiseConv2DOptions.decodeText(t,e);case"ConcatEmbeddingsOptions":return $root.tflite.ConcatEmbeddingsOptions.decodeText(t,e);case"LSHProjectionOptions":return $root.tflite.LSHProjectionOptions.decodeText(t,e);case"Pool2DOptions":return $root.tflite.Pool2DOptions.decodeText(t,e);case"SVDFOptions":return $root.tflite.SVDFOptions.decodeText(t,e);case"RNNOptions":return $root.tflite.RNNOptions.decodeText(t,e);case"FullyConnectedOptions":return $root.tflite.FullyConnectedOptions.decodeText(t,e);case"SoftmaxOptions":return $root.tflite.SoftmaxOptions.decodeText(t,e);case"ConcatenationOptions":return $root.tflite.ConcatenationOptions.decodeText(t,e);case"AddOptions":return $root.tflite.AddOptions.decodeText(t,e);case"L2NormOptions":return $root.tflite.L2NormOptions.decodeText(t,e);case"LocalResponseNormalizationOptions":return $root.tflite.LocalResponseNormalizationOptions.decodeText(t,e);case"LSTMOptions":return $root.tflite.LSTMOptions.decodeText(t,e);case"ResizeBilinearOptions":return $root.tflite.ResizeBilinearOptions.decodeText(t,e);case"CallOptions":return $root.tflite.CallOptions.decodeText(t,e);case"ReshapeOptions":return $root.tflite.ReshapeOptions.decodeText(t,e);case"SkipGramOptions":return $root.tflite.SkipGramOptions.decodeText(t,e);case"SpaceToDepthOptions":return $root.tflite.SpaceToDepthOptions.decodeText(t,e);case"EmbeddingLookupSparseOptions":return $root.tflite.EmbeddingLookupSparseOptions.decodeText(t,e);case"MulOptions":return $root.tflite.MulOptions.decodeText(t,e);case"PadOptions":return $root.tflite.PadOptions.decodeText(t,e);case"GatherOptions":return $root.tflite.GatherOptions.decodeText(t,e);case"BatchToSpaceNDOptions":return $root.tflite.BatchToSpaceNDOptions.decodeText(t,e);case"SpaceToBatchNDOptions":return $root.tflite.SpaceToBatchNDOptions.decodeText(t,e);case"TransposeOptions":return $root.tflite.TransposeOptions.decodeText(t,e);case"ReducerOptions":return $root.tflite.ReducerOptions.decodeText(t,e);case"SubOptions":return $root.tflite.SubOptions.decodeText(t,e);case"DivOptions":return $root.tflite.DivOptions.decodeText(t,e);case"SqueezeOptions":return $root.tflite.SqueezeOptions.decodeText(t,e);case"SequenceRNNOptions":return $root.tflite.SequenceRNNOptions.decodeText(t,e);case"StridedSliceOptions":return $root.tflite.StridedSliceOptions.decodeText(t,e);case"ExpOptions":return $root.tflite.ExpOptions.decodeText(t,e);case"TopKV2Options":return $root.tflite.TopKV2Options.decodeText(t,e);case"SplitOptions":return $root.tflite.SplitOptions.decodeText(t,e);case"LogSoftmaxOptions":return $root.tflite.LogSoftmaxOptions.decodeText(t,e);case"CastOptions":return $root.tflite.CastOptions.decodeText(t,e);case"DequantizeOptions":return $root.tflite.DequantizeOptions.decodeText(t,e);case"MaximumMinimumOptions":return $root.tflite.MaximumMinimumOptions.decodeText(t,e);case"ArgMaxOptions":return $root.tflite.ArgMaxOptions.decodeText(t,e);case"LessOptions":return $root.tflite.LessOptions.decodeText(t,e);case"NegOptions":return $root.tflite.NegOptions.decodeText(t,e);case"PadV2Options":return $root.tflite.PadV2Options.decodeText(t,e);case"GreaterOptions":return $root.tflite.GreaterOptions.decodeText(t,e);case"GreaterEqualOptions":return $root.tflite.GreaterEqualOptions.decodeText(t,e);case"LessEqualOptions":return $root.tflite.LessEqualOptions.decodeText(t,e);case"SelectOptions":return $root.tflite.SelectOptions.decodeText(t,e);case"SliceOptions":return $root.tflite.SliceOptions.decodeText(t,e);case"TransposeConvOptions":return $root.tflite.TransposeConvOptions.decodeText(t,e);case"SparseToDenseOptions":return $root.tflite.SparseToDenseOptions.decodeText(t,e);case"TileOptions":return $root.tflite.TileOptions.decodeText(t,e);case"ExpandDimsOptions":return $root.tflite.ExpandDimsOptions.decodeText(t,e);case"EqualOptions":return $root.tflite.EqualOptions.decodeText(t,e);case"NotEqualOptions":return $root.tflite.NotEqualOptions.decodeText(t,e);case"ShapeOptions":return $root.tflite.ShapeOptions.decodeText(t,e);case"PowOptions":return $root.tflite.PowOptions.decodeText(t,e);case"ArgMinOptions":return $root.tflite.ArgMinOptions.decodeText(t,e);case"FakeQuantOptions":return $root.tflite.FakeQuantOptions.decodeText(t,e);case"PackOptions":return $root.tflite.PackOptions.decodeText(t,e);case"LogicalOrOptions":return $root.tflite.LogicalOrOptions.decodeText(t,e);case"OneHotOptions":return $root.tflite.OneHotOptions.decodeText(t,e);case"LogicalAndOptions":return $root.tflite.LogicalAndOptions.decodeText(t,e);case"LogicalNotOptions":return $root.tflite.LogicalNotOptions.decodeText(t,e);case"UnpackOptions":return $root.tflite.UnpackOptions.decodeText(t,e);case"FloorDivOptions":return $root.tflite.FloorDivOptions.decodeText(t,e);case"SquareOptions":return $root.tflite.SquareOptions.decodeText(t,e);case"ZerosLikeOptions":return $root.tflite.ZerosLikeOptions.decodeText(t,e);case"FillOptions":return $root.tflite.FillOptions.decodeText(t,e);case"BidirectionalSequenceLSTMOptions":return $root.tflite.BidirectionalSequenceLSTMOptions.decodeText(t,e);case"BidirectionalSequenceRNNOptions":return $root.tflite.BidirectionalSequenceRNNOptions.decodeText(t,e);case"UnidirectionalSequenceLSTMOptions":return $root.tflite.UnidirectionalSequenceLSTMOptions.decodeText(t,e);case"FloorModOptions":return $root.tflite.FloorModOptions.decodeText(t,e);case"RangeOptions":return $root.tflite.RangeOptions.decodeText(t,e);case"ResizeNearestNeighborOptions":return $root.tflite.ResizeNearestNeighborOptions.decodeText(t,e);case"LeakyReluOptions":return $root.tflite.LeakyReluOptions.decodeText(t,e);case"SquaredDifferenceOptions":return $root.tflite.SquaredDifferenceOptions.decodeText(t,e);case"MirrorPadOptions":return $root.tflite.MirrorPadOptions.decodeText(t,e);case"AbsOptions":return $root.tflite.AbsOptions.decodeText(t,e);case"SplitVOptions":return $root.tflite.SplitVOptions.decodeText(t,e);case"UniqueOptions":return $root.tflite.UniqueOptions.decodeText(t,e);case"ReverseV2Options":return $root.tflite.ReverseV2Options.decodeText(t,e);case"AddNOptions":return $root.tflite.AddNOptions.decodeText(t,e);case"GatherNdOptions":return $root.tflite.GatherNdOptions.decodeText(t,e);case"CosOptions":return $root.tflite.CosOptions.decodeText(t,e);case"WhereOptions":return $root.tflite.WhereOptions.decodeText(t,e);case"RankOptions":return $root.tflite.RankOptions.decodeText(t,e);case"ReverseSequenceOptions":return $root.tflite.ReverseSequenceOptions.decodeText(t,e);case"MatrixDiagOptions":return $root.tflite.MatrixDiagOptions.decodeText(t,e);case"QuantizeOptions":return $root.tflite.QuantizeOptions.decodeText(t,e);case"MatrixSetDiagOptions":return $root.tflite.MatrixSetDiagOptions.decodeText(t,e);case"HardSwishOptions":return $root.tflite.HardSwishOptions.decodeText(t,e);case"IfOptions":return $root.tflite.IfOptions.decodeText(t,e);case"WhileOptions":return $root.tflite.WhileOptions.decodeText(t,e);case"DepthToSpaceOptions":return $root.tflite.DepthToSpaceOptions.decodeText(t,e);case"NonMaxSuppressionV4Options":return $root.tflite.NonMaxSuppressionV4Options.decodeText(t,e);case"NonMaxSuppressionV5Options":return $root.tflite.NonMaxSuppressionV5Options.decodeText(t,e);case"ScatterNdOptions":return $root.tflite.ScatterNdOptions.decodeText(t,e);case"SelectV2Options":return $root.tflite.SelectV2Options.decodeText(t,e);case"DensifyOptions":return $root.tflite.DensifyOptions.decodeText(t,e);case"SegmentSumOptions":return $root.tflite.SegmentSumOptions.decodeText(t,e);case"BatchMatMulOptions":return $root.tflite.BatchMatMulOptions.decodeText(t,e)}}},$root.tflite.Padding={SAME:0,VALID:1},$root.tflite.ActivationFunctionType={NONE:0,RELU:1,RELU_N1_TO_1:2,RELU6:3,TANH:4,SIGN_BIT:5},$root.tflite.Conv2DOptions=class{static decode(t,e){const o=new $root.tflite.Conv2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.fused_activation_function=t.int8_(e,10,0),o.dilation_w_factor=t.int32_(e,12,1),o.dilation_h_factor=t.int32_(e,14,1),o}static decodeText(t,e){const o=new $root.tflite.Conv2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.dilation_w_factor=t.value(e.dilation_w_factor,1),o.dilation_h_factor=t.value(e.dilation_h_factor,1),o}},$root.tflite.Pool2DOptions=class{static decode(t,e){const o=new $root.tflite.Pool2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.filter_width=t.int32_(e,10,0),o.filter_height=t.int32_(e,12,0),o.fused_activation_function=t.int8_(e,14,0),o}static decodeText(t,e){const o=new $root.tflite.Pool2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.filter_width=t.value(e.filter_width,0),o.filter_height=t.value(e.filter_height,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.DepthwiseConv2DOptions=class{static decode(t,e){const o=new $root.tflite.DepthwiseConv2DOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o.depth_multiplier=t.int32_(e,10,0),o.fused_activation_function=t.int8_(e,12,0),o.dilation_w_factor=t.int32_(e,14,1),o.dilation_h_factor=t.int32_(e,16,1),o}static decodeText(t,e){const o=new $root.tflite.DepthwiseConv2DOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o.depth_multiplier=t.value(e.depth_multiplier,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.dilation_w_factor=t.value(e.dilation_w_factor,1),o.dilation_h_factor=t.value(e.dilation_h_factor,1),o}},$root.tflite.ConcatEmbeddingsOptions=class{static decode(t,e){const o=new $root.tflite.ConcatEmbeddingsOptions;return o.num_channels=t.int32_(e,4,0),o.num_columns_per_channel=t.typedArray(e,6,Int32Array),o.embedding_dim_per_channel=t.typedArray(e,8,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.ConcatEmbeddingsOptions;return o.num_channels=t.value(e.num_channels,0),o.num_columns_per_channel=t.typedArray(e.num_columns_per_channel,Int32Array),o.embedding_dim_per_channel=t.typedArray(e.embedding_dim_per_channel,Int32Array),o}},$root.tflite.LSHProjectionType={UNKNOWN:0,SPARSE:1,DENSE:2},$root.tflite.LSHProjectionOptions=class{static decode(t,e){const o=new $root.tflite.LSHProjectionOptions;return o.type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.LSHProjectionOptions;return o.type=$root.tflite.LSHProjectionType[e.type],o}},$root.tflite.SVDFOptions=class{static decode(t,e){const o=new $root.tflite.SVDFOptions;return o.rank=t.int32_(e,4,0),o.fused_activation_function=t.int8_(e,6,0),o.asymmetric_quantize_inputs=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SVDFOptions;return o.rank=t.value(e.rank,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.RNNOptions=class{static decode(t,e){const o=new $root.tflite.RNNOptions;return o.fused_activation_function=t.int8_(e,4,0),o.asymmetric_quantize_inputs=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.RNNOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.SequenceRNNOptions=class{static decode(t,e){const o=new $root.tflite.SequenceRNNOptions;return o.time_major=t.bool_(e,4,!1),o.fused_activation_function=t.int8_(e,6,0),o.asymmetric_quantize_inputs=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SequenceRNNOptions;return o.time_major=t.value(e.time_major,!1),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.BidirectionalSequenceRNNOptions=class{static decode(t,e){const o=new $root.tflite.BidirectionalSequenceRNNOptions;return o.time_major=t.bool_(e,4,!1),o.fused_activation_function=t.int8_(e,6,0),o.merge_outputs=t.bool_(e,8,!1),o.asymmetric_quantize_inputs=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.BidirectionalSequenceRNNOptions;return o.time_major=t.value(e.time_major,!1),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.merge_outputs=t.value(e.merge_outputs,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.FullyConnectedOptionsWeightsFormat={DEFAULT:0,SHUFFLED4x16INT8:1},$root.tflite.FullyConnectedOptions=class{static decode(t,e){const o=new $root.tflite.FullyConnectedOptions;return o.fused_activation_function=t.int8_(e,4,0),o.weights_format=t.int8_(e,6,0),o.keep_num_dims=t.bool_(e,8,!1),o.asymmetric_quantize_inputs=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.FullyConnectedOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.weights_format=$root.tflite.FullyConnectedOptionsWeightsFormat[e.weights_format],o.keep_num_dims=t.value(e.keep_num_dims,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.SoftmaxOptions=class{static decode(t,e){const o=new $root.tflite.SoftmaxOptions;return o.beta=t.float32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SoftmaxOptions;return o.beta=t.value(e.beta,0),o}},$root.tflite.ConcatenationOptions=class{static decode(t,e){const o=new $root.tflite.ConcatenationOptions;return o.axis=t.int32_(e,4,0),o.fused_activation_function=t.int8_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.ConcatenationOptions;return o.axis=t.value(e.axis,0),o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.AddOptions=class{static decode(t,e){const o=new $root.tflite.AddOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.AddOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.MulOptions=class{static decode(t,e){const o=new $root.tflite.MulOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.MulOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.L2NormOptions=class{static decode(t,e){const o=new $root.tflite.L2NormOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.L2NormOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.LocalResponseNormalizationOptions=class{static decode(t,e){const o=new $root.tflite.LocalResponseNormalizationOptions;return o.radius=t.int32_(e,4,0),o.bias=t.float32_(e,6,0),o.alpha=t.float32_(e,8,0),o.beta=t.float32_(e,10,0),o}static decodeText(t,e){const o=new $root.tflite.LocalResponseNormalizationOptions;return o.radius=t.value(e.radius,0),o.bias=t.value(e.bias,0),o.alpha=t.value(e.alpha,0),o.beta=t.value(e.beta,0),o}},$root.tflite.LSTMKernelType={FULL:0,BASIC:1},$root.tflite.LSTMOptions=class{static decode(t,e){const o=new $root.tflite.LSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.kernel_type=t.int8_(e,10,0),o.asymmetric_quantize_inputs=t.bool_(e,12,!1),o}static decodeText(t,e){const o=new $root.tflite.LSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.kernel_type=$root.tflite.LSTMKernelType[e.kernel_type],o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.UnidirectionalSequenceLSTMOptions=class{static decode(t,e){const o=new $root.tflite.UnidirectionalSequenceLSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.time_major=t.bool_(e,10,!1),o.asymmetric_quantize_inputs=t.bool_(e,12,!1),o}static decodeText(t,e){const o=new $root.tflite.UnidirectionalSequenceLSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.time_major=t.value(e.time_major,!1),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.BidirectionalSequenceLSTMOptions=class{static decode(t,e){const o=new $root.tflite.BidirectionalSequenceLSTMOptions;return o.fused_activation_function=t.int8_(e,4,0),o.cell_clip=t.float32_(e,6,0),o.proj_clip=t.float32_(e,8,0),o.merge_outputs=t.bool_(e,10,!1),o.time_major=t.bool_(e,12,!0),o.asymmetric_quantize_inputs=t.bool_(e,14,!1),o}static decodeText(t,e){const o=new $root.tflite.BidirectionalSequenceLSTMOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o.cell_clip=t.value(e.cell_clip,0),o.proj_clip=t.value(e.proj_clip,0),o.merge_outputs=t.value(e.merge_outputs,!1),o.time_major=t.value(e.time_major,!0),o.asymmetric_quantize_inputs=t.value(e.asymmetric_quantize_inputs,!1),o}},$root.tflite.ResizeBilinearOptions=class{static decode(t,e){const o=new $root.tflite.ResizeBilinearOptions;return o.new_height=t.int32_(e,4,0),o.new_width=t.int32_(e,6,0),o.align_corners=t.bool_(e,8,!1),o.half_pixel_centers=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.ResizeBilinearOptions;return o.new_height=t.value(e.new_height,0),o.new_width=t.value(e.new_width,0),o.align_corners=t.value(e.align_corners,!1),o.half_pixel_centers=t.value(e.half_pixel_centers,!1),o}},$root.tflite.ResizeNearestNeighborOptions=class{static decode(t,e){const o=new $root.tflite.ResizeNearestNeighborOptions;return o.align_corners=t.bool_(e,4,!1),o.half_pixel_centers=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.ResizeNearestNeighborOptions;return o.align_corners=t.value(e.align_corners,!1),o.half_pixel_centers=t.value(e.half_pixel_centers,!1),o}},$root.tflite.CallOptions=class{static decode(t,e){const o=new $root.tflite.CallOptions;return o.subgraph=t.uint32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.CallOptions;return o.subgraph=t.value(e.subgraph,0),o}},$root.tflite.PadOptions=class{static decode(t,e){return new $root.tflite.PadOptions}static decodeText(t,e){return new $root.tflite.PadOptions}},$root.tflite.PadV2Options=class{static decode(t,e){return new $root.tflite.PadV2Options}static decodeText(t,e){return new $root.tflite.PadV2Options}},$root.tflite.ReshapeOptions=class{static decode(t,e){const o=new $root.tflite.ReshapeOptions;return o.new_shape=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.ReshapeOptions;return o.new_shape=t.typedArray(e.new_shape,Int32Array),o}},$root.tflite.SpaceToBatchNDOptions=class{static decode(t,e){return new $root.tflite.SpaceToBatchNDOptions}static decodeText(t,e){return new $root.tflite.SpaceToBatchNDOptions}},$root.tflite.BatchToSpaceNDOptions=class{static decode(t,e){return new $root.tflite.BatchToSpaceNDOptions}static decodeText(t,e){return new $root.tflite.BatchToSpaceNDOptions}},$root.tflite.SkipGramOptions=class{static decode(t,e){const o=new $root.tflite.SkipGramOptions;return o.ngram_size=t.int32_(e,4,0),o.max_skip_size=t.int32_(e,6,0),o.include_all_ngrams=t.bool_(e,8,!1),o}static decodeText(t,e){const o=new $root.tflite.SkipGramOptions;return o.ngram_size=t.value(e.ngram_size,0),o.max_skip_size=t.value(e.max_skip_size,0),o.include_all_ngrams=t.value(e.include_all_ngrams,!1),o}},$root.tflite.SpaceToDepthOptions=class{static decode(t,e){const o=new $root.tflite.SpaceToDepthOptions;return o.block_size=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SpaceToDepthOptions;return o.block_size=t.value(e.block_size,0),o}},$root.tflite.DepthToSpaceOptions=class{static decode(t,e){const o=new $root.tflite.DepthToSpaceOptions;return o.block_size=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.DepthToSpaceOptions;return o.block_size=t.value(e.block_size,0),o}},$root.tflite.SubOptions=class{static decode(t,e){const o=new $root.tflite.SubOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SubOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.DivOptions=class{static decode(t,e){const o=new $root.tflite.DivOptions;return o.fused_activation_function=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.DivOptions;return o.fused_activation_function=$root.tflite.ActivationFunctionType[e.fused_activation_function],o}},$root.tflite.TopKV2Options=class{static decode(t,e){return new $root.tflite.TopKV2Options}static decodeText(t,e){return new $root.tflite.TopKV2Options}},$root.tflite.CombinerType={SUM:0,MEAN:1,SQRTN:2},$root.tflite.EmbeddingLookupSparseOptions=class{static decode(t,e){const o=new $root.tflite.EmbeddingLookupSparseOptions;return o.combiner=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.EmbeddingLookupSparseOptions;return o.combiner=$root.tflite.CombinerType[e.combiner],o}},$root.tflite.GatherOptions=class{static decode(t,e){const o=new $root.tflite.GatherOptions;return o.axis=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.GatherOptions;return o.axis=t.value(e.axis,0),o}},$root.tflite.TransposeOptions=class{static decode(t,e){return new $root.tflite.TransposeOptions}static decodeText(t,e){return new $root.tflite.TransposeOptions}},$root.tflite.ExpOptions=class{static decode(t,e){return new $root.tflite.ExpOptions}static decodeText(t,e){return new $root.tflite.ExpOptions}},$root.tflite.CosOptions=class{static decode(t,e){return new $root.tflite.CosOptions}static decodeText(t,e){return new $root.tflite.CosOptions}},$root.tflite.ReducerOptions=class{static decode(t,e){const o=new $root.tflite.ReducerOptions;return o.keep_dims=t.bool_(e,4,!1),o}static decodeText(t,e){const o=new $root.tflite.ReducerOptions;return o.keep_dims=t.value(e.keep_dims,!1),o}},$root.tflite.SqueezeOptions=class{static decode(t,e){const o=new $root.tflite.SqueezeOptions;return o.squeeze_dims=t.typedArray(e,4,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.SqueezeOptions;return o.squeeze_dims=t.typedArray(e.squeeze_dims,Int32Array),o}},$root.tflite.SplitOptions=class{static decode(t,e){const o=new $root.tflite.SplitOptions;return o.num_splits=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SplitOptions;return o.num_splits=t.value(e.num_splits,0),o}},$root.tflite.SplitVOptions=class{static decode(t,e){const o=new $root.tflite.SplitVOptions;return o.num_splits=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.SplitVOptions;return o.num_splits=t.value(e.num_splits,0),o}},$root.tflite.StridedSliceOptions=class{static decode(t,e){const o=new $root.tflite.StridedSliceOptions;return o.begin_mask=t.int32_(e,4,0),o.end_mask=t.int32_(e,6,0),o.ellipsis_mask=t.int32_(e,8,0),o.new_axis_mask=t.int32_(e,10,0),o.shrink_axis_mask=t.int32_(e,12,0),o}static decodeText(t,e){const o=new $root.tflite.StridedSliceOptions;return o.begin_mask=t.value(e.begin_mask,0),o.end_mask=t.value(e.end_mask,0),o.ellipsis_mask=t.value(e.ellipsis_mask,0),o.new_axis_mask=t.value(e.new_axis_mask,0),o.shrink_axis_mask=t.value(e.shrink_axis_mask,0),o}},$root.tflite.LogSoftmaxOptions=class{static decode(t,e){return new $root.tflite.LogSoftmaxOptions}static decodeText(t,e){return new $root.tflite.LogSoftmaxOptions}},$root.tflite.CastOptions=class{static decode(t,e){const o=new $root.tflite.CastOptions;return o.in_data_type=t.int8_(e,4,0),o.out_data_type=t.int8_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.CastOptions;return o.in_data_type=$root.tflite.TensorType[e.in_data_type],o.out_data_type=$root.tflite.TensorType[e.out_data_type],o}},$root.tflite.DequantizeOptions=class{static decode(t,e){return new $root.tflite.DequantizeOptions}static decodeText(t,e){return new $root.tflite.DequantizeOptions}},$root.tflite.MaximumMinimumOptions=class{static decode(t,e){return new $root.tflite.MaximumMinimumOptions}static decodeText(t,e){return new $root.tflite.MaximumMinimumOptions}},$root.tflite.TileOptions=class{static decode(t,e){return new $root.tflite.TileOptions}static decodeText(t,e){return new $root.tflite.TileOptions}},$root.tflite.ArgMaxOptions=class{static decode(t,e){const o=new $root.tflite.ArgMaxOptions;return o.output_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ArgMaxOptions;return o.output_type=$root.tflite.TensorType[e.output_type],o}},$root.tflite.ArgMinOptions=class{static decode(t,e){const o=new $root.tflite.ArgMinOptions;return o.output_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ArgMinOptions;return o.output_type=$root.tflite.TensorType[e.output_type],o}},$root.tflite.GreaterOptions=class{static decode(t,e){return new $root.tflite.GreaterOptions}static decodeText(t,e){return new $root.tflite.GreaterOptions}},$root.tflite.GreaterEqualOptions=class{static decode(t,e){return new $root.tflite.GreaterEqualOptions}static decodeText(t,e){return new $root.tflite.GreaterEqualOptions}},$root.tflite.LessOptions=class{static decode(t,e){return new $root.tflite.LessOptions}static decodeText(t,e){return new $root.tflite.LessOptions}},$root.tflite.LessEqualOptions=class{static decode(t,e){return new $root.tflite.LessEqualOptions}static decodeText(t,e){return new $root.tflite.LessEqualOptions}},$root.tflite.NegOptions=class{static decode(t,e){return new $root.tflite.NegOptions}static decodeText(t,e){return new $root.tflite.NegOptions}},$root.tflite.SelectOptions=class{static decode(t,e){return new $root.tflite.SelectOptions}static decodeText(t,e){return new $root.tflite.SelectOptions}},$root.tflite.SliceOptions=class{static decode(t,e){return new $root.tflite.SliceOptions}static decodeText(t,e){return new $root.tflite.SliceOptions}},$root.tflite.TransposeConvOptions=class{static decode(t,e){const o=new $root.tflite.TransposeConvOptions;return o.padding=t.int8_(e,4,0),o.stride_w=t.int32_(e,6,0),o.stride_h=t.int32_(e,8,0),o}static decodeText(t,e){const o=new $root.tflite.TransposeConvOptions;return o.padding=$root.tflite.Padding[e.padding],o.stride_w=t.value(e.stride_w,0),o.stride_h=t.value(e.stride_h,0),o}},$root.tflite.ExpandDimsOptions=class{static decode(t,e){return new $root.tflite.ExpandDimsOptions}static decodeText(t,e){return new $root.tflite.ExpandDimsOptions}},$root.tflite.SparseToDenseOptions=class{static decode(t,e){const o=new $root.tflite.SparseToDenseOptions;return o.validate_indices=t.bool_(e,4,!1),o}static decodeText(t,e){const o=new $root.tflite.SparseToDenseOptions;return o.validate_indices=t.value(e.validate_indices,!1),o}},$root.tflite.EqualOptions=class{static decode(t,e){return new $root.tflite.EqualOptions}static decodeText(t,e){return new $root.tflite.EqualOptions}},$root.tflite.NotEqualOptions=class{static decode(t,e){return new $root.tflite.NotEqualOptions}static decodeText(t,e){return new $root.tflite.NotEqualOptions}},$root.tflite.ShapeOptions=class{static decode(t,e){const o=new $root.tflite.ShapeOptions;return o.out_type=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.ShapeOptions;return o.out_type=$root.tflite.TensorType[e.out_type],o}},$root.tflite.RankOptions=class{static decode(t,e){return new $root.tflite.RankOptions}static decodeText(t,e){return new $root.tflite.RankOptions}},$root.tflite.PowOptions=class{static decode(t,e){return new $root.tflite.PowOptions}static decodeText(t,e){return new $root.tflite.PowOptions}},$root.tflite.FakeQuantOptions=class{static decode(t,e){const o=new $root.tflite.FakeQuantOptions;return o.min=t.float32_(e,4,0),o.max=t.float32_(e,6,0),o.num_bits=t.int32_(e,8,0),o.narrow_range=t.bool_(e,10,!1),o}static decodeText(t,e){const o=new $root.tflite.FakeQuantOptions;return o.min=t.value(e.min,0),o.max=t.value(e.max,0),o.num_bits=t.value(e.num_bits,0),o.narrow_range=t.value(e.narrow_range,!1),o}},$root.tflite.PackOptions=class{static decode(t,e){const o=new $root.tflite.PackOptions;return o.values_count=t.int32_(e,4,0),o.axis=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.PackOptions;return o.values_count=t.value(e.values_count,0),o.axis=t.value(e.axis,0),o}},$root.tflite.LogicalOrOptions=class{static decode(t,e){return new $root.tflite.LogicalOrOptions}static decodeText(t,e){return new $root.tflite.LogicalOrOptions}},$root.tflite.OneHotOptions=class{static decode(t,e){const o=new $root.tflite.OneHotOptions;return o.axis=t.int32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.OneHotOptions;return o.axis=t.value(e.axis,0),o}},$root.tflite.AbsOptions=class{static decode(t,e){return new $root.tflite.AbsOptions}static decodeText(t,e){return new $root.tflite.AbsOptions}},$root.tflite.HardSwishOptions=class{static decode(t,e){return new $root.tflite.HardSwishOptions}static decodeText(t,e){return new $root.tflite.HardSwishOptions}},$root.tflite.LogicalAndOptions=class{static decode(t,e){return new $root.tflite.LogicalAndOptions}static decodeText(t,e){return new $root.tflite.LogicalAndOptions}},$root.tflite.LogicalNotOptions=class{static decode(t,e){return new $root.tflite.LogicalNotOptions}static decodeText(t,e){return new $root.tflite.LogicalNotOptions}},$root.tflite.UnpackOptions=class{static decode(t,e){const o=new $root.tflite.UnpackOptions;return o.num=t.int32_(e,4,0),o.axis=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.UnpackOptions;return o.num=t.value(e.num,0),o.axis=t.value(e.axis,0),o}},$root.tflite.FloorDivOptions=class{static decode(t,e){return new $root.tflite.FloorDivOptions}static decodeText(t,e){return new $root.tflite.FloorDivOptions}},$root.tflite.SquareOptions=class{static decode(t,e){return new $root.tflite.SquareOptions}static decodeText(t,e){return new $root.tflite.SquareOptions}},$root.tflite.ZerosLikeOptions=class{static decode(t,e){return new $root.tflite.ZerosLikeOptions}static decodeText(t,e){return new $root.tflite.ZerosLikeOptions}},$root.tflite.FillOptions=class{static decode(t,e){return new $root.tflite.FillOptions}static decodeText(t,e){return new $root.tflite.FillOptions}},$root.tflite.FloorModOptions=class{static decode(t,e){return new $root.tflite.FloorModOptions}static decodeText(t,e){return new $root.tflite.FloorModOptions}},$root.tflite.RangeOptions=class{static decode(t,e){return new $root.tflite.RangeOptions}static decodeText(t,e){return new $root.tflite.RangeOptions}},$root.tflite.LeakyReluOptions=class{static decode(t,e){const o=new $root.tflite.LeakyReluOptions;return o.alpha=t.float32_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.LeakyReluOptions;return o.alpha=t.value(e.alpha,0),o}},$root.tflite.SquaredDifferenceOptions=class{static decode(t,e){return new $root.tflite.SquaredDifferenceOptions}static decodeText(t,e){return new $root.tflite.SquaredDifferenceOptions}},$root.tflite.MirrorPadMode={REFLECT:0,SYMMETRIC:1},$root.tflite.MirrorPadOptions=class{static decode(t,e){const o=new $root.tflite.MirrorPadOptions;return o.mode=t.int8_(e,4,0),o}static decodeText(t,e){const o=new $root.tflite.MirrorPadOptions;return o.mode=$root.tflite.MirrorPadMode[e.mode],o}},$root.tflite.UniqueOptions=class{static decode(t,e){const o=new $root.tflite.UniqueOptions;return o.idx_out_type=t.int8_(e,4,2),o}static decodeText(t,e){const o=new $root.tflite.UniqueOptions;return o.idx_out_type=$root.tflite.TensorType[e.idx_out_type],o}},$root.tflite.ReverseV2Options=class{static decode(t,e){return new $root.tflite.ReverseV2Options}static decodeText(t,e){return new $root.tflite.ReverseV2Options}},$root.tflite.AddNOptions=class{static decode(t,e){return new $root.tflite.AddNOptions}static decodeText(t,e){return new $root.tflite.AddNOptions}},$root.tflite.GatherNdOptions=class{static decode(t,e){return new $root.tflite.GatherNdOptions}static decodeText(t,e){return new $root.tflite.GatherNdOptions}},$root.tflite.WhereOptions=class{static decode(t,e){return new $root.tflite.WhereOptions}static decodeText(t,e){return new $root.tflite.WhereOptions}},$root.tflite.ReverseSequenceOptions=class{static decode(t,e){const o=new $root.tflite.ReverseSequenceOptions;return o.seq_dim=t.int32_(e,4,0),o.batch_dim=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.ReverseSequenceOptions;return o.seq_dim=t.value(e.seq_dim,0),o.batch_dim=t.value(e.batch_dim,0),o}},$root.tflite.MatrixDiagOptions=class{static decode(t,e){return new $root.tflite.MatrixDiagOptions}static decodeText(t,e){return new $root.tflite.MatrixDiagOptions}},$root.tflite.QuantizeOptions=class{static decode(t,e){return new $root.tflite.QuantizeOptions}static decodeText(t,e){return new $root.tflite.QuantizeOptions}},$root.tflite.MatrixSetDiagOptions=class{static decode(t,e){return new $root.tflite.MatrixSetDiagOptions}static decodeText(t,e){return new $root.tflite.MatrixSetDiagOptions}},$root.tflite.IfOptions=class{static decode(t,e){const o=new $root.tflite.IfOptions;return o.then_subgraph_index=t.int32_(e,4,0),o.else_subgraph_index=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.IfOptions;return o.then_subgraph_index=t.value(e.then_subgraph_index,0),o.else_subgraph_index=t.value(e.else_subgraph_index,0),o}},$root.tflite.WhileOptions=class{static decode(t,e){const o=new $root.tflite.WhileOptions;return o.cond_subgraph_index=t.int32_(e,4,0),o.body_subgraph_index=t.int32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.WhileOptions;return o.cond_subgraph_index=t.value(e.cond_subgraph_index,0),o.body_subgraph_index=t.value(e.body_subgraph_index,0),o}},$root.tflite.NonMaxSuppressionV4Options=class{static decode(t,e){return new $root.tflite.NonMaxSuppressionV4Options}static decodeText(t,e){return new $root.tflite.NonMaxSuppressionV4Options}},$root.tflite.NonMaxSuppressionV5Options=class{static decode(t,e){return new $root.tflite.NonMaxSuppressionV5Options}static decodeText(t,e){return new $root.tflite.NonMaxSuppressionV5Options}},$root.tflite.ScatterNdOptions=class{static decode(t,e){return new $root.tflite.ScatterNdOptions}static decodeText(t,e){return new $root.tflite.ScatterNdOptions}},$root.tflite.SelectV2Options=class{static decode(t,e){return new $root.tflite.SelectV2Options}static decodeText(t,e){return new $root.tflite.SelectV2Options}},$root.tflite.DensifyOptions=class{static decode(t,e){return new $root.tflite.DensifyOptions}static decodeText(t,e){return new $root.tflite.DensifyOptions}},$root.tflite.SegmentSumOptions=class{static decode(t,e){return new $root.tflite.SegmentSumOptions}static decodeText(t,e){return new $root.tflite.SegmentSumOptions}},$root.tflite.BatchMatMulOptions=class{static decode(t,e){const o=new $root.tflite.BatchMatMulOptions;return o.adj_x=t.bool_(e,4,!1),o.adj_y=t.bool_(e,6,!1),o}static decodeText(t,e){const o=new $root.tflite.BatchMatMulOptions;return o.adj_x=t.value(e.adj_x,!1),o.adj_y=t.value(e.adj_y,!1),o}},$root.tflite.OperatorCode=class{static decode(t,e){const o=new $root.tflite.OperatorCode;return o.builtin_code=t.int8_(e,4,0),o.custom_code=t.string_(e,6,null),o.version=t.int32_(e,8,1),o}static decodeText(t,e){const o=new $root.tflite.OperatorCode;return o.builtin_code=$root.tflite.BuiltinOperator[e.builtin_code],o.custom_code=t.value(e.custom_code,null),o.version=t.value(e.version,1),o}},$root.tflite.CustomOptionsFormat={FLEXBUFFERS:0},$root.tflite.Operator=class{static decode(t,e){const o=new $root.tflite.Operator;return o.opcode_index=t.uint32_(e,4,0),o.inputs=t.typedArray(e,6,Int32Array),o.outputs=t.typedArray(e,8,Int32Array),o.builtin_options=t.union(e,10,$root.tflite.BuiltinOptions.decode),o.custom_options=t.typedArray(e,14,Uint8Array),o.custom_options_format=t.int8_(e,16,0),o.mutating_variable_inputs=t.bools_(e,18),o.intermediates=t.typedArray(e,20,Int32Array),o}static decodeText(t,e){const o=new $root.tflite.Operator;return o.opcode_index=t.value(e.opcode_index,0),o.inputs=t.typedArray(e.inputs,Int32Array),o.outputs=t.typedArray(e.outputs,Int32Array),o.builtin_options=$root.tflite.BuiltinOptions.decodeText(t,e.builtin_options,e.builtin_options_type),o.custom_options=t.typedArray(e.custom_options,Uint8Array),o.custom_options_format=$root.tflite.CustomOptionsFormat[e.custom_options_format],o.mutating_variable_inputs=t.array(e.mutating_variable_inputs),o.intermediates=t.typedArray(e.intermediates,Int32Array),o}},$root.tflite.SubGraph=class{static decode(t,e){const o=new $root.tflite.SubGraph;return o.tensors=t.tableArray(e,4,$root.tflite.Tensor.decode),o.inputs=t.typedArray(e,6,Int32Array),o.outputs=t.typedArray(e,8,Int32Array),o.operators=t.tableArray(e,10,$root.tflite.Operator.decode),o.name=t.string_(e,12,null),o}static decodeText(t,e){const o=new $root.tflite.SubGraph;return o.tensors=t.objectArray(e.tensors,$root.tflite.Tensor.decodeText),o.inputs=t.typedArray(e.inputs,Int32Array),o.outputs=t.typedArray(e.outputs,Int32Array),o.operators=t.objectArray(e.operators,$root.tflite.Operator.decodeText),o.name=t.value(e.name,null),o}},$root.tflite.Buffer=class{static decode(t,e){const o=new $root.tflite.Buffer;return o.data=t.typedArray(e,4,Uint8Array),o}static decodeText(t,e){const o=new $root.tflite.Buffer;return o.data=t.typedArray(e.data,Uint8Array),o}},$root.tflite.Metadata=class{static decode(t,e){const o=new $root.tflite.Metadata;return o.name=t.string_(e,4,null),o.buffer=t.uint32_(e,6,0),o}static decodeText(t,e){const o=new $root.tflite.Metadata;return o.name=t.value(e.name,null),o.buffer=t.value(e.buffer,0),o}},$root.tflite.Model=class{static identifier(t){return t.identifier("TFL3")}static create(t){return $root.tflite.Model.decode(t,t.root)}static createText(t){return $root.tflite.Model.decodeText(t,t.root)}static decode(t,e){const o=new $root.tflite.Model;return o.version=t.uint32_(e,4,0),o.operator_codes=t.tableArray(e,6,$root.tflite.OperatorCode.decode),o.subgraphs=t.tableArray(e,8,$root.tflite.SubGraph.decode),o.description=t.string_(e,10,null),o.buffers=t.tableArray(e,12,$root.tflite.Buffer.decode),o.metadata_buffer=t.typedArray(e,14,Int32Array),o.metadata=t.tableArray(e,16,$root.tflite.Metadata.decode),o}static decodeText(t,e){const o=new $root.tflite.Model;return o.version=t.value(e.version,0),o.operator_codes=t.objectArray(e.operator_codes,$root.tflite.OperatorCode.decodeText),o.subgraphs=t.objectArray(e.subgraphs,$root.tflite.SubGraph.decodeText),o.description=t.value(e.description,null),o.buffers=t.objectArray(e.buffers,$root.tflite.Buffer.decodeText),o.metadata_buffer=t.typedArray(e.metadata_buffer,Int32Array),o.metadata=t.objectArray(e.metadata,$root.tflite.Metadata.decodeText),o}},$root.tflite=$root.tflite||{},$root.tflite.AssociatedFileType={UNKNOWN:0,DESCRIPTIONS:1,TENSOR_AXIS_LABELS:2,TENSOR_VALUE_LABELS:3,TENSOR_AXIS_SCORE_CALIBRATION:4,VOCABULARY:5},$root.tflite.AssociatedFile=class{static decode(t,e){const o=new $root.tflite.AssociatedFile;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.type=t.int8_(e,8,0),o.locale=t.string_(e,10,null),o}},$root.tflite.FeatureProperties=class{static decode(t,e){return new $root.tflite.FeatureProperties}},$root.tflite.ColorSpaceType={UNKNOWN:0,RGB:1,GRAYSCALE:2},$root.tflite.ImageSize=class{static decode(t,e){const o=new $root.tflite.ImageSize;return o.width=t.uint32_(e,4,0),o.height=t.uint32_(e,6,0),o}},$root.tflite.ImageProperties=class{static decode(t,e){const o=new $root.tflite.ImageProperties;return o.color_space=t.int8_(e,4,0),o.default_size=t.table(e,6,$root.tflite.ImageSize.decode),o}},$root.tflite.BoundingBoxType={UNKNOWN:0,BOUNDARIES:1,UPPER_LEFT:2,CENTER:3},$root.tflite.CoordinateType={RATIO:0,PIXEL:1},$root.tflite.BoundingBoxProperties=class{static decode(t,e){const o=new $root.tflite.BoundingBoxProperties;return o.index=t.typedArray(e,4,Uint32Array),o.type=t.int8_(e,6,0),o.coordinate_type=t.int8_(e,8,0),o}},$root.tflite.ContentProperties=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.FeatureProperties.decode(t,e);case 2:return $root.tflite.ImageProperties.decode(t,e);case 3:return $root.tflite.BoundingBoxProperties.decode(t,e)}}static decodeText(t,e,o){switch(o){case"FeatureProperties":return $root.tflite.FeatureProperties.decodeText(t,e);case"ImageProperties":return $root.tflite.ImageProperties.decodeText(t,e);case"BoundingBoxProperties":return $root.tflite.BoundingBoxProperties.decodeText(t,e)}}},$root.tflite.ValueRange=class{static decode(t,e){const o=new $root.tflite.ValueRange;return o.min=t.int32_(e,4,0),o.max=t.int32_(e,6,0),o}},$root.tflite.Content=class{static decode(t,e){const o=new $root.tflite.Content;return o.content_properties=t.union(e,4,$root.tflite.ContentProperties.decode),o.range=t.table(e,8,$root.tflite.ValueRange.decode),o}},$root.tflite.NormalizationOptions=class{static decode(t,e){const o=new $root.tflite.NormalizationOptions;return o.mean=t.typedArray(e,4,Float32Array),o.std=t.typedArray(e,6,Float32Array),o}},$root.tflite.ScoreTransformationType={IDENTITY:0,LOG:1,INVERSE_LOGISTIC:2},$root.tflite.ScoreCalibrationOptions=class{static decode(t,e){const o=new $root.tflite.ScoreCalibrationOptions;return o.score_transformation=t.int8_(e,4,0),o.default_score=t.float32_(e,6,0),o}},$root.tflite.ScoreThresholdingOptions=class{static decode(t,e){const o=new $root.tflite.ScoreThresholdingOptions;return o.global_score_threshold=t.float32_(e,4,0),o}},$root.tflite.BertTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.BertTokenizerOptions;return o.vocab_file=t.tableArray(e,4,$root.tflite.AssociatedFile.decode),o}},$root.tflite.SentencePieceTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.SentencePieceTokenizerOptions;return o.sentencePiece_model=t.tableArray(e,4,$root.tflite.AssociatedFile.decode),o.vocab_file=t.tableArray(e,6,$root.tflite.AssociatedFile.decode),o}},$root.tflite.RegexTokenizerOptions=class{static decode(t,e){const o=new $root.tflite.RegexTokenizerOptions;return o.delim_regex_pattern=t.string_(e,4,null),o.vocab_file=t.tableArray(e,6,$root.tflite.AssociatedFile.decode),o}},$root.tflite.ProcessUnitOptions=class{static decode(t,e,o){switch(o){case 1:return $root.tflite.NormalizationOptions.decode(t,e);case 2:return $root.tflite.ScoreCalibrationOptions.decode(t,e);case 3:return $root.tflite.ScoreThresholdingOptions.decode(t,e);case 4:return $root.tflite.BertTokenizerOptions.decode(t,e);case 5:return $root.tflite.SentencePieceTokenizerOptions.decode(t,e);case 6:return $root.tflite.RegexTokenizerOptions.decode(t,e)}}static decodeText(t,e,o){switch(o){case"NormalizationOptions":return $root.tflite.NormalizationOptions.decodeText(t,e);case"ScoreCalibrationOptions":return $root.tflite.ScoreCalibrationOptions.decodeText(t,e);case"ScoreThresholdingOptions":return $root.tflite.ScoreThresholdingOptions.decodeText(t,e);case"BertTokenizerOptions":return $root.tflite.BertTokenizerOptions.decodeText(t,e);case"SentencePieceTokenizerOptions":return $root.tflite.SentencePieceTokenizerOptions.decodeText(t,e);case"RegexTokenizerOptions":return $root.tflite.RegexTokenizerOptions.decodeText(t,e)}}},$root.tflite.ProcessUnit=class{static decode(t,e){const o=new $root.tflite.ProcessUnit;return o.options=t.union(e,4,$root.tflite.ProcessUnitOptions.decode),o}},$root.tflite.Stats=class{static decode(t,e){const o=new $root.tflite.Stats;return o.max=t.typedArray(e,4,Float32Array),o.min=t.typedArray(e,6,Float32Array),o}},$root.tflite.TensorGroup=class{static decode(t,e){const o=new $root.tflite.TensorGroup;return o.name=t.string_(e,4,null),o.tensor_names=t.strings_(e,6),o}},$root.tflite.TensorMetadata=class{static decode(t,e){const o=new $root.tflite.TensorMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.dimension_names=t.strings_(e,8),o.content=t.table(e,10,$root.tflite.Content.decode),o.process_units=t.tableArray(e,12,$root.tflite.ProcessUnit.decode),o.stats=t.table(e,14,$root.tflite.Stats.decode),o.associated_files=t.tableArray(e,16,$root.tflite.AssociatedFile.decode),o}},$root.tflite.SubGraphMetadata=class{static decode(t,e){const o=new $root.tflite.SubGraphMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.input_tensor_metadata=t.tableArray(e,8,$root.tflite.TensorMetadata.decode),o.output_tensor_metadata=t.tableArray(e,10,$root.tflite.TensorMetadata.decode),o.associated_files=t.tableArray(e,12,$root.tflite.AssociatedFile.decode),o.input_process_units=t.tableArray(e,14,$root.tflite.ProcessUnit.decode),o.output_process_units=t.tableArray(e,16,$root.tflite.ProcessUnit.decode),o.input_tensor_groups=t.tableArray(e,18,$root.tflite.TensorGroup.decode),o.output_tensor_groups=t.tableArray(e,20,$root.tflite.TensorGroup.decode),o}},$root.tflite.ModelMetadata=class{static identifier(t){return t.identifier("M001")}static create(t){return $root.tflite.ModelMetadata.decode(t,t.root)}static decode(t,e){const o=new $root.tflite.ModelMetadata;return o.name=t.string_(e,4,null),o.description=t.string_(e,6,null),o.version=t.string_(e,8,null),o.subgraph_metadata=t.tableArray(e,10,$root.tflite.SubGraphMetadata.decode),o.author=t.string_(e,12,null),o.license=t.string_(e,14,null),o.associated_files=t.tableArray(e,16,$root.tflite.AssociatedFile.decode),o.min_parser_version=t.string_(e,18,null),o}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite.js new file mode 100644 index 0000000000000000000000000000000000000000..fcf752f84c7708fed770a3b78a553d4008c1df06 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tflite.js @@ -0,0 +1 @@ +var tflite=tflite||{},base=base||require("./base"),flatbuffers=flatbuffers||require("./flatbuffers"),long=long||{Long:require("long")};tflite.ModelFactory=class{match(t){const e=t.identifier.split(".").pop().toLowerCase();if(-1!==["tflite","lite","tfl","bin","pb","model","tmfile","h5"].indexOf(e)){const e=t.buffer,i="TFL3";if(e&&e.length>8&&e.subarray(4,8).every(((t,e)=>t===i.charCodeAt(e))))return!0}if("json"===e){const e=t.text;if(-1!==e.indexOf('"subgraphs"',0)&&-1!==e.indexOf('"operator_codes"',0))return!0}return!1}open(t,e){return e.require("./tflite-schema").then((()=>(tflite.schema=flatbuffers.get("tflite").tflite,tflite.Metadata.open(e).then((e=>{const i=t.identifier;try{switch(i.split(".").pop().toLowerCase()){default:{const i=new flatbuffers.Reader(t.buffer);if(!tflite.schema.Model.identifier(i))throw new tflite.Error("File format is not tflite.Model.");const n=tflite.schema.Model.create(i);return new tflite.Model(e,n)}case"json":{const i=new flatbuffers.TextReader(t.text),n=tflite.schema.Model.createText(i);return new tflite.Model(e,n)}}}catch(t){const e=t&&t.message?t.message:t.toString();throw new tflite.Error(e.replace(/\.$/,"")+" in '"+i+"'.")}})))))}},tflite.Model=class{constructor(t,e){this._graphs=[],this._format="TensorFlow Lite",this._format=this._format+" v"+e.version.toString(),this._description=e.description||"";const i=[],n={};for(const t of Object.keys(tflite.schema.BuiltinOperator))n[tflite.schema.BuiltinOperator[t]]=tflite.Utility.type(t);for(let t=0;t1?n.toString():"",l=r&&n0||s?new tflite.Tensor(t,i,n,s):null;r.push(new tflite.Argument(t,i,u)),o.push(i.name)}const l=e.operators;for(let i=0;i{if(e){const i=e.description;i&&(t.description=i);const n=e.content;if(t.type&&n){let e=null;const i=n.content_properties;if(i instanceof tflite.schema.FeatureProperties)e="Feature";else if(i instanceof tflite.schema.ImageProperties)switch(e="Image",i.color_space){case 1:e+="(RGB)";break;case 2:e+="(Grayscale)"}else i instanceof tflite.schema.BoundingBoxProperties&&(e="BoundingBox");e&&(t.type.denotation=e)}}},h=e.inputs;for(let t=0;t0){const i=t.attribute(this.type,"custom");this._attributes.push(new tflite.Attribute(i,"custom",Array.from(e.custom_options)))}const l=e.builtin_options;if(l)for(const e of Object.keys(l)){const i=l[e];if("fused_activation_function"===e&&0!==i){const e={1:"Relu",2:"ReluN1To1",3:"Relu6",4:"Tanh",5:"SignBit"};if(!e[i])throw new tflite.Error("Unknown activation funtion index '"+JSON.stringify(i)+"'.");const n=e[i];this._chain=[new tflite.Node(t,null,{name:n},null,[])]}const n=t.attribute(this.type,e);this._attributes.push(new tflite.Attribute(n,e,i))}}}get type(){return this._type.name}get name(){return""}get location(){return this._location}get domain(){return null}get metadata(){return this._type.custom?{name:this.type,category:"custom"}:this._metadata.type(this.type)}get group(){return null}get inputs(){return this._inputs}get outputs(){return this._outputs}get chain(){return this._chain}get attributes(){return this._attributes}},tflite.Attribute=class{constructor(t,e,i){if(this._type=null,this._name=e,this._value=i,"fused_activation_function"==this._name&&(this._visible=!1),t){if(t.type&&(this._type=t.type),this._type)switch(this._type){case"shape":this._value=new tflite.TensorShape(i);break;case"TensorType":this._value=tflite.Utility.dataType(this._value);break;default:this._value=tflite.Utility.enum(this._type,this._value)}Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible?this._visible=!1:Object.prototype.hasOwnProperty.call(t,"default")&&("function"==typeof(i=this._value)&&(i=i()),i==t.default&&(this._visible=!1))}}get name(){return this._name}get type(){return this._type}get value(){return this._value}get visible(){return 0!=this._visible}},tflite.Parameter=class{constructor(t,e,i){this._name=t,this._visible=e,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},tflite.Argument=class{constructor(t,e,i){this._location=t.toString(),this._type=new tflite.TensorType(e),this._initializer=i,this._name=e.name;const n=e.quantization;if(n){let t="q";const e=1==n.scale.length?n.scale[0]:0,i=1==n.zero_point.length?n.zero_point[0]:0;0==e&&0==i||(t=e.toString()+" * "+(0==i?"q":"(q - "+i.toString()+")")),1==n.min.length&&(t=n.min[0].toString()+" ≤ "+t),1==n.max.length&&(t=t+" ≤ "+n.max[0].toString()),"q"!=t&&(this._quantization=t)}}get name(){return this._name}get location(){return this._location}get type(){return this._type}get quantization(){return this._quantization}set description(t){this._description=t}get description(){return this._description}get initializer(){return this._initializer}},tflite.Tensor=class{constructor(t,e,i,n){this._location=t.toString(),this._type=new tflite.TensorType(e),this._is_variable=n,this._name=e.name,this._data=i.data.slice(0)}get kind(){return this._is_variable?"Variable":""}get name(){return this._name}get location(){return this._location}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};if(null==this._data||0===this._data.length)return t.state="Tensor data is empty.",t;if(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),"string"==this._type.dataType){let e=0;const i=t.data.getInt32(0,!0);e+=4;const n=[];for(let s=0;st.limit)return s.push("..."),s;switch(t.dataType){case"uint8":s.push(t.data.getUint8(t.index)),t.index+=1,t.count++;break;case"int8":s.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":s.push(t.data.getInt16(t.index)),t.index+=2,t.count++;break;case"int32":s.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":s.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float64":s.push(t.data.getFloat64(t.index,!0)),t.index+=8,t.count++;break;case"string":s.push(t.data[t.index++]),t.count++}}else for(let i=0;it.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},tflite.TensorType=class{constructor(t){this._dataType=tflite.Utility.dataType(t.type),this._shape=new tflite.TensorShape(Array.from(t.shape||[]))}get dataType(){return this._dataType}get shape(){return this._shape}set denotation(t){this._denotation=t}get denotation(){return this._denotation}toString(){return this.dataType+this._shape.toString()}},tflite.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},tflite.Metadata=class{static open(t){return tflite.Metadata._metadata?Promise.resolve(tflite.Metadata._metadata):t.request(null,"tflite-metadata.json","utf-8").then((t=>(tflite.Metadata._metadata=new tflite.Metadata(t),tflite.Metadata._metadata))).catch((()=>(tflite.Metadata._metadata=new tflite.Metadata(null),tflite.Metadata._metadata)))}constructor(t){if(this._map=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.schema.name=t.name,this._map.set(t.name,t.schema)}}type(t){return this._map.has(t)?this._map.get(t):null}attribute(t,e){const i=this.type(t);if(i){let t=i.attributeMap;if(!t){if(t={},i.attributes)for(const e of i.attributes)t[e.name]=e;i.attributeMap=t}const n=t[e];if(n)return n}return null}},tflite.Utility=class{static dataType(t){if(!tflite.Utility._tensorTypeMap){tflite.Utility._tensorTypeMap=new Map;for(const t of Object.keys(tflite.schema.TensorType))tflite.Utility._tensorTypeMap.set(tflite.schema.TensorType[t],t.toLowerCase());tflite.Utility._tensorTypeMap.set(6,"boolean")}return tflite.Utility._tensorTypeMap.has(t)?tflite.Utility._tensorTypeMap.get(t):"?"}static enum(t,e){const i=t&&tflite.schema?tflite.schema[t]:void 0;if(i){if(tflite.Utility._enumKeyMap=tflite.Utility._enumKeyMap||new Map,!tflite.Utility._enumKeyMap.has(t)){const e=new Map;for(const t of Object.keys(i))e.set(i[t],t);tflite.Utility._enumKeyMap.set(t,e)}const n=tflite.Utility._enumKeyMap.get(t);if(n.has(e))return n.get(e)}return e}static type(t){const e=new Set(["2D","LSH","SVDF","RNN","L2","LSTM"]);return t.split("_").map((t=>t.length<1||e.has(t)?t:t[0]+t.substring(1).toLowerCase())).join("")}},tflite.Error=class extends Error{constructor(t){super(t),this.name="Error loading TensorFlow Lite model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tflite.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..27da838d8bd0ff2d958484f8e917812cb0cc948f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn-metadata.json @@ -0,0 +1 @@ +[{"name":"AbsVal","schema":{"operator":0}},{"name":"ArgMax","schema":{"operator":1}},{"name":"BatchNormCxx","schema":{"operator":2,"category":"Normalization"}},{"name":"Bias","schema":{"operator":3,"category":"Layer","attributes":[{"name":"bias_data_size","default":0,"visible":false}]}},{"name":"BNLL","schema":{"operator":4}},{"name":"Concat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"QuantizedConcat","schema":{"operator":5,"category":"Tensor","attributes":[{"name":"axis","type":"int32","default":0}],"inputs":[{"name":"input","option":"variadic"}],"outputs":[{"name":"output"}]}},{"name":"Convolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"QuantizedConvolution","schema":{"operator":6,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"Crop","schema":{"operator":7,"category":"Data"}},{"name":"Deconvolution","schema":{"operator":8,"category":"Layer"}},{"name":"Dropout","schema":{"operator":9,"category":"Dropout","attributes":[{"name":"scale","type":"float32","default":1}]}},{"name":"Eltwise","schema":{"operator":10}},{"name":"ELU","schema":{"operator":11}},{"name":"Embed","schema":{"operator":12,"category":"Transform","attributes":[{"name":"num_output","default":0},{"name":"input_dim","default":0},{"name":"bias_term","default":0},{"name":"weight_data_size","default":0}]}},{"name":"Exp","schema":{"operator":13}},{"name":"Flatten","schema":{"operator":14,"category":"Shape","attributes":[{"name":"axis","default":1},{"name":"num_axis","default":4}]}},{"name":"InnerProduct","schema":{"operator":15,"category":"Layer","attributes":[{"name":"num_output","type":"int32","default":0},{"name":"has_bias ","default":0,"visible":false},{"name":"transpose","default":0,"visible":false},{"name":"axis ","default":0}]}},{"name":"Input","schema":{"operator":16}},{"name":"Exp","schema":{"operator":17}},{"name":"LRN","schema":{"operator":18,"category":"Normalization","attributes":[{"name":"alpha","default":0},{"name":"beta","default":0.75},{"name":"bias","default":1},{"name":"size","default":1}]}},{"name":"Exp","schema":{"operator":19}},{"name":"MVN","schema":{"operator":20}},{"name":"Pooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"QuantizedPooling","schema":{"operator":21,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"Power","schema":{"operator":22}},{"name":"PReLU","schema":{"operator":23,"category":"Activation","attributes":[{"name":"channel_shared","default":0},{"name":"has_filler","default":0}]}},{"name":"Proposal","schema":{"operator":24}},{"name":"Reduce","schema":{"operator":25,"attributes":[{"name":"keep_dims","default":0},{"name":"axis","default":0}]}},{"name":"ReLU","schema":{"operator":26,"category":"Activation"}},{"name":"ROIPooling","schema":{"operator":27,"attributes":[{"name":"pool_type","default":0},{"name":"spatial_scale","default":0},{"name":"pooled_w ","default":0},{"name":"pooled_h","default":0},{"name":"pooled_d","default":0}]}},{"name":"Reshape","schema":{"operator":28,"category":"Shape","attributes":[{"name":"axis","default":0},{"name":"num_axes","default":4},{"name":"top_blob_dim_size","default":-233},{"name":"shape","type":"int32[]","size":2,"default":233},{"name":"reshape_type","default":0}]}},{"name":"Scale","schema":{"operator":29,"category":"Layer","attributes":[{"name":"axis","default":0,"visible":false},{"name":"num_axes","default":0,"visible":false},{"name":"bias_term","default":0,"visible":false}]}},{"name":"Sigmoid","schema":{"operator":30,"category":"Activation"}},{"name":"Slice","schema":{"operator":31,"category":"Tensor","attributes":[{"name":"slices","default":[]},{"name":"axis","default":1}]}},{"name":"Softmax","schema":{"operator":32,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0}]}},{"name":"Splitv","schema":{"operator":33,"category":"Tensor","inputs":[{"name":"input"}],"outputs":[{"name":"output","option":"variadic"}]}},{"name":"SPP","schema":{"operator":34,"category":"Activation"}},{"name":"Tanh","schema":{"operator":35,"category":"Activation"}},{"name":"Threshold","schema":{"operator":36}},{"name":"Tile","schema":{"operator":37}},{"name":"RNN","schema":{"operator":38,"category":"Layer"}},{"name":"LSTM","schema":{"operator":39,"category":"Layer"}},{"name":"BinaryOp","schema":{"operator":40,"attributes":[{"name":"op_type","type":"int32","default":0},{"name":"b","type":"float32","default":0}]}},{"name":"UnaryOp","schema":{"operator":41}},{"name":"ConvolutionDepthWise","schema":{"operator":42,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_w","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_h","type":"int32","default":0},{"name":"dialation_w","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"Pad","schema":{"operator":43,"attributes":[{"name":" n1","default":0},{"name":" n2","default":0},{"name":" pad_h","default":0},{"name":" pad_b","default":0},{"name":" pad_w","default":0},{"name":" pad_r","default":0},{"name":" c1","default":0},{"name":" c2","default":0},{"name":" type","default":0}]}},{"name":"Squeeze","schema":{"operator":44}},{"name":"ExpandDims","schema":{"operator":45}},{"name":"Normalize","schema":{"operator":46,"arributes":[{"name":"across_spatial","default":0},{"name":"epsilon","type":"float32","default":0},{"name":"channel_shared","default":0},{"name":"axis","default":0},{"name":"p","default":0}]}},{"name":"Permute","schema":{"operator":47,"category":"Shape","attributes":[{"name":"order_size","default":0},{"name":"orders","type":"int32[]","size":"0"}]}},{"name":"PriorBox","schema":{"operator":48,"attributes":[{"name":"min_size","default":[]},{"name":"max_size","default":[]},{"name":"clip","default":1},{"name":"flip","default":1},{"name":"varainces0","type":"float32","default":0},{"name":"varainces1","type":"float32","default":0},{"name":"varainces2","type":"float32","default":0},{"name":"varainces3","type":"float32","default":0},{"name":"aspect_ratios","default":0},{"name":"img_w","default":0},{"name":"img_h","default":0},{"name":"step_w","default":-233},{"name":"step_h","default":-233},{"name":"offset","default":0}]}},{"name":"DetectionOutput","schema":{"operator":49,"attributes":[{"name":"num_class","default":0},{"name":"share_location","default":0},{"name":"background_label_id","default":0},{"name":"variance_encoded_in_target","default":0},{"name":"code_type","default":0},{"name":"keep_top_k","default":0},{"name":"confidence_threshold","default":0},{"name":"nms_param.nms_threshold","default":0},{"name":"nms_param.top_k","default":0},{"name":"eta","default":0}]}},{"name":"Interp","schema":{"operator":50}},{"name":"DeconvolutionDepthWise","schema":{"operator":51,"category":"Layer"}},{"name":"Shuffle","schema":{"operator":52,"attributes":[{"name":"group","default":1}]}},{"name":"InstanceNorm","schema":{"operator":53}},{"name":"Clip","schema":{"operator":54,"attributes":[{"name":"min","default":0},{"name":"max","default":0}]}},{"name":"Reorg","schema":{"operator":55,"attributes":[{"name":"stride","default":0},{"name":"reverse","default":0}]}},{"name":"YoloDetectionOutput","schema":{"operator":56}},{"name":"Quantize","schema":{"operator":57}},{"name":"Dequantize","schema":{"operator":58}},{"name":"Yolov3DetectionOutput","schema":{"operator":59}},{"name":"ROIPooling","schema":{"operator":60,"attributes":[{"name":"pool_type","default":0},{"name":"pool_type","type":"float32","default":0},{"name":"pooled_w","default":0},{"name":"pooled_h","default":0},{"name":"pooled_d","default":0}]}},{"name":"ROIAlign","schema":{"operator":61}},{"name":"Packing","schema":{"operator":62}},{"name":"Requantize","schema":{"operator":63}},{"name":"Cast","schema":{"operator":64}},{"name":"HardSigmoid","schema":{"operator":65,"category":"Activation","attributes":[{"name":"alpha","type":"float32","default":0},{"name":"beta","type":"float32","default":0}]}},{"name":"SELU","schema":{"operator":66,"category":"Activation","attributes":[{"name":"alpha","default":0},{"name":"gamma","default":0}]}},{"name":"ReLU6","schema":{"category":"Activation"}},{"name":"Conv3D","schema":{"operator":68,"category":"Layer","attributes":[{"name":"group","type":"int32","default":0},{"name":"input_channel","type":"int32","default":0},{"name":"output_channel","type":"int32","default":1},{"name":"kernel_w","type":"int32","default":0},{"name":"kernel_h","type":"int32","default":0},{"name":"kernel_d","type":"int32","default":0},{"name":"stride_h","default":0,"visible":false},{"name":"stride_w","type":"int32","default":0,"visible":false},{"name":"stride_d","type":"int32","default":0,"visible":false},{"name":"pad_h","type":"int32","default":0},{"name":"pad_w ","default":0},{"name":"pad_d ","default":0},{"name":"bias","default":0},{"name":"pad_type","default":[]},{"name":"dialation_w","type":"int32","default":0},{"name":"dialation_h","type":"int32","default":1},{"name":"dialation_d","type":"int32","default":1},{"name":"activation_type","type":"int32","default":1}]}},{"name":"HardSwish","schema":{"operator":69,"category":"Layer","attributes":[{"name":"alpha","type":"float32","default":1},{"name":"beta","type":"float32","default":1}]}},{"name":"HdrGuide","schema":{"operator":70,"category":"Layer"}},{"name":"Max","schema":{"operator":71,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Min","schema":{"operator":72,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Mul","schema":{"operator":73,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Pooling3D","schema":{"operator":74,"category":"Pool","attributes":[{"name":"pool_type","default":0},{"name":"kernel_h","default":0},{"name":"kernel_w","default":0},{"name":"kernel_d","default":0},{"name":"stride_h","default":0},{"name":"stride_w ","default":0},{"name":"stride_d ","default":0},{"name":"pad_h","default":0},{"name":"pad_w","default":0},{"name":"pad_d","default":0},{"name":"kernel_h_index","default":0},{"name":"kernel_w_index","default":0},{"name":"kernel_d_index","default":0},{"name":"pad_type ","default":0},{"name":"ceil_mode ","default":0}]}},{"name":"Pow","schema":{"operator":75,"category":"Layer","attributes":[{"name":"exponent","type":"float32","default":0},{"name":"scale ","type":"float32","default":0},{"name":"shift ","type":"float32","default":0}]}},{"name":"StridedSlice","schema":{"operator":76,"category":"Layer","attributes":[{"name":"n1","default":0}]}},{"name":"Sub","schema":{"operator":77,"category":"Layer","attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Upsample","schema":{"operator":78,"category":"Layer","attributes":[{"name":"type","default":0},{"name":"scale_h","type":"float32","default":0},{"name":"scale_w","type":"float32","default":0},{"name":"align_corners","default":0},{"name":"height","default":0},{"name":"width","default":0}]}},{"name":"BlobScale","schema":{"operator":78,"category":"Layer"}},{"name":"Add","schema":{"operator":79,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"Div","schema":{"operator":80,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"SplitV","schema":{"operator":81,"category":"Layer","attributes":[{"name":"axis","default":1},{"name":"slice_count","default":1}]}},{"name":"Sub","schema":{"operator":80,"attributes":[{"name":"weight_input_index","default":0}]}},{"name":"InstBatchNormCxx","schema":{"operator":81,"category":"Layer"}},{"name":"SoftmaxCaffe","schema":{"operator":82,"category":"Activation","attributes":[{"name":"axis","type":"int32","default":0}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn.js new file mode 100644 index 0000000000000000000000000000000000000000..e1df76bdbd8b1132d037922d6a73b3b6d99bfdf8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/tnn.js @@ -0,0 +1 @@ +var tnn=tnn||{},base=base||require("./base");tnn.ModelFactory=class{match(t){const e=t.identifier.toLowerCase();if(e.endsWith(".tnnproto")){let e=t.text;e=e.substring(0,Math.min(e.length,128));const n=e.split("\n").shift().trim();if(n.startsWith('"')&&n.endsWith('"')){const t=n.replace(/(^")|("$)/g,"").split(",").shift().trim().split(" ");if(3===t.length||t.length>=4&&"4206624770"===t[3])return!0}}if(e.endsWith(".tnnmodel")){const e=t.buffer;if(e.length>4&&4206624770==(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0)return!0}return!1}open(t,e){return tnn.Metadata.open(e).then((e=>{const n=t.identifier.toLowerCase();if(n.endsWith(".tnnproto")){const s=t.identifier.substring(0,t.identifier.length-9)+".tnnmodel";return t.request(s,null).then((n=>new tnn.Model(e,t.text,n))).catch((()=>new tnn.Model(e,t.text,null))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new tnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}if(n.endsWith(".tnnmodel")){const s=t.identifier.substring(0,t.identifier.length-9)+".tnnproto";return t.request(s,"utf-8").then((n=>new tnn.Model(e,n,t.buffer))).catch((t=>{const e=t&&t.message?t.message:t.toString();throw new tnn.Error(e.replace(/\.$/,"")+" in '"+n+"'.")}))}}))}},tnn.Model=class{constructor(t,e,n){this._graphs=[],this._graphs.push(new tnn.Graph(t,e,n))}get format(){return"TNN"}get graphs(){return this._graphs}},tnn.Graph=class{constructor(t,e,n){this._inputs=[],this._outputs=[],this._nodes=[];const s=new tnn.LayerResourceReader(n),i=new tnn.TextProtoReader(e);for(const t of i.inputs){const e=new tnn.TensorShape(t.shape),n=new tnn.TensorType("float32",e);this._inputs.push(new tnn.Parameter(t.name,[new tnn.Argument(t.name,n,null)]))}for(const t of i.outputs)this._outputs.push(new tnn.Parameter(t.name,[new tnn.Argument(t.name,null,null)]));for(const e of i.layers)this._nodes.push(new tnn.Node(t,s,e))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},tnn.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},tnn.Argument=class{constructor(t,e,n){if("string"!=typeof t)throw new tnn.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=n||null}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},tnn.Node=class{constructor(t,e,n){this._metadata=t,this._inputs=[],this._outputs=[],this._attributes=[],this._type=n.type,this._name=n.name;const s=t.operator(this._type);s&&(this._type=s);const i=t.type(this._type),a=i&&i.attributes?i&&i.attributes.slice():[],r=n.attributes.slice();for(;r.length>0;){const t=a.shift();let e=null,s="";if(t&&"int32[]"===t.type&&t.size)s=t.name,e=r.splice(0,n.attr[t.size]).map((t=>parseInt(t.value,10)));else{const t=r.shift();s=t.key,e=t.value}this._attributes.push(new tnn.Attribute(t,s,e))}const o=n.inputs;let h=0;if(i&&i.inputs){for(const t of i.inputs)if(h""!=e||"optional"!=t.option)).map((t=>new tnn.Argument(t,null,null)));this._inputs.push(new tnn.Parameter(t.name,n)),h+=e}}else this._inputs=this._inputs.concat(o.slice(h).map(((t,e)=>{const n=h+e==0?"input":(h+e).toString();return new tnn.Parameter(n,[new tnn.Argument(t,null,null)])})));const u=n.outputs;let l=0;if(i&&i.outputs){for(const t of i.outputs)if(lnew tnn.Argument(t,null,null)));this._outputs.push(new tnn.Parameter(t.name,n)),l+=e}}else this._outputs=this._outputs.concat(u.slice(l).map(((t,e)=>{const n=l+e==0?"output":(l+e).toString();return new tnn.Parameter(n,[new tnn.Argument(t,null,null)])})));switch(this._type){case"Convolution":case"ConvolutionDepthWise":case"Deconvolution":case"DeconvolutionDepthWise":{const t=e.read(this._name);if(t){const e=parseInt(n.attr[2]||0,10),s=parseInt(n.attr[3]||0,10),i=parseInt(n.attr[4]||s,10),a=t.filter.length;this._weight(t,"filter",[e,a/(e*s*i),s,i]),t.bias&&this._weight(t,"bias",[e]),t.quantized&&this._weight(t,"quantized",[e])}break}case"Conv3D":{const t=e.read(this._name);if(t){const s=parseInt(n.attr[2]||0,10),i=parseInt(n.attr[3]||0,10),a=parseInt(n.attr[4]||i,10),r=parseInt(n.attr[5]||i,10),o=t.filter.length;this._weight(t,"weight",[s,o/(s*i*a*r),i,a,r]),t.bias&&this._weight(e,"bias",[s])}break}case"InnerProduct":{const t=e.read(this._name);if(t){const e=parseInt(n.attr[0]||0,10),s=t.weight.length;this._weight(t,"weight",[e,s/e]),this._weight(t,"bias",[e]),"int8"===t.weight.dataType&&this._weight(t,"scale",[e])}break}case"PReLU":{const t=e.read(this._name);t&&this._weight(t,"slope",[t.slope.length]);break}case"BatchNormCxx":{const t=e.read(this._name);t&&(this._weight(t,"scale",[t.scale.length]),this._weight(t,"bias",[t.bias.length]));break}case"Div":case"Sub":case"Add":case"Mul":if(1===this._inputs.length){const t=e.read(this._name);if(t){const e=t.slope.length;this._weight(t,"slope",[e])}}break;case"HdrGuide":{const t=e.read(this._name);if(t){const e=t.ccm_weight.length;this._weight(t,"ccm_weight",[e]),this._weight(t,"ccm_bias",[e]),this._weight(t,"shifts",[e]),this._weight(t,"slopes",[e]),this._weight(t,"projection_weight",[e]),this._weight(t,"projection_bias",[e])}break}case"BlobScale":{const t=e.read(this._name);if(t){const e=t.scale.length;this._weight(t,"scale",[e]),this._weight(t,"bias",[e])}break}}}get type(){return this._type}get name(){return this._name}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_weight(t,e,n){const s=t[e];if(!s)throw new tnn.Error("Layer initializer'"+t.type+"."+e+"' not found '");const i=new tnn.Tensor(new tnn.TensorType(s.dataType,new tnn.TensorShape(n)),s.value);this._inputs.push(new tnn.Parameter(e,[new tnn.Argument("",null,i)]))}},tnn.Attribute=class{constructor(t,e,n){if(this._type="",this._name=e.toString(),this._value=n,t){switch(this._name=t.name,t.type&&(this._type=t.type),this._type){case"int32":this._value=parseInt(this._value,10);break;case"float32":this._value=parseFloat(this._value);break;case"float32[]":this._value=this._value.map((t=>parseFloat(t)))}(Object.prototype.hasOwnProperty.call(t,"visible")&&!t.visible||Object.prototype.hasOwnProperty.call(t,"default")&&(this._value==t.default||this._value&&this._value.toString()==t.default.toString()))&&(this._visible=!1)}}get type(){return this._type}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},tnn.Tensor=class{constructor(t,e){this._type=t,this._data=e}get kind(){return"Weight"}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={index:0,count:0,state:null};if("?"==this._type.dataType)return t.state="Tensor has unknown data type.",t;if(!this._type.shape)return t.state="Tensor has no dimensions.",t;if(!this._data)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"float16":case"float32":t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength);break;default:t.state="Tensor data type is not implemented."}return t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t}_decode(t,e){const n=0!==t.shape.length?t.shape:[1],s=[],i=n[e];if(e==n.length-1)for(let e=0;et.limit)return s.push("..."),s;switch(this._type.dataType){case"float32":s.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++;break;case"float16":s.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++}}else for(let n=0;nt.limit)return s.push("..."),s;s.push(this._decode(t,e+1))}return 0==t.shape.length?s[0]:s}},tnn.TensorType=class{constructor(t,e){this._dataType=t||"?",this._shape=e}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this._dataType+this._shape.toString()}},tnn.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?"["+this._dimensions.map((t=>t?t.toString():"?")).join(",")+"]":""}},tnn.Metadata=class{static open(t){return tnn.Metadata._metadata?Promise.resolve(tnn.Metadata._metadata):t.request(null,"tnn-metadata.json","utf-8").then((t=>(tnn.Metadata._metadata=new tnn.Metadata(t),tnn.Metadata._metadata))).catch((()=>(tnn.Metadata._metadata=new tnn.Metadata(null),tnn.Metadata._metadatas)))}constructor(t){if(this._operatorMap=new Map,this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema),Object.prototype.hasOwnProperty.call(t.schema,"operator")&&this._operatorMap.set(t.schema.operator,t.name))}}operator(t){return this._operatorMap.get(t)}type(t){return this._map.get(t)}attribute(t,e){const n=t+":"+e;if(!this._attributeCache.has(n)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const n of e.attributes)this._attributeCache.set(t+":"+n.name,n);this._attributeCache.has(n)||this._attributeCache.set(n,null)}return this._attributeCache.get(n)}},tnn.TextProtoReader=class{constructor(t){const e=(t,e,n,s)=>t.split(e).map((t=>n?t.trim():t)).filter((t=>!s||t)),n=e(t.replace(/\r?\n|"/g,""),",",!0,!1);if(n.length<=5)throw new tnn.Error("Invalid line count.");const s=e(n.shift()," ",!0,!1);if(s.length<3)throw new tnn.Error("Invalid header size.");if(s.length>3&&"4206624770"!==s[3])throw new tnn.Error("Invalid signature '"+s[3]+"'.");for(this._inputs=e(n.shift(),":",!0,!1).map((t=>{const n=e(t," ",!0,!1);return{name:n.shift(),shape:n.map((t=>parseInt(t,10)))}})),n.shift(),this._outputs=e(n.shift()," ",!0,!1).map((t=>({name:t}))),n.shift(),this._layers=[];n.length>0;){const t=n.shift().trim();if(t.length>0){const n=e(t," ",!0,!0),s={};s.type=n.shift(),s.name=n.shift();const i=parseInt(n.shift(),10),a=parseInt(n.shift(),10);s.inputs=n.splice(0,i),s.outputs=n.splice(0,a),s.attr={},s.attributes=[];let r=0;for(const t of n){const e=t.split(" ");if(1===e.length){let t=r,n=e.toString();const i=parseInt(t,10);i<0&&(n=n.split(",").map((t=>t.trim())),n.shift(),t=(-(i+23300)).toString()),s.attr[t]=n,s.attributes.push({key:t,value:n}),r++}}this._layers.push(s)}}}get inputs(){return this._inputs}get outputs(){return this._outputs}get layers(){return this._layers}},tnn.LayerResourceReader=class{constructor(t){if(this._layerResources=[],t){const e=new tnn.BinaryReader(t),n=e.uint32();if(4206624770!==n)throw new tnn.Error("Invalid blob header signature '"+n.toString()+"'.");const s=536870911&e.int32(),i=t=>{const e=t.uint32();if(4206624770!==e)throw new tnn.Error("Invalid raw signature '"+e.toString()+"'.");const n=t.int32();if(n>4)throw new tnn.Error("Unknown data type '"+n+"'.");const s=t.int32();return s<=0?null:{dataType:["float32","float16","int8","int32","bfloat16"][n],length:s/[4,2,1,4,2][n],value:t.bytes(s)}};for(let t=0;tthis._buffer.length)throw new tnn.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}bytes(t){const e=this._position;return this.skip(t),this._buffer.subarray(e,this._position)}uint32(){const t=this._position;return this.skip(4),this._dataView.getUint32(t,!0)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}string(){const t=this.int32(),e=this._position;this.skip(t);const n=this._buffer.subarray(e,this._position);return new TextDecoder("utf-8").decode(n)}expect(t){const e=this.string();if(t!==e)throw new tnn.Error("Invalid string '"+e+"' instead of '"+t+"'.")}},tnn.Error=class extends Error{constructor(t){super(t),this.name="Error loading TNN model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=tnn.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..90575950f50131da82196d3202e19c88d56a5cba --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch-metadata.json @@ -0,0 +1 @@ +[{"name":"nn.Linear","schema":{"category":"Layer"}},{"name":"nn.LinearNoBias","schema":{"category":"Layer"}},{"name":"nn.SpatialConvolution","schema":{"category":"Layer","attributes":[{"name":"benchmarked","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false},{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"fmode","visible":false},{"name":"bwmode","visible":false},{"name":"bdmode","visible":false}]}},{"name":"cudnn.SpatialConvolution","schema":{"category":"Layer","attributes":[{"name":"benchmarked","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false},{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"fmode","visible":false},{"name":"bwmode","visible":false},{"name":"bdmode","visible":false}]}},{"name":"nn.VolumetricConvolution","schema":{"category":"Layer"}},{"name":"nn.SpatialConvolutionMM","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"padding","default":0},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false}]}},{"name":"nn.SpatialFullConvolution","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false}]}},{"name":"cudnn.SpatialFullConvolution","schema":{"category":"Layer","attributes":[{"name":"groups","default":1},{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"convDescData","visible":false},{"name":"autotunerHash","visible":false},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false},{"name":"input_offset","visible":false},{"name":"output_offset","visible":false},{"name":"weight_offset","visible":false}]}},{"name":"nn.SpatialDilatedConvolution","schema":{"category":"Layer","attributes":[{"name":"d","default":[1,1]},{"name":"dilation","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"nInputPlane","visible":false},{"name":"nOutputPlane","visible":false}]}},{"name":"nn.SpatialSubtractiveNormalization","schema":{"category":"Normalization"}},{"name":"nn.InstanceNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"nOutput","visible":false},{"name":"prev_batch_size","visible":false},{"name":"eps","default":0.00001},{"name":"momentum","default":0.1}]}},{"name":"nn.BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"cudnn.BatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"nn.SpatialBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001},{"name":"mode","default":"CUDNN_BATCHNORM_SPATIAL"},{"name":"nDim","default":4},{"name":"__shareGradInputKey","visible":false}]}},{"name":"cudnn.SpatialBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001},{"name":"mode","default":"CUDNN_BATCHNORM_SPATIAL"},{"name":"nDim","default":4},{"name":"__shareGradInputKey","visible":false}]}},{"name":"nn.VolumetricBatchNormalization","schema":{"category":"Normalization","attributes":[{"name":"affine","default":true},{"name":"momentum","default":0.1},{"name":"eps","default":0.00001}]}},{"name":"nn.SpatialAveragePooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING"},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"count_include_pad","visible":false}]}},{"name":"cudnn.SpatialAveragePooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING"},{"name":"d","default":[1,1]},{"name":"pad","default":[0,0]},{"name":"count_include_pad","visible":false}]}},{"name":"nn.VolumetricAveragePooling","schema":{"category":"Pool"}},{"name":"nn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"cudnn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"inn.SpatialMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false},{"name":"mode","default":"CUDNN_POOLING_MAX"},{"name":"pad","default":[0,0]},{"name":"iheight","visible":false},{"name":"iwidth","visible":false}]}},{"name":"nn.VolumetricMaxPooling","schema":{"category":"Pool","attributes":[{"name":"ceil_mode","default":false}]}},{"name":"nn.SpatialFractionalMaxPooling","schema":{"category":"Pool"}},{"name":"nn.SpatialZeroPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.SpatialReflectionPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.SpatialReplicationPadding","schema":{"category":"Tensor","attributes":[]}},{"name":"nn.Concat","schema":{"category":"Tensor","attributes":[{"name":"outputSize","visible":false}]}},{"name":"nn.PReLU","schema":{"category":"Activation"}},{"name":"nn.ReLU","schema":{"category":"Activation","attributes":[{"name":"threshold","default":0},{"name":"val","default":0},{"name":"inplace","default":false,"visible":false},{"name":"mode","default":"CUDNN_ACTIVATION_RELU"},{"name":"nElem","visible":false}]}},{"name":"cudnn.ReLU","schema":{"category":"Activation","attributes":[{"name":"threshold","default":0},{"name":"val","default":0},{"name":"inplace","default":false,"visible":false},{"name":"mode","default":"CUDNN_ACTIVATION_RELU"},{"name":"nElem","visible":false}]}},{"name":"nn.SoftMax","schema":{"category":"Activation"}},{"name":"nn.LogSoftMax","schema":{"category":"Activation"}},{"name":"cudnn.LogSoftMax","schema":{"category":"Activation"}},{"name":"nn.Tanh","schema":{"category":"Activation","attributes":[{"name":"mode","default":"CUDNN_ACTIVATION_TANH"},{"name":"nElem","visible":false}]}},{"name":"nn.LeakyReLU","schema":{"category":"Activation","attributes":[{"name":"negval","default":0.01,"visible":false},{"name":"inplace","default":false,"visible":false}]}},{"name":"nn.Sigmoid","schema":{"category":"Activation","attributes":[{"name":"mode","default":"CUDNN_ACTIVATION_SIGMOID"},{"name":"nElem","visible":false}]}},{"name":"nn.Reshape","schema":{"category":"Shape","attributes":[{"name":"nelement","visible":false}]}},{"name":"nn.Dropout","schema":{"category":"Dropout","attributes":[{"name":"v2","visible":false}]}},{"name":"nn.SpatialDropout","schema":{"category":"Dropout"}},{"name":"nn.Normalize","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.Normalize2","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.SpatialCrossMapLRN","schema":{"category":"Normalization","attributes":[]}},{"name":"nn.Mean","schema":{"attributes":[{"name":"squeeze","default":true},{"name":"sizeAverage","default":false},{"name":"dimension","default":1},{"name":"nInputDims","visible":false}]}},{"name":"nn.MulConstant","schema":{"attributes":[{"name":"inplace","default":false,"visible":false}]}},{"name":"nn.Identity","schema":{}},{"name":"nn.ConcatTable","schema":{}},{"name":"nn.CAddTable","schema":{}},{"name":"nn.ScaleTable","schema":{}},{"name":"nn.SelectTable","schema":{}},{"name":"w2nn.ScaleTable","schema":{}},{"name":"nn.SplitTable","schema":{}},{"name":"nn.FlattenTable","schema":{}},{"name":"nn.View","schema":{}},{"name":"nn.Sequencer","schema":{}},{"name":"nn.TotalVariation","schema":{}},{"name":"nn.ShaveImage","schema":{}},{"name":"nn.Contiguous","schema":{}},{"name":"nn.Squeeze","schema":{"category":"Transform"}},{"name":"nn.MM","schema":{}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch.js new file mode 100644 index 0000000000000000000000000000000000000000..987552869673ca83037a9c6b45dab02e31fbd156 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/torch.js @@ -0,0 +1 @@ +var torch=torch||{},base=base||require("./base"),long=long||{Long:require("long")};torch.ModelFactory=class{match(t){if("t7"==t.identifier.split(".").pop().toLowerCase()){const n=t.buffer;return!(n.length>=1&&n[0]>58)}return!1}open(t,n){return torch.Metadata.open(n).then((i=>{const e=t.identifier;try{let s=new torch.T7Reader(t.buffer,(t=>(!t||"nn.JointTrainModule"==t||t.startsWith("nn.MSDNet_")||t.startsWith("onmt.")||n.exception(new torch.Error("Unknown type '"+t+"' in '"+e+"'."),!1),null))).read();return s&&Array.isArray(s)&&2==s.length&&s[0].__type__&&!s[1].__type__&&(s=s[0]),new torch.Model(i,s)}catch(t){const n=t&&t.message?t.message:t.toString();throw new torch.Error(n.replace(/\.$/,"")+" in '"+e+"'.")}}))}},torch.Model=class{constructor(t,n){this._graphs=[],this._graphs.push(new torch.Graph(t,n))}get graphs(){return this._graphs}get format(){return"Torch v7"}},torch.Graph=class{constructor(t,n){this._inputs=[],this._outputs=[],this._nodes=[],this._groups="false",Object.prototype.hasOwnProperty.call(n,"model")&&(n=n.model);const i=[],e=[];this._loadModule(t,n,[],"",i,e),this._inputs=this._inputs.concat(i.map(((t,n)=>new torch.Parameter("input"+(0!=n?(n+1).toString():""),!0,[t])))),this._outputs=this._outputs.concat(e.map(((t,n)=>new torch.Parameter("output"+(0!=n?(n+1).toString():""),!0,[t]))))}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}get groups(){return this._groups}_loadModule(t,n,i,e,s,r){switch(i.length>0&&(this._groups=!0),n.__type__){case"nn.Sequential":{i.push(e);let o=s,a=[];const h=n.modules.length;let c=0;for(const e of n.modules)c==h-1&&(a=r),this._loadModule(t,e,i,c.toString(),o,a),o=a,a=[],c++;i.pop();break}case"nn.Parallel":case"nn.ParallelTable":case"nn.JointTrain":{i.push(e);let o=[],a=[],h=0;for(const e of n.modules){const n=[].concat(s),c=[].concat(r);this._loadModule(t,e,i,h.toString(),n,c),0==s.length&&(o=o.concat(n)),0==r.length&&(a=a.concat(c)),h++}s=s.concat(o);for(const t of a)r.push(t);i.pop();break}case"nn.Concat":case"nn.ConcatTable":{const o=e;0==s.length&&s.push(new torch.Argument(i.join("/")+":"+e+":in",null,null));let a=[],h=0;for(const e of n.modules){const n=s.map((t=>t)),r=[];this._loadModule(t,e,i,o+"."+h.toString(),n,r),a=a.concat(r),h++}delete n.modules,delete n.dimension,this._createNode(t,n,i,e,a,r);break}case"nn.Inception":delete n.modules,delete n.module,delete n.transfer,delete n.pool,this._createNode(t,n,i,e,s,r);break;default:this._createNode(t,n,i,e,s,r)}}_createNode(t,n,i,e,s,r){this._nodes.push(new torch.Node(t,n,i,e,s,r))}},torch.Parameter=class{constructor(t,n,i){this._name=t,this._visible=n,this._arguments=i}get name(){return this._name}get visible(){return this._visible}get arguments(){return this._arguments}},torch.Argument=class{constructor(t,n,i){if("string"!=typeof t)throw new torch.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=n,this._initializer=i}get name(){return this._name}get type(){return this._initializer?this._initializer.type:this._type}get initializer(){return this._initializer}},torch.Node=class{constructor(t,n,i,e,s,r){this._metadata=t,this._group=i.join("/"),n.name&&"string"==typeof n.name?(this._name=n.name,delete n.name):this._name=this._group?this._group+":"+e:e,this._type=n.__type__||"nn.Module";let o=[];for(const t of Object.keys(n)){const i=n[t];if(i&&i.__type__&&i.__type__.startsWith("torch.")&&i.__type__.endsWith("Storage")){const e=[];i.reset();for(let t=0;tt&&t.__type__&&t.__type__.startsWith("nn.")))||(i.__type__&&i.__type__.startsWith("torch.")&&i.__type__.endsWith("Tensor")?o.push(new torch.Parameter(t,!0,[new torch.Argument(t,null,new torch.Tensor(i))])):"modules"==t||i.__type__&&"Function"!=i.__type__||this._attributes.push(new torch.Attribute(this._metadata,this._type,t,i)))}this._inputs=[],0==s.length&&this._name&&s.push(new torch.Argument(this._name+":in",null,null)),this._inputs.push(new torch.Parameter("input",!0,s)),0==r.length&&this._name&&r.push(new torch.Argument(this._name,null,null)),this._outputs=[],this._outputs.push(new torch.Parameter("output",!0,r)),o=o.filter((t=>"weight"!=t.name||(this._inputs.push(t),!1))),o=o.filter((t=>"bias"!=t.name||(this._inputs.push(t),!1))),this._inputs=this._inputs.concat(o)}get name(){return this._name}get type(){return this._type}get group(){return this._group}get metadata(){return this._metadata.type(this._type)}get attributes(){return this._attributes}get inputs(){return this._inputs}get outputs(){return this._outputs}_updateSize(t,n){Object.prototype.hasOwnProperty.call(t,n+"W")&&Object.prototype.hasOwnProperty.call(t,n+"H")&&(t[n]=[t[n+"W"],t[n+"H"]],delete t[n+"W"],delete t[n+"H"])}_updateBox(t,n){Object.prototype.hasOwnProperty.call(t,n+"_t")&&Object.prototype.hasOwnProperty.call(t,n+"_r")&&Object.prototype.hasOwnProperty.call(t,n+"_b")&&Object.prototype.hasOwnProperty.call(t,n+"_l")&&(t[n]=[t[n+"_t"],t[n+"_r"],t[n+"_b"],t[n+"_l"]],delete t[n+"_t"],delete t[n+"_r"],delete t[n+"_b"],delete t[n+"_l"])}},torch.Attribute=class{constructor(t,n,i,e){this._name=i,this._value=e,"train"==i&&(this._visible=!1);const s=t.attribute(n,i);s&&(Object.prototype.hasOwnProperty.call(s,"visible")?this._visible=s.visible:Object.prototype.hasOwnProperty.call(s,"default")&&JSON.stringify(s.default)==JSON.stringify(this._value)&&(this._visible=!1))}get name(){return this._name}get value(){return this._value}get visible(){return 0!=this._visible}},torch.Tensor=class{constructor(t){this._type=new torch.TensorType(t),this._storage=t.storage}get type(){return this._type}get state(){return this._context().state||null}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e3;const n=this._decode(t,0);return JSON.stringify(n,null,4)}_context(){const t={state:null,index:0,count:0};if(!this._storage||!this._storage.reader)return t.state="Tensor data is empty.",t;switch(this._type.dataType){case"uint8":case"int8":case"int16":case"int32":case"int64":case"float32":case"float64":break;default:t.state="Tensor data type is not implemented."}return t.dimensions=this._type.shape.dimensions,t.dimensions||0!=t.dimensions.length?(t.storage=this._storage,t.storage.reset(),t):(t.state="Tensor has no dimensions.",t)}_decode(t,n){const i=[],e=t.dimensions[n];if(n==t.dimensions.length-1)for(let n=0;nt.limit)return i.push("..."),i;i.push(t.storage.read()),t.index++,t.count++}else for(let s=0;st.limit)return i.push("..."),i;i.push(this._decode(t,n+1))}return i}},torch.TensorType=class{constructor(t){this._dataType=t.dataType,this._shape=new torch.TensorShape(t.size)}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return(this.dataType||"?")+this._shape.toString()}},torch.TensorShape=class{constructor(t){this._dimensions=t}get dimensions(){return this._dimensions}toString(){return this._dimensions?0==this._dimensions.length?"":"["+this._dimensions.map((t=>t.toString())).join(",")+"]":""}},torch.Metadata=class{static open(t){return torch.Metadata._metadata?Promise.resolve(torch.Metadata._metadata):t.request(null,"torch-metadata.json","utf-8").then((t=>(torch.Metadata._metadata=new torch.Metadata(t),torch.Metadata._metadata))).catch((()=>(torch.Metadata._metadata=new torch.Metadata(null),torch.Metadata._metadata)))}constructor(t){if(this._map={},this._attributeCache={},t){const n=JSON.parse(t);if(n)for(const t of n)t.schema.name=t.name,this._map[t.name]=t.schema}}type(t){return this._map[t]||null}attribute(t,n){let i=this._attributeCache[t];if(!i){i={};const n=this.type(t);if(n&&n.attributes&&n.attributes.length>0)for(const t of n.attributes)i[t.name]=t;this._attributeCache[t]=i}return i[n]||null}},torch.Error=class extends Error{constructor(t){super(t),this.name="Error loading Torch model."}},torch.T7Reader=class{constructor(t,n){if(this._callback=n,this._memo=new Map,this._registry={},this._registry["bnn.Binary"]=function(t){t.nn(this)},this._registry["bnn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["cudnn.BatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.ReLU"]=function(t){t.nn(this)},this._registry["cudnn.Sigmoid"]=function(t){t.nn(this)},this._registry["cudnn.SoftMax"]=function(t){t.nn(this)},this._registry["cudnn.LogSoftMax"]=function(t){t.nn(this)},this._registry["cudnn.SpatialAveragePooling"]=function(t){t.nn(this)},this._registry["cudnn.SpatialBatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["cudnn.SpatialFullConvolution"]=function(t){t.nn(this)},this._registry["cudnn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["cudnn.SpatialSoftMax"]=function(t){t.nn(this)},this._registry["cudnn.Tanh"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricAveragePooling"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricBatchNormalization"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricConvolution"]=function(t){t.nn(this)},this._registry["cudnn.VolumetricMaxPooling"]=function(t){t.nn(this)},this._registry.Dict=function(t){t.nn(this)},this._registry["inn.ConstAffine"]=function(t){t.nn(this)},this._registry["inn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["nn.Abs"]=function(t){t.nn(this)},this._registry["nn.AddConstant"]=function(t){t.nn(this)},this._registry["nn.BatchNormalization"]=function(t){t.nn(this)},this._registry["nn.BilinearSamplerBHWD"]=function(t){t.nn(this)},this._registry["nn.BinActiveZ"]=function(t){t.nn(this)},this._registry["nn.BCECriterion"]=function(t){t.nn(this)},this._registry["nn.CMul"]=function(t){t.nn(this)},this._registry["nn.CAddTable"]=function(t){t.nn(this)},this._registry["nn.CDivTable"]=function(t){t.nn(this)},this._registry["nn.CMulTable"]=function(t){t.nn(this)},this._registry["nn.CSubTable"]=function(t){t.nn(this)},this._registry["nn.Concat"]=function(t){t.nn(this)},this._registry["nn.Copy"]=function(t){t.nn(this)},this._registry["nn.ConcatTable"]=function(t){t.nn(this)},this._registry["nn.Contiguous"]=function(t){t.nn(this)},this._registry["nn.Constant"]=function(t){t.nn(this)},this._registry["nn.CostVolMulti"]=function(t){t.nn(this)},this._registry["nn.DepthConcat"]=function(t){t.nn(this)},this._registry["nn.Dropout"]=function(t){t.nn(this)},this._registry["nn.Exp"]=function(t){t.nn(this)},this._registry["nn.ExpOut"]=function(t){t.nn(this)},this._registry["nn.FlattenTable"]=function(t){t.nn(this)},this._registry["nn.GenNoise"]=function(t){t.nn(this)},this._registry["nn.Identity"]=function(t){t.nn(this)},this._registry["nn.Index"]=function(t){t.nn(this)},this._registry["nn.Inception"]=function(t){t.nn(this)},this._registry["nn.InstanceNormalization"]=function(t){t.nn(this)},this._registry["nn.JoinTable"]=function(t){t.nn(this)},this._registry["nn.JointTrain"]=function(t){t.nn(this)},this._registry["nn.KeypointCoordinate"]=function(t){t.nn(this)},this._registry["nn.LeakyReLU"]=function(t){t.nn(this)},this._registry["nn.Linear"]=function(t){t.nn(this)},this._registry["nn.LinearNoBias"]=function(t){t.nn(this)},this._registry["nn.LogSoftMax"]=function(t){t.nn(this)},this._registry["nn.LookupTable"]=function(t){t.nn(this)},this._registry["nn.LSTM"]=function(t){t.nn(this)},this._registry["nn.MaskZero"]=function(t){t.nn(this)},this._registry["nn.MapTable"]=function(t){t.nn(this)},this._registry["nn.Max"]=function(t){t.nn(this)},this._registry["nn.Mean"]=function(t){t.nn(this)},this._registry["nn.Min"]=function(t){t.nn(this)},this._registry["nn.MulConstant"]=function(t){t.nn(this)},this._registry["nn.MM"]=function(t){t.nn(this)},this._registry["nn.MSECriterion"]=function(t){t.nn(this)},this._registry["nn.Narrow"]=function(t){t.nn(this)},this._registry["nn.NarrowTable"]=function(t){t.nn(this)},this._registry["nn.Normalize"]=function(t){t.nn(this)},this._registry["nn.Normalize2"]=function(t){t.nn(this)},this._registry["nn.NoiseFill"]=function(t){t.nn(this)},this._registry["nn.Padding"]=function(t){t.nn(this)},this._registry["nn.Parallel"]=function(t){t.nn(this)},this._registry["nn.ParallelCriterion"]=function(t){t.nn(this)},this._registry["nn.ParallelTable"]=function(t){t.nn(this)},this._registry["nn.PixelShuffle"]=function(t){t.nn(this)},this._registry["nn.Power"]=function(t){t.nn(this)},this._registry["nn.PReLU"]=function(t){t.nn(this)},this._registry["nn.Recursor"]=function(t){t.nn(this)},this._registry["nn.ReLU"]=function(t){t.nn(this)},this._registry["nn.Replicate"]=function(t){t.nn(this)},this._registry["nn.Reshape"]=function(t){t.nn(this)},this._registry["nn.ShaveImage"]=function(t){t.nn(this)},this._registry["nn.Select"]=function(t){t.nn(this)},this._registry["nn.SelectTable"]=function(t){t.nn(this)},this._registry["nn.Sequencer"]=function(t){t.nn(this)},this._registry["nn.Sequential"]=function(t){t.nn(this)},this._registry["nn.Sigmoid"]=function(t){t.nn(this)},this._registry["nn.Sum"]=function(t){t.nn(this)},this._registry["nn.SoftMax"]=function(t){t.nn(this)},this._registry["nn.SpatialAveragePooling"]=function(t){t.nn(this)},this._registry["nn.SpatialBatchNormalization"]=function(t){t.nn(this)},this._registry["nn.SpatialConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialConvolutionMM"]=function(t){t.nn(this)},this._registry["nn.SpatialCrossMapLRN"]=function(t){t.nn(this)},this._registry["nn.SpatialDilatedConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialDropout"]=function(t){t.nn(this)},this._registry["nn.SpatialFractionalMaxPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialFullConvolution"]=function(t){t.nn(this)},this._registry["nn.SpatialLPPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialMaxPooling"]=function(t){t.nn(this)},this._registry["nn.SpatialReflectionPadding"]=function(t){t.nn(this)},this._registry["nn.SpatialReplicationPadding"]=function(t){t.nn(this)},this._registry["nn.SpatialSoftMax"]=function(t){t.nn(this)},this._registry["nn.SpatialSubtractiveNormalization"]=function(t){t.nn(this)},this._registry["nn.SpatialUpSamplingBilinear"]=function(t){t.nn(this)},this._registry["nn.SpatialUpSamplingNearest"]=function(t){t.nn(this)},this._registry["nn.SpatialZeroPadding"]=function(t){t.nn(this)},this._registry["nn.SplitTable"]=function(t){t.nn(this)},this._registry["nn.Squeeze"]=function(t){t.nn(this)},this._registry["nn.Square"]=function(t){t.nn(this)},this._registry["nn.Sqrt"]=function(t){t.nn(this)},this._registry["nn.StereoJoin"]=function(t){t.nn(this)},this._registry["nn.Tanh"]=function(t){t.nn(this)},this._registry["nn.Transpose"]=function(t){t.nn(this)},this._registry["nn.TotalVariation"]=function(t){t.nn(this)},this._registry["nn.Unpool"]=function(t){t.nn(this)},this._registry["nn.View"]=function(t){t.nn(this)},this._registry["nn.gModule"]=function(t){t.nn(this)},this._registry["nngraph.Node"]=function(t){t.nn(this)},this._registry["graph.Edge"]=function(t){t.nn(this)},this._registry["graph.Graph"]=function(t){t.nn(this)},this._registry["torch.ByteTensor"]=function(t){t.tensor(this,"uint8")},this._registry["torch.CharTensor"]=function(t){t.tensor(this,"int8")},this._registry["torch.ShortTensor"]=function(t){t.tensor(this,"int16")},this._registry["torch.IntTensor"]=function(t){t.tensor(this,"int32")},this._registry["torch.LongTensor"]=function(t){t.tensor(this,"int64")},this._registry["torch.FloatTensor"]=function(t){t.tensor(this,"float32")},this._registry["torch.DoubleTensor"]=function(t){t.tensor(this,"float64")},this._registry["torch.CudaByteTensor"]=function(t){t.tensor(this,"uint8")},this._registry["torch.CudaCharTensor"]=function(t){t.tensor(this,"int8")},this._registry["torch.CudaShortTensor"]=function(t){t.tensor(this,"int16")},this._registry["torch.CudaIntTensor"]=function(t){t.tensor(this,"int32")},this._registry["torch.CudaLongTensor"]=function(t){t.tensor(this,"int64")},this._registry["torch.CudaTensor"]=function(t){t.tensor(this,"float32")},this._registry["torch.CudaDoubleTensor"]=function(t){t.tensor(this,"float64")},this._registry["torch.ByteStorage"]=function(t){t.storage(this,"uint8",1)},this._registry["torch.CharStorage"]=function(t){t.storage(this,"int8",1)},this._registry["torch.ShortStorage"]=function(t){t.storage(this,"int16",2)},this._registry["torch.IntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.LongStorage"]=function(t){t.storage(this,"int64",8)},this._registry["torch.FloatStorage"]=function(t){t.storage(this,"float32",4)},this._registry["torch.DoubleStorage"]=function(t){t.storage(this,"float64",8)},this._registry["torch.CudaByteStorage"]=function(t){t.storage(this,"uint8",1)},this._registry["torch.CudaCharStorage"]=function(t){t.storage(this,"int8",1)},this._registry["torch.CudaShortStorage"]=function(t){t.storage(this,"int16",2)},this._registry["torch.CudaIntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.CudaLongStorage"]=function(t){t.storage(this,"int64",8)},this._registry["torch.CudaIntStorage"]=function(t){t.storage(this,"int32",4)},this._registry["torch.CudaStorage"]=function(t){t.storage(this,"float32",4)},this._registry["torch.CudaFloatStorage"]=function(t){t.storage(this,"float64",8)},this._registry["w2nn.AuxiliaryLossTable"]=function(t){t.nn(this)},this._registry["w2nn.InplaceClip01"]=function(t){t.nn(this)},this._registry["w2nn.ScaleTable"]=function(t){t.nn(this)},0==t.length)throw new torch.Error("File is empty.");t[0]<=8?this._reader=new torch.BinaryReader(t):(this._reader=new torch.TextReader(t),this._reader.int32(),this._reader.reset())}read(){const t=this.int32();switch(t){case 0:return null;case 1:return this.float64();case 2:return this.string();case 3:return this.table();case 4:return this.object();case 5:return this.boolean();case 6:case 7:case 8:return this.function();default:throw new torch.Error("File format has invalid type '"+t+"'.")}}boolean(){return this._reader.boolean()}bytes(t){return this._reader.bytes(t)}int32(){return this._reader.int32()}int64(){return this._reader.int64()}int64s(t){return this._reader.int64s(t)}float64(){return this._reader.float64()}string(){return this._reader.string()}object(){const t=this.int32();if(this._memo.has(t))return this._memo.get(t);let n=this.string(),i=null;n.startsWith("V ")?(i=this.string(),n=Number(n.split(" ")[1])):(i=n,n=0);const e={__type__:i};this._memo.set(t,e);let s=this._registry[i];return s?s.apply(e,[this,n]):(s=this._callback(i),s&&s.apply(e,[this,n]),this.nn(e)),e}table(){const t=this.int32();if(this._memo.has(t))return this._memo.get(t);const n={};this._memo.set(t,n);const i=this.int32();let e=!0,s=0;for(let t=0;t=0?s+=t:e=!1}const r=Object.keys(n).length;if(e&&r*(r+1)==2*s){const i=[];for(let t=0;tthis._buffer.length)throw new torch.Error("Expected "+(this._position-this._buffer.length)+" more bytes. The file might be corrupted. Unexpected end of file.")}boolean(){return 1==this.int32()}bytes(t){const n=this._position;return this.skip(t),this._buffer.subarray(n,this._position)}int8(){const t=this._position;return this.skip(1),this._dataView.getInt8(t,!0)}int16(){const t=this._position;return this.skip(2),this._dataView.getInt16(t,!0)}int32(){const t=this._position;return this.skip(4),this._dataView.getInt32(t,!0)}int64(){const t=this._position;this.skip(8);const n=this._dataView.getUint32(t,!0),i=this._dataView.getUint32(t+4,!0);return new long.Long(n,i,!1).toNumber()}int64s(t){const n=[];for(let i=0;i-1;){if(this._buffer[this._position++]==this._separator)return this._buffer.slice(n,this._position-1);if(this._position==this._buffer.length)return this._buffer.slice(n,this._position);t--}throw new torch.Error("Line exceeded maximum length.")}boolean(){return 1==this.int32()}bytes(t){return this.line(t)}int8(){return this.int64()}int16(){return this.int64()}int32(){return this.int64()}int64(){const t=this._textDecoder.decode(this.line(20)),n=Number.parseInt(t,10);if(Number.isNaN(t-n))throw new torch.Error("Couldn't parse int64 '"+t+"'.");return n}int64s(t){const n=[];if(t>0){const t=this._textDecoder.decode(this.line(Number.MAX_SAFE_INTEGER));for(const i of t.split(" ")){const t=Number.parseInt(i,10);if(Number.isNaN(i-t))throw new torch.Error("Couldn't parse int64 '"+i+"'.");n.push(t)}}return n}float32(){return this.float64()}float64(){const t=this._textDecoder.decode(this.line(24));if(t.startsWith("-nan"))return NaN;if(t.startsWith("nan"))return NaN;if(t.startsWith("inf"))return 1/0;if(t.startsWith("-inf"))return-1/0;const n=Number.parseFloat(t);if(Number.isNaN(t-n))throw new torch.Error("Couldn't parse float '"+t+"'.");return n}string(){const t=this.int32();if(0==t)return"";const n=this.line(t),i=this._textDecoder.decode(n);if(t!=i.length)throw torch.Error("Invalid text length.");return i}storage(t,n,i){if(t<=0)throw new torch.Error("Unsupported storage size '"+t+"'.");if("uint8"===i){const n=this._position;this._position+=t;const i=this._buffer.slice(n,this._position);return this.line(0),new torch.BinaryReader(i)}const e=this.line(Number.MAX_SAFE_INTEGER);return new torch.TextReader(e,32)}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=torch.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-metadata.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1919181ad65f07bb4574c0ebdacb50a14d8379a8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-metadata.json @@ -0,0 +1 @@ +[{"name":"Activation","schema":{"category":"Activation","inputs":[{"name":"input"}]}},{"name":"Binary","schema":{"inputs":[{"name":"x"},{"name":"y"}]}},{"name":"Unary","schema":{"inputs":[{"name":"input"}]}},{"name":"Conv","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"kernel"}]}},{"name":"FullyConnected","schema":{"category":"Layer","inputs":[{"name":"input"},{"name":"weights"}]}},{"name":"Reshape","schema":{"category":"Shape","inputs":[{"name":"input"},{"name":"shape"}]}},{"name":"StridedSlice","schema":{"category":"Tensor","inputs":[{"name":"input"},{"name":"begin"},{"name":"end"},{"name":"strides"}]}},{"name":"Squeeze","schema":{"category":"Transform"}},{"name":"BatchNorm","schema":{"category":"Normalization","inputs":[{"name":"input"},{"name":"gamma"},{"name":"beta"},{"name":"moving_mean"},{"name":"moving_variance"}]}},{"name":"Pool","schema":{"category":"Pool","inputs":[{"name":"input"}]}},{"name":"_MaxPool","schema":{"category":"Pool","inputs":[{"name":"input"}]}},{"name":"Concat","schema":{"category":"Tensor"}},{"name":"Flatten","schema":{"category":"Shape"}},{"name":"GatherV2","schema":{"category":"Data","inputs":[{"name":"input"},{"name":"indices"}]}}] \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-proto.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-proto.js new file mode 100644 index 0000000000000000000000000000000000000000..087812e9dd8ba63e5d1dabebbbb3a8f44d2dbc64 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff-proto.js @@ -0,0 +1 @@ +var $root=protobuf.get("uff");$root.uff={},$root.uff.MetaGraph=class{constructor(){this.descriptors=[],this.graphs=[],this.referenced_data=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.MetaGraph,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.version=e.int64();break;case 2:r.descriptor_core_version=e.int64();break;case 3:r.descriptors.push($root.uff.Descriptor.decode(e,e.uint32()));break;case 4:r.graphs.push($root.uff.Graph.decode(e,e.uint32()));break;case 5:r.referenced_data.push($root.uff.MetaGraph.ReferencedDataEntry.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.MetaGraph.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph;for(e.start();!e.end();){const r=e.tag();switch(r){case"version":t.version=e.integer();break;case"descriptor_core_version":t.descriptor_core_version=e.integer();break;case"descriptors":t.descriptors.push($root.uff.Descriptor.decodeText(e,!0));break;case"graphs":t.graphs.push($root.uff.Graph.decodeText(e,!0));break;case"referenced_data":t.referenced_data.push($root.uff.MetaGraph.ReferencedDataEntry.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.MetaGraph.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.MetaGraph.prototype.descriptor_core_version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.MetaGraph.ReferencedDataEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.MetaGraph.ReferencedDataEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph.ReferencedDataEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.ReferencedDataEntry.prototype.key="",$root.uff.MetaGraph.ReferencedDataEntry.prototype.value=null,$root.uff.MetaGraph.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.MetaGraph.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.MetaGraph.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.MetaGraph.ExtraFieldsEntry.prototype.key="",$root.uff.MetaGraph.ExtraFieldsEntry.prototype.value=null,$root.uff.Descriptor=class{constructor(){}static decode(e,t){const r=new $root.uff.Descriptor,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.version=e.int64();break;case 3:r.optional=e.bool();break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Descriptor;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"version":t.version=e.integer();break;case"optional":t.optional=e.boolean();break;default:e.field(r,t)}}return t}},$root.uff.Descriptor.prototype.id="",$root.uff.Descriptor.prototype.version=protobuf.Long?protobuf.Long.fromBits(0,0,!1):0,$root.uff.Descriptor.prototype.optional=!1,$root.uff.Graph=class{constructor(){this.nodes=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.Graph,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.nodes.push($root.uff.Node.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.Graph.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Graph;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"nodes":t.nodes.push($root.uff.Node.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.Graph.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.Graph.prototype.id="",$root.uff.Graph.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Graph.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Graph.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Graph.ExtraFieldsEntry.prototype.key="",$root.uff.Graph.ExtraFieldsEntry.prototype.value=null,$root.uff.Node=class{constructor(){this.inputs=[],this.fields=[],this.extra_fields=[]}static decode(e,t){const r=new $root.uff.Node,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.id=e.string();break;case 2:r.inputs.push(e.string());break;case 3:r.operation=e.string();break;case 4:r.fields.push($root.uff.Node.FieldsEntry.decode(e,e.uint32()));break;case 100:r.extra_fields.push($root.uff.Node.ExtraFieldsEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node;for(e.start();!e.end();){const r=e.tag();switch(r){case"id":t.id=e.string();break;case"inputs":e.array(t.inputs,(()=>e.string()));break;case"operation":t.operation=e.string();break;case"fields":t.fields.push($root.uff.Node.FieldsEntry.decodeText(e,!0));break;case"extra_fields":t.extra_fields.push($root.uff.Node.ExtraFieldsEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.Node.prototype.id="",$root.uff.Node.prototype.operation="",$root.uff.Node.FieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Node.FieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node.FieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Node.FieldsEntry.prototype.key="",$root.uff.Node.FieldsEntry.prototype.value=null,$root.uff.Node.ExtraFieldsEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.Node.ExtraFieldsEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=$root.uff.Data.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Node.ExtraFieldsEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.string();break;case"value":t.value=$root.uff.Data.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.Node.ExtraFieldsEntry.prototype.key="",$root.uff.Node.ExtraFieldsEntry.prototype.value=null,$root.uff.Data=class{constructor(){}get type(){return $root.uff.Data.typeSet=$root.uff.Data.typeSet||new Set(["s","s_list","d","d_list","b","b_list","i","i_list","blob","ref","dtype","dtype_list","dim_orders","dim_orders_list"]),Object.keys(this).find((e=>$root.uff.Data.typeSet.has(e)&&null!=this[e]))}static decode(e,t){const r=new $root.uff.Data,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.s=e.string();break;case 2:r.s_list=$root.uff.ListString.decode(e,e.uint32());break;case 3:r.d=e.double();break;case 4:r.d_list=$root.uff.ListDouble.decode(e,e.uint32());break;case 5:r.b=e.bool();break;case 6:r.b_list=$root.uff.ListBool.decode(e,e.uint32());break;case 7:r.i=e.int64();break;case 8:r.i_list=$root.uff.ListInt64.decode(e,e.uint32());break;case 9:r.blob=e.bytes();break;case 100:r.ref=e.string();break;case 101:r.dtype=e.int32();break;case 102:r.dtype_list=$root.uff.ListDataType.decode(e,e.uint32());break;case 103:r.dim_orders=$root.uff.DimensionOrders.decode(e,e.uint32());break;case 104:r.dim_orders_list=$root.uff.ListDimensionOrders.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.Data;for(e.start();!e.end();){const r=e.tag();switch(r){case"s":t.s=e.string();break;case"s_list":t.s_list=$root.uff.ListString.decodeText(e,!0);break;case"d":t.d=e.float();break;case"d_list":t.d_list=$root.uff.ListDouble.decodeText(e,!0);break;case"b":t.b=e.boolean();break;case"b_list":t.b_list=$root.uff.ListBool.decodeText(e,!0);break;case"i":t.i=e.integer();break;case"i_list":t.i_list=$root.uff.ListInt64.decodeText(e,!0);break;case"blob":t.blob=e.bytes();break;case"ref":t.ref=e.string();break;case"dtype":t.dtype=e.enum($root.uff.DataType);break;case"dtype_list":t.dtype_list=$root.uff.ListDataType.decodeText(e,!0);break;case"dim_orders":t.dim_orders=$root.uff.DimensionOrders.decodeText(e,!0);break;case"dim_orders_list":t.dim_orders_list=$root.uff.ListDimensionOrders.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.DataType={DT_INVALID:0,DT_INT8:65544,DT_INT16:65552,DT_INT32:65568,DT_INT64:65600,DT_FLOAT16:131088,DT_FLOAT32:131104},$root.uff.OrderEnum={OE_ZERO:0,OE_SPECIAL:-1,OE_INCREMENT:2147483647,OE_DECREMENT:-2147483648},$root.uff.DimensionOrders=class{constructor(){this.orders=[]}static decode(e,t){const r=new $root.uff.DimensionOrders,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.orders.push($root.uff.DimensionOrders.OrdersEntry.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.DimensionOrders;for(e.start();!e.end();){const r=e.tag();switch(r){case"orders":t.orders.push($root.uff.DimensionOrders.OrdersEntry.decodeText(e,!0));break;default:e.field(r,t)}}return t}},$root.uff.DimensionOrders.OrdersEntry=class{constructor(){}static decode(e,t){const r=new $root.uff.DimensionOrders.OrdersEntry,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.key=e.int32();break;case 2:r.value=$root.uff.ListInt64.decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.DimensionOrders.OrdersEntry;for(e.start();!e.end();){const r=e.tag();switch(r){case"key":t.key=e.enum($root.uff.OrderEnum);break;case"value":t.value=$root.uff.ListInt64.decodeText(e,!0);break;default:e.field(r,t)}}return t}},$root.uff.DimensionOrders.OrdersEntry.prototype.key=0,$root.uff.DimensionOrders.OrdersEntry.prototype.value=null,$root.uff.ListString=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListString,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val.push(e.string());break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListString;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.string()));break;default:e.field(r,t)}}return t}},$root.uff.ListDouble=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDouble,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.doubles(r.val,t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDouble;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.float()));break;default:e.field(r,t)}}return t}},$root.uff.ListBool=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListBool,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.bool()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListBool;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.boolean()));break;default:e.field(r,t)}}return t}},$root.uff.ListInt64=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListInt64,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.int64()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListInt64;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.integer()));break;default:e.field(r,t)}}return t}},$root.uff.ListDataType=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDataType,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val=e.array(r.val,(()=>e.int32()),t);break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDataType;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":e.array(t.val,(()=>e.enum($root.uff.DataType)));break;default:e.field(r,t)}}return t}},$root.uff.ListDimensionOrders=class{constructor(){this.val=[]}static decode(e,t){const r=new $root.uff.ListDimensionOrders,o=e.next(t);for(;e.end(o);){const t=e.uint32();switch(t>>>3){case 1:r.val.push($root.uff.DimensionOrders.decode(e,e.uint32()));break;default:e.skipType(7&t)}}return r}static decodeText(e){const t=new $root.uff.ListDimensionOrders;for(e.start();!e.end();){const r=e.tag();switch(r){case"val":t.val.push($root.uff.DimensionOrders.decodeText(e,!0));break;default:e.field(r,t)}}return t}}; \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff.js new file mode 100644 index 0000000000000000000000000000000000000000..811450868efdd49c58447865a957d9333c4d6b16 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/uff.js @@ -0,0 +1 @@ +var uff=uff||{},base=base||require("./base"),long=long||{Long:require("long")},protobuf=protobuf||require("./protobuf");uff.ModelFactory=class{match(t){const e=t.identifier,s=e.split(".").pop().toLowerCase();if("uff"===s||"pb"===s){const e=t.tags("pb");if(e.size>0&&e.has(1)&&0===e.get(1)&&e.has(2)&&0===e.get(2)&&e.has(3)&&2===e.get(3)&&e.has(4)&&2===e.get(4)&&e.has(5)&&2===e.get(5))return!0}if("pbtxt"===s||e.toLowerCase().endsWith(".uff.txt")){const e=t.tags("pbtxt");if(e.has("version")&&e.has("descriptors")&&e.has("graphs"))return!0}return!1}open(t,e){return e.require("./uff-proto").then((()=>{let s=null;const a=t.identifier;if("pbtxt"===a.split(".").pop().toLowerCase()||a.toLowerCase().endsWith(".uff.txt"))try{uff.proto=protobuf.get("uff").uff;const e=protobuf.TextReader.create(t.text);s=uff.proto.MetaGraph.decodeText(e)}catch(t){throw new uff.Error("File text format is not uff.MetaGraph ("+t.message+") in '"+a+"'.")}else try{uff.proto=protobuf.get("uff").uff;const e=protobuf.Reader.create(t.buffer);s=uff.proto.MetaGraph.decode(e)}catch(t){throw new uff.Error("File format is not uff.MetaGraph ("+t.message+") in '"+a+"'.")}return uff.Metadata.open(e).then((t=>{try{return new uff.Model(t,s)}catch(t){e.exception(t,!1);const s=t&&t.message?t.message:t.toString();throw new uff.Error(s.replace(/\.$/,"")+" in '"+a+"'.")}}))}))}},uff.Model=class{constructor(t,e){this._version=e.version,this._imports=e.descriptors.map((t=>t.id+" v"+t.version.toString())).join(", ");const s=new Map(e.referenced_data.map((t=>[t.key,t.value])));for(const t of e.graphs)for(const e of t.nodes)for(const t of e.fields)"ref"===t.value.type&&s.has(t.value.ref)&&(t.value=s.get(t.value.ref));this._graphs=e.graphs.map((e=>new uff.Graph(t,e)))}get format(){return"UFF"+(this._version?" v"+this._version.toString():"")}get imports(){return this._imports}get graphs(){return this._graphs}},uff.Graph=class{constructor(t,e){this._name=e.id,this._inputs=[],this._outputs=[],this._nodes=[];const s=new Map,a=new Map;for(const t of e.nodes){for(const e of t.inputs)a.set(e,a.has(e)?a.get(e)+1:1),s.set(e,new uff.Argument(e));s.has(t.id)||s.set(t.id,new uff.Argument(t.id))}for(let t=e.nodes.length-1;t>=0;t--){const n=e.nodes[t];if("Const"===n.operation&&0===n.inputs.length&&1===a.get(n.id)){const a={};for(const t of n.fields)a[t.key]=t.value;if(a.dtype&&a.shape&&a.values){const i=new uff.Tensor(a.dtype,a.shape,a.values);s.set(n.id,new uff.Argument(n.id,i.type,i)),e.nodes.splice(t,1)}}if("Input"===n.operation&&0===n.inputs.length){const t={};for(const e of n.fields)t[e.key]=e.value;const e=t.dtype&&t.shape?new uff.TensorType(t.dtype,t.shape):null;s.set(n.id,new uff.Argument(n.id,e,null))}}for(const a of e.nodes)"Input"!==a.operation?"MarkOutput"!==a.operation||1!==a.inputs.length?this._nodes.push(new uff.Node(t,a,s)):this._outputs.push(new uff.Parameter(a.id,[s.get(a.inputs[0])])):this._inputs.push(new uff.Parameter(a.id,[s.get(a.id)]))}get name(){return this._name}get inputs(){return this._inputs}get outputs(){return this._outputs}get nodes(){return this._nodes}},uff.Parameter=class{constructor(t,e){this._name=t,this._arguments=e}get name(){return this._name}get visible(){return!0}get arguments(){return this._arguments}},uff.Argument=class{constructor(t,e,s){if("string"!=typeof t)throw new uff.Error("Invalid argument identifier '"+JSON.stringify(t)+"'.");this._name=t,this._type=e||null,this._initializer=s||null}get name(){return this._name}get type(){return this._type}get initializer(){return this._initializer}},uff.Node=class{constructor(t,e,s){this._name=e.id,this._operation=e.operation,this._metadata=t.type(e.operation),this._attributes=[],this._inputs=[],this._outputs=[];const a=t.type(e.operation);if(e.inputs&&e.inputs.length>0){let t=0;if(a&&a.inputs)for(const n of a.inputs)if(ts.get(t)));t+=a,this._inputs.push(new uff.Parameter(n.name,i))}this._inputs=this._inputs.concat(e.inputs.slice(t).map(((e,a)=>{const n=t+a==0?"input":(t+a).toString();return new uff.Parameter(n,[s.get(e)])})))}this._outputs.push(new uff.Parameter("output",[s.get(e.id)]));for(const s of e.fields)this._attributes.push(new uff.Attribute(t.attribute(this._operation,s.key),s.key,s.value))}get name(){return this._name}get type(){return this._operation}get metadata(){return this._metadata}get inputs(){return this._inputs}get outputs(){return this._outputs}get attributes(){return this._attributes}},uff.Attribute=class{constructor(t,e,s){switch(this._name=e,s.type){case"s":this._value=s.s,this._type="string";break;case"s_list":this._value=s.s_list,this._type="string[]";break;case"d":this._value=s.d,this._type="float64";break;case"d_list":this._value=s.d_list.val,this._type="float64[]";break;case"i":this._value=s.i,this._type="int64";break;case"i_list":this._value=s.i_list.val,this._type="int64[]";break;case"b":this._value=s.b,this._type="boolean";break;case"b_list":this._value=s.b_list,this._type="boolean[]";break;case"blob":this._value=s.blob;break;case"dtype":this._value=new uff.TensorType(s,null).dataType;break;case"dim_orders_list":this._value=s.dim_orders_list.val;break;default:throw new uff.Error("Unknown attribute '"+e+"'format '"+JSON.stringify(s)+"'.")}}get type(){return this._type}get name(){return this._name}get value(){return this._value}},uff.Tensor=class{constructor(t,e,s){switch(this._type=new uff.TensorType(t,e),s.type){case"blob":this._data=s.blob;break;default:throw new uff.Error("Unknown values format '"+JSON.stringify(s.type)+"'.")}}get kind(){return"Const"}get type(){return this._type}get state(){return this._context().state}get value(){const t=this._context();return t.state?null:(t.limit=Number.MAX_SAFE_INTEGER,this._decode(t,0))}toString(){const t=this._context();if(t.state)return"";t.limit=1e4;const e=this._decode(t,0);return JSON.stringify(e,null,4)}_context(){const t={state:null,index:0,count:0};return null==this._data||this._data.length>8&&40===this._data[0]&&46===this._data[1]&&46===this._data[2]&&46===this._data[3]&&41===this._data[this._data.length-1]&&46===this._data[this._data.length-2]&&46===this._data[this._data.length-3]&&46===this._data[this._data.length-4]?(t.state="Tensor data is empty.",t):(t.dataType=this._type.dataType,t.shape=this._type.shape.dimensions,t.data=new DataView(this._data.buffer,this._data.byteOffset,this._data.byteLength),t)}_decode(t,e){const s=0==t.shape.length?[1]:t.shape,a=s[e],n=[];if(e==s.length-1)for(let e=0;et.limit)return n.push("..."),n;switch(t.dataType){case"int8":n.push(t.data.getInt8(t.index)),t.index+=1,t.count++;break;case"int16":n.push(t.data.getInt16(t.index)),t.index+=2,t.count++;break;case"int32":n.push(t.data.getInt32(t.index,!0)),t.index+=4,t.count++;break;case"int64":n.push(new long.Long(t.data.getUint32(t.index,!0),t.data.getUint32(t.index+4,!0),!1)),t.index+=8,t.count++;break;case"float16":n.push(t.data.getFloat16(t.index,!0)),t.index+=2,t.count++;break;case"float32":n.push(t.data.getFloat32(t.index,!0)),t.index+=4,t.count++}}else for(let s=0;st.limit)return n.push("..."),n;n.push(this._decode(t,e+1))}return 0==t.shape.length?n[0]:n}},uff.TensorType=class{constructor(t,e){if("dtype"!==t.type)throw new uff.Error("Unknown data type format '"+JSON.stringify(t.type)+"'.");switch(t.dtype){case uff.proto.DataType.DT_INT8:this._dataType="int8";break;case uff.proto.DataType.DT_INT16:this._dataType="int16";break;case uff.proto.DataType.DT_INT32:this._dataType="int32";break;case uff.proto.DataType.DT_INT64:this._dataType="int64";break;case uff.proto.DataType.DT_FLOAT16:this._dataType="float16";break;case uff.proto.DataType.DT_FLOAT32:this._dataType="float32";break;default:throw new uff.Error("Unknown data type '"+JSON.stringify(t)+"'.")}this._shape=e?new uff.TensorShape(e):null}get dataType(){return this._dataType}get shape(){return this._shape}toString(){return this.dataType+this._shape.toString()}},uff.TensorShape=class{constructor(t){if("i_list"!==t.type)throw new uff.Error("Unknown shape format '"+JSON.stringify(t.type)+"'.");this._dimensions=t.i_list.val}get dimensions(){return this._dimensions}toString(){return this._dimensions&&0!=this._dimensions.length?"["+this._dimensions.join(",")+"]":""}},uff.Metadata=class{static open(t){return uff.Metadata._metadata?Promise.resolve(uff.Metadata._metadata):t.request(null,"uff-metadata.json","utf-8").then((t=>(uff.Metadata._metadata=new uff.Metadata(t),uff.Metadata._metadata))).catch((()=>(uff.Metadata._metadata=new uff.Metadata(null),uff.Metadata._metadata)))}constructor(t){if(this._map=new Map,this._attributeCache=new Map,t){const e=JSON.parse(t);if(e)for(const t of e)t.name&&t.schema&&(t.schema.name=t.name,this._map.set(t.name,t.schema))}}type(t){return this._map.get(t)}attribute(t,e){const s=t+":"+e;if(!this._attributeCache.has(s)){const e=this.type(t);if(e&&e.attributes&&e.attributes.length>0)for(const s of e.attributes)this._attributeCache.set(t+":"+s.name,s);this._attributeCache.has(s)||this._attributeCache.set(s,null)}return this._attributeCache.get(s)}},uff.Error=class extends Error{constructor(t){super(t),this.name="Error loading UFF model."}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.ModelFactory=uff.ModelFactory); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/vendors.8575cdbcf0e4a1a337e2.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/vendors.8575cdbcf0e4a1a337e2.js new file mode 100644 index 0000000000000000000000000000000000000000..2e3abd6576dbf4674bffbf463e6e411abd0158da --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/vendors.8575cdbcf0e4a1a337e2.js @@ -0,0 +1 @@ +(globalThis.webpackChunk_visualdl_netron2=globalThis.webpackChunk_visualdl_netron2||[]).push([[216],{81666:(t,e,n)=>{"use strict";function r(t,e){return te?1:t>=e?0:NaN}n.d(e,{Z:()=>r})},50533:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81666);function i(t){var e;return 1===t.length&&(e=t,t=function(t,n){return(0,r.Z)(e(t),n)}),{left:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)<0?r=a+1:i=a}return r},right:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)>0?i=a:r=a+1}return r}}}},53047:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},34825:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(98193);function i(t,e,n){var i,a,o,u,s=t.length,c=e.length,f=new Array(s*c);for(null==n&&(n=r.$),i=o=0;i{"use strict";function r(t,e){return et?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},34398:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(48347);function i(t,e){var n=(0,r.Z)(t,e);return n?Math.sqrt(n):n}},66804:(t,e,n)=>{"use strict";function r(t,e){var n,r,i,a=t.length,o=-1;if(null==e){for(;++o=n)for(r=i=n;++on&&(r=n),i=n)for(r=i=n;++on&&(r=n),ir})},13932:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},58470:(t,e,n)=>{"use strict";n.d(e,{j2:()=>r.Z,b4:()=>s,Nw:()=>u,ml:()=>o,YF:()=>i.Z,kC:()=>c.Z,$1:()=>f.Z,P3:()=>l.Z,We:()=>h.Z,KX:()=>E,Fp:()=>F.Z,J6:()=>B.Z,C2:()=>S.Z,TS:()=>N.Z,VV:()=>T.Z,X:()=>z.Z,FO:()=>O.Z,VR:()=>j.Z,w6:()=>b.Z,Rp:()=>R.Z,TV:()=>P.Z,Sm:()=>I.Z,o6:()=>C,FA:()=>M.Z,_X:()=>k.Z,G9:()=>Z,ly:()=>D,sd:()=>w,p4:()=>L.Z,CA:()=>U.Z,$R:()=>$.Z});var r=n(81666),i=n(50533),a=(0,i.Z)(r.Z),o=a.right,u=a.left;const s=o;var c=n(34825),f=n(62758),l=n(34398),h=n(66804),d=Array.prototype,p=d.slice,v=d.map,g=n(53047),_=n(13932),b=n(24228),y=Math.sqrt(50),m=Math.sqrt(10),x=Math.sqrt(2);function w(t,e,n){var r,i,a,o,u=-1;if(n=+n,(t=+t)==(e=+e)&&n>0)return[t];if((r=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++u=0?(a>=y?10:a>=m?5:a>=x?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=y?10:a>=m?5:a>=x?2:1)}function D(t,e,n){var r=Math.abs(e-t)/Math.max(0,n),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=y?i*=10:a>=m?i*=5:a>=x&&(i*=2),el;)h.pop(),--d;var p,v=new Array(d+1);for(i=0;i<=d;++i)(p=v[i]=[]).x0=i>0?h[i-1]:f,p.x1=i{"use strict";function r(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++ar&&(r=n)}else for(;++a=n)for(r=n;++ar&&(r=n);return r}n.d(e,{Z:()=>r})},23490:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e){var n,i=t.length,a=i,o=-1,u=0;if(null==e)for(;++o{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(81666);if(826==n.j)var i=n(8895);if(826==n.j)var a=n(80463);function o(t,e){var n,o=t.length,u=-1,s=[];if(null==e)for(;++u{"use strict";function r(t){for(var e,n,r,i=t.length,a=-1,o=0;++a=0;)for(e=(r=t[i]).length;--e>=0;)n[--o]=r[e];return n}n.d(e,{Z:()=>r})},27566:(t,e,n)=>{"use strict";function r(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++an&&(r=n)}else for(;++a=n)for(r=n;++an&&(r=n);return r}n.d(e,{Z:()=>r})},8895:(t,e,n)=>{"use strict";function r(t){return null===t?NaN:+t}n.d(e,{Z:()=>r})},98193:(t,e,n)=>{"use strict";function r(t,e){null==e&&(e=i);for(var n=0,r=t.length-1,a=t[0],o=new Array(r<0?0:r);nr,$:()=>i})},71756:(t,e,n)=>{"use strict";function r(t,e){for(var n=e.length,r=new Array(n);n--;)r[n]=t[e[n]];return r}n.d(e,{Z:()=>r})},80463:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e,n){if(null==n&&(n=r.Z),i=t.length){if((e=+e)<=0||i<2)return+n(t[0],0,t);if(e>=1)return+n(t[i-1],i-1,t);var i,a=(i-1)*e,o=Math.floor(a),u=+n(t[o],o,t);return u+(+n(t[o+1],o+1,t)-u)*(a-o)}}},24228:(t,e,n)=>{"use strict";function r(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=0|Math.max(0,Math.ceil((e-t)/n)),a=new Array(i);++rr})},68691:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81666);function i(t,e){if(n=t.length){var n,i,a=0,o=0,u=t[o];for(null==e&&(e=r.Z);++a{"use strict";function r(t,e,n){for(var r,i,a=(null==n?t.length:n)-(e=null==e?0:+e);a;)i=Math.random()*a--|0,r=t[a+e],t[a+e]=t[i+e],t[i+e]=r;return t}n.d(e,{Z:()=>r})},42507:(t,e,n)=>{"use strict";function r(t,e){var n,r=t.length,i=-1,a=0;if(null==e)for(;++ir})},34416:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(34398);function i(t,e,n){return Math.ceil((n-e)/(3.5*(0,r.Z)(t)*Math.pow(t.length,-1/3)))}},19823:(t,e,n)=>{"use strict";function r(t){return Math.ceil(Math.log(t.length)/Math.LN2)+1}n.d(e,{Z:()=>r})},93966:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(27566);function i(t){if(!(o=t.length))return[];for(var e=-1,n=(0,r.Z)(t,a),i=new Array(n);++e{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(8895);function i(t,e){var n,i,a=t.length,o=0,u=-1,s=0,c=0;if(null==e)for(;++u1)return c/(o-1)}},20446:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(93966);function i(){return(0,r.Z)(arguments)}},71603:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},41989:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},14289:(t,e,n)=>{"use strict";function r(t,e,n){this.target=t,this.type=e,this.selection=n}n.d(e,{Z:()=>r})},78459:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},96199:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},1053:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push({key:n,value:t[n]});return e}n.d(e,{Z:()=>r})},55201:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push(n);return e}n.d(e,{Z:()=>r})},7781:(t,e,n)=>{"use strict";function r(t){var e=[];for(var n in t)e.push(t[n]);return e}n.d(e,{Z:()=>r})},68847:(t,e,n)=>{"use strict";n.d(e,{Il:()=>i,xV:()=>a,J5:()=>o,ZP:()=>m,SU:()=>Z,B8:()=>D,Ss:()=>k,Ym:()=>F});var r=n(40948);function i(){}var a=.7,o=1/a,u="\\s*([+-]?\\d+)\\s*",s="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",c="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",f=/^#([0-9a-f]{3,8})$/,l=new RegExp("^rgb\\("+[u,u,u]+"\\)$"),h=new RegExp("^rgb\\("+[c,c,c]+"\\)$"),d=new RegExp("^rgba\\("+[u,u,u,s]+"\\)$"),p=new RegExp("^rgba\\("+[c,c,c,s]+"\\)$"),v=new RegExp("^hsl\\("+[s,c,c]+"\\)$"),g=new RegExp("^hsla\\("+[s,c,c,s]+"\\)$"),_={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function b(){return this.rgb().formatHex()}function y(){return this.rgb().formatRgb()}function m(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=f.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?x(e):3===n?new k(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?w(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?w(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=l.exec(t))?new k(e[1],e[2],e[3],1):(e=h.exec(t))?new k(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=d.exec(t))?w(e[1],e[2],e[3],e[4]):(e=p.exec(t))?w(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=v.exec(t))?C(e[1],e[2]/100,e[3]/100,1):(e=g.exec(t))?C(e[1],e[2]/100,e[3]/100,e[4]):_.hasOwnProperty(t)?x(_[t]):"transparent"===t?new k(NaN,NaN,NaN,0):null}function x(t){return new k(t>>16&255,t>>8&255,255&t,1)}function w(t,e,n,r){return r<=0&&(t=e=n=NaN),new k(t,e,n,r)}function Z(t){return t instanceof i||(t=m(t)),t?new k((t=t.rgb()).r,t.g,t.b,t.opacity):new k}function D(t,e,n,r){return 1===arguments.length?Z(t):new k(t,e,n,null==r?1:r)}function k(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function E(){return"#"+j(this.r)+j(this.g)+j(this.b)}function A(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function j(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function C(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new B(t,e,n,r)}function M(t){if(t instanceof B)return new B(t.h,t.s,t.l,t.opacity);if(t instanceof i||(t=m(t)),!t)return new B;if(t instanceof B)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,a=Math.min(e,n,r),o=Math.max(e,n,r),u=NaN,s=o-a,c=(o+a)/2;return s?(u=e===o?(n-r)/s+6*(n0&&c<1?0:u,new B(u,s,c,t.opacity)}function F(t,e,n,r){return 1===arguments.length?M(t):new B(t,e,n,null==r?1:r)}function B(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function S(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}(0,r.Z)(i,m,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:b,formatHex:b,formatHsl:function(){return M(this).formatHsl()},formatRgb:y,toString:y}),(0,r.Z)(k,D,(0,r.l)(i,{brighter:function(t){return t=null==t?o:Math.pow(o,t),new k(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?a:Math.pow(a,t),new k(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:E,formatHex:E,formatRgb:A,toString:A})),(0,r.Z)(B,F,(0,r.l)(i,{brighter:function(t){return t=null==t?o:Math.pow(o,t),new B(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?a:Math.pow(a,t),new B(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new k(S(t>=240?t-240:t+120,i,r),S(t,i,r),S(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}))},29607:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r=n(40948),i=n(68847),a=n(10810),o=-.14861,u=1.78277,s=-.29227,c=-.90649,f=1.97294,l=f*c,h=f*u,d=u*s-c*o;function p(t){if(t instanceof g)return new g(t.h,t.s,t.l,t.opacity);t instanceof i.Ss||(t=(0,i.SU)(t));var e=t.r/255,n=t.g/255,r=t.b/255,o=(d*r+l*e-h*n)/(d+l-h),u=r-o,p=(f*(n-o)-s*u)/c,v=Math.sqrt(p*p+u*u)/(f*o*(1-o)),_=v?Math.atan2(p,u)*a.B-120:NaN;return new g(_<0?_+360:_,v,o,t.opacity)}function v(t,e,n,r){return 1===arguments.length?p(t):new g(t,e,n,null==r?1:r)}function g(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}(0,r.Z)(g,v,(0,r.l)(i.Il,{brighter:function(t){return t=null==t?i.J5:Math.pow(i.J5,t),new g(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?i.xV:Math.pow(i.xV,t),new g(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*a.V,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),l=Math.sin(t);return new i.Ss(255*(e+n*(o*r+u*l)),255*(e+n*(s*r+c*l)),255*(e+n*(f*r)),this.opacity)}}))},40948:(t,e,n)=>{"use strict";function r(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function i(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}n.d(e,{Z:()=>r,l:()=>i})},75302:(t,e,n)=>{"use strict";if(n.d(e,{$_:()=>r.ZP,B8:()=>r.B8,Ym:()=>r.Ym,Nn:()=>i.ZP,Uc:()=>i.Uc,tW:()=>i.tW,MA:()=>i.MA,K:()=>a.Z}),826==n.j)var r=n(68847);if(826==n.j)var i=n(20966);if(826==n.j)var a=n(29607)},20966:(t,e,n)=>{"use strict";n.d(e,{MA:()=>h,ZP:()=>d,tW:()=>m,Uc:()=>x});var r=n(40948),i=n(68847),a=n(10810),o=.96422,u=.82521,s=4/29,c=6/29,f=3*c*c;function l(t){if(t instanceof p)return new p(t.l,t.a,t.b,t.opacity);if(t instanceof w)return Z(t);t instanceof i.Ss||(t=(0,i.SU)(t));var e,n,r=b(t.r),a=b(t.g),s=b(t.b),c=v((.2225045*r+.7168786*a+.0606169*s)/1);return r===a&&a===s?e=n=c:(e=v((.4360747*r+.3850649*a+.1430804*s)/o),n=v((.0139322*r+.0971045*a+.7141733*s)/u)),new p(116*c-16,500*(e-c),200*(c-n),t.opacity)}function h(t,e){return new p(t,0,0,null==e?1:e)}function d(t,e,n,r){return 1===arguments.length?l(t):new p(t,e,n,null==r?1:r)}function p(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function v(t){return t>.008856451679035631?Math.pow(t,1/3):t/f+s}function g(t){return t>c?t*t*t:f*(t-s)}function _(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function b(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function y(t){if(t instanceof w)return new w(t.h,t.c,t.l,t.opacity);if(t instanceof p||(t=l(t)),0===t.a&&0===t.b)return new w(NaN,0{"use strict";n.d(e,{V:()=>r,B:()=>i});var r=Math.PI/180,i=180/Math.PI},66847:(t,e,n)=>{"use strict";function r(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++er})},45163:(t,e,n)=>{"use strict";function r(t,e){return t-e}n.d(e,{Z:()=>r})},5109:(t,e,n)=>{"use strict";function r(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(u>=a&&(s-=t.data[u-a+o*r]),e.data[u-n+o*r]=s/Math.min(u+1,r-1+a-u,a))}function i(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(u>=a&&(s-=t.data[o+(u-a)*r]),e.data[o+(u-n)*r]=s/Math.min(u+1,i-1+a-u,a))}n.d(e,{_:()=>r,$:()=>i})},82261:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},97158:(t,e,n)=>{"use strict";function r(t,e){for(var n,r=-1,a=e.length;++rr!=p>r&&n<(d-f)*(r-l)/(p-l)+f&&(i=-i)}return i}function a(t,e,n){var r,i,a,o;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(i=t[r=+(t[0]===e[0])],a=n[r],o=e[r],i<=a&&a<=o||o<=a&&a<=i)}n.d(e,{Z:()=>r})},42451:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},65264:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r={value:function(){}};function i(){for(var t,e=0,n=arguments.length,r={};e=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function u(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;a{"use strict";if(n.d(e,{W:()=>r.Z}),826==n.j)var r=n(65264)},44223:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},44319:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>g}),826==n.j)var r=n(65264);if(826==n.j)var i=n(78011);if(826==n.j)var a=n(42637);if(826==n.j)var o=n(23475);if(826==n.j)var u=n(13171);if(826==n.j)var s=n(61062);if(826==n.j)var c=n(42254);if(826==n.j)var f=n(44223);if(826==n.j)var l=n(63932);function h(){return!i.B.ctrlKey&&!i.B.button}function d(){return this.parentNode}function p(t){return null==t?{x:i.B.x,y:i.B.y}:t}function v(){return navigator.maxTouchPoints||"ontouchstart"in this}function g(){var t,e,n,g,_=h,b=d,y=p,m=v,x={},w=(0,r.Z)("start","drag","end"),Z=0,D=0;function k(t){t.on("mousedown.drag",E).filter(m).on("touchstart.drag",C).on("touchmove.drag",M).on("touchend.drag touchcancel.drag",F).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function E(){if(!g&&_.apply(this,arguments)){var r=B("mouse",b.apply(this,arguments),a.Z,this,arguments);r&&((0,o.Z)(i.B.view).on("mousemove.drag",A,!0).on("mouseup.drag",j,!0),(0,s.Z)(i.B.view),(0,c.r)(),n=!1,t=i.B.clientX,e=i.B.clientY,r("start"))}}function A(){if((0,c.Z)(),!n){var r=i.B.clientX-t,a=i.B.clientY-e;n=r*r+a*a>D}x.mouse("drag")}function j(){(0,o.Z)(i.B.view).on("mousemove.drag mouseup.drag",null),(0,s.D)(i.B.view,n),(0,c.Z)(),x.mouse("end")}function C(){if(_.apply(this,arguments)){var t,e,n=i.B.changedTouches,r=b.apply(this,arguments),a=n.length;for(t=0;t{"use strict";function r(t,e,n,r,i,a,o,u,s,c){this.target=t,this.type=e,this.subject=n,this.identifier=r,this.active=i,this.x=a,this.y=o,this.dx=u,this.dy=s,this._=c}n.d(e,{Z:()=>r}),r.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t}},95520:(t,e,n)=>{"use strict";if(n.d(e,{oh:()=>r.Z,Kn:()=>i.Z,eF:()=>i.D}),826==n.j)var r=n(44319);if(826==n.j)var i=n(61062)},61062:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,D:()=>o}),826==n.j)var r=n(23475);if(826==n.j)var i=n(42254);function a(t){var e=t.document.documentElement,n=(0,r.Z)(t).on("dragstart.drag",i.Z,!0);"onselectstart"in e?n.on("selectstart.drag",i.Z,!0):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none")}function o(t,e){var n=t.document.documentElement,a=(0,r.Z)(t).on("dragstart.drag",null);e&&(a.on("click.drag",i.Z,!0),setTimeout((function(){a.on("click.drag",null)}),0)),"onselectstart"in n?a.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}},42254:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},65986:(t,e,n)=>{"use strict";function r(t){for(var e in t){var n,r,a=t[e].trim();if(a)if("true"===a)a=!0;else if("false"===a)a=!1;else if("NaN"===a)a=NaN;else if(isNaN(n=+a)){if(!(r=a.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;i&&r[4]&&!r[7]&&(a=a.replace(/-/g,"/").replace(/T/," ")),a=new Date(a)}else a=n;else a=null;t[e]=a}return t}n.d(e,{Z:()=>r});var i=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours()},55370:(t,e,n)=>{"use strict";n.d(e,{ue:()=>i,Bj:()=>a,Sf:()=>o,S:()=>u,Jb:()=>s,fh:()=>c,eX:()=>f});var r=(0,n(13428).Z)(","),i=r.parse,a=r.parseRows,o=r.format,u=r.formatBody,s=r.formatRows,c=r.formatRow,f=r.formatValue},13428:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r={},i={};function a(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function o(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r)})),n}function u(t,e){var n=t+"",r=n.length;return r=u?f=!0:10===(a=t.charCodeAt(s++))?l=!0:13===a&&(l=!0,10===t.charCodeAt(s)&&++s),t.slice(o+1,e-1).replace(/""/g,'"')}for(;s9999?"+"+u(r,6):u(r,4))+"-"+u(n.getUTCMonth()+1,2)+"-"+u(n.getUTCDate(),2)+(s?"T"+u(i,2)+":"+u(a,2)+":"+u(o,2)+"."+u(s,3)+"Z":o?"T"+u(i,2)+":"+u(a,2)+":"+u(o,2)+"Z":a||i?"T"+u(i,2)+":"+u(a,2)+"Z":"")):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t;var n,r,i,a,o,s}return{parse:function(t,e){var n,r,i=s(t,(function(t,i){if(n)return n(t,i-1);r=t,n=e?function(t,e){var n=a(t);return function(r,i){return e(n(r),i,t)}}(t,e):a(t)}));return i.columns=r||[],i},parseRows:s,format:function(e,n){return null==n&&(n=o(e)),[n.map(l).join(t)].concat(c(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=o(t)),c(t,e).join("\n")},formatRows:function(t){return t.map(f).join("\n")},formatRow:f,formatValue:l}}},83611:(t,e,n)=>{"use strict";if(n.d(e,{yv:()=>r.Z,ue:()=>i.ue,Bj:()=>i.Bj,Sf:()=>i.Sf,S:()=>i.S,Jb:()=>i.Jb,fh:()=>i.fh,eX:()=>i.eX,tJ:()=>a.tJ,E0:()=>a.E0,vP:()=>a.vP,uH:()=>a.uH,n5:()=>a.n5,Hf:()=>a.Hf,sS:()=>a.sS,rA:()=>o.Z}),826==n.j)var r=n(13428);if(826==n.j)var i=n(55370);if(826==n.j)var a=n(92044);if(826==n.j)var o=n(65986)},92044:(t,e,n)=>{"use strict";n.d(e,{tJ:()=>i,E0:()=>a,vP:()=>o,uH:()=>u,n5:()=>s,Hf:()=>c,sS:()=>f});var r=(0,n(13428).Z)("\t"),i=r.parse,a=r.parseRows,o=r.format,u=r.formatBody,s=r.formatRows,c=r.formatRow,f=r.formatValue},31704:(t,e,n)=>{"use strict";n.d(e,{G2:()=>i,CG:()=>a,XL:()=>o});var r=1.70158,i=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(r),a=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(r),o=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(r)},91105:(t,e,n)=>{"use strict";n.d(e,{h9:()=>h,gJ:()=>d,yD:()=>p});var r=826==n.j?6/11:null,i=826==n.j?8/11:null,a=826==n.j?3/4:null,o=826==n.j?9/11:null,u=826==n.j?10/11:null,s=826==n.j?15/16:null,c=826==n.j?21/22:null,f=826==n.j?63/64:null,l=7.5625;function h(t){return 1-d(1-t)}function d(t){return(t=+t)<.36363636363636365?l*t*t:t{"use strict";function r(t){return 1-Math.sqrt(1-t*t)}function i(t){return Math.sqrt(1- --t*t)}function a(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}n.d(e,{rf:()=>r,v2:()=>i,WE:()=>a})},2432:(t,e,n)=>{"use strict";function r(t){return t*t*t}function i(t){return--t*t*t+1}function a(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}n.d(e,{yD:()=>r,_e:()=>i,tw:()=>a})},70447:(t,e,n)=>{"use strict";n.d(e,{x8:()=>a,_D:()=>o,NL:()=>u});var r=n(11639),i=2*Math.PI,a=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return e*(0,r.N)(- --t)*Math.sin((a-t)/n)}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3),o=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return 1-e*(0,r.N)(t=+t)*Math.sin((t+a)/n)}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3),u=function t(e,n){var a=Math.asin(1/(e=Math.max(1,e)))*(n/=i);function o(t){return((t=2*t-1)<0?e*(0,r.N)(-t)*Math.sin((a-t)/n):2-e*(0,r.N)(t)*Math.sin((a+t)/n))/2}return o.amplitude=function(e){return t(e,n*i)},o.period=function(n){return t(e,n)},o}(1,.3)},31081:(t,e,n)=>{"use strict";if(n.d(e,{oP:()=>i,M4:()=>a,Oo:()=>o}),826==n.j)var r=n(11639);function i(t){return(0,r.N)(1-+t)}function a(t){return 1-(0,r.N)(t)}function o(t){return((t*=2)<=1?(0,r.N)(1-t):2-(0,r.N)(t-1))/2}},13756:(t,e,n)=>{"use strict";if(n.d(e,{Ny:()=>r.G,uw:()=>i.U2,V_:()=>i.Kl,mm:()=>i.u4,Tu:()=>i.U2,LU:()=>a.tw,HU:()=>a.yD,oS:()=>a._e,cC:()=>a.tw,m2:()=>o.SE,Tf:()=>o.RY,Ct:()=>o.fW,z5:()=>o.SE,Tl:()=>u.xU,tl:()=>u.yx,p4:()=>u.Dh,v:()=>u.xU,Ll:()=>s.Oo,uY:()=>s.oP,mf:()=>s.M4,nm:()=>s.Oo,Xe:()=>c.WE,kO:()=>c.rf,te:()=>c.v2,sq:()=>c.WE,sf:()=>f.gJ,RK:()=>f.h9,qj:()=>f.gJ,hE:()=>f.yD,bW:()=>l.XL,gp:()=>l.G2,ZN:()=>l.CG,gI:()=>l.XL,Az:()=>h._D,aM:()=>h.x8,Px:()=>h._D,H1:()=>h.NL}),826==n.j)var r=n(72738);if(826==n.j)var i=n(91502);if(826==n.j)var a=n(2432);if(826==n.j)var o=n(106);if(826==n.j)var u=n(98614);if(826==n.j)var s=n(31081);if(826==n.j)var c=n(60605);if(826==n.j)var f=n(91105);if(826==n.j)var l=n(31704);if(826==n.j)var h=n(70447)},72738:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{G:()=>r})},11639:(t,e,n)=>{"use strict";function r(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}n.d(e,{N:()=>r})},106:(t,e,n)=>{"use strict";n.d(e,{RY:()=>r,fW:()=>i,SE:()=>a});var r=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),i=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),a=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3)},91502:(t,e,n)=>{"use strict";function r(t){return t*t}function i(t){return t*(2-t)}function a(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}n.d(e,{Kl:()=>r,u4:()=>i,U2:()=>a})},98614:(t,e,n)=>{"use strict";n.d(e,{yx:()=>a,Dh:()=>o,xU:()=>u});var r=Math.PI,i=r/2;function a(t){return 1==+t?1:1-Math.cos(t*i)}function o(t){return Math.sin(t*i)}function u(t){return(1-Math.cos(r*t))/2}},55710:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},42472:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},8557:(t,e,n)=>{"use strict";if(n.d(e,{ZP:()=>s,gy:()=>c,pv:()=>f}),826==n.j)var r=n(13428);var i=n(55370),a=n(92044),o=n(92935);function u(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),(0,o.Z)(e,n).then((function(e){return t(e,r)}))}}function s(t,e,n,i){3===arguments.length&&"function"==typeof n&&(i=n,n=void 0);var a=(0,r.Z)(t);return(0,o.Z)(e,n).then((function(t){return a.parse(t,i)}))}var c=u(i.ue),f=u(a.tJ)},43973:(t,e,n)=>{"use strict";function r(t,e){return new Promise((function(n,r){var i=new Image;for(var a in e)i[a]=e[a];i.onerror=r,i.onload=function(){n(i)},i.src=t}))}n.d(e,{Z:()=>r})},14413:(t,e,n)=>{"use strict";if(n.d(e,{Ik:()=>r.Z,f3:()=>i.Z,Ds:()=>a.ZP,gy:()=>a.gy,pv:()=>a.pv,BH:()=>o.Z,AV:()=>u.Z,fL:()=>s.Z,Ls:()=>c.ZP,dy:()=>c.dy,YP:()=>c.YP}),826==n.j)var r=n(55710);if(826==n.j)var i=n(42472);if(826==n.j)var a=n(8557);if(826==n.j)var o=n(43973);if(826==n.j)var u=n(27969);if(826==n.j)var s=n(92935);if(826==n.j)var c=n(5110)},27969:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},92935:(t,e,n)=>{"use strict";function r(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function i(t,e){return fetch(t,e).then(r)}n.d(e,{Z:()=>i})},5110:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,dy:()=>o,YP:()=>u});var r=n(92935);function i(t){return function(e,n){return(0,r.Z)(e,n).then((function(e){return(new DOMParser).parseFromString(e,t)}))}}const a=i("application/xml");var o=i("text/html"),u=i("image/svg+xml")},71233:(t,e,n)=>{"use strict";function r(t,e){var n;function r(){var r,i,a=n.length,o=0,u=0;for(r=0;rr})},47226:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(84442);if(826==n.j)var i=n(43266);if(826==n.j)var a=n(94673);function o(t){return t.x+t.vx}function u(t){return t.y+t.vy}function s(t){var e,n,s=1,c=1;function f(){for(var t,r,f,h,d,p,v,g=e.length,_=0;_h+c||rd+c||af.index){var l=h-o.x-o.vx,g=d-o.y-o.vy,_=l*l+g*g;_t.r&&(t.r=t[e].r)}function h(){if(e){var r,i,a=e.length;for(n=new Array(a),r=0;r{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},43266:(t,e,n)=>{"use strict";function r(){return 1e-6*(Math.random()-.5)}n.d(e,{Z:()=>r})},5724:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t,e,n){var i,a,o,u=(0,r.Z)(.1);function s(t){for(var r=0,u=i.length;r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t){var e,n,i,a=(0,r.Z)(.1);function o(t){for(var r,a=0,o=e.length;a{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(84442);function i(t){var e,n,i,a=(0,r.Z)(.1);function o(t){for(var r,a=0,o=e.length;a{"use strict";function r(){return new i}function i(){this.reset()}n.d(e,{Z:()=>r}),i.prototype={constructor:i,reset:function(){this.s=this.t=0},add:function(t){o(a,t,this.t),o(this,a.s,this.s),this.s?this.t+=a.t:this.s=a.t},valueOf:function(){return this.s}};var a=new i;function o(t,e,n){var r=t.s=e+n,i=r-e,a=r-i;t.t=e-a+(n-i)}},86593:(t,e,n)=>{"use strict";n.d(e,{L9:()=>h,gL:()=>p,ZP:()=>y});var r=n(6236),i=n(66573),a=n(48340);if(826==n.j)var o=n(60600);var u,s,c,f,l,h=(0,r.Z)(),d=(0,r.Z)(),p={point:a.Z,lineStart:a.Z,lineEnd:a.Z,polygonStart:function(){h.reset(),p.lineStart=v,p.lineEnd=g},polygonEnd:function(){var t=+h;d.add(t<0?i.BZ+t:t),this.lineStart=this.lineEnd=this.point=a.Z},sphere:function(){d.add(i.BZ)}};function v(){p.point=_}function g(){b(u,s)}function _(t,e){p.point=b,u=t,s=e,t*=i.uR,e*=i.uR,c=t,f=(0,i.mC)(e=e/2+i.pu),l=(0,i.O$)(e)}function b(t,e){t*=i.uR,e=(e*=i.uR)/2+i.pu;var n=t-c,r=n>=0?1:-1,a=r*n,o=(0,i.mC)(e),u=(0,i.O$)(e),s=l*u,d=f*o+s*(0,i.mC)(a),p=s*r*(0,i.O$)(a);h.add((0,i.fv)(p,d)),c=t,f=o,l=u}function y(t){return d.reset(),(0,o.Z)(t,p),2*d}},70456:(t,e,n)=>{"use strict";n.d(e,{Z:()=>M});var r=n(6236),i=n(86593),a=n(67776),o=n(66573);if(826==n.j)var u=n(60600);var s,c,f,l,h,d,p,v,g,_,b=(0,r.Z)(),y={point:m,lineStart:w,lineEnd:Z,polygonStart:function(){y.point=D,y.lineStart=k,y.lineEnd=E,b.reset(),i.gL.polygonStart()},polygonEnd:function(){i.gL.polygonEnd(),y.point=m,y.lineStart=w,y.lineEnd=Z,i.L9<0?(s=-(f=180),c=-(l=90)):b>o.Ho?l=90:b<-o.Ho&&(c=-90),_[0]=s,_[1]=f},sphere:function(){s=-(f=180),c=-(l=90)}};function m(t,e){g.push(_=[s=t,f=t]),el&&(l=e)}function x(t,e){var n=(0,a.Og)([t*o.uR,e*o.uR]);if(v){var r=(0,a.T5)(v,n),i=[r[1],-r[0],0],u=(0,a.T5)(i,r);(0,a.iJ)(u),u=(0,a.Y1)(u);var d,p=t-h,b=p>0?1:-1,y=u[0]*o.RW*b,m=(0,o.Wn)(p)>180;m^(b*hl&&(l=d):m^(b*h<(y=(y+360)%360-180)&&yl&&(l=e)),m?tA(s,f)&&(f=t):A(t,f)>A(s,f)&&(s=t):f>=s?(tf&&(f=t)):t>h?A(s,t)>A(s,f)&&(f=t):A(t,f)>A(s,f)&&(s=t)}else g.push(_=[s=t,f=t]);el&&(l=e),v=n,h=t}function w(){y.point=x}function Z(){_[0]=s,_[1]=f,y.point=m,v=null}function D(t,e){if(v){var n=t-h;b.add((0,o.Wn)(n)>180?n+(n>0?360:-360):n)}else d=t,p=e;i.gL.point(t,e),x(t,e)}function k(){i.gL.lineStart()}function E(){D(d,p),i.gL.lineEnd(),(0,o.Wn)(b)>o.Ho&&(s=-(f=180)),_[0]=s,_[1]=f,v=null}function A(t,e){return(e-=t)<0?e+360:e}function j(t,e){return t[0]-e[0]}function C(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eA(r[0],r[1])&&(r[1]=i[1]),A(i[0],r[1])>A(r[0],r[1])&&(r[0]=i[0])):a.push(r=i);for(o=-1/0,e=0,r=a[n=a.length-1];e<=n;r=i,++e)i=a[e],(h=A(r[1],i[0]))>o&&(o=h,s=i[0],f=r[1])}return g=_=null,s===1/0||c===1/0?[[NaN,NaN],[NaN,NaN]]:[[s,c],[f,l]]}},67776:(t,e,n)=>{"use strict";if(n.d(e,{Y1:()=>i,Og:()=>a,j9:()=>o,T5:()=>u,s0:()=>s,T:()=>c,iJ:()=>f}),826==n.j)var r=n(66573);function i(t){return[(0,r.fv)(t[1],t[0]),(0,r.ZR)(t[2])]}function a(t){var e=t[0],n=t[1],i=(0,r.mC)(n);return[i*(0,r.mC)(e),i*(0,r.O$)(e),(0,r.O$)(n)]}function o(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function u(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function s(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function c(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function f(t){var e=(0,r._b)(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}},83922:(t,e,n)=>{"use strict";n.d(e,{Z:()=>S});var r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y=n(66573),m=n(48340);if(826==n.j)var x=n(60600);var w={sphere:m.Z,point:Z,lineStart:k,lineEnd:j,polygonStart:function(){w.lineStart=C,w.lineEnd=M},polygonEnd:function(){w.lineStart=k,w.lineEnd=j}};function Z(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e);D(n*(0,y.mC)(t),n*(0,y.O$)(t),(0,y.O$)(e))}function D(t,e,n){++r,a+=(t-a)/r,o+=(e-o)/r,u+=(n-u)/r}function k(){w.point=E}function E(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e);g=n*(0,y.mC)(t),_=n*(0,y.O$)(t),b=(0,y.O$)(e),w.point=A,D(g,_,b)}function A(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e),r=n*(0,y.mC)(t),a=n*(0,y.O$)(t),o=(0,y.O$)(e),u=(0,y.fv)((0,y._b)((u=_*o-b*a)*u+(u=b*r-g*o)*u+(u=g*a-_*r)*u),g*r+_*a+b*o);i+=u,s+=u*(g+(g=r)),c+=u*(_+(_=a)),f+=u*(b+(b=o)),D(g,_,b)}function j(){w.point=Z}function C(){w.point=F}function M(){B(p,v),w.point=Z}function F(t,e){p=t,v=e,t*=y.uR,e*=y.uR,w.point=B;var n=(0,y.mC)(e);g=n*(0,y.mC)(t),_=n*(0,y.O$)(t),b=(0,y.O$)(e),D(g,_,b)}function B(t,e){t*=y.uR,e*=y.uR;var n=(0,y.mC)(e),r=n*(0,y.mC)(t),a=n*(0,y.O$)(t),o=(0,y.O$)(e),u=_*o-b*a,p=b*r-g*o,v=g*a-_*r,m=(0,y._b)(u*u+p*p+v*v),x=(0,y.ZR)(m),w=m&&-x/m;l+=w*u,h+=w*p,d+=w*v,i+=x,s+=x*(g+(g=r)),c+=x*(_+(_=a)),f+=x*(b+(b=o)),D(g,_,b)}function S(t){r=i=a=o=u=s=c=f=l=h=d=0,(0,x.Z)(t,w);var e=l,n=h,p=d,v=e*e+n*n+p*p;return v{"use strict";if(n.d(e,{m:()=>u,Z:()=>c}),826==n.j)var r=n(67776);if(826==n.j)var i=n(90303);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(85295);function u(t,e,n,i,o,u){if(n){var c=(0,a.mC)(e),f=(0,a.O$)(e),l=i*n;null==o?(o=e+i*a.BZ,u=e-l/2):(o=s(c,o),u=s(c,u),(i>0?ou)&&(o+=i*a.BZ));for(var h,d=o;i>0?d>u:d{"use strict";n.d(e,{Z:()=>a});var r=n(38147),i=n(66573);const a=(0,r.Z)((function(){return!0}),(function(t){var e,n=NaN,r=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,u){var s=o>0?i.pi:-i.pi,c=(0,i.Wn)(o-n);(0,i.Wn)(c-i.pi)0?i.ou:-i.ou),t.point(a,r),t.lineEnd(),t.lineStart(),t.point(s,r),t.point(o,r),e=0):a!==s&&c>=i.pi&&((0,i.Wn)(n-a)i.Ho?(0,i.z4)(((0,i.O$)(e)*(o=(0,i.mC)(r))*(0,i.O$)(n)-(0,i.O$)(r)*(a=(0,i.mC)(e))*(0,i.O$)(t))/(a*o*u)):(e+r)/2}(n,r,o,u),t.point(a,r),t.lineEnd(),t.lineStart(),t.point(s,r),e=0),t.point(n=o,r=u),a=s},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var a;if(null==t)a=n*i.ou,r.point(-i.pi,a),r.point(0,a),r.point(i.pi,a),r.point(i.pi,0),r.point(i.pi,-a),r.point(0,-a),r.point(-i.pi,-a),r.point(-i.pi,0),r.point(-i.pi,a);else if((0,i.Wn)(t[0]-e[0])>i.Ho){var o=t[0]{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(48340);function i(){var t,e=[];return{point:function(e,n,r){t.push([e,n,r])},lineStart:function(){e.push(t=[])},lineEnd:r.Z,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}},24883:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(67776);if(826==n.j)var i=n(62332);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(12447);if(826==n.j)var u=n(38147);function s(t){var e=(0,a.mC)(t),n=6*a.uR,s=e>0,c=(0,a.Wn)(e)>a.Ho;function f(t,n){return(0,a.mC)(t)*(0,a.mC)(n)>e}function l(t,n,i){var o=(0,r.Og)(t),u=(0,r.Og)(n),s=[1,0,0],c=(0,r.T5)(o,u),f=(0,r.j9)(c,c),l=c[0],h=f-l*l;if(!h)return!i&&t;var d=e*f/h,p=-e*l/h,v=(0,r.T5)(s,c),g=(0,r.T)(s,d),_=(0,r.T)(c,p);(0,r.s0)(g,_);var b=v,y=(0,r.j9)(g,b),m=(0,r.j9)(b,b),x=y*y-m*((0,r.j9)(g,g)-1);if(!(x<0)){var w=(0,a._b)(x),Z=(0,r.T)(b,(-y-w)/m);if((0,r.s0)(Z,g),Z=(0,r.Y1)(Z),!i)return Z;var D,k=t[0],E=n[0],A=t[1],j=n[1];E0^Z[1]<((0,a.Wn)(Z[0]-k)a.pi^(k<=Z[0]&&Z[0]<=E)){var F=(0,r.T)(b,(-y+w)/m);return(0,r.s0)(F,g),[Z,(0,r.Y1)(F)]}}}function h(e,n){var r=s?t:a.pi-t,i=0;return e<-r?i|=1:e>r&&(i|=2),n<-r?i|=4:n>r&&(i|=8),i}return(0,u.Z)(f,(function(t){var e,n,r,i,u;return{lineStart:function(){i=r=!1,u=1},point:function(d,p){var v,g=[d,p],_=f(d,p),b=s?_?0:h(d,p):_?h(d+(d<0?a.pi:-a.pi),p):0;if(!e&&(i=r=_)&&t.lineStart(),_!==r&&(!(v=l(e,g))||(0,o.Z)(e,v)||(0,o.Z)(g,v))&&(g[2]=1),_!==r)u=0,_?(t.lineStart(),v=l(g,e),t.point(v[0],v[1])):(v=l(e,g),t.point(v[0],v[1],2),t.lineEnd()),e=v;else if(c&&e&&s^_){var y;b&n||!(y=l(g,e,!0))||(u=0,s?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1],3)))}!_||e&&(0,o.Z)(e,g)||t.point(g[0],g[1]),e=g,r=_,n=b},lineEnd:function(){r&&t.lineEnd(),e=null},clean:function(){return u|(i&&r)<<1}}}),(function(e,r,a,o){(0,i.m)(o,t,n,a,e,r)}),s?[0,-t]:[-a.pi,t-a.pi])}},37023:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(94892);function i(){var t,e,n,i=0,a=0,o=960,u=500;return n={stream:function(n){return t&&e===n?t:t=(0,r.Z)(i,a,o,u)(e=n)},extent:function(r){return arguments.length?(i=+r[0][0],a=+r[0][1],o=+r[1][0],u=+r[1][1],t=e=null,n):[[i,a],[o,u]]}}}},38147:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(92590);if(826==n.j)var i=n(40559);if(826==n.j)var a=n(66573);if(826==n.j)var o=n(3378);var u=n(58470);function s(t,e,n,a){return function(s){var l,h,d,p=e(s),v=(0,r.Z)(),g=e(v),_=!1,b={point:y,lineStart:x,lineEnd:w,polygonStart:function(){b.point=Z,b.lineStart=D,b.lineEnd=k,h=[],l=[]},polygonEnd:function(){b.point=y,b.lineStart=x,b.lineEnd=w,h=(0,u.TS)(h);var t=(0,o.Z)(l,a);h.length?(_||(s.polygonStart(),_=!0),(0,i.Z)(h,f,t,n,s)):t&&(_||(s.polygonStart(),_=!0),s.lineStart(),n(null,null,1,s),s.lineEnd()),_&&(s.polygonEnd(),_=!1),h=l=null},sphere:function(){s.polygonStart(),s.lineStart(),n(null,null,1,s),s.lineEnd(),s.polygonEnd()}};function y(e,n){t(e,n)&&s.point(e,n)}function m(t,e){p.point(t,e)}function x(){b.point=m,p.lineStart()}function w(){b.point=y,p.lineEnd()}function Z(t,e){d.push([t,e]),g.point(t,e)}function D(){g.lineStart(),d=[]}function k(){Z(d[0][0],d[0][1]),g.lineEnd();var t,e,n,r,i=g.clean(),a=v.result(),o=a.length;if(d.pop(),l.push(d),d=null,o)if(1&i){if((e=(n=a[0]).length-1)>0){for(_||(s.polygonStart(),_=!0),s.lineStart(),t=0;t1&&2&i&&a.push(a.pop().concat(a.shift())),h.push(a.filter(c))}return b}}function c(t){return t.length>1}function f(t,e){return((t=t.x)[0]<0?t[1]-a.ou-a.Ho:a.ou-t[1])-((e=e.x)[0]<0?e[1]-a.ou-a.Ho:a.ou-e[1])}},96610:(t,e,n)=>{"use strict";function r(t,e,n,r,i,a){var o,u=t[0],s=t[1],c=0,f=1,l=e[0]-u,h=e[1]-s;if(o=n-u,l||!(o>0)){if(o/=l,l<0){if(o0){if(o>f)return;o>c&&(c=o)}if(o=i-u,l||!(o<0)){if(o/=l,l<0){if(o>f)return;o>c&&(c=o)}else if(l>0){if(o0)){if(o/=h,h<0){if(o0){if(o>f)return;o>c&&(c=o)}if(o=a-s,h||!(o<0)){if(o/=h,h<0){if(o>f)return;o>c&&(c=o)}else if(h>0){if(o0&&(t[0]=u+c*l,t[1]=s+c*h),f<1&&(e[0]=u+f*l,e[1]=s+f*h),!0}}}}}n.d(e,{Z:()=>r})},94892:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>f}),826==n.j)var r=n(66573);if(826==n.j)var i=n(92590);if(826==n.j)var a=n(96610);if(826==n.j)var o=n(40559);var u=n(58470),s=1e9,c=-s;function f(t,e,n,f){function l(r,i){return t<=r&&r<=n&&e<=i&&i<=f}function h(r,i,a,o){var u=0,s=0;if(null==r||(u=d(r,a))!==(s=d(i,a))||v(r,i)<0^a>0)do{o.point(0===u||3===u?t:n,u>1?f:e)}while((u=(u+a+4)%4)!==s);else o.point(i[0],i[1])}function d(i,a){return(0,r.Wn)(i[0]-t)0?0:3:(0,r.Wn)(i[0]-n)0?2:1:(0,r.Wn)(i[1]-e)0?1:0:a>0?3:2}function p(t,e){return v(t.x,e.x)}function v(t,e){var n=d(t,1),r=d(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(r){var d,v,g,_,b,y,m,x,w,Z,D,k=r,E=(0,i.Z)(),A={point:j,lineStart:function(){A.point=C,v&&v.push(g=[]),Z=!0,w=!1,m=x=NaN},lineEnd:function(){d&&(C(_,b),y&&w&&E.rejoin(),d.push(E.result())),A.point=j,w&&k.lineEnd()},polygonStart:function(){k=E,d=[],v=[],D=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,r=v.length;nf&&(l-i)*(f-a)>(h-a)*(t-i)&&++e:h<=f&&(l-i)*(f-a)<(h-a)*(t-i)&&--e;return e}(),n=D&&e,i=(d=(0,u.TS)(d)).length;(n||i)&&(r.polygonStart(),n&&(r.lineStart(),h(null,null,1,r),r.lineEnd()),i&&(0,o.Z)(d,p,e,h,r),r.polygonEnd()),k=r,d=v=g=null}};function j(t,e){l(t,e)&&k.point(t,e)}function C(r,i){var o=l(r,i);if(v&&g.push([r,i]),Z)_=r,b=i,y=o,Z=!1,o&&(k.lineStart(),k.point(r,i));else if(o&&w)k.point(r,i);else{var u=[m=Math.max(c,Math.min(s,m)),x=Math.max(c,Math.min(s,x))],h=[r=Math.max(c,Math.min(s,r)),i=Math.max(c,Math.min(s,i))];(0,a.Z)(u,h,t,e,n,f)?(w||(k.lineStart(),k.point(u[0],u[1])),k.point(h[0],h[1]),o||k.lineEnd(),D=!1):o&&(k.lineStart(),k.point(r,i),D=!1)}m=r,x=i,w=o}return A}}},40559:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(12447);if(826==n.j)var i=n(66573);function a(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function o(t,e,n,o,s){var c,f,l=[],h=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,o=t[0],u=t[e];if((0,r.Z)(o,u)){if(!o[2]&&!u[2]){for(s.lineStart(),c=0;c=0;--c)s.point((p=d[c])[0],p[1]);else o(g.x,g.p.x,-1,s);g=g.p}d=(g=g.o).z,_=!_}while(!g.v);s.lineEnd()}}}function u(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r{"use strict";function r(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return(n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}n.d(e,{Z:()=>r})},90303:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},37236:(t,e,n)=>{"use strict";n.d(e,{Z:()=>p});var r=n(3378),i=n(65055),a=n(66573),o={Feature:function(t,e){return s(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r0&&(o=(0,i.Z)(t[u],t[u-1]))>0&&n<=o&&r<=o&&(n+r-o)*(1-Math.pow((n-r)/o,2)){"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(74108);var i=[null,null],a={type:"LineString",coordinates:i};function o(t,e){return i[0]=t,i[1]=e,(0,r.Z)(a)}},51418:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u,e:()=>s});var r=n(58470);if(826==n.j)var i=n(66573);function a(t,e,n){var a=(0,r.w6)(t,e-i.Ho,n).concat(e);return function(t){return a.map((function(e){return[t,e]}))}}function o(t,e,n){var a=(0,r.w6)(t,e-i.Ho,n).concat(e);return function(t){return a.map((function(e){return[e,t]}))}}function u(){var t,e,n,u,s,c,f,l,h,d,p,v,g=10,_=g,b=90,y=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:w()}}function w(){return(0,r.w6)((0,i.mD)(u/b)*b,n,b).map(p).concat((0,r.w6)((0,i.mD)(l/y)*y,f,y).map(v)).concat((0,r.w6)((0,i.mD)(e/g)*g,t,g).filter((function(t){return(0,i.Wn)(t%b)>i.Ho})).map(h)).concat((0,r.w6)((0,i.mD)(c/_)*_,s,_).filter((function(t){return(0,i.Wn)(t%y)>i.Ho})).map(d))}return x.lines=function(){return w().map((function(t){return{type:"LineString",coordinates:t}}))},x.outline=function(){return{type:"Polygon",coordinates:[p(u).concat(v(f).slice(1),p(n).reverse().slice(1),v(l).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.extentMajor(t).extentMinor(t):x.extentMinor()},x.extentMajor=function(t){return arguments.length?(u=+t[0][0],n=+t[1][0],l=+t[0][1],f=+t[1][1],u>n&&(t=u,u=n,n=t),l>f&&(t=l,l=f,f=t),x.precision(m)):[[u,l],[n,f]]},x.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],c=+n[0][1],s=+n[1][1],e>t&&(n=e,e=t,t=n),c>s&&(n=c,c=s,s=n),x.precision(m)):[[e,c],[t,s]]},x.step=function(t){return arguments.length?x.stepMajor(t).stepMinor(t):x.stepMinor()},x.stepMajor=function(t){return arguments.length?(b=+t[0],y=+t[1],x):[b,y]},x.stepMinor=function(t){return arguments.length?(g=+t[0],_=+t[1],x):[g,_]},x.precision=function(r){return arguments.length?(m=+r,h=a(c,s,90),d=o(e,t,m),p=a(l,f,90),v=o(u,n,m),x):m},x.extentMajor([[-180,-90+i.Ho],[180,90-i.Ho]]).extentMinor([[-180,-80-i.Ho],[180,80+i.Ho]])}function s(){return u()()}},59350:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},74200:(t,e,n)=>{"use strict";if(n.d(e,{ID:()=>r.ZP,qT:()=>i.Z,cS:()=>a.Z,ub:()=>o.Z,o6:()=>u.Z,Fh:()=>s.Z,iM:()=>c.Z,LF:()=>f.Z,xk:()=>l.Z,gD:()=>h.Z,S:()=>d.Z,HV:()=>d.e,iG:()=>p.Z,Jp:()=>v.Z,l4:()=>g.Z,FW:()=>_.Z,wk:()=>b.Z,Rf:()=>y.Z,fN:()=>y.l,aM:()=>m.Z,dz:()=>m.N,tJ:()=>x.Z,W$:()=>x.l,ET:()=>w.Z,SQ:()=>w.v,ah:()=>Z.Z,nh:()=>Z.o,bf:()=>D.Z,bw:()=>D.i,ES:()=>k.Z,Hw:()=>k.k,Bq:()=>E.Z,ot:()=>E.M,NL:()=>A.Z,OA:()=>j.Z,gv:()=>j.r,mw:()=>C.ZP,z:()=>C.hk,li:()=>M.Z,Bh:()=>M.K,Wv:()=>F.Z,jx:()=>F.I,kn:()=>B.Z,PA:()=>B.T,Il:()=>S.Z,GN:()=>S.F,w7:()=>N.Z,HZ:()=>T.Z,jD:()=>z.Z}),826==n.j)var r=n(86593);if(826==n.j)var i=n(70456);if(826==n.j)var a=n(83922);if(826==n.j)var o=n(62332);if(826==n.j)var u=n(98503);if(826==n.j)var s=n(24883);if(826==n.j)var c=n(37023);if(826==n.j)var f=n(94892);if(826==n.j)var l=n(37236);if(826==n.j)var h=n(65055);if(826==n.j)var d=n(51418);if(826==n.j)var p=n(70193);if(826==n.j)var v=n(74108);if(826==n.j)var g=n(53635);if(826==n.j)var _=n(48645);if(826==n.j)var b=n(51700);if(826==n.j)var y=n(13205);if(826==n.j)var m=n(71820);if(826==n.j)var x=n(54719);if(826==n.j)var w=n(41202);if(826==n.j)var Z=n(51105);if(826==n.j)var D=n(74749);if(826==n.j)var k=n(67650);if(826==n.j)var E=n(77164);if(826==n.j)var A=n(47880);if(826==n.j)var j=n(93137);if(826==n.j)var C=n(15317);if(826==n.j)var M=n(42617);if(826==n.j)var F=n(77792);if(826==n.j)var B=n(874);if(826==n.j)var S=n(17025);if(826==n.j)var N=n(85295);if(826==n.j)var T=n(60600);if(826==n.j)var z=n(13582)},70193:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(66573);function i(t,e){var n=t[0]*r.uR,i=t[1]*r.uR,a=e[0]*r.uR,o=e[1]*r.uR,u=(0,r.mC)(i),s=(0,r.O$)(i),c=(0,r.mC)(o),f=(0,r.O$)(o),l=u*(0,r.mC)(n),h=u*(0,r.O$)(n),d=c*(0,r.mC)(a),p=c*(0,r.O$)(a),v=2*(0,r.ZR)((0,r._b)((0,r.Jy)(o-i)+u*c*(0,r.Jy)(a-n))),g=(0,r.O$)(v),_=v?function(t){var e=(0,r.O$)(t*=v)/g,n=(0,r.O$)(v-t)/g,i=n*l+e*d,a=n*h+e*p,o=n*s+e*f;return[(0,r.fv)(a,i)*r.RW,(0,r.fv)(o,(0,r._b)(i*i+a*a))*r.RW]}:function(){return[n*r.RW,i*r.RW]};return _.distance=v,_}},74108:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r=n(6236),i=n(66573),a=n(48340);if(826==n.j)var o=n(60600);var u,s,c,f=(0,r.Z)(),l={sphere:a.Z,point:a.Z,lineStart:function(){l.point=d,l.lineEnd=h},lineEnd:a.Z,polygonStart:a.Z,polygonEnd:a.Z};function h(){l.point=l.lineEnd=a.Z}function d(t,e){t*=i.uR,e*=i.uR,u=t,s=(0,i.O$)(e),c=(0,i.mC)(e),l.point=p}function p(t,e){t*=i.uR,e*=i.uR;var n=(0,i.O$)(e),r=(0,i.mC)(e),a=(0,i.Wn)(t-u),o=(0,i.mC)(a),l=r*(0,i.O$)(a),h=c*n-s*r*o,d=s*n+c*r*o;f.add((0,i.fv)((0,i._b)(l*l+h*h),d)),u=t,s=n,c=r}function v(t){return f.reset(),(0,o.Z)(t,l),+f}},66573:(t,e,n)=>{"use strict";n.d(e,{Ho:()=>r,aW:()=>i,pi:()=>a,ou:()=>o,pu:()=>u,BZ:()=>s,RW:()=>c,uR:()=>f,Wn:()=>l,z4:()=>h,fv:()=>d,mC:()=>p,mD:()=>v,Qq:()=>g,cM:()=>_,sQ:()=>b,O$:()=>y,Xx:()=>m,_b:()=>x,OR:()=>w,Kh:()=>Z,ZR:()=>D,Jy:()=>k});var r=1e-6,i=1e-12,a=Math.PI,o=a/2,u=a/4,s=2*a,c=180/a,f=a/180,l=Math.abs,h=Math.atan,d=Math.atan2,p=Math.cos,v=Math.ceil,g=Math.exp,_=(Math.floor,Math.log),b=Math.pow,y=Math.sin,m=Math.sign||function(t){return t>0?1:t<0?-1:0},x=Math.sqrt,w=Math.tan;function Z(t){return t>1?0:t<-1?a:Math.acos(t)}function D(t){return t>1?o:t<-1?-o:Math.asin(t)}function k(t){return(t=y(t/2))*t}},48340:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},4503:(t,e,n)=>{"use strict";n.d(e,{Z:()=>_});var r,i,a,o,u=n(6236),s=n(66573),c=n(48340),f=(0,u.Z)(),l=(0,u.Z)(),h={point:c.Z,lineStart:c.Z,lineEnd:c.Z,polygonStart:function(){h.lineStart=d,h.lineEnd=g},polygonEnd:function(){h.lineStart=h.lineEnd=h.point=c.Z,f.add((0,s.Wn)(l)),l.reset()},result:function(){var t=f/2;return f.reset(),t}};function d(){h.point=p}function p(t,e){h.point=v,r=a=t,i=o=e}function v(t,e){l.add(o*t-a*e),a=t,o=e}function g(){v(r,i)}const _=826==n.j?h:null},57620:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=n(48340),i=1/0,a=i,o=-i,u=o,s={point:function(t,e){to&&(o=t),eu&&(u=e)},lineStart:r.Z,lineEnd:r.Z,polygonStart:r.Z,polygonEnd:r.Z,result:function(){var t=[[i,a],[o,u]];return o=u=-(a=i=1/0),t}};const c=826==n.j?s:null},93087:(t,e,n)=>{"use strict";n.d(e,{Z:()=>A});var r,i,a,o,u=n(66573),s=0,c=0,f=0,l=0,h=0,d=0,p=0,v=0,g=0,_={point:b,lineStart:y,lineEnd:w,polygonStart:function(){_.lineStart=Z,_.lineEnd=D},polygonEnd:function(){_.point=b,_.lineStart=y,_.lineEnd=w},result:function(){var t=g?[p/g,v/g]:d?[l/d,h/d]:f?[s/f,c/f]:[NaN,NaN];return s=c=f=l=h=d=p=v=g=0,t}};function b(t,e){s+=t,c+=e,++f}function y(){_.point=m}function m(t,e){_.point=x,b(a=t,o=e)}function x(t,e){var n=t-a,r=e-o,i=(0,u._b)(n*n+r*r);l+=i*(a+t)/2,h+=i*(o+e)/2,d+=i,b(a=t,o=e)}function w(){_.point=b}function Z(){_.point=k}function D(){E(r,i)}function k(t,e){_.point=E,b(r=a=t,i=o=e)}function E(t,e){var n=t-a,r=e-o,i=(0,u._b)(n*n+r*r);l+=i*(a+t)/2,h+=i*(o+e)/2,d+=i,p+=(i=o*t-a*e)*(a+t),v+=i*(o+e),g+=3*i,b(a=t,o=e)}const A=826==n.j?_:null},39695:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(66573),i=n(48340);function a(t){this._context=t}a.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,r.BZ)}},result:i.Z}},53635:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>l}),826==n.j)var r=n(59350);if(826==n.j)var i=n(60600);if(826==n.j)var a=n(4503);if(826==n.j)var o=n(57620);if(826==n.j)var u=n(93087);if(826==n.j)var s=n(39695);if(826==n.j)var c=n(61148);if(826==n.j)var f=n(21868);function l(t,e){var n,l,h=4.5;function d(t){return t&&("function"==typeof h&&l.pointRadius(+h.apply(this,arguments)),(0,i.Z)(t,n(l))),l.result()}return d.area=function(t){return(0,i.Z)(t,n(a.Z)),a.Z.result()},d.measure=function(t){return(0,i.Z)(t,n(c.Z)),c.Z.result()},d.bounds=function(t){return(0,i.Z)(t,n(o.Z)),o.Z.result()},d.centroid=function(t){return(0,i.Z)(t,n(u.Z)),u.Z.result()},d.projection=function(e){return arguments.length?(n=null==e?(t=null,r.Z):(t=e).stream,d):t},d.context=function(t){return arguments.length?(l=null==t?(e=null,new f.Z):new s.Z(e=t),"function"!=typeof h&&l.pointRadius(h),d):e},d.pointRadius=function(t){return arguments.length?(h="function"==typeof t?t:(l.pointRadius(+t),+t),d):h},d.projection(t).context(e)}},61148:(t,e,n)=>{"use strict";n.d(e,{Z:()=>v});var r,i,a,o,u,s=n(6236),c=n(66573),f=n(48340),l=(0,s.Z)(),h={point:f.Z,lineStart:function(){h.point=d},lineEnd:function(){r&&p(i,a),h.point=f.Z},polygonStart:function(){r=!0},polygonEnd:function(){r=null},result:function(){var t=+l;return l.reset(),t}};function d(t,e){h.point=p,i=o=t,a=u=e}function p(t,e){o-=t,u-=e,l.add((0,c._b)(o*o+u*u)),o=t,u=e}const v=826==n.j?h:null},21868:(t,e,n)=>{"use strict";function r(){this._string=[]}function i(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}n.d(e,{Z:()=>r}),r.prototype={_radius:4.5,_circle:i(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=i(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}}},12447:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(66573);function i(t,e){return(0,r.Wn)(t[0]-e[0]){"use strict";n.d(e,{Z:()=>s});var r=n(6236);if(826==n.j)var i=n(67776);if(826==n.j)var a=n(66573);var o=(0,r.Z)();function u(t){return(0,a.Wn)(t[0])<=a.pi?t[0]:(0,a.Xx)(t[0])*(((0,a.Wn)(t[0])+a.pi)%a.BZ-a.pi)}function s(t,e){var n=u(e),r=e[1],s=(0,a.O$)(r),c=[(0,a.O$)(n),-(0,a.mC)(n),0],f=0,l=0;o.reset(),1===s?r=a.ou+a.Ho:-1===s&&(r=-a.ou-a.Ho);for(var h=0,d=t.length;h=0?1:-1,C=j*A,M=C>a.pi,F=y*k;if(o.add((0,a.fv)(F*j*(0,a.O$)(C),m*E+F*(0,a.mC)(C))),f+=M?A+j*a.BZ:A,M^_>=n^Z>=n){var B=(0,i.T5)((0,i.Og)(g),(0,i.Og)(w));(0,i.iJ)(B);var S=(0,i.T5)(c,B);(0,i.iJ)(S);var N=(M^A>=0?-1:1)*(0,a.ZR)(S[2]);(r>N||r===N&&(B[0]||B[1]))&&(l+=M^A>=0?1:-1)}}return(f<-a.Ho||f{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(41202);function i(){return(0,r.Z)().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}},51700:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(48645);if(826==n.j)var a=n(41202);if(826==n.j)var o=n(80686);function u(){var t,e,n,u,s,c,f=(0,i.Z)(),l=(0,a.Z)().rotate([154,0]).center([-2,58.5]).parallels([55,65]),h=(0,a.Z)().rotate([157,0]).center([-3,19.9]).parallels([8,18]),d={point:function(t,e){c=[t,e]}};function p(t){var e=t[0],r=t[1];return c=null,n.point(e,r),c||(u.point(e,r),c)||(s.point(e,r),c)}function v(){return t=e=null,p}return p.invert=function(t){var e=f.scale(),n=f.translate(),r=(t[0]-n[0])/e,i=(t[1]-n[1])/e;return(i>=.12&&i<.234&&r>=-.425&&r<-.214?l:i>=.166&&i<.234&&r>=-.214&&r<-.115?h:f).invert(t)},p.stream=function(n){return t&&e===n?t:(r=[f.stream(e=n),l.stream(n),h.stream(n)],i=r.length,t={point:function(t,e){for(var n=-1;++n{"use strict";if(n.d(e,{W:()=>i,O:()=>a}),826==n.j)var r=n(66573);function i(t){return function(e,n){var i=(0,r.mC)(e),a=(0,r.mC)(n),o=t(i*a);return[o*a*(0,r.O$)(e),o*(0,r.O$)(n)]}}function a(t){return function(e,n){var i=(0,r._b)(e*e+n*n),a=t(i),o=(0,r.O$)(a),u=(0,r.mC)(a);return[(0,r.fv)(e*o,i*u),(0,r.ZR)(i&&n*o/i)]}}},13205:(t,e,n)=>{"use strict";n.d(e,{l:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);var o=(0,i.W)((function(t){return(0,r._b)(2/(1+t))}));function u(){return(0,a.Z)(o).scale(124.75).clipAngle(179.999)}o.invert=(0,i.O)((function(t){return 2*(0,r.ZR)(t/2)}))},71820:(t,e,n)=>{"use strict";n.d(e,{N:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);var o=(0,i.W)((function(t){return(t=(0,r.Kh)(t))&&t/(0,r.O$)(t)}));function u(){return(0,a.Z)(o).scale(79.4188).clipAngle(179.999)}o.invert=(0,i.O)((function(t){return t}))},32387:(t,e,n)=>{"use strict";if(n.d(e,{o:()=>a}),826==n.j)var r=n(66573);if(826==n.j)var i=n(93137);function a(t){var e=0,n=r.pi/3,a=(0,i.r)(t),o=a(e,n);return o.parallels=function(t){return arguments.length?a(e=t[0]*r.uR,n=t[1]*r.uR):[e*r.RW,n*r.RW]},o}},54719:(t,e,n)=>{"use strict";if(n.d(e,{l:()=>u,Z:()=>s}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(15317);function o(t){return(0,r.OR)((r.ou+t)/2)}function u(t,e){var n=(0,r.mC)(t),i=t===e?(0,r.O$)(t):(0,r.cM)(n/(0,r.mC)(e))/(0,r.cM)(o(e)/o(t)),u=n*(0,r.sQ)(o(t),i)/i;if(!i)return a.hk;function s(t,e){u>0?e<-r.ou+r.Ho&&(e=-r.ou+r.Ho):e>r.ou-r.Ho&&(e=r.ou-r.Ho);var n=u/(0,r.sQ)(o(e),i);return[n*(0,r.O$)(i*t),u-n*(0,r.mC)(i*t)]}return s.invert=function(t,e){var n=u-e,a=(0,r.Xx)(i)*(0,r._b)(t*t+n*n),o=(0,r.fv)(t,(0,r.Wn)(n))*(0,r.Xx)(n);return n*i<0&&(o-=r.pi*(0,r.Xx)(t)*(0,r.Xx)(n)),[o/i,2*(0,r.z4)((0,r.sQ)(u/a,1/i))-r.ou]},s}function s(){return(0,i.o)(u).scale(109.5).parallels([30,30])}},41202:(t,e,n)=>{"use strict";if(n.d(e,{v:()=>o,Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(8145);function o(t,e){var n=(0,r.O$)(t),i=(n+(0,r.O$)(e))/2;if((0,r.Wn)(i){"use strict";if(n.d(e,{o:()=>o,Z:()=>u}),826==n.j)var r=n(66573);if(826==n.j)var i=n(32387);if(826==n.j)var a=n(67650);function o(t,e){var n=(0,r.mC)(t),i=t===e?(0,r.O$)(t):(n-(0,r.mC)(e))/(e-t),o=n/i+t;if((0,r.Wn)(i){"use strict";if(n.d(e,{V:()=>i}),826==n.j)var r=n(66573);function i(t){var e=(0,r.mC)(t);function n(t,n){return[t*e,(0,r.O$)(n)/e]}return n.invert=function(t,n){return[t/e,(0,r.ZR)(n*e)]},n}},74749:(t,e,n)=>{"use strict";if(n.d(e,{i:()=>f,Z:()=>l}),826==n.j)var r=n(93137);var i=n(66573),a=1.340264,o=-.081106,u=893e-6,s=.003796,c=(0,i._b)(3)/2;function f(t,e){var n=(0,i.ZR)(c*(0,i.O$)(e)),r=n*n,f=r*r*r;return[t*(0,i.mC)(n)/(c*(a+3*o*r+f*(7*u+9*s*r))),n*(a+o*r+f*(u+s*r))]}function l(){return(0,r.Z)(f).scale(177.158)}f.invert=function(t,e){for(var n,r=e,f=r*r,l=f*f*f,h=0;h<12&&(l=(f=(r-=n=(r*(a+o*f+l*(u+s*f))-e)/(a+3*o*f+l*(7*u+9*s*f)))*r)*f*f,!((0,i.Wn)(n){"use strict";if(n.d(e,{k:()=>i,Z:()=>a}),826==n.j)var r=n(93137);function i(t,e){return[t,e]}function a(){return(0,r.Z)(i).scale(152.63)}i.invert=i},80686:(t,e,n)=>{"use strict";if(n.d(e,{qg:()=>o,mF:()=>u,V6:()=>s,rf:()=>c}),826==n.j)var r=n(60600);if(826==n.j)var i=n(57620);function a(t,e,n){var a=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=a&&t.clipExtent(null),(0,r.Z)(n,t.stream(i.Z)),e(i.Z.result()),null!=a&&t.clipExtent(a),t}function o(t,e,n){return a(t,(function(n){var r=e[1][0]-e[0][0],i=e[1][1]-e[0][1],a=Math.min(r/(n[1][0]-n[0][0]),i/(n[1][1]-n[0][1])),o=+e[0][0]+(r-a*(n[1][0]+n[0][0]))/2,u=+e[0][1]+(i-a*(n[1][1]+n[0][1]))/2;t.scale(150*a).translate([o,u])}),n)}function u(t,e,n){return o(t,[[0,0],e],n)}function s(t,e,n){return a(t,(function(n){var r=+e,i=r/(n[1][0]-n[0][0]),a=(r-i*(n[1][0]+n[0][0]))/2,o=-i*n[0][1];t.scale(150*i).translate([a,o])}),n)}function c(t,e,n){return a(t,(function(n){var r=+e,i=r/(n[1][1]-n[0][1]),a=-i*n[0][0],o=(r-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([a,o])}),n)}},77164:(t,e,n)=>{"use strict";n.d(e,{M:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){var n=(0,r.mC)(e),i=(0,r.mC)(t)*n;return[n*(0,r.O$)(t)/i,(0,r.O$)(e)/i]}function u(){return(0,a.Z)(o).scale(144.049).clipAngle(60)}o.invert=(0,i.O)(r.z4)},47880:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(94892);if(826==n.j)var i=n(59350);if(826==n.j)var a=n(13582);if(826==n.j)var o=n(80686);if(826==n.j)var u=n(66573);function s(){var t,e,n,s,c,f,l,h=1,d=0,p=0,v=1,g=1,_=0,b=null,y=1,m=1,x=(0,a.l)({point:function(t,e){var n=D([t,e]);this.stream.point(n[0],n[1])}}),w=i.Z;function Z(){return y=h*v,m=h*g,f=l=null,D}function D(n){var r=n[0]*y,i=n[1]*m;if(_){var a=i*t-r*e;r=r*t+i*e,i=a}return[r+d,i+p]}return D.invert=function(n){var r=n[0]-d,i=n[1]-p;if(_){var a=i*t+r*e;r=r*t-i*e,i=a}return[r/y,i/m]},D.stream=function(t){return f&&l===t?f:f=x(w(l=t))},D.postclip=function(t){return arguments.length?(w=t,b=n=s=c=null,Z()):w},D.clipExtent=function(t){return arguments.length?(w=null==t?(b=n=s=c=null,i.Z):(0,r.Z)(b=+t[0][0],n=+t[0][1],s=+t[1][0],c=+t[1][1]),Z()):null==b?null:[[b,n],[s,c]]},D.scale=function(t){return arguments.length?(h=+t,Z()):h},D.translate=function(t){return arguments.length?(d=+t[0],p=+t[1],Z()):[d,p]},D.angle=function(n){return arguments.length?(_=n%360*u.uR,e=(0,u.O$)(_),t=(0,u.mC)(_),Z()):_*u.RW},D.reflectX=function(t){return arguments.length?(v=t?-1:1,Z()):v<0},D.reflectY=function(t){return arguments.length?(g=t?-1:1,Z()):g<0},D.fitExtent=function(t,e){return(0,o.qg)(D,t,e)},D.fitSize=function(t,e){return(0,o.mF)(D,t,e)},D.fitWidth=function(t,e){return(0,o.V6)(D,t,e)},D.fitHeight=function(t,e){return(0,o.rf)(D,t,e)},D}},93137:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>g,r:()=>_}),826==n.j)var r=n(98503);if(826==n.j)var i=n(24883);if(826==n.j)var a=n(94892);if(826==n.j)var o=n(81319);if(826==n.j)var u=n(59350);var s=n(66573);if(826==n.j)var c=n(85295);var f=n(13582);if(826==n.j)var l=n(80686);if(826==n.j)var h=n(9650);var d=(0,f.l)({point:function(t,e){this.stream.point(t*s.uR,e*s.uR)}});function p(t,e,n,r,i){function a(a,o){return[e+t*(a*=r),n-t*(o*=i)]}return a.invert=function(a,o){return[(a-e)/t*r,(n-o)/t*i]},a}function v(t,e,n,r,i,a){var o=(0,s.mC)(a),u=(0,s.O$)(a),c=o*t,f=u*t,l=o/t,h=u/t,d=(u*n-o*e)/t,p=(u*e+o*n)/t;function v(t,a){return[c*(t*=r)-f*(a*=i)+e,n-f*t-c*a]}return v.invert=function(t,e){return[r*(l*t-h*e+d),i*(p-h*t-l*e)]},v}function g(t){return _((function(){return t}))()}function _(t){var e,n,g,_,b,y,m,x,w,Z,D=150,k=480,E=250,A=0,j=0,C=0,M=0,F=0,B=0,S=1,N=1,T=null,z=r.Z,O=null,R=u.Z,P=.5;function I(t){return x(t[0]*s.uR,t[1]*s.uR)}function L(t){return(t=x.invert(t[0],t[1]))&&[t[0]*s.RW,t[1]*s.RW]}function U(){var t=v(D,0,0,S,N,B).apply(null,e(A,j)),r=(B?v:p)(D,k-t[0],E-t[1],S,N,B);return n=(0,c.I)(C,M,F),m=(0,o.Z)(e,r),x=(0,o.Z)(n,m),y=(0,h.Z)(m,P),$()}function $(){return w=Z=null,I}return I.stream=function(t){return w&&Z===t?w:w=d(function(t){return(0,f.l)({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(z(y(R(Z=t)))))},I.preclip=function(t){return arguments.length?(z=t,T=void 0,$()):z},I.postclip=function(t){return arguments.length?(R=t,O=g=_=b=null,$()):R},I.clipAngle=function(t){return arguments.length?(z=+t?(0,i.Z)(T=t*s.uR):(T=null,r.Z),$()):T*s.RW},I.clipExtent=function(t){return arguments.length?(R=null==t?(O=g=_=b=null,u.Z):(0,a.Z)(O=+t[0][0],g=+t[0][1],_=+t[1][0],b=+t[1][1]),$()):null==O?null:[[O,g],[_,b]]},I.scale=function(t){return arguments.length?(D=+t,U()):D},I.translate=function(t){return arguments.length?(k=+t[0],E=+t[1],U()):[k,E]},I.center=function(t){return arguments.length?(A=t[0]%360*s.uR,j=t[1]%360*s.uR,U()):[A*s.RW,j*s.RW]},I.rotate=function(t){return arguments.length?(C=t[0]%360*s.uR,M=t[1]%360*s.uR,F=t.length>2?t[2]%360*s.uR:0,U()):[C*s.RW,M*s.RW,F*s.RW]},I.angle=function(t){return arguments.length?(B=t%360*s.uR,U()):B*s.RW},I.reflectX=function(t){return arguments.length?(S=t?-1:1,U()):S<0},I.reflectY=function(t){return arguments.length?(N=t?-1:1,U()):N<0},I.precision=function(t){return arguments.length?(y=(0,h.Z)(m,P=t*t),$()):(0,s._b)(P)},I.fitExtent=function(t,e){return(0,l.qg)(I,t,e)},I.fitSize=function(t,e){return(0,l.mF)(I,t,e)},I.fitWidth=function(t,e){return(0,l.V6)(I,t,e)},I.fitHeight=function(t,e){return(0,l.rf)(I,t,e)},function(){return e=t.apply(this,arguments),I.invert=e.invert&&L,U()}}},15317:(t,e,n)=>{"use strict";n.d(e,{hk:()=>o,ZP:()=>u,iW:()=>s});var r=n(66573);if(826==n.j)var i=n(85295);if(826==n.j)var a=n(93137);function o(t,e){return[t,(0,r.cM)((0,r.OR)((r.ou+e)/2))]}function u(){return s(o).scale(961/r.BZ)}function s(t){var e,n,u,s=(0,a.Z)(t),c=s.center,f=s.scale,l=s.translate,h=s.clipExtent,d=null;function p(){var a=r.pi*f(),c=s((0,i.Z)(s.rotate()).invert([0,0]));return h(null==d?[[c[0]-a,c[1]-a],[c[0]+a,c[1]+a]]:t===o?[[Math.max(c[0]-a,d),e],[Math.min(c[0]+a,n),u]]:[[d,Math.max(c[1]-a,e)],[n,Math.min(c[1]+a,u)]])}return s.scale=function(t){return arguments.length?(f(t),p()):f()},s.translate=function(t){return arguments.length?(l(t),p()):l()},s.center=function(t){return arguments.length?(c(t),p()):c()},s.clipExtent=function(t){return arguments.length?(null==t?d=e=n=u=null:(d=+t[0][0],e=+t[0][1],n=+t[1][0],u=+t[1][1]),p()):null==d?null:[[d,e],[n,u]]},p()}o.invert=function(t,e){return[t,2*(0,r.z4)((0,r.Qq)(e))-r.ou]}},42617:(t,e,n)=>{"use strict";if(n.d(e,{K:()=>a,Z:()=>o}),826==n.j)var r=n(93137);var i=n(66573);function a(t,e){var n=e*e,r=n*n;return[t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function o(){return(0,r.Z)(a).scale(175.295)}a.invert=function(t,e){var n,r=e,a=25;do{var o=r*r,u=o*o;r-=n=(r*(1.007226+o*(.015085+u*(.028874*o-.044475-.005916*u)))-e)/(1.007226+o*(.045255+u*(.259866*o-.311325-.005916*11*u)))}while((0,i.Wn)(n)>i.Ho&&--a>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]}},77792:(t,e,n)=>{"use strict";n.d(e,{I:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){return[(0,r.mC)(e)*(0,r.O$)(t),(0,r.O$)(e)]}function u(){return(0,a.Z)(o).scale(249.5).clipAngle(90+r.Ho)}o.invert=(0,i.O)(r.ZR)},9650:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(67776);var i=n(66573);if(826==n.j)var a=n(13582);var o=(0,i.mC)(30*i.uR);function u(t,e){return+e?function(t,e){function n(r,a,u,s,c,f,l,h,d,p,v,g,_,b){var y=l-r,m=h-a,x=y*y+m*m;if(x>4*e&&_--){var w=s+p,Z=c+v,D=f+g,k=(0,i._b)(w*w+Z*Z+D*D),E=(0,i.ZR)(D/=k),A=(0,i.Wn)((0,i.Wn)(D)-1)e||(0,i.Wn)((y*F+m*B)/x-.5)>.3||s*p+c*v+f*g{"use strict";n.d(e,{T:()=>o,Z:()=>u});var r=n(66573),i=n(82210);if(826==n.j)var a=n(93137);function o(t,e){var n=(0,r.mC)(e),i=1+(0,r.mC)(t)*n;return[n*(0,r.O$)(t)/i,(0,r.O$)(e)/i]}function u(){return(0,a.Z)(o).scale(250).clipAngle(142)}o.invert=(0,i.O)((function(t){return 2*(0,r.z4)(t)}))},17025:(t,e,n)=>{"use strict";n.d(e,{F:()=>a,Z:()=>o});var r=n(66573);if(826==n.j)var i=n(15317);function a(t,e){return[(0,r.cM)((0,r.OR)((r.ou+e)/2)),-t]}function o(){var t=(0,i.iW)(a),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}a.invert=function(t,e){return[-e,2*(0,r.z4)((0,r.Qq)(t))-r.ou]}},85295:(t,e,n)=>{"use strict";if(n.d(e,{I:()=>o,Z:()=>f}),826==n.j)var r=n(81319);var i=n(66573);function a(t,e){return[(0,i.Wn)(t)>i.pi?t+Math.round(-t/i.BZ)*i.BZ:t,e]}function o(t,e,n){return(t%=i.BZ)?e||n?(0,r.Z)(s(t),c(e,n)):s(t):e||n?c(e,n):a}function u(t){return function(e,n){return[(e+=t)>i.pi?e-i.BZ:e<-i.pi?e+i.BZ:e,n]}}function s(t){var e=u(t);return e.invert=u(-t),e}function c(t,e){var n=(0,i.mC)(t),r=(0,i.O$)(t),a=(0,i.mC)(e),o=(0,i.O$)(e);function u(t,e){var u=(0,i.mC)(e),s=(0,i.mC)(t)*u,c=(0,i.O$)(t)*u,f=(0,i.O$)(e),l=f*n+s*r;return[(0,i.fv)(c*a-l*o,s*n-f*r),(0,i.ZR)(l*a+c*o)]}return u.invert=function(t,e){var u=(0,i.mC)(e),s=(0,i.mC)(t)*u,c=(0,i.O$)(t)*u,f=(0,i.O$)(e),l=f*a-c*o;return[(0,i.fv)(c*a+f*o,s*n+l*r),(0,i.ZR)(l*n-s*r)]},u}function f(t){function e(e){return(e=t(e[0]*i.uR,e[1]*i.uR))[0]*=i.RW,e[1]*=i.RW,e}return t=o(t[0]*i.uR,t[1]*i.uR,t.length>2?t[2]*i.uR:0),e.invert=function(e){return(e=t.invert(e[0]*i.uR,e[1]*i.uR))[0]*=i.RW,e[1]*=i.RW,e},e}a.invert=a},60600:(t,e,n)=>{"use strict";function r(t,e){t&&a.hasOwnProperty(t.type)&&a[t.type](t,e)}n.d(e,{Z:()=>s});var i={Feature:function(t,e){r(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,i=-1,a=n.length;++i{"use strict";function r(t){return{stream:i(t)}}function i(t){return function(e){var n=new a;for(var r in t)n[r]=t[r];return n.stream=e,n}}function a(){}n.d(e,{Z:()=>r,l:()=>i}),a.prototype={constructor:a,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}}},47033:(t,e,n)=>{"use strict";function r(t){return null==t?null:i(t)}function i(t){if("function"!=typeof t)throw new Error;return t}n.d(e,{j:()=>r,C:()=>i})},86642:(t,e,n)=>{"use strict";n.d(e,{t:()=>r,T:()=>i});var r=Array.prototype.slice;function i(t){for(var e,n,r=t.length;r;)n=Math.random()*r--|0,e=t[r],t[r]=t[n],t[n]=e;return t}},50287:(t,e,n)=>{"use strict";function r(t,e){return t.parent===e.parent?1:2}function i(t,e){return t+e.x}function a(t,e){return Math.max(t,e.y)}function o(){var t=r,e=1,n=1,o=!1;function u(r){var u,s=0;r.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(i,0)/t.length}(n),e.y=function(t){return 1+t.reduce(a,0)}(n)):(e.x=u?s+=t(e,u):0,e.y=0,u=e)}));var c=function(t){for(var e;e=t.children;)t=e[0];return t}(r),f=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(r),l=c.x-t(c,f)/2,h=f.x+t(f,c)/2;return r.eachAfter(o?function(t){t.x=(t.x-r.x)*e,t.y=(r.y-t.y)*n}:function(t){t.x=(t.x-l)/(h-l)*e,t.y=(1-(r.y?t.y/r.y:1))*n})}return u.separation=function(e){return arguments.length?(t=e,u):t},u.size=function(t){return arguments.length?(o=!1,e=+t[0],n=+t[1],u):o?null:[e,n]},u.nodeSize=function(t){return arguments.length?(o=!0,e=+t[0],n=+t[1],u):o?[e,n]:null},u}n.d(e,{Z:()=>o})},35227:(t,e,n)=>{"use strict";function r(){return 0}function i(t){return function(){return t}}n.d(e,{G:()=>r,Z:()=>i})},22210:(t,e,n)=>{"use strict";function r(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function i(t,e){var n,r,i,o,c,f=new s(t),l=+t.value&&(f.value=t.value),h=[f];for(null==e&&(e=a);n=h.pop();)if(l&&(n.value=+n.data.value),(i=e(n.data))&&(c=i.length))for(n.children=new Array(c),o=c-1;o>=0;--o)h.push(r=n.children[o]=new s(i[o])),r.parent=n,r.depth=n.depth+1;return f.eachBefore(u)}function a(t){return t.children}function o(t){t.data=t.data.data}function u(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function s(t){this.data=t,this.depth=this.height=0,this.parent=null}n.d(e,{NB:()=>s,le:()=>u,ZP:()=>i}),s.prototype=i.prototype={constructor:s,count:function(){return this.eachAfter(r)},each:function(t){var e,n,r,i,a=this,o=[a];do{for(e=o.reverse(),o=[];a=e.pop();)if(t(a),n=a.children)for(r=0,i=n.length;r=0;--n)i.push(e[n]);return this},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,i=r&&r.length;--i>=0;)n+=r[i].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;for(t=n.pop(),e=r.pop();t===e;)i=t,t=n.pop(),e=r.pop();return i}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){var t=[];return this.each((function(e){t.push(e)})),t},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return i(this).eachBefore(o)}}},27611:(t,e,n)=>{"use strict";if(n.d(e,{ki:()=>r.Z,bT:()=>i.ZP,P2:()=>a.Z,jA:()=>o.Z,O1:()=>u.Z,uK:()=>s.Z,QP:()=>c.Z,G_:()=>f.Z,pN:()=>l.Z,wL:()=>h.Z,LQ:()=>d.Z,Km:()=>p.Z,E_:()=>v.Z,o$:()=>g.ZP,eA:()=>_.Z}),826==n.j)var r=n(50287);if(826==n.j)var i=n(22210);if(826==n.j)var a=n(3438);if(826==n.j)var o=n(31750);if(826==n.j)var u=n(92589);if(826==n.j)var s=n(5610);if(826==n.j)var c=n(10018);if(826==n.j)var f=n(6046);if(826==n.j)var l=n(23062);if(826==n.j)var h=n(29483);if(826==n.j)var d=n(44925);if(826==n.j)var p=n(12460);if(826==n.j)var v=n(44164);if(826==n.j)var g=n(21086);if(826==n.j)var _=n(3346)},92589:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(86642);function i(t){for(var e,n,i=0,o=(t=(0,r.T)(r.t.call(t))).length,s=[];i0&&n*n>r*r+i*i}function s(t,e){for(var n=0;n{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(31750);if(826==n.j)var i=n(47033);if(826==n.j)var a=n(35227);function o(t){return Math.sqrt(t.value)}function u(){var t=null,e=1,n=1,r=a.G;function u(i){return i.x=e/2,i.y=n/2,t?i.eachBefore(s(t)).eachAfter(c(r,.5)).eachBefore(f(1)):i.eachBefore(s(o)).eachAfter(c(a.G,1)).eachAfter(c(r,i.r/Math.min(e,n))).eachBefore(f(Math.min(e,n)/(2*i.r))),i}return u.radius=function(e){return arguments.length?(t=(0,i.j)(e),u):t},u.size=function(t){return arguments.length?(e=+t[0],n=+t[1],u):[e,n]},u.padding=function(t){return arguments.length?(r="function"==typeof t?t:(0,a.Z)(+t),u):r},u}function s(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0))}}function c(t,e){return function(n){if(i=n.children){var i,a,o,u=i.length,s=t(n)*e||0;if(s)for(a=0;a{"use strict";if(n.d(e,{O:()=>s,Z:()=>c}),826==n.j)var r=n(92589);function i(t,e,n){var r,i,a,o,u=t.x-e.x,s=t.y-e.y,c=u*u+s*s;c?(i=e.r+n.r,i*=i,o=t.r+n.r,i>(o*=o)?(r=(c+o-i)/(2*c),a=Math.sqrt(Math.max(0,o/c-r*r)),n.x=t.x-r*u-a*s,n.y=t.y-r*s+a*u):(r=(c+i-o)/(2*c),a=Math.sqrt(Math.max(0,i/c-r*r)),n.x=e.x+r*u-a*s,n.y=e.y+r*s+a*u)):(n.x=e.x+n.r,n.y=e.y)}function a(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,i=e.y-t.y;return n>0&&n*n>r*r+i*i}function o(t){var e=t._,n=t.next._,r=e.r+n.r,i=(e.x*n.r+n.x*e.r)/r,a=(e.y*n.r+n.y*e.r)/r;return i*i+a*a}function u(t){this._=t,this.next=null,this.previous=null}function s(t){if(!(c=t.length))return 0;var e,n,s,c,f,l,h,d,p,v,g;if((e=t[0]).x=0,e.y=0,!(c>1))return e.r;if(n=t[1],e.x=-n.r,n.x=e.r,n.y=0,!(c>2))return e.r+n.r;i(n,e,s=t[2]),e=new u(e),n=new u(n),s=new u(s),e.next=s.previous=n,n.next=e.previous=s,s.next=n.previous=e;t:for(h=3;h{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(86228);if(826==n.j)var i=n(44925);function a(){var t=1,e=1,n=0,a=!1;function o(o){var u=o.height+1;return o.x0=o.y0=n,o.x1=t,o.y1=e/u,o.eachBefore(function(t,e){return function(r){r.children&&(0,i.Z)(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var a=r.x0,o=r.y0,u=r.x1-n,s=r.y1-n;u{"use strict";if(n.d(e,{Z:()=>c}),826==n.j)var r=n(47033);if(826==n.j)var i=n(22210);var a={depth:-1},o={};function u(t){return t.id}function s(t){return t.parentId}function c(){var t=u,e=s;function n(n){var r,u,s,c,f,l,h,d=n.length,p=new Array(d),v={};for(u=0;u0)throw new Error("cycle");return s}return n.id=function(e){return arguments.length?(t=(0,r.C)(e),n):t},n.parentId=function(t){return arguments.length?(e=(0,r.C)(t),n):e},n}},6046:(t,e,n)=>{"use strict";n.d(e,{Z:()=>f});var r=n(22210);function i(t,e){return t.parent===e.parent?1:2}function a(t){var e=t.children;return e?e[0]:t.t}function o(t){var e=t.children;return e?e[e.length-1]:t.t}function u(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function s(t,e,n){return t.a.parent===e.parent?t.a:n}function c(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function f(){var t=i,e=1,n=1,r=null;function f(i){var a=function(t){for(var e,n,r,i,a,o=new c(t,0),u=[o];e=u.pop();)if(r=e._.children)for(e.children=new Array(a=r.length),i=a-1;i>=0;--i)u.push(n=e.children[i]=new c(r[i],i)),n.parent=e;return(o.parent=new c(null,0)).children=[o],o}(i);if(a.eachAfter(l),a.parent.m=-a.z,a.eachBefore(h),r)i.eachBefore(d);else{var o=i,u=i,s=i;i.eachBefore((function(t){t.xu.x&&(u=t),t.depth>s.depth&&(s=t)}));var f=o===u?1:t(o,u)/2,p=f-o.x,v=e/(u.x+f+p),g=n/(s.depth||1);i.eachBefore((function(t){t.x=(t.x+p)*v,t.y=t.depth*g}))}return i}function l(e){var n=e.children,r=e.parent.children,i=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,i=t.children,a=i.length;--a>=0;)(e=i[a]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var c=(n[0].z+n[n.length-1].z)/2;i?(e.z=i.z+t(e._,i._),e.m=e.z-c):e.z=c}else i&&(e.z=i.z+t(e._,i._));e.parent.A=function(e,n,r){if(n){for(var i,c=e,f=e,l=n,h=c.parent.children[0],d=c.m,p=f.m,v=l.m,g=h.m;l=o(l),c=a(c),l&&c;)h=a(h),(f=o(f)).a=e,(i=l.z+v-c.z-d+t(l._,c._))>0&&(u(s(l,e,r),e,i),d+=i,p+=i),v+=l.m,d+=c.m,g+=h.m,p+=f.m;l&&!o(f)&&(f.t=l,f.m+=v-p),c&&!a(h)&&(h.t=c,h.m+=d-g,r=e)}return r}(e,i,e.parent.A||r[0])}function h(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function d(t){t.x*=e,t.y=t.depth*n}return f.separation=function(e){return arguments.length?(t=e,f):t},f.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],f):r?null:[e,n]},f.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],f):r?[e,n]:null},f}c.prototype=Object.create(r.NB.prototype)},29483:(t,e,n)=>{"use strict";function r(t,e,n,r,i){var a,o,u=t.children,s=u.length,c=new Array(s+1);for(c[0]=o=a=0;a=n-1){var f=u[e];return f.x0=i,f.y0=a,f.x1=o,void(f.y1=s)}for(var l=c[e],h=r/2+l,d=e+1,p=n-1;d>>1;c[v]s-a){var b=(i*_+o*g)/r;t(e,d,g,i,a,b,s),t(d,n,_,b,a,o,s)}else{var y=(a*_+s*g)/r;t(e,d,g,i,a,o,y),t(d,n,_,i,y,o,s)}}(0,s,t.value,e,n,r,i)}n.d(e,{Z:()=>r})},44925:(t,e,n)=>{"use strict";function r(t,e,n,r,i){for(var a,o=t.children,u=-1,s=o.length,c=t.value&&(r-e)/t.value;++ur})},23062:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(86228);if(826==n.j)var i=n(21086);if(826==n.j)var a=n(47033);if(826==n.j)var o=n(35227);function u(){var t=i.ZP,e=!1,n=1,u=1,s=[0],c=o.G,f=o.G,l=o.G,h=o.G,d=o.G;function p(t){return t.x0=t.y0=0,t.x1=n,t.y1=u,t.eachBefore(v),s=[0],e&&t.eachBefore(r.Z),t}function v(e){var n=s[e.depth],r=e.x0+n,i=e.y0+n,a=e.x1-n,o=e.y1-n;a{"use strict";n.d(e,{Z:()=>o});var r=n(44925),i=n(12460),a=n(21086);const o=function t(e){function n(t,n,o,u,s){if((c=t._squarify)&&c.ratio===e)for(var c,f,l,h,d,p=-1,v=c.length,g=t.value;++p1?e:1)},n}(a.Sk)},86228:(t,e,n)=>{"use strict";function r(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}n.d(e,{Z:()=>r})},12460:(t,e,n)=>{"use strict";function r(t,e,n,r,i){for(var a,o=t.children,u=-1,s=o.length,c=t.value&&(i-n)/t.value;++ur})},44164:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(44925);if(826==n.j)var i=n(12460);function a(t,e,n,a,o){(1&t.depth?i.Z:r.Z)(t,e,n,a,o)}},21086:(t,e,n)=>{"use strict";n.d(e,{Sk:()=>a,DD:()=>o,ZP:()=>u});var r=n(44925),i=n(12460),a=(1+Math.sqrt(5))/2;function o(t,e,n,a,o,u){for(var s,c,f,l,h,d,p,v,g,_,b,y=[],m=e.children,x=0,w=0,Z=m.length,D=e.value;xp&&(p=c),b=h*h*_,(v=Math.max(p/b,b/d))>g){h-=c;break}g=v}y.push(s={value:h,dice:f1?e:1)},n}(a)},47639:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,M:()=>o}),826==n.j)var r=n(69777);if(826==n.j)var i=n(43289);function a(t,e){return((0,i.v)(e)?i.Z:o)(t,e)}function o(t,e){var n,i=e?e.length:0,a=t?Math.min(i,t.length):0,o=new Array(a),u=new Array(i);for(n=0;n{"use strict";function r(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}function i(t){var e=t.length-1;return function(n){var i=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],u=i>0?t[i-1]:2*a-o,s=ir,Z:()=>i})},6984:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(67855);function i(t){var e=t.length;return function(n){var i=Math.floor(((n%=1)<0?++n:n)*e),a=t[(i+e-1)%e],o=t[i%e],u=t[(i+1)%e],s=t[(i+2)%e];return(0,r.t)((n-i/e)*e,a,o,u,s)}}},1234:(t,e,n)=>{"use strict";if(n.d(e,{wx:()=>a,yi:()=>o,ZP:()=>u}),826==n.j)var r=n(88992);function i(t,e){return function(n){return t+n*e}}function a(t,e){var n=e-t;return n?i(t,n>180||n<-180?n-360*Math.round(n/360):n):(0,r.Z)(isNaN(t)?e:t)}function o(t){return 1==(t=+t)?u:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):(0,r.Z)(isNaN(e)?n:e)}}function u(t,e){var n=e-t;return n?i(t,n):(0,r.Z)(isNaN(t)?e:t)}},88992:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},20546:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,B:()=>u});var r=n(29607),i=n(1234);function a(t){return function e(n){function a(e,a){var o=t((e=(0,r.Z)(e)).h,(a=(0,r.Z)(a)).h),u=(0,i.ZP)(e.s,a.s),s=(0,i.ZP)(e.l,a.l),c=(0,i.ZP)(e.opacity,a.opacity);return function(t){return e.h=o(t),e.s=u(t),e.l=s(Math.pow(t,n)),e.opacity=c(t),e+""}}return n=+n,a.gamma=e,a}(1)}const o=a(i.wx);var u=a(i.ZP)},91255:(t,e,n)=>{"use strict";function r(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}n.d(e,{Z:()=>r})},32165:(t,e,n)=>{"use strict";function r(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}n.d(e,{Z:()=>r})},87286:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,b:()=>u});var r=n(20966),i=n(1234);function a(t){return function(e,n){var a=t((e=(0,r.Uc)(e)).h,(n=(0,r.Uc)(n)).h),o=(0,i.ZP)(e.c,n.c),u=(0,i.ZP)(e.l,n.l),s=(0,i.ZP)(e.opacity,n.opacity);return function(t){return e.h=a(t),e.c=o(t),e.l=u(t),e.opacity=s(t),e+""}}}const o=a(i.wx);var u=a(i.ZP)},43780:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,q:()=>u});var r=n(68847),i=n(1234);function a(t){return function(e,n){var a=t((e=(0,r.Ym)(e)).h,(n=(0,r.Ym)(n)).h),o=(0,i.ZP)(e.s,n.s),u=(0,i.ZP)(e.l,n.l),s=(0,i.ZP)(e.opacity,n.opacity);return function(t){return e.h=a(t),e.s=o(t),e.l=u(t),e.opacity=s(t),e+""}}}const o=a(i.wx);var u=a(i.ZP)},7806:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(1234);function i(t,e){var n=(0,r.wx)(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}},67982:(t,e,n)=>{"use strict";if(n.d(e,{sX:()=>r.Z,Ck:()=>i.Z,nH:()=>a.Z,FO:()=>o.Z,NW:()=>u.Z,Tp:()=>s.Z,EP:()=>c.Z,k4:()=>f.Z,qN:()=>l.Z,IW:()=>h.Z,uL:()=>d.Z,IT:()=>p.Z,Yb:()=>v.Y,wL:()=>v.w,JX:()=>g.Z,LX:()=>_.ZP,u1:()=>_.hD,F5:()=>_.YD,US:()=>b.Z,H:()=>b.q,uU:()=>y.Z,JH:()=>m.Z,Yr:()=>m.b,Ji:()=>x.Z,tR:()=>x.B,sO:()=>w.Z,q$:()=>Z.Z}),826==n.j)var r=n(69777);if(826==n.j)var i=n(47639);if(826==n.j)var a=n(67855);if(826==n.j)var o=n(6984);if(826==n.j)var u=n(91255);if(826==n.j)var s=n(32165);if(826==n.j)var c=n(7806);if(826==n.j)var f=n(98876);if(826==n.j)var l=n(43289);if(826==n.j)var h=n(73363);if(826==n.j)var d=n(74672);if(826==n.j)var p=n(76060);if(826==n.j)var v=n(88994);if(826==n.j)var g=n(68498);if(826==n.j)var _=n(78978);if(826==n.j)var b=n(43780);if(826==n.j)var y=n(88751);if(826==n.j)var m=n(87286);if(826==n.j)var x=n(20546);if(826==n.j)var w=n(87475);if(826==n.j)var Z=n(78106)},88751:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(20966);if(826==n.j)var i=n(1234);function a(t,e){var n=(0,i.ZP)((t=(0,r.ZP)(t)).l,(e=(0,r.ZP)(e)).l),a=(0,i.ZP)(t.a,e.a),o=(0,i.ZP)(t.b,e.b),u=(0,i.ZP)(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=a(e),t.b=o(e),t.opacity=u(e),t+""}}},98876:(t,e,n)=>{"use strict";function r(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}n.d(e,{Z:()=>r})},43289:(t,e,n)=>{"use strict";function r(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,i=e.slice();return function(a){for(n=0;nr,v:()=>i})},73363:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(69777);function i(t,e){var n,i={},a={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?i[n]=(0,r.Z)(t[n],e[n]):a[n]=e[n];return function(t){for(n in i)a[n]=i[n](t);return a}}},87475:(t,e,n)=>{"use strict";function r(t,e){for(var n=0,r=e.length-1,i=e[0],a=new Array(r<0?0:r);nr})},78106:(t,e,n)=>{"use strict";function r(t,e){for(var n=new Array(e),r=0;rr})},78978:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>u,hD:()=>c,YD:()=>f});var r=n(68847),i=n(67855),a=n(6984),o=n(1234);const u=function t(e){var n=(0,o.yi)(e);function i(t,e){var i=n((t=(0,r.B8)(t)).r,(e=(0,r.B8)(e)).r),a=n(t.g,e.g),u=n(t.b,e.b),s=(0,o.ZP)(t.opacity,e.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=u(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function s(t){return function(e){var n,i,a=e.length,o=new Array(a),u=new Array(a),s=new Array(a);for(n=0;n{"use strict";function r(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}n.d(e,{Z:()=>r})},76060:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(98876);var i=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,a=new RegExp(i.source,"g");function o(t,e){var n,o,u,s=i.lastIndex=a.lastIndex=0,c=-1,f=[],l=[];for(t+="",e+="";(n=i.exec(t))&&(o=a.exec(e));)(u=o.index)>s&&(u=e.slice(s,u),f[c]?f[c]+=u:f[++c]=u),(n=n[0])===(o=o[0])?f[c]?f[c]+=o:f[++c]=o:(f[++c]=null,l.push({i:c,x:(0,r.Z)(n,o)})),s=a.lastIndex;return s{"use strict";n.d(e,{y:()=>i,Z:()=>a});var r=180/Math.PI,i={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function a(t,e,n,i,a,o){var u,s,c;return(u=Math.sqrt(t*t+e*e))&&(t/=u,e/=u),(c=t*n+e*i)&&(n-=t*c,i-=e*c),(s=Math.sqrt(n*n+i*i))&&(n/=s,i/=s,c/=s),t*i{"use strict";n.d(e,{Y:()=>f,w:()=>l});var r,i,a,o,u=n(98876),s=n(97367);function c(t,e,n,r){function i(t){return t.length?t.pop()+" ":""}return function(a,o){var s=[],c=[];return a=t(a),o=t(o),function(t,r,i,a,o,s){if(t!==i||r!==a){var c=o.push("translate(",null,e,null,n);s.push({i:c-4,x:(0,u.Z)(t,i)},{i:c-2,x:(0,u.Z)(r,a)})}else(i||a)&&o.push("translate("+i+e+a+n)}(a.translateX,a.translateY,o.translateX,o.translateY,s,c),function(t,e,n,a){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:(0,u.Z)(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:(0,u.Z)(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:(0,u.Z)(t,n)},{i:s-2,x:(0,u.Z)(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n{"use strict";if(n.d(e,{Z:()=>h}),826==n.j)var r=n(68847);if(826==n.j)var i=n(78978);if(826==n.j)var a=n(47639);if(826==n.j)var o=n(91255);if(826==n.j)var u=n(98876);if(826==n.j)var s=n(73363);if(826==n.j)var c=n(76060);if(826==n.j)var f=n(88992);if(826==n.j)var l=n(43289);function h(t,e){var n,h=typeof e;return null==e||"boolean"===h?(0,f.Z)(e):("number"===h?u.Z:"string"===h?(n=(0,r.ZP)(e))?(e=n,i.ZP):c.Z:e instanceof r.ZP?i.ZP:e instanceof Date?o.Z:(0,l.v)(e)?l.Z:Array.isArray(e)?a.M:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?s.Z:u.Z)(t,e)}},68498:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=Math.SQRT2;function i(t){return((t=Math.exp(t))+1/t)/2}function a(t,e){var n,a,o=t[0],u=t[1],s=t[2],c=e[0],f=e[1],l=e[2],h=c-o,d=f-u,p=h*h+d*d;if(p<1e-12)a=Math.log(l/s)/r,n=function(t){return[o+t*h,u+t*d,s*Math.exp(r*t*a)]};else{var v=Math.sqrt(p),g=(l*l-s*s+4*p)/(2*s*2*v),_=(l*l-s*s-4*p)/(2*l*2*v),b=Math.log(Math.sqrt(g*g+1)-g),y=Math.log(Math.sqrt(_*_+1)-_);a=(y-b)/r,n=function(t){var e,n=t*a,c=i(b),f=s/(2*v)*(c*(e=r*n+b,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(b));return[o+f*h,u+f*d,s*c/i(r*n+b)]}}return n.duration=1e3*a,n}},42540:(t,e,n)=>{"use strict";if(n.d(e,{E:()=>r.Z}),826==n.j)var r=n(91672)},91672:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c});var r=Math.PI,i=2*r,a=1e-6,o=i-a;function u(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function s(){return new u}u.prototype=s.prototype={constructor:u,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r)},bezierCurveTo:function(t,e,n,r,i,a){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+i)+","+(this._y1=+a)},arcTo:function(t,e,n,i,o){t=+t,e=+e,n=+n,i=+i,o=+o;var u=this._x1,s=this._y1,c=n-t,f=i-e,l=u-t,h=s-e,d=l*l+h*h;if(o<0)throw new Error("negative radius: "+o);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(d>a)if(Math.abs(h*c-f*l)>a&&o){var p=n-u,v=i-s,g=c*c+f*f,_=p*p+v*v,b=Math.sqrt(g),y=Math.sqrt(d),m=o*Math.tan((r-Math.acos((g+d-_)/(2*b*y)))/2),x=m/y,w=m/b;Math.abs(x-1)>a&&(this._+="L"+(t+x*l)+","+(e+x*h)),this._+="A"+o+","+o+",0,0,"+ +(h*p>l*v)+","+(this._x1=t+w*c)+","+(this._y1=e+w*f)}else this._+="L"+(this._x1=t)+","+(this._y1=e)},arc:function(t,e,n,u,s,c){t=+t,e=+e,c=!!c;var f=(n=+n)*Math.cos(u),l=n*Math.sin(u),h=t+f,d=e+l,p=1^c,v=c?u-s:s-u;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+h+","+d:(Math.abs(this._x1-h)>a||Math.abs(this._y1-d)>a)&&(this._+="L"+h+","+d),n&&(v<0&&(v=v%i+i),v>o?this._+="A"+n+","+n+",0,1,"+p+","+(t-f)+","+(e-l)+"A"+n+","+n+",0,1,"+p+","+(this._x1=h)+","+(this._y1=d):v>a&&(this._+="A"+n+","+n+",0,"+ +(v>=r)+","+p+","+(this._x1=t+n*Math.cos(s))+","+(this._y1=e+n*Math.sin(s))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const c=826==n.j?s:null},82162:(t,e,n)=>{"use strict";function r(t){for(var e,n=-1,r=t.length,i=t[r-1],a=0;++nr})},81473:(t,e,n)=>{"use strict";function r(t){for(var e,n,r=-1,i=t.length,a=0,o=0,u=t[i-1],s=0;++rr})},83972:(t,e,n)=>{"use strict";function r(t,e){for(var n,r,i=t.length,a=t[i-1],o=e[0],u=e[1],s=a[0],c=a[1],f=!1,l=0;lu!=c>u&&o<(s-n)*(u-r)/(c-r)+n&&(f=!f),s=n,c=r;return f}n.d(e,{Z:()=>r})},69847:(t,e,n)=>{"use strict";function r(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}n.d(e,{Z:()=>r})},50880:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(69847);function i(t,e){return t[0]-e[0]||t[1]-e[1]}function a(t){for(var e=t.length,n=[0,1],i=2,a=2;a1&&(0,r.Z)(t[n[i-2]],t[n[i-1]],t[a])<=0;)--i;n[i++]=a}return n.slice(0,i)}function o(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),o=new Array(n);for(e=0;e=0;--e)l.push(t[r[u[e]][2]]);for(e=+c;e{"use strict";if(n.d(e,{mI:()=>r.Z,tO:()=>i.Z,WF:()=>a.Z,Q6:()=>o.Z,NZ:()=>u.Z}),826==n.j)var r=n(82162);if(826==n.j)var i=n(81473);if(826==n.j)var a=n(50880);if(826==n.j)var o=n(83972);if(826==n.j)var u=n(40495)},40495:(t,e,n)=>{"use strict";function r(t){for(var e,n,r=-1,i=t.length,a=t[i-1],o=a[0],u=a[1],s=0;++rr})},93365:(t,e,n)=>{"use strict";if(n.d(e,{T:()=>r.Z}),826==n.j)var r=n(94673)},7196:(t,e,n)=>{"use strict";function r(t,e,n,r,i){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=i}n.d(e,{Z:()=>r})},94673:(t,e,n)=>{"use strict";function r(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var i,a,o,u,s,c,f,l,h,d=t._root,p={data:r},v=t._x0,g=t._y0,_=t._x1,b=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((c=e>=(a=(v+_)/2))?v=a:_=a,(f=n>=(o=(g+b)/2))?g=o:b=o,i=d,!(d=d[l=f<<1|c]))return i[l]=p,t;if(u=+t._x.call(null,d.data),s=+t._y.call(null,d.data),e===u&&n===s)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(c=e>=(a=(v+_)/2))?v=a:_=a,(f=n>=(o=(g+b)/2))?g=o:b=o}while((l=f<<1|c)==(h=(s>=o)<<1|u>=a));return i[h]=d,i[l]=p,t}n.d(e,{Z:()=>u});var i=n(7196);function a(t){return t[0]}function o(t){return t[1]}function u(t,e,n){var r=new s(null==e?a:e,null==n?o:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function s(t,e,n,r,i,a){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0}function c(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var f=u.prototype=s.prototype;f.copy=function(){var t,e,n=new s(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=c(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(e=r.source[i])&&(e.length?t.push({source:e,target:r.target[i]=new Array(4)}):r.target[i]=c(e));return n},f.add=function(t){var e=+this._x.call(null,t),n=+this._y.call(null,t);return r(this.cover(e,n),e,n,t)},f.addAll=function(t){var e,n,i,a,o=t.length,u=new Array(o),s=new Array(o),c=1/0,f=1/0,l=-1/0,h=-1/0;for(n=0;nl&&(l=i),ah&&(h=a));if(c>l||f>h)return this;for(this.cover(c,f).cover(l,h),n=0;nt||t>=i||r>e||e>=a;)switch(u=(ed||(o=c.y0)>p||(u=c.x1)=b)<<1|t>=_)&&(c=v[v.length-1],v[v.length-1]=v[v.length-1-f],v[v.length-1-f]=c)}else{var y=t-+this._x.call(null,g.data),m=e-+this._y.call(null,g.data),x=y*y+m*m;if(x=(u=(p+g)/2))?p=u:g=u,(f=o>=(s=(v+_)/2))?v=s:_=s,e=d,!(d=d[l=f<<1|c]))return this;if(!d.length)break;(e[l+1&3]||e[l+2&3]||e[l+3&3])&&(n=e,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):e?(i?e[l]=i:delete e[l],(d=e[0]||e[1]||e[2]||e[3])&&d===(e[3]||e[2]||e[1]||e[0])&&!d.length&&(n?n[h]=d:this._root=d),this):(this._root=i,this)},f.removeAll=function(t){for(var e=0,n=t.length;e{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666")},25673:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666")},52399:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928")},43642:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2")},62514:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc")},94841:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999")},33536:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3")},24966:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f")},27561:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab")},8475:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r=(0,n(89589).Z)("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf")},89589:(t,e,n)=>{"use strict";function r(t){for(var e=t.length/6|0,n=new Array(e),r=0;rr})},28133:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(r.Z);const o=(0,i.Z)(a)},91233:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(r.Z);const o=(0,i.Z)(a)},33037:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(r.Z);const o=(0,i.Z)(a)},15333:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(r.Z);const o=(0,i.Z)(a)},21594:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(r.Z);const o=(0,i.Z)(a)},39418:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(r.Z);const o=(0,i.Z)(a)},65648:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(r.Z);const o=(0,i.Z)(a)},10549:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(r.Z);const o=(0,i.Z)(a)},30656:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(r.Z);const o=(0,i.Z)(a)},40989:(t,e,n)=>{"use strict";if(n.d(e,{Cn:()=>r.Z,Mr:()=>i.Z,Xg:()=>a.Z,xH:()=>o.Z,rp:()=>u.Z,i4:()=>s.Z,yK:()=>c.Z,W1:()=>f.Z,UC:()=>l.Z,K2:()=>h.Z,yl:()=>d.Z,QA:()=>d.r,nn:()=>p.Z,Uh:()=>p.r,qw:()=>v.Z,Lx:()=>v.r,xN:()=>g.Z,$K:()=>g.r,De:()=>_.Z,HW:()=>_.r,PL:()=>b.Z,u_:()=>b.r,zJ:()=>y.Z,XX:()=>y.r,BT:()=>m.Z,Kr:()=>m.r,T0:()=>x.Z,lq:()=>x.r,pl:()=>w.Z,S1:()=>w.r,hb:()=>Z.Z,DQ:()=>Z.r,Xw:()=>D.Z,AT:()=>D.r,RZ:()=>k.Z,MX:()=>k.r,S7:()=>E.Z,g1:()=>E.r,GM:()=>A.Z,UV:()=>A.r,cU:()=>j.Z,F6:()=>j.r,A4:()=>C.Z,zs:()=>C.r,Ht:()=>M.Z,Yi:()=>M.r,aE:()=>F.Z,GE:()=>F.r,Y_:()=>B.Z,Gb:()=>B.r,cj:()=>S.Z,M7:()=>S.r,sY:()=>N.Z,KH:()=>N.r,M:()=>T.Z,Yo:()=>T.r,A_:()=>z.Z,bU:()=>z.r,XW:()=>O.Z,DR:()=>O.r,bc:()=>R.Z,zU:()=>R.r,n$:()=>P.Z,P0:()=>P.r,r1:()=>I.Z,yB:()=>L.Z,IC:()=>U.ZP,AO:()=>U.s7,vc:()=>U.H7,OO:()=>$.Z,_B:()=>H.Z,V:()=>q.ZP,Gi:()=>q.uX,sN:()=>q.yy,iA:()=>q.zD}),826==n.j)var r=n(8475);if(826==n.j)var i=n(45795);if(826==n.j)var a=n(25673);if(826==n.j)var o=n(52399);if(826==n.j)var u=n(43642);if(826==n.j)var s=n(62514);if(826==n.j)var c=n(94841);if(826==n.j)var f=n(33536);if(826==n.j)var l=n(24966);if(826==n.j)var h=n(27561);if(826==n.j)var d=n(28133);if(826==n.j)var p=n(91233);if(826==n.j)var v=n(33037);if(826==n.j)var g=n(15333);if(826==n.j)var _=n(21594);if(826==n.j)var b=n(39418);if(826==n.j)var y=n(65648);if(826==n.j)var m=n(10549);if(826==n.j)var x=n(30656);if(826==n.j)var w=n(52149);if(826==n.j)var Z=n(43261);if(826==n.j)var D=n(4267);if(826==n.j)var k=n(22504);if(826==n.j)var E=n(8302);if(826==n.j)var A=n(93418);if(826==n.j)var j=n(65972);if(826==n.j)var C=n(1906);if(826==n.j)var M=n(44447);if(826==n.j)var F=n(5201);if(826==n.j)var B=n(5768);if(826==n.j)var S=n(91599);if(826==n.j)var N=n(61945);if(826==n.j)var T=n(99506);if(826==n.j)var z=n(54208);if(826==n.j)var O=n(64914);if(826==n.j)var R=n(90202);if(826==n.j)var P=n(7491);if(826==n.j)var I=n(3666);if(826==n.j)var L=n(35098);if(826==n.j)var U=n(155);if(826==n.j)var $=n(35996);if(826==n.j)var H=n(52858);if(826==n.j)var q=n(44687)},11303:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(78978);function i(t){return(0,r.hD)(t[t.length-1])}},52149:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(r.Z);const o=(0,i.Z)(a)},43261:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(r.Z);const o=(0,i.Z)(a)},4267:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(r.Z);const o=(0,i.Z)(a)},22504:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(r.Z);const o=(0,i.Z)(a)},93418:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(r.Z);const o=(0,i.Z)(a)},8302:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(r.Z);const o=(0,i.Z)(a)},65972:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(r.Z);const o=(0,i.Z)(a)},1906:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(r.Z);const o=(0,i.Z)(a)},5201:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(r.Z);const o=(0,i.Z)(a)},44447:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(r.Z);const o=(0,i.Z)(a)},5768:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(r.Z);const o=(0,i.Z)(a)},91599:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(r.Z);const o=(0,i.Z)(a)},3666:(t,e,n)=>{"use strict";function r(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}n.d(e,{Z:()=>r})},35098:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(29607);const i=(0,n(20546).B)((0,r.Z)(300,.5,0),(0,r.Z)(-240,.5,1))},155:(t,e,n)=>{"use strict";n.d(e,{s7:()=>a,H7:()=>o,ZP:()=>s});var r=n(29607),i=n(20546),a=(0,i.B)((0,r.Z)(-100,.75,.35),(0,r.Z)(80,1.5,.8)),o=(0,i.B)((0,r.Z)(260,.75,.35),(0,r.Z)(80,1.5,.8)),u=(0,r.Z)();function s(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return u.h=360*t-100,u.s=1.5-1.5*e,u.l=.8-.9*e,u+""}},35996:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=(0,n(68847).B8)(),i=Math.PI/3,a=2*Math.PI/3;function o(t){var e;return t=(.5-t)*Math.PI,r.r=255*(e=Math.sin(t))*e,r.g=255*(e=Math.sin(t+i))*e,r.b=255*(e=Math.sin(t+a))*e,r+""}},52858:(t,e,n)=>{"use strict";function r(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}n.d(e,{Z:()=>r})},44687:(t,e,n)=>{"use strict";n.d(e,{ZP:()=>a,uX:()=>o,yy:()=>u,zD:()=>s});var r=n(89589);function i(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const a=i((0,r.Z)("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var o=i((0,r.Z)("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),u=i((0,r.Z)("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),s=i((0,r.Z)("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"))},61945:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(r.Z);const o=(0,i.Z)(a)},99506:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(r.Z);const o=(0,i.Z)(a)},54208:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(r.Z);const o=(0,i.Z)(a)},7491:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(r.Z);const o=(0,i.Z)(a)},64914:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(r.Z);const o=(0,i.Z)(a)},90202:(t,e,n)=>{"use strict";n.d(e,{r:()=>a,Z:()=>o});var r=n(89589),i=n(11303),a=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(r.Z);const o=(0,i.Z)(a)},46973:(t,e,n)=>{"use strict";n.d(e,{WU:()=>i,jH:()=>a});var r,i,a,o=n(29053),u=n(36159),s=n(49613),c=n(47681),f=n(52003),l=n(1166),h=n(61903),d=n(81015),p=Array.prototype.map,v=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];r=function(t){var e=void 0===t.grouping||void 0===t.thousands?d.Z:(0,u.Z)(p.call(t.grouping,Number),t.thousands+""),n=void 0===t.currency?"":t.currency[0]+"",r=void 0===t.currency?"":t.currency[1]+"",i=void 0===t.decimal?".":t.decimal+"",a=void 0===t.numerals?d.Z:(0,s.Z)(p.call(t.numerals,String)),g=void 0===t.percent?"%":t.percent+"",_=void 0===t.minus?"-":t.minus+"",b=void 0===t.nan?"NaN":t.nan+"";function y(t){var o=(t=(0,c.Z)(t)).fill,u=t.align,s=t.sign,d=t.symbol,p=t.zero,y=t.width,m=t.comma,x=t.precision,w=t.trim,Z=t.type;"n"===Z?(m=!0,Z="g"):l.Z[Z]||(void 0===x&&(x=12),w=!0,Z="g"),(p||"0"===o&&"="===u)&&(p=!0,o="0",u="=");var D="$"===d?n:"#"===d&&/[boxX]/.test(Z)?"0"+Z.toLowerCase():"",k="$"===d?r:/[%p]/.test(Z)?g:"",E=l.Z[Z],A=/[defgprs%]/.test(Z);function j(t){var n,r,c,l=D,d=k;if("c"===Z)d=E(t)+d,t="";else{var g=(t=+t)<0||1/t<0;if(t=isNaN(t)?b:E(Math.abs(t),x),w&&(t=(0,f.Z)(t)),g&&0==+t&&"+"!==s&&(g=!1),l=(g?"("===s?s:_:"-"===s||"("===s?"":s)+l,d=("s"===Z?v[8+h.y/3]:"")+d+(g&&"("===s?")":""),A)for(n=-1,r=t.length;++n(c=t.charCodeAt(n))||c>57){d=(46===c?i+t.slice(n+1):t.slice(n))+d,t=t.slice(0,n);break}}m&&!p&&(t=e(t,1/0));var j=l.length+t.length+d.length,C=j>1)+l+t+d+C.slice(j);break;default:t=C+l+t+d}return a(t)}return x=void 0===x?6:/[gprs]/.test(Z)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x)),j.toString=function(){return t+""},j}return{format:y,formatPrefix:function(t,e){var n=y(((t=(0,c.Z)(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor((0,o.Z)(e)/3))),i=Math.pow(10,-r),a=v[8+r/3];return function(t){return n(i*t)+a}}}}({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"}),i=r.format,a=r.formatPrefix},29053:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(57480);function i(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},57480:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function i(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{Z:()=>r,V:()=>i})},36159:(t,e,n)=>{"use strict";function r(t,e){return function(n,r){for(var i=n.length,a=[],o=0,u=t[0],s=0;i>0&&u>0&&(s+u+1>r&&(u=Math.max(1,r-s)),a.push(n.substring(i-=u,i+u)),!((s+=u+1)>r));)u=t[o=(o+1)%t.length];return a.reverse().join(e)}}n.d(e,{Z:()=>r})},49613:(t,e,n)=>{"use strict";function r(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}n.d(e,{Z:()=>r})},61903:(t,e,n)=>{"use strict";if(n.d(e,{y:()=>i,Z:()=>a}),826==n.j)var r=n(57480);var i;function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var a=n[0],o=n[1],u=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,s=a.length;return u===s?a:u>s?a+new Array(u-s+1).join("0"):u>0?a.slice(0,u)+"."+a.slice(u):"0."+new Array(1-u).join("0")+(0,r.V)(t,Math.max(0,e+u-1))[0]}},47681:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function i(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new a({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function a(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}i.prototype=a.prototype,a.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},52003:(t,e,n)=>{"use strict";function r(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}n.d(e,{Z:()=>r})},1166:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(57480),i=n(61903);function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var i=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+i:i.length>a+1?i.slice(0,a+1)+"."+i.slice(a+1):i+new Array(a-i.length+2).join("0")}const o={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:r.Z,e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return a(100*t,e)},r:a,s:i.Z,X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}}},81015:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},84418:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},94735:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},54415:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(29053);function i(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},84901:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},22274:(t,e,n)=>{"use strict";function r(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}function i(t,e){switch(arguments.length){case 0:break;case 1:this.interpolator(t);break;default:this.interpolator(e).domain(t)}return this}n.d(e,{o:()=>r,O:()=>i})},10070:(t,e,n)=>{"use strict";function r(t,e){var n,r=0,i=(t=t.slice()).length-1,a=t[r],o=t[i];return or})},5497:(t,e,n)=>{"use strict";function r(t){return+t}n.d(e,{Z:()=>r})},57076:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},81648:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(15515);if(826==n.j)var i=n(23475);function a(t){return(0,i.Z)((0,r.Z)(t).call(document.documentElement))}},15515:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(69998);if(826==n.j)var i=n(70378);function a(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===i.P&&e.documentElement.namespaceURI===i.P?e.createElement(t):e.createElementNS(n,t)}}function o(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function u(t){var e=(0,r.Z)(t);return(e.local?o:a)(e)}},16761:(t,e,n)=>{"use strict";if(n.d(e,{Ue:()=>r.Z,Du:()=>i.Z,I_:()=>a.Z,C2:()=>o.Z,Jz:()=>u.Z,uD:()=>s.Z,aC:()=>c.Z,Eb:()=>f.Z,Ys:()=>l.Z,td:()=>h.Z,f_:()=>d.ZP,nZ:()=>p.Z,UK:()=>v.Z,oB:()=>g.S,Fq:()=>_.Z,W4:()=>b.Z,u9:()=>y.Z,B:()=>m.B,_H:()=>m._H}),826==n.j)var r=n(81648);if(826==n.j)var i=n(15515);if(826==n.j)var a=n(36857);if(826==n.j)var o=n(73151);if(826==n.j)var u=n(42637);if(826==n.j)var s=n(69998);if(826==n.j)var c=n(70378);if(826==n.j)var f=n(94040);if(826==n.j)var l=n(23475);if(826==n.j)var h=n(18321);if(826==n.j)var d=n(54632);if(826==n.j)var p=n(61566);if(826==n.j)var v=n(87393);if(826==n.j)var g=n(34675);if(826==n.j)var _=n(13171);if(826==n.j)var b=n(74357);if(826==n.j)var y=n(42044);if(826==n.j)var m=n(78011)},36857:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=0;function i(){return new a}function a(){this._="@"+(++r).toString(36)}a.prototype=i.prototype={constructor:a,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}}},73151:(t,e,n)=>{"use strict";function r(t){return function(){return this.matches(t)}}n.d(e,{Z:()=>r})},42637:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t){var e=(0,r.Z)();return e.changedTouches&&(e=e.changedTouches[0]),(0,i.Z)(t,e)}},69998:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(70378);function i(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),r.Z.hasOwnProperty(e)?{space:r.Z[e],local:t}:t}},70378:(t,e,n)=>{"use strict";n.d(e,{P:()=>r,Z:()=>i});var r="http://www.w3.org/1999/xhtml";const i={svg:"http://www.w3.org/2000/svg",xhtml:r,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"}},94040:(t,e,n)=>{"use strict";function r(t,e){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}n.d(e,{Z:()=>r})},23475:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(54632);function i(t){return"string"==typeof t?new r.Y1([[document.querySelector(t)]],[document.documentElement]):new r.Y1([[t]],r.Jz)}},18321:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(54632);function i(t){return"string"==typeof t?new r.Y1([document.querySelectorAll(t)],[document.documentElement]):new r.Y1([null==t?[]:t],r.Jz)}},64461:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a,F:()=>o}),826==n.j)var r=n(56335);if(826==n.j)var i=n(54632);function a(){return new i.Y1(this._enter||this._groups.map(r.Z),this._parents)}function o(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}o.prototype={constructor:o,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}}},54632:(t,e,n)=>{"use strict";n.d(e,{Y1:()=>X,ZP:()=>J,Jz:()=>G});var r=n(61566),i=n(87393),a=n(73151),o=n(64461),u=n(57076);function s(t,e,n,r,i,a){for(var u,s=0,c=e.length,f=a.length;se?1:t>=e?0:NaN}var h=n(69998);function d(t){return function(){this.removeAttribute(t)}}function p(t){return function(){this.removeAttributeNS(t.space,t.local)}}function v(t,e){return function(){this.setAttribute(t,e)}}function g(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function _(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function b(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}var y=n(34675);function m(t){return function(){delete this[t]}}function x(t,e){return function(){this[t]=e}}function w(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function Z(t){return t.trim().split(/^|\s+/)}function D(t){return t.classList||new k(t)}function k(t){this._node=t,this._names=Z(t.getAttribute("class")||"")}function E(t,e){for(var n=D(t),r=-1,i=e.length;++r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var P=n(15515);function I(){return null}function L(){var t=this.parentNode;t&&t.removeChild(this)}function U(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function $(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}var H=n(78011),q=n(42044);function Y(t,e,n){var r=(0,q.Z)(t),i=r.CustomEvent;"function"==typeof i?i=new i(e,n):(i=r.document.createEvent("Event"),n?(i.initEvent(e,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(e,!1,!1)),t.dispatchEvent(i)}function W(t,e){return function(){return Y(this,t,e)}}function V(t,e){return function(){return Y(this,t,e.apply(this,arguments))}}var G=[null];function X(t,e){this._groups=t,this._parents=e}function K(){return new X([[document.documentElement]],G)}X.prototype=K.prototype={constructor:X,select:function(t){"function"!=typeof t&&(t=(0,r.Z)(t));for(var e=this._groups,n=e.length,i=new Array(n),a=0;a=Z&&(Z=w+1);!(x=y[Z])&&++Z<_;);m._next=x||null}}return(o=new X(o,r))._enter=f,o._exit=l,o},enter:o.Z,exit:function(){return new X(this._exit||this._groups.map(f.Z),this._parents)},join:function(t,e,n){var r=this.enter(),i=this,a=this.exit();return r="function"==typeof t?t(r):r.append(t+""),null!=e&&(i=e(i)),null==n?a.remove():n(a),r&&i?r.merge(i).order():i},merge:function(t){for(var e=this._groups,n=t._groups,r=e.length,i=n.length,a=Math.min(r,i),o=new Array(r),u=0;u=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=l);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?m:"function"==typeof e?w:x)(t,e)):this.node()[t]},classed:function(t,e){var n=Z(t+"");if(arguments.length<2){for(var r=D(this.node()),i=-1,a=n.length;++i{"use strict";n.d(e,{B:()=>i,ZP:()=>f,_H:()=>l});var r={},i=null;function a(t,e,n){return t=o(t,e,n),function(e){var n=e.relatedTarget;n&&(n===this||8&n.compareDocumentPosition(this))||t.call(this,e)}}function o(t,e,n){return function(r){var a=i;i=r;try{t.call(this,this.__data__,e,n)}finally{i=a}}}function u(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function s(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r{"use strict";function r(t){return new Array(t.length)}n.d(e,{Z:()=>r})},34675:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u,S:()=>s}),826==n.j)var r=n(42044);function i(t){return function(){this.style.removeProperty(t)}}function a(t,e,n){return function(){this.style.setProperty(t,e,n)}}function o(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function u(t,e,n){return arguments.length>1?this.each((null==e?i:"function"==typeof e?o:a)(t,e,null==n?"":n)):s(this.node(),t)}function s(t,e){return t.style.getPropertyValue(e)||(0,r.Z)(t).getComputedStyle(t,null).getPropertyValue(e)}},61566:(t,e,n)=>{"use strict";function r(){}function i(t){return null==t?r:function(){return this.querySelector(t)}}n.d(e,{Z:()=>i})},87393:(t,e,n)=>{"use strict";function r(){return[]}function i(t){return null==t?r:function(){return this.querySelectorAll(t)}}n.d(e,{Z:()=>i})},45778:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(78011);function i(){for(var t,e=r.B;t=e.sourceEvent;)e=t;return e}},13171:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t,e,n){arguments.length<3&&(n=e,e=(0,r.Z)().changedTouches);for(var a,o=0,u=e?e.length:0;o{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(45778);if(826==n.j)var i=n(94040);function a(t,e){null==e&&(e=(0,r.Z)().touches);for(var n=0,a=e?e.length:0,o=new Array(a);n{"use strict";function r(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}n.d(e,{Z:()=>r})},38764:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>d}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(15);function o(t){return t.innerRadius}function u(t){return t.outerRadius}function s(t){return t.startAngle}function c(t){return t.endAngle}function f(t){return t&&t.padAngle}function l(t,e,n,r,i,o,u,s){var c=n-t,f=r-e,l=u-i,h=s-o,d=h*c-l*f;if(!(d*dF*F+B*B&&(k=A,E=j),{cx:k,cy:E,x01:-l,y01:-h,x11:k*(i/w-1),y11:E*(i/w-1)}}function d(){var t=o,e=u,n=(0,i.Z)(0),d=null,p=s,v=c,g=f,_=null;function b(){var i,o,u=+t.apply(this,arguments),s=+e.apply(this,arguments),c=p.apply(this,arguments)-a.ou,f=v.apply(this,arguments)-a.ou,b=(0,a.Wn)(f-c),y=f>c;if(_||(_=i=(0,r.Z)()),sa.Ho)if(b>a.BZ-a.Ho)_.moveTo(s*(0,a.mC)(c),s*(0,a.O$)(c)),_.arc(0,0,s,c,f,!y),u>a.Ho&&(_.moveTo(u*(0,a.mC)(f),u*(0,a.O$)(f)),_.arc(0,0,u,f,c,y));else{var m,x,w=c,Z=f,D=c,k=f,E=b,A=b,j=g.apply(this,arguments)/2,C=j>a.Ho&&(d?+d.apply(this,arguments):(0,a._b)(u*u+s*s)),M=(0,a.VV)((0,a.Wn)(s-u)/2,+n.apply(this,arguments)),F=M,B=M;if(C>a.Ho){var S=(0,a.ZR)(C/u*(0,a.O$)(j)),N=(0,a.ZR)(C/s*(0,a.O$)(j));(E-=2*S)>a.Ho?(D+=S*=y?1:-1,k-=S):(E=0,D=k=(c+f)/2),(A-=2*N)>a.Ho?(w+=N*=y?1:-1,Z-=N):(A=0,w=Z=(c+f)/2)}var T=s*(0,a.mC)(w),z=s*(0,a.O$)(w),O=u*(0,a.mC)(k),R=u*(0,a.O$)(k);if(M>a.Ho){var P,I=s*(0,a.mC)(Z),L=s*(0,a.O$)(Z),U=u*(0,a.mC)(D),$=u*(0,a.O$)(D);if(ba.Ho?B>a.Ho?(m=h(U,$,T,z,s,B,y),x=h(I,L,O,R,s,B,y),_.moveTo(m.cx+m.x01,m.cy+m.y01),Ba.Ho&&E>a.Ho?F>a.Ho?(m=h(O,R,I,L,u,-F,y),x=h(T,z,U,$,u,-F,y),_.lineTo(m.cx+m.x01,m.cy+m.y01),F{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(20651);if(826==n.j)var o=n(79767);if(826==n.j)var u=n(11053);function s(){var t=u.x,e=null,n=(0,i.Z)(0),s=u.y,c=(0,i.Z)(!0),f=null,l=a.Z,h=null;function d(i){var a,o,u,d,p,v=i.length,g=!1,_=new Array(v),b=new Array(v);for(null==f&&(h=l(p=(0,r.Z)())),a=0;a<=v;++a){if(!(a=o;--u)h.point(_[u],b[u]);h.lineEnd(),h.areaEnd()}g&&(_[a]=+t(d,a,i),b[a]=+n(d,a,i),h.point(e?+e(d,a,i):_[a],s?+s(d,a,i):b[a]))}if(p)return h=null,p+""||null}function p(){return(0,o.Z)().defined(c).curve(l).context(f)}return d.x=function(n){return arguments.length?(t="function"==typeof n?n:(0,i.Z)(+n),e=null,d):t},d.x0=function(e){return arguments.length?(t="function"==typeof e?e:(0,i.Z)(+e),d):t},d.x1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:(0,i.Z)(+t),d):e},d.y=function(t){return arguments.length?(n="function"==typeof t?t:(0,i.Z)(+t),s=null,d):n},d.y0=function(t){return arguments.length?(n="function"==typeof t?t:(0,i.Z)(+t),d):n},d.y1=function(t){return arguments.length?(s=null==t?null:"function"==typeof t?t:(0,i.Z)(+t),d):s},d.lineX0=d.lineY0=function(){return p().x(t).y(n)},d.lineY1=function(){return p().x(t).y(s)},d.lineX1=function(){return p().x(e).y(n)},d.defined=function(t){return arguments.length?(c="function"==typeof t?t:(0,i.Z)(!!t),d):c},d.curve=function(t){return arguments.length?(l=t,null!=f&&(h=l(f)),d):l},d.context=function(t){return arguments.length?(null==t?f=h=null:h=l(f=t),d):f},d}},69896:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>o}),826==n.j)var r=n(23165);if(826==n.j)var i=n(79493);if(826==n.j)var a=n(8329);function o(){var t=(0,i.Z)().curve(r.j),e=t.curve,n=t.lineX0,o=t.lineX1,u=t.lineY0,s=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return(0,a.X)(n())},delete t.lineX0,t.lineEndAngle=function(){return(0,a.X)(o())},delete t.lineX1,t.lineInnerRadius=function(){return(0,a.X)(u())},delete t.lineY0,t.lineOuterRadius=function(){return(0,a.X)(s())},delete t.lineY1,t.curve=function(t){return arguments.length?e((0,r.Z)(t)):e()._curve},t}},72299:(t,e,n)=>{"use strict";n.d(e,{t:()=>r});var r=Array.prototype.slice},33554:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},6023:(t,e,n)=>{"use strict";function r(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function i(t){this._context=t}function a(t){return new i(t)}n.d(e,{xm:()=>r,fE:()=>i,ZP:()=>a}),i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:r(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:r(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},25972:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(69706),i=n(6023);function a(t){this._context=t}function o(t){return new a(t)}a.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:(0,i.xm)(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},541:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(6023);function i(t){this._context=t}function a(t){return new i(t)}i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,i=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,i):this._context.moveTo(n,i);break;case 3:this._point=4;default:(0,r.xm)(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}}},94244:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(6023);function i(t,e){this._basis=new r.fE(t),this._beta=e}i.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,i=t[0],a=e[0],o=t[n]-i,u=e[n]-a,s=-1;++s<=n;)r=s/n,this._basis.point(this._beta*t[s]+(1-this._beta)*(i+r*o),this._beta*e[s]+(1-this._beta)*(a+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const a=function t(e){function n(t){return 1===e?new r.fE(t):new i(t,e)}return n.beta=function(e){return t(+e)},n}(.85)},46385:(t,e,n)=>{"use strict";function r(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function i(t,e){this._context=t,this._k=(1-e)/6}n.d(e,{xm:()=>r,pC:()=>i,ZP:()=>a}),i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:r(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:r(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const a=function t(e){function n(t){return new i(t,e)}return n.tension=function(e){return t(+e)},n}(0)},91931:(t,e,n)=>{"use strict";n.d(e,{U:()=>a,Z:()=>o});var r=n(69706),i=n(46385);function a(t,e){this._context=t,this._k=(1-e)/6}a.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:(0,i.xm)(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const o=function t(e){function n(t){return new a(t,e)}return n.tension=function(e){return t(+e)},n}(0)},42688:(t,e,n)=>{"use strict";n.d(e,{T:()=>i,Z:()=>a});var r=n(46385);function i(t,e){this._context=t,this._k=(1-e)/6}i.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:(0,r.xm)(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const a=function t(e){function n(t){return new i(t,e)}return n.tension=function(e){return t(+e)},n}(0)},74924:(t,e,n)=>{"use strict";n.d(e,{x:()=>a,Z:()=>u});var r=n(15),i=n(46385);function a(t,e,n){var i=t._x1,a=t._y1,o=t._x2,u=t._y2;if(t._l01_a>r.Ho){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);i=(i*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,a=(a*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>r.Ho){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,l=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-e*t._l12_2a)/l,u=(u*f+t._y1*t._l23_2a-n*t._l12_2a)/l}t._context.bezierCurveTo(i,a,o,u,t._x2,t._y2)}function o(t,e){this._context=t,this._alpha=e}o.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:a(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const u=function t(e){function n(t){return e?new o(t,e):new i.pC(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},85578:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(91931),i=n(69706),a=n(74924);function o(t,e){this._context=t,this._alpha=e}o.prototype={areaStart:i.Z,areaEnd:i.Z,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:(0,a.x)(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const u=function t(e){function n(t){return e?new o(t,e):new r.U(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},74129:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(42688),i=n(74924);function a(t,e){this._context=t,this._alpha=e}a.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:(0,i.x)(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const o=function t(e){function n(t){return e?new a(t,e):new r.T(t,0)}return n.alpha=function(e){return t(+e)},n}(.5)},20651:(t,e,n)=>{"use strict";function r(t){this._context=t}function i(t){return new r(t)}n.d(e,{Z:()=>i}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}}},71219:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=n(69706);function i(t){this._context=t}function a(t){return new i(t)}i.prototype={areaStart:r.Z,areaEnd:r.Z,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}}},27266:(t,e,n)=>{"use strict";function r(t){return t<0?-1:1}function i(t,e,n){var i=t._x1-t._x0,a=e-t._x1,o=(t._y1-t._y0)/(i||a<0&&-0),u=(n-t._y1)/(a||i<0&&-0),s=(o*a+u*i)/(i+a);return(r(o)+r(u))*Math.min(Math.abs(o),Math.abs(u),.5*Math.abs(s))||0}function a(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function o(t,e,n){var r=t._x0,i=t._y0,a=t._x1,o=t._y1,u=(a-r)/3;t._context.bezierCurveTo(r+u,i+u*e,a-u,o-u*n,a,o)}function u(t){this._context=t}function s(t){this._context=new c(t)}function c(t){this._context=t}function f(t){return new u(t)}function l(t){return new s(t)}n.d(e,{Z:()=>f,s:()=>l}),u.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:o(this,this._t0,a(this,this._t0))}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,o(this,a(this,n=i(this,t,e)),n);break;default:o(this,this._t0,n=i(this,t,e))}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}},(s.prototype=Object.create(u.prototype)).point=function(t,e){u.prototype.point.call(this,e,t)},c.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,i,a){this._context.bezierCurveTo(e,t,r,n,a,i)}}},43276:(t,e,n)=>{"use strict";function r(t){this._context=t}function i(t){var e,n,r=t.length-1,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;ea}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=i(t),a=i(e),o=0,u=1;u{"use strict";n.d(e,{j:()=>r,Z:()=>a});var r=a(n(20651).Z);function i(t){this._curve=t}function a(t){function e(e){return new i(t(e))}return e._curve=t,e}i.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}}},45742:(t,e,n)=>{"use strict";function r(t,e){this._context=t,this._t=e}function i(t){return new r(t,.5)}function a(t){return new r(t,0)}function o(t){return new r(t,1)}n.d(e,{ZP:()=>i,RN:()=>a,cD:()=>o}),r.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}}},57119:(t,e,n)=>{"use strict";function r(t,e){return et?1:e>=t?0:NaN}n.d(e,{Z:()=>r})},75435:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},33764:(t,e,n)=>{"use strict";if(n.d(e,{Nb:()=>r.Z,SO:()=>i.Z,jv:()=>a.Z,ve:()=>o.Z,am:()=>u.Z,N1:()=>u.Z,XB:()=>s.Z,aJ:()=>s.Z,Hs:()=>c.Z,h5:()=>f.h5,rR:()=>f.rR,M4:()=>f.M4,NA:()=>l.Z,uH:()=>l.u,JF:()=>h.Z,tJ:()=>d.Z,rZ:()=>p.Z,m_:()=>v.Z,Hm:()=>g.Z,P6:()=>_.Z,n3:()=>b.Z,Dt:()=>y.Z,WQ:()=>m.Z,$0:()=>x.ZP,tF:()=>w.Z,Ov:()=>Z.Z,dC:()=>D.Z,YY:()=>k.ZP,fG:()=>E.Z,$m:()=>A.Z,zg:()=>j.Z,fx:()=>C.Z,c_:()=>M.Z,Fd:()=>F.Z,ak:()=>F.s,Sx:()=>B.Z,eA:()=>S.ZP,js:()=>S.cD,iJ:()=>S.RN,kn:()=>N.Z,pB:()=>T.Z,W$:()=>z.Z,HL:()=>O.Z,Ku:()=>R.Z,YG:()=>P.Z,mG:()=>I.Z,$K:()=>L.Z,IX:()=>U.Z,FP:()=>$.Z,Qx:()=>H.Z,cY:()=>q.Z}),826==n.j)var r=n(38764);if(826==n.j)var i=n(79493);if(826==n.j)var a=n(79767);if(826==n.j)var o=n(95937);if(826==n.j)var u=n(69896);if(826==n.j)var s=n(8329);if(826==n.j)var c=n(3326);if(826==n.j)var f=n(72215);if(826==n.j)var l=n(24037);if(826==n.j)var h=n(62628);if(826==n.j)var d=n(9135);if(826==n.j)var p=n(82893);if(826==n.j)var v=n(44523);if(826==n.j)var g=n(86707);if(826==n.j)var _=n(42965);if(826==n.j)var b=n(60598);if(826==n.j)var y=n(25972);if(826==n.j)var m=n(541);if(826==n.j)var x=n(6023);if(826==n.j)var w=n(94244);if(826==n.j)var Z=n(91931);if(826==n.j)var D=n(42688);if(826==n.j)var k=n(46385);if(826==n.j)var E=n(85578);if(826==n.j)var A=n(74129);if(826==n.j)var j=n(74924);if(826==n.j)var C=n(71219);if(826==n.j)var M=n(20651);if(826==n.j)var F=n(27266);if(826==n.j)var B=n(43276);if(826==n.j)var S=n(45742);if(826==n.j)var N=n(98926);if(826==n.j)var T=n(22254);if(826==n.j)var z=n(76751);if(826==n.j)var O=n(90541);if(826==n.j)var R=n(36538);if(826==n.j)var P=n(34928);if(826==n.j)var I=n(42467);if(826==n.j)var L=n(19721);if(826==n.j)var U=n(82564);if(826==n.j)var $=n(12197);if(826==n.j)var H=n(81182);if(826==n.j)var q=n(40277)},79767:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(91672);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(20651);if(826==n.j)var o=n(11053);function u(){var t=o.x,e=o.y,n=(0,i.Z)(!0),u=null,s=a.Z,c=null;function f(i){var a,o,f,l=i.length,h=!1;for(null==u&&(c=s(f=(0,r.Z)())),a=0;a<=l;++a)!(a{"use strict";if(n.d(e,{X:()=>a,Z:()=>o}),826==n.j)var r=n(23165);if(826==n.j)var i=n(79767);function a(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e((0,r.Z)(t)):e()._curve},t}function o(){return a((0,i.Z)().curve(r.j))}},72215:(t,e,n)=>{"use strict";if(n.d(e,{h5:()=>p,rR:()=>v,M4:()=>g}),826==n.j)var r=n(91672);if(826==n.j)var i=n(72299);if(826==n.j)var a=n(33554);if(826==n.j)var o=n(11053);if(826==n.j)var u=n(3326);function s(t){return t.source}function c(t){return t.target}function f(t){var e=s,n=c,u=o.x,f=o.y,l=null;function h(){var a,o=i.t.call(arguments),s=e.apply(this,o),c=n.apply(this,o);if(l||(l=a=(0,r.Z)()),t(l,+u.apply(this,(o[0]=s,o)),+f.apply(this,o),+u.apply(this,(o[0]=c,o)),+f.apply(this,o)),a)return l=null,a+""||null}return h.source=function(t){return arguments.length?(e=t,h):e},h.target=function(t){return arguments.length?(n=t,h):n},h.x=function(t){return arguments.length?(u="function"==typeof t?t:(0,a.Z)(+t),h):u},h.y=function(t){return arguments.length?(f="function"==typeof t?t:(0,a.Z)(+t),h):f},h.context=function(t){return arguments.length?(l=null==t?null:t,h):l},h}function l(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e=(e+r)/2,n,e,i,r,i)}function h(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e,n=(n+i)/2,r,n,r,i)}function d(t,e,n,r,i){var a=(0,u.Z)(e,n),o=(0,u.Z)(e,n=(n+i)/2),s=(0,u.Z)(r,n),c=(0,u.Z)(r,i);t.moveTo(a[0],a[1]),t.bezierCurveTo(o[0],o[1],s[0],s[1],c[0],c[1])}function p(){return f(l)}function v(){return f(h)}function g(){var t=f(d);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}},15:(t,e,n)=>{"use strict";n.d(e,{Wn:()=>r,fv:()=>i,mC:()=>a,Fp:()=>o,VV:()=>u,O$:()=>s,_b:()=>c,Ho:()=>f,pi:()=>l,ou:()=>h,BZ:()=>d,Kh:()=>p,ZR:()=>v});var r=Math.abs,i=Math.atan2,a=Math.cos,o=Math.max,u=Math.min,s=Math.sin,c=Math.sqrt,f=1e-12,l=Math.PI,h=l/2,d=2*l;function p(t){return t>1?0:t<-1?l:Math.acos(t)}function v(t){return t>=1?h:t<=-1?-h:Math.asin(t)}},69706:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},76751:(t,e,n)=>{"use strict";function r(t,e){if((u=t.length)>0)for(var n,r,i,a,o,u,s=0,c=t[e[0]].length;s0?(r[0]=a,r[1]=a+=i):i<0?(r[1]=o,r[0]=o+=i):(r[0]=0,r[1]=i)}n.d(e,{Z:()=>r})},22254:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((i=t.length)>0){for(var n,i,a,o=0,u=t[0].length;o{"use strict";function r(t,e){if((i=t.length)>1)for(var n,r,i,a=1,o=t[e[0]],u=o.length;ar})},36538:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((n=t.length)>0){for(var n,i=0,a=t[e[0]],o=a.length;i{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(90541);function i(t,e){if((a=t.length)>0&&(i=(n=t[e[0]]).length)>0){for(var n,i,a,o=0,u=1;u{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81182);function i(t){var e=t.map(a);return(0,r.Z)(t).sort((function(t,n){return e[t]-e[n]}))}function a(t){for(var e,n=-1,r=0,i=t.length,a=-1/0;++na&&(a=e,r=n);return r}},19721:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i,S:()=>a}),826==n.j)var r=n(81182);function i(t){var e=t.map(a);return(0,r.Z)(t).sort((function(t,n){return e[t]-e[n]}))}function a(t){for(var e,n=0,r=-1,i=t.length;++r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(19721);function i(t){return(0,r.Z)(t).reverse()}},12197:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>a}),826==n.j)var r=n(42467);if(826==n.j)var i=n(19721);function a(t){var e,n,a=t.length,o=t.map(i.S),u=(0,r.Z)(t),s=0,c=0,f=[],l=[];for(e=0;e{"use strict";function r(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}n.d(e,{Z:()=>r})},40277:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(81182);function i(t){return(0,r.Z)(t).reverse()}},95937:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>u}),826==n.j)var r=n(33554);if(826==n.j)var i=n(57119);if(826==n.j)var a=n(75435);if(826==n.j)var o=n(15);function u(){var t=a.Z,e=i.Z,n=null,u=(0,r.Z)(0),s=(0,r.Z)(o.BZ),c=(0,r.Z)(0);function f(r){var i,a,f,l,h,d=r.length,p=0,v=new Array(d),g=new Array(d),_=+u.apply(this,arguments),b=Math.min(o.BZ,Math.max(-o.BZ,s.apply(this,arguments)-_)),y=Math.min(Math.abs(b)/d,c.apply(this,arguments)),m=y*(b<0?-1:1);for(i=0;i0&&(p+=h);for(null!=e?v.sort((function(t,n){return e(g[t],g[n])})):null!=n&&v.sort((function(t,e){return n(r[t],r[e])})),i=0,f=p?(b-d*m)/p:0;i0?h*f:0)+m,g[a]={data:r[a],index:i,value:h,startAngle:_,endAngle:l,padAngle:y};return g}return f.value=function(e){return arguments.length?(t="function"==typeof e?e:(0,r.Z)(+e),f):t},f.sortValues=function(t){return arguments.length?(e=t,n=null,f):e},f.sort=function(t){return arguments.length?(n=t,e=null,f):n},f.startAngle=function(t){return arguments.length?(u="function"==typeof t?t:(0,r.Z)(+t),f):u},f.endAngle=function(t){return arguments.length?(s="function"==typeof t?t:(0,r.Z)(+t),f):s},f.padAngle=function(t){return arguments.length?(c="function"==typeof t?t:(0,r.Z)(+t),f):c},f}},11053:(t,e,n)=>{"use strict";function r(t){return t[0]}function i(t){return t[1]}n.d(e,{x:()=>r,y:()=>i})},3326:(t,e,n)=>{"use strict";function r(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}n.d(e,{Z:()=>r})},98926:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>s}),826==n.j)var r=n(72299);if(826==n.j)var i=n(33554);if(826==n.j)var a=n(90541);if(826==n.j)var o=n(81182);function u(t,e){return t[e]}function s(){var t=(0,i.Z)([]),e=o.Z,n=a.Z,s=u;function c(r){var i,a,o=t.apply(this,arguments),u=r.length,c=o.length,f=new Array(c);for(i=0;i{"use strict";if(n.d(e,{u:()=>h,Z:()=>d}),826==n.j)var r=n(91672);var i=n(62628),a=n(9135),o=n(82893),u=n(86707),s=n(44523),c=n(42965),f=n(60598);if(826==n.j)var l=n(33554);var h=[i.Z,a.Z,o.Z,s.Z,u.Z,c.Z,f.Z];function d(){var t=(0,l.Z)(i.Z),e=(0,l.Z)(64),n=null;function a(){var i;if(n||(n=i=(0,r.Z)()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(e){return arguments.length?(t="function"==typeof e?e:(0,l.Z)(e),a):t},a.size=function(t){return arguments.length?(e="function"==typeof t?t:(0,l.Z)(+t),a):e},a.context=function(t){return arguments.length?(n=null==t?null:t,a):n},a}},62628:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(15);const i={draw:function(t,e){var n=Math.sqrt(e/r.pi);t.moveTo(n,0),t.arc(0,0,n,0,r.BZ)}}},9135:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r={draw:function(t,e){var n=Math.sqrt(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}}},82893:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=Math.sqrt(1/3),i=2*r;const a={draw:function(t,e){var n=Math.sqrt(e/i),a=n*r;t.moveTo(0,-n),t.lineTo(a,0),t.lineTo(0,n),t.lineTo(-a,0),t.closePath()}}},44523:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r});const r={draw:function(t,e){var n=Math.sqrt(e),r=-n/2;t.rect(r,r,n,n)}}},86707:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(15),i=Math.sin(r.pi/10)/Math.sin(7*r.pi/10),a=Math.sin(r.BZ/10)*i,o=-Math.cos(r.BZ/10)*i;const u={draw:function(t,e){var n=Math.sqrt(.8908130915292852*e),i=a*n,u=o*n;t.moveTo(0,-n),t.lineTo(i,u);for(var s=1;s<5;++s){var c=r.BZ*s/5,f=Math.cos(c),l=Math.sin(c);t.lineTo(l*n,-f*n),t.lineTo(f*i-l*u,l*i+f*u)}t.closePath()}}},42965:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=Math.sqrt(3);const i={draw:function(t,e){var n=-Math.sqrt(e/(3*r));t.moveTo(0,2*n),t.lineTo(-r*n,-n),t.lineTo(r*n,-n),t.closePath()}}},60598:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=-.5,i=Math.sqrt(3)/2,a=1/Math.sqrt(12),o=3*(a/2+1);const u={draw:function(t,e){var n=Math.sqrt(e/o),u=n/2,s=n*a,c=u,f=n*a+n,l=-c,h=f;t.moveTo(u,s),t.lineTo(c,f),t.lineTo(l,h),t.lineTo(r*u-i*s,i*u+r*s),t.lineTo(r*c-i*f,i*c+r*f),t.lineTo(r*l-i*h,i*l+r*h),t.lineTo(r*u+i*s,r*s-i*u),t.lineTo(r*c+i*f,r*f-i*c),t.lineTo(r*l+i*h,r*h-i*l),t.closePath()}}},49164:(t,e,n)=>{"use strict";n.d(e,{i$:()=>i,Z1:()=>a,g0:()=>o,wp:()=>u,ZP:()=>c});var r,i,a,o,u,s=n(30778);function c(t){return r=(0,s.Z)(t),i=r.format,a=r.parse,o=r.utcFormat,u=r.utcParse,r}c({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]})},56221:(t,e,n)=>{"use strict";n.d(e,{Ds:()=>r.ZP,i$:()=>r.i$,Z1:()=>r.Z1,g0:()=>r.g0,wp:()=>r.wp,Dq:()=>i.Z,zh:()=>a.Z,ji:()=>o.Z});var r=n(49164);if(826==n.j)var i=n(30778);if(826==n.j)var a=n(25920);if(826==n.j)var o=n(77214)},25920:(t,e,n)=>{"use strict";n.d(e,{f:()=>i,Z:()=>o});var r=n(49164),i="%Y-%m-%dT%H:%M:%S.%LZ",a=Date.prototype.toISOString?function(t){return t.toISOString()}:(0,r.g0)(i);const o=826==n.j?a:null},77214:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(25920),i=n(49164),a=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:(0,i.wp)(r.f);const o=826==n.j?a:null},30778:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>h}),826==n.j)var r=n(97631);if(826==n.j)var i=n(12370);if(826==n.j)var a=n(76231);if(826==n.j)var o=n(68603);if(826==n.j)var u=n(97344);if(826==n.j)var s=n(2908);function c(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function f(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function l(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function h(t){var e=t.dateTime,n=t.date,u=t.time,s=t.periods,h=t.days,p=t.shortDays,v=t.months,g=t.shortMonths,_=y(s),b=m(s),J=y(h),bt=m(h),Mt=y(p),Ft=m(p),Bt=y(v),St=m(v),Nt=y(g),Tt=m(g),zt={a:function(t){return p[t.getDay()]},A:function(t){return h[t.getDay()]},b:function(t){return g[t.getMonth()]},B:function(t){return v[t.getMonth()]},c:null,d:L,e:L,f:Y,g:rt,G:at,H:U,I:$,j:H,L:q,m:W,M:V,p:function(t){return s[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:jt,s:Ct,S:G,u:X,U:K,V:Q,w:tt,W:et,x:null,X:null,y:nt,Y:it,Z:ot,"%":At},Ot={a:function(t){return p[t.getUTCDay()]},A:function(t){return h[t.getUTCDay()]},b:function(t){return g[t.getUTCMonth()]},B:function(t){return v[t.getUTCMonth()]},c:null,d:ut,e:ut,f:ht,g:Zt,G:kt,H:st,I:ct,j:ft,L:lt,m:dt,M:pt,p:function(t){return s[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:jt,s:Ct,S:vt,u:gt,U:_t,V:yt,w:mt,W:xt,x:null,X:null,y:wt,Y:Dt,Z:Et,"%":At},Rt={a:function(t,e,n){var r=Mt.exec(e.slice(n));return r?(t.w=Ft[r[0].toLowerCase()],n+r[0].length):-1},A:function(t,e,n){var r=J.exec(e.slice(n));return r?(t.w=bt[r[0].toLowerCase()],n+r[0].length):-1},b:function(t,e,n){var r=Nt.exec(e.slice(n));return r?(t.m=Tt[r[0].toLowerCase()],n+r[0].length):-1},B:function(t,e,n){var r=Bt.exec(e.slice(n));return r?(t.m=St[r[0].toLowerCase()],n+r[0].length):-1},c:function(t,n,r){return Lt(t,e,n,r)},d:F,e:F,f:O,g:A,G:E,H:S,I:S,j:B,L:z,m:M,M:N,p:function(t,e,n){var r=_.exec(e.slice(n));return r?(t.p=b[r[0].toLowerCase()],n+r[0].length):-1},q:C,Q:P,s:I,S:T,u:w,U:Z,V:D,w:x,W:k,x:function(t,e,r){return Lt(t,n,e,r)},X:function(t,e,n){return Lt(t,u,e,n)},y:A,Y:E,Z:j,"%":R};function Pt(t,e){return function(n){var r,i,a,o=[],u=-1,s=0,c=t.length;for(n instanceof Date||(n=new Date(+n));++u53)return null;"w"in h||(h.w=1),"Z"in h?(s=(u=f(l(h.y,0,1))).getUTCDay(),u=s>4||0===s?r.l6.ceil(u):(0,r.l6)(u),u=i.Z.offset(u,7*(h.V-1)),h.y=u.getUTCFullYear(),h.m=u.getUTCMonth(),h.d=u.getUTCDate()+(h.w+6)%7):(s=(u=c(l(h.y,0,1))).getDay(),u=s>4||0===s?a.wA.ceil(u):(0,a.wA)(u),u=o.Z.offset(u,7*(h.V-1)),h.y=u.getFullYear(),h.m=u.getMonth(),h.d=u.getDate()+(h.w+6)%7)}else("W"in h||"U"in h)&&("w"in h||(h.w="u"in h?h.u%7:"W"in h?1:0),s="Z"in h?f(l(h.y,0,1)).getUTCDay():c(l(h.y,0,1)).getDay(),h.m=0,h.d="W"in h?(h.w+6)%7+7*h.W-(s+5)%7:h.w+7*h.U-(s+6)%7);return"Z"in h?(h.H+=h.Z/100|0,h.M+=h.Z%100,f(h)):c(h)}}function Lt(t,e,n,r){for(var i,a,o=0,u=e.length,s=n.length;o=s)return-1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=Rt[i in d?e.charAt(o++):i])||(r=a(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}return zt.x=Pt(n,zt),zt.X=Pt(u,zt),zt.c=Pt(e,zt),Ot.x=Pt(n,Ot),Ot.X=Pt(u,Ot),Ot.c=Pt(e,Ot),{format:function(t){var e=Pt(t+="",zt);return e.toString=function(){return t},e},parse:function(t){var e=It(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=Pt(t+="",Ot);return e.toString=function(){return t},e},utcParse:function(t){var e=It(t+="",!0);return e.toString=function(){return t},e}}}var d={"-":"",_:" ",0:"0"},p=/^\s*\d+/,v=/^%/,g=/[\\^$*+?|[\]().{}]/g;function _(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",a=i.length;return r+(a68?1900:2e3),n+r[0].length):-1}function j(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function C(t,e,n){var r=p.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function M(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function F(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function B(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function S(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function N(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function T(t,e,n){var r=p.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function z(t,e,n){var r=p.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function O(t,e,n){var r=p.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function R(t,e,n){var r=v.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function P(t,e,n){var r=p.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function I(t,e,n){var r=p.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function L(t,e){return _(t.getDate(),e,2)}function U(t,e){return _(t.getHours(),e,2)}function $(t,e){return _(t.getHours()%12||12,e,2)}function H(t,e){return _(1+o.Z.count((0,u.Z)(t),t),e,3)}function q(t,e){return _(t.getMilliseconds(),e,3)}function Y(t,e){return q(t,e)+"000"}function W(t,e){return _(t.getMonth()+1,e,2)}function V(t,e){return _(t.getMinutes(),e,2)}function G(t,e){return _(t.getSeconds(),e,2)}function X(t){var e=t.getDay();return 0===e?7:e}function K(t,e){return _(a.OM.count((0,u.Z)(t)-1,t),e,2)}function J(t){var e=t.getDay();return e>=4||0===e?(0,a.bL)(t):a.bL.ceil(t)}function Q(t,e){return t=J(t),_(a.bL.count((0,u.Z)(t),t)+(4===(0,u.Z)(t).getDay()),e,2)}function tt(t){return t.getDay()}function et(t,e){return _(a.wA.count((0,u.Z)(t)-1,t),e,2)}function nt(t,e){return _(t.getFullYear()%100,e,2)}function rt(t,e){return _((t=J(t)).getFullYear()%100,e,2)}function it(t,e){return _(t.getFullYear()%1e4,e,4)}function at(t,e){var n=t.getDay();return _((t=n>=4||0===n?(0,a.bL)(t):a.bL.ceil(t)).getFullYear()%1e4,e,4)}function ot(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+_(e/60|0,"0",2)+_(e%60,"0",2)}function ut(t,e){return _(t.getUTCDate(),e,2)}function st(t,e){return _(t.getUTCHours(),e,2)}function ct(t,e){return _(t.getUTCHours()%12||12,e,2)}function ft(t,e){return _(1+i.Z.count((0,s.Z)(t),t),e,3)}function lt(t,e){return _(t.getUTCMilliseconds(),e,3)}function ht(t,e){return lt(t,e)+"000"}function dt(t,e){return _(t.getUTCMonth()+1,e,2)}function pt(t,e){return _(t.getUTCMinutes(),e,2)}function vt(t,e){return _(t.getUTCSeconds(),e,2)}function gt(t){var e=t.getUTCDay();return 0===e?7:e}function _t(t,e){return _(r.Ox.count((0,s.Z)(t)-1,t),e,2)}function bt(t){var e=t.getUTCDay();return e>=4||0===e?(0,r.hB)(t):r.hB.ceil(t)}function yt(t,e){return t=bt(t),_(r.hB.count((0,s.Z)(t),t)+(4===(0,s.Z)(t).getUTCDay()),e,2)}function mt(t){return t.getUTCDay()}function xt(t,e){return _(r.l6.count((0,s.Z)(t)-1,t),e,2)}function wt(t,e){return _(t.getUTCFullYear()%100,e,2)}function Zt(t,e){return _((t=bt(t)).getUTCFullYear()%100,e,2)}function Dt(t,e){return _(t.getUTCFullYear()%1e4,e,4)}function kt(t,e){var n=t.getUTCDay();return _((t=n>=4||0===n?(0,r.hB)(t):r.hB.ceil(t)).getUTCFullYear()%1e4,e,4)}function Et(){return"+0000"}function At(){return"%"}function jt(t){return+t}function Ct(t){return Math.floor(+t/1e3)}},68603:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,a:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*i.yB)/i.UD}),(function(t){return t.getDate()-1}));const o=826==n.j?a:null;var u=a.range},1514:(t,e,n)=>{"use strict";n.d(e,{Ym:()=>r,yB:()=>i,Y2:()=>a,UD:()=>o,iM:()=>u});var r=1e3,i=6e4,a=36e5,o=864e5,u=6048e5},54076:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,i:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*i.Ym-t.getMinutes()*i.yB)}),(function(t,e){t.setTime(+t+e*i.Y2)}),(function(t,e){return(e-t)/i.Y2}),(function(t){return t.getHours()}));const o=826==n.j?a:null;var u=a.range},11365:(t,e,n)=>{"use strict";if(n.d(e,{JZ:()=>r.Z,U8:()=>i.Z,DG:()=>i.m,GK:()=>i.Z,An:()=>i.m,S1:()=>a.Z,BW:()=>a.m,OL:()=>a.Z,z1:()=>a.m,Z_:()=>o.Z,Xo:()=>o.L,WQ:()=>u.Z,w8:()=>u.i,rr:()=>s.Z,Nu:()=>s.a,NG:()=>c.OM,EN:()=>c.vm,Zy:()=>c.OM,WC:()=>c.vm,Ox:()=>c.wA,ip:()=>c.bJ,YD:()=>c.sy,RA:()=>c.aU,EF:()=>c.zg,S3:()=>c.Ld,Ig:()=>c.bL,Pl:()=>c.$t,y2:()=>c.mC,$N:()=>c.b$,Lq:()=>c.EY,X2:()=>c.Ff,F0:()=>f.Z,K_:()=>f.e,jB:()=>l.Z,HK:()=>l.g,rz:()=>h.Z,NH:()=>h.N,lM:()=>d.Z,Xt:()=>d.X,AN:()=>p.Z,yw:()=>p.y,YF:()=>v.Ox,_T:()=>v.SU,pI:()=>v.Ox,SU:()=>v.SU,l6:()=>v.l6,$3:()=>v.$3,J1:()=>v.J1,DK:()=>v.DK,b3:()=>v.b3,uy:()=>v.uy,hB:()=>v.hB,xj:()=>v.xj,QQ:()=>v.QQ,fz:()=>v.fz,g4:()=>v.g4,Q_:()=>v.Q_,me:()=>g.Z,Ks:()=>g.K,ol:()=>_.Z,DX:()=>_.D}),826==n.j)var r=n(22179);if(826==n.j)var i=n(30356);if(826==n.j)var a=n(52546);if(826==n.j)var o=n(18450);if(826==n.j)var u=n(54076);if(826==n.j)var s=n(68603);if(826==n.j)var c=n(76231);if(826==n.j)var f=n(50690);if(826==n.j)var l=n(97344);if(826==n.j)var h=n(52004);if(826==n.j)var d=n(28239);if(826==n.j)var p=n(12370);if(826==n.j)var v=n(97631);if(826==n.j)var g=n(94758);if(826==n.j)var _=n(2908)},22179:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a});var r=new Date,i=new Date;function a(t,e,n,o){function u(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return u.floor=function(e){return t(e=new Date(+e)),e},u.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},u.round=function(t){var e=u(t),n=u.ceil(t);return t-e0))return o;do{o.push(a=new Date(+n)),e(n,i),t(n)}while(a=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(u.count=function(e,a){return r.setTime(+e),i.setTime(+a),t(r),t(i),Math.floor(n(r,i))},u.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?u.filter(o?function(e){return o(e)%t==0}:function(e){return u.count(0,e)%t==0}):u:null}),u}},30356:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,m:()=>o});var r=n(22179),i=(0,r.Z)((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?(0,r.Z)((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):i:null};const a=826==n.j?i:null;var o=i.range},18450:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,L:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*i.Ym)}),(function(t,e){t.setTime(+t+e*i.yB)}),(function(t,e){return(e-t)/i.yB}),(function(t){return t.getMinutes()}));const o=826==n.j?a:null;var u=a.range},50690:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,e:()=>a});var r=(0,n(22179).Z)((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const i=826==n.j?r:null;var a=r.range},52546:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,m:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*i.Ym)}),(function(t,e){return(e-t)/i.Ym}),(function(t){return t.getUTCSeconds()}));const o=826==n.j?a:null;var u=a.range},12370:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,y:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/i.UD}),(function(t){return t.getUTCDate()-1}));const o=826==n.j?a:null;var u=a.range},28239:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,X:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*i.Y2)}),(function(t,e){return(e-t)/i.Y2}),(function(t){return t.getUTCHours()}));const o=826==n.j?a:null;var u=a.range},52004:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o,N:()=>u});var r=n(22179),i=n(1514),a=(0,r.Z)((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*i.yB)}),(function(t,e){return(e-t)/i.yB}),(function(t){return t.getUTCMinutes()}));const o=826==n.j?a:null;var u=a.range},94758:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,K:()=>a});var r=(0,n(22179).Z)((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const i=826==n.j?r:null;var a=r.range},97631:(t,e,n)=>{"use strict";n.d(e,{Ox:()=>o,l6:()=>u,J1:()=>s,b3:()=>c,hB:()=>f,QQ:()=>l,g4:()=>h,SU:()=>d,$3:()=>p,DK:()=>v,uy:()=>g,xj:()=>_,fz:()=>b,Q_:()=>y});var r=n(22179),i=n(1514);function a(t){return(0,r.Z)((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/i.iM}))}var o=a(0),u=a(1),s=a(2),c=a(3),f=a(4),l=a(5),h=a(6),d=o.range,p=u.range,v=s.range,g=c.range,_=f.range,b=l.range,y=h.range},2908:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,D:()=>o});var r=n(22179),i=(0,r.Z)((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));i.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const a=826==n.j?i:null;var o=i.range},76231:(t,e,n)=>{"use strict";n.d(e,{OM:()=>o,wA:()=>u,sy:()=>s,zg:()=>c,bL:()=>f,mC:()=>l,EY:()=>h,vm:()=>d,bJ:()=>p,aU:()=>v,Ld:()=>g,$t:()=>_,b$:()=>b,Ff:()=>y});var r=n(22179),i=n(1514);function a(t){return(0,r.Z)((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*i.yB)/i.iM}))}var o=a(0),u=a(1),s=a(2),c=a(3),f=a(4),l=a(5),h=a(6),d=o.range,p=u.range,v=s.range,g=c.range,_=f.range,b=l.range,y=h.range},97344:(t,e,n)=>{"use strict";n.d(e,{Z:()=>a,g:()=>o});var r=n(22179),i=(0,r.Z)((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));i.every=function(t){return isFinite(t=Math.floor(t))&&t>0?(0,r.Z)((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const a=826==n.j?i:null;var o=i.range},48050:(t,e,n)=>{"use strict";if(n.d(e,{zO:()=>r.zO,HT:()=>r.HT,R8:()=>r.R8,Vs:()=>i.Z,FG:()=>a.Z}),826==n.j)var r=n(51852);if(826==n.j)var i=n(58148);if(826==n.j)var a=n(30419)},30419:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(51852);function i(t,e,n){var i=new r.B7,a=e;return null==e?(i.restart(t,e,n),i):(e=+e,n=null==n?(0,r.zO)():+n,i.restart((function r(o){o+=a,i.restart(r,a+=e,n),t(o)}),e,n),i)}},58148:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(51852);function i(t,e,n){var i=new r.B7;return e=null==e?0:+e,i.restart((function(n){i.stop(),t(n+e)}),e,n),i}},51852:(t,e,n)=>{"use strict";n.d(e,{zO:()=>d,B7:()=>v,HT:()=>g,R8:()=>_});var r,i,a=0,o=0,u=0,s=0,c=0,f=0,l="object"==typeof performance&&performance.now?performance:Date,h="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};function d(){return c||(h(p),c=l.now()+f)}function p(){c=0}function v(){this._call=this._time=this._next=null}function g(t,e,n){var r=new v;return r.restart(t,e,n),r}function _(){d(),++a;for(var t,e=r;e;)(t=c-e._time)>=0&&e._call.call(null,t),e=e._next;--a}function b(){c=(s=l.now())+f,a=o=0;try{_()}finally{a=0,function(){for(var t,e,n=r,a=1/0;n;)n._call?(a>n._time&&(a=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:r=e);i=t,m(a)}(),c=0}}function y(){var t=l.now(),e=t-s;e>1e3&&(f-=e,s=t)}function m(t){a||(o&&(o=clearTimeout(o)),t-c>24?(t<1/0&&(o=setTimeout(b,t-l.now()-f)),u&&(u=clearInterval(u))):(u||(s=l.now(),u=setInterval(y,1e3)),a=1,h(b)))}v.prototype=g.prototype={constructor:v,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?d():+n)+(null==e?0:+e),this._next||i===this||(i?i._next=this:r=this,i=this),this._call=t,this._time=n,m()},stop:function(){this._call&&(this._call=null,this._time=1/0,m())}}},81321:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},16751:(t,e,n)=>{"use strict";function r(t){return t[0]}function i(t){return t[1]}n.d(e,{x:()=>r,y:()=>i})},4864:(t,e,n)=>{"use strict";function r(t){return function(){return t}}n.d(e,{Z:()=>r})},9103:(t,e,n)=>{"use strict";function r(t,e,n){this.target=t,this.type=e,this.transform=n}n.d(e,{Z:()=>r})},39492:(t,e,n)=>{"use strict";if(n.d(e,{r:()=>i,Z:()=>a}),826==n.j)var r=n(78011);function i(){r.B.stopImmediatePropagation()}function a(){r.B.preventDefault(),r.B.stopImmediatePropagation()}},71462:(t,e,n)=>{"use strict";n.r(e),n.d(e,{FormatSpecifier:()=>gn.vr,active:()=>kt,arc:()=>li.Nb,area:()=>li.SO,areaRadial:()=>li.am,ascending:()=>i.j2,autoType:()=>Xe.rA,axisBottom:()=>g,axisLeft:()=>_,axisRight:()=>v,axisTop:()=>p,bisect:()=>i.b4,bisectLeft:()=>i.Nw,bisectRight:()=>i.ml,bisector:()=>i.YF,blob:()=>Je.Ik,brush:()=>Qt,brushSelection:()=>Xt,brushX:()=>Kt,brushY:()=>Jt,buffer:()=>Je.f3,chord:()=>se,clientPoint:()=>fi.Eb,cluster:()=>bn.ki,color:()=>Ne.$_,contourDensity:()=>We,contours:()=>Ue,create:()=>fi.Ue,creator:()=>fi.Du,cross:()=>i.kC,csv:()=>Je.gy,csvFormat:()=>Xe.Sf,csvFormatBody:()=>Xe.S,csvFormatRow:()=>Xe.fh,csvFormatRows:()=>Xe.Jb,csvFormatValue:()=>Xe.eX,csvParse:()=>Xe.ue,csvParseRows:()=>Xe.Bj,cubehelix:()=>Ne.K,curveBasis:()=>li.$0,curveBasisClosed:()=>li.Dt,curveBasisOpen:()=>li.WQ,curveBundle:()=>li.tF,curveCardinal:()=>li.YY,curveCardinalClosed:()=>li.Ov,curveCardinalOpen:()=>li.dC,curveCatmullRom:()=>li.zg,curveCatmullRomClosed:()=>li.fG,curveCatmullRomOpen:()=>li.$m,curveLinear:()=>li.c_,curveLinearClosed:()=>li.fx,curveMonotoneX:()=>li.Fd,curveMonotoneY:()=>li.ak,curveNatural:()=>li.Sx,curveStep:()=>li.eA,curveStepAfter:()=>li.js,curveStepBefore:()=>li.iJ,customEvent:()=>fi._H,descending:()=>i.$1,deviation:()=>i.P3,dispatch:()=>Ve.W,drag:()=>Ge.oh,dragDisable:()=>Ge.Kn,dragEnable:()=>Ge.eF,dsv:()=>Je.Ds,dsvFormat:()=>Xe.yv,easeBack:()=>Ke.bW,easeBackIn:()=>Ke.gp,easeBackInOut:()=>Ke.gI,easeBackOut:()=>Ke.ZN,easeBounce:()=>Ke.sf,easeBounceIn:()=>Ke.RK,easeBounceInOut:()=>Ke.hE,easeBounceOut:()=>Ke.qj,easeCircle:()=>Ke.Xe,easeCircleIn:()=>Ke.kO,easeCircleInOut:()=>Ke.sq,easeCircleOut:()=>Ke.te,easeCubic:()=>Ke.LU,easeCubicIn:()=>Ke.HU,easeCubicInOut:()=>Ke.cC,easeCubicOut:()=>Ke.oS,easeElastic:()=>Ke.Az,easeElasticIn:()=>Ke.aM,easeElasticInOut:()=>Ke.H1,easeElasticOut:()=>Ke.Px,easeExp:()=>Ke.Ll,easeExpIn:()=>Ke.uY,easeExpInOut:()=>Ke.nm,easeExpOut:()=>Ke.mf,easeLinear:()=>Ke.Ny,easePoly:()=>Ke.m2,easePolyIn:()=>Ke.Tf,easePolyInOut:()=>Ke.z5,easePolyOut:()=>Ke.Ct,easeQuad:()=>Ke.uw,easeQuadIn:()=>Ke.V_,easeQuadInOut:()=>Ke.Tu,easeQuadOut:()=>Ke.mm,easeSin:()=>Ke.Tl,easeSinIn:()=>Ke.tl,easeSinInOut:()=>Ke.v,easeSinOut:()=>Ke.p4,entries:()=>Se.Z,event:()=>fi.B,extent:()=>i.We,forceCenter:()=>Qe.Z,forceCollide:()=>tn.Z,forceLink:()=>on,forceManyBody:()=>hn,forceRadial:()=>dn.Z,forceSimulation:()=>ln,forceX:()=>pn.Z,forceY:()=>vn.Z,format:()=>gn.WU,formatDefaultLocale:()=>gn.Zq,formatLocale:()=>gn.FF,formatPrefix:()=>gn.jH,formatSpecifier:()=>gn.YQ,geoAlbers:()=>_n.FW,geoAlbersUsa:()=>_n.wk,geoArea:()=>_n.ID,geoAzimuthalEqualArea:()=>_n.Rf,geoAzimuthalEqualAreaRaw:()=>_n.fN,geoAzimuthalEquidistant:()=>_n.aM,geoAzimuthalEquidistantRaw:()=>_n.dz,geoBounds:()=>_n.qT,geoCentroid:()=>_n.cS,geoCircle:()=>_n.ub,geoClipAntimeridian:()=>_n.o6,geoClipCircle:()=>_n.Fh,geoClipExtent:()=>_n.iM,geoClipRectangle:()=>_n.LF,geoConicConformal:()=>_n.tJ,geoConicConformalRaw:()=>_n.W$,geoConicEqualArea:()=>_n.ET,geoConicEqualAreaRaw:()=>_n.SQ,geoConicEquidistant:()=>_n.ah,geoConicEquidistantRaw:()=>_n.nh,geoContains:()=>_n.xk,geoDistance:()=>_n.gD,geoEqualEarth:()=>_n.bf,geoEqualEarthRaw:()=>_n.bw,geoEquirectangular:()=>_n.ES,geoEquirectangularRaw:()=>_n.Hw,geoGnomonic:()=>_n.Bq,geoGnomonicRaw:()=>_n.ot,geoGraticule:()=>_n.S,geoGraticule10:()=>_n.HV,geoIdentity:()=>_n.NL,geoInterpolate:()=>_n.iG,geoLength:()=>_n.Jp,geoMercator:()=>_n.mw,geoMercatorRaw:()=>_n.z,geoNaturalEarth1:()=>_n.li,geoNaturalEarth1Raw:()=>_n.Bh,geoOrthographic:()=>_n.Wv,geoOrthographicRaw:()=>_n.jx,geoPath:()=>_n.l4,geoProjection:()=>_n.OA,geoProjectionMutator:()=>_n.gv,geoRotation:()=>_n.w7,geoStereographic:()=>_n.kn,geoStereographicRaw:()=>_n.PA,geoStream:()=>_n.HZ,geoTransform:()=>_n.jD,geoTransverseMercator:()=>_n.Il,geoTransverseMercatorRaw:()=>_n.GN,gray:()=>Ne.MA,hcl:()=>Ne.Uc,hierarchy:()=>bn.bT,histogram:()=>i.KX,hsl:()=>Ne.Ym,html:()=>Je.dy,image:()=>Je.BH,interpolate:()=>yn.sX,interpolateArray:()=>yn.Ck,interpolateBasis:()=>yn.nH,interpolateBasisClosed:()=>yn.FO,interpolateBlues:()=>ci.sY,interpolateBrBG:()=>ci.yl,interpolateBuGn:()=>ci.pl,interpolateBuPu:()=>ci.hb,interpolateCividis:()=>ci.r1,interpolateCool:()=>ci.vc,interpolateCubehelix:()=>yn.Ji,interpolateCubehelixDefault:()=>ci.yB,interpolateCubehelixLong:()=>yn.tR,interpolateDate:()=>yn.NW,interpolateDiscrete:()=>yn.Tp,interpolateGnBu:()=>ci.Xw,interpolateGreens:()=>ci.M,interpolateGreys:()=>ci.A_,interpolateHcl:()=>yn.JH,interpolateHclLong:()=>yn.Yr,interpolateHsl:()=>yn.US,interpolateHslLong:()=>yn.H,interpolateHue:()=>yn.EP,interpolateInferno:()=>ci.sN,interpolateLab:()=>yn.uU,interpolateMagma:()=>ci.Gi,interpolateNumber:()=>yn.k4,interpolateNumberArray:()=>yn.qN,interpolateObject:()=>yn.IW,interpolateOrRd:()=>ci.RZ,interpolateOranges:()=>ci.n$,interpolatePRGn:()=>ci.nn,interpolatePiYG:()=>ci.qw,interpolatePlasma:()=>ci.iA,interpolatePuBu:()=>ci.GM,interpolatePuBuGn:()=>ci.S7,interpolatePuOr:()=>ci.xN,interpolatePuRd:()=>ci.cU,interpolatePurples:()=>ci.XW,interpolateRainbow:()=>ci.IC,interpolateRdBu:()=>ci.De,interpolateRdGy:()=>ci.PL,interpolateRdPu:()=>ci.A4,interpolateRdYlBu:()=>ci.zJ,interpolateRdYlGn:()=>ci.BT,interpolateReds:()=>ci.bc,interpolateRgb:()=>yn.LX,interpolateRgbBasis:()=>yn.u1,interpolateRgbBasisClosed:()=>yn.F5,interpolateRound:()=>yn.uL,interpolateSinebow:()=>ci.OO,interpolateSpectral:()=>ci.T0,interpolateString:()=>yn.IT,interpolateTransformCss:()=>yn.Yb,interpolateTransformSvg:()=>yn.wL,interpolateTurbo:()=>ci._B,interpolateViridis:()=>ci.V,interpolateWarm:()=>ci.AO,interpolateYlGn:()=>ci.aE,interpolateYlGnBu:()=>ci.Ht,interpolateYlOrBr:()=>ci.Y_,interpolateYlOrRd:()=>ci.cj,interpolateZoom:()=>yn.JX,interrupt:()=>N,interval:()=>pi.FG,isoFormat:()=>di.zh,isoParse:()=>di.ji,json:()=>Je.AV,keys:()=>Fe.Z,lab:()=>Ne.Nn,lch:()=>Ne.tW,line:()=>li.jv,lineRadial:()=>li.XB,linkHorizontal:()=>li.h5,linkRadial:()=>li.M4,linkVertical:()=>li.rR,local:()=>fi.I_,map:()=>xe,matcher:()=>fi.C2,max:()=>i.Fp,mean:()=>i.J6,median:()=>i.C2,merge:()=>i.TS,min:()=>i.VV,mouse:()=>fi.Jz,namespace:()=>fi.uD,namespaces:()=>fi.aC,nest:()=>we,now:()=>pi.zO,pack:()=>bn.P2,packEnclose:()=>bn.O1,packSiblings:()=>bn.jA,pairs:()=>i.X,partition:()=>bn.uK,path:()=>mn.E,permute:()=>i.FO,pie:()=>li.ve,piecewise:()=>yn.sO,pointRadial:()=>li.Hs,polygonArea:()=>xn.mI,polygonCentroid:()=>xn.tO,polygonContains:()=>xn.Q6,polygonHull:()=>xn.WF,polygonLength:()=>xn.NZ,precisionFixed:()=>gn.zB,precisionPrefix:()=>gn.S5,precisionRound:()=>gn.F0,quadtree:()=>wn.T,quantile:()=>i.VR,quantize:()=>yn.q$,radialArea:()=>li.N1,radialLine:()=>li.aJ,randomBates:()=>jn,randomExponential:()=>Cn,randomIrwinHall:()=>An,randomLogNormal:()=>En,randomNormal:()=>kn,randomUniform:()=>Dn,range:()=>i.w6,rgb:()=>Ne.B8,ribbon:()=>_e,scaleBand:()=>zn,scaleDiverging:()=>ii,scaleDivergingLog:()=>ai,scaleDivergingPow:()=>ui,scaleDivergingSqrt:()=>si,scaleDivergingSymlog:()=>oi,scaleIdentity:()=>ar,scaleImplicit:()=>Nn,scaleLinear:()=>ir,scaleLog:()=>pr,scaleOrdinal:()=>Tn,scalePoint:()=>Rn,scalePow:()=>Zr,scaleQuantile:()=>kr,scaleQuantize:()=>Er,scaleSequential:()=>Kr,scaleSequentialLog:()=>Jr,scaleSequentialPow:()=>ti,scaleSequentialQuantile:()=>ni,scaleSequentialSqrt:()=>ei,scaleSequentialSymlog:()=>Qr,scaleSqrt:()=>Dr,scaleSymlog:()=>br,scaleThreshold:()=>Ar,scaleTime:()=>Lr,scaleUtc:()=>Vr,scan:()=>i.Rp,schemeAccent:()=>ci.Mr,schemeBlues:()=>ci.KH,schemeBrBG:()=>ci.QA,schemeBuGn:()=>ci.S1,schemeBuPu:()=>ci.DQ,schemeCategory10:()=>ci.Cn,schemeDark2:()=>ci.Xg,schemeGnBu:()=>ci.AT,schemeGreens:()=>ci.Yo,schemeGreys:()=>ci.bU,schemeOrRd:()=>ci.MX,schemeOranges:()=>ci.P0,schemePRGn:()=>ci.Uh,schemePaired:()=>ci.xH,schemePastel1:()=>ci.rp,schemePastel2:()=>ci.i4,schemePiYG:()=>ci.Lx,schemePuBu:()=>ci.UV,schemePuBuGn:()=>ci.g1,schemePuOr:()=>ci.$K,schemePuRd:()=>ci.F6,schemePurples:()=>ci.DR,schemeRdBu:()=>ci.HW,schemeRdGy:()=>ci.u_,schemeRdPu:()=>ci.zs,schemeRdYlBu:()=>ci.XX,schemeRdYlGn:()=>ci.Kr,schemeReds:()=>ci.zU,schemeSet1:()=>ci.yK,schemeSet2:()=>ci.W1,schemeSet3:()=>ci.UC,schemeSpectral:()=>ci.lq,schemeTableau10:()=>ci.K2,schemeYlGn:()=>ci.GE,schemeYlGnBu:()=>ci.Yi,schemeYlOrBr:()=>ci.Gb,schemeYlOrRd:()=>ci.M7,select:()=>fi.Ys,selectAll:()=>fi.td,selection:()=>fi.f_,selector:()=>fi.nZ,selectorAll:()=>fi.UK,set:()=>Me,shuffle:()=>i.TV,stack:()=>li.kn,stackOffsetDiverging:()=>li.W$,stackOffsetExpand:()=>li.pB,stackOffsetNone:()=>li.HL,stackOffsetSilhouette:()=>li.Ku,stackOffsetWiggle:()=>li.YG,stackOrderAppearance:()=>li.mG,stackOrderAscending:()=>li.$K,stackOrderDescending:()=>li.IX,stackOrderInsideOut:()=>li.FP,stackOrderNone:()=>li.Qx,stackOrderReverse:()=>li.cY,stratify:()=>bn.QP,style:()=>fi.oB,sum:()=>i.Sm,svg:()=>Je.YP,symbol:()=>li.NA,symbolCircle:()=>li.JF,symbolCross:()=>li.tJ,symbolDiamond:()=>li.rZ,symbolSquare:()=>li.m_,symbolStar:()=>li.Hm,symbolTriangle:()=>li.P6,symbolWye:()=>li.n3,symbols:()=>li.uH,text:()=>Je.fL,thresholdFreedmanDiaconis:()=>i.o6,thresholdScott:()=>i.FA,thresholdSturges:()=>i._X,tickFormat:()=>nr,tickIncrement:()=>i.G9,tickStep:()=>i.ly,ticks:()=>i.sd,timeDay:()=>hi.rr,timeDays:()=>hi.Nu,timeFormat:()=>di.i$,timeFormatDefaultLocale:()=>di.Ds,timeFormatLocale:()=>di.Dq,timeFriday:()=>hi.y2,timeFridays:()=>hi.$N,timeHour:()=>hi.WQ,timeHours:()=>hi.w8,timeInterval:()=>hi.JZ,timeMillisecond:()=>hi.U8,timeMilliseconds:()=>hi.DG,timeMinute:()=>hi.Z_,timeMinutes:()=>hi.Xo,timeMonday:()=>hi.Ox,timeMondays:()=>hi.ip,timeMonth:()=>hi.F0,timeMonths:()=>hi.K_,timeParse:()=>di.Z1,timeSaturday:()=>hi.Lq,timeSaturdays:()=>hi.X2,timeSecond:()=>hi.S1,timeSeconds:()=>hi.BW,timeSunday:()=>hi.Zy,timeSundays:()=>hi.WC,timeThursday:()=>hi.Ig,timeThursdays:()=>hi.Pl,timeTuesday:()=>hi.YD,timeTuesdays:()=>hi.RA,timeWednesday:()=>hi.EF,timeWednesdays:()=>hi.S3,timeWeek:()=>hi.NG,timeWeeks:()=>hi.EN,timeYear:()=>hi.jB,timeYears:()=>hi.HK,timeout:()=>pi.Vs,timer:()=>pi.HT,timerFlush:()=>pi.R8,touch:()=>fi.Fq,touches:()=>fi.W4,transition:()=>yt,transpose:()=>i.p4,tree:()=>bn.G_,treemap:()=>bn.pN,treemapBinary:()=>bn.wL,treemapDice:()=>bn.LQ,treemapResquarify:()=>bn.eA,treemapSlice:()=>bn.Km,treemapSliceDice:()=>bn.E_,treemapSquarify:()=>bn.o$,tsv:()=>Je.pv,tsvFormat:()=>Xe.vP,tsvFormatBody:()=>Xe.uH,tsvFormatRow:()=>Xe.Hf,tsvFormatRows:()=>Xe.n5,tsvFormatValue:()=>Xe.sS,tsvParse:()=>Xe.tJ,tsvParseRows:()=>Xe.E0,utcDay:()=>hi.AN,utcDays:()=>hi.yw,utcFormat:()=>di.g0,utcFriday:()=>hi.QQ,utcFridays:()=>hi.fz,utcHour:()=>hi.lM,utcHours:()=>hi.Xt,utcMillisecond:()=>hi.GK,utcMilliseconds:()=>hi.An,utcMinute:()=>hi.rz,utcMinutes:()=>hi.NH,utcMonday:()=>hi.l6,utcMondays:()=>hi.$3,utcMonth:()=>hi.me,utcMonths:()=>hi.Ks,utcParse:()=>di.wp,utcSaturday:()=>hi.g4,utcSaturdays:()=>hi.Q_,utcSecond:()=>hi.OL,utcSeconds:()=>hi.z1,utcSunday:()=>hi.pI,utcSundays:()=>hi.SU,utcThursday:()=>hi.hB,utcThursdays:()=>hi.xj,utcTuesday:()=>hi.J1,utcTuesdays:()=>hi.DK,utcWednesday:()=>hi.b3,utcWednesdays:()=>hi.uy,utcWeek:()=>hi.YF,utcWeeks:()=>hi._T,utcYear:()=>hi.ol,utcYears:()=>hi.DX,values:()=>Be.Z,variance:()=>i.CA,version:()=>r,voronoi:()=>Ji,window:()=>fi.u9,xml:()=>Je.Ls,zip:()=>i.$R,zoom:()=>ha,zoomIdentity:()=>ra,zoomTransform:()=>ia});var r="5.16.0",i=n(58470),a=Array.prototype.slice,o=n(71603),u=1e-6;function s(t){return"translate("+(t+.5)+",0)"}function c(t){return"translate(0,"+(t+.5)+")"}function f(t){return function(e){return+t(e)}}function l(t){var e=Math.max(0,t.bandwidth()-1)/2;return t.round()&&(e=Math.round(e)),function(n){return+t(n)+e}}function h(){return!this.__axis}function d(t,e){var n=[],r=null,i=null,d=6,p=6,v=3,g=1===t||4===t?-1:1,_=4===t||2===t?"x":"y",b=1===t||3===t?s:c;function y(a){var s=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,c=null==i?e.tickFormat?e.tickFormat.apply(e,n):o.Z:i,y=Math.max(d,0)+v,m=e.range(),x=+m[0]+.5,w=+m[m.length-1]+.5,Z=(e.bandwidth?l:f)(e.copy()),D=a.selection?a.selection():a,k=D.selectAll(".domain").data([null]),E=D.selectAll(".tick").data(s,e).order(),A=E.exit(),j=E.enter().append("g").attr("class","tick"),C=E.select("line"),M=E.select("text");k=k.merge(k.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),E=E.merge(j),C=C.merge(j.append("line").attr("stroke","currentColor").attr(_+"2",g*d)),M=M.merge(j.append("text").attr("fill","currentColor").attr(_,g*y).attr("dy",1===t?"0em":3===t?"0.71em":"0.32em")),a!==D&&(k=k.transition(a),E=E.transition(a),C=C.transition(a),M=M.transition(a),A=A.transition(a).attr("opacity",u).attr("transform",(function(t){return isFinite(t=Z(t))?b(t):this.getAttribute("transform")})),j.attr("opacity",u).attr("transform",(function(t){var e=this.parentNode.__axis;return b(e&&isFinite(e=e(t))?e:Z(t))}))),A.remove(),k.attr("d",4===t||2==t?p?"M"+g*p+","+x+"H0.5V"+w+"H"+g*p:"M0.5,"+x+"V"+w:p?"M"+x+","+g*p+"V0.5H"+w+"V"+g*p:"M"+x+",0.5H"+w),E.attr("opacity",1).attr("transform",(function(t){return b(Z(t))})),C.attr(_+"2",g*d),M.attr(_,g*y).text(c),D.filter(h).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",2===t?"start":4===t?"end":"middle"),D.each((function(){this.__axis=Z}))}return y.scale=function(t){return arguments.length?(e=t,y):e},y.ticks=function(){return n=a.call(arguments),y},y.tickArguments=function(t){return arguments.length?(n=null==t?[]:a.call(t),y):n.slice()},y.tickValues=function(t){return arguments.length?(r=null==t?null:a.call(t),y):r&&r.slice()},y.tickFormat=function(t){return arguments.length?(i=t,y):i},y.tickSize=function(t){return arguments.length?(d=p=+t,y):d},y.tickSizeInner=function(t){return arguments.length?(d=+t,y):d},y.tickSizeOuter=function(t){return arguments.length?(p=+t,y):p},y.tickPadding=function(t){return arguments.length?(v=+t,y):v},y}function p(t){return d(1,t)}function v(t){return d(2,t)}function g(t){return d(3,t)}function _(t){return d(4,t)}var b=n(65264),y=n(61062),m=n(69777),x=n(13171),w=n(78011),Z=n(23475),D=n(42637),k=n(54632),E=n(51852),A=n(58148),j=(0,b.Z)("start","end","cancel","interrupt"),C=[];function M(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(s){var c,f,l,h;if(1!==n.state)return u();for(c in i)if((h=i[c]).name===n.name){if(3===h.state)return(0,A.Z)(a);4===h.state?(h.state=6,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[c]):+c0)throw new Error("too late; already scheduled");return n}function B(t,e){var n=S(t,e);if(n.state>3)throw new Error("too late; already running");return n}function S(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function N(t,e){var n,r,i,a=t.__transition,o=!0;if(a){for(i in e=null==e?null:e+"",a)(n=a[i]).name===e?(r=n.state>2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}var T=n(88994),z=n(69998);function O(t,e){var n,r;return function(){var i=B(this,t),a=i.tween;if(a!==n)for(var o=0,u=(r=n=a).length;o=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?F:B;return function(){var o=a(this,t),u=o.on;u!==r&&(i=(r=u).copy()).on(e,n),o.on=i}}var st=n(61566),ct=n(87393),ft=k.ZP.prototype.constructor,lt=n(34675);function ht(t){return function(){this.style.removeProperty(t)}}function dt(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function pt(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&dt(t,a,n)),r}return a._value=e,a}function vt(t){return function(e){this.textContent=t.call(this,e)}}function gt(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&vt(r)),e}return r._value=t,r}var _t=0;function bt(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function yt(t){return(0,k.ZP)().transition(t)}function mt(){return++_t}var xt=k.ZP.prototype;bt.prototype=yt.prototype={constructor:bt,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=(0,st.Z)(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o1&&n.name===e)return new bt([[t]],Dt,e,+r);return null}var Et=n(41989),At=n(14289),jt=n(78459),Ct={name:"drag"},Mt={name:"space"},Ft={name:"handle"},Bt={name:"center"};function St(t){return[+t[0],+t[1]]}function Nt(t){return[St(t[0]),St(t[1])]}function Tt(t){return function(e){return(0,x.Z)(e,w.B.touches,t)}}var zt={name:"x",handles:["w","e"].map(Ht),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},Ot={name:"y",handles:["n","s"].map(Ht),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},Rt={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(Ht),input:function(t){return null==t?null:Nt(t)},output:function(t){return t}},Pt={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},It={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},Lt={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Ut={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},$t={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function Ht(t){return{type:t}}function qt(){return!w.B.ctrlKey&&!w.B.button}function Yt(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function Wt(){return navigator.maxTouchPoints||"ontouchstart"in this}function Vt(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Gt(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}function Xt(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Kt(){return te(zt)}function Jt(){return te(Ot)}function Qt(){return te(Rt)}function te(t){var e,n=Yt,r=qt,i=Wt,a=!0,o=(0,b.Z)("start","brush","end"),u=6;function s(e){var n=e.property("__brush",v).selectAll(".overlay").data([Ht("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",Pt.overlay).merge(n).each((function(){var t=Vt(this).extent;(0,Z.Z)(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([Ht("selection")]).enter().append("rect").attr("class","selection").attr("cursor",Pt.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return Pt[t.type]})),e.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function c(){var t=(0,Z.Z)(this),e=Vt(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-u/2:e[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-u/2:e[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function f(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new l(t,e,n):r}function l(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function h(){if((!e||w.B.touches)&&r.apply(this,arguments)){var n,i,o,u,s,l,h,d,p,v,g,_=this,b=w.B.target.__data__.type,m="selection"===(a&&w.B.metaKey?b="overlay":b)?Ct:a&&w.B.altKey?Bt:Ft,x=t===Ot?null:Ut[b],k=t===zt?null:$t[b],E=Vt(_),A=E.extent,j=E.selection,C=A[0][0],M=A[0][1],F=A[1][0],B=A[1][1],S=0,T=0,z=x&&k&&a&&w.B.shiftKey,O=w.B.touches?Tt(w.B.changedTouches[0].identifier):D.Z,R=O(_),P=R,I=f(_,arguments,!0).beforestart();"overlay"===b?(j&&(p=!0),E.selection=j=[[n=t===Ot?C:R[0],o=t===zt?M:R[1]],[s=t===Ot?F:n,h=t===zt?B:o]]):(n=j[0][0],o=j[0][1],s=j[1][0],h=j[1][1]),i=n,u=o,l=s,d=h;var L=(0,Z.Z)(_).attr("pointer-events","none"),U=L.selectAll(".overlay").attr("cursor",Pt[b]);if(w.B.touches)I.moved=H,I.ended=Y;else{var $=(0,Z.Z)(w.B.view).on("mousemove.brush",H,!0).on("mouseup.brush",Y,!0);a&&$.on("keydown.brush",W,!0).on("keyup.brush",V,!0),(0,y.Z)(w.B.view)}(0,jt.r)(),N(_),c.call(_),I.start()}function H(){var t=O(_);!z||v||g||(Math.abs(t[0]-P[0])>Math.abs(t[1]-P[1])?g=!0:v=!0),P=t,p=!0,(0,jt.Z)(),q()}function q(){var t;switch(S=P[0]-R[0],T=P[1]-R[1],m){case Mt:case Ct:x&&(S=Math.max(C-n,Math.min(F-s,S)),i=n+S,l=s+S),k&&(T=Math.max(M-o,Math.min(B-h,T)),u=o+T,d=h+T);break;case Ft:x<0?(S=Math.max(C-n,Math.min(F-n,S)),i=n+S,l=s):x>0&&(S=Math.max(C-s,Math.min(F-s,S)),i=n,l=s+S),k<0?(T=Math.max(M-o,Math.min(B-o,T)),u=o+T,d=h):k>0&&(T=Math.max(M-h,Math.min(B-h,T)),u=o,d=h+T);break;case Bt:x&&(i=Math.max(C,Math.min(F,n-S*x)),l=Math.max(C,Math.min(F,s+S*x))),k&&(u=Math.max(M,Math.min(B,o-T*k)),d=Math.max(M,Math.min(B,h+T*k)))}l0&&(n=i-S),k<0?h=d-T:k>0&&(o=u-T),m=Mt,U.attr("cursor",Pt.selection),q());break;default:return}(0,jt.Z)()}function V(){switch(w.B.keyCode){case 16:z&&(v=g=z=!1,q());break;case 18:m===Bt&&(x<0?s=l:x>0&&(n=i),k<0?h=d:k>0&&(o=u),m=Ft,q());break;case 32:m===Mt&&(w.B.altKey?(x&&(s=l-S*x,n=i+S*x),k&&(h=d-T*k,o=u+T*k),m=Bt):(x<0?s=l:x>0&&(n=i),k<0?h=d:k>0&&(o=u),m=Ft),U.attr("cursor",Pt[b]),q());break;default:return}(0,jt.Z)()}}function d(){f(this,arguments).moved()}function p(){f(this,arguments).ended()}function v(){var e=this.__brush||{selection:null};return e.extent=Nt(n.apply(this,arguments)),e.dim=t,e}return s.move=function(e,n){e.selection?e.on("start.brush",(function(){f(this,arguments).beforestart().start()})).on("interrupt.brush end.brush",(function(){f(this,arguments).end()})).tween("brush",(function(){var e=this,r=e.__brush,i=f(e,arguments),a=r.selection,o=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),u=(0,m.Z)(a,o);function s(t){r.selection=1===t&&null===o?null:u(t),c.call(e),i.brush()}return null!==a&&null!==o?s:s(1)})):e.each((function(){var e=this,r=arguments,i=e.__brush,a=t.input("function"==typeof n?n.apply(e,r):n,i.extent),o=f(e,r).beforestart();N(e),i.selection=null===a?null:a,c.call(e),o.start().brush().end()}))},s.clear=function(t){s.move(t,null)},l.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(){return this.starting?(this.starting=!1,this.emit("start")):this.emit("brush"),this},brush:function(){return this.emit("brush"),this},end:function(){return 0==--this.active&&(delete this.state.emitter,this.emit("end")),this},emit:function(e){(0,w._H)(new At.Z(s,e,t.output(this.state.selection)),o.apply,o,[e,this.that,this.args])}},s.extent=function(t){return arguments.length?(n="function"==typeof t?t:(0,Et.Z)(Nt(t)),s):n},s.filter=function(t){return arguments.length?(r="function"==typeof t?t:(0,Et.Z)(!!t),s):r},s.touchable=function(t){return arguments.length?(i="function"==typeof t?t:(0,Et.Z)(!!t),s):i},s.handleSize=function(t){return arguments.length?(u=+t,s):u},s.keyModifiers=function(t){return arguments.length?(a=!!t,s):a},s.on=function(){var t=o.on.apply(o,arguments);return t===o?s:t},s}var ee=Math.cos,ne=Math.sin,re=Math.PI,ie=re/2,ae=2*re,oe=Math.max;function ue(t){return function(e,n){return t(e.source.value+e.target.value,n.source.value+n.target.value)}}function se(){var t=0,e=null,n=null,r=null;function a(a){var o,u,s,c,f,l,h=a.length,d=[],p=(0,i.w6)(h),v=[],g=[],_=g.groups=new Array(h),b=new Array(h*h);for(o=0,f=-1;++f=r.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,c,f,l=-1,h=n.length,d=r[i++],p=xe(),v=o();++lr.length)return t;var a,u=i[n-1];return null!=e&&n>=r.length?a=t.entries():(a=[],t.each((function(t,e){a.push({key:e,values:o(t,n)})}))),null!=u?a.sort((function(t,e){return u(t.key,e.key)})):a}return n={object:function(t){return a(t,0,Ze,De)},map:function(t){return a(t,0,ke,Ee)},entries:function(t){return o(a(t,0,ke,Ee),0)},key:function(t){return r.push(t),n},sortKeys:function(t){return i[r.length-1]=t,n},sortValues:function(e){return t=e,n},rollup:function(t){return e=t,n}}}function Ze(){return{}}function De(t,e,n){t[e]=n}function ke(){return xe()}function Ee(t,e,n){t.set(e,n)}function Ae(){}var je=xe.prototype;function Ce(t,e){var n=new Ae;if(t instanceof Ae)t.each((function(t){n.add(t)}));else if(t){var r=-1,i=t.length;if(null==e)for(;++r=r,Le[c<<1].forEach(p);++a=r,Le[s|c<<1].forEach(p);for(Le[c<<0].forEach(p);++o=r,f=n[o*t]>=r,Le[c<<1|f<<2].forEach(p);++a=r,l=f,f=n[o*t+a+1]>=r,Le[s|c<<1|f<<2|l<<3].forEach(p);Le[c|f<<3].forEach(p)}for(a=-1,f=n[o*t]>=r,Le[f<<2].forEach(p);++a=r,Le[f<<2|l<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+a,t[0][1]+o],s=[t[1][0]+a,t[1][1]+o],c=u(r),f=u(s);(e=d[c])?(n=h[f])?(delete d[e.end],delete h[n.start],e===n?(e.ring.push(s),i(e.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete d[e.end],e.ring.push(s),d[e.end=f]=e):(e=h[f])?(n=d[c])?(delete h[e.start],delete d[n.end],e===n?(e.ring.push(s),i(e.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete h[e.start],e.ring.unshift(r),h[e.start=c]=e):h[c]=d[f]={start:c,end:f,ring:[r,s]}}Le[f<<3].forEach(p)}(n,i,(function(t){r(t,n,i),(0,Oe.Z)(t)>0?a.push([t]):o.push(t)})),o.forEach((function(t){for(var e,n=0,r=a.length;n0&&o0&&u0&&i>0))throw new Error("invalid size");return t=r,e=i,a},a.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?(0,Re.Z)(Te.call(t)):(0,Re.Z)(t),a):n},a.smooth=function(t){return arguments.length?(r=t?s:Ie.Z,a):r===s},a}var $e=n(5109);function He(t){return t[0]}function qe(t){return t[1]}function Ye(){return 1}function We(){var t=He,e=qe,n=Ye,r=960,a=500,o=20,u=2,s=3*o,c=r+2*s>>u,f=a+2*s>>u,l=(0,Re.Z)(20);function h(r){var a=new Float32Array(c*f),h=new Float32Array(c*f);r.forEach((function(r,i,o){var l=+t(r,i,o)+s>>u,h=+e(r,i,o)+s>>u,d=+n(r,i,o);l>=0&&l=0&&h>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u),(0,$e._)({width:c,height:f,data:a},{width:c,height:f,data:h},o>>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u),(0,$e._)({width:c,height:f,data:a},{width:c,height:f,data:h},o>>u),(0,$e.$)({width:c,height:f,data:h},{width:c,height:f,data:a},o>>u);var p=l(a);if(!Array.isArray(p)){var v=(0,i.Fp)(a);p=(0,i.ly)(0,v,p),(p=(0,i.w6)(0,Math.floor(v/p)*p,p)).shift()}return Ue().thresholds(p).size([c,f])(a).map(d)}function d(t){return t.value*=Math.pow(2,-2*u),t.coordinates.forEach(p),t}function p(t){t.forEach(v)}function v(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,u)-s,t[1]=t[1]*Math.pow(2,u)-s}function _(){return c=r+2*(s=3*o)>>u,f=a+2*s>>u,h}return h.x=function(e){return arguments.length?(t="function"==typeof e?e:(0,Re.Z)(+e),h):t},h.y=function(t){return arguments.length?(e="function"==typeof t?t:(0,Re.Z)(+t),h):e},h.weight=function(t){return arguments.length?(n="function"==typeof t?t:(0,Re.Z)(+t),h):n},h.size=function(t){if(!arguments.length)return[r,a];var e=Math.ceil(t[0]),n=Math.ceil(t[1]);if(!(e>=0||e>=0))throw new Error("invalid size");return r=e,a=n,_()},h.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return u=Math.floor(Math.log(t)/Math.LN2),_()},h.thresholds=function(t){return arguments.length?(l="function"==typeof t?t:Array.isArray(t)?(0,Re.Z)(Te.call(t)):(0,Re.Z)(t),h):l},h.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),_()},h}var Ve=n(10961),Ge=n(95520),Xe=n(83611),Ke=n(13756),Je=n(14413),Qe=n(71233),tn=n(47226),en=n(84442),nn=n(43266);function rn(t){return t.index}function an(t,e){var n=t.get(e);if(!n)throw new Error("missing: "+e);return n}function on(t){var e,n,r,i,a,o=rn,u=function(t){return 1/Math.min(i[t.source.index],i[t.target.index])},s=(0,en.Z)(30),c=1;function f(r){for(var i=0,o=t.length;i1?(null==n?u.remove(t):u.set(t,d(n)),e):u.get(t)},find:function(e,n,r){var i,a,o,u,s,c=0,f=t.length;for(null==r?r=1/0:r*=r,c=0;c1?(c.on(t,n),e):c.on(t)}}}function hn(){var t,e,n,r,i=(0,en.Z)(-30),a=1,o=1/0,u=.81;function s(r){var i,a=t.length,o=(0,un.Z)(t,sn,cn).visitAfter(f);for(n=r,i=0;i=o)){(t.data!==e||t.next)&&(0===f&&(d+=(f=(0,nn.Z)())*f),0===l&&(d+=(l=(0,nn.Z)())*l),d1);return t+n*a*Math.sqrt(-2*Math.log(i)/i)}}return n.source=t,n}(Zn),En=function t(e){function n(){var t=kn.source(e).apply(this,arguments);return function(){return Math.exp(t())}}return n.source=t,n}(Zn),An=function t(e){function n(t){return function(){for(var n=0,r=0;rr&&(e=n,n=r,r=e),function(t){return Math.max(n,Math.min(r,t))}}function Yn(t,e,n){var r=t[0],i=t[1],a=e[0],o=e[1];return i2?Wn:Yn,i=a=null,l}function l(e){return isNaN(e=+e)?n:(i||(i=r(o.map(t),u,s)))(t(c(e)))}return l.invert=function(n){return c(e((a||(a=r(u,o.map(t),L.Z)))(n)))},l.domain=function(t){return arguments.length?(o=Bn.call(t,Ln.Z),c===$n||(c=qn(o)),f()):o.slice()},l.range=function(t){return arguments.length?(u=Sn.call(t),f()):u.slice()},l.rangeRound=function(t){return u=Sn.call(t),s=Pn.Z,f()},l.clamp=function(t){return arguments.length?(c=t?qn(o):$n,l):c!==$n},l.interpolate=function(t){return arguments.length?(s=t,f()):s},l.unknown=function(t){return arguments.length?(n=t,l):n},function(n,r){return t=n,e=r,f()}}function Xn(t,e){return Gn()(t,e)}var Kn=n(47681),Jn=n(94735),Qn=n(46973),tr=n(54415),er=n(84418);function nr(t,e,n,r){var a,o=(0,i.ly)(t,e,n);switch((r=(0,Kn.Z)(null==r?",f":r)).type){case"s":var u=Math.max(Math.abs(t),Math.abs(e));return null!=r.precision||isNaN(a=(0,Jn.Z)(o,u))||(r.precision=a),(0,Qn.jH)(r,u);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(a=(0,tr.Z)(o,Math.max(Math.abs(t),Math.abs(e))))||(r.precision=a-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(a=(0,er.Z)(o))||(r.precision=a-2*("%"===r.type))}return(0,Qn.WU)(r)}function rr(t){var e=t.domain;return t.ticks=function(t){var n=e();return(0,i.sd)(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return nr(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var r,a=e(),o=0,u=a.length-1,s=a[o],c=a[u];return c0?(s=Math.floor(s/r)*r,c=Math.ceil(c/r)*r,r=(0,i.G9)(s,c,n)):r<0&&(s=Math.ceil(s*r)/r,c=Math.floor(c*r)/r,r=(0,i.G9)(s,c,n)),r>0?(a[o]=Math.floor(s/r)*r,a[u]=Math.ceil(c/r)*r,e(a)):r<0&&(a[o]=Math.ceil(s*r)/r,a[u]=Math.floor(c*r)/r,e(a)),t},t}function ir(){var t=Xn($n,$n);return t.copy=function(){return Vn(t,ir())},Mn.o.apply(t,arguments),rr(t)}function ar(t){var e;function n(t){return isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Bn.call(e,Ln.Z),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return ar(t).unknown(e)},t=arguments.length?Bn.call(t,Ln.Z):[0,1],rr(n)}var or=n(10070);function ur(t){return Math.log(t)}function sr(t){return Math.exp(t)}function cr(t){return-Math.log(-t)}function fr(t){return-Math.exp(-t)}function lr(t){return isFinite(t)?+("1e"+t):t<0?0:t}function hr(t){return function(e){return-t(-e)}}function dr(t){var e,n,r=t(ur,sr),a=r.domain,o=10;function u(){return e=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),function(e){return Math.log(e)/t})}(o),n=function(t){return 10===t?lr:t===Math.E?Math.exp:function(e){return Math.pow(t,e)}}(o),a()[0]<0?(e=hr(e),n=hr(n),t(cr,fr)):t(ur,sr),r}return r.base=function(t){return arguments.length?(o=+t,u()):o},r.domain=function(t){return arguments.length?(a(t),u()):a()},r.ticks=function(t){var r,u=a(),s=u[0],c=u[u.length-1];(r=c0){for(;dc)break;g.push(h)}}else for(;d=1;--l)if(!((h=f*l)c)break;g.push(h)}}else g=(0,i.sd)(d,p,Math.min(p-d,v)).map(n);return r?g.reverse():g},r.tickFormat=function(t,i){if(null==i&&(i=10===o?".0e":","),"function"!=typeof i&&(i=(0,Qn.WU)(i)),t===1/0)return i;null==t&&(t=10);var a=Math.max(1,o*t/r.ticks().length);return function(t){var r=t/n(Math.round(e(t)));return r*o0?r[i-1]:e[0],i=r?[a[r-1],n]:[a[i-1],a[i]]},u.unknown=function(e){return arguments.length?(t=e,u):u},u.thresholds=function(){return a.slice()},u.copy=function(){return Er().domain([e,n]).range(o).unknown(t)},Mn.o.apply(rr(u),arguments)}function Ar(){var t,e=[.5],n=[0,1],r=1;function a(a){return a<=a?n[(0,i.b4)(e,a,0,r)]:t}return a.domain=function(t){return arguments.length?(e=Sn.call(t),r=Math.min(e.length,n.length-1),a):e.slice()},a.range=function(t){return arguments.length?(n=Sn.call(t),r=Math.min(e.length,n.length-1),a):n.slice()},a.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},a.unknown=function(e){return arguments.length?(t=e,a):t},a.copy=function(){return Ar().domain(e).range(n).unknown(t)},Mn.o.apply(a,arguments)}var jr=n(97344),Cr=n(50690),Mr=n(76231),Fr=n(68603),Br=n(54076),Sr=n(18450),Nr=n(52546),Tr=n(30356),zr=n(49164),Or=31536e6;function Rr(t){return new Date(t)}function Pr(t){return t instanceof Date?+t:+new Date(+t)}function Ir(t,e,n,r,a,o,u,s,c){var f=Xn($n,$n),l=f.invert,h=f.domain,d=c(".%L"),p=c(":%S"),v=c("%I:%M"),g=c("%I %p"),_=c("%a %d"),b=c("%b %d"),y=c("%B"),m=c("%Y"),x=[[u,1,1e3],[u,5,5e3],[u,15,15e3],[u,30,3e4],[o,1,6e4],[o,5,3e5],[o,15,9e5],[o,30,18e5],[a,1,36e5],[a,3,108e5],[a,6,216e5],[a,12,432e5],[r,1,864e5],[r,2,1728e5],[n,1,6048e5],[e,1,2592e6],[e,3,7776e6],[t,1,Or]];function w(i){return(u(i)0)){if(a/=h,h<0){if(a0){if(a>l)return;a>f&&(f=a)}if(a=r-s,h||!(a<0)){if(a/=h,h<0){if(a>l)return;a>f&&(f=a)}else if(h>0){if(a0)){if(a/=d,d<0){if(a0){if(a>l)return;a>f&&(f=a)}if(a=i-c,d||!(a<0)){if(a/=d,d<0){if(a>l)return;a>f&&(f=a)}else if(d>0){if(a0||l<1)||(f>0&&(t[0]=[s+f*h,c+f*d]),l<1&&(t[1]=[s+l*h,c+l*d]),!0)}}}}}function Ai(t,e,n,r,i){var a=t[1];if(a)return!0;var o,u,s=t[0],c=t.left,f=t.right,l=c[0],h=c[1],d=f[0],p=f[1],v=(l+d)/2,g=(h+p)/2;if(p===h){if(v=r)return;if(l>d){if(s){if(s[1]>=i)return}else s=[v,n];a=[v,i]}else{if(s){if(s[1]1)if(l>d){if(s){if(s[1]>=i)return}else s=[(n-u)/o,n];a=[(i-u)/o,i]}else{if(s){if(s[1]=r)return}else s=[e,o*e+u];a=[r,o*r+u]}else{if(s){if(s[0]=-Gi)){var d=s*s+c*c,p=f*f+l*l,v=(l*d-c*p)/h,g=(s*p-f*d)/h,_=Bi.pop()||new Si;_.arc=t,_.site=i,_.x=v+o,_.y=(_.cy=g+u)+Math.sqrt(v*v+g*g),t.circle=_;for(var b=null,y=Yi._;y;)if(_.yVi)u=u.L;else{if(!((i=a-$i(u,o))>Vi)){r>-Vi?(e=u.P,n=u):i>-Vi?(e=u,n=u.N):e=n=u;break}if(!u.R){e=u;break}u=u.R}!function(t){qi[t.index]={site:t,halfedges:[]}}(t);var s=Ri(t);if(Hi.insert(e,s),e||n){if(e===n)return Ti(e),n=Ri(e.site),Hi.insert(s,n),s.edge=n.edge=Zi(e.site,s.site),Ni(e),void Ni(n);if(n){Ti(e),Ti(n);var c=e.site,f=c[0],l=c[1],h=t[0]-f,d=t[1]-l,p=n.site,v=p[0]-f,g=p[1]-l,_=2*(h*g-d*v),b=h*h+d*d,y=v*v+g*g,m=[(g*b-d*y)/_+f,(h*y-v*b)/_+l];ki(n.edge,c,p,m),s.edge=Zi(c,t,null,m),n.edge=Zi(t,p,null,m),Ni(e),Ni(n)}else s.edge=Zi(e.site,s.site)}}function Ui(t,e){var n=t.site,r=n[0],i=n[1],a=i-e;if(!a)return r;var o=t.P;if(!o)return-1/0;var u=(n=o.site)[0],s=n[1],c=s-e;if(!c)return u;var f=u-r,l=1/a-1/c,h=f/c;return l?(-h+Math.sqrt(h*h-2*l*(f*f/(-2*c)-s+c/2+i-a/2)))/l+r:(r+u)/2}function $i(t,e){var n=t.N;if(n)return Ui(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var Hi,qi,Yi,Wi,Vi=1e-6,Gi=1e-12;function Xi(t,e){return e[1]-t[1]||e[0]-t[0]}function Ki(t,e){var n,r,i,a=t.sort(Xi).pop();for(Wi=[],qi=new Array(t.length),Hi=new wi,Yi=new wi;;)if(i=Fi,a&&(!i||a[1]Vi||Math.abs(i[0][1]-i[1][1])>Vi)||delete Wi[a]}(o,u,s,c),function(t,e,n,r){var i,a,o,u,s,c,f,l,h,d,p,v,g=qi.length,_=!0;for(i=0;iVi||Math.abs(v-h)>Vi)&&(s.splice(u,0,Wi.push(Di(o,d,Math.abs(p-t)Vi?[t,Math.abs(l-t)Vi?[Math.abs(h-r)Vi?[n,Math.abs(l-n)Vi?[Math.abs(h-e)=u)return null;var s=t-i.site[0],c=e-i.site[1],f=s*s+c*c;do{i=a.cells[r=o],o=null,i.halfedges.forEach((function(n){var r=a.edges[n],u=r.left;if(u!==i.site&&u||(u=r.right)){var s=t-u[0],c=e-u[1],l=s*s+c*c;lr?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function ha(){var t,e,n=oa,r=ua,i=la,a=ca,o=fa,u=[0,1/0],s=[[-1/0,-1/0],[1/0,1/0]],c=250,f=Qi.Z,l=(0,b.Z)("start","zoom","end"),h=500,d=0;function p(t){t.property("__zoom",sa).on("wheel.zoom",A).on("mousedown.zoom",j).on("dblclick.zoom",C).filter(o).on("touchstart.zoom",M).on("touchmove.zoom",F).on("touchend.zoom touchcancel.zoom",B).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function v(t,e){return(e=Math.max(u[0],Math.min(u[1],e)))===t.k?t:new na(e,t.x,t.y)}function g(t,e,n){var r=e[0]-n[0]*t.k,i=e[1]-n[1]*t.k;return r===t.x&&i===t.y?t:new na(t.k,r,i)}function _(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function m(t,e,n){t.on("start.zoom",(function(){k(this,arguments).start()})).on("interrupt.zoom end.zoom",(function(){k(this,arguments).end()})).tween("zoom",(function(){var t=this,i=arguments,a=k(t,i),o=r.apply(t,i),u=null==n?_(o):"function"==typeof n?n.apply(t,i):n,s=Math.max(o[1][0]-o[0][0],o[1][1]-o[0][1]),c=t.__zoom,l="function"==typeof e?e.apply(t,i):e,h=f(c.invert(u).concat(s/c.k),l.invert(u).concat(s/l.k));return function(t){if(1===t)t=l;else{var e=h(t),n=s/e[2];t=new na(n,u[0]-e[0]*n,u[1]-e[1]*n)}a.zoom(null,t)}}))}function k(t,e,n){return!n&&t.__zooming||new E(t,e)}function E(t,e){this.that=t,this.args=e,this.active=0,this.extent=r.apply(t,e),this.taps=0}function A(){if(n.apply(this,arguments)){var t=k(this,arguments),e=this.__zoom,r=Math.max(u[0],Math.min(u[1],e.k*Math.pow(2,a.apply(this,arguments)))),o=(0,D.Z)(this);if(t.wheel)t.mouse[0][0]===o[0]&&t.mouse[0][1]===o[1]||(t.mouse[1]=e.invert(t.mouse[0]=o)),clearTimeout(t.wheel);else{if(e.k===r)return;t.mouse=[o,e.invert(o)],N(this),t.start()}(0,aa.Z)(),t.wheel=setTimeout(c,150),t.zoom("mouse",i(g(v(e,r),t.mouse[0],t.mouse[1]),t.extent,s))}function c(){t.wheel=null,t.end()}}function j(){if(!e&&n.apply(this,arguments)){var t=k(this,arguments,!0),r=(0,Z.Z)(w.B.view).on("mousemove.zoom",c,!0).on("mouseup.zoom",f,!0),a=(0,D.Z)(this),o=w.B.clientX,u=w.B.clientY;(0,y.Z)(w.B.view),(0,aa.r)(),t.mouse=[a,this.__zoom.invert(a)],N(this),t.start()}function c(){if((0,aa.Z)(),!t.moved){var e=w.B.clientX-o,n=w.B.clientY-u;t.moved=e*e+n*n>d}t.zoom("mouse",i(g(t.that.__zoom,t.mouse[0]=(0,D.Z)(t.that),t.mouse[1]),t.extent,s))}function f(){r.on("mousemove.zoom mouseup.zoom",null),(0,y.D)(w.B.view,t.moved),(0,aa.Z)(),t.end()}}function C(){if(n.apply(this,arguments)){var t=this.__zoom,e=(0,D.Z)(this),a=t.invert(e),o=t.k*(w.B.shiftKey?.5:2),u=i(g(v(t,o),e,a),r.apply(this,arguments),s);(0,aa.Z)(),c>0?(0,Z.Z)(this).transition().duration(c).call(m,u,e):(0,Z.Z)(this).call(p.transform,u)}}function M(){if(n.apply(this,arguments)){var e,r,i,a,o=w.B.touches,u=o.length,s=k(this,arguments,w.B.changedTouches.length===u);for((0,aa.r)(),r=0;r{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(60401);function i(t){return(t=(0,r.V)(Math.abs(t)))?t[1]:NaN}},60401:(t,e,n)=>{"use strict";function r(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function i(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}n.d(e,{Z:()=>r,V:()=>i})},10499:(t,e,n)=>{"use strict";function r(t,e){return function(n,r){for(var i=n.length,a=[],o=0,u=t[0],s=0;i>0&&u>0&&(s+u+1>r&&(u=Math.max(1,r-s)),a.push(n.substring(i-=u,i+u)),!((s+=u+1)>r));)u=t[o=(o+1)%t.length];return a.reverse().join(e)}}n.d(e,{Z:()=>r})},47447:(t,e,n)=>{"use strict";function r(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}n.d(e,{Z:()=>r})},30267:(t,e,n)=>{"use strict";if(n.d(e,{y:()=>i,Z:()=>a}),826==n.j)var r=n(60401);var i;function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var a=n[0],o=n[1],u=o-(i=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,s=a.length;return u===s?a:u>s?a+new Array(u-s+1).join("0"):u>0?a.slice(0,u)+"."+a.slice(u):"0."+new Array(1-u).join("0")+(0,r.V)(t,Math.max(0,e+u-1))[0]}},14473:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i,v:()=>a});var r=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function i(t){if(!(e=r.exec(t)))throw new Error("invalid format: "+t);var e;return new a({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function a(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}i.prototype=a.prototype,a.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type}},33123:(t,e,n)=>{"use strict";function r(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}n.d(e,{Z:()=>r})},9985:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(60401),i=n(30267);function a(t,e){var n=(0,r.V)(t,e);if(!n)return t+"";var i=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+i:i.length>a+1?i.slice(0,a+1)+"."+i.slice(a+1):i+new Array(a-i.length+2).join("0")}const o={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:r.Z,e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return a(100*t,e)},r:a,s:i.Z,X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}}},21568:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{Z:()=>r})},68639:(t,e,n)=>{"use strict";n.d(e,{vr:()=>s.v,WU:()=>i,Zq:()=>u,FF:()=>o.Z,jH:()=>a,YQ:()=>s.Z,zB:()=>c.Z,S5:()=>f.Z,F0:()=>l.Z});var r,i,a,o=n(12555);function u(t){return r=(0,o.Z)(t),i=r.format,a=r.formatPrefix,r}u({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});var s=n(14473),c=n(84125),f=n(11491),l=n(76515)},12555:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>d}),826==n.j)var r=n(21074);if(826==n.j)var i=n(10499);if(826==n.j)var a=n(47447);if(826==n.j)var o=n(14473);if(826==n.j)var u=n(33123);if(826==n.j)var s=n(9985);if(826==n.j)var c=n(30267);if(826==n.j)var f=n(21568);var l=Array.prototype.map,h=826==n.j?["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"]:null;function d(t){var e=void 0===t.grouping||void 0===t.thousands?f.Z:(0,i.Z)(l.call(t.grouping,Number),t.thousands+""),n=void 0===t.currency?"":t.currency[0]+"",d=void 0===t.currency?"":t.currency[1]+"",p=void 0===t.decimal?".":t.decimal+"",v=void 0===t.numerals?f.Z:(0,a.Z)(l.call(t.numerals,String)),g=void 0===t.percent?"%":t.percent+"",_=void 0===t.minus?"-":t.minus+"",b=void 0===t.nan?"NaN":t.nan+"";function y(t){var r=(t=(0,o.Z)(t)).fill,i=t.align,a=t.sign,f=t.symbol,l=t.zero,y=t.width,m=t.comma,x=t.precision,w=t.trim,Z=t.type;"n"===Z?(m=!0,Z="g"):s.Z[Z]||(void 0===x&&(x=12),w=!0,Z="g"),(l||"0"===r&&"="===i)&&(l=!0,r="0",i="=");var D="$"===f?n:"#"===f&&/[boxX]/.test(Z)?"0"+Z.toLowerCase():"",k="$"===f?d:/[%p]/.test(Z)?g:"",E=s.Z[Z],A=/[defgprs%]/.test(Z);function j(t){var n,o,s,f=D,d=k;if("c"===Z)d=E(t)+d,t="";else{var g=(t=+t)<0||1/t<0;if(t=isNaN(t)?b:E(Math.abs(t),x),w&&(t=(0,u.Z)(t)),g&&0==+t&&"+"!==a&&(g=!1),f=(g?"("===a?a:_:"-"===a||"("===a?"":a)+f,d=("s"===Z?h[8+c.y/3]:"")+d+(g&&"("===a?")":""),A)for(n=-1,o=t.length;++n(s=t.charCodeAt(n))||s>57){d=(46===s?p+t.slice(n+1):t.slice(n))+d,t=t.slice(0,n);break}}m&&!l&&(t=e(t,1/0));var j=f.length+t.length+d.length,C=j>1)+f+t+d+C.slice(j);break;default:t=C+f+t+d}return v(t)}return x=void 0===x?6:/[gprs]/.test(Z)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x)),j.toString=function(){return t+""},j}return{format:y,formatPrefix:function(t,e){var n=y(((t=(0,o.Z)(t)).type="f",t)),i=3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3))),a=Math.pow(10,-i),u=h[8+i/3];return function(t){return n(a*t)+u}}}}},84125:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t){return Math.max(0,-(0,r.Z)(Math.abs(t)))}},11491:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor((0,r.Z)(e)/3)))-(0,r.Z)(Math.abs(t)))}},76515:(t,e,n)=>{"use strict";if(n.d(e,{Z:()=>i}),826==n.j)var r=n(21074);function i(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,(0,r.Z)(e)-(0,r.Z)(t))+1}},46506:(t,e,n)=>{t.exports={graphlib:n(71310),layout:n(42529),debug:n(5512),util:{time:n(8783).time,notime:n(8783).notime},version:n(57589)}},85247:(t,e,n)=>{"use strict";var r=n(43294),i=n(38757);t.exports={run:function(t){var e="greedy"===t.graph().acyclicer?i(t,function(t){return function(e){return t.edge(e).weight}}(t)):function(t){var e=[],n={},i={};return r.forEach(t.nodes(),(function a(o){r.has(i,o)||(i[o]=!0,n[o]=!0,r.forEach(t.outEdges(o),(function(t){r.has(n,t.w)?e.push(t):a(t.w)})),delete n[o])})),e}(t);r.forEach(e,(function(e){var n=t.edge(e);t.removeEdge(e),n.forwardName=e.name,n.reversed=!0,t.setEdge(e.w,e.v,n,r.uniqueId("rev"))}))},undo:function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.reversed){t.removeEdge(e);var r=n.forwardName;delete n.reversed,delete n.forwardName,t.setEdge(e.w,e.v,n,r)}}))}}},49654:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n,r,a,o){var u={width:0,height:0,rank:o,borderType:e},s=a[e][o-1],c=i.addDummyNode(t,"border",u,n);a[e][o]=c,t.setParent(c,r),s&&t.setEdge(s,c,{weight:1})}t.exports=function(t){r.forEach(t.children(),(function e(n){var i=t.children(n),o=t.node(n);if(i.length&&r.forEach(i,e),r.has(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(var u=o.minRank,s=o.maxRank+1;u{"use strict";var r=n(43294);function i(t){r.forEach(t.nodes(),(function(e){a(t.node(e))})),r.forEach(t.edges(),(function(e){a(t.edge(e))}))}function a(t){var e=t.width;t.width=t.height,t.height=e}function o(t){t.y=-t.y}function u(t){var e=t.x;t.x=t.y,t.y=e}t.exports={adjust:function(t){var e=t.graph().rankdir.toLowerCase();"lr"!==e&&"rl"!==e||i(t)},undo:function(t){var e=t.graph().rankdir.toLowerCase();"bt"!==e&&"rl"!==e||function(t){r.forEach(t.nodes(),(function(e){o(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,o),r.has(n,"y")&&o(n)}))}(t),"lr"!==e&&"rl"!==e||(function(t){r.forEach(t.nodes(),(function(e){u(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,u),r.has(n,"x")&&u(n)}))}(t),i(t))}}},65199:t=>{function e(){var t={};t._next=t._prev=t,this._sentinel=t}function n(t){t._prev._next=t._next,t._next._prev=t._prev,delete t._next,delete t._prev}function r(t,e){if("_next"!==t&&"_prev"!==t)return e}t.exports=e,e.prototype.dequeue=function(){var t=this._sentinel,e=t._prev;if(e!==t)return n(e),e},e.prototype.enqueue=function(t){var e=this._sentinel;t._prev&&t._next&&n(t),t._next=e._next,e._next._prev=t,e._next=t,t._prev=e},e.prototype.toString=function(){for(var t=[],e=this._sentinel,n=e._prev;n!==e;)t.push(JSON.stringify(n,r)),n=n._prev;return"["+t.join(", ")+"]"}},5512:(t,e,n)=>{var r=n(43294),i=n(8783),a=n(71310).Graph;t.exports={debugOrdering:function(t){var e=i.buildLayerMatrix(t),n=new a({compound:!0,multigraph:!0}).setGraph({});return r.forEach(t.nodes(),(function(e){n.setNode(e,{label:e}),n.setParent(e,"layer"+t.node(e).rank)})),r.forEach(t.edges(),(function(t){n.setEdge(t.v,t.w,{},t.name)})),r.forEach(e,(function(t,e){var i="layer"+e;n.setNode(i,{rank:"same"}),r.reduce(t,(function(t,e){return n.setEdge(t,e,{style:"invis"}),e}))})),n}}},71310:(t,e,n)=>{var r;try{r=n(87377)}catch(t){}r||(r=window.graphlib),t.exports=r},38757:(t,e,n)=>{var r=n(43294),i=n(71310).Graph,a=n(65199);t.exports=function(t,e){if(t.nodeCount()<=1)return[];var n=function(t,e){var n=new i,o=0,u=0;r.forEach(t.nodes(),(function(t){n.setNode(t,{v:t,in:0,out:0})})),r.forEach(t.edges(),(function(t){var r=n.edge(t.v,t.w)||0,i=e(t),a=r+i;n.setEdge(t.v,t.w,a),u=Math.max(u,n.node(t.v).out+=i),o=Math.max(o,n.node(t.w).in+=i)}));var c=r.range(u+o+3).map((function(){return new a})),f=o+1;return r.forEach(n.nodes(),(function(t){s(c,f,n.node(t))})),{graph:n,buckets:c,zeroIdx:f}}(t,e||o),c=function(t,e,n){for(var r,i=[],a=e[e.length-1],o=e[0];t.nodeCount();){for(;r=o.dequeue();)u(t,e,n,r);for(;r=a.dequeue();)u(t,e,n,r);if(t.nodeCount())for(var s=e.length-2;s>0;--s)if(r=e[s].dequeue()){i=i.concat(u(t,e,n,r,!0));break}}return i}(n.graph,n.buckets,n.zeroIdx);return r.flatten(r.map(c,(function(e){return t.outEdges(e.v,e.w)})),!0)};var o=r.constant(1);function u(t,e,n,i,a){var o=a?[]:void 0;return r.forEach(t.inEdges(i.v),(function(r){var i=t.edge(r),u=t.node(r.v);a&&o.push({v:r.v,w:r.w}),u.out-=i,s(e,n,u)})),r.forEach(t.outEdges(i.v),(function(r){var i=t.edge(r),a=r.w,o=t.node(a);o.in-=i,s(e,n,o)})),t.removeNode(i.v),o}function s(t,e,n){n.out?n.in?t[n.out-n.in+e].enqueue(n):t[t.length-1].enqueue(n):t[0].enqueue(n)}},42529:(t,e,n)=>{"use strict";var r=n(43294),i=n(85247),a=n(20450),o=n(64618),u=n(8783).normalizeRanks,s=n(77908),c=n(8783).removeEmptyRanks,f=n(96820),l=n(49654),h=n(25128),d=n(73641),p=n(65784),v=n(8783),g=n(71310).Graph;t.exports=function(t,e){var n=e&&e.debugTiming?v.time:v.notime;n("layout",(function(){var e=n(" buildLayoutGraph",(function(){return function(t){var e=new g({multigraph:!0,compound:!0}),n=E(t.graph());return e.setGraph(r.merge({},b,k(n,_),r.pick(n,y))),r.forEach(t.nodes(),(function(n){var i=E(t.node(n));e.setNode(n,r.defaults(k(i,m),x)),e.setParent(n,t.parent(n))})),r.forEach(t.edges(),(function(n){var i=E(t.edge(n));e.setEdge(n,r.merge({},Z,k(i,w),r.pick(i,D)))})),e}(t)}));n(" runLayout",(function(){!function(t,e){e(" makeSpaceForEdgeLabels",(function(){!function(t){var e=t.graph();e.ranksep/=2,r.forEach(t.edges(),(function(n){var r=t.edge(n);r.minlen*=2,"c"!==r.labelpos.toLowerCase()&&("TB"===e.rankdir||"BT"===e.rankdir?r.width+=r.labeloffset:r.height+=r.labeloffset)}))}(t)})),e(" removeSelfEdges",(function(){!function(t){r.forEach(t.edges(),(function(e){if(e.v===e.w){var n=t.node(e.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e,label:t.edge(e)}),t.removeEdge(e)}}))}(t)})),e(" acyclic",(function(){i.run(t)})),e(" nestingGraph.run",(function(){f.run(t)})),e(" rank",(function(){o(v.asNonCompoundGraph(t))})),e(" injectEdgeLabelProxies",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.width&&n.height){var r=t.node(e.v),i={rank:(t.node(e.w).rank-r.rank)/2+r.rank,e};v.addDummyNode(t,"edge-proxy",i,"_ep")}}))}(t)})),e(" removeEmptyRanks",(function(){c(t)})),e(" nestingGraph.cleanup",(function(){f.cleanup(t)})),e(" normalizeRanks",(function(){u(t)})),e(" assignRankMinMax",(function(){!function(t){var e=0;r.forEach(t.nodes(),(function(n){var i=t.node(n);i.borderTop&&(i.minRank=t.node(i.borderTop).rank,i.maxRank=t.node(i.borderBottom).rank,e=r.max(e,i.maxRank))})),t.graph().maxRank=e}(t)})),e(" removeEdgeLabelProxies",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);"edge-proxy"===n.dummy&&(t.edge(n.e).labelRank=n.rank,t.removeNode(e))}))}(t)})),e(" normalize.run",(function(){a.run(t)})),e(" parentDummyChains",(function(){s(t)})),e(" addBorderSegments",(function(){l(t)})),e(" order",(function(){d(t)})),e(" insertSelfEdges",(function(){!function(t){var e=v.buildLayerMatrix(t);r.forEach(e,(function(e){var n=0;r.forEach(e,(function(e,i){var a=t.node(e);a.order=i+n,r.forEach(a.selfEdges,(function(e){v.addDummyNode(t,"selfedge",{width:e.label.width,height:e.label.height,rank:a.rank,order:i+ ++n,e:e.e,label:e.label},"_se")})),delete a.selfEdges}))}))}(t)})),e(" adjustCoordinateSystem",(function(){h.adjust(t)})),e(" position",(function(){p(t)})),e(" positionSelfEdges",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);if("selfedge"===n.dummy){var r=t.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,u=r.height/2;t.setEdge(n.e,n.label),t.removeNode(e),n.label.points=[{x:i+2*o/3,y:a-u},{x:i+5*o/6,y:a-u},{x:i+o,y:a},{x:i+5*o/6,y:a+u},{x:i+2*o/3,y:a+u}],n.label.x=n.x,n.label.y=n.y}}))}(t)})),e(" removeBorderNodes",(function(){!function(t){r.forEach(t.nodes(),(function(e){if(t.children(e).length){var n=t.node(e),i=t.node(n.borderTop),a=t.node(n.borderBottom),o=t.node(r.last(n.borderLeft)),u=t.node(r.last(n.borderRight));n.width=Math.abs(u.x-o.x),n.height=Math.abs(a.y-i.y),n.x=o.x+n.width/2,n.y=i.y+n.height/2}})),r.forEach(t.nodes(),(function(e){"border"===t.node(e).dummy&&t.removeNode(e)}))}(t)})),e(" normalize.undo",(function(){a.undo(t)})),e(" fixupEdgeLabelCoords",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(r.has(n,"x"))switch("l"!==n.labelpos&&"r"!==n.labelpos||(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset}}))}(t)})),e(" undoCoordinateSystem",(function(){h.undo(t)})),e(" translateGraph",(function(){!function(t){var e=Number.POSITIVE_INFINITY,n=0,i=Number.POSITIVE_INFINITY,a=0,o=t.graph(),u=o.marginx||0,s=o.marginy||0;function c(t){var r=t.x,o=t.y,u=t.width,s=t.height;e=Math.min(e,r-u/2),n=Math.max(n,r+u/2),i=Math.min(i,o-s/2),a=Math.max(a,o+s/2)}r.forEach(t.nodes(),(function(e){c(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.has(n,"x")&&c(n)})),e-=u,i-=s,r.forEach(t.nodes(),(function(n){var r=t.node(n);r.x-=e,r.y-=i})),r.forEach(t.edges(),(function(n){var a=t.edge(n);r.forEach(a.points,(function(t){t.x-=e,t.y-=i})),r.has(a,"x")&&(a.x-=e),r.has(a,"y")&&(a.y-=i)})),o.width=n-e+u,o.height=a-i+s}(t)})),e(" assignNodeIntersects",(function(){!function(t){r.forEach(t.edges(),(function(e){var n,r,i=t.edge(e),a=t.node(e.v),o=t.node(e.w);i.points?(n=i.points[0],r=i.points[i.points.length-1]):(i.points=[],n=o,r=a),i.points.unshift(v.intersectRect(a,n)),i.points.push(v.intersectRect(o,r))}))}(t)})),e(" reversePoints",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);n.reversed&&n.points.reverse()}))}(t)})),e(" acyclic.undo",(function(){i.undo(t)}))}(e,n)})),n(" updateInputGraph",(function(){!function(t,e){r.forEach(t.nodes(),(function(n){var r=t.node(n),i=e.node(n);r&&(r.x=i.x,r.y=i.y,e.children(n).length&&(r.width=i.width,r.height=i.height))})),r.forEach(t.edges(),(function(n){var i=t.edge(n),a=e.edge(n);i.points=a.points,r.has(a,"x")&&(i.x=a.x,i.y=a.y)})),t.graph().width=e.graph().width,t.graph().height=e.graph().height}(t,e)}))}))};var _=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},y=["acyclicer","ranker","rankdir","align"],m=["width","height"],x={width:0,height:0},w=["minlen","weight","width","height","labeloffset"],Z={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},D=["labelpos"];function k(t,e){return r.mapValues(r.pick(t,e),Number)}function E(t){var e={};return r.forEach(t,(function(t,n){e[n.toLowerCase()]=t})),e}},43294:(t,e,n)=>{var r;try{r={cloneDeep:n(9850),constant:n(86874),defaults:n(84573),each:n(79421),filter:n(90882),find:n(55281),flatten:n(35676),forEach:n(59756),forIn:n(20792),has:n(93352),isUndefined:n(84336),last:n(56974),map:n(16760),mapValues:n(34519),max:n(71644),merge:n(98537),min:n(65680),minBy:n(10937),now:n(61100),pick:n(13888),range:n(2689),reduce:n(58215),sortBy:n(829),uniqueId:n(74930),values:n(98346),zipObject:n(46150)}}catch(t){}r||(r=window._),t.exports=r},96820:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n,o,u,s,c){var f=t.children(c);if(f.length){var l=i.addBorderNode(t,"_bt"),h=i.addBorderNode(t,"_bb"),d=t.node(c);t.setParent(l,c),d.borderTop=l,t.setParent(h,c),d.borderBottom=h,r.forEach(f,(function(r){a(t,e,n,o,u,s,r);var i=t.node(r),f=i.borderTop?i.borderTop:r,d=i.borderBottom?i.borderBottom:r,p=i.borderTop?o:2*o,v=f!==d?1:u-s[c]+1;t.setEdge(l,f,{weight:p,minlen:v,nestingEdge:!0}),t.setEdge(d,h,{weight:p,minlen:v,nestingEdge:!0})})),t.parent(c)||t.setEdge(e,l,{weight:0,minlen:u+s[c]})}else c!==e&&t.setEdge(e,c,{weight:0,minlen:n})}t.exports={run:function(t){var e=i.addDummyNode(t,"root",{},"_root"),n=function(t){var e={};function n(i,a){var o=t.children(i);o&&o.length&&r.forEach(o,(function(t){n(t,a+1)})),e[i]=a}return r.forEach(t.children(),(function(t){n(t,1)})),e}(t),o=r.max(r.values(n))-1,u=2*o+1;t.graph().nestingRoot=e,r.forEach(t.edges(),(function(e){t.edge(e).minlen*=u}));var s=function(t){return r.reduce(t.edges(),(function(e,n){return e+t.edge(n).weight}),0)}(t)+1;r.forEach(t.children(),(function(r){a(t,e,u,s,o,n,r)})),t.graph().nodeRankFactor=u},cleanup:function(t){var e=t.graph();t.removeNode(e.nestingRoot),delete e.nestingRoot,r.forEach(t.edges(),(function(e){t.edge(e).nestingEdge&&t.removeEdge(e)}))}}},20450:(t,e,n)=>{"use strict";var r=n(43294),i=n(8783);t.exports={run:function(t){t.graph().dummyChains=[],r.forEach(t.edges(),(function(e){!function(t,e){var n,r,a,o=e.v,u=t.node(o).rank,s=e.w,c=t.node(s).rank,f=e.name,l=t.edge(e),h=l.labelRank;if(c!==u+1){for(t.removeEdge(e),a=0,++u;u{var r=n(43294);t.exports=function(t,e,n){var i,a={};r.forEach(n,(function(n){for(var r,o,u=t.parent(n);u;){if((r=t.parent(u))?(o=a[r],a[r]=u):(o=i,i=u),o&&o!==u)return void e.setEdge(o,u);u=r}}))}},29533:(t,e,n)=>{var r=n(43294);t.exports=function(t,e){return r.map(e,(function(e){var n=t.inEdges(e);if(n.length){var i=r.reduce(n,(function(e,n){var r=t.edge(n),i=t.node(n.v);return{sum:e.sum+r.weight*i.order,weight:e.weight+r.weight}}),{sum:0,weight:0});return{v:e,barycenter:i.sum/i.weight,weight:i.weight}}return{v:e}}))}},64622:(t,e,n)=>{var r=n(43294),i=n(71310).Graph;t.exports=function(t,e,n){var a=function(t){for(var e;t.hasNode(e=r.uniqueId("_root")););return e}(t),o=new i({compound:!0}).setGraph({root:a}).setDefaultNodeLabel((function(e){return t.node(e)}));return r.forEach(t.nodes(),(function(i){var u=t.node(i),s=t.parent(i);(u.rank===e||u.minRank<=e&&e<=u.maxRank)&&(o.setNode(i),o.setParent(i,s||a),r.forEach(t[n](i),(function(e){var n=e.v===i?e.w:e.v,a=o.edge(n,i),u=r.isUndefined(a)?0:a.weight;o.setEdge(n,i,{weight:t.edge(e).weight+u})})),r.has(u,"minRank")&&o.setNode(i,{borderLeft:u.borderLeft[e],borderRight:u.borderRight[e]}))})),o}},6254:(t,e,n)=>{"use strict";var r=n(43294);function i(t,e,n){for(var i=r.zipObject(n,r.map(n,(function(t,e){return e}))),a=r.flatten(r.map(e,(function(e){return r.sortBy(r.map(t.outEdges(e),(function(e){return{pos:i[e.w],weight:t.edge(e).weight}})),"pos")})),!0),o=1;o0;)e%2&&(n+=s[e+1]),s[e=e-1>>1]+=t.weight;c+=t.weight*n}))),c}t.exports=function(t,e){for(var n=0,r=1;r{"use strict";var r=n(43294),i=n(65036),a=n(6254),o=n(83956),u=n(64622),s=n(47897),c=n(71310).Graph,f=n(8783);function l(t,e,n){return r.map(e,(function(e){return u(t,e,n)}))}function h(t,e){var n=new c;r.forEach(t,(function(t){var i=t.graph().root,a=o(t,i,n,e);r.forEach(a.vs,(function(e,n){t.node(e).order=n})),s(t,n,a.vs)}))}function d(t,e){r.forEach(e,(function(e){r.forEach(e,(function(e,n){t.node(e).order=n}))}))}t.exports=function(t){var e=f.maxRank(t),n=l(t,r.range(1,e+1),"inEdges"),o=l(t,r.range(e-1,-1,-1),"outEdges"),u=i(t);d(t,u);for(var s,c=Number.POSITIVE_INFINITY,p=0,v=0;v<4;++p,++v){h(p%2?n:o,p%4>=2),u=f.buildLayerMatrix(t);var g=a(t,u);g{"use strict";var r=n(43294);t.exports=function(t){var e={},n=r.filter(t.nodes(),(function(e){return!t.children(e).length})),i=r.max(r.map(n,(function(e){return t.node(e).rank}))),a=r.map(r.range(i+1),(function(){return[]})),o=r.sortBy(n,(function(e){return t.node(e).rank}));return r.forEach(o,(function n(i){if(!r.has(e,i)){e[i]=!0;var o=t.node(i);a[o.rank].push(i),r.forEach(t.successors(i),n)}})),a}},39953:(t,e,n)=>{"use strict";var r=n(43294);t.exports=function(t,e){var n={};return r.forEach(t,(function(t,e){var i=n[t.v]={indegree:0,in:[],out:[],vs:[t.v],i:e};r.isUndefined(t.barycenter)||(i.barycenter=t.barycenter,i.weight=t.weight)})),r.forEach(e.edges(),(function(t){var e=n[t.v],i=n[t.w];r.isUndefined(e)||r.isUndefined(i)||(i.indegree++,e.out.push(n[t.w]))})),function(t){var e=[];function n(t){return function(e){var n,i,a,o;e.merged||(r.isUndefined(e.barycenter)||r.isUndefined(t.barycenter)||e.barycenter>=t.barycenter)&&(i=e,a=0,o=0,(n=t).weight&&(a+=n.barycenter*n.weight,o+=n.weight),i.weight&&(a+=i.barycenter*i.weight,o+=i.weight),n.vs=i.vs.concat(n.vs),n.barycenter=a/o,n.weight=o,n.i=Math.min(i.i,n.i),i.merged=!0)}}function i(e){return function(n){n.in.push(e),0==--n.indegree&&t.push(n)}}for(;t.length;){var a=t.pop();e.push(a),r.forEach(a.in.reverse(),n(a)),r.forEach(a.out,i(a))}return r.map(r.filter(e,(function(t){return!t.merged})),(function(t){return r.pick(t,["vs","i","barycenter","weight"])}))}(r.filter(n,(function(t){return!t.indegree})))}},83956:(t,e,n)=>{var r=n(43294),i=n(29533),a=n(39953),o=n(11957);t.exports=function t(e,n,u,s){var c=e.children(n),f=e.node(n),l=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,d={};l&&(c=r.filter(c,(function(t){return t!==l&&t!==h})));var p=i(e,c);r.forEach(p,(function(n){if(e.children(n.v).length){var i=t(e,n.v,u,s);d[n.v]=i,r.has(i,"barycenter")&&(a=n,o=i,r.isUndefined(a.barycenter)?(a.barycenter=o.barycenter,a.weight=o.weight):(a.barycenter=(a.barycenter*a.weight+o.barycenter*o.weight)/(a.weight+o.weight),a.weight+=o.weight))}var a,o}));var v=a(p,u);!function(t,e){r.forEach(t,(function(t){t.vs=r.flatten(t.vs.map((function(t){return e[t]?e[t].vs:t})),!0)}))}(v,d);var g=o(v,s);if(l&&(g.vs=r.flatten([l,g.vs,h],!0),e.predecessors(l).length)){var _=e.node(e.predecessors(l)[0]),b=e.node(e.predecessors(h)[0]);r.has(g,"barycenter")||(g.barycenter=0,g.weight=0),g.barycenter=(g.barycenter*g.weight+_.order+b.order)/(g.weight+2),g.weight+=2}return g}},11957:(t,e,n)=>{var r=n(43294),i=n(8783);function a(t,e,n){for(var i;e.length&&(i=r.last(e)).i<=n;)e.pop(),t.push(i.vs),n++;return n}t.exports=function(t,e){var n,o=i.partition(t,(function(t){return r.has(t,"barycenter")})),u=o.lhs,s=r.sortBy(o.rhs,(function(t){return-t.i})),c=[],f=0,l=0,h=0;u.sort((n=!!e,function(t,e){return t.barycentere.barycenter?1:n?e.i-t.i:t.i-e.i})),h=a(c,s,h),r.forEach(u,(function(t){h+=t.vs.length,c.push(t.vs),f+=t.barycenter*t.weight,l+=t.weight,h=a(c,s,h)}));var d={vs:r.flatten(c,!0)};return l&&(d.barycenter=f/l,d.weight=l),d}},77908:(t,e,n)=>{var r=n(43294);t.exports=function(t){var e=function(t){var e={},n=0;return r.forEach(t.children(),(function i(a){var o=n;r.forEach(t.children(a),i),e[a]={low:o,lim:n++}})),e}(t);r.forEach(t.graph().dummyChains,(function(n){for(var r=t.node(n),i=r.edgeObj,a=function(t,e,n,r){var i,a,o=[],u=[],s=Math.min(e[n].low,e[r].low),c=Math.max(e[n].lim,e[r].lim);i=n;do{i=t.parent(i),o.push(i)}while(i&&(e[i].low>s||c>e[i].lim));for(a=i,i=r;(i=t.parent(i))!==a;)u.push(i);return{path:o.concat(u.reverse()),lca:a}}(t,e,i.v,i.w),o=a.path,u=a.lca,s=0,c=o[s],f=!0;n!==i.w;){if(r=t.node(n),f){for(;(c=o[s])!==u&&t.node(c).maxRank{"use strict";var r=n(43294),i=n(71310).Graph,a=n(8783);function o(t,e){var n={};return r.reduce(e,(function(e,i){var a=0,o=0,u=e.length,c=r.last(i);return r.forEach(i,(function(e,f){var l=function(t,e){if(t.node(e).dummy)return r.find(t.predecessors(e),(function(e){return t.node(e).dummy}))}(t,e),h=l?t.node(l).order:u;(l||e===c)&&(r.forEach(i.slice(o,f+1),(function(e){r.forEach(t.predecessors(e),(function(r){var i=t.node(r),o=i.order;!(ou)&&s(n,e,c)}))}))}return r.reduce(e,(function(e,n){var a,o=-1,u=0;return r.forEach(n,(function(r,s){if("border"===t.node(r).dummy){var c=t.predecessors(r);c.length&&(a=t.node(c[0]).order,i(n,u,s,o,a),u=s,o=a)}i(n,u,n.length,a,e.length)})),n})),n}function s(t,e,n){if(e>n){var r=e;e=n,n=r}var i=t[e];i||(t[e]=i={}),i[n]=!0}function c(t,e,n){if(e>n){var i=e;e=n,n=i}return r.has(t[e],n)}function f(t,e,n,i){var a={},o={},u={};return r.forEach(e,(function(t){r.forEach(t,(function(t,e){a[t]=t,o[t]=t,u[t]=e}))})),r.forEach(e,(function(t){var e=-1;r.forEach(t,(function(t){var s=i(t);if(s.length)for(var f=((s=r.sortBy(s,(function(t){return u[t]}))).length-1)/2,l=Math.floor(f),h=Math.ceil(f);l<=h;++l){var d=s[l];o[t]===t&&e{"use strict";var r=n(43294),i=n(8783),a=n(91753).positionX;t.exports=function(t){(function(t){var e=i.buildLayerMatrix(t),n=t.graph().ranksep,a=0;r.forEach(e,(function(e){var i=r.max(r.map(e,(function(e){return t.node(e).height})));r.forEach(e,(function(e){t.node(e).y=a+i/2})),a+=i+n}))})(t=i.asNonCompoundGraph(t)),r.forEach(a(t),(function(e,n){t.node(n).x=e}))}},49154:(t,e,n)=>{"use strict";var r=n(43294),i=n(71310).Graph,a=n(85986).slack;function o(t,e){return r.forEach(t.nodes(),(function n(i){r.forEach(e.nodeEdges(i),(function(r){var o=r.v,u=i===o?r.w:o;t.hasNode(u)||a(e,r)||(t.setNode(u,{}),t.setEdge(i,u,{}),n(u))}))})),t.nodeCount()}function u(t,e){return r.minBy(e.edges(),(function(n){if(t.hasNode(n.v)!==t.hasNode(n.w))return a(e,n)}))}function s(t,e,n){r.forEach(t.nodes(),(function(t){e.node(t).rank+=n}))}t.exports=function(t){var e,n,r=new i({directed:!1}),c=t.nodes()[0],f=t.nodeCount();for(r.setNode(c,{});o(r,t){"use strict";var r=n(85986).longestPath,i=n(49154),a=n(57310);t.exports=function(t){switch(t.graph().ranker){case"network-simplex":u(t);break;case"tight-tree":!function(t){r(t),i(t)}(t);break;case"longest-path":o(t);break;default:u(t)}};var o=r;function u(t){a(t)}},57310:(t,e,n)=>{"use strict";var r=n(43294),i=n(49154),a=n(85986).slack,o=n(85986).longestPath,u=n(71310).alg.preorder,s=n(71310).alg.postorder,c=n(8783).simplify;function f(t){t=c(t),o(t);var e,n=i(t);for(d(n),l(n,t);e=v(n);)_(n,t,e,g(n,t,e))}function l(t,e){var n=s(t,t.nodes());n=n.slice(0,n.length-1),r.forEach(n,(function(n){!function(t,e,n){var r=t.node(n).parent;t.edge(n,r).cutvalue=h(t,e,n)}(t,e,n)}))}function h(t,e,n){var i=t.node(n).parent,a=!0,o=e.edge(n,i),u=0;return o||(a=!1,o=e.edge(i,n)),u=o.weight,r.forEach(e.nodeEdges(n),(function(r){var o,s,c=r.v===n,f=c?r.w:r.v;if(f!==i){var l=c===a,h=e.edge(r).weight;if(u+=l?h:-h,o=n,s=f,t.hasEdge(o,s)){var d=t.edge(n,f).cutvalue;u+=l?-d:d}}})),u}function d(t,e){arguments.length<2&&(e=t.nodes()[0]),p(t,{},1,e)}function p(t,e,n,i,a){var o=n,u=t.node(i);return e[i]=!0,r.forEach(t.neighbors(i),(function(a){r.has(e,a)||(n=p(t,e,n,a,i))})),u.low=o,u.lim=n++,a?u.parent=a:delete u.parent,n}function v(t){return r.find(t.edges(),(function(e){return t.edge(e).cutvalue<0}))}function g(t,e,n){var i=n.v,o=n.w;e.hasEdge(i,o)||(i=n.w,o=n.v);var u=t.node(i),s=t.node(o),c=u,f=!1;u.lim>s.lim&&(c=s,f=!0);var l=r.filter(e.edges(),(function(e){return f===b(0,t.node(e.v),c)&&f!==b(0,t.node(e.w),c)}));return r.minBy(l,(function(t){return a(e,t)}))}function _(t,e,n,i){var a=n.v,o=n.w;t.removeEdge(a,o),t.setEdge(i.v,i.w,{}),d(t),l(t,e),function(t,e){var n=r.find(t.nodes(),(function(t){return!e.node(t).parent})),i=u(t,n);i=i.slice(1),r.forEach(i,(function(n){var r=t.node(n).parent,i=e.edge(n,r),a=!1;i||(i=e.edge(r,n),a=!0),e.node(n).rank=e.node(r).rank+(a?i.minlen:-i.minlen)}))}(t,e)}function b(t,e,n){return n.low<=e.lim&&e.lim<=n.lim}t.exports=f,f.initLowLimValues=d,f.initCutValues=l,f.calcCutValue=h,f.leaveEdge=v,f.enterEdge=g,f.exchangeEdges=_},85986:(t,e,n)=>{"use strict";var r=n(43294);t.exports={longestPath:function(t){var e={};r.forEach(t.sources(),(function n(i){var a=t.node(i);if(r.has(e,i))return a.rank;e[i]=!0;var o=r.min(r.map(t.outEdges(i),(function(e){return n(e.w)-t.edge(e).minlen})));return o!==Number.POSITIVE_INFINITY&&null!=o||(o=0),a.rank=o}))},slack:function(t,e){return t.node(e.w).rank-t.node(e.v).rank-t.edge(e).minlen}}},8783:(t,e,n)=>{"use strict";var r=n(43294),i=n(71310).Graph;function a(t,e,n,i){var a;do{a=r.uniqueId(i)}while(t.hasNode(a));return n.dummy=e,t.setNode(a,n),a}function o(t){return r.max(r.map(t.nodes(),(function(e){var n=t.node(e).rank;if(!r.isUndefined(n))return n})))}t.exports={addDummyNode:a,simplify:function(t){var e=(new i).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){var r=e.edge(n.v,n.w)||{weight:0,minlen:1},i=t.edge(n);e.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})})),e},asNonCompoundGraph:function(t){var e=new i({multigraph:t.isMultigraph()}).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){t.children(n).length||e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){e.setEdge(n,t.edge(n))})),e},successorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.outEdges(e),(function(e){n[e.w]=(n[e.w]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},predecessorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.inEdges(e),(function(e){n[e.v]=(n[e.v]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},intersectRect:function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,u=e.y-a,s=t.width/2,c=t.height/2;if(!o&&!u)throw new Error("Not possible to find intersection inside of the rectangle");return Math.abs(u)*s>Math.abs(o)*c?(u<0&&(c=-c),n=c*o/u,r=c):(o<0&&(s=-s),n=s,r=s*u/o),{x:i+n,y:a+r}},buildLayerMatrix:function(t){var e=r.map(r.range(o(t)+1),(function(){return[]}));return r.forEach(t.nodes(),(function(n){var i=t.node(n),a=i.rank;r.isUndefined(a)||(e[a][i.order]=n)})),e},normalizeRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank})));r.forEach(t.nodes(),(function(n){var i=t.node(n);r.has(i,"rank")&&(i.rank-=e)}))},removeEmptyRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank}))),n=[];r.forEach(t.nodes(),(function(r){var i=t.node(r).rank-e;n[i]||(n[i]=[]),n[i].push(r)}));var i=0,a=t.graph().nodeRankFactor;r.forEach(n,(function(e,n){r.isUndefined(e)&&n%a!=0?--i:i&&r.forEach(e,(function(e){t.node(e).rank+=i}))}))},addBorderNode:function(t,e,n,r){var i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),a(t,"border",i,e)},maxRank:o,partition:function(t,e){var n={lhs:[],rhs:[]};return r.forEach(t,(function(t){e(t)?n.lhs.push(t):n.rhs.push(t)})),n},time:function(t,e){var n=r.now();try{return e()}finally{console.log(t+" time: "+(r.now()-n)+"ms")}},notime:function(t,e){return e()}}},57589:t=>{t.exports="0.8.5"},87377:(t,e,n)=>{var r=n(89);t.exports={Graph:r.Graph,json:n(80109),alg:n(577),version:r.version}},95189:(t,e,n)=>{var r=n(60274);t.exports=function(t){var e,n={},i=[];function a(i){r.has(n,i)||(n[i]=!0,e.push(i),r.each(t.successors(i),a),r.each(t.predecessors(i),a))}return r.each(t.nodes(),(function(t){e=[],a(t),e.length&&i.push(e)})),i}},70223:(t,e,n)=>{var r=n(60274);function i(t,e,n,a,o,u){r.has(a,e)||(a[e]=!0,n||u.push(e),r.each(o(e),(function(e){i(t,e,n,a,o,u)})),n&&u.push(e))}t.exports=function(t,e,n){r.isArray(e)||(e=[e]);var a=(t.isDirected()?t.successors:t.neighbors).bind(t),o=[],u={};return r.each(e,(function(e){if(!t.hasNode(e))throw new Error("Graph does not have node: "+e);i(t,e,"post"===n,u,a,o)})),o}},19487:(t,e,n)=>{var r=n(16493),i=n(60274);t.exports=function(t,e,n){return i.transform(t.nodes(),(function(i,a){i[a]=r(t,a,e,n)}),{})}},16493:(t,e,n)=>{var r=n(60274),i=n(70905);t.exports=function(t,e,n,r){return function(t,e,n,r){var a,o,u={},s=new i,c=function(t){var e=t.v!==a?t.v:t.w,r=u[e],i=n(t),c=o.distance+i;if(i<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+t+" Weight: "+i);c0&&(a=s.removeMin(),(o=u[a]).distance!==Number.POSITIVE_INFINITY);)r(a).forEach(c);return u}(t,String(e),n||a,r||function(e){return t.outEdges(e)})};var a=r.constant(1)},24395:(t,e,n)=>{var r=n(60274),i=n(99289);t.exports=function(t){return r.filter(i(t),(function(e){return e.length>1||1===e.length&&t.hasEdge(e[0],e[0])}))}},92077:(t,e,n)=>{var r=n(60274);t.exports=function(t,e,n){return function(t,e,n){var r={},i=t.nodes();return i.forEach((function(t){r[t]={},r[t][t]={distance:0},i.forEach((function(e){t!==e&&(r[t][e]={distance:Number.POSITIVE_INFINITY})})),n(t).forEach((function(n){var i=n.v===t?n.w:n.v,a=e(n);r[t][i]={distance:a,predecessor:t}}))})),i.forEach((function(t){var e=r[t];i.forEach((function(n){var a=r[n];i.forEach((function(n){var r=a[t],i=e[n],o=a[n],u=r.distance+i.distance;u{t.exports={components:n(95189),dijkstra:n(16493),dijkstraAll:n(19487),findCycles:n(24395),floydWarshall:n(92077),isAcyclic:n(67141),postorder:n(53533),preorder:n(78852),prim:n(78492),tarjan:n(99289),topsort:n(69176)}},67141:(t,e,n)=>{var r=n(69176);t.exports=function(t){try{r(t)}catch(t){if(t instanceof r.CycleException)return!1;throw t}return!0}},53533:(t,e,n)=>{var r=n(70223);t.exports=function(t,e){return r(t,e,"post")}},78852:(t,e,n)=>{var r=n(70223);t.exports=function(t,e){return r(t,e,"pre")}},78492:(t,e,n)=>{var r=n(60274),i=n(53099),a=n(70905);t.exports=function(t,e){var n,o=new i,u={},s=new a;function c(t){var r=t.v===n?t.w:t.v,i=s.priority(r);if(void 0!==i){var a=e(t);a0;){if(n=s.removeMin(),r.has(u,n))o.setEdge(n,u[n]);else{if(f)throw new Error("Input graph is not connected: "+t);f=!0}t.nodeEdges(n).forEach(c)}return o}},99289:(t,e,n)=>{var r=n(60274);t.exports=function(t){var e=0,n=[],i={},a=[];function o(u){var s=i[u]={onStack:!0,lowlink:e,index:e++};if(n.push(u),t.successors(u).forEach((function(t){r.has(i,t)?i[t].onStack&&(s.lowlink=Math.min(s.lowlink,i[t].index)):(o(t),s.lowlink=Math.min(s.lowlink,i[t].lowlink))})),s.lowlink===s.index){var c,f=[];do{c=n.pop(),i[c].onStack=!1,f.push(c)}while(u!==c);a.push(f)}}return t.nodes().forEach((function(t){r.has(i,t)||o(t)})),a}},69176:(t,e,n)=>{var r=n(60274);function i(t){var e={},n={},i=[];if(r.each(t.sinks(),(function o(u){if(r.has(n,u))throw new a;r.has(e,u)||(n[u]=!0,e[u]=!0,r.each(t.predecessors(u),o),delete n[u],i.push(u))})),r.size(e)!==t.nodeCount())throw new a;return i}function a(){}t.exports=i,i.CycleException=a,a.prototype=new Error},70905:(t,e,n)=>{var r=n(60274);function i(){this._arr=[],this._keyIndices={}}t.exports=i,i.prototype.size=function(){return this._arr.length},i.prototype.keys=function(){return this._arr.map((function(t){return t.key}))},i.prototype.has=function(t){return r.has(this._keyIndices,t)},i.prototype.priority=function(t){var e=this._keyIndices[t];if(void 0!==e)return this._arr[e].priority},i.prototype.min=function(){if(0===this.size())throw new Error("Queue underflow");return this._arr[0].key},i.prototype.add=function(t,e){var n=this._keyIndices;if(t=String(t),!r.has(n,t)){var i=this._arr,a=i.length;return n[t]=a,i.push({key:t,priority:e}),this._decrease(a),!0}return!1},i.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var t=this._arr.pop();return delete this._keyIndices[t.key],this._heapify(0),t.key},i.prototype.decrease=function(t,e){var n=this._keyIndices[t];if(e>this._arr[n].priority)throw new Error("New priority is greater than current priority. Key: "+t+" Old: "+this._arr[n].priority+" New: "+e);this._arr[n].priority=e,this._decrease(n)},i.prototype._heapify=function(t){var e=this._arr,n=2*t,r=n+1,i=t;n>1].priority{"use strict";var r=n(60274);t.exports=a;var i="\0";function a(t){this._isDirected=!r.has(t,"directed")||t.directed,this._isMultigraph=!!r.has(t,"multigraph")&&t.multigraph,this._isCompound=!!r.has(t,"compound")&&t.compound,this._label=void 0,this._defaultNodeLabelFn=r.constant(void 0),this._defaultEdgeLabelFn=r.constant(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children["\0"]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}function o(t,e){t[e]?t[e]++:t[e]=1}function u(t,e){--t[e]||delete t[e]}function s(t,e,n,i){var a=""+e,o=""+n;if(!t&&a>o){var u=a;a=o,o=u}return a+""+o+""+(r.isUndefined(i)?"\0":i)}function c(t,e,n,r){var i=""+e,a=""+n;if(!t&&i>a){var o=i;i=a,a=o}var u={v:i,w:a};return r&&(u.name=r),u}function f(t,e){return s(t,e.v,e.w,e.name)}a.prototype._nodeCount=0,a.prototype._edgeCount=0,a.prototype.isDirected=function(){return this._isDirected},a.prototype.isMultigraph=function(){return this._isMultigraph},a.prototype.isCompound=function(){return this._isCompound},a.prototype.setGraph=function(t){return this._label=t,this},a.prototype.graph=function(){return this._label},a.prototype.setDefaultNodeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultNodeLabelFn=t,this},a.prototype.nodeCount=function(){return this._nodeCount},a.prototype.nodes=function(){return r.keys(this._nodes)},a.prototype.sources=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._in[e])}))},a.prototype.sinks=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._out[e])}))},a.prototype.setNodes=function(t,e){var n=arguments,i=this;return r.each(t,(function(t){n.length>1?i.setNode(t,e):i.setNode(t)})),this},a.prototype.setNode=function(t,e){return r.has(this._nodes,t)?(arguments.length>1&&(this._nodes[t]=e),this):(this._nodes[t]=arguments.length>1?e:this._defaultNodeLabelFn(t),this._isCompound&&(this._parent[t]=i,this._children[t]={},this._children["\0"][t]=!0),this._in[t]={},this._preds[t]={},this._out[t]={},this._sucs[t]={},++this._nodeCount,this)},a.prototype.node=function(t){return this._nodes[t]},a.prototype.hasNode=function(t){return r.has(this._nodes,t)},a.prototype.removeNode=function(t){var e=this;if(r.has(this._nodes,t)){var n=function(t){e.removeEdge(e._edgeObjs[t])};delete this._nodes[t],this._isCompound&&(this._removeFromParentsChildList(t),delete this._parent[t],r.each(this.children(t),(function(t){e.setParent(t)})),delete this._children[t]),r.each(r.keys(this._in[t]),n),delete this._in[t],delete this._preds[t],r.each(r.keys(this._out[t]),n),delete this._out[t],delete this._sucs[t],--this._nodeCount}return this},a.prototype.setParent=function(t,e){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(r.isUndefined(e))e=i;else{for(var n=e+="";!r.isUndefined(n);n=this.parent(n))if(n===t)throw new Error("Setting "+e+" as parent of "+t+" would create a cycle");this.setNode(e)}return this.setNode(t),this._removeFromParentsChildList(t),this._parent[t]=e,this._children[e][t]=!0,this},a.prototype._removeFromParentsChildList=function(t){delete this._children[this._parent[t]][t]},a.prototype.parent=function(t){if(this._isCompound){var e=this._parent[t];if(e!==i)return e}},a.prototype.children=function(t){if(r.isUndefined(t)&&(t=i),this._isCompound){var e=this._children[t];if(e)return r.keys(e)}else{if(t===i)return this.nodes();if(this.hasNode(t))return[]}},a.prototype.predecessors=function(t){var e=this._preds[t];if(e)return r.keys(e)},a.prototype.successors=function(t){var e=this._sucs[t];if(e)return r.keys(e)},a.prototype.neighbors=function(t){var e=this.predecessors(t);if(e)return r.union(e,this.successors(t))},a.prototype.isLeaf=function(t){return 0===(this.isDirected()?this.successors(t):this.neighbors(t)).length},a.prototype.filterNodes=function(t){var e=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});e.setGraph(this.graph());var n=this;r.each(this._nodes,(function(n,r){t(r)&&e.setNode(r,n)})),r.each(this._edgeObjs,(function(t){e.hasNode(t.v)&&e.hasNode(t.w)&&e.setEdge(t,n.edge(t))}));var i={};function a(t){var r=n.parent(t);return void 0===r||e.hasNode(r)?(i[t]=r,r):r in i?i[r]:a(r)}return this._isCompound&&r.each(e.nodes(),(function(t){e.setParent(t,a(t))})),e},a.prototype.setDefaultEdgeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultEdgeLabelFn=t,this},a.prototype.edgeCount=function(){return this._edgeCount},a.prototype.edges=function(){return r.values(this._edgeObjs)},a.prototype.setPath=function(t,e){var n=this,i=arguments;return r.reduce(t,(function(t,r){return i.length>1?n.setEdge(t,r,e):n.setEdge(t,r),r})),this},a.prototype.setEdge=function(){var t,e,n,i,a=!1,u=arguments[0];"object"==typeof u&&null!==u&&"v"in u?(t=u.v,e=u.w,n=u.name,2===arguments.length&&(i=arguments[1],a=!0)):(t=u,e=arguments[1],n=arguments[3],arguments.length>2&&(i=arguments[2],a=!0)),t=""+t,e=""+e,r.isUndefined(n)||(n=""+n);var f=s(this._isDirected,t,e,n);if(r.has(this._edgeLabels,f))return a&&(this._edgeLabels[f]=i),this;if(!r.isUndefined(n)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(t),this.setNode(e),this._edgeLabels[f]=a?i:this._defaultEdgeLabelFn(t,e,n);var l=c(this._isDirected,t,e,n);return t=l.v,e=l.w,Object.freeze(l),this._edgeObjs[f]=l,o(this._preds[e],t),o(this._sucs[t],e),this._in[e][f]=l,this._out[t][f]=l,this._edgeCount++,this},a.prototype.edge=function(t,e,n){var r=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n);return this._edgeLabels[r]},a.prototype.hasEdge=function(t,e,n){var i=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n);return r.has(this._edgeLabels,i)},a.prototype.removeEdge=function(t,e,n){var r=1===arguments.length?f(this._isDirected,arguments[0]):s(this._isDirected,t,e,n),i=this._edgeObjs[r];return i&&(t=i.v,e=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],u(this._preds[e],t),u(this._sucs[t],e),delete this._in[e][r],delete this._out[t][r],this._edgeCount--),this},a.prototype.inEdges=function(t,e){var n=this._in[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.v===e})):i}},a.prototype.outEdges=function(t,e){var n=this._out[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.w===e})):i}},a.prototype.nodeEdges=function(t,e){var n=this.inEdges(t,e);if(n)return n.concat(this.outEdges(t,e))}},89:(t,e,n)=>{t.exports={Graph:n(53099),version:n(90702)}},80109:(t,e,n)=>{var r=n(60274),i=n(53099);function a(t){return r.map(t.nodes(),(function(e){var n=t.node(e),i=t.parent(e),a={v:e};return r.isUndefined(n)||(a.value=n),r.isUndefined(i)||(a.parent=i),a}))}function o(t){return r.map(t.edges(),(function(e){var n=t.edge(e),i={v:e.v,w:e.w};return r.isUndefined(e.name)||(i.name=e.name),r.isUndefined(n)||(i.value=n),i}))}t.exports={write:function(t){var e={options:{directed:t.isDirected(),multigraph:t.isMultigraph(),compound:t.isCompound()},nodes:a(t),edges:o(t)};return r.isUndefined(t.graph())||(e.value=r.clone(t.graph())),e},read:function(t){var e=new i(t.options).setGraph(t.value);return r.each(t.nodes,(function(t){e.setNode(t.v,t.value),t.parent&&e.setParent(t.v,t.parent)})),r.each(t.edges,(function(t){e.setEdge({v:t.v,w:t.w,name:t.name},t.value)})),e}}},60274:(t,e,n)=>{var r;try{r={clone:n(54004),constant:n(86874),each:n(79421),filter:n(90882),has:n(93352),isArray:n(86152),isEmpty:n(45455),isFunction:n(61049),isUndefined:n(84336),keys:n(90249),map:n(16760),reduce:n(58215),size:n(36402),transform:n(89466),union:n(26139),values:n(98346)}}catch(t){}r||(r=window._),t.exports=r},90702:t=>{t.exports="2.1.8"},39515:(t,e,n)=>{var r=n(38761)(n(37772),"DataView");t.exports=r},89612:(t,e,n)=>{var r=n(52118),i=n(96909),a=n(98138),o=n(4174),u=n(7942);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(3945),i=n(21846),a=n(88028),o=n(72344),u=n(94769);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(38761)(n(37772),"Map");t.exports=r},96738:(t,e,n)=>{var r=n(92411),i=n(36417),a=n(86928),o=n(18052),u=n(24150);function s(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e{var r=n(38761)(n(37772),"Promise");t.exports=r},2143:(t,e,n)=>{var r=n(38761)(n(37772),"Set");t.exports=r},45386:(t,e,n)=>{var r=n(96738),i=n(52842),a=n(52482);function o(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new r;++e{var r=n(80235),i=n(15243),a=n(72858),o=n(4417),u=n(8605),s=n(71418);function c(t){var e=this.__data__=new r(t);this.size=e.size}c.prototype.clear=i,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=u,c.prototype.set=s,t.exports=c},50857:(t,e,n)=>{var r=n(37772).Symbol;t.exports=r},79162:(t,e,n)=>{var r=n(37772).Uint8Array;t.exports=r},93215:(t,e,n)=>{var r=n(38761)(n(37772),"WeakMap");t.exports=r},49432:t=>{t.exports=function(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}},72517:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=0,a=[];++n{var r=n(77832);t.exports=function(t,e){return!(null==t||!t.length)&&r(t,e,0)>-1}},34893:t=>{t.exports=function(t,e,n){for(var r=-1,i=null==t?0:t.length;++r{var r=n(36473),i=n(79631),a=n(86152),o=n(73226),u=n(39045),s=n(77598),c=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=a(t),f=!n&&i(t),l=!n&&!f&&o(t),h=!n&&!f&&!l&&s(t),d=n||f||l||h,p=d?r(t.length,String):[],v=p.length;for(var g in t)!e&&!c.call(t,g)||d&&("length"==g||l&&("offset"==g||"parent"==g)||h&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||u(g,v))||p.push(g);return p}},50343:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n{t.exports=function(t,e){for(var n=-1,r=e.length,i=t.length;++n{t.exports=function(t,e,n,r){var i=-1,a=null==t?0:t.length;for(r&&a&&(n=t[++i]);++i{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n{var r=n(20256)("length");t.exports=r},28582:(t,e,n)=>{var r=n(13940),i=n(41225);t.exports=function(t,e,n){(void 0!==n&&!i(t[e],n)||void 0===n&&!(e in t))&&r(t,e,n)}},60091:(t,e,n)=>{var r=n(13940),i=n(41225),a=Object.prototype.hasOwnProperty;t.exports=function(t,e,n){var o=t[e];a.call(t,e)&&i(o,n)&&(void 0!==n||e in t)||r(t,e,n)}},22218:(t,e,n)=>{var r=n(41225);t.exports=function(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return-1}},67993:(t,e,n)=>{var r=n(752),i=n(90249);t.exports=function(t,e){return t&&r(e,i(e),t)}},55906:(t,e,n)=>{var r=n(752),i=n(18582);t.exports=function(t,e){return t&&r(e,i(e),t)}},13940:(t,e,n)=>{var r=n(83043);t.exports=function(t,e,n){"__proto__"==e&&r?r(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}},18874:(t,e,n)=>{var r=n(86571),i=n(72517),a=n(60091),o=n(67993),u=n(55906),s=n(92175),c=n(51522),f=n(7680),l=n(19987),h=n(13483),d=n(76939),p=n(70940),v=n(99917),g=n(8222),_=n(78725),b=n(86152),y=n(73226),m=n(4714),x=n(29259),w=n(43679),Z=n(90249),D=n(18582),k="[object Arguments]",E="[object Function]",A="[object Object]",j={};j[k]=j["[object Array]"]=j["[object ArrayBuffer]"]=j["[object DataView]"]=j["[object Boolean]"]=j["[object Date]"]=j["[object Float32Array]"]=j["[object Float64Array]"]=j["[object Int8Array]"]=j["[object Int16Array]"]=j["[object Int32Array]"]=j["[object Map]"]=j["[object Number]"]=j[A]=j["[object RegExp]"]=j["[object Set]"]=j["[object String]"]=j["[object Symbol]"]=j["[object Uint8Array]"]=j["[object Uint8ClampedArray]"]=j["[object Uint16Array]"]=j["[object Uint32Array]"]=!0,j["[object Error]"]=j[E]=j["[object WeakMap]"]=!1,t.exports=function t(e,n,C,M,F,B){var S,N=1&n,T=2&n,z=4&n;if(C&&(S=F?C(e,M,F,B):C(e)),void 0!==S)return S;if(!x(e))return e;var O=b(e);if(O){if(S=v(e),!N)return c(e,S)}else{var R=p(e),P=R==E||"[object GeneratorFunction]"==R;if(y(e))return s(e,N);if(R==A||R==k||P&&!F){if(S=T||P?{}:_(e),!N)return T?l(e,u(S,e)):f(e,o(S,e))}else{if(!j[R])return F?e:{};S=g(e,R,N)}}B||(B=new r);var I=B.get(e);if(I)return I;B.set(e,S),w(e)?e.forEach((function(r){S.add(t(r,n,C,r,e,B))})):m(e)&&e.forEach((function(r,i){S.set(i,t(r,n,C,i,e,B))}));var L=O?void 0:(z?T?d:h:T?D:Z)(e);return i(L||e,(function(r,i){L&&(r=e[i=r]),a(S,i,t(r,n,C,i,e,B))})),S}},39413:(t,e,n)=>{var r=n(29259),i=Object.create,a=function(){function t(){}return function(e){if(!r(e))return{};if(i)return i(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();t.exports=a},24303:(t,e,n)=>{var r=n(26548),i=n(92019)(r);t.exports=i},2229:(t,e,n)=>{var r=n(4795);t.exports=function(t,e,n){for(var i=-1,a=t.length;++i{var r=n(24303);t.exports=function(t,e){var n=[];return r(t,(function(t,r,i){e(t,r,i)&&n.push(t)})),n}},21359:t=>{t.exports=function(t,e,n,r){for(var i=t.length,a=n+(r?1:-1);r?a--:++a{var r=n(65067),i=n(95882);t.exports=function t(e,n,a,o,u){var s=-1,c=e.length;for(a||(a=i),u||(u=[]);++s0&&a(f)?n>1?t(f,n-1,a,o,u):r(u,f):o||(u[u.length]=f)}return u}},15308:(t,e,n)=>{var r=n(55463)();t.exports=r},26548:(t,e,n)=>{var r=n(15308),i=n(90249);t.exports=function(t,e){return t&&r(t,e,i)}},13324:(t,e,n)=>{var r=n(17297),i=n(33812);t.exports=function(t,e){for(var n=0,a=(e=r(e,t)).length;null!=t&&n{var r=n(65067),i=n(86152);t.exports=function(t,e,n){var a=e(t);return i(t)?a:r(a,n(t))}},53366:(t,e,n)=>{var r=n(50857),i=n(62107),a=n(37157),o=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":o&&o in Object(t)?i(t):a(t)}},84134:t=>{t.exports=function(t,e){return t>e}},32726:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t,n){return null!=t&&e.call(t,n)}},20187:t=>{t.exports=function(t,e){return null!=t&&e in Object(t)}},77832:(t,e,n)=>{var r=n(21359),i=n(22195),a=n(66024);t.exports=function(t,e,n){return e==e?a(t,e,n):r(t,i,n)}},15183:(t,e,n)=>{var r=n(53366),i=n(15125);t.exports=function(t){return i(t)&&"[object Arguments]"==r(t)}},88746:(t,e,n)=>{var r=n(51952),i=n(15125);t.exports=function t(e,n,a,o,u){return e===n||(null==e||null==n||!i(e)&&!i(n)?e!=e&&n!=n:r(e,n,a,o,t,u))}},51952:(t,e,n)=>{var r=n(86571),i=n(74871),a=n(8703),o=n(17416),u=n(70940),s=n(86152),c=n(73226),f=n(77598),l="[object Arguments]",h="[object Array]",d="[object Object]",p=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,v,g,_){var b=s(t),y=s(e),m=b?h:u(t),x=y?h:u(e),w=(m=m==l?d:m)==d,Z=(x=x==l?d:x)==d,D=m==x;if(D&&c(t)){if(!c(e))return!1;b=!0,w=!1}if(D&&!w)return _||(_=new r),b||f(t)?i(t,e,n,v,g,_):a(t,e,m,n,v,g,_);if(!(1&n)){var k=w&&p.call(t,"__wrapped__"),E=Z&&p.call(e,"__wrapped__");if(k||E){var A=k?t.value():t,j=E?e.value():e;return _||(_=new r),g(A,j,n,v,_)}}return!!D&&(_||(_=new r),o(t,e,n,v,g,_))}},74511:(t,e,n)=>{var r=n(70940),i=n(15125);t.exports=function(t){return i(t)&&"[object Map]"==r(t)}},37036:(t,e,n)=>{var r=n(86571),i=n(88746);t.exports=function(t,e,n,a){var o=n.length,u=o,s=!a;if(null==t)return!u;for(t=Object(t);o--;){var c=n[o];if(s&&c[2]?c[1]!==t[c[0]]:!(c[0]in t))return!1}for(;++o{t.exports=function(t){return t!=t}},6840:(t,e,n)=>{var r=n(61049),i=n(47394),a=n(29259),o=n(87035),u=/^\[object .+?Constructor\]$/,s=Function.prototype,c=Object.prototype,f=s.toString,l=c.hasOwnProperty,h=RegExp("^"+f.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!a(t)||i(t))&&(r(t)?h:u).test(o(t))}},8109:(t,e,n)=>{var r=n(70940),i=n(15125);t.exports=function(t){return i(t)&&"[object Set]"==r(t)}},35522:(t,e,n)=>{var r=n(53366),i=n(61158),a=n(15125),o={};o["[object Float32Array]"]=o["[object Float64Array]"]=o["[object Int8Array]"]=o["[object Int16Array]"]=o["[object Int32Array]"]=o["[object Uint8Array]"]=o["[object Uint8ClampedArray]"]=o["[object Uint16Array]"]=o["[object Uint32Array]"]=!0,o["[object Arguments]"]=o["[object Array]"]=o["[object ArrayBuffer]"]=o["[object Boolean]"]=o["[object DataView]"]=o["[object Date]"]=o["[object Error]"]=o["[object Function]"]=o["[object Map]"]=o["[object Number]"]=o["[object Object]"]=o["[object RegExp]"]=o["[object Set]"]=o["[object String]"]=o["[object WeakMap]"]=!1,t.exports=function(t){return a(t)&&i(t.length)&&!!o[r(t)]}},68286:(t,e,n)=>{var r=n(26423),i=n(74716),a=n(23059),o=n(86152),u=n(65798);t.exports=function(t){return"function"==typeof t?t:null==t?a:"object"==typeof t?o(t)?i(t[0],t[1]):r(t):u(t)}},86411:(t,e,n)=>{var r=n(16001),i=n(54248),a=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return i(t);var e=[];for(var n in Object(t))a.call(t,n)&&"constructor"!=n&&e.push(n);return e}},18390:(t,e,n)=>{var r=n(29259),i=n(16001),a=n(62966),o=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return a(t);var e=i(t),n=[];for(var u in t)("constructor"!=u||!e&&o.call(t,u))&&n.push(u);return n}},17606:t=>{t.exports=function(t,e){return t{var r=n(24303),i=n(67878);t.exports=function(t,e){var n=-1,a=i(t)?Array(t.length):[];return r(t,(function(t,r,i){a[++n]=e(t,r,i)})),a}},26423:(t,e,n)=>{var r=n(37036),i=n(49882),a=n(73477);t.exports=function(t){var e=i(t);return 1==e.length&&e[0][2]?a(e[0][0],e[0][1]):function(n){return n===t||r(n,t,e)}}},74716:(t,e,n)=>{var r=n(88746),i=n(72579),a=n(95041),o=n(21401),u=n(28792),s=n(73477),c=n(33812);t.exports=function(t,e){return o(t)&&u(e)?s(c(t),e):function(n){var o=i(n,t);return void 0===o&&o===e?a(n,t):r(e,o,3)}}},84565:(t,e,n)=>{var r=n(86571),i=n(28582),a=n(15308),o=n(25561),u=n(29259),s=n(18582),c=n(52434);t.exports=function t(e,n,f,l,h){e!==n&&a(n,(function(a,s){if(h||(h=new r),u(a))o(e,n,s,f,t,l,h);else{var d=l?l(c(e,s),a,s+"",e,n,h):void 0;void 0===d&&(d=a),i(e,s,d)}}),s)}},25561:(t,e,n)=>{var r=n(28582),i=n(92175),a=n(6190),o=n(51522),u=n(78725),s=n(79631),c=n(86152),f=n(93746),l=n(73226),h=n(61049),d=n(29259),p=n(97030),v=n(77598),g=n(52434),_=n(63329);t.exports=function(t,e,n,b,y,m,x){var w=g(t,n),Z=g(e,n),D=x.get(Z);if(D)r(t,n,D);else{var k=m?m(w,Z,n+"",t,e,x):void 0,E=void 0===k;if(E){var A=c(Z),j=!A&&l(Z),C=!A&&!j&&v(Z);k=Z,A||j||C?c(w)?k=w:f(w)?k=o(w):j?(E=!1,k=i(Z,!0)):C?(E=!1,k=a(Z,!0)):k=[]:p(Z)||s(Z)?(k=w,s(w)?k=_(w):d(w)&&!h(w)||(k=u(Z))):E=!1}E&&(x.set(Z,k),y(k,Z,b,m,x),x.delete(Z)),r(t,n,k)}}},23813:(t,e,n)=>{var r=n(50343),i=n(13324),a=n(68286),o=n(93401),u=n(27095),s=n(47826),c=n(18477),f=n(23059),l=n(86152);t.exports=function(t,e,n){e=e.length?r(e,(function(t){return l(t)?function(e){return i(e,1===t.length?t[0]:t)}:t})):[f];var h=-1;e=r(e,s(a));var d=o(t,(function(t,n,i){return{criteria:r(e,(function(e){return e(t)})),index:++h,value:t}}));return u(d,(function(t,e){return c(t,e,n)}))}},92602:(t,e,n)=>{var r=n(93759),i=n(95041);t.exports=function(t,e){return r(t,e,(function(e,n){return i(t,n)}))}},93759:(t,e,n)=>{var r=n(13324),i=n(82857),a=n(17297);t.exports=function(t,e,n){for(var o=-1,u=e.length,s={};++o{t.exports=function(t){return function(e){return null==e?void 0:e[t]}}},82952:(t,e,n)=>{var r=n(13324);t.exports=function(t){return function(e){return r(e,t)}}},93228:t=>{var e=Math.ceil,n=Math.max;t.exports=function(t,r,i,a){for(var o=-1,u=n(e((r-t)/(i||1)),0),s=Array(u);u--;)s[a?u:++o]=t,t+=i;return s}},5877:t=>{t.exports=function(t,e,n,r,i){return i(t,(function(t,i,a){n=r?(r=!1,t):e(n,t,i,a)})),n}},36060:(t,e,n)=>{var r=n(23059),i=n(43114),a=n(75251);t.exports=function(t,e){return a(i(t,e,r),t+"")}},82857:(t,e,n)=>{var r=n(60091),i=n(17297),a=n(39045),o=n(29259),u=n(33812);t.exports=function(t,e,n,s){if(!o(t))return t;for(var c=-1,f=(e=i(e,t)).length,l=f-1,h=t;null!=h&&++c{var r=n(86874),i=n(83043),a=n(23059),o=i?function(t,e){return i(t,"toString",{configurable:!0,enumerable:!1,value:r(e),writable:!0})}:a;t.exports=o},27095:t=>{t.exports=function(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}},36473:t=>{t.exports=function(t,e){for(var n=-1,r=Array(t);++n{var r=n(50857),i=n(50343),a=n(86152),o=n(4795),u=r?r.prototype:void 0,s=u?u.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(a(e))return i(e,t)+"";if(o(e))return s?s.call(e):"";var n=e+"";return"0"==n&&1/e==-1/0?"-0":n}},51704:(t,e,n)=>{var r=n(52153),i=/^\s+/;t.exports=function(t){return t?t.slice(0,r(t)+1).replace(i,""):t}},47826:t=>{t.exports=function(t){return function(e){return t(e)}}},67326:(t,e,n)=>{var r=n(45386),i=n(38333),a=n(34893),o=n(59950),u=n(78803),s=n(16909);t.exports=function(t,e,n){var c=-1,f=i,l=t.length,h=!0,d=[],p=d;if(n)h=!1,f=a;else if(l>=200){var v=e?null:u(t);if(v)return s(v);h=!1,f=o,p=new r}else p=e?[]:d;t:for(;++c{var r=n(50343);t.exports=function(t,e){return r(e,(function(e){return t[e]}))}},40509:t=>{t.exports=function(t,e,n){for(var r=-1,i=t.length,a=e.length,o={};++r{t.exports=function(t,e){return t.has(e)}},89419:(t,e,n)=>{var r=n(23059);t.exports=function(t){return"function"==typeof t?t:r}},17297:(t,e,n)=>{var r=n(86152),i=n(21401),a=n(54452),o=n(66188);t.exports=function(t,e){return r(t)?t:i(t,e)?[t]:a(o(t))}},79882:(t,e,n)=>{var r=n(79162);t.exports=function(t){var e=new t.constructor(t.byteLength);return new r(e).set(new r(t)),e}},92175:(t,e,n)=>{t=n.nmd(t);var r=n(37772),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i?r.Buffer:void 0,u=o?o.allocUnsafe:void 0;t.exports=function(t,e){if(e)return t.slice();var n=t.length,r=u?u(n):new t.constructor(n);return t.copy(r),r}},34727:(t,e,n)=>{var r=n(79882);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}},96058:t=>{var e=/\w*$/;t.exports=function(t){var n=new t.constructor(t.source,e.exec(t));return n.lastIndex=t.lastIndex,n}},70169:(t,e,n)=>{var r=n(50857),i=r?r.prototype:void 0,a=i?i.valueOf:void 0;t.exports=function(t){return a?Object(a.call(t)):{}}},6190:(t,e,n)=>{var r=n(79882);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}},27520:(t,e,n)=>{var r=n(4795);t.exports=function(t,e){if(t!==e){var n=void 0!==t,i=null===t,a=t==t,o=r(t),u=void 0!==e,s=null===e,c=e==e,f=r(e);if(!s&&!f&&!o&&t>e||o&&u&&c&&!s&&!f||i&&u&&c||!n&&c||!a)return 1;if(!i&&!o&&!f&&t{var r=n(27520);t.exports=function(t,e,n){for(var i=-1,a=t.criteria,o=e.criteria,u=a.length,s=n.length;++i=s?c:c*("desc"==n[i]?-1:1)}return t.index-e.index}},51522:t=>{t.exports=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n{var r=n(60091),i=n(13940);t.exports=function(t,e,n,a){var o=!n;n||(n={});for(var u=-1,s=e.length;++u{var r=n(752),i=n(80633);t.exports=function(t,e){return r(t,i(t),e)}},19987:(t,e,n)=>{var r=n(752),i=n(12680);t.exports=function(t,e){return r(t,i(t),e)}},24019:(t,e,n)=>{var r=n(37772)["__core-js_shared__"];t.exports=r},97263:(t,e,n)=>{var r=n(36060),i=n(82406);t.exports=function(t){return r((function(e,n){var r=-1,a=n.length,o=a>1?n[a-1]:void 0,u=a>2?n[2]:void 0;for(o=t.length>3&&"function"==typeof o?(a--,o):void 0,u&&i(n[0],n[1],u)&&(o=a<3?void 0:o,a=1),e=Object(e);++r{var r=n(67878);t.exports=function(t,e){return function(n,i){if(null==n)return n;if(!r(n))return t(n,i);for(var a=n.length,o=e?a:-1,u=Object(n);(e?o--:++o{t.exports=function(t){return function(e,n,r){for(var i=-1,a=Object(e),o=r(e),u=o.length;u--;){var s=o[t?u:++i];if(!1===n(a[s],s,a))break}return e}}},98776:(t,e,n)=>{var r=n(68286),i=n(67878),a=n(90249);t.exports=function(t){return function(e,n,o){var u=Object(e);if(!i(e)){var s=r(n,3);e=a(e),n=function(t){return s(u[t],t,u)}}var c=t(e,n,o);return c>-1?u[s?e[c]:c]:void 0}}},82941:(t,e,n)=>{var r=n(93228),i=n(82406),a=n(5707);t.exports=function(t){return function(e,n,o){return o&&"number"!=typeof o&&i(e,n,o)&&(n=o=void 0),e=a(e),void 0===n?(n=e,e=0):n=a(n),o=void 0===o?e{var r=n(2143),i=n(34291),a=n(16909),o=r&&1/a(new r([,-0]))[1]==1/0?function(t){return new r(t)}:i;t.exports=o},83043:(t,e,n)=>{var r=n(38761),i=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=i},74871:(t,e,n)=>{var r=n(45386),i=n(87064),a=n(59950);t.exports=function(t,e,n,o,u,s){var c=1&n,f=t.length,l=e.length;if(f!=l&&!(c&&l>f))return!1;var h=s.get(t),d=s.get(e);if(h&&d)return h==e&&d==t;var p=-1,v=!0,g=2&n?new r:void 0;for(s.set(t,e),s.set(e,t);++p{var r=n(50857),i=n(79162),a=n(41225),o=n(74871),u=n(75179),s=n(16909),c=r?r.prototype:void 0,f=c?c.valueOf:void 0;t.exports=function(t,e,n,r,c,l,h){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return!(t.byteLength!=e.byteLength||!l(new i(t),new i(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return a(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var d=u;case"[object Set]":var p=1&r;if(d||(d=s),t.size!=e.size&&!p)return!1;var v=h.get(t);if(v)return v==e;r|=2,h.set(t,e);var g=o(d(t),d(e),r,c,l,h);return h.delete(t),g;case"[object Symbol]":if(f)return f.call(t)==f.call(e)}return!1}},17416:(t,e,n)=>{var r=n(13483),i=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,a,o,u){var s=1&n,c=r(t),f=c.length;if(f!=r(e).length&&!s)return!1;for(var l=f;l--;){var h=c[l];if(!(s?h in e:i.call(e,h)))return!1}var d=u.get(t),p=u.get(e);if(d&&p)return d==e&&p==t;var v=!0;u.set(t,e),u.set(e,t);for(var g=s;++l{var r=n(35676),i=n(43114),a=n(75251);t.exports=function(t){return a(i(t,void 0,r),t+"")}},51242:(t,e,n)=>{var r="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;t.exports=r},13483:(t,e,n)=>{var r=n(1897),i=n(80633),a=n(90249);t.exports=function(t){return r(t,a,i)}},76939:(t,e,n)=>{var r=n(1897),i=n(12680),a=n(18582);t.exports=function(t){return r(t,a,i)}},27937:(t,e,n)=>{var r=n(98304);t.exports=function(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map}},49882:(t,e,n)=>{var r=n(28792),i=n(90249);t.exports=function(t){for(var e=i(t),n=e.length;n--;){var a=e[n],o=t[a];e[n]=[a,o,r(o)]}return e}},38761:(t,e,n)=>{var r=n(6840),i=n(98109);t.exports=function(t,e){var n=i(t,e);return r(n)?n:void 0}},47353:(t,e,n)=>{var r=n(60241)(Object.getPrototypeOf,Object);t.exports=r},62107:(t,e,n)=>{var r=n(50857),i=Object.prototype,a=i.hasOwnProperty,o=i.toString,u=r?r.toStringTag:void 0;t.exports=function(t){var e=a.call(t,u),n=t[u];try{t[u]=void 0;var r=!0}catch(t){}var i=o.call(t);return r&&(e?t[u]=n:delete t[u]),i}},80633:(t,e,n)=>{var r=n(67552),i=n(30981),a=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,u=o?function(t){return null==t?[]:(t=Object(t),r(o(t),(function(e){return a.call(t,e)})))}:i;t.exports=u},12680:(t,e,n)=>{var r=n(65067),i=n(47353),a=n(80633),o=n(30981),u=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)r(e,a(t)),t=i(t);return e}:o;t.exports=u},70940:(t,e,n)=>{var r=n(39515),i=n(10326),a=n(52760),o=n(2143),u=n(93215),s=n(53366),c=n(87035),f="[object Map]",l="[object Promise]",h="[object Set]",d="[object WeakMap]",p="[object DataView]",v=c(r),g=c(i),_=c(a),b=c(o),y=c(u),m=s;(r&&m(new r(new ArrayBuffer(1)))!=p||i&&m(new i)!=f||a&&m(a.resolve())!=l||o&&m(new o)!=h||u&&m(new u)!=d)&&(m=function(t){var e=s(t),n="[object Object]"==e?t.constructor:void 0,r=n?c(n):"";if(r)switch(r){case v:return p;case g:return f;case _:return l;case b:return h;case y:return d}return e}),t.exports=m},98109:t=>{t.exports=function(t,e){return null==t?void 0:t[e]}},1369:(t,e,n)=>{var r=n(17297),i=n(79631),a=n(86152),o=n(39045),u=n(61158),s=n(33812);t.exports=function(t,e,n){for(var c=-1,f=(e=r(e,t)).length,l=!1;++c{var e=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return e.test(t)}},52118:(t,e,n)=>{var r=n(99191);t.exports=function(){this.__data__=r?r(null):{},this.size=0}},96909:t=>{t.exports=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}},98138:(t,e,n)=>{var r=n(99191),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;if(r){var n=e[t];return"__lodash_hash_undefined__"===n?void 0:n}return i.call(e,t)?e[t]:void 0}},4174:(t,e,n)=>{var r=n(99191),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;return r?void 0!==e[t]:i.call(e,t)}},7942:(t,e,n)=>{var r=n(99191);t.exports=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?"__lodash_hash_undefined__":e,this}},99917:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=t.length,r=new t.constructor(n);return n&&"string"==typeof t[0]&&e.call(t,"index")&&(r.index=t.index,r.input=t.input),r}},8222:(t,e,n)=>{var r=n(79882),i=n(34727),a=n(96058),o=n(70169),u=n(6190);t.exports=function(t,e,n){var s=t.constructor;switch(e){case"[object ArrayBuffer]":return r(t);case"[object Boolean]":case"[object Date]":return new s(+t);case"[object DataView]":return i(t,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return u(t,n);case"[object Map]":return new s;case"[object Number]":case"[object String]":return new s(t);case"[object RegExp]":return a(t);case"[object Set]":return new s;case"[object Symbol]":return o(t)}}},78725:(t,e,n)=>{var r=n(39413),i=n(47353),a=n(16001);t.exports=function(t){return"function"!=typeof t.constructor||a(t)?{}:r(i(t))}},95882:(t,e,n)=>{var r=n(50857),i=n(79631),a=n(86152),o=r?r.isConcatSpreadable:void 0;t.exports=function(t){return a(t)||i(t)||!!(o&&t&&t[o])}},39045:t=>{var e=/^(?:0|[1-9]\d*)$/;t.exports=function(t,n){var r=typeof t;return!!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&e.test(t))&&t>-1&&t%1==0&&t{var r=n(41225),i=n(67878),a=n(39045),o=n(29259);t.exports=function(t,e,n){if(!o(n))return!1;var u=typeof e;return!!("number"==u?i(n)&&a(e,n.length):"string"==u&&e in n)&&r(n[e],t)}},21401:(t,e,n)=>{var r=n(86152),i=n(4795),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=function(t,e){if(r(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!i(t))||o.test(t)||!a.test(t)||null!=e&&t in Object(e)}},98304:t=>{t.exports=function(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}},47394:(t,e,n)=>{var r,i=n(24019),a=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!a&&a in t}},16001:t=>{var e=Object.prototype;t.exports=function(t){var n=t&&t.constructor;return t===("function"==typeof n&&n.prototype||e)}},28792:(t,e,n)=>{var r=n(29259);t.exports=function(t){return t==t&&!r(t)}},3945:t=>{t.exports=function(){this.__data__=[],this.size=0}},21846:(t,e,n)=>{var r=n(22218),i=Array.prototype.splice;t.exports=function(t){var e=this.__data__,n=r(e,t);return!(n<0||(n==e.length-1?e.pop():i.call(e,n,1),--this.size,0))}},88028:(t,e,n)=>{var r=n(22218);t.exports=function(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]}},72344:(t,e,n)=>{var r=n(22218);t.exports=function(t){return r(this.__data__,t)>-1}},94769:(t,e,n)=>{var r=n(22218);t.exports=function(t,e){var n=this.__data__,i=r(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this}},92411:(t,e,n)=>{var r=n(89612),i=n(80235),a=n(10326);t.exports=function(){this.size=0,this.__data__={hash:new r,map:new(a||i),string:new r}}},36417:(t,e,n)=>{var r=n(27937);t.exports=function(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e}},86928:(t,e,n)=>{var r=n(27937);t.exports=function(t){return r(this,t).get(t)}},18052:(t,e,n)=>{var r=n(27937);t.exports=function(t){return r(this,t).has(t)}},24150:(t,e,n)=>{var r=n(27937);t.exports=function(t,e){var n=r(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}},75179:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}},73477:t=>{t.exports=function(t,e){return function(n){return null!=n&&n[t]===e&&(void 0!==e||t in Object(n))}}},77777:(t,e,n)=>{var r=n(30733);t.exports=function(t){var e=r(t,(function(t){return 500===n.size&&n.clear(),t})),n=e.cache;return e}},99191:(t,e,n)=>{var r=n(38761)(Object,"create");t.exports=r},54248:(t,e,n)=>{var r=n(60241)(Object.keys,Object);t.exports=r},62966:t=>{t.exports=function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}},4146:(t,e,n)=>{t=n.nmd(t);var r=n(51242),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i&&r.process,u=function(){try{return a&&a.require&&a.require("util").types||o&&o.binding&&o.binding("util")}catch(t){}}();t.exports=u},37157:t=>{var e=Object.prototype.toString;t.exports=function(t){return e.call(t)}},60241:t=>{t.exports=function(t,e){return function(n){return t(e(n))}}},43114:(t,e,n)=>{var r=n(49432),i=Math.max;t.exports=function(t,e,n){return e=i(void 0===e?t.length-1:e,0),function(){for(var a=arguments,o=-1,u=i(a.length-e,0),s=Array(u);++o{var r=n(51242),i="object"==typeof self&&self&&self.Object===Object&&self,a=r||i||Function("return this")();t.exports=a},52434:t=>{t.exports=function(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}},52842:t=>{t.exports=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this}},52482:t=>{t.exports=function(t){return this.__data__.has(t)}},16909:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}},75251:(t,e,n)=>{var r=n(86532),i=n(97787)(r);t.exports=i},97787:t=>{var e=Date.now;t.exports=function(t){var n=0,r=0;return function(){var i=e(),a=16-(i-r);if(r=i,a>0){if(++n>=800)return arguments[0]}else n=0;return t.apply(void 0,arguments)}}},15243:(t,e,n)=>{var r=n(80235);t.exports=function(){this.__data__=new r,this.size=0}},72858:t=>{t.exports=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}},4417:t=>{t.exports=function(t){return this.__data__.get(t)}},8605:t=>{t.exports=function(t){return this.__data__.has(t)}},71418:(t,e,n)=>{var r=n(80235),i=n(10326),a=n(96738);t.exports=function(t,e){var n=this.__data__;if(n instanceof r){var o=n.__data__;if(!i||o.length<199)return o.push([t,e]),this.size=++n.size,this;n=this.__data__=new a(o)}return n.set(t,e),this.size=n.size,this}},66024:t=>{t.exports=function(t,e,n){for(var r=n-1,i=t.length;++r{var r=n(8589),i=n(33880),a=n(35555);t.exports=function(t){return i(t)?a(t):r(t)}},54452:(t,e,n)=>{var r=n(77777),i=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,o=r((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(i,(function(t,n,r,i){e.push(r?i.replace(a,"$1"):n||t)})),e}));t.exports=o},33812:(t,e,n)=>{var r=n(4795);t.exports=function(t){if("string"==typeof t||r(t))return t;var e=t+"";return"0"==e&&1/t==-1/0?"-0":e}},87035:t=>{var e=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return e.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},52153:t=>{var e=/\s/;t.exports=function(t){for(var n=t.length;n--&&e.test(t.charAt(n)););return n}},35555:t=>{var e="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",n="\\ud83c[\\udffb-\\udfff]",r="[^\\ud800-\\udfff]",i="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",o="(?:"+e+"|"+n+")?",u="[\\ufe0e\\ufe0f]?",s=u+o+"(?:\\u200d(?:"+[r,i,a].join("|")+")"+u+o+")*",c="(?:"+[r+e+"?",e,i,a,"[\\ud800-\\udfff]"].join("|")+")",f=RegExp(n+"(?="+n+")|"+c+s,"g");t.exports=function(t){for(var e=f.lastIndex=0;f.test(t);)++e;return e}},54004:(t,e,n)=>{var r=n(18874);t.exports=function(t){return r(t,4)}},9850:(t,e,n)=>{var r=n(18874);t.exports=function(t){return r(t,5)}},86874:t=>{t.exports=function(t){return function(){return t}}},84573:(t,e,n)=>{var r=n(36060),i=n(41225),a=n(82406),o=n(18582),u=Object.prototype,s=u.hasOwnProperty,c=r((function(t,e){t=Object(t);var n=-1,r=e.length,c=r>2?e[2]:void 0;for(c&&a(e[0],e[1],c)&&(r=1);++n{t.exports=n(59756)},41225:t=>{t.exports=function(t,e){return t===e||t!=t&&e!=e}},90882:(t,e,n)=>{var r=n(67552),i=n(98043),a=n(68286),o=n(86152);t.exports=function(t,e){return(o(t)?r:i)(t,a(e,3))}},55281:(t,e,n)=>{var r=n(98776)(n(12982));t.exports=r},12982:(t,e,n)=>{var r=n(21359),i=n(68286),a=n(38101),o=Math.max;t.exports=function(t,e,n){var u=null==t?0:t.length;if(!u)return-1;var s=null==n?0:a(n);return s<0&&(s=o(u+s,0)),r(t,i(e,3),s)}},35676:(t,e,n)=>{var r=n(62034);t.exports=function(t){return null!=t&&t.length?r(t,1):[]}},59756:(t,e,n)=>{var r=n(72517),i=n(24303),a=n(89419),o=n(86152);t.exports=function(t,e){return(o(t)?r:i)(t,a(e))}},20792:(t,e,n)=>{var r=n(15308),i=n(89419),a=n(18582);t.exports=function(t,e){return null==t?t:r(t,i(e),a)}},72579:(t,e,n)=>{var r=n(13324);t.exports=function(t,e,n){var i=null==t?void 0:r(t,e);return void 0===i?n:i}},93352:(t,e,n)=>{var r=n(32726),i=n(1369);t.exports=function(t,e){return null!=t&&i(t,e,r)}},95041:(t,e,n)=>{var r=n(20187),i=n(1369);t.exports=function(t,e){return null!=t&&i(t,e,r)}},23059:t=>{t.exports=function(t){return t}},79631:(t,e,n)=>{var r=n(15183),i=n(15125),a=Object.prototype,o=a.hasOwnProperty,u=a.propertyIsEnumerable,s=r(function(){return arguments}())?r:function(t){return i(t)&&o.call(t,"callee")&&!u.call(t,"callee")};t.exports=s},86152:t=>{var e=Array.isArray;t.exports=e},67878:(t,e,n)=>{var r=n(61049),i=n(61158);t.exports=function(t){return null!=t&&i(t.length)&&!r(t)}},93746:(t,e,n)=>{var r=n(67878),i=n(15125);t.exports=function(t){return i(t)&&r(t)}},73226:(t,e,n)=>{t=n.nmd(t);var r=n(37772),i=n(36330),a=e&&!e.nodeType&&e,o=a&&t&&!t.nodeType&&t,u=o&&o.exports===a?r.Buffer:void 0,s=(u?u.isBuffer:void 0)||i;t.exports=s},45455:(t,e,n)=>{var r=n(86411),i=n(70940),a=n(79631),o=n(86152),u=n(67878),s=n(73226),c=n(16001),f=n(77598),l=Object.prototype.hasOwnProperty;t.exports=function(t){if(null==t)return!0;if(u(t)&&(o(t)||"string"==typeof t||"function"==typeof t.splice||s(t)||f(t)||a(t)))return!t.length;var e=i(t);if("[object Map]"==e||"[object Set]"==e)return!t.size;if(c(t))return!r(t).length;for(var n in t)if(l.call(t,n))return!1;return!0}},61049:(t,e,n)=>{var r=n(53366),i=n(29259);t.exports=function(t){if(!i(t))return!1;var e=r(t);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e}},61158:t=>{t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}},4714:(t,e,n)=>{var r=n(74511),i=n(47826),a=n(4146),o=a&&a.isMap,u=o?i(o):r;t.exports=u},29259:t=>{t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},15125:t=>{t.exports=function(t){return null!=t&&"object"==typeof t}},97030:(t,e,n)=>{var r=n(53366),i=n(47353),a=n(15125),o=Function.prototype,u=Object.prototype,s=o.toString,c=u.hasOwnProperty,f=s.call(Object);t.exports=function(t){if(!a(t)||"[object Object]"!=r(t))return!1;var e=i(t);if(null===e)return!0;var n=c.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&s.call(n)==f}},43679:(t,e,n)=>{var r=n(8109),i=n(47826),a=n(4146),o=a&&a.isSet,u=o?i(o):r;t.exports=u},85505:(t,e,n)=>{var r=n(53366),i=n(86152),a=n(15125);t.exports=function(t){return"string"==typeof t||!i(t)&&a(t)&&"[object String]"==r(t)}},4795:(t,e,n)=>{var r=n(53366),i=n(15125);t.exports=function(t){return"symbol"==typeof t||i(t)&&"[object Symbol]"==r(t)}},77598:(t,e,n)=>{var r=n(35522),i=n(47826),a=n(4146),o=a&&a.isTypedArray,u=o?i(o):r;t.exports=u},84336:t=>{t.exports=function(t){return void 0===t}},90249:(t,e,n)=>{var r=n(1634),i=n(86411),a=n(67878);t.exports=function(t){return a(t)?r(t):i(t)}},18582:(t,e,n)=>{var r=n(1634),i=n(18390),a=n(67878);t.exports=function(t){return a(t)?r(t,!0):i(t)}},56974:t=>{t.exports=function(t){var e=null==t?0:t.length;return e?t[e-1]:void 0}},16760:(t,e,n)=>{var r=n(50343),i=n(68286),a=n(93401),o=n(86152);t.exports=function(t,e){return(o(t)?r:a)(t,i(e,3))}},34519:(t,e,n)=>{var r=n(13940),i=n(26548),a=n(68286);t.exports=function(t,e){var n={};return e=a(e,3),i(t,(function(t,i,a){r(n,i,e(t,i,a))})),n}},71644:(t,e,n)=>{var r=n(2229),i=n(84134),a=n(23059);t.exports=function(t){return t&&t.length?r(t,a,i):void 0}},30733:(t,e,n)=>{var r=n(96738);function i(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError("Expected a function");var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);var o=t.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(i.Cache||r),n}i.Cache=r,t.exports=i},98537:(t,e,n)=>{var r=n(84565),i=n(97263)((function(t,e,n){r(t,e,n)}));t.exports=i},65680:(t,e,n)=>{var r=n(2229),i=n(17606),a=n(23059);t.exports=function(t){return t&&t.length?r(t,a,i):void 0}},10937:(t,e,n)=>{var r=n(2229),i=n(68286),a=n(17606);t.exports=function(t,e){return t&&t.length?r(t,i(e,2),a):void 0}},34291:t=>{t.exports=function(){}},61100:(t,e,n)=>{var r=n(37772);t.exports=function(){return r.Date.now()}},13888:(t,e,n)=>{var r=n(92602),i=n(29097)((function(t,e){return null==t?{}:r(t,e)}));t.exports=i},65798:(t,e,n)=>{var r=n(20256),i=n(82952),a=n(21401),o=n(33812);t.exports=function(t){return a(t)?r(o(t)):i(t)}},2689:(t,e,n)=>{var r=n(82941)();t.exports=r},58215:(t,e,n)=>{var r=n(81207),i=n(24303),a=n(68286),o=n(5877),u=n(86152);t.exports=function(t,e,n){var s=u(t)?r:o,c=arguments.length<3;return s(t,a(e,4),n,c,i)}},36402:(t,e,n)=>{var r=n(86411),i=n(70940),a=n(67878),o=n(85505),u=n(82302);t.exports=function(t){if(null==t)return 0;if(a(t))return o(t)?u(t):t.length;var e=i(t);return"[object Map]"==e||"[object Set]"==e?t.size:r(t).length}},829:(t,e,n)=>{var r=n(62034),i=n(23813),a=n(36060),o=n(82406),u=a((function(t,e){if(null==t)return[];var n=e.length;return n>1&&o(t,e[0],e[1])?e=[]:n>2&&o(e[0],e[1],e[2])&&(e=[e[0]]),i(t,r(e,1),[])}));t.exports=u},30981:t=>{t.exports=function(){return[]}},36330:t=>{t.exports=function(){return!1}},5707:(t,e,n)=>{var r=n(7642);t.exports=function(t){return t?Infinity===(t=r(t))||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}},38101:(t,e,n)=>{var r=n(5707);t.exports=function(t){var e=r(t),n=e%1;return e==e?n?e-n:e:0}},7642:(t,e,n)=>{var r=n(51704),i=n(29259),a=n(4795),o=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,s=/^0o[0-7]+$/i,c=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(a(t))return NaN;if(i(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=i(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=r(t);var n=u.test(t);return n||s.test(t)?c(t.slice(2),n?2:8):o.test(t)?NaN:+t}},63329:(t,e,n)=>{var r=n(752),i=n(18582);t.exports=function(t){return r(t,i(t))}},66188:(t,e,n)=>{var r=n(1054);t.exports=function(t){return null==t?"":r(t)}},89466:(t,e,n)=>{var r=n(72517),i=n(39413),a=n(26548),o=n(68286),u=n(47353),s=n(86152),c=n(73226),f=n(61049),l=n(29259),h=n(77598);t.exports=function(t,e,n){var d=s(t),p=d||c(t)||h(t);if(e=o(e,4),null==n){var v=t&&t.constructor;n=p?d?new v:[]:l(t)&&f(v)?i(u(t)):{}}return(p?r:a)(t,(function(t,r,i){return e(n,t,r,i)})),n}},26139:(t,e,n)=>{var r=n(62034),i=n(36060),a=n(67326),o=n(93746),u=i((function(t){return a(r(t,1,o,!0))}));t.exports=u},74930:(t,e,n)=>{var r=n(66188),i=0;t.exports=function(t){var e=++i;return r(t)+e}},98346:(t,e,n)=>{var r=n(50753),i=n(90249);t.exports=function(t){return null==t?[]:r(t,i(t))}},46150:(t,e,n)=>{var r=n(60091),i=n(40509);t.exports=function(t,e){return i(t||[],e||[],r)}},27808:t=>{t.exports=n;var e=null;try{e=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},a={};function o(t,e){var n,r,o;return e?(o=0<=(t>>>=0)&&t<256)&&(r=a[t])?r:(n=s(t,(0|t)<0?-1:0,!0),o&&(a[t]=n),n):(o=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=s(t,t<0?-1:0,!1),o&&(i[t]=n),n)}function u(t,e){if(isNaN(t))return e?_:g;if(e){if(t<0)return _;if(t>=d)return w}else{if(t<=-p)return Z;if(t+1>=p)return x}return t<0?u(-t,e).neg():s(t%h|0,t/h|0,e)}function s(t,e,r){return new n(t,e,r)}n.fromInt=o,n.fromNumber=u,n.fromBits=s;var c=Math.pow;function f(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return g;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return f(t.substring(1),e,n).neg();for(var i=u(c(n,8)),a=g,o=0;o>>0:this.low},D.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},D.toString=function(t){if((t=t||10)<2||36>>0).toString(t);if((a=s).isZero())return f+o;for(;f.length<6;)f="0"+f;o=""+f+o}},D.getHighBits=function(){return this.high},D.getHighBitsUnsigned=function(){return this.high>>>0},D.getLowBits=function(){return this.low},D.getLowBitsUnsigned=function(){return this.low>>>0},D.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Z)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<=0},D.isOdd=function(){return 1==(1&this.low)},D.isEven=function(){return 0==(1&this.low)},D.equals=function(t){return r(t)||(t=l(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},D.eq=D.equals,D.notEquals=function(t){return!this.eq(t)},D.neq=D.notEquals,D.ne=D.notEquals,D.lessThan=function(t){return this.comp(t)<0},D.lt=D.lessThan,D.lessThanOrEqual=function(t){return this.comp(t)<=0},D.lte=D.lessThanOrEqual,D.le=D.lessThanOrEqual,D.greaterThan=function(t){return this.comp(t)>0},D.gt=D.greaterThan,D.greaterThanOrEqual=function(t){return this.comp(t)>=0},D.gte=D.greaterThanOrEqual,D.ge=D.greaterThanOrEqual,D.compare=function(t){if(r(t)||(t=l(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},D.comp=D.compare,D.negate=function(){return!this.unsigned&&this.eq(Z)?Z:this.not().add(b)},D.neg=D.negate,D.add=function(t){r(t)||(t=l(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,a=65535&this.low,o=t.high>>>16,u=65535&t.high,c=t.low>>>16,f=0,h=0,d=0,p=0;return d+=(p+=a+(65535&t.low))>>>16,h+=(d+=i+c)>>>16,f+=(h+=n+u)>>>16,f+=e+o,s((d&=65535)<<16|(p&=65535),(f&=65535)<<16|(h&=65535),this.unsigned)},D.subtract=function(t){return r(t)||(t=l(t)),this.add(t.neg())},D.sub=D.subtract,D.multiply=function(t){if(this.isZero())return g;if(r(t)||(t=l(t)),e)return s(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return g;if(this.eq(Z))return t.isOdd()?Z:g;if(t.eq(Z))return this.isOdd()?Z:g;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(v)&&t.lt(v))return u(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,a=this.low>>>16,o=65535&this.low,c=t.high>>>16,f=65535&t.high,h=t.low>>>16,d=65535&t.low,p=0,_=0,b=0,y=0;return b+=(y+=o*d)>>>16,_+=(b+=a*d)>>>16,b&=65535,_+=(b+=o*h)>>>16,p+=(_+=i*d)>>>16,_&=65535,p+=(_+=a*h)>>>16,_&=65535,p+=(_+=o*f)>>>16,p+=n*d+i*h+a*f+o*c,s((b&=65535)<<16|(y&=65535),(p&=65535)<<16|(_&=65535),this.unsigned)},D.mul=D.multiply,D.divide=function(t){if(r(t)||(t=l(t)),t.isZero())throw Error("division by zero");var n,i,a;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?s((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?_:g;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return _;if(t.gt(this.shru(1)))return y;a=_}else{if(this.eq(Z))return t.eq(b)||t.eq(m)?Z:t.eq(Z)?b:(n=this.shr(1).div(t).shl(1)).eq(g)?t.isNegative()?b:m:(i=this.sub(t.mul(n)),a=n.add(i.div(t)));if(t.eq(Z))return this.unsigned?_:g;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();a=g}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(n)/Math.LN2),f=o<=48?1:c(2,o-48),h=u(n),d=h.mul(t);d.isNegative()||d.gt(i);)d=(h=u(n-=f,this.unsigned)).mul(t);h.isZero()&&(h=b),a=a.add(h),i=i.sub(d)}return a},D.div=D.divide,D.modulo=function(t){return r(t)||(t=l(t)),e?s((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},D.mod=D.modulo,D.rem=D.modulo,D.not=function(){return s(~this.low,~this.high,this.unsigned)},D.and=function(t){return r(t)||(t=l(t)),s(this.low&t.low,this.high&t.high,this.unsigned)},D.or=function(t){return r(t)||(t=l(t)),s(this.low|t.low,this.high|t.high,this.unsigned)},D.xor=function(t){return r(t)||(t=l(t)),s(this.low^t.low,this.high^t.high,this.unsigned)},D.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?s(this.low<>>32-t,this.unsigned):s(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):s(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},D.shr=D.shiftRight,D.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?s(this.low>>>t|e<<32-t,e>>>t,this.unsigned):s(32===t?e:e>>>t-32,0,this.unsigned)},D.shru=D.shiftRightUnsigned,D.shr_u=D.shiftRightUnsigned,D.toSigned=function(){return this.unsigned?s(this.low,this.high,!1):this},D.toUnsigned=function(){return this.unsigned?this:s(this.low,this.high,!0)},D.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},D.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},D.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},13917:function(t){t.exports=function(){"use strict";function t(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r={exports:{}};function i(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}r.exports={defaults:{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1},getDefaults:i,changeDefaults:function(t){r.exports.defaults=t}};var a=/[&<>"']/,o=/[&<>"']/g,u=/[<>"']|&(?!#?\w+;)/,s=/[<>"']|&(?!#?\w+;)/g,c={"&":"&","<":"<",">":">",'"':""","'":"'"},f=function(t){return c[t]};var l=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function h(t){return t.replace(l,(function(t,e){return"colon"===(e=e.toLowerCase())?":":"#"===e.charAt(0)?"x"===e.charAt(1)?String.fromCharCode(parseInt(e.substring(2),16)):String.fromCharCode(+e.substring(1)):""}))}var d=/(^|[^\[])\^/g;var p=/[^\w:]/g,v=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;var g={},_=/^[^:]+:\/*[^/]*$/,b=/^([^:]+:)[\s\S]*$/,y=/^([^:]+:\/*[^/]*)[\s\S]*$/;function m(t,e){g[" "+t]||(_.test(t)?g[" "+t]=t+"/":g[" "+t]=x(t,"/",!0));var n=-1===(t=g[" "+t]).indexOf(":");return"//"===e.substring(0,2)?n?e:t.replace(b,"$1")+e:"/"===e.charAt(0)?n?e:t.replace(y,"$1")+e:t+e}function x(t,e,n){var r=t.length;if(0===r)return"";for(var i=0;i=0&&"\\"===n[i];)r=!r;return r?"|":" |"})).split(/ \|/),r=0;if(n.length>e)n.splice(e);else for(;n.length1;)1&e&&(n+=t),e>>=1,t+=t;return n+t},S=r.exports.defaults,N=C,T=j,z=w,O=M;function R(t,e,n){var r=e.href,i=e.title?z(e.title):null,a=t[1].replace(/\\([\[\]])/g,"$1");return"!"!==t[0].charAt(0)?{type:"link",raw:n,href:r,title:i,text:a}:{type:"image",raw:n,href:r,title:i,text:z(a)}}var P=function(){function t(t){this.options=t||S}var e=t.prototype;return e.space=function(t){var e=this.rules.block.newline.exec(t);if(e)return e[0].length>1?{type:"space",raw:e[0]}:{raw:"\n"}},e.code=function(t){var e=this.rules.block.code.exec(t);if(e){var n=e[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:N(n,"\n")}}},e.fences=function(t){var e=this.rules.block.fences.exec(t);if(e){var n=e[0],r=function(t,e){var n=t.match(/^(\s+)(?:```)/);if(null===n)return e;var r=n[1];return e.split("\n").map((function(t){var e=t.match(/^\s+/);return null===e?t:e[0].length>=r.length?t.slice(r.length):t})).join("\n")}(n,e[3]||"");return{type:"code",raw:n,lang:e[2]?e[2].trim():e[2],text:r}}},e.heading=function(t){var e=this.rules.block.heading.exec(t);if(e){var n=e[2].trim();if(/#$/.test(n)){var r=N(n,"#");this.options.pedantic?n=r.trim():r&&!/ $/.test(r)||(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n}}},e.nptable=function(t){var e=this.rules.block.nptable.exec(t);if(e){var n={type:"table",header:T(e[1].replace(/^ *| *\| *$/g,"")),align:e[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:e[3]?e[3].replace(/\n$/,"").split("\n"):[],raw:e[0]};if(n.header.length===n.align.length){var r,i=n.align.length;for(r=0;r ?/gm,"");return{type:"blockquote",raw:e[0],text:n}}},e.list=function(t){var e=this.rules.block.list.exec(t);if(e){var n,r,i,a,o,u,s,c,f,l=e[0],h=e[2],d=h.length>1,p={type:"list",raw:l,ordered:d,start:d?+h.slice(0,-1):"",loose:!1,items:[]},v=e[0].match(this.rules.block.item),g=!1,_=v.length;i=this.rules.block.listItemStart.exec(v[0]);for(var b=0;b<_;b++){if(l=n=v[b],this.options.pedantic||(f=n.match(new RegExp("\\n\\s*\\n {0,"+(i[0].length-1)+"}\\S")))&&(o=n.length-f.index+v.slice(b+1).join("\n").length,p.raw=p.raw.substring(0,p.raw.length-o),l=n=n.substring(0,f.index),_=b+1),b!==_-1){if(a=this.rules.block.listItemStart.exec(v[b+1]),this.options.pedantic?a[1].length>i[1].length:a[1].length>=i[0].length||a[1].length>3){v.splice(b,2,v[b]+(!this.options.pedantic&&a[1].length/i.test(r[0])&&(e=!1),!n&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?n=!0:n&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(n=!1),{type:this.options.sanitize?"text":"html",raw:r[0],inLink:e,inRawBlock:n,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):z(r[0]):r[0]}},e.link=function(t){var e=this.rules.inline.link.exec(t);if(e){var n=e[2].trim();if(!this.options.pedantic&&/^$/.test(n))return;var r=N(n.slice(0,-1),"\\");if((n.length-r.length)%2==0)return}else{var i=O(e[2],"()");if(i>-1){var a=(0===e[0].indexOf("!")?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,a).trim(),e[3]=""}}var o=e[2],u="";if(this.options.pedantic){var s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);s&&(o=s[1],u=s[3])}else u=e[3]?e[3].slice(1,-1):"";return o=o.trim(),/^$/.test(n)?o.slice(1):o.slice(1,-1)),R(e,{href:o?o.replace(this.rules.inline._escapes,"$1"):o,title:u?u.replace(this.rules.inline._escapes,"$1"):u},e[0])}},e.reflink=function(t,e){var n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){var r=(n[2]||n[1]).replace(/\s+/g," ");if(!(r=e[r.toLowerCase()])||!r.href){var i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return R(n,r,n[0])}},e.emStrong=function(t,e,n){void 0===n&&(n="");var r=this.rules.inline.emStrong.lDelim.exec(t);if(r&&(!r[3]||!n.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/))){var i=r[1]||r[2]||"";if(!i||i&&(""===n||this.rules.inline.punctuation.exec(n))){var a,o,u=r[0].length-1,s=u,c=0,f="*"===r[0][0]?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,e=e.slice(-1*t.length+u);null!=(r=f.exec(e));)if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6])if(o=a.length,r[3]||r[4])s+=o;else if(!((r[5]||r[6])&&u%3)||(u+o)%3){if(!((s-=o)>0))return o=Math.min(o,o+s+c),Math.min(u,o)%2?{type:"em",raw:t.slice(0,u+r.index+o+1),text:t.slice(1,u+r.index+o)}:{type:"strong",raw:t.slice(0,u+r.index+o+1),text:t.slice(2,u+r.index+o-1)}}else c+=o}}},e.codespan=function(t){var e=this.rules.inline.code.exec(t);if(e){var n=e[2].replace(/\n/g," "),r=/[^ ]/.test(n),i=/^ /.test(n)&&/ $/.test(n);return r&&i&&(n=n.substring(1,n.length-1)),n=z(n,!0),{type:"codespan",raw:e[0],text:n}}},e.br=function(t){var e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}},e.del=function(t){var e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2]}},e.autolink=function(t,e){var n,r,i=this.rules.inline.autolink.exec(t);if(i)return r="@"===i[2]?"mailto:"+(n=z(this.options.mangle?e(i[1]):i[1])):n=z(i[1]),{type:"link",raw:i[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}},e.url=function(t,e){var n;if(n=this.rules.inline.url.exec(t)){var r,i;if("@"===n[2])i="mailto:"+(r=z(this.options.mangle?e(n[0]):n[0]));else{var a;do{a=n[0],n[0]=this.rules.inline._backpedal.exec(n[0])[0]}while(a!==n[0]);r=z(n[0]),i="www."===n[1]?"http://"+r:r}return{type:"link",raw:n[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}},e.inlineText=function(t,e,n){var r,i=this.rules.inline.text.exec(t);if(i)return r=e?this.options.sanitize?this.options.sanitizer?this.options.sanitizer(i[0]):z(i[0]):i[0]:z(this.options.smartypants?n(i[0]):i[0]),{type:"text",raw:i[0],text:r}},t}(),I=E,L=D,U=A,$={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?! {0,3}bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,nptable:I,table:I,lheading:/^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/,text:/^[^\n]+/,_label:/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,_title:/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/};$.def=L($.def).replace("label",$._label).replace("title",$._title).getRegex(),$.bullet=/(?:[*+-]|\d{1,9}[.)])/,$.item=/^( *)(bull) ?[^\n]*(?:\n(?! *bull ?)[^\n]*)*/,$.item=L($.item,"gm").replace(/bull/g,$.bullet).getRegex(),$.listItemStart=L(/^( *)(bull) */).replace("bull",$.bullet).getRegex(),$.list=L($.list).replace(/bull/g,$.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+$.def.source+")").getRegex(),$._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",$._comment=/|$)/,$.html=L($.html,"i").replace("comment",$._comment).replace("tag",$._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),$.paragraph=L($._paragraph).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.blockquote=L($.blockquote).replace("paragraph",$.paragraph).getRegex(),$.normal=U({},$),$.gfm=U({},$.normal,{nptable:"^ *([^|\\n ].*\\|.*)\\n {0,3}([-:]+ *\\|[-| :]*)(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)",table:"^ *\\|(.+)\\n {0,3}\\|?( *[-:]+[-| :]*)(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"}),$.gfm.nptable=L($.gfm.nptable).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.gfm.table=L($.gfm.table).replace("hr",$.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|!--)").replace("tag",$._tag).getRegex(),$.pedantic=U({},$.normal,{html:L("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",$._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:I,paragraph:L($.normal._paragraph).replace("hr",$.hr).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});var H={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:I,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/\_\_[^_*]*?\*[^_*]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,rDelimUnd:/\*\*[^_*]*?\_[^_*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:I,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~"};H.punctuation=L(H.punctuation).replace(/punctuation/g,H._punctuation).getRegex(),H.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,H.escapedEmSt=/\\\*|\\_/g,H._comment=L($._comment).replace("(?:--\x3e|$)","--\x3e").getRegex(),H.emStrong.lDelim=L(H.emStrong.lDelim).replace(/punct/g,H._punctuation).getRegex(),H.emStrong.rDelimAst=L(H.emStrong.rDelimAst,"g").replace(/punct/g,H._punctuation).getRegex(),H.emStrong.rDelimUnd=L(H.emStrong.rDelimUnd,"g").replace(/punct/g,H._punctuation).getRegex(),H._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,H._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,H._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,H.autolink=L(H.autolink).replace("scheme",H._scheme).replace("email",H._email).getRegex(),H._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,H.tag=L(H.tag).replace("comment",H._comment).replace("attribute",H._attribute).getRegex(),H._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,H._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,H._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,H.link=L(H.link).replace("label",H._label).replace("href",H._href).replace("title",H._title).getRegex(),H.reflink=L(H.reflink).replace("label",H._label).getRegex(),H.reflinkSearch=L(H.reflinkSearch,"g").replace("reflink",H.reflink).replace("nolink",H.nolink).getRegex(),H.normal=U({},H),H.pedantic=U({},H.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:L(/^!?\[(label)\]\((.*?)\)/).replace("label",H._label).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",H._label).getRegex()}),H.gfm=U({},H.normal,{escape:L(H.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\.5&&(n="x"+n.toString(16)),r+="&#"+n+";";return r}var Q=function(){function e(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||W,this.options.tokenizer=this.options.tokenizer||new Y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options;var e={block:V.normal,inline:G.normal};this.options.pedantic?(e.block=V.pedantic,e.inline=G.pedantic):this.options.gfm&&(e.block=V.gfm,this.options.breaks?e.inline=G.breaks:e.inline=G.gfm),this.tokenizer.rules=e}e.lex=function(t,n){return new e(n).lex(t)},e.lexInline=function(t,n){return new e(n).inlineTokens(t)};var n,r,i,a=e.prototype;return a.lex=function(t){return t=t.replace(/\r\n|\r/g,"\n").replace(/\t/g," "),this.blockTokens(t,this.tokens,!0),this.inline(this.tokens),this.tokens},a.blockTokens=function(t,e,n){var r,i,a,o;for(void 0===e&&(e=[]),void 0===n&&(n=!0),this.options.pedantic&&(t=t.replace(/^ +$/gm,""));t;)if(r=this.tokenizer.space(t))t=t.substring(r.raw.length),r.type&&e.push(r);else if(r=this.tokenizer.code(t))t=t.substring(r.raw.length),(o=e[e.length-1])&&"paragraph"===o.type?(o.raw+="\n"+r.raw,o.text+="\n"+r.text):e.push(r);else if(r=this.tokenizer.fences(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.heading(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.nptable(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.hr(t))t=t.substring(r.raw.length),e.push(r);else if(r=this.tokenizer.blockquote(t))t=t.substring(r.raw.length),r.tokens=this.blockTokens(r.text,[],n),e.push(r);else if(r=this.tokenizer.list(t)){for(t=t.substring(r.raw.length),a=r.items.length,i=0;i0)for(;null!=(o=this.tokenizer.rules.inline.reflinkSearch.exec(c));)f.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(c=c.slice(0,o.index)+"["+X("a",o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(o=this.tokenizer.rules.inline.blockSkip.exec(c));)c=c.slice(0,o.index)+"["+X("a",o[0].length-2)+"]"+c.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(o=this.tokenizer.rules.inline.escapedEmSt.exec(c));)c=c.slice(0,o.index)+"++"+c.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);for(;t;)if(u||(s=""),u=!1,i=this.tokenizer.escape(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.tag(t,n,r)){t=t.substring(i.raw.length),n=i.inLink,r=i.inRawBlock;var l=e[e.length-1];l&&"text"===i.type&&"text"===l.type?(l.raw+=i.raw,l.text+=i.text):e.push(i)}else if(i=this.tokenizer.link(t))t=t.substring(i.raw.length),"link"===i.type&&(i.tokens=this.inlineTokens(i.text,[],!0,r)),e.push(i);else if(i=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(i.raw.length);var h=e[e.length-1];"link"===i.type?(i.tokens=this.inlineTokens(i.text,[],!0,r),e.push(i)):h&&"text"===i.type&&"text"===h.type?(h.raw+=i.raw,h.text+=i.text):e.push(i)}else if(i=this.tokenizer.emStrong(t,c,s))t=t.substring(i.raw.length),i.tokens=this.inlineTokens(i.text,[],n,r),e.push(i);else if(i=this.tokenizer.codespan(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.br(t))t=t.substring(i.raw.length),e.push(i);else if(i=this.tokenizer.del(t))t=t.substring(i.raw.length),i.tokens=this.inlineTokens(i.text,[],n,r),e.push(i);else if(i=this.tokenizer.autolink(t,J))t=t.substring(i.raw.length),e.push(i);else if(n||!(i=this.tokenizer.url(t,J))){if(i=this.tokenizer.inlineText(t,r,K))t=t.substring(i.raw.length),"_"!==i.raw.slice(-1)&&(s=i.raw.slice(-1)),u=!0,(a=e[e.length-1])&&"text"===a.type?(a.raw+=i.raw,a.text+=i.text):e.push(i);else if(t){var d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}throw new Error(d)}}else t=t.substring(i.raw.length),e.push(i);return e},n=e,i=[{key:"rules",get:function(){return{block:V,inline:G}}}],(r=null)&&t(n.prototype,r),i&&t(n,i),e}(),tt=r.exports.defaults,et=k,nt=w,rt=function(){function t(t){this.options=t||tt}var e=t.prototype;return e.code=function(t,e,n){var r=(e||"").match(/\S*/)[0];if(this.options.highlight){var i=this.options.highlight(t,r);null!=i&&i!==t&&(n=!0,t=i)}return t=t.replace(/\n$/,"")+"\n",r?'
    '+(n?t:nt(t,!0))+"
    \n":"
    "+(n?t:nt(t,!0))+"
    \n"},e.blockquote=function(t){return"
    \n"+t+"
    \n"},e.html=function(t){return t},e.heading=function(t,e,n,r){return this.options.headerIds?"'+t+"\n":""+t+"\n"},e.hr=function(){return this.options.xhtml?"
    \n":"
    \n"},e.list=function(t,e,n){var r=e?"ol":"ul";return"<"+r+(e&&1!==n?' start="'+n+'"':"")+">\n"+t+"\n"},e.listitem=function(t){return"
  • "+t+"
  • \n"},e.checkbox=function(t){return" "},e.paragraph=function(t){return"

    "+t+"

    \n"},e.table=function(t,e){return e&&(e=""+e+""),"\n\n"+t+"\n"+e+"
    \n"},e.tablerow=function(t){return"\n"+t+"\n"},e.tablecell=function(t,e){var n=e.header?"th":"td";return(e.align?"<"+n+' align="'+e.align+'">':"<"+n+">")+t+"\n"},e.strong=function(t){return""+t+""},e.em=function(t){return""+t+""},e.codespan=function(t){return""+t+""},e.br=function(){return this.options.xhtml?"
    ":"
    "},e.del=function(t){return""+t+""},e.link=function(t,e,n){if(null===(t=et(this.options.sanitize,this.options.baseUrl,t)))return n;var r='"+n+""},e.image=function(t,e,n){if(null===(t=et(this.options.sanitize,this.options.baseUrl,t)))return n;var r=''+n+'":">")},e.text=function(t){return t},t}(),it=function(){function t(){}var e=t.prototype;return e.strong=function(t){return t},e.em=function(t){return t},e.codespan=function(t){return t},e.del=function(t){return t},e.html=function(t){return t},e.text=function(t){return t},e.link=function(t,e,n){return""+n},e.image=function(t,e,n){return""+n},e.br=function(){return""},t}(),at=function(){function t(){this.seen={}}var e=t.prototype;return e.serialize=function(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")},e.getNextSafeSlug=function(t,e){var n=t,r=0;if(this.seen.hasOwnProperty(n)){r=this.seen[t];do{n=t+"-"+ ++r}while(this.seen.hasOwnProperty(n))}return e||(this.seen[t]=r,this.seen[n]=0),n},e.slug=function(t,e){void 0===e&&(e={});var n=this.serialize(t);return this.getNextSafeSlug(n,e.dryrun)},t}(),ot=rt,ut=it,st=at,ct=r.exports.defaults,ft=Z,lt=Q,ht=function(){function t(t){this.options=t||ct,this.options.renderer=this.options.renderer||new ot,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ut,this.slugger=new st}t.parse=function(e,n){return new t(n).parse(e)},t.parseInline=function(e,n){return new t(n).parseInline(e)};var e=t.prototype;return e.parse=function(t,e){void 0===e&&(e=!0);var n,r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y,m="",x=t.length;for(n=0;n0&&"text"===g.tokens[0].type?(g.tokens[0].text=y+" "+g.tokens[0].text,g.tokens[0].tokens&&g.tokens[0].tokens.length>0&&"text"===g.tokens[0].tokens[0].type&&(g.tokens[0].tokens[0].text=y+" "+g.tokens[0].tokens[0].text)):g.tokens.unshift({type:"text",text:y}):v+=y),v+=this.parse(g.tokens,p),f+=this.renderer.listitem(v,b,_);m+=this.renderer.list(f,h,d);continue;case"html":m+=this.renderer.html(l.text);continue;case"paragraph":m+=this.renderer.paragraph(this.parseInline(l.tokens));continue;case"text":for(f=l.tokens?this.parseInline(l.tokens):l.text;n+1An error occurred:

    "+yt(t.message+"",!0)+"
    ";throw t}}return Zt.options=Zt.setOptions=function(t){return _t(Zt.defaults,t),xt(Zt.defaults),Zt},Zt.getDefaults=mt,Zt.defaults=wt,Zt.use=function(t){var e=_t({},t);if(t.renderer&&function(){var n=Zt.defaults.renderer||new pt,r=function(e){var r=n[e];n[e]=function(){for(var i=arguments.length,a=new Array(i),o=0;oAn error occurred:

    "+yt(t.message+"",!0)+"
    ";throw t}},Zt.Parser=ht,Zt.parser=ht.parse,Zt.Renderer=pt,Zt.TextRenderer=vt,Zt.Lexer=lt,Zt.lexer=lt.lex,Zt.Tokenizer=dt,Zt.Slugger=gt,Zt.parse=Zt,Zt}()},32845:(t,e,n)=>{"use strict";var r={};(0,n(49761).assign)(r,n(79880),n(21380),n(91271)),t.exports=r},79880:(t,e,n)=>{"use strict";var r=n(75789),i=n(49761),a=n(47944),o=n(82950),u=n(20744),s=Object.prototype.toString;function c(t){if(!(this instanceof c))return new c(t);this.options=i.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new u,this.strm.avail_out=0;var n=r.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(0!==n)throw new Error(o[n]);if(e.header&&r.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?a.string2buf(e.dictionary):"[object ArrayBuffer]"===s.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,0!==(n=r.deflateSetDictionary(this.strm,f)))throw new Error(o[n]);this._dict_set=!0}}function f(t,e){var n=new c(e);if(n.push(t,!0),n.err)throw n.msg||o[n.err];return n.result}c.prototype.push=function(t,e){var n,o,u=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?u.input=a.string2buf(t):"[object ArrayBuffer]"===s.call(t)?u.input=new Uint8Array(t):u.input=t,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new i.Buf8(c),u.next_out=0,u.avail_out=c),1!==(n=r.deflate(u,o))&&0!==n)return this.onEnd(n),this.ended=!0,!1;0!==u.avail_out&&(0!==u.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(a.buf2binstring(i.shrinkBuf(u.output,u.next_out))):this.onData(i.shrinkBuf(u.output,u.next_out)))}while((u.avail_in>0||0===u.avail_out)&&1!==n);return 4===o?(n=r.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,0===n):2!==o||(this.onEnd(0),u.avail_out=0,!0)},c.prototype.onData=function(t){this.chunks.push(t)},c.prototype.onEnd=function(t){0===t&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Deflate=c,e.deflate=f,e.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},e.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},21380:(t,e,n)=>{"use strict";var r=n(35020),i=n(49761),a=n(47944),o=n(91271),u=n(82950),s=n(20744),c=n(7357),f=Object.prototype.toString;function l(t){if(!(this instanceof l))return new l(t);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var n=r.inflateInit2(this.strm,e.windowBits);if(n!==o.Z_OK)throw new Error(u[n]);if(this.header=new c,r.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=a.string2buf(e.dictionary):"[object ArrayBuffer]"===f.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(n=r.inflateSetDictionary(this.strm,e.dictionary))!==o.Z_OK))throw new Error(u[n])}function h(t,e){var n=new l(e);if(n.push(t,!0),n.err)throw n.msg||u[n.err];return n.result}l.prototype.push=function(t,e){var n,u,s,c,l,h=this.strm,d=this.options.chunkSize,p=this.options.dictionary,v=!1;if(this.ended)return!1;u=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?h.input=a.binstring2buf(t):"[object ArrayBuffer]"===f.call(t)?h.input=new Uint8Array(t):h.input=t,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(d),h.next_out=0,h.avail_out=d),(n=r.inflate(h,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&p&&(n=r.inflateSetDictionary(this.strm,p)),n===o.Z_BUF_ERROR&&!0===v&&(n=o.Z_OK,v=!1),n!==o.Z_STREAM_END&&n!==o.Z_OK)return this.onEnd(n),this.ended=!0,!1;h.next_out&&(0!==h.avail_out&&n!==o.Z_STREAM_END&&(0!==h.avail_in||u!==o.Z_FINISH&&u!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(s=a.utf8border(h.output,h.next_out),c=h.next_out-s,l=a.buf2string(h.output,s),h.next_out=c,h.avail_out=d-c,c&&i.arraySet(h.output,h.output,s,c,0),this.onData(l)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(v=!0)}while((h.avail_in>0||0===h.avail_out)&&n!==o.Z_STREAM_END);return n===o.Z_STREAM_END&&(u=o.Z_FINISH),u===o.Z_FINISH?(n=r.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===o.Z_OK):u!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),h.avail_out=0,!0)},l.prototype.onData=function(t){this.chunks.push(t)},l.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=l,e.inflate=h,e.inflateRaw=function(t,e){return(e=e||{}).raw=!0,h(t,e)},e.ungzip=h},49761:(t,e)=>{"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var i in n)r(n,i)&&(t[i]=n[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var i={arraySet:function(t,e,n,r,i){if(e.subarray&&t.subarray)t.set(e.subarray(n,n+r),i);else for(var a=0;a{"use strict";var r=n(49761),i=!0,a=!0;try{String.fromCharCode.apply(null,[0])}catch(t){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){a=!1}for(var o=new r.Buf8(256),u=0;u<256;u++)o[u]=u>=252?6:u>=248?5:u>=240?4:u>=224?3:u>=192?2:1;function s(t,e){if(e<65534&&(t.subarray&&a||!t.subarray&&i))return String.fromCharCode.apply(null,r.shrinkBuf(t,e));for(var n="",o=0;o>>6,e[o++]=128|63&n):n<65536?(e[o++]=224|n>>>12,e[o++]=128|n>>>6&63,e[o++]=128|63&n):(e[o++]=240|n>>>18,e[o++]=128|n>>>12&63,e[o++]=128|n>>>6&63,e[o++]=128|63&n);return e},e.buf2binstring=function(t){return s(t,t.length)},e.binstring2buf=function(t){for(var e=new r.Buf8(t.length),n=0,i=e.length;n4)c[r++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?c[r++]=65533:i<65536?c[r++]=i:(i-=65536,c[r++]=55296|i>>10&1023,c[r++]=56320|1023&i)}return s(c,r)},e.utf8border=function(t,e){var n;for((e=e||t.length)>t.length&&(e=t.length),n=e-1;n>=0&&128==(192&t[n]);)n--;return n<0||0===n?e:n+o[t[n]]>e?n:e}},95562:t=>{"use strict";t.exports=function(t,e,n,r){for(var i=65535&t|0,a=t>>>16&65535|0,o=0;0!==n;){n-=o=n>2e3?2e3:n;do{a=a+(i=i+e[r++]|0)|0}while(--o);i%=65521,a%=65521}return i|a<<16|0}},91271:t=>{"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},24299:t=>{"use strict";var e=function(){for(var t,e=[],n=0;n<256;n++){t=n;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e}();t.exports=function(t,n,r,i){var a=e,o=i+r;t^=-1;for(var u=i;u>>8^a[255&(t^n[u])];return-1^t}},75789:(t,e,n)=>{"use strict";var r,i=n(49761),a=n(69564),o=n(95562),u=n(24299),s=n(82950),c=-2,f=258,l=262,h=103,d=113,p=666;function v(t,e){return t.msg=s[e],e}function g(t){return(t<<1)-(t>4?9:0)}function _(t){for(var e=t.length;--e>=0;)t[e]=0}function b(t){var e=t.state,n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(i.arraySet(t.output,e.pending_buf,e.pending_out,n,t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))}function y(t,e){a._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,b(t.strm)}function m(t,e){t.pending_buf[t.pending++]=e}function x(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function w(t,e){var n,r,i=t.max_chain_length,a=t.strstart,o=t.prev_length,u=t.nice_match,s=t.strstart>t.w_size-l?t.strstart-(t.w_size-l):0,c=t.window,h=t.w_mask,d=t.prev,p=t.strstart+f,v=c[a+o-1],g=c[a+o];t.prev_length>=t.good_match&&(i>>=2),u>t.lookahead&&(u=t.lookahead);do{if(c[(n=e)+o]===g&&c[n+o-1]===v&&c[n]===c[a]&&c[++n]===c[a+1]){a+=2,n++;do{}while(c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&c[++a]===c[++n]&&ao){if(t.match_start=e,o=r,r>=u)break;v=c[a+o-1],g=c[a+o]}}}while((e=d[e&h])>s&&0!=--i);return o<=t.lookahead?o:t.lookahead}function Z(t){var e,n,r,a,s,c,f,h,d,p,v=t.w_size;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=v+(v-l)){i.arraySet(t.window,t.window,v,v,0),t.match_start-=v,t.strstart-=v,t.block_start-=v,e=n=t.hash_size;do{r=t.head[--e],t.head[e]=r>=v?r-v:0}while(--n);e=n=v;do{r=t.prev[--e],t.prev[e]=r>=v?r-v:0}while(--n);a+=v}if(0===t.strm.avail_in)break;if(c=t.strm,f=t.window,h=t.strstart+t.lookahead,d=a,p=void 0,(p=c.avail_in)>d&&(p=d),n=0===p?0:(c.avail_in-=p,i.arraySet(f,c.input,c.next_in,p,h),1===c.state.wrap?c.adler=o(c.adler,f,p,h):2===c.state.wrap&&(c.adler=u(c.adler,f,p,h)),c.next_in+=p,c.total_in+=p,p),t.lookahead+=n,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=(t.ins_h<=3&&(t.ins_h=(t.ins_h<=3)if(r=a._tr_tally(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<=3&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-3,r=a._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=(t.ins_h<15&&(u=2,r-=16),a<1||a>9||8!==n||r<8||r>15||e<0||e>9||o<0||o>4)return v(t,c);8===r&&(r=9);var s=new A;return t.state=s,s.strm=t,s.wrap=u,s.gzhead=null,s.w_bits=r,s.w_size=1<t.pending_buf_size-5&&(n=t.pending_buf_size-5);;){if(t.lookahead<=1){if(Z(t),0===t.lookahead&&0===e)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var r=t.block_start+n;if((0===t.strstart||t.strstart>=r)&&(t.lookahead=t.strstart-r,t.strstart=r,y(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-l&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(y(t,!1),t.strm.avail_out),1)})),new E(4,4,8,4,D),new E(4,5,16,8,D),new E(4,6,32,32,D),new E(4,4,16,16,k),new E(8,16,32,32,k),new E(8,16,128,128,k),new E(8,32,128,256,k),new E(32,128,258,1024,k),new E(32,258,258,4096,k)],e.deflateInit=function(t,e){return M(t,e,8,15,8,0)},e.deflateInit2=M,e.deflateReset=C,e.deflateResetKeep=j,e.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?c:(t.state.gzhead=e,0):c},e.deflate=function(t,e){var n,i,o,s;if(!t||!t.state||e>5||e<0)return t?v(t,c):c;if(i=t.state,!t.output||!t.input&&0!==t.avail_in||i.status===p&&4!==e)return v(t,0===t.avail_out?-5:c);if(i.strm=t,n=i.last_flush,i.last_flush=e,42===i.status)if(2===i.wrap)t.adler=0,m(i,31),m(i,139),m(i,8),i.gzhead?(m(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),m(i,255&i.gzhead.time),m(i,i.gzhead.time>>8&255),m(i,i.gzhead.time>>16&255),m(i,i.gzhead.time>>24&255),m(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),m(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(m(i,255&i.gzhead.extra.length),m(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=u(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(m(i,0),m(i,0),m(i,0),m(i,0),m(i,0),m(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),m(i,3),i.status=d);else{var l=8+(i.w_bits-8<<4)<<8;l|=(i.strategy>=2||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(l|=32),l+=31-l%31,i.status=d,x(i,l),0!==i.strstart&&(x(i,t.adler>>>16),x(i,65535&t.adler)),t.adler=1}if(69===i.status)if(i.gzhead.extra){for(o=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending!==i.pending_buf_size));)m(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(73===i.status)if(i.gzhead.name){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexo&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),0===s&&(i.gzindex=0,i.status=91)}else i.status=91;if(91===i.status)if(i.gzhead.comment){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),b(t),o=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexo&&(t.adler=u(t.adler,i.pending_buf,i.pending-o,o)),0===s&&(i.status=h)}else i.status=h;if(i.status===h&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&b(t),i.pending+2<=i.pending_buf_size&&(m(i,255&t.adler),m(i,t.adler>>8&255),t.adler=0,i.status=d)):i.status=d),0!==i.pending){if(b(t),0===t.avail_out)return i.last_flush=-1,0}else if(0===t.avail_in&&g(e)<=g(n)&&4!==e)return v(t,-5);if(i.status===p&&0!==t.avail_in)return v(t,-5);if(0!==t.avail_in||0!==i.lookahead||0!==e&&i.status!==p){var w=2===i.strategy?function(t,e){for(var n;;){if(0===t.lookahead&&(Z(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,n=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(y(t,!1),0===t.strm.avail_out)?1:2}(i,e):3===i.strategy?function(t,e){for(var n,r,i,o,u=t.window;;){if(t.lookahead<=f){if(Z(t),t.lookahead<=f&&0===e)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(r=u[i=t.strstart-1])===u[++i]&&r===u[++i]&&r===u[++i]){o=t.strstart+f;do{}while(r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&r===u[++i]&&it.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(n=a._tr_tally(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=a._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(y(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(y(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(y(t,!1),0===t.strm.avail_out)?1:2}(i,e):r[i.level].func(i,e);if(3!==w&&4!==w||(i.status=p),1===w||3===w)return 0===t.avail_out&&(i.last_flush=-1),0;if(2===w&&(1===e?a._tr_align(i):5!==e&&(a._tr_stored_block(i,0,0,!1),3===e&&(_(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),b(t),0===t.avail_out))return i.last_flush=-1,0}return 4!==e?0:i.wrap<=0?1:(2===i.wrap?(m(i,255&t.adler),m(i,t.adler>>8&255),m(i,t.adler>>16&255),m(i,t.adler>>24&255),m(i,255&t.total_in),m(i,t.total_in>>8&255),m(i,t.total_in>>16&255),m(i,t.total_in>>24&255)):(x(i,t.adler>>>16),x(i,65535&t.adler)),b(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?0:1)},e.deflateEnd=function(t){var e;return t&&t.state?42!==(e=t.state.status)&&69!==e&&73!==e&&91!==e&&e!==h&&e!==d&&e!==p?v(t,c):(t.state=null,e===d?v(t,-3):0):c},e.deflateSetDictionary=function(t,e){var n,r,a,u,s,f,l,h,d=e.length;if(!t||!t.state)return c;if(2===(u=(n=t.state).wrap)||1===u&&42!==n.status||n.lookahead)return c;for(1===u&&(t.adler=o(t.adler,e,d,0)),n.wrap=0,d>=n.w_size&&(0===u&&(_(n.head),n.strstart=0,n.block_start=0,n.insert=0),h=new i.Buf8(n.w_size),i.arraySet(h,e,d-n.w_size,n.w_size,0),e=h,d=n.w_size),s=t.avail_in,f=t.next_in,l=t.input,t.avail_in=d,t.next_in=0,t.input=e,Z(n);n.lookahead>=3;){r=n.strstart,a=n.lookahead-2;do{n.ins_h=(n.ins_h<{"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},24980:t=>{"use strict";t.exports=function(t,e){var n,r,i,a,o,u,s,c,f,l,h,d,p,v,g,_,b,y,m,x,w,Z,D,k,E;n=t.state,r=t.next_in,k=t.input,i=r+(t.avail_in-5),a=t.next_out,E=t.output,o=a-(e-t.avail_out),u=a+(t.avail_out-257),s=n.dmax,c=n.wsize,f=n.whave,l=n.wnext,h=n.window,d=n.hold,p=n.bits,v=n.lencode,g=n.distcode,_=(1<>>=m=y>>>24,p-=m,0==(m=y>>>16&255))E[a++]=65535&y;else{if(!(16&m)){if(0==(64&m)){y=v[(65535&y)+(d&(1<>>=m,p-=m),p<15&&(d+=k[r++]<>>=m=y>>>24,p-=m,!(16&(m=y>>>16&255))){if(0==(64&m)){y=g[(65535&y)+(d&(1<s){t.msg="invalid distance too far back",n.mode=30;break t}if(d>>>=m,p-=m,w>(m=a-o)){if((m=w-m)>f&&n.sane){t.msg="invalid distance too far back",n.mode=30;break t}if(Z=0,D=h,0===l){if(Z+=c-m,m2;)E[a++]=D[Z++],E[a++]=D[Z++],E[a++]=D[Z++],x-=3;x&&(E[a++]=D[Z++],x>1&&(E[a++]=D[Z++]))}else{Z=a-w;do{E[a++]=E[Z++],E[a++]=E[Z++],E[a++]=E[Z++],x-=3}while(x>2);x&&(E[a++]=E[Z++],x>1&&(E[a++]=E[Z++]))}break}}break}}while(r>3,d&=(1<<(p-=x<<3))-1,t.next_in=r,t.next_out=a,t.avail_in=r{"use strict";var r=n(49761),i=n(95562),a=n(24299),o=n(24980),u=n(50881),s=-2,c=12,f=30;function l(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function h(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new r.Buf32(852),e.distcode=e.distdyn=new r.Buf32(592),e.sane=1,e.back=-1,0):s}function p(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,d(t)):s}function v(t,e){var n,r;return t&&t.state?(r=t.state,e<0?(n=0,e=-e):(n=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?s:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=n,r.wbits=e,p(t))):s}function g(t,e){var n,r;return t?(r=new h,t.state=r,r.window=null,0!==(n=v(t,e))&&(t.state=null),n):s}var _,b,y=!0;function m(t){if(y){var e;for(_=new r.Buf32(512),b=new r.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(u(1,t.lens,0,288,_,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;u(2,t.lens,0,32,b,0,t.work,{bits:5}),y=!1}t.lencode=_,t.lenbits=9,t.distcode=b,t.distbits=5}function x(t,e,n,i){var a,o=t.state;return null===o.window&&(o.wsize=1<=o.wsize?(r.arraySet(o.window,e,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):((a=o.wsize-o.wnext)>i&&(a=i),r.arraySet(o.window,e,n-i,a,o.wnext),(i-=a)?(r.arraySet(o.window,e,n-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=a(n.check,R,2,0),b=0,y=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&b)<<8)+(b>>8))%31){t.msg="incorrect header check",n.mode=f;break}if(8!=(15&b)){t.msg="unknown compression method",n.mode=f;break}if(y-=4,S=8+(15&(b>>>=4)),0===n.wbits)n.wbits=S;else if(S>n.wbits){t.msg="invalid window size",n.mode=f;break}n.dmax=1<>8&1),512&n.flags&&(R[0]=255&b,R[1]=b>>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0,n.mode=3;case 3:for(;y<32;){if(0===g)break t;g--,b+=h[p++]<>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,n.check=a(n.check,R,4,0)),b=0,y=0,n.mode=4;case 4:for(;y<16;){if(0===g)break t;g--,b+=h[p++]<>8),512&n.flags&&(R[0]=255&b,R[1]=b>>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0,n.mode=5;case 5:if(1024&n.flags){for(;y<16;){if(0===g)break t;g--,b+=h[p++]<>>8&255,n.check=a(n.check,R,2,0)),b=0,y=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((D=n.length)>g&&(D=g),D&&(n.head&&(S=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),r.arraySet(n.head.extra,h,p,D,S)),512&n.flags&&(n.check=a(n.check,h,D,p)),g-=D,p+=D,n.length-=D),n.length))break t;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===g)break t;D=0;do{S=h[p+D++],n.head&&S&&n.length<65536&&(n.head.name+=String.fromCharCode(S))}while(S&&D>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=c;break;case 10:for(;y<32;){if(0===g)break t;g--,b+=h[p++]<>>=7&y,y-=7&y,n.mode=27;break}for(;y<3;){if(0===g)break t;g--,b+=h[p++]<>>=1)){case 0:n.mode=14;break;case 1:if(m(n),n.mode=20,6===e){b>>>=2,y-=2;break t}break;case 2:n.mode=17;break;case 3:t.msg="invalid block type",n.mode=f}b>>>=2,y-=2;break;case 14:for(b>>>=7&y,y-=7&y;y<32;){if(0===g)break t;g--,b+=h[p++]<>>16^65535)){t.msg="invalid stored block lengths",n.mode=f;break}if(n.length=65535&b,b=0,y=0,n.mode=15,6===e)break t;case 15:n.mode=16;case 16:if(D=n.length){if(D>g&&(D=g),D>_&&(D=_),0===D)break t;r.arraySet(d,h,p,D,v),g-=D,p+=D,_-=D,v+=D,n.length-=D;break}n.mode=c;break;case 17:for(;y<14;){if(0===g)break t;g--,b+=h[p++]<>>=5,y-=5,n.ndist=1+(31&b),b>>>=5,y-=5,n.ncode=4+(15&b),b>>>=4,y-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=f;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,y-=3}for(;n.have<19;)n.lens[P[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,T={bits:n.lenbits},N=u(0,n.lens,0,19,n.lencode,0,n.work,T),n.lenbits=T.bits,N){t.msg="invalid code lengths set",n.mode=f;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=A,y-=A,n.lens[n.have++]=C;else{if(16===C){for(z=A+2;y>>=A,y-=A,0===n.have){t.msg="invalid bit length repeat",n.mode=f;break}S=n.lens[n.have-1],D=3+(3&b),b>>>=2,y-=2}else if(17===C){for(z=A+3;y>>=A)),b>>>=3,y-=3}else{for(z=A+7;y>>=A)),b>>>=7,y-=7}if(n.have+D>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=f;break}for(;D--;)n.lens[n.have++]=S}}if(n.mode===f)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=f;break}if(n.lenbits=9,T={bits:n.lenbits},N=u(1,n.lens,0,n.nlen,n.lencode,0,n.work,T),n.lenbits=T.bits,N){t.msg="invalid literal/lengths set",n.mode=f;break}if(n.distbits=6,n.distcode=n.distdyn,T={bits:n.distbits},N=u(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,T),n.distbits=T.bits,N){t.msg="invalid distances set",n.mode=f;break}if(n.mode=20,6===e)break t;case 20:n.mode=21;case 21:if(g>=6&&_>=258){t.next_out=v,t.avail_out=_,t.next_in=p,t.avail_in=g,n.hold=b,n.bits=y,o(t,Z),v=t.next_out,d=t.output,_=t.avail_out,p=t.next_in,h=t.input,g=t.avail_in,b=n.hold,y=n.bits,n.mode===c&&(n.back=-1);break}for(n.back=0;j=(O=n.lencode[b&(1<>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>M)])>>>16&255,C=65535&O,!(M+(A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=M,y-=M,n.back+=M}if(b>>>=A,y-=A,n.back+=A,n.length=C,0===j){n.mode=26;break}if(32&j){n.back=-1,n.mode=c;break}if(64&j){t.msg="invalid literal/length code",n.mode=f;break}n.extra=15&j,n.mode=22;case 22:if(n.extra){for(z=n.extra;y>>=n.extra,y-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;j=(O=n.distcode[b&(1<>>16&255,C=65535&O,!((A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>M)])>>>16&255,C=65535&O,!(M+(A=O>>>24)<=y);){if(0===g)break t;g--,b+=h[p++]<>>=M,y-=M,n.back+=M}if(b>>>=A,y-=A,n.back+=A,64&j){t.msg="invalid distance code",n.mode=f;break}n.offset=C,n.extra=15&j,n.mode=24;case 24:if(n.extra){for(z=n.extra;y>>=n.extra,y-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=f;break}n.mode=25;case 25:if(0===_)break t;if(D=Z-_,n.offset>D){if((D=n.offset-D)>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=f;break}D>n.wnext?(D-=n.wnext,k=n.wsize-D):k=n.wnext-D,D>n.length&&(D=n.length),E=n.window}else E=d,k=v-n.offset,D=n.length;D>_&&(D=_),_-=D,n.length-=D;do{d[v++]=E[k++]}while(--D);0===n.length&&(n.mode=21);break;case 26:if(0===_)break t;d[v++]=n.length,_--,n.mode=21;break;case 27:if(n.wrap){for(;y<32;){if(0===g)break t;g--,b|=h[p++]<{"use strict";var r=n(49761),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],a=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],u=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(t,e,n,s,c,f,l,h){var d,p,v,g,_,b,y,m,x,w=h.bits,Z=0,D=0,k=0,E=0,A=0,j=0,C=0,M=0,F=0,B=0,S=null,N=0,T=new r.Buf16(16),z=new r.Buf16(16),O=null,R=0;for(Z=0;Z<=15;Z++)T[Z]=0;for(D=0;D=1&&0===T[E];E--);if(A>E&&(A=E),0===E)return c[f++]=20971520,c[f++]=20971520,h.bits=1,0;for(k=1;k0&&(0===t||1!==E))return-1;for(z[1]=0,Z=1;Z<15;Z++)z[Z+1]=z[Z]+T[Z];for(D=0;D852||2===t&&F>592)return 1;for(;;){y=Z-C,l[D]b?(m=O[R+l[D]],x=S[N+l[D]]):(m=96,x=0),d=1<>C)+(p-=d)]=y<<24|m<<16|x|0}while(0!==p);for(d=1<>=1;if(0!==d?(B&=d-1,B+=d):B=0,D++,0==--T[Z]){if(Z===E)break;Z=e[n+l[D]]}if(Z>A&&(B&g)!==v){for(0===C&&(C=A),_+=k,M=1<<(j=Z-C);j+C852||2===t&&F>592)return 1;c[v=B&g]=A<<24|j<<16|_-f|0}}return 0!==B&&(c[_+B]=Z-C<<24|64<<16|0),h.bits=A,0}},82950:t=>{"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},69564:(t,e,n)=>{"use strict";var r=n(49761);function i(t){for(var e=t.length;--e>=0;)t[e]=0}var a=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],o=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],s=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],c=new Array(576);i(c);var f=new Array(60);i(f);var l=new Array(512);i(l);var h=new Array(256);i(h);var d=new Array(29);i(d);var p,v,g,_=new Array(30);function b(t,e,n,r,i){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=t&&t.length}function y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function m(t){return t<256?l[t]:l[256+(t>>>7)]}function x(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function w(t,e,n){t.bi_valid>16-n?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=n-16):(t.bi_buf|=e<>>=1,n<<=1}while(--e>0);return n>>>1}function k(t,e,n){var r,i,a=new Array(16),o=0;for(r=1;r<=15;r++)a[r]=o=o+n[r-1]<<1;for(i=0;i<=e;i++){var u=t[2*i+1];0!==u&&(t[2*i]=D(a[u]++,u))}}function E(t){var e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function A(t){t.bi_valid>8?x(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function j(t,e,n,r){var i=2*e,a=2*n;return t[i]>1;n>=1;n--)C(t,a,n);i=s;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],C(t,a,1),r=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=r,a[2*i]=a[2*n]+a[2*r],t.depth[i]=(t.depth[n]>=t.depth[r]?t.depth[n]:t.depth[r])+1,a[2*n+1]=a[2*r+1]=i,t.heap[1]=i++,C(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var n,r,i,a,o,u,s=e.dyn_tree,c=e.max_code,f=e.stat_desc.static_tree,l=e.stat_desc.has_stree,h=e.stat_desc.extra_bits,d=e.stat_desc.extra_base,p=e.stat_desc.max_length,v=0;for(a=0;a<=15;a++)t.bl_count[a]=0;for(s[2*t.heap[t.heap_max]+1]=0,n=t.heap_max+1;n<573;n++)(a=s[2*s[2*(r=t.heap[n])+1]+1]+1)>p&&(a=p,v++),s[2*r+1]=a,r>c||(t.bl_count[a]++,o=0,r>=d&&(o=h[r-d]),u=s[2*r],t.opt_len+=u*(a+o),l&&(t.static_len+=u*(f[2*r+1]+o)));if(0!==v){do{for(a=p-1;0===t.bl_count[a];)a--;t.bl_count[a]--,t.bl_count[a+1]+=2,t.bl_count[p]--,v-=2}while(v>0);for(a=p;0!==a;a--)for(r=t.bl_count[a];0!==r;)(i=t.heap[--n])>c||(s[2*i+1]!==a&&(t.opt_len+=(a-s[2*i+1])*s[2*i],s[2*i+1]=a),r--)}}(t,e),k(a,c,t.bl_count)}function B(t,e,n){var r,i,a=-1,o=e[1],u=0,s=7,c=4;for(0===o&&(s=138,c=3),e[2*(n+1)+1]=65535,r=0;r<=n;r++)i=o,o=e[2*(r+1)+1],++u>=7;r<30;r++)for(_[r]=i<<7,t=0;t<1<0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,n=4093624447;for(e=0;e<=31;e++,n>>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),F(t,t.l_desc),F(t,t.d_desc),o=function(t){var e;for(B(t,t.dyn_ltree,t.l_desc.max_code),B(t,t.dyn_dtree,t.d_desc.max_code),F(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*s[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),i=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=i&&(i=a)):i=a=n+5,n+4<=i&&-1!==e?T(t,e,n,r):4===t.strategy||a===i?(w(t,2+(r?1:0),3),M(t,c,f)):(w(t,4+(r?1:0),3),function(t,e,n,r){var i;for(w(t,e-257,5),w(t,n-1,5),w(t,r-4,4),i=0;i>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&n,t.last_lit++,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(h[n]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.last_lit===t.lit_bufsize-1},e._tr_align=function(t){w(t,2,3),Z(t,256,c),function(t){16===t.bi_valid?(x(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},20744:t=>{"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}}]); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/zip.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/zip.js new file mode 100644 index 0000000000000000000000000000000000000000..972e24b264548c2d6d4d495b8327b8b3f4f27a7a --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/netron2/dist/zip.js @@ -0,0 +1 @@ +var zip=zip||{};zip.Archive=class{constructor(t){if(this._entries=[],t.length<4||80!=t[0]||75!=t[1])throw new zip.Error("Invalid Zip archive.");let e=null;for(let i=t.length-4;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3]){e=new zip.Reader(t,i+4,t.length);break}if(!e)throw new zip.Error("End of central directory not found.");for(e.skip(12),e.position=e.uint32();e.match([80,75,1,2]);)this._entries.push(new zip.Entry(e))}get entries(){return this._entries}},zip.Entry=class{constructor(t){if(t.uint16(),t.skip(2),this._flags=t.uint16(),1==(1&this._flags))throw new zip.Error("Encrypted entries not supported.");this._compressionMethod=t.uint16(),t.uint32(),t.uint32(),this._compressedSize=t.uint32(),this._size=t.uint32();let e=t.uint16(),i=t.uint16();const s=t.uint16();t.uint16(),t.uint16(),t.uint32();const r=t.uint32();t.skip(e),t.skip(i),t.bytes(s);const n=t.position;if(t.position=r,!t.match([80,75,3,4]))throw new zip.Error("Invalid local file header signature.");t.skip(22),e=t.uint16(),i=t.uint16();const o=t.bytes(e);this._name="";for(const t of o)this._name+=String.fromCharCode(t);t.skip(i),this._compressedData=t.bytes(this._compressedSize),t.position=n}get name(){return this._name}get data(){if(!this._data){switch(this._compressionMethod){case 0:if(this._size!=this._compressedSize)throw new zip.Error("Invalid compression size.");this._data=new Uint8Array(this._compressedData.length),this._data.set(this._compressedData);break;case 8:if(this._data=(new zip.Inflater).inflateRaw(this._compressedData),this._size!=this._data.length)throw new zip.Error("Invalid uncompressed size.");break;default:throw new zip.Error("Invalid compression method.")}delete this._size,delete this._compressedData}return this._data}},zip.HuffmanTree=class{constructor(){this.table=new Uint16Array(16),this.symbol=new Uint16Array(288),zip.HuffmanTree._offsets=zip.HuffmanTree._offsets||new Uint16Array(16)}build(t,e,i){for(let t=0;t<16;++t)this.table[t]=0;for(let s=0;s>>1){case 0:this._inflateUncompressedBlock(e,i);break;case 1:this._inflateBlockData(e,i,zip.HuffmanTree.staticLiteralLengthTree,zip.HuffmanTree.staticDistanceTree);break;case 2:this._decodeTrees(e,s,r),this._inflateBlockData(e,i,s,r);break;default:throw new zip.Error("Unknown block type.")}}while(0==(1&n));return i.merge()}_inflateUncompressedBlock(t,e){for(;t.data>8;)t.position--,t.data-=8;t.data=0;const i=t.uint16();if(i!==(65535&~t.uint16()))throw new zip.Error("Invalid uncompressed block length.");const s=t.bytes(i);e.push(s),i>32768?(e.buffer.set(s.subarray(s.length-32768,s.length),0),e.position=32768):(e.reset(),e.buffer.set(s,e.position),e.position+=s.length)}_decodeTrees(t,e,i){const s=t.bits(5)+257,r=t.bits(5)+1,n=t.bits(4)+4;for(let t=0;t<19;t++)zip.Inflater._lengths[t]=0;for(let e=0;e62464&&(e.position=n,e.push(new Uint8Array(r.subarray(o,n))),n=e.reset(),o=n);let a=t.symbol(i);if(256===a)return e.position=n,e.push(new Uint8Array(r.subarray(o,e.position))),void e.reset();if(a<256)r[n++]=a;else{a-=257;const e=t.bitsBase(zip.Inflater._lengthBits[a],zip.Inflater._lengthBase[a]),i=t.symbol(s);let o=n-t.bitsBase(zip.Inflater._distanceBits[i],zip.Inflater._distanceBase[i]);for(let t=0;t32768&&(this.buffer.set(this.buffer.subarray(this.position-32768,this.position),0),this.position=32768),this.position}push(t){this._blocks.push(t)}merge(){let t=0;for(const e of this._blocks)t+=e.length;const e=new Uint8Array(t);let i=0;for(const t of this._blocks)e.set(t,i),i+=t.length;return e}},zip.BitReader=class{constructor(t){this.buffer=t,this.position=0,this.data=0,this.value=0}bits(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,e}bitsBase(t,e){if(0==t)return e;for(;this.data<24;)this.value|=this.buffer[this.position++]<>>16-t;return this.value>>>=t,this.data-=t,i+e}bytes(t){const e=this.buffer.subarray(this.position,this.position+t);return this.position+=t,e}uint16(){const t=this.buffer[this.position]|this.buffer[this.position+1]<<8;return this.position+=2,t}symbol(t){for(;this.data<24;)this.value|=this.buffer[this.position++]<>>=1,s++,e+=n[s],i-=n[s]}while(i>=0);return this.value=r,this.data-=s,t.symbol[e+i]}},zip.Reader=class{constructor(t,e,i){this._buffer=t,this._position=e,this._end=i}match(t){if(this._position+t.length<=this._end)for(let e=0;e=0?t:this._end+t}peek(){return this._positionthis._end)throw new zip.Error("Data not available.");this._position+=t}bytes(t){if(this._position+t>this._end)throw new zip.Error("Data not available.");t=void 0===t?this._end:t;const e=this._buffer.subarray(this._position,this._position+t);return this._position+=t,e}uint16(){if(this._position+2>this._end)throw new zip.Error("Data not available.");const t=this._buffer[this._position]|this._buffer[this._position+1]<<8;return this._position+=2,t}uint32(){return this.uint16()|this.uint16()<<16}},zip.Error=class extends Error{constructor(t){super(t),this.name="Zip Error"}},"undefined"!=typeof module&&"object"==typeof module.exports&&(module.exports.Archive=zip.Archive,module.exports.Inflater=zip.Inflater); \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..66f6aca5f320396a436b341c587b14be6ef2612c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.html @@ -0,0 +1,2 @@ +
    \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0746b2013cc76316d8827ba880aea7f27dbb6f57 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/index.js @@ -0,0 +1,3 @@ +export async function render() { + document.location.href = 'index.html'; +} diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_embedding.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_embedding.html new file mode 100644 index 0000000000000000000000000000000000000000..e0c712c81bde1fd363046354e050fde46252a29d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_embedding.html @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_viewer_full.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_viewer_full.html new file mode 100644 index 0000000000000000000000000000000000000000..7f4f82846ad2272956495b69ab708ff5b094d6f1 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/trace/dist/trace_viewer_full.html @@ -0,0 +1,10177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7bca2b842ba91125fc97e1290d0226387104c5c6 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index.js @@ -0,0 +1,341 @@ + +let wasm; + +const heap = new Array(32).fill(undefined); + +heap.push(undefined, null, true, false); + +function getObject(idx) { return heap[idx]; } + +let WASM_VECTOR_LEN = 0; + +let cachegetUint8Memory0 = null; +function getUint8Memory0() { + if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) { + cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachegetUint8Memory0; +} + +let cachedTextEncoder = new TextEncoder('utf-8'); + +const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' + ? function (arg, view) { + return cachedTextEncoder.encodeInto(arg, view); +} + : function (arg, view) { + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length + }; +}); + +function passStringToWasm0(arg, malloc, realloc) { + + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length); + getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); + WASM_VECTOR_LEN = buf.length; + return ptr; + } + + let len = arg.length; + let ptr = malloc(len); + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7F) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, len = offset + arg.length * 3); + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; +} + +let cachegetInt32Memory0 = null; +function getInt32Memory0() { + if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) { + cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachegetInt32Memory0; +} + +let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); + +cachedTextDecoder.decode(); + +function getStringFromWasm0(ptr, len) { + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); +} + +let heap_next = heap.length; + +function addHeapObject(obj) { + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; + + heap[idx] = obj; + return idx; +} + +function dropObject(idx) { + if (idx < 36) return; + heap[idx] = heap_next; + heap_next = idx; +} + +function takeObject(idx) { + const ret = getObject(idx); + dropObject(idx); + return ret; +} + +function debugString(val) { + // primitive types + const type = typeof val; + if (type == 'number' || type == 'boolean' || val == null) { + return `${val}`; + } + if (type == 'string') { + return `"${val}"`; + } + if (type == 'symbol') { + const description = val.description; + if (description == null) { + return 'Symbol'; + } else { + return `Symbol(${description})`; + } + } + if (type == 'function') { + const name = val.name; + if (typeof name == 'string' && name.length > 0) { + return `Function(${name})`; + } else { + return 'Function'; + } + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = '['; + if (length > 0) { + debug += debugString(val[0]); + } + for(let i = 1; i < length; i++) { + debug += ', ' + debugString(val[i]); + } + debug += ']'; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == 'Object') { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return 'Object(' + JSON.stringify(val) + ')'; + } catch (_) { + return 'Object'; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; +} + +let stack_pointer = 32; + +function addBorrowedObject(obj) { + if (stack_pointer == 1) throw new Error('out of js stack'); + heap[--stack_pointer] = obj; + return stack_pointer; +} +/** +* @param {any} js_datasets +* @param {number} smoothing +* @returns {any} +*/ +export function scalar_transform(js_datasets, smoothing) { + try { + var ret = wasm.scalar_transform(addBorrowedObject(js_datasets), smoothing); + return takeObject(ret); + } finally { + heap[stack_pointer++] = undefined; + } +} + +/** +* @param {any} js_datasets +* @returns {any} +*/ +export function scalar_range(js_datasets) { + try { + var ret = wasm.scalar_range(addBorrowedObject(js_datasets)); + return takeObject(ret); + } finally { + heap[stack_pointer++] = undefined; + } +} + +/** +* @param {any} js_datasets +* @param {boolean} outlier +* @returns {any} +*/ +export function scalar_axis_range(js_datasets, outlier) { + try { + var ret = wasm.scalar_axis_range(addBorrowedObject(js_datasets), outlier); + return takeObject(ret); + } finally { + heap[stack_pointer++] = undefined; + } +} + +/** +* @param {any} js_data +* @param {string} mode +* @returns {any} +*/ +export function histogram_transform(js_data, mode) { + try { + var ptr0 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + var ret = wasm.histogram_transform(addBorrowedObject(js_data), ptr0, len0); + return takeObject(ret); + } finally { + heap[stack_pointer++] = undefined; + } +} + +/** +* @param {any} js_input +* @param {number} dim +* @param {number} n_components +* @returns {any} +*/ +export function high_dimensional_pca(js_input, dim, n_components) { + try { + var ret = wasm.high_dimensional_pca(addBorrowedObject(js_input), dim, n_components); + return takeObject(ret); + } finally { + heap[stack_pointer++] = undefined; + } +} + +async function load(module, imports) { + if (typeof Response === 'function' && module instanceof Response) { + + if (typeof WebAssembly.instantiateStreaming === 'function') { + try { + return await WebAssembly.instantiateStreaming(module, imports); + + } catch (e) { + if (module.headers.get('Content-Type') != 'application/wasm') { + console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); + + } else { + throw e; + } + } + } + + const bytes = await module.arrayBuffer(); + return await WebAssembly.instantiate(bytes, imports); + + } else { + + const instance = await WebAssembly.instantiate(module, imports); + + if (instance instanceof WebAssembly.Instance) { + return { instance, module }; + + } else { + return instance; + } + } +} + +async function init(input) { + if (typeof input === 'undefined') { + input = import.meta.url.replace(/\.js$/, '_bg.wasm'); + } + const imports = {}; + imports.wbg = {}; + imports.wbg.__wbindgen_json_serialize = function(arg0, arg1) { + const obj = getObject(arg1); + var ret = JSON.stringify(obj === undefined ? null : obj); + var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }; + imports.wbg.__wbindgen_string_new = function(arg0, arg1) { + var ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); + }; + imports.wbg.__wbg_log_cc6b9ddc6ca5449d = function(arg0) { + console.log(getObject(arg0)); + }; + imports.wbg.__wbindgen_object_drop_ref = function(arg0) { + takeObject(arg0); + }; + imports.wbg.__wbindgen_json_parse = function(arg0, arg1) { + var ret = JSON.parse(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); + }; + imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { + var ret = debugString(getObject(arg1)); + var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len0 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len0; + getInt32Memory0()[arg0 / 4 + 0] = ptr0; + }; + imports.wbg.__wbindgen_throw = function(arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); + }; + + if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) { + input = fetch(input); + } + + const { instance, module } = await load(await input, imports); + + wasm = instance.exports; + init.__wbindgen_wasm_module = module; + + return wasm; +} + +export default init; + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index_bg.wasm b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index_bg.wasm new file mode 100644 index 0000000000000000000000000000000000000000..9b0007a093843fb9d3bd0e386688bfb8b8d75c17 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/link/packages/wasm/dist/index_bg.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7254151da2dffbbab4748364017c1497d35255cfa052a71ffc270838d20aa2e +size 176920 diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/optimize-manifest.json b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/optimize-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..2cdcc72079bb2abeab9db26c6c27621d55899a2f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/optimize-manifest.json @@ -0,0 +1,156 @@ +{ + "imports": { + "/__snowpack__/link/packages/netron/dist/index.html": { + "entry": [ + "/__snowpack__/link/packages/netron/dist/index.d8acc26a33c3950d58c4.js", + "/__snowpack__/link/packages/netron/dist/shim.f615a7b13d08c028a2c9.js", + "/__snowpack__/link/packages/netron/dist/style.31d6cfe0d16ae931b73c.js", + "/__snowpack__/link/packages/netron/dist/vendors.6247f3ee105723ca1ab6.js" + ], + "css": [ + "/__snowpack__/link/packages/netron/dist/style.css" + ], + "js": [ + "/__snowpack__/link/packages/netron/dist/index.d8acc26a33c3950d58c4.js", + "/__snowpack__/link/packages/netron/dist/shim.f615a7b13d08c028a2c9.js", + "/__snowpack__/link/packages/netron/dist/style.31d6cfe0d16ae931b73c.js", + "/__snowpack__/link/packages/netron/dist/vendors.6247f3ee105723ca1ab6.js" + ] + }, + "/__snowpack__/link/packages/netron2/dist/index.html": { + "entry": [ + "/__snowpack__/link/packages/netron2/dist/index.89a9e0515adada0d3ac5.js", + "/__snowpack__/link/packages/netron2/dist/shim.90c09599987168babbcd.js", + "/__snowpack__/link/packages/netron2/dist/style.31d6cfe0d16ae931b73c.js", + "/__snowpack__/link/packages/netron2/dist/vendors.8575cdbcf0e4a1a337e2.js" + ], + "css": [ + "/__snowpack__/link/packages/netron2/dist/style.css" + ], + "js": [ + "/__snowpack__/link/packages/netron2/dist/index.89a9e0515adada0d3ac5.js", + "/__snowpack__/link/packages/netron2/dist/shim.90c09599987168babbcd.js", + "/__snowpack__/link/packages/netron2/dist/style.31d6cfe0d16ae931b73c.js", + "/__snowpack__/link/packages/netron2/dist/vendors.8575cdbcf0e4a1a337e2.js" + ] + }, + "/index.html": { + "entry": [ + "/_dist_/assets/js/compatibility.js", + "/_dist_/index.js" + ], + "css": [ + "/favicon.ico" + ], + "js": [ + "/__snowpack__/env.js", + "/__snowpack__/link/packages/icons/index.js", + "/__snowpack__/pkg/@tippyjs/react.js", + "/__snowpack__/pkg/antd/dist/antd.css.proxy.js", + "/__snowpack__/pkg/axios.js", + "/__snowpack__/pkg/classnames.js", + "/__snowpack__/pkg/common/_arrayMap-c3125c3a.js", + "/__snowpack__/pkg/common/_baseGetTag-3262967e.js", + "/__snowpack__/pkg/common/_commonjsHelpers-b3efd043.js", + "/__snowpack__/pkg/common/hoist-non-react-statics.cjs-01efe895.js", + "/__snowpack__/pkg/common/index-021016f6.js", + "/__snowpack__/pkg/common/index-3928d36b.js", + "/__snowpack__/pkg/common/index-55e7d60e.js", + "/__snowpack__/pkg/common/index-78959ebc.js", + "/__snowpack__/pkg/common/index-87351f60.js", + "/__snowpack__/pkg/common/index-b156b0b9.js", + "/__snowpack__/pkg/common/index-f7c80223.js", + "/__snowpack__/pkg/common/isArray-1ab33e59.js", + "/__snowpack__/pkg/common/isObjectLike-0219adc7.js", + "/__snowpack__/pkg/common/isSymbol-cf06cd7f.js", + "/__snowpack__/pkg/common/process-2545f00a.js", + "/__snowpack__/pkg/common/redux-ea100ce9.js", + "/__snowpack__/pkg/common/toString-31cf0354.js", + "/__snowpack__/pkg/common/unitless.browser.esm-319df2e6.js", + "/__snowpack__/pkg/eventemitter3.js", + "/__snowpack__/pkg/i18next-browser-languagedetector.js", + "/__snowpack__/pkg/i18next-fetch-backend.js", + "/__snowpack__/pkg/i18next.js", + "/__snowpack__/pkg/lodash.js", + "/__snowpack__/pkg/lodash/kebabCase.js", + "/__snowpack__/pkg/moment.js", + "/__snowpack__/pkg/nprogress.js", + "/__snowpack__/pkg/polished.js", + "/__snowpack__/pkg/query-string.js", + "/__snowpack__/pkg/react-dom.js", + "/__snowpack__/pkg/react-helmet.js", + "/__snowpack__/pkg/react-i18next.js", + "/__snowpack__/pkg/react-redux.js", + "/__snowpack__/pkg/react-router-dom.js", + "/__snowpack__/pkg/react-spinners/HashLoader.js", + "/__snowpack__/pkg/react-toastify.js", + "/__snowpack__/pkg/react-toastify/dist/ReactToastify.css.proxy.js", + "/__snowpack__/pkg/react.js", + "/__snowpack__/pkg/redux.js", + "/__snowpack__/pkg/styled-components.js", + "/__snowpack__/pkg/swr.js", + "/__snowpack__/pkg/tippyjs/animations/shift-away-subtle.css.proxy.js", + "/__snowpack__/pkg/tippyjs/dist/tippy.css.proxy.js", + "/_dist_/App.js", + "/_dist_/assets/images/logo.svg.proxy.js", + "/_dist_/assets/js/compatibility.js", + "/_dist_/components/BodyLoading.js", + "/_dist_/components/Content.js", + "/_dist_/components/Error.js", + "/_dist_/components/ErrorBoundary.js", + "/_dist_/components/Icon.js", + "/_dist_/components/Language.js", + "/_dist_/components/Navbar.js", + "/_dist_/components/ThemeToggle.js", + "/_dist_/hooks/useClassNames.js", + "/_dist_/hooks/useComponents.js", + "/_dist_/hooks/useRequest.js", + "/_dist_/index.js", + "/_dist_/pages/error.js", + "/_dist_/routes/index.js", + "/_dist_/store/graph/actions.js", + "/_dist_/store/graph/reducers.js", + "/_dist_/store/graph/selectors.js", + "/_dist_/store/graph/types.js", + "/_dist_/store/index.js", + "/_dist_/store/runs/actions.js", + "/_dist_/store/runs/reducers.js", + "/_dist_/store/runs/selectors.js", + "/_dist_/store/runs/types.js", + "/_dist_/store/theme/actions.js", + "/_dist_/store/theme/reducers.js", + "/_dist_/store/theme/selectors.js", + "/_dist_/store/theme/types.js", + "/_dist_/utils/event.js", + "/_dist_/utils/fetch.js", + "/_dist_/utils/i18n.js", + "/_dist_/utils/style.js", + "/_dist_/utils/theme.js" + ] + }, + "/static/index.html": { + "entry": [], + "css": [], + "js": [ + "https://www.gstatic.com/charts/loader.js" + ] + }, + "/static/trace_embedding.html": { + "entry": [], + "css": [ + "/static/trace_viewer_full.html" + ], + "js": [ + "https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.24/webcomponents.min.js" + ] + }, + "/static/trace_viewer_full.html": { + "entry": [], + "css": [], + "js": [] + } + }, + "generated": { + "preloadedCSS": "/imported-styles.css" + } +} \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@ant-design/icons.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@ant-design/icons.js new file mode 100644 index 0000000000000000000000000000000000000000..4acc7ee37300cbd3db632cf97af37c67cda7e8c3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@ant-design/icons.js @@ -0,0 +1 @@ +import{I as c,_ as e}from"../common/PlusOutlined-90dfc612.js";export{D as DownOutlined,P as PlusOutlined}from"../common/PlusOutlined-90dfc612.js";import{r as t}from"../common/index-78959ebc.js";import"../common/index-3928d36b.js";import"../common/_commonjsHelpers-b3efd043.js";var u={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"}}]},name:"delete",theme:"outlined"},a=function(l,i){return t.createElement(c,e(e({},l),{},{ref:i,icon:u}))};a.displayName="DeleteOutlined";var d=t.forwardRef(a),m={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M696 480H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h368c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8z"}},{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}}]},name:"minus-circle",theme:"outlined"},r=function(l,i){return t.createElement(c,e(e({},l),{},{ref:i,icon:m}))};r.displayName="MinusCircleOutlined";var v=t.forwardRef(r),f={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M696 480H544V328c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v152H328c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h152v152c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V544h152c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8z"}},{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}}]},name:"plus-circle",theme:"outlined"},o=function(l,i){return t.createElement(c,e(e({},l),{},{ref:i,icon:f}))};o.displayName="PlusCircleOutlined";var h=t.forwardRef(o),O={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M859.9 780H164.1c-4.5 0-8.1 3.6-8.1 8v60c0 4.4 3.6 8 8.1 8h695.8c4.5 0 8.1-3.6 8.1-8v-60c0-4.4-3.6-8-8.1-8zM505.7 669a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V176c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8z"}}]},name:"vertical-align-bottom",theme:"outlined"},s=function(l,i){return t.createElement(c,e(e({},l),{},{ref:i,icon:O}))};s.displayName="VerticalAlignBottomOutlined";var g=t.forwardRef(s);export{d as DeleteOutlined,v as MinusCircleOutlined,h as PlusCircleOutlined,g as VerticalAlignBottomOutlined}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-clipboard.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-clipboard.js new file mode 100644 index 0000000000000000000000000000000000000000..1daafb651cebf612743931449ab4367e8be03e61 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-clipboard.js @@ -0,0 +1 @@ +import{M as f,s as m,G as l,d as y,B as u}from"../common/html-43a4a009.js";class O{constructor(){this.cells=[]}copy(t,e,o={}){this.options=Object.assign({},o);const n=(f.isModel(e)?e:e.model).cloneSubGraph(t,o);this.cells=m(Object.keys(n).map(r=>n[r]),r=>r.isEdge()?2:1),this.serialize(o)}cut(t,e,o={}){this.copy(t,e,o),(l.isGraph(e)?e.model:e).batchUpdate("cut",()=>{t.forEach(n=>n.remove())})}paste(t,e={}){const o=Object.assign(Object.assign({},this.options),e),{offset:s,edgeProps:n,nodeProps:r}=o;let a=20,d=20;s&&(a=typeof s=="number"?s:s.dx,d=typeof s=="number"?s:s.dy),this.deserialize(o);const h=this.cells;h.forEach(c=>{c.model=null,c.removeProp("zIndex"),(a||d)&&c.translate(a,d),r&&c.isNode()&&c.prop(r),n&&c.isEdge()&&c.prop(n)});const b=l.isGraph(t)?t.model:t;return b.batchUpdate("paste",()=>{b.addCells(this.cells)}),this.copy(h,t,e),h}serialize(t){t.useLocalStorage!==!1&&p.save(this.cells)}deserialize(t){if(t.useLocalStorage){const e=p.fetch();e&&(this.cells=e)}}isEmpty(){return this.cells.length<=0}clean(){this.options={},this.cells=[],p.clean()}}var p;(function(i){const t=`${y.prefixCls}.clipboard.cells`;function e(n){if(window.localStorage){const r=n.map(a=>a.toJSON());localStorage.setItem(t,JSON.stringify(r))}}i.save=e;function o(){if(window.localStorage){const n=localStorage.getItem(t),r=n?JSON.parse(n):[];if(r)return f.fromJSON(r)}}i.fetch=o;function s(){window.localStorage&&localStorage.removeItem(t)}i.clean=s})(p||(p={})),l.prototype.isClipboardEnabled=function(){const i=this.getPlugin("clipboard");return i?i.isEnabled():!1},l.prototype.enableClipboard=function(){const i=this.getPlugin("clipboard");return i&&i.enable(),this},l.prototype.disableClipboard=function(){const i=this.getPlugin("clipboard");return i&&i.disable(),this},l.prototype.toggleClipboard=function(i){const t=this.getPlugin("clipboard");return t&&t.toggleEnabled(i),this},l.prototype.isClipboardEmpty=function(){const i=this.getPlugin("clipboard");return i?i.isEmpty():!0},l.prototype.getCellsInClipboard=function(){const i=this.getPlugin("clipboard");return i?i.getCellsInClipboard():[]},l.prototype.cleanClipboard=function(){const i=this.getPlugin("clipboard");return i&&i.clean(),this},l.prototype.copy=function(i,t){const e=this.getPlugin("clipboard");return e&&e.copy(i,t),this},l.prototype.cut=function(i,t){const e=this.getPlugin("clipboard");return e&&e.cut(i,t),this},l.prototype.paste=function(i,t){const e=this.getPlugin("clipboard");return e?e.paste(i,t):[]};var E=function(i,t,e,o){var s=arguments.length,n=s<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,e):o,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(i,t,e,o);else for(var a=i.length-1;a>=0;a--)(r=i[a])&&(n=(s<3?r(n):s>3?r(t,e,n):r(t,e))||n);return s>3&&n&&Object.defineProperty(t,e,n),n},j=function(i,t){var e={};for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&t.indexOf(o)<0&&(e[o]=i[o]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(i);s{G.downloadDataUri(a,e)},t)}exportJPEG(e="chart",t={}){this.toPNG(a=>{G.downloadDataUri(a,e)},t)}exportSVG(e="chart",t={}){this.toSVG(a=>{G.downloadDataUri(G.svgToDataUrl(a),e)},t)}toSVG(e,t={}){this.notify("before:export",t);const a=this.view.svg,o=E.create(a).clone();let m=o.node;const b=o.findOne(`.${this.view.prefixClassName("graph-svg-stage")}`),l=t.viewBox||this.graph.graphToLocal(this.graph.getContentBBox()),n=t.preserveDimensions;if(n){const i=typeof n=="boolean"?l:n;o.attr({width:i.width,height:i.height})}if(o.removeAttribute("style").attr("viewBox",[l.x,l.y,l.width,l.height].join(" ")),b.removeAttribute("transform"),t.copyStyles!==!1){const i=a.ownerDocument,h=Array.from(a.querySelectorAll("*")),g=Array.from(m.querySelectorAll("*")),f=i.styleSheets.length,P=[];for(let s=f-1;s>=0;s-=1)P[s]=i.styleSheets[s],i.styleSheets[s].disabled=!0;const w={};h.forEach((s,d)=>{const y=window.getComputedStyle(s,null),v={};Object.keys(y).forEach(x=>{v[x]=y.getPropertyValue(x)}),w[d]=v}),f!==i.styleSheets.length&&P.forEach((s,d)=>{i.styleSheets[d]=s});for(let s=0;s{const y=window.getComputedStyle(s,null),v=w[d],x={};Object.keys(y).forEach(S=>{!j(S)&&y.getPropertyValue(S)!==v[S]&&(x[S]=y.getPropertyValue(S))}),D[d]=x}),g.forEach((s,d)=>{U(s,D[d])})}const u=t.stylesheet;if(typeof u=="string"){const i=a.ownerDocument.implementation.createDocument(null,"xml",null).createCDATASection(u);o.prepend(E.create("style",{type:"text/css"},[i]))}const r=()=>{const i=t.beforeSerialize;if(typeof i=="function"){const g=A(i,this.graph,m);g instanceof SVGSVGElement&&(m=g)}const h=new XMLSerializer().serializeToString(m).replace(/ /g,"\xA0");this.notify("after:export",t),e(h)};if(t.serializeImages){const i=o.find("image").map(h=>new Promise(g=>{const f=h.attr("xlink:href")||h.attr("href");G.imageToDataUri(f,(P,w)=>{!P&&w&&h.attr("xlink:href",w),g()})}));Promise.all(i).then(r)}else r()}toDataURL(e,t){let a=t.viewBox||this.graph.getContentBBox();const o=z(t.padding);t.width&&t.height&&(o.left+o.right>=t.width&&(o.left=o.right=0),o.top+o.bottom>=t.height&&(o.top=o.bottom=0));const m=new V(-o.left,-o.top,o.left+o.right,o.top+o.bottom);if(t.width&&t.height){const r=a.width+o.left+o.right,i=a.height+o.top+o.bottom;m.scale(r/t.width,i/t.height)}a=V.create(a).moveAndExpand(m);const b=typeof t.width=="number"&&typeof t.height=="number"?{width:t.width,height:t.height}:a;let l=t.ratio?parseFloat(t.ratio):1;(!Number.isFinite(l)||l===0)&&(l=1);const n={width:Math.max(Math.round(b.width*l),1),height:Math.max(Math.round(b.height*l),1)};{const r=document.createElement("canvas"),i=r.getContext("2d");r.width=n.width,r.height=n.height;const h=n.width-1,g=n.height-1;i.fillStyle="rgb(1,1,1)",i.fillRect(h,g,1,1);const f=i.getImageData(h,g,1,1).data;if(f[0]!==1||f[1]!==1||f[2]!==1)throw new Error("size exceeded")}const u=new Image;u.onload=()=>{const r=document.createElement("canvas");r.width=n.width,r.height=n.height;const i=r.getContext("2d");i.fillStyle=t.backgroundColor||"white",i.fillRect(0,0,n.width,n.height);try{i.drawImage(u,0,0,n.width,n.height);const h=r.toDataURL(t.type,t.quality);e(h)}catch(h){}},this.toSVG(r=>{u.src=`data:image/svg+xml,${encodeURIComponent(r)}`},Object.assign(Object.assign({},t),{viewBox:a,serializeImages:!0,preserveDimensions:Object.assign({},n)}))}toPNG(e,t={}){this.toDataURL(e,Object.assign(Object.assign({},t),{type:"image/png"}))}toJPEG(e,t={}){this.toDataURL(e,Object.assign(Object.assign({},t),{type:"image/jpeg"}))}notify(e,t){this.trigger(e,t),this.graph.trigger(e,t)}}export{B as Export}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-history.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-history.js new file mode 100644 index 0000000000000000000000000000000000000000..77098d35aff37a379c71ba115ba5b4425ec5da91 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-history.js @@ -0,0 +1 @@ +import{h as B,j as S,o as O,k as C,l as E,t as k,m as I,p as P,q as R,r as L,G as f,B as v,g as y,M as N,u as b,v as _}from"../common/html-43a4a009.js";function z(s){var t=s==null?0:s.length;return t?B(s,1):[]}function M(s){return S(O(s,void 0,z),s+"")}function w(s,t,e,n){if(!C(s))return s;t=E(t,s);for(var a=-1,r=t.length,i=r-1,h=s;h!=null&&++a=0;h--)(i=s[h])&&(r=(a<3?i(r):a>3?i(t,e,r):i(t,e))||r);return a>3&&r&&Object.defineProperty(t,e,r),r};class p extends v{constructor(t){super();this.name="history",this.batchCommands=null,this.batchLevel=0,this.lastBatchIndex=-1,this.freezed=!1,this.handlers=[],this.options=l.getOptions(t),this.validator=new p.Validator({history:this,cancelInvalid:this.options.cancelInvalid})}init(t){this.graph=t,this.model=this.graph.model,this.clean(),this.startListening()}isEnabled(){return!this.disabled}enable(){this.disabled&&(this.options.enabled=!0)}disable(){this.disabled||(this.options.enabled=!1)}toggleEnabled(t){return t!=null?t!==this.isEnabled()&&(t?this.enable():this.disable()):this.isEnabled()?this.disable():this.enable(),this}undo(t={}){if(!this.disabled){const e=this.undoStack.pop();e&&(this.revertCommand(e,t),this.redoStack.push(e),this.notify("undo",e,t))}return this}redo(t={}){if(!this.disabled){const e=this.redoStack.pop();e&&(this.applyCommand(e,t),this.undoStack.push(e),this.notify("redo",e,t))}return this}cancel(t={}){if(!this.disabled){const e=this.undoStack.pop();e&&(this.revertCommand(e,t),this.redoStack=[],this.notify("cancel",e,t))}return this}canUndo(){return!this.disabled&&this.undoStack.length>0}canRedo(){return!this.disabled&&this.redoStack.length>0}clean(t={}){return this.undoStack=[],this.redoStack=[],this.notify("clean",null,t),this}get disabled(){return this.options.enabled!==!0}validate(t,...e){return this.validator.validate(t,...e),this}startListening(){this.model.on("batch:start",this.initBatchCommand,this),this.model.on("batch:stop",this.storeBatchCommand,this),this.options.eventNames&&this.options.eventNames.forEach((t,e)=>{this.handlers[e]=this.addCommand.bind(this,t),this.model.on(t,this.handlers[e])}),this.validator.on("invalid",t=>this.trigger("invalid",t))}stopListening(){this.model.off("batch:start",this.initBatchCommand,this),this.model.off("batch:stop",this.storeBatchCommand,this),this.options.eventNames&&(this.options.eventNames.forEach((t,e)=>{this.model.off(t,this.handlers[e])}),this.handlers.length=0),this.validator.off("invalid")}createCommand(t){return{batch:t?t.batch:!1,data:{}}}revertCommand(t,e){this.freezed=!0;const n=Array.isArray(t)?l.sortBatchCommands(t):[t];for(let a=n.length-1;a>=0;a-=1){const r=n[a],i=Object.assign(Object.assign({},e),x(r.options,this.options.revertOptionsList||[]));this.executeCommand(r,!0,i)}this.freezed=!1}applyCommand(t,e){this.freezed=!0;const n=Array.isArray(t)?l.sortBatchCommands(t):[t];for(let a=0;a=0&&(d||u)){const g=this.batchCommands.findIndex(m=>(h&&m.modelChange||m.data.id===i.id)&&m.event===t);g<0||l.isAddEvent(t)||l.isRemoveEvent(t)?o=this.createCommand({batch:!0}):(o=this.batchCommands[g],this.batchCommands.splice(g,1)),this.batchCommands.push(o),this.lastBatchIndex=this.batchCommands.length-1}}else o=this.createCommand({batch:!1});if(l.isAddEvent(t)||l.isRemoveEvent(t)){const d=o.data;return o.event=t,o.options=a,d.id=i.id,d.props=b(i.toJSON()),i.isEdge()?d.edge=!0:i.isNode()&&(d.node=!0),this.push(o,a)}if(l.isChangeEvent(t)){const d=e.key,u=o.data;return(!o.batch||!o.event)&&(o.event=t,o.options=a,u.key=d,u.prev==null&&(u.prev={}),u.prev[d]=b(i.previous(d)),h?o.modelChange=!0:u.id=i.id),u.next==null&&(u.next={}),u.next[d]=b(i.prop(d)),this.push(o,a)}const c=this.options.afterAddCommand;c&&y(c,this,t,e,o),this.push(o,a)}initBatchCommand(t){this.freezed||(this.batchCommands?this.batchLevel+=1:(this.batchCommands=[this.createCommand({batch:!0})],this.batchLevel=0,this.lastBatchIndex=-1))}storeBatchCommand(t){if(!this.freezed)if(this.batchCommands&&this.batchLevel<=0){const e=this.filterBatchCommand(this.batchCommands);e.length>0&&(this.redoStack=[],this.undoStack.push(e),this.consolidateCommands(),this.notify("add",e,t)),this.batchCommands=null,this.lastBatchIndex=-1,this.batchLevel=0}else this.batchCommands&&this.batchLevel>0&&(this.batchLevel-=1)}filterBatchCommand(t){let e=t.slice();const n=[];for(;e.length>0;){const a=e.shift(),r=a.event,i=a.data.id;if(r!=null&&(i!=null||a.modelChange)){if(l.isAddEvent(r)){const h=e.findIndex(o=>l.isRemoveEvent(o.event)&&o.data.id===i);if(h>=0){e=e.filter((o,c)=>hl.isAddEvent(o.event)&&o.data.id===i);if(h>=0){e.splice(h,1);continue}}else if(l.isChangeEvent(r)){const h=a.data;if(_(h.prev,h.next))continue}n.push(a)}}return n}notify(t,e,n){const a=e==null?null:Array.isArray(e)?e:[e];this.emit(t,{cmds:a,options:n}),this.graph.trigger(`history:${t}`,{cmds:a,options:n}),this.emit("change",{cmds:a,options:n}),this.graph.trigger("history:change",{cmds:a,options:n})}push(t,e){this.redoStack=[],t.batch?(this.lastBatchIndex=Math.max(this.lastBatchIndex,0),this.emit("batch",{cmd:t,options:e})):(this.undoStack.push(t),this.consolidateCommands(),this.notify("add",t,e))}consolidateCommands(){var t;const e=this.undoStack[this.undoStack.length-1],n=this.undoStack[this.undoStack.length-2];if(!Array.isArray(e))return;const a=new Set(e.map(i=>i.event));if(a.size!==2||!a.has("cell:change:parent")||!a.has("cell:change:children")||!e.every(i=>{var h;return i.batch&&((h=i.options)===null||h===void 0?void 0:h.ui)})||!Array.isArray(n)||n.length!==1)return;const r=n[0];r.event!=="cell:change:position"||!((t=r.options)===null||t===void 0?void 0:t.ui)||(n.push(...e),this.undoStack.pop())}dispose(){this.validator.dispose(),this.clean(),this.stopListening(),this.off()}}A([v.dispose()],p.prototype,"dispose",null),function(s){class t extends v{constructor(n){super();this.map={},this.command=n.history,this.cancelInvalid=n.cancelInvalid!==!1,this.command.on("add",this.onCommandAdded,this)}onCommandAdded({cmds:n}){return Array.isArray(n)?n.every(a=>this.isValidCommand(a)):this.isValidCommand(n)}isValidCommand(n){if(n.options&&n.options.validation===!1)return!0;const a=n.event&&this.map[n.event]||[];let r=null;return a.forEach(i=>{let h=0;const o=c=>{const d=i[h];h+=1;try{if(d)d(c,n,o);else{r=c;return}}catch(u){o(u)}};o(r)}),r?(this.cancelInvalid&&this.command.cancel(),this.emit("invalid",{err:r}),!1):!0}validate(n,...a){const r=Array.isArray(n)?n:n.split(/\s+/);return a.forEach(i=>{if(typeof i!="function")throw new Error(`${r.join(" ")} requires callback functions.`)}),r.forEach(i=>{this.map[i]==null&&(this.map[i]=[]),this.map[i].push(a)}),this}dispose(){this.command.off("add",this.onCommandAdded,this)}}A([v.dispose()],t.prototype,"dispose",null),s.Validator=t}(p||(p={}));var l;(function(s){function t(i){return i==="cell:added"}s.isAddEvent=t;function e(i){return i==="cell:removed"}s.isRemoveEvent=e;function n(i){return i!=null&&i.startsWith("cell:change:")}s.isChangeEvent=n;function a(i){const h=["cell:added","cell:removed","cell:change:*"],o=["batch:start","batch:stop"],c=i.eventNames?i.eventNames.filter(d=>!(s.isChangeEvent(d)||h.includes(d)||o.includes(d))):h;return Object.assign(Object.assign({},i),{eventNames:c,applyOptionsList:i.applyOptionsList||["propertyPath"],revertOptionsList:i.revertOptionsList||["propertyPath"]})}s.getOptions=a;function r(i){const h=[];for(let o=0,c=i.length;o":".","?":"/","|":"\\"},_={option:"alt",command:"meta",return:"enter",escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},A,m=1;m<20;++m)l[111+m]="f"+m;for(m=0;m<=9;++m)l[m+96]=m.toString();function S(t,e,a){if(t.addEventListener){t.addEventListener(e,a,!1);return}t.attachEvent("on"+e,a)}function j(t){if(t.type=="keypress"){var e=String.fromCharCode(t.which);return t.shiftKey||(e=e.toLowerCase()),e}return l[t.which]?l[t.which]:d[t.which]?d[t.which]:String.fromCharCode(t.which).toLowerCase()}function B(t,e){return t.sort().join(",")===e.sort().join(",")}function V(t){var e=[];return t.shiftKey&&e.push("shift"),t.altKey&&e.push("alt"),t.ctrlKey&&e.push("ctrl"),t.metaKey&&e.push("meta"),e}function U(t){if(t.preventDefault){t.preventDefault();return}t.returnValue=!1}function X(t){if(t.stopPropagation){t.stopPropagation();return}t.cancelBubble=!0}function x(t){return t=="shift"||t=="ctrl"||t=="alt"||t=="meta"}function Y(){if(!A){A={};for(var t in l)t>95&&t<112||l.hasOwnProperty(t)&&(A[l[t]]=t)}return A}function $(t,e,a){return a||(a=Y()[t]?"keydown":"keypress"),a=="keypress"&&e.length&&(a="keydown"),a}function z(t){return t==="+"?["+"]:(t=t.replace(/\+{2}/g,"+plus"),t.split("+"))}function R(t,e){var a,b,E,K=[];for(a=z(t),E=0;E1){Q(i,k,u,p);return}c=R(i,p),e._callbacks[c.key]=e._callbacks[c.key]||[],F(c.key,c.modifiers,{type:c.action},o,i,h),e._callbacks[c.key][o?"unshift":"push"]({callback:u,modifiers:c.modifiers,action:c.action,seq:o,level:h,combo:i})}e._bindMultiple=function(i,u,p){for(var o=0;o-1||D(e,a.target))return!1;if("composedPath"in t&&typeof t.composedPath=="function"){var b=t.composedPath()[0];b!==t.target&&(e=b)}return e.tagName=="INPUT"||e.tagName=="SELECT"||e.tagName=="TEXTAREA"||e.isContentEditable},g.prototype.handleKey=function(){var t=this;return t._handleKey.apply(t,arguments)},g.addKeycodes=function(t){for(var e in t)t.hasOwnProperty(e)&&(l[e]=t[e]);A=null},g.init=function(){var t=g(n);for(var e in t)e.charAt(0)!=="_"&&(g[e]=function(a){return function(){return t[a].apply(t,arguments)}}(e))},g.init(),r.Mousetrap=g,f.exports&&(f.exports=g),typeof s=="function"&&s.amd&&s(function(){return g})})(typeof window!="undefined"?window:null,typeof window!="undefined"?document:null)}),nt=function(f,r,n,s){var l=arguments.length,d=l<3?r:s===null?s=Object.getOwnPropertyDescriptor(r,n):s,y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(f,r,n,s);else for(var _=f.length-1;_>=0;_--)(y=f[_])&&(d=(l<3?y(d):l>3?y(r,n,d):y(r,n))||d);return l>3&&d&&Object.defineProperty(r,n,d),d};class C extends I{get graph(){return this.options.graph}constructor(r){super();this.options=r;const n=this.graph.getPlugin("scroller");this.container=n?n.container:this.graph.container,r.global?this.target=document:(this.target=this.container,this.disabled||this.target.setAttribute("tabindex","-1"),this.graph.on("cell:mouseup",this.focus,this),this.graph.on("blank:mouseup",this.focus,this)),this.mousetrap=C.createMousetrap(this)}get disabled(){return this.options.enabled!==!0}enable(){this.disabled&&(this.options.enabled=!0,this.target instanceof HTMLElement&&this.target.setAttribute("tabindex","-1"))}disable(){this.disabled||(this.options.enabled=!1,this.target instanceof HTMLElement&&this.target.removeAttribute("tabindex"))}on(r,n,s){this.mousetrap.bind(this.getKeys(r),n,s)}off(r,n){this.mousetrap.unbind(this.getKeys(r),n)}focus(r){if(this.isInputEvent(r.e))return;this.target.focus({preventScroll:!0})}getKeys(r){return(Array.isArray(r)?r:[r]).map(n=>this.formatkey(n))}formatkey(r){const n=r.toLowerCase().replace(/\s/g,"").replace("delete","del").replace("cmd","command"),s=this.options.format;return s?H(s,this.graph,n):n}isGraphEvent(r){const n=r.target,s=r.currentTarget;return n?n===this.target||s===this.target||n===document.body?!0:tt(this.container,n):!1}isInputEvent(r){var n;const s=r.target,l=(n=s==null?void 0:s.tagName)===null||n===void 0?void 0:n.toLowerCase();return["input","textarea"].includes(l)}isEnabledForEvent(r){const n=!this.disabled&&this.isGraphEvent(r),s=this.isInputEvent(r);if(n){const l=r.keyCode||r.which;if(s&&(l===8||l===46))return!1;if(this.options.guard)return H(this.options.guard,this.graph,r)}return n}dispose(){this.mousetrap.reset()}}nt([I.dispose()],C.prototype,"dispose",null),function(f){function r(n){const s=new rt(n.target),l=s.stopCallback;return s.stopCallback=(d,y,_)=>n.isEnabledForEvent(d)?l?l.call(s,d,y,_):!1:!0,s}f.createMousetrap=r}(C||(C={})),M.prototype.isKeyboardEnabled=function(){const f=this.getPlugin("keyboard");return f?f.isEnabled():!1},M.prototype.enableKeyboard=function(){const f=this.getPlugin("keyboard");return f&&f.enable(),this},M.prototype.disableKeyboard=function(){const f=this.getPlugin("keyboard");return f&&f.disable(),this},M.prototype.toggleKeyboard=function(f){const r=this.getPlugin("keyboard");return r&&r.toggleEnabled(f),this},M.prototype.bindKey=function(f,r,n){const s=this.getPlugin("keyboard");return s&&s.bindKey(f,r,n),this},M.prototype.unbindKey=function(f,r){const n=this.getPlugin("keyboard");return n&&n.unbindKey(f,r),this};var it=function(f,r,n,s){var l=arguments.length,d=l<3?r:s===null?s=Object.getOwnPropertyDescriptor(r,n):s,y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(f,r,n,s);else for(var _=f.length-1;_>=0;_--)(y=f[_])&&(d=(l<3?y(d):l>3?y(r,n,d):y(r,n))||d);return l>3&&d&&Object.defineProperty(r,n,d),d};class N extends I{constructor(r){super();this.name="keyboard",this.options=r}init(r){this.keyboardImpl=new C(Object.assign(Object.assign({},this.options),{graph:r}))}isEnabled(){return!this.keyboardImpl.disabled}enable(){return this.keyboardImpl.enable(),this}disable(){return this.keyboardImpl.disable(),this}toggleEnabled(r){return r!=null?r!==this.isEnabled()&&(r?this.enable():this.disable()):this.isEnabled()?this.disable():this.enable(),this}bindKey(r,n,s){return this.keyboardImpl.on(r,n,s),this}unbindKey(r,n){return this.keyboardImpl.off(r,n),this}dispose(){this.keyboardImpl.dispose()}}it([I.dispose()],N.prototype,"dispose",null);export{N as Keyboard}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-snapline.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-snapline.js new file mode 100644 index 0000000000000000000000000000000000000000..8685721fd975ab942f99d0535439ae8a8e3d0d24 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6-plugin-snapline.js @@ -0,0 +1,14 @@ +import{y as _,V as D,g as $,A as H,s as X,f as Y,z as j,G as y,w as G,F as k,J as K}from"../common/html-43a4a009.js";var Q=function(i,t,e,n){var s=arguments.length,o=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(i,t,e,n);else for(var c=i.length-1;c>=0;c--)(l=i[c])&&(o=(s<3?l(o):s>3?l(t,e,o):l(t,e))||o);return s>3&&o&&Object.defineProperty(t,e,o),o},U=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{if(this.isIgnored(t,a))return!1;const g=a.getBBox().bbox(a.getAngle()),T=g.getTopLeft(),E=g.getBottomRight(),W={vertical:[T.x,E.x],horizontal:[T.y,E.y]},I={};return Object.keys(W).forEach(q=>{const N=q,J=W[N].map(A=>({position:A,distance:Math.abs(A-p[N])})).filter(A=>A.distance<=C);I[N]=X(J,A=>A.distance)}),u==null&&I.vertical.length>0&&(u=I.vertical[0].position,P=Math.min(o.y,g.y),O=Math.max(c.y,E.y)-P),r==null&&I.horizontal.length>0&&(r=I.horizontal[0].position,R=Math.min(o.x,g.x),x=Math.max(c.x,E.x)-R),u!=null&&r!=null}),this.hide();let z=0,b=0;(r!=null||u!=null)&&(u!=null&&(z=B.indexOf("right")!==-1?u-c.x:l.x-u),r!=null&&(b=B.indexOf("bottom")!==-1?r-c.y:l.y-r));let M=0,w=0;if(v%90==0)v===90||v===270?(M=b,w=z):(M=z,w=b);else{const a=v>=0&&v<90?1:v>=90&&v<180?4:v>=180&&v<270?3:2;r!=null&&u!=null&&(zS&&(f=Math.max(f,e.minWidth)),e.minHeight&&e.minHeight>S&&(m=Math.max(m,e.minHeight)),e.maxWidth&&(f=Math.min(f,e.maxWidth)),e.maxHeight&&(m=Math.min(m,e.maxHeight)),e.preserveAspectRatio&&(w1&&Math.abs(h.width+h.x-u)>1&&(u=void 0),r&&Math.abs(h.y-r)>1&&Math.abs(h.height+h.y-r)>1&&(r=void 0),this.update({verticalLeft:u,verticalTop:P,verticalHeight:O,horizontalTop:r,horizontalLeft:R,horizontalWidth:x})}}}snapOnMoving({view:t,e,x:n,y:s}){const o=t.getEventData(e).delegatedView||t;if(!this.isNodeMovable(o))return;const l=o.cell,c=l.getSize(),v=l.getPosition(),C=new Y(n-this.offset.x,s-this.offset.y,c.width,c.height),u=l.getAngle(),P=C.getCenter(),O=C.bbox(u),r=O.getTopLeft(),R=O.getBottomRight(),x=this.options.tolerance||0;let p,L,B,d,z,b,M=0,w=0;if(this.model.getNodes().some(S=>{if(this.isIgnored(l,S))return!1;const f=S.getBBox().bbox(S.getAngle()),m=f.getCenter(),h=f.getTopLeft(),a=f.getBottomRight();return p==null&&(Math.abs(m.x-P.x)typeof n=="string"?t.shape===n:t.id===n.id):typeof e=="function"?$(e,this.graph,t):!0}update(t){if(t.horizontalTop){const e=this.graph.localToGraph(new j(t.horizontalLeft,t.horizontalTop)),n=this.graph.localToGraph(new j(t.horizontalLeft+t.horizontalWidth,t.horizontalTop));this.horizontal.setAttributes({x1:this.options.sharp?`${e.x}`:"0",y1:`${e.y}`,x2:this.options.sharp?`${n.x}`:"100%",y2:`${n.y}`,display:"inherit"})}else this.horizontal.setAttribute("display","none");if(t.verticalLeft){const e=this.graph.localToGraph(new j(t.verticalLeft,t.verticalTop)),n=this.graph.localToGraph(new j(t.verticalLeft,t.verticalTop+t.verticalHeight));this.vertical.setAttributes({x1:`${e.x}`,y1:this.options.sharp?`${e.y}`:"0",x2:`${n.x}`,y2:this.options.sharp?`${n.y}`:"100%",display:"inherit"})}else this.vertical.setAttribute("display","none");this.show()}resetTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}show(){return this.resetTimer(),this.container.parentNode==null&&this.graph.container.appendChild(this.container),this}hide(){this.resetTimer(),this.vertical.setAttribute("display","none"),this.horizontal.setAttribute("display","none");const t=this.options.clean,e=typeof t=="number"?t:t!==!1?3e3:0;return e>0&&(this.timer=window.setTimeout(()=>{this.container.parentNode!==null&&this.unmount()},e)),this}onRemove(){this.stopListening(),this.hide()}dispose(){this.remove()}}Q([_.dispose()],F.prototype,"dispose",null);const Z=`.x6-widget-snapline { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + pointer-events: none; +} +.x6-widget-snapline-vertical, +.x6-widget-snapline-horizontal { + stroke: #2ecc71; + stroke-width: 1px; +} +`;y.prototype.isSnaplineEnabled=function(){const i=this.getPlugin("snapline");return i?i.isEnabled():!1},y.prototype.enableSnapline=function(){const i=this.getPlugin("snapline");return i&&i.enable(),this},y.prototype.disableSnapline=function(){const i=this.getPlugin("snapline");return i&&i.disable(),this},y.prototype.toggleSnapline=function(){const i=this.getPlugin("snapline");return i&&i.toggleEnabled(),this},y.prototype.hideSnapline=function(){const i=this.getPlugin("snapline");return i&&i.hide(),this},y.prototype.setSnaplineFilter=function(i){const t=this.getPlugin("snapline");return t&&t.setFilter(i),this},y.prototype.isSnaplineOnResizingEnabled=function(){const i=this.getPlugin("snapline");return i?i.isOnResizingEnabled():!1},y.prototype.enableSnaplineOnResizing=function(){const i=this.getPlugin("snapline");return i&&i.enableOnResizing(),this},y.prototype.disableSnaplineOnResizing=function(){const i=this.getPlugin("snapline");return i&&i.disableOnResizing(),this},y.prototype.toggleSnaplineOnResizing=function(i){const t=this.getPlugin("snapline");return t&&t.toggleOnResizing(i),this},y.prototype.isSharpSnapline=function(){const i=this.getPlugin("snapline");return i?i.isSharp():!1},y.prototype.enableSharpSnapline=function(){const i=this.getPlugin("snapline");return i&&i.enableSharp(),this},y.prototype.disableSharpSnapline=function(){const i=this.getPlugin("snapline");return i&&i.disableSharp(),this},y.prototype.toggleSharpSnapline=function(i){const t=this.getPlugin("snapline");return t&&t.toggleSharp(i),this},y.prototype.getSnaplineTolerance=function(){const i=this.getPlugin("snapline");if(i)return i.getTolerance()},y.prototype.setSnaplineTolerance=function(i){const t=this.getPlugin("snapline");return t&&t.setTolerance(i),this};var tt=function(i,t,e,n){var s=arguments.length,o=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(i,t,e,n);else for(var c=i.length-1;c>=0;c--)(l=i[c])&&(o=(s<3?l(o):s>3?l(t,e,o):l(t,e))||o);return s>3&&o&&Object.defineProperty(t,e,o),o};class V extends G{constructor(t){super();this.options=t,this.name="snapline",k(this.name,Z)}init(t){this.snaplineImpl=new F(Object.assign(Object.assign({},this.options),{graph:t}))}isEnabled(){return!this.snaplineImpl.disabled}enable(){return this.snaplineImpl.enable(),this}disable(){return this.snaplineImpl.disable(),this}toggleEnabled(t){if(t!=null)t!==this.isEnabled()&&(t?this.enable():this.disable());else return this.isEnabled()?this.disable():this.enable(),this}hide(){return this.snaplineImpl.hide(),this}setFilter(t){return this.snaplineImpl.setFilter(t),this}isOnResizingEnabled(){return this.snaplineImpl.options.resizing===!0}enableOnResizing(){return this.snaplineImpl.options.resizing=!0,this}disableOnResizing(){return this.snaplineImpl.options.resizing=!1,this}toggleOnResizing(t){return t!=null?t!==this.isOnResizingEnabled()&&(t?this.enableOnResizing():this.disableOnResizing()):this.isOnResizingEnabled()?this.disableOnResizing():this.enableOnResizing(),this}isSharp(){return this.snaplineImpl.options.sharp===!0}enableSharp(){return this.snaplineImpl.options.sharp=!0,this}disableSharp(){return this.snaplineImpl.options.sharp=!1,this}toggleSharp(t){return t!=null?t!==this.isSharp()&&(t?this.enableSharp():this.disableSharp()):this.isSharp()?this.disableSharp():this.enableSharp(),this}getTolerance(){return this.snaplineImpl.options.tolerance}setTolerance(t){return this.snaplineImpl.options.tolerance=t,this}captureCursorOffset(t){this.snaplineImpl.captureCursorOffset(t)}snapOnMoving(t){this.snaplineImpl.snapOnMoving(t)}dispose(){this.snaplineImpl.dispose(),K(this.name)}}tt([G.dispose()],V.prototype,"dispose",null);export{V as Snapline}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6.js new file mode 100644 index 0000000000000000000000000000000000000000..71a0f08dba213235e946172061ea0526425e44b0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@antv/x6.js @@ -0,0 +1 @@ +import{R as a,E as e,a as o,P as l,b as s,c as t,T as r,I as m,C as c,H as n}from"../common/html-43a4a009.js";export{G as Graph}from"../common/html-43a4a009.js";var i=Object.freeze({__proto__:null,Rect:a,Edge:e,Ellipse:o,Polygon:l,Polyline:s,Path:t,TextBlock:r,Image:m,Circle:c,get HTML(){return n}});export{i as Shape}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@material-ui/core/ClickAwayListener.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@material-ui/core/ClickAwayListener.js new file mode 100644 index 0000000000000000000000000000000000000000..78d5a1608696d3cf5a40a4e98685ff6f083e0624 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@material-ui/core/ClickAwayListener.js @@ -0,0 +1 @@ +import{c as s,g as H}from"../../common/_commonjsHelpers-b3efd043.js";import{r as k}from"../../common/index-78959ebc.js";import{r as $}from"../../common/index-f7c80223.js";import{p as N}from"../../common/index-55e7d60e.js";var E=s(function(n){function t(e){return e&&e.__esModule?e:{default:e}}n.exports=t,n.exports.__esModule=!0,n.exports.default=n.exports}),j=s(function(n){function t(e){return n.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u},n.exports.__esModule=!0,n.exports.default=n.exports,t(e)}n.exports=t,n.exports.__esModule=!0,n.exports.default=n.exports}),O=s(function(n){var t=j.default;function e(r){if(typeof WeakMap!="function")return null;var o=new WeakMap,a=new WeakMap;return(e=function(_){return _?a:o})(r)}function u(r,o){if(!o&&r&&r.__esModule)return r;if(r===null||t(r)!=="object"&&typeof r!="function")return{default:r};var a=e(o);if(a&&a.has(r))return a.get(r);var f={},_=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var d in r)if(d!=="default"&&Object.prototype.hasOwnProperty.call(r,d)){var m=_?Object.getOwnPropertyDescriptor(r,d):null;m&&(m.get||m.set)?Object.defineProperty(f,d,m):f[d]=r[d]}return f.default=r,a&&a.set(r,f),f}n.exports=u,n.exports.__esModule=!0,n.exports.default=n.exports}),I=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=e;function e(u){return u&&u.ownerDocument||document}}),X=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=e;function e(u,r){typeof u=="function"?u(r):u&&(u.current=r)}}),Y=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var e=O(k),u=E(X);function r(o,a){return e.useMemo(function(){return o==null&&a==null?null:function(f){(0,u.default)(o,f),(0,u.default)(a,f)}},[o,a])}}),z=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var e=O(k),u=typeof window!="undefined"?e.useLayoutEffect:e.useEffect;function r(o){var a=e.useRef(o);return u(function(){a.current=o}),e.useCallback(function(){return a.current.apply(void 0,arguments)},[])}}),G=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var e=O(k),u=O($),r=E(N),o=E(I),a=E(Y),f=E(z);function _(l){return l.substring(2).toLowerCase()}function d(l){return document.documentElement.clientWidth-1;else{var w=(0,o.default)(p.current);v=!w.documentElement.contains(c.target)||p.current.contains(c.target)}!v&&(W||!i)&&q(c)}}),S=function(i){return function(v){P.current=!0;var w=M.props[i];w&&w(v)}},g={ref:F};return R!==!1&&(g[R]=S(R)),e.useEffect(function(){if(R!==!1){var c=_(R),i=(0,o.default)(p.current),v=function(){b.current=!0};return i.addEventListener(c,h),i.addEventListener("touchmove",v),function(){i.removeEventListener(c,h),i.removeEventListener("touchmove",v)}}},[h,R]),y!==!1&&(g[y]=S(y)),e.useEffect(function(){if(y!==!1){var c=_(y),i=(0,o.default)(p.current);return i.addEventListener(c,h),function(){i.removeEventListener(c,h)}}},[h,y]),e.createElement(e.Fragment,null,e.cloneElement(M,g))}var T=m;t.default=T}),J=s(function(n,t){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return e.default}});var e=E(G)}),K=H(J);export default K; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@tippyjs/react.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@tippyjs/react.js new file mode 100644 index 0000000000000000000000000000000000000000..485306b832e6288f2cafa3c126f3851d2b65867d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/@tippyjs/react.js @@ -0,0 +1 @@ +import{r as X}from"../common/index-78959ebc.js";import{r as mr}from"../common/index-f7c80223.js";import"../common/_commonjsHelpers-b3efd043.js";var Y="top",K="bottom",J="right",G="left",et="auto",Ce=[Y,K,J,G],be="start",tt="end",hr="clippingParents",yt="viewport",Se="popper",gr="reference",wt=Ce.reduce(function(e,t){return e.concat([t+"-"+be,t+"-"+tt])},[]),Ot=[].concat(Ce,[et]).reduce(function(e,t){return e.concat([t,t+"-"+be,t+"-"+tt])},[]),br="beforeRead",yr="read",wr="afterRead",Or="beforeMain",xr="main",Er="afterMain",Ar="beforeWrite",Tr="write",Dr="afterWrite",Cr=[br,yr,wr,Or,xr,Er,Ar,Tr,Dr];function re(e){return e?(e.nodeName||"").toLowerCase():null}function Q(e){if(e==null)return window;if(e.toString()!=="[object Window]"){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function Le(e){var t=Q(e).Element;return e instanceof t||e instanceof Element}function Z(e){var t=Q(e).HTMLElement;return e instanceof t||e instanceof HTMLElement}function xt(e){if(typeof ShadowRoot=="undefined")return!1;var t=Q(e).ShadowRoot;return e instanceof t||e instanceof ShadowRoot}function Sr(e){var t=e.state;Object.keys(t.elements).forEach(function(r){var n=t.styles[r]||{},o=t.attributes[r]||{},a=t.elements[r];!Z(a)||!re(a)||(Object.assign(a.style,n),Object.keys(o).forEach(function(u){var f=o[u];f===!1?a.removeAttribute(u):a.setAttribute(u,f===!0?"":f)}))})}function Lr(e){var t=e.state,r={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,r.popper),t.styles=r,t.elements.arrow&&Object.assign(t.elements.arrow.style,r.arrow),function(){Object.keys(t.elements).forEach(function(n){var o=t.elements[n],a=t.attributes[n]||{},u=Object.keys(t.styles.hasOwnProperty(n)?t.styles[n]:r[n]),f=u.reduce(function(c,d){return c[d]="",c},{});!Z(o)||!re(o)||(Object.assign(o.style,f),Object.keys(a).forEach(function(c){o.removeAttribute(c)}))})}}var Et={name:"applyStyles",enabled:!0,phase:"write",fn:Sr,effect:Lr,requires:["computeStyles"]};function ne(e){return e.split("-")[0]}function ye(e){var t=e.getBoundingClientRect();return{width:t.width,height:t.height,top:t.top,right:t.right,bottom:t.bottom,left:t.left,x:t.left,y:t.top}}function rt(e){var t=ye(e),r=e.offsetWidth,n=e.offsetHeight;return Math.abs(t.width-r)<=1&&(r=t.width),Math.abs(t.height-n)<=1&&(n=t.height),{x:e.offsetLeft,y:e.offsetTop,width:r,height:n}}function At(e,t){var r=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(r&&xt(r)){var n=t;do{if(n&&e.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function se(e){return Q(e).getComputedStyle(e)}function $r(e){return["table","td","th"].indexOf(re(e))>=0}function ce(e){return((Le(e)?e.ownerDocument:e.document)||window.document).documentElement}function Fe(e){return re(e)==="html"?e:e.assignedSlot||e.parentNode||(xt(e)?e.host:null)||ce(e)}function Tt(e){return!Z(e)||se(e).position==="fixed"?null:e.offsetParent}function Rr(e){var t=navigator.userAgent.toLowerCase().indexOf("firefox")!==-1,r=navigator.userAgent.indexOf("Trident")!==-1;if(r&&Z(e)){var n=se(e);if(n.position==="fixed")return null}for(var o=Fe(e);Z(o)&&["html","body"].indexOf(re(o))<0;){var a=se(o);if(a.transform!=="none"||a.perspective!=="none"||a.contain==="paint"||["transform","perspective"].indexOf(a.willChange)!==-1||t&&a.willChange==="filter"||t&&a.filter&&a.filter!=="none")return o;o=o.parentNode}return null}function $e(e){for(var t=Q(e),r=Tt(e);r&&$r(r)&&se(r).position==="static";)r=Tt(r);return r&&(re(r)==="html"||re(r)==="body"&&se(r).position==="static")?t:r||Rr(e)||t}function nt(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}var pe=Math.max,Re=Math.min,_e=Math.round;function qe(e,t,r){return pe(e,Re(t,r))}function Dt(){return{top:0,right:0,bottom:0,left:0}}function Ct(e){return Object.assign({},Dt(),e)}function St(e,t){return t.reduce(function(r,n){return r[n]=e,r},{})}var jr=function(t,r){return t=typeof t=="function"?t(Object.assign({},r.rects,{placement:r.placement})):t,Ct(typeof t!="number"?t:St(t,Ce))};function Mr(e){var t,r=e.state,n=e.name,o=e.options,a=r.elements.arrow,u=r.modifiersData.popperOffsets,f=ne(r.placement),c=nt(f),d=[G,J].indexOf(f)>=0,p=d?"height":"width";if(!(!a||!u)){var w=jr(o.padding,r),A=rt(a),b=c==="y"?Y:G,h=c==="y"?K:J,x=r.rects.reference[p]+r.rects.reference[c]-u[c]-r.rects.popper[p],g=u[c]-r.rects.reference[c],T=$e(a),E=T?c==="y"?T.clientHeight||0:T.clientWidth||0:0,M=x/2-g/2,i=w[b],$=E-A[p]-w[h],l=E/2-A[p]/2+M,R=qe(i,l,$),L=c;r.modifiersData[n]=(t={},t[L]=R,t.centerOffset=R-l,t)}}function Pr(e){var t=e.state,r=e.options,n=r.element,o=n===void 0?"[data-popper-arrow]":n;o!=null&&(typeof o=="string"&&(o=t.elements.popper.querySelector(o),!o)||!At(t.elements.popper,o)||(t.elements.arrow=o))}var Br={name:"arrow",enabled:!0,phase:"main",fn:Mr,effect:Pr,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},kr={top:"auto",right:"auto",bottom:"auto",left:"auto"};function Hr(e){var t=e.x,r=e.y,n=window,o=n.devicePixelRatio||1;return{x:_e(_e(t*o)/o)||0,y:_e(_e(r*o)/o)||0}}function Lt(e){var t,r=e.popper,n=e.popperRect,o=e.placement,a=e.offsets,u=e.position,f=e.gpuAcceleration,c=e.adaptive,d=e.roundOffsets,p=d===!0?Hr(a):typeof d=="function"?d(a):a,w=p.x,A=w===void 0?0:w,b=p.y,h=b===void 0?0:b,x=a.hasOwnProperty("x"),g=a.hasOwnProperty("y"),T=G,E=Y,M=window;if(c){var i=$e(r),$="clientHeight",l="clientWidth";i===Q(r)&&(i=ce(r),se(i).position!=="static"&&($="scrollHeight",l="scrollWidth")),i=i,o===Y&&(E=K,h-=i[$]-n.height,h*=f?1:-1),o===G&&(T=J,A-=i[l]-n.width,A*=f?1:-1)}var R=Object.assign({position:u},c&&kr);if(f){var L;return Object.assign({},R,(L={},L[E]=g?"0":"",L[T]=x?"0":"",L.transform=(M.devicePixelRatio||1)<2?"translate("+A+"px, "+h+"px)":"translate3d("+A+"px, "+h+"px, 0)",L))}return Object.assign({},R,(t={},t[E]=g?h+"px":"",t[T]=x?A+"px":"",t.transform="",t))}function Ir(e){var t=e.state,r=e.options,n=r.gpuAcceleration,o=n===void 0?!0:n,a=r.adaptive,u=a===void 0?!0:a,f=r.roundOffsets,c=f===void 0?!0:f,d={placement:ne(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:o};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,Lt(Object.assign({},d,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:u,roundOffsets:c})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,Lt(Object.assign({},d,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:c})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}var Nr={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:Ir,data:{}},ze={passive:!0};function Wr(e){var t=e.state,r=e.instance,n=e.options,o=n.scroll,a=o===void 0?!0:o,u=n.resize,f=u===void 0?!0:u,c=Q(t.elements.popper),d=[].concat(t.scrollParents.reference,t.scrollParents.popper);return a&&d.forEach(function(p){p.addEventListener("scroll",r.update,ze)}),f&&c.addEventListener("resize",r.update,ze),function(){a&&d.forEach(function(p){p.removeEventListener("scroll",r.update,ze)}),f&&c.removeEventListener("resize",r.update,ze)}}var Vr={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:Wr,data:{}},Ur={left:"right",right:"left",bottom:"top",top:"bottom"};function Xe(e){return e.replace(/left|right|bottom|top/g,function(t){return Ur[t]})}var Fr={start:"end",end:"start"};function $t(e){return e.replace(/start|end/g,function(t){return Fr[t]})}function it(e){var t=Q(e),r=t.pageXOffset,n=t.pageYOffset;return{scrollLeft:r,scrollTop:n}}function ot(e){return ye(ce(e)).left+it(e).scrollLeft}function _r(e){var t=Q(e),r=ce(e),n=t.visualViewport,o=r.clientWidth,a=r.clientHeight,u=0,f=0;return n&&(o=n.width,a=n.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(u=n.offsetLeft,f=n.offsetTop)),{width:o,height:a,x:u+ot(e),y:f}}function qr(e){var t,r=ce(e),n=it(e),o=(t=e.ownerDocument)==null?void 0:t.body,a=pe(r.scrollWidth,r.clientWidth,o?o.scrollWidth:0,o?o.clientWidth:0),u=pe(r.scrollHeight,r.clientHeight,o?o.scrollHeight:0,o?o.clientHeight:0),f=-n.scrollLeft+ot(e),c=-n.scrollTop;return se(o||r).direction==="rtl"&&(f+=pe(r.clientWidth,o?o.clientWidth:0)-a),{width:a,height:u,x:f,y:c}}function at(e){var t=se(e),r=t.overflow,n=t.overflowX,o=t.overflowY;return/auto|scroll|overlay|hidden/.test(r+o+n)}function Rt(e){return["html","body","#document"].indexOf(re(e))>=0?e.ownerDocument.body:Z(e)&&at(e)?e:Rt(Fe(e))}function je(e,t){var r;t===void 0&&(t=[]);var n=Rt(e),o=n===((r=e.ownerDocument)==null?void 0:r.body),a=Q(n),u=o?[a].concat(a.visualViewport||[],at(n)?n:[]):n,f=t.concat(u);return o?f:f.concat(je(Fe(u)))}function st(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function zr(e){var t=ye(e);return t.top=t.top+e.clientTop,t.left=t.left+e.clientLeft,t.bottom=t.top+e.clientHeight,t.right=t.left+e.clientWidth,t.width=e.clientWidth,t.height=e.clientHeight,t.x=t.left,t.y=t.top,t}function jt(e,t){return t===yt?st(_r(e)):Z(t)?zr(t):st(qr(ce(e)))}function Xr(e){var t=je(Fe(e)),r=["absolute","fixed"].indexOf(se(e).position)>=0,n=r&&Z(e)?$e(e):e;return Le(n)?t.filter(function(o){return Le(o)&&At(o,n)&&re(o)!=="body"}):[]}function Yr(e,t,r){var n=t==="clippingParents"?Xr(e):[].concat(t),o=[].concat(n,[r]),a=o[0],u=o.reduce(function(f,c){var d=jt(e,c);return f.top=pe(d.top,f.top),f.right=Re(d.right,f.right),f.bottom=Re(d.bottom,f.bottom),f.left=pe(d.left,f.left),f},jt(e,a));return u.width=u.right-u.left,u.height=u.bottom-u.top,u.x=u.left,u.y=u.top,u}function Me(e){return e.split("-")[1]}function Mt(e){var t=e.reference,r=e.element,n=e.placement,o=n?ne(n):null,a=n?Me(n):null,u=t.x+t.width/2-r.width/2,f=t.y+t.height/2-r.height/2,c;switch(o){case Y:c={x:u,y:t.y-r.height};break;case K:c={x:u,y:t.y+t.height};break;case J:c={x:t.x+t.width,y:f};break;case G:c={x:t.x-r.width,y:f};break;default:c={x:t.x,y:t.y}}var d=o?nt(o):null;if(d!=null){var p=d==="y"?"height":"width";switch(a){case be:c[d]=c[d]-(t[p]/2-r[p]/2);break;case tt:c[d]=c[d]+(t[p]/2-r[p]/2);break}}return c}function Pe(e,t){t===void 0&&(t={});var r=t,n=r.placement,o=n===void 0?e.placement:n,a=r.boundary,u=a===void 0?hr:a,f=r.rootBoundary,c=f===void 0?yt:f,d=r.elementContext,p=d===void 0?Se:d,w=r.altBoundary,A=w===void 0?!1:w,b=r.padding,h=b===void 0?0:b,x=Ct(typeof h!="number"?h:St(h,Ce)),g=p===Se?gr:Se,T=e.elements.reference,E=e.rects.popper,M=e.elements[A?g:p],i=Yr(Le(M)?M:M.contextElement||ce(e.elements.popper),u,c),$=ye(T),l=Mt({reference:$,element:E,strategy:"absolute",placement:o}),R=st(Object.assign({},E,l)),L=p===Se?R:$,H={top:i.top-L.top+x.top,bottom:L.bottom-i.bottom+x.bottom,left:i.left-L.left+x.left,right:L.right-i.right+x.right},I=e.modifiersData.offset;if(p===Se&&I){var j=I[o];Object.keys(H).forEach(function(S){var D=[J,K].indexOf(S)>=0?1:-1,N=[Y,K].indexOf(S)>=0?"y":"x";H[S]+=j[N]*D})}return H}function Gr(e,t){t===void 0&&(t={});var r=t,n=r.placement,o=r.boundary,a=r.rootBoundary,u=r.padding,f=r.flipVariations,c=r.allowedAutoPlacements,d=c===void 0?Ot:c,p=Me(n),w=p?f?wt:wt.filter(function(h){return Me(h)===p}):Ce,A=w.filter(function(h){return d.indexOf(h)>=0});A.length===0&&(A=w);var b=A.reduce(function(h,x){return h[x]=Pe(e,{placement:x,boundary:o,rootBoundary:a,padding:u})[ne(x)],h},{});return Object.keys(b).sort(function(h,x){return b[h]-b[x]})}function Kr(e){if(ne(e)===et)return[];var t=Xe(e);return[$t(e),t,$t(t)]}function Jr(e){var t=e.state,r=e.options,n=e.name;if(!t.modifiersData[n]._skip){for(var o=r.mainAxis,a=o===void 0?!0:o,u=r.altAxis,f=u===void 0?!0:u,c=r.fallbackPlacements,d=r.padding,p=r.boundary,w=r.rootBoundary,A=r.altBoundary,b=r.flipVariations,h=b===void 0?!0:b,x=r.allowedAutoPlacements,g=t.options.placement,T=ne(g),E=T===g,M=c||(E||!h?[Xe(g)]:Kr(g)),i=[g].concat(M).reduce(function(te,q){return te.concat(ne(q)===et?Gr(t,{placement:q,boundary:p,rootBoundary:w,padding:d,flipVariations:h,allowedAutoPlacements:x}):q)},[]),$=t.rects.reference,l=t.rects.popper,R=new Map,L=!0,H=i[0],I=0;I=0,F=N?"width":"height",B=Pe(t,{placement:j,boundary:p,rootBoundary:w,altBoundary:A,padding:d}),y=N?D?J:G:D?K:Y;$[F]>l[F]&&(y=Xe(y));var k=Xe(y),W=[];if(a&&W.push(B[S]<=0),f&&W.push(B[y]<=0,B[k]<=0),W.every(function(te){return te})){H=j,L=!1;break}R.set(j,W)}if(L)for(var V=h?3:1,_=function(q){var ue=i.find(function(we){var fe=R.get(we);if(fe)return fe.slice(0,q).every(function(me){return me})});if(ue)return H=ue,"break"},P=V;P>0;P--){var oe=_(P);if(oe==="break")break}t.placement!==H&&(t.modifiersData[n]._skip=!0,t.placement=H,t.reset=!0)}}var Qr={name:"flip",enabled:!0,phase:"main",fn:Jr,requiresIfExists:["offset"],data:{_skip:!1}};function Pt(e,t,r){return r===void 0&&(r={x:0,y:0}),{top:e.top-t.height-r.y,right:e.right-t.width+r.x,bottom:e.bottom-t.height+r.y,left:e.left-t.width-r.x}}function Bt(e){return[Y,J,K,G].some(function(t){return e[t]>=0})}function Zr(e){var t=e.state,r=e.name,n=t.rects.reference,o=t.rects.popper,a=t.modifiersData.preventOverflow,u=Pe(t,{elementContext:"reference"}),f=Pe(t,{altBoundary:!0}),c=Pt(u,n),d=Pt(f,o,a),p=Bt(c),w=Bt(d);t.modifiersData[r]={referenceClippingOffsets:c,popperEscapeOffsets:d,isReferenceHidden:p,hasPopperEscaped:w},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":p,"data-popper-escaped":w})}var en={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:Zr};function tn(e,t,r){var n=ne(e),o=[G,Y].indexOf(n)>=0?-1:1,a=typeof r=="function"?r(Object.assign({},t,{placement:e})):r,u=a[0],f=a[1];return u=u||0,f=(f||0)*o,[G,J].indexOf(n)>=0?{x:f,y:u}:{x:u,y:f}}function rn(e){var t=e.state,r=e.options,n=e.name,o=r.offset,a=o===void 0?[0,0]:o,u=Ot.reduce(function(p,w){return p[w]=tn(w,t.rects,a),p},{}),f=u[t.placement],c=f.x,d=f.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=c,t.modifiersData.popperOffsets.y+=d),t.modifiersData[n]=u}var nn={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:rn};function on(e){var t=e.state,r=e.name;t.modifiersData[r]=Mt({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}var an={name:"popperOffsets",enabled:!0,phase:"read",fn:on,data:{}};function sn(e){return e==="x"?"y":"x"}function un(e){var t=e.state,r=e.options,n=e.name,o=r.mainAxis,a=o===void 0?!0:o,u=r.altAxis,f=u===void 0?!1:u,c=r.boundary,d=r.rootBoundary,p=r.altBoundary,w=r.padding,A=r.tether,b=A===void 0?!0:A,h=r.tetherOffset,x=h===void 0?0:h,g=Pe(t,{boundary:c,rootBoundary:d,padding:w,altBoundary:p}),T=ne(t.placement),E=Me(t.placement),M=!E,i=nt(T),$=sn(i),l=t.modifiersData.popperOffsets,R=t.rects.reference,L=t.rects.popper,H=typeof x=="function"?x(Object.assign({},t.rects,{placement:t.placement})):x,I={x:0,y:0};if(!!l){if(a||f){var j=i==="y"?Y:G,S=i==="y"?K:J,D=i==="y"?"height":"width",N=l[i],F=l[i]+g[j],B=l[i]-g[S],y=b?-L[D]/2:0,k=E===be?R[D]:L[D],W=E===be?-L[D]:-R[D],V=t.elements.arrow,_=b&&V?rt(V):{width:0,height:0},P=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:Dt(),oe=P[j],te=P[S],q=qe(0,R[D],_[D]),ue=M?R[D]/2-y-q-oe-H:k-q-oe-H,we=M?-R[D]/2+y+q+te+H:W+q+te+H,fe=t.elements.arrow&&$e(t.elements.arrow),me=fe?i==="y"?fe.clientTop||0:fe.clientLeft||0:0,ae=t.modifiersData.offset?t.modifiersData.offset[t.placement][i]:0,Oe=l[i]+ue-ae-me,xe=l[i]+we-ae;if(a){var Ee=qe(b?Re(F,Oe):F,N,b?pe(B,xe):B);l[i]=Ee,I[i]=Ee-N}if(f){var Ie=i==="x"?Y:G,Ne=i==="x"?K:J,le=l[$],Ae=le+g[Ie],Te=le-g[Ne],De=qe(b?Re(Ae,Oe):Ae,le,b?pe(Te,xe):Te);l[$]=De,I[$]=De-le}}t.modifiersData[n]=I}}var fn={name:"preventOverflow",enabled:!0,phase:"main",fn:un,requiresIfExists:["offset"]};function cn(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function pn(e){return e===Q(e)||!Z(e)?it(e):cn(e)}function ln(e,t,r){r===void 0&&(r=!1);var n=ce(t),o=ye(e),a=Z(t),u={scrollLeft:0,scrollTop:0},f={x:0,y:0};return(a||!a&&!r)&&((re(t)!=="body"||at(n))&&(u=pn(t)),Z(t)?(f=ye(t),f.x+=t.clientLeft,f.y+=t.clientTop):n&&(f.x=ot(n))),{x:o.left+u.scrollLeft-f.x,y:o.top+u.scrollTop-f.y,width:o.width,height:o.height}}function dn(e){var t=new Map,r=new Set,n=[];e.forEach(function(a){t.set(a.name,a)});function o(a){r.add(a.name);var u=[].concat(a.requires||[],a.requiresIfExists||[]);u.forEach(function(f){if(!r.has(f)){var c=t.get(f);c&&o(c)}}),n.push(a)}return e.forEach(function(a){r.has(a.name)||o(a)}),n}function vn(e){var t=dn(e);return Cr.reduce(function(r,n){return r.concat(t.filter(function(o){return o.phase===n}))},[])}function mn(e){var t;return function(){return t||(t=new Promise(function(r){Promise.resolve().then(function(){t=void 0,r(e())})})),t}}function hn(e){var t=e.reduce(function(r,n){var o=r[n.name];return r[n.name]=o?Object.assign({},o,n,{options:Object.assign({},o.options,n.options),data:Object.assign({},o.data,n.data)}):n,r},{});return Object.keys(t).map(function(r){return t[r]})}var kt={placement:"bottom",modifiers:[],strategy:"absolute"};function Ht(){for(var e=arguments.length,t=new Array(e),r=0;r-1}function Vt(e,t){return typeof e=="function"?e.apply(void 0,t):e}function Ut(e,t){if(t===0)return e;var r;return function(n){clearTimeout(r),r=setTimeout(function(){e(n)},t)}}function xn(e){return e.split(/\s+/).filter(Boolean)}function Be(e){return[].concat(e)}function Ft(e,t){e.indexOf(t)===-1&&e.push(t)}function En(e){return e.filter(function(t,r){return e.indexOf(t)===r})}function An(e){return e.split("-")[0]}function Ye(e){return[].slice.call(e)}function Tn(e){return Object.keys(e).reduce(function(t,r){return e[r]!==void 0&&(t[r]=e[r]),t},{})}function ke(){return document.createElement("div")}function Ge(e){return["Element","Fragment"].some(function(t){return ft(e,t)})}function Dn(e){return ft(e,"NodeList")}function Cn(e){return ft(e,"MouseEvent")}function Sn(e){return!!(e&&e._tippy&&e._tippy.reference===e)}function Ln(e){return Ge(e)?[e]:Dn(e)?Ye(e):Array.isArray(e)?e:Ye(document.querySelectorAll(e))}function ct(e,t){e.forEach(function(r){r&&(r.style.transitionDuration=t+"ms")})}function _t(e,t){e.forEach(function(r){r&&r.setAttribute("data-state",t)})}function $n(e){var t,r=Be(e),n=r[0];return(n==null||(t=n.ownerDocument)==null?void 0:t.body)?n.ownerDocument:document}function Rn(e,t){var r=t.clientX,n=t.clientY;return e.every(function(o){var a=o.popperRect,u=o.popperState,f=o.props,c=f.interactiveBorder,d=An(u.placement),p=u.modifiersData.offset;if(!p)return!0;var w=d==="bottom"?p.top.y:0,A=d==="top"?p.bottom.y:0,b=d==="right"?p.left.x:0,h=d==="left"?p.right.x:0,x=a.top-n+w>c,g=n-a.bottom-A>c,T=a.left-r+b>c,E=r-a.right-h>c;return x||g||T||E})}function pt(e,t,r){var n=t+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(o){e[n](o,r)})}var ie={isTouch:!1},qt=0;function jn(){ie.isTouch||(ie.isTouch=!0,window.performance&&document.addEventListener("mousemove",zt))}function zt(){var e=performance.now();e-qt<20&&(ie.isTouch=!1,document.removeEventListener("mousemove",zt)),qt=e}function Mn(){var e=document.activeElement;if(Sn(e)){var t=e._tippy;e.blur&&!t.state.isVisible&&e.blur()}}function Pn(){document.addEventListener("touchstart",jn,ve),window.addEventListener("blur",Mn)}var Bn=typeof window!="undefined"&&typeof document!="undefined",kn=Bn?navigator.userAgent:"",Hn=/MSIE |Trident\//.test(kn),In={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Nn={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ee=Object.assign({appendTo:function(){return document.body},aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},In,{},Nn),Wn=Object.keys(ee),Vn=function(t){var r=Object.keys(t);r.forEach(function(n){ee[n]=t[n]})};function Xt(e){var t=e.plugins||[],r=t.reduce(function(n,o){var a=o.name,u=o.defaultValue;return a&&(n[a]=e[a]!==void 0?e[a]:u),n},{});return Object.assign({},e,{},r)}function Un(e,t){var r=t?Object.keys(Xt(Object.assign({},ee,{plugins:t}))):Wn,n=r.reduce(function(o,a){var u=(e.getAttribute("data-tippy-"+a)||"").trim();if(!u)return o;if(a==="content")o[a]=u;else try{o[a]=JSON.parse(u)}catch(f){o[a]=u}return o},{});return n}function Yt(e,t){var r=Object.assign({},t,{content:Vt(t.content,[e])},t.ignoreAttributes?{}:Un(e,t.plugins));return r.aria=Object.assign({},ee.aria,{},r.aria),r.aria={expanded:r.aria.expanded==="auto"?t.interactive:r.aria.expanded,content:r.aria.content==="auto"?t.interactive?null:"describedby":r.aria.content},r}var Fn=function(){return"innerHTML"};function lt(e,t){e[Fn()]=t}function Gt(e){var t=ke();return e===!0?t.className=Nt:(t.className=Wt,Ge(e)?t.appendChild(e):lt(t,e)),t}function Kt(e,t){Ge(t.content)?(lt(e,""),e.appendChild(t.content)):typeof t.content!="function"&&(t.allowHTML?lt(e,t.content):e.textContent=t.content)}function dt(e){var t=e.firstElementChild,r=Ye(t.children);return{box:t,content:r.find(function(n){return n.classList.contains(It)}),arrow:r.find(function(n){return n.classList.contains(Nt)||n.classList.contains(Wt)}),backdrop:r.find(function(n){return n.classList.contains(On)})}}function Jt(e){var t=ke(),r=ke();r.className=wn,r.setAttribute("data-state","hidden"),r.setAttribute("tabindex","-1");var n=ke();n.className=It,n.setAttribute("data-state","hidden"),Kt(n,e.props),t.appendChild(r),r.appendChild(n),o(e.props,e.props);function o(a,u){var f=dt(t),c=f.box,d=f.content,p=f.arrow;u.theme?c.setAttribute("data-theme",u.theme):c.removeAttribute("data-theme"),typeof u.animation=="string"?c.setAttribute("data-animation",u.animation):c.removeAttribute("data-animation"),u.inertia?c.setAttribute("data-inertia",""):c.removeAttribute("data-inertia"),c.style.maxWidth=typeof u.maxWidth=="number"?u.maxWidth+"px":u.maxWidth,u.role?c.setAttribute("role",u.role):c.removeAttribute("role"),(a.content!==u.content||a.allowHTML!==u.allowHTML)&&Kt(d,e.props),u.arrow?p?a.arrow!==u.arrow&&(c.removeChild(p),c.appendChild(Gt(u.arrow))):c.appendChild(Gt(u.arrow)):p&&c.removeChild(p)}return{popper:t,onUpdate:o}}Jt.$$tippy=!0;var _n=1,Ke=[],vt=[];function qn(e,t){var r=Yt(e,Object.assign({},ee,{},Xt(Tn(t)))),n,o,a,u=!1,f=!1,c=!1,d=!1,p,w,A,b=[],h=Ut(Ie,r.interactiveDebounce),x,g=_n++,T=null,E=En(r.plugins),M={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},i={id:g,reference:e,popper:ke(),popperInstance:T,props:r,state:M,plugins:E,clearDelayTimeouts:ar,setProps:sr,setContent:ur,show:fr,hide:cr,hideWithInteractivity:pr,enable:ir,disable:or,unmount:lr,destroy:dr};if(!r.render)return i;var $=r.render(i),l=$.popper,R=$.onUpdate;l.setAttribute("data-tippy-root",""),l.id="tippy-"+i.id,i.popper=l,e._tippy=i,l._tippy=i;var L=E.map(function(s){return s.fn(i)}),H=e.hasAttribute("aria-expanded");return Oe(),V(),y(),k("onCreate",[i]),r.showOnCreate&>(),l.addEventListener("mouseenter",function(){i.props.interactive&&i.state.isVisible&&i.clearDelayTimeouts()}),l.addEventListener("mouseleave",function(s){i.props.interactive&&i.props.trigger.indexOf("mouseenter")>=0&&(N().addEventListener("mousemove",h),h(s))}),i;function I(){var s=i.props.touch;return Array.isArray(s)?s:[s,0]}function j(){return I()[0]==="hold"}function S(){var s;return!!((s=i.props.render)==null?void 0:s.$$tippy)}function D(){return x||e}function N(){var s=D().parentNode;return s?$n(s):document}function F(){return dt(l)}function B(s){return i.state.isMounted&&!i.state.isVisible||ie.isTouch||p&&p.type==="focus"?0:ut(i.props.delay,s?0:1,ee.delay)}function y(){l.style.pointerEvents=i.props.interactive&&i.state.isVisible?"":"none",l.style.zIndex=""+i.props.zIndex}function k(s,v,m){if(m===void 0&&(m=!0),L.forEach(function(O){O[s]&&O[s].apply(void 0,v)}),m){var C;(C=i.props)[s].apply(C,v)}}function W(){var s=i.props.aria;if(!!s.content){var v="aria-"+s.content,m=l.id,C=Be(i.props.triggerTarget||e);C.forEach(function(O){var U=O.getAttribute(v);if(i.state.isVisible)O.setAttribute(v,U?U+" "+m:m);else{var z=U&&U.replace(m,"").trim();z?O.setAttribute(v,z):O.removeAttribute(v)}})}}function V(){if(!(H||!i.props.aria.expanded)){var s=Be(i.props.triggerTarget||e);s.forEach(function(v){i.props.interactive?v.setAttribute("aria-expanded",i.state.isVisible&&v===D()?"true":"false"):v.removeAttribute("aria-expanded")})}}function _(){N().removeEventListener("mousemove",h),Ke=Ke.filter(function(s){return s!==h})}function P(s){if(!(ie.isTouch&&(c||s.type==="mousedown"))&&!(i.props.interactive&&l.contains(s.target))){if(D().contains(s.target)){if(ie.isTouch||i.state.isVisible&&i.props.trigger.indexOf("click")>=0)return}else k("onClickOutside",[i,s]);i.props.hideOnClick===!0&&(i.clearDelayTimeouts(),i.hide(),f=!0,setTimeout(function(){f=!1}),i.state.isMounted||ue())}}function oe(){c=!0}function te(){c=!1}function q(){var s=N();s.addEventListener("mousedown",P,!0),s.addEventListener("touchend",P,ve),s.addEventListener("touchstart",te,ve),s.addEventListener("touchmove",oe,ve)}function ue(){var s=N();s.removeEventListener("mousedown",P,!0),s.removeEventListener("touchend",P,ve),s.removeEventListener("touchstart",te,ve),s.removeEventListener("touchmove",oe,ve)}function we(s,v){me(s,function(){!i.state.isVisible&&l.parentNode&&l.parentNode.contains(l)&&v()})}function fe(s,v){me(s,v)}function me(s,v){var m=F().box;function C(O){O.target===m&&(pt(m,"remove",C),v())}if(s===0)return v();pt(m,"remove",w),pt(m,"add",C),w=C}function ae(s,v,m){m===void 0&&(m=!1);var C=Be(i.props.triggerTarget||e);C.forEach(function(O){O.addEventListener(s,v,m),b.push({node:O,eventType:s,handler:v,options:m})})}function Oe(){j()&&(ae("touchstart",Ee,{passive:!0}),ae("touchend",Ne,{passive:!0})),xn(i.props.trigger).forEach(function(s){if(s!=="manual")switch(ae(s,Ee),s){case"mouseenter":ae("mouseleave",Ne);break;case"focus":ae(Hn?"focusout":"blur",le);break;case"focusin":ae("focusout",le);break}})}function xe(){b.forEach(function(s){var v=s.node,m=s.eventType,C=s.handler,O=s.options;v.removeEventListener(m,C,O)}),b=[]}function Ee(s){var v,m=!1;if(!(!i.state.isEnabled||Ae(s)||f)){var C=((v=p)==null?void 0:v.type)==="focus";p=s,x=s.currentTarget,V(),!i.state.isVisible&&Cn(s)&&Ke.forEach(function(O){return O(s)}),s.type==="click"&&(i.props.trigger.indexOf("mouseenter")<0||u)&&i.props.hideOnClick!==!1&&i.state.isVisible?m=!0:gt(s),s.type==="click"&&(u=!m),m&&!C&&We(s)}}function Ie(s){var v=s.target,m=D().contains(v)||l.contains(v);if(!(s.type==="mousemove"&&m)){var C=Je().concat(l).map(function(O){var U,z=O._tippy,he=(U=z.popperInstance)==null?void 0:U.state;return he?{popperRect:O.getBoundingClientRect(),popperState:he,props:r}:null}).filter(Boolean);Rn(C,s)&&(_(),We(s))}}function Ne(s){var v=Ae(s)||i.props.trigger.indexOf("click")>=0&&u;if(!v){if(i.props.interactive){i.hideWithInteractivity(s);return}We(s)}}function le(s){i.props.trigger.indexOf("focusin")<0&&s.target!==D()||i.props.interactive&&s.relatedTarget&&l.contains(s.relatedTarget)||We(s)}function Ae(s){return ie.isTouch?j()!==s.type.indexOf("touch")>=0:!1}function Te(){De();var s=i.props,v=s.popperOptions,m=s.placement,C=s.offset,O=s.getReferenceClientRect,U=s.moveTransition,z=S()?dt(l).arrow:null,he=O?{getBoundingClientRect:O,contextElement:O.contextElement||D()}:e,bt={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(Ve){var ge=Ve.state;if(S()){var vr=F(),Ze=vr.box;["placement","reference-hidden","escaped"].forEach(function(Ue){Ue==="placement"?Ze.setAttribute("data-placement",ge.placement):ge.attributes.popper["data-popper-"+Ue]?Ze.setAttribute("data-"+Ue,""):Ze.removeAttribute("data-"+Ue)}),ge.attributes.popper={}}}},de=[{name:"offset",options:{offset:C}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!U}},bt];S()&&z&&de.push({name:"arrow",options:{element:z,padding:3}}),de.push.apply(de,(v==null?void 0:v.modifiers)||[]),i.popperInstance=yn(he,l,Object.assign({},v,{placement:m,onFirstUpdate:A,modifiers:de}))}function De(){i.popperInstance&&(i.popperInstance.destroy(),i.popperInstance=null)}function nr(){var s=i.props.appendTo,v,m=D();i.props.interactive&&s===ee.appendTo||s==="parent"?v=m.parentNode:v=Vt(s,[m]),v.contains(l)||v.appendChild(l),Te()}function Je(){return Ye(l.querySelectorAll("[data-tippy-root]"))}function gt(s){i.clearDelayTimeouts(),s&&k("onTrigger",[i,s]),q();var v=B(!0),m=I(),C=m[0],O=m[1];ie.isTouch&&C==="hold"&&O&&(v=O),v?n=setTimeout(function(){i.show()},v):i.show()}function We(s){if(i.clearDelayTimeouts(),k("onUntrigger",[i,s]),!i.state.isVisible){ue();return}if(!(i.props.trigger.indexOf("mouseenter")>=0&&i.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(s.type)>=0&&u)){var v=B(!1);v?o=setTimeout(function(){i.state.isVisible&&i.hide()},v):a=requestAnimationFrame(function(){i.hide()})}}function ir(){i.state.isEnabled=!0}function or(){i.hide(),i.state.isEnabled=!1}function ar(){clearTimeout(n),clearTimeout(o),cancelAnimationFrame(a)}function sr(s){if(!i.state.isDestroyed){k("onBeforeUpdate",[i,s]),xe();var v=i.props,m=Yt(e,Object.assign({},i.props,{},s,{ignoreAttributes:!0}));i.props=m,Oe(),v.interactiveDebounce!==m.interactiveDebounce&&(_(),h=Ut(Ie,m.interactiveDebounce)),v.triggerTarget&&!m.triggerTarget?Be(v.triggerTarget).forEach(function(C){C.removeAttribute("aria-expanded")}):m.triggerTarget&&e.removeAttribute("aria-expanded"),V(),y(),R&&R(v,m),i.popperInstance&&(Te(),Je().forEach(function(C){requestAnimationFrame(C._tippy.popperInstance.forceUpdate)})),k("onAfterUpdate",[i,s])}}function ur(s){i.setProps({content:s})}function fr(){var s=i.state.isVisible,v=i.state.isDestroyed,m=!i.state.isEnabled,C=ie.isTouch&&!i.props.touch,O=ut(i.props.duration,0,ee.duration);if(!(s||v||m||C)&&!D().hasAttribute("disabled")&&(k("onShow",[i],!1),i.props.onShow(i)!==!1)){if(i.state.isVisible=!0,S()&&(l.style.visibility="visible"),y(),q(),i.state.isMounted||(l.style.transition="none"),S()){var U=F(),z=U.box,he=U.content;ct([z,he],0)}A=function(){var de;if(!(!i.state.isVisible||d)){if(d=!0,l.offsetHeight,l.style.transition=i.props.moveTransition,S()&&i.props.animation){var Qe=F(),Ve=Qe.box,ge=Qe.content;ct([Ve,ge],O),_t([Ve,ge],"visible")}W(),V(),Ft(vt,i),(de=i.popperInstance)==null||de.forceUpdate(),i.state.isMounted=!0,k("onMount",[i]),i.props.animation&&S()&&fe(O,function(){i.state.isShown=!0,k("onShown",[i])})}},nr()}}function cr(){var s=!i.state.isVisible,v=i.state.isDestroyed,m=!i.state.isEnabled,C=ut(i.props.duration,1,ee.duration);if(!(s||v||m)&&(k("onHide",[i],!1),i.props.onHide(i)!==!1)){if(i.state.isVisible=!1,i.state.isShown=!1,d=!1,u=!1,S()&&(l.style.visibility="hidden"),_(),ue(),y(),S()){var O=F(),U=O.box,z=O.content;i.props.animation&&(ct([U,z],C),_t([U,z],"hidden"))}W(),V(),i.props.animation?S()&&we(C,i.unmount):i.unmount()}}function pr(s){N().addEventListener("mousemove",h),Ft(Ke,h),h(s)}function lr(){i.state.isVisible&&i.hide(),!!i.state.isMounted&&(De(),Je().forEach(function(s){s._tippy.unmount()}),l.parentNode&&l.parentNode.removeChild(l),vt=vt.filter(function(s){return s!==i}),i.state.isMounted=!1,k("onHidden",[i]))}function dr(){i.state.isDestroyed||(i.clearDelayTimeouts(),i.unmount(),xe(),delete e._tippy,i.state.isDestroyed=!0,k("onDestroy",[i]))}}function He(e,t){t===void 0&&(t={});var r=ee.plugins.concat(t.plugins||[]);Pn();var n=Object.assign({},t,{plugins:r}),o=Ln(e),a=o.reduce(function(u,f){var c=f&&qn(f,n);return c&&u.push(c),u},[]);return Ge(e)?a[0]:a}He.defaultProps=ee,He.setDefaultProps=Vn,He.currentInput=ie;var ni=Object.assign({},Et,{effect:function(t){var r=t.state,n={popper:{position:r.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(r.elements.popper.style,n.popper),r.styles=n,r.elements.arrow&&Object.assign(r.elements.arrow.style,n.arrow)}});He.setDefaultProps({render:Jt});function Qt(e,t){if(e==null)return{};var r={},n=Object.keys(e),o,a;for(a=0;a=0)&&(r[o]=e[o]);return r}var Zt=typeof window!="undefined"&&typeof document!="undefined";function mt(e,t){e&&(typeof e=="function"&&e(t),{}.hasOwnProperty.call(e,"current")&&(e.current=t))}function er(){return Zt&&document.createElement("div")}function zn(e){var t={"data-placement":e.placement};return e.referenceHidden&&(t["data-reference-hidden"]=""),e.escaped&&(t["data-escaped"]=""),t}function tr(e,t){if(e===t)return!0;if(typeof e=="object"&&e!=null&&typeof t=="object"&&t!=null){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(var r in e)if(t.hasOwnProperty(r)){if(!tr(e[r],t[r]))return!1}else return!1;return!0}else return!1}function Xn(e){var t=[];return e.forEach(function(r){t.find(function(n){return tr(r,n)})||t.push(r)}),t}function Yn(e,t){var r,n;return Object.assign({},t,{popperOptions:Object.assign({},e.popperOptions,t.popperOptions,{modifiers:Xn([].concat(((r=e.popperOptions)==null?void 0:r.modifiers)||[],((n=t.popperOptions)==null?void 0:n.modifiers)||[]))})})}var ht=Zt?X.useLayoutEffect:X.useEffect;function Gn(e){var t=X.useRef();return t.current||(t.current=typeof e=="function"?e():e),t.current}function rr(e,t,r){r.split(/\s+/).forEach(function(n){n&&e.classList[t](n)})}var Kn={name:"className",defaultValue:"",fn:function(t){var r=t.popper.firstElementChild,n=function(){var f;return!!((f=t.props.render)==null?void 0:f.$$tippy)};function o(){t.props.className&&!n()||rr(r,"add",t.props.className)}function a(){n()&&rr(r,"remove",t.props.className)}return{onCreate:o,onBeforeUpdate:a,onAfterUpdate:o}}};function Jn(e){function t(r){var n=r.children,o=r.content,a=r.visible,u=r.singleton,f=r.render,c=r.reference,d=r.disabled,p=d===void 0?!1:d,w=r.ignoreAttributes,A=w===void 0?!0:w,b=r.__source,h=r.__self,x=Qt(r,["children","content","visible","singleton","render","reference","disabled","ignoreAttributes","__source","__self"]),g=a!==void 0,T=u!==void 0,E=X.useState(!1),M=E[0],i=E[1],$=X.useState({}),l=$[0],R=$[1],L=X.useState(),H=L[0],I=L[1],j=Gn(function(){return{container:er(),renders:1}}),S=Object.assign({ignoreAttributes:A},x,{content:j.container});g&&(S.trigger="manual",S.hideOnClick=!1),T&&(p=!0);var D=S,N=S.plugins||[];f&&(D=Object.assign({},S,{plugins:T?[].concat(N,[{fn:function(){return{onTrigger:function(k,W){var V=u.data.children.find(function(P){var oe=P.instance;return oe.reference===W.currentTarget}),_=V.content;I(_)}}}}]):N,render:function(){return{popper:j.container}}}));var F=[c].concat(n?[n.type]:[]);return ht(function(){var B=c;c&&c.hasOwnProperty("current")&&(B=c.current);var y=e(B||j.ref||er(),Object.assign({},D,{plugins:[Kn].concat(S.plugins||[])}));return j.instance=y,p&&y.disable(),a&&y.show(),T&&u.hook({instance:y,content:o,props:D}),i(!0),function(){y.destroy(),u==null||u.cleanup(y)}},F),ht(function(){var B;if(j.renders===1){j.renders++;return}var y=j.instance;y.setProps(Yn(y.props,D)),(B=y.popperInstance)==null||B.forceUpdate(),p?y.disable():y.enable(),g&&(a?y.show():y.hide()),T&&u.hook({instance:y,content:o,props:D})}),ht(function(){var B;if(!!f){var y=j.instance;y.setProps({popperOptions:Object.assign({},y.props.popperOptions,{modifiers:[].concat((((B=y.props.popperOptions)==null?void 0:B.modifiers)||[]).filter(function(k){var W=k.name;return W!=="$$tippyReact"}),[{name:"$$tippyReact",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(W){var V,_=W.state,P=(V=_.modifiersData)==null?void 0:V.hide;(l.placement!==_.placement||l.referenceHidden!==(P==null?void 0:P.isReferenceHidden)||l.escaped!==(P==null?void 0:P.hasPopperEscaped))&&R({placement:_.placement,referenceHidden:P==null?void 0:P.isReferenceHidden,escaped:P==null?void 0:P.hasPopperEscaped}),_.attributes.popper={}}}])})})}},[l.placement,l.referenceHidden,l.escaped].concat(F)),X.createElement(X.Fragment,null,n?X.cloneElement(n,{ref:function(y){j.ref=y,mt(n.ref,y)}}):null,M&&mr.createPortal(f?f(zn(l),H,j.instance):o,j.container))}return t}var Qn=function(e,t){return X.forwardRef(function(n,o){var a=n.children,u=Qt(n,["children"]);return X.createElement(e,Object.assign({},t,u),a?X.cloneElement(a,{ref:function(c){mt(o,c),mt(a.ref,c)}}):null)})},Zn=Qn(Jn(He));export default Zn; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd.js new file mode 100644 index 0000000000000000000000000000000000000000..d4a168dad3b91a989c194befc1d8d491352d7ed4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd.js @@ -0,0 +1,57 @@ +import{r as o,R as Rp}from"./common/index-78959ebc.js";import{n as kp,i as Op,b as Ip,r as Oc,a as Ic,c as Mc,d as Mp,e as Tc,f as Tp,g as Fa,I as yt,_ as L,h as ke,j as _p,k as _c,w as Ot,l as Dp,m as $p,o as T,p as Fe,q as W,s as Ut,u as ti,t as Dc,v as Fp,x as Ap,y as br,D as $c,P as Lp,z as Fc,A as ni}from"./common/PlusOutlined-90dfc612.js";import{r as Ac}from"./common/index-87351f60.js";import{p as Lc}from"./common/process-2545f00a.js";import{c as Y}from"./common/index-3928d36b.js";import{r as Vn,R as Kp}from"./common/index-f7c80223.js";import{_ as Vp}from"./common/_baseIsEqual-b23e7931.js";import{i as Kc}from"./common/ResizeObserver.es-fd8ba902.js";import{s as xr}from"./common/index-b156b0b9.js";import{d as zp}from"./common/debounce-f81279fe.js";import"./common/_commonjsHelpers-b3efd043.js";import"./common/_arrayLikeKeys-a1c01456.js";import"./common/_MapCache-c4ecbe9d.js";import"./common/_getNative-f6f203b5.js";import"./common/_baseGetTag-3262967e.js";import"./common/isObject-d5e189f7.js";import"./common/_Map-e270ea77.js";import"./common/_baseTimes-d6ede5f1.js";import"./common/_overArg-78664c5e.js";import"./common/isObjectLike-0219adc7.js";import"./common/isArrayLike-4a96f864.js";import"./common/_baseUnary-52d6173a.js";import"./common/isArray-1ab33e59.js";import"./common/_cacheHas-57850b8b.js";import"./common/_setToArray-57c49479.js";import"./common/_arrayFilter-5e37ed84.js";import"./common/_getTag-45fd9209.js";import"./common/_Set-7b0a30a4.js";import"./common/isSymbol-cf06cd7f.js";var ri=function(){function e(t,r){t===void 0&&(t=""),r===void 0&&(r={});var n;if(t instanceof e)return t;typeof t=="number"&&(t=kp(t)),this.originalInput=t;var a=Op(t);this.originalInput=t,this.r=a.r,this.g=a.g,this.b=a.b,this.a=a.a,this.roundA=Math.round(100*this.a)/100,this.format=(n=r.format)!==null&&n!==void 0?n:a.format,this.gradientType=r.gradientType,this.r<1&&(this.r=Math.round(this.r)),this.g<1&&(this.g=Math.round(this.g)),this.b<1&&(this.b=Math.round(this.b)),this.isValid=a.ok}return e.prototype.isDark=function(){return this.getBrightness()<128},e.prototype.isLight=function(){return!this.isDark()},e.prototype.getBrightness=function(){var t=this.toRgb();return(t.r*299+t.g*587+t.b*114)/1e3},e.prototype.getLuminance=function(){var t=this.toRgb(),r,n,a,i=t.r/255,l=t.g/255,c=t.b/255;return i<=.03928?r=i/12.92:r=Math.pow((i+.055)/1.055,2.4),l<=.03928?n=l/12.92:n=Math.pow((l+.055)/1.055,2.4),c<=.03928?a=c/12.92:a=Math.pow((c+.055)/1.055,2.4),.2126*r+.7152*n+.0722*a},e.prototype.getAlpha=function(){return this.a},e.prototype.setAlpha=function(t){return this.a=Ip(t),this.roundA=Math.round(100*this.a)/100,this},e.prototype.toHsv=function(){var t=Oc(this.r,this.g,this.b);return{h:t.h*360,s:t.s,v:t.v,a:this.a}},e.prototype.toHsvString=function(){var t=Oc(this.r,this.g,this.b),r=Math.round(t.h*360),n=Math.round(t.s*100),a=Math.round(t.v*100);return this.a===1?"hsv(".concat(r,", ").concat(n,"%, ").concat(a,"%)"):"hsva(".concat(r,", ").concat(n,"%, ").concat(a,"%, ").concat(this.roundA,")")},e.prototype.toHsl=function(){var t=Ic(this.r,this.g,this.b);return{h:t.h*360,s:t.s,l:t.l,a:this.a}},e.prototype.toHslString=function(){var t=Ic(this.r,this.g,this.b),r=Math.round(t.h*360),n=Math.round(t.s*100),a=Math.round(t.l*100);return this.a===1?"hsl(".concat(r,", ").concat(n,"%, ").concat(a,"%)"):"hsla(".concat(r,", ").concat(n,"%, ").concat(a,"%, ").concat(this.roundA,")")},e.prototype.toHex=function(t){return t===void 0&&(t=!1),Mc(this.r,this.g,this.b,t)},e.prototype.toHexString=function(t){return t===void 0&&(t=!1),"#"+this.toHex(t)},e.prototype.toHex8=function(t){return t===void 0&&(t=!1),Mp(this.r,this.g,this.b,this.a,t)},e.prototype.toHex8String=function(t){return t===void 0&&(t=!1),"#"+this.toHex8(t)},e.prototype.toRgb=function(){return{r:Math.round(this.r),g:Math.round(this.g),b:Math.round(this.b),a:this.a}},e.prototype.toRgbString=function(){var t=Math.round(this.r),r=Math.round(this.g),n=Math.round(this.b);return this.a===1?"rgb(".concat(t,", ").concat(r,", ").concat(n,")"):"rgba(".concat(t,", ").concat(r,", ").concat(n,", ").concat(this.roundA,")")},e.prototype.toPercentageRgb=function(){var t=function(r){return"".concat(Math.round(Tc(r,255)*100),"%")};return{r:t(this.r),g:t(this.g),b:t(this.b),a:this.a}},e.prototype.toPercentageRgbString=function(){var t=function(r){return Math.round(Tc(r,255)*100)};return this.a===1?"rgb(".concat(t(this.r),"%, ").concat(t(this.g),"%, ").concat(t(this.b),"%)"):"rgba(".concat(t(this.r),"%, ").concat(t(this.g),"%, ").concat(t(this.b),"%, ").concat(this.roundA,")")},e.prototype.toName=function(){if(this.a===0)return"transparent";if(this.a<1)return!1;for(var t="#"+Mc(this.r,this.g,this.b,!1),r=0,n=Object.entries(Tp);r=0,i=!r&&a&&(t.startsWith("hex")||t==="name");return i?t==="name"&&this.a===0?this.toName():this.toRgbString():(t==="rgb"&&(n=this.toRgbString()),t==="prgb"&&(n=this.toPercentageRgbString()),(t==="hex"||t==="hex6")&&(n=this.toHexString()),t==="hex3"&&(n=this.toHexString(!0)),t==="hex4"&&(n=this.toHex8String(!0)),t==="hex8"&&(n=this.toHex8String()),t==="name"&&(n=this.toName()),t==="hsl"&&(n=this.toHslString()),t==="hsv"&&(n=this.toHsvString()),n||this.toHexString())},e.prototype.toNumber=function(){return(Math.round(this.r)<<16)+(Math.round(this.g)<<8)+Math.round(this.b)},e.prototype.clone=function(){return new e(this.toString())},e.prototype.lighten=function(t){t===void 0&&(t=10);var r=this.toHsl();return r.l+=t/100,r.l=Fa(r.l),new e(r)},e.prototype.brighten=function(t){t===void 0&&(t=10);var r=this.toRgb();return r.r=Math.max(0,Math.min(255,r.r-Math.round(255*-(t/100)))),r.g=Math.max(0,Math.min(255,r.g-Math.round(255*-(t/100)))),r.b=Math.max(0,Math.min(255,r.b-Math.round(255*-(t/100)))),new e(r)},e.prototype.darken=function(t){t===void 0&&(t=10);var r=this.toHsl();return r.l-=t/100,r.l=Fa(r.l),new e(r)},e.prototype.tint=function(t){return t===void 0&&(t=10),this.mix("white",t)},e.prototype.shade=function(t){return t===void 0&&(t=10),this.mix("black",t)},e.prototype.desaturate=function(t){t===void 0&&(t=10);var r=this.toHsl();return r.s-=t/100,r.s=Fa(r.s),new e(r)},e.prototype.saturate=function(t){t===void 0&&(t=10);var r=this.toHsl();return r.s+=t/100,r.s=Fa(r.s),new e(r)},e.prototype.greyscale=function(){return this.desaturate(100)},e.prototype.spin=function(t){var r=this.toHsl(),n=(r.h+t)%360;return r.h=n<0?360+n:n,new e(r)},e.prototype.mix=function(t,r){r===void 0&&(r=50);var n=this.toRgb(),a=new e(t).toRgb(),i=r/100,l={r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a};return new e(l)},e.prototype.analogous=function(t,r){t===void 0&&(t=6),r===void 0&&(r=30);var n=this.toHsl(),a=360/r,i=[this];for(n.h=(n.h-(a*t>>1)+720)%360;--t;)n.h=(n.h+a)%360,i.push(new e(n));return i},e.prototype.complement=function(){var t=this.toHsl();return t.h=(t.h+180)%360,new e(t)},e.prototype.monochromatic=function(t){t===void 0&&(t=6);for(var r=this.toHsv(),n=r.h,a=r.s,i=r.v,l=[],c=1/t;t--;)l.push(new e({h:n,s:a,v:i})),i=(i+c)%1;return l},e.prototype.splitcomplement=function(){var t=this.toHsl(),r=t.h;return[this,new e({h:(r+72)%360,s:t.s,l:t.l}),new e({h:(r+216)%360,s:t.s,l:t.l})]},e.prototype.onBackground=function(t){var r=this.toRgb(),n=new e(t).toRgb();return new e({r:n.r+(r.r-n.r)*r.a,g:n.g+(r.g-n.g)*r.a,b:n.b+(r.b-n.b)*r.a})},e.prototype.triad=function(){return this.polyad(3)},e.prototype.tetrad=function(){return this.polyad(4)},e.prototype.polyad=function(t){for(var r=this.toHsl(),n=r.h,a=[this],i=360/t,l=1;l1&&arguments[1]!==void 0?arguments[1]:{},r=[];return o.Children.forEach(e,function(n){n==null&&!t.keepEmpty||(Array.isArray(n)?r=r.concat(an(n)):Ac.isFragment(n)&&n.props?r=r.concat(an(n.props.children,t)):r.push(n))}),r}function La(e,t,r){var n=o.useRef({});return(!("value"in n.current)||r(n.current.condition,t))&&(n.current.value=e(),n.current.condition=t),n.current.value}function Ka(e,t){typeof e=="function"?e(t):ke(e)==="object"&&e&&"current"in e&&(e.current=t)}function on(){for(var e=arguments.length,t=new Array(e),r=0;r=0;--$){var D=this.tryEntries[$],A=D.completion;if(D.tryLoc==="root")return _("end");if(D.tryLoc<=this.prev){var V=r.call(D,"catchLoc"),U=r.call(D,"finallyLoc");if(V&&U){if(this.prev=0;--_){var $=this.tryEntries[_];if($.tryLoc<=this.prev&&r.call($,"finallyLoc")&&this.prev<$.finallyLoc){var D=$;break}}D&&(N==="break"||N==="continue")&&D.tryLoc<=P&&P<=D.finallyLoc&&(D=null);var A=D?D.completion:{};return A.type=N,A.arg=P,D?(this.method="next",this.next=D.finallyLoc,f):this.complete(A)},complete:function(N,P){if(N.type==="throw")throw N.arg;return N.type==="break"||N.type==="continue"?this.next=N.arg:N.type==="return"?(this.rval=this.arg=N.arg,this.method="return",this.next="end"):N.type==="normal"&&P&&(this.next=P),f},finish:function(N){for(var P=this.tryEntries.length-1;P>=0;--P){var _=this.tryEntries[P];if(_.finallyLoc===N)return this.complete(_.completion,_.afterLoc),E(_),f}},catch:function(N){for(var P=this.tryEntries.length-1;P>=0;--P){var _=this.tryEntries[P];if(_.tryLoc===N){var $=_.completion;if($.type==="throw"){var D=$.arg;E(_)}return D}}throw new Error("illegal catch attempt")},delegateYield:function(N,P,_){return this.delegate={iterator:I(N),resultName:P,nextLoc:_},this.method==="next"&&(this.arg=void 0),f}},e}function Ps(e,t,r,n,a,i,l){try{var c=e[i](l),s=c.value}catch(u){r(u);return}c.done?t(s):Promise.resolve(s).then(n,a)}function or(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var i=e.apply(t,r);function l(s){Ps(i,n,a,l,c,"next",s)}function c(s){Ps(i,n,a,l,c,"throw",s)}l(void 0)})}}function ir(){return ir=Object.assign?Object.assign.bind():function(e){for(var t=1;t1?t-1:0),n=1;n=i)return c;switch(c){case"%s":return String(r[a++]);case"%d":return Number(r[a++]);case"%j":try{return JSON.stringify(r[a++])}catch(s){return"[Circular]"}break;default:return c}});return l}return e}function Yh(e){return e==="string"||e==="url"||e==="hex"||e==="email"||e==="date"||e==="pattern"}function $t(e,t){return!!(e==null||t==="array"&&Array.isArray(e)&&!e.length||Yh(t)&&typeof e=="string"&&!e)}function Xh(e,t,r){var n=[],a=0,i=e.length;function l(c){n.push.apply(n,c||[]),a++,a===i&&r(n)}e.forEach(function(c){t(c,l)})}function Rs(e,t,r){var n=0,a=e.length;function i(l){if(l&&l.length){r(l);return}var c=n;n=n+1,c()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/,hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},ra={integer:function(t){return ra.number(t)&&parseInt(t,10)===t},float:function(t){return ra.number(t)&&!ra.integer(t)},array:function(t){return Array.isArray(t)},regexp:function(t){if(t instanceof RegExp)return!0;try{return!!new RegExp(t)}catch(r){return!1}},date:function(t){return typeof t.getTime=="function"&&typeof t.getMonth=="function"&&typeof t.getYear=="function"&&!isNaN(t.getTime())},number:function(t){return isNaN(t)?!1:typeof t=="number"},object:function(t){return typeof t=="object"&&!ra.array(t)},method:function(t){return typeof t=="function"},email:function(t){return typeof t=="string"&&t.length<=320&&!!t.match(Ts.email)},url:function(t){return typeof t=="string"&&t.length<=2048&&!!t.match(ng())},hex:function(t){return typeof t=="string"&&!!t.match(Ts.hex)}},rg=function(t,r,n,a,i){if(t.required&&r===void 0){Ms(t,r,n,a,i);return}var l=["integer","float","array","regexp","object","method","email","number","date","url","hex"],c=t.type;l.indexOf(c)>-1?ra[c](r)||a.push(Xt(i.messages.types[c],t.fullField,t.type)):c&&typeof r!==t.type&&a.push(Xt(i.messages.types[c],t.fullField,t.type))},ag=function(t,r,n,a,i){var l=typeof t.len=="number",c=typeof t.min=="number",s=typeof t.max=="number",u=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,d=r,f=null,v=typeof r=="number",m=typeof r=="string",p=Array.isArray(r);if(v?f="number":m?f="string":p&&(f="array"),!f)return!1;p&&(d=r.length),m&&(d=r.replace(u,"_").length),l?d!==t.len&&a.push(Xt(i.messages[f].len,t.fullField,t.len)):c&&!s&&dt.max?a.push(Xt(i.messages[f].max,t.fullField,t.max)):c&&s&&(dt.max)&&a.push(Xt(i.messages[f].range,t.fullField,t.min,t.max))},wr="enum",og=function(t,r,n,a,i){t[wr]=Array.isArray(t[wr])?t[wr]:[],t[wr].indexOf(r)===-1&&a.push(Xt(i.messages[wr],t.fullField,t[wr].join(", ")))},ig=function(t,r,n,a,i){if(t.pattern){if(t.pattern instanceof RegExp)t.pattern.lastIndex=0,t.pattern.test(r)||a.push(Xt(i.messages.pattern.mismatch,t.fullField,r,t.pattern));else if(typeof t.pattern=="string"){var l=new RegExp(t.pattern);l.test(r)||a.push(Xt(i.messages.pattern.mismatch,t.fullField,r,t.pattern))}}},st={required:Ms,whitespace:tg,type:rg,range:ag,enum:og,pattern:ig},lg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r,"string")&&!t.required)return n();st.required(t,r,a,l,i,"string"),$t(r,"string")||(st.type(t,r,a,l,i),st.range(t,r,a,l,i),st.pattern(t,r,a,l,i),t.whitespace===!0&&st.whitespace(t,r,a,l,i))}n(l)},cg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&st.type(t,r,a,l,i)}n(l)},sg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if(r===""&&(r=void 0),$t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&(st.type(t,r,a,l,i),st.range(t,r,a,l,i))}n(l)},ug=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&st.type(t,r,a,l,i)}n(l)},dg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),$t(r)||st.type(t,r,a,l,i)}n(l)},fg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&(st.type(t,r,a,l,i),st.range(t,r,a,l,i))}n(l)},vg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&(st.type(t,r,a,l,i),st.range(t,r,a,l,i))}n(l)},mg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if(r==null&&!t.required)return n();st.required(t,r,a,l,i,"array"),r!=null&&(st.type(t,r,a,l,i),st.range(t,r,a,l,i))}n(l)},pg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&st.type(t,r,a,l,i)}n(l)},hg="enum",gg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i),r!==void 0&&st[hg](t,r,a,l,i)}n(l)},yg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r,"string")&&!t.required)return n();st.required(t,r,a,l,i),$t(r,"string")||st.pattern(t,r,a,l,i)}n(l)},Cg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r,"date")&&!t.required)return n();if(st.required(t,r,a,l,i),!$t(r,"date")){var s;r instanceof Date?s=r:s=new Date(r),st.type(t,s,a,l,i),s&&st.range(t,s.getTime(),a,l,i)}}n(l)},bg=function(t,r,n,a,i){var l=[],c=Array.isArray(r)?"array":typeof r;st.required(t,r,a,l,i,c),n(l)},hi=function(t,r,n,a,i){var l=t.type,c=[],s=t.required||!t.required&&a.hasOwnProperty(t.field);if(s){if($t(r,l)&&!t.required)return n();st.required(t,r,a,c,i,l),$t(r,l)||st.type(t,r,a,c,i)}n(c)},xg=function(t,r,n,a,i){var l=[],c=t.required||!t.required&&a.hasOwnProperty(t.field);if(c){if($t(r)&&!t.required)return n();st.required(t,r,a,l,i)}n(l)},aa={string:lg,method:cg,number:sg,boolean:ug,regexp:dg,integer:fg,float:vg,array:mg,object:pg,enum:gg,pattern:yg,date:Cg,url:hi,hex:hi,email:hi,required:bg,any:xg};function gi(){return{default:"Validation error on field %s",required:"%s is required",enum:"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s",boolean:"%s is not a %s",integer:"%s is not an %s",float:"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var t=JSON.parse(JSON.stringify(this));return t.clone=this.clone,t}}}var yi=gi(),oa=function(){function e(r){this.rules=null,this._messages=yi,this.define(r)}var t=e.prototype;return t.define=function(n){var a=this;if(!n)throw new Error("Cannot configure a schema with no rules");if(typeof n!="object"||Array.isArray(n))throw new Error("Rules must be an object");this.rules={},Object.keys(n).forEach(function(i){var l=n[i];a.rules[i]=Array.isArray(l)?l:[l]})},t.messages=function(n){return n&&(this._messages=Is(gi(),n)),this._messages},t.validate=function(n,a,i){var l=this;a===void 0&&(a={}),i===void 0&&(i=function(){});var c=n,s=a,u=i;if(typeof s=="function"&&(u=s,s={}),!this.rules||Object.keys(this.rules).length===0)return u&&u(null,c),Promise.resolve(c);function d(g){var h=[],y={};function C(x){if(Array.isArray(x)){var w;h=(w=h).concat.apply(w,x)}else h.push(x)}for(var b=0;b3&&arguments[3]!==void 0?arguments[3]:!1;return t.length&&n&&r===void 0&&!Ds(e,t.slice(0,-1))?e:$s(e,t,r,n)}function ja(e){return Array.isArray(e)?wg(e):ke(e)==="object"&&e!==null?Eg(e):e}function Eg(e){if(Object.getPrototypeOf(e)===Object.prototype){var t={};for(var r in e)t[r]=ja(e[r]);return t}return e}function wg(e){return e.map(function(t){return ja(t)})}function It(e){return fi(e)}function jn(e,t){var r=Ds(e,t);return r}function Hn(e,t,r){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,a=Sg(e,t,r,n);return a}function Fs(e,t){var r={};return t.forEach(function(n){var a=jn(e,n);r=Hn(r,n,a)}),r}function ia(e,t){return e&&e.some(function(r){return Ks(r,t)})}function As(e){return ke(e)==="object"&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}function Ls(e,t){var r=Array.isArray(e)?ue(e):L({},e);return t&&Object.keys(t).forEach(function(n){var a=r[n],i=t[n],l=As(a)&&As(i);r[n]=l?Ls(a,i||{}):ja(i)}),r}function Ha(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n=n||r<0||r>=n)return e;var a=e[t],i=t-r;return i>0?[].concat(ue(e.slice(0,r)),[a],ue(e.slice(r,t)),ue(e.slice(t+1,n))):i<0?[].concat(ue(e.slice(0,t)),ue(e.slice(t+1,r+1)),[a],ue(e.slice(r+1,n))):e}var Rg=oa;function kg(e,t){return e.replace(/\$\{\w+\}/g,function(r){var n=r.slice(2,-1);return t[n]})}var zs="CODE_LOGIC_ERROR";function bi(e,t,r,n,a){return xi.apply(this,arguments)}function xi(){return xi=or(qt().mark(function e(t,r,n,a,i){var l,c,s,u,d,f,v,m,p;return qt().wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return l=L({},n),delete l.ruleIndex,l.validator&&(c=l.validator,l.validator=function(){try{return c.apply(void 0,arguments)}catch(y){return console.error(y),Promise.reject(zs)}}),s=null,l&&l.type==="array"&&l.defaultField&&(s=l.defaultField,delete l.defaultField),u=new Rg(T({},t,[l])),d=Ha({},_s,a.validateMessages),u.messages(d),f=[],h.prev=9,h.next=12,Promise.resolve(u.validate(T({},t,r),L({},a)));case 12:h.next=17;break;case 14:h.prev=14,h.t0=h.catch(9),h.t0.errors&&(f=h.t0.errors.map(function(y,C){var b=y.message,x=b===zs?d.default:b;return o.isValidElement(x)?o.cloneElement(x,{key:"error_".concat(C)}):x}));case 17:if(!(!f.length&&s)){h.next=22;break}return h.next=20,Promise.all(r.map(function(y,C){return bi("".concat(t,".").concat(C),y,s,a,i)}));case 20:return v=h.sent,h.abrupt("return",v.reduce(function(y,C){return[].concat(ue(y),ue(C))},[]));case 22:return m=L(L({},n),{},{name:t,enum:(n.enum||[]).join(", ")},i),p=f.map(function(y){return typeof y=="string"?kg(y,m):y}),h.abrupt("return",p);case 25:case"end":return h.stop()}},e,null,[[9,14]])})),xi.apply(this,arguments)}function Og(e,t,r,n,a,i){var l=e.join("."),c=r.map(function(d,f){var v=d.validator,m=L(L({},d),{},{ruleIndex:f});return v&&(m.validator=function(p,g,h){var y=!1,C=function(){for(var w=arguments.length,S=new Array(w),O=0;O0&&arguments[0]!==void 0?arguments[0]:ln;if(a.validatePromise===f){var w;a.validatePromise=null;var S=[],O=[];(w=x.forEach)===null||w===void 0||w.call(x,function(E){var k=E.rule.warningOnly,I=E.errors,M=I===void 0?ln:I;k?O.push.apply(O,ue(M)):S.push.apply(S,ue(M))}),a.errors=S,a.warnings=O,a.triggerMetaEvent(),a.reRender()}}),b});return a.validatePromise=f,a.dirty=!0,a.errors=ln,a.warnings=ln,a.triggerMetaEvent(),a.reRender(),f},a.isFieldValidating=function(){return!!a.validatePromise},a.isFieldTouched=function(){return a.touched},a.isFieldDirty=function(){if(a.dirty||a.props.initialValue!==void 0)return!0;var s=a.props.fieldContext,u=s.getInternalHooks(rr),d=u.getInitialValue;return d(a.getNamePath())!==void 0},a.getErrors=function(){return a.errors},a.getWarnings=function(){return a.warnings},a.isListField=function(){return a.props.isListField},a.isList=function(){return a.props.isList},a.isPreserve=function(){return a.props.preserve},a.getMeta=function(){a.prevValidating=a.isFieldValidating();var s={touched:a.isFieldTouched(),validating:a.prevValidating,errors:a.errors,warnings:a.warnings,name:a.getNamePath()};return s},a.getOnlyChild=function(s){if(typeof s=="function"){var u=a.getMeta();return L(L({},a.getOnlyChild(s(a.getControlled(),u,a.props.fieldContext))),{},{isFunction:!0})}var d=an(s);return d.length!==1||!o.isValidElement(d[0])?{child:d,isFunction:!1}:{child:d[0],isFunction:!1}},a.getValue=function(s){var u=a.props.fieldContext.getFieldsValue,d=a.getNamePath();return jn(s||u(!0),d)},a.getControlled=function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},u=a.props,d=u.trigger,f=u.validateTrigger,v=u.getValueFromEvent,m=u.normalize,p=u.valuePropName,g=u.getValueProps,h=u.fieldContext,y=f!==void 0?f:h.validateTrigger,C=a.getNamePath(),b=h.getInternalHooks,x=h.getFieldsValue,w=b(rr),S=w.dispatch,O=a.getValue(),E=g||function(R){return T({},p,R)},k=s[d],I=L(L({},s),E(O));I[d]=function(){a.touched=!0,a.dirty=!0,a.triggerMetaEvent();for(var R,N=arguments.length,P=new Array(N),_=0;_=0&&k<=I.length?(u.keys=[].concat(ue(u.keys.slice(0,k)),[u.id],ue(u.keys.slice(k))),C([].concat(ue(I.slice(0,k)),[E],ue(I.slice(k))))):(u.keys=[].concat(ue(u.keys),[u.id]),C([].concat(ue(I),[E]))),u.id+=1},remove:function(E){var k=x(),I=new Set(Array.isArray(E)?E:[E]);I.size<=0||(u.keys=u.keys.filter(function(M,R){return!I.has(R)}),C(k.filter(function(M,R){return!I.has(R)})))},move:function(E,k){if(E!==k){var I=x();E<0||E>=I.length||k<0||k>=I.length||(u.keys=Vs(u.keys,E,k),C(Vs(I,E,k)))}}},S=y||[];return Array.isArray(S)||(S=[]),a(S.map(function(O,E){var k=u.keys[E];return k===void 0&&(u.keys[E]=u.id,k=u.keys[E],u.id+=1),{name:E,key:k,isListField:!0}}),w,g)})))};function _g(e){var t=!1,r=e.length,n=[];return e.length?new Promise(function(a,i){e.forEach(function(l,c){l.catch(function(s){return t=!0,s}).then(function(s){r-=1,n[c]=s,!(r>0)&&(t&&i(n),a(n))})})}):Promise.resolve([])}var Ws="__@field_split__";function Pi(e){return e.map(function(t){return"".concat(ke(t),":").concat(t)}).join(Ws)}var Nr=function(){function e(){Pt(this,e),this.kvs=new Map}return Rt(e,[{key:"set",value:function(r,n){this.kvs.set(Pi(r),n)}},{key:"get",value:function(r){return this.kvs.get(Pi(r))}},{key:"update",value:function(r,n){var a=this.get(r),i=n(a);i?this.set(r,i):this.delete(r)}},{key:"delete",value:function(r){this.kvs.delete(Pi(r))}},{key:"map",value:function(r){return ue(this.kvs.entries()).map(function(n){var a=W(n,2),i=a[0],l=a[1],c=i.split(Ws);return r({key:c.map(function(s){var u=s.match(/^([^:]*):(.*)$/),d=W(u,3),f=d[1],v=d[2];return f==="number"?Number(v):v}),value:l})})}},{key:"toJSON",value:function(){var r={};return this.map(function(n){var a=n.key,i=n.value;return r[a.join(".")]=i,null}),r}}]),e}(),Dg=["name","errors"],$g=Rt(function e(t){var r=this;Pt(this,e),this.formHooked=!1,this.forceRootUpdate=void 0,this.subscribable=!0,this.store={},this.fieldEntities=[],this.initialValues={},this.callbacks={},this.validateMessages=null,this.preserve=null,this.lastValidatePromise=null,this.getForm=function(){return{getFieldValue:r.getFieldValue,getFieldsValue:r.getFieldsValue,getFieldError:r.getFieldError,getFieldWarning:r.getFieldWarning,getFieldsError:r.getFieldsError,isFieldsTouched:r.isFieldsTouched,isFieldTouched:r.isFieldTouched,isFieldValidating:r.isFieldValidating,isFieldsValidating:r.isFieldsValidating,resetFields:r.resetFields,setFields:r.setFields,setFieldValue:r.setFieldValue,setFieldsValue:r.setFieldsValue,validateFields:r.validateFields,submit:r.submit,_init:!0,getInternalHooks:r.getInternalHooks}},this.getInternalHooks=function(n){return n===rr?(r.formHooked=!0,{dispatch:r.dispatch,initEntityValue:r.initEntityValue,registerField:r.registerField,useSubscribe:r.useSubscribe,setInitialValues:r.setInitialValues,destroyForm:r.destroyForm,setCallbacks:r.setCallbacks,setValidateMessages:r.setValidateMessages,getFields:r.getFields,setPreserve:r.setPreserve,getInitialValue:r.getInitialValue,registerWatch:r.registerWatch}):(Ot(!1,"`getInternalHooks` is internal usage. Should not call directly."),null)},this.useSubscribe=function(n){r.subscribable=n},this.prevWithoutPreserves=null,this.setInitialValues=function(n,a){if(r.initialValues=n||{},a){var i,l=Ha({},n,r.store);(i=r.prevWithoutPreserves)===null||i===void 0||i.map(function(c){var s=c.key;l=Hn(l,s,jn(n,s))}),r.prevWithoutPreserves=null,r.updateStore(l)}},this.destroyForm=function(){var n=new Nr;r.getFieldEntities(!0).forEach(function(a){r.isMergedPreserve(a.isPreserve())||n.set(a.getNamePath(),!0)}),r.prevWithoutPreserves=n},this.getInitialValue=function(n){var a=jn(r.initialValues,n);return n.length?ja(a):a},this.setCallbacks=function(n){r.callbacks=n},this.setValidateMessages=function(n){r.validateMessages=n},this.setPreserve=function(n){r.preserve=n},this.watchList=[],this.registerWatch=function(n){return r.watchList.push(n),function(){r.watchList=r.watchList.filter(function(a){return a!==n})}},this.notifyWatch=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];if(r.watchList.length){var a=r.getFieldsValue();r.watchList.forEach(function(i){i(a,n)})}},this.timeoutId=null,this.warningUnhooked=function(){},this.updateStore=function(n){r.store=n},this.getFieldEntities=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return n?r.fieldEntities.filter(function(a){return a.getNamePath().length}):r.fieldEntities},this.getFieldsMap=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,a=new Nr;return r.getFieldEntities(n).forEach(function(i){var l=i.getNamePath();a.set(l,i)}),a},this.getFieldEntitiesForNamePathList=function(n){if(!n)return r.getFieldEntities(!0);var a=r.getFieldsMap(!0);return n.map(function(i){var l=It(i);return a.get(l)||{INVALIDATE_NAME_PATH:It(i)}})},this.getFieldsValue=function(n,a){if(r.warningUnhooked(),n===!0&&!a)return r.store;var i=r.getFieldEntitiesForNamePathList(Array.isArray(n)?n:null),l=[];return i.forEach(function(c){var s,u="INVALIDATE_NAME_PATH"in c?c.INVALIDATE_NAME_PATH:c.getNamePath();if(!(!n&&((s=c.isListField)===null||s===void 0?void 0:s.call(c))))if(!a)l.push(u);else{var d="getMeta"in c?c.getMeta():null;a(d)&&l.push(u)}}),Fs(r.store,l.map(It))},this.getFieldValue=function(n){r.warningUnhooked();var a=It(n);return jn(r.store,a)},this.getFieldsError=function(n){r.warningUnhooked();var a=r.getFieldEntitiesForNamePathList(n);return a.map(function(i,l){return i&&!("INVALIDATE_NAME_PATH"in i)?{name:i.getNamePath(),errors:i.getErrors(),warnings:i.getWarnings()}:{name:It(n[l]),errors:[],warnings:[]}})},this.getFieldError=function(n){r.warningUnhooked();var a=It(n),i=r.getFieldsError([a])[0];return i.errors},this.getFieldWarning=function(n){r.warningUnhooked();var a=It(n),i=r.getFieldsError([a])[0];return i.warnings},this.isFieldsTouched=function(){r.warningUnhooked();for(var n=arguments.length,a=new Array(n),i=0;i0&&arguments[0]!==void 0?arguments[0]:{},a=new Nr,i=r.getFieldEntities(!0);i.forEach(function(s){var u=s.props.initialValue,d=s.getNamePath();if(u!==void 0){var f=a.get(d)||new Set;f.add({entity:s,value:u}),a.set(d,f)}});var l=function(u){u.forEach(function(d){var f=d.props.initialValue;if(f!==void 0){var v=d.getNamePath(),m=r.getInitialValue(v);if(m!==void 0)Ot(!1,"Form already set 'initialValues' with path '".concat(v.join("."),"'. Field can not overwrite it."));else{var p=a.get(v);if(p&&p.size>1)Ot(!1,"Multiple Field with path '".concat(v.join("."),"' set 'initialValue'. Can not decide which one to pick."));else if(p){var g=r.getFieldValue(v);(!n.skipExist||g===void 0)&&r.updateStore(Hn(r.store,v,ue(p)[0].value))}}}})},c;n.entities?c=n.entities:n.namePathList?(c=[],n.namePathList.forEach(function(s){var u=a.get(s);if(u){var d;(d=c).push.apply(d,ue(ue(u).map(function(f){return f.entity})))}})):c=i,l(c)},this.resetFields=function(n){r.warningUnhooked();var a=r.store;if(!n){r.updateStore(Ha({},r.initialValues)),r.resetWithFieldInitialValue(),r.notifyObservers(a,null,{type:"reset"}),r.notifyWatch();return}var i=n.map(It);i.forEach(function(l){var c=r.getInitialValue(l);r.updateStore(Hn(r.store,l,c))}),r.resetWithFieldInitialValue({namePathList:i}),r.notifyObservers(a,i,{type:"reset"}),r.notifyWatch(i)},this.setFields=function(n){r.warningUnhooked();var a=r.store,i=[];n.forEach(function(l){var c=l.name,s=l.errors,u=Fe(l,Dg),d=It(c);i.push(d),"value"in u&&r.updateStore(Hn(r.store,d,u.value)),r.notifyObservers(a,[d],{type:"setField",data:l})}),r.notifyWatch(i)},this.getFields=function(){var n=r.getFieldEntities(!0),a=n.map(function(i){var l=i.getNamePath(),c=i.getMeta(),s=L(L({},c),{},{name:l,value:r.getFieldValue(l)});return Object.defineProperty(s,"originRCField",{value:!0}),s});return a},this.initEntityValue=function(n){var a=n.props.initialValue;if(a!==void 0){var i=n.getNamePath(),l=jn(r.store,i);l===void 0&&r.updateStore(Hn(r.store,i,a))}},this.isMergedPreserve=function(n){var a=n!==void 0?n:r.preserve;return a!=null?a:!0},this.registerField=function(n){r.fieldEntities.push(n);var a=n.getNamePath();if(r.notifyWatch([a]),n.props.initialValue!==void 0){var i=r.store;r.resetWithFieldInitialValue({entities:[n],skipExist:!0}),r.notifyObservers(i,[n.getNamePath()],{type:"valueUpdate",source:"internal"})}return function(l,c){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];if(r.fieldEntities=r.fieldEntities.filter(function(f){return f!==n}),!r.isMergedPreserve(c)&&(!l||s.length>1)){var u=l?void 0:r.getInitialValue(a);if(a.length&&r.getFieldValue(a)!==u&&r.fieldEntities.every(function(f){return!Ks(f.getNamePath(),a)})){var d=r.store;r.updateStore(Hn(d,a,u,!0)),r.notifyObservers(d,[a],{type:"remove"}),r.triggerDependenciesUpdate(d,a)}}r.notifyWatch([a])}},this.dispatch=function(n){switch(n.type){case"updateValue":{var a=n.namePath,i=n.value;r.updateValue(a,i);break}case"validateField":{var l=n.namePath,c=n.triggerName;r.validateFields([l],{triggerName:c});break}}},this.notifyObservers=function(n,a,i){if(r.subscribable){var l=L(L({},i),{},{store:r.getFieldsValue(!0)});r.getFieldEntities().forEach(function(c){var s=c.onStoreChange;s(n,a,l)})}else r.forceRootUpdate()},this.triggerDependenciesUpdate=function(n,a){var i=r.getDependencyChildrenFields(a);return i.length&&r.validateFields(i),r.notifyObservers(n,i,{type:"dependenciesUpdate",relatedFields:[a].concat(ue(i))}),i},this.updateValue=function(n,a){var i=It(n),l=r.store;r.updateStore(Hn(r.store,i,a)),r.notifyObservers(l,[i],{type:"valueUpdate",source:"internal"}),r.notifyWatch([i]);var c=r.triggerDependenciesUpdate(l,i),s=r.callbacks.onValuesChange;if(s){var u=Fs(r.store,[i]);s(u,r.getFieldsValue())}r.triggerOnFieldsChange([i].concat(ue(c)))},this.setFieldsValue=function(n){r.warningUnhooked();var a=r.store;if(n){var i=Ha(r.store,n);r.updateStore(i)}r.notifyObservers(a,null,{type:"valueUpdate",source:"external"}),r.notifyWatch()},this.setFieldValue=function(n,a){r.setFields([{name:n,value:a}])},this.getDependencyChildrenFields=function(n){var a=new Set,i=[],l=new Nr;r.getFieldEntities().forEach(function(s){var u=s.props.dependencies;(u||[]).forEach(function(d){var f=It(d);l.update(f,function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Set;return v.add(s),v})})});var c=function s(u){var d=l.get(u)||new Set;d.forEach(function(f){if(!a.has(f)){a.add(f);var v=f.getNamePath();f.isFieldDirty()&&v.length&&(i.push(v),s(v))}})};return c(n),i},this.triggerOnFieldsChange=function(n,a){var i=r.callbacks.onFieldsChange;if(i){var l=r.getFields();if(a){var c=new Nr;a.forEach(function(u){var d=u.name,f=u.errors;c.set(d,f)}),l.forEach(function(u){u.errors=c.get(u.name)||u.errors})}var s=l.filter(function(u){var d=u.name;return ia(n,d)});i(s,l)}},this.validateFields=function(n,a){r.warningUnhooked();var i=!!n,l=i?n.map(It):[],c=[];r.getFieldEntities(!0).forEach(function(d){if(i||l.push(d.getNamePath()),(a==null?void 0:a.recursive)&&i){var f=d.getNamePath();f.every(function(p,g){return n[g]===p||n[g]===void 0})&&l.push(f)}if(!(!d.props.rules||!d.props.rules.length)){var v=d.getNamePath();if(!i||ia(l,v)){var m=d.validateRules(L({validateMessages:L(L({},_s),r.validateMessages)},a));c.push(m.then(function(){return{name:v,errors:[],warnings:[]}}).catch(function(p){var g,h=[],y=[];return(g=p.forEach)===null||g===void 0||g.call(p,function(C){var b=C.rule.warningOnly,x=C.errors;b?y.push.apply(y,ue(x)):h.push.apply(h,ue(x))}),h.length?Promise.reject({name:v,errors:h,warnings:y}):{name:v,errors:h,warnings:y}}))}}});var s=_g(c);r.lastValidatePromise=s,s.catch(function(d){return d}).then(function(d){var f=d.map(function(v){var m=v.name;return m});r.notifyObservers(r.store,f,{type:"validateFinish"}),r.triggerOnFieldsChange(f,d)});var u=s.then(function(){return r.lastValidatePromise===s?Promise.resolve(r.getFieldsValue(l)):Promise.reject([])}).catch(function(d){var f=d.filter(function(v){return v&&v.errors.length});return Promise.reject({values:r.getFieldsValue(l),errorFields:f,outOfDate:r.lastValidatePromise!==s})});return u.catch(function(d){return d}),u},this.submit=function(){r.warningUnhooked(),r.validateFields().then(function(n){var a=r.callbacks.onFinish;if(a)try{a(n)}catch(i){console.error(i)}}).catch(function(n){var a=r.callbacks.onFinishFailed;a&&a(n)})},this.forceRootUpdate=t});function Ri(e){var t=o.useRef(),r=o.useState({}),n=W(r,2),a=n[1];if(!t.current)if(e)t.current=e;else{var i=function(){a({})},l=new $g(i);t.current=l.getForm()}return[t.current]}var ki=o.createContext({triggerFormChange:function(){},triggerFormFinish:function(){},registerForm:function(){},unregisterForm:function(){}}),Oi=function(t){var r=t.validateMessages,n=t.onFormChange,a=t.onFormFinish,i=t.children,l=o.useContext(ki),c=o.useRef({});return o.createElement(ki.Provider,{value:L(L({},l),{},{validateMessages:L(L({},l.validateMessages),r),triggerFormChange:function(u,d){n&&n(u,{changedFields:d,forms:c.current}),l.triggerFormChange(u,d)},triggerFormFinish:function(u,d){a&&a(u,{values:d,forms:c.current}),l.triggerFormFinish(u,d)},registerForm:function(u,d){u&&(c.current=L(L({},c.current),{},T({},u,d))),l.registerForm(u,d)},unregisterForm:function(u){var d=L({},c.current);delete d[u],c.current=d,l.unregisterForm(u)}})},i)},Fg=["name","initialValues","fields","form","preserve","children","component","validateMessages","validateTrigger","onValuesChange","onFieldsChange","onFinish","onFinishFailed"],Ag=function(t,r){var n=t.name,a=t.initialValues,i=t.fields,l=t.form,c=t.preserve,s=t.children,u=t.component,d=u===void 0?"form":u,f=t.validateMessages,v=t.validateTrigger,m=v===void 0?"onChange":v,p=t.onValuesChange,g=t.onFieldsChange,h=t.onFinish,y=t.onFinishFailed,C=Fe(t,Fg),b=o.useContext(ki),x=Ri(l),w=W(x,1),S=w[0],O=S.getInternalHooks(rr),E=O.useSubscribe,k=O.setInitialValues,I=O.setCallbacks,M=O.setValidateMessages,R=O.setPreserve,N=O.destroyForm;o.useImperativeHandle(r,function(){return S}),o.useEffect(function(){return b.registerForm(n,S),function(){b.unregisterForm(n)}},[b,S,n]),M(L(L({},b.validateMessages),f)),I({onValuesChange:p,onFieldsChange:function(K){if(b.triggerFormChange(n,K),g){for(var H=arguments.length,j=new Array(H>1?H-1:0),z=1;z=18&&(Wa=ca.createRoot)}catch(e){}function Zs(e){var t=ca.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;t&&ke(t)==="object"&&(t.usingClientEntryPoint=e)}var Ua="__rc_react_root__";function qg(e,t){Zs(!0);var r=t[Ua]||Wa(t);Zs(!1),r.render(e),t[Ua]=r}function Gg(e,t){Bg(e,t)}function eu(e,t){if(Wa){qg(e,t);return}Gg(e,t)}function Yg(e){return Mi.apply(this,arguments)}function Mi(){return Mi=or(qt().mark(function e(t){return qt().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",Promise.resolve().then(function(){var a;(a=t[Ua])===null||a===void 0||a.unmount(),delete t[Ua]}));case 1:case"end":return n.stop()}},e)})),Mi.apply(this,arguments)}function Xg(e){Wg(e)}function tu(e){return Ti.apply(this,arguments)}function Ti(){return Ti=or(qt().mark(function e(t){return qt().wrap(function(n){for(;;)switch(n.prev=n.next){case 0:if(Wa===void 0){n.next=2;break}return n.abrupt("return",Yg(t));case 2:Xg(t);case 3:case"end":return n.stop()}},e)})),Ti.apply(this,arguments)}function nu(e,t){var r={};return r[e.toLowerCase()]=t.toLowerCase(),r["Webkit".concat(e)]="webkit".concat(t),r["Moz".concat(e)]="moz".concat(t),r["ms".concat(e)]="MS".concat(t),r["O".concat(e)]="o".concat(t.toLowerCase()),r}function Qg(e,t){var r={animationend:nu("Animation","AnimationEnd"),transitionend:nu("Transition","TransitionEnd")};return e&&("AnimationEvent"in t||delete r.animationend.animation,"TransitionEvent"in t||delete r.transitionend.transition),r}var Jg=Qg(Ut(),typeof window!="undefined"?window:{}),ru={};if(Ut()){var Zg=document.createElement("div");ru=Zg.style}var qa={};function au(e){if(qa[e])return qa[e];var t=Jg[e];if(t)for(var r=Object.keys(t),n=r.length,a=0;a1&&arguments[1]!==void 0?arguments[1]:1;mu+=1;var n=mu;function a(i){if(i===0)pu(n),t();else{var l=fu(function(){a(i-1)});Di.set(n,l)}}return a(r),n};nt.cancel=function(e){var t=Di.get(e);return pu(t),vu(t)};var ey=function(){var e=o.useRef(null);function t(){nt.cancel(e.current)}function r(n){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;t();var i=nt(function(){a<=1?n({isCanceled:function(){return i!==e.current}}):r(n,a-1)});e.current=i}return o.useEffect(function(){return function(){t()}},[]),[r,t]},hu=Ut()?o.useLayoutEffect:o.useEffect,gu=[Rn,kr,Or,_i],yu=!1,ty=!0;function Cu(e){return e===Or||e===_i}var ny=function(e,t){var r=kn(du),n=W(r,2),a=n[0],i=n[1],l=ey(),c=W(l,2),s=c[0],u=c[1];function d(){i(Rn,!0)}return hu(function(){if(a!==du&&a!==_i){var f=gu.indexOf(a),v=gu[f+1],m=t(a);m===yu?i(v,!0):s(function(p){function g(){p.isCanceled()||i(v,!0)}m===!0?g():Promise.resolve(m).then(g)})}},[e,a]),o.useEffect(function(){return function(){u()}},[]),[d,a]},ry=function(e){var t=o.useRef(),r=o.useRef(e);r.current=e;var n=o.useCallback(function(l){r.current(l)},[]);function a(l){l&&(l.removeEventListener(su,n),l.removeEventListener(cu,n))}function i(l){t.current&&t.current!==l&&a(t.current),l&&l!==t.current&&(l.addEventListener(su,n),l.addEventListener(cu,n),t.current=l)}return o.useEffect(function(){return function(){a(t.current)}},[]),[i,a]};function ay(e,t,r,n){var a=n.motionEnter,i=a===void 0?!0:a,l=n.motionAppear,c=l===void 0?!0:l,s=n.motionLeave,u=s===void 0?!0:s,d=n.motionDeadline,f=n.motionLeaveImmediately,v=n.onAppearPrepare,m=n.onEnterPrepare,p=n.onLeavePrepare,g=n.onAppearStart,h=n.onEnterStart,y=n.onLeaveStart,C=n.onAppearActive,b=n.onEnterActive,x=n.onLeaveActive,w=n.onAppearEnd,S=n.onEnterEnd,O=n.onLeaveEnd,E=n.onVisibleChanged,k=kn(),I=W(k,2),M=I[0],R=I[1],N=kn(Rr),P=W(N,2),_=P[0],$=P[1],D=kn(null),A=W(D,2),V=A[0],U=A[1],q=o.useRef(!1),K=o.useRef(null);function H(){return r()}var j=o.useRef(!1);function z(ce){var pe=H();if(!(ce&&!ce.deadline&&ce.target!==pe)){var me=j.current,ve;_===Ga&&me?ve=w==null?void 0:w(pe,ce):_===Ya&&me?ve=S==null?void 0:S(pe,ce):_===Xa&&me&&(ve=O==null?void 0:O(pe,ce)),_!==Rr&&me&&ve!==!1&&($(Rr,!0),U(null,!0))}}var B=ry(z),G=W(B,1),Q=G[0],J=o.useMemo(function(){var ce,pe,me;switch(_){case Ga:return ce={},T(ce,Rn,v),T(ce,kr,g),T(ce,Or,C),ce;case Ya:return pe={},T(pe,Rn,m),T(pe,kr,h),T(pe,Or,b),pe;case Xa:return me={},T(me,Rn,p),T(me,kr,y),T(me,Or,x),me;default:return{}}},[_]),Z=ny(_,function(ce){if(ce===Rn){var pe=J[Rn];return pe?pe(H()):yu}if(X in J){var me;U(((me=J[X])===null||me===void 0?void 0:me.call(J,H(),null))||null)}return X===Or&&(Q(H()),d>0&&(clearTimeout(K.current),K.current=setTimeout(function(){z({deadline:!0})},d))),ty}),ne=W(Z,2),de=ne[0],X=ne[1],ae=Cu(X);j.current=ae,hu(function(){R(t);var ce=q.current;if(q.current=!0,!!e){var pe;!ce&&t&&c&&(pe=Ga),ce&&t&&i&&(pe=Ya),(ce&&!t&&u||!ce&&f&&!t&&u)&&(pe=Xa),pe&&($(pe),de())}},[t]),o.useEffect(function(){(_===Ga&&!c||_===Ya&&!i||_===Xa&&!u)&&$(Rr)},[c,i,u]),o.useEffect(function(){return function(){q.current=!1,clearTimeout(K.current)}},[]);var te=o.useRef(!1);o.useEffect(function(){M&&(te.current=!0),M!==void 0&&_===Rr&&((te.current||M)&&(E==null||E(M)),te.current=!0)},[M,_]);var oe=V;return J[Rn]&&X===kr&&(oe=L({transition:"none"},oe)),[_,X,oe,M!=null?M:t]}var oy=function(e){_t(r,e);var t=Dt(r);function r(){return Pt(this,r),t.apply(this,arguments)}return Rt(r,[{key:"render",value:function(){return this.props.children}}]),r}(o.Component);function iy(e){var t=e;ke(e)==="object"&&(t=e.transitionSupport);function r(a){return!!(a.motionName&&t)}var n=o.forwardRef(function(a,i){var l=a.visible,c=l===void 0?!0:l,s=a.removeOnLeave,u=s===void 0?!0:s,d=a.forceRender,f=a.children,v=a.motionName,m=a.leavedClassName,p=a.eventProps,g=r(a),h=o.useRef(),y=o.useRef();function C(){try{return h.current instanceof HTMLElement?h.current:ta(y.current)}catch(D){return null}}var b=ay(g,c,C,a),x=W(b,4),w=x[0],S=x[1],O=x[2],E=x[3],k=o.useRef(E);E&&(k.current=!0);var I=o.useCallback(function(D){h.current=D,Ka(i,D)},[i]),M,R=L(L({},p),{},{visible:c});if(!f)M=null;else if(w===Rr||!r(a))E?M=f(L({},R),I):!u&&k.current?M=f(L(L({},R),{},{className:m}),I):d?M=f(L(L({},R),{},{style:{display:"none"}}),I):M=null;else{var N,P;S===Rn?P="prepare":Cu(S)?P="active":S===kr&&(P="start"),M=f(L(L({},R),{},{className:Y(uu(v,w),(N={},T(N,uu(v,"".concat(w,"-").concat(P)),P),T(N,v,typeof v=="string"),N)),style:O}),I)}if(o.isValidElement(M)&&nr(M)){var _=M,$=_.ref;$||(M=o.cloneElement(M,{ref:I}))}return o.createElement(oy,{ref:y},M)});return n.displayName="CSSMotion",n}var Zt=iy(lu),$i="add",Fi="keep",Ai="remove",Li="removed";function ly(e){var t;return e&&ke(e)==="object"&&"key"in e?t=e:t={key:e},L(L({},t),{},{key:String(t.key)})}function Ki(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return e.map(ly)}function cy(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],r=[],n=0,a=t.length,i=Ki(e),l=Ki(t);i.forEach(function(u){for(var d=!1,f=n;f1});return s.forEach(function(u){r=r.filter(function(d){var f=d.key,v=d.status;return f!==u||v!==Ai}),r.forEach(function(d){d.key===u&&(d.status=Fi)})}),r}var sy=["component","children","onVisibleChanged","onAllRemoved"],uy=["status"],dy=["eventProps","visible","children","motionName","motionAppear","motionEnter","motionLeave","motionLeaveImmediately","motionDeadline","removeOnLeave","leavedClassName","onAppearStart","onAppearActive","onAppearEnd","onEnterStart","onEnterActive","onEnterEnd","onLeaveStart","onLeaveActive","onLeaveEnd"];function fy(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Zt,r=function(n){_t(i,n);var a=Dt(i);function i(){var l;Pt(this,i);for(var c=arguments.length,s=new Array(c),u=0;u=v&&(f.key=h[0].notice.key,f.updateMark=Su(),f.userPassKey=d,h.shift()),h.push({notice:f,holderCallback:s})),{notices:h}})},n.remove=function(c){n.setState(function(s){var u=s.notices;return{notices:u.filter(function(d){var f=d.notice,v=f.key,m=f.userPassKey,p=m!=null?m:v;return p!==c})}})},n.noticePropsMap={},n}return Rt(r,[{key:"getTransitionName",value:function(){var a=this.props,i=a.prefixCls,l=a.animation,c=this.props.transitionName;return!c&&l&&(c="".concat(i,"-").concat(l)),c}},{key:"render",value:function(){var a=this,i=this.state.notices,l=this.props,c=l.prefixCls,s=l.className,u=l.closeIcon,d=l.style,f=[];return i.forEach(function(v,m){var p=v.notice,g=v.holderCallback,h=m===i.length-1?p.updateMark:void 0,y=p.key,C=p.userPassKey,b=L(L(L({prefixCls:c,closeIcon:u},p),p.props),{},{key:y,noticeKey:C||y,updateMark:h,onClose:function(w){var S;a.remove(w),(S=p.onClose)===null||S===void 0||S.call(p)},onClick:p.onClick,children:p.content});f.push(y),a.noticePropsMap[y]={props:b,holderCallback:g}}),o.createElement("div",{className:Y(c,s),style:d},o.createElement(bu,{keys:f,motionName:this.getTransitionName(),onVisibleChanged:function(m,p){var g=p.key;m||delete a.noticePropsMap[g]}},function(v){var m=v.key,p=v.className,g=v.style,h=v.visible,y=a.noticePropsMap[m],C=y.props,b=y.holderCallback;return b?o.createElement("div",{key:m,className:Y(p,"".concat(c,"-hook-holder")),style:L({},g),ref:function(w){typeof m!="undefined"&&(w?(a.hookRefs.set(m,w),b(w,C)):a.hookRefs.delete(m))}}):o.createElement(Vi,F({},C,{className:Y(p,C==null?void 0:C.className),style:L(L({},g),C==null?void 0:C.style),visible:h}))}))}}]),r}(o.Component);Ir.newInstance=void 0,Ir.defaultProps={prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}},Ir.newInstance=function(t,r){var n=t||{},a=n.getContainer,i=Fe(n,vy),l=document.createElement("div");if(a){var c=a();c.appendChild(l)}else document.body.appendChild(l);var s=!1;function u(d){s||(s=!0,r({notice:function(v){d.add(v)},removeNotice:function(v){d.remove(v)},component:d,destroy:function(){tu(l),l.parentNode&&l.parentNode.removeChild(l)},useNotification:function(){return zi(d)}}))}eu(o.createElement(Ir,F({},i,{ref:u})),l)};function py(e,t){var r=function(){var a,i,l=null,c={add:function(g,h){l==null||l.component.add(g,h)}},s=zi(c),u=W(s,2),d=u[0],f=u[1];function v(p){var g=p.prefixCls,h=a("message",g),y=a(),C=p.key||Iu(),b=new Promise(function(w){var S=function(){return typeof p.onClose=="function"&&p.onClose(),w(!0)};e(F(F({},p),{prefixCls:h,rootPrefixCls:y,getPopupContainer:i}),function(O){var E=O.prefixCls,k=O.instance;l=k,d(t(F(F({},p),{key:C,onClose:S}),E))})}),x=function(){l&&l.removeNotice(C)};return x.then=function(w,S){return b.then(w,S)},x.promise=b,x}var m=o.useRef({});return m.current.open=v,_u.forEach(function(p){return $u(m.current,p)}),[m.current,o.createElement(cr,{key:"holder"},function(p){return a=p.getPrefixCls,i=p.getPopupContainer,f})]};return r}var Gt,Eu=3,wu,hy=1,Nu="",ji="move-up",Pu=!1,Ru,ku,Ou=!1;function Iu(){return hy++}function gy(e){e.top!==void 0&&(wu=e.top,Gt=null),e.duration!==void 0&&(Eu=e.duration),e.prefixCls!==void 0&&(Nu=e.prefixCls),e.getContainer!==void 0&&(Ru=e.getContainer,Gt=null),e.transitionName!==void 0&&(ji=e.transitionName,Gt=null,Pu=!0),e.maxCount!==void 0&&(ku=e.maxCount,Gt=null),e.rtl!==void 0&&(Ou=e.rtl)}function Mu(e,t){var r=e.prefixCls,n=e.getPopupContainer,a=Bi(),i=a.getPrefixCls,l=a.getRootPrefixCls,c=a.getIconPrefixCls,s=i("message",r||Nu),u=l(e.rootPrefixCls,s),d=c();if(Gt){t({prefixCls:s,rootPrefixCls:u,iconPrefixCls:d,instance:Gt});return}var f={prefixCls:s,transitionName:Pu?ji:"".concat(u,"-").concat(ji),style:{top:wu},getContainer:Ru||n,maxCount:ku};Ir.newInstance(f,function(v){if(Gt){t({prefixCls:s,rootPrefixCls:u,iconPrefixCls:d,instance:Gt});return}Gt=v,t({prefixCls:s,rootPrefixCls:u,iconPrefixCls:d,instance:v})})}var Tu={info:xh,success:ai,error:Sr,warning:ns,loading:tr},_u=Object.keys(Tu);function Du(e,t,r){var n,a=e.duration!==void 0?e.duration:Eu,i=Tu[e.type],l=Y("".concat(t,"-custom-content"),(n={},T(n,"".concat(t,"-").concat(e.type),e.type),T(n,"".concat(t,"-rtl"),Ou===!0),n));return{key:e.key,duration:a,style:e.style||{},className:e.className,content:o.createElement(_r,{iconPrefixCls:r},o.createElement("div",{className:l},e.icon||i&&o.createElement(i,null),o.createElement("span",null,e.content))),onClose:e.onClose,onClick:e.onClick}}function yy(e){var t=e.key||Iu(),r=new Promise(function(a){var i=function(){return typeof e.onClose=="function"&&e.onClose(),a(!0)};Mu(e,function(l){var c=l.prefixCls,s=l.iconPrefixCls,u=l.instance;u.notice(Du(F(F({},e),{key:t,onClose:i}),c,s))})}),n=function(){var i;Gt&&(Gt.removeNotice(t),(i=e.onClose)===null||i===void 0||i.call(e))};return n.then=function(a,i){return r.then(a,i)},n.promise=r,n}function Cy(e){return Object.prototype.toString.call(e)==="[object Object]"&&!!e.content}var Mr={open:yy,config:gy,destroy:function(t){if(Gt)if(t){var r=Gt,n=r.removeNotice;n(t)}else{var a=Gt,i=a.destroy;i(),Gt=null}}};function $u(e,t){e[t]=function(r,n,a){return Cy(r)?e.open(F(F({},r),{type:t})):(typeof n=="function"&&(a=n,n=void 0),e.open({content:r,duration:n,type:t,onClose:a}))}}_u.forEach(function(e){return $u(Mr,e)}),Mr.warn=Mr.warning,Mr.useMessage=py(Mu,Du);function by(e,t){var r=function(){var a,i=null,l={add:function(p,g){i==null||i.component.add(p,g)}},c=zi(l),s=W(c,2),u=s[0],d=s[1];function f(m){var p=m.prefixCls,g=a("notification",p);e(F(F({},m),{prefixCls:g}),function(h){var y=h.prefixCls,C=h.instance;i=C,u(t(m,y))})}var v=o.useRef({});return v.current.open=f,["success","info","warning","error"].forEach(function(m){v.current[m]=function(p){return v.current.open(F(F({},p),{type:m}))}}),[v.current,o.createElement(cr,{key:"holder"},function(m){return a=m.getPrefixCls,d})]};return r}var gP=function(e,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function c(d){try{u(n.next(d))}catch(f){l(f)}}function s(d){try{u(n.throw(d))}catch(f){l(f)}}function u(d){d.done?i(d.value):a(d.value).then(c,s)}u((n=n.apply(e,t||[])).next())})},lr={},Fu=4.5,Au=24,Lu=24,Ku="",Hi="topRight",Vu,zu,ju=!1,Hu;function xy(e){var t=e.duration,r=e.placement,n=e.bottom,a=e.top,i=e.getContainer,l=e.closeIcon,c=e.prefixCls;c!==void 0&&(Ku=c),t!==void 0&&(Fu=t),r!==void 0?Hi=r:e.rtl&&(Hi="topLeft"),n!==void 0&&(Lu=n),a!==void 0&&(Au=a),i!==void 0&&(Vu=i),l!==void 0&&(zu=l),e.rtl!==void 0&&(ju=e.rtl),e.maxCount!==void 0&&(Hu=e.maxCount)}function Sy(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Au,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Lu,n;switch(e){case"top":n={left:"50%",transform:"translateX(-50%)",right:"auto",top:t,bottom:"auto"};break;case"topLeft":n={left:0,top:t,bottom:"auto"};break;case"topRight":n={right:0,top:t,bottom:"auto"};break;case"bottom":n={left:"50%",transform:"translateX(-50%)",right:"auto",top:"auto",bottom:r};break;case"bottomLeft":n={left:0,top:"auto",bottom:r};break;default:n={right:0,top:"auto",bottom:r};break}return n}function Bu(e,t){var r=e.placement,n=r===void 0?Hi:r,a=e.top,i=e.bottom,l=e.getContainer,c=l===void 0?Vu:l,s=e.prefixCls,u=Bi(),d=u.getPrefixCls,f=u.getIconPrefixCls,v=d("notification",s||Ku),m=f(),p="".concat(v,"-").concat(n),g=lr[p];if(g){Promise.resolve(g).then(function(y){t({prefixCls:"".concat(v,"-notice"),iconPrefixCls:m,instance:y})});return}var h=Y("".concat(v,"-").concat(n),T({},"".concat(v,"-rtl"),ju===!0));lr[p]=new Promise(function(y){Ir.newInstance({prefixCls:v,className:h,style:Sy(n,a,i),getContainer:c,maxCount:Hu},function(C){y(C),t({prefixCls:"".concat(v,"-notice"),iconPrefixCls:m,instance:C})})})}var Ey={success:Wc,info:ms,error:Xc,warning:ii};function Wu(e,t,r){var n=e.duration,a=e.icon,i=e.type,l=e.description,c=e.message,s=e.btn,u=e.onClose,d=e.onClick,f=e.key,v=e.style,m=e.className,p=e.closeIcon,g=p===void 0?zu:p,h=e.props,y=n===void 0?Fu:n,C=null;a?C=o.createElement("span",{className:"".concat(t,"-icon")},e.icon):i&&(C=o.createElement(Ey[i]||null,{className:"".concat(t,"-icon ").concat(t,"-icon-").concat(i)}));var b=o.createElement("span",{className:"".concat(t,"-close-x")},g||o.createElement(Er,{className:"".concat(t,"-close-icon")})),x=!l&&C?o.createElement("span",{className:"".concat(t,"-message-single-line-auto-margin")}):null;return{content:o.createElement(_r,{iconPrefixCls:r},o.createElement("div",{className:C?"".concat(t,"-with-icon"):"",role:"alert"},C,o.createElement("div",{className:"".concat(t,"-message")},x,c),o.createElement("div",{className:"".concat(t,"-description")},l),s?o.createElement("span",{className:"".concat(t,"-btn")},s):null)),duration:y,closable:!0,closeIcon:b,onClose:u,onClick:d,key:f,style:v||{},className:Y(m,T({},"".concat(t,"-").concat(i),!!i)),props:h}}function wy(e){Bu(e,function(t){var r=t.prefixCls,n=t.iconPrefixCls,a=t.instance;a.notice(Wu(e,r,n))})}var Tr={open:wy,close:function(t){Object.keys(lr).forEach(function(r){return Promise.resolve(lr[r]).then(function(n){n.removeNotice(t)})})},config:xy,destroy:function(){Object.keys(lr).forEach(function(t){Promise.resolve(lr[t]).then(function(r){r.destroy()}),delete lr[t]})}};["success","info","warning","error"].forEach(function(e){Tr[e]=function(t){return Tr.open(F(F({},t),{type:e}))}}),Tr.warn=Tr.warning,Tr.useNotification=by(Bu,Wu);var Ny=function(t,r){return r||(t?"ant-".concat(t):"ant")},qe=o.createContext({getPrefixCls:Ny}),cr=qe.Consumer,Py="-ant-".concat(Date.now(),"-").concat(Math.random());function Ry(e,t){var r={},n=function(d,f){var v=d.clone();return v=(f==null?void 0:f(v))||v,v.toRgbString()},a=function(d,f){var v=new ri(d),m=Dc(v.toRgbString());r["".concat(f,"-color")]=n(v),r["".concat(f,"-color-disabled")]=m[1],r["".concat(f,"-color-hover")]=m[4],r["".concat(f,"-color-active")]=m[6],r["".concat(f,"-color-outline")]=v.clone().setAlpha(.2).toRgbString(),r["".concat(f,"-color-deprecated-bg")]=m[0],r["".concat(f,"-color-deprecated-border")]=m[2]};if(t.primaryColor){a(t.primaryColor,"primary");var i=new ri(t.primaryColor),l=Dc(i.toRgbString());l.forEach(function(u,d){r["primary-".concat(d+1)]=u}),r["primary-color-deprecated-l-35"]=n(i,function(u){return u.lighten(35)}),r["primary-color-deprecated-l-20"]=n(i,function(u){return u.lighten(20)}),r["primary-color-deprecated-t-20"]=n(i,function(u){return u.tint(20)}),r["primary-color-deprecated-t-50"]=n(i,function(u){return u.tint(50)}),r["primary-color-deprecated-f-12"]=n(i,function(u){return u.setAlpha(u.getAlpha()*.12)});var c=new ri(l[0]);r["primary-color-active-deprecated-f-30"]=n(c,function(u){return u.setAlpha(u.getAlpha()*.3)}),r["primary-color-active-deprecated-d-02"]=n(c,function(u){return u.darken(2)})}t.successColor&&a(t.successColor,"success"),t.warningColor&&a(t.warningColor,"warning"),t.errorColor&&a(t.errorColor,"error"),t.infoColor&&a(t.infoColor,"info");var s=Object.keys(r).map(function(u){return"--".concat(e,"-").concat(u,": ").concat(r[u],";")});return` + :root { + `.concat(s.join(` +`),` + } + `).trim()}function ky(e,t){var r=Ry(e,t);Ut()&&ti(r,"".concat(Py,"-dynamic-theme"))}var hn=o.createContext(!1),Uu=function(t){var r=t.children,n=t.disabled,a=o.useContext(hn);return o.createElement(hn.Provider,{value:n!=null?n:a},r)},en=o.createContext(void 0),qu=function(t){var r=t.children,n=t.size;return o.createElement(en.Consumer,null,function(a){return o.createElement(en.Provider,{value:n||a},r)})},Oy=["getTargetContainer","getPopupContainer","renderEmpty","pageHeader","input","pagination","form"],Iy="ant",My="anticon",Qa,Gu;function Ja(){return Qa||Iy}function Ty(){return Gu||My}var _y=function(t){var r=t.prefixCls,n=t.iconPrefixCls,a=t.theme;r!==void 0&&(Qa=r),n!==void 0&&(Gu=n),a&&ky(Ja(),a)},Bi=function(){return{getPrefixCls:function(r,n){return n||(r?"".concat(Ja(),"-").concat(r):Ja())},getIconPrefixCls:Ty,getRootPrefixCls:function(r,n){return r||Qa||(n&&n.includes("-")?n.replace(/^(.*)-[^-]*$/,"$1"):Ja())}}},Dy=function(t){var r,n,a=t.children,i=t.csp,l=t.autoInsertSpaceInButton,c=t.form,s=t.locale,u=t.componentSize,d=t.direction,f=t.space,v=t.virtual,m=t.dropdownMatchSelectWidth,p=t.legacyLocale,g=t.parentContext,h=t.iconPrefixCls,y=t.componentDisabled,C=o.useCallback(function(E,k){var I=t.prefixCls;if(k)return k;var M=I||g.getPrefixCls("");return E?"".concat(M,"-").concat(E):M},[g.getPrefixCls,t.prefixCls]),b=F(F({},g),{csp:i,autoInsertSpaceInButton:l,locale:s||p,direction:d,space:f,virtual:v,dropdownMatchSelectWidth:m,getPrefixCls:C});Oy.forEach(function(E){var k=t[E];k&&(b[E]=k)});var x=La(function(){return b},b,function(E,k){var I=Object.keys(E),M=Object.keys(k);return I.length!==M.length||I.some(function(R){return E[R]!==k[R]})}),w=o.useMemo(function(){return{prefixCls:h,csp:i}},[h,i]),S=a,O={};return s&&(O=((r=s.Form)===null||r===void 0?void 0:r.defaultValidateMessages)||((n=Pn.Form)===null||n===void 0?void 0:n.defaultValidateMessages)||{}),c&&c.validateMessages&&(O=F(F({},O),c.validateMessages)),Object.keys(O).length>0&&(S=o.createElement(Oi,{validateMessages:O},a)),s&&(S=o.createElement(zg,{locale:s,_ANT_MARK__:Vg},S)),(h||i)&&(S=o.createElement(Fp.Provider,{value:w},S)),u&&(S=o.createElement(qu,{size:u},S)),y!==void 0&&(S=o.createElement(Uu,{disabled:y},S)),o.createElement(qe.Provider,{value:x},S)},_r=function(t){return o.useEffect(function(){t.direction&&(Mr.config({rtl:t.direction==="rtl"}),Tr.config({rtl:t.direction==="rtl"}))},[t.direction]),o.createElement(la,null,function(r,n,a){return o.createElement(cr,null,function(i){return o.createElement(Dy,F({parentContext:i,legacyLocale:a},t))})})};_r.ConfigContext=qe,_r.SizeContext=en,_r.config=_y;function On(e,t,r,n){var a=Vn.unstable_batchedUpdates?function(l){Vn.unstable_batchedUpdates(r,l)}:r;return e.addEventListener&&e.addEventListener(t,a,n),{remove:function(){e.removeEventListener&&e.removeEventListener(t,a,n)}}}function $y(e){return Object.keys(e).reduce(function(t,r){return(r.startsWith("data-")||r.startsWith("aria-")||r==="role")&&!r.startsWith("data-__")&&(t[r]=e[r]),t},{})}var cn=o.isValidElement;function Yu(e){return e&&cn(e)&&e.type===o.Fragment}function Fy(e,t,r){return cn(e)?o.cloneElement(e,typeof r=="function"?r(e.props||{}):r):t}function Ht(e,t){return Fy(e,e,t)}function Wi(e){return e!=null&&e===e.window}function Ay(e,t){var r,n;if(typeof window=="undefined")return 0;var a=t?"scrollTop":"scrollLeft",i=0;return Wi(e)?i=e[t?"pageYOffset":"pageXOffset"]:e instanceof Document?i=e.documentElement[a]:(e instanceof HTMLElement||e)&&(i=e[a]),e&&!Wi(e)&&typeof i!="number"&&(i=(n=((r=e.ownerDocument)!==null&&r!==void 0?r:e).documentElement)===null||n===void 0?void 0:n[a]),i}function Ly(e,t,r,n){var a=r-t;return e/=n/2,e<1?a/2*e*e*e+t:a/2*((e-=2)*e*e+2)+t}function Ky(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=t.getContainer,n=r===void 0?function(){return window}:r,a=t.callback,i=t.duration,l=i===void 0?450:i,c=n(),s=Ay(c,!0),u=Date.now(),d=function f(){var v=Date.now(),m=v-u,p=Ly(m>l?l:m,s,e,l);Wi(c)?c.scrollTo(window.pageXOffset,p):c instanceof Document||c.constructor.name==="HTMLDocument"?c.documentElement.scrollTop=p:c.scrollTop=p,m=ie.F1&&r<=ie.F12)return!1;switch(r){case ie.ALT:case ie.CAPS_LOCK:case ie.CONTEXT_MENU:case ie.CTRL:case ie.DOWN:case ie.END:case ie.ESC:case ie.HOME:case ie.INSERT:case ie.LEFT:case ie.MAC_FF_META:case ie.META:case ie.NUMLOCK:case ie.NUM_CENTER:case ie.PAGE_DOWN:case ie.PAGE_UP:case ie.PAUSE:case ie.PRINT_SCREEN:case ie.RIGHT:case ie.SHIFT:case ie.UP:case ie.WIN_KEY:case ie.WIN_KEY_RIGHT:return!1;default:return!0}},isCharacterKey:function(t){if(t>=ie.ZERO&&t<=ie.NINE||t>=ie.NUM_ZERO&&t<=ie.NUM_MULTIPLY||t>=ie.A&&t<=ie.Z||window.navigator.userAgent.indexOf("WebKit")!==-1&&t===0)return!0;switch(t){case ie.SPACE:case ie.QUESTION_MARK:case ie.NUM_PLUS:case ie.NUM_MINUS:case ie.NUM_PERIOD:case ie.NUM_DIVISION:case ie.SEMICOLON:case ie.DASH:case ie.EQUALS:case ie.COMMA:case ie.PERIOD:case ie.SLASH:case ie.APOSTROPHE:case ie.SINGLE_QUOTE:case ie.OPEN_SQUARE_BRACKET:case ie.BACKSLASH:case ie.CLOSE_SQUARE_BRACKET:return!0;default:return!1}}},Xu=o.createContext(null);function Za(){return o.useContext(Xu)}function zy(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:10,t=o.useState(!1),r=W(t,2),n=r[0],a=r[1],i=o.useRef(null),l=function(){window.clearTimeout(i.current)};o.useEffect(function(){return l},[]);var c=function(u,d){l(),i.current=window.setTimeout(function(){a(u),d&&d()},e)};return[n,c,l]}function Qu(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:250,t=o.useRef(null),r=o.useRef(null);o.useEffect(function(){return function(){window.clearTimeout(r.current)}},[]);function n(a){(a||t.current===null)&&(t.current=a),window.clearTimeout(r.current),r.current=window.setTimeout(function(){t.current=null},e)}return[function(){return t.current},n]}function jy(e,t,r,n){var a=o.useRef(null);a.current={open:t,triggerOpen:r,customizedTrigger:n},o.useEffect(function(){function i(l){var c;if(!((c=a.current)!==null&&c!==void 0&&c.customizedTrigger)){var s=l.target;s.shadowRoot&&l.composed&&(s=l.composedPath()[0]||s),a.current.open&&e().filter(function(u){return u}).every(function(u){return!u.contains(s)&&u!==s})&&a.current.triggerOpen(!1)}}return window.addEventListener("mousedown",i),function(){return window.removeEventListener("mousedown",i)}},[])}var Hy=`accept acceptCharset accessKey action allowFullScreen allowTransparency + alt async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge + charSet checked classID className colSpan cols content contentEditable contextMenu + controls coords crossOrigin data dateTime default defer dir disabled download draggable + encType form formAction formEncType formMethod formNoValidate formTarget frameBorder + headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode integrity + is keyParams keyType kind label lang list loop low manifest marginHeight marginWidth max maxLength media + mediaGroup method min minLength multiple muted name noValidate nonce open + optimum pattern placeholder poster preload radioGroup readOnly rel required + reversed role rowSpan rows sandbox scope scoped scrolling seamless selected + shape size sizes span spellCheck src srcDoc srcLang srcSet start step style + summary tabIndex target title type useMap value width wmode wrap`,By=`onCopy onCut onPaste onCompositionEnd onCompositionStart onCompositionUpdate onKeyDown + onKeyPress onKeyUp onFocus onBlur onChange onInput onSubmit onClick onContextMenu onDoubleClick + onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown + onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp onSelect onTouchCancel + onTouchEnd onTouchMove onTouchStart onScroll onWheel onAbort onCanPlay onCanPlayThrough + onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata + onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting onLoad onError`,Wy="".concat(Hy," ").concat(By).split(/[\s\n]+/),Uy="aria-",qy="data-";function Ju(e,t){return e.indexOf(t)===0}function Bn(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r;t===!1?r={aria:!0,data:!0,attr:!0}:t===!0?r={aria:!0}:r=L({},t);var n={};return Object.keys(e).forEach(function(a){(r.aria&&(a==="role"||Ju(a,Uy))||r.data&&Ju(a,qy)||r.attr&&Wy.includes(a))&&(n[a]=e[a])}),n}var Gy=["prefixCls","invalidate","item","renderItem","responsive","responsiveDisabled","registerSize","itemKey","className","style","children","display","order","component"],Dr=void 0;function Yy(e,t){var r=e.prefixCls,n=e.invalidate,a=e.item,i=e.renderItem,l=e.responsive,c=e.responsiveDisabled,s=e.registerSize,u=e.itemKey,d=e.className,f=e.style,v=e.children,m=e.display,p=e.order,g=e.component,h=g===void 0?"div":g,y=Fe(e,Gy),C=l&&!m;function b(E){s(u,E)}o.useEffect(function(){return function(){b(null)}},[]);var x=i&&a!==Dr?i(a):v,w;n||(w={opacity:C?0:1,height:C?0:Dr,overflowY:C?"hidden":Dr,order:l?p:Dr,pointerEvents:C?"none":Dr,position:C?"absolute":Dr});var S={};C&&(S["aria-hidden"]=!0);var O=o.createElement(h,F({className:Y(!n&&r,d),style:L(L({},w),f)},S,y,{ref:t}),x);return l&&(O=o.createElement(pn,{onResize:function(k){var I=k.offsetWidth;b(I)},disabled:c},O)),O}var ua=o.forwardRef(Yy);ua.displayName="Item";function Xy(){var e=kn({}),t=W(e,2),r=t[1],n=o.useRef([]),a=0,i=0;function l(c){var s=a;a+=1,n.current.lengthp,ge=o.useMemo(function(){var le=i;return Ce?M===null&&E?le=i:le=i.slice(0,Math.min(i.length,N/d)):typeof p=="number"&&(le=i.slice(0,p)),le},[i,d,M,p,Ce]),xe=o.useMemo(function(){return Ce?i.slice(pe+1):i.slice(ge.length)},[i,ge,Ce,pe]),De=o.useCallback(function(le,fe){var he;return typeof s=="function"?s(le):(he=s&&(le==null?void 0:le[s]))!==null&&he!==void 0?he:fe},[s]),we=o.useCallback(l||function(le){return le},[l]);function Oe(le,fe,he){oe===le&&(fe===void 0||fe===de)||(ce(le),he||(ee(leN){Oe(be-1,le-Ie-Q+j);break}}y&&Ye(0)+Q>N&&X(null)}},[N,$,j,Q,De,ge]);var ot=se&&!!xe.length,Ae={};de!==null&&Ce&&(Ae={position:"absolute",left:de,top:0});var $e={prefixCls:re,responsive:Ce,component:x,invalidate:_e},rt=c?function(le,fe){var he=De(le,fe);return o.createElement(eo.Provider,{key:he,value:L(L({},$e),{},{order:fe,item:le,itemKey:he,registerSize:et,display:fe<=pe})},c(le,fe))}:function(le,fe){var he=De(le,fe);return o.createElement(ua,F({},$e,{order:fe,key:he,item:le,renderItem:we,itemKey:he,registerSize:et,display:fe<=pe}))},tt,Ze={order:ot?pe:Number.MAX_SAFE_INTEGER,className:"".concat(re,"-rest"),registerSize:Ke,display:ot};if(h)h&&(tt=o.createElement(eo.Provider,{value:L(L({},$e),Ze)},h(xe)));else{var Me=g||nC;tt=o.createElement(ua,F({},$e,Ze),typeof Me=="function"?Me(xe):Me)}var Se=o.createElement(b,F({className:Y(!_e&&n,m),style:v,ref:t},S),ge.map(rt),Ee?tt:null,y&&o.createElement(ua,F({},$e,{responsive:Ne,responsiveDisabled:!Ce,order:pe,className:"".concat(re,"-suffix"),registerSize:ut,display:!0,style:Ae}),y));return Ne&&(Se=o.createElement(pn,{onResize:Le,disabled:!Ce},Se)),Se}var gn=o.forwardRef(rC);gn.displayName="Overflow",gn.Item=Zu,gn.RESPONSIVE=ed,gn.INVALIDATE=td;var to=function(t){var r=t.className,n=t.customizeIcon,a=t.customizeIconProps,i=t.onMouseDown,l=t.onClick,c=t.children,s;return typeof n=="function"?s=n(a):s=n,o.createElement("span",{className:r,onMouseDown:function(d){d.preventDefault(),i&&i(d)},style:{userSelect:"none",WebkitUserSelect:"none"},unselectable:"on",onClick:l,"aria-hidden":!0},s!==void 0?s:o.createElement("span",{className:Y(r.split(/\s+/).map(function(u){return"".concat(u,"-icon")}))},c))},aC=function(t,r){var n,a,i=t.prefixCls,l=t.id,c=t.inputElement,s=t.disabled,u=t.tabIndex,d=t.autoFocus,f=t.autoComplete,v=t.editable,m=t.activeDescendantId,p=t.value,g=t.maxLength,h=t.onKeyDown,y=t.onMouseDown,C=t.onChange,b=t.onPaste,x=t.onCompositionStart,w=t.onCompositionEnd,S=t.open,O=t.attrs,E=c||o.createElement("input",null),k=E,I=k.ref,M=k.props,R=M.onKeyDown,N=M.onChange,P=M.onMouseDown,_=M.onCompositionStart,$=M.onCompositionEnd,D=M.style;return Ap(!("maxLength"in E.props)),E=o.cloneElement(E,L(L(L({type:"search"},M),{},{id:l,ref:on(r,I),disabled:s,tabIndex:u,autoComplete:f||"off",autoFocus:d,className:Y("".concat(i,"-selection-search-input"),(n=E)===null||n===void 0||(a=n.props)===null||a===void 0?void 0:a.className),role:"combobox","aria-expanded":S,"aria-haspopup":"listbox","aria-owns":"".concat(l,"_list"),"aria-autocomplete":"list","aria-controls":"".concat(l,"_list"),"aria-activedescendant":m},O),{},{value:v?p:"",maxLength:g,readOnly:!v,unselectable:v?null:"on",style:L(L({},D),{},{opacity:v?null:0}),onKeyDown:function(V){h(V),R&&R(V)},onMouseDown:function(V){y(V),P&&P(V)},onChange:function(V){C(V),N&&N(V)},onCompositionStart:function(V){x(V),_&&_(V)},onCompositionEnd:function(V){w(V),$&&$(V)},onPaste:b})),E},Gi=o.forwardRef(aC);Gi.displayName="Input";function nd(e){return Array.isArray(e)?e:e!==void 0?[e]:[]}var oC=typeof window!="undefined"&&window.document&&window.document.documentElement,iC=oC;function lC(e){return e!=null}function rd(e){return["string","number"].includes(ke(e))}function ad(e){var t=void 0;return e&&(rd(e.title)?t=e.title.toString():rd(e.label)&&(t=e.label.toString())),t}function cC(e,t){iC?o.useLayoutEffect(e,t):o.useEffect(e,t)}function sC(e){var t;return(t=e.key)!==null&&t!==void 0?t:e.value}var od=function(t){t.preventDefault(),t.stopPropagation()},uC=function(t){var r=t.id,n=t.prefixCls,a=t.values,i=t.open,l=t.searchValue,c=t.autoClearSearchValue,s=t.inputRef,u=t.placeholder,d=t.disabled,f=t.mode,v=t.showSearch,m=t.autoFocus,p=t.autoComplete,g=t.activeDescendantId,h=t.tabIndex,y=t.removeIcon,C=t.maxTagCount,b=t.maxTagTextLength,x=t.maxTagPlaceholder,w=x===void 0?function(X){return"+ ".concat(X.length," ...")}:x,S=t.tagRender,O=t.onToggleOpen,E=t.onRemove,k=t.onInputChange,I=t.onInputPaste,M=t.onInputKeyDown,R=t.onInputMouseDown,N=t.onInputCompositionStart,P=t.onInputCompositionEnd,_=o.useRef(null),$=o.useState(0),D=W($,2),A=D[0],V=D[1],U=o.useState(!1),q=W(U,2),K=q[0],H=q[1],j="".concat(n,"-selection"),z=i||f==="multiple"&&c===!1||f==="tags"?l:"",B=f==="tags"||f==="multiple"&&c===!1||v&&(i||K);cC(function(){V(_.current.scrollWidth)},[z]);function G(X,ae,te,oe,ce){return o.createElement("span",{className:Y("".concat(j,"-item"),T({},"".concat(j,"-item-disabled"),te)),title:ad(X)},o.createElement("span",{className:"".concat(j,"-item-content")},ae),oe&&o.createElement(to,{className:"".concat(j,"-item-remove"),onMouseDown:od,onClick:ce,customizeIcon:y},"\xD7"))}function Q(X,ae,te,oe,ce){var pe=function(ve){od(ve),O(!i)};return o.createElement("span",{onMouseDown:pe},S({label:ae,value:X,disabled:te,closable:oe,onClose:ce}))}function J(X){var ae=X.disabled,te=X.label,oe=X.value,ce=!d&&!ae,pe=te;if(typeof b=="number"&&(typeof te=="string"||typeof te=="number")){var me=String(pe);me.length>b&&(pe="".concat(me.slice(0,b),"..."))}var ve=function(ee){ee&&ee.stopPropagation(),E(X)};return typeof S=="function"?Q(oe,pe,ae,ce,ve):G(X,pe,ae,ce,ve)}function Z(X){var ae=typeof w=="function"?w(X):w;return G({title:ae},ae,!1)}var ne=o.createElement("div",{className:"".concat(j,"-search"),style:{width:A},onFocus:function(){H(!0)},onBlur:function(){H(!1)}},o.createElement(Gi,{ref:s,open:i,prefixCls:n,id:r,inputElement:null,disabled:d,autoFocus:m,autoComplete:p,editable:B,activeDescendantId:g,value:z,onKeyDown:M,onMouseDown:R,onChange:k,onPaste:I,onCompositionStart:N,onCompositionEnd:P,tabIndex:h,attrs:Bn(t,!0)}),o.createElement("span",{ref:_,className:"".concat(j,"-search-mirror"),"aria-hidden":!0},z,"\xA0")),de=o.createElement(gn,{prefixCls:"".concat(j,"-overflow"),data:a,renderItem:J,renderRest:Z,suffix:ne,itemKey:sC,maxCount:C});return o.createElement(o.Fragment,null,de,!a.length&&!z&&o.createElement("span",{className:"".concat(j,"-placeholder")},u))},dC=function(t){var r=t.inputElement,n=t.prefixCls,a=t.id,i=t.inputRef,l=t.disabled,c=t.autoFocus,s=t.autoComplete,u=t.activeDescendantId,d=t.mode,f=t.open,v=t.values,m=t.placeholder,p=t.tabIndex,g=t.showSearch,h=t.searchValue,y=t.activeValue,C=t.maxLength,b=t.onInputKeyDown,x=t.onInputMouseDown,w=t.onInputChange,S=t.onInputPaste,O=t.onInputCompositionStart,E=t.onInputCompositionEnd,k=o.useState(!1),I=W(k,2),M=I[0],R=I[1],N=d==="combobox",P=N||g,_=v[0],$=h||"";N&&y&&!M&&($=y),o.useEffect(function(){N&&R(!1)},[N,y]);var D=d!=="combobox"&&!f&&!g?!1:!!$,A=ad(_),V=function(){if(_)return null;var q=D?{visibility:"hidden"}:void 0;return o.createElement("span",{className:"".concat(n,"-selection-placeholder"),style:q},m)};return o.createElement(o.Fragment,null,o.createElement("span",{className:"".concat(n,"-selection-search")},o.createElement(Gi,{ref:i,prefixCls:n,id:a,open:f,inputElement:r,disabled:l,autoFocus:c,autoComplete:s,editable:P,activeDescendantId:u,value:$,onKeyDown:b,onMouseDown:x,onChange:function(q){R(!0),w(q)},onPaste:S,onCompositionStart:O,onCompositionEnd:E,tabIndex:p,attrs:Bn(t,!0),maxLength:N?C:void 0})),!N&&_&&!D&&o.createElement("span",{className:"".concat(n,"-selection-item"),title:A},_.label),V())};function fC(e){return![ie.ESC,ie.SHIFT,ie.BACKSPACE,ie.TAB,ie.WIN_KEY,ie.ALT,ie.META,ie.WIN_KEY_RIGHT,ie.CTRL,ie.SEMICOLON,ie.EQUALS,ie.CAPS_LOCK,ie.CONTEXT_MENU,ie.F1,ie.F2,ie.F3,ie.F4,ie.F5,ie.F6,ie.F7,ie.F8,ie.F9,ie.F10,ie.F11,ie.F12].includes(e)}var vC=function(t,r){var n=o.useRef(null),a=o.useRef(!1),i=t.prefixCls,l=t.open,c=t.mode,s=t.showSearch,u=t.tokenWithEnter,d=t.onSearch,f=t.onSearchSubmit,v=t.onToggleOpen,m=t.onInputKeyDown,p=t.domRef;o.useImperativeHandle(r,function(){return{focus:function(){n.current.focus()},blur:function(){n.current.blur()}}});var g=Qu(0),h=W(g,2),y=h[0],C=h[1],b=function($){var D=$.which;(D===ie.UP||D===ie.DOWN)&&$.preventDefault(),m&&m($),D===ie.ENTER&&c==="tags"&&!a.current&&!l&&(f==null||f($.target.value)),fC(D)&&v(!0)},x=function(){C(!0)},w=o.useRef(null),S=function($){d($,!0,a.current)!==!1&&v(!0)},O=function(){a.current=!0},E=function($){a.current=!1,c!=="combobox"&&S($.target.value)},k=function($){var D=$.target.value;if(u&&w.current&&/[\r\n]/.test(w.current)){var A=w.current.replace(/[\r\n]+$/,"").replace(/\r\n/g," ").replace(/[\r\n]/g," ");D=D.replace(A,w.current)}w.current=null,S(D)},I=function($){var D=$.clipboardData,A=D.getData("text");w.current=A},M=function($){var D=$.target;if(D!==n.current){var A=document.body.style.msTouchAction!==void 0;A?setTimeout(function(){n.current.focus()}):n.current.focus()}},R=function($){var D=y();$.target!==n.current&&!D&&c!=="combobox"&&$.preventDefault(),(c!=="combobox"&&(!s||!D)||!l)&&(l&&d("",!0,!1),v())},N={inputRef:n,onInputKeyDown:b,onInputMouseDown:x,onInputChange:k,onInputPaste:I,onInputCompositionStart:O,onInputCompositionEnd:E},P=c==="multiple"||c==="tags"?o.createElement(uC,F({},t,N)):o.createElement(dC,F({},t,N));return o.createElement("div",{ref:p,className:"".concat(i,"-selector"),onClick:M,onMouseDown:R},P)},id=o.forwardRef(vC);id.displayName="Selector";var mC=o.forwardRef(function(e,t){var r=e.didUpdate,n=e.getContainer,a=e.children,i=o.useRef(),l=o.useRef();o.useImperativeHandle(t,function(){return{}});var c=o.useRef(!1);return!c.current&&Ut()&&(l.current=n(),i.current=l.current.parentNode,c.current=!0),o.useEffect(function(){r==null||r(e)}),o.useEffect(function(){return l.current.parentNode===null&&i.current!==null&&i.current.appendChild(l.current),function(){var s,u;(s=l.current)===null||s===void 0||(u=s.parentNode)===null||u===void 0||u.removeChild(l.current)}},[]),l.current?Vn.createPortal(a,l.current):null});function pC(e,t,r){return r?e[0]===t[0]:e[0]===t[0]&&e[1]===t[1]}function hC(e,t,r){var n=e[t]||{};return L(L({},n),r)}function gC(e,t,r,n){for(var a=r.points,i=Object.keys(e),l=0;l=0&&r.left>=0&&r.bottom>r.top&&r.right>r.left?r:null}function zC(e,t,r,n){var a=Je.clone(e),i={width:t.width,height:t.height};return n.adjustX&&a.left=r.left&&a.left+i.width>r.right&&(i.width-=a.left+i.width-r.right),n.adjustX&&a.left+i.width>r.right&&(a.left=Math.max(r.right-i.width,r.left)),n.adjustY&&a.top=r.top&&a.top+i.height>r.bottom&&(i.height-=a.top+i.height-r.bottom),n.adjustY&&a.top+i.height>r.bottom&&(a.top=Math.max(r.bottom-i.height,r.top)),Je.mix(a,i)}function ll(e){var t,r,n;if(!Je.isWindow(e)&&e.nodeType!==9)t=Je.offset(e),r=Je.outerWidth(e),n=Je.outerHeight(e);else{var a=Je.getWindow(e);t={left:Je.getWindowScrollLeft(a),top:Je.getWindowScrollTop(a)},r=Je.viewportWidth(a),n=Je.viewportHeight(a)}return t.width=r,t.height=n,t}function wd(e,t){var r=t.charAt(0),n=t.charAt(1),a=e.width,i=e.height,l=e.left,c=e.top;return r==="c"?c+=i/2:r==="b"&&(c+=i),n==="c"?l+=a/2:n==="r"&&(l+=a),{left:l,top:c}}function oo(e,t,r,n,a){var i=wd(t,r[1]),l=wd(e,r[0]),c=[l.left-i.left,l.top-i.top];return{left:Math.round(e.left-c[0]+n[0]-a[0]),top:Math.round(e.top-c[1]+n[1]-a[1])}}function Nd(e,t,r){return e.leftr.right}function Pd(e,t,r){return e.topr.bottom}function jC(e,t,r){return e.left>r.right||e.left+t.widthr.bottom||e.top+t.height=r.right||n.top>=r.bottom}function cl(e,t,r){var n=r.target||t,a=ll(n),i=!BC(n,r.overflow&&r.overflow.alwaysByViewport);return Od(e,a,r,i)}cl.__getOffsetParent=ol,cl.__getVisibleRectForElement=il;function WC(e,t,r){var n,a,i=Je.getDocument(e),l=i.defaultView||i.parentWindow,c=Je.getWindowScrollLeft(l),s=Je.getWindowScrollTop(l),u=Je.viewportWidth(l),d=Je.viewportHeight(l);"pageX"in t?n=t.pageX:n=c+t.clientX,"pageY"in t?a=t.pageY:a=s+t.clientY;var f={left:n,top:a,width:0,height:0},v=n>=0&&n<=c+u&&a>=0&&a<=s+d,m=[r.points[0],"cc"];return Od(e,f,sd(sd({},r),{},{points:m}),v)}function UC(e,t){return Vp(e,t)}var sl=UC;function qC(e,t){return e===t?!0:!e||!t?!1:"pageX"in t&&"pageY"in t?e.pageX===t.pageX&&e.pageY===t.pageY:"clientX"in t&&"clientY"in t?e.clientX===t.clientX&&e.clientY===t.clientY:!1}function GC(e,t){e!==document.activeElement&&br(t,e)&&typeof e.focus=="function"&&e.focus()}function Id(e,t){var r=null,n=null;function a(l){var c=W(l,1),s=c[0].target;if(!!document.documentElement.contains(s)){var u=s.getBoundingClientRect(),d=u.width,f=u.height,v=Math.floor(d),m=Math.floor(f);(r!==v||n!==m)&&Promise.resolve().then(function(){t({width:v,height:m})}),r=v,n=m}}var i=new Kc(a);return e&&i.observe(e),function(){i.disconnect()}}var YC=function(e,t){var r=o.useRef(!1),n=o.useRef(null);function a(){window.clearTimeout(n.current)}function i(l){if(a(),!r.current||l===!0){if(e()===!1)return;r.current=!0,n.current=window.setTimeout(function(){r.current=!1},t)}else n.current=window.setTimeout(function(){r.current=!1,i()},t)}return[i,function(){r.current=!1,a()}]};function Md(e){return typeof e!="function"?null:e()}function Td(e){return ke(e)!=="object"||!e?null:e}var XC=function(t,r){var n=t.children,a=t.disabled,i=t.target,l=t.align,c=t.onAlign,s=t.monitorWindowResize,u=t.monitorBufferTime,d=u===void 0?0:u,f=o.useRef({}),v=o.useRef(),m=o.Children.only(n),p=o.useRef({});p.current.disabled=a,p.current.target=i,p.current.align=l,p.current.onAlign=c;var g=YC(function(){var S=p.current,O=S.disabled,E=S.target,k=S.align,I=S.onAlign;if(!O&&E){var M=v.current,R,N=Md(E),P=Td(E);f.current.element=N,f.current.point=P,f.current.align=k;var _=document,$=_.activeElement;return N&&Yi(N)?R=cl(M,N,k):P&&(R=WC(M,P,k)),GC($,M),I&&R&&I(M,R),!0}return!1},d),h=W(g,2),y=h[0],C=h[1],b=o.useRef({cancel:function(){}}),x=o.useRef({cancel:function(){}});o.useEffect(function(){var S=Md(i),O=Td(i);v.current!==x.current.element&&(x.current.cancel(),x.current.element=v.current,x.current.cancel=Id(v.current,y)),(f.current.element!==S||!qC(f.current.point,O)||!sl(f.current.align,l))&&(y(),b.current.element!==S&&(b.current.cancel(),b.current.element=S,b.current.cancel=Id(S,y)))}),o.useEffect(function(){a?C():y()},[a]);var w=o.useRef(null);return o.useEffect(function(){s?w.current||(w.current=On(window,"resize",y)):w.current&&(w.current.remove(),w.current=null)},[s]),o.useEffect(function(){return function(){b.current.cancel(),x.current.cancel(),w.current&&w.current.remove(),C()}},[]),o.useImperativeHandle(r,function(){return{forceAlign:function(){return y(!0)}}}),o.isValidElement(m)&&(m=o.cloneElement(m,{ref:on(m.ref,v)})),m},_d=o.forwardRef(XC);_d.displayName="Align";var Dd=["measure","alignPre","align",null,"motion"],QC=function(e,t){var r=kn(null),n=W(r,2),a=n[0],i=n[1],l=o.useRef();function c(d){i(d,!0)}function s(){nt.cancel(l.current)}function u(d){s(),l.current=nt(function(){c(function(f){switch(a){case"align":return"motion";case"motion":return"stable"}return f}),d==null||d()})}return o.useEffect(function(){c("measure")},[e]),o.useEffect(function(){switch(a){case"measure":t();break}a&&(l.current=nt(or(qt().mark(function d(){var f,v;return qt().wrap(function(p){for(;;)switch(p.prev=p.next){case 0:f=Dd.indexOf(a),v=Dd[f+1],v&&f!==-1&&c(v);case 3:case"end":return p.stop()}},d)}))))},[a]),o.useEffect(function(){return function(){s()}},[]),[a,u]},JC=function(e){var t=o.useState({width:0,height:0}),r=W(t,2),n=r[0],a=r[1];function i(c){a({width:c.offsetWidth,height:c.offsetHeight})}var l=o.useMemo(function(){var c={};if(e){var s=n.width,u=n.height;e.indexOf("height")!==-1&&u?c.height=u:e.indexOf("minHeight")!==-1&&u&&(c.minHeight=u),e.indexOf("width")!==-1&&s?c.width=s:e.indexOf("minWidth")!==-1&&s&&(c.minWidth=s)}return c},[e,n]);return[l,i]},$d=o.forwardRef(function(e,t){var r=e.visible,n=e.prefixCls,a=e.className,i=e.style,l=e.children,c=e.zIndex,s=e.stretch,u=e.destroyPopupOnHide,d=e.forceRender,f=e.align,v=e.point,m=e.getRootDomNode,p=e.getClassNameFromAlign,g=e.onAlign,h=e.onMouseEnter,y=e.onMouseLeave,C=e.onMouseDown,b=e.onTouchStart,x=e.onClick,w=o.useRef(),S=o.useRef(),O=o.useState(),E=W(O,2),k=E[0],I=E[1],M=JC(s),R=W(M,2),N=R[0],P=R[1];function _(){s&&P(m())}var $=QC(r,_),D=W($,2),A=D[0],V=D[1],U=o.useState(0),q=W(U,2),K=q[0],H=q[1],j=o.useRef();jt(function(){A==="alignPre"&&H(0)},[A]);function z(){return v||m}function B(){var X;(X=w.current)===null||X===void 0||X.forceAlign()}function G(X,ae){var te=p(ae);k!==te&&I(te),H(function(oe){return oe+1}),A==="align"&&(g==null||g(X,ae))}jt(function(){A==="align"&&(K<3?B():V(function(){var X;(X=j.current)===null||X===void 0||X.call(j)}))},[K]);var Q=L({},ld(e));["onAppearEnd","onEnterEnd","onLeaveEnd"].forEach(function(X){var ae=Q[X];Q[X]=function(te,oe){return V(),ae==null?void 0:ae(te,oe)}});function J(){return new Promise(function(X){j.current=X})}o.useEffect(function(){!Q.motionName&&A==="motion"&&V()},[Q.motionName,A]),o.useImperativeHandle(t,function(){return{forceAlign:B,getElement:function(){return S.current}}});var Z=L(L({},N),{},{zIndex:c,opacity:A==="motion"||A==="stable"||!r?void 0:0,pointerEvents:!r&&A!=="stable"?"none":void 0},i),ne=!0;f!=null&&f.points&&(A==="align"||A==="stable")&&(ne=!1);var de=l;return o.Children.count(l)>1&&(de=o.createElement("div",{className:"".concat(n,"-content")},l)),o.createElement(Zt,F({visible:r,ref:S,leavedClassName:"".concat(n,"-hidden")},Q,{onAppearPrepare:J,onEnterPrepare:J,removeOnLeave:u,forceRender:d}),function(X,ae){var te=X.className,oe=X.style,ce=Y(n,a,k,te);return o.createElement(_d,{target:z(),key:"popup",ref:w,monitorWindowResize:!0,disabled:ne,align:f,onAlign:G},o.createElement("div",{ref:ae,className:ce,onMouseEnter:h,onMouseLeave:y,onMouseDownCapture:C,onTouchStartCapture:b,onClick:x,style:L(L({},oe),Z)},de))})});$d.displayName="PopupInner";var Fd=o.forwardRef(function(e,t){var r=e.prefixCls,n=e.visible,a=e.zIndex,i=e.children,l=e.mobile;l=l===void 0?{}:l;var c=l.popupClassName,s=l.popupStyle,u=l.popupMotion,d=u===void 0?{}:u,f=l.popupRender,v=e.onClick,m=o.useRef();o.useImperativeHandle(t,function(){return{forceAlign:function(){},getElement:function(){return m.current}}});var p=L({zIndex:a},s),g=i;return o.Children.count(i)>1&&(g=o.createElement("div",{className:"".concat(r,"-content")},i)),f&&(g=f(g)),o.createElement(Zt,F({visible:n,ref:m,removeOnLeave:!0},d),function(h,y){var C=h.className,b=h.style,x=Y(r,c,C);return o.createElement("div",{ref:y,className:x,onClick:v,style:L(L({},b),p)},g)})});Fd.displayName="MobilePopupInner";var ZC=["visible","mobile"],Ad=o.forwardRef(function(e,t){var r=e.visible,n=e.mobile,a=Fe(e,ZC),i=o.useState(r),l=W(i,2),c=l[0],s=l[1],u=o.useState(!1),d=W(u,2),f=d[0],v=d[1],m=L(L({},a),{},{visible:c});o.useEffect(function(){s(r),r&&n&&v(qi())},[r,n]);var p=f?o.createElement(Fd,F({},m,{mobile:n,ref:t})):o.createElement($d,F({},m,{ref:t}));return o.createElement("div",null,o.createElement(yC,m),p)});Ad.displayName="Popup";var Ld=o.createContext(null);function ul(){}function eb(){return""}function tb(e){return e?e.ownerDocument:window.document}var nb=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur","onContextMenu"];function rb(e){var t=function(r){_t(a,r);var n=Dt(a);function a(i){var l;Pt(this,a),l=n.call(this,i),T(We(l),"popupRef",o.createRef()),T(We(l),"triggerRef",o.createRef()),T(We(l),"portalContainer",void 0),T(We(l),"attachId",void 0),T(We(l),"clickOutsideHandler",void 0),T(We(l),"touchOutsideHandler",void 0),T(We(l),"contextMenuOutsideHandler1",void 0),T(We(l),"contextMenuOutsideHandler2",void 0),T(We(l),"mouseDownTimeout",void 0),T(We(l),"focusTime",void 0),T(We(l),"preClickTime",void 0),T(We(l),"preTouchTime",void 0),T(We(l),"delayTimer",void 0),T(We(l),"hasPopupMouseDown",void 0),T(We(l),"onMouseEnter",function(s){var u=l.props.mouseEnterDelay;l.fireEvents("onMouseEnter",s),l.delaySetPopupVisible(!0,u,u?null:s)}),T(We(l),"onMouseMove",function(s){l.fireEvents("onMouseMove",s),l.setPoint(s)}),T(We(l),"onMouseLeave",function(s){l.fireEvents("onMouseLeave",s),l.delaySetPopupVisible(!1,l.props.mouseLeaveDelay)}),T(We(l),"onPopupMouseEnter",function(){l.clearDelayTimer()}),T(We(l),"onPopupMouseLeave",function(s){var u;s.relatedTarget&&!s.relatedTarget.setTimeout&&br((u=l.popupRef.current)===null||u===void 0?void 0:u.getElement(),s.relatedTarget)||l.delaySetPopupVisible(!1,l.props.mouseLeaveDelay)}),T(We(l),"onFocus",function(s){l.fireEvents("onFocus",s),l.clearDelayTimer(),l.isFocusToShow()&&(l.focusTime=Date.now(),l.delaySetPopupVisible(!0,l.props.focusDelay))}),T(We(l),"onMouseDown",function(s){l.fireEvents("onMouseDown",s),l.preClickTime=Date.now()}),T(We(l),"onTouchStart",function(s){l.fireEvents("onTouchStart",s),l.preTouchTime=Date.now()}),T(We(l),"onBlur",function(s){l.fireEvents("onBlur",s),l.clearDelayTimer(),l.isBlurToHide()&&l.delaySetPopupVisible(!1,l.props.blurDelay)}),T(We(l),"onContextMenu",function(s){s.preventDefault(),l.fireEvents("onContextMenu",s),l.setPopupVisible(!0,s)}),T(We(l),"onContextMenuClose",function(){l.isContextMenuToShow()&&l.close()}),T(We(l),"onClick",function(s){if(l.fireEvents("onClick",s),l.focusTime){var u;if(l.preClickTime&&l.preTouchTime?u=Math.min(l.preClickTime,l.preTouchTime):l.preClickTime?u=l.preClickTime:l.preTouchTime&&(u=l.preTouchTime),Math.abs(u-l.focusTime)<20)return;l.focusTime=0}l.preClickTime=0,l.preTouchTime=0,l.isClickToShow()&&(l.isClickToHide()||l.isBlurToHide())&&s&&s.preventDefault&&s.preventDefault();var d=!l.state.popupVisible;(l.isClickToHide()&&!d||d&&l.isClickToShow())&&l.setPopupVisible(!l.state.popupVisible,s)}),T(We(l),"onPopupMouseDown",function(){if(l.hasPopupMouseDown=!0,clearTimeout(l.mouseDownTimeout),l.mouseDownTimeout=window.setTimeout(function(){l.hasPopupMouseDown=!1},0),l.context){var s;(s=l.context).onPopupMouseDown.apply(s,arguments)}}),T(We(l),"onDocumentClick",function(s){if(!(l.props.mask&&!l.props.maskClosable)){var u=s.target,d=l.getRootDomNode(),f=l.getPopupDomNode();(!br(d,u)||l.isContextMenuOnly())&&!br(f,u)&&!l.hasPopupMouseDown&&l.close()}}),T(We(l),"getRootDomNode",function(){var s=l.props.getTriggerDOMNode;if(s)return s(l.triggerRef.current);try{var u=ta(l.triggerRef.current);if(u)return u}catch(d){}return Vn.findDOMNode(We(l))}),T(We(l),"getPopupClassNameFromAlign",function(s){var u=[],d=l.props,f=d.popupPlacement,v=d.builtinPlacements,m=d.prefixCls,p=d.alignPoint,g=d.getPopupClassNameFromAlign;return f&&v&&u.push(gC(v,m,s,p)),g&&u.push(g(s)),u.join(" ")}),T(We(l),"getComponent",function(){var s=l.props,u=s.prefixCls,d=s.destroyPopupOnHide,f=s.popupClassName,v=s.onPopupAlign,m=s.popupMotion,p=s.popupAnimation,g=s.popupTransitionName,h=s.popupStyle,y=s.mask,C=s.maskAnimation,b=s.maskTransitionName,x=s.maskMotion,w=s.zIndex,S=s.popup,O=s.stretch,E=s.alignPoint,k=s.mobile,I=s.forceRender,M=s.onPopupClick,R=l.state,N=R.popupVisible,P=R.point,_=l.getPopupAlign(),$={};return l.isMouseEnterToShow()&&($.onMouseEnter=l.onPopupMouseEnter),l.isMouseLeaveToHide()&&($.onMouseLeave=l.onPopupMouseLeave),$.onMouseDown=l.onPopupMouseDown,$.onTouchStart=l.onPopupMouseDown,o.createElement(Ad,F({prefixCls:u,destroyPopupOnHide:d,visible:N,point:E&&P,className:f,align:_,onAlign:v,animation:p,getClassNameFromAlign:l.getPopupClassNameFromAlign},$,{stretch:O,getRootDomNode:l.getRootDomNode,style:h,mask:y,zIndex:w,transitionName:g,maskAnimation:C,maskTransitionName:b,maskMotion:x,ref:l.popupRef,motion:m,mobile:k,forceRender:I,onClick:M}),typeof S=="function"?S():S)}),T(We(l),"attachParent",function(s){nt.cancel(l.attachId);var u=l.props,d=u.getPopupContainer,f=u.getDocument,v=l.getRootDomNode(),m;d?(v||d.length===0)&&(m=d(v)):m=f(l.getRootDomNode()).body,m?m.appendChild(s):l.attachId=nt(function(){l.attachParent(s)})}),T(We(l),"getContainer",function(){if(!l.portalContainer){var s=l.props.getDocument,u=s(l.getRootDomNode()).createElement("div");u.style.position="absolute",u.style.top="0",u.style.left="0",u.style.width="100%",l.portalContainer=u}return l.attachParent(l.portalContainer),l.portalContainer}),T(We(l),"setPoint",function(s){var u=l.props.alignPoint;!u||!s||l.setState({point:{pageX:s.pageX,pageY:s.pageY}})}),T(We(l),"handlePortalUpdate",function(){l.state.prevPopupVisible!==l.state.popupVisible&&l.props.afterPopupVisibleChange(l.state.popupVisible)}),T(We(l),"triggerContextValue",{onPopupMouseDown:l.onPopupMouseDown});var c;return"popupVisible"in i?c=!!i.popupVisible:c=!!i.defaultPopupVisible,l.state={prevPopupVisible:c,popupVisible:c},nb.forEach(function(s){l["fire".concat(s)]=function(u){l.fireEvents(s,u)}}),l}return Rt(a,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentDidUpdate",value:function(){var l=this.props,c=this.state;if(c.popupVisible){var s;!this.clickOutsideHandler&&(this.isClickToHide()||this.isContextMenuToShow())&&(s=l.getDocument(this.getRootDomNode()),this.clickOutsideHandler=On(s,"mousedown",this.onDocumentClick)),this.touchOutsideHandler||(s=s||l.getDocument(this.getRootDomNode()),this.touchOutsideHandler=On(s,"touchstart",this.onDocumentClick)),!this.contextMenuOutsideHandler1&&this.isContextMenuToShow()&&(s=s||l.getDocument(this.getRootDomNode()),this.contextMenuOutsideHandler1=On(s,"scroll",this.onContextMenuClose)),!this.contextMenuOutsideHandler2&&this.isContextMenuToShow()&&(this.contextMenuOutsideHandler2=On(window,"blur",this.onContextMenuClose));return}this.clearOutsideHandler()}},{key:"componentWillUnmount",value:function(){this.clearDelayTimer(),this.clearOutsideHandler(),clearTimeout(this.mouseDownTimeout),nt.cancel(this.attachId)}},{key:"getPopupDomNode",value:function(){var l;return((l=this.popupRef.current)===null||l===void 0?void 0:l.getElement())||null}},{key:"getPopupAlign",value:function(){var l=this.props,c=l.popupPlacement,s=l.popupAlign,u=l.builtinPlacements;return c&&u?hC(u,c,s):s}},{key:"setPopupVisible",value:function(l,c){var s=this.props.alignPoint,u=this.state.popupVisible;this.clearDelayTimer(),u!==l&&("popupVisible"in this.props||this.setState({popupVisible:l,prevPopupVisible:u}),this.props.onPopupVisibleChange(l)),s&&c&&l&&this.setPoint(c)}},{key:"delaySetPopupVisible",value:function(l,c,s){var u=this,d=c*1e3;if(this.clearDelayTimer(),d){var f=s?{pageX:s.pageX,pageY:s.pageY}:null;this.delayTimer=window.setTimeout(function(){u.setPopupVisible(l,f),u.clearDelayTimer()},d)}else this.setPopupVisible(l,s)}},{key:"clearDelayTimer",value:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)}},{key:"clearOutsideHandler",value:function(){this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.clickOutsideHandler=null),this.contextMenuOutsideHandler1&&(this.contextMenuOutsideHandler1.remove(),this.contextMenuOutsideHandler1=null),this.contextMenuOutsideHandler2&&(this.contextMenuOutsideHandler2.remove(),this.contextMenuOutsideHandler2=null),this.touchOutsideHandler&&(this.touchOutsideHandler.remove(),this.touchOutsideHandler=null)}},{key:"createTwoChains",value:function(l){var c=this.props.children.props,s=this.props;return c[l]&&s[l]?this["fire".concat(l)]:c[l]||s[l]}},{key:"isClickToShow",value:function(){var l=this.props,c=l.action,s=l.showAction;return c.indexOf("click")!==-1||s.indexOf("click")!==-1}},{key:"isContextMenuOnly",value:function(){var l=this.props.action;return l==="contextMenu"||l.length===1&&l[0]==="contextMenu"}},{key:"isContextMenuToShow",value:function(){var l=this.props,c=l.action,s=l.showAction;return c.indexOf("contextMenu")!==-1||s.indexOf("contextMenu")!==-1}},{key:"isClickToHide",value:function(){var l=this.props,c=l.action,s=l.hideAction;return c.indexOf("click")!==-1||s.indexOf("click")!==-1}},{key:"isMouseEnterToShow",value:function(){var l=this.props,c=l.action,s=l.showAction;return c.indexOf("hover")!==-1||s.indexOf("mouseEnter")!==-1}},{key:"isMouseLeaveToHide",value:function(){var l=this.props,c=l.action,s=l.hideAction;return c.indexOf("hover")!==-1||s.indexOf("mouseLeave")!==-1}},{key:"isFocusToShow",value:function(){var l=this.props,c=l.action,s=l.showAction;return c.indexOf("focus")!==-1||s.indexOf("focus")!==-1}},{key:"isBlurToHide",value:function(){var l=this.props,c=l.action,s=l.hideAction;return c.indexOf("focus")!==-1||s.indexOf("blur")!==-1}},{key:"forcePopupAlign",value:function(){if(this.state.popupVisible){var l;(l=this.popupRef.current)===null||l===void 0||l.forceAlign()}}},{key:"fireEvents",value:function(l,c){var s=this.props.children.props[l];s&&s(c);var u=this.props[l];u&&u(c)}},{key:"close",value:function(){this.setPopupVisible(!1)}},{key:"render",value:function(){var l=this.state.popupVisible,c=this.props,s=c.children,u=c.forceRender,d=c.alignPoint,f=c.className,v=c.autoDestroy,m=o.Children.only(s),p={key:"trigger"};this.isContextMenuToShow()?p.onContextMenu=this.onContextMenu:p.onContextMenu=this.createTwoChains("onContextMenu"),this.isClickToHide()||this.isClickToShow()?(p.onClick=this.onClick,p.onMouseDown=this.onMouseDown,p.onTouchStart=this.onTouchStart):(p.onClick=this.createTwoChains("onClick"),p.onMouseDown=this.createTwoChains("onMouseDown"),p.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?(p.onMouseEnter=this.onMouseEnter,d&&(p.onMouseMove=this.onMouseMove)):p.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?p.onMouseLeave=this.onMouseLeave:p.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(p.onFocus=this.onFocus,p.onBlur=this.onBlur):(p.onFocus=this.createTwoChains("onFocus"),p.onBlur=this.createTwoChains("onBlur"));var g=Y(m&&m.props&&m.props.className,f);g&&(p.className=g);var h=L({},p);nr(m)&&(h.ref=on(this.triggerRef,m.ref));var y=o.cloneElement(m,h),C;return(l||this.popupRef.current||u)&&(C=o.createElement(e,{key:"portal",getContainer:this.getContainer,didUpdate:this.handlePortalUpdate},this.getComponent())),!l&&v&&(C=null),o.createElement(Ld.Provider,{value:this.triggerContextValue},y,C)}}],[{key:"getDerivedStateFromProps",value:function(l,c){var s=l.popupVisible,u={};return s!==void 0&&c.popupVisible!==s&&(u.popupVisible=s,u.prevPopupVisible=c.popupVisible),u}}]),a}(o.Component);return T(t,"contextType",Ld),T(t,"defaultProps",{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:eb,getDocument:tb,onPopupVisibleChange:ul,afterPopupVisibleChange:ul,onPopupAlign:ul,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0,action:[],showAction:[],hideAction:[],autoDestroy:!1}),t}var co=rb(mC),ab=["prefixCls","disabled","visible","children","popupElement","containerWidth","animation","transitionName","dropdownStyle","dropdownClassName","direction","placement","dropdownMatchSelectWidth","dropdownRender","dropdownAlign","getPopupContainer","empty","getTriggerDOMNode","onPopupVisibleChange","onPopupMouseEnter"],ob=function(t){var r=t===!0?0:1;return{bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:r,adjustY:1}},bottomRight:{points:["tr","br"],offset:[0,4],overflow:{adjustX:r,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:r,adjustY:1}},topRight:{points:["br","tr"],offset:[0,-4],overflow:{adjustX:r,adjustY:1}}}},ib=function(t,r){var n=t.prefixCls,a=t.disabled,i=t.visible,l=t.children,c=t.popupElement,s=t.containerWidth,u=t.animation,d=t.transitionName,f=t.dropdownStyle,v=t.dropdownClassName,m=t.direction,p=m===void 0?"ltr":m,g=t.placement,h=t.dropdownMatchSelectWidth,y=t.dropdownRender,C=t.dropdownAlign,b=t.getPopupContainer,x=t.empty,w=t.getTriggerDOMNode,S=t.onPopupVisibleChange,O=t.onPopupMouseEnter,E=Fe(t,ab),k="".concat(n,"-dropdown"),I=c;y&&(I=y(c));var M=o.useMemo(function(){return ob(h)},[h]),R=u?"".concat(k,"-").concat(u):d,N=o.useRef(null);o.useImperativeHandle(r,function(){return{getPopupElement:function(){return N.current}}});var P=L({minWidth:s},f);return typeof h=="number"?P.width=h:h&&(P.width=s),o.createElement(co,F({},E,{showAction:S?["click"]:[],hideAction:S?["click"]:[],popupPlacement:g||(p==="rtl"?"bottomRight":"bottomLeft"),builtinPlacements:M,prefixCls:k,popupTransitionName:R,popup:o.createElement("div",{ref:N,onMouseEnter:O},I),popupAlign:C,popupVisible:i,getPopupContainer:b,popupClassName:Y(v,T({},"".concat(k,"-empty"),x)),popupStyle:P,getTriggerDOMNode:w,onPopupVisibleChange:S}),l)},Kd=o.forwardRef(ib);Kd.displayName="SelectTrigger";function Vd(e,t){var r=e.key,n;return"value"in e&&(n=e.value),r!=null?r:n!==void 0?n:"rc-index-key-".concat(t)}function zd(e,t){var r=e||{},n=r.label,a=r.value,i=r.options;return{label:n||(t?"children":"label"),value:a||"value",options:i||"options"}}function lb(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=t.fieldNames,n=t.childrenAsData,a=[],i=zd(r,!1),l=i.label,c=i.value,s=i.options;function u(d,f){d.forEach(function(v){var m=v[l];if(f||!(s in v)){var p=v[c];a.push({key:Vd(v,a.length),groupOption:f,data:v,label:m,value:p})}else{var g=m;g===void 0&&n&&(g=v.label),a.push({key:Vd(v,a.length),group:!0,data:v,label:g}),u(v[s],!0)}})}return u(e,!1),a}function dl(e){var t=L({},e);return"props"in t||Object.defineProperty(t,"props",{get:function(){return Ot(!1,"Return type is option instead of Option instance. Please read value directly instead of reading from `props`."),t}}),t}function cb(e,t){if(!t||!t.length)return null;var r=!1;function n(i,l){var c=Ci(l),s=c[0],u=c.slice(1);if(!s)return[i];var d=i.split(s);return r=r||d.length>1,d.reduce(function(f,v){return[].concat(ue(f),ue(n(v,u)))},[]).filter(function(f){return f})}var a=n(e,t);return r?a:null}var sb=["id","prefixCls","className","showSearch","tagRender","direction","omitDomProps","displayValues","onDisplayValuesChange","emptyOptions","notFoundContent","onClear","mode","disabled","loading","getInputElement","getRawInputElement","open","defaultOpen","onDropdownVisibleChange","activeValue","onActiveValueChange","activeDescendantId","searchValue","autoClearSearchValue","onSearch","onSearchSplit","tokenSeparators","allowClear","showArrow","inputIcon","clearIcon","OptionList","animation","transitionName","dropdownStyle","dropdownClassName","dropdownMatchSelectWidth","dropdownRender","dropdownAlign","placement","getPopupContainer","showAction","onFocus","onBlur","onKeyUp","onKeyDown","onMouseDown"],ub=["value","onChange","removeIcon","placeholder","autoFocus","maxTagCount","maxTagTextLength","maxTagPlaceholder","choiceTransitionName","onInputKeyDown","onPopupScroll","tabIndex"];function fl(e){return e==="tags"||e==="multiple"}var jd=o.forwardRef(function(e,t){var r,n,a=e.id,i=e.prefixCls,l=e.className,c=e.showSearch,s=e.tagRender,u=e.direction,d=e.omitDomProps,f=e.displayValues,v=e.onDisplayValuesChange,m=e.emptyOptions,p=e.notFoundContent,g=p===void 0?"Not Found":p,h=e.onClear,y=e.mode,C=e.disabled,b=e.loading,x=e.getInputElement,w=e.getRawInputElement,S=e.open,O=e.defaultOpen,E=e.onDropdownVisibleChange,k=e.activeValue,I=e.onActiveValueChange,M=e.activeDescendantId,R=e.searchValue,N=e.autoClearSearchValue,P=e.onSearch,_=e.onSearchSplit,$=e.tokenSeparators,D=e.allowClear,A=e.showArrow,V=e.inputIcon,U=e.clearIcon,q=e.OptionList,K=e.animation,H=e.transitionName,j=e.dropdownStyle,z=e.dropdownClassName,B=e.dropdownMatchSelectWidth,G=e.dropdownRender,Q=e.dropdownAlign,J=e.placement,Z=e.getPopupContainer,ne=e.showAction,de=ne===void 0?[]:ne,X=e.onFocus,ae=e.onBlur,te=e.onKeyUp,oe=e.onKeyDown,ce=e.onMouseDown,pe=Fe(e,sb),me=fl(y),ve=(c!==void 0?c:me)||y==="combobox",se=L({},pe);ub.forEach(function(Be){delete se[Be]}),d==null||d.forEach(function(Be){delete se[Be]});var ee=o.useState(!1),re=W(ee,2),ye=re[0],Ne=re[1];o.useEffect(function(){Ne(qi())},[]);var Ce=o.useRef(null),_e=o.useRef(null),Ee=o.useRef(null),ge=o.useRef(null),xe=o.useRef(null),De=zy(),we=W(De,3),Oe=we[0],Le=we[1],et=we[2];o.useImperativeHandle(t,function(){var Be,Ue;return{focus:(Be=ge.current)===null||Be===void 0?void 0:Be.focus,blur:(Ue=ge.current)===null||Ue===void 0?void 0:Ue.blur,scrollTo:function(Lt){var St;return(St=xe.current)===null||St===void 0?void 0:St.scrollTo(Lt)}}});var Ke=o.useMemo(function(){var Be;if(y!=="combobox")return R;var Ue=(Be=f[0])===null||Be===void 0?void 0:Be.value;return typeof Ue=="string"||typeof Ue=="number"?String(Ue):""},[R,y,f]),ut=y==="combobox"&&typeof x=="function"&&x()||null,Ye=typeof w=="function"&&w(),ot=ui(_e,Ye==null||(r=Ye.props)===null||r===void 0?void 0:r.ref),Ae=Ft(void 0,{defaultValue:O,value:S}),$e=W(Ae,2),rt=$e[0],tt=$e[1],Ze=rt,Me=!g&&m;(C||Me&&Ze&&y==="combobox")&&(Ze=!1);var Se=Me?!1:Ze,le=o.useCallback(function(Be){var Ue=Be!==void 0?Be:!Ze;C||(tt(Ue),Ze!==Ue&&(E==null||E(Ue)))},[C,Ze,tt,E]),fe=o.useMemo(function(){return($||[]).some(function(Be){return[` +`,`\r +`].includes(Be)})},[$]),he=function(Ue,Nt,Lt){var St=!0,Kt=Ue;I==null||I(null);var Bt=Lt?null:cb(Ue,$);return y!=="combobox"&&Bt&&(Kt="",_==null||_(Bt),le(!1),St=!1),P&&Ke!==Kt&&P(Kt,{source:Nt?"typing":"effect"}),St},be=function(Ue){!Ue||!Ue.trim()||P(Ue,{source:"submit"})};o.useEffect(function(){!Ze&&!me&&y!=="combobox"&&he("",!1,!1)},[Ze]),o.useEffect(function(){rt&&C&&tt(!1),C&&Le(!1)},[C]);var Ie=Qu(),Qe=W(Ie,2),vt=Qe[0],Et=Qe[1],at=function(Ue){var Nt=vt(),Lt=Ue.which;if(Lt===ie.ENTER&&(y!=="combobox"&&Ue.preventDefault(),Ze||le(!0)),Et(!!Ke),Lt===ie.BACKSPACE&&!Nt&&me&&!Ke&&f.length){for(var St=ue(f),Kt=null,Bt=St.length-1;Bt>=0;Bt-=1){var mt=St[Bt];if(!mt.disabled){St.splice(Bt,1),Kt=mt;break}}Kt&&v(St,{type:"remove",values:[Kt]})}for(var it=arguments.length,ft=new Array(it>1?it-1:0),bt=1;bt1?Nt-1:0),St=1;St1?Bt-1:0),it=1;it1&&arguments[1]!==void 0?arguments[1]:!1;return an(e).map(function(r,n){if(!o.isValidElement(r)||!r.type)return null;var a=r,i=a.type.isSelectOptGroup,l=a.key,c=a.props,s=c.children,u=Fe(c,hb);return t||!i?gb(r):L(L({key:"__RC_SELECT_GRP__".concat(l===null?n:l,"__"),label:l},u),{},{options:Wd(s)})}).filter(function(r){return r})}function yb(e,t,r,n,a){return o.useMemo(function(){var i=e,l=!e;l&&(i=Wd(t));var c=new Map,s=new Map,u=function(v,m,p){p&&typeof p=="string"&&v.set(m[p],m)};function d(f){for(var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,m=0;ms},n}return Rt(r,[{key:"componentDidMount",value:function(){this.scrollbarRef.current.addEventListener("touchstart",this.onScrollbarTouchStart),this.thumbRef.current.addEventListener("touchstart",this.onMouseDown)}},{key:"componentDidUpdate",value:function(a){a.scrollTop!==this.props.scrollTop&&this.delayHidden()}},{key:"componentWillUnmount",value:function(){this.removeEvents(),clearTimeout(this.visibleTimeout)}},{key:"render",value:function(){var a=this.state,i=a.dragging,l=a.visible,c=this.props.prefixCls,s=this.getSpinHeight(),u=this.getTop(),d=this.showScroll(),f=d&&l;return o.createElement("div",{ref:this.scrollbarRef,className:Y("".concat(c,"-scrollbar"),T({},"".concat(c,"-scrollbar-show"),d)),style:{width:8,top:0,bottom:0,right:0,position:"absolute",display:f?null:"none"},onMouseDown:this.onContainerMouseDown,onMouseMove:this.delayHidden},o.createElement("div",{ref:this.thumbRef,className:Y("".concat(c,"-scrollbar-thumb"),T({},"".concat(c,"-scrollbar-thumb-moving"),i)),style:{width:"100%",height:s,top:u,left:0,position:"absolute",background:"rgba(0, 0, 0, 0.5)",borderRadius:99,cursor:"pointer",userSelect:"none"},onMouseDown:this.onMouseDown}))}}]),r}(o.Component);function xb(e){var t=e.children,r=e.setRef,n=o.useCallback(function(a){r(a)},[]);return o.cloneElement(t,{ref:n})}function Sb(e,t,r,n,a,i){var l=i.getKey;return e.slice(t,r+1).map(function(c,s){var u=t+s,d=a(c,u,{}),f=l(c);return o.createElement(xb,{key:f,setRef:function(m){return n(c,m)}},d)})}var Eb=function(){function e(){Pt(this,e),this.maps=void 0,this.maps=Object.create(null)}return Rt(e,[{key:"set",value:function(r,n){this.maps[r]=n}},{key:"get",value:function(r){return this.maps[r]}}]),e}();function wb(e,t,r){var n=o.useState(0),a=W(n,2),i=a[0],l=a[1],c=o.useRef(new Map),s=o.useRef(new Eb),u=o.useRef();function d(){nt.cancel(u.current)}function f(){d(),u.current=nt(function(){c.current.forEach(function(m,p){if(m&&m.offsetParent){var g=ta(m),h=g.offsetHeight;s.current.get(p)!==h&&s.current.set(p,g.offsetHeight)}}),l(function(m){return m+1})})}function v(m,p){var g=e(m),h=c.current.get(g);p?(c.current.set(g,p),f()):c.current.delete(g),!h!=!p&&(p?t==null||t(m):r==null||r(m))}return o.useEffect(function(){return d},[]),[v,f,s.current,i]}function Nb(e,t,r,n,a,i,l,c){var s=o.useRef();return function(u){if(u==null){c();return}if(nt.cancel(s.current),typeof u=="number")l(u);else if(u&&ke(u)==="object"){var d,f=u.align;"index"in u?d=u.index:d=t.findIndex(function(g){return a(g)===u.key});var v=u.offset,m=v===void 0?0:v,p=function g(h,y){if(!(h<0||!e.current)){var C=e.current.clientHeight,b=!1,x=y;if(C){for(var w=y||f,S=0,O=0,E=0,k=Math.min(t.length,d),I=0;I<=k;I+=1){var M=a(t[I]);O=S;var R=r.get(M);E=O+(R===void 0?n:R),S=E,I===d&&R===void 0&&(b=!0)}var N=null;switch(w){case"top":N=O-m;break;case"bottom":N=E-C+m;break;default:{var P=e.current.scrollTop,_=P+C;O_&&(x="bottom")}}N!==null&&N!==e.current.scrollTop&&l(N)}s.current=nt(function(){b&&i(),g(h-1,x)})}};p(3)}}}function Pb(e,t,r){var n=e.length,a=t.length,i,l;if(n===0&&a===0)return null;n1&&arguments[1]!==void 0?arguments[1]:!1,s=l<0&&i.current.top||l>0&&i.current.bottom;return c&&s?(clearTimeout(n.current),r.current=!1):(!s||r.current)&&a(),!r.current&&s}};function Ob(e,t,r,n){var a=o.useRef(0),i=o.useRef(null),l=o.useRef(null),c=o.useRef(!1),s=Yd(t,r);function u(f){if(!!e){nt.cancel(i.current);var v=f.deltaY;a.current+=v,l.current=v,!s(v)&&(kb||f.preventDefault(),i.current=nt(function(){var m=c.current?10:1;n(a.current*m),a.current=0}))}}function d(f){!e||(c.current=f.detail===l.current)}return[u,d]}var Ib=14/15;function Mb(e,t,r){var n=o.useRef(!1),a=o.useRef(0),i=o.useRef(null),l=o.useRef(null),c,s=function(v){if(n.current){var m=Math.ceil(v.touches[0].pageY),p=a.current-m;a.current=m,r(p)&&v.preventDefault(),clearInterval(l.current),l.current=setInterval(function(){p*=Ib,(!r(p,!0)||Math.abs(p)<=.1)&&clearInterval(l.current)},16)}},u=function(){n.current=!1,c()},d=function(v){c(),v.touches.length===1&&!n.current&&(n.current=!0,a.current=Math.ceil(v.touches[0].pageY),i.current=v.target,i.current.addEventListener("touchmove",s),i.current.addEventListener("touchend",u))};c=function(){i.current&&(i.current.removeEventListener("touchmove",s),i.current.removeEventListener("touchend",u))},jt(function(){return e&&t.current.addEventListener("touchstart",d),function(){var f;(f=t.current)===null||f===void 0||f.removeEventListener("touchstart",d),c(),clearInterval(l.current)}},[e])}var Tb=["prefixCls","className","height","itemHeight","fullHeight","style","data","children","itemKey","virtual","component","onScroll","onVisibleChange"],_b=[],Db={overflowY:"auto",overflowAnchor:"none"};function $b(e,t){var r=e.prefixCls,n=r===void 0?"rc-virtual-list":r,a=e.className,i=e.height,l=e.itemHeight,c=e.fullHeight,s=c===void 0?!0:c,u=e.style,d=e.data,f=e.children,v=e.itemKey,m=e.virtual,p=e.component,g=p===void 0?"div":p,h=e.onScroll,y=e.onVisibleChange,C=Fe(e,Tb),b=!!(m!==!1&&i&&l),x=b&&d&&l*d.length>i,w=o.useState(0),S=W(w,2),O=S[0],E=S[1],k=o.useState(!1),I=W(k,2),M=I[0],R=I[1],N=Y(n,a),P=d||_b,_=o.useRef(),$=o.useRef(),D=o.useRef(),A=o.useCallback(function(we){return typeof v=="function"?v(we):we==null?void 0:we[v]},[v]),V={getKey:A};function U(we){E(function(Oe){var Le;typeof we=="function"?Le=we(Oe):Le=we;var et=me(Le);return _.current.scrollTop=et,et})}var q=o.useRef({start:0,end:P.length}),K=o.useRef(),H=Rb(P,A),j=W(H,1),z=j[0];K.current=z;var B=wb(A,null,null),G=W(B,4),Q=G[0],J=G[1],Z=G[2],ne=G[3],de=o.useMemo(function(){if(!b)return{scrollHeight:void 0,start:0,end:P.length-1,offset:void 0};if(!x){var we;return{scrollHeight:((we=$.current)===null||we===void 0?void 0:we.offsetHeight)||0,start:0,end:P.length-1,offset:void 0}}for(var Oe=0,Le,et,Ke,ut=P.length,Ye=0;Ye=O&&Le===void 0&&(Le=Ye,et=Oe),rt>O+i&&Ke===void 0&&(Ke=Ye),Oe=rt}return Le===void 0&&(Le=0,et=0,Ke=Math.ceil(i/l)),Ke===void 0&&(Ke=P.length-1),Ke=Math.min(Ke+1,P.length),{scrollHeight:Oe,start:Le,end:Ke,offset:et}},[x,b,O,P,ne,i]),X=de.scrollHeight,ae=de.start,te=de.end,oe=de.offset;q.current.start=ae,q.current.end=te;var ce=X-i,pe=o.useRef(ce);pe.current=ce;function me(we){var Oe=we;return Number.isNaN(pe.current)||(Oe=Math.min(Oe,pe.current)),Oe=Math.max(Oe,0),Oe}var ve=O<=0,se=O>=ce,ee=Yd(ve,se);function re(we){var Oe=we;U(Oe)}function ye(we){var Oe=we.currentTarget.scrollTop;Oe!==O&&U(Oe),h==null||h(we)}var Ne=Ob(b,ve,se,function(we){U(function(Oe){var Le=Oe+we;return Le})}),Ce=W(Ne,2),_e=Ce[0],Ee=Ce[1];Mb(b,_,function(we,Oe){return ee(we,Oe)?!1:(_e({preventDefault:function(){},deltaY:we}),!0)}),jt(function(){function we(Oe){b&&Oe.preventDefault()}return _.current.addEventListener("wheel",_e),_.current.addEventListener("DOMMouseScroll",Ee),_.current.addEventListener("MozMousePixelScroll",we),function(){_.current&&(_.current.removeEventListener("wheel",_e),_.current.removeEventListener("DOMMouseScroll",Ee),_.current.removeEventListener("MozMousePixelScroll",we))}},[b]);var ge=Nb(_,P,Z,l,A,J,U,function(){var we;(we=D.current)===null||we===void 0||we.delayHidden()});o.useImperativeHandle(t,function(){return{scrollTo:ge}}),jt(function(){if(y){var we=P.slice(ae,te+1);y(we,P)}},[ae,te,P]);var xe=Sb(P,ae,te,Q,f,V),De=null;return i&&(De=L(T({},s?"height":"maxHeight",i),Db),b&&(De.overflowY="hidden",M&&(De.pointerEvents="none"))),o.createElement("div",F({style:L(L({},u),{},{position:"relative"}),className:N},C),o.createElement(g,{className:"".concat(n,"-holder"),style:De,ref:_,onScroll:ye},o.createElement(qd,{prefixCls:n,height:X,offset:oe,onInnerResize:J,ref:$},xe)),b&&o.createElement(bb,{ref:D,prefixCls:n,scrollTop:O,height:i,scrollHeight:X,count:P.length,onScroll:re,onStartMove:function(){R(!0)},onStopMove:function(){R(!1)}}))}var hl=o.forwardRef($b);hl.displayName="List";function Fb(){return/(mac\sos|macintosh)/i.test(navigator.appVersion)}var Xd=o.createContext(null),Ab=["disabled","title","children","style","className"];function Qd(e){return typeof e=="string"||typeof e=="number"}var Lb=function(t,r){var n=Za(),a=n.prefixCls,i=n.id,l=n.open,c=n.multiple,s=n.mode,u=n.searchValue,d=n.toggleOpen,f=n.notFoundContent,v=n.onPopupScroll,m=o.useContext(Xd),p=m.flattenOptions,g=m.onActiveValue,h=m.defaultActiveFirstOption,y=m.onSelect,C=m.menuItemSelectedIcon,b=m.rawValues,x=m.fieldNames,w=m.virtual,S=m.listHeight,O=m.listItemHeight,E="".concat(a,"-item"),k=La(function(){return p},[l,p],function(j,z){return z[0]&&j[1]!==z[1]}),I=o.useRef(null),M=function(z){z.preventDefault()},R=function(z){I.current&&I.current.scrollTo(typeof z=="number"?{index:z}:z)},N=function(z){for(var B=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1,G=k.length,Q=0;Q1&&arguments[1]!==void 0?arguments[1]:!1;D(z);var G={source:B?"keyboard":"mouse"},Q=k[z];if(!Q){g(null,-1,G);return}g(Q.value,z,G)};o.useEffect(function(){A(h!==!1?N(0):-1)},[k.length,u]);var V=o.useCallback(function(j){return b.has(j)&&s!=="combobox"},[s,ue(b).toString(),b.size]);o.useEffect(function(){var j=setTimeout(function(){if(!c&&l&&b.size===1){var B=Array.from(b)[0],G=k.findIndex(function(Q){var J=Q.data;return J.value===B});G!==-1&&(A(G),R(G))}});if(l){var z;(z=I.current)===null||z===void 0||z.scrollTo(void 0)}return function(){return clearTimeout(j)}},[l,u]);var U=function(z){z!==void 0&&y(z,{selected:!b.has(z)}),c||d(!1)};if(o.useImperativeHandle(r,function(){return{onKeyDown:function(z){var B=z.which,G=z.ctrlKey;switch(B){case ie.N:case ie.P:case ie.UP:case ie.DOWN:{var Q=0;if(B===ie.UP?Q=-1:B===ie.DOWN?Q=1:Fb()&&G&&(B===ie.N?Q=1:B===ie.P&&(Q=-1)),Q!==0){var J=N($+Q,Q);R(J),A(J,!0)}break}case ie.ENTER:{var Z=k[$];Z&&!Z.data.disabled?U(Z.value):U(void 0),l&&z.preventDefault();break}case ie.ESC:d(!1),l&&z.stopPropagation()}},onKeyUp:function(){},scrollTo:function(z){R(z)}}}),k.length===0)return o.createElement("div",{role:"listbox",id:"".concat(i,"_list"),className:"".concat(E,"-empty"),onMouseDown:M},f);var q=Object.keys(x).map(function(j){return x[j]}),K=function(z){return z.label},H=function(z){var B=k[z];if(!B)return null;var G=B.data||{},Q=G.value,J=B.group,Z=Bn(G,!0),ne=K(B);return B?o.createElement("div",F({"aria-label":typeof ne=="string"&&!J?ne:null},Z,{key:z,role:J?"presentation":"option",id:"".concat(i,"_list_").concat(z),"aria-selected":V(Q)}),Q):null};return o.createElement(o.Fragment,null,o.createElement("div",{role:"listbox",id:"".concat(i,"_list"),style:{height:0,width:0,overflow:"hidden"}},H($-1),H($),H($+1)),o.createElement(hl,{itemKey:"key",ref:I,data:k,height:S,itemHeight:O,fullHeight:!1,onMouseDown:M,onScroll:v,virtual:w},function(j,z){var B,G=j.group,Q=j.groupOption,J=j.data,Z=j.label,ne=j.value,de=J.key;if(G){var X,ae=(X=J.title)!==null&&X!==void 0?X:Qd(Z)?Z.toString():void 0;return o.createElement("div",{className:Y(E,"".concat(E,"-group")),title:ae},Z!==void 0?Z:de)}var te=J.disabled,oe=J.title,ce=J.children,pe=J.style,me=J.className,ve=Fe(J,Ab),se=zt(ve,q),ee=V(ne),re="".concat(E,"-option"),ye=Y(E,re,me,(B={},T(B,"".concat(re,"-grouped"),Q),T(B,"".concat(re,"-active"),$===z&&!te),T(B,"".concat(re,"-disabled"),te),T(B,"".concat(re,"-selected"),ee),B)),Ne=K(j),Ce=!C||typeof C=="function"||ee,_e=typeof Ne=="number"?Ne:Ne||ne,Ee=Qd(_e)?_e.toString():void 0;return oe!==void 0&&(Ee=oe),o.createElement("div",F({},Bn(se),{"aria-selected":ee,className:ye,title:Ee,onMouseMove:function(){$===z||te||A(z)},onClick:function(){te||U(ne)},style:pe}),o.createElement("div",{className:"".concat(re,"-content")},_e),o.isValidElement(C)||ee,Ce&&o.createElement(to,{className:"".concat(E,"-option-state"),customizeIcon:C,customizeIconProps:{isSelected:ee}},ee?"\u2713":null))}))},Jd=o.forwardRef(Lb);Jd.displayName="OptionList";var Kb=["id","mode","prefixCls","backfill","fieldNames","inputValue","searchValue","onSearch","autoClearSearchValue","onSelect","onDeselect","dropdownMatchSelectWidth","filterOption","filterSort","optionFilterProp","optionLabelProp","options","children","defaultActiveFirstOption","menuItemSelectedIcon","virtual","listHeight","listItemHeight","value","defaultValue","labelInValue","onChange"],Vb=["inputValue"];function zb(e){return!e||ke(e)!=="object"}var jb=o.forwardRef(function(e,t){var r=e.id,n=e.mode,a=e.prefixCls,i=a===void 0?"rc-select":a,l=e.backfill,c=e.fieldNames,s=e.inputValue,u=e.searchValue,d=e.onSearch,f=e.autoClearSearchValue,v=f===void 0?!0:f,m=e.onSelect,p=e.onDeselect,g=e.dropdownMatchSelectWidth,h=g===void 0?!0:g,y=e.filterOption,C=e.filterSort,b=e.optionFilterProp,x=e.optionLabelProp,w=e.options,S=e.children,O=e.defaultActiveFirstOption,E=e.menuItemSelectedIcon,k=e.virtual,I=e.listHeight,M=I===void 0?200:I,R=e.listItemHeight,N=R===void 0?20:R,P=e.value,_=e.defaultValue,$=e.labelInValue,D=e.onChange,A=Fe(e,Kb),V=Bd(r),U=fl(n),q=!!(!w&&S),K=o.useMemo(function(){return y===void 0&&n==="combobox"?!1:y},[y,n]),H=o.useMemo(function(){return zd(c,q)},[JSON.stringify(c),q]),j=Ft("",{value:u!==void 0?u:s,postState:function(fe){return fe||""}}),z=W(j,2),B=z[0],G=z[1],Q=yb(w,S,H,b,x),J=Q.valueOptions,Z=Q.labelOptions,ne=Q.options,de=o.useCallback(function(le){var fe=nd(le);return fe.map(function(he){var be,Ie,Qe,vt,Et;if(zb(he))be=he;else{var at;Qe=he.key,Ie=he.label,be=(at=he.value)!==null&&at!==void 0?at:Qe}var Te=J.get(be);if(Te){var Re;Ie===void 0&&(Ie=Te==null?void 0:Te[x||H.label]),Qe===void 0&&(Qe=(Re=Te==null?void 0:Te.key)!==null&&Re!==void 0?Re:be),vt=Te==null?void 0:Te.disabled,Et=Te==null?void 0:Te.title}return{label:Ie,value:be,key:Qe,disabled:vt,title:Et}})},[H,x,J]),X=Ft(_,{value:P}),ae=W(X,2),te=ae[0],oe=ae[1],ce=o.useMemo(function(){var le,fe=de(te);return n==="combobox"&&!((le=fe[0])!==null&&le!==void 0&&le.value)?[]:fe},[te,de,n]),pe=db(ce,J),me=W(pe,2),ve=me[0],se=me[1],ee=o.useMemo(function(){if(!n&&ve.length===1){var le=ve[0];if(le.value===null&&(le.label===null||le.label===void 0))return[]}return ve.map(function(fe){var he;return L(L({},fe),{},{label:(he=fe.label)!==null&&he!==void 0?he:fe.value})})},[n,ve]),re=o.useMemo(function(){return new Set(ve.map(function(le){return le.value}))},[ve]);o.useEffect(function(){if(n==="combobox"){var le,fe=(le=ve[0])===null||le===void 0?void 0:le.value;G(lC(fe)?String(fe):"")}},[ve]);var ye=Ud(function(le,fe){var he,be=fe!=null?fe:le;return he={},T(he,H.value,le),T(he,H.label,be),he}),Ne=o.useMemo(function(){if(n!=="tags")return ne;var le=ue(ne),fe=function(be){return J.has(be)};return ue(ve).sort(function(he,be){return he.value2&&arguments[2]!==void 0?arguments[2]:{},be=he.source,Ie=be===void 0?"keyboard":be;Ye(fe),l&&n==="combobox"&&le!==null&&Ie==="keyboard"&&Le(String(le))},[l,n]),$e=function(fe,he,be){var Ie=function(){var dt,ct=se(fe);return[$?{label:ct==null?void 0:ct[H.label],value:fe,key:(dt=ct==null?void 0:ct.key)!==null&&dt!==void 0?dt:fe}:fe,dl(ct)]};if(he&&m){var Qe=Ie(),vt=W(Qe,2),Et=vt[0],at=vt[1];m(Et,at)}else if(!he&&p&&be!=="clear"){var Te=Ie(),Re=W(Te,2),je=Re[0],He=Re[1];p(je,He)}},rt=Ud(function(le,fe){var he,be=U?fe.selected:!0;be?he=U?[].concat(ue(ve),[le]):[le]:he=ve.filter(function(Ie){return Ie.value!==le}),xe(he),$e(le,be),n==="combobox"?Le(""):(!fl||v)&&(G(""),Le(""))}),tt=function(fe,he){xe(fe);var be=he.type,Ie=he.values;(be==="remove"||be==="clear")&&Ie.forEach(function(Qe){$e(Qe.value,!1,be)})},Ze=function(fe,he){if(G(fe),Le(null),he.source==="submit"){var be=(fe||"").trim();if(be){var Ie=Array.from(new Set([].concat(ue(re),[be])));xe(Ie),$e(be,!0),G("")}return}he.source!=="blur"&&(n==="combobox"&&xe(fe),d==null||d(fe))},Me=function(fe){var he=fe;n!=="tags"&&(he=fe.map(function(Ie){var Qe=Z.get(Ie);return Qe==null?void 0:Qe.value}).filter(function(Ie){return Ie!==void 0}));var be=Array.from(new Set([].concat(ue(re),ue(he))));xe(be),be.forEach(function(Ie){$e(Ie,!0)})},Se=o.useMemo(function(){var le=k!==!1&&h!==!1;return L(L({},Q),{},{flattenOptions:ge,onActiveValue:Ae,defaultActiveFirstOption:ot,onSelect:rt,menuItemSelectedIcon:E,rawValues:re,fieldNames:H,virtual:le,listHeight:M,listItemHeight:N,childrenAsData:q})},[Q,ge,Ae,ot,rt,E,re,H,k,h,M,N,q]);return o.createElement(Xd.Provider,{value:Se},o.createElement(jd,F({},A,{id:V,prefixCls:i,ref:t,omitDomProps:Vb,mode:n,displayValues:ee,onDisplayValuesChange:tt,searchValue:B,onSearch:Ze,autoClearSearchValue:v,onSearchSplit:Me,dropdownMatchSelectWidth:h,OptionList:Jd,emptyOptions:!ge.length,activeValue:Oe,activeDescendantId:"".concat(V,"_list_").concat(ut)})))}),gl=jb;gl.Option=pl,gl.OptGroup=ml;var Hb=function(){var t=o.useContext(qe),r=t.getPrefixCls,n=r("empty-img-default");return o.createElement("svg",{className:n,width:"184",height:"152",viewBox:"0 0 184 152",xmlns:"http://www.w3.org/2000/svg"},o.createElement("g",{fill:"none",fillRule:"evenodd"},o.createElement("g",{transform:"translate(24 31.67)"},o.createElement("ellipse",{className:"".concat(n,"-ellipse"),cx:"67.797",cy:"106.89",rx:"67.797",ry:"12.668"}),o.createElement("path",{className:"".concat(n,"-path-1"),d:"M122.034 69.674L98.109 40.229c-1.148-1.386-2.826-2.225-4.593-2.225h-51.44c-1.766 0-3.444.839-4.592 2.225L13.56 69.674v15.383h108.475V69.674z"}),o.createElement("path",{className:"".concat(n,"-path-2"),d:"M101.537 86.214L80.63 61.102c-1.001-1.207-2.507-1.867-4.048-1.867H31.724c-1.54 0-3.047.66-4.048 1.867L6.769 86.214v13.792h94.768V86.214z",transform:"translate(13.56)"}),o.createElement("path",{className:"".concat(n,"-path-3"),d:"M33.83 0h67.933a4 4 0 0 1 4 4v93.344a4 4 0 0 1-4 4H33.83a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4z"}),o.createElement("path",{className:"".concat(n,"-path-4"),d:"M42.678 9.953h50.237a2 2 0 0 1 2 2V36.91a2 2 0 0 1-2 2H42.678a2 2 0 0 1-2-2V11.953a2 2 0 0 1 2-2zM42.94 49.767h49.713a2.262 2.262 0 1 1 0 4.524H42.94a2.262 2.262 0 0 1 0-4.524zM42.94 61.53h49.713a2.262 2.262 0 1 1 0 4.525H42.94a2.262 2.262 0 0 1 0-4.525zM121.813 105.032c-.775 3.071-3.497 5.36-6.735 5.36H20.515c-3.238 0-5.96-2.29-6.734-5.36a7.309 7.309 0 0 1-.222-1.79V69.675h26.318c2.907 0 5.25 2.448 5.25 5.42v.04c0 2.971 2.37 5.37 5.277 5.37h34.785c2.907 0 5.277-2.421 5.277-5.393V75.1c0-2.972 2.343-5.426 5.25-5.426h26.318v33.569c0 .617-.077 1.216-.221 1.789z"})),o.createElement("path",{className:"".concat(n,"-path-5"),d:"M149.121 33.292l-6.83 2.65a1 1 0 0 1-1.317-1.23l1.937-6.207c-2.589-2.944-4.109-6.534-4.109-10.408C138.802 8.102 148.92 0 161.402 0 173.881 0 184 8.102 184 18.097c0 9.995-10.118 18.097-22.599 18.097-4.528 0-8.744-1.066-12.28-2.902z"}),o.createElement("g",{className:"".concat(n,"-g"),transform:"translate(149.65 15.383)"},o.createElement("ellipse",{cx:"20.654",cy:"3.167",rx:"2.849",ry:"2.815"}),o.createElement("path",{d:"M5.698 5.63H0L2.898.704zM9.259.704h4.985V5.63H9.259z"}))))},Bb=function(){var t=o.useContext(qe),r=t.getPrefixCls,n=r("empty-img-simple");return o.createElement("svg",{className:n,width:"64",height:"41",viewBox:"0 0 64 41",xmlns:"http://www.w3.org/2000/svg"},o.createElement("g",{transform:"translate(0 1)",fill:"none",fillRule:"evenodd"},o.createElement("ellipse",{className:"".concat(n,"-ellipse"),cx:"32",cy:"33",rx:"32",ry:"7"}),o.createElement("g",{className:"".concat(n,"-g"),fillRule:"nonzero"},o.createElement("path",{d:"M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z"}),o.createElement("path",{d:"M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z",className:"".concat(n,"-path")}))))},Wb=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a=1},subscribe:function(t){return ur.size||this.register(),Sl+=1,ur.set(Sl,t),t(po),Sl},unsubscribe:function(t){ur.delete(t),ur.size||this.unregister()},unregister:function(){var t=this;Object.keys(mo).forEach(function(r){var n=mo[r],a=t.matchHandlers[n];a==null||a.mql.removeListener(a==null?void 0:a.listener)}),ur.clear()},register:function(){var t=this;Object.keys(mo).forEach(function(r){var n=mo[r],a=function(c){var s=c.matches;t.dispatch(F(F({},po),T({},r,s)))},i=window.matchMedia(n);i.addListener(a),t.matchHandlers[n]={mql:i,listener:a},a(i)})}};function sf(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=o.useRef({}),r=cf();return o.useEffect(function(){var n=ho.subscribe(function(a){t.current=a,e&&r()});return function(){return ho.unsubscribe(n)}},[]),t.current}var un={adjustX:1,adjustY:1},dn=[0,0],uf={left:{points:["cr","cl"],overflow:un,offset:[-4,0],targetOffset:dn},right:{points:["cl","cr"],overflow:un,offset:[4,0],targetOffset:dn},top:{points:["bc","tc"],overflow:un,offset:[0,-4],targetOffset:dn},bottom:{points:["tc","bc"],overflow:un,offset:[0,4],targetOffset:dn},topLeft:{points:["bl","tl"],overflow:un,offset:[0,-4],targetOffset:dn},leftTop:{points:["tr","tl"],overflow:un,offset:[-4,0],targetOffset:dn},topRight:{points:["br","tr"],overflow:un,offset:[0,-4],targetOffset:dn},rightTop:{points:["tl","tr"],overflow:un,offset:[4,0],targetOffset:dn},bottomRight:{points:["tr","br"],overflow:un,offset:[0,4],targetOffset:dn},rightBottom:{points:["bl","br"],overflow:un,offset:[4,0],targetOffset:dn},bottomLeft:{points:["tl","bl"],overflow:un,offset:[0,4],targetOffset:dn},leftBottom:{points:["br","bl"],overflow:un,offset:[-4,0],targetOffset:dn}};function Jb(e){var t=e.showArrow,r=e.arrowContent,n=e.children,a=e.prefixCls,i=e.id,l=e.overlayInnerStyle,c=e.className,s=e.style;return o.createElement("div",{className:Y("".concat(a,"-content"),c),style:s},t!==!1&&o.createElement("div",{className:"".concat(a,"-arrow"),key:"arrow"},r),o.createElement("div",{className:"".concat(a,"-inner"),id:i,role:"tooltip",style:l},typeof n=="function"?n():n))}var Zb=function(t,r){var n=t.overlayClassName,a=t.trigger,i=a===void 0?["hover"]:a,l=t.mouseEnterDelay,c=l===void 0?0:l,s=t.mouseLeaveDelay,u=s===void 0?.1:s,d=t.overlayStyle,f=t.prefixCls,v=f===void 0?"rc-tooltip":f,m=t.children,p=t.onVisibleChange,g=t.afterVisibleChange,h=t.transitionName,y=t.animation,C=t.motion,b=t.placement,x=b===void 0?"right":b,w=t.align,S=w===void 0?{}:w,O=t.destroyTooltipOnHide,E=O===void 0?!1:O,k=t.defaultVisible,I=t.getTooltipContainer,M=t.overlayInnerStyle,R=t.arrowContent,N=t.overlay,P=t.id,_=t.showArrow,$=Fe(t,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","afterVisibleChange","transitionName","animation","motion","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer","overlayInnerStyle","arrowContent","overlay","id","showArrow"]),D=o.useRef(null);o.useImperativeHandle(r,function(){return D.current});var A=L({},$);"visible"in t&&(A.popupVisible=t.visible);var V=function(){return o.createElement(Jb,{showArrow:_,arrowContent:R,key:"content",prefixCls:v,id:P,overlayInnerStyle:M},N)},U=!1,q=!1;if(typeof E=="boolean")U=E;else if(E&&ke(E)==="object"){var K=E.keepParent;U=K===!0,q=K===!1}return o.createElement(co,F({popupClassName:n,prefixCls:v,popup:V,action:i,builtinPlacements:uf,popupPlacement:x,ref:D,popupAlign:S,getPopupContainer:I,onPopupVisibleChange:p,afterPopupVisibleChange:g,popupTransitionName:h,popupAnimation:y,popupMotion:C,defaultPopupVisible:k,destroyPopupOnHide:U,autoDestroy:q,mouseLeaveDelay:u,popupStyle:d,mouseEnterDelay:c},A),m)},e0=o.forwardRef(Zb),bP=Wt("success","processing","error","default","warning"),t0=Wt("pink","red","yellow","orange","cyan","green","blue","purple","geekblue","magenta","volcano","gold","lime"),n0={adjustX:1,adjustY:1},df={adjustX:0,adjustY:0},r0=[0,0];function ff(e){return typeof e=="boolean"?e?n0:df:F(F({},df),e)}function vf(e){var t=e.arrowWidth,r=t===void 0?4:t,n=e.horizontalArrowShift,a=n===void 0?16:n,i=e.verticalArrowShift,l=i===void 0?8:i,c=e.autoAdjustOverflow,s=e.arrowPointAtCenter,u={left:{points:["cr","cl"],offset:[-4,0]},right:{points:["cl","cr"],offset:[4,0]},top:{points:["bc","tc"],offset:[0,-4]},bottom:{points:["tc","bc"],offset:[0,4]},topLeft:{points:["bl","tc"],offset:[-(a+r),-4]},leftTop:{points:["tr","cl"],offset:[-4,-(l+r)]},topRight:{points:["br","tc"],offset:[a+r,-4]},rightTop:{points:["tl","cr"],offset:[4,-(l+r)]},bottomRight:{points:["tr","bc"],offset:[a+r,4]},rightBottom:{points:["bl","cr"],offset:[4,l+r]},bottomLeft:{points:["tl","bc"],offset:[-(a+r),4]},leftBottom:{points:["br","cl"],offset:[-4,l+r]}};return Object.keys(u).forEach(function(d){u[d]=s?F(F({},u[d]),{overflow:ff(c),targetOffset:r0}):F(F({},uf[d]),{overflow:ff(c)}),u[d].ignoreShake=!0}),u}var a0=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a1&&arguments[1]!==void 0?arguments[1]:!1;if(Yi(e)){var r=e.nodeName.toLowerCase(),n=["input","select","textarea","button"].includes(r)||e.isContentEditable||r==="a"&&!!e.getAttribute("href"),a=e.getAttribute("tabindex"),i=Number(a),l=null;return a&&!Number.isNaN(i)?l=i:n&&l===null&&(l=0),n&&e.disabled&&(l=null),l!==null&&(l>=0||t&&l<0)}return!1}function Sf(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=ue(e.querySelectorAll("*")).filter(function(n){return xf(n,t)});return xf(e,t)&&r.unshift(e),r}var Nl=ie.LEFT,Pl=ie.RIGHT,Rl=ie.UP,yo=ie.DOWN,Co=ie.ENTER,Ef=ie.ESC,Ca=ie.HOME,ba=ie.END,wf=[Rl,yo,Nl,Pl];function v0(e,t,r,n){var a,i,l,c,s="prev",u="next",d="children",f="parent";if(e==="inline"&&n===Co)return{inlineTrigger:!0};var v=(a={},T(a,Rl,s),T(a,yo,u),a),m=(i={},T(i,Nl,r?u:s),T(i,Pl,r?s:u),T(i,yo,d),T(i,Co,d),i),p=(l={},T(l,Rl,s),T(l,yo,u),T(l,Co,d),T(l,Ef,f),T(l,Nl,r?d:f),T(l,Pl,r?f:d),l),g={inline:v,horizontal:m,vertical:p,inlineSub:v,horizontalSub:p,verticalSub:p},h=(c=g["".concat(e).concat(t?"":"Sub")])===null||c===void 0?void 0:c[n];switch(h){case s:return{offset:-1,sibling:!0};case u:return{offset:1,sibling:!0};case f:return{offset:-1,sibling:!1};case d:return{offset:1,sibling:!1};default:return null}}function m0(e){for(var t=e;t;){if(t.getAttribute("data-menu-list"))return t;t=t.parentElement}return null}function p0(e,t){for(var r=e||document.activeElement;r;){if(t.has(r))return r;r=r.parentElement}return null}function Nf(e,t){var r=Sf(e,!0);return r.filter(function(n){return t.has(n)})}function Pf(e,t,r){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;if(!e)return null;var a=Nf(e,t),i=a.length,l=a.findIndex(function(c){return r===c});return n<0?l===-1?l=i-1:l-=1:n>0&&(l+=1),l=(l+i)%i,a[l]}function h0(e,t,r,n,a,i,l,c,s,u){var d=o.useRef(),f=o.useRef();f.current=t;var v=function(){nt.cancel(d.current)};return o.useEffect(function(){return function(){v()}},[]),function(m){var p=m.which;if([].concat(wf,[Co,Ef,Ca,ba]).includes(p)){var g,h,y,C=function(){g=new Set,h=new Map,y=new Map;var _=i();return _.forEach(function($){var D=document.querySelector("[data-menu-id='".concat(El(n,$),"']"));D&&(g.add(D),y.set(D,$),h.set($,D))}),g};C();var b=h.get(t),x=p0(b,g),w=y.get(x),S=v0(e,l(w,!0).length===1,r,p);if(!S&&p!==Ca&&p!==ba)return;(wf.includes(p)||[Ca,ba].includes(p))&&m.preventDefault();var O=function(_){if(_){var $=_,D=_.querySelector("a");D!=null&&D.getAttribute("href")&&($=D);var A=y.get(_);c(A),v(),d.current=nt(function(){f.current===A&&$.focus()})}};if([Ca,ba].includes(p)||S.sibling||!x){var E;!x||e==="inline"?E=a.current:E=m0(x);var k,I=Nf(E,g);p===Ca?k=I[0]:p===ba?k=I[I.length-1]:k=Pf(E,g,x,S.offset),O(k)}else if(S.inlineTrigger)s(w);else if(S.offset>0)s(w,!0),v(),d.current=nt(function(){C();var P=x.getAttribute("aria-controls"),_=document.getElementById(P),$=Pf(_,g);O($)},5);else if(S.offset<0){var M=l(w,!0),R=M[M.length-2],N=h.get(R);s(R,!1),O(N)}}u==null||u(m)}}function g0(e){Promise.resolve().then(e)}var kl="__RC_UTIL_PATH_SPLIT__",Rf=function(t){return t.join(kl)},y0=function(t){return t.split(kl)},Ol="rc-menu-more";function C0(){var e=o.useState({}),t=W(e,2),r=t[1],n=o.useRef(new Map),a=o.useRef(new Map),i=o.useState([]),l=W(i,2),c=l[0],s=l[1],u=o.useRef(0),d=o.useRef(!1),f=function(){d.current||r({})},v=o.useCallback(function(b,x){var w=Rf(x);a.current.set(w,b),n.current.set(b,w),u.current+=1;var S=u.current;g0(function(){S===u.current&&f()})},[]),m=o.useCallback(function(b,x){var w=Rf(x);a.current.delete(w),n.current.delete(b)},[]),p=o.useCallback(function(b){s(b)},[]),g=o.useCallback(function(b,x){var w=n.current.get(b)||"",S=y0(w);return x&&c.includes(S[0])&&S.unshift(Ol),S},[c]),h=o.useCallback(function(b,x){return b.some(function(w){var S=g(w,!0);return S.includes(x)})},[g]),y=function(){var x=ue(n.current.keys());return c.length&&x.push(Ol),x},C=o.useCallback(function(b){var x="".concat(n.current.get(b)).concat(kl),w=new Set;return ue(a.current.keys()).forEach(function(S){S.startsWith(x)&&w.add(a.current.get(S))}),w},[]);return o.useEffect(function(){return function(){d.current=!0}},[]),{registerPath:v,unregisterPath:m,refreshOverflowKeys:p,isSubPathKey:h,getKeyPath:g,getKeys:y,getSubPathKeys:C}}function Lr(e){var t=o.useRef(e);t.current=e;var r=o.useCallback(function(){for(var n,a=arguments.length,i=new Array(a),l=0;l1&&(C.motionAppear=!1);var b=C.onVisibleChanged;return C.onVisibleChanged=function(x){return!v.current&&!x&&h(!0),b==null?void 0:b(x)},g?null:o.createElement(ya,{mode:i,locked:!v.current},o.createElement(Zt,F({visible:y},C,{forceRender:s,removeOnLeave:!1,leavedClassName:"".concat(c,"-hidden")}),function(x){var w=x.className,S=x.style;return o.createElement(Il,{id:t,className:w,style:S},a)}))}var A0=["style","className","title","eventKey","warnKey","disabled","internalPopupClose","children","itemIcon","expandIcon","popupClassName","popupOffset","onClick","onMouseEnter","onMouseLeave","onTitleClick","onTitleMouseEnter","onTitleMouseLeave"],L0=["active"],K0=function(t){var r,n=t.style,a=t.className,i=t.title,l=t.eventKey,c=t.warnKey,s=t.disabled,u=t.internalPopupClose,d=t.children,f=t.itemIcon,v=t.expandIcon,m=t.popupClassName,p=t.popupOffset,g=t.onClick,h=t.onMouseEnter,y=t.onMouseLeave,C=t.onTitleClick,b=t.onTitleMouseEnter,x=t.onTitleMouseLeave,w=Fe(t,A0),S=gf(l),O=o.useContext(vn),E=O.prefixCls,k=O.mode,I=O.openKeys,M=O.disabled,R=O.overflowDisabled,N=O.activeKey,P=O.selectedKeys,_=O.itemIcon,$=O.expandIcon,D=O.onItemClick,A=O.onOpenChange,V=O.onActive,U=o.useContext(wl),q=U._internalRenderSubMenuItem,K=o.useContext(bf),H=K.isSubPathKey,j=Ar(),z="".concat(E,"-submenu"),B=M||s,G=o.useRef(),Q=o.useRef(),J=f||_,Z=v||$,ne=I.includes(l),de=!R&&ne,X=H(P,l),ae=Of(l,B,b,x),te=ae.active,oe=Fe(ae,L0),ce=o.useState(!1),pe=W(ce,2),me=pe[0],ve=pe[1],se=function(Ke){B||ve(Ke)},ee=function(Ke){se(!0),h==null||h({key:l,domEvent:Ke})},re=function(Ke){se(!1),y==null||y({key:l,domEvent:Ke})},ye=o.useMemo(function(){return te||(k!=="inline"?me||H([N],l):!1)},[k,te,N,me,l,H]),Ne=Mf(j.length),Ce=function(Ke){B||(C==null||C({key:l,domEvent:Ke}),k==="inline"&&A(l,!ne))},_e=Lr(function(et){g==null||g(bo(et)),D(et)}),Ee=function(Ke){k!=="inline"&&A(l,Ke)},ge=function(){V(l)},xe=S&&"".concat(S,"-popup"),De=o.createElement("div",F({role:"menuitem",style:Ne,className:"".concat(z,"-title"),tabIndex:B?null:-1,ref:G,title:typeof i=="string"?i:null,"data-menu-id":R&&S?null:S,"aria-expanded":de,"aria-haspopup":!0,"aria-controls":xe,"aria-disabled":B,onClick:Ce,onFocus:ge},oe),i,o.createElement(If,{icon:k!=="horizontal"?Z:null,props:L(L({},t),{},{isOpen:de,isSubMenu:!0})},o.createElement("i",{className:"".concat(z,"-arrow")}))),we=o.useRef(k);if(k!=="inline"&&j.length>1?we.current="vertical":we.current=k,!R){var Oe=we.current;De=o.createElement($0,{mode:Oe,prefixCls:z,visible:!u&&de&&k!=="inline",popupClassName:m,popupOffset:p,popup:o.createElement(ya,{mode:Oe==="horizontal"?"vertical":Oe},o.createElement(Il,{id:xe,ref:Q},d)),disabled:B,onVisibleChange:Ee},De)}var Le=o.createElement(gn.Item,F({role:"none"},w,{component:"li",style:n,className:Y(z,"".concat(z,"-").concat(k),a,(r={},T(r,"".concat(z,"-open"),de),T(r,"".concat(z,"-active"),ye),T(r,"".concat(z,"-selected"),X),T(r,"".concat(z,"-disabled"),B),r)),onMouseEnter:ee,onMouseLeave:re}),De,!R&&o.createElement(F0,{id:xe,open:de,keyPath:j},d));return q&&(Le=q(Le,t,{selected:X,active:ye,open:de,disabled:B})),o.createElement(ya,{onItemClick:_e,mode:k==="horizontal"?"vertical":k,itemIcon:J,expandIcon:Z},Le)};function xo(e){var t=e.eventKey,r=e.children,n=Ar(t),a=Ml(r,n),i=go();o.useEffect(function(){if(i)return i.registerPath(t,n),function(){i.unregisterPath(t,n)}},[n]);var l;return i?l=a:l=o.createElement(K0,e,a),o.createElement(Cf.Provider,{value:n},l)}var V0=["prefixCls","rootClassName","style","className","tabIndex","items","children","direction","id","mode","inlineCollapsed","disabled","disabledOverflow","subMenuOpenDelay","subMenuCloseDelay","forceSubMenuRender","defaultOpenKeys","openKeys","activeKey","defaultActiveFirst","selectable","multiple","defaultSelectedKeys","selectedKeys","onSelect","onDeselect","inlineIndent","motion","defaultMotions","triggerSubMenuAction","builtinPlacements","itemIcon","expandIcon","overflowedIndicator","overflowedIndicatorPopupClassName","getPopupContainer","onClick","onOpenChange","onKeyDown","openAnimation","openTransitionName","_internalRenderMenuItem","_internalRenderSubMenuItem"],Kr=[],z0=o.forwardRef(function(e,t){var r,n,a=e,i=a.prefixCls,l=i===void 0?"rc-menu":i,c=a.rootClassName,s=a.style,u=a.className,d=a.tabIndex,f=d===void 0?0:d,v=a.items,m=a.children,p=a.direction,g=a.id,h=a.mode,y=h===void 0?"vertical":h,C=a.inlineCollapsed,b=a.disabled,x=a.disabledOverflow,w=a.subMenuOpenDelay,S=w===void 0?.1:w,O=a.subMenuCloseDelay,E=O===void 0?.1:O,k=a.forceSubMenuRender,I=a.defaultOpenKeys,M=a.openKeys,R=a.activeKey,N=a.defaultActiveFirst,P=a.selectable,_=P===void 0?!0:P,$=a.multiple,D=$===void 0?!1:$,A=a.defaultSelectedKeys,V=a.selectedKeys,U=a.onSelect,q=a.onDeselect,K=a.inlineIndent,H=K===void 0?24:K,j=a.motion,z=a.defaultMotions,B=a.triggerSubMenuAction,G=B===void 0?"hover":B,Q=a.builtinPlacements,J=a.itemIcon,Z=a.expandIcon,ne=a.overflowedIndicator,de=ne===void 0?"...":ne,X=a.overflowedIndicatorPopupClassName,ae=a.getPopupContainer,te=a.onClick,oe=a.onOpenChange,ce=a.onKeyDown,pe=a.openAnimation,me=a.openTransitionName,ve=a._internalRenderMenuItem,se=a._internalRenderSubMenuItem,ee=Fe(a,V0),re=o.useMemo(function(){return M0(m,v,Kr)},[m,v]),ye=o.useState(!1),Ne=W(ye,2),Ce=Ne[0],_e=Ne[1],Ee=o.useRef(),ge=x0(g),xe=p==="rtl",De=Ft(I,{value:M,postState:function(it){return it||Kr}}),we=W(De,2),Oe=we[0],Le=we[1],et=function(it){var ft=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;function bt(){Le(it),oe==null||oe(it)}ft?Vn.flushSync(bt):bt()},Ke=o.useState(Oe),ut=W(Ke,2),Ye=ut[0],ot=ut[1],Ae=o.useRef(!1),$e=o.useMemo(function(){return(y==="inline"||y==="vertical")&&C?["vertical",C]:[y,!1]},[y,C]),rt=W($e,2),tt=rt[0],Ze=rt[1],Me=tt==="inline",Se=o.useState(tt),le=W(Se,2),fe=le[0],he=le[1],be=o.useState(Ze),Ie=W(be,2),Qe=Ie[0],vt=Ie[1];o.useEffect(function(){he(tt),vt(Ze),!!Ae.current&&(Me?Le(Ye):et(Kr))},[tt,Ze]);var Et=o.useState(0),at=W(Et,2),Te=at[0],Re=at[1],je=Te>=re.length-1||fe!=="horizontal"||x;o.useEffect(function(){Me&&ot(Oe)},[Oe]),o.useEffect(function(){return Ae.current=!0,function(){Ae.current=!1}},[]);var He=C0(),ht=He.registerPath,dt=He.unregisterPath,ct=He.refreshOverflowKeys,wt=He.isSubPathKey,kt=He.getKeyPath,At=He.getKeys,Ve=He.getSubPathKeys,Pe=o.useMemo(function(){return{registerPath:ht,unregisterPath:dt}},[ht,dt]),Xe=o.useMemo(function(){return{isSubPathKey:wt}},[wt]);o.useEffect(function(){ct(je?Kr:re.slice(Te+1).map(function(mt){return mt.key}))},[Te,je]);var ze=Ft(R||N&&((r=re[0])===null||r===void 0?void 0:r.key),{value:R}),Ge=W(ze,2),gt=Ge[0],xt=Ge[1],nn=Lr(function(mt){xt(mt)}),En=Lr(function(){xt(void 0)});o.useImperativeHandle(t,function(){return{list:Ee.current,focus:function(it){var ft,bt=gt!=null?gt:(ft=re.find(function(Qo){return!Qo.props.disabled}))===null||ft===void 0?void 0:ft.key;if(bt){var Vt,Nn,er;(Vt=Ee.current)===null||Vt===void 0||(Nn=Vt.querySelector("li[data-menu-id='".concat(El(ge,bt),"']")))===null||Nn===void 0||(er=Nn.focus)===null||er===void 0||er.call(Nn,it)}}}});var Zn=Ft(A||[],{value:V,postState:function(it){return Array.isArray(it)?it:it==null?Kr:[it]}}),yr=W(Zn,2),wn=yr[0],ea=yr[1],Cr=function(it){if(_){var ft=it.key,bt=wn.includes(ft),Vt;D?bt?Vt=wn.filter(function(er){return er!==ft}):Vt=[].concat(ue(wn),[ft]):Vt=[ft],ea(Vt);var Nn=L(L({},it),{},{selectedKeys:Vt});bt?q==null||q(Nn):U==null||U(Nn)}!D&&Oe.length&&fe!=="inline"&&et(Kr)},Ln=Lr(function(mt){te==null||te(bo(mt)),Cr(mt)}),Be=Lr(function(mt,it){var ft=Oe.filter(function(Vt){return Vt!==mt});if(it)ft.push(mt);else if(fe!=="inline"){var bt=Ve(mt);ft=ft.filter(function(Vt){return!bt.has(Vt)})}xr(Oe,ft)||et(ft,!0)}),Ue=Lr(ae),Nt=function(it,ft){var bt=ft!=null?ft:!Oe.includes(it);Be(it,bt)},Lt=h0(fe,gt,xe,ge,Ee,At,kt,xt,Nt,ce);o.useEffect(function(){_e(!0)},[]);var St=o.useMemo(function(){return{_internalRenderMenuItem:ve,_internalRenderSubMenuItem:se}},[ve,se]),Kt=fe!=="horizontal"||x?re:re.map(function(mt,it){return o.createElement(ya,{key:mt.key,overflowDisabled:it>Te},mt)}),Bt=o.createElement(gn,F({id:g,ref:Ee,prefixCls:"".concat(l,"-overflow"),component:"ul",itemComponent:xa,className:Y(l,"".concat(l,"-root"),"".concat(l,"-").concat(fe),u,(n={},T(n,"".concat(l,"-inline-collapsed"),Qe),T(n,"".concat(l,"-rtl"),xe),n),c),dir:p,style:s,role:"menu",tabIndex:f,data:Kt,renderRawItem:function(it){return it},renderRawRest:function(it){var ft=it.length,bt=ft?re.slice(-ft):null;return o.createElement(xo,{eventKey:Ol,title:de,disabled:je,internalPopupClose:ft===0,popupClassName:X},bt)},maxCount:fe!=="horizontal"||x?gn.INVALIDATE:gn.RESPONSIVE,ssr:"full","data-menu-list":!0,onVisibleChange:function(it){Re(it)},onKeyDown:Lt},ee));return o.createElement(wl.Provider,{value:St},o.createElement(hf.Provider,{value:ge},o.createElement(ya,{prefixCls:l,rootClassName:c,mode:fe,openKeys:Oe,rtl:xe,disabled:b,motion:Ce?j:null,defaultMotions:Ce?z:null,activeKey:gt,onActive:nn,onInactive:En,selectedKeys:wn,inlineIndent:H,subMenuOpenDelay:S,subMenuCloseDelay:E,forceSubMenuRender:k,builtinPlacements:Q,triggerSubMenuAction:G,getPopupContainer:Ue,itemIcon:J,expandIcon:Z,onItemClick:Ln,onOpenChange:Be},o.createElement(bf.Provider,{value:Xe},Bt),o.createElement("div",{style:{display:"none"},"aria-hidden":!0},o.createElement(yf.Provider,{value:Pe},re)))))}),j0=["className","title","eventKey","children"],H0=["children"],B0=function(t){var r=t.className,n=t.title,a=t.eventKey,i=t.children,l=Fe(t,j0),c=o.useContext(vn),s=c.prefixCls,u="".concat(s,"-item-group");return o.createElement("li",F({},l,{onClick:function(f){return f.stopPropagation()},className:Y(u,r)}),o.createElement("div",{className:"".concat(u,"-title"),title:typeof n=="string"?n:void 0},n),o.createElement("ul",{className:"".concat(u,"-list")},i))};function So(e){var t=e.children,r=Fe(e,H0),n=Ar(r.eventKey),a=Ml(t,n),i=go();return i?a:o.createElement(B0,zt(r,["warnKey"]),a)}function _l(e){var t=e.className,r=e.style,n=o.useContext(vn),a=n.prefixCls,i=go();return i?null:o.createElement("li",{className:Y("".concat(a,"-item-divider"),t),style:r})}var Vr=z0;Vr.Item=xa,Vr.SubMenu=xo,Vr.ItemGroup=So,Vr.Divider=_l;var xP=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a1&&arguments[1]!==void 0?arguments[1]:1,r=ax++,n=t;function a(){n-=1,n<=0?(e(),delete Br[r]):Br[r]=nt(a)}return Br[r]=nt(a),r}No.cancel=function(t){t!==void 0&&(nt.cancel(Br[t]),delete Br[t])},No.ids=Br;var Fl;function Lf(e){return!e||e.offsetParent===null||e.hidden}function ox(e){return e instanceof Document?e.body:Array.from(e.childNodes).find(function(t){return(t==null?void 0:t.nodeType)===Node.ELEMENT_NODE})}function ix(e){var t=(e||"").match(/rgba?\((\d*), (\d*), (\d*)(, [\d.]*)?\)/);return t&&t[1]&&t[2]&&t[3]?!(t[1]===t[2]&&t[2]===t[3]):!0}var Kf=function(e){_t(r,e);var t=Dt(r);function r(){var n;return Pt(this,r),n=t.apply(this,arguments),n.containerRef=o.createRef(),n.animationStart=!1,n.destroyed=!1,n.onClick=function(a,i){var l,c,s=n.props,u=s.insertExtraNode,d=s.disabled;if(!(d||!a||Lf(a)||a.className.includes("-leave"))){n.extraNode=document.createElement("div");var f=We(n),v=f.extraNode,m=n.context.getPrefixCls;v.className="".concat(m(""),"-click-animating-node");var p=n.getAttributeName();if(a.setAttribute(p,"true"),i&&i!=="#fff"&&i!=="#ffffff"&&i!=="rgb(255, 255, 255)"&&i!=="rgba(255, 255, 255, 1)"&&ix(i)&&!/rgba\((?:\d*, ){3}0\)/.test(i)&&i!=="transparent"){v.style.borderColor=i;var g=((l=a.getRootNode)===null||l===void 0?void 0:l.call(a))||a.ownerDocument,h=(c=ox(g))!==null&&c!==void 0?c:g;Fl=ti(` + [`.concat(m(""),"-click-animating-without-extra-node='true']::after, .").concat(m(""),`-click-animating-node { + --antd-wave-shadow-color: `).concat(i,`; + }`),"antd-wave",{csp:n.csp,attachTo:h})}u&&a.appendChild(v),["transition","animation"].forEach(function(y){a.addEventListener("".concat(y,"start"),n.onTransitionStart),a.addEventListener("".concat(y,"end"),n.onTransitionEnd)})}},n.onTransitionStart=function(a){if(!n.destroyed){var i=n.containerRef.current;!a||a.target!==i||n.animationStart||n.resetEffect(i)}},n.onTransitionEnd=function(a){!a||a.animationName!=="fadeEffect"||n.resetEffect(a.target)},n.bindAnimationEvent=function(a){if(!(!a||!a.getAttribute||a.getAttribute("disabled")||a.className.includes("disabled"))){var i=function(c){if(!(c.target.tagName==="INPUT"||Lf(c.target))){n.resetEffect(a);var s=getComputedStyle(a).getPropertyValue("border-top-color")||getComputedStyle(a).getPropertyValue("border-color")||getComputedStyle(a).getPropertyValue("background-color");n.clickWaveTimeoutId=window.setTimeout(function(){return n.onClick(a,s)},0),No.cancel(n.animationStartId),n.animationStart=!0,n.animationStartId=No(function(){n.animationStart=!1},10)}};return a.addEventListener("click",i,!0),{cancel:function(){a.removeEventListener("click",i,!0)}}}},n.renderWave=function(a){var i=a.csp,l=n.props.children;if(n.csp=i,!o.isValidElement(l))return l;var c=n.containerRef;return nr(l)&&(c=on(l.ref,n.containerRef)),Ht(l,{ref:c})},n}return Rt(r,[{key:"componentDidMount",value:function(){this.destroyed=!1;var a=this.containerRef.current;!a||a.nodeType!==1||(this.instance=this.bindAnimationEvent(a))}},{key:"componentWillUnmount",value:function(){this.instance&&this.instance.cancel(),this.clickWaveTimeoutId&&clearTimeout(this.clickWaveTimeoutId),this.destroyed=!0}},{key:"getAttributeName",value:function(){var a=this.context.getPrefixCls,i=this.props.insertExtraNode;return i?"".concat(a(""),"-click-animating"):"".concat(a(""),"-click-animating-without-extra-node")}},{key:"resetEffect",value:function(a){var i=this;if(!(!a||a===this.extraNode||!(a instanceof Element))){var l=this.props.insertExtraNode,c=this.getAttributeName();a.setAttribute(c,"false"),Fl&&(Fl.innerHTML=""),l&&this.extraNode&&a.contains(this.extraNode)&&a.removeChild(this.extraNode),["transition","animation"].forEach(function(s){a.removeEventListener("".concat(s,"start"),i.onTransitionStart),a.removeEventListener("".concat(s,"end"),i.onTransitionEnd)})}}},{key:"render",value:function(){return o.createElement(cr,null,this.renderWave)}}]),r}(o.Component);Kf.contextType=qe;var lx=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0&&(N=g.map(function($){return typeof $=="string"||typeof $=="number"?o.createElement(ko,{key:$.toString(),prefixCls:M,disabled:C,value:$,checked:u===$},$):o.createElement(ko,{key:"radio-group-value-options-".concat($.value),prefixCls:M,disabled:$.disabled||C,value:$.value,checked:u===$.value,style:$.style},$.label)}));var P=x||l,_=Y(R,"".concat(R,"-").concat(y),(r={},T(r,"".concat(R,"-").concat(P),P),T(r,"".concat(R,"-rtl"),i==="rtl"),r),p);return o.createElement("div",F({},$y(e),{className:_,style:w,onMouseEnter:O,onMouseLeave:E,onFocus:k,onBlur:I,id:S,ref:t}),o.createElement(wx,{value:{onChange:f,value:u,disabled:e.disabled,name:e.name,optionType:e.optionType}},N))}),Ox=o.memo(kx),Ix=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);av+t){p=g-1;break}}for(var y=0,C=m-1;C>=0;C-=1){var b=e.get(c[C].key)||Zf;if(b[f]P?(R=I,S.current="x"):(R=M,S.current="y"),t(-R,-R)&&k.preventDefault()}var E=o.useRef(null);E.current={onTouchStart:b,onTouchMove:x,onTouchEnd:w,onWheel:O},o.useEffect(function(){function k(N){E.current.onTouchStart(N)}function I(N){E.current.onTouchMove(N)}function M(N){E.current.onTouchEnd(N)}function R(N){E.current.onWheel(N)}return document.addEventListener("touchmove",I,{passive:!1}),document.addEventListener("touchend",M,{passive:!1}),e.current.addEventListener("touchstart",k,{passive:!1}),e.current.addEventListener("wheel",R),function(){document.removeEventListener("touchmove",I),document.removeEventListener("touchend",M)}},[])}function Wx(){var e=o.useRef(new Map);function t(n){return e.current.has(n)||e.current.set(n,o.createRef()),e.current.get(n)}function r(n){e.current.delete(n)}return[t,r]}function rv(e,t){var r=o.useRef(e),n=o.useState({}),a=W(n,2),i=a[1];function l(c){var s=typeof c=="function"?c(r.current):c;s!==r.current&&t(s,r.current),r.current=s,i({})}return[r.current,l]}function av(e){var t;return e instanceof Map?(t={},e.forEach(function(r,n){t[n]=r})):t=e,JSON.stringify(t)}var ov=o.forwardRef(function(e,t){var r=e.position,n=e.prefixCls,a=e.extra;if(!a)return null;var i,l={};return ke(a)==="object"&&!o.isValidElement(a)?l=a:l.right=a,r==="right"&&(i=l.right),r==="left"&&(i=l.left),i?o.createElement("div",{className:"".concat(n,"-extra-content"),ref:t},i):null}),Ur=function(t){var r=t.current||{},n=r.offsetWidth,a=n===void 0?0:n,i=r.offsetHeight,l=i===void 0?0:i;return[a,l]},Mo=function(t,r){return t[r?0:1]};function Ux(e,t){var r,n=o.useContext(Oo),a=n.prefixCls,i=n.tabs,l=e.className,c=e.style,s=e.id,u=e.animated,d=e.activeKey,f=e.rtl,v=e.extra,m=e.editable,p=e.locale,g=e.tabPosition,h=e.tabBarGutter,y=e.children,C=e.onTabClick,b=e.onTabScroll,x=o.useRef(),w=o.useRef(),S=o.useRef(),O=o.useRef(),E=o.useRef(),k=o.useRef(),I=o.useRef(),M=Wx(),R=W(M,2),N=R[0],P=R[1],_=g==="top"||g==="bottom",$=rv(0,function(Pe,Xe){_&&b&&b({direction:Pe>Xe?"left":"right"})}),D=W($,2),A=D[0],V=D[1],U=rv(0,function(Pe,Xe){!_&&b&&b({direction:Pe>Xe?"top":"bottom"})}),q=W(U,2),K=q[0],H=q[1],j=o.useState([0,0]),z=W(j,2),B=z[0],G=z[1],Q=o.useState([0,0]),J=W(Q,2),Z=J[0],ne=J[1],de=o.useState([0,0]),X=W(de,2),ae=X[0],te=X[1],oe=o.useState([0,0]),ce=W(oe,2),pe=ce[0],me=ce[1],ve=$x(new Map),se=W(ve,2),ee=se[0],re=se[1],ye=Lx(i,ee,Z[0]),Ne=Mo(B,_),Ce=Mo(Z,_),_e=Mo(ae,_),Ee=Mo(pe,_),ge=NeOe?Oe:Pe}var et=o.useRef(),Ke=o.useState(),ut=W(Ke,2),Ye=ut[0],ot=ut[1];function Ae(){ot(Date.now())}function $e(){window.clearTimeout(et.current)}Bx(O,function(Pe,Xe){function ze(Ge,gt){Ge(function(xt){var nn=Le(xt+gt);return nn})}return Ne>=Ce?!1:(_?ze(V,Pe):ze(H,Xe),$e(),Ae(),!0)}),o.useEffect(function(){return $e(),Ye&&(et.current=window.setTimeout(function(){ot(0)},100)),$e},[Ye]);var rt=Kx(ye,xe,_?A:K,Ce,_e,Ee,L(L({},e),{},{tabs:i})),tt=W(rt,2),Ze=tt[0],Me=tt[1],Se=function(){var Xe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:d,ze=ye.get(Xe)||{width:0,height:0,left:0,right:0,top:0};if(_){var Ge=A;f?ze.rightA+xe&&(Ge=ze.right+ze.width-xe):ze.left<-A?Ge=-ze.left:ze.left+ze.width>-A+xe&&(Ge=-(ze.left+ze.width-xe)),H(0),V(Le(Ge))}else{var gt=K;ze.top<-K?gt=-ze.top:ze.top+ze.height>-K+xe&&(gt=-(ze.top+ze.height-xe)),V(0),H(Le(gt))}},le={};g==="top"||g==="bottom"?le[f?"marginRight":"marginLeft"]=h:le.marginTop=h;var fe=i.map(function(Pe,Xe){var ze=Pe.key;return o.createElement(Ax,{id:s,prefixCls:a,key:ze,tab:Pe,style:Xe===0?void 0:le,closable:Pe.closable,editable:m,active:ze===d,renderWrapper:y,removeAriaLabel:p==null?void 0:p.removeAriaLabel,ref:N(ze),onClick:function(gt){C(ze,gt)},onRemove:function(){P(ze)},onFocus:function(){Se(ze),Ae(),!!O.current&&(f||(O.current.scrollLeft=0),O.current.scrollTop=0)}})}),he=function(){return re(function(){var Xe=new Map;return i.forEach(function(ze){var Ge=ze.key,gt=N(Ge).current;gt&&Xe.set(Ge,{width:gt.offsetWidth,height:gt.offsetHeight,left:gt.offsetLeft,top:gt.offsetTop})}),Xe})};o.useEffect(function(){he()},[i.map(function(Pe){return Pe.key}).join("_")]);var be=Qf(function(){var Pe=Ur(x),Xe=Ur(w),ze=Ur(S);G([Pe[0]-Xe[0]-ze[0],Pe[1]-Xe[1]-ze[1]]);var Ge=Ur(I);te(Ge);var gt=Ur(k);me(gt);var xt=Ur(E);ne([xt[0]-Ge[0],xt[1]-Ge[1]])}),Ie=i.slice(0,Ze),Qe=i.slice(Me+1),vt=[].concat(ue(Ie),ue(Qe)),Et=o.useState(),at=W(Et,2),Te=at[0],Re=at[1],je=ye.get(d),He=o.useRef();function ht(){nt.cancel(He.current)}o.useEffect(function(){var Pe={};return je&&(_?(f?Pe.right=je.right:Pe.left=je.left,Pe.width=je.width):(Pe.top=je.top,Pe.height=je.height)),ht(),He.current=nt(function(){Re(Pe)}),ht},[je,_,f]),o.useEffect(function(){Se()},[d,av(je),av(ye),_]),o.useEffect(function(){be()},[f]);var dt=!!vt.length,ct="".concat(a,"-nav-wrap"),wt,kt,At,Ve;return _?f?(kt=A>0,wt=A+Ne0&&arguments[0]!==void 0?arguments[0]:{inkBar:!0,tabPane:!1},t;return e===!1?t={inkBar:!1,tabPane:!1}:e===!0?t={inkBar:!0,tabPane:!1}:t=L({inkBar:!0},ke(e)==="object"?e:{}),t.tabPaneMotion&&t.tabPane===void 0&&(t.tabPane=!0),!t.tabPaneMotion&&t.tabPane&&(t.tabPane=!1),t}var Qx=["id","prefixCls","className","items","direction","activeKey","defaultActiveKey","editable","animated","tabPosition","tabBarGutter","tabBarStyle","tabBarExtraContent","locale","moreIcon","moreTransitionName","destroyInactiveTabPane","renderTabBar","onChange","onTabClick","onTabScroll","getPopupContainer","popupClassName"],lv=0;function Jx(e,t){var r,n=e.id,a=e.prefixCls,i=a===void 0?"rc-tabs":a,l=e.className,c=e.items,s=e.direction,u=e.activeKey,d=e.defaultActiveKey,f=e.editable,v=e.animated,m=e.tabPosition,p=m===void 0?"top":m,g=e.tabBarGutter,h=e.tabBarStyle,y=e.tabBarExtraContent,C=e.locale,b=e.moreIcon,x=e.moreTransitionName,w=e.destroyInactiveTabPane,S=e.renderTabBar,O=e.onChange,E=e.onTabClick,k=e.onTabScroll,I=e.getPopupContainer,M=e.popupClassName,R=Fe(e,Qx),N=o.useMemo(function(){return(c||[]).filter(function(oe){return oe&&ke(oe)==="object"&&"key"in oe})},[c]),P=s==="rtl",_=Xx(v),$=o.useState(!1),D=W($,2),A=D[0],V=D[1];o.useEffect(function(){V(qi())},[]);var U=Ft(function(){var oe;return(oe=N[0])===null||oe===void 0?void 0:oe.key},{value:u,defaultValue:d}),q=W(U,2),K=q[0],H=q[1],j=o.useState(function(){return N.findIndex(function(oe){return oe.key===K})}),z=W(j,2),B=z[0],G=z[1];o.useEffect(function(){var oe=N.findIndex(function(pe){return pe.key===K});if(oe===-1){var ce;oe=Math.max(0,Math.min(B,N.length-1)),H((ce=N[oe])===null||ce===void 0?void 0:ce.key)}G(oe)},[N.map(function(oe){return oe.key}).join("_"),K,B]);var Q=Ft(null,{value:n}),J=W(Q,2),Z=J[0],ne=J[1];o.useEffect(function(){n||(ne("rc-tabs-".concat(lv)),lv+=1)},[]);function de(oe,ce){E==null||E(oe,ce);var pe=oe!==K;H(oe),pe&&(O==null||O(oe))}var X={id:Z,activeKey:K,animated:_,tabPosition:p,rtl:P,mobile:A},ae,te=L(L({},X),{},{editable:f,locale:C,moreIcon:b,moreTransitionName:x,tabBarGutter:g,onTabClick:de,onTabScroll:k,extra:y,style:h,panes:null,getPopupContainer:I,popupClassName:M});return o.createElement(Oo.Provider,{value:{tabs:N,prefixCls:i}},o.createElement("div",F({ref:t,id:n,className:Y(i,"".concat(i,"-").concat(p),(r={},T(r,"".concat(i,"-mobile"),A),T(r,"".concat(i,"-editable"),f),T(r,"".concat(i,"-rtl"),P),r),l)},R),ae,o.createElement(Yx,F({},te,{renderTabBar:S})),o.createElement(Dx,F({destroyInactiveTabPane:w},X,{animated:_}))))}var Zx=o.forwardRef(Jx),eS={motionAppear:!1,motionEnter:!0,motionLeave:!0};function tS(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{inkBar:!0,tabPane:!1},r;return t===!1?r={inkBar:!1,tabPane:!1}:t===!0?r={inkBar:!0,tabPane:!0}:r=F({inkBar:!0},ke(t)==="object"?t:{}),r.tabPane&&(r.tabPaneMotion=F(F({},eS),{motionName:sn(e,"switch")})),r}var nS=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);ae.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&(r[a]=e[a]);return r}function mS(e,t){if(e==null)return{};var r=vS(e,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&(!Object.prototype.propertyIsEnumerable.call(e,n)||(r[n]=e[n]))}return r}function uv(e,t){var r=new Set;return e.forEach(function(n){t.has(n)||r.add(n)}),r}function pS(e){var t=e||{},r=t.disabled,n=t.disableCheckbox,a=t.checkable;return!!(r||n)||a===!1}function hS(e,t,r,n){for(var a=new Set(e),i=new Set,l=0;l<=r;l+=1){var c=t.get(l)||new Set;c.forEach(function(f){var v=f.key,m=f.node,p=f.children,g=p===void 0?[]:p;a.has(v)&&!n(m)&&g.filter(function(h){return!n(h.node)}).forEach(function(h){a.add(h.key)})})}for(var s=new Set,u=r;u>=0;u-=1){var d=t.get(u)||new Set;d.forEach(function(f){var v=f.parent,m=f.node;if(!(n(m)||!f.parent||s.has(f.parent.key))){if(n(f.parent.node)){s.add(v.key);return}var p=!0,g=!1;(v.children||[]).filter(function(h){return!n(h.node)}).forEach(function(h){var y=h.key,C=a.has(y);p&&!C&&(p=!1),!g&&(C||i.has(y))&&(g=!0)}),p&&a.add(v.key),g&&i.add(v.key),s.add(v.key)}})}return{checkedKeys:Array.from(a),halfCheckedKeys:Array.from(uv(i,a))}}function gS(e,t,r,n,a){for(var i=new Set(e),l=new Set(t),c=0;c<=n;c+=1){var s=r.get(c)||new Set;s.forEach(function(v){var m=v.key,p=v.node,g=v.children,h=g===void 0?[]:g;!i.has(m)&&!l.has(m)&&!a(p)&&h.filter(function(y){return!a(y.node)}).forEach(function(y){i.delete(y.key)})})}l=new Set;for(var u=new Set,d=n;d>=0;d-=1){var f=r.get(d)||new Set;f.forEach(function(v){var m=v.parent,p=v.node;if(!(a(p)||!v.parent||u.has(v.parent.key))){if(a(v.parent.node)){u.add(m.key);return}var g=!0,h=!1;(m.children||[]).filter(function(y){return!a(y.node)}).forEach(function(y){var C=y.key,b=i.has(C);g&&!b&&(g=!1),!h&&(b||l.has(C))&&(h=!0)}),g||i.delete(m.key),h&&l.add(m.key),u.add(m.key)}})}return{checkedKeys:Array.from(i),halfCheckedKeys:Array.from(uv(l,i))}}function _n(e,t,r,n){var a=[],i;n?i=n:i=pS;var l=new Set(e.filter(function(d){var f=!!r[d];return f||a.push(d),f})),c=new Map,s=0;Object.keys(r).forEach(function(d){var f=r[d],v=f.level,m=c.get(v);m||(m=new Set,c.set(v,m)),m.add(f),s=Math.max(s,v)}),Ot(!a.length,"Tree missing follow keys: ".concat(a.slice(0,100).map(function(d){return"'".concat(d,"'")}).join(", ")));var u;return t===!0?u=hS(l,c,s,i):u=gS(l,t.halfCheckedKeys,c,s,i),u}var Sa=o.createContext(null);function Ea(e){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ea=function(r){return typeof r}:Ea=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Ea(e)}var Bl="__RC_CASCADER_SPLIT__",dv="SHOW_PARENT",fv="SHOW_CHILD";function Yn(e){return e.join(Bl)}function qr(e){return e.map(Yn)}function yS(e){return e.split(Bl)}function CS(e){var t=e||{},r=t.label,n=t.value,a=t.children,i=n||"value";return{label:r||"label",value:i,key:i,children:a||"children"}}function wa(e,t){var r,n;return(r=e.isLeaf)!==null&&r!==void 0?r:!((n=e[t.children])===null||n===void 0?void 0:n.length)}function bS(e){var t=e.parentElement;if(!!t){var r=e.offsetTop-t.offsetTop;r-t.scrollTop<0?t.scrollTo({top:r}):r+e.offsetHeight-t.scrollTop>t.offsetHeight&&t.scrollTo({top:r+e.offsetHeight-t.offsetHeight})}}function vv(e,t,r){var n=new Set(e),a=t();return e.filter(function(i){var l=a[i],c=l?l.parent:null,s=l?l.children:null;return r===fv?!(s&&s.some(function(u){return u.key&&n.has(u.key)})):!(c&&!c.node.disabled&&n.has(c.key))})}function Na(e,t,r){for(var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,a=t,i=[],l=function(u){var d,f,v,m=e[u],p=(d=a)===null||d===void 0?void 0:d.findIndex(function(h){var y=h[r.value];return n?String(y)===String(m):y===m}),g=p!==-1?(f=a)===null||f===void 0?void 0:f[p]:null;i.push({value:(v=g==null?void 0:g[r.value])!==null&&v!==void 0?v:m,index:p,option:g}),a=g==null?void 0:g[r.children]},c=0;c=0&&r.splice(n,1),r}function Dn(e,t){var r=(e||[]).slice();return r.indexOf(t)===-1&&r.push(t),r}function Ul(e){return e.split("-")}function gv(e,t){return"".concat(e,"-").concat(t)}function RS(e){return e&&e.type&&e.type.isTreeNode}function kS(e,t){var r=[],n=t[e];function a(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];i.forEach(function(l){var c=l.key,s=l.children;r.push(c),a(s)})}return a(n.children),r}function OS(e){if(e.parent){var t=Ul(e.pos);return Number(t[t.length-1])===e.parent.children.length-1}return!1}function IS(e){var t=Ul(e.pos);return Number(t[t.length-1])===0}function yv(e,t,r,n,a,i,l,c,s,u){var d,f=e.clientX,v=e.clientY,m=e.target.getBoundingClientRect(),p=m.top,g=m.height,h=(u==="rtl"?-1:1)*(((a==null?void 0:a.x)||0)-f),y=(h-12)/n,C=c[r.props.eventKey];if(v-1.5?i({dragNode:R,dropNode:N,dropPosition:1})?k=1:P=!1:i({dragNode:R,dropNode:N,dropPosition:0})?k=0:i({dragNode:R,dropNode:N,dropPosition:1})?k=1:P=!1:i({dragNode:R,dropNode:N,dropPosition:1})?k=1:P=!1,{dropPosition:k,dropLevelOffset:I,dropTargetKey:C.key,dropTargetPos:C.pos,dragOverNodeKey:E,dropContainerKey:k===0?null:((d=C.parent)===null||d===void 0?void 0:d.key)||null,dropAllowed:P}}function Cv(e,t){if(!!e){var r=t.multiple;return r?e.slice():e.length?[e[0]]:e}}function ql(e){if(!e)return null;var t;if(Array.isArray(e))t={checkedKeys:e,halfCheckedKeys:void 0};else if(ke(e)==="object")t={checkedKeys:e.checked||void 0,halfCheckedKeys:e.halfChecked||void 0};else return Ot(!1,"`checkedKeys` is not an array or an object"),null;return t}function Gl(e,t){var r=new Set;function n(a){if(!r.has(a)){var i=t[a];if(!!i){r.add(a);var l=i.parent,c=i.node;c.disabled||l&&n(l.key)}}}return(e||[]).forEach(function(a){n(a)}),ue(r)}var MS=["children"];function Pa(e,t){return e!=null?e:t}function _o(e){var t=e||{},r=t.title,n=t._title,a=t.key,i=t.children,l=r||"title";return{title:l,_title:n||[l],key:a||"key",children:i||"children"}}function bv(e){function t(r){var n=an(r);return n.map(function(a){if(!RS(a))return Ot(!a,"Tree/TreeNode can only accept TreeNode as children."),null;var i=a.key,l=a.props,c=l.children,s=Fe(l,MS),u=L({key:i},s),d=t(c);return d.length&&(u.children=d),u}).filter(function(a){return a})}return t(e)}function Yl(e,t,r){var n=_o(r),a=n._title,i=n.key,l=n.children,c=new Set(t===!0?[]:t),s=[];function u(d){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return d.map(function(v,m){for(var p=gv(f?f.pos:"0",m),g=Pa(v[i],p),h,y=0;y1&&arguments[1]!==void 0?arguments[1]:{},r=t.initWrapper,n=t.processEntity,a=t.onProcessFinished,i=t.externalGetKey,l=t.childrenPropName,c=t.fieldNames,s=arguments.length>2?arguments[2]:void 0,u=i||s,d={},f={},v={posEntities:d,keyEntities:f};return r&&(v=r(v)||v),TS(e,function(m){var p=m.node,g=m.index,h=m.pos,y=m.key,C=m.parentPos,b=m.level,x=m.nodes,w={node:p,nodes:x,index:g,key:y,pos:h,level:b},S=Pa(y,h);d[h]=w,f[S]=w,w.parent=d[C],w.parent&&(w.parent.children=w.parent.children||[],w.parent.children.push(w)),n&&n(w,v)},{externalGetKey:u,childrenPropName:l,fieldNames:c}),a&&a(v),v}function Ra(e,t){var r=t.expandedKeys,n=t.selectedKeys,a=t.loadedKeys,i=t.loadingKeys,l=t.checkedKeys,c=t.halfCheckedKeys,s=t.dragOverNodeKey,u=t.dropPosition,d=t.keyEntities,f=d[e],v={eventKey:e,expanded:r.indexOf(e)!==-1,selected:n.indexOf(e)!==-1,loaded:a.indexOf(e)!==-1,loading:i.indexOf(e)!==-1,checked:l.indexOf(e)!==-1,halfChecked:c.indexOf(e)!==-1,pos:String(f?f.pos:""),dragOver:s===e&&u===0,dragOverGapTop:s===e&&u===-1,dragOverGapBottom:s===e&&u===1};return v}function Tt(e){var t=e.data,r=e.expanded,n=e.selected,a=e.checked,i=e.loaded,l=e.loading,c=e.halfChecked,s=e.dragOver,u=e.dragOverGapTop,d=e.dragOverGapBottom,f=e.pos,v=e.active,m=e.eventKey,p=L(L({},t),{},{expanded:r,selected:n,checked:a,loaded:i,loading:l,halfChecked:c,dragOver:s,dragOverGapTop:u,dragOverGapBottom:d,pos:f,active:v,key:m});return"props"in p||Object.defineProperty(p,"props",{get:function(){return Ot(!1,"Second param return from event is node data instead of TreeNode instance. Please read value directly instead of reading from `props`."),e}}),p}var _S=function(e,t){var r=o.useRef({options:null,info:null}),n=o.useCallback(function(){return r.current.options!==e&&(r.current.options=e,r.current.info=Do(e,{fieldNames:t,initWrapper:function(i){return Xn(Xn({},i),{},{pathKeyEntities:{}})},processEntity:function(i,l){var c=i.nodes.map(function(s){return s[t.value]}).join(Bl);l.pathKeyEntities[c]=i,i.key=c}})),r.current.info.pathKeyEntities},[t,e]);return n},DS=function(e,t){return o.useCallback(function(r){var n=[],a=[];return r.forEach(function(i){var l=Na(i,e,t);l.every(function(c){return c.option})?a.push(i):n.push(i)}),[a,n]},[e,t])};function xv(e){var t=o.useRef();t.current=e;var r=o.useCallback(function(){return t.current.apply(t,arguments)},[]);return r}function $S(e){return o.useMemo(function(){if(!e)return[!1,{}];var t={matchInputWidth:!0,limit:50};return e&&Ea(e)==="object"&&(t=Xn(Xn({},t),e)),t.limit<=0&&delete t.limit,[!0,t]},[e])}var ka="__rc_cascader_search_mark__",FS=function(t,r,n){var a=n.label;return r.some(function(i){return String(i[a]).toLowerCase().includes(t.toLowerCase())})},AS=function(t,r,n,a){return r.map(function(i){return i[a.label]}).join(" / ")},LS=function(e,t,r,n,a,i){var l=a.filter,c=l===void 0?FS:l,s=a.render,u=s===void 0?AS:s,d=a.limit,f=d===void 0?50:d,v=a.sort;return o.useMemo(function(){var m=[];if(!e)return[];function p(g,h){g.forEach(function(y){if(!(!v&&f>0&&m.length>=f)){var C=[].concat(Cn(h),[y]),b=y[r.children];if((!b||b.length===0||i)&&c(e,C,{label:r.label})){var x;m.push(Xn(Xn({},y),{},(x={},Yt(x,r.label,u(e,C,n,r)),Yt(x,ka,C),x)))}b&&p(y[r.children],C)}})}return p(t,[]),v&&m.sort(function(g,h){return v(g[ka],h[ka],e,r)}),f>0?m.slice(0,f):m},[e,t,r,n,u,i,c,v,f])};function KS(e){var t,r=e.prefixCls,n=e.checked,a=e.halfChecked,i=e.disabled,l=e.onClick,c=o.useContext(Sa),s=c.checkable,u=typeof s!="boolean"?s:null;return o.createElement("span",{className:Y("".concat(r),(t={},Yt(t,"".concat(r,"-checked"),n),Yt(t,"".concat(r,"-indeterminate"),!n&&a),Yt(t,"".concat(r,"-disabled"),i),t)),onClick:l},u)}var Sv="__cascader_fix_label__";function VS(e){var t=e.prefixCls,r=e.multiple,n=e.options,a=e.activeValue,i=e.prevValuePath,l=e.onToggleOpen,c=e.onSelect,s=e.onActive,u=e.checkedSet,d=e.halfCheckedSet,f=e.loadingKeys,v=e.isSelectable,m="".concat(t,"-menu"),p="".concat(t,"-menu-item"),g=o.useContext(Sa),h=g.fieldNames,y=g.changeOnSelect,C=g.expandTrigger,b=g.expandIcon,x=g.loadingIcon,w=g.dropdownMenuColumnStyle,S=C==="hover",O=o.useMemo(function(){return n.map(function(E){var k,I=E.disabled,M=E[ka],R=(k=E[Sv])!==null&&k!==void 0?k:E[h.label],N=E[h.value],P=wa(E,h),_=M?M.map(function(U){return U[h.value]}):[].concat(Cn(i),[N]),$=Yn(_),D=f.includes($),A=u.has($),V=d.has($);return{disabled:I,label:R,value:N,isLeaf:P,isLoading:D,checked:A,halfChecked:V,option:E,fullPath:_,fullPathKey:$}})},[n,u,h,d,f,i]);return o.createElement("ul",{className:m,role:"menu"},O.map(function(E){var k,I=E.disabled,M=E.label,R=E.value,N=E.isLeaf,P=E.isLoading,_=E.checked,$=E.halfChecked,D=E.option,A=E.fullPath,V=E.fullPathKey,U=function(){!I&&(!S||!N)&&s(A)},q=function(){v(D)&&c(A,N)},K;return typeof D.title=="string"?K=D.title:typeof M=="string"&&(K=M),o.createElement("li",{key:V,className:Y(p,(k={},Yt(k,"".concat(p,"-expand"),!N),Yt(k,"".concat(p,"-active"),a===R),Yt(k,"".concat(p,"-disabled"),I),Yt(k,"".concat(p,"-loading"),P),k)),style:w,role:"menuitemcheckbox",title:K,"aria-checked":_,"data-path-key":V,onClick:function(){U(),(!r||N)&&q()},onDoubleClick:function(){y&&l(!1)},onMouseEnter:function(){S&&U()},onMouseDown:function(j){j.preventDefault()}},r&&o.createElement(KS,{prefixCls:"".concat(t,"-checkbox"),checked:_,halfChecked:$,disabled:I,onClick:function(j){j.stopPropagation(),q()}}),o.createElement("div",{className:"".concat(p,"-content")},M),!P&&b&&!N&&o.createElement("div",{className:"".concat(p,"-expand-icon")},b),P&&x&&o.createElement("div",{className:"".concat(p,"-loading-icon")},x))}))}var zS=function(){var e=Za(),t=e.multiple,r=e.open,n=o.useContext(Sa),a=n.values,i=o.useState([]),l=Tn(i,2),c=l[0],s=l[1];return o.useEffect(function(){if(r&&!t){var u=a[0];s(u||[])}},[r]),[c,s]},jS=function(e,t,r,n,a,i){var l=Za(),c=l.direction,s=l.searchValue,u=l.toggleOpen,d=l.open,f=c==="rtl",v=o.useMemo(function(){for(var w=-1,S=t,O=[],E=[],k=n.length,I=function($){var D=S.findIndex(function(A){return A[r.value]===n[$]});if(D===-1)return"break";w=D,O.push(w),E.push(n[$]),S=S[w][r.children]},M=0;M1){var S=p.slice(0,-1);y(S)}else u(!1)},x=function(){var S,O=((S=h[g])===null||S===void 0?void 0:S[r.children])||[],E=O.find(function(I){return!I.disabled});if(E){var k=[].concat(Cn(p),[E[r.value]]);y(k)}};o.useImperativeHandle(e,function(){return{onKeyDown:function(S){var O=S.which;switch(O){case ie.UP:case ie.DOWN:{var E=0;O===ie.UP?E=-1:O===ie.DOWN&&(E=1),E!==0&&C(E);break}case ie.LEFT:{f?x():b();break}case ie.RIGHT:{f?b():x();break}case ie.BACKSPACE:{s||b();break}case ie.ENTER:{if(p.length){var k=h[g],I=(k==null?void 0:k[ka])||[];I.length?i(I.map(function(M){return M[r.value]}),I[I.length-1]):i(p,h[g])}break}case ie.ESC:u(!1),d&&S.stopPropagation()}},onKeyUp:function(){}}})},HS=o.forwardRef(function(e,t){var r,n,a,i,l=Za(),c=l.prefixCls,s=l.multiple,u=l.searchValue,d=l.toggleOpen,f=l.notFoundContent,v=l.direction,m=o.useRef(),p=v==="rtl",g=o.useContext(Sa),h=g.options,y=g.values,C=g.halfValues,b=g.fieldNames,x=g.changeOnSelect,w=g.onSelect,S=g.searchOptions,O=g.dropdownPrefixCls,E=g.loadData,k=g.expandTrigger,I=O||c,M=o.useState([]),R=Tn(M,2),N=R[0],P=R[1],_=function(ae){if(!(!E||u)){var te=Na(ae,h,b),oe=te.map(function(me){var ve=me.option;return ve}),ce=oe[oe.length-1];if(ce&&!wa(ce,b)){var pe=Yn(ae);P(function(me){return[].concat(Cn(me),[pe])}),E(oe)}}};o.useEffect(function(){N.length&&N.forEach(function(X){var ae=yS(X),te=Na(ae,h,b,!0).map(function(ce){var pe=ce.option;return pe}),oe=te[te.length-1];(!oe||oe[b.children]||wa(oe,b))&&P(function(ce){return ce.filter(function(pe){return pe!==X})})})},[h,N,b]);var $=o.useMemo(function(){return new Set(qr(y))},[y]),D=o.useMemo(function(){return new Set(qr(C))},[C]),A=zS(),V=Tn(A,2),U=V[0],q=V[1],K=function(ae){q(ae),_(ae)},H=function(ae){var te=ae.disabled,oe=wa(ae,b);return!te&&(oe||x||s)},j=function(ae,te){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;w(ae),!s&&(te||x&&(k==="hover"||oe))&&d(!1)},z=o.useMemo(function(){return u?S:h},[u,S,h]),B=o.useMemo(function(){for(var X=[{options:z}],ae=z,te=function(me){var ve=U[me],se=ae.find(function(re){return re[b.value]===ve}),ee=se==null?void 0:se[b.children];if(!(ee==null?void 0:ee.length))return"break";ae=ee,X.push({options:ee})},oe=0;oe":R,P=e.loadingIcon,_=e.children,$=e.dropdownMatchSelectWidth,D=$===void 0?!1:$,A=e.showCheckedStrategy,V=A===void 0?dv:A,U=mS(e,BS),q=Bd(r),K=!!f,H=Ft(l,{value:c,postState:Ev}),j=Tn(H,2),z=j[0],B=j[1],G=o.useMemo(function(){return CS(i)},[JSON.stringify(i)]),Q=o.useMemo(function(){return h||[]},[h]),J=_S(Q,G),Z=o.useCallback(function(ot){var Ae=J();return ot.map(function($e){var rt=Ae[$e].nodes;return rt.map(function(tt){return tt[G.value]})})},[J,G]),ne=Ft("",{value:v,postState:function(Ae){return Ae||""}}),de=Tn(ne,2),X=de[0],ae=de[1],te=function(Ae,$e){ae(Ae),$e.source!=="blur"&&m&&m(Ae)},oe=$S(p),ce=Tn(oe,2),pe=ce[0],me=ce[1],ve=LS(X,Q,G,y||a,me,s),se=DS(Q,G),ee=o.useMemo(function(){var ot=se(z),Ae=Tn(ot,2),$e=Ae[0],rt=Ae[1];if(!K||!z.length)return[$e,[],rt];var tt=qr($e),Ze=J(),Me=_n(tt,!0,Ze),Se=Me.checkedKeys,le=Me.halfCheckedKeys;return[Z(Se),Z(le),rt]},[K,z,J,Z,se]),re=Tn(ee,3),ye=re[0],Ne=re[1],Ce=re[2],_e=o.useMemo(function(){var ot=qr(ye),Ae=vv(ot,J,V);return[].concat(Cn(Ce),Cn(Z(Ae)))},[ye,J,Z,Ce,V]),Ee=xS(_e,Q,G,K,d),ge=xv(function(ot){if(B(ot),u){var Ae=Ev(ot),$e=Ae.map(function(Ze){return Na(Ze,Q,G).map(function(Me){return Me.option})}),rt=K?Ae:Ae[0],tt=K?$e:$e[0];u(rt,tt)}}),xe=xv(function(ot){if(ae(""),!K)ge(ot);else{var Ae=Yn(ot),$e=qr(ye),rt=qr(Ne),tt=$e.includes(Ae),Ze=Ce.some(function(vt){return Yn(vt)===Ae}),Me=ye,Se=Ce;if(Ze&&!tt)Se=Ce.filter(function(vt){return Yn(vt)!==Ae});else{var le=tt?$e.filter(function(vt){return vt!==Ae}):[].concat(Cn($e),[Ae]),fe=J(),he;if(tt){var be=_n(le,{checked:!1,halfCheckedKeys:rt},fe);he=be.checkedKeys}else{var Ie=_n(le,!0,fe);he=Ie.checkedKeys}var Qe=vv(he,J,V);Me=Z(Qe)}ge([].concat(Cn(Se),Cn(Me)))}}),De=function(Ae,$e){if($e.type==="clear"){ge([]);return}var rt=$e.values[0].valueCells;xe(rt)},we=x!==void 0?x:b,Oe=S||w,Le=k||E,et=function(Ae){I==null||I(Ae),M==null||M(Ae)},Ke=o.useMemo(function(){return{options:Q,fieldNames:G,values:ye,halfValues:Ne,changeOnSelect:s,onSelect:xe,checkable:f,searchOptions:ve,dropdownPrefixCls:y,loadData:C,expandTrigger:g,expandIcon:N,loadingIcon:P,dropdownMenuColumnStyle:O}},[Q,G,ye,Ne,s,xe,f,ve,y,C,g,N,P,O]),ut=!(X?ve:Q).length,Ye=X&&me.matchInputWidth||ut?{}:{minWidth:"auto"};return o.createElement(Sa.Provider,{value:Ke},o.createElement(jd,To({},U,{ref:t,id:q,prefixCls:a,dropdownMatchSelectWidth:D,dropdownStyle:Ye,displayValues:Ee,onDisplayValuesChange:De,mode:K?"multiple":void 0,searchValue:X,onSearch:te,showSearch:pe,OptionList:HS,emptyOptions:ut,open:we,dropdownClassName:Oe,placement:Le,onDropdownVisibleChange:et,getRawInputElement:function(){return _}})))});Oa.SHOW_PARENT=dv,Oa.SHOW_CHILD=fv;var US=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0&&(a=O().map(function($){return o.createElement(Nv,{prefixCls:M,key:$.value.toString(),disabled:"disabled"in $?$.disabled:f.disabled,value:$.value,checked:y.includes($.value),onChange:$.onChange,className:"".concat(R,"-item"),style:$.style},$.label)}));var P={toggleOption:I,value:y,disabled:f.disabled,name:f.name,registerValue:k,cancelValue:E},_=Y(R,T({},"".concat(R,"-rtl"),p==="rtl"),s);return o.createElement("div",F({className:_,style:u},N,{ref:r}),o.createElement(wv.Provider,{value:P},a))},ZS=o.forwardRef(JS),eE=o.memo(ZS),tE=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0){var k=c[0]/2;E.paddingLeft=k,E.paddingRight=k}if(c&&c[1]>0&&!u){var I=c[1]/2;E.paddingTop=I,E.paddingBottom=I}return C&&(E.flex=aE(C),s===!1&&!E.minWidth&&(E.minWidth=0)),o.createElement("div",F({},x,{style:F(F({},E),b),className:O,ref:t}),y)}),iE=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0?P[0]/-2:void 0,A=P[1]!=null&&P[1]>0?P[1]/-2:void 0;if(D&&($.marginLeft=D,$.marginRight=D),I){var V=W(P,2);$.rowGap=V[1]}else A&&($.marginTop=A,$.marginBottom=A);var U=W(P,2),q=U[0],K=U[1],H=o.useMemo(function(){return{gutter:[q,K],wrap:f,supportFlexGap:I}},[q,K,f,I]);return o.createElement(Pv.Provider,{value:H},o.createElement("div",F({},v,{className:_,style:F(F({},$),c),ref:t}),s))}),Ov=o.createContext(null),Iv=[];function cE(e,t){var r=o.useState(function(){if(!Ut())return null;var p=document.createElement("div");return p}),n=W(r,1),a=n[0],i=o.useRef(!1),l=o.useContext(Ov),c=o.useState(Iv),s=W(c,2),u=s[0],d=s[1],f=l||(i.current?void 0:function(p){d(function(g){var h=[p].concat(ue(g));return h})});function v(){a.parentElement||document.body.appendChild(a),i.current=!0}function m(){var p;(p=a.parentElement)===null||p===void 0||p.removeChild(a),i.current=!1}return jt(function(){return e?l?l(v):v():m(),m},[e]),jt(function(){u.length&&(u.forEach(function(p){return p()}),d(Iv))},[u]),[a,f]}var Ql;function $o(e){if(typeof document=="undefined")return 0;if(e||Ql===void 0){var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var r=document.createElement("div"),n=r.style;n.position="absolute",n.top="0",n.left="0",n.pointerEvents="none",n.visibility="hidden",n.width="200px",n.height="150px",n.overflow="hidden",r.appendChild(t),document.body.appendChild(r);var a=t.offsetWidth;r.style.overflow="scroll";var i=t.offsetWidth;a===i&&(i=r.clientWidth),document.body.removeChild(r),Ql=a-i}return Ql}function Mv(e){var t=e.match(/^(.*)px$/),r=Number(t==null?void 0:t[1]);return Number.isNaN(r)?$o():r}function Tv(e){if(typeof document=="undefined"||!e||!(e instanceof Element))return{width:0,height:0};var t=getComputedStyle(e,"::-webkit-scrollbar"),r=t.width,n=t.height;return{width:Mv(r),height:Mv(n)}}function sE(){return document.body.scrollHeight>(window.innerHeight||document.documentElement.clientHeight)&&window.innerWidth>document.body.offsetWidth}var uE="rc-util-locker-".concat(Date.now()),_v=0;function dE(e){var t=!!e,r=o.useState(function(){return _v+=1,"".concat(uE,"_").concat(_v)}),n=W(r,1),a=n[0];jt(function(){if(t){var i=$o(),l=sE();ti(` +html body { + overflow-y: hidden; + `.concat(l?"width: calc(100% - ".concat(i,"px);"):"",` +}`),a)}else Fc(a);return function(){Fc(a)}},[t,a])}var Dv=!1;function fE(e){return typeof e=="boolean"&&(Dv=e),Dv}var $v=function(t){return t===!1?!1:!Ut()||!t?null:typeof t=="string"?document.querySelector(t):typeof t=="function"?t():t},Fv=o.forwardRef(function(e,t){var r=e.open,n=e.autoLock,a=e.getContainer,i=e.debug,l=e.autoDestroy,c=l===void 0?!0:l,s=e.children,u=o.useState(r),d=W(u,2),f=d[0],v=d[1],m=f||r;o.useEffect(function(){(c||r)&&v(r)},[r,c]);var p=o.useState(function(){return $v(a)}),g=W(p,2),h=g[0],y=g[1];o.useEffect(function(){var R=$v(a);y(R!=null?R:null)});var C=cE(m&&!h),b=W(C,2),x=b[0],w=b[1],S=h!=null?h:x;dE(n&&r&&Ut()&&(S===x||S===document.body));var O=null;if(s&&nr(s)&&t){var E=s;O=E.ref}var k=ui(O,t);if(!m||!Ut()||h===void 0)return null;var I=S===!1||fE(),M=s;return t&&(M=o.cloneElement(s,{ref:k})),o.createElement(Ov.Provider,{value:w},I?M:Vn.createPortal(M,S))}),vE=function(t){var r=t.prefixCls,n=t.className,a=t.style,i=t.children,l=t.containerRef;return o.createElement(o.Fragment,null,o.createElement("div",{className:Y("".concat(r,"-content"),n),style:L({},a),"aria-modal":"true",role:"dialog",ref:l},i))},Av=o.createContext(null);function Lv(e){return typeof e=="string"&&String(Number(e))===e?(Ot(!1,"Invalid value type of `width` or `height` which should be number type instead."),Number(e)):e}var Kv={width:0,height:0,overflow:"hidden",outline:"none",position:"absolute"};function mE(e){var t,r,n,a,i=e.prefixCls,l=e.open,c=e.placement,s=e.inline,u=e.push,d=e.forceRender,f=e.autoFocus,v=e.keyboard,m=e.rootClassName,p=e.rootStyle,g=e.zIndex,h=e.className,y=e.style,C=e.motion,b=e.width,x=e.height,w=e.children,S=e.contentWrapperStyle,O=e.mask,E=e.maskClosable,k=e.maskMotion,I=e.maskClassName,M=e.maskStyle,R=e.afterOpenChange,N=e.onClose,P=o.useRef(),_=o.useRef(),$=o.useRef(),D=function(de){var X=de.keyCode,ae=de.shiftKey;switch(X){case ie.TAB:{if(X===ie.TAB){if(!ae&&document.activeElement===$.current){var te;(te=_.current)===null||te===void 0||te.focus({preventScroll:!0})}else if(ae&&document.activeElement===_.current){var oe;(oe=$.current)===null||oe===void 0||oe.focus({preventScroll:!0})}}break}case ie.ESC:{N&&v&&N(de);break}}};o.useEffect(function(){if(l&&f){var ne;(ne=P.current)===null||ne===void 0||ne.focus({preventScroll:!0})}},[l,f]);var A=o.useState(!1),V=W(A,2),U=V[0],q=V[1],K=o.useContext(Av),H;u===!1?H={distance:0}:u===!0?H={}:H=u||{};var j=(t=(r=(n=H)===null||n===void 0?void 0:n.distance)!==null&&r!==void 0?r:K==null?void 0:K.pushDistance)!==null&&t!==void 0?t:180,z=o.useMemo(function(){return{pushDistance:j,push:function(){q(!0)},pull:function(){q(!1)}}},[j]);o.useEffect(function(){if(l){var ne;K==null||(ne=K.push)===null||ne===void 0||ne.call(K)}else{var de;K==null||(de=K.pull)===null||de===void 0||de.call(K)}},[l]),o.useEffect(function(){return function(){var ne;K==null||(ne=K.pull)===null||ne===void 0||ne.call(K)}},[]);var B=O&&o.createElement(Zt,F({key:"mask"},k,{visible:l}),function(ne,de){var X=ne.className,ae=ne.style;return o.createElement("div",{className:Y("".concat(i,"-mask"),X,I),style:L(L({},ae),M),onClick:E?N:void 0,ref:de})}),G=typeof C=="function"?C(c):C,Q={};if(U&&j)switch(c){case"top":Q.transform="translateY(".concat(j,"px)");break;case"bottom":Q.transform="translateY(".concat(-j,"px)");break;case"left":Q.transform="translateX(".concat(j,"px)");break;default:Q.transform="translateX(".concat(-j,"px)");break}c==="left"||c==="right"?Q.width=Lv(b):Q.height=Lv(x);var J=o.createElement(Zt,F({key:"panel"},G,{visible:l,forceRender:d,onVisibleChanged:function(de){R==null||R(de)},removeOnLeave:!1,leavedClassName:"".concat(i,"-content-wrapper-hidden")}),function(ne,de){var X=ne.className,ae=ne.style;return o.createElement("div",{className:Y("".concat(i,"-content-wrapper"),X),style:L(L(L({},Q),ae),S)},o.createElement(vE,{containerRef:de,prefixCls:i,className:h,style:y},w))}),Z=L({},p);return g&&(Z.zIndex=g),o.createElement(Av.Provider,{value:z},o.createElement("div",{className:Y(i,"".concat(i,"-").concat(c),m,(a={},T(a,"".concat(i,"-open"),l),T(a,"".concat(i,"-inline"),s),a)),style:Z,tabIndex:-1,ref:P,onKeyDown:D},B,o.createElement("div",{tabIndex:0,ref:_,style:Kv,"aria-hidden":"true","data-sentinel":"start"}),J,o.createElement("div",{tabIndex:0,ref:$,style:Kv,"aria-hidden":"true","data-sentinel":"end"})))}var Vv=function(t){var r=t.open,n=t.getContainer,a=t.forceRender,i=t.prefixCls,l=t.afterOpenChange,c=t.destroyOnClose,s=t.mask,u=o.useState(!1),d=W(u,2),f=d[0],v=d[1],m=function(h){v(h),l==null||l(h)};if(!a&&!f&&!r&&c)return null;var p=L(L({},t),{},{prefixCls:i,afterOpenChange:m});return o.createElement(Fv,{open:r||a||f,autoDestroy:!1,getContainer:n,autoLock:s&&(r||f)},o.createElement(mE,F({},p,{inline:n===!1})))};Vv.defaultProps={open:!1,prefixCls:"rc-drawer",placement:"right",autoFocus:!0,keyboard:!0,width:378,mask:!0,maskClosable:!0};var pE=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a3&&arguments[3]!==void 0?arguments[3]:0;return{key:typeof e=="string"?e:"".concat(r,"-").concat(n),error:e,errorStatus:t}}function jv(e){var t=e.help,r=e.helpStatus,n=e.errors,a=n===void 0?zv:n,i=e.warnings,l=i===void 0?zv:i,c=e.className,s=e.fieldId,u=e.onVisibleChanged,d=o.useContext(Cl),f=d.prefixCls,v=o.useContext(qe),m=v.getPrefixCls,p="".concat(f,"-item-explain"),g=m(),h=Fo(a),y=Fo(l),C=o.useMemo(function(){return t!=null?[Jl(t,r,"help")]:[].concat(ue(h.map(function(x,w){return Jl(x,"error","error",w)})),ue(y.map(function(x,w){return Jl(x,"warning","warning",w)})))},[t,r,h,y]),b={};return s&&(b.id="".concat(s,"_help")),o.createElement(Zt,{motionDeadline:uo.motionDeadline,motionName:"".concat(g,"-show-help"),visible:!!C.length,onVisibleChanged:u},function(x){var w=x.className,S=x.style;return o.createElement("div",F({},b,{className:Y(p,w,c),style:S,role:"alert"}),o.createElement(bu,F({keys:C},uo,{motionName:"".concat(g,"-show-help-item"),component:!1}),function(O){var E=O.key,k=O.error,I=O.errorStatus,M=O.className,R=O.style;return o.createElement("div",{key:E,className:Y(M,T({},"".concat(p,"-").concat(I),I)),style:R},k)}))})}function Hv(e){return typeof e=="object"&&e!=null&&e.nodeType===1}function Bv(e,t){return(!t||e!=="hidden")&&e!=="visible"&&e!=="clip"}function Zl(e,t){if(e.clientHeightt||i>e&&l=t&&c>=r?i-e-n:l>t&&cr?l-t+a:0}function Wv(e,t){var r=window,n=t.scrollMode,a=t.block,i=t.inline,l=t.boundary,c=t.skipOverflowHiddenElements,s=typeof l=="function"?l:function(Z){return Z!==l};if(!Hv(e))throw new TypeError("Invalid target");for(var u=document.scrollingElement||document.documentElement,d=[],f=e;Hv(f)&&s(f);){if((f=f.parentElement)===u){d.push(f);break}f!=null&&f===document.body&&Zl(f)&&!Zl(document.documentElement)||f!=null&&Zl(f,c)&&d.push(f)}for(var v=r.visualViewport?r.visualViewport.width:innerWidth,m=r.visualViewport?r.visualViewport.height:innerHeight,p=window.scrollX||pageXOffset,g=window.scrollY||pageYOffset,h=e.getBoundingClientRect(),y=h.height,C=h.width,b=h.top,x=h.right,w=h.bottom,S=h.left,O=a==="start"||a==="nearest"?b:a==="end"?w:b+y/2,E=i==="center"?S+C/2:i==="end"?x:S,k=[],I=0;I=0&&S>=0&&w<=m&&x<=v&&b>=_&&w<=D&&S>=A&&x<=$)return k;var V=getComputedStyle(M),U=parseInt(V.borderLeftWidth,10),q=parseInt(V.borderTopWidth,10),K=parseInt(V.borderRightWidth,10),H=parseInt(V.borderBottomWidth,10),j=0,z=0,B="offsetWidth"in M?M.offsetWidth-M.clientWidth-U-K:0,G="offsetHeight"in M?M.offsetHeight-M.clientHeight-q-H:0;if(u===M)j=a==="start"?O:a==="end"?O-m:a==="nearest"?Ao(g,g+m,m,q,H,g+O,g+O+y,y):O-m/2,z=i==="start"?E:i==="center"?E-v/2:i==="end"?E-v:Ao(p,p+v,v,U,K,p+E,p+E+C,C),j=Math.max(0,j+g),z=Math.max(0,z+p);else{j=a==="start"?O-_-q:a==="end"?O-D+H+G:a==="nearest"?Ao(_,D,N,q,H+G,O,O+y,y):O-(_+N/2)+G/2,z=i==="start"?E-A-U:i==="center"?E-(A+P/2)+B/2:i==="end"?E-$+K+B:Ao(A,$,P,U,K+B,E,E+C,C);var Q=M.scrollLeft,J=M.scrollTop;O+=J-(j=Math.max(0,Math.min(J+j,M.scrollHeight-N+G))),E+=Q-(z=Math.max(0,Math.min(Q+z,M.scrollWidth-P+B)))}k.push({el:M,top:j,left:z})}return k}function Uv(e){return e===Object(e)&&Object.keys(e).length!==0}function yE(e,t){t===void 0&&(t="auto");var r="scrollBehavior"in document.body.style;e.forEach(function(n){var a=n.el,i=n.top,l=n.left;a.scroll&&r?a.scroll({top:i,left:l,behavior:t}):(a.scrollTop=i,a.scrollLeft=l)})}function CE(e){return e===!1?{block:"end",inline:"nearest"}:Uv(e)?e:{block:"start",inline:"nearest"}}function bE(e,t){var r=e.isConnected||e.ownerDocument.documentElement.contains(e);if(Uv(t)&&typeof t.behavior=="function")return t.behavior(r?Wv(e,t):[]);if(!!r){var n=CE(t);return yE(Wv(e,n),n.behavior)}}var xE=["parentNode"],SE="form_item";function Ia(e){return e===void 0||e===!1?[]:Array.isArray(e)?e:[e]}function qv(e,t){if(!!e.length){var r=e.join("_");if(t)return"".concat(t,"_").concat(r);var n=xE.includes(r);return n?"".concat(SE,"_").concat(r):r}}function Gv(e){var t=Ia(e);return t.join("_")}function Yv(e){var t=Ri(),r=W(t,1),n=r[0],a=o.useRef({}),i=o.useMemo(function(){return e!=null?e:F(F({},n),{__INTERNAL__:{itemRef:function(c){return function(s){var u=Gv(c);s?a.current[u]=s:delete a.current[u]}}},scrollToField:function(c){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u=Ia(c),d=qv(u,i.__INTERNAL__.name),f=d?document.getElementById(d):null;f&&bE(f,F({scrollMode:"if-needed",block:"nearest"},s))},getFieldInstance:function(c){var s=Gv(c);return a.current[s]}})},[e,n]);return[i]}var EE=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0||z.length>0||e.extra){var pe=[];(e.help||j.length>0)&&pe.push("".concat(X,"_help")),e.extra&&pe.push("".concat(X,"_extra")),ce["aria-describedby"]=pe.join(" ")}j.length>0&&(ce["aria-invalid"]="true"),ae&&(ce["aria-required"]="true"),nr(c)&&(ce.ref=B(de,c));var me=new Set([].concat(ue(Ia(v)),ue(Ia(O))));me.forEach(function(se){ce[se]=function(){for(var ee,re,ye,Ne,Ce,_e=arguments.length,Ee=new Array(_e),ge=0;ge<_e;ge++)Ee[ge]=arguments[ge];(ye=te[se])===null||ye===void 0||(ee=ye).call.apply(ee,[te].concat(Ee)),(Ce=(Ne=c.props)[se])===null||Ce===void 0||(re=Ce).call.apply(re,[Ne].concat(Ee))}});var ve=[ce["aria-required"],ce["aria-invalid"],ce["aria-describedby"]];oe=o.createElement(AE,{value:te[e.valuePropName||"value"],update:c,childProps:ve},Ht(c,ce))}else b&&(i||n)&&!E?oe=c(ne):oe=c}return G(oe,X,ae)})}var Qv=KE;Qv.useStatus=PE;var VE=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0;if(p||g){var H=lm(S),j=ue(H).length,z=ke(g)==="object"?g.formatter({value:H,count:j,maxLength:m}):"".concat(j).concat(K?" / ".concat(m):"");return o.createElement(o.Fragment,null,!!g&&o.createElement("span",{className:Y("".concat(u,"-show-count-suffix"),T({},"".concat(u,"-show-count-has-suffix"),!!p))},z),p)}return null};return o.createElement(JE,F({},b,{prefixCls:u,className:v,inputElement:V(),handleReset:A,value:lm(S),focused:I,triggerFocus:N,suffix:U(),disabled:d}))});function cm(e,t){var r=o.useRef([]),n=function(){r.current.push(setTimeout(function(){var i,l,c,s;((i=e.current)===null||i===void 0?void 0:i.input)&&((l=e.current)===null||l===void 0?void 0:l.input.getAttribute("type"))==="password"&&((c=e.current)===null||c===void 0?void 0:c.input.hasAttribute("value"))&&((s=e.current)===null||s===void 0||s.input.removeAttribute("value"))}))};return o.useEffect(function(){return t&&n(),function(){return r.current.forEach(function(a){a&&clearTimeout(a)})}},[]),n}function tw(e){return!!(e.prefix||e.suffix||e.allowClear)}var nw=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a1&&arguments[1]!==void 0?arguments[1]:!1,r=e.getAttribute("id")||e.getAttribute("data-reactid")||e.getAttribute("name");if(t&&nc[r])return nc[r];var n=window.getComputedStyle(e),a=n.getPropertyValue("box-sizing")||n.getPropertyValue("-moz-box-sizing")||n.getPropertyValue("-webkit-box-sizing"),i=parseFloat(n.getPropertyValue("padding-bottom"))+parseFloat(n.getPropertyValue("padding-top")),l=parseFloat(n.getPropertyValue("border-bottom-width"))+parseFloat(n.getPropertyValue("border-top-width")),c=fw.map(function(u){return"".concat(u,":").concat(n.getPropertyValue(u))}).join(";"),s={sizingStyle:c,paddingSize:i,borderSize:l,boxSizing:a};return t&&r&&(nc[r]=s),s}function mw(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;fn||(fn=document.createElement("textarea"),fn.setAttribute("tab-index","-1"),fn.setAttribute("aria-hidden","true"),document.body.appendChild(fn)),e.getAttribute("wrap")?fn.setAttribute("wrap",e.getAttribute("wrap")):fn.removeAttribute("wrap");var a=vw(e,t),i=a.paddingSize,l=a.borderSize,c=a.boxSizing,s=a.sizingStyle;fn.setAttribute("style","".concat(s,";").concat(dw)),fn.value=e.value||e.placeholder||"";var u=void 0,d=void 0,f,v=fn.scrollHeight;if(c==="border-box"?v+=l:c==="content-box"&&(v-=i),r!==null||n!==null){fn.value=" ";var m=fn.scrollHeight-i;r!==null&&(u=m*r,c==="border-box"&&(u=u+i+l),v=Math.max(u,v)),n!==null&&(d=m*n,c==="border-box"&&(d=d+i+l),f=v>d?"":"hidden",v=Math.min(d,v))}var p={height:v,overflowY:f,resize:"none"};return u&&(p.minHeight=u),d&&(p.maxHeight=d),p}var pw=["prefixCls","onPressEnter","defaultValue","value","autoSize","onResize","className","style","disabled","onChange","onInternalAutoSize"],rc=0,ac=1,oc=2,hw=o.forwardRef(function(e,t){var r=e.prefixCls,n=r===void 0?"rc-textarea":r,a=e.onPressEnter,i=e.defaultValue,l=e.value,c=e.autoSize,s=e.onResize,u=e.className,d=e.style,f=e.disabled,v=e.onChange,m=e.onInternalAutoSize,p=Fe(e,pw),g=Ft(i,{value:l,postState:function(B){return B!=null?B:""}}),h=W(g,2),y=h[0],C=h[1],b=function(B){C(B.target.value),v==null||v(B)},x=o.useRef();o.useImperativeHandle(t,function(){return{textArea:x.current}});var w=o.useMemo(function(){return c&&ke(c)==="object"?[c.minRows,c.maxRows]:[]},[c]),S=W(w,2),O=S[0],E=S[1],k=!!c,I=function(){try{if(document.activeElement===x.current){var B=x.current,G=B.selectionStart,Q=B.selectionEnd,J=B.scrollTop;x.current.setSelectionRange(G,Q),x.current.scrollTop=J}}catch(Z){}},M=o.useState(oc),R=W(M,2),N=R[0],P=R[1],_=o.useState(),$=W(_,2),D=$[0],A=$[1],V=function(){P(rc)};jt(function(){k&&V()},[l,O,E,k]),jt(function(){if(N===rc)P(ac);else if(N===ac){var z=mw(x.current,!1,O,E);P(oc),A(z)}else I()},[N]);var U=o.useRef(),q=function(){nt.cancel(U.current)},K=function(B){N===oc&&(s==null||s(B),c&&(q(),U.current=nt(function(){V()})))};o.useEffect(function(){return q},[]);var H=k?D:null,j=L(L({},d),H);return(N===rc||N===ac)&&(j.overflowY="hidden",j.overflowX="hidden"),o.createElement(pn,{onResize:K,disabled:!(c||s)},o.createElement("textarea",F({},p,{ref:x,style:j,className:Y(n,u,T({},"".concat(n,"-disabled"),f)),disabled:f,value:y,onChange:b})))}),gw=function(e){_t(r,e);var t=Dt(r);function r(n){var a;Pt(this,r),a=t.call(this,n),a.resizableTextArea=void 0,a.focus=function(){a.resizableTextArea.textArea.focus()},a.saveTextArea=function(l){a.resizableTextArea=l},a.handleChange=function(l){var c=a.props.onChange;a.setValue(l.target.value),c&&c(l)},a.handleKeyDown=function(l){var c=a.props,s=c.onPressEnter,u=c.onKeyDown;l.keyCode===13&&s&&s(l),u&&u(l)};var i=typeof n.value=="undefined"||n.value===null?n.defaultValue:n.value;return a.state={value:i},a}return Rt(r,[{key:"setValue",value:function(a,i){"value"in this.props||this.setState({value:a},i)}},{key:"blur",value:function(){this.resizableTextArea.textArea.blur()}},{key:"render",value:function(){return o.createElement(hw,F({},this.props,{value:this.state.value,onKeyDown:this.handleKeyDown,onChange:this.handleChange,ref:this.saveTextArea}))}}],[{key:"getDerivedStateFromProps",value:function(a){return"value"in a?{value:a.value}:null}}]),r}(o.Component),yw=Wt("text","input");function Cw(e){return!!(e.addonBefore||e.addonAfter)}var bw=function(e){_t(r,e);var t=Dt(r);function r(){return Pt(this,r),t.apply(this,arguments)}return Rt(r,[{key:"renderClearIcon",value:function(a){var i,l=this.props,c=l.value,s=l.disabled,u=l.readOnly,d=l.handleReset,f=l.suffix,v=!s&&!u&&c,m="".concat(a,"-clear-icon");return o.createElement(Sr,{onClick:d,onMouseDown:function(g){return g.preventDefault()},className:Y((i={},T(i,"".concat(m,"-hidden"),!v),T(i,"".concat(m,"-has-suffix"),!!f),i),m),role:"button"})}},{key:"renderTextAreaWithClearIcon",value:function(a,i,l){var c,s=this.props,u=s.value,d=s.allowClear,f=s.className,v=s.style,m=s.direction,p=s.bordered,g=s.hidden,h=s.status,y=l.status,C=l.hasFeedback;if(!d)return Ht(i,{value:u});var b=Y("".concat(a,"-affix-wrapper"),"".concat(a,"-affix-wrapper-textarea-with-clear-btn"),Un("".concat(a,"-affix-wrapper"),pa(y,h),C),(c={},T(c,"".concat(a,"-affix-wrapper-rtl"),m==="rtl"),T(c,"".concat(a,"-affix-wrapper-borderless"),!p),T(c,"".concat(f),!Cw(this.props)&&f),c));return o.createElement("span",{className:b,style:v,hidden:g},Ht(i,{style:null,value:u}),this.renderClearIcon(a))}},{key:"render",value:function(){var a=this;return o.createElement(tn.Consumer,null,function(i){var l=a.props,c=l.prefixCls,s=l.inputType,u=l.element;if(s===yw[0])return a.renderTextAreaWithClearIcon(c,u,i)})}}]),r}(o.Component),xw=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);an&&(a=t),a}var Sw=o.forwardRef(function(e,t){var r,n=e.prefixCls,a=e.bordered,i=a===void 0?!0:a,l=e.showCount,c=l===void 0?!1:l,s=e.maxLength,u=e.className,d=e.style,f=e.size,v=e.disabled,m=e.onCompositionStart,p=e.onCompositionEnd,g=e.onChange,h=e.status,y=xw(e,["prefixCls","bordered","showCount","maxLength","className","style","size","disabled","onCompositionStart","onCompositionEnd","onChange","status"]),C=o.useContext(qe),b=C.getPrefixCls,x=C.direction,w=o.useContext(en),S=o.useContext(hn),O=v!=null?v:S,E=o.useContext(tn),k=E.status,I=E.hasFeedback,M=E.isFormItemInput,R=E.feedbackIcon,N=pa(k,h),P=o.useRef(null),_=o.useRef(null),$=o.useState(!1),D=W($,2),A=D[0],V=D[1],U=o.useRef(),q=o.useRef(0),K=Ft(y.defaultValue,{value:y.value}),H=W(K,2),j=H[0],z=H[1],B=y.hidden,G=function(se,ee){y.value===void 0&&(z(se),ee==null||ee())},Q=Number(s)>0,J=function(se){V(!0),U.current=j,q.current=se.currentTarget.selectionStart,m==null||m(se)},Z=function(se){var ee;V(!1);var re=se.currentTarget.value;if(Q){var ye=q.current>=s+1||q.current===((ee=U.current)===null||ee===void 0?void 0:ee.length);re=um(ye,U.current,re,s)}re!==j&&(G(re),ec(se.currentTarget,se,g,re)),p==null||p(se)},ne=function(se){var ee=se.target.value;if(!A&&Q){var re=se.target.selectionStart>=s+1||se.target.selectionStart===ee.length||!se.target.selectionStart;ee=um(re,j,ee,s)}G(ee),ec(se.currentTarget,se,g,ee)},de=function(se){var ee,re,ye;G(""),(ee=P.current)===null||ee===void 0||ee.focus(),ec((ye=(re=P.current)===null||re===void 0?void 0:re.resizableTextArea)===null||ye===void 0?void 0:ye.textArea,se,g)},X=b("input",n);o.useImperativeHandle(t,function(){var ve;return{resizableTextArea:(ve=P.current)===null||ve===void 0?void 0:ve.resizableTextArea,focus:function(ee){var re,ye;aw((ye=(re=P.current)===null||re===void 0?void 0:re.resizableTextArea)===null||ye===void 0?void 0:ye.textArea,ee)},blur:function(){var ee;return(ee=P.current)===null||ee===void 0?void 0:ee.blur()}}});var ae=o.createElement(gw,F({},zt(y,["allowClear"]),{disabled:O,className:Y((r={},T(r,"".concat(X,"-borderless"),!i),T(r,u,u&&!c),T(r,"".concat(X,"-sm"),w==="small"||f==="small"),T(r,"".concat(X,"-lg"),w==="large"||f==="large"),r),Un(X,N)),style:c?{resize:d==null?void 0:d.resize}:d,prefixCls:X,onCompositionStart:J,onChange:ne,onCompositionEnd:Z,ref:P})),te=rw(j);!A&&Q&&(y.value===null||y.value===void 0)&&(te=sm(te,s));var oe=o.createElement(bw,F({disabled:O},y,{prefixCls:X,direction:x,inputType:"text",value:te,element:ae,handleReset:de,ref:_,bordered:i,status:h,style:c?void 0:d}));if(c||I){var ce,pe=ue(te).length,me="";return ke(c)==="object"?me=c.formatter({value:te,count:pe,maxLength:s}):me="".concat(pe).concat(Q?" / ".concat(s):""),o.createElement("div",{hidden:B,className:Y("".concat(X,"-textarea"),(ce={},T(ce,"".concat(X,"-textarea-rtl"),x==="rtl"),T(ce,"".concat(X,"-textarea-show-count"),c),T(ce,"".concat(X,"-textarea-in-form-item"),M),ce),Un("".concat(X,"-textarea"),N,I),u),style:d,"data-count":me},oe,I&&o.createElement("span",{className:"".concat(X,"-textarea-suffix")},R))}return oe}),Yr=tc;Yr.Group=XE,Yr.Search=uw,Yr.TextArea=Sw,Yr.Password=cw;var Ma=function(t){var r,n="".concat(t.rootPrefixCls,"-item"),a=Y(n,"".concat(n,"-").concat(t.page),(r={},T(r,"".concat(n,"-active"),t.active),T(r,"".concat(n,"-disabled"),!t.page),T(r,t.className,!!t.className),r)),i=function(){t.onClick(t.page)},l=function(s){t.onKeyPress(s,t.onClick,t.page)};return o.createElement("li",{title:t.showTitle?t.page:null,className:a,onClick:i,onKeyPress:l,tabIndex:"0"},t.itemRender(t.page,"page",o.createElement("a",{rel:"nofollow"},t.page)))},fr={ZERO:48,NINE:57,NUMPAD_ZERO:96,NUMPAD_NINE:105,BACKSPACE:8,DELETE:46,ENTER:13,ARROW_UP:38,ARROW_DOWN:40},dm=function(e){_t(r,e);var t=Dt(r);function r(){var n;Pt(this,r);for(var a=arguments.length,i=new Array(a),l=0;l=0||c.relatedTarget.className.indexOf("".concat(f,"-item"))>=0))&&d(n.getValidValue()))},n.go=function(c){var s=n.state.goInputText;s!==""&&(c.keyCode===fr.ENTER||c.type==="click")&&(n.setState({goInputText:""}),n.props.quickGo(n.getValidValue()))},n}return Rt(r,[{key:"getValidValue",value:function(){var a=this.state.goInputText;return!a||isNaN(a)?void 0:Number(a)}},{key:"getPageSizeOptions",value:function(){var a=this.props,i=a.pageSize,l=a.pageSizeOptions;return l.some(function(c){return c.toString()===i.toString()})?l:l.concat([i.toString()]).sort(function(c,s){var u=isNaN(Number(c))?0:Number(c),d=isNaN(Number(s))?0:Number(s);return u-d})}},{key:"render",value:function(){var a=this,i=this.props,l=i.pageSize,c=i.locale,s=i.rootPrefixCls,u=i.changeSize,d=i.quickGo,f=i.goButton,v=i.selectComponentClass,m=i.buildOptionText,p=i.selectPrefixCls,g=i.disabled,h=this.state.goInputText,y="".concat(s,"-options"),C=v,b=null,x=null,w=null;if(!u&&!d)return null;var S=this.getPageSizeOptions();if(u&&C){var O=S.map(function(E,k){return o.createElement(C.Option,{key:k,value:E.toString()},(m||a.buildOptionText)(E))});b=o.createElement(C,{disabled:g,prefixCls:p,showSearch:!1,className:"".concat(y,"-size-changer"),optionLabelProp:"children",dropdownMatchSelectWidth:!1,value:(l||S[0]).toString(),onChange:this.changeSize,getPopupContainer:function(k){return k.parentNode},"aria-label":c.page_size,defaultOpen:!1},O)}return d&&(f&&(w=typeof f=="boolean"?o.createElement("button",{type:"button",onClick:this.go,onKeyUp:this.go,disabled:g,className:"".concat(y,"-quick-jumper-button")},c.jump_to_confirm):o.createElement("span",{onClick:this.go,onKeyUp:this.go},f)),x=o.createElement("div",{className:"".concat(y,"-quick-jumper")},c.jump_to,o.createElement("input",{disabled:g,type:"text",value:h,onChange:this.handleChange,onKeyUp:this.go,onBlur:this.handleBlur,"aria-label":c.page}),c.page,w)),o.createElement("li",{className:"".concat(y)},b,x)}}]),r}(o.Component);dm.defaultProps={pageSizeOptions:["10","20","50","100"]};var Ew={items_per_page:"\u6761/\u9875",jump_to:"\u8DF3\u81F3",jump_to_confirm:"\u786E\u5B9A",page:"\u9875",prev_page:"\u4E0A\u4E00\u9875",next_page:"\u4E0B\u4E00\u9875",prev_5:"\u5411\u524D 5 \u9875",next_5:"\u5411\u540E 5 \u9875",prev_3:"\u5411\u524D 3 \u9875",next_3:"\u5411\u540E 3 \u9875",page_size:"\u9875\u7801"};function ic(){}function fm(e){var t=Number(e);return typeof t=="number"&&!isNaN(t)&&isFinite(t)&&Math.floor(t)===t}function ww(e,t,r){return r}function Qn(e,t,r){var n=typeof e=="undefined"?t.pageSize:e;return Math.floor((r.total-1)/n)+1}var vm=function(e){_t(r,e);var t=Dt(r);function r(n){var a;Pt(this,r),a=t.call(this,n),a.getJumpPrevPage=function(){return Math.max(1,a.state.current-(a.props.showLessItems?3:5))},a.getJumpNextPage=function(){return Math.min(Qn(void 0,a.state,a.props),a.state.current+(a.props.showLessItems?3:5))},a.getItemIcon=function(u,d){var f=a.props.prefixCls,v=u||o.createElement("button",{type:"button","aria-label":d,className:"".concat(f,"-item-link")});return typeof u=="function"&&(v=o.createElement(u,L({},a.props))),v},a.savePaginationNode=function(u){a.paginationNode=u},a.isValid=function(u){var d=a.props.total;return fm(u)&&u!==a.state.current&&fm(d)&&d>0},a.shouldDisplayQuickJumper=function(){var u=a.props,d=u.showQuickJumper,f=u.total,v=a.state.pageSize;return f<=v?!1:d},a.handleKeyDown=function(u){(u.keyCode===fr.ARROW_UP||u.keyCode===fr.ARROW_DOWN)&&u.preventDefault()},a.handleKeyUp=function(u){var d=a.getValidValue(u),f=a.state.currentInputValue;d!==f&&a.setState({currentInputValue:d}),u.keyCode===fr.ENTER?a.handleChange(d):u.keyCode===fr.ARROW_UP?a.handleChange(d-1):u.keyCode===fr.ARROW_DOWN&&a.handleChange(d+1)},a.handleBlur=function(u){var d=a.getValidValue(u);a.handleChange(d)},a.changePageSize=function(u){var d=a.state.current,f=Qn(u,a.state,a.props);d=d>f?f:d,f===0&&(d=a.state.current),typeof u=="number"&&("pageSize"in a.props||a.setState({pageSize:u}),"current"in a.props||a.setState({current:d,currentInputValue:d})),a.props.onShowSizeChange(d,u),"onChange"in a.props&&a.props.onChange&&a.props.onChange(d,u)},a.handleChange=function(u){var d=a.props,f=d.disabled,v=d.onChange,m=a.state,p=m.pageSize,g=m.current,h=m.currentInputValue;if(a.isValid(u)&&!f){var y=Qn(void 0,a.state,a.props),C=u;return u>y?C=y:u<1&&(C=1),"current"in a.props||a.setState({current:C}),C!==h&&a.setState({currentInputValue:C}),v(C,p),C}return g},a.prev=function(){a.hasPrev()&&a.handleChange(a.state.current-1)},a.next=function(){a.hasNext()&&a.handleChange(a.state.current+1)},a.jumpPrev=function(){a.handleChange(a.getJumpPrevPage())},a.jumpNext=function(){a.handleChange(a.getJumpNextPage())},a.hasPrev=function(){return a.state.current>1},a.hasNext=function(){return a.state.current2?f-2:0),m=2;m=l?s=l:s=Number(i),s}},{key:"getShowSizeChanger",value:function(){var a=this.props,i=a.showSizeChanger,l=a.total,c=a.totalBoundaryShowSizeChanger;return typeof i!="undefined"?i:l>c}},{key:"renderPrev",value:function(a){var i=this.props,l=i.prevIcon,c=i.itemRender,s=c(a,"prev",this.getItemIcon(l,"prev page")),u=!this.hasPrev();return o.isValidElement(s)?o.cloneElement(s,{disabled:u}):s}},{key:"renderNext",value:function(a){var i=this.props,l=i.nextIcon,c=i.itemRender,s=c(a,"next",this.getItemIcon(l,"next page")),u=!this.hasNext();return o.isValidElement(s)?o.cloneElement(s,{disabled:u}):s}},{key:"render",value:function(){var a=this,i=this.props,l=i.prefixCls,c=i.className,s=i.style,u=i.disabled,d=i.hideOnSinglePage,f=i.total,v=i.locale,m=i.showQuickJumper,p=i.showLessItems,g=i.showTitle,h=i.showTotal,y=i.simple,C=i.itemRender,b=i.showPrevNextJumpers,x=i.jumpPrevIcon,w=i.jumpNextIcon,S=i.selectComponentClass,O=i.selectPrefixCls,E=i.pageSizeOptions,k=this.state,I=k.current,M=k.pageSize,R=k.currentInputValue;if(d===!0&&f<=M)return null;var N=Qn(void 0,this.state,this.props),P=[],_=null,$=null,D=null,A=null,V=null,U=m&&m.goButton,q=p?1:2,K=I-1>0?I-1:0,H=I+1f?f:I*M]));if(y)return U&&(typeof U=="boolean"?V=o.createElement("button",{type:"button",onClick:this.handleGoTO,onKeyUp:this.handleGoTO},v.jump_to_confirm):V=o.createElement("span",{onClick:this.handleGoTO,onKeyUp:this.handleGoTO},U),V=o.createElement("li",{title:g?"".concat(v.jump_to).concat(I,"/").concat(N):null,className:"".concat(l,"-simple-pager")},V)),o.createElement("ul",F({className:Y(l,"".concat(l,"-simple"),T({},"".concat(l,"-disabled"),u),c),style:s,ref:this.savePaginationNode},j),z,o.createElement("li",{title:g?v.prev_page:null,onClick:this.prev,tabIndex:this.hasPrev()?0:null,onKeyPress:this.runIfEnterPrev,className:Y("".concat(l,"-prev"),T({},"".concat(l,"-disabled"),!this.hasPrev())),"aria-disabled":!this.hasPrev()},this.renderPrev(K)),o.createElement("li",{title:g?"".concat(I,"/").concat(N):null,className:"".concat(l,"-simple-pager")},o.createElement("input",{type:"text",value:R,disabled:u,onKeyDown:this.handleKeyDown,onKeyUp:this.handleKeyUp,onChange:this.handleKeyUp,onBlur:this.handleBlur,size:"3"}),o.createElement("span",{className:"".concat(l,"-slash")},"/"),N),o.createElement("li",{title:g?v.next_page:null,onClick:this.next,tabIndex:this.hasPrev()?0:null,onKeyPress:this.runIfEnterNext,className:Y("".concat(l,"-next"),T({},"".concat(l,"-disabled"),!this.hasNext())),"aria-disabled":!this.hasNext()},this.renderNext(H)),V);if(N<=3+q*2){var B={locale:v,rootPrefixCls:l,onClick:this.handleChange,onKeyPress:this.runIfEnter,showTitle:g,itemRender:C};N||P.push(o.createElement(Ma,F({},B,{key:"noPager",page:1,className:"".concat(l,"-item-disabled")})));for(var G=1;G<=N;G+=1){var Q=I===G;P.push(o.createElement(Ma,F({},B,{key:G,page:G,active:Q})))}}else{var J=p?v.prev_3:v.prev_5,Z=p?v.next_3:v.next_5;b&&(_=o.createElement("li",{title:g?J:null,key:"prev",onClick:this.jumpPrev,tabIndex:"0",onKeyPress:this.runIfEnterJumpPrev,className:Y("".concat(l,"-jump-prev"),T({},"".concat(l,"-jump-prev-custom-icon"),!!x))},C(this.getJumpPrevPage(),"jump-prev",this.getItemIcon(x,"prev page"))),$=o.createElement("li",{title:g?Z:null,key:"next",tabIndex:"0",onClick:this.jumpNext,onKeyPress:this.runIfEnterJumpNext,className:Y("".concat(l,"-jump-next"),T({},"".concat(l,"-jump-next-custom-icon"),!!w))},C(this.getJumpNextPage(),"jump-next",this.getItemIcon(w,"next page")))),A=o.createElement(Ma,{locale:v,last:!0,rootPrefixCls:l,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:N,page:N,active:!1,showTitle:g,itemRender:C}),D=o.createElement(Ma,{locale:v,rootPrefixCls:l,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:1,page:1,active:!1,showTitle:g,itemRender:C});var ne=Math.max(1,I-q),de=Math.min(I+q,N);I-1<=q&&(de=1+q*2),N-I<=q&&(ne=N-q*2);for(var X=ne;X<=de;X+=1){var ae=I===X;P.push(o.createElement(Ma,{locale:v,rootPrefixCls:l,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:X,page:X,active:ae,showTitle:g,itemRender:C}))}I-1>=q*2&&I!==1+2&&(P[0]=o.cloneElement(P[0],{className:"".concat(l,"-item-after-jump-prev")}),P.unshift(_)),N-I>=q*2&&I!==N-2&&(P[P.length-1]=o.cloneElement(P[P.length-1],{className:"".concat(l,"-item-before-jump-next")}),P.push($)),ne!==1&&P.unshift(D),de!==N&&P.push(A)}var te=!this.hasPrev()||!N,oe=!this.hasNext()||!N;return o.createElement("ul",F({className:Y(l,c,T({},"".concat(l,"-disabled"),u)),style:s,ref:this.savePaginationNode},j),z,o.createElement("li",{title:g?v.prev_page:null,onClick:this.prev,tabIndex:te?null:0,onKeyPress:this.runIfEnterPrev,className:Y("".concat(l,"-prev"),T({},"".concat(l,"-disabled"),te)),"aria-disabled":te},this.renderPrev(K)),P,o.createElement("li",{title:g?v.next_page:null,onClick:this.next,tabIndex:oe?null:0,onKeyPress:this.runIfEnterNext,className:Y("".concat(l,"-next"),T({},"".concat(l,"-disabled"),oe)),"aria-disabled":oe},this.renderNext(H)),o.createElement(dm,{disabled:u,locale:v,rootPrefixCls:l,selectComponentClass:S,selectPrefixCls:O,changeSize:this.getShowSizeChanger()?this.changePageSize:null,current:I,pageSize:M,pageSizeOptions:E,quickGo:this.shouldDisplayQuickJumper()?this.handleChange:null,goButton:U}))}}],[{key:"getDerivedStateFromProps",value:function(a,i){var l={};if("current"in a&&(l.current=a.current,a.current!==i.current&&(l.currentInputValue=l.current)),"pageSize"in a&&a.pageSize!==i.pageSize){var c=i.current,s=Qn(a.pageSize,i,a);c=c>s?s:c,"current"in a||(l.current=c,l.currentInputValue=c),l.pageSize=a.pageSize}return l}}]),r}(o.Component);vm.defaultProps={defaultCurrent:1,total:0,defaultPageSize:10,onChange:ic,className:"",selectPrefixCls:"rc-select",prefixCls:"rc-pagination",selectComponentClass:null,hideOnSinglePage:!1,showPrevNextJumpers:!0,showQuickJumper:!1,showLessItems:!1,showTitle:!0,onShowSizeChange:ic,locale:Ew,style:{},itemRender:ww,totalBoundaryShowSizeChanger:50};var mm=function(t){return o.createElement(qn,F({},t,{size:"small"}))},pm=function(t){return o.createElement(qn,F({},t,{size:"middle"}))};mm.Option=qn.Option,pm.Option=qn.Option;var Nw=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a10&&arguments[10]!==void 0?arguments[10]:0,v=n/100*360*((360-l)/360),m=l===0?0:{bottom:0,top:180,left:90,right:-90}[c],p=(100-a)/100*r;return u==="round"&&a!==100&&(p+=d/2,p>=r&&(p=r-.01)),{stroke:typeof s=="string"?s:void 0,strokeDasharray:"".concat(r,"px ").concat(t),strokeDashoffset:p+f,transform:"rotate(".concat(i+v+m,"deg)"),transformOrigin:"0 0",transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s, opacity .3s ease 0s",fillOpacity:0}},sc=function(t){var r=t.id,n=t.prefixCls,a=t.steps,i=t.strokeWidth,l=t.trailWidth,c=t.gapDegree,s=c===void 0?0:c,u=t.gapPosition,d=t.trailColor,f=t.strokeLinecap,v=t.style,m=t.className,p=t.strokeColor,g=t.percent,h=Fe(t,Uw),y=Ww(r),C="".concat(y,"-gradient"),b=_a/2-i/2,x=Math.PI*2*b,w=s>0?90+s/2:-90,S=x*((360-s)/360),O=ke(a)==="object"?a:{count:a,space:2},E=O.count,k=O.space,I=cc(x,S,0,100,w,s,u,d,f,i),M=Mm(g),R=Mm(p),N=R.find(function(D){return D&&ke(D)==="object"}),P=jw(),_=function(){var A=0;return M.map(function(V,U){var q=R[U]||R[R.length-1],K=q&&ke(q)==="object"?"url(#".concat(C,")"):void 0,H=cc(x,S,A,V,w,s,u,q,f,i);return A+=V,o.createElement("circle",{key:U,className:"".concat(n,"-circle-path"),r:b,cx:0,cy:0,stroke:K,strokeLinecap:f,strokeWidth:i,opacity:V===0?0:1,style:H,ref:function(z){P[U]=z}})}).reverse()},$=function(){var A=Math.round(E*(M[0]/100)),V=100/E,U=0;return new Array(E).fill(null).map(function(q,K){var H=K<=A-1?R[0]:d,j=H&&ke(H)==="object"?"url(#".concat(C,")"):void 0,z=cc(x,S,U,V,w,s,u,H,"butt",i,k);return U+=(S-z.strokeDashoffset+k)*100/S,o.createElement("circle",{key:K,className:"".concat(n,"-circle-path"),r:b,cx:0,cy:0,stroke:j,strokeWidth:i,opacity:1,style:z,ref:function(G){P[K]=G}})})};return o.createElement("svg",F({className:Y("".concat(n,"-circle"),m),viewBox:"".concat(-_a/2," ").concat(-_a/2," ").concat(_a," ").concat(_a),style:v,id:r,role:"presentation"},h),N&&o.createElement("defs",null,o.createElement("linearGradient",{id:C,x1:"100%",y1:"0%",x2:"0%",y2:"0%"},Object.keys(N).sort(function(D,A){return Im(D)-Im(A)}).map(function(D,A){return o.createElement("stop",{key:A,offset:D,stopColor:N[D]})}))),!E&&o.createElement("circle",{className:"".concat(n,"-circle-trail"),r:b,cx:0,cy:0,stroke:d,strokeLinecap:f,strokeWidth:l||i,style:I}),E?$():_())};sc.defaultProps=zw,sc.displayName="Circle";function vr(e){return!e||e<0?0:e>100?100:e}function Vo(e){var t=e.success,r=e.successPercent,n=r;return t&&"progress"in t&&(n=t.progress),t&&"percent"in t&&(n=t.percent),n}function qw(e){var t=e.percent,r=e.success,n=e.successPercent,a=vr(Vo({success:r,successPercent:n}));return[a,vr(vr(t)-a)]}function Gw(e){var t=e.success,r=t===void 0?{}:t,n=e.strokeColor,a=r.strokeColor;return[a||ni.green,n||null]}var Yw=function(t){var r=t.prefixCls,n=t.width,a=t.strokeWidth,i=t.trailColor,l=i===void 0?null:i,c=t.strokeLinecap,s=c===void 0?"round":c,u=t.gapPosition,d=t.gapDegree,f=t.type,v=t.children,m=t.success,p=n||120,g={width:p,height:p,fontSize:p*.15+6},h=a||6,y=u||f==="dashboard"&&"bottom"||void 0,C=function(){if(d||d===0)return d;if(f==="dashboard")return 75},b=Object.prototype.toString.call(t.strokeColor)==="[object Object]",x=Gw({success:m,strokeColor:t.strokeColor}),w=Y("".concat(r,"-inner"),T({},"".concat(r,"-circle-gradient"),b));return o.createElement("div",{className:w,style:g},o.createElement(sc,{percent:qw(t),strokeWidth:h,trailWidth:h,strokeColor:x,strokeLinecap:s,trailColor:l,prefixCls:r,gapDegree:C(),gapPosition:y}),v)},Xw=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a=100?"success":N||"normal"}function C(N,P){var _=t.format,$=Vo(t);if(!v)return null;var D,A=_||function(U){return"".concat(U,"%")},V=p==="line";return _||P!=="exception"&&P!=="success"?D=A(vr(s),vr($)):P==="exception"?D=V?o.createElement(Sr,null):o.createElement(Er,null):P==="success"&&(D=V?o.createElement(ai,null):o.createElement(qc,null)),o.createElement("span",{className:"".concat(N,"-text"),title:typeof D=="string"?D:void 0},D)}var b=o.useContext(qe),x=b.getPrefixCls,w=b.direction,S=x("progress",n),O=y(),E=C(S,O),k=Array.isArray(l)?l[0]:l,I=typeof l=="string"||Array.isArray(l)?l:void 0,M;p==="line"?M=i?o.createElement(e1,F({},t,{strokeColor:I,prefixCls:S,steps:i}),E):o.createElement(Zw,F({},t,{strokeColor:k,prefixCls:S,direction:w}),E):(p==="circle"||p==="dashboard")&&(M=o.createElement(Yw,F({},t,{strokeColor:k,prefixCls:S,progressStatus:O}),E));var R=Y(S,(r={},T(r,"".concat(S,"-").concat(p==="dashboard"&&"circle"||i&&"steps"||p),!0),T(r,"".concat(S,"-status-").concat(O),!0),T(r,"".concat(S,"-show-info"),v),T(r,"".concat(S,"-").concat(d),d),T(r,"".concat(S,"-rtl"),w==="rtl"),r),a);return o.createElement("div",F({},zt(g,["status","format","trailColor","strokeWidth","width","gapDegree","gapPosition","strokeLinecap","success","successPercent"]),{className:R,role:"progressbar"}),M)},mr=o.createContext({min:0,max:0,direction:"ltr",step:1,includedStart:0,includedEnd:0,tabIndex:0});function uc(e,t,r){return(e-t)/(r-t)}function dc(e,t,r,n){var a=uc(t,r,n),i={};switch(e){case"rtl":i.right="".concat(a*100,"%"),i.transform="translateX(50%)";break;case"btt":i.bottom="".concat(a*100,"%"),i.transform="translateY(50%)";break;case"ttb":i.top="".concat(a*100,"%"),i.transform="translateY(-50%)";break;default:i.left="".concat(a*100,"%"),i.transform="translateX(-50%)";break}return i}function Qr(e,t){return Array.isArray(e)?e[t]:e}var a1=["prefixCls","value","valueIndex","onStartMove","style","render","dragging","onOffsetChange"],o1=o.forwardRef(function(e,t){var r,n,a=e.prefixCls,i=e.value,l=e.valueIndex,c=e.onStartMove,s=e.style,u=e.render,d=e.dragging,f=e.onOffsetChange,v=Fe(e,a1),m=o.useContext(mr),p=m.min,g=m.max,h=m.direction,y=m.disabled,C=m.range,b=m.tabIndex,x=m.ariaLabelForHandle,w=m.ariaLabelledByForHandle,S=m.ariaValueTextFormatterForHandle,O="".concat(a,"-handle"),E=function(N){y||c(N,l)},k=function(N){if(!y){var P=null;switch(N.which||N.keyCode){case ie.LEFT:P=h==="ltr"||h==="btt"?-1:1;break;case ie.RIGHT:P=h==="ltr"||h==="btt"?1:-1;break;case ie.UP:P=h!=="ttb"?1:-1;break;case ie.DOWN:P=h!=="ttb"?-1:1;break;case ie.HOME:P="min";break;case ie.END:P="max";break;case ie.PAGE_UP:P=2;break;case ie.PAGE_DOWN:P=-2;break}P!==null&&(N.preventDefault(),f(P,l))}},I=dc(h,i,p,g),M=o.createElement("div",F({ref:t,className:Y(O,(r={},T(r,"".concat(O,"-").concat(l+1),C),T(r,"".concat(O,"-dragging"),d),r)),style:L(L({},I),s),onMouseDown:E,onTouchStart:E,onKeyDown:k,tabIndex:y?null:Qr(b,l),role:"slider","aria-valuemin":p,"aria-valuemax":g,"aria-valuenow":i,"aria-disabled":y,"aria-label":Qr(x,l),"aria-labelledby":Qr(w,l),"aria-valuetext":(n=Qr(S,l))===null||n===void 0?void 0:n(i)},v));return u&&(M=u(M,{index:l,prefixCls:a,value:i,dragging:d})),M}),i1=["prefixCls","style","onStartMove","onOffsetChange","values","handleRender","draggingIndex"],l1=o.forwardRef(function(e,t){var r=e.prefixCls,n=e.style,a=e.onStartMove,i=e.onOffsetChange,l=e.values,c=e.handleRender,s=e.draggingIndex,u=Fe(e,i1),d=o.useRef({});return o.useImperativeHandle(t,function(){return{focus:function(v){var m;(m=d.current[v])===null||m===void 0||m.focus()}}}),o.createElement(o.Fragment,null,l.map(function(f,v){return o.createElement(o1,F({ref:function(p){p?d.current[v]=p:delete d.current[v]},dragging:s===v,prefixCls:r,style:Qr(n,v),key:v,value:f,valueIndex:v,onStartMove:a,onOffsetChange:i,render:c},u))}))});function Tm(e){var t="touches"in e?e.touches[0]:e;return{pageX:t.pageX,pageY:t.pageY}}function c1(e,t,r,n,a,i,l,c,s){var u=o.useState(null),d=W(u,2),f=d[0],v=d[1],m=o.useState(-1),p=W(m,2),g=p[0],h=p[1],y=o.useState(r),C=W(y,2),b=C[0],x=C[1],w=o.useState(r),S=W(w,2),O=S[0],E=S[1],k=o.useRef(null),I=o.useRef(null);o.useEffect(function(){g===-1&&x(r)},[r,g]),o.useEffect(function(){return function(){document.removeEventListener("mousemove",k.current),document.removeEventListener("mouseup",I.current),document.removeEventListener("touchmove",k.current),document.removeEventListener("touchend",I.current)}},[]);var M=function(D,A){b.some(function(V,U){return V!==D[U]})&&(A!==void 0&&v(A),x(D),l(D))},R=function(D,A){if(D===-1){var V=O[0],U=O[O.length-1],q=n-V,K=a-U,H=A*(a-n);H=Math.max(H,q),H=Math.min(H,K);var j=i(V+H);H=j-V;var z=O.map(function(J){return J+H});M(z)}else{var B=(a-n)*A,G=ue(b);G[D]=O[D];var Q=s(G,B,D,"dist");M(Q.values,Q.value)}},N=o.useRef(R);N.current=R;var P=function(D,A){D.stopPropagation();var V=r[A];h(A),v(V),E(r);var U=Tm(D),q=U.pageX,K=U.pageY,H=function(B){B.preventDefault();var G=Tm(B),Q=G.pageX,J=G.pageY,Z=Q-q,ne=J-K,de=e.current.getBoundingClientRect(),X=de.width,ae=de.height,te;switch(t){case"btt":te=-ne/ae;break;case"ttb":te=ne/ae;break;case"rtl":te=-Z/X;break;default:te=Z/X}N.current(A,te)},j=function z(B){B.preventDefault(),document.removeEventListener("mouseup",z),document.removeEventListener("mousemove",H),document.removeEventListener("touchend",z),document.removeEventListener("touchmove",H),k.current=null,I.current=null,h(-1),c()};document.addEventListener("mouseup",j),document.addEventListener("mousemove",H),document.addEventListener("touchend",j),document.addEventListener("touchmove",H),k.current=H,I.current=j},_=o.useMemo(function(){var $=ue(r).sort(function(A,V){return A-V}),D=ue(b).sort(function(A,V){return A-V});return $.every(function(A,V){return A===D[V]})?b:r},[r,b]);return[g,f,_,P]}function s1(e){var t=e.prefixCls,r=e.style,n=e.start,a=e.end,i=e.index,l=e.onStartMove,c=o.useContext(mr),s=c.direction,u=c.min,d=c.max,f=c.disabled,v=c.range,m="".concat(t,"-track"),p=uc(n,u,d),g=uc(a,u,d),h=function(b){!f&&l&&l(b,-1)},y={};switch(s){case"rtl":y.right="".concat(p*100,"%"),y.width="".concat(g*100-p*100,"%");break;case"btt":y.bottom="".concat(p*100,"%"),y.height="".concat(g*100-p*100,"%");break;case"ttb":y.top="".concat(p*100,"%"),y.height="".concat(g*100-p*100,"%");break;default:y.left="".concat(p*100,"%"),y.width="".concat(g*100-p*100,"%")}return o.createElement("div",{className:Y(m,v&&"".concat(m,"-").concat(i+1)),style:L(L({},y),r),onMouseDown:h,onTouchStart:h})}function u1(e){var t=e.prefixCls,r=e.style,n=e.values,a=e.startPoint,i=e.onStartMove,l=o.useContext(mr),c=l.included,s=l.range,u=l.min,d=o.useMemo(function(){if(!s){if(n.length===0)return[];var f=a!=null?a:u,v=n[0];return[{start:Math.min(f,v),end:Math.max(f,v)}]}for(var m=[],p=0;p3&&arguments[3]!==void 0?arguments[3]:"unit";if(typeof g=="number"){var C,b=p[h],x=b+g,w=[];n.forEach(function(I){w.push(I.value)}),w.push(e,t),w.push(c(b));var S=g>0?1:-1;y==="unit"?w.push(c(b+S*r)):w.push(c(x)),w=w.filter(function(I){return I!==null}).filter(function(I){return g<0?I<=b:I>=b}),y==="unit"&&(w=w.filter(function(I){return I!==b}));var O=y==="unit"?b:x;C=w[0];var E=Math.abs(C-O);if(w.forEach(function(I){var M=Math.abs(I-O);M1){var k=ue(p);return k[h]=C,m(k,g-S,h,y)}return C}else{if(g==="min")return e;if(g==="max")return t}},d=function(p,g,h){var y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unit",C=p[h],b=u(p,g,h,y);return{value:b,changed:b!==C}},f=function(p){return i===null&&p===0||typeof i=="number"&&p3&&arguments[3]!==void 0?arguments[3]:"unit",C=p.map(s),b=C[h],x=u(C,g,h,y);if(C[h]=x,a===!1){var w=i||0;h>0&&C[h-1]!==b&&(C[h]=Math.max(C[h],C[h-1]+w)),h0;k-=1)for(var I=!0;f(C[k]-C[k-1])&&I;){var M=d(C,-1,k-1);C[k-1]=M.value,I=M.changed}for(var R=C.length-1;R>0;R-=1)for(var N=!0;f(C[R]-C[R-1])&&N;){var P=d(C,-1,R-1);C[R-1]=P.value,N=P.changed}for(var _=0;_=0?R:!1},[R,ce]),me=o.useMemo(function(){var at=Object.keys(j||{});return at.map(function(Te){var Re=j[Te],je={value:Number(Te)};return Re&&ke(Re)==="object"&&!o.isValidElement(Re)&&("label"in Re||"style"in Re)?(je.style=Re.style,je.label=Re.label):je.label=Re,je}).filter(function(Te){var Re=Te.label;return Re||typeof Re=="number"}).sort(function(Te,Re){return Te.value-Re.value})},[j]),ve=p1(te,oe,ce,me,I,pe),se=W(ve,2),ee=se[0],re=se[1],ye=Ft(b,{value:C}),Ne=W(ye,2),Ce=Ne[0],_e=Ne[1],Ee=o.useMemo(function(){var at=Ce==null?[]:Array.isArray(Ce)?Ce:[Ce],Te=W(at,1),Re=Te[0],je=Re===void 0?te:Re,He=Ce===null?[]:[je];if(x){if(He=ue(at),w||Ce===void 0){var ht=w>=0?w+1:2;for(He=He.slice(0,ht);He.length=0&&de.current.focus(at)}ut(null)},[Ke]);var ot=o.useMemo(function(){return N&&ce===null?!1:N},[N,ce]),Ae=function(){E==null||E(xe(ge.current))},$e=c1(X,ae,Ee,te,oe,ee,De,Ae,re),rt=W($e,4),tt=rt[0],Ze=rt[1],Me=rt[2],Se=rt[3],le=function(Te,Re){Se(Te,Re),O==null||O(xe(ge.current))},fe=tt!==-1;o.useEffect(function(){if(!fe){var at=Ee.lastIndexOf(Ze);de.current.focus(at)}},[fe]);var he=o.useMemo(function(){return ue(Me).sort(function(at,Te){return at-Te})},[Me]),be=o.useMemo(function(){return x?[he[0],he[he.length-1]]:[te,he[0]]},[he,x,te]),Ie=W(be,2),Qe=Ie[0],vt=Ie[1];o.useImperativeHandle(t,function(){return{focus:function(){de.current.focus(0)},blur:function(){var Te=document,Re=Te.activeElement;X.current.contains(Re)&&(Re==null||Re.blur())}}}),o.useEffect(function(){u&&de.current.focus(0)},[]);var Et=o.useMemo(function(){return{min:te,max:oe,direction:ae,disabled:s,step:ce,included:D,includedStart:Qe,includedEnd:vt,range:x,tabIndex:Q,ariaLabelForHandle:J,ariaLabelledByForHandle:Z,ariaValueTextFormatterForHandle:ne}},[te,oe,ae,s,ce,D,Qe,vt,x,Q,J,Z,ne]);return o.createElement(mr.Provider,{value:Et},o.createElement("div",{ref:X,className:Y(a,i,(r={},T(r,"".concat(a,"-disabled"),s),T(r,"".concat(a,"-vertical"),_),T(r,"".concat(a,"-horizontal"),!_),T(r,"".concat(a,"-with-marks"),me.length),r)),style:l,onMouseDown:Oe},o.createElement("div",{className:"".concat(a,"-rail"),style:q}),o.createElement(u1,{prefixCls:a,style:V,values:he,startPoint:A,onStartMove:ot?le:null}),o.createElement(m1,{prefixCls:a,marks:me,dots:z,style:K,activeStyle:H}),o.createElement(l1,{ref:de,prefixCls:a,style:U,values:Me,draggingIndex:tt,onStartMove:le,onOffsetChange:Ye,onFocus:d,onBlur:f,handleRender:B}),o.createElement(f1,{prefixCls:a,marks:me,onClick:we})))}),g1=o.forwardRef(function(e,t){var r=e.open,n=o.useRef(null),a=o.useRef(null);function i(){nt.cancel(a.current),a.current=null}function l(){a.current=nt(function(){var c;(c=n.current)===null||c===void 0||c.forcePopupAlign(),a.current=null})}return o.useEffect(function(){return r?l():i(),i},[r,e.title]),o.createElement(ga,F({ref:on(n,t)},e))}),y1=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a=r}function R1(e){return e&&ke(e)==="object"&&!Array.isArray(e)&&!o.isValidElement(e)}function k1(e){return typeof e=="string"?!0:nr(e)}var O1=function(t){var r=t.ellipsis,n=t.rowType,a=t.children,i,l=r===!0?{showTitle:!0}:r;return l&&(l.showTitle||n==="header")&&(typeof a=="string"||typeof a=="number"?i=a.toString():o.isValidElement(a)&&typeof a.props.children=="string"&&(i=a.props.children)),i};function I1(e,t){var r,n,a,i=e.prefixCls,l=e.className,c=e.record,s=e.index,u=e.renderIndex,d=e.dataIndex,f=e.render,v=e.children,m=e.component,p=m===void 0?"td":m,g=e.colSpan,h=e.rowSpan,y=e.fixLeft,C=e.fixRight,b=e.firstFixLeft,x=e.lastFixLeft,w=e.firstFixRight,S=e.lastFixRight,O=e.appendNode,E=e.additionalProps,k=E===void 0?{}:E,I=e.ellipsis,M=e.align,R=e.rowType,N=e.isSticky,P=e.hovering,_=e.onHover,$="".concat(i,"-cell"),D=o.useContext(Am),A=o.useContext($m),V=o.useContext(jo),U=V.allColumnsFixedLeft,q=o.useMemo(function(){if(fc(v))return[v];var ee=Dm(c,d),re=ee,ye=void 0;if(f){var Ne=f(ee,c,u);R1(Ne)?(re=Ne.children,ye=Ne.props,D.renderWithProps=!0):re=Ne}return[re,ye]},[D.renderWithProps?Math.random():0,v,d,D,c,f,u]),K=W(q,2),H=K[0],j=K[1],z=H;ke(z)==="object"&&!Array.isArray(z)&&!o.isValidElement(z)&&(z=null),I&&(x||w)&&(z=o.createElement("span",{className:"".concat($,"-content")},z));var B=j||{},G=B.colSpan,Q=B.rowSpan,J=B.style,Z=B.className,ne=Fe(B,N1),de=(r=G!==void 0?G:g)!==null&&r!==void 0?r:1,X=(n=Q!==void 0?Q:h)!==null&&n!==void 0?n:1;if(de===0||X===0)return null;var ae={},te=typeof y=="number"&&A,oe=typeof C=="number"&&A;te&&(ae.position="sticky",ae.left=y),oe&&(ae.position="sticky",ae.right=C);var ce={};M&&(ce.textAlign=M);var pe=function(re){var ye;c&&_(s,s+X-1),k==null||(ye=k.onMouseEnter)===null||ye===void 0||ye.call(k,re)},me=function(re){var ye;c&&_(-1,-1),k==null||(ye=k.onMouseLeave)===null||ye===void 0||ye.call(k,re)},ve=O1({rowType:R,ellipsis:I,children:H}),se=L(L(L({title:ve},ne),k),{},{colSpan:de!==1?de:null,rowSpan:X!==1?X:null,className:Y($,l,(a={},T(a,"".concat($,"-fix-left"),te&&A),T(a,"".concat($,"-fix-left-first"),b&&A),T(a,"".concat($,"-fix-left-last"),x&&A),T(a,"".concat($,"-fix-left-all"),x&&U&&A),T(a,"".concat($,"-fix-right"),oe&&A),T(a,"".concat($,"-fix-right-first"),w&&A),T(a,"".concat($,"-fix-right-last"),S&&A),T(a,"".concat($,"-ellipsis"),I),T(a,"".concat($,"-with-append"),O),T(a,"".concat($,"-fix-sticky"),(te||oe)&&N&&A),T(a,"".concat($,"-row-hover"),!j&&P),a),k.className,Z),style:L(L(L(L({},k.style),ce),ae),J),onMouseEnter:pe,onMouseLeave:me,ref:k1(p)?t:null});return o.createElement(p,se,O,z)}var Lm=o.forwardRef(I1);Lm.displayName="Cell";var M1=["expanded","className","hovering"],T1=o.memo(Lm,function(e,t){return t.shouldCellUpdate?M1.every(function(r){return e[r]===t[r]})&&!t.shouldCellUpdate(t.record,e.record):xr(e,t)}),Da=o.forwardRef(function(e,t){var r=e.index,n=e.additionalProps,a=n===void 0?{}:n,i=e.colSpan,l=e.rowSpan,c=a.colSpan,s=a.rowSpan,u=i!=null?i:c,d=l!=null?l:s,f=w1(Fm,function(p){var g=P1(r,d||1,p==null?void 0:p.startRow,p==null?void 0:p.endRow);return{onHover:p==null?void 0:p.onHover,hovering:g}}),v=f.onHover,m=f.hovering;return o.createElement(T1,F({},e,{colSpan:u,rowSpan:d,hovering:m,ref:t,onHover:v}))});Da.displayName="WrappedCell";var Sn=o.createContext(null);function vc(e,t,r,n,a){var i=r[e]||{},l=r[t]||{},c,s;i.fixed==="left"?c=n.left[e]:l.fixed==="right"&&(s=n.right[t]);var u=!1,d=!1,f=!1,v=!1,m=r[t+1],p=r[e-1];if(a==="rtl"){if(c!==void 0){var g=p&&p.fixed==="left";v=!g}else if(s!==void 0){var h=m&&m.fixed==="right";f=!h}}else if(c!==void 0){var y=m&&m.fixed==="left";u=!y}else if(s!==void 0){var C=p&&p.fixed==="right";d=!C}return{fixLeft:c,fixRight:s,lastFixLeft:u,firstFixRight:d,lastFixRight:f,firstFixLeft:v,isSticky:n.isSticky}}function Km(e){var t=e.cells,r=e.stickyOffsets,n=e.flattenColumns,a=e.rowComponent,i=e.cellComponent,l=e.onHeaderRow,c=e.index,s=o.useContext(Sn),u=s.prefixCls,d=s.direction,f;l&&(f=l(t.map(function(m){return m.column}),c));var v=zo(t.map(function(m){return m.column}));return o.createElement(a,f,t.map(function(m,p){var g=m.column,h=vc(m.colStart,m.colEnd,n,r,d),y;return g&&g.onHeaderCell&&(y=m.column.onHeaderCell(g)),o.createElement(Da,F({},m,{ellipsis:g.ellipsis,align:g.align,component:i,prefixCls:u,key:v[p]},h,{additionalProps:y,rowType:"header"}))}))}Km.displayName="HeaderRow";function _1(e){var t=[];function r(l,c){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;t[s]=t[s]||[];var u=c,d=l.filter(Boolean).map(function(f){var v={key:f.key,className:f.className||"",children:f.title,column:f,colStart:u},m=1,p=f.children;return p&&p.length>0&&(m=r(p,u,s+1).reduce(function(g,h){return g+h},0),v.hasSubColumns=!0),"colSpan"in f&&(m=f.colSpan),"rowSpan"in f&&(v.rowSpan=f.rowSpan),v.colSpan=m,v.colEnd=v.colStart+m-1,t[s].push(v),u+=m,m});return d}r(e,0);for(var n=t.length,a=function(c){t[c].forEach(function(s){!("rowSpan"in s)&&!s.hasSubColumns&&(s.rowSpan=n-c)})},i=0;i1?te-1:0),ce=1;ce0?[].concat(ue(t),ue(pc(i).map(function(l){return L({fixed:a},l)}))):[].concat(ue(t),[L(L({},r),{},{fixed:a})])},[])}function j1(e){return e.map(function(t){var r=t.fixed,n=Fe(t,z1),a=r;return r==="left"?a="right":r==="right"&&(a="left"),L({fixed:a},n)})}function H1(e,t){var r=e.prefixCls,n=e.columns,a=e.children,i=e.expandable,l=e.expandedKeys,c=e.columnTitle,s=e.getRowKey,u=e.onTriggerExpand,d=e.expandIcon,f=e.rowExpandable,v=e.expandIconColumnIndex,m=e.direction,p=e.expandRowByClick,g=e.columnWidth,h=e.fixed,y=o.useMemo(function(){return n||mc(a)},[n,a]),C=o.useMemo(function(){if(i){var w,S=y.slice();if(!S.includes(pr)){var O=v||0;O>=0&&S.splice(O,0,pr)}var E=S.indexOf(pr);S=S.filter(function(R,N){return R!==pr||N===E});var k=y[E],I;(h==="left"||h)&&!v?I="left":(h==="right"||h)&&v===y.length?I="right":I=k?k.fixed:null;var M=(w={},T(w,$a,{className:"".concat(r,"-expand-icon-col"),columnType:"EXPAND_COLUMN"}),T(w,"title",c),T(w,"fixed",I),T(w,"className","".concat(r,"-row-expand-icon-cell")),T(w,"width",g),T(w,"render",function(N,P,_){var $=s(P,_),D=l.has($),A=f?f(P):!0,V=d({prefixCls:r,expanded:D,expandable:A,record:P,onExpand:u});return p?o.createElement("span",{onClick:function(q){return q.stopPropagation()}},V):V}),w);return S.map(function(R){return R===pr?M:R})}return y.filter(function(R){return R!==pr})},[i,y,s,l,d,m]),b=o.useMemo(function(){var w=C;return t&&(w=t(w)),w.length||(w=[{render:function(){return null}}]),w},[t,C,m]),x=o.useMemo(function(){return m==="rtl"?j1(pc(b)):pc(b)},[b,m]);return[b,x]}function qm(e){var t=o.useRef(e),r=o.useState({}),n=W(r,2),a=n[1],i=o.useRef(null),l=o.useRef([]);function c(s){l.current.push(s);var u=Promise.resolve();i.current=u,u.then(function(){if(i.current===u){var d=l.current,f=t.current;l.current=[],d.forEach(function(v){t.current=v(t.current)}),i.current=null,f!==t.current&&a({})}})}return o.useEffect(function(){return function(){i.current=null}},[]),[t.current,c]}function B1(e){var t=o.useRef(e||null),r=o.useRef();function n(){window.clearTimeout(r.current)}function a(l){t.current=l,n(),r.current=window.setTimeout(function(){t.current=null,r.current=void 0},100)}function i(){return t.current}return o.useEffect(function(){return n},[]),[a,i]}function W1(e,t,r){var n=o.useMemo(function(){for(var a=[],i=[],l=0,c=0,s=0;s=0;c-=1){var s=t[c],u=r&&r[c],d=u&&u[$a];if(s||d||l){var f=d||{},v=f.columnType,m=Fe(f,U1);a.unshift(o.createElement("col",F({key:c,style:{width:s}},m))),l=!0}}return o.createElement("colgroup",null,a)}function Ym(e){var t=e.className,r=e.children;return o.createElement("div",{className:t},r)}var Xm=o.createContext({});function q1(e){var t=e.className,r=e.index,n=e.children,a=e.colSpan,i=a===void 0?1:a,l=e.rowSpan,c=e.align,s=o.useContext(Sn),u=s.prefixCls,d=s.direction,f=o.useContext(Xm),v=f.scrollColumnIndex,m=f.stickyOffsets,p=f.flattenColumns,g=r+i-1,h=g+1===v?i+1:i,y=vc(r,r+h-1,p,m,d);return o.createElement(Da,F({className:t,index:r,component:"td",prefixCls:u,record:null,dataIndex:null,align:c,colSpan:h,rowSpan:l,render:function(){return n}},y))}var G1=["children"];function Y1(e){var t=e.children,r=Fe(e,G1);return o.createElement("tr",r,t)}function Ho(e){var t=e.children;return t}Ho.Row=Y1,Ho.Cell=q1;function Bo(e){var t=e.children,r=e.stickyOffsets,n=e.flattenColumns,a=o.useContext(Sn),i=a.prefixCls,l=n.length-1,c=n[l],s=o.useMemo(function(){return{stickyOffsets:r,flattenColumns:n,scrollColumnIndex:(c==null?void 0:c.scrollbar)?l:null}},[c,n,l,r]);return o.createElement(Xm.Provider,{value:s},o.createElement("tfoot",{className:"".concat(i,"-summary")},t))}var Qm=Ho;function X1(e){var t,r=e.prefixCls,n=e.record,a=e.onExpand,i=e.expanded,l=e.expandable,c="".concat(r,"-row-expand-icon");if(!l)return o.createElement("span",{className:Y(c,"".concat(r,"-row-spaced"))});var s=function(d){a(n,d),d.stopPropagation()};return o.createElement("span",{className:Y(c,(t={},T(t,"".concat(r,"-row-expanded"),i),T(t,"".concat(r,"-row-collapsed"),!i),t)),onClick:s})}function Q1(e,t,r){var n=[];function a(i){(i||[]).forEach(function(l,c){n.push(t(l,c)),a(l[r])})}return a(e),n}var J1=function(t,r){var n,a,i=t.scrollBodyRef,l=t.onScroll,c=t.offsetScroll,s=t.container,u=o.useContext(Sn),d=u.prefixCls,f=((n=i.current)===null||n===void 0?void 0:n.scrollWidth)||0,v=((a=i.current)===null||a===void 0?void 0:a.clientWidth)||0,m=f&&v*(v/f),p=o.useRef(),g=qm({scrollLeft:0,isHiddenScrollBar:!1}),h=W(g,2),y=h[0],C=h[1],b=o.useRef({delta:0,x:0}),x=o.useState(!1),w=W(x,2),S=w[0],O=w[1],E=function(){O(!1)},k=function(P){P.persist(),b.current.delta=P.pageX-y.scrollLeft,b.current.x=0,O(!0),P.preventDefault()},I=function(P){var _,$=P||((_=window)===null||_===void 0?void 0:_.event),D=$.buttons;if(!S||D===0){S&&O(!1);return}var A=b.current.x+P.pageX-b.current.x-b.current.delta;A<=0&&(A=0),A+m>=v&&(A=v-m),l({scrollLeft:A/v*(f+2)}),b.current.x=P.pageX},M=function(){if(!!i.current){var P=Jv(i.current).top,_=P+i.current.offsetHeight,$=s===window?document.documentElement.scrollTop+window.innerHeight:Jv(s).top+s.clientHeight;_-$o()<=$||P>=$-c?C(function(D){return L(L({},D),{},{isHiddenScrollBar:!0})}):C(function(D){return L(L({},D),{},{isHiddenScrollBar:!1})})}},R=function(P){C(function(_){return L(L({},_),{},{scrollLeft:P/f*v||0})})};return o.useImperativeHandle(r,function(){return{setScrollLeft:R}}),o.useEffect(function(){var N=On(document.body,"mouseup",E,!1),P=On(document.body,"mousemove",I,!1);return M(),function(){N.remove(),P.remove()}},[m,S]),o.useEffect(function(){var N=On(s,"scroll",M,!1),P=On(window,"resize",M,!1);return function(){N.remove(),P.remove()}},[s]),o.useEffect(function(){y.isHiddenScrollBar||C(function(N){var P=i.current;return P?L(L({},N),{},{scrollLeft:P.scrollLeft/P.scrollWidth*P.clientWidth}):N})},[y.isHiddenScrollBar]),f<=v||!m||y.isHiddenScrollBar?null:o.createElement("div",{style:{height:$o(),width:v,bottom:c},className:"".concat(d,"-sticky-scroll")},o.createElement("div",{onMouseDown:k,ref:p,className:Y("".concat(d,"-sticky-scroll-bar"),T({},"".concat(d,"-sticky-scroll-bar-active"),S)),style:{width:"".concat(m,"px"),transform:"translate3d(".concat(y.scrollLeft,"px, 0, 0)")}}))},Z1=o.forwardRef(J1),Jm=Ut()?window:null;function eN(e,t){var r=ke(e)==="object"?e:{},n=r.offsetHeader,a=n===void 0?0:n,i=r.offsetSummary,l=i===void 0?0:i,c=r.offsetScroll,s=c===void 0?0:c,u=r.getContainer,d=u===void 0?function(){return Jm}:u,f=d()||Jm;return o.useMemo(function(){var v=!!e;return{isSticky:v,stickyClassName:v?"".concat(t,"-sticky-holder"):"",offsetHeader:a,offsetSummary:l,offsetScroll:s,container:f}},[s,a,l,t,f])}var tN=["className","noData","columns","flattenColumns","colWidths","columCount","stickyOffsets","direction","fixHeader","stickyTopOffset","stickyBottomOffset","stickyClassName","onScroll","maxContentScroll","children"];function nN(e,t){return o.useMemo(function(){for(var r=[],n=0;n=0})},[i]),I=i[i.length-1],M={fixed:I?I.fixed:null,scrollbar:!0,onHeaderCell:function(){return{className:"".concat(b,"-cell-scrollbar")}}},R=o.useMemo(function(){return S?[].concat(ue(a),[M]):a},[S,a]),N=o.useMemo(function(){return S?[].concat(ue(i),[M]):i},[S,i]),P=o.useMemo(function(){var $=s.right,D=s.left;return L(L({},s),{},{left:u==="rtl"?[].concat(ue(D.map(function(A){return A+S})),[0]):D,right:u==="rtl"?$:[].concat(ue($.map(function(A){return A+S})),[0]),isSticky:w})},[S,s,w]),_=nN(l,c);return o.createElement("div",{style:L({overflow:"hidden"},w?{top:f,bottom:v}:{}),ref:E,className:Y(r,T({},m,!!m))},o.createElement("table",{style:{tableLayout:"fixed",visibility:n||_?null:"hidden"}},(!n||!g||k)&&o.createElement(Gm,{colWidths:_?[].concat(ue(_),[S]):[],columCount:c+1,columns:N}),h(L(L({},y),{},{stickyOffsets:P,columns:R,flattenColumns:N}))))});hc.displayName="FixedHolder";var rN=[],aN={},Wo="rc-table-internal-hook",oN=o.memo(function(e){var t=e.children;return t},function(e,t){return xr(e.props,t.props)?e.pingLeft!==t.pingLeft||e.pingRight!==t.pingRight:!1});function hr(e){var t,r=e.prefixCls,n=e.className,a=e.rowClassName,i=e.style,l=e.data,c=e.rowKey,s=e.scroll,u=e.tableLayout,d=e.direction,f=e.title,v=e.footer,m=e.summary,p=e.id,g=e.showHeader,h=e.components,y=e.emptyText,C=e.onRow,b=e.onHeaderRow,x=e.internalHooks,w=e.transformColumns,S=e.internalRefs,O=e.sticky,E=l||rN,k=!!E.length,I=o.useCallback(function(lt,pt){return Dm(h||{},lt)||pt},[h]),M=o.useMemo(function(){return typeof c=="function"?c:function(lt){var pt=lt&<[c];return pt}},[c]),R=K1(e),N=R.expandIcon,P=R.expandedRowKeys,_=R.defaultExpandedRowKeys,$=R.defaultExpandAllRows,D=R.expandedRowRender,A=R.columnTitle,V=R.onExpand,U=R.onExpandedRowsChange,q=R.expandRowByClick,K=R.rowExpandable,H=R.expandIconColumnIndex,j=R.expandedRowClassName,z=R.childrenColumnName,B=R.indentSize,G=N||X1,Q=z||"children",J=o.useMemo(function(){return D?"row":e.expandable&&x===Wo&&e.expandable.__PARENT_RENDER_ICON__||E.some(function(lt){return lt&&ke(lt)==="object"&<[Q]})?"nest":!1},[!!D,E]),Z=o.useState(function(){return _||($?Q1(E,M,Q):[])}),ne=W(Z,2),de=ne[0],X=ne[1],ae=o.useMemo(function(){return new Set(P||de||[])},[P,de]),te=o.useCallback(function(lt){var pt=M(lt,E.indexOf(lt)),Mt,rn=ae.has(pt);rn?(ae.delete(pt),Mt=ue(ae)):Mt=[].concat(ue(ae),[pt]),X(Mt),V&&V(!rn,lt),U&&U(Mt)},[M,ae,E,V,U]),oe=o.useState(0),ce=W(oe,2),pe=ce[0],me=ce[1],ve=H1(L(L(L({},e),R),{},{expandable:!!D,columnTitle:A,expandedKeys:ae,getRowKey:M,onTriggerExpand:te,expandIcon:G,expandIconColumnIndex:H,direction:d}),x===Wo?w:null),se=W(ve,2),ee=se[0],re=se[1],ye=o.useMemo(function(){return{columns:ee,flattenColumns:re}},[ee,re]),Ne=o.useRef(),Ce=o.useRef(),_e=o.useRef(),Ee=o.useRef(),ge=o.useRef(),xe=o.useState(!1),De=W(xe,2),we=De[0],Oe=De[1],Le=o.useState(!1),et=W(Le,2),Ke=et[0],ut=et[1],Ye=qm(new Map),ot=W(Ye,2),Ae=ot[0],$e=ot[1],rt=zo(re),tt=rt.map(function(lt){return Ae.get(lt)}),Ze=o.useMemo(function(){return tt},[tt.join("_")]),Me=W1(Ze,re.length,d),Se=s&&fc(s.y),le=s&&fc(s.x)||Boolean(R.fixed),fe=le&&re.some(function(lt){var pt=lt.fixed;return pt}),he=o.useRef(),be=eN(O,r),Ie=be.isSticky,Qe=be.offsetHeader,vt=be.offsetSummary,Et=be.offsetScroll,at=be.stickyClassName,Te=be.container,Re=m==null?void 0:m(E),je=(Se||Ie)&&o.isValidElement(Re)&&Re.type===Ho&&Re.props.fixed,He,ht,dt;Se&&(ht={overflowY:"scroll",maxHeight:s.y}),le&&(He={overflowX:"auto"},Se||(ht={overflowY:"hidden"}),dt={width:(s==null?void 0:s.x)===!0?"auto":s==null?void 0:s.x,minWidth:"100%"});var ct=o.useCallback(function(lt,pt){Yi(Ne.current)&&$e(function(Mt){if(Mt.get(lt)!==pt){var rn=new Map(Mt);return rn.set(lt,pt),rn}return Mt})},[]),wt=B1(null),kt=W(wt,2),At=kt[0],Ve=kt[1];function Pe(lt,pt){!pt||(typeof pt=="function"?pt(lt):pt.scrollLeft!==lt&&(pt.scrollLeft=lt))}var Xe=function(pt){var Mt=pt.currentTarget,rn=pt.scrollLeft,Pp=d==="rtl",Kn=typeof rn=="number"?rn:Mt.scrollLeft,kc=Mt||aN;if(!Ve()||Ve()===kc){var Jo;At(kc),Pe(Kn,Ce.current),Pe(Kn,_e.current),Pe(Kn,ge.current),Pe(Kn,(Jo=he.current)===null||Jo===void 0?void 0:Jo.setScrollLeft)}if(Mt){var Zo=Mt.scrollWidth,ei=Mt.clientWidth;if(Zo===ei){Oe(!1),ut(!1);return}Pp?(Oe(-Kn0)):(Oe(Kn>0),ut(Kn0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],r=e.length,n=t.length;if(Math.abs(r-n)!==1)return{add:!1,key:null};function a(i,l){var c=new Map;i.forEach(function(u){c.set(u,!0)});var s=l.filter(function(u){return!c.has(u)});return s.length===1?s[0]:null}return r ").concat(t);return t}var lp=o.forwardRef(function(e,t){var r=e.prefixCls,n=e.data,a=e.selectable,i=e.checkable,l=e.expandedKeys,c=e.selectedKeys,s=e.checkedKeys,u=e.loadedKeys,d=e.loadingKeys,f=e.halfCheckedKeys,v=e.keyEntities,m=e.disabled,p=e.dragging,g=e.dragOverNodeKey,h=e.dropPosition,y=e.motion,C=e.height,b=e.itemHeight,x=e.virtual,w=e.focusable,S=e.activeItem,O=e.focused,E=e.tabIndex,k=e.onKeyDown,I=e.onFocus,M=e.onBlur,R=e.onActiveChange,N=e.onListChangeStart,P=e.onListChangeEnd,_=Fe(e,vN),$=o.useRef(null),D=o.useRef(null);o.useImperativeHandle(t,function(){return{scrollTo:function(re){$.current.scrollTo(re)},getIndentWidth:function(){return D.current.offsetWidth}}});var A=o.useState(l),V=W(A,2),U=V[0],q=V[1],K=o.useState(n),H=W(K,2),j=H[0],z=H[1],B=o.useState(n),G=W(B,2),Q=G[0],J=G[1],Z=o.useState([]),ne=W(Z,2),de=ne[0],X=ne[1],ae=o.useState(null),te=W(ae,2),oe=te[0],ce=te[1],pe=o.useRef(n);pe.current=n;function me(){var ee=pe.current;z(ee),J(ee),X([]),ce(null),P()}o.useEffect(function(){q(l);var ee=fN(U,l);if(ee.key!==null)if(ee.add){var re=j.findIndex(function(ge){var xe=ge.key;return xe===ee.key}),ye=op(tp(j,n,ee.key),x,C,b),Ne=j.slice();Ne.splice(re+1,0,ap),J(Ne),X(ye),ce("show")}else{var Ce=n.findIndex(function(ge){var xe=ge.key;return xe===ee.key}),_e=op(tp(n,j,ee.key),x,C,b),Ee=n.slice();Ee.splice(Ce+1,0,ap),J(Ee),X(_e),ce("hide")}else j!==n&&(z(n),J(n))},[l,n]),o.useEffect(function(){p||me()},[p]);var ve=y?Q:n,se={expandedKeys:l,selectedKeys:c,loadedKeys:u,loadingKeys:d,checkedKeys:s,halfCheckedKeys:f,dragOverNodeKey:g,dropPosition:h,keyEntities:v};return o.createElement(o.Fragment,null,O&&S&&o.createElement("span",{style:np,"aria-live":"assertive"},pN(S)),o.createElement("div",null,o.createElement("input",{style:np,disabled:w===!1||m,tabIndex:w!==!1?E:null,onKeyDown:k,onFocus:I,onBlur:M,value:"",onChange:mN,"aria-label":"for screen reader"})),o.createElement("div",{className:"".concat(r,"-treenode"),"aria-hidden":!0,style:{position:"absolute",pointerEvents:"none",visibility:"hidden",height:0,overflow:"hidden"}},o.createElement("div",{className:"".concat(r,"-indent")},o.createElement("div",{ref:D,className:"".concat(r,"-indent-unit")}))),o.createElement(hl,F({},_,{data:ve,itemKey:ip,height:C,fullHeight:!1,virtual:x,itemHeight:b,prefixCls:"".concat(r,"-list"),ref:$,onVisibleChange:function(re,ye){var Ne=new Set(re),Ce=ye.filter(function(_e){return!Ne.has(_e)});Ce.some(function(_e){return ip(_e)===gr})&&me()}}),function(ee){var re=ee.pos,ye=F({},(Zm(ee.data),ee.data)),Ne=ee.title,Ce=ee.key,_e=ee.isStart,Ee=ee.isEnd,ge=Pa(Ce,re);delete ye.key,delete ye.children;var xe=Ra(ge,se);return o.createElement(dN,F({},ye,xe,{title:Ne,active:!!S&&Ce===S.key,pos:re,data:ee.data,isStart:_e,isEnd:Ee,motion:y,motionNodes:Ce===gr?de:null,motionType:oe,onMotionStart:N,onMotionEnd:me,treeNodeRequiredProps:se,onMouseMove:function(){R(null)}}))}))});lp.displayName="NodeList";function hN(e){var t=e.dropPosition,r=e.dropLevelOffset,n=e.indent,a={pointerEvents:"none",position:"absolute",right:0,backgroundColor:"red",height:2};switch(t){case-1:a.top=0,a.left=-r*n;break;case 1:a.bottom=0,a.left=-r*n;break;case 0:a.bottom=0,a.left=n;break}return o.createElement("div",{style:a})}var gN=10,yc=function(e){_t(r,e);var t=Dt(r);function r(){var n;Pt(this,r);for(var a=arguments.length,i=new Array(a),l=0;l2&&arguments[2]!==void 0?arguments[2]:!1,f=n.state,v=f.dragChildrenKeys,m=f.dropPosition,p=f.dropTargetKey,g=f.dropTargetPos,h=f.dropAllowed;if(!!h){var y=n.props.onDrop;if(n.setState({dragOverNodeKey:null}),n.cleanDragState(),p!==null){var C=L(L({},Ra(p,n.getTreeNodeRequiredProps())),{},{active:((u=n.getActiveItem())===null||u===void 0?void 0:u.key)===p,data:n.state.keyEntities[p].node}),b=v.indexOf(p)!==-1;Ot(!b,"Can not drop to dragNode's children node. This is a bug of rc-tree. Please report an issue.");var x=Ul(g),w={event:c,node:Tt(C),dragNode:n.dragNode?Tt(n.dragNode.props):null,dragNodesKeys:[n.dragNode.props.eventKey].concat(v),dropToGap:m!==0,dropPosition:m+Number(x[x.length-1])};d||y==null||y(w),n.dragNode=null}}},n.cleanDragState=function(){var c=n.state.draggingNodeKey;c!==null&&n.setState({draggingNodeKey:null,dropPosition:null,dropContainerKey:null,dropTargetKey:null,dropLevelOffset:null,dropAllowed:!0,dragOverNodeKey:null}),n.dragStartMousePosition=null,n.currentMouseOverDroppableNodeKey=null},n.triggerExpandActionExpand=function(c,s){var u=n.state,d=u.expandedKeys,f=u.flattenNodes,v=s.expanded,m=s.key,p=s.isLeaf;if(!(p||c.shiftKey||c.metaKey||c.ctrlKey)){var g=f.filter(function(y){return y.key===m})[0],h=Tt(L(L({},Ra(m,n.getTreeNodeRequiredProps())),{},{data:g.data}));n.setExpandedKeys(v?bn(d,m):Dn(d,m)),n.onNodeExpand(c,h)}},n.onNodeClick=function(c,s){var u=n.props,d=u.onClick,f=u.expandAction;f==="click"&&n.triggerExpandActionExpand(c,s),d==null||d(c,s)},n.onNodeDoubleClick=function(c,s){var u=n.props,d=u.onDoubleClick,f=u.expandAction;f==="doubleClick"&&n.triggerExpandActionExpand(c,s),d==null||d(c,s)},n.onNodeSelect=function(c,s){var u=n.state.selectedKeys,d=n.state,f=d.keyEntities,v=d.fieldNames,m=n.props,p=m.onSelect,g=m.multiple,h=s.selected,y=s[v.key],C=!h;C?g?u=Dn(u,y):u=[y]:u=bn(u,y);var b=u.map(function(x){var w=f[x];return w?w.node:null}).filter(function(x){return x});n.setUncontrolledState({selectedKeys:u}),p==null||p(u,{event:"select",selected:C,node:s,selectedNodes:b,nativeEvent:c.nativeEvent})},n.onNodeCheck=function(c,s,u){var d=n.state,f=d.keyEntities,v=d.checkedKeys,m=d.halfCheckedKeys,p=n.props,g=p.checkStrictly,h=p.onCheck,y=s.key,C,b={event:"check",node:s,checked:u,nativeEvent:c.nativeEvent};if(g){var x=u?Dn(v,y):bn(v,y),w=bn(m,y);C={checked:x,halfChecked:w},b.checkedNodes=x.map(function(M){return f[M]}).filter(function(M){return M}).map(function(M){return M.node}),n.setUncontrolledState({checkedKeys:x})}else{var S=_n([].concat(ue(v),[y]),!0,f),O=S.checkedKeys,E=S.halfCheckedKeys;if(!u){var k=new Set(O);k.delete(y);var I=_n(Array.from(k),{checked:!1,halfCheckedKeys:E},f);O=I.checkedKeys,E=I.halfCheckedKeys}C=O,b.checkedNodes=[],b.checkedNodesPositions=[],b.halfCheckedKeys=E,O.forEach(function(M){var R=f[M];if(!!R){var N=R.node,P=R.pos;b.checkedNodes.push(N),b.checkedNodesPositions.push({node:N,pos:P})}}),n.setUncontrolledState({checkedKeys:O},!1,{halfCheckedKeys:E})}h==null||h(C,b)},n.onNodeLoad=function(c){var s=c.key,u=new Promise(function(d,f){n.setState(function(v){var m=v.loadedKeys,p=m===void 0?[]:m,g=v.loadingKeys,h=g===void 0?[]:g,y=n.props,C=y.loadData,b=y.onLoad;if(!C||p.indexOf(s)!==-1||h.indexOf(s)!==-1)return null;var x=C(c);return x.then(function(){var w=n.state.loadedKeys,S=Dn(w,s);b==null||b(S,{event:"load",node:c}),n.setUncontrolledState({loadedKeys:S}),n.setState(function(O){return{loadingKeys:bn(O.loadingKeys,s)}}),d()}).catch(function(w){if(n.setState(function(O){return{loadingKeys:bn(O.loadingKeys,s)}}),n.loadingRetryTimes[s]=(n.loadingRetryTimes[s]||0)+1,n.loadingRetryTimes[s]>=gN){var S=n.state.loadedKeys;Ot(!1,"Retry for `loadData` many times but still failed. No more retry."),n.setUncontrolledState({loadedKeys:Dn(S,s)}),d()}f(w)}),{loadingKeys:Dn(h,s)}})});return u.catch(function(){}),u},n.onNodeMouseEnter=function(c,s){var u=n.props.onMouseEnter;u==null||u({event:c,node:s})},n.onNodeMouseLeave=function(c,s){var u=n.props.onMouseLeave;u==null||u({event:c,node:s})},n.onNodeContextMenu=function(c,s){var u=n.props.onRightClick;u&&(c.preventDefault(),u({event:c,node:s}))},n.onFocus=function(){var c=n.props.onFocus;n.setState({focused:!0});for(var s=arguments.length,u=new Array(s),d=0;d1&&arguments[1]!==void 0?arguments[1]:!1,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(!n.destroyed){var d=!1,f=!0,v={};Object.keys(c).forEach(function(m){if(m in n.props){f=!1;return}d=!0,v[m]=c[m]}),d&&(!s||f)&&n.setState(L(L({},v),u))}},n.scrollTo=function(c){n.listRef.current.scrollTo(c)},n}return Rt(r,[{key:"componentDidMount",value:function(){this.destroyed=!1,this.onUpdated()}},{key:"componentDidUpdate",value:function(){this.onUpdated()}},{key:"onUpdated",value:function(){var a=this.props.activeKey;a!==void 0&&a!==this.state.activeKey&&(this.setState({activeKey:a}),a!==null&&this.scrollTo({key:a}))}},{key:"componentWillUnmount",value:function(){window.removeEventListener("dragend",this.onWindowDragEnd),this.destroyed=!0}},{key:"resetDragState",value:function(){this.setState({dragOverNodeKey:null,dropPosition:null,dropLevelOffset:null,dropTargetKey:null,dropContainerKey:null,dropTargetPos:null,dropAllowed:!1})}},{key:"render",value:function(){var a,i=this.state,l=i.focused,c=i.flattenNodes,s=i.keyEntities,u=i.draggingNodeKey,d=i.activeKey,f=i.dropLevelOffset,v=i.dropContainerKey,m=i.dropTargetKey,p=i.dropPosition,g=i.dragOverNodeKey,h=i.indent,y=this.props,C=y.prefixCls,b=y.className,x=y.style,w=y.showLine,S=y.focusable,O=y.tabIndex,E=O===void 0?0:O,k=y.selectable,I=y.showIcon,M=y.icon,R=y.switcherIcon,N=y.draggable,P=y.checkable,_=y.checkStrictly,$=y.disabled,D=y.motion,A=y.loadData,V=y.filterTreeNode,U=y.height,q=y.itemHeight,K=y.virtual,H=y.titleRender,j=y.dropIndicatorRender,z=y.onContextMenu,B=y.onScroll,G=y.direction,Q=y.rootClassName,J=y.rootStyle,Z=Bn(this.props,{aria:!0,data:!0}),ne;return N&&(ke(N)==="object"?ne=N:typeof N=="function"?ne={nodeDraggable:N}:ne={}),o.createElement(Wl.Provider,{value:{prefixCls:C,selectable:k,showIcon:I,icon:M,switcherIcon:R,draggable:ne,draggingNodeKey:u,checkable:P,checkStrictly:_,disabled:$,keyEntities:s,dropLevelOffset:f,dropContainerKey:v,dropTargetKey:m,dropPosition:p,dragOverNodeKey:g,indent:h,direction:G,dropIndicatorRender:j,loadData:A,filterTreeNode:V,titleRender:H,onNodeClick:this.onNodeClick,onNodeDoubleClick:this.onNodeDoubleClick,onNodeExpand:this.onNodeExpand,onNodeSelect:this.onNodeSelect,onNodeCheck:this.onNodeCheck,onNodeLoad:this.onNodeLoad,onNodeMouseEnter:this.onNodeMouseEnter,onNodeMouseLeave:this.onNodeMouseLeave,onNodeContextMenu:this.onNodeContextMenu,onNodeDragStart:this.onNodeDragStart,onNodeDragEnter:this.onNodeDragEnter,onNodeDragOver:this.onNodeDragOver,onNodeDragLeave:this.onNodeDragLeave,onNodeDragEnd:this.onNodeDragEnd,onNodeDrop:this.onNodeDrop}},o.createElement("div",{role:"tree",className:Y(C,b,Q,(a={},T(a,"".concat(C,"-show-line"),w),T(a,"".concat(C,"-focused"),l),T(a,"".concat(C,"-active-focused"),d!==null),a)),style:J},o.createElement(lp,F({ref:this.listRef,prefixCls:C,style:x,data:c,disabled:$,selectable:k,checkable:!!P,motion:D,dragging:u!==null,height:U,itemHeight:q,virtual:K,focusable:S,focused:l,tabIndex:E,activeItem:this.getActiveItem(),onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:this.onKeyDown,onActiveChange:this.onActiveChange,onListChangeStart:this.onListChangeStart,onListChangeEnd:this.onListChangeEnd,onContextMenu:z,onScroll:B},this.getTreeNodeRequiredProps(),Z))))}}],[{key:"getDerivedStateFromProps",value:function(a,i){var l=i.prevProps,c={prevProps:a};function s(S){return!l&&S in a||l&&l[S]!==a[S]}var u,d=i.fieldNames;if(s("fieldNames")&&(d=_o(a.fieldNames),c.fieldNames=d),s("treeData")?u=a.treeData:s("children")&&(Ot(!1,"`children` of Tree is deprecated. Please use `treeData` instead."),u=bv(a.children)),u){c.treeData=u;var f=Do(u,{fieldNames:d});c.keyEntities=L(T({},gr,rp),f.keyEntities)}var v=c.keyEntities||i.keyEntities;if(s("expandedKeys")||l&&s("autoExpandParent"))c.expandedKeys=a.autoExpandParent||!l&&a.defaultExpandParent?Gl(a.expandedKeys,v):a.expandedKeys;else if(!l&&a.defaultExpandAll){var m=L({},v);delete m[gr],c.expandedKeys=Object.keys(m).map(function(S){return m[S].key})}else!l&&a.defaultExpandedKeys&&(c.expandedKeys=a.autoExpandParent||a.defaultExpandParent?Gl(a.defaultExpandedKeys,v):a.defaultExpandedKeys);if(c.expandedKeys||delete c.expandedKeys,u||c.expandedKeys){var p=Yl(u||i.treeData,c.expandedKeys||i.expandedKeys,d);c.flattenNodes=p}if(a.selectable&&(s("selectedKeys")?c.selectedKeys=Cv(a.selectedKeys,a):!l&&a.defaultSelectedKeys&&(c.selectedKeys=Cv(a.defaultSelectedKeys,a))),a.checkable){var g;if(s("checkedKeys")?g=ql(a.checkedKeys)||{}:!l&&a.defaultCheckedKeys?g=ql(a.defaultCheckedKeys)||{}:u&&(g=ql(a.checkedKeys)||{checkedKeys:i.checkedKeys,halfCheckedKeys:i.halfCheckedKeys}),g){var h=g,y=h.checkedKeys,C=y===void 0?[]:y,b=h.halfCheckedKeys,x=b===void 0?[]:b;if(!a.checkStrictly){var w=_n(C,!0,v);C=w.checkedKeys,x=w.halfCheckedKeys}c.checkedKeys=C,c.halfCheckedKeys=x}}return s("loadedKeys")&&(c.loadedKeys=a.loadedKeys),c}}]),r}(o.Component);yc.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,disabled:!1,checkStrictly:!1,draggable:!1,defaultExpandParent:!0,autoExpandParent:!1,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[],dropIndicatorRender:hN,allowDrop:function(){return!0},expandAction:!1},yc.TreeNode=dr;var cp=4;function yN(e){var t,r=e.dropPosition,n=e.dropLevelOffset,a=e.prefixCls,i=e.indent,l=e.direction,c=l===void 0?"ltr":l,s=c==="ltr"?"left":"right",u=c==="ltr"?"right":"left",d=(t={},T(t,s,-n*i+cp),T(t,u,0),t);switch(r){case-1:d.top=-3;break;case 1:d.bottom=-3;break;default:d.bottom=-3,d[s]=i+cp;break}return o.createElement("div",{style:d,className:"".concat(a,"-drop-indicator")})}function CN(e,t,r,n){var a=n.isLeaf,i=n.expanded,l=n.loading;if(l)return o.createElement(tr,{className:"".concat(e,"-switcher-loading-icon")});var c;if(r&&ke(r)==="object"&&(c=r.showLeafIcon),a){if(!r)return null;if(typeof c!="boolean"&&!!c){var s=typeof c=="function"?c(n):c,u="".concat(e,"-switcher-line-custom-icon");return cn(s)?Ht(s,{className:Y(s.props.className||"",u)}):s}return c?o.createElement(ls,{className:"".concat(e,"-switcher-line-icon")}):o.createElement("span",{className:"".concat(e,"-switcher-leaf-line")})}var d="".concat(e,"-switcher-icon"),f=typeof t=="function"?t(n):t;return cn(f)?Ht(f,{className:Y(f.props.className||"",d)}):f||(r?i?o.createElement(Ph,{className:"".concat(e,"-switcher-line-icon")}):o.createElement(kh,{className:"".concat(e,"-switcher-line-icon")}):o.createElement(Hp,{className:d}))}var sp=o.forwardRef(function(e,t){var r,n=o.useContext(qe),a=n.getPrefixCls,i=n.direction,l=n.virtual,c=e.prefixCls,s=e.className,u=e.showIcon,d=u===void 0?!1:u,f=e.showLine,v=e.switcherIcon,m=e.blockNode,p=m===void 0?!1:m,g=e.children,h=e.checkable,y=h===void 0?!1:h,C=e.selectable,b=C===void 0?!0:C,x=e.draggable,w=e.motion,S=w===void 0?F(F({},uo),{motionAppear:!1}):w,O=a("tree",c),E=F(F({},e),{checkable:y,selectable:b,showIcon:d,motion:S,blockNode:p,showLine:Boolean(f),dropIndicatorRender:yN}),k=o.useMemo(function(){if(!x)return!1;var I={};switch(ke(x)){case"function":I.nodeDraggable=x;break;case"object":I=F({},x);break}return I.icon!==!1&&(I.icon=I.icon||o.createElement(Ch,null)),I},[x]);return o.createElement(yc,F({itemHeight:20,ref:t,virtual:l},E,{prefixCls:O,className:Y((r={},T(r,"".concat(O,"-icon-hide"),!d),T(r,"".concat(O,"-block-node"),p),T(r,"".concat(O,"-unselectable"),!b),T(r,"".concat(O,"-rtl"),i==="rtl"),r),s),direction:i,checkable:y&&o.createElement("span",{className:"".concat(O,"-checkbox-inner")}),selectable:b,switcherIcon:function(M){return CN(O,v,f,M)},draggable:k}),g)}),Fn;(function(e){e[e.None=0]="None",e[e.Start=1]="Start",e[e.End=2]="End"})(Fn||(Fn={}));function Cc(e,t){function r(n){var a=n.key,i=n.children;t(a,n)!==!1&&Cc(i||[],t)}e.forEach(r)}function bN(e){var t=e.treeData,r=e.expandedKeys,n=e.startKey,a=e.endKey,i=[],l=Fn.None;if(n&&n===a)return[n];if(!n||!a)return[];function c(s){return s===n||s===a}return Cc(t,function(s){if(l===Fn.End)return!1;if(c(s)){if(i.push(s),l===Fn.None)l=Fn.Start;else if(l===Fn.Start)return l=Fn.End,!1}else l===Fn.Start&&i.push(s);return r.includes(s)}),i}function bc(e,t){var r=ue(t),n=[];return Cc(e,function(a,i){var l=r.indexOf(a);return l!==-1&&(n.push(i),r.splice(l,1)),!!r.length}),n}var up=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a0&&arguments[0]!==void 0?arguments[0]:{confirm:!1,closeDropdown:!1},xe=ge.confirm,De=ge.closeDropdown;xe&&ne([]),De&&R(!1),J(""),A(w?(S||[]).map(function(we){return String(we)}):[])},ae=function(){var ge=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{closeDropdown:!0},xe=ge.closeDropdown;xe&&R(!1),ne(D())},te=function(ge){ge&&P!==void 0&&A(P||[]),R(ge),!ge&&!a.filterDropdown&&de()},oe=Y(T({},"".concat(i,"-menu-without-submenu"),!RN(a.filters||[]))),ce=function(ge){if(ge.target.checked){var xe=Zr(a==null?void 0:a.filters).map(function(De){return String(De)});A(xe)}else A([])},pe=function Ee(ge){var xe=ge.filters;return(xe||[]).map(function(De,we){var Oe=String(De.value),Le={title:De.text,key:De.value!==void 0?Oe:we};return De.children&&(Le.children=Ee({filters:De.children})),Le})},me=function Ee(ge){var xe;return F(F({},ge),{text:ge.title,value:ge.key,children:((xe=ge.children)===null||xe===void 0?void 0:xe.map(function(De){return Ee(De)}))||[]})},ve;if(typeof a.filterDropdown=="function")ve=a.filterDropdown({prefixCls:"".concat(i,"-custom"),setSelectedKeys:function(ge){return V({selectedKeys:ge})},selectedKeys:D(),confirm:ae,clearFilters:X,filters:a.filters,visible:N,close:function(){R(!1)}});else if(a.filterDropdown)ve=a.filterDropdown;else{var se=D()||[],ee=function(){return(a.filters||[]).length===0?o.createElement(Mn,{image:Mn.PRESENTED_IMAGE_SIMPLE,description:p.filterEmptyText,imageStyle:{height:24},style:{margin:0,padding:"16px 0"}}):u==="tree"?o.createElement(o.Fragment,null,o.createElement(fp,{filterSearch:f,value:Q,onChange:Z,tablePrefixCls:r,locale:p}),o.createElement("div",{className:"".concat(r,"-filter-dropdown-tree")},c?o.createElement(Gr,{checked:se.length===Zr(a.filters).length,indeterminate:se.length>0&&se.length0?i:e}),v=Math.ceil((i||e)/f.pageSize);f.current>v&&(f.current=v||1);var m=function(h,y){d({current:h!=null?h:1,pageSize:y||f.pageSize})},p=function(h,y){var C;t&&((C=t.onChange)===null||C===void 0||C.call(t,h,y)),m(h,y),r(h,y||(f==null?void 0:f.pageSize))};return t===!1?[{},function(){}]:[F(F({},f),{onChange:p}),m]}var Jn={},Sc="SELECT_ALL",Ec="SELECT_INVERT",wc="SELECT_NONE",Cp=[];function bp(e,t){var r=[];return(e||[]).forEach(function(n){r.push(n),n&&ke(n)==="object"&&t in n&&(r=[].concat(ue(r),ue(bp(n[t],t))))}),r}function $N(e,t){var r=e||{},n=r.preserveSelectedRowKeys,a=r.selectedRowKeys,i=r.defaultSelectedRowKeys,l=r.getCheckboxProps,c=r.onChange,s=r.onSelect,u=r.onSelectAll,d=r.onSelectInvert,f=r.onSelectNone,v=r.onSelectMultiple,m=r.columnWidth,p=r.type,g=r.selections,h=r.fixed,y=r.renderCell,C=r.hideSelectAll,b=r.checkStrictly,x=b===void 0?!0:b,w=t.prefixCls,S=t.data,O=t.pageData,E=t.getRecordByKey,k=t.getRowKey,I=t.expandType,M=t.childrenColumnName,R=t.locale,N=t.getPopupContainer,P=Ft(a||i||Cp,{value:a}),_=W(P,2),$=_[0],D=_[1],A=o.useRef(new Map),V=o.useCallback(function(me){if(n){var ve=new Map;me.forEach(function(se){var ee=E(se);!ee&&A.current.has(se)&&(ee=A.current.get(se)),ve.set(se,ee)}),A.current=ve}},[E,n]);o.useEffect(function(){V($)},[$]);var U=o.useMemo(function(){return x?{keyEntities:null}:Do(S,{externalGetKey:k,childrenPropName:M})},[S,k,x,M]),q=U.keyEntities,K=o.useMemo(function(){return bp(O,M)},[O,M]),H=o.useMemo(function(){var me=new Map;return K.forEach(function(ve,se){var ee=k(ve,se),re=(l?l(ve):null)||{};me.set(ee,re)}),me},[K,k,l]),j=o.useCallback(function(me){var ve;return!!((ve=H.get(k(me)))===null||ve===void 0?void 0:ve.disabled)},[H,k]),z=o.useMemo(function(){if(x)return[$||[],[]];var me=_n($,!0,q,j),ve=me.checkedKeys,se=me.halfCheckedKeys;return[ve||[],se]},[$,x,q,j]),B=W(z,2),G=B[0],Q=B[1],J=o.useMemo(function(){var me=p==="radio"?G.slice(0,1):G;return new Set(me)},[G,p]),Z=o.useMemo(function(){return p==="radio"?new Set:new Set(Q)},[Q,p]),ne=o.useState(null),de=W(ne,2),X=de[0],ae=de[1];o.useEffect(function(){e||D(Cp)},[!!e]);var te=o.useCallback(function(me,ve){var se,ee;V(me),n?(se=me,ee=me.map(function(re){return A.current.get(re)})):(se=[],ee=[],me.forEach(function(re){var ye=E(re);ye!==void 0&&(se.push(re),ee.push(ye))})),D(se),c==null||c(se,ee,{type:ve})},[D,E,c,n]),oe=o.useCallback(function(me,ve,se,ee){if(s){var re=se.map(function(ye){return E(ye)});s(E(me),ve,re,ee)}te(se,"single")},[s,E,te]),ce=o.useMemo(function(){if(!g||C)return null;var me=g===!0?[Sc,Ec,wc]:g;return me.map(function(ve){return ve===Sc?{key:"all",text:R.selectionAll,onSelect:function(){te(S.map(function(ee,re){return k(ee,re)}).filter(function(ee){var re=H.get(ee);return!(re==null?void 0:re.disabled)||J.has(ee)}),"all")}}:ve===Ec?{key:"invert",text:R.selectInvert,onSelect:function(){var ee=new Set(J);O.forEach(function(ye,Ne){var Ce=k(ye,Ne),_e=H.get(Ce);(_e==null?void 0:_e.disabled)||(ee.has(Ce)?ee.delete(Ce):ee.add(Ce))});var re=Array.from(ee);d&&d(re),te(re,"invert")}}:ve===wc?{key:"none",text:R.selectNone,onSelect:function(){f==null||f(),te(Array.from(J).filter(function(ee){var re=H.get(ee);return re==null?void 0:re.disabled}),"none")}}:ve}).map(function(ve){return F(F({},ve),{onSelect:function(){for(var ee,re,ye=arguments.length,Ne=new Array(ye),Ce=0;Ce2&&arguments[2]!==void 0?arguments[2]:!1,Ge=F(F({},ee),Pe);ze&&(ee.resetPagination(),Ge.pagination.current&&(Ge.pagination.current=1),d&&d.onChange&&d.onChange(1,Ge.pagination.pageSize)),I&&I.scrollToFirstRowOnChange!==!1&&ce.body.current&&Ky(0,{getContainer:function(){return ce.body.current}}),C==null||C(Ge.pagination,Ge.filters,Ge.sorter,{currentDataSource:gp(Rc(Q,Ge.sorterStates,te),Ge.filterStates),action:Xe})},ye=function(Pe,Xe){re({sorter:Pe,sorterStates:Xe},"sort",!1)},Ne=AN({prefixCls:ne,mergedColumns:A,onSorterChange:ye,sortDirections:M||["ascend","descend"],tableLocale:G,showSorterTooltip:P}),Ce=W(Ne,4),_e=Ce[0],Ee=Ce[1],ge=Ce[2],xe=Ce[3],De=o.useMemo(function(){return Rc(Q,Ee,te)},[Q,Ee]);ee.sorter=xe(),ee.sorterStates=Ee;var we=function(Pe,Xe){re({filters:Pe,filterStates:Xe},"filter",!0)},Oe=ON({prefixCls:ne,locale:G,dropdownPrefixCls:de,mergedColumns:A,onFilterChange:we,getPopupContainer:b}),Le=W(Oe,3),et=Le[0],Ke=Le[1],ut=Le[2],Ye=gp(De,Ke);ee.filters=ut,ee.filterStates=Ke;var ot=o.useMemo(function(){var Ve={};return Object.keys(ut).forEach(function(Pe){ut[Pe]!==null&&(Ve[Pe]=ut[Pe])}),F(F({},ge),{filters:Ve})},[ge,ut]),Ae=LN(ot),$e=W(Ae,1),rt=$e[0],tt=function(Pe,Xe){re({pagination:F(F({},ee.pagination),{current:Pe,pageSize:Xe})},"paginate")},Ze=DN(Ye.length,d,tt),Me=W(Ze,2),Se=Me[0],le=Me[1];ee.pagination=d===!1?{}:TN(d,Se),ee.resetPagination=le;var fe=o.useMemo(function(){if(d===!1||!Se.pageSize)return Ye;var Ve=Se.current,Pe=Ve===void 0?1:Ve,Xe=Se.total,ze=Se.pageSize,Ge=ze===void 0?yp:ze;return Ye.lengthGe?Ye.slice((Pe-1)*Ge,Pe*Ge):Ye:Ye.slice((Pe-1)*Ge,Pe*Ge)},[!!d,Ye,Se&&Se.current,Se&&Se.pageSize,Se&&Se.total]),he=$N(f,{prefixCls:ne,data:Ye,pageData:fe,getRowKey:pe,getRecordByKey:se,expandType:oe,childrenColumnName:te,locale:G,getPopupContainer:b}),be=W(he,2),Ie=be[0],Qe=be[1],vt=function(Pe,Xe,ze){var Ge;return typeof p=="function"?Ge=Y(p(Pe,Xe,ze)):Ge=Y(p),Y(T({},"".concat(ne,"-row-selected"),Qe.has(pe(Pe,Xe))),Ge)};X.__PARENT_RENDER_ICON__=X.expandIcon,X.expandIcon=X.expandIcon||w||cN(G),oe==="nest"&&X.expandIconColumnIndex===void 0?X.expandIconColumnIndex=f?1:0:X.expandIconColumnIndex>0&&f&&(X.expandIconColumnIndex-=1),typeof X.indentSize!="number"&&(X.indentSize=typeof k=="number"?k:15);var Et=o.useCallback(function(Ve){return rt(Ie(et(_e(Ve))))},[_e,et,Ie]),at,Te;if(d!==!1&&(Se==null?void 0:Se.total)){var Re;Se.size?Re=Se.size:Re=B==="small"||B==="middle"?"small":void 0;var je=function(Pe){return o.createElement(Pw,F({},Se,{className:Y("".concat(ne,"-pagination ").concat(ne,"-pagination-").concat(Pe),Se.className),size:Re}))},He=z==="rtl"?"left":"right",ht=Se.position;if(ht!==null&&Array.isArray(ht)){var dt=ht.find(function(Ve){return Ve.includes("top")}),ct=ht.find(function(Ve){return Ve.includes("bottom")}),wt=ht.every(function(Ve){return"".concat(Ve)==="none"});!dt&&!ct&&!wt&&(Te=je(He)),dt&&(at=je(dt.toLowerCase().replace("top",""))),ct&&(Te=je(ct.toLowerCase().replace("bottom","")))}else Te=je(He)}var kt;typeof x=="boolean"?kt={spinning:x}:ke(x)==="object"&&(kt=F({spinning:!0},x));var At=Y("".concat(ne,"-wrapper"),T({},"".concat(ne,"-wrapper-rtl"),z==="rtl"),a);return o.createElement("div",{ref:t,className:At,style:i},o.createElement(hm,F({spinning:!1},kt),at,o.createElement(hr,F({},V,{columns:A,direction:z,expandable:X,prefixCls:ne,className:Y((r={},T(r,"".concat(ne,"-middle"),B==="middle"),T(r,"".concat(ne,"-small"),B==="small"),T(r,"".concat(ne,"-bordered"),c),T(r,"".concat(ne,"-empty"),Q.length===0),r)),data:fe,rowKey:pe,rowClassName:vt,emptyText:R&&R.emptyText||(j||yl)("Table"),internalHooks:Wo,internalRefs:ce,transformColumns:Et})),Te))}var zN=o.forwardRef(VN),An=zN;An.SELECTION_COLUMN=Jn,An.EXPAND_COLUMN=hr.EXPAND_COLUMN,An.SELECTION_ALL=Sc,An.SELECTION_INVERT=Ec,An.SELECTION_NONE=wc,An.Column=iN,An.ColumnGroup=lN,An.Summary=Qm;export{mn as Button,Xl as Cascader,gE as Drawer,$n as Form,Yr as Input,xn as Modal,s0 as Popover,r1 as Progress,Wr as Radio,qn as Select,C1 as Slider,zl as Space,An as Table,cv as Tabs,Go as Tree,Mr as message}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd/dist/antd.css.proxy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd/dist/antd.css.proxy.js new file mode 100644 index 0000000000000000000000000000000000000000..8335bbb5839edca58d3c2bb0f842fd8edd501276 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/antd/dist/antd.css.proxy.js @@ -0,0 +1,10 @@ +// [snowpack] add styles to the page (skip if no document exists) +if (typeof document !== 'undefined') { + const code = "/*!\n * \n * antd v4.24.5\n * \n * Copyright 2015-present, Alipay, Inc.\n * All rights reserved.\n * \n */\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n[class^=ant-]::-ms-clear,\n[class*= ant-]::-ms-clear,\n[class^=ant-] input::-ms-clear,\n[class*= ant-] input::-ms-clear,\n[class^=ant-] input::-ms-reveal,\n[class*= ant-] input::-ms-reveal {\n display: none;\n}\n/* stylelint-disable property-no-vendor-prefix, at-rule-no-vendor-prefix */\nhtml,\nbody {\n width: 100%;\n height: 100%;\n}\ninput::-ms-clear,\ninput::-ms-reveal {\n display: none;\n}\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n}\nhtml {\n font-family: sans-serif;\n line-height: 1.15;\n -webkit-text-size-adjust: 100%;\n -ms-text-size-adjust: 100%;\n -ms-overflow-style: scrollbar;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\n@-ms-viewport {\n width: device-width;\n}\nbody {\n margin: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n font-variant: tabular-nums;\n line-height: 1.5715;\n background-color: #fff;\n font-feature-settings: 'tnum';\n}\n[tabindex='-1']:focus {\n outline: none !important;\n}\nhr {\n box-sizing: content-box;\n height: 0;\n overflow: visible;\n}\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n margin-top: 0;\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n}\np {\n margin-top: 0;\n margin-bottom: 1em;\n}\nabbr[title],\nabbr[data-original-title] {\n text-decoration: underline;\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n border-bottom: 0;\n cursor: help;\n}\naddress {\n margin-bottom: 1em;\n font-style: normal;\n line-height: inherit;\n}\ninput[type='text'],\ninput[type='password'],\ninput[type='number'],\ntextarea {\n -webkit-appearance: none;\n}\nol,\nul,\ndl {\n margin-top: 0;\n margin-bottom: 1em;\n}\nol ol,\nul ul,\nol ul,\nul ol {\n margin-bottom: 0;\n}\ndt {\n font-weight: 500;\n}\ndd {\n margin-bottom: 0.5em;\n margin-left: 0;\n}\nblockquote {\n margin: 0 0 1em;\n}\ndfn {\n font-style: italic;\n}\nb,\nstrong {\n font-weight: bolder;\n}\nsmall {\n font-size: 80%;\n}\nsub,\nsup {\n position: relative;\n font-size: 75%;\n line-height: 0;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\na {\n color: #1890ff;\n text-decoration: none;\n background-color: transparent;\n outline: none;\n cursor: pointer;\n transition: color 0.3s;\n -webkit-text-decoration-skip: objects;\n}\na:hover {\n color: #40a9ff;\n}\na:active {\n color: #096dd9;\n}\na:active,\na:hover {\n text-decoration: none;\n outline: 0;\n}\na:focus {\n text-decoration: none;\n outline: 0;\n}\na[disabled] {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\npre,\ncode,\nkbd,\nsamp {\n font-size: 1em;\n font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;\n}\npre {\n margin-top: 0;\n margin-bottom: 1em;\n overflow: auto;\n}\nfigure {\n margin: 0 0 1em;\n}\nimg {\n vertical-align: middle;\n border-style: none;\n}\na,\narea,\nbutton,\n[role='button'],\ninput:not([type='range']),\nlabel,\nselect,\nsummary,\ntextarea {\n touch-action: manipulation;\n}\ntable {\n border-collapse: collapse;\n}\ncaption {\n padding-top: 0.75em;\n padding-bottom: 0.3em;\n color: rgba(0, 0, 0, 0.45);\n text-align: left;\n caption-side: bottom;\n}\ninput,\nbutton,\nselect,\noptgroup,\ntextarea {\n margin: 0;\n color: inherit;\n font-size: inherit;\n font-family: inherit;\n line-height: inherit;\n}\nbutton,\ninput {\n overflow: visible;\n}\nbutton,\nselect {\n text-transform: none;\n}\nbutton,\nhtml [type=\"button\"],\n[type=\"reset\"],\n[type=\"submit\"] {\n -webkit-appearance: button;\n}\nbutton::-moz-focus-inner,\n[type='button']::-moz-focus-inner,\n[type='reset']::-moz-focus-inner,\n[type='submit']::-moz-focus-inner {\n padding: 0;\n border-style: none;\n}\ninput[type='radio'],\ninput[type='checkbox'] {\n box-sizing: border-box;\n padding: 0;\n}\ninput[type='date'],\ninput[type='time'],\ninput[type='datetime-local'],\ninput[type='month'] {\n -webkit-appearance: listbox;\n}\ntextarea {\n overflow: auto;\n resize: vertical;\n}\nfieldset {\n min-width: 0;\n margin: 0;\n padding: 0;\n border: 0;\n}\nlegend {\n display: block;\n width: 100%;\n max-width: 100%;\n margin-bottom: 0.5em;\n padding: 0;\n color: inherit;\n font-size: 1.5em;\n line-height: inherit;\n white-space: normal;\n}\nprogress {\n vertical-align: baseline;\n}\n[type='number']::-webkit-inner-spin-button,\n[type='number']::-webkit-outer-spin-button {\n height: auto;\n}\n[type='search'] {\n outline-offset: -2px;\n -webkit-appearance: none;\n}\n[type='search']::-webkit-search-cancel-button,\n[type='search']::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-file-upload-button {\n font: inherit;\n -webkit-appearance: button;\n}\noutput {\n display: inline-block;\n}\nsummary {\n display: list-item;\n}\ntemplate {\n display: none;\n}\n[hidden] {\n display: none !important;\n}\nmark {\n padding: 0.2em;\n background-color: #feffe6;\n}\n::-moz-selection {\n color: #fff;\n background: #1890ff;\n}\n::selection {\n color: #fff;\n background: #1890ff;\n}\n.clearfix::before {\n display: table;\n content: '';\n}\n.clearfix::after {\n display: table;\n clear: both;\n content: '';\n}\n.anticon {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizelegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.anticon > * {\n line-height: 1;\n}\n.anticon svg {\n display: inline-block;\n}\n.anticon::before {\n display: none;\n}\n.anticon .anticon-icon {\n display: block;\n}\n.anticon > .anticon {\n line-height: 0;\n vertical-align: 0;\n}\n.anticon[tabindex] {\n cursor: pointer;\n}\n.anticon-spin,\n.anticon-spin::before {\n display: inline-block;\n animation: loadingCircle 1s infinite linear;\n}\n.ant-fade-enter,\n.ant-fade-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-fade-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-fade-enter.ant-fade-enter-active,\n.ant-fade-appear.ant-fade-appear-active {\n animation-name: antFadeIn;\n animation-play-state: running;\n}\n.ant-fade-leave.ant-fade-leave-active {\n animation-name: antFadeOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-fade-enter,\n.ant-fade-appear {\n opacity: 0;\n animation-timing-function: linear;\n}\n.ant-fade-leave {\n animation-timing-function: linear;\n}\n@keyframes antFadeIn {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n@keyframes antFadeOut {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n}\n.ant-move-up-enter,\n.ant-move-up-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-up-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-up-enter.ant-move-up-enter-active,\n.ant-move-up-appear.ant-move-up-appear-active {\n animation-name: antMoveUpIn;\n animation-play-state: running;\n}\n.ant-move-up-leave.ant-move-up-leave-active {\n animation-name: antMoveUpOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-move-up-enter,\n.ant-move-up-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-move-up-leave {\n animation-timing-function: cubic-bezier(0.6, 0.04, 0.98, 0.34);\n}\n.ant-move-down-enter,\n.ant-move-down-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-down-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-down-enter.ant-move-down-enter-active,\n.ant-move-down-appear.ant-move-down-appear-active {\n animation-name: antMoveDownIn;\n animation-play-state: running;\n}\n.ant-move-down-leave.ant-move-down-leave-active {\n animation-name: antMoveDownOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-move-down-enter,\n.ant-move-down-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-move-down-leave {\n animation-timing-function: cubic-bezier(0.6, 0.04, 0.98, 0.34);\n}\n.ant-move-left-enter,\n.ant-move-left-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-left-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-left-enter.ant-move-left-enter-active,\n.ant-move-left-appear.ant-move-left-appear-active {\n animation-name: antMoveLeftIn;\n animation-play-state: running;\n}\n.ant-move-left-leave.ant-move-left-leave-active {\n animation-name: antMoveLeftOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-move-left-enter,\n.ant-move-left-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-move-left-leave {\n animation-timing-function: cubic-bezier(0.6, 0.04, 0.98, 0.34);\n}\n.ant-move-right-enter,\n.ant-move-right-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-right-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-move-right-enter.ant-move-right-enter-active,\n.ant-move-right-appear.ant-move-right-appear-active {\n animation-name: antMoveRightIn;\n animation-play-state: running;\n}\n.ant-move-right-leave.ant-move-right-leave-active {\n animation-name: antMoveRightOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-move-right-enter,\n.ant-move-right-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-move-right-leave {\n animation-timing-function: cubic-bezier(0.6, 0.04, 0.98, 0.34);\n}\n@keyframes antMoveDownIn {\n 0% {\n transform: translateY(100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n 100% {\n transform: translateY(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n}\n@keyframes antMoveDownOut {\n 0% {\n transform: translateY(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n 100% {\n transform: translateY(100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n}\n@keyframes antMoveLeftIn {\n 0% {\n transform: translateX(-100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n 100% {\n transform: translateX(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n}\n@keyframes antMoveLeftOut {\n 0% {\n transform: translateX(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n 100% {\n transform: translateX(-100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n}\n@keyframes antMoveRightIn {\n 0% {\n transform: translateX(100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n 100% {\n transform: translateX(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n}\n@keyframes antMoveRightOut {\n 0% {\n transform: translateX(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n 100% {\n transform: translateX(100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n}\n@keyframes antMoveUpIn {\n 0% {\n transform: translateY(-100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n 100% {\n transform: translateY(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n}\n@keyframes antMoveUpOut {\n 0% {\n transform: translateY(0%);\n transform-origin: 0 0;\n opacity: 1;\n }\n 100% {\n transform: translateY(-100%);\n transform-origin: 0 0;\n opacity: 0;\n }\n}\n@keyframes loadingCircle {\n 100% {\n transform: rotate(360deg);\n }\n}\n[ant-click-animating='true'],\n[ant-click-animating-without-extra-node='true'] {\n position: relative;\n}\nhtml {\n --antd-wave-shadow-color: #1890ff;\n --scroll-bar: 0;\n}\n[ant-click-animating-without-extra-node='true']::after,\n.ant-click-animating-node {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: block;\n border-radius: inherit;\n box-shadow: 0 0 0 0 #1890ff;\n box-shadow: 0 0 0 0 var(--antd-wave-shadow-color);\n opacity: 0.2;\n animation: fadeEffect 2s cubic-bezier(0.08, 0.82, 0.17, 1), waveEffect 0.4s cubic-bezier(0.08, 0.82, 0.17, 1);\n animation-fill-mode: forwards;\n content: '';\n pointer-events: none;\n}\n@keyframes waveEffect {\n 100% {\n box-shadow: 0 0 0 #1890ff;\n box-shadow: 0 0 0 6px var(--antd-wave-shadow-color);\n }\n}\n@keyframes fadeEffect {\n 100% {\n opacity: 0;\n }\n}\n.ant-slide-up-enter,\n.ant-slide-up-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-up-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-up-enter.ant-slide-up-enter-active,\n.ant-slide-up-appear.ant-slide-up-appear-active {\n animation-name: antSlideUpIn;\n animation-play-state: running;\n}\n.ant-slide-up-leave.ant-slide-up-leave-active {\n animation-name: antSlideUpOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-slide-up-enter,\n.ant-slide-up-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n}\n.ant-slide-up-leave {\n animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n}\n.ant-slide-down-enter,\n.ant-slide-down-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-down-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-down-enter.ant-slide-down-enter-active,\n.ant-slide-down-appear.ant-slide-down-appear-active {\n animation-name: antSlideDownIn;\n animation-play-state: running;\n}\n.ant-slide-down-leave.ant-slide-down-leave-active {\n animation-name: antSlideDownOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-slide-down-enter,\n.ant-slide-down-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n}\n.ant-slide-down-leave {\n animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n}\n.ant-slide-left-enter,\n.ant-slide-left-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-left-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-left-enter.ant-slide-left-enter-active,\n.ant-slide-left-appear.ant-slide-left-appear-active {\n animation-name: antSlideLeftIn;\n animation-play-state: running;\n}\n.ant-slide-left-leave.ant-slide-left-leave-active {\n animation-name: antSlideLeftOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-slide-left-enter,\n.ant-slide-left-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n}\n.ant-slide-left-leave {\n animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n}\n.ant-slide-right-enter,\n.ant-slide-right-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-right-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-slide-right-enter.ant-slide-right-enter-active,\n.ant-slide-right-appear.ant-slide-right-appear-active {\n animation-name: antSlideRightIn;\n animation-play-state: running;\n}\n.ant-slide-right-leave.ant-slide-right-leave-active {\n animation-name: antSlideRightOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-slide-right-enter,\n.ant-slide-right-appear {\n opacity: 0;\n animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);\n}\n.ant-slide-right-leave {\n animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);\n}\n@keyframes antSlideUpIn {\n 0% {\n transform: scaleY(0.8);\n transform-origin: 0% 0%;\n opacity: 0;\n }\n 100% {\n transform: scaleY(1);\n transform-origin: 0% 0%;\n opacity: 1;\n }\n}\n@keyframes antSlideUpOut {\n 0% {\n transform: scaleY(1);\n transform-origin: 0% 0%;\n opacity: 1;\n }\n 100% {\n transform: scaleY(0.8);\n transform-origin: 0% 0%;\n opacity: 0;\n }\n}\n@keyframes antSlideDownIn {\n 0% {\n transform: scaleY(0.8);\n transform-origin: 100% 100%;\n opacity: 0;\n }\n 100% {\n transform: scaleY(1);\n transform-origin: 100% 100%;\n opacity: 1;\n }\n}\n@keyframes antSlideDownOut {\n 0% {\n transform: scaleY(1);\n transform-origin: 100% 100%;\n opacity: 1;\n }\n 100% {\n transform: scaleY(0.8);\n transform-origin: 100% 100%;\n opacity: 0;\n }\n}\n@keyframes antSlideLeftIn {\n 0% {\n transform: scaleX(0.8);\n transform-origin: 0% 0%;\n opacity: 0;\n }\n 100% {\n transform: scaleX(1);\n transform-origin: 0% 0%;\n opacity: 1;\n }\n}\n@keyframes antSlideLeftOut {\n 0% {\n transform: scaleX(1);\n transform-origin: 0% 0%;\n opacity: 1;\n }\n 100% {\n transform: scaleX(0.8);\n transform-origin: 0% 0%;\n opacity: 0;\n }\n}\n@keyframes antSlideRightIn {\n 0% {\n transform: scaleX(0.8);\n transform-origin: 100% 0%;\n opacity: 0;\n }\n 100% {\n transform: scaleX(1);\n transform-origin: 100% 0%;\n opacity: 1;\n }\n}\n@keyframes antSlideRightOut {\n 0% {\n transform: scaleX(1);\n transform-origin: 100% 0%;\n opacity: 1;\n }\n 100% {\n transform: scaleX(0.8);\n transform-origin: 100% 0%;\n opacity: 0;\n }\n}\n.ant-zoom-enter,\n.ant-zoom-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-enter.ant-zoom-enter-active,\n.ant-zoom-appear.ant-zoom-appear-active {\n animation-name: antZoomIn;\n animation-play-state: running;\n}\n.ant-zoom-leave.ant-zoom-leave-active {\n animation-name: antZoomOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-enter,\n.ant-zoom-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-enter-prepare,\n.ant-zoom-appear-prepare {\n transform: none;\n}\n.ant-zoom-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-big-enter,\n.ant-zoom-big-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-big-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-big-enter.ant-zoom-big-enter-active,\n.ant-zoom-big-appear.ant-zoom-big-appear-active {\n animation-name: antZoomBigIn;\n animation-play-state: running;\n}\n.ant-zoom-big-leave.ant-zoom-big-leave-active {\n animation-name: antZoomBigOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-big-enter,\n.ant-zoom-big-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-big-enter-prepare,\n.ant-zoom-big-appear-prepare {\n transform: none;\n}\n.ant-zoom-big-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-big-fast-enter,\n.ant-zoom-big-fast-appear {\n animation-duration: 0.1s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-big-fast-leave {\n animation-duration: 0.1s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-big-fast-enter.ant-zoom-big-fast-enter-active,\n.ant-zoom-big-fast-appear.ant-zoom-big-fast-appear-active {\n animation-name: antZoomBigIn;\n animation-play-state: running;\n}\n.ant-zoom-big-fast-leave.ant-zoom-big-fast-leave-active {\n animation-name: antZoomBigOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-big-fast-enter,\n.ant-zoom-big-fast-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-big-fast-enter-prepare,\n.ant-zoom-big-fast-appear-prepare {\n transform: none;\n}\n.ant-zoom-big-fast-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-up-enter,\n.ant-zoom-up-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-up-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-up-enter.ant-zoom-up-enter-active,\n.ant-zoom-up-appear.ant-zoom-up-appear-active {\n animation-name: antZoomUpIn;\n animation-play-state: running;\n}\n.ant-zoom-up-leave.ant-zoom-up-leave-active {\n animation-name: antZoomUpOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-up-enter,\n.ant-zoom-up-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-up-enter-prepare,\n.ant-zoom-up-appear-prepare {\n transform: none;\n}\n.ant-zoom-up-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-down-enter,\n.ant-zoom-down-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-down-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-down-enter.ant-zoom-down-enter-active,\n.ant-zoom-down-appear.ant-zoom-down-appear-active {\n animation-name: antZoomDownIn;\n animation-play-state: running;\n}\n.ant-zoom-down-leave.ant-zoom-down-leave-active {\n animation-name: antZoomDownOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-down-enter,\n.ant-zoom-down-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-down-enter-prepare,\n.ant-zoom-down-appear-prepare {\n transform: none;\n}\n.ant-zoom-down-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-left-enter,\n.ant-zoom-left-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-left-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-left-enter.ant-zoom-left-enter-active,\n.ant-zoom-left-appear.ant-zoom-left-appear-active {\n animation-name: antZoomLeftIn;\n animation-play-state: running;\n}\n.ant-zoom-left-leave.ant-zoom-left-leave-active {\n animation-name: antZoomLeftOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-left-enter,\n.ant-zoom-left-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-left-enter-prepare,\n.ant-zoom-left-appear-prepare {\n transform: none;\n}\n.ant-zoom-left-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-zoom-right-enter,\n.ant-zoom-right-appear {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-right-leave {\n animation-duration: 0.2s;\n animation-fill-mode: both;\n animation-play-state: paused;\n}\n.ant-zoom-right-enter.ant-zoom-right-enter-active,\n.ant-zoom-right-appear.ant-zoom-right-appear-active {\n animation-name: antZoomRightIn;\n animation-play-state: running;\n}\n.ant-zoom-right-leave.ant-zoom-right-leave-active {\n animation-name: antZoomRightOut;\n animation-play-state: running;\n pointer-events: none;\n}\n.ant-zoom-right-enter,\n.ant-zoom-right-appear {\n transform: scale(0);\n opacity: 0;\n animation-timing-function: cubic-bezier(0.08, 0.82, 0.17, 1);\n}\n.ant-zoom-right-enter-prepare,\n.ant-zoom-right-appear-prepare {\n transform: none;\n}\n.ant-zoom-right-leave {\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n@keyframes antZoomIn {\n 0% {\n transform: scale(0.2);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n opacity: 1;\n }\n}\n@keyframes antZoomOut {\n 0% {\n transform: scale(1);\n }\n 100% {\n transform: scale(0.2);\n opacity: 0;\n }\n}\n@keyframes antZoomBigIn {\n 0% {\n transform: scale(0.8);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n opacity: 1;\n }\n}\n@keyframes antZoomBigOut {\n 0% {\n transform: scale(1);\n }\n 100% {\n transform: scale(0.8);\n opacity: 0;\n }\n}\n@keyframes antZoomUpIn {\n 0% {\n transform: scale(0.8);\n transform-origin: 50% 0%;\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n transform-origin: 50% 0%;\n }\n}\n@keyframes antZoomUpOut {\n 0% {\n transform: scale(1);\n transform-origin: 50% 0%;\n }\n 100% {\n transform: scale(0.8);\n transform-origin: 50% 0%;\n opacity: 0;\n }\n}\n@keyframes antZoomLeftIn {\n 0% {\n transform: scale(0.8);\n transform-origin: 0% 50%;\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n transform-origin: 0% 50%;\n }\n}\n@keyframes antZoomLeftOut {\n 0% {\n transform: scale(1);\n transform-origin: 0% 50%;\n }\n 100% {\n transform: scale(0.8);\n transform-origin: 0% 50%;\n opacity: 0;\n }\n}\n@keyframes antZoomRightIn {\n 0% {\n transform: scale(0.8);\n transform-origin: 100% 50%;\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n transform-origin: 100% 50%;\n }\n}\n@keyframes antZoomRightOut {\n 0% {\n transform: scale(1);\n transform-origin: 100% 50%;\n }\n 100% {\n transform: scale(0.8);\n transform-origin: 100% 50%;\n opacity: 0;\n }\n}\n@keyframes antZoomDownIn {\n 0% {\n transform: scale(0.8);\n transform-origin: 50% 100%;\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n transform-origin: 50% 100%;\n }\n}\n@keyframes antZoomDownOut {\n 0% {\n transform: scale(1);\n transform-origin: 50% 100%;\n }\n 100% {\n transform: scale(0.8);\n transform-origin: 50% 100%;\n opacity: 0;\n }\n}\n.ant-motion-collapse-legacy {\n overflow: hidden;\n}\n.ant-motion-collapse-legacy-active {\n transition: height 0.2s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) !important;\n}\n.ant-motion-collapse {\n overflow: hidden;\n transition: height 0.2s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) !important;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-affix {\n position: fixed;\n z-index: 10;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-alert {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: flex;\n align-items: center;\n padding: 8px 15px;\n word-wrap: break-word;\n border-radius: 2px;\n}\n.ant-alert-content {\n flex: 1;\n min-width: 0;\n}\n.ant-alert-icon {\n margin-right: 8px;\n}\n.ant-alert-description {\n display: none;\n font-size: 14px;\n line-height: 22px;\n}\n.ant-alert-success {\n background-color: #f6ffed;\n border: 1px solid #b7eb8f;\n}\n.ant-alert-success .ant-alert-icon {\n color: #52c41a;\n}\n.ant-alert-info {\n background-color: #e6f7ff;\n border: 1px solid #91d5ff;\n}\n.ant-alert-info .ant-alert-icon {\n color: #1890ff;\n}\n.ant-alert-warning {\n background-color: #fffbe6;\n border: 1px solid #ffe58f;\n}\n.ant-alert-warning .ant-alert-icon {\n color: #faad14;\n}\n.ant-alert-error {\n background-color: #fff2f0;\n border: 1px solid #ffccc7;\n}\n.ant-alert-error .ant-alert-icon {\n color: #ff4d4f;\n}\n.ant-alert-error .ant-alert-description > pre {\n margin: 0;\n padding: 0;\n}\n.ant-alert-action {\n margin-left: 8px;\n}\n.ant-alert-close-icon {\n margin-left: 8px;\n padding: 0;\n overflow: hidden;\n font-size: 12px;\n line-height: 12px;\n background-color: transparent;\n border: none;\n outline: none;\n cursor: pointer;\n}\n.ant-alert-close-icon .anticon-close {\n color: rgba(0, 0, 0, 0.45);\n transition: color 0.3s;\n}\n.ant-alert-close-icon .anticon-close:hover {\n color: rgba(0, 0, 0, 0.75);\n}\n.ant-alert-close-text {\n color: rgba(0, 0, 0, 0.45);\n transition: color 0.3s;\n}\n.ant-alert-close-text:hover {\n color: rgba(0, 0, 0, 0.75);\n}\n.ant-alert-with-description {\n align-items: flex-start;\n padding: 15px 15px 15px 24px;\n}\n.ant-alert-with-description.ant-alert-no-icon {\n padding: 15px 15px;\n}\n.ant-alert-with-description .ant-alert-icon {\n margin-right: 15px;\n font-size: 24px;\n}\n.ant-alert-with-description .ant-alert-message {\n display: block;\n margin-bottom: 4px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 16px;\n}\n.ant-alert-message {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-alert-with-description .ant-alert-description {\n display: block;\n}\n.ant-alert.ant-alert-motion-leave {\n overflow: hidden;\n opacity: 1;\n transition: max-height 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86), opacity 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86), padding-top 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86), padding-bottom 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86), margin-bottom 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-alert.ant-alert-motion-leave-active {\n max-height: 0;\n margin-bottom: 0 !important;\n padding-top: 0;\n padding-bottom: 0;\n opacity: 0;\n}\n.ant-alert-banner {\n margin-bottom: 0;\n border: 0;\n border-radius: 0;\n}\n.ant-alert.ant-alert-rtl {\n direction: rtl;\n}\n.ant-alert-rtl .ant-alert-icon {\n margin-right: auto;\n margin-left: 8px;\n}\n.ant-alert-rtl .ant-alert-action {\n margin-right: 8px;\n margin-left: auto;\n}\n.ant-alert-rtl .ant-alert-close-icon {\n margin-right: 8px;\n margin-left: auto;\n}\n.ant-alert-rtl.ant-alert-with-description {\n padding-right: 24px;\n padding-left: 15px;\n}\n.ant-alert-rtl.ant-alert-with-description .ant-alert-icon {\n margin-right: auto;\n margin-left: 15px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-anchor {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n padding-left: 2px;\n}\n.ant-anchor-wrapper {\n margin-left: -4px;\n padding-left: 4px;\n overflow: auto;\n background-color: transparent;\n}\n.ant-anchor-ink {\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n}\n.ant-anchor-ink::before {\n position: relative;\n display: block;\n width: 2px;\n height: 100%;\n margin: 0 auto;\n background-color: #f0f0f0;\n content: ' ';\n}\n.ant-anchor-ink-ball {\n position: absolute;\n left: 50%;\n display: none;\n width: 8px;\n height: 8px;\n background-color: #fff;\n border: 2px solid #1890ff;\n border-radius: 8px;\n transform: translateX(-50%);\n transition: top 0.3s ease-in-out;\n}\n.ant-anchor-ink-ball.ant-anchor-ink-ball-visible {\n display: inline-block;\n}\n.ant-anchor-fixed .ant-anchor-ink .ant-anchor-ink-ball {\n display: none;\n}\n.ant-anchor-link {\n padding: 4px 0 4px 16px;\n}\n.ant-anchor-link-title {\n position: relative;\n display: block;\n margin-bottom: 3px;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n white-space: nowrap;\n text-overflow: ellipsis;\n transition: all 0.3s;\n}\n.ant-anchor-link-title:only-child {\n margin-bottom: 0;\n}\n.ant-anchor-link-active > .ant-anchor-link-title {\n color: #1890ff;\n}\n.ant-anchor-link .ant-anchor-link {\n padding-top: 2px;\n padding-bottom: 2px;\n}\n.ant-anchor-rtl {\n direction: rtl;\n}\n.ant-anchor-rtl.ant-anchor-wrapper {\n margin-right: -4px;\n margin-left: 0;\n padding-right: 4px;\n padding-left: 0;\n}\n.ant-anchor-rtl .ant-anchor-ink {\n right: 0;\n left: auto;\n}\n.ant-anchor-rtl .ant-anchor-ink-ball {\n right: 50%;\n left: 0;\n transform: translateX(50%);\n}\n.ant-anchor-rtl .ant-anchor-link {\n padding: 4px 16px 4px 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-select-auto-complete {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n}\n.ant-select-auto-complete .ant-select-clear {\n right: 13px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-select-single .ant-select-selector {\n display: flex;\n}\n.ant-select-single .ant-select-selector .ant-select-selection-search {\n position: absolute;\n top: 0;\n right: 11px;\n bottom: 0;\n left: 11px;\n}\n.ant-select-single .ant-select-selector .ant-select-selection-search-input {\n width: 100%;\n}\n.ant-select-single .ant-select-selector .ant-select-selection-item,\n.ant-select-single .ant-select-selector .ant-select-selection-placeholder {\n padding: 0;\n line-height: 30px;\n transition: all 0.3s;\n}\n.ant-select-single .ant-select-selector .ant-select-selection-item {\n position: relative;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-select-single .ant-select-selector .ant-select-selection-placeholder {\n transition: none;\n pointer-events: none;\n}\n.ant-select-single .ant-select-selector::after,\n.ant-select-single .ant-select-selector .ant-select-selection-item::after,\n.ant-select-single .ant-select-selector .ant-select-selection-placeholder::after {\n display: inline-block;\n width: 0;\n visibility: hidden;\n content: '\\a0';\n}\n.ant-select-single.ant-select-show-arrow .ant-select-selection-search {\n right: 25px;\n}\n.ant-select-single.ant-select-show-arrow .ant-select-selection-item,\n.ant-select-single.ant-select-show-arrow .ant-select-selection-placeholder {\n padding-right: 18px;\n}\n.ant-select-single.ant-select-open .ant-select-selection-item {\n color: #bfbfbf;\n}\n.ant-select-single:not(.ant-select-customize-input) .ant-select-selector {\n width: 100%;\n height: 32px;\n padding: 0 11px;\n}\n.ant-select-single:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-search-input {\n height: 30px;\n}\n.ant-select-single:not(.ant-select-customize-input) .ant-select-selector::after {\n line-height: 30px;\n}\n.ant-select-single.ant-select-customize-input .ant-select-selector::after {\n display: none;\n}\n.ant-select-single.ant-select-customize-input .ant-select-selector .ant-select-selection-search {\n position: static;\n width: 100%;\n}\n.ant-select-single.ant-select-customize-input .ant-select-selector .ant-select-selection-placeholder {\n position: absolute;\n right: 0;\n left: 0;\n padding: 0 11px;\n}\n.ant-select-single.ant-select-customize-input .ant-select-selector .ant-select-selection-placeholder::after {\n display: none;\n}\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input) .ant-select-selector {\n height: 40px;\n}\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input) .ant-select-selector::after,\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-item,\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-placeholder {\n line-height: 38px;\n}\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input):not(.ant-select-customize-input) .ant-select-selection-search-input {\n height: 38px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selector {\n height: 24px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selector::after,\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-item,\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-placeholder {\n line-height: 22px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input):not(.ant-select-customize-input) .ant-select-selection-search-input {\n height: 22px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selection-search {\n right: 7px;\n left: 7px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input) .ant-select-selector {\n padding: 0 7px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-search {\n right: 28px;\n}\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-item,\n.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-placeholder {\n padding-right: 21px;\n}\n.ant-select-single.ant-select-lg:not(.ant-select-customize-input) .ant-select-selector {\n padding: 0 11px;\n}\n/**\n * Do not merge `height` & `line-height` under style with `selection` & `search`,\n * since chrome may update to redesign with its align logic.\n */\n.ant-select-selection-overflow {\n position: relative;\n display: flex;\n flex: auto;\n flex-wrap: wrap;\n max-width: 100%;\n}\n.ant-select-selection-overflow-item {\n flex: none;\n align-self: center;\n max-width: 100%;\n}\n.ant-select-multiple .ant-select-selector {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n padding: 1px 4px;\n}\n.ant-select-show-search.ant-select-multiple .ant-select-selector {\n cursor: text;\n}\n.ant-select-disabled.ant-select-multiple .ant-select-selector {\n background: #f5f5f5;\n cursor: not-allowed;\n}\n.ant-select-multiple .ant-select-selector::after {\n display: inline-block;\n width: 0;\n margin: 2px 0;\n line-height: 24px;\n content: '\\a0';\n}\n.ant-select-multiple.ant-select-show-arrow .ant-select-selector,\n.ant-select-multiple.ant-select-allow-clear .ant-select-selector {\n padding-right: 24px;\n}\n.ant-select-multiple .ant-select-selection-item {\n position: relative;\n display: flex;\n flex: none;\n box-sizing: border-box;\n max-width: 100%;\n height: 24px;\n margin-top: 2px;\n margin-bottom: 2px;\n line-height: 22px;\n background: #f5f5f5;\n border: 1px solid #f0f0f0;\n border-radius: 2px;\n cursor: default;\n transition: font-size 0.3s, line-height 0.3s, height 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n -webkit-margin-end: 4px;\n margin-inline-end: 4px;\n -webkit-padding-start: 8px;\n padding-inline-start: 8px;\n -webkit-padding-end: 4px;\n padding-inline-end: 4px;\n}\n.ant-select-disabled.ant-select-multiple .ant-select-selection-item {\n color: #bfbfbf;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-select-multiple .ant-select-selection-item-content {\n display: inline-block;\n margin-right: 4px;\n overflow: hidden;\n white-space: pre;\n text-overflow: ellipsis;\n}\n.ant-select-multiple .ant-select-selection-item-remove {\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizelegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n display: inline-block;\n color: rgba(0, 0, 0, 0.45);\n font-weight: bold;\n font-size: 10px;\n line-height: inherit;\n cursor: pointer;\n}\n.ant-select-multiple .ant-select-selection-item-remove > * {\n line-height: 1;\n}\n.ant-select-multiple .ant-select-selection-item-remove svg {\n display: inline-block;\n}\n.ant-select-multiple .ant-select-selection-item-remove::before {\n display: none;\n}\n.ant-select-multiple .ant-select-selection-item-remove .ant-select-multiple .ant-select-selection-item-remove-icon {\n display: block;\n}\n.ant-select-multiple .ant-select-selection-item-remove > .anticon {\n vertical-align: middle;\n}\n.ant-select-multiple .ant-select-selection-item-remove:hover {\n color: rgba(0, 0, 0, 0.75);\n}\n.ant-select-multiple .ant-select-selection-overflow-item + .ant-select-selection-overflow-item .ant-select-selection-search {\n -webkit-margin-start: 0;\n margin-inline-start: 0;\n}\n.ant-select-multiple .ant-select-selection-search {\n position: relative;\n max-width: 100%;\n -webkit-margin-start: 7px;\n margin-inline-start: 7px;\n}\n.ant-select-multiple .ant-select-selection-search-input,\n.ant-select-multiple .ant-select-selection-search-mirror {\n height: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n line-height: 24px;\n transition: all 0.3s;\n}\n.ant-select-multiple .ant-select-selection-search-input {\n width: 100%;\n min-width: 4.1px;\n}\n.ant-select-multiple .ant-select-selection-search-mirror {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 999;\n white-space: pre;\n visibility: hidden;\n}\n.ant-select-multiple .ant-select-selection-placeholder {\n position: absolute;\n top: 50%;\n right: 11px;\n left: 11px;\n transform: translateY(-50%);\n transition: all 0.3s;\n}\n.ant-select-multiple.ant-select-lg .ant-select-selector::after {\n line-height: 32px;\n}\n.ant-select-multiple.ant-select-lg .ant-select-selection-item {\n height: 32px;\n line-height: 30px;\n}\n.ant-select-multiple.ant-select-lg .ant-select-selection-search {\n height: 32px;\n line-height: 32px;\n}\n.ant-select-multiple.ant-select-lg .ant-select-selection-search-input,\n.ant-select-multiple.ant-select-lg .ant-select-selection-search-mirror {\n height: 32px;\n line-height: 30px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selector::after {\n line-height: 16px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selection-item {\n height: 16px;\n line-height: 14px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selection-search {\n height: 16px;\n line-height: 16px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selection-search-input,\n.ant-select-multiple.ant-select-sm .ant-select-selection-search-mirror {\n height: 16px;\n line-height: 14px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selection-placeholder {\n left: 7px;\n}\n.ant-select-multiple.ant-select-sm .ant-select-selection-search {\n -webkit-margin-start: 3px;\n margin-inline-start: 3px;\n}\n.ant-select-multiple.ant-select-lg .ant-select-selection-item {\n height: 32px;\n line-height: 32px;\n}\n.ant-select-disabled .ant-select-selection-item-remove {\n display: none;\n}\n.ant-select-status-error.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer) .ant-select-selector {\n background-color: #fff;\n border-color: #ff4d4f !important;\n}\n.ant-select-status-error.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer).ant-select-open .ant-select-selector,\n.ant-select-status-error.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer).ant-select-focused .ant-select-selector {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-select-status-warning.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer) .ant-select-selector {\n background-color: #fff;\n border-color: #faad14 !important;\n}\n.ant-select-status-warning.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer).ant-select-open .ant-select-selector,\n.ant-select-status-warning.ant-select:not(.ant-select-disabled):not(.ant-select-customize-input):not(.ant-pagination-size-changer).ant-select-focused .ant-select-selector {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-select-status-error.ant-select-has-feedback .ant-select-clear,\n.ant-select-status-warning.ant-select-has-feedback .ant-select-clear,\n.ant-select-status-success.ant-select-has-feedback .ant-select-clear,\n.ant-select-status-validating.ant-select-has-feedback .ant-select-clear {\n right: 32px;\n}\n.ant-select-status-error.ant-select-has-feedback .ant-select-selection-selected-value,\n.ant-select-status-warning.ant-select-has-feedback .ant-select-selection-selected-value,\n.ant-select-status-success.ant-select-has-feedback .ant-select-selection-selected-value,\n.ant-select-status-validating.ant-select-has-feedback .ant-select-selection-selected-value {\n padding-right: 42px;\n}\n/* Reset search input style */\n.ant-select {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-block;\n cursor: pointer;\n}\n.ant-select:not(.ant-select-customize-input) .ant-select-selector {\n position: relative;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-select:not(.ant-select-customize-input) .ant-select-selector input {\n cursor: pointer;\n}\n.ant-select-show-search.ant-select:not(.ant-select-customize-input) .ant-select-selector {\n cursor: text;\n}\n.ant-select-show-search.ant-select:not(.ant-select-customize-input) .ant-select-selector input {\n cursor: auto;\n}\n.ant-select-focused:not(.ant-select-disabled).ant-select:not(.ant-select-customize-input) .ant-select-selector {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector {\n color: rgba(0, 0, 0, 0.25);\n background: #f5f5f5;\n cursor: not-allowed;\n}\n.ant-select-multiple.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector {\n background: #f5f5f5;\n}\n.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector input {\n cursor: not-allowed;\n}\n.ant-select:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-search-input {\n margin: 0;\n padding: 0;\n background: transparent;\n border: none;\n outline: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n}\n.ant-select:not(.ant-select-customize-input) .ant-select-selector .ant-select-selection-search-input::-webkit-search-cancel-button {\n display: none;\n /* stylelint-disable-next-line property-no-vendor-prefix */\n -webkit-appearance: none;\n}\n.ant-select:not(.ant-select-disabled):hover .ant-select-selector {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-select-selection-item {\n flex: 1;\n overflow: hidden;\n font-weight: normal;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n@media all and (-ms-high-contrast: none) {\n .ant-select-selection-item *::-ms-backdrop,\n .ant-select-selection-item {\n flex: auto;\n }\n}\n.ant-select-selection-placeholder {\n flex: 1;\n overflow: hidden;\n color: #bfbfbf;\n white-space: nowrap;\n text-overflow: ellipsis;\n pointer-events: none;\n}\n@media all and (-ms-high-contrast: none) {\n .ant-select-selection-placeholder *::-ms-backdrop,\n .ant-select-selection-placeholder {\n flex: auto;\n }\n}\n.ant-select-arrow {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizelegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n position: absolute;\n top: 50%;\n right: 11px;\n display: flex;\n align-items: center;\n height: 12px;\n margin-top: -6px;\n color: rgba(0, 0, 0, 0.25);\n font-size: 12px;\n line-height: 1;\n text-align: center;\n pointer-events: none;\n}\n.ant-select-arrow > * {\n line-height: 1;\n}\n.ant-select-arrow svg {\n display: inline-block;\n}\n.ant-select-arrow::before {\n display: none;\n}\n.ant-select-arrow .ant-select-arrow-icon {\n display: block;\n}\n.ant-select-arrow .anticon {\n vertical-align: top;\n transition: transform 0.3s;\n}\n.ant-select-arrow .anticon > svg {\n vertical-align: top;\n}\n.ant-select-arrow .anticon:not(.ant-select-suffix) {\n pointer-events: auto;\n}\n.ant-select-disabled .ant-select-arrow {\n cursor: not-allowed;\n}\n.ant-select-arrow > *:not(:last-child) {\n -webkit-margin-end: 8px;\n margin-inline-end: 8px;\n}\n.ant-select-clear {\n position: absolute;\n top: 50%;\n right: 11px;\n z-index: 1;\n display: inline-block;\n width: 12px;\n height: 12px;\n margin-top: -6px;\n color: rgba(0, 0, 0, 0.25);\n font-size: 12px;\n font-style: normal;\n line-height: 1;\n text-align: center;\n text-transform: none;\n background: #fff;\n cursor: pointer;\n opacity: 0;\n transition: color 0.3s ease, opacity 0.15s ease;\n text-rendering: auto;\n}\n.ant-select-clear::before {\n display: block;\n}\n.ant-select-clear:hover {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-select:hover .ant-select-clear {\n opacity: 1;\n}\n.ant-select-dropdown {\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: -9999px;\n left: -9999px;\n z-index: 1050;\n box-sizing: border-box;\n padding: 4px 0;\n overflow: hidden;\n font-size: 14px;\n font-variant: initial;\n background-color: #fff;\n border-radius: 2px;\n outline: none;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-select-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-select-dropdown-placement-bottomLeft,\n.ant-select-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-select-dropdown-placement-bottomLeft {\n animation-name: antSlideUpIn;\n}\n.ant-select-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-select-dropdown-placement-topLeft,\n.ant-select-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-select-dropdown-placement-topLeft {\n animation-name: antSlideDownIn;\n}\n.ant-select-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-select-dropdown-placement-bottomLeft {\n animation-name: antSlideUpOut;\n}\n.ant-select-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-select-dropdown-placement-topLeft {\n animation-name: antSlideDownOut;\n}\n.ant-select-dropdown-hidden {\n display: none;\n}\n.ant-select-dropdown-empty {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-select-item-empty {\n position: relative;\n display: block;\n min-height: 32px;\n padding: 5px 12px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n line-height: 22px;\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-select-item {\n position: relative;\n display: block;\n min-height: 32px;\n padding: 5px 12px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n transition: background 0.3s ease;\n}\n.ant-select-item-group {\n color: rgba(0, 0, 0, 0.45);\n font-size: 12px;\n cursor: default;\n}\n.ant-select-item-option {\n display: flex;\n}\n.ant-select-item-option-content {\n flex: auto;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-select-item-option-state {\n flex: none;\n}\n.ant-select-item-option-active:not(.ant-select-item-option-disabled) {\n background-color: #f5f5f5;\n}\n.ant-select-item-option-selected:not(.ant-select-item-option-disabled) {\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n background-color: #e6f7ff;\n}\n.ant-select-item-option-selected:not(.ant-select-item-option-disabled) .ant-select-item-option-state {\n color: #1890ff;\n}\n.ant-select-item-option-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-select-item-option-disabled.ant-select-item-option-selected {\n background-color: #f5f5f5;\n}\n.ant-select-item-option-grouped {\n padding-left: 24px;\n}\n.ant-select-lg {\n font-size: 16px;\n}\n.ant-select-borderless .ant-select-selector {\n background-color: transparent !important;\n border-color: transparent !important;\n box-shadow: none !important;\n}\n.ant-select.ant-select-in-form-item {\n width: 100%;\n}\n.ant-select-compact-item:not(.ant-select-compact-last-item) {\n margin-right: -1px;\n}\n.ant-select-compact-item:not(.ant-select-compact-last-item).ant-select-compact-item-rtl {\n margin-right: 0;\n margin-left: -1px;\n}\n.ant-select-compact-item:hover > *,\n.ant-select-compact-item:focus > *,\n.ant-select-compact-item:active > * {\n z-index: 2;\n}\n.ant-select-compact-item.ant-select-focused > * {\n z-index: 2;\n}\n.ant-select-compact-item[disabled] > * {\n z-index: 0;\n}\n.ant-select-compact-item:not(.ant-select-compact-first-item):not(.ant-select-compact-last-item).ant-select > .ant-select-selector {\n border-radius: 0;\n}\n.ant-select-compact-item.ant-select-compact-first-item.ant-select:not(.ant-select-compact-last-item):not(.ant-select-compact-item-rtl) > .ant-select-selector {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-select-compact-item.ant-select-compact-last-item.ant-select:not(.ant-select-compact-first-item):not(.ant-select-compact-item-rtl) > .ant-select-selector {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-select-compact-item.ant-select.ant-select-compact-first-item.ant-select-compact-item-rtl:not(.ant-select-compact-last-item) > .ant-select-selector {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-select-compact-item.ant-select.ant-select-compact-last-item.ant-select-compact-item-rtl:not(.ant-select-compact-first-item) > .ant-select-selector {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-select-rtl {\n direction: rtl;\n}\n.ant-select-rtl .ant-select-arrow {\n right: initial;\n left: 11px;\n}\n.ant-select-rtl .ant-select-clear {\n right: initial;\n left: 11px;\n}\n.ant-select-dropdown-rtl {\n direction: rtl;\n}\n.ant-select-dropdown-rtl .ant-select-item-option-grouped {\n padding-right: 24px;\n padding-left: 12px;\n}\n.ant-select-rtl.ant-select-multiple.ant-select-show-arrow .ant-select-selector,\n.ant-select-rtl.ant-select-multiple.ant-select-allow-clear .ant-select-selector {\n padding-right: 4px;\n padding-left: 24px;\n}\n.ant-select-rtl.ant-select-multiple .ant-select-selection-item {\n text-align: right;\n}\n.ant-select-rtl.ant-select-multiple .ant-select-selection-item-content {\n margin-right: 0;\n margin-left: 4px;\n text-align: right;\n}\n.ant-select-rtl.ant-select-multiple .ant-select-selection-search-mirror {\n right: 0;\n left: auto;\n}\n.ant-select-rtl.ant-select-multiple .ant-select-selection-placeholder {\n right: 11px;\n left: auto;\n}\n.ant-select-rtl.ant-select-multiple.ant-select-sm .ant-select-selection-placeholder {\n right: 7px;\n}\n.ant-select-rtl.ant-select-single .ant-select-selector .ant-select-selection-item,\n.ant-select-rtl.ant-select-single .ant-select-selector .ant-select-selection-placeholder {\n right: 0;\n left: 9px;\n text-align: right;\n}\n.ant-select-rtl.ant-select-single.ant-select-show-arrow .ant-select-selection-search {\n right: 11px;\n left: 25px;\n}\n.ant-select-rtl.ant-select-single.ant-select-show-arrow .ant-select-selection-item,\n.ant-select-rtl.ant-select-single.ant-select-show-arrow .ant-select-selection-placeholder {\n padding-right: 0;\n padding-left: 18px;\n}\n.ant-select-rtl.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-search {\n right: 6px;\n}\n.ant-select-rtl.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-item,\n.ant-select-rtl.ant-select-single.ant-select-sm:not(.ant-select-customize-input).ant-select-show-arrow .ant-select-selection-placeholder {\n padding-right: 0;\n padding-left: 21px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-empty {\n margin: 0 8px;\n font-size: 14px;\n line-height: 1.5715;\n text-align: center;\n}\n.ant-empty-image {\n height: 100px;\n margin-bottom: 8px;\n}\n.ant-empty-image img {\n height: 100%;\n}\n.ant-empty-image svg {\n height: 100%;\n margin: auto;\n}\n.ant-empty-footer {\n margin-top: 16px;\n}\n.ant-empty-normal {\n margin: 32px 0;\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-empty-normal .ant-empty-image {\n height: 40px;\n}\n.ant-empty-small {\n margin: 8px 0;\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-empty-small .ant-empty-image {\n height: 35px;\n}\n.ant-empty-img-default-ellipse {\n fill: #f5f5f5;\n fill-opacity: 0.8;\n}\n.ant-empty-img-default-path-1 {\n fill: #aeb8c2;\n}\n.ant-empty-img-default-path-2 {\n fill: url('#linearGradient-1');\n}\n.ant-empty-img-default-path-3 {\n fill: #f5f5f7;\n}\n.ant-empty-img-default-path-4 {\n fill: #dce0e6;\n}\n.ant-empty-img-default-path-5 {\n fill: #dce0e6;\n}\n.ant-empty-img-default-g {\n fill: #fff;\n}\n.ant-empty-img-simple-ellipse {\n fill: #f5f5f5;\n}\n.ant-empty-img-simple-g {\n stroke: #d9d9d9;\n}\n.ant-empty-img-simple-path {\n fill: #fafafa;\n}\n.ant-empty-rtl {\n direction: rtl;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-avatar {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-block;\n overflow: hidden;\n color: #fff;\n white-space: nowrap;\n text-align: center;\n vertical-align: middle;\n background: #ccc;\n width: 32px;\n height: 32px;\n line-height: 32px;\n border-radius: 50%;\n}\n.ant-avatar-image {\n background: transparent;\n}\n.ant-avatar .ant-image-img {\n display: block;\n}\n.ant-avatar-string {\n position: absolute;\n left: 50%;\n transform-origin: 0 center;\n}\n.ant-avatar.ant-avatar-icon {\n font-size: 18px;\n}\n.ant-avatar.ant-avatar-icon > .anticon {\n margin: 0;\n}\n.ant-avatar-lg {\n width: 40px;\n height: 40px;\n line-height: 40px;\n border-radius: 50%;\n}\n.ant-avatar-lg-string {\n position: absolute;\n left: 50%;\n transform-origin: 0 center;\n}\n.ant-avatar-lg.ant-avatar-icon {\n font-size: 24px;\n}\n.ant-avatar-lg.ant-avatar-icon > .anticon {\n margin: 0;\n}\n.ant-avatar-sm {\n width: 24px;\n height: 24px;\n line-height: 24px;\n border-radius: 50%;\n}\n.ant-avatar-sm-string {\n position: absolute;\n left: 50%;\n transform-origin: 0 center;\n}\n.ant-avatar-sm.ant-avatar-icon {\n font-size: 14px;\n}\n.ant-avatar-sm.ant-avatar-icon > .anticon {\n margin: 0;\n}\n.ant-avatar-square {\n border-radius: 2px;\n}\n.ant-avatar > img {\n display: block;\n width: 100%;\n height: 100%;\n -o-object-fit: cover;\n object-fit: cover;\n}\n.ant-avatar-group {\n display: inline-flex;\n}\n.ant-avatar-group .ant-avatar {\n border: 1px solid #fff;\n}\n.ant-avatar-group .ant-avatar:not(:first-child) {\n margin-left: -8px;\n}\n.ant-avatar-group-popover .ant-avatar + .ant-avatar {\n margin-left: 3px;\n}\n.ant-avatar-group-rtl .ant-avatar:not(:first-child) {\n margin-right: -8px;\n margin-left: 0;\n}\n.ant-avatar-group-popover.ant-popover-rtl .ant-avatar + .ant-avatar {\n margin-right: 3px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-popover {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1030;\n font-weight: normal;\n white-space: normal;\n text-align: left;\n cursor: auto;\n -webkit-user-select: text;\n -moz-user-select: text;\n -ms-user-select: text;\n user-select: text;\n}\n.ant-popover-content {\n position: relative;\n}\n.ant-popover::after {\n position: absolute;\n background: rgba(255, 255, 255, 0.01);\n content: '';\n}\n.ant-popover-hidden {\n display: none;\n}\n.ant-popover-placement-top,\n.ant-popover-placement-topLeft,\n.ant-popover-placement-topRight {\n padding-bottom: 15.3137085px;\n}\n.ant-popover-placement-right,\n.ant-popover-placement-rightTop,\n.ant-popover-placement-rightBottom {\n padding-left: 15.3137085px;\n}\n.ant-popover-placement-bottom,\n.ant-popover-placement-bottomLeft,\n.ant-popover-placement-bottomRight {\n padding-top: 15.3137085px;\n}\n.ant-popover-placement-left,\n.ant-popover-placement-leftTop,\n.ant-popover-placement-leftBottom {\n padding-right: 15.3137085px;\n}\n.ant-popover-inner {\n background-color: #fff;\n background-clip: padding-box;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {\n .ant-popover {\n /* IE10+ */\n }\n .ant-popover-inner {\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n }\n}\n.ant-popover-title {\n min-width: 177px;\n min-height: 32px;\n margin: 0;\n padding: 5px 16px 4px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-popover-inner-content {\n padding: 12px 16px;\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-popover-message {\n display: flex;\n padding: 4px 0 12px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n}\n.ant-popover-message-icon {\n display: inline-block;\n margin-right: 8px;\n color: #faad14;\n font-size: 14px;\n}\n.ant-popover-buttons {\n margin-bottom: 4px;\n text-align: right;\n}\n.ant-popover-buttons button:not(:first-child) {\n margin-left: 8px;\n}\n.ant-popover-arrow {\n position: absolute;\n display: block;\n width: 22px;\n height: 22px;\n overflow: hidden;\n background: transparent;\n pointer-events: none;\n}\n.ant-popover-arrow-content {\n --antd-arrow-background-color: #fff;\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: block;\n width: 11.3137085px;\n height: 11.3137085px;\n margin: auto;\n content: '';\n pointer-events: auto;\n border-radius: 0 0 2px;\n pointer-events: none;\n}\n.ant-popover-arrow-content::before {\n position: absolute;\n top: -11.3137085px;\n left: -11.3137085px;\n width: 33.9411255px;\n height: 33.9411255px;\n background: var(--antd-arrow-background-color);\n background-repeat: no-repeat;\n background-position: -10px -10px;\n content: '';\n -webkit-clip-path: inset(33% 33%);\n clip-path: inset(33% 33%);\n -webkit-clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n}\n.ant-popover-placement-top .ant-popover-arrow,\n.ant-popover-placement-topLeft .ant-popover-arrow,\n.ant-popover-placement-topRight .ant-popover-arrow {\n bottom: 0;\n transform: translateY(100%);\n}\n.ant-popover-placement-top .ant-popover-arrow-content,\n.ant-popover-placement-topLeft .ant-popover-arrow-content,\n.ant-popover-placement-topRight .ant-popover-arrow-content {\n box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n transform: translateY(-11px) rotate(45deg);\n}\n.ant-popover-placement-top .ant-popover-arrow {\n left: 50%;\n transform: translateY(100%) translateX(-50%);\n}\n.ant-popover-placement-topLeft .ant-popover-arrow {\n left: 16px;\n}\n.ant-popover-placement-topRight .ant-popover-arrow {\n right: 16px;\n}\n.ant-popover-placement-right .ant-popover-arrow,\n.ant-popover-placement-rightTop .ant-popover-arrow,\n.ant-popover-placement-rightBottom .ant-popover-arrow {\n left: 0;\n transform: translateX(-100%);\n}\n.ant-popover-placement-right .ant-popover-arrow-content,\n.ant-popover-placement-rightTop .ant-popover-arrow-content,\n.ant-popover-placement-rightBottom .ant-popover-arrow-content {\n box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n transform: translateX(11px) rotate(135deg);\n}\n.ant-popover-placement-right .ant-popover-arrow {\n top: 50%;\n transform: translateX(-100%) translateY(-50%);\n}\n.ant-popover-placement-rightTop .ant-popover-arrow {\n top: 12px;\n}\n.ant-popover-placement-rightBottom .ant-popover-arrow {\n bottom: 12px;\n}\n.ant-popover-placement-bottom .ant-popover-arrow,\n.ant-popover-placement-bottomLeft .ant-popover-arrow,\n.ant-popover-placement-bottomRight .ant-popover-arrow {\n top: 0;\n transform: translateY(-100%);\n}\n.ant-popover-placement-bottom .ant-popover-arrow-content,\n.ant-popover-placement-bottomLeft .ant-popover-arrow-content,\n.ant-popover-placement-bottomRight .ant-popover-arrow-content {\n box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.06);\n transform: translateY(11px) rotate(-135deg);\n}\n.ant-popover-placement-bottom .ant-popover-arrow {\n left: 50%;\n transform: translateY(-100%) translateX(-50%);\n}\n.ant-popover-placement-bottomLeft .ant-popover-arrow {\n left: 16px;\n}\n.ant-popover-placement-bottomRight .ant-popover-arrow {\n right: 16px;\n}\n.ant-popover-placement-left .ant-popover-arrow,\n.ant-popover-placement-leftTop .ant-popover-arrow,\n.ant-popover-placement-leftBottom .ant-popover-arrow {\n right: 0;\n transform: translateX(100%);\n}\n.ant-popover-placement-left .ant-popover-arrow-content,\n.ant-popover-placement-leftTop .ant-popover-arrow-content,\n.ant-popover-placement-leftBottom .ant-popover-arrow-content {\n box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n transform: translateX(-11px) rotate(-45deg);\n}\n.ant-popover-placement-left .ant-popover-arrow {\n top: 50%;\n transform: translateX(100%) translateY(-50%);\n}\n.ant-popover-placement-leftTop .ant-popover-arrow {\n top: 12px;\n}\n.ant-popover-placement-leftBottom .ant-popover-arrow {\n bottom: 12px;\n}\n.ant-popover-pink .ant-popover-inner {\n background-color: #eb2f96;\n}\n.ant-popover-pink .ant-popover-arrow-content {\n background-color: #eb2f96;\n}\n.ant-popover-magenta .ant-popover-inner {\n background-color: #eb2f96;\n}\n.ant-popover-magenta .ant-popover-arrow-content {\n background-color: #eb2f96;\n}\n.ant-popover-red .ant-popover-inner {\n background-color: #f5222d;\n}\n.ant-popover-red .ant-popover-arrow-content {\n background-color: #f5222d;\n}\n.ant-popover-volcano .ant-popover-inner {\n background-color: #fa541c;\n}\n.ant-popover-volcano .ant-popover-arrow-content {\n background-color: #fa541c;\n}\n.ant-popover-orange .ant-popover-inner {\n background-color: #fa8c16;\n}\n.ant-popover-orange .ant-popover-arrow-content {\n background-color: #fa8c16;\n}\n.ant-popover-yellow .ant-popover-inner {\n background-color: #fadb14;\n}\n.ant-popover-yellow .ant-popover-arrow-content {\n background-color: #fadb14;\n}\n.ant-popover-gold .ant-popover-inner {\n background-color: #faad14;\n}\n.ant-popover-gold .ant-popover-arrow-content {\n background-color: #faad14;\n}\n.ant-popover-cyan .ant-popover-inner {\n background-color: #13c2c2;\n}\n.ant-popover-cyan .ant-popover-arrow-content {\n background-color: #13c2c2;\n}\n.ant-popover-lime .ant-popover-inner {\n background-color: #a0d911;\n}\n.ant-popover-lime .ant-popover-arrow-content {\n background-color: #a0d911;\n}\n.ant-popover-green .ant-popover-inner {\n background-color: #52c41a;\n}\n.ant-popover-green .ant-popover-arrow-content {\n background-color: #52c41a;\n}\n.ant-popover-blue .ant-popover-inner {\n background-color: #1890ff;\n}\n.ant-popover-blue .ant-popover-arrow-content {\n background-color: #1890ff;\n}\n.ant-popover-geekblue .ant-popover-inner {\n background-color: #2f54eb;\n}\n.ant-popover-geekblue .ant-popover-arrow-content {\n background-color: #2f54eb;\n}\n.ant-popover-purple .ant-popover-inner {\n background-color: #722ed1;\n}\n.ant-popover-purple .ant-popover-arrow-content {\n background-color: #722ed1;\n}\n.ant-popover-rtl {\n direction: rtl;\n text-align: right;\n}\n.ant-popover-rtl .ant-popover-message-icon {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-popover-rtl .ant-popover-message-title {\n padding-left: 16px;\n}\n.ant-popover-rtl .ant-popover-buttons {\n text-align: left;\n}\n.ant-popover-rtl .ant-popover-buttons button {\n margin-right: 8px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-back-top {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: fixed;\n right: 100px;\n bottom: 50px;\n z-index: 10;\n width: 40px;\n height: 40px;\n cursor: pointer;\n}\n.ant-back-top:empty {\n display: none;\n}\n.ant-back-top-rtl {\n right: auto;\n left: 100px;\n direction: rtl;\n}\n.ant-back-top-content {\n width: 40px;\n height: 40px;\n overflow: hidden;\n color: #fff;\n text-align: center;\n background-color: rgba(0, 0, 0, 0.45);\n border-radius: 20px;\n transition: all 0.3s;\n}\n.ant-back-top-content:hover {\n background-color: rgba(0, 0, 0, 0.85);\n transition: all 0.3s;\n}\n.ant-back-top-icon {\n font-size: 24px;\n line-height: 40px;\n}\n@media screen and (max-width: 768px) {\n .ant-back-top {\n right: 60px;\n }\n .ant-back-top-rtl {\n right: auto;\n left: 60px;\n }\n}\n@media screen and (max-width: 480px) {\n .ant-back-top {\n right: 20px;\n }\n .ant-back-top-rtl {\n right: auto;\n left: 20px;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-badge {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-block;\n line-height: 1;\n}\n.ant-badge-count {\n z-index: auto;\n min-width: 20px;\n height: 20px;\n padding: 0 6px;\n color: #fff;\n font-weight: normal;\n font-size: 12px;\n line-height: 20px;\n white-space: nowrap;\n text-align: center;\n background: #ff4d4f;\n border-radius: 10px;\n box-shadow: 0 0 0 1px #fff;\n}\n.ant-badge-count a,\n.ant-badge-count a:hover {\n color: #fff;\n}\n.ant-badge-count-sm {\n min-width: 14px;\n height: 14px;\n padding: 0;\n font-size: 12px;\n line-height: 14px;\n border-radius: 7px;\n}\n.ant-badge-multiple-words {\n padding: 0 8px;\n}\n.ant-badge-dot {\n z-index: auto;\n width: 6px;\n min-width: 6px;\n height: 6px;\n background: #ff4d4f;\n border-radius: 100%;\n box-shadow: 0 0 0 1px #fff;\n}\n.ant-badge-dot.ant-scroll-number {\n transition: background 1.5s;\n}\n.ant-badge-count,\n.ant-badge-dot,\n.ant-badge .ant-scroll-number-custom-component {\n position: absolute;\n top: 0;\n right: 0;\n transform: translate(50%, -50%);\n transform-origin: 100% 0%;\n}\n.ant-badge-count.anticon-spin,\n.ant-badge-dot.anticon-spin,\n.ant-badge .ant-scroll-number-custom-component.anticon-spin {\n animation: antBadgeLoadingCircle 1s infinite linear;\n}\n.ant-badge-status {\n line-height: inherit;\n vertical-align: baseline;\n}\n.ant-badge-status-dot {\n position: relative;\n top: -1px;\n display: inline-block;\n width: 6px;\n height: 6px;\n vertical-align: middle;\n border-radius: 50%;\n}\n.ant-badge-status-success {\n background-color: #52c41a;\n}\n.ant-badge-status-processing {\n position: relative;\n background-color: #1890ff;\n}\n.ant-badge-status-processing::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 50%;\n animation: antStatusProcessing 1.2s infinite ease-in-out;\n content: '';\n}\n.ant-badge-status-default {\n background-color: #d9d9d9;\n}\n.ant-badge-status-error {\n background-color: #ff4d4f;\n}\n.ant-badge-status-warning {\n background-color: #faad14;\n}\n.ant-badge-status-pink {\n background: #eb2f96;\n}\n.ant-badge-status-magenta {\n background: #eb2f96;\n}\n.ant-badge-status-red {\n background: #f5222d;\n}\n.ant-badge-status-volcano {\n background: #fa541c;\n}\n.ant-badge-status-orange {\n background: #fa8c16;\n}\n.ant-badge-status-yellow {\n background: #fadb14;\n}\n.ant-badge-status-gold {\n background: #faad14;\n}\n.ant-badge-status-cyan {\n background: #13c2c2;\n}\n.ant-badge-status-lime {\n background: #a0d911;\n}\n.ant-badge-status-green {\n background: #52c41a;\n}\n.ant-badge-status-blue {\n background: #1890ff;\n}\n.ant-badge-status-geekblue {\n background: #2f54eb;\n}\n.ant-badge-status-purple {\n background: #722ed1;\n}\n.ant-badge-status-text {\n margin-left: 8px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n}\n.ant-badge-zoom-appear,\n.ant-badge-zoom-enter {\n animation: antZoomBadgeIn 0.3s cubic-bezier(0.12, 0.4, 0.29, 1.46);\n animation-fill-mode: both;\n}\n.ant-badge-zoom-leave {\n animation: antZoomBadgeOut 0.3s cubic-bezier(0.71, -0.46, 0.88, 0.6);\n animation-fill-mode: both;\n}\n.ant-badge-not-a-wrapper .ant-badge-zoom-appear,\n.ant-badge-not-a-wrapper .ant-badge-zoom-enter {\n animation: antNoWrapperZoomBadgeIn 0.3s cubic-bezier(0.12, 0.4, 0.29, 1.46);\n}\n.ant-badge-not-a-wrapper .ant-badge-zoom-leave {\n animation: antNoWrapperZoomBadgeOut 0.3s cubic-bezier(0.71, -0.46, 0.88, 0.6);\n}\n.ant-badge-not-a-wrapper:not(.ant-badge-status) {\n vertical-align: middle;\n}\n.ant-badge-not-a-wrapper .ant-scroll-number-custom-component,\n.ant-badge-not-a-wrapper .ant-badge-count {\n transform: none;\n}\n.ant-badge-not-a-wrapper .ant-scroll-number-custom-component,\n.ant-badge-not-a-wrapper .ant-scroll-number {\n position: relative;\n top: auto;\n display: block;\n transform-origin: 50% 50%;\n}\n@keyframes antStatusProcessing {\n 0% {\n transform: scale(0.8);\n opacity: 0.5;\n }\n 100% {\n transform: scale(2.4);\n opacity: 0;\n }\n}\n.ant-scroll-number {\n overflow: hidden;\n direction: ltr;\n}\n.ant-scroll-number-only {\n position: relative;\n display: inline-block;\n height: 20px;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n /* stylelint-disable property-no-vendor-prefix */\n -webkit-transform-style: preserve-3d;\n -webkit-backface-visibility: hidden;\n /* stylelint-enable property-no-vendor-prefix */\n}\n.ant-scroll-number-only > p.ant-scroll-number-only-unit {\n height: 20px;\n margin: 0;\n /* stylelint-disable property-no-vendor-prefix */\n -webkit-transform-style: preserve-3d;\n -webkit-backface-visibility: hidden;\n /* stylelint-enable property-no-vendor-prefix */\n}\n.ant-scroll-number-symbol {\n vertical-align: top;\n}\n@keyframes antZoomBadgeIn {\n 0% {\n transform: scale(0) translate(50%, -50%);\n opacity: 0;\n }\n 100% {\n transform: scale(1) translate(50%, -50%);\n }\n}\n@keyframes antZoomBadgeOut {\n 0% {\n transform: scale(1) translate(50%, -50%);\n }\n 100% {\n transform: scale(0) translate(50%, -50%);\n opacity: 0;\n }\n}\n@keyframes antNoWrapperZoomBadgeIn {\n 0% {\n transform: scale(0);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n }\n}\n@keyframes antNoWrapperZoomBadgeOut {\n 0% {\n transform: scale(1);\n }\n 100% {\n transform: scale(0);\n opacity: 0;\n }\n}\n@keyframes antBadgeLoadingCircle {\n 0% {\n transform-origin: 50%;\n }\n 100% {\n transform: translate(50%, -50%) rotate(360deg);\n transform-origin: 50%;\n }\n}\n.ant-ribbon-wrapper {\n position: relative;\n}\n.ant-ribbon {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: 8px;\n height: 22px;\n padding: 0 8px;\n color: #fff;\n line-height: 22px;\n white-space: nowrap;\n background-color: #1890ff;\n border-radius: 2px;\n}\n.ant-ribbon-text {\n color: #fff;\n}\n.ant-ribbon-corner {\n position: absolute;\n top: 100%;\n width: 8px;\n height: 8px;\n color: currentcolor;\n border: 4px solid;\n transform: scaleY(0.75);\n transform-origin: top;\n}\n.ant-ribbon-corner::after {\n position: absolute;\n top: -4px;\n left: -4px;\n width: inherit;\n height: inherit;\n color: rgba(0, 0, 0, 0.25);\n border: inherit;\n content: '';\n}\n.ant-ribbon-color-pink {\n color: #eb2f96;\n background: #eb2f96;\n}\n.ant-ribbon-color-magenta {\n color: #eb2f96;\n background: #eb2f96;\n}\n.ant-ribbon-color-red {\n color: #f5222d;\n background: #f5222d;\n}\n.ant-ribbon-color-volcano {\n color: #fa541c;\n background: #fa541c;\n}\n.ant-ribbon-color-orange {\n color: #fa8c16;\n background: #fa8c16;\n}\n.ant-ribbon-color-yellow {\n color: #fadb14;\n background: #fadb14;\n}\n.ant-ribbon-color-gold {\n color: #faad14;\n background: #faad14;\n}\n.ant-ribbon-color-cyan {\n color: #13c2c2;\n background: #13c2c2;\n}\n.ant-ribbon-color-lime {\n color: #a0d911;\n background: #a0d911;\n}\n.ant-ribbon-color-green {\n color: #52c41a;\n background: #52c41a;\n}\n.ant-ribbon-color-blue {\n color: #1890ff;\n background: #1890ff;\n}\n.ant-ribbon-color-geekblue {\n color: #2f54eb;\n background: #2f54eb;\n}\n.ant-ribbon-color-purple {\n color: #722ed1;\n background: #722ed1;\n}\n.ant-ribbon.ant-ribbon-placement-end {\n right: -8px;\n border-bottom-right-radius: 0;\n}\n.ant-ribbon.ant-ribbon-placement-end .ant-ribbon-corner {\n right: 0;\n border-color: currentcolor transparent transparent currentcolor;\n}\n.ant-ribbon.ant-ribbon-placement-start {\n left: -8px;\n border-bottom-left-radius: 0;\n}\n.ant-ribbon.ant-ribbon-placement-start .ant-ribbon-corner {\n left: 0;\n border-color: currentcolor currentcolor transparent transparent;\n}\n.ant-badge-rtl {\n direction: rtl;\n}\n.ant-badge-rtl.ant-badge:not(.ant-badge-not-a-wrapper) .ant-badge-count,\n.ant-badge-rtl.ant-badge:not(.ant-badge-not-a-wrapper) .ant-badge-dot,\n.ant-badge-rtl.ant-badge:not(.ant-badge-not-a-wrapper) .ant-scroll-number-custom-component {\n right: auto;\n left: 0;\n direction: ltr;\n transform: translate(-50%, -50%);\n transform-origin: 0% 0%;\n}\n.ant-badge-rtl.ant-badge:not(.ant-badge-not-a-wrapper) .ant-scroll-number-custom-component {\n right: auto;\n left: 0;\n transform: translate(-50%, -50%);\n transform-origin: 0% 0%;\n}\n.ant-badge-rtl .ant-badge-status-text {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-badge:not(.ant-badge-not-a-wrapper).ant-badge-rtl .ant-badge-zoom-appear,\n.ant-badge:not(.ant-badge-not-a-wrapper).ant-badge-rtl .ant-badge-zoom-enter {\n animation-name: antZoomBadgeInRtl;\n}\n.ant-badge:not(.ant-badge-not-a-wrapper).ant-badge-rtl .ant-badge-zoom-leave {\n animation-name: antZoomBadgeOutRtl;\n}\n.ant-ribbon-rtl {\n direction: rtl;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-end {\n right: unset;\n left: -8px;\n border-bottom-right-radius: 2px;\n border-bottom-left-radius: 0;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-end .ant-ribbon-corner {\n right: unset;\n left: 0;\n border-color: currentcolor currentcolor transparent transparent;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-end .ant-ribbon-corner::after {\n border-color: currentcolor currentcolor transparent transparent;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-start {\n right: -8px;\n left: unset;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 2px;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-start .ant-ribbon-corner {\n right: 0;\n left: unset;\n border-color: currentcolor transparent transparent currentcolor;\n}\n.ant-ribbon-rtl.ant-ribbon-placement-start .ant-ribbon-corner::after {\n border-color: currentcolor transparent transparent currentcolor;\n}\n@keyframes antZoomBadgeInRtl {\n 0% {\n transform: scale(0) translate(-50%, -50%);\n opacity: 0;\n }\n 100% {\n transform: scale(1) translate(-50%, -50%);\n }\n}\n@keyframes antZoomBadgeOutRtl {\n 0% {\n transform: scale(1) translate(-50%, -50%);\n }\n 100% {\n transform: scale(0) translate(-50%, -50%);\n opacity: 0;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-breadcrumb {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-breadcrumb .anticon {\n font-size: 14px;\n}\n.ant-breadcrumb ol {\n display: flex;\n flex-wrap: wrap;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ant-breadcrumb a {\n color: rgba(0, 0, 0, 0.45);\n transition: color 0.3s;\n}\n.ant-breadcrumb a:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-breadcrumb li:last-child {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-breadcrumb li:last-child a {\n color: rgba(0, 0, 0, 0.85);\n}\nli:last-child > .ant-breadcrumb-separator {\n display: none;\n}\n.ant-breadcrumb-separator {\n margin: 0 8px;\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-breadcrumb-link > .anticon + span,\n.ant-breadcrumb-link > .anticon + a {\n margin-left: 4px;\n}\n.ant-breadcrumb-overlay-link > .anticon {\n margin-left: 4px;\n}\n.ant-breadcrumb-rtl {\n direction: rtl;\n}\n.ant-breadcrumb-rtl::before {\n display: table;\n content: '';\n}\n.ant-breadcrumb-rtl::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-breadcrumb-rtl > span {\n float: right;\n}\n.ant-breadcrumb-rtl .ant-breadcrumb-link > .anticon + span,\n.ant-breadcrumb-rtl .ant-breadcrumb-link > .anticon + a {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-breadcrumb-rtl .ant-breadcrumb-overlay-link > .anticon {\n margin-right: 4px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-dropdown-menu-item.ant-dropdown-menu-item-danger {\n color: #ff4d4f;\n}\n.ant-dropdown-menu-item.ant-dropdown-menu-item-danger:hover {\n color: #fff;\n background-color: #ff4d4f;\n}\n.ant-dropdown {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: -9999px;\n left: -9999px;\n z-index: 1050;\n display: block;\n}\n.ant-dropdown::before {\n position: absolute;\n top: -4px;\n right: 0;\n bottom: -4px;\n left: -7px;\n z-index: -9999;\n opacity: 0.0001;\n content: ' ';\n}\n.ant-dropdown-wrap {\n position: relative;\n}\n.ant-dropdown-wrap .ant-btn > .anticon-down {\n font-size: 10px;\n}\n.ant-dropdown-wrap .anticon-down::before {\n transition: transform 0.2s;\n}\n.ant-dropdown-wrap-open .anticon-down::before {\n transform: rotate(180deg);\n}\n.ant-dropdown-hidden,\n.ant-dropdown-menu-hidden,\n.ant-dropdown-menu-submenu-hidden {\n display: none;\n}\n.ant-dropdown-show-arrow.ant-dropdown-placement-topLeft,\n.ant-dropdown-show-arrow.ant-dropdown-placement-top,\n.ant-dropdown-show-arrow.ant-dropdown-placement-topRight {\n padding-bottom: 15.3137085px;\n}\n.ant-dropdown-show-arrow.ant-dropdown-placement-bottomLeft,\n.ant-dropdown-show-arrow.ant-dropdown-placement-bottom,\n.ant-dropdown-show-arrow.ant-dropdown-placement-bottomRight {\n padding-top: 15.3137085px;\n}\n.ant-dropdown-arrow {\n position: absolute;\n z-index: 1;\n display: block;\n width: 11.3137085px;\n height: 11.3137085px;\n border-radius: 0 0 2px;\n pointer-events: none;\n}\n.ant-dropdown-arrow::before {\n position: absolute;\n top: -11.3137085px;\n left: -11.3137085px;\n width: 33.9411255px;\n height: 33.9411255px;\n background: #fff;\n background-repeat: no-repeat;\n background-position: -10px -10px;\n content: '';\n -webkit-clip-path: inset(33% 33%);\n clip-path: inset(33% 33%);\n -webkit-clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n}\n.ant-dropdown-placement-top > .ant-dropdown-arrow,\n.ant-dropdown-placement-topLeft > .ant-dropdown-arrow,\n.ant-dropdown-placement-topRight > .ant-dropdown-arrow {\n bottom: 10px;\n box-shadow: 3px 3px 7px -3px rgba(0, 0, 0, 0.1);\n transform: rotate(45deg);\n}\n.ant-dropdown-placement-top > .ant-dropdown-arrow {\n left: 50%;\n transform: translateX(-50%) rotate(45deg);\n}\n.ant-dropdown-placement-topLeft > .ant-dropdown-arrow {\n left: 16px;\n}\n.ant-dropdown-placement-topRight > .ant-dropdown-arrow {\n right: 16px;\n}\n.ant-dropdown-placement-bottom > .ant-dropdown-arrow,\n.ant-dropdown-placement-bottomLeft > .ant-dropdown-arrow,\n.ant-dropdown-placement-bottomRight > .ant-dropdown-arrow {\n top: 9.41421356px;\n box-shadow: 2px 2px 5px -2px rgba(0, 0, 0, 0.1);\n transform: rotate(-135deg) translateY(-0.5px);\n}\n.ant-dropdown-placement-bottom > .ant-dropdown-arrow {\n left: 50%;\n transform: translateX(-50%) rotate(-135deg) translateY(-0.5px);\n}\n.ant-dropdown-placement-bottomLeft > .ant-dropdown-arrow {\n left: 16px;\n}\n.ant-dropdown-placement-bottomRight > .ant-dropdown-arrow {\n right: 16px;\n}\n.ant-dropdown-menu {\n position: relative;\n margin: 0;\n padding: 4px 0;\n text-align: left;\n list-style-type: none;\n background-color: #fff;\n background-clip: padding-box;\n border-radius: 2px;\n outline: none;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-dropdown-menu-item-group-title {\n padding: 5px 12px;\n color: rgba(0, 0, 0, 0.45);\n transition: all 0.3s;\n}\n.ant-dropdown-menu-submenu-popup {\n position: absolute;\n z-index: 1050;\n background: transparent;\n box-shadow: none;\n transform-origin: 0 0;\n}\n.ant-dropdown-menu-submenu-popup ul,\n.ant-dropdown-menu-submenu-popup li {\n list-style: none;\n}\n.ant-dropdown-menu-submenu-popup ul {\n margin-right: 0.3em;\n margin-left: 0.3em;\n}\n.ant-dropdown-menu-item {\n position: relative;\n display: flex;\n align-items: center;\n}\n.ant-dropdown-menu-item-icon {\n min-width: 12px;\n margin-right: 8px;\n font-size: 12px;\n}\n.ant-dropdown-menu-title-content {\n flex: auto;\n}\n.ant-dropdown-menu-title-content > a {\n color: inherit;\n transition: all 0.3s;\n}\n.ant-dropdown-menu-title-content > a:hover {\n color: inherit;\n}\n.ant-dropdown-menu-title-content > a::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n content: '';\n}\n.ant-dropdown-menu-item,\n.ant-dropdown-menu-submenu-title {\n clear: both;\n margin: 0;\n padding: 5px 12px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-dropdown-menu-item-selected,\n.ant-dropdown-menu-submenu-title-selected {\n color: #1890ff;\n background-color: #e6f7ff;\n}\n.ant-dropdown-menu-item:hover,\n.ant-dropdown-menu-submenu-title:hover,\n.ant-dropdown-menu-item.ant-dropdown-menu-item-active,\n.ant-dropdown-menu-item.ant-dropdown-menu-submenu-title-active,\n.ant-dropdown-menu-submenu-title.ant-dropdown-menu-item-active,\n.ant-dropdown-menu-submenu-title.ant-dropdown-menu-submenu-title-active {\n background-color: #f5f5f5;\n}\n.ant-dropdown-menu-item-disabled,\n.ant-dropdown-menu-submenu-title-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-dropdown-menu-item-disabled:hover,\n.ant-dropdown-menu-submenu-title-disabled:hover {\n color: rgba(0, 0, 0, 0.25);\n background-color: #fff;\n cursor: not-allowed;\n}\n.ant-dropdown-menu-item-disabled a,\n.ant-dropdown-menu-submenu-title-disabled a {\n pointer-events: none;\n}\n.ant-dropdown-menu-item-divider,\n.ant-dropdown-menu-submenu-title-divider {\n height: 1px;\n margin: 4px 0;\n overflow: hidden;\n line-height: 0;\n background-color: #f0f0f0;\n}\n.ant-dropdown-menu-item .ant-dropdown-menu-submenu-expand-icon,\n.ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-expand-icon {\n position: absolute;\n right: 8px;\n}\n.ant-dropdown-menu-item .ant-dropdown-menu-submenu-expand-icon .ant-dropdown-menu-submenu-arrow-icon,\n.ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-expand-icon .ant-dropdown-menu-submenu-arrow-icon {\n margin-right: 0 !important;\n color: rgba(0, 0, 0, 0.45);\n font-size: 10px;\n font-style: normal;\n}\n.ant-dropdown-menu-item-group-list {\n margin: 0 8px;\n padding: 0;\n list-style: none;\n}\n.ant-dropdown-menu-submenu-title {\n padding-right: 24px;\n}\n.ant-dropdown-menu-submenu-vertical {\n position: relative;\n}\n.ant-dropdown-menu-submenu-vertical > .ant-dropdown-menu {\n position: absolute;\n top: 0;\n left: 100%;\n min-width: 100%;\n margin-left: 4px;\n transform-origin: 0 0;\n}\n.ant-dropdown-menu-submenu.ant-dropdown-menu-submenu-disabled .ant-dropdown-menu-submenu-title,\n.ant-dropdown-menu-submenu.ant-dropdown-menu-submenu-disabled .ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-arrow-icon {\n color: rgba(0, 0, 0, 0.25);\n background-color: #fff;\n cursor: not-allowed;\n}\n.ant-dropdown-menu-submenu-selected .ant-dropdown-menu-submenu-title {\n color: #1890ff;\n}\n.ant-dropdown.ant-slide-down-enter.ant-slide-down-enter-active.ant-dropdown-placement-bottomLeft,\n.ant-dropdown.ant-slide-down-appear.ant-slide-down-appear-active.ant-dropdown-placement-bottomLeft,\n.ant-dropdown.ant-slide-down-enter.ant-slide-down-enter-active.ant-dropdown-placement-bottom,\n.ant-dropdown.ant-slide-down-appear.ant-slide-down-appear-active.ant-dropdown-placement-bottom,\n.ant-dropdown.ant-slide-down-enter.ant-slide-down-enter-active.ant-dropdown-placement-bottomRight,\n.ant-dropdown.ant-slide-down-appear.ant-slide-down-appear-active.ant-dropdown-placement-bottomRight {\n animation-name: antSlideUpIn;\n}\n.ant-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-dropdown-placement-topLeft,\n.ant-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-dropdown-placement-topLeft,\n.ant-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-dropdown-placement-top,\n.ant-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-dropdown-placement-top,\n.ant-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-dropdown-placement-topRight,\n.ant-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-dropdown-placement-topRight {\n animation-name: antSlideDownIn;\n}\n.ant-dropdown.ant-slide-down-leave.ant-slide-down-leave-active.ant-dropdown-placement-bottomLeft,\n.ant-dropdown.ant-slide-down-leave.ant-slide-down-leave-active.ant-dropdown-placement-bottom,\n.ant-dropdown.ant-slide-down-leave.ant-slide-down-leave-active.ant-dropdown-placement-bottomRight {\n animation-name: antSlideUpOut;\n}\n.ant-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-dropdown-placement-topLeft,\n.ant-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-dropdown-placement-top,\n.ant-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-dropdown-placement-topRight {\n animation-name: antSlideDownOut;\n}\n.ant-dropdown-trigger > .anticon.anticon-down,\n.ant-dropdown-link > .anticon.anticon-down,\n.ant-dropdown-button > .anticon.anticon-down {\n font-size: 10px;\n vertical-align: baseline;\n}\n.ant-dropdown-button {\n white-space: nowrap;\n}\n.ant-dropdown-button.ant-btn-group > .ant-btn-loading,\n.ant-dropdown-button.ant-btn-group > .ant-btn-loading + .ant-btn {\n cursor: default;\n pointer-events: none;\n}\n.ant-dropdown-button.ant-btn-group > .ant-btn-loading + .ant-btn::before {\n display: block;\n}\n.ant-dropdown-button.ant-btn-group > .ant-btn:last-child:not(:first-child):not(.ant-btn-icon-only) {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-dropdown-menu-dark,\n.ant-dropdown-menu-dark .ant-dropdown-menu {\n background: #001529;\n}\n.ant-dropdown-menu-dark .ant-dropdown-menu-item,\n.ant-dropdown-menu-dark .ant-dropdown-menu-submenu-title,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > a,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > .anticon + span > a {\n color: rgba(255, 255, 255, 0.65);\n}\n.ant-dropdown-menu-dark .ant-dropdown-menu-item .ant-dropdown-menu-submenu-arrow::after,\n.ant-dropdown-menu-dark .ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-arrow::after,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > a .ant-dropdown-menu-submenu-arrow::after,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > .anticon + span > a .ant-dropdown-menu-submenu-arrow::after {\n color: rgba(255, 255, 255, 0.65);\n}\n.ant-dropdown-menu-dark .ant-dropdown-menu-item:hover,\n.ant-dropdown-menu-dark .ant-dropdown-menu-submenu-title:hover,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > a:hover,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item > .anticon + span > a:hover {\n color: #fff;\n background: transparent;\n}\n.ant-dropdown-menu-dark .ant-dropdown-menu-item-selected,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item-selected:hover,\n.ant-dropdown-menu-dark .ant-dropdown-menu-item-selected > a {\n color: #fff;\n background: #1890ff;\n}\n.ant-dropdown-rtl {\n direction: rtl;\n}\n.ant-dropdown-rtl.ant-dropdown::before {\n right: -7px;\n left: 0;\n}\n.ant-dropdown-menu.ant-dropdown-menu-rtl {\n direction: rtl;\n text-align: right;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-item-group-title,\n.ant-dropdown-menu-submenu-rtl .ant-dropdown-menu-item-group-title {\n direction: rtl;\n text-align: right;\n}\n.ant-dropdown-menu-submenu-popup.ant-dropdown-menu-submenu-rtl {\n transform-origin: 100% 0;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-popup ul,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-popup li {\n text-align: right;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-item,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title {\n text-align: right;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-item > .anticon:first-child,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title > .anticon:first-child,\n.ant-dropdown-rtl .ant-dropdown-menu-item > span > .anticon:first-child,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title > span > .anticon:first-child {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-item .ant-dropdown-menu-submenu-expand-icon,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-expand-icon {\n right: auto;\n left: 8px;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-item .ant-dropdown-menu-submenu-expand-icon .ant-dropdown-menu-submenu-arrow-icon,\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title .ant-dropdown-menu-submenu-expand-icon .ant-dropdown-menu-submenu-arrow-icon {\n margin-left: 0 !important;\n transform: scaleX(-1);\n}\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-title {\n padding-right: 12px;\n padding-left: 24px;\n}\n.ant-dropdown-rtl .ant-dropdown-menu-submenu-vertical > .ant-dropdown-menu {\n right: 100%;\n left: 0;\n margin-right: 4px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-btn {\n line-height: 1.5715;\n position: relative;\n display: inline-block;\n font-weight: 400;\n white-space: nowrap;\n text-align: center;\n background-image: none;\n border: 1px solid transparent;\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);\n cursor: pointer;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n touch-action: manipulation;\n height: 32px;\n padding: 4px 15px;\n font-size: 14px;\n border-radius: 2px;\n color: rgba(0, 0, 0, 0.85);\n border-color: #d9d9d9;\n background: #fff;\n}\n.ant-btn > .anticon {\n line-height: 1;\n}\n.ant-btn,\n.ant-btn:active,\n.ant-btn:focus {\n outline: 0;\n}\n.ant-btn:not([disabled]):hover {\n text-decoration: none;\n}\n.ant-btn:not([disabled]):active {\n outline: 0;\n box-shadow: none;\n}\n.ant-btn[disabled] {\n cursor: not-allowed;\n}\n.ant-btn[disabled] > * {\n pointer-events: none;\n}\n.ant-btn-lg {\n height: 40px;\n padding: 6.4px 15px;\n font-size: 16px;\n border-radius: 2px;\n}\n.ant-btn-sm {\n height: 24px;\n padding: 0px 7px;\n font-size: 14px;\n border-radius: 2px;\n}\n.ant-btn > a:only-child {\n color: currentcolor;\n}\n.ant-btn > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn:hover,\n.ant-btn:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: #fff;\n}\n.ant-btn:hover > a:only-child,\n.ant-btn:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn:hover > a:only-child::after,\n.ant-btn:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn:active {\n color: #096dd9;\n border-color: #096dd9;\n background: #fff;\n}\n.ant-btn:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn[disabled],\n.ant-btn[disabled]:hover,\n.ant-btn[disabled]:focus,\n.ant-btn[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn[disabled] > a:only-child,\n.ant-btn[disabled]:hover > a:only-child,\n.ant-btn[disabled]:focus > a:only-child,\n.ant-btn[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn[disabled] > a:only-child::after,\n.ant-btn[disabled]:hover > a:only-child::after,\n.ant-btn[disabled]:focus > a:only-child::after,\n.ant-btn[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn:hover,\n.ant-btn:focus,\n.ant-btn:active {\n text-decoration: none;\n background: #fff;\n}\n.ant-btn > span {\n display: inline-block;\n}\n.ant-btn-primary {\n color: #fff;\n border-color: #1890ff;\n background: #1890ff;\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);\n}\n.ant-btn-primary > a:only-child {\n color: currentcolor;\n}\n.ant-btn-primary > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-primary:hover,\n.ant-btn-primary:focus {\n color: #fff;\n border-color: #40a9ff;\n background: #40a9ff;\n}\n.ant-btn-primary:hover > a:only-child,\n.ant-btn-primary:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-primary:hover > a:only-child::after,\n.ant-btn-primary:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-primary:active {\n color: #fff;\n border-color: #096dd9;\n background: #096dd9;\n}\n.ant-btn-primary:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-primary:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-primary[disabled],\n.ant-btn-primary[disabled]:hover,\n.ant-btn-primary[disabled]:focus,\n.ant-btn-primary[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-primary[disabled] > a:only-child,\n.ant-btn-primary[disabled]:hover > a:only-child,\n.ant-btn-primary[disabled]:focus > a:only-child,\n.ant-btn-primary[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-primary[disabled] > a:only-child::after,\n.ant-btn-primary[disabled]:hover > a:only-child::after,\n.ant-btn-primary[disabled]:focus > a:only-child::after,\n.ant-btn-primary[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-group .ant-btn-primary:not(:first-child):not(:last-child) {\n border-right-color: #40a9ff;\n border-left-color: #40a9ff;\n}\n.ant-btn-group .ant-btn-primary:not(:first-child):not(:last-child):disabled {\n border-color: #d9d9d9;\n}\n.ant-btn-group .ant-btn-primary:first-child:not(:last-child) {\n border-right-color: #40a9ff;\n}\n.ant-btn-group .ant-btn-primary:first-child:not(:last-child)[disabled] {\n border-right-color: #d9d9d9;\n}\n.ant-btn-group .ant-btn-primary:last-child:not(:first-child),\n.ant-btn-group .ant-btn-primary + .ant-btn-primary {\n border-left-color: #40a9ff;\n}\n.ant-btn-group .ant-btn-primary:last-child:not(:first-child)[disabled],\n.ant-btn-group .ant-btn-primary + .ant-btn-primary[disabled] {\n border-left-color: #d9d9d9;\n}\n.ant-btn-ghost {\n color: rgba(0, 0, 0, 0.85);\n border-color: #d9d9d9;\n background: transparent;\n}\n.ant-btn-ghost > a:only-child {\n color: currentcolor;\n}\n.ant-btn-ghost > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-ghost:hover,\n.ant-btn-ghost:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: transparent;\n}\n.ant-btn-ghost:hover > a:only-child,\n.ant-btn-ghost:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-ghost:hover > a:only-child::after,\n.ant-btn-ghost:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-ghost:active {\n color: #096dd9;\n border-color: #096dd9;\n background: transparent;\n}\n.ant-btn-ghost:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-ghost:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-ghost[disabled],\n.ant-btn-ghost[disabled]:hover,\n.ant-btn-ghost[disabled]:focus,\n.ant-btn-ghost[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-ghost[disabled] > a:only-child,\n.ant-btn-ghost[disabled]:hover > a:only-child,\n.ant-btn-ghost[disabled]:focus > a:only-child,\n.ant-btn-ghost[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-ghost[disabled] > a:only-child::after,\n.ant-btn-ghost[disabled]:hover > a:only-child::after,\n.ant-btn-ghost[disabled]:focus > a:only-child::after,\n.ant-btn-ghost[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dashed {\n color: rgba(0, 0, 0, 0.85);\n border-color: #d9d9d9;\n background: #fff;\n border-style: dashed;\n}\n.ant-btn-dashed > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dashed > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dashed:hover,\n.ant-btn-dashed:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: #fff;\n}\n.ant-btn-dashed:hover > a:only-child,\n.ant-btn-dashed:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dashed:hover > a:only-child::after,\n.ant-btn-dashed:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dashed:active {\n color: #096dd9;\n border-color: #096dd9;\n background: #fff;\n}\n.ant-btn-dashed:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dashed:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dashed[disabled],\n.ant-btn-dashed[disabled]:hover,\n.ant-btn-dashed[disabled]:focus,\n.ant-btn-dashed[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dashed[disabled] > a:only-child,\n.ant-btn-dashed[disabled]:hover > a:only-child,\n.ant-btn-dashed[disabled]:focus > a:only-child,\n.ant-btn-dashed[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dashed[disabled] > a:only-child::after,\n.ant-btn-dashed[disabled]:hover > a:only-child::after,\n.ant-btn-dashed[disabled]:focus > a:only-child::after,\n.ant-btn-dashed[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-danger {\n color: #fff;\n border-color: #ff4d4f;\n background: #ff4d4f;\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);\n}\n.ant-btn-danger > a:only-child {\n color: currentcolor;\n}\n.ant-btn-danger > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-danger:hover,\n.ant-btn-danger:focus {\n color: #fff;\n border-color: #ff7875;\n background: #ff7875;\n}\n.ant-btn-danger:hover > a:only-child,\n.ant-btn-danger:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-danger:hover > a:only-child::after,\n.ant-btn-danger:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-danger:active {\n color: #fff;\n border-color: #d9363e;\n background: #d9363e;\n}\n.ant-btn-danger:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-danger:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-danger[disabled],\n.ant-btn-danger[disabled]:hover,\n.ant-btn-danger[disabled]:focus,\n.ant-btn-danger[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-danger[disabled] > a:only-child,\n.ant-btn-danger[disabled]:hover > a:only-child,\n.ant-btn-danger[disabled]:focus > a:only-child,\n.ant-btn-danger[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-danger[disabled] > a:only-child::after,\n.ant-btn-danger[disabled]:hover > a:only-child::after,\n.ant-btn-danger[disabled]:focus > a:only-child::after,\n.ant-btn-danger[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-link {\n color: #1890ff;\n border-color: transparent;\n background: transparent;\n box-shadow: none;\n}\n.ant-btn-link > a:only-child {\n color: currentcolor;\n}\n.ant-btn-link > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-link:hover,\n.ant-btn-link:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: transparent;\n}\n.ant-btn-link:hover > a:only-child,\n.ant-btn-link:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-link:hover > a:only-child::after,\n.ant-btn-link:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-link:active {\n color: #096dd9;\n border-color: #096dd9;\n background: transparent;\n}\n.ant-btn-link:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-link:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-link[disabled],\n.ant-btn-link[disabled]:hover,\n.ant-btn-link[disabled]:focus,\n.ant-btn-link[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-link[disabled] > a:only-child,\n.ant-btn-link[disabled]:hover > a:only-child,\n.ant-btn-link[disabled]:focus > a:only-child,\n.ant-btn-link[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-link[disabled] > a:only-child::after,\n.ant-btn-link[disabled]:hover > a:only-child::after,\n.ant-btn-link[disabled]:focus > a:only-child::after,\n.ant-btn-link[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-link:hover {\n background: transparent;\n}\n.ant-btn-link:hover,\n.ant-btn-link:focus,\n.ant-btn-link:active {\n border-color: transparent;\n}\n.ant-btn-link[disabled],\n.ant-btn-link[disabled]:hover,\n.ant-btn-link[disabled]:focus,\n.ant-btn-link[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: transparent;\n background: transparent;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-link[disabled] > a:only-child,\n.ant-btn-link[disabled]:hover > a:only-child,\n.ant-btn-link[disabled]:focus > a:only-child,\n.ant-btn-link[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-link[disabled] > a:only-child::after,\n.ant-btn-link[disabled]:hover > a:only-child::after,\n.ant-btn-link[disabled]:focus > a:only-child::after,\n.ant-btn-link[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-text {\n color: rgba(0, 0, 0, 0.85);\n border-color: transparent;\n background: transparent;\n box-shadow: none;\n}\n.ant-btn-text > a:only-child {\n color: currentcolor;\n}\n.ant-btn-text > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-text:hover,\n.ant-btn-text:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: transparent;\n}\n.ant-btn-text:hover > a:only-child,\n.ant-btn-text:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-text:hover > a:only-child::after,\n.ant-btn-text:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-text:active {\n color: #096dd9;\n border-color: #096dd9;\n background: transparent;\n}\n.ant-btn-text:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-text:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-text[disabled],\n.ant-btn-text[disabled]:hover,\n.ant-btn-text[disabled]:focus,\n.ant-btn-text[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-text[disabled] > a:only-child,\n.ant-btn-text[disabled]:hover > a:only-child,\n.ant-btn-text[disabled]:focus > a:only-child,\n.ant-btn-text[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-text[disabled] > a:only-child::after,\n.ant-btn-text[disabled]:hover > a:only-child::after,\n.ant-btn-text[disabled]:focus > a:only-child::after,\n.ant-btn-text[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-text:hover,\n.ant-btn-text:focus {\n color: rgba(0, 0, 0, 0.85);\n background: rgba(0, 0, 0, 0.018);\n border-color: transparent;\n}\n.ant-btn-text:active {\n color: rgba(0, 0, 0, 0.85);\n background: rgba(0, 0, 0, 0.028);\n border-color: transparent;\n}\n.ant-btn-text[disabled],\n.ant-btn-text[disabled]:hover,\n.ant-btn-text[disabled]:focus,\n.ant-btn-text[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: transparent;\n background: transparent;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-text[disabled] > a:only-child,\n.ant-btn-text[disabled]:hover > a:only-child,\n.ant-btn-text[disabled]:focus > a:only-child,\n.ant-btn-text[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-text[disabled] > a:only-child::after,\n.ant-btn-text[disabled]:hover > a:only-child::after,\n.ant-btn-text[disabled]:focus > a:only-child::after,\n.ant-btn-text[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous {\n color: #ff4d4f;\n border-color: #ff4d4f;\n background: #fff;\n}\n.ant-btn-dangerous > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous:hover,\n.ant-btn-dangerous:focus {\n color: #ff7875;\n border-color: #ff7875;\n background: #fff;\n}\n.ant-btn-dangerous:hover > a:only-child,\n.ant-btn-dangerous:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous:hover > a:only-child::after,\n.ant-btn-dangerous:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous:active {\n color: #d9363e;\n border-color: #d9363e;\n background: #fff;\n}\n.ant-btn-dangerous:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous[disabled],\n.ant-btn-dangerous[disabled]:hover,\n.ant-btn-dangerous[disabled]:focus,\n.ant-btn-dangerous[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous[disabled] > a:only-child,\n.ant-btn-dangerous[disabled]:hover > a:only-child,\n.ant-btn-dangerous[disabled]:focus > a:only-child,\n.ant-btn-dangerous[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous[disabled] > a:only-child::after,\n.ant-btn-dangerous[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-primary {\n color: #fff;\n border-color: #ff4d4f;\n background: #ff4d4f;\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);\n box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);\n}\n.ant-btn-dangerous.ant-btn-primary > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-primary > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-primary:hover,\n.ant-btn-dangerous.ant-btn-primary:focus {\n color: #fff;\n border-color: #ff7875;\n background: #ff7875;\n}\n.ant-btn-dangerous.ant-btn-primary:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-primary:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-primary:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-primary:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-primary:active {\n color: #fff;\n border-color: #d9363e;\n background: #d9363e;\n}\n.ant-btn-dangerous.ant-btn-primary:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-primary:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-primary[disabled],\n.ant-btn-dangerous.ant-btn-primary[disabled]:hover,\n.ant-btn-dangerous.ant-btn-primary[disabled]:focus,\n.ant-btn-dangerous.ant-btn-primary[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-primary[disabled] > a:only-child,\n.ant-btn-dangerous.ant-btn-primary[disabled]:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-primary[disabled]:focus > a:only-child,\n.ant-btn-dangerous.ant-btn-primary[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-primary[disabled] > a:only-child::after,\n.ant-btn-dangerous.ant-btn-primary[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-primary[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous.ant-btn-primary[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link {\n color: #ff4d4f;\n border-color: transparent;\n background: transparent;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-link > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link:hover,\n.ant-btn-dangerous.ant-btn-link:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-link:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-link:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link:active {\n color: #096dd9;\n border-color: #096dd9;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-link:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link[disabled],\n.ant-btn-dangerous.ant-btn-link[disabled]:hover,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus,\n.ant-btn-dangerous.ant-btn-link[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link:hover,\n.ant-btn-dangerous.ant-btn-link:focus {\n color: #ff7875;\n border-color: transparent;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-link:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-link:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link:active {\n color: #d9363e;\n border-color: transparent;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-link:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-link[disabled],\n.ant-btn-dangerous.ant-btn-link[disabled]:hover,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus,\n.ant-btn-dangerous.ant-btn-link[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: transparent;\n background: transparent;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child,\n.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text {\n color: #ff4d4f;\n border-color: transparent;\n background: transparent;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-text > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text:hover,\n.ant-btn-dangerous.ant-btn-text:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-text:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-text:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text:active {\n color: #096dd9;\n border-color: #096dd9;\n background: transparent;\n}\n.ant-btn-dangerous.ant-btn-text:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text[disabled],\n.ant-btn-dangerous.ant-btn-text[disabled]:hover,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus,\n.ant-btn-dangerous.ant-btn-text[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-text[disabled] > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text[disabled] > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text:hover,\n.ant-btn-dangerous.ant-btn-text:focus {\n color: #ff7875;\n border-color: transparent;\n background: rgba(0, 0, 0, 0.018);\n}\n.ant-btn-dangerous.ant-btn-text:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-text:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text:active {\n color: #d9363e;\n border-color: transparent;\n background: rgba(0, 0, 0, 0.028);\n}\n.ant-btn-dangerous.ant-btn-text:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-dangerous.ant-btn-text[disabled],\n.ant-btn-dangerous.ant-btn-text[disabled]:hover,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus,\n.ant-btn-dangerous.ant-btn-text[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: transparent;\n background: transparent;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-dangerous.ant-btn-text[disabled] > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:hover > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus > a:only-child,\n.ant-btn-dangerous.ant-btn-text[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-dangerous.ant-btn-text[disabled] > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:hover > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:focus > a:only-child::after,\n.ant-btn-dangerous.ant-btn-text[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-icon-only {\n width: 32px;\n height: 32px;\n padding: 2.4px 0;\n font-size: 16px;\n border-radius: 2px;\n vertical-align: -3px;\n}\n.ant-btn-icon-only > * {\n font-size: 16px;\n}\n.ant-btn-icon-only.ant-btn-lg {\n width: 40px;\n height: 40px;\n padding: 4.9px 0;\n font-size: 18px;\n border-radius: 2px;\n}\n.ant-btn-icon-only.ant-btn-lg > * {\n font-size: 18px;\n}\n.ant-btn-icon-only.ant-btn-sm {\n width: 24px;\n height: 24px;\n padding: 0px 0;\n font-size: 14px;\n border-radius: 2px;\n}\n.ant-btn-icon-only.ant-btn-sm > * {\n font-size: 14px;\n}\n.ant-btn-icon-only > .anticon {\n display: flex;\n justify-content: center;\n}\n.ant-btn-icon-only .anticon-loading {\n padding: 0 !important;\n}\na.ant-btn-icon-only {\n vertical-align: -1px;\n}\na.ant-btn-icon-only > .anticon {\n display: inline;\n}\n.ant-btn-round {\n height: 32px;\n padding: 4px 16px;\n font-size: 14px;\n border-radius: 32px;\n}\n.ant-btn-round.ant-btn-lg {\n height: 40px;\n padding: 6.4px 20px;\n font-size: 16px;\n border-radius: 40px;\n}\n.ant-btn-round.ant-btn-sm {\n height: 24px;\n padding: 0px 12px;\n font-size: 14px;\n border-radius: 24px;\n}\n.ant-btn-round.ant-btn-icon-only {\n width: auto;\n}\n.ant-btn-circle {\n min-width: 32px;\n padding-right: 0;\n padding-left: 0;\n text-align: center;\n border-radius: 50%;\n}\n.ant-btn-circle.ant-btn-lg {\n min-width: 40px;\n border-radius: 50%;\n}\n.ant-btn-circle.ant-btn-sm {\n min-width: 24px;\n border-radius: 50%;\n}\n.ant-btn::before {\n position: absolute;\n top: -1px;\n right: -1px;\n bottom: -1px;\n left: -1px;\n z-index: 1;\n display: none;\n background: #fff;\n border-radius: inherit;\n opacity: 0.35;\n transition: opacity 0.2s;\n content: '';\n pointer-events: none;\n}\n.ant-btn .anticon {\n transition: margin-left 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-btn .anticon.anticon-plus > svg,\n.ant-btn .anticon.anticon-minus > svg {\n shape-rendering: optimizespeed;\n}\n.ant-btn.ant-btn-loading {\n position: relative;\n cursor: default;\n}\n.ant-btn.ant-btn-loading::before {\n display: block;\n}\n.ant-btn > .ant-btn-loading-icon {\n transition: width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-btn > .ant-btn-loading-icon .anticon {\n padding-right: 8px;\n animation: none;\n}\n.ant-btn > .ant-btn-loading-icon .anticon svg {\n animation: loadingCircle 1s infinite linear;\n}\n.ant-btn-group {\n position: relative;\n display: inline-flex;\n}\n.ant-btn-group > .ant-btn,\n.ant-btn-group > span > .ant-btn {\n position: relative;\n}\n.ant-btn-group > .ant-btn:hover,\n.ant-btn-group > span > .ant-btn:hover,\n.ant-btn-group > .ant-btn:focus,\n.ant-btn-group > span > .ant-btn:focus,\n.ant-btn-group > .ant-btn:active,\n.ant-btn-group > span > .ant-btn:active {\n z-index: 2;\n}\n.ant-btn-group > .ant-btn[disabled],\n.ant-btn-group > span > .ant-btn[disabled] {\n z-index: 0;\n}\n.ant-btn-group .ant-btn-icon-only {\n font-size: 14px;\n}\n.ant-btn-group .ant-btn + .ant-btn,\n.ant-btn + .ant-btn-group,\n.ant-btn-group span + .ant-btn,\n.ant-btn-group .ant-btn + span,\n.ant-btn-group > span + span,\n.ant-btn-group + .ant-btn,\n.ant-btn-group + .ant-btn-group {\n margin-left: -1px;\n}\n.ant-btn-group .ant-btn-primary + .ant-btn:not(.ant-btn-primary):not([disabled]) {\n border-left-color: transparent;\n}\n.ant-btn-group .ant-btn {\n border-radius: 0;\n}\n.ant-btn-group > .ant-btn:first-child,\n.ant-btn-group > span:first-child > .ant-btn {\n margin-left: 0;\n}\n.ant-btn-group > .ant-btn:only-child {\n border-radius: 2px;\n}\n.ant-btn-group > span:only-child > .ant-btn {\n border-radius: 2px;\n}\n.ant-btn-group > .ant-btn:first-child:not(:last-child),\n.ant-btn-group > span:first-child:not(:last-child) > .ant-btn {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-btn-group > .ant-btn:last-child:not(:first-child),\n.ant-btn-group > span:last-child:not(:first-child) > .ant-btn {\n border-top-right-radius: 2px;\n border-bottom-right-radius: 2px;\n}\n.ant-btn-group-sm > .ant-btn:only-child {\n border-radius: 2px;\n}\n.ant-btn-group-sm > span:only-child > .ant-btn {\n border-radius: 2px;\n}\n.ant-btn-group-sm > .ant-btn:first-child:not(:last-child),\n.ant-btn-group-sm > span:first-child:not(:last-child) > .ant-btn {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-btn-group-sm > .ant-btn:last-child:not(:first-child),\n.ant-btn-group-sm > span:last-child:not(:first-child) > .ant-btn {\n border-top-right-radius: 2px;\n border-bottom-right-radius: 2px;\n}\n.ant-btn-group > .ant-btn-group {\n float: left;\n}\n.ant-btn-group > .ant-btn-group:not(:first-child):not(:last-child) > .ant-btn {\n border-radius: 0;\n}\n.ant-btn-group > .ant-btn-group:first-child:not(:last-child) > .ant-btn:last-child {\n padding-right: 8px;\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-btn-group > .ant-btn-group:last-child:not(:first-child) > .ant-btn:first-child {\n padding-left: 8px;\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-rtl.ant-btn-group .ant-btn + .ant-btn,\n.ant-btn-rtl.ant-btn + .ant-btn-group,\n.ant-btn-rtl.ant-btn-group span + .ant-btn,\n.ant-btn-rtl.ant-btn-group .ant-btn + span,\n.ant-btn-rtl.ant-btn-group > span + span,\n.ant-btn-rtl.ant-btn-group + .ant-btn,\n.ant-btn-rtl.ant-btn-group + .ant-btn-group,\n.ant-btn-group-rtl.ant-btn-group .ant-btn + .ant-btn,\n.ant-btn-group-rtl.ant-btn + .ant-btn-group,\n.ant-btn-group-rtl.ant-btn-group span + .ant-btn,\n.ant-btn-group-rtl.ant-btn-group .ant-btn + span,\n.ant-btn-group-rtl.ant-btn-group > span + span,\n.ant-btn-group-rtl.ant-btn-group + .ant-btn,\n.ant-btn-group-rtl.ant-btn-group + .ant-btn-group {\n margin-right: -1px;\n margin-left: auto;\n}\n.ant-btn-group.ant-btn-group-rtl {\n direction: rtl;\n}\n.ant-btn-group-rtl.ant-btn-group > .ant-btn:first-child:not(:last-child),\n.ant-btn-group-rtl.ant-btn-group > span:first-child:not(:last-child) > .ant-btn {\n border-radius: 0 2px 2px 0;\n}\n.ant-btn-group-rtl.ant-btn-group > .ant-btn:last-child:not(:first-child),\n.ant-btn-group-rtl.ant-btn-group > span:last-child:not(:first-child) > .ant-btn {\n border-radius: 2px 0 0 2px;\n}\n.ant-btn-group-rtl.ant-btn-group-sm > .ant-btn:first-child:not(:last-child),\n.ant-btn-group-rtl.ant-btn-group-sm > span:first-child:not(:last-child) > .ant-btn {\n border-radius: 0 2px 2px 0;\n}\n.ant-btn-group-rtl.ant-btn-group-sm > .ant-btn:last-child:not(:first-child),\n.ant-btn-group-rtl.ant-btn-group-sm > span:last-child:not(:first-child) > .ant-btn {\n border-radius: 2px 0 0 2px;\n}\n.ant-btn:focus > span,\n.ant-btn:active > span {\n position: relative;\n}\n.ant-btn > .anticon + span,\n.ant-btn > span + .anticon {\n margin-left: 8px;\n}\n.ant-btn.ant-btn-background-ghost {\n color: #fff;\n border-color: #fff;\n}\n.ant-btn.ant-btn-background-ghost,\n.ant-btn.ant-btn-background-ghost:hover,\n.ant-btn.ant-btn-background-ghost:active,\n.ant-btn.ant-btn-background-ghost:focus {\n background: transparent;\n}\n.ant-btn.ant-btn-background-ghost:hover,\n.ant-btn.ant-btn-background-ghost:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n}\n.ant-btn.ant-btn-background-ghost:active {\n color: #096dd9;\n border-color: #096dd9;\n}\n.ant-btn.ant-btn-background-ghost[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background: transparent;\n border-color: #d9d9d9;\n}\n.ant-btn-background-ghost.ant-btn-primary {\n color: #1890ff;\n border-color: #1890ff;\n text-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-primary > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-primary > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-primary:hover,\n.ant-btn-background-ghost.ant-btn-primary:focus {\n color: #40a9ff;\n border-color: #40a9ff;\n}\n.ant-btn-background-ghost.ant-btn-primary:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-primary:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-primary:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-primary:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-primary:active {\n color: #096dd9;\n border-color: #096dd9;\n}\n.ant-btn-background-ghost.ant-btn-primary:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-primary:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-primary[disabled],\n.ant-btn-background-ghost.ant-btn-primary[disabled]:hover,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:focus,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-primary[disabled] > a:only-child,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:focus > a:only-child,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-primary[disabled] > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:focus > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-primary[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-danger {\n color: #ff4d4f;\n border-color: #ff4d4f;\n text-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-danger > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-danger > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-danger:hover,\n.ant-btn-background-ghost.ant-btn-danger:focus {\n color: #ff7875;\n border-color: #ff7875;\n}\n.ant-btn-background-ghost.ant-btn-danger:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-danger:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-danger:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-danger:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-danger:active {\n color: #d9363e;\n border-color: #d9363e;\n}\n.ant-btn-background-ghost.ant-btn-danger:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-danger:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-danger[disabled],\n.ant-btn-background-ghost.ant-btn-danger[disabled]:hover,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:focus,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-danger[disabled] > a:only-child,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:focus > a:only-child,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-danger[disabled] > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:focus > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-danger[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous {\n color: #ff4d4f;\n border-color: #ff4d4f;\n text-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-dangerous > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous:hover,\n.ant-btn-background-ghost.ant-btn-dangerous:focus {\n color: #ff7875;\n border-color: #ff7875;\n}\n.ant-btn-background-ghost.ant-btn-dangerous:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous:active {\n color: #d9363e;\n border-color: #d9363e;\n}\n.ant-btn-background-ghost.ant-btn-dangerous:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous[disabled],\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:hover,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:focus,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-dangerous[disabled] > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:focus > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous[disabled] > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:focus > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link {\n color: #ff4d4f;\n border-color: transparent;\n text-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:hover,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:focus {\n color: #ff7875;\n border-color: transparent;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:focus > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:focus > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:active {\n color: #d9363e;\n border-color: transparent;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled],\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:hover,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:focus,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n background: #f5f5f5;\n text-shadow: none;\n box-shadow: none;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child {\n color: currentcolor;\n}\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled] > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:hover > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:focus > a:only-child::after,\n.ant-btn-background-ghost.ant-btn-dangerous.ant-btn-link[disabled]:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\n.ant-btn-two-chinese-chars::first-letter {\n letter-spacing: 0.34em;\n}\n.ant-btn-two-chinese-chars > *:not(.anticon) {\n margin-right: -0.34em;\n letter-spacing: 0.34em;\n}\n.ant-btn.ant-btn-block {\n width: 100%;\n}\n.ant-btn:empty {\n display: inline-block;\n width: 0;\n visibility: hidden;\n content: '\\a0';\n}\na.ant-btn {\n padding-top: 0.01px !important;\n line-height: 30px;\n}\na.ant-btn-disabled {\n cursor: not-allowed;\n}\na.ant-btn-disabled > * {\n pointer-events: none;\n}\na.ant-btn-disabled,\na.ant-btn-disabled:hover,\na.ant-btn-disabled:focus,\na.ant-btn-disabled:active {\n color: rgba(0, 0, 0, 0.25);\n border-color: transparent;\n background: transparent;\n text-shadow: none;\n box-shadow: none;\n}\na.ant-btn-disabled > a:only-child,\na.ant-btn-disabled:hover > a:only-child,\na.ant-btn-disabled:focus > a:only-child,\na.ant-btn-disabled:active > a:only-child {\n color: currentcolor;\n}\na.ant-btn-disabled > a:only-child::after,\na.ant-btn-disabled:hover > a:only-child::after,\na.ant-btn-disabled:focus > a:only-child::after,\na.ant-btn-disabled:active > a:only-child::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n content: '';\n}\na.ant-btn-lg {\n line-height: 38px;\n}\na.ant-btn-sm {\n line-height: 22px;\n}\n.ant-btn-compact-item:not(.ant-btn-compact-last-item):not(.ant-btn-compact-item-rtl) {\n margin-right: -1px;\n}\n.ant-btn-compact-item:not(.ant-btn-compact-last-item).ant-btn-compact-item-rtl {\n margin-left: -1px;\n}\n.ant-btn-compact-item:hover,\n.ant-btn-compact-item:focus,\n.ant-btn-compact-item:active {\n z-index: 2;\n}\n.ant-btn-compact-item[disabled] {\n z-index: 0;\n}\n.ant-btn-compact-item:not(.ant-btn-compact-first-item):not(.ant-btn-compact-last-item).ant-btn {\n border-radius: 0;\n}\n.ant-btn-compact-item.ant-btn.ant-btn-compact-first-item:not(.ant-btn-compact-last-item):not(.ant-btn-compact-item-rtl) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-btn-compact-item.ant-btn.ant-btn-compact-last-item:not(.ant-btn-compact-first-item):not(.ant-btn-compact-item-rtl) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-compact-item.ant-btn.ant-btn-compact-item-rtl.ant-btn-compact-first-item:not(.ant-btn-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-compact-item.ant-btn.ant-btn-compact-item-rtl.ant-btn-compact-last-item:not(.ant-btn-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-btn-icon-only.ant-btn-compact-item {\n flex: none;\n}\n.ant-btn-compact-item.ant-btn-primary:not([disabled]) + .ant-btn-compact-item.ant-btn-primary:not([disabled]) {\n position: relative;\n}\n.ant-btn-compact-item.ant-btn-primary:not([disabled]) + .ant-btn-compact-item.ant-btn-primary:not([disabled])::after {\n position: absolute;\n top: -1px;\n left: -1px;\n display: inline-block;\n width: 1px;\n height: calc(100% + 1px * 2);\n background-color: #40a9ff;\n content: ' ';\n}\n.ant-btn-compact-item-rtl.ant-btn-compact-first-item.ant-btn-compact-item-rtl:not(.ant-btn-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-compact-item-rtl.ant-btn-compact-last-item.ant-btn-compact-item-rtl:not(.ant-btn-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-btn-compact-item-rtl.ant-btn-sm.ant-btn-compact-first-item.ant-btn-compact-item-rtl.ant-btn-sm:not(.ant-btn-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-compact-item-rtl.ant-btn-sm.ant-btn-compact-last-item.ant-btn-compact-item-rtl.ant-btn-sm:not(.ant-btn-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-btn-compact-item-rtl.ant-btn-primary:not([disabled]) + .ant-btn-compact-item-rtl.ant-btn-primary:not([disabled])::after {\n right: -1px;\n}\n.ant-btn-compact-vertical-item:not(.ant-btn-compact-vertical-last-item) {\n margin-bottom: -1px;\n}\n.ant-btn-compact-vertical-item:hover,\n.ant-btn-compact-vertical-item:focus,\n.ant-btn-compact-vertical-item:active {\n z-index: 2;\n}\n.ant-btn-compact-vertical-item[disabled] {\n z-index: 0;\n}\n.ant-btn-compact-vertical-item:not(.ant-btn-compact-vertical-first-item):not(.ant-btn-compact-vertical-last-item) {\n border-radius: 0;\n}\n.ant-btn-compact-vertical-item.ant-btn-compact-vertical-first-item:not(.ant-btn-compact-vertical-last-item) {\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-btn-compact-vertical-item.ant-btn-compact-vertical-last-item:not(.ant-btn-compact-vertical-first-item) {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n}\n.ant-btn-compact-vertical-item.ant-btn-primary:not([disabled]) + .ant-btn-compact-vertical-item.ant-btn-primary:not([disabled]) {\n position: relative;\n}\n.ant-btn-compact-vertical-item.ant-btn-primary:not([disabled]) + .ant-btn-compact-vertical-item.ant-btn-primary:not([disabled])::after {\n position: absolute;\n top: -1px;\n left: -1px;\n display: inline-block;\n width: calc(100% + 1px * 2);\n height: 1px;\n background-color: #40a9ff;\n content: ' ';\n}\n.ant-btn-rtl {\n direction: rtl;\n}\n.ant-btn-group-rtl.ant-btn-group .ant-btn-primary:last-child:not(:first-child),\n.ant-btn-group-rtl.ant-btn-group .ant-btn-primary + .ant-btn-primary {\n border-right-color: #40a9ff;\n border-left-color: #d9d9d9;\n}\n.ant-btn-group-rtl.ant-btn-group .ant-btn-primary:last-child:not(:first-child)[disabled],\n.ant-btn-group-rtl.ant-btn-group .ant-btn-primary + .ant-btn-primary[disabled] {\n border-right-color: #d9d9d9;\n border-left-color: #40a9ff;\n}\n.ant-btn-rtl.ant-btn > .ant-btn-loading-icon .anticon {\n padding-right: 0;\n padding-left: 8px;\n}\n.ant-btn-rtl.ant-btn > .anticon + span,\n.ant-btn-rtl.ant-btn > span + .anticon {\n margin-right: 8px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-menu-item-danger.ant-menu-item {\n color: #ff4d4f;\n}\n.ant-menu-item-danger.ant-menu-item:hover,\n.ant-menu-item-danger.ant-menu-item-active {\n color: #ff4d4f;\n}\n.ant-menu-item-danger.ant-menu-item:active {\n background: #fff1f0;\n}\n.ant-menu-item-danger.ant-menu-item-selected {\n color: #ff4d4f;\n}\n.ant-menu-item-danger.ant-menu-item-selected > a,\n.ant-menu-item-danger.ant-menu-item-selected > a:hover {\n color: #ff4d4f;\n}\n.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-danger.ant-menu-item-selected {\n background-color: #fff1f0;\n}\n.ant-menu-inline .ant-menu-item-danger.ant-menu-item::after {\n border-right-color: #ff4d4f;\n}\n.ant-menu-dark .ant-menu-item-danger.ant-menu-item,\n.ant-menu-dark .ant-menu-item-danger.ant-menu-item:hover,\n.ant-menu-dark .ant-menu-item-danger.ant-menu-item > a {\n color: #ff4d4f;\n}\n.ant-menu-dark.ant-menu-dark:not(.ant-menu-horizontal) .ant-menu-item-danger.ant-menu-item-selected {\n color: #fff;\n background-color: #ff4d4f;\n}\n.ant-menu {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n font-variant: tabular-nums;\n line-height: 1.5715;\n font-feature-settings: 'tnum';\n margin-bottom: 0;\n padding-left: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 0;\n text-align: left;\n list-style: none;\n background: #fff;\n outline: none;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n transition: background 0.3s, width 0.3s cubic-bezier(0.2, 0, 0, 1) 0s;\n}\n.ant-menu::before {\n display: table;\n content: '';\n}\n.ant-menu::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-menu.ant-menu-root:focus-visible {\n box-shadow: 0 0 0 2px #bae7ff;\n}\n.ant-menu ul,\n.ant-menu ol {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ant-menu-overflow {\n display: flex;\n}\n.ant-menu-overflow-item {\n flex: none;\n}\n.ant-menu-hidden,\n.ant-menu-submenu-hidden {\n display: none;\n}\n.ant-menu-item-group-title {\n height: 1.5715;\n padding: 8px 16px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.5715;\n transition: all 0.3s;\n}\n.ant-menu-horizontal .ant-menu-submenu {\n transition: border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-submenu,\n.ant-menu-submenu-inline {\n transition: border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), padding 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-submenu-selected {\n color: #1890ff;\n}\n.ant-menu-item:active,\n.ant-menu-submenu-title:active {\n background: #e6f7ff;\n}\n.ant-menu-submenu .ant-menu-sub {\n cursor: initial;\n transition: background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-title-content {\n transition: color 0.3s;\n}\n.ant-menu-item a {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-menu-item a:hover {\n color: #1890ff;\n}\n.ant-menu-item a::before {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: transparent;\n content: '';\n}\n.ant-menu-item > .ant-badge a {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-menu-item > .ant-badge a:hover {\n color: #1890ff;\n}\n.ant-menu-item-divider {\n overflow: hidden;\n line-height: 0;\n border-color: #f0f0f0;\n border-style: solid;\n border-width: 1px 0 0;\n}\n.ant-menu-item-divider-dashed {\n border-style: dashed;\n}\n.ant-menu-horizontal .ant-menu-item,\n.ant-menu-horizontal .ant-menu-submenu {\n margin-top: -1px;\n}\n.ant-menu-horizontal > .ant-menu-item:hover,\n.ant-menu-horizontal > .ant-menu-item-active,\n.ant-menu-horizontal > .ant-menu-submenu .ant-menu-submenu-title:hover {\n background-color: transparent;\n}\n.ant-menu-item-selected {\n color: #1890ff;\n}\n.ant-menu-item-selected a,\n.ant-menu-item-selected a:hover {\n color: #1890ff;\n}\n.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {\n background-color: #e6f7ff;\n}\n.ant-menu-inline,\n.ant-menu-vertical,\n.ant-menu-vertical-left {\n border-right: 1px solid #f0f0f0;\n}\n.ant-menu-vertical-right {\n border-left: 1px solid #f0f0f0;\n}\n.ant-menu-vertical.ant-menu-sub,\n.ant-menu-vertical-left.ant-menu-sub,\n.ant-menu-vertical-right.ant-menu-sub {\n min-width: 160px;\n max-height: calc(100vh - 100px);\n padding: 0;\n overflow: hidden;\n border-right: 0;\n}\n.ant-menu-vertical.ant-menu-sub:not([class*='-active']),\n.ant-menu-vertical-left.ant-menu-sub:not([class*='-active']),\n.ant-menu-vertical-right.ant-menu-sub:not([class*='-active']) {\n overflow-x: hidden;\n overflow-y: auto;\n}\n.ant-menu-vertical.ant-menu-sub .ant-menu-item,\n.ant-menu-vertical-left.ant-menu-sub .ant-menu-item,\n.ant-menu-vertical-right.ant-menu-sub .ant-menu-item {\n left: 0;\n margin-left: 0;\n border-right: 0;\n}\n.ant-menu-vertical.ant-menu-sub .ant-menu-item::after,\n.ant-menu-vertical-left.ant-menu-sub .ant-menu-item::after,\n.ant-menu-vertical-right.ant-menu-sub .ant-menu-item::after {\n border-right: 0;\n}\n.ant-menu-vertical.ant-menu-sub > .ant-menu-item,\n.ant-menu-vertical-left.ant-menu-sub > .ant-menu-item,\n.ant-menu-vertical-right.ant-menu-sub > .ant-menu-item,\n.ant-menu-vertical.ant-menu-sub > .ant-menu-submenu,\n.ant-menu-vertical-left.ant-menu-sub > .ant-menu-submenu,\n.ant-menu-vertical-right.ant-menu-sub > .ant-menu-submenu {\n transform-origin: 0 0;\n}\n.ant-menu-horizontal.ant-menu-sub {\n min-width: 114px;\n}\n.ant-menu-horizontal .ant-menu-item,\n.ant-menu-horizontal .ant-menu-submenu-title {\n transition: border-color 0.3s, background 0.3s;\n}\n.ant-menu-item,\n.ant-menu-submenu-title {\n position: relative;\n display: block;\n margin: 0;\n padding: 0 20px;\n white-space: nowrap;\n cursor: pointer;\n transition: border-color 0.3s, background 0.3s, padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-item .ant-menu-item-icon,\n.ant-menu-submenu-title .ant-menu-item-icon,\n.ant-menu-item .anticon,\n.ant-menu-submenu-title .anticon {\n min-width: 14px;\n font-size: 14px;\n transition: font-size 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), margin 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), color 0.3s;\n}\n.ant-menu-item .ant-menu-item-icon + span,\n.ant-menu-submenu-title .ant-menu-item-icon + span,\n.ant-menu-item .anticon + span,\n.ant-menu-submenu-title .anticon + span {\n margin-left: 10px;\n opacity: 1;\n transition: opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), margin 0.3s, color 0.3s;\n}\n.ant-menu-item .ant-menu-item-icon.svg,\n.ant-menu-submenu-title .ant-menu-item-icon.svg {\n vertical-align: -0.125em;\n}\n.ant-menu-item.ant-menu-item-only-child > .anticon,\n.ant-menu-submenu-title.ant-menu-item-only-child > .anticon,\n.ant-menu-item.ant-menu-item-only-child > .ant-menu-item-icon,\n.ant-menu-submenu-title.ant-menu-item-only-child > .ant-menu-item-icon {\n margin-right: 0;\n}\n.ant-menu-item:not(.ant-menu-item-disabled):focus-visible,\n.ant-menu-submenu-title:not(.ant-menu-item-disabled):focus-visible {\n box-shadow: 0 0 0 2px #bae7ff;\n}\n.ant-menu > .ant-menu-item-divider {\n margin: 1px 0;\n padding: 0;\n}\n.ant-menu-submenu-popup {\n position: absolute;\n z-index: 1050;\n background: transparent;\n border-radius: 2px;\n box-shadow: none;\n transform-origin: 0 0;\n}\n.ant-menu-submenu-popup::before {\n position: absolute;\n top: -7px;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: -1;\n width: 100%;\n height: 100%;\n opacity: 0.0001;\n content: ' ';\n}\n.ant-menu-submenu-placement-rightTop::before {\n top: 0;\n left: -7px;\n}\n.ant-menu-submenu > .ant-menu {\n background-color: #fff;\n border-radius: 2px;\n}\n.ant-menu-submenu > .ant-menu-submenu-title::after {\n transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-submenu-popup > .ant-menu {\n background-color: #fff;\n}\n.ant-menu-submenu-expand-icon,\n.ant-menu-submenu-arrow {\n position: absolute;\n top: 50%;\n right: 16px;\n width: 10px;\n color: rgba(0, 0, 0, 0.85);\n transform: translateY(-50%);\n transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-submenu-arrow::before,\n.ant-menu-submenu-arrow::after {\n position: absolute;\n width: 6px;\n height: 1.5px;\n background-color: currentcolor;\n border-radius: 2px;\n transition: background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), top 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n content: '';\n}\n.ant-menu-submenu-arrow::before {\n transform: rotate(45deg) translateY(-2.5px);\n}\n.ant-menu-submenu-arrow::after {\n transform: rotate(-45deg) translateY(2.5px);\n}\n.ant-menu-submenu:hover > .ant-menu-submenu-title > .ant-menu-submenu-expand-icon,\n.ant-menu-submenu:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow {\n color: #1890ff;\n}\n.ant-menu-inline-collapsed .ant-menu-submenu-arrow::before,\n.ant-menu-submenu-inline .ant-menu-submenu-arrow::before {\n transform: rotate(-45deg) translateX(2.5px);\n}\n.ant-menu-inline-collapsed .ant-menu-submenu-arrow::after,\n.ant-menu-submenu-inline .ant-menu-submenu-arrow::after {\n transform: rotate(45deg) translateX(-2.5px);\n}\n.ant-menu-submenu-horizontal .ant-menu-submenu-arrow {\n display: none;\n}\n.ant-menu-submenu-open.ant-menu-submenu-inline > .ant-menu-submenu-title > .ant-menu-submenu-arrow {\n transform: translateY(-2px);\n}\n.ant-menu-submenu-open.ant-menu-submenu-inline > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after {\n transform: rotate(-45deg) translateX(-2.5px);\n}\n.ant-menu-submenu-open.ant-menu-submenu-inline > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before {\n transform: rotate(45deg) translateX(2.5px);\n}\n.ant-menu-vertical .ant-menu-submenu-selected,\n.ant-menu-vertical-left .ant-menu-submenu-selected,\n.ant-menu-vertical-right .ant-menu-submenu-selected {\n color: #1890ff;\n}\n.ant-menu-horizontal {\n line-height: 46px;\n border: 0;\n border-bottom: 1px solid #f0f0f0;\n box-shadow: none;\n}\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu {\n margin-top: -1px;\n margin-bottom: 0;\n padding: 0 20px;\n}\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item:hover,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu:hover,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-active,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-active,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-open,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-open,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-selected,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-selected {\n color: #1890ff;\n}\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item:hover::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu:hover::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-active::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-active::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-open::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-open::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-selected::after,\n.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-submenu-selected::after {\n border-bottom: 2px solid #1890ff;\n}\n.ant-menu-horizontal > .ant-menu-item,\n.ant-menu-horizontal > .ant-menu-submenu {\n position: relative;\n top: 1px;\n display: inline-block;\n vertical-align: bottom;\n}\n.ant-menu-horizontal > .ant-menu-item::after,\n.ant-menu-horizontal > .ant-menu-submenu::after {\n position: absolute;\n right: 20px;\n bottom: 0;\n left: 20px;\n border-bottom: 2px solid transparent;\n transition: border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n content: '';\n}\n.ant-menu-horizontal > .ant-menu-submenu > .ant-menu-submenu-title {\n padding: 0;\n}\n.ant-menu-horizontal > .ant-menu-item a {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-menu-horizontal > .ant-menu-item a:hover {\n color: #1890ff;\n}\n.ant-menu-horizontal > .ant-menu-item a::before {\n bottom: -2px;\n}\n.ant-menu-horizontal > .ant-menu-item-selected a {\n color: #1890ff;\n}\n.ant-menu-horizontal::after {\n display: block;\n clear: both;\n height: 0;\n content: '\\20';\n}\n.ant-menu-vertical .ant-menu-item,\n.ant-menu-vertical-left .ant-menu-item,\n.ant-menu-vertical-right .ant-menu-item,\n.ant-menu-inline .ant-menu-item {\n position: relative;\n}\n.ant-menu-vertical .ant-menu-item::after,\n.ant-menu-vertical-left .ant-menu-item::after,\n.ant-menu-vertical-right .ant-menu-item::after,\n.ant-menu-inline .ant-menu-item::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n border-right: 3px solid #1890ff;\n transform: scaleY(0.0001);\n opacity: 0;\n transition: transform 0.15s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.15s cubic-bezier(0.215, 0.61, 0.355, 1);\n content: '';\n}\n.ant-menu-vertical .ant-menu-item,\n.ant-menu-vertical-left .ant-menu-item,\n.ant-menu-vertical-right .ant-menu-item,\n.ant-menu-inline .ant-menu-item,\n.ant-menu-vertical .ant-menu-submenu-title,\n.ant-menu-vertical-left .ant-menu-submenu-title,\n.ant-menu-vertical-right .ant-menu-submenu-title,\n.ant-menu-inline .ant-menu-submenu-title {\n height: 40px;\n margin-top: 4px;\n margin-bottom: 4px;\n padding: 0 16px;\n overflow: hidden;\n line-height: 40px;\n text-overflow: ellipsis;\n}\n.ant-menu-vertical .ant-menu-submenu,\n.ant-menu-vertical-left .ant-menu-submenu,\n.ant-menu-vertical-right .ant-menu-submenu,\n.ant-menu-inline .ant-menu-submenu {\n padding-bottom: 0.02px;\n}\n.ant-menu-vertical .ant-menu-item:not(:last-child),\n.ant-menu-vertical-left .ant-menu-item:not(:last-child),\n.ant-menu-vertical-right .ant-menu-item:not(:last-child),\n.ant-menu-inline .ant-menu-item:not(:last-child) {\n margin-bottom: 8px;\n}\n.ant-menu-vertical > .ant-menu-item,\n.ant-menu-vertical-left > .ant-menu-item,\n.ant-menu-vertical-right > .ant-menu-item,\n.ant-menu-inline > .ant-menu-item,\n.ant-menu-vertical > .ant-menu-submenu > .ant-menu-submenu-title,\n.ant-menu-vertical-left > .ant-menu-submenu > .ant-menu-submenu-title,\n.ant-menu-vertical-right > .ant-menu-submenu > .ant-menu-submenu-title,\n.ant-menu-inline > .ant-menu-submenu > .ant-menu-submenu-title {\n height: 40px;\n line-height: 40px;\n}\n.ant-menu-vertical .ant-menu-item-group-list .ant-menu-submenu-title,\n.ant-menu-vertical .ant-menu-submenu-title {\n padding-right: 34px;\n}\n.ant-menu-inline {\n width: 100%;\n}\n.ant-menu-inline .ant-menu-selected::after,\n.ant-menu-inline .ant-menu-item-selected::after {\n transform: scaleY(1);\n opacity: 1;\n transition: transform 0.15s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-menu-inline .ant-menu-item,\n.ant-menu-inline .ant-menu-submenu-title {\n width: calc(100% + 1px);\n}\n.ant-menu-inline .ant-menu-item-group-list .ant-menu-submenu-title,\n.ant-menu-inline .ant-menu-submenu-title {\n padding-right: 34px;\n}\n.ant-menu-inline.ant-menu-root .ant-menu-item,\n.ant-menu-inline.ant-menu-root .ant-menu-submenu-title {\n display: flex;\n align-items: center;\n transition: border-color 0.3s, background 0.3s, padding 0.1s cubic-bezier(0.215, 0.61, 0.355, 1);\n}\n.ant-menu-inline.ant-menu-root .ant-menu-item > .ant-menu-title-content,\n.ant-menu-inline.ant-menu-root .ant-menu-submenu-title > .ant-menu-title-content {\n flex: auto;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.ant-menu-inline.ant-menu-root .ant-menu-item > *,\n.ant-menu-inline.ant-menu-root .ant-menu-submenu-title > * {\n flex: none;\n}\n.ant-menu.ant-menu-inline-collapsed {\n width: 80px;\n}\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title {\n left: 0;\n padding: 0 calc(50% - 16px / 2);\n text-overflow: clip;\n}\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item .ant-menu-submenu-arrow,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item .ant-menu-submenu-arrow,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-submenu-arrow {\n opacity: 0;\n}\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item .anticon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item .anticon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title .anticon,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title .anticon {\n margin: 0;\n font-size: 16px;\n line-height: 40px;\n}\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item .ant-menu-item-icon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item .ant-menu-item-icon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-item-icon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title .ant-menu-item-icon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item .anticon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-item .anticon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-item-group > .ant-menu-item-group-list > .ant-menu-submenu > .ant-menu-submenu-title .anticon + span,\n.ant-menu.ant-menu-inline-collapsed > .ant-menu-submenu > .ant-menu-submenu-title .anticon + span {\n display: inline-block;\n opacity: 0;\n}\n.ant-menu.ant-menu-inline-collapsed .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed .anticon {\n display: inline-block;\n}\n.ant-menu.ant-menu-inline-collapsed-tooltip {\n pointer-events: none;\n}\n.ant-menu.ant-menu-inline-collapsed-tooltip .ant-menu-item-icon,\n.ant-menu.ant-menu-inline-collapsed-tooltip .anticon {\n display: none;\n}\n.ant-menu.ant-menu-inline-collapsed-tooltip a {\n color: rgba(255, 255, 255, 0.85);\n}\n.ant-menu.ant-menu-inline-collapsed .ant-menu-item-group-title {\n padding-right: 4px;\n padding-left: 4px;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-menu-item-group-list {\n margin: 0;\n padding: 0;\n}\n.ant-menu-item-group-list .ant-menu-item,\n.ant-menu-item-group-list .ant-menu-submenu-title {\n padding: 0 16px 0 28px;\n}\n.ant-menu-root.ant-menu-vertical,\n.ant-menu-root.ant-menu-vertical-left,\n.ant-menu-root.ant-menu-vertical-right,\n.ant-menu-root.ant-menu-inline {\n box-shadow: none;\n}\n.ant-menu-root.ant-menu-inline-collapsed .ant-menu-item > .ant-menu-inline-collapsed-noicon,\n.ant-menu-root.ant-menu-inline-collapsed .ant-menu-submenu .ant-menu-submenu-title > .ant-menu-inline-collapsed-noicon {\n font-size: 16px;\n text-align: center;\n}\n.ant-menu-sub.ant-menu-inline {\n padding: 0;\n background: #fafafa;\n border: 0;\n border-radius: 0;\n box-shadow: none;\n}\n.ant-menu-sub.ant-menu-inline > .ant-menu-item,\n.ant-menu-sub.ant-menu-inline > .ant-menu-submenu > .ant-menu-submenu-title {\n height: 40px;\n line-height: 40px;\n list-style-position: inside;\n list-style-type: disc;\n}\n.ant-menu-sub.ant-menu-inline .ant-menu-item-group-title {\n padding-left: 32px;\n}\n.ant-menu-item-disabled,\n.ant-menu-submenu-disabled {\n color: rgba(0, 0, 0, 0.25) !important;\n background: none;\n cursor: not-allowed;\n}\n.ant-menu-item-disabled::after,\n.ant-menu-submenu-disabled::after {\n border-color: transparent !important;\n}\n.ant-menu-item-disabled a,\n.ant-menu-submenu-disabled a {\n color: rgba(0, 0, 0, 0.25) !important;\n pointer-events: none;\n}\n.ant-menu-item-disabled > .ant-menu-submenu-title,\n.ant-menu-submenu-disabled > .ant-menu-submenu-title {\n color: rgba(0, 0, 0, 0.25) !important;\n cursor: not-allowed;\n}\n.ant-menu-item-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-submenu-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-item-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-submenu-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after {\n background: rgba(0, 0, 0, 0.25) !important;\n}\n.ant-layout-header .ant-menu {\n line-height: inherit;\n}\n.ant-menu-inline-collapsed-tooltip a,\n.ant-menu-inline-collapsed-tooltip a:hover {\n color: #fff;\n}\n.ant-menu-light .ant-menu-item:hover,\n.ant-menu-light .ant-menu-item-active,\n.ant-menu-light .ant-menu:not(.ant-menu-inline) .ant-menu-submenu-open,\n.ant-menu-light .ant-menu-submenu-active,\n.ant-menu-light .ant-menu-submenu-title:hover {\n color: #1890ff;\n}\n.ant-menu.ant-menu-root:focus-visible {\n box-shadow: 0 0 0 2px #096dd9;\n}\n.ant-menu-dark .ant-menu-item:focus-visible,\n.ant-menu-dark .ant-menu-submenu-title:focus-visible {\n box-shadow: 0 0 0 2px #096dd9;\n}\n.ant-menu.ant-menu-dark,\n.ant-menu-dark .ant-menu-sub,\n.ant-menu.ant-menu-dark .ant-menu-sub {\n color: rgba(255, 255, 255, 0.65);\n background: #001529;\n}\n.ant-menu.ant-menu-dark .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow {\n opacity: 0.45;\n transition: all 0.3s;\n}\n.ant-menu.ant-menu-dark .ant-menu-submenu-title .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow::after,\n.ant-menu.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow::after,\n.ant-menu.ant-menu-dark .ant-menu-submenu-title .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow::before,\n.ant-menu.ant-menu-dark .ant-menu-sub .ant-menu-submenu-title .ant-menu-submenu-arrow::before {\n background: #fff;\n}\n.ant-menu-dark.ant-menu-submenu-popup {\n background: transparent;\n}\n.ant-menu-dark .ant-menu-inline.ant-menu-sub {\n background: #000c17;\n}\n.ant-menu-dark.ant-menu-horizontal {\n border-bottom: 0;\n}\n.ant-menu-dark.ant-menu-horizontal > .ant-menu-item,\n.ant-menu-dark.ant-menu-horizontal > .ant-menu-submenu {\n top: 0;\n margin-top: 0;\n padding: 0 20px;\n border-color: #001529;\n border-bottom: 0;\n}\n.ant-menu-dark.ant-menu-horizontal > .ant-menu-item:hover {\n background-color: #1890ff;\n}\n.ant-menu-dark.ant-menu-horizontal > .ant-menu-item > a::before {\n bottom: 0;\n}\n.ant-menu-dark .ant-menu-item,\n.ant-menu-dark .ant-menu-item-group-title,\n.ant-menu-dark .ant-menu-item > a,\n.ant-menu-dark .ant-menu-item > span > a {\n color: rgba(255, 255, 255, 0.65);\n}\n.ant-menu-dark.ant-menu-inline,\n.ant-menu-dark.ant-menu-vertical,\n.ant-menu-dark.ant-menu-vertical-left,\n.ant-menu-dark.ant-menu-vertical-right {\n border-right: 0;\n}\n.ant-menu-dark.ant-menu-inline .ant-menu-item,\n.ant-menu-dark.ant-menu-vertical .ant-menu-item,\n.ant-menu-dark.ant-menu-vertical-left .ant-menu-item,\n.ant-menu-dark.ant-menu-vertical-right .ant-menu-item {\n left: 0;\n margin-left: 0;\n border-right: 0;\n}\n.ant-menu-dark.ant-menu-inline .ant-menu-item::after,\n.ant-menu-dark.ant-menu-vertical .ant-menu-item::after,\n.ant-menu-dark.ant-menu-vertical-left .ant-menu-item::after,\n.ant-menu-dark.ant-menu-vertical-right .ant-menu-item::after {\n border-right: 0;\n}\n.ant-menu-dark.ant-menu-inline .ant-menu-item,\n.ant-menu-dark.ant-menu-inline .ant-menu-submenu-title {\n width: 100%;\n}\n.ant-menu-dark .ant-menu-item:hover,\n.ant-menu-dark .ant-menu-item-active,\n.ant-menu-dark .ant-menu-submenu-active,\n.ant-menu-dark .ant-menu-submenu-open,\n.ant-menu-dark .ant-menu-submenu-selected,\n.ant-menu-dark .ant-menu-submenu-title:hover {\n color: #fff;\n background-color: transparent;\n}\n.ant-menu-dark .ant-menu-item:hover > a,\n.ant-menu-dark .ant-menu-item-active > a,\n.ant-menu-dark .ant-menu-submenu-active > a,\n.ant-menu-dark .ant-menu-submenu-open > a,\n.ant-menu-dark .ant-menu-submenu-selected > a,\n.ant-menu-dark .ant-menu-submenu-title:hover > a,\n.ant-menu-dark .ant-menu-item:hover > span > a,\n.ant-menu-dark .ant-menu-item-active > span > a,\n.ant-menu-dark .ant-menu-submenu-active > span > a,\n.ant-menu-dark .ant-menu-submenu-open > span > a,\n.ant-menu-dark .ant-menu-submenu-selected > span > a,\n.ant-menu-dark .ant-menu-submenu-title:hover > span > a {\n color: #fff;\n}\n.ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title > .ant-menu-submenu-arrow,\n.ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow {\n opacity: 1;\n}\n.ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-item:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-item-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-submenu-active > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-submenu-open > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-submenu-selected > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-submenu-title:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before {\n background: #fff;\n}\n.ant-menu-dark .ant-menu-item:hover {\n background-color: transparent;\n}\n.ant-menu-dark.ant-menu-dark:not(.ant-menu-horizontal) .ant-menu-item-selected {\n background-color: #1890ff;\n}\n.ant-menu-dark .ant-menu-item-selected {\n color: #fff;\n border-right: 0;\n}\n.ant-menu-dark .ant-menu-item-selected::after {\n border-right: 0;\n}\n.ant-menu-dark .ant-menu-item-selected > a,\n.ant-menu-dark .ant-menu-item-selected > span > a,\n.ant-menu-dark .ant-menu-item-selected > a:hover,\n.ant-menu-dark .ant-menu-item-selected > span > a:hover {\n color: #fff;\n}\n.ant-menu-dark .ant-menu-item-selected .ant-menu-item-icon,\n.ant-menu-dark .ant-menu-item-selected .anticon {\n color: #fff;\n}\n.ant-menu-dark .ant-menu-item-selected .ant-menu-item-icon + span,\n.ant-menu-dark .ant-menu-item-selected .anticon + span {\n color: #fff;\n}\n.ant-menu.ant-menu-dark .ant-menu-item-selected,\n.ant-menu-submenu-popup.ant-menu-dark .ant-menu-item-selected {\n background-color: #1890ff;\n}\n.ant-menu-dark .ant-menu-item-disabled,\n.ant-menu-dark .ant-menu-submenu-disabled,\n.ant-menu-dark .ant-menu-item-disabled > a,\n.ant-menu-dark .ant-menu-submenu-disabled > a,\n.ant-menu-dark .ant-menu-item-disabled > span > a,\n.ant-menu-dark .ant-menu-submenu-disabled > span > a {\n color: rgba(255, 255, 255, 0.35) !important;\n opacity: 0.8;\n}\n.ant-menu-dark .ant-menu-item-disabled > .ant-menu-submenu-title,\n.ant-menu-dark .ant-menu-submenu-disabled > .ant-menu-submenu-title {\n color: rgba(255, 255, 255, 0.35) !important;\n}\n.ant-menu-dark .ant-menu-item-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-submenu-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::before,\n.ant-menu-dark .ant-menu-item-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after,\n.ant-menu-dark .ant-menu-submenu-disabled > .ant-menu-submenu-title > .ant-menu-submenu-arrow::after {\n background: rgba(255, 255, 255, 0.35) !important;\n}\n.ant-menu.ant-menu-rtl {\n direction: rtl;\n text-align: right;\n}\n.ant-menu-rtl .ant-menu-item-group-title {\n text-align: right;\n}\n.ant-menu-rtl.ant-menu-inline,\n.ant-menu-rtl.ant-menu-vertical {\n border-right: none;\n border-left: 1px solid #f0f0f0;\n}\n.ant-menu-rtl.ant-menu-dark.ant-menu-inline,\n.ant-menu-rtl.ant-menu-dark.ant-menu-vertical {\n border-left: none;\n}\n.ant-menu-rtl.ant-menu-vertical.ant-menu-sub > .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical-left.ant-menu-sub > .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical-right.ant-menu-sub > .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical.ant-menu-sub > .ant-menu-submenu,\n.ant-menu-rtl.ant-menu-vertical-left.ant-menu-sub > .ant-menu-submenu,\n.ant-menu-rtl.ant-menu-vertical-right.ant-menu-sub > .ant-menu-submenu {\n transform-origin: top right;\n}\n.ant-menu-rtl .ant-menu-item .ant-menu-item-icon,\n.ant-menu-rtl .ant-menu-submenu-title .ant-menu-item-icon,\n.ant-menu-rtl .ant-menu-item .anticon,\n.ant-menu-rtl .ant-menu-submenu-title .anticon {\n margin-right: auto;\n margin-left: 10px;\n}\n.ant-menu-rtl .ant-menu-item.ant-menu-item-only-child > .ant-menu-item-icon,\n.ant-menu-rtl .ant-menu-submenu-title.ant-menu-item-only-child > .ant-menu-item-icon,\n.ant-menu-rtl .ant-menu-item.ant-menu-item-only-child > .anticon,\n.ant-menu-rtl .ant-menu-submenu-title.ant-menu-item-only-child > .anticon {\n margin-left: 0;\n}\n.ant-menu-submenu-rtl.ant-menu-submenu-popup {\n transform-origin: 100% 0;\n}\n.ant-menu-rtl .ant-menu-submenu-vertical > .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu-rtl .ant-menu-submenu-vertical-left > .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu-rtl .ant-menu-submenu-vertical-right > .ant-menu-submenu-title .ant-menu-submenu-arrow,\n.ant-menu-rtl .ant-menu-submenu-inline > .ant-menu-submenu-title .ant-menu-submenu-arrow {\n right: auto;\n left: 16px;\n}\n.ant-menu-rtl .ant-menu-submenu-vertical > .ant-menu-submenu-title .ant-menu-submenu-arrow::before,\n.ant-menu-rtl .ant-menu-submenu-vertical-left > .ant-menu-submenu-title .ant-menu-submenu-arrow::before,\n.ant-menu-rtl .ant-menu-submenu-vertical-right > .ant-menu-submenu-title .ant-menu-submenu-arrow::before {\n transform: rotate(-45deg) translateY(-2px);\n}\n.ant-menu-rtl .ant-menu-submenu-vertical > .ant-menu-submenu-title .ant-menu-submenu-arrow::after,\n.ant-menu-rtl .ant-menu-submenu-vertical-left > .ant-menu-submenu-title .ant-menu-submenu-arrow::after,\n.ant-menu-rtl .ant-menu-submenu-vertical-right > .ant-menu-submenu-title .ant-menu-submenu-arrow::after {\n transform: rotate(45deg) translateY(2px);\n}\n.ant-menu-rtl.ant-menu-vertical .ant-menu-item::after,\n.ant-menu-rtl.ant-menu-vertical-left .ant-menu-item::after,\n.ant-menu-rtl.ant-menu-vertical-right .ant-menu-item::after,\n.ant-menu-rtl.ant-menu-inline .ant-menu-item::after {\n right: auto;\n left: 0;\n}\n.ant-menu-rtl.ant-menu-vertical .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical-left .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical-right .ant-menu-item,\n.ant-menu-rtl.ant-menu-inline .ant-menu-item,\n.ant-menu-rtl.ant-menu-vertical .ant-menu-submenu-title,\n.ant-menu-rtl.ant-menu-vertical-left .ant-menu-submenu-title,\n.ant-menu-rtl.ant-menu-vertical-right .ant-menu-submenu-title,\n.ant-menu-rtl.ant-menu-inline .ant-menu-submenu-title {\n text-align: right;\n}\n.ant-menu-rtl.ant-menu-inline .ant-menu-submenu-title {\n padding-right: 0;\n padding-left: 34px;\n}\n.ant-menu-rtl.ant-menu-vertical .ant-menu-submenu-title {\n padding-right: 16px;\n padding-left: 34px;\n}\n.ant-menu-rtl.ant-menu-inline-collapsed.ant-menu-vertical .ant-menu-submenu-title {\n padding: 0 calc(50% - 16px / 2);\n}\n.ant-menu-rtl .ant-menu-item-group-list .ant-menu-item,\n.ant-menu-rtl .ant-menu-item-group-list .ant-menu-submenu-title {\n padding: 0 28px 0 16px;\n}\n.ant-menu-sub.ant-menu-inline {\n border: 0;\n}\n.ant-menu-rtl.ant-menu-sub.ant-menu-inline .ant-menu-item-group-title {\n padding-right: 32px;\n padding-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-tooltip {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n z-index: 1070;\n display: block;\n width: -moz-max-content;\n width: max-content;\n width: intrinsic;\n max-width: 250px;\n visibility: visible;\n}\n.ant-tooltip-content {\n position: relative;\n}\n.ant-tooltip-hidden {\n display: none;\n}\n.ant-tooltip-placement-top,\n.ant-tooltip-placement-topLeft,\n.ant-tooltip-placement-topRight {\n padding-bottom: 14.3137085px;\n}\n.ant-tooltip-placement-right,\n.ant-tooltip-placement-rightTop,\n.ant-tooltip-placement-rightBottom {\n padding-left: 14.3137085px;\n}\n.ant-tooltip-placement-bottom,\n.ant-tooltip-placement-bottomLeft,\n.ant-tooltip-placement-bottomRight {\n padding-top: 14.3137085px;\n}\n.ant-tooltip-placement-left,\n.ant-tooltip-placement-leftTop,\n.ant-tooltip-placement-leftBottom {\n padding-right: 14.3137085px;\n}\n.ant-tooltip-inner {\n min-width: 30px;\n min-height: 32px;\n padding: 6px 8px;\n color: #fff;\n text-align: left;\n text-decoration: none;\n word-wrap: break-word;\n background-color: rgba(0, 0, 0, 0.75);\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-tooltip-arrow {\n position: absolute;\n z-index: 2;\n display: block;\n width: 22px;\n height: 22px;\n overflow: hidden;\n background: transparent;\n pointer-events: none;\n}\n.ant-tooltip-arrow-content {\n --antd-arrow-background-color: linear-gradient(to right bottom, rgba(0, 0, 0, 0.65), rgba(0, 0, 0, 0.75));\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: block;\n width: 11.3137085px;\n height: 11.3137085px;\n margin: auto;\n content: '';\n pointer-events: auto;\n border-radius: 0 0 2px;\n pointer-events: none;\n}\n.ant-tooltip-arrow-content::before {\n position: absolute;\n top: -11.3137085px;\n left: -11.3137085px;\n width: 33.9411255px;\n height: 33.9411255px;\n background: var(--antd-arrow-background-color);\n background-repeat: no-repeat;\n background-position: -10px -10px;\n content: '';\n -webkit-clip-path: inset(33% 33%);\n clip-path: inset(33% 33%);\n -webkit-clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n}\n.ant-tooltip-placement-top .ant-tooltip-arrow,\n.ant-tooltip-placement-topLeft .ant-tooltip-arrow,\n.ant-tooltip-placement-topRight .ant-tooltip-arrow {\n bottom: 0;\n transform: translateY(100%);\n}\n.ant-tooltip-placement-top .ant-tooltip-arrow-content,\n.ant-tooltip-placement-topLeft .ant-tooltip-arrow-content,\n.ant-tooltip-placement-topRight .ant-tooltip-arrow-content {\n box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n transform: translateY(-11px) rotate(45deg);\n}\n.ant-tooltip-placement-top .ant-tooltip-arrow {\n left: 50%;\n transform: translateY(100%) translateX(-50%);\n}\n.ant-tooltip-placement-topLeft .ant-tooltip-arrow {\n left: 13px;\n}\n.ant-tooltip-placement-topRight .ant-tooltip-arrow {\n right: 13px;\n}\n.ant-tooltip-placement-right .ant-tooltip-arrow,\n.ant-tooltip-placement-rightTop .ant-tooltip-arrow,\n.ant-tooltip-placement-rightBottom .ant-tooltip-arrow {\n left: 0;\n transform: translateX(-100%);\n}\n.ant-tooltip-placement-right .ant-tooltip-arrow-content,\n.ant-tooltip-placement-rightTop .ant-tooltip-arrow-content,\n.ant-tooltip-placement-rightBottom .ant-tooltip-arrow-content {\n box-shadow: -3px 3px 7px rgba(0, 0, 0, 0.07);\n transform: translateX(11px) rotate(135deg);\n}\n.ant-tooltip-placement-right .ant-tooltip-arrow {\n top: 50%;\n transform: translateX(-100%) translateY(-50%);\n}\n.ant-tooltip-placement-rightTop .ant-tooltip-arrow {\n top: 5px;\n}\n.ant-tooltip-placement-rightBottom .ant-tooltip-arrow {\n bottom: 5px;\n}\n.ant-tooltip-placement-left .ant-tooltip-arrow,\n.ant-tooltip-placement-leftTop .ant-tooltip-arrow,\n.ant-tooltip-placement-leftBottom .ant-tooltip-arrow {\n right: 0;\n transform: translateX(100%);\n}\n.ant-tooltip-placement-left .ant-tooltip-arrow-content,\n.ant-tooltip-placement-leftTop .ant-tooltip-arrow-content,\n.ant-tooltip-placement-leftBottom .ant-tooltip-arrow-content {\n box-shadow: 3px -3px 7px rgba(0, 0, 0, 0.07);\n transform: translateX(-11px) rotate(315deg);\n}\n.ant-tooltip-placement-left .ant-tooltip-arrow {\n top: 50%;\n transform: translateX(100%) translateY(-50%);\n}\n.ant-tooltip-placement-leftTop .ant-tooltip-arrow {\n top: 5px;\n}\n.ant-tooltip-placement-leftBottom .ant-tooltip-arrow {\n bottom: 5px;\n}\n.ant-tooltip-placement-bottom .ant-tooltip-arrow,\n.ant-tooltip-placement-bottomLeft .ant-tooltip-arrow,\n.ant-tooltip-placement-bottomRight .ant-tooltip-arrow {\n top: 0;\n transform: translateY(-100%);\n}\n.ant-tooltip-placement-bottom .ant-tooltip-arrow-content,\n.ant-tooltip-placement-bottomLeft .ant-tooltip-arrow-content,\n.ant-tooltip-placement-bottomRight .ant-tooltip-arrow-content {\n box-shadow: -3px -3px 7px rgba(0, 0, 0, 0.07);\n transform: translateY(11px) rotate(225deg);\n}\n.ant-tooltip-placement-bottom .ant-tooltip-arrow {\n left: 50%;\n transform: translateY(-100%) translateX(-50%);\n}\n.ant-tooltip-placement-bottomLeft .ant-tooltip-arrow {\n left: 13px;\n}\n.ant-tooltip-placement-bottomRight .ant-tooltip-arrow {\n right: 13px;\n}\n.ant-tooltip-pink .ant-tooltip-inner {\n background-color: #eb2f96;\n}\n.ant-tooltip-pink .ant-tooltip-arrow-content::before {\n background: #eb2f96;\n}\n.ant-tooltip-magenta .ant-tooltip-inner {\n background-color: #eb2f96;\n}\n.ant-tooltip-magenta .ant-tooltip-arrow-content::before {\n background: #eb2f96;\n}\n.ant-tooltip-red .ant-tooltip-inner {\n background-color: #f5222d;\n}\n.ant-tooltip-red .ant-tooltip-arrow-content::before {\n background: #f5222d;\n}\n.ant-tooltip-volcano .ant-tooltip-inner {\n background-color: #fa541c;\n}\n.ant-tooltip-volcano .ant-tooltip-arrow-content::before {\n background: #fa541c;\n}\n.ant-tooltip-orange .ant-tooltip-inner {\n background-color: #fa8c16;\n}\n.ant-tooltip-orange .ant-tooltip-arrow-content::before {\n background: #fa8c16;\n}\n.ant-tooltip-yellow .ant-tooltip-inner {\n background-color: #fadb14;\n}\n.ant-tooltip-yellow .ant-tooltip-arrow-content::before {\n background: #fadb14;\n}\n.ant-tooltip-gold .ant-tooltip-inner {\n background-color: #faad14;\n}\n.ant-tooltip-gold .ant-tooltip-arrow-content::before {\n background: #faad14;\n}\n.ant-tooltip-cyan .ant-tooltip-inner {\n background-color: #13c2c2;\n}\n.ant-tooltip-cyan .ant-tooltip-arrow-content::before {\n background: #13c2c2;\n}\n.ant-tooltip-lime .ant-tooltip-inner {\n background-color: #a0d911;\n}\n.ant-tooltip-lime .ant-tooltip-arrow-content::before {\n background: #a0d911;\n}\n.ant-tooltip-green .ant-tooltip-inner {\n background-color: #52c41a;\n}\n.ant-tooltip-green .ant-tooltip-arrow-content::before {\n background: #52c41a;\n}\n.ant-tooltip-blue .ant-tooltip-inner {\n background-color: #1890ff;\n}\n.ant-tooltip-blue .ant-tooltip-arrow-content::before {\n background: #1890ff;\n}\n.ant-tooltip-geekblue .ant-tooltip-inner {\n background-color: #2f54eb;\n}\n.ant-tooltip-geekblue .ant-tooltip-arrow-content::before {\n background: #2f54eb;\n}\n.ant-tooltip-purple .ant-tooltip-inner {\n background-color: #722ed1;\n}\n.ant-tooltip-purple .ant-tooltip-arrow-content::before {\n background: #722ed1;\n}\n.ant-tooltip-rtl {\n direction: rtl;\n}\n.ant-tooltip-rtl .ant-tooltip-inner {\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-space {\n display: inline-flex;\n}\n.ant-space-vertical {\n flex-direction: column;\n}\n.ant-space-align-center {\n align-items: center;\n}\n.ant-space-align-start {\n align-items: flex-start;\n}\n.ant-space-align-end {\n align-items: flex-end;\n}\n.ant-space-align-baseline {\n align-items: baseline;\n}\n.ant-space-item:empty {\n display: none;\n}\n.ant-space-compact {\n display: inline-flex;\n}\n.ant-space-compact-block {\n display: flex;\n width: 100%;\n}\n.ant-space-compact-vertical {\n flex-direction: column;\n}\n.ant-space-rtl {\n direction: rtl;\n}\n.ant-space-compact-rtl {\n direction: rtl;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-picker-calendar {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n background: #fff;\n}\n.ant-picker-calendar-header {\n display: flex;\n justify-content: flex-end;\n padding: 12px 0;\n}\n.ant-picker-calendar-header .ant-picker-calendar-year-select {\n min-width: 80px;\n}\n.ant-picker-calendar-header .ant-picker-calendar-month-select {\n min-width: 70px;\n margin-left: 8px;\n}\n.ant-picker-calendar-header .ant-picker-calendar-mode-switch {\n margin-left: 8px;\n}\n.ant-picker-calendar .ant-picker-panel {\n background: #fff;\n border: 0;\n border-top: 1px solid #f0f0f0;\n border-radius: 0;\n}\n.ant-picker-calendar .ant-picker-panel .ant-picker-month-panel,\n.ant-picker-calendar .ant-picker-panel .ant-picker-date-panel {\n width: auto;\n}\n.ant-picker-calendar .ant-picker-panel .ant-picker-body {\n padding: 8px 0;\n}\n.ant-picker-calendar .ant-picker-panel .ant-picker-content {\n width: 100%;\n}\n.ant-picker-calendar-mini {\n border-radius: 2px;\n}\n.ant-picker-calendar-mini .ant-picker-calendar-header {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-picker-calendar-mini .ant-picker-panel {\n border-radius: 0 0 2px 2px;\n}\n.ant-picker-calendar-mini .ant-picker-content {\n height: 256px;\n}\n.ant-picker-calendar-mini .ant-picker-content th {\n height: auto;\n padding: 0;\n line-height: 18px;\n}\n.ant-picker-calendar-mini .ant-picker-cell::before {\n pointer-events: none;\n}\n.ant-picker-calendar-full .ant-picker-panel {\n display: block;\n width: 100%;\n text-align: right;\n background: #fff;\n border: 0;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-body th,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-body td {\n padding: 0;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-body th {\n height: auto;\n padding: 0 12px 5px 0;\n line-height: 18px;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell::before {\n display: none;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell:hover .ant-picker-calendar-date {\n background: #f5f5f5;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell .ant-picker-calendar-date-today::before {\n display: none;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected .ant-picker-calendar-date,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected:hover .ant-picker-calendar-date,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected .ant-picker-calendar-date-today,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected:hover .ant-picker-calendar-date-today {\n background: #e6f7ff;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected .ant-picker-calendar-date .ant-picker-calendar-date-value,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected:hover .ant-picker-calendar-date .ant-picker-calendar-date-value,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected .ant-picker-calendar-date-today .ant-picker-calendar-date-value,\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-cell-selected:hover .ant-picker-calendar-date-today .ant-picker-calendar-date-value {\n color: #1890ff;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date {\n display: block;\n width: auto;\n height: auto;\n margin: 0 4px;\n padding: 4px 8px 0;\n border: 0;\n border-top: 2px solid #f0f0f0;\n border-radius: 0;\n transition: background 0.3s;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date-value {\n line-height: 24px;\n transition: color 0.3s;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date-content {\n position: static;\n width: auto;\n height: 86px;\n overflow-y: auto;\n color: rgba(0, 0, 0, 0.85);\n line-height: 1.5715;\n text-align: left;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date-today {\n border-color: #1890ff;\n}\n.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date-today .ant-picker-calendar-date-value {\n color: rgba(0, 0, 0, 0.85);\n}\n@media only screen and (max-width: 480px) {\n .ant-picker-calendar-header {\n display: block;\n }\n .ant-picker-calendar-header .ant-picker-calendar-year-select {\n width: 50%;\n }\n .ant-picker-calendar-header .ant-picker-calendar-month-select {\n width: calc(50% - 8px);\n }\n .ant-picker-calendar-header .ant-picker-calendar-mode-switch {\n width: 100%;\n margin-top: 8px;\n margin-left: 0;\n }\n .ant-picker-calendar-header .ant-picker-calendar-mode-switch > label {\n width: 50%;\n text-align: center;\n }\n}\n.ant-picker-calendar-rtl {\n direction: rtl;\n}\n.ant-picker-calendar-rtl .ant-picker-calendar-header .ant-picker-calendar-month-select {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-picker-calendar-rtl .ant-picker-calendar-header .ant-picker-calendar-mode-switch {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-picker-calendar-rtl.ant-picker-calendar-full .ant-picker-panel {\n text-align: left;\n}\n.ant-picker-calendar-rtl.ant-picker-calendar-full .ant-picker-panel .ant-picker-body th {\n padding: 0 0 5px 12px;\n}\n.ant-picker-calendar-rtl.ant-picker-calendar-full .ant-picker-panel .ant-picker-calendar-date-content {\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-picker-status-error.ant-picker,\n.ant-picker-status-error.ant-picker:not([disabled]):hover {\n background-color: #fff;\n border-color: #ff4d4f;\n}\n.ant-picker-status-error.ant-picker-focused,\n.ant-picker-status-error.ant-picker:focus {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-picker-status-error.ant-picker .ant-picker-active-bar {\n background: #ff7875;\n}\n.ant-picker-status-warning.ant-picker,\n.ant-picker-status-warning.ant-picker:not([disabled]):hover {\n background-color: #fff;\n border-color: #faad14;\n}\n.ant-picker-status-warning.ant-picker-focused,\n.ant-picker-status-warning.ant-picker:focus {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-picker-status-warning.ant-picker .ant-picker-active-bar {\n background: #ffc53d;\n}\n.ant-picker {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n padding: 4px 11px 4px;\n position: relative;\n display: inline-flex;\n align-items: center;\n background: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: border 0.3s, box-shadow 0.3s;\n}\n.ant-picker:hover,\n.ant-picker-focused {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-picker-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-picker.ant-picker-disabled {\n background: #f5f5f5;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-picker.ant-picker-disabled .ant-picker-suffix {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-picker.ant-picker-borderless {\n background-color: transparent !important;\n border-color: transparent !important;\n box-shadow: none !important;\n}\n.ant-picker-input {\n position: relative;\n display: inline-flex;\n align-items: center;\n width: 100%;\n}\n.ant-picker-input > input {\n position: relative;\n display: inline-block;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n flex: auto;\n min-width: 1px;\n height: auto;\n padding: 0;\n background: transparent;\n border: 0;\n}\n.ant-picker-input > input::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-picker-input > input:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-picker-input > input::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-picker-input > input:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-picker-input > input:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-picker-input > input:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-picker-input > input:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-picker-input > input:focus,\n.ant-picker-input > input-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-picker-input > input-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-picker-input > input-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-picker-input > input[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-picker-input > input[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-picker-input > input-borderless,\n.ant-picker-input > input-borderless:hover,\n.ant-picker-input > input-borderless:focus,\n.ant-picker-input > input-borderless-focused,\n.ant-picker-input > input-borderless-disabled,\n.ant-picker-input > input-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-picker-input > input {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-picker-input > input-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-picker-input > input-sm {\n padding: 0px 7px;\n}\n.ant-picker-input > input:focus {\n box-shadow: none;\n}\n.ant-picker-input > input[disabled] {\n background: transparent;\n}\n.ant-picker-input:hover .ant-picker-clear {\n opacity: 1;\n}\n.ant-picker-input-placeholder > input {\n color: #bfbfbf;\n}\n.ant-picker-large {\n padding: 6.5px 11px 6.5px;\n}\n.ant-picker-large .ant-picker-input > input {\n font-size: 16px;\n}\n.ant-picker-small {\n padding: 0px 7px 0px;\n}\n.ant-picker-suffix {\n display: flex;\n flex: none;\n align-self: center;\n margin-left: 4px;\n color: rgba(0, 0, 0, 0.25);\n line-height: 1;\n pointer-events: none;\n}\n.ant-picker-suffix > * {\n vertical-align: top;\n}\n.ant-picker-suffix > *:not(:last-child) {\n margin-right: 8px;\n}\n.ant-picker-clear {\n position: absolute;\n top: 50%;\n right: 0;\n color: rgba(0, 0, 0, 0.25);\n line-height: 1;\n background: #fff;\n transform: translateY(-50%);\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.3s, color 0.3s;\n}\n.ant-picker-clear > * {\n vertical-align: top;\n}\n.ant-picker-clear:hover {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-picker-separator {\n position: relative;\n display: inline-block;\n width: 1em;\n height: 16px;\n color: rgba(0, 0, 0, 0.25);\n font-size: 16px;\n vertical-align: top;\n cursor: default;\n}\n.ant-picker-focused .ant-picker-separator {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-picker-disabled .ant-picker-range-separator .ant-picker-separator {\n cursor: not-allowed;\n}\n.ant-picker-range {\n position: relative;\n display: inline-flex;\n}\n.ant-picker-range .ant-picker-clear {\n right: 11px;\n}\n.ant-picker-range:hover .ant-picker-clear {\n opacity: 1;\n}\n.ant-picker-range .ant-picker-active-bar {\n bottom: -1px;\n height: 2px;\n margin-left: 11px;\n background: #1890ff;\n opacity: 0;\n transition: all 0.3s ease-out;\n pointer-events: none;\n}\n.ant-picker-range.ant-picker-focused .ant-picker-active-bar {\n opacity: 1;\n}\n.ant-picker-range-separator {\n align-items: center;\n padding: 0 8px;\n line-height: 1;\n}\n.ant-picker-range.ant-picker-small .ant-picker-clear {\n right: 7px;\n}\n.ant-picker-range.ant-picker-small .ant-picker-active-bar {\n margin-left: 7px;\n}\n.ant-picker-dropdown {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: -9999px;\n left: -9999px;\n z-index: 1050;\n}\n.ant-picker-dropdown-hidden {\n display: none;\n}\n.ant-picker-dropdown-placement-bottomLeft .ant-picker-range-arrow {\n top: 2.58561808px;\n display: block;\n transform: rotate(-135deg) translateY(1px);\n}\n.ant-picker-dropdown-placement-topLeft .ant-picker-range-arrow {\n bottom: 2.58561808px;\n display: block;\n transform: rotate(45deg);\n}\n.ant-picker-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-picker-dropdown-placement-topLeft,\n.ant-picker-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-picker-dropdown-placement-topRight,\n.ant-picker-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-picker-dropdown-placement-topLeft,\n.ant-picker-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-picker-dropdown-placement-topRight {\n animation-name: antSlideDownIn;\n}\n.ant-picker-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-picker-dropdown-placement-bottomLeft,\n.ant-picker-dropdown.ant-slide-up-enter.ant-slide-up-enter-active.ant-picker-dropdown-placement-bottomRight,\n.ant-picker-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-picker-dropdown-placement-bottomLeft,\n.ant-picker-dropdown.ant-slide-up-appear.ant-slide-up-appear-active.ant-picker-dropdown-placement-bottomRight {\n animation-name: antSlideUpIn;\n}\n.ant-picker-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-picker-dropdown-placement-topLeft,\n.ant-picker-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-picker-dropdown-placement-topRight {\n animation-name: antSlideDownOut;\n}\n.ant-picker-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-picker-dropdown-placement-bottomLeft,\n.ant-picker-dropdown.ant-slide-up-leave.ant-slide-up-leave-active.ant-picker-dropdown-placement-bottomRight {\n animation-name: antSlideUpOut;\n}\n.ant-picker-dropdown-range {\n padding: 7.54247233px 0;\n}\n.ant-picker-dropdown-range-hidden {\n display: none;\n}\n.ant-picker-dropdown .ant-picker-panel > .ant-picker-time-panel {\n padding-top: 4px;\n}\n.ant-picker-ranges {\n margin-bottom: 0;\n padding: 4px 12px;\n overflow: hidden;\n line-height: 34px;\n text-align: left;\n list-style: none;\n}\n.ant-picker-ranges > li {\n display: inline-block;\n}\n.ant-picker-ranges .ant-picker-preset > .ant-tag-blue {\n color: #1890ff;\n background: #e6f7ff;\n border-color: #91d5ff;\n cursor: pointer;\n}\n.ant-picker-ranges .ant-picker-ok {\n float: right;\n margin-left: 8px;\n}\n.ant-picker-range-wrapper {\n display: flex;\n}\n.ant-picker-range-arrow {\n position: absolute;\n z-index: 1;\n display: none;\n width: 11.3137085px;\n height: 11.3137085px;\n margin-left: 16.5px;\n box-shadow: 2px 2px 6px -2px rgba(0, 0, 0, 0.1);\n transition: left 0.3s ease-out;\n border-radius: 0 0 2px;\n pointer-events: none;\n}\n.ant-picker-range-arrow::before {\n position: absolute;\n top: -11.3137085px;\n left: -11.3137085px;\n width: 33.9411255px;\n height: 33.9411255px;\n background: #fff;\n background-repeat: no-repeat;\n background-position: -10px -10px;\n content: '';\n -webkit-clip-path: inset(33% 33%);\n clip-path: inset(33% 33%);\n -webkit-clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n clip-path: path('M 9.849242404917499 24.091883092036785 A 5 5 0 0 1 13.384776310850237 22.627416997969522 L 20.627416997969522 22.627416997969522 A 2 2 0 0 0 22.627416997969522 20.627416997969522 L 22.627416997969522 13.384776310850237 A 5 5 0 0 1 24.091883092036785 9.849242404917499 L 23.091883092036785 9.849242404917499 L 9.849242404917499 23.091883092036785 Z');\n}\n.ant-picker-panel-container {\n overflow: hidden;\n vertical-align: top;\n background: #fff;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n transition: margin 0.3s;\n}\n.ant-picker-panel-container .ant-picker-panels {\n display: inline-flex;\n flex-wrap: nowrap;\n direction: ltr;\n}\n.ant-picker-panel-container .ant-picker-panel {\n vertical-align: top;\n background: transparent;\n border-width: 0 0 1px 0;\n border-radius: 0;\n}\n.ant-picker-panel-container .ant-picker-panel .ant-picker-content,\n.ant-picker-panel-container .ant-picker-panel table {\n text-align: center;\n}\n.ant-picker-panel-container .ant-picker-panel-focused {\n border-color: #f0f0f0;\n}\n.ant-picker-compact-item:not(.ant-picker-compact-last-item):not(.ant-picker-compact-item-rtl) {\n margin-right: -1px;\n}\n.ant-picker-compact-item:not(.ant-picker-compact-last-item).ant-picker-compact-item-rtl {\n margin-left: -1px;\n}\n.ant-picker-compact-item:hover,\n.ant-picker-compact-item:focus,\n.ant-picker-compact-item:active {\n z-index: 2;\n}\n.ant-picker-compact-item.ant-picker-focused {\n z-index: 2;\n}\n.ant-picker-compact-item[disabled] {\n z-index: 0;\n}\n.ant-picker-compact-item:not(.ant-picker-compact-first-item):not(.ant-picker-compact-last-item).ant-picker {\n border-radius: 0;\n}\n.ant-picker-compact-item.ant-picker.ant-picker-compact-first-item:not(.ant-picker-compact-last-item):not(.ant-picker-compact-item-rtl) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-picker-compact-item.ant-picker.ant-picker-compact-last-item:not(.ant-picker-compact-first-item):not(.ant-picker-compact-item-rtl) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-picker-compact-item.ant-picker.ant-picker-compact-item-rtl.ant-picker-compact-first-item:not(.ant-picker-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-picker-compact-item.ant-picker.ant-picker-compact-item-rtl.ant-picker-compact-last-item:not(.ant-picker-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-picker-panel {\n display: inline-flex;\n flex-direction: column;\n text-align: center;\n background: #fff;\n border: 1px solid #f0f0f0;\n border-radius: 2px;\n outline: none;\n}\n.ant-picker-panel-focused {\n border-color: #1890ff;\n}\n.ant-picker-decade-panel,\n.ant-picker-year-panel,\n.ant-picker-quarter-panel,\n.ant-picker-month-panel,\n.ant-picker-week-panel,\n.ant-picker-date-panel,\n.ant-picker-time-panel {\n display: flex;\n flex-direction: column;\n width: 280px;\n}\n.ant-picker-header {\n display: flex;\n padding: 0 8px;\n color: rgba(0, 0, 0, 0.85);\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-picker-header > * {\n flex: none;\n}\n.ant-picker-header button {\n padding: 0;\n color: rgba(0, 0, 0, 0.25);\n line-height: 40px;\n background: transparent;\n border: 0;\n cursor: pointer;\n transition: color 0.3s;\n}\n.ant-picker-header > button {\n min-width: 1.6em;\n font-size: 14px;\n}\n.ant-picker-header > button:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-picker-header-view {\n flex: auto;\n font-weight: 500;\n line-height: 40px;\n}\n.ant-picker-header-view button {\n color: inherit;\n font-weight: inherit;\n}\n.ant-picker-header-view button:not(:first-child) {\n margin-left: 8px;\n}\n.ant-picker-header-view button:hover {\n color: #1890ff;\n}\n.ant-picker-prev-icon,\n.ant-picker-next-icon,\n.ant-picker-super-prev-icon,\n.ant-picker-super-next-icon {\n position: relative;\n display: inline-block;\n width: 7px;\n height: 7px;\n}\n.ant-picker-prev-icon::before,\n.ant-picker-next-icon::before,\n.ant-picker-super-prev-icon::before,\n.ant-picker-super-next-icon::before {\n position: absolute;\n top: 0;\n left: 0;\n display: inline-block;\n width: 7px;\n height: 7px;\n border: 0 solid currentcolor;\n border-width: 1.5px 0 0 1.5px;\n content: '';\n}\n.ant-picker-super-prev-icon::after,\n.ant-picker-super-next-icon::after {\n position: absolute;\n top: 4px;\n left: 4px;\n display: inline-block;\n width: 7px;\n height: 7px;\n border: 0 solid currentcolor;\n border-width: 1.5px 0 0 1.5px;\n content: '';\n}\n.ant-picker-prev-icon,\n.ant-picker-super-prev-icon {\n transform: rotate(-45deg);\n}\n.ant-picker-next-icon,\n.ant-picker-super-next-icon {\n transform: rotate(135deg);\n}\n.ant-picker-content {\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n}\n.ant-picker-content th,\n.ant-picker-content td {\n position: relative;\n min-width: 24px;\n font-weight: 400;\n}\n.ant-picker-content th {\n height: 30px;\n color: rgba(0, 0, 0, 0.85);\n line-height: 30px;\n}\n.ant-picker-cell {\n padding: 3px 0;\n color: rgba(0, 0, 0, 0.25);\n cursor: pointer;\n}\n.ant-picker-cell-in-view {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-picker-cell::before {\n position: absolute;\n top: 50%;\n right: 0;\n left: 0;\n z-index: 1;\n height: 24px;\n transform: translateY(-50%);\n transition: all 0.3s;\n content: '';\n}\n.ant-picker-cell .ant-picker-cell-inner {\n position: relative;\n z-index: 2;\n display: inline-block;\n min-width: 24px;\n height: 24px;\n line-height: 24px;\n border-radius: 2px;\n transition: background 0.3s, border 0.3s;\n}\n.ant-picker-cell:hover:not(.ant-picker-cell-in-view) .ant-picker-cell-inner,\n.ant-picker-cell:hover:not(.ant-picker-cell-selected):not(.ant-picker-cell-range-start):not(.ant-picker-cell-range-end):not(.ant-picker-cell-range-hover-start):not(.ant-picker-cell-range-hover-end) .ant-picker-cell-inner {\n background: #f5f5f5;\n}\n.ant-picker-cell-in-view.ant-picker-cell-today .ant-picker-cell-inner::before {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n border: 1px solid #1890ff;\n border-radius: 2px;\n content: '';\n}\n.ant-picker-cell-in-view.ant-picker-cell-in-range {\n position: relative;\n}\n.ant-picker-cell-in-view.ant-picker-cell-in-range::before {\n background: #e6f7ff;\n}\n.ant-picker-cell-in-view.ant-picker-cell-selected .ant-picker-cell-inner,\n.ant-picker-cell-in-view.ant-picker-cell-range-start .ant-picker-cell-inner,\n.ant-picker-cell-in-view.ant-picker-cell-range-end .ant-picker-cell-inner {\n color: #fff;\n background: #1890ff;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-start:not(.ant-picker-cell-range-start-single)::before,\n.ant-picker-cell-in-view.ant-picker-cell-range-end:not(.ant-picker-cell-range-end-single)::before {\n background: #e6f7ff;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-start::before {\n left: 50%;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-end::before {\n right: 50%;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-start:not(.ant-picker-cell-in-range):not(.ant-picker-cell-range-start):not(.ant-picker-cell-range-end)::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-end:not(.ant-picker-cell-in-range):not(.ant-picker-cell-range-start):not(.ant-picker-cell-range-end)::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-start.ant-picker-cell-range-start-single::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-start.ant-picker-cell-range-start.ant-picker-cell-range-end.ant-picker-cell-range-end-near-hover::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-end.ant-picker-cell-range-start.ant-picker-cell-range-end.ant-picker-cell-range-start-near-hover::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-end.ant-picker-cell-range-end-single::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover:not(.ant-picker-cell-in-range)::after {\n position: absolute;\n top: 50%;\n z-index: 0;\n height: 24px;\n border-top: 1px dashed #7ec1ff;\n border-bottom: 1px dashed #7ec1ff;\n transform: translateY(-50%);\n transition: all 0.3s;\n content: '';\n}\n.ant-picker-cell-range-hover-start::after,\n.ant-picker-cell-range-hover-end::after,\n.ant-picker-cell-range-hover::after {\n right: 0;\n left: 2px;\n}\n.ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover::before,\n.ant-picker-cell-in-view.ant-picker-cell-range-start.ant-picker-cell-range-hover::before,\n.ant-picker-cell-in-view.ant-picker-cell-range-end.ant-picker-cell-range-hover::before,\n.ant-picker-cell-in-view.ant-picker-cell-range-start:not(.ant-picker-cell-range-start-single).ant-picker-cell-range-hover-start::before,\n.ant-picker-cell-in-view.ant-picker-cell-range-end:not(.ant-picker-cell-range-end-single).ant-picker-cell-range-hover-end::before,\n.ant-picker-panel > :not(.ant-picker-date-panel) .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-start::before,\n.ant-picker-panel > :not(.ant-picker-date-panel) .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-end::before {\n background: #cbe6ff;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-start:not(.ant-picker-cell-range-start-single):not(.ant-picker-cell-range-end) .ant-picker-cell-inner {\n border-radius: 2px 0 0 2px;\n}\n.ant-picker-cell-in-view.ant-picker-cell-range-end:not(.ant-picker-cell-range-end-single):not(.ant-picker-cell-range-start) .ant-picker-cell-inner {\n border-radius: 0 2px 2px 0;\n}\n.ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-start .ant-picker-cell-inner::after,\n.ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-end .ant-picker-cell-inner::after {\n position: absolute;\n top: 0;\n bottom: 0;\n z-index: -1;\n background: #cbe6ff;\n transition: all 0.3s;\n content: '';\n}\n.ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-start .ant-picker-cell-inner::after {\n right: -6px;\n left: 0;\n}\n.ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-end .ant-picker-cell-inner::after {\n right: 0;\n left: -6px;\n}\n.ant-picker-cell-range-hover.ant-picker-cell-range-start::after {\n right: 50%;\n}\n.ant-picker-cell-range-hover.ant-picker-cell-range-end::after {\n left: 50%;\n}\ntr > .ant-picker-cell-in-view.ant-picker-cell-range-hover:first-child::after,\ntr > .ant-picker-cell-in-view.ant-picker-cell-range-hover-end:first-child::after,\n.ant-picker-cell-in-view.ant-picker-cell-start.ant-picker-cell-range-hover-edge-start.ant-picker-cell-range-hover-edge-start-near-range::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-edge-start:not(.ant-picker-cell-range-hover-edge-start-near-range)::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-start::after {\n left: 6px;\n border-left: 1px dashed #7ec1ff;\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\ntr > .ant-picker-cell-in-view.ant-picker-cell-range-hover:last-child::after,\ntr > .ant-picker-cell-in-view.ant-picker-cell-range-hover-start:last-child::after,\n.ant-picker-cell-in-view.ant-picker-cell-end.ant-picker-cell-range-hover-edge-end.ant-picker-cell-range-hover-edge-end-near-range::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-edge-end:not(.ant-picker-cell-range-hover-edge-end-near-range)::after,\n.ant-picker-cell-in-view.ant-picker-cell-range-hover-end::after {\n right: 6px;\n border-right: 1px dashed #7ec1ff;\n border-top-right-radius: 2px;\n border-bottom-right-radius: 2px;\n}\n.ant-picker-cell-disabled {\n color: rgba(0, 0, 0, 0.25);\n pointer-events: none;\n}\n.ant-picker-cell-disabled .ant-picker-cell-inner {\n background: transparent;\n}\n.ant-picker-cell-disabled::before {\n background: rgba(0, 0, 0, 0.04);\n}\n.ant-picker-cell-disabled.ant-picker-cell-today .ant-picker-cell-inner::before {\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-picker-decade-panel .ant-picker-content,\n.ant-picker-year-panel .ant-picker-content,\n.ant-picker-quarter-panel .ant-picker-content,\n.ant-picker-month-panel .ant-picker-content {\n height: 264px;\n}\n.ant-picker-decade-panel .ant-picker-cell-inner,\n.ant-picker-year-panel .ant-picker-cell-inner,\n.ant-picker-quarter-panel .ant-picker-cell-inner,\n.ant-picker-month-panel .ant-picker-cell-inner {\n padding: 0 8px;\n}\n.ant-picker-quarter-panel .ant-picker-content {\n height: 56px;\n}\n.ant-picker-footer {\n width: -moz-min-content;\n width: min-content;\n min-width: 100%;\n line-height: 38px;\n text-align: center;\n border-bottom: 1px solid transparent;\n}\n.ant-picker-panel .ant-picker-footer {\n border-top: 1px solid #f0f0f0;\n}\n.ant-picker-footer-extra {\n padding: 0 12px;\n line-height: 38px;\n text-align: left;\n}\n.ant-picker-footer-extra:not(:last-child) {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-picker-now {\n text-align: left;\n}\n.ant-picker-today-btn {\n color: #1890ff;\n}\n.ant-picker-today-btn:hover {\n color: #40a9ff;\n}\n.ant-picker-today-btn:active {\n color: #096dd9;\n}\n.ant-picker-today-btn.ant-picker-today-btn-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-picker-decade-panel .ant-picker-cell-inner {\n padding: 0 4px;\n}\n.ant-picker-decade-panel .ant-picker-cell::before {\n display: none;\n}\n.ant-picker-year-panel .ant-picker-body,\n.ant-picker-quarter-panel .ant-picker-body,\n.ant-picker-month-panel .ant-picker-body {\n padding: 0 8px;\n}\n.ant-picker-year-panel .ant-picker-cell-inner,\n.ant-picker-quarter-panel .ant-picker-cell-inner,\n.ant-picker-month-panel .ant-picker-cell-inner {\n width: 60px;\n}\n.ant-picker-year-panel .ant-picker-cell-range-hover-start::after,\n.ant-picker-quarter-panel .ant-picker-cell-range-hover-start::after,\n.ant-picker-month-panel .ant-picker-cell-range-hover-start::after {\n left: 14px;\n border-left: 1px dashed #7ec1ff;\n border-radius: 2px 0 0 2px;\n}\n.ant-picker-panel-rtl .ant-picker-year-panel .ant-picker-cell-range-hover-start::after,\n.ant-picker-panel-rtl .ant-picker-quarter-panel .ant-picker-cell-range-hover-start::after,\n.ant-picker-panel-rtl .ant-picker-month-panel .ant-picker-cell-range-hover-start::after {\n right: 14px;\n border-right: 1px dashed #7ec1ff;\n border-radius: 0 2px 2px 0;\n}\n.ant-picker-year-panel .ant-picker-cell-range-hover-end::after,\n.ant-picker-quarter-panel .ant-picker-cell-range-hover-end::after,\n.ant-picker-month-panel .ant-picker-cell-range-hover-end::after {\n right: 14px;\n border-right: 1px dashed #7ec1ff;\n border-radius: 0 2px 2px 0;\n}\n.ant-picker-panel-rtl .ant-picker-year-panel .ant-picker-cell-range-hover-end::after,\n.ant-picker-panel-rtl .ant-picker-quarter-panel .ant-picker-cell-range-hover-end::after,\n.ant-picker-panel-rtl .ant-picker-month-panel .ant-picker-cell-range-hover-end::after {\n left: 14px;\n border-left: 1px dashed #7ec1ff;\n border-radius: 2px 0 0 2px;\n}\n.ant-picker-week-panel .ant-picker-body {\n padding: 8px 12px;\n}\n.ant-picker-week-panel .ant-picker-cell:hover .ant-picker-cell-inner,\n.ant-picker-week-panel .ant-picker-cell-selected .ant-picker-cell-inner,\n.ant-picker-week-panel .ant-picker-cell .ant-picker-cell-inner {\n background: transparent !important;\n}\n.ant-picker-week-panel-row td {\n transition: background 0.3s;\n}\n.ant-picker-week-panel-row:hover td {\n background: #f5f5f5;\n}\n.ant-picker-week-panel-row-selected td,\n.ant-picker-week-panel-row-selected:hover td {\n background: #1890ff;\n}\n.ant-picker-week-panel-row-selected td.ant-picker-cell-week,\n.ant-picker-week-panel-row-selected:hover td.ant-picker-cell-week {\n color: rgba(255, 255, 255, 0.5);\n}\n.ant-picker-week-panel-row-selected td.ant-picker-cell-today .ant-picker-cell-inner::before,\n.ant-picker-week-panel-row-selected:hover td.ant-picker-cell-today .ant-picker-cell-inner::before {\n border-color: #fff;\n}\n.ant-picker-week-panel-row-selected td .ant-picker-cell-inner,\n.ant-picker-week-panel-row-selected:hover td .ant-picker-cell-inner {\n color: #fff;\n}\n.ant-picker-date-panel .ant-picker-body {\n padding: 8px 12px;\n}\n.ant-picker-date-panel .ant-picker-content {\n width: 252px;\n}\n.ant-picker-date-panel .ant-picker-content th {\n width: 36px;\n}\n.ant-picker-datetime-panel {\n display: flex;\n}\n.ant-picker-datetime-panel .ant-picker-time-panel {\n border-left: 1px solid #f0f0f0;\n}\n.ant-picker-datetime-panel .ant-picker-date-panel,\n.ant-picker-datetime-panel .ant-picker-time-panel {\n transition: opacity 0.3s;\n}\n.ant-picker-datetime-panel-active .ant-picker-date-panel,\n.ant-picker-datetime-panel-active .ant-picker-time-panel {\n opacity: 0.3;\n}\n.ant-picker-datetime-panel-active .ant-picker-date-panel-active,\n.ant-picker-datetime-panel-active .ant-picker-time-panel-active {\n opacity: 1;\n}\n.ant-picker-time-panel {\n width: auto;\n min-width: auto;\n}\n.ant-picker-time-panel .ant-picker-content {\n display: flex;\n flex: auto;\n height: 224px;\n}\n.ant-picker-time-panel-column {\n flex: 1 0 auto;\n width: 56px;\n margin: 0;\n padding: 0;\n overflow-y: hidden;\n text-align: left;\n list-style: none;\n transition: background 0.3s;\n}\n.ant-picker-time-panel-column::after {\n display: block;\n height: 196px;\n content: '';\n}\n.ant-picker-datetime-panel .ant-picker-time-panel-column::after {\n height: 198px;\n}\n.ant-picker-time-panel-column:not(:first-child) {\n border-left: 1px solid #f0f0f0;\n}\n.ant-picker-time-panel-column-active {\n background: rgba(230, 247, 255, 0.2);\n}\n.ant-picker-time-panel-column:hover {\n overflow-y: auto;\n}\n.ant-picker-time-panel-column > li {\n margin: 0;\n padding: 0;\n}\n.ant-picker-time-panel-column > li.ant-picker-time-panel-cell .ant-picker-time-panel-cell-inner {\n display: block;\n width: 100%;\n height: 28px;\n margin: 0;\n padding: 0 0 0 14px;\n color: rgba(0, 0, 0, 0.85);\n line-height: 28px;\n border-radius: 0;\n cursor: pointer;\n transition: background 0.3s;\n}\n.ant-picker-time-panel-column > li.ant-picker-time-panel-cell .ant-picker-time-panel-cell-inner:hover {\n background: #f5f5f5;\n}\n.ant-picker-time-panel-column > li.ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner {\n background: #e6f7ff;\n}\n.ant-picker-time-panel-column > li.ant-picker-time-panel-cell-disabled .ant-picker-time-panel-cell-inner {\n color: rgba(0, 0, 0, 0.25);\n background: transparent;\n cursor: not-allowed;\n}\n/* stylelint-disable selector-type-no-unknown,selector-no-vendor-prefix */\n_:-ms-fullscreen .ant-picker-range-wrapper .ant-picker-month-panel .ant-picker-cell,\n:root .ant-picker-range-wrapper .ant-picker-month-panel .ant-picker-cell,\n_:-ms-fullscreen .ant-picker-range-wrapper .ant-picker-year-panel .ant-picker-cell,\n:root .ant-picker-range-wrapper .ant-picker-year-panel .ant-picker-cell {\n padding: 21px 0;\n}\n.ant-picker-rtl {\n direction: rtl;\n}\n.ant-picker-rtl .ant-picker-suffix {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-picker-rtl .ant-picker-clear {\n right: auto;\n left: 0;\n}\n.ant-picker-rtl .ant-picker-separator {\n transform: rotate(180deg);\n}\n.ant-picker-panel-rtl .ant-picker-header-view button:not(:first-child) {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-picker-rtl.ant-picker-range .ant-picker-clear {\n right: auto;\n left: 11px;\n}\n.ant-picker-rtl.ant-picker-range .ant-picker-active-bar {\n margin-right: 11px;\n margin-left: 0;\n}\n.ant-picker-rtl.ant-picker-range.ant-picker-small .ant-picker-active-bar {\n margin-right: 7px;\n}\n.ant-picker-dropdown-rtl .ant-picker-ranges {\n text-align: right;\n}\n.ant-picker-dropdown-rtl .ant-picker-ranges .ant-picker-ok {\n float: left;\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-picker-panel-rtl {\n direction: rtl;\n}\n.ant-picker-panel-rtl .ant-picker-prev-icon,\n.ant-picker-panel-rtl .ant-picker-super-prev-icon {\n transform: rotate(135deg);\n}\n.ant-picker-panel-rtl .ant-picker-next-icon,\n.ant-picker-panel-rtl .ant-picker-super-next-icon {\n transform: rotate(-45deg);\n}\n.ant-picker-cell .ant-picker-cell-inner {\n position: relative;\n z-index: 2;\n display: inline-block;\n min-width: 24px;\n height: 24px;\n line-height: 24px;\n border-radius: 2px;\n transition: background 0.3s, border 0.3s;\n}\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-start::before {\n right: 50%;\n left: 0;\n}\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-end::before {\n right: 0;\n left: 50%;\n}\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-start.ant-picker-cell-range-end::before {\n right: 50%;\n left: 50%;\n}\n.ant-picker-panel-rtl .ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-start .ant-picker-cell-inner::after {\n right: 0;\n left: -6px;\n}\n.ant-picker-panel-rtl .ant-picker-date-panel .ant-picker-cell-in-view.ant-picker-cell-in-range.ant-picker-cell-range-hover-end .ant-picker-cell-inner::after {\n right: -6px;\n left: 0;\n}\n.ant-picker-panel-rtl .ant-picker-cell-range-hover.ant-picker-cell-range-start::after {\n right: 0;\n left: 50%;\n}\n.ant-picker-panel-rtl .ant-picker-cell-range-hover.ant-picker-cell-range-end::after {\n right: 50%;\n left: 0;\n}\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-start:not(.ant-picker-cell-range-start-single):not(.ant-picker-cell-range-end) .ant-picker-cell-inner {\n border-radius: 0 2px 2px 0;\n}\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-end:not(.ant-picker-cell-range-end-single):not(.ant-picker-cell-range-start) .ant-picker-cell-inner {\n border-radius: 2px 0 0 2px;\n}\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-range-hover:not(.ant-picker-cell-selected):first-child::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-start.ant-picker-cell-range-hover-edge-start.ant-picker-cell-range-hover-edge-start-near-range::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-hover-edge-start:not(.ant-picker-cell-range-hover-edge-start-near-range)::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-hover-start::after {\n right: 6px;\n left: 0;\n border-right: 1px dashed #7ec1ff;\n border-left: none;\n border-radius: 0 2px 2px 0;\n}\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-range-hover:not(.ant-picker-cell-selected):last-child::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-end.ant-picker-cell-range-hover-edge-end.ant-picker-cell-range-hover-edge-end-near-range::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-hover-edge-end:not(.ant-picker-cell-range-hover-edge-end-near-range)::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-range-hover-end::after {\n right: 0;\n left: 6px;\n border-right: none;\n border-left: 1px dashed #7ec1ff;\n border-radius: 2px 0 0 2px;\n}\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-range-hover-start:last-child::after,\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-range-hover-end:first-child::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-start.ant-picker-cell-range-hover-edge-start:not(.ant-picker-cell-range-hover)::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-start.ant-picker-cell-range-hover-end.ant-picker-cell-range-hover-edge-start:not(.ant-picker-cell-range-hover)::after,\n.ant-picker-panel-rtl .ant-picker-cell-in-view.ant-picker-cell-end.ant-picker-cell-range-hover-start.ant-picker-cell-range-hover-edge-end:not(.ant-picker-cell-range-hover)::after,\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-start.ant-picker-cell-range-hover.ant-picker-cell-range-hover-edge-start:last-child::after,\n.ant-picker-panel-rtl tr > .ant-picker-cell-in-view.ant-picker-cell-end.ant-picker-cell-range-hover.ant-picker-cell-range-hover-edge-end:first-child::after {\n right: 6px;\n left: 6px;\n border-right: 1px dashed #7ec1ff;\n border-left: 1px dashed #7ec1ff;\n border-radius: 2px;\n}\n.ant-picker-dropdown-rtl .ant-picker-footer-extra {\n direction: rtl;\n text-align: right;\n}\n.ant-picker-panel-rtl .ant-picker-time-panel {\n direction: ltr;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-tag {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n height: auto;\n margin-right: 8px;\n padding: 0 7px;\n font-size: 12px;\n line-height: 20px;\n white-space: nowrap;\n background: #fafafa;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n opacity: 1;\n transition: all 0.3s;\n}\n.ant-tag,\n.ant-tag a,\n.ant-tag a:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-tag > a:first-child:last-child {\n display: inline-block;\n margin: 0 -8px;\n padding: 0 8px;\n}\n.ant-tag-close-icon {\n margin-left: 3px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 10px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-tag-close-icon:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-tag-has-color {\n border-color: transparent;\n}\n.ant-tag-has-color,\n.ant-tag-has-color a,\n.ant-tag-has-color a:hover,\n.ant-tag-has-color .anticon-close,\n.ant-tag-has-color .anticon-close:hover {\n color: #fff;\n}\n.ant-tag-checkable {\n background-color: transparent;\n border-color: transparent;\n cursor: pointer;\n}\n.ant-tag-checkable:not(.ant-tag-checkable-checked):hover {\n color: #1890ff;\n}\n.ant-tag-checkable:active,\n.ant-tag-checkable-checked {\n color: #fff;\n}\n.ant-tag-checkable-checked {\n background-color: #1890ff;\n}\n.ant-tag-checkable:active {\n background-color: #096dd9;\n}\n.ant-tag-hidden {\n display: none;\n}\n.ant-tag-pink {\n color: #c41d7f;\n background: #fff0f6;\n border-color: #ffadd2;\n}\n.ant-tag-pink-inverse {\n color: #fff;\n background: #eb2f96;\n border-color: #eb2f96;\n}\n.ant-tag-magenta {\n color: #c41d7f;\n background: #fff0f6;\n border-color: #ffadd2;\n}\n.ant-tag-magenta-inverse {\n color: #fff;\n background: #eb2f96;\n border-color: #eb2f96;\n}\n.ant-tag-red {\n color: #cf1322;\n background: #fff1f0;\n border-color: #ffa39e;\n}\n.ant-tag-red-inverse {\n color: #fff;\n background: #f5222d;\n border-color: #f5222d;\n}\n.ant-tag-volcano {\n color: #d4380d;\n background: #fff2e8;\n border-color: #ffbb96;\n}\n.ant-tag-volcano-inverse {\n color: #fff;\n background: #fa541c;\n border-color: #fa541c;\n}\n.ant-tag-orange {\n color: #d46b08;\n background: #fff7e6;\n border-color: #ffd591;\n}\n.ant-tag-orange-inverse {\n color: #fff;\n background: #fa8c16;\n border-color: #fa8c16;\n}\n.ant-tag-yellow {\n color: #d4b106;\n background: #feffe6;\n border-color: #fffb8f;\n}\n.ant-tag-yellow-inverse {\n color: #fff;\n background: #fadb14;\n border-color: #fadb14;\n}\n.ant-tag-gold {\n color: #d48806;\n background: #fffbe6;\n border-color: #ffe58f;\n}\n.ant-tag-gold-inverse {\n color: #fff;\n background: #faad14;\n border-color: #faad14;\n}\n.ant-tag-cyan {\n color: #08979c;\n background: #e6fffb;\n border-color: #87e8de;\n}\n.ant-tag-cyan-inverse {\n color: #fff;\n background: #13c2c2;\n border-color: #13c2c2;\n}\n.ant-tag-lime {\n color: #7cb305;\n background: #fcffe6;\n border-color: #eaff8f;\n}\n.ant-tag-lime-inverse {\n color: #fff;\n background: #a0d911;\n border-color: #a0d911;\n}\n.ant-tag-green {\n color: #389e0d;\n background: #f6ffed;\n border-color: #b7eb8f;\n}\n.ant-tag-green-inverse {\n color: #fff;\n background: #52c41a;\n border-color: #52c41a;\n}\n.ant-tag-blue {\n color: #096dd9;\n background: #e6f7ff;\n border-color: #91d5ff;\n}\n.ant-tag-blue-inverse {\n color: #fff;\n background: #1890ff;\n border-color: #1890ff;\n}\n.ant-tag-geekblue {\n color: #1d39c4;\n background: #f0f5ff;\n border-color: #adc6ff;\n}\n.ant-tag-geekblue-inverse {\n color: #fff;\n background: #2f54eb;\n border-color: #2f54eb;\n}\n.ant-tag-purple {\n color: #531dab;\n background: #f9f0ff;\n border-color: #d3adf7;\n}\n.ant-tag-purple-inverse {\n color: #fff;\n background: #722ed1;\n border-color: #722ed1;\n}\n.ant-tag-success {\n color: #52c41a;\n background: #f6ffed;\n border-color: #b7eb8f;\n}\n.ant-tag-processing {\n color: #1890ff;\n background: #e6f7ff;\n border-color: #91d5ff;\n}\n.ant-tag-error {\n color: #ff4d4f;\n background: #fff2f0;\n border-color: #ffccc7;\n}\n.ant-tag-warning {\n color: #faad14;\n background: #fffbe6;\n border-color: #ffe58f;\n}\n.ant-tag > .anticon + span,\n.ant-tag > span + .anticon {\n margin-left: 7px;\n}\n.ant-tag.ant-tag-rtl {\n margin-right: 0;\n margin-left: 8px;\n direction: rtl;\n text-align: right;\n}\n.ant-tag-rtl .ant-tag-close-icon {\n margin-right: 3px;\n margin-left: 0;\n}\n.ant-tag-rtl.ant-tag > .anticon + span,\n.ant-tag-rtl.ant-tag > span + .anticon {\n margin-right: 7px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-radio-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n font-size: 0;\n}\n.ant-radio-group .ant-badge-count {\n z-index: 1;\n}\n.ant-radio-group > .ant-badge:not(:first-child) > .ant-radio-button-wrapper {\n border-left: none;\n}\n.ant-radio-wrapper {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-flex;\n align-items: baseline;\n margin-right: 8px;\n cursor: pointer;\n}\n.ant-radio-wrapper-disabled {\n cursor: not-allowed;\n}\n.ant-radio-wrapper::after {\n display: inline-block;\n width: 0;\n overflow: hidden;\n content: '\\a0';\n}\n.ant-radio-wrapper.ant-radio-wrapper-in-form-item input[type='radio'] {\n width: 14px;\n height: 14px;\n}\n.ant-radio {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n top: 0.2em;\n display: inline-block;\n outline: none;\n cursor: pointer;\n}\n.ant-radio-wrapper:hover .ant-radio,\n.ant-radio:hover .ant-radio-inner,\n.ant-radio-input:focus + .ant-radio-inner {\n border-color: #1890ff;\n}\n.ant-radio-input:focus + .ant-radio-inner {\n box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.12);\n}\n.ant-radio-checked::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 50%;\n visibility: hidden;\n animation: antRadioEffect 0.36s ease-in-out;\n animation-fill-mode: both;\n content: '';\n}\n.ant-radio:hover::after,\n.ant-radio-wrapper:hover .ant-radio::after {\n visibility: visible;\n}\n.ant-radio-inner {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n width: 16px;\n height: 16px;\n background-color: #fff;\n border-color: #d9d9d9;\n border-style: solid;\n border-width: 1px;\n border-radius: 50%;\n transition: all 0.3s;\n}\n.ant-radio-inner::after {\n position: absolute;\n top: 50%;\n left: 50%;\n display: block;\n width: 16px;\n height: 16px;\n margin-top: -8px;\n margin-left: -8px;\n background-color: #1890ff;\n border-top: 0;\n border-left: 0;\n border-radius: 16px;\n transform: scale(0);\n opacity: 0;\n transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);\n content: ' ';\n}\n.ant-radio-input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n cursor: pointer;\n opacity: 0;\n}\n.ant-radio.ant-radio-disabled .ant-radio-inner {\n border-color: #d9d9d9;\n}\n.ant-radio-checked .ant-radio-inner {\n border-color: #1890ff;\n}\n.ant-radio-checked .ant-radio-inner::after {\n transform: scale(0.5);\n opacity: 1;\n transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-radio-disabled {\n cursor: not-allowed;\n}\n.ant-radio-disabled .ant-radio-inner {\n background-color: #f5f5f5;\n cursor: not-allowed;\n}\n.ant-radio-disabled .ant-radio-inner::after {\n background-color: rgba(0, 0, 0, 0.2);\n}\n.ant-radio-disabled .ant-radio-input {\n cursor: not-allowed;\n}\n.ant-radio-disabled + span {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\nspan.ant-radio + * {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-radio-button-wrapper {\n position: relative;\n display: inline-block;\n height: 32px;\n margin: 0;\n padding: 0 15px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 30px;\n background: #fff;\n border: 1px solid #d9d9d9;\n border-top-width: 1.02px;\n border-left-width: 0;\n cursor: pointer;\n transition: color 0.3s, background 0.3s, border-color 0.3s, box-shadow 0.3s;\n}\n.ant-radio-button-wrapper a {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-radio-button-wrapper > .ant-radio-button {\n position: absolute;\n top: 0;\n left: 0;\n z-index: -1;\n width: 100%;\n height: 100%;\n}\n.ant-radio-group-large .ant-radio-button-wrapper {\n height: 40px;\n font-size: 16px;\n line-height: 38px;\n}\n.ant-radio-group-small .ant-radio-button-wrapper {\n height: 24px;\n padding: 0 7px;\n line-height: 22px;\n}\n.ant-radio-button-wrapper:not(:first-child)::before {\n position: absolute;\n top: -1px;\n left: -1px;\n display: block;\n box-sizing: content-box;\n width: 1px;\n height: 100%;\n padding: 1px 0;\n background-color: #d9d9d9;\n transition: background-color 0.3s;\n content: '';\n}\n.ant-radio-button-wrapper:first-child {\n border-left: 1px solid #d9d9d9;\n border-radius: 2px 0 0 2px;\n}\n.ant-radio-button-wrapper:last-child {\n border-radius: 0 2px 2px 0;\n}\n.ant-radio-button-wrapper:first-child:last-child {\n border-radius: 2px;\n}\n.ant-radio-button-wrapper:hover {\n position: relative;\n color: #1890ff;\n}\n.ant-radio-button-wrapper:focus-within {\n box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.12);\n}\n.ant-radio-button-wrapper .ant-radio-inner,\n.ant-radio-button-wrapper input[type='checkbox'],\n.ant-radio-button-wrapper input[type='radio'] {\n width: 0;\n height: 0;\n opacity: 0;\n pointer-events: none;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {\n z-index: 1;\n color: #1890ff;\n background: #fff;\n border-color: #1890ff;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)::before {\n background-color: #1890ff;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):first-child {\n border-color: #1890ff;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {\n color: #40a9ff;\n border-color: #40a9ff;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover::before {\n background-color: #40a9ff;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):active {\n color: #096dd9;\n border-color: #096dd9;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):active::before {\n background-color: #096dd9;\n}\n.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):focus-within {\n box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.12);\n}\n.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {\n color: #fff;\n background: #1890ff;\n border-color: #1890ff;\n}\n.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {\n color: #fff;\n background: #40a9ff;\n border-color: #40a9ff;\n}\n.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):active {\n color: #fff;\n background: #096dd9;\n border-color: #096dd9;\n}\n.ant-radio-group-solid .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):focus-within {\n box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.12);\n}\n.ant-radio-button-wrapper-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-radio-button-wrapper-disabled:first-child,\n.ant-radio-button-wrapper-disabled:hover {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n}\n.ant-radio-button-wrapper-disabled:first-child {\n border-left-color: #d9d9d9;\n}\n.ant-radio-button-wrapper-disabled.ant-radio-button-wrapper-checked {\n color: rgba(0, 0, 0, 0.25);\n background-color: #e6e6e6;\n border-color: #d9d9d9;\n box-shadow: none;\n}\n@keyframes antRadioEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n.ant-radio-group.ant-radio-group-rtl {\n direction: rtl;\n}\n.ant-radio-wrapper.ant-radio-wrapper-rtl {\n margin-right: 0;\n margin-left: 8px;\n direction: rtl;\n}\n.ant-radio-button-wrapper.ant-radio-button-wrapper-rtl {\n border-right-width: 0;\n border-left-width: 1px;\n}\n.ant-radio-button-wrapper.ant-radio-button-wrapper-rtl.ant-radio-button-wrapper:not(:first-child)::before {\n right: -1px;\n left: 0;\n}\n.ant-radio-button-wrapper.ant-radio-button-wrapper-rtl.ant-radio-button-wrapper:first-child {\n border-right: 1px solid #d9d9d9;\n border-radius: 0 2px 2px 0;\n}\n.ant-radio-button-wrapper-checked:not([class*=' ant-radio-button-wrapper-disabled']).ant-radio-button-wrapper:first-child {\n border-right-color: #40a9ff;\n}\n.ant-radio-button-wrapper.ant-radio-button-wrapper-rtl.ant-radio-button-wrapper:last-child {\n border-radius: 2px 0 0 2px;\n}\n.ant-radio-button-wrapper.ant-radio-button-wrapper-rtl.ant-radio-button-wrapper-disabled:first-child {\n border-right-color: #d9d9d9;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-card {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n background: #fff;\n border-radius: 2px;\n}\n.ant-card-rtl {\n direction: rtl;\n}\n.ant-card-hoverable {\n cursor: pointer;\n transition: box-shadow 0.3s, border-color 0.3s;\n}\n.ant-card-hoverable:hover {\n border-color: transparent;\n box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);\n}\n.ant-card-bordered {\n border: 1px solid #f0f0f0;\n}\n.ant-card-head {\n min-height: 48px;\n margin-bottom: -1px;\n padding: 0 24px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n background: transparent;\n border-bottom: 1px solid #f0f0f0;\n border-radius: 2px 2px 0 0;\n}\n.ant-card-head::before {\n display: table;\n content: '';\n}\n.ant-card-head::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-card-head-wrapper {\n display: flex;\n align-items: center;\n}\n.ant-card-head-title {\n display: inline-block;\n flex: 1;\n padding: 16px 0;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-card-head-title > .ant-typography,\n.ant-card-head-title > .ant-typography-edit-content {\n left: 0;\n margin-top: 0;\n margin-bottom: 0;\n}\n.ant-card-head .ant-tabs-top {\n clear: both;\n margin-bottom: -17px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n}\n.ant-card-head .ant-tabs-top-bar {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-card-extra {\n margin-left: auto;\n padding: 16px 0;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n}\n.ant-card-rtl .ant-card-extra {\n margin-right: auto;\n margin-left: 0;\n}\n.ant-card-body {\n padding: 24px;\n}\n.ant-card-body::before {\n display: table;\n content: '';\n}\n.ant-card-body::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-card-contain-grid .ant-card-body {\n display: flex;\n flex-wrap: wrap;\n}\n.ant-card-contain-grid:not(.ant-card-loading) .ant-card-body {\n margin: -1px 0 0 -1px;\n padding: 0;\n}\n.ant-card-grid {\n width: 33.33%;\n padding: 24px;\n border: 0;\n border-radius: 0;\n box-shadow: 1px 0 0 0 #f0f0f0, 0 1px 0 0 #f0f0f0, 1px 1px 0 0 #f0f0f0, 1px 0 0 0 #f0f0f0 inset, 0 1px 0 0 #f0f0f0 inset;\n transition: all 0.3s;\n}\n.ant-card-grid-hoverable:hover {\n position: relative;\n z-index: 1;\n box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);\n}\n.ant-card-contain-tabs > .ant-card-head .ant-card-head-title {\n min-height: 32px;\n padding-bottom: 0;\n}\n.ant-card-contain-tabs > .ant-card-head .ant-card-extra {\n padding-bottom: 0;\n}\n.ant-card-bordered .ant-card-cover {\n margin-top: -1px;\n margin-right: -1px;\n margin-left: -1px;\n}\n.ant-card-cover > * {\n display: block;\n width: 100%;\n}\n.ant-card-cover img {\n border-radius: 2px 2px 0 0;\n}\n.ant-card-actions {\n display: flex;\n margin: 0;\n padding: 0;\n list-style: none;\n background: #fff;\n border-top: 1px solid #f0f0f0;\n}\n.ant-card-actions::before {\n display: table;\n content: '';\n}\n.ant-card-actions::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-card-actions > li {\n margin: 12px 0;\n color: rgba(0, 0, 0, 0.45);\n text-align: center;\n}\n.ant-card-actions > li > span {\n position: relative;\n display: block;\n min-width: 32px;\n font-size: 14px;\n line-height: 1.5715;\n cursor: pointer;\n}\n.ant-card-actions > li > span:hover {\n color: #1890ff;\n transition: color 0.3s;\n}\n.ant-card-actions > li > span a:not(.ant-btn),\n.ant-card-actions > li > span > .anticon {\n display: inline-block;\n width: 100%;\n color: rgba(0, 0, 0, 0.45);\n line-height: 22px;\n transition: color 0.3s;\n}\n.ant-card-actions > li > span a:not(.ant-btn):hover,\n.ant-card-actions > li > span > .anticon:hover {\n color: #1890ff;\n}\n.ant-card-actions > li > span > .anticon {\n font-size: 16px;\n line-height: 22px;\n}\n.ant-card-actions > li:not(:last-child) {\n border-right: 1px solid #f0f0f0;\n}\n.ant-card-rtl .ant-card-actions > li:not(:last-child) {\n border-right: none;\n border-left: 1px solid #f0f0f0;\n}\n.ant-card-type-inner .ant-card-head {\n padding: 0 24px;\n background: #fafafa;\n}\n.ant-card-type-inner .ant-card-head-title {\n padding: 12px 0;\n font-size: 14px;\n}\n.ant-card-type-inner .ant-card-body {\n padding: 16px 24px;\n}\n.ant-card-type-inner .ant-card-extra {\n padding: 13.5px 0;\n}\n.ant-card-meta {\n display: flex;\n margin: -4px 0;\n}\n.ant-card-meta::before {\n display: table;\n content: '';\n}\n.ant-card-meta::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-card-meta-avatar {\n padding-right: 16px;\n}\n.ant-card-rtl .ant-card-meta-avatar {\n padding-right: 0;\n padding-left: 16px;\n}\n.ant-card-meta-detail {\n flex: 1;\n overflow: hidden;\n}\n.ant-card-meta-detail > div:not(:last-child) {\n margin-bottom: 8px;\n}\n.ant-card-meta-title {\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-card-meta-description {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-card-loading {\n overflow: hidden;\n}\n.ant-card-loading .ant-card-body {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-card-small > .ant-card-head {\n min-height: 36px;\n padding: 0 12px;\n font-size: 14px;\n}\n.ant-card-small > .ant-card-head > .ant-card-head-wrapper > .ant-card-head-title {\n padding: 8px 0;\n}\n.ant-card-small > .ant-card-head > .ant-card-head-wrapper > .ant-card-extra {\n padding: 8px 0;\n font-size: 14px;\n}\n.ant-card-small > .ant-card-body {\n padding: 12px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-skeleton {\n display: table;\n width: 100%;\n}\n.ant-skeleton-header {\n display: table-cell;\n padding-right: 16px;\n vertical-align: top;\n}\n.ant-skeleton-header .ant-skeleton-avatar {\n display: inline-block;\n vertical-align: top;\n background: rgba(190, 190, 190, 0.2);\n width: 32px;\n height: 32px;\n line-height: 32px;\n}\n.ant-skeleton-header .ant-skeleton-avatar.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-header .ant-skeleton-avatar-lg {\n width: 40px;\n height: 40px;\n line-height: 40px;\n}\n.ant-skeleton-header .ant-skeleton-avatar-lg.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-header .ant-skeleton-avatar-sm {\n width: 24px;\n height: 24px;\n line-height: 24px;\n}\n.ant-skeleton-header .ant-skeleton-avatar-sm.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-content {\n display: table-cell;\n width: 100%;\n vertical-align: top;\n}\n.ant-skeleton-content .ant-skeleton-title {\n width: 100%;\n height: 16px;\n background: rgba(190, 190, 190, 0.2);\n border-radius: 2px;\n}\n.ant-skeleton-content .ant-skeleton-title + .ant-skeleton-paragraph {\n margin-top: 24px;\n}\n.ant-skeleton-content .ant-skeleton-paragraph {\n padding: 0;\n}\n.ant-skeleton-content .ant-skeleton-paragraph > li {\n width: 100%;\n height: 16px;\n list-style: none;\n background: rgba(190, 190, 190, 0.2);\n border-radius: 2px;\n}\n.ant-skeleton-content .ant-skeleton-paragraph > li:last-child:not(:first-child):not(:nth-child(2)) {\n width: 61%;\n}\n.ant-skeleton-content .ant-skeleton-paragraph > li + li {\n margin-top: 16px;\n}\n.ant-skeleton-with-avatar .ant-skeleton-content .ant-skeleton-title {\n margin-top: 12px;\n}\n.ant-skeleton-with-avatar .ant-skeleton-content .ant-skeleton-title + .ant-skeleton-paragraph {\n margin-top: 28px;\n}\n.ant-skeleton-round .ant-skeleton-content .ant-skeleton-title,\n.ant-skeleton-round .ant-skeleton-content .ant-skeleton-paragraph > li {\n border-radius: 100px;\n}\n.ant-skeleton-active .ant-skeleton-title,\n.ant-skeleton-active .ant-skeleton-paragraph > li,\n.ant-skeleton-active .ant-skeleton-avatar,\n.ant-skeleton-active .ant-skeleton-button,\n.ant-skeleton-active .ant-skeleton-input,\n.ant-skeleton-active .ant-skeleton-image {\n position: relative;\n /* stylelint-disable-next-line property-no-vendor-prefix,value-no-vendor-prefix */\n z-index: 0;\n overflow: hidden;\n background: transparent;\n}\n.ant-skeleton-active .ant-skeleton-title::after,\n.ant-skeleton-active .ant-skeleton-paragraph > li::after,\n.ant-skeleton-active .ant-skeleton-avatar::after,\n.ant-skeleton-active .ant-skeleton-button::after,\n.ant-skeleton-active .ant-skeleton-input::after,\n.ant-skeleton-active .ant-skeleton-image::after {\n position: absolute;\n top: 0;\n right: -150%;\n bottom: 0;\n left: -150%;\n background: linear-gradient(90deg, rgba(190, 190, 190, 0.2) 25%, rgba(129, 129, 129, 0.24) 37%, rgba(190, 190, 190, 0.2) 63%);\n animation: ant-skeleton-loading 1.4s ease infinite;\n content: '';\n}\n.ant-skeleton.ant-skeleton-block {\n width: 100%;\n}\n.ant-skeleton.ant-skeleton-block .ant-skeleton-button {\n width: 100%;\n}\n.ant-skeleton.ant-skeleton-block .ant-skeleton-input {\n width: 100%;\n}\n.ant-skeleton-element {\n display: inline-block;\n width: auto;\n}\n.ant-skeleton-element .ant-skeleton-button {\n display: inline-block;\n vertical-align: top;\n background: rgba(190, 190, 190, 0.2);\n border-radius: 2px;\n width: 64px;\n min-width: 64px;\n height: 32px;\n line-height: 32px;\n}\n.ant-skeleton-element .ant-skeleton-button.ant-skeleton-button-square {\n width: 32px;\n min-width: 32px;\n}\n.ant-skeleton-element .ant-skeleton-button.ant-skeleton-button-circle {\n width: 32px;\n min-width: 32px;\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-button.ant-skeleton-button-round {\n border-radius: 32px;\n}\n.ant-skeleton-element .ant-skeleton-button-lg {\n width: 80px;\n min-width: 80px;\n height: 40px;\n line-height: 40px;\n}\n.ant-skeleton-element .ant-skeleton-button-lg.ant-skeleton-button-square {\n width: 40px;\n min-width: 40px;\n}\n.ant-skeleton-element .ant-skeleton-button-lg.ant-skeleton-button-circle {\n width: 40px;\n min-width: 40px;\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-button-lg.ant-skeleton-button-round {\n border-radius: 40px;\n}\n.ant-skeleton-element .ant-skeleton-button-sm {\n width: 48px;\n min-width: 48px;\n height: 24px;\n line-height: 24px;\n}\n.ant-skeleton-element .ant-skeleton-button-sm.ant-skeleton-button-square {\n width: 24px;\n min-width: 24px;\n}\n.ant-skeleton-element .ant-skeleton-button-sm.ant-skeleton-button-circle {\n width: 24px;\n min-width: 24px;\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-button-sm.ant-skeleton-button-round {\n border-radius: 24px;\n}\n.ant-skeleton-element .ant-skeleton-avatar {\n display: inline-block;\n vertical-align: top;\n background: rgba(190, 190, 190, 0.2);\n width: 32px;\n height: 32px;\n line-height: 32px;\n}\n.ant-skeleton-element .ant-skeleton-avatar.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-avatar-lg {\n width: 40px;\n height: 40px;\n line-height: 40px;\n}\n.ant-skeleton-element .ant-skeleton-avatar-lg.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-avatar-sm {\n width: 24px;\n height: 24px;\n line-height: 24px;\n}\n.ant-skeleton-element .ant-skeleton-avatar-sm.ant-skeleton-avatar-circle {\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-input {\n display: inline-block;\n vertical-align: top;\n background: rgba(190, 190, 190, 0.2);\n width: 160px;\n min-width: 160px;\n height: 32px;\n line-height: 32px;\n}\n.ant-skeleton-element .ant-skeleton-input-lg {\n width: 200px;\n min-width: 200px;\n height: 40px;\n line-height: 40px;\n}\n.ant-skeleton-element .ant-skeleton-input-sm {\n width: 120px;\n min-width: 120px;\n height: 24px;\n line-height: 24px;\n}\n.ant-skeleton-element .ant-skeleton-image {\n display: flex;\n align-items: center;\n justify-content: center;\n vertical-align: top;\n background: rgba(190, 190, 190, 0.2);\n width: 96px;\n height: 96px;\n line-height: 96px;\n}\n.ant-skeleton-element .ant-skeleton-image.ant-skeleton-image-circle {\n border-radius: 50%;\n}\n.ant-skeleton-element .ant-skeleton-image-path {\n fill: #bfbfbf;\n}\n.ant-skeleton-element .ant-skeleton-image-svg {\n width: 48px;\n height: 48px;\n line-height: 48px;\n max-width: 192px;\n max-height: 192px;\n}\n.ant-skeleton-element .ant-skeleton-image-svg.ant-skeleton-image-circle {\n border-radius: 50%;\n}\n@keyframes ant-skeleton-loading {\n 0% {\n transform: translateX(-37.5%);\n }\n 100% {\n transform: translateX(37.5%);\n }\n}\n.ant-skeleton-rtl {\n direction: rtl;\n}\n.ant-skeleton-rtl .ant-skeleton-header {\n padding-right: 0;\n padding-left: 16px;\n}\n.ant-skeleton-rtl.ant-skeleton.ant-skeleton-active .ant-skeleton-content .ant-skeleton-title,\n.ant-skeleton-rtl.ant-skeleton.ant-skeleton-active .ant-skeleton-content .ant-skeleton-paragraph > li {\n animation-name: ant-skeleton-loading-rtl;\n}\n.ant-skeleton-rtl.ant-skeleton.ant-skeleton-active .ant-skeleton-avatar {\n animation-name: ant-skeleton-loading-rtl;\n}\n@keyframes ant-skeleton-loading-rtl {\n 0% {\n background-position: 0% 50%;\n }\n 100% {\n background-position: 100% 50%;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-tabs-small > .ant-tabs-nav .ant-tabs-tab {\n padding: 8px 0;\n font-size: 14px;\n}\n.ant-tabs-large > .ant-tabs-nav .ant-tabs-tab {\n padding: 16px 0;\n font-size: 16px;\n}\n.ant-tabs-card.ant-tabs-small > .ant-tabs-nav .ant-tabs-tab {\n padding: 6px 16px;\n}\n.ant-tabs-card.ant-tabs-large > .ant-tabs-nav .ant-tabs-tab {\n padding: 7px 16px 6px;\n}\n.ant-tabs-rtl {\n direction: rtl;\n}\n.ant-tabs-rtl .ant-tabs-nav .ant-tabs-tab {\n margin: 0 0 0 32px;\n}\n.ant-tabs-rtl .ant-tabs-nav .ant-tabs-tab:last-of-type {\n margin-left: 0;\n}\n.ant-tabs-rtl .ant-tabs-nav .ant-tabs-tab .anticon {\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-tabs-rtl .ant-tabs-nav .ant-tabs-tab .ant-tabs-tab-remove {\n margin-right: 8px;\n margin-left: -4px;\n}\n.ant-tabs-rtl .ant-tabs-nav .ant-tabs-tab .ant-tabs-tab-remove .anticon {\n margin: 0;\n}\n.ant-tabs-rtl.ant-tabs-left > .ant-tabs-nav {\n order: 1;\n}\n.ant-tabs-rtl.ant-tabs-left > .ant-tabs-content-holder {\n order: 0;\n}\n.ant-tabs-rtl.ant-tabs-right > .ant-tabs-nav {\n order: 0;\n}\n.ant-tabs-rtl.ant-tabs-right > .ant-tabs-content-holder {\n order: 1;\n}\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab {\n margin-right: 2px;\n margin-left: 0;\n}\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-add,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-add,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-add,\n.ant-tabs-rtl.ant-tabs-card.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-add {\n margin-right: 2px;\n margin-left: 0;\n}\n.ant-tabs-dropdown-rtl {\n direction: rtl;\n}\n.ant-tabs-dropdown-rtl .ant-tabs-dropdown-menu-item {\n text-align: right;\n}\n.ant-tabs-top,\n.ant-tabs-bottom {\n flex-direction: column;\n}\n.ant-tabs-top > .ant-tabs-nav,\n.ant-tabs-bottom > .ant-tabs-nav,\n.ant-tabs-top > div > .ant-tabs-nav,\n.ant-tabs-bottom > div > .ant-tabs-nav {\n margin: 0 0 16px 0;\n}\n.ant-tabs-top > .ant-tabs-nav::before,\n.ant-tabs-bottom > .ant-tabs-nav::before,\n.ant-tabs-top > div > .ant-tabs-nav::before,\n.ant-tabs-bottom > div > .ant-tabs-nav::before {\n position: absolute;\n right: 0;\n left: 0;\n border-bottom: 1px solid #f0f0f0;\n content: '';\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-ink-bar {\n height: 2px;\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-ink-bar-animated {\n transition: width 0.3s, left 0.3s, right 0.3s;\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap::after {\n top: 0;\n bottom: 0;\n width: 30px;\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap::before {\n left: 0;\n box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.08);\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap::after {\n right: 0;\n box-shadow: inset -10px 0 8px -8px rgba(0, 0, 0, 0.08);\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-left::before,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-left::before,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-left::before,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-left::before {\n opacity: 1;\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-right::after,\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-right::after,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-right::after,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-right::after {\n opacity: 1;\n}\n.ant-tabs-top > .ant-tabs-nav::before,\n.ant-tabs-top > div > .ant-tabs-nav::before {\n bottom: 0;\n}\n.ant-tabs-top > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-ink-bar {\n bottom: 0;\n}\n.ant-tabs-bottom > .ant-tabs-nav,\n.ant-tabs-bottom > div > .ant-tabs-nav {\n order: 1;\n margin-top: 16px;\n margin-bottom: 0;\n}\n.ant-tabs-bottom > .ant-tabs-nav::before,\n.ant-tabs-bottom > div > .ant-tabs-nav::before {\n top: 0;\n}\n.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-ink-bar {\n top: 0;\n}\n.ant-tabs-bottom > .ant-tabs-content-holder,\n.ant-tabs-bottom > div > .ant-tabs-content-holder {\n order: 0;\n}\n.ant-tabs-left > .ant-tabs-nav,\n.ant-tabs-right > .ant-tabs-nav,\n.ant-tabs-left > div > .ant-tabs-nav,\n.ant-tabs-right > div > .ant-tabs-nav {\n flex-direction: column;\n min-width: 50px;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-tab {\n padding: 8px 24px;\n text-align: center;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab {\n margin: 16px 0 0 0;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap {\n flex-direction: column;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap::after {\n right: 0;\n left: 0;\n height: 30px;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap::before {\n top: 0;\n box-shadow: inset 0 10px 8px -8px rgba(0, 0, 0, 0.08);\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap::after {\n bottom: 0;\n box-shadow: inset 0 -10px 8px -8px rgba(0, 0, 0, 0.08);\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-top::before,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-top::before,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-top::before,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-top::before {\n opacity: 1;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-bottom::after,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-bottom::after,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-bottom::after,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-wrap.ant-tabs-nav-wrap-ping-bottom::after {\n opacity: 1;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-ink-bar {\n width: 2px;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-ink-bar-animated,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-ink-bar-animated {\n transition: height 0.3s, top 0.3s;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-list,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-list,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-list,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-list,\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-nav-operations,\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-nav-operations,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-nav-operations,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-nav-operations {\n flex: 1 0 auto;\n flex-direction: column;\n}\n.ant-tabs-left > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-ink-bar {\n right: 0;\n}\n.ant-tabs-left > .ant-tabs-content-holder,\n.ant-tabs-left > div > .ant-tabs-content-holder {\n margin-left: -1px;\n border-left: 1px solid #f0f0f0;\n}\n.ant-tabs-left > .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane,\n.ant-tabs-left > div > .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane {\n padding-left: 24px;\n}\n.ant-tabs-right > .ant-tabs-nav,\n.ant-tabs-right > div > .ant-tabs-nav {\n order: 1;\n}\n.ant-tabs-right > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-ink-bar {\n left: 0;\n}\n.ant-tabs-right > .ant-tabs-content-holder,\n.ant-tabs-right > div > .ant-tabs-content-holder {\n order: 0;\n margin-right: -1px;\n border-right: 1px solid #f0f0f0;\n}\n.ant-tabs-right > .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane,\n.ant-tabs-right > div > .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane {\n padding-right: 24px;\n}\n.ant-tabs-dropdown {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: -9999px;\n left: -9999px;\n z-index: 1050;\n display: block;\n}\n.ant-tabs-dropdown-hidden {\n display: none;\n}\n.ant-tabs-dropdown-menu {\n max-height: 200px;\n margin: 0;\n padding: 4px 0;\n overflow-x: hidden;\n overflow-y: auto;\n text-align: left;\n list-style-type: none;\n background-color: #fff;\n background-clip: padding-box;\n border-radius: 2px;\n outline: none;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-tabs-dropdown-menu-item {\n display: flex;\n align-items: center;\n min-width: 120px;\n margin: 0;\n padding: 5px 12px;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n line-height: 22px;\n white-space: nowrap;\n text-overflow: ellipsis;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-tabs-dropdown-menu-item > span {\n flex: 1;\n white-space: nowrap;\n}\n.ant-tabs-dropdown-menu-item-remove {\n flex: none;\n margin-left: 12px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 12px;\n background: transparent;\n border: 0;\n cursor: pointer;\n}\n.ant-tabs-dropdown-menu-item-remove:hover {\n color: #40a9ff;\n}\n.ant-tabs-dropdown-menu-item:hover {\n background: #f5f5f5;\n}\n.ant-tabs-dropdown-menu-item-disabled,\n.ant-tabs-dropdown-menu-item-disabled:hover {\n color: rgba(0, 0, 0, 0.25);\n background: transparent;\n cursor: not-allowed;\n}\n.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-card > div > .ant-tabs-nav .ant-tabs-tab {\n margin: 0;\n padding: 8px 16px;\n background: #fafafa;\n border: 1px solid #f0f0f0;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab-active,\n.ant-tabs-card > div > .ant-tabs-nav .ant-tabs-tab-active {\n color: #1890ff;\n background: #fff;\n}\n.ant-tabs-card > .ant-tabs-nav .ant-tabs-ink-bar,\n.ant-tabs-card > div > .ant-tabs-nav .ant-tabs-ink-bar {\n visibility: hidden;\n}\n.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab {\n margin-left: 2px;\n}\n.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-tab {\n border-radius: 2px 2px 0 0;\n}\n.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab-active,\n.ant-tabs-card.ant-tabs-top > div > .ant-tabs-nav .ant-tabs-tab-active {\n border-bottom-color: #fff;\n}\n.ant-tabs-card.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-tab {\n border-radius: 0 0 2px 2px;\n}\n.ant-tabs-card.ant-tabs-bottom > .ant-tabs-nav .ant-tabs-tab-active,\n.ant-tabs-card.ant-tabs-bottom > div > .ant-tabs-nav .ant-tabs-tab-active {\n border-top-color: #fff;\n}\n.ant-tabs-card.ant-tabs-left > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-right > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-tab + .ant-tabs-tab {\n margin-top: 2px;\n}\n.ant-tabs-card.ant-tabs-left > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-tab {\n border-radius: 2px 0 0 2px;\n}\n.ant-tabs-card.ant-tabs-left > .ant-tabs-nav .ant-tabs-tab-active,\n.ant-tabs-card.ant-tabs-left > div > .ant-tabs-nav .ant-tabs-tab-active {\n border-right-color: #fff;\n}\n.ant-tabs-card.ant-tabs-right > .ant-tabs-nav .ant-tabs-tab,\n.ant-tabs-card.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-tab {\n border-radius: 0 2px 2px 0;\n}\n.ant-tabs-card.ant-tabs-right > .ant-tabs-nav .ant-tabs-tab-active,\n.ant-tabs-card.ant-tabs-right > div > .ant-tabs-nav .ant-tabs-tab-active {\n border-left-color: #fff;\n}\n.ant-tabs {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: flex;\n}\n.ant-tabs > .ant-tabs-nav,\n.ant-tabs > div > .ant-tabs-nav {\n position: relative;\n display: flex;\n flex: none;\n align-items: center;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-wrap,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-wrap {\n position: relative;\n display: inline-block;\n display: flex;\n flex: auto;\n align-self: stretch;\n overflow: hidden;\n white-space: nowrap;\n transform: translate(0);\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-wrap::before,\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-wrap::after,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-wrap::after {\n position: absolute;\n z-index: 1;\n opacity: 0;\n transition: opacity 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-list,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-list {\n position: relative;\n display: flex;\n transition: transform 0.3s;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-operations,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-operations {\n display: flex;\n align-self: stretch;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-operations-hidden,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-operations-hidden {\n position: absolute;\n visibility: hidden;\n pointer-events: none;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-more,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-more {\n position: relative;\n padding: 8px 16px;\n background: transparent;\n border: 0;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-more::after,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-more::after {\n position: absolute;\n right: 0;\n bottom: 0;\n left: 0;\n height: 5px;\n transform: translateY(100%);\n content: '';\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-add,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-add {\n min-width: 40px;\n margin-left: 2px;\n padding: 0 8px;\n background: #fafafa;\n border: 1px solid #f0f0f0;\n border-radius: 2px 2px 0 0;\n outline: none;\n cursor: pointer;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-add:hover,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-add:hover {\n color: #40a9ff;\n}\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-add:active,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-add:active,\n.ant-tabs > .ant-tabs-nav .ant-tabs-nav-add:focus,\n.ant-tabs > div > .ant-tabs-nav .ant-tabs-nav-add:focus {\n color: #096dd9;\n}\n.ant-tabs-extra-content {\n flex: none;\n}\n.ant-tabs-centered > .ant-tabs-nav .ant-tabs-nav-wrap:not([class*='ant-tabs-nav-wrap-ping']),\n.ant-tabs-centered > div > .ant-tabs-nav .ant-tabs-nav-wrap:not([class*='ant-tabs-nav-wrap-ping']) {\n justify-content: center;\n}\n.ant-tabs-ink-bar {\n position: absolute;\n background: #1890ff;\n pointer-events: none;\n}\n.ant-tabs-tab {\n position: relative;\n display: inline-flex;\n align-items: center;\n padding: 12px 0;\n font-size: 14px;\n background: transparent;\n border: 0;\n outline: none;\n cursor: pointer;\n}\n.ant-tabs-tab-btn:focus,\n.ant-tabs-tab-remove:focus,\n.ant-tabs-tab-btn:active,\n.ant-tabs-tab-remove:active {\n color: #096dd9;\n}\n.ant-tabs-tab-btn {\n outline: none;\n transition: all 0.3s;\n}\n.ant-tabs-tab-remove {\n flex: none;\n margin-right: -4px;\n margin-left: 8px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 12px;\n background: transparent;\n border: none;\n outline: none;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-tabs-tab-remove:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-tabs-tab:hover {\n color: #40a9ff;\n}\n.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {\n color: #1890ff;\n text-shadow: 0 0 0.25px currentcolor;\n}\n.ant-tabs-tab.ant-tabs-tab-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-tabs-tab.ant-tabs-tab-disabled .ant-tabs-tab-btn:focus,\n.ant-tabs-tab.ant-tabs-tab-disabled .ant-tabs-tab-remove:focus,\n.ant-tabs-tab.ant-tabs-tab-disabled .ant-tabs-tab-btn:active,\n.ant-tabs-tab.ant-tabs-tab-disabled .ant-tabs-tab-remove:active {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-tabs-tab .ant-tabs-tab-remove .anticon {\n margin: 0;\n}\n.ant-tabs-tab .anticon {\n margin-right: 12px;\n}\n.ant-tabs-tab + .ant-tabs-tab {\n margin: 0 0 0 32px;\n}\n.ant-tabs-content {\n position: relative;\n width: 100%;\n}\n.ant-tabs-content-holder {\n flex: auto;\n min-width: 0;\n min-height: 0;\n}\n.ant-tabs-tabpane {\n outline: none;\n}\n.ant-tabs-tabpane-hidden {\n display: none;\n}\n.ant-tabs-switch-appear,\n.ant-tabs-switch-enter {\n transition: none;\n}\n.ant-tabs-switch-appear-start,\n.ant-tabs-switch-enter-start {\n opacity: 0;\n}\n.ant-tabs-switch-appear-active,\n.ant-tabs-switch-enter-active {\n opacity: 1;\n transition: opacity 0.3s;\n}\n.ant-tabs-switch-leave {\n position: absolute;\n transition: none;\n inset: 0;\n}\n.ant-tabs-switch-leave-start {\n opacity: 1;\n}\n.ant-tabs-switch-leave-active {\n opacity: 0;\n transition: opacity 0.3s;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-carousel {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n}\n.ant-carousel .slick-slider {\n position: relative;\n display: block;\n box-sizing: border-box;\n touch-action: pan-y;\n -webkit-touch-callout: none;\n -webkit-tap-highlight-color: transparent;\n}\n.ant-carousel .slick-list {\n position: relative;\n display: block;\n margin: 0;\n padding: 0;\n overflow: hidden;\n}\n.ant-carousel .slick-list:focus {\n outline: none;\n}\n.ant-carousel .slick-list.dragging {\n cursor: pointer;\n}\n.ant-carousel .slick-list .slick-slide {\n pointer-events: none;\n}\n.ant-carousel .slick-list .slick-slide input.ant-radio-input,\n.ant-carousel .slick-list .slick-slide input.ant-checkbox-input {\n visibility: hidden;\n}\n.ant-carousel .slick-list .slick-slide.slick-active {\n pointer-events: auto;\n}\n.ant-carousel .slick-list .slick-slide.slick-active input.ant-radio-input,\n.ant-carousel .slick-list .slick-slide.slick-active input.ant-checkbox-input {\n visibility: visible;\n}\n.ant-carousel .slick-list .slick-slide > div > div {\n vertical-align: bottom;\n}\n.ant-carousel .slick-slider .slick-track,\n.ant-carousel .slick-slider .slick-list {\n transform: translate3d(0, 0, 0);\n touch-action: pan-y;\n}\n.ant-carousel .slick-track {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n}\n.ant-carousel .slick-track::before,\n.ant-carousel .slick-track::after {\n display: table;\n content: '';\n}\n.ant-carousel .slick-track::after {\n clear: both;\n}\n.slick-loading .ant-carousel .slick-track {\n visibility: hidden;\n}\n.ant-carousel .slick-slide {\n display: none;\n float: left;\n height: 100%;\n min-height: 1px;\n}\n.ant-carousel .slick-slide img {\n display: block;\n}\n.ant-carousel .slick-slide.slick-loading img {\n display: none;\n}\n.ant-carousel .slick-slide.dragging img {\n pointer-events: none;\n}\n.ant-carousel .slick-initialized .slick-slide {\n display: block;\n}\n.ant-carousel .slick-loading .slick-slide {\n visibility: hidden;\n}\n.ant-carousel .slick-vertical .slick-slide {\n display: block;\n height: auto;\n}\n.ant-carousel .slick-arrow.slick-hidden {\n display: none;\n}\n.ant-carousel .slick-prev,\n.ant-carousel .slick-next {\n position: absolute;\n top: 50%;\n display: block;\n width: 20px;\n height: 20px;\n margin-top: -10px;\n padding: 0;\n color: transparent;\n font-size: 0;\n line-height: 0;\n background: transparent;\n border: 0;\n outline: none;\n cursor: pointer;\n}\n.ant-carousel .slick-prev:hover,\n.ant-carousel .slick-next:hover,\n.ant-carousel .slick-prev:focus,\n.ant-carousel .slick-next:focus {\n color: transparent;\n background: transparent;\n outline: none;\n}\n.ant-carousel .slick-prev:hover::before,\n.ant-carousel .slick-next:hover::before,\n.ant-carousel .slick-prev:focus::before,\n.ant-carousel .slick-next:focus::before {\n opacity: 1;\n}\n.ant-carousel .slick-prev.slick-disabled::before,\n.ant-carousel .slick-next.slick-disabled::before {\n opacity: 0.25;\n}\n.ant-carousel .slick-prev {\n left: -25px;\n}\n.ant-carousel .slick-prev::before {\n content: '←';\n}\n.ant-carousel .slick-next {\n right: -25px;\n}\n.ant-carousel .slick-next::before {\n content: '→';\n}\n.ant-carousel .slick-dots {\n position: absolute;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 15;\n display: flex !important;\n justify-content: center;\n margin-right: 15%;\n margin-bottom: 0;\n margin-left: 15%;\n padding-left: 0;\n list-style: none;\n}\n.ant-carousel .slick-dots-bottom {\n bottom: 12px;\n}\n.ant-carousel .slick-dots-top {\n top: 12px;\n bottom: auto;\n}\n.ant-carousel .slick-dots li {\n position: relative;\n display: inline-block;\n flex: 0 1 auto;\n box-sizing: content-box;\n width: 16px;\n height: 3px;\n margin: 0 4px;\n padding: 0;\n text-align: center;\n text-indent: -999px;\n vertical-align: top;\n transition: all 0.5s;\n}\n.ant-carousel .slick-dots li button {\n position: relative;\n display: block;\n width: 100%;\n height: 3px;\n padding: 0;\n color: transparent;\n font-size: 0;\n background: #fff;\n border: 0;\n border-radius: 1px;\n outline: none;\n cursor: pointer;\n opacity: 0.3;\n transition: all 0.5s;\n}\n.ant-carousel .slick-dots li button:hover,\n.ant-carousel .slick-dots li button:focus {\n opacity: 0.75;\n}\n.ant-carousel .slick-dots li button::after {\n position: absolute;\n top: -4px;\n right: -4px;\n bottom: -4px;\n left: -4px;\n content: '';\n}\n.ant-carousel .slick-dots li.slick-active {\n width: 24px;\n}\n.ant-carousel .slick-dots li.slick-active button {\n background: #fff;\n opacity: 1;\n}\n.ant-carousel .slick-dots li.slick-active:hover,\n.ant-carousel .slick-dots li.slick-active:focus {\n opacity: 1;\n}\n.ant-carousel-vertical .slick-dots {\n top: 50%;\n bottom: auto;\n flex-direction: column;\n width: 3px;\n height: auto;\n margin: 0;\n transform: translateY(-50%);\n}\n.ant-carousel-vertical .slick-dots-left {\n right: auto;\n left: 12px;\n}\n.ant-carousel-vertical .slick-dots-right {\n right: 12px;\n left: auto;\n}\n.ant-carousel-vertical .slick-dots li {\n width: 3px;\n height: 16px;\n margin: 4px 0;\n vertical-align: baseline;\n}\n.ant-carousel-vertical .slick-dots li button {\n width: 3px;\n height: 16px;\n}\n.ant-carousel-vertical .slick-dots li.slick-active {\n width: 3px;\n height: 24px;\n}\n.ant-carousel-vertical .slick-dots li.slick-active button {\n width: 3px;\n height: 24px;\n}\n.ant-carousel-rtl {\n direction: rtl;\n}\n.ant-carousel-rtl .ant-carousel .slick-track {\n right: 0;\n left: auto;\n}\n.ant-carousel-rtl .ant-carousel .slick-prev {\n right: -25px;\n left: auto;\n}\n.ant-carousel-rtl .ant-carousel .slick-prev::before {\n content: '→';\n}\n.ant-carousel-rtl .ant-carousel .slick-next {\n right: auto;\n left: -25px;\n}\n.ant-carousel-rtl .ant-carousel .slick-next::before {\n content: '←';\n}\n.ant-carousel-rtl.ant-carousel .slick-dots {\n flex-direction: row-reverse;\n}\n.ant-carousel-rtl.ant-carousel-vertical .slick-dots {\n flex-direction: column;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n@keyframes antCheckboxEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n.ant-cascader-checkbox {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n top: 0.2em;\n line-height: 1;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n}\n.ant-cascader-checkbox-wrapper:hover .ant-cascader-checkbox-inner,\n.ant-cascader-checkbox:hover .ant-cascader-checkbox-inner,\n.ant-cascader-checkbox-input:focus + .ant-cascader-checkbox-inner {\n border-color: #1890ff;\n}\n.ant-cascader-checkbox-checked::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 2px;\n visibility: hidden;\n animation: antCheckboxEffect 0.36s ease-in-out;\n animation-fill-mode: backwards;\n content: '';\n}\n.ant-cascader-checkbox:hover::after,\n.ant-cascader-checkbox-wrapper:hover .ant-cascader-checkbox::after {\n visibility: visible;\n}\n.ant-cascader-checkbox-inner {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n width: 16px;\n height: 16px;\n direction: ltr;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n border-collapse: separate;\n transition: all 0.3s;\n}\n.ant-cascader-checkbox-inner::after {\n position: absolute;\n top: 50%;\n left: 21.5%;\n display: table;\n width: 5.71428571px;\n height: 9.14285714px;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(0) translate(-50%, -50%);\n opacity: 0;\n transition: all 0.1s cubic-bezier(0.71, -0.46, 0.88, 0.6), opacity 0.1s;\n content: ' ';\n}\n.ant-cascader-checkbox-input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n width: 100%;\n height: 100%;\n cursor: pointer;\n opacity: 0;\n}\n.ant-cascader-checkbox-checked .ant-cascader-checkbox-inner::after {\n position: absolute;\n display: table;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(1) translate(-50%, -50%);\n opacity: 1;\n transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;\n content: ' ';\n}\n.ant-cascader-checkbox-checked .ant-cascader-checkbox-inner {\n background-color: #1890ff;\n border-color: #1890ff;\n}\n.ant-cascader-checkbox-disabled {\n cursor: not-allowed;\n}\n.ant-cascader-checkbox-disabled.ant-cascader-checkbox-checked .ant-cascader-checkbox-inner::after {\n border-color: rgba(0, 0, 0, 0.25);\n animation-name: none;\n}\n.ant-cascader-checkbox-disabled .ant-cascader-checkbox-input {\n cursor: not-allowed;\n pointer-events: none;\n}\n.ant-cascader-checkbox-disabled .ant-cascader-checkbox-inner {\n background-color: #f5f5f5;\n border-color: #d9d9d9 !important;\n}\n.ant-cascader-checkbox-disabled .ant-cascader-checkbox-inner::after {\n border-color: #f5f5f5;\n border-collapse: separate;\n animation-name: none;\n}\n.ant-cascader-checkbox-disabled + span {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-cascader-checkbox-disabled:hover::after,\n.ant-cascader-checkbox-wrapper:hover .ant-cascader-checkbox-disabled::after {\n visibility: hidden;\n}\n.ant-cascader-checkbox-wrapper {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-flex;\n align-items: baseline;\n line-height: unset;\n cursor: pointer;\n}\n.ant-cascader-checkbox-wrapper::after {\n display: inline-block;\n width: 0;\n overflow: hidden;\n content: '\\a0';\n}\n.ant-cascader-checkbox-wrapper.ant-cascader-checkbox-wrapper-disabled {\n cursor: not-allowed;\n}\n.ant-cascader-checkbox-wrapper + .ant-cascader-checkbox-wrapper {\n margin-left: 8px;\n}\n.ant-cascader-checkbox-wrapper.ant-cascader-checkbox-wrapper-in-form-item input[type='checkbox'] {\n width: 14px;\n height: 14px;\n}\n.ant-cascader-checkbox + span {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-cascader-checkbox-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n}\n.ant-cascader-checkbox-group-item {\n margin-right: 8px;\n}\n.ant-cascader-checkbox-group-item:last-child {\n margin-right: 0;\n}\n.ant-cascader-checkbox-group-item + .ant-cascader-checkbox-group-item {\n margin-left: 0;\n}\n.ant-cascader-checkbox-indeterminate .ant-cascader-checkbox-inner {\n background-color: #fff;\n border-color: #d9d9d9;\n}\n.ant-cascader-checkbox-indeterminate .ant-cascader-checkbox-inner::after {\n top: 50%;\n left: 50%;\n width: 8px;\n height: 8px;\n background-color: #1890ff;\n border: 0;\n transform: translate(-50%, -50%) scale(1);\n opacity: 1;\n content: ' ';\n}\n.ant-cascader-checkbox-indeterminate.ant-cascader-checkbox-disabled .ant-cascader-checkbox-inner::after {\n background-color: rgba(0, 0, 0, 0.25);\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-cascader {\n width: 184px;\n}\n.ant-cascader-checkbox {\n top: 0;\n margin-right: 8px;\n}\n.ant-cascader-menus {\n display: flex;\n flex-wrap: nowrap;\n align-items: flex-start;\n}\n.ant-cascader-menus.ant-cascader-menu-empty .ant-cascader-menu {\n width: 100%;\n height: auto;\n}\n.ant-cascader-menu {\n flex-grow: 1;\n min-width: 111px;\n height: 180px;\n margin: 0;\n margin: -4px 0;\n padding: 4px 0;\n overflow: auto;\n vertical-align: top;\n list-style: none;\n border-right: 1px solid #f0f0f0;\n -ms-overflow-style: -ms-autohiding-scrollbar;\n}\n.ant-cascader-menu-item {\n display: flex;\n flex-wrap: nowrap;\n align-items: center;\n padding: 5px 12px;\n overflow: hidden;\n line-height: 22px;\n white-space: nowrap;\n text-overflow: ellipsis;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-cascader-menu-item:hover {\n background: #f5f5f5;\n}\n.ant-cascader-menu-item-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-cascader-menu-item-disabled:hover {\n background: transparent;\n}\n.ant-cascader-menu-empty .ant-cascader-menu-item {\n color: rgba(0, 0, 0, 0.25);\n cursor: default;\n pointer-events: none;\n}\n.ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled),\n.ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled):hover {\n font-weight: 600;\n background-color: #e6f7ff;\n}\n.ant-cascader-menu-item-content {\n flex: auto;\n}\n.ant-cascader-menu-item-expand .ant-cascader-menu-item-expand-icon,\n.ant-cascader-menu-item-loading-icon {\n margin-left: 4px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 10px;\n}\n.ant-cascader-menu-item-disabled.ant-cascader-menu-item-expand .ant-cascader-menu-item-expand-icon,\n.ant-cascader-menu-item-disabled.ant-cascader-menu-item-loading-icon {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-cascader-menu-item-keyword {\n color: #ff4d4f;\n}\n.ant-cascader-compact-item:not(.ant-cascader-compact-last-item):not(.ant-cascader-compact-item-rtl) {\n margin-right: -1px;\n}\n.ant-cascader-compact-item:not(.ant-cascader-compact-last-item).ant-cascader-compact-item-rtl {\n margin-left: -1px;\n}\n.ant-cascader-compact-item:hover,\n.ant-cascader-compact-item:focus,\n.ant-cascader-compact-item:active {\n z-index: 2;\n}\n.ant-cascader-compact-item[disabled] {\n z-index: 0;\n}\n.ant-cascader-compact-item:not(.ant-cascader-compact-first-item):not(.ant-cascader-compact-last-item).ant-cascader {\n border-radius: 0;\n}\n.ant-cascader-compact-item.ant-cascader.ant-cascader-compact-first-item:not(.ant-cascader-compact-last-item):not(.ant-cascader-compact-item-rtl) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-cascader-compact-item.ant-cascader.ant-cascader-compact-last-item:not(.ant-cascader-compact-first-item):not(.ant-cascader-compact-item-rtl) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-cascader-compact-item.ant-cascader.ant-cascader-compact-item-rtl.ant-cascader-compact-first-item:not(.ant-cascader-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-cascader-compact-item.ant-cascader.ant-cascader-compact-item-rtl.ant-cascader-compact-last-item:not(.ant-cascader-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-cascader-rtl .ant-cascader-menu-item-expand-icon,\n.ant-cascader-rtl .ant-cascader-menu-item-loading-icon {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-cascader-rtl .ant-cascader-checkbox {\n top: 0;\n margin-right: 0;\n margin-left: 8px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n@keyframes antCheckboxEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n.ant-checkbox {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n top: 0.2em;\n line-height: 1;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n}\n.ant-checkbox-wrapper:hover .ant-checkbox-inner,\n.ant-checkbox:hover .ant-checkbox-inner,\n.ant-checkbox-input:focus + .ant-checkbox-inner {\n border-color: #1890ff;\n}\n.ant-checkbox-checked::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 2px;\n visibility: hidden;\n animation: antCheckboxEffect 0.36s ease-in-out;\n animation-fill-mode: backwards;\n content: '';\n}\n.ant-checkbox:hover::after,\n.ant-checkbox-wrapper:hover .ant-checkbox::after {\n visibility: visible;\n}\n.ant-checkbox-inner {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n width: 16px;\n height: 16px;\n direction: ltr;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n border-collapse: separate;\n transition: all 0.3s;\n}\n.ant-checkbox-inner::after {\n position: absolute;\n top: 50%;\n left: 21.5%;\n display: table;\n width: 5.71428571px;\n height: 9.14285714px;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(0) translate(-50%, -50%);\n opacity: 0;\n transition: all 0.1s cubic-bezier(0.71, -0.46, 0.88, 0.6), opacity 0.1s;\n content: ' ';\n}\n.ant-checkbox-input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n width: 100%;\n height: 100%;\n cursor: pointer;\n opacity: 0;\n}\n.ant-checkbox-checked .ant-checkbox-inner::after {\n position: absolute;\n display: table;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(1) translate(-50%, -50%);\n opacity: 1;\n transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;\n content: ' ';\n}\n.ant-checkbox-checked .ant-checkbox-inner {\n background-color: #1890ff;\n border-color: #1890ff;\n}\n.ant-checkbox-disabled {\n cursor: not-allowed;\n}\n.ant-checkbox-disabled.ant-checkbox-checked .ant-checkbox-inner::after {\n border-color: rgba(0, 0, 0, 0.25);\n animation-name: none;\n}\n.ant-checkbox-disabled .ant-checkbox-input {\n cursor: not-allowed;\n pointer-events: none;\n}\n.ant-checkbox-disabled .ant-checkbox-inner {\n background-color: #f5f5f5;\n border-color: #d9d9d9 !important;\n}\n.ant-checkbox-disabled .ant-checkbox-inner::after {\n border-color: #f5f5f5;\n border-collapse: separate;\n animation-name: none;\n}\n.ant-checkbox-disabled + span {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-checkbox-disabled:hover::after,\n.ant-checkbox-wrapper:hover .ant-checkbox-disabled::after {\n visibility: hidden;\n}\n.ant-checkbox-wrapper {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-flex;\n align-items: baseline;\n line-height: unset;\n cursor: pointer;\n}\n.ant-checkbox-wrapper::after {\n display: inline-block;\n width: 0;\n overflow: hidden;\n content: '\\a0';\n}\n.ant-checkbox-wrapper.ant-checkbox-wrapper-disabled {\n cursor: not-allowed;\n}\n.ant-checkbox-wrapper + .ant-checkbox-wrapper {\n margin-left: 8px;\n}\n.ant-checkbox-wrapper.ant-checkbox-wrapper-in-form-item input[type='checkbox'] {\n width: 14px;\n height: 14px;\n}\n.ant-checkbox + span {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-checkbox-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n}\n.ant-checkbox-group-item {\n margin-right: 8px;\n}\n.ant-checkbox-group-item:last-child {\n margin-right: 0;\n}\n.ant-checkbox-group-item + .ant-checkbox-group-item {\n margin-left: 0;\n}\n.ant-checkbox-indeterminate .ant-checkbox-inner {\n background-color: #fff;\n border-color: #d9d9d9;\n}\n.ant-checkbox-indeterminate .ant-checkbox-inner::after {\n top: 50%;\n left: 50%;\n width: 8px;\n height: 8px;\n background-color: #1890ff;\n border: 0;\n transform: translate(-50%, -50%) scale(1);\n opacity: 1;\n content: ' ';\n}\n.ant-checkbox-indeterminate.ant-checkbox-disabled .ant-checkbox-inner::after {\n background-color: rgba(0, 0, 0, 0.25);\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-checkbox-rtl {\n direction: rtl;\n}\n.ant-checkbox-group-rtl .ant-checkbox-group-item {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-checkbox-group-rtl .ant-checkbox-group-item:last-child {\n margin-left: 0 !important;\n}\n.ant-checkbox-group-rtl .ant-checkbox-group-item + .ant-checkbox-group-item {\n margin-left: 8px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-row {\n display: flex;\n flex-flow: row wrap;\n min-width: 0;\n}\n.ant-row::before,\n.ant-row::after {\n display: flex;\n}\n.ant-row-no-wrap {\n flex-wrap: nowrap;\n}\n.ant-row-start {\n justify-content: flex-start;\n}\n.ant-row-center {\n justify-content: center;\n}\n.ant-row-end {\n justify-content: flex-end;\n}\n.ant-row-space-between {\n justify-content: space-between;\n}\n.ant-row-space-around {\n justify-content: space-around;\n}\n.ant-row-space-evenly {\n justify-content: space-evenly;\n}\n.ant-row-top {\n align-items: flex-start;\n}\n.ant-row-middle {\n align-items: center;\n}\n.ant-row-bottom {\n align-items: flex-end;\n}\n.ant-col {\n position: relative;\n max-width: 100%;\n min-height: 1px;\n}\n.ant-col-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n}\n.ant-col-push-24 {\n left: 100%;\n}\n.ant-col-pull-24 {\n right: 100%;\n}\n.ant-col-offset-24 {\n margin-left: 100%;\n}\n.ant-col-order-24 {\n order: 24;\n}\n.ant-col-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n}\n.ant-col-push-23 {\n left: 95.83333333%;\n}\n.ant-col-pull-23 {\n right: 95.83333333%;\n}\n.ant-col-offset-23 {\n margin-left: 95.83333333%;\n}\n.ant-col-order-23 {\n order: 23;\n}\n.ant-col-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n}\n.ant-col-push-22 {\n left: 91.66666667%;\n}\n.ant-col-pull-22 {\n right: 91.66666667%;\n}\n.ant-col-offset-22 {\n margin-left: 91.66666667%;\n}\n.ant-col-order-22 {\n order: 22;\n}\n.ant-col-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n}\n.ant-col-push-21 {\n left: 87.5%;\n}\n.ant-col-pull-21 {\n right: 87.5%;\n}\n.ant-col-offset-21 {\n margin-left: 87.5%;\n}\n.ant-col-order-21 {\n order: 21;\n}\n.ant-col-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n}\n.ant-col-push-20 {\n left: 83.33333333%;\n}\n.ant-col-pull-20 {\n right: 83.33333333%;\n}\n.ant-col-offset-20 {\n margin-left: 83.33333333%;\n}\n.ant-col-order-20 {\n order: 20;\n}\n.ant-col-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n}\n.ant-col-push-19 {\n left: 79.16666667%;\n}\n.ant-col-pull-19 {\n right: 79.16666667%;\n}\n.ant-col-offset-19 {\n margin-left: 79.16666667%;\n}\n.ant-col-order-19 {\n order: 19;\n}\n.ant-col-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n}\n.ant-col-push-18 {\n left: 75%;\n}\n.ant-col-pull-18 {\n right: 75%;\n}\n.ant-col-offset-18 {\n margin-left: 75%;\n}\n.ant-col-order-18 {\n order: 18;\n}\n.ant-col-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n}\n.ant-col-push-17 {\n left: 70.83333333%;\n}\n.ant-col-pull-17 {\n right: 70.83333333%;\n}\n.ant-col-offset-17 {\n margin-left: 70.83333333%;\n}\n.ant-col-order-17 {\n order: 17;\n}\n.ant-col-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n}\n.ant-col-push-16 {\n left: 66.66666667%;\n}\n.ant-col-pull-16 {\n right: 66.66666667%;\n}\n.ant-col-offset-16 {\n margin-left: 66.66666667%;\n}\n.ant-col-order-16 {\n order: 16;\n}\n.ant-col-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n}\n.ant-col-push-15 {\n left: 62.5%;\n}\n.ant-col-pull-15 {\n right: 62.5%;\n}\n.ant-col-offset-15 {\n margin-left: 62.5%;\n}\n.ant-col-order-15 {\n order: 15;\n}\n.ant-col-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n}\n.ant-col-push-14 {\n left: 58.33333333%;\n}\n.ant-col-pull-14 {\n right: 58.33333333%;\n}\n.ant-col-offset-14 {\n margin-left: 58.33333333%;\n}\n.ant-col-order-14 {\n order: 14;\n}\n.ant-col-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n}\n.ant-col-push-13 {\n left: 54.16666667%;\n}\n.ant-col-pull-13 {\n right: 54.16666667%;\n}\n.ant-col-offset-13 {\n margin-left: 54.16666667%;\n}\n.ant-col-order-13 {\n order: 13;\n}\n.ant-col-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n}\n.ant-col-push-12 {\n left: 50%;\n}\n.ant-col-pull-12 {\n right: 50%;\n}\n.ant-col-offset-12 {\n margin-left: 50%;\n}\n.ant-col-order-12 {\n order: 12;\n}\n.ant-col-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n}\n.ant-col-push-11 {\n left: 45.83333333%;\n}\n.ant-col-pull-11 {\n right: 45.83333333%;\n}\n.ant-col-offset-11 {\n margin-left: 45.83333333%;\n}\n.ant-col-order-11 {\n order: 11;\n}\n.ant-col-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n}\n.ant-col-push-10 {\n left: 41.66666667%;\n}\n.ant-col-pull-10 {\n right: 41.66666667%;\n}\n.ant-col-offset-10 {\n margin-left: 41.66666667%;\n}\n.ant-col-order-10 {\n order: 10;\n}\n.ant-col-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n}\n.ant-col-push-9 {\n left: 37.5%;\n}\n.ant-col-pull-9 {\n right: 37.5%;\n}\n.ant-col-offset-9 {\n margin-left: 37.5%;\n}\n.ant-col-order-9 {\n order: 9;\n}\n.ant-col-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n}\n.ant-col-push-8 {\n left: 33.33333333%;\n}\n.ant-col-pull-8 {\n right: 33.33333333%;\n}\n.ant-col-offset-8 {\n margin-left: 33.33333333%;\n}\n.ant-col-order-8 {\n order: 8;\n}\n.ant-col-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n}\n.ant-col-push-7 {\n left: 29.16666667%;\n}\n.ant-col-pull-7 {\n right: 29.16666667%;\n}\n.ant-col-offset-7 {\n margin-left: 29.16666667%;\n}\n.ant-col-order-7 {\n order: 7;\n}\n.ant-col-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n}\n.ant-col-push-6 {\n left: 25%;\n}\n.ant-col-pull-6 {\n right: 25%;\n}\n.ant-col-offset-6 {\n margin-left: 25%;\n}\n.ant-col-order-6 {\n order: 6;\n}\n.ant-col-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n}\n.ant-col-push-5 {\n left: 20.83333333%;\n}\n.ant-col-pull-5 {\n right: 20.83333333%;\n}\n.ant-col-offset-5 {\n margin-left: 20.83333333%;\n}\n.ant-col-order-5 {\n order: 5;\n}\n.ant-col-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n}\n.ant-col-push-4 {\n left: 16.66666667%;\n}\n.ant-col-pull-4 {\n right: 16.66666667%;\n}\n.ant-col-offset-4 {\n margin-left: 16.66666667%;\n}\n.ant-col-order-4 {\n order: 4;\n}\n.ant-col-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n}\n.ant-col-push-3 {\n left: 12.5%;\n}\n.ant-col-pull-3 {\n right: 12.5%;\n}\n.ant-col-offset-3 {\n margin-left: 12.5%;\n}\n.ant-col-order-3 {\n order: 3;\n}\n.ant-col-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n}\n.ant-col-push-2 {\n left: 8.33333333%;\n}\n.ant-col-pull-2 {\n right: 8.33333333%;\n}\n.ant-col-offset-2 {\n margin-left: 8.33333333%;\n}\n.ant-col-order-2 {\n order: 2;\n}\n.ant-col-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n}\n.ant-col-push-1 {\n left: 4.16666667%;\n}\n.ant-col-pull-1 {\n right: 4.16666667%;\n}\n.ant-col-offset-1 {\n margin-left: 4.16666667%;\n}\n.ant-col-order-1 {\n order: 1;\n}\n.ant-col-0 {\n display: none;\n}\n.ant-col-push-0 {\n left: auto;\n}\n.ant-col-pull-0 {\n right: auto;\n}\n.ant-col-push-0 {\n left: auto;\n}\n.ant-col-pull-0 {\n right: auto;\n}\n.ant-col-offset-0 {\n margin-left: 0;\n}\n.ant-col-order-0 {\n order: 0;\n}\n.ant-col-push-0.ant-col-rtl {\n right: auto;\n}\n.ant-col-pull-0.ant-col-rtl {\n left: auto;\n}\n.ant-col-push-0.ant-col-rtl {\n right: auto;\n}\n.ant-col-pull-0.ant-col-rtl {\n left: auto;\n}\n.ant-col-offset-0.ant-col-rtl {\n margin-right: 0;\n}\n.ant-col-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n}\n.ant-col-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n}\n.ant-col-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n}\n.ant-col-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n}\n.ant-col-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n}\n.ant-col-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n}\n.ant-col-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n}\n.ant-col-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n}\n.ant-col-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n}\n.ant-col-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n}\n.ant-col-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n}\n.ant-col-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n}\n.ant-col-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n}\n.ant-col-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n}\n.ant-col-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n}\n.ant-col-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n}\n.ant-col-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n}\n.ant-col-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n}\n.ant-col-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n}\n.ant-col-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n}\n.ant-col-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n}\n.ant-col-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n}\n.ant-col-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n}\n.ant-col-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n}\n.ant-col-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n}\n.ant-col-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n}\n.ant-col-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n}\n.ant-col-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n}\n.ant-col-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n}\n.ant-col-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n}\n.ant-col-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n}\n.ant-col-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n}\n.ant-col-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n}\n.ant-col-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n}\n.ant-col-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n}\n.ant-col-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n}\n.ant-col-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n}\n.ant-col-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n}\n.ant-col-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n}\n.ant-col-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n}\n.ant-col-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n}\n.ant-col-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n}\n.ant-col-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n}\n.ant-col-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n}\n.ant-col-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n}\n.ant-col-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n}\n.ant-col-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n}\n.ant-col-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n}\n.ant-col-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n}\n.ant-col-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n}\n.ant-col-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n}\n.ant-col-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n}\n.ant-col-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n}\n.ant-col-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n}\n.ant-col-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n}\n.ant-col-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n}\n.ant-col-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n}\n.ant-col-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n}\n.ant-col-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n}\n.ant-col-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n}\n.ant-col-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n}\n.ant-col-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n}\n.ant-col-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n}\n.ant-col-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n}\n.ant-col-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n}\n.ant-col-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n}\n.ant-col-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n}\n.ant-col-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n}\n.ant-col-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n}\n.ant-col-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n}\n.ant-col-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n}\n.ant-col-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n}\n.ant-col-xs-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n}\n.ant-col-xs-push-24 {\n left: 100%;\n}\n.ant-col-xs-pull-24 {\n right: 100%;\n}\n.ant-col-xs-offset-24 {\n margin-left: 100%;\n}\n.ant-col-xs-order-24 {\n order: 24;\n}\n.ant-col-xs-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n}\n.ant-col-xs-push-23 {\n left: 95.83333333%;\n}\n.ant-col-xs-pull-23 {\n right: 95.83333333%;\n}\n.ant-col-xs-offset-23 {\n margin-left: 95.83333333%;\n}\n.ant-col-xs-order-23 {\n order: 23;\n}\n.ant-col-xs-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n}\n.ant-col-xs-push-22 {\n left: 91.66666667%;\n}\n.ant-col-xs-pull-22 {\n right: 91.66666667%;\n}\n.ant-col-xs-offset-22 {\n margin-left: 91.66666667%;\n}\n.ant-col-xs-order-22 {\n order: 22;\n}\n.ant-col-xs-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n}\n.ant-col-xs-push-21 {\n left: 87.5%;\n}\n.ant-col-xs-pull-21 {\n right: 87.5%;\n}\n.ant-col-xs-offset-21 {\n margin-left: 87.5%;\n}\n.ant-col-xs-order-21 {\n order: 21;\n}\n.ant-col-xs-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n}\n.ant-col-xs-push-20 {\n left: 83.33333333%;\n}\n.ant-col-xs-pull-20 {\n right: 83.33333333%;\n}\n.ant-col-xs-offset-20 {\n margin-left: 83.33333333%;\n}\n.ant-col-xs-order-20 {\n order: 20;\n}\n.ant-col-xs-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n}\n.ant-col-xs-push-19 {\n left: 79.16666667%;\n}\n.ant-col-xs-pull-19 {\n right: 79.16666667%;\n}\n.ant-col-xs-offset-19 {\n margin-left: 79.16666667%;\n}\n.ant-col-xs-order-19 {\n order: 19;\n}\n.ant-col-xs-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n}\n.ant-col-xs-push-18 {\n left: 75%;\n}\n.ant-col-xs-pull-18 {\n right: 75%;\n}\n.ant-col-xs-offset-18 {\n margin-left: 75%;\n}\n.ant-col-xs-order-18 {\n order: 18;\n}\n.ant-col-xs-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n}\n.ant-col-xs-push-17 {\n left: 70.83333333%;\n}\n.ant-col-xs-pull-17 {\n right: 70.83333333%;\n}\n.ant-col-xs-offset-17 {\n margin-left: 70.83333333%;\n}\n.ant-col-xs-order-17 {\n order: 17;\n}\n.ant-col-xs-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n}\n.ant-col-xs-push-16 {\n left: 66.66666667%;\n}\n.ant-col-xs-pull-16 {\n right: 66.66666667%;\n}\n.ant-col-xs-offset-16 {\n margin-left: 66.66666667%;\n}\n.ant-col-xs-order-16 {\n order: 16;\n}\n.ant-col-xs-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n}\n.ant-col-xs-push-15 {\n left: 62.5%;\n}\n.ant-col-xs-pull-15 {\n right: 62.5%;\n}\n.ant-col-xs-offset-15 {\n margin-left: 62.5%;\n}\n.ant-col-xs-order-15 {\n order: 15;\n}\n.ant-col-xs-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n}\n.ant-col-xs-push-14 {\n left: 58.33333333%;\n}\n.ant-col-xs-pull-14 {\n right: 58.33333333%;\n}\n.ant-col-xs-offset-14 {\n margin-left: 58.33333333%;\n}\n.ant-col-xs-order-14 {\n order: 14;\n}\n.ant-col-xs-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n}\n.ant-col-xs-push-13 {\n left: 54.16666667%;\n}\n.ant-col-xs-pull-13 {\n right: 54.16666667%;\n}\n.ant-col-xs-offset-13 {\n margin-left: 54.16666667%;\n}\n.ant-col-xs-order-13 {\n order: 13;\n}\n.ant-col-xs-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n}\n.ant-col-xs-push-12 {\n left: 50%;\n}\n.ant-col-xs-pull-12 {\n right: 50%;\n}\n.ant-col-xs-offset-12 {\n margin-left: 50%;\n}\n.ant-col-xs-order-12 {\n order: 12;\n}\n.ant-col-xs-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n}\n.ant-col-xs-push-11 {\n left: 45.83333333%;\n}\n.ant-col-xs-pull-11 {\n right: 45.83333333%;\n}\n.ant-col-xs-offset-11 {\n margin-left: 45.83333333%;\n}\n.ant-col-xs-order-11 {\n order: 11;\n}\n.ant-col-xs-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n}\n.ant-col-xs-push-10 {\n left: 41.66666667%;\n}\n.ant-col-xs-pull-10 {\n right: 41.66666667%;\n}\n.ant-col-xs-offset-10 {\n margin-left: 41.66666667%;\n}\n.ant-col-xs-order-10 {\n order: 10;\n}\n.ant-col-xs-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n}\n.ant-col-xs-push-9 {\n left: 37.5%;\n}\n.ant-col-xs-pull-9 {\n right: 37.5%;\n}\n.ant-col-xs-offset-9 {\n margin-left: 37.5%;\n}\n.ant-col-xs-order-9 {\n order: 9;\n}\n.ant-col-xs-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n}\n.ant-col-xs-push-8 {\n left: 33.33333333%;\n}\n.ant-col-xs-pull-8 {\n right: 33.33333333%;\n}\n.ant-col-xs-offset-8 {\n margin-left: 33.33333333%;\n}\n.ant-col-xs-order-8 {\n order: 8;\n}\n.ant-col-xs-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n}\n.ant-col-xs-push-7 {\n left: 29.16666667%;\n}\n.ant-col-xs-pull-7 {\n right: 29.16666667%;\n}\n.ant-col-xs-offset-7 {\n margin-left: 29.16666667%;\n}\n.ant-col-xs-order-7 {\n order: 7;\n}\n.ant-col-xs-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n}\n.ant-col-xs-push-6 {\n left: 25%;\n}\n.ant-col-xs-pull-6 {\n right: 25%;\n}\n.ant-col-xs-offset-6 {\n margin-left: 25%;\n}\n.ant-col-xs-order-6 {\n order: 6;\n}\n.ant-col-xs-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n}\n.ant-col-xs-push-5 {\n left: 20.83333333%;\n}\n.ant-col-xs-pull-5 {\n right: 20.83333333%;\n}\n.ant-col-xs-offset-5 {\n margin-left: 20.83333333%;\n}\n.ant-col-xs-order-5 {\n order: 5;\n}\n.ant-col-xs-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n}\n.ant-col-xs-push-4 {\n left: 16.66666667%;\n}\n.ant-col-xs-pull-4 {\n right: 16.66666667%;\n}\n.ant-col-xs-offset-4 {\n margin-left: 16.66666667%;\n}\n.ant-col-xs-order-4 {\n order: 4;\n}\n.ant-col-xs-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n}\n.ant-col-xs-push-3 {\n left: 12.5%;\n}\n.ant-col-xs-pull-3 {\n right: 12.5%;\n}\n.ant-col-xs-offset-3 {\n margin-left: 12.5%;\n}\n.ant-col-xs-order-3 {\n order: 3;\n}\n.ant-col-xs-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n}\n.ant-col-xs-push-2 {\n left: 8.33333333%;\n}\n.ant-col-xs-pull-2 {\n right: 8.33333333%;\n}\n.ant-col-xs-offset-2 {\n margin-left: 8.33333333%;\n}\n.ant-col-xs-order-2 {\n order: 2;\n}\n.ant-col-xs-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n}\n.ant-col-xs-push-1 {\n left: 4.16666667%;\n}\n.ant-col-xs-pull-1 {\n right: 4.16666667%;\n}\n.ant-col-xs-offset-1 {\n margin-left: 4.16666667%;\n}\n.ant-col-xs-order-1 {\n order: 1;\n}\n.ant-col-xs-0 {\n display: none;\n}\n.ant-col-push-0 {\n left: auto;\n}\n.ant-col-pull-0 {\n right: auto;\n}\n.ant-col-xs-push-0 {\n left: auto;\n}\n.ant-col-xs-pull-0 {\n right: auto;\n}\n.ant-col-xs-offset-0 {\n margin-left: 0;\n}\n.ant-col-xs-order-0 {\n order: 0;\n}\n.ant-col-push-0.ant-col-rtl {\n right: auto;\n}\n.ant-col-pull-0.ant-col-rtl {\n left: auto;\n}\n.ant-col-xs-push-0.ant-col-rtl {\n right: auto;\n}\n.ant-col-xs-pull-0.ant-col-rtl {\n left: auto;\n}\n.ant-col-xs-offset-0.ant-col-rtl {\n margin-right: 0;\n}\n.ant-col-xs-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n}\n.ant-col-xs-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n}\n.ant-col-xs-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n}\n.ant-col-xs-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n}\n.ant-col-xs-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n}\n.ant-col-xs-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n}\n.ant-col-xs-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n}\n.ant-col-xs-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n}\n.ant-col-xs-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n}\n.ant-col-xs-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n}\n.ant-col-xs-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n}\n.ant-col-xs-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n}\n.ant-col-xs-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n}\n.ant-col-xs-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n}\n.ant-col-xs-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n}\n.ant-col-xs-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n}\n.ant-col-xs-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n}\n.ant-col-xs-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n}\n.ant-col-xs-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n}\n.ant-col-xs-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n}\n.ant-col-xs-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n}\n.ant-col-xs-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n}\n.ant-col-xs-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n}\n.ant-col-xs-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n}\n.ant-col-xs-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n}\n.ant-col-xs-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n}\n.ant-col-xs-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n}\n.ant-col-xs-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n}\n.ant-col-xs-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n}\n.ant-col-xs-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n}\n.ant-col-xs-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n}\n.ant-col-xs-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n}\n.ant-col-xs-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n}\n.ant-col-xs-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n}\n.ant-col-xs-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n}\n.ant-col-xs-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n}\n.ant-col-xs-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n}\n.ant-col-xs-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n}\n.ant-col-xs-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n}\n.ant-col-xs-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n}\n.ant-col-xs-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n}\n.ant-col-xs-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n}\n.ant-col-xs-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n}\n.ant-col-xs-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n}\n.ant-col-xs-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n}\n.ant-col-xs-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n}\n.ant-col-xs-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n}\n.ant-col-xs-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n}\n.ant-col-xs-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n}\n.ant-col-xs-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n}\n.ant-col-xs-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n}\n.ant-col-xs-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n}\n.ant-col-xs-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n}\n.ant-col-xs-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n}\n.ant-col-xs-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n}\n.ant-col-xs-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n}\n.ant-col-xs-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n}\n.ant-col-xs-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n}\n@media (min-width: 576px) {\n .ant-col-sm-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-sm-push-24 {\n left: 100%;\n }\n .ant-col-sm-pull-24 {\n right: 100%;\n }\n .ant-col-sm-offset-24 {\n margin-left: 100%;\n }\n .ant-col-sm-order-24 {\n order: 24;\n }\n .ant-col-sm-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n }\n .ant-col-sm-push-23 {\n left: 95.83333333%;\n }\n .ant-col-sm-pull-23 {\n right: 95.83333333%;\n }\n .ant-col-sm-offset-23 {\n margin-left: 95.83333333%;\n }\n .ant-col-sm-order-23 {\n order: 23;\n }\n .ant-col-sm-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n }\n .ant-col-sm-push-22 {\n left: 91.66666667%;\n }\n .ant-col-sm-pull-22 {\n right: 91.66666667%;\n }\n .ant-col-sm-offset-22 {\n margin-left: 91.66666667%;\n }\n .ant-col-sm-order-22 {\n order: 22;\n }\n .ant-col-sm-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n }\n .ant-col-sm-push-21 {\n left: 87.5%;\n }\n .ant-col-sm-pull-21 {\n right: 87.5%;\n }\n .ant-col-sm-offset-21 {\n margin-left: 87.5%;\n }\n .ant-col-sm-order-21 {\n order: 21;\n }\n .ant-col-sm-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n }\n .ant-col-sm-push-20 {\n left: 83.33333333%;\n }\n .ant-col-sm-pull-20 {\n right: 83.33333333%;\n }\n .ant-col-sm-offset-20 {\n margin-left: 83.33333333%;\n }\n .ant-col-sm-order-20 {\n order: 20;\n }\n .ant-col-sm-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n }\n .ant-col-sm-push-19 {\n left: 79.16666667%;\n }\n .ant-col-sm-pull-19 {\n right: 79.16666667%;\n }\n .ant-col-sm-offset-19 {\n margin-left: 79.16666667%;\n }\n .ant-col-sm-order-19 {\n order: 19;\n }\n .ant-col-sm-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n }\n .ant-col-sm-push-18 {\n left: 75%;\n }\n .ant-col-sm-pull-18 {\n right: 75%;\n }\n .ant-col-sm-offset-18 {\n margin-left: 75%;\n }\n .ant-col-sm-order-18 {\n order: 18;\n }\n .ant-col-sm-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n }\n .ant-col-sm-push-17 {\n left: 70.83333333%;\n }\n .ant-col-sm-pull-17 {\n right: 70.83333333%;\n }\n .ant-col-sm-offset-17 {\n margin-left: 70.83333333%;\n }\n .ant-col-sm-order-17 {\n order: 17;\n }\n .ant-col-sm-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n }\n .ant-col-sm-push-16 {\n left: 66.66666667%;\n }\n .ant-col-sm-pull-16 {\n right: 66.66666667%;\n }\n .ant-col-sm-offset-16 {\n margin-left: 66.66666667%;\n }\n .ant-col-sm-order-16 {\n order: 16;\n }\n .ant-col-sm-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n }\n .ant-col-sm-push-15 {\n left: 62.5%;\n }\n .ant-col-sm-pull-15 {\n right: 62.5%;\n }\n .ant-col-sm-offset-15 {\n margin-left: 62.5%;\n }\n .ant-col-sm-order-15 {\n order: 15;\n }\n .ant-col-sm-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n }\n .ant-col-sm-push-14 {\n left: 58.33333333%;\n }\n .ant-col-sm-pull-14 {\n right: 58.33333333%;\n }\n .ant-col-sm-offset-14 {\n margin-left: 58.33333333%;\n }\n .ant-col-sm-order-14 {\n order: 14;\n }\n .ant-col-sm-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n }\n .ant-col-sm-push-13 {\n left: 54.16666667%;\n }\n .ant-col-sm-pull-13 {\n right: 54.16666667%;\n }\n .ant-col-sm-offset-13 {\n margin-left: 54.16666667%;\n }\n .ant-col-sm-order-13 {\n order: 13;\n }\n .ant-col-sm-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n }\n .ant-col-sm-push-12 {\n left: 50%;\n }\n .ant-col-sm-pull-12 {\n right: 50%;\n }\n .ant-col-sm-offset-12 {\n margin-left: 50%;\n }\n .ant-col-sm-order-12 {\n order: 12;\n }\n .ant-col-sm-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n }\n .ant-col-sm-push-11 {\n left: 45.83333333%;\n }\n .ant-col-sm-pull-11 {\n right: 45.83333333%;\n }\n .ant-col-sm-offset-11 {\n margin-left: 45.83333333%;\n }\n .ant-col-sm-order-11 {\n order: 11;\n }\n .ant-col-sm-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n }\n .ant-col-sm-push-10 {\n left: 41.66666667%;\n }\n .ant-col-sm-pull-10 {\n right: 41.66666667%;\n }\n .ant-col-sm-offset-10 {\n margin-left: 41.66666667%;\n }\n .ant-col-sm-order-10 {\n order: 10;\n }\n .ant-col-sm-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n }\n .ant-col-sm-push-9 {\n left: 37.5%;\n }\n .ant-col-sm-pull-9 {\n right: 37.5%;\n }\n .ant-col-sm-offset-9 {\n margin-left: 37.5%;\n }\n .ant-col-sm-order-9 {\n order: 9;\n }\n .ant-col-sm-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n }\n .ant-col-sm-push-8 {\n left: 33.33333333%;\n }\n .ant-col-sm-pull-8 {\n right: 33.33333333%;\n }\n .ant-col-sm-offset-8 {\n margin-left: 33.33333333%;\n }\n .ant-col-sm-order-8 {\n order: 8;\n }\n .ant-col-sm-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n }\n .ant-col-sm-push-7 {\n left: 29.16666667%;\n }\n .ant-col-sm-pull-7 {\n right: 29.16666667%;\n }\n .ant-col-sm-offset-7 {\n margin-left: 29.16666667%;\n }\n .ant-col-sm-order-7 {\n order: 7;\n }\n .ant-col-sm-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n }\n .ant-col-sm-push-6 {\n left: 25%;\n }\n .ant-col-sm-pull-6 {\n right: 25%;\n }\n .ant-col-sm-offset-6 {\n margin-left: 25%;\n }\n .ant-col-sm-order-6 {\n order: 6;\n }\n .ant-col-sm-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n }\n .ant-col-sm-push-5 {\n left: 20.83333333%;\n }\n .ant-col-sm-pull-5 {\n right: 20.83333333%;\n }\n .ant-col-sm-offset-5 {\n margin-left: 20.83333333%;\n }\n .ant-col-sm-order-5 {\n order: 5;\n }\n .ant-col-sm-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n }\n .ant-col-sm-push-4 {\n left: 16.66666667%;\n }\n .ant-col-sm-pull-4 {\n right: 16.66666667%;\n }\n .ant-col-sm-offset-4 {\n margin-left: 16.66666667%;\n }\n .ant-col-sm-order-4 {\n order: 4;\n }\n .ant-col-sm-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n }\n .ant-col-sm-push-3 {\n left: 12.5%;\n }\n .ant-col-sm-pull-3 {\n right: 12.5%;\n }\n .ant-col-sm-offset-3 {\n margin-left: 12.5%;\n }\n .ant-col-sm-order-3 {\n order: 3;\n }\n .ant-col-sm-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n }\n .ant-col-sm-push-2 {\n left: 8.33333333%;\n }\n .ant-col-sm-pull-2 {\n right: 8.33333333%;\n }\n .ant-col-sm-offset-2 {\n margin-left: 8.33333333%;\n }\n .ant-col-sm-order-2 {\n order: 2;\n }\n .ant-col-sm-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n }\n .ant-col-sm-push-1 {\n left: 4.16666667%;\n }\n .ant-col-sm-pull-1 {\n right: 4.16666667%;\n }\n .ant-col-sm-offset-1 {\n margin-left: 4.16666667%;\n }\n .ant-col-sm-order-1 {\n order: 1;\n }\n .ant-col-sm-0 {\n display: none;\n }\n .ant-col-push-0 {\n left: auto;\n }\n .ant-col-pull-0 {\n right: auto;\n }\n .ant-col-sm-push-0 {\n left: auto;\n }\n .ant-col-sm-pull-0 {\n right: auto;\n }\n .ant-col-sm-offset-0 {\n margin-left: 0;\n }\n .ant-col-sm-order-0 {\n order: 0;\n }\n .ant-col-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-sm-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-sm-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-sm-offset-0.ant-col-rtl {\n margin-right: 0;\n }\n .ant-col-sm-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n }\n .ant-col-sm-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n }\n .ant-col-sm-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n }\n .ant-col-sm-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n }\n .ant-col-sm-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n }\n .ant-col-sm-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n }\n .ant-col-sm-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n }\n .ant-col-sm-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n }\n .ant-col-sm-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n }\n .ant-col-sm-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n }\n .ant-col-sm-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n }\n .ant-col-sm-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n }\n .ant-col-sm-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n }\n .ant-col-sm-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n }\n .ant-col-sm-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n }\n .ant-col-sm-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n }\n .ant-col-sm-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n }\n .ant-col-sm-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n }\n .ant-col-sm-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n }\n .ant-col-sm-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n }\n .ant-col-sm-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n }\n .ant-col-sm-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n }\n .ant-col-sm-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n }\n .ant-col-sm-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n }\n .ant-col-sm-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n }\n .ant-col-sm-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n }\n .ant-col-sm-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n }\n .ant-col-sm-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n }\n .ant-col-sm-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n }\n .ant-col-sm-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n }\n .ant-col-sm-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n }\n .ant-col-sm-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n }\n .ant-col-sm-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n }\n .ant-col-sm-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n }\n .ant-col-sm-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n }\n .ant-col-sm-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n }\n .ant-col-sm-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n }\n .ant-col-sm-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n }\n .ant-col-sm-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n }\n .ant-col-sm-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n }\n .ant-col-sm-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n }\n .ant-col-sm-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n }\n .ant-col-sm-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n }\n .ant-col-sm-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n }\n .ant-col-sm-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n }\n .ant-col-sm-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n }\n .ant-col-sm-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n }\n .ant-col-sm-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n }\n .ant-col-sm-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n }\n .ant-col-sm-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n }\n .ant-col-sm-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n }\n .ant-col-sm-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n }\n .ant-col-sm-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n }\n .ant-col-sm-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n }\n .ant-col-sm-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n }\n .ant-col-sm-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n }\n .ant-col-sm-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n }\n .ant-col-sm-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n }\n}\n@media (min-width: 768px) {\n .ant-col-md-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-md-push-24 {\n left: 100%;\n }\n .ant-col-md-pull-24 {\n right: 100%;\n }\n .ant-col-md-offset-24 {\n margin-left: 100%;\n }\n .ant-col-md-order-24 {\n order: 24;\n }\n .ant-col-md-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n }\n .ant-col-md-push-23 {\n left: 95.83333333%;\n }\n .ant-col-md-pull-23 {\n right: 95.83333333%;\n }\n .ant-col-md-offset-23 {\n margin-left: 95.83333333%;\n }\n .ant-col-md-order-23 {\n order: 23;\n }\n .ant-col-md-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n }\n .ant-col-md-push-22 {\n left: 91.66666667%;\n }\n .ant-col-md-pull-22 {\n right: 91.66666667%;\n }\n .ant-col-md-offset-22 {\n margin-left: 91.66666667%;\n }\n .ant-col-md-order-22 {\n order: 22;\n }\n .ant-col-md-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n }\n .ant-col-md-push-21 {\n left: 87.5%;\n }\n .ant-col-md-pull-21 {\n right: 87.5%;\n }\n .ant-col-md-offset-21 {\n margin-left: 87.5%;\n }\n .ant-col-md-order-21 {\n order: 21;\n }\n .ant-col-md-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n }\n .ant-col-md-push-20 {\n left: 83.33333333%;\n }\n .ant-col-md-pull-20 {\n right: 83.33333333%;\n }\n .ant-col-md-offset-20 {\n margin-left: 83.33333333%;\n }\n .ant-col-md-order-20 {\n order: 20;\n }\n .ant-col-md-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n }\n .ant-col-md-push-19 {\n left: 79.16666667%;\n }\n .ant-col-md-pull-19 {\n right: 79.16666667%;\n }\n .ant-col-md-offset-19 {\n margin-left: 79.16666667%;\n }\n .ant-col-md-order-19 {\n order: 19;\n }\n .ant-col-md-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n }\n .ant-col-md-push-18 {\n left: 75%;\n }\n .ant-col-md-pull-18 {\n right: 75%;\n }\n .ant-col-md-offset-18 {\n margin-left: 75%;\n }\n .ant-col-md-order-18 {\n order: 18;\n }\n .ant-col-md-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n }\n .ant-col-md-push-17 {\n left: 70.83333333%;\n }\n .ant-col-md-pull-17 {\n right: 70.83333333%;\n }\n .ant-col-md-offset-17 {\n margin-left: 70.83333333%;\n }\n .ant-col-md-order-17 {\n order: 17;\n }\n .ant-col-md-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n }\n .ant-col-md-push-16 {\n left: 66.66666667%;\n }\n .ant-col-md-pull-16 {\n right: 66.66666667%;\n }\n .ant-col-md-offset-16 {\n margin-left: 66.66666667%;\n }\n .ant-col-md-order-16 {\n order: 16;\n }\n .ant-col-md-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n }\n .ant-col-md-push-15 {\n left: 62.5%;\n }\n .ant-col-md-pull-15 {\n right: 62.5%;\n }\n .ant-col-md-offset-15 {\n margin-left: 62.5%;\n }\n .ant-col-md-order-15 {\n order: 15;\n }\n .ant-col-md-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n }\n .ant-col-md-push-14 {\n left: 58.33333333%;\n }\n .ant-col-md-pull-14 {\n right: 58.33333333%;\n }\n .ant-col-md-offset-14 {\n margin-left: 58.33333333%;\n }\n .ant-col-md-order-14 {\n order: 14;\n }\n .ant-col-md-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n }\n .ant-col-md-push-13 {\n left: 54.16666667%;\n }\n .ant-col-md-pull-13 {\n right: 54.16666667%;\n }\n .ant-col-md-offset-13 {\n margin-left: 54.16666667%;\n }\n .ant-col-md-order-13 {\n order: 13;\n }\n .ant-col-md-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n }\n .ant-col-md-push-12 {\n left: 50%;\n }\n .ant-col-md-pull-12 {\n right: 50%;\n }\n .ant-col-md-offset-12 {\n margin-left: 50%;\n }\n .ant-col-md-order-12 {\n order: 12;\n }\n .ant-col-md-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n }\n .ant-col-md-push-11 {\n left: 45.83333333%;\n }\n .ant-col-md-pull-11 {\n right: 45.83333333%;\n }\n .ant-col-md-offset-11 {\n margin-left: 45.83333333%;\n }\n .ant-col-md-order-11 {\n order: 11;\n }\n .ant-col-md-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n }\n .ant-col-md-push-10 {\n left: 41.66666667%;\n }\n .ant-col-md-pull-10 {\n right: 41.66666667%;\n }\n .ant-col-md-offset-10 {\n margin-left: 41.66666667%;\n }\n .ant-col-md-order-10 {\n order: 10;\n }\n .ant-col-md-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n }\n .ant-col-md-push-9 {\n left: 37.5%;\n }\n .ant-col-md-pull-9 {\n right: 37.5%;\n }\n .ant-col-md-offset-9 {\n margin-left: 37.5%;\n }\n .ant-col-md-order-9 {\n order: 9;\n }\n .ant-col-md-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n }\n .ant-col-md-push-8 {\n left: 33.33333333%;\n }\n .ant-col-md-pull-8 {\n right: 33.33333333%;\n }\n .ant-col-md-offset-8 {\n margin-left: 33.33333333%;\n }\n .ant-col-md-order-8 {\n order: 8;\n }\n .ant-col-md-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n }\n .ant-col-md-push-7 {\n left: 29.16666667%;\n }\n .ant-col-md-pull-7 {\n right: 29.16666667%;\n }\n .ant-col-md-offset-7 {\n margin-left: 29.16666667%;\n }\n .ant-col-md-order-7 {\n order: 7;\n }\n .ant-col-md-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n }\n .ant-col-md-push-6 {\n left: 25%;\n }\n .ant-col-md-pull-6 {\n right: 25%;\n }\n .ant-col-md-offset-6 {\n margin-left: 25%;\n }\n .ant-col-md-order-6 {\n order: 6;\n }\n .ant-col-md-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n }\n .ant-col-md-push-5 {\n left: 20.83333333%;\n }\n .ant-col-md-pull-5 {\n right: 20.83333333%;\n }\n .ant-col-md-offset-5 {\n margin-left: 20.83333333%;\n }\n .ant-col-md-order-5 {\n order: 5;\n }\n .ant-col-md-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n }\n .ant-col-md-push-4 {\n left: 16.66666667%;\n }\n .ant-col-md-pull-4 {\n right: 16.66666667%;\n }\n .ant-col-md-offset-4 {\n margin-left: 16.66666667%;\n }\n .ant-col-md-order-4 {\n order: 4;\n }\n .ant-col-md-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n }\n .ant-col-md-push-3 {\n left: 12.5%;\n }\n .ant-col-md-pull-3 {\n right: 12.5%;\n }\n .ant-col-md-offset-3 {\n margin-left: 12.5%;\n }\n .ant-col-md-order-3 {\n order: 3;\n }\n .ant-col-md-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n }\n .ant-col-md-push-2 {\n left: 8.33333333%;\n }\n .ant-col-md-pull-2 {\n right: 8.33333333%;\n }\n .ant-col-md-offset-2 {\n margin-left: 8.33333333%;\n }\n .ant-col-md-order-2 {\n order: 2;\n }\n .ant-col-md-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n }\n .ant-col-md-push-1 {\n left: 4.16666667%;\n }\n .ant-col-md-pull-1 {\n right: 4.16666667%;\n }\n .ant-col-md-offset-1 {\n margin-left: 4.16666667%;\n }\n .ant-col-md-order-1 {\n order: 1;\n }\n .ant-col-md-0 {\n display: none;\n }\n .ant-col-push-0 {\n left: auto;\n }\n .ant-col-pull-0 {\n right: auto;\n }\n .ant-col-md-push-0 {\n left: auto;\n }\n .ant-col-md-pull-0 {\n right: auto;\n }\n .ant-col-md-offset-0 {\n margin-left: 0;\n }\n .ant-col-md-order-0 {\n order: 0;\n }\n .ant-col-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-md-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-md-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-md-offset-0.ant-col-rtl {\n margin-right: 0;\n }\n .ant-col-md-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n }\n .ant-col-md-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n }\n .ant-col-md-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n }\n .ant-col-md-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n }\n .ant-col-md-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n }\n .ant-col-md-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n }\n .ant-col-md-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n }\n .ant-col-md-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n }\n .ant-col-md-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n }\n .ant-col-md-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n }\n .ant-col-md-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n }\n .ant-col-md-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n }\n .ant-col-md-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n }\n .ant-col-md-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n }\n .ant-col-md-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n }\n .ant-col-md-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n }\n .ant-col-md-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n }\n .ant-col-md-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n }\n .ant-col-md-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n }\n .ant-col-md-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n }\n .ant-col-md-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n }\n .ant-col-md-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n }\n .ant-col-md-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n }\n .ant-col-md-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n }\n .ant-col-md-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n }\n .ant-col-md-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n }\n .ant-col-md-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n }\n .ant-col-md-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n }\n .ant-col-md-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n }\n .ant-col-md-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n }\n .ant-col-md-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n }\n .ant-col-md-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n }\n .ant-col-md-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n }\n .ant-col-md-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n }\n .ant-col-md-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n }\n .ant-col-md-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n }\n .ant-col-md-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n }\n .ant-col-md-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n }\n .ant-col-md-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n }\n .ant-col-md-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n }\n .ant-col-md-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n }\n .ant-col-md-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n }\n .ant-col-md-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n }\n .ant-col-md-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n }\n .ant-col-md-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n }\n .ant-col-md-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n }\n .ant-col-md-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n }\n .ant-col-md-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n }\n .ant-col-md-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n }\n .ant-col-md-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n }\n .ant-col-md-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n }\n .ant-col-md-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n }\n .ant-col-md-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n }\n .ant-col-md-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n }\n .ant-col-md-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n }\n .ant-col-md-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n }\n .ant-col-md-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n }\n .ant-col-md-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n }\n .ant-col-md-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n }\n .ant-col-md-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n }\n .ant-col-md-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n }\n .ant-col-md-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n }\n .ant-col-md-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n }\n .ant-col-md-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n }\n .ant-col-md-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n }\n .ant-col-md-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n }\n .ant-col-md-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n }\n .ant-col-md-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n }\n .ant-col-md-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n }\n .ant-col-md-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n }\n .ant-col-md-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n }\n .ant-col-md-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n }\n}\n@media (min-width: 992px) {\n .ant-col-lg-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-lg-push-24 {\n left: 100%;\n }\n .ant-col-lg-pull-24 {\n right: 100%;\n }\n .ant-col-lg-offset-24 {\n margin-left: 100%;\n }\n .ant-col-lg-order-24 {\n order: 24;\n }\n .ant-col-lg-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n }\n .ant-col-lg-push-23 {\n left: 95.83333333%;\n }\n .ant-col-lg-pull-23 {\n right: 95.83333333%;\n }\n .ant-col-lg-offset-23 {\n margin-left: 95.83333333%;\n }\n .ant-col-lg-order-23 {\n order: 23;\n }\n .ant-col-lg-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n }\n .ant-col-lg-push-22 {\n left: 91.66666667%;\n }\n .ant-col-lg-pull-22 {\n right: 91.66666667%;\n }\n .ant-col-lg-offset-22 {\n margin-left: 91.66666667%;\n }\n .ant-col-lg-order-22 {\n order: 22;\n }\n .ant-col-lg-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n }\n .ant-col-lg-push-21 {\n left: 87.5%;\n }\n .ant-col-lg-pull-21 {\n right: 87.5%;\n }\n .ant-col-lg-offset-21 {\n margin-left: 87.5%;\n }\n .ant-col-lg-order-21 {\n order: 21;\n }\n .ant-col-lg-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n }\n .ant-col-lg-push-20 {\n left: 83.33333333%;\n }\n .ant-col-lg-pull-20 {\n right: 83.33333333%;\n }\n .ant-col-lg-offset-20 {\n margin-left: 83.33333333%;\n }\n .ant-col-lg-order-20 {\n order: 20;\n }\n .ant-col-lg-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n }\n .ant-col-lg-push-19 {\n left: 79.16666667%;\n }\n .ant-col-lg-pull-19 {\n right: 79.16666667%;\n }\n .ant-col-lg-offset-19 {\n margin-left: 79.16666667%;\n }\n .ant-col-lg-order-19 {\n order: 19;\n }\n .ant-col-lg-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n }\n .ant-col-lg-push-18 {\n left: 75%;\n }\n .ant-col-lg-pull-18 {\n right: 75%;\n }\n .ant-col-lg-offset-18 {\n margin-left: 75%;\n }\n .ant-col-lg-order-18 {\n order: 18;\n }\n .ant-col-lg-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n }\n .ant-col-lg-push-17 {\n left: 70.83333333%;\n }\n .ant-col-lg-pull-17 {\n right: 70.83333333%;\n }\n .ant-col-lg-offset-17 {\n margin-left: 70.83333333%;\n }\n .ant-col-lg-order-17 {\n order: 17;\n }\n .ant-col-lg-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n }\n .ant-col-lg-push-16 {\n left: 66.66666667%;\n }\n .ant-col-lg-pull-16 {\n right: 66.66666667%;\n }\n .ant-col-lg-offset-16 {\n margin-left: 66.66666667%;\n }\n .ant-col-lg-order-16 {\n order: 16;\n }\n .ant-col-lg-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n }\n .ant-col-lg-push-15 {\n left: 62.5%;\n }\n .ant-col-lg-pull-15 {\n right: 62.5%;\n }\n .ant-col-lg-offset-15 {\n margin-left: 62.5%;\n }\n .ant-col-lg-order-15 {\n order: 15;\n }\n .ant-col-lg-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n }\n .ant-col-lg-push-14 {\n left: 58.33333333%;\n }\n .ant-col-lg-pull-14 {\n right: 58.33333333%;\n }\n .ant-col-lg-offset-14 {\n margin-left: 58.33333333%;\n }\n .ant-col-lg-order-14 {\n order: 14;\n }\n .ant-col-lg-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n }\n .ant-col-lg-push-13 {\n left: 54.16666667%;\n }\n .ant-col-lg-pull-13 {\n right: 54.16666667%;\n }\n .ant-col-lg-offset-13 {\n margin-left: 54.16666667%;\n }\n .ant-col-lg-order-13 {\n order: 13;\n }\n .ant-col-lg-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n }\n .ant-col-lg-push-12 {\n left: 50%;\n }\n .ant-col-lg-pull-12 {\n right: 50%;\n }\n .ant-col-lg-offset-12 {\n margin-left: 50%;\n }\n .ant-col-lg-order-12 {\n order: 12;\n }\n .ant-col-lg-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n }\n .ant-col-lg-push-11 {\n left: 45.83333333%;\n }\n .ant-col-lg-pull-11 {\n right: 45.83333333%;\n }\n .ant-col-lg-offset-11 {\n margin-left: 45.83333333%;\n }\n .ant-col-lg-order-11 {\n order: 11;\n }\n .ant-col-lg-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n }\n .ant-col-lg-push-10 {\n left: 41.66666667%;\n }\n .ant-col-lg-pull-10 {\n right: 41.66666667%;\n }\n .ant-col-lg-offset-10 {\n margin-left: 41.66666667%;\n }\n .ant-col-lg-order-10 {\n order: 10;\n }\n .ant-col-lg-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n }\n .ant-col-lg-push-9 {\n left: 37.5%;\n }\n .ant-col-lg-pull-9 {\n right: 37.5%;\n }\n .ant-col-lg-offset-9 {\n margin-left: 37.5%;\n }\n .ant-col-lg-order-9 {\n order: 9;\n }\n .ant-col-lg-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n }\n .ant-col-lg-push-8 {\n left: 33.33333333%;\n }\n .ant-col-lg-pull-8 {\n right: 33.33333333%;\n }\n .ant-col-lg-offset-8 {\n margin-left: 33.33333333%;\n }\n .ant-col-lg-order-8 {\n order: 8;\n }\n .ant-col-lg-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n }\n .ant-col-lg-push-7 {\n left: 29.16666667%;\n }\n .ant-col-lg-pull-7 {\n right: 29.16666667%;\n }\n .ant-col-lg-offset-7 {\n margin-left: 29.16666667%;\n }\n .ant-col-lg-order-7 {\n order: 7;\n }\n .ant-col-lg-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n }\n .ant-col-lg-push-6 {\n left: 25%;\n }\n .ant-col-lg-pull-6 {\n right: 25%;\n }\n .ant-col-lg-offset-6 {\n margin-left: 25%;\n }\n .ant-col-lg-order-6 {\n order: 6;\n }\n .ant-col-lg-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n }\n .ant-col-lg-push-5 {\n left: 20.83333333%;\n }\n .ant-col-lg-pull-5 {\n right: 20.83333333%;\n }\n .ant-col-lg-offset-5 {\n margin-left: 20.83333333%;\n }\n .ant-col-lg-order-5 {\n order: 5;\n }\n .ant-col-lg-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n }\n .ant-col-lg-push-4 {\n left: 16.66666667%;\n }\n .ant-col-lg-pull-4 {\n right: 16.66666667%;\n }\n .ant-col-lg-offset-4 {\n margin-left: 16.66666667%;\n }\n .ant-col-lg-order-4 {\n order: 4;\n }\n .ant-col-lg-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n }\n .ant-col-lg-push-3 {\n left: 12.5%;\n }\n .ant-col-lg-pull-3 {\n right: 12.5%;\n }\n .ant-col-lg-offset-3 {\n margin-left: 12.5%;\n }\n .ant-col-lg-order-3 {\n order: 3;\n }\n .ant-col-lg-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n }\n .ant-col-lg-push-2 {\n left: 8.33333333%;\n }\n .ant-col-lg-pull-2 {\n right: 8.33333333%;\n }\n .ant-col-lg-offset-2 {\n margin-left: 8.33333333%;\n }\n .ant-col-lg-order-2 {\n order: 2;\n }\n .ant-col-lg-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n }\n .ant-col-lg-push-1 {\n left: 4.16666667%;\n }\n .ant-col-lg-pull-1 {\n right: 4.16666667%;\n }\n .ant-col-lg-offset-1 {\n margin-left: 4.16666667%;\n }\n .ant-col-lg-order-1 {\n order: 1;\n }\n .ant-col-lg-0 {\n display: none;\n }\n .ant-col-push-0 {\n left: auto;\n }\n .ant-col-pull-0 {\n right: auto;\n }\n .ant-col-lg-push-0 {\n left: auto;\n }\n .ant-col-lg-pull-0 {\n right: auto;\n }\n .ant-col-lg-offset-0 {\n margin-left: 0;\n }\n .ant-col-lg-order-0 {\n order: 0;\n }\n .ant-col-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-lg-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-lg-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-lg-offset-0.ant-col-rtl {\n margin-right: 0;\n }\n .ant-col-lg-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n }\n .ant-col-lg-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n }\n .ant-col-lg-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n }\n .ant-col-lg-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n }\n .ant-col-lg-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n }\n .ant-col-lg-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n }\n .ant-col-lg-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n }\n .ant-col-lg-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n }\n .ant-col-lg-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n }\n .ant-col-lg-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n }\n .ant-col-lg-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n }\n .ant-col-lg-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n }\n .ant-col-lg-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n }\n .ant-col-lg-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n }\n .ant-col-lg-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n }\n .ant-col-lg-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n }\n .ant-col-lg-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n }\n .ant-col-lg-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n }\n .ant-col-lg-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n }\n .ant-col-lg-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n }\n .ant-col-lg-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n }\n .ant-col-lg-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n }\n .ant-col-lg-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n }\n .ant-col-lg-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n }\n .ant-col-lg-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n }\n .ant-col-lg-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n }\n .ant-col-lg-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n }\n .ant-col-lg-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n }\n .ant-col-lg-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n }\n .ant-col-lg-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n }\n .ant-col-lg-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n }\n .ant-col-lg-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n }\n .ant-col-lg-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n }\n .ant-col-lg-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n }\n .ant-col-lg-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n }\n .ant-col-lg-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n }\n .ant-col-lg-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n }\n .ant-col-lg-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n }\n .ant-col-lg-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n }\n .ant-col-lg-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n }\n .ant-col-lg-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n }\n .ant-col-lg-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n }\n .ant-col-lg-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n }\n .ant-col-lg-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n }\n .ant-col-lg-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n }\n .ant-col-lg-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n }\n .ant-col-lg-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n }\n .ant-col-lg-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n }\n .ant-col-lg-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n }\n .ant-col-lg-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n }\n .ant-col-lg-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n }\n .ant-col-lg-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n }\n .ant-col-lg-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n }\n .ant-col-lg-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n }\n .ant-col-lg-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n }\n .ant-col-lg-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n }\n .ant-col-lg-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n }\n .ant-col-lg-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n }\n}\n@media (min-width: 1200px) {\n .ant-col-xl-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-xl-push-24 {\n left: 100%;\n }\n .ant-col-xl-pull-24 {\n right: 100%;\n }\n .ant-col-xl-offset-24 {\n margin-left: 100%;\n }\n .ant-col-xl-order-24 {\n order: 24;\n }\n .ant-col-xl-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n }\n .ant-col-xl-push-23 {\n left: 95.83333333%;\n }\n .ant-col-xl-pull-23 {\n right: 95.83333333%;\n }\n .ant-col-xl-offset-23 {\n margin-left: 95.83333333%;\n }\n .ant-col-xl-order-23 {\n order: 23;\n }\n .ant-col-xl-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n }\n .ant-col-xl-push-22 {\n left: 91.66666667%;\n }\n .ant-col-xl-pull-22 {\n right: 91.66666667%;\n }\n .ant-col-xl-offset-22 {\n margin-left: 91.66666667%;\n }\n .ant-col-xl-order-22 {\n order: 22;\n }\n .ant-col-xl-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n }\n .ant-col-xl-push-21 {\n left: 87.5%;\n }\n .ant-col-xl-pull-21 {\n right: 87.5%;\n }\n .ant-col-xl-offset-21 {\n margin-left: 87.5%;\n }\n .ant-col-xl-order-21 {\n order: 21;\n }\n .ant-col-xl-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n }\n .ant-col-xl-push-20 {\n left: 83.33333333%;\n }\n .ant-col-xl-pull-20 {\n right: 83.33333333%;\n }\n .ant-col-xl-offset-20 {\n margin-left: 83.33333333%;\n }\n .ant-col-xl-order-20 {\n order: 20;\n }\n .ant-col-xl-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n }\n .ant-col-xl-push-19 {\n left: 79.16666667%;\n }\n .ant-col-xl-pull-19 {\n right: 79.16666667%;\n }\n .ant-col-xl-offset-19 {\n margin-left: 79.16666667%;\n }\n .ant-col-xl-order-19 {\n order: 19;\n }\n .ant-col-xl-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n }\n .ant-col-xl-push-18 {\n left: 75%;\n }\n .ant-col-xl-pull-18 {\n right: 75%;\n }\n .ant-col-xl-offset-18 {\n margin-left: 75%;\n }\n .ant-col-xl-order-18 {\n order: 18;\n }\n .ant-col-xl-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n }\n .ant-col-xl-push-17 {\n left: 70.83333333%;\n }\n .ant-col-xl-pull-17 {\n right: 70.83333333%;\n }\n .ant-col-xl-offset-17 {\n margin-left: 70.83333333%;\n }\n .ant-col-xl-order-17 {\n order: 17;\n }\n .ant-col-xl-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n }\n .ant-col-xl-push-16 {\n left: 66.66666667%;\n }\n .ant-col-xl-pull-16 {\n right: 66.66666667%;\n }\n .ant-col-xl-offset-16 {\n margin-left: 66.66666667%;\n }\n .ant-col-xl-order-16 {\n order: 16;\n }\n .ant-col-xl-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n }\n .ant-col-xl-push-15 {\n left: 62.5%;\n }\n .ant-col-xl-pull-15 {\n right: 62.5%;\n }\n .ant-col-xl-offset-15 {\n margin-left: 62.5%;\n }\n .ant-col-xl-order-15 {\n order: 15;\n }\n .ant-col-xl-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n }\n .ant-col-xl-push-14 {\n left: 58.33333333%;\n }\n .ant-col-xl-pull-14 {\n right: 58.33333333%;\n }\n .ant-col-xl-offset-14 {\n margin-left: 58.33333333%;\n }\n .ant-col-xl-order-14 {\n order: 14;\n }\n .ant-col-xl-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n }\n .ant-col-xl-push-13 {\n left: 54.16666667%;\n }\n .ant-col-xl-pull-13 {\n right: 54.16666667%;\n }\n .ant-col-xl-offset-13 {\n margin-left: 54.16666667%;\n }\n .ant-col-xl-order-13 {\n order: 13;\n }\n .ant-col-xl-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n }\n .ant-col-xl-push-12 {\n left: 50%;\n }\n .ant-col-xl-pull-12 {\n right: 50%;\n }\n .ant-col-xl-offset-12 {\n margin-left: 50%;\n }\n .ant-col-xl-order-12 {\n order: 12;\n }\n .ant-col-xl-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n }\n .ant-col-xl-push-11 {\n left: 45.83333333%;\n }\n .ant-col-xl-pull-11 {\n right: 45.83333333%;\n }\n .ant-col-xl-offset-11 {\n margin-left: 45.83333333%;\n }\n .ant-col-xl-order-11 {\n order: 11;\n }\n .ant-col-xl-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n }\n .ant-col-xl-push-10 {\n left: 41.66666667%;\n }\n .ant-col-xl-pull-10 {\n right: 41.66666667%;\n }\n .ant-col-xl-offset-10 {\n margin-left: 41.66666667%;\n }\n .ant-col-xl-order-10 {\n order: 10;\n }\n .ant-col-xl-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n }\n .ant-col-xl-push-9 {\n left: 37.5%;\n }\n .ant-col-xl-pull-9 {\n right: 37.5%;\n }\n .ant-col-xl-offset-9 {\n margin-left: 37.5%;\n }\n .ant-col-xl-order-9 {\n order: 9;\n }\n .ant-col-xl-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n }\n .ant-col-xl-push-8 {\n left: 33.33333333%;\n }\n .ant-col-xl-pull-8 {\n right: 33.33333333%;\n }\n .ant-col-xl-offset-8 {\n margin-left: 33.33333333%;\n }\n .ant-col-xl-order-8 {\n order: 8;\n }\n .ant-col-xl-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n }\n .ant-col-xl-push-7 {\n left: 29.16666667%;\n }\n .ant-col-xl-pull-7 {\n right: 29.16666667%;\n }\n .ant-col-xl-offset-7 {\n margin-left: 29.16666667%;\n }\n .ant-col-xl-order-7 {\n order: 7;\n }\n .ant-col-xl-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n }\n .ant-col-xl-push-6 {\n left: 25%;\n }\n .ant-col-xl-pull-6 {\n right: 25%;\n }\n .ant-col-xl-offset-6 {\n margin-left: 25%;\n }\n .ant-col-xl-order-6 {\n order: 6;\n }\n .ant-col-xl-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n }\n .ant-col-xl-push-5 {\n left: 20.83333333%;\n }\n .ant-col-xl-pull-5 {\n right: 20.83333333%;\n }\n .ant-col-xl-offset-5 {\n margin-left: 20.83333333%;\n }\n .ant-col-xl-order-5 {\n order: 5;\n }\n .ant-col-xl-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n }\n .ant-col-xl-push-4 {\n left: 16.66666667%;\n }\n .ant-col-xl-pull-4 {\n right: 16.66666667%;\n }\n .ant-col-xl-offset-4 {\n margin-left: 16.66666667%;\n }\n .ant-col-xl-order-4 {\n order: 4;\n }\n .ant-col-xl-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n }\n .ant-col-xl-push-3 {\n left: 12.5%;\n }\n .ant-col-xl-pull-3 {\n right: 12.5%;\n }\n .ant-col-xl-offset-3 {\n margin-left: 12.5%;\n }\n .ant-col-xl-order-3 {\n order: 3;\n }\n .ant-col-xl-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n }\n .ant-col-xl-push-2 {\n left: 8.33333333%;\n }\n .ant-col-xl-pull-2 {\n right: 8.33333333%;\n }\n .ant-col-xl-offset-2 {\n margin-left: 8.33333333%;\n }\n .ant-col-xl-order-2 {\n order: 2;\n }\n .ant-col-xl-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n }\n .ant-col-xl-push-1 {\n left: 4.16666667%;\n }\n .ant-col-xl-pull-1 {\n right: 4.16666667%;\n }\n .ant-col-xl-offset-1 {\n margin-left: 4.16666667%;\n }\n .ant-col-xl-order-1 {\n order: 1;\n }\n .ant-col-xl-0 {\n display: none;\n }\n .ant-col-push-0 {\n left: auto;\n }\n .ant-col-pull-0 {\n right: auto;\n }\n .ant-col-xl-push-0 {\n left: auto;\n }\n .ant-col-xl-pull-0 {\n right: auto;\n }\n .ant-col-xl-offset-0 {\n margin-left: 0;\n }\n .ant-col-xl-order-0 {\n order: 0;\n }\n .ant-col-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-xl-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-xl-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-xl-offset-0.ant-col-rtl {\n margin-right: 0;\n }\n .ant-col-xl-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n }\n .ant-col-xl-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n }\n .ant-col-xl-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n }\n .ant-col-xl-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n }\n .ant-col-xl-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n }\n .ant-col-xl-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n }\n .ant-col-xl-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n }\n .ant-col-xl-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n }\n .ant-col-xl-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n }\n .ant-col-xl-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n }\n .ant-col-xl-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n }\n .ant-col-xl-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n }\n .ant-col-xl-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n }\n .ant-col-xl-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n }\n .ant-col-xl-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n }\n .ant-col-xl-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n }\n .ant-col-xl-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n }\n .ant-col-xl-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n }\n .ant-col-xl-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n }\n .ant-col-xl-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n }\n .ant-col-xl-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n }\n .ant-col-xl-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n }\n .ant-col-xl-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n }\n .ant-col-xl-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n }\n .ant-col-xl-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n }\n .ant-col-xl-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n }\n .ant-col-xl-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n }\n .ant-col-xl-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n }\n .ant-col-xl-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n }\n .ant-col-xl-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n }\n .ant-col-xl-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n }\n .ant-col-xl-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n }\n .ant-col-xl-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n }\n .ant-col-xl-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n }\n .ant-col-xl-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n }\n .ant-col-xl-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n }\n .ant-col-xl-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n }\n .ant-col-xl-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n }\n .ant-col-xl-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n }\n .ant-col-xl-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n }\n .ant-col-xl-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n }\n .ant-col-xl-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n }\n .ant-col-xl-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n }\n .ant-col-xl-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n }\n .ant-col-xl-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n }\n .ant-col-xl-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n }\n .ant-col-xl-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n }\n .ant-col-xl-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n }\n .ant-col-xl-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n }\n .ant-col-xl-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n }\n .ant-col-xl-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n }\n .ant-col-xl-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n }\n .ant-col-xl-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n }\n .ant-col-xl-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n }\n .ant-col-xl-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n }\n .ant-col-xl-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n }\n .ant-col-xl-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n }\n .ant-col-xl-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n }\n}\n@media (min-width: 1600px) {\n .ant-col-xxl-24 {\n display: block;\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-xxl-push-24 {\n left: 100%;\n }\n .ant-col-xxl-pull-24 {\n right: 100%;\n }\n .ant-col-xxl-offset-24 {\n margin-left: 100%;\n }\n .ant-col-xxl-order-24 {\n order: 24;\n }\n .ant-col-xxl-23 {\n display: block;\n flex: 0 0 95.83333333%;\n max-width: 95.83333333%;\n }\n .ant-col-xxl-push-23 {\n left: 95.83333333%;\n }\n .ant-col-xxl-pull-23 {\n right: 95.83333333%;\n }\n .ant-col-xxl-offset-23 {\n margin-left: 95.83333333%;\n }\n .ant-col-xxl-order-23 {\n order: 23;\n }\n .ant-col-xxl-22 {\n display: block;\n flex: 0 0 91.66666667%;\n max-width: 91.66666667%;\n }\n .ant-col-xxl-push-22 {\n left: 91.66666667%;\n }\n .ant-col-xxl-pull-22 {\n right: 91.66666667%;\n }\n .ant-col-xxl-offset-22 {\n margin-left: 91.66666667%;\n }\n .ant-col-xxl-order-22 {\n order: 22;\n }\n .ant-col-xxl-21 {\n display: block;\n flex: 0 0 87.5%;\n max-width: 87.5%;\n }\n .ant-col-xxl-push-21 {\n left: 87.5%;\n }\n .ant-col-xxl-pull-21 {\n right: 87.5%;\n }\n .ant-col-xxl-offset-21 {\n margin-left: 87.5%;\n }\n .ant-col-xxl-order-21 {\n order: 21;\n }\n .ant-col-xxl-20 {\n display: block;\n flex: 0 0 83.33333333%;\n max-width: 83.33333333%;\n }\n .ant-col-xxl-push-20 {\n left: 83.33333333%;\n }\n .ant-col-xxl-pull-20 {\n right: 83.33333333%;\n }\n .ant-col-xxl-offset-20 {\n margin-left: 83.33333333%;\n }\n .ant-col-xxl-order-20 {\n order: 20;\n }\n .ant-col-xxl-19 {\n display: block;\n flex: 0 0 79.16666667%;\n max-width: 79.16666667%;\n }\n .ant-col-xxl-push-19 {\n left: 79.16666667%;\n }\n .ant-col-xxl-pull-19 {\n right: 79.16666667%;\n }\n .ant-col-xxl-offset-19 {\n margin-left: 79.16666667%;\n }\n .ant-col-xxl-order-19 {\n order: 19;\n }\n .ant-col-xxl-18 {\n display: block;\n flex: 0 0 75%;\n max-width: 75%;\n }\n .ant-col-xxl-push-18 {\n left: 75%;\n }\n .ant-col-xxl-pull-18 {\n right: 75%;\n }\n .ant-col-xxl-offset-18 {\n margin-left: 75%;\n }\n .ant-col-xxl-order-18 {\n order: 18;\n }\n .ant-col-xxl-17 {\n display: block;\n flex: 0 0 70.83333333%;\n max-width: 70.83333333%;\n }\n .ant-col-xxl-push-17 {\n left: 70.83333333%;\n }\n .ant-col-xxl-pull-17 {\n right: 70.83333333%;\n }\n .ant-col-xxl-offset-17 {\n margin-left: 70.83333333%;\n }\n .ant-col-xxl-order-17 {\n order: 17;\n }\n .ant-col-xxl-16 {\n display: block;\n flex: 0 0 66.66666667%;\n max-width: 66.66666667%;\n }\n .ant-col-xxl-push-16 {\n left: 66.66666667%;\n }\n .ant-col-xxl-pull-16 {\n right: 66.66666667%;\n }\n .ant-col-xxl-offset-16 {\n margin-left: 66.66666667%;\n }\n .ant-col-xxl-order-16 {\n order: 16;\n }\n .ant-col-xxl-15 {\n display: block;\n flex: 0 0 62.5%;\n max-width: 62.5%;\n }\n .ant-col-xxl-push-15 {\n left: 62.5%;\n }\n .ant-col-xxl-pull-15 {\n right: 62.5%;\n }\n .ant-col-xxl-offset-15 {\n margin-left: 62.5%;\n }\n .ant-col-xxl-order-15 {\n order: 15;\n }\n .ant-col-xxl-14 {\n display: block;\n flex: 0 0 58.33333333%;\n max-width: 58.33333333%;\n }\n .ant-col-xxl-push-14 {\n left: 58.33333333%;\n }\n .ant-col-xxl-pull-14 {\n right: 58.33333333%;\n }\n .ant-col-xxl-offset-14 {\n margin-left: 58.33333333%;\n }\n .ant-col-xxl-order-14 {\n order: 14;\n }\n .ant-col-xxl-13 {\n display: block;\n flex: 0 0 54.16666667%;\n max-width: 54.16666667%;\n }\n .ant-col-xxl-push-13 {\n left: 54.16666667%;\n }\n .ant-col-xxl-pull-13 {\n right: 54.16666667%;\n }\n .ant-col-xxl-offset-13 {\n margin-left: 54.16666667%;\n }\n .ant-col-xxl-order-13 {\n order: 13;\n }\n .ant-col-xxl-12 {\n display: block;\n flex: 0 0 50%;\n max-width: 50%;\n }\n .ant-col-xxl-push-12 {\n left: 50%;\n }\n .ant-col-xxl-pull-12 {\n right: 50%;\n }\n .ant-col-xxl-offset-12 {\n margin-left: 50%;\n }\n .ant-col-xxl-order-12 {\n order: 12;\n }\n .ant-col-xxl-11 {\n display: block;\n flex: 0 0 45.83333333%;\n max-width: 45.83333333%;\n }\n .ant-col-xxl-push-11 {\n left: 45.83333333%;\n }\n .ant-col-xxl-pull-11 {\n right: 45.83333333%;\n }\n .ant-col-xxl-offset-11 {\n margin-left: 45.83333333%;\n }\n .ant-col-xxl-order-11 {\n order: 11;\n }\n .ant-col-xxl-10 {\n display: block;\n flex: 0 0 41.66666667%;\n max-width: 41.66666667%;\n }\n .ant-col-xxl-push-10 {\n left: 41.66666667%;\n }\n .ant-col-xxl-pull-10 {\n right: 41.66666667%;\n }\n .ant-col-xxl-offset-10 {\n margin-left: 41.66666667%;\n }\n .ant-col-xxl-order-10 {\n order: 10;\n }\n .ant-col-xxl-9 {\n display: block;\n flex: 0 0 37.5%;\n max-width: 37.5%;\n }\n .ant-col-xxl-push-9 {\n left: 37.5%;\n }\n .ant-col-xxl-pull-9 {\n right: 37.5%;\n }\n .ant-col-xxl-offset-9 {\n margin-left: 37.5%;\n }\n .ant-col-xxl-order-9 {\n order: 9;\n }\n .ant-col-xxl-8 {\n display: block;\n flex: 0 0 33.33333333%;\n max-width: 33.33333333%;\n }\n .ant-col-xxl-push-8 {\n left: 33.33333333%;\n }\n .ant-col-xxl-pull-8 {\n right: 33.33333333%;\n }\n .ant-col-xxl-offset-8 {\n margin-left: 33.33333333%;\n }\n .ant-col-xxl-order-8 {\n order: 8;\n }\n .ant-col-xxl-7 {\n display: block;\n flex: 0 0 29.16666667%;\n max-width: 29.16666667%;\n }\n .ant-col-xxl-push-7 {\n left: 29.16666667%;\n }\n .ant-col-xxl-pull-7 {\n right: 29.16666667%;\n }\n .ant-col-xxl-offset-7 {\n margin-left: 29.16666667%;\n }\n .ant-col-xxl-order-7 {\n order: 7;\n }\n .ant-col-xxl-6 {\n display: block;\n flex: 0 0 25%;\n max-width: 25%;\n }\n .ant-col-xxl-push-6 {\n left: 25%;\n }\n .ant-col-xxl-pull-6 {\n right: 25%;\n }\n .ant-col-xxl-offset-6 {\n margin-left: 25%;\n }\n .ant-col-xxl-order-6 {\n order: 6;\n }\n .ant-col-xxl-5 {\n display: block;\n flex: 0 0 20.83333333%;\n max-width: 20.83333333%;\n }\n .ant-col-xxl-push-5 {\n left: 20.83333333%;\n }\n .ant-col-xxl-pull-5 {\n right: 20.83333333%;\n }\n .ant-col-xxl-offset-5 {\n margin-left: 20.83333333%;\n }\n .ant-col-xxl-order-5 {\n order: 5;\n }\n .ant-col-xxl-4 {\n display: block;\n flex: 0 0 16.66666667%;\n max-width: 16.66666667%;\n }\n .ant-col-xxl-push-4 {\n left: 16.66666667%;\n }\n .ant-col-xxl-pull-4 {\n right: 16.66666667%;\n }\n .ant-col-xxl-offset-4 {\n margin-left: 16.66666667%;\n }\n .ant-col-xxl-order-4 {\n order: 4;\n }\n .ant-col-xxl-3 {\n display: block;\n flex: 0 0 12.5%;\n max-width: 12.5%;\n }\n .ant-col-xxl-push-3 {\n left: 12.5%;\n }\n .ant-col-xxl-pull-3 {\n right: 12.5%;\n }\n .ant-col-xxl-offset-3 {\n margin-left: 12.5%;\n }\n .ant-col-xxl-order-3 {\n order: 3;\n }\n .ant-col-xxl-2 {\n display: block;\n flex: 0 0 8.33333333%;\n max-width: 8.33333333%;\n }\n .ant-col-xxl-push-2 {\n left: 8.33333333%;\n }\n .ant-col-xxl-pull-2 {\n right: 8.33333333%;\n }\n .ant-col-xxl-offset-2 {\n margin-left: 8.33333333%;\n }\n .ant-col-xxl-order-2 {\n order: 2;\n }\n .ant-col-xxl-1 {\n display: block;\n flex: 0 0 4.16666667%;\n max-width: 4.16666667%;\n }\n .ant-col-xxl-push-1 {\n left: 4.16666667%;\n }\n .ant-col-xxl-pull-1 {\n right: 4.16666667%;\n }\n .ant-col-xxl-offset-1 {\n margin-left: 4.16666667%;\n }\n .ant-col-xxl-order-1 {\n order: 1;\n }\n .ant-col-xxl-0 {\n display: none;\n }\n .ant-col-push-0 {\n left: auto;\n }\n .ant-col-pull-0 {\n right: auto;\n }\n .ant-col-xxl-push-0 {\n left: auto;\n }\n .ant-col-xxl-pull-0 {\n right: auto;\n }\n .ant-col-xxl-offset-0 {\n margin-left: 0;\n }\n .ant-col-xxl-order-0 {\n order: 0;\n }\n .ant-col-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-xxl-push-0.ant-col-rtl {\n right: auto;\n }\n .ant-col-xxl-pull-0.ant-col-rtl {\n left: auto;\n }\n .ant-col-xxl-offset-0.ant-col-rtl {\n margin-right: 0;\n }\n .ant-col-xxl-push-1.ant-col-rtl {\n right: 4.16666667%;\n left: auto;\n }\n .ant-col-xxl-pull-1.ant-col-rtl {\n right: auto;\n left: 4.16666667%;\n }\n .ant-col-xxl-offset-1.ant-col-rtl {\n margin-right: 4.16666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-2.ant-col-rtl {\n right: 8.33333333%;\n left: auto;\n }\n .ant-col-xxl-pull-2.ant-col-rtl {\n right: auto;\n left: 8.33333333%;\n }\n .ant-col-xxl-offset-2.ant-col-rtl {\n margin-right: 8.33333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-3.ant-col-rtl {\n right: 12.5%;\n left: auto;\n }\n .ant-col-xxl-pull-3.ant-col-rtl {\n right: auto;\n left: 12.5%;\n }\n .ant-col-xxl-offset-3.ant-col-rtl {\n margin-right: 12.5%;\n margin-left: 0;\n }\n .ant-col-xxl-push-4.ant-col-rtl {\n right: 16.66666667%;\n left: auto;\n }\n .ant-col-xxl-pull-4.ant-col-rtl {\n right: auto;\n left: 16.66666667%;\n }\n .ant-col-xxl-offset-4.ant-col-rtl {\n margin-right: 16.66666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-5.ant-col-rtl {\n right: 20.83333333%;\n left: auto;\n }\n .ant-col-xxl-pull-5.ant-col-rtl {\n right: auto;\n left: 20.83333333%;\n }\n .ant-col-xxl-offset-5.ant-col-rtl {\n margin-right: 20.83333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-6.ant-col-rtl {\n right: 25%;\n left: auto;\n }\n .ant-col-xxl-pull-6.ant-col-rtl {\n right: auto;\n left: 25%;\n }\n .ant-col-xxl-offset-6.ant-col-rtl {\n margin-right: 25%;\n margin-left: 0;\n }\n .ant-col-xxl-push-7.ant-col-rtl {\n right: 29.16666667%;\n left: auto;\n }\n .ant-col-xxl-pull-7.ant-col-rtl {\n right: auto;\n left: 29.16666667%;\n }\n .ant-col-xxl-offset-7.ant-col-rtl {\n margin-right: 29.16666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-8.ant-col-rtl {\n right: 33.33333333%;\n left: auto;\n }\n .ant-col-xxl-pull-8.ant-col-rtl {\n right: auto;\n left: 33.33333333%;\n }\n .ant-col-xxl-offset-8.ant-col-rtl {\n margin-right: 33.33333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-9.ant-col-rtl {\n right: 37.5%;\n left: auto;\n }\n .ant-col-xxl-pull-9.ant-col-rtl {\n right: auto;\n left: 37.5%;\n }\n .ant-col-xxl-offset-9.ant-col-rtl {\n margin-right: 37.5%;\n margin-left: 0;\n }\n .ant-col-xxl-push-10.ant-col-rtl {\n right: 41.66666667%;\n left: auto;\n }\n .ant-col-xxl-pull-10.ant-col-rtl {\n right: auto;\n left: 41.66666667%;\n }\n .ant-col-xxl-offset-10.ant-col-rtl {\n margin-right: 41.66666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-11.ant-col-rtl {\n right: 45.83333333%;\n left: auto;\n }\n .ant-col-xxl-pull-11.ant-col-rtl {\n right: auto;\n left: 45.83333333%;\n }\n .ant-col-xxl-offset-11.ant-col-rtl {\n margin-right: 45.83333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-12.ant-col-rtl {\n right: 50%;\n left: auto;\n }\n .ant-col-xxl-pull-12.ant-col-rtl {\n right: auto;\n left: 50%;\n }\n .ant-col-xxl-offset-12.ant-col-rtl {\n margin-right: 50%;\n margin-left: 0;\n }\n .ant-col-xxl-push-13.ant-col-rtl {\n right: 54.16666667%;\n left: auto;\n }\n .ant-col-xxl-pull-13.ant-col-rtl {\n right: auto;\n left: 54.16666667%;\n }\n .ant-col-xxl-offset-13.ant-col-rtl {\n margin-right: 54.16666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-14.ant-col-rtl {\n right: 58.33333333%;\n left: auto;\n }\n .ant-col-xxl-pull-14.ant-col-rtl {\n right: auto;\n left: 58.33333333%;\n }\n .ant-col-xxl-offset-14.ant-col-rtl {\n margin-right: 58.33333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-15.ant-col-rtl {\n right: 62.5%;\n left: auto;\n }\n .ant-col-xxl-pull-15.ant-col-rtl {\n right: auto;\n left: 62.5%;\n }\n .ant-col-xxl-offset-15.ant-col-rtl {\n margin-right: 62.5%;\n margin-left: 0;\n }\n .ant-col-xxl-push-16.ant-col-rtl {\n right: 66.66666667%;\n left: auto;\n }\n .ant-col-xxl-pull-16.ant-col-rtl {\n right: auto;\n left: 66.66666667%;\n }\n .ant-col-xxl-offset-16.ant-col-rtl {\n margin-right: 66.66666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-17.ant-col-rtl {\n right: 70.83333333%;\n left: auto;\n }\n .ant-col-xxl-pull-17.ant-col-rtl {\n right: auto;\n left: 70.83333333%;\n }\n .ant-col-xxl-offset-17.ant-col-rtl {\n margin-right: 70.83333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-18.ant-col-rtl {\n right: 75%;\n left: auto;\n }\n .ant-col-xxl-pull-18.ant-col-rtl {\n right: auto;\n left: 75%;\n }\n .ant-col-xxl-offset-18.ant-col-rtl {\n margin-right: 75%;\n margin-left: 0;\n }\n .ant-col-xxl-push-19.ant-col-rtl {\n right: 79.16666667%;\n left: auto;\n }\n .ant-col-xxl-pull-19.ant-col-rtl {\n right: auto;\n left: 79.16666667%;\n }\n .ant-col-xxl-offset-19.ant-col-rtl {\n margin-right: 79.16666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-20.ant-col-rtl {\n right: 83.33333333%;\n left: auto;\n }\n .ant-col-xxl-pull-20.ant-col-rtl {\n right: auto;\n left: 83.33333333%;\n }\n .ant-col-xxl-offset-20.ant-col-rtl {\n margin-right: 83.33333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-21.ant-col-rtl {\n right: 87.5%;\n left: auto;\n }\n .ant-col-xxl-pull-21.ant-col-rtl {\n right: auto;\n left: 87.5%;\n }\n .ant-col-xxl-offset-21.ant-col-rtl {\n margin-right: 87.5%;\n margin-left: 0;\n }\n .ant-col-xxl-push-22.ant-col-rtl {\n right: 91.66666667%;\n left: auto;\n }\n .ant-col-xxl-pull-22.ant-col-rtl {\n right: auto;\n left: 91.66666667%;\n }\n .ant-col-xxl-offset-22.ant-col-rtl {\n margin-right: 91.66666667%;\n margin-left: 0;\n }\n .ant-col-xxl-push-23.ant-col-rtl {\n right: 95.83333333%;\n left: auto;\n }\n .ant-col-xxl-pull-23.ant-col-rtl {\n right: auto;\n left: 95.83333333%;\n }\n .ant-col-xxl-offset-23.ant-col-rtl {\n margin-right: 95.83333333%;\n margin-left: 0;\n }\n .ant-col-xxl-push-24.ant-col-rtl {\n right: 100%;\n left: auto;\n }\n .ant-col-xxl-pull-24.ant-col-rtl {\n right: auto;\n left: 100%;\n }\n .ant-col-xxl-offset-24.ant-col-rtl {\n margin-right: 100%;\n margin-left: 0;\n }\n}\n.ant-row-rtl {\n direction: rtl;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-collapse {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n background-color: #fafafa;\n border: 1px solid #d9d9d9;\n border-bottom: 0;\n border-radius: 2px;\n}\n.ant-collapse > .ant-collapse-item {\n border-bottom: 1px solid #d9d9d9;\n}\n.ant-collapse > .ant-collapse-item:last-child,\n.ant-collapse > .ant-collapse-item:last-child > .ant-collapse-header {\n border-radius: 0 0 2px 2px;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header {\n position: relative;\n display: flex;\n flex-wrap: nowrap;\n align-items: flex-start;\n padding: 12px 16px;\n color: rgba(0, 0, 0, 0.85);\n line-height: 1.5715;\n cursor: pointer;\n transition: all 0.3s, visibility 0s;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow {\n display: inline-block;\n margin-right: 12px;\n font-size: 12px;\n vertical-align: -1px;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow svg {\n transition: transform 0.24s;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-header-text {\n flex: auto;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-extra {\n margin-left: auto;\n}\n.ant-collapse > .ant-collapse-item > .ant-collapse-header:focus {\n outline: none;\n}\n.ant-collapse > .ant-collapse-item .ant-collapse-header-collapsible-only {\n cursor: default;\n}\n.ant-collapse > .ant-collapse-item .ant-collapse-header-collapsible-only .ant-collapse-header-text {\n flex: none;\n cursor: pointer;\n}\n.ant-collapse > .ant-collapse-item .ant-collapse-icon-collapsible-only {\n cursor: default;\n}\n.ant-collapse > .ant-collapse-item .ant-collapse-icon-collapsible-only .ant-collapse-expand-icon {\n cursor: pointer;\n}\n.ant-collapse > .ant-collapse-item.ant-collapse-no-arrow > .ant-collapse-header {\n padding-left: 12px;\n}\n.ant-collapse-icon-position-end > .ant-collapse-item > .ant-collapse-header {\n position: relative;\n padding: 12px 16px;\n padding-right: 40px;\n}\n.ant-collapse-icon-position-end > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow {\n position: absolute;\n top: 50%;\n right: 16px;\n left: auto;\n margin: 0;\n transform: translateY(-50%);\n}\n.ant-collapse-content {\n color: rgba(0, 0, 0, 0.85);\n background-color: #fff;\n border-top: 1px solid #d9d9d9;\n}\n.ant-collapse-content > .ant-collapse-content-box {\n padding: 16px;\n}\n.ant-collapse-content-hidden {\n display: none;\n}\n.ant-collapse-item:last-child > .ant-collapse-content {\n border-radius: 0 0 2px 2px;\n}\n.ant-collapse-borderless {\n background-color: #fafafa;\n border: 0;\n}\n.ant-collapse-borderless > .ant-collapse-item {\n border-bottom: 1px solid #d9d9d9;\n}\n.ant-collapse-borderless > .ant-collapse-item:last-child,\n.ant-collapse-borderless > .ant-collapse-item:last-child .ant-collapse-header {\n border-radius: 0;\n}\n.ant-collapse-borderless > .ant-collapse-item:last-child {\n border-bottom: 0;\n}\n.ant-collapse-borderless > .ant-collapse-item > .ant-collapse-content {\n background-color: transparent;\n border-top: 0;\n}\n.ant-collapse-borderless > .ant-collapse-item > .ant-collapse-content > .ant-collapse-content-box {\n padding-top: 4px;\n}\n.ant-collapse-ghost {\n background-color: transparent;\n border: 0;\n}\n.ant-collapse-ghost > .ant-collapse-item {\n border-bottom: 0;\n}\n.ant-collapse-ghost > .ant-collapse-item > .ant-collapse-content {\n background-color: transparent;\n border-top: 0;\n}\n.ant-collapse-ghost > .ant-collapse-item > .ant-collapse-content > .ant-collapse-content-box {\n padding-top: 12px;\n padding-bottom: 12px;\n}\n.ant-collapse .ant-collapse-item-disabled > .ant-collapse-header,\n.ant-collapse .ant-collapse-item-disabled > .ant-collapse-header > .arrow {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-collapse-rtl {\n direction: rtl;\n}\n.ant-collapse-rtl.ant-collapse.ant-collapse-icon-position-end > .ant-collapse-item > .ant-collapse-header {\n position: relative;\n padding: 12px 16px;\n padding-left: 40px;\n}\n.ant-collapse-rtl.ant-collapse.ant-collapse-icon-position-end > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow {\n position: absolute;\n top: 50%;\n right: auto;\n left: 16px;\n margin: 0;\n transform: translateY(-50%);\n}\n.ant-collapse-rtl .ant-collapse > .ant-collapse-item > .ant-collapse-header {\n padding: 12px 16px;\n padding-right: 40px;\n}\n.ant-collapse-rtl.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow {\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-collapse-rtl.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow svg {\n transform: rotate(180deg);\n}\n.ant-collapse-rtl.ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-extra {\n margin-right: auto;\n margin-left: 0;\n}\n.ant-collapse-rtl.ant-collapse > .ant-collapse-item.ant-collapse-no-arrow > .ant-collapse-header {\n padding-right: 12px;\n padding-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-comment {\n position: relative;\n background-color: inherit;\n}\n.ant-comment-inner {\n display: flex;\n padding: 16px 0;\n}\n.ant-comment-avatar {\n position: relative;\n flex-shrink: 0;\n margin-right: 12px;\n cursor: pointer;\n}\n.ant-comment-avatar img {\n width: 32px;\n height: 32px;\n border-radius: 50%;\n}\n.ant-comment-content {\n position: relative;\n flex: 1 1 auto;\n min-width: 1px;\n font-size: 14px;\n word-wrap: break-word;\n}\n.ant-comment-content-author {\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start;\n margin-bottom: 4px;\n font-size: 14px;\n}\n.ant-comment-content-author > a,\n.ant-comment-content-author > span {\n padding-right: 8px;\n font-size: 12px;\n line-height: 18px;\n}\n.ant-comment-content-author-name {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n transition: color 0.3s;\n}\n.ant-comment-content-author-name > * {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-comment-content-author-name > *:hover {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-comment-content-author-time {\n color: #ccc;\n white-space: nowrap;\n cursor: auto;\n}\n.ant-comment-content-detail p {\n margin-bottom: inherit;\n white-space: pre-wrap;\n}\n.ant-comment-actions {\n margin-top: 12px;\n margin-bottom: inherit;\n padding-left: 0;\n}\n.ant-comment-actions > li {\n display: inline-block;\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-comment-actions > li > span {\n margin-right: 10px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 12px;\n cursor: pointer;\n transition: color 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-comment-actions > li > span:hover {\n color: #595959;\n}\n.ant-comment-nested {\n margin-left: 44px;\n}\n.ant-comment-rtl {\n direction: rtl;\n}\n.ant-comment-rtl .ant-comment-avatar {\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-comment-rtl .ant-comment-content-author > a,\n.ant-comment-rtl .ant-comment-content-author > span {\n padding-right: 0;\n padding-left: 8px;\n}\n.ant-comment-rtl .ant-comment-actions {\n padding-right: 0;\n}\n.ant-comment-rtl .ant-comment-actions > li > span {\n margin-right: 0;\n margin-left: 10px;\n}\n.ant-comment-rtl .ant-comment-nested {\n margin-right: 44px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-descriptions-header {\n display: flex;\n align-items: center;\n margin-bottom: 20px;\n}\n.ant-descriptions-title {\n flex: auto;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n font-weight: bold;\n font-size: 16px;\n line-height: 1.5715;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-descriptions-extra {\n margin-left: auto;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n}\n.ant-descriptions-view {\n width: 100%;\n border-radius: 2px;\n}\n.ant-descriptions-view table {\n width: 100%;\n table-layout: fixed;\n}\n.ant-descriptions-row > th,\n.ant-descriptions-row > td {\n padding-bottom: 16px;\n}\n.ant-descriptions-row:last-child {\n border-bottom: none;\n}\n.ant-descriptions-item-label {\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n line-height: 1.5715;\n text-align: start;\n}\n.ant-descriptions-item-label::after {\n content: ':';\n position: relative;\n top: -0.5px;\n margin: 0 8px 0 2px;\n}\n.ant-descriptions-item-label.ant-descriptions-item-no-colon::after {\n content: ' ';\n}\n.ant-descriptions-item-no-label::after {\n margin: 0;\n content: '';\n}\n.ant-descriptions-item-content {\n display: table-cell;\n flex: 1;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n word-break: break-word;\n overflow-wrap: break-word;\n}\n.ant-descriptions-item {\n padding-bottom: 0;\n vertical-align: top;\n}\n.ant-descriptions-item-container {\n display: flex;\n}\n.ant-descriptions-item-container .ant-descriptions-item-label,\n.ant-descriptions-item-container .ant-descriptions-item-content {\n display: inline-flex;\n align-items: baseline;\n}\n.ant-descriptions-middle .ant-descriptions-row > th,\n.ant-descriptions-middle .ant-descriptions-row > td {\n padding-bottom: 12px;\n}\n.ant-descriptions-small .ant-descriptions-row > th,\n.ant-descriptions-small .ant-descriptions-row > td {\n padding-bottom: 8px;\n}\n.ant-descriptions-bordered .ant-descriptions-view {\n border: 1px solid #f0f0f0;\n}\n.ant-descriptions-bordered .ant-descriptions-view > table {\n table-layout: auto;\n border-collapse: collapse;\n}\n.ant-descriptions-bordered .ant-descriptions-item-label,\n.ant-descriptions-bordered .ant-descriptions-item-content {\n padding: 16px 24px;\n border-right: 1px solid #f0f0f0;\n}\n.ant-descriptions-bordered .ant-descriptions-item-label:last-child,\n.ant-descriptions-bordered .ant-descriptions-item-content:last-child {\n border-right: none;\n}\n.ant-descriptions-bordered .ant-descriptions-item-label {\n background-color: #fafafa;\n}\n.ant-descriptions-bordered .ant-descriptions-item-label::after {\n display: none;\n}\n.ant-descriptions-bordered .ant-descriptions-row {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-descriptions-bordered .ant-descriptions-row:last-child {\n border-bottom: none;\n}\n.ant-descriptions-bordered.ant-descriptions-middle .ant-descriptions-item-label,\n.ant-descriptions-bordered.ant-descriptions-middle .ant-descriptions-item-content {\n padding: 12px 24px;\n}\n.ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-label,\n.ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-content {\n padding: 8px 16px;\n}\n.ant-descriptions-rtl {\n direction: rtl;\n}\n.ant-descriptions-rtl .ant-descriptions-item-label::after {\n margin: 0 2px 0 8px;\n}\n.ant-descriptions-rtl.ant-descriptions-bordered .ant-descriptions-item-label,\n.ant-descriptions-rtl.ant-descriptions-bordered .ant-descriptions-item-content {\n border-right: none;\n border-left: 1px solid #f0f0f0;\n}\n.ant-descriptions-rtl.ant-descriptions-bordered .ant-descriptions-item-label:last-child,\n.ant-descriptions-rtl.ant-descriptions-bordered .ant-descriptions-item-content:last-child {\n border-left: none;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-divider {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n border-top: 1px solid rgba(0, 0, 0, 0.06);\n}\n.ant-divider-vertical {\n position: relative;\n top: -0.06em;\n display: inline-block;\n height: 0.9em;\n margin: 0 8px;\n vertical-align: middle;\n border-top: 0;\n border-left: 1px solid rgba(0, 0, 0, 0.06);\n}\n.ant-divider-horizontal {\n display: flex;\n clear: both;\n width: 100%;\n min-width: 100%;\n margin: 24px 0;\n}\n.ant-divider-horizontal.ant-divider-with-text {\n display: flex;\n margin: 16px 0;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n white-space: nowrap;\n text-align: center;\n border-top: 0;\n border-top-color: rgba(0, 0, 0, 0.06);\n}\n.ant-divider-horizontal.ant-divider-with-text::before,\n.ant-divider-horizontal.ant-divider-with-text::after {\n position: relative;\n top: 50%;\n width: 50%;\n border-top: 1px solid transparent;\n border-top-color: inherit;\n border-bottom: 0;\n transform: translateY(50%);\n content: '';\n}\n.ant-divider-horizontal.ant-divider-with-text-left::before {\n top: 50%;\n width: 5%;\n}\n.ant-divider-horizontal.ant-divider-with-text-left::after {\n top: 50%;\n width: 95%;\n}\n.ant-divider-horizontal.ant-divider-with-text-right::before {\n top: 50%;\n width: 95%;\n}\n.ant-divider-horizontal.ant-divider-with-text-right::after {\n top: 50%;\n width: 5%;\n}\n.ant-divider-inner-text {\n display: inline-block;\n padding: 0 1em;\n}\n.ant-divider-dashed {\n background: none;\n border-color: rgba(0, 0, 0, 0.06);\n border-style: dashed;\n border-width: 1px 0 0;\n}\n.ant-divider-horizontal.ant-divider-with-text.ant-divider-dashed::before,\n.ant-divider-horizontal.ant-divider-with-text.ant-divider-dashed::after {\n border-style: dashed none none;\n}\n.ant-divider-vertical.ant-divider-dashed {\n border-width: 0 0 0 1px;\n}\n.ant-divider-plain.ant-divider-with-text {\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n}\n.ant-divider-horizontal.ant-divider-with-text-left.ant-divider-no-default-orientation-margin-left::before {\n width: 0;\n}\n.ant-divider-horizontal.ant-divider-with-text-left.ant-divider-no-default-orientation-margin-left::after {\n width: 100%;\n}\n.ant-divider-horizontal.ant-divider-with-text-left.ant-divider-no-default-orientation-margin-left .ant-divider-inner-text {\n padding-left: 0;\n}\n.ant-divider-horizontal.ant-divider-with-text-right.ant-divider-no-default-orientation-margin-right::before {\n width: 100%;\n}\n.ant-divider-horizontal.ant-divider-with-text-right.ant-divider-no-default-orientation-margin-right::after {\n width: 0;\n}\n.ant-divider-horizontal.ant-divider-with-text-right.ant-divider-no-default-orientation-margin-right .ant-divider-inner-text {\n padding-right: 0;\n}\n.ant-divider-rtl {\n direction: rtl;\n}\n.ant-divider-rtl.ant-divider-horizontal.ant-divider-with-text-left::before {\n width: 95%;\n}\n.ant-divider-rtl.ant-divider-horizontal.ant-divider-with-text-left::after {\n width: 5%;\n}\n.ant-divider-rtl.ant-divider-horizontal.ant-divider-with-text-right::before {\n width: 5%;\n}\n.ant-divider-rtl.ant-divider-horizontal.ant-divider-with-text-right::after {\n width: 95%;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-drawer {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1000;\n pointer-events: none;\n}\n.ant-drawer-inline {\n position: absolute;\n}\n.ant-drawer-mask {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1000;\n background: rgba(0, 0, 0, 0.45);\n pointer-events: auto;\n}\n.ant-drawer-content-wrapper {\n position: absolute;\n z-index: 1000;\n transition: all 0.3s;\n}\n.ant-drawer-content-wrapper-hidden {\n display: none;\n}\n.ant-drawer-left > .ant-drawer-content-wrapper {\n top: 0;\n bottom: 0;\n left: 0;\n box-shadow: 6px 0 16px -8px rgba(0, 0, 0, 0.08), 9px 0 28px 0 rgba(0, 0, 0, 0.05), 12px 0 48px 16px rgba(0, 0, 0, 0.03);\n}\n.ant-drawer-right > .ant-drawer-content-wrapper {\n top: 0;\n right: 0;\n bottom: 0;\n box-shadow: -6px 0 16px -8px rgba(0, 0, 0, 0.08), -9px 0 28px 0 rgba(0, 0, 0, 0.05), -12px 0 48px 16px rgba(0, 0, 0, 0.03);\n}\n.ant-drawer-top > .ant-drawer-content-wrapper {\n top: 0;\n right: 0;\n left: 0;\n box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08), 0 9px 28px 0 rgba(0, 0, 0, 0.05), 0 12px 48px 16px rgba(0, 0, 0, 0.03);\n}\n.ant-drawer-bottom > .ant-drawer-content-wrapper {\n right: 0;\n bottom: 0;\n left: 0;\n box-shadow: 0 -6px 16px -8px rgba(0, 0, 0, 0.08), 0 -9px 28px 0 rgba(0, 0, 0, 0.05), 0 -12px 48px 16px rgba(0, 0, 0, 0.03);\n}\n.ant-drawer-content {\n width: 100%;\n height: 100%;\n overflow: auto;\n background: #fff;\n pointer-events: auto;\n}\n.ant-drawer-wrapper-body {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n}\n.ant-drawer-header {\n display: flex;\n flex: 0;\n align-items: center;\n padding: 16px 24px;\n font-size: 16px;\n line-height: 22px;\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-drawer-header-title {\n display: flex;\n flex: 1;\n align-items: center;\n min-width: 0;\n min-height: 0;\n}\n.ant-drawer-extra {\n flex: none;\n}\n.ant-drawer-close {\n display: inline-block;\n margin-right: 12px;\n color: rgba(0, 0, 0, 0.45);\n font-weight: 700;\n font-size: 16px;\n font-style: normal;\n line-height: 1;\n text-align: center;\n text-transform: none;\n text-decoration: none;\n background: transparent;\n border: 0;\n outline: 0;\n cursor: pointer;\n transition: color 0.3s;\n text-rendering: auto;\n}\n.ant-drawer-close:focus,\n.ant-drawer-close:hover {\n color: rgba(0, 0, 0, 0.75);\n text-decoration: none;\n}\n.ant-drawer-title {\n flex: 1;\n margin: 0;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n line-height: 22px;\n}\n.ant-drawer-body {\n flex: 1;\n min-width: 0;\n min-height: 0;\n padding: 24px;\n overflow: auto;\n}\n.ant-drawer-footer {\n flex-shrink: 0;\n padding: 10px 16px;\n border-top: 1px solid #f0f0f0;\n}\n.panel-motion-enter-start,\n.panel-motion-appear-start,\n.panel-motion-leave-start {\n transition: none;\n}\n.panel-motion-enter-active,\n.panel-motion-appear-active,\n.panel-motion-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-mask-motion-enter-active,\n.ant-drawer-mask-motion-appear-active,\n.ant-drawer-mask-motion-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-mask-motion-enter,\n.ant-drawer-mask-motion-appear {\n opacity: 0;\n}\n.ant-drawer-mask-motion-enter-active,\n.ant-drawer-mask-motion-appear-active {\n opacity: 1;\n}\n.ant-drawer-mask-motion-leave {\n opacity: 1;\n}\n.ant-drawer-mask-motion-leave-active {\n opacity: 0;\n}\n.ant-drawer-panel-motion-left-enter-start,\n.ant-drawer-panel-motion-left-appear-start,\n.ant-drawer-panel-motion-left-leave-start {\n transition: none;\n}\n.ant-drawer-panel-motion-left-enter-active,\n.ant-drawer-panel-motion-left-appear-active,\n.ant-drawer-panel-motion-left-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-panel-motion-left-enter-start,\n.ant-drawer-panel-motion-left-appear-start {\n transform: translateX(-100%) !important;\n}\n.ant-drawer-panel-motion-left-enter-active,\n.ant-drawer-panel-motion-left-appear-active {\n transform: translateX(0);\n}\n.ant-drawer-panel-motion-left-leave {\n transform: translateX(0);\n}\n.ant-drawer-panel-motion-left-leave-active {\n transform: translateX(-100%);\n}\n.ant-drawer-panel-motion-right-enter-start,\n.ant-drawer-panel-motion-right-appear-start,\n.ant-drawer-panel-motion-right-leave-start {\n transition: none;\n}\n.ant-drawer-panel-motion-right-enter-active,\n.ant-drawer-panel-motion-right-appear-active,\n.ant-drawer-panel-motion-right-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-panel-motion-right-enter-start,\n.ant-drawer-panel-motion-right-appear-start {\n transform: translateX(100%) !important;\n}\n.ant-drawer-panel-motion-right-enter-active,\n.ant-drawer-panel-motion-right-appear-active {\n transform: translateX(0);\n}\n.ant-drawer-panel-motion-right-leave {\n transform: translateX(0);\n}\n.ant-drawer-panel-motion-right-leave-active {\n transform: translateX(100%);\n}\n.ant-drawer-panel-motion-top-enter-start,\n.ant-drawer-panel-motion-top-appear-start,\n.ant-drawer-panel-motion-top-leave-start {\n transition: none;\n}\n.ant-drawer-panel-motion-top-enter-active,\n.ant-drawer-panel-motion-top-appear-active,\n.ant-drawer-panel-motion-top-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-panel-motion-top-enter-start,\n.ant-drawer-panel-motion-top-appear-start {\n transform: translateY(-100%) !important;\n}\n.ant-drawer-panel-motion-top-enter-active,\n.ant-drawer-panel-motion-top-appear-active {\n transform: translateY(0);\n}\n.ant-drawer-panel-motion-top-leave {\n transform: translateY(0);\n}\n.ant-drawer-panel-motion-top-leave-active {\n transform: translateY(-100%);\n}\n.ant-drawer-panel-motion-bottom-enter-start,\n.ant-drawer-panel-motion-bottom-appear-start,\n.ant-drawer-panel-motion-bottom-leave-start {\n transition: none;\n}\n.ant-drawer-panel-motion-bottom-enter-active,\n.ant-drawer-panel-motion-bottom-appear-active,\n.ant-drawer-panel-motion-bottom-leave-active {\n transition: all 0.3s;\n}\n.ant-drawer-panel-motion-bottom-enter-start,\n.ant-drawer-panel-motion-bottom-appear-start {\n transform: translateY(100%) !important;\n}\n.ant-drawer-panel-motion-bottom-enter-active,\n.ant-drawer-panel-motion-bottom-appear-active {\n transform: translateY(0);\n}\n.ant-drawer-panel-motion-bottom-leave {\n transform: translateY(0);\n}\n.ant-drawer-panel-motion-bottom-leave-active {\n transform: translateY(100%);\n}\n.ant-drawer-rtl {\n direction: rtl;\n}\n.ant-drawer-rtl .ant-drawer-close {\n margin-right: 0;\n margin-left: 12px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-form-item .ant-input-number + .ant-form-text {\n margin-left: 8px;\n}\n.ant-form-inline {\n display: flex;\n flex-wrap: wrap;\n}\n.ant-form-inline .ant-form-item {\n flex: none;\n flex-wrap: nowrap;\n margin-right: 16px;\n margin-bottom: 0;\n}\n.ant-form-inline .ant-form-item-with-help {\n margin-bottom: 24px;\n}\n.ant-form-inline .ant-form-item > .ant-form-item-label,\n.ant-form-inline .ant-form-item > .ant-form-item-control {\n display: inline-block;\n vertical-align: top;\n}\n.ant-form-inline .ant-form-item > .ant-form-item-label {\n flex: none;\n}\n.ant-form-inline .ant-form-item .ant-form-text {\n display: inline-block;\n}\n.ant-form-inline .ant-form-item .ant-form-item-has-feedback {\n display: inline-block;\n}\n.ant-form-horizontal .ant-form-item-label {\n flex-grow: 0;\n}\n.ant-form-horizontal .ant-form-item-control {\n flex: 1 1 0;\n min-width: 0;\n}\n.ant-form-horizontal .ant-form-item-label[class$='-24'] + .ant-form-item-control,\n.ant-form-horizontal .ant-form-item-label[class*='-24 '] + .ant-form-item-control {\n min-width: unset;\n}\n.ant-form-vertical .ant-form-item-row {\n flex-direction: column;\n}\n.ant-form-vertical .ant-form-item-label > label {\n height: auto;\n}\n.ant-form-vertical .ant-form-item .ant-form-item-control {\n width: 100%;\n}\n.ant-form-vertical .ant-form-item-label,\n.ant-col-24.ant-form-item-label,\n.ant-col-xl-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n}\n.ant-form-vertical .ant-form-item-label > label,\n.ant-col-24.ant-form-item-label > label,\n.ant-col-xl-24.ant-form-item-label > label {\n margin: 0;\n}\n.ant-form-vertical .ant-form-item-label > label::after,\n.ant-col-24.ant-form-item-label > label::after,\n.ant-col-xl-24.ant-form-item-label > label::after {\n display: none;\n}\n.ant-form-rtl.ant-form-vertical .ant-form-item-label,\n.ant-form-rtl.ant-col-24.ant-form-item-label,\n.ant-form-rtl.ant-col-xl-24.ant-form-item-label {\n text-align: right;\n}\n@media (max-width: 575px) {\n .ant-form-item .ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-form-item .ant-form-item-label > label {\n margin: 0;\n }\n .ant-form-item .ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-form-item .ant-form-item-label {\n text-align: right;\n }\n .ant-form .ant-form-item {\n flex-wrap: wrap;\n }\n .ant-form .ant-form-item .ant-form-item-label,\n .ant-form .ant-form-item .ant-form-item-control {\n flex: 0 0 100%;\n max-width: 100%;\n }\n .ant-col-xs-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-col-xs-24.ant-form-item-label > label {\n margin: 0;\n }\n .ant-col-xs-24.ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-col-xs-24.ant-form-item-label {\n text-align: right;\n }\n}\n@media (max-width: 767px) {\n .ant-col-sm-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-col-sm-24.ant-form-item-label > label {\n margin: 0;\n }\n .ant-col-sm-24.ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-col-sm-24.ant-form-item-label {\n text-align: right;\n }\n}\n@media (max-width: 991px) {\n .ant-col-md-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-col-md-24.ant-form-item-label > label {\n margin: 0;\n }\n .ant-col-md-24.ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-col-md-24.ant-form-item-label {\n text-align: right;\n }\n}\n@media (max-width: 1199px) {\n .ant-col-lg-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-col-lg-24.ant-form-item-label > label {\n margin: 0;\n }\n .ant-col-lg-24.ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-col-lg-24.ant-form-item-label {\n text-align: right;\n }\n}\n@media (max-width: 1599px) {\n .ant-col-xl-24.ant-form-item-label {\n padding: 0 0 8px;\n line-height: 1.5715;\n white-space: initial;\n text-align: left;\n }\n .ant-col-xl-24.ant-form-item-label > label {\n margin: 0;\n }\n .ant-col-xl-24.ant-form-item-label > label::after {\n display: none;\n }\n .ant-form-rtl.ant-col-xl-24.ant-form-item-label {\n text-align: right;\n }\n}\n.ant-form-item {\n /* Some non-status related component style is in `components.less` */\n /* To support leave along ErrorList. We add additional className to handle explain style */\n}\n.ant-form-item-explain-error {\n color: #ff4d4f;\n}\n.ant-form-item-explain-warning {\n color: #faad14;\n}\n.ant-form-item-has-feedback .ant-switch {\n margin: 2px 0 4px;\n}\n.ant-form-item-has-warning .ant-form-item-split {\n color: #faad14;\n}\n.ant-form-item-has-error .ant-form-item-split {\n color: #ff4d4f;\n}\n.ant-form {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n}\n.ant-form legend {\n display: block;\n width: 100%;\n margin-bottom: 20px;\n padding: 0;\n color: rgba(0, 0, 0, 0.45);\n font-size: 16px;\n line-height: inherit;\n border: 0;\n border-bottom: 1px solid #d9d9d9;\n}\n.ant-form label {\n font-size: 14px;\n}\n.ant-form input[type='search'] {\n box-sizing: border-box;\n}\n.ant-form input[type='radio'],\n.ant-form input[type='checkbox'] {\n line-height: normal;\n}\n.ant-form input[type='file'] {\n display: block;\n}\n.ant-form input[type='range'] {\n display: block;\n width: 100%;\n}\n.ant-form select[multiple],\n.ant-form select[size] {\n height: auto;\n}\n.ant-form input[type='file']:focus,\n.ant-form input[type='radio']:focus,\n.ant-form input[type='checkbox']:focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\n.ant-form output {\n display: block;\n padding-top: 15px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n}\n.ant-form .ant-form-text {\n display: inline-block;\n padding-right: 8px;\n}\n.ant-form-small .ant-form-item-label > label {\n height: 24px;\n}\n.ant-form-small .ant-form-item-control-input {\n min-height: 24px;\n}\n.ant-form-large .ant-form-item-label > label {\n height: 40px;\n}\n.ant-form-large .ant-form-item-control-input {\n min-height: 40px;\n}\n.ant-form-item {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n margin-bottom: 24px;\n vertical-align: top;\n}\n.ant-form-item-with-help {\n transition: none;\n}\n.ant-form-item-hidden,\n.ant-form-item-hidden.ant-row {\n display: none;\n}\n.ant-form-item-label {\n display: inline-block;\n flex-grow: 0;\n overflow: hidden;\n white-space: nowrap;\n text-align: right;\n vertical-align: middle;\n}\n.ant-form-item-label-left {\n text-align: left;\n}\n.ant-form-item-label-wrap {\n overflow: unset;\n line-height: 1.3215em;\n white-space: unset;\n}\n.ant-form-item-label > label {\n position: relative;\n display: inline-flex;\n align-items: center;\n max-width: 100%;\n height: 32px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n}\n.ant-form-item-label > label > .anticon {\n font-size: 14px;\n vertical-align: top;\n}\n.ant-form-item-label > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before {\n display: inline-block;\n margin-right: 4px;\n color: #ff4d4f;\n font-size: 14px;\n font-family: SimSun, sans-serif;\n line-height: 1;\n content: '*';\n}\n.ant-form-hide-required-mark .ant-form-item-label > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before {\n display: none;\n}\n.ant-form-item-label > label .ant-form-item-optional {\n display: inline-block;\n margin-left: 4px;\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-form-hide-required-mark .ant-form-item-label > label .ant-form-item-optional {\n display: none;\n}\n.ant-form-item-label > label .ant-form-item-tooltip {\n color: rgba(0, 0, 0, 0.45);\n cursor: help;\n -ms-writing-mode: lr-tb;\n writing-mode: horizontal-tb;\n -webkit-margin-start: 4px;\n margin-inline-start: 4px;\n}\n.ant-form-item-label > label::after {\n content: ':';\n position: relative;\n top: -0.5px;\n margin: 0 8px 0 2px;\n}\n.ant-form-item-label > label.ant-form-item-no-colon::after {\n content: ' ';\n}\n.ant-form-item-control {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n}\n.ant-form-item-control:first-child:not([class^='ant-col-']):not([class*=' ant-col-']) {\n width: 100%;\n}\n.ant-form-item-control-input {\n position: relative;\n display: flex;\n align-items: center;\n min-height: 32px;\n}\n.ant-form-item-control-input-content {\n flex: auto;\n max-width: 100%;\n}\n.ant-form-item-explain,\n.ant-form-item-extra {\n clear: both;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.5715;\n transition: color 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);\n}\n.ant-form-item-explain-connected {\n width: 100%;\n}\n.ant-form-item-extra {\n min-height: 24px;\n}\n.ant-form-item-with-help .ant-form-item-explain {\n height: auto;\n opacity: 1;\n}\n.ant-form-item-feedback-icon {\n font-size: 14px;\n text-align: center;\n visibility: visible;\n animation: zoomIn 0.3s cubic-bezier(0.12, 0.4, 0.29, 1.46);\n pointer-events: none;\n}\n.ant-form-item-feedback-icon-success {\n color: #52c41a;\n}\n.ant-form-item-feedback-icon-error {\n color: #ff4d4f;\n}\n.ant-form-item-feedback-icon-warning {\n color: #faad14;\n}\n.ant-form-item-feedback-icon-validating {\n color: #1890ff;\n}\n.ant-show-help {\n transition: opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-show-help-appear,\n.ant-show-help-enter {\n opacity: 0;\n}\n.ant-show-help-appear-active,\n.ant-show-help-enter-active {\n opacity: 1;\n}\n.ant-show-help-leave {\n opacity: 1;\n}\n.ant-show-help-leave-active {\n opacity: 0;\n}\n.ant-show-help-item {\n overflow: hidden;\n transition: height 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) !important;\n}\n.ant-show-help-item-appear,\n.ant-show-help-item-enter {\n transform: translateY(-5px);\n opacity: 0;\n}\n.ant-show-help-item-appear-active,\n.ant-show-help-item-enter-active {\n transform: translateY(0);\n opacity: 1;\n}\n.ant-show-help-item-leave {\n transition: height 0.2s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.2s cubic-bezier(0.645, 0.045, 0.355, 1), transform 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) !important;\n}\n.ant-show-help-item-leave-active {\n transform: translateY(-5px);\n}\n@keyframes diffZoomIn1 {\n 0% {\n transform: scale(0);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n opacity: 1;\n }\n}\n@keyframes diffZoomIn2 {\n 0% {\n transform: scale(0);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n opacity: 1;\n }\n}\n@keyframes diffZoomIn3 {\n 0% {\n transform: scale(0);\n opacity: 0;\n }\n 100% {\n transform: scale(1);\n opacity: 1;\n }\n}\n.ant-form-rtl {\n direction: rtl;\n}\n.ant-form-rtl .ant-form-item-label {\n text-align: left;\n}\n.ant-form-rtl .ant-form-item-label > label.ant-form-item-required::before {\n margin-right: 0;\n margin-left: 4px;\n}\n.ant-form-rtl .ant-form-item-label > label::after {\n margin: 0 2px 0 8px;\n}\n.ant-form-rtl .ant-form-item-label > label .ant-form-item-optional {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-col-rtl .ant-form-item-control:first-child {\n width: 100%;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input {\n padding-right: 11px;\n padding-left: 24px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input-affix-wrapper .ant-input-suffix {\n padding-right: 11px;\n padding-left: 18px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input-affix-wrapper .ant-input {\n padding: 0;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input-number-affix-wrapper .ant-input-number {\n padding: 0;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input-search:not(.ant-input-search-enter-button) .ant-input-suffix {\n right: auto;\n left: 28px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-input-number {\n padding-left: 18px;\n}\n.ant-form-rtl .ant-form-item-has-feedback > .ant-select .ant-select-arrow,\n.ant-form-rtl .ant-form-item-has-feedback > .ant-select .ant-select-clear,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-group-addon) > .ant-select .ant-select-arrow,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-group-addon) > .ant-select .ant-select-clear,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-number-group-addon) > .ant-select .ant-select-arrow,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-number-group-addon) > .ant-select .ant-select-clear {\n right: auto;\n left: 32px;\n}\n.ant-form-rtl .ant-form-item-has-feedback > .ant-select .ant-select-selection-selected-value,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-group-addon) > .ant-select .ant-select-selection-selected-value,\n.ant-form-rtl .ant-form-item-has-feedback :not(.ant-input-number-group-addon) > .ant-select .ant-select-selection-selected-value {\n padding-right: 0;\n padding-left: 42px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-cascader-picker-arrow {\n margin-right: 0;\n margin-left: 19px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-cascader-picker-clear {\n right: auto;\n left: 32px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-picker {\n padding-right: 11px;\n padding-left: 29.2px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-picker-large {\n padding-right: 11px;\n padding-left: 29.2px;\n}\n.ant-form-rtl .ant-form-item-has-feedback .ant-picker-small {\n padding-right: 7px;\n padding-left: 25.2px;\n}\n.ant-form-rtl .ant-form-item-has-feedback.ant-form-item-has-success .ant-form-item-children-icon,\n.ant-form-rtl .ant-form-item-has-feedback.ant-form-item-has-warning .ant-form-item-children-icon,\n.ant-form-rtl .ant-form-item-has-feedback.ant-form-item-has-error .ant-form-item-children-icon,\n.ant-form-rtl .ant-form-item-has-feedback.ant-form-item-is-validating .ant-form-item-children-icon {\n right: auto;\n left: 0;\n}\n.ant-form-rtl.ant-form-inline .ant-form-item {\n margin-right: 0;\n margin-left: 16px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-image {\n position: relative;\n display: inline-block;\n}\n.ant-image-img {\n width: 100%;\n height: auto;\n vertical-align: middle;\n}\n.ant-image-img-placeholder {\n background-color: #f5f5f5;\n background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNMTQuNSAyLjVoLTEzQS41LjUgMCAwIDAgMSAzdjEwYS41LjUgMCAwIDAgLjUuNWgxM2EuNS41IDAgMCAwIC41LS41VjNhLjUuNSAwIDAgMC0uNS0uNXpNNS4yODEgNC43NWExIDEgMCAwIDEgMCAyIDEgMSAwIDAgMSAwLTJ6bTguMDMgNi44M2EuMTI3LjEyNyAwIDAgMS0uMDgxLjAzSDIuNzY5YS4xMjUuMTI1IDAgMCAxLS4wOTYtLjIwN2wyLjY2MS0zLjE1NmEuMTI2LjEyNiAwIDAgMSAuMTc3LS4wMTZsLjAxNi4wMTZMNy4wOCAxMC4wOWwyLjQ3LTIuOTNhLjEyNi4xMjYgMCAwIDEgLjE3Ny0uMDE2bC4wMTUuMDE2IDMuNTg4IDQuMjQ0YS4xMjcuMTI3IDAgMCAxLS4wMi4xNzV6IiBmaWxsPSIjOEM4QzhDIiBmaWxsLXJ1bGU9Im5vbnplcm8iLz48L3N2Zz4=');\n background-repeat: no-repeat;\n background-position: center center;\n background-size: 30%;\n}\n.ant-image-mask {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #fff;\n background: rgba(0, 0, 0, 0.5);\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.3s;\n}\n.ant-image-mask-info {\n padding: 0 4px;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-image-mask-info .anticon {\n -webkit-margin-end: 4px;\n margin-inline-end: 4px;\n}\n.ant-image-mask:hover {\n opacity: 1;\n}\n.ant-image-placeholder {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n.ant-image-preview {\n pointer-events: none;\n height: 100%;\n text-align: center;\n}\n.ant-image-preview.ant-zoom-enter,\n.ant-image-preview.ant-zoom-appear {\n transform: none;\n opacity: 0;\n animation-duration: 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-image-preview-mask {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1000;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.45);\n}\n.ant-image-preview-mask-hidden {\n display: none;\n}\n.ant-image-preview-wrap {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n overflow: auto;\n outline: 0;\n}\n.ant-image-preview-body {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n overflow: hidden;\n}\n.ant-image-preview-img {\n max-width: 100%;\n max-height: 100%;\n vertical-align: middle;\n transform: scale3d(1, 1, 1);\n cursor: grab;\n transition: transform 0.3s cubic-bezier(0.215, 0.61, 0.355, 1) 0s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n pointer-events: auto;\n}\n.ant-image-preview-img-wrapper {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n transition: transform 0.3s cubic-bezier(0.215, 0.61, 0.355, 1) 0s;\n}\n.ant-image-preview-img-wrapper::before {\n display: inline-block;\n width: 1px;\n height: 50%;\n margin-right: -1px;\n content: '';\n}\n.ant-image-preview-moving .ant-image-preview-img {\n cursor: grabbing;\n}\n.ant-image-preview-moving .ant-image-preview-img-wrapper {\n transition-duration: 0s;\n}\n.ant-image-preview-wrap {\n z-index: 1080;\n}\n.ant-image-preview-operations-wrapper {\n position: fixed;\n top: 0;\n right: 0;\n z-index: 1081;\n width: 100%;\n}\n.ant-image-preview-operations {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n font-feature-settings: 'tnum';\n display: flex;\n flex-direction: row-reverse;\n align-items: center;\n color: rgba(255, 255, 255, 0.85);\n list-style: none;\n background: rgba(0, 0, 0, 0.1);\n pointer-events: auto;\n}\n.ant-image-preview-operations-operation {\n margin-left: 12px;\n padding: 12px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-image-preview-operations-operation:hover {\n background: rgba(0, 0, 0, 0.2);\n}\n.ant-image-preview-operations-operation-disabled {\n color: rgba(255, 255, 255, 0.25);\n pointer-events: none;\n}\n.ant-image-preview-operations-operation:last-of-type {\n margin-left: 0;\n}\n.ant-image-preview-operations-progress {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n}\n.ant-image-preview-operations-icon {\n font-size: 18px;\n}\n.ant-image-preview-switch-left,\n.ant-image-preview-switch-right {\n position: fixed;\n top: 50%;\n right: 8px;\n z-index: 1081;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 44px;\n height: 44px;\n color: rgba(255, 255, 255, 0.85);\n background: rgba(0, 0, 0, 0.1);\n border-radius: 50%;\n transform: translateY(-50%);\n cursor: pointer;\n transition: all 0.3s;\n pointer-events: auto;\n}\n.ant-image-preview-switch-left:hover,\n.ant-image-preview-switch-right:hover {\n background: rgba(0, 0, 0, 0.2);\n}\n.ant-image-preview-switch-left-disabled,\n.ant-image-preview-switch-right-disabled,\n.ant-image-preview-switch-left-disabled:hover,\n.ant-image-preview-switch-right-disabled:hover {\n color: rgba(255, 255, 255, 0.25);\n background: rgba(0, 0, 0, 0.1);\n cursor: not-allowed;\n}\n.ant-image-preview-switch-left-disabled > .anticon,\n.ant-image-preview-switch-right-disabled > .anticon,\n.ant-image-preview-switch-left-disabled:hover > .anticon,\n.ant-image-preview-switch-right-disabled:hover > .anticon {\n cursor: not-allowed;\n}\n.ant-image-preview-switch-left > .anticon,\n.ant-image-preview-switch-right > .anticon {\n font-size: 18px;\n}\n.ant-image-preview-switch-left {\n left: 8px;\n}\n.ant-image-preview-switch-right {\n right: 8px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-input-number-affix-wrapper {\n display: inline-block;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n position: relative;\n display: inline-flex;\n width: 90px;\n padding: 0;\n -webkit-padding-start: 11px;\n padding-inline-start: 11px;\n}\n.ant-input-number-affix-wrapper::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-input-number-affix-wrapper:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number-affix-wrapper::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number-affix-wrapper:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number-affix-wrapper:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-input-number-affix-wrapper:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number-affix-wrapper:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-input-number-affix-wrapper:focus,\n.ant-input-number-affix-wrapper-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-affix-wrapper-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-number-affix-wrapper-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-number-affix-wrapper[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-number-affix-wrapper[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-number-affix-wrapper-borderless,\n.ant-input-number-affix-wrapper-borderless:hover,\n.ant-input-number-affix-wrapper-borderless:focus,\n.ant-input-number-affix-wrapper-borderless-focused,\n.ant-input-number-affix-wrapper-borderless-disabled,\n.ant-input-number-affix-wrapper-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-input-number-affix-wrapper {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-input-number-affix-wrapper-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-number-affix-wrapper-sm {\n padding: 0px 7px;\n}\n.ant-input-number-affix-wrapper:not(.ant-input-number-affix-wrapper-disabled):hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n z-index: 1;\n}\n.ant-input-number-affix-wrapper-focused,\n.ant-input-number-affix-wrapper:focus {\n z-index: 1;\n}\n.ant-input-number-affix-wrapper-disabled .ant-input-number[disabled] {\n background: transparent;\n}\n.ant-input-number-affix-wrapper > div.ant-input-number {\n width: 100%;\n border: none;\n outline: none;\n}\n.ant-input-number-affix-wrapper > div.ant-input-number.ant-input-number-focused {\n box-shadow: none !important;\n}\n.ant-input-number-affix-wrapper input.ant-input-number-input {\n padding: 0;\n}\n.ant-input-number-affix-wrapper::before {\n width: 0;\n visibility: hidden;\n content: '\\a0';\n}\n.ant-input-number-affix-wrapper .ant-input-number-handler-wrap {\n z-index: 2;\n}\n.ant-input-number-prefix,\n.ant-input-number-suffix {\n display: flex;\n flex: none;\n align-items: center;\n pointer-events: none;\n}\n.ant-input-number-prefix {\n -webkit-margin-end: 4px;\n margin-inline-end: 4px;\n}\n.ant-input-number-suffix {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 1;\n height: 100%;\n margin-right: 11px;\n margin-left: 4px;\n}\n.ant-input-number-group-wrapper .ant-input-number-affix-wrapper {\n width: 100%;\n}\n.ant-input-number-status-error:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number,\n.ant-input-number-status-error:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number:hover {\n background: #fff;\n border-color: #ff4d4f;\n}\n.ant-input-number-status-error:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number:focus,\n.ant-input-number-status-error:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number-focused {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-status-error .ant-input-number-prefix {\n color: #ff4d4f;\n}\n.ant-input-number-status-warning:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number,\n.ant-input-number-status-warning:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number:hover {\n background: #fff;\n border-color: #faad14;\n}\n.ant-input-number-status-warning:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number:focus,\n.ant-input-number-status-warning:not(.ant-input-number-disabled):not(.ant-input-number-borderless).ant-input-number-focused {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-status-warning .ant-input-number-prefix {\n color: #faad14;\n}\n.ant-input-number-affix-wrapper-status-error:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper,\n.ant-input-number-affix-wrapper-status-error:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper:hover {\n background: #fff;\n border-color: #ff4d4f;\n}\n.ant-input-number-affix-wrapper-status-error:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper:focus,\n.ant-input-number-affix-wrapper-status-error:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper-focused {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-affix-wrapper-status-error .ant-input-number-prefix {\n color: #ff4d4f;\n}\n.ant-input-number-affix-wrapper-status-warning:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper,\n.ant-input-number-affix-wrapper-status-warning:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper:hover {\n background: #fff;\n border-color: #faad14;\n}\n.ant-input-number-affix-wrapper-status-warning:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper:focus,\n.ant-input-number-affix-wrapper-status-warning:not(.ant-input-number-affix-wrapper-disabled):not(.ant-input-number-affix-wrapper-borderless).ant-input-number-affix-wrapper-focused {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-affix-wrapper-status-warning .ant-input-number-prefix {\n color: #faad14;\n}\n.ant-input-number-group-wrapper-status-error .ant-input-number-group-addon {\n color: #ff4d4f;\n border-color: #ff4d4f;\n}\n.ant-input-number-group-wrapper-status-warning .ant-input-number-group-addon {\n color: #faad14;\n border-color: #faad14;\n}\n.ant-input-number {\n box-sizing: border-box;\n font-variant: tabular-nums;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n transition: all 0.3s;\n display: inline-block;\n width: 90px;\n margin: 0;\n padding: 0;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n}\n.ant-input-number::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-input-number:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-input-number:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-input-number:focus,\n.ant-input-number-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-number-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-number[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-number[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-number-borderless,\n.ant-input-number-borderless:hover,\n.ant-input-number-borderless:focus,\n.ant-input-number-borderless-focused,\n.ant-input-number-borderless-disabled,\n.ant-input-number-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-input-number {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-input-number-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-number-sm {\n padding: 0px 7px;\n}\n.ant-input-number-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: table;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n}\n.ant-input-number-group[class*='col-'] {\n float: none;\n padding-right: 0;\n padding-left: 0;\n}\n.ant-input-number-group > [class*='col-'] {\n padding-right: 8px;\n}\n.ant-input-number-group > [class*='col-']:last-child {\n padding-right: 0;\n}\n.ant-input-number-group-addon,\n.ant-input-number-group-wrap,\n.ant-input-number-group > .ant-input-number {\n display: table-cell;\n}\n.ant-input-number-group-addon:not(:first-child):not(:last-child),\n.ant-input-number-group-wrap:not(:first-child):not(:last-child),\n.ant-input-number-group > .ant-input-number:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.ant-input-number-group-addon,\n.ant-input-number-group-wrap {\n width: 1px;\n white-space: nowrap;\n vertical-align: middle;\n}\n.ant-input-number-group-wrap > * {\n display: block !important;\n}\n.ant-input-number-group .ant-input-number {\n float: left;\n width: 100%;\n margin-bottom: 0;\n text-align: inherit;\n}\n.ant-input-number-group .ant-input-number:focus {\n z-index: 1;\n border-right-width: 1px;\n}\n.ant-input-number-group .ant-input-number:hover {\n z-index: 1;\n border-right-width: 1px;\n}\n.ant-input-search-with-button .ant-input-number-group .ant-input-number:hover {\n z-index: 0;\n}\n.ant-input-number-group-addon {\n position: relative;\n padding: 0 11px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n text-align: center;\n background-color: #fafafa;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n}\n.ant-input-number-group-addon .ant-select {\n margin: -5px -11px;\n}\n.ant-input-number-group-addon .ant-select.ant-select-single:not(.ant-select-customize-input) .ant-select-selector {\n background-color: inherit;\n border: 1px solid transparent;\n box-shadow: none;\n}\n.ant-input-number-group-addon .ant-select-open .ant-select-selector,\n.ant-input-number-group-addon .ant-select-focused .ant-select-selector {\n color: #1890ff;\n}\n.ant-input-number-group-addon .ant-cascader-picker {\n margin: -9px -12px;\n background-color: transparent;\n}\n.ant-input-number-group-addon .ant-cascader-picker .ant-cascader-input {\n text-align: left;\n border: 0;\n box-shadow: none;\n}\n.ant-input-number-group > .ant-input-number:first-child,\n.ant-input-number-group-addon:first-child {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-number-group > .ant-input-number:first-child .ant-select .ant-select-selector,\n.ant-input-number-group-addon:first-child .ant-select .ant-select-selector {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-number-group > .ant-input-number-affix-wrapper:not(:first-child) .ant-input-number {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-group > .ant-input-number-affix-wrapper:not(:last-child) .ant-input-number {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-number-group-addon:first-child {\n border-right: 0;\n}\n.ant-input-number-group-addon:last-child {\n border-left: 0;\n}\n.ant-input-number-group > .ant-input-number:last-child,\n.ant-input-number-group-addon:last-child {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-group > .ant-input-number:last-child .ant-select .ant-select-selector,\n.ant-input-number-group-addon:last-child .ant-select .ant-select-selector {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-group-lg .ant-input-number,\n.ant-input-number-group-lg > .ant-input-number-group-addon {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-number-group-sm .ant-input-number,\n.ant-input-number-group-sm > .ant-input-number-group-addon {\n padding: 0px 7px;\n}\n.ant-input-number-group-lg .ant-select-single .ant-select-selector {\n height: 40px;\n}\n.ant-input-number-group-sm .ant-select-single .ant-select-selector {\n height: 24px;\n}\n.ant-input-number-group .ant-input-number-affix-wrapper:not(:last-child) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-search .ant-input-number-group .ant-input-number-affix-wrapper:not(:last-child) {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-input-number-group .ant-input-number-affix-wrapper:not(:first-child),\n.ant-input-search .ant-input-number-group .ant-input-number-affix-wrapper:not(:first-child) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-group.ant-input-number-group-compact {\n display: block;\n}\n.ant-input-number-group.ant-input-number-group-compact::before {\n display: table;\n content: '';\n}\n.ant-input-number-group.ant-input-number-group-compact::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-input-number-group.ant-input-number-group-compact-addon:not(:first-child):not(:last-child),\n.ant-input-number-group.ant-input-number-group-compact-wrap:not(:first-child):not(:last-child),\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-number:not(:first-child):not(:last-child) {\n border-right-width: 1px;\n}\n.ant-input-number-group.ant-input-number-group-compact-addon:not(:first-child):not(:last-child):hover,\n.ant-input-number-group.ant-input-number-group-compact-wrap:not(:first-child):not(:last-child):hover,\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-number:not(:first-child):not(:last-child):hover {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact-addon:not(:first-child):not(:last-child):focus,\n.ant-input-number-group.ant-input-number-group-compact-wrap:not(:first-child):not(:last-child):focus,\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-number:not(:first-child):not(:last-child):focus {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact > * {\n display: inline-block;\n float: none;\n vertical-align: top;\n border-radius: 0;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-number-affix-wrapper {\n display: inline-flex;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-picker-range {\n display: inline-flex;\n}\n.ant-input-number-group.ant-input-number-group-compact > *:not(:last-child) {\n margin-right: -1px;\n border-right-width: 1px;\n}\n.ant-input-number-group.ant-input-number-group-compact .ant-input-number {\n float: none;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select > .ant-select-selector,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-auto-complete .ant-input,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker .ant-input,\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-group-wrapper .ant-input {\n border-right-width: 1px;\n border-radius: 0;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select > .ant-select-selector:hover,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-auto-complete .ant-input:hover,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker .ant-input:hover,\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-group-wrapper .ant-input:hover {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select > .ant-select-selector:focus,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-auto-complete .ant-input:focus,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker .ant-input:focus,\n.ant-input-number-group.ant-input-number-group-compact > .ant-input-group-wrapper .ant-input:focus {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-focused {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select > .ant-select-arrow {\n z-index: 1;\n}\n.ant-input-number-group.ant-input-number-group-compact > *:first-child,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select:first-child > .ant-select-selector,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-auto-complete:first-child .ant-input,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker:first-child .ant-input {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-input-number-group.ant-input-number-group-compact > *:last-child,\n.ant-input-number-group.ant-input-number-group-compact > .ant-select:last-child > .ant-select-selector,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker:last-child .ant-input,\n.ant-input-number-group.ant-input-number-group-compact > .ant-cascader-picker-focused:last-child .ant-input {\n border-right-width: 1px;\n border-top-right-radius: 2px;\n border-bottom-right-radius: 2px;\n}\n.ant-input-number-group.ant-input-number-group-compact > .ant-select-auto-complete .ant-input {\n vertical-align: top;\n}\n.ant-input-number-group.ant-input-number-group-compact .ant-input-group-wrapper + .ant-input-group-wrapper {\n margin-left: -1px;\n}\n.ant-input-number-group.ant-input-number-group-compact .ant-input-group-wrapper + .ant-input-group-wrapper .ant-input-affix-wrapper {\n border-radius: 0;\n}\n.ant-input-number-group.ant-input-number-group-compact .ant-input-group-wrapper:not(:last-child).ant-input-search > .ant-input-group > .ant-input-group-addon > .ant-input-search-button {\n border-radius: 0;\n}\n.ant-input-number-group.ant-input-number-group-compact .ant-input-group-wrapper:not(:last-child).ant-input-search > .ant-input-group > .ant-input {\n border-radius: 2px 0 0 2px;\n}\n.ant-input-number-group > .ant-input-number-rtl:first-child {\n border-radius: 0 2px 2px 0;\n}\n.ant-input-number-group > .ant-input-number-rtl:last-child {\n border-radius: 2px 0 0 2px;\n}\n.ant-input-number-group-rtl .ant-input-number-group-addon:first-child {\n border-right: 1px solid #d9d9d9;\n border-left: 0;\n border-radius: 0 2px 2px 0;\n}\n.ant-input-number-group-rtl .ant-input-number-group-addon:last-child {\n border-right: 0;\n border-left: 1px solid #d9d9d9;\n border-radius: 2px 0 0 2px;\n}\n.ant-input-number-group-wrapper {\n display: inline-block;\n text-align: start;\n vertical-align: top;\n}\n.ant-input-number-handler {\n position: relative;\n display: block;\n width: 100%;\n height: 50%;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.45);\n font-weight: bold;\n line-height: 0;\n text-align: center;\n border-left: 1px solid #d9d9d9;\n transition: all 0.1s linear;\n}\n.ant-input-number-handler:active {\n background: #f4f4f4;\n}\n.ant-input-number-handler:hover .ant-input-number-handler-up-inner,\n.ant-input-number-handler:hover .ant-input-number-handler-down-inner {\n color: #40a9ff;\n}\n.ant-input-number-handler-up-inner,\n.ant-input-number-handler-down-inner {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizelegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n position: absolute;\n right: 4px;\n width: 12px;\n height: 12px;\n color: rgba(0, 0, 0, 0.45);\n line-height: 12px;\n transition: all 0.1s linear;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number-handler-up-inner > *,\n.ant-input-number-handler-down-inner > * {\n line-height: 1;\n}\n.ant-input-number-handler-up-inner svg,\n.ant-input-number-handler-down-inner svg {\n display: inline-block;\n}\n.ant-input-number-handler-up-inner::before,\n.ant-input-number-handler-down-inner::before {\n display: none;\n}\n.ant-input-number-handler-up-inner .ant-input-number-handler-up-inner-icon,\n.ant-input-number-handler-up-inner .ant-input-number-handler-down-inner-icon,\n.ant-input-number-handler-down-inner .ant-input-number-handler-up-inner-icon,\n.ant-input-number-handler-down-inner .ant-input-number-handler-down-inner-icon {\n display: block;\n}\n.ant-input-number:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-input-number:hover + .ant-form-item-children-icon {\n opacity: 0;\n transition: opacity 0.24s linear 0.24s;\n}\n.ant-input-number-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-number-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-number-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-number-disabled .ant-input-number-input {\n cursor: not-allowed;\n}\n.ant-input-number-disabled .ant-input-number-handler-wrap {\n display: none;\n}\n.ant-input-number-readonly .ant-input-number-handler-wrap {\n display: none;\n}\n.ant-input-number-input {\n width: 100%;\n height: 30px;\n padding: 0 11px;\n text-align: left;\n background-color: transparent;\n border: 0;\n border-radius: 2px;\n outline: 0;\n transition: all 0.3s linear;\n -webkit-appearance: textfield !important;\n -moz-appearance: textfield !important;\n appearance: textfield !important;\n}\n.ant-input-number-input::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-input-number-input:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number-input::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-number-input:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number-input:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-input-number-input:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-number-input[type='number']::-webkit-inner-spin-button,\n.ant-input-number-input[type='number']::-webkit-outer-spin-button {\n margin: 0;\n /* stylelint-disable-next-line property-no-vendor-prefix */\n -webkit-appearance: none;\n appearance: none;\n}\n.ant-input-number-lg {\n padding: 0;\n font-size: 16px;\n}\n.ant-input-number-lg input {\n height: 38px;\n}\n.ant-input-number-sm {\n padding: 0;\n}\n.ant-input-number-sm input {\n height: 22px;\n padding: 0 7px;\n}\n.ant-input-number-handler-wrap {\n position: absolute;\n top: 0;\n right: 0;\n width: 22px;\n height: 100%;\n background: #fff;\n border-radius: 0 2px 2px 0;\n opacity: 0;\n transition: opacity 0.24s linear 0.1s;\n}\n.ant-input-number-handler-wrap .ant-input-number-handler .ant-input-number-handler-up-inner,\n.ant-input-number-handler-wrap .ant-input-number-handler .ant-input-number-handler-down-inner {\n display: flex;\n align-items: center;\n justify-content: center;\n min-width: auto;\n margin-right: 0;\n font-size: 7px;\n}\n.ant-input-number-borderless .ant-input-number-handler-wrap {\n border-left-width: 0;\n}\n.ant-input-number-handler-wrap:hover .ant-input-number-handler {\n height: 40%;\n}\n.ant-input-number:hover .ant-input-number-handler-wrap,\n.ant-input-number-focused .ant-input-number-handler-wrap {\n opacity: 1;\n}\n.ant-input-number-handler-up {\n border-top-right-radius: 2px;\n cursor: pointer;\n}\n.ant-input-number-handler-up-inner {\n top: 50%;\n margin-top: -5px;\n text-align: center;\n}\n.ant-input-number-handler-up:hover {\n height: 60% !important;\n}\n.ant-input-number-handler-down {\n top: 0;\n border-top: 1px solid #d9d9d9;\n border-bottom-right-radius: 2px;\n cursor: pointer;\n}\n.ant-input-number-handler-down-inner {\n top: 50%;\n text-align: center;\n transform: translateY(-50%);\n}\n.ant-input-number-handler-down:hover {\n height: 60% !important;\n}\n.ant-input-number-borderless .ant-input-number-handler-down {\n border-top-width: 0;\n}\n.ant-input-number:hover:not(.ant-input-number-borderless) .ant-input-number-handler-down,\n.ant-input-number-focused:not(.ant-input-number-borderless) .ant-input-number-handler-down {\n border-top: 1px solid #d9d9d9;\n}\n.ant-input-number-handler-up-disabled,\n.ant-input-number-handler-down-disabled {\n cursor: not-allowed;\n}\n.ant-input-number-handler-up-disabled:hover .ant-input-number-handler-up-inner,\n.ant-input-number-handler-down-disabled:hover .ant-input-number-handler-down-inner {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-input-number-borderless {\n box-shadow: none;\n}\n.ant-input-number-out-of-range input {\n color: #ff4d4f;\n}\n.ant-input-number-compact-item:not(.ant-input-number-compact-last-item):not(.ant-input-number-compact-item-rtl) {\n margin-right: -1px;\n}\n.ant-input-number-compact-item:not(.ant-input-number-compact-last-item).ant-input-number-compact-item-rtl {\n margin-left: -1px;\n}\n.ant-input-number-compact-item:hover,\n.ant-input-number-compact-item:focus,\n.ant-input-number-compact-item:active {\n z-index: 2;\n}\n.ant-input-number-compact-item.ant-input-number-focused {\n z-index: 2;\n}\n.ant-input-number-compact-item[disabled] {\n z-index: 0;\n}\n.ant-input-number-compact-item:not(.ant-input-number-compact-first-item):not(.ant-input-number-compact-last-item).ant-input-number {\n border-radius: 0;\n}\n.ant-input-number-compact-item.ant-input-number.ant-input-number-compact-first-item:not(.ant-input-number-compact-last-item):not(.ant-input-number-compact-item-rtl) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-number-compact-item.ant-input-number.ant-input-number-compact-last-item:not(.ant-input-number-compact-first-item):not(.ant-input-number-compact-item-rtl) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-compact-item.ant-input-number.ant-input-number-compact-item-rtl.ant-input-number-compact-first-item:not(.ant-input-number-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-number-compact-item.ant-input-number.ant-input-number-compact-item-rtl.ant-input-number-compact-last-item:not(.ant-input-number-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-number-rtl {\n direction: rtl;\n}\n.ant-input-number-rtl .ant-input-number-handler {\n border-right: 1px solid #d9d9d9;\n border-left: 0;\n}\n.ant-input-number-rtl .ant-input-number-handler-wrap {\n right: auto;\n left: 0;\n}\n.ant-input-number-rtl.ant-input-number-borderless .ant-input-number-handler-wrap {\n border-right-width: 0;\n}\n.ant-input-number-rtl .ant-input-number-handler-up {\n border-top-right-radius: 0;\n}\n.ant-input-number-rtl .ant-input-number-handler-down {\n border-bottom-right-radius: 0;\n}\n.ant-input-number-rtl .ant-input-number-input {\n direction: ltr;\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-input-affix-wrapper {\n position: relative;\n display: inline-block;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n display: inline-flex;\n}\n.ant-input-affix-wrapper::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-input-affix-wrapper:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-affix-wrapper::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input-affix-wrapper:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-affix-wrapper:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-input-affix-wrapper:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input-affix-wrapper:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-input-rtl .ant-input-affix-wrapper:hover {\n border-right-width: 0;\n border-left-width: 1px !important;\n}\n.ant-input-affix-wrapper:focus,\n.ant-input-affix-wrapper-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-rtl .ant-input-affix-wrapper:focus,\n.ant-input-rtl .ant-input-affix-wrapper-focused {\n border-right-width: 0;\n border-left-width: 1px !important;\n}\n.ant-input-affix-wrapper-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-affix-wrapper-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-affix-wrapper[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-affix-wrapper[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-affix-wrapper-borderless,\n.ant-input-affix-wrapper-borderless:hover,\n.ant-input-affix-wrapper-borderless:focus,\n.ant-input-affix-wrapper-borderless-focused,\n.ant-input-affix-wrapper-borderless-disabled,\n.ant-input-affix-wrapper-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-input-affix-wrapper {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-input-affix-wrapper-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-affix-wrapper-sm {\n padding: 0px 7px;\n}\n.ant-input-affix-wrapper-rtl {\n direction: rtl;\n}\n.ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n z-index: 1;\n}\n.ant-input-rtl .ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover {\n border-right-width: 0;\n border-left-width: 1px !important;\n}\n.ant-input-search-with-button .ant-input-affix-wrapper:not(.ant-input-affix-wrapper-disabled):hover {\n z-index: 0;\n}\n.ant-input-affix-wrapper-focused,\n.ant-input-affix-wrapper:focus {\n z-index: 1;\n}\n.ant-input-affix-wrapper-disabled .ant-input[disabled] {\n background: transparent;\n}\n.ant-input-affix-wrapper > .ant-input {\n font-size: inherit;\n border: none;\n outline: none;\n}\n.ant-input-affix-wrapper > .ant-input:focus {\n box-shadow: none !important;\n}\n.ant-input-affix-wrapper > .ant-input:not(textarea) {\n padding: 0;\n}\n.ant-input-affix-wrapper::before {\n width: 0;\n visibility: hidden;\n content: '\\a0';\n}\n.ant-input-prefix,\n.ant-input-suffix {\n display: flex;\n flex: none;\n align-items: center;\n}\n.ant-input-prefix > *:not(:last-child),\n.ant-input-suffix > *:not(:last-child) {\n margin-right: 8px;\n}\n.ant-input-show-count-suffix {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-input-show-count-has-suffix {\n margin-right: 2px;\n}\n.ant-input-prefix {\n margin-right: 4px;\n}\n.ant-input-suffix {\n margin-left: 4px;\n}\n.anticon.ant-input-clear-icon,\n.ant-input-clear-icon {\n margin: 0;\n color: rgba(0, 0, 0, 0.25);\n font-size: 12px;\n vertical-align: -1px;\n cursor: pointer;\n transition: color 0.3s;\n}\n.anticon.ant-input-clear-icon:hover,\n.ant-input-clear-icon:hover {\n color: rgba(0, 0, 0, 0.45);\n}\n.anticon.ant-input-clear-icon:active,\n.ant-input-clear-icon:active {\n color: rgba(0, 0, 0, 0.85);\n}\n.anticon.ant-input-clear-icon-hidden,\n.ant-input-clear-icon-hidden {\n visibility: hidden;\n}\n.anticon.ant-input-clear-icon-has-suffix,\n.ant-input-clear-icon-has-suffix {\n margin: 0 4px;\n}\n.ant-input-affix-wrapper.ant-input-affix-wrapper-textarea-with-clear-btn {\n padding: 0;\n}\n.ant-input-affix-wrapper.ant-input-affix-wrapper-textarea-with-clear-btn .ant-input-clear-icon {\n position: absolute;\n top: 8px;\n right: 8px;\n z-index: 1;\n}\n.ant-input-status-error:not(.ant-input-disabled):not(.ant-input-borderless).ant-input,\n.ant-input-status-error:not(.ant-input-disabled):not(.ant-input-borderless).ant-input:hover {\n background: #fff;\n border-color: #ff4d4f;\n}\n.ant-input-status-error:not(.ant-input-disabled):not(.ant-input-borderless).ant-input:focus,\n.ant-input-status-error:not(.ant-input-disabled):not(.ant-input-borderless).ant-input-focused {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-status-error .ant-input-prefix {\n color: #ff4d4f;\n}\n.ant-input-status-warning:not(.ant-input-disabled):not(.ant-input-borderless).ant-input,\n.ant-input-status-warning:not(.ant-input-disabled):not(.ant-input-borderless).ant-input:hover {\n background: #fff;\n border-color: #faad14;\n}\n.ant-input-status-warning:not(.ant-input-disabled):not(.ant-input-borderless).ant-input:focus,\n.ant-input-status-warning:not(.ant-input-disabled):not(.ant-input-borderless).ant-input-focused {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-status-warning .ant-input-prefix {\n color: #faad14;\n}\n.ant-input-affix-wrapper-status-error:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper,\n.ant-input-affix-wrapper-status-error:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper:hover {\n background: #fff;\n border-color: #ff4d4f;\n}\n.ant-input-affix-wrapper-status-error:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper:focus,\n.ant-input-affix-wrapper-status-error:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper-focused {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-affix-wrapper-status-error .ant-input-prefix {\n color: #ff4d4f;\n}\n.ant-input-affix-wrapper-status-warning:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper,\n.ant-input-affix-wrapper-status-warning:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper:hover {\n background: #fff;\n border-color: #faad14;\n}\n.ant-input-affix-wrapper-status-warning:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper:focus,\n.ant-input-affix-wrapper-status-warning:not(.ant-input-affix-wrapper-disabled):not(.ant-input-affix-wrapper-borderless).ant-input-affix-wrapper-focused {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-affix-wrapper-status-warning .ant-input-prefix {\n color: #faad14;\n}\n.ant-input-textarea-status-error.ant-input-textarea-has-feedback .ant-input,\n.ant-input-textarea-status-warning.ant-input-textarea-has-feedback .ant-input,\n.ant-input-textarea-status-success.ant-input-textarea-has-feedback .ant-input,\n.ant-input-textarea-status-validating.ant-input-textarea-has-feedback .ant-input {\n padding-right: 24px;\n}\n.ant-input-group-wrapper-status-error .ant-input-group-addon {\n color: #ff4d4f;\n border-color: #ff4d4f;\n}\n.ant-input-group-wrapper-status-warning .ant-input-group-addon {\n color: #faad14;\n border-color: #faad14;\n}\n.ant-input {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n font-variant: tabular-nums;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-block;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n}\n.ant-input::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-input:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-input:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-input:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-input:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-input-rtl .ant-input:hover {\n border-right-width: 0;\n border-left-width: 1px !important;\n}\n.ant-input:focus,\n.ant-input-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-input-rtl .ant-input:focus,\n.ant-input-rtl .ant-input-focused {\n border-right-width: 0;\n border-left-width: 1px !important;\n}\n.ant-input-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-input[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-input-borderless,\n.ant-input-borderless:hover,\n.ant-input-borderless:focus,\n.ant-input-borderless-focused,\n.ant-input-borderless-disabled,\n.ant-input-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-input {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-input-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-sm {\n padding: 0px 7px;\n}\n.ant-input-rtl {\n direction: rtl;\n}\n.ant-input-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: table;\n width: 100%;\n border-collapse: separate;\n border-spacing: 0;\n}\n.ant-input-group[class*='col-'] {\n float: none;\n padding-right: 0;\n padding-left: 0;\n}\n.ant-input-group > [class*='col-'] {\n padding-right: 8px;\n}\n.ant-input-group > [class*='col-']:last-child {\n padding-right: 0;\n}\n.ant-input-group-addon,\n.ant-input-group-wrap,\n.ant-input-group > .ant-input {\n display: table-cell;\n}\n.ant-input-group-addon:not(:first-child):not(:last-child),\n.ant-input-group-wrap:not(:first-child):not(:last-child),\n.ant-input-group > .ant-input:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.ant-input-group-addon,\n.ant-input-group-wrap {\n width: 1px;\n white-space: nowrap;\n vertical-align: middle;\n}\n.ant-input-group-wrap > * {\n display: block !important;\n}\n.ant-input-group .ant-input {\n float: left;\n width: 100%;\n margin-bottom: 0;\n text-align: inherit;\n}\n.ant-input-group .ant-input:focus {\n z-index: 1;\n border-right-width: 1px;\n}\n.ant-input-group .ant-input:hover {\n z-index: 1;\n border-right-width: 1px;\n}\n.ant-input-search-with-button .ant-input-group .ant-input:hover {\n z-index: 0;\n}\n.ant-input-group-addon {\n position: relative;\n padding: 0 11px;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n font-size: 14px;\n text-align: center;\n background-color: #fafafa;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n}\n.ant-input-group-addon .ant-select {\n margin: -5px -11px;\n}\n.ant-input-group-addon .ant-select.ant-select-single:not(.ant-select-customize-input) .ant-select-selector {\n background-color: inherit;\n border: 1px solid transparent;\n box-shadow: none;\n}\n.ant-input-group-addon .ant-select-open .ant-select-selector,\n.ant-input-group-addon .ant-select-focused .ant-select-selector {\n color: #1890ff;\n}\n.ant-input-group-addon .ant-cascader-picker {\n margin: -9px -12px;\n background-color: transparent;\n}\n.ant-input-group-addon .ant-cascader-picker .ant-cascader-input {\n text-align: left;\n border: 0;\n box-shadow: none;\n}\n.ant-input-group > .ant-input:first-child,\n.ant-input-group-addon:first-child {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-group > .ant-input:first-child .ant-select .ant-select-selector,\n.ant-input-group-addon:first-child .ant-select .ant-select-selector {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-group > .ant-input-affix-wrapper:not(:first-child) .ant-input {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-group > .ant-input-affix-wrapper:not(:last-child) .ant-input {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-group-addon:first-child {\n border-right: 0;\n}\n.ant-input-group-addon:last-child {\n border-left: 0;\n}\n.ant-input-group > .ant-input:last-child,\n.ant-input-group-addon:last-child {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-group > .ant-input:last-child .ant-select .ant-select-selector,\n.ant-input-group-addon:last-child .ant-select .ant-select-selector {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-group-lg .ant-input,\n.ant-input-group-lg > .ant-input-group-addon {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-input-group-sm .ant-input,\n.ant-input-group-sm > .ant-input-group-addon {\n padding: 0px 7px;\n}\n.ant-input-group-lg .ant-select-single .ant-select-selector {\n height: 40px;\n}\n.ant-input-group-sm .ant-select-single .ant-select-selector {\n height: 24px;\n}\n.ant-input-group .ant-input-affix-wrapper:not(:last-child) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-search .ant-input-group .ant-input-affix-wrapper:not(:last-child) {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-input-group .ant-input-affix-wrapper:not(:first-child),\n.ant-input-search .ant-input-group .ant-input-affix-wrapper:not(:first-child) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-group.ant-input-group-compact {\n display: block;\n}\n.ant-input-group.ant-input-group-compact::before {\n display: table;\n content: '';\n}\n.ant-input-group.ant-input-group-compact::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-input-group.ant-input-group-compact-addon:not(:first-child):not(:last-child),\n.ant-input-group.ant-input-group-compact-wrap:not(:first-child):not(:last-child),\n.ant-input-group.ant-input-group-compact > .ant-input:not(:first-child):not(:last-child) {\n border-right-width: 1px;\n}\n.ant-input-group.ant-input-group-compact-addon:not(:first-child):not(:last-child):hover,\n.ant-input-group.ant-input-group-compact-wrap:not(:first-child):not(:last-child):hover,\n.ant-input-group.ant-input-group-compact > .ant-input:not(:first-child):not(:last-child):hover {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact-addon:not(:first-child):not(:last-child):focus,\n.ant-input-group.ant-input-group-compact-wrap:not(:first-child):not(:last-child):focus,\n.ant-input-group.ant-input-group-compact > .ant-input:not(:first-child):not(:last-child):focus {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact > * {\n display: inline-block;\n float: none;\n vertical-align: top;\n border-radius: 0;\n}\n.ant-input-group.ant-input-group-compact > .ant-input-affix-wrapper {\n display: inline-flex;\n}\n.ant-input-group.ant-input-group-compact > .ant-picker-range {\n display: inline-flex;\n}\n.ant-input-group.ant-input-group-compact > *:not(:last-child) {\n margin-right: -1px;\n border-right-width: 1px;\n}\n.ant-input-group.ant-input-group-compact .ant-input {\n float: none;\n}\n.ant-input-group.ant-input-group-compact > .ant-select > .ant-select-selector,\n.ant-input-group.ant-input-group-compact > .ant-select-auto-complete .ant-input,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker .ant-input,\n.ant-input-group.ant-input-group-compact > .ant-input-group-wrapper .ant-input {\n border-right-width: 1px;\n border-radius: 0;\n}\n.ant-input-group.ant-input-group-compact > .ant-select > .ant-select-selector:hover,\n.ant-input-group.ant-input-group-compact > .ant-select-auto-complete .ant-input:hover,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker .ant-input:hover,\n.ant-input-group.ant-input-group-compact > .ant-input-group-wrapper .ant-input:hover {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact > .ant-select > .ant-select-selector:focus,\n.ant-input-group.ant-input-group-compact > .ant-select-auto-complete .ant-input:focus,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker .ant-input:focus,\n.ant-input-group.ant-input-group-compact > .ant-input-group-wrapper .ant-input:focus {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact > .ant-select-focused {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact > .ant-select > .ant-select-arrow {\n z-index: 1;\n}\n.ant-input-group.ant-input-group-compact > *:first-child,\n.ant-input-group.ant-input-group-compact > .ant-select:first-child > .ant-select-selector,\n.ant-input-group.ant-input-group-compact > .ant-select-auto-complete:first-child .ant-input,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker:first-child .ant-input {\n border-top-left-radius: 2px;\n border-bottom-left-radius: 2px;\n}\n.ant-input-group.ant-input-group-compact > *:last-child,\n.ant-input-group.ant-input-group-compact > .ant-select:last-child > .ant-select-selector,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker:last-child .ant-input,\n.ant-input-group.ant-input-group-compact > .ant-cascader-picker-focused:last-child .ant-input {\n border-right-width: 1px;\n border-top-right-radius: 2px;\n border-bottom-right-radius: 2px;\n}\n.ant-input-group.ant-input-group-compact > .ant-select-auto-complete .ant-input {\n vertical-align: top;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper + .ant-input-group-wrapper {\n margin-left: -1px;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper + .ant-input-group-wrapper .ant-input-affix-wrapper {\n border-radius: 0;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper:not(:last-child).ant-input-search > .ant-input-group > .ant-input-group-addon > .ant-input-search-button {\n border-radius: 0;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper:not(:last-child).ant-input-search > .ant-input-group > .ant-input {\n border-radius: 2px 0 0 2px;\n}\n.ant-input-group > .ant-input-rtl:first-child,\n.ant-input-group-rtl .ant-input-group-addon:first-child {\n border-radius: 0 2px 2px 0;\n}\n.ant-input-group-rtl .ant-input-group-addon:first-child {\n border-right: 1px solid #d9d9d9;\n border-left: 0;\n}\n.ant-input-group-rtl .ant-input-group-addon:last-child {\n border-right: 0;\n border-left: 1px solid #d9d9d9;\n border-radius: 2px 0 0 2px;\n}\n.ant-input-group-rtl.ant-input-group > .ant-input:last-child,\n.ant-input-group-rtl.ant-input-group-addon:last-child {\n border-radius: 2px 0 0 2px;\n}\n.ant-input-group-rtl.ant-input-group .ant-input-affix-wrapper:not(:first-child) {\n border-radius: 2px 0 0 2px;\n}\n.ant-input-group-rtl.ant-input-group .ant-input-affix-wrapper:not(:last-child) {\n border-radius: 0 2px 2px 0;\n}\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > *:not(:last-child) {\n margin-right: 0;\n margin-left: -1px;\n border-left-width: 1px;\n}\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > *:first-child,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-select:first-child > .ant-select-selector,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-select-auto-complete:first-child .ant-input,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-cascader-picker:first-child .ant-input {\n border-radius: 0 2px 2px 0;\n}\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > *:last-child,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-select:last-child > .ant-select-selector,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-select-auto-complete:last-child .ant-input,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-cascader-picker:last-child .ant-input,\n.ant-input-group-rtl.ant-input-group.ant-input-group-compact > .ant-cascader-picker-focused:last-child .ant-input {\n border-left-width: 1px;\n border-radius: 2px 0 0 2px;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper-rtl + .ant-input-group-wrapper-rtl {\n margin-right: -1px;\n margin-left: 0;\n}\n.ant-input-group.ant-input-group-compact .ant-input-group-wrapper-rtl:not(:last-child).ant-input-search > .ant-input-group > .ant-input {\n border-radius: 0 2px 2px 0;\n}\n.ant-input-group-wrapper {\n display: inline-block;\n width: 100%;\n text-align: start;\n vertical-align: top;\n}\n.ant-input-password-icon.anticon {\n color: rgba(0, 0, 0, 0.45);\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-input-password-icon.anticon:hover {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-input[type='color'] {\n height: 32px;\n}\n.ant-input[type='color'].ant-input-lg {\n height: 40px;\n}\n.ant-input[type='color'].ant-input-sm {\n height: 24px;\n padding-top: 3px;\n padding-bottom: 3px;\n}\n.ant-input-textarea-show-count > .ant-input {\n height: 100%;\n}\n.ant-input-textarea-show-count::after {\n float: right;\n color: rgba(0, 0, 0, 0.45);\n white-space: nowrap;\n content: attr(data-count);\n pointer-events: none;\n}\n.ant-input-textarea-show-count.ant-input-textarea-in-form-item::after {\n margin-bottom: -22px;\n}\n.ant-input-textarea-suffix {\n position: absolute;\n top: 0;\n right: 11px;\n bottom: 0;\n z-index: 1;\n display: inline-flex;\n align-items: center;\n margin: auto;\n}\n.ant-input-compact-item:not(.ant-input-compact-last-item):not(.ant-input-compact-item-rtl) {\n margin-right: -1px;\n}\n.ant-input-compact-item:not(.ant-input-compact-last-item).ant-input-compact-item-rtl {\n margin-left: -1px;\n}\n.ant-input-compact-item:hover,\n.ant-input-compact-item:focus,\n.ant-input-compact-item:active {\n z-index: 2;\n}\n.ant-input-compact-item[disabled] {\n z-index: 0;\n}\n.ant-input-compact-item:not(.ant-input-compact-first-item):not(.ant-input-compact-last-item).ant-input {\n border-radius: 0;\n}\n.ant-input-compact-item.ant-input.ant-input-compact-first-item:not(.ant-input-compact-last-item):not(.ant-input-compact-item-rtl) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-compact-item.ant-input.ant-input-compact-last-item:not(.ant-input-compact-first-item):not(.ant-input-compact-item-rtl) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-compact-item.ant-input.ant-input-compact-item-rtl.ant-input-compact-first-item:not(.ant-input-compact-last-item) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n.ant-input-compact-item.ant-input.ant-input-compact-item-rtl.ant-input-compact-last-item:not(.ant-input-compact-first-item) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n}\n.ant-input-search .ant-input:hover,\n.ant-input-search .ant-input:focus {\n border-color: #40a9ff;\n}\n.ant-input-search .ant-input:hover + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary),\n.ant-input-search .ant-input:focus + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary) {\n border-left-color: #40a9ff;\n}\n.ant-input-search .ant-input-affix-wrapper {\n border-radius: 0;\n}\n.ant-input-search .ant-input-lg {\n line-height: 1.5713;\n}\n.ant-input-search > .ant-input-group > .ant-input-group-addon:last-child {\n left: -1px;\n padding: 0;\n border: 0;\n}\n.ant-input-search > .ant-input-group > .ant-input-group-addon:last-child .ant-input-search-button {\n padding-top: 0;\n padding-bottom: 0;\n border-radius: 0 2px 2px 0;\n}\n.ant-input-search > .ant-input-group > .ant-input-group-addon:last-child .ant-input-search-button:not(.ant-btn-primary) {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-input-search > .ant-input-group > .ant-input-group-addon:last-child .ant-input-search-button:not(.ant-btn-primary).ant-btn-loading::before {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n}\n.ant-input-search-button {\n height: 32px;\n}\n.ant-input-search-button:hover,\n.ant-input-search-button:focus {\n z-index: 1;\n}\n.ant-input-search-large .ant-input-search-button {\n height: 40px;\n}\n.ant-input-search-small .ant-input-search-button {\n height: 24px;\n}\n.ant-input-search.ant-input-compact-item:not(.ant-input-compact-item-rtl):not(.ant-input-compact-last-item) .ant-input-group-addon .ant-input-search-button {\n margin-right: -1px;\n border-radius: 0;\n}\n.ant-input-search.ant-input-compact-item:not(.ant-input-compact-first-item) .ant-input,\n.ant-input-search.ant-input-compact-item:not(.ant-input-compact-first-item) .ant-input-affix-wrapper {\n border-radius: 0;\n}\n.ant-input-search.ant-input-compact-item > .ant-input-group-addon .ant-input-search-button:hover,\n.ant-input-search.ant-input-compact-item > .ant-input:hover,\n.ant-input-search.ant-input-compact-item .ant-input-affix-wrapper:hover,\n.ant-input-search.ant-input-compact-item > .ant-input-group-addon .ant-input-search-button:focus,\n.ant-input-search.ant-input-compact-item > .ant-input:focus,\n.ant-input-search.ant-input-compact-item .ant-input-affix-wrapper:focus,\n.ant-input-search.ant-input-compact-item > .ant-input-group-addon .ant-input-search-button:active,\n.ant-input-search.ant-input-compact-item > .ant-input:active,\n.ant-input-search.ant-input-compact-item .ant-input-affix-wrapper:active {\n z-index: 2;\n}\n.ant-input-search.ant-input-compact-item > .ant-input-affix-wrapper-focused {\n z-index: 2;\n}\n.ant-input-search.ant-input-compact-item-rtl:not(.ant-input-compact-last-item) .ant-input-group-addon:last-child .ant-input-search-button {\n margin-left: -1px;\n border-radius: 0;\n}\n.ant-input-group-wrapper-rtl {\n direction: rtl;\n}\n.ant-input-group-rtl {\n direction: rtl;\n}\n.ant-input-affix-wrapper.ant-input-affix-wrapper-rtl > input.ant-input {\n border: none;\n outline: none;\n}\n.ant-input-affix-wrapper-rtl .ant-input-prefix {\n margin: 0 0 0 4px;\n}\n.ant-input-affix-wrapper-rtl .ant-input-suffix {\n margin: 0 4px 0 0;\n}\n.ant-input-textarea-rtl {\n direction: rtl;\n}\n.ant-input-textarea-rtl.ant-input-textarea-show-count::after {\n text-align: left;\n}\n.ant-input-affix-wrapper-rtl .ant-input-clear-icon-has-suffix {\n margin-right: 0;\n margin-left: 4px;\n}\n.ant-input-affix-wrapper-rtl .ant-input-clear-icon {\n right: auto;\n left: 8px;\n}\n.ant-input-search-rtl {\n direction: rtl;\n}\n.ant-input-search-rtl .ant-input:hover + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary),\n.ant-input-search-rtl .ant-input:focus + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary) {\n border-left-color: #d9d9d9;\n}\n.ant-input-search-rtl .ant-input:hover + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary):hover,\n.ant-input-search-rtl .ant-input:focus + .ant-input-group-addon .ant-input-search-button:not(.ant-btn-primary):hover {\n border-left-color: #40a9ff;\n}\n.ant-input-search-rtl > .ant-input-group > .ant-input-affix-wrapper:hover,\n.ant-input-search-rtl > .ant-input-group > .ant-input-affix-wrapper-focused {\n border-right-color: #40a9ff;\n}\n.ant-input-search-rtl > .ant-input-group > .ant-input-group-addon:last-child {\n right: -1px;\n left: auto;\n}\n.ant-input-search-rtl > .ant-input-group > .ant-input-group-addon:last-child .ant-input-search-button {\n border-radius: 2px 0 0 2px;\n}\n@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {\n .ant-input {\n height: 32px;\n }\n .ant-input-lg {\n height: 40px;\n }\n .ant-input-sm {\n height: 24px;\n }\n .ant-input-affix-wrapper > input.ant-input {\n height: auto;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-layout {\n display: flex;\n flex: auto;\n flex-direction: column;\n /* fix firefox can't set height smaller than content on flex item */\n min-height: 0;\n background: #f0f2f5;\n}\n.ant-layout,\n.ant-layout * {\n box-sizing: border-box;\n}\n.ant-layout.ant-layout-has-sider {\n flex-direction: row;\n}\n.ant-layout.ant-layout-has-sider > .ant-layout,\n.ant-layout.ant-layout-has-sider > .ant-layout-content {\n width: 0;\n}\n.ant-layout-header,\n.ant-layout-footer {\n flex: 0 0 auto;\n}\n.ant-layout-header {\n height: 64px;\n padding: 0 50px;\n color: rgba(0, 0, 0, 0.85);\n line-height: 64px;\n background: #001529;\n}\n.ant-layout-footer {\n padding: 24px 50px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n background: #f0f2f5;\n}\n.ant-layout-content {\n flex: auto;\n /* fix firefox can't set height smaller than content on flex item */\n min-height: 0;\n}\n.ant-layout-sider {\n position: relative;\n /* fix firefox can't set width smaller than content on flex item */\n min-width: 0;\n background: #001529;\n transition: all 0.2s;\n}\n.ant-layout-sider-children {\n height: 100%;\n margin-top: -0.1px;\n padding-top: 0.1px;\n}\n.ant-layout-sider-children .ant-menu.ant-menu-inline-collapsed {\n width: auto;\n}\n.ant-layout-sider-has-trigger {\n padding-bottom: 48px;\n}\n.ant-layout-sider-right {\n order: 1;\n}\n.ant-layout-sider-trigger {\n position: fixed;\n bottom: 0;\n z-index: 1;\n height: 48px;\n color: #fff;\n line-height: 48px;\n text-align: center;\n background: #002140;\n cursor: pointer;\n transition: all 0.2s;\n}\n.ant-layout-sider-zero-width > * {\n overflow: hidden;\n}\n.ant-layout-sider-zero-width-trigger {\n position: absolute;\n top: 64px;\n right: -36px;\n z-index: 1;\n width: 36px;\n height: 42px;\n color: #fff;\n font-size: 18px;\n line-height: 42px;\n text-align: center;\n background: #001529;\n border-radius: 0 2px 2px 0;\n cursor: pointer;\n transition: background 0.3s ease;\n}\n.ant-layout-sider-zero-width-trigger::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: transparent;\n transition: all 0.3s;\n content: '';\n}\n.ant-layout-sider-zero-width-trigger:hover::after {\n background: rgba(255, 255, 255, 0.1);\n}\n.ant-layout-sider-zero-width-trigger-right {\n left: -36px;\n border-radius: 2px 0 0 2px;\n}\n.ant-layout-sider-light {\n background: #fff;\n}\n.ant-layout-sider-light .ant-layout-sider-trigger {\n color: rgba(0, 0, 0, 0.85);\n background: #fff;\n}\n.ant-layout-sider-light .ant-layout-sider-zero-width-trigger {\n color: rgba(0, 0, 0, 0.85);\n background: #fff;\n}\n.ant-layout-rtl {\n direction: rtl;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-list {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n}\n.ant-list * {\n outline: none;\n}\n.ant-list-pagination {\n margin-top: 24px;\n text-align: right;\n}\n.ant-list-pagination .ant-pagination-options {\n text-align: left;\n}\n.ant-list-more {\n margin-top: 12px;\n text-align: center;\n}\n.ant-list-more button {\n padding-right: 32px;\n padding-left: 32px;\n}\n.ant-list-spin {\n min-height: 40px;\n text-align: center;\n}\n.ant-list-empty-text {\n padding: 16px;\n color: rgba(0, 0, 0, 0.25);\n font-size: 14px;\n text-align: center;\n}\n.ant-list-items {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ant-list-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 0;\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-list-item-meta {\n display: flex;\n flex: 1;\n align-items: flex-start;\n max-width: 100%;\n}\n.ant-list-item-meta-avatar {\n margin-right: 16px;\n}\n.ant-list-item-meta-content {\n flex: 1 0;\n width: 0;\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-list-item-meta-title {\n margin-bottom: 4px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n}\n.ant-list-item-meta-title > a {\n color: rgba(0, 0, 0, 0.85);\n transition: all 0.3s;\n}\n.ant-list-item-meta-title > a:hover {\n color: #1890ff;\n}\n.ant-list-item-meta-description {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.5715;\n}\n.ant-list-item-action {\n flex: 0 0 auto;\n margin-left: 48px;\n padding: 0;\n font-size: 0;\n list-style: none;\n}\n.ant-list-item-action > li {\n position: relative;\n display: inline-block;\n padding: 0 8px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.5715;\n text-align: center;\n}\n.ant-list-item-action > li:first-child {\n padding-left: 0;\n}\n.ant-list-item-action-split {\n position: absolute;\n top: 50%;\n right: 0;\n width: 1px;\n height: 14px;\n margin-top: -7px;\n background-color: #f0f0f0;\n}\n.ant-list-header {\n background: transparent;\n}\n.ant-list-footer {\n background: transparent;\n}\n.ant-list-header,\n.ant-list-footer {\n padding-top: 12px;\n padding-bottom: 12px;\n}\n.ant-list-empty {\n padding: 16px 0;\n color: rgba(0, 0, 0, 0.45);\n font-size: 12px;\n text-align: center;\n}\n.ant-list-split .ant-list-item {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-list-split .ant-list-item:last-child {\n border-bottom: none;\n}\n.ant-list-split .ant-list-header {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-list-split.ant-list-empty .ant-list-footer {\n border-top: 1px solid #f0f0f0;\n}\n.ant-list-loading .ant-list-spin-nested-loading {\n min-height: 32px;\n}\n.ant-list-split.ant-list-something-after-last-item .ant-spin-container > .ant-list-items > .ant-list-item:last-child {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-list-lg .ant-list-item {\n padding: 16px 24px;\n}\n.ant-list-sm .ant-list-item {\n padding: 8px 16px;\n}\n.ant-list-vertical .ant-list-item {\n align-items: initial;\n}\n.ant-list-vertical .ant-list-item-main {\n display: block;\n flex: 1;\n}\n.ant-list-vertical .ant-list-item-extra {\n margin-left: 40px;\n}\n.ant-list-vertical .ant-list-item-meta {\n margin-bottom: 16px;\n}\n.ant-list-vertical .ant-list-item-meta-title {\n margin-bottom: 12px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 16px;\n line-height: 24px;\n}\n.ant-list-vertical .ant-list-item-action {\n margin-top: 16px;\n margin-left: auto;\n}\n.ant-list-vertical .ant-list-item-action > li {\n padding: 0 16px;\n}\n.ant-list-vertical .ant-list-item-action > li:first-child {\n padding-left: 0;\n}\n.ant-list-grid .ant-col > .ant-list-item {\n display: block;\n max-width: 100%;\n margin-bottom: 16px;\n padding-top: 0;\n padding-bottom: 0;\n border-bottom: none;\n}\n.ant-list-item-no-flex {\n display: block;\n}\n.ant-list:not(.ant-list-vertical) .ant-list-item-no-flex .ant-list-item-action {\n float: right;\n}\n.ant-list-bordered {\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n}\n.ant-list-bordered .ant-list-header {\n padding-right: 24px;\n padding-left: 24px;\n}\n.ant-list-bordered .ant-list-footer {\n padding-right: 24px;\n padding-left: 24px;\n}\n.ant-list-bordered .ant-list-item {\n padding-right: 24px;\n padding-left: 24px;\n}\n.ant-list-bordered .ant-list-pagination {\n margin: 16px 24px;\n}\n.ant-list-bordered.ant-list-sm .ant-list-item {\n padding: 8px 16px;\n}\n.ant-list-bordered.ant-list-sm .ant-list-header,\n.ant-list-bordered.ant-list-sm .ant-list-footer {\n padding: 8px 16px;\n}\n.ant-list-bordered.ant-list-lg .ant-list-item {\n padding: 16px 24px;\n}\n.ant-list-bordered.ant-list-lg .ant-list-header,\n.ant-list-bordered.ant-list-lg .ant-list-footer {\n padding: 16px 24px;\n}\n@media screen and (max-width: 768px) {\n .ant-list-item-action {\n margin-left: 24px;\n }\n .ant-list-vertical .ant-list-item-extra {\n margin-left: 24px;\n }\n}\n@media screen and (max-width: 576px) {\n .ant-list-item {\n flex-wrap: wrap;\n }\n .ant-list-item-action {\n margin-left: 12px;\n }\n .ant-list-vertical .ant-list-item {\n flex-wrap: wrap-reverse;\n }\n .ant-list-vertical .ant-list-item-main {\n min-width: 220px;\n }\n .ant-list-vertical .ant-list-item-extra {\n margin: auto auto 16px;\n }\n}\n.ant-list-rtl {\n direction: rtl;\n text-align: right;\n}\n.ant-list-rtl .ReactVirtualized__List .ant-list-item {\n direction: rtl;\n}\n.ant-list-rtl .ant-list-pagination {\n text-align: left;\n}\n.ant-list-rtl .ant-list-item-meta-avatar {\n margin-right: 0;\n margin-left: 16px;\n}\n.ant-list-rtl .ant-list-item-action {\n margin-right: 48px;\n margin-left: 0;\n}\n.ant-list.ant-list-rtl .ant-list-item-action > li:first-child {\n padding-right: 0;\n padding-left: 16px;\n}\n.ant-list-rtl .ant-list-item-action-split {\n right: auto;\n left: 0;\n}\n.ant-list-rtl.ant-list-vertical .ant-list-item-extra {\n margin-right: 40px;\n margin-left: 0;\n}\n.ant-list-rtl.ant-list-vertical .ant-list-item-action {\n margin-right: auto;\n}\n.ant-list-rtl .ant-list-vertical .ant-list-item-action > li:first-child {\n padding-right: 0;\n padding-left: 16px;\n}\n.ant-list-rtl .ant-list:not(.ant-list-vertical) .ant-list-item-no-flex .ant-list-item-action {\n float: left;\n}\n@media screen and (max-width: 768px) {\n .ant-list-rtl .ant-list-item-action {\n margin-right: 24px;\n margin-left: 0;\n }\n .ant-list-rtl .ant-list-vertical .ant-list-item-extra {\n margin-right: 24px;\n margin-left: 0;\n }\n}\n@media screen and (max-width: 576px) {\n .ant-list-rtl .ant-list-item-action {\n margin-right: 22px;\n margin-left: 0;\n }\n .ant-list-rtl.ant-list-vertical .ant-list-item-extra {\n margin: auto auto 16px;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-pagination {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n}\n.ant-pagination ul,\n.ant-pagination ol {\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ant-pagination::after {\n display: block;\n clear: both;\n height: 0;\n overflow: hidden;\n visibility: hidden;\n content: ' ';\n}\n.ant-pagination-total-text {\n display: inline-block;\n height: 32px;\n margin-right: 8px;\n line-height: 30px;\n vertical-align: middle;\n}\n.ant-pagination-item {\n display: inline-block;\n min-width: 32px;\n height: 32px;\n margin-right: 8px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n line-height: 30px;\n text-align: center;\n vertical-align: middle;\n list-style: none;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n outline: 0;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-pagination-item a {\n display: block;\n padding: 0 6px;\n color: rgba(0, 0, 0, 0.85);\n transition: none;\n}\n.ant-pagination-item a:hover {\n text-decoration: none;\n}\n.ant-pagination-item:hover {\n border-color: #1890ff;\n transition: all 0.3s;\n}\n.ant-pagination-item:hover a {\n color: #1890ff;\n}\n.ant-pagination-item:focus-visible {\n border-color: #1890ff;\n transition: all 0.3s;\n}\n.ant-pagination-item:focus-visible a {\n color: #1890ff;\n}\n.ant-pagination-item-active {\n font-weight: 500;\n background: #fff;\n border-color: #1890ff;\n}\n.ant-pagination-item-active a {\n color: #1890ff;\n}\n.ant-pagination-item-active:hover {\n border-color: #40a9ff;\n}\n.ant-pagination-item-active:focus-visible {\n border-color: #40a9ff;\n}\n.ant-pagination-item-active:hover a {\n color: #40a9ff;\n}\n.ant-pagination-item-active:focus-visible a {\n color: #40a9ff;\n}\n.ant-pagination-jump-prev,\n.ant-pagination-jump-next {\n outline: 0;\n}\n.ant-pagination-jump-prev .ant-pagination-item-container,\n.ant-pagination-jump-next .ant-pagination-item-container {\n position: relative;\n}\n.ant-pagination-jump-prev .ant-pagination-item-container .ant-pagination-item-link-icon,\n.ant-pagination-jump-next .ant-pagination-item-container .ant-pagination-item-link-icon {\n color: #1890ff;\n font-size: 12px;\n letter-spacing: -1px;\n opacity: 0;\n transition: all 0.2s;\n}\n.ant-pagination-jump-prev .ant-pagination-item-container .ant-pagination-item-link-icon-svg,\n.ant-pagination-jump-next .ant-pagination-item-container .ant-pagination-item-link-icon-svg {\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n margin: auto;\n}\n.ant-pagination-jump-prev .ant-pagination-item-container .ant-pagination-item-ellipsis,\n.ant-pagination-jump-next .ant-pagination-item-container .ant-pagination-item-ellipsis {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n display: block;\n margin: auto;\n color: rgba(0, 0, 0, 0.25);\n font-family: Arial, Helvetica, sans-serif;\n letter-spacing: 2px;\n text-align: center;\n text-indent: 0.13em;\n opacity: 1;\n transition: all 0.2s;\n}\n.ant-pagination-jump-prev:hover .ant-pagination-item-link-icon,\n.ant-pagination-jump-next:hover .ant-pagination-item-link-icon {\n opacity: 1;\n}\n.ant-pagination-jump-prev:hover .ant-pagination-item-ellipsis,\n.ant-pagination-jump-next:hover .ant-pagination-item-ellipsis {\n opacity: 0;\n}\n.ant-pagination-jump-prev:focus-visible .ant-pagination-item-link-icon,\n.ant-pagination-jump-next:focus-visible .ant-pagination-item-link-icon {\n opacity: 1;\n}\n.ant-pagination-jump-prev:focus-visible .ant-pagination-item-ellipsis,\n.ant-pagination-jump-next:focus-visible .ant-pagination-item-ellipsis {\n opacity: 0;\n}\n.ant-pagination-prev,\n.ant-pagination-jump-prev,\n.ant-pagination-jump-next {\n margin-right: 8px;\n}\n.ant-pagination-prev,\n.ant-pagination-next,\n.ant-pagination-jump-prev,\n.ant-pagination-jump-next {\n display: inline-block;\n min-width: 32px;\n height: 32px;\n color: rgba(0, 0, 0, 0.85);\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n line-height: 32px;\n text-align: center;\n vertical-align: middle;\n list-style: none;\n border-radius: 2px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-pagination-prev,\n.ant-pagination-next {\n font-family: Arial, Helvetica, sans-serif;\n outline: 0;\n}\n.ant-pagination-prev button,\n.ant-pagination-next button {\n color: rgba(0, 0, 0, 0.85);\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-pagination-prev:hover button,\n.ant-pagination-next:hover button {\n border-color: #40a9ff;\n}\n.ant-pagination-prev .ant-pagination-item-link,\n.ant-pagination-next .ant-pagination-item-link {\n display: block;\n width: 100%;\n height: 100%;\n padding: 0;\n font-size: 12px;\n text-align: center;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n outline: none;\n transition: all 0.3s;\n}\n.ant-pagination-prev:focus-visible .ant-pagination-item-link,\n.ant-pagination-next:focus-visible .ant-pagination-item-link {\n color: #1890ff;\n border-color: #1890ff;\n}\n.ant-pagination-prev:hover .ant-pagination-item-link,\n.ant-pagination-next:hover .ant-pagination-item-link {\n color: #1890ff;\n border-color: #1890ff;\n}\n.ant-pagination-disabled,\n.ant-pagination-disabled:hover {\n cursor: not-allowed;\n}\n.ant-pagination-disabled .ant-pagination-item-link,\n.ant-pagination-disabled:hover .ant-pagination-item-link {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-pagination-disabled:focus-visible {\n cursor: not-allowed;\n}\n.ant-pagination-disabled:focus-visible .ant-pagination-item-link {\n color: rgba(0, 0, 0, 0.25);\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-pagination-slash {\n margin: 0 10px 0 5px;\n}\n.ant-pagination-options {\n display: inline-block;\n margin-left: 16px;\n vertical-align: middle;\n}\n@media all and (-ms-high-contrast: none) {\n .ant-pagination-options *::-ms-backdrop,\n .ant-pagination-options {\n vertical-align: top;\n }\n}\n.ant-pagination-options-size-changer.ant-select {\n display: inline-block;\n width: auto;\n}\n.ant-pagination-options-quick-jumper {\n display: inline-block;\n height: 32px;\n margin-left: 8px;\n line-height: 32px;\n vertical-align: top;\n}\n.ant-pagination-options-quick-jumper input {\n position: relative;\n display: inline-block;\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n line-height: 1.5715;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n width: 50px;\n height: 32px;\n margin: 0 8px;\n}\n.ant-pagination-options-quick-jumper input::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-pagination-options-quick-jumper input:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-pagination-options-quick-jumper input::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-pagination-options-quick-jumper input:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-pagination-options-quick-jumper input:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-pagination-options-quick-jumper input:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-pagination-options-quick-jumper input:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-pagination-options-quick-jumper input:focus,\n.ant-pagination-options-quick-jumper input-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-pagination-options-quick-jumper input-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-pagination-options-quick-jumper input-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-pagination-options-quick-jumper input[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-pagination-options-quick-jumper input[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-pagination-options-quick-jumper input-borderless,\n.ant-pagination-options-quick-jumper input-borderless:hover,\n.ant-pagination-options-quick-jumper input-borderless:focus,\n.ant-pagination-options-quick-jumper input-borderless-focused,\n.ant-pagination-options-quick-jumper input-borderless-disabled,\n.ant-pagination-options-quick-jumper input-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-pagination-options-quick-jumper input {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-pagination-options-quick-jumper input-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-pagination-options-quick-jumper input-sm {\n padding: 0px 7px;\n}\n.ant-pagination-simple .ant-pagination-prev,\n.ant-pagination-simple .ant-pagination-next {\n height: 24px;\n line-height: 24px;\n vertical-align: top;\n}\n.ant-pagination-simple .ant-pagination-prev .ant-pagination-item-link,\n.ant-pagination-simple .ant-pagination-next .ant-pagination-item-link {\n height: 24px;\n background-color: transparent;\n border: 0;\n}\n.ant-pagination-simple .ant-pagination-prev .ant-pagination-item-link::after,\n.ant-pagination-simple .ant-pagination-next .ant-pagination-item-link::after {\n height: 24px;\n line-height: 24px;\n}\n.ant-pagination-simple .ant-pagination-simple-pager {\n display: inline-block;\n height: 24px;\n margin-right: 8px;\n}\n.ant-pagination-simple .ant-pagination-simple-pager input {\n box-sizing: border-box;\n height: 100%;\n margin-right: 8px;\n padding: 0 6px;\n text-align: center;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n outline: none;\n transition: border-color 0.3s;\n}\n.ant-pagination-simple .ant-pagination-simple-pager input:hover {\n border-color: #1890ff;\n}\n.ant-pagination-simple .ant-pagination-simple-pager input:focus {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n}\n.ant-pagination-simple .ant-pagination-simple-pager input[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background: #f5f5f5;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-total-text,\n.ant-pagination.ant-pagination-mini .ant-pagination-simple-pager {\n height: 24px;\n line-height: 24px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-item {\n min-width: 24px;\n height: 24px;\n margin: 0;\n line-height: 22px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-item:not(.ant-pagination-item-active) {\n background: transparent;\n border-color: transparent;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-prev,\n.ant-pagination.ant-pagination-mini .ant-pagination-next {\n min-width: 24px;\n height: 24px;\n margin: 0;\n line-height: 24px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-prev .ant-pagination-item-link,\n.ant-pagination.ant-pagination-mini .ant-pagination-next .ant-pagination-item-link {\n background: transparent;\n border-color: transparent;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-prev .ant-pagination-item-link::after,\n.ant-pagination.ant-pagination-mini .ant-pagination-next .ant-pagination-item-link::after {\n height: 24px;\n line-height: 24px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-jump-prev,\n.ant-pagination.ant-pagination-mini .ant-pagination-jump-next {\n height: 24px;\n margin-right: 0;\n line-height: 24px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-options {\n margin-left: 2px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-options-size-changer {\n top: 0px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-options-quick-jumper {\n height: 24px;\n line-height: 24px;\n}\n.ant-pagination.ant-pagination-mini .ant-pagination-options-quick-jumper input {\n padding: 0px 7px;\n width: 44px;\n height: 24px;\n}\n.ant-pagination.ant-pagination-disabled {\n cursor: not-allowed;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item {\n background: #f5f5f5;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item a {\n color: rgba(0, 0, 0, 0.25);\n background: transparent;\n border: none;\n cursor: not-allowed;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item-active {\n background: #e6e6e6;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item-active a {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item-link {\n color: rgba(0, 0, 0, 0.25);\n background: #f5f5f5;\n border-color: #d9d9d9;\n cursor: not-allowed;\n}\n.ant-pagination-simple.ant-pagination.ant-pagination-disabled .ant-pagination-item-link {\n background: transparent;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item-link-icon {\n opacity: 0;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-item-ellipsis {\n opacity: 1;\n}\n.ant-pagination.ant-pagination-disabled .ant-pagination-simple-pager {\n color: rgba(0, 0, 0, 0.25);\n}\n@media only screen and (max-width: 992px) {\n .ant-pagination-item-after-jump-prev,\n .ant-pagination-item-before-jump-next {\n display: none;\n }\n}\n@media only screen and (max-width: 576px) {\n .ant-pagination-options {\n display: none;\n }\n}\n.ant-pagination-rtl .ant-pagination-total-text {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-pagination-rtl .ant-pagination-item,\n.ant-pagination-rtl .ant-pagination-prev,\n.ant-pagination-rtl .ant-pagination-jump-prev,\n.ant-pagination-rtl .ant-pagination-jump-next {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-pagination-rtl .ant-pagination-slash {\n margin: 0 5px 0 10px;\n}\n.ant-pagination-rtl .ant-pagination-options {\n margin-right: 16px;\n margin-left: 0;\n}\n.ant-pagination-rtl .ant-pagination-options .ant-pagination-options-size-changer.ant-select {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-pagination-rtl .ant-pagination-options .ant-pagination-options-quick-jumper {\n margin-left: 0;\n}\n.ant-pagination-rtl.ant-pagination-simple .ant-pagination-simple-pager {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-pagination-rtl.ant-pagination-simple .ant-pagination-simple-pager input {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-pagination-rtl.ant-pagination.mini .ant-pagination-options {\n margin-right: 2px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-spin {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n display: none;\n color: #1890ff;\n text-align: center;\n vertical-align: middle;\n opacity: 0;\n transition: transform 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);\n}\n.ant-spin-spinning {\n position: static;\n display: inline-block;\n opacity: 1;\n}\n.ant-spin-nested-loading {\n position: relative;\n}\n.ant-spin-nested-loading > div > .ant-spin {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 4;\n display: block;\n width: 100%;\n height: 100%;\n max-height: 400px;\n}\n.ant-spin-nested-loading > div > .ant-spin .ant-spin-dot {\n position: absolute;\n top: 50%;\n left: 50%;\n margin: -10px;\n}\n.ant-spin-nested-loading > div > .ant-spin .ant-spin-text {\n position: absolute;\n top: 50%;\n width: 100%;\n padding-top: 5px;\n text-shadow: 0 1px 2px #fff;\n}\n.ant-spin-nested-loading > div > .ant-spin.ant-spin-show-text .ant-spin-dot {\n margin-top: -20px;\n}\n.ant-spin-nested-loading > div > .ant-spin-sm .ant-spin-dot {\n margin: -7px;\n}\n.ant-spin-nested-loading > div > .ant-spin-sm .ant-spin-text {\n padding-top: 2px;\n}\n.ant-spin-nested-loading > div > .ant-spin-sm.ant-spin-show-text .ant-spin-dot {\n margin-top: -17px;\n}\n.ant-spin-nested-loading > div > .ant-spin-lg .ant-spin-dot {\n margin: -16px;\n}\n.ant-spin-nested-loading > div > .ant-spin-lg .ant-spin-text {\n padding-top: 11px;\n}\n.ant-spin-nested-loading > div > .ant-spin-lg.ant-spin-show-text .ant-spin-dot {\n margin-top: -26px;\n}\n.ant-spin-container {\n position: relative;\n transition: opacity 0.3s;\n}\n.ant-spin-container::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 10;\n display: none \\9;\n width: 100%;\n height: 100%;\n background: #fff;\n opacity: 0;\n transition: all 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-spin-blur {\n clear: both;\n opacity: 0.5;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n pointer-events: none;\n}\n.ant-spin-blur::after {\n opacity: 0.4;\n pointer-events: auto;\n}\n.ant-spin-tip {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-spin-dot {\n position: relative;\n display: inline-block;\n font-size: 20px;\n width: 1em;\n height: 1em;\n}\n.ant-spin-dot-item {\n position: absolute;\n display: block;\n width: 9px;\n height: 9px;\n background-color: #1890ff;\n border-radius: 100%;\n transform: scale(0.75);\n transform-origin: 50% 50%;\n opacity: 0.3;\n animation: antSpinMove 1s infinite linear alternate;\n}\n.ant-spin-dot-item:nth-child(1) {\n top: 0;\n left: 0;\n}\n.ant-spin-dot-item:nth-child(2) {\n top: 0;\n right: 0;\n animation-delay: 0.4s;\n}\n.ant-spin-dot-item:nth-child(3) {\n right: 0;\n bottom: 0;\n animation-delay: 0.8s;\n}\n.ant-spin-dot-item:nth-child(4) {\n bottom: 0;\n left: 0;\n animation-delay: 1.2s;\n}\n.ant-spin-dot-spin {\n transform: rotate(0deg);\n animation: antRotate 1.2s infinite linear;\n}\n.ant-spin-sm .ant-spin-dot {\n font-size: 14px;\n}\n.ant-spin-sm .ant-spin-dot i {\n width: 6px;\n height: 6px;\n}\n.ant-spin-lg .ant-spin-dot {\n font-size: 32px;\n}\n.ant-spin-lg .ant-spin-dot i {\n width: 14px;\n height: 14px;\n}\n.ant-spin.ant-spin-show-text .ant-spin-text {\n display: block;\n}\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n /* IE10+ */\n .ant-spin-blur {\n background: #fff;\n opacity: 0.5;\n }\n}\n@keyframes antSpinMove {\n to {\n opacity: 1;\n }\n}\n@keyframes antRotate {\n to {\n transform: rotate(360deg);\n }\n}\n.ant-spin-rtl {\n direction: rtl;\n}\n.ant-spin-rtl .ant-spin-dot-spin {\n transform: rotate(-45deg);\n animation-name: antRotateRtl;\n}\n@keyframes antRotateRtl {\n to {\n transform: rotate(-405deg);\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-mentions-status-error:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions,\n.ant-mentions-status-error:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions:hover {\n background: #fff;\n border-color: #ff4d4f;\n}\n.ant-mentions-status-error:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions:focus,\n.ant-mentions-status-error:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions-focused {\n border-color: #ff7875;\n box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-mentions-status-error .ant-input-prefix {\n color: #ff4d4f;\n}\n.ant-mentions-status-warning:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions,\n.ant-mentions-status-warning:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions:hover {\n background: #fff;\n border-color: #faad14;\n}\n.ant-mentions-status-warning:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions:focus,\n.ant-mentions-status-warning:not(.ant-mentions-disabled):not(.ant-mentions-borderless).ant-mentions-focused {\n border-color: #ffc53d;\n box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-mentions-status-warning .ant-input-prefix {\n color: #faad14;\n}\n.ant-mentions {\n box-sizing: border-box;\n margin: 0;\n font-variant: tabular-nums;\n list-style: none;\n font-feature-settings: 'tnum';\n width: 100%;\n min-width: 0;\n padding: 4px 11px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n background-color: #fff;\n background-image: none;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n transition: all 0.3s;\n position: relative;\n display: inline-block;\n height: auto;\n padding: 0;\n overflow: hidden;\n line-height: 1.5715;\n white-space: pre-wrap;\n vertical-align: bottom;\n}\n.ant-mentions::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-mentions:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-mentions::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-mentions:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-mentions:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-mentions:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-mentions:hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-mentions:focus,\n.ant-mentions-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-mentions-disabled {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-mentions-disabled:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-mentions[disabled] {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-mentions[disabled]:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-mentions-borderless,\n.ant-mentions-borderless:hover,\n.ant-mentions-borderless:focus,\n.ant-mentions-borderless-focused,\n.ant-mentions-borderless-disabled,\n.ant-mentions-borderless[disabled] {\n background-color: transparent;\n border: none;\n box-shadow: none;\n}\ntextarea.ant-mentions {\n max-width: 100%;\n height: auto;\n min-height: 32px;\n line-height: 1.5715;\n vertical-align: bottom;\n transition: all 0.3s, height 0s;\n}\n.ant-mentions-lg {\n padding: 6.5px 11px;\n font-size: 16px;\n}\n.ant-mentions-sm {\n padding: 0px 7px;\n}\n.ant-mentions-disabled > textarea {\n color: rgba(0, 0, 0, 0.25);\n background-color: #f5f5f5;\n border-color: #d9d9d9;\n box-shadow: none;\n cursor: not-allowed;\n opacity: 1;\n}\n.ant-mentions-disabled > textarea:hover {\n border-color: #d9d9d9;\n border-right-width: 1px;\n}\n.ant-mentions-focused {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-mentions > textarea,\n.ant-mentions-measure {\n min-height: 30px;\n margin: 0;\n padding: 4px 11px;\n overflow: inherit;\n overflow-x: hidden;\n overflow-y: auto;\n /* stylelint-disable declaration-block-no-redundant-longhand-properties */\n font-weight: inherit;\n font-size: inherit;\n font-family: inherit;\n font-style: inherit;\n font-variant: inherit;\n font-size-adjust: inherit;\n font-stretch: inherit;\n line-height: inherit;\n /* stylelint-enable declaration-block-no-redundant-longhand-properties */\n direction: inherit;\n letter-spacing: inherit;\n white-space: inherit;\n text-align: inherit;\n vertical-align: top;\n word-wrap: break-word;\n word-break: inherit;\n -moz-tab-size: inherit;\n -o-tab-size: inherit;\n tab-size: inherit;\n}\n.ant-mentions > textarea {\n width: 100%;\n border: none;\n outline: none;\n resize: none;\n}\n.ant-mentions > textarea::-moz-placeholder {\n color: #bfbfbf;\n -moz-user-select: none;\n user-select: none;\n}\n.ant-mentions > textarea:-ms-input-placeholder {\n color: #bfbfbf;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-mentions > textarea::placeholder {\n color: #bfbfbf;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-mentions > textarea:-moz-placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-mentions > textarea:-ms-input-placeholder {\n text-overflow: ellipsis;\n}\n.ant-mentions > textarea:placeholder-shown {\n text-overflow: ellipsis;\n}\n.ant-mentions-measure {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: -1;\n color: transparent;\n pointer-events: none;\n}\n.ant-mentions-measure > span {\n display: inline-block;\n min-height: 1em;\n}\n.ant-mentions-dropdown {\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: absolute;\n top: -9999px;\n left: -9999px;\n z-index: 1050;\n box-sizing: border-box;\n font-size: 14px;\n font-variant: initial;\n background-color: #fff;\n border-radius: 2px;\n outline: none;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-mentions-dropdown-hidden {\n display: none;\n}\n.ant-mentions-dropdown-menu {\n max-height: 250px;\n margin-bottom: 0;\n padding-left: 0;\n overflow: auto;\n list-style: none;\n outline: none;\n}\n.ant-mentions-dropdown-menu-item {\n position: relative;\n display: block;\n min-width: 100px;\n padding: 5px 12px;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n font-weight: normal;\n line-height: 1.5715;\n white-space: nowrap;\n text-overflow: ellipsis;\n cursor: pointer;\n transition: background 0.3s ease;\n}\n.ant-mentions-dropdown-menu-item:hover {\n background-color: #f5f5f5;\n}\n.ant-mentions-dropdown-menu-item:first-child {\n border-radius: 2px 2px 0 0;\n}\n.ant-mentions-dropdown-menu-item:last-child {\n border-radius: 0 0 2px 2px;\n}\n.ant-mentions-dropdown-menu-item-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-mentions-dropdown-menu-item-disabled:hover {\n color: rgba(0, 0, 0, 0.25);\n background-color: #fff;\n cursor: not-allowed;\n}\n.ant-mentions-dropdown-menu-item-selected {\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n background-color: #fafafa;\n}\n.ant-mentions-dropdown-menu-item-active {\n background-color: #f5f5f5;\n}\n.ant-mentions-suffix {\n position: absolute;\n top: 0;\n right: 11px;\n bottom: 0;\n z-index: 1;\n display: inline-flex;\n align-items: center;\n margin: auto;\n}\n.ant-mentions-rtl {\n direction: rtl;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-message {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: fixed;\n top: 8px;\n left: 0;\n z-index: 1010;\n width: 100%;\n pointer-events: none;\n}\n.ant-message-notice {\n padding: 8px;\n text-align: center;\n}\n.ant-message-notice-content {\n display: inline-block;\n padding: 10px 16px;\n background: #fff;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n pointer-events: all;\n}\n.ant-message-success .anticon {\n color: #52c41a;\n}\n.ant-message-error .anticon {\n color: #ff4d4f;\n}\n.ant-message-warning .anticon {\n color: #faad14;\n}\n.ant-message-info .anticon,\n.ant-message-loading .anticon {\n color: #1890ff;\n}\n.ant-message .anticon {\n position: relative;\n top: 1px;\n margin-right: 8px;\n font-size: 16px;\n}\n.ant-message-notice.ant-move-up-leave.ant-move-up-leave-active {\n animation-name: MessageMoveOut;\n animation-duration: 0.3s;\n}\n@keyframes MessageMoveOut {\n 0% {\n max-height: 150px;\n padding: 8px;\n opacity: 1;\n }\n 100% {\n max-height: 0;\n padding: 0;\n opacity: 0;\n }\n}\n.ant-message-rtl {\n direction: rtl;\n}\n.ant-message-rtl span {\n direction: rtl;\n}\n.ant-message-rtl .anticon {\n margin-right: 0;\n margin-left: 8px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-modal {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n pointer-events: none;\n position: relative;\n top: 100px;\n width: auto;\n max-width: calc(100vw - 32px);\n margin: 0 auto;\n padding-bottom: 24px;\n}\n.ant-modal.ant-zoom-enter,\n.ant-modal.ant-zoom-appear {\n transform: none;\n opacity: 0;\n animation-duration: 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-modal-mask {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1000;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.45);\n}\n.ant-modal-mask-hidden {\n display: none;\n}\n.ant-modal-wrap {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n overflow: auto;\n outline: 0;\n}\n.ant-modal-wrap {\n z-index: 1000;\n}\n.ant-modal-title {\n margin: 0;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n line-height: 22px;\n word-wrap: break-word;\n}\n.ant-modal-content {\n position: relative;\n background-color: #fff;\n background-clip: padding-box;\n border: 0;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n pointer-events: auto;\n}\n.ant-modal-close {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 10;\n padding: 0;\n color: rgba(0, 0, 0, 0.45);\n font-weight: 700;\n line-height: 1;\n text-decoration: none;\n background: transparent;\n border: 0;\n outline: 0;\n cursor: pointer;\n transition: color 0.3s;\n}\n.ant-modal-close-x {\n display: block;\n width: 54px;\n height: 54px;\n font-size: 16px;\n font-style: normal;\n line-height: 54px;\n text-align: center;\n text-transform: none;\n text-rendering: auto;\n}\n.ant-modal-close:focus,\n.ant-modal-close:hover {\n color: rgba(0, 0, 0, 0.75);\n text-decoration: none;\n}\n.ant-modal-header {\n padding: 16px 24px;\n color: rgba(0, 0, 0, 0.85);\n background: #fff;\n border-bottom: 1px solid #f0f0f0;\n border-radius: 2px 2px 0 0;\n}\n.ant-modal-body {\n padding: 24px;\n font-size: 14px;\n line-height: 1.5715;\n word-wrap: break-word;\n}\n.ant-modal-footer {\n padding: 10px 16px;\n text-align: right;\n background: transparent;\n border-top: 1px solid #f0f0f0;\n border-radius: 0 0 2px 2px;\n}\n.ant-modal-footer .ant-btn + .ant-btn:not(.ant-dropdown-trigger) {\n margin-bottom: 0;\n margin-left: 8px;\n}\n.ant-modal-open {\n overflow: hidden;\n}\n.ant-modal-centered {\n text-align: center;\n}\n.ant-modal-centered::before {\n display: inline-block;\n width: 0;\n height: 100%;\n vertical-align: middle;\n content: '';\n}\n.ant-modal-centered .ant-modal {\n top: 0;\n display: inline-block;\n padding-bottom: 0;\n text-align: left;\n vertical-align: middle;\n}\n@media (max-width: 767px) {\n .ant-modal {\n max-width: calc(100vw - 16px);\n margin: 8px auto;\n }\n .ant-modal-centered .ant-modal {\n flex: 1;\n }\n}\n.ant-modal-confirm .ant-modal-header {\n display: none;\n}\n.ant-modal-confirm .ant-modal-body {\n padding: 32px 32px 24px;\n}\n.ant-modal-confirm-body-wrapper::before {\n display: table;\n content: '';\n}\n.ant-modal-confirm-body-wrapper::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-modal-confirm-body .ant-modal-confirm-title {\n display: block;\n overflow: hidden;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n font-size: 16px;\n line-height: 1.4;\n}\n.ant-modal-confirm-body .ant-modal-confirm-content {\n margin-top: 8px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n}\n.ant-modal-confirm-body > .anticon {\n float: left;\n margin-right: 16px;\n font-size: 22px;\n}\n.ant-modal-confirm-body > .anticon + .ant-modal-confirm-title + .ant-modal-confirm-content {\n margin-left: 38px;\n}\n.ant-modal-confirm .ant-modal-confirm-btns {\n margin-top: 24px;\n text-align: right;\n}\n.ant-modal-confirm .ant-modal-confirm-btns .ant-btn + .ant-btn {\n margin-bottom: 0;\n margin-left: 8px;\n}\n.ant-modal-confirm-error .ant-modal-confirm-body > .anticon {\n color: #ff4d4f;\n}\n.ant-modal-confirm-warning .ant-modal-confirm-body > .anticon,\n.ant-modal-confirm-confirm .ant-modal-confirm-body > .anticon {\n color: #faad14;\n}\n.ant-modal-confirm-info .ant-modal-confirm-body > .anticon {\n color: #1890ff;\n}\n.ant-modal-confirm-success .ant-modal-confirm-body > .anticon {\n color: #52c41a;\n}\n.ant-modal-confirm .ant-zoom-leave .ant-modal-confirm-btns {\n pointer-events: none;\n}\n.ant-modal-wrap-rtl {\n direction: rtl;\n}\n.ant-modal-wrap-rtl .ant-modal-close {\n right: initial;\n left: 0;\n}\n.ant-modal-wrap-rtl .ant-modal-footer {\n text-align: left;\n}\n.ant-modal-wrap-rtl .ant-modal-footer .ant-btn + .ant-btn {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-modal-wrap-rtl .ant-modal-confirm-body {\n direction: rtl;\n}\n.ant-modal-wrap-rtl .ant-modal-confirm-body > .anticon {\n float: right;\n margin-right: 0;\n margin-left: 16px;\n}\n.ant-modal-wrap-rtl .ant-modal-confirm-body > .anticon + .ant-modal-confirm-title + .ant-modal-confirm-content {\n margin-right: 38px;\n margin-left: 0;\n}\n.ant-modal-wrap-rtl .ant-modal-confirm-btns {\n text-align: left;\n}\n.ant-modal-wrap-rtl .ant-modal-confirm-btns .ant-btn + .ant-btn {\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-modal-wrap-rtl.ant-modal-centered .ant-modal {\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-notification {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: fixed;\n z-index: 1010;\n margin-right: 24px;\n}\n.ant-notification-close-icon {\n font-size: 14px;\n cursor: pointer;\n}\n.ant-notification-hook-holder {\n position: relative;\n}\n.ant-notification-notice {\n position: relative;\n width: 384px;\n max-width: calc(100vw - 24px * 2);\n margin-bottom: 16px;\n margin-left: auto;\n padding: 16px 24px;\n overflow: hidden;\n line-height: 1.5715;\n word-wrap: break-word;\n background: #fff;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-notification-top .ant-notification-notice,\n.ant-notification-bottom .ant-notification-notice {\n margin-right: auto;\n margin-left: auto;\n}\n.ant-notification-topLeft .ant-notification-notice,\n.ant-notification-bottomLeft .ant-notification-notice {\n margin-right: auto;\n margin-left: 0;\n}\n.ant-notification-notice-message {\n margin-bottom: 8px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 16px;\n line-height: 24px;\n}\n.ant-notification-notice-message-single-line-auto-margin {\n display: block;\n width: calc(384px - 24px * 2 - 24px - 48px - 100%);\n max-width: 4px;\n background-color: transparent;\n pointer-events: none;\n}\n.ant-notification-notice-message-single-line-auto-margin::before {\n display: block;\n content: '';\n}\n.ant-notification-notice-description {\n font-size: 14px;\n}\n.ant-notification-notice-closable .ant-notification-notice-message {\n padding-right: 24px;\n}\n.ant-notification-notice-with-icon .ant-notification-notice-message {\n margin-bottom: 4px;\n margin-left: 48px;\n font-size: 16px;\n}\n.ant-notification-notice-with-icon .ant-notification-notice-description {\n margin-left: 48px;\n font-size: 14px;\n}\n.ant-notification-notice-icon {\n position: absolute;\n margin-left: 4px;\n font-size: 24px;\n line-height: 24px;\n}\n.anticon.ant-notification-notice-icon-success {\n color: #52c41a;\n}\n.anticon.ant-notification-notice-icon-info {\n color: #1890ff;\n}\n.anticon.ant-notification-notice-icon-warning {\n color: #faad14;\n}\n.anticon.ant-notification-notice-icon-error {\n color: #ff4d4f;\n}\n.ant-notification-notice-close {\n position: absolute;\n top: 16px;\n right: 22px;\n color: rgba(0, 0, 0, 0.45);\n outline: none;\n}\n.ant-notification-notice-close:hover {\n color: rgba(0, 0, 0, 0.67);\n}\n.ant-notification-notice-btn {\n float: right;\n margin-top: 16px;\n}\n.ant-notification .notification-fade-effect {\n animation-duration: 0.24s;\n animation-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);\n animation-fill-mode: both;\n}\n.ant-notification-fade-enter,\n.ant-notification-fade-appear {\n animation-duration: 0.24s;\n animation-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);\n animation-fill-mode: both;\n opacity: 0;\n animation-play-state: paused;\n}\n.ant-notification-fade-leave {\n animation-duration: 0.24s;\n animation-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);\n animation-fill-mode: both;\n animation-duration: 0.2s;\n animation-play-state: paused;\n}\n.ant-notification-fade-enter.ant-notification-fade-enter-active,\n.ant-notification-fade-appear.ant-notification-fade-appear-active {\n animation-name: NotificationFadeIn;\n animation-play-state: running;\n}\n.ant-notification-fade-leave.ant-notification-fade-leave-active {\n animation-name: NotificationFadeOut;\n animation-play-state: running;\n}\n@keyframes NotificationFadeIn {\n 0% {\n left: 384px;\n opacity: 0;\n }\n 100% {\n left: 0;\n opacity: 1;\n }\n}\n@keyframes NotificationFadeOut {\n 0% {\n max-height: 150px;\n margin-bottom: 16px;\n opacity: 1;\n }\n 100% {\n max-height: 0;\n margin-bottom: 0;\n padding-top: 0;\n padding-bottom: 0;\n opacity: 0;\n }\n}\n.ant-notification-rtl {\n direction: rtl;\n}\n.ant-notification-rtl .ant-notification-notice-closable .ant-notification-notice-message {\n padding-right: 0;\n padding-left: 24px;\n}\n.ant-notification-rtl .ant-notification-notice-with-icon .ant-notification-notice-message {\n margin-right: 48px;\n margin-left: 0;\n}\n.ant-notification-rtl .ant-notification-notice-with-icon .ant-notification-notice-description {\n margin-right: 48px;\n margin-left: 0;\n}\n.ant-notification-rtl .ant-notification-notice-icon {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-notification-rtl .ant-notification-notice-close {\n right: auto;\n left: 22px;\n}\n.ant-notification-rtl .ant-notification-notice-btn {\n float: left;\n}\n.ant-notification-top,\n.ant-notification-bottom {\n margin-right: 0;\n margin-left: 0;\n}\n.ant-notification-top .ant-notification-fade-enter.ant-notification-fade-enter-active,\n.ant-notification-top .ant-notification-fade-appear.ant-notification-fade-appear-active {\n animation-name: NotificationTopFadeIn;\n}\n.ant-notification-bottom .ant-notification-fade-enter.ant-notification-fade-enter-active,\n.ant-notification-bottom .ant-notification-fade-appear.ant-notification-fade-appear-active {\n animation-name: NotificationBottomFadeIn;\n}\n.ant-notification-topLeft,\n.ant-notification-bottomLeft {\n margin-right: 0;\n margin-left: 24px;\n}\n.ant-notification-topLeft .ant-notification-fade-enter.ant-notification-fade-enter-active,\n.ant-notification-bottomLeft .ant-notification-fade-enter.ant-notification-fade-enter-active,\n.ant-notification-topLeft .ant-notification-fade-appear.ant-notification-fade-appear-active,\n.ant-notification-bottomLeft .ant-notification-fade-appear.ant-notification-fade-appear-active {\n animation-name: NotificationLeftFadeIn;\n}\n@keyframes NotificationTopFadeIn {\n 0% {\n margin-top: -100%;\n opacity: 0;\n }\n 100% {\n margin-top: 0;\n opacity: 1;\n }\n}\n@keyframes NotificationBottomFadeIn {\n 0% {\n margin-bottom: -100%;\n opacity: 0;\n }\n 100% {\n margin-bottom: 0;\n opacity: 1;\n }\n}\n@keyframes NotificationLeftFadeIn {\n 0% {\n right: 384px;\n opacity: 0;\n }\n 100% {\n right: 0;\n opacity: 1;\n }\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-page-header {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n padding: 16px 24px;\n background-color: #fff;\n}\n.ant-page-header-ghost {\n background-color: inherit;\n}\n.ant-page-header.has-breadcrumb {\n padding-top: 12px;\n}\n.ant-page-header.has-footer {\n padding-bottom: 0;\n}\n.ant-page-header-back {\n margin-right: 16px;\n font-size: 16px;\n line-height: 1;\n}\n.ant-page-header-back-button {\n color: #1890ff;\n outline: none;\n cursor: pointer;\n transition: color 0.3s;\n color: #000;\n}\n.ant-page-header-back-button:focus-visible,\n.ant-page-header-back-button:hover {\n color: #40a9ff;\n}\n.ant-page-header-back-button:active {\n color: #096dd9;\n}\n.ant-page-header .ant-divider-vertical {\n height: 14px;\n margin: 0 12px;\n vertical-align: middle;\n}\n.ant-breadcrumb + .ant-page-header-heading {\n margin-top: 8px;\n}\n.ant-page-header-heading {\n display: flex;\n justify-content: space-between;\n}\n.ant-page-header-heading-left {\n display: flex;\n align-items: center;\n margin: 4px 0;\n overflow: hidden;\n}\n.ant-page-header-heading-title {\n margin-right: 12px;\n margin-bottom: 0;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 20px;\n line-height: 32px;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-page-header-heading .ant-avatar {\n margin-right: 12px;\n}\n.ant-page-header-heading-sub-title {\n margin-right: 12px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.5715;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-page-header-heading-extra {\n margin: 4px 0;\n white-space: nowrap;\n}\n.ant-page-header-heading-extra > * {\n white-space: unset;\n}\n.ant-page-header-content {\n padding-top: 12px;\n}\n.ant-page-header-footer {\n margin-top: 16px;\n}\n.ant-page-header-footer .ant-tabs > .ant-tabs-nav {\n margin: 0;\n}\n.ant-page-header-footer .ant-tabs > .ant-tabs-nav::before {\n border: none;\n}\n.ant-page-header-footer .ant-tabs .ant-tabs-tab {\n padding-top: 8px;\n padding-bottom: 8px;\n font-size: 16px;\n}\n.ant-page-header-compact .ant-page-header-heading {\n flex-wrap: wrap;\n}\n.ant-page-header-rtl {\n direction: rtl;\n}\n.ant-page-header-rtl .ant-page-header-back {\n float: right;\n margin-right: 0;\n margin-left: 16px;\n}\n.ant-page-header-rtl .ant-page-header-heading-title {\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-page-header-rtl .ant-page-header-heading .ant-avatar {\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-page-header-rtl .ant-page-header-heading-sub-title {\n float: right;\n margin-right: 0;\n margin-left: 12px;\n}\n.ant-page-header-rtl .ant-page-header-heading-tags {\n float: right;\n}\n.ant-page-header-rtl .ant-page-header-heading-extra {\n float: left;\n}\n.ant-page-header-rtl .ant-page-header-heading-extra > * {\n margin-right: 12px;\n margin-left: 0;\n}\n.ant-page-header-rtl .ant-page-header-heading-extra > *:first-child {\n margin-right: 0;\n}\n.ant-page-header-rtl .ant-page-header-footer .ant-tabs-bar .ant-tabs-nav {\n float: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-popconfirm {\n z-index: 1060;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-progress {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n}\n.ant-progress-line {\n position: relative;\n width: 100%;\n font-size: 14px;\n}\n.ant-progress-steps {\n display: inline-block;\n}\n.ant-progress-steps-outer {\n display: flex;\n flex-direction: row;\n align-items: center;\n}\n.ant-progress-steps-item {\n flex-shrink: 0;\n min-width: 2px;\n margin-right: 2px;\n background: #f3f3f3;\n transition: all 0.3s;\n}\n.ant-progress-steps-item-active {\n background: #1890ff;\n}\n.ant-progress-small.ant-progress-line,\n.ant-progress-small.ant-progress-line .ant-progress-text .anticon {\n font-size: 12px;\n}\n.ant-progress-outer {\n display: inline-block;\n width: 100%;\n margin-right: 0;\n padding-right: 0;\n}\n.ant-progress-show-info .ant-progress-outer {\n margin-right: calc(-2em - 8px);\n padding-right: calc(2em + 8px);\n}\n.ant-progress-inner {\n position: relative;\n display: inline-block;\n width: 100%;\n overflow: hidden;\n vertical-align: middle;\n background-color: #f5f5f5;\n border-radius: 100px;\n}\n.ant-progress-circle-trail {\n stroke: #f5f5f5;\n}\n.ant-progress-circle-path {\n animation: ant-progress-appear 0.3s;\n}\n.ant-progress-inner:not(.ant-progress-circle-gradient) .ant-progress-circle-path {\n stroke: #1890ff;\n}\n.ant-progress-success-bg,\n.ant-progress-bg {\n position: relative;\n background-color: #1890ff;\n border-radius: 100px;\n transition: all 0.4s cubic-bezier(0.08, 0.82, 0.17, 1) 0s;\n}\n.ant-progress-success-bg {\n position: absolute;\n top: 0;\n left: 0;\n background-color: #52c41a;\n}\n.ant-progress-text {\n display: inline-block;\n width: 2em;\n margin-left: 8px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 1em;\n line-height: 1;\n white-space: nowrap;\n text-align: left;\n vertical-align: middle;\n word-break: normal;\n}\n.ant-progress-text .anticon {\n font-size: 14px;\n}\n.ant-progress-status-active .ant-progress-bg::before {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: #fff;\n border-radius: 10px;\n opacity: 0;\n animation: ant-progress-active 2.4s cubic-bezier(0.23, 1, 0.32, 1) infinite;\n content: '';\n}\n.ant-progress-status-exception .ant-progress-bg {\n background-color: #ff4d4f;\n}\n.ant-progress-status-exception .ant-progress-text {\n color: #ff4d4f;\n}\n.ant-progress-status-exception .ant-progress-inner:not(.ant-progress-circle-gradient) .ant-progress-circle-path {\n stroke: #ff4d4f;\n}\n.ant-progress-status-success .ant-progress-bg {\n background-color: #52c41a;\n}\n.ant-progress-status-success .ant-progress-text {\n color: #52c41a;\n}\n.ant-progress-status-success .ant-progress-inner:not(.ant-progress-circle-gradient) .ant-progress-circle-path {\n stroke: #52c41a;\n}\n.ant-progress-circle .ant-progress-inner {\n position: relative;\n line-height: 1;\n background-color: transparent;\n}\n.ant-progress-circle .ant-progress-text {\n position: absolute;\n top: 50%;\n left: 50%;\n width: 100%;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 1em;\n line-height: 1;\n white-space: normal;\n text-align: center;\n transform: translate(-50%, -50%);\n}\n.ant-progress-circle .ant-progress-text .anticon {\n font-size: 1.16666667em;\n}\n.ant-progress-circle.ant-progress-status-exception .ant-progress-text {\n color: #ff4d4f;\n}\n.ant-progress-circle.ant-progress-status-success .ant-progress-text {\n color: #52c41a;\n}\n@keyframes ant-progress-active {\n 0% {\n transform: translateX(-100%) scaleX(0);\n opacity: 0.1;\n }\n 20% {\n transform: translateX(-100%) scaleX(0);\n opacity: 0.5;\n }\n 100% {\n transform: translateX(0) scaleX(1);\n opacity: 0;\n }\n}\n.ant-progress-rtl {\n direction: rtl;\n}\n.ant-progress-rtl.ant-progress-show-info .ant-progress-outer {\n margin-right: 0;\n margin-left: calc(-2em - 8px);\n padding-right: 0;\n padding-left: calc(2em + 8px);\n}\n.ant-progress-rtl .ant-progress-success-bg {\n right: 0;\n left: auto;\n}\n.ant-progress-rtl.ant-progress-line .ant-progress-text,\n.ant-progress-rtl.ant-progress-steps .ant-progress-text {\n margin-right: 8px;\n margin-left: 0;\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-rate {\n box-sizing: border-box;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n font-feature-settings: 'tnum';\n display: inline-block;\n margin: 0;\n padding: 0;\n color: #fadb14;\n font-size: 20px;\n line-height: unset;\n list-style: none;\n outline: none;\n}\n.ant-rate-disabled .ant-rate-star {\n cursor: default;\n}\n.ant-rate-disabled .ant-rate-star > div:hover {\n transform: scale(1);\n}\n.ant-rate-star {\n position: relative;\n display: inline-block;\n color: inherit;\n cursor: pointer;\n}\n.ant-rate-star:not(:last-child) {\n margin-right: 8px;\n}\n.ant-rate-star > div {\n transition: all 0.3s, outline 0s;\n}\n.ant-rate-star > div:hover {\n transform: scale(1.1);\n}\n.ant-rate-star > div:focus {\n outline: 0;\n}\n.ant-rate-star > div:focus-visible {\n outline: 1px dashed #fadb14;\n transform: scale(1.1);\n}\n.ant-rate-star-first,\n.ant-rate-star-second {\n color: #f0f0f0;\n transition: all 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-rate-star-first .anticon,\n.ant-rate-star-second .anticon {\n vertical-align: middle;\n}\n.ant-rate-star-first {\n position: absolute;\n top: 0;\n left: 0;\n width: 50%;\n height: 100%;\n overflow: hidden;\n opacity: 0;\n}\n.ant-rate-star-half .ant-rate-star-first,\n.ant-rate-star-half .ant-rate-star-second {\n opacity: 1;\n}\n.ant-rate-star-half .ant-rate-star-first,\n.ant-rate-star-full .ant-rate-star-second {\n color: inherit;\n}\n.ant-rate-text {\n display: inline-block;\n margin: 0 8px;\n font-size: 14px;\n}\n.ant-rate-rtl {\n direction: rtl;\n}\n.ant-rate-rtl .ant-rate-star:not(:last-child) {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-rate-rtl .ant-rate-star-first {\n right: 0;\n left: auto;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-result {\n padding: 48px 32px;\n}\n.ant-result-success .ant-result-icon > .anticon {\n color: #52c41a;\n}\n.ant-result-error .ant-result-icon > .anticon {\n color: #ff4d4f;\n}\n.ant-result-info .ant-result-icon > .anticon {\n color: #1890ff;\n}\n.ant-result-warning .ant-result-icon > .anticon {\n color: #faad14;\n}\n.ant-result-image {\n width: 250px;\n height: 295px;\n margin: auto;\n}\n.ant-result-icon {\n margin-bottom: 24px;\n text-align: center;\n}\n.ant-result-icon > .anticon {\n font-size: 72px;\n}\n.ant-result-title {\n color: rgba(0, 0, 0, 0.85);\n font-size: 24px;\n line-height: 1.8;\n text-align: center;\n}\n.ant-result-subtitle {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n line-height: 1.6;\n text-align: center;\n}\n.ant-result-extra {\n margin: 24px 0 0 0;\n text-align: center;\n}\n.ant-result-extra > * {\n margin-right: 8px;\n}\n.ant-result-extra > *:last-child {\n margin-right: 0;\n}\n.ant-result-content {\n margin-top: 24px;\n padding: 24px 40px;\n background-color: #fafafa;\n}\n.ant-result-rtl {\n direction: rtl;\n}\n.ant-result-rtl .ant-result-extra > * {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-result-rtl .ant-result-extra > *:last-child {\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.segmented-disabled-item,\n.segmented-disabled-item:hover,\n.segmented-disabled-item:focus {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.segmented-item-selected {\n background-color: #fff;\n border-radius: 2px;\n box-shadow: 0 2px 8px -2px rgba(0, 0, 0, 0.05), 0 1px 4px -1px rgba(0, 0, 0, 0.07), 0 0 1px 0 rgba(0, 0, 0, 0.08);\n}\n.segmented-text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n word-break: keep-all;\n}\n.ant-segmented {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n padding: 2px;\n color: rgba(0, 0, 0, 0.65);\n background-color: rgba(0, 0, 0, 0.04);\n border-radius: 2px;\n transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-segmented-group {\n position: relative;\n display: flex;\n align-items: stretch;\n justify-items: flex-start;\n width: 100%;\n}\n.ant-segmented.ant-segmented-block {\n display: flex;\n}\n.ant-segmented.ant-segmented-block .ant-segmented-item {\n flex: 1;\n min-width: 0;\n}\n.ant-segmented:not(.ant-segmented-disabled):hover,\n.ant-segmented:not(.ant-segmented-disabled):focus {\n background-color: rgba(0, 0, 0, 0.06);\n}\n.ant-segmented-item {\n position: relative;\n text-align: center;\n cursor: pointer;\n transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n}\n.ant-segmented-item-selected {\n background-color: #fff;\n border-radius: 2px;\n box-shadow: 0 2px 8px -2px rgba(0, 0, 0, 0.05), 0 1px 4px -1px rgba(0, 0, 0, 0.07), 0 0 1px 0 rgba(0, 0, 0, 0.08);\n color: #262626;\n}\n.ant-segmented-item:hover,\n.ant-segmented-item:focus {\n color: #262626;\n}\n.ant-segmented-item-label {\n min-height: 28px;\n padding: 0 11px;\n line-height: 28px;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n word-break: keep-all;\n}\n.ant-segmented-item-icon + * {\n margin-left: 6px;\n}\n.ant-segmented-item-input {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 0;\n opacity: 0;\n pointer-events: none;\n}\n.ant-segmented.ant-segmented-lg .ant-segmented-item-label {\n min-height: 36px;\n padding: 0 11px;\n font-size: 16px;\n line-height: 36px;\n}\n.ant-segmented.ant-segmented-sm .ant-segmented-item-label {\n min-height: 20px;\n padding: 0 7px;\n line-height: 20px;\n}\n.ant-segmented-item-disabled,\n.ant-segmented-item-disabled:hover,\n.ant-segmented-item-disabled:focus {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-segmented-thumb {\n background-color: #fff;\n border-radius: 2px;\n box-shadow: 0 2px 8px -2px rgba(0, 0, 0, 0.05), 0 1px 4px -1px rgba(0, 0, 0, 0.07), 0 0 1px 0 rgba(0, 0, 0, 0.08);\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n padding: 4px 0;\n}\n.ant-segmented-thumb-motion-appear-active {\n transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);\n will-change: transform, width;\n}\n.ant-segmented.ant-segmented-rtl {\n direction: rtl;\n}\n.ant-segmented.ant-segmented-rtl .ant-segmented-item-icon {\n margin-right: 0;\n margin-left: 6px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-slider {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n height: 12px;\n margin: 10px 6px 10px;\n padding: 4px 0;\n cursor: pointer;\n touch-action: none;\n}\n.ant-slider-vertical {\n width: 12px;\n height: 100%;\n margin: 6px 10px;\n padding: 0 4px;\n}\n.ant-slider-vertical .ant-slider-rail {\n width: 4px;\n height: 100%;\n}\n.ant-slider-vertical .ant-slider-track {\n width: 4px;\n}\n.ant-slider-vertical .ant-slider-handle {\n margin-top: -6px;\n margin-left: -5px;\n}\n.ant-slider-vertical .ant-slider-mark {\n top: 0;\n left: 12px;\n width: 18px;\n height: 100%;\n}\n.ant-slider-vertical .ant-slider-mark-text {\n left: 4px;\n white-space: nowrap;\n}\n.ant-slider-vertical .ant-slider-step {\n width: 4px;\n height: 100%;\n}\n.ant-slider-vertical .ant-slider-dot {\n top: auto;\n margin-left: -2px;\n}\n.ant-slider-tooltip .ant-tooltip-inner {\n min-width: unset;\n}\n.ant-slider-rtl.ant-slider-vertical .ant-slider-handle {\n margin-right: -5px;\n margin-left: 0;\n}\n.ant-slider-rtl.ant-slider-vertical .ant-slider-mark {\n right: 12px;\n left: auto;\n}\n.ant-slider-rtl.ant-slider-vertical .ant-slider-mark-text {\n right: 4px;\n left: auto;\n}\n.ant-slider-rtl.ant-slider-vertical .ant-slider-dot {\n right: 2px;\n left: auto;\n}\n.ant-slider-with-marks {\n margin-bottom: 28px;\n}\n.ant-slider-rail {\n position: absolute;\n width: 100%;\n height: 4px;\n background-color: #f5f5f5;\n border-radius: 2px;\n transition: background-color 0.3s;\n}\n.ant-slider-track {\n position: absolute;\n height: 4px;\n background-color: #91d5ff;\n border-radius: 2px;\n transition: background-color 0.3s;\n}\n.ant-slider-handle {\n position: absolute;\n width: 14px;\n height: 14px;\n margin-top: -5px;\n background-color: #fff;\n border: solid 2px #91d5ff;\n border-radius: 50%;\n box-shadow: 0;\n cursor: pointer;\n transition: border-color 0.3s, box-shadow 0.6s, transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);\n}\n.ant-slider-handle-dragging {\n z-index: 1;\n}\n.ant-slider-handle:focus {\n border-color: #46a6ff;\n outline: none;\n box-shadow: 0 0 0 5px rgba(24, 144, 255, 0.12);\n}\n.ant-slider-handle.ant-tooltip-open {\n border-color: #1890ff;\n}\n.ant-slider-handle::after {\n position: absolute;\n top: -6px;\n right: -6px;\n bottom: -6px;\n left: -6px;\n content: '';\n}\n.ant-slider:hover .ant-slider-rail {\n background-color: #e1e1e1;\n}\n.ant-slider:hover .ant-slider-track {\n background-color: #69c0ff;\n}\n.ant-slider:hover .ant-slider-handle:not(.ant-tooltip-open) {\n border-color: #69c0ff;\n}\n.ant-slider-mark {\n position: absolute;\n top: 14px;\n left: 0;\n width: 100%;\n font-size: 14px;\n}\n.ant-slider-mark-text {\n position: absolute;\n display: inline-block;\n color: rgba(0, 0, 0, 0.45);\n text-align: center;\n word-break: keep-all;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-slider-mark-text-active {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-slider-step {\n position: absolute;\n width: 100%;\n height: 4px;\n background: transparent;\n pointer-events: none;\n}\n.ant-slider-dot {\n position: absolute;\n top: -2px;\n width: 8px;\n height: 8px;\n background-color: #fff;\n border: 2px solid #f0f0f0;\n border-radius: 50%;\n cursor: pointer;\n}\n.ant-slider-dot-active {\n border-color: #8cc8ff;\n}\n.ant-slider-disabled {\n cursor: not-allowed;\n}\n.ant-slider-disabled .ant-slider-rail {\n background-color: #f5f5f5 !important;\n}\n.ant-slider-disabled .ant-slider-track {\n background-color: rgba(0, 0, 0, 0.25) !important;\n}\n.ant-slider-disabled .ant-slider-handle,\n.ant-slider-disabled .ant-slider-dot {\n background-color: #fff;\n border-color: rgba(0, 0, 0, 0.25) !important;\n box-shadow: none;\n cursor: not-allowed;\n}\n.ant-slider-disabled .ant-slider-mark-text,\n.ant-slider-disabled .ant-slider-dot {\n cursor: not-allowed !important;\n}\n.ant-slider-rtl {\n direction: rtl;\n}\n.ant-slider-rtl .ant-slider-mark {\n right: 0;\n left: auto;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-statistic {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n}\n.ant-statistic-title {\n margin-bottom: 4px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-statistic-skeleton {\n padding-top: 16px;\n}\n.ant-statistic-content {\n color: rgba(0, 0, 0, 0.85);\n font-size: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n}\n.ant-statistic-content-value {\n display: inline-block;\n direction: ltr;\n}\n.ant-statistic-content-prefix,\n.ant-statistic-content-suffix {\n display: inline-block;\n}\n.ant-statistic-content-prefix {\n margin-right: 4px;\n}\n.ant-statistic-content-suffix {\n margin-left: 4px;\n}\n.ant-statistic-rtl {\n direction: rtl;\n}\n.ant-statistic-rtl .ant-statistic-content-prefix {\n margin-right: 0;\n margin-left: 4px;\n}\n.ant-statistic-rtl .ant-statistic-content-suffix {\n margin-right: 4px;\n margin-left: 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-steps {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: flex;\n width: 100%;\n font-size: 0;\n text-align: initial;\n}\n.ant-steps-item {\n position: relative;\n display: inline-block;\n flex: 1;\n overflow: hidden;\n vertical-align: top;\n}\n.ant-steps-item-container {\n outline: none;\n}\n.ant-steps-item:last-child {\n flex: none;\n}\n.ant-steps-item:last-child > .ant-steps-item-container > .ant-steps-item-tail,\n.ant-steps-item:last-child > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n display: none;\n}\n.ant-steps-item-icon,\n.ant-steps-item-content {\n display: inline-block;\n vertical-align: top;\n}\n.ant-steps-item-icon {\n width: 32px;\n height: 32px;\n margin: 0 8px 0 0;\n font-size: 16px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n line-height: 32px;\n text-align: center;\n border: 1px solid rgba(0, 0, 0, 0.25);\n border-radius: 32px;\n transition: background-color 0.3s, border-color 0.3s;\n}\n.ant-steps-item-icon .ant-steps-icon {\n position: relative;\n top: -0.5px;\n color: #1890ff;\n line-height: 1;\n}\n.ant-steps-item-tail {\n position: absolute;\n top: 12px;\n left: 0;\n width: 100%;\n padding: 0 10px;\n}\n.ant-steps-item-tail::after {\n display: inline-block;\n width: 100%;\n height: 1px;\n background: #f0f0f0;\n border-radius: 1px;\n transition: background 0.3s;\n content: '';\n}\n.ant-steps-item-title {\n position: relative;\n display: inline-block;\n padding-right: 16px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 16px;\n line-height: 32px;\n}\n.ant-steps-item-title::after {\n position: absolute;\n top: 16px;\n left: 100%;\n display: block;\n width: 9999px;\n height: 1px;\n background: #f0f0f0;\n content: '';\n}\n.ant-steps-item-subtitle {\n display: inline;\n margin-left: 8px;\n color: rgba(0, 0, 0, 0.45);\n font-weight: normal;\n font-size: 14px;\n}\n.ant-steps-item-description {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-steps-item-wait .ant-steps-item-icon {\n background-color: #fff;\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-steps-item-wait .ant-steps-item-icon > .ant-steps-icon {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-steps-item-wait .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot {\n background: rgba(0, 0, 0, 0.25);\n}\n.ant-steps-item-wait > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-steps-item-wait > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item-wait > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-description {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-steps-item-wait > .ant-steps-item-container > .ant-steps-item-tail::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item-process .ant-steps-item-icon {\n background-color: #fff;\n border-color: #1890ff;\n}\n.ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon {\n color: #1890ff;\n}\n.ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot {\n background: #1890ff;\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-description {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-tail::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-icon {\n background: #1890ff;\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-icon .ant-steps-icon {\n color: #fff;\n}\n.ant-steps-item-process > .ant-steps-item-container > .ant-steps-item-title {\n font-weight: 500;\n}\n.ant-steps-item-finish .ant-steps-item-icon {\n background-color: #fff;\n border-color: #1890ff;\n}\n.ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon {\n color: #1890ff;\n}\n.ant-steps-item-finish .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot {\n background: #1890ff;\n}\n.ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n background-color: #1890ff;\n}\n.ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-description {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-steps-item-finish > .ant-steps-item-container > .ant-steps-item-tail::after {\n background-color: #1890ff;\n}\n.ant-steps-item-error .ant-steps-item-icon {\n background-color: #fff;\n border-color: #ff4d4f;\n}\n.ant-steps-item-error .ant-steps-item-icon > .ant-steps-icon {\n color: #ff4d4f;\n}\n.ant-steps-item-error .ant-steps-item-icon > .ant-steps-icon .ant-steps-icon-dot {\n background: #ff4d4f;\n}\n.ant-steps-item-error > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title {\n color: #ff4d4f;\n}\n.ant-steps-item-error > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item-error > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-description {\n color: #ff4d4f;\n}\n.ant-steps-item-error > .ant-steps-item-container > .ant-steps-item-tail::after {\n background-color: #f0f0f0;\n}\n.ant-steps-item.ant-steps-next-error .ant-steps-item-title::after {\n background: #ff4d4f;\n}\n.ant-steps-item-disabled {\n cursor: not-allowed;\n}\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button'] {\n cursor: pointer;\n}\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button'] .ant-steps-item-title,\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button'] .ant-steps-item-subtitle,\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button'] .ant-steps-item-description,\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button'] .ant-steps-item-icon .ant-steps-icon {\n transition: color 0.3s;\n}\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button']:hover .ant-steps-item-title,\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button']:hover .ant-steps-item-subtitle,\n.ant-steps .ant-steps-item:not(.ant-steps-item-active) > .ant-steps-item-container[role='button']:hover .ant-steps-item-description {\n color: #1890ff;\n}\n.ant-steps .ant-steps-item:not(.ant-steps-item-active):not(.ant-steps-item-process) > .ant-steps-item-container[role='button']:hover .ant-steps-item-icon {\n border-color: #1890ff;\n}\n.ant-steps .ant-steps-item:not(.ant-steps-item-active):not(.ant-steps-item-process) > .ant-steps-item-container[role='button']:hover .ant-steps-item-icon .ant-steps-icon {\n color: #1890ff;\n}\n.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item {\n padding-left: 16px;\n white-space: nowrap;\n}\n.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:first-child {\n padding-left: 0;\n}\n.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:last-child .ant-steps-item-title {\n padding-right: 0;\n}\n.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item-tail {\n display: none;\n}\n.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item-description {\n max-width: 140px;\n white-space: normal;\n}\n.ant-steps-item-custom > .ant-steps-item-container > .ant-steps-item-icon {\n height: auto;\n background: none;\n border: 0;\n}\n.ant-steps-item-custom > .ant-steps-item-container > .ant-steps-item-icon > .ant-steps-icon {\n top: 0px;\n left: 0.5px;\n width: 32px;\n height: 32px;\n font-size: 24px;\n line-height: 32px;\n}\n.ant-steps-item-custom.ant-steps-item-process .ant-steps-item-icon > .ant-steps-icon {\n color: #1890ff;\n}\n.ant-steps:not(.ant-steps-vertical) .ant-steps-item-custom .ant-steps-item-icon {\n width: auto;\n background: none;\n}\n.ant-steps-small.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item {\n padding-left: 12px;\n}\n.ant-steps-small.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:first-child {\n padding-left: 0;\n}\n.ant-steps-small .ant-steps-item-icon {\n width: 24px;\n height: 24px;\n margin: 0 8px 0 0;\n font-size: 12px;\n line-height: 24px;\n text-align: center;\n border-radius: 24px;\n}\n.ant-steps-small .ant-steps-item-title {\n padding-right: 12px;\n font-size: 14px;\n line-height: 24px;\n}\n.ant-steps-small .ant-steps-item-title::after {\n top: 12px;\n}\n.ant-steps-small .ant-steps-item-description {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-steps-small .ant-steps-item-tail {\n top: 8px;\n}\n.ant-steps-small .ant-steps-item-custom .ant-steps-item-icon {\n width: inherit;\n height: inherit;\n line-height: inherit;\n background: none;\n border: 0;\n border-radius: 0;\n}\n.ant-steps-small .ant-steps-item-custom .ant-steps-item-icon > .ant-steps-icon {\n font-size: 24px;\n line-height: 24px;\n transform: none;\n}\n.ant-steps-vertical {\n display: flex;\n flex-direction: column;\n}\n.ant-steps-vertical > .ant-steps-item {\n display: block;\n flex: 1 0 auto;\n padding-left: 0;\n overflow: visible;\n}\n.ant-steps-vertical > .ant-steps-item .ant-steps-item-icon {\n float: left;\n margin-right: 16px;\n}\n.ant-steps-vertical > .ant-steps-item .ant-steps-item-content {\n display: block;\n min-height: 48px;\n overflow: hidden;\n}\n.ant-steps-vertical > .ant-steps-item .ant-steps-item-title {\n line-height: 32px;\n}\n.ant-steps-vertical > .ant-steps-item .ant-steps-item-description {\n padding-bottom: 12px;\n}\n.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n position: absolute;\n top: 0;\n left: 15px;\n width: 1px;\n height: 100%;\n padding: 38px 0 6px;\n}\n.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail::after {\n width: 1px;\n height: 100%;\n}\n.ant-steps-vertical > .ant-steps-item:not(:last-child) > .ant-steps-item-container > .ant-steps-item-tail {\n display: block;\n}\n.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-content > .ant-steps-item-title::after {\n display: none;\n}\n.ant-steps-vertical.ant-steps-small .ant-steps-item-container .ant-steps-item-tail {\n position: absolute;\n top: 0;\n left: 11px;\n padding: 30px 0 6px;\n}\n.ant-steps-vertical.ant-steps-small .ant-steps-item-container .ant-steps-item-title {\n line-height: 24px;\n}\n.ant-steps-label-vertical .ant-steps-item {\n overflow: visible;\n}\n.ant-steps-label-vertical .ant-steps-item-tail {\n margin-left: 58px;\n padding: 3.5px 24px;\n}\n.ant-steps-label-vertical .ant-steps-item-content {\n display: block;\n width: 116px;\n margin-top: 8px;\n text-align: center;\n}\n.ant-steps-label-vertical .ant-steps-item-icon {\n display: inline-block;\n margin-left: 42px;\n}\n.ant-steps-label-vertical .ant-steps-item-title {\n padding-right: 0;\n padding-left: 0;\n}\n.ant-steps-label-vertical .ant-steps-item-title::after {\n display: none;\n}\n.ant-steps-label-vertical .ant-steps-item-subtitle {\n display: block;\n margin-bottom: 4px;\n margin-left: 0;\n line-height: 1.5715;\n}\n.ant-steps-label-vertical.ant-steps-small:not(.ant-steps-dot) .ant-steps-item-icon {\n margin-left: 46px;\n}\n.ant-steps-dot .ant-steps-item-title,\n.ant-steps-dot.ant-steps-small .ant-steps-item-title {\n line-height: 1.5715;\n}\n.ant-steps-dot .ant-steps-item-tail,\n.ant-steps-dot.ant-steps-small .ant-steps-item-tail {\n top: 2px;\n width: 100%;\n margin: 0 0 0 70px;\n padding: 0;\n}\n.ant-steps-dot .ant-steps-item-tail::after,\n.ant-steps-dot.ant-steps-small .ant-steps-item-tail::after {\n width: calc(100% - 20px);\n height: 3px;\n margin-left: 12px;\n}\n.ant-steps-dot .ant-steps-item:first-child .ant-steps-icon-dot,\n.ant-steps-dot.ant-steps-small .ant-steps-item:first-child .ant-steps-icon-dot {\n left: 2px;\n}\n.ant-steps-dot .ant-steps-item-icon,\n.ant-steps-dot.ant-steps-small .ant-steps-item-icon {\n width: 8px;\n height: 8px;\n margin-left: 67px;\n padding-right: 0;\n line-height: 8px;\n background: transparent;\n border: 0;\n}\n.ant-steps-dot .ant-steps-item-icon .ant-steps-icon-dot,\n.ant-steps-dot.ant-steps-small .ant-steps-item-icon .ant-steps-icon-dot {\n position: relative;\n float: left;\n width: 100%;\n height: 100%;\n border-radius: 100px;\n transition: all 0.3s;\n /* expand hover area */\n}\n.ant-steps-dot .ant-steps-item-icon .ant-steps-icon-dot::after,\n.ant-steps-dot.ant-steps-small .ant-steps-item-icon .ant-steps-icon-dot::after {\n position: absolute;\n top: -12px;\n left: -26px;\n width: 60px;\n height: 32px;\n background: rgba(0, 0, 0, 0.001);\n content: '';\n}\n.ant-steps-dot .ant-steps-item-content,\n.ant-steps-dot.ant-steps-small .ant-steps-item-content {\n width: 140px;\n}\n.ant-steps-dot .ant-steps-item-process .ant-steps-item-icon,\n.ant-steps-dot.ant-steps-small .ant-steps-item-process .ant-steps-item-icon {\n position: relative;\n top: -1px;\n width: 10px;\n height: 10px;\n line-height: 10px;\n background: none;\n}\n.ant-steps-dot .ant-steps-item-process .ant-steps-icon:first-child .ant-steps-icon-dot,\n.ant-steps-dot.ant-steps-small .ant-steps-item-process .ant-steps-icon:first-child .ant-steps-icon-dot {\n left: 0;\n}\n.ant-steps-vertical.ant-steps-dot .ant-steps-item-icon {\n margin-top: 13px;\n margin-left: 0;\n background: none;\n}\n.ant-steps-vertical.ant-steps-dot .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n top: 6.5px;\n left: -9px;\n margin: 0;\n padding: 22px 0 4px;\n}\n.ant-steps-vertical.ant-steps-dot.ant-steps-small .ant-steps-item-icon {\n margin-top: 10px;\n}\n.ant-steps-vertical.ant-steps-dot.ant-steps-small .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n top: 3.5px;\n}\n.ant-steps-vertical.ant-steps-dot .ant-steps-item:first-child .ant-steps-icon-dot {\n left: 0;\n}\n.ant-steps-vertical.ant-steps-dot .ant-steps-item-content {\n width: inherit;\n}\n.ant-steps-vertical.ant-steps-dot .ant-steps-item-process .ant-steps-item-container .ant-steps-item-icon .ant-steps-icon-dot {\n top: -1px;\n left: -1px;\n}\n.ant-steps-navigation {\n padding-top: 12px;\n}\n.ant-steps-navigation.ant-steps-small .ant-steps-item-container {\n margin-left: -12px;\n}\n.ant-steps-navigation .ant-steps-item {\n overflow: visible;\n text-align: center;\n}\n.ant-steps-navigation .ant-steps-item-container {\n display: inline-block;\n height: 100%;\n margin-left: -16px;\n padding-bottom: 12px;\n text-align: left;\n transition: opacity 0.3s;\n}\n.ant-steps-navigation .ant-steps-item-container .ant-steps-item-content {\n max-width: auto;\n}\n.ant-steps-navigation .ant-steps-item-container .ant-steps-item-title {\n max-width: 100%;\n padding-right: 0;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-steps-navigation .ant-steps-item-container .ant-steps-item-title::after {\n display: none;\n}\n.ant-steps-navigation .ant-steps-item:not(.ant-steps-item-active) .ant-steps-item-container[role='button'] {\n cursor: pointer;\n}\n.ant-steps-navigation .ant-steps-item:not(.ant-steps-item-active) .ant-steps-item-container[role='button']:hover {\n opacity: 0.85;\n}\n.ant-steps-navigation .ant-steps-item:last-child {\n flex: 1;\n}\n.ant-steps-navigation .ant-steps-item:last-child::after {\n display: none;\n}\n.ant-steps-navigation .ant-steps-item::after {\n position: absolute;\n top: 50%;\n left: 100%;\n display: inline-block;\n width: 12px;\n height: 12px;\n margin-top: -14px;\n margin-left: -2px;\n border: 1px solid rgba(0, 0, 0, 0.25);\n border-bottom: none;\n border-left: none;\n transform: rotate(45deg);\n content: '';\n}\n.ant-steps-navigation .ant-steps-item::before {\n position: absolute;\n bottom: 0;\n left: 50%;\n display: inline-block;\n width: 0;\n height: 2px;\n background-color: #1890ff;\n transition: width 0.3s, left 0.3s;\n transition-timing-function: ease-out;\n content: '';\n}\n.ant-steps-navigation .ant-steps-item.ant-steps-item-active::before {\n left: 0;\n width: 100%;\n}\n.ant-steps-navigation.ant-steps-vertical > .ant-steps-item {\n margin-right: 0 !important;\n}\n.ant-steps-navigation.ant-steps-vertical > .ant-steps-item::before {\n display: none;\n}\n.ant-steps-navigation.ant-steps-vertical > .ant-steps-item.ant-steps-item-active::before {\n top: 0;\n right: 0;\n left: unset;\n display: block;\n width: 3px;\n height: calc(100% - 24px);\n}\n.ant-steps-navigation.ant-steps-vertical > .ant-steps-item::after {\n position: relative;\n top: -2px;\n left: 50%;\n display: block;\n width: 8px;\n height: 8px;\n margin-bottom: 8px;\n text-align: center;\n transform: rotate(135deg);\n}\n.ant-steps-navigation.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n visibility: hidden;\n}\n.ant-steps-navigation.ant-steps-horizontal > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n visibility: hidden;\n}\n.ant-steps-rtl {\n direction: rtl;\n}\n.ant-steps.ant-steps-rtl .ant-steps-item-icon {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-steps-rtl .ant-steps-item-tail {\n right: 0;\n left: auto;\n}\n.ant-steps-rtl .ant-steps-item-title {\n padding-right: 0;\n padding-left: 16px;\n}\n.ant-steps-rtl .ant-steps-item-title .ant-steps-item-subtitle {\n float: left;\n margin-right: 8px;\n margin-left: 0;\n}\n.ant-steps-rtl .ant-steps-item-title::after {\n right: 100%;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item {\n padding-right: 16px;\n padding-left: 0;\n}\n.ant-steps-rtl.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:first-child {\n padding-right: 0;\n}\n.ant-steps-rtl.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:last-child .ant-steps-item-title {\n padding-left: 0;\n}\n.ant-steps-rtl .ant-steps-item-custom .ant-steps-item-icon > .ant-steps-icon {\n right: 0.5px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-navigation.ant-steps-small .ant-steps-item-container {\n margin-right: -12px;\n margin-left: 0;\n}\n.ant-steps-rtl.ant-steps-navigation .ant-steps-item-container {\n margin-right: -16px;\n margin-left: 0;\n text-align: right;\n}\n.ant-steps-rtl.ant-steps-navigation .ant-steps-item-container .ant-steps-item-title {\n padding-left: 0;\n}\n.ant-steps-rtl.ant-steps-navigation .ant-steps-item::after {\n right: 100%;\n left: auto;\n margin-right: -2px;\n margin-left: 0;\n transform: rotate(225deg);\n}\n.ant-steps-rtl.ant-steps-small.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item {\n padding-right: 12px;\n padding-left: 0;\n}\n.ant-steps-rtl.ant-steps-small.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:first-child {\n padding-right: 0;\n}\n.ant-steps-rtl.ant-steps-small .ant-steps-item-title {\n padding-right: 0;\n padding-left: 12px;\n}\n.ant-steps-rtl.ant-steps-vertical > .ant-steps-item .ant-steps-item-icon {\n float: right;\n margin-right: 0;\n margin-left: 16px;\n}\n.ant-steps-rtl.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n right: 16px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-vertical.ant-steps-small .ant-steps-item-container .ant-steps-item-tail {\n right: 12px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-label-vertical .ant-steps-item-title {\n padding-left: 0;\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item-tail,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item-tail {\n margin: 0 70px 0 0;\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item-tail::after,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item-tail::after {\n margin-right: 12px;\n margin-left: 0;\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item:first-child .ant-steps-icon-dot,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item:first-child .ant-steps-icon-dot {\n right: 2px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item-icon,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item-icon {\n margin-right: 67px;\n margin-left: 0;\n}\n.ant-steps-dot .ant-steps-item-icon .ant-steps-icon-dot,\n.ant-steps-dot.ant-steps-small .ant-steps-item-icon .ant-steps-icon-dot {\n /* expand hover area */\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item-icon .ant-steps-icon-dot,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item-icon .ant-steps-icon-dot {\n float: right;\n}\n.ant-steps-rtl.ant-steps-dot .ant-steps-item-icon .ant-steps-icon-dot::after,\n.ant-steps-rtl.ant-steps-dot.ant-steps-small .ant-steps-item-icon .ant-steps-icon-dot::after {\n right: -26px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-vertical.ant-steps-dot .ant-steps-item-icon {\n margin-right: 0;\n margin-left: 16px;\n}\n.ant-steps-rtl.ant-steps-vertical.ant-steps-dot .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n right: -9px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-vertical.ant-steps-dot .ant-steps-item:first-child .ant-steps-icon-dot {\n right: 0;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-vertical.ant-steps-dot .ant-steps-item-process .ant-steps-icon-dot {\n right: -2px;\n left: auto;\n}\n.ant-steps-rtl.ant-steps-with-progress.ant-steps-vertical > .ant-steps-item {\n padding-right: 4px;\n}\n.ant-steps-rtl.ant-steps-with-progress.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n right: 19px;\n}\n.ant-steps-rtl.ant-steps-with-progress.ant-steps-small.ant-steps-vertical > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n right: 15px;\n}\n.ant-steps-rtl.ant-steps-with-progress.ant-steps-horizontal.ant-steps-label-horizontal .ant-steps-item:first-child {\n padding-right: 4px;\n padding-left: 0;\n}\n.ant-steps-rtl.ant-steps-with-progress.ant-steps-horizontal.ant-steps-label-horizontal .ant-steps-item:first-child.ant-steps-item-active {\n padding-right: 4px;\n}\n.ant-steps-with-progress .ant-steps-item {\n padding-top: 4px;\n}\n.ant-steps-with-progress .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n top: 4px;\n left: 19px;\n}\n.ant-steps-with-progress.ant-steps-horizontal .ant-steps-item:first-child,\n.ant-steps-with-progress.ant-steps-small.ant-steps-horizontal .ant-steps-item:first-child {\n padding-bottom: 4px;\n padding-left: 4px;\n}\n.ant-steps-with-progress.ant-steps-small > .ant-steps-item > .ant-steps-item-container > .ant-steps-item-tail {\n left: 15px;\n}\n.ant-steps-with-progress.ant-steps-vertical .ant-steps-item {\n padding-left: 4px;\n}\n.ant-steps-with-progress.ant-steps-label-vertical .ant-steps-item .ant-steps-item-tail {\n top: 14px !important;\n}\n.ant-steps-with-progress .ant-steps-item-icon {\n position: relative;\n}\n.ant-steps-with-progress .ant-steps-item-icon .ant-progress {\n position: absolute;\n top: -5px;\n right: -5px;\n bottom: -5px;\n left: -5px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-switch {\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: inline-block;\n box-sizing: border-box;\n min-width: 44px;\n height: 22px;\n line-height: 22px;\n vertical-align: middle;\n background-color: rgba(0, 0, 0, 0.25);\n border: 0;\n border-radius: 100px;\n cursor: pointer;\n transition: all 0.2s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-switch:focus {\n outline: 0;\n box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);\n}\n.ant-switch-checked:focus {\n box-shadow: 0 0 0 2px #e6f7ff;\n}\n.ant-switch:focus:hover {\n box-shadow: none;\n}\n.ant-switch-checked {\n background-color: #1890ff;\n}\n.ant-switch-loading,\n.ant-switch-disabled {\n cursor: not-allowed;\n opacity: 0.4;\n}\n.ant-switch-loading *,\n.ant-switch-disabled * {\n box-shadow: none;\n cursor: not-allowed;\n}\n.ant-switch-inner {\n display: block;\n margin: 0 7px 0 25px;\n color: #fff;\n font-size: 12px;\n transition: margin 0.2s;\n}\n.ant-switch-checked .ant-switch-inner {\n margin: 0 25px 0 7px;\n}\n.ant-switch-handle {\n position: absolute;\n top: 2px;\n left: 2px;\n width: 18px;\n height: 18px;\n transition: all 0.2s ease-in-out;\n}\n.ant-switch-handle::before {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: #fff;\n border-radius: 9px;\n box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);\n transition: all 0.2s ease-in-out;\n content: '';\n}\n.ant-switch-checked .ant-switch-handle {\n left: calc(100% - 18px - 2px);\n}\n.ant-switch:not(.ant-switch-disabled):active .ant-switch-handle::before {\n right: -30%;\n left: 0;\n}\n.ant-switch:not(.ant-switch-disabled):active.ant-switch-checked .ant-switch-handle::before {\n right: 0;\n left: -30%;\n}\n.ant-switch-loading-icon.anticon {\n position: relative;\n top: 2px;\n color: rgba(0, 0, 0, 0.65);\n vertical-align: top;\n}\n.ant-switch-checked .ant-switch-loading-icon {\n color: #1890ff;\n}\n.ant-switch-small {\n min-width: 28px;\n height: 16px;\n line-height: 16px;\n}\n.ant-switch-small .ant-switch-inner {\n margin: 0 5px 0 18px;\n font-size: 12px;\n}\n.ant-switch-small .ant-switch-handle {\n width: 12px;\n height: 12px;\n}\n.ant-switch-small .ant-switch-loading-icon {\n top: 1.5px;\n font-size: 9px;\n}\n.ant-switch-small.ant-switch-checked .ant-switch-inner {\n margin: 0 18px 0 5px;\n}\n.ant-switch-small.ant-switch-checked .ant-switch-handle {\n left: calc(100% - 12px - 2px);\n}\n.ant-switch-rtl {\n direction: rtl;\n}\n.ant-switch-rtl .ant-switch-inner {\n margin: 0 25px 0 7px;\n}\n.ant-switch-rtl .ant-switch-handle {\n right: 2px;\n left: auto;\n}\n.ant-switch-rtl:not(.ant-switch-rtl-disabled):active .ant-switch-handle::before {\n right: 0;\n left: -30%;\n}\n.ant-switch-rtl:not(.ant-switch-rtl-disabled):active.ant-switch-checked .ant-switch-handle::before {\n right: -30%;\n left: 0;\n}\n.ant-switch-rtl.ant-switch-checked .ant-switch-inner {\n margin: 0 7px 0 25px;\n}\n.ant-switch-rtl.ant-switch-checked .ant-switch-handle {\n right: calc(100% - 18px - 2px);\n}\n.ant-switch-rtl.ant-switch-small.ant-switch-checked .ant-switch-handle {\n right: calc(100% - 12px - 2px);\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-table.ant-table-middle {\n font-size: 14px;\n}\n.ant-table.ant-table-middle .ant-table-title,\n.ant-table.ant-table-middle .ant-table-footer,\n.ant-table.ant-table-middle .ant-table-thead > tr > th,\n.ant-table.ant-table-middle .ant-table-tbody > tr > td,\n.ant-table.ant-table-middle tfoot > tr > th,\n.ant-table.ant-table-middle tfoot > tr > td {\n padding: 12px 8px;\n}\n.ant-table.ant-table-middle .ant-table-filter-trigger {\n margin-right: -4px;\n}\n.ant-table.ant-table-middle .ant-table-expanded-row-fixed {\n margin: -12px -8px;\n}\n.ant-table.ant-table-middle .ant-table-tbody .ant-table-wrapper:only-child .ant-table {\n margin: -12px -8px -12px 40px;\n}\n.ant-table.ant-table-middle .ant-table-selection-column {\n -webkit-padding-start: 2px;\n padding-inline-start: 2px;\n}\n.ant-table.ant-table-small {\n font-size: 14px;\n}\n.ant-table.ant-table-small .ant-table-title,\n.ant-table.ant-table-small .ant-table-footer,\n.ant-table.ant-table-small .ant-table-thead > tr > th,\n.ant-table.ant-table-small .ant-table-tbody > tr > td,\n.ant-table.ant-table-small tfoot > tr > th,\n.ant-table.ant-table-small tfoot > tr > td {\n padding: 8px 8px;\n}\n.ant-table.ant-table-small .ant-table-filter-trigger {\n margin-right: -4px;\n}\n.ant-table.ant-table-small .ant-table-expanded-row-fixed {\n margin: -8px -8px;\n}\n.ant-table.ant-table-small .ant-table-tbody .ant-table-wrapper:only-child .ant-table {\n margin: -8px -8px -8px 40px;\n}\n.ant-table.ant-table-small .ant-table-selection-column {\n -webkit-padding-start: 2px;\n padding-inline-start: 2px;\n}\n.ant-table.ant-table-bordered > .ant-table-title {\n border: 1px solid #f0f0f0;\n border-bottom: 0;\n}\n.ant-table.ant-table-bordered > .ant-table-container {\n border-left: 1px solid #f0f0f0;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > thead > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > thead > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > thead > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > thead > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tbody > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tbody > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tbody > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tbody > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tfoot > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tfoot > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tfoot > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tfoot > tr > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tfoot > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tfoot > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tfoot > tr > td,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tfoot > tr > td {\n border-right: 1px solid #f0f0f0;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > thead > tr:not(:last-child) > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > thead > tr:not(:last-child) > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > thead > tr:not(:last-child) > th,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > thead > tr:not(:last-child) > th {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > thead > tr > th::before,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > thead > tr > th::before,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > thead > tr > th::before,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > thead > tr > th::before {\n background-color: transparent !important;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > thead > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > thead > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > thead > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > thead > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tbody > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tbody > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tbody > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tbody > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tfoot > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tfoot > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tfoot > tr > .ant-table-cell-fix-right-first::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tfoot > tr > .ant-table-cell-fix-right-first::after {\n border-right: 1px solid #f0f0f0;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tbody > tr > td > .ant-table-expanded-row-fixed,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tbody > tr > td > .ant-table-expanded-row-fixed,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tbody > tr > td > .ant-table-expanded-row-fixed,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tbody > tr > td > .ant-table-expanded-row-fixed {\n margin: -16px -17px;\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table > tbody > tr > td > .ant-table-expanded-row-fixed::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table > tbody > tr > td > .ant-table-expanded-row-fixed::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-body > table > tbody > tr > td > .ant-table-expanded-row-fixed::after,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-summary > table > tbody > tr > td > .ant-table-expanded-row-fixed::after {\n position: absolute;\n top: 0;\n right: 1px;\n bottom: 0;\n border-right: 1px solid #f0f0f0;\n content: '';\n}\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-content > table,\n.ant-table.ant-table-bordered > .ant-table-container > .ant-table-header > table {\n border-top: 1px solid #f0f0f0;\n}\n.ant-table.ant-table-bordered.ant-table-scroll-horizontal > .ant-table-container > .ant-table-body > table > tbody > tr.ant-table-expanded-row > td,\n.ant-table.ant-table-bordered.ant-table-scroll-horizontal > .ant-table-container > .ant-table-body > table > tbody > tr.ant-table-placeholder > td {\n border-right: 0;\n}\n.ant-table.ant-table-bordered.ant-table-middle > .ant-table-container > .ant-table-content > table > tbody > tr > td > .ant-table-expanded-row-fixed,\n.ant-table.ant-table-bordered.ant-table-middle > .ant-table-container > .ant-table-body > table > tbody > tr > td > .ant-table-expanded-row-fixed {\n margin: -12px -9px;\n}\n.ant-table.ant-table-bordered.ant-table-small > .ant-table-container > .ant-table-content > table > tbody > tr > td > .ant-table-expanded-row-fixed,\n.ant-table.ant-table-bordered.ant-table-small > .ant-table-container > .ant-table-body > table > tbody > tr > td > .ant-table-expanded-row-fixed {\n margin: -8px -9px;\n}\n.ant-table.ant-table-bordered > .ant-table-footer {\n border: 1px solid #f0f0f0;\n border-top: 0;\n}\n.ant-table-cell .ant-table-container:first-child {\n border-top: 0;\n}\n.ant-table-cell-scrollbar:not([rowspan]) {\n box-shadow: 0 1px 0 1px #fafafa;\n}\n.ant-table-wrapper {\n clear: both;\n max-width: 100%;\n}\n.ant-table-wrapper::before {\n display: table;\n content: '';\n}\n.ant-table-wrapper::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-table {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n font-size: 14px;\n background: #fff;\n border-radius: 2px;\n}\n.ant-table table {\n width: 100%;\n text-align: left;\n border-radius: 2px 2px 0 0;\n border-collapse: separate;\n border-spacing: 0;\n}\n.ant-table-thead > tr > th,\n.ant-table-tbody > tr > td,\n.ant-table tfoot > tr > th,\n.ant-table tfoot > tr > td {\n position: relative;\n padding: 16px 16px;\n overflow-wrap: break-word;\n}\n.ant-table-cell-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n word-break: keep-all;\n}\n.ant-table-cell-ellipsis.ant-table-cell-fix-left-last,\n.ant-table-cell-ellipsis.ant-table-cell-fix-right-first {\n overflow: visible;\n}\n.ant-table-cell-ellipsis.ant-table-cell-fix-left-last .ant-table-cell-content,\n.ant-table-cell-ellipsis.ant-table-cell-fix-right-first .ant-table-cell-content {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.ant-table-cell-ellipsis .ant-table-column-title {\n overflow: hidden;\n text-overflow: ellipsis;\n word-break: keep-all;\n}\n.ant-table-title {\n padding: 16px 16px;\n}\n.ant-table-footer {\n padding: 16px 16px;\n color: rgba(0, 0, 0, 0.85);\n background: #fafafa;\n}\n.ant-table-thead > tr > th {\n position: relative;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 500;\n text-align: left;\n background: #fafafa;\n border-bottom: 1px solid #f0f0f0;\n transition: background 0.3s ease;\n}\n.ant-table-thead > tr > th[colspan]:not([colspan='1']) {\n text-align: center;\n}\n.ant-table-thead > tr > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {\n position: absolute;\n top: 50%;\n right: 0;\n width: 1px;\n height: 1.6em;\n background-color: rgba(0, 0, 0, 0.06);\n transform: translateY(-50%);\n transition: background-color 0.3s;\n content: '';\n}\n.ant-table-thead > tr:not(:last-child) > th[colspan] {\n border-bottom: 0;\n}\n.ant-table-tbody > tr > td {\n border-bottom: 1px solid #f0f0f0;\n transition: background 0.3s;\n}\n.ant-table-tbody > tr > td > .ant-table-wrapper:only-child .ant-table,\n.ant-table-tbody > tr > td > .ant-table-expanded-row-fixed > .ant-table-wrapper:only-child .ant-table {\n margin: -16px -16px -16px 32px;\n}\n.ant-table-tbody > tr > td > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td,\n.ant-table-tbody > tr > td > .ant-table-expanded-row-fixed > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td {\n border-bottom: 0;\n}\n.ant-table-tbody > tr > td > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td:first-child,\n.ant-table-tbody > tr > td > .ant-table-expanded-row-fixed > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td:first-child,\n.ant-table-tbody > tr > td > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td:last-child,\n.ant-table-tbody > tr > td > .ant-table-expanded-row-fixed > .ant-table-wrapper:only-child .ant-table-tbody > tr:last-child > td:last-child {\n border-radius: 0;\n}\n.ant-table-tbody > tr.ant-table-row:hover > td,\n.ant-table-tbody > tr > td.ant-table-cell-row-hover {\n background: #fafafa;\n}\n.ant-table-tbody > tr.ant-table-row-selected > td {\n background: #e6f7ff;\n border-color: rgba(0, 0, 0, 0.03);\n}\n.ant-table-tbody > tr.ant-table-row-selected:hover > td {\n background: #dcf4ff;\n}\n.ant-table-summary {\n position: relative;\n z-index: 2;\n background: #fff;\n}\ndiv.ant-table-summary {\n box-shadow: 0 -1px 0 #f0f0f0;\n}\n.ant-table-summary > tr > th,\n.ant-table-summary > tr > td {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-table-pagination.ant-pagination {\n margin: 16px 0;\n}\n.ant-table-pagination {\n display: flex;\n flex-wrap: wrap;\n row-gap: 8px;\n}\n.ant-table-pagination > * {\n flex: none;\n}\n.ant-table-pagination-left {\n justify-content: flex-start;\n}\n.ant-table-pagination-center {\n justify-content: center;\n}\n.ant-table-pagination-right {\n justify-content: flex-end;\n}\n.ant-table-thead th.ant-table-column-has-sorters {\n outline: none;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-table-thead th.ant-table-column-has-sorters:hover {\n background: rgba(0, 0, 0, 0.04);\n}\n.ant-table-thead th.ant-table-column-has-sorters:hover::before {\n background-color: transparent !important;\n}\n.ant-table-thead th.ant-table-column-has-sorters:focus-visible {\n color: #1890ff;\n}\n.ant-table-thead th.ant-table-column-has-sorters.ant-table-cell-fix-left:hover,\n.ant-table-thead th.ant-table-column-has-sorters.ant-table-cell-fix-right:hover {\n background: #f5f5f5;\n}\n.ant-table-thead th.ant-table-column-sort {\n background: #f5f5f5;\n}\n.ant-table-thead th.ant-table-column-sort::before {\n background-color: transparent !important;\n}\ntd.ant-table-column-sort {\n background: #fafafa;\n}\n.ant-table-column-title {\n position: relative;\n z-index: 1;\n flex: 1;\n}\n.ant-table-column-sorters {\n display: flex;\n flex: auto;\n align-items: center;\n justify-content: space-between;\n}\n.ant-table-column-sorters::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n width: 100%;\n height: 100%;\n content: '';\n}\n.ant-table-column-sorter {\n margin-left: 4px;\n color: #bfbfbf;\n font-size: 0;\n transition: color 0.3s;\n}\n.ant-table-column-sorter-inner {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n}\n.ant-table-column-sorter-up,\n.ant-table-column-sorter-down {\n font-size: 11px;\n}\n.ant-table-column-sorter-up.active,\n.ant-table-column-sorter-down.active {\n color: #1890ff;\n}\n.ant-table-column-sorter-up + .ant-table-column-sorter-down {\n margin-top: -0.3em;\n}\n.ant-table-column-sorters:hover .ant-table-column-sorter {\n color: #a6a6a6;\n}\n.ant-table-filter-column {\n display: flex;\n justify-content: space-between;\n}\n.ant-table-filter-trigger {\n position: relative;\n display: flex;\n align-items: center;\n margin: -4px -8px -4px 4px;\n padding: 0 4px;\n color: #bfbfbf;\n font-size: 12px;\n border-radius: 2px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-table-filter-trigger:hover {\n color: rgba(0, 0, 0, 0.45);\n background: rgba(0, 0, 0, 0.04);\n}\n.ant-table-filter-trigger.active {\n color: #1890ff;\n}\n.ant-table-filter-dropdown {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n min-width: 120px;\n background-color: #fff;\n border-radius: 2px;\n box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05);\n}\n.ant-table-filter-dropdown .ant-dropdown-menu {\n max-height: 264px;\n overflow-x: hidden;\n border: 0;\n box-shadow: none;\n}\n.ant-table-filter-dropdown .ant-dropdown-menu:empty::after {\n display: block;\n padding: 8px 0;\n color: rgba(0, 0, 0, 0.25);\n font-size: 12px;\n text-align: center;\n content: 'Not Found';\n}\n.ant-table-filter-dropdown-tree {\n padding: 8px 8px 0;\n}\n.ant-table-filter-dropdown-tree .ant-tree-treenode .ant-tree-node-content-wrapper:hover {\n background-color: #f5f5f5;\n}\n.ant-table-filter-dropdown-tree .ant-tree-treenode-checkbox-checked .ant-tree-node-content-wrapper,\n.ant-table-filter-dropdown-tree .ant-tree-treenode-checkbox-checked .ant-tree-node-content-wrapper:hover {\n background-color: #bae7ff;\n}\n.ant-table-filter-dropdown-search {\n padding: 8px;\n border-bottom: 1px #f0f0f0 solid;\n}\n.ant-table-filter-dropdown-search-input input {\n min-width: 140px;\n}\n.ant-table-filter-dropdown-search-input .anticon {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-table-filter-dropdown-checkall {\n width: 100%;\n margin-bottom: 4px;\n margin-left: 4px;\n}\n.ant-table-filter-dropdown-submenu > ul {\n max-height: calc(100vh - 130px);\n overflow-x: hidden;\n overflow-y: auto;\n}\n.ant-table-filter-dropdown .ant-checkbox-wrapper + span,\n.ant-table-filter-dropdown-submenu .ant-checkbox-wrapper + span {\n padding-left: 8px;\n}\n.ant-table-filter-dropdown-btns {\n display: flex;\n justify-content: space-between;\n padding: 7px 8px;\n overflow: hidden;\n background-color: inherit;\n border-top: 1px solid #f0f0f0;\n}\n.ant-table-selection-col {\n width: 32px;\n}\n.ant-table-bordered .ant-table-selection-col {\n width: 50px;\n}\ntable tr th.ant-table-selection-column,\ntable tr td.ant-table-selection-column {\n padding-right: 8px;\n padding-left: 8px;\n text-align: center;\n}\ntable tr th.ant-table-selection-column .ant-radio-wrapper,\ntable tr td.ant-table-selection-column .ant-radio-wrapper {\n margin-right: 0;\n}\ntable tr th.ant-table-selection-column.ant-table-cell-fix-left {\n z-index: 3;\n}\ntable tr th.ant-table-selection-column::after {\n background-color: transparent !important;\n}\n.ant-table-selection {\n position: relative;\n display: inline-flex;\n flex-direction: column;\n}\n.ant-table-selection-extra {\n position: absolute;\n top: 0;\n z-index: 1;\n cursor: pointer;\n transition: all 0.3s;\n -webkit-margin-start: 100%;\n margin-inline-start: 100%;\n -webkit-padding-start: 4px;\n padding-inline-start: 4px;\n}\n.ant-table-selection-extra .anticon {\n color: #bfbfbf;\n font-size: 10px;\n}\n.ant-table-selection-extra .anticon:hover {\n color: #a6a6a6;\n}\n.ant-table-expand-icon-col {\n width: 48px;\n}\n.ant-table-row-expand-icon-cell {\n text-align: center;\n}\n.ant-table-row-expand-icon-cell .ant-table-row-expand-icon {\n display: inline-flex;\n float: none;\n vertical-align: sub;\n}\n.ant-table-row-indent {\n float: left;\n height: 1px;\n}\n.ant-table-row-expand-icon {\n color: #1890ff;\n outline: none;\n cursor: pointer;\n transition: color 0.3s;\n position: relative;\n float: left;\n box-sizing: border-box;\n width: 17px;\n height: 17px;\n padding: 0;\n color: inherit;\n line-height: 17px;\n background: #fff;\n border: 1px solid #f0f0f0;\n border-radius: 2px;\n transform: scale(0.94117647);\n transition: all 0.3s;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-table-row-expand-icon:focus-visible,\n.ant-table-row-expand-icon:hover {\n color: #40a9ff;\n}\n.ant-table-row-expand-icon:active {\n color: #096dd9;\n}\n.ant-table-row-expand-icon:focus,\n.ant-table-row-expand-icon:hover,\n.ant-table-row-expand-icon:active {\n border-color: currentcolor;\n}\n.ant-table-row-expand-icon::before,\n.ant-table-row-expand-icon::after {\n position: absolute;\n background: currentcolor;\n transition: transform 0.3s ease-out;\n content: '';\n}\n.ant-table-row-expand-icon::before {\n top: 7px;\n right: 3px;\n left: 3px;\n height: 1px;\n}\n.ant-table-row-expand-icon::after {\n top: 3px;\n bottom: 3px;\n left: 7px;\n width: 1px;\n transform: rotate(90deg);\n}\n.ant-table-row-expand-icon-collapsed::before {\n transform: rotate(-180deg);\n}\n.ant-table-row-expand-icon-collapsed::after {\n transform: rotate(0deg);\n}\n.ant-table-row-expand-icon-spaced {\n background: transparent;\n border: 0;\n visibility: hidden;\n}\n.ant-table-row-expand-icon-spaced::before,\n.ant-table-row-expand-icon-spaced::after {\n display: none;\n content: none;\n}\n.ant-table-row-indent + .ant-table-row-expand-icon {\n margin-top: 2.5005px;\n margin-right: 8px;\n}\ntr.ant-table-expanded-row > td,\ntr.ant-table-expanded-row:hover > td {\n background: #fbfbfb;\n}\ntr.ant-table-expanded-row .ant-descriptions-view {\n display: flex;\n}\ntr.ant-table-expanded-row .ant-descriptions-view table {\n flex: auto;\n width: auto;\n}\n.ant-table .ant-table-expanded-row-fixed {\n position: relative;\n margin: -16px -16px;\n padding: 16px 16px;\n}\n.ant-table-tbody > tr.ant-table-placeholder {\n text-align: center;\n}\n.ant-table-empty .ant-table-tbody > tr.ant-table-placeholder {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-table-tbody > tr.ant-table-placeholder:hover > td {\n background: #fff;\n}\n.ant-table-cell-fix-left,\n.ant-table-cell-fix-right {\n position: sticky !important;\n z-index: 2;\n background: #fff;\n}\n.ant-table-cell-fix-left-first::after,\n.ant-table-cell-fix-left-last::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: -1px;\n width: 30px;\n transform: translateX(100%);\n transition: box-shadow 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-table-cell-fix-left-all::after {\n display: none;\n}\n.ant-table-cell-fix-right-first::after,\n.ant-table-cell-fix-right-last::after {\n position: absolute;\n top: 0;\n bottom: -1px;\n left: 0;\n width: 30px;\n transform: translateX(-100%);\n transition: box-shadow 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-table .ant-table-container::before,\n.ant-table .ant-table-container::after {\n position: absolute;\n top: 0;\n bottom: 0;\n z-index: calc(calc(2 + 1) + 1);\n width: 30px;\n transition: box-shadow 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-table .ant-table-container::before {\n left: 0;\n}\n.ant-table .ant-table-container::after {\n right: 0;\n}\n.ant-table-ping-left:not(.ant-table-has-fix-left) > .ant-table-container {\n position: relative;\n}\n.ant-table-ping-left:not(.ant-table-has-fix-left) > .ant-table-container::before {\n box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.15);\n}\n.ant-table-ping-left .ant-table-cell-fix-left-first::after,\n.ant-table-ping-left .ant-table-cell-fix-left-last::after {\n box-shadow: inset 10px 0 8px -8px rgba(0, 0, 0, 0.15);\n}\n.ant-table-ping-left .ant-table-cell-fix-left-last::before {\n background-color: transparent !important;\n}\n.ant-table-ping-right:not(.ant-table-has-fix-right) > .ant-table-container {\n position: relative;\n}\n.ant-table-ping-right:not(.ant-table-has-fix-right) > .ant-table-container::after {\n box-shadow: inset -10px 0 8px -8px rgba(0, 0, 0, 0.15);\n}\n.ant-table-ping-right .ant-table-cell-fix-right-first::after,\n.ant-table-ping-right .ant-table-cell-fix-right-last::after {\n box-shadow: inset -10px 0 8px -8px rgba(0, 0, 0, 0.15);\n}\n.ant-table-sticky-holder {\n position: sticky;\n z-index: calc(2 + 1);\n background: #fff;\n}\n.ant-table-sticky-scroll {\n position: sticky;\n bottom: 0;\n z-index: calc(2 + 1);\n display: flex;\n align-items: center;\n background: #ffffff;\n border-top: 1px solid #f0f0f0;\n opacity: 0.6;\n}\n.ant-table-sticky-scroll:hover {\n transform-origin: center bottom;\n}\n.ant-table-sticky-scroll-bar {\n height: 8px;\n background-color: rgba(0, 0, 0, 0.35);\n border-radius: 4px;\n}\n.ant-table-sticky-scroll-bar:hover {\n background-color: rgba(0, 0, 0, 0.8);\n}\n.ant-table-sticky-scroll-bar-active {\n background-color: rgba(0, 0, 0, 0.8);\n}\n@media all and (-ms-high-contrast: none) {\n .ant-table-ping-left .ant-table-cell-fix-left-last::after {\n box-shadow: none !important;\n }\n .ant-table-ping-right .ant-table-cell-fix-right-first::after {\n box-shadow: none !important;\n }\n}\n.ant-table {\n /* title + table */\n /* table */\n /* table + footer */\n}\n.ant-table-title {\n border-radius: 2px 2px 0 0;\n}\n.ant-table-title + .ant-table-container {\n border-top-left-radius: 0;\n border-top-right-radius: 0;\n}\n.ant-table-title + .ant-table-container table {\n border-radius: 0;\n}\n.ant-table-title + .ant-table-container table > thead > tr:first-child th:first-child {\n border-radius: 0;\n}\n.ant-table-title + .ant-table-container table > thead > tr:first-child th:last-child {\n border-radius: 0;\n}\n.ant-table-container {\n border-top-left-radius: 2px;\n border-top-right-radius: 2px;\n}\n.ant-table-container table > thead > tr:first-child th:first-child {\n border-top-left-radius: 2px;\n}\n.ant-table-container table > thead > tr:first-child th:last-child {\n border-top-right-radius: 2px;\n}\n.ant-table-footer {\n border-radius: 0 0 2px 2px;\n}\n.ant-table-wrapper-rtl {\n direction: rtl;\n}\n.ant-table-rtl {\n direction: rtl;\n}\n.ant-table-wrapper-rtl .ant-table table {\n text-align: right;\n}\n.ant-table-wrapper-rtl .ant-table-thead > tr > th[colspan]:not([colspan='1']) {\n text-align: center;\n}\n.ant-table-wrapper-rtl .ant-table-thead > tr > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before {\n right: auto;\n left: 0;\n}\n.ant-table-wrapper-rtl .ant-table-thead > tr > th {\n text-align: right;\n}\n.ant-table-tbody > tr .ant-table-wrapper:only-child .ant-table.ant-table-rtl {\n margin: -16px 33px -16px -16px;\n}\n.ant-table-wrapper.ant-table-wrapper-rtl .ant-table-pagination-left {\n justify-content: flex-end;\n}\n.ant-table-wrapper.ant-table-wrapper-rtl .ant-table-pagination-right {\n justify-content: flex-start;\n}\n.ant-table-wrapper-rtl .ant-table-column-sorter {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-table-wrapper-rtl .ant-table-filter-column-title {\n padding: 16px 16px 16px 2.3em;\n}\n.ant-table-rtl .ant-table-thead tr th.ant-table-column-has-sorters .ant-table-filter-column-title {\n padding: 0 0 0 2.3em;\n}\n.ant-table-wrapper-rtl .ant-table-filter-trigger {\n margin: -4px 4px -4px -8px;\n}\n.ant-dropdown-rtl .ant-table-filter-dropdown .ant-checkbox-wrapper + span,\n.ant-dropdown-rtl .ant-table-filter-dropdown-submenu .ant-checkbox-wrapper + span,\n.ant-dropdown-menu-submenu-rtl.ant-table-filter-dropdown .ant-checkbox-wrapper + span,\n.ant-dropdown-menu-submenu-rtl.ant-table-filter-dropdown-submenu .ant-checkbox-wrapper + span {\n padding-right: 8px;\n padding-left: 0;\n}\n.ant-table-wrapper-rtl .ant-table-selection {\n text-align: center;\n}\n.ant-table-wrapper-rtl .ant-table-row-indent {\n float: right;\n}\n.ant-table-wrapper-rtl .ant-table-row-expand-icon {\n float: right;\n}\n.ant-table-wrapper-rtl .ant-table-row-indent + .ant-table-row-expand-icon {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-table-wrapper-rtl .ant-table-row-expand-icon::after {\n transform: rotate(-90deg);\n}\n.ant-table-wrapper-rtl .ant-table-row-expand-icon-collapsed::before {\n transform: rotate(180deg);\n}\n.ant-table-wrapper-rtl .ant-table-row-expand-icon-collapsed::after {\n transform: rotate(0deg);\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n@keyframes antCheckboxEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n@keyframes ant-tree-node-fx-do-not-use {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode {\n position: relative;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode::before {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 4px;\n left: 0;\n transition: background-color 0.3s;\n content: '';\n pointer-events: none;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode:hover::before {\n background: #f5f5f5;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode > * {\n z-index: 1;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode .ant-tree-switcher {\n transition: color 0.3s;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode .ant-tree-node-content-wrapper {\n border-radius: 0;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode .ant-tree-node-content-wrapper:hover {\n background: transparent;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode .ant-tree-node-content-wrapper.ant-tree-node-selected {\n color: #fff;\n background: transparent;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode-selected:hover::before,\n.ant-tree.ant-tree-directory .ant-tree-treenode-selected::before {\n background: #1890ff;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode-selected .ant-tree-switcher {\n color: #fff;\n}\n.ant-tree.ant-tree-directory .ant-tree-treenode-selected .ant-tree-node-content-wrapper {\n color: #fff;\n background: transparent;\n}\n.ant-tree-checkbox {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n top: 0.2em;\n line-height: 1;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n}\n.ant-tree-checkbox-wrapper:hover .ant-tree-checkbox-inner,\n.ant-tree-checkbox:hover .ant-tree-checkbox-inner,\n.ant-tree-checkbox-input:focus + .ant-tree-checkbox-inner {\n border-color: #1890ff;\n}\n.ant-tree-checkbox-checked::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 2px;\n visibility: hidden;\n animation: antCheckboxEffect 0.36s ease-in-out;\n animation-fill-mode: backwards;\n content: '';\n}\n.ant-tree-checkbox:hover::after,\n.ant-tree-checkbox-wrapper:hover .ant-tree-checkbox::after {\n visibility: visible;\n}\n.ant-tree-checkbox-inner {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n width: 16px;\n height: 16px;\n direction: ltr;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n border-collapse: separate;\n transition: all 0.3s;\n}\n.ant-tree-checkbox-inner::after {\n position: absolute;\n top: 50%;\n left: 21.5%;\n display: table;\n width: 5.71428571px;\n height: 9.14285714px;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(0) translate(-50%, -50%);\n opacity: 0;\n transition: all 0.1s cubic-bezier(0.71, -0.46, 0.88, 0.6), opacity 0.1s;\n content: ' ';\n}\n.ant-tree-checkbox-input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n width: 100%;\n height: 100%;\n cursor: pointer;\n opacity: 0;\n}\n.ant-tree-checkbox-checked .ant-tree-checkbox-inner::after {\n position: absolute;\n display: table;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(1) translate(-50%, -50%);\n opacity: 1;\n transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;\n content: ' ';\n}\n.ant-tree-checkbox-checked .ant-tree-checkbox-inner {\n background-color: #1890ff;\n border-color: #1890ff;\n}\n.ant-tree-checkbox-disabled {\n cursor: not-allowed;\n}\n.ant-tree-checkbox-disabled.ant-tree-checkbox-checked .ant-tree-checkbox-inner::after {\n border-color: rgba(0, 0, 0, 0.25);\n animation-name: none;\n}\n.ant-tree-checkbox-disabled .ant-tree-checkbox-input {\n cursor: not-allowed;\n pointer-events: none;\n}\n.ant-tree-checkbox-disabled .ant-tree-checkbox-inner {\n background-color: #f5f5f5;\n border-color: #d9d9d9 !important;\n}\n.ant-tree-checkbox-disabled .ant-tree-checkbox-inner::after {\n border-color: #f5f5f5;\n border-collapse: separate;\n animation-name: none;\n}\n.ant-tree-checkbox-disabled + span {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-tree-checkbox-disabled:hover::after,\n.ant-tree-checkbox-wrapper:hover .ant-tree-checkbox-disabled::after {\n visibility: hidden;\n}\n.ant-tree-checkbox-wrapper {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-flex;\n align-items: baseline;\n line-height: unset;\n cursor: pointer;\n}\n.ant-tree-checkbox-wrapper::after {\n display: inline-block;\n width: 0;\n overflow: hidden;\n content: '\\a0';\n}\n.ant-tree-checkbox-wrapper.ant-tree-checkbox-wrapper-disabled {\n cursor: not-allowed;\n}\n.ant-tree-checkbox-wrapper + .ant-tree-checkbox-wrapper {\n margin-left: 8px;\n}\n.ant-tree-checkbox-wrapper.ant-tree-checkbox-wrapper-in-form-item input[type='checkbox'] {\n width: 14px;\n height: 14px;\n}\n.ant-tree-checkbox + span {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-tree-checkbox-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n}\n.ant-tree-checkbox-group-item {\n margin-right: 8px;\n}\n.ant-tree-checkbox-group-item:last-child {\n margin-right: 0;\n}\n.ant-tree-checkbox-group-item + .ant-tree-checkbox-group-item {\n margin-left: 0;\n}\n.ant-tree-checkbox-indeterminate .ant-tree-checkbox-inner {\n background-color: #fff;\n border-color: #d9d9d9;\n}\n.ant-tree-checkbox-indeterminate .ant-tree-checkbox-inner::after {\n top: 50%;\n left: 50%;\n width: 8px;\n height: 8px;\n background-color: #1890ff;\n border: 0;\n transform: translate(-50%, -50%) scale(1);\n opacity: 1;\n content: ' ';\n}\n.ant-tree-checkbox-indeterminate.ant-tree-checkbox-disabled .ant-tree-checkbox-inner::after {\n background-color: rgba(0, 0, 0, 0.25);\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-tree {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n background: #fff;\n border-radius: 2px;\n transition: background-color 0.3s;\n}\n.ant-tree-focused:not(:hover):not(.ant-tree-active-focused) {\n background: #e6f7ff;\n}\n.ant-tree-list-holder-inner {\n align-items: flex-start;\n}\n.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner {\n align-items: stretch;\n}\n.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-node-content-wrapper {\n flex: auto;\n}\n.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-treenode.dragging {\n position: relative;\n}\n.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-treenode.dragging::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 4px;\n left: 0;\n border: 1px solid #1890ff;\n opacity: 0;\n animation: ant-tree-node-fx-do-not-use 0.3s;\n animation-play-state: running;\n animation-fill-mode: forwards;\n content: '';\n pointer-events: none;\n}\n.ant-tree .ant-tree-treenode {\n display: flex;\n align-items: flex-start;\n padding: 0 0 4px 0;\n outline: none;\n}\n.ant-tree .ant-tree-treenode-disabled .ant-tree-node-content-wrapper {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-tree .ant-tree-treenode-disabled .ant-tree-node-content-wrapper:hover {\n background: transparent;\n}\n.ant-tree .ant-tree-treenode-active .ant-tree-node-content-wrapper {\n background: #f5f5f5;\n}\n.ant-tree .ant-tree-treenode:not(.ant-tree .ant-tree-treenode-disabled).filter-node .ant-tree-title {\n color: inherit;\n font-weight: 500;\n}\n.ant-tree .ant-tree-treenode-draggable .ant-tree-draggable-icon {\n width: 24px;\n line-height: 24px;\n text-align: center;\n visibility: visible;\n opacity: 0.2;\n transition: opacity 0.3s;\n}\n.ant-tree-treenode:hover .ant-tree .ant-tree-treenode-draggable .ant-tree-draggable-icon {\n opacity: 0.45;\n}\n.ant-tree .ant-tree-treenode-draggable.ant-tree-treenode-disabled .ant-tree-draggable-icon {\n visibility: hidden;\n}\n.ant-tree-indent {\n align-self: stretch;\n white-space: nowrap;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-tree-indent-unit {\n display: inline-block;\n width: 24px;\n}\n.ant-tree-draggable-icon {\n visibility: hidden;\n}\n.ant-tree-switcher {\n position: relative;\n flex: none;\n align-self: stretch;\n width: 24px;\n margin: 0;\n line-height: 24px;\n text-align: center;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-tree-switcher .ant-tree-switcher-icon,\n.ant-tree-switcher .ant-select-tree-switcher-icon {\n display: inline-block;\n font-size: 10px;\n vertical-align: baseline;\n}\n.ant-tree-switcher .ant-tree-switcher-icon svg,\n.ant-tree-switcher .ant-select-tree-switcher-icon svg {\n transition: transform 0.3s;\n}\n.ant-tree-switcher-noop {\n cursor: default;\n}\n.ant-tree-switcher_close .ant-tree-switcher-icon svg {\n transform: rotate(-90deg);\n}\n.ant-tree-switcher-loading-icon {\n color: #1890ff;\n}\n.ant-tree-switcher-leaf-line {\n position: relative;\n z-index: 1;\n display: inline-block;\n width: 100%;\n height: 100%;\n}\n.ant-tree-switcher-leaf-line::before {\n position: absolute;\n top: 0;\n right: 12px;\n bottom: -4px;\n margin-left: -1px;\n border-right: 1px solid #d9d9d9;\n content: ' ';\n}\n.ant-tree-switcher-leaf-line::after {\n position: absolute;\n width: 10px;\n height: 14px;\n border-bottom: 1px solid #d9d9d9;\n content: ' ';\n}\n.ant-tree-checkbox {\n top: initial;\n margin: 4px 8px 0 0;\n}\n.ant-tree .ant-tree-node-content-wrapper {\n position: relative;\n z-index: auto;\n min-height: 24px;\n margin: 0;\n padding: 0 4px;\n color: inherit;\n line-height: 24px;\n background: transparent;\n border-radius: 2px;\n cursor: pointer;\n transition: all 0.3s, border 0s, line-height 0s, box-shadow 0s;\n}\n.ant-tree .ant-tree-node-content-wrapper:hover {\n background-color: #f5f5f5;\n}\n.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected {\n background-color: #bae7ff;\n}\n.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle {\n display: inline-block;\n width: 24px;\n height: 24px;\n line-height: 24px;\n text-align: center;\n vertical-align: top;\n}\n.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle:empty {\n display: none;\n}\n.ant-tree-unselectable .ant-tree-node-content-wrapper:hover {\n background-color: transparent;\n}\n.ant-tree-node-content-wrapper {\n line-height: 24px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-tree-node-content-wrapper .ant-tree-drop-indicator {\n position: absolute;\n z-index: 1;\n height: 2px;\n background-color: #1890ff;\n border-radius: 1px;\n pointer-events: none;\n}\n.ant-tree-node-content-wrapper .ant-tree-drop-indicator::after {\n position: absolute;\n top: -3px;\n left: -6px;\n width: 8px;\n height: 8px;\n background-color: transparent;\n border: 2px solid #1890ff;\n border-radius: 50%;\n content: '';\n}\n.ant-tree .ant-tree-treenode.drop-container > [draggable] {\n box-shadow: 0 0 0 2px #1890ff;\n}\n.ant-tree-show-line .ant-tree-indent-unit {\n position: relative;\n height: 100%;\n}\n.ant-tree-show-line .ant-tree-indent-unit::before {\n position: absolute;\n top: 0;\n right: 12px;\n bottom: -4px;\n border-right: 1px solid #d9d9d9;\n content: '';\n}\n.ant-tree-show-line .ant-tree-indent-unit-end::before {\n display: none;\n}\n.ant-tree-show-line .ant-tree-switcher {\n background: #fff;\n}\n.ant-tree-show-line .ant-tree-switcher-line-icon {\n vertical-align: -0.15em;\n}\n.ant-tree .ant-tree-treenode-leaf-last .ant-tree-switcher-leaf-line::before {\n top: auto !important;\n bottom: auto !important;\n height: 14px !important;\n}\n.ant-tree-rtl {\n direction: rtl;\n}\n.ant-tree-rtl .ant-tree-node-content-wrapper[draggable='true'] .ant-tree-drop-indicator::after {\n right: -6px;\n left: unset;\n}\n.ant-tree .ant-tree-treenode-rtl {\n direction: rtl;\n}\n.ant-tree-rtl .ant-tree-switcher_close .ant-tree-switcher-icon svg {\n transform: rotate(90deg);\n}\n.ant-tree-rtl.ant-tree-show-line .ant-tree-indent-unit::before {\n right: auto;\n left: -13px;\n border-right: none;\n border-left: 1px solid #d9d9d9;\n}\n.ant-tree-rtl .ant-tree-checkbox {\n margin: 4px 0 0 8px;\n}\n.ant-tree-select-dropdown-rtl .ant-select-tree-checkbox {\n margin: 4px 0 0 8px;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-timeline {\n box-sizing: border-box;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n font-feature-settings: 'tnum';\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.ant-timeline-item {\n position: relative;\n margin: 0;\n padding-bottom: 20px;\n font-size: 14px;\n list-style: none;\n}\n.ant-timeline-item-tail {\n position: absolute;\n top: 10px;\n left: 4px;\n height: calc(100% - 10px);\n border-left: 2px solid #f0f0f0;\n}\n.ant-timeline-item-pending .ant-timeline-item-head {\n font-size: 12px;\n background-color: transparent;\n}\n.ant-timeline-item-pending .ant-timeline-item-tail {\n display: none;\n}\n.ant-timeline-item-head {\n position: absolute;\n width: 10px;\n height: 10px;\n background-color: #fff;\n border: 2px solid transparent;\n border-radius: 100px;\n}\n.ant-timeline-item-head-blue {\n color: #1890ff;\n border-color: #1890ff;\n}\n.ant-timeline-item-head-red {\n color: #ff4d4f;\n border-color: #ff4d4f;\n}\n.ant-timeline-item-head-green {\n color: #52c41a;\n border-color: #52c41a;\n}\n.ant-timeline-item-head-gray {\n color: rgba(0, 0, 0, 0.25);\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-timeline-item-head-custom {\n position: absolute;\n top: 5.5px;\n left: 5px;\n width: auto;\n height: auto;\n margin-top: 0;\n padding: 3px 1px;\n line-height: 1;\n text-align: center;\n border: 0;\n border-radius: 0;\n transform: translate(-50%, -50%);\n}\n.ant-timeline-item-content {\n position: relative;\n top: -7.001px;\n margin: 0 0 0 26px;\n word-break: break-word;\n}\n.ant-timeline-item-last > .ant-timeline-item-tail {\n display: none;\n}\n.ant-timeline-item-last > .ant-timeline-item-content {\n min-height: 48px;\n}\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-tail,\n.ant-timeline.ant-timeline-right .ant-timeline-item-tail,\n.ant-timeline.ant-timeline-label .ant-timeline-item-tail,\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-head,\n.ant-timeline.ant-timeline-right .ant-timeline-item-head,\n.ant-timeline.ant-timeline-label .ant-timeline-item-head,\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-head-custom,\n.ant-timeline.ant-timeline-right .ant-timeline-item-head-custom,\n.ant-timeline.ant-timeline-label .ant-timeline-item-head-custom {\n left: 50%;\n}\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-head,\n.ant-timeline.ant-timeline-right .ant-timeline-item-head,\n.ant-timeline.ant-timeline-label .ant-timeline-item-head {\n margin-left: -4px;\n}\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-head-custom,\n.ant-timeline.ant-timeline-right .ant-timeline-item-head-custom,\n.ant-timeline.ant-timeline-label .ant-timeline-item-head-custom {\n margin-left: 1px;\n}\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-left .ant-timeline-item-content,\n.ant-timeline.ant-timeline-right .ant-timeline-item-left .ant-timeline-item-content,\n.ant-timeline.ant-timeline-label .ant-timeline-item-left .ant-timeline-item-content {\n left: calc(50% - 4px);\n width: calc(50% - 14px);\n text-align: left;\n}\n.ant-timeline.ant-timeline-alternate .ant-timeline-item-right .ant-timeline-item-content,\n.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-content,\n.ant-timeline.ant-timeline-label .ant-timeline-item-right .ant-timeline-item-content {\n width: calc(50% - 12px);\n margin: 0;\n text-align: right;\n}\n.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-tail,\n.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-head,\n.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-head-custom {\n left: calc(100% - 4px - 2px);\n}\n.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-content {\n width: calc(100% - 18px);\n}\n.ant-timeline.ant-timeline-pending .ant-timeline-item-last .ant-timeline-item-tail {\n display: block;\n height: calc(100% - 14px);\n border-left: 2px dotted #f0f0f0;\n}\n.ant-timeline.ant-timeline-reverse .ant-timeline-item-last .ant-timeline-item-tail {\n display: none;\n}\n.ant-timeline.ant-timeline-reverse .ant-timeline-item-pending .ant-timeline-item-tail {\n top: 15px;\n display: block;\n height: calc(100% - 15px);\n border-left: 2px dotted #f0f0f0;\n}\n.ant-timeline.ant-timeline-reverse .ant-timeline-item-pending .ant-timeline-item-content {\n min-height: 48px;\n}\n.ant-timeline.ant-timeline-label .ant-timeline-item-label {\n position: absolute;\n top: -7.001px;\n width: calc(50% - 12px);\n text-align: right;\n}\n.ant-timeline.ant-timeline-label .ant-timeline-item-right .ant-timeline-item-label {\n left: calc(50% + 14px);\n width: calc(50% - 14px);\n text-align: left;\n}\n.ant-timeline-rtl {\n direction: rtl;\n}\n.ant-timeline-rtl .ant-timeline-item-tail {\n right: 4px;\n left: auto;\n border-right: 2px solid #f0f0f0;\n border-left: none;\n}\n.ant-timeline-rtl .ant-timeline-item-head-custom {\n right: 5px;\n left: auto;\n transform: translate(50%, -50%);\n}\n.ant-timeline-rtl .ant-timeline-item-content {\n margin: 0 18px 0 0;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-tail,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-tail,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-tail,\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-head-custom,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-head-custom,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-head-custom {\n right: 50%;\n left: auto;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-head {\n margin-right: -4px;\n margin-left: 0;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-head-custom,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-head-custom,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-head-custom {\n margin-right: 1px;\n margin-left: 0;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-left .ant-timeline-item-content,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-left .ant-timeline-item-content,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-left .ant-timeline-item-content {\n right: calc(50% - 4px);\n left: auto;\n text-align: right;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-alternate .ant-timeline-item-right .ant-timeline-item-content,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-content,\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-right .ant-timeline-item-content {\n text-align: left;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-tail,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-head,\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-head-custom {\n right: 0;\n left: auto;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-right .ant-timeline-item-right .ant-timeline-item-content {\n width: 100%;\n margin-right: 18px;\n text-align: right;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-pending .ant-timeline-item-last .ant-timeline-item-tail {\n border-right: 2px dotted #f0f0f0;\n border-left: none;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-reverse .ant-timeline-item-pending .ant-timeline-item-tail {\n border-right: 2px dotted #f0f0f0;\n border-left: none;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-label {\n text-align: left;\n}\n.ant-timeline-rtl.ant-timeline.ant-timeline-label .ant-timeline-item-right .ant-timeline-item-label {\n right: calc(50% + 14px);\n text-align: right;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n@keyframes antCheckboxEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n.ant-transfer-customize-list .ant-transfer-list {\n flex: 1 1 50%;\n width: auto;\n height: auto;\n min-height: 200px;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-small {\n border: 0;\n border-radius: 0;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-small .ant-table-selection-column {\n width: 40px;\n min-width: 40px;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-small > .ant-table-content > .ant-table-body > table > .ant-table-thead > tr > th {\n background: #fafafa;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-small > .ant-table-content .ant-table-row:last-child td {\n border-bottom: 1px solid #f0f0f0;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-small .ant-table-body {\n margin: 0;\n}\n.ant-transfer-customize-list .ant-table-wrapper .ant-table-pagination.ant-pagination {\n margin: 16px 0 4px;\n}\n.ant-transfer-customize-list .ant-input[disabled] {\n background-color: transparent;\n}\n.ant-transfer-status-error .ant-transfer-list {\n border-color: #ff4d4f;\n}\n.ant-transfer-status-error .ant-transfer-list-search:not([disabled]) {\n border-color: #d9d9d9;\n}\n.ant-transfer-status-error .ant-transfer-list-search:not([disabled]):hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-transfer-status-error .ant-transfer-list-search:not([disabled]):focus {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-transfer-status-warning .ant-transfer-list {\n border-color: #faad14;\n}\n.ant-transfer-status-warning .ant-transfer-list-search:not([disabled]) {\n border-color: #d9d9d9;\n}\n.ant-transfer-status-warning .ant-transfer-list-search:not([disabled]):hover {\n border-color: #40a9ff;\n border-right-width: 1px;\n}\n.ant-transfer-status-warning .ant-transfer-list-search:not([disabled]):focus {\n border-color: #40a9ff;\n box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);\n border-right-width: 1px;\n outline: 0;\n}\n.ant-transfer {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n display: flex;\n align-items: stretch;\n}\n.ant-transfer-disabled .ant-transfer-list {\n background: #f5f5f5;\n}\n.ant-transfer-list {\n display: flex;\n flex-direction: column;\n width: 180px;\n height: 200px;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n}\n.ant-transfer-list-with-pagination {\n width: 250px;\n height: auto;\n}\n.ant-transfer-list-search .anticon-search {\n color: rgba(0, 0, 0, 0.25);\n}\n.ant-transfer-list-header {\n display: flex;\n flex: none;\n align-items: center;\n height: 40px;\n padding: 8px 12px 9px;\n color: rgba(0, 0, 0, 0.85);\n background: #fff;\n border-bottom: 1px solid #f0f0f0;\n border-radius: 2px 2px 0 0;\n}\n.ant-transfer-list-header > *:not(:last-child) {\n margin-right: 4px;\n}\n.ant-transfer-list-header > * {\n flex: none;\n}\n.ant-transfer-list-header-title {\n flex: auto;\n overflow: hidden;\n white-space: nowrap;\n text-align: right;\n text-overflow: ellipsis;\n}\n.ant-transfer-list-header-dropdown {\n font-size: 10px;\n transform: translateY(10%);\n cursor: pointer;\n}\n.ant-transfer-list-header-dropdown[disabled] {\n cursor: not-allowed;\n}\n.ant-transfer-list-body {\n display: flex;\n flex: auto;\n flex-direction: column;\n overflow: hidden;\n font-size: 14px;\n}\n.ant-transfer-list-body-search-wrapper {\n position: relative;\n flex: none;\n padding: 12px;\n}\n.ant-transfer-list-content {\n flex: auto;\n margin: 0;\n padding: 0;\n overflow: auto;\n list-style: none;\n}\n.ant-transfer-list-content-item {\n display: flex;\n align-items: center;\n min-height: 32px;\n padding: 6px 12px;\n line-height: 20px;\n transition: all 0.3s;\n}\n.ant-transfer-list-content-item > *:not(:last-child) {\n margin-right: 8px;\n}\n.ant-transfer-list-content-item > * {\n flex: none;\n}\n.ant-transfer-list-content-item-text {\n flex: auto;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-transfer-list-content-item-remove {\n position: relative;\n color: #d9d9d9;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-transfer-list-content-item-remove:hover {\n color: #40a9ff;\n}\n.ant-transfer-list-content-item-remove::after {\n position: absolute;\n top: -6px;\n right: -50%;\n bottom: -6px;\n left: -50%;\n content: '';\n}\n.ant-transfer-list-content-item:not(.ant-transfer-list-content-item-disabled):hover {\n background-color: #f5f5f5;\n cursor: pointer;\n}\n.ant-transfer-list-content-item:not(.ant-transfer-list-content-item-disabled).ant-transfer-list-content-item-checked:hover {\n background-color: #dcf4ff;\n}\n.ant-transfer-list-content-show-remove .ant-transfer-list-content-item:not(.ant-transfer-list-content-item-disabled):hover {\n background: transparent;\n cursor: default;\n}\n.ant-transfer-list-content-item-checked {\n background-color: #e6f7ff;\n}\n.ant-transfer-list-content-item-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-transfer-list-pagination {\n padding: 8px 0;\n text-align: right;\n border-top: 1px solid #f0f0f0;\n}\n.ant-transfer-list-body-not-found {\n flex: none;\n width: 100%;\n margin: auto 0;\n color: rgba(0, 0, 0, 0.25);\n text-align: center;\n}\n.ant-transfer-list-footer {\n border-top: 1px solid #f0f0f0;\n}\n.ant-transfer-operation {\n display: flex;\n flex: none;\n flex-direction: column;\n align-self: center;\n margin: 0 8px;\n vertical-align: middle;\n}\n.ant-transfer-operation .ant-btn {\n display: block;\n}\n.ant-transfer-operation .ant-btn:first-child {\n margin-bottom: 4px;\n}\n.ant-transfer-operation .ant-btn .anticon {\n font-size: 12px;\n}\n.ant-transfer .ant-empty-image {\n max-height: -2px;\n}\n.ant-transfer-rtl {\n direction: rtl;\n}\n.ant-transfer-rtl .ant-transfer-list-search {\n padding-right: 8px;\n padding-left: 24px;\n}\n.ant-transfer-rtl .ant-transfer-list-search-action {\n right: auto;\n left: 12px;\n}\n.ant-transfer-rtl .ant-transfer-list-header > *:not(:last-child) {\n margin-right: 0;\n margin-left: 4px;\n}\n.ant-transfer-rtl .ant-transfer-list-header {\n right: 0;\n left: auto;\n}\n.ant-transfer-rtl .ant-transfer-list-header-title {\n text-align: left;\n}\n.ant-transfer-rtl .ant-transfer-list-content-item > *:not(:last-child) {\n margin-right: 0;\n margin-left: 8px;\n}\n.ant-transfer-rtl .ant-transfer-list-pagination {\n text-align: left;\n}\n.ant-transfer-rtl .ant-transfer-list-footer {\n right: 0;\n left: auto;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n@keyframes ant-tree-node-fx-do-not-use {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n@keyframes antCheckboxEffect {\n 0% {\n transform: scale(1);\n opacity: 0.5;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n}\n.ant-select-tree-checkbox {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n position: relative;\n top: 0.2em;\n line-height: 1;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n}\n.ant-select-tree-checkbox-wrapper:hover .ant-select-tree-checkbox-inner,\n.ant-select-tree-checkbox:hover .ant-select-tree-checkbox-inner,\n.ant-select-tree-checkbox-input:focus + .ant-select-tree-checkbox-inner {\n border-color: #1890ff;\n}\n.ant-select-tree-checkbox-checked::after {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n border: 1px solid #1890ff;\n border-radius: 2px;\n visibility: hidden;\n animation: antCheckboxEffect 0.36s ease-in-out;\n animation-fill-mode: backwards;\n content: '';\n}\n.ant-select-tree-checkbox:hover::after,\n.ant-select-tree-checkbox-wrapper:hover .ant-select-tree-checkbox::after {\n visibility: visible;\n}\n.ant-select-tree-checkbox-inner {\n position: relative;\n top: 0;\n left: 0;\n display: block;\n width: 16px;\n height: 16px;\n direction: ltr;\n background-color: #fff;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n border-collapse: separate;\n transition: all 0.3s;\n}\n.ant-select-tree-checkbox-inner::after {\n position: absolute;\n top: 50%;\n left: 21.5%;\n display: table;\n width: 5.71428571px;\n height: 9.14285714px;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(0) translate(-50%, -50%);\n opacity: 0;\n transition: all 0.1s cubic-bezier(0.71, -0.46, 0.88, 0.6), opacity 0.1s;\n content: ' ';\n}\n.ant-select-tree-checkbox-input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1;\n width: 100%;\n height: 100%;\n cursor: pointer;\n opacity: 0;\n}\n.ant-select-tree-checkbox-checked .ant-select-tree-checkbox-inner::after {\n position: absolute;\n display: table;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n transform: rotate(45deg) scale(1) translate(-50%, -50%);\n opacity: 1;\n transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;\n content: ' ';\n}\n.ant-select-tree-checkbox-checked .ant-select-tree-checkbox-inner {\n background-color: #1890ff;\n border-color: #1890ff;\n}\n.ant-select-tree-checkbox-disabled {\n cursor: not-allowed;\n}\n.ant-select-tree-checkbox-disabled.ant-select-tree-checkbox-checked .ant-select-tree-checkbox-inner::after {\n border-color: rgba(0, 0, 0, 0.25);\n animation-name: none;\n}\n.ant-select-tree-checkbox-disabled .ant-select-tree-checkbox-input {\n cursor: not-allowed;\n pointer-events: none;\n}\n.ant-select-tree-checkbox-disabled .ant-select-tree-checkbox-inner {\n background-color: #f5f5f5;\n border-color: #d9d9d9 !important;\n}\n.ant-select-tree-checkbox-disabled .ant-select-tree-checkbox-inner::after {\n border-color: #f5f5f5;\n border-collapse: separate;\n animation-name: none;\n}\n.ant-select-tree-checkbox-disabled + span {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-select-tree-checkbox-disabled:hover::after,\n.ant-select-tree-checkbox-wrapper:hover .ant-select-tree-checkbox-disabled::after {\n visibility: hidden;\n}\n.ant-select-tree-checkbox-wrapper {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-flex;\n align-items: baseline;\n line-height: unset;\n cursor: pointer;\n}\n.ant-select-tree-checkbox-wrapper::after {\n display: inline-block;\n width: 0;\n overflow: hidden;\n content: '\\a0';\n}\n.ant-select-tree-checkbox-wrapper.ant-select-tree-checkbox-wrapper-disabled {\n cursor: not-allowed;\n}\n.ant-select-tree-checkbox-wrapper + .ant-select-tree-checkbox-wrapper {\n margin-left: 8px;\n}\n.ant-select-tree-checkbox-wrapper.ant-select-tree-checkbox-wrapper-in-form-item input[type='checkbox'] {\n width: 14px;\n height: 14px;\n}\n.ant-select-tree-checkbox + span {\n padding-right: 8px;\n padding-left: 8px;\n}\n.ant-select-tree-checkbox-group {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n display: inline-block;\n}\n.ant-select-tree-checkbox-group-item {\n margin-right: 8px;\n}\n.ant-select-tree-checkbox-group-item:last-child {\n margin-right: 0;\n}\n.ant-select-tree-checkbox-group-item + .ant-select-tree-checkbox-group-item {\n margin-left: 0;\n}\n.ant-select-tree-checkbox-indeterminate .ant-select-tree-checkbox-inner {\n background-color: #fff;\n border-color: #d9d9d9;\n}\n.ant-select-tree-checkbox-indeterminate .ant-select-tree-checkbox-inner::after {\n top: 50%;\n left: 50%;\n width: 8px;\n height: 8px;\n background-color: #1890ff;\n border: 0;\n transform: translate(-50%, -50%) scale(1);\n opacity: 1;\n content: ' ';\n}\n.ant-select-tree-checkbox-indeterminate.ant-select-tree-checkbox-disabled .ant-select-tree-checkbox-inner::after {\n background-color: rgba(0, 0, 0, 0.25);\n border-color: rgba(0, 0, 0, 0.25);\n}\n.ant-tree-select-dropdown {\n padding: 8px 4px;\n}\n.ant-tree-select-dropdown-rtl {\n direction: rtl;\n}\n.ant-tree-select-dropdown .ant-select-tree {\n border-radius: 0;\n}\n.ant-tree-select-dropdown .ant-select-tree-list-holder-inner {\n align-items: stretch;\n}\n.ant-tree-select-dropdown .ant-select-tree-list-holder-inner .ant-select-tree-treenode .ant-select-tree-node-content-wrapper {\n flex: auto;\n}\n.ant-select-tree {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n background: #fff;\n border-radius: 2px;\n transition: background-color 0.3s;\n}\n.ant-select-tree-focused:not(:hover):not(.ant-select-tree-active-focused) {\n background: #e6f7ff;\n}\n.ant-select-tree-list-holder-inner {\n align-items: flex-start;\n}\n.ant-select-tree.ant-select-tree-block-node .ant-select-tree-list-holder-inner {\n align-items: stretch;\n}\n.ant-select-tree.ant-select-tree-block-node .ant-select-tree-list-holder-inner .ant-select-tree-node-content-wrapper {\n flex: auto;\n}\n.ant-select-tree.ant-select-tree-block-node .ant-select-tree-list-holder-inner .ant-select-tree-treenode.dragging {\n position: relative;\n}\n.ant-select-tree.ant-select-tree-block-node .ant-select-tree-list-holder-inner .ant-select-tree-treenode.dragging::after {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 4px;\n left: 0;\n border: 1px solid #1890ff;\n opacity: 0;\n animation: ant-tree-node-fx-do-not-use 0.3s;\n animation-play-state: running;\n animation-fill-mode: forwards;\n content: '';\n pointer-events: none;\n}\n.ant-select-tree .ant-select-tree-treenode {\n display: flex;\n align-items: flex-start;\n padding: 0 0 4px 0;\n outline: none;\n}\n.ant-select-tree .ant-select-tree-treenode-disabled .ant-select-tree-node-content-wrapper {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-select-tree .ant-select-tree-treenode-disabled .ant-select-tree-node-content-wrapper:hover {\n background: transparent;\n}\n.ant-select-tree .ant-select-tree-treenode-active .ant-select-tree-node-content-wrapper {\n background: #f5f5f5;\n}\n.ant-select-tree .ant-select-tree-treenode:not(.ant-select-tree .ant-select-tree-treenode-disabled).filter-node .ant-select-tree-title {\n color: inherit;\n font-weight: 500;\n}\n.ant-select-tree .ant-select-tree-treenode-draggable .ant-select-tree-draggable-icon {\n width: 24px;\n line-height: 24px;\n text-align: center;\n visibility: visible;\n opacity: 0.2;\n transition: opacity 0.3s;\n}\n.ant-select-tree-treenode:hover .ant-select-tree .ant-select-tree-treenode-draggable .ant-select-tree-draggable-icon {\n opacity: 0.45;\n}\n.ant-select-tree .ant-select-tree-treenode-draggable.ant-select-tree-treenode-disabled .ant-select-tree-draggable-icon {\n visibility: hidden;\n}\n.ant-select-tree-indent {\n align-self: stretch;\n white-space: nowrap;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-select-tree-indent-unit {\n display: inline-block;\n width: 24px;\n}\n.ant-select-tree-draggable-icon {\n visibility: hidden;\n}\n.ant-select-tree-switcher {\n position: relative;\n flex: none;\n align-self: stretch;\n width: 24px;\n margin: 0;\n line-height: 24px;\n text-align: center;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-select-tree-switcher .ant-tree-switcher-icon,\n.ant-select-tree-switcher .ant-select-tree-switcher-icon {\n display: inline-block;\n font-size: 10px;\n vertical-align: baseline;\n}\n.ant-select-tree-switcher .ant-tree-switcher-icon svg,\n.ant-select-tree-switcher .ant-select-tree-switcher-icon svg {\n transition: transform 0.3s;\n}\n.ant-select-tree-switcher-noop {\n cursor: default;\n}\n.ant-select-tree-switcher_close .ant-select-tree-switcher-icon svg {\n transform: rotate(-90deg);\n}\n.ant-select-tree-switcher-loading-icon {\n color: #1890ff;\n}\n.ant-select-tree-switcher-leaf-line {\n position: relative;\n z-index: 1;\n display: inline-block;\n width: 100%;\n height: 100%;\n}\n.ant-select-tree-switcher-leaf-line::before {\n position: absolute;\n top: 0;\n right: 12px;\n bottom: -4px;\n margin-left: -1px;\n border-right: 1px solid #d9d9d9;\n content: ' ';\n}\n.ant-select-tree-switcher-leaf-line::after {\n position: absolute;\n width: 10px;\n height: 14px;\n border-bottom: 1px solid #d9d9d9;\n content: ' ';\n}\n.ant-select-tree-checkbox {\n top: initial;\n margin: 4px 8px 0 0;\n}\n.ant-select-tree .ant-select-tree-node-content-wrapper {\n position: relative;\n z-index: auto;\n min-height: 24px;\n margin: 0;\n padding: 0 4px;\n color: inherit;\n line-height: 24px;\n background: transparent;\n border-radius: 2px;\n cursor: pointer;\n transition: all 0.3s, border 0s, line-height 0s, box-shadow 0s;\n}\n.ant-select-tree .ant-select-tree-node-content-wrapper:hover {\n background-color: #f5f5f5;\n}\n.ant-select-tree .ant-select-tree-node-content-wrapper.ant-select-tree-node-selected {\n background-color: #bae7ff;\n}\n.ant-select-tree .ant-select-tree-node-content-wrapper .ant-select-tree-iconEle {\n display: inline-block;\n width: 24px;\n height: 24px;\n line-height: 24px;\n text-align: center;\n vertical-align: top;\n}\n.ant-select-tree .ant-select-tree-node-content-wrapper .ant-select-tree-iconEle:empty {\n display: none;\n}\n.ant-select-tree-unselectable .ant-select-tree-node-content-wrapper:hover {\n background-color: transparent;\n}\n.ant-select-tree-node-content-wrapper {\n line-height: 24px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.ant-select-tree-node-content-wrapper .ant-tree-drop-indicator {\n position: absolute;\n z-index: 1;\n height: 2px;\n background-color: #1890ff;\n border-radius: 1px;\n pointer-events: none;\n}\n.ant-select-tree-node-content-wrapper .ant-tree-drop-indicator::after {\n position: absolute;\n top: -3px;\n left: -6px;\n width: 8px;\n height: 8px;\n background-color: transparent;\n border: 2px solid #1890ff;\n border-radius: 50%;\n content: '';\n}\n.ant-select-tree .ant-select-tree-treenode.drop-container > [draggable] {\n box-shadow: 0 0 0 2px #1890ff;\n}\n.ant-select-tree-show-line .ant-select-tree-indent-unit {\n position: relative;\n height: 100%;\n}\n.ant-select-tree-show-line .ant-select-tree-indent-unit::before {\n position: absolute;\n top: 0;\n right: 12px;\n bottom: -4px;\n border-right: 1px solid #d9d9d9;\n content: '';\n}\n.ant-select-tree-show-line .ant-select-tree-indent-unit-end::before {\n display: none;\n}\n.ant-select-tree-show-line .ant-select-tree-switcher {\n background: #fff;\n}\n.ant-select-tree-show-line .ant-select-tree-switcher-line-icon {\n vertical-align: -0.15em;\n}\n.ant-select-tree .ant-select-tree-treenode-leaf-last .ant-select-tree-switcher-leaf-line::before {\n top: auto !important;\n bottom: auto !important;\n height: 14px !important;\n}\n.ant-tree-select-dropdown-rtl .ant-select-tree .ant-select-tree-switcher_close .ant-select-tree-switcher-icon svg {\n transform: rotate(90deg);\n}\n.ant-tree-select-dropdown-rtl .ant-select-tree .ant-select-tree-switcher-loading-icon {\n transform: scaleY(-1);\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-typography {\n color: rgba(0, 0, 0, 0.85);\n word-break: break-word;\n}\n.ant-typography.ant-typography-secondary {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-typography.ant-typography-success {\n color: #52c41a;\n}\n.ant-typography.ant-typography-warning {\n color: #faad14;\n}\n.ant-typography.ant-typography-danger {\n color: #ff4d4f;\n}\na.ant-typography.ant-typography-danger:active,\na.ant-typography.ant-typography-danger:focus {\n color: #d9363e;\n}\na.ant-typography.ant-typography-danger:hover {\n color: #ff7875;\n}\n.ant-typography.ant-typography-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\ndiv.ant-typography,\n.ant-typography p {\n margin-bottom: 1em;\n}\nh1.ant-typography,\ndiv.ant-typography-h1,\ndiv.ant-typography-h1 > textarea,\n.ant-typography h1 {\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 38px;\n line-height: 1.23;\n}\nh2.ant-typography,\ndiv.ant-typography-h2,\ndiv.ant-typography-h2 > textarea,\n.ant-typography h2 {\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 30px;\n line-height: 1.35;\n}\nh3.ant-typography,\ndiv.ant-typography-h3,\ndiv.ant-typography-h3 > textarea,\n.ant-typography h3 {\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 24px;\n line-height: 1.35;\n}\nh4.ant-typography,\ndiv.ant-typography-h4,\ndiv.ant-typography-h4 > textarea,\n.ant-typography h4 {\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 20px;\n line-height: 1.4;\n}\nh5.ant-typography,\ndiv.ant-typography-h5,\ndiv.ant-typography-h5 > textarea,\n.ant-typography h5 {\n margin-bottom: 0.5em;\n color: rgba(0, 0, 0, 0.85);\n font-weight: 600;\n font-size: 16px;\n line-height: 1.5;\n}\n.ant-typography + h1.ant-typography,\n.ant-typography + h2.ant-typography,\n.ant-typography + h3.ant-typography,\n.ant-typography + h4.ant-typography,\n.ant-typography + h5.ant-typography {\n margin-top: 1.2em;\n}\n.ant-typography div + h1,\n.ant-typography ul + h1,\n.ant-typography li + h1,\n.ant-typography p + h1,\n.ant-typography h1 + h1,\n.ant-typography h2 + h1,\n.ant-typography h3 + h1,\n.ant-typography h4 + h1,\n.ant-typography h5 + h1,\n.ant-typography div + h2,\n.ant-typography ul + h2,\n.ant-typography li + h2,\n.ant-typography p + h2,\n.ant-typography h1 + h2,\n.ant-typography h2 + h2,\n.ant-typography h3 + h2,\n.ant-typography h4 + h2,\n.ant-typography h5 + h2,\n.ant-typography div + h3,\n.ant-typography ul + h3,\n.ant-typography li + h3,\n.ant-typography p + h3,\n.ant-typography h1 + h3,\n.ant-typography h2 + h3,\n.ant-typography h3 + h3,\n.ant-typography h4 + h3,\n.ant-typography h5 + h3,\n.ant-typography div + h4,\n.ant-typography ul + h4,\n.ant-typography li + h4,\n.ant-typography p + h4,\n.ant-typography h1 + h4,\n.ant-typography h2 + h4,\n.ant-typography h3 + h4,\n.ant-typography h4 + h4,\n.ant-typography h5 + h4,\n.ant-typography div + h5,\n.ant-typography ul + h5,\n.ant-typography li + h5,\n.ant-typography p + h5,\n.ant-typography h1 + h5,\n.ant-typography h2 + h5,\n.ant-typography h3 + h5,\n.ant-typography h4 + h5,\n.ant-typography h5 + h5 {\n margin-top: 1.2em;\n}\na.ant-typography-ellipsis,\nspan.ant-typography-ellipsis {\n display: inline-block;\n max-width: 100%;\n}\na.ant-typography,\n.ant-typography a {\n color: #1890ff;\n outline: none;\n cursor: pointer;\n transition: color 0.3s;\n text-decoration: none;\n}\na.ant-typography:focus-visible,\n.ant-typography a:focus-visible,\na.ant-typography:hover,\n.ant-typography a:hover {\n color: #40a9ff;\n}\na.ant-typography:active,\n.ant-typography a:active {\n color: #096dd9;\n}\na.ant-typography:active,\n.ant-typography a:active,\na.ant-typography:hover,\n.ant-typography a:hover {\n text-decoration: none;\n}\na.ant-typography[disabled],\n.ant-typography a[disabled],\na.ant-typography.ant-typography-disabled,\n.ant-typography a.ant-typography-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\na.ant-typography[disabled]:active,\n.ant-typography a[disabled]:active,\na.ant-typography.ant-typography-disabled:active,\n.ant-typography a.ant-typography-disabled:active,\na.ant-typography[disabled]:hover,\n.ant-typography a[disabled]:hover,\na.ant-typography.ant-typography-disabled:hover,\n.ant-typography a.ant-typography-disabled:hover {\n color: rgba(0, 0, 0, 0.25);\n}\na.ant-typography[disabled]:active,\n.ant-typography a[disabled]:active,\na.ant-typography.ant-typography-disabled:active,\n.ant-typography a.ant-typography-disabled:active {\n pointer-events: none;\n}\n.ant-typography code {\n margin: 0 0.2em;\n padding: 0.2em 0.4em 0.1em;\n font-size: 85%;\n background: rgba(150, 150, 150, 0.1);\n border: 1px solid rgba(100, 100, 100, 0.2);\n border-radius: 3px;\n}\n.ant-typography kbd {\n margin: 0 0.2em;\n padding: 0.15em 0.4em 0.1em;\n font-size: 90%;\n background: rgba(150, 150, 150, 0.06);\n border: 1px solid rgba(100, 100, 100, 0.2);\n border-bottom-width: 2px;\n border-radius: 3px;\n}\n.ant-typography mark {\n padding: 0;\n background-color: #ffe58f;\n}\n.ant-typography u,\n.ant-typography ins {\n text-decoration: underline;\n -webkit-text-decoration-skip: ink;\n text-decoration-skip-ink: auto;\n}\n.ant-typography s,\n.ant-typography del {\n text-decoration: line-through;\n}\n.ant-typography strong {\n font-weight: 600;\n}\n.ant-typography-expand,\n.ant-typography-edit,\n.ant-typography-copy {\n color: #1890ff;\n outline: none;\n cursor: pointer;\n transition: color 0.3s;\n margin-left: 4px;\n}\n.ant-typography-expand:focus-visible,\n.ant-typography-edit:focus-visible,\n.ant-typography-copy:focus-visible,\n.ant-typography-expand:hover,\n.ant-typography-edit:hover,\n.ant-typography-copy:hover {\n color: #40a9ff;\n}\n.ant-typography-expand:active,\n.ant-typography-edit:active,\n.ant-typography-copy:active {\n color: #096dd9;\n}\n.ant-typography-copy-success,\n.ant-typography-copy-success:hover,\n.ant-typography-copy-success:focus {\n color: #52c41a;\n}\n.ant-typography-edit-content {\n position: relative;\n}\ndiv.ant-typography-edit-content {\n left: -12px;\n margin-top: -5px;\n margin-bottom: calc(1em - 4px - 1px);\n}\n.ant-typography-edit-content-confirm {\n position: absolute;\n right: 10px;\n bottom: 8px;\n color: rgba(0, 0, 0, 0.45);\n font-weight: normal;\n font-size: 14px;\n font-style: normal;\n pointer-events: none;\n}\n.ant-typography-edit-content textarea {\n height: 1em;\n margin: 0 !important;\n /* stylelint-disable-next-line property-no-vendor-prefix */\n -moz-transition: none;\n}\n.ant-typography ul,\n.ant-typography ol {\n margin: 0 0 1em;\n padding: 0;\n}\n.ant-typography ul li,\n.ant-typography ol li {\n margin: 0 0 0 20px;\n padding: 0 0 0 4px;\n}\n.ant-typography ul {\n list-style-type: circle;\n}\n.ant-typography ul ul {\n list-style-type: disc;\n}\n.ant-typography ol {\n list-style-type: decimal;\n}\n.ant-typography pre,\n.ant-typography blockquote {\n margin: 1em 0;\n}\n.ant-typography pre {\n padding: 0.4em 0.6em;\n white-space: pre-wrap;\n word-wrap: break-word;\n background: rgba(150, 150, 150, 0.1);\n border: 1px solid rgba(100, 100, 100, 0.2);\n border-radius: 3px;\n}\n.ant-typography pre code {\n display: inline;\n margin: 0;\n padding: 0;\n font-size: inherit;\n font-family: inherit;\n background: transparent;\n border: 0;\n}\n.ant-typography blockquote {\n padding: 0 0 0 0.6em;\n border-left: 4px solid rgba(100, 100, 100, 0.2);\n opacity: 0.85;\n}\n.ant-typography-single-line {\n white-space: nowrap;\n}\n.ant-typography-ellipsis-single-line {\n overflow: hidden;\n text-overflow: ellipsis;\n}\na.ant-typography-ellipsis-single-line,\nspan.ant-typography-ellipsis-single-line {\n vertical-align: bottom;\n}\n.ant-typography-ellipsis-multiple-line {\n /* stylelint-disable-next-line value-no-vendor-prefix */\n display: -webkit-box;\n overflow: hidden;\n -webkit-line-clamp: 3;\n /*! autoprefixer: ignore next */\n -webkit-box-orient: vertical;\n}\n.ant-typography-rtl {\n direction: rtl;\n}\n.ant-typography-rtl .ant-typography-expand,\n.ant-typography-rtl .ant-typography-edit,\n.ant-typography-rtl .ant-typography-copy {\n margin-right: 4px;\n margin-left: 0;\n}\n.ant-typography-rtl .ant-typography-expand {\n float: left;\n}\ndiv.ant-typography-edit-content.ant-typography-rtl {\n right: -12px;\n left: auto;\n}\n.ant-typography-rtl .ant-typography-edit-content-confirm {\n right: auto;\n left: 10px;\n}\n.ant-typography-rtl.ant-typography ul li,\n.ant-typography-rtl.ant-typography ol li {\n margin: 0 20px 0 0;\n padding: 0 4px 0 0;\n}\n\n/* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */\n/* stylelint-disable no-duplicate-selectors */\n/* stylelint-disable */\n/* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */\n.ant-upload {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n line-height: 1.5715;\n list-style: none;\n font-feature-settings: 'tnum';\n outline: 0;\n}\n.ant-upload p {\n margin: 0;\n}\n.ant-upload-btn {\n display: block;\n width: 100%;\n outline: none;\n}\n.ant-upload input[type='file'] {\n cursor: pointer;\n}\n.ant-upload.ant-upload-select {\n display: inline-block;\n}\n.ant-upload.ant-upload-disabled {\n color: rgba(0, 0, 0, 0.25);\n cursor: not-allowed;\n}\n.ant-upload.ant-upload-select-picture-card {\n width: 104px;\n height: 104px;\n margin-right: 8px;\n margin-bottom: 8px;\n text-align: center;\n vertical-align: top;\n background-color: #fafafa;\n border: 1px dashed #d9d9d9;\n border-radius: 2px;\n cursor: pointer;\n transition: border-color 0.3s;\n}\n.ant-upload.ant-upload-select-picture-card > .ant-upload {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n text-align: center;\n}\n.ant-upload.ant-upload-select-picture-card:hover {\n border-color: #1890ff;\n}\n.ant-upload-disabled.ant-upload.ant-upload-select-picture-card:hover {\n border-color: #d9d9d9;\n}\n.ant-upload.ant-upload-drag {\n position: relative;\n width: 100%;\n height: 100%;\n text-align: center;\n background: #fafafa;\n border: 1px dashed #d9d9d9;\n border-radius: 2px;\n cursor: pointer;\n transition: border-color 0.3s;\n}\n.ant-upload.ant-upload-drag .ant-upload {\n padding: 16px 0;\n}\n.ant-upload.ant-upload-drag.ant-upload-drag-hover:not(.ant-upload-disabled) {\n border-color: #096dd9;\n}\n.ant-upload.ant-upload-drag.ant-upload-disabled {\n cursor: not-allowed;\n}\n.ant-upload.ant-upload-drag .ant-upload-btn {\n display: table;\n height: 100%;\n}\n.ant-upload.ant-upload-drag .ant-upload-drag-container {\n display: table-cell;\n vertical-align: middle;\n}\n.ant-upload.ant-upload-drag:not(.ant-upload-disabled):hover {\n border-color: #40a9ff;\n}\n.ant-upload.ant-upload-drag p.ant-upload-drag-icon {\n margin-bottom: 20px;\n}\n.ant-upload.ant-upload-drag p.ant-upload-drag-icon .anticon {\n color: #40a9ff;\n font-size: 48px;\n}\n.ant-upload.ant-upload-drag p.ant-upload-text {\n margin: 0 0 4px;\n color: rgba(0, 0, 0, 0.85);\n font-size: 16px;\n}\n.ant-upload.ant-upload-drag p.ant-upload-hint {\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-upload.ant-upload-drag .anticon-plus {\n color: rgba(0, 0, 0, 0.25);\n font-size: 30px;\n transition: all 0.3s;\n}\n.ant-upload.ant-upload-drag .anticon-plus:hover {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-upload.ant-upload-drag:hover .anticon-plus {\n color: rgba(0, 0, 0, 0.45);\n}\n.ant-upload-picture-card-wrapper {\n display: inline-block;\n width: 100%;\n}\n.ant-upload-picture-card-wrapper::before {\n display: table;\n content: '';\n}\n.ant-upload-picture-card-wrapper::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-upload-list {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.85);\n font-size: 14px;\n font-variant: tabular-nums;\n list-style: none;\n font-feature-settings: 'tnum';\n line-height: 1.5715;\n}\n.ant-upload-list::before {\n display: table;\n content: '';\n}\n.ant-upload-list::after {\n display: table;\n clear: both;\n content: '';\n}\n.ant-upload-list-item {\n position: relative;\n height: 22.001px;\n margin-top: 8px;\n font-size: 14px;\n}\n.ant-upload-list-item-name {\n display: inline-block;\n width: 100%;\n padding-left: 22px;\n overflow: hidden;\n line-height: 1.5715;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n.ant-upload-list-item-card-actions {\n position: absolute;\n right: 0;\n}\n.ant-upload-list-item-card-actions-btn {\n opacity: 0;\n}\n.ant-upload-list-item-card-actions-btn.ant-btn-sm {\n height: 22.001px;\n line-height: 1;\n vertical-align: top;\n}\n.ant-upload-list-item-card-actions.picture {\n top: 22px;\n line-height: 0;\n}\n.ant-upload-list-item-card-actions-btn:focus,\n.ant-upload-list-item-card-actions.picture .ant-upload-list-item-card-actions-btn {\n opacity: 1;\n}\n.ant-upload-list-item-card-actions .anticon {\n color: rgba(0, 0, 0, 0.45);\n transition: all 0.3s;\n}\n.ant-upload-list-item-card-actions:hover .anticon {\n color: rgba(0, 0, 0, 0.85);\n}\n.ant-upload-list-item-info {\n height: 100%;\n transition: background-color 0.3s;\n}\n.ant-upload-list-item-info > span {\n display: block;\n width: 100%;\n height: 100%;\n}\n.ant-upload-list-item-info .anticon-loading .anticon,\n.ant-upload-list-item-info .ant-upload-text-icon .anticon {\n position: absolute;\n top: 5px;\n color: rgba(0, 0, 0, 0.45);\n font-size: 14px;\n}\n.ant-upload-list-item:hover .ant-upload-list-item-info {\n background-color: #f5f5f5;\n}\n.ant-upload-list-item:hover .ant-upload-list-item-card-actions-btn {\n opacity: 1;\n}\n.ant-upload-list-item-error,\n.ant-upload-list-item-error .ant-upload-text-icon > .anticon,\n.ant-upload-list-item-error .ant-upload-list-item-name {\n color: #ff4d4f;\n}\n.ant-upload-list-item-error .ant-upload-list-item-card-actions .anticon {\n color: #ff4d4f;\n}\n.ant-upload-list-item-error .ant-upload-list-item-card-actions-btn {\n opacity: 1;\n}\n.ant-upload-list-item-progress {\n position: absolute;\n bottom: -12px;\n width: 100%;\n padding-left: 26px;\n font-size: 14px;\n line-height: 0;\n}\n.ant-upload-list-picture .ant-upload-list-item,\n.ant-upload-list-picture-card .ant-upload-list-item {\n position: relative;\n height: 66px;\n padding: 8px;\n border: 1px solid #d9d9d9;\n border-radius: 2px;\n}\n.ant-upload-list-picture .ant-upload-list-item:hover,\n.ant-upload-list-picture-card .ant-upload-list-item:hover {\n background: transparent;\n}\n.ant-upload-list-picture .ant-upload-list-item-error,\n.ant-upload-list-picture-card .ant-upload-list-item-error {\n border-color: #ff4d4f;\n}\n.ant-upload-list-picture .ant-upload-list-item-info,\n.ant-upload-list-picture-card .ant-upload-list-item-info {\n padding: 0;\n}\n.ant-upload-list-picture .ant-upload-list-item:hover .ant-upload-list-item-info,\n.ant-upload-list-picture-card .ant-upload-list-item:hover .ant-upload-list-item-info {\n background: transparent;\n}\n.ant-upload-list-picture .ant-upload-list-item-uploading,\n.ant-upload-list-picture-card .ant-upload-list-item-uploading {\n border-style: dashed;\n}\n.ant-upload-list-picture .ant-upload-list-item-thumbnail,\n.ant-upload-list-picture-card .ant-upload-list-item-thumbnail {\n width: 48px;\n height: 48px;\n line-height: 60px;\n text-align: center;\n opacity: 0.8;\n}\n.ant-upload-list-picture .ant-upload-list-item-thumbnail .anticon,\n.ant-upload-list-picture-card .ant-upload-list-item-thumbnail .anticon {\n font-size: 26px;\n}\n.ant-upload-list-picture .ant-upload-list-item-error .ant-upload-list-item-thumbnail .anticon svg path[fill='#e6f7ff'],\n.ant-upload-list-picture-card .ant-upload-list-item-error .ant-upload-list-item-thumbnail .anticon svg path[fill='#e6f7ff'] {\n fill: #fff2f0;\n}\n.ant-upload-list-picture .ant-upload-list-item-error .ant-upload-list-item-thumbnail .anticon svg path[fill='#1890ff'],\n.ant-upload-list-picture-card .ant-upload-list-item-error .ant-upload-list-item-thumbnail .anticon svg path[fill='#1890ff'] {\n fill: #ff4d4f;\n}\n.ant-upload-list-picture .ant-upload-list-item-icon,\n.ant-upload-list-picture-card .ant-upload-list-item-icon {\n position: absolute;\n top: 50%;\n left: 50%;\n font-size: 26px;\n transform: translate(-50%, -50%);\n}\n.ant-upload-list-picture .ant-upload-list-item-icon .anticon,\n.ant-upload-list-picture-card .ant-upload-list-item-icon .anticon {\n font-size: 26px;\n}\n.ant-upload-list-picture .ant-upload-list-item-image,\n.ant-upload-list-picture-card .ant-upload-list-item-image {\n max-width: 100%;\n}\n.ant-upload-list-picture .ant-upload-list-item-thumbnail img,\n.ant-upload-list-picture-card .ant-upload-list-item-thumbnail img {\n display: block;\n width: 48px;\n height: 48px;\n overflow: hidden;\n}\n.ant-upload-list-picture .ant-upload-list-item-name,\n.ant-upload-list-picture-card .ant-upload-list-item-name {\n display: inline-block;\n box-sizing: border-box;\n max-width: 100%;\n margin: 0 0 0 8px;\n padding-right: 8px;\n padding-left: 48px;\n overflow: hidden;\n line-height: 44px;\n white-space: nowrap;\n text-overflow: ellipsis;\n transition: all 0.3s;\n}\n.ant-upload-list-picture .ant-upload-list-item-uploading .ant-upload-list-item-name,\n.ant-upload-list-picture-card .ant-upload-list-item-uploading .ant-upload-list-item-name {\n margin-bottom: 12px;\n}\n.ant-upload-list-picture .ant-upload-list-item-progress,\n.ant-upload-list-picture-card .ant-upload-list-item-progress {\n bottom: 14px;\n width: calc(100% - 24px);\n margin-top: 0;\n padding-left: 56px;\n}\n.ant-upload-list-picture-card-container {\n display: inline-block;\n width: 104px;\n height: 104px;\n margin: 0 8px 8px 0;\n vertical-align: top;\n}\n.ant-upload-list-picture-card .ant-upload-list-item {\n height: 100%;\n margin: 0;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-info {\n position: relative;\n height: 100%;\n overflow: hidden;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-info::before {\n position: absolute;\n z-index: 1;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: all 0.3s;\n content: ' ';\n}\n.ant-upload-list-picture-card .ant-upload-list-item:hover .ant-upload-list-item-info::before {\n opacity: 1;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-actions {\n position: absolute;\n top: 50%;\n left: 50%;\n z-index: 10;\n white-space: nowrap;\n transform: translate(-50%, -50%);\n opacity: 0;\n transition: all 0.3s;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-eye,\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-download,\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-delete {\n z-index: 10;\n width: 16px;\n margin: 0 4px;\n color: rgba(255, 255, 255, 0.85);\n font-size: 16px;\n cursor: pointer;\n transition: all 0.3s;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-eye:hover,\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-download:hover,\n.ant-upload-list-picture-card .ant-upload-list-item-actions .anticon-delete:hover {\n color: #fff;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-info:hover + .ant-upload-list-item-actions,\n.ant-upload-list-picture-card .ant-upload-list-item-actions:hover {\n opacity: 1;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-thumbnail,\n.ant-upload-list-picture-card .ant-upload-list-item-thumbnail img {\n position: static;\n display: block;\n width: 100%;\n height: 100%;\n -o-object-fit: contain;\n object-fit: contain;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-name {\n display: none;\n margin: 8px 0 0;\n padding: 0;\n line-height: 1.5715;\n text-align: center;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-file + .ant-upload-list-item-name {\n position: absolute;\n bottom: 10px;\n display: block;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-uploading.ant-upload-list-item {\n background-color: #fafafa;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-uploading .ant-upload-list-item-info {\n height: auto;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-uploading .ant-upload-list-item-info::before,\n.ant-upload-list-picture-card .ant-upload-list-item-uploading .ant-upload-list-item-info .anticon-eye,\n.ant-upload-list-picture-card .ant-upload-list-item-uploading .ant-upload-list-item-info .anticon-delete {\n display: none;\n}\n.ant-upload-list-picture-card .ant-upload-list-item-progress {\n bottom: 32px;\n width: calc(100% - 14px);\n padding-left: 0;\n}\n.ant-upload-list-text-container,\n.ant-upload-list-picture-container {\n transition: opacity 0.3s, height 0.3s;\n}\n.ant-upload-list-text-container::before,\n.ant-upload-list-picture-container::before {\n display: table;\n width: 0;\n height: 0;\n content: '';\n}\n.ant-upload-list-text-container .ant-upload-span,\n.ant-upload-list-picture-container .ant-upload-span {\n display: block;\n flex: auto;\n}\n.ant-upload-list-text .ant-upload-span,\n.ant-upload-list-picture .ant-upload-span {\n display: flex;\n align-items: center;\n}\n.ant-upload-list-text .ant-upload-span > *,\n.ant-upload-list-picture .ant-upload-span > * {\n flex: none;\n}\n.ant-upload-list-text .ant-upload-list-item-name,\n.ant-upload-list-picture .ant-upload-list-item-name {\n flex: auto;\n margin: 0;\n padding: 0 8px;\n}\n.ant-upload-list-text .ant-upload-list-item-card-actions,\n.ant-upload-list-picture .ant-upload-list-item-card-actions {\n position: static;\n}\n.ant-upload-list-text .ant-upload-text-icon .anticon {\n position: static;\n}\n.ant-upload-list .ant-upload-animate-inline-appear,\n.ant-upload-list .ant-upload-animate-inline-enter,\n.ant-upload-list .ant-upload-animate-inline-leave {\n animation-duration: 0.3s;\n animation-timing-function: cubic-bezier(0.78, 0.14, 0.15, 0.86);\n animation-fill-mode: forwards;\n}\n.ant-upload-list .ant-upload-animate-inline-appear,\n.ant-upload-list .ant-upload-animate-inline-enter {\n animation-name: uploadAnimateInlineIn;\n}\n.ant-upload-list .ant-upload-animate-inline-leave {\n animation-name: uploadAnimateInlineOut;\n}\n@keyframes uploadAnimateInlineIn {\n from {\n width: 0;\n height: 0;\n margin: 0;\n padding: 0;\n opacity: 0;\n }\n}\n@keyframes uploadAnimateInlineOut {\n to {\n width: 0;\n height: 0;\n margin: 0;\n padding: 0;\n opacity: 0;\n }\n}\n.ant-upload-rtl {\n direction: rtl;\n}\n.ant-upload-rtl.ant-upload.ant-upload-select-picture-card {\n margin-right: auto;\n margin-left: 8px;\n}\n.ant-upload-list-rtl {\n direction: rtl;\n}\n.ant-upload-list-rtl .ant-upload-list-item-list-type-text:hover .ant-upload-list-item-name-icon-count-1 {\n padding-right: 22px;\n padding-left: 14px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-list-type-text:hover .ant-upload-list-item-name-icon-count-2 {\n padding-right: 22px;\n padding-left: 28px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-name {\n padding-right: 22px;\n padding-left: 0;\n}\n.ant-upload-list-rtl .ant-upload-list-item-name-icon-count-1 {\n padding-left: 14px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-card-actions {\n right: auto;\n left: 0;\n}\n.ant-upload-list-rtl .ant-upload-list-item-card-actions .anticon {\n padding-right: 0;\n padding-left: 5px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-info {\n padding: 0 4px 0 12px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-error .ant-upload-list-item-card-actions .anticon {\n padding-right: 0;\n padding-left: 5px;\n}\n.ant-upload-list-rtl .ant-upload-list-item-progress {\n padding-right: 26px;\n padding-left: 0;\n}\n.ant-upload-list-picture .ant-upload-list-item-info,\n.ant-upload-list-picture-card .ant-upload-list-item-info {\n padding: 0;\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-thumbnail,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-thumbnail {\n right: 8px;\n left: auto;\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-icon,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-icon {\n right: 50%;\n left: auto;\n transform: translate(50%, -50%);\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-name,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-name {\n margin: 0 8px 0 0;\n padding-right: 48px;\n padding-left: 8px;\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-name-icon-count-1,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-name-icon-count-1 {\n padding-right: 48px;\n padding-left: 18px;\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-name-icon-count-2,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-name-icon-count-2 {\n padding-right: 48px;\n padding-left: 36px;\n}\n.ant-upload-list-rtl.ant-upload-list-picture .ant-upload-list-item-progress,\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-progress {\n padding-right: 0;\n padding-left: 0;\n}\n.ant-upload-list-rtl .ant-upload-list-picture-card-container {\n margin: 0 0 8px 8px;\n}\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-actions {\n right: 50%;\n left: auto;\n transform: translate(50%, -50%);\n}\n.ant-upload-list-rtl.ant-upload-list-picture-card .ant-upload-list-item-file + .ant-upload-list-item-name {\n margin: 8px 0 0;\n padding: 0;\n}\n\n\n"; + + const styleEl = document.createElement("style"); + const codeEl = document.createTextNode(code); + styleEl.type = 'text/css'; + styleEl.appendChild(codeEl); + document.head.appendChild(styleEl); +} \ No newline at end of file diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/axios.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/axios.js new file mode 100644 index 0000000000000000000000000000000000000000..7a287650df79645adf864671841b957c5c016dde --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/axios.js @@ -0,0 +1,2 @@ +import{p as Y}from"./common/process-2545f00a.js";function G(e,t){return function(){return e.apply(t,arguments)}}const{toString:Z}=Object.prototype,{getPrototypeOf:H}=Object,z=(e=>t=>{const n=Z.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),O=e=>(e=e.toLowerCase(),t=>z(t)===e),U=e=>t=>typeof t===e,{isArray:F}=Array,q=U("undefined");function Fe(e){return e!==null&&!q(e)&&e.constructor!==null&&!q(e.constructor)&&P(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ee=O("ArrayBuffer");function De(e){let t;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ee(e.buffer),t}const _e=U("string"),P=U("function"),te=U("number"),ne=e=>e!==null&&typeof e=="object",Be=e=>e===!0||e===!1,j=e=>{if(z(e)!=="object")return!1;const t=H(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ge=O("Date"),Le=O("File"),Ue=O("Blob"),je=O("FileList"),ke=e=>ne(e)&&P(e.pipe),Me=e=>{const t="[object FormData]";return e&&(typeof FormData=="function"&&e instanceof FormData||Z.call(e)===t||P(e.toString)&&e.toString()===t)},Ie=O("URLSearchParams"),He=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function k(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e=="undefined")return;let r,o;if(typeof e!="object"&&(e=[e]),F(e))for(r=0,o=e.length;r{j(e[r])&&j(n)?e[r]=J(e[r],n):j(n)?e[r]=J({},n):F(n)?e[r]=n.slice():e[r]=n};for(let n=0,r=arguments.length;n(k(t,(o,i)=>{n&&P(o)?e[i]=G(o,n):e[i]=o},{allOwnKeys:r}),e),qe=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Je=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Ve=(e,t,n,r)=>{let o,i,s;const c={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!c[s]&&(t[s]=e[s],c[s]=!0);e=n!==!1&&H(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},$e=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},We=e=>{if(!e)return null;if(F(e))return e;let t=e.length;if(!te(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Ke=(e=>t=>e&&t instanceof e)(typeof Uint8Array!="undefined"&&H(Uint8Array)),ve=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},Xe=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},Qe=O("HTMLFormElement"),Ye=e=>e.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),re=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Ge=O("RegExp"),se=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};k(n,(o,i)=>{t(o,i,e)!==!1&&(r[i]=o)}),Object.defineProperties(e,r)},Ze=e=>{se(e,(t,n)=>{const r=e[n];if(!!P(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not read-only method '"+n+"'")})}})},et=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return F(e)?r(e):r(String(e).split(t)),n},tt=()=>{},nt=(e,t)=>(e=+e,Number.isFinite(e)?e:t);var a={isArray:F,isArrayBuffer:ee,isBuffer:Fe,isFormData:Me,isArrayBufferView:De,isString:_e,isNumber:te,isBoolean:Be,isObject:ne,isPlainObject:j,isUndefined:q,isDate:ge,isFile:Le,isBlob:Ue,isRegExp:Ge,isFunction:P,isStream:ke,isURLSearchParams:Ie,isTypedArray:Ke,isFileList:je,forEach:k,merge:J,extend:ze,trim:He,stripBOM:qe,inherits:Je,toFlatObject:Ve,kindOf:z,kindOfTest:O,endsWith:$e,toArray:We,forEachEntry:ve,matchAll:Xe,isHTMLForm:Qe,hasOwnProperty:re,hasOwnProp:re,reduceDescriptors:se,freezeMethods:Ze,toObjectSet:et,toCamelCase:Ye,noop:tt,toFiniteNumber:nt};function p(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}a.inherits(p,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const oe=p.prototype,ie={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ie[e]={value:e}}),Object.defineProperties(p,ie),Object.defineProperty(oe,"isAxiosError",{value:!0}),p.from=(e,t,n,r,o,i)=>{const s=Object.create(oe);return a.toFlatObject(e,s,function(f){return f!==Error.prototype},c=>c!=="isAxiosError"),p.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};var rt=typeof self=="object"?self.FormData:window.FormData;function V(e){return a.isPlainObject(e)||a.isArray(e)}function ae(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function ue(e,t,n){return e?e.concat(t).map(function(o,i){return o=ae(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function st(e){return a.isArray(e)&&!e.some(V)}const ot=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function it(e){return e&&a.isFunction(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator]}function M(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new(rt||FormData),n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,T){return!a.isUndefined(T[m])});const r=n.metaTokens,o=n.visitor||d,i=n.dots,s=n.indexes,f=(n.Blob||typeof Blob!="undefined"&&Blob)&&it(t);if(!a.isFunction(o))throw new TypeError("visitor must be a function");function u(l){if(l===null)return"";if(a.isDate(l))return l.toISOString();if(!f&&a.isBlob(l))throw new p("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(l)||a.isTypedArray(l)?f&&typeof Blob=="function"?new Blob([l]):Buffer.from(l):l}function d(l,m,T){let R=l;if(l&&!T&&typeof l=="object"){if(a.endsWith(m,"{}"))m=r?m:m.slice(0,-2),l=JSON.stringify(l);else if(a.isArray(l)&&st(l)||a.isFileList(l)||a.endsWith(m,"[]")&&(R=a.toArray(l)))return m=ae(m),R.forEach(function(L,Ce){!(a.isUndefined(L)||L===null)&&t.append(s===!0?ue([m],Ce,i):s===null?m:m+"[]",u(L))}),!1}return V(l)?!0:(t.append(ue(T,m,i),u(l)),!1)}const E=[],w=Object.assign(ot,{defaultVisitor:d,convertValue:u,isVisitable:V});function h(l,m){if(!a.isUndefined(l)){if(E.indexOf(l)!==-1)throw Error("Circular reference detected in "+m.join("."));E.push(l),a.forEach(l,function(R,N){(!(a.isUndefined(R)||R===null)&&o.call(t,R,a.isString(N)?N.trim():N,m,w))===!0&&h(R,m?m.concat(N):[N])}),E.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return h(e),t}function ce(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function $(e,t){this._pairs=[],e&&M(e,this,t)}const le=$.prototype;le.append=function(t,n){this._pairs.push([t,n])},le.toString=function(t){const n=t?function(r){return t.call(this,r,ce)}:ce;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function at(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function fe(e,t,n){if(!t)return e;const r=n&&n.encode||at,o=n&&n.serialize;let i;if(o?i=o(t,n):i=a.isURLSearchParams(t)?t.toString():new $(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class de{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}var he={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ut=typeof URLSearchParams!="undefined"?URLSearchParams:$,ct=FormData;const lt=(()=>{let e;return typeof navigator!="undefined"&&((e=navigator.product)==="ReactNative"||e==="NativeScript"||e==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"})();var S={isBrowser:!0,classes:{URLSearchParams:ut,FormData:ct,Blob},isStandardBrowserEnv:lt,protocols:["http","https","file","blob","url","data"]};function ft(e,t){return M(e,new S.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return i.defaultVisitor.apply(this,arguments)}},t))}function dt(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function ht(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&a.isArray(o)?o.length:s,f?(a.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!c):((!o[s]||!a.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&a.isArray(o[s])&&(o[s]=ht(o[s])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,o)=>{t(dt(r),o,n,0)}),n}return null}function pt(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new p("Request failed with status code "+n.status,[p.ERR_BAD_REQUEST,p.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}var mt=S.isStandardBrowserEnv?function(){return{write:function(n,r,o,i,s,c){const f=[];f.push(n+"="+encodeURIComponent(r)),a.isNumber(o)&&f.push("expires="+new Date(o).toGMTString()),a.isString(i)&&f.push("path="+i),a.isString(s)&&f.push("domain="+s),c===!0&&f.push("secure"),document.cookie=f.join("; ")},read:function(n){const r=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(n){this.write(n,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function Et(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function wt(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function me(e,t){return e&&!Et(t)?wt(e,t):t}var yt=S.isStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const c=a.isString(s)?o(s):s;return c.protocol===r.protocol&&c.host===r.host}}():function(){return function(){return!0}}();function D(e,t,n){p.call(this,e==null?"canceled":e,p.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(D,p,{__CANCEL__:!0});function bt(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}const Rt=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var Ot=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&Rt[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};const Ee=Symbol("internals"),we=Symbol("defaults");function _(e){return e&&String(e).trim().toLowerCase()}function I(e){return e===!1||e==null?e:a.isArray(e)?e.map(I):String(e)}function St(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}function ye(e,t,n,r){if(a.isFunction(r))return r.call(this,t,n);if(!!a.isString(t)){if(a.isString(r))return t.indexOf(r)!==-1;if(a.isRegExp(r))return r.test(t)}}function At(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Tt(e,t){const n=a.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}function B(e,t){t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}function b(e,t){e&&this.set(e),this[we]=t||null}Object.assign(b.prototype,{set:function(e,t,n){const r=this;function o(i,s,c){const f=_(s);if(!f)throw new Error("header name must be a non-empty string");const u=B(r,f);u&&c!==!0&&(r[u]===!1||c===!1)||(r[u||s]=I(i))}return a.isPlainObject(e)?a.forEach(e,(i,s)=>{o(i,s,t)}):o(t,e,n),this},get:function(e,t){if(e=_(e),!e)return;const n=B(this,e);if(n){const r=this[n];if(!t)return r;if(t===!0)return St(r);if(a.isFunction(t))return t.call(this,r,n);if(a.isRegExp(t))return t.exec(r);throw new TypeError("parser must be boolean|regexp|function")}},has:function(e,t){if(e=_(e),e){const n=B(this,e);return!!(n&&(!t||ye(this,this[n],n,t)))}return!1},delete:function(e,t){const n=this;let r=!1;function o(i){if(i=_(i),i){const s=B(n,i);s&&(!t||ye(n,n[s],s,t))&&(delete n[s],r=!0)}}return a.isArray(e)?e.forEach(o):o(e),r},clear:function(){return Object.keys(this).forEach(this.delete.bind(this))},normalize:function(e){const t=this,n={};return a.forEach(this,(r,o)=>{const i=B(n,o);if(i){t[i]=I(r),delete t[o];return}const s=e?At(o):String(o).trim();s!==o&&delete t[o],t[s]=I(r),n[s]=!0}),this},toJSON:function(e){const t=Object.create(null);return a.forEach(Object.assign({},this[we]||null,this),(n,r)=>{n==null||n===!1||(t[r]=e&&a.isArray(n)?n.join(", "):n)}),t}}),Object.assign(b,{from:function(e){return a.isString(e)?new this(Ot(e)):e instanceof this?e:new this(e)},accessor:function(e){const n=(this[Ee]=this[Ee]={accessors:{}}).accessors,r=this.prototype;function o(i){const s=_(i);n[s]||(Tt(r,i),n[s]=!0)}return a.isArray(e)?e.forEach(o):o(e),this}}),b.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),a.freezeMethods(b.prototype),a.freezeMethods(b);function xt(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(f){const u=Date.now(),d=r[i];s||(s=u),n[o]=f,r[o]=u;let E=i,w=0;for(;E!==o;)w+=n[E++],E=E%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),u-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,c=i-n,f=r(c),u=i<=s;n=i;const d={loaded:i,total:s,progress:s?i/s:void 0,bytes:c,rate:f||void 0,estimated:f&&s&&u?(s-i)/f:void 0};d[t?"download":"upload"]=!0,e(d)}}function Re(e){return new Promise(function(n,r){let o=e.data;const i=b.from(e.headers).normalize(),s=e.responseType;let c;function f(){e.cancelToken&&e.cancelToken.unsubscribe(c),e.signal&&e.signal.removeEventListener("abort",c)}a.isFormData(o)&&S.isStandardBrowserEnv&&i.setContentType(!1);let u=new XMLHttpRequest;if(e.auth){const h=e.auth.username||"",l=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(h+":"+l))}const d=me(e.baseURL,e.url);u.open(e.method.toUpperCase(),fe(d,e.params,e.paramsSerializer),!0),u.timeout=e.timeout;function E(){if(!u)return;const h=b.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),m={data:!s||s==="text"||s==="json"?u.responseText:u.response,status:u.status,statusText:u.statusText,headers:h,config:e,request:u};pt(function(R){n(R),f()},function(R){r(R),f()},m),u=null}if("onloadend"in u?u.onloadend=E:u.onreadystatechange=function(){!u||u.readyState!==4||u.status===0&&!(u.responseURL&&u.responseURL.indexOf("file:")===0)||setTimeout(E)},u.onabort=function(){!u||(r(new p("Request aborted",p.ECONNABORTED,e,u)),u=null)},u.onerror=function(){r(new p("Network Error",p.ERR_NETWORK,e,u)),u=null},u.ontimeout=function(){let l=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const m=e.transitional||he;e.timeoutErrorMessage&&(l=e.timeoutErrorMessage),r(new p(l,m.clarifyTimeoutError?p.ETIMEDOUT:p.ECONNABORTED,e,u)),u=null},S.isStandardBrowserEnv){const h=(e.withCredentials||yt(d))&&e.xsrfCookieName&&mt.read(e.xsrfCookieName);h&&i.set(e.xsrfHeaderName,h)}o===void 0&&i.setContentType(null),"setRequestHeader"in u&&a.forEach(i.toJSON(),function(l,m){u.setRequestHeader(m,l)}),a.isUndefined(e.withCredentials)||(u.withCredentials=!!e.withCredentials),s&&s!=="json"&&(u.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&u.addEventListener("progress",be(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&u.upload&&u.upload.addEventListener("progress",be(e.onUploadProgress)),(e.cancelToken||e.signal)&&(c=h=>{!u||(r(!h||h.type?new D(null,e,u):h),u.abort(),u=null)},e.cancelToken&&e.cancelToken.subscribe(c),e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c)));const w=bt(d);if(w&&S.protocols.indexOf(w)===-1){r(new p("Unsupported protocol "+w+":",p.ERR_BAD_REQUEST,e));return}u.send(o||null)})}const Oe={http:Re,xhr:Re};var Se={getAdapter:e=>{if(a.isString(e)){const t=Oe[e];if(!e)throw Error(a.hasOwnProp(e)?`Adapter '${e}' is not available in the build`:`Can not resolve adapter '${e}'`);return t}if(!a.isFunction(e))throw new TypeError("adapter is not a function");return e},adapters:Oe};const Nt={"Content-Type":"application/x-www-form-urlencoded"};function Pt(){let e;return typeof XMLHttpRequest!="undefined"?e=Se.getAdapter("xhr"):typeof Y!="undefined"&&a.kindOf(Y)==="process"&&(e=Se.getAdapter("http")),e}function Ct(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const C={transitional:he,adapter:Pt(),transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=a.isObject(t);if(i&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return o&&o?JSON.stringify(pe(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return ft(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return M(c?{"files[]":t}:t,f&&new f,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),Ct(t)):t}],transformResponse:[function(t){const n=this.transitional||C.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&a.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(c){if(s)throw c.name==="SyntaxError"?p.from(c,p.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:S.classes.FormData,Blob:S.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};a.forEach(["delete","get","head"],function(t){C.headers[t]={}}),a.forEach(["post","put","patch"],function(t){C.headers[t]=a.merge(Nt)});function W(e,t){const n=this||C,r=t||n,o=b.from(r.headers);let i=r.data;return a.forEach(e,function(c){i=c.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function Ae(e){return!!(e&&e.__CANCEL__)}function K(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new D}function Te(e){return K(e),e.headers=b.from(e.headers),e.data=W.call(e,e.transformRequest),(e.adapter||C.adapter)(e).then(function(r){return K(e),r.data=W.call(e,e.transformResponse,r),r.headers=b.from(r.headers),r},function(r){return Ae(r)||(K(e),r&&r.response&&(r.response.data=W.call(e,e.transformResponse,r.response),r.response.headers=b.from(r.response.headers))),Promise.reject(r)})}function g(e,t){t=t||{};const n={};function r(u,d){return a.isPlainObject(u)&&a.isPlainObject(d)?a.merge(u,d):a.isPlainObject(d)?a.merge({},d):a.isArray(d)?d.slice():d}function o(u){if(a.isUndefined(t[u])){if(!a.isUndefined(e[u]))return r(void 0,e[u])}else return r(e[u],t[u])}function i(u){if(!a.isUndefined(t[u]))return r(void 0,t[u])}function s(u){if(a.isUndefined(t[u])){if(!a.isUndefined(e[u]))return r(void 0,e[u])}else return r(void 0,t[u])}function c(u){if(u in t)return r(e[u],t[u]);if(u in e)return r(void 0,e[u])}const f={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:c};return a.forEach(Object.keys(e).concat(Object.keys(t)),function(d){const E=f[d]||o,w=E(d);a.isUndefined(w)&&E!==c||(n[d]=w)}),n}const xe="1.1.3",v={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{v[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ne={};v.transitional=function(t,n,r){function o(i,s){return"[Axios v"+xe+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,c)=>{if(t===!1)throw new p(o(s," has been removed"+(n?" in "+n:"")),p.ERR_DEPRECATED);return n&&!Ne[s]&&(Ne[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,c):!0}};function Ft(e,t,n){if(typeof e!="object")throw new p("options must be an object",p.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const c=e[i],f=c===void 0||s(c,i,e);if(f!==!0)throw new p("option "+i+" must be "+f,p.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new p("Unknown option "+i,p.ERR_BAD_OPTION)}}var X={assertOptions:Ft,validators:v};const A=X.validators;class x{constructor(t){this.defaults=t,this.interceptors={request:new de,response:new de}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=g(this.defaults,n);const{transitional:r,paramsSerializer:o}=n;r!==void 0&&X.assertOptions(r,{silentJSONParsing:A.transitional(A.boolean),forcedJSONParsing:A.transitional(A.boolean),clarifyTimeoutError:A.transitional(A.boolean)},!1),o!==void 0&&X.assertOptions(o,{encode:A.function,serialize:A.function},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();const i=n.headers&&a.merge(n.headers.common,n.headers[n.method]);i&&a.forEach(["delete","get","head","post","put","patch","common"],function(l){delete n.headers[l]}),n.headers=new b(n.headers,i);const s=[];let c=!0;this.interceptors.request.forEach(function(l){typeof l.runWhen=="function"&&l.runWhen(n)===!1||(c=c&&l.synchronous,s.unshift(l.fulfilled,l.rejected))});const f=[];this.interceptors.response.forEach(function(l){f.push(l.fulfilled,l.rejected)});let u,d=0,E;if(!c){const h=[Te.bind(this),void 0];for(h.unshift.apply(h,s),h.push.apply(h,f),E=h.length,u=Promise.resolve(n);d{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(c=>{r.subscribe(c),i=c}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,c){r.reason||(r.reason=new D(i,s,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new Q(function(o){t=o}),cancel:t}}}function Dt(e){return function(n){return e.apply(null,n)}}function _t(e){return a.isObject(e)&&e.isAxiosError===!0}function Pe(e){const t=new x(e),n=G(x.prototype.request,t);return a.extend(n,x.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pe(g(e,o))},n}const y=Pe(C);y.Axios=x,y.CanceledError=D,y.CancelToken=Q,y.isCancel=Ae,y.VERSION=xe,y.toFormData=M,y.AxiosError=p,y.Cancel=y.CanceledError,y.all=function(t){return Promise.all(t)},y.spread=Dt,y.isAxiosError=_t,y.formToJSON=e=>pe(a.isHTMLForm(e)?new FormData(e):e);export default y; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/bignumberjs.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/bignumberjs.js new file mode 100644 index 0000000000000000000000000000000000000000..565d20951ae35c4dc799107a9311f7951ec44f2b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/bignumberjs.js @@ -0,0 +1 @@ +var we=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ue=Math.ceil,H=Math.floor,k="[BigNumber Error] ",ge=k+"Number primitive has more than 15 significant digits: ",z=1e14,E=14,ce=9007199254740991,ae=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],J=1e7,P=1e9;function pe(O){var N,_,I,g=h.prototype={constructor:h,toString:null,valueOf:null},R=new h(1),v=20,B=4,U=-7,C=21,Q=-1e7,$=1e7,Z=!1,b=1,Y=0,te={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},K="0123456789abcdefghijklmnopqrstuvwxyz";function h(e,r){var i,s,t,l,c,n,f,u,o=this;if(!(o instanceof h))return new h(e,r);if(r==null){if(e&&e._isBigNumber===!0){o.s=e.s,!e.c||e.e>$?o.c=o.e=null:e.e=10;c/=10,l++);l>$?o.c=o.e=null:(o.e=l,o.c=[e]);return}u=String(e)}else{if(!we.test(u=String(e)))return I(o,u,n);o.s=u.charCodeAt(0)==45?(u=u.slice(1),-1):1}(l=u.indexOf("."))>-1&&(u=u.replace(".","")),(c=u.search(/e/i))>0?(l<0&&(l=c),l+=+u.slice(c+1),u=u.substring(0,c)):l<0&&(l=u.length)}else{if(S(r,2,K.length,"Base"),r==10)return o=new h(e),G(o,v+o.e+1,B);if(u=String(e),n=typeof e=="number"){if(e*0!=0)return I(o,u,n,r);if(o.s=1/e<0?(u=u.slice(1),-1):1,h.DEBUG&&u.replace(/^0\.0*|\./,"").length>15)throw Error(ge+e)}else o.s=u.charCodeAt(0)===45?(u=u.slice(1),-1):1;for(i=K.slice(0,r),l=c=0,f=u.length;cl){l=f;continue}}else if(!t&&(u==u.toUpperCase()&&(u=u.toLowerCase())||u==u.toLowerCase()&&(u=u.toUpperCase()))){t=!0,c=-1,l=0;continue}return I(o,String(e),n,r)}n=!1,u=_(u,r,10,o.s),(l=u.indexOf("."))>-1?u=u.replace(".",""):l=u.length}for(c=0;u.charCodeAt(c)===48;c++);for(f=u.length;u.charCodeAt(--f)===48;);if(u=u.slice(c,++f)){if(f-=c,n&&h.DEBUG&&f>15&&(e>ce||e!==H(e)))throw Error(ge+o.s*e);if((l=l-c-1)>$)o.c=o.e=null;else if(l=-P&&t<=P&&t===H(t)){if(s[0]===0){if(t===0&&s.length===1)return!0;break e}if(r=(t+1)%E,r<1&&(r+=E),String(s[0]).length==r){for(r=0;r=z||i!==H(i))break e;if(i!==0)return!0}}}else if(s===null&&t===null&&(l===null||l===1||l===-1))return!0;throw Error(k+"Invalid BigNumber: "+e)},h.maximum=h.max=function(){return he(arguments,g.lt)},h.minimum=h.min=function(){return he(arguments,g.gt)},h.random=function(){var e=9007199254740992,r=Math.random()*e&2097151?function(){return H(Math.random()*e)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(i){var s,t,l,c,n,f=0,u=[],o=new h(R);if(i==null?i=v:S(i,0,P),c=ue(i/E),Z)if(crypto.getRandomValues){for(s=crypto.getRandomValues(new Uint32Array(c*=2));f>>11),n>=9e15?(t=crypto.getRandomValues(new Uint32Array(2)),s[f]=t[0],s[f+1]=t[1]):(u.push(n%1e14),f+=2);f=c/2}else if(crypto.randomBytes){for(s=crypto.randomBytes(c*=7);f=9e15?crypto.randomBytes(7).copy(s,f):(u.push(n%1e14),f+=7);f=c/7}else throw Z=!1,Error(k+"crypto unavailable");if(!Z)for(;f=10;n/=10,f++);ft-1&&(n[c+1]==null&&(n[c+1]=0),n[c+1]+=n[c]/t|0,n[c]%=t)}return n.reverse()}return function(i,s,t,l,c){var n,f,u,o,a,p,w,d,x=i.indexOf("."),M=v,m=B;for(x>=0&&(o=Y,Y=0,i=i.replace(".",""),d=new h(s),p=d.pow(i.length-x),Y=o,d.c=r(W(y(p.c),p.e,"0"),10,t,e),d.e=d.c.length),w=r(i,s,t,c?(n=K,e):(n=e,K)),u=o=w.length;w[--o]==0;w.pop());if(!w[0])return n.charAt(0);if(x<0?--u:(p.c=w,p.e=u,p.s=l,p=N(p,d,M,m,t),w=p.c,a=p.r,u=p.e),f=u+M+1,x=w[f],o=t/2,a=a||f<0||w[f+1]!=null,a=m<4?(x!=null||a)&&(m==0||m==(p.s<0?3:2)):x>o||x==o&&(m==4||a||m==6&&w[f-1]&1||m==(p.s<0?8:7)),f<1||!w[0])i=a?W(n.charAt(1),-M,n.charAt(0)):n.charAt(0);else{if(w.length=f,a)for(--t;++w[--f]>t;)w[f]=0,f||(++u,w=[1].concat(w));for(o=w.length;!w[--o];);for(x=0,i="";x<=o;i+=n.charAt(w[x++]));i=W(i,u,n.charAt(0))}return i}}(),N=function(){function e(s,t,l){var c,n,f,u,o=0,a=s.length,p=t%J,w=t/J|0;for(s=s.slice();a--;)f=s[a]%J,u=s[a]/J|0,c=w*f+u*p,n=p*f+c%J*J+o,o=(n/l|0)+(c/J|0)+w*u,s[a]=n%l;return o&&(s=[o].concat(s)),s}function r(s,t,l,c){var n,f;if(l!=c)f=l>c?1:-1;else for(n=f=0;nt[n]?1:-1;break}return f}function i(s,t,l,c){for(var n=0;l--;)s[l]-=n,n=s[l]1;s.splice(0,1));}return function(s,t,l,c,n){var f,u,o,a,p,w,d,x,M,m,A,L,re,oe,se,X,ee,F=s.s==t.s?1:-1,D=s.c,T=t.c;if(!D||!D[0]||!T||!T[0])return new h(!s.s||!t.s||(D?T&&D[0]==T[0]:!T)?NaN:D&&D[0]==0||!T?F*0:F/0);for(x=new h(F),M=x.c=[],u=s.e-t.e,F=l+u+1,n||(n=z,u=q(s.e/E)-q(t.e/E),F=F/E|0),o=0;T[o]==(D[o]||0);o++);if(T[o]>(D[o]||0)&&u--,F<0)M.push(1),a=!0;else{for(oe=D.length,X=T.length,o=0,F+=2,p=H(n/(T[0]+1)),p>1&&(T=e(T,p,n),D=e(D,p,n),X=T.length,oe=D.length),re=X,m=D.slice(0,X),A=m.length;A=n/2&&se++;do{if(p=0,f=r(T,m,X,A),f<0){if(L=m[0],X!=A&&(L=L*n+(m[1]||0)),p=H(L/se),p>1)for(p>=n&&(p=n-1),w=e(T,p,n),d=w.length,A=m.length;r(w,m,d,A)==1;)p--,i(w,X=10;F/=10,o++);G(x,l+(x.e=o+u*E-1)+1,c,a)}else x.e=u,x.r=+a;return x}}();function fe(e,r,i,s){var t,l,c,n,f;if(i==null?i=B:S(i,0,8),!e.c)return e.toString();if(t=e.c[0],c=e.e,r==null)f=y(e.c),f=s==1||s==2&&(c<=U||c>=C)?ne(f,c):W(f,c,"0");else if(e=G(new h(e),r,i),l=e.e,f=y(e.c),n=f.length,s==1||s==2&&(r<=l||l<=U)){for(;nn){if(--r>0)for(f+=".";r--;f+="0");}else if(r+=l-n,r>0)for(l+1==n&&(f+=".");r--;f+="0");return e.s<0&&t?"-"+f:f}function he(e,r){for(var i,s=1,t=new h(e[0]);s=10;t/=10,s++);return(i=s+i*E-1)>$?e.c=e.e=null:i=10;n/=10,t++);if(l=r-t,l<0)l+=E,c=r,f=a[u=0],o=f/p[t-c-1]%10|0;else if(u=ue((l+1)/E),u>=a.length)if(s){for(;a.length<=u;a.push(0));f=o=0,t=1,l%=E,c=l-E+1}else break e;else{for(f=n=a[u],t=1;n>=10;n/=10,t++);l%=E,c=l-E+t,o=c<0?0:f/p[t-c-1]%10|0}if(s=s||r<0||a[u+1]!=null||(c<0?f:f%p[t-c-1]),s=i<4?(o||s)&&(i==0||i==(e.s<0?3:2)):o>5||o==5&&(i==4||s||i==6&&(l>0?c>0?f/p[t-c]:0:a[u-1])%10&1||i==(e.s<0?8:7)),r<1||!a[0])return a.length=0,s?(r-=e.e+1,a[0]=p[(E-r%E)%E],e.e=-r||0):a[0]=e.e=0,e;if(l==0?(a.length=u,n=1,u--):(a.length=u+1,n=p[E-l],a[u]=c>0?H(f/p[t-c]%p[c])*n:0),s)for(;;)if(u==0){for(l=1,c=a[0];c>=10;c/=10,l++);for(c=a[0]+=n,n=1;c>=10;c/=10,n++);l!=n&&(e.e++,a[0]==z&&(a[0]=1));break}else{if(a[u]+=n,a[u]!=z)break;a[u--]=0,n=1}for(l=a.length;a[--l]===0;a.pop());}e.e>$?e.c=e.e=null:e.e=C?ne(r,i):W(r,i,"0"),e.s<0?"-"+r:r)}return g.absoluteValue=g.abs=function(){var e=new h(this);return e.s<0&&(e.s=1),e},g.comparedTo=function(e,r){return j(this,new h(e,r))},g.decimalPlaces=g.dp=function(e,r){var i,s,t,l=this;if(e!=null)return S(e,0,P),r==null?r=B:S(r,0,8),G(new h(l),e+l.e+1,r);if(!(i=l.c))return null;if(s=((t=i.length-1)-q(this.e/E))*E,t=i[t])for(;t%10==0;t/=10,s--);return s<0&&(s=0),s},g.dividedBy=g.div=function(e,r){return N(this,new h(e,r),v,B)},g.dividedToIntegerBy=g.idiv=function(e,r){return N(this,new h(e,r),0,1)},g.exponentiatedBy=g.pow=function(e,r){var i,s,t,l,c,n,f,u,o,a=this;if(e=new h(e),e.c&&!e.isInteger())throw Error(k+"Exponent not an integer: "+V(e));if(r!=null&&(r=new h(r)),n=e.e>14,!a.c||!a.c[0]||a.c[0]==1&&!a.e&&a.c.length==1||!e.c||!e.c[0])return o=new h(Math.pow(+V(a),n?2-ie(e):+V(e))),r?o.mod(r):o;if(f=e.s<0,r){if(r.c?!r.c[0]:!r.s)return new h(NaN);s=!f&&a.isInteger()&&r.isInteger(),s&&(a=a.mod(r))}else{if(e.e>9&&(a.e>0||a.e<-1||(a.e==0?a.c[0]>1||n&&a.c[1]>=24e7:a.c[0]<8e13||n&&a.c[0]<=9999975e7)))return l=(a.s<0&&ie(e),-0),a.e>-1&&(l=1/l),new h(f?1/l:l);Y&&(l=ue(Y/E+2))}for(n?(i=new h(.5),f&&(e.s=1),u=ie(e)):(t=Math.abs(+V(e)),u=t%2),o=new h(R);;){if(u){if(o=o.times(a),!o.c)break;l?o.c.length>l&&(o.c.length=l):s&&(o=o.mod(r))}if(t){if(t=H(t/2),t===0)break;u=t%2}else if(e=e.times(i),G(e,e.e+1,1),e.e>14)u=ie(e);else{if(t=+V(e),t===0)break;u=t%2}a=a.times(a),l?a.c&&a.c.length>l&&(a.c.length=l):s&&(a=a.mod(r))}return s?o:(f&&(o=R.div(o)),r?o.mod(r):l?G(o,Y,B,c):o)},g.integerValue=function(e){var r=new h(this);return e==null?e=B:S(e,0,8),G(r,r.e+1,e)},g.isEqualTo=g.eq=function(e,r){return j(this,new h(e,r))===0},g.isFinite=function(){return!!this.c},g.isGreaterThan=g.gt=function(e,r){return j(this,new h(e,r))>0},g.isGreaterThanOrEqualTo=g.gte=function(e,r){return(r=j(this,new h(e,r)))===1||r===0},g.isInteger=function(){return!!this.c&&q(this.e/E)>this.c.length-2},g.isLessThan=g.lt=function(e,r){return j(this,new h(e,r))<0},g.isLessThanOrEqualTo=g.lte=function(e,r){return(r=j(this,new h(e,r)))===-1||r===0},g.isNaN=function(){return!this.s},g.isNegative=function(){return this.s<0},g.isPositive=function(){return this.s>0},g.isZero=function(){return!!this.c&&this.c[0]==0},g.minus=function(e,r){var i,s,t,l,c=this,n=c.s;if(e=new h(e,r),r=e.s,!n||!r)return new h(NaN);if(n!=r)return e.s=-r,c.plus(e);var f=c.e/E,u=e.e/E,o=c.c,a=e.c;if(!f||!u){if(!o||!a)return o?(e.s=-r,e):new h(a?c:NaN);if(!o[0]||!a[0])return a[0]?(e.s=-r,e):new h(o[0]?c:(B==3,-0))}if(f=q(f),u=q(u),o=o.slice(),n=f-u){for((l=n<0)?(n=-n,t=o):(u=f,t=a),t.reverse(),r=n;r--;t.push(0));t.reverse()}else for(s=(l=(n=o.length)<(r=a.length))?n:r,n=r=0;r0)for(;r--;o[i++]=0);for(r=z-1;s>n;){if(o[--s]=0;){for(i=0,p=L[t]%M,w=L[t]/M|0,c=f,l=t+c;l>t;)u=A[--c]%M,o=A[c]/M|0,n=w*u+o*p,u=p*u+n%M*M+d[l]+i,i=(u/x|0)+(n/M|0)+w*o,d[l--]=u%x;d[l]=i}return i?++s:d.splice(0,1),le(e,d,s)},g.negated=function(){var e=new h(this);return e.s=-e.s||null,e},g.plus=function(e,r){var i,s=this,t=s.s;if(e=new h(e,r),r=e.s,!t||!r)return new h(NaN);if(t!=r)return e.s=-r,s.minus(e);var l=s.e/E,c=e.e/E,n=s.c,f=e.c;if(!l||!c){if(!n||!f)return new h(t/0);if(!n[0]||!f[0])return f[0]?e:new h(n[0]?s:t*0)}if(l=q(l),c=q(c),n=n.slice(),t=l-c){for(t>0?(c=l,i=f):(t=-t,i=n),i.reverse();t--;i.push(0));i.reverse()}for(t=n.length,r=f.length,t-r<0&&(i=f,f=n,n=i,r=t),t=0;r;)t=(n[--r]=n[r]+f[r]+t)/z|0,n[r]=z===n[r]?0:n[r]%z;return t&&(n=[t].concat(n),++c),le(e,n,c)},g.precision=g.sd=function(e,r){var i,s,t,l=this;if(e!=null&&e!==!!e)return S(e,1,P),r==null?r=B:S(r,0,8),G(new h(l),e,r);if(!(i=l.c))return null;if(t=i.length-1,s=t*E+1,t=i[t]){for(;t%10==0;t/=10,s--);for(t=i[0];t>=10;t/=10,s++);}return e&&l.e+1>s&&(s=l.e+1),s},g.shiftedBy=function(e){return S(e,-ce,ce),this.times("1e"+e)},g.squareRoot=g.sqrt=function(){var e,r,i,s,t,l=this,c=l.c,n=l.s,f=l.e,u=v+4,o=new h("0.5");if(n!==1||!c||!c[0])return new h(!n||n<0&&(!c||c[0])?NaN:c?l:1/0);if(n=Math.sqrt(+V(l)),n==0||n==1/0?(r=y(c),(r.length+f)%2==0&&(r+="0"),n=Math.sqrt(+r),f=q((f+1)/2)-(f<0||f%2),n==1/0?r="5e"+f:(r=n.toExponential(),r=r.slice(0,r.indexOf("e")+1)+f),i=new h(r)):i=new h(n+""),i.c[0]){for(f=i.e,n=f+u,n<3&&(n=0);;)if(t=i,i=o.times(t.plus(N(l,t,u,1))),y(t.c).slice(0,n)===(r=y(i.c)).slice(0,n))if(i.e0&&d>0){for(l=d%n||n,o=w.substr(0,l);l0&&(o+=u+w.slice(l)),p&&(o="-"+o)}s=a?o+(i.decimalSeparator||"")+((f=+i.fractionGroupSize)?a.replace(new RegExp("\\d{"+f+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):a):o}return(i.prefix||"")+s+(i.suffix||"")},g.toFraction=function(e){var r,i,s,t,l,c,n,f,u,o,a,p,w=this,d=w.c;if(e!=null&&(n=new h(e),!n.isInteger()&&(n.c||n.s!==1)||n.lt(R)))throw Error(k+"Argument "+(n.isInteger()?"out of range: ":"not an integer: ")+V(n));if(!d)return new h(w);for(r=new h(R),u=i=new h(R),s=f=new h(R),p=y(d),l=r.e=p.length-w.e-1,r.c[0]=ae[(c=l%E)<0?E+c:c],e=!e||n.comparedTo(r)>0?l>0?r:u:n,c=$,$=1/0,n=new h(p),f.c[0]=0;o=N(n,r,0,1),t=i.plus(o.times(s)),t.comparedTo(e)!=1;)i=s,s=t,u=f.plus(o.times(t=u)),f=t,r=n.minus(o.times(t=r)),n=t;return t=N(e.minus(i),s,0,1),f=f.plus(t.times(u)),i=i.plus(t.times(s)),f.s=u.s=w.s,l=l*2,a=N(u,s,l,B).minus(w).abs().comparedTo(N(f,i,l,B).minus(w).abs())<1?[u,s]:[f,i],$=c,a},g.toNumber=function(){return+V(this)},g.toPrecision=function(e,r){return e!=null&&S(e,1,P),fe(this,e,r,2)},g.toString=function(e){var r,i=this,s=i.s,t=i.e;return t===null?s?(r="Infinity",s<0&&(r="-"+r)):r="NaN":(e==null?r=t<=U||t>=C?ne(y(i.c),t):W(y(i.c),t,"0"):e===10?(i=G(new h(i),v+t+1,B),r=W(y(i.c),i.e,"0")):(S(e,2,K.length,"Base"),r=_(W(y(i.c),t,"0"),10,e,s,!0)),s<0&&i.c[0]&&(r="-"+r)),r},g.valueOf=g.toJSON=function(){return V(this)},g._isBigNumber=!0,g[Symbol.toStringTag]="BigNumber",g[Symbol.for("nodejs.util.inspect.custom")]=g.valueOf,O!=null&&h.set(O),h}function q(O){var N=O|0;return O>0||O===N?N:N-1}function y(O){for(var N,_,I=1,g=O.length,R=O[0]+"";IC^_?1:-1;for(B=(U=g.length)<(C=R.length)?U:C,v=0;vR[v]^_?1:-1;return U==C?0:U>C^_?1:-1}function S(O,N,_,I){if(O_||O!==H(O))throw Error(k+(I||"Argument")+(typeof O=="number"?O_?" out of range: ":" not an integer: ":" not a primitive number: ")+String(O))}function ie(O){var N=O.c.length-1;return q(O.e/E)==N&&O.c[N]%2!=0}function ne(O,N){return(O.length>1?O.charAt(0)+"."+O.slice(1):O)+(N<0?"e":"e+")+N}function W(O,N,_){var I,g;if(N<0){for(g=_+".";++N;g+=_);O=g+O}else if(I=O.length,++N>I){for(g=_,N-=I;--N;g+=_);O+=g}else Ne.length)&&(n=e.length);for(var r=0,t=new Array(n);r=0)&&(r[a]=e[a]);return r}function _(e,n){if(e==null)return{};var r=Re(e,n),t,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(a=0;a=0)&&(!Object.prototype.propertyIsEnumerable.call(e,t)||(r[t]=e[t]))}return r}function S(e){return S=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},S(e)}function c(e,n){_e(e)&&(e="100%");var r=qe(e);return e=n===360?e:Math.min(n,Math.max(0,parseFloat(e))),r&&(e=parseInt(String(e*n),10)/100),Math.abs(e-n)<1e-6?1:(n===360?e=(e<0?e%n+n:e%n)/parseFloat(String(n)):e=e%n/parseFloat(String(n)),e)}function De(e){return Math.min(1,Math.max(0,e))}function _e(e){return typeof e=="string"&&e.indexOf(".")!==-1&&parseFloat(e)===1}function qe(e){return typeof e=="string"&&e.indexOf("%")!==-1}function J(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function M(e){return e<=1?"".concat(Number(e)*100,"%"):e}function p(e){return e.length===1?"0"+e:String(e)}function He(e,n,r){return{r:c(e,255)*255,g:c(n,255)*255,b:c(r,255)*255}}function ze(e,n,r){e=c(e,255),n=c(n,255),r=c(r,255);var t=Math.max(e,n,r),a=Math.min(e,n,r),i=0,f=0,o=(t+a)/2;if(t===a)f=0,i=0;else{var u=t-a;switch(f=o>.5?u/(2-t-a):u/(t+a),t){case e:i=(n-r)/u+(n1&&(r-=1),r<1/6?e+(n-e)*(6*r):r<1/2?n:r<2/3?e+(n-e)*(2/3-r)*6:e}function Be(e,n,r){var t,a,i;if(e=c(e,360),n=c(n,100),r=c(r,100),n===0)a=r,i=r,t=r;else{var f=r<.5?r*(1+n):r+n-r*n,o=2*r-f;t=q(o,f,e+1/3),a=q(o,f,e),i=q(o,f,e-1/3)}return{r:t*255,g:a*255,b:i*255}}function X(e,n,r){e=c(e,255),n=c(n,255),r=c(r,255);var t=Math.max(e,n,r),a=Math.min(e,n,r),i=0,f=t,o=t-a,u=t===0?0:o/t;if(t===a)i=0;else{switch(t){case e:i=(n-r)/o+(n>16,g:(e&65280)>>8,b:e&255}}var H={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",goldenrod:"#daa520",gold:"#ffd700",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavenderblush:"#fff0f5",lavender:"#e6e6fa",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};function C(e){var n={r:0,g:0,b:0},r=1,t=null,a=null,i=null,f=!1,o=!1;return typeof e=="string"&&(e=Ge(e)),typeof e=="object"&&(b(e.r)&&b(e.g)&&b(e.b)?(n=He(e.r,e.g,e.b),f=!0,o=String(e.r).substr(-1)==="%"?"prgb":"rgb"):b(e.h)&&b(e.s)&&b(e.v)?(t=M(e.s),a=M(e.v),n=$e(e.h,t,a),f=!0,o="hsv"):b(e.h)&&b(e.s)&&b(e.l)&&(t=M(e.s),i=M(e.l),n=Be(e.h,t,i),f=!0,o="hsl"),Object.prototype.hasOwnProperty.call(e,"a")&&(r=e.a)),r=J(r),{ok:f,format:e.format||o,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a:r}}var Ve="[-\\+]?\\d+%?",Ke="[-\\+]?\\d*\\.\\d+%?",v="(?:".concat(Ke,")|(?:").concat(Ve,")"),z="[\\s|\\(]+(".concat(v,")[,|\\s]+(").concat(v,")[,|\\s]+(").concat(v,")\\s*\\)?"),B="[\\s|\\(]+(".concat(v,")[,|\\s]+(").concat(v,")[,|\\s]+(").concat(v,")[,|\\s]+(").concat(v,")\\s*\\)?"),m={CSS_UNIT:new RegExp(v),rgb:new RegExp("rgb"+z),rgba:new RegExp("rgba"+B),hsl:new RegExp("hsl"+z),hsla:new RegExp("hsla"+B),hsv:new RegExp("hsv"+z),hsva:new RegExp("hsva"+B),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/};function Ge(e){if(e=e.trim().toLowerCase(),e.length===0)return!1;var n=!1;if(H[e])e=H[e],n=!0;else if(e==="transparent")return{r:0,g:0,b:0,a:0,format:"name"};var r=m.rgb.exec(e);return r?{r:r[1],g:r[2],b:r[3]}:(r=m.rgba.exec(e),r?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=m.hsl.exec(e),r?{h:r[1],s:r[2],l:r[3]}:(r=m.hsla.exec(e),r?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=m.hsv.exec(e),r?{h:r[1],s:r[2],v:r[3]}:(r=m.hsva.exec(e),r?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=m.hex8.exec(e),r?{r:g(r[1]),g:g(r[2]),b:g(r[3]),a:re(r[4]),format:n?"name":"hex8"}:(r=m.hex6.exec(e),r?{r:g(r[1]),g:g(r[2]),b:g(r[3]),format:n?"name":"hex"}:(r=m.hex4.exec(e),r?{r:g(r[1]+r[1]),g:g(r[2]+r[2]),b:g(r[3]+r[3]),a:re(r[4]+r[4]),format:n?"name":"hex8"}:(r=m.hex3.exec(e),r?{r:g(r[1]+r[1]),g:g(r[2]+r[2]),b:g(r[3]+r[3]),format:n?"name":"hex"}:!1)))))))))}function b(e){return Boolean(m.CSS_UNIT.exec(String(e)))}var E=2,ne=.16,Qe=.05,Ye=.05,Ze=.15,te=5,ae=4,Je=[{index:7,opacity:.15},{index:6,opacity:.25},{index:5,opacity:.3},{index:5,opacity:.45},{index:5,opacity:.65},{index:5,opacity:.85},{index:4,opacity:.9},{index:3,opacity:.95},{index:2,opacity:.97},{index:1,opacity:.98}];function ie(e){var n=e.r,r=e.g,t=e.b,a=X(n,r,t);return{h:a.h*360,s:a.s,v:a.v}}function N(e){var n=e.r,r=e.g,t=e.b;return"#".concat(ee(n,r,t,!1))}function Xe(e,n,r){var t=r/100,a={r:(n.r-e.r)*t+e.r,g:(n.g-e.g)*t+e.g,b:(n.b-e.b)*t+e.b};return a}function oe(e,n,r){var t;return Math.round(e.h)>=60&&Math.round(e.h)<=240?t=r?Math.round(e.h)-E*n:Math.round(e.h)+E*n:t=r?Math.round(e.h)+E*n:Math.round(e.h)-E*n,t<0?t+=360:t>=360&&(t-=360),t}function fe(e,n,r){if(e.h===0&&e.s===0)return e.s;var t;return r?t=e.s-ne*n:n===ae?t=e.s+ne:t=e.s+Qe*n,t>1&&(t=1),r&&n===te&&t>.1&&(t=.1),t<.06&&(t=.06),Number(t.toFixed(2))}function ue(e,n,r){var t;return r?t=e.v+Ye*n:t=e.v-Ze*n,t>1&&(t=1),Number(t.toFixed(2))}function I(e){for(var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=[],t=C(e),a=te;a>0;a-=1){var i=ie(t),f=N(C({h:oe(i,a,!0),s:fe(i,a,!0),v:ue(i,a,!0)}));r.push(f)}r.push(N(t));for(var o=1;o<=ae;o+=1){var u=ie(t),h=N(C({h:oe(u,o),s:fe(u,o),v:ue(u,o)}));r.push(h)}return n.theme==="dark"?Je.map(function(l){var y=l.index,A=l.opacity,k=N(Xe(C(n.backgroundColor||"#141414"),C(r[y]),A*100));return k}):r}var P={red:"#F5222D",volcano:"#FA541C",orange:"#FA8C16",gold:"#FAAD14",yellow:"#FADB14",lime:"#A0D911",green:"#52C41A",cyan:"#13C2C2",blue:"#1890FF",geekblue:"#2F54EB",purple:"#722ED1",magenta:"#EB2F96",grey:"#666666"},$={},W={};Object.keys(P).forEach(function(e){$[e]=I(P[e]),$[e].primary=$[e][5],W[e]=I(P[e],{theme:"dark",backgroundColor:"#141414"}),W[e].primary=W[e][5]});var ce={};function le(e,n){}function er(e,n,r){!n&&!ce[r]&&(e(!1,r),ce[r]=!0)}function se(e,n){er(le,e,n)}function de(){return!!(typeof window!="undefined"&&window.document&&window.document.createElement)}function ge(e,n){if(!e)return!1;if(e.contains)return e.contains(n);for(var r=n;r;){if(r===e)return!0;r=r.parentNode}return!1}var me="data-rc-order",rr="rc-util-key",L=new Map;function he(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=e.mark;return n?n.startsWith("data-")?n:"data-".concat(n):rr}function U(e){if(e.attachTo)return e.attachTo;var n=document.querySelector("head");return n||document.body}function nr(e){return e==="queue"?"prependQueue":e?"prepend":"append"}function be(e){return Array.from((L.get(e)||e).children).filter(function(n){return n.tagName==="STYLE"})}function ve(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!de())return null;var r=n.csp,t=n.prepend,a=document.createElement("style");a.setAttribute(me,nr(t)),(r==null?void 0:r.nonce)&&(a.nonce=r==null?void 0:r.nonce),a.innerHTML=e;var i=U(n),f=i.firstChild;if(t){if(t==="queue"){var o=be(i).filter(function(u){return["prepend","prependQueue"].includes(u.getAttribute(me))});if(o.length)return i.insertBefore(a,o[o.length-1].nextSibling),a}i.insertBefore(a,f)}else i.appendChild(a);return a}function pe(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=U(n);return be(r).find(function(t){return t.getAttribute(he(n))===e})}function tr(e){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=pe(e,r);t==null||(n=t.parentNode)===null||n===void 0||n.removeChild(t)}function ar(e,n){var r=L.get(e);if(!r||!ge(document,r)){var t=ve("",n),a=t.parentNode;L.set(e,a),a.removeChild(t)}}function ye(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},t=U(r);ar(t,r);var a=pe(n,r);if(a){var i,f;if(((i=r.csp)===null||i===void 0?void 0:i.nonce)&&a.nonce!==((f=r.csp)===null||f===void 0?void 0:f.nonce)){var o;a.nonce=(o=r.csp)===null||o===void 0?void 0:o.nonce}return a.innerHTML!==e&&(a.innerHTML=e),a}var u=ve(e,r);return u.setAttribute(he(r),n),u}function ir(e,n){se(e,"[@ant-design/icons] ".concat(n))}function Ce(e){return S(e)==="object"&&typeof e.name=="string"&&typeof e.theme=="string"&&(S(e.icon)==="object"||typeof e.icon=="function")}function we(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Object.keys(e).reduce(function(n,r){var t=e[r];switch(r){case"class":n.className=t,delete n.class;break;default:n[r]=t}return n},{})}function V(e,n,r){return r?d.createElement(e.tag,s(s({key:n},we(e.attrs)),r),(e.children||[]).map(function(t,a){return V(t,"".concat(n,"-").concat(e.tag,"-").concat(a))})):d.createElement(e.tag,s({key:n},we(e.attrs)),(e.children||[]).map(function(t,a){return V(t,"".concat(n,"-").concat(e.tag,"-").concat(a))}))}function xe(e){return I(e)[0]}function ke(e){return e?Array.isArray(e)?e:[e]:[]}var or=` +.anticon { + display: inline-block; + color: inherit; + font-style: normal; + line-height: 0; + text-align: center; + text-transform: none; + vertical-align: -0.125em; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.anticon > * { + line-height: 1; +} + +.anticon svg { + display: inline-block; +} + +.anticon::before { + display: none; +} + +.anticon .anticon-icon { + display: block; +} + +.anticon[tabindex] { + cursor: pointer; +} + +.anticon-spin::before, +.anticon-spin { + display: inline-block; + -webkit-animation: loadingCircle 1s infinite linear; + animation: loadingCircle 1s infinite linear; +} + +@-webkit-keyframes loadingCircle { + 100% { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} + +@keyframes loadingCircle { + 100% { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } +} +`,fr=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:or,r=d.useContext(j),t=r.csp;d.useEffect(function(){ye(n,"@ant-design-icons",{prepend:!0,csp:t})},[])},ur=["icon","className","onClick","style","primaryColor","secondaryColor"],T={primaryColor:"#333",secondaryColor:"#E6E6E6",calculated:!1};function cr(e){var n=e.primaryColor,r=e.secondaryColor;T.primaryColor=n,T.secondaryColor=r||xe(n),T.calculated=!!r}function lr(){return s({},T)}var w=function(n){var r=n.icon,t=n.className,a=n.onClick,i=n.style,f=n.primaryColor,o=n.secondaryColor,u=_(n,ur),h=T;if(f&&(h={primaryColor:f,secondaryColor:o||xe(f)}),fr(),ir(Ce(r),"icon should be icon definiton, but got ".concat(r)),!Ce(r))return null;var l=r;return l&&typeof l.icon=="function"&&(l=s(s({},l),{},{icon:l.icon(h.primaryColor,h.secondaryColor)})),V(l.icon,"svg-".concat(l.name),s({className:t,onClick:a,style:i,"data-icon":l.name,width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true"},u))};w.displayName="IconReact",w.getTwoToneColors=lr,w.setTwoToneColors=cr;function Se(e){var n=ke(e),r=D(n,2),t=r[0],a=r[1];return w.setTwoToneColors({primaryColor:t,secondaryColor:a})}function sr(){var e=w.getTwoToneColors();return e.calculated?[e.primaryColor,e.secondaryColor]:e.primaryColor}var dr=["className","icon","spin","rotate","tabIndex","onClick","twoToneColor"];Se("#1890ff");var x=d.forwardRef(function(e,n){var r,t=e.className,a=e.icon,i=e.spin,f=e.rotate,o=e.tabIndex,u=e.onClick,h=e.twoToneColor,l=_(e,dr),y=d.useContext(j),A=y.prefixCls,k=A===void 0?"anticon":A,Oe=y.rootClassName,Me=Fe(Oe,k,(r={},O(r,"".concat(k,"-").concat(a.name),!!a.name),O(r,"".concat(k,"-spin"),!!i||a.name==="loading"),r),t),F=o;F===void 0&&u&&(F=-1);var Ee=f?{msTransform:"rotate(".concat(f,"deg)"),transform:"rotate(".concat(f,"deg)")}:void 0,Ne=ke(h),K=D(Ne,2),Ie=K[0],Pe=K[1];return d.createElement("span",s(s({role:"img","aria-label":a.name},l),{},{ref:n,tabIndex:F,onClick:u,className:Me}),d.createElement(w,{icon:a,primaryColor:Ie,secondaryColor:Pe,style:Ee}))});x.displayName="AntdIcon",x.getTwoToneColor=sr,x.setTwoToneColor=Se;var gr={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z"}}]},name:"down",theme:"outlined"},Te=function(n,r){return d.createElement(x,s(s({},n),{},{ref:r,icon:gr}))};Te.displayName="DownOutlined";var mr=d.forwardRef(Te),hr={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"defs",attrs:{},children:[{tag:"style",attrs:{}}]},{tag:"path",attrs:{d:"M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"}},{tag:"path",attrs:{d:"M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"}}]},name:"plus",theme:"outlined"},Ae=function(n,r){return d.createElement(x,s(s({},n),{},{ref:r,icon:hr}))};Ae.displayName="PlusOutlined";var br=d.forwardRef(Ae);export{P as A,mr as D,x as I,br as P,s as _,ze as a,J as b,ee as c,We as d,c as e,H as f,De as g,S as h,C as i,R as j,Y as k,Q as l,Z as m,Ue as n,O as o,_ as p,D as q,X as r,de as s,I as t,ye as u,j as v,se as w,le as x,ge as y,tr as z}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/ResizeObserver.es-fd8ba902.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/ResizeObserver.es-fd8ba902.js new file mode 100644 index 0000000000000000000000000000000000000000..fa76dcb019abe5aa2d61f149049dc6e0c5fddccb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/ResizeObserver.es-fd8ba902.js @@ -0,0 +1 @@ +var b=function(){if(typeof Map!="undefined")return Map;function e(t,n){var r=-1;return t.some(function(i,o){return i[0]===n?(r=o,!0):!1}),r}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(n){var r=e(this.__entries__,n),i=this.__entries__[r];return i&&i[1]},t.prototype.set=function(n,r){var i=e(this.__entries__,n);~i?this.__entries__[i][1]=r:this.__entries__.push([n,r])},t.prototype.delete=function(n){var r=this.__entries__,i=e(r,n);~i&&r.splice(i,1)},t.prototype.has=function(n){return!!~e(this.__entries__,n)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(n,r){r===void 0&&(r=null);for(var i=0,o=this.__entries__;i0},e.prototype.connect_=function(){!v||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),A?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!v||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(t){var n=t.propertyName,r=n===void 0?"":n,i=x.some(function(o){return!!~r.indexOf(o)});i&&this.refresh()},e.getInstance=function(){return this.instance_||(this.instance_=new e),this.instance_},e.instance_=null,e}(),_=function(e,t){for(var n=0,r=Object.keys(t);n0},e}(),g=typeof WeakMap!="undefined"?new WeakMap:new b,w=function(){function e(t){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var n=z.getInstance(),r=new F(t,n,this);g.set(this,r)}return e}();["observe","unobserve","disconnect"].forEach(function(e){w.prototype[e]=function(){var t;return(t=g.get(this))[e].apply(t,arguments)}});var H=function(){return typeof f.ResizeObserver!="undefined"?f.ResizeObserver:w}();export{H as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_Map-e270ea77.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_Map-e270ea77.js new file mode 100644 index 0000000000000000000000000000000000000000..d3930a7f1fdfffef79466df190620b3d1e7e7e20 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_Map-e270ea77.js @@ -0,0 +1 @@ +import{_ as a}from"./_getNative-f6f203b5.js";import{_ as t}from"./_baseGetTag-3262967e.js";var e=a(t,"Map"),r=e;export{r as _}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_MapCache-c4ecbe9d.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_MapCache-c4ecbe9d.js new file mode 100644 index 0000000000000000000000000000000000000000..8cfd5b8143f7048467d143cdbdc6d7d8e79f3d81 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_MapCache-c4ecbe9d.js @@ -0,0 +1 @@ +import{_ as u}from"./_getNative-f6f203b5.js";import{_ as d}from"./_Map-e270ea77.js";function v(){this.__data__=[],this.size=0}var f=v;function C(t,a){return t===a||t!==t&&a!==a}var p=C;function g(t,a){for(var e=t.length;e--;)if(p(t[e][0],a))return e;return-1}var _=g,m=Array.prototype,y=m.splice;function z(t){var a=this.__data__,e=_(a,t);if(e<0)return!1;var r=a.length-1;return e==r?a.pop():y.call(a,e,1),--this.size,!0}var D=z;function H(t){var a=this.__data__,e=_(a,t);return e<0?void 0:a[e][1]}var b=H;function w(t){return _(this.__data__,t)>-1}var x=w;function O(t,a){var e=this.__data__,r=_(e,t);return r<0?(++this.size,e.push([t,a])):e[r][1]=a,this}var S=O;function s(t){var a=-1,e=t==null?0:t.length;for(this.clear();++a-1}var g=x;function v(n,e,t){for(var r=-1,i=n==null?0:n.length;++r-1&&t%1==0&&tt))return!1;var _=a.get(r),A=a.get(e);if(_&&A)return _==e&&A==r;var g=-1,i=!0,p=n&k?new H:void 0;for(a.set(r,e),a.set(e,r);++g0){if(++e>=S)return arguments[0]}else e=0;return r.apply(void 0,arguments)}}var g=w,O=g(h),x=O;function R(r,e){return x(_(r,e,l),r+"")}var N=R;export{N as _,c as a}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_baseTimes-d6ede5f1.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_baseTimes-d6ede5f1.js new file mode 100644 index 0000000000000000000000000000000000000000..5029f57edd1c5190b68de800452e1d588e5d7e61 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/_baseTimes-d6ede5f1.js @@ -0,0 +1 @@ +function i(r,s){for(var e=-1,a=Array(r);++e=y){var c=_?null:m(i);if(c)return I(c);h=!1,f=b,s=new S}else s=_?[]:r;s:for(;++t=120&&i.length>=120)?new o(n&&i):void 0}i=s[0];var g=-1,r=f[0];n:for(;++g=r||a<0||c&&m>=l}function g(){var n=I();if(h(n))return p(n);i=setTimeout(g,O(n))}function p(n){return i=void 0,v&&u?T(n):(u=o=void 0,s)}function W(){i!==void 0&&clearTimeout(i),d=0,u=f=o=i=void 0}function j(){return i===void 0?s:p(I())}function b(){var n=I(),a=h(n);if(u=arguments,o=this,f=n,a){if(i===void 0)return k(f);if(c)return clearTimeout(i),i=setTimeout(g,r),T(f)}return i===void 0&&(i=setTimeout(g,r)),s}return b.cancel=W,b.flush=j,b}var K=J;export{K as d}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/defaultLocale-5df5e395.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/defaultLocale-5df5e395.js new file mode 100644 index 0000000000000000000000000000000000000000..39172209f467e8d5d3c9c8195c68a3b941d65f4e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/defaultLocale-5df5e395.js @@ -0,0 +1 @@ +function W(n){return Math.abs(n=Math.round(n))>=1e21?n.toLocaleString("en").replace(/,/g,""):n.toString(10)}function A(n,t){if((e=(n=t?n.toExponential(t-1):n.toExponential()).indexOf("e"))<0)return null;var e,i=n.slice(0,e);return[i.length>1?i[0]+i.slice(2):i,+n.slice(e+1)]}function G(n){return n=A(Math.abs(n)),n?n[1]:NaN}function _(n,t){return function(e,i){for(var o=e.length,f=[],c=0,u=n[0],p=0;o>0&&u>0&&(p+u+1>i&&(u=Math.max(1,i-p)),f.push(e.substring(o-=u,o+u)),!((p+=u+1)>i));)u=n[c=(c+1)%n.length];return f.reverse().join(t)}}function v(n){return function(t){return t.replace(/[0-9]/g,function(e){return n[+e]})}}var nn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function j(n){if(!(t=nn.exec(n)))throw new Error("invalid format: "+n);var t;return new E({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}j.prototype=E.prototype;function E(n){this.fill=n.fill===void 0?" ":n.fill+"",this.align=n.align===void 0?">":n.align+"",this.sign=n.sign===void 0?"-":n.sign+"",this.symbol=n.symbol===void 0?"":n.symbol+"",this.zero=!!n.zero,this.width=n.width===void 0?void 0:+n.width,this.comma=!!n.comma,this.precision=n.precision===void 0?void 0:+n.precision,this.trim=!!n.trim,this.type=n.type===void 0?"":n.type+""}E.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function tn(n){n:for(var t=n.length,e=1,i=-1,o;e0&&(i=0);break}return i>0?n.slice(0,i)+n.slice(o+1):n}var I;function rn(n,t){var e=A(n,t);if(!e)return n+"";var i=e[0],o=e[1],f=o-(I=Math.max(-8,Math.min(8,Math.floor(o/3)))*3)+1,c=i.length;return f===c?i:f>c?i+new Array(f-c+1).join("0"):f>0?i.slice(0,f)+"."+i.slice(f):"0."+new Array(1-f).join("0")+A(n,Math.max(0,t+f-1))[0]}function X(n,t){var e=A(n,t);if(!e)return n+"";var i=e[0],o=e[1];return o<0?"0."+new Array(-o).join("0")+i:i.length>o+1?i.slice(0,o+1)+"."+i.slice(o+1):i+new Array(o-i.length+2).join("0")}var O={"%":(n,t)=>(n*100).toFixed(t),b:n=>Math.round(n).toString(2),c:n=>n+"",d:W,e:(n,t)=>n.toExponential(t),f:(n,t)=>n.toFixed(t),g:(n,t)=>n.toPrecision(t),o:n=>Math.round(n).toString(8),p:(n,t)=>X(n*100,t),r:X,s:rn,X:n=>Math.round(n).toString(16).toUpperCase(),x:n=>Math.round(n).toString(16)};function R(n){return n}var U=Array.prototype.map,Y=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function Z(n){var t=n.grouping===void 0||n.thousands===void 0?R:_(U.call(n.grouping,Number),n.thousands+""),e=n.currency===void 0?"":n.currency[0]+"",i=n.currency===void 0?"":n.currency[1]+"",o=n.decimal===void 0?".":n.decimal+"",f=n.numerals===void 0?R:v(U.call(n.numerals,String)),c=n.percent===void 0?"%":n.percent+"",u=n.minus===void 0?"\u2212":n.minus+"",p=n.nan===void 0?"NaN":n.nan+"";function $(a){a=j(a);var x=a.fill,M=a.align,m=a.sign,w=a.symbol,l=a.zero,S=a.width,N=a.comma,g=a.precision,L=a.trim,d=a.type;d==="n"?(N=!0,d="g"):O[d]||(g===void 0&&(g=12),L=!0,d="g"),(l||x==="0"&&M==="=")&&(l=!0,x="0",M="=");var K=w==="$"?e:w==="#"&&/[boxX]/.test(d)?"0"+d.toLowerCase():"",Q=w==="$"?i:/[%p]/.test(d)?c:"",T=O[d],V=/[defgprs%]/.test(d);g=g===void 0?6:/[gprs]/.test(d)?Math.max(1,Math.min(21,g)):Math.max(0,Math.min(20,g));function C(r){var y=K,h=Q,b,D,k;if(d==="c")h=T(r)+h,r="";else{r=+r;var P=r<0||1/r<0;if(r=isNaN(r)?p:T(Math.abs(r),g),L&&(r=tn(r)),P&&+r==0&&m!=="+"&&(P=!1),y=(P?m==="("?m:u:m==="-"||m==="("?"":m)+y,h=(d==="s"?Y[8+I/3]:"")+h+(P&&m==="("?")":""),V){for(b=-1,D=r.length;++bk||k>57){h=(k===46?o+r.slice(b+1):r.slice(b))+h,r=r.slice(0,b);break}}}N&&!l&&(r=t(r,Infinity));var z=y.length+r.length+h.length,s=z>1)+y+r+h+s.slice(z);break;default:r=s+y+r+h;break}return f(r)}return C.toString=function(){return a+""},C}function J(a,x){var M=$((a=j(a),a.type="f",a)),m=Math.max(-8,Math.min(8,Math.floor(G(x)/3)))*3,w=Math.pow(10,-m),l=Y[8+m/3];return function(S){return M(w*S)+l}}return{format:$,formatPrefix:J}}var F,q,B;H({thousands:",",grouping:[3],currency:["$",""]});function H(n){return F=Z(n),q=F.format,B=F.formatPrefix,F}export{E as F,B as a,q as b,Z as c,H as d,G as e,j as f}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/hoist-non-react-statics.cjs-01efe895.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/hoist-non-react-statics.cjs-01efe895.js new file mode 100644 index 0000000000000000000000000000000000000000..37e095c5f9880551f302601d6c02ef34a3defecb --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/hoist-non-react-statics.cjs-01efe895.js @@ -0,0 +1 @@ +import{r as f}from"./index-87351f60.js";var d={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},g={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},l={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},y={};y[f.ForwardRef]=l,y[f.Memo]=s;function T(r){return f.isMemo(r)?s:y[r.$$typeof]||d}var j=Object.defineProperty,N=Object.getOwnPropertyNames,c=Object.getOwnPropertySymbols,b=Object.getOwnPropertyDescriptor,w=Object.getPrototypeOf,O=Object.prototype;function P(r,t,p){if(typeof t!="string"){if(O){var u=w(t);u&&u!==O&&P(r,u,p)}var a=N(t);c&&(a=a.concat(c(t)));for(var v=T(r),i=T(t),o=0;o{Object.prototype.hasOwnProperty.call(t,"append")||Object.defineProperty(t,"append",{configurable:!0,enumerable:!0,writable:!0,value(...e){const n=document.createDocumentFragment();e.forEach(s=>{const r=s instanceof Node;n.appendChild(r?s:document.createTextNode(String(s)))}),this.appendChild(n)}})})}([Element.prototype,Document.prototype,DocumentFragment.prototype]);class qt{get disposed(){return this._disposed===!0}dispose(){this._disposed=!0}}(function(i){function t(){return(e,n,s)=>{const r=s.value,o=e.__proto__;s.value=function(){this.disposed||(r.call(this),o.dispose.call(this))}}}i.dispose=t})(qt||(qt={}));class tr{constructor(){this.isDisposed=!1,this.items=new Set}get disposed(){return this.isDisposed}dispose(){this.isDisposed||(this.isDisposed=!0,this.items.forEach(t=>{t.dispose()}),this.items.clear())}contains(t){return this.items.has(t)}add(t){this.items.add(t)}remove(t){this.items.delete(t)}clear(){this.items.clear()}}(function(i){function t(e){const n=new i;return e.forEach(s=>{n.add(s)}),n}i.from=t})(tr||(tr={}));var er=typeof global=="object"&&global&&global.Object===Object&&global,nc=typeof self=="object"&&self&&self.Object===Object&&self,Tt=er||nc||Function("return this")(),At=Tt.Symbol,nr=Object.prototype,sc=nr.hasOwnProperty,ic=nr.toString,un=At?At.toStringTag:void 0;function rc(i){var t=sc.call(i,un),e=i[un];try{i[un]=void 0;var n=!0}catch(r){}var s=ic.call(i);return n&&(t?i[un]=e:delete i[un]),s}var oc=Object.prototype,ac=oc.toString;function lc(i){return ac.call(i)}var cc="[object Null]",hc="[object Undefined]",sr=At?At.toStringTag:void 0;function ee(i){return i==null?i===void 0?hc:cc:sr&&sr in Object(i)?rc(i):lc(i)}function Nt(i){return i!=null&&typeof i=="object"}var uc="[object Symbol]";function Dt(i){return typeof i=="symbol"||Nt(i)&&ee(i)==uc}function fn(i,t){for(var e=-1,n=i==null?0:i.length,s=Array(n);++e0){if(++t>=zc)return arguments[0]}else t=0;return i.apply(void 0,arguments)}}function Hc(i){return function(){return i}}var Jn=function(){try{var i=me(Object,"defineProperty");return i({},"",{}),i}catch(t){}}(),qc=Jn?function(i,t){return Jn(i,"toString",{configurable:!0,enumerable:!1,value:Hc(t),writable:!0})}:Ne,fr=_c(qc);function Gc(i,t){for(var e=-1,n=i==null?0:i.length;++e-1}var Yc=9007199254740991,Zc=/^(?:0|[1-9]\d*)$/;function Yn(i,t){var e=typeof i;return t=t==null?Yc:t,!!t&&(e=="number"||e!="symbol"&&Zc.test(i))&&i>-1&&i%1==0&&i-1&&i%1==0&&i<=th}function ye(i){return i!=null&&Hs(i.length)&&!zs(i)}function Kn(i,t,e){if(!rt(e))return!1;var n=typeof t;return(n=="number"?ye(e)&&Yn(t,e.length):n=="string"&&t in e)?Le(e[t],i):!1}function mr(i){return Ie(function(t,e){var n=-1,s=e.length,r=s>1?e[s-1]:void 0,o=s>2?e[2]:void 0;for(r=i.length>3&&typeof r=="function"?(s--,r):void 0,o&&Kn(e[0],e[1],o)&&(r=s<3?void 0:r,s=1),t=Object(t);++n-1}function cu(i,t){var e=this.__data__,n=es(e,i);return n<0?(++this.size,e.push([i,t])):e[n][1]=t,this}function Gt(i){var t=-1,e=i==null?0:i.length;for(this.clear();++t0&&e(a)?t>1?Pn(a,t-1,e,n,s):Xs(s,a):n||(s[s.length]=a)}return s}var Js=Sr(Object.getPrototypeOf,Object),Su="[object Object]",Ou=Function.prototype,Eu=Object.prototype,Mr=Ou.toString,Mu=Eu.hasOwnProperty,Tu=Mr.call(Object);function $t(i){if(!Nt(i)||ee(i)!=Su)return!1;var t=Js(i);if(t===null)return!0;var e=Mu.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Mr.call(e)==Tu}function Nu(i,t,e){var n=-1,s=i.length;t<0&&(t=-t>s?0:s+t),e=e>s?s:e,e<0&&(e+=s),s=t>e?0:e-t>>>0,t>>>=0;for(var r=Array(s);++n=n?i:Nu(i,t,e)}var Iu="\\ud800-\\udfff",ju="\\u0300-\\u036f",Du="\\ufe20-\\ufe2f",$u="\\u20d0-\\u20ff",Ru=ju+Du+$u,ku="\\ufe0e\\ufe0f",Bu="\\u200d",zu=RegExp("["+Bu+Iu+Ru+ku+"]");function Tr(i){return zu.test(i)}function Vu(i){return i.split("")}var Nr="\\ud800-\\udfff",Fu="\\u0300-\\u036f",_u="\\ufe20-\\ufe2f",Hu="\\u20d0-\\u20ff",qu=Fu+_u+Hu,Gu="\\ufe0e\\ufe0f",Uu="["+Nr+"]",Ys="["+qu+"]",Zs="\\ud83c[\\udffb-\\udfff]",Wu="(?:"+Ys+"|"+Zs+")",Lr="[^"+Nr+"]",Ir="(?:\\ud83c[\\udde6-\\uddff]){2}",jr="[\\ud800-\\udbff][\\udc00-\\udfff]",Xu="\\u200d",Dr=Wu+"?",$r="["+Gu+"]?",Ju="(?:"+Xu+"(?:"+[Lr,Ir,jr].join("|")+")"+$r+Dr+")*",Yu=$r+Dr+Ju,Zu="(?:"+[Lr+Ys+"?",Ys,Ir,jr,Uu].join("|")+")",Ku=RegExp(Zs+"(?="+Zs+")|"+Zu+Yu,"g");function Qu(i){return i.match(Ku)||[]}function tf(i){return Tr(i)?Qu(i):Vu(i)}function Rr(i){return function(t){t=vn(t);var e=Tr(t)?tf(t):void 0,n=e?e[0]:t.charAt(0),s=e?Lu(e,1).join(""):t.slice(1);return n[i]()+s}}var is=Rr("toUpperCase");function ef(i){return is(vn(i).toLowerCase())}function nf(i,t,e,n){var s=-1,r=i==null?0:i.length;for(n&&r&&(e=i[++s]);++s=t?i:t)),i}function Ct(i,t,e){return e===void 0&&(e=t,t=void 0),e!==void 0&&(e=dn(e),e=e===e?e:0),t!==void 0&&(t=dn(t),t=t===t?t:0),Gf(dn(i),t,e)}function Uf(){this.__data__=new Gt,this.size=0}function Wf(i){var t=this.__data__,e=t.delete(i);return this.size=t.size,e}function Xf(i){return this.__data__.get(i)}function Jf(i){return this.__data__.has(i)}var Yf=200;function Zf(i,t){var e=this.__data__;if(e instanceof Gt){var n=e.__data__;if(!xn||n.lengtha))return!1;var c=r.get(i),h=r.get(t);if(c&&h)return c==t&&h==i;var u=-1,f=!0,d=e&Eg?new Ve:void 0;for(r.set(i,t),r.set(t,i);++u=t||S<0||u&&E>=r}function y(){var A=li();if(m(A))return x(A);a=setTimeout(y,p(A))}function x(A){return a=void 0,f&&n?d(A):(n=s=void 0,o)}function b(){a!==void 0&&clearTimeout(a),c=0,n=l=s=a=void 0}function w(){return a===void 0?o:x(li())}function P(){var A=li(),S=m(A);if(n=arguments,s=this,l=A,S){if(a===void 0)return g(l);if(u)return clearTimeout(a),a=setTimeout(y,t),d(l)}return a===void 0&&(a=setTimeout(y,t)),o}return P.cancel=b,P.flush=w,P}var Ro=Object.prototype,bp=Ro.hasOwnProperty,xp=Ie(function(i,t){i=Object(i);var e=-1,n=t.length,s=n>2?t[2]:void 0;for(s&&Kn(t[0],t[1],s)&&(n=1);++e=Ap&&(r=ii,o=!1,t=new Ve(t));t:for(;++st}var Np=Object.prototype,Lp=Np.hasOwnProperty;function Ip(i,t){return i!=null&&Lp.call(i,t)}function us(i,t){return i!=null&&Io(i,t,Ip)}var jp="[object Map]",Dp="[object Set]",$p=Object.prototype,Rp=$p.hasOwnProperty;function Fo(i){if(i==null)return!0;if(ye(i)&&(bt(i)||typeof i=="string"||typeof i.splice=="function"||De(i)||ts(i)||je(i)))return!i.length;var t=ze(i);if(t==jp||t==Dp)return!i.size;if(Qn(i))return!Or(i).length;for(var e in i)if(Rp.call(i,e))return!1;return!0}function Rt(i,t){return ls(i,t)}var kp="[object Number]";function ui(i){return typeof i=="number"||Nt(i)&&ee(i)==kp}var Bp=Rr("toLowerCase");function zp(i,t,e){for(var n=-1,s=i.length;++nt||r&&o&&l&&!a&&!c||n&&o&&l||!e&&l||!s)return 1;if(!n&&!r&&!c&&i=a)return l;var c=e[n];return l*(c=="desc"?-1:1)}}return i.index-t.index}function qp(i,t,e){t.length?t=fn(t,function(r){return bt(r)?function(o){return ss(o,r.length===1?r[0]:r)}:r}):t=[Ne];var n=-1;t=fn(t,pn(ai));var s=Op(i,function(r,o,a){var l=fn(t,function(c){return c(r)});return{criteria:l,index:++n,value:r}});return Fp(s,function(r,o){return Hp(r,o,e)})}var _o=Ie(function(i,t){if(i==null)return[];var e=t.length;return e>1&&Kn(i,t[0],t[1])?t=[]:e>2&&Kn(t[0],t[1],t[2])&&(t=[t[0]]),qp(i,Pn(t,1),[])}),Gp=4294967295,Up=Gp-1,Wp=Math.floor,Xp=Math.min;function Ho(i,t,e,n){var s=0,r=i==null?0:i.length;if(r===0)return 0;t=e(t);for(var o=t!==t,a=t===null,l=Dt(t),c=t===void 0;s>>1;function Zp(i,t,e){var n=0,s=i==null?n:i.length;if(typeof t=="number"&&t===t&&s<=Yp){for(;n>>1,o=i[r];o!==null&&!Dt(o)&&(e?o<=t:o=sm){var c=t?null:nm(i);if(c)return ri(c);o=!1,s=ii,l=new Ve}else l=t?[]:a;t:for(;++n{Array.isArray(n)?t.push(...n):t.push(n)}),t.some(n=>Xo(n))){const n=t.map(s=>Xo(s)?s:Promise.resolve(s!==!1));return Promise.all(n).then(s=>s.reduce((r,o)=>o!==!1&&r,!0))}return t.every(n=>n!==!1)}function fi(i,t){const e=[];for(let n=0;n(this.off(t,s),fi([e,n],r));return this.on(t,s,this)}off(t,e,n){if(!(t||e||n))return this.listeners={},this;const s=this.listeners;return(t?[t]:Object.keys(s)).forEach(o=>{const a=s[o];if(!!a){if(!(e||n)){delete s[o];return}for(let l=a.length-2;l>=0;l-=2)e&&a[l]!==e||n&&a[l+1]!==n||a.splice(l,2)}}),this}trigger(t,...e){let n=!0;if(t!=="*"){const r=this.listeners[t];r!=null&&(n=fi([...r],e))}const s=this.listeners["*"];return s!=null?Jo([n,fi([...s],[t,...e])]):n}emit(t,...e){return this.trigger(t,...e)}}function om(i,...t){t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(n=>{n!=="constructor"&&Object.defineProperty(i.prototype,n,Object.getOwnPropertyDescriptor(e.prototype,n))})})}const am=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,t){i.__proto__=t}||function(i,t){for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(i[e]=t[e])};function lm(i,t){am(i,t);function e(){this.constructor=i}i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}class cm{}const hm=/^\s*class\s+/.test(`${cm}`)||/^\s*class\s*\{/.test(`${class{}}`);function di(i,t){let e;return hm?e=class extends t{}:(e=function(){return t.apply(this,arguments)},lm(e,t)),Object.defineProperty(e,"name",{value:i}),e}function Yo(i){return i==="__proto__"}function gi(i,t,e="/"){let n;const s=Array.isArray(t)?t:t.split(e);if(s.length)for(n=i;s.length;){const r=s.shift();if(Object(n)===n&&r&&r in n)n=n[r];else return}return n}function Cn(i,t,e,n="/"){const s=Array.isArray(t)?t:t.split(n),r=s.pop();if(r&&!Yo(r)){let o=i;s.forEach(a=>{Yo(a)||(o[a]==null&&(o[a]={}),o=o[a])}),o[r]=e}return i}function Zo(i,t,e="/"){const n=Array.isArray(t)?t.slice():t.split(e),s=n.pop();if(s)if(n.length>0){const r=gi(i,n);r&&delete r[s]}else delete i[s];return i}class Pt extends rm{}(function(i){i.dispose=qt.dispose})(Pt||(Pt={})),om(Pt,qt);const Ko=i=>{const t=Object.create(null);return e=>t[e]||(t[e]=i(e))},Qo=Ko(i=>i.replace(/\B([A-Z])/g,"-$1").toLowerCase()),pi=Ko(i=>tm(rs(i)).replace(/ /g,""));function mi(i){let t=2166136261,e=!1,n=i;for(let s=0,r=n.length;s127&&!e&&(n=unescape(encodeURIComponent(n)),o=n.charCodeAt(s),e=!0),t^=o,t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24)}return t>>>0}function yi(){let i="";const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";for(let e=0,n=t.length;ee?a-e:1,h=t.length>e+a?e+a:t.length;s[0]=a;let u=a;for(let d=1;de)return;const f=n;n=s,s=f}const o=n[t.length];return o>e?void 0:o}function Wt(i){return typeof i=="string"&&i.slice(-1)==="%"}function Xt(i,t){if(i==null)return 0;let e;if(typeof i=="string"){if(e=parseFloat(i),Wt(i)&&(e/=100,Number.isFinite(e)))return e*t}else e=i;return Number.isFinite(e)?e>0&&e<1?e*t:e:0}function ne(i){if(typeof i=="object"){let e=0,n=0,s=0,r=0;return i.vertical!=null&&Number.isFinite(i.vertical)&&(n=r=i.vertical),i.horizontal!=null&&Number.isFinite(i.horizontal)&&(s=e=i.horizontal),i.left!=null&&Number.isFinite(i.left)&&(e=i.left),i.top!=null&&Number.isFinite(i.top)&&(n=i.top),i.right!=null&&Number.isFinite(i.right)&&(s=i.right),i.bottom!=null&&Number.isFinite(i.bottom)&&(r=i.bottom),{top:n,right:s,bottom:r,left:e}}let t=0;return i!=null&&Number.isFinite(i)&&(t=i),{top:t,right:t,bottom:t,left:t}}let bi=!1,ta=!1,ea=!1,na=!1,sa=!1,ia=!1,ra=!1,oa=!1,aa=!1,la=!1,ca=!1,ha=!1,ua=!1,fa=!1,da=!1,ga=!1;if(typeof navigator=="object"){const i=navigator.userAgent;bi=i.indexOf("Macintosh")>=0,ta=!!i.match(/(iPad|iPhone|iPod)/g),ea=i.indexOf("Windows")>=0,na=i.indexOf("MSIE")>=0,sa=!!i.match(/Trident\/7\./),ia=!!i.match(/Edge\//),ra=i.indexOf("Mozilla/")>=0&&i.indexOf("MSIE")<0&&i.indexOf("Edge/")<0,aa=i.indexOf("Chrome/")>=0&&i.indexOf("Edge/")<0,la=i.indexOf("Opera/")>=0||i.indexOf("OPR/")>=0,ca=i.indexOf("Firefox/")>=0,ha=i.indexOf("AppleWebKit/")>=0&&i.indexOf("Chrome/")<0&&i.indexOf("Edge/")<0,typeof document=="object"&&(ga=!document.createElementNS||`${document.createElementNS("http://www.w3.org/2000/svg","foreignObject")}`!="[object SVGForeignObjectElement]"||i.indexOf("Opera/")>=0)}if(typeof window=="object"&&(oa=window.chrome!=null&&window.chrome.app!=null&&window.chrome.app.runtime!=null,fa=window.PointerEvent!=null&&!bi),typeof document=="object"){ua="ontouchstart"in document.documentElement;try{const i=Object.defineProperty({},"passive",{get(){da=!0}}),t=document.createElement("div");t.addEventListener&&t.addEventListener("click",()=>{},i)}catch(i){}}var se;(function(i){i.IS_MAC=bi,i.IS_IOS=ta,i.IS_WINDOWS=ea,i.IS_IE=na,i.IS_IE11=sa,i.IS_EDGE=ia,i.IS_NETSCAPE=ra,i.IS_CHROME_APP=oa,i.IS_CHROME=aa,i.IS_OPERA=la,i.IS_FIREFOX=ca,i.IS_SAFARI=ha,i.SUPPORT_TOUCH=ua,i.SUPPORT_POINTER=fa,i.SUPPORT_PASSIVE=da,i.NO_FOREIGNOBJECT=ga,i.SUPPORT_FOREIGNOBJECT=!i.NO_FOREIGNOBJECT})(se||(se={})),function(i){function t(){const r=window.module;return r!=null&&r.hot!=null&&r.hot.status!=null?r.hot.status():"unkonwn"}i.getHMRStatus=t;function e(){return t()==="apply"}i.isApplyingHMR=e;const n={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};function s(r){const o=document.createElement(n[r]||"div"),a=`on${r}`;let l=a in o;return l||(o.setAttribute(a,"return;"),l=typeof o[a]=="function"),l}i.isEventSupported=s}(se||(se={}));const xi=/[\t\r\n\f]/g,vi=/\S+/g,Fe=i=>` ${i} `;function _e(i){return i&&i.getAttribute&&i.getAttribute("class")||""}function He(i,t){if(i==null||t==null)return!1;const e=Fe(_e(i)),n=Fe(t);return i.nodeType===1?e.replace(xi," ").includes(n):!1}function V(i,t){if(!(i==null||t==null)){if(typeof t=="function")return V(i,t(_e(i)));if(typeof t=="string"&&i.nodeType===1){const e=t.match(vi)||[],n=Fe(_e(i)).replace(xi," ");let s=e.reduce((r,o)=>r.indexOf(Fe(o))<0?`${r}${o} `:r,n);s=s.trim(),n!==s&&i.setAttribute("class",s)}}}function St(i,t){if(i!=null){if(typeof t=="function")return St(i,t(_e(i)));if((!t||typeof t=="string")&&i.nodeType===1){const e=(t||"").match(vi)||[],n=Fe(_e(i)).replace(xi," ");let s=e.reduce((r,o)=>{const a=Fe(o);return r.indexOf(a)>-1?r.replace(a," "):r},n);s=t?s.trim():"",n!==s&&i.setAttribute("class",s)}}}function pa(i,t,e){if(!(i==null||t==null)){if(e!=null&&typeof t=="string"){e?V(i,t):St(i,t);return}if(typeof t=="function")return pa(i,t(_e(i),e),e);typeof t=="string"&&(t.match(vi)||[]).forEach(s=>{He(i,s)?St(i,s):V(i,s)})}}let ma=0;function dm(){return ma+=1,`v${ma}`}function wi(i){return(i.id==null||i.id==="")&&(i.id=dm()),i.id}function ie(i){return i==null?!1:typeof i.getScreenCTM=="function"&&i instanceof SVGElement}const ut={svg:"http://www.w3.org/2000/svg",xmlns:"http://www.w3.org/2000/xmlns/",xml:"http://www.w3.org/XML/1998/namespace",xlink:"http://www.w3.org/1999/xlink",xhtml:"http://www.w3.org/1999/xhtml"},ya="1.1";function ba(i,t=document){return t.createElement(i)}function Pi(i,t=ut.xhtml,e=document){return e.createElementNS(t,i)}function Jt(i,t=document){return Pi(i,ut.svg,t)}function fs(i){if(i){const e=`${i}`,{documentElement:n}=gm(e,{async:!1});return n}const t=document.createElementNS(ut.svg,"svg");return t.setAttributeNS(ut.xmlns,"xmlns:xlink",ut.xlink),t.setAttribute("version",ya),t}function gm(i,t={}){let e;try{const n=new DOMParser;if(t.async!=null){const s=n;s.async=t.async}e=n.parseFromString(i,t.mimeType||"text/xml")}catch(n){e=void 0}if(!e||e.getElementsByTagName("parsererror").length)throw new Error(`Invalid XML: ${i}`);return e}function pm(i,t=!0){const e=i.nodeName;return t?e.toLowerCase():e.toUpperCase()}function Ai(i){let t=0,e=i.previousSibling;for(;e;)e.nodeType===1&&(t+=1),e=e.previousSibling;return t}function mm(i,t){return i.querySelectorAll(t)}function ym(i,t){return i.querySelector(t)}function xa(i,t,e){const n=i.ownerSVGElement;let s=i.parentNode;for(;s&&s!==e&&s!==n;){if(He(s,t))return s;s=s.parentNode}return null}function Ci(i,t){const e=t&&t.parentNode;return i===e||!!(e&&e.nodeType===1&&i.compareDocumentPosition(e)&16)}function qe(i){i&&(Array.isArray(i)?i:[i]).forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)})}function Sn(i){for(;i.firstChild;)i.removeChild(i.firstChild)}function On(i,t){(Array.isArray(t)?t:[t]).forEach(n=>{n!=null&&i.appendChild(n)})}function bm(i,t){const e=i.firstChild;return e?Si(e,t):On(i,t)}function Si(i,t){const e=i.parentNode;e&&(Array.isArray(t)?t:[t]).forEach(s=>{s!=null&&e.insertBefore(s,i)})}function xm(i,t){t!=null&&t.appendChild(i)}function va(i){try{return i instanceof HTMLElement}catch(t){return typeof i=="object"&&i.nodeType===1&&typeof i.style=="object"&&typeof i.ownerDocument=="object"}}const wa=["viewBox","attributeName","attributeType","repeatCount"];function vm(i,t){return i.getAttribute(t)}function Pa(i,t){const e=Ca(t);e.ns?i.hasAttributeNS(e.ns,e.local)&&i.removeAttributeNS(e.ns,e.local):i.hasAttribute(t)&&i.removeAttribute(t)}function Oi(i,t,e){if(e==null)return Pa(i,t);const n=Ca(t);n.ns&&typeof e=="string"?i.setAttributeNS(n.ns,t,e):t==="id"?i.id=`${e}`:i.setAttribute(t,`${e}`)}function Aa(i,t){Object.keys(t).forEach(e=>{Oi(i,e,t[e])})}function H(i,t,e){if(t==null){const n=i.attributes,s={};for(let r=0;r{const n=wa.includes(e)?e:Qo(e);t[n]=i[e]}),t}function ds(i){const t={};return i.split(";").forEach(n=>{const s=n.trim();if(s){const r=s.split("=");r.length&&(t[r[0].trim()]=r[1]?r[1].trim():"")}}),t}function Ei(i,t){return Object.keys(t).forEach(e=>{if(e==="class")i[e]=i[e]?`${i[e]} ${t[e]}`:t[e];else if(e==="style"){const n=typeof i[e]=="object",s=typeof t[e]=="object";let r,o;n&&s?(r=i[e],o=t[e]):n?(r=i[e],o=ds(t[e])):s?(r=ds(i[e]),o=t[e]):(r=ds(i[e]),o=ds(t[e])),i[e]=Ei(r,o)}else i[e]=t[e]}),i}function wm(i,t,e={}){const n=e.offset||0,s=[],r=[];let o,a,l=null;for(let c=0;c=d&&ch(null,c));return}const u=()=>{h(new Error(`Failed to load image: ${c}`))},f=window.FileReader?g=>{if(g.status===200){const p=new FileReader;p.onload=m=>{const y=m.target.result;h(null,y)},p.onerror=u,p.readAsDataURL(g.response)}else u()}:g=>{const p=m=>{const y=32768,x=[];for(let b=0;bf(d)),d.send()}i.imageToDataUri=e;function n(c){let h=c.replace(/\s/g,"");h=decodeURIComponent(h);const u=h.indexOf(","),f=h.slice(0,u),d=f.split(":")[1].split(";")[0],g=h.slice(u+1);let p;f.indexOf("base64")>=0?p=atob(g):p=unescape(encodeURIComponent(g));const m=new Uint8Array(p.length);for(let y=0;y]*viewBox\s*=\s*(["']?)(.+?)\1[^>]*>/i);return h&&h[2]?h[2].replace(/\s+/," ").split(" "):null}function a(c){const h=parseFloat(c);return Number.isNaN(h)?null:h}function l(c,h={}){let u=null;const f=b=>(u==null&&(u=o(c)),u!=null?a(u[b]):null),d=b=>{const w=c.match(b);return w&&w[2]?a(w[2]):null};let g=h.width;if(g==null&&(g=d(/]*width\s*=\s*(["']?)(.+?)\1[^>]*>/i)),g==null&&(g=f(2)),g==null)throw new Error("Can not parse width from svg string");let p=h.height;if(p==null&&(p=d(/]*height\s*=\s*(["']?)(.+?)\1[^>]*>/i)),p==null&&(p=f(3)),p==null)throw new Error("Can not parse height from svg string");return`data:image/svg+xml,${encodeURIComponent(c).replace(/'/g,"%27").replace(/"/g,"%22")}`}i.svgToDataUrl=l})(Mi||(Mi={}));let ve;const Am={px(i){return i},mm(i){return ve*i},cm(i){return ve*i*10},in(i){return ve*i*25.4},pt(i){return ve*(25.4*i/72)},pc(i){return ve*(25.4*i/6)}};var Sa;(function(i){function t(n,s,r){const o=document.createElement("div"),a=o.style;a.display="inline-block",a.position="absolute",a.left="-15000px",a.top="-15000px",a.width=n+(r||"px"),a.height=s+(r||"px"),document.body.appendChild(o);const l=o.getBoundingClientRect(),c={width:l.width||0,height:l.height||0};return document.body.removeChild(o),c}i.measure=t;function e(n,s){ve==null&&(ve=t("1","1","mm").width);const r=s?Am[s]:null;return r?r(n):n}i.toPx=e})(Sa||(Sa={}));const Cm=/-(.)/g;function Sm(i){return i.replace(Cm,(t,e)=>e.toUpperCase())}const Ti={},Oa=["webkit","ms","moz","o"],Ea=document?document.createElement("div").style:{};function Om(i){for(let t=0;ts(a)):[s(o)]}i.toNodes=r})($||($={}));const Na=document.createElement("canvas").getContext("2d");function jm(i,t){const e=$.create(t),n=$.create("textPath"),s=i.d;if(s&&i["xlink:href"]===void 0){const r=$.create("path").attr("d",s).appendTo(e.defs());n.attr("xlink:href",`#${r.id}`)}return typeof i=="object"&&n.attr(i),n.node}function Dm(i,t,e){const n=e.eol,s=e.baseSize,r=e.lineHeight;let o=0,a;const l={},c=t.length-1;for(let h=0;h<=c;h+=1){let u=t[h],f=null;if(typeof u=="object"){const d=u.attrs,g=$.create("tspan",d);a=g.node;let p=u.t;n&&h===c&&(p+=n),a.textContent=p;const m=d.class;m&&g.addClass(m),e.includeAnnotationIndices&&g.attr("annotations",u.annotations.join(",")),f=parseFloat(d["font-size"]),f===void 0&&(f=s),f&&f>o&&(o=f)}else n&&h===c&&(u+=n),a=document.createTextNode(u||" "),s&&s>o&&(o=s);i.appendChild(a)}return o&&(l.maxFontSize=o),r?l.lineHeight=r:o&&(l.lineHeight=o*1.2),l}const La=/em$/;function gs(i,t){const e=parseFloat(i);return La.test(i)?e*t:e}function $m(i,t,e,n){if(!Array.isArray(t))return 0;const s=t.length;if(!s)return 0;let r=t[0];const o=gs(r.maxFontSize,e)||e;let a=0;const l=gs(n,e);for(let u=1;u0&&N.setAttribute("dy",m),(S>0||s)&&N.setAttribute("x",a),N.className.baseVal=E,p.appendChild(N),y+=T.length+1}if(o)if(c)m=$m(r,w,g,f);else if(r==="top")m="0.8em";else{let S;switch(P>0?(S=parseFloat(f)||1,S*=P,La.test(f)||(S/=g)):S=0,r){case"middle":m=`${.3-S/2}em`;break;case"bottom":m=`${-S-.3}em`;break}}else r===0?m="0em":r?m=r:(m=0,i.getAttribute("y")==null&&i.setAttribute("y",`${x||"0.8em"}`));p.firstChild.setAttribute("dy",m),i.appendChild(p)}function Mn(i,t={}){if(!i)return{width:0};const e=[],n=t["font-size"]?`${parseFloat(t["font-size"])}px`:"14px";return e.push(t["font-style"]||"normal"),e.push(t["font-variant"]||"normal"),e.push(t["font-weight"]||400),e.push(n),e.push(t["font-family"]||"sans-serif"),Na.font=e.join(" "),Na.measureText(i)}function ja(i,t,e,n={}){if(t>=e)return[i,""];const s=i.length,r={};let o=Math.round(t/e*s-1);for(o<0&&(o=0);o>=0&&ot)o-=1;else if(h<=t)o+=1;else break}return[i.slice(0,o),i.slice(o)]}function Rm(i,t,e={},n={}){const s=t.width,r=t.height,o=n.eol||` +`,{width:a}=Mn(i,e);if(as)if(m===u-1){const[x]=ja(f,s-p,d,e);l.push(g?`${x}${g}`:x)}else{const[x,b]=ja(f,s,d,e);l.push(x),f=b,d=Mn(f,e).width}else{l.push(f);break}return l.join(o)}const Ni=.551784;function mt(i,t,e=NaN){const n=i.getAttribute(t);if(n==null)return e;const s=parseFloat(n);return Number.isNaN(s)?e:s}function km(i,t=1){const e=i.getTotalLength(),n=[];let s=0,r;for(;s`${e.x} ${e.y}`).join(" L")}`}function ps(i){const t=[],e=i.points;if(e)for(let n=0,s=e.numberOfItems;n=0){const o=Nn(i),a=Xm(o);t=[a.translateX,a.translateY],e=[a.rotation],n=[a.scaleX,a.scaleY];const l=[];(t[0]!==0||t[1]!==0)&&l.push(`translate(${t.join(",")})`),(n[0]!==1||n[1]!==1)&&l.push(`scale(${n.join(",")})`),e[0]!==0&&l.push(`rotate(${e[0]})`),i=l.join(" ")}else{const o=i.match(/translate\((.*?)\)/);o&&(t=o[1].split(r));const a=i.match(/rotate\((.*?)\)/);a&&(e=a[1].split(r));const l=i.match(/scale\((.*?)\)/);l&&(n=l[1].split(r))}}const s=n&&n[0]?parseFloat(n[0]):1;return{raw:i||"",translation:{tx:t&&t[0]?parseInt(t[0],10):0,ty:t&&t[1]?parseInt(t[1],10):0},rotation:{angle:e&&e[0]?parseInt(e[0],10):0,cx:e&&e[1]?parseInt(e[1],10):void 0,cy:e&&e[2]?parseInt(e[2],10):void 0},scale:{sx:s,sy:n&&n[1]?parseFloat(n[1]):s}}}function Li(i,t){const e=t.x*i.a+t.y*i.c+0,n=t.x*i.b+t.y*i.d+0;return{x:e,y:n}}function Xm(i){const t=Li(i,{x:0,y:1}),e=Li(i,{x:1,y:0}),n=180/Math.PI*Math.atan2(t.y,t.x)-90,s=180/Math.PI*Math.atan2(e.y,e.x);return{skewX:n,skewY:s,translateX:i.e,translateY:i.f,scaleX:Math.sqrt(i.a*i.a+i.b*i.b),scaleY:Math.sqrt(i.c*i.c+i.d*i.d),rotation:n}}function Jm(i){let t,e,n,s;return i?(t=i.a==null?1:i.a,s=i.d==null?1:i.d,e=i.b,n=i.c):t=s=1,{sx:e?Math.sqrt(t*t+e*e):t,sy:n?Math.sqrt(n*n+s*s):s}}function Ym(i){let t={x:0,y:1};i&&(t=Li(i,t));const e=180*Math.atan2(t.y,t.x)/Math.PI%360-90;return{angle:e%360+(e<0?360:0)}}function Zm(i){return{tx:i&&i.e||0,ty:i&&i.f||0}}function We(i,t,e={}){if(t==null)return Nn(H(i,"transform"));if(e.absolute){i.setAttribute("transform",Ue(t));return}const n=i.transform,s=Tn(t);n.baseVal.appendItem(s)}function Ba(i,t,e=0,n={}){let s=H(i,"transform");const r=ys(s);if(t==null)return r.translation;s=r.raw,s=s.replace(/translate\([^)]*\)/g,"").trim();const o=n.absolute?t:r.translation.tx+t,a=n.absolute?e:r.translation.ty+e,l=`translate(${o},${a})`;i.setAttribute("transform",`${l} ${s}`.trim())}function Ii(i,t,e,n,s={}){let r=H(i,"transform");const o=ys(r);if(t==null)return o.rotation;r=o.raw,r=r.replace(/rotate\([^)]*\)/g,"").trim(),t%=360;const a=s.absolute?t:o.rotation.angle+t,l=e!=null&&n!=null?`,${e},${n}`:"",c=`rotate(${a}${l})`;i.setAttribute("transform",`${r} ${c}`.trim())}function ji(i,t,e){let n=H(i,"transform");const s=ys(n);if(t==null)return s.scale;e=e==null?t:e,n=s.raw,n=n.replace(/scale\([^)]*\)/g,"").trim();const r=`scale(${t},${e})`;i.setAttribute("transform",`${n} ${r}`.trim())}function Ln(i,t){if(ie(t)&&ie(i)){const e=t.getScreenCTM(),n=i.getScreenCTM();if(e&&n)return e.inverse().multiply(n)}return ft()}function Km(i,t){let e=ft();if(ie(t)&&ie(i)){let n=i;const s=[];for(;n&&n!==t;){const r=n.getAttribute("transform")||null,o=Nn(r);s.push(o),n=n.parentNode}s.reverse().forEach(r=>{e=e.multiply(r)})}return e}function Qm(i,t,e){const n=i instanceof SVGSVGElement?i:i.ownerSVGElement,s=n.createSVGPoint();s.x=t,s.y=e;try{const r=n.getScreenCTM(),o=s.matrixTransform(r.inverse()),a=Ln(i,n).inverse();return o.matrixTransform(a)}catch(r){return s}}var Ot;(function(i){const t={};function e(r){return t[r]||{}}i.get=e;function n(r,o){t[r]=o}i.register=n;function s(r){delete t[r]}i.unregister=s})(Ot||(Ot={}));var Pe;(function(i){const t=new WeakMap;function e(r){return t.has(r)||t.set(r,{events:Object.create(null)}),t.get(r)}i.ensure=e;function n(r){return t.get(r)}i.get=n;function s(r){return t.delete(r)}i.remove=s})(Pe||(Pe={}));var B;(function(i){i.returnTrue=()=>!0,i.returnFalse=()=>!1;function t(s){s.stopPropagation()}i.stopPropagationCallback=t;function e(s,r,o){s.addEventListener!=null&&s.addEventListener(r,o)}i.addEventListener=e;function n(s,r,o){s.removeEventListener!=null&&s.removeEventListener(r,o)}i.removeEventListener=n})(B||(B={})),function(i){const t=/[^\x20\t\r\n\f]+/g,e=/^([^.]*)(?:\.(.+)|)/;function n(a){return(a||"").match(t)||[""]}i.splitType=n;function s(a){const l=e.exec(a)||[];return{originType:l[1]?l[1].trim():l[1],namespaces:l[2]?l[2].split(".").map(c=>c.trim()).sort():[]}}i.normalizeType=s;function r(a){return a.nodeType===1||a.nodeType===9||!+a.nodeType}i.isValidTarget=r;function o(a,l){if(l){const c=a;return c.querySelector!=null&&c.querySelector(l)!=null}return!0}i.isValidSelector=o}(B||(B={})),function(i){let t=0;const e=new WeakMap;function n(a){return e.has(a)||(e.set(a,t),t+=1),e.get(a)}i.ensureHandlerId=n;function s(a){return e.get(a)}i.getHandlerId=s;function r(a){return e.delete(a)}i.removeHandlerId=r;function o(a,l){return e.set(a,l)}i.setHandlerId=o}(B||(B={})),function(i){function t(e,n){const s=[],r=Pe.get(e),o=r&&r.events&&r.events[n.type],a=o&&o.handlers||[],l=o?o.delegateCount:0;if(l>0&&!(n.type==="click"&&typeof n.button=="number"&&n.button>=1)){for(let c=n.target;c!==e;c=c.parentNode||e)if(c.nodeType===1&&!(n.type==="click"&&c.disabled===!0)){const h=[],u={};for(let f=0;f{m.push(y)}),u[g]=m.includes(c)}u[g]&&h.push(d)}h.length&&s.push({elem:c,handlers:h})}}return li.addProperty(e,t[e]))}(kt||(kt={})),function(i){Ot.register("load",{noBubble:!0})}(),function(i){Ot.register("beforeunload",{postDispatch(t,e){e.result!==void 0&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}})}(),function(i){Ot.register("mouseenter",{delegateType:"mouseover",bindType:"mouseover",handle(t,e){let n;const s=e.relatedTarget,r=e.handleObj;return(!s||s!==t&&!B.contains(t,s))&&(e.type=r.originType,n=r.handler.call(t,e),e.type="mouseover"),n}}),Ot.register("mouseleave",{delegateType:"mouseout",bindType:"mouseout",handle(t,e){let n;const s=e.relatedTarget,r=e.handleObj;return(!s||s!==t&&!B.contains(t,s))&&(e.type=r.originType,n=r.handler.call(t,e),e.type="mouseout"),n}})}();var ty=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const{originType:m,namespaces:y}=B.normalizeType(p);if(!m)return;let x=m,b=Ot.get(x);x=(h?b.delegateType:b.bindType)||x,b=Ot.get(x);const w=Object.assign({type:x,originType:m,data:c,selector:h,guid:g,handler:l,namespace:y.join(".")},u),P=f.events;let A=P[x];A||(A=P[x]={handlers:[],delegateCount:0},(!b.setup||b.setup(o,c,y,d)===!1)&&B.addEventListener(o,x,d)),b.add&&(B.removeHandlerId(w.handler),b.add(o,w),B.setHandlerId(w.handler,g)),h?(A.handlers.splice(A.delegateCount,0,w),A.delegateCount+=1):A.handlers.push(w)})}i.on=e;function n(o,a,l,c,h){const u=Pe.get(o);if(!u)return;const f=u.events;!f||(B.splitType(a).forEach(d=>{const{originType:g,namespaces:p}=B.normalizeType(d);if(!g){Object.keys(f).forEach(P=>{n(o,P+d,l,c,!0)});return}let m=g;const y=Ot.get(m);m=(c?y.delegateType:y.bindType)||m;const x=f[m]||{},b=p.length>0?new RegExp(`(^|\\.)${p.join("\\.(?:.*\\.|)")}(\\.|$)`):null,w=x.handlers.length;for(let P=x.handlers.length-1;P>=0;P-=1){const A=x.handlers[P];(h||g===A.originType)&&(!l||B.getHandlerId(l)===A.guid)&&(b==null||A.namespace&&b.test(A.namespace))&&(c==null||c===A.selector||c==="**"&&A.selector)&&(x.handlers.splice(P,1),A.selector&&(x.delegateCount-=1),y.remove&&y.remove(o,A))}w&&x.handlers.length===0&&((!y.teardown||y.teardown(o,p,u.handler)===!1)&&B.removeEventListener(o,m,u.handler),delete f[m])}),Object.keys(f).length===0&&Pe.remove(o))}i.off=n;function s(o,a,...l){const c=kt.create(a);c.delegateTarget=o;const h=Ot.get(c.type);if(h.preDispatch&&h.preDispatch(o,c)===!1)return;const u=B.getHandlerQueue(o,c);for(let f=0,d=u.length;f-1&&(f=u.split("."),u=f.shift(),f.sort());const g=u.indexOf(":")<0&&`on${u}`;h=o instanceof kt?o:new kt(u,typeof o=="object"?o:null),h.namespace=f.join("."),h.rnamespace=h.namespace?new RegExp(`(^|\\.)${f.join("\\.(?:.*\\.|)")}(\\.|$)`):null,h.result=void 0,h.target||(h.target=d);const p=[h];Array.isArray(a)?p.push(...a):p.push(a);const m=Ot.get(u);if(!c&&m.trigger&&m.trigger(d,h,a)===!1)return;let y;const x=[d];if(!c&&!m.noBubble&&!B.isWindow(d)){y=m.delegateType||u;let w=d,P=d.parentNode;for(;P!=null;)x.push(P),w=P,P=P.parentNode;const A=d.ownerDocument||document;if(w===A){const S=w.defaultView||w.parentWindow||window;x.push(S)}}let b=d;for(let w=0,P=x.length;w1?y:m.bindType||u;const S=Pe.get(A);S&&S.events[h.type]&&S.handler&&S.handler.call(A,...p);const E=g&&A[g]||null;E&&B.isValidTarget(A)&&(h.result=E.call(A,...p),h.result===!1&&h.preventDefault())}if(h.type=u,!c&&!h.isDefaultPrevented()){const w=m.preventDefault;if((w==null||w(x.pop(),h,a)===!1)&&B.isValidTarget(d)&&g&&typeof d[u]=="function"&&!B.isWindow(d)){const P=d[g];P&&(d[g]=null),t=u,h.isPropagationStopped()&&b.addEventListener(u,B.stopPropagationCallback),d[u](),h.isPropagationStopped()&&b.removeEventListener(u,B.stopPropagationCallback),t=void 0,P&&(d[g]=P)}}return h.result}i.trigger=r})(In||(In={}));var vt;(function(i){function t(r,o,a,l,c){return jn.on(r,o,a,l,c),r}i.on=t;function e(r,o,a,l,c){return jn.on(r,o,a,l,c,!0),r}i.once=e;function n(r,o,a,l){return jn.off(r,o,a,l),r}i.off=n;function s(r,o,a,l){return In.trigger(o,a,r,l),r}i.trigger=s})(vt||(vt={}));var jn;(function(i){function t(n,s,r,o,a,l){if(typeof s=="object"){typeof r!="string"&&(o=o||r,r=void 0),Object.keys(s).forEach(c=>t(n,c,r,o,s[c],l));return}if(o==null&&a==null?(a=r,o=r=void 0):a==null&&(typeof r=="string"?(a=o,o=void 0):(a=o,o=r,r=void 0)),a===!1)a=B.returnFalse;else if(!a)return;if(l){const c=a;a=function(h,...u){return i.off(n,h),c.call(this,h,...u)},B.setHandlerId(a,B.ensureHandlerId(c))}In.on(n,s,a,o,r)}i.on=t;function e(n,s,r,o){const a=s;if(a&&a.preventDefault!=null&&a.handleObj!=null){const l=a.handleObj;e(a.delegateTarget,l.namespace?`${l.originType}.${l.namespace}`:l.originType,l.selector,l.handler);return}if(typeof s=="object"){const l=s;Object.keys(l).forEach(c=>e(n,c,r,l[c]));return}(r===!1||typeof r=="function")&&(o=r,r=void 0),o===!1&&(o=B.returnFalse),In.off(n,s,o,r)}i.off=e})(jn||(jn={}));class za{constructor(t,e,n){this.animationFrameId=0,this.deltaX=0,this.deltaY=0,this.eventName=se.isEventSupported("wheel")?"wheel":"mousewheel",this.target=t,this.onWheelCallback=e,this.onWheelGuard=n,this.onWheel=this.onWheel.bind(this),this.didWheel=this.didWheel.bind(this)}enable(){this.target.addEventListener(this.eventName,this.onWheel,{passive:!1})}disable(){this.target.removeEventListener(this.eventName,this.onWheel)}onWheel(t){if(this.onWheelGuard!=null&&!this.onWheelGuard(t))return;this.deltaX+=t.deltaX,this.deltaY+=t.deltaY,t.preventDefault();let e;(this.deltaX!==0||this.deltaY!==0)&&(t.stopPropagation(),e=!0),e===!0&&this.animationFrameId===0&&(this.animationFrameId=requestAnimationFrame(()=>{this.didWheel(t)}))}didWheel(t){this.animationFrameId=0,this.onWheelCallback(t,this.deltaX,this.deltaY),this.deltaX=0,this.deltaY=0}}function Va(i,t=60){let e=null;return(...n)=>{e&&clearTimeout(e),e=window.setTimeout(()=>{i.apply(this,n)},t)}}function ey(i){let t=null,e=[];const n=()=>{if(getComputedStyle(i).position==="static"){const c=i.style;c.position="relative"}const l=document.createElement("object");return l.onload=()=>{l.contentDocument.defaultView.addEventListener("resize",s),s()},l.style.display="block",l.style.position="absolute",l.style.top="0",l.style.left="0",l.style.height="100%",l.style.width="100%",l.style.overflow="hidden",l.style.pointerEvents="none",l.style.zIndex="-1",l.style.opacity="0",l.setAttribute("tabindex","-1"),l.type="text/html",i.appendChild(l),l.data="about:blank",l},s=Va(()=>{e.forEach(l=>l(i))}),r=l=>{t||(t=n()),e.indexOf(l)===-1&&e.push(l)},o=()=>{t&&t.parentNode&&(t.contentDocument&&t.contentDocument.defaultView.removeEventListener("resize",s),t.parentNode.removeChild(t),t=null,e=[])};return{element:i,bind:r,destroy:o,unbind:l=>{const c=e.indexOf(l);c!==-1&&e.splice(c,1),e.length===0&&t&&o()}}}function ny(i){let t=null,e=[];const n=Va(()=>{e.forEach(l=>{l(i)})}),s=()=>{const l=new ResizeObserver(n);return l.observe(i),n(),l},r=l=>{t||(t=s()),e.indexOf(l)===-1&&e.push(l)},o=()=>{t&&(t.disconnect(),e=[],t=null)};return{element:i,bind:r,destroy:o,unbind:l=>{const c=e.indexOf(l);c!==-1&&e.splice(c,1),e.length===0&&t&&o()}}}const sy=typeof ResizeObserver!="undefined"?ny:ey;var bs;(function(i){const t=new WeakMap;function e(s){let r=t.get(s);return r||(r=sy(s),t.set(s,r),r)}function n(s){s.destroy(),t.delete(s.element)}i.bind=(s,r)=>{const o=e(s);return o.bind(r),()=>o.unbind(r)},i.clear=s=>{const r=e(s);n(r)}})(bs||(bs={}));class Dn{constructor(t={}){this.comparator=t.comparator||Dn.defaultComparator,this.index={},this.data=t.data||[],this.heapify()}isEmpty(){return this.data.length===0}insert(t,e,n){const s={priority:t,value:e},r=this.data.length-1;return n&&(s.id=n,this.index[n]=r),this.data.push(s),this.bubbleUp(r),this}peek(){return this.data[0]?this.data[0].value:null}peekPriority(){return this.data[0]?this.data[0].priority:null}updatePriority(t,e){const n=this.index[t];if(typeof n=="undefined")throw new Error(`Node with id '${t}' was not found in the heap.`);const s=this.data,r=s[n].priority,o=this.comparator(e,r);o<0?(s[n].priority=e,this.bubbleUp(n)):o>0&&(s[n].priority=e,this.bubbleDown(n))}remove(){const t=this.data,e=t[0],n=t.pop();return delete this.index[t.length],t.length>0&&(t[0]=n,n.id&&(this.index[n.id]=0),this.bubbleDown(0)),e?e.value:null}heapify(){for(let t=0;t0&&(s=r-1>>>1,this.comparator(e[r].priority,e[s].priority)<0);){n=e[s],e[s]=e[r];let o=e[r].id;o!=null&&(this.index[o]=s),e[r]=n,o=e[r].id,o!=null&&(this.index[o]=r),r=s}}bubbleDown(t){const e=this.data,n=e.length-1;let s=t;for(;;){const r=(s<<1)+1,o=r+1;let a=s;if(r<=n&&this.comparator(e[r].priority,e[a].priority)<0&&(a=r),o<=n&&this.comparator(e[o].priority,e[a].priority)<0&&(a=o),a!==s){const l=e[a];e[a]=e[s];let c=e[s].id;c!=null&&(this.index[c]=a),e[s]=l,c=e[s].id,c!=null&&(this.index[c]=s),s=a}else break}}}(function(i){i.defaultComparator=(t,e)=>t-e})(Dn||(Dn={}));var Di;(function(i){function t(e,n,s=(r,o)=>1){const r={},o={},a={},l=new Dn;for(r[n]=0,Object.keys(e).forEach(c=>{c!==n&&(r[c]=Infinity),l.insert(r[c],c,c)});!l.isEmpty();){const c=l.remove();a[c]=!0;const h=e[c]||[];for(let u=0;u{const n=this[e].toString(16);return n.length<2?`0${n}`:n}).join("")}`}toRGBA(){return this.toArray()}toHSLA(){return Yt.rgba2hsla(this.r,this.g,this.b,this.a)}toCSS(t){const e=`${this.r},${this.g},${this.b},`;return t?`rgb(${e})`:`rgba(${e},${this.a})`}toGrey(){return Yt.makeGrey(Math.round((this.r+this.g+this.b)/3),this.a)}toArray(){return[this.r,this.g,this.b,this.a]}toString(){return this.toCSS()}}(function(i){function t(b){return new i(b)}i.fromArray=t;function e(b){return new i([...g(b),1])}i.fromHex=e;function n(b){const w=b.toLowerCase().match(/^rgba?\(([\s.,0-9]+)\)/);if(w){const P=w[1].split(/\s*,\s*/).map(A=>parseInt(A,10));return new i(P)}return null}i.fromRGBA=n;function s(b,w,P){P<0&&++P,P>1&&--P;const A=6*P;return A<1?b+(w-b)*A:2*P<1?w:3*P<2?b+(w-b)*(2/3-P)*6:b}function r(b){const w=b.toLowerCase().match(/^hsla?\(([\s.,0-9]+)\)/);if(w){const P=w[2].split(/\s*,\s*/),A=(parseFloat(P[0])%360+360)%360/360,S=parseFloat(P[1])/100,E=parseFloat(P[2])/100,N=P[3]==null?1:parseInt(P[3],10);return new i(c(A,S,E,N))}return null}i.fromHSLA=r;function o(b){if(b.startsWith("#"))return e(b);if(b.startsWith("rgb"))return n(b);const w=i.named[b];return w?e(w):r(b)}i.fromString=o;function a(b,w){return i.fromArray([b,b,b,w])}i.makeGrey=a;function l(b,w,P,A){const S=Array.isArray(b)?b[0]:b,E=Array.isArray(b)?b[1]:w,N=Array.isArray(b)?b[2]:P,L=Array.isArray(b)?b[3]:A,T=Math.max(S,E,N),j=Math.min(S,E,N),Q=(T+j)/2;let F=0,C=0;if(j!==T){const O=T-j;switch(C=Q>.5?O/(2-T-j):O/(T+j),T){case S:F=(E-N)/O+(E186?"#000000":"#ffffff":`${N?"#":""}${p(255-L,255-T,255-j)}`}const P=b[0],A=b[1],S=b[2],E=b[3];return w?P*.299+A*.587+S*.114>186?[0,0,0,E]:[255,255,255,E]:[255-P,255-A,255-S,E]}i.invert=d;function g(b){const w=b.indexOf("#")===0?b:`#${b}`;let P=Number(`0x${w.substr(1)}`);if(!(w.length===4||w.length===7)||Number.isNaN(P))throw new Error("Invalid hex color.");const A=w.length===4?4:8,S=(1<{const N=P&S;return P>>=A,A===4?17*N:N});return[E[2],E[1],E[0]]}function p(b,w,P){const A=S=>S.length<2?`0${S}`:S;return`${A(b.toString(16))}${A(w.toString(16))}${A(P.toString(16))}`}function m(b,w){return x(b,w)}i.lighten=m;function y(b,w){return x(b,-w)}i.darken=y;function x(b,w){if(typeof b=="string"){const S=b[0]==="#",E=parseInt(S?b.substr(1):b,16),N=Ct((E>>16)+w,0,255),L=Ct((E>>8&255)+w,0,255),T=Ct((E&255)+w,0,255);return`${S?"#":""}${(T|L<<8|N<<16).toString(16)}`}const P=p(b[0],b[1],b[2]),A=g(x(P,w));return[A[0],A[1],A[2],b[3]]}})(Yt||(Yt={})),function(i){i.named={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",burntsienna:"#ea7e5d",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}}(Yt||(Yt={}));class $i{constructor(){this.clear()}clear(){this.map=new WeakMap,this.arr=[]}has(t){return this.map.has(t)}get(t){return this.map.get(t)}set(t,e){this.map.set(t,e),this.arr.push(t)}delete(t){const e=this.arr.indexOf(t);e>=0&&this.arr.splice(e,1);const n=this.map.get(t);return this.map.delete(t),n}each(t){this.arr.forEach(e=>{const n=this.map.get(e);t(n,e)})}dispose(){this.clear()}}var $n;(function(i){function t(s){const r=[],o=[];return Array.isArray(s)?r.push(...s):s.split("|").forEach(a=>{a.indexOf("&")===-1?r.push(a):o.push(...a.split("&"))}),{or:r,and:o}}i.parse=t;function e(s,r){if(s!=null&&r!=null){const o=t(s),a=t(r),l=o.or.sort(),c=a.or.sort(),h=o.and.sort(),u=a.and.sort(),f=(d,g)=>d.length===g.length&&(d.length===0||d.every((p,m)=>p===g[m]));return f(l,c)&&f(h,u)}return s==null&&r==null}i.equals=e;function n(s,r,o){if(r==null||Array.isArray(r)&&r.length===0)return o?s.altKey!==!0&&s.ctrlKey!==!0&&s.metaKey!==!0&&s.shiftKey!==!0:!0;const{or:a,and:l}=t(r),c=h=>{const u=`${h.toLowerCase()}Key`;return s[u]===!0};return a.some(h=>c(h))&&l.every(h=>c(h))}i.isMatch=n})($n||($n={}));var Ae;(function(i){i.linear=t=>t,i.quad=t=>t*t,i.cubic=t=>t*t*t,i.inout=t=>{if(t<=0)return 0;if(t>=1)return 1;const e=t*t,n=e*t;return 4*(t<.5?n:3*(t-e)+n-.75)},i.exponential=t=>Math.pow(2,10*(t-1)),i.bounce=t=>{for(let e=0,n=1;;e+=n,n/=2)if(t>=(7-4*e)/11){const s=(11-6*e-11*t)/4;return-s*s+n*n}}})(Ae||(Ae={})),function(i){i.decorators={reverse(t){return e=>1-t(1-e)},reflect(t){return e=>.5*(e<.5?t(2*e):2-t(2-2*e))},clamp(t,e=0,n=1){return s=>{const r=t(s);return rn?n:r}},back(t=1.70158){return e=>e*e*((t+1)*e-t)},elastic(t=1.5){return e=>Math.pow(2,10*(e-1))*Math.cos(20*Math.PI*t/3*e)}}}(Ae||(Ae={})),function(i){function t(C){return-1*Math.cos(C*(Math.PI/2))+1}i.easeInSine=t;function e(C){return Math.sin(C*(Math.PI/2))}i.easeOutSine=e;function n(C){return-.5*(Math.cos(Math.PI*C)-1)}i.easeInOutSine=n;function s(C){return C*C}i.easeInQuad=s;function r(C){return C*(2-C)}i.easeOutQuad=r;function o(C){return C<.5?2*C*C:-1+(4-2*C)*C}i.easeInOutQuad=o;function a(C){return C*C*C}i.easeInCubic=a;function l(C){const O=C-1;return O*O*O+1}i.easeOutCubic=l;function c(C){return C<.5?4*C*C*C:(C-1)*(2*C-2)*(2*C-2)+1}i.easeInOutCubic=c;function h(C){return C*C*C*C}i.easeInQuart=h;function u(C){const O=C-1;return 1-O*O*O*O}i.easeOutQuart=u;function f(C){const O=C-1;return C<.5?8*C*C*C*C:1-8*O*O*O*O}i.easeInOutQuart=f;function d(C){return C*C*C*C*C}i.easeInQuint=d;function g(C){const O=C-1;return 1+O*O*O*O*O}i.easeOutQuint=g;function p(C){const O=C-1;return C<.5?16*C*C*C*C*C:1+16*O*O*O*O*O}i.easeInOutQuint=p;function m(C){return C===0?0:Math.pow(2,10*(C-1))}i.easeInExpo=m;function y(C){return C===1?1:-Math.pow(2,-10*C)+1}i.easeOutExpo=y;function x(C){if(C===0||C===1)return C;const O=C*2,k=O-1;return O<1?.5*Math.pow(2,10*k):.5*(-Math.pow(2,-10*k)+2)}i.easeInOutExpo=x;function b(C){const O=C/1;return-1*(Math.sqrt(1-O*C)-1)}i.easeInCirc=b;function w(C){const O=C-1;return Math.sqrt(1-O*O)}i.easeOutCirc=w;function P(C){const O=C*2,k=O-2;return O<1?-.5*(Math.sqrt(1-O*O)-1):.5*(Math.sqrt(1-k*k)+1)}i.easeInOutCirc=P;function A(C,O=1.70158){return C*C*((O+1)*C-O)}i.easeInBack=A;function S(C,O=1.70158){const k=C/1-1;return k*k*((O+1)*k+O)+1}i.easeOutBack=S;function E(C,O=1.70158){const k=C*2,J=k-2,Y=O*1.525;return k<1?.5*k*k*((Y+1)*k-Y):.5*(J*J*((Y+1)*J+Y)+2)}i.easeInOutBack=E;function N(C,O=.7){if(C===0||C===1)return C;const J=C/1-1,Y=1-O,ct=Y/(2*Math.PI)*Math.asin(1);return-(Math.pow(2,10*J)*Math.sin((J-ct)*(2*Math.PI)/Y))}i.easeInElastic=N;function L(C,O=.7){const k=1-O,J=C*2;if(C===0||C===1)return C;const Y=k/(2*Math.PI)*Math.asin(1);return Math.pow(2,-10*J)*Math.sin((J-Y)*(2*Math.PI)/k)+1}i.easeOutElastic=L;function T(C,O=.65){const k=1-O;if(C===0||C===1)return C;const J=C*2,Y=J-1,ct=k/(2*Math.PI)*Math.asin(1);return J<1?-.5*(Math.pow(2,10*Y)*Math.sin((Y-ct)*(2*Math.PI)/k)):Math.pow(2,-10*Y)*Math.sin((Y-ct)*(2*Math.PI)/k)*.5+1}i.easeInOutElastic=T;function j(C){const O=C/1;if(O<1/2.75)return 7.5625*O*O;if(O<2/2.75){const k=O-1.5/2.75;return 7.5625*k*k+.75}if(O<2.5/2.75){const k=O-2.25/2.75;return 7.5625*k*k+.9375}{const k=O-2.625/2.75;return 7.5625*k*k+.984375}}i.easeOutBounce=j;function Q(C){return 1-j(1-C)}i.easeInBounce=Q;function F(C){return C<.5?Q(C*2)*.5:j(C*2-1)*.5+.5}i.easeInOutBounce=F}(Ae||(Ae={}));var Ce;(function(i){i.number=(t,e)=>{const n=e-t;return s=>t+n*s},i.object=(t,e)=>{const n=Object.keys(t);return s=>{const r={};for(let o=n.length-1;o!==-1;o-=1){const a=n[o];r[a]=t[a]+(e[a]-t[a])*s}return r}},i.unit=(t,e)=>{const n=/(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/,s=n.exec(t),r=n.exec(e),o=r?r[1]:"",a=s?+s[1]:0,l=r?+r[1]:0,c=o.indexOf("."),h=c>0?o[1].length-c-1:0,u=l-a,f=s?s[2]:"";return d=>(a+u*d).toFixed(h)+f},i.color=(t,e)=>{const n=parseInt(t.slice(1),16),s=parseInt(e.slice(1),16),r=n&255,o=(s&255)-r,a=n&65280,l=(s&65280)-a,c=n&16711680,h=(s&16711680)-c;return u=>{const f=r+o*u&255,d=a+l*u&65280,g=c+h*u&16711680;return`#${(1<<24|f|d|g).toString(16).slice(1)}`}}})(Ce||(Ce={}));const Rn=[];function Fa(i,t){if(!Rn.find(n=>n.name===i)&&!se.isApplyingHMR()){const n=document.createElement("style");n.setAttribute("type","text/css"),n.textContent=t;const s=document.querySelector("head");s&&s.insertBefore(n,s.firstChild),Rn.push({name:i,styleElement:n})}}function _a(i){const t=Rn.findIndex(e=>e.name===i);if(t>-1){let e=Rn[t].styleElement;e&&e.parentNode&&e.parentNode.removeChild(e),e=null,Rn.splice(t,1)}}var q;(function(i){function t(n){return 180*n/Math.PI%360}i.toDeg=t,i.toRad=function(n,s=!1){return(s?n:n%360)*Math.PI/180};function e(n){return n%360+(n<0?360:0)}i.normalize=e})(q||(q={}));var G;(function(i){function t(a,l=0){return Number.isInteger(a)?a:+a.toFixed(l)}i.round=t;function e(a,l){let c,h;if(l==null?(h=a==null?1:a,c=0):(h=l,c=a==null?0:a),hc?c:a:al?l:a}i.clamp=n;function s(a,l){return l*Math.round(a/l)}i.snapToGrid=s;function r(a,l){return l!=null&&a!=null&&l.x>=a.x&&l.x<=a.x+a.width&&l.y>=a.y&&l.y<=a.y+a.height}i.containsPoint=r;function o(a,l){const c=a.x-l.x,h=a.y-l.y;return c*c+h*h}i.squaredLength=o})(G||(G={}));class re{valueOf(){return this.toJSON()}toString(){return JSON.stringify(this.toJSON())}}class v extends re{constructor(t,e){super();this.x=t==null?0:t,this.y=e==null?0:e}round(t=0){return this.x=G.round(this.x,t),this.y=G.round(this.y,t),this}add(t,e){const n=v.create(t,e);return this.x+=n.x,this.y+=n.y,this}update(t,e){const n=v.create(t,e);return this.x=n.x,this.y=n.y,this}translate(t,e){const n=v.create(t,e);return this.x+=n.x,this.y+=n.y,this}rotate(t,e){const n=v.rotate(this,t,e);return this.x=n.x,this.y=n.y,this}scale(t,e,n=new v){const s=v.create(n);return this.x=s.x+t*(this.x-s.x),this.y=s.y+e*(this.y-s.y),this}closest(t){if(t.length===1)return v.create(t[0]);let e=null,n=Infinity;return t.forEach(s=>{const r=this.squaredDistance(s);rs&&(a=(this.x+this.width-s)/(p.x-s)),p.y>r&&(u=(this.y+this.height-r)/(p.y-r));const m=n.topRight;m.x>s&&(l=(this.x+this.width-s)/(m.x-s)),m.yr&&(d=(this.y+this.height-r)/(y.y-r)),{sx:Math.min(o,a,l,c),sy:Math.min(h,u,f,d)}}getMaxUniformScaleToFit(t,e=this.center){const n=this.getMaxScaleToFit(t,e);return Math.min(n.sx,n.sy)}containsPoint(t,e){return G.containsPoint(this,v.create(t,e))}containsRect(t,e,n,s){const r=M.create(t,e,n,s),o=this.x,a=this.y,l=this.width,c=this.height,h=r.x,u=r.y,f=r.width,d=r.height;return l===0||c===0||f===0||d===0?!1:h>=o&&u>=a&&h+f<=o+l&&u+d<=a+c}intersectsWithLine(t){const e=[this.topLine,this.rightLine,this.bottomLine,this.leftLine],n=[],s=[];return e.forEach(r=>{const o=t.intersectsWithLine(r);o!==null&&s.indexOf(o.toString())<0&&(n.push(o),s.push(o.toString()))}),n.length>0?n:null}intersectsWithLineFromCenterToPoint(t,e){const n=v.clone(t),s=this.center;let r=null;e!=null&&e!==0&&n.rotate(e,s);const o=[this.topLine,this.rightLine,this.bottomLine,this.leftLine],a=new I(s,n);for(let l=o.length-1;l>=0;l-=1){const c=o[l].intersectsWithLine(a);if(c!==null){r=c;break}}return r&&e!=null&&e!==0&&r.rotate(-e,s),r}intersectsWithRect(t,e,n,s){const r=M.create(t,e,n,s);if(!this.isIntersectWithRect(r))return null;const o=this.origin,a=this.corner,l=r.origin,c=r.corner,h=Math.max(o.x,l.x),u=Math.max(o.y,l.y);return new M(h,u,Math.min(a.x,c.x)-h,Math.min(a.y,c.y)-u)}isIntersectWithRect(t,e,n,s){const r=M.create(t,e,n,s),o=this.origin,a=this.corner,l=r.origin,c=r.corner;return!(c.x<=o.x||c.y<=o.y||l.x>=a.x||l.y>=a.y)}normalize(){let t=this.x,e=this.y,n=this.width,s=this.height;return this.width<0&&(t=this.x+this.width,n=-this.width),this.height<0&&(e=this.y+this.height,s=-this.height),this.x=t,this.y=e,this.width=n,this.height=s,this}union(t){const e=M.clone(t),n=this.origin,s=this.corner,r=e.origin,o=e.corner,a=Math.min(n.x,r.x),l=Math.min(n.y,r.y),c=Math.max(s.x,o.x),h=Math.max(s.y,o.y);return new M(a,l,c-a,h-l)}getNearestSideToPoint(t){const e=v.clone(t),n=e.x-this.x,s=this.x+this.width-e.x,r=e.y-this.y,o=this.y+this.height-e.y;let a=n,l="left";return s=1?n.clone():e.lerp(n,t)}pointAtLength(t){const e=this.start,n=this.end;let s=!0;t<0&&(s=!1,t=-t);const r=this.length();if(t>=r)return s?n.clone():e.clone();const o=(s?t:r-t)/r;return this.pointAt(o)}divideAt(t){const e=this.pointAt(t);return[new I(this.start,e),new I(e,this.end)]}divideAtLength(t){const e=this.pointAtLength(t);return[new I(this.start,e),new I(e,this.end)]}containsPoint(t){const e=this.start,n=this.end;if(e.cross(t,n)!==0)return!1;const s=this.length();return!(new I(e,t).length()>s||new I(t,n).length()>s)}intersect(t,e){const n=t.intersectsWithLine(this,e);return n?Array.isArray(n)?n:[n]:null}intersectsWithLine(t){const e=new v(this.end.x-this.start.x,this.end.y-this.start.y),n=new v(t.end.x-t.start.x,t.end.y-t.start.y),s=e.x*n.y-e.y*n.x,r=new v(t.start.x-this.start.x,t.start.y-this.start.y),o=r.x*n.y-r.y*n.x,a=r.x*e.y-r.y*e.x;if(s===0||o*s<0||a*s<0)return null;if(s>0){if(o>s||a>s)return null}else if(o0&&(s-=o,r-=a,l=s*o+r*a,l<0&&(l=0))),l<0?-1:l>0?1:0}equals(t){return t!=null&&this.start.x===t.start.x&&this.start.y===t.start.y&&this.end.x===t.end.x&&this.end.y===t.end.y}clone(){return new I(this.start,this.end)}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}serialize(){return[this.start.serialize(),this.end.serialize()].join(" ")}}(function(i){function t(e){return e!=null&&e instanceof i}i.isLine=t})(I||(I={}));class It extends re{constructor(t,e,n,s){super();this.x=t==null?0:t,this.y=e==null?0:e,this.a=n==null?0:n,this.b=s==null?0:s}get center(){return new v(this.x,this.y)}bbox(){return M.fromEllipse(this)}getCenter(){return this.center}inflate(t,e){const n=t,s=e!=null?e:t;return this.a+=2*n,this.b+=2*s,this}normalizedDistance(t,e){const n=v.create(t,e),s=n.x-this.x,r=n.y-this.y,o=this.a,a=this.b;return s*s/(o*o)+r*r/(a*a)}containsPoint(t,e){return this.normalizedDistance(t,e)<=1}intersectsWithLine(t){const e=[],n=this.a,s=this.b,r=t.start,o=t.end,a=t.vector(),l=r.diff(new v(this.x,this.y)),c=new v(a.x/(n*n),a.y/(s*s)),h=new v(l.x/(n*n),l.y/(s*s)),u=a.dot(c),f=a.dot(h),d=l.dot(h)-1,g=f*f-u*d;if(g<0)return null;if(g>0){const p=Math.sqrt(g),m=(-f-p)/u,y=(-f+p)/u;if((m<0||m>1)&&(y<0||y>1))return null;m>=0&&m<=1&&e.push(r.lerp(o,m)),y>=0&&y<=1&&e.push(r.lerp(o,y))}else{const p=-f/u;if(p>=0&&p<=1)e.push(r.lerp(o,p));else return null}return e}intersectsWithLineFromCenterToPoint(t,e=0){const n=v.clone(t);e&&n.rotate(e,this.getCenter());const s=n.x-this.x,r=n.y-this.y;let o;if(s===0)return o=this.bbox().getNearestPointToPoint(n),e?o.rotate(-e,this.getCenter()):o;const a=r/s,l=a*a,c=this.a*this.a,h=this.b*this.b;let u=Math.sqrt(1/(1/c+l/h));u=s<0?-u:u;const f=a*u;return o=new v(this.x+u,this.y+f),e?o.rotate(-e,this.getCenter()):o}tangentTheta(t){const e=v.clone(t),n=e.x,s=e.y,r=this.a,o=this.b,a=this.bbox().center,l=a.x,c=a.y,h=30,u=n>a.x+r/2,f=na.x?s-h:s+h,d=r*r/(n-l)-r*r*(s-c)*(g-c)/(o*o*(n-l))+l):(d=s>a.y?n+h:n-h,g=o*o/(s-c)-o*o*(n-l)*(d-l)/(r*r*(s-c))+c),new v(d,g).theta(e)}scale(t,e){return this.a*=t,this.b*=e,this}rotate(t,e){const n=M.fromEllipse(this);n.rotate(t,e);const s=It.fromRect(n);return this.a=s.a,this.b=s.b,this.x=s.x,this.y=s.y,this}translate(t,e){const n=v.create(t,e);return this.x+=n.x,this.y+=n.y,this}equals(t){return t!=null&&t.x===this.x&&t.y===this.y&&t.a===this.a&&t.b===this.b}clone(){return new It(this.x,this.y,this.a,this.b)}toJSON(){return{x:this.x,y:this.y,a:this.a,b:this.b}}serialize(){return`${this.x} ${this.y} ${this.a} ${this.b}`}}(function(i){function t(e){return e!=null&&e instanceof i}i.isEllipse=t})(It||(It={})),function(i){function t(s,r,o,a){return s==null||typeof s=="number"?new i(s,r,o,a):e(s)}i.create=t;function e(s){return i.isEllipse(s)?s.clone():Array.isArray(s)?new i(s[0],s[1],s[2],s[3]):new i(s.x,s.y,s.a,s.b)}i.parse=e;function n(s){const r=s.center;return new i(r.x,r.y,s.width/2,s.height/2)}i.fromRect=n}(It||(It={}));const iy=new RegExp("^[\\s\\dLMCZz,.]*$");function ry(i){return typeof i!="string"?!1:iy.test(i)}function Ri(i,t){return(i%t+t)%t}function oy(i,t,e,n,s){const r=[],o=i[i.length-1],a=t!=null&&t>0,l=t||0;if(n&&a){i=i.slice();const u=i[0],f=new v(o.x+(u.x-o.x)/2,o.y+(u.y-o.y)/2);i.splice(0,0,f)}let c=i[0],h=1;for(e?r.push("M",c.x,c.y):r.push("L",c.x,c.y);h<(n?i.length:i.length-1);){let u=i[Ri(h,i.length)],f=c.x-u.x,d=c.y-u.y;if(a&&(f!==0||d!==0)&&(s==null||s.indexOf(h-1)<0)){let g=Math.sqrt(f*f+d*d);const p=f*Math.min(l,g/2)/g,m=d*Math.min(l,g/2)/g,y=u.x+p,x=u.y+m;r.push("L",y,x);let b=i[Ri(h+1,i.length)];for(;htypeof u=="string"?u:+u.toFixed(3)).join(" ")}function Ha(i,t={}){const e=[];return i&&i.length&&i.forEach(n=>{Array.isArray(n)?e.push({x:n[0],y:n[1]}):e.push({x:n.x,y:n.y})}),oy(e,t.round,t.initialMove==null||t.initialMove,t.close,t.exclude)}function xs(i,t,e,n,s=0,r=0,o=0,a,l){if(e===0||n===0)return[];a-=i,l-=t,e=Math.abs(e),n=Math.abs(n);const c=-a/2,h=-l/2,u=Math.cos(s*Math.PI/180),f=Math.sin(s*Math.PI/180),d=u*c+f*h,g=-1*f*c+u*h,p=d*d,m=g*g,y=e*e,x=n*n,b=p/y+m/x;let w;if(b>1)e=Math.sqrt(b)*e,n=Math.sqrt(b)*n,w=0;else{let Ht=1;r===o&&(Ht=-1),w=Ht*Math.sqrt((y*x-y*m-x*p)/(y*m+x*p))}const P=w*e*g/n,A=-1*w*n*d/e,S=u*P-f*A+a/2,E=f*P+u*A+l/2;let N=Math.atan2((g-A)/n,(d-P)/e)-Math.atan2(0,1),L=N>=0?N:2*Math.PI+N;N=Math.atan2((-g-A)/n,(-d-P)/e)-Math.atan2((g-A)/n,(d-P)/e);let T=N>=0?N:2*Math.PI+N;o===0&&T>0?T-=2*Math.PI:o!==0&&T<0&&(T+=2*Math.PI);const j=T*2/Math.PI,Q=Math.ceil(j<0?-1*j:j),F=T/Q,C=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),O=u*e,k=u*n,J=f*e,Y=f*n;let ct=Math.cos(L),yt=Math.sin(L),Wn=-C*(O*yt+Y*ct),Xn=-C*(J*yt-k*ct),te=0,hn=0;const _t=[];for(let Ht=0;Ht+Ht.toFixed(2))}function ay(i,t,e,n,s=0,r=0,o=0,a,l){const c=[],h=xs(i,t,e,n,s,r,o,a,l);if(h!=null)for(let u=0,f=h.length;uv.create(e))}else this.points=[]}get start(){return this.points[0]||null}get end(){return this.points[this.points.length-1]||null}scale(t,e,n=new v){return this.points.forEach(s=>s.scale(t,e,n)),this}rotate(t,e){return this.points.forEach(n=>n.rotate(t,e)),this}translate(t,e){const n=v.create(t,e);return this.points.forEach(s=>s.translate(n.x,n.y)),this}round(t=0){return this.points.forEach(e=>e.round(t)),this}bbox(){if(this.points.length===0)return new M;let t=Infinity,e=-Infinity,n=Infinity,s=-Infinity;const r=this.points;for(let o=0,a=r.length;oe&&(e=c),hs&&(s=h)}return new M(t,n,e-t,s-n)}closestPoint(t){const e=this.closestPointLength(t);return this.pointAtLength(e)}closestPointLength(t){const e=this.points,n=e.length;if(n===0||n===1)return 0;let s=0,r=0,o=Infinity;for(let a=0,l=n-1;au.y||s>h.y&&s<=u.y){const d=h.x-n>u.x-n?h.x-n:u.x-n;if(d>=0){const g=new v(n+d,s),p=new I(t,g);f.intersectsWithLine(p)&&(l+=1)}}a=c}return l%2==1}intersectsWithLine(t){const e=[];for(let n=0,s=this.points.length-1;n0?e:null}isDifferentiable(){for(let t=0,e=this.points.length-1;t=1)return e[n-1].clone();const r=this.length()*t;return this.pointAtLength(r)}pointAtLength(t){const e=this.points,n=e.length;if(n===0)return null;if(n===1)return e[0].clone();let s=!0;t<0&&(s=!1,t=-t);let r=0;for(let a=0,l=n-1;a1&&(t=1);const r=this.length()*t;return this.tangentAtLength(r)}tangentAtLength(t){const e=this.points,n=e.length;if(n===0||n===1)return null;let s=!0;t<0&&(s=!1,t=-t);let r,o=0;for(let a=0,l=n-1;an.x)&&(n=t[f]);const s=[];for(let f=0;f{let g=f[2]-d[2];return g===0&&(g=d[1]-f[1]),g}),s.length>2){const f=s[s.length-1];s.unshift(f)}const r={},o=[],a=f=>`${f[0].toString()}@${f[1]}`;for(;s.length!==0;){const f=s.pop(),d=f[0];if(r[a(f)])continue;let g=!1;for(;!g;)if(o.length<2)o.push(f),g=!0;else{const p=o.pop(),m=p[0],y=o.pop(),x=y[0],b=x.cross(m,d);if(b<0)o.push(y),o.push(p),o.push(f),g=!0;else if(b===0){const w=1e-10,P=m.angleBetween(x,d);Math.abs(P-180)2&&o.pop();let l,c=-1;for(let f=0,d=o.length;f0){const f=o.slice(c),d=o.slice(0,c);h=f.concat(d)}else h=o;const u=[];for(let f=0,d=h.length;fe.equals(this.points[n]))}clone(){return new nt(this.points.map(t=>t.clone()))}toJSON(){return this.points.map(t=>t.toJSON())}serialize(){return this.points.map(t=>`${t.serialize()}`).join(" ")}}(function(i){function t(e){return e!=null&&e instanceof i}i.isPolyline=t})(nt||(nt={})),function(i){function t(e){const n=e.trim();if(n==="")return new i;const s=[],r=n.split(/\s*,\s*|\s+/);for(let o=0,a=r.length;o0&&b<1&&g.push(b);continue}A=y*y-4*x*m,S=Math.sqrt(A),!(A<0)&&(w=(-y+S)/(2*m),w>0&&w<1&&g.push(w),P=(-y-S)/(2*m),P>0&&P<1&&g.push(P))}let E,N,L,T=g.length;const j=T;for(;T;)T-=1,b=g[T],L=1-b,E=L*L*L*r+3*L*L*b*a+3*L*b*b*c+b*b*b*u,p[0][T]=E,N=L*L*L*o+3*L*L*b*l+3*L*b*b*h+b*b*b*f,p[1][T]=N,d[T]={X:E,Y:N};g[j]=0,g[j+1]=1,d[j]={X:r,Y:o},d[j+1]={X:u,Y:f},p[0][j]=r,p[1][j]=o,p[0][j+1]=u,p[1][j+1]=f,g.length=j+2,p[0].length=j+2,p[1].length=j+2,d.length=j+2;const Q=Math.min.apply(null,p[0]),F=Math.min.apply(null,p[1]),C=Math.max.apply(null,p[0]),O=Math.max.apply(null,p[1]);return new M(Q,F,C-Q,O-F)}closestPoint(t,e={}){return this.pointAtT(this.closestPointT(t,e))}closestPointLength(t,e={}){const n=this.getOptions(e);return this.lengthAtT(this.closestPointT(t,n),n)}closestPointNormalizedLength(t,e={}){const n=this.getOptions(e),s=this.closestPointLength(t,n);if(!s)return 0;const r=this.length(n);return r===0?0:s/r}closestPointT(t,e={}){const n=this.getPrecision(e),s=this.getDivisions(e),r=Math.pow(10,-n);let o=null,a=0,l=0,c=0,h=0,u=0,f=null;const d=s.length;let g=d>0?1/d:0;for(s.forEach((p,m)=>{const y=p.start.distance(t),x=p.end.distance(t),b=y+x;(f==null||b=1)return this.divideAtT(1);const n=this.tAt(t,e);return this.divideAtT(n)}divideAtLength(t,e={}){const n=this.tAtLength(t,e);return this.divideAtT(n)}divide(t){return this.divideAtT(t)}divideAtT(t){const e=this.start,n=this.controlPoint1,s=this.controlPoint2,r=this.end;if(t<=0)return[new et(e,e,e,e),new et(e,n,s,r)];if(t>=1)return[new et(e,n,s,r),new et(r,r,r,r)];const o=this.getSkeletonPoints(t),a=o.startControlPoint1,l=o.startControlPoint2,c=o.divider,h=o.dividerControlPoint1,u=o.dividerControlPoint2;return[new et(e,a,l,c),new et(c,h,u,r)]}endpointDistance(){return this.start.distance(this.end)}getSkeletonPoints(t){const e=this.start,n=this.controlPoint1,s=this.controlPoint2,r=this.end;if(t<=0)return{startControlPoint1:e.clone(),startControlPoint2:e.clone(),divider:e.clone(),dividerControlPoint1:n.clone(),dividerControlPoint2:s.clone()};if(t>=1)return{startControlPoint1:n.clone(),startControlPoint2:s.clone(),divider:r.clone(),dividerControlPoint1:r.clone(),dividerControlPoint2:r.clone()};const o=new I(e,n).pointAt(t),a=new I(n,s).pointAt(t),l=new I(s,r).pointAt(t),c=new I(o,a).pointAt(t),h=new I(a,l).pointAt(t),u=new I(c,h).pointAt(t);return{startControlPoint1:o,startControlPoint2:c,divider:u,dividerControlPoint1:h,dividerControlPoint2:l}}getSubdivisions(t={}){const e=this.getPrecision(t);let n=[new et(this.start,this.controlPoint1,this.controlPoint2,this.end)];if(e===0)return n;let s=this.endpointDistance();const r=Math.pow(10,-e);let o=0;for(;;){o+=1;const a=[];n.forEach(h=>{const u=h.divide(.5);a.push(u[0],u[1])});const l=a.reduce((h,u)=>h+u.endpointDistance(),0),c=l!==0?(l-s)/l:0;if(o>1&&cn+s.endpointDistance(),0)}lengthAtT(t,e={}){if(t<=0)return 0;const n=e.precision===void 0?this.PRECISION:e.precision;return this.divide(t)[0].length({precision:n})}pointAt(t,e={}){if(t<=0)return this.start.clone();if(t>=1)return this.end.clone();const n=this.tAt(t,e);return this.pointAtT(n)}pointAtLength(t,e={}){const n=this.tAtLength(t,e);return this.pointAtT(n)}pointAtT(t){return t<=0?this.start.clone():t>=1?this.end.clone():this.getSkeletonPoints(t).divider}isDifferentiable(){const t=this.start,e=this.controlPoint1,n=this.controlPoint2,s=this.end;return!(t.equals(e)&&e.equals(n)&&n.equals(s))}tangentAt(t,e={}){if(!this.isDifferentiable())return null;t<0?t=0:t>1&&(t=1);const n=this.tAt(t,e);return this.tangentAtT(n)}tangentAtLength(t,e={}){if(!this.isDifferentiable())return null;const n=this.tAtLength(t,e);return this.tangentAtT(n)}tangentAtT(t){if(!this.isDifferentiable())return null;t<0&&(t=0),t>1&&(t=1);const e=this.getSkeletonPoints(t),n=e.startControlPoint2,s=e.dividerControlPoint1,r=e.divider,o=new I(n,s);return o.translate(r.x-n.x,r.y-n.y),o}getPrecision(t={}){return t.precision==null?this.PRECISION:t.precision}getDivisions(t={}){if(t.subdivisions!=null)return t.subdivisions;const e=this.getPrecision(t);return this.getSubdivisions({precision:e})}getOptions(t={}){const e=this.getPrecision(t),n=this.getDivisions(t);return{precision:e,subdivisions:n}}tAt(t,e={}){if(t<=0)return 0;if(t>=1)return 1;const n=this.getOptions(e),r=this.length(n)*t;return this.tAtLength(r,n)}tAtLength(t,e={}){let n=!0;t<0&&(n=!1,t=-t);const s=this.getPrecision(e),r=this.getDivisions(e),o={precision:s,subdivisions:r};let a=null,l,c,h=0,u=0,f=0;const d=r.length;let g=d>0?1/d:0;for(let y=0;yn.push(s.end.clone())),n}toPolyline(t={}){return new nt(this.toPoints(t))}scale(t,e,n){return this.start.scale(t,e,n),this.controlPoint1.scale(t,e,n),this.controlPoint2.scale(t,e,n),this.end.scale(t,e,n),this}rotate(t,e){return this.start.rotate(t,e),this.controlPoint1.rotate(t,e),this.controlPoint2.rotate(t,e),this.end.rotate(t,e),this}translate(t,e){return typeof t=="number"?(this.start.translate(t,e),this.controlPoint1.translate(t,e),this.controlPoint2.translate(t,e),this.end.translate(t,e)):(this.start.translate(t),this.controlPoint1.translate(t),this.controlPoint2.translate(t),this.end.translate(t)),this}equals(t){return t!=null&&this.start.equals(t.start)&&this.controlPoint1.equals(t.controlPoint1)&&this.controlPoint2.equals(t.controlPoint2)&&this.end.equals(t.end)}clone(){return new et(this.start,this.controlPoint1,this.controlPoint2,this.end)}toJSON(){return{start:this.start.toJSON(),controlPoint1:this.controlPoint1.toJSON(),controlPoint2:this.controlPoint2.toJSON(),end:this.end.toJSON()}}serialize(){return[this.start.serialize(),this.controlPoint1.serialize(),this.controlPoint2.serialize(),this.end.serialize()].join(" ")}}(function(i){function t(e){return e!=null&&e instanceof i}i.isCurve=t})(et||(et={})),function(i){function t(s){const r=s.length,o=[],a=[];let l=2;o[0]=s[0]/l;for(let c=1;cv.clone(f)),o=[],a=[],l=r.length-1;if(l===1)return o[0]=new v((2*r[0].x+r[1].x)/3,(2*r[0].y+r[1].y)/3),a[0]=new v(2*o[0].x-r[0].x,2*o[0].y-r[0].y),[o,a];const c=[];for(let f=1;f=1?n:n*t}divideAtT(t){if(this.divideAt)return this.divideAt(t);throw new Error("Neither `divideAtT` nor `divideAt` method is implemented.")}pointAtT(t){if(this.pointAt)return this.pointAt(t);throw new Error("Neither `pointAtT` nor `pointAt` method is implemented.")}tangentAtT(t){if(this.tangentAt)return this.tangentAt(t);throw new Error("Neither `tangentAtT` nor `tangentAt` method is implemented.")}}class xt extends vs{constructor(t,e){super();I.isLine(t)?this.endPoint=t.end.clone().round(2):this.endPoint=v.create(t,e).round(2)}get type(){return"L"}get line(){return new I(this.start,this.end)}bbox(){return this.line.bbox()}closestPoint(t){return this.line.closestPoint(t)}closestPointLength(t){return this.line.closestPointLength(t)}closestPointNormalizedLength(t){return this.line.closestPointNormalizedLength(t)}closestPointTangent(t){return this.line.closestPointTangent(t)}length(){return this.line.length()}divideAt(t){const e=this.line.divideAt(t);return[new xt(e[0]),new xt(e[1])]}divideAtLength(t){const e=this.line.divideAtLength(t);return[new xt(e[0]),new xt(e[1])]}getSubdivisions(){return[]}pointAt(t){return this.line.pointAt(t)}pointAtLength(t){return this.line.pointAtLength(t)}tangentAt(t){return this.line.tangentAt(t)}tangentAtLength(t){return this.line.tangentAtLength(t)}isDifferentiable(){return this.previousSegment==null?!1:!this.start.equals(this.end)}clone(){return new xt(this.end)}scale(t,e,n){return this.end.scale(t,e,n),this}rotate(t,e){return this.end.rotate(t,e),this}translate(t,e){return typeof t=="number"?this.end.translate(t,e):this.end.translate(t),this}equals(t){return this.type===t.type&&this.start.equals(t.start)&&this.end.equals(t.end)}toJSON(){return{type:this.type,start:this.start.toJSON(),end:this.end.toJSON()}}serialize(){const t=this.end;return`${this.type} ${t.x} ${t.y}`}}(function(i){function t(...e){const n=e.length,s=e[0];if(I.isLine(s))return new i(s);if(v.isPointLike(s))return n===1?new i(s):e.map(o=>new i(o));if(n===2)return new i(+e[0],+e[1]);const r=[];for(let o=0;o1&&(O=Math.sqrt(O),e=O*e,n=O*n);const k=e*e,J=n*n,Y=(r===o?-1:1)*Math.sqrt(Math.abs((k*J-k*C*C-J*F*F)/(k*C*C+J*F*F)));m=Y*e*C/n+(i+a)/2,y=Y*-n*F/e+(t+l)/2,g=Math.asin((t-y)/n),p=Math.asin((l-y)/n),g=ip&&(g-=Math.PI*2),!o&&p>g&&(p-=Math.PI*2)}let x=p-g;if(Math.abs(x)>h){const F=p,C=a,O=l;p=g+h*(o&&p>g?1:-1),a=m+e*Math.cos(p),l=y+n*Math.sin(p),f=Ga(a,l,e,n,s,0,o,C,O,[p,F,m,y])}x=p-g;const b=Math.cos(g),w=Math.sin(g),P=Math.cos(p),A=Math.sin(p),S=Math.tan(x/4),E=4/3*(e*S),N=4/3*(n*S),L=[i,t],T=[i+E*w,t-N*b],j=[a+E*A,l-N*P],Q=[a,l];if(T[0]=2*L[0]-T[0],T[1]=2*L[1]-T[1],c)return[T,j,Q].concat(f);{f=[T,j,Q].concat(f).join().split(",");const F=[],C=f.length;for(let O=0;O{const c=[];let h=a.toLowerCase();l.replace(n,(f,d)=>(d&&c.push(+d),f)),h==="m"&&c.length>2&&(r.push([a,...c.splice(0,2)]),h="l",a=a==="m"?"l":"L");const u=s[h];for(;c.length>=u&&(r.push([a,...c.splice(0,u)]),!!u););return o}),r}function cy(i){const t=ly(i);if(!t||!t.length)return[["M",0,0]];let e=0,n=0,s=0,r=0;const o=[];for(let a=0,l=t.length;a7){l[c].shift();const h=l[c];for(;h.length;)r[c]="A",c+=1,l.splice(c,0,["C"].concat(h.splice(0,6)));l.splice(c,1),a=t.length}}const r=[];let o="",a=t.length;for(let l=0;l0&&(o=r[l-1])),t[l]=n(t[l],e,o),r[l]!=="A"&&c==="C"&&(r[l]="C"),s(t,l);const h=t[l],u=h.length;e.x=h[u-2],e.y=h[u-1],e.bx=parseFloat(h[u-4])||e.x,e.by=parseFloat(h[u-3])||e.y}return(!t[0][0]||t[0][0]!=="M")&&t.unshift(["M",0,0]),t}function uy(i){return hy(i).map(t=>t.map(e=>typeof e=="string"?e:G.round(e,2))).join(",").split(",").join(" ")}class D extends re{constructor(t){super();if(this.PRECISION=3,this.segments=[],Array.isArray(t))if(I.isLine(t[0])||et.isCurve(t[0])){let e=null;t.forEach((s,r)=>{r===0&&this.appendSegment(D.createSegment("M",s.start)),e!=null&&!e.end.equals(s.start)&&this.appendSegment(D.createSegment("M",s.start)),I.isLine(s)?this.appendSegment(D.createSegment("L",s.end)):et.isCurve(s)&&this.appendSegment(D.createSegment("C",s.controlPoint1,s.controlPoint2,s.end)),e=s})}else t.forEach(n=>{n.isSegment&&this.appendSegment(n)});else t!=null&&(I.isLine(t)?(this.appendSegment(D.createSegment("M",t.start)),this.appendSegment(D.createSegment("L",t.end))):et.isCurve(t)?(this.appendSegment(D.createSegment("M",t.start)),this.appendSegment(D.createSegment("C",t.controlPoint1,t.controlPoint2,t.end))):nt.isPolyline(t)?t.points&&t.points.length&&t.points.forEach((e,n)=>{const s=n===0?D.createSegment("M",e):D.createSegment("L",e);this.appendSegment(s)}):t.isSegment&&this.appendSegment(t))}get start(){const t=this.segments,e=t.length;if(e===0)return null;for(let n=0;n=0;n-=1){const s=t[n];if(s.isVisible)return s.end}return t[e-1].end}moveTo(...t){return this.appendSegment(Je.create.call(null,...t))}lineTo(...t){return this.appendSegment(xt.create.call(null,...t))}curveTo(...t){return this.appendSegment(Et.create.call(null,...t))}arcTo(t,e,n,s,r,o,a){const l=this.end||new v,c=typeof o=="number"?xs(l.x,l.y,t,e,n,s,r,o,a):xs(l.x,l.y,t,e,n,s,r,o.x,o.y);if(c!=null)for(let h=0,u=c.length;hn||t<0)throw new Error("Index out of range.");let s,r=null,o=null;if(n!==0&&(t>=1?(r=this.segments[t-1],o=r.nextSegment):(r=null,o=this.segments[0])),!Array.isArray(e))s=this.prepareSegment(e,r,o),this.segments.splice(t,0,s);else for(let a=0,l=e.length;a=e||n<0)throw new Error("Index out of range.");return n}segmentAt(t,e={}){const n=this.segmentIndexAt(t,e);return n?this.getSegment(n):null}segmentAtLength(t,e={}){const n=this.segmentIndexAtLength(t,e);return n?this.getSegment(n):null}segmentIndexAt(t,e={}){if(this.segments.length===0)return null;const n=G.clamp(t,0,1),s=this.getOptions(e),o=this.length(s)*n;return this.segmentIndexAtLength(o,s)}segmentIndexAtLength(t,e={}){const n=this.segments.length;if(n===0)return null;let s=!0;t<0&&(s=!1,t=-t);const r=this.getPrecision(e),o=this.getSubdivisions(e);let a=0,l=null;for(let c=0;c=1)return this.end.clone();const n=this.getOptions(e),r=this.length(n)*t;return this.pointAtLength(r,n)}pointAtLength(t,e={}){if(this.segments.length===0)return null;if(t===0)return this.start.clone();let n=!0;t<0&&(n=!1,t=-t);const s=this.getPrecision(e),r=this.getSubdivisions(e);let o,a=0;for(let c=0,h=this.segments.length;c=n)return e[n-1].pointAtT(1);const r=G.clamp(t.value,0,1);return e[s].pointAtT(r)}divideAt(t,e={}){if(this.segments.length===0)return null;const n=G.clamp(t,0,1),s=this.getOptions(e),o=this.length(s)*n;return this.divideAtLength(o,s)}divideAtLength(t,e={}){if(this.segments.length===0)return null;let n=!0;t<0&&(n=!1,t=-t);const s=this.getPrecision(e),r=this.getSubdivisions(e);let o=0,a,l,c,h,u;for(let P=0,A=this.segments.length;P=n&&(s=n-1,r=1);const o=this.getPrecision(e),a=this.getSubdivisions(e);let l=0;for(let u=0;u=e)return this.segments[e-1].tangentAtT(1);const s=G.clamp(t.value,0,1);return this.segments[n].tangentAtT(s)}getPrecision(t={}){return t.precision==null?this.PRECISION:t.precision}getSubdivisions(t={}){if(t.segmentSubdivisions==null){const e=this.getPrecision(t);return this.getSegmentSubdivisions({precision:e})}return t.segmentSubdivisions}getOptions(t={}){const e=this.getPrecision(t),n=this.getSubdivisions(t);return{precision:e,segmentSubdivisions:n}}toPoints(t={}){const e=this.segments,n=e.length;if(n===0)return null;const s=this.getSubdivisions(t),r=[];let o=[];for(let a=0;a0?c.forEach(h=>o.push(h.start)):o.push(l.start)}else o.length>0&&(o.push(e[a-1].end),r.push(o),o=[])}return o.length>0&&(o.push(this.end),r.push(o)),r}toPolylines(t={}){const e=this.toPoints(t);return e?e.map(n=>new nt(n)):null}scale(t,e,n){return this.segments.forEach(s=>s.scale(t,e,n)),this}rotate(t,e){return this.segments.forEach(n=>n.rotate(t,e)),this}translate(t,e){return typeof t=="number"?this.segments.forEach(n=>n.translate(t,e)):this.segments.forEach(n=>n.translate(t)),this}clone(){const t=new D;return this.segments.forEach(e=>t.appendSegment(e.clone())),t}equals(t){if(t==null)return!1;const e=this.segments,n=t.segments,s=e.length;if(n.length!==s)return!1;for(let r=0;rt.toJSON())}serialize(){if(!this.isValid())throw new Error("Invalid path segments.");return this.segments.map(t=>t.serialize()).join(" ")}toString(){return this.serialize()}}(function(i){function t(e){return e!=null&&e instanceof i}i.isPath=t})(D||(D={})),function(i){function t(n){if(!n)return new i;const s=new i,r=/(?:[a-zA-Z] *)(?:(?:-?\d+(?:\.\d+)?(?:e[-+]?\d+)? *,? *)|(?:-?\.\d+ *,? *))+|(?:[a-zA-Z] *)(?! |\d|-|\.)/g,o=i.normalize(n).match(r);if(o!=null)for(let a=0,l=o.length;a+p),g=e.call(null,f,...d);s.appendSegment(g)}}return s}i.parse=t;function e(n,...s){if(n==="M")return Je.create.call(null,...s);if(n==="L")return xt.create.call(null,...s);if(n==="C")return Et.create.call(null,...s);if(n==="z"||n==="Z")return Xe.create();throw new Error(`Invalid path segment type "${n}"`)}i.createSegment=e}(D||(D={})),function(i){i.normalize=uy,i.isValid=ry,i.drawArc=ay,i.drawPoints=Ha,i.arcToCurves=xs}(D||(D={}));class st{constructor(t){this.options=Object.assign({},t),this.data=this.options.data||{},this.register=this.register.bind(this),this.unregister=this.unregister.bind(this)}get names(){return Object.keys(this.data)}register(t,e,n=!1){if(typeof t=="object"){Object.keys(t).forEach(o=>{this.register(o,t[o],e)});return}this.exist(t)&&!n&&!se.isApplyingHMR()&&this.onDuplicated(t);const s=this.options.process,r=s?R(s,this,t,e):e;return this.data[t]=r,r}unregister(t){const e=t?this.data[t]:null;return delete this.data[t],e}get(t){return t?this.data[t]:null}exist(t){return t?this.data[t]!=null:!1}onDuplicated(t){try{throw this.options.onConflict&&R(this.options.onConflict,this,t),new Error(`${is(this.options.type)} with name '${t}' already registered.`)}catch(e){throw e}}onNotFound(t,e){throw new Error(this.getSpellingSuggestion(t,e))}getSpellingSuggestion(t,e){const n=this.getSpellingSuggestionForName(t),s=e?`${e} ${Bp(this.options.type)}`:this.options.type;return`${is(s)} with name '${t}' does not exist.${n?` Did you mean '${n}'?`:""}`}getSpellingSuggestionForName(t){return um(t,Object.keys(this.data),e=>e)}}(function(i){function t(e){return new i(e)}i.create=t})(st||(st={}));const fy={color:"#aaaaaa",thickness:1,markup:"rect",update(i,t){const e=t.thickness*t.sx,n=t.thickness*t.sy;H(i,{width:e,height:n,rx:e,ry:n,fill:t.color})}},dy={color:"#aaaaaa",thickness:1,markup:"rect",update(i,t){const e=t.sx<=1?t.thickness*t.sx:t.thickness;H(i,{width:e,height:e,rx:e,ry:e,fill:t.color})}},gy={color:"rgba(224,224,224,1)",thickness:1,markup:"path",update(i,t){let e;const n=t.width,s=t.height,r=t.thickness;n-r>=0&&s-r>=0?e=["M",n,0,"H0 M0 0 V0",s].join(" "):e="M 0 0 0 0",H(i,{d:e,stroke:t.color,"stroke-width":t.thickness})}},py=[{color:"rgba(224,224,224,1)",thickness:1,markup:"path",update(i,t){let e;const n=t.width,s=t.height,r=t.thickness;n-r>=0&&s-r>=0?e=["M",n,0,"H0 M0 0 V0",s].join(" "):e="M 0 0 0 0",H(i,{d:e,stroke:t.color,"stroke-width":t.thickness})}},{color:"rgba(224,224,224,0.2)",thickness:3,factor:4,markup:"path",update(i,t){let e;const n=t.factor||1,s=t.width*n,r=t.height*n,o=t.thickness;s-o>=0&&r-o>=0?e=["M",s,0,"H0 M0 0 V0",r].join(" "):e="M 0 0 0 0",t.width=s,t.height=r,H(i,{d:e,stroke:t.color,"stroke-width":t.thickness})}}];var my=Object.freeze({__proto__:null,dot:fy,fixedDot:dy,mesh:gy,doubleMesh:py});class oe{constructor(){this.patterns={},this.root=$.create(fs(),{width:"100%",height:"100%"},[Jt("defs")]).node}add(t,e){const n=this.root.childNodes[0];n&&n.appendChild(e),this.patterns[t]=e,$.create("rect",{width:"100%",height:"100%",fill:`url(#${t})`}).appendTo(this.root)}get(t){return this.patterns[t]}has(t){return this.patterns[t]!=null}}(function(i){i.presets=my,i.registry=st.create({type:"grid"}),i.registry.register(i.presets,!0)})(oe||(oe={}));const Ua=function(i){const t=document.createElement("canvas"),e=i.width,n=i.height;t.width=e*2,t.height=n;const s=t.getContext("2d");return s.drawImage(i,0,0,e,n),s.translate(2*e,0),s.scale(-1,1),s.drawImage(i,0,0,e,n),t},Wa=function(i){const t=document.createElement("canvas"),e=i.width,n=i.height;t.width=e,t.height=n*2;const s=t.getContext("2d");return s.drawImage(i,0,0,e,n),s.translate(0,2*n),s.scale(1,-1),s.drawImage(i,0,0,e,n),t},Xa=function(i){const t=document.createElement("canvas"),e=i.width,n=i.height;t.width=2*e,t.height=2*n;const s=t.getContext("2d");return s.drawImage(i,0,0,e,n),s.setTransform(-1,0,0,-1,t.width,t.height),s.drawImage(i,0,0,e,n),s.setTransform(-1,0,0,1,t.width,0),s.drawImage(i,0,0,e,n),s.setTransform(1,0,0,-1,0,t.height),s.drawImage(i,0,0,e,n),t},yy=function(i,t){const e=i.width,n=i.height,s=document.createElement("canvas");s.width=e*3,s.height=n*3;const r=s.getContext("2d"),o=t.angle!=null?-t.angle:-20,a=q.toRad(o),l=s.width/4,c=s.height/4;for(let h=0;h<4;h+=1)for(let u=0;u<4;u+=1)(h+u)%2>0&&(r.setTransform(1,0,0,1,(2*h-1)*l,(2*u-1)*c),r.rotate(a),r.drawImage(i,-e/2,-n/2,e,n));return s};var by=Object.freeze({__proto__:null,flipX:Ua,flipY:Wa,flipXY:Xa,watermark:yy}),kn;(function(i){i.presets=Object.assign({},by),i.presets["flip-x"]=Ua,i.presets["flip-y"]=Wa,i.presets["flip-xy"]=Xa,i.registry=st.create({type:"background pattern"}),i.registry.register(i.presets,!0)})(kn||(kn={}));function ki(i,t){return i!=null?i:t}function dt(i,t){return i!=null&&Number.isFinite(i)?i:t}function xy(i={}){const t=ki(i.color,"blue"),e=dt(i.width,1),n=dt(i.margin,2),s=dt(i.opacity,1),r=n,o=n+e;return` + + + + + + + + + + + + `.trim()}function vy(i={}){const t=ki(i.color,"red"),e=dt(i.blur,0),n=dt(i.width,1),s=dt(i.opacity,1);return` + + + + + + + + `.trim()}function wy(i={}){const t=dt(i.x,2);return` + + + + `.trim()}function Py(i={}){const t=dt(i.dx,0),e=dt(i.dy,0),n=ki(i.color,"black"),s=dt(i.blur,4),r=dt(i.opacity,1);return"SVGFEDropShadowElement"in window?` + + `.trim():` + + + + + + + + + + + + `.trim()}function Ay(i={}){const t=dt(i.amount,1),e=.2126+.7874*(1-t),n=.7152-.7152*(1-t),s=.0722-.0722*(1-t),r=.2126-.2126*(1-t),o=.7152+.2848*(1-t),a=.0722-.0722*(1-t),l=.2126-.2126*(1-t),c=.0722+.9278*(1-t);return` + + + + `.trim()}function Cy(i={}){const t=dt(i.amount,1),e=.393+.607*(1-t),n=.769-.769*(1-t),s=.189-.189*(1-t),r=.349-.349*(1-t),o=.686+.314*(1-t),a=.168-.168*(1-t),l=.272-.272*(1-t),c=.534-.534*(1-t),h=.131+.869*(1-t);return` + + + + `.trim()}function Sy(i={}){const t=dt(i.amount,1);return` + + + + `.trim()}function Oy(i={}){return` + + + + `.trim()}function Ey(i={}){const t=dt(i.amount,1),e=1-t;return` + + + + + + + + `.trim()}function My(i={}){const t=dt(i.amount,1);return` + + + + + + + + `.trim()}function Ty(i={}){const t=dt(i.amount,1),e=.5-t/2;return` + + + + + + + + `.trim()}var Ny=Object.freeze({__proto__:null,outline:xy,highlight:vy,blur:wy,dropShadow:Py,grayScale:Ay,sepia:Cy,saturate:Sy,hueRotate:Oy,invert:Ey,brightness:My,contrast:Ty}),Ye;(function(i){i.presets=Ny,i.registry=st.create({type:"filter"}),i.registry.register(i.presets,!0)})(Ye||(Ye={}));const Ly={xlinkHref:"xlink:href",xlinkShow:"xlink:show",xlinkRole:"xlink:role",xlinkType:"xlink:type",xlinkArcrole:"xlink:arcrole",xlinkTitle:"xlink:title",xlinkActuate:"xlink:actuate",xmlSpace:"xml:space",xmlBase:"xml:base",xmlLang:"xml:lang",preserveAspectRatio:"preserveAspectRatio",requiredExtension:"requiredExtension",requiredFeatures:"requiredFeatures",systemLanguage:"systemLanguage",externalResourcesRequired:"externalResourceRequired"},Iy={},Ja={position:Ps("x","width","origin")},Ya={position:Ps("y","height","origin")},jy={position:Ps("x","width","corner")},Dy={position:Ps("y","height","corner")},Za={set:ae("width","width")},Ka={set:ae("height","height")},$y={set:ae("rx","width")},Ry={set:ae("ry","height")},Qa={set:(i=>{const t=ae(i,"width"),e=ae(i,"height");return function(n,s){const r=s.refBBox,o=r.height>r.width?t:e;return R(o,this,n,s)}})("r")},ky={set(i,{refBBox:t}){let e=parseFloat(i);const n=Wt(i);n&&(e/=100);const s=Math.sqrt(t.height*t.height+t.width*t.width);let r;return Number.isFinite(e)&&(n||e>=0&&e<=1?r=e*s:r=Math.max(e+s,0)),{r}}},By={set:ae("cx","width")},zy={set:ae("cy","height")},tl={set:sl({resetOffset:!0})},Vy={set:sl({resetOffset:!1})},el={set:il({resetOffset:!0})},Fy={set:il({resetOffset:!1})},_y=Qa,Hy=tl,qy=el,Gy=Ja,Uy=Ya,Wy=Za,Xy=Ka;function Ps(i,t,e){return(n,{refBBox:s})=>{if(n==null)return null;let r=parseFloat(n);const o=Wt(n);o&&(r/=100);let a;if(Number.isFinite(r)){const c=s[e];o||r>0&&r<1?a=c[i]+s[t]*r:a=c[i]+r}const l=new v;return l[i]=a||0,l}}function ae(i,t){return function(e,{refBBox:n}){let s=parseFloat(e);const r=Wt(e);r&&(s/=100);const o={};if(Number.isFinite(s)){const a=r||s>=0&&s<=1?s*n[t]:Math.max(s+n[t],0);o[i]=a}return o}}function nl(i,t){const e="x6-shape",n=t&&t.resetOffset;return function(s,{elem:r,refBBox:o}){let a=we(r,e);if(!a||a.value!==s){const p=i(s);a={value:s,shape:p,shapeBBox:p.bbox()},we(r,e,a)}const l=a.shape.clone(),c=a.shapeBBox.clone(),h=c.getOrigin(),u=o.getOrigin();c.x=u.x,c.y=u.y;const f=o.getMaxScaleToFit(c,u),d=c.width===0||o.width===0?1:f.sx,g=c.height===0||o.height===0?1:f.sy;return l.scale(d,g,h),n&&l.translate(-h.x,-h.y),l}}function sl(i){function t(n){return D.parse(n)}const e=nl(t,i);return(n,s)=>({d:e(n,s).serialize()})}function il(i){const t=nl(e=>new nt(e),i);return(e,n)=>({points:t(e,n).serialize()})}const Jy={qualify:$t,set(i,{view:t}){return`url(#${t.graph.defineGradient(i)})`}},Yy={qualify:$t,set(i,{view:t}){const e=t.cell,n=Object.assign({},i);if(e.isEdge()&&n.type==="linearGradient"){const s=t,r=s.sourcePoint,o=s.targetPoint;n.id=`gradient-${n.type}-${e.id}`,n.attrs=Object.assign(Object.assign({},n.attrs),{x1:r.x,y1:r.y,x2:o.x,y2:o.y,gradientUnits:"userSpaceOnUse"}),t.graph.defs.remove(n.id)}return`url(#${t.graph.defineGradient(n)})`}},rl={qualify(i,{attrs:t}){return t.textWrap==null||!$t(t.textWrap)},set(i,{view:t,elem:e,attrs:n}){const s="x6-text",r=we(e,s),o=h=>{try{return JSON.parse(h)}catch(u){return h}},a={x:n.x,eol:n.eol,annotations:o(n.annotations),textPath:o(n["text-path"]||n.textPath),textVerticalAnchor:n["text-vertical-anchor"]||n.textVerticalAnchor,displayEmpty:(n["display-empty"]||n.displayEmpty)==="true",lineHeight:n["line-height"]||n.lineHeight},l=n["font-size"]||n.fontSize,c=JSON.stringify([i,a]);if(l&&e.setAttribute("font-size",l),r==null||r!==c){const h=a.textPath;if(h!=null&&typeof h=="object"){const u=h.selector;if(typeof u=="string"){const f=t.find(u)[0];f instanceof SVGPathElement&&(wi(f),a.textPath=Object.assign({"xlink:href":`#${f.id}`},h))}}Ia(e,`${i}`,a),we(e,s,c)}}},Zy={qualify:$t,set(i,{view:t,elem:e,attrs:n,refBBox:s}){const r=i,o=r.width||0;Wt(o)?s.width*=parseFloat(o)/100:o<=0?s.width+=o:s.width=o;const a=r.height||0;Wt(a)?s.height*=parseFloat(a)/100:a<=0?s.height+=a:s.height=a;let l,c=r.text;c==null&&(c=n.text),c!=null?l=Rm(`${c}`,s,{"font-weight":n["font-weight"]||n.fontWeight,"font-size":n["font-size"]||n.fontSize,"font-family":n["font-family"]||n.fontFamily,lineHeight:n.lineHeight},{ellipsis:r.ellipsis}):l="",R(rl.set,this,l,{view:t,elem:e,attrs:n,refBBox:s,cell:t.cell})}},Ze=(i,{attrs:t})=>t.text!==void 0,Ky={qualify:Ze},Qy={qualify:Ze},tb={qualify:Ze},eb={qualify:Ze},nb={qualify:Ze},sb={qualify:Ze},ib={qualify(i,{elem:t}){return t instanceof SVGElement},set(i,{elem:t}){const e="x6-title",n=`${i}`,s=we(t,e);if(s==null||s!==n){we(t,e,n);const r=t.firstChild;if(r&&r.tagName.toUpperCase()==="TITLE"){const o=r;o.textContent=n}else{const o=document.createElementNS(t.namespaceURI,"title");o.textContent=n,t.insertBefore(o,r)}}}},rb={offset:ol("x","width","right")},ob={offset:ol("y","height","bottom")},ab={offset(i,{refBBox:t}){return i?{x:-t.x,y:-t.y}:{x:0,y:0}}};function ol(i,t,e){return(n,{refBBox:s})=>{const r=new v;let o;return n==="middle"?o=s[t]/2:n===e?o=s[t]:typeof n=="number"&&Number.isFinite(n)?o=n>-1&&n<1?-s[t]*n:-n:Wt(n)?o=s[t]*parseFloat(n)/100:o=0,r[i]=-(s[i]+o),r}}const lb={qualify:$t,set(i,{elem:t}){Ge(t,i)}},cb={set(i,{elem:t}){t.innerHTML=`${i}`}},hb={qualify:$t,set(i,{view:t}){return`url(#${t.graph.defineFilter(i)})`}},ub={set(i){return i!=null&&typeof i=="object"&&i.id?i.id:i}};function Se(i,t,e){let n,s;typeof t=="object"?(n=t.x,s=t.y):(n=t,s=e);const r=D.parse(i),o=r.bbox();if(o){let a=-o.height/2-o.y,l=-o.width/2-o.x;typeof n=="number"&&(l-=n),typeof s=="number"&&(a-=s),r.translate(l,a)}return r.serialize()}var al=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{size:t,width:e,height:n,offset:s,open:r}=i,o=al(i,["size","width","height","offset","open"]);return ll({size:t,width:e,height:n,offset:s},r===!0,!0,void 0,o)},db=i=>{var{size:t,width:e,height:n,offset:s,factor:r}=i,o=al(i,["size","width","height","offset","factor"]);return ll({size:t,width:e,height:n,offset:s},!1,!1,r,o)};function ll(i,t,e,n=3/4,s={}){const r=i.size||10,o=i.width||r,a=i.height||r,l=new D,c={};if(t)l.moveTo(o,0).lineTo(0,a/2).lineTo(o,a),c.fill="none";else{if(l.moveTo(0,a/2),l.lineTo(o,0),!e){const h=Ct(n,0,1);l.lineTo(o*h,a/2)}l.lineTo(o,a),l.close()}return Object.assign(Object.assign(Object.assign({},c),s),{tagName:"path",d:Se(l.serialize(),{x:i.offset!=null?i.offset:-o/2})})}var gb=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{size:t,width:e,height:n,offset:s}=i,r=gb(i,["size","width","height","offset"]);const o=t||10,a=e||o,l=n||o,c=new D;return c.moveTo(0,l/2).lineTo(a/2,0).lineTo(a,l/2).lineTo(a/2,l).close(),Object.assign(Object.assign({},r),{tagName:"path",d:Se(c.serialize(),s==null?-a/2:s)})};var mb=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{d:t,offsetX:e,offsetY:n}=i,s=mb(i,["d","offsetX","offsetY"]);return Object.assign(Object.assign({},s),{tagName:"path",d:Se(t,e,n)})};var bb=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{size:t,width:e,height:n,offset:s}=i,r=bb(i,["size","width","height","offset"]);const o=t||10,a=e||o,l=n||o,c=new D;return c.moveTo(0,0).lineTo(a,l).moveTo(0,l).lineTo(a,0),Object.assign(Object.assign({},r),{tagName:"path",fill:"none",d:Se(c.serialize(),s||-a/2)})};var vb=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{width:t,height:e,offset:n,open:s,flip:r}=i,o=vb(i,["width","height","offset","open","flip"]);let a=e||6;const l=t||10,c=s===!0,h=r===!0,u=Object.assign(Object.assign({},o),{tagName:"path"});h&&(a=-a);const f=new D;return f.moveTo(0,a).lineTo(l,0),c?u.fill="none":(f.lineTo(l,a),f.close()),u.d=Se(f.serialize(),{x:n||-l/2,y:a/2}),u};var cl=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{r:t}=i,e=cl(i,["r"]);const n=t||5;return Object.assign(Object.assign({cx:n},e),{tagName:"circle",r:n})},Pb=i=>{var{r:t}=i,e=cl(i,["r"]);const n=t||5,s=new D;return s.moveTo(n,0).lineTo(n,n*2),s.moveTo(0,n).lineTo(n*2,n),{children:[Object.assign(Object.assign({},hl({r:n})),{fill:"none"}),Object.assign(Object.assign({},e),{tagName:"path",d:Se(s.serialize(),-n)})]}};var Ab=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var{rx:t,ry:e}=i,n=Ab(i,["rx","ry"]);const s=t||5,r=e||5;return Object.assign(Object.assign({cx:s},n),{tagName:"ellipse",rx:s,ry:r})};var Sb=Object.freeze({__proto__:null,block:fb,classic:db,diamond:pb,path:yb,cross:xb,async:wb,circle:hl,circlePlus:Pb,ellipse:Cb}),le;(function(i){i.presets=Sb,i.registry=st.create({type:"marker"}),i.registry.register(i.presets,!0)})(le||(le={})),function(i){i.normalize=Se}(le||(le={}));var Ob=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s1){const o=Math.ceil(r/2);e.refX=t==="marker-start"?o:-o}}return e}const Bn=(i,{view:t})=>t.cell.isEdge(),Lb={qualify:Bn,set(i,t){var e,n,s,r;const o=t.view,a=i.reverse||!1,l=i.stubs||0;let c;if(Number.isFinite(l)&&l!==0)if(a){let h,u;const f=o.getConnectionLength()||0;l<0?(h=(f+l)/2,u=-l):(h=l,u=f-l*2);const d=o.getConnection();c=(r=(s=(n=(e=d==null?void 0:d.divideAtLength(h))===null||e===void 0?void 0:e[1])===null||n===void 0?void 0:n.divideAtLength(u))===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.serialize()}else{let h;l<0?h=((o.getConnectionLength()||0)+l)/2:h=l;const u=o.getConnection();if(u){const f=u.divideAtLength(h),d=u.divideAtLength(-h);f&&d&&(c=`${f[0].serialize()} ${d[1].serialize()}`)}}return{d:c||o.getConnectionPathData()}}},ul={qualify:Bn,set:As("getTangentAtLength",{rotate:!0})},Ib={qualify:Bn,set:As("getTangentAtLength",{rotate:!1})},fl={qualify:Bn,set:As("getTangentAtRatio",{rotate:!0})},jb={qualify:Bn,set:As("getTangentAtRatio",{rotate:!1})},Db=ul,$b=fl;function As(i,t){const e={x:1,y:0};return(n,s)=>{let r,o;const a=s.view,l=a[i](Number(n));return l?(o=t.rotate?l.vector().vectorAngle(e):0,r=l.start):(r=a.path.start,o=0),o===0?{transform:`translate(${r.x},${r.y}')`}:{transform:`translate(${r.x},${r.y}') rotate(${o})`}}}var Rb=Object.freeze({__proto__:null,ref:Iy,refX:Ja,refY:Ya,refDx:jy,refDy:Dy,refWidth:Za,refHeight:Ka,refRx:$y,refRy:Ry,refRInscribed:Qa,refRCircumscribed:ky,refCx:By,refCy:zy,refDResetOffset:tl,refDKeepOffset:Vy,refPointsResetOffset:el,refPointsKeepOffset:Fy,refR:_y,refD:Hy,refPoints:qy,refX2:Gy,refY2:Uy,refWidth2:Wy,refHeight2:Xy,fill:Jy,stroke:Yy,text:rl,textWrap:Zy,lineHeight:Ky,textVerticalAnchor:Qy,textPath:tb,annotations:eb,eol:nb,displayEmpty:sb,title:ib,xAlign:rb,yAlign:ob,resetOffset:ab,style:lb,html:cb,filter:hb,port:ub,sourceMarker:Eb,targetMarker:Mb,vertexMarker:Tb,connection:Lb,atConnectionLengthKeepGradient:ul,atConnectionLengthIgnoreGradient:Ib,atConnectionRatioKeepGradient:fl,atConnectionRatioIgnoreGradient:jb,atConnectionLength:Db,atConnectionRatio:$b}),Bt;(function(i){function t(e,n,s){return!!(e!=null&&(typeof e=="string"||typeof e.qualify!="function"||R(e.qualify,this,n,s)))}i.isValidDefinition=t})(Bt||(Bt={})),function(i){i.presets=Object.assign(Object.assign({},Ly),Rb),i.registry=st.create({type:"attribute definition"}),i.registry.register(i.presets,!0)}(Bt||(Bt={}));const gt={prefixCls:"x6",autoInsertCSS:!0,useCSSSelector:!0,prefix(i){return`${gt.prefixCls}-${i}`}},dl=gt.prefix("highlighted"),kb={highlight(i,t,e){const n=e&&e.className||dl;V(t,n)},unhighlight(i,t,e){const n=e&&e.className||dl;St(t,n)}},gl=gt.prefix("highlight-opacity"),Bb={highlight(i,t){V(t,gl)},unhighlight(i,t){St(t,gl)}};var _;(function(i){const t=Jt("svg");function e(d,g){const p=Wm(d.x,d.y).matrixTransform(g);return new v(p.x,p.y)}i.transformPoint=e;function n(d,g){return new I(e(d.start,g),e(d.end,g))}i.transformLine=n;function s(d,g){let p=d instanceof nt?d.points:d;return Array.isArray(p)||(p=[]),new nt(p.map(m=>e(m,g)))}i.transformPolyline=s;function r(d,g){const p=t.createSVGPoint();p.x=d.x,p.y=d.y;const m=p.matrixTransform(g);p.x=d.x+d.width,p.y=d.y;const y=p.matrixTransform(g);p.x=d.x+d.width,p.y=d.y+d.height;const x=p.matrixTransform(g);p.x=d.x,p.y=d.y+d.height;const b=p.matrixTransform(g),w=Math.min(m.x,y.x,x.x,b.x),P=Math.max(m.x,y.x,x.x,b.x),A=Math.min(m.y,y.y,x.y,b.y),S=Math.max(m.y,y.y,x.y,b.y);return new M(w,A,P-w,S-A)}i.transformRectangle=r;function o(d,g,p){let m;const y=d.ownerSVGElement;if(!y)return new M(0,0,0,0);try{m=d.getBBox()}catch(b){m={x:d.clientLeft,y:d.clientTop,width:d.clientWidth,height:d.clientHeight}}if(g)return M.create(m);const x=Ln(d,p||y);return r(m,x)}i.bbox=o;function a(d,g={}){let p;if(!d.ownerSVGElement||!ie(d)){if(va(d)){const{left:b,top:w,width:P,height:A}=l(d);return new M(b,w,P,A)}return new M(0,0,0,0)}let y=g.target;if(!g.recursive){try{p=d.getBBox()}catch(w){p={x:d.clientLeft,y:d.clientTop,width:d.clientWidth,height:d.clientHeight}}if(!y)return M.create(p);const b=Ln(d,y);return r(p,b)}{const b=d.childNodes,w=b.length;if(w===0)return a(d,{target:y});y||(y=d);for(let P=0;P{const m=d.getAttribute(p),y=m?parseFloat(m):0;return Number.isNaN(y)?0:y};switch(d instanceof SVGElement&&d.nodeName.toLowerCase()){case"rect":return new M(g("x"),g("y"),g("width"),g("height"));case"circle":return new It(g("cx"),g("cy"),g("r"),g("r"));case"ellipse":return new It(g("cx"),g("cy"),g("rx"),g("ry"));case"polyline":{const p=ps(d);return new nt(p)}case"polygon":{const p=ps(d);return p.length>1&&p.push(p[0]),new nt(p)}case"path":{let p=d.getAttribute("d");return D.isValid(p)||(p=D.normalize(p)),D.parse(p)}case"line":return new I(g("x1"),g("y1"),g("x2"),g("y2"))}return a(d)}i.toGeometryShape=c;function h(d,g,p,m){const y=v.create(g),x=v.create(p);m||(m=d instanceof SVGSVGElement?d:d.ownerSVGElement);const b=ji(d);d.setAttribute("transform","");const w=a(d,{target:m}).scale(b.sx,b.sy),P=Tn();P.setTranslate(-w.x-w.width/2,-w.y-w.height/2);const A=Tn(),S=y.angleBetween(x,y.clone().translate(1,0));S&&A.setRotate(S,0,0);const E=Tn(),N=y.clone().move(x,w.width/2);E.setTranslate(2*y.x-N.x,2*y.y-N.y);const L=Ln(d,m),T=Tn();T.setMatrix(E.matrix.multiply(A.matrix.multiply(P.matrix.multiply(L.scale(b.sx,b.sy))))),d.setAttribute("transform",Ue(T.matrix))}i.translateAndAutoOrient=h;function u(d){if(d==null)return null;let g=d;do{let p=g.tagName;if(typeof p!="string")return null;if(p=p.toUpperCase(),He(g,"x6-port"))g=g.nextElementSibling;else if(p==="G")g=g.firstElementChild;else if(p==="TITLE")g=g.nextElementSibling;else break}while(g);return g}i.findShapeNode=u;function f(d){const g=u(d);if(!ie(g)){if(va(d)){const{left:m,top:y,width:x,height:b}=l(d);return new M(m,y,x,b)}return new M(0,0,0,0)}return c(g).bbox()||M.create()}i.getBBoxV2=f})(_||(_={}));const zb={padding:3,rx:0,ry:0,attrs:{"stroke-width":3,stroke:"#FEB663"}},Vb={highlight(i,t,e){const n=ce.getHighlighterId(t,e);if(ce.hasCache(n))return;e=Bo({},e,zb);const s=$.create(t);let r,o;try{r=s.toPathData()}catch(h){o=_.bbox(s.node,!0),r=$a(Object.assign(Object.assign({},e),o))}const a=Jt("path");if(H(a,Object.assign({d:r,"pointer-events":"none","vector-effect":"non-scaling-stroke",fill:"none"},e.attrs?En(e.attrs):null)),i.isEdgeElement(t))H(a,"d",i.getConnectionPathData());else{let h=s.getTransformToElement(i.container);const u=e.padding;if(u){o==null&&(o=_.bbox(s.node,!0));const f=o.x+o.width/2,d=o.y+o.height/2;o=_.transformRectangle(o,h);const g=Math.max(o.width,1),p=Math.max(o.height,1),m=(g+u)/g,y=(p+u)/p,x=ft({a:m,b:0,c:0,d:y,e:f-m*f,f:d-y*d});h=h.multiply(x)}We(a,h)}V(a,gt.prefix("highlight-stroke"));const l=i.cell,c=()=>ce.removeHighlighter(n);l.on("removed",c),l.model&&l.model.on("reseted",c),i.container.appendChild(a),ce.setCache(n,a)},unhighlight(i,t,e){ce.removeHighlighter(ce.getHighlighterId(t,e))}};var ce;(function(i){function t(o,a){return wi(o),o.id+JSON.stringify(a)}i.getHighlighterId=t;const e={};function n(o,a){e[o]=a}i.setCache=n;function s(o){return e[o]!=null}i.hasCache=s;function r(o){const a=e[o];a&&(qe(a),delete e[o])}i.removeHighlighter=r})(ce||(ce={}));var Fb=Object.freeze({__proto__:null,className:kb,opacity:Bb,stroke:Vb}),Zt;(function(i){function t(e,n){if(typeof n.highlight!="function")throw new Error(`Highlighter '${e}' is missing required \`highlight()\` method`);if(typeof n.unhighlight!="function")throw new Error(`Highlighter '${e}' is missing required \`unhighlight()\` method`)}i.check=t})(Zt||(Zt={})),function(i){i.presets=Fb,i.registry=st.create({type:"highlighter"}),i.registry.register(i.presets,!0)}(Zt||(Zt={}));function Vi(i,t={}){return new v(Xt(t.x,i.width),Xt(t.y,i.height))}function Fi(i,t,e){return Object.assign({angle:t,position:i.toJSON()},e)}const _b=(i,t)=>i.map(({x:e,y:n,angle:s})=>Fi(Vi(t,{x:e,y:n}),s||0)),Hb=(i,t,e)=>{const n=e.start||0,s=e.step||20;return pl(i,t,n,(r,o)=>(r+.5-o/2)*s)},qb=(i,t,e)=>{const n=e.start||0,s=e.step||360/i.length;return pl(i,t,n,r=>r*s)};function pl(i,t,e,n){const s=t.getCenter(),r=t.getTopCenter(),o=t.width/t.height,a=It.fromRect(t),l=i.length;return i.map((c,h)=>{const u=e+n(h,l),f=r.clone().rotate(-u,s).scale(o,1,s),d=c.compensateRotate?-a.tangentTheta(f):0;return(c.dx||c.dy)&&f.translate(c.dx||0,c.dy||0),c.dr&&f.move(s,c.dr),Fi(f.round(),d,c)})}var Gb=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const n=Vi(t,e.start||t.getOrigin()),s=Vi(t,e.end||t.getCorner());return zn(i,n,s,e)},Wb=(i,t,e)=>zn(i,t.getTopLeft(),t.getBottomLeft(),e),Xb=(i,t,e)=>zn(i,t.getTopRight(),t.getBottomRight(),e),Jb=(i,t,e)=>zn(i,t.getTopLeft(),t.getTopRight(),e),Yb=(i,t,e)=>zn(i,t.getBottomLeft(),t.getBottomRight(),e);function zn(i,t,e,n){const s=new I(t,e),r=i.length;return i.map((o,a)=>{var{strict:l}=o,c=Gb(o,["strict"]);const h=l||n.strict?(a+1)/(r+1):(a+.5)/r,u=s.pointAt(h);return(c.dx||c.dy)&&u.translate(c.dx||0,c.dy||0),Fi(u.round(),0,c)})}var Zb=Object.freeze({__proto__:null,absolute:_b,ellipse:Hb,ellipseSpread:qb,line:Ub,left:Wb,right:Xb,top:Jb,bottom:Yb}),Oe;(function(i){i.presets=Zb,i.registry=st.create({type:"port layout"}),i.registry.register(i.presets,!0)})(Oe||(Oe={}));const Kb={position:{x:0,y:0},angle:0,attrs:{".":{y:"0","text-anchor":"start"}}};function he(i,t){const{x:e,y:n,angle:s,attrs:r}=t||{};return Bo({},{angle:s,attrs:r,position:{x:e,y:n}},i,Kb)}const Qb=(i,t,e)=>he({position:t.getTopLeft()},e),t0=(i,t,e)=>he({position:{x:-15,y:0},attrs:{".":{y:".3em","text-anchor":"end"}}},e),e0=(i,t,e)=>he({position:{x:15,y:0},attrs:{".":{y:".3em","text-anchor":"start"}}},e),n0=(i,t,e)=>he({position:{x:0,y:-15},attrs:{".":{"text-anchor":"middle"}}},e),s0=(i,t,e)=>he({position:{x:0,y:15},attrs:{".":{y:".6em","text-anchor":"middle"}}},e),i0=(i,t,e)=>ml(i,t,!1,e),r0=(i,t,e)=>ml(i,t,!0,e),o0=(i,t,e)=>yl(i,t,!1,e),a0=(i,t,e)=>yl(i,t,!0,e);function ml(i,t,e,n){const s=n.offset!=null?n.offset:15,r=t.getCenter().theta(i),o=bl(t);let a,l,c,h,u=0;return ro[2]?(a=".3em",l=s,c=0,h="start"):ro[2]?(a=".3em",l=-s,c=0,h="end"):rxl(i.diff(t.getCenter()),!1,e),c0=(i,t,e)=>xl(i.diff(t.getCenter()),!0,e);function xl(i,t,e){const n=e.offset!=null?e.offset:20,s=new v(0,0),r=-i.theta(s),o=i.clone().move(s,n).diff(i).round();let a=".3em",l,c=r;return(r+90)%180==0?(l=t?"end":"middle",!t&&r===-270&&(a="0em")):r>-270&&r<-90?(l="start",c=r-180):l="end",he({position:o.round().toJSON(),angle:t?c:0,attrs:{".":{y:a,"text-anchor":l}}},e)}var h0=Object.freeze({__proto__:null,manual:Qb,left:t0,right:e0,top:n0,bottom:s0,outside:i0,outsideOriented:r0,inside:o0,insideOriented:a0,radial:l0,radialOriented:c0}),Ke;(function(i){i.presets=h0,i.registry=st.create({type:"port label layout"}),i.registry.register(i.presets,!0)})(Ke||(Ke={}));class Z extends Pt{constructor(){super();this.cid=_i.uniqueId(),Z.views[this.cid]=this}get priority(){return 2}confirmUpdate(t,e){return 0}empty(t=this.container){return Sn(t),this}unmount(t=this.container){return qe(t),this}remove(t=this.container){return t===this.container&&(this.removeEventListeners(document),this.onRemove(),delete Z.views[this.cid]),this.unmount(t),this}onRemove(){}setClass(t,e=this.container){e.classList.value=Array.isArray(t)?t.join(" "):t}addClass(t,e=this.container){return V(e,Array.isArray(t)?t.join(" "):t),this}removeClass(t,e=this.container){return St(e,Array.isArray(t)?t.join(" "):t),this}setStyle(t,e=this.container){return Ge(e,t),this}setAttrs(t,e=this.container){return t!=null&&e!=null&&H(e,t),this}findAttr(t,e=this.container){let n=e;for(;n&&n.nodeType===1;){const s=n.getAttribute(t);if(s!=null)return s;if(n===this.container)return null;n=n.parentNode}return null}find(t,e=this.container,n=this.selectors){return Z.find(t,e,n).elems}findOne(t,e=this.container,n=this.selectors){const s=this.find(t,e,n);return s.length>0?s[0]:null}findByAttr(t,e=this.container){let n=e;for(;n&&n.getAttribute;){const s=n.getAttribute(t);if((s!=null||n===this.container)&&s!=="false")return n;n=n.parentNode}return null}getSelector(t,e){let n;if(t===this.container)return typeof e=="string"&&(n=`> ${e}`),n;if(t){const s=Ai(t)+1;n=`${t.tagName.toLowerCase()}:nth-child(${s})`,e&&(n+=` > ${e}`),n=this.getSelector(t.parentNode,n)}return n}prefixClassName(t){return gt.prefix(t)}delegateEvents(t,e){if(t==null)return this;e||this.undelegateEvents();const n=/^(\S+)\s*(.*)$/;return Object.keys(t).forEach(s=>{const r=s.match(n);if(r==null)return;const o=this.getEventHandler(t[s]);typeof o=="function"&&this.delegateEvent(r[1],r[2],o)}),this}undelegateEvents(){return vt.off(this.container,this.getEventNamespace()),this}delegateDocumentEvents(t,e){return this.addEventListeners(document,t,e),this}undelegateDocumentEvents(){return this.removeEventListeners(document),this}delegateEvent(t,e,n){return vt.on(this.container,t+this.getEventNamespace(),e,n),this}undelegateEvent(t,e,n){const s=t+this.getEventNamespace();return e==null?vt.off(this.container,s):typeof e=="string"?vt.off(this.container,s,e,n):vt.off(this.container,s,e),this}addEventListeners(t,e,n){if(e==null)return this;const s=this.getEventNamespace();return Object.keys(e).forEach(r=>{const o=this.getEventHandler(e[r]);typeof o=="function"&&vt.on(t,r+s,n,o)}),this}removeEventListeners(t){return t!=null&&vt.off(t,this.getEventNamespace()),this}getEventNamespace(){return`.${gt.prefixCls}-event-${this.cid}`}getEventHandler(t){let e;if(typeof t=="string"){const n=this[t];typeof n=="function"&&(e=(...s)=>n.call(this,...s))}else e=(...n)=>t.call(this,...n);return e}getEventTarget(t,e={}){const{target:n,type:s,clientX:r=0,clientY:o=0}=t;return e.fromPoint||s==="touchmove"||s==="touchend"?document.elementFromPoint(r,o):n}stopPropagation(t){return this.setEventData(t,{propagationStopped:!0}),this}isPropagationStopped(t){return this.getEventData(t).propagationStopped===!0}getEventData(t){return this.eventData(t)}setEventData(t,e){return this.eventData(t,e)}eventData(t,e){if(t==null)throw new TypeError("Event object required");let n=t.data;const s=`__${this.cid}__`;return e==null?n==null?{}:n[s]||{}:(n==null&&(n=t.data={}),n[s]==null?n[s]=Object.assign({},e):n[s]=Object.assign(Object.assign({},n[s]),e),n[s])}normalizeEvent(t){return Z.normalizeEvent(t)}}(function(i){function t(s,r){return r?Jt(s||"g"):Pi(s||"div")}i.createElement=t;function e(s,r,o){if(!s||s===".")return{elems:[r]};if(o){const a=o[s];if(a)return{elems:Array.isArray(a)?a:[a]}}if(gt.useCSSSelector){const a=s.includes(">")?`:scope ${s}`:s;return{isCSSSelector:!0,elems:Array.prototype.slice.call(r.querySelectorAll(a))}}return{elems:[]}}i.find=e;function n(s){let r=s;const o=s.originalEvent,a=o&&o.changedTouches&&o.changedTouches[0];if(a){for(const c in s)a[c]===void 0&&(a[c]=s[c]);r=a}const l=r.target;if(l){const c=l.correspondingUseElement;c&&(r.target=c)}return r}i.normalizeEvent=n})(Z||(Z={})),function(i){i.views={};function t(e){return i.views[e]||null}i.getView=t}(Z||(Z={}));var _i;(function(i){let t=0;function e(){const n=`v${t}`;return t+=1,n}i.uniqueId=e})(_i||(_i={}));class u0{constructor(t){this.view=t,this.clean()}clean(){this.elemCache&&this.elemCache.dispose(),this.elemCache=new $i,this.pathCache={}}get(t){return this.elemCache.has(t)||this.elemCache.set(t,{}),this.elemCache.get(t)}getData(t){const e=this.get(t);return e.data||(e.data={}),e.data}getMatrix(t){const e=this.get(t);if(e.matrix==null){const n=this.view.container;e.matrix=Km(t,n)}return ft(e.matrix)}getShape(t){const e=this.get(t);return e.shape==null&&(e.shape=_.toGeometryShape(t)),e.shape.clone()}getBoundingRect(t){const e=this.get(t);return e.boundingRect==null&&(e.boundingRect=_.getBBoxV2(t)),e.boundingRect.clone()}}var X;(function(i){function t(c){return c!=null&&!e(c)}i.isJSONMarkup=t;function e(c){return c!=null&&typeof c=="string"}i.isStringMarkup=e;function n(c){return c==null||e(c)?c:tt(c)}i.clone=n;function s(c){return`${c}`.trim().replace(/[\r|\n]/g," ").replace(/>\s+<")}i.sanitize=s;function r(c,h={ns:ut.svg}){const u=document.createDocumentFragment(),f={},d={},g=[{markup:Array.isArray(c)?c:[c],parent:u,ns:h.ns}];for(;g.length>0;){const p=g.pop();let m=p.ns||ut.svg;const y=p.markup,x=p.parent;y.forEach(b=>{const w=b.tagName;if(!w)throw new TypeError("Invalid tagName");b.ns&&(m=b.ns);const P=m?Pi(w,m):ba(w),A=b.attrs;A&&H(P,En(A));const S=b.style;S&&Ge(P,S);const E=b.className;E!=null&&P.setAttribute("class",Array.isArray(E)?E.join(" "):E),b.textContent&&(P.textContent=b.textContent);const N=b.selector;if(N!=null){if(d[N])throw new TypeError("Selector must be unique");d[N]=P}if(b.groupSelector){let T=b.groupSelector;Array.isArray(T)||(T=[T]),T.forEach(j=>{f[j]||(f[j]=[]),f[j].push(P)})}x.appendChild(P);const L=b.children;Array.isArray(L)&&g.push({ns:m,markup:L,parent:P})})}return Object.keys(f).forEach(p=>{if(d[p])throw new Error("Ambiguous group selector");d[p]=f[p]}),{fragment:u,selectors:d,groups:f}}i.parseJSONMarkup=r;function o(c){return c instanceof SVGElement?Jt("g"):ba("div")}function a(c){if(e(c)){const d=$.createVectors(c),g=d.length;if(g===1)return{elem:d[0].node};if(g>1){const p=o(d[0].node);return d.forEach(m=>{p.appendChild(m.node)}),{elem:p}}return{}}const h=r(c),u=h.fragment;let f=null;return u.childNodes.length>1?(f=o(u.firstChild),f.appendChild(u)):f=u.firstChild,{elem:f,selectors:h.selectors}}i.renderMarkup=a;function l(c){const h=$.createVectors(c),u=document.createDocumentFragment();for(let f=0,d=h.length;f ${o} > ${s}`:r=`> ${o}`,r;const a=e.parentNode;if(a&&a.childNodes.length>1){const l=Ai(e)+1;r=`${o}:nth-child(${l})`}else r=o;return s&&(r+=` > ${s}`),t(e.parentNode,n,r)}return s}i.getSelector=t}(X||(X={})),function(i){function t(){return"g"}i.getPortContainerMarkup=t;function e(){return{tagName:"circle",selector:"circle",attrs:{r:10,fill:"#FFFFFF",stroke:"#000000"}}}i.getPortMarkup=e;function n(){return{tagName:"text",selector:"text",attrs:{fill:"#000000"}}}i.getPortLabelMarkup=n}(X||(X={})),function(i){function t(){return[{tagName:"path",selector:"wrap",groupSelector:"lines",attrs:{fill:"none",cursor:"pointer",stroke:"transparent",strokeLinecap:"round"}},{tagName:"path",selector:"line",groupSelector:"lines",attrs:{fill:"none",pointerEvents:"none"}}]}i.getEdgeMarkup=t}(X||(X={})),function(i){function t(e=!1){return{tagName:"foreignObject",selector:"fo",children:[{ns:ut.xhtml,tagName:"body",selector:"foBody",attrs:{xmlns:ut.xhtml},style:{width:"100%",height:"100%",background:"transparent"},children:e?[]:[{tagName:"div",selector:"foContent",style:{width:"100%",height:"100%"}}]}]}}i.getForeignObjectMarkup=t}(X||(X={}));class vl{constructor(t){this.view=t}get cell(){return this.view.cell}getDefinition(t){return this.cell.getAttrDefinition(t)}processAttrs(t,e){let n,s,r,o;const a=[];return Object.keys(e).forEach(l=>{const c=e[l],h=this.getDefinition(l),u=R(Bt.isValidDefinition,this.view,h,c,{elem:t,attrs:e,cell:this.cell,view:this.view});if(h&&u)typeof h=="string"?(n==null&&(n={}),n[h]=c):c!==null&&a.push({name:l,definition:h});else{n==null&&(n={});const f=wa.includes(l)?l:Qo(l);n[f]=c}}),a.forEach(({name:l,definition:c})=>{const h=e[l];typeof c.set=="function"&&(s==null&&(s={}),s[l]=h),typeof c.offset=="function"&&(r==null&&(r={}),r[l]=h),typeof c.position=="function"&&(o==null&&(o={}),o[l]=h)}),{raw:e,normal:n,set:s,offset:r,position:o}}mergeProcessedAttrs(t,e){t.set=Object.assign(Object.assign({},t.set),e.set),t.position=Object.assign(Object.assign({},t.position),e.position),t.offset=Object.assign(Object.assign({},t.offset),e.offset);const n=t.normal&&t.normal.transform;n!=null&&e.normal&&(e.normal.transform=n),t.normal=e.normal}findAttrs(t,e,n,s){const r=[],o=new $i;return Object.keys(t).forEach(a=>{const l=t[a];if(!$t(l))return;const{isCSSSelector:c,elems:h}=Z.find(a,e,s);n[a]=h;for(let u=0,f=h.length;u{const l=o.get(a),c=l.attrs;l.attrs=c.reduceRight((h,u)=>ot(h,u),{})}),o}updateRelativeAttrs(t,e,n){const s=e.raw||{};let r=e.normal||{};const o=e.set,a=e.position,l=e.offset,c=()=>({elem:t,cell:this.cell,view:this.view,attrs:s,refBBox:n.clone()});if(o!=null&&Object.keys(o).forEach(m=>{const y=o[m],x=this.getDefinition(m);if(x!=null){const b=R(x.set,this.view,y,c());typeof b=="object"?r=Object.assign(Object.assign({},r),b):b!=null&&(r[m]=b)}}),t instanceof HTMLElement){this.view.setAttrs(r,t);return}const h=r.transform,u=h?`${h}`:null,f=Nn(u),d=new v(f.e,f.f);h&&(delete r.transform,f.e=0,f.f=0);let g=!1;a!=null&&Object.keys(a).forEach(m=>{const y=a[m],x=this.getDefinition(m);if(x!=null){const b=R(x.position,this.view,y,c());b!=null&&(g=!0,d.translate(v.create(b)))}}),this.view.setAttrs(r,t);let p=!1;if(l!=null){const m=this.view.getBoundingRectOfElement(t);if(m.width>0&&m.height>0){const y=_.transformRectangle(m,f);Object.keys(l).forEach(x=>{const b=l[x],w=this.getDefinition(x);if(w!=null){const P=R(w.offset,this.view,b,{elem:t,cell:this.cell,view:this.view,attrs:s,refBBox:y});P!=null&&(p=!0,d.translate(v.create(P)))}})}}(h!=null||g||p)&&(d.round(1),f.e=d.x,f.f=d.y,t.setAttribute("transform",Ue(f)))}update(t,e,n){const s={},r=this.findAttrs(n.attrs||e,t,s,n.selectors),o=n.attrs?this.findAttrs(e,t,s,n.selectors):r,a=[];r.each(h=>{const u=h.elem,f=h.attrs,d=this.processAttrs(u,f);if(d.set==null&&d.position==null&&d.offset==null)this.view.setAttrs(d.normal,u);else{const g=o.get(u),p=g?g.attrs:null,m=p&&f.ref==null?p.ref:f.ref;let y;if(m){if(y=(s[m]||this.view.find(m,t,n.selectors))[0],!y)throw new Error(`"${m}" reference does not exist.`)}else y=null;const x={node:u,refNode:y,attributes:p,processedAttributes:d},b=a.findIndex(w=>w.refNode===u);b>-1?a.splice(b,0,x):a.push(x)}});const l=new $i;let c;a.forEach(h=>{const u=h.node,f=h.refNode;let d;const g=f!=null&&n.rotatableNode!=null&&Ci(n.rotatableNode,f);if(f&&(d=l.get(f)),!d){const y=g?n.rotatableNode:t;d=f?_.getBBox(f,{target:y}):n.rootBBox,f&&l.set(f,d)}let p;n.attrs&&h.attributes?(p=this.processAttrs(u,h.attributes),this.mergeProcessedAttrs(p,h.processedAttributes)):p=h.processedAttributes;let m=d;g&&n.rotatableNode!=null&&!n.rotatableNode.contains(u)&&(c||(c=Nn(H(n.rotatableNode,"transform"))),m=_.transformRectangle(d,c)),this.updateRelativeAttrs(u,p,m)})}}class wl{constructor(t,e,n=[]){this.view=t;const s={},r={};let o=0;Object.keys(e).forEach(l=>{let c=e[l];Array.isArray(c)||(c=[c]),c.forEach(h=>{let u=s[h];u||(o+=1,u=s[h]=1<{s[l]||(o+=1,s[l]=1<25)throw new Error("Maximum number of flags exceeded.");this.flags=s,this.attrs=r,this.bootstrap=n}get cell(){return this.view.cell}getFlag(t){const e=this.flags;return e==null?0:Array.isArray(t)?t.reduce((n,s)=>n|e[s],0):e[t]|0}hasAction(t,e){return t&this.getFlag(e)}removeAction(t,e){return t^t&this.getFlag(e)}getBootstrapFlag(){return this.getFlag(this.bootstrap)}getChangedFlag(){let t=0;return this.attrs&&Object.keys(this.attrs).forEach(e=>{this.cell.hasChanged(e)&&(t|=this.attrs[e])}),t}}var f0=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);sh!=null?Uo([...Array.isArray(c)?c:[c],...Array.isArray(h)?h:[h]]):Array.isArray(c)?[...c]:[c],n=tt(this.getDefaults()),{bootstrap:s,actions:r,events:o,documentEvents:a}=t,l=f0(t,["bootstrap","actions","events","documentEvents"]);return s&&(n.bootstrap=e(n.bootstrap,s)),r&&Object.keys(r).forEach(c=>{const h=r[c],u=n.actions[c];h&&u?n.actions[c]=e(u,h):h&&(n.actions[c]=e(h))}),o&&(n.events=Object.assign(Object.assign({},n.events),o)),t.documentEvents&&(n.documentEvents=Object.assign(Object.assign({},n.documentEvents),a)),ot(n,l)}get[Symbol.toStringTag](){return ht.toStringTag}init(){}onRemove(){this.removeTools()}get priority(){return this.options.priority}get rootSelector(){return this.options.rootSelector}getConstructor(){return this.constructor}ensureOptions(t){return this.getConstructor().getOptions(t)}getContainerTagName(){return this.options.isSvgElement?"g":"div"}getContainerStyle(){}getContainerAttrs(){return{"data-cell-id":this.cell.id,"data-shape":this.cell.shape}}getContainerClassName(){return this.prefixClassName("cell")}ensureContainer(){return Z.createElement(this.getContainerTagName(),this.options.isSvgElement)}setContainer(t){if(this.container!==t){this.undelegateEvents(),this.container=t,this.options.events!=null&&this.delegateEvents(this.options.events);const e=this.getContainerAttrs();e!=null&&this.setAttrs(e,t);const n=this.getContainerStyle();n!=null&&this.setStyle(n,t);const s=this.getContainerClassName();s!=null&&this.addClass(s,t)}return this}isNodeView(){return!1}isEdgeView(){return!1}render(){return this}confirmUpdate(t,e={}){return 0}getBootstrapFlag(){return this.flag.getBootstrapFlag()}getFlag(t){return this.flag.getFlag(t)}hasAction(t,e){return this.flag.hasAction(t,e)}removeAction(t,e){return this.flag.removeAction(t,e)}handleAction(t,e,n,s){if(this.hasAction(t,e)){n();const r=[e];return s&&(typeof s=="string"?r.push(s):r.push(...s)),this.removeAction(t,r)}return t}setup(){this.cell.on("changed",({options:t})=>this.onAttrsChange(t))}onAttrsChange(t){let e=this.flag.getChangedFlag();t.updated||!e||(t.dirty&&this.hasAction(e,"update")&&(e|=this.getFlag("render")),t.toolId&&(t.async=!1),this.graph!=null&&this.graph.renderer.requestViewUpdate(this,e,t))}parseJSONMarkup(t,e){const n=X.parseJSONMarkup(t),s=n.selectors,r=this.rootSelector;if(e&&r){if(s[r])throw new Error("Invalid root selector");s[r]=e}return n}can(t){let e=this.graph.options.interacting;if(typeof e=="function"&&(e=R(e,this.graph,this)),typeof e=="object"){let n=e[t];return typeof n=="function"&&(n=R(n,this.graph,this)),n!==!1}return typeof e=="boolean"?e:!1}cleanCache(){return this.cache.clean(),this}getCache(t){return this.cache.get(t)}getDataOfElement(t){return this.cache.getData(t)}getMatrixOfElement(t){return this.cache.getMatrix(t)}getShapeOfElement(t){return this.cache.getShape(t)}getBoundingRectOfElement(t){return this.cache.getBoundingRect(t)}getBBoxOfElement(t){const e=this.getBoundingRectOfElement(t),n=this.getMatrixOfElement(t),s=this.getRootRotatedMatrix(),r=this.getRootTranslatedMatrix();return _.transformRectangle(e,r.multiply(s).multiply(n))}getUnrotatedBBoxOfElement(t){const e=this.getBoundingRectOfElement(t),n=this.getMatrixOfElement(t),s=this.getRootTranslatedMatrix();return _.transformRectangle(e,s.multiply(n))}getBBox(t={}){let e;if(t.useCellGeometry){const n=this.cell,s=n.isNode()?n.getAngle():0;e=n.getBBox().bbox(s)}else e=this.getBBoxOfElement(this.container);return this.graph.coord.localToGraphRect(e)}getRootTranslatedMatrix(){const t=this.cell,e=t.isNode()?t.getPosition():{x:0,y:0};return ft().translate(e.x,e.y)}getRootRotatedMatrix(){let t=ft();const e=this.cell,n=e.isNode()?e.getAngle():0;if(n){const s=e.getBBox(),r=s.width/2,o=s.height/2;t=t.translate(r,o).rotate(n).translate(-r,-o)}return t}findMagnet(t=this.container){return this.findByAttr("magnet",t)}updateAttrs(t,e,n={}){n.rootBBox==null&&(n.rootBBox=new M),n.selectors==null&&(n.selectors=this.selectors),this.attr.update(t,e,n)}isEdgeElement(t){return this.cell.isEdge()&&(t==null||t===this.container)}prepareHighlight(t,e={}){const n=t||this.container;return e.partial=n===this.container,n}highlight(t,e={}){const n=this.prepareHighlight(t,e);return this.notify("cell:highlight",{magnet:n,options:e,view:this,cell:this.cell}),this.isEdgeView()?this.notify("edge:highlight",{magnet:n,options:e,view:this,edge:this.cell,cell:this.cell}):this.isNodeView()&&this.notify("node:highlight",{magnet:n,options:e,view:this,node:this.cell,cell:this.cell}),this}unhighlight(t,e={}){const n=this.prepareHighlight(t,e);return this.notify("cell:unhighlight",{magnet:n,options:e,view:this,cell:this.cell}),this.isNodeView()?this.notify("node:unhighlight",{magnet:n,options:e,view:this,node:this.cell,cell:this.cell}):this.isEdgeView()&&this.notify("edge:unhighlight",{magnet:n,options:e,view:this,edge:this.cell,cell:this.cell}),this}notifyUnhighlight(t,e){}getEdgeTerminal(t,e,n,s,r){const o=this.cell,a=this.findAttr("port",t),l=t.getAttribute("data-selector"),c={cell:o.id};return l!=null&&(c.magnet=l),a!=null?(c.port=a,o.isNode()&&!o.hasPort(a)&&l==null&&(c.selector=this.getSelector(t))):l==null&&this.container!==t&&(c.selector=this.getSelector(t)),c}getMagnetFromEdgeTerminal(t){const e=this.cell,n=this.container,s=t.port;let r=t.magnet,o;return s!=null&&e.isNode()&&e.hasPort(s)?o=this.findPortElem(s,r)||n:(r||(r=t.selector),!r&&s!=null&&(r=`[port="${s}"]`),o=this.findOne(r,n,this.selectors)),o}hasTools(t){const e=this.tools;return e==null?!1:t==null?!0:e.name===t}addTools(t){if(!this.can("toolsAddable"))return this;if(this.removeTools(),t){const e=at.isToolsView(t)?t:new at(t);this.tools=e,e.config({view:this}),e.mount()}return this}updateTools(t={}){return this.tools&&this.tools.update(t),this}removeTools(){return this.tools&&(this.tools.remove(),this.tools=null),this}hideTools(){return this.tools&&this.tools.hide(),this}showTools(){return this.tools&&this.tools.show(),this}renderTools(){const t=this.cell.getTools();return this.addTools(t),this}notify(t,e){return this.trigger(t,e),this.graph.trigger(t,e),this}getEventArgs(t,e,n){const s=this,r=s.cell;return e==null||n==null?{e:t,view:s,cell:r}:{e:t,x:e,y:n,view:s,cell:r}}onClick(t,e,n){this.notify("cell:click",this.getEventArgs(t,e,n))}onDblClick(t,e,n){this.notify("cell:dblclick",this.getEventArgs(t,e,n))}onContextMenu(t,e,n){this.notify("cell:contextmenu",this.getEventArgs(t,e,n))}onMouseDown(t,e,n){this.cell.model&&(this.cachedModelForMouseEvent=this.cell.model,this.cachedModelForMouseEvent.startBatch("mouse")),this.notify("cell:mousedown",this.getEventArgs(t,e,n))}onMouseUp(t,e,n){this.notify("cell:mouseup",this.getEventArgs(t,e,n)),this.cachedModelForMouseEvent&&(this.cachedModelForMouseEvent.stopBatch("mouse",{cell:this.cell}),this.cachedModelForMouseEvent=null)}onMouseMove(t,e,n){this.notify("cell:mousemove",this.getEventArgs(t,e,n))}onMouseOver(t){this.notify("cell:mouseover",this.getEventArgs(t))}onMouseOut(t){this.notify("cell:mouseout",this.getEventArgs(t))}onMouseEnter(t){this.notify("cell:mouseenter",this.getEventArgs(t))}onMouseLeave(t){this.notify("cell:mouseleave",this.getEventArgs(t))}onMouseWheel(t,e,n,s){this.notify("cell:mousewheel",Object.assign({delta:s},this.getEventArgs(t,e,n)))}onCustomEvent(t,e,n,s){this.notify("cell:customevent",Object.assign({name:e},this.getEventArgs(t,n,s))),this.notify(e,Object.assign({},this.getEventArgs(t,n,s)))}onMagnetMouseDown(t,e,n,s){}onMagnetDblClick(t,e,n,s){}onMagnetContextMenu(t,e,n,s){}onLabelMouseDown(t,e,n){}checkMouseleave(t){const e=this.getEventTarget(t,{fromPoint:!0}),n=this.graph.findViewByElem(e);n!==this&&(this.onMouseLeave(t),!!n&&n.onMouseEnter(t))}}ht.defaults={isSvgElement:!0,rootSelector:"root",priority:0,bootstrap:[],actions:{}},function(i){i.Flag=wl,i.Attr=vl}(ht||(ht={})),function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNodeView=="function"&&typeof s.isEdgeView=="function"&&typeof s.confirmUpdate=="function"}i.isCellView=t}(ht||(ht={})),function(i){function t(n){return function(s){s.config({priority:n})}}i.priority=t;function e(n){return function(s){s.config({bootstrap:n})}}i.bootstrap=e}(ht||(ht={})),function(i){i.registry=st.create({type:"view"})}(ht||(ht={}));class at extends Z{constructor(t={}){super();this.svgContainer=this.createContainer(!0,t),this.htmlContainer=this.createContainer(!1,t),this.config(t)}get name(){return this.options.name}get graph(){return this.cellView.graph}get cell(){return this.cellView.cell}get[Symbol.toStringTag](){return at.toStringTag}createContainer(t,e){const n=t?Z.createElement("g",!0):Z.createElement("div",!1);return V(n,this.prefixClassName("cell-tools")),e.className&&V(n,e.className),n}config(t){if(this.options=Object.assign(Object.assign({},this.options),t),!ht.isCellView(t.view)||t.view===this.cellView)return this;this.cellView=t.view,this.cell.isEdge()?(V(this.svgContainer,this.prefixClassName("edge-tools")),V(this.htmlContainer,this.prefixClassName("edge-tools"))):this.cell.isNode()&&(V(this.svgContainer,this.prefixClassName("node-tools")),V(this.htmlContainer,this.prefixClassName("node-tools"))),this.svgContainer.setAttribute("data-cell-id",this.cell.id),this.htmlContainer.setAttribute("data-cell-id",this.cell.id),this.name&&(this.svgContainer.setAttribute("data-tools-name",this.name),this.htmlContainer.setAttribute("data-tools-name",this.name));const e=this.options.items;if(!Array.isArray(e))return this;this.tools=[];const n=[];e.forEach(s=>{at.ToolItem.isToolItem(s)?s.name==="vertices"?n.unshift(s):n.push(s):(typeof s=="object"?s.name:s)==="vertices"?n.unshift(s):n.push(s)});for(let s=0;s{t.toolId!==n.cid&&n.isVisible()&&n.update()}),this}focus(t){const e=this.tools;return e&&e.forEach(n=>{t===n?n.show():n.hide()}),this}blur(t){const e=this.tools;return e&&e.forEach(n=>{n!==t&&!n.isVisible()&&(n.show(),n.update())}),this}hide(){return this.focus(null)}show(){return this.blur(null)}remove(){const t=this.tools;return t&&(t.forEach(e=>e.remove()),this.tools=null),qe(this.svgContainer),qe(this.htmlContainer),super.remove()}mount(){const t=this.tools,e=this.cellView;if(e&&t){const n=t.some(r=>r.options.isSVGElement!==!1),s=t.some(r=>r.options.isSVGElement===!1);n&&(this.options.local?e.container:e.graph.view.decorator).appendChild(this.svgContainer),s&&this.graph.container.appendChild(this.htmlContainer)}return this}}(function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&s.graph!=null&&s.cell!=null&&typeof s.config=="function"&&typeof s.update=="function"&&typeof s.focus=="function"&&typeof s.blur=="function"&&typeof s.show=="function"&&typeof s.hide=="function"}i.isToolsView=t})(at||(at={})),function(i){class t extends Z{constructor(n={}){super();this.visible=!0,this.options=this.getOptions(n),this.container=Z.createElement(this.options.tagName||"g",this.options.isSVGElement!==!1),V(this.container,this.prefixClassName("cell-tool")),typeof this.options.className=="string"&&V(this.container,this.options.className),this.init()}static getDefaults(){return this.defaults}static config(n){this.defaults=this.getOptions(n)}static getOptions(n){return ot(tt(this.getDefaults()),n)}get graph(){return this.cellView.graph}get cell(){return this.cellView.cell}get name(){return this.options.name}get[Symbol.toStringTag](){return t.toStringTag}init(){}getOptions(n){return this.constructor.getOptions(n)}delegateEvents(){return this.options.events&&super.delegateEvents(this.options.events),this}config(n,s){return this.cellView=n,this.parent=s,this.stamp(this.container),this.cell.isEdge()?V(this.container,this.prefixClassName("edge-tool")):this.cell.isNode()&&V(this.container,this.prefixClassName("node-tool")),this.name&&this.container.setAttribute("data-tool-name",this.name),this.delegateEvents(),this}render(){this.empty();const n=this.options.markup;if(n){const s=X.parseJSONMarkup(n);this.container.appendChild(s.fragment),this.childNodes=s.selectors}return this.onRender(),this}onRender(){}update(){return this}stamp(n){n&&n.setAttribute("data-cell-id",this.cellView.cell.id)}show(){return this.container.style.display="",this.visible=!0,this}hide(){return this.container.style.display="none",this.visible=!1,this}isVisible(){return this.visible}focus(){const n=this.options.focusOpacity;return n!=null&&Number.isFinite(n)&&(this.container.style.opacity=`${n}`),this.parent.focus(this),this}blur(){return this.container.style.opacity="",this.parent.blur(this),this}guard(n){return this.graph==null||this.cellView==null?!0:this.graph.view.guard(n,this.cellView)}}t.defaults={isSVGElement:!0,tagName:"g"},i.ToolItem=t,function(e){let n=0;function s(o){return o?pi(o):(n+=1,`CustomTool${n}`)}function r(o){const a=di(s(o.name),this);return a.config(o),a}e.define=r}(t=i.ToolItem||(i.ToolItem={})),function(e){e.toStringTag=`X6.${e.name}`;function n(s){if(s==null)return!1;if(s instanceof e)return!0;const r=s[Symbol.toStringTag],o=s;return(r==null||r===e.toStringTag)&&o.graph!=null&&o.cell!=null&&typeof o.config=="function"&&typeof o.update=="function"&&typeof o.focus=="function"&&typeof o.blur=="function"&&typeof o.show=="function"&&typeof o.hide=="function"&&typeof o.isVisible=="function"}e.isToolItem=n}(t=i.ToolItem||(i.ToolItem={}))}(at||(at={}));const d0=i=>i;function Pl(i,t){return t===0?"0%":`${Math.round(i/t*100)}%`}function Al(i){return(e,n,s,r)=>n.isEdgeElement(s)?p0(i,e,n,s,r):g0(i,e,n,s,r)}function g0(i,t,e,n,s){const r=e.cell,o=r.getAngle(),a=e.getUnrotatedBBoxOfElement(n),l=r.getBBox().getCenter(),c=v.create(s).rotate(o,l);let h=c.x-a.x,u=c.y-a.y;return i&&(h=Pl(h,a.width),u=Pl(u,a.height)),t.anchor={name:"topLeft",args:{dx:h,dy:u,rotate:!0}},t}function p0(i,t,e,n,s){const r=e.getConnection();if(!r)return t;const o=r.closestPointLength(s);if(i){const a=r.length();t.anchor={name:"ratio",args:{ratio:o/a}}}else t.anchor={name:"length",args:{length:o}};return t}const m0=Al(!0),y0=Al(!1);var b0=Object.freeze({__proto__:null,noop:d0,pinRelative:m0,pinAbsolute:y0}),Hi;(function(i){i.presets=b0,i.registry=st.create({type:"connection strategy"}),i.registry.register(i.presets,!0)})(Hi||(Hi={}));function Cl(i,t,e,n){return R(Hi.presets.pinRelative,this.graph,{},t,e,i,this.cell,n,{}).anchor}function Sl(i,t){return t?i.cell.getBBox():i.cell.isEdge()?i.getConnection().bbox():i.getUnrotatedBBoxOfElement(i.container)}class ue extends at.ToolItem{onRender(){V(this.container,this.prefixClassName("cell-tool-button")),this.update()}update(){return this.updatePosition(),this}updatePosition(){const e=this.cellView.cell.isEdge()?this.getEdgeMatrix():this.getNodeMatrix();We(this.container,e,{absolute:!0})}getNodeMatrix(){const t=this.cellView,e=this.options;let{x:n=0,y:s=0}=e;const{offset:r,useCellGeometry:o,rotate:a}=e;let l=Sl(t,o);const c=t.cell.getAngle();a||(l=l.bbox(c));let h=0,u=0;typeof r=="number"?(h=r,u=r):typeof r=="object"&&(h=r.x,u=r.y),n=Xt(n,l.width),s=Xt(s,l.height);let f=ft().translate(l.x+l.width/2,l.y+l.height/2);return a&&(f=f.rotate(c)),f=f.translate(n+h-l.width/2,s+u-l.height/2),f}getEdgeMatrix(){const t=this.cellView,e=this.options,{offset:n=0,distance:s=0,rotate:r}=e;let o,a,l;const c=Xt(s,1);c>=0&&c<=1?o=t.getTangentAtRatio(c):o=t.getTangentAtLength(c),o?(a=o.start,l=o.vector().vectorAngle(new v(1,0))||0):(a=t.getConnection().start,l=0);let h=ft().translate(a.x,a.y).rotate(l);return typeof n=="object"?h=h.translate(n.x||0,n.y||0):h=h.translate(0,n),r||(h=h.rotate(-l)),h}onMouseDown(t){if(this.guard(t))return;t.stopPropagation(),t.preventDefault();const e=this.options.onClick;typeof e=="function"&&R(e,this.cellView,{e:t,view:this.cellView,cell:this.cellView.cell,btn:this})}}(function(i){i.config({name:"button",useCellGeometry:!0,events:{mousedown:"onMouseDown",touchstart:"onMouseDown"}})})(ue||(ue={})),function(i){i.Remove=i.define({name:"button-remove",markup:[{tagName:"circle",selector:"button",attrs:{r:7,fill:"#FF1D00",cursor:"pointer"}},{tagName:"path",selector:"icon",attrs:{d:"M -3 -3 3 3 M -3 3 3 -3",fill:"none",stroke:"#FFFFFF","stroke-width":2,"pointer-events":"none"}}],distance:60,offset:0,useCellGeometry:!0,onClick({view:t,btn:e}){e.parent.remove(),t.cell.remove({ui:!0,toolId:e.cid})}})}(ue||(ue={}));var x0=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{this.stopHandleListening(e),e.remove()})}renderHandles(){const t=this.vertices;for(let e=0,n=t.length;ethis.guard(l),attrs:this.options.attrs||{}});o&&o(a),a.updatePosition(s.x,s.y),this.stamp(a.container),this.container.appendChild(a.container),this.handles.push(a),this.startHandleListening(a)}}updateHandles(){const t=this.vertices;for(let e=0,n=t.length;e0?n[t-1]:e.sourceAnchor,r=t0){const s=this.getNeighborPoints(e),r=s.prev,o=s.next;Math.abs(t.x-r.x)new i.Handle(e),markup:[{tagName:"path",selector:"connection",className:t,attrs:{fill:"none",stroke:"transparent","stroke-width":10,cursor:"pointer"}}],events:{[`mousedown .${t}`]:"onPathMouseDown",[`touchstart .${t}`]:"onPathMouseDown"}})}(Vn||(Vn={}));class Fn extends at.ToolItem{constructor(){super(...arguments);this.handles=[]}get vertices(){return this.cellView.cell.getVertices()}update(){return this.render(),this}onRender(){V(this.container,this.prefixClassName("edge-tool-segments")),this.resetHandles();const t=this.cellView,e=[...this.vertices];e.unshift(t.sourcePoint),e.push(t.targetPoint);for(let n=0,s=e.length;nthis.guard(r),attrs:this.options.attrs||{}});return this.options.processHandle&&this.options.processHandle(s),this.updateHandle(s,t,e),this.container.appendChild(s.container),this.startHandleListening(s),s}startHandleListening(t){t.on("change",this.onHandleChange,this),t.on("changing",this.onHandleChanging,this),t.on("changed",this.onHandleChanged,this)}stopHandleListening(t){t.off("change",this.onHandleChange,this),t.off("changing",this.onHandleChanging,this),t.off("changed",this.onHandleChanged,this)}resetHandles(){const t=this.handles;this.handles=[],t&&t.forEach(e=>{this.stopHandleListening(e),e.remove()})}shiftHandleIndexes(t){const e=this.handles;for(let n=0,s=e.length;nnew i.Handle(t),anchor:Cl})}(Fn||(Fn={}));class Ss extends at.ToolItem{get type(){return this.options.type}onRender(){V(this.container,this.prefixClassName(`edge-tool-${this.type}-anchor`)),this.toggleArea(!1),this.update()}update(){const t=this.type;return this.cellView.getTerminalView(t)?(this.updateAnchor(),this.updateArea(),this.container.style.display=""):this.container.style.display="none",this}updateAnchor(){const t=this.childNodes;if(!t)return;const e=t.anchor;if(!e)return;const n=this.type,s=this.cellView,r=this.options,o=s.getTerminalAnchor(n),a=s.cell.prop([n,"anchor"]);e.setAttribute("transform",`translate(${o.x}, ${o.y})`);const l=a?r.customAnchorAttrs:r.defaultAnchorAttrs;l&&Object.keys(l).forEach(c=>{e.setAttribute(c,l[c])})}updateArea(){const t=this.childNodes;if(!t)return;const e=t.area;if(!e)return;const n=this.type,s=this.cellView,r=s.getTerminalView(n);if(r){const o=r.cell,a=s.getTerminalMagnet(n);let l=this.options.areaPadding||0;Number.isFinite(l)||(l=0);let c,h,u;r.isEdgeElement(a)?(c=r.getBBox(),h=0,u=c.getCenter()):(c=r.getUnrotatedBBoxOfElement(a),h=o.getAngle(),u=c.getCenter(),h&&u.rotate(-h,o.getBBox().getCenter())),c.inflate(l),H(e,{x:-c.width/2,y:-c.height/2,width:c.width,height:c.height,transform:`translate(${u.x}, ${u.y}) rotate(${h})`})}}toggleArea(t){if(this.childNodes){const e=this.childNodes.area;e&&(e.style.display=t?"":"none")}}onMouseDown(t){this.guard(t)||(t.stopPropagation(),t.preventDefault(),this.graph.view.undelegateEvents(),this.options.documentEvents&&this.delegateDocumentEvents(this.options.documentEvents),this.focus(),this.toggleArea(this.options.restrictArea),this.cell.startBatch("move-anchor",{ui:!0,toolId:this.cid}))}resetAnchor(t){const e=this.type,n=this.cell;t?n.prop([e,"anchor"],t,{rewrite:!0,ui:!0,toolId:this.cid}):n.removeProp([e,"anchor"],{ui:!0,toolId:this.cid})}onMouseMove(t){const e=this.type,n=this.cellView,s=n.getTerminalView(e);if(s==null)return;const r=this.normalizeEvent(t),o=s.cell,a=n.getTerminalMagnet(e);let l=this.graph.coord.clientToLocalPoint(r.clientX,r.clientY);const c=this.options.snap;if(typeof c=="function"){const f=R(c,n,l,s,a,e,n,this);l=v.create(f)}if(this.options.restrictArea)if(s.isEdgeElement(a)){const f=s.getClosestPoint(l);f&&(l=f)}else{const f=s.getUnrotatedBBoxOfElement(a),d=o.getAngle(),g=o.getBBox().getCenter(),p=l.clone().rotate(d,g);f.containsPoint(p)||(l=f.getNearestPointToPoint(p).rotate(-d,g))}let h;const u=this.options.anchor;typeof u=="function"&&(h=R(u,n,l,s,a,e,n,this)),this.resetAnchor(h),this.update()}onMouseUp(t){this.graph.view.delegateEvents(),this.undelegateDocumentEvents(),this.blur(),this.toggleArea(!1);const e=this.cellView;this.options.removeRedundancies&&e.removeRedundantLinearVertices({ui:!0,toolId:this.cid}),this.cell.stopBatch("move-anchor",{ui:!0,toolId:this.cid})}onDblClick(){const t=this.options.resetAnchor;t&&this.resetAnchor(t===!0?void 0:t),this.update()}}(function(i){i.config({tagName:"g",markup:[{tagName:"circle",selector:"anchor",attrs:{cursor:"pointer"}},{tagName:"rect",selector:"area",attrs:{"pointer-events":"none",fill:"none",stroke:"#33334F","stroke-dasharray":"2,4",rx:5,ry:5}}],events:{mousedown:"onMouseDown",touchstart:"onMouseDown",dblclick:"onDblClick"},documentEvents:{mousemove:"onMouseMove",touchmove:"onMouseMove",mouseup:"onMouseUp",touchend:"onMouseUp",touchcancel:"onMouseUp"},customAnchorAttrs:{"stroke-width":4,stroke:"#33334F",fill:"#FFFFFF",r:5},defaultAnchorAttrs:{"stroke-width":2,stroke:"#FFFFFF",fill:"#33334F",r:6},areaPadding:6,snapRadius:10,resetAnchor:!0,restrictArea:!0,removeRedundancies:!0,anchor:Cl,snap(t,e,n,s,r,o){const a=o.options.snapRadius||0,l=s==="source",c=l?0:-1,h=this.cell.getVertexAt(c)||this.getTerminalAnchor(l?"target":"source");return h&&(Math.abs(h.x-t.x){this.editor.focus(),this.selectText()})}selectText(){if(window.getSelection){const t=document.createRange(),e=window.getSelection();t.selectNodeContents(this.editor),e.removeAllRanges(),e.addRange(t)}}}(function(i){i.config({tagName:"div",isSVGElement:!1,events:{dblclick:"onDblClick",mousedown:"onMouseDown"},documentEvents:{mousedown:"onDocumentMouseDown"}})})(Qe||(Qe={})),function(i){i.NodeEditor=i.define({attrs:{fontSize:14,fontFamily:"Arial, helvetica, sans-serif",color:"#000",backgroundColor:"#fff"},getText({cell:t}){return t.attr("text/text")},setText({cell:t,value:e}){t.attr("text/text",e)}}),i.EdgeEditor=i.define({attrs:{fontSize:14,fontFamily:"Arial, helvetica, sans-serif",color:"#000",backgroundColor:"#fff"},labelAddable:!0,getText({cell:t,index:e}){return e===-1?"":t.prop(`labels/${e}/attrs/label/text`)},setText({cell:t,value:e,index:n,distance:s}){const r=t;n===-1?r.appendLabel({position:{distance:s},attrs:{label:{text:e}}}):e?r.prop(`labels/${n}/attrs/label/text`,e):typeof n=="number"&&r.removeLabelAt(n)}})}(Qe||(Qe={}));var Ol=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s1&&(s/=100),i.getPointAtRatio(s)},F0=function(i,t,e,n){const s=n.length!=null?n.length:20;return i.getPointAtLength(s)},Ml=function(i,t,e,n){const s=i.getClosestPoint(e);return s!=null?s:new v},_0=Es(Ml),H0=function(i,t,e,n){const s=1e6,r=i.getConnection(),o=i.getConnectionSubdivisions(),a=new I(e.clone().translate(0,s),e.clone().translate(0,-s)),l=new I(e.clone().translate(s,0),e.clone().translate(-s,0)),c=a.intersect(r,{segmentSubdivisions:o}),h=l.intersect(r,{segmentSubdivisions:o}),u=[];return c&&u.push(...c),h&&u.push(...h),u.length>0?e.closest(u):n.fallbackAt!=null?El(i,n.fallbackAt):R(Ml,this,i,t,e,n)},q0=Es(H0);var G0=Object.freeze({__proto__:null,closest:_0,ratio:V0,length:F0,orth:q0}),sn;(function(i){i.presets=G0,i.registry=st.create({type:"edge endpoint"}),i.registry.register(i.presets,!0)})(sn||(sn={}));function Ms(i,t,e){let n;if(typeof e=="object"){if(Number.isFinite(e.y)){const r=new I(t,i),{start:o,end:a}=r.parallel(e.y);t=o,i=a}n=e.x}else n=e;if(n==null||!Number.isFinite(n))return i;const s=i.distance(t);return n===0&&s>0?i:i.move(t,-Math.min(n,s-1))}function Ts(i){const t=i.getAttribute("stroke-width");return t===null?0:parseFloat(t)||0}function U0(i){if(i==null)return null;let t=i;do{let e=t.tagName;if(typeof e!="string")return null;if(e=e.toUpperCase(),e==="G")t=t.firstElementChild;else if(e==="TITLE")t=t.nextElementSibling;else break}while(t);return t}const Tl=function(i,t,e,n){const s=t.getBBoxOfElement(e);n.stroked&&s.inflate(Ts(e)/2);const r=i.intersect(s),o=r&&r.length?i.start.closest(r):i.end;return Ms(o,i.start,n.offset)},W0=function(i,t,e,n,s){const r=t.cell,o=r.isNode()?r.getAngle():0;if(o===0)return R(Tl,this,i,t,e,n,s);const a=t.getUnrotatedBBoxOfElement(e);n.stroked&&a.inflate(Ts(e)/2);const l=a.getCenter(),c=i.clone().rotate(o,l),h=c.setLength(1e6).intersect(a),u=h&&h.length?c.start.closest(h).rotate(-o,l):i.end;return Ms(u,i.start,n.offset)},X0=function(i,t,e,n){let s,r;const o=i.end,a=n.selector;if(typeof a=="string"?s=t.findOne(a):Array.isArray(a)?s=gi(e,a):s=U0(e),!ie(s)){if(s===e||!ie(e))return o;s=e}const l=t.getShapeOfElement(s),c=t.getMatrixOfElement(s),h=t.getRootTranslatedMatrix(),u=t.getRootRotatedMatrix(),f=h.multiply(u).multiply(c),d=f.inverse(),g=_.transformLine(i,d),p=g.start.clone(),m=t.getDataOfElement(s);if(n.insideout===!1){m.shapeBBox==null&&(m.shapeBBox=l.bbox());const w=m.shapeBBox;if(w!=null&&w.containsPoint(p))return o}n.extrapolate===!0&&g.setLength(1e6);let y;if(D.isPath(l)){const w=n.precision||2;m.segmentSubdivisions==null&&(m.segmentSubdivisions=l.getSegmentSubdivisions({precision:w})),y={precision:w,segmentSubdivisions:m.segmentSubdivisions},r=g.intersect(l,y)}else r=g.intersect(l);r?Array.isArray(r)&&(r=p.closest(r)):n.sticky===!0&&(M.isRectangle(l)?r=l.getNearestPointToPoint(p):It.isEllipse(l)?r=l.intersectsWithLineFromCenterToPoint(p):r=l.closestPoint(p,y));const x=r?_.transformPoint(r,f):o;let b=n.offset||0;return n.stroked!==!1&&(typeof b=="object"?(b=Object.assign({},b),b.x==null&&(b.x=0),b.x+=Ts(s)/2):b+=Ts(s)/2),Ms(x,i.start,b)};function J0(i,t,e=0){const{start:n,end:s}=i;let r,o,a,l;switch(t){case"left":l="x",r=s,o=n,a=-1;break;case"right":l="x",r=n,o=s,a=1;break;case"top":l="y",r=s,o=n,a=-1;break;case"bottom":l="y",r=n,o=s,a=1;break;default:return}n[l]0?l[c]=a[c]:a[c]=l[c],[a.toJSON(),...i,l.toJSON()]};function Ns(i){return new M(i.x,i.y,0,0)}function Ls(i={}){const t=ne(i.padding||20);return{x:-t.left,y:-t.top,width:t.left+t.right,height:t.top+t.bottom}}function Nl(i,t={}){return i.sourceBBox.clone().moveAndExpand(Ls(t))}function Ll(i,t={}){return i.targetBBox.clone().moveAndExpand(Ls(t))}function tx(i,t={}){return i.sourceAnchor?i.sourceAnchor:Nl(i,t).getCenter()}function ex(i,t={}){return i.targetAnchor?i.targetAnchor:Ll(i,t).getCenter()}const Il=function(i,t,e){let n=Nl(e,t),s=Ll(e,t);const r=tx(e,t),o=ex(e,t);n=n.union(Ns(r)),s=s.union(Ns(o));const a=i.map(h=>v.create(h));a.unshift(r),a.push(o);let l=null;const c=[];for(let h=0,u=a.length-1;hf.y?"N":"S":u.y===f.y?u.x>f.x?"W":"E":null}i.getBearing=r;function o(u,f,d){const g=new v(u.x,f.y),p=new v(f.x,u.y),m=r(u,g),y=r(u,p),x=d?t[d]:null,b=m===d||m!==x&&(y===x||y!==d)?g:p;return{points:[b],direction:r(b,f)}}i.vertexToVertex=o;function a(u,f,d){const g=n(u,f,d);return{points:[g],direction:r(g,f)}}i.nodeToVertex=a;function l(u,f,d,g){const p=[new v(u.x,f.y),new v(f.x,u.y)],m=p.filter(b=>!d.containsPoint(b)),y=m.filter(b=>r(b,u)!==g);let x;if(y.length>0)return x=y.filter(b=>r(u,b)===g).pop(),x=x||y[0],{points:[x],direction:r(x,f)};{x=Sp(p,m)[0];const b=v.create(f).move(x,-s(d,g)/2);return{points:[n(b,u,d),b],direction:r(b,f)}}}i.vertexToNode=l;function c(u,f,d,g){let p=a(f,u,g);const m=p.points[0];if(d.containsPoint(m)){p=a(u,f,d);const y=p.points[0];if(g.containsPoint(y)){const x=v.create(u).move(y,-s(d,r(u,y))/2),b=v.create(f).move(m,-s(g,r(f,m))/2),w=new I(x,b).getCenter(),P=a(u,w,d),A=o(w,f,P.direction);p.points=[P.points[0],A.points[0]],p.direction=A.direction}}return p}i.nodeToNode=c;function h(u,f,d,g,p){const m=d.union(g).inflate(1),y=m.getCenter(),x=y.distance(f)>y.distance(u),b=x?f:u,w=x?u:f;let P,A,S;p?(P=v.fromPolar(m.width+m.height,e[p],b),P=m.getNearestPointToPoint(P).move(P,-1)):P=m.getNearestPointToPoint(b).move(b,1),A=n(P,w,m);let E;P.round().equals(A.round())?(A=v.fromPolar(m.width+m.height,q.toRad(P.theta(b))+Math.PI/2,w),A=m.getNearestPointToPoint(A).move(w,1).round(),S=n(P,A,m),E=x?[A,S,P]:[P,S,A]):E=x?[A,P]:[P,A];const N=r(x?P:A,f);return{points:E,direction:N}}i.insideNode=h})(Mt||(Mt={}));const nx={step:10,maxLoopCount:2e3,precision:1,maxDirectionChange:90,perpendicular:!0,excludeTerminals:[],excludeShapes:[],excludeNodes:[],excludeHiddenNodes:!1,startDirections:["top","right","bottom","left"],endDirections:["top","right","bottom","left"],directionMap:{top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}},cost(){return fe(this.step,this)},directions(){const i=fe(this.step,this),t=fe(this.cost,this);return[{cost:t,offsetX:i,offsetY:0},{cost:t,offsetX:-i,offsetY:0},{cost:t,offsetX:0,offsetY:i},{cost:t,offsetX:0,offsetY:-i}]},penalties(){const i=fe(this.step,this);return{0:0,45:i/2,90:i/2}},paddingBox(){const i=fe(this.step,this);return{x:-i,y:-i,width:2*i,height:2*i}},fallbackRouter:Il,draggingRouter:null};function fe(i,t){return typeof i=="function"?i.call(t):i}function sx(i){const t=Object.keys(i).reduce((e,n)=>{const s=e;return n==="fallbackRouter"||n==="draggingRouter"||n==="fallbackRoute"?s[n]=i[n]:s[n]=fe(i[n],i),e},{});if(t.padding){const e=ne(t.padding);t.paddingBox={x:-e.left,y:-e.top,width:e.left+e.right,height:e.top+e.bottom}}return t.directions.forEach(e=>{const n=new v(0,0),s=new v(e.offsetX,e.offsetY);e.angle=q.normalize(n.theta(s))}),t}const jl=1,Dl=2;class ix{constructor(){this.items=[],this.hash={},this.values={}}add(t,e){this.hash[t]?this.items.splice(this.items.indexOf(t),1):this.hash[t]=jl,this.values[t]=e;const n=Qp(this.items,t,s=>this.values[s]);this.items.splice(n,0,t)}pop(){const t=this.items.shift();return t&&(this.hash[t]=Dl),t}isOpen(t){return this.hash[t]===jl}isClose(t){return this.hash[t]===Dl}isEmpty(){return this.items.length===0}}class rx{constructor(t){this.options=t,this.mapGridSize=100,this.map={}}build(t,e){const n=this.options,s=n.excludeTerminals.reduce((c,h)=>{const u=e[h];if(u){const f=t.getCell(u.cell);f&&c.push(f)}return c},[]);let r=[];const o=t.getCell(e.getSourceCellId());o&&(r=Go(r,o.getAncestors().map(c=>c.id)));const a=t.getCell(e.getTargetCellId());a&&(r=Go(r,a.getAncestors().map(c=>c.id)));const l=this.mapGridSize;return t.getNodes().reduce((c,h)=>{const u=h.shape,f=n.excludeShapes,d=u?f.includes(u):!1,g=s.some(b=>b.id===h.id),p=n.excludeNodes.includes(h),m=r.includes(h.id),y=n.excludeHiddenNodes&&!h.isVisible();if(!(d||g||p||m||y)){const b=h.getBBox().moveAndExpand(n.paddingBox),w=b.getOrigin().snapToGrid(l),P=b.getCorner().snapToGrid(l);for(let A=w.x;A<=P.x;A+=l)for(let S=w.y;S<=P.y;S+=l){const E=new v(A,S).toString();c[E]==null&&(c[E]=[]),c[E].push(b)}}return c},this.map),this}isAccessible(t){const e=t.clone().snapToGrid(this.mapGridSize).toString(),n=this.map[e];return n?n.every(s=>!s.containsPoint(t)):!0}}function $l(i,t){const e=i.sourceBBox.clone();return t&&t.paddingBox?e.moveAndExpand(t.paddingBox):e}function Rl(i,t){const e=i.targetBBox.clone();return t&&t.paddingBox?e.moveAndExpand(t.paddingBox):e}function kl(i,t){return i.sourceAnchor?i.sourceAnchor:$l(i,t).getCenter()}function ox(i,t){return i.targetAnchor?i.targetAnchor:Rl(i,t).getCenter()}function qi(i,t,e,n,s){const r=360/e,o=i.theta(ax(i,t,n,s)),a=q.normalize(o+r/2);return r*Math.floor(a/r)}function ax(i,t,e,n){const s=n.step,r=t.x-i.x,o=t.y-i.y,a=r/e.x,l=o/e.y,c=a*s,h=l*s;return new v(i.x+c,i.y+h)}function Bl(i,t){const e=Math.abs(i-t);return e>180?360-e:e}function lx(i,t){const e=t.step;return t.directions.forEach(n=>{n.gridOffsetX=n.offsetX/e*i.x,n.gridOffsetY=n.offsetY/e*i.y}),t.directions}function cx(i,t,e){return{source:t.clone(),x:zl(e.x-t.x,i),y:zl(e.y-t.y,i)}}function zl(i,t){if(!i)return t;const e=Math.abs(i),n=Math.round(e/t);if(!n)return e;const s=n*t,o=(e-s)/n;return t+o}function hx(i,t){const e=t.source,n=G.snapToGrid(i.x-e.x,t.x)+e.x,s=G.snapToGrid(i.y-e.y,t.y)+e.y;return new v(n,s)}function _n(i,t){return i.round(t)}function Is(i,t,e){return _n(hx(i.clone(),t),e)}function Hn(i){return i.toString()}function Gi(i){return new v(i.x===0?0:Math.abs(i.x)/i.x,i.y===0?0:Math.abs(i.y)/i.y)}function Vl(i,t){let e=Infinity;for(let n=0,s=t.length;n{if(e.includes(h)){const u=o[h],f=new v(i.x+u.x*(Math.abs(a.x)+t.width),i.y+u.y*(Math.abs(a.y)+t.height)),g=new I(i,f).intersect(t)||[];let p,m=null;for(let y=0;yp)&&(p=b,m=x)}if(m){let y=Is(m,n,r);t.containsPoint(y)&&(y=Is(y.translate(u.x*n.x,u.y*n.y),n,r)),c.push(y)}}return c},[]);return t.containsPoint(i)||l.push(Is(i,n,r)),l}function ux(i,t,e,n,s){const r=[];let o=Gi(s.diff(e)),a=Hn(e),l=i[a],c;for(;l;){c=t[a];const f=Gi(c.diff(l));f.equals(o)||(r.unshift(c),o=f),a=Hn(l),l=i[a]}const h=t[a];return Gi(h.diff(n)).equals(o)||r.unshift(h),r}function fx(i,t,e,n,s){const r=s.precision;let o,a;M.isRectangle(t)?o=_n(kl(i,s).clone(),r):o=_n(t.clone(),r),M.isRectangle(e)?a=_n(ox(i,s).clone(),r):a=_n(e.clone(),r);const l=cx(s.step,o,a),c=o,h=a;let u,f;if(M.isRectangle(t)?u=Fl(c,t,s.startDirections,l,s):u=[c],M.isRectangle(e)?f=Fl(a,e,s.endDirections,l,s):f=[h],u=u.filter(d=>n.isAccessible(d)),f=f.filter(d=>n.isAccessible(d)),u.length>0&&f.length>0){const d=new ix,g={},p={},m={};for(let L=0,T=u.length;L{const j=Hn(T);return L.push(j),L},[]),E=v.equalPoints(u,f);let N=s.maxLoopCount;for(;!d.isEmpty()&&N>0;){const L=d.pop(),T=g[L],j=p[L],Q=m[L],F=T.equals(c),C=j==null;let O;if(C?x?F?O=null:O=qi(c,T,A,l,s):O=y:O=qi(j,T,A,l,s),!(C&&E)&&S.indexOf(L)>=0)return s.previousDirectionAngle=O,ux(p,g,T,c,h);for(let J=0;Js.maxDirectionChange)continue;const ct=Is(T.clone().translate(b.gridOffsetX||0,b.gridOffsetY||0),l,r),yt=Hn(ct);if(d.isClose(yt)||!n.isAccessible(ct))continue;if(S.indexOf(yt)>=0&&!ct.equals(h)){const _t=qi(ct,h,A,l,s);if(Bl(Y,_t)>s.maxDirectionChange)continue}const Wn=b.cost,Xn=F?0:s.penalties[w],te=Q+Wn+Xn;(!d.isOpen(yt)||tev.create(d)),c=[];let h=o,u,f;for(let d=0,g=l.length;d<=g;d+=1){let p=null;if(u=f||s,f=l[d],f==null){f=r;const y=e.cell;if((y.getSourceCellId()==null||y.getTargetCellId()==null)&&typeof n.draggingRouter=="function"){const b=u===s?o:u,w=f.getOrigin();p=R(n.draggingRouter,e,b,w,n)}}if(p==null&&(p=fx(e,u,f,a,n)),p===null)return console.warn("Unable to execute manhattan algorithm, use orth instead"),R(n.fallbackRouter,this,i,n,e);const m=p[0];m&&m.equals(h)&&p.shift(),h=p[p.length-1]||h,c.push(...p)}return c},_l=function(i,t,e){return R(dx,this,i,Object.assign(Object.assign({},nx),t),e)},gx={maxDirectionChange:45,directions(){const i=fe(this.step,this),t=fe(this.cost,this),e=Math.ceil(Math.sqrt(i*i<<1));return[{cost:t,offsetX:i,offsetY:0},{cost:e,offsetX:i,offsetY:i},{cost:t,offsetX:0,offsetY:i},{cost:e,offsetX:-i,offsetY:i},{cost:t,offsetX:-i,offsetY:0},{cost:e,offsetX:-i,offsetY:-i},{cost:t,offsetX:0,offsetY:-i},{cost:e,offsetX:i,offsetY:-i}]},fallbackRoute(i,t,e){const n=i.theta(t),s=[];let r={x:t.x,y:i.y},o={x:i.x,y:t.y};if(n%180>90){const b=r;r=o,o=b}const a=n%90<45?r:o,l=new I(i,a),c=90*Math.ceil(n/90),h=v.fromPolar(l.squaredLength(),q.toRad(c+135),a),u=new I(t,h),f=l.intersectsWithLine(u),d=f||t,g=f?d:i,p=360/e.directions.length,m=g.theta(t),y=q.normalize(m+p/2),x=p*Math.floor(y/p);return e.previousDirectionAngle=x,d&&s.push(d.round()),s.push(t),s}},px=function(i,t,e){return R(_l,this,i,Object.assign(Object.assign({},gx),t),e)},mx=function(i,t,e){const n=t.offset||32,s=t.min==null?16:t.min;let r=0,o=t.direction;const a=e.sourceBBox,l=e.targetBBox,c=a.getCenter(),h=l.getCenter();if(typeof n=="number"&&(r=n),o==null){let y=l.left-a.right,x=l.top-a.bottom;y>=0&&x>=0?o=y>=x?"L":"T":y<=0&&x>=0?(y=a.left-l.right,y>=0?o=y>=x?"R":"T":o="T"):y>=0&&x<=0?(x=a.top-l.bottom,x>=0?o=y>=x?"L":"B":o="L"):(y=a.left-l.right,x=a.top-l.bottom,y>=0&&x>=0?o=y>=x?"R":"B":y<=0&&x>=0?o="B":y>=0&&x<=0?o="R":o=Math.abs(y)>Math.abs(x)?"R":"B")}o==="H"?o=h.x-c.x>=0?"L":"R":o==="V"&&(o=h.y-c.y>=0?"T":"B"),n==="center"&&(o==="L"?r=(l.left-a.right)/2:o==="R"?r=(a.left-l.right)/2:o==="T"?r=(l.top-a.bottom)/2:o==="B"&&(r=(a.top-l.bottom)/2));let u,f,d;const g=o==="L"||o==="R";if(g){if(h.y===c.y)return[...i];d=o==="L"?1:-1,u="x",f="width"}else{if(h.x===c.x)return[...i];d=o==="T"?1:-1,u="y",f="height"}const p=c.clone(),m=h.clone();if(p[u]+=d*(a[f]/2+r),m[u]-=d*(l[f]/2+r),g){const y=p.x,x=m.x,b=a.width/2+s,w=l.width/2+s;h.x>c.x?x<=y&&(p.x=Math.max(x,c.x+b),m.x=Math.min(y,h.x-w)):x>=y&&(p.x=Math.min(x,c.x-b),m.x=Math.max(y,h.x+w))}else{const y=p.y,x=m.y,b=a.height/2+s,w=l.height/2+s;h.y>c.y?x<=y&&(p.y=Math.max(x,c.y+b),m.y=Math.min(y,h.y-w)):x>=y&&(p.y=Math.min(x,c.y-b),m.y=Math.max(y,h.y+w))}return[p.toJSON(),...i,m.toJSON()]};function on(i,t){if(t!=null&&t!==!1){const e=typeof t=="boolean"?0:t;if(e>0){const n=v.create(i[1]).move(i[2],e),s=v.create(i[1]).move(i[0],e);return[n.toJSON(),...i,s.toJSON()]}{const n=i[1];return[Object.assign({},n),...i,Object.assign({},n)]}}return i}const yx=function(i,t,e){const n=t.width||50,r=(t.height||80)/2,o=t.angle||"auto",a=e.sourceAnchor,l=e.targetAnchor,c=e.sourceBBox,h=e.targetBBox;if(a.equals(l)){const u=y=>{const x=q.toRad(y),b=Math.sin(x),w=Math.cos(x),P=new v(a.x+w*n,a.y+b*n),A=new v(P.x-w*r,P.y-b*r),S=A.clone().rotate(-90,P),E=A.clone().rotate(90,P);return[S.toJSON(),P.toJSON(),E.toJSON()]},f=y=>{const x=a.clone().move(y,-1),b=new I(x,y);return!c.containsPoint(y)&&!c.intersectsWithLine(b)},d=[0,90,180,270,45,135,225,315];if(typeof o=="number")return on(u(o),t.merge);const g=c.getCenter();if(g.equals(a))return on(u(0),t.merge);const p=g.angleBetween(a,g.clone().translate(1,0));let m=u(p);if(f(m[1]))return on(m,t.merge);for(let y=1,x=d.length;y1&&(r.rotate(180-h,c),o.rotate(180-h,c),a.rotate(180-h,c))}const l=` + M ${i.x} ${i.y} + Q ${r.x} ${r.y} ${a.x} ${a.y} + Q ${o.x} ${o.y} ${t.x} ${t.y} + `;return n.raw?D.parse(l):l},wx=function(i,t,e,n={}){const s=new D;s.appendSegment(D.createSegment("M",i));const r=1/3,o=2/3,a=n.radius||10;let l,c;for(let h=0,u=e.length;h=Math.abs(i.y-t.y)?"H":"V"),r==="H"){const o=(i.x+t.x)/2;s.appendSegment(D.createSegment("C",o,i.y,o,t.y,t.x,t.y))}else{const o=(i.y+t.y)/2;s.appendSegment(D.createSegment("C",i.x,o,t.x,o,t.x,t.y))}return n.raw?s:s.serialize()},Hl=1,js=1/3,Ds=2/3;function Ax(i){let t=i.graph._jumpOverUpdateList;if(t==null&&(t=i.graph._jumpOverUpdateList=[],i.graph.on("cell:mouseup",()=>{const e=i.graph._jumpOverUpdateList;for(let n=0;n{t=i.graph._jumpOverUpdateList=[]})),t.indexOf(i)<0){t.push(i);const e=()=>t.splice(t.indexOf(i),1);i.cell.once("change:connector",e),i.cell.once("removed",e)}}function Ui(i,t,e=[]){const n=[i,...e,t],s=[];return n.forEach((r,o)=>{const a=n[o+1];a!=null&&s.push(new I(r,a))}),s}function Cx(i,t){const e=[];return t.forEach(n=>{const s=i.intersectsWithLine(n);s&&e.push(s)}),e}function ql(i,t){return new I(i,t).squaredLength()}function Sx(i,t,e){return t.reduce((n,s,r)=>{if($s.includes(s))return n;const o=n.pop()||i,a=v.create(s).move(o.start,-e);let l=v.create(s).move(o.start,+e);const c=t[r+1];if(c!=null){const f=l.distance(c);f<=e&&(l=c.move(o.start,f),$s.push(c))}else if(a.distance(o.end){if(qn.includes(o)){let l,c,h,u;if(e==="arc"){l=-90,c=o.start.diff(o.end),(c.x<0||c.x===0&&c.y<0)&&(l+=180);const d=o.getCenter(),g=new I(d,o.end).rotate(l,d);let p;p=new I(o.start,d),h=p.pointAt(2/3).rotate(l,o.start),u=g.pointAt(1/3).rotate(-l,g.end),r=D.createSegment("C",h,u,g.end),s.appendSegment(r),p=new I(d,o.end),h=g.pointAt(1/3).rotate(l,g.end),u=p.pointAt(1/3).rotate(-l,o.end),r=D.createSegment("C",h,u,o.end),s.appendSegment(r)}else if(e==="gap")r=D.createSegment("M",o.end),s.appendSegment(r);else if(e==="cubic"){l=o.start.theta(o.end);const f=t*.6;let d=t*1.35;c=o.start.diff(o.end),(c.x<0||c.x===0&&c.y<0)&&(d*=-1),h=new v(o.start.x+f,o.start.y+d).rotate(l,o.start),u=new v(o.end.x-f,o.end.y+d).rotate(l,o.end),r=D.createSegment("C",h,u,o.end),s.appendSegment(r)}}else{const l=i[a+1];n===0||!l||qn.includes(l)?(r=D.createSegment("L",o.end),s.appendSegment(r)):Ox(n,s,o.end,o.start,l.end)}}),s}function Ox(i,t,e,n,s){const r=e.distance(n)/2,o=e.distance(s)/2,a=-Math.min(i,r),l=-Math.min(i,o),c=e.clone().move(n,a).round(),h=e.clone().move(s,l).round(),u=new v(js*c.x+Ds*e.x,Ds*e.y+js*c.y),f=new v(js*h.x+Ds*e.x,Ds*e.y+js*h.y);let d;d=D.createSegment("L",c),t.appendSegment(d),d=D.createSegment("C",u,f,h),t.appendSegment(d)}let qn,$s;const Ex=function(i,t,e,n={}){qn=[],$s=[],Ax(this);const s=n.size||5,r=n.type||"arc",o=n.radius||0,a=n.ignoreConnectors||["smooth"],l=this.graph,h=l.model.getEdges();if(h.length===1)return Gl(Ui(i,t,e),s,r,o);const u=this.cell,f=h.indexOf(u),d=l.options.connecting.connector||{},g=h.filter((w,P)=>{const A=w.getConnector()||d;return a.includes(A.name)?!1:P>f?A.name!=="jumpover":!0}),p=g.map(w=>l.findViewByCell(w)),m=Ui(i,t,e),y=p.map(w=>w==null?[]:w===this?m:Ui(w.sourcePoint,w.targetPoint,w.routePoints)),x=[];m.forEach(w=>{const P=g.reduce((A,S,E)=>{if(S!==u){const N=Cx(w,y[E]);A.push(...N)}return A},[]).sort((A,S)=>ql(w.start,A)-ql(w.start,S));P.length>0?x.push(...Sx(w,P,s)):x.push(w)});const b=Gl(x,s,r,o);return qn=[],$s=[],n.raw?b:b.serialize()};var Mx=Object.freeze({__proto__:null,normal:xx,loop:vx,rounded:wx,smooth:Px,jumpover:Ex}),Ee;(function(i){i.presets=Mx,i.registry=st.create({type:"connector"}),i.registry.register(i.presets,!0)})(Ee||(Ee={}));var Tx=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Ul extends Pt{constructor(t={}){super();this.pending=!1,this.changing=!1,this.data={},this.mutate(tt(t)),this.changed={}}mutate(t,e={}){const n=e.unset===!0,s=e.silent===!0,r=[],o=this.changing;this.changing=!0,o||(this.previous=tt(this.data),this.changed={});const a=this.data,l=this.previous,c=this.changed;if(Object.keys(t).forEach(h=>{const u=h,f=t[u];Rt(a[u],f)||r.push(u),Rt(l[u],f)?delete c[u]:c[u]=f,n?delete a[u]:a[u]=f}),!s&&r.length>0&&(this.pending=!0,this.pendingOptions=e,r.forEach(h=>{this.emit("change:*",{key:h,options:e,store:this,current:a[h],previous:l[h]})})),o)return this;if(!s)for(;this.pending;)this.pending=!1,this.emit("changed",{current:a,previous:l,store:this,options:this.pendingOptions});return this.pending=!1,this.changing=!1,this.pendingOptions=null,this}get(t,e){if(t==null)return this.data;const n=this.data[t];return n==null?e:n}getPrevious(t){if(this.previous){const e=this.previous[t];return e==null?void 0:e}}set(t,e,n){return t!=null&&(typeof t=="object"?this.mutate(t,e):this.mutate({[t]:e},n)),this}remove(t,e){const n=void 0,s={};let r;if(typeof t=="string")s[t]=n,r=e;else if(Array.isArray(t))t.forEach(o=>s[o]=n),r=e;else{for(const o in this.data)s[o]=n;r=t}return this.mutate(s,Object.assign(Object.assign({},r),{unset:!0})),this}getByPath(t){return gi(this.data,t,"/")}setByPath(t,e,n={}){const s="/",r=Array.isArray(t)?[...t]:t.split(s),o=Array.isArray(t)?t.join(s):t,a=r[0],l=r.length;if(n.propertyPath=o,n.propertyValue=e,n.propertyPathArray=r,l===1)this.set(a,e,n);else{const c={};let h=c,u=a;for(let g=1;g0:t in this.changed}getChanges(t){if(t==null)return this.hasChanged()?tt(this.changed):null;const e=this.changing?this.previous:this.data,n={};let s;for(const r in t){const o=t[r];Rt(e[r],o)||(n[r]=o,s=!0)}return s?tt(n):null}toJSON(){return tt(this.data)}clone(){const t=this.constructor;return new t(this.data)}dispose(){this.off(),this.data={},this.previous={},this.changed={},this.pending=!1,this.changing=!1,this.pendingOptions=null,this.trigger("disposed",{store:this})}}Tx([Pt.dispose()],Ul.prototype,"dispose",null);class Gn{constructor(t){this.cell=t,this.ids={},this.cache={}}get(){return Object.keys(this.ids)}start(t,e,n={},s="/"){const r=this.cell.getPropByPath(t),o=xp(n,Gn.defaultOptions),a=this.getTiming(o.timing),l=this.getInterp(o.interp,r,e);let c=0;const h=Array.isArray(t)?t.join(s):t,u=Array.isArray(t)?t:t.split(s),f=()=>{const d=new Date().getTime();c===0&&(c=d);let p=(d-c)/o.duration;p<1?this.ids[h]=requestAnimationFrame(f):p=1;const m=l(a(p));this.cell.setPropByPath(u,m),n.progress&&n.progress(Object.assign({progress:p,currentValue:m},this.getArgs(h))),p===1&&(this.cell.notify("transition:complete",this.getArgs(h)),n.complete&&n.complete(this.getArgs(h)),this.cell.notify("transition:finish",this.getArgs(h)),n.finish&&n.finish(this.getArgs(h)),this.clean(h))};return setTimeout(()=>{this.stop(t,void 0,s),this.cache[h]={startValue:r,targetValue:e,options:o},this.ids[h]=requestAnimationFrame(f),this.cell.notify("transition:start",this.getArgs(h)),n.start&&n.start(this.getArgs(h))},n.delay),this.stop.bind(this,t,s,n)}stop(t,e={},n="/"){const s=Array.isArray(t)?t:t.split(n);return Object.keys(this.ids).filter(r=>Rt(s,r.split(n).slice(0,s.length))).forEach(r=>{cancelAnimationFrame(this.ids[r]);const o=this.cache[r],a=this.getArgs(r),l=Object.assign(Object.assign({},o.options),e),c=l.jumpedToEnd;c&&o.targetValue!=null&&(this.cell.setPropByPath(r,o.targetValue),this.cell.notify("transition:end",Object.assign({},a)),this.cell.notify("transition:complete",Object.assign({},a)),l.complete&&l.complete(Object.assign({},a)));const h=Object.assign({jumpedToEnd:c},a);this.cell.notify("transition:stop",Object.assign({},h)),l.stop&&l.stop(Object.assign({},h)),this.cell.notify("transition:finish",Object.assign({},a)),l.finish&&l.finish(Object.assign({},a)),this.clean(r)}),this}clean(t){delete this.ids[t],delete this.cache[t]}getTiming(t){return typeof t=="string"?Ae[t]:t}getInterp(t,e,n){return t?t(e,n):typeof n=="number"?Ce.number(e,n):typeof n=="string"?n[0]==="#"?Ce.color(e,n):Ce.unit(e,n):Ce.object(e,n)}getArgs(t){const e=this.cache[t];return{path:t,startValue:e.startValue,targetValue:e.targetValue,cell:this.cell}}}(function(i){i.defaultOptions={delay:10,duration:100,timing:"linear"}})(Gn||(Gn={}));var Nx=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r},Wl=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const a=n[o];typeof a=="function"&&this.propHooks.push(a)})),s&&(this.attrHooks=Object.assign(Object.assign({},this.attrHooks),s)),this.defaults=ot({},this.defaults,r)}static getMarkup(){return this.markup}static getDefaults(t){return t?this.defaults:tt(this.defaults)}static getAttrHooks(){return this.attrHooks}static applyPropHooks(t,e){return this.propHooks.reduce((n,s)=>s?R(s,t,n):n,e)}get[Symbol.toStringTag](){return z.toStringTag}init(){}get model(){return this._model}set model(t){this._model!==t&&(this._model=t)}preprocess(t,e){const n=t.id,r=this.constructor.applyPropHooks(this,t);return n==null&&e!==!0&&(r.id=yi()),r}postprocess(t){}setup(){this.store.on("change:*",t=>{const{key:e,current:n,previous:s,options:r}=t;this.notify("change:*",{key:e,options:r,current:n,previous:s,cell:this}),this.notify(`change:${e}`,{options:r,current:n,previous:s,cell:this});const o=e;(o==="source"||o==="target")&&this.notify("change:terminal",{type:o,current:n,previous:s,options:r,cell:this})}),this.store.on("changed",({options:t})=>this.notify("changed",{options:t,cell:this}))}notify(t,e){this.trigger(t,e);const n=this.model;return n&&(n.notify(`cell:${t}`,e),this.isNode()?n.notify(`node:${t}`,Object.assign(Object.assign({},e),{node:this})):this.isEdge()&&n.notify(`edge:${t}`,Object.assign(Object.assign({},e),{edge:this}))),this}isNode(){return!1}isEdge(){return!1}isSameStore(t){return this.store===t.store}get view(){return this.store.get("view")}get shape(){return this.store.get("shape","")}getProp(t,e){return t==null?this.store.get():this.store.get(t,e)}setProp(t,e,n){if(typeof t=="string")this.store.set(t,e,n);else{const s=this.preprocess(t,!0);this.store.set(ot({},this.getProp(),s),e),this.postprocess(t)}return this}removeProp(t,e){return typeof t=="string"||Array.isArray(t)?this.store.removeByPath(t,e):this.store.remove(e),this}hasChanged(t){return t==null?this.store.hasChanged():this.store.hasChanged(t)}getPropByPath(t){return this.store.getByPath(t)}setPropByPath(t,e,n={}){return this.model&&(t==="children"?this._children=e?e.map(s=>this.model.getCell(s)).filter(s=>s!=null):null:t==="parent"&&(this._parent=e?this.model.getCell(e):null)),this.store.setByPath(t,e,n),this}removePropByPath(t,e={}){const n=Array.isArray(t)?t:t.split("/");return n[0]==="attrs"&&(e.dirty=!0),this.store.removeByPath(n,e),this}prop(t,e,n){return t==null?this.getProp():typeof t=="string"||Array.isArray(t)?arguments.length===1?this.getPropByPath(t):e==null?this.removePropByPath(t,n||{}):this.setPropByPath(t,e,n||{}):this.setProp(t,e||{})}previous(t){return this.store.getPrevious(t)}get zIndex(){return this.getZIndex()}set zIndex(t){t==null?this.removeZIndex():this.setZIndex(t)}getZIndex(){return this.store.get("zIndex")}setZIndex(t,e={}){return this.store.set("zIndex",t,e),this}removeZIndex(t={}){return this.store.remove("zIndex",t),this}toFront(t={}){const e=this.model;if(e){let n=e.getMaxZIndex(),s;t.deep?(s=this.getDescendants({deep:!0,breadthFirst:!0}),s.unshift(this)):s=[this],n=n-s.length+1;const r=e.total();let o=e.indexOf(this)!==r-s.length;o||(o=s.some((a,l)=>a.getZIndex()!==n+l)),o&&this.batchUpdate("to-front",()=>{n+=s.length,s.forEach((a,l)=>{a.setZIndex(n+l,t)})})}return this}toBack(t={}){const e=this.model;if(e){let n=e.getMinZIndex(),s;t.deep?(s=this.getDescendants({deep:!0,breadthFirst:!0}),s.unshift(this)):s=[this];let r=e.indexOf(this)!==0;r||(r=s.some((o,a)=>o.getZIndex()!==n+a)),r&&this.batchUpdate("to-back",()=>{n-=s.length,s.forEach((o,a)=>{o.setZIndex(n+a,t)})})}return this}get markup(){return this.getMarkup()}set markup(t){t==null?this.removeMarkup():this.setMarkup(t)}getMarkup(){let t=this.store.get("markup");return t==null&&(t=this.constructor.getMarkup()),t}setMarkup(t,e={}){return this.store.set("markup",t,e),this}removeMarkup(t={}){return this.store.remove("markup",t),this}get attrs(){return this.getAttrs()}set attrs(t){t==null?this.removeAttrs():this.setAttrs(t)}getAttrs(){const t=this.store.get("attrs");return t?Object.assign({},t):{}}setAttrs(t,e={}){if(t==null)this.removeAttrs(e);else{const n=s=>this.store.set("attrs",s,e);if(e.overwrite===!0)n(t);else{const s=this.getAttrs();e.deep===!1?n(Object.assign(Object.assign({},s),t)):n(ot({},s,t))}}return this}replaceAttrs(t,e={}){return this.setAttrs(t,Object.assign(Object.assign({},e),{overwrite:!0}))}updateAttrs(t,e={}){return this.setAttrs(t,Object.assign(Object.assign({},e),{deep:!1}))}removeAttrs(t={}){return this.store.remove("attrs",t),this}getAttrDefinition(t){if(!t)return null;const n=this.constructor.getAttrHooks()||{};let s=n[t]||Bt.registry.get(t);if(!s){const r=rs(t);s=n[r]||Bt.registry.get(r)}return s||null}getAttrByPath(t){return t==null||t===""?this.getAttrs():this.getPropByPath(this.prefixAttrPath(t))}setAttrByPath(t,e,n={}){return this.setPropByPath(this.prefixAttrPath(t),e,n),this}removeAttrByPath(t,e={}){return this.removePropByPath(this.prefixAttrPath(t),e),this}prefixAttrPath(t){return Array.isArray(t)?["attrs"].concat(t):`attrs/${t}`}attr(t,e,n){return t==null?this.getAttrByPath():typeof t=="string"||Array.isArray(t)?arguments.length===1?this.getAttrByPath(t):e==null?this.removeAttrByPath(t,n||{}):this.setAttrByPath(t,e,n||{}):this.setAttrs(t,e||{})}get visible(){return this.isVisible()}set visible(t){this.setVisible(t)}setVisible(t,e={}){return this.store.set("visible",t,e),this}isVisible(){return this.store.get("visible")!==!1}show(t={}){return this.isVisible()||this.setVisible(!0,t),this}hide(t={}){return this.isVisible()&&this.setVisible(!1,t),this}toggleVisible(t,e={}){const n=typeof t=="boolean"?t:!this.isVisible(),s=typeof t=="boolean"?e:t;return n?this.show(s):this.hide(s),this}get data(){return this.getData()}set data(t){this.setData(t)}getData(){return this.store.get("data")}setData(t,e={}){if(t==null)this.removeData(e);else{const n=s=>this.store.set("data",s,e);if(e.overwrite===!0)n(t);else{const s=this.getData();e.deep===!1?n(typeof t=="object"?Object.assign(Object.assign({},s),t):t):n(ot({},s,t))}}return this}replaceData(t,e={}){return this.setData(t,Object.assign(Object.assign({},e),{overwrite:!0}))}updateData(t,e={}){return this.setData(t,Object.assign(Object.assign({},e),{deep:!1}))}removeData(t={}){return this.store.remove("data",t),this}get parent(){return this.getParent()}get children(){return this.getChildren()}getParentId(){return this.store.get("parent")}getParent(){const t=this.getParentId();if(t&&this.model){const e=this.model.getCell(t);return this._parent=e,e}return null}getChildren(){const t=this.store.get("children");if(t&&t.length&&this.model){const e=t.map(n=>{var s;return(s=this.model)===null||s===void 0?void 0:s.getCell(n)}).filter(n=>n!=null);return this._children=e,[...e]}return null}hasParent(){return this.parent!=null}isParentOf(t){return t!=null&&t.getParent()===this}isChildOf(t){return t!=null&&this.getParent()===t}eachChild(t,e){return this.children&&this.children.forEach(t,e),this}filterChild(t,e){return this.children?this.children.filter(t,e):[]}getChildCount(){return this.children==null?0:this.children.length}getChildIndex(t){return this.children==null?-1:this.children.indexOf(t)}getChildAt(t){return this.children!=null&&t>=0?this.children[t]:null}getAncestors(t={}){const e=[];let n=this.getParent();for(;n;)e.push(n),n=t.deep!==!1?n.getParent():null;return e}getDescendants(t={}){if(t.deep!==!1){if(t.breadthFirst){const e=[],n=this.getChildren()||[];for(;n.length>0;){const s=n.shift(),r=s.getChildren();e.push(s),r&&n.push(...r)}return e}{const e=this.getChildren()||[];return e.forEach(n=>{e.push(...n.getDescendants(t))}),e}}return this.getChildren()||[]}isDescendantOf(t,e={}){if(t==null)return!1;if(e.deep!==!1){let n=this.getParent();for(;n;){if(n===t)return!0;n=n.getParent()}return!1}return this.isChildOf(t)}isAncestorOf(t,e={}){return t==null?!1:t.isDescendantOf(this,e)}contains(t){return this.isAncestorOf(t)}getCommonAncestor(...t){return z.getCommonAncestor(this,...t)}setParent(t,e={}){return this._parent=t,t?this.store.set("parent",t.id,e):this.store.remove("parent",e),this}setChildren(t,e={}){return this._children=t,t!=null?this.store.set("children",t.map(n=>n.id),e):this.store.remove("children",e),this}unembed(t,e={}){const n=this.children;if(n!=null&&t!=null){const s=this.getChildIndex(t);s!==-1&&(n.splice(s,1),t.setParent(null,e),this.setChildren(n,e))}return this}embed(t,e={}){return t.addTo(this,e),this}addTo(t,e={}){return z.isCell(t)?t.addChild(this,e):t.addCell(this,e),this}insertTo(t,e,n={}){return t.insertChild(this,e,n),this}addChild(t,e={}){return this.insertChild(t,void 0,e)}insertChild(t,e,n={}){if(t!=null&&t!==this){const s=t.getParent(),r=this!==s;let o=e;if(o==null&&(o=this.getChildCount(),r||(o-=1)),s){const l=s.getChildren();if(l){const c=l.indexOf(t);c>=0&&(t.setParent(null,n),l.splice(c,1),s.setChildren(l,n))}}let a=this.children;if(a==null?(a=[],a.push(t)):a.splice(o,0,t),t.setParent(this,n),this.setChildren(a,n),r&&this.model){const l=this.model.getIncomingEdges(this),c=this.model.getOutgoingEdges(this);l&&l.forEach(h=>h.updateParent(n)),c&&c.forEach(h=>h.updateParent(n))}this.model&&this.model.addCell(t,n)}return this}removeFromParent(t={}){const e=this.getParent();if(e!=null){const n=e.getChildIndex(this);e.removeChildAt(n,t)}return this}removeChild(t,e={}){const n=this.getChildIndex(t);return this.removeChildAt(n,e)}removeChildAt(t,e={}){const n=this.getChildAt(t);return this.children!=null&&n!=null&&(this.unembed(n,e),n.remove(e)),n}remove(t={}){return this.batchUpdate("remove",()=>{const e=this.getParent();e&&e.removeChild(this,t),t.deep!==!1&&this.eachChild(n=>n.remove(t)),this.model&&this.model.removeCell(this,t)}),this}transition(t,e,n={},s="/"){return this.animation.start(t,e,n,s)}stopTransition(t,e,n="/"){return this.animation.stop(t,e,n),this}getTransitions(){return this.animation.get()}translate(t,e,n){return this}scale(t,e,n,s){return this}addTools(t,e,n){const s=Array.isArray(t)?t:[t],r=typeof e=="string"?e:null,o=typeof e=="object"?e:typeof n=="object"?n:{};if(o.reset)return this.setTools({name:r,items:s,local:o.local},o);let a=tt(this.getTools());if(a==null||r==null||a.name===r)return a==null&&(a={}),a.items||(a.items=[]),a.name=r,a.items=[...a.items,...s],this.setTools(Object.assign({},a),o)}setTools(t,e={}){return t==null?this.removeTools():this.store.set("tools",z.normalizeTools(t),e),this}getTools(){return this.store.get("tools")}removeTools(t={}){return this.store.remove("tools",t),this}hasTools(t){const e=this.getTools();return e==null?!1:t==null?!0:e.name===t}hasTool(t){const e=this.getTools();return e==null?!1:e.items.some(n=>typeof n=="string"?n===t:n.name===t)}removeTool(t,e={}){const n=tt(this.getTools());if(n){let s=!1;const r=n.items.slice(),o=a=>{r.splice(a,1),s=!0};if(typeof t=="number")o(t);else for(let a=r.length-1;a>=0;a-=1){const l=r[a];(typeof l=="string"?l===t:l.name===t)&&o(a)}s&&(n.items=r,this.setTools(n,e))}return this}getBBox(t){return new M}getConnectionPoint(t,e){return new v}toJSON(t={}){const e=Object.assign({},this.store.get()),n=Object.prototype.toString,s=this.isNode()?"node":this.isEdge()?"edge":"cell";if(!e.shape){const g=this.constructor;throw new Error(`Unable to serialize ${s} missing "shape" prop, check the ${s} "${g.name||n.call(g)}"`)}const r=this.constructor,o=t.diff===!0,a=e.attrs||{},l=r.getDefaults(!0),c=o?this.preprocess(l,!0):l,h=c.attrs||{},u={};Object.keys(e).forEach(g=>{const p=e[g];if(p!=null&&!Array.isArray(p)&&typeof p=="object"&&!$t(p))throw new Error(`Can only serialize ${s} with plain-object props, but got a "${n.call(p)}" type of key "${g}" on ${s} "${this.id}"`);if(g!=="attrs"&&g!=="shape"&&o){const m=c[g];Rt(p,m)&&delete e[g]}}),Object.keys(a).forEach(g=>{const p=a[g],m=h[g];Object.keys(p).forEach(y=>{const x=p[y],b=m?m[y]:null;x!=null&&typeof x=="object"&&!Array.isArray(x)?Object.keys(x).forEach(w=>{const P=x[w];if(m==null||b==null||!rt(b)||!Rt(b[w],P)){u[g]==null&&(u[g]={}),u[g][y]==null&&(u[g][y]={});const A=u[g][y];A[w]=P}}):(m==null||!Rt(b,x))&&(u[g]==null&&(u[g]={}),u[g][y]=x)})});const f=Object.assign(Object.assign({},e),{attrs:Fo(u)?void 0:u});f.attrs==null&&delete f.attrs;const d=f;return d.angle===0&&delete d.angle,tt(d)}clone(t={}){if(!t.deep){const n=Object.assign({},this.store.get());t.keepId||delete n.id,delete n.parent,delete n.children;const s=this.constructor;return new s(n)}return z.deepClone(this)[this.id]}findView(t){return t.findViewByCell(this)}startBatch(t,e={},n=this.model){return this.notify("batch:start",{name:t,data:e,cell:this}),n&&n.startBatch(t,Object.assign(Object.assign({},e),{cell:this})),this}stopBatch(t,e={},n=this.model){return n&&n.stopBatch(t,Object.assign(Object.assign({},e),{cell:this})),this.notify("batch:stop",{name:t,data:e,cell:this}),this}batchUpdate(t,e,n){const s=this.model;this.startBatch(t,n,s);const r=e();return this.stopBatch(t,n,s),r}dispose(){this.removeFromParent(),this.store.dispose()}}z.defaults={},z.attrHooks={},z.propHooks=[],Nx([Pt.dispose()],z.prototype,"dispose",null),function(i){function t(e){return typeof e=="string"?{items:[e]}:Array.isArray(e)?{items:e}:e.items?e:{items:[e]}}i.normalizeTools=t}(z||(z={})),function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNode=="function"&&typeof s.isEdge=="function"&&typeof s.prop=="function"&&typeof s.attr=="function"}i.isCell=t}(z||(z={})),function(i){function t(...r){const o=r.filter(l=>l!=null).map(l=>l.getAncestors()).sort((l,c)=>l.length-c.length);return o.shift().find(l=>o.every(c=>c.includes(l)))||null}i.getCommonAncestor=t;function e(r,o={}){let a=null;for(let l=0,c=r.length;l(l[c.id]=c.clone(),l),{});return o.forEach(l=>{const c=a[l.id];if(c.isEdge()){const f=c.getSourceCellId(),d=c.getTargetCellId();f&&a[f]&&c.setSource(Object.assign(Object.assign({},c.getSource()),{cell:a[f].id})),d&&a[d]&&c.setTarget(Object.assign(Object.assign({},c.getTarget()),{cell:a[d].id}))}const h=l.getParent();h&&a[h.id]&&c.setParent(a[h.id]);const u=l.getChildren();if(u&&u.length){const f=u.reduce((d,g)=>(a[g.id]&&d.push(a[g.id]),d),[]);f.length>0&&c.setChildren(f)}}),a}i.cloneCells=s}(z||(z={})),function(i){i.config({propHooks(t){var{tools:e}=t,n=Wl(t,["tools"]);return e&&(n.tools=i.normalizeTools(e)),n}})}(z||(z={}));var an;(function(i){let t,e;function n(o,a){return a?t!=null&&t.exist(o):e!=null&&e.exist(o)}i.exist=n;function s(o){t=o}i.setEdgeRegistry=s;function r(o){e=o}i.setNodeRegistry=r})(an||(an={}));class Lx{constructor(t){this.ports=[],this.groups={},this.init(tt(t))}getPorts(){return this.ports}getGroup(t){return t!=null?this.groups[t]:null}getPortsByGroup(t){return this.ports.filter(e=>e.group===t||e.group==null&&t==null)}getPortsLayoutByGroup(t,e){const n=this.getPortsByGroup(t),s=t?this.getGroup(t):null,r=s?s.position:null,o=r?r.name:null;let a;if(o!=null){const u=Oe.registry.get(o);if(u==null)return Oe.registry.onNotFound(o);a=u}else a=Oe.presets.left;const l=n.map(u=>u&&u.position&&u.position.args||{}),c=r&&r.args||{};return a(l,e,c).map((u,f)=>{const d=n[f];return{portLayout:u,portId:d.id,portSize:d.size,portAttrs:d.attrs,labelSize:d.label.size,labelLayout:this.getPortLabelLayout(d,v.create(u.position),e)}})}init(t){const{groups:e,items:n}=t;e!=null&&Object.keys(e).forEach(s=>{this.groups[s]=this.parseGroup(e[s])}),Array.isArray(n)&&n.forEach(s=>{this.ports.push(this.parsePort(s))})}parseGroup(t){return Object.assign(Object.assign({},t),{label:this.getLabel(t,!0),position:this.getPortPosition(t.position,!0)})}parsePort(t){const e=Object.assign({},t),n=this.getGroup(t.group)||{};return e.markup=e.markup||n.markup,e.attrs=ot({},n.attrs,e.attrs),e.position=this.createPosition(n,e),e.label=ot({},n.label,this.getLabel(e)),e.zIndex=this.getZIndex(n,e),e.size=Object.assign(Object.assign({},n.size),e.size),e}getZIndex(t,e){return typeof e.zIndex=="number"?e.zIndex:typeof t.zIndex=="number"||t.zIndex==="auto"?t.zIndex:"auto"}createPosition(t,e){return ot({name:"left",args:{}},t.position,{args:e.args})}getPortPosition(t,e=!1){if(t==null){if(e)return{name:"left",args:{}}}else{if(typeof t=="string")return{name:t,args:{}};if(Array.isArray(t))return{name:"absolute",args:{x:t[0],y:t[1]}};if(typeof t=="object")return t}return{args:{}}}getPortLabelPosition(t,e=!1){if(t==null){if(e)return{name:"left",args:{}}}else{if(typeof t=="string")return{name:t,args:{}};if(typeof t=="object")return t}return{args:{}}}getLabel(t,e=!1){const n=t.label||{};return n.position=this.getPortLabelPosition(n.position,e),n}getPortLabelLayout(t,e,n){const s=t.label.position.name||"left",r=t.label.position.args||{},o=Ke.registry.get(s)||Ke.presets.left;return o?o(e,n,r):null}}var Rs=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{var a;((a=n.exclude)===null||a===void 0?void 0:a.includes(o))||o.translate(t,e,n)})):(this.startBatch("translate",n),this.store.set("position",r,n),this.eachChild(o=>{var a;((a=n.exclude)===null||a===void 0?void 0:a.includes(o))||o.translate(t,e,n)}),this.stopBatch("translate",n)),this}angle(t,e){return t==null?this.getAngle():this.rotate(t,e)}getAngle(){return this.store.get("angle",0)}rotate(t,e={}){const n=this.getAngle();if(e.center){const s=this.getSize(),r=this.getPosition(),o=this.getBBox().getCenter();o.rotate(n-t,e.center);const a=o.x-s.width/2-r.x,l=o.y-s.height/2-r.y;this.startBatch("rotate",{angle:t,options:e}),this.setPosition(r.x+a,r.y+l,e),this.rotate(t,Object.assign(Object.assign({},e),{center:null})),this.stopBatch("rotate")}else this.store.set("angle",e.absolute?t:(n+t)%360,e);return this}getBBox(t={}){if(t.deep){const e=this.getDescendants({deep:!0,breadthFirst:!0});return e.push(this),z.getCellsBBox(e)}return M.fromPositionAndSize(this.getPosition(),this.getSize())}getConnectionPoint(t,e){const n=this.getBBox(),s=n.getCenter(),r=t.getTerminal(e);if(r==null)return s;const o=r.port;if(!o||!this.hasPort(o))return s;const a=this.getPort(o);if(!a||!a.group)return s;const c=this.getPortsPosition(a.group)[o].position,h=v.create(c).translate(n.getOrigin()),u=this.getAngle();return u&&h.rotate(-u,s),h}fit(t={}){const n=(this.getChildren()||[]).filter(c=>c.isNode());if(n.length===0)return this;this.startBatch("fit-embeds",t),t.deep&&n.forEach(c=>c.fit(t));let{x:s,y:r,width:o,height:a}=z.getCellsBBox(n);const l=ne(t.padding);return s-=l.left,r-=l.top,o+=l.left+l.right,a+=l.bottom+l.top,this.store.set({position:{x:s,y:r},size:{width:o,height:a}},t),this.stopBatch("fit-embeds"),this}get portContainerMarkup(){return this.getPortContainerMarkup()}set portContainerMarkup(t){this.setPortContainerMarkup(t)}getDefaultPortContainerMarkup(){return this.store.get("defaultPortContainerMarkup")||X.getPortContainerMarkup()}getPortContainerMarkup(){return this.store.get("portContainerMarkup")||this.getDefaultPortContainerMarkup()}setPortContainerMarkup(t,e={}){return this.store.set("portContainerMarkup",X.clone(t),e),this}get portMarkup(){return this.getPortMarkup()}set portMarkup(t){this.setPortMarkup(t)}getDefaultPortMarkup(){return this.store.get("defaultPortMarkup")||X.getPortMarkup()}getPortMarkup(){return this.store.get("portMarkup")||this.getDefaultPortMarkup()}setPortMarkup(t,e={}){return this.store.set("portMarkup",X.clone(t),e),this}get portLabelMarkup(){return this.getPortLabelMarkup()}set portLabelMarkup(t){this.setPortLabelMarkup(t)}getDefaultPortLabelMarkup(){return this.store.get("defaultPortLabelMarkup")||X.getPortLabelMarkup()}getPortLabelMarkup(){return this.store.get("portLabelMarkup")||this.getDefaultPortLabelMarkup()}setPortLabelMarkup(t,e={}){return this.store.set("portLabelMarkup",X.clone(t),e),this}get ports(){const t=this.store.get("ports",{items:[]});return t.items==null&&(t.items=[]),t}getPorts(){return tt(this.ports.items)}getPortsByGroup(t){return this.getPorts().filter(e=>e.group===t)}getPort(t){return tt(this.ports.items.find(e=>e.id&&e.id===t))}getPortAt(t){return this.ports.items[t]||null}hasPorts(){return this.ports.items.length>0}hasPort(t){return this.getPortIndex(t)!==-1}getPortIndex(t){const e=typeof t=="string"?t:t.id;return e!=null?this.ports.items.findIndex(n=>n.id===e):-1}getPortsPosition(t){const e=this.getSize();return this.port.getPortsLayoutByGroup(t,new M(0,0,e.width,e.height)).reduce((s,r)=>{const o=r.portLayout;return s[r.portId]={position:Object.assign({},o.position),angle:o.angle||0},s},{})}getPortProp(t,e){return this.getPropByPath(this.prefixPortPath(t,e))}setPortProp(t,e,n,s){if(typeof e=="string"||Array.isArray(e)){const a=this.prefixPortPath(t,e),l=n;return this.setPropByPath(a,l,s)}const r=this.prefixPortPath(t),o=e;return this.setPropByPath(r,o,n)}removePortProp(t,e,n){return typeof e=="string"||Array.isArray(e)?this.removePropByPath(this.prefixPortPath(t,e),n):this.removePropByPath(this.prefixPortPath(t),e)}portProp(t,e,n,s){return e==null?this.getPortProp(t):typeof e=="string"||Array.isArray(e)?arguments.length===2?this.getPortProp(t,e):n==null?this.removePortProp(t,e,s):this.setPortProp(t,e,n,s):this.setPortProp(t,e,n)}prefixPortPath(t,e){const n=this.getPortIndex(t);if(n===-1)throw new Error(`Unable to find port with id: "${t}"`);return e==null||e===""?["ports","items",`${n}`]:Array.isArray(e)?["ports","items",`${n}`,...e]:`ports/items/${n}/${e}`}addPort(t,e){const n=[...this.ports.items];return n.push(t),this.setPropByPath("ports/items",n,e),this}addPorts(t,e){return this.setPropByPath("ports/items",[...this.ports.items,...t],e),this}insertPort(t,e,n){const s=[...this.ports.items];return s.splice(t,0,e),this.setPropByPath("ports/items",s,n),this}removePort(t,e={}){return this.removePortAt(this.getPortIndex(t),e)}removePortAt(t,e={}){if(t>=0){const n=[...this.ports.items];n.splice(t,1),e.rewrite=!0,this.setPropByPath("ports/items",n,e)}return this}removePorts(t,e){let n;if(Array.isArray(t)){if(n=e||{},t.length){n.rewrite=!0;const r=[...this.ports.items].filter(o=>!t.some(a=>{const l=typeof a=="string"?a:a.id;return o.id===l}));this.setPropByPath("ports/items",r,n)}}else n=t||{},n.rewrite=!0,this.setPropByPath("ports/items",[],n);return this}getParsedPorts(){return this.port.getPorts()}getParsedGroups(){return this.port.groups}getPortsLayoutByGroup(t,e){return this.port.getPortsLayoutByGroup(t,e)}initPorts(){this.updatePortData(),this.on("change:ports",()=>{this.processRemovedPort(),this.updatePortData()})}processRemovedPort(){const t=this.ports,e={};t.items.forEach(o=>{o.id&&(e[o.id]=!0)});const n={};(this.store.getPrevious("ports")||{items:[]}).items.forEach(o=>{o.id&&!e[o.id]&&(n[o.id]=!0)});const r=this.model;r&&!Fo(n)&&(r.getConnectedEdges(this,{incoming:!0}).forEach(l=>{const c=l.getTargetPortId();c&&n[c]&&l.remove()}),r.getConnectedEdges(this,{outgoing:!0}).forEach(l=>{const c=l.getSourcePortId();c&&n[c]&&l.remove()}))}validatePorts(){const t={},e=[];return this.ports.items.forEach(n=>{typeof n!="object"&&e.push(`Invalid port ${n}.`),n.id==null&&(n.id=this.generatePortId()),t[n.id]&&e.push("Duplicitied port id."),t[n.id]=!0}),e}generatePortId(){return yi()}updatePortData(){const t=this.validatePorts();if(t.length>0)throw this.store.set("ports",this.store.getPrevious("ports")),new Error(t.join(" "));const e=this.port?this.port.getPorts():null;this.port=new Lx(this.ports);const n=this.port.getPorts(),s=e?n.filter(o=>e.find(a=>a.id===o.id)?null:o):[...n],r=e?e.filter(o=>n.find(a=>a.id===o.id)?null:o):[];s.length>0&&this.notify("ports:added",{added:s,cell:this,node:this}),r.length>0&&this.notify("ports:removed",{removed:r,cell:this,node:this})}}it.defaults={angle:0,position:{x:0,y:0},size:{width:1,height:1}},function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNode=="function"&&typeof s.isEdge=="function"&&typeof s.prop=="function"&&typeof s.attr=="function"&&typeof s.size=="function"&&typeof s.position=="function"}i.isNode=t}(it||(it={})),function(i){i.config({propHooks(t){var{ports:e}=t,n=Rs(t,["ports"]);return e&&(n.ports=Array.isArray(e)?{items:e}:e),n}})}(it||(it={})),function(i){i.registry=st.create({type:"node",process(t,e){if(an.exist(t,!0))throw new Error(`Node with name '${t}' was registered by anthor Edge`);if(typeof e=="function")return e.config({shape:t}),e;let n=i;const{inherit:s}=e,r=Rs(e,["inherit"]);if(s)if(typeof s=="string"){const a=this.get(s);a==null?this.onNotFound(s,"inherited"):n=a}else n=s;r.constructorName==null&&(r.constructorName=t);const o=n.define.call(n,r);return o.config({shape:t}),o}}),an.setNodeRegistry(i.registry)}(it||(it={})),function(i){let t=0;function e(r){return r?pi(r):(t+=1,`CustomNode${t}`)}function n(r){const{constructorName:o,overwrite:a}=r,l=Rs(r,["constructorName","overwrite"]),c=di(e(o||l.shape),this);return c.config(l),l.shape&&i.registry.register(l.shape,c,a),c}i.define=n;function s(r){const o=r.shape||"rect",a=i.registry.get(o);return a?new a(r):i.registry.onNotFound(o)}i.create=s}(it||(it={}));var ks=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);stypeof g=="string"||typeof g=="number";if(n!=null)if(z.isCell(n))f.source={cell:n.id};else if(d(n))f.source={cell:n};else if(v.isPoint(n))f.source=n.toJSON();else if(Array.isArray(n))f.source={x:n[0],y:n[1]};else{const g=n.cell;z.isCell(g)?f.source=Object.assign(Object.assign({},n),{cell:g.id}):f.source=n}if(s!=null||r!=null){let g=f.source;if(s!=null){const p=d(s)?s:s.id;g?g.cell=p:g=f.source={cell:p}}r!=null&&g&&(g.port=r)}else o!=null&&(f.source=v.create(o).toJSON());if(a!=null)if(z.isCell(a))f.target={cell:a.id};else if(d(a))f.target={cell:a};else if(v.isPoint(a))f.target=a.toJSON();else if(Array.isArray(a))f.target={x:a[0],y:a[1]};else{const g=a.cell;z.isCell(g)?f.target=Object.assign(Object.assign({},a),{cell:g.id}):f.target=a}if(l!=null||c!=null){let g=f.target;if(l!=null){const p=d(l)?l:l.id;g?g.cell=p:g=f.target={cell:p}}c!=null&&g&&(g.port=c)}else h!=null&&(f.target=v.create(h).toJSON());return super.preprocess(f,e)}setup(){super.setup(),this.on("change:labels",t=>this.onLabelsChanged(t)),this.on("change:vertices",t=>this.onVertexsChanged(t))}isEdge(){return!0}disconnect(t={}){return this.store.set({source:{x:0,y:0},target:{x:0,y:0}},t),this}get source(){return this.getSource()}set source(t){this.setSource(t)}getSource(){return this.getTerminal("source")}getSourceCellId(){return this.source.cell}getSourcePortId(){return this.source.port}setSource(t,e,n={}){return this.setTerminal("source",t,e,n)}get target(){return this.getTarget()}set target(t){this.setTarget(t)}getTarget(){return this.getTerminal("target")}getTargetCellId(){return this.target.cell}getTargetPortId(){return this.target.port}setTarget(t,e,n={}){return this.setTerminal("target",t,e,n)}getTerminal(t){return Object.assign({},this.store.get(t))}setTerminal(t,e,n,s={}){if(z.isCell(e))return this.store.set(t,ot({},n,{cell:e.id}),s),this;const r=e;return v.isPoint(e)||r.x!=null&&r.y!=null?(this.store.set(t,ot({},n,{x:r.x,y:r.y}),s),this):(this.store.set(t,tt(e),s),this)}getSourcePoint(){return this.getTerminalPoint("source")}getTargetPoint(){return this.getTerminalPoint("target")}getTerminalPoint(t){const e=this[t];if(v.isPointLike(e))return v.create(e);const n=this.getTerminalCell(t);return n?n.getConnectionPoint(this,t):new v}getSourceCell(){return this.getTerminalCell("source")}getTargetCell(){return this.getTerminalCell("target")}getTerminalCell(t){if(this.model){const e=t==="source"?this.getSourceCellId():this.getTargetCellId();if(e)return this.model.getCell(e)}return null}getSourceNode(){return this.getTerminalNode("source")}getTargetNode(){return this.getTerminalNode("target")}getTerminalNode(t){let e=this;const n={};for(;e&&e.isEdge();){if(n[e.id])return null;n[e.id]=!0,e=e.getTerminalCell(t)}return e&&e.isNode()?e:null}get router(){return this.getRouter()}set router(t){t==null?this.removeRouter():this.setRouter(t)}getRouter(){return this.store.get("router")}setRouter(t,e,n){return typeof t=="object"?this.store.set("router",t,e):this.store.set("router",{name:t,args:e},n),this}removeRouter(t={}){return this.store.remove("router",t),this}get connector(){return this.getConnector()}set connector(t){t==null?this.removeConnector():this.setConnector(t)}getConnector(){return this.store.get("connector")}setConnector(t,e,n){return typeof t=="object"?this.store.set("connector",t,e):this.store.set("connector",{name:t,args:e},n),this}removeConnector(t={}){return this.store.remove("connector",t)}getDefaultLabel(){const t=this.constructor,e=this.store.get("defaultLabel")||t.defaultLabel||{};return tt(e)}get labels(){return this.getLabels()}set labels(t){this.setLabels(t)}getLabels(){return[...this.store.get("labels",[])].map(t=>this.parseLabel(t))}setLabels(t,e={}){return this.store.set("labels",Array.isArray(t)?t:[t],e),this}insertLabel(t,e,n={}){const s=this.getLabels(),r=s.length;let o=e!=null&&Number.isFinite(e)?e:r;return o<0&&(o=r+o+1),s.splice(o,0,this.parseLabel(t)),this.setLabels(s,n)}appendLabel(t,e={}){return this.insertLabel(t,-1,e)}getLabelAt(t){const e=this.getLabels();return t!=null&&Number.isFinite(t)?this.parseLabel(e[t]):null}setLabelAt(t,e,n={}){if(t!=null&&Number.isFinite(t)){const s=this.getLabels();s[t]=this.parseLabel(e),this.setLabels(s,n)}return this}removeLabelAt(t,e={}){const n=this.getLabels(),s=t!=null&&Number.isFinite(t)?t:-1,r=n.splice(s,1);return this.setLabels(n,e),r.length?r[0]:null}parseLabel(t){return typeof t=="string"?this.constructor.parseStringLabel(t):t}onLabelsChanged({previous:t,current:e}){const n=t&&e?e.filter(r=>t.find(o=>r===o||Rt(r,o))?null:r):e?[...e]:[],s=t&&e?t.filter(r=>e.find(o=>r===o||Rt(r,o))?null:r):t?[...t]:[];n.length>0&&this.notify("labels:added",{added:n,cell:this,edge:this}),s.length>0&&this.notify("labels:removed",{removed:s,cell:this,edge:this})}get vertices(){return this.getVertices()}set vertices(t){this.setVertices(t)}getVertices(){return[...this.store.get("vertices",[])]}setVertices(t,e={}){const n=Array.isArray(t)?t:[t];return this.store.set("vertices",n.map(s=>v.toJSON(s)),e),this}insertVertex(t,e,n={}){const s=this.getVertices(),r=s.length;let o=e!=null&&Number.isFinite(e)?e:r;return o<0&&(o=r+o+1),s.splice(o,0,v.toJSON(t)),this.setVertices(s,n)}appendVertex(t,e={}){return this.insertVertex(t,-1,e)}getVertexAt(t){return t!=null&&Number.isFinite(t)?this.getVertices()[t]:null}setVertexAt(t,e,n={}){if(t!=null&&Number.isFinite(t)){const s=this.getVertices();s[t]=e,this.setVertices(s,n)}return this}removeVertexAt(t,e={}){const n=this.getVertices(),s=t!=null&&Number.isFinite(t)?t:-1;return n.splice(s,1),this.setVertices(n,e)}onVertexsChanged({previous:t,current:e}){const n=t&&e?e.filter(r=>t.find(o=>v.equals(r,o))?null:r):e?[...e]:[],s=t&&e?t.filter(r=>e.find(o=>v.equals(r,o))?null:r):t?[...t]:[];n.length>0&&this.notify("vertexs:added",{added:n,cell:this,edge:this}),s.length>0&&this.notify("vertexs:removed",{removed:s,cell:this,edge:this})}getDefaultMarkup(){return this.store.get("defaultMarkup")||X.getEdgeMarkup()}getMarkup(){return super.getMarkup()||this.getDefaultMarkup()}translate(t,e,n={}){return n.translateBy=n.translateBy||this.id,n.tx=t,n.ty=e,this.applyToPoints(s=>({x:(s.x||0)+t,y:(s.y||0)+e}),n)}scale(t,e,n,s={}){return this.applyToPoints(r=>v.create(r).scale(t,e,n).toJSON(),s)}applyToPoints(t,e={}){const n={},s=this.getSource(),r=this.getTarget();v.isPointLike(s)&&(n.source=t(s)),v.isPointLike(r)&&(n.target=t(r));const o=this.getVertices();return o.length>0&&(n.vertices=o.map(t)),this.store.set(n,e),this}getBBox(){return this.getPolyline().bbox()}getConnectionPoint(){return this.getPolyline().pointAt(.5)}getPolyline(){const t=[this.getSourcePoint(),...this.getVertices().map(e=>v.create(e)),this.getTargetPoint()];return new nt(t)}updateParent(t){let e=null;const n=this.getSourceCell(),s=this.getTargetCell(),r=this.getParent();return n&&s&&(n===s||n.isDescendantOf(s)?e=s:s.isDescendantOf(n)?e=n:e=z.getCommonAncestor(n,s)),r&&(!e||e.id!==r.id)&&r.unembed(this,t),e&&e.embed(this,t),e}hasLoop(t={}){const e=this.getSource(),n=this.getTarget(),s=e.cell,r=n.cell;if(!s||!r)return!1;let o=s===r;if(!o&&t.deep&&this._model){const a=this.getSourceCell(),l=this.getTargetCell();a&&l&&(o=a.isAncestorOf(l,t)||l.isAncestorOf(a,t))}return o}getFragmentAncestor(){const t=[this,this.getSourceNode(),this.getTargetNode()].filter(e=>e!=null);return this.getCommonAncestor(...t)}isFragmentDescendantOf(t){const e=this.getFragmentAncestor();return!!e&&(e.id===t.id||e.isDescendantOf(t))}}K.defaults={},function(i){function t(e,n){const s=e,r=n;return s.cell===r.cell?s.port===r.port||s.port==null&&r.port==null:!1}i.equalTerminals=t}(K||(K={})),function(i){i.defaultLabel={markup:[{tagName:"rect",selector:"body"},{tagName:"text",selector:"label"}],attrs:{text:{fill:"#000",fontSize:14,textAnchor:"middle",textVerticalAnchor:"middle",pointerEvents:"none"},rect:{ref:"label",fill:"#fff",rx:3,ry:3,refWidth:1,refHeight:1,refX:0,refY:0}},position:{distance:.5}};function t(e){return{attrs:{label:{text:e}}}}i.parseStringLabel=t}(K||(K={})),function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNode=="function"&&typeof s.isEdge=="function"&&typeof s.prop=="function"&&typeof s.attr=="function"&&typeof s.disconnect=="function"&&typeof s.getSource=="function"&&typeof s.getTarget=="function"}i.isEdge=t}(K||(K={})),function(i){i.registry=st.create({type:"edge",process(t,e){if(an.exist(t,!1))throw new Error(`Edge with name '${t}' was registered by anthor Node`);if(typeof e=="function")return e.config({shape:t}),e;let n=i;const{inherit:s="edge"}=e,r=ks(e,["inherit"]);if(typeof s=="string"){const a=this.get(s||"edge");a==null&&s?this.onNotFound(s,"inherited"):n=a}else n=s;r.constructorName==null&&(r.constructorName=t);const o=n.define.call(n,r);return o.config({shape:t}),o}}),an.setEdgeRegistry(i.registry)}(K||(K={})),function(i){let t=0;function e(r){return r?pi(r):(t+=1,`CustomEdge${t}`)}function n(r){const{constructorName:o,overwrite:a}=r,l=ks(r,["constructorName","overwrite"]),c=di(e(o||l.shape),this);return c.config(l),l.shape&&i.registry.register(l.shape,c,a),c}i.define=n;function s(r){const o=r.shape||"edge",a=i.registry.get(o);return a?new a(r):i.registry.onNotFound(o)}i.create=s}(K||(K={})),function(i){const t="basic.edge";i.config({shape:t,propHooks(e){const{label:n,vertices:s}=e,r=ks(e,["label","vertices"]);if(n){r.labels==null&&(r.labels=[]);const o=typeof n=="string"?i.parseStringLabel(n):n;r.labels.push(o)}return s&&Array.isArray(s)&&(r.vertices=s.map(o=>v.create(o).toJSON())),r}}),i.registry.register(t,i)}(K||(K={}));class Ix extends Pt{constructor(t,e={}){super();this.length=0,this.comparator=e.comparator||"zIndex",this.clean(),t&&this.reset(t,{silent:!0})}toJSON(){return this.cells.map(t=>t.toJSON())}add(t,e,n){let s,r;typeof e=="number"?(s=e,r=Object.assign({merge:!1},n)):(s=this.length,r=Object.assign({merge:!1},e)),s>this.length&&(s=this.length),s<0&&(s+=this.length+1);const o=Array.isArray(t)?t:[t],a=this.comparator&&typeof e!="number"&&r.sort!==!1,l=this.comparator||null;let c=!1;const h=[],u=[];return o.forEach(f=>{const d=this.get(f);d?r.merge&&!f.isSameStore(d)&&(d.setProp(f.getProp(),n),u.push(d),a&&!c&&(l==null||typeof l=="function"?c=d.hasChanged():typeof l=="string"?c=d.hasChanged(l):c=l.some(g=>d.hasChanged(g)))):(h.push(f),this.reference(f))}),h.length&&(a&&(c=!0),this.cells.splice(s,0,...h),this.length=this.cells.length),c&&this.sort({silent:!0}),r.silent||(h.forEach((f,d)=>{const g={cell:f,index:s+d,options:r};this.trigger("added",g),r.dryrun||f.notify("added",Object.assign({},g))}),c&&this.trigger("sorted"),(h.length||u.length)&&this.trigger("updated",{added:h,merged:u,removed:[],options:r})),this}remove(t,e={}){const n=Array.isArray(t)?t:[t],s=this.removeCells(n,e);return!e.silent&&s.length>0&&this.trigger("updated",{options:e,removed:s,added:[],merged:[]}),Array.isArray(t)?s:s[0]}removeCells(t,e){const n=[];for(let s=0;sthis.unreference(s)),this.clean(),this.add(t,Object.assign({silent:!0},e)),!e.silent){const s=this.cells.slice();this.trigger("reseted",{options:e,previous:n,current:s});const r=[],o=[];s.forEach(a=>{n.some(c=>c.id===a.id)||r.push(a)}),n.forEach(a=>{s.some(c=>c.id===a.id)||o.push(a)}),this.trigger("updated",{options:e,added:r,removed:o,merged:[]})}return this}push(t,e){return this.add(t,this.length,e)}pop(t){const e=this.at(this.length-1);return this.remove(e,t)}unshift(t,e){return this.add(t,0,e)}shift(t){const e=this.at(0);return this.remove(e,t)}get(t){if(t==null)return null;const e=typeof t=="string"||typeof t=="number"?t:t.id;return this.map[e]||null}has(t){return this.get(t)!=null}at(t){return t<0&&(t+=this.length),this.cells[t]||null}first(){return this.at(0)}last(){return this.at(-1)}indexOf(t){return this.cells.indexOf(t)}toArray(){return this.cells.slice()}sort(t={}){return this.comparator!=null&&(this.cells=_o(this.cells,this.comparator),t.silent||this.trigger("sorted")),this}clone(){const t=this.constructor;return new t(this.cells.slice(),{comparator:this.comparator})}reference(t){this.map[t.id]=t,t.on("*",this.notifyCellEvent,this)}unreference(t){t.off("*",this.notifyCellEvent,this),delete this.map[t.id]}notifyCellEvent(t,e){const n=e.cell;this.trigger(`cell:${t}`,e),n&&(n.isNode()?this.trigger(`node:${t}`,Object.assign(Object.assign({},e),{node:n})):n.isEdge()&&this.trigger(`edge:${t}`,Object.assign(Object.assign({},e),{edge:n})))}clean(){this.length=0,this.cells=[],this.map={}}}class zt extends Pt{constructor(t=[]){super();this.batches={},this.addings=new WeakMap,this.nodes={},this.edges={},this.outgoings={},this.incomings={},this.collection=new Ix(t),this.setup()}get[Symbol.toStringTag](){return zt.toStringTag}notify(t,e){this.trigger(t,e);const n=this.graph;return n&&(t==="sorted"||t==="reseted"||t==="updated"?n.trigger(`model:${t}`,e):n.trigger(t,e)),this}setup(){const t=this.collection;t.on("sorted",()=>this.notify("sorted",null)),t.on("updated",e=>this.notify("updated",e)),t.on("cell:change:zIndex",()=>this.sortOnChangeZ()),t.on("added",({cell:e})=>{this.onCellAdded(e)}),t.on("removed",e=>{const n=e.cell;this.onCellRemoved(n,e.options),this.notify("cell:removed",e),n.isNode()?this.notify("node:removed",Object.assign(Object.assign({},e),{node:n})):n.isEdge()&&this.notify("edge:removed",Object.assign(Object.assign({},e),{edge:n}))}),t.on("reseted",e=>{this.onReset(e.current),this.notify("reseted",e)}),t.on("edge:change:source",({edge:e})=>this.onEdgeTerminalChanged(e,"source")),t.on("edge:change:target",({edge:e})=>{this.onEdgeTerminalChanged(e,"target")})}sortOnChangeZ(){this.collection.sort()}onCellAdded(t){const e=t.id;t.isEdge()?(t.updateParent(),this.edges[e]=!0,this.onEdgeTerminalChanged(t,"source"),this.onEdgeTerminalChanged(t,"target")):this.nodes[e]=!0}onCellRemoved(t,e){const n=t.id;if(t.isEdge()){delete this.edges[n];const s=t.getSource(),r=t.getTarget();if(s&&s.cell){const o=this.outgoings[s.cell],a=o?o.indexOf(n):-1;a>=0&&(o.splice(a,1),o.length===0&&delete this.outgoings[s.cell])}if(r&&r.cell){const o=this.incomings[r.cell],a=o?o.indexOf(n):-1;a>=0&&(o.splice(a,1),o.length===0&&delete this.incomings[r.cell])}}else delete this.nodes[n];e.clear||(e.disconnectEdges?this.disconnectConnectedEdges(t,e):this.removeConnectedEdges(t,e)),t.model===this&&(t.model=null)}onReset(t){this.nodes={},this.edges={},this.outgoings={},this.incomings={},t.forEach(e=>this.onCellAdded(e))}onEdgeTerminalChanged(t,e){const n=e==="source"?this.outgoings:this.incomings,s=t.previous(e);if(s&&s.cell){const o=z.isCell(s.cell)?s.cell.id:s.cell,a=n[o],l=a?a.indexOf(t.id):-1;l>=0&&(a.splice(l,1),a.length===0&&delete n[o])}const r=t.getTerminal(e);if(r&&r.cell){const o=z.isCell(r.cell)?r.cell.id:r.cell,a=n[o]||[];a.indexOf(t.id)===-1&&a.push(t.id),n[o]=a}}prepareCell(t,e){return!t.model&&(!e||!e.dryrun)&&(t.model=this),t.zIndex==null&&t.setZIndex(this.getMaxZIndex()+1,{silent:!0}),t}resetCells(t,e={}){return t.map(n=>this.prepareCell(n,Object.assign(Object.assign({},e),{dryrun:!0}))),this.collection.reset(t,e),t.map(n=>this.prepareCell(n,{options:e})),this}clear(t={}){const e=this.getCells();if(e.length===0)return this;const n=Object.assign(Object.assign({},t),{clear:!0});return this.batchUpdate("clear",()=>{const s=e.sort((r,o)=>{const a=r.isEdge()?1:2,l=o.isEdge()?1:2;return a-l});for(;s.length>0;){const r=s.shift();r&&r.remove(n)}},n),this}addNode(t,e={}){const n=it.isNode(t)?t:this.createNode(t);return this.addCell(n,e),n}createNode(t){return it.create(t)}addEdge(t,e={}){const n=K.isEdge(t)?t:this.createEdge(t);return this.addCell(n,e),n}createEdge(t){return K.create(t)}addCell(t,e={}){return Array.isArray(t)?this.addCells(t,e):(!this.collection.has(t)&&!this.addings.has(t)&&(this.addings.set(t,!0),this.collection.add(this.prepareCell(t,e),e),t.eachChild(n=>this.addCell(n,e)),this.addings.delete(t)),this)}addCells(t,e={}){const n=t.length;if(n===0)return this;const s=Object.assign(Object.assign({},e),{position:n-1,maxPosition:n-1});return this.startBatch("add",Object.assign(Object.assign({},s),{cells:t})),t.forEach(r=>{this.addCell(r,s),s.position-=1}),this.stopBatch("add",Object.assign(Object.assign({},s),{cells:t})),this}removeCell(t,e={}){const n=typeof t=="string"?this.getCell(t):t;return n&&this.has(n)?this.collection.remove(n,e):null}updateCellId(t,e){this.startBatch("update",{id:e}),t.prop("id",e);const n=t.clone({keepId:!0});return this.addCell(n),this.getConnectedEdges(t).forEach(r=>{const o=r.getSourceCell(),a=r.getTargetCell();o===t&&r.setSource(Object.assign(Object.assign({},r.getSource()),{cell:e})),a===t&&r.setTarget(Object.assign(Object.assign({},r.getTarget()),{cell:e}))}),this.removeCell(t),this.stopBatch("update",{id:e}),n}removeCells(t,e={}){return t.length?this.batchUpdate("remove",()=>t.map(n=>this.removeCell(n,e))):[]}removeConnectedEdges(t,e={}){const n=this.getConnectedEdges(t);return n.forEach(s=>{s.remove(e)}),n}disconnectConnectedEdges(t,e={}){const n=typeof t=="string"?t:t.id;this.getConnectedEdges(t).forEach(s=>{const r=s.getSourceCell(),o=s.getTargetCell();r&&r.id===n&&s.setSource({x:0,y:0},e),o&&o.id===n&&s.setTarget({x:0,y:0},e)})}has(t){return this.collection.has(t)}total(){return this.collection.length}indexOf(t){return this.collection.indexOf(t)}getCell(t){return this.collection.get(t)}getCells(){return this.collection.toArray()}getFirstCell(){return this.collection.first()}getLastCell(){return this.collection.last()}getMinZIndex(){const t=this.collection.first();return t&&t.getZIndex()||0}getMaxZIndex(){const t=this.collection.last();return t&&t.getZIndex()||0}getCellsFromCache(t){return t?Object.keys(t).map(e=>this.getCell(e)).filter(e=>e!=null):[]}getNodes(){return this.getCellsFromCache(this.nodes)}getEdges(){return this.getCellsFromCache(this.edges)}getOutgoingEdges(t){const e=typeof t=="string"?t:t.id,n=this.outgoings[e];return n?n.map(s=>this.getCell(s)).filter(s=>s&&s.isEdge()):null}getIncomingEdges(t){const e=typeof t=="string"?t:t.id,n=this.incomings[e];return n?n.map(s=>this.getCell(s)).filter(s=>s&&s.isEdge()):null}getConnectedEdges(t,e={}){const n=[],s=typeof t=="string"?this.getCell(t):t;if(s==null)return n;const r={},o=e.indirect;let a=e.incoming,l=e.outgoing;a==null&&l==null&&(a=l=!0);const c=(h,u)=>{const f=u?this.getOutgoingEdges(h):this.getIncomingEdges(h);if(f!=null&&f.forEach(d=>{r[d.id]||(n.push(d),r[d.id]=!0,o&&(a&&c(d,!1),l&&c(d,!0)))}),o&&h.isEdge()){const d=u?h.getTargetCell():h.getSourceCell();d&&d.isEdge()&&(r[d.id]||(n.push(d),c(d,u)))}};if(l&&c(s,!0),a&&c(s,!1),e.deep){const h=s.getDescendants({deep:!0}),u={};h.forEach(d=>{d.isNode()&&(u[d.id]=!0)});const f=(d,g)=>{const p=g?this.getOutgoingEdges(d.id):this.getIncomingEdges(d.id);p!=null&&p.forEach(m=>{if(!r[m.id]){const y=m.getSourceCell(),x=m.getTargetCell();if(!e.enclosed&&y&&u[y.id]&&x&&u[x.id])return;n.push(m),r[m.id]=!0}})};h.forEach(d=>{d.isEdge()||(l&&f(d,!0),a&&f(d,!1))})}return n}isBoundary(t,e){const n=typeof t=="string"?this.getCell(t):t,s=e?this.getIncomingEdges(n):this.getOutgoingEdges(n);return s==null||s.length===0}getBoundaryNodes(t){const e=[];return Object.keys(this.nodes).forEach(n=>{if(this.isBoundary(n,t)){const s=this.getCell(n);s&&e.push(s)}}),e}getRoots(){return this.getBoundaryNodes(!0)}getLeafs(){return this.getBoundaryNodes(!1)}isRoot(t){return this.isBoundary(t,!0)}isLeaf(t){return this.isBoundary(t,!1)}getNeighbors(t,e={}){let n=e.incoming,s=e.outgoing;n==null&&s==null&&(n=s=!0);const o=this.getConnectedEdges(t,e).reduce((a,l)=>{const c=l.hasLoop(e),h=l.getSourceCell(),u=l.getTargetCell();return n&&h&&h.isNode()&&!a[h.id]&&(c||h!==t&&(!e.deep||!h.isDescendantOf(t)))&&(a[h.id]=h),s&&u&&u.isNode()&&!a[u.id]&&(c||u!==t&&(!e.deep||!u.isDescendantOf(t)))&&(a[u.id]=u),a},{});if(t.isEdge()){if(n){const a=t.getSourceCell();a&&a.isNode()&&!o[a.id]&&(o[a.id]=a)}if(s){const a=t.getTargetCell();a&&a.isNode()&&!o[a.id]&&(o[a.id]=a)}}return Object.keys(o).map(a=>o[a])}isNeighbor(t,e,n={}){let s=n.incoming,r=n.outgoing;return s==null&&r==null&&(s=r=!0),this.getConnectedEdges(t,n).some(o=>{const a=o.getSourceCell(),l=o.getTargetCell();return!!(s&&a&&a.id===e.id||r&&l&&l.id===e.id)})}getSuccessors(t,e={}){const n=[];return this.search(t,(s,r)=>{s!==t&&this.matchDistance(r,e.distance)&&n.push(s)},Object.assign(Object.assign({},e),{outgoing:!0})),n}isSuccessor(t,e,n={}){let s=!1;return this.search(t,(r,o)=>{if(r===e&&r!==t&&this.matchDistance(o,n.distance))return s=!0,!1},Object.assign(Object.assign({},n),{outgoing:!0})),s}getPredecessors(t,e={}){const n=[];return this.search(t,(s,r)=>{s!==t&&this.matchDistance(r,e.distance)&&n.push(s)},Object.assign(Object.assign({},e),{incoming:!0})),n}isPredecessor(t,e,n={}){let s=!1;return this.search(t,(r,o)=>{if(r===e&&r!==t&&this.matchDistance(o,n.distance))return s=!0,!1},Object.assign(Object.assign({},n),{incoming:!0})),s}matchDistance(t,e){return e==null?!0:typeof e=="function"?e(t):Array.isArray(e)&&e.includes(t)?!0:t===e}getCommonAncestor(...t){const e=[];return t.forEach(n=>{n&&(Array.isArray(n)?e.push(...n):e.push(n))}),z.getCommonAncestor(...e)}getSubGraph(t,e={}){const n=[],s={},r=[],o=[],a=l=>{s[l.id]||(n.push(l),s[l.id]=l,l.isEdge()&&o.push(l),l.isNode()&&r.push(l))};return t.forEach(l=>{a(l),e.deep&&l.getDescendants({deep:!0}).forEach(h=>a(h))}),o.forEach(l=>{const c=l.getSourceCell(),h=l.getTargetCell();c&&!s[c.id]&&(n.push(c),s[c.id]=c,c.isNode()&&r.push(c)),h&&!s[h.id]&&(n.push(h),s[h.id]=h,h.isNode()&&r.push(h))}),r.forEach(l=>{this.getConnectedEdges(l,e).forEach(h=>{const u=h.getSourceCell(),f=h.getTargetCell();!s[h.id]&&u&&s[u.id]&&f&&s[f.id]&&(n.push(h),s[h.id]=h)})}),n}cloneSubGraph(t,e={}){const n=this.getSubGraph(t,e);return this.cloneCells(n)}cloneCells(t){return z.cloneCells(t)}getNodesFromPoint(t,e){const n=typeof t=="number"?{x:t,y:e||0}:t;return this.getNodes().filter(s=>s.getBBox().containsPoint(n))}getNodesInArea(t,e,n,s,r){const o=typeof t=="number"?new M(t,e,n,s):M.create(t),a=typeof t=="number"?r:e,l=a&&a.strict;return this.getNodes().filter(c=>{const h=c.getBBox();return l?o.containsRect(h):o.isIntersectWithRect(h)})}getEdgesInArea(t,e,n,s,r){const o=typeof t=="number"?new M(t,e,n,s):M.create(t),a=typeof t=="number"?r:e,l=a&&a.strict;return this.getEdges().filter(c=>{const h=c.getBBox();return h.width===0?h.inflate(1,0):h.height===0&&h.inflate(0,1),l?o.containsRect(h):o.isIntersectWithRect(h)})}getNodesUnderNode(t,e={}){const n=t.getBBox();return(e.by==null||e.by==="bbox"?this.getNodesInArea(n):this.getNodesFromPoint(n[e.by])).filter(r=>t.id!==r.id&&!r.isDescendantOf(t))}getAllCellsBBox(){return this.getCellsBBox(this.getCells())}getCellsBBox(t,e={}){return z.getCellsBBox(t,e)}search(t,e,n={}){n.breadthFirst?this.breadthFirstSearch(t,e,n):this.depthFirstSearch(t,e,n)}breadthFirstSearch(t,e,n={}){const s=[],r={},o={};for(s.push(t),o[t.id]=0;s.length>0;){const a=s.shift();if(a==null||r[a.id]||(r[a.id]=!0,R(e,this,a,o[a.id])===!1))continue;this.getNeighbors(a,n).forEach(c=>{o[c.id]=o[a.id]+1,s.push(c)})}}depthFirstSearch(t,e,n={}){const s=[],r={},o={};for(s.push(t),o[t.id]=0;s.length>0;){const a=s.pop();if(a==null||r[a.id]||(r[a.id]=!0,R(e,this,a,o[a.id])===!1))continue;const l=this.getNeighbors(a,n),c=s.length;l.forEach(h=>{o[h.id]=o[a.id]+1,s.splice(c,0,h)})}}getShortestPath(t,e,n={}){const s={};this.getEdges().forEach(c=>{const h=c.getSourceCellId(),u=c.getTargetCellId();h&&u&&(s[h]||(s[h]=[]),s[u]||(s[u]=[]),s[h].push(u),n.directed||s[u].push(h))});const r=typeof t=="string"?t:t.id,o=Di.run(s,r,n.weight),a=[];let l=typeof e=="string"?e:e.id;for(o[l]&&a.push(l);l=o[l];)a.unshift(l);return a}translate(t,e,n){return this.getCells().filter(s=>!s.hasParent()).forEach(s=>s.translate(t,e,n)),this}resize(t,e,n){return this.resizeCells(t,e,this.getCells(),n)}resizeCells(t,e,n,s={}){const r=this.getCellsBBox(n);if(r){const o=Math.max(t/r.width,0),a=Math.max(e/r.height,0),l=r.getOrigin();n.forEach(c=>c.scale(o,a,l,s))}return this}toJSON(t={}){return zt.toJSON(this.getCells(),t)}parseJSON(t){return zt.fromJSON(t)}fromJSON(t,e={}){const n=this.parseJSON(t);return this.resetCells(n,e),this}startBatch(t,e={}){return this.batches[t]=(this.batches[t]||0)+1,this.notify("batch:start",{name:t,data:e}),this}stopBatch(t,e={}){return this.batches[t]=(this.batches[t]||0)-1,this.notify("batch:stop",{name:t,data:e}),this}batchUpdate(t,e,n={}){this.startBatch(t,n);const s=e();return this.stopBatch(t,n),s}hasActiveBatch(t=Object.keys(this.batches)){return(Array.isArray(t)?t:[t]).some(n=>this.batches[n]>0)}}(function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.addNode=="function"&&typeof s.addEdge=="function"&&s.collection!=null}i.isModel=t})(zt||(zt={})),function(i){function t(n,s={}){return{cells:n.map(r=>r.toJSON(s))}}i.toJSON=t;function e(n){const s=[];return Array.isArray(n)?s.push(...n):(n.cells&&s.push(...n.cells),n.nodes&&n.nodes.forEach(r=>{r.shape==null&&(r.shape="rect"),s.push(r)}),n.edges&&n.edges.forEach(r=>{r.shape==null&&(r.shape="edge"),s.push(r)})),s.map(r=>{const o=r.shape;if(o){if(it.registry.exist(o))return it.create(r);if(K.registry.exist(o))return K.create(r)}throw new Error("The `shape` should be specified when creating a node/edge instance")})}i.fromJSON=e}(zt||(zt={}));var jx=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const{imageUrl:n,imageWidth:s,imageHeight:r}=e,o=Dx(e,["imageUrl","imageWidth","imageHeight"]);if(n!=null||s!=null||r!=null){const a=()=>{if(o.attrs){const l=o.attrs.image;n!=null&&(l[i]=n),s!=null&&(l.width=s),r!=null&&(l.height=r),o.attrs.image=l}};o.attrs?(o.attrs.image==null&&(o.attrs.image={}),a()):(o.attrs={image:{}},a())}return o}}function ln(i,t,e={}){const n={constructorName:i,markup:$x(i,e.selector),attrs:{[i]:Object.assign({},ge.bodyAttr)}};return(e.parent||ge).define(ot(n,t,{shape:i}))}const kx=ln("rect",{attrs:{body:{refWidth:"100%",refHeight:"100%"}}}),Xl=K.define({shape:"edge",markup:[{tagName:"path",selector:"wrap",groupSelector:"lines",attrs:{fill:"none",cursor:"pointer",stroke:"transparent",strokeLinecap:"round"}},{tagName:"path",selector:"line",groupSelector:"lines",attrs:{fill:"none",pointerEvents:"none"}}],attrs:{lines:{connection:!0,strokeLinejoin:"round"},wrap:{strokeWidth:10},line:{stroke:"#333",strokeWidth:2,targetMarker:"classic"}}}),Bx=ln("ellipse",{attrs:{body:{refCx:"50%",refCy:"50%",refRx:"50%",refRy:"50%"}}});var zx=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);sArray.isArray(n)?n.join(","):v.isPointLike(n)?`${n.x}, ${n.y}`:"").join(" ")}i.pointsToString=t,i.config({propHooks(e){const{points:n}=e,s=zx(e,["points"]);if(n){const r=t(n);r&&Cn(s,"attrs/body/refPoints",r)}return s}})})(cn||(cn={}));const Vx=ln("polygon",{},{parent:cn}),Fx=ln("polyline",{},{parent:cn});var _x=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);sthis.resize(),"update"),e=this.handleAction(e,"update",()=>this.update(),gt.useCSSSelector?"ports":null),e=this.handleAction(e,"translate",()=>this.translate()),e=this.handleAction(e,"rotate",()=>this.rotate()),e=this.handleAction(e,"ports",()=>this.renderPorts()),e=this.handleAction(e,"tools",()=>this.renderTools())),e}update(t){this.cleanCache(),gt.useCSSSelector&&this.removePorts();const e=this.cell,n=e.getSize(),s=e.getAttrs();this.updateAttrs(this.container,s,{attrs:t===s?null:t,rootBBox:new M(0,0,n.width,n.height),selectors:this.selectors}),gt.useCSSSelector&&this.renderPorts()}renderMarkup(){const t=this.cell.markup;if(t){if(typeof t=="string")throw new TypeError("Not support string markup.");return this.renderJSONMarkup(t)}throw new TypeError("Invalid node markup.")}renderJSONMarkup(t){const e=this.parseJSONMarkup(t,this.container);this.selectors=e.selectors,this.container.appendChild(e.fragment)}render(){return this.empty(),this.renderMarkup(),this.resize(),this.updateTransform(),gt.useCSSSelector||this.renderPorts(),this.renderTools(),this}resize(){this.cell.getAngle()&&this.rotate(),this.update()}translate(){this.updateTransform()}rotate(){this.updateTransform()}getTranslationString(){const t=this.cell.getPosition();return`translate(${t.x},${t.y})`}getRotationString(){const t=this.cell.getAngle();if(t){const e=this.cell.getSize();return`rotate(${t},${e.width/2},${e.height/2})`}}updateTransform(){let t=this.getTranslationString();const e=this.getRotationString();e&&(t+=` ${e}`),this.container.setAttribute("transform",t)}findPortElem(t,e){const n=t?this.portsCache[t]:null;if(!n)return null;const s=n.portContentElement,r=n.portContentSelectors||{};return this.findOne(e,s,r)}cleanPortsCache(){this.portsCache={}}removePorts(){Object.keys(this.portsCache).forEach(t=>{const e=this.portsCache[t];qe(e.portElement)})}renderPorts(){const t=this.container,e=[];t.childNodes.forEach(o=>{e.push(o)});const n=this.cell.getParsedPorts(),s=Vo(n,"zIndex"),r="auto";s[r]&&s[r].forEach(o=>{const a=this.getPortElement(o);t.append(a),e.push(a)}),Object.keys(s).forEach(o=>{if(o!==r){const a=parseInt(o,10);this.appendPorts(s[o],a,e)}}),this.updatePorts()}appendPorts(t,e,n){const s=t.map(r=>this.getPortElement(r));n[e]||e<0?Si(n[Math.max(e,0)],s):On(this.container,s)}getPortElement(t){const e=this.portsCache[t.id];return e?e.portElement:this.createPortElement(t)}createPortElement(t){let e=X.renderMarkup(this.cell.getPortContainerMarkup());const n=e.elem;if(n==null)throw new Error("Invalid port container markup.");e=X.renderMarkup(this.getPortMarkup(t));const s=e.elem,r=e.selectors;if(s==null)throw new Error("Invalid port markup.");this.setAttrs({port:t.id,"port-group":t.group},s);let o="x6-port";t.group&&(o+=` x6-port-${t.group}`),V(n,o),V(n,"x6-port"),V(s,"x6-port-body"),n.appendChild(s);let a=r,l,c;if(this.existPortLabel(t)){if(e=X.renderMarkup(this.getPortLabelMarkup(t.label)),l=e.elem,c=e.selectors,l==null)throw new Error("Invalid port label markup.");if(r&&c){for(const u in c)if(r[u]&&u!==this.rootSelector)throw new Error("Selectors within port must be unique.");a=Object.assign(Object.assign({},r),c)}V(l,"x6-port-label"),n.appendChild(l)}return this.portsCache[t.id]={portElement:n,portSelectors:a,portLabelElement:l,portLabelSelectors:c,portContentElement:s,portContentSelectors:r},this.graph.options.onPortRendered&&this.graph.options.onPortRendered({port:t,node:this.cell,container:n,selectors:a,labelContainer:l,labelSelectors:c,contentContainer:s,contentSelectors:r}),n}updatePorts(){const t=this.cell.getParsedGroups();Object.keys(t).forEach(e=>this.updatePortGroup(e))}updatePortGroup(t){const e=M.fromSize(this.cell.getSize()),n=this.cell.getPortsLayoutByGroup(t,e);for(let s=0,r=n.length;sr.options.clickThreshold||this.notify("node:magnet:click",Object.assign({magnet:e},this.getEventArgs(t,n,s)))}onMagnetDblClick(t,e,n,s){this.notify("node:magnet:dblclick",Object.assign({magnet:e},this.getEventArgs(t,n,s)))}onMagnetContextMenu(t,e,n,s){this.notify("node:magnet:contextmenu",Object.assign({magnet:e},this.getEventArgs(t,n,s)))}onMagnetMouseDown(t,e,n,s){this.startMagnetDragging(t,n,s)}onCustomEvent(t,e,n,s){this.notify("node:customevent",Object.assign({name:e},this.getEventArgs(t,n,s))),super.onCustomEvent(t,e,n,s)}prepareEmbedding(t){const e=this.graph,s=this.getEventData(t).cell||this.cell,r=e.findViewByCell(s),o=e.snapToGrid(t.clientX,t.clientY);this.notify("node:embed",{e:t,node:s,view:r,cell:s,x:o.x,y:o.y,currentParent:s.getParent()})}processEmbedding(t,e){const n=e.cell||this.cell,s=e.graph||this.graph,r=s.options.embedding,o=r.findParent;let a=typeof o=="function"?R(o,s,{view:this,node:this.cell}).filter(f=>z.isCell(f)&&this.cell.id!==f.id&&!f.isDescendantOf(this.cell)):s.model.getNodesUnderNode(n,{by:o});if(r.frontOnly&&a.length>0){const f=Vo(a,"zIndex"),d=Vp(Object.keys(f));d&&(a=f[d])}a=a.filter(f=>f.visible);let l=null;const c=e.candidateEmbedView,h=r.validate;for(let f=a.length-1;f>=0;f-=1){const d=a[f];if(c&&c.cell.id===d.id){l=c;break}else{const g=d.findView(s);if(R(h,s,{child:this.cell,parent:g.cell,childView:this,parentView:g})){l=g;break}}}this.clearEmbedding(e),l&&l.highlight(null,{type:"embedding"}),e.candidateEmbedView=l;const u=s.snapToGrid(t.clientX,t.clientY);this.notify("node:embedding",{e:t,cell:n,node:n,view:s.findViewByCell(n),x:u.x,y:u.y,currentParent:n.getParent(),candidateParent:l?l.cell:null})}clearEmbedding(t){const e=t.candidateEmbedView;e&&(e.unhighlight(null,{type:"embedding"}),t.candidateEmbedView=null)}finalizeEmbedding(t,e){this.graph.startBatch("embedding");const n=e.cell||this.cell,s=e.graph||this.graph,r=s.findViewByCell(n),o=n.getParent(),a=e.candidateEmbedView;if(a?(a.unhighlight(null,{type:"embedding"}),e.candidateEmbedView=null,(o==null||o.id!==a.cell.id)&&a.cell.insertChild(n,void 0,{ui:!0})):o&&o.unembed(n,{ui:!0}),s.model.getConnectedEdges(n,{deep:!0}).forEach(l=>{l.updateParent({ui:!0})}),r&&a){const l=s.snapToGrid(t.clientX,t.clientY);r.notify("node:embedded",{e:t,cell:n,x:l.x,y:l.y,node:n,view:s.findViewByCell(n),previousParent:o,currentParent:n.getParent()})}this.graph.stopBatch("embedding")}getDelegatedView(){let t=this.cell,e=this;for(;e&&!t.isEdge();){if(!t.hasParent()||e.can("stopDelegateOnDragging"))return e;t=t.getParent(),e=this.graph.findViewByCell(t)}return null}validateMagnet(t,e,n){if(e.getAttribute("magnet")!=="passive"){const s=this.graph.options.connecting.validateMagnet;return s?R(s,this.graph,{e:n,magnet:e,view:t,cell:t.cell}):!0}return!1}startMagnetDragging(t,e,n){if(!this.can("magnetConnectable"))return;t.stopPropagation();const s=t.currentTarget,r=this.graph;this.setEventData(t,{targetMagnet:s}),this.validateMagnet(this,s,t)?(r.options.magnetThreshold<=0&&this.startConnectting(t,s,e,n),this.setEventData(t,{action:"magnet"}),this.stopPropagation(t)):((He(s,"x6-port-body")||!!s.closest(".x6-port-body"))&&this.stopPropagation(t),this.onMouseDown(t,e,n)),r.view.delegateDragEvents(t,this)}startConnectting(t,e,n,s){this.graph.model.startBatch("add-edge");const r=this.createEdgeFromMagnet(e,n,s);r.notifyMouseDown(t,n,s),r.setEventData(t,r.prepareArrowheadDragging("target",{x:n,y:s,isNewEdge:!0,fallbackAction:"remove"})),this.setEventData(t,{edgeView:r})}getDefaultEdge(t,e){let n;const s=this.graph.options.connecting.createEdge;return s&&(n=R(s,this.graph,{sourceMagnet:e,sourceView:t,sourceCell:t.cell})),n}createEdgeFromMagnet(t,e,n){const s=this.graph,r=s.model,o=this.getDefaultEdge(this,t);return o.setSource(Object.assign(Object.assign({},o.getSource()),this.getEdgeTerminal(t,e,n,o,"source"))),o.setTarget(Object.assign(Object.assign({},o.getTarget()),{x:e,y:n})),o.addTo(r,{async:!1,ui:!0}),o.findView(s)}dragMagnet(t,e,n){const s=this.getEventData(t),r=s.edgeView;if(r)r.onMouseMove(t,e,n),this.autoScrollGraph(t.clientX,t.clientY);else{const o=this.graph,a=o.options.magnetThreshold,l=this.getEventTarget(t),c=s.targetMagnet;if(a==="onleave"){if(c===l||c.contains(l))return}else if(o.view.getMouseMovedCount(t)<=a)return;this.startConnectting(t,c,e,n)}}stopMagnetDragging(t,e,n){const r=this.eventData(t).edgeView;r&&(r.onMouseUp(t,e,n),this.graph.model.stopBatch("add-edge"))}notifyUnhandledMouseDown(t,e,n){this.notify("node:unhandled:mousedown",{e:t,x:e,y:n,view:this,cell:this.cell,node:this.cell})}notifyNodeMove(t,e,n,s,r){let o=[r];const a=this.graph.getPlugin("selection");if(a&&a.isSelectionMovable()){const l=a.getSelectedCells();l.includes(r)&&(o=l.filter(c=>c.isNode()))}o.forEach(l=>{this.notify(t,{e,x:n,y:s,cell:l,node:l,view:l.findView(this.graph)})})}getRestrictArea(t){const e=this.graph.options.translating.restrict,n=typeof e=="function"?R(e,this.graph,t):e;return typeof n=="number"?this.graph.transform.getGraphArea().inflate(n):n===!0?this.graph.transform.getGraphArea():n||null}startNodeDragging(t,e,n){const s=this.getDelegatedView();if(s==null||!s.can("nodeMovable"))return this.notifyUnhandledMouseDown(t,e,n);this.setEventData(t,{targetView:s,action:"move"});const r=v.create(s.cell.getPosition());s.setEventData(t,{moving:!1,offset:r.diff(e,n),restrict:this.getRestrictArea(s)})}dragNode(t,e,n){const s=this.cell,r=this.graph,o=r.getGridSize(),a=this.getEventData(t),l=a.offset,c=a.restrict;a.moving||(a.moving=!0,this.addClass("node-moving"),this.notifyNodeMove("node:move",t,e,n,this.cell)),this.autoScrollGraph(t.clientX,t.clientY);const h=G.snapToGrid(e+l.x,o),u=G.snapToGrid(n+l.y,o);s.setPosition(h,u,{restrict:c,deep:!0,ui:!0}),r.options.embedding.enabled&&(a.embedding||(this.prepareEmbedding(t),a.embedding=!0),this.processEmbedding(t,a))}stopNodeDragging(t,e,n){const s=this.getEventData(t);s.embedding&&this.finalizeEmbedding(t,s),s.moving&&(this.removeClass("node-moving"),this.notifyNodeMove("node:moved",t,e,n,this.cell)),s.moving=!1,s.embedding=!1}autoScrollGraph(t,e){const n=this.graph.getPlugin("scroller");n&&n.autoScroll(t,e)}}(function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNodeView=="function"&&typeof s.isEdgeView=="function"&&typeof s.confirmUpdate=="function"&&typeof s.update=="function"&&typeof s.findPortElem=="function"&&typeof s.resize=="function"&&typeof s.rotate=="function"&&typeof s.translate=="function"}i.isNodeView=t})(jt||(jt={})),jt.config({isSvgElement:!0,priority:0,bootstrap:["render"],actions:{view:["render"],markup:["render"],attrs:["update"],size:["resize","ports","tools"],angle:["rotate","tools"],position:["translate","tools"],ports:["ports"],tools:["tools"]}}),jt.registry.register("node",jt,!0);class Qt extends ht{constructor(){super(...arguments);this.POINT_ROUNDING=2}get[Symbol.toStringTag](){return Qt.toStringTag}getContainerClassName(){return[super.getContainerClassName(),this.prefixClassName("edge")].join(" ")}get sourceBBox(){const t=this.sourceView;if(!t){const n=this.cell.getSource();return new M(n.x,n.y)}const e=this.sourceMagnet;return t.isEdgeElement(e)?new M(this.sourceAnchor.x,this.sourceAnchor.y):t.getBBoxOfElement(e||t.container)}get targetBBox(){const t=this.targetView;if(!t){const n=this.cell.getTarget();return new M(n.x,n.y)}const e=this.targetMagnet;return t.isEdgeElement(e)?new M(this.targetAnchor.x,this.targetAnchor.y):t.getBBoxOfElement(e||t.container)}isEdgeView(){return!0}confirmUpdate(t,e={}){let n=t;if(this.hasAction(n,"source")){if(!this.updateTerminalProperties("source"))return n;n=this.removeAction(n,"source")}if(this.hasAction(n,"target")){if(!this.updateTerminalProperties("target"))return n;n=this.removeAction(n,"target")}const s=this.graph,r=this.sourceView,o=this.targetView;return s&&(r&&!s.renderer.isViewMounted(r)||o&&!s.renderer.isViewMounted(o))?n:this.hasAction(n,"render")?(this.render(),n=this.removeAction(n,["render","update","labels","tools"]),n):(n=this.handleAction(n,"update",()=>this.update(e)),n=this.handleAction(n,"labels",()=>this.onLabelsChange(e)),n=this.handleAction(n,"tools",()=>this.renderTools()),n)}render(){return this.empty(),this.renderMarkup(),this.labelContainer=null,this.renderLabels(),this.update(),this.renderTools(),this}renderMarkup(){const t=this.cell.markup;if(t){if(typeof t=="string")throw new TypeError("Not support string markup.");return this.renderJSONMarkup(t)}throw new TypeError("Invalid edge markup.")}renderJSONMarkup(t){const e=this.parseJSONMarkup(t,this.container);this.selectors=e.selectors,this.container.append(e.fragment)}customizeLabels(){if(this.labelContainer){const t=this.cell,e=t.labels;for(let n=0,s=e.length;n1){const r=n[1];if(e[r]){if(s===2)return typeof t.propertyValue=="object"&&us(t.propertyValue,"markup");if(n[2]!=="markup")return!1}}}return!0}parseLabelMarkup(t){return t?typeof t=="string"?this.parseLabelStringMarkup(t):this.parseJSONMarkup(t):null}parseLabelStringMarkup(t){const e=$.createVectors(t),n=document.createDocumentFragment();for(let s=0,r=e.length;s1||s[0].nodeName.toUpperCase()!=="G"?n=$.create("g").append(e):n=$.create(s[0]),n.addClass(this.prefixClassName("edge-label")),{node:n.node,selectors:t.selectors}}updateLabels(){if(this.labelContainer){const t=this.cell,e=t.labels,n=this.can("edgeLabelMovable"),s=t.getDefaultLabel();for(let r=0,o=e.length;rc.toJSON()),l=a.length;return r===l?0:(e.setVertices(a.slice(1,l-1),t),r-l)}getTerminalView(t){switch(t){case"source":return this.sourceView||null;case"target":return this.targetView||null;default:throw new Error(`Unknown terminal type '${t}'`)}}getTerminalAnchor(t){switch(t){case"source":return v.create(this.sourceAnchor);case"target":return v.create(this.targetAnchor);default:throw new Error(`Unknown terminal type '${t}'`)}}getTerminalConnectionPoint(t){switch(t){case"source":return v.create(this.sourcePoint);case"target":return v.create(this.targetPoint);default:throw new Error(`Unknown terminal type '${t}'`)}}getTerminalMagnet(t,e={}){switch(t){case"source":{if(e.raw)return this.sourceMagnet;const n=this.sourceView;return n?this.sourceMagnet||n.container:null}case"target":{if(e.raw)return this.targetMagnet;const n=this.targetView;return n?this.targetMagnet||n.container:null}default:throw new Error(`Unknown terminal type '${t}'`)}}updateConnection(t={}){const e=this.cell;if(t.translateBy&&e.isFragmentDescendantOf(t.translateBy)){const n=t.tx||0,s=t.ty||0;this.routePoints=new nt(this.routePoints).translate(n,s).points,this.translateConnectionPoints(n,s),this.path.translate(n,s)}else{const n=e.getVertices(),s=this.findAnchors(n);this.sourceAnchor=s.source,this.targetAnchor=s.target,this.routePoints=this.findRoutePoints(n);const r=this.findConnectionPoints(this.routePoints,this.sourceAnchor,this.targetAnchor);this.sourcePoint=r.source,this.targetPoint=r.target;const o=this.findMarkerPoints(this.routePoints,this.sourcePoint,this.targetPoint);this.path=this.findPath(this.routePoints,o.source||this.sourcePoint,o.target||this.targetPoint)}this.cleanCache()}findAnchors(t){const e=this.cell,n=e.source,s=e.target,r=t[0],o=t[t.length-1];return s.priority&&!n.priority?this.findAnchorsOrdered("target",o,"source",r):this.findAnchorsOrdered("source",r,"target",o)}findAnchorsOrdered(t,e,n,s){let r,o;const a=this.cell,l=a[t],c=a[n],h=this.getTerminalView(t),u=this.getTerminalView(n),f=this.getTerminalMagnet(t),d=this.getTerminalMagnet(n);if(h){let g;e?g=v.create(e):u?g=d:g=v.create(c),r=this.getAnchor(l.anchor,h,f,g,t)}else r=v.create(l);if(u){const g=v.create(s||r);o=this.getAnchor(c.anchor,u,d,g,n)}else o=v.isPointLike(c)?v.create(c):new v;return{[t]:r,[n]:o}}getAnchor(t,e,n,s,r){const o=e.isEdgeElement(n),a=this.graph.options.connecting;let l=typeof t=="string"?{name:t}:t;if(!l){const u=o?(r==="source"?a.sourceEdgeAnchor:a.targetEdgeAnchor)||a.edgeAnchor:(r==="source"?a.sourceAnchor:a.targetAnchor)||a.anchor;l=typeof u=="string"?{name:u}:u}if(!l)throw new Error("Anchor should be specified.");let c;const h=l.name;if(o){const u=sn.registry.get(h);if(typeof u!="function")return sn.registry.onNotFound(h);c=R(u,this,e,n,s,l.args||{},r)}else{const u=nn.registry.get(h);if(typeof u!="function")return nn.registry.onNotFound(h);c=R(u,this,e,n,s,l.args||{},r)}return c?c.round(this.POINT_ROUNDING):new v}findRoutePoints(t=[]){const e=this.graph.options.connecting.router||de.presets.normal,n=this.cell.getRouter()||e;let s;if(typeof n=="function")s=R(n,this,t,{},this);else{const r=typeof n=="string"?n:n.name,o=typeof n=="string"?{}:n.args||{},a=r?de.registry.get(r):de.presets.normal;if(typeof a!="function")return de.registry.onNotFound(r);s=R(a,this,t,o,this)}return s==null?t.map(r=>v.create(r)):s.map(r=>v.create(r))}findConnectionPoints(t,e,n){const s=this.cell,r=this.graph.options.connecting,o=s.getSource(),a=s.getTarget(),l=this.sourceView,c=this.targetView,h=t[0],u=t[t.length-1];let f;if(l&&!l.isEdgeElement(this.sourceMagnet)){const g=this.sourceMagnet||l.container,p=h||n,m=new I(p,e),y=o.connectionPoint||r.sourceConnectionPoint||r.connectionPoint;f=this.getConnectionPoint(y,l,g,m,"source")}else f=e;let d;if(c&&!c.isEdgeElement(this.targetMagnet)){const g=this.targetMagnet||c.container,p=a.connectionPoint||r.targetConnectionPoint||r.connectionPoint,m=u||e,y=new I(m,n);d=this.getConnectionPoint(p,c,g,y,"target")}else d=n;return{source:f,target:d}}getConnectionPoint(t,e,n,s,r){const o=s.end;if(t==null)return o;const a=typeof t=="string"?t:t.name,l=typeof t=="string"?{}:t.args,c=rn.registry.get(a);if(typeof c!="function")return rn.registry.onNotFound(a);const h=R(c,this,s,e,n,l||{},r);return h?h.round(this.POINT_ROUNDING):o}findMarkerPoints(t,e,n){const s=u=>{const f=this.cell.getAttrs(),d=Object.keys(f);for(let g=0,p=d.length;g0?m/p:0),h&&(m=-1*(p-m)||1),r.distance=m;let y;l||(y=u.tangentAtT(g));let x;if(y)x=y.pointOffset(d);else{const b=u.pointAtT(g),w=d.diff(b);x={x:w.x,y:w.y}}return r.offset=x,r.angle=o,r}normalizeLabelPosition(t){return typeof t=="number"?{distance:t}:t}getLabelTransformationMatrix(t){const e=this.normalizeLabelPosition(t),n=e.options||{},s=e.angle||0,r=e.distance,o=r>0&&r<=1;let a=0;const l={x:0,y:0},c=e.offset;c&&(typeof c=="number"?a=c:(c.x!=null&&(l.x=c.x),c.y!=null&&(l.y=c.y)));const h=l.x!==0||l.y!==0||a===0,u=n.keepGradient,f=n.ensureLegibility,d=this.path,g={segmentSubdivisions:this.getConnectionSubdivisions()},p=o?r*this.getConnectionLength():r,m=d.tangentAtLength(p,g);let y,x=s;if(m){if(h)y=m.start,y.translate(l);else{const b=m.clone();b.rotate(-90,m.start),b.setLength(a),y=b.end}u&&(x=m.angle()+s,f&&(x=q.normalize((x+90)%180-90)))}else y=d.start,h&&y.translate(l);return ft().translate(y.x,y.y).rotate(x)}getVertexIndex(t,e){const s=this.cell.getVertices(),r=this.getClosestPointLength(new v(t,e));let o=0;if(r!=null)for(const a=s.length;o(e[r]=l,e[r+1]=l.container===c?void 0:c,e)}beforeArrowheadDragging(t){t.zIndex=this.cell.zIndex,this.cell.toFront();const e=this.container.style;t.pointerEvents=e.pointerEvents,e.pointerEvents="none",this.graph.options.connecting.highlight&&this.highlightAvailableMagnets(t)}afterArrowheadDragging(t){t.zIndex!=null&&(this.cell.setZIndex(t.zIndex,{ui:!0}),t.zIndex=null);const e=this.container;e.style.pointerEvents=t.pointerEvents||"",this.graph.options.connecting.highlight&&this.unhighlightAvailableMagnets(t)}validateConnection(t,e,n,s,r,o,a){const l=this.graph.options.connecting,c=l.allowLoop,h=l.allowNode,u=l.allowEdge,f=l.allowPort,d=l.allowMulti,g=l.validateConnection,p=o?o.cell:null,m=r==="target"?n:t,y=r==="target"?s:e;let x=!0;const b=w=>{const P=r==="source"?a?a.port:null:p?p.getSourcePortId():null,A=r==="target"?a?a.port:null:p?p.getTargetPortId():null;return R(w,this.graph,{edge:p,edgeView:o,sourceView:t,targetView:n,sourcePort:P,targetPort:A,sourceMagnet:e,targetMagnet:s,sourceCell:t?t.cell:null,targetCell:n?n.cell:null,type:r})};if(c!=null&&(typeof c=="boolean"?!c&&t===n&&(x=!1):x=b(c)),x&&f!=null&&(typeof f=="boolean"?!f&&y&&(x=!1):x=b(f)),x&&u!=null&&(typeof u=="boolean"?!u&&Qt.isEdgeView(m)&&(x=!1):x=b(u)),x&&h!=null&&y==null&&(typeof h=="boolean"?!h&&jt.isNodeView(m)&&(x=!1):x=b(h)),x&&d!=null&&o){const w=o.cell,P=r==="source"?a:w.getSource(),A=r==="target"?a:w.getTarget(),S=a?this.graph.getCellById(a.cell):null;if(P&&A&&P.cell&&A.cell&&S)if(typeof d=="function")x=b(d);else{const E=this.graph.model.getConnectedEdges(S,{outgoing:r==="source",incoming:r==="target"});E.length&&(d==="withPort"?E.some(L=>{const T=L.getSource(),j=L.getTarget();return T&&j&&T.cell===P.cell&&j.cell===A.cell&&T.port!=null&&T.port===P.port&&j.port!=null&&j.port===A.port})&&(x=!1):d||E.some(L=>{const T=L.getSource(),j=L.getTarget();return T&&j&&T.cell===P.cell&&j.cell===A.cell})&&(x=!1))}}return x&&g!=null&&(x=b(g)),x}allowConnectToBlank(t){const e=this.graph,s=e.options.connecting.allowBlank;if(typeof s!="function")return!!s;const r=e.findViewByCell(t),o=t.getSourceCell(),a=t.getTargetCell(),l=e.findViewByCell(o),c=e.findViewByCell(a);return R(s,e,{edge:t,edgeView:r,sourceCell:o,targetCell:a,sourceView:l,targetView:c,sourcePort:t.getSourcePortId(),targetPort:t.getTargetPortId(),sourceMagnet:r.sourceMagnet,targetMagnet:r.targetMagnet})}validateEdge(t,e,n){const s=this.graph;if(!this.allowConnectToBlank(t)){const o=t.getSourceCellId(),a=t.getTargetCellId();if(!(o&&a))return!1}const r=s.options.connecting.validateEdge;return r?R(r,s,{edge:t,type:e,previous:n}):!0}arrowheadDragging(t,e,n,s){s.x=e,s.y=n,s.currentTarget!==t&&(s.currentMagnet&&s.currentView&&s.currentView.unhighlight(s.currentMagnet,{type:"magnetAdsorbed"}),s.currentView=this.graph.findViewByElem(t),s.currentView?(s.currentMagnet=s.currentView.findMagnet(t),s.currentMagnet&&this.validateConnection(...s.getValidateConnectionArgs(s.currentView,s.currentMagnet),s.currentView.getEdgeTerminal(s.currentMagnet,e,n,this.cell,s.terminalType))?s.currentView.highlight(s.currentMagnet,{type:"magnetAdsorbed"}):s.currentMagnet=null):s.currentMagnet=null),s.currentTarget=t,this.cell.prop(s.terminalType,{x:e,y:n},Object.assign(Object.assign({},s.options),{ui:!0}))}arrowheadDragged(t,e,n){const s=t.currentView,r=t.currentMagnet;if(!r||!s)return;s.unhighlight(r,{type:"magnetAdsorbed"});const o=t.terminalType,a=s.getEdgeTerminal(r,e,n,this.cell,o);this.cell.setTerminal(o,a,{ui:!0})}snapArrowhead(t,e,n){const s=this.graph,{snap:r,allowEdge:o}=s.options.connecting,a=typeof r=="object"&&r.radius||50,l={x:t-a,y:e-a,width:2*a,height:2*a},c=s.renderer.findViewsInArea(l);if(o){const w=s.renderer.findEdgeViewsInArea(l).filter(P=>P!==this);c.push(...w)}const h=n.closestView||null,u=n.closestMagnet||null;n.closestView=null,n.closestMagnet=null;let f,d=Number.MAX_SAFE_INTEGER;const g=new v(t,e);c.forEach(w=>{w.container.getAttribute("magnet")!=="false"&&(f=w.cell.getBBox().getCenter().distance(g),f{if(P.getAttribute("magnet")!=="false"){const A=w.getBBoxOfElement(P);f=g.distance(A.getCenter()),fthis.validateConnection(...t.getValidateConnectionArgs(o,c),o.getEdgeTerminal(c,t.x,t.y,this.cell,t.terminalType)));if(l.length>0){for(let c=0,h=l.length;c{const s=this.graph.findViewByCell(n);s&&(e[n].forEach(o=>{s.unhighlight(o,{type:"magnetAvailable"})}),s.unhighlight(null,{type:"nodeAvailable"}))}),t.marked=null}startArrowheadDragging(t,e,n){if(!this.can("arrowheadMovable")){this.notifyUnhandledMouseDown(t,e,n);return}const r=t.target.getAttribute("data-terminal"),o=this.prepareArrowheadDragging(r,{x:e,y:n});this.setEventData(t,o)}dragArrowhead(t,e,n){const s=this.getEventData(t);this.graph.options.connecting.snap?this.snapArrowhead(e,n,s):this.arrowheadDragging(this.getEventTarget(t),e,n,s)}stopArrowheadDragging(t,e,n){const s=this.graph,r=this.getEventData(t);s.options.connecting.snap?this.snapArrowheadEnd(r):this.arrowheadDragged(r,e,n),this.validateEdge(this.cell,r.terminalType,r.initialTerminal)?(this.finishEmbedding(r),this.notifyConnectionEvent(r,t)):this.fallbackConnection(r),this.afterArrowheadDragging(r)}startLabelDragging(t,e,n){if(this.can("edgeLabelMovable")){const s=t.currentTarget,r=parseInt(s.getAttribute("data-index"),10),o=this.getLabelPositionAngle(r),a=this.getLabelPositionArgs(r),l=this.getDefaultLabelPositionArgs(),c=this.mergeLabelPositionArgs(a,l);this.setEventData(t,{index:r,positionAngle:o,positionArgs:c,stopPropagation:!0,action:"drag-label"})}else this.setEventData(t,{stopPropagation:!0});this.graph.view.delegateDragEvents(t,this)}dragLabel(t,e,n){const s=this.getEventData(t),r=this.cell.getLabelAt(s.index),o=ot({},r,{position:this.getLabelPosition(e,n,s.positionAngle,s.positionArgs)});this.cell.setLabelAt(s.index,o)}stopLabelDragging(t,e,n){}}(function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag],s=e;return(n==null||n===i.toStringTag)&&typeof s.isNodeView=="function"&&typeof s.isEdgeView=="function"&&typeof s.confirmUpdate=="function"&&typeof s.update=="function"&&typeof s.getConnection=="function"}i.isEdgeView=t})(Qt||(Qt={})),Qt.config({isSvgElement:!0,priority:1,bootstrap:["render","source","target"],actions:{view:["render"],markup:["render"],attrs:["update"],source:["source","update"],target:["target","update"],router:["update"],connector:["update"],labels:["labels"],defaultLabel:["labels"],tools:["tools"],vertices:["vertices","update"]}}),Qt.registry.register("edge",Qt,!0);var Xx=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Vt extends Z{constructor(t){super();this.graph=t;const{selectors:e,fragment:n}=X.parseJSONMarkup(Vt.markup);this.background=e.background,this.grid=e.grid,this.svg=e.svg,this.defs=e.defs,this.viewport=e.viewport,this.primer=e.primer,this.stage=e.stage,this.decorator=e.decorator,this.overlay=e.overlay,this.container=this.options.container,this.restore=Vt.snapshoot(this.container),V(this.container,this.prefixClassName("graph")),On(this.container,n),this.delegateEvents()}get options(){return this.graph.options}delegateEvents(){const t=this.constructor;return super.delegateEvents(t.events),this}guard(t,e){return t.type==="mousedown"&&t.button===2||this.options.guard&&this.options.guard(t,e)?!0:t.data&&t.data.guarded!==void 0?t.data.guarded:!(e&&e.cell&&z.isCell(e.cell)||this.svg===t.target||this.container===t.target||this.svg.contains(t.target))}findView(t){return this.graph.findViewByElem(t)}onDblClick(t){this.options.preventDefaultDblClick&&t.preventDefault();const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;const s=this.graph.snapToGrid(e.clientX,e.clientY);n?n.onDblClick(e,s.x,s.y):this.graph.trigger("blank:dblclick",{e,x:s.x,y:s.y})}onClick(t){if(this.getMouseMovedCount(t)<=this.options.clickThreshold){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;const s=this.graph.snapToGrid(e.clientX,e.clientY);n?n.onClick(e,s.x,s.y):this.graph.trigger("blank:click",{e,x:s.x,y:s.y})}}isPreventDefaultContextMenu(t){let e=this.options.preventDefaultContextMenu;return typeof e=="function"&&(e=R(e,this.graph,{view:t})),e}onContextMenu(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.isPreventDefaultContextMenu(n)&&t.preventDefault(),this.guard(e,n))return;const s=this.graph.snapToGrid(e.clientX,e.clientY);n?n.onContextMenu(e,s.x,s.y):this.graph.trigger("blank:contextmenu",{e,x:s.x,y:s.y})}delegateDragEvents(t,e){t.data==null&&(t.data={}),this.setEventData(t,{currentView:e||null,mouseMovedCount:0,startPosition:{x:t.clientX,y:t.clientY}});const n=this.constructor;this.delegateDocumentEvents(n.documentEvents,t.data),this.undelegateEvents()}getMouseMovedCount(t){return this.getEventData(t).mouseMovedCount||0}onMouseDown(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;this.options.preventDefaultMouseDown&&e.preventDefault();const s=this.graph.snapToGrid(e.clientX,e.clientY);n?n.onMouseDown(e,s.x,s.y):(this.options.preventDefaultBlankAction&&["touchstart"].includes(e.type)&&e.preventDefault(),this.graph.trigger("blank:mousedown",{e,x:s.x,y:s.y})),this.delegateDragEvents(e,n)}onMouseMove(t){const e=this.getEventData(t),n=e.startPosition;if(n&&n.x===t.clientX&&n.y===t.clientY||(e.mouseMovedCount==null&&(e.mouseMovedCount=0),e.mouseMovedCount+=1,e.mouseMovedCount<=this.options.moveThreshold))return;const r=this.normalizeEvent(t),o=this.graph.snapToGrid(r.clientX,r.clientY),a=e.currentView;a?a.onMouseMove(r,o.x,o.y):this.graph.trigger("blank:mousemove",{e:r,x:o.x,y:o.y}),this.setEventData(r,e)}onMouseUp(t){this.undelegateDocumentEvents();const e=this.normalizeEvent(t),n=this.graph.snapToGrid(e.clientX,e.clientY),r=this.getEventData(t).currentView;if(r?r.onMouseUp(e,n.x,n.y):this.graph.trigger("blank:mouseup",{e,x:n.x,y:n.y}),!t.isPropagationStopped()){const o=new kt(t,{type:"click",data:t.data});this.onClick(o)}t.stopImmediatePropagation(),this.delegateEvents()}onMouseOver(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(!this.guard(e,n))if(n)n.onMouseOver(e);else{if(this.container===e.target)return;this.graph.trigger("blank:mouseover",{e})}}onMouseOut(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(!this.guard(e,n))if(n)n.onMouseOut(e);else{if(this.container===e.target)return;this.graph.trigger("blank:mouseout",{e})}}onMouseEnter(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;const s=this.graph.findViewByElem(e.relatedTarget);if(n){if(s===n)return;n.onMouseEnter(e)}else{if(s)return;this.graph.trigger("graph:mouseenter",{e})}}onMouseLeave(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;const s=this.graph.findViewByElem(e.relatedTarget);if(n){if(s===n)return;n.onMouseLeave(e)}else{if(s)return;this.graph.trigger("graph:mouseleave",{e})}}onMouseWheel(t){const e=this.normalizeEvent(t),n=this.findView(e.target);if(this.guard(e,n))return;const s=e.originalEvent,r=this.graph.snapToGrid(s.clientX,s.clientY),o=Math.max(-1,Math.min(1,s.wheelDelta||-s.detail));n?n.onMouseWheel(e,r.x,r.y,o):this.graph.trigger("blank:mousewheel",{e,delta:o,x:r.x,y:r.y})}onCustomEvent(t){const e=t.currentTarget,n=e.getAttribute("event")||e.getAttribute("data-event");if(n){const s=this.findView(e);if(s){const r=this.normalizeEvent(t);if(this.guard(r,s))return;const o=this.graph.snapToGrid(r.clientX,r.clientY);s.onCustomEvent(r,n,o.x,o.y)}}}handleMagnetEvent(t,e){const n=t.currentTarget,s=n.getAttribute("magnet");if(s&&s.toLowerCase()!=="false"){const r=this.findView(n);if(r){const o=this.normalizeEvent(t);if(this.guard(o,r))return;const a=this.graph.snapToGrid(o.clientX,o.clientY);R(e,this.graph,r,o,n,a.x,a.y)}}}onMagnetMouseDown(t){this.handleMagnetEvent(t,(e,n,s,r,o)=>{e.onMagnetMouseDown(n,s,r,o)})}onMagnetDblClick(t){this.handleMagnetEvent(t,(e,n,s,r,o)=>{e.onMagnetDblClick(n,s,r,o)})}onMagnetContextMenu(t){const e=this.findView(t.target);this.isPreventDefaultContextMenu(e)&&t.preventDefault(),this.handleMagnetEvent(t,(n,s,r,o,a)=>{n.onMagnetContextMenu(s,r,o,a)})}onLabelMouseDown(t){const e=t.currentTarget,n=this.findView(e);if(n){const s=this.normalizeEvent(t);if(this.guard(s,n))return;const r=this.graph.snapToGrid(s.clientX,s.clientY);n.onLabelMouseDown(s,r.x,r.y)}}onImageDragStart(){return!1}dispose(){this.undelegateEvents(),this.undelegateDocumentEvents(),this.restore(),this.restore=()=>{}}}Xx([Z.dispose()],Vt.prototype,"dispose",null),function(i){const t=`${gt.prefixCls}-graph`;i.markup=[{ns:ut.xhtml,tagName:"div",selector:"background",className:`${t}-background`},{ns:ut.xhtml,tagName:"div",selector:"grid",className:`${t}-grid`},{ns:ut.svg,tagName:"svg",selector:"svg",className:`${t}-svg`,attrs:{width:"100%",height:"100%","xmlns:xlink":ut.xlink},children:[{tagName:"defs",selector:"defs"},{tagName:"g",selector:"viewport",className:`${t}-svg-viewport`,children:[{tagName:"g",selector:"primer",className:`${t}-svg-primer`},{tagName:"g",selector:"stage",className:`${t}-svg-stage`},{tagName:"g",selector:"decorator",className:`${t}-svg-decorator`},{tagName:"g",selector:"overlay",className:`${t}-svg-overlay`}]}]}];function e(n){const s=n.cloneNode();return n.childNodes.forEach(r=>s.appendChild(r)),()=>{for(Sn(n);n.attributes.length>0;)n.removeAttribute(n.attributes[0].name);for(let r=0,o=s.attributes.length;rn.appendChild(r))}}i.snapshoot=e}(Vt||(Vt={})),function(i){const t=gt.prefixCls;i.events={dblclick:"onDblClick",contextmenu:"onContextMenu",touchstart:"onMouseDown",mousedown:"onMouseDown",mouseover:"onMouseOver",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",mousewheel:"onMouseWheel",DOMMouseScroll:"onMouseWheel",[`mouseenter .${t}-cell`]:"onMouseEnter",[`mouseleave .${t}-cell`]:"onMouseLeave",[`mouseenter .${t}-cell-tools`]:"onMouseEnter",[`mouseleave .${t}-cell-tools`]:"onMouseLeave",[`mousedown .${t}-cell [event]`]:"onCustomEvent",[`touchstart .${t}-cell [event]`]:"onCustomEvent",[`mousedown .${t}-cell [data-event]`]:"onCustomEvent",[`touchstart .${t}-cell [data-event]`]:"onCustomEvent",[`dblclick .${t}-cell [magnet]`]:"onMagnetDblClick",[`contextmenu .${t}-cell [magnet]`]:"onMagnetContextMenu",[`mousedown .${t}-cell [magnet]`]:"onMagnetMouseDown",[`touchstart .${t}-cell [magnet]`]:"onMagnetMouseDown",[`dblclick .${t}-cell [data-magnet]`]:"onMagnetDblClick",[`contextmenu .${t}-cell [data-magnet]`]:"onMagnetContextMenu",[`mousedown .${t}-cell [data-magnet]`]:"onMagnetMouseDown",[`touchstart .${t}-cell [data-magnet]`]:"onMagnetMouseDown",[`dragstart .${t}-cell image`]:"onImageDragStart",[`mousedown .${t}-edge .${t}-edge-label`]:"onLabelMouseDown",[`touchstart .${t}-edge .${t}-edge-label`]:"onLabelMouseDown"},i.documentEvents={mousemove:"onMouseMove",touchmove:"onMouseMove",mouseup:"onMouseUp",touchend:"onMouseUp",touchcancel:"onMouseUp"}}(Vt||(Vt={}));const Jx=`.x6-graph { + position: relative; + outline: none; + touch-action: none; +} +.x6-graph-background, +.x6-graph-grid, +.x6-graph-svg { + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; +} +.x6-graph-background-stage, +.x6-graph-grid-stage, +.x6-graph-svg-stage { + user-select: none; +} +.x6-graph.x6-graph-pannable { + cursor: grab; + cursor: -moz-grab; + cursor: -webkit-grab; +} +.x6-graph.x6-graph-panning { + cursor: grabbing; + cursor: -moz-grabbing; + cursor: -webkit-grabbing; + user-select: none; +} +.x6-node { + cursor: move; + /* stylelint-disable-next-line */ +} +.x6-node.x6-node-immovable { + cursor: default; +} +.x6-node * { + -webkit-user-drag: none; +} +.x6-node .scalable * { + vector-effect: non-scaling-stroke; +} +.x6-node [magnet='true'] { + cursor: crosshair; + transition: opacity 0.3s; +} +.x6-node [magnet='true']:hover { + opacity: 0.7; +} +.x6-node foreignObject { + display: block; + overflow: visible; + background-color: transparent; +} +.x6-node foreignObject > body { + position: static; + width: 100%; + height: 100%; + margin: 0; + padding: 0; + overflow: visible; + background-color: transparent; +} +.x6-edge .source-marker, +.x6-edge .target-marker { + vector-effect: non-scaling-stroke; +} +.x6-edge .connection { + stroke-linejoin: round; + fill: none; +} +.x6-edge .connection-wrap { + cursor: move; + opacity: 0; + fill: none; + stroke: #000; + stroke-width: 15; + stroke-linecap: round; + stroke-linejoin: round; +} +.x6-edge .connection-wrap:hover { + opacity: 0.4; + stroke-opacity: 0.4; +} +.x6-edge .vertices { + cursor: move; + opacity: 0; +} +.x6-edge .vertices .vertex { + fill: #1abc9c; +} +.x6-edge .vertices .vertex :hover { + fill: #34495e; + stroke: none; +} +.x6-edge .vertices .vertex-remove { + cursor: pointer; + fill: #fff; +} +.x6-edge .vertices .vertex-remove-area { + cursor: pointer; + opacity: 0.1; +} +.x6-edge .vertices .vertex-group:hover .vertex-remove-area { + opacity: 1; +} +.x6-edge .arrowheads { + cursor: move; + opacity: 0; +} +.x6-edge .arrowheads .arrowhead { + fill: #1abc9c; +} +.x6-edge .arrowheads .arrowhead :hover { + fill: #f39c12; + stroke: none; +} +.x6-edge .tools { + cursor: pointer; + opacity: 0; +} +.x6-edge .tools .tool-options { + display: none; +} +.x6-edge .tools .tool-remove circle { + fill: #f00; +} +.x6-edge .tools .tool-remove path { + fill: #fff; +} +.x6-edge:hover .vertices, +.x6-edge:hover .arrowheads, +.x6-edge:hover .tools { + opacity: 1; +} +.x6-highlight-opacity { + opacity: 0.3; +} +.x6-cell-tool-editor { + position: relative; + display: inline-block; + min-height: 1em; + margin: 0; + padding: 0; + line-height: 1; + white-space: normal; + text-align: center; + vertical-align: top; + overflow-wrap: normal; + outline: none; + transform-origin: 0 0; + -webkit-user-drag: none; +} +.x6-edge-tool-editor { + border: 1px solid #275fc5; + border-radius: 2px; +} +`;class pt extends qt{constructor(t){super();this.graph=t,this.init()}get options(){return this.graph.options}get model(){return this.graph.model}get view(){return this.graph.view}init(){}}var Yx=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Wi extends pt{init(){gt.autoInsertCSS&&Fa("core",Jx)}dispose(){_a("core")}}Yx([Wi.dispose()],Wi.prototype,"dispose",null);var Zx=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const d=e[f];typeof d=="boolean"?c[f].enabled=d:c[f]=Object.assign(Object.assign({},c[f]),d)}),c}i.get=t})(Un||(Un={})),function(i){i.defaults={x:0,y:0,scaling:{min:.01,max:16},grid:{size:10,visible:!1},background:!1,panning:{enabled:!1,eventTypes:["leftMouseDown"]},mousewheel:{enabled:!1,factor:1.2,zoomAtMousePosition:!0},highlighting:{default:{name:"stroke",args:{padding:3}},nodeAvailable:{name:"className",args:{className:gt.prefix("available-node")}},magnetAvailable:{name:"className",args:{className:gt.prefix("available-magnet")}}},connecting:{snap:!1,allowLoop:!0,allowNode:!0,allowEdge:!1,allowPort:!0,highlight:!1,anchor:"center",edgeAnchor:"ratio",connectionPoint:"boundary",router:"normal",connector:"normal",validateConnection({type:t,sourceView:e,targetView:n}){return(t==="target"?n:e)!=null},createEdge(){return new Xl}},translating:{restrict:!1},embedding:{enabled:!1,findParent:"bbox",frontOnly:!0,validate:()=>!0},moveThreshold:0,clickThreshold:0,magnetThreshold:0,preventDefaultDblClick:!0,preventDefaultMouseDown:!1,preventDefaultContextMenu:!0,preventDefaultBlankAction:!0,interacting:{edgeLabelMovable:!1},async:!0,virtual:!1,guard:()=>!1}}(Un||(Un={}));var Kx=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r},Qx=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const h=`pattern_${c}`,u=n.a||1,f=n.d||1,{update:d,markup:g}=l,p=Qx(l,["update","markup"]),m=Object.assign(Object.assign(Object.assign({},p),r[c]),{sx:u,sy:f,ox:n.e||0,oy:n.f||0,width:e*u,height:e*f});s.has(h)||s.add(h,$.create("pattern",{id:h,patternUnits:"userSpaceOnUse"},$.createVectors(g)).node);const y=s.get(h);typeof d=="function"&&d(y.childNodes[0],m);let x=m.ox%m.width;x<0&&(x+=m.width);let b=m.oy%m.height;b<0&&(b+=m.height),H(y,{x,y:b,width:m.width,height:m.height})});const o=new XMLSerializer().serializeToString(s.root),a=`url(data:image/svg+xml;base64,${btoa(o)})`;this.elem.style.backgroundImage=a}getInstance(){return this.instance||(this.instance=new oe),this.instance}resolveGrid(t){if(!t)return[];const e=t.type;if(e==null)return[Object.assign(Object.assign({},oe.presets.dot),t.args)];const n=oe.registry.get(e);if(n){let s=t.args||[];return Array.isArray(s)||(s=[s]),Array.isArray(n)?n.map((r,o)=>Object.assign(Object.assign({},r),s[o])):[Object.assign(Object.assign({},n),s[0])]}return oe.registry.onNotFound(e)}dispose(){this.stopListening(),this.clear()}}Kx([pt.dispose()],Xi.prototype,"dispose",null);class Jl extends pt{get container(){return this.graph.view.container}get viewport(){return this.graph.view.viewport}get stage(){return this.graph.view.stage}init(){this.resize()}getMatrix(){const t=this.viewport.getAttribute("transform");return t!==this.viewportTransformString&&(this.viewportMatrix=this.viewport.getCTM(),this.viewportTransformString=t),ft(this.viewportMatrix)}setMatrix(t){const e=ft(t),n=Ue(e);this.viewport.setAttribute("transform",n),this.viewportMatrix=e,this.viewportTransformString=n}resize(t,e){let n=t===void 0?this.options.width:t,s=e===void 0?this.options.height:e;this.options.width=n,this.options.height=s,typeof n=="number"&&(n=Math.round(n)),typeof s=="number"&&(s=Math.round(s)),this.container.style.width=n==null?"":`${n}px`,this.container.style.height=s==null?"":`${s}px`;const r=this.getComputedSize();return this.graph.trigger("resize",Object.assign({},r)),this}getComputedSize(){let t=this.options.width,e=this.options.height;return ui(t)||(t=this.container.clientWidth),ui(e)||(e=this.container.clientHeight),{width:t,height:e}}getScale(){return Jm(this.getMatrix())}scale(t,e=t,n=0,s=0){if(t=this.clampScale(t),e=this.clampScale(e),n||s){const o=this.getTranslation(),a=o.tx-n*(t-1),l=o.ty-s*(e-1);(a!==o.tx||l!==o.ty)&&this.translate(a,l)}const r=this.getMatrix();return r.a=t,r.d=e,this.setMatrix(r),this.graph.trigger("scale",{sx:t,sy:e,ox:n,oy:s}),this}clampScale(t){const e=this.graph.options.scaling;return Ct(t,e.min||.01,e.max||16)}getZoom(){return this.getScale().sx}zoom(t,e){e=e||{};let n=t,s=t;const r=this.getScale(),o=this.getComputedSize();let a=o.width/2,l=o.height/2;if(e.absolute||(n+=r.sx,s+=r.sy),e.scaleGrid&&(n=Math.round(n/e.scaleGrid)*e.scaleGrid,s=Math.round(s/e.scaleGrid)*e.scaleGrid),e.maxScale&&(n=Math.min(e.maxScale,n),s=Math.min(e.maxScale,s)),e.minScale&&(n=Math.max(e.minScale,n),s=Math.max(e.minScale,s)),e.center&&(a=e.center.x,l=e.center.y),n=this.clampScale(n),s=this.clampScale(s),a||l){const c=this.getTranslation(),h=a-(a-c.tx)*(n/r.sx),u=l-(l-c.ty)*(s/r.sy);(h!==c.tx||u!==c.ty)&&this.translate(h,u)}return this.scale(n,s),this}getRotation(){return Ym(this.getMatrix())}rotate(t,e,n){if(e==null||n==null){const r=_.getBBox(this.stage);e=r.width/2,n=r.height/2}const s=this.getMatrix().translate(e,n).rotate(t).translate(-e,-n);return this.setMatrix(s),this}getTranslation(){return Zm(this.getMatrix())}translate(t,e){const n=this.getMatrix();n.e=t||0,n.f=e||0,this.setMatrix(n);const s=this.getTranslation();return this.options.x=s.tx,this.options.y=s.ty,this.graph.trigger("translate",Object.assign({},s)),this}setOrigin(t,e){return this.translate(t||0,e||0)}fitToContent(t,e,n,s){if(typeof t=="object"){const b=t;t=b.gridWidth||1,e=b.gridHeight||1,n=b.padding||0,s=b}else t=t||1,e=e||1,n=n||0,s==null&&(s={});const r=ne(n),o=s.border||0,a=s.contentArea?M.create(s.contentArea):this.getContentArea(s);o>0&&a.inflate(o);const l=this.getScale(),c=this.getTranslation(),h=l.sx,u=l.sy;a.x*=h,a.y*=u,a.width*=h,a.height*=u;let f=Math.max(Math.ceil((a.width+a.x)/t),1)*t,d=Math.max(Math.ceil((a.height+a.y)/e),1)*e,g=0,p=0;(s.allowNewOrigin==="negative"&&a.x<0||s.allowNewOrigin==="positive"&&a.x>=0||s.allowNewOrigin==="any")&&(g=Math.ceil(-a.x/t)*t,g+=r.left,f+=g),(s.allowNewOrigin==="negative"&&a.y<0||s.allowNewOrigin==="positive"&&a.y>=0||s.allowNewOrigin==="any")&&(p=Math.ceil(-a.y/e)*e,p+=r.top,d+=p),f+=r.right,d+=r.bottom,f=Math.max(f,s.minWidth||0),d=Math.max(d,s.minHeight||0),f=Math.min(f,s.maxWidth||Number.MAX_SAFE_INTEGER),d=Math.min(d,s.maxHeight||Number.MAX_SAFE_INTEGER);const m=this.getComputedSize(),y=f!==m.width||d!==m.height;return(g!==c.tx||p!==c.ty)&&this.translate(g,p),y&&this.resize(f,d),new M(-g/h,-p/u,f/h,d/u)}scaleContentToFit(t={}){this.scaleContentToFitImpl(t)}scaleContentToFitImpl(t={},e=!0){let n,s;if(t.contentArea){const y=t.contentArea;n=this.graph.localToGraph(y),s=v.create(y)}else n=this.getContentBBox(t),s=this.graph.graphToLocal(n);if(!n.width||!n.height)return;const r=ne(t.padding),o=t.minScale||0,a=t.maxScale||Number.MAX_SAFE_INTEGER,l=t.minScaleX||o,c=t.maxScaleX||a,h=t.minScaleY||o,u=t.maxScaleY||a;let f;if(t.viewportArea)f=t.viewportArea;else{const y=this.getComputedSize(),x=this.getTranslation();f={x:x.tx,y:x.ty,width:y.width,height:y.height}}f=M.create(f).moveAndExpand({x:r.left,y:r.top,width:-r.left-r.right,height:-r.top-r.bottom});const d=this.getScale();let g=f.width/n.width*d.sx,p=f.height/n.height*d.sy;t.preserveAspectRatio!==!1&&(g=p=Math.min(g,p));const m=t.scaleGrid;if(m&&(g=m*Math.floor(g/m),p=m*Math.floor(p/m)),g=Ct(g,l,c),p=Ct(p,h,u),this.scale(g,p),e){const y=this.options,x=f.x-s.x*g-y.x,b=f.y-s.y*p-y.y;this.translate(x,b)}}getContentArea(t={}){return t.useCellGeometry!==!1?this.model.getAllCellsBBox()||new M:_.getBBox(this.stage)}getContentBBox(t={}){return this.graph.localToGraph(this.getContentArea(t))}getGraphArea(){const t=M.fromSize(this.getComputedSize());return this.graph.graphToLocal(t)}zoomToRect(t,e={}){const n=M.create(t),s=this.graph;e.contentArea=n,e.viewportArea==null&&(e.viewportArea={x:s.options.x,y:s.options.y,width:this.options.width,height:this.options.height}),this.scaleContentToFitImpl(e,!1);const r=n.getCenter();return this.centerPoint(r.x,r.y),this}zoomToFit(t={}){return this.zoomToRect(this.getContentArea(t),t)}centerPoint(t,e){const n=this.getComputedSize(),s=this.getScale(),r=this.getTranslation(),o=n.width/2,a=n.height/2;t=typeof t=="number"?t:o,e=typeof e=="number"?e:a,t=o-t*s.sx,e=a-e*s.sy,(r.tx!==t||r.ty!==e)&&this.translate(t,e)}centerContent(t){const n=this.graph.getContentArea(t).getCenter();this.centerPoint(n.x,n.y)}centerCell(t){return this.positionCell(t,"center")}positionPoint(t,e,n){const s=this.getComputedSize();e=Xt(e,Math.max(0,s.width)),e<0&&(e=s.width+e),n=Xt(n,Math.max(0,s.height)),n<0&&(n=s.height+n);const r=this.getTranslation(),o=this.getScale(),a=e-t.x*o.sx,l=n-t.y*o.sy;(r.tx!==a||r.ty!==l)&&this.translate(a,l)}positionRect(t,e){const n=M.create(t);switch(e){case"center":return this.positionPoint(n.getCenter(),"50%","50%");case"top":return this.positionPoint(n.getTopCenter(),"50%",0);case"top-right":return this.positionPoint(n.getTopRight(),"100%",0);case"right":return this.positionPoint(n.getRightMiddle(),"100%","50%");case"bottom-right":return this.positionPoint(n.getBottomRight(),"100%","100%");case"bottom":return this.positionPoint(n.getBottomCenter(),"50%","100%");case"bottom-left":return this.positionPoint(n.getBottomLeft(),0,"100%");case"left":return this.positionPoint(n.getLeftMiddle(),0,"50%");case"top-left":return this.positionPoint(n.getTopLeft(),0,0);default:return this}}positionCell(t,e){const n=t.getBBox();return this.positionRect(n,e)}positionContent(t,e){const n=this.graph.getContentArea(e);return this.positionRect(n,t)}}var tv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Ji extends pt{get elem(){return this.view.background}init(){this.startListening(),this.options.background&&this.draw(this.options.background)}startListening(){this.graph.on("scale",this.update,this),this.graph.on("translate",this.update,this)}stopListening(){this.graph.off("scale",this.update,this),this.graph.off("translate",this.update,this)}updateBackgroundImage(t={}){let e=t.size||"auto auto",n=t.position||"center";const s=this.graph.transform.getScale(),r=this.graph.translate();if(typeof n=="object"){const o=r.tx+s.sx*(n.x||0),a=r.ty+s.sy*(n.y||0);n=`${o}px ${a}px`}typeof e=="object"&&(e=M.fromSize(e).scale(s.sx,s.sy),e=`${e.width}px ${e.height}px`),this.elem.style.backgroundSize=e,this.elem.style.backgroundPosition=n}drawBackgroundImage(t,e={}){if(!(t instanceof HTMLImageElement)){this.elem.style.backgroundImage="";return}const n=this.optionsCache;if(n&&n.image!==e.image)return;let s;const r=e.opacity,o=e.size;let a=e.repeat||"no-repeat";const l=kn.registry.get(a);if(typeof l=="function"){const h=e.quality||1;t.width*=h,t.height*=h;const u=l(t,e);if(!(u instanceof HTMLCanvasElement))throw new Error("Background pattern must return an HTML Canvas instance");s=u.toDataURL("image/png"),e.repeat&&a!==e.repeat?a=e.repeat:a="repeat",typeof o=="object"?(o.width*=u.width/t.width,o.height*=u.height/t.height):o===void 0&&(e.size={width:u.width/h,height:u.height/h})}else s=t.src,o===void 0&&(e.size={width:t.width,height:t.height});n!=null&&typeof e.size=="object"&&e.image===n.image&&e.repeat===n.repeat&&e.quality===n.quality&&(n.size=si(e.size));const c=this.elem.style;c.backgroundImage=`url(${s})`,c.backgroundRepeat=a,c.opacity=r==null||r>=1?"":`${r}`,this.updateBackgroundImage(e)}updateBackgroundColor(t){this.elem.style.backgroundColor=t||""}updateBackgroundOptions(t){this.graph.options.background=t}update(){this.optionsCache&&this.updateBackgroundImage(this.optionsCache)}draw(t){const e=t||{};if(this.updateBackgroundOptions(t),this.updateBackgroundColor(e.color),e.image){this.optionsCache=si(e);const n=document.createElement("img");n.onload=()=>this.drawBackgroundImage(n,t),n.setAttribute("crossorigin","anonymous"),n.src=e.image}else this.drawBackgroundImage(null),this.optionsCache=null}clear(){this.draw()}dispose(){this.clear(),this.stopListening()}}tv([pt.dispose()],Ji.prototype,"dispose",null);var ev=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Yl extends pt{get widgetOptions(){return this.options.panning}get pannable(){return this.widgetOptions&&this.widgetOptions.enabled===!0}init(){this.startListening(),this.updateClassName()}startListening(){const t=this.widgetOptions.eventTypes;!t||(t.includes("leftMouseDown")&&(this.graph.on("blank:mousedown",this.preparePanning,this),this.graph.on("node:unhandled:mousedown",this.preparePanning,this),this.graph.on("edge:unhandled:mousedown",this.preparePanning,this)),t.includes("rightMouseDown")&&(this.onRightMouseDown=this.onRightMouseDown.bind(this),vt.on(this.graph.container,"mousedown",this.onRightMouseDown)),t.includes("mouseWheel")&&(this.mousewheelHandle=new za(this.graph.container,this.onMouseWheel.bind(this),this.allowMouseWheel.bind(this)),this.mousewheelHandle.enable()))}stopListening(){const t=this.widgetOptions.eventTypes;!t||(t.includes("leftMouseDown")&&(this.graph.off("blank:mousedown",this.preparePanning,this),this.graph.off("node:unhandled:mousedown",this.preparePanning,this),this.graph.off("edge:unhandled:mousedown",this.preparePanning,this)),t.includes("rightMouseDown")&&vt.off(this.graph.container,"mousedown",this.onRightMouseDown),t.includes("mouseWheel")&&this.mousewheelHandle&&this.mousewheelHandle.disable())}preparePanning({e:t}){const e=this.graph.getPlugin("selection"),n=e&&e.allowRubberband(t,!0);(this.allowPanning(t,!0)||this.allowPanning(t)&&!n)&&this.startPanning(t)}allowPanning(t,e){return this.pannable&&$n.isMatch(t,this.widgetOptions.modifiers,e)}startPanning(t){const e=this.view.normalizeEvent(t);this.clientX=e.clientX,this.clientY=e.clientY,this.panning=!0,this.updateClassName(),vt.on(document.body,{"mousemove.panning touchmove.panning":this.pan.bind(this),"mouseup.panning touchend.panning":this.stopPanning.bind(this),"mouseleave.panning":this.stopPanning.bind(this)}),vt.on(window,"mouseup.panning",this.stopPanning.bind(this))}pan(t){const e=this.view.normalizeEvent(t),n=e.clientX-this.clientX,s=e.clientY-this.clientY;this.clientX=e.clientX,this.clientY=e.clientY,this.graph.translateBy(n,s)}stopPanning(t){this.panning=!1,this.updateClassName(),vt.off(document.body,".panning"),vt.off(window,".panning")}updateClassName(){const t=this.view.container,e=this.view.prefixClassName("graph-panning"),n=this.view.prefixClassName("graph-pannable");this.pannable?this.panning?(V(t,e),St(t,n)):(St(t,e),V(t,n)):(St(t,e),St(t,n))}onRightMouseDown(t){t.button===2&&this.allowPanning(t,!0)&&this.startPanning(t)}allowMouseWheel(t){return this.pannable&&!t.ctrlKey}onMouseWheel(t,e,n){t.ctrlKey||this.graph.translateBy(-e,-n)}autoPanning(t,e){const n=10,s=this.graph.getGraphArea();let r=0,o=0;t<=s.left+n&&(r=-n),e<=s.top+n&&(o=-n),t>=s.right-n&&(r=n),e>=s.bottom-n&&(o=n),(r!==0||o!==0)&&this.graph.translateBy(-r,-o)}enablePanning(){this.pannable||(this.widgetOptions.enabled=!0,this.updateClassName())}disablePanning(){this.pannable&&(this.widgetOptions.enabled=!1,this.updateClassName())}dispose(){this.stopListening()}}ev([pt.dispose()],Yl.prototype,"dispose",null);var nv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Yi extends pt{constructor(){super(...arguments);this.cumulatedFactor=1}get widgetOptions(){return this.options.mousewheel}init(){this.container=this.graph.container,this.target=this.widgetOptions.global?document:this.container,this.mousewheelHandle=new za(this.target,this.onMouseWheel.bind(this),this.allowMouseWheel.bind(this)),this.widgetOptions.enabled&&this.enable(!0)}get disabled(){return this.widgetOptions.enabled!==!0}enable(t){(this.disabled||t)&&(this.widgetOptions.enabled=!0,this.mousewheelHandle.enable())}disable(){this.disabled||(this.widgetOptions.enabled=!1,this.mousewheelHandle.disable())}allowMouseWheel(t){const e=this.widgetOptions.guard;return(e==null||e.call(t))&&$n.isMatch(t,this.widgetOptions.modifiers)}onMouseWheel(t){const e=this.widgetOptions.guard;if((e==null||e.call(t))&&$n.isMatch(t,this.widgetOptions.modifiers)){const n=this.widgetOptions.factor||1.2;this.currentScale==null&&(this.startPos={x:t.clientX,y:t.clientY},this.currentScale=this.graph.transform.getScale().sx),t.deltaY<0?this.currentScale<.15?this.cumulatedFactor=(this.currentScale+.01)/this.currentScale:this.cumulatedFactor=Math.round(this.currentScale*n*20)/20/this.currentScale:this.currentScale<=.15?this.cumulatedFactor=(this.currentScale-.01)/this.currentScale:this.cumulatedFactor=Math.round(this.currentScale*(1/n)*20)/20/this.currentScale,this.cumulatedFactor=Math.max(.01,Math.min(this.currentScale*this.cumulatedFactor,160)/this.currentScale);const r=this.currentScale;let o=this.graph.transform.clampScale(r*this.cumulatedFactor);const a=this.widgetOptions.minScale||Number.MIN_SAFE_INTEGER,l=this.widgetOptions.maxScale||Number.MAX_SAFE_INTEGER;if(o=Ct(o,a,l),o!==r)if(this.widgetOptions.zoomAtMousePosition){const h=!!this.graph.getPlugin("scroller")?this.graph.clientToLocal(this.startPos):this.graph.clientToGraph(this.startPos);this.graph.zoom(o,{absolute:!0,center:h.clone()})}else this.graph.zoom(o,{absolute:!0});this.currentScale=null,this.cumulatedFactor=1}}dispose(){this.disable()}}nv([qt.dispose()],Yi.prototype,"dispose",null);var sv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Zl extends pt{init(){this.resetRenderArea=yp(this.resetRenderArea,200),this.resetRenderArea(),this.startListening()}startListening(){this.graph.on("translate",this.resetRenderArea,this),this.graph.on("scale",this.resetRenderArea,this),this.graph.on("resize",this.resetRenderArea,this)}stopListening(){this.graph.off("translate",this.resetRenderArea,this),this.graph.off("scale",this.resetRenderArea,this),this.graph.off("resize",this.resetRenderArea,this)}enableVirtualRender(){this.options.virtual=!0,this.resetRenderArea()}disableVirtualRender(){this.options.virtual=!1,this.graph.renderer.setRenderArea(void 0)}resetRenderArea(){if(this.options.virtual){const t=this.graph.getGraphArea();this.graph.renderer.setRenderArea(t)}}dispose(){this.stopListening()}}sv([pt.dispose()],Zl.prototype,"dispose",null);class iv{constructor(){this.isFlushing=!1,this.isFlushPending=!1,this.scheduleId=0,this.queue=[],this.frameInterval=33,this.initialTime=Date.now()}queueJob(t){if(t.priority===Ft.PRIOR)t.cb();else{const e=this.findInsertionIndex(t);e>=0&&this.queue.splice(e,0,t)}}queueFlush(){!this.isFlushing&&!this.isFlushPending&&(this.isFlushPending=!0,this.scheduleJob())}queueFlushSync(){!this.isFlushing&&!this.isFlushPending&&(this.isFlushPending=!0,this.flushJobsSync())}clearJobs(){this.queue.length=0,this.isFlushing=!1,this.isFlushPending=!1,this.cancelScheduleJob()}flushJobs(){this.isFlushPending=!1,this.isFlushing=!0;const t=this.getCurrentTime();let e;for(;e=this.queue.shift();){try{e.cb()}catch(n){}if(this.getCurrentTime()-t>=this.frameInterval)break}this.isFlushing=!1,this.queue.length&&this.queueFlush()}flushJobsSync(){this.isFlushPending=!1,this.isFlushing=!0;let t;for(;t=this.queue.shift();)try{t.cb()}catch(e){}this.isFlushing=!1}findInsertionIndex(t){let e=0;for(;this.queue[e]&&this.queue[e].priority>=t.priority;)e+=1;return e}scheduleJob(){"requestIdleCallback"in window?(this.scheduleId&&this.cancelScheduleJob(),this.scheduleId=window.requestIdleCallback(this.flushJobs.bind(this),{timeout:100})):(this.scheduleId&&this.cancelScheduleJob(),this.scheduleId=window.setTimeout(this.flushJobs.bind(this)))}cancelScheduleJob(){"cancelIdleCallback"in window?(this.scheduleId&&window.cancelIdleCallback(this.scheduleId),this.scheduleId=0):(this.scheduleId&&clearTimeout(this.scheduleId),this.scheduleId=0)}getCurrentTime(){return typeof performance=="object"&&typeof performance.now=="function"?performance.now():Date.now()-this.initialTime}}var Ft;(function(i){i[i.RenderEdge=1]="RenderEdge",i[i.RenderNode=2]="RenderNode",i[i.Update=3]="Update",i[i.PRIOR=100]="PRIOR"})(Ft||(Ft={}));var rv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class lt extends qt{constructor(t){super();this.views={},this.queue=new iv,this.graph=t,this.init()}get model(){return this.graph.model}get container(){return this.graph.view.stage}init(){this.startListening()}startListening(){this.model.on("reseted",this.onModelReseted,this),this.model.on("cell:added",this.onCellAdded,this),this.model.on("cell:removed",this.onCellRemoved,this),this.model.on("cell:change:zIndex",this.onCellZIndexChanged,this),this.model.on("cell:change:visible",this.onCellVisibleChanged,this)}stopListening(){this.model.off("reseted",this.onModelReseted,this),this.model.off("cell:added",this.onCellAdded,this),this.model.off("cell:removed",this.onCellRemoved,this),this.model.off("cell:change:zIndex",this.onCellZIndexChanged,this),this.model.off("cell:change:visible",this.onCellVisibleChanged,this)}onModelReseted({options:t}){this.queue.clearJobs(),this.removeZPivots(),this.removeViews(),this.renderViews(this.model.getCells(),t)}onCellAdded({cell:t,options:e}){this.renderViews([t],e)}onCellRemoved({cell:t,options:e}){const n=this.views[t.id];if(n){const s=n.view;this.requestViewUpdate(s,lt.FLAG_REMOVE,e)}}onCellZIndexChanged({cell:t,options:e}){const n=this.views[t.id];n&&this.requestViewUpdate(n.view,lt.FLAG_INSERT,e,Ft.Update,!0)}onCellVisibleChanged({cell:t,current:e}){this.toggleVisible(t,!!e)}requestViewUpdate(t,e,n={},s=Ft.Update,r=!0){const o=t.cell.id,a=this.views[o];if(!a)return;a.flag=e,a.options=n;const l=t.hasAction(e,["translate","resize","rotate"]);t.isNodeView()&&l&&(s=Ft.PRIOR,r=!1),this.queue.queueJob({id:o,priority:s,cb:()=>{this.renderViewInArea(t,e,n)}}),this.getEffectedEdges(t).forEach(h=>{this.requestViewUpdate(h.view,h.flag,n,s,!1)}),r&&this.flush()}setRenderArea(t){this.renderArea=t,this.flushWaittingViews()}isViewMounted(t){if(t==null)return!1;const e=this.views[t.cell.id];return e?e.state===lt.ViewState.MOUNTED:!1}renderViews(t,e={}){t.sort((n,s)=>n.isNode()&&s.isEdge()?-1:0),t.forEach(n=>{const s=n.id,r=this.views;let o=0,a=r[s];if(a)o=lt.FLAG_INSERT;else{const l=this.createCellView(n);l&&(l.graph=this.graph,o=lt.FLAG_INSERT|l.getBootstrapFlag(),a={view:l,flag:o,options:e,state:lt.ViewState.CREATED},this.views[s]=a)}this.requestViewUpdate(a.view,o,e,n.isNode()?Ft.RenderNode:Ft.RenderEdge,!1)}),this.flush()}renderViewInArea(t,e,n={}){const r=t.cell.id,o=this.views[r];if(!o)return;let a=0;this.isInRenderArea(t)?(a=this.updateView(t,e,n),o.flag=a):o.state===lt.ViewState.MOUNTED?(a=this.updateView(t,e,n),o.flag=a):o.state=lt.ViewState.WAITTING,a&&console.log("left flag",a)}flush(){this.graph.options.async?this.queue.queueFlush():this.queue.queueFlushSync()}flushWaittingViews(){const t=Object.keys(this.views);for(let e=0,n=t.length;e{const e=this.views[t];e&&this.removeView(e.view.cell)}),this.views={}}removeView(t){const e=this.views[t.id];return e&&(e.view.remove(),delete this.views[t.id]),e.view}toggleVisible(t,e){const n=this.model.getConnectedEdges(t);for(let r=0,o=n.length;rs&&(s=a,s===t-1))}const r=this.container;if(s!==-Infinity){const o=e[s];r.insertBefore(n,o.nextSibling)}else r.insertBefore(n,r.firstChild);return n}removeZPivots(){this.zPivots&&Object.keys(this.zPivots).forEach(t=>{const e=this.zPivots[t];e&&e.parentNode&&e.parentNode.removeChild(e)}),this.zPivots={}}createCellView(t){const e={graph:this.graph},n=t.view;if(n!=null&&typeof n=="string"){const s=ht.registry.get(n);return s?new s(t,e):ht.registry.onNotFound(n)}return t.isNode()?new jt(t,e):t.isEdge()?new Qt(t,e):null}getEffectedEdges(t){const e=[],n=t.cell,s=this.model.getConnectedEdges(n);for(let r=0,o=s.length;r=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Zi extends pt{constructor(){super(...arguments);this.schedule=new lt(this.graph)}requestViewUpdate(t,e,n={}){this.schedule.requestViewUpdate(t,e,n)}isViewMounted(t){return this.schedule.isViewMounted(t)}setRenderArea(t){this.schedule.setRenderArea(t)}findViewByElem(t){if(t==null)return null;const e=this.options.container,n=typeof t=="string"?e.querySelector(t):t instanceof Element?t:t[0];if(n){const s=this.graph.view.findAttr("data-cell-id",n);if(s){const r=this.schedule.views;if(r[s])return r[s].view}}return null}findViewByCell(t){if(t==null)return null;const e=z.isCell(t)?t.id:t,n=this.schedule.views;return n[e]?n[e].view:null}findViewsFromPoint(t){const e={x:t.x,y:t.y};return this.model.getCells().map(n=>this.findViewByCell(n)).filter(n=>n!=null?_.getBBox(n.container,{target:this.view.stage}).containsPoint(e):!1)}findViewsInArea(t,e={}){const n=M.create(t);return this.model.getNodes().map(s=>this.findViewByCell(s)).filter(s=>{if(s){const r=_.getBBox(s.container,{target:this.graph.view.stage});return e.strict?n.containsRect(r):n.isIntersectWithRect(r)}return!1})}findEdgeViewsInArea(t,e={}){const n=M.create(t);return this.model.getEdges().map(s=>this.findViewByCell(s)).filter(s=>{if(s){const r=_.getBBox(s.container,{target:this.view.stage});return r.width===0?r.inflate(1,0):r.height===0&&r.inflate(0,1),e.strict?n.containsRect(r):n.isIntersectWithRect(r)}return!1})}dispose(){this.schedule.dispose()}}ov([pt.dispose()],Zi.prototype,"dispose",null);var Kl=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const c=l.opacity!=null&&Number.isFinite(l.opacity)?l.opacity:1;return``}),o=`<${n}>${r.join("")}`,a=Object.assign({id:e},t.attrs);$.create(o,a).appendTo(this.defs)}return e}marker(t){const{id:e,refX:n,refY:s,markerUnits:r,markerOrient:o,tagName:a,children:l}=t,c=Kl(t,["id","refX","refY","markerUnits","markerOrient","tagName","children"]);let h=e;if(h||(h=`marker-${this.cid}-${mi(JSON.stringify(t))}`),!this.isDefined(h)){a!=="path"&&delete c.d;const u=$.create("marker",{refX:n,refY:s,id:h,overflow:"visible",orient:o!=null?o:"auto",markerUnits:r||"userSpaceOnUse"},l?l.map(f=>{var{tagName:d}=f,g=Kl(f,["tagName"]);return $.create(`${d}`||"path",En(Object.assign(Object.assign({},c),g)))}):[$.create(a||"path",En(c))]);this.defs.appendChild(u.node)}return h}remove(t){const e=this.svg.getElementById(t);e&&e.parentNode&&e.parentNode.removeChild(e)}}class tc extends pt{getClientMatrix(){return ft(this.view.stage.getScreenCTM())}getClientOffset(){const t=this.view.svg.getBoundingClientRect();return new v(t.left,t.top)}getPageOffset(){return this.getClientOffset().translate(window.scrollX,window.scrollY)}snapToGrid(t,e){return(typeof t=="number"?this.clientToLocalPoint(t,e):this.clientToLocalPoint(t.x,t.y)).snapToGrid(this.graph.getGridSize())}localToGraphPoint(t,e){const n=v.create(t,e);return _.transformPoint(n,this.graph.matrix())}localToClientPoint(t,e){const n=v.create(t,e);return _.transformPoint(n,this.getClientMatrix())}localToPagePoint(t,e){return(typeof t=="number"?this.localToGraphPoint(t,e):this.localToGraphPoint(t)).translate(this.getPageOffset())}localToGraphRect(t,e,n,s){const r=M.create(t,e,n,s);return _.transformRectangle(r,this.graph.matrix())}localToClientRect(t,e,n,s){const r=M.create(t,e,n,s);return _.transformRectangle(r,this.getClientMatrix())}localToPageRect(t,e,n,s){return(typeof t=="number"?this.localToGraphRect(t,e,n,s):this.localToGraphRect(t)).translate(this.getPageOffset())}graphToLocalPoint(t,e){const n=v.create(t,e);return _.transformPoint(n,this.graph.matrix().inverse())}clientToLocalPoint(t,e){const n=v.create(t,e);return _.transformPoint(n,this.getClientMatrix().inverse())}clientToGraphPoint(t,e){const n=v.create(t,e);return _.transformPoint(n,this.graph.matrix().multiply(this.getClientMatrix().inverse()))}pageToLocalPoint(t,e){const s=v.create(t,e).diff(this.getPageOffset());return this.graphToLocalPoint(s)}graphToLocalRect(t,e,n,s){const r=M.create(t,e,n,s);return _.transformRectangle(r,this.graph.matrix().inverse())}clientToLocalRect(t,e,n,s){const r=M.create(t,e,n,s);return _.transformRectangle(r,this.getClientMatrix().inverse())}clientToGraphRect(t,e,n,s){const r=M.create(t,e,n,s);return _.transformRectangle(r,this.graph.matrix().multiply(this.getClientMatrix().inverse()))}pageToLocalRect(t,e,n,s){const r=M.create(t,e,n,s),o=this.getPageOffset();return r.x-=o.x,r.y-=o.y,this.graphToLocalRect(r)}}var av=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class Bs extends pt{constructor(){super(...arguments);this.highlights={}}init(){this.startListening()}startListening(){this.graph.on("cell:highlight",this.onCellHighlight,this),this.graph.on("cell:unhighlight",this.onCellUnhighlight,this)}stopListening(){this.graph.off("cell:highlight",this.onCellHighlight,this),this.graph.off("cell:unhighlight",this.onCellUnhighlight,this)}onCellHighlight({view:t,magnet:e,options:n={}}){const s=this.resolveHighlighter(n);if(!s)return;const r=this.getHighlighterId(e,s);if(!this.highlights[r]){const o=s.highlighter;o.highlight(t,e,Object.assign({},s.args)),this.highlights[r]={cellView:t,magnet:e,highlighter:o,args:s.args}}}onCellUnhighlight({magnet:t,options:e={}}){const n=this.resolveHighlighter(e);if(!n)return;const s=this.getHighlighterId(t,n);this.unhighlight(s)}resolveHighlighter(t){const e=this.options;let n=t.highlighter;if(n==null){const a=t.type;n=a&&e.highlighting[a]||e.highlighting.default}if(n==null)return null;const s=typeof n=="string"?{name:n}:n,r=s.name,o=Zt.registry.get(r);return o==null?Zt.registry.onNotFound(r):(Zt.check(r,o),{name:r,highlighter:o,args:s.args||{}})}getHighlighterId(t,e){return wi(t),e.name+t.id+JSON.stringify(e.args)}unhighlight(t){const e=this.highlights[t];e&&(e.highlighter.unhighlight(e.cellView,e.magnet,e.args),delete this.highlights[t])}dispose(){Object.keys(this.highlights).forEach(t=>this.unhighlight(t)),this.stopListening()}}av([Bs.dispose()],Bs.prototype,"dispose",null);var lv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class ec extends pt{getScroller(){const t=this.graph.getPlugin("scroller");return t&&t.options.enabled?t:null}getContainer(){const t=this.getScroller();return t?t.container.parentElement:this.graph.container.parentElement}getSensorTarget(){const t=this.options.autoResize;if(t)return typeof t=="boolean"?this.getContainer():t}init(){if(this.options.autoResize){const e=this.getSensorTarget();e&&bs.bind(e,()=>{const n=e.offsetWidth,s=e.offsetHeight;this.resize(n,s)})}}resize(t,e){const n=this.getScroller();n?n.resize(t,e):this.graph.transform.resize(t,e)}dispose(){bs.clear(this.graph.container)}}lv([pt.dispose()],ec.prototype,"dispose",null);var cv=function(i,t,e,n){var s=arguments.length,r=s<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(r=(s<3?o(r):s>3?o(t,e,r):o(t,e))||r);return s>3&&r&&Object.defineProperty(t,e,r),r};class wt extends Pt{constructor(t){super();this.installedPlugins=new Set,this.options=Un.get(t),this.css=new Wi(this),this.view=new Vt(this),this.defs=new Ql(this),this.coord=new tc(this),this.transform=new Jl(this),this.highlight=new Bs(this),this.grid=new Xi(this),this.background=new Ji(this),this.model=this.options.model?this.options.model:new zt,this.model.graph=this,this.renderer=new Zi(this),this.panning=new Yl(this),this.mousewheel=new Yi(this),this.virtualRender=new Zl(this),this.size=new ec(this)}get container(){return this.options.container}get[Symbol.toStringTag](){return wt.toStringTag}isNode(t){return t.isNode()}isEdge(t){return t.isEdge()}resetCells(t,e={}){return this.model.resetCells(t,e),this}clearCells(t={}){return this.model.clear(t),this}toJSON(t={}){return this.model.toJSON(t)}parseJSON(t){return this.model.parseJSON(t)}fromJSON(t,e={}){return this.model.fromJSON(t,e),this}getCellById(t){return this.model.getCell(t)}addNode(t,e={}){return this.model.addNode(t,e)}addNodes(t,e={}){return this.addCell(t.map(n=>it.isNode(n)?n:this.createNode(n)),e)}createNode(t){return this.model.createNode(t)}removeNode(t,e={}){return this.model.removeCell(t,e)}addEdge(t,e={}){return this.model.addEdge(t,e)}addEdges(t,e={}){return this.addCell(t.map(n=>K.isEdge(n)?n:this.createEdge(n)),e)}removeEdge(t,e={}){return this.model.removeCell(t,e)}createEdge(t){return this.model.createEdge(t)}addCell(t,e={}){return this.model.addCell(t,e),this}removeCell(t,e={}){return this.model.removeCell(t,e)}removeCells(t,e={}){return this.model.removeCells(t,e)}removeConnectedEdges(t,e={}){return this.model.removeConnectedEdges(t,e)}disconnectConnectedEdges(t,e={}){return this.model.disconnectConnectedEdges(t,e),this}hasCell(t){return this.model.has(t)}getCells(){return this.model.getCells()}getCellCount(){return this.model.total()}getNodes(){return this.model.getNodes()}getEdges(){return this.model.getEdges()}getOutgoingEdges(t){return this.model.getOutgoingEdges(t)}getIncomingEdges(t){return this.model.getIncomingEdges(t)}getConnectedEdges(t,e={}){return this.model.getConnectedEdges(t,e)}getRootNodes(){return this.model.getRoots()}getLeafNodes(){return this.model.getLeafs()}isRootNode(t){return this.model.isRoot(t)}isLeafNode(t){return this.model.isLeaf(t)}getNeighbors(t,e={}){return this.model.getNeighbors(t,e)}isNeighbor(t,e,n={}){return this.model.isNeighbor(t,e,n)}getSuccessors(t,e={}){return this.model.getSuccessors(t,e)}isSuccessor(t,e,n={}){return this.model.isSuccessor(t,e,n)}getPredecessors(t,e={}){return this.model.getPredecessors(t,e)}isPredecessor(t,e,n={}){return this.model.isPredecessor(t,e,n)}getCommonAncestor(...t){return this.model.getCommonAncestor(...t)}getSubGraph(t,e={}){return this.model.getSubGraph(t,e)}cloneSubGraph(t,e={}){return this.model.cloneSubGraph(t,e)}cloneCells(t){return this.model.cloneCells(t)}getNodesFromPoint(t,e){return this.model.getNodesFromPoint(t,e)}getNodesInArea(t,e,n,s,r){return this.model.getNodesInArea(t,e,n,s,r)}getNodesUnderNode(t,e={}){return this.model.getNodesUnderNode(t,e)}searchCell(t,e,n={}){return this.model.search(t,e,n),this}getShortestPath(t,e,n={}){return this.model.getShortestPath(t,e,n)}getAllCellsBBox(){return this.model.getAllCellsBBox()}getCellsBBox(t,e={}){return this.model.getCellsBBox(t,e)}startBatch(t,e={}){this.model.startBatch(t,e)}stopBatch(t,e={}){this.model.stopBatch(t,e)}batchUpdate(t,e,n){const s=typeof t=="string"?t:"update",r=typeof t=="string"?e:t,o=typeof e=="function"?n:e;this.startBatch(s,o);const a=r();return this.stopBatch(s,o),a}updateCellId(t,e){return this.model.updateCellId(t,e)}findView(t){return z.isCell(t)?this.findViewByCell(t):this.findViewByElem(t)}findViews(t){return M.isRectangleLike(t)?this.findViewsInArea(t):v.isPointLike(t)?this.findViewsFromPoint(t):[]}findViewByCell(t){return this.renderer.findViewByCell(t)}findViewByElem(t){return this.renderer.findViewByElem(t)}findViewsFromPoint(t,e){const n=typeof t=="number"?{x:t,y:e}:t;return this.renderer.findViewsFromPoint(n)}findViewsInArea(t,e,n,s,r){const o=typeof t=="number"?{x:t,y:e,width:n,height:s}:t,a=typeof t=="number"?r:e;return this.renderer.findViewsInArea(o,a)}matrix(t){return typeof t=="undefined"?this.transform.getMatrix():(this.transform.setMatrix(t),this)}resize(t,e){const n=this.getPlugin("scroller");return n?n.resize(t,e):this.transform.resize(t,e),this}scale(t,e=t,n=0,s=0){return typeof t=="undefined"?this.transform.getScale():(this.transform.scale(t,e,n,s),this)}zoom(t,e){const n=this.getPlugin("scroller");if(n){if(typeof t=="undefined")return n.zoom();n.zoom(t,e)}else{if(typeof t=="undefined")return this.transform.getZoom();this.transform.zoom(t,e)}return this}zoomTo(t,e={}){const n=this.getPlugin("scroller");return n?n.zoom(t,Object.assign(Object.assign({},e),{absolute:!0})):this.transform.zoom(t,Object.assign(Object.assign({},e),{absolute:!0})),this}zoomToRect(t,e={}){const n=this.getPlugin("scroller");return n?n.zoomToRect(t,e):this.transform.zoomToRect(t,e),this}zoomToFit(t={}){const e=this.getPlugin("scroller");return e?e.zoomToFit(t):this.transform.zoomToFit(t),this}rotate(t,e,n){return typeof t=="undefined"?this.transform.getRotation():(this.transform.rotate(t,e,n),this)}translate(t,e){return typeof t=="undefined"?this.transform.getTranslation():(this.transform.translate(t,e),this)}translateBy(t,e){const n=this.translate(),s=n.tx+t,r=n.ty+e;return this.translate(s,r)}getGraphArea(){return this.transform.getGraphArea()}getContentArea(t={}){return this.transform.getContentArea(t)}getContentBBox(t={}){return this.transform.getContentBBox(t)}fitToContent(t,e,n,s){return this.transform.fitToContent(t,e,n,s)}scaleContentToFit(t={}){return this.transform.scaleContentToFit(t),this}center(){return this.centerPoint()}centerPoint(t,e){const n=this.getPlugin("scroller");return n?n.centerPoint(t,e):this.transform.centerPoint(t,e),this}centerContent(t){const e=this.getPlugin("scroller");return e?e.centerContent(t):this.transform.centerContent(t),this}centerCell(t){const e=this.getPlugin("scroller");return e?e.centerCell(t):this.transform.centerCell(t),this}positionPoint(t,e,n){const s=this.getPlugin("scroller");return s?s.positionPoint(t,e,n):this.transform.positionPoint(t,e,n),this}positionRect(t,e){const n=this.getPlugin("scroller");return n?n.positionRect(t,e):this.transform.positionRect(t,e),this}positionCell(t,e){const n=this.getPlugin("scroller");return n?n.positionCell(t,e):this.transform.positionCell(t,e),this}positionContent(t,e){const n=this.getPlugin("scroller");return n?n.positionContent(t,e):this.transform.positionContent(t,e),this}snapToGrid(t,e){return this.coord.snapToGrid(t,e)}pageToLocal(t,e,n,s){return M.isRectangleLike(t)?this.coord.pageToLocalRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.pageToLocalRect(t,e,n,s):this.coord.pageToLocalPoint(t,e)}localToPage(t,e,n,s){return M.isRectangleLike(t)?this.coord.localToPageRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.localToPageRect(t,e,n,s):this.coord.localToPagePoint(t,e)}clientToLocal(t,e,n,s){return M.isRectangleLike(t)?this.coord.clientToLocalRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.clientToLocalRect(t,e,n,s):this.coord.clientToLocalPoint(t,e)}localToClient(t,e,n,s){return M.isRectangleLike(t)?this.coord.localToClientRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.localToClientRect(t,e,n,s):this.coord.localToClientPoint(t,e)}localToGraph(t,e,n,s){return M.isRectangleLike(t)?this.coord.localToGraphRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.localToGraphRect(t,e,n,s):this.coord.localToGraphPoint(t,e)}graphToLocal(t,e,n,s){return M.isRectangleLike(t)?this.coord.graphToLocalRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.graphToLocalRect(t,e,n,s):this.coord.graphToLocalPoint(t,e)}clientToGraph(t,e,n,s){return M.isRectangleLike(t)?this.coord.clientToGraphRect(t):typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof s=="number"?this.coord.clientToGraphRect(t,e,n,s):this.coord.clientToGraphPoint(t,e)}defineFilter(t){return this.defs.filter(t)}defineGradient(t){return this.defs.gradient(t)}defineMarker(t){return this.defs.marker(t)}getGridSize(){return this.grid.getGridSize()}setGridSize(t){return this.grid.setGridSize(t),this}showGrid(){return this.grid.show(),this}hideGrid(){return this.grid.hide(),this}clearGrid(){return this.grid.clear(),this}drawGrid(t){return this.grid.draw(t),this}updateBackground(){return this.background.update(),this}drawBackground(t,e){const n=this.getPlugin("scroller");return n!=null&&(this.options.background==null||!e)?n.drawBackground(t,e):this.background.draw(t),this}clearBackground(t){const e=this.getPlugin("scroller");return e!=null&&(this.options.background==null||!t)?e.clearBackground(t):this.background.clear(),this}enableVirtualRender(){return this.virtualRender.enableVirtualRender(),this}disableVirtualRender(){return this.virtualRender.disableVirtualRender(),this}isMouseWheelEnabled(){return!this.mousewheel.disabled}enableMouseWheel(){return this.mousewheel.enable(),this}disableMouseWheel(){return this.mousewheel.disable(),this}toggleMouseWheel(t){return t==null?this.isMouseWheelEnabled()?this.disableMouseWheel():this.enableMouseWheel():t?this.enableMouseWheel():this.disableMouseWheel(),this}isPannable(){const t=this.getPlugin("scroller");return t?t.isPannable():this.panning.pannable}enablePanning(){const t=this.getPlugin("scroller");return t?t.enablePanning():this.panning.enablePanning(),this}disablePanning(){const t=this.getPlugin("scroller");return t?t.disablePanning():this.panning.disablePanning(),this}togglePanning(t){return t==null?this.isPannable()?this.disablePanning():this.enablePanning():t!==this.isPannable()&&(t?this.enablePanning():this.disablePanning()),this}use(t,...e){return this.installedPlugins.has(t)||(this.installedPlugins.add(t),t.init(this,...e)),this}getPlugin(t){let e;return this.installedPlugins.forEach(n=>{n.name===t&&(e=n)}),e}dispose(){this.clearCells(),this.off(),this.css.dispose(),this.defs.dispose(),this.grid.dispose(),this.coord.dispose(),this.transform.dispose(),this.highlight.dispose(),this.background.dispose(),this.mousewheel.dispose(),this.panning.dispose(),this.view.dispose(),this.renderer.dispose(),this.installedPlugins.forEach(t=>{t.dispose()})}}cv([Pt.dispose()],wt.prototype,"dispose",null),function(i){i.View=Vt,i.Renderer=Zi,i.MouseWheel=Yi,i.DefsManager=Ql,i.GridManager=Xi,i.CoordManager=tc,i.TransformManager=Jl,i.HighlightManager=Bs,i.BackgroundManager=Ji}(wt||(wt={})),function(i){i.toStringTag=`X6.${i.name}`;function t(e){if(e==null)return!1;if(e instanceof i)return!0;const n=e[Symbol.toStringTag];return n==null||n===i.toStringTag}i.isGraph=t}(wt||(wt={})),function(i){function t(e,n){const s=e instanceof HTMLElement?new i({container:e}):new i(e);return n!=null&&s.fromJSON(n),s}i.render=t}(wt||(wt={})),function(i){i.registerNode=it.registry.register,i.registerEdge=K.registry.register,i.registerView=ht.registry.register,i.registerAttr=Bt.registry.register,i.registerGrid=oe.registry.register,i.registerFilter=Ye.registry.register,i.registerNodeTool=tn.registry.register,i.registerEdgeTool=en.registry.register,i.registerBackground=kn.registry.register,i.registerHighlighter=Zt.registry.register,i.registerPortLayout=Oe.registry.register,i.registerPortLabelLayout=Ke.registry.register,i.registerMarker=le.registry.register,i.registerRouter=de.registry.register,i.registerConnector=Ee.registry.register,i.registerAnchor=nn.registry.register,i.registerEdgeAnchor=sn.registry.register,i.registerConnectionPoint=rn.registry.register}(wt||(wt={})),function(i){i.unregisterNode=it.registry.unregister,i.unregisterEdge=K.registry.unregister,i.unregisterView=ht.registry.unregister,i.unregisterAttr=Bt.registry.unregister,i.unregisterGrid=oe.registry.unregister,i.unregisterFilter=Ye.registry.unregister,i.unregisterNodeTool=tn.registry.unregister,i.unregisterEdgeTool=en.registry.unregister,i.unregisterBackground=kn.registry.unregister,i.unregisterHighlighter=Zt.registry.unregister,i.unregisterPortLayout=Oe.registry.unregister,i.unregisterPortLabelLayout=Ke.registry.unregister,i.unregisterMarker=le.registry.unregister,i.unregisterRouter=de.registry.unregister,i.unregisterConnector=Ee.registry.unregister,i.unregisterAnchor=nn.registry.unregister,i.unregisterEdgeAnchor=sn.registry.unregister,i.unregisterConnectionPoint=rn.registry.unregister}(wt||(wt={}));var hv=function(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(i);s{const s=i.shapeMaps[this.cell.shape];if(s){const{effect:r}=s;(!r||r.includes(n))&&this.renderHTMLComponent()}})}confirmUpdate(n){const s=super.confirmUpdate(n);return this.handleAction(s,t.action,()=>this.renderHTMLComponent())}renderHTMLComponent(){const n=this.selectors.foContent;if(n){Sn(n);const s=i.shapeMaps[this.cell.shape];if(!s)return;let{html:r}=s;typeof r=="function"&&(r=r(this.cell)),r&&(typeof r=="string"?n.innerHTML=r:On(n,r))}}}i.View=t,function(e){e.action="html",e.config({bootstrap:[e.action],actions:{html:e.action}}),jt.registry.register("html-view",e,!0)}(t=i.View||(i.View={}))})(Me||(Me={})),function(i){i.config({view:"html-view",markup:[{tagName:"rect",selector:"body"},Object.assign({},X.getForeignObjectMarkup()),{tagName:"text",selector:"label"}],attrs:{body:{fill:"none",stroke:"none",refWidth:"100%",refHeight:"100%"},fo:{refWidth:"100%",refHeight:"100%"}}}),it.registry.register("html",i,!0)}(Me||(Me={})),function(i){i.shapeMaps={};function t(e){const{shape:n,html:s,effect:r,inherit:o}=e,a=hv(e,["shape","html","effect","inherit"]);if(!n)throw new Error("should specify shape in config");i.shapeMaps[n]={html:s,effect:r},wt.registerNode(n,Object.assign({inherit:o||"html"},a),!0)}i.register=t}(Me||(Me={}));export{q as A,Pt as B,Wx as C,Mi as D,Xl as E,Fa as F,wt as G,Me as H,Ux as I,_a as J,zt as M,Vx as P,kx as R,Gx as T,$ as V,Bx as a,Fx as b,Hx as c,gt as d,Ge as e,M as f,R as g,Pn as h,ui as i,fr as j,rt as k,Ws as l,Yn as m,ne as n,pr as o,_s as p,ss as q,jo as r,_o as s,wn as t,tt as u,Rt as v,qt as w,Ci as x,Z as y,v as z}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/identity-2f636783.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/identity-2f636783.js new file mode 100644 index 0000000000000000000000000000000000000000..625a148fed5c93785afee092529d611ac17c52e4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/identity-2f636783.js @@ -0,0 +1 @@ +function i(t){return t}var n=i;export{n as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/index-021016f6.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/index-021016f6.js new file mode 100644 index 0000000000000000000000000000000000000000..1324755d31b77fc2978425123c9839166ce7ce24 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/index-021016f6.js @@ -0,0 +1 @@ +import{r as g}from"./index-78959ebc.js";import{h as Te}from"./hoist-non-react-statics.cjs-01efe895.js";import{u as Ne}from"./unitless.browser.esm-319df2e6.js";import{c as D,a as U}from"./_commonjsHelpers-b3efd043.js";function Me(e){if(e.sheet)return e.sheet;for(var r=0;r0?S(k,--E):0,M--,y===10&&(M=1,K--),y}function C(){return y=E2||X(y)>3?"":" "}function He(e,r){for(;--r&&C()&&!(y<48||y>102||y>57&&y<65||y>70&&y<97););return Q(e,J()+(r<6&&P()==32&&C()==32))}function ue(e){for(;C();)switch(y){case e:return E;case 34:case 39:return ue(e===34||e===39?e:y);case 40:e===41&&ue(e);break;case 92:C();break}return E}function Ke(e,r){for(;C()&&e+y!==47+10;)if(e+y===42+42&&P()===47)break;return"/*"+Q(r,E-1)+"*"+G(e===47?e:C())}function pe(e){for(;!X(P());)C();return Q(e,E)}function Ze(e){return ge(Y("",null,null,null,[""],e=ye(e),0,[0],e))}function Y(e,r,t,n,a,s,u,i,f){for(var l=0,c=0,d=u,F=0,R=0,A=0,h=1,x=1,p=1,w=0,O="",I=a,N=s,_=n,m=O;x;)switch(A=w,w=C()){case 34:case 39:case 91:case 40:m+=se(w);break;case 9:case 10:case 13:case 32:m+=Ge(A);break;case 92:m+=He(J()-1,7);continue;case 47:switch(P()){case 42:case 47:H(Je(Ke(C(),J()),r,t),f);break;default:m+="/"}break;case 123*h:i[l++]=$(m)*p;case 125*h:case 59:case 0:switch(w){case 0:case 125:x=0;case 59+c:R>0&&$(m)-d&&H(R>32?we(m+";",n,t,d-1):we(v(m," ","")+";",n,t,d-2),f);break;case 59:m+=";";default:if(H(_=be(m,r,t,l,c,a,i,O,I=[],N=[],d),s),w===123)if(c===0)Y(m,r,_,_,I,s,d,i,N);else switch(F){case 100:case 109:case 115:Y(e,_,_,n&&H(be(e,_,_,0,0,a,i,O,a,I=[],d),N),a,N,d,i,n?I:N);break;default:Y(m,_,_,_,[""],N,d,i,N)}}l=c=R=0,h=p=1,O=m="",d=u;break;case 58:d=1+$(m),R=A;default:if(h<1){if(w==123)--h;else if(w==125&&h++==0&&qe()==125)continue}switch(m+=G(w),w*h){case 38:p=c>0?1:(m+="\f",-1);break;case 44:i[l++]=($(m)-1)*p,p=1;break;case 64:P()===45&&(m+=se(C())),F=P(),c=$(O=m+=pe(J())),w++;break;case 45:A===45&&$(m)==2&&(h=0)}}return s}function be(e,r,t,n,a,s,u,i,f,l,c){for(var d=a-1,F=a===0?s:[""],R=ae(F),A=0,h=0,x=0;A0?F[p]+" "+w:v(w,/&\f/g,F[p])))&&(f[x++]=O);return Z(e,r,t,a===0?te:i,f,l,c)}function Je(e,r,t){return Z(e,r,t,ve,G(Ue()),L(e,2,-2),0)}function we(e,r,t,n){return Z(e,r,t,ne,L(e,0,n),L(e,n+1,-1),n)}function xe(e,r){switch(ze(e,r)){case 5103:return o+"print-"+e+e;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return o+e+e;case 5349:case 4246:case 4810:case 6968:case 2756:return o+e+q+e+b+e+e;case 6828:case 4268:return o+e+b+e+e;case 6165:return o+e+b+"flex-"+e+e;case 5187:return o+e+v(e,/(\w+).+(:[^]+)/,o+"box-$1$2"+b+"flex-$1$2")+e;case 5443:return o+e+b+"flex-item-"+v(e,/flex-|-self/,"")+e;case 4675:return o+e+b+"flex-line-pack"+v(e,/align-content|flex-|-self/,"")+e;case 5548:return o+e+b+v(e,"shrink","negative")+e;case 5292:return o+e+b+v(e,"basis","preferred-size")+e;case 6060:return o+"box-"+v(e,"-grow","")+o+e+b+v(e,"grow","positive")+e;case 4554:return o+v(e,/([^-])(transform)/g,"$1"+o+"$2")+e;case 6187:return v(v(v(e,/(zoom-|grab)/,o+"$1"),/(image-set)/,o+"$1"),e,"")+e;case 5495:case 3959:return v(e,/(image-set\([^]*)/,o+"$1$`$1");case 4968:return v(v(e,/(.+:)(flex-)?(.*)/,o+"box-pack:$3"+b+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+o+e+e;case 4095:case 3583:case 4068:case 2532:return v(e,/(.+)-inline(.+)/,o+"$1$2")+e;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if($(e)-1-r>6)switch(S(e,r+1)){case 109:if(S(e,r+4)!==45)break;case 102:return v(e,/(.+:)(.+)-([^]+)/,"$1"+o+"$2-$3$1"+q+(S(e,r+3)==108?"$3":"$2-$3"))+e;case 115:return~de(e,"stretch")?xe(v(e,"stretch","fill-available"),r)+e:e}break;case 4949:if(S(e,r+1)!==115)break;case 6444:switch(S(e,$(e)-3-(~de(e,"!important")&&10))){case 107:return v(e,":",":"+o)+e;case 101:return v(e,/(.+:)([^;!]+)(;|!.+)?/,"$1"+o+(S(e,14)===45?"inline-":"")+"box$3$1"+o+"$2$3$1"+b+"$2box$3")+e}break;case 5936:switch(S(e,r+11)){case 114:return o+e+b+v(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return o+e+b+v(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return o+e+b+v(e,/[svh]\w+-[tblr]{2}/,"lr")+e}return o+e+b+e+e}return e}function z(e,r){for(var t="",n=ae(e),a=0;a=4;++n,a-=4)t=e.charCodeAt(n)&255|(e.charCodeAt(++n)&255)<<8|(e.charCodeAt(++n)&255)<<16|(e.charCodeAt(++n)&255)<<24,t=(t&65535)*1540483477+((t>>>16)*59797<<16),t^=t>>>24,r=(t&65535)*1540483477+((t>>>16)*59797<<16)^(r&65535)*1540483477+((r>>>16)*59797<<16);switch(a){case 3:r^=(e.charCodeAt(n+2)&255)<<16;case 2:r^=(e.charCodeAt(n+1)&255)<<8;case 1:r^=e.charCodeAt(n)&255,r=(r&65535)*1540483477+((r>>>16)*59797<<16)}return r^=r>>>13,r=(r&65535)*1540483477+((r>>>16)*59797<<16),((r^r>>>15)>>>0).toString(36)}var or=/[A-Z]|^ms/g,lr=/_EMO_([^_]+?)_([^]*?)_EMO_/g,Ce=function(r){return r.charCodeAt(1)===45},Oe=function(r){return r!=null&&typeof r!="boolean"},fe=er(function(e){return Ce(e)?e:e.replace(or,"-$&").toLowerCase()}),_e=function(r,t){switch(r){case"animation":case"animationName":if(typeof t=="string")return t.replace(lr,function(n,a,s){return j={name:a,styles:s,next:j},a})}return Ne[r]!==1&&!Ce(r)&&typeof t=="number"&&t!==0?t+"px":t};function V(e,r,t){if(t==null)return"";if(t.__emotion_styles!==void 0)return t;switch(typeof t){case"boolean":return"";case"object":{if(t.anim===1)return j={name:t.name,styles:t.styles,next:j},t.name;if(t.styles!==void 0){var n=t.next;if(n!==void 0)for(;n!==void 0;)j={name:n.name,styles:n.styles,next:j},n=n.next;var a=t.styles+";";return a}return vr(e,r,t)}case"function":{if(e!==void 0){var s=j,u=t(e);return j=s,V(e,r,u)}break}}if(r==null)return t;var i=r[t];return i!==void 0?i:t}function vr(e,r,t){var n="";if(Array.isArray(t))for(var a=0;a=p},i=function(){},n.unstable_forceFrameRate=function(g){0>g||125>>1,Q=g[U];if(Q!==void 0&&0P(Ze,M))dn!==void 0&&0>P(dn,Ze)?(g[U]=dn,g[Hn]=M,U=Hn):(g[U]=Ze,g[Ge]=M,U=Ge);else if(dn!==void 0&&0>P(dn,M))g[U]=dn,g[Hn]=M,U=Hn;else break e}}return L}return null}function P(g,L){var M=g.sortIndex-L.sortIndex;return M!==0?M:g.id-L.id}var B=[],he=[],Is=1,ue=null,K=3,jt=!1,Ke=!1,Wn=!1;function Hr(g){for(var L=E(he);L!==null;){if(L.callback===null)z(he);else if(L.startTime<=g)z(he),L.sortIndex=L.expirationTime,w(B,L);else break;L=E(he)}}function Ar(g){if(Wn=!1,Hr(g),!Ke)if(E(B)!==null)Ke=!0,t(Qr);else{var L=E(he);L!==null&&r(Ar,L.startTime-g)}}function Qr(g,L){Ke=!1,Wn&&(Wn=!1,l()),jt=!0;var M=K;try{for(Hr(L),ue=E(B);ue!==null&&(!(ue.expirationTime>L)||g&&!n.unstable_shouldYield());){var U=ue.callback;if(typeof U=="function"){ue.callback=null,K=ue.priorityLevel;var Q=U(ue.expirationTime<=L);L=n.unstable_now(),typeof Q=="function"?ue.callback=Q:ue===E(B)&&z(B),Hr(L)}else z(B);ue=E(B)}if(ue!==null)var Ge=!0;else{var Ze=E(he);Ze!==null&&r(Ar,Ze.startTime-L),Ge=!1}return Ge}finally{ue=null,K=M,jt=!1}}var Fs=i;n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(g){g.callback=null},n.unstable_continueExecution=function(){Ke||jt||(Ke=!0,t(Qr))},n.unstable_getCurrentPriorityLevel=function(){return K},n.unstable_getFirstCallbackNode=function(){return E(B)},n.unstable_next=function(g){switch(K){case 1:case 2:case 3:var L=3;break;default:L=K}var M=K;K=L;try{return g()}finally{K=M}},n.unstable_pauseExecution=function(){},n.unstable_requestPaint=Fs,n.unstable_runWithPriority=function(g,L){switch(g){case 1:case 2:case 3:case 4:case 5:break;default:g=3}var M=K;K=g;try{return L()}finally{K=M}},n.unstable_scheduleCallback=function(g,L,M){var U=n.unstable_now();switch(typeof M=="object"&&M!==null?(M=M.delay,M=typeof M=="number"&&0U?(g.sortIndex=M,w(he,g),E(B)===null&&g===E(he)&&(Wn?l():Wn=!0,r(Ar,M-U))):(g.sortIndex=Q,w(B,g),Ke||jt||(Ke=!0,t(Qr))),g},n.unstable_wrapCallback=function(g){var L=K;return function(){var M=K;K=L;try{return g.apply(this,arguments)}finally{K=M}}}}),H=$r(function(e){e.exports=js});function v(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;tn}return!1}function b(e,n,t,r,l,i,o){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=i,this.removeEmptyString=o}var $={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){$[e]=new b(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];$[n]=new b(n,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){$[e]=new b(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){$[e]=new b(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){$[e]=new b(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){$[e]=new b(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){$[e]=new b(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){$[e]=new b(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){$[e]=new b(e,5,!1,e.toLowerCase(),null,!1,!1)});var Yr=/[\-:]([a-z])/g;function Xr(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var n=e.replace(Yr,Xr);$[n]=new b(n,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(Yr,Xr);$[n]=new b(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(Yr,Xr);$[n]=new b(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){$[e]=new b(e,1,!1,e.toLowerCase(),null,!1,!1)}),$.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){$[e]=new b(e,1,!1,e.toLowerCase(),null,!0,!0)});function Kr(e,n,t,r){var l=$.hasOwnProperty(n)?$[n]:null,i=l!==null?l.type===0:r?!1:!(!(2u||l[o]!==i[u])return` +`+l[o].replace(" at new "," at ");while(1<=o&&0<=u);break}}}finally{ll=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?Kn(e):""}function Hs(e){switch(e.tag){case 5:return Kn(e.type);case 16:return Kn("Lazy");case 13:return Kn("Suspense");case 19:return Kn("SuspenseList");case 0:case 2:case 15:return e=Ht(e.type,!1),e;case 11:return e=Ht(e.type.render,!1),e;case 22:return e=Ht(e.type._render,!1),e;case 1:return e=Ht(e.type,!0),e;default:return""}}function mn(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Te:return"Fragment";case be:return"Portal";case $n:return"Profiler";case Gr:return"StrictMode";case Yn:return"Suspense";case Bt:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Jr:return(e.displayName||"Context")+".Consumer";case Zr:return(e._context.displayName||"Context")+".Provider";case Vt:var n=e.render;return n=n.displayName||n.name||"",e.displayName||(n!==""?"ForwardRef("+n+")":"ForwardRef");case Wt:return mn(e.type);case br:return mn(e._render);case qr:n=e._payload,e=e._init;try{return mn(e(n))}catch(t){}}return null}function Le(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function bi(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function As(e){var n=bi(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t!="undefined"&&typeof t.get=="function"&&typeof t.set=="function"){var l=t.get,i=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function At(e){e._valueTracker||(e._valueTracker=As(e))}function eo(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=bi(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function Qt(e){if(e=e||(typeof document!="undefined"?document:void 0),typeof e=="undefined")return null;try{return e.activeElement||e.body}catch(n){return e.body}}function il(e,n){var t=n.checked;return I({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t!=null?t:e._wrapperState.initialChecked})}function no(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=Le(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function to(e,n){n=n.checked,n!=null&&Kr(e,"checked",n,!1)}function ol(e,n){to(e,n);var t=Le(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?ul(e,n.type,t):n.hasOwnProperty("defaultValue")&&ul(e,n.type,Le(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function ro(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function ul(e,n,t){(n!=="number"||Qt(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}function Qs(e){var n="";return Ut.Children.forEach(e,function(t){t!=null&&(n+=t)}),n}function sl(e,n){return e=I({children:void 0},n),(n=Qs(n.children))&&(e.children=n),e}function hn(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l=t.length))throw Error(v(93));t=t[0]}n=t}n==null&&(n=""),t=n}e._wrapperState={initialValue:Le(t)}}function io(e,n){var t=Le(n.value),r=Le(n.defaultValue);t!=null&&(t=""+t,t!==e.value&&(e.value=t),n.defaultValue==null&&e.defaultValue!==t&&(e.defaultValue=t)),r!=null&&(e.defaultValue=""+r)}function oo(e){var n=e.textContent;n===e._wrapperState.initialValue&&n!==""&&n!==null&&(e.value=n)}var fl={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function uo(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function cl(e,n){return e==null||e==="http://www.w3.org/1999/xhtml"?uo(n):e==="http://www.w3.org/2000/svg"&&n==="foreignObject"?"http://www.w3.org/1999/xhtml":e}var $t,so=function(e){return typeof MSApp!="undefined"&&MSApp.execUnsafeLocalFunction?function(n,t,r,l){MSApp.execUnsafeLocalFunction(function(){return e(n,t,r,l)})}:e}(function(e,n){if(e.namespaceURI!==fl.svg||"innerHTML"in e)e.innerHTML=n;else{for($t=$t||document.createElement("div"),$t.innerHTML=""+n.valueOf().toString()+"",n=$t.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function Gn(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var Zn={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},$s=["Webkit","ms","Moz","O"];Object.keys(Zn).forEach(function(e){$s.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Zn[n]=Zn[e]})});function ao(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||Zn.hasOwnProperty(e)&&Zn[e]?(""+n).trim():n+"px"}function fo(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,l=ao(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}var Ys=I({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function dl(e,n){if(n){if(Ys[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(v(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(v(60));if(!(typeof n.dangerouslySetInnerHTML=="object"&&"__html"in n.dangerouslySetInnerHTML))throw Error(v(61))}if(n.style!=null&&typeof n.style!="object")throw Error(v(62))}}function pl(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function ml(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var hl=null,vn=null,yn=null;function co(e){if(e=ht(e)){if(typeof hl!="function")throw Error(v(280));var n=e.stateNode;n&&(n=ar(n),hl(e.stateNode,e.type,n))}}function po(e){vn?yn?yn.push(e):yn=[e]:vn=e}function mo(){if(vn){var e=vn,n=yn;if(yn=vn=null,co(e),n)for(e=0;er?0:1<t;t++)n.push(e);return n}function qt(e,n,t){e.pendingLanes|=n;var r=n-1;e.suspendedLanes&=r,e.pingedLanes&=r,e=e.eventTimes,n=31-Re(n),e[n]=t}var Re=Math.clz32?Math.clz32:sa,oa=Math.log,ua=Math.LN2;function sa(e){return e===0?32:31-(oa(e)/ua|0)|0}var aa=H.unstable_UserBlockingPriority,fa=H.unstable_runWithPriority,bt=!0;function ca(e,n,t,r){en||yl();var l=Ll,i=en;en=!0;try{ho(l,e,n,t,r)}finally{(en=i)||wl()}}function da(e,n,t,r){fa(aa,Ll.bind(null,e,n,t,r))}function Ll(e,n,t,r){if(bt){var l;if((l=(n&4)==0)&&0=st),Wo=String.fromCharCode(32),Ho=!1;function Ao(e,n){switch(e){case"keyup":return Ia.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Qo(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var En=!1;function ja(e,n){switch(e){case"compositionend":return Qo(n);case"keypress":return n.which!==32?null:(Ho=!0,Wo);case"textInput":return e=n.data,e===Wo&&Ho?null:e;default:return null}}function Ua(e,n){if(En)return e==="compositionend"||!jl&&Ao(e,n)?(e=Io(),er=Ml=De=null,En=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=Jo(t)}}function bo(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?bo(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function eu(){for(var e=window,n=Qt();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch(r){t=!1}if(t)e=n.contentWindow;else break;n=Qt(e.document)}return n}function Bl(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}var Ka=Ee&&"documentMode"in document&&11>=document.documentMode,_n=null,Wl=null,dt=null,Hl=!1;function nu(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;Hl||_n==null||_n!==Qt(r)||(r=_n,"selectionStart"in r&&Bl(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),dt&&ct(dt,r)||(dt=r,r=ir(Wl,"onSelect"),0Tn||(e.current=Gl[Tn],Gl[Tn]=null,Tn--)}function F(e,n){Tn++,Gl[Tn]=e.current,e.current=n}var je={},G=Fe(je),ne=Fe(!1),rn=je;function Ln(e,n){var t=e.type.contextTypes;if(!t)return je;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function te(e){return e=e.childContextTypes,e!=null}function fr(){D(ne),D(G)}function yu(e,n,t){if(G.current!==je)throw Error(v(168));F(G,n),F(ne,t)}function gu(e,n,t){var r=e.stateNode;if(e=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in e))throw Error(v(108,mn(n)||"Unknown",l));return I({},t,r)}function cr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||je,rn=G.current,F(G,e),F(ne,ne.current),!0}function wu(e,n,t){var r=e.stateNode;if(!r)throw Error(v(169));t?(e=gu(e,n,rn),r.__reactInternalMemoizedMergedChildContext=e,D(ne),D(G),F(G,e)):D(ne),F(ne,t)}var Zl=null,ln=null,Ja=H.unstable_runWithPriority,Jl=H.unstable_scheduleCallback,ql=H.unstable_cancelCallback,qa=H.unstable_shouldYield,ku=H.unstable_requestPaint,bl=H.unstable_now,ba=H.unstable_getCurrentPriorityLevel,dr=H.unstable_ImmediatePriority,Su=H.unstable_UserBlockingPriority,Eu=H.unstable_NormalPriority,_u=H.unstable_LowPriority,Cu=H.unstable_IdlePriority,ei={},ef=ku!==void 0?ku:function(){},_e=null,pr=null,ni=!1,xu=bl(),Z=1e4>xu?bl:function(){return bl()-xu};function zn(){switch(ba()){case dr:return 99;case Su:return 98;case Eu:return 97;case _u:return 96;case Cu:return 95;default:throw Error(v(332))}}function Nu(e){switch(e){case 99:return dr;case 98:return Su;case 97:return Eu;case 96:return _u;case 95:return Cu;default:throw Error(v(332))}}function on(e,n){return e=Nu(e),Ja(e,n)}function vt(e,n,t){return e=Nu(e),Jl(e,n,t)}function ye(){if(pr!==null){var e=pr;pr=null,ql(e)}Pu()}function Pu(){if(!ni&&_e!==null){ni=!0;var e=0;try{var n=_e;on(99,function(){for(;eE?(z=w,w=null):z=w.sibling;var P=h(c,w,f[E],p);if(P===null){w===null&&(w=z);break}e&&w&&P.alternate===null&&n(c,w),a=i(P,a,E),N===null?m=P:N.sibling=P,N=P,w=z}if(E===f.length)return t(c,w),m;if(w===null){for(;EE?(z=w,w=null):z=w.sibling;var B=h(c,w,P.value,p);if(B===null){w===null&&(w=z);break}e&&w&&B.alternate===null&&n(c,w),a=i(B,a,E),N===null?m=B:N.sibling=B,N=B,w=z}if(P.done)return t(c,w),m;if(w===null){for(;!P.done;E++,P=f.next())P=C(c,P.value,p),P!==null&&(a=i(P,a,E),N===null?m=P:N.sibling=P,N=P);return m}for(w=r(c,w);!P.done;E++,P=f.next())P=S(w,c,E,P.value,p),P!==null&&(e&&P.alternate!==null&&w.delete(P.key===null?E:P.key),a=i(P,a,E),N===null?m=P:N.sibling=P,N=P);return e&&w.forEach(function(he){return n(c,he)}),m}return function(c,a,f,p){var m=typeof f=="object"&&f!==null&&f.type===Te&&f.key===null;m&&(f=f.props.children);var N=typeof f=="object"&&f!==null;if(N)switch(f.$$typeof){case Qn:e:{for(N=f.key,m=a;m!==null;){if(m.key===N){switch(m.tag){case 7:if(f.type===Te){t(c,m.sibling),a=l(m,f.props.children),a.return=c,c=a;break e}break;default:if(m.elementType===f.type){t(c,m.sibling),a=l(m,f.props),a.ref=gt(c,m,f),a.return=c,c=a;break e}}t(c,m);break}else n(c,m);m=m.sibling}f.type===Te?(a=Bn(f.props.children,c.mode,p,f.key),a.return=c,c=a):(p=Ur(f.type,f.key,f.props,null,c.mode,p),p.ref=gt(c,a,f),p.return=c,c=p)}return o(c);case be:e:{for(m=f.key;a!==null;){if(a.key===m)if(a.tag===4&&a.stateNode.containerInfo===f.containerInfo&&a.stateNode.implementation===f.implementation){t(c,a.sibling),a=l(a,f.children||[]),a.return=c,c=a;break e}else{t(c,a);break}else n(c,a);a=a.sibling}a=Hi(f,c.mode,p),a.return=c,c=a}return o(c)}if(typeof f=="string"||typeof f=="number")return f=""+f,a!==null&&a.tag===6?(t(c,a.sibling),a=l(a,f),a.return=c,c=a):(t(c,a),a=Wi(f,c.mode,p),a.return=c,c=a),o(c);if(wr(f))return x(c,a,f,p);if(Xn(f))return _(c,a,f,p);if(N&&kr(c,f),typeof f=="undefined"&&!m)switch(c.tag){case 1:case 22:case 0:case 11:case 15:throw Error(v(152,mn(c.type)||"Component"))}return t(c,a)}}var Sr=Fu(!0),ju=Fu(!1),wt={},ge=Fe(wt),kt=Fe(wt),St=Fe(wt);function un(e){if(e===wt)throw Error(v(174));return e}function oi(e,n){switch(F(St,n),F(kt,e),F(ge,wt),e=n.nodeType,e){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:cl(null,"");break;default:e=e===8?n.parentNode:n,n=e.namespaceURI||null,e=e.tagName,n=cl(n,e)}D(ge),F(ge,n)}function Rn(){D(ge),D(kt),D(St)}function Uu(e){un(St.current);var n=un(ge.current),t=cl(n,e.type);n!==t&&(F(kt,e),F(ge,t))}function ui(e){kt.current===e&&(D(ge),D(kt))}var j=Fe(0);function Er(e){for(var n=e;n!==null;){if(n.tag===13){var t=n.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return n}else if(n.tag===19&&n.memoizedProps.revealOrder!==void 0){if((n.flags&64)!=0)return n}else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var Ce=null,We=null,we=!1;function Vu(e,n){var t=de(5,null,null,0);t.elementType="DELETED",t.type="DELETED",t.stateNode=n,t.return=e,t.flags=8,e.lastEffect!==null?(e.lastEffect.nextEffect=t,e.lastEffect=t):e.firstEffect=e.lastEffect=t}function Bu(e,n){switch(e.tag){case 5:var t=e.type;return n=n.nodeType!==1||t.toLowerCase()!==n.nodeName.toLowerCase()?null:n,n!==null?(e.stateNode=n,!0):!1;case 6:return n=e.pendingProps===""||n.nodeType!==3?null:n,n!==null?(e.stateNode=n,!0):!1;case 13:return!1;default:return!1}}function si(e){if(we){var n=We;if(n){var t=n;if(!Bu(e,n)){if(n=xn(t.nextSibling),!n||!Bu(e,n)){e.flags=e.flags&-1025|2,we=!1,Ce=e;return}Vu(Ce,t)}Ce=e,We=xn(n.firstChild)}else e.flags=e.flags&-1025|2,we=!1,Ce=e}}function Wu(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Ce=e}function _r(e){if(e!==Ce)return!1;if(!we)return Wu(e),we=!0,!1;var n=e.type;if(e.tag!==5||n!=="head"&&n!=="body"&&!Yl(n,e.memoizedProps))for(n=We;n;)Vu(e,n),n=xn(n.nextSibling);if(Wu(e),e.tag===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(v(317));e:{for(e=e.nextSibling,n=0;e;){if(e.nodeType===8){var t=e.data;if(t==="/$"){if(n===0){We=xn(e.nextSibling);break e}n--}else t!=="$"&&t!=="$!"&&t!=="$?"||n++}e=e.nextSibling}We=null}}else We=Ce?xn(e.stateNode.nextSibling):null;return!0}function ai(){We=Ce=null,we=!1}var Dn=[];function fi(){for(var e=0;ei))throw Error(v(301));i+=1,Y=J=null,n.updateQueue=null,Et.current=of,e=t(r,l)}while(Ct)}if(Et.current=Tr,n=J!==null&&J.next!==null,_t=0,Y=J=V=null,Cr=!1,n)throw Error(v(300));return e}function sn(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Y===null?V.memoizedState=Y=e:Y=Y.next=e,Y}function an(){if(J===null){var e=V.alternate;e=e!==null?e.memoizedState:null}else e=J.next;var n=Y===null?V.memoizedState:Y.next;if(n!==null)Y=n,J=e;else{if(e===null)throw Error(v(310));J=e,e={memoizedState:J.memoizedState,baseState:J.baseState,baseQueue:J.baseQueue,queue:J.queue,next:null},Y===null?V.memoizedState=Y=e:Y=Y.next=e}return Y}function ke(e,n){return typeof n=="function"?n(e):n}function xt(e){var n=an(),t=n.queue;if(t===null)throw Error(v(311));t.lastRenderedReducer=e;var r=J,l=r.baseQueue,i=t.pending;if(i!==null){if(l!==null){var o=l.next;l.next=i.next,i.next=o}r.baseQueue=l=i,t.pending=null}if(l!==null){l=l.next,r=r.baseState;var u=o=i=null,s=l;do{var d=s.lane;if((_t&d)===d)u!==null&&(u=u.next={lane:0,action:s.action,eagerReducer:s.eagerReducer,eagerState:s.eagerState,next:null}),r=s.eagerReducer===e?s.eagerState:e(r,s.action);else{var y={lane:d,action:s.action,eagerReducer:s.eagerReducer,eagerState:s.eagerState,next:null};u===null?(o=u=y,i=r):u=u.next=y,V.lanes|=d,Lt|=d}s=s.next}while(s!==null&&s!==l);u===null?i=r:u.next=o,se(r,n.memoizedState)||(me=!0),n.memoizedState=r,n.baseState=i,n.baseQueue=u,t.lastRenderedState=r}return[n.memoizedState,t.dispatch]}function Nt(e){var n=an(),t=n.queue;if(t===null)throw Error(v(311));t.lastRenderedReducer=e;var r=t.dispatch,l=t.pending,i=n.memoizedState;if(l!==null){t.pending=null;var o=l=l.next;do i=e(i,o.action),o=o.next;while(o!==l);se(i,n.memoizedState)||(me=!0),n.memoizedState=i,n.baseQueue===null&&(n.baseState=i),t.lastRenderedState=i}return[i,r]}function Hu(e,n,t){var r=n._getVersion;r=r(n._source);var l=n._workInProgressVersionPrimary;if(l!==null?e=l===r:(e=e.mutableReadLanes,(e=(_t&e)===e)&&(n._workInProgressVersionPrimary=r,Dn.push(n))),e)return t(n._source);throw Dn.push(n),Error(v(350))}function Au(e,n,t,r){var l=ee;if(l===null)throw Error(v(349));var i=n._getVersion,o=i(n._source),u=Et.current,s=u.useState(function(){return Hu(l,n,t)}),d=s[1],y=s[0];s=Y;var C=e.memoizedState,h=C.refs,S=h.getSnapshot,x=C.source;C=C.subscribe;var _=V;return e.memoizedState={refs:h,source:n,subscribe:r},u.useEffect(function(){h.getSnapshot=t,h.setSnapshot=d;var c=i(n._source);if(!se(o,c)){c=t(n._source),se(y,c)||(d(c),c=Ae(_),l.mutableReadLanes|=c&l.pendingLanes),c=l.mutableReadLanes,l.entangledLanes|=c;for(var a=l.entanglements,f=c;0t?98:t,function(){e(!0)}),on(97",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(t,{is:r.is}):(e=o.createElement(t),t==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,t),e[Ie]=n,e[sr]=r,fs(e,n,!1,!1),n.stateNode=e,o=pl(t,r),t){case"dialog":R("cancel",e),R("close",e),l=r;break;case"iframe":case"object":case"embed":R("load",e),l=r;break;case"video":case"audio":for(l=0;lOi&&(n.flags|=64,i=!0,Tt(r,!1),n.lanes=33554432)}else{if(!i)if(e=Er(o),e!==null){if(n.flags|=64,i=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),Tt(r,!0),r.tail===null&&r.tailMode==="hidden"&&!o.alternate&&!we)return n=n.lastEffect=r.lastEffect,n!==null&&(n.nextEffect=null),null}else 2*Z()-r.renderingStartTime>Oi&&t!==1073741824&&(n.flags|=64,i=!0,Tt(r,!1),n.lanes=33554432);r.isBackwards?(o.sibling=n.child,n.child=o):(t=r.last,t!==null?t.sibling=o:n.child=o,r.last=o)}return r.tail!==null?(t=r.tail,r.rendering=t,r.tail=t.sibling,r.lastEffect=n.lastEffect,r.renderingStartTime=Z(),t.sibling=null,n=j.current,F(j,i?n&1|2:n&1),t):null;case 23:case 24:return Ui(),e!==null&&e.memoizedState!==null!=(n.memoizedState!==null)&&r.mode!=="unstable-defer-without-hiding"&&(n.flags|=4),null}throw Error(v(156,n.tag))}function af(e){switch(e.tag){case 1:te(e.type)&&fr();var n=e.flags;return n&4096?(e.flags=n&-4097|64,e):null;case 3:if(Rn(),D(ne),D(G),fi(),n=e.flags,(n&64)!=0)throw Error(v(285));return e.flags=n&-4097|64,e;case 5:return ui(e),null;case 13:return D(j),n=e.flags,n&4096?(e.flags=n&-4097|64,e):null;case 19:return D(j),null;case 4:return Rn(),null;case 10:return ri(e),null;case 23:case 24:return Ui(),null;default:return null}}function Ei(e,n){try{var t="",r=n;do t+=Hs(r),r=r.return;while(r);var l=t}catch(i){l=` +Error generating stack: `+i.message+` +`+i.stack}return{value:e,source:n,stack:l}}function _i(e,n){try{console.error(n.value)}catch(t){setTimeout(function(){throw t})}}var ff=typeof WeakMap=="function"?WeakMap:Map;function ps(e,n,t){t=Ve(-1,t),t.tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){Or||(Or=!0,Ri=r),_i(e,n)},t}function ms(e,n,t){t=Ve(-1,t),t.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=n.value;t.payload=function(){return _i(e,n),r(l)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(t.callback=function(){typeof r!="function"&&(Se===null?Se=new Set([this]):Se.add(this),_i(e,n));var o=n.stack;this.componentDidCatch(n.value,{componentStack:o!==null?o:""})}),t}var cf=typeof WeakSet=="function"?WeakSet:Set;function hs(e){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(t){Ye(e,t)}else n.current=null}function df(e,n){switch(n.tag){case 0:case 11:case 15:case 22:return;case 1:if(n.flags&256&&e!==null){var t=e.memoizedProps,r=e.memoizedState;e=n.stateNode,n=e.getSnapshotBeforeUpdate(n.elementType===n.type?t:pe(n.type,t),r),e.__reactInternalSnapshotBeforeUpdate=n}return;case 3:n.flags&256&&Xl(n.stateNode.containerInfo);return;case 5:case 6:case 4:case 17:return}throw Error(v(163))}function pf(e,n,t){switch(t.tag){case 0:case 11:case 15:case 22:if(n=t.updateQueue,n=n!==null?n.lastEffect:null,n!==null){e=n=n.next;do{if((e.tag&3)==3){var r=e.create;e.destroy=r()}e=e.next}while(e!==n)}if(n=t.updateQueue,n=n!==null?n.lastEffect:null,n!==null){e=n=n.next;do{var l=e;r=l.next,l=l.tag,(l&4)!=0&&(l&1)!=0&&(zs(t,e),Sf(t,e)),e=r}while(e!==n)}return;case 1:e=t.stateNode,t.flags&4&&(n===null?e.componentDidMount():(r=t.elementType===t.type?n.memoizedProps:pe(t.type,n.memoizedProps),e.componentDidUpdate(r,n.memoizedState,e.__reactInternalSnapshotBeforeUpdate))),n=t.updateQueue,n!==null&&Mu(t,n,e);return;case 3:if(n=t.updateQueue,n!==null){if(e=null,t.child!==null)switch(t.child.tag){case 5:e=t.child.stateNode;break;case 1:e=t.child.stateNode}Mu(t,n,e)}return;case 5:e=t.stateNode,n===null&&t.flags&4&&du(t.type,t.memoizedProps)&&e.focus();return;case 6:return;case 4:return;case 12:return;case 13:t.memoizedState===null&&(t=t.alternate,t!==null&&(t=t.memoizedState,t!==null&&(t=t.dehydrated,t!==null&&Po(t))));return;case 19:case 17:case 20:case 21:case 23:case 24:return}throw Error(v(163))}function vs(e,n){for(var t=e;;){if(t.tag===5){var r=t.stateNode;if(n)r=r.style,typeof r.setProperty=="function"?r.setProperty("display","none","important"):r.display="none";else{r=t.stateNode;var l=t.memoizedProps.style;l=l!=null&&l.hasOwnProperty("display")?l.display:null,r.style.display=ao("display",l)}}else if(t.tag===6)t.stateNode.nodeValue=n?"":t.memoizedProps;else if((t.tag!==23&&t.tag!==24||t.memoizedState===null||t===e)&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}}function ys(e,n){if(ln&&typeof ln.onCommitFiberUnmount=="function")try{ln.onCommitFiberUnmount(Zl,n)}catch(i){}switch(n.tag){case 0:case 11:case 14:case 15:case 22:if(e=n.updateQueue,e!==null&&(e=e.lastEffect,e!==null)){var t=e=e.next;do{var r=t,l=r.destroy;if(r=r.tag,l!==void 0)if((r&4)!=0)zs(n,t);else{r=n;try{l()}catch(i){Ye(r,i)}}t=t.next}while(t!==e)}break;case 1:if(hs(n),e=n.stateNode,typeof e.componentWillUnmount=="function")try{e.props=n.memoizedProps,e.state=n.memoizedState,e.componentWillUnmount()}catch(i){Ye(n,i)}break;case 5:hs(n);break;case 4:Ss(e,n)}}function gs(e){e.alternate=null,e.child=null,e.dependencies=null,e.firstEffect=null,e.lastEffect=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.return=null,e.updateQueue=null}function ws(e){return e.tag===5||e.tag===3||e.tag===4}function ks(e){e:{for(var n=e.return;n!==null;){if(ws(n))break e;n=n.return}throw Error(v(160))}var t=n;switch(n=t.stateNode,t.tag){case 5:var r=!1;break;case 3:n=n.containerInfo,r=!0;break;case 4:n=n.containerInfo,r=!0;break;default:throw Error(v(161))}t.flags&16&&(Gn(n,""),t.flags&=-17);e:n:for(t=e;;){for(;t.sibling===null;){if(t.return===null||ws(t.return)){t=null;break e}t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue n;t.child.return=t,t=t.child}if(!(t.flags&2)){t=t.stateNode;break e}}r?Ci(e,t,n):xi(e,t,n)}function Ci(e,n,t){var r=e.tag,l=r===5||r===6;if(l)e=l?e.stateNode:e.stateNode.instance,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=or));else if(r!==4&&(e=e.child,e!==null))for(Ci(e,n,t),e=e.sibling;e!==null;)Ci(e,n,t),e=e.sibling}function xi(e,n,t){var r=e.tag,l=r===5||r===6;if(l)e=l?e.stateNode:e.stateNode.instance,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(xi(e,n,t),e=e.sibling;e!==null;)xi(e,n,t),e=e.sibling}function Ss(e,n){for(var t=n,r=!1,l,i;;){if(!r){r=t.return;e:for(;;){if(r===null)throw Error(v(160));switch(l=r.stateNode,r.tag){case 5:i=!1;break e;case 3:l=l.containerInfo,i=!0;break e;case 4:l=l.containerInfo,i=!0;break e}r=r.return}r=!0}if(t.tag===5||t.tag===6){e:for(var o=e,u=t,s=u;;)if(ys(o,s),s.child!==null&&s.tag!==4)s.child.return=s,s=s.child;else{if(s===u)break e;for(;s.sibling===null;){if(s.return===null||s.return===u)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}i?(o=l,u=t.stateNode,o.nodeType===8?o.parentNode.removeChild(u):o.removeChild(u)):l.removeChild(t.stateNode)}else if(t.tag===4){if(t.child!==null){l=t.stateNode.containerInfo,i=!0,t.child.return=t,t=t.child;continue}}else if(ys(e,t),t.child!==null){t.child.return=t,t=t.child;continue}if(t===n)break;for(;t.sibling===null;){if(t.return===null||t.return===n)return;t=t.return,t.tag===4&&(r=!1)}t.sibling.return=t.return,t=t.sibling}}function Ni(e,n){switch(n.tag){case 0:case 11:case 14:case 15:case 22:var t=n.updateQueue;if(t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do(r.tag&3)==3&&(e=r.destroy,r.destroy=void 0,e!==void 0&&e()),r=r.next;while(r!==t)}return;case 1:return;case 5:if(t=n.stateNode,t!=null){r=n.memoizedProps;var l=e!==null?e.memoizedProps:r;e=n.type;var i=n.updateQueue;if(n.updateQueue=null,i!==null){for(t[sr]=r,e==="input"&&r.type==="radio"&&r.name!=null&&to(t,r),pl(e,l),n=pl(e,r),l=0;ll&&(l=o),t&=~i}if(t=l,t=Z()-t,t=(120>t?120:480>t?480:1080>t?1080:1920>t?1920:3e3>t?3e3:4320>t?4320:1960*hf(t/1960))-t,10 component higher in the tree to provide a loading indicator or placeholder to display.`)}X!==5&&(X=2),s=Ei(s,u),h=o;do{switch(h.tag){case 3:i=s,h.flags|=4096,n&=-n,h.lanes|=n;var N=ps(h,i,n);zu(h,N);break e;case 1:i=s;var w=h.type,E=h.stateNode;if((h.flags&64)==0&&(typeof w.getDerivedStateFromError=="function"||E!==null&&typeof E.componentDidCatch=="function"&&(Se===null||!Se.has(E)))){h.flags|=4096,n&=-n,h.lanes|=n;var z=ms(h,i,n);zu(h,z);break e}}h=h.return}while(h!==null)}Ls(t)}catch(P){n=P,W===t&&t!==null&&(W=t=t.return);continue}break}while(1)}function Ps(){var e=zr.current;return zr.current=Tr,e===null?Tr:e}function Dt(e,n){var t=T;T|=16;var r=Ps();ee===e&&q===n||Vn(e,n);do try{yf();break}catch(l){Ns(e,l)}while(1);if(ti(),T=t,zr.current=r,W!==null)throw Error(v(261));return ee=null,q=0,X}function yf(){for(;W!==null;)Ts(W)}function gf(){for(;W!==null&&!qa();)Ts(W)}function Ts(e){var n=Os(e.alternate,e,fn);e.memoizedProps=e.pendingProps,n===null?Ls(e):W=n,Pi.current=null}function Ls(e){var n=e;do{var t=n.alternate;if(e=n.return,(n.flags&2048)==0){if(t=sf(t,n,fn),t!==null){W=t;return}if(t=n,t.tag!==24&&t.tag!==23||t.memoizedState===null||(fn&1073741824)!=0||(t.mode&4)==0){for(var r=0,l=t.child;l!==null;)r|=l.lanes|l.childLanes,l=l.sibling;t.childLanes=r}e!==null&&(e.flags&2048)==0&&(e.firstEffect===null&&(e.firstEffect=n.firstEffect),n.lastEffect!==null&&(e.lastEffect!==null&&(e.lastEffect.nextEffect=n.firstEffect),e.lastEffect=n.lastEffect),1o&&(u=o,o=N,N=u),u=qo(f,N),i=qo(f,o),u&&i&&(m.rangeCount!==1||m.anchorNode!==u.node||m.anchorOffset!==u.offset||m.focusNode!==i.node||m.focusOffset!==i.offset)&&(p=p.createRange(),p.setStart(u.node,u.offset),m.removeAllRanges(),N>o?(m.addRange(p),m.extend(i.node,i.offset)):(p.setEnd(i.node,i.offset),m.addRange(p)))))),p=[],m=f;m=m.parentNode;)m.nodeType===1&&p.push({element:m,left:m.scrollLeft,top:m.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;fZ()-Mi?Vn(e,0):Li|=t),ce(e,n)}function Cf(e,n){var t=e.stateNode;t!==null&&t.delete(n),n=0,n===0&&(n=e.mode,(n&2)==0?n=1:(n&4)==0?n=zn()===99?1:2:(Pe===0&&(Pe=In),n=kn(62914560&~Pe),n===0&&(n=4194304))),t=oe(),e=Fr(e,n),e!==null&&(qt(e,n,t),ce(e,t))}var Os;Os=function(e,n,t){var r=n.lanes;if(e!==null)if(e.memoizedProps!==n.pendingProps||ne.current)me=!0;else if((t&r)!=0)me=(e.flags&16384)!=0;else{switch(me=!1,n.tag){case 3:rs(n),ai();break;case 5:Uu(n);break;case 1:te(n.type)&&cr(n);break;case 4:oi(n,n.stateNode.containerInfo);break;case 10:r=n.memoizedProps.value;var l=n.type._context;F(mr,l._currentValue),l._currentValue=r;break;case 13:if(n.memoizedState!==null)return(t&n.child.childLanes)!=0?ls(e,n,t):(F(j,j.current&1),n=xe(e,n,t),n!==null?n.sibling:null);F(j,j.current&1);break;case 19:if(r=(t&n.childLanes)!=0,(e.flags&64)!=0){if(r)return as(e,n,t);n.flags|=64}if(l=n.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),F(j,j.current),r)break;return null;case 23:case 24:return n.lanes=0,yi(e,n,t)}return xe(e,n,t)}else me=!1;switch(n.lanes=0,n.tag){case 2:if(r=n.type,e!==null&&(e.alternate=null,n.alternate=null,n.flags|=2),e=n.pendingProps,l=Ln(n,G.current),On(n,t),l=di(null,n,r,e,l,t),n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0){if(n.tag=1,n.memoizedState=null,n.updateQueue=null,te(r)){var i=!0;cr(n)}else i=!1;n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,li(n);var o=r.getDerivedStateFromProps;typeof o=="function"&&yr(n,r,o,e),l.updater=gr,n.stateNode=l,l._reactInternals=n,ii(n,r,e,t),n=wi(null,n,r,!0,i,t)}else n.tag=0,le(null,n,l,t),n=n.child;return n;case 16:l=n.elementType;e:{switch(e!==null&&(e.alternate=null,n.alternate=null,n.flags|=2),e=n.pendingProps,i=l._init,l=i(l._payload),n.type=l,i=n.tag=Nf(l),e=pe(l,e),i){case 0:n=gi(null,n,l,e,t);break e;case 1:n=ts(null,n,l,e,t);break e;case 11:n=qu(null,n,l,e,t);break e;case 14:n=bu(null,n,l,pe(l.type,e),r,t);break e}throw Error(v(306,l,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:pe(r,l),gi(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:pe(r,l),ts(e,n,r,l,t);case 3:if(rs(n),r=n.updateQueue,e===null||r===null)throw Error(v(282));if(r=n.pendingProps,l=n.memoizedState,l=l!==null?l.element:null,Lu(e,n),yt(n,r,null,t),r=n.memoizedState.element,r===l)ai(),n=xe(e,n,t);else{if(l=n.stateNode,(i=l.hydrate)&&(We=xn(n.stateNode.containerInfo.firstChild),Ce=n,i=we=!0),i){if(e=l.mutableSourceEagerHydrationData,e!=null)for(l=0;l-1&&r%1==0&&r<=t}var i=s;function e(r){return r!=null&&i(r.length)&&!n(r)}var o=e;export{i as a,o as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isArrayLikeObject-e565c37f.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isArrayLikeObject-e565c37f.js new file mode 100644 index 0000000000000000000000000000000000000000..b9eb42a1a662139d97671df6ae6f4d0f3d06ba3c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isArrayLikeObject-e565c37f.js @@ -0,0 +1 @@ +import{i as r}from"./isArrayLike-4a96f864.js";import{i as e}from"./isObjectLike-0219adc7.js";function s(i){return e(i)&&r(i)}var a=s;export{a as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObject-d5e189f7.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObject-d5e189f7.js new file mode 100644 index 0000000000000000000000000000000000000000..6b4265c812125fb042489d45d89808cd331bdd42 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObject-d5e189f7.js @@ -0,0 +1 @@ +function n(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var c=n;export{c as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObjectLike-0219adc7.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObjectLike-0219adc7.js new file mode 100644 index 0000000000000000000000000000000000000000..5a7aa74b50e378a1fe12639a26f3dde82e39060e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isObjectLike-0219adc7.js @@ -0,0 +1 @@ +function t(e){return e!=null&&typeof e=="object"}var i=t;export{i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isSymbol-cf06cd7f.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isSymbol-cf06cd7f.js new file mode 100644 index 0000000000000000000000000000000000000000..62c11d8d5e4e8127ecf118dfe65a3b31e6334dd4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/isSymbol-cf06cd7f.js @@ -0,0 +1 @@ +import{a as s}from"./_baseGetTag-3262967e.js";import{i as e}from"./isObjectLike-0219adc7.js";var i="[object Symbol]";function t(o){return typeof o=="symbol"||e(o)&&s(o)==i}var a=t;export{a as i}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/process-2545f00a.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/process-2545f00a.js new file mode 100644 index 0000000000000000000000000000000000000000..3ed3abaa9a81ea2a6f99a9474510d7f2f1faaf32 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/process-2545f00a.js @@ -0,0 +1 @@ +function v(){throw new Error("setTimeout has not been defined")}function d(){throw new Error("clearTimeout has not been defined")}var o=v,i=d,c;typeof window!="undefined"?c=window:typeof self!="undefined"?c=self:c={},typeof c.setTimeout=="function"&&(o=setTimeout),typeof c.clearTimeout=="function"&&(i=clearTimeout);function h(e){if(o===setTimeout)return setTimeout(e,0);if((o===v||!o)&&setTimeout)return o=setTimeout,setTimeout(e,0);try{return o(e,0)}catch(r){try{return o.call(null,e,0)}catch(t){return o.call(this,e,0)}}}function p(e){if(i===clearTimeout)return clearTimeout(e);if((i===d||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{return i(e)}catch(r){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}var n=[],l=!1,a,m=-1;function g(){!l||!a||(l=!1,a.length?n=a.concat(n):m=-1,n.length&&w())}function w(){if(!l){var e=h(g);l=!0;for(var r=n.length;r;){for(a=n,n=[];++m1)for(var t=1;t>8&255]+ct[s>>16&255]+ct[s>>24&255]+"-"+ct[e&255]+ct[e>>8&255]+"-"+ct[e>>16&15|64]+ct[e>>24&255]+"-"+ct[t&63|128]+ct[t>>8&255]+"-"+ct[t>>16&255]+ct[t>>24&255]+ct[n&255]+ct[n>>8&255]+ct[n>>16&255]+ct[n>>24&255]).toUpperCase()}function ut(s,e,t){return Math.max(e,Math.min(t,s))}function za(s,e){return(s%e+e)%e}function bf(s,e,t,n,i){return n+(s-e)*(i-n)/(t-e)}function Mf(s,e,t){return s!==e?(t-s)/(e-s):0}function sr(s,e,t){return(1-t)*s+t*e}function wf(s,e,t,n){return sr(s,e,1-Math.exp(-t*n))}function Sf(s,e=1){return e-Math.abs(za(s,e*2)-e)}function Tf(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*(3-2*s))}function Ef(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*s*(s*(s*6-15)+10))}function Af(s,e){return s+Math.floor(Math.random()*(e-s+1))}function Lf(s,e){return s+Math.random()*(e-s)}function Rf(s){return s*(.5-Math.random())}function Cf(s){return s!==void 0&&(ns=s%2147483647),ns=ns*16807%2147483647,(ns-1)/2147483646}function Pf(s){return s*On}function If(s){return s*rr}function Ua(s){return(s&s-1)==0&&s!==0}function eu(s){return Math.pow(2,Math.ceil(Math.log(s)/Math.LN2))}function tu(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function Df(s,e,t,n,i){const r=Math.cos,a=Math.sin,o=r(t/2),l=a(t/2),c=r((e+n)/2),h=a((e+n)/2),d=r((e-n)/2),u=a((e-n)/2),f=r((n-e)/2),p=a((n-e)/2);switch(i){case"XYX":s.set(o*h,l*d,l*u,o*c);break;case"YZY":s.set(l*u,o*h,l*d,o*c);break;case"ZXZ":s.set(l*d,l*u,o*h,o*c);break;case"XZX":s.set(o*h,l*p,l*f,o*c);break;case"YXY":s.set(l*f,o*h,l*p,o*c);break;case"ZYZ":s.set(l*p,l*f,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}var Ff=Object.freeze({__proto__:null,DEG2RAD:On,RAD2DEG:rr,generateUUID:bt,clamp:ut,euclideanModulo:za,mapLinear:bf,inverseLerp:Mf,lerp:sr,damp:wf,pingpong:Sf,smoothstep:Tf,smootherstep:Ef,randInt:Af,randFloat:Lf,randFloatSpread:Rf,seededRandom:Cf,degToRad:Pf,radToDeg:If,isPowerOfTwo:Ua,ceilPowerOfTwo:eu,floorPowerOfTwo:tu,setQuaternionFromProperEuler:Df});class Y{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e,t){return t!==void 0?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this)}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e,t){return t!==void 0?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this)}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t,n){return n!==void 0&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*i+e.x,this.y=r*i+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}}Y.prototype.isVector2=!0;class et{constructor(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}set(e,t,n,i,r,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=r,h[5]=l,h[6]=n,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,a=n[0],o=n[3],l=n[6],c=n[1],h=n[4],d=n[7],u=n[2],f=n[5],p=n[8],x=i[0],y=i[3],g=i[6],m=i[1],_=i[4],v=i[7],T=i[2],A=i[5],b=i[8];return r[0]=a*x+o*m+l*T,r[3]=a*y+o*_+l*A,r[6]=a*g+o*v+l*b,r[1]=c*x+h*m+d*T,r[4]=c*y+h*_+d*A,r[7]=c*g+h*v+d*b,r[2]=u*x+f*m+p*T,r[5]=u*y+f*_+p*A,r[8]=u*g+f*v+p*b,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-n*r*h+n*o*l+i*r*c-i*a*l}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=h*a-o*c,u=o*l-h*r,f=c*r-a*l,p=t*d+n*u+i*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const x=1/p;return e[0]=d*x,e[1]=(i*c-h*n)*x,e[2]=(o*n-i*a)*x,e[3]=u*x,e[4]=(h*t-i*l)*x,e[5]=(i*r-o*t)*x,e[6]=f*x,e[7]=(n*l-c*t)*x,e[8]=(a*t-n*r)*x,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,a,o){const l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*a+c*o)+a+e,-i*c,i*l,-i*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=t,n[4]*=t,n[7]*=t,this}rotate(e){const t=Math.cos(e),n=Math.sin(e),i=this.elements,r=i[0],a=i[3],o=i[6],l=i[1],c=i[4],h=i[7];return i[0]=t*r+n*l,i[3]=t*a+n*c,i[6]=t*o+n*h,i[1]=-n*r+t*l,i[4]=-n*a+t*c,i[7]=-n*o+t*h,this}translate(e,t){const n=this.elements;return n[0]+=e*n[2],n[3]+=e*n[5],n[6]+=e*n[8],n[1]+=t*n[2],n[4]+=t*n[5],n[7]+=t*n[8],this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}et.prototype.isMatrix3=!0;let fi;class Hn{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement=="undefined")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{fi===void 0&&(fi=document.createElementNS("http://www.w3.org/1999/xhtml","canvas")),fi.width=e.width,fi.height=e.height;const n=fi.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=fi}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}}let Bf=0;class tt extends cn{constructor(e=tt.DEFAULT_IMAGE,t=tt.DEFAULT_MAPPING,n=lt,i=lt,r=Ke,a=In,o=xt,l=Dn,c=1,h=yt){super();Object.defineProperty(this,"id",{value:Bf++}),this.uuid=bt(),this.name="",this.image=e,this.mipmaps=[],this.mapping=t,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new et,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=h,this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.image=e.image,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.encoding=e.encoding,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(this.image!==void 0){const i=this.image;if(i.uuid===void 0&&(i.uuid=bt()),!t&&e.images[i.uuid]===void 0){let r;if(Array.isArray(i)){r=[];for(let a=0,o=i.length;a1)switch(this.wrapS){case $i:e.x=e.x-Math.floor(e.x);break;case lt:e.x=e.x<0?0:1;break;case Qi:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case $i:e.y=e.y-Math.floor(e.y);break;case lt:e.y=e.y<0?0:1;break;case Qi:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&this.version++}}tt.DEFAULT_IMAGE=void 0,tt.DEFAULT_MAPPING=Jr,tt.prototype.isTexture=!0;function Oa(s){return typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&s instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&s instanceof ImageBitmap?Hn.getDataURL(s):s.data?{data:Array.prototype.slice.call(s.data),width:s.width,height:s.height,type:s.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}class Oe{constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e,t){return t!==void 0?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e,t){return t!==void 0?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*i+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*i+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*i+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*i+a[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const a=.01,o=.1,l=e.elements,c=l[0],h=l[4],d=l[8],u=l[1],f=l[5],p=l[9],x=l[2],y=l[6],g=l[10];if(Math.abs(h-u)v&&_>T?_T?v=0?1:-1,_=1-g*g;if(_>Number.EPSILON){const T=Math.sqrt(_),A=Math.atan2(T,g*m);y=Math.sin(y*A)/T,o=Math.sin(o*A)/T}const v=o*m;if(l=l*y+u*v,c=c*y+f*v,h=h*y+p*v,d=d*y+x*v,y===1-o){const T=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=T,c*=T,h*=T,d*=T}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=d}static multiplyQuaternionsFlat(e,t,n,i,r,a){const o=n[i],l=n[i+1],c=n[i+2],h=n[i+3],d=r[a],u=r[a+1],f=r[a+2],p=r[a+3];return e[t]=o*p+h*d+l*f-c*u,e[t+1]=l*p+h*u+c*d-o*f,e[t+2]=c*p+h*f+o*u-l*d,e[t+3]=h*p-o*d-l*u-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t){if(!(e&&e.isEuler))throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");const n=e._x,i=e._y,r=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(n/2),h=o(i/2),d=o(r/2),u=l(n/2),f=l(i/2),p=l(r/2);switch(a){case"XYZ":this._x=u*h*d+c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d-u*f*p;break;case"YXZ":this._x=u*h*d+c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d+u*f*p;break;case"ZXY":this._x=u*h*d-c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d-u*f*p;break;case"ZYX":this._x=u*h*d-c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d+u*f*p;break;case"YZX":this._x=u*h*d+c*f*p,this._y=c*f*d+u*h*p,this._z=c*h*p-u*f*d,this._w=c*h*d-u*f*p;break;case"XZY":this._x=u*h*d-c*f*p,this._y=c*f*d-u*h*p,this._z=c*h*p+u*f*d,this._w=c*h*d+u*f*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t!==!1&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],d=t[10],u=n+o+d;if(u>0){const f=.5/Math.sqrt(u+1);this._w=.25/f,this._x=(h-l)*f,this._y=(r-c)*f,this._z=(a-i)*f}else if(n>o&&n>d){const f=2*Math.sqrt(1+n-o-d);this._w=(h-l)/f,this._x=.25*f,this._y=(i+a)/f,this._z=(r+c)/f}else if(o>d){const f=2*Math.sqrt(1+o-n-d);this._w=(r-c)/f,this._x=(i+a)/f,this._y=.25*f,this._z=(l+h)/f}else{const f=2*Math.sqrt(1+d-n-o);this._w=(a-i)/f,this._x=(r+c)/f,this._y=(l+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(ut(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e,t){return t!==void 0?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(e,t)):this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=n*h+a*o+i*c-r*l,this._y=i*h+a*l+r*o-n*c,this._z=r*h+a*c+n*l-i*o,this._w=a*h-n*o-i*l-r*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const n=this._x,i=this._y,r=this._z,a=this._w;let o=a*e._w+n*e._x+i*e._y+r*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=i,this._z=r,this;const l=1-o*o;if(l<=Number.EPSILON){const f=1-t;return this._w=f*a+t*this._w,this._x=f*n+t*this._x,this._y=f*i+t*this._y,this._z=f*r+t*this._z,this.normalize(),this._onChangeCallback(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),d=Math.sin((1-t)*h)/c,u=Math.sin(t*h)/c;return this._w=a*d+this._w*u,this._x=n*d+this._x*u,this._y=i*d+this._y*u,this._z=r*d+this._z*u,this._onChangeCallback(),this}slerpQuaternions(e,t,n){this.copy(e).slerp(t,n)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}ht.prototype.isQuaternion=!0;class M{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e,t){return t!==void 0?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(e,t)):(this.x+=e.x,this.y+=e.y,this.z+=e.z,this)}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e,t){return t!==void 0?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(e,t)):(this.x-=e.x,this.y-=e.y,this.z-=e.z,this)}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e,t){return t!==void 0?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(e,t)):(this.x*=e.x,this.y*=e.y,this.z*=e.z,this)}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(iu.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(iu.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,a=e.y,o=e.z,l=e.w,c=l*t+a*i-o*n,h=l*n+o*t-r*i,d=l*i+r*n-a*t,u=-r*t-a*n-o*i;return this.x=c*l+u*-r+h*-o-d*-a,this.y=h*l+u*-a+d*-r-c*-o,this.z=d*l+u*-o+c*-a-h*-r,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e,t){return t!==void 0?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(e,t)):this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,a=t.x,o=t.y,l=t.z;return this.x=i*l-r*o,this.y=r*a-n*l,this.z=n*o-i*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Ga.copy(this).projectOnVector(e),this.sub(Ga)}reflect(e){return this.sub(Ga.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(ut(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t,n){return n!==void 0&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}}M.prototype.isVector3=!0;const Ga=new M,iu=new ht;class Mt{constructor(e=new M(Infinity,Infinity,Infinity),t=new M(-Infinity,-Infinity,-Infinity)){this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){let t=Infinity,n=Infinity,i=Infinity,r=-Infinity,a=-Infinity,o=-Infinity;for(let l=0,c=e.length;lr&&(r=h),d>a&&(a=d),u>o&&(o=u)}return this.min.set(t,n,i),this.max.set(r,a,o),this}setFromBufferAttribute(e){let t=Infinity,n=Infinity,i=Infinity,r=-Infinity,a=-Infinity,o=-Infinity;for(let l=0,c=e.count;lr&&(r=h),d>a&&(a=d),u>o&&(o=u)}return this.min.set(t,n,i),this.max.set(r,a,o),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,ar),ar.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(or),is.subVectors(this.max,or),pi.subVectors(e.a,or),mi.subVectors(e.b,or),gi.subVectors(e.c,or),un.subVectors(mi,pi),hn.subVectors(gi,mi),Gn.subVectors(pi,gi);let t=[0,-un.z,un.y,0,-hn.z,hn.y,0,-Gn.z,Gn.y,un.z,0,-un.x,hn.z,0,-hn.x,Gn.z,0,-Gn.x,-un.y,un.x,0,-hn.y,hn.x,0,-Gn.y,Gn.x,0];return!Va(t,pi,mi,gi,is)||(t=[1,0,0,0,1,0,0,0,1],!Va(t,pi,mi,gi,is))?!1:(rs.crossVectors(un,hn),t=[rs.x,rs.y,rs.z],Va(t,pi,mi,gi,is))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return ar.copy(e).clamp(this.min,this.max).sub(e).length()}getBoundingSphere(e){return this.getCenter(e.center),e.radius=this.getSize(ar).length()*.5,e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Jt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Jt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Jt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Jt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Jt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Jt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Jt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Jt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Jt),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}Mt.prototype.isBox3=!0;const Jt=[new M,new M,new M,new M,new M,new M,new M,new M],ar=new M,ka=new Mt,pi=new M,mi=new M,gi=new M,un=new M,hn=new M,Gn=new M,or=new M,is=new M,rs=new M,kn=new M;function Va(s,e,t,n,i){for(let r=0,a=s.length-3;r<=a;r+=3){kn.fromArray(s,r);const o=i.x*Math.abs(kn.x)+i.y*Math.abs(kn.y)+i.z*Math.abs(kn.z),l=e.dot(kn),c=t.dot(kn),h=n.dot(kn);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const Nf=new Mt,ru=new M,Wa=new M,qa=new M;class dn{constructor(e=new M,t=-1){this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):Nf.setFromPoints(e).getCenter(n);let i=0;for(let r=0,a=e.length;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){qa.subVectors(e,this.center);const t=qa.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.add(qa.multiplyScalar(i/n)),this.radius+=i}return this}union(e){return Wa.subVectors(e.center,this.center).normalize().multiplyScalar(e.radius),this.expandByPoint(ru.copy(e.center).add(Wa)),this.expandByPoint(ru.copy(e.center).sub(Wa)),this}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const Zt=new M,Xa=new M,ss=new M,fn=new M,Ya=new M,as=new M,Ja=new M;class pn{constructor(e=new M,t=new M(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.direction).multiplyScalar(e).add(this.origin)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Zt)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.direction).multiplyScalar(n).add(this.origin)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Zt.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Zt.copy(this.direction).multiplyScalar(t).add(this.origin),Zt.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Xa.copy(e).add(t).multiplyScalar(.5),ss.copy(t).sub(e).normalize(),fn.copy(this.origin).sub(Xa);const r=e.distanceTo(t)*.5,a=-this.direction.dot(ss),o=fn.dot(this.direction),l=-fn.dot(ss),c=fn.lengthSq(),h=Math.abs(1-a*a);let d,u,f,p;if(h>0)if(d=a*l-o,u=a*o-l,p=r*h,d>=0)if(u>=-p)if(u<=p){const x=1/h;d*=x,u*=x,f=d*(d+a*u+2*o)+u*(a*d+u+2*l)+c}else u=r,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;else u=-r,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;else u<=-p?(d=Math.max(0,-(-a*r+o)),u=d>0?-r:Math.min(Math.max(-r,-l),r),f=-d*d+u*(u+2*l)+c):u<=p?(d=0,u=Math.min(Math.max(-r,-l),r),f=u*(u+2*l)+c):(d=Math.max(0,-(a*r+o)),u=d>0?r:Math.min(Math.max(-r,-l),r),f=-d*d+u*(u+2*l)+c);else u=a>0?-r:r,d=Math.max(0,-(a*u+o)),f=-d*d+u*(u+2*l)+c;return n&&n.copy(this.direction).multiplyScalar(d).add(this.origin),i&&i.copy(ss).multiplyScalar(u).add(Xa),f}intersectSphere(e,t){Zt.subVectors(e.center,this.origin);const n=Zt.dot(this.direction),i=Zt.dot(Zt)-n*n,r=e.radius*e.radius;if(i>r)return null;const a=Math.sqrt(r-i),o=n-a,l=n+a;return o<0&&l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(n=(e.min.x-u.x)*c,i=(e.max.x-u.x)*c):(n=(e.max.x-u.x)*c,i=(e.min.x-u.x)*c),h>=0?(r=(e.min.y-u.y)*h,a=(e.max.y-u.y)*h):(r=(e.max.y-u.y)*h,a=(e.min.y-u.y)*h),n>a||r>i||((r>n||n!==n)&&(n=r),(a=0?(o=(e.min.z-u.z)*d,l=(e.max.z-u.z)*d):(o=(e.max.z-u.z)*d,l=(e.min.z-u.z)*d),n>l||o>i)||((o>n||n!==n)&&(n=o),(l=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,Zt)!==null}intersectTriangle(e,t,n,i,r){Ya.subVectors(t,e),as.subVectors(n,e),Ja.crossVectors(Ya,as);let a=this.direction.dot(Ja),o;if(a>0){if(i)return null;o=1}else if(a<0)o=-1,a=-a;else return null;fn.subVectors(this.origin,e);const l=o*this.direction.dot(as.crossVectors(fn,as));if(l<0)return null;const c=o*this.direction.dot(Ya.cross(fn));if(c<0||l+c>a)return null;const h=-o*fn.dot(Ja);return h<0?null:this.at(h/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class he{constructor(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}set(e,t,n,i,r,a,o,l,c,h,d,u,f,p,x,y){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=a,g[9]=o,g[13]=l,g[2]=c,g[6]=h,g[10]=d,g[14]=u,g[3]=f,g[7]=p,g[11]=x,g[15]=y,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new he().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/xi.setFromMatrixColumn(e,0).length(),r=1/xi.setFromMatrixColumn(e,1).length(),a=1/xi.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");const t=this.elements,n=e.x,i=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),l=Math.cos(i),c=Math.sin(i),h=Math.cos(r),d=Math.sin(r);if(e.order==="XYZ"){const u=a*h,f=a*d,p=o*h,x=o*d;t[0]=l*h,t[4]=-l*d,t[8]=c,t[1]=f+p*c,t[5]=u-x*c,t[9]=-o*l,t[2]=x-u*c,t[6]=p+f*c,t[10]=a*l}else if(e.order==="YXZ"){const u=l*h,f=l*d,p=c*h,x=c*d;t[0]=u+x*o,t[4]=p*o-f,t[8]=a*c,t[1]=a*d,t[5]=a*h,t[9]=-o,t[2]=f*o-p,t[6]=x+u*o,t[10]=a*l}else if(e.order==="ZXY"){const u=l*h,f=l*d,p=c*h,x=c*d;t[0]=u-x*o,t[4]=-a*d,t[8]=p+f*o,t[1]=f+p*o,t[5]=a*h,t[9]=x-u*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const u=a*h,f=a*d,p=o*h,x=o*d;t[0]=l*h,t[4]=p*c-f,t[8]=u*c+x,t[1]=l*d,t[5]=x*c+u,t[9]=f*c-p,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const u=a*l,f=a*c,p=o*l,x=o*c;t[0]=l*h,t[4]=x-u*d,t[8]=p*d+f,t[1]=d,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=f*d+p,t[10]=u-x*d}else if(e.order==="XZY"){const u=a*l,f=a*c,p=o*l,x=o*c;t[0]=l*h,t[4]=-d,t[8]=c*h,t[1]=u*d+x,t[5]=a*h,t[9]=f*d-p,t[2]=p*d-f,t[6]=o*h,t[10]=x*d+u}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(zf,e,Uf)}lookAt(e,t,n){const i=this.elements;return wt.subVectors(e,t),wt.lengthSq()===0&&(wt.z=1),wt.normalize(),mn.crossVectors(n,wt),mn.lengthSq()===0&&(Math.abs(n.z)===1?wt.x+=1e-4:wt.z+=1e-4,wt.normalize(),mn.crossVectors(n,wt)),mn.normalize(),os.crossVectors(wt,mn),i[0]=mn.x,i[4]=os.x,i[8]=wt.x,i[1]=mn.y,i[5]=os.y,i[9]=wt.y,i[2]=mn.z,i[6]=os.z,i[10]=wt.z,this}multiply(e,t){return t!==void 0?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(e,t)):this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,a=n[0],o=n[4],l=n[8],c=n[12],h=n[1],d=n[5],u=n[9],f=n[13],p=n[2],x=n[6],y=n[10],g=n[14],m=n[3],_=n[7],v=n[11],T=n[15],A=i[0],b=i[4],L=i[8],N=i[12],P=i[1],R=i[5],J=i[9],B=i[13],F=i[2],G=i[6],z=i[10],k=i[14],j=i[3],ue=i[7],ye=i[11],se=i[15];return r[0]=a*A+o*P+l*F+c*j,r[4]=a*b+o*R+l*G+c*ue,r[8]=a*L+o*J+l*z+c*ye,r[12]=a*N+o*B+l*k+c*se,r[1]=h*A+d*P+u*F+f*j,r[5]=h*b+d*R+u*G+f*ue,r[9]=h*L+d*J+u*z+f*ye,r[13]=h*N+d*B+u*k+f*se,r[2]=p*A+x*P+y*F+g*j,r[6]=p*b+x*R+y*G+g*ue,r[10]=p*L+x*J+y*z+g*ye,r[14]=p*N+x*B+y*k+g*se,r[3]=m*A+_*P+v*F+T*j,r[7]=m*b+_*R+v*G+T*ue,r[11]=m*L+_*J+v*z+T*ye,r[15]=m*N+_*B+v*k+T*se,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],d=e[6],u=e[10],f=e[14],p=e[3],x=e[7],y=e[11],g=e[15];return p*(+r*l*d-i*c*d-r*o*u+n*c*u+i*o*f-n*l*f)+x*(+t*l*f-t*c*u+r*a*u-i*a*f+i*c*h-r*l*h)+y*(+t*c*d-t*o*f-r*a*d+n*a*f+r*o*h-n*c*h)+g*(-i*o*h-t*l*d+t*o*u+i*a*d-n*a*u+n*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],d=e[9],u=e[10],f=e[11],p=e[12],x=e[13],y=e[14],g=e[15],m=d*y*c-x*u*c+x*l*f-o*y*f-d*l*g+o*u*g,_=p*u*c-h*y*c-p*l*f+a*y*f+h*l*g-a*u*g,v=h*x*c-p*d*c+p*o*f-a*x*f-h*o*g+a*d*g,T=p*d*l-h*x*l-p*o*u+a*x*u+h*o*y-a*d*y,A=t*m+n*_+i*v+r*T;if(A===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const b=1/A;return e[0]=m*b,e[1]=(x*u*r-d*y*r-x*i*f+n*y*f+d*i*g-n*u*g)*b,e[2]=(o*y*r-x*l*r+x*i*c-n*y*c-o*i*g+n*l*g)*b,e[3]=(d*l*r-o*u*r-d*i*c+n*u*c+o*i*f-n*l*f)*b,e[4]=_*b,e[5]=(h*y*r-p*u*r+p*i*f-t*y*f-h*i*g+t*u*g)*b,e[6]=(p*l*r-a*y*r-p*i*c+t*y*c+a*i*g-t*l*g)*b,e[7]=(a*u*r-h*l*r+h*i*c-t*u*c-a*i*f+t*l*f)*b,e[8]=v*b,e[9]=(p*d*r-h*x*r-p*n*f+t*x*f+h*n*g-t*d*g)*b,e[10]=(a*x*r-p*o*r+p*n*c-t*x*c-a*n*g+t*o*g)*b,e[11]=(h*o*r-a*d*r-h*n*c+t*d*c+a*n*f-t*o*f)*b,e[12]=T*b,e[13]=(h*x*i-p*d*i+p*n*u-t*x*u-h*n*y+t*d*y)*b,e[14]=(p*o*i-a*x*i-p*n*l+t*x*l+a*n*y-t*o*y)*b,e[15]=(a*d*i-h*o*i+h*n*l-t*d*l-a*n*u+t*o*u)*b,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,a=e.x,o=e.y,l=e.z,c=r*a,h=r*o;return this.set(c*a+n,c*o-i*l,c*l+i*o,0,c*o+i*l,h*o+n,h*l-i*a,0,c*l-i*o,h*l+i*a,r*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,a){return this.set(1,n,r,0,e,1,a,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,a=t._y,o=t._z,l=t._w,c=r+r,h=a+a,d=o+o,u=r*c,f=r*h,p=r*d,x=a*h,y=a*d,g=o*d,m=l*c,_=l*h,v=l*d,T=n.x,A=n.y,b=n.z;return i[0]=(1-(x+g))*T,i[1]=(f+v)*T,i[2]=(p-_)*T,i[3]=0,i[4]=(f-v)*A,i[5]=(1-(u+g))*A,i[6]=(y+m)*A,i[7]=0,i[8]=(p+_)*b,i[9]=(y-m)*b,i[10]=(1-(u+x))*b,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=xi.set(i[0],i[1],i[2]).length();const a=xi.set(i[4],i[5],i[6]).length(),o=xi.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Rt.copy(this);const c=1/r,h=1/a,d=1/o;return Rt.elements[0]*=c,Rt.elements[1]*=c,Rt.elements[2]*=c,Rt.elements[4]*=h,Rt.elements[5]*=h,Rt.elements[6]*=h,Rt.elements[8]*=d,Rt.elements[9]*=d,Rt.elements[10]*=d,t.setFromRotationMatrix(Rt),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,a){a===void 0&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");const o=this.elements,l=2*r/(t-e),c=2*r/(n-i),h=(t+e)/(t-e),d=(n+i)/(n-i),u=-(a+r)/(a-r),f=-2*a*r/(a-r);return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=d,o[13]=0,o[2]=0,o[6]=0,o[10]=u,o[14]=f,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,i,r,a){const o=this.elements,l=1/(t-e),c=1/(n-i),h=1/(a-r),d=(t+e)*l,u=(n+i)*c,f=(a+r)*h;return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-d,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-u,o[2]=0,o[6]=0,o[10]=-2*h,o[14]=-f,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}he.prototype.isMatrix4=!0;const xi=new M,Rt=new he,zf=new M(0,0,0),Uf=new M(1,1,1),mn=new M,os=new M,wt=new M,su=new he,au=new ht;class Vn{constructor(e=0,t=0,n=0,i=Vn.DefaultOrder){this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],a=i[4],o=i[8],l=i[1],c=i[5],h=i[9],d=i[2],u=i[6],f=i[10];switch(t){case"XYZ":this._y=Math.asin(ut(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(u,c),this._z=0);break;case"YXZ":this._x=Math.asin(-ut(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,r),this._z=0);break;case"ZXY":this._x=Math.asin(ut(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-d,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-ut(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(u,f),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(ut(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-d,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-ut(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(u,c),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return su.makeRotationFromQuaternion(e),this.setFromRotationMatrix(su,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return au.setFromEuler(this),this.setFromQuaternion(au,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}toVector3(e){return e?e.set(this._x,this._y,this._z):new M(this._x,this._y,this._z)}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}}Vn.prototype.isEuler=!0,Vn.DefaultOrder="XYZ",Vn.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];class Za{constructor(){this.mask=1|0}set(e){this.mask=1<1){for(let t=0;t1){for(let n=0;n0){i.children=[];for(let o=0;o0){i.animations=[];for(let o=0;o0&&(n.geometries=o),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),u.length>0&&(n.skeletons=u),f.length>0&&(n.animations=f)}return n.object=i,n;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Ct.subVectors(i,t),Qt.subVectors(n,t),$a.subVectors(e,t);const a=Ct.dot(Ct),o=Ct.dot(Qt),l=Ct.dot($a),c=Qt.dot(Qt),h=Qt.dot($a),d=a*c-o*o;if(d===0)return r.set(-2,-1,-1);const u=1/d,f=(c*l-o*h)*u,p=(a*h-o*l)*u;return r.set(1-f-p,p,f)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,jt),jt.x>=0&&jt.y>=0&&jt.x+jt.y<=1}static getUV(e,t,n,i,r,a,o,l){return this.getBarycoord(e,t,n,i,jt),l.set(0,0),l.addScaledVector(r,jt.x),l.addScaledVector(a,jt.y),l.addScaledVector(o,jt.z),l}static isFrontFacing(e,t,n,i){return Ct.subVectors(n,t),Qt.subVectors(e,t),Ct.cross(Qt).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ct.subVectors(this.c,this.b),Qt.subVectors(this.a,this.b),Ct.cross(Qt).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Ye.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Ye.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,n,i,r){return Ye.getUV(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Ye.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Ye.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let a,o;vi.subVectors(i,n),_i.subVectors(r,n),Qa.subVectors(e,n);const l=vi.dot(Qa),c=_i.dot(Qa);if(l<=0&&c<=0)return t.copy(n);ja.subVectors(e,i);const h=vi.dot(ja),d=_i.dot(ja);if(h>=0&&d<=h)return t.copy(i);const u=l*d-h*c;if(u<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(n).addScaledVector(vi,a);Ka.subVectors(e,r);const f=vi.dot(Ka),p=_i.dot(Ka);if(p>=0&&f<=p)return t.copy(r);const x=f*c-l*p;if(x<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(_i,o);const y=h*p-f*d;if(y<=0&&d-h>=0&&f-p>=0)return du.subVectors(r,i),o=(d-h)/(d-h+(f-p)),t.copy(i).addScaledVector(du,o);const g=1/(y+x+u);return a=x*g,o=u*g,t.copy(n).addScaledVector(vi,a).addScaledVector(_i,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}let Vf=0;class it extends cn{constructor(){super();Object.defineProperty(this,"id",{value:Vf++}),this.uuid=bt(),this.name="",this.type="Material",this.fog=!0,this.blending=si,this.side=Rn,this.vertexColors=!1,this.opacity=1,this.format=xt,this.transparent=!1,this.blendSrc=va,this.blendDst=_a,this.blendEquation=Pn,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=Yr,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Kc,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ts,this.stencilZFail=ts,this.stencilZPass=ts,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){console.warn("THREE.Material: '"+t+"' parameter is undefined.");continue}if(t==="shading"){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=n===fa;continue}const i=this[t];if(i===void 0){console.warn("THREE."+this.type+": '"+t+"' is not a property of this material.");continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheenTint&&this.sheenTint.isColor&&(n.sheenTint=this.sheenTint.getHex()),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularTint&&this.specularTint.isColor&&(n.specularTint=this.specularTint.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularTintMap&&this.specularTintMap.isTexture&&(n.specularTintMap=this.specularTintMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationTint!==void 0&&(n.attenuationTint=this.attenuationTint.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==si&&(n.blending=this.blending),this.side!==Rn&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.format!==xt&&(n.format=this.format),this.transparent===!0&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaToCoverage===!0&&(n.alphaToCoverage=this.alphaToCoverage),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=this.flatShading),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),JSON.stringify(this.userData)!=="{}"&&(n.userData=this.userData);function i(r){const a=[];for(const o in r){const l=r[o];delete l.metadata,a.push(l)}return a}if(t){const r=i(e.textures),a=i(e.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.fog=e.fog,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.format=e.format,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const i=t.length;n=new Array(i);for(let r=0;r!==i;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}it.prototype.isMaterial=!0;const fu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Pt={h:0,s:0,l:0},cs={h:0,s:0,l:0};function eo(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}function to(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function no(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}class te{constructor(e,t,n){return t===void 0&&n===void 0?this.set(e):this.setRGB(e,t,n)}set(e){return e&&e.isColor?this.copy(e):typeof e=="number"?this.setHex(e):typeof e=="string"&&this.setStyle(e),this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,this}setRGB(e,t,n){return this.r=e,this.g=t,this.b=n,this}setHSL(e,t,n){if(e=za(e,1),t=ut(t,0,1),n=ut(n,0,1),t===0)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=eo(r,i,e+1/3),this.g=eo(r,i,e),this.b=eo(r,i,e-1/3)}return this}setStyle(e){function t(i){i!==void 0&&parseFloat(i)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(e)){let i;const r=n[1],a=n[2];switch(r){case"rgb":case"rgba":if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.r=Math.min(255,parseInt(i[1],10))/255,this.g=Math.min(255,parseInt(i[2],10))/255,this.b=Math.min(255,parseInt(i[3],10))/255,t(i[4]),this;if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return this.r=Math.min(100,parseInt(i[1],10))/100,this.g=Math.min(100,parseInt(i[2],10))/100,this.b=Math.min(100,parseInt(i[3],10))/100,t(i[4]),this;break;case"hsl":case"hsla":if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a)){const o=parseFloat(i[1])/360,l=parseInt(i[2],10)/100,c=parseInt(i[3],10)/100;return t(i[4]),this.setHSL(o,l,c)}break}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const i=n[1],r=i.length;if(r===3)return this.r=parseInt(i.charAt(0)+i.charAt(0),16)/255,this.g=parseInt(i.charAt(1)+i.charAt(1),16)/255,this.b=parseInt(i.charAt(2)+i.charAt(2),16)/255,this;if(r===6)return this.r=parseInt(i.charAt(0)+i.charAt(1),16)/255,this.g=parseInt(i.charAt(2)+i.charAt(3),16)/255,this.b=parseInt(i.charAt(4)+i.charAt(5),16)/255,this}return e&&e.length>0?this.setColorName(e):this}setColorName(e){const t=fu[e.toLowerCase()];return t!==void 0?this.setHex(t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyGammaToLinear(e,t=2){return this.r=Math.pow(e.r,t),this.g=Math.pow(e.g,t),this.b=Math.pow(e.b,t),this}copyLinearToGamma(e,t=2){const n=t>0?1/t:1;return this.r=Math.pow(e.r,n),this.g=Math.pow(e.g,n),this.b=Math.pow(e.b,n),this}convertGammaToLinear(e){return this.copyGammaToLinear(this,e),this}convertLinearToGamma(e){return this.copyLinearToGamma(this,e),this}copySRGBToLinear(e){return this.r=to(e.r),this.g=to(e.g),this.b=to(e.b),this}copyLinearToSRGB(e){return this.r=no(e.r),this.g=no(e.g),this.b=no(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0}getHexString(){return("000000"+this.getHex().toString(16)).slice(-6)}getHSL(e){const t=this.r,n=this.g,i=this.b,r=Math.max(t,n,i),a=Math.min(t,n,i);let o,l;const c=(a+r)/2;if(a===r)o=0,l=0;else{const h=r-a;switch(l=c<=.5?h/(r+a):h/(2-r-a),r){case t:o=(n-i)/h+(ne&&(e=s[t]);return e}const Wf={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function bi(s,e){return new Wf[s](e)}let qf=0;const Et=new he,io=new Ce,Mi=new M,St=new Mt,cr=new Mt,rt=new M;class _e extends cn{constructor(){super();Object.defineProperty(this,"id",{value:qf++}),this.uuid=bt(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:Infinity},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(bu(e)>65535?ds:hs)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new et().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Et.makeRotationFromQuaternion(e),this.applyMatrix4(Et),this}rotateX(e){return Et.makeRotationX(e),this.applyMatrix4(Et),this}rotateY(e){return Et.makeRotationY(e),this.applyMatrix4(Et),this}rotateZ(e){return Et.makeRotationZ(e),this.applyMatrix4(Et),this}translate(e,t,n){return Et.makeTranslation(e,t,n),this.applyMatrix4(Et),this}scale(e,t,n){return Et.makeScale(e,t,n),this.applyMatrix4(Et),this}lookAt(e){return io.lookAt(e),io.updateMatrix(),this.applyMatrix4(io.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Mi).negate(),this.translate(Mi.x,Mi.y,Mi.z),this}setFromPoints(e){const t=[];for(let n=0,i=e.length;n0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const l in n){const c=n[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let r=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let d=0,u=c.length;d0&&(i[l]=h,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new _e().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone(t));const i=e.attributes;for(const c in i){const h=i[c];this.setAttribute(c,h.clone(t))}const r=e.morphAttributes;for(const c in r){const h=[],d=r[c];for(let u=0,f=d.length;u0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r0&&console.error("THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}}raycast(e,t){const n=this.geometry,i=this.material,r=this.matrixWorld;if(i===void 0||(n.boundingSphere===null&&n.computeBoundingSphere(),ro.copy(n.boundingSphere),ro.applyMatrix4(r),e.ray.intersectsSphere(ro)===!1)||(Mu.copy(r).invert(),wi.copy(e.ray).applyMatrix4(Mu),n.boundingBox!==null&&wi.intersectsBox(n.boundingBox)===!1))return;let a;if(n.isBufferGeometry){const o=n.index,l=n.attributes.position,c=n.morphAttributes.position,h=n.morphTargetsRelative,d=n.attributes.uv,u=n.attributes.uv2,f=n.groups,p=n.drawRange;if(o!==null)if(Array.isArray(i))for(let x=0,y=f.length;xt.far?null:{distance:c,point:vs.clone(),object:s}}function _s(s,e,t,n,i,r,a,o,l,c,h,d){gn.fromBufferAttribute(i,c),xn.fromBufferAttribute(i,h),yn.fromBufferAttribute(i,d);const u=s.morphTargetInfluences;if(r&&u){fs.set(0,0,0),ps.set(0,0,0),ms.set(0,0,0);for(let p=0,x=r.length;p0?1:-1,h.push(ue.x,ue.y,ue.z),d.push(Ee/b),d.push(1-ye/L),k+=1}}for(let ye=0;ye0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader;const n={};for(const i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}en.prototype.isShaderMaterial=!0;class ur extends Ce{constructor(){super();this.type="Camera",this.matrixWorldInverse=new he,this.projectionMatrix=new he,this.projectionMatrixInverse=new he}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(-t[8],-t[9],-t[10]).normalize()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}ur.prototype.isCamera=!0;class st extends ur{constructor(e=50,t=1,n=.1,i=2e3){super();this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=rr*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(On*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return rr*2*Math.atan(Math.tan(On*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,n,i,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(On*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const a=this.view;if(this.view!==null&&this.view.enabled){const l=a.fullWidth,c=a.fullHeight;r+=a.offsetX*i/l,t-=a.offsetY*n/c,i*=a.width/l,n*=a.height/c}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}st.prototype.isPerspectiveCamera=!0;const Ti=90,Ei=1;class bs extends Ce{constructor(e,t,n){super();if(this.type="CubeCamera",n.isWebGLCubeRenderTarget!==!0){console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");return}this.renderTarget=n;const i=new st(Ti,Ei,e,t);i.layers=this.layers,i.up.set(0,-1,0),i.lookAt(new M(1,0,0)),this.add(i);const r=new st(Ti,Ei,e,t);r.layers=this.layers,r.up.set(0,-1,0),r.lookAt(new M(-1,0,0)),this.add(r);const a=new st(Ti,Ei,e,t);a.layers=this.layers,a.up.set(0,0,1),a.lookAt(new M(0,1,0)),this.add(a);const o=new st(Ti,Ei,e,t);o.layers=this.layers,o.up.set(0,0,-1),o.lookAt(new M(0,-1,0)),this.add(o);const l=new st(Ti,Ei,e,t);l.layers=this.layers,l.up.set(0,-1,0),l.lookAt(new M(0,0,1)),this.add(l);const c=new st(Ti,Ei,e,t);c.layers=this.layers,c.up.set(0,-1,0),c.lookAt(new M(0,0,-1)),this.add(c)}update(e,t){this.parent===null&&this.updateMatrixWorld();const n=this.renderTarget,[i,r,a,o,l,c]=this.children,h=e.xr.enabled,d=e.getRenderTarget();e.xr.enabled=!1;const u=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0),e.render(t,i),e.setRenderTarget(n,1),e.render(t,r),e.setRenderTarget(n,2),e.render(t,a),e.setRenderTarget(n,3),e.render(t,o),e.setRenderTarget(n,4),e.render(t,l),n.texture.generateMipmaps=u,e.setRenderTarget(n,5),e.render(t,c),e.setRenderTarget(d),e.xr.enabled=h}}class Ai extends tt{constructor(e,t,n,i,r,a,o,l,c,h){e=e!==void 0?e:[],t=t!==void 0?t:ai,o=o!==void 0?o:Yt,super(e,t,n,i,r,a,o,l,c,h),this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}Ai.prototype.isCubeTexture=!0;class Ms extends Lt{constructor(e,t,n){Number.isInteger(t)&&(console.warn("THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )"),t=n),super(e,e,t),t=t||{},this.texture=new Ai(void 0,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.encoding),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:Ke,this.texture._needsFlipEnvMap=!1}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.format=xt,this.texture.encoding=t.encoding,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},i=new vn(5,5,5),r=new en({name:"CubemapFromEquirect",uniforms:Si(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Xe,blending:qt});r.uniforms.tEquirect.value=t;const a=new je(i,r),o=t.minFilter;return t.minFilter===In&&(t.minFilter=Ke),new bs(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,i);e.setRenderTarget(r)}}Ms.prototype.isWebGLCubeRenderTarget=!0;const co=new M,Zf=new M,$f=new et;class Ut{constructor(e=new M(1,0,0),t=0){this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=co.subVectors(n,t).cross(Zf.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(this.normal).multiplyScalar(-this.distanceToPoint(e)).add(e)}intersectLine(e,t){const n=e.delta(co),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(n).multiplyScalar(r).add(e.start)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||$f.getNormalMatrix(e),i=this.coplanarPoint(co).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}Ut.prototype.isPlane=!0;const Li=new dn,ws=new M;class hr{constructor(e=new Ut,t=new Ut,n=new Ut,i=new Ut,r=new Ut,a=new Ut){this.planes=[e,t,n,i,r,a]}set(e,t,n,i,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(i),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e){const t=this.planes,n=e.elements,i=n[0],r=n[1],a=n[2],o=n[3],l=n[4],c=n[5],h=n[6],d=n[7],u=n[8],f=n[9],p=n[10],x=n[11],y=n[12],g=n[13],m=n[14],_=n[15];return t[0].setComponents(o-i,d-l,x-u,_-y).normalize(),t[1].setComponents(o+i,d+l,x+u,_+y).normalize(),t[2].setComponents(o+r,d+c,x+f,_+g).normalize(),t[3].setComponents(o-r,d-c,x-f,_-g).normalize(),t[4].setComponents(o-a,d-h,x-p,_-m).normalize(),t[5].setComponents(o+a,d+h,x+p,_+m).normalize(),this}intersectsObject(e){const t=e.geometry;return t.boundingSphere===null&&t.computeBoundingSphere(),Li.copy(t.boundingSphere).applyMatrix4(e.matrixWorld),this.intersectsSphere(Li)}intersectsSprite(e){return Li.center.set(0,0,0),Li.radius=.7071067811865476,Li.applyMatrix4(e.matrixWorld),this.intersectsSphere(Li)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)0?e.max.x:e.min.x,ws.y=i.normal.y>0?e.max.y:e.min.y,ws.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ws)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function Su(){let s=null,e=!1,t=null,n=null;function i(r,a){t(r,a),n=s.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=s.requestAnimationFrame(i),e=!0)},stop:function(){s.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){s=r}}}function Qf(s,e){const t=e.isWebGL2,n=new WeakMap;function i(c,h){const d=c.array,u=c.usage,f=s.createBuffer();s.bindBuffer(h,f),s.bufferData(h,d,u),c.onUploadCallback();let p=5126;return d instanceof Float32Array?p=5126:d instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):d instanceof Uint16Array?c.isFloat16BufferAttribute?t?p=5131:console.warn("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."):p=5123:d instanceof Int16Array?p=5122:d instanceof Uint32Array?p=5125:d instanceof Int32Array?p=5124:d instanceof Int8Array?p=5120:(d instanceof Uint8Array||d instanceof Uint8ClampedArray)&&(p=5121),{buffer:f,type:p,bytesPerElement:d.BYTES_PER_ELEMENT,version:c.version}}function r(c,h,d){const u=h.array,f=h.updateRange;s.bindBuffer(d,c),f.count===-1?s.bufferSubData(d,0,u):(t?s.bufferSubData(d,f.offset*u.BYTES_PER_ELEMENT,u,f.offset,f.count):s.bufferSubData(d,f.offset*u.BYTES_PER_ELEMENT,u.subarray(f.offset,f.offset+f.count)),f.count=-1)}function a(c){return c.isInterleavedBufferAttribute&&(c=c.data),n.get(c)}function o(c){c.isInterleavedBufferAttribute&&(c=c.data);const h=n.get(c);h&&(s.deleteBuffer(h.buffer),n.delete(c))}function l(c,h){if(c.isGLBufferAttribute){const u=n.get(c);(!u||u.version 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir ); + float dotNH = saturate( dot( geometry.normal, halfDir ) ); + float dotVH = saturate( dot( geometry.viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float NoH ) { + float invAlpha = 1.0 / roughness; + float cos2h = NoH * NoH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float NoV, float NoL ) { + return saturate( 1.0 / ( 4.0 * ( NoL + NoV - NoL * NoV ) ) ); +} +vec3 BRDF_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) { + vec3 N = geometry.normal; + vec3 V = geometry.viewDir; + vec3 H = normalize( V + L ); + float dotNH = saturate( dot( N, H ) ); + return specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) ); +} +#endif`,op=`#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vUv ); + vec2 dSTdy = dFdy( vUv ); + float Hll = bumpScale * texture2D( bumpMap, vUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) ); + vec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`,lp=`#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif +#endif`,cp=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,up=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,hp=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,dp=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,fp=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,pp=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + varying vec3 vColor; +#endif`,mp=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif`,gp=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +struct GeometricContext { + vec3 position; + vec3 normal; + vec3 viewDir; +#ifdef USE_CLEARCOAT + vec3 clearcoatNormal; +#endif +}; +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +float linearToRelativeLuminance( const in vec3 color ) { + vec3 weights = vec3( 0.2126, 0.7152, 0.0722 ); + return dot( weights, color.rgb ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +}`,xp=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_maxMipLevel 8.0 + #define cubeUV_minMipLevel 4.0 + #define cubeUV_maxTileSize 256.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + float texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize ); + vec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ); + vec2 f = fract( uv ); + uv += 0.5 - f; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + if ( mipInt < cubeUV_maxMipLevel ) { + uv.y += 2.0 * cubeUV_maxTileSize; + } + uv.y += filterInt * 2.0 * cubeUV_minTileSize; + uv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize ); + uv *= texelSize; + vec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb; + uv.x += texelSize; + vec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb; + uv.y += texelSize; + vec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb; + uv.x -= texelSize; + vec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb; + vec3 tm = mix( tl, tr, f.x ); + vec3 bm = mix( bl, br, f.x ); + return mix( tm, bm, f.y ); + } + #define r0 1.0 + #define v0 0.339 + #define m0 - 2.0 + #define r1 0.8 + #define v1 0.276 + #define m1 - 1.0 + #define r4 0.4 + #define v4 0.046 + #define m4 2.0 + #define r5 0.305 + #define v5 0.016 + #define m5 3.0 + #define r6 0.21 + #define v6 0.0038 + #define m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= r1 ) { + mip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0; + } else if ( roughness >= r4 ) { + mip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1; + } else if ( roughness >= r5 ) { + mip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4; + } else if ( roughness >= r6 ) { + mip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,yp=`vec3 transformedNormal = objectNormal; +#ifdef USE_INSTANCING + mat3 m = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) ); + transformedNormal = m * transformedNormal; +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + vec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,vp=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,_p=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias ); +#endif`,bp=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vUv ); + emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb; + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Mp=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,wp="gl_FragColor = linearToOutputTexel( gl_FragColor );",Sp=` +vec4 LinearToLinear( in vec4 value ) { + return value; +} +vec4 GammaToLinear( in vec4 value, in float gammaFactor ) { + return vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a ); +} +vec4 LinearToGamma( in vec4 value, in float gammaFactor ) { + return vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a ); +} +vec4 sRGBToLinear( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 LinearTosRGB( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +} +vec4 RGBEToLinear( in vec4 value ) { + return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 ); +} +vec4 LinearToRGBE( in vec4 value ) { + float maxComponent = max( max( value.r, value.g ), value.b ); + float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 ); + return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 ); +} +vec4 RGBMToLinear( in vec4 value, in float maxRange ) { + return vec4( value.rgb * value.a * maxRange, 1.0 ); +} +vec4 LinearToRGBM( in vec4 value, in float maxRange ) { + float maxRGB = max( value.r, max( value.g, value.b ) ); + float M = clamp( maxRGB / maxRange, 0.0, 1.0 ); + M = ceil( M * 255.0 ) / 255.0; + return vec4( value.rgb / ( M * maxRange ), M ); +} +vec4 RGBDToLinear( in vec4 value, in float maxRange ) { + return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 ); +} +vec4 LinearToRGBD( in vec4 value, in float maxRange ) { + float maxRGB = max( value.r, max( value.g, value.b ) ); + float D = max( maxRange / maxRGB, 1.0 ); + D = clamp( floor( D ) / 255.0, 0.0, 1.0 ); + return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D ); +} +const mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 ); +vec4 LinearToLogLuv( in vec4 value ) { + vec3 Xp_Y_XYZp = cLogLuvM * value.rgb; + Xp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) ); + vec4 vResult; + vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z; + float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0; + vResult.w = fract( Le ); + vResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0; + return vResult; +} +const mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 ); +vec4 LogLuvToLinear( in vec4 value ) { + float Le = value.z * 255.0 + value.w; + vec3 Xp_Y_XYZp; + Xp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 ); + Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y; + Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z; + vec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb; + return vec4( max( vRGB, 0.0 ), 1.0 ); +}`,Tp=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + envColor = envMapTexelToLinear( envColor ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Ep=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform int maxMipLevel; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,Ap=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,Lp=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Rp=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,Cp=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Pp=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Ip=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,Dp=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,Fp=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return texture2D( gradientMap, coord ).rgb; + #else + return ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 ); + #endif +}`,Bp=`#ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vUv2 ); + vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity; + #ifndef PHYSICALLY_CORRECT_LIGHTS + lightMapIrradiance *= PI; + #endif + reflectedLight.indirectDiffuse += lightMapIrradiance; +#endif`,Np=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,zp=`vec3 diffuse = vec3( 1.0 ); +GeometricContext geometry; +geometry.position = mvPosition.xyz; +geometry.normal = normalize( transformedNormal ); +geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); +GeometricContext backGeometry; +backGeometry.position = geometry.position; +backGeometry.normal = -geometry.normal; +backGeometry.viewDir = geometry.viewDir; +vLightFront = vec3( 0.0 ); +vIndirectFront = vec3( 0.0 ); +#ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); + vIndirectBack = vec3( 0.0 ); +#endif +IncidentLight directLight; +float dotNL; +vec3 directLightColor_Diffuse; +vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); +vIndirectFront += getLightProbeIrradiance( lightProbe, geometry ); +#ifdef DOUBLE_SIDED + vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); + vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry ); +#endif +#if NUM_POINT_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + getPointLightInfo( pointLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_SPOT_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + getSpotLightInfo( spotLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_DIR_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + getDirectionalLightInfo( directionalLights[ i ], geometry, directLight ); + dotNL = dot( geometry.normal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + #ifdef DOUBLE_SIDED + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + #endif + } + #pragma unroll_loop_end +#endif +#if NUM_HEMI_LIGHTS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); + #ifdef DOUBLE_SIDED + vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry ); + #endif + } + #pragma unroll_loop_end +#endif`,Up=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +uniform vec3 lightProbe[ 9 ]; +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) { + vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + #if defined ( PHYSICALLY_CORRECT_LIGHTS ) + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; + #else + if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { + return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); + } + return 1.0; + #endif +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometry.position; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometry.position; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) { + float dotNL = dot( geometry.normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,Op=`#if defined( USE_ENVMAP ) + #ifdef ENVMAP_MODE_REFRACTION + uniform float refractionRatio; + #endif + vec3 getIBLIrradiance( const in GeometricContext geometry ) { + #if defined( ENVMAP_TYPE_CUBE_UV ) + vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #if defined( ENVMAP_TYPE_CUBE_UV ) + vec3 reflectVec; + #ifdef ENVMAP_MODE_REFLECTION + reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + #else + reflectVec = refract( - viewDir, normal, refractionRatio ); + #endif + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } +#endif`,Hp=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Gp=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon +#define Material_LightProbeLOD( material ) (0)`,kp=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,Vp=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong +#define Material_LightProbeLOD( material ) (0)`,Wp=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + #ifdef SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularTintFactor = specularTint; + #ifdef USE_SPECULARINTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a; + #endif + #ifdef USE_SPECULARTINTMAP + specularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularTintFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_SHEEN + material.sheenTint = sheenTint; +#endif`,qp=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_SHEEN + vec3 sheenTint; + #endif +}; +vec3 clearcoatSpecular = vec3( 0.0 ); +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + vec3 FssEss = specularColor * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometry.normal; + vec3 viewDir = geometry.viewDir; + vec3 position = geometry.position; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecular += ccIrradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + reflectedLight.directSpecular += irradiance * BRDF_Sheen( material.roughness, directLight.direction, geometry, material.sheenTint ); + #else + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness ); + #endif + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + computeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + vec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,Xp=` +GeometricContext geometry; +geometry.position = - vViewPosition; +geometry.normal = normal; +geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +#ifdef USE_CLEARCOAT + geometry.clearcoatNormal = clearcoatNormal; +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, geometry, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + irradiance += getLightProbeIrradiance( lightProbe, geometry ); + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,Yp=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vUv2 ); + vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity; + #ifndef PHYSICALLY_CORRECT_LIGHTS + lightMapIrradiance *= PI; + #endif + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometry ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + radiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness ); + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,Jp=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight ); +#endif`,Zp=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,$p=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,Qp=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + varying float vFragDepth; + varying float vIsPerspective; + #else + uniform float logDepthBufFC; + #endif +#endif`,jp=`#ifdef USE_LOGDEPTHBUF + #ifdef USE_LOGDEPTHBUF_EXT + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); + #else + if ( isPerspectiveMatrix( projectionMatrix ) ) { + gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; + gl_Position.z *= gl_Position.w; + } + #endif +#endif`,Kp=`#ifdef USE_MAP + vec4 texelColor = texture2D( map, vUv ); + texelColor = mapTexelToLinear( texelColor ); + diffuseColor *= texelColor; +#endif`,em=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,tm=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; +#endif +#ifdef USE_MAP + vec4 mapTexel = texture2D( map, uv ); + diffuseColor *= mapTexelToLinear( mapTexel ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,nm=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,im=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vUv ); + metalnessFactor *= texelMetalness.b; +#endif`,rm=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,sm=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; + objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; + objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; + objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; +#endif`,am=`#ifdef USE_MORPHTARGETS + uniform float morphTargetBaseInfluence; + #ifndef USE_MORPHNORMALS + uniform float morphTargetInfluences[ 8 ]; + #else + uniform float morphTargetInfluences[ 4 ]; + #endif +#endif`,om=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + transformed += morphTarget0 * morphTargetInfluences[ 0 ]; + transformed += morphTarget1 * morphTargetInfluences[ 1 ]; + transformed += morphTarget2 * morphTargetInfluences[ 2 ]; + transformed += morphTarget3 * morphTargetInfluences[ 3 ]; + #ifndef USE_MORPHNORMALS + transformed += morphTarget4 * morphTargetInfluences[ 4 ]; + transformed += morphTarget5 * morphTargetInfluences[ 5 ]; + transformed += morphTarget6 * morphTargetInfluences[ 6 ]; + transformed += morphTarget7 * morphTargetInfluences[ 7 ]; + #endif +#endif`,lm=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) ); + vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + #ifdef USE_TANGENT + vec3 tangent = normalize( vTangent ); + vec3 bitangent = normalize( vBitangent ); + #ifdef DOUBLE_SIDED + tangent = tangent * faceDirection; + bitangent = bitangent * faceDirection; + #endif + #if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP ) + mat3 vTBN = mat3( tangent, bitangent, normal ); + #endif + #endif +#endif +vec3 geometryNormal = normal;`,cm=`#ifdef OBJECTSPACE_NORMALMAP + normal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( TANGENTSPACE_NORMALMAP ) + vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + #ifdef USE_TANGENT + normal = normalize( vTBN * mapN ); + #else + normal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection ); + #endif +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,um=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,hm=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,dm=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,fm=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef OBJECTSPACE_NORMALMAP + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) ) + vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { + vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); + vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); + vec2 st0 = dFdx( vUv.st ); + vec2 st1 = dFdy( vUv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det ); + return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z ); + } +#endif`,pm=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = geometryNormal; +#endif`,mm=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + #ifdef USE_TANGENT + clearcoatNormal = normalize( vTBN * clearcoatMapN ); + #else + clearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection ); + #endif +#endif`,gm=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif`,xm=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= transmissionAlpha + 0.1; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,ym=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; +const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); +const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); +const float ShiftRight8 = 1. / 256.; +vec4 packDepthToRGBA( const in float v ) { + vec4 r = vec4( fract( v * PackFactors ), v ); + r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors ); +} +vec4 pack2HalfToRGBA( vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) { + return linearClipZ * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * invClipZ - far ); +}`,vm=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,_m=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,bm=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Mm=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,wm=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vUv ); + roughnessFactor *= texelRoughness.g; +#endif`,Sm=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,Tm=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 ); + bool inFrustum = all( inFrustumVec ); + bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 ); + bool frustumTest = all( frustumTestVec ); + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return shadow; + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + vec3 lightToPosition = shadowCoord.xyz; + float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + return ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } +#endif`,Em=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ]; + varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,Am=`#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; + #endif + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 ); + vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif`,Lm=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Rm=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,Cm=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + #ifdef BONE_TEXTURE + uniform highp sampler2D boneTexture; + uniform int boneTextureSize; + mat4 getBoneMatrix( const in float i ) { + float j = i * 4.0; + float x = mod( j, float( boneTextureSize ) ); + float y = floor( j / float( boneTextureSize ) ); + float dx = 1.0 / float( boneTextureSize ); + float dy = 1.0 / float( boneTextureSize ); + y = dy * ( y + 0.5 ); + vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) ); + vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) ); + vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) ); + vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) ); + mat4 bone = mat4( v1, v2, v3, v4 ); + return bone; + } + #else + uniform mat4 boneMatrices[ MAX_BONES ]; + mat4 getBoneMatrix( const in float i ) { + mat4 bone = boneMatrices[ int(i) ]; + return bone; + } + #endif +#endif`,Pm=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,Im=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,Dm=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,Fm=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,Bm=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,Nm=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return toneMappingExposure * color; +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 OptimizedCineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,zm=`#ifdef USE_TRANSMISSION + float transmissionAlpha = 1.0; + float transmissionFactor = transmission; + float thicknessFactor = thickness; + #ifdef USE_TRANSMISSIONMAP + transmissionFactor *= texture2D( transmissionMap, vUv ).r; + #endif + #ifdef USE_THICKNESSMAP + thicknessFactor *= texture2D( thicknessMap, vUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmission = getIBLVolumeRefraction( + n, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor, + attenuationTint, attenuationDistance ); + totalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor ); + transmissionAlpha = transmission.a; +#endif`,Um=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationTint; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + vec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( float roughness, float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) { + float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + #ifdef TEXTURE_LOD_EXT + return texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod ); + #else + return texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod ); + #endif + } + vec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) { + if ( attenuationDistance == 0.0 ) { + return radiance; + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance * radiance; + } + } + vec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90, + vec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness, + vec3 attenuationColor, float attenuationDistance ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance ); + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a ); + } +#endif`,Om=`#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) ) + varying vec2 vUv; +#endif`,Hm=`#ifdef USE_UV + #ifdef UVS_VERTEX_ONLY + vec2 vUv; + #else + varying vec2 vUv; + #endif + uniform mat3 uvTransform; +#endif`,Gm=`#ifdef USE_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; +#endif`,km=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + varying vec2 vUv2; +#endif`,Vm=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + attribute vec2 uv2; + varying vec2 vUv2; + uniform mat3 uv2Transform; +#endif`,Wm=`#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; +#endif`,qm=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,Xm=`uniform sampler2D t2D; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + gl_FragColor = mapTexelToLinear( texColor ); + #include + #include +}`,Ym=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,Jm=`#include +uniform float opacity; +varying vec3 vWorldDirection; +#include +void main() { + vec3 vReflect = vWorldDirection; + #include + gl_FragColor = envColor; + gl_FragColor.a *= opacity; + #include + #include +}`,Zm=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,$m=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + vec4 diffuseColor = vec4( 1.0 ); + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #endif +}`,Qm=`#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,jm=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main () { + #include + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,Km=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,eg=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + vec4 texColor = texture2D( tEquirect, sampleUV ); + gl_FragColor = mapTexelToLinear( texColor ); + #include + #include +}`,tg=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,ng=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +void main() { + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,ig=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include +}`,rg=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel= texture2D( lightMap, vUv2 ); + reflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,sg=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,ag=`uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +varying vec3 vLightFront; +varying vec3 vIndirectFront; +#ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #ifdef DOUBLE_SIDED + reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; + #else + reflectedLight.indirectDiffuse += vIndirectFront; + #endif + #include + reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); + #ifdef DOUBLE_SIDED + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + #else + reflectedLight.directDiffuse = vLightFront; + #endif + reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,og=`#define LAMBERT +varying vec3 vLightFront; +varying vec3 vIndirectFront; +#ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,lg=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + matcapColor = matcapTexelToLinear( matcapColor ); + #else + vec4 matcapColor = vec4( 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,cg=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,ug=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), opacity ); +}`,hg=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP ) + vViewPosition = - mvPosition.xyz; +#endif +}`,dg=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,fg=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,pg=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef SPECULAR + uniform float specularIntensity; + uniform vec3 specularTint; + #ifdef USE_SPECULARINTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif + #ifdef USE_SPECULARTINTMAP + uniform sampler2D specularTintMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenTint; +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,mg=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,gg=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,xg=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,yg=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,vg=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,_g=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,bg=`#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Mg=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + vec3 outgoingLight = vec3( 0.0 ); + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,wg=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); + vec2 scale; + scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); + scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`;const Pe={alphamap_fragment:jf,alphamap_pars_fragment:Kf,alphatest_fragment:ep,alphatest_pars_fragment:tp,aomap_fragment:np,aomap_pars_fragment:ip,begin_vertex:rp,beginnormal_vertex:sp,bsdfs:ap,bumpmap_pars_fragment:op,clipping_planes_fragment:lp,clipping_planes_pars_fragment:cp,clipping_planes_pars_vertex:up,clipping_planes_vertex:hp,color_fragment:dp,color_pars_fragment:fp,color_pars_vertex:pp,color_vertex:mp,common:gp,cube_uv_reflection_fragment:xp,defaultnormal_vertex:yp,displacementmap_pars_vertex:vp,displacementmap_vertex:_p,emissivemap_fragment:bp,emissivemap_pars_fragment:Mp,encodings_fragment:wp,encodings_pars_fragment:Sp,envmap_fragment:Tp,envmap_common_pars_fragment:Ep,envmap_pars_fragment:Ap,envmap_pars_vertex:Lp,envmap_physical_pars_fragment:Op,envmap_vertex:Rp,fog_vertex:Cp,fog_pars_vertex:Pp,fog_fragment:Ip,fog_pars_fragment:Dp,gradientmap_pars_fragment:Fp,lightmap_fragment:Bp,lightmap_pars_fragment:Np,lights_lambert_vertex:zp,lights_pars_begin:Up,lights_toon_fragment:Hp,lights_toon_pars_fragment:Gp,lights_phong_fragment:kp,lights_phong_pars_fragment:Vp,lights_physical_fragment:Wp,lights_physical_pars_fragment:qp,lights_fragment_begin:Xp,lights_fragment_maps:Yp,lights_fragment_end:Jp,logdepthbuf_fragment:Zp,logdepthbuf_pars_fragment:$p,logdepthbuf_pars_vertex:Qp,logdepthbuf_vertex:jp,map_fragment:Kp,map_pars_fragment:em,map_particle_fragment:tm,map_particle_pars_fragment:nm,metalnessmap_fragment:im,metalnessmap_pars_fragment:rm,morphnormal_vertex:sm,morphtarget_pars_vertex:am,morphtarget_vertex:om,normal_fragment_begin:lm,normal_fragment_maps:cm,normal_pars_fragment:um,normal_pars_vertex:hm,normal_vertex:dm,normalmap_pars_fragment:fm,clearcoat_normal_fragment_begin:pm,clearcoat_normal_fragment_maps:mm,clearcoat_pars_fragment:gm,output_fragment:xm,packing:ym,premultiplied_alpha_fragment:vm,project_vertex:_m,dithering_fragment:bm,dithering_pars_fragment:Mm,roughnessmap_fragment:wm,roughnessmap_pars_fragment:Sm,shadowmap_pars_fragment:Tm,shadowmap_pars_vertex:Em,shadowmap_vertex:Am,shadowmask_pars_fragment:Lm,skinbase_vertex:Rm,skinning_pars_vertex:Cm,skinning_vertex:Pm,skinnormal_vertex:Im,specularmap_fragment:Dm,specularmap_pars_fragment:Fm,tonemapping_fragment:Bm,tonemapping_pars_fragment:Nm,transmission_fragment:zm,transmission_pars_fragment:Um,uv_pars_fragment:Om,uv_pars_vertex:Hm,uv_vertex:Gm,uv2_pars_fragment:km,uv2_pars_vertex:Vm,uv2_vertex:Wm,worldpos_vertex:qm,background_frag:Xm,background_vert:Ym,cube_frag:Jm,cube_vert:Zm,depth_frag:$m,depth_vert:Qm,distanceRGBA_frag:jm,distanceRGBA_vert:Km,equirect_frag:eg,equirect_vert:tg,linedashed_frag:ng,linedashed_vert:ig,meshbasic_frag:rg,meshbasic_vert:sg,meshlambert_frag:ag,meshlambert_vert:og,meshmatcap_frag:lg,meshmatcap_vert:cg,meshnormal_frag:ug,meshnormal_vert:hg,meshphong_frag:dg,meshphong_vert:fg,meshphysical_frag:pg,meshphysical_vert:mg,meshtoon_frag:gg,meshtoon_vert:xg,points_frag:yg,points_vert:vg,shadow_frag:_g,shadow_vert:bg,sprite_frag:Mg,sprite_vert:wg},ee={common:{diffuse:{value:new te(16777215)},opacity:{value:1},map:{value:null},uvTransform:{value:new et},uv2Transform:{value:new et},alphaMap:{value:null},alphaTest:{value:0}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new Y(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new te(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new te(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new et}},sprite:{diffuse:{value:new te(16777215)},opacity:{value:1},center:{value:new Y(.5,.5)},rotation:{value:0},map:{value:null},alphaMap:{value:null},alphaTest:{value:0},uvTransform:{value:new et}}},It={basic:{uniforms:pt([ee.common,ee.specularmap,ee.envmap,ee.aomap,ee.lightmap,ee.fog]),vertexShader:Pe.meshbasic_vert,fragmentShader:Pe.meshbasic_frag},lambert:{uniforms:pt([ee.common,ee.specularmap,ee.envmap,ee.aomap,ee.lightmap,ee.emissivemap,ee.fog,ee.lights,{emissive:{value:new te(0)}}]),vertexShader:Pe.meshlambert_vert,fragmentShader:Pe.meshlambert_frag},phong:{uniforms:pt([ee.common,ee.specularmap,ee.envmap,ee.aomap,ee.lightmap,ee.emissivemap,ee.bumpmap,ee.normalmap,ee.displacementmap,ee.fog,ee.lights,{emissive:{value:new te(0)},specular:{value:new te(1118481)},shininess:{value:30}}]),vertexShader:Pe.meshphong_vert,fragmentShader:Pe.meshphong_frag},standard:{uniforms:pt([ee.common,ee.envmap,ee.aomap,ee.lightmap,ee.emissivemap,ee.bumpmap,ee.normalmap,ee.displacementmap,ee.roughnessmap,ee.metalnessmap,ee.fog,ee.lights,{emissive:{value:new te(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Pe.meshphysical_vert,fragmentShader:Pe.meshphysical_frag},toon:{uniforms:pt([ee.common,ee.aomap,ee.lightmap,ee.emissivemap,ee.bumpmap,ee.normalmap,ee.displacementmap,ee.gradientmap,ee.fog,ee.lights,{emissive:{value:new te(0)}}]),vertexShader:Pe.meshtoon_vert,fragmentShader:Pe.meshtoon_frag},matcap:{uniforms:pt([ee.common,ee.bumpmap,ee.normalmap,ee.displacementmap,ee.fog,{matcap:{value:null}}]),vertexShader:Pe.meshmatcap_vert,fragmentShader:Pe.meshmatcap_frag},points:{uniforms:pt([ee.points,ee.fog]),vertexShader:Pe.points_vert,fragmentShader:Pe.points_frag},dashed:{uniforms:pt([ee.common,ee.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Pe.linedashed_vert,fragmentShader:Pe.linedashed_frag},depth:{uniforms:pt([ee.common,ee.displacementmap]),vertexShader:Pe.depth_vert,fragmentShader:Pe.depth_frag},normal:{uniforms:pt([ee.common,ee.bumpmap,ee.normalmap,ee.displacementmap,{opacity:{value:1}}]),vertexShader:Pe.meshnormal_vert,fragmentShader:Pe.meshnormal_frag},sprite:{uniforms:pt([ee.sprite,ee.fog]),vertexShader:Pe.sprite_vert,fragmentShader:Pe.sprite_frag},background:{uniforms:{uvTransform:{value:new et},t2D:{value:null}},vertexShader:Pe.background_vert,fragmentShader:Pe.background_frag},cube:{uniforms:pt([ee.envmap,{opacity:{value:1}}]),vertexShader:Pe.cube_vert,fragmentShader:Pe.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Pe.equirect_vert,fragmentShader:Pe.equirect_frag},distanceRGBA:{uniforms:pt([ee.common,ee.displacementmap,{referencePosition:{value:new M},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Pe.distanceRGBA_vert,fragmentShader:Pe.distanceRGBA_frag},shadow:{uniforms:pt([ee.lights,ee.fog,{color:{value:new te(0)},opacity:{value:1}}]),vertexShader:Pe.shadow_vert,fragmentShader:Pe.shadow_frag}};It.physical={uniforms:pt([It.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new Y(1,1)},clearcoatNormalMap:{value:null},sheenTint:{value:new te(0)},transmission:{value:0},transmissionMap:{value:null},transmissionSamplerSize:{value:new Y},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:0},attenuationTint:{value:new te(0)},specularIntensity:{value:0},specularIntensityMap:{value:null},specularTint:{value:new te(1,1,1)},specularTintMap:{value:null}}]),vertexShader:Pe.meshphysical_vert,fragmentShader:Pe.meshphysical_frag};function Sg(s,e,t,n,i){const r=new te(0);let a=0,o,l,c=null,h=0,d=null;function u(p,x){let y=!1,g=x.isScene===!0?x.background:null;g&&g.isTexture&&(g=e.get(g));const m=s.xr,_=m.getSession&&m.getSession();_&&_.environmentBlendMode==="additive"&&(g=null),g===null?f(r,a):g&&g.isColor&&(f(g,1),y=!0),(s.autoClear||y)&&s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil),g&&(g.isCubeTexture||g.mapping===li)?(l===void 0&&(l=new je(new vn(1,1,1),new en({name:"BackgroundCubeMaterial",uniforms:Si(It.cube.uniforms),vertexShader:It.cube.vertexShader,fragmentShader:It.cube.fragmentShader,side:Xe,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(v,T,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(l)),l.material.uniforms.envMap.value=g,l.material.uniforms.flipEnvMap.value=g.isCubeTexture&&g.isRenderTargetTexture===!1?-1:1,(c!==g||h!==g.version||d!==s.toneMapping)&&(l.material.needsUpdate=!0,c=g,h=g.version,d=s.toneMapping),p.unshift(l,l.geometry,l.material,0,0,null)):g&&g.isTexture&&(o===void 0&&(o=new je(new Ri(2,2),new en({name:"BackgroundMaterial",uniforms:Si(It.background.uniforms),vertexShader:It.background.vertexShader,fragmentShader:It.background.fragmentShader,side:Rn,depthTest:!1,depthWrite:!1,fog:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(o)),o.material.uniforms.t2D.value=g,g.matrixAutoUpdate===!0&&g.updateMatrix(),o.material.uniforms.uvTransform.value.copy(g.matrix),(c!==g||h!==g.version||d!==s.toneMapping)&&(o.material.needsUpdate=!0,c=g,h=g.version,d=s.toneMapping),p.unshift(o,o.geometry,o.material,0,0,null))}function f(p,x){t.buffers.color.setClear(p.r,p.g,p.b,x,i)}return{getClearColor:function(){return r},setClearColor:function(p,x=1){r.set(p),a=x,f(r,a)},getClearAlpha:function(){return a},setClearAlpha:function(p){a=p,f(r,a)},render:u}}function Tg(s,e,t,n){const i=s.getParameter(34921),r=n.isWebGL2?null:e.get("OES_vertex_array_object"),a=n.isWebGL2||r!==null,o={},l=x(null);let c=l;function h(B,F,G,z,k){let j=!1;if(a){const ue=p(z,G,F);c!==ue&&(c=ue,u(c.object)),j=y(z,k),j&&g(z,k)}else{const ue=F.wireframe===!0;(c.geometry!==z.id||c.program!==G.id||c.wireframe!==ue)&&(c.geometry=z.id,c.program=G.id,c.wireframe=ue,j=!0)}B.isInstancedMesh===!0&&(j=!0),k!==null&&t.update(k,34963),j&&(b(B,F,G,z),k!==null&&s.bindBuffer(34963,t.get(k).buffer))}function d(){return n.isWebGL2?s.createVertexArray():r.createVertexArrayOES()}function u(B){return n.isWebGL2?s.bindVertexArray(B):r.bindVertexArrayOES(B)}function f(B){return n.isWebGL2?s.deleteVertexArray(B):r.deleteVertexArrayOES(B)}function p(B,F,G){const z=G.wireframe===!0;let k=o[B.id];k===void 0&&(k={},o[B.id]=k);let j=k[F.id];j===void 0&&(j={},k[F.id]=j);let ue=j[z];return ue===void 0&&(ue=x(d()),j[z]=ue),ue}function x(B){const F=[],G=[],z=[];for(let k=0;k=0){let Ee=k[ye];if(Ee===void 0&&(ye==="instanceMatrix"&&B.instanceMatrix&&(Ee=B.instanceMatrix),ye==="instanceColor"&&B.instanceColor&&(Ee=B.instanceColor)),Ee!==void 0){const q=Ee.normalized,Q=Ee.itemSize,pe=t.get(Ee);if(pe===void 0)continue;const U=pe.buffer,ve=pe.type,Se=pe.bytesPerElement;if(Ee.isInterleavedBufferAttribute){const ce=Ee.data,de=ce.stride,Le=Ee.offset;if(ce&&ce.isInstancedInterleavedBuffer){for(let V=0;V0&&s.getShaderPrecisionFormat(35632,36338).precision>0)return"highp";b="mediump"}return b==="mediump"&&s.getShaderPrecisionFormat(35633,36337).precision>0&&s.getShaderPrecisionFormat(35632,36337).precision>0?"mediump":"lowp"}const a=typeof WebGL2RenderingContext!="undefined"&&s instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!="undefined"&&s instanceof WebGL2ComputeRenderingContext;let o=t.precision!==void 0?t.precision:"highp";const l=r(o);l!==o&&(console.warn("THREE.WebGLRenderer:",o,"not supported, using",l,"instead."),o=l);const c=a||e.has("WEBGL_draw_buffers"),h=t.logarithmicDepthBuffer===!0,d=s.getParameter(34930),u=s.getParameter(35660),f=s.getParameter(3379),p=s.getParameter(34076),x=s.getParameter(34921),y=s.getParameter(36347),g=s.getParameter(36348),m=s.getParameter(36349),_=u>0,v=a||e.has("OES_texture_float"),T=_&&v,A=a?s.getParameter(36183):0;return{isWebGL2:a,drawBuffers:c,getMaxAnisotropy:i,getMaxPrecision:r,precision:o,logarithmicDepthBuffer:h,maxTextures:d,maxVertexTextures:u,maxTextureSize:f,maxCubemapSize:p,maxAttributes:x,maxVertexUniforms:y,maxVaryings:g,maxFragmentUniforms:m,vertexTextures:_,floatFragmentTextures:v,floatVertexTextures:T,maxSamples:A}}function Lg(s){const e=this;let t=null,n=0,i=!1,r=!1;const a=new Ut,o=new et,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,u,f){const p=d.length!==0||u||n!==0||i;return i=u,t=h(d,f,0),n=d.length,p},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1,c()},this.setState=function(d,u,f){const p=d.clippingPlanes,x=d.clipIntersection,y=d.clipShadows,g=s.get(d);if(!i||p===null||p.length===0||r&&!y)r?h(null):c();else{const m=r?0:n,_=m*4;let v=g.clippingState||null;l.value=v,v=h(p,u,_,f);for(let T=0;T!==_;++T)v[T]=t[T];g.clippingState=v,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=m}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(d,u,f,p){const x=d!==null?d.length:0;let y=null;if(x!==0){if(y=l.value,p!==!0||y===null){const g=f+x*4,m=u.matrixWorldInverse;o.getNormalMatrix(m),(y===null||y.length0){const c=s.getRenderTarget(),h=new Ms(l.height/2);return h.fromEquirectangularTexture(s,a),e.set(a,h),s.setRenderTarget(c),a.addEventListener("dispose",i),t(h.texture,a.mapping)}else return null}}return a}function i(a){const o=a.target;o.removeEventListener("dispose",i);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}class dr extends ur{constructor(e=-1,t=1,n=1,i=-1,r=.1,a=2e3){super();this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,a=n+e,o=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=c*this.view.offsetX,a=r+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,l,this.near,this.far),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}dr.prototype.isOrthographicCamera=!0;class Ci extends en{constructor(e){super(e);this.type="RawShaderMaterial"}}Ci.prototype.isRawShaderMaterial=!0;const Pi=4,_n=8,Ot=Math.pow(2,_n),Tu=[.125,.215,.35,.446,.526,.582],Eu=_n-Pi+1+Tu.length,Ii=20,Ht={[yt]:0,[ir]:1,[es]:2,[Da]:3,[Fa]:4,[Ba]:5,[Kr]:6},uo=new dr,{_lodPlanes:fr,_sizeLods:Au,_sigmas:Ss}=Pg(),Lu=new te;let ho=null;const Wn=(1+Math.sqrt(5))/2,Di=1/Wn,Ru=[new M(1,1,1),new M(-1,1,1),new M(1,1,-1),new M(-1,1,-1),new M(0,Wn,Di),new M(0,Wn,-Di),new M(Di,0,Wn),new M(-Di,0,Wn),new M(Wn,Di,0),new M(-Wn,Di,0)];class Cu{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._blurMaterial=Ig(Ii),this._equirectShader=null,this._cubemapShader=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100){ho=this._renderer.getRenderTarget();const r=this._allocateTargets();return this._sceneToCubeUV(e,n,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e){return this._fromTexture(e)}fromCubemap(e){return this._fromTexture(e)}compileCubemapShader(){this._cubemapShader===null&&(this._cubemapShader=Du(),this._compileMaterial(this._cubemapShader))}compileEquirectangularShader(){this._equirectShader===null&&(this._equirectShader=Iu(),this._compileMaterial(this._equirectShader))}dispose(){this._blurMaterial.dispose(),this._cubemapShader!==null&&this._cubemapShader.dispose(),this._equirectShader!==null&&this._equirectShader.dispose();for(let e=0;e2?Ot:0,Ot,Ot),h.setRenderTarget(i),y&&h.render(x,o),h.render(e,o)}x.geometry.dispose(),x.material.dispose(),h.toneMapping=f,h.outputEncoding=u,h.autoClear=d,e.background=g}_textureToCubeUV(e,t){const n=this._renderer;e.isCubeTexture?this._cubemapShader==null&&(this._cubemapShader=Du()):this._equirectShader==null&&(this._equirectShader=Iu());const i=e.isCubeTexture?this._cubemapShader:this._equirectShader,r=new je(fr[0],i),a=i.uniforms;a.envMap.value=e,e.isCubeTexture||a.texelSize.value.set(1/e.image.width,1/e.image.height),a.inputEncoding.value=Ht[e.encoding],a.outputEncoding.value=Ht[t.texture.encoding],Ts(t,0,0,3*Ot,2*Ot),n.setRenderTarget(t),n.render(r,uo)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;for(let i=1;iIi&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${y} samples when the maximum is set to ${Ii}`);const g=[];let m=0;for(let A=0;A_n-Pi?i-_n+Pi:0);Ts(t,v,T,3*_,2*_),l.setRenderTarget(t),l.render(d,uo)}}function Cg(s){return s===void 0||s.type!==Dn?!1:s.encoding===yt||s.encoding===ir||s.encoding===Kr}function Pg(){const s=[],e=[],t=[];let n=_n;for(let i=0;i_n-Pi?a=Tu[i-_n+Pi-1]:i==0&&(a=0),t.push(a);const o=1/(r-1),l=-o/2,c=1+o/2,h=[l,l,c,l,c,c,l,l,c,c,l,c],d=6,u=6,f=3,p=2,x=1,y=new Float32Array(f*u*d),g=new Float32Array(p*u*d),m=new Float32Array(x*u*d);for(let v=0;v2?0:-1,b=[T,A,0,T+2/3,A,0,T+2/3,A+1,0,T,A,0,T+2/3,A+1,0,T,A+1,0];y.set(b,f*u*v),g.set(h,p*u*v);const L=[v,v,v,v,v,v];m.set(L,x*u*v)}const _=new _e;_.setAttribute("position",new Be(y,f)),_.setAttribute("uv",new Be(g,p)),_.setAttribute("faceIndex",new Be(m,x)),s.push(_),n>Pi&&n--}return{_lodPlanes:s,_sizeLods:e,_sigmas:t}}function Pu(s){const e=new Lt(3*Ot,3*Ot,s);return e.texture.mapping=li,e.texture.name="PMREM.cubeUv",e.scissorTest=!0,e}function Ts(s,e,t,n,i){s.viewport.set(e,t,n,i),s.scissor.set(e,t,n,i)}function Ig(s){const e=new Float32Array(s),t=new M(0,1,0);return new Ci({name:"SphericalGaussianBlur",defines:{n:s},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:e},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:t},inputEncoding:{value:Ht[yt]},outputEncoding:{value:Ht[yt]}},vertexShader:fo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + ${po()} + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + gl_FragColor = linearToOutputTexel( gl_FragColor ); + + } + `,blending:qt,depthTest:!1,depthWrite:!1})}function Iu(){const s=new Y(1,1);return new Ci({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null},texelSize:{value:s},inputEncoding:{value:Ht[yt]},outputEncoding:{value:Ht[yt]}},vertexShader:fo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform vec2 texelSize; + + ${po()} + + #include + + void main() { + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + vec2 f = fract( uv / texelSize - 0.5 ); + uv -= f * texelSize; + vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + uv.x += texelSize.x; + vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + uv.y += texelSize.y; + vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + uv.x -= texelSize.x; + vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb; + + vec3 tm = mix( tl, tr, f.x ); + vec3 bm = mix( bl, br, f.x ); + gl_FragColor.rgb = mix( tm, bm, f.y ); + + gl_FragColor = linearToOutputTexel( gl_FragColor ); + + } + `,blending:qt,depthTest:!1,depthWrite:!1})}function Du(){return new Ci({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},inputEncoding:{value:Ht[yt]},outputEncoding:{value:Ht[yt]}},vertexShader:fo(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + ${po()} + + void main() { + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb; + gl_FragColor = linearToOutputTexel( gl_FragColor ); + + } + `,blending:qt,depthTest:!1,depthWrite:!1})}function fo(){return` + + precision mediump float; + precision mediump int; + + attribute vec3 position; + attribute vec2 uv; + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function po(){return` + + uniform int inputEncoding; + uniform int outputEncoding; + + #include + + vec4 inputTexelToLinear( vec4 value ) { + + if ( inputEncoding == 0 ) { + + return value; + + } else if ( inputEncoding == 1 ) { + + return sRGBToLinear( value ); + + } else if ( inputEncoding == 2 ) { + + return RGBEToLinear( value ); + + } else if ( inputEncoding == 3 ) { + + return RGBMToLinear( value, 7.0 ); + + } else if ( inputEncoding == 4 ) { + + return RGBMToLinear( value, 16.0 ); + + } else if ( inputEncoding == 5 ) { + + return RGBDToLinear( value, 256.0 ); + + } else { + + return GammaToLinear( value, 2.2 ); + + } + + } + + vec4 linearToOutputTexel( vec4 value ) { + + if ( outputEncoding == 0 ) { + + return value; + + } else if ( outputEncoding == 1 ) { + + return LinearTosRGB( value ); + + } else if ( outputEncoding == 2 ) { + + return LinearToRGBE( value ); + + } else if ( outputEncoding == 3 ) { + + return LinearToRGBM( value, 7.0 ); + + } else if ( outputEncoding == 4 ) { + + return LinearToRGBM( value, 16.0 ); + + } else if ( outputEncoding == 5 ) { + + return LinearToRGBD( value, 256.0 ); + + } else { + + return LinearToGamma( value, 2.2 ); + + } + + } + + vec4 envMapTexelToLinear( vec4 color ) { + + return inputTexelToLinear( color ); + + } + `}function Dg(s){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture&&o.isRenderTargetTexture===!1){const l=o.mapping,c=l===Yi||l===Ji,h=l===ai||l===oi;if(c||h){if(e.has(o))return e.get(o).texture;{const d=o.image;if(c&&d&&d.height>0||h&&d&&i(d)){const u=s.getRenderTarget();t===null&&(t=new Cu(s));const f=c?t.fromEquirectangular(o):t.fromCubemap(o);return e.set(o,f),s.setRenderTarget(u),o.addEventListener("dispose",r),f.texture}else return null}}}return o}function i(o){let l=0;const c=6;for(let h=0;h65535?ds:hs)(u,1);y.version=x;const g=r.get(d);g&&e.remove(g),r.set(d,y)}function h(d){const u=r.get(d);if(u){const f=d.index;f!==null&&u.version0)return s;const i=e*t;let r=Nu[i];if(r===void 0&&(r=new Float32Array(i),Nu[i]=r),e!==0){n.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,s[a].toArray(r,o)}return r}function vt(s,e){if(s.length!==e.length)return!1;for(let t=0,n=s.length;t/gm;function yo(s){return s.replace(zx,Ux)}function Ux(s,e){const t=Pe[e];if(t===void 0)throw new Error("Can not resolve #include <"+e+">");return yo(t)}const Ox=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,Hx=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function $u(s){return s.replace(Hx,Qu).replace(Ox,Gx)}function Gx(s,e,t,n){return console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead."),Qu(s,e,t,n)}function Qu(s,e,t,n){let i="";for(let r=parseInt(e);r0?s.gammaFactor:1,f=t.isWebGL2?"":Fx(t),p=Bx(r),x=i.createProgram();let y,g,m=t.glslVersion?"#version "+t.glslVersion+` +`:"";t.isRawShaderMaterial?(y=[p].filter(pr).join(` +`),y.length>0&&(y+=` +`),g=[f,p].filter(pr).join(` +`),g.length>0&&(g+=` +`)):(y=[ju(t),"#define SHADER_NAME "+t.shaderName,p,t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+u,"#define MAX_BONES "+t.maxBones,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMap&&t.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",t.normalMap&&t.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.displacementMap&&t.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",t.specularTintMap?"#define USE_SPECULARTINTMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUvs?"#define USE_UV":"",t.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.useVertexTexture?"#define BONE_TEXTURE":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(pr).join(` +`),g=[f,ju(t),"#define SHADER_NAME "+t.shaderName,p,"#define GAMMA_FACTOR "+u,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+d:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMap&&t.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",t.normalMap&&t.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",t.specularTintMap?"#define USE_SPECULARTINTMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.sheenTint?"#define USE_SHEEN":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUvs?"#define USE_UV":"",t.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"",(t.extensionShaderTextureLOD||t.envMap)&&t.rendererExtensionShaderTextureLod?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ln?"#define TONE_MAPPING":"",t.toneMapping!==ln?Pe.tonemapping_pars_fragment:"",t.toneMapping!==ln?Dx("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.format===Yt?"#define OPAQUE":"",Pe.encodings_pars_fragment,t.map?Bi("mapTexelToLinear",t.mapEncoding):"",t.matcap?Bi("matcapTexelToLinear",t.matcapEncoding):"",t.envMap?Bi("envMapTexelToLinear",t.envMapEncoding):"",t.emissiveMap?Bi("emissiveMapTexelToLinear",t.emissiveMapEncoding):"",t.specularTintMap?Bi("specularTintMapTexelToLinear",t.specularTintMapEncoding):"",t.lightMap?Bi("lightMapTexelToLinear",t.lightMapEncoding):"",Ix("linearToOutputTexel",t.outputEncoding),t.depthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(pr).join(` +`)),a=yo(a),a=Ju(a,t),a=Zu(a,t),o=yo(o),o=Ju(o,t),o=Zu(o,t),a=$u(a),o=$u(o),t.isWebGL2&&t.isRawShaderMaterial!==!0&&(m=`#version 300 es +`,y=["#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+y,g=["#define varying in",t.glslVersion===Na?"":"out highp vec4 pc_fragColor;",t.glslVersion===Na?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+g);const _=m+y+a,v=m+g+o,T=qu(i,35633,_),A=qu(i,35632,v);if(i.attachShader(x,T),i.attachShader(x,A),t.index0AttributeName!==void 0?i.bindAttribLocation(x,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(x,0,"position"),i.linkProgram(x),s.debug.checkShaderErrors){const N=i.getProgramInfoLog(x).trim(),P=i.getShaderInfoLog(T).trim(),R=i.getShaderInfoLog(A).trim();let J=!0,B=!0;if(i.getProgramParameter(x,35714)===!1){J=!1;const F=Yu(i,T,"vertex"),G=Yu(i,A,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(x,35715)+` + +Program Info Log: `+N+` +`+F+` +`+G)}else N!==""?console.warn("THREE.WebGLProgram: Program Info Log:",N):(P===""||R==="")&&(B=!1);B&&(this.diagnostics={runnable:J,programLog:N,vertexShader:{log:P,prefix:y},fragmentShader:{log:R,prefix:g}})}i.deleteShader(T),i.deleteShader(A);let b;this.getUniforms=function(){return b===void 0&&(b=new bn(i,x)),b};let L;return this.getAttributes=function(){return L===void 0&&(L=Nx(i,x)),L},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(x),this.program=void 0},this.name=t.shaderName,this.id=Cx++,this.cacheKey=e,this.usedTimes=1,this.program=x,this.vertexShader=T,this.fragmentShader=A,this}function Yx(s,e,t,n,i,r,a){const o=[],l=i.isWebGL2,c=i.logarithmicDepthBuffer,h=i.floatVertexTextures,d=i.maxVertexUniforms,u=i.vertexTextures;let f=i.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"},x=["precision","isWebGL2","supportsVertexTextures","outputEncoding","instancing","instancingColor","map","mapEncoding","matcap","matcapEncoding","envMap","envMapMode","envMapEncoding","envMapCubeUV","lightMap","lightMapEncoding","aoMap","emissiveMap","emissiveMapEncoding","bumpMap","normalMap","objectSpaceNormalMap","tangentSpaceNormalMap","clearcoat","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","displacementMap","specularMap","specularIntensityMap","specularTintMap","specularTintMapEncoding","roughnessMap","metalnessMap","gradientMap","alphaMap","alphaTest","combine","vertexColors","vertexAlphas","vertexTangents","vertexUvs","uvsVertexOnly","fog","useFog","fogExp2","flatShading","sizeAttenuation","logarithmicDepthBuffer","skinning","maxBones","useVertexTexture","morphTargets","morphNormals","premultipliedAlpha","numDirLights","numPointLights","numSpotLights","numHemiLights","numRectAreaLights","numDirLightShadows","numPointLightShadows","numSpotLightShadows","shadowMapEnabled","shadowMapType","toneMapping","physicallyCorrectLights","doubleSided","flipSided","numClippingPlanes","numClipIntersection","depthPacking","dithering","format","sheenTint","transmission","transmissionMap","thicknessMap"];function y(b){const N=b.skeleton.bones;if(h)return 1024;{const R=Math.floor((d-20)/4),J=Math.min(R,N.length);return J0,se=b.clearcoat>0;return{isWebGL2:l,shaderID:G,shaderName:b.type,vertexShader:k,fragmentShader:j,defines:b.defines,isRawShaderMaterial:b.isRawShaderMaterial===!0,glslVersion:b.glslVersion,precision:f,instancing:R.isInstancedMesh===!0,instancingColor:R.isInstancedMesh===!0&&R.instanceColor!==null,supportsVertexTextures:u,outputEncoding:ue!==null?g(ue.texture):s.outputEncoding,map:!!b.map,mapEncoding:g(b.map),matcap:!!b.matcap,matcapEncoding:g(b.matcap),envMap:!!F,envMapMode:F&&F.mapping,envMapEncoding:g(F),envMapCubeUV:!!F&&(F.mapping===li||F.mapping===Zi),lightMap:!!b.lightMap,lightMapEncoding:g(b.lightMap),aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:g(b.emissiveMap),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,objectSpaceNormalMap:b.normalMapType===jc,tangentSpaceNormalMap:b.normalMapType===Un,clearcoat:se,clearcoatMap:se&&!!b.clearcoatMap,clearcoatRoughnessMap:se&&!!b.clearcoatRoughnessMap,clearcoatNormalMap:se&&!!b.clearcoatNormalMap,displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,specularIntensityMap:!!b.specularIntensityMap,specularTintMap:!!b.specularTintMap,specularTintMapEncoding:g(b.specularTintMap),alphaMap:!!b.alphaMap,alphaTest:ye,gradientMap:!!b.gradientMap,sheenTint:!!b.sheenTint&&(b.sheenTint.r>0||b.sheenTint.g>0||b.sheenTint.b>0),transmission:b.transmission>0,transmissionMap:!!b.transmissionMap,thicknessMap:!!b.thicknessMap,combine:b.combine,vertexTangents:!!b.normalMap&&!!R.geometry&&!!R.geometry.attributes.tangent,vertexColors:b.vertexColors,vertexAlphas:b.vertexColors===!0&&!!R.geometry&&!!R.geometry.attributes.color&&R.geometry.attributes.color.itemSize===4,vertexUvs:!!b.map||!!b.bumpMap||!!b.normalMap||!!b.specularMap||!!b.alphaMap||!!b.emissiveMap||!!b.roughnessMap||!!b.metalnessMap||!!b.clearcoatMap||!!b.clearcoatRoughnessMap||!!b.clearcoatNormalMap||!!b.displacementMap||!!b.transmissionMap||!!b.thicknessMap||!!b.specularIntensityMap||!!b.specularTintMap,uvsVertexOnly:!(!!b.map||!!b.bumpMap||!!b.normalMap||!!b.specularMap||!!b.alphaMap||!!b.emissiveMap||!!b.roughnessMap||!!b.metalnessMap||!!b.clearcoatNormalMap||b.transmission>0||!!b.transmissionMap||!!b.thicknessMap||!!b.specularIntensityMap||!!b.specularTintMap)&&!!b.displacementMap,fog:!!J,useFog:b.fog,fogExp2:J&&J.isFogExp2,flatShading:!!b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c,skinning:R.isSkinnedMesh===!0&&z>0,maxBones:z,useVertexTexture:h,morphTargets:!!R.geometry&&!!R.geometry.morphAttributes.position,morphNormals:!!R.geometry&&!!R.geometry.morphAttributes.normal,numDirLights:L.directional.length,numPointLights:L.point.length,numSpotLights:L.spot.length,numRectAreaLights:L.rectArea.length,numHemiLights:L.hemi.length,numDirLightShadows:L.directionalShadowMap.length,numPointLightShadows:L.pointShadowMap.length,numSpotLightShadows:L.spotShadowMap.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,format:b.format,dithering:b.dithering,shadowMapEnabled:s.shadowMap.enabled&&N.length>0,shadowMapType:s.shadowMap.type,toneMapping:b.toneMapped?s.toneMapping:ln,physicallyCorrectLights:s.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,doubleSided:b.side===Cn,flipSided:b.side===Xe,depthPacking:b.depthPacking!==void 0?b.depthPacking:!1,index0AttributeName:b.index0AttributeName,extensionDerivatives:b.extensions&&b.extensions.derivatives,extensionFragDepth:b.extensions&&b.extensions.fragDepth,extensionDrawBuffers:b.extensions&&b.extensions.drawBuffers,extensionShaderTextureLOD:b.extensions&&b.extensions.shaderTextureLOD,rendererExtensionFragDepth:l||n.has("EXT_frag_depth"),rendererExtensionDrawBuffers:l||n.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:l||n.has("EXT_shader_texture_lod"),customProgramCacheKey:b.customProgramCacheKey()}}function _(b){const L=[];if(b.shaderID?L.push(b.shaderID):(L.push(b.fragmentShader),L.push(b.vertexShader)),b.defines!==void 0)for(const N in b.defines)L.push(N),L.push(b.defines[N]);if(b.isRawShaderMaterial===!1){for(let N=0;N0?i.push(_):x.transparent===!0?r.push(_):n.push(_)}function h(f,p,x,y,g,m){const _=l(f,p,x,y,g,m);x.transmission>0?i.unshift(_):x.transparent===!0?r.unshift(_):n.unshift(_)}function d(f,p){n.length>1&&n.sort(f||Zx),i.length>1&&i.sort(p||Ku),r.length>1&&r.sort(p||Ku)}function u(){for(let f=t,p=e.length;f=e.get(i).length?(a=new eh(s),e.get(i).push(a)):a=e.get(i)[r],a}function n(){e=new WeakMap}return{get:t,dispose:n}}function Qx(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new M,color:new te};break;case"SpotLight":t={position:new M,direction:new M,color:new te,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new M,color:new te,distance:0,decay:0};break;case"HemisphereLight":t={direction:new M,skyColor:new te,groundColor:new te};break;case"RectAreaLight":t={color:new te,position:new M,halfWidth:new M,halfHeight:new M};break}return s[e.id]=t,t}}}function jx(){const s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}let Kx=0;function ey(s,e){return(e.castShadow?1:0)-(s.castShadow?1:0)}function ty(s,e){const t=new Qx,n=jx(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let h=0;h<9;h++)i.probe.push(new M);const r=new M,a=new he,o=new he;function l(h,d){let u=0,f=0,p=0;for(let N=0;N<9;N++)i.probe[N].set(0,0,0);let x=0,y=0,g=0,m=0,_=0,v=0,T=0,A=0;h.sort(ey);const b=d!==!0?Math.PI:1;for(let N=0,P=h.length;N0&&(e.isWebGL2||s.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=ee.LTC_FLOAT_1,i.rectAreaLTC2=ee.LTC_FLOAT_2):s.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=ee.LTC_HALF_1,i.rectAreaLTC2=ee.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=u,i.ambient[1]=f,i.ambient[2]=p;const L=i.hash;(L.directionalLength!==x||L.pointLength!==y||L.spotLength!==g||L.rectAreaLength!==m||L.hemiLength!==_||L.numDirectionalShadows!==v||L.numPointShadows!==T||L.numSpotShadows!==A)&&(i.directional.length=x,i.spot.length=g,i.rectArea.length=m,i.point.length=y,i.hemi.length=_,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=T,i.pointShadowMap.length=T,i.spotShadow.length=A,i.spotShadowMap.length=A,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=T,i.spotShadowMatrix.length=A,L.directionalLength=x,L.pointLength=y,L.spotLength=g,L.rectAreaLength=m,L.hemiLength=_,L.numDirectionalShadows=v,L.numPointShadows=T,L.numSpotShadows=A,i.version=Kx++)}function c(h,d){let u=0,f=0,p=0,x=0,y=0;const g=d.matrixWorldInverse;for(let m=0,_=h.length;m<_;m++){const v=h[m];if(v.isDirectionalLight){const T=i.directional[u];T.direction.setFromMatrixPosition(v.matrixWorld),r.setFromMatrixPosition(v.target.matrixWorld),T.direction.sub(r),T.direction.transformDirection(g),u++}else if(v.isSpotLight){const T=i.spot[p];T.position.setFromMatrixPosition(v.matrixWorld),T.position.applyMatrix4(g),T.direction.setFromMatrixPosition(v.matrixWorld),r.setFromMatrixPosition(v.target.matrixWorld),T.direction.sub(r),T.direction.transformDirection(g),p++}else if(v.isRectAreaLight){const T=i.rectArea[x];T.position.setFromMatrixPosition(v.matrixWorld),T.position.applyMatrix4(g),o.identity(),a.copy(v.matrixWorld),a.premultiply(g),o.extractRotation(a),T.halfWidth.set(v.width*.5,0,0),T.halfHeight.set(0,v.height*.5,0),T.halfWidth.applyMatrix4(o),T.halfHeight.applyMatrix4(o),x++}else if(v.isPointLight){const T=i.point[f];T.position.setFromMatrixPosition(v.matrixWorld),T.position.applyMatrix4(g),f++}else if(v.isHemisphereLight){const T=i.hemi[y];T.direction.setFromMatrixPosition(v.matrixWorld),T.direction.transformDirection(g),T.direction.normalize(),y++}}}return{setup:l,setupView:c,state:i}}function th(s,e){const t=new ty(s,e),n=[],i=[];function r(){n.length=0,i.length=0}function a(d){n.push(d)}function o(d){i.push(d)}function l(d){t.setup(n,d)}function c(d){t.setupView(n,d)}return{init:r,state:{lightsArray:n,shadowsArray:i,lights:t},setupLights:l,setupLightsView:c,pushLight:a,pushShadow:o}}function ny(s,e){let t=new WeakMap;function n(r,a=0){let o;return t.has(r)===!1?(o=new th(s,e),t.set(r,[o])):a>=t.get(r).length?(o=new th(s,e),t.get(r).push(o)):o=t.get(r)[a],o}function i(){t=new WeakMap}return{get:n,dispose:i}}class Es extends it{constructor(e){super();this.type="MeshDepthMaterial",this.depthPacking=$c,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}Es.prototype.isMeshDepthMaterial=!0;class As extends it{constructor(e){super();this.type="MeshDistanceMaterial",this.referencePosition=new M,this.nearDistance=1,this.farDistance=1e3,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.setValues(e)}copy(e){return super.copy(e),this.referencePosition.copy(e.referencePosition),this.nearDistance=e.nearDistance,this.farDistance=e.farDistance,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}As.prototype.isMeshDistanceMaterial=!0;var iy=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +uniform float samples; +#include +void main() { + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`,ry=`void main() { + gl_Position = vec4( position, 1.0 ); +}`;function nh(s,e,t){let n=new hr;const i=new Y,r=new Y,a=new Oe,o=new Es({depthPacking:Qc}),l=new As,c={},h=t.maxTextureSize,d={0:Xe,1:Rn,2:Cn},u=new en({uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4},samples:{value:8}},vertexShader:ry,fragmentShader:iy}),f=u.clone();f.defines.HORIZONTAL_PASS=1;const p=new _e;p.setAttribute("position",new Be(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new je(p,u),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=da,this.render=function(v,T,A){if(y.enabled===!1||y.autoUpdate===!1&&y.needsUpdate===!1||v.length===0)return;const b=s.getRenderTarget(),L=s.getActiveCubeFace(),N=s.getActiveMipmapLevel(),P=s.state;P.setBlending(qt),P.buffers.color.setClear(1,1,1,1),P.buffers.depth.setTest(!0),P.setScissorTest(!1);for(let R=0,J=v.length;Rh||i.y>h)&&(i.x>h&&(r.x=Math.floor(h/G.x),i.x=r.x*G.x,F.mapSize.x=r.x),i.y>h&&(r.y=Math.floor(h/G.y),i.y=r.y*G.y,F.mapSize.y=r.y)),F.map===null&&!F.isPointLightShadow&&this.type===ri){const k={minFilter:Ke,magFilter:Ke,format:xt};F.map=new Lt(i.x,i.y,k),F.map.texture.name=B.name+".shadowMap",F.mapPass=new Lt(i.x,i.y,k),F.camera.updateProjectionMatrix()}if(F.map===null){const k={minFilter:Qe,magFilter:Qe,format:xt};F.map=new Lt(i.x,i.y,k),F.map.texture.name=B.name+".shadowMap",F.camera.updateProjectionMatrix()}s.setRenderTarget(F.map),s.clear();const z=F.getViewportCount();for(let k=0;k0){const B=R.uuid,F=A.uuid;let G=c[B];G===void 0&&(G={},c[B]=G);let z=G[F];z===void 0&&(z=R.clone(),G[F]=z),R=z}return R.visible=A.visible,R.wireframe=A.wireframe,P===ri?R.side=A.shadowSide!==null?A.shadowSide:A.side:R.side=A.shadowSide!==null?A.shadowSide:d[A.side],R.alphaMap=A.alphaMap,R.alphaTest=A.alphaTest,R.clipShadows=A.clipShadows,R.clippingPlanes=A.clippingPlanes,R.clipIntersection=A.clipIntersection,R.displacementMap=A.displacementMap,R.displacementScale=A.displacementScale,R.displacementBias=A.displacementBias,R.wireframeLinewidth=A.wireframeLinewidth,R.linewidth=A.linewidth,b.isPointLight===!0&&R.isMeshDistanceMaterial===!0&&(R.referencePosition.setFromMatrixPosition(b.matrixWorld),R.nearDistance=L,R.farDistance=N),R}function _(v,T,A,b,L){if(v.visible===!1)return;if(v.layers.test(T.layers)&&(v.isMesh||v.isLine||v.isPoints)&&(v.castShadow||v.receiveShadow&&L===ri)&&(!v.frustumCulled||n.intersectsObject(v))){v.modelViewMatrix.multiplyMatrices(A.matrixWorldInverse,v.matrixWorld);const R=e.update(v),J=v.material;if(Array.isArray(J)){const B=R.groups;for(let F=0,G=B.length;F=1):G.indexOf("OpenGL ES")!==-1&&(F=parseFloat(/^OpenGL ES (\d)/.exec(G)[1]),B=F>=2);let z=null,k={};const j=s.getParameter(3088),ue=s.getParameter(2978),ye=new Oe().fromArray(j),se=new Oe().fromArray(ue);function Ee(C,re,W){const le=new Uint8Array(4),fe=s.createTexture();s.bindTexture(C,fe),s.texParameteri(C,10241,9728),s.texParameteri(C,10240,9728);for(let De=0;DeX||E.height>X)&&(ne=X/Math.max(E.width,E.height)),ne<1||S===!0)if(typeof HTMLImageElement!="undefined"&&E instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&E instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&E instanceof ImageBitmap){const oe=S?tu:Math.floor,we=oe(ne*E.width),xe=oe(ne*E.height);f===void 0&&(f=x(we,xe));const Ae=H?x(we,xe):f;return Ae.width=we,Ae.height=xe,Ae.getContext("2d").drawImage(E,0,0,we,xe),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+E.width+"x"+E.height+") to ("+we+"x"+xe+")."),Ae}else return"data"in E&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+E.width+"x"+E.height+")."),E;return E}function g(E){return Ua(E.width)&&Ua(E.height)}function m(E){return o?!1:E.wrapS!==lt||E.wrapT!==lt||E.minFilter!==Qe&&E.minFilter!==Ke}function _(E,S){return E.generateMipmaps&&S&&E.minFilter!==Qe&&E.minFilter!==Ke}function v(E,S,H,X,ne=1){s.generateMipmap(E);const oe=n.get(S);oe.__maxMipLevel=Math.log2(Math.max(H,X,ne))}function T(E,S,H){if(o===!1)return S;if(E!==null){if(s[E]!==void 0)return s[E];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+E+"'")}let X=S;return S===6403&&(H===5126&&(X=33326),H===5131&&(X=33325),H===5121&&(X=33321)),S===6407&&(H===5126&&(X=34837),H===5131&&(X=34843),H===5121&&(X=32849)),S===6408&&(H===5126&&(X=34836),H===5131&&(X=34842),H===5121&&(X=32856)),(X===33325||X===33326||X===34842||X===34836)&&e.get("EXT_color_buffer_float"),X}function A(E){return E===Qe||E===Zr||E===$r?9728:9729}function b(E){const S=E.target;S.removeEventListener("dispose",b),N(S),S.isVideoTexture&&u.delete(S),a.memory.textures--}function L(E){const S=E.target;S.removeEventListener("dispose",L),P(S)}function N(E){const S=n.get(E);S.__webglInit!==void 0&&(s.deleteTexture(S.__webglTexture),n.remove(E))}function P(E){const S=E.texture,H=n.get(E),X=n.get(S);if(!!E){if(X.__webglTexture!==void 0&&(s.deleteTexture(X.__webglTexture),a.memory.textures--),E.depthTexture&&E.depthTexture.dispose(),E.isWebGLCubeRenderTarget)for(let ne=0;ne<6;ne++)s.deleteFramebuffer(H.__webglFramebuffer[ne]),H.__webglDepthbuffer&&s.deleteRenderbuffer(H.__webglDepthbuffer[ne]);else s.deleteFramebuffer(H.__webglFramebuffer),H.__webglDepthbuffer&&s.deleteRenderbuffer(H.__webglDepthbuffer),H.__webglMultisampledFramebuffer&&s.deleteFramebuffer(H.__webglMultisampledFramebuffer),H.__webglColorRenderbuffer&&s.deleteRenderbuffer(H.__webglColorRenderbuffer),H.__webglDepthRenderbuffer&&s.deleteRenderbuffer(H.__webglDepthRenderbuffer);if(E.isWebGLMultipleRenderTargets)for(let ne=0,oe=S.length;ne=l&&console.warn("THREE.WebGLTextures: Trying to use "+E+" texture units while this GPU supports only "+l),R+=1,E}function F(E,S){const H=n.get(E);if(E.isVideoTexture&&V(E),E.version>0&&H.__version!==E.version){const X=E.image;if(X===void 0)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");else if(X.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Ee(H,E,S);return}}t.activeTexture(33984+S),t.bindTexture(3553,H.__webglTexture)}function G(E,S){const H=n.get(E);if(E.version>0&&H.__version!==E.version){Ee(H,E,S);return}t.activeTexture(33984+S),t.bindTexture(35866,H.__webglTexture)}function z(E,S){const H=n.get(E);if(E.version>0&&H.__version!==E.version){Ee(H,E,S);return}t.activeTexture(33984+S),t.bindTexture(32879,H.__webglTexture)}function k(E,S){const H=n.get(E);if(E.version>0&&H.__version!==E.version){q(H,E,S);return}t.activeTexture(33984+S),t.bindTexture(34067,H.__webglTexture)}const j={[$i]:10497,[lt]:33071,[Qi]:33648},ue={[Qe]:9728,[Zr]:9984,[$r]:9986,[Ke]:9729,[ba]:9985,[In]:9987};function ye(E,S,H){if(H?(s.texParameteri(E,10242,j[S.wrapS]),s.texParameteri(E,10243,j[S.wrapT]),(E===32879||E===35866)&&s.texParameteri(E,32882,j[S.wrapR]),s.texParameteri(E,10240,ue[S.magFilter]),s.texParameteri(E,10241,ue[S.minFilter])):(s.texParameteri(E,10242,33071),s.texParameteri(E,10243,33071),(E===32879||E===35866)&&s.texParameteri(E,32882,33071),(S.wrapS!==lt||S.wrapT!==lt)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),s.texParameteri(E,10240,A(S.magFilter)),s.texParameteri(E,10241,A(S.minFilter)),S.minFilter!==Qe&&S.minFilter!==Ke&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),e.has("EXT_texture_filter_anisotropic")===!0){const X=e.get("EXT_texture_filter_anisotropic");if(S.type===Xt&&e.has("OES_texture_float_linear")===!1||o===!1&&S.type===Fn&&e.has("OES_texture_half_float_linear")===!1)return;(S.anisotropy>1||n.get(S).__currentAnisotropy)&&(s.texParameterf(E,X.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(S.anisotropy,i.getMaxAnisotropy())),n.get(S).__currentAnisotropy=S.anisotropy)}}function se(E,S){E.__webglInit===void 0&&(E.__webglInit=!0,S.addEventListener("dispose",b),E.__webglTexture=s.createTexture(),a.memory.textures++)}function Ee(E,S,H){let X=3553;S.isDataTexture2DArray&&(X=35866),S.isDataTexture3D&&(X=32879),se(E,S),t.activeTexture(33984+H),t.bindTexture(X,E.__webglTexture),s.pixelStorei(37440,S.flipY),s.pixelStorei(37441,S.premultiplyAlpha),s.pixelStorei(3317,S.unpackAlignment),s.pixelStorei(37443,0);const ne=m(S)&&g(S.image)===!1,oe=y(S.image,ne,!1,h),we=g(oe)||o,xe=r.convert(S.format);let Ae=r.convert(S.type),ge=T(S.internalFormat,xe,Ae);ye(X,S,we);let C;const re=S.mipmaps;if(S.isDepthTexture)ge=6402,o?S.type===Xt?ge=36012:S.type===Ki?ge=33190:S.type===ci?ge=35056:ge=33189:S.type===Xt&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),S.format===Bn&&ge===6402&&S.type!==ji&&S.type!==Ki&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),S.type=ji,Ae=r.convert(S.type)),S.format===ui&&ge===6402&&(ge=34041,S.type!==ci&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),S.type=ci,Ae=r.convert(S.type))),t.texImage2D(3553,0,ge,oe.width,oe.height,0,xe,Ae,null);else if(S.isDataTexture)if(re.length>0&&we){for(let W=0,le=re.length;W0&&we){for(let W=0,le=re.length;Wf+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&u<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));return o!==null&&(o.visible=i!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=a!==null),this}}class ly extends cn{constructor(e,t){super();const n=this,i=e.state;let r=null,a=1,o=null,l="local-floor",c=null,h=null,d=null,u=null,f=null,p=!1,x=null,y=null,g=null,m=null,_=null,v=null;const T=[],A=new Map,b=new st;b.layers.enable(1),b.viewport=new Oe;const L=new st;L.layers.enable(2),L.viewport=new Oe;const N=[b,L],P=new vo;P.layers.enable(1),P.layers.enable(2);let R=null,J=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let Q=T[q];return Q===void 0&&(Q=new _o,T[q]=Q),Q.getTargetRaySpace()},this.getControllerGrip=function(q){let Q=T[q];return Q===void 0&&(Q=new _o,T[q]=Q),Q.getGripSpace()},this.getHand=function(q){let Q=T[q];return Q===void 0&&(Q=new _o,T[q]=Q),Q.getHandSpace()};function B(q){const Q=A.get(q.inputSource);Q&&Q.dispatchEvent({type:q.type,data:q.inputSource})}function F(){A.forEach(function(q,Q){q.disconnect(Q)}),A.clear(),R=null,J=null,i.bindXRFramebuffer(null),e.setRenderTarget(e.getRenderTarget()),d&&t.deleteFramebuffer(d),x&&t.deleteFramebuffer(x),y&&t.deleteRenderbuffer(y),g&&t.deleteRenderbuffer(g),d=null,x=null,y=null,g=null,f=null,u=null,h=null,r=null,Ee.stop(),n.isPresenting=!1,n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){a=q,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){l=q,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return o},this.getBaseLayer=function(){return u!==null?u:f},this.getBinding=function(){return h},this.getFrame=function(){return m},this.getSession=function(){return r},this.setSession=async function(q){if(r=q,r!==null){r.addEventListener("select",B),r.addEventListener("selectstart",B),r.addEventListener("selectend",B),r.addEventListener("squeeze",B),r.addEventListener("squeezestart",B),r.addEventListener("squeezeend",B),r.addEventListener("end",F),r.addEventListener("inputsourceschange",G);const Q=t.getContextAttributes();if(Q.xrCompatible!==!0&&await t.makeXRCompatible(),r.renderState.layers===void 0){const pe={antialias:Q.antialias,alpha:Q.alpha,depth:Q.depth,stencil:Q.stencil,framebufferScaleFactor:a};f=new XRWebGLLayer(r,t,pe),r.updateRenderState({baseLayer:f})}else if(t instanceof WebGLRenderingContext){const pe={antialias:!0,alpha:Q.alpha,depth:Q.depth,stencil:Q.stencil,framebufferScaleFactor:a};f=new XRWebGLLayer(r,t,pe),r.updateRenderState({layers:[f]})}else{p=Q.antialias;let pe=null;Q.depth&&(v=256,Q.stencil&&(v|=1024),_=Q.stencil?33306:36096,pe=Q.stencil?35056:33190);const U={colorFormat:Q.alpha?32856:32849,depthFormat:pe,scaleFactor:a};h=new XRWebGLBinding(r,t),u=h.createProjectionLayer(U),d=t.createFramebuffer(),r.updateRenderState({layers:[u]}),p&&(x=t.createFramebuffer(),y=t.createRenderbuffer(),t.bindRenderbuffer(36161,y),t.renderbufferStorageMultisample(36161,4,32856,u.textureWidth,u.textureHeight),i.bindFramebuffer(36160,x),t.framebufferRenderbuffer(36160,36064,36161,y),t.bindRenderbuffer(36161,null),pe!==null&&(g=t.createRenderbuffer(),t.bindRenderbuffer(36161,g),t.renderbufferStorageMultisample(36161,4,pe,u.textureWidth,u.textureHeight),t.framebufferRenderbuffer(36160,_,36161,g),t.bindRenderbuffer(36161,null)),i.bindFramebuffer(36160,null))}o=await r.requestReferenceSpace(l),Ee.setContext(r),Ee.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}};function G(q){const Q=r.inputSources;for(let pe=0;pe0&&(g.alphaTest.value=m.alphaTest);const _=s.get(m).envMap;if(_){g.envMap.value=_,g.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio;const A=s.get(_).__maxMipLevel;A!==void 0&&(g.maxMipLevel.value=A)}m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity);let v;m.map?v=m.map:m.specularMap?v=m.specularMap:m.displacementMap?v=m.displacementMap:m.normalMap?v=m.normalMap:m.bumpMap?v=m.bumpMap:m.roughnessMap?v=m.roughnessMap:m.metalnessMap?v=m.metalnessMap:m.alphaMap?v=m.alphaMap:m.emissiveMap?v=m.emissiveMap:m.clearcoatMap?v=m.clearcoatMap:m.clearcoatNormalMap?v=m.clearcoatNormalMap:m.clearcoatRoughnessMap?v=m.clearcoatRoughnessMap:m.specularIntensityMap?v=m.specularIntensityMap:m.specularTintMap?v=m.specularTintMap:m.transmissionMap?v=m.transmissionMap:m.thicknessMap&&(v=m.thicknessMap),v!==void 0&&(v.isWebGLRenderTarget&&(v=v.texture),v.matrixAutoUpdate===!0&&v.updateMatrix(),g.uvTransform.value.copy(v.matrix));let T;m.aoMap?T=m.aoMap:m.lightMap&&(T=m.lightMap),T!==void 0&&(T.isWebGLRenderTarget&&(T=T.texture),T.matrixAutoUpdate===!0&&T.updateMatrix(),g.uv2Transform.value.copy(T.matrix))}function i(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity}function r(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function a(g,m,_,v){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*_,g.scale.value=v*.5,m.map&&(g.map.value=m.map),m.alphaMap&&(g.alphaMap.value=m.alphaMap),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);let T;m.map?T=m.map:m.alphaMap&&(T=m.alphaMap),T!==void 0&&(T.matrixAutoUpdate===!0&&T.updateMatrix(),g.uvTransform.value.copy(T.matrix))}function o(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map),m.alphaMap&&(g.alphaMap.value=m.alphaMap),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);let _;m.map?_=m.map:m.alphaMap&&(_=m.alphaMap),_!==void 0&&(_.matrixAutoUpdate===!0&&_.updateMatrix(),g.uvTransform.value.copy(_.matrix))}function l(g,m){m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap)}function c(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap),m.bumpMap&&(g.bumpMap.value=m.bumpMap,g.bumpScale.value=m.bumpScale,m.side===Xe&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,g.normalScale.value.copy(m.normalScale),m.side===Xe&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias)}function h(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap),m.bumpMap&&(g.bumpMap.value=m.bumpMap,g.bumpScale.value=m.bumpScale,m.side===Xe&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,g.normalScale.value.copy(m.normalScale),m.side===Xe&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias)}function d(g,m){g.roughness.value=m.roughness,g.metalness.value=m.metalness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap),m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap),m.bumpMap&&(g.bumpMap.value=m.bumpMap,g.bumpScale.value=m.bumpScale,m.side===Xe&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,g.normalScale.value.copy(m.normalScale),m.side===Xe&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),s.get(m).envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function u(g,m,_){d(g,m),g.ior.value=m.ior,m.sheenTint&&g.sheenTint.value.copy(m.sheenTint),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap),m.clearcoatNormalMap&&(g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),g.clearcoatNormalMap.value=m.clearcoatNormalMap,m.side===Xe&&g.clearcoatNormalScale.value.negate())),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap),g.attenuationDistance.value=m.attenuationDistance,g.attenuationTint.value.copy(m.attenuationTint)),g.specularIntensity.value=m.specularIntensity,g.specularTint.value.copy(m.specularTint),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap),m.specularTintMap&&(g.specularTintMap.value=m.specularTintMap)}function f(g,m){m.matcap&&(g.matcap.value=m.matcap),m.bumpMap&&(g.bumpMap.value=m.bumpMap,g.bumpScale.value=m.bumpScale,m.side===Xe&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,g.normalScale.value.copy(m.normalScale),m.side===Xe&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias)}function p(g,m){m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias)}function x(g,m){m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),g.referencePosition.value.copy(m.referencePosition),g.nearDistance.value=m.nearDistance,g.farDistance.value=m.farDistance}function y(g,m){m.bumpMap&&(g.bumpMap.value=m.bumpMap,g.bumpScale.value=m.bumpScale,m.side===Xe&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,g.normalScale.value.copy(m.normalScale),m.side===Xe&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias)}return{refreshFogUniforms:e,refreshMaterialUniforms:t}}function uy(){const s=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");return s.style.display="block",s}function He(s={}){const e=s.canvas!==void 0?s.canvas:uy(),t=s.context!==void 0?s.context:null,n=s.alpha!==void 0?s.alpha:!1,i=s.depth!==void 0?s.depth:!0,r=s.stencil!==void 0?s.stencil:!0,a=s.antialias!==void 0?s.antialias:!1,o=s.premultipliedAlpha!==void 0?s.premultipliedAlpha:!0,l=s.preserveDrawingBuffer!==void 0?s.preserveDrawingBuffer:!1,c=s.powerPreference!==void 0?s.powerPreference:"default",h=s.failIfMajorPerformanceCaveat!==void 0?s.failIfMajorPerformanceCaveat:!1;let d=null,u=null;const f=[],p=[];this.domElement=e,this.debug={checkShaderErrors:!0},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.outputEncoding=yt,this.physicallyCorrectLights=!1,this.toneMapping=ln,this.toneMappingExposure=1;const x=this;let y=!1,g=0,m=0,_=null,v=-1,T=null;const A=new Oe,b=new Oe;let L=null,N=e.width,P=e.height,R=1,J=null,B=null;const F=new Oe(0,0,N,P),G=new Oe(0,0,N,P);let z=!1;const k=[],j=new hr;let ue=!1,ye=!1,se=null;const Ee=new he,q=new M,Q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function pe(){return _===null?R:1}let U=t;function ve(w,D){for(let I=0;I0?u=p[p.length-1]:u=null,f.pop(),f.length>0?d=f[f.length-1]:d=null};function _l(w,D,I,O){if(w.visible===!1)return;if(w.layers.test(D.layers)){if(w.isGroup)I=w.renderOrder;else if(w.isLOD)w.autoUpdate===!0&&w.update(D);else if(w.isLight)u.pushLight(w),w.castShadow&&u.pushShadow(w);else if(w.isSprite){if(!w.frustumCulled||j.intersectsSprite(w)){O&&q.setFromMatrixPosition(w.matrixWorld).applyMatrix4(Ee);const Me=S.update(w),be=w.material;be.visible&&d.push(w,Me,be,I,q.z,null)}}else if(w.isImmediateRenderObject)O&&q.setFromMatrixPosition(w.matrixWorld).applyMatrix4(Ee),d.push(w,null,w.material,I,q.z,null);else if((w.isMesh||w.isLine||w.isPoints)&&(w.isSkinnedMesh&&w.skeleton.frame!==Le.render.frame&&(w.skeleton.update(),w.skeleton.frame=Le.render.frame),!w.frustumCulled||j.intersectsObject(w))){O&&q.setFromMatrixPosition(w.matrixWorld).applyMatrix4(Ee);const Me=S.update(w),be=w.material;if(Array.isArray(be)){const Ie=Me.groups;for(let Ue=0,Fe=Ie.length;Ue0&&zd(Z,D,I),O&&de.viewport(A.copy(O)),Z.length>0&&Xr(Z,D,I),Re.length>0&&Xr(Re,D,I),Me.length>0&&Xr(Me,D,I)}function zd(w,D,I){if(se===null){const Me=a===!0&&ce.isWebGL2===!0?Ha:Lt;se=new Me(1024,1024,{generateMipmaps:!0,type:W.convert(Fn)!==null?Fn:Dn,minFilter:In,magFilter:Qe,wrapS:lt,wrapT:lt})}const O=x.getRenderTarget();x.setRenderTarget(se),x.clear();const Z=x.toneMapping;x.toneMapping=ln,Xr(w,D,I),x.toneMapping=Z,$.updateMultisampleRenderTarget(se),$.updateRenderTargetMipmap(se),x.setRenderTarget(O)}function Xr(w,D,I){const O=D.isScene===!0?D.overrideMaterial:null;for(let Z=0,Re=w.length;Z=0&&D<=w.width-O&&I>=0&&I<=w.height-Z&&U.readPixels(D,I,O,Z,W.convert(Ue),W.convert(Fe),Re):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{const Ie=_!==null?V.get(_).__webglFramebuffer:null;de.bindFramebuffer(36160,Ie)}}},this.copyFramebufferToTexture=function(w,D,I=0){const O=Math.pow(2,-I),Z=Math.floor(D.image.width*O),Re=Math.floor(D.image.height*O);let Me=W.convert(D.format);ce.isWebGL2&&(Me===6407&&(Me=32849),Me===6408&&(Me=32856)),$.setTexture2D(D,0),U.copyTexImage2D(3553,I,Me,w.x,w.y,Z,Re,0),de.unbindTexture()},this.copyTextureToTexture=function(w,D,I,O=0){const Z=D.image.width,Re=D.image.height,Me=W.convert(I.format),be=W.convert(I.type);$.setTexture2D(I,0),U.pixelStorei(37440,I.flipY),U.pixelStorei(37441,I.premultiplyAlpha),U.pixelStorei(3317,I.unpackAlignment),D.isDataTexture?U.texSubImage2D(3553,O,w.x,w.y,Z,Re,Me,be,D.image.data):D.isCompressedTexture?U.compressedTexSubImage2D(3553,O,w.x,w.y,D.mipmaps[0].width,D.mipmaps[0].height,Me,D.mipmaps[0].data):U.texSubImage2D(3553,O,w.x,w.y,Me,be,D.image),O===0&&I.generateMipmaps&&U.generateMipmap(3553),de.unbindTexture()},this.copyTextureToTexture3D=function(w,D,I,O,Z=0){if(x.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const Re=w.max.x-w.min.x+1,Me=w.max.y-w.min.y+1,be=w.max.z-w.min.z+1,Ie=W.convert(O.format),Ue=W.convert(O.type);let Fe;if(O.isDataTexture3D)$.setTexture3D(O,0),Fe=32879;else if(O.isDataTexture2DArray)$.setTexture2DArray(O,0),Fe=35866;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}U.pixelStorei(37440,O.flipY),U.pixelStorei(37441,O.premultiplyAlpha),U.pixelStorei(3317,O.unpackAlignment);const ze=U.getParameter(3314),Te=U.getParameter(32878),An=U.getParameter(3316),$e=U.getParameter(3315),an=U.getParameter(32877),At=I.isCompressedTexture?I.mipmaps[0]:I.image;U.pixelStorei(3314,At.width),U.pixelStorei(32878,At.height),U.pixelStorei(3316,w.min.x),U.pixelStorei(3315,w.min.y),U.pixelStorei(32877,w.min.z),I.isDataTexture||I.isDataTexture3D?U.texSubImage3D(Fe,Z,D.x,D.y,D.z,Re,Me,be,Ie,Ue,At.data):I.isCompressedTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),U.compressedTexSubImage3D(Fe,Z,D.x,D.y,D.z,Re,Me,be,Ie,At.data)):U.texSubImage3D(Fe,Z,D.x,D.y,D.z,Re,Me,be,Ie,Ue,At),U.pixelStorei(3314,ze),U.pixelStorei(32878,Te),U.pixelStorei(3316,An),U.pixelStorei(3315,$e),U.pixelStorei(32877,an),Z===0&&O.generateMipmaps&&U.generateMipmap(Fe),de.unbindTexture()},this.initTexture=function(w){$.setTexture2D(w,0),de.unbindTexture()},this.resetState=function(){g=0,m=0,_=null,de.reset(),le.reset()},typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}class rh extends He{}rh.prototype.isWebGL1Renderer=!0;class mr{constructor(e,t=25e-5){this.name="",this.color=new te(e),this.density=t}clone(){return new mr(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}}mr.prototype.isFogExp2=!0;class gr{constructor(e,t=1,n=1e3){this.name="",this.color=new te(e),this.near=t,this.far=n}clone(){return new gr(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}}gr.prototype.isFog=!0;class Ls extends Ce{constructor(){super();this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.autoUpdate=e.autoUpdate,this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t}}Ls.prototype.isScene=!0;class Xn{constructor(e,t){this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=hi,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=bt()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;ie.far||t.push({distance:l,point:xr.clone(),uv:Ye.getUV(xr,Cs,vr,Ps,ah,bo,oh,new Y),face:null,object:this})}copy(e){return super.copy(e),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}Is.prototype.isSprite=!0;function Ds(s,e,t,n,i,r){Oi.subVectors(s,t).addScalar(.5).multiply(n),i!==void 0?(yr.x=r*Oi.x-i*Oi.y,yr.y=i*Oi.x+r*Oi.y):yr.copy(Oi),s.copy(e),s.x+=yr.x,s.y+=yr.y,s.applyMatrix4(sh)}const Fs=new M,lh=new M;class ch extends Ce{constructor(){super();this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let n=0,i=t.length;n0){let n,i;for(n=1,i=t.length;n0){Fs.setFromMatrixPosition(this.matrixWorld);const i=e.ray.origin.distanceTo(Fs);this.getObjectForDistance(i).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Fs.setFromMatrixPosition(e.matrixWorld),lh.setFromMatrixPosition(this.matrixWorld);const n=Fs.distanceTo(lh)/e.zoom;t[0].object.visible=!0;let i,r;for(i=1,r=t.length;i=t[i].distance;i++)t[i-1].object.visible=!1,t[i].object.visible=!0;for(this._currentLevel=i-1;il)continue;u.applyMatrix4(this.matrixWorld);const L=e.ray.origin.distanceTo(u);Le.far||t.push({distance:L,point:d.clone().applyMatrix4(this.matrixWorld),index:_,face:null,faceIndex:null,object:this})}}else{const g=Math.max(0,a.start),m=Math.min(y.count,a.start+a.count);for(let _=g,v=m-1;_l)continue;u.applyMatrix4(this.matrixWorld);const A=e.ray.origin.distanceTo(u);Ae.far||t.push({distance:A,point:d.clone().applyMatrix4(this.matrixWorld),index:_,face:null,faceIndex:null,object:this})}}}else n.isGeometry&&console.error("THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.")}updateMorphTargets(){const e=this.geometry;if(e.isBufferGeometry){const t=e.morphAttributes,n=Object.keys(t);if(n.length>0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r0&&console.error("THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}tn.prototype.isLine=!0;const _h=new M,bh=new M;class _t extends tn{constructor(e,t){super(e,t);this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.isBufferGeometry)if(e.index===null){const t=e.attributes.position,n=[];for(let i=0,r=t.count;i0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=i.length;r0&&console.error("THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.")}}}br.prototype.isPoints=!0;function wh(s,e,t,n,i,r,a){const o=To.distanceSqToPoint(s);if(oi.far)return;r.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,object:a})}}class Sh extends tt{constructor(e,t,n,i,r,a,o,l,c){super(e,t,n,i,r,a,o,l,c);this.format=o!==void 0?o:Yt,this.minFilter=a!==void 0?a:Ke,this.magFilter=r!==void 0?r:Ke,this.generateMipmaps=!1;const h=this;function d(){h.needsUpdate=!0,e.requestVideoFrameCallback(d)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(d)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}Sh.prototype.isVideoTexture=!0;class Eo extends tt{constructor(e,t,n,i,r,a,o,l,c,h,d,u){super(null,a,o,l,c,h,i,r,d,u);this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}Eo.prototype.isCompressedTexture=!0;class Th extends tt{constructor(e,t,n,i,r,a,o,l,c){super(e,t,n,i,r,a,o,l,c);this.needsUpdate=!0}}Th.prototype.isCanvasTexture=!0;class Eh extends tt{constructor(e,t,n,i,r,a,o,l,c,h){if(h=h!==void 0?h:Bn,h!==Bn&&h!==ui)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n===void 0&&h===Bn&&(n=ji),n===void 0&&h===ui&&(n=ci),super(null,i,r,a,o,l,h,n,c),this.image={width:e,height:t},this.magFilter=o!==void 0?o:Qe,this.minFilter=l!==void 0?l:Qe,this.flipY=!1,this.generateMipmaps=!1}}Eh.prototype.isDepthTexture=!0;class Mr extends _e{constructor(e=1,t=8,n=0,i=Math.PI*2){super();this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:i},t=Math.max(3,t);const r=[],a=[],o=[],l=[],c=new M,h=new Y;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let d=0,u=3;d<=t;d++,u+=3){const f=n+d/t*i;c.x=e*Math.cos(f),c.y=e*Math.sin(f),a.push(c.x,c.y,c.z),o.push(0,0,1),h.x=(a[u]/e+1)/2,h.y=(a[u+1]/e+1)/2,l.push(h.x,h.y)}for(let d=1;d<=t;d++)r.push(d,d+1,0);this.setIndex(r),this.setAttribute("position",new ae(a,3)),this.setAttribute("normal",new ae(o,3)),this.setAttribute("uv",new ae(l,2))}static fromJSON(e){return new Mr(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class $n extends _e{constructor(e=1,t=1,n=1,i=8,r=1,a=!1,o=0,l=Math.PI*2){super();this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:r,openEnded:a,thetaStart:o,thetaLength:l};const c=this;i=Math.floor(i),r=Math.floor(r);const h=[],d=[],u=[],f=[];let p=0;const x=[],y=n/2;let g=0;m(),a===!1&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(h),this.setAttribute("position",new ae(d,3)),this.setAttribute("normal",new ae(u,3)),this.setAttribute("uv",new ae(f,2));function m(){const v=new M,T=new M;let A=0;const b=(t-e)/n;for(let L=0;L<=r;L++){const N=[],P=L/r,R=P*(t-e)+e;for(let J=0;J<=i;J++){const B=J/i,F=B*l+o,G=Math.sin(F),z=Math.cos(F);T.x=R*G,T.y=-P*n+y,T.z=R*z,d.push(T.x,T.y,T.z),v.set(G,b,z).normalize(),u.push(v.x,v.y,v.z),f.push(B,1-P),N.push(p++)}x.push(N)}for(let L=0;L.9&&b<.1&&(_<.2&&(a[m+0]+=1),v<.2&&(a[m+2]+=1),T<.2&&(a[m+4]+=1))}}function u(m){r.push(m.x,m.y,m.z)}function f(m,_){const v=m*3;_.x=e[v+0],_.y=e[v+1],_.z=e[v+2]}function p(){const m=new M,_=new M,v=new M,T=new M,A=new Y,b=new Y,L=new Y;for(let N=0,P=0;N0)l=i-1;else{l=i;break}if(i=l,n[i]===a)return i/(r-1);const h=n[i],u=n[i+1]-h,f=(a-h)/u;return(i+f)/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const a=this.getPoint(i),o=this.getPoint(r),l=t||(a.isVector2?new Y:new M);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t){const n=new M,i=[],r=[],a=[],o=new M,l=new he;for(let f=0;f<=e;f++){const p=f/e;i[f]=this.getTangentAt(p,new M),i[f].normalize()}r[0]=new M,a[0]=new M;let c=Number.MAX_VALUE;const h=Math.abs(i[0].x),d=Math.abs(i[0].y),u=Math.abs(i[0].z);h<=c&&(c=h,n.set(1,0,0)),d<=c&&(c=d,n.set(0,1,0)),u<=c&&n.set(0,0,1),o.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],o),a[0].crossVectors(i[0],r[0]);for(let f=1;f<=e;f++){if(r[f]=r[f-1].clone(),a[f]=a[f-1].clone(),o.crossVectors(i[f-1],i[f]),o.length()>Number.EPSILON){o.normalize();const p=Math.acos(ut(i[f-1].dot(i[f]),-1,1));r[f].applyMatrix4(l.makeRotationAxis(o,p))}a[f].crossVectors(i[f],r[f])}if(t===!0){let f=Math.acos(ut(r[0].dot(r[e]),-1,1));f/=e,i[0].dot(o.crossVectors(r[0],r[e]))>0&&(f=-f);for(let p=1;p<=e;p++)r[p].applyMatrix4(l.makeRotationAxis(i[p],f*p)),a[p].crossVectors(i[p],r[p])}return{tangents:i,normals:r,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Tr extends Tt{constructor(e=0,t=0,n=1,i=1,r=0,a=Math.PI*2,o=!1,l=0){super();this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t){const n=t||new Y,i=Math.PI*2;let r=this.aEndAngle-this.aStartAngle;const a=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(o)/r)+1)*r:l===0&&o===r-1&&(o=r-2,l=1);let c,h;this.closed||o>0?c=i[(o-1)%r]:(qs.subVectors(i[0],i[1]).add(i[0]),c=qs);const d=i[o%r],u=i[(o+1)%r];if(this.closed||o+2i.length-2?i.length-1:a+1],d=i[a>i.length-3?i.length-1:a+2];return n.set(Ah(o,l.x,c.x,h.x,d.x),Ah(o,l.y,c.y,h.y,d.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t80*t){o=c=s[0],l=h=s[1];for(let p=t;pc&&(c=d),u>h&&(h=u);f=Math.max(c-o,h-l),f=f!==0?1/f:0}return Rr(r,a,t,o,l,f),a}};function Rh(s,e,t,n,i){let r,a;if(i===Ny(s,e,t,n)>0)for(r=e;r=e;r-=n)a=Ih(r,s[r],s[r+1],a);return a&&Zs(a,a.next)&&(Pr(a),a=a.next),a}function wn(s,e){if(!s)return s;e||(e=s);let t=s,n;do if(n=!1,!t.steiner&&(Zs(t,t.next)||Ve(t.prev,t,t.next)===0)){if(Pr(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function Rr(s,e,t,n,i,r,a){if(!s)return;!a&&r&&Cy(s,n,i,r);let o=s,l,c;for(;s.prev!==s.next;){if(l=s.prev,c=s.next,r?My(s,n,i,r):by(s)){e.push(l.i/t),e.push(s.i/t),e.push(c.i/t),Pr(s),s=c.next,o=c.next;continue}if(s=c,s===o){a?a===1?(s=wy(wn(s),e,t),Rr(s,e,t,n,i,r,2)):a===2&&Sy(s,e,t,n,i,r):Rr(wn(s),e,t,n,i,r,1);break}}}function by(s){const e=s.prev,t=s,n=s.next;if(Ve(e,t,n)>=0)return!1;let i=s.next.next;for(;i!==s.prev;){if(Hi(e.x,e.y,t.x,t.y,n.x,n.y,i.x,i.y)&&Ve(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function My(s,e,t,n){const i=s.prev,r=s,a=s.next;if(Ve(i,r,a)>=0)return!1;const o=i.xr.x?i.x>a.x?i.x:a.x:r.x>a.x?r.x:a.x,h=i.y>r.y?i.y>a.y?i.y:a.y:r.y>a.y?r.y:a.y,d=Uo(o,l,e,t,n),u=Uo(c,h,e,t,n);let f=s.prevZ,p=s.nextZ;for(;f&&f.z>=d&&p&&p.z<=u;){if(f!==s.prev&&f!==s.next&&Hi(i.x,i.y,r.x,r.y,a.x,a.y,f.x,f.y)&&Ve(f.prev,f,f.next)>=0||(f=f.prevZ,p!==s.prev&&p!==s.next&&Hi(i.x,i.y,r.x,r.y,a.x,a.y,p.x,p.y)&&Ve(p.prev,p,p.next)>=0))return!1;p=p.nextZ}for(;f&&f.z>=d;){if(f!==s.prev&&f!==s.next&&Hi(i.x,i.y,r.x,r.y,a.x,a.y,f.x,f.y)&&Ve(f.prev,f,f.next)>=0)return!1;f=f.prevZ}for(;p&&p.z<=u;){if(p!==s.prev&&p!==s.next&&Hi(i.x,i.y,r.x,r.y,a.x,a.y,p.x,p.y)&&Ve(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function wy(s,e,t){let n=s;do{const i=n.prev,r=n.next.next;!Zs(i,r)&&Ch(i,n,n.next,r)&&Cr(i,r)&&Cr(r,i)&&(e.push(i.i/t),e.push(n.i/t),e.push(r.i/t),Pr(n),Pr(n.next),n=s=r),n=n.next}while(n!==s);return wn(n)}function Sy(s,e,t,n,i,r){let a=s;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&Dy(a,o)){let l=Ph(a,o);a=wn(a,a.next),l=wn(l,l.next),Rr(a,e,t,n,i,r),Rr(l,e,t,n,i,r);return}o=o.next}a=a.next}while(a!==s)}function Ty(s,e,t,n){const i=[];let r,a,o,l,c;for(r=0,a=e.length;r=t.next.y&&t.next.y!==t.y){const u=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=n&&u>r){if(r=u,u===n){if(i===t.y)return t;if(i===t.next.y)return t.next}a=t.x=t.x&&t.x>=l&&n!==t.x&&Hi(ia.x||t.x===a.x&&Ry(a,t)))&&(a=t,h=d)),t=t.next;while(t!==o);return a}function Ry(s,e){return Ve(s.prev,s,e.prev)<0&&Ve(e.next,s,s.next)<0}function Cy(s,e,t,n){let i=s;do i.z===null&&(i.z=Uo(i.x,i.y,e,t,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==s);i.prevZ.nextZ=null,i.prevZ=null,Py(i)}function Py(s){let e,t,n,i,r,a,o,l,c=1;do{for(t=s,s=null,r=null,a=0;t;){for(a++,n=t,o=0,e=0;e0||l>0&&n;)o!==0&&(l===0||!n||t.z<=n.z)?(i=t,t=t.nextZ,o--):(i=n,n=n.nextZ,l--),r?r.nextZ=i:s=i,i.prevZ=r,r=i;t=n}r.nextZ=null,c*=2}while(a>1);return s}function Uo(s,e,t,n,i){return s=32767*(s-t)*i,e=32767*(e-n)*i,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,s|e<<1}function Iy(s){let e=s,t=s;do(e.x=0&&(s-a)*(n-o)-(t-a)*(e-o)>=0&&(t-a)*(r-o)-(i-a)*(n-o)>=0}function Dy(s,e){return s.next.i!==e.i&&s.prev.i!==e.i&&!Fy(s,e)&&(Cr(s,e)&&Cr(e,s)&&By(s,e)&&(Ve(s.prev,s,e.prev)||Ve(s,e.prev,e))||Zs(s,e)&&Ve(s.prev,s,s.next)>0&&Ve(e.prev,e,e.next)>0)}function Ve(s,e,t){return(e.y-s.y)*(t.x-e.x)-(e.x-s.x)*(t.y-e.y)}function Zs(s,e){return s.x===e.x&&s.y===e.y}function Ch(s,e,t,n){const i=Qs(Ve(s,e,t)),r=Qs(Ve(s,e,n)),a=Qs(Ve(t,n,s)),o=Qs(Ve(t,n,e));return!!(i!==r&&a!==o||i===0&&$s(s,t,e)||r===0&&$s(s,n,e)||a===0&&$s(t,s,n)||o===0&&$s(t,e,n))}function $s(s,e,t){return e.x<=Math.max(s.x,t.x)&&e.x>=Math.min(s.x,t.x)&&e.y<=Math.max(s.y,t.y)&&e.y>=Math.min(s.y,t.y)}function Qs(s){return s>0?1:s<0?-1:0}function Fy(s,e){let t=s;do{if(t.i!==s.i&&t.next.i!==s.i&&t.i!==e.i&&t.next.i!==e.i&&Ch(t,t.next,s,e))return!0;t=t.next}while(t!==s);return!1}function Cr(s,e){return Ve(s.prev,s,s.next)<0?Ve(s,e,s.next)>=0&&Ve(s,s.prev,e)>=0:Ve(s,e,s.prev)<0||Ve(s,s.next,e)<0}function By(s,e){let t=s,n=!1;const i=(s.x+e.x)/2,r=(s.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&i<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==s);return n}function Ph(s,e){const t=new Oo(s.i,s.x,s.y),n=new Oo(e.i,e.x,e.y),i=s.next,r=e.prev;return s.next=e,e.prev=s,t.next=i,i.prev=t,n.next=t,t.prev=n,r.next=n,n.prev=r,n}function Ih(s,e,t,n){const i=new Oo(s,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Pr(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function Oo(s,e,t){this.i=s,this.x=e,this.y=t,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function Ny(s,e,t,n){let i=0;for(let r=e,a=t-n;r2&&s[e-1].equals(s[0])&&s.pop()}function Fh(s,e){for(let t=0;tNumber.EPSILON){const xe=Math.sqrt(oe),Ae=Math.sqrt(X*X+ne*ne),ge=$.x-H/xe,C=$.y+S/xe,re=K.x-ne/Ae,W=K.y+X/Ae,le=((re-ge)*ne-(W-C)*X)/(S*ne-H*X);me=ge+S*le-V.x,ie=C+H*le-V.y;const fe=me*me+ie*ie;if(fe<=2)return new Y(me,ie);E=Math.sqrt(fe/2)}else{let xe=!1;S>Number.EPSILON?X>Number.EPSILON&&(xe=!0):S<-Number.EPSILON?X<-Number.EPSILON&&(xe=!0):Math.sign(H)===Math.sign(ne)&&(xe=!0),xe?(me=-H,ie=S,E=Math.sqrt(oe)):(me=S,ie=H,E=Math.sqrt(oe/2))}return new Y(me/E,ie/E)}const ue=[];for(let V=0,$=F.length,K=$-1,me=V+1;V<$;V++,K++,me++)K===$&&(K=0),me===$&&(me=0),ue[V]=j(F[V],F[K],F[me]);const ye=[];let se,Ee=ue.concat();for(let V=0,$=R.length;V<$;V++){const K=R[V];se=[];for(let me=0,ie=K.length,E=ie-1,S=me+1;me=0;V--){const $=V/y,K=f*Math.cos($*Math.PI/2),me=p*Math.sin($*Math.PI/2)+x;for(let ie=0,E=F.length;ie=0;){const me=K;let ie=K-1;ie<0&&(ie=V.length-1);for(let E=0,S=h+y*2;E=0?(e(m-l,y,d),u.subVectors(h,d)):(e(m+l,y,d),u.subVectors(d,h)),y-l>=0?(e(m,y-l,d),f.subVectors(h,d)):(e(m,y+l,d),f.subVectors(d,h)),c.crossVectors(u,f).normalize(),a.push(c.x,c.y,c.z),o.push(m,y)}}for(let x=0;x0)&&f.push(_,v,A),(g!==n-1||l0!=e>0&&this.version++,this._clearcoat=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.sheenTint.copy(e.sheenTint),this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationTint.copy(e.attenuationTint),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularTint.copy(e.specularTint),this.specularTintMap=e.specularTintMap,this}}Wo.prototype.isMeshPhysicalMaterial=!0;class qo extends it{constructor(e){super();this.type="MeshPhongMaterial",this.color=new te(16777215),this.specular=new te(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new te(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Un,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=Xi,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this}}qo.prototype.isMeshPhongMaterial=!0;class Xo extends it{constructor(e){super();this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new te(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new te(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Un,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this}}Xo.prototype.isMeshToonMaterial=!0;class Yo extends it{constructor(e){super();this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Un,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}Yo.prototype.isMeshNormalMaterial=!0;class Jo extends it{constructor(e){super();this.type="MeshLambertMaterial",this.color=new te(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new te(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=Xi,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this}}Jo.prototype.isMeshLambertMaterial=!0;class Zo extends it{constructor(e){super();this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new te(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Un,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this}}Zo.prototype.isMeshMatcapMaterial=!0;class $o extends at{constructor(e){super();this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}$o.prototype.isLineDashedMaterial=!0;var Hy=Object.freeze({__proto__:null,ShadowMaterial:Vo,SpriteMaterial:Rs,RawShaderMaterial:Ci,ShaderMaterial:en,PointsMaterial:Zn,MeshPhysicalMaterial:Wo,MeshStandardMaterial:js,MeshPhongMaterial:qo,MeshToonMaterial:Xo,MeshNormalMaterial:Yo,MeshLambertMaterial:Jo,MeshDepthMaterial:Es,MeshDistanceMaterial:As,MeshBasicMaterial:Kt,MeshMatcapMaterial:Zo,LineDashedMaterial:$o,LineBasicMaterial:at,Material:it});const ke={arraySlice:function(s,e,t){return ke.isTypedArray(s)?new s.constructor(s.subarray(e,t!==void 0?t:s.length)):s.slice(e,t)},convertArray:function(s,e,t){return!s||!t&&s.constructor===e?s:typeof e.BYTES_PER_ELEMENT=="number"?new e(s):Array.prototype.slice.call(s)},isTypedArray:function(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)},getKeyframeOrder:function(s){function e(i,r){return s[i]-s[r]}const t=s.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(e),n},sortedArray:function(s,e,t){const n=s.length,i=new s.constructor(n);for(let r=0,a=0;a!==n;++r){const o=t[r]*e;for(let l=0;l!==e;++l)i[a++]=s[o+l]}return i},flattenJSON:function(s,e,t,n){let i=1,r=s[0];for(;r!==void 0&&r[n]===void 0;)r=s[i++];if(r===void 0)return;let a=r[n];if(a!==void 0)if(Array.isArray(a))do a=r[n],a!==void 0&&(e.push(r.time),t.push.apply(t,a)),r=s[i++];while(r!==void 0);else if(a.toArray!==void 0)do a=r[n],a!==void 0&&(e.push(r.time),a.toArray(t,t.length)),r=s[i++];while(r!==void 0);else do a=r[n],a!==void 0&&(e.push(r.time),t.push(a)),r=s[i++];while(r!==void 0)},subclip:function(s,e,t,n,i=30){const r=s.clone();r.name=e;const a=[];for(let l=0;l=n)){d.push(c.times[f]);for(let x=0;xr.tracks[l].times[0]&&(o=r.tracks[l].times[0]);for(let l=0;l=o.times[p]){const g=p*d+h,m=g+d-h;x=ke.arraySlice(o.values,g,m)}else{const g=o.createInterpolant(),m=h,_=d-h;g.evaluate(r),x=ke.arraySlice(g.resultBuffer,m,_)}l==="quaternion"&&new ht().fromArray(x).normalize().conjugate().toArray(x);const y=c.times.length;for(let g=0;g=r)){const o=t[1];e=r)break t}a=n,n=0;break n}break e}for(;n>>1;et;)--a;if(++a,r!==0||a!==i){r>=a&&(a=Math.max(a,1),r=a-1);const o=this.getValueSize();this.times=ke.arraySlice(n,r,a),this.values=ke.arraySlice(this.values,r*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const n=this.times,i=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==r;o++){const l=n[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(i!==void 0&&ke.isTypedArray(i))for(let o=0,l=i.length;o!==l;++o){const c=i[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=ke.arraySlice(this.times),t=ke.arraySlice(this.values),n=this.getValueSize(),i=this.getInterpolation()===Qr,r=e.length-1;let a=1;for(let o=1;o0){e[a]=e[r];for(let o=r*n,l=a*n,c=0;c!==n;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=ke.arraySlice(e,0,a),this.values=ke.arraySlice(t,0,a*n)):(this.times=e,this.values=t),this}clone(){const e=ke.arraySlice(this.times,0),t=ke.arraySlice(this.values,0),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}}Dt.prototype.TimeBufferType=Float32Array,Dt.prototype.ValueBufferType=Float32Array,Dt.prototype.DefaultInterpolation=tr;class Qn extends Dt{}Qn.prototype.ValueTypeName="bool",Qn.prototype.ValueBufferType=Array,Qn.prototype.DefaultInterpolation=er,Qn.prototype.InterpolantFactoryMethodLinear=void 0,Qn.prototype.InterpolantFactoryMethodSmooth=void 0;class jo extends Dt{}jo.prototype.ValueTypeName="color";class Or extends Dt{}Or.prototype.ValueTypeName="number";class Oh extends rn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){const r=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(n-t)/(i-t);let c=e*o;for(let h=c+o;c!==h;c+=4)ht.slerpFlat(r,0,a,c-o,a,c,l);return r}}class Wi extends Dt{InterpolantFactoryMethodLinear(e){return new Oh(this.times,this.values,this.getValueSize(),e)}}Wi.prototype.ValueTypeName="quaternion",Wi.prototype.DefaultInterpolation=tr,Wi.prototype.InterpolantFactoryMethodSmooth=void 0;class jn extends Dt{}jn.prototype.ValueTypeName="string",jn.prototype.ValueBufferType=Array,jn.prototype.DefaultInterpolation=er,jn.prototype.InterpolantFactoryMethodLinear=void 0,jn.prototype.InterpolantFactoryMethodSmooth=void 0;class Hr extends Dt{}Hr.prototype.ValueTypeName="vector";class Gr{constructor(e,t=-1,n,i=jr){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=bt(),this.duration<0&&this.resetDuration()}static parse(e){const t=[],n=e.tracks,i=1/(e.fps||1);for(let a=0,o=n.length;a!==o;++a)t.push(ky(n[a]).scale(i));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){const t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let r=0,a=n.length;r!==a;++r)t.push(Dt.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){const r=t.length,a=[];for(let o=0;o1){const d=h[1];let u=i[d];u||(i[d]=u=[]),u.push(c)}}const a=[];for(const o in i)a.push(this.CreateFromMorphTargetSequence(o,i[o],t,n));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(d,u,f,p,x){if(f.length!==0){const y=[],g=[];ke.flattenJSON(f,y,g,p),y.length!==0&&x.push(new d(u,y,g))}},i=[],r=e.name||"default",a=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let d=0;d0||e.search(/^data\:image\/jpeg/)===0;r.format=l?Yt:xt,r.needsUpdate=!0,t!==void 0&&t(r)},n,i),r}}class Wh extends Tt{constructor(){super();this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){const e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);e.equals(t)||this.curves.push(new Lr(t,e))}getPoint(e){const t=e*this.getLength(),n=this.getCurveLengths();let i=0;for(;i=t){const r=n[i]-t,a=this.curves[i],o=a.getLength(),l=o===0?0:1-r/o;return a.getPointAt(l)}i++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let n=0,i=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){const d=c.getPoint(0);d.equals(this.currentPoint)||this.lineTo(d.x,d.y)}this.curves.push(c);const h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Sn extends Vr{constructor(e){super(e);this.uuid=bt(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let n=0,i=this.holes.length;n0:i.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const r in e.uniforms){const a=e.uniforms[r];switch(i.uniforms[r]={},a.type){case"t":i.uniforms[r].value=n(a.value);break;case"c":i.uniforms[r].value=new te().setHex(a.value);break;case"v2":i.uniforms[r].value=new Y().fromArray(a.value);break;case"v3":i.uniforms[r].value=new M().fromArray(a.value);break;case"v4":i.uniforms[r].value=new Oe().fromArray(a.value);break;case"m3":i.uniforms[r].value=new et().fromArray(a.value);break;case"m4":i.uniforms[r].value=new he().fromArray(a.value);break;default:i.uniforms[r].value=a.value}}if(e.defines!==void 0&&(i.defines=e.defines),e.vertexShader!==void 0&&(i.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(i.fragmentShader=e.fragmentShader),e.extensions!==void 0)for(const r in e.extensions)i.extensions[r]=e.extensions[r];if(e.shading!==void 0&&(i.flatShading=e.shading===1),e.size!==void 0&&(i.size=e.size),e.sizeAttenuation!==void 0&&(i.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(i.map=n(e.map)),e.matcap!==void 0&&(i.matcap=n(e.matcap)),e.alphaMap!==void 0&&(i.alphaMap=n(e.alphaMap)),e.bumpMap!==void 0&&(i.bumpMap=n(e.bumpMap)),e.bumpScale!==void 0&&(i.bumpScale=e.bumpScale),e.normalMap!==void 0&&(i.normalMap=n(e.normalMap)),e.normalMapType!==void 0&&(i.normalMapType=e.normalMapType),e.normalScale!==void 0){let r=e.normalScale;Array.isArray(r)===!1&&(r=[r,r]),i.normalScale=new Y().fromArray(r)}return e.displacementMap!==void 0&&(i.displacementMap=n(e.displacementMap)),e.displacementScale!==void 0&&(i.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(i.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(i.roughnessMap=n(e.roughnessMap)),e.metalnessMap!==void 0&&(i.metalnessMap=n(e.metalnessMap)),e.emissiveMap!==void 0&&(i.emissiveMap=n(e.emissiveMap)),e.emissiveIntensity!==void 0&&(i.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(i.specularMap=n(e.specularMap)),e.specularIntensityMap!==void 0&&(i.specularIntensityMap=n(e.specularIntensityMap)),e.specularTintMap!==void 0&&(i.specularTintMap=n(e.specularTintMap)),e.envMap!==void 0&&(i.envMap=n(e.envMap)),e.envMapIntensity!==void 0&&(i.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(i.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(i.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(i.lightMap=n(e.lightMap)),e.lightMapIntensity!==void 0&&(i.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(i.aoMap=n(e.aoMap)),e.aoMapIntensity!==void 0&&(i.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(i.gradientMap=n(e.gradientMap)),e.clearcoatMap!==void 0&&(i.clearcoatMap=n(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(i.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(i.clearcoatNormalMap=n(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(i.clearcoatNormalScale=new Y().fromArray(e.clearcoatNormalScale)),e.transmissionMap!==void 0&&(i.transmissionMap=n(e.transmissionMap)),e.thicknessMap!==void 0&&(i.thicknessMap=n(e.thicknessMap)),i}setTextures(e){return this.textures=e,this}}class Ks{static decodeText(e){if(typeof TextDecoder!="undefined")return new TextDecoder().decode(e);let t="";for(let n=0,i=e.length;n0){const l=new Ko(t);r=new kr(l),r.setCrossOrigin(this.crossOrigin);for(let c=0,h=e.length;c0){i=new kr(this.manager),i.setCrossOrigin(this.crossOrigin);for(let a=0,o=e.length;aNumber.EPSILON){if(R<0&&(L=_[b],P=-P,N=_[A],R=-R),m.yN.y)continue;if(m.y===L.y){if(m.x===L.x)return!0}else{const J=R*(m.x-L.x)-P*(m.y-L.y);if(J===0)return!0;if(J<0)continue;T=!T}}else{if(m.y!==L.y)continue;if(N.x<=m.x&&m.x<=L.x||L.x<=m.x&&m.x<=N.x)return!0}}return T}const r=Gt.isClockWise,a=this.subPaths;if(a.length===0)return[];if(t===!0)return n(a);let o,l,c;const h=[];if(a.length===1)return l=a[0],c=new Sn,c.curves=l.curves,h.push(c),h;let d=!r(a[0].getPoints());d=e?!d:d;const u=[],f=[];let p=[],x=0,y;f[x]=void 0,p[x]=[];for(let m=0,_=a.length;m<_;m++)l=a[m],y=l.getPoints(),o=r(y),o=e?!o:o,o?(!d&&f[x]&&x++,f[x]={s:new Sn,p:y},f[x].s.curves=l.curves,d&&x++,p[x]=[]):p[x].push({h:l,p:y[0]});if(!f[0])return n(a);if(f.length>1){let m=!1;const _=[];for(let v=0,T=f.length;v0&&(m||(p=u))}let g;for(let m=0,_=f.length;m<_;m++){c=f[m].s,h.push(c),g=p[m];for(let v=0,T=g.length;v0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(n[l]!==n[l+t]){o.setValue(n,i);break}}saveOriginalState(){const e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let r=n,a=i;r!==a;++r)t[r]=t[i+r%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let a=0;a!==r;++a)e[t+a]=e[n+a]}_slerp(e,t,n,i){ht.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,r){const a=this._workIndex*r;ht.multiplyQuaternionsFlat(e,a,e,t,e,n),ht.slerpFlat(e,t,e,t,e,a,i)}_lerp(e,t,n,i,r){const a=1-i;for(let o=0;o!==r;++o){const l=t+o;e[l]=e[l]*a+e[n+o]*i}}_lerpAdditive(e,t,n,i,r){for(let a=0;a!==r;++a){const o=t+a;e[o]=e[o]+e[n+a]*i}}}const fl="\\[\\]\\.:\\/",t0=new RegExp("["+fl+"]","g"),pl="[^"+fl+"]",n0="[^"+fl.replace("\\.","")+"]",i0=/((?:WC+[\/:])*)/.source.replace("WC",pl),r0=/(WCOD+)?/.source.replace("WCOD",n0),s0=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",pl),a0=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",pl),o0=new RegExp("^"+i0+r0+s0+a0+"$"),l0=["material","materials","bones"];class c0{constructor(e,t,n){const i=n||Ne.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();const n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){const n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}}class Ne{constructor(e,t,n){this.path=t,this.parsedPath=n||Ne.parseTrackName(t),this.node=Ne.findNode(e,this.parsedPath.nodeName)||e,this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new Ne.Composite(e,t,n):new Ne(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(t0,"")}static parseTrackName(e){const t=o0.exec(e);if(!t)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){const r=n.nodeName.substring(i+1);l0.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(!t||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){const n=function(r){for(let a=0;a=r){const d=r++,u=e[d];t[u.uuid]=h,e[h]=u,t[c]=d,e[d]=l;for(let f=0,p=i;f!==p;++f){const x=n[f],y=x[d],g=x[h];x[h]=y,x[d]=g}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,a=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],h=c.uuid,d=t[h];if(d!==void 0)if(delete t[h],d0&&(t[f.uuid]=d),e[d]=f,e.pop();for(let p=0,x=i;p!==x;++p){const y=n[p];y[d]=y[u],y.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const n=this._bindingsIndicesByPath;let i=n[e];const r=this._bindings;if(i!==void 0)return r[i];const a=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,h=this.nCachedObjects_,d=new Array(c);i=r.length,n[e]=i,a.push(e),o.push(t),r.push(d);for(let u=h,f=l.length;u!==f;++u){const p=l[u];d[u]=new Ne(p,e,t)}return d}unsubscribe_(e){const t=this._bindingsIndicesByPath,n=t[e];if(n!==void 0){const i=this._paths,r=this._parsedPaths,a=this._bindings,o=a.length-1,l=a[o],c=e[o];t[c]=n,a[n]=l,a.pop(),r[n]=r[o],r.pop(),i[n]=i[o],i.pop()}}}md.prototype.isAnimationObjectGroup=!0;class u0{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;const r=t.tracks,a=r.length,o=new Array(a),l={endingStart:Nn,endingEnd:Nn};for(let c=0;c!==a;++c){const h=r[c].createInterpolant(null);o[c]=h,h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Xc,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=Infinity,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n){if(e.fadeOut(t),this.fadeIn(t),n){const i=this._clip.duration,r=e._clip.duration,a=r/i,o=i/r;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,n){return e.crossFadeFrom(this,t,n)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){const i=this._mixer,r=i.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=i._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=r,l[1]=r+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled){this._updateWeight(e);return}const r=this._startTime;if(r!==null){const l=(e-r)*n;if(l<0||n===0)return;this._startTime=null,t=n*l}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Ia:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case jr:default:for(let h=0,d=l.length;h!==d;++h)l[h].evaluate(a),c[h].accumulate(i,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const n=this._weightInterpolant;if(n!==null){const i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const n=this._timeScaleInterpolant;n!==null&&(t*=n.evaluate(e)[0],e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t))}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,n=this.loop;let i=this.time+e,r=this._loopCount;const a=n===Yc;if(e===0)return r===-1?i:a&&(r&1)==1?t-i:i;if(n===qc){r===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(r===-1&&(e>=0?(r=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),i>=t||i<0){const o=Math.floor(i/t);i-=t*o,r+=Math.abs(o);const l=this.repetitions-r;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=i;if(a&&(r&1)==1)return t-i}return i}_setEndings(e,t,n){const i=this._interpolantSettings;n?(i.endingStart=zn,i.endingEnd=zn):(e?i.endingStart=this.zeroSlopeAtStart?zn:Nn:i.endingStart=nr,t?i.endingEnd=this.zeroSlopeAtEnd?zn:Nn:i.endingEnd=nr)}_scheduleFading(e,t,n){const i=this._mixer,r=i.time;let a=this._weightInterpolant;a===null&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,l[0]=t,o[1]=r+e,l[1]=n,this}}class gd extends cn{constructor(e){super();this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const n=e._localRoot||this._root,i=e._clip.tracks,r=i.length,a=e._propertyBindings,o=e._interpolants,l=n.uuid,c=this._bindingsByRootAndName;let h=c[l];h===void 0&&(h={},c[l]=h);for(let d=0;d!==r;++d){const u=i[d],f=u.name;let p=h[f];if(p!==void 0)a[d]=p;else{if(p=a[d],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,l,f));continue}const x=t&&t._propertyBindings[d].binding.parsedPath;p=new pd(Ne.create(n,f,x),u.ValueTypeName,u.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,l,f),a[d]=p}o[d].resultBuffer=p.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const n=(e._localRoot||this._root).uuid,i=e._clip.uuid,r=this._actionsByClip[i];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,i,n)}const t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){const r=t[n];r.useCount++==0&&(this._lendBinding(r),r.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){const r=t[n];--r.useCount==0&&(r.restoreOriginalState(),this._takeBackBinding(r))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;const t=this._actions,n=this._nActiveActions,i=this.time+=e,r=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==n;++c)t[c]._update(i,e,r,a);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;tthis.max.x||e.ythis.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return _d.copy(e).clamp(this.min,this.max).sub(e).length()}intersect(e){return this.min.max(e.min),this.max.min(e.max),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}qi.prototype.isBox2=!0;const bd=new M,na=new M;class Md{constructor(e=new M,t=new M){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){bd.subVectors(e,this.start),na.subVectors(this.end,this.start);const n=na.dot(na);let r=na.dot(bd)/n;return t&&(r=ut(r,0,1)),r}closestPointToPoint(e,t,n){const i=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}class wd extends Ce{constructor(e){super();this.material=e,this.render=function(){},this.hasPositions=!1,this.hasNormals=!1,this.hasColors=!1,this.hasUvs=!1,this.positionArray=null,this.normalArray=null,this.colorArray=null,this.uvArray=null,this.count=0}}wd.prototype.isImmediateRenderObject=!0;const Sd=new M;class p0 extends Ce{constructor(e,t){super();this.light=e,this.light.updateMatrixWorld(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=t;const n=new _e,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Dd.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Dd,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}}class Fd extends _t{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new _e;i.setAttribute("position",new ae(t,3)),i.setAttribute("color",new ae(n,3));const r=new at({vertexColors:!0,toneMapped:!1});super(i,r);this.type="AxesHelper"}setColors(e,t,n){const i=new te,r=this.geometry.attributes.color.array;return i.set(e),i.toArray(r,0),i.toArray(r,3),i.set(t),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}const Bd=new Float32Array(1),S0=new Int32Array(Bd.buffer);class T0{static toHalfFloat(e){Bd[0]=e;const t=S0[0];let n=t>>16&32768,i=t>>12&2047;const r=t>>23&255;return r<103?n:r>142?(n|=31744,n|=(r==255?0:1)&&t&8388607,n):r<113?(i|=2048,n|=(i>>114-r)+(i>>113-r&1),n):(n|=r-112<<10|i>>1,n+=i&1,n)}}const E0=0,A0=1,L0=0,R0=1,C0=2;function P0(s){return console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead."),s}function I0(s=[]){return console.warn("THREE.MultiMaterial has been removed. Use an Array instead."),s.isMultiMaterial=!0,s.materials=s,s.clone=function(){return s.slice()},s}function D0(s,e){return console.warn("THREE.PointCloud has been renamed to THREE.Points."),new br(s,e)}function F0(s){return console.warn("THREE.Particle has been renamed to THREE.Sprite."),new Is(s)}function B0(s,e){return console.warn("THREE.ParticleSystem has been renamed to THREE.Points."),new br(s,e)}function N0(s){return console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial."),new Zn(s)}function z0(s){return console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial."),new Zn(s)}function U0(s){return console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial."),new Zn(s)}function O0(s,e,t){return console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead."),new M(s,e,t)}function H0(s,e){return console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead."),new Be(s,e).setUsage(di)}function G0(s,e){return console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead."),new pu(s,e)}function k0(s,e){return console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead."),new mu(s,e)}function V0(s,e){return console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead."),new gu(s,e)}function W0(s,e){return console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead."),new xu(s,e)}function q0(s,e){return console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead."),new hs(s,e)}function X0(s,e){return console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead."),new yu(s,e)}function Y0(s,e){return console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead."),new ds(s,e)}function J0(s,e){return console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead."),new ae(s,e)}function Z0(s,e){return console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead."),new _u(s,e)}Tt.create=function(s,e){return console.log("THREE.Curve.create() has been deprecated"),s.prototype=Object.create(Tt.prototype),s.prototype.constructor=s,s.prototype.getPoint=e,s},Vr.prototype.fromPoints=function(s){return console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints()."),this.setFromPoints(s)};function $0(s){return console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper."),new Fd(s)}function Q0(s,e){return console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead."),new Id(s,e)}function j0(s,e){return console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead."),new _t(new Lo(s.geometry),new at({color:e!==void 0?e:16777215}))}Rd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")},Td.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};function K0(s,e){return console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead."),new _t(new ko(s.geometry),new at({color:e!==void 0?e:16777215}))}gt.prototype.extractUrlBase=function(s){return console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead."),Ks.extractUrlBase(s)},gt.Handlers={add:function(){console.error("THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.")},get:function(){console.error("THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.")}};function ev(s){return console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader."),new Bt(s)}function tv(s){return console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader."),new kh(s)}qi.prototype.center=function(s){return console.warn("THREE.Box2: .center() has been renamed to .getCenter()."),this.getCenter(s)},qi.prototype.empty=function(){return console.warn("THREE.Box2: .empty() has been renamed to .isEmpty()."),this.isEmpty()},qi.prototype.isIntersectionBox=function(s){return console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(s)},qi.prototype.size=function(s){return console.warn("THREE.Box2: .size() has been renamed to .getSize()."),this.getSize(s)},Mt.prototype.center=function(s){return console.warn("THREE.Box3: .center() has been renamed to .getCenter()."),this.getCenter(s)},Mt.prototype.empty=function(){return console.warn("THREE.Box3: .empty() has been renamed to .isEmpty()."),this.isEmpty()},Mt.prototype.isIntersectionBox=function(s){return console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(s)},Mt.prototype.isIntersectionSphere=function(s){return console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(s)},Mt.prototype.size=function(s){return console.warn("THREE.Box3: .size() has been renamed to .getSize()."),this.getSize(s)},dn.prototype.empty=function(){return console.warn("THREE.Sphere: .empty() has been renamed to .isEmpty()."),this.isEmpty()},hr.prototype.setFromMatrix=function(s){return console.warn("THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix()."),this.setFromProjectionMatrix(s)},Md.prototype.center=function(s){return console.warn("THREE.Line3: .center() has been renamed to .getCenter()."),this.getCenter(s)},et.prototype.flattenToArrayOffset=function(s,e){return console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(s,e)},et.prototype.multiplyVector3=function(s){return console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead."),s.applyMatrix3(this)},et.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},et.prototype.applyToBufferAttribute=function(s){return console.warn("THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead."),s.applyMatrix3(this)},et.prototype.applyToVector3Array=function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")},et.prototype.getInverse=function(s){return console.warn("THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(s).invert()},he.prototype.extractPosition=function(s){return console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition()."),this.copyPosition(s)},he.prototype.flattenToArrayOffset=function(s,e){return console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead."),this.toArray(s,e)},he.prototype.getPosition=function(){return console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead."),new M().setFromMatrixColumn(this,3)},he.prototype.setRotationFromQuaternion=function(s){return console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion()."),this.makeRotationFromQuaternion(s)},he.prototype.multiplyToArray=function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},he.prototype.multiplyVector3=function(s){return console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead."),s.applyMatrix4(this)},he.prototype.multiplyVector4=function(s){return console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead."),s.applyMatrix4(this)},he.prototype.multiplyVector3Array=function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},he.prototype.rotateAxis=function(s){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead."),s.transformDirection(this)},he.prototype.crossVector=function(s){return console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead."),s.applyMatrix4(this)},he.prototype.translate=function(){console.error("THREE.Matrix4: .translate() has been removed.")},he.prototype.rotateX=function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},he.prototype.rotateY=function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},he.prototype.rotateZ=function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},he.prototype.rotateByAxis=function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},he.prototype.applyToBufferAttribute=function(s){return console.warn("THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead."),s.applyMatrix4(this)},he.prototype.applyToVector3Array=function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},he.prototype.makeFrustum=function(s,e,t,n,i,r){return console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead."),this.makePerspective(s,e,n,t,i,r)},he.prototype.getInverse=function(s){return console.warn("THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead."),this.copy(s).invert()},Ut.prototype.isIntersectionLine=function(s){return console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine()."),this.intersectsLine(s)},ht.prototype.multiplyVector3=function(s){return console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead."),s.applyQuaternion(this)},ht.prototype.inverse=function(){return console.warn("THREE.Quaternion: .inverse() has been renamed to invert()."),this.invert()},pn.prototype.isIntersectionBox=function(s){return console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox()."),this.intersectsBox(s)},pn.prototype.isIntersectionPlane=function(s){return console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane()."),this.intersectsPlane(s)},pn.prototype.isIntersectionSphere=function(s){return console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere()."),this.intersectsSphere(s)},Ye.prototype.area=function(){return console.warn("THREE.Triangle: .area() has been renamed to .getArea()."),this.getArea()},Ye.prototype.barycoordFromPoint=function(s,e){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),this.getBarycoord(s,e)},Ye.prototype.midpoint=function(s){return console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint()."),this.getMidpoint(s)},Ye.prototypenormal=function(s){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),this.getNormal(s)},Ye.prototype.plane=function(s){return console.warn("THREE.Triangle: .plane() has been renamed to .getPlane()."),this.getPlane(s)},Ye.barycoordFromPoint=function(s,e,t,n,i){return console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord()."),Ye.getBarycoord(s,e,t,n,i)},Ye.normal=function(s,e,t,n){return console.warn("THREE.Triangle: .normal() has been renamed to .getNormal()."),Ye.getNormal(s,e,t,n)},Sn.prototype.extractAllPoints=function(s){return console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead."),this.extractPoints(s)},Sn.prototype.extrude=function(s){return console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead."),new kt(this,s)},Sn.prototype.makeGeometry=function(s){return console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead."),new ki(this,s)},Y.prototype.fromAttribute=function(s,e,t){return console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(s,e,t)},Y.prototype.distanceToManhattan=function(s){return console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(s)},Y.prototype.lengthManhattan=function(){return console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},M.prototype.setEulerFromRotationMatrix=function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},M.prototype.setEulerFromQuaternion=function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},M.prototype.getPositionFromMatrix=function(s){return console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition()."),this.setFromMatrixPosition(s)},M.prototype.getScaleFromMatrix=function(s){return console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale()."),this.setFromMatrixScale(s)},M.prototype.getColumnFromMatrix=function(s,e){return console.warn("THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn()."),this.setFromMatrixColumn(e,s)},M.prototype.applyProjection=function(s){return console.warn("THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead."),this.applyMatrix4(s)},M.prototype.fromAttribute=function(s,e,t){return console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(s,e,t)},M.prototype.distanceToManhattan=function(s){return console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo()."),this.manhattanDistanceTo(s)},M.prototype.lengthManhattan=function(){return console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Oe.prototype.fromAttribute=function(s,e,t){return console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute()."),this.fromBufferAttribute(s,e,t)},Oe.prototype.lengthManhattan=function(){return console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength()."),this.manhattanLength()},Ce.prototype.getChildByName=function(s){return console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName()."),this.getObjectByName(s)},Ce.prototype.renderDepth=function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},Ce.prototype.translate=function(s,e){return console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead."),this.translateOnAxis(e,s)},Ce.prototype.getWorldRotation=function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.")},Ce.prototype.applyMatrix=function(s){return console.warn("THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(s)},Object.defineProperties(Ce.prototype,{eulerOrder:{get:function(){return console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order},set:function(s){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order."),this.rotation.order=s}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}}),je.prototype.setDrawMode=function(){console.error("THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")},Object.defineProperties(je.prototype,{drawMode:{get:function(){return console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode."),Jc},set:function(){console.error("THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.")}}}),Bs.prototype.initBones=function(){console.error("THREE.SkinnedMesh: initBones() has been removed.")},st.prototype.setLens=function(s,e){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup."),e!==void 0&&(this.filmGauge=e),this.setFocalLength(s)},Object.defineProperties(Nt.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(s){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov."),this.shadow.camera.fov=s}},shadowCameraLeft:{set:function(s){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left."),this.shadow.camera.left=s}},shadowCameraRight:{set:function(s){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right."),this.shadow.camera.right=s}},shadowCameraTop:{set:function(s){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top."),this.shadow.camera.top=s}},shadowCameraBottom:{set:function(s){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom."),this.shadow.camera.bottom=s}},shadowCameraNear:{set:function(s){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near."),this.shadow.camera.near=s}},shadowCameraFar:{set:function(s){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far."),this.shadow.camera.far=s}},shadowCameraVisible:{set:function(){console.warn("THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.")}},shadowBias:{set:function(s){console.warn("THREE.Light: .shadowBias is now .shadow.bias."),this.shadow.bias=s}},shadowDarkness:{set:function(){console.warn("THREE.Light: .shadowDarkness has been removed.")}},shadowMapWidth:{set:function(s){console.warn("THREE.Light: .shadowMapWidth is now .shadow.mapSize.width."),this.shadow.mapSize.width=s}},shadowMapHeight:{set:function(s){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height."),this.shadow.mapSize.height=s}}}),Object.defineProperties(Be.prototype,{length:{get:function(){return console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead."),this.array.length}},dynamic:{get:function(){return console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.usage===di},set:function(){console.warn("THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead."),this.setUsage(di)}}}),Be.prototype.setDynamic=function(s){return console.warn("THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(s===!0?di:hi),this},Be.prototype.copyIndicesArray=function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.")},Be.prototype.setArray=function(){console.error("THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},_e.prototype.addIndex=function(s){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex()."),this.setIndex(s)},_e.prototype.addAttribute=function(s,e){return console.warn("THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute()."),!(e&&e.isBufferAttribute)&&!(e&&e.isInterleavedBufferAttribute)?(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.setAttribute(s,new Be(arguments[1],arguments[2]))):s==="index"?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(e),this):this.setAttribute(s,e)},_e.prototype.addDrawCall=function(s,e,t){t!==void 0&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset."),console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup()."),this.addGroup(s,e)},_e.prototype.clearDrawCalls=function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups()."),this.clearGroups()},_e.prototype.computeOffsets=function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")},_e.prototype.removeAttribute=function(s){return console.warn("THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute()."),this.deleteAttribute(s)},_e.prototype.applyMatrix=function(s){return console.warn("THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4()."),this.applyMatrix4(s)},Object.defineProperties(_e.prototype,{drawcalls:{get:function(){return console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups."),this.groups}},offsets:{get:function(){return console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups."),this.groups}}}),Xn.prototype.setDynamic=function(s){return console.warn("THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead."),this.setUsage(s===!0?di:hi),this},Xn.prototype.setArray=function(){console.error("THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers")},kt.prototype.getArrays=function(){console.error("THREE.ExtrudeGeometry: .getArrays() has been removed.")},kt.prototype.addShapeList=function(){console.error("THREE.ExtrudeGeometry: .addShapeList() has been removed.")},kt.prototype.addShape=function(){console.error("THREE.ExtrudeGeometry: .addShape() has been removed.")},Ls.prototype.dispose=function(){console.error("THREE.Scene: .dispose() has been removed.")},ta.prototype.onUpdate=function(){return console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead."),this},Object.defineProperties(it.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},overdraw:{get:function(){console.warn("THREE.Material: .overdraw has been removed.")},set:function(){console.warn("THREE.Material: .overdraw has been removed.")}},wrapRGB:{get:function(){return console.warn("THREE.Material: .wrapRGB has been removed."),new te}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(s){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=s===fa}},stencilMask:{get:function(){return console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask},set:function(s){console.warn("THREE."+this.type+": .stencilMask has been removed. Use .stencilFuncMask instead."),this.stencilFuncMask=s}},vertexTangents:{get:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")},set:function(){console.warn("THREE."+this.type+": .vertexTangents has been removed.")}}}),Object.defineProperties(en.prototype,{derivatives:{get:function(){return console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives},set:function(s){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives."),this.extensions.derivatives=s}}}),He.prototype.clearTarget=function(s,e,t,n){console.warn("THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead."),this.setRenderTarget(s),this.clear(e,t,n)},He.prototype.animate=function(s){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop()."),this.setAnimationLoop(s)},He.prototype.getCurrentRenderTarget=function(){return console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget()."),this.getRenderTarget()},He.prototype.getMaxAnisotropy=function(){return console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy()."),this.capabilities.getMaxAnisotropy()},He.prototype.getPrecision=function(){return console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision."),this.capabilities.precision},He.prototype.resetGLState=function(){return console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset()."),this.state.reset()},He.prototype.supportsFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' )."),this.extensions.get("OES_texture_float")},He.prototype.supportsHalfFloatTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' )."),this.extensions.get("OES_texture_half_float")},He.prototype.supportsStandardDerivatives=function(){return console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' )."),this.extensions.get("OES_standard_derivatives")},He.prototype.supportsCompressedTextureS3TC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' )."),this.extensions.get("WEBGL_compressed_texture_s3tc")},He.prototype.supportsCompressedTexturePVRTC=function(){return console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' )."),this.extensions.get("WEBGL_compressed_texture_pvrtc")},He.prototype.supportsBlendMinMax=function(){return console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' )."),this.extensions.get("EXT_blend_minmax")},He.prototype.supportsVertexTextures=function(){return console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures."),this.capabilities.vertexTextures},He.prototype.supportsInstancedArrays=function(){return console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' )."),this.extensions.get("ANGLE_instanced_arrays")},He.prototype.enableScissorTest=function(s){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest()."),this.setScissorTest(s)},He.prototype.initMaterial=function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},He.prototype.addPrePlugin=function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},He.prototype.addPostPlugin=function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},He.prototype.updateShadowMap=function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")},He.prototype.setFaceCulling=function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.")},He.prototype.allocTextureUnit=function(){console.warn("THREE.WebGLRenderer: .allocTextureUnit() has been removed.")},He.prototype.setTexture=function(){console.warn("THREE.WebGLRenderer: .setTexture() has been removed.")},He.prototype.setTexture2D=function(){console.warn("THREE.WebGLRenderer: .setTexture2D() has been removed.")},He.prototype.setTextureCube=function(){console.warn("THREE.WebGLRenderer: .setTextureCube() has been removed.")},He.prototype.getActiveMipMapLevel=function(){return console.warn("THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel()."),this.getActiveMipmapLevel()},Object.defineProperties(He.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(s){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled."),this.shadowMap.enabled=s}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(s){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type."),this.shadowMap.type=s}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")}},context:{get:function(){return console.warn("THREE.WebGLRenderer: .context has been removed. Use .getContext() instead."),this.getContext()}},vr:{get:function(){return console.warn("THREE.WebGLRenderer: .vr has been renamed to .xr"),this.xr}},gammaInput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead."),!1},set:function(){console.warn("THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.")}},gammaOutput:{get:function(){return console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),!1},set:function(s){console.warn("THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead."),this.outputEncoding=s===!0?ir:yt}},toneMappingWhitePoint:{get:function(){return console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed."),1},set:function(){console.warn("THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.")}}}),Object.defineProperties(nh.prototype,{cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")}},renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")}}});function nv(s,e,t){return console.warn("THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options )."),new Ms(s,t)}Object.defineProperties(Lt.prototype,{wrapS:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS},set:function(s){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS."),this.texture.wrapS=s}},wrapT:{get:function(){return console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT},set:function(s){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT."),this.texture.wrapT=s}},magFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter},set:function(s){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter."),this.texture.magFilter=s}},minFilter:{get:function(){return console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter},set:function(s){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter."),this.texture.minFilter=s}},anisotropy:{get:function(){return console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy},set:function(s){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy."),this.texture.anisotropy=s}},offset:{get:function(){return console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset},set:function(s){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset."),this.texture.offset=s}},repeat:{get:function(){return console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat},set:function(s){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat."),this.texture.repeat=s}},format:{get:function(){return console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format},set:function(s){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format."),this.texture.format=s}},type:{get:function(){return console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type},set:function(s){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type."),this.texture.type=s}},generateMipmaps:{get:function(){return console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps},set:function(s){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps."),this.texture.generateMipmaps=s}}}),dl.prototype.load=function(s){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");const e=this;return new rd().load(s,function(n){e.setBuffer(n)}),this},fd.prototype.getData=function(){return console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData()."),this.getFrequencyData()},bs.prototype.updateCubeMap=function(s,e){return console.warn("THREE.CubeCamera: .updateCubeMap() is now .update()."),this.update(s,e)},bs.prototype.clear=function(s,e,t,n){return console.warn("THREE.CubeCamera: .clear() is now .renderTarget.clear()."),this.renderTarget.clear(s,e,t,n)},Hn.crossOrigin=void 0,Hn.loadTexture=function(s,e,t,n){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");const i=new Vh;i.setCrossOrigin(this.crossOrigin);const r=i.load(s,t,void 0,n);return e&&(r.mapping=e),r},Hn.loadTextureCube=function(s,e,t,n){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");const i=new Gh;i.setCrossOrigin(this.crossOrigin);const r=i.load(s,t,void 0,n);return e&&(r.mapping=e),r},Hn.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},Hn.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")};function iv(){console.error("THREE.CanvasRenderer has been removed")}function rv(){console.error("THREE.JSONLoader has been removed.")}const sv={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")},attach:function(){console.error("THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js")}};function av(){console.error("THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js")}typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:ua}})),typeof window!="undefined"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=ua);export{jo as $,Ql as A,Xe as B,tv as C,Ns as D,Qn as E,Q0 as F,qi as G,Mt as H,b0 as I,vn as J,Id as K,Be as L,_e as M,Kh as N,Kl as O,Kn as P,ur as Q,_0 as R,Pe as S,iv as T,Th as U,Fo as V,$l as W,Mr as X,lt as Y,cd as Z,te as _,Pn as a,Xt as a$,Eo as a0,Wy as a1,wr as a2,bs as a3,ai as a4,oi as a5,Ai as a6,Gh as a7,li as a8,Zi as a9,Uh as aA,Sr as aB,Cn as aC,Fl as aD,Nl as aE,H0 as aF,yf as aG,di as aH,mf as aI,Lo as aJ,j0 as aK,Tr as aL,kl as aM,lf as aN,Yi as aO,Ji as aP,Vn as aQ,cn as aR,kt as aS,R0 as aT,Bt as aU,fa as aV,vu as aW,J0 as aX,ae as aY,Z0 as aZ,_u as a_,Xs as aa,Bo as ab,zh as ac,ha as ad,Tl as ae,Vd as af,Sl as ag,Tt as ah,Wh as ai,Al as aj,jl as ak,$n as al,f0 as am,Yn as an,mo as ao,go as ap,kh as aq,T0 as ar,tf as as,rf as at,Hh as au,Bn as av,ui as aw,Eh as ax,sl as ay,v0 as az,Yl as b,$o as b$,gr as b0,mr as b1,ul as b2,Zy as b3,Rn as b4,hr as b5,yd as b6,_f as b7,Na as b8,Kr as b9,pu as bA,tc as bB,Xn as bC,Mn as bD,rn as bE,er as bF,tr as bG,Qr as bH,sf as bI,rv as bJ,ts as bK,Dt as bL,ch as bM,Dr as bN,Za as bO,av as bP,Gl as bQ,Yr as bR,cf as bS,of as bT,Nt as bU,qr as bV,tn as bW,Md as bX,at as bY,Lr as bZ,Lh as b_,Wl as ba,Vl as bb,df as bc,uf as bd,Rd as be,qn as bf,Fn as bg,el as bh,x0 as bi,sd as bj,Ir as bk,nd as bl,kr as bm,Hn as bn,wd as bo,ef as bp,nf as bq,Jn as br,cl as bs,xd as bt,Mo as bu,W0 as bv,xu as bw,X0 as bx,yu as by,G0 as bz,Ia as c,jc as c$,So as c0,A0 as c1,_t as c2,E0 as c3,yt as c4,Ke as c5,Qo as c6,Zd as c7,Jd as c8,In as c9,qo as cA,Wo as cB,js as cC,Xo as cD,xa as cE,Qi as cF,Xl as cG,I0 as cH,ga as cI,Xi as cJ,Qe as cK,Yd as cL,Xd as cM,$r as cN,Zr as cO,Ol as cP,af as cQ,qt as cR,L0 as cS,ln as cT,jr as cU,si as cV,ql as cW,hf as cX,Or as cY,Ce as cZ,qy as c_,ba as ca,Jl as cb,gt as cc,Ks as cd,Ko as ce,Zc as cf,qc as cg,Yc as ch,Xc as ci,oc as cj,ac as ck,Gd as cl,it as cm,jh as cn,Ff as co,et as cp,he as cq,ya as cr,je as cs,Kt as ct,Es as cu,As as cv,P0 as cw,Jo as cx,Zo as cy,Yo as cz,pa as d,es as d$,Gi as d0,Pl as d1,Bl as d2,zl as d3,_a as d4,Dl as d5,dr as d6,da as d7,El as d8,Cu as d9,Oh as dA,ua as dB,Qc as dC,xt as dD,pc as dE,Ac as dF,Sc as dG,Tc as dH,Ec as dI,Lc as dJ,Rc as dK,gc as dL,xc as dM,yc as dN,vc as dO,_c as dP,bc as dQ,Mc as dR,wc as dS,Cc as dT,Pa as dU,Ra as dV,La as dW,wa as dX,Sa as dY,Ta as dZ,Ba as d_,Ho as da,F0 as db,z0 as dc,B0 as dd,U0 as de,Vr as df,st as dg,Ut as dh,Ri as di,M0 as dj,D0 as dk,N0 as dl,rl as dm,m0 as dn,br as dp,Zn as dq,y0 as dr,nn as ds,e0 as dt,Ne as du,pd as dv,Ys as dw,No as dx,ht as dy,Wi as dz,sc as e,xf as e$,lc as e0,Yt as e1,fc as e2,Fa as e3,Da as e4,mc as e5,Ca as e6,Aa as e7,Ea as e8,Ma as e9,Uc as eA,Ls as eB,sv as eC,It as eD,en as eE,Vo as eF,Sn as eG,ki as eH,id as eI,Gt as eJ,ec as eK,zs as eL,Td as eM,Bs as eN,qd as eO,dn as eP,Vi as eQ,d0 as eR,ll as eS,Js as eT,nl as eU,p0 as eV,Is as eW,Rs as eX,va as eY,Ul as eZ,Il as e_,hc as ea,dc as eb,Ci as ec,pn as ed,h0 as ee,ol as ef,cc as eg,uc as eh,Zl as ei,$i as ej,Kd as ek,Rl as el,Fr as em,kc as en,Oc as eo,Hc as ep,Gc as eq,Vc as er,Wc as es,Pc as et,Ic as eu,Dc as ev,Fc as ew,Bc as ex,Nc as ey,zc as ez,Hl as f,zn as f$,hi as f0,pf as f1,$y as f2,vf as f3,ff as f4,gf as f5,jn as f6,Ll as f7,ma as f8,kd as f9,Ki as fA,nc as fB,ic as fC,rc as fD,ji as fE,ri as fF,Y as fG,M as fH,Oe as fI,Hr as fJ,O0 as fK,C0 as fL,Sh as fM,rh as fN,Ms as fO,nu as fP,Ha as fQ,Lt as fR,nv as fS,He as fT,ih as fU,ko as fV,K0 as fW,nr as fX,ev as fY,Nn as fZ,Cl as f_,Un as fa,Br as fb,Go as fc,tt as fd,Vh as fe,Nr as ff,zr as fg,Ye as fh,Qd as fi,$d as fj,Jc as fk,Ur as fl,Jr as fm,q0 as fn,hs as fo,Y0 as fp,ds as fq,k0 as fr,mu as fs,V0 as ft,gu as fu,ta as fv,ee as fw,wu as fx,Dn as fy,ci as fz,Kc as g,jd as g0,ir as g1,al as h,ad as i,Gr as j,Vy as k,gd as l,md as m,ke as n,Ro as o,vo as p,w0 as q,dl as r,fd as s,hl as t,jy as u,rd as v,Fd as w,$0 as x,$c as y,Wd as z}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/toString-31cf0354.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/toString-31cf0354.js new file mode 100644 index 0000000000000000000000000000000000000000..16ed492897db1b1826fdef53548bcb74d66bd1a4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/toString-31cf0354.js @@ -0,0 +1 @@ +import{b as o}from"./_baseGetTag-3262967e.js";import{_ as a}from"./_arrayMap-c3125c3a.js";import{i as f}from"./isArray-1ab33e59.js";import{i as m}from"./isSymbol-cf06cd7f.js";var e=1/0,i=o?o.prototype:void 0,n=i?i.toString:void 0;function s(r){if(typeof r=="string")return r;if(f(r))return a(r,s)+"";if(m(r))return n?n.call(r):"";var t=r+"";return t=="0"&&1/r==-e?"-0":t}var y=s;function b(r){return r==null?"":y(r)}var p=b;export{p as t}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/unitless.browser.esm-319df2e6.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/unitless.browser.esm-319df2e6.js new file mode 100644 index 0000000000000000000000000000000000000000..ee6f385a003ecc6e2b500980a792b3a59b843873 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/common/unitless.browser.esm-319df2e6.js @@ -0,0 +1 @@ +var o={animationIterationCount:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};export{o as u}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3-format.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3-format.js new file mode 100644 index 0000000000000000000000000000000000000000..b0760407f5d25aa3ffcea55fef9ff2bb99119ca2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3-format.js @@ -0,0 +1 @@ +export{b as format}from"./common/defaultLocale-5df5e395.js"; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3.js new file mode 100644 index 0000000000000000000000000000000000000000..c9d71693f447db87d0185012ed05d1b3b4667164 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/d3.js @@ -0,0 +1,5 @@ +import{e as Je,f as pd,a as md,b as Qf}from"./common/defaultLocale-5df5e395.js";export{F as FormatSpecifier,b as format,d as formatDefaultLocale,c as formatLocale,a as formatPrefix,f as formatSpecifier}from"./common/defaultLocale-5df5e395.js";function wn(n,t){return n==null||t==null?NaN:nt?1:n>=t?0:NaN}function jr(n){let t=n,e=n,r=n;n.length===1&&(t=(u,f)=>n(u)-f,e=wn,r=(u,f)=>wn(n(u),f));function i(u,f,c=0,s=u.length){if(c>>1;r(u[h],f)<0?c=h+1:s=h}while(c>>1;r(u[h],f)<=0?c=h+1:s=h}while(cc&&t(u[h-1],f)>-t(u[h],f)?h-1:h}return{left:i,center:o,right:a}}function Kf(n){return n===null?NaN:+n}function*yd(n,t){if(t===void 0)for(let e of n)e!=null&&(e=+e)>=e&&(yield e);else{let e=-1;for(let r of n)(r=t(r,++e,n))!=null&&(r=+r)>=r&&(yield r)}}const Jf=jr(wn),Rt=Jf.right,vd=Jf.left,_d=jr(Kf).center;function ni(n,t){let e=0;if(t===void 0)for(let r of n)r!=null&&(r=+r)>=r&&++e;else{let r=-1;for(let i of n)(i=t(i,++r,n))!=null&&(i=+i)>=i&&++e}return e}function bd(n){return n.length|0}function wd(n){return!(n>0)}function xd(n){return typeof n!="object"||"length"in n?n:Array.from(n)}function Md(n){return t=>n(...t)}function Sd(...n){const t=typeof n[n.length-1]=="function"&&Md(n.pop());n=n.map(xd);const e=n.map(bd),r=n.length-1,i=new Array(r+1).fill(0),a=[];if(r<0||e.some(wd))return a;for(;;){a.push(i.map((u,f)=>n[f][u]));let o=r;for(;++i[o]===e[o];){if(o===0)return t?a.map(t):a;i[o--]=0}}}function Td(n,t){var e=0,r=0;return Float64Array.from(n,t===void 0?i=>e+=+i||0:i=>e+=+t(i,r++,n)||0)}function Ad(n,t){return n==null||t==null?NaN:tn?1:t>=n?0:NaN}function jf(n,t){let e=0,r,i=0,a=0;if(t===void 0)for(let o of n)o!=null&&(o=+o)>=o&&(r=o-i,i+=r/++e,a+=r*(o-i));else{let o=-1;for(let u of n)(u=t(u,++o,n))!=null&&(u=+u)>=u&&(r=u-i,i+=r/++e,a+=r*(u-i))}if(e>1)return a/(e-1)}function nc(n,t){const e=jf(n,t);return e&&Math.sqrt(e)}function je(n,t){let e,r;if(t===void 0)for(const i of n)i!=null&&(e===void 0?i>=i&&(e=r=i):(e>i&&(e=i),r=a&&(e=r=a):(e>a&&(e=a),r0){for(o=t[--e];e>0&&(r=o,i=t[--e],o=r+i,a=i-(o-r),!a););e>0&&(a<0&&t[e-1]<0||a>0&&t[e-1]>0)&&(i=a*2,r=o+i,i==r-o&&(o=r))}return o}}function Ed(n,t){const e=new pn;if(t===void 0)for(let r of n)(r=+r)&&e.add(r);else{let r=-1;for(let i of n)(i=+t(i,++r,n))&&e.add(i)}return+e}function Nd(n,t){const e=new pn;let r=-1;return Float64Array.from(n,t===void 0?i=>e.add(+i||0):i=>e.add(+t(i,++r,n)||0))}class nr extends Map{constructor(t,e=rc){super();if(Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),t!=null)for(const[r,i]of t)this.set(r,i)}get(t){return super.get(ja(this,t))}has(t){return super.has(ja(this,t))}set(t,e){return super.set(tc(this,t),e)}delete(t){return super.delete(ec(this,t))}}class kd extends Set{constructor(t,e=rc){super();if(Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),t!=null)for(const r of t)this.add(r)}has(t){return super.has(ja(this,t))}add(t){return super.add(tc(this,t))}delete(t){return super.delete(ec(this,t))}}function ja({_intern:n,_key:t},e){const r=t(e);return n.has(r)?n.get(r):e}function tc({_intern:n,_key:t},e){const r=t(e);return n.has(r)?n.get(r):(n.set(r,e),e)}function ec({_intern:n,_key:t},e){const r=t(e);return n.has(r)&&(e=n.get(e),n.delete(r)),e}function rc(n){return n!==null&&typeof n=="object"?n.valueOf():n}function pe(n){return n}function ic(n,...t){return me(n,pe,pe,t)}function ac(n,...t){return me(n,Array.from,pe,t)}function oc(n,t){for(let e=1,r=t.length;ei.pop().map(([a,o])=>[...i,a,o]));return n}function $d(n,...t){return oc(ac(n,...t),t)}function Cd(n,t,...e){return oc(fc(n,t,...e),e)}function uc(n,t,...e){return me(n,pe,t,e)}function fc(n,t,...e){return me(n,Array.from,t,e)}function Rd(n,...t){return me(n,pe,cc,t)}function Pd(n,...t){return me(n,Array.from,cc,t)}function cc(n){if(n.length!==1)throw new Error("duplicate key");return n[0]}function me(n,t,e,r){return function i(a,o){if(o>=r.length)return e(a);const u=new nr,f=r[o++];let c=-1;for(const s of a){const h=f(s,++c,a),l=u.get(h);l?l.push(s):u.set(h,[s])}for(const[s,h]of u)u.set(s,i(h,o));return t(u)}(n,0)}function sc(n,t){return Array.from(t,e=>n[e])}function no(n,...t){if(typeof n[Symbol.iterator]!="function")throw new TypeError("values is not iterable");n=Array.from(n);let[e]=t;if(e&&e.length===1||t.length>1){const r=Uint32Array.from(n,(i,a)=>a);return t.length>1?(t=t.map(i=>n.map(i)),r.sort((i,a)=>{for(const o of t){const u=ti(o[i],o[a]);if(u)return u}})):(e=n.map(e),r.sort((i,a)=>ti(e[i],e[a]))),sc(n,r)}return n.sort(e===void 0?ti:lc(e))}function lc(n){if(typeof n!="function")throw new TypeError("compare is not a function");return(t,e)=>{const r=n(t,e);return r||r===0?r:(n(e,e)===0)-(n(t,t)===0)}}function ti(n,t){return(n==null||!(n>=n))-(t==null||!(t>=t))||(nt?1:0)}function Id(n,t,e){return(t.length===1?no(uc(n,t,e),([r,i],[a,o])=>wn(i,o)||wn(r,a)):no(ic(n,e),([r,i],[a,o])=>t(i,o)||wn(r,a))).map(([r])=>r)}var zd=Array.prototype,Dd=zd.slice;function ei(n){return()=>n}var to=Math.sqrt(50),eo=Math.sqrt(10),ro=Math.sqrt(2);function ye(n,t,e){var r,i=-1,a,o,u;if(t=+t,n=+n,e=+e,n===t&&e>0)return[n];if((r=t0){let f=Math.round(n/u),c=Math.round(t/u);for(f*ut&&--c,o=new Array(a=c-f+1);++it&&--c,o=new Array(a=c-f+1);++i=0?(a>=to?10:a>=eo?5:a>=ro?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=to?10:a>=eo?5:a>=ro?2:1)}function ve(n,t,e){var r=Math.abs(t-n)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=to?i*=10:a>=eo?i*=5:a>=ro&&(i*=2),t0?(n=Math.floor(n/i)*i,t=Math.ceil(t/i)*i):i<0&&(n=Math.ceil(n*i)/i,t=Math.floor(t*i)/i),r=i}}function io(n){return Math.ceil(Math.log(ni(n))/Math.LN2)+1}function dc(){var n=pe,t=je,e=io;function r(i){Array.isArray(i)||(i=Array.from(i));var a,o=i.length,u,f=new Array(o);for(a=0;a=h)if(g>=h&&t===je){const b=tr(s,h,p);isFinite(b)&&(b>0?h=(Math.floor(h/b)+1)*b:b<0&&(h=(Math.ceil(h*-b)+1)/-b))}else l.pop()}for(var d=l.length;l[0]<=s;)l.shift(),--d;for(;l[d-1]>h;)l.pop(),--d;var y=new Array(d+1),m;for(a=0;a<=d;++a)m=y[a]=[],m.x0=a>0?l[a-1]:s,m.x1=a=r)&&(e=r);else{let r=-1;for(let i of n)(i=t(i,++r,n))!=null&&(e=i)&&(e=i)}return e}function ii(n,t){let e;if(t===void 0)for(const r of n)r!=null&&(e>r||e===void 0&&r>=r)&&(e=r);else{let r=-1;for(let i of n)(i=t(i,++r,n))!=null&&(e>i||e===void 0&&i>=i)&&(e=i)}return e}function ao(n,t,e=0,r=n.length-1,i){for(i=i===void 0?ti:lc(i);r>e;){if(r-e>600){const f=r-e+1,c=t-e+1,s=Math.log(f),h=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*h*(f-h)/f)*(c-f/2<0?-1:1),d=Math.max(e,Math.floor(t-c*h/f+l)),y=Math.min(r,Math.floor(t+(f-c)*h/f+l));ao(n,t,d,y,i)}const a=n[t];let o=e,u=r;for(er(n,e,t),i(n[r],a)>0&&er(n,e,r);o0;)--u}i(n[e],a)===0?er(n,e,u):(++u,er(n,u,r)),u<=t&&(e=u+1),t<=u&&(r=u-1)}return n}function er(n,t,e){const r=n[t];n[t]=n[e],n[e]=r}function rr(n,t,e){if(n=Float64Array.from(yd(n,e)),!!(r=n.length)){if((t=+t)<=0||r<2)return ii(n);if(t>=1)return ri(n);var r,i=(r-1)*t,a=Math.floor(i),o=ri(ao(n,a).subarray(0,a+1)),u=ii(n.subarray(a+1));return o+(u-o)*(i-a)}}function gc(n,t,e=Kf){if(!!(r=n.length)){if((t=+t)<=0||r<2)return+e(n[0],0,n);if(t>=1)return+e(n[r-1],r-1,n);var r,i=(r-1)*t,a=Math.floor(i),o=+e(n[a],a,n),u=+e(n[a+1],a+1,n);return o+(u-o)*(i-a)}}function Od(n,t,e){return Math.ceil((e-t)/(2*(rr(n,.75)-rr(n,.25))*Math.pow(ni(n),-1/3)))}function qd(n,t,e){return Math.ceil((e-t)/(3.5*nc(n)*Math.pow(ni(n),-1/3)))}function pc(n,t){let e,r=-1,i=-1;if(t===void 0)for(const a of n)++i,a!=null&&(e=a)&&(e=a,r=i);else for(let a of n)(a=t(a,++i,n))!=null&&(e=a)&&(e=a,r=i);return r}function Ld(n,t){let e=0,r=0;if(t===void 0)for(let i of n)i!=null&&(i=+i)>=i&&(++e,r+=i);else{let i=-1;for(let a of n)(a=t(a,++i,n))!=null&&(a=+a)>=a&&(++e,r+=a)}if(e)return r/e}function Fd(n,t){return rr(n,.5,t)}function*Yd(n){for(const t of n)yield*t}function oo(n){return Array.from(Yd(n))}function mc(n,t){let e,r=-1,i=-1;if(t===void 0)for(const a of n)++i,a!=null&&(e>a||e===void 0&&a>=a)&&(e=a,r=i);else for(let a of n)(a=t(a,++i,n))!=null&&(e>a||e===void 0&&a>=a)&&(e=a,r=i);return r}function Ud(n,t){const e=new nr;if(t===void 0)for(let a of n)a!=null&&a>=a&&e.set(a,(e.get(a)||0)+1);else{let a=-1;for(let o of n)(o=t(o,++a,n))!=null&&o>=o&&e.set(o,(e.get(o)||0)+1)}let r,i=0;for(const[a,o]of e)o>i&&(i=o,r=a);return r}function Bd(n,t=Hd){const e=[];let r,i=!1;for(const a of n)i&&e.push(t(r,a)),r=a,i=!0;return e}function Hd(n,t){return[n,t]}function _t(n,t,e){n=+n,t=+t,e=(i=arguments.length)<2?(t=n,n=0,1):i<3?1:+e;for(var r=-1,i=Math.max(0,Math.ceil((t-n)/e))|0,a=new Array(i);++r0:wn(o,o)===0)&&(e=a,i=o,r=!0)}}else for(const i of n)(r?t(i,e)>0:t(i,i)===0)&&(e=i,r=!0);return e}function Vd(n,t=wn){if(t.length===1)return pc(n,t);let e,r=-1,i=-1;for(const a of n)++i,(r<0?t(a,a)===0:t(a,e)>0)&&(e=a,r=i);return r}function Wd(n,t){const e=yc(n,t);return e<0?void 0:e}var Zd=vc(Math.random);function vc(n){return function(e,r=0,i=e.length){let a=i-(r=+r);for(;a;){const o=n()*a--|0,u=e[a+r];e[a+r]=e[o+r],e[o+r]=u}return e}}function Qd(n,t){let e=0;if(t===void 0)for(let r of n)(r=+r)&&(e+=r);else{let r=-1;for(let i of n)(i=+t(i,++r,n))&&(e+=i)}return e}function _c(n){if(!(a=n.length))return[];for(var t=-1,e=ii(n,Kd),r=new Array(e);++tt(e,r,n))}function rg(n,t,e){if(typeof t!="function")throw new TypeError("reducer is not a function");const r=n[Symbol.iterator]();let i,a,o=-1;if(arguments.length<3){if({done:i,value:e}=r.next(),i)return;++o}for(;{done:i,value:a}=r.next(),!i;)e=t(e,a,++o,n);return e}function ig(n){if(typeof n[Symbol.iterator]!="function")throw new TypeError("values is not iterable");return Array.from(n).reverse()}function ag(n,...t){n=new Set(n);for(const e of t)for(const r of e)n.delete(r);return n}function og(n,t){const e=t[Symbol.iterator](),r=new Set;for(const i of n){if(r.has(i))return!1;let a,o;for(;({value:a,done:o}=e.next())&&!o;){if(Object.is(i,a))return!1;r.add(a)}}return!0}function ug(n){return n instanceof Set?n:new Set(n)}function fg(n,...t){n=new Set(n),t=t.map(ug);n:for(const e of n)for(const r of t)if(!r.has(e)){n.delete(e);continue n}return n}function bc(n,t){const e=n[Symbol.iterator](),r=new Set;for(const i of t){if(r.has(i))continue;let a,o;for(;{value:a,done:o}=e.next();){if(o)return!1;if(r.add(a),Object.is(i,a))break}}return!0}function cg(n,t){return bc(t,n)}function sg(...n){const t=new Set;for(const e of n)for(const r of e)t.add(r);return t}function lg(n){return n}var ai=1,oi=2,uo=3,ir=4,wc=1e-6;function hg(n){return"translate("+n+",0)"}function dg(n){return"translate(0,"+n+")"}function gg(n){return t=>+n(t)}function pg(n,t){return t=Math.max(0,n.bandwidth()-t*2)/2,n.round()&&(t=Math.round(t)),e=>+n(e)+t}function mg(){return!this.__axis}function ui(n,t){var e=[],r=null,i=null,a=6,o=6,u=3,f=typeof window!="undefined"&&window.devicePixelRatio>1?0:.5,c=n===ai||n===ir?-1:1,s=n===ir||n===oi?"x":"y",h=n===ai||n===uo?hg:dg;function l(d){var y=r==null?t.ticks?t.ticks.apply(t,e):t.domain():r,m=i==null?t.tickFormat?t.tickFormat.apply(t,e):lg:i,g=Math.max(a,0)+u,p=t.range(),b=+p[0]+f,_=+p[p.length-1]+f,v=(t.bandwidth?pg:gg)(t.copy(),f),w=d.selection?d.selection():d,x=w.selectAll(".domain").data([null]),N=w.selectAll(".tick").data(y,t).order(),k=N.exit(),P=N.enter().append("g").attr("class","tick"),S=N.select("line"),E=N.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),N=N.merge(P),S=S.merge(P.append("line").attr("stroke","currentColor").attr(s+"2",c*a)),E=E.merge(P.append("text").attr("fill","currentColor").attr(s,c*g).attr("dy",n===ai?"0em":n===uo?"0.71em":"0.32em")),d!==w&&(x=x.transition(d),N=N.transition(d),S=S.transition(d),E=E.transition(d),k=k.transition(d).attr("opacity",wc).attr("transform",function(R){return isFinite(R=v(R))?h(R+f):this.getAttribute("transform")}),P.attr("opacity",wc).attr("transform",function(R){var $=this.parentNode.__axis;return h(($&&isFinite($=$(R))?$:v(R))+f)})),k.remove(),x.attr("d",n===ir||n===oi?o?"M"+c*o+","+b+"H"+f+"V"+_+"H"+c*o:"M"+f+","+b+"V"+_:o?"M"+b+","+c*o+"V"+f+"H"+_+"V"+c*o:"M"+b+","+f+"H"+_),N.attr("opacity",1).attr("transform",function(R){return h(v(R)+f)}),S.attr(s+"2",c*a),E.attr(s,c*g).text(m),w.filter(mg).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",n===oi?"start":n===ir?"end":"middle"),w.each(function(){this.__axis=v})}return l.scale=function(d){return arguments.length?(t=d,l):t},l.ticks=function(){return e=Array.from(arguments),l},l.tickArguments=function(d){return arguments.length?(e=d==null?[]:Array.from(d),l):e.slice()},l.tickValues=function(d){return arguments.length?(r=d==null?null:Array.from(d),l):r&&r.slice()},l.tickFormat=function(d){return arguments.length?(i=d,l):i},l.tickSize=function(d){return arguments.length?(a=o=+d,l):a},l.tickSizeInner=function(d){return arguments.length?(a=+d,l):a},l.tickSizeOuter=function(d){return arguments.length?(o=+d,l):o},l.tickPadding=function(d){return arguments.length?(u=+d,l):u},l.offset=function(d){return arguments.length?(f=+d,l):f},l}function yg(n){return ui(ai,n)}function vg(n){return ui(oi,n)}function _g(n){return ui(uo,n)}function bg(n){return ui(ir,n)}var wg={value:()=>{}};function Gt(){for(var n=0,t=arguments.length,e={},r;n=0&&(r=e.slice(i+1),e=e.slice(0,i)),e&&!t.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:r}})}fi.prototype=Gt.prototype={constructor:fi,on:function(n,t){var e=this._,r=xg(n+"",e),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var e=new Array(i),r=0,i,a;r=0&&(t=n.slice(0,e))!=="xmlns"&&(n=n.slice(e+1)),co.hasOwnProperty(t)?{space:co[t],local:n}:n}function Sg(n){return function(){var t=this.ownerDocument,e=this.namespaceURI;return e===fo&&t.documentElement.namespaceURI===fo?t.createElement(n):t.createElementNS(e,n)}}function Tg(n){return function(){return this.ownerDocument.createElementNS(n.space,n.local)}}function ci(n){var t=ar(n);return(t.local?Tg:Sg)(t)}function Ag(){}function si(n){return n==null?Ag:function(){return this.querySelector(n)}}function Eg(n){typeof n!="function"&&(n=si(n));for(var t=this._groups,e=t.length,r=new Array(e),i=0;i=_&&(_=b+1);!(w=g[_])&&++_=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function Kg(n){n||(n=Jg);function t(h,l){return h&&l?n(h.__data__,l.__data__):!h-!l}for(var e=this._groups,r=e.length,i=new Array(r),a=0;at?1:n>=t?0:NaN}function jg(){var n=arguments[0];return arguments[0]=this,n.apply(null,arguments),this}function np(){return Array.from(this)}function tp(){for(var n=this._groups,t=0,e=n.length;t1?this.each((t==null?hp:typeof t=="function"?gp:dp)(n,t,e==null?"":e)):Vt(this.node(),n)}function Vt(n,t){return n.style.getPropertyValue(t)||ho(n).getComputedStyle(n,null).getPropertyValue(t)}function mp(n){return function(){delete this[n]}}function yp(n,t){return function(){this[n]=t}}function vp(n,t){return function(){var e=t.apply(this,arguments);e==null?delete this[n]:this[n]=e}}function _p(n,t){return arguments.length>1?this.each((t==null?mp:typeof t=="function"?vp:yp)(n,t)):this.node()[n]}function Ac(n){return n.trim().split(/^|\s+/)}function go(n){return n.classList||new Ec(n)}function Ec(n){this._node=n,this._names=Ac(n.getAttribute("class")||"")}Ec.prototype={add:function(n){var t=this._names.indexOf(n);t<0&&(this._names.push(n),this._node.setAttribute("class",this._names.join(" ")))},remove:function(n){var t=this._names.indexOf(n);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(n){return this._names.indexOf(n)>=0}};function Nc(n,t){for(var e=go(n),r=-1,i=t.length;++r=0&&(e=t.slice(r+1),t=t.slice(0,r)),{type:t,name:e}})}function Vp(n){return function(){var t=this.__on;if(!!t){for(var e=0,r=-1,i=t.length,a;eXn(e,t))}function i2(n){return typeof n=="string"?new Rn([document.querySelectorAll(n)],[document.documentElement]):new Rn([Mc(n)],po)}const a2={passive:!1},or={capture:!0,passive:!1};function yo(n){n.stopImmediatePropagation()}function _e(n){n.preventDefault(),n.stopImmediatePropagation()}function hi(n){var t=n.document.documentElement,e=Sn(n).on("dragstart.drag",_e,or);"onselectstart"in t?e.on("selectstart.drag",_e,or):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function di(n,t){var e=n.document.documentElement,r=Sn(n).on("dragstart.drag",null);t&&(r.on("click.drag",_e,or),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in e?r.on("selectstart.drag",null):(e.style.MozUserSelect=e.__noselect,delete e.__noselect)}var gi=n=>()=>n;function vo(n,{sourceEvent:t,subject:e,target:r,identifier:i,active:a,x:o,y:u,dx:f,dy:c,dispatch:s}){Object.defineProperties(this,{type:{value:n,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:e,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:s}})}vo.prototype.on=function(){var n=this._.on.apply(this._,arguments);return n===this._?this:n};function o2(n){return!n.ctrlKey&&!n.button}function u2(){return this.parentNode}function f2(n,t){return t==null?{x:n.x,y:n.y}:t}function c2(){return navigator.maxTouchPoints||"ontouchstart"in this}function s2(){var n=o2,t=u2,e=f2,r=c2,i={},a=Gt("start","drag","end"),o=0,u,f,c,s,h=0;function l(v){v.on("mousedown.drag",d).filter(r).on("touchstart.drag",g).on("touchmove.drag",p,a2).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(v,w){if(!(s||!n.call(this,v,w))){var x=_(this,t.call(this,v,w),v,w,"mouse");!x||(Sn(v.view).on("mousemove.drag",y,or).on("mouseup.drag",m,or),hi(v.view),yo(v),c=!1,u=v.clientX,f=v.clientY,x("start",v))}}function y(v){if(_e(v),!c){var w=v.clientX-u,x=v.clientY-f;c=w*w+x*x>h}i.mouse("drag",v)}function m(v){Sn(v.view).on("mousemove.drag mouseup.drag",null),di(v.view,c),_e(v),i.mouse("end",v)}function g(v,w){if(!!n.call(this,v,w)){var x=v.changedTouches,N=t.call(this,v,w),k=x.length,P,S;for(P=0;P>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):e===8?pi(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):e===4?pi(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=h2.exec(n))?new xn(t[1],t[2],t[3],1):(t=d2.exec(n))?new xn(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=g2.exec(n))?pi(t[1],t[2],t[3],t[4]):(t=p2.exec(n))?pi(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=m2.exec(n))?Lc(t[1],t[2]/100,t[3]/100,1):(t=y2.exec(n))?Lc(t[1],t[2]/100,t[3]/100,t[4]):Pc.hasOwnProperty(n)?Dc(Pc[n]):n==="transparent"?new xn(NaN,NaN,NaN,0):null}function Dc(n){return new xn(n>>16&255,n>>8&255,n&255,1)}function pi(n,t,e,r){return r<=0&&(n=t=e=NaN),new xn(n,t,e,r)}function _o(n){return n instanceof Pt||(n=It(n)),n?(n=n.rgb(),new xn(n.r,n.g,n.b,n.opacity)):new xn}function Me(n,t,e,r){return arguments.length===1?_o(n):new xn(n,t,e,r==null?1:r)}function xn(n,t,e,r){this.r=+n,this.g=+t,this.b=+e,this.opacity=+r}be(xn,Me,ur(Pt,{brighter:function(n){return n=n==null?we:Math.pow(we,n),new xn(this.r*n,this.g*n,this.b*n,this.opacity)},darker:function(n){return n=n==null?Zt:Math.pow(Zt,n),new xn(this.r*n,this.g*n,this.b*n,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Oc,formatHex:Oc,formatRgb:qc,toString:qc}));function Oc(){return"#"+bo(this.r)+bo(this.g)+bo(this.b)}function qc(){var n=this.opacity;return n=isNaN(n)?1:Math.max(0,Math.min(1,n)),(n===1?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(n===1?")":", "+n+")")}function bo(n){return n=Math.max(0,Math.min(255,Math.round(n)||0)),(n<16?"0":"")+n.toString(16)}function Lc(n,t,e,r){return r<=0?n=t=e=NaN:e<=0||e>=1?n=t=NaN:t<=0&&(n=NaN),new ut(n,t,e,r)}function Fc(n){if(n instanceof ut)return new ut(n.h,n.s,n.l,n.opacity);if(n instanceof Pt||(n=It(n)),!n)return new ut;if(n instanceof ut)return n;n=n.rgb();var t=n.r/255,e=n.g/255,r=n.b/255,i=Math.min(t,e,r),a=Math.max(t,e,r),o=NaN,u=a-i,f=(a+i)/2;return u?(t===a?o=(e-r)/u+(e0&&f<1?0:o,new ut(o,u,f,n.opacity)}function mi(n,t,e,r){return arguments.length===1?Fc(n):new ut(n,t,e,r==null?1:r)}function ut(n,t,e,r){this.h=+n,this.s=+t,this.l=+e,this.opacity=+r}be(ut,mi,ur(Pt,{brighter:function(n){return n=n==null?we:Math.pow(we,n),new ut(this.h,this.s,this.l*n,this.opacity)},darker:function(n){return n=n==null?Zt:Math.pow(Zt,n),new ut(this.h,this.s,this.l*n,this.opacity)},rgb:function(){var n=this.h%360+(this.h<0)*360,t=isNaN(n)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*t,i=2*e-r;return new xn(wo(n>=240?n-240:n+120,i,r),wo(n,i,r),wo(n<120?n+240:n-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var n=this.opacity;return n=isNaN(n)?1:Math.max(0,Math.min(1,n)),(n===1?"hsl(":"hsla(")+(this.h||0)+", "+(this.s||0)*100+"%, "+(this.l||0)*100+"%"+(n===1?")":", "+n+")")}}));function wo(n,t,e){return(n<60?t+(e-t)*n/60:n<180?e:n<240?t+(e-t)*(240-n)/60:t)*255}const Yc=Math.PI/180,Uc=180/Math.PI,yi=18,Bc=.96422,Hc=1,Xc=.82521,Gc=4/29,Se=6/29,Vc=3*Se*Se,_2=Se*Se*Se;function Wc(n){if(n instanceof tt)return new tt(n.l,n.a,n.b,n.opacity);if(n instanceof ft)return Qc(n);n instanceof xn||(n=_o(n));var t=To(n.r),e=To(n.g),r=To(n.b),i=xo((.2225045*t+.7168786*e+.0606169*r)/Hc),a,o;return t===e&&e===r?a=o=i:(a=xo((.4360747*t+.3850649*e+.1430804*r)/Bc),o=xo((.0139322*t+.0971045*e+.7141733*r)/Xc)),new tt(116*i-16,500*(a-i),200*(i-o),n.opacity)}function b2(n,t){return new tt(n,0,0,t==null?1:t)}function vi(n,t,e,r){return arguments.length===1?Wc(n):new tt(n,t,e,r==null?1:r)}function tt(n,t,e,r){this.l=+n,this.a=+t,this.b=+e,this.opacity=+r}be(tt,vi,ur(Pt,{brighter:function(n){return new tt(this.l+yi*(n==null?1:n),this.a,this.b,this.opacity)},darker:function(n){return new tt(this.l-yi*(n==null?1:n),this.a,this.b,this.opacity)},rgb:function(){var n=(this.l+16)/116,t=isNaN(this.a)?n:n+this.a/500,e=isNaN(this.b)?n:n-this.b/200;return t=Bc*Mo(t),n=Hc*Mo(n),e=Xc*Mo(e),new xn(So(3.1338561*t-1.6168667*n-.4906146*e),So(-.9787684*t+1.9161415*n+.033454*e),So(.0719453*t-.2289914*n+1.4052427*e),this.opacity)}}));function xo(n){return n>_2?Math.pow(n,1/3):n/Vc+Gc}function Mo(n){return n>Se?n*n*n:Vc*(n-Gc)}function So(n){return 255*(n<=.0031308?12.92*n:1.055*Math.pow(n,1/2.4)-.055)}function To(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Zc(n){if(n instanceof ft)return new ft(n.h,n.c,n.l,n.opacity);if(n instanceof tt||(n=Wc(n)),n.a===0&&n.b===0)return new ft(NaN,0=1?(e=1,t-1):Math.floor(e*t),i=n[r],a=n[r+1],o=r>0?n[r-1]:2*i-a,u=r()=>n;function is(n,t){return function(e){return n+e*t}}function M2(n,t,e){return n=Math.pow(n,e),t=Math.pow(t,e)-n,e=1/e,function(r){return Math.pow(n+r*t,e)}}function xi(n,t){var e=t-n;return e?is(n,e>180||e<-180?e-360*Math.round(e/360):e):wi(isNaN(n)?t:n)}function S2(n){return(n=+n)==1?vn:function(t,e){return e-t?M2(t,e,n):wi(isNaN(t)?e:t)}}function vn(n,t){var e=t-n;return e?is(n,e):wi(isNaN(n)?t:n)}var sr=function n(t){var e=S2(t);function r(i,a){var o=e((i=Me(i)).r,(a=Me(a)).r),u=e(i.g,a.g),f=e(i.b,a.b),c=vn(i.opacity,a.opacity);return function(s){return i.r=o(s),i.g=u(s),i.b=f(s),i.opacity=c(s),i+""}}return r.gamma=n,r}(1);function as(n){return function(t){var e=t.length,r=new Array(e),i=new Array(e),a=new Array(e),o,u;for(o=0;oe&&(a=t.slice(e,a),u[o]?u[o]+=a:u[++o]=a),(r=r[0])===(i=i[0])?u[o]?u[o]+=i:u[++o]=i:(u[++o]=null,f.push({i:o,x:Wn(r,i)})),e=$o.lastIndex;return e180?s+=360:s-c>180&&(c+=360),l.push({i:h.push(i(h)+"rotate(",null,r)-2,x:Wn(c,s)})):s&&h.push(i(h)+"rotate("+s+r)}function u(c,s,h,l){c!==s?l.push({i:h.push(i(h)+"skewX(",null,r)-2,x:Wn(c,s)}):s&&h.push(i(h)+"skewX("+s+r)}function f(c,s,h,l,d,y){if(c!==h||s!==l){var m=d.push(i(d)+"scale(",null,",",null,")");y.push({i:m-4,x:Wn(c,h)},{i:m-2,x:Wn(s,l)})}else(h!==1||l!==1)&&d.push(i(d)+"scale("+h+","+l+")")}return function(c,s){var h=[],l=[];return c=n(c),s=n(s),a(c.translateX,c.translateY,s.translateX,s.translateY,h,l),o(c.rotate,s.rotate,h,l),u(c.skewX,s.skewX,h,l),f(c.scaleX,c.scaleY,s.scaleX,s.scaleY,h,l),c=s=null,function(d){for(var y=-1,m=l.length,g;++y=0&&n._call.call(void 0,t),n=n._next;--Te}function Ts(){Kt=(Ei=gr.now())+Ni,Te=lr=0;try{Ss()}finally{Te=0,X2(),Kt=0}}function H2(){var n=gr.now(),t=n-Ei;t>xs&&(Ni-=t,Ei=n)}function X2(){for(var n,t=Ai,e,r=Infinity;t;)t._call?(r>t._time&&(r=t._time),n=t,t=t._next):(e=t._next,t._next=null,t=n?n._next=e:Ai=e);dr=n,Po(r)}function Po(n){if(!Te){lr&&(lr=clearTimeout(lr));var t=n-Kt;t>24?(n{r.stop(),n(i+t)},t,e),r}function G2(n,t,e){var r=new mr,i=t;return t==null?(r.restart(n,t,e),r):(r._restart=r.restart,r.restart=function(a,o,u){o=+o,u=u==null?pr():+u,r._restart(function f(c){c+=i,r._restart(f,i+=o,u),a(c)},o,u)},r.restart(n,t,e),r)}var V2=Gt("start","end","cancel","interrupt"),W2=[],As=0,zo=1,Do=2,$i=3,Es=4,Oo=5,Ci=6;function Ri(n,t,e,r,i,a){var o=n.__transition;if(!o)n.__transition={};else if(e in o)return;Z2(n,e,{name:t,index:r,group:i,on:V2,tween:W2,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:As})}function qo(n,t){var e=rt(n,t);if(e.state>As)throw new Error("too late; already scheduled");return e}function ct(n,t){var e=rt(n,t);if(e.state>$i)throw new Error("too late; already running");return e}function rt(n,t){var e=n.__transition;if(!e||!(e=e[t]))throw new Error("transition not found");return e}function Z2(n,t,e){var r=n.__transition,i;r[t]=e,e.timer=ki(a,0,e.time);function a(c){e.state=zo,e.timer.restart(o,e.delay,e.time),e.delay<=c&&o(c-e.delay)}function o(c){var s,h,l,d;if(e.state!==zo)return f();for(s in r)if(d=r[s],d.name===e.name){if(d.state===$i)return Io(o);d.state===Es?(d.state=Ci,d.timer.stop(),d.on.call("interrupt",n,n.__data__,d.index,d.group),delete r[s]):+sDo&&r.state=0&&(t=t.slice(0,e)),!t||t==="start"})}function Tm(n,t,e){var r,i,a=Sm(t)?qo:ct;return function(){var o=a(this,n),u=o.on;u!==r&&(i=(r=u).copy()).on(t,e),o.on=i}}function Am(n,t){var e=this._id;return arguments.length<2?rt(this.node(),e).on.on(n):this.each(Tm(e,n,t))}function Em(n){return function(){var t=this.parentNode;for(var e in this.__transition)if(+e!==n)return;t&&t.removeChild(this)}}function Nm(){return this.on("end.remove",Em(this._id))}function km(n){var t=this._name,e=this._id;typeof n!="function"&&(n=si(n));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o+n;function Km(n){return n*n}function Jm(n){return n*(2-n)}function Rs(n){return((n*=2)<=1?n*n:--n*(2-n)+1)/2}function jm(n){return n*n*n}function ny(n){return--n*n*n+1}function Fo(n){return((n*=2)<=1?n*n*n:(n-=2)*n*n+2)/2}var Yo=3,ty=function n(t){t=+t;function e(r){return Math.pow(r,t)}return e.exponent=n,e}(Yo),ey=function n(t){t=+t;function e(r){return 1-Math.pow(1-r,t)}return e.exponent=n,e}(Yo),Ps=function n(t){t=+t;function e(r){return((r*=2)<=1?Math.pow(r,t):2-Math.pow(2-r,t))/2}return e.exponent=n,e}(Yo),Is=Math.PI,zs=Is/2;function ry(n){return+n==1?1:1-Math.cos(n*zs)}function iy(n){return Math.sin(n*zs)}function Ds(n){return(1-Math.cos(Is*n))/2}function Dt(n){return(Math.pow(2,-10*n)-.0009765625)*1.0009775171065494}function ay(n){return Dt(1-+n)}function oy(n){return 1-Dt(n)}function Os(n){return((n*=2)<=1?Dt(1-n):2-Dt(n-1))/2}function uy(n){return 1-Math.sqrt(1-n*n)}function fy(n){return Math.sqrt(1- --n*n)}function qs(n){return((n*=2)<=1?1-Math.sqrt(1-n*n):Math.sqrt(1-(n-=2)*n)+1)/2}var Uo=4/11,cy=6/11,sy=8/11,ly=3/4,hy=9/11,dy=10/11,gy=15/16,py=21/22,my=63/64,Pi=1/Uo/Uo;function yy(n){return 1-yr(1-n)}function yr(n){return(n=+n)zo&&r.name===t)return new st([[n]],Ay,t,+i)}return null}var Go=n=>()=>n;function Ny(n,{sourceEvent:t,target:e,selection:r,mode:i,dispatch:a}){Object.defineProperties(this,{type:{value:n,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:a}})}function ky(n){n.stopImmediatePropagation()}function Vo(n){n.preventDefault(),n.stopImmediatePropagation()}var Ys={name:"drag"},Wo={name:"space"},Ee={name:"handle"},Ne={name:"center"};const{abs:Us,max:Tn,min:An}=Math;function Bs(n){return[+n[0],+n[1]]}function Zo(n){return[Bs(n[0]),Bs(n[1])]}var Ii={name:"x",handles:["w","e"].map(vr),input:function(n,t){return n==null?null:[[+n[0],t[0][1]],[+n[1],t[1][1]]]},output:function(n){return n&&[n[0][0],n[1][0]]}},zi={name:"y",handles:["n","s"].map(vr),input:function(n,t){return n==null?null:[[t[0][0],+n[0]],[t[1][0],+n[1]]]},output:function(n){return n&&[n[0][1],n[1][1]]}},$y={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(vr),input:function(n){return n==null?null:Zo(n)},output:function(n){return n}},wt={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Hs={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},Xs={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},Cy={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},Ry={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function vr(n){return{type:n}}function Py(n){return!n.ctrlKey&&!n.button}function Iy(){var n=this.ownerSVGElement||this;return n.hasAttribute("viewBox")?(n=n.viewBox.baseVal,[[n.x,n.y],[n.x+n.width,n.y+n.height]]):[[0,0],[n.width.baseVal.value,n.height.baseVal.value]]}function zy(){return navigator.maxTouchPoints||"ontouchstart"in this}function Qo(n){for(;!n.__brush;)if(!(n=n.parentNode))return;return n.__brush}function Dy(n){return n[0][0]===n[1][0]||n[0][1]===n[1][1]}function Oy(n){var t=n.__brush;return t?t.dim.output(t.selection):null}function qy(){return Ko(Ii)}function Ly(){return Ko(zi)}function Fy(){return Ko($y)}function Ko(n){var t=Iy,e=Py,r=zy,i=!0,a=Gt("start","brush","end"),o=6,u;function f(g){var p=g.property("__brush",m).selectAll(".overlay").data([vr("overlay")]);p.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",wt.overlay).merge(p).each(function(){var _=Qo(this).extent;Sn(this).attr("x",_[0][0]).attr("y",_[0][1]).attr("width",_[1][0]-_[0][0]).attr("height",_[1][1]-_[0][1])}),g.selectAll(".selection").data([vr("selection")]).enter().append("rect").attr("class","selection").attr("cursor",wt.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var b=g.selectAll(".handle").data(n.handles,function(_){return _.type});b.exit().remove(),b.enter().append("rect").attr("class",function(_){return"handle handle--"+_.type}).attr("cursor",function(_){return wt[_.type]}),g.each(c).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",l).filter(r).on("touchstart.brush",l).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",y).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}f.move=function(g,p,b){g.tween?g.on("start.brush",function(_){s(this,arguments).beforestart().start(_)}).on("interrupt.brush end.brush",function(_){s(this,arguments).end(_)}).tween("brush",function(){var _=this,v=_.__brush,w=s(_,arguments),x=v.selection,N=n.input(typeof p=="function"?p.apply(this,arguments):p,v.extent),k=zt(x,N);function P(S){v.selection=S===1&&N===null?null:k(S),c.call(_),w.brush()}return x!==null&&N!==null?P:P(1)}):g.each(function(){var _=this,v=arguments,w=_.__brush,x=n.input(typeof p=="function"?p.apply(_,v):p,w.extent),N=s(_,v).beforestart();Jt(_),w.selection=x===null?null:x,c.call(_),N.start(b).brush(b).end(b)})},f.clear=function(g,p){f.move(g,null,p)};function c(){var g=Sn(this),p=Qo(this).selection;p?(g.selectAll(".selection").style("display",null).attr("x",p[0][0]).attr("y",p[0][1]).attr("width",p[1][0]-p[0][0]).attr("height",p[1][1]-p[0][1]),g.selectAll(".handle").style("display",null).attr("x",function(b){return b.type[b.type.length-1]==="e"?p[1][0]-o/2:p[0][0]-o/2}).attr("y",function(b){return b.type[0]==="s"?p[1][1]-o/2:p[0][1]-o/2}).attr("width",function(b){return b.type==="n"||b.type==="s"?p[1][0]-p[0][0]+o:o}).attr("height",function(b){return b.type==="e"||b.type==="w"?p[1][1]-p[0][1]+o:o})):g.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function s(g,p,b){var _=g.__brush.emitter;return _&&(!b||!_.clean)?_:new h(g,p,b)}function h(g,p,b){this.that=g,this.args=p,this.state=g.__brush,this.active=0,this.clean=b}h.prototype={beforestart:function(){return++this.active==1&&(this.state.emitter=this,this.starting=!0),this},start:function(g,p){return this.starting?(this.starting=!1,this.emit("start",g,p)):this.emit("brush",g),this},brush:function(g,p){return this.emit("brush",g,p),this},end:function(g,p){return--this.active==0&&(delete this.state.emitter,this.emit("end",g,p)),this},emit:function(g,p,b){var _=Sn(this.that).datum();a.call(g,this.that,new Ny(g,{sourceEvent:p,target:f,selection:n.output(this.state.selection),mode:b,dispatch:a}),_)}};function l(g){if(u&&!g.touches||!e.apply(this,arguments))return;var p=this,b=g.target.__data__.type,_=(i&&g.metaKey?b="overlay":b)==="selection"?Ys:i&&g.altKey?Ne:Ee,v=n===zi?null:Cy[b],w=n===Ii?null:Ry[b],x=Qo(p),N=x.extent,k=x.selection,P=N[0][0],S,E,R=N[0][1],$,M,T=N[1][0],A,C,I=N[1][1],D,O,L=0,U=0,tn,Z=v&&w&&i&&g.shiftKey,en,gn,j=Array.from(g.touches||[g],X=>{const sn=X.identifier;return X=Xn(X,p),X.point0=X.slice(),X.identifier=sn,X});Jt(p);var dn=s(p,arguments,!0).beforestart();if(b==="overlay"){k&&(tn=!0);const X=[j[0],j[1]||j[0]];x.selection=k=[[S=n===zi?P:An(X[0][0],X[1][0]),$=n===Ii?R:An(X[0][1],X[1][1])],[A=n===zi?T:Tn(X[0][0],X[1][0]),D=n===Ii?I:Tn(X[0][1],X[1][1])]],j.length>1&&cn(g)}else S=k[0][0],$=k[0][1],A=k[1][0],D=k[1][1];E=S,M=$,C=A,O=D;var q=Sn(p).attr("pointer-events","none"),G=q.selectAll(".overlay").attr("cursor",wt[b]);if(g.touches)dn.moved=z,dn.ended=rn;else{var K=Sn(g.view).on("mousemove.brush",z,!0).on("mouseup.brush",rn,!0);i&&K.on("keydown.brush",$n,!0).on("keyup.brush",Cn,!0),hi(g.view)}c.call(p),dn.start(g,_.name);function z(X){for(const sn of X.changedTouches||[X])for(const Ke of j)Ke.identifier===sn.identifier&&(Ke.cur=Xn(sn,p));if(Z&&!en&&!gn&&j.length===1){const sn=j[0];Us(sn.cur[0]-sn[0])>Us(sn.cur[1]-sn[1])?gn=!0:en=!0}for(const sn of j)sn.cur&&(sn[0]=sn.cur[0],sn[1]=sn.cur[1]);tn=!0,Vo(X),cn(X)}function cn(X){const sn=j[0],Ke=sn.point0;var Ct;switch(L=sn[0]-Ke[0],U=sn[1]-Ke[1],_){case Wo:case Ys:{v&&(L=Tn(P-S,An(T-A,L)),E=S+L,C=A+L),w&&(U=Tn(R-$,An(I-D,U)),M=$+U,O=D+U);break}case Ee:{j[1]?(v&&(E=Tn(P,An(T,j[0][0])),C=Tn(P,An(T,j[1][0])),v=1),w&&(M=Tn(R,An(I,j[0][1])),O=Tn(R,An(I,j[1][1])),w=1)):(v<0?(L=Tn(P-S,An(T-S,L)),E=S+L,C=A):v>0&&(L=Tn(P-A,An(T-A,L)),E=S,C=A+L),w<0?(U=Tn(R-$,An(I-$,U)),M=$+U,O=D):w>0&&(U=Tn(R-D,An(I-D,U)),M=$,O=D+U));break}case Ne:{v&&(E=Tn(P,An(T,S-L*v)),C=Tn(P,An(T,A+L*v))),w&&(M=Tn(R,An(I,$-U*w)),O=Tn(R,An(I,D+U*w)));break}}C0&&(S=E-L),w<0?D=O-U:w>0&&($=M-U),_=Wo,G.attr("cursor",wt.selection),cn(X));break}default:return}Vo(X)}function Cn(X){switch(X.keyCode){case 16:{Z&&(en=gn=Z=!1,cn(X));break}case 18:{_===Ne&&(v<0?A=C:v>0&&(S=E),w<0?D=O:w>0&&($=M),_=Ee,cn(X));break}case 32:{_===Wo&&(X.altKey?(v&&(A=C-L*v,S=E+L*v),w&&(D=O-U*w,$=M+U*w),_=Ne):(v<0?A=C:v>0&&(S=E),w<0?D=O:w>0&&($=M),_=Ee),G.attr("cursor",wt[b]),cn(X));break}default:return}Vo(X)}}function d(g){s(this,arguments).moved(g)}function y(g){s(this,arguments).ended(g)}function m(){var g=this.__brush||{selection:null};return g.extent=Zo(t.apply(this,arguments)),g.dim=n,g}return f.extent=function(g){return arguments.length?(t=typeof g=="function"?g:Go(Zo(g)),f):t},f.filter=function(g){return arguments.length?(e=typeof g=="function"?g:Go(!!g),f):e},f.touchable=function(g){return arguments.length?(r=typeof g=="function"?g:Go(!!g),f):r},f.handleSize=function(g){return arguments.length?(o=+g,f):o},f.keyModifiers=function(g){return arguments.length?(i=!!g,f):i},f.on=function(){var g=a.on.apply(a,arguments);return g===a?f:g},f}var Gs=Math.abs,ke=Math.cos,$e=Math.sin,Vs=Math.PI,Di=Vs/2,Ws=Vs*2,Zs=Math.max,Jo=1e-12;function jo(n,t){return Array.from({length:t-n},(e,r)=>n+r)}function Yy(n){return function(t,e){return n(t.source.value+t.target.value,e.source.value+e.target.value)}}function Uy(){return nu(!1,!1)}function By(){return nu(!1,!0)}function Hy(){return nu(!0,!1)}function nu(n,t){var e=0,r=null,i=null,a=null;function o(u){var f=u.length,c=new Array(f),s=jo(0,f),h=new Array(f*f),l=new Array(f),d=0,y;u=Float64Array.from({length:f*f},t?(m,g)=>u[g%f][g/f|0]:(m,g)=>u[g/f|0][g%f]);for(let m=0;mr(c[g],c[p]));for(const g of s){const p=m;if(n){const b=jo(~f+1,f).filter(_=>_<0?u[~_*f+g]:u[g*f+_]);i&&b.sort((_,v)=>i(_<0?-u[~_*f+g]:u[g*f+_],v<0?-u[~v*f+g]:u[g*f+v]));for(const _ of b)if(_<0){const v=h[~_*f+g]||(h[~_*f+g]={source:null,target:null});v.target={index:g,startAngle:m,endAngle:m+=u[~_*f+g]*d,value:u[~_*f+g]}}else{const v=h[g*f+_]||(h[g*f+_]={source:null,target:null});v.source={index:g,startAngle:m,endAngle:m+=u[g*f+_]*d,value:u[g*f+_]}}l[g]={index:g,startAngle:p,endAngle:m,value:c[g]}}else{const b=jo(0,f).filter(_=>u[g*f+_]||u[_*f+g]);i&&b.sort((_,v)=>i(u[g*f+_],u[g*f+v]));for(const _ of b){let v;if(g<_?(v=h[g*f+_]||(h[g*f+_]={source:null,target:null}),v.source={index:g,startAngle:m,endAngle:m+=u[g*f+_]*d,value:u[g*f+_]}):(v=h[_*f+g]||(h[_*f+g]={source:null,target:null}),v.target={index:g,startAngle:m,endAngle:m+=u[g*f+_]*d,value:u[g*f+_]},g===_&&(v.source=v.target)),v.source&&v.target&&v.source.valuejt)if(!(Math.abs(s*u-f*c)>jt)||!i)this._+="L"+(this._x1=n)+","+(this._y1=t);else{var l=e-a,d=r-o,y=u*u+f*f,m=l*l+d*d,g=Math.sqrt(y),p=Math.sqrt(h),b=i*Math.tan((tu-Math.acos((y+h-m)/(2*g*p)))/2),_=b/p,v=b/g;Math.abs(_-1)>jt&&(this._+="L"+(n+_*c)+","+(t+_*s)),this._+="A"+i+","+i+",0,0,"+ +(s*l>c*d)+","+(this._x1=n+v*u)+","+(this._y1=t+v*f)}},arc:function(n,t,e,r,i,a){n=+n,t=+t,e=+e,a=!!a;var o=e*Math.cos(r),u=e*Math.sin(r),f=n+o,c=t+u,s=1^a,h=a?r-i:i-r;if(e<0)throw new Error("negative radius: "+e);this._x1===null?this._+="M"+f+","+c:(Math.abs(this._x1-f)>jt||Math.abs(this._y1-c)>jt)&&(this._+="L"+f+","+c),!!e&&(h<0&&(h=h%eu+eu),h>Xy?this._+="A"+e+","+e+",0,1,"+s+","+(n-o)+","+(t-u)+"A"+e+","+e+",0,1,"+s+","+(this._x1=f)+","+(this._y1=c):h>jt&&(this._+="A"+e+","+e+",0,"+ +(h>=tu)+","+s+","+(this._x1=n+e*Math.cos(i))+","+(this._y1=t+e*Math.sin(i))))},rect:function(n,t,e,r){this._+="M"+(this._x0=this._x1=+n)+","+(this._y0=this._y1=+t)+"h"+ +e+"v"+ +r+"h"+-e+"Z"},toString:function(){return this._}};var Gy=Array.prototype.slice;function ne(n){return function(){return n}}function Vy(n){return n.source}function Wy(n){return n.target}function Qs(n){return n.radius}function Zy(n){return n.startAngle}function Qy(n){return n.endAngle}function Ky(){return 0}function Jy(){return 10}function Ks(n){var t=Vy,e=Wy,r=Qs,i=Qs,a=Zy,o=Qy,u=Ky,f=null;function c(){var s,h=t.apply(this,arguments),l=e.apply(this,arguments),d=u.apply(this,arguments)/2,y=Gy.call(arguments),m=+r.apply(this,(y[0]=h,y)),g=a.apply(this,y)-Di,p=o.apply(this,y)-Di,b=+i.apply(this,(y[0]=l,y)),_=a.apply(this,y)-Di,v=o.apply(this,y)-Di;if(f||(f=s=Ot()),d>Jo&&(Gs(p-g)>d*2+Jo?p>g?(g+=d,p-=d):(g-=d,p+=d):g=p=(g+p)/2,Gs(v-_)>d*2+Jo?v>_?(_+=d,v-=d):(_-=d,v+=d):_=v=(_+v)/2),f.moveTo(m*ke(g),m*$e(g)),f.arc(0,0,m,g,p),g!==_||p!==v)if(n){var w=+n.apply(this,arguments),x=b-w,N=(_+v)/2;f.quadraticCurveTo(0,0,x*ke(_),x*$e(_)),f.lineTo(b*ke(N),b*$e(N)),f.lineTo(x*ke(v),x*$e(v))}else f.quadraticCurveTo(0,0,b*ke(_),b*$e(_)),f.arc(0,0,b,_,v);if(f.quadraticCurveTo(0,0,m*ke(g),m*$e(g)),f.closePath(),s)return f=null,s+""||null}return n&&(c.headRadius=function(s){return arguments.length?(n=typeof s=="function"?s:ne(+s),c):n}),c.radius=function(s){return arguments.length?(r=i=typeof s=="function"?s:ne(+s),c):r},c.sourceRadius=function(s){return arguments.length?(r=typeof s=="function"?s:ne(+s),c):r},c.targetRadius=function(s){return arguments.length?(i=typeof s=="function"?s:ne(+s),c):i},c.startAngle=function(s){return arguments.length?(a=typeof s=="function"?s:ne(+s),c):a},c.endAngle=function(s){return arguments.length?(o=typeof s=="function"?s:ne(+s),c):o},c.padAngle=function(s){return arguments.length?(u=typeof s=="function"?s:ne(+s),c):u},c.source=function(s){return arguments.length?(t=s,c):t},c.target=function(s){return arguments.length?(e=s,c):e},c.context=function(s){return arguments.length?(f=s==null?null:s,c):f},c}function jy(){return Ks()}function nv(){return Ks(Jy)}var tv=Array.prototype,Js=tv.slice;function ev(n,t){return n-t}function rv(n){for(var t=0,e=n.length,r=n[e-1][1]*n[0][0]-n[e-1][0]*n[0][1];++t()=>n;function iv(n,t){for(var e=-1,r=t.length,i;++er!=d>r&&e<(l-c)*(r-s)/(d-s)+c&&(i=-i)}return i}function ov(n,t,e){var r;return uv(n,t,e)&&fv(n[r=+(n[0]===t[0])],e[r],t[r])}function uv(n,t,e){return(t[0]-n[0])*(e[1]-n[1])==(e[0]-n[0])*(t[1]-n[1])}function fv(n,t,e){return n<=t&&t<=e||e<=t&&t<=n}function cv(){}var xt=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function js(){var n=1,t=1,e=io,r=f;function i(c){var s=e(c);if(Array.isArray(s))s=s.slice().sort(ev);else{const h=je(c),l=ve(h[0],h[1],s);s=ye(Math.floor(h[0]/l)*l,Math.floor(h[1]/l-1)*l,s)}return s.map(h=>a(c,h))}function a(c,s){var h=[],l=[];return o(c,s,function(d){r(d,c,s),rv(d)>0?h.push([d]):l.push(d)}),l.forEach(function(d){for(var y=0,m=h.length,g;y=s,xt[p<<1].forEach(v);++y=s,xt[g|p<<1].forEach(v);for(xt[p<<0].forEach(v);++m=s,b=c[m*n]>=s,xt[p<<1|b<<2].forEach(v);++y=s,_=b,b=c[m*n+y+1]>=s,xt[g|p<<1|b<<2|_<<3].forEach(v);xt[p|b<<3].forEach(v)}for(y=-1,b=c[m*n]>=s,xt[b<<2].forEach(v);++y=s,xt[b<<2|_<<3].forEach(v);xt[b<<3].forEach(v);function v(w){var x=[w[0][0]+y,w[0][1]+m],N=[w[1][0]+y,w[1][1]+m],k=u(x),P=u(N),S,E;(S=d[k])?(E=l[P])?(delete d[S.end],delete l[E.start],S===E?(S.ring.push(N),h(S.ring)):l[S.start]=d[E.end]={start:S.start,end:E.end,ring:S.ring.concat(E.ring)}):(delete d[S.end],S.ring.push(N),d[S.end=P]=S):(S=l[P])?(E=d[k])?(delete l[S.start],delete d[E.end],S===E?(S.ring.push(N),h(S.ring)):l[E.start]=d[S.end]={start:E.start,end:S.end,ring:E.ring.concat(S.ring)}):(delete l[S.start],S.ring.unshift(x),l[S.start=k]=S):l[k]=d[P]={start:k,end:P,ring:[x,N]}}}function u(c){return c[0]*2+c[1]*(n+1)*4}function f(c,s,h){c.forEach(function(l){var d=l[0],y=l[1],m=d|0,g=y|0,p,b=s[g*n+m];d>0&&d0&&y=0&&h>=0))throw new Error("invalid size");return n=s,t=h,i},i.thresholds=function(c){return arguments.length?(e=typeof c=="function"?c:Array.isArray(c)?qt(Js.call(c)):qt(c),i):e},i.smooth=function(c){return arguments.length?(r=c?f:cv,i):r===f},i}function iu(n,t,e){for(var r=n.width,i=n.height,a=(e<<1)+1,o=0;o=e&&(u>=a&&(f-=n.data[u-a+o*r]),t.data[u-e+o*r]=f/Math.min(u+1,r-1+a-u,a))}function au(n,t,e){for(var r=n.width,i=n.height,a=(e<<1)+1,o=0;o=e&&(u>=a&&(f-=n.data[o+(u-a)*r]),t.data[o+(u-e)*r]=f/Math.min(u+1,i-1+a-u,a))}function sv(n){return n[0]}function lv(n){return n[1]}function hv(){return 1}function dv(){var n=sv,t=lv,e=hv,r=960,i=500,a=20,o=2,u=a*3,f=r+u*2>>o,c=i+u*2>>o,s=qt(20);function h(p){var b=new Float32Array(f*c),_=new Float32Array(f*c),v=Math.pow(2,-o);p.forEach(function(N,k,P){var S=(n(N,k,P)+u)*v,E=(t(N,k,P)+u)*v,R=+e(N,k,P);if(S>=0&&S=0&&E>o),au({width:f,height:c,data:_},{width:f,height:c,data:b},a>>o),iu({width:f,height:c,data:b},{width:f,height:c,data:_},a>>o),au({width:f,height:c,data:_},{width:f,height:c,data:b},a>>o),iu({width:f,height:c,data:b},{width:f,height:c,data:_},a>>o),au({width:f,height:c,data:_},{width:f,height:c,data:b},a>>o);var w=s(b);if(!Array.isArray(w)){var x=ri(b);w=ve(0,x,w),w=_t(0,Math.floor(x/w)*w,w),w.shift()}return js().thresholds(w).size([f,c])(b).map(l)}function l(p){return p.value*=Math.pow(2,-2*o),p.coordinates.forEach(d),p}function d(p){p.forEach(y)}function y(p){p.forEach(m)}function m(p){p[0]=p[0]*Math.pow(2,o)-u,p[1]=p[1]*Math.pow(2,o)-u}function g(){return u=a*3,f=r+u*2>>o,c=i+u*2>>o,h}return h.x=function(p){return arguments.length?(n=typeof p=="function"?p:qt(+p),h):n},h.y=function(p){return arguments.length?(t=typeof p=="function"?p:qt(+p),h):t},h.weight=function(p){return arguments.length?(e=typeof p=="function"?p:qt(+p),h):e},h.size=function(p){if(!arguments.length)return[r,i];var b=+p[0],_=+p[1];if(!(b>=0&&_>=0))throw new Error("invalid size");return r=b,i=_,g()},h.cellSize=function(p){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return o=Math.floor(Math.log(p)/Math.LN2),g()},h.thresholds=function(p){return arguments.length?(s=typeof p=="function"?p:Array.isArray(p)?qt(Js.call(p)):qt(p),h):s},h.bandwidth=function(p){if(!arguments.length)return Math.sqrt(a*(a+1));if(!((p=+p)>=0))throw new Error("invalid bandwidth");return a=Math.round((Math.sqrt(4*p*p+1)-1)/2),g()},h}const Mt=11102230246251565e-32,En=134217729,gv=(3+8*Mt)*Mt;function ou(n,t,e,r,i){let a,o,u,f,c=t[0],s=r[0],h=0,l=0;s>c==s>-c?(a=c,c=t[++h]):(a=s,s=r[++l]);let d=0;if(hc==s>-c?(o=c+a,u=a-(o-c),c=t[++h]):(o=s+a,u=a-(o-s),s=r[++l]),a=o,u!==0&&(i[d++]=u);hc==s>-c?(o=a+c,f=o-a,u=a-(o-f)+(c-f),c=t[++h]):(o=a+s,f=o-a,u=a-(o-f)+(s-f),s=r[++l]),a=o,u!==0&&(i[d++]=u);for(;h=M||-$>=M||(h=n-P,u=n-(P+h)+(h-i),h=e-S,c=e-(S+h)+(h-i),h=t-E,f=t-(E+h)+(h-a),h=r-R,s=r-(R+h)+(h-a),u===0&&f===0&&c===0&&s===0)||(M=vv*o+gv*Math.abs($),$+=P*s+R*u-(E*c+S*f),$>=M||-$>=M))return $;v=u*R,l=En*u,d=l-(l-u),y=u-d,l=En*R,m=l-(l-R),g=R-m,w=y*g-(v-d*m-y*m-d*g),x=f*S,l=En*f,d=l-(l-f),y=f-d,l=En*S,m=l-(l-S),g=S-m,N=y*g-(x-d*m-y*m-d*g),p=w-N,h=w-p,Pn[0]=w-(p+h)+(h-N),b=v+p,h=b-v,_=v-(b-h)+(p-h),p=_-x,h=_-p,Pn[1]=_-(p+h)+(h-x),k=b+p,h=k-b,Pn[2]=b-(k-h)+(p-h),Pn[3]=k;const T=ou(4,Ce,4,Pn,nl);v=P*s,l=En*P,d=l-(l-P),y=P-d,l=En*s,m=l-(l-s),g=s-m,w=y*g-(v-d*m-y*m-d*g),x=E*c,l=En*E,d=l-(l-E),y=E-d,l=En*c,m=l-(l-c),g=c-m,N=y*g-(x-d*m-y*m-d*g),p=w-N,h=w-p,Pn[0]=w-(p+h)+(h-N),b=v+p,h=b-v,_=v-(b-h)+(p-h),p=_-x,h=_-p,Pn[1]=_-(p+h)+(h-x),k=b+p,h=k-b,Pn[2]=b-(k-h)+(p-h),Pn[3]=k;const A=ou(T,nl,4,Pn,tl);v=u*s,l=En*u,d=l-(l-u),y=u-d,l=En*s,m=l-(l-s),g=s-m,w=y*g-(v-d*m-y*m-d*g),x=f*c,l=En*f,d=l-(l-f),y=f-d,l=En*c,m=l-(l-c),g=c-m,N=y*g-(x-d*m-y*m-d*g),p=w-N,h=w-p,Pn[0]=w-(p+h)+(h-N),b=v+p,h=b-v,_=v-(b-h)+(p-h),p=_-x,h=_-p,Pn[1]=_-(p+h)+(h-x),k=b+p,h=k-b,Pn[2]=b-(k-h)+(p-h),Pn[3]=k;const C=ou(A,tl,4,Pn,el);return el[C-1]}function Oi(n,t,e,r,i,a){const o=(t-a)*(e-i),u=(n-i)*(r-a),f=o-u;if(o===0||u===0||o>0!=u>0)return f;const c=Math.abs(o+u);return Math.abs(f)>=mv*c?f:-_v(n,t,e,r,i,a,c)}const rl=Math.pow(2,-52),qi=new Uint32Array(512);class Li{static from(t,e=Sv,r=Tv){const i=t.length,a=new Float64Array(i*2);for(let o=0;o>1;if(e>0&&typeof t[0]!="number")throw new Error("Expected coords to contain numbers.");this.coords=t;const r=Math.max(2*e-5,0);this._triangles=new Uint32Array(r*3),this._halfedges=new Int32Array(r*3),this._hashSize=Math.ceil(Math.sqrt(e)),this._hullPrev=new Uint32Array(e),this._hullNext=new Uint32Array(e),this._hullTri=new Uint32Array(e),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(e),this._dists=new Float64Array(e),this.update()}update(){const{coords:t,_hullPrev:e,_hullNext:r,_hullTri:i,_hullHash:a}=this,o=t.length>>1;let u=Infinity,f=Infinity,c=-Infinity,s=-Infinity;for(let S=0;Sc&&(c=E),R>s&&(s=R),this._ids[S]=S}const h=(u+c)/2,l=(f+s)/2;let d=Infinity,y,m,g;for(let S=0;S0&&(m=S,d=E)}let _=t[2*m],v=t[2*m+1],w=Infinity;for(let S=0;S$&&(S[E++]=M,$=this._dists[M])}this.hull=S.subarray(0,E),this.triangles=new Uint32Array(0),this.halfedges=new Uint32Array(0);return}if(Oi(p,b,_,v,x,N)<0){const S=m,E=_,R=v;m=g,_=x,v=N,g=S,x=E,N=R}const k=Mv(p,b,_,v,x,N);this._cx=k.x,this._cy=k.y;for(let S=0;S0&&Math.abs(M-E)<=rl&&Math.abs(T-R)<=rl||(E=M,R=T,$===y||$===m||$===g))continue;let A=0;for(let L=0,U=this._hashKey(M,T);L=0;)if(C=I,C===A){C=-1;break}if(C===-1)continue;let D=this._addTriangle(C,$,r[C],-1,-1,i[C]);i[$]=this._legalize(D+2),i[C]=D,P++;let O=r[C];for(;I=r[O],Oi(M,T,t[2*O],t[2*O+1],t[2*I],t[2*I+1])<0;)D=this._addTriangle(O,$,I,i[$],-1,i[O]),i[$]=this._legalize(D+2),r[O]=O,P--,O=I;if(C===A)for(;I=e[C],Oi(M,T,t[2*I],t[2*I+1],t[2*C],t[2*C+1])<0;)D=this._addTriangle(I,$,C,-1,i[C],i[I]),this._legalize(D+2),i[I]=D,r[C]=C,P--,C=I;this._hullStart=e[$]=C,r[C]=e[O]=$,r[$]=O,a[this._hashKey(M,T)]=$,a[this._hashKey(t[2*C],t[2*C+1])]=C}this.hull=new Uint32Array(P);for(let S=0,E=this._hullStart;S0?3-e:1+e)/4}function uu(n,t,e,r){const i=n-e,a=t-r;return i*i+a*a}function wv(n,t,e,r,i,a,o,u){const f=n-o,c=t-u,s=e-o,h=r-u,l=i-o,d=a-u,y=f*f+c*c,m=s*s+h*h,g=l*l+d*d;return f*(h*g-m*d)-c*(s*g-m*l)+y*(s*d-h*l)<0}function xv(n,t,e,r,i,a){const o=e-n,u=r-t,f=i-n,c=a-t,s=o*o+u*u,h=f*f+c*c,l=.5/(o*c-u*f),d=(c*s-u*h)*l,y=(o*h-f*s)*l;return d*d+y*y}function Mv(n,t,e,r,i,a){const o=e-n,u=r-t,f=i-n,c=a-t,s=o*o+u*u,h=f*f+c*c,l=.5/(o*c-u*f),d=n+(c*s-u*h)*l,y=t+(o*h-f*s)*l;return{x:d,y}}function Re(n,t,e,r){if(r-e<=20)for(let i=e+1;i<=r;i++){const a=n[i],o=t[a];let u=i-1;for(;u>=e&&t[n[u]]>o;)n[u+1]=n[u--];n[u+1]=a}else{const i=e+r>>1;let a=e+1,o=r;br(n,i,a),t[n[e]]>t[n[r]]&&br(n,e,r),t[n[a]]>t[n[r]]&&br(n,a,r),t[n[e]]>t[n[a]]&&br(n,e,a);const u=n[a],f=t[u];for(;;){do a++;while(t[n[a]]f);if(o=o-e?(Re(n,t,a,r),Re(n,t,e,o-1)):(Re(n,t,e,o-1),Re(n,t,a,r))}}function br(n,t,e){const r=n[t];n[t]=n[e],n[e]=r}function Sv(n){return n[0]}function Tv(n){return n[1]}const il=1e-6;class te{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,e){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,e){this._+=`L${this._x1=+t},${this._y1=+e}`}arc(t,e,r){t=+t,e=+e,r=+r;const i=t+r,a=e;if(r<0)throw new Error("negative radius");this._x1===null?this._+=`M${i},${a}`:(Math.abs(this._x1-i)>il||Math.abs(this._y1-a)>il)&&(this._+="L"+i+","+a),!!r&&(this._+=`A${r},${r},0,1,1,${t-r},${e}A${r},${r},0,1,1,${this._x1=i},${this._y1=a}`)}rect(t,e,r,i){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${+r}v${+i}h${-r}Z`}value(){return this._||null}}class fu{constructor(){this._=[]}moveTo(t,e){this._.push([t,e])}closePath(){this._.push(this._[0].slice())}lineTo(t,e){this._.push([t,e])}value(){return this._.length?this._:null}}class al{constructor(t,[e,r,i,a]=[0,0,960,500]){if(!((i=+i)>=(e=+e))||!((a=+a)>=(r=+r)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(t.points.length*2),this.vectors=new Float64Array(t.points.length*2),this.xmax=i,this.xmin=e,this.ymax=a,this.ymin=r,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:e,triangles:r},vectors:i}=this,a=this.circumcenters=this._circumcenters.subarray(0,r.length/3*2);for(let d=0,y=0,m=r.length,g,p;d1;)a-=2;for(let o=2;o4)for(let o=0;o0){if(e>=this.ymax)return null;(o=(this.ymax-e)/i)0){if(t>=this.xmax)return null;(o=(this.xmax-t)/r)this.xmax?2:0)|(ethis.ymax?8:0)}}const Av=2*Math.PI,Pe=Math.pow;function Ev(n){return n[0]}function Nv(n){return n[1]}function kv(n){const{triangles:t,coords:e}=n;for(let r=0;r1e-10)return!1}return!0}function $v(n,t,e){return[n+Math.sin(n+t)*e,t+Math.cos(n-t)*e]}class cu{static from(t,e=Ev,r=Nv,i){return new cu("length"in t?Cv(t,e,r,i):Float64Array.from(Rv(t,e,r,i)))}constructor(t){this._delaunator=new Li(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init()}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,e=this.points;if(t.hull&&t.hull.length>2&&kv(t)){this.collinear=Int32Array.from({length:e.length/2},(l,d)=>d).sort((l,d)=>e[2*l]-e[2*d]||e[2*l+1]-e[2*d+1]);const f=this.collinear[0],c=this.collinear[this.collinear.length-1],s=[e[2*f],e[2*f+1],e[2*c],e[2*c+1]],h=1e-8*Math.hypot(s[3]-s[1],s[2]-s[0]);for(let l=0,d=e.length/2;l0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=i[0],o[i[0]]=1,i.length===2&&(o[i[1]]=0,this.triangles[1]=i[1],this.triangles[2]=i[1]))}voronoi(t){return new al(this,t)}*neighbors(t){const{inedges:e,hull:r,_hullIndex:i,halfedges:a,triangles:o,collinear:u}=this;if(u){const h=u.indexOf(t);h>0&&(yield u[h-1]),h=0&&a!==r&&a!==i;)r=a;return a}_step(t,e,r){const{inedges:i,hull:a,_hullIndex:o,halfedges:u,triangles:f,points:c}=this;if(i[t]===-1||!c.length)return(t+1)%(c.length>>1);let s=t,h=Pe(e-c[t*2],2)+Pe(r-c[t*2+1],2);const l=i[t];let d=l;do{let y=f[d];const m=Pe(e-c[y*2],2)+Pe(r-c[y*2+1],2);if(m9999?"+"+Bn(n,6):Bn(n,4)}function zv(n){var t=n.getUTCHours(),e=n.getUTCMinutes(),r=n.getUTCSeconds(),i=n.getUTCMilliseconds();return isNaN(n)?"Invalid Date":Iv(n.getUTCFullYear())+"-"+Bn(n.getUTCMonth()+1,2)+"-"+Bn(n.getUTCDate(),2)+(i?"T"+Bn(t,2)+":"+Bn(e,2)+":"+Bn(r,2)+"."+Bn(i,3)+"Z":r?"T"+Bn(t,2)+":"+Bn(e,2)+":"+Bn(r,2)+"Z":e||t?"T"+Bn(t,2)+":"+Bn(e,2)+"Z":"")}function Fi(n){var t=new RegExp('["'+n+` +\r]`),e=n.charCodeAt(0);function r(h,l){var d,y,m=i(h,function(g,p){if(d)return d(g,p-1);y=g,d=l?Pv(g,l):ul(g)});return m.columns=y||[],m}function i(h,l){var d=[],y=h.length,m=0,g=0,p,b=y<=0,_=!1;h.charCodeAt(y-1)===wr&&--y,h.charCodeAt(y-1)===hu&&--y;function v(){if(b)return su;if(_)return _=!1,ol;var x,N=m,k;if(h.charCodeAt(N)===lu){for(;m++=y?b=!0:(k=h.charCodeAt(m++))===wr?_=!0:k===hu&&(_=!0,h.charCodeAt(m)===wr&&++m),h.slice(N+1,x-1).replace(/""/g,'"')}for(;mYi(t,e).then(r=>new DOMParser().parseFromString(r,n))}var u_=du("application/xml"),f_=du("text/html"),c_=du("image/svg+xml");function s_(n,t){var e,r=1;n==null&&(n=0),t==null&&(t=0);function i(){var a,o=e.length,u,f=0,c=0;for(a=0;a=(h=(u+c)/2))?u=h:c=h,(g=e>=(l=(f+s)/2))?f=l:s=l,i=a,!(a=a[p=g<<1|m]))return i[p]=o,n;if(d=+n._x.call(null,a.data),y=+n._y.call(null,a.data),t===d&&e===y)return o.next=a,i?i[p]=o:n._root=o,n;do i=i?i[p]=new Array(4):n._root=new Array(4),(m=t>=(h=(u+c)/2))?u=h:c=h,(g=e>=(l=(f+s)/2))?f=l:s=l;while((p=g<<1|m)==(b=(y>=l)<<1|d>=h));return i[b]=a,i[p]=o,n}function h_(n){var t,e,r=n.length,i,a,o=new Array(r),u=new Array(r),f=Infinity,c=Infinity,s=-Infinity,h=-Infinity;for(e=0;es&&(s=i),ah&&(h=a));if(f>s||c>h)return this;for(this.cover(f,c).cover(s,h),e=0;en||n>=i||r>t||t>=a;)switch(c=(ts||(u=y.y0)>h||(f=y.x1)=p)<<1|n>=g)&&(y=l[l.length-1],l[l.length-1]=l[l.length-1-m],l[l.length-1-m]=y)}else{var b=n-+this._x.call(null,d.data),_=t-+this._y.call(null,d.data),v=b*b+_*_;if(v=(l=(o+f)/2))?o=l:f=l,(m=h>=(d=(u+c)/2))?u=d:c=d,t=e,!(e=e[g=m<<1|y]))return this;if(!e.length)break;(t[g+1&3]||t[g+2&3]||t[g+3&3])&&(r=t,p=g)}for(;e.data!==n;)if(i=e,!(e=e.next))return this;return(a=e.next)&&delete e.next,i?(a?i.next=a:delete i.next,this):t?(a?t[g]=a:delete t[g],(e=t[0]||t[1]||t[2]||t[3])&&e===(t[3]||t[2]||t[1]||t[0])&&!e.length&&(r?r[p]=e:this._root=e),this):(this._root=a,this)}function v_(n){for(var t=0,e=n.length;tl.index){var E=d-k.x-k.vx,R=y-k.y-k.vy,$=E*E+R*R;$d+S||xy+S||Nc.r&&(c.r=c[s].r)}function f(){if(!!t){var c,s=t.length,h;for(e=new Array(s),c=0;c[t(w,x,o),w])),v;for(g=0,u=new Array(p);g(n=(R_*n+P_)%pl)/pl}function z_(n){return n.x}function D_(n){return n.y}var O_=10,q_=Math.PI*(3-Math.sqrt(5));function L_(n){var t,e=1,r=.001,i=1-Math.pow(r,1/300),a=0,o=.6,u=new Map,f=ki(h),c=Gt("tick","end"),s=I_();n==null&&(n=[]);function h(){l(),c.call("tick",t),e1?(g==null?u.delete(m):u.set(m,y(g)),t):u.get(m)},find:function(m,g,p){var b=0,_=n.length,v,w,x,N,k;for(p==null?p=Infinity:p*=p,b=0;b<_;++b)N=n[b],v=m-N.x,w=g-N.y,x=v*v+w*w,x1?(c.on(m,g),t):c.on(m)}}}function F_(){var n,t,e,r,i=mn(-30),a,o=1,u=Infinity,f=.81;function c(d){var y,m=n.length,g=Ui(n,z_,D_).visitAfter(h);for(r=d,y=0;y=u)return;(d.data!==t||d.next)&&(p===0&&(p=Lt(e),v+=p*p),b===0&&(b=Lt(e),v+=b*b),v0?1:n<0?-1:0},_n=Math.sqrt,yu=Math.tan;function bl(n){return n>1?0:n<-1?Q:Math.acos(n)}function qn(n){return n>1?ln:n<-1?-ln:Math.asin(n)}function wl(n){return(n=F(n/2))*n}function un(){}function Gi(n,t){n&&Ml.hasOwnProperty(n.type)&&Ml[n.type](n,t)}var xl={Feature:function(n,t){Gi(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,a=Y(t),o=F(t),u=wu*o,f=bu*a+u*Y(i),c=u*r*F(i);Vi.add(On(c,f)),_u=n,bu=a,wu=o}function V_(n){return Wi=new pn,it(n,lt),Wi*2}function Zi(n){return[On(n[1],n[0]),qn(n[2])]}function ie(n){var t=n[0],e=n[1],r=Y(e);return[r*Y(t),r*F(t),F(e)]}function Qi(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function ze(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function xu(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function Ki(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function Ji(n){var t=_n(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}var fn,Hn,hn,Gn,ae,Nl,kl,De,Mr,Ft,St,Tt={point:Mu,lineStart:Cl,lineEnd:Rl,polygonStart:function(){Tt.point=Pl,Tt.lineStart=W_,Tt.lineEnd=Z_,Mr=new pn,lt.polygonStart()},polygonEnd:function(){lt.polygonEnd(),Tt.point=Mu,Tt.lineStart=Cl,Tt.lineEnd=Rl,Vi<0?(fn=-(hn=180),Hn=-(Gn=90)):Mr>B?Gn=90:Mr<-B&&(Hn=-90),St[0]=fn,St[1]=hn},sphere:function(){fn=-(hn=180),Hn=-(Gn=90)}};function Mu(n,t){Ft.push(St=[fn=n,hn=n]),tGn&&(Gn=t)}function $l(n,t){var e=ie([n*H,t*H]);if(De){var r=ze(De,e),i=[r[1],-r[0],0],a=ze(i,r);Ji(a),a=Zi(a);var o=n-ae,u=o>0?1:-1,f=a[0]*an*u,c,s=J(o)>180;s^(u*aeGn&&(Gn=c)):(f=(f+360)%360-180,s^(u*aeGn&&(Gn=t))),s?nVn(fn,hn)&&(hn=n):Vn(n,hn)>Vn(fn,hn)&&(fn=n):hn>=fn?(nhn&&(hn=n)):n>ae?Vn(fn,n)>Vn(fn,hn)&&(hn=n):Vn(n,hn)>Vn(fn,hn)&&(fn=n)}else Ft.push(St=[fn=n,hn=n]);tGn&&(Gn=t),De=e,ae=n}function Cl(){Tt.point=$l}function Rl(){St[0]=fn,St[1]=hn,Tt.point=Mu,De=null}function Pl(n,t){if(De){var e=n-ae;Mr.add(J(e)>180?e+(e>0?360:-360):e)}else Nl=n,kl=t;lt.point(n,t),$l(n,t)}function W_(){lt.lineStart()}function Z_(){Pl(Nl,kl),lt.lineEnd(),J(Mr)>B&&(fn=-(hn=180)),St[0]=fn,St[1]=hn,De=null}function Vn(n,t){return(t-=n)<0?t+360:t}function Q_(n,t){return n[0]-t[0]}function Il(n,t){return n[0]<=n[1]?n[0]<=t&&t<=n[1]:tVn(r[0],r[1])&&(r[1]=i[1]),Vn(i[0],r[1])>Vn(r[0],r[1])&&(r[0]=i[0])):a.push(r=i);for(o=-Infinity,e=a.length-1,t=0,r=a[e];t<=e;r=i,++t)i=a[t],(u=Vn(r[1],i[0]))>o&&(o=u,fn=i[0],hn=r[1])}return Ft=St=null,fn===Infinity||Hn===Infinity?[[NaN,NaN],[NaN,NaN]]:[[fn,Hn],[hn,Gn]]}var Sr,ji,na,ta,ea,ra,ia,aa,Su,Tu,Au,zl,Dl,Ln,Fn,Yn,at={sphere:un,point:Eu,lineStart:Ol,lineEnd:ql,polygonStart:function(){at.lineStart=nb,at.lineEnd=tb},polygonEnd:function(){at.lineStart=Ol,at.lineEnd=ql}};function Eu(n,t){n*=H,t*=H;var e=Y(t);Tr(e*Y(n),e*F(n),F(t))}function Tr(n,t,e){++Sr,na+=(n-na)/Sr,ta+=(t-ta)/Sr,ea+=(e-ea)/Sr}function Ol(){at.point=J_}function J_(n,t){n*=H,t*=H;var e=Y(t);Ln=e*Y(n),Fn=e*F(n),Yn=F(t),at.point=j_,Tr(Ln,Fn,Yn)}function j_(n,t){n*=H,t*=H;var e=Y(t),r=e*Y(n),i=e*F(n),a=F(t),o=On(_n((o=Fn*a-Yn*i)*o+(o=Yn*r-Ln*a)*o+(o=Ln*i-Fn*r)*o),Ln*r+Fn*i+Yn*a);ji+=o,ra+=o*(Ln+(Ln=r)),ia+=o*(Fn+(Fn=i)),aa+=o*(Yn+(Yn=a)),Tr(Ln,Fn,Yn)}function ql(){at.point=Eu}function nb(){at.point=eb}function tb(){Ll(zl,Dl),at.point=Eu}function eb(n,t){zl=n,Dl=t,n*=H,t*=H,at.point=Ll;var e=Y(t);Ln=e*Y(n),Fn=e*F(n),Yn=F(t),Tr(Ln,Fn,Yn)}function Ll(n,t){n*=H,t*=H;var e=Y(t),r=e*Y(n),i=e*F(n),a=F(t),o=Fn*a-Yn*i,u=Yn*r-Ln*a,f=Ln*i-Fn*r,c=pu(o,u,f),s=qn(c),h=c&&-s/c;Su.add(h*o),Tu.add(h*u),Au.add(h*f),ji+=s,ra+=s*(Ln+(Ln=r)),ia+=s*(Fn+(Fn=i)),aa+=s*(Yn+(Yn=a)),Tr(Ln,Fn,Yn)}function rb(n){Sr=ji=na=ta=ea=ra=ia=aa=0,Su=new pn,Tu=new pn,Au=new pn,it(n,at);var t=+Su,e=+Tu,r=+Au,i=pu(t,e,r);return iQ?n+Math.round(-n/Dn)*Dn:n,t]}ku.invert=ku;function $u(n,t,e){return(n%=Dn)?t||e?Nu(Yl(n),Ul(t,e)):Yl(n):t||e?Ul(t,e):ku}function Fl(n){return function(t,e){return t+=n,[t>Q?t-Dn:t<-Q?t+Dn:t,e]}}function Yl(n){var t=Fl(n);return t.invert=Fl(-n),t}function Ul(n,t){var e=Y(n),r=F(n),i=Y(t),a=F(t);function o(u,f){var c=Y(f),s=Y(u)*c,h=F(u)*c,l=F(f),d=l*e+s*r;return[On(h*i-d*a,s*e-l*r),qn(d*i+h*a)]}return o.invert=function(u,f){var c=Y(f),s=Y(u)*c,h=F(u)*c,l=F(f),d=l*i-h*a;return[On(h*i+l*a,s*e+d*r),qn(d*e-s*r)]},o}function Bl(n){n=$u(n[0]*H,n[1]*H,n.length>2?n[2]*H:0);function t(e){return e=n(e[0]*H,e[1]*H),e[0]*=an,e[1]*=an,e}return t.invert=function(e){return e=n.invert(e[0]*H,e[1]*H),e[0]*=an,e[1]*=an,e},t}function Hl(n,t,e,r,i,a){if(!!e){var o=Y(t),u=F(t),f=r*e;i==null?(i=t+r*Dn,a=t-f/2):(i=Xl(o,i),a=Xl(o,a),(r>0?ia)&&(i+=r*Dn));for(var c,s=i;r>0?s>a:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function oa(n,t){return J(n[0]-t[0])=0;--u)i.point((h=s[u])[0],h[1]);else r(l.x,l.p.x,-1,i);l=l.p}l=l.o,s=l.z,d=!d}while(!l.v);i.lineEnd()}}}function Wl(n){if(!!(t=n.length)){for(var t,e=0,r=n[0],i;++e=0?1:-1,S=P*k,E=S>Q,R=g*x;if(f.add(On(R*P*F(S),p*N+R*Y(S))),o+=E?k+P*Dn:k,E^y>=e^v>=e){var $=ze(ie(d),ie(_));Ji($);var M=ze(a,$);Ji(M);var T=(E^k>=0?-1:1)*qn(M[2]);(r>T||r===T&&($[0]||$[1]))&&(u+=E^k>=0?1:-1)}}return(o<-B||o0){for(f||(i.polygonStart(),f=!0),i.lineStart(),x=0;x1&&v&2&&w.push(w.pop().concat(w.shift())),s.push(w.filter(ab))}}return l}}function ab(n){return n.length>1}function ob(n,t){return((n=n.x)[0]<0?n[1]-ln-B:ln-n[1])-((t=t.x)[0]<0?t[1]-ln-B:ln-t[1])}var Ru=Ql(function(){return!0},ub,cb,[-Q,-ln]);function ub(n){var t=NaN,e=NaN,r=NaN,i;return{lineStart:function(){n.lineStart(),i=1},point:function(a,o){var u=a>0?Q:-Q,f=J(a-t);J(f-Q)0?ln:-ln),n.point(r,e),n.lineEnd(),n.lineStart(),n.point(u,e),n.point(a,e),i=0):r!==u&&f>=Q&&(J(t-r)B?Ie((F(t)*(a=Y(r))*F(e)-F(r)*(i=Y(t))*F(n))/(i*a*o)):(t+r)/2}function cb(n,t,e,r){var i;if(n==null)i=e*ln,r.point(-Q,i),r.point(0,i),r.point(Q,i),r.point(Q,0),r.point(Q,-i),r.point(0,-i),r.point(-Q,-i),r.point(-Q,0),r.point(-Q,i);else if(J(n[0]-t[0])>B){var a=n[0]0,i=J(t)>B;function a(s,h,l,d){Hl(d,n,e,l,s,h)}function o(s,h){return Y(s)*Y(h)>t}function u(s){var h,l,d,y,m;return{lineStart:function(){y=d=!1,m=1},point:function(g,p){var b=[g,p],_,v=o(g,p),w=r?v?0:c(g,p):v?c(g+(g<0?Q:-Q),p):0;if(!h&&(y=d=v)&&s.lineStart(),v!==d&&(_=f(h,b),(!_||oa(h,_)||oa(b,_))&&(b[2]=1)),v!==d)m=0,v?(s.lineStart(),_=f(b,h),s.point(_[0],_[1])):(_=f(h,b),s.point(_[0],_[1],2),s.lineEnd()),h=_;else if(i&&h&&r^v){var x;!(w&l)&&(x=f(b,h,!0))&&(m=0,r?(s.lineStart(),s.point(x[0][0],x[0][1]),s.point(x[1][0],x[1][1]),s.lineEnd()):(s.point(x[1][0],x[1][1]),s.lineEnd(),s.lineStart(),s.point(x[0][0],x[0][1],3)))}v&&(!h||!oa(h,b))&&s.point(b[0],b[1]),h=b,d=v,l=w},lineEnd:function(){d&&s.lineEnd(),h=null},clean:function(){return m|(y&&d)<<1}}}function f(s,h,l){var d=ie(s),y=ie(h),m=[1,0,0],g=ze(d,y),p=Qi(g,g),b=g[0],_=p-b*b;if(!_)return!l&&s;var v=t*p/_,w=-t*b/_,x=ze(m,g),N=Ki(m,v),k=Ki(g,w);xu(N,k);var P=x,S=Qi(N,P),E=Qi(P,P),R=S*S-E*(Qi(N,N)-1);if(!(R<0)){var $=_n(R),M=Ki(P,(-S-$)/E);if(xu(M,N),M=Zi(M),!l)return M;var T=s[0],A=h[0],C=s[1],I=h[1],D;A0^M[1]<(J(M[0]-T)Q^(T<=M[0]&&M[0]<=A)){var tn=Ki(P,(-S+$)/E);return xu(tn,N),[M,Zi(tn)]}}}function c(s,h){var l=r?n:Q-n,d=0;return s<-l?d|=1:s>l&&(d|=2),h<-l?d|=4:h>l&&(d|=8),d}return Ql(o,u,a,r?[0,-n]:[-Q,n-Q])}function sb(n,t,e,r,i,a){var o=n[0],u=n[1],f=t[0],c=t[1],s=0,h=1,l=f-o,d=c-u,y;if(y=e-o,!(!l&&y>0)){if(y/=l,l<0){if(y0){if(y>h)return;y>s&&(s=y)}if(y=i-o,!(!l&&y<0)){if(y/=l,l<0){if(y>h)return;y>s&&(s=y)}else if(l>0){if(y0)){if(y/=d,d<0){if(y0){if(y>h)return;y>s&&(s=y)}if(y=a-u,!(!d&&y<0)){if(y/=d,d<0){if(y>h)return;y>s&&(s=y)}else if(d>0){if(y0&&(n[0]=o+s*l,n[1]=u+s*d),h<1&&(t[0]=o+h*l,t[1]=u+h*d),!0}}}}}var Ar=1e9,fa=-Ar;function ca(n,t,e,r){function i(c,s){return n<=c&&c<=e&&t<=s&&s<=r}function a(c,s,h,l){var d=0,y=0;if(c==null||(d=o(c,h))!==(y=o(s,h))||f(c,s)<0^h>0)do l.point(d===0||d===3?n:e,d>1?r:t);while((d=(d+h+4)%4)!==y);else l.point(s[0],s[1])}function o(c,s){return J(c[0]-n)0?0:3:J(c[0]-e)0?2:1:J(c[1]-t)0?1:0:s>0?3:2}function u(c,s){return f(c.x,s.x)}function f(c,s){var h=o(c,1),l=o(s,1);return h!==l?h-l:h===0?s[1]-c[1]:h===1?c[0]-s[0]:h===2?c[1]-s[1]:s[0]-c[0]}return function(c){var s=c,h=Gl(),l,d,y,m,g,p,b,_,v,w,x,N={point:k,lineStart:R,lineEnd:$,polygonStart:S,polygonEnd:E};function k(T,A){i(T,A)&&s.point(T,A)}function P(){for(var T=0,A=0,C=d.length;Ar&&(Z-U)*(r-tn)>(en-tn)*(n-U)&&++T:en<=r&&(Z-U)*(r-tn)<(en-tn)*(n-U)&&--T;return T}function S(){s=h,l=[],d=[],x=!0}function E(){var T=P(),A=x&&T,C=(l=oo(l)).length;(A||C)&&(c.polygonStart(),A&&(c.lineStart(),a(null,null,1,c),c.lineEnd()),C&&Vl(l,u,T,a,c),c.polygonEnd()),s=c,l=d=y=null}function R(){N.point=M,d&&d.push(y=[]),w=!0,v=!1,b=_=NaN}function $(){l&&(M(m,g),p&&v&&h.rejoin(),l.push(h.result())),N.point=k,v&&s.lineEnd()}function M(T,A){var C=i(T,A);if(d&&y.push([T,A]),w)m=T,g=A,p=C,w=!1,C&&(s.lineStart(),s.point(T,A));else if(C&&v)s.point(T,A);else{var I=[b=Math.max(fa,Math.min(Ar,b)),_=Math.max(fa,Math.min(Ar,_))],D=[T=Math.max(fa,Math.min(Ar,T)),A=Math.max(fa,Math.min(Ar,A))];sb(I,D,n,t,e,r)?(v||(s.lineStart(),s.point(I[0],I[1])),s.point(D[0],D[1]),C||s.lineEnd(),x=!1):C&&(s.lineStart(),s.point(T,A),x=!1)}b=T,_=A,v=C}return N}}function lb(){var n=0,t=0,e=960,r=500,i,a,o;return o={stream:function(u){return i&&a===u?i:i=ca(n,t,e,r)(a=u)},extent:function(u){return arguments.length?(n=+u[0][0],t=+u[0][1],e=+u[1][0],r=+u[1][1],i=a=null,o):[[n,t],[e,r]]}}}var Pu,Iu,sa,la,qe={sphere:un,point:un,lineStart:hb,lineEnd:un,polygonStart:un,polygonEnd:un};function hb(){qe.point=gb,qe.lineEnd=db}function db(){qe.point=qe.lineEnd=un}function gb(n,t){n*=H,t*=H,Iu=n,sa=F(t),la=Y(t),qe.point=pb}function pb(n,t){n*=H,t*=H;var e=F(t),r=Y(t),i=J(n-Iu),a=Y(i),o=F(i),u=r*o,f=la*e-sa*r*a,c=sa*e+la*r*a;Pu.add(On(_n(u*u+f*f),c)),Iu=n,sa=e,la=r}function Jl(n){return Pu=new pn,it(n,qe),+Pu}var zu=[null,null],mb={type:"LineString",coordinates:zu};function ha(n,t){return zu[0]=n,zu[1]=t,Jl(mb)}var jl={Feature:function(n,t){return da(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,i=e.length;++r0&&(i=ha(n[a],n[a-1]),i>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))B}).map(l)).concat(_t(Hi(a/c)*c,i,c).filter(function(_){return J(_%h)>B}).map(d))}return p.lines=function(){return b().map(function(_){return{type:"LineString",coordinates:_}})},p.outline=function(){return{type:"Polygon",coordinates:[y(r).concat(m(o).slice(1),y(e).reverse().slice(1),m(u).reverse().slice(1))]}},p.extent=function(_){return arguments.length?p.extentMajor(_).extentMinor(_):p.extentMinor()},p.extentMajor=function(_){return arguments.length?(r=+_[0][0],e=+_[1][0],u=+_[0][1],o=+_[1][1],r>e&&(_=r,r=e,e=_),u>o&&(_=u,u=o,o=_),p.precision(g)):[[r,u],[e,o]]},p.extentMinor=function(_){return arguments.length?(t=+_[0][0],n=+_[1][0],a=+_[0][1],i=+_[1][1],t>n&&(_=t,t=n,n=_),a>i&&(_=a,a=i,i=_),p.precision(g)):[[t,a],[n,i]]},p.step=function(_){return arguments.length?p.stepMajor(_).stepMinor(_):p.stepMinor()},p.stepMajor=function(_){return arguments.length?(s=+_[0],h=+_[1],p):[s,h]},p.stepMinor=function(_){return arguments.length?(f=+_[0],c=+_[1],p):[f,c]},p.precision=function(_){return arguments.length?(g=+_,l=ah(a,i,90),d=oh(t,n,g),y=ah(u,o,90),m=oh(r,e,g),p):g},p.extentMajor([[-180,-90+B],[180,90-B]]).extentMinor([[-180,-80-B],[180,80+B]])}function _b(){return uh()()}function bb(n,t){var e=n[0]*H,r=n[1]*H,i=t[0]*H,a=t[1]*H,o=Y(r),u=F(r),f=Y(a),c=F(a),s=o*Y(e),h=o*F(e),l=f*Y(i),d=f*F(i),y=2*qn(_n(wl(a-r)+o*f*wl(i-e))),m=F(y),g=y?function(p){var b=F(p*=y)/m,_=F(y-p)/m,v=_*s+b*l,w=_*h+b*d,x=_*u+b*c;return[On(w,v)*an,On(x,_n(v*v+w*w))*an]}:function(){return[e*an,r*an]};return g.distance=y,g}var Er=n=>n,Du=new pn,Ou=new pn,fh,ch,qu,Lu,At={point:un,lineStart:un,lineEnd:un,polygonStart:function(){At.lineStart=wb,At.lineEnd=Mb},polygonEnd:function(){At.lineStart=At.lineEnd=At.point=un,Du.add(J(Ou)),Ou=new pn},result:function(){var n=Du/2;return Du=new pn,n}};function wb(){At.point=xb}function xb(n,t){At.point=sh,fh=qu=n,ch=Lu=t}function sh(n,t){Ou.add(Lu*n-qu*t),qu=n,Lu=t}function Mb(){sh(fh,ch)}var Le=Infinity,ga=Le,Nr=-Le,pa=Nr,ma={point:Sb,lineStart:un,lineEnd:un,polygonStart:un,polygonEnd:un,result:function(){var n=[[Le,ga],[Nr,pa]];return Nr=pa=-(ga=Le=Infinity),n}};function Sb(n,t){nNr&&(Nr=n),tpa&&(pa=t)}var Fu=0,Yu=0,kr=0,ya=0,va=0,Fe=0,Uu=0,Bu=0,$r=0,lh,hh,ht,dt,Qn={point:oe,lineStart:dh,lineEnd:gh,polygonStart:function(){Qn.lineStart=Eb,Qn.lineEnd=Nb},polygonEnd:function(){Qn.point=oe,Qn.lineStart=dh,Qn.lineEnd=gh},result:function(){var n=$r?[Uu/$r,Bu/$r]:Fe?[ya/Fe,va/Fe]:kr?[Fu/kr,Yu/kr]:[NaN,NaN];return Fu=Yu=kr=ya=va=Fe=Uu=Bu=$r=0,n}};function oe(n,t){Fu+=n,Yu+=t,++kr}function dh(){Qn.point=Tb}function Tb(n,t){Qn.point=Ab,oe(ht=n,dt=t)}function Ab(n,t){var e=n-ht,r=t-dt,i=_n(e*e+r*r);ya+=i*(ht+n)/2,va+=i*(dt+t)/2,Fe+=i,oe(ht=n,dt=t)}function gh(){Qn.point=oe}function Eb(){Qn.point=kb}function Nb(){ph(lh,hh)}function kb(n,t){Qn.point=ph,oe(lh=ht=n,hh=dt=t)}function ph(n,t){var e=n-ht,r=t-dt,i=_n(e*e+r*r);ya+=i*(ht+n)/2,va+=i*(dt+t)/2,Fe+=i,i=dt*n-ht*t,Uu+=i*(ht+n),Bu+=i*(dt+t),$r+=i*3,oe(ht=n,dt=t)}function mh(n){this._context=n}mh.prototype={_radius:4.5,pointRadius:function(n){return this._radius=n,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){this._line===0&&this._context.closePath(),this._point=NaN},point:function(n,t){switch(this._point){case 0:{this._context.moveTo(n,t),this._point=1;break}case 1:{this._context.lineTo(n,t);break}default:{this._context.moveTo(n+this._radius,t),this._context.arc(n,t,this._radius,0,Dn);break}}},result:un};var Hu=new pn,Xu,yh,vh,Cr,Rr,Pr={point:un,lineStart:function(){Pr.point=$b},lineEnd:function(){Xu&&_h(yh,vh),Pr.point=un},polygonStart:function(){Xu=!0},polygonEnd:function(){Xu=null},result:function(){var n=+Hu;return Hu=new pn,n}};function $b(n,t){Pr.point=_h,yh=Cr=n,vh=Rr=t}function _h(n,t){Cr-=n,Rr-=t,Hu.add(_n(Cr*Cr+Rr*Rr)),Cr=n,Rr=t}function bh(){this._string=[]}bh.prototype={_radius:4.5,_circle:wh(4.5),pointRadius:function(n){return(n=+n)!==this._radius&&(this._radius=n,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){this._line===0&&this._string.push("Z"),this._point=NaN},point:function(n,t){switch(this._point){case 0:{this._string.push("M",n,",",t),this._point=1;break}case 1:{this._string.push("L",n,",",t);break}default:{this._circle==null&&(this._circle=wh(this._radius)),this._string.push("M",n,",",t,this._circle);break}}},result:function(){if(this._string.length){var n=this._string.join("");return this._string=[],n}else return null}};function wh(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Cb(n,t){var e=4.5,r,i;function a(o){return o&&(typeof e=="function"&&i.pointRadius(+e.apply(this,arguments)),it(o,r(i))),i.result()}return a.area=function(o){return it(o,r(At)),At.result()},a.measure=function(o){return it(o,r(Pr)),Pr.result()},a.bounds=function(o){return it(o,r(ma)),ma.result()},a.centroid=function(o){return it(o,r(Qn)),Qn.result()},a.projection=function(o){return arguments.length?(r=o==null?(n=null,Er):(n=o).stream,a):n},a.context=function(o){return arguments.length?(i=o==null?(t=null,new bh):new mh(t=o),typeof e!="function"&&i.pointRadius(e),a):t},a.pointRadius=function(o){return arguments.length?(e=typeof o=="function"?o:(i.pointRadius(+o),+o),a):e},a.projection(n).context(t)}function Rb(n){return{stream:Ir(n)}}function Ir(n){return function(t){var e=new Gu;for(var r in n)e[r]=n[r];return e.stream=t,e}}function Gu(){}Gu.prototype={constructor:Gu,point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function Vu(n,t,e){var r=n.clipExtent&&n.clipExtent();return n.scale(150).translate([0,0]),r!=null&&n.clipExtent(null),it(e,n.stream(ma)),t(ma.result()),r!=null&&n.clipExtent(r),n}function _a(n,t,e){return Vu(n,function(r){var i=t[1][0]-t[0][0],a=t[1][1]-t[0][1],o=Math.min(i/(r[1][0]-r[0][0]),a/(r[1][1]-r[0][1])),u=+t[0][0]+(i-o*(r[1][0]+r[0][0]))/2,f=+t[0][1]+(a-o*(r[1][1]+r[0][1]))/2;n.scale(150*o).translate([u,f])},e)}function Wu(n,t,e){return _a(n,[[0,0],t],e)}function Zu(n,t,e){return Vu(n,function(r){var i=+t,a=i/(r[1][0]-r[0][0]),o=(i-a*(r[1][0]+r[0][0]))/2,u=-a*r[0][1];n.scale(150*a).translate([o,u])},e)}function Qu(n,t,e){return Vu(n,function(r){var i=+t,a=i/(r[1][1]-r[0][1]),o=-a*r[0][0],u=(i-a*(r[1][1]+r[0][1]))/2;n.scale(150*a).translate([o,u])},e)}var xh=16,Pb=Y(30*H);function Mh(n,t){return+t?zb(n,t):Ib(n)}function Ib(n){return Ir({point:function(t,e){t=n(t,e),this.stream.point(t[0],t[1])}})}function zb(n,t){function e(r,i,a,o,u,f,c,s,h,l,d,y,m,g){var p=c-r,b=s-i,_=p*p+b*b;if(_>4*t&&m--){var v=o+l,w=u+d,x=f+y,N=_n(v*v+w*w+x*x),k=qn(x/=N),P=J(J(x)-1)t||J((p*$+b*M)/_-.5)>.3||o*l+u*d+f*y2?T[2]%360*H:0,$()):[u*an,f*an,c*an]},E.angle=function(T){return arguments.length?(h=T%360*H,$()):h*an},E.reflectX=function(T){return arguments.length?(l=T?-1:1,$()):l<0},E.reflectY=function(T){return arguments.length?(d=T?-1:1,$()):d<0},E.precision=function(T){return arguments.length?(x=Mh(N,w=T*T),M()):_n(w)},E.fitExtent=function(T,A){return _a(E,T,A)},E.fitSize=function(T,A){return Wu(E,T,A)},E.fitWidth=function(T,A){return Zu(E,T,A)},E.fitHeight=function(T,A){return Qu(E,T,A)};function $(){var T=Sh(e,0,0,l,d,h).apply(null,t(a,o)),A=Sh(e,r-T[0],i-T[1],l,d,h);return s=$u(u,f,c),N=Nu(t,A),k=Nu(s,N),x=Mh(N,w),M()}function M(){return P=S=null,E}return function(){return t=n.apply(this,arguments),E.invert=t.invert&&R,$()}}function Ju(n){var t=0,e=Q/3,r=Ku(n),i=r(t,e);return i.parallels=function(a){return arguments.length?r(t=a[0]*H,e=a[1]*H):[t*an,e*an]},i}function Lb(n){var t=Y(n);function e(r,i){return[r*t,F(i)/t]}return e.invert=function(r,i){return[r/t,qn(i*t)]},e}function Th(n,t){var e=F(n),r=(e+F(t))/2;if(J(r)=.12&&g<.234&&m>=-.425&&m<-.214?i:g>=.166&&g<.234&&m>=-.214&&m<-.115?o:e).invert(l)},s.stream=function(l){return n&&t===l?n:n=Fb([e.stream(t=l),i.stream(l),o.stream(l)])},s.precision=function(l){return arguments.length?(e.precision(l),i.precision(l),o.precision(l),h()):e.precision()},s.scale=function(l){return arguments.length?(e.scale(l),i.scale(l*.35),o.scale(l),s.translate(e.translate())):e.scale()},s.translate=function(l){if(!arguments.length)return e.translate();var d=e.scale(),y=+l[0],m=+l[1];return r=e.translate(l).clipExtent([[y-.455*d,m-.238*d],[y+.455*d,m+.238*d]]).stream(c),a=i.translate([y-.307*d,m+.201*d]).clipExtent([[y-.425*d+B,m+.12*d+B],[y-.214*d-B,m+.234*d-B]]).stream(c),u=o.translate([y-.205*d,m+.212*d]).clipExtent([[y-.214*d+B,m+.166*d+B],[y-.115*d-B,m+.234*d-B]]).stream(c),h()},s.fitExtent=function(l,d){return _a(s,l,d)},s.fitSize=function(l,d){return Wu(s,l,d)},s.fitWidth=function(l,d){return Zu(s,l,d)},s.fitHeight=function(l,d){return Qu(s,l,d)};function h(){return n=t=null,s}return s.scale(1070)}function Eh(n){return function(t,e){var r=Y(t),i=Y(e),a=n(r*i);return a===Infinity?[2,0]:[a*i*F(t),a*F(e)]}}function zr(n){return function(t,e){var r=_n(t*t+e*e),i=n(r),a=F(i),o=Y(i);return[On(t*a,r*o),qn(r&&e*a/r)]}}var ju=Eh(function(n){return _n(2/(1+n))});ju.invert=zr(function(n){return 2*qn(n/2)});function Ub(){return gt(ju).scale(124.75).clipAngle(180-.001)}var nf=Eh(function(n){return(n=bl(n))&&n/F(n)});nf.invert=zr(function(n){return n});function Bb(){return gt(nf).scale(79.4188).clipAngle(180-.001)}function Dr(n,t){return[n,Xi(yu((ln+t)/2))]}Dr.invert=function(n,t){return[n,2*Ie(_l(t))-ln]};function Hb(){return Nh(Dr).scale(961/Dn)}function Nh(n){var t=gt(n),e=t.center,r=t.scale,i=t.translate,a=t.clipExtent,o=null,u,f,c;t.scale=function(h){return arguments.length?(r(h),s()):r()},t.translate=function(h){return arguments.length?(i(h),s()):i()},t.center=function(h){return arguments.length?(e(h),s()):e()},t.clipExtent=function(h){return arguments.length?(h==null?o=u=f=c=null:(o=+h[0][0],u=+h[0][1],f=+h[1][0],c=+h[1][1]),s()):o==null?null:[[o,u],[f,c]]};function s(){var h=Q*r(),l=t(Bl(t.rotate()).invert([0,0]));return a(o==null?[[l[0]-h,l[1]-h],[l[0]+h,l[1]+h]]:n===Dr?[[Math.max(l[0]-h,o),u],[Math.min(l[0]+h,f),c]]:[[o,Math.max(l[1]-h,u)],[f,Math.min(l[1]+h,c)]])}return s()}function wa(n){return yu((ln+n)/2)}function kh(n,t){var e=Y(n),r=n===t?F(n):Xi(e/Y(t))/Xi(wa(t)/wa(n)),i=e*mu(wa(n),r)/r;if(!r)return Dr;function a(o,u){i>0?u<-ln+B&&(u=-ln+B):u>ln-B&&(u=ln-B);var f=i/mu(wa(u),r);return[f*F(r*o),i-f*Y(r*o)]}return a.invert=function(o,u){var f=i-u,c=Zn(r)*_n(o*o+f*f),s=On(o,J(f))*Zn(f);return f*r<0&&(s-=Q*Zn(o)*Zn(f)),[s/r,2*Ie(mu(i/c,1/r))-ln]},a}function Xb(){return Ju(kh).scale(109.5).parallels([30,30])}function Or(n,t){return[n,t]}Or.invert=Or;function Gb(){return gt(Or).scale(152.63)}function $h(n,t){var e=Y(n),r=n===t?F(n):(e-Y(t))/(t-n),i=e/r+n;if(J(r)B&&--r>0);return[n/(.8707+(a=e*e)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),e]};function Jb(){return gt(rf).scale(175.295)}function af(n,t){return[Y(t)*F(n),F(t)]}af.invert=zr(qn);function jb(){return gt(af).scale(249.5).clipAngle(90+B)}function of(n,t){var e=Y(t),r=1+Y(n)*e;return[e*F(n)/r,F(t)/r]}of.invert=zr(function(n){return 2*Ie(n)});function n3(){return gt(of).scale(250).clipAngle(142)}function uf(n,t){return[Xi(yu((ln+t)/2)),-n]}uf.invert=function(n,t){return[-t,2*Ie(_l(n))-ln]};function t3(){var n=Nh(uf),t=n.center,e=n.rotate;return n.center=function(r){return arguments.length?t([-r[1],r[0]]):(r=t(),[r[1],-r[0]])},n.rotate=function(r){return arguments.length?e([r[0],r[1],r.length>2?r[2]+90:90]):(r=e(),[r[0],r[1],r[2]-90])},e([0,0,90]).scale(159.155)}function e3(n,t){return n.parent===t.parent?1:2}function r3(n){return n.reduce(i3,0)/n.length}function i3(n,t){return n+t.x}function a3(n){return 1+n.reduce(o3,0)}function o3(n,t){return Math.max(n,t.y)}function u3(n){for(var t;t=n.children;)n=t[0];return n}function f3(n){for(var t;t=n.children;)n=t[t.length-1];return n}function c3(){var n=e3,t=1,e=1,r=!1;function i(a){var o,u=0;a.eachAfter(function(l){var d=l.children;d?(l.x=r3(d),l.y=a3(d)):(l.x=o?u+=n(l,o):0,l.y=0,o=l)});var f=u3(a),c=f3(a),s=f.x-n(f,c)/2,h=c.x+n(c,f)/2;return a.eachAfter(r?function(l){l.x=(l.x-a.x)*t,l.y=(a.y-l.y)*e}:function(l){l.x=(l.x-s)/(h-s)*t,l.y=(1-(a.y?l.y/a.y:1))*e})}return i.separation=function(a){return arguments.length?(n=a,i):n},i.size=function(a){return arguments.length?(r=!1,t=+a[0],e=+a[1],i):r?null:[t,e]},i.nodeSize=function(a){return arguments.length?(r=!0,t=+a[0],e=+a[1],i):r?[t,e]:null},i}function s3(n){var t=0,e=n.children,r=e&&e.length;if(!r)t=1;else for(;--r>=0;)t+=e[r].value;n.value=t}function l3(){return this.eachAfter(s3)}function h3(n,t){let e=-1;for(const r of this)n.call(t,r,++e,this);return this}function d3(n,t){for(var e=this,r=[e],i,a,o=-1;e=r.pop();)if(n.call(t,e,++o,this),i=e.children)for(a=i.length-1;a>=0;--a)r.push(i[a]);return this}function g3(n,t){for(var e=this,r=[e],i=[],a,o,u,f=-1;e=r.pop();)if(i.push(e),a=e.children)for(o=0,u=a.length;o=0;)e+=r[i].value;t.value=e})}function y3(n){return this.eachBefore(function(t){t.children&&t.children.sort(n)})}function v3(n){for(var t=this,e=_3(t,n),r=[t];t!==e;)t=t.parent,r.push(t);for(var i=r.length;n!==e;)r.splice(i,0,n),n=n.parent;return r}function _3(n,t){if(n===t)return n;var e=n.ancestors(),r=t.ancestors(),i=null;for(n=e.pop(),t=r.pop();n===t;)i=n,n=e.pop(),t=r.pop();return i}function b3(){for(var n=this,t=[n];n=n.parent;)t.push(n);return t}function w3(){return Array.from(this)}function x3(){var n=[];return this.eachBefore(function(t){t.children||n.push(t)}),n}function M3(){var n=this,t=[];return n.each(function(e){e!==n&&t.push({source:e.parent,target:e})}),t}function*S3(){var n=this,t,e=[n],r,i,a;do for(t=e.reverse(),e=[];n=t.pop();)if(yield n,r=n.children)for(i=0,a=r.length;i=0;--u)i.push(a=o[u]=new ue(o[u])),a.parent=r,a.depth=r.depth+1;return e.eachBefore(Ch)}function T3(){return ff(this).eachBefore(N3)}function A3(n){return n.children}function E3(n){return Array.isArray(n)?n[1]:null}function N3(n){n.data.value!==void 0&&(n.value=n.data.value),n.data=n.data.data}function Ch(n){var t=0;do n.height=t;while((n=n.parent)&&n.height<++t)}function ue(n){this.data=n,this.depth=this.height=0,this.parent=null}ue.prototype=ff.prototype={constructor:ue,count:l3,each:h3,eachAfter:g3,eachBefore:d3,find:p3,sum:m3,sort:y3,path:v3,ancestors:b3,descendants:w3,leaves:x3,links:M3,copy:T3,[Symbol.iterator]:S3};function k3(n){return typeof n=="object"&&"length"in n?n:Array.from(n)}function $3(n){for(var t=n.length,e,r;t;)r=Math.random()*t--|0,e=n[t],n[t]=n[r],n[r]=e;return n}function Rh(n){for(var t=0,e=(n=$3(Array.from(n))).length,r=[],i,a;t0&&e*e>r*r+i*i}function cf(n,t){for(var e=0;ef?(i=(c+f-a)/(2*c),u=Math.sqrt(Math.max(0,f/c-i*i)),e.x=n.x-i*r-u*o,e.y=n.y-i*o+u*r):(i=(c+a-f)/(2*c),u=Math.sqrt(Math.max(0,a/c-i*i)),e.x=t.x+i*r-u*o,e.y=t.y+i*o+u*r)):(e.x=t.x+e.r,e.y=t.y)}function Dh(n,t){var e=n.r+t.r-1e-6,r=t.x-n.x,i=t.y-n.y;return e>0&&e*e>r*r+i*i}function Oh(n){var t=n._,e=n.next._,r=t.r+e.r,i=(t.x*e.r+e.x*t.r)/r,a=(t.y*e.r+e.y*t.r)/r;return i*i+a*a}function Sa(n){this._=n,this.next=null,this.previous=null}function qh(n){if(!(i=(n=k3(n)).length))return 0;var t,e,r,i,a,o,u,f,c,s,h;if(t=n[0],t.x=0,t.y=0,!(i>1))return t.r;if(e=n[1],t.x=-e.r,e.x=t.r,e.y=0,!(i>2))return t.r+e.r;zh(e,t,r=n[2]),t=new Sa(t),e=new Sa(e),r=new Sa(r),t.next=r.previous=e,e.next=t.previous=r,r.next=e.previous=t;n:for(u=3;u0)throw new Error("cycle");return f}return e.id=function(r){return arguments.length?(n=Ta(r),e):n},e.parentId=function(r){return arguments.length?(t=Ta(r),e):t},e}function B3(n,t){return n.parent===t.parent?1:2}function lf(n){var t=n.children;return t?t[0]:n.t}function hf(n){var t=n.children;return t?t[t.length-1]:n.t}function H3(n,t,e){var r=e/(t.i-n.i);t.c-=r,t.s+=e,n.c+=r,t.z+=e,t.m+=e}function X3(n){for(var t=0,e=0,r=n.children,i=r.length,a;--i>=0;)a=r[i],a.z+=t,a.m+=t,t+=a.s+(e+=a.c)}function G3(n,t,e){return n.a.parent===t.parent?n.a:e}function Aa(n,t){this._=n,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=t}Aa.prototype=Object.create(ue.prototype);function V3(n){for(var t=new Aa(n,0),e,r=[t],i,a,o,u;e=r.pop();)if(a=e._.children)for(e.children=new Array(u=a.length),o=u-1;o>=0;--o)r.push(i=e.children[o]=new Aa(a[o],o)),i.parent=e;return(t.parent=new Aa(null,0)).children=[t],t}function W3(){var n=B3,t=1,e=1,r=null;function i(c){var s=V3(c);if(s.eachAfter(a),s.parent.m=-s.z,s.eachBefore(o),r)c.eachBefore(f);else{var h=c,l=c,d=c;c.eachBefore(function(b){b.xl.x&&(l=b),b.depth>d.depth&&(d=b)});var y=h===l?1:n(h,l)/2,m=y-h.x,g=t/(l.x+y+m),p=e/(d.depth||1);c.eachBefore(function(b){b.x=(b.x+m)*g,b.y=b.depth*p})}return c}function a(c){var s=c.children,h=c.parent.children,l=c.i?h[c.i-1]:null;if(s){X3(c);var d=(s[0].z+s[s.length-1].z)/2;l?(c.z=l.z+n(c._,l._),c.m=c.z-d):c.z=d}else l&&(c.z=l.z+n(c._,l._));c.parent.A=u(c,l,c.parent.A||h[0])}function o(c){c._.x=c.z+c.parent.m,c.m+=c.parent.m}function u(c,s,h){if(s){for(var l=c,d=c,y=s,m=l.parent.children[0],g=l.m,p=d.m,b=y.m,_=m.m,v;y=hf(y),l=lf(l),y&&l;)m=lf(m),d=hf(d),d.a=c,v=y.z+b-l.z-g+n(y._,l._),v>0&&(H3(G3(y,c,h),c,v),g+=v,p+=v),b+=y.m,g+=l.m,_+=m.m,p+=d.m;y&&!hf(d)&&(d.t=y,d.m+=b-p),l&&!lf(m)&&(m.t=l,m.m+=g-_,h=c)}return h}function f(c){c.x*=t,c.y=c.depth*e}return i.separation=function(c){return arguments.length?(n=c,i):n},i.size=function(c){return arguments.length?(r=!1,t=+c[0],e=+c[1],i):r?null:[t,e]},i.nodeSize=function(c){return arguments.length?(r=!0,t=+c[0],e=+c[1],i):r?[t,e]:null},i}function Ea(n,t,e,r,i){for(var a=n.children,o,u=-1,f=a.length,c=n.value&&(i-e)/n.value;++ub&&(b=c),x=g*g*w,_=Math.max(b/x,x/p),_>v){g-=c;break}v=_}o.push(f={value:g,dice:d1?r:1)},e}(Bh);function Z3(){var n=Xh,t=!1,e=1,r=1,i=[0],a=fe,o=fe,u=fe,f=fe,c=fe;function s(l){return l.x0=l.y0=0,l.x1=e,l.y1=r,l.eachBefore(h),i=[0],t&&l.eachBefore(Yh),l}function h(l){var d=i[l.depth],y=l.x0+d,m=l.y0+d,g=l.x1-d,p=l.y1-d;g=l-1){var b=a[h];b.x0=y,b.y0=m,b.x1=g,b.y1=p;return}for(var _=c[h],v=d/2+_,w=h+1,x=l-1;w>>1;c[N]p-m){var S=d?(y*P+g*k)/d:g;s(h,w,k,y,m,S,p),s(w,l,P,S,m,g,p)}else{var E=d?(m*P+p*k)/d:p;s(h,w,k,y,m,g,E),s(w,l,P,y,E,g,p)}}}function K3(n,t,e,r,i){(n.depth&1?Ea:Br)(n,t,e,r,i)}var J3=function n(t){function e(r,i,a,o,u){if((f=r._squarify)&&f.ratio===t)for(var f,c,s,h,l=-1,d,y=f.length,m=r.value;++l1?r:1)},e}(Bh);function j3(n){for(var t=-1,e=n.length,r,i=n[e-1],a=0;++t1&&t6(n[e[r-2]],n[e[r-1]],n[i])<=0;)--r;e[r++]=i}return e.slice(0,r)}function r6(n){if((e=n.length)<3)return null;var t,e,r=new Array(e),i=new Array(e);for(t=0;t=0;--t)c.push(n[r[a[t]][2]]);for(t=+u;ta!=u>a&&i<(o-f)*(a-c)/(u-c)+f&&(s=!s),o=f,u=c;return s}function a6(n){for(var t=-1,e=n.length,r=n[e-1],i,a,o=r[0],u=r[1],f=0;++t1);return r+i*u*Math.sqrt(-2*Math.log(o)/o)}}return e.source=n,e}(Mn),f6=function n(t){var e=df.source(t);function r(){var i=e.apply(this,arguments);return function(){return Math.exp(i())}}return r.source=n,r}(Mn),Vh=function n(t){function e(r){return(r=+r)<=0?()=>0:function(){for(var i=0,a=r;a>1;--a)i+=t();return i+a*t()}}return e.source=n,e}(Mn),c6=function n(t){var e=Vh.source(t);function r(i){if((i=+i)==0)return t;var a=e(i);return function(){return a()/i}}return r.source=n,r}(Mn),s6=function n(t){function e(r){return function(){return-Math.log1p(-t())/r}}return e.source=n,e}(Mn),l6=function n(t){function e(r){if((r=+r)<0)throw new RangeError("invalid alpha");return r=1/-r,function(){return Math.pow(1-t(),r)}}return e.source=n,e}(Mn),h6=function n(t){function e(r){if((r=+r)<0||r>1)throw new RangeError("invalid p");return function(){return Math.floor(t()+r)}}return e.source=n,e}(Mn),Wh=function n(t){function e(r){if((r=+r)<0||r>1)throw new RangeError("invalid p");return r===0?()=>Infinity:r===1?()=>1:(r=Math.log1p(-r),function(){return 1+Math.floor(Math.log1p(-t())/r)})}return e.source=n,e}(Mn),gf=function n(t){var e=df.source(t)();function r(i,a){if((i=+i)<0)throw new RangeError("invalid k");if(i===0)return()=>0;if(a=a==null?1:+a,i===1)return()=>-Math.log1p(-t())*a;var o=(i<1?i+1:i)-1/3,u=1/(3*Math.sqrt(o)),f=i<1?()=>Math.pow(t(),1/i):()=>1;return function(){do{do var c=e(),s=1+u*c;while(s<=0);s*=s*s;var h=1-t()}while(h>=1-.0331*c*c*c*c&&Math.log(h)>=.5*c*c+o*(1-s+Math.log(s)));return o*s*f()*a}}return r.source=n,r}(Mn),Zh=function n(t){var e=gf.source(t);function r(i,a){var o=e(i),u=e(a);return function(){var f=o();return f===0?0:f/(f+u())}}return r.source=n,r}(Mn),Qh=function n(t){var e=Wh.source(t),r=Zh.source(t);function i(a,o){return a=+a,(o=+o)>=1?()=>a:o<=0?()=>0:function(){for(var u=0,f=a,c=o;f*c>16&&f*(1-c)>16;){var s=Math.floor((f+1)*c),h=r(s,f-s+1)();h<=c?(u+=s,f-=s,c=(c-h)/(1-h)):(f=s-1,c/=h)}for(var l=c<.5,d=l?c:1-c,y=e(d),m=y(),g=0;m<=f;++g)m+=y();return u+(l?g:f-g)}}return i.source=n,i}(Mn),d6=function n(t){function e(r,i,a){var o;return(r=+r)==0?o=u=>-Math.log(u):(r=1/r,o=u=>Math.pow(u,r)),i=i==null?0:+i,a=a==null?1:+a,function(){return i+a*o(-Math.log1p(-t()))}}return e.source=n,e}(Mn),g6=function n(t){function e(r,i){return r=r==null?0:+r,i=i==null?1:+i,function(){return r+i*Math.tan(Math.PI*t())}}return e.source=n,e}(Mn),p6=function n(t){function e(r,i){return r=r==null?0:+r,i=i==null?1:+i,function(){var a=t();return r+i*Math.log(a/(1-a))}}return e.source=n,e}(Mn),m6=function n(t){var e=gf.source(t),r=Qh.source(t);function i(a){return function(){for(var o=0,u=a;u>16;){var f=Math.floor(.875*u),c=e(f)();if(c>u)return o+r(f-1,u/c)();o+=f,u-=c}for(var s=-Math.log1p(-t()),h=0;s<=u;++h)s-=Math.log1p(-t());return o+h}}return i.source=n,i}(Mn);const y6=1664525,v6=1013904223,Kh=1/4294967296;function _6(n=Math.random()){let t=(0<=n&&n<1?n/Kh:Math.abs(n))|0;return()=>(t=y6*t+v6|0,Kh*(t>>>0))}function Kn(n,t){switch(arguments.length){case 0:break;case 1:this.range(n);break;default:this.range(t).domain(n);break}return this}function Et(n,t){switch(arguments.length){case 0:break;case 1:{typeof n=="function"?this.interpolator(n):this.range(n);break}default:{this.domain(n),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}const pf=Symbol("implicit");function mf(){var n=new nr,t=[],e=[],r=pf;function i(a){let o=n.get(a);if(o===void 0){if(r!==pf)return r;n.set(a,o=t.push(a)-1)}return e[o%e.length]}return i.domain=function(a){if(!arguments.length)return t.slice();t=[],n=new nr;for(const o of a)n.has(o)||n.set(o,t.push(o)-1);return i},i.range=function(a){return arguments.length?(e=Array.from(a),i):e.slice()},i.unknown=function(a){return arguments.length?(r=a,i):r},i.copy=function(){return mf(t,e).unknown(r)},Kn.apply(i,arguments),i}function yf(){var n=mf().unknown(void 0),t=n.domain,e=n.range,r=0,i=1,a,o,u=!1,f=0,c=0,s=.5;delete n.unknown;function h(){var l=t().length,d=it&&(e=n,n=t,t=e),function(r){return Math.max(n,Math.min(t,r))}}function M6(n,t,e){var r=n[0],i=n[1],a=t[0],o=t[1];return i2?S6:M6,f=c=null,h}function h(l){return l==null||isNaN(l=+l)?a:(f||(f=u(n.map(r),t,e)))(r(o(l)))}return h.invert=function(l){return o(i((c||(c=u(t,n.map(r),Wn)))(l)))},h.domain=function(l){return arguments.length?(n=Array.from(l,Na),s()):n.slice()},h.range=function(l){return arguments.length?(t=Array.from(l),s()):t.slice()},h.rangeRound=function(l){return t=Array.from(l),e=Mi,s()},h.clamp=function(l){return arguments.length?(o=l?!0:Un,s()):o!==Un},h.interpolate=function(l){return arguments.length?(e=l,s()):e},h.unknown=function(l){return arguments.length?(a=l,h):a},function(l,d){return r=l,i=d,s()}}function _f(){return ka()(Un,Un)}function n0(n,t,e,r){var i=ve(n,t,e),a;switch(r=pd(r==null?",f":r),r.type){case"s":{var o=Math.max(Math.abs(n),Math.abs(t));return r.precision==null&&!isNaN(a=yl(i,o))&&(r.precision=a),md(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(a=vl(i,Math.max(Math.abs(n),Math.abs(t))))&&(r.precision=a-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(a=ml(i))&&(r.precision=a-(r.type==="%")*2);break}}return Qf(r)}function Yt(n){var t=n.domain;return n.ticks=function(e){var r=t();return ye(r[0],r[r.length-1],e==null?10:e)},n.tickFormat=function(e,r){var i=t();return n0(i[0],i[i.length-1],e==null?10:e,r)},n.nice=function(e){e==null&&(e=10);var r=t(),i=0,a=r.length-1,o=r[i],u=r[a],f,c,s=10;for(u0;){if(c=tr(o,u,e),c===f)return r[i]=o,r[a]=u,t(r);if(c>0)o=Math.floor(o/c)*c,u=Math.ceil(u/c)*c;else if(c<0)o=Math.ceil(o*c)/c,u=Math.floor(u*c)/c;else break;f=c}return n},n}function t0(){var n=_f();return n.copy=function(){return Hr(n,t0())},Kn.apply(n,arguments),Yt(n)}function e0(n){var t;function e(r){return r==null||isNaN(r=+r)?t:r}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(n=Array.from(r,Na),e):n.slice()},e.unknown=function(r){return arguments.length?(t=r,e):t},e.copy=function(){return e0(n).unknown(t)},n=arguments.length?Array.from(n,Na):[0,1],Yt(e)}function r0(n,t){n=n.slice();var e=0,r=n.length-1,i=n[e],a=n[r],o;return a0){for(;l<=d;++l)for(m=1,y=a(l);ms)break;b.push(g)}}else for(;l<=d;++l)for(m=r-1,y=a(l);m>=1;--m)if(g=y*m,!(gs)break;b.push(g)}b.length*20?e[u-1]:n[0],u=e?[r[e-1],t]:[r[c-1],r[c]]},o.unknown=function(f){return arguments.length&&(a=f),o},o.thresholds=function(){return r.slice()},o.copy=function(){return p0().domain([n,t]).range(i).unknown(a)},Kn.apply(Yt(o),arguments)}function m0(){var n=[.5],t=[0,1],e,r=1;function i(a){return a!=null&&a<=a?t[Rt(n,a,0,r)]:e}return i.domain=function(a){return arguments.length?(n=Array.from(a),r=Math.min(n.length,t.length-1),i):n.slice()},i.range=function(a){return arguments.length?(t=Array.from(a),r=Math.min(n.length,t.length-1),i):t.slice()},i.invertExtent=function(a){var o=t.indexOf(a);return[n[o-1],n[o]]},i.unknown=function(a){return arguments.length?(e=a,i):e},i.copy=function(){return m0().domain(n).range(t).unknown(e)},Kn.apply(i,arguments)}var Sf=new Date,Tf=new Date;function yn(n,t,e,r){function i(a){return n(a=arguments.length===0?new Date:new Date(+a)),a}return i.floor=function(a){return n(a=new Date(+a)),a},i.ceil=function(a){return n(a=new Date(a-1)),t(a,1),n(a),a},i.round=function(a){var o=i(a),u=i.ceil(a);return a-o0))return f;do f.push(c=new Date(+a)),t(a,u),n(a);while(c=o)for(;n(o),!a(o);)o.setTime(o-1)},function(o,u){if(o>=o)if(u<0)for(;++u<=0;)for(;t(o,-1),!a(o););else for(;--u>=0;)for(;t(o,1),!a(o););})},e&&(i.count=function(a,o){return Sf.setTime(+a),Tf.setTime(+o),n(Sf),n(Tf),Math.floor(e(Sf,Tf))},i.every=function(a){return a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(r?function(o){return r(o)%a==0}:function(o){return i.count(0,o)%a==0}):i}),i}var Ue=yn(function(){},function(n,t){n.setTime(+n+t)},function(n,t){return t-n});Ue.every=function(n){return n=Math.floor(n),!isFinite(n)||!(n>0)?null:n>1?yn(function(t){t.setTime(Math.floor(t/n)*n)},function(t,e){t.setTime(+t+e*n)},function(t,e){return(e-t)/n}):Ue};var y0=Ue.range;const Nt=1e3,Jn=Nt*60,kt=Jn*60,ce=kt*24,Af=ce*7,v0=ce*30,Ef=ce*365;var $t=yn(function(n){n.setTime(n-n.getMilliseconds())},function(n,t){n.setTime(+n+t*Nt)},function(n,t){return(t-n)/Nt},function(n){return n.getUTCSeconds()}),_0=$t.range,$a=yn(function(n){n.setTime(n-n.getMilliseconds()-n.getSeconds()*Nt)},function(n,t){n.setTime(+n+t*Jn)},function(n,t){return(t-n)/Jn},function(n){return n.getMinutes()}),I6=$a.range,Ca=yn(function(n){n.setTime(n-n.getMilliseconds()-n.getSeconds()*Nt-n.getMinutes()*Jn)},function(n,t){n.setTime(+n+t*kt)},function(n,t){return(t-n)/kt},function(n){return n.getHours()}),z6=Ca.range,Be=yn(n=>n.setHours(0,0,0,0),(n,t)=>n.setDate(n.getDate()+t),(n,t)=>(t-n-(t.getTimezoneOffset()-n.getTimezoneOffset())*Jn)/ce,n=>n.getDate()-1),D6=Be.range;function se(n){return yn(function(t){t.setDate(t.getDate()-(t.getDay()+7-n)%7),t.setHours(0,0,0,0)},function(t,e){t.setDate(t.getDate()+e*7)},function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Jn)/Af})}var He=se(0),Xr=se(1),b0=se(2),w0=se(3),le=se(4),x0=se(5),M0=se(6),S0=He.range,O6=Xr.range,q6=b0.range,L6=w0.range,F6=le.range,Y6=x0.range,U6=M0.range,Ra=yn(function(n){n.setDate(1),n.setHours(0,0,0,0)},function(n,t){n.setMonth(n.getMonth()+t)},function(n,t){return t.getMonth()-n.getMonth()+(t.getFullYear()-n.getFullYear())*12},function(n){return n.getMonth()}),B6=Ra.range,pt=yn(function(n){n.setMonth(0,1),n.setHours(0,0,0,0)},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n,t){return t.getFullYear()-n.getFullYear()},function(n){return n.getFullYear()});pt.every=function(n){return!isFinite(n=Math.floor(n))||!(n>0)?null:yn(function(t){t.setFullYear(Math.floor(t.getFullYear()/n)*n),t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,e){t.setFullYear(t.getFullYear()+e*n)})};var H6=pt.range,Pa=yn(function(n){n.setUTCSeconds(0,0)},function(n,t){n.setTime(+n+t*Jn)},function(n,t){return(t-n)/Jn},function(n){return n.getUTCMinutes()}),X6=Pa.range,Ia=yn(function(n){n.setUTCMinutes(0,0,0)},function(n,t){n.setTime(+n+t*kt)},function(n,t){return(t-n)/kt},function(n){return n.getUTCHours()}),G6=Ia.range,Xe=yn(function(n){n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCDate(n.getUTCDate()+t)},function(n,t){return(t-n)/ce},function(n){return n.getUTCDate()-1}),V6=Xe.range;function he(n){return yn(function(t){t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-n)%7),t.setUTCHours(0,0,0,0)},function(t,e){t.setUTCDate(t.getUTCDate()+e*7)},function(t,e){return(e-t)/Af})}var Ge=he(0),Gr=he(1),T0=he(2),A0=he(3),de=he(4),E0=he(5),N0=he(6),k0=Ge.range,W6=Gr.range,Z6=T0.range,Q6=A0.range,K6=de.range,J6=E0.range,j6=N0.range,za=yn(function(n){n.setUTCDate(1),n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCMonth(n.getUTCMonth()+t)},function(n,t){return t.getUTCMonth()-n.getUTCMonth()+(t.getUTCFullYear()-n.getUTCFullYear())*12},function(n){return n.getUTCMonth()}),n5=za.range,mt=yn(function(n){n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCFullYear(n.getUTCFullYear()+t)},function(n,t){return t.getUTCFullYear()-n.getUTCFullYear()},function(n){return n.getUTCFullYear()});mt.every=function(n){return!isFinite(n=Math.floor(n))||!(n>0)?null:yn(function(t){t.setUTCFullYear(Math.floor(t.getUTCFullYear()/n)*n),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e*n)})};var t5=mt.range;function $0(n,t,e,r,i,a){const o=[[$t,1,Nt],[$t,5,5*Nt],[$t,15,15*Nt],[$t,30,30*Nt],[a,1,Jn],[a,5,5*Jn],[a,15,15*Jn],[a,30,30*Jn],[i,1,kt],[i,3,3*kt],[i,6,6*kt],[i,12,12*kt],[r,1,ce],[r,2,2*ce],[e,1,Af],[t,1,v0],[t,3,3*v0],[n,1,Ef]];function u(c,s,h){const l=sg).right(o,l);if(d===o.length)return n.every(ve(c/Ef,s/Ef,h));if(d===0)return Ue.every(Math.max(ve(c,s,h),1));const[y,m]=o[l/o[d-1][2]53)return null;"w"in z||(z.w=1),"Z"in z?(rn=kf(Vr(z.y,0,1)),$n=rn.getUTCDay(),rn=$n>4||$n===0?Gr.ceil(rn):Gr(rn),rn=Xe.offset(rn,(z.V-1)*7),z.y=rn.getUTCFullYear(),z.m=rn.getUTCMonth(),z.d=rn.getUTCDate()+(z.w+6)%7):(rn=Nf(Vr(z.y,0,1)),$n=rn.getDay(),rn=$n>4||$n===0?Xr.ceil(rn):Xr(rn),rn=Be.offset(rn,(z.V-1)*7),z.y=rn.getFullYear(),z.m=rn.getMonth(),z.d=rn.getDate()+(z.w+6)%7)}else("W"in z||"U"in z)&&("w"in z||(z.w="u"in z?z.u%7:"W"in z?1:0),$n="Z"in z?kf(Vr(z.y,0,1)).getUTCDay():Nf(Vr(z.y,0,1)).getDay(),z.m=0,z.d="W"in z?(z.w+6)%7+z.W*7-($n+5)%7:z.w+z.U*7-($n+6)%7);return"Z"in z?(z.H+=z.Z/100|0,z.M+=z.Z%100,kf(z)):Nf(z)}}function k(q,G,K,z){for(var cn=0,rn=G.length,$n=K.length,Cn,X;cn=$n)return-1;if(Cn=G.charCodeAt(cn++),Cn===37){if(Cn=G.charAt(cn++),X=w[Cn in D0?G.charAt(cn++):Cn],!X||(z=X(q,K,z))<0)return-1}else if(Cn!=K.charCodeAt(z++))return-1}return z}function P(q,G,K){var z=c.exec(G.slice(K));return z?(q.p=s.get(z[0].toLowerCase()),K+z[0].length):-1}function S(q,G,K){var z=d.exec(G.slice(K));return z?(q.w=y.get(z[0].toLowerCase()),K+z[0].length):-1}function E(q,G,K){var z=h.exec(G.slice(K));return z?(q.w=l.get(z[0].toLowerCase()),K+z[0].length):-1}function R(q,G,K){var z=p.exec(G.slice(K));return z?(q.m=b.get(z[0].toLowerCase()),K+z[0].length):-1}function $(q,G,K){var z=m.exec(G.slice(K));return z?(q.m=g.get(z[0].toLowerCase()),K+z[0].length):-1}function M(q,G,K){return k(q,t,G,K)}function T(q,G,K){return k(q,e,G,K)}function A(q,G,K){return k(q,r,G,K)}function C(q){return o[q.getDay()]}function I(q){return a[q.getDay()]}function D(q){return f[q.getMonth()]}function O(q){return u[q.getMonth()]}function L(q){return i[+(q.getHours()>=12)]}function U(q){return 1+~~(q.getMonth()/3)}function tn(q){return o[q.getUTCDay()]}function Z(q){return a[q.getUTCDay()]}function en(q){return f[q.getUTCMonth()]}function gn(q){return u[q.getUTCMonth()]}function j(q){return i[+(q.getUTCHours()>=12)]}function dn(q){return 1+~~(q.getUTCMonth()/3)}return{format:function(q){var G=x(q+="",_);return G.toString=function(){return q},G},parse:function(q){var G=N(q+="",!1);return G.toString=function(){return q},G},utcFormat:function(q){var G=x(q+="",v);return G.toString=function(){return q},G},utcParse:function(q){var G=N(q+="",!0);return G.toString=function(){return q},G}}}var D0={"-":"",_:" ","0":"0"},bn=/^\s*\d+/,e5=/^%/,r5=/[\\^$*+?|[\]().{}]/g;function nn(n,t,e){var r=n<0?"-":"",i=(r?-n:n)+"",a=i.length;return r+(a[t.toLowerCase(),e]))}function a5(n,t,e){var r=bn.exec(t.slice(e,e+1));return r?(n.w=+r[0],e+r[0].length):-1}function o5(n,t,e){var r=bn.exec(t.slice(e,e+1));return r?(n.u=+r[0],e+r[0].length):-1}function u5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.U=+r[0],e+r[0].length):-1}function f5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.V=+r[0],e+r[0].length):-1}function c5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.W=+r[0],e+r[0].length):-1}function O0(n,t,e){var r=bn.exec(t.slice(e,e+4));return r?(n.y=+r[0],e+r[0].length):-1}function q0(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.y=+r[0]+(+r[0]>68?1900:2e3),e+r[0].length):-1}function s5(n,t,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(e,e+6));return r?(n.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function l5(n,t,e){var r=bn.exec(t.slice(e,e+1));return r?(n.q=r[0]*3-3,e+r[0].length):-1}function h5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function L0(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function d5(n,t,e){var r=bn.exec(t.slice(e,e+3));return r?(n.m=0,n.d=+r[0],e+r[0].length):-1}function F0(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function g5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function p5(n,t,e){var r=bn.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function m5(n,t,e){var r=bn.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function y5(n,t,e){var r=bn.exec(t.slice(e,e+6));return r?(n.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function v5(n,t,e){var r=e5.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function _5(n,t,e){var r=bn.exec(t.slice(e));return r?(n.Q=+r[0],e+r[0].length):-1}function b5(n,t,e){var r=bn.exec(t.slice(e));return r?(n.s=+r[0],e+r[0].length):-1}function Y0(n,t){return nn(n.getDate(),t,2)}function w5(n,t){return nn(n.getHours(),t,2)}function x5(n,t){return nn(n.getHours()%12||12,t,2)}function M5(n,t){return nn(1+Be.count(pt(n),n),t,3)}function U0(n,t){return nn(n.getMilliseconds(),t,3)}function S5(n,t){return U0(n,t)+"000"}function T5(n,t){return nn(n.getMonth()+1,t,2)}function A5(n,t){return nn(n.getMinutes(),t,2)}function E5(n,t){return nn(n.getSeconds(),t,2)}function N5(n){var t=n.getDay();return t===0?7:t}function k5(n,t){return nn(He.count(pt(n)-1,n),t,2)}function B0(n){var t=n.getDay();return t>=4||t===0?le(n):le.ceil(n)}function $5(n,t){return n=B0(n),nn(le.count(pt(n),n)+(pt(n).getDay()===4),t,2)}function C5(n){return n.getDay()}function R5(n,t){return nn(Xr.count(pt(n)-1,n),t,2)}function P5(n,t){return nn(n.getFullYear()%100,t,2)}function I5(n,t){return n=B0(n),nn(n.getFullYear()%100,t,2)}function z5(n,t){return nn(n.getFullYear()%1e4,t,4)}function D5(n,t){var e=n.getDay();return n=e>=4||e===0?le(n):le.ceil(n),nn(n.getFullYear()%1e4,t,4)}function O5(n){var t=n.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+nn(t/60|0,"0",2)+nn(t%60,"0",2)}function H0(n,t){return nn(n.getUTCDate(),t,2)}function q5(n,t){return nn(n.getUTCHours(),t,2)}function L5(n,t){return nn(n.getUTCHours()%12||12,t,2)}function F5(n,t){return nn(1+Xe.count(mt(n),n),t,3)}function X0(n,t){return nn(n.getUTCMilliseconds(),t,3)}function Y5(n,t){return X0(n,t)+"000"}function U5(n,t){return nn(n.getUTCMonth()+1,t,2)}function B5(n,t){return nn(n.getUTCMinutes(),t,2)}function H5(n,t){return nn(n.getUTCSeconds(),t,2)}function X5(n){var t=n.getUTCDay();return t===0?7:t}function G5(n,t){return nn(Ge.count(mt(n)-1,n),t,2)}function G0(n){var t=n.getUTCDay();return t>=4||t===0?de(n):de.ceil(n)}function V5(n,t){return n=G0(n),nn(de.count(mt(n),n)+(mt(n).getUTCDay()===4),t,2)}function W5(n){return n.getUTCDay()}function Z5(n,t){return nn(Gr.count(mt(n)-1,n),t,2)}function Q5(n,t){return nn(n.getUTCFullYear()%100,t,2)}function K5(n,t){return n=G0(n),nn(n.getUTCFullYear()%100,t,2)}function J5(n,t){return nn(n.getUTCFullYear()%1e4,t,4)}function j5(n,t){var e=n.getUTCDay();return n=e>=4||e===0?de(n):de.ceil(n),nn(n.getUTCFullYear()%1e4,t,4)}function nw(){return"+0000"}function V0(){return"%"}function W0(n){return+n}function Z0(n){return Math.floor(+n/1e3)}var Ve,$f,Q0,Da,Cf;K0({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function K0(n){return Ve=z0(n),$f=Ve.format,Q0=Ve.parse,Da=Ve.utcFormat,Cf=Ve.utcParse,Ve}var J0="%Y-%m-%dT%H:%M:%S.%LZ";function tw(n){return n.toISOString()}var ew=Date.prototype.toISOString?tw:Da(J0);function rw(n){var t=new Date(n);return isNaN(t)?null:t}var iw=+new Date("2000-01-01T00:00:00.000Z")?rw:Cf(J0);function aw(n){return new Date(n)}function ow(n){return n instanceof Date?+n:+new Date(+n)}function Rf(n,t,e,r,i,a,o,u,f,c){var s=_f(),h=s.invert,l=s.domain,d=c(".%L"),y=c(":%S"),m=c("%I:%M"),g=c("%I %p"),p=c("%a %d"),b=c("%b %d"),_=c("%B"),v=c("%Y");function w(x){return(f(x)t(i/(n.length-1)))},e.quantiles=function(r){return Array.from({length:r+1},(i,a)=>rr(n,a/r))},e.copy=function(){return e1(t).domain(n)},Et.apply(e,arguments)}function qa(){var n=0,t=.5,e=1,r=1,i,a,o,u,f,c=Un,s,h=!1,l;function d(m){return isNaN(m=+m)?l:(m=.5+((m=+s(m))-a)*(r*mos(n[n.length-1]),o1=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(W),ww=on(o1),u1=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(W),xw=on(u1),f1=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(W),Mw=on(f1),c1=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(W),Sw=on(c1),s1=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(W),Tw=on(s1),l1=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(W),Aw=on(l1),h1=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(W),Ew=on(h1),d1=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(W),Nw=on(d1),g1=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(W),kw=on(g1),p1=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(W),$w=on(p1),m1=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(W),Cw=on(m1),y1=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(W),Rw=on(y1),v1=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(W),Pw=on(v1),_1=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(W),Iw=on(_1),b1=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(W),zw=on(b1),w1=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(W),Dw=on(w1),x1=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(W),Ow=on(x1),M1=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(W),qw=on(M1),S1=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(W),Lw=on(S1),T1=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(W),Fw=on(T1),A1=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(W),Yw=on(A1),E1=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(W),Uw=on(E1),N1=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(W),Bw=on(N1),k1=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(W),Hw=on(k1),$1=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(W),Xw=on($1),C1=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(W),Gw=on(C1),R1=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(W),Vw=on(R1);function Ww(n){return n=Math.max(0,Math.min(1,n)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-n*(35.34-n*(2381.73-n*(6402.7-n*(7024.72-n*2710.57)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+n*(170.73+n*(52.82-n*(131.46-n*(176.58-n*67.37)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+n*(442.36-n*(2482.43-n*(6167.24-n*(6614.94-n*2475.67)))))))+")"}var Zw=Ti(et(300,.5,0),et(-240,.5,1)),Qw=Ti(et(-100,.75,.35),et(80,1.5,.8)),Kw=Ti(et(260,.75,.35),et(80,1.5,.8)),La=et();function Jw(n){(n<0||n>1)&&(n-=Math.floor(n));var t=Math.abs(n-.5);return La.h=360*n-100,La.s=1.5-1.5*t,La.l=.8-.9*t,La+""}var Fa=Me(),jw=Math.PI/3,n8=Math.PI*2/3;function t8(n){var t;return n=(.5-n)*Math.PI,Fa.r=255*(t=Math.sin(n))*t,Fa.g=255*(t=Math.sin(n+jw))*t,Fa.b=255*(t=Math.sin(n+n8))*t,Fa+""}function e8(n){return n=Math.max(0,Math.min(1,n)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+n*(1172.33-n*(10793.56-n*(33300.12-n*(38394.49-n*14825.05)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+n*(557.33+n*(1225.33-n*(3574.96-n*(1073.77+n*707.56)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+n*(3211.1-n*(15327.97-n*(27814-n*(22569.18-n*6838.66)))))))+")"}function Ya(n){var t=n.length;return function(e){return n[Math.max(0,Math.min(t-1,Math.floor(e*t)))]}}var r8=Ya(W("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),i8=Ya(W("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),a8=Ya(W("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),o8=Ya(W("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function V(n){return function(){return n}}var P1=Math.abs,Nn=Math.atan2,ge=Math.cos,u8=Math.max,zf=Math.min,yt=Math.sin,We=Math.sqrt,kn=1e-12,Bt=Math.PI,Ua=Bt/2,Ht=2*Bt;function f8(n){return n>1?0:n<-1?Bt:Math.acos(n)}function I1(n){return n>=1?Ua:n<=-1?-Ua:Math.asin(n)}function c8(n){return n.innerRadius}function s8(n){return n.outerRadius}function l8(n){return n.startAngle}function h8(n){return n.endAngle}function d8(n){return n&&n.padAngle}function g8(n,t,e,r,i,a,o,u){var f=e-n,c=r-t,s=o-i,h=u-a,l=h*f-s*c;if(!(l*lM*M+T*T&&(k=S,P=E),{cx:k,cy:P,x01:-s,y01:-h,x11:k*(i/w-1),y11:P*(i/w-1)}}function p8(){var n=c8,t=s8,e=V(0),r=null,i=l8,a=h8,o=d8,u=null;function f(){var c,s,h=+n.apply(this,arguments),l=+t.apply(this,arguments),d=i.apply(this,arguments)-Ua,y=a.apply(this,arguments)-Ua,m=P1(y-d),g=y>d;if(u||(u=c=Ot()),lkn))u.moveTo(0,0);else if(m>Ht-kn)u.moveTo(l*ge(d),l*yt(d)),u.arc(0,0,l,d,y,!g),h>kn&&(u.moveTo(h*ge(y),h*yt(y)),u.arc(0,0,h,y,d,g));else{var p=d,b=y,_=d,v=y,w=m,x=m,N=o.apply(this,arguments)/2,k=N>kn&&(r?+r.apply(this,arguments):We(h*h+l*l)),P=zf(P1(l-h)/2,+e.apply(this,arguments)),S=P,E=P,R,$;if(k>kn){var M=I1(k/h*yt(N)),T=I1(k/l*yt(N));(w-=M*2)>kn?(M*=g?1:-1,_+=M,v-=M):(w=0,_=v=(d+y)/2),(x-=T*2)>kn?(T*=g?1:-1,p+=T,b-=T):(x=0,p=b=(d+y)/2)}var A=l*ge(p),C=l*yt(p),I=h*ge(v),D=h*yt(v);if(P>kn){var O=l*ge(b),L=l*yt(b),U=h*ge(_),tn=h*yt(_),Z;if(mkn?E>kn?(R=Ba(U,tn,A,C,l,E,g),$=Ba(O,L,I,D,l,E,g),u.moveTo(R.cx+R.x01,R.cy+R.y01),Ekn)||!(w>kn)?u.lineTo(I,D):S>kn?(R=Ba(I,D,O,L,h,-S,g),$=Ba(A,C,U,tn,h,-S,g),u.lineTo(R.cx+R.x01,R.cy+R.y01),S=l;--d)u.point(b[d],_[d]);u.lineEnd(),u.areaEnd()}g&&(b[h]=+n(m,h,s),_[h]=+t(m,h,s),u.point(r?+r(m,h,s):b[h],e?+e(m,h,s):_[h]))}if(p)return u=null,p+""||null}function c(){return qf().defined(i).curve(o).context(a)}return f.x=function(s){return arguments.length?(n=typeof s=="function"?s:V(+s),r=null,f):n},f.x0=function(s){return arguments.length?(n=typeof s=="function"?s:V(+s),f):n},f.x1=function(s){return arguments.length?(r=s==null?null:typeof s=="function"?s:V(+s),f):r},f.y=function(s){return arguments.length?(t=typeof s=="function"?s:V(+s),e=null,f):t},f.y0=function(s){return arguments.length?(t=typeof s=="function"?s:V(+s),f):t},f.y1=function(s){return arguments.length?(e=s==null?null:typeof s=="function"?s:V(+s),f):e},f.lineX0=f.lineY0=function(){return c().x(n).y(t)},f.lineY1=function(){return c().x(n).y(e)},f.lineX1=function(){return c().x(r).y(t)},f.defined=function(s){return arguments.length?(i=typeof s=="function"?s:V(!!s),f):i},f.curve=function(s){return arguments.length?(o=s,a!=null&&(u=o(a)),f):o},f.context=function(s){return arguments.length?(s==null?a=u=null:u=o(a=s),f):a},f}function y8(n,t){return tn?1:t>=n?0:NaN}function v8(n){return n}function _8(){var n=v8,t=y8,e=null,r=V(0),i=V(Ht),a=V(0);function o(u){var f,c=(u=Ha(u)).length,s,h,l=0,d=new Array(c),y=new Array(c),m=+r.apply(this,arguments),g=Math.min(Ht,Math.max(-Ht,i.apply(this,arguments)-m)),p,b=Math.min(Math.abs(g)/c,a.apply(this,arguments)),_=b*(g<0?-1:1),v;for(f=0;f0&&(l+=v);for(t!=null?d.sort(function(w,x){return t(y[w],y[x])}):e!=null&&d.sort(function(w,x){return e(u[w],u[x])}),f=0,h=l?(g-c*_)/l:0;f0?v*h:0)+_,y[s]={data:u[s],index:f,value:v,startAngle:m,endAngle:p,padAngle:b};return y}return o.value=function(u){return arguments.length?(n=typeof u=="function"?u:V(+u),o):n},o.sortValues=function(u){return arguments.length?(t=u,e=null,o):t},o.sort=function(u){return arguments.length?(e=u,t=null,o):e},o.startAngle=function(u){return arguments.length?(r=typeof u=="function"?u:V(+u),o):r},o.endAngle=function(u){return arguments.length?(i=typeof u=="function"?u:V(+u),o):i},o.padAngle=function(u){return arguments.length?(a=typeof u=="function"?u:V(+u),o):a},o}var O1=Lf(Xa);function q1(n){this._curve=n}q1.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(n,t){this._curve.point(t*Math.sin(n),t*-Math.cos(n))}};function Lf(n){function t(e){return new q1(n(e))}return t._curve=n,t}function Qr(n){var t=n.curve;return n.angle=n.x,delete n.x,n.radius=n.y,delete n.y,n.curve=function(e){return arguments.length?t(Lf(e)):t()._curve},n}function L1(){return Qr(qf().curve(O1))}function F1(){var n=D1().curve(O1),t=n.curve,e=n.lineX0,r=n.lineX1,i=n.lineY0,a=n.lineY1;return n.angle=n.x,delete n.x,n.startAngle=n.x0,delete n.x0,n.endAngle=n.x1,delete n.x1,n.radius=n.y,delete n.y,n.innerRadius=n.y0,delete n.y0,n.outerRadius=n.y1,delete n.y1,n.lineStartAngle=function(){return Qr(e())},delete n.lineX0,n.lineEndAngle=function(){return Qr(r())},delete n.lineX1,n.lineInnerRadius=function(){return Qr(i())},delete n.lineY0,n.lineOuterRadius=function(){return Qr(a())},delete n.lineY1,n.curve=function(o){return arguments.length?t(Lf(o)):t()._curve},n}function Kr(n,t){return[(t=+t)*Math.cos(n-=Math.PI/2),t*Math.sin(n)]}function b8(n){return n.source}function w8(n){return n.target}function Ff(n){var t=b8,e=w8,r=Df,i=Of,a=null;function o(){var u,f=m8.call(arguments),c=t.apply(this,f),s=e.apply(this,f);if(a||(a=u=Ot()),n(a,+r.apply(this,(f[0]=c,f)),+i.apply(this,f),+r.apply(this,(f[0]=s,f)),+i.apply(this,f)),u)return a=null,u+""||null}return o.source=function(u){return arguments.length?(t=u,o):t},o.target=function(u){return arguments.length?(e=u,o):e},o.x=function(u){return arguments.length?(r=typeof u=="function"?u:V(+u),o):r},o.y=function(u){return arguments.length?(i=typeof u=="function"?u:V(+u),o):i},o.context=function(u){return arguments.length?(a=u==null?null:u,o):a},o}function x8(n,t,e,r,i){n.moveTo(t,e),n.bezierCurveTo(t=(t+r)/2,e,t,i,r,i)}function M8(n,t,e,r,i){n.moveTo(t,e),n.bezierCurveTo(t,e=(e+i)/2,r,e,r,i)}function S8(n,t,e,r,i){var a=Kr(t,e),o=Kr(t,e=(e+i)/2),u=Kr(r,e),f=Kr(r,i);n.moveTo(a[0],a[1]),n.bezierCurveTo(o[0],o[1],u[0],u[1],f[0],f[1])}function T8(){return Ff(x8)}function A8(){return Ff(M8)}function E8(){var n=Ff(S8);return n.angle=n.x,delete n.x,n.radius=n.y,delete n.y,n}var Yf={draw:function(n,t){var e=Math.sqrt(t/Bt);n.moveTo(e,0),n.arc(0,0,e,0,Ht)}},Y1={draw:function(n,t){var e=Math.sqrt(t/5)/2;n.moveTo(-3*e,-e),n.lineTo(-e,-e),n.lineTo(-e,-3*e),n.lineTo(e,-3*e),n.lineTo(e,-e),n.lineTo(3*e,-e),n.lineTo(3*e,e),n.lineTo(e,e),n.lineTo(e,3*e),n.lineTo(-e,3*e),n.lineTo(-e,e),n.lineTo(-3*e,e),n.closePath()}},U1=Math.sqrt(1/3),N8=U1*2,B1={draw:function(n,t){var e=Math.sqrt(t/N8),r=e*U1;n.moveTo(0,-e),n.lineTo(r,0),n.lineTo(0,e),n.lineTo(-r,0),n.closePath()}},k8=.8908130915292852,H1=Math.sin(Bt/10)/Math.sin(7*Bt/10),$8=Math.sin(Ht/10)*H1,C8=-Math.cos(Ht/10)*H1,X1={draw:function(n,t){var e=Math.sqrt(t*k8),r=$8*e,i=C8*e;n.moveTo(0,-e),n.lineTo(r,i);for(var a=1;a<5;++a){var o=Ht*a/5,u=Math.cos(o),f=Math.sin(o);n.lineTo(f*e,-u*e),n.lineTo(u*r-f*i,f*r+u*i)}n.closePath()}},G1={draw:function(n,t){var e=Math.sqrt(t),r=-e/2;n.rect(r,r,e,e)}},Uf=Math.sqrt(3),V1={draw:function(n,t){var e=-Math.sqrt(t/(Uf*3));n.moveTo(0,e*2),n.lineTo(-Uf*e,-e),n.lineTo(Uf*e,-e),n.closePath()}},jn=-.5,nt=Math.sqrt(3)/2,Bf=1/Math.sqrt(12),R8=(Bf/2+1)*3,W1={draw:function(n,t){var e=Math.sqrt(t/R8),r=e/2,i=e*Bf,a=r,o=e*Bf+e,u=-a,f=o;n.moveTo(r,i),n.lineTo(a,o),n.lineTo(u,f),n.lineTo(jn*r-nt*i,nt*r+jn*i),n.lineTo(jn*a-nt*o,nt*a+jn*o),n.lineTo(jn*u-nt*f,nt*u+jn*f),n.lineTo(jn*r+nt*i,jn*i-nt*r),n.lineTo(jn*a+nt*o,jn*o-nt*a),n.lineTo(jn*u+nt*f,jn*f-nt*u),n.closePath()}},P8=[Yf,Y1,B1,G1,X1,V1,W1];function I8(n,t){var e=null;n=typeof n=="function"?n:V(n||Yf),t=typeof t=="function"?t:V(t===void 0?64:+t);function r(){var i;if(e||(e=i=Ot()),n.apply(this,arguments).draw(e,+t.apply(this,arguments)),i)return e=null,i+""||null}return r.type=function(i){return arguments.length?(n=typeof i=="function"?i:V(i),r):n},r.size=function(i){return arguments.length?(t=typeof i=="function"?i:V(+i),r):t},r.context=function(i){return arguments.length?(e=i==null?null:i,r):e},r}function Xt(){}function Ga(n,t,e){n._context.bezierCurveTo((2*n._x0+n._x1)/3,(2*n._y0+n._y1)/3,(n._x0+2*n._x1)/3,(n._y0+2*n._y1)/3,(n._x0+4*n._x1+t)/6,(n._y0+4*n._y1+e)/6)}function Va(n){this._context=n}Va.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Ga(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(n,t):this._context.moveTo(n,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Ga(this,n,t);break}this._x0=this._x1,this._x1=n,this._y0=this._y1,this._y1=t}};function z8(n){return new Va(n)}function Z1(n){this._context=n}Z1.prototype={areaStart:Xt,areaEnd:Xt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1,this._x2=n,this._y2=t;break;case 1:this._point=2,this._x3=n,this._y3=t;break;case 2:this._point=3,this._x4=n,this._y4=t,this._context.moveTo((this._x0+4*this._x1+n)/6,(this._y0+4*this._y1+t)/6);break;default:Ga(this,n,t);break}this._x0=this._x1,this._x1=n,this._y0=this._y1,this._y1=t}};function D8(n){return new Z1(n)}function Q1(n){this._context=n}Q1.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+n)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:Ga(this,n,t);break}this._x0=this._x1,this._x1=n,this._y0=this._y1,this._y1=t}};function O8(n){return new Q1(n)}class K1{constructor(t,e){this._context=t,this._x=e}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,e){switch(t=+t,e=+e,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e);break}}this._x0=t,this._y0=e}}function q8(n){return new K1(n,!0)}function L8(n){return new K1(n,!1)}function J1(n,t){this._basis=new Va(n),this._beta=t}J1.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var n=this._x,t=this._y,e=n.length-1;if(e>0)for(var r=n[0],i=t[0],a=n[e]-r,o=t[e]-i,u=-1,f;++u<=e;)f=u/e,this._basis.point(this._beta*n[u]+(1-this._beta)*(r+f*a),this._beta*t[u]+(1-this._beta)*(i+f*o));this._x=this._y=null,this._basis.lineEnd()},point:function(n,t){this._x.push(+n),this._y.push(+t)}};var F8=function n(t){function e(r){return t===1?new Va(r):new J1(r,t)}return e.beta=function(r){return n(+r)},e}(.85);function Wa(n,t,e){n._context.bezierCurveTo(n._x1+n._k*(n._x2-n._x0),n._y1+n._k*(n._y2-n._y0),n._x2+n._k*(n._x1-t),n._y2+n._k*(n._y1-e),n._x2,n._y2)}function Hf(n,t){this._context=n,this._k=(1-t)/6}Hf.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Wa(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(n,t):this._context.moveTo(n,t);break;case 1:this._point=2,this._x1=n,this._y1=t;break;case 2:this._point=3;default:Wa(this,n,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Y8=function n(t){function e(r){return new Hf(r,t)}return e.tension=function(r){return n(+r)},e}(0);function Xf(n,t){this._context=n,this._k=(1-t)/6}Xf.prototype={areaStart:Xt,areaEnd:Xt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1,this._x3=n,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=n,this._y4=t);break;case 2:this._point=3,this._x5=n,this._y5=t;break;default:Wa(this,n,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var U8=function n(t){function e(r){return new Xf(r,t)}return e.tension=function(r){return n(+r)},e}(0);function Gf(n,t){this._context=n,this._k=(1-t)/6}Gf.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Wa(this,n,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var B8=function n(t){function e(r){return new Gf(r,t)}return e.tension=function(r){return n(+r)},e}(0);function Vf(n,t,e){var r=n._x1,i=n._y1,a=n._x2,o=n._y2;if(n._l01_a>kn){var u=2*n._l01_2a+3*n._l01_a*n._l12_a+n._l12_2a,f=3*n._l01_a*(n._l01_a+n._l12_a);r=(r*u-n._x0*n._l12_2a+n._x2*n._l01_2a)/f,i=(i*u-n._y0*n._l12_2a+n._y2*n._l01_2a)/f}if(n._l23_a>kn){var c=2*n._l23_2a+3*n._l23_a*n._l12_a+n._l12_2a,s=3*n._l23_a*(n._l23_a+n._l12_a);a=(a*c+n._x1*n._l23_2a-t*n._l12_2a)/s,o=(o*c+n._y1*n._l23_2a-e*n._l12_2a)/s}n._context.bezierCurveTo(r,i,a,o,n._x2,n._y2)}function j1(n,t){this._context=n,this._alpha=t}j1.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){if(n=+n,t=+t,this._point){var e=this._x2-n,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(n,t):this._context.moveTo(n,t);break;case 1:this._point=2;break;case 2:this._point=3;default:Vf(this,n,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var H8=function n(t){function e(r){return t?new j1(r,t):new Hf(r,0)}return e.alpha=function(r){return n(+r)},e}(.5);function nd(n,t){this._context=n,this._alpha=t}nd.prototype={areaStart:Xt,areaEnd:Xt,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(n,t){if(n=+n,t=+t,this._point){var e=this._x2-n,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=n,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=n,this._y4=t);break;case 2:this._point=3,this._x5=n,this._y5=t;break;default:Vf(this,n,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var X8=function n(t){function e(r){return t?new nd(r,t):new Xf(r,0)}return e.alpha=function(r){return n(+r)},e}(.5);function td(n,t){this._context=n,this._alpha=t}td.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){if(n=+n,t=+t,this._point){var e=this._x2-n,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Vf(this,n,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=n,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var G8=function n(t){function e(r){return t?new td(r,t):new Gf(r,0)}return e.alpha=function(r){return n(+r)},e}(.5);function ed(n){this._context=n}ed.prototype={areaStart:Xt,areaEnd:Xt,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(n,t){n=+n,t=+t,this._point?this._context.lineTo(n,t):(this._point=1,this._context.moveTo(n,t))}};function V8(n){return new ed(n)}function rd(n){return n<0?-1:1}function id(n,t,e){var r=n._x1-n._x0,i=t-n._x1,a=(n._y1-n._y0)/(r||i<0&&-0),o=(e-n._y1)/(i||r<0&&-0),u=(a*i+o*r)/(r+i);return(rd(a)+rd(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(u))||0}function ad(n,t){var e=n._x1-n._x0;return e?(3*(n._y1-n._y0)/e-t)/2:t}function Wf(n,t,e){var r=n._x0,i=n._y0,a=n._x1,o=n._y1,u=(a-r)/3;n._context.bezierCurveTo(r+u,i+u*t,a-u,o-u*e,a,o)}function Za(n){this._context=n}Za.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Wf(this,this._t0,ad(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(n,t){var e=NaN;if(n=+n,t=+t,!(n===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(n,t):this._context.moveTo(n,t);break;case 1:this._point=2;break;case 2:this._point=3,Wf(this,ad(this,e=id(this,n,t)),e);break;default:Wf(this,this._t0,e=id(this,n,t));break}this._x0=this._x1,this._x1=n,this._y0=this._y1,this._y1=t,this._t0=e}}};function od(n){this._context=new ud(n)}(od.prototype=Object.create(Za.prototype)).point=function(n,t){Za.prototype.point.call(this,t,n)};function ud(n){this._context=n}ud.prototype={moveTo:function(n,t){this._context.moveTo(t,n)},closePath:function(){this._context.closePath()},lineTo:function(n,t){this._context.lineTo(t,n)},bezierCurveTo:function(n,t,e,r,i,a){this._context.bezierCurveTo(t,n,r,e,a,i)}};function W8(n){return new Za(n)}function Z8(n){return new od(n)}function fd(n){this._context=n}fd.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var n=this._x,t=this._y,e=n.length;if(e)if(this._line?this._context.lineTo(n[0],t[0]):this._context.moveTo(n[0],t[0]),e===2)this._context.lineTo(n[1],t[1]);else for(var r=cd(n),i=cd(t),a=0,o=1;o=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[e-1]=(n[e]+i[e-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(n,t){switch(n=+n,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(n,t):this._context.moveTo(n,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(n,t);else{var e=this._x*(1-this._t)+n*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,t)}break}}this._x=n,this._y=t}};function K8(n){return new Qa(n,.5)}function J8(n){return new Qa(n,0)}function j8(n){return new Qa(n,1)}function Ze(n,t){if((o=n.length)>1)for(var e=1,r,i,a=n[t[0]],o,u=a.length;e=0;)e[t]=t;return e}function n4(n,t){return n[t]}function t4(n){const t=[];return t.key=n,t}function e4(){var n=V([]),t=Qe,e=Ze,r=n4;function i(a){var o=Array.from(n.apply(this,arguments),t4),u,f=o.length,c=-1,s;for(const h of a)for(u=0,++c;u0){for(var e,r,i=0,a=n[0].length,o;i0)for(var e,r=0,i,a,o,u,f,c=n[t[0]].length;r0?(i[0]=o,i[1]=o+=a):a<0?(i[1]=u,i[0]=u+=a):(i[0]=0,i[1]=a)}function a4(n,t){if((i=n.length)>0){for(var e=0,r=n[t[0]],i,a=r.length;e0)||!((a=(i=n[t[0]]).length)>0))){for(var e=0,r=1,i,a,o;ra&&(a=i,e=t);return e}function ld(n){var t=n.map(hd);return Qe(n).sort(function(e,r){return t[e]-t[r]})}function hd(n){for(var t=0,e=-1,r=n.length,i;++e()=>n;function l4(n,{sourceEvent:t,target:e,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:n,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function vt(n,t,e){this.k=n,this.x=t,this.y=e}vt.prototype={constructor:vt,scale:function(n){return n===1?this:new vt(this.k*n,this.x,this.y)},translate:function(n,t){return n===0&t===0?this:new vt(this.k,this.x+this.k*n,this.y+this.k*t)},apply:function(n){return[n[0]*this.k+this.x,n[1]*this.k+this.y]},applyX:function(n){return n*this.k+this.x},applyY:function(n){return n*this.k+this.y},invert:function(n){return[(n[0]-this.x)/this.k,(n[1]-this.y)/this.k]},invertX:function(n){return(n-this.x)/this.k},invertY:function(n){return(n-this.y)/this.k},rescaleX:function(n){return n.copy().domain(n.range().map(this.invertX,this).map(n.invert,n))},rescaleY:function(n){return n.copy().domain(n.range().map(this.invertY,this).map(n.invert,n))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Ja=new vt(1,0,0);dd.prototype=vt.prototype;function dd(n){for(;!n.__zoom;)if(!(n=n.parentNode))return Ja;return n.__zoom}function Zf(n){n.stopImmediatePropagation()}function Jr(n){n.preventDefault(),n.stopImmediatePropagation()}function h4(n){return(!n.ctrlKey||n.type==="wheel")&&!n.button}function d4(){var n=this;return n instanceof SVGElement?(n=n.ownerSVGElement||n,n.hasAttribute("viewBox")?(n=n.viewBox.baseVal,[[n.x,n.y],[n.x+n.width,n.y+n.height]]):[[0,0],[n.width.baseVal.value,n.height.baseVal.value]]):[[0,0],[n.clientWidth,n.clientHeight]]}function gd(){return this.__zoom||Ja}function g4(n){return-n.deltaY*(n.deltaMode===1?.05:n.deltaMode?1:.002)*(n.ctrlKey?10:1)}function p4(){return navigator.maxTouchPoints||"ontouchstart"in this}function m4(n,t,e){var r=n.invertX(t[0][0])-e[0][0],i=n.invertX(t[1][0])-e[1][0],a=n.invertY(t[0][1])-e[0][1],o=n.invertY(t[1][1])-e[1][1];return n.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function y4(){var n=h4,t=d4,e=m4,r=g4,i=p4,a=[0,Infinity],o=[[-Infinity,-Infinity],[Infinity,Infinity]],u=250,f=ys,c=Gt("start","zoom","end"),s,h,l,d=500,y=150,m=0,g=10;function p(M){M.property("__zoom",gd).on("wheel.zoom",k,{passive:!1}).on("mousedown.zoom",P).on("dblclick.zoom",S).filter(i).on("touchstart.zoom",E).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",$).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}p.transform=function(M,T,A,C){var I=M.selection?M.selection():M;I.property("__zoom",gd),M!==I?w(M,T,A,C):I.interrupt().each(function(){x(this,arguments).event(C).start().zoom(null,typeof T=="function"?T.apply(this,arguments):T).end()})},p.scaleBy=function(M,T,A,C){p.scaleTo(M,function(){var I=this.__zoom.k,D=typeof T=="function"?T.apply(this,arguments):T;return I*D},A,C)},p.scaleTo=function(M,T,A,C){p.transform(M,function(){var I=t.apply(this,arguments),D=this.__zoom,O=A==null?v(I):typeof A=="function"?A.apply(this,arguments):A,L=D.invert(O),U=typeof T=="function"?T.apply(this,arguments):T;return e(_(b(D,U),O,L),I,o)},A,C)},p.translateBy=function(M,T,A,C){p.transform(M,function(){return e(this.__zoom.translate(typeof T=="function"?T.apply(this,arguments):T,typeof A=="function"?A.apply(this,arguments):A),t.apply(this,arguments),o)},null,C)},p.translateTo=function(M,T,A,C,I){p.transform(M,function(){var D=t.apply(this,arguments),O=this.__zoom,L=C==null?v(D):typeof C=="function"?C.apply(this,arguments):C;return e(Ja.translate(L[0],L[1]).scale(O.k).translate(typeof T=="function"?-T.apply(this,arguments):-T,typeof A=="function"?-A.apply(this,arguments):-A),D,o)},C,I)};function b(M,T){return T=Math.max(a[0],Math.min(a[1],T)),T===M.k?M:new vt(T,M.x,M.y)}function _(M,T,A){var C=T[0]-A[0]*M.k,I=T[1]-A[1]*M.k;return C===M.x&&I===M.y?M:new vt(M.k,C,I)}function v(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function w(M,T,A,C){M.on("start.zoom",function(){x(this,arguments).event(C).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).event(C).end()}).tween("zoom",function(){var I=this,D=arguments,O=x(I,D).event(C),L=t.apply(I,D),U=A==null?v(L):typeof A=="function"?A.apply(I,D):A,tn=Math.max(L[1][0]-L[0][0],L[1][1]-L[0][1]),Z=I.__zoom,en=typeof T=="function"?T.apply(I,D):T,gn=f(Z.invert(U).concat(tn/Z.k),en.invert(U).concat(tn/en.k));return function(j){if(j===1)j=en;else{var dn=gn(j),q=tn/dn[2];j=new vt(q,U[0]-dn[0]*q,U[1]-dn[1]*q)}O.zoom(null,j)}})}function x(M,T,A){return!A&&M.__zooming||new N(M,T)}function N(M,T){this.that=M,this.args=T,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,T),this.taps=0}N.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active==1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,T){return this.mouse&&M!=="mouse"&&(this.mouse[1]=T.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=T.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=T.invert(this.touch1[0])),this.that.__zoom=T,this.emit("zoom"),this},end:function(){return--this.active==0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var T=Sn(this.that).datum();c.call(M,this.that,new l4(M,{sourceEvent:this.sourceEvent,target:p,type:M,transform:this.that.__zoom,dispatch:c}),T)}};function k(M,...T){if(!n.apply(this,arguments))return;var A=x(this,T).event(M),C=this.__zoom,I=Math.max(a[0],Math.min(a[1],C.k*Math.pow(2,r.apply(this,arguments)))),D=Xn(M);if(A.wheel)(A.mouse[0][0]!==D[0]||A.mouse[0][1]!==D[1])&&(A.mouse[1]=C.invert(A.mouse[0]=D)),clearTimeout(A.wheel);else{if(C.k===I)return;A.mouse=[D,C.invert(D)],Jt(this),A.start()}Jr(M),A.wheel=setTimeout(O,y),A.zoom("mouse",e(_(b(C,I),A.mouse[0],A.mouse[1]),A.extent,o));function O(){A.wheel=null,A.end()}}function P(M,...T){if(l||!n.apply(this,arguments))return;var A=M.currentTarget,C=x(this,T,!0).event(M),I=Sn(M.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",tn,!0),D=Xn(M,A),O=M.clientX,L=M.clientY;hi(M.view),Zf(M),C.mouse=[D,this.__zoom.invert(D)],Jt(this),C.start();function U(Z){if(Jr(Z),!C.moved){var en=Z.clientX-O,gn=Z.clientY-L;C.moved=en*en+gn*gn>m}C.event(Z).zoom("mouse",e(_(C.that.__zoom,C.mouse[0]=Xn(Z,A),C.mouse[1]),C.extent,o))}function tn(Z){I.on("mousemove.zoom mouseup.zoom",null),di(Z.view,C.moved),Jr(Z),C.event(Z).end()}}function S(M,...T){if(!!n.apply(this,arguments)){var A=this.__zoom,C=Xn(M.changedTouches?M.changedTouches[0]:M,this),I=A.invert(C),D=A.k*(M.shiftKey?.5:2),O=e(_(b(A,D),C,I),t.apply(this,T),o);Jr(M),u>0?Sn(this).transition().duration(u).call(w,O,C,M):Sn(this).call(p.transform,O,C,M)}}function E(M,...T){if(!!n.apply(this,arguments)){var A=M.touches,C=A.length,I=x(this,T,M.changedTouches.length===C).event(M),D,O,L,U;for(Zf(M),O=0;O18),o&&(t.weChat=!0),e.svgSupported=typeof SVGRect!="undefined",e.touchEventsSupported="ontouchstart"in window&&!t.ie&&!t.edge,e.pointerEventsSupported="onpointerdown"in window&&(t.edge||t.ie&&+t.version>=11),e.domSupported=typeof document!="undefined";var s=document.documentElement.style;e.transform3dSupported=(t.ie&&"transition"in s||t.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in s)&&!("OTransition"in s),e.transformSupported=e.transform3dSupported||t.ie&&+t.version>=9}var ev=12,Mm="sans-serif",Ca=ev+"px "+Mm,fL=20,hL=100,vL="007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";function cL(r){var e={};if(typeof JSON=="undefined")return e;for(var t=0;t=0)s=o*t.length;else for(var l=0;l>1)%2;s.cssText=["position: absolute","visibility: hidden","padding: 0","margin: 0","border-width: 0","user-select: none","width:0","height:0",a[l]+":0",n[u]+":0",a[1-l]+":auto",n[1-u]+":auto",""].join("!important;"),r.appendChild(o),t.push(o)}return t}function OL(r,e,t){for(var a=t?"invTrans":"trans",n=e[a],i=e.srcCoords,o=[],s=[],l=!0,u=0;u<4;u++){var f=r[u].getBoundingClientRect(),h=2*u,v=f.left,c=f.top;o.push(v,c),l=l&&i&&v===i[h]&&c===i[h+1],s.push(r[u].offsetLeft,r[u].offsetTop)}return l&&n?n:(e.srcCoords=o,e[a]=t?Fm(s,o):Fm(o,s))}function Wm(r){return r.nodeName.toUpperCase()==="CANVAS"}var NL=/([&<>"'])/g,BL={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ce(r){return r==null?"":(r+"").replace(NL,function(e,t){return BL[t]})}var VL=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,pv=[],zL=_t.browser.firefox&&+_t.browser.version.split(".")[0]<39;function dv(r,e,t,a){return t=t||{},a?Um(r,e,t):zL&&e.layerX!=null&&e.layerX!==e.offsetX?(t.zrX=e.layerX,t.zrY=e.layerY):e.offsetX!=null?(t.zrX=e.offsetX,t.zrY=e.offsetY):Um(r,e,t),t}function Um(r,e,t){if(_t.domSupported&&r.getBoundingClientRect){var a=e.clientX,n=e.clientY;if(Wm(r)){var i=r.getBoundingClientRect();t.zrX=a-i.left,t.zrY=n-i.top;return}else if(cv(pv,r,a,n)){t.zrX=pv[0],t.zrY=pv[1];return}}t.zrX=t.zrY=0}function gv(r){return r||window.event}function Qe(r,e,t){if(e=gv(e),e.zrX!=null)return e;var a=e.type,n=a&&a.indexOf("touch")>=0;if(n){var o=a!=="touchend"?e.targetTouches[0]:e.changedTouches[0];o&&dv(r,o,e,t)}else{dv(r,e,e,t);var i=GL(e);e.zrDelta=i?i/120:-(e.detail||0)/3}var s=e.button;return e.which==null&&s!==void 0&&VL.test(e.type)&&(e.which=s&1?1:s&2?3:s&4?2:0),e}function GL(r){var e=r.wheelDelta;if(e)return e;var t=r.deltaX,a=r.deltaY;if(t==null||a==null)return e;var n=Math.abs(a!==0?a:t),i=a>0?-1:a<0?1:t>0?-1:1;return 3*n*i}function yv(r,e,t,a){r.addEventListener(e,t,a)}function FL(r,e,t,a){r.removeEventListener(e,t,a)}var ia=function(r){r.preventDefault(),r.stopPropagation(),r.cancelBubble=!0};function Ym(r){return r.which===2||r.which===3}var HL=function(){function r(){this._track=[]}return r.prototype.recognize=function(e,t,a){return this._doTrack(e,t,a),this._recognize(e)},r.prototype.clear=function(){return this._track.length=0,this},r.prototype._doTrack=function(e,t,a){var n=e.touches;if(!!n){for(var i={points:[],touches:[],target:t,event:e},o=0,s=n.length;o1&&a&&a.length>1){var i=Xm(a)/Xm(n);!isFinite(i)&&(i=1),e.pinchScale=i;var o=WL(a);return e.pinchX=o[0],e.pinchY=o[1],{type:"pinch",target:r[0].target,event:e}}}}};function Ge(){return[1,0,0,1,0,0]}function Ho(r){return r[0]=1,r[1]=0,r[2]=0,r[3]=1,r[4]=0,r[5]=0,r}function Jl(r,e){return r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=e[4],r[5]=e[5],r}function Or(r,e,t){var a=e[0]*t[0]+e[2]*t[1],n=e[1]*t[0]+e[3]*t[1],i=e[0]*t[2]+e[2]*t[3],o=e[1]*t[2]+e[3]*t[3],s=e[0]*t[4]+e[2]*t[5]+e[4],l=e[1]*t[4]+e[3]*t[5]+e[5];return r[0]=a,r[1]=n,r[2]=i,r[3]=o,r[4]=s,r[5]=l,r}function mr(r,e,t){return r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=e[4]+t[0],r[5]=e[5]+t[1],r}function Ia(r,e,t){var a=e[0],n=e[2],i=e[4],o=e[1],s=e[3],l=e[5],u=Math.sin(t),f=Math.cos(t);return r[0]=a*f+o*u,r[1]=-a*u+o*f,r[2]=n*f+s*u,r[3]=-n*u+f*s,r[4]=f*i+u*l,r[5]=f*l-u*i,r}function tu(r,e,t){var a=t[0],n=t[1];return r[0]=e[0]*a,r[1]=e[1]*n,r[2]=e[2]*a,r[3]=e[3]*n,r[4]=e[4]*a,r[5]=e[5]*n,r}function hn(r,e){var t=e[0],a=e[2],n=e[4],i=e[1],o=e[3],s=e[5],l=t*o-i*a;return l?(l=1/l,r[0]=o*l,r[1]=-i*l,r[2]=-a*l,r[3]=t*l,r[4]=(a*s-o*n)*l,r[5]=(i*n-t*s)*l,r):null}function Zm(r){var e=Ge();return Jl(e,r),e}var UL=Object.freeze({__proto__:null,create:Ge,identity:Ho,copy:Jl,mul:Or,translate:mr,rotate:Ia,scale:tu,invert:hn,clone:Zm}),ut=function(){function r(e,t){this.x=e||0,this.y=t||0}return r.prototype.copy=function(e){return this.x=e.x,this.y=e.y,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.prototype.set=function(e,t){return this.x=e,this.y=t,this},r.prototype.equal=function(e){return e.x===this.x&&e.y===this.y},r.prototype.add=function(e){return this.x+=e.x,this.y+=e.y,this},r.prototype.scale=function(e){this.x*=e,this.y*=e},r.prototype.scaleAndAdd=function(e,t){this.x+=e.x*t,this.y+=e.y*t},r.prototype.sub=function(e){return this.x-=e.x,this.y-=e.y,this},r.prototype.dot=function(e){return this.x*e.x+this.y*e.y},r.prototype.len=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lenSquare=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var e=this.len();return this.x/=e,this.y/=e,this},r.prototype.distance=function(e){var t=this.x-e.x,a=this.y-e.y;return Math.sqrt(t*t+a*a)},r.prototype.distanceSquare=function(e){var t=this.x-e.x,a=this.y-e.y;return t*t+a*a},r.prototype.negate=function(){return this.x=-this.x,this.y=-this.y,this},r.prototype.transform=function(e){if(!!e){var t=this.x,a=this.y;return this.x=e[0]*t+e[2]*a+e[4],this.y=e[1]*t+e[3]*a+e[5],this}},r.prototype.toArray=function(e){return e[0]=this.x,e[1]=this.y,e},r.prototype.fromArray=function(e){this.x=e[0],this.y=e[1]},r.set=function(e,t,a){e.x=t,e.y=a},r.copy=function(e,t){e.x=t.x,e.y=t.y},r.len=function(e){return Math.sqrt(e.x*e.x+e.y*e.y)},r.lenSquare=function(e){return e.x*e.x+e.y*e.y},r.dot=function(e,t){return e.x*t.x+e.y*t.y},r.add=function(e,t,a){e.x=t.x+a.x,e.y=t.y+a.y},r.sub=function(e,t,a){e.x=t.x-a.x,e.y=t.y-a.y},r.scale=function(e,t,a){e.x=t.x*a,e.y=t.y*a},r.scaleAndAdd=function(e,t,a,n){e.x=t.x+a.x*n,e.y=t.y+a.y*n},r.lerp=function(e,t,a,n){var i=1-n;e.x=i*t.x+n*a.x,e.y=i*t.y+n*a.y},r}(),eu=Math.min,ru=Math.max,vn=new ut,cn=new ut,pn=new ut,dn=new ut,Wo=new ut,Uo=new ut,ft=function(){function r(e,t,a,n){a<0&&(e=e+a,a=-a),n<0&&(t=t+n,n=-n),this.x=e,this.y=t,this.width=a,this.height=n}return r.prototype.union=function(e){var t=eu(e.x,this.x),a=eu(e.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=ru(e.x+e.width,this.x+this.width)-t:this.width=e.width,isFinite(this.y)&&isFinite(this.height)?this.height=ru(e.y+e.height,this.y+this.height)-a:this.height=e.height,this.x=t,this.y=a},r.prototype.applyTransform=function(e){r.applyTransform(this,this,e)},r.prototype.calculateTransform=function(e){var t=this,a=e.width/t.width,n=e.height/t.height,i=Ge();return mr(i,i,[-t.x,-t.y]),tu(i,i,[a,n]),mr(i,i,[e.x,e.y]),i},r.prototype.intersect=function(e,t){if(!e)return!1;e instanceof r||(e=r.create(e));var a=this,n=a.x,i=a.x+a.width,o=a.y,s=a.y+a.height,l=e.x,u=e.x+e.width,f=e.y,h=e.y+e.height,v=!(ip&&(p=_,dp&&(p=S,y=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height},r.prototype.clone=function(){return new r(this.x,this.y,this.width,this.height)},r.prototype.copy=function(e){r.copy(this,e)},r.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},r.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},r.prototype.isZero=function(){return this.width===0||this.height===0},r.create=function(e){return new r(e.x,e.y,e.width,e.height)},r.copy=function(e,t){e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height},r.applyTransform=function(e,t,a){if(!a){e!==t&&r.copy(e,t);return}if(a[1]<1e-5&&a[1]>-1e-5&&a[2]<1e-5&&a[2]>-1e-5){var n=a[0],i=a[3],o=a[4],s=a[5];e.x=t.x*n+o,e.y=t.y*i+s,e.width=t.width*n,e.height=t.height*i,e.width<0&&(e.x+=e.width,e.width=-e.width),e.height<0&&(e.y+=e.height,e.height=-e.height);return}vn.x=pn.x=t.x,vn.y=dn.y=t.y,cn.x=dn.x=t.x+t.width,cn.y=pn.y=t.y+t.height,vn.transform(a),dn.transform(a),cn.transform(a),pn.transform(a),e.x=eu(vn.x,cn.x,pn.x,dn.x),e.y=eu(vn.y,cn.y,pn.y,dn.y);var l=ru(vn.x,cn.x,pn.x,dn.x),u=ru(vn.y,cn.y,pn.y,dn.y);e.width=l-e.x,e.height=u-e.y},r}(),$m="silent";function YL(r,e,t){return{type:r,event:t,target:e.target,topTarget:e.topTarget,cancelBubble:!1,offsetX:t.zrX,offsetY:t.zrY,gestureEvent:t.gestureEvent,pinchX:t.pinchX,pinchY:t.pinchY,pinchScale:t.pinchScale,wheelDelta:t.zrDelta,zrByTouch:t.zrByTouch,which:t.which,stop:XL}}function XL(){ia(this.event)}var ZL=function(r){zt(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.handler=null,t}return e.prototype.dispose=function(){},e.prototype.setCursor=function(){},e}(je),Yo=function(){function r(e,t){this.x=e,this.y=t}return r}(),$L=["click","dblclick","mousewheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],_v=new ft(0,0,0,0),qm=function(r){zt(e,r);function e(t,a,n,i,o){var s=r.call(this)||this;return s._hovered=new Yo(0,0),s.storage=t,s.painter=a,s.painterRoot=i,s._pointerSize=o,n=n||new ZL,s.proxy=null,s.setHandlerProxy(n),s._draggingMgr=new PL(s),s}return e.prototype.setHandlerProxy=function(t){this.proxy&&this.proxy.dispose(),t&&(A($L,function(a){t.on&&t.on(a,this[a],this)},this),t.handler=this),this.proxy=t},e.prototype.mousemove=function(t){var a=t.zrX,n=t.zrY,i=jm(this,a,n),o=this._hovered,s=o.target;s&&!s.__zr&&(o=this.findHover(o.x,o.y),s=o.target);var l=this._hovered=i?new Yo(a,n):this.findHover(a,n),u=l.target,f=this.proxy;f.setCursor&&f.setCursor(u?u.cursor:"default"),s&&u!==s&&this.dispatchToElement(o,"mouseout",t),this.dispatchToElement(l,"mousemove",t),u&&u!==s&&this.dispatchToElement(l,"mouseover",t)},e.prototype.mouseout=function(t){var a=t.zrEventControl;a!=="only_globalout"&&this.dispatchToElement(this._hovered,"mouseout",t),a!=="no_globalout"&&this.trigger("globalout",{type:"globalout",event:t})},e.prototype.resize=function(){this._hovered=new Yo(0,0)},e.prototype.dispatch=function(t,a){var n=this[t];n&&n.call(this,a)},e.prototype.dispose=function(){this.proxy.dispose(),this.storage=null,this.proxy=null,this.painter=null},e.prototype.setCursorStyle=function(t){var a=this.proxy;a.setCursor&&a.setCursor(t)},e.prototype.dispatchToElement=function(t,a,n){t=t||{};var i=t.target;if(!(i&&i.silent)){for(var o="on"+a,s=YL(a,t,n);i&&(i[o]&&(s.cancelBubble=!!i[o].call(i,s)),i.trigger(a,s),i=i.__hostTarget?i.__hostTarget:i.parent,!s.cancelBubble););s.cancelBubble||(this.trigger(a,s),this.painter&&this.painter.eachOtherLayer&&this.painter.eachOtherLayer(function(l){typeof l[o]=="function"&&l[o].call(l,s),l.trigger&&l.trigger(a,s)}))}},e.prototype.findHover=function(t,a,n){var i=this.storage.getDisplayList(),o=new Yo(t,a);if(Km(i,o,t,a,n),this._pointerSize&&!o.target){for(var s=[],l=this._pointerSize,u=l/2,f=new ft(t-u,a-u,l,l),h=i.length-1;h>=0;h--){var v=i[h];v!==n&&!v.ignore&&!v.ignoreCoarsePointer&&(!v.parent||!v.parent.ignoreCoarsePointer)&&(_v.copy(v.getBoundingRect()),v.transform&&_v.applyTransform(v.transform),_v.intersect(f)&&s.push(v))}if(s.length)for(var c=4,p=Math.PI/12,d=Math.PI*2,g=0;g4)return;this._downPoint=null}this.dispatchToElement(i,r,e)}});function qL(r,e,t){if(r[r.rectHover?"rectContain":"contain"](e,t)){for(var a=r,n=void 0,i=!1;a;){if(a.ignoreClip&&(i=!0),!i){var o=a.getClipPath();if(o&&!o.contain(e,t))return!1;a.silent&&(n=!0)}var s=a.__hostTarget;a=s||a.parent}return n?$m:!0}return!1}function Km(r,e,t,a,n){for(var i=r.length-1;i>=0;i--){var o=r[i],s=void 0;if(o!==n&&!o.ignore&&(s=qL(o,t,a))&&(!e.topTarget&&(e.topTarget=o),s!==$m)){e.target=o;break}}}function jm(r,e,t){var a=r.painter;return e<0||e>a.getWidth()||t<0||t>a.getHeight()}var Qm=32,Xo=7;function KL(r){for(var e=0;r>=Qm;)e|=r&1,r>>=1;return r+e}function Jm(r,e,t,a){var n=e+1;if(n===t)return 1;if(a(r[n++],r[e])<0){for(;n=0;)n++;return n-e}function jL(r,e,t){for(t--;e>>1,n(i,r[l])<0?s=l:o=l+1;var u=a-o;switch(u){case 3:r[o+3]=r[o+2];case 2:r[o+2]=r[o+1];case 1:r[o+1]=r[o];break;default:for(;u>0;)r[o+u]=r[o+u-1],u--}r[o]=i}}function Sv(r,e,t,a,n,i){var o=0,s=0,l=1;if(i(r,e[t+n])>0){for(s=a-n;l0;)o=l,l=(l<<1)+1,l<=0&&(l=s);l>s&&(l=s),o+=n,l+=n}else{for(s=n+1;ls&&(l=s);var u=o;o=n-l,l=n-u}for(o++;o>>1);i(r,e[t+f])>0?o=f+1:l=f}return l}function xv(r,e,t,a,n,i){var o=0,s=0,l=1;if(i(r,e[t+n])<0){for(s=n+1;ls&&(l=s);var u=o;o=n-l,l=n-u}else{for(s=a-n;l=0;)o=l,l=(l<<1)+1,l<=0&&(l=s);l>s&&(l=s),o+=n,l+=n}for(o++;o>>1);i(r,e[t+f])<0?l=f:o=f+1}return l}function QL(r,e){var t=Xo,a,n,i=0;r.length;var o=[];a=[],n=[];function s(c,p){a[i]=c,n[i]=p,i+=1}function l(){for(;i>1;){var c=i-2;if(c>=1&&n[c-1]<=n[c]+n[c+1]||c>=2&&n[c-2]<=n[c]+n[c-1])n[c-1]n[c+1])break;f(c)}}function u(){for(;i>1;){var c=i-2;c>0&&n[c-1]=Xo||w>=Xo);if(T)break;b<0&&(b=0),b+=2}if(t=b,t<1&&(t=1),p===1){for(y=0;y=0;y--)r[x+y]=r[b+y];r[S]=o[_];return}for(var w=t;;){var T=0,C=0,D=!1;do if(e(o[_],r[m])<0){if(r[S--]=r[m--],T++,C=0,--p==0){D=!0;break}}else if(r[S--]=o[_--],C++,T=0,--g==1){D=!0;break}while((T|C)=0;y--)r[x+y]=r[b+y];if(p===0){D=!0;break}}if(r[S--]=o[_--],--g==1){D=!0;break}if(C=g-Sv(r[m],o,0,g,g-1,e),C!==0){for(S-=C,_-=C,g-=C,x=S+1,b=_+1,y=0;y=Xo||C>=Xo);if(D)break;w<0&&(w=0),w+=2}if(t=w,t<1&&(t=1),g===1){for(S-=p,m-=p,x=S+1,b=m+1,y=p-1;y>=0;y--)r[x+y]=r[b+y];r[S]=o[_]}else{if(g===0)throw new Error;for(b=S-(g-1),y=0;ys&&(l=s),t0(r,t,t+l,t+i,e),i=l}o.pushRun(t,i),o.mergeRuns(),n-=i,t+=i}while(n!==0);o.forceMergeRuns()}}var Fe=1,Zo=2,wi=4,e0=!1;function bv(){e0||(e0=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function r0(r,e){return r.zlevel===e.zlevel?r.z===e.z?r.z2-e.z2:r.z-e.z:r.zlevel-e.zlevel}var JL=function(){function r(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=r0}return r.prototype.traverse=function(e,t){for(var a=0;a0&&(f.__clipPaths=[]),isNaN(f.z)&&(bv(),f.z=0),isNaN(f.z2)&&(bv(),f.z2=0),isNaN(f.zlevel)&&(bv(),f.zlevel=0),this._displayList[this._displayListLen++]=f}var h=e.getDecalElement&&e.getDecalElement();h&&this._updateAndAddDisplayable(h,t,a);var v=e.getTextGuideLine();v&&this._updateAndAddDisplayable(v,t,a);var c=e.getTextContent();c&&this._updateAndAddDisplayable(c,t,a)}},r.prototype.addRoot=function(e){e.__zr&&e.__zr.storage===this||this._roots.push(e)},r.prototype.delRoot=function(e){if(e instanceof Array){for(var t=0,a=e.length;t=0&&this._roots.splice(n,1)},r.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},r.prototype.getRoots=function(){return this._roots},r.prototype.dispose=function(){this._displayList=null,this._roots=null},r}(),a0;a0=_t.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(r){return setTimeout(r,16)};var wv=a0,$o={linear:function(r){return r},quadraticIn:function(r){return r*r},quadraticOut:function(r){return r*(2-r)},quadraticInOut:function(r){return(r*=2)<1?.5*r*r:-.5*(--r*(r-2)-1)},cubicIn:function(r){return r*r*r},cubicOut:function(r){return--r*r*r+1},cubicInOut:function(r){return(r*=2)<1?.5*r*r*r:.5*((r-=2)*r*r+2)},quarticIn:function(r){return r*r*r*r},quarticOut:function(r){return 1- --r*r*r*r},quarticInOut:function(r){return(r*=2)<1?.5*r*r*r*r:-.5*((r-=2)*r*r*r-2)},quinticIn:function(r){return r*r*r*r*r},quinticOut:function(r){return--r*r*r*r*r+1},quinticInOut:function(r){return(r*=2)<1?.5*r*r*r*r*r:.5*((r-=2)*r*r*r*r+2)},sinusoidalIn:function(r){return 1-Math.cos(r*Math.PI/2)},sinusoidalOut:function(r){return Math.sin(r*Math.PI/2)},sinusoidalInOut:function(r){return .5*(1-Math.cos(Math.PI*r))},exponentialIn:function(r){return r===0?0:Math.pow(1024,r-1)},exponentialOut:function(r){return r===1?1:1-Math.pow(2,-10*r)},exponentialInOut:function(r){return r===0?0:r===1?1:(r*=2)<1?.5*Math.pow(1024,r-1):.5*(-Math.pow(2,-10*(r-1))+2)},circularIn:function(r){return 1-Math.sqrt(1-r*r)},circularOut:function(r){return Math.sqrt(1- --r*r)},circularInOut:function(r){return(r*=2)<1?-.5*(Math.sqrt(1-r*r)-1):.5*(Math.sqrt(1-(r-=2)*r)+1)},elasticIn:function(r){var e,t=.1,a=.4;return r===0?0:r===1?1:(!t||t<1?(t=1,e=a/4):e=a*Math.asin(1/t)/(2*Math.PI),-(t*Math.pow(2,10*(r-=1))*Math.sin((r-e)*(2*Math.PI)/a)))},elasticOut:function(r){var e,t=.1,a=.4;return r===0?0:r===1?1:(!t||t<1?(t=1,e=a/4):e=a*Math.asin(1/t)/(2*Math.PI),t*Math.pow(2,-10*r)*Math.sin((r-e)*(2*Math.PI)/a)+1)},elasticInOut:function(r){var e,t=.1,a=.4;return r===0?0:r===1?1:(!t||t<1?(t=1,e=a/4):e=a*Math.asin(1/t)/(2*Math.PI),(r*=2)<1?-.5*(t*Math.pow(2,10*(r-=1))*Math.sin((r-e)*(2*Math.PI)/a)):t*Math.pow(2,-10*(r-=1))*Math.sin((r-e)*(2*Math.PI)/a)*.5+1)},backIn:function(r){var e=1.70158;return r*r*((e+1)*r-e)},backOut:function(r){var e=1.70158;return--r*r*((e+1)*r+e)+1},backInOut:function(r){var e=1.70158*1.525;return(r*=2)<1?.5*(r*r*((e+1)*r-e)):.5*((r-=2)*r*((e+1)*r+e)+2)},bounceIn:function(r){return 1-$o.bounceOut(1-r)},bounceOut:function(r){return r<1/2.75?7.5625*r*r:r<2/2.75?7.5625*(r-=1.5/2.75)*r+.75:r<2.5/2.75?7.5625*(r-=2.25/2.75)*r+.9375:7.5625*(r-=2.625/2.75)*r+.984375},bounceInOut:function(r){return r<.5?$o.bounceIn(r*2)*.5:$o.bounceOut(r*2-1)*.5+.5}},nu=Math.pow,La=Math.sqrt,iu=1e-8,n0=1e-4,i0=La(3),ou=1/3,Nr=Aa(),Je=Aa(),Ti=Aa();function Pa(r){return r>-iu&&riu||r<-iu}function re(r,e,t,a,n){var i=1-n;return i*i*(i*r+3*n*e)+n*n*(n*a+3*i*t)}function s0(r,e,t,a,n){var i=1-n;return 3*(((e-r)*i+2*(t-e)*n)*i+(a-t)*n*n)}function su(r,e,t,a,n,i){var o=a+3*(e-t)-r,s=3*(t-e*2+r),l=3*(e-r),u=r-n,f=s*s-3*o*l,h=s*l-9*o*u,v=l*l-3*s*u,c=0;if(Pa(f)&&Pa(h))if(Pa(s))i[0]=0;else{var p=-l/s;p>=0&&p<=1&&(i[c++]=p)}else{var d=h*h-4*f*v;if(Pa(d)){var g=h/f,p=-s/o+g,y=-g/2;p>=0&&p<=1&&(i[c++]=p),y>=0&&y<=1&&(i[c++]=y)}else if(d>0){var m=La(d),_=f*s+1.5*o*(-h+m),S=f*s+1.5*o*(-h-m);_<0?_=-nu(-_,ou):_=nu(_,ou),S<0?S=-nu(-S,ou):S=nu(S,ou);var p=(-s-(_+S))/(3*o);p>=0&&p<=1&&(i[c++]=p)}else{var b=(2*f*s-3*o*h)/(2*La(f*f*f)),x=Math.acos(b)/3,w=La(f),T=Math.cos(x),p=(-s-2*w*T)/(3*o),y=(-s+w*(T+i0*Math.sin(x)))/(3*o),C=(-s+w*(T-i0*Math.sin(x)))/(3*o);p>=0&&p<=1&&(i[c++]=p),y>=0&&y<=1&&(i[c++]=y),C>=0&&C<=1&&(i[c++]=C)}}return c}function l0(r,e,t,a,n){var i=6*t-12*e+6*r,o=9*e+3*a-3*r-9*t,s=3*e-3*r,l=0;if(Pa(o)){if(o0(i)){var u=-s/i;u>=0&&u<=1&&(n[l++]=u)}}else{var f=i*i-4*o*s;if(Pa(f))n[0]=-i/(2*o);else if(f>0){var h=La(f),u=(-i+h)/(2*o),v=(-i-h)/(2*o);u>=0&&u<=1&&(n[l++]=u),v>=0&&v<=1&&(n[l++]=v)}}return l}function Ra(r,e,t,a,n,i){var o=(e-r)*n+r,s=(t-e)*n+e,l=(a-t)*n+t,u=(s-o)*n+o,f=(l-s)*n+s,h=(f-u)*n+u;i[0]=r,i[1]=o,i[2]=u,i[3]=h,i[4]=h,i[5]=f,i[6]=l,i[7]=a}function u0(r,e,t,a,n,i,o,s,l,u,f){var h,v=.005,c=Infinity,p,d,g,y;Nr[0]=l,Nr[1]=u;for(var m=0;m<1;m+=.05)Je[0]=re(r,t,n,o,m),Je[1]=re(e,a,i,s,m),g=Ma(Nr,Je),g=0&&g=0&&u<=1&&(n[l++]=u)}}else{var f=o*o-4*i*s;if(Pa(f)){var u=-o/(2*i);u>=0&&u<=1&&(n[l++]=u)}else if(f>0){var h=La(f),u=(-o+h)/(2*i),v=(-o-h)/(2*i);u>=0&&u<=1&&(n[l++]=u),v>=0&&v<=1&&(n[l++]=v)}}return l}function f0(r,e,t){var a=r+t-2*e;return a===0?.5:(r-e)/a}function qo(r,e,t,a,n){var i=(e-r)*a+r,o=(t-e)*a+e,s=(o-i)*a+i;n[0]=r,n[1]=i,n[2]=s,n[3]=s,n[4]=o,n[5]=t}function h0(r,e,t,a,n,i,o,s,l){var u,f=.005,h=Infinity;Nr[0]=o,Nr[1]=s;for(var v=0;v<1;v+=.05){Je[0]=ue(r,t,n,v),Je[1]=ue(e,a,i,v);var c=Ma(Nr,Je);c=0&&c=1?1:su(0,a,i,1,l,s)&&re(0,n,o,1,s[0])}}}var n2=function(){function r(e){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=e.life||1e3,this._delay=e.delay||0,this.loop=e.loop||!1,this.onframe=e.onframe||Zt,this.ondestroy=e.ondestroy||Zt,this.onrestart=e.onrestart||Zt,e.easing&&this.setEasing(e.easing)}return r.prototype.step=function(e,t){if(this._inited||(this._startTime=e+this._delay,this._inited=!0),this._paused){this._pausedTime+=t;return}var a=this._life,n=e-this._startTime-this._pausedTime,i=n/a;i<0&&(i=0),i=Math.min(i,1);var o=this.easingFunc,s=o?o(i):i;if(this.onframe(s),i===1)if(this.loop){var l=n%a;this._startTime=e-l,this._pausedTime=0,this.onrestart()}else return!0;return!1},r.prototype.pause=function(){this._paused=!0},r.prototype.resume=function(){this._paused=!1},r.prototype.setEasing=function(e){this.easing=e,this.easingFunc=K(e)?e:$o[e]||Cv(e)},r}(),v0=function(){function r(e){this.value=e}return r}(),i2=function(){function r(){this._len=0}return r.prototype.insert=function(e){var t=new v0(e);return this.insertEntry(t),t},r.prototype.insertEntry=function(e){this.head?(this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e):this.head=this.tail=e,this._len++},r.prototype.remove=function(e){var t=e.prev,a=e.next;t?t.next=a:this.head=a,a?a.prev=t:this.tail=t,e.next=e.prev=null,this._len--},r.prototype.len=function(){return this._len},r.prototype.clear=function(){this.head=this.tail=null,this._len=0},r}(),Ko=function(){function r(e){this._list=new i2,this._maxSize=10,this._map={},this._maxSize=e}return r.prototype.put=function(e,t){var a=this._list,n=this._map,i=null;if(n[e]==null){var o=a.len(),s=this._lastRemovedEntry;if(o>=this._maxSize&&o>0){var l=a.head;a.remove(l),delete n[l.key],i=l.value,this._lastRemovedEntry=l}s?s.value=t:s=new v0(t),s.key=e,a.insertEntry(s),n[e]=s}return i},r.prototype.get=function(e){var t=this._map[e],a=this._list;if(t!=null)return t!==a.tail&&(a.remove(t),a.insertEntry(t)),t.value},r.prototype.clear=function(){this._list.clear(),this._map={}},r.prototype.len=function(){return this._list.len()},r}(),c0={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function _r(r){return r=Math.round(r),r<0?0:r>255?255:r}function o2(r){return r=Math.round(r),r<0?0:r>360?360:r}function jo(r){return r<0?0:r>1?1:r}function Av(r){var e=r;return e.length&&e.charAt(e.length-1)==="%"?_r(parseFloat(e)/100*255):_r(parseInt(e,10))}function gn(r){var e=r;return e.length&&e.charAt(e.length-1)==="%"?jo(parseFloat(e)/100):jo(parseFloat(e))}function Dv(r,e,t){return t<0?t+=1:t>1&&(t-=1),t*6<1?r+(e-r)*t*6:t*2<1?e:t*3<2?r+(e-r)*(2/3-t)*6:r}function Ea(r,e,t){return r+(e-r)*t}function tr(r,e,t,a,n){return r[0]=e,r[1]=t,r[2]=a,r[3]=n,r}function Mv(r,e){return r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=e[3],r}var p0=new Ko(20),lu=null;function Ci(r,e){lu&&Mv(lu,e),lu=p0.put(r,lu||e.slice())}function Ae(r,e){if(!!r){e=e||[];var t=p0.get(r);if(t)return Mv(e,t);r=r+"";var a=r.replace(/ /g,"").toLowerCase();if(a in c0)return Mv(e,c0[a]),Ci(r,e),e;var n=a.length;if(a.charAt(0)==="#"){if(n===4||n===5){var i=parseInt(a.slice(1,4),16);if(!(i>=0&&i<=4095)){tr(e,0,0,0,1);return}return tr(e,(i&3840)>>4|(i&3840)>>8,i&240|(i&240)>>4,i&15|(i&15)<<4,n===5?parseInt(a.slice(4),16)/15:1),Ci(r,e),e}else if(n===7||n===9){var i=parseInt(a.slice(1,7),16);if(!(i>=0&&i<=16777215)){tr(e,0,0,0,1);return}return tr(e,(i&16711680)>>16,(i&65280)>>8,i&255,n===9?parseInt(a.slice(7),16)/255:1),Ci(r,e),e}return}var o=a.indexOf("("),s=a.indexOf(")");if(o!==-1&&s+1===n){var l=a.substr(0,o),u=a.substr(o+1,s-(o+1)).split(","),f=1;switch(l){case"rgba":if(u.length!==4)return u.length===3?tr(e,+u[0],+u[1],+u[2],1):tr(e,0,0,0,1);f=gn(u.pop());case"rgb":if(u.length>=3)return tr(e,Av(u[0]),Av(u[1]),Av(u[2]),u.length===3?f:gn(u[3])),Ci(r,e),e;tr(e,0,0,0,1);return;case"hsla":if(u.length!==4){tr(e,0,0,0,1);return}return u[3]=gn(u[3]),Iv(u,e),Ci(r,e),e;case"hsl":if(u.length!==3){tr(e,0,0,0,1);return}return Iv(u,e),Ci(r,e),e;default:return}}tr(e,0,0,0,1)}}function Iv(r,e){var t=(parseFloat(r[0])%360+360)%360/360,a=gn(r[1]),n=gn(r[2]),i=n<=.5?n*(a+1):n+a-n*a,o=n*2-i;return e=e||[],tr(e,_r(Dv(o,i,t+1/3)*255),_r(Dv(o,i,t)*255),_r(Dv(o,i,t-1/3)*255),1),r.length===4&&(e[3]=r[3]),e}function s2(r){if(!!r){var e=r[0]/255,t=r[1]/255,a=r[2]/255,n=Math.min(e,t,a),i=Math.max(e,t,a),o=i-n,s=(i+n)/2,l,u;if(o===0)l=0,u=0;else{s<.5?u=o/(i+n):u=o/(2-i-n);var f=((i-e)/6+o/2)/o,h=((i-t)/6+o/2)/o,v=((i-a)/6+o/2)/o;e===i?l=v-h:t===i?l=1/3+f-v:a===i&&(l=2/3+h-f),l<0&&(l+=1),l>1&&(l-=1)}var c=[l*360,u,s];return r[3]!=null&&c.push(r[3]),c}}function uu(r,e){var t=Ae(r);if(t){for(var a=0;a<3;a++)e<0?t[a]=t[a]*(1-e)|0:t[a]=(255-t[a])*e+t[a]|0,t[a]>255?t[a]=255:t[a]<0&&(t[a]=0);return Sr(t,t.length===4?"rgba":"rgb")}}function l2(r){var e=Ae(r);if(e)return((1<<24)+(e[0]<<16)+(e[1]<<8)+ +e[2]).toString(16).slice(1)}function Qo(r,e,t){if(!(!(e&&e.length)||!(r>=0&&r<=1))){t=t||[];var a=r*(e.length-1),n=Math.floor(a),i=Math.ceil(a),o=e[n],s=e[i],l=a-n;return t[0]=_r(Ea(o[0],s[0],l)),t[1]=_r(Ea(o[1],s[1],l)),t[2]=_r(Ea(o[2],s[2],l)),t[3]=jo(Ea(o[3],s[3],l)),t}}var u2=Qo;function Lv(r,e,t){if(!(!(e&&e.length)||!(r>=0&&r<=1))){var a=r*(e.length-1),n=Math.floor(a),i=Math.ceil(a),o=Ae(e[n]),s=Ae(e[i]),l=a-n,u=Sr([_r(Ea(o[0],s[0],l)),_r(Ea(o[1],s[1],l)),_r(Ea(o[2],s[2],l)),jo(Ea(o[3],s[3],l))],"rgba");return t?{color:u,leftIndex:n,rightIndex:i,value:a}:u}}var f2=Lv;function Ai(r,e,t,a){var n=Ae(r);if(r)return n=s2(n),e!=null&&(n[0]=o2(e)),t!=null&&(n[1]=gn(t)),a!=null&&(n[2]=gn(a)),Sr(Iv(n),"rgba")}function Jo(r,e){var t=Ae(r);if(t&&e!=null)return t[3]=jo(e),Sr(t,"rgba")}function Sr(r,e){if(!(!r||!r.length)){var t=r[0]+","+r[1]+","+r[2];return(e==="rgba"||e==="hsva"||e==="hsla")&&(t+=","+r[3]),e+"("+t+")"}}function ts(r,e){var t=Ae(r);return t?(.299*t[0]+.587*t[1]+.114*t[2])*t[3]/255+(1-t[3])*e:0}function h2(){return Sr([Math.round(Math.random()*255),Math.round(Math.random()*255),Math.round(Math.random()*255)],"rgb")}var v2=Object.freeze({__proto__:null,parse:Ae,lift:uu,toHex:l2,fastLerp:Qo,fastMapToColor:u2,lerp:Lv,mapToColor:f2,modifyHSL:Ai,modifyAlpha:Jo,stringify:Sr,lum:ts,random:h2}),fu=Math.round;function es(r){var e;if(!r||r==="transparent")r="none";else if(typeof r=="string"&&r.indexOf("rgba")>-1){var t=Ae(r);t&&(r="rgb("+t[0]+","+t[1]+","+t[2]+")",e=t[3])}return{color:r,opacity:e==null?1:e}}var d0=1e-4;function ka(r){return r-d0}function hu(r){return fu(r*1e3)/1e3}function Pv(r){return fu(r*1e4)/1e4}function c2(r){return"matrix("+hu(r[0])+","+hu(r[1])+","+hu(r[2])+","+hu(r[3])+","+Pv(r[4])+","+Pv(r[5])+")"}var p2={left:"start",right:"end",center:"middle",middle:"middle"};function d2(r,e,t){return t==="top"?r+=e/2:t==="bottom"&&(r-=e/2),r}function g2(r){return r&&(r.shadowBlur||r.shadowOffsetX||r.shadowOffsetY)}function y2(r){var e=r.style,t=r.getGlobalScale();return[e.shadowColor,(e.shadowBlur||0).toFixed(2),(e.shadowOffsetX||0).toFixed(2),(e.shadowOffsetY||0).toFixed(2),t[0],t[1]].join(",")}function g0(r){return r&&!!r.image}function m2(r){return r&&!!r.svgElement}function Rv(r){return g0(r)||m2(r)}function y0(r){return r.type==="linear"}function m0(r){return r.type==="radial"}function _0(r){return r&&(r.type==="linear"||r.type==="radial")}function vu(r){return"url(#"+r+")"}function S0(r){var e=r.getGlobalScale(),t=Math.max(e[0],e[1]);return Math.max(Math.ceil(Math.log(t)/Math.log(10)),1)}function x0(r){var e=r.x||0,t=r.y||0,a=(r.rotation||0)*Vo,n=lt(r.scaleX,1),i=lt(r.scaleY,1),o=r.skewX||0,s=r.skewY||0,l=[];return(e||t)&&l.push("translate("+e+"px,"+t+"px)"),a&&l.push("rotate("+a+")"),(n!==1||i!==1)&&l.push("scale("+n+","+i+")"),(o||s)&&l.push("skew("+fu(o*Vo)+"deg, "+fu(s*Vo)+"deg)"),l.join(" ")}var _2=function(){return _t.hasGlobalWindow&&K(window.btoa)?function(r){return window.btoa(unescape(encodeURIComponent(r)))}:typeof Buffer!="undefined"?function(r){return Buffer.from(r).toString("base64")}:function(r){return null}}(),Ev=Array.prototype.slice;function oa(r,e,t){return(e-r)*t+r}function kv(r,e,t,a){for(var n=e.length,i=0;ia?e:r,i=Math.min(t,a),o=n[i-1]||{color:[0,0,0,0],offset:0},s=i;so;if(s)a.length=o;else for(var l=i;l=1},r.prototype.getAdditiveTrack=function(){return this._additiveTrack},r.prototype.addKeyframe=function(e,t,a){this._needsSort=!0;var n=this.keyframes,i=n.length,o=!1,s=T0,l=t;if(fe(t)){var u=w2(t);s=u,(u===1&&!Tt(t[0])||u===2&&!Tt(t[0][0]))&&(o=!0)}else if(Tt(t)&&!Si(t))s=du;else if(U(t))if(!isNaN(+t))s=du;else{var f=Ae(t);f&&(l=f,s=as)}else if(ko(t)){var h=B({},l);h.colorStops=G(t.colorStops,function(c){return{offset:c.offset,color:Ae(c.color)}}),y0(t)?s=Ov:m0(t)&&(s=Nv),l=h}i===0?this.valType=s:(s!==this.valType||s===T0)&&(o=!0),this.discrete=this.discrete||o;var v={time:e,value:l,rawValue:t,percent:0};return a&&(v.easing=a,v.easingFunc=K(a)?a:$o[a]||Cv(a)),n.push(v),v},r.prototype.prepare=function(e,t){var a=this.keyframes;this._needsSort&&a.sort(function(d,g){return d.time-g.time});for(var n=this.valType,i=a.length,o=a[i-1],s=this.discrete,l=yu(n),u=C0(n),f=0;f=0&&!(o[f].percent<=t);f--);f=v(f,s-2)}else{for(f=h;ft);f++);f=v(f-1,s-2)}p=o[f+1],c=o[f]}if(!!(c&&p)){this._lastFr=f,this._lastFrP=t;var g=p.percent-c.percent,y=g===0?1:v((t-c.percent)/g,1);p.easingFunc&&(y=p.easingFunc(y));var m=a?this._additiveValue:u?ns:e[l];if((yu(i)||u)&&!m&&(m=this._additiveValue=[]),this.discrete)e[l]=y<1?c.rawValue:p.rawValue;else if(yu(i))i===gu?kv(m,c[n],p[n],y):S2(m,c[n],p[n],y);else if(C0(i)){var _=c[n],S=p[n],b=i===Ov;e[l]={type:b?"linear":"radial",x:oa(_.x,S.x,y),y:oa(_.y,S.y,y),colorStops:G(_.colorStops,function(w,T){var C=S.colorStops[T];return{offset:oa(w.offset,C.offset,y),color:pu(kv([],w.color,C.color,y))}}),global:S.global},b?(e[l].x2=oa(_.x2,S.x2,y),e[l].y2=oa(_.y2,S.y2,y)):e[l].r=oa(_.r,S.r,y)}else if(u)kv(m,c[n],p[n],y),a||(e[l]=pu(m));else{var x=oa(c[n],p[n],y);a?this._additiveValue=x:e[l]=x}a&&this._addToTarget(e)}}},r.prototype._addToTarget=function(e){var t=this.valType,a=this.propName,n=this._additiveValue;t===du?e[a]=e[a]+n:t===as?(Ae(e[a],ns),cu(ns,ns,n,1),e[a]=pu(ns)):t===gu?cu(e[a],e[a],n,1):t===w0&&b0(e[a],e[a],n,1)},r}(),Bv=function(){function r(e,t,a,n){if(this._tracks={},this._trackKeys=[],this._maxTime=0,this._started=0,this._clip=null,this._target=e,this._loop=t,t&&n){Xl("Can' use additive animation on looped animation.");return}this._additiveAnimators=n,this._allowDiscrete=a}return r.prototype.getMaxTime=function(){return this._maxTime},r.prototype.getDelay=function(){return this._delay},r.prototype.getLoop=function(){return this._loop},r.prototype.getTarget=function(){return this._target},r.prototype.changeTarget=function(e){this._target=e},r.prototype.when=function(e,t,a){return this.whenWithKeys(e,t,St(t),a)},r.prototype.whenWithKeys=function(e,t,a,n){for(var i=this._tracks,o=0;o0&&l.addKeyframe(0,rs(u),n),this._trackKeys.push(s)}l.addKeyframe(e,rs(t[s]),n)}return this._maxTime=Math.max(this._maxTime,e),this},r.prototype.pause=function(){this._clip.pause(),this._paused=!0},r.prototype.resume=function(){this._clip.resume(),this._paused=!1},r.prototype.isPaused=function(){return!!this._paused},r.prototype.duration=function(e){return this._maxTime=e,this._force=!0,this},r.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var e=this._doneCbs;if(e)for(var t=e.length,a=0;a0)){this._started=1;for(var t=this,a=[],n=this._maxTime||0,i=0;i1){var s=o.pop();i.addKeyframe(s.time,e[n]),i.prepare(this._maxTime,i.getAdditiveTrack())}}}},r}();function Di(){return new Date().getTime()}var C2=function(r){zt(e,r);function e(t){var a=r.call(this)||this;return a._running=!1,a._time=0,a._pausedTime=0,a._pauseStart=0,a._paused=!1,t=t||{},a.stage=t.stage||{},a}return e.prototype.addClip=function(t){t.animation&&this.removeClip(t),this._head?(this._tail.next=t,t.prev=this._tail,t.next=null,this._tail=t):this._head=this._tail=t,t.animation=this},e.prototype.addAnimator=function(t){t.animation=this;var a=t.getClip();a&&this.addClip(a)},e.prototype.removeClip=function(t){if(!!t.animation){var a=t.prev,n=t.next;a?a.next=n:this._head=n,n?n.prev=a:this._tail=a,t.next=t.prev=t.animation=null}},e.prototype.removeAnimator=function(t){var a=t.getClip();a&&this.removeClip(a),t.animation=null},e.prototype.update=function(t){for(var a=Di()-this._pausedTime,n=a-this._time,i=this._head;i;){var o=i.next,s=i.step(a,n);s&&(i.ondestroy(),this.removeClip(i)),i=o}this._time=a,t||(this.trigger("frame",n),this.stage.update&&this.stage.update())},e.prototype._startLoop=function(){var t=this;this._running=!0;function a(){t._running&&(wv(a),!t._paused&&t.update())}wv(a)},e.prototype.start=function(){this._running||(this._time=Di(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Di(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Di()-this._pauseStart,this._paused=!1)},e.prototype.clear=function(){for(var t=this._head;t;){var a=t.next;t.prev=t.next=t.animation=null,t=a}this._head=this._tail=null},e.prototype.isFinished=function(){return this._head==null},e.prototype.animate=function(t,a){a=a||{},this.start();var n=new Bv(t,a.loop);return this.addAnimator(n),n},e}(je),A2=300,Vv=_t.domSupported,zv=function(){var r=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],e=["touchstart","touchend","touchmove"],t={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},a=G(r,function(n){var i=n.replace("mouse","pointer");return t.hasOwnProperty(i)?i:n});return{mouse:r,touch:e,pointer:a}}(),A0={mouse:["mousemove","mouseup"],pointer:["pointermove","pointerup"]},D0=!1;function Gv(r){var e=r.pointerType;return e==="pen"||e==="touch"}function D2(r){r.touching=!0,r.touchTimer!=null&&(clearTimeout(r.touchTimer),r.touchTimer=null),r.touchTimer=setTimeout(function(){r.touching=!1,r.touchTimer=null},700)}function Fv(r){r&&(r.zrByTouch=!0)}function M2(r,e){return Qe(r.dom,new I2(r,e),!0)}function M0(r,e){for(var t=e,a=!1;t&&t.nodeType!==9&&!(a=t.domBelongToZr||t!==e&&t===r.painterRoot);)t=t.parentNode;return a}var I2=function(){function r(e,t){this.stopPropagation=Zt,this.stopImmediatePropagation=Zt,this.preventDefault=Zt,this.type=t.type,this.target=this.currentTarget=e.dom,this.pointerType=t.pointerType,this.clientX=t.clientX,this.clientY=t.clientY}return r}(),xr={mousedown:function(r){r=Qe(this.dom,r),this.__mayPointerCapture=[r.zrX,r.zrY],this.trigger("mousedown",r)},mousemove:function(r){r=Qe(this.dom,r);var e=this.__mayPointerCapture;e&&(r.zrX!==e[0]||r.zrY!==e[1])&&this.__togglePointerCapture(!0),this.trigger("mousemove",r)},mouseup:function(r){r=Qe(this.dom,r),this.__togglePointerCapture(!1),this.trigger("mouseup",r)},mouseout:function(r){r=Qe(this.dom,r);var e=r.toElement||r.relatedTarget;M0(this,e)||(this.__pointerCapturing&&(r.zrEventControl="no_globalout"),this.trigger("mouseout",r))},wheel:function(r){D0=!0,r=Qe(this.dom,r),this.trigger("mousewheel",r)},mousewheel:function(r){D0||(r=Qe(this.dom,r),this.trigger("mousewheel",r))},touchstart:function(r){r=Qe(this.dom,r),Fv(r),this.__lastTouchMoment=new Date,this.handler.processGesture(r,"start"),xr.mousemove.call(this,r),xr.mousedown.call(this,r)},touchmove:function(r){r=Qe(this.dom,r),Fv(r),this.handler.processGesture(r,"change"),xr.mousemove.call(this,r)},touchend:function(r){r=Qe(this.dom,r),Fv(r),this.handler.processGesture(r,"end"),xr.mouseup.call(this,r),+new Date-+this.__lastTouchMomentR0||r<-R0}var mn=[],Mi=[],Zv=Ge(),$v=Math.abs,sa=function(){function r(){}return r.prototype.getLocalTransform=function(e){return r.getLocalTransform(this,e)},r.prototype.setPosition=function(e){this.x=e[0],this.y=e[1]},r.prototype.setScale=function(e){this.scaleX=e[0],this.scaleY=e[1]},r.prototype.setSkew=function(e){this.skewX=e[0],this.skewY=e[1]},r.prototype.setOrigin=function(e){this.originX=e[0],this.originY=e[1]},r.prototype.needLocalTransform=function(){return yn(this.rotation)||yn(this.x)||yn(this.y)||yn(this.scaleX-1)||yn(this.scaleY-1)||yn(this.skewX)||yn(this.skewY)},r.prototype.updateTransform=function(){var e=this.parent&&this.parent.transform,t=this.needLocalTransform(),a=this.transform;if(!(t||e)){a&&P0(a);return}a=a||Ge(),t?this.getLocalTransform(a):P0(a),e&&(t?Or(a,e,a):Jl(a,e)),this.transform=a,this._resolveGlobalScaleRatio(a)},r.prototype._resolveGlobalScaleRatio=function(e){var t=this.globalScaleRatio;if(t!=null&&t!==1){this.getGlobalScale(mn);var a=mn[0]<0?-1:1,n=mn[1]<0?-1:1,i=((mn[0]-a)*t+a)/mn[0]||0,o=((mn[1]-n)*t+n)/mn[1]||0;e[0]*=i,e[1]*=i,e[2]*=o,e[3]*=o}this.invTransform=this.invTransform||Ge(),hn(this.invTransform,e)},r.prototype.getComputedTransform=function(){for(var e=this,t=[];e;)t.push(e),e=e.parent;for(;e=t.pop();)e.updateTransform();return this.transform},r.prototype.setLocalTransform=function(e){if(!!e){var t=e[0]*e[0]+e[1]*e[1],a=e[2]*e[2]+e[3]*e[3],n=Math.atan2(e[1],e[0]),i=Math.PI/2+n-Math.atan2(e[3],e[2]);a=Math.sqrt(a)*Math.cos(i),t=Math.sqrt(t),this.skewX=i,this.skewY=0,this.rotation=-n,this.x=+e[4],this.y=+e[5],this.scaleX=t,this.scaleY=a,this.originX=0,this.originY=0}},r.prototype.decomposeTransform=function(){if(!!this.transform){var e=this.parent,t=this.transform;e&&e.transform&&(Or(Mi,e.invTransform,t),t=Mi);var a=this.originX,n=this.originY;(a||n)&&(Zv[4]=a,Zv[5]=n,Or(Mi,t,Zv),Mi[4]-=a,Mi[5]-=n,t=Mi),this.setLocalTransform(t)}},r.prototype.getGlobalScale=function(e){var t=this.transform;return e=e||[],t?(e[0]=Math.sqrt(t[0]*t[0]+t[1]*t[1]),e[1]=Math.sqrt(t[2]*t[2]+t[3]*t[3]),t[0]<0&&(e[0]=-e[0]),t[3]<0&&(e[1]=-e[1]),e):(e[0]=1,e[1]=1,e)},r.prototype.transformCoordToLocal=function(e,t){var a=[e,t],n=this.invTransform;return n&&le(a,a,n),a},r.prototype.transformCoordToGlobal=function(e,t){var a=[e,t],n=this.transform;return n&&le(a,a,n),a},r.prototype.getLineScale=function(){var e=this.transform;return e&&$v(e[0]-1)>1e-10&&$v(e[3]-1)>1e-10?Math.sqrt($v(e[0]*e[3]-e[2]*e[1])):1},r.prototype.copyTransform=function(e){E0(this,e)},r.getLocalTransform=function(e,t){t=t||[];var a=e.originX||0,n=e.originY||0,i=e.scaleX,o=e.scaleY,s=e.anchorX,l=e.anchorY,u=e.rotation||0,f=e.x,h=e.y,v=e.skewX?Math.tan(e.skewX):0,c=e.skewY?Math.tan(-e.skewY):0;if(a||n||s||l){var p=a+s,d=n+l;t[4]=-p*i-v*d*o,t[5]=-d*o-c*p*i}else t[4]=t[5]=0;return t[0]=i,t[3]=o,t[1]=c*i,t[2]=v*o,u&&Ia(t,t,u),t[4]+=a+f,t[5]+=n+h,t},r.initDefaultProps=function(){var e=r.prototype;e.scaleX=e.scaleY=e.globalScaleRatio=1,e.x=e.y=e.originX=e.originY=e.skewX=e.skewY=e.rotation=e.anchorX=e.anchorY=0}(),r}(),la=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function E0(r,e){for(var t=0;t=0?parseFloat(r)/100*e:parseFloat(r):r}function xu(r,e,t){var a=e.position||"inside",n=e.distance!=null?e.distance:5,i=t.height,o=t.width,s=i/2,l=t.x,u=t.y,f="left",h="top";if(a instanceof Array)l+=br(a[0],t.width),u+=br(a[1],t.height),f=null,h=null;else switch(a){case"left":l-=n,u+=s,f="right",h="middle";break;case"right":l+=n+o,u+=s,h="middle";break;case"top":l+=o/2,u-=n,f="center",h="bottom";break;case"bottom":l+=o/2,u+=i+n,f="center";break;case"inside":l+=o/2,u+=s,f="center",h="middle";break;case"insideLeft":l+=n,u+=s,h="middle";break;case"insideRight":l+=o-n,u+=s,f="right",h="middle";break;case"insideTop":l+=o/2,u+=n,f="center";break;case"insideBottom":l+=o/2,u+=i-n,f="center",h="bottom";break;case"insideTopLeft":l+=n,u+=n;break;case"insideTopRight":l+=o-n,u+=n,f="right";break;case"insideBottomLeft":l+=n,u+=i-n,h="bottom";break;case"insideBottomRight":l+=o-n,u+=i-n,f="right",h="bottom";break}return r=r||{},r.x=l,r.y=u,r.align=f,r.verticalAlign=h,r}var qv="__zr_normal__",Kv=la.concat(["ignore"]),k2=qe(la,function(r,e){return r[e]=!0,r},{ignore:!1}),Li={},O2=new ft(0,0,0,0),bu=function(){function r(e){this.id=nv(),this.animators=[],this.currentStates=[],this.states={},this._init(e)}return r.prototype._init=function(e){this.attr(e)},r.prototype.drift=function(e,t,a){switch(this.draggable){case"horizontal":t=0;break;case"vertical":e=0;break}var n=this.transform;n||(n=this.transform=[1,0,0,1,0,0]),n[4]+=e,n[5]+=t,this.decomposeTransform(),this.markRedraw()},r.prototype.beforeUpdate=function(){},r.prototype.afterUpdate=function(){},r.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},r.prototype.updateInnerText=function(e){var t=this._textContent;if(t&&(!t.ignore||e)){this.textConfig||(this.textConfig={});var a=this.textConfig,n=a.local,i=t.innerTransformable,o=void 0,s=void 0,l=!1;i.parent=n?this:null;var u=!1;if(i.copyTransform(t),a.position!=null){var f=O2;a.layoutRect?f.copy(a.layoutRect):f.copy(this.getBoundingRect()),n||f.applyTransform(this.transform),this.calculateTextPosition?this.calculateTextPosition(Li,a,f):xu(Li,a,f),i.x=Li.x,i.y=Li.y,o=Li.align,s=Li.verticalAlign;var h=a.origin;if(h&&a.rotation!=null){var v=void 0,c=void 0;h==="center"?(v=f.width*.5,c=f.height*.5):(v=br(h[0],f.width),c=br(h[1],f.height)),u=!0,i.originX=-i.x+v+(n?0:f.x),i.originY=-i.y+c+(n?0:f.y)}}a.rotation!=null&&(i.rotation=a.rotation);var p=a.offset;p&&(i.x+=p[0],i.y+=p[1],u||(i.originX=-p[0],i.originY=-p[1]));var d=a.inside==null?typeof a.position=="string"&&a.position.indexOf("inside")>=0:a.inside,g=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={}),y=void 0,m=void 0,_=void 0;d&&this.canBeInsideText()?(y=a.insideFill,m=a.insideStroke,(y==null||y==="auto")&&(y=this.getInsideTextFill()),(m==null||m==="auto")&&(m=this.getInsideTextStroke(y),_=!0)):(y=a.outsideFill,m=a.outsideStroke,(y==null||y==="auto")&&(y=this.getOutsideFill()),(m==null||m==="auto")&&(m=this.getOutsideStroke(y),_=!0)),y=y||"#000",(y!==g.fill||m!==g.stroke||_!==g.autoStroke||o!==g.align||s!==g.verticalAlign)&&(l=!0,g.fill=y,g.stroke=m,g.autoStroke=_,g.align=o,g.verticalAlign=s,t.setDefaultTextStyle(g)),t.__dirty|=Fe,l&&t.dirtyStyle(!0)}},r.prototype.canBeInsideText=function(){return!0},r.prototype.getInsideTextFill=function(){return"#fff"},r.prototype.getInsideTextStroke=function(e){return"#000"},r.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Xv:Yv},r.prototype.getOutsideStroke=function(e){var t=this.__zr&&this.__zr.getBackgroundColor(),a=typeof t=="string"&&Ae(t);a||(a=[255,255,255,1]);for(var n=a[3],i=this.__zr.isDarkMode(),o=0;o<3;o++)a[o]=a[o]*n+(i?0:255)*(1-n);return a[3]=1,Sr(a,"rgba")},r.prototype.traverse=function(e,t){},r.prototype.attrKV=function(e,t){e==="textConfig"?this.setTextConfig(t):e==="textContent"?this.setTextContent(t):e==="clipPath"?this.setClipPath(t):e==="extra"?(this.extra=this.extra||{},B(this.extra,t)):this[e]=t},r.prototype.hide=function(){this.ignore=!0,this.markRedraw()},r.prototype.show=function(){this.ignore=!1,this.markRedraw()},r.prototype.attr=function(e,t){if(typeof e=="string")this.attrKV(e,t);else if(J(e))for(var a=e,n=St(a),i=0;i0},r.prototype.getState=function(e){return this.states[e]},r.prototype.ensureState=function(e){var t=this.states;return t[e]||(t[e]={}),t[e]},r.prototype.clearStates=function(e){this.useState(qv,!1,e)},r.prototype.useState=function(e,t,a,n){var i=e===qv,o=this.hasState();if(!(!o&&i)){var s=this.currentStates,l=this.stateTransition;if(!(vt(s,e)>=0&&(t||s.length===1))){var u;if(this.stateProxy&&!i&&(u=this.stateProxy(e)),u||(u=this.states&&this.states[e]),!u&&!i){Xl("State "+e+" not exists.");return}i||this.saveCurrentToNormalState(u);var f=!!(u&&u.hoverLayer||n);f&&this._toggleHoverLayerFlag(!0),this._applyStateObj(e,u,this._normalState,t,!a&&!this.__inHover&&l&&l.duration>0,l);var h=this._textContent,v=this._textGuide;return h&&h.useState(e,t,a,f),v&&v.useState(e,t,a,f),i?(this.currentStates=[],this._normalState={}):t?this.currentStates.push(e):this.currentStates=[e],this._updateAnimationTargets(),this.markRedraw(),!f&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=~Fe),u}}},r.prototype.useStates=function(e,t,a){if(!e.length)this.clearStates();else{var n=[],i=this.currentStates,o=e.length,s=o===i.length;if(s){for(var l=0;l0,p);var d=this._textContent,g=this._textGuide;d&&d.useStates(e,t,v),g&&g.useStates(e,t,v),this._updateAnimationTargets(),this.currentStates=e.slice(),this.markRedraw(),!v&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=~Fe)}},r.prototype._updateAnimationTargets=function(){for(var e=0;e=0){var a=this.currentStates.slice();a.splice(t,1),this.useStates(a)}},r.prototype.replaceState=function(e,t,a){var n=this.currentStates.slice(),i=vt(n,e),o=vt(n,t)>=0;i>=0?o?n.splice(i,1):n[i]=t:a&&!o&&n.push(t),this.useStates(n)},r.prototype.toggleState=function(e,t){t?this.useState(e,!0):this.removeState(e)},r.prototype._mergeStates=function(e){for(var t={},a,n=0;n=0&&i.splice(o,1)}),this.animators.push(e),a&&a.animation.addAnimator(e),a&&a.wakeUp()},r.prototype.updateDuringAnimation=function(e){this.markRedraw()},r.prototype.stopAnimation=function(e,t){for(var a=this.animators,n=a.length,i=[],o=0;o0&&t.during&&i[0].during(function(p,d){t.during(d)});for(var v=0;v0||n.force&&!o.length){var T=void 0,C=void 0,D=void 0;if(s){C={},v&&(T={});for(var S=0;S<_;S++){var y=d[S];C[y]=t[y],v?T[y]=a[y]:t[y]=a[y]}}else if(v){D={};for(var S=0;S<_;S++){var y=d[S];D[y]=rs(t[y]),B2(t,a,y)}}var b=new Bv(t,!1,!1,h?Lt(p,function(I){return I.targetName===e}):null);b.targetName=e,n.scope&&(b.scope=n.scope),v&&T&&b.whenWithKeys(0,T,d),D&&b.whenWithKeys(0,D,d),b.whenWithKeys(u==null?500:u,s?C:a,d).delay(f||0),r.addAnimator(b,e),o.push(b)}}var rt=function(r){zt(e,r);function e(t){var a=r.call(this)||this;return a.isGroup=!0,a._children=[],a.attr(t),a}return e.prototype.childrenRef=function(){return this._children},e.prototype.children=function(){return this._children.slice()},e.prototype.childAt=function(t){return this._children[t]},e.prototype.childOfName=function(t){for(var a=this._children,n=0;n=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,a){var n=vt(this._children,t);return n>=0&&this.replaceAt(a,n),this},e.prototype.replaceAt=function(t,a){var n=this._children,i=n[a];if(t&&t!==this&&t.parent!==this&&t!==i){n[a]=t,i.parent=null;var o=this.__zr;o&&i.removeSelfFromZr(o),this._doAdd(t)}return this},e.prototype._doAdd=function(t){t.parent&&t.parent.remove(t),t.parent=this;var a=this.__zr;a&&a!==t.__zr&&t.addSelfToZr(a),a&&a.refresh()},e.prototype.remove=function(t){var a=this.__zr,n=this._children,i=vt(n,t);return i<0?this:(n.splice(i,1),t.parent=null,a&&t.removeSelfFromZr(a),a&&a.refresh(),this)},e.prototype.removeAll=function(){for(var t=this._children,a=this.__zr,n=0;n0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},r.prototype.setSleepAfterStill=function(e){this._sleepAfterStill=e},r.prototype.wakeUp=function(){this.animation.start(),this._stillFrameAccum=0},r.prototype.refreshHover=function(){this._needsRefreshHover=!0},r.prototype.refreshHoverImmediately=function(){this._needsRefreshHover=!1,this.painter.refreshHover&&this.painter.getType()==="canvas"&&this.painter.refreshHover()},r.prototype.resize=function(e){e=e||{},this.painter.resize(e.width,e.height),this.handler.resize()},r.prototype.clearAnimation=function(){this.animation.clear()},r.prototype.getWidth=function(){return this.painter.getWidth()},r.prototype.getHeight=function(){return this.painter.getHeight()},r.prototype.setCursorStyle=function(e){this.handler.setCursorStyle(e)},r.prototype.findHover=function(e,t){return this.handler.findHover(e,t)},r.prototype.on=function(e,t,a){return this.handler.on(e,t,a),this},r.prototype.off=function(e,t){this.handler.off(e,t)},r.prototype.trigger=function(e,t){this.handler.trigger(e,t)},r.prototype.clear=function(){for(var e=this.storage.getRoots(),t=0;t0){if(r<=n)return o;if(r>=i)return s}else{if(r>=n)return o;if(r<=i)return s}else{if(r===n)return o;if(r===i)return s}return(r-n)/l*u+o}function H(r,e){switch(r){case"center":case"middle":r="50%";break;case"left":case"top":r="0%";break;case"right":case"bottom":r="100%";break}return U(r)?$2(r).match(/%$/)?parseFloat(r)/100*e:parseFloat(r):r==null?NaN:+r}function Wt(r,e,t){return e==null&&(e=10),e=Math.min(Math.max(0,e),z0),r=(+r).toFixed(e),t?r:+r}function We(r){return r.sort(function(e,t){return e-t}),r}function wr(r){if(r=+r,isNaN(r))return 0;if(r>1e-14){for(var e=1,t=0;t<15;t++,e*=10)if(Math.round(r*e)/e===r)return t}return G0(r)}function G0(r){var e=r.toString().toLowerCase(),t=e.indexOf("e"),a=t>0?+e.slice(t+1):0,n=t>0?t:e.length,i=e.indexOf("."),o=i<0?0:n-1-i;return Math.max(0,o-a)}function tc(r,e){var t=Math.log,a=Math.LN10,n=Math.floor(t(r[1]-r[0])/a),i=Math.round(t(Math.abs(e[1]-e[0]))/a),o=Math.min(Math.max(-n+i,0),20);return isFinite(o)?o:20}function q2(r,e,t){if(!r[e])return 0;var a=F0(r,t);return a[e]||0}function F0(r,e){var t=qe(r,function(c,p){return c+(isNaN(p)?0:p)},0);if(t===0)return[];for(var a=Math.pow(10,e),n=G(r,function(c){return(isNaN(c)?0:c)/t*a*100}),i=a*100,o=G(n,function(c){return Math.floor(c)}),s=qe(o,function(c,p){return c+p},0),l=G(n,function(c,p){return c-o[p]});su&&(u=l[h],f=h);++o[f],l[f]=0,++s}return G(o,function(c){return c/a})}function K2(r,e){var t=Math.max(wr(r),wr(e)),a=r+e;return t>z0?a:Wt(a,t)}var ec=9007199254740991;function rc(r){var e=Math.PI*2;return(r%e+e)%e}function ss(r){return r>-V0&&r=10&&e++,e}function ac(r,e){var t=Tu(r),a=Math.pow(10,t),n=r/a,i;return e?n<1.5?i=1:n<2.5?i=2:n<4?i=3:n<7?i=5:i=10:n<1?i=1:n<2?i=2:n<3?i=3:n<5?i=5:i=10,r=i*a,t>=-20?+r.toFixed(t<0?-t:0):r}function Cu(r,e){var t=(r.length-1)*e+1,a=Math.floor(t),n=+r[a-1],i=t-a;return i?n+i*(r[a]-n):n}function nc(r){r.sort(function(l,u){return s(l,u,0)?-1:1});for(var e=-Infinity,t=1,a=0;a=0||i&&vt(i,l)<0)){var u=a.getShallow(l,e);u!=null&&(o[r[s][0]]=u)}}return o}}var TP=[["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]],CP=wn(TP),AP=function(){function r(){}return r.prototype.getAreaStyle=function(e,t){return CP(this,e,t)},r}(),fc=new Ko(50);function DP(r){if(typeof r=="string"){var e=fc.get(r);return e&&e.image}else return r}function hc(r,e,t,a,n){if(r)if(typeof r=="string"){if(e&&e.__zrImageSrc===r||!t)return e;var i=fc.get(r),o={hostEl:t,cb:a,cbPayload:n};return i?(e=i.image,!Du(e)&&i.pending.push(o)):(e=yr.loadImage(r,a_,a_),e.__zrImageSrc=r,fc.put(r,e.__cachedImgObj={image:e,pending:[o]})),e}else return r;else return e}function a_(){var r=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=o;l++)s-=o;var u=He(t,e);return u>s&&(t="",u=0),s=r-u,n.ellipsis=t,n.ellipsisWidth=u,n.contentWidth=s,n.containerWidth=r,n}function o_(r,e){var t=e.containerWidth,a=e.font,n=e.contentWidth;if(!t)return"";var i=He(r,a);if(i<=t)return r;for(var o=0;;o++){if(i<=n||o>=e.maxIterations){r+=e.ellipsis;break}var s=o===0?MP(r,n,e.ascCharWidth,e.cnCharWidth):i>0?Math.floor(r.length*n/i):0;r=r.substr(0,s),i=He(r,a)}return r===""&&(r=e.placeholder),r}function MP(r,e,t,a){for(var n=0,i=0,o=r.length;ic&&u){var p=Math.floor(c/s);h=h.slice(0,p)}if(r&&i&&f!=null)for(var d=i_(f,n,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),g=0;gs&&cc(t,r.substring(s,u),e,o),cc(t,l[2],e,o,l[1]),s=vc.lastIndex}sn){b>0?(m.tokens=m.tokens.slice(0,b),g(m,S,_),t.lines=t.lines.slice(0,y+1)):t.lines=t.lines.slice(0,y);break t}var I=w.width,L=I==null||I==="auto";if(typeof I=="string"&&I.charAt(I.length-1)==="%")x.percentWidth=I,f.push(x),x.contentWidth=He(x.text,D);else{if(L){var P=w.backgroundColor,R=P&&P.image;R&&(R=DP(R),Du(R)&&(x.width=Math.max(x.width,R.width*M/R.height)))}var E=p&&a!=null?a-S:null;E!=null&&E0&&p+a.accumWidth>a.width&&(f=e.split(` +`),u=!0),a.accumWidth=p}else{var d=l_(e,l,a.width,a.breakAll,a.accumWidth);a.accumWidth=d.accumWidth+c,h=d.linesWidths,f=d.lines}}else f=e.split(` +`);for(var g=0;g=33&&e<=383}var kP=qe(",&?/;] ".split(""),function(r,e){return r[e]=!0,r},{});function OP(r){return EP(r)?!!kP[r]:!0}function l_(r,e,t,a,n){for(var i=[],o=[],s="",l="",u=0,f=0,h=0;ht:n+f+c>t){f?(s||l)&&(p?(s||(s=l,l="",u=0,f=u),i.push(s),o.push(f-u),l+=v,u+=c,s="",f=u):(l&&(s+=l,l="",u=0),i.push(s),o.push(f),s=v,f=c)):p?(i.push(l),o.push(u),l=v,u=c):(i.push(v),o.push(c));continue}f+=c,p?(l+=v,u+=c):(l&&(s+=l,l="",u=0),s+=v)}return!i.length&&!s&&(s=r,l="",u=0),l&&(s+=l),s&&(i.push(s),o.push(f)),i.length===1&&(f+=n),{accumWidth:f,lines:i,linesWidths:o}}var pc="__zr_style_"+Math.round(Math.random()*10),Tn={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},Mu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};Tn[pc]=!0;var u_=["z","z2","invisible"],NP=["invisible"],er=function(r){zt(e,r);function e(t){return r.call(this,t)||this}return e.prototype._init=function(t){for(var a=St(t),n=0;n1e-4){s[0]=r-t,s[1]=e-a,l[0]=r+t,l[1]=e+a;return}if(Iu[0]=mc(n)*t+r,Iu[1]=yc(n)*a+e,Lu[0]=mc(i)*t+r,Lu[1]=yc(i)*a+e,u(s,Iu,Lu),f(l,Iu,Lu),n=n%Cn,n<0&&(n=n+Cn),i=i%Cn,i<0&&(i=i+Cn),n>i&&!o?i+=Cn:nn&&(Pu[0]=mc(c)*t+r,Pu[1]=yc(c)*a+e,u(s,Pu,s),f(l,Pu,l))}var Ot={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},An=[],Dn=[],zr=[],Oa=[],Gr=[],Fr=[],_c=Math.min,Sc=Math.max,Mn=Math.cos,In=Math.sin,ua=Math.abs,xc=Math.PI,Na=xc*2,bc=typeof Float32Array!="undefined",vs=[];function wc(r){var e=Math.round(r/xc*1e8)/1e8;return e%2*xc}function c_(r,e){var t=wc(r[0]);t<0&&(t+=Na);var a=t-r[0],n=r[1];n+=a,!e&&n-t>=Na?n=t+Na:e&&t-n>=Na?n=t-Na:!e&&t>n?n=t+(Na-wc(t-n)):e&&t0&&(this._ux=ua(a/_u/e)||0,this._uy=ua(a/_u/t)||0)},r.prototype.setDPR=function(e){this.dpr=e},r.prototype.setContext=function(e){this._ctx=e},r.prototype.getContext=function(){return this._ctx},r.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},r.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},r.prototype.moveTo=function(e,t){return this._drawPendingPt(),this.addData(Ot.M,e,t),this._ctx&&this._ctx.moveTo(e,t),this._x0=e,this._y0=t,this._xi=e,this._yi=t,this},r.prototype.lineTo=function(e,t){var a=ua(e-this._xi),n=ua(t-this._yi),i=a>this._ux||n>this._uy;if(this.addData(Ot.L,e,t),this._ctx&&i&&this._ctx.lineTo(e,t),i)this._xi=e,this._yi=t,this._pendingPtDist=0;else{var o=a*a+n*n;o>this._pendingPtDist&&(this._pendingPtX=e,this._pendingPtY=t,this._pendingPtDist=o)}return this},r.prototype.bezierCurveTo=function(e,t,a,n,i,o){return this._drawPendingPt(),this.addData(Ot.C,e,t,a,n,i,o),this._ctx&&this._ctx.bezierCurveTo(e,t,a,n,i,o),this._xi=i,this._yi=o,this},r.prototype.quadraticCurveTo=function(e,t,a,n){return this._drawPendingPt(),this.addData(Ot.Q,e,t,a,n),this._ctx&&this._ctx.quadraticCurveTo(e,t,a,n),this._xi=a,this._yi=n,this},r.prototype.arc=function(e,t,a,n,i,o){this._drawPendingPt(),vs[0]=n,vs[1]=i,c_(vs,o),n=vs[0],i=vs[1];var s=i-n;return this.addData(Ot.A,e,t,a,a,n,s,0,o?0:1),this._ctx&&this._ctx.arc(e,t,a,n,i,o),this._xi=Mn(i)*a+e,this._yi=In(i)*a+t,this},r.prototype.arcTo=function(e,t,a,n,i){return this._drawPendingPt(),this._ctx&&this._ctx.arcTo(e,t,a,n,i),this},r.prototype.rect=function(e,t,a,n){return this._drawPendingPt(),this._ctx&&this._ctx.rect(e,t,a,n),this.addData(Ot.R,e,t,a,n),this},r.prototype.closePath=function(){this._drawPendingPt(),this.addData(Ot.Z);var e=this._ctx,t=this._x0,a=this._y0;return e&&e.closePath(),this._xi=t,this._yi=a,this},r.prototype.fill=function(e){e&&e.fill(),this.toStatic()},r.prototype.stroke=function(e){e&&e.stroke(),this.toStatic()},r.prototype.len=function(){return this._len},r.prototype.setData=function(e){var t=e.length;!(this.data&&this.data.length===t)&&bc&&(this.data=new Float32Array(t));for(var a=0;af.length&&(this._expandData(),f=this.data);for(var h=0;h0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},r.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var e=[],t=0;t11&&(this.data=new Float32Array(e)))}},r.prototype.getBoundingRect=function(){zr[0]=zr[1]=Gr[0]=Gr[1]=Number.MAX_VALUE,Oa[0]=Oa[1]=Fr[0]=Fr[1]=-Number.MAX_VALUE;var e=this.data,t=0,a=0,n=0,i=0,o;for(o=0;oa||ua(_)>n||v===t-1)&&(d=Math.sqrt(m*m+_*_),i=g,o=y);break}case Ot.C:{var S=e[v++],b=e[v++],g=e[v++],y=e[v++],x=e[v++],w=e[v++];d=t2(i,o,S,b,g,y,x,w,10),i=x,o=w;break}case Ot.Q:{var S=e[v++],b=e[v++],g=e[v++],y=e[v++];d=r2(i,o,S,b,g,y,10),i=g,o=y;break}case Ot.A:var T=e[v++],C=e[v++],D=e[v++],M=e[v++],I=e[v++],L=e[v++],P=L+I;v+=1;var R=!e[v++];p&&(s=Mn(I)*D+T,l=In(I)*M+C),d=Sc(D,M)*_c(Na,Math.abs(L)),i=Mn(P)*D+T,o=In(P)*M+C;break;case Ot.R:{s=i=e[v++],l=o=e[v++];var E=e[v++],N=e[v++];d=E*2+N*2;break}case Ot.Z:{var m=s-i,_=l-o;d=Math.sqrt(m*m+_*_),i=s,o=l;break}}d>=0&&(u[h++]=d,f+=d)}return this._pathLen=f,f},r.prototype.rebuildPath=function(e,t){var a=this.data,n=this._ux,i=this._uy,o=this._len,s,l,u,f,h,v,c=t<1,p,d,g=0,y=0,m,_=0,S,b;if(c&&(this._pathSegLen||this._calculateLength(),p=this._pathSegLen,d=this._pathLen,m=t*d,!m))return;t:for(var x=0;x0&&(e.lineTo(S,b),_=0),w){case Ot.M:s=u=a[x++],l=f=a[x++],e.moveTo(u,f);break;case Ot.L:{h=a[x++],v=a[x++];var C=ua(h-u),D=ua(v-f);if(C>n||D>i){if(c){var M=p[y++];if(g+M>m){var I=(m-g)/M;e.lineTo(u*(1-I)+h*I,f*(1-I)+v*I);break t}g+=M}e.lineTo(h,v),u=h,f=v,_=0}else{var L=C*C+D*D;L>_&&(S=h,b=v,_=L)}break}case Ot.C:{var P=a[x++],R=a[x++],E=a[x++],N=a[x++],k=a[x++],V=a[x++];if(c){var M=p[y++];if(g+M>m){var I=(m-g)/M;Ra(u,P,E,k,I,An),Ra(f,R,N,V,I,Dn),e.bezierCurveTo(An[1],Dn[1],An[2],Dn[2],An[3],Dn[3]);break t}g+=M}e.bezierCurveTo(P,R,E,N,k,V),u=k,f=V;break}case Ot.Q:{var P=a[x++],R=a[x++],E=a[x++],N=a[x++];if(c){var M=p[y++];if(g+M>m){var I=(m-g)/M;qo(u,P,E,I,An),qo(f,R,N,I,Dn),e.quadraticCurveTo(An[1],Dn[1],An[2],Dn[2]);break t}g+=M}e.quadraticCurveTo(P,R,E,N),u=E,f=N;break}case Ot.A:var F=a[x++],W=a[x++],Z=a[x++],Q=a[x++],tt=a[x++],yt=a[x++],Dt=a[x++],pt=!a[x++],at=Z>Q?Z:Q,mt=ua(Z-Q)>.001,ht=tt+yt,q=!1;if(c){var M=p[y++];g+M>m&&(ht=tt+yt*(m-g)/M,q=!0),g+=M}if(mt&&e.ellipse?e.ellipse(F,W,Z,Q,Dt,tt,ht,pt):e.arc(F,W,at,tt,ht,pt),q)break t;T&&(s=Mn(tt)*Z+F,l=In(tt)*Q+W),u=Mn(ht)*Z+F,f=In(ht)*Q+W;break;case Ot.R:s=u=a[x],l=f=a[x+1],h=a[x++],v=a[x++];var st=a[x++],Ft=a[x++];if(c){var M=p[y++];if(g+M>m){var wt=m-g;e.moveTo(h,v),e.lineTo(h+_c(wt,st),v),wt-=st,wt>0&&e.lineTo(h+st,v+_c(wt,Ft)),wt-=Ft,wt>0&&e.lineTo(h+Sc(st-wt,0),v+Ft),wt-=st,wt>0&&e.lineTo(h,v+Sc(Ft-wt,0));break t}g+=M}e.rect(h,v,st,Ft);break;case Ot.Z:if(c){var M=p[y++];if(g+M>m){var I=(m-g)/M;e.lineTo(u*(1-I)+s*I,f*(1-I)+l*I);break t}g+=M}e.closePath(),u=s,f=l}}},r.prototype.clone=function(){var e=new r,t=this.data;return e.data=t.slice?t.slice():Array.prototype.slice.call(t),e._len=this._len,e},r.CMD=Ot,r.initDefaultProps=function(){var e=r.prototype;e._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,e._version=0}(),r}();function Ba(r,e,t,a,n,i,o){if(n===0)return!1;var s=n,l=0,u=r;if(o>e+s&&o>a+s||or+s&&i>t+s||ie+h&&f>a+h&&f>i+h&&f>s+h||fr+h&&u>t+h&&u>n+h&&u>o+h||ue+u&&l>a+u&&l>i+u||lr+u&&s>t+u&&s>n+u||st||f+un&&(n+=cs);var v=Math.atan2(l,s);return v<0&&(v+=cs),v>=a&&v<=n||v+cs>=a&&v+cs<=n}function fa(r,e,t,a,n,i){if(i>e&&i>a||in?s:0}var za=Hr.CMD,Ln=Math.PI*2,WP=1e-4;function UP(r,e){return Math.abs(r-e)e&&u>a&&u>i&&u>s||u1&&YP(),c=re(e,a,i,s,rr[0]),v>1&&(p=re(e,a,i,s,rr[1]))),v===2?ge&&s>a&&s>i||s=0&&u<=1){for(var f=0,h=ue(e,a,i,u),v=0;vt||s<-t)return 0;var l=Math.sqrt(t*t-s*s);De[0]=-l,De[1]=l;var u=Math.abs(a-n);if(u<1e-4)return 0;if(u>=Ln-1e-4){a=0,n=Ln;var f=i?1:-1;return o>=De[0]+r&&o<=De[1]+r?f:0}if(a>n){var h=a;a=n,n=h}a<0&&(a+=Ln,n+=Ln);for(var v=0,c=0;c<2;c++){var p=De[c];if(p+r>o){var d=Math.atan2(s,p),f=i?1:-1;d<0&&(d=Ln+d),(d>=a&&d<=n||d+Ln>=a&&d+Ln<=n)&&(d>Math.PI/2&&d1&&(t||(s+=fa(l,u,f,h,a,n))),g&&(l=i[p],u=i[p+1],f=l,h=u),d){case za.M:f=i[p++],h=i[p++],l=f,u=h;break;case za.L:if(t){if(Ba(l,u,i[p],i[p+1],e,a,n))return!0}else s+=fa(l,u,i[p],i[p+1],a,n)||0;l=i[p++],u=i[p++];break;case za.C:if(t){if(FP(l,u,i[p++],i[p++],i[p++],i[p++],i[p],i[p+1],e,a,n))return!0}else s+=XP(l,u,i[p++],i[p++],i[p++],i[p++],i[p],i[p+1],a,n)||0;l=i[p++],u=i[p++];break;case za.Q:if(t){if(p_(l,u,i[p++],i[p++],i[p],i[p+1],e,a,n))return!0}else s+=ZP(l,u,i[p++],i[p++],i[p],i[p+1],a,n)||0;l=i[p++],u=i[p++];break;case za.A:var y=i[p++],m=i[p++],_=i[p++],S=i[p++],b=i[p++],x=i[p++];p+=1;var w=!!(1-i[p++]);v=Math.cos(b)*_+y,c=Math.sin(b)*S+m,g?(f=v,h=c):s+=fa(l,u,v,c,a,n);var T=(a-y)*S/_+y;if(t){if(HP(y,m,S,b,b+x,w,e,T,n))return!0}else s+=$P(y,m,S,b,b+x,w,T,n);l=Math.cos(b+x)*_+y,u=Math.sin(b+x)*S+m;break;case za.R:f=l=i[p++],h=u=i[p++];var C=i[p++],D=i[p++];if(v=f+C,c=h+D,t){if(Ba(f,h,v,h,e,a,n)||Ba(v,h,v,c,e,a,n)||Ba(v,c,f,c,e,a,n)||Ba(f,c,f,h,e,a,n))return!0}else s+=fa(v,h,v,c,a,n),s+=fa(f,c,f,h,a,n);break;case za.Z:if(t){if(Ba(l,u,f,h,e,a,n))return!0}else s+=fa(l,u,f,h,a,n);l=f,u=h;break}}return!t&&!UP(u,h)&&(s+=fa(l,u,f,h,a,n)||0),s!==0}function qP(r,e,t){return g_(r,0,!1,e,t)}function KP(r,e,t,a){return g_(r,e,!0,t,a)}var Eu=j({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},Tn),jP={style:j({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},Mu.style)},Tc=la.concat(["invisible","culling","z","z2","zlevel","parent"]),dt=function(r){zt(e,r);function e(t){return r.call(this,t)||this}return e.prototype.update=function(){var t=this;r.prototype.update.call(this);var a=this.style;if(a.decal){var n=this._decalEl=this._decalEl||new e;n.buildPath===e.prototype.buildPath&&(n.buildPath=function(l){t.buildPath(l,t.shape)}),n.silent=!0;var i=n.style;for(var o in a)i[o]!==a[o]&&(i[o]=a[o]);i.fill=a.fill?a.decal:null,i.decal=null,i.shadowColor=null,a.strokeFirst&&(i.stroke=null);for(var s=0;s.5?Yv:a>.2?E2:Xv}else if(t)return Xv}return Yv},e.prototype.getInsideTextStroke=function(t){var a=this.style.fill;if(U(a)){var n=this.__zr,i=!!(n&&n.isDarkMode()),o=ts(t,0)0))},e.prototype.hasFill=function(){var t=this.style,a=t.fill;return a!=null&&a!=="none"},e.prototype.getBoundingRect=function(){var t=this._rect,a=this.style,n=!t;if(n){var i=!1;this.path||(i=!0,this.createPathProxy());var o=this.path;(i||this.__dirty&wi)&&(o.beginPath(),this.buildPath(o,this.shape,!1),this.pathUpdated()),t=o.getBoundingRect()}if(this._rect=t,this.hasStroke()&&this.path&&this.path.len()>0){var s=this._rectStroke||(this._rectStroke=t.clone());if(this.__dirty||n){s.copy(t);var l=a.strokeNoScale?this.getLineScale():1,u=a.lineWidth;if(!this.hasFill()){var f=this.strokeContainThreshold;u=Math.max(u,f==null?4:f)}l>1e-10&&(s.width+=u/l,s.height+=u/l,s.x-=u/l/2,s.y-=u/l/2)}return s}return t},e.prototype.contain=function(t,a){var n=this.transformCoordToLocal(t,a),i=this.getBoundingRect(),o=this.style;if(t=n[0],a=n[1],i.contain(t,a)){var s=this.path;if(this.hasStroke()){var l=o.lineWidth,u=o.strokeNoScale?this.getLineScale():1;if(u>1e-10&&(this.hasFill()||(l=Math.max(l,this.strokeContainThreshold)),KP(s,l/u,t,a)))return!0}if(this.hasFill())return qP(s,t,a)}return!1},e.prototype.dirtyShape=function(){this.__dirty|=wi,this._rect&&(this._rect=null),this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},e.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},e.prototype.animateShape=function(t){return this.animate("shape",t)},e.prototype.updateDuringAnimation=function(t){t==="style"?this.dirtyStyle():t==="shape"?this.dirtyShape():this.markRedraw()},e.prototype.attrKV=function(t,a){t==="shape"?this.setShape(a):r.prototype.attrKV.call(this,t,a)},e.prototype.setShape=function(t,a){var n=this.shape;return n||(n=this.shape={}),typeof t=="string"?n[t]=a:B(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(this.__dirty&wi)},e.prototype.createStyle=function(t){return Bo(Eu,t)},e.prototype._innerSaveToNormal=function(t){r.prototype._innerSaveToNormal.call(this,t);var a=this._normalState;t.shape&&!a.shape&&(a.shape=B({},this.shape))},e.prototype._applyStateObj=function(t,a,n,i,o,s){r.prototype._applyStateObj.call(this,t,a,n,i,o,s);var l=!(a&&i),u;if(a&&a.shape?o?i?u=a.shape:(u=B({},n.shape),B(u,a.shape)):(u=B({},i?this.shape:n.shape),B(u,a.shape)):l&&(u=n.shape),u)if(o){this.shape=B({},this.shape);for(var f={},h=St(u),v=0;v0},e.prototype.hasFill=function(){var t=this.style,a=t.fill;return a!=null&&a!=="none"},e.prototype.createStyle=function(t){return Bo(QP,t)},e.prototype.setBoundingRect=function(t){this._rect=t},e.prototype.getBoundingRect=function(){var t=this.style;if(!this._rect){var a=t.text;a!=null?a+="":a="";var n=is(a,t.font,t.textAlign,t.textBaseline);if(n.x+=t.x||0,n.y+=t.y||0,this.hasStroke()){var i=t.lineWidth;n.x-=i/2,n.y-=i/2,n.width+=i,n.height+=i}this._rect=n}return this._rect},e.initDefaultProps=function(){var t=e.prototype;t.dirtyRectTolerance=10}(),e}(er);Ri.prototype.type="tspan";var JP=j({x:0,y:0},Tn),tR={style:j({x:!0,y:!0,width:!0,height:!0,sx:!0,sy:!0,sWidth:!0,sHeight:!0},Mu.style)};function eR(r){return!!(r&&typeof r!="string"&&r.width&&r.height)}var ae=function(r){zt(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createStyle=function(t){return Bo(JP,t)},e.prototype._getSize=function(t){var a=this.style,n=a[t];if(n!=null)return n;var i=eR(a.image)?a.image:this.__image;if(!i)return 0;var o=t==="width"?"height":"width",s=a[o];return s==null?i[t]:i[t]/i[o]*s},e.prototype.getWidth=function(){return this._getSize("width")},e.prototype.getHeight=function(){return this._getSize("height")},e.prototype.getAnimationStyleProps=function(){return tR},e.prototype.getBoundingRect=function(){var t=this.style;return this._rect||(this._rect=new ft(t.x||0,t.y||0,this.getWidth(),this.getHeight())),this._rect},e}(er);ae.prototype.type="image";function rR(r,e){var t=e.x,a=e.y,n=e.width,i=e.height,o=e.r,s,l,u,f;n<0&&(t=t+n,n=-n),i<0&&(a=a+i,i=-i),typeof o=="number"?s=l=u=f=o:o instanceof Array?o.length===1?s=l=u=f=o[0]:o.length===2?(s=u=o[0],l=f=o[1]):o.length===3?(s=o[0],l=f=o[1],u=o[2]):(s=o[0],l=o[1],u=o[2],f=o[3]):s=l=u=f=0;var h;s+l>n&&(h=s+l,s*=n/h,l*=n/h),u+f>n&&(h=u+f,u*=n/h,f*=n/h),l+u>i&&(h=l+u,l*=i/h,u*=i/h),s+f>i&&(h=s+f,s*=i/h,f*=i/h),r.moveTo(t+s,a),r.lineTo(t+n-l,a),l!==0&&r.arc(t+n-l,a+l,l,-Math.PI/2,0),r.lineTo(t+n,a+i-u),u!==0&&r.arc(t+n-u,a+i-u,u,0,Math.PI/2),r.lineTo(t+f,a+i),f!==0&&r.arc(t+f,a+i-f,f,Math.PI/2,Math.PI),r.lineTo(t,a+s),s!==0&&r.arc(t+s,a+s,s,Math.PI,Math.PI*1.5)}var Ei=Math.round;function y_(r,e,t){if(!!e){var a=e.x1,n=e.x2,i=e.y1,o=e.y2;r.x1=a,r.x2=n,r.y1=i,r.y2=o;var s=t&&t.lineWidth;return s&&(Ei(a*2)===Ei(n*2)&&(r.x1=r.x2=Pn(a,s,!0)),Ei(i*2)===Ei(o*2)&&(r.y1=r.y2=Pn(i,s,!0))),r}}function m_(r,e,t){if(!!e){var a=e.x,n=e.y,i=e.width,o=e.height;r.x=a,r.y=n,r.width=i,r.height=o;var s=t&&t.lineWidth;return s&&(r.x=Pn(a,s,!0),r.y=Pn(n,s,!0),r.width=Math.max(Pn(a+i,s,!1)-r.x,i===0?0:1),r.height=Math.max(Pn(n+o,s,!1)-r.y,o===0?0:1)),r}}function Pn(r,e,t){if(!e)return r;var a=Ei(r*2);return(a+Ei(e))%2==0?a/2:(a+(t?1:-1))/2}var aR=function(){function r(){this.x=0,this.y=0,this.width=0,this.height=0}return r}(),nR={},xt=function(r){zt(e,r);function e(t){return r.call(this,t)||this}return e.prototype.getDefaultShape=function(){return new aR},e.prototype.buildPath=function(t,a){var n,i,o,s;if(this.subPixelOptimize){var l=m_(nR,a,this.style);n=l.x,i=l.y,o=l.width,s=l.height,l.r=a.r,a=l}else n=a.x,i=a.y,o=a.width,s=a.height;a.r?rR(t,a):t.rect(n,i,o,s)},e.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},e}(dt);xt.prototype.type="rect";var __={fill:"#000"},S_=2,iR={style:j({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},Mu.style)},bt=function(r){zt(e,r);function e(t){var a=r.call(this)||this;return a.type="text",a._children=[],a._defaultStyle=__,a.attr(t),a}return e.prototype.childrenRef=function(){return this._children},e.prototype.update=function(){r.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var t=0;t0,I=t.width!=null&&(t.overflow==="truncate"||t.overflow==="break"||t.overflow==="breakAll"),L=o.calculatedLineHeight,P=0;P=0&&(P=x[L],P.align==="right");)this._placeToken(P,t,T,y,I,"right",_),C-=P.width,I-=P.width,L--;for(M+=(i-(M-g)-(m-I)-C)/2;D<=L;)P=x[D],this._placeToken(P,t,T,y,M+P.width/2,"center",_),M+=P.width,D++;y+=T}},e.prototype._placeToken=function(t,a,n,i,o,s,l){var u=a.rich[t.styleName]||{};u.text=t.text;var f=t.verticalAlign,h=i+n/2;f==="top"?h=i+t.height/2:f==="bottom"&&(h=i+n-t.height/2);var v=!t.isLineHolder&&Cc(u);v&&this._renderBackground(u,a,s==="right"?o-t.width:s==="center"?o-t.width/2:o,h-t.height/2,t.width,t.height);var c=!!u.backgroundColor,p=t.textPadding;p&&(o=M_(o,s,p),h-=t.height/2-p[0]-t.innerHeight/2);var d=this._getOrCreateChild(Ri),g=d.createStyle();d.useStyle(g);var y=this._defaultStyle,m=!1,_=0,S=D_("fill"in u?u.fill:"fill"in a?a.fill:(m=!0,y.fill)),b=A_("stroke"in u?u.stroke:"stroke"in a?a.stroke:!c&&!l&&(!y.autoStroke||m)?(_=S_,y.stroke):null),x=u.textShadowBlur>0||a.textShadowBlur>0;g.text=t.text,g.x=o,g.y=h,x&&(g.shadowBlur=u.textShadowBlur||a.textShadowBlur||0,g.shadowColor=u.textShadowColor||a.textShadowColor||"transparent",g.shadowOffsetX=u.textShadowOffsetX||a.textShadowOffsetX||0,g.shadowOffsetY=u.textShadowOffsetY||a.textShadowOffsetY||0),g.textAlign=s,g.textBaseline="middle",g.font=t.font||Ca,g.opacity=Er(u.opacity,a.opacity,1),w_(g,u),b&&(g.lineWidth=Er(u.lineWidth,a.lineWidth,_),g.lineDash=lt(u.lineDash,a.lineDash),g.lineDashOffset=a.lineDashOffset||0,g.stroke=b),S&&(g.fill=S);var w=t.contentWidth,T=t.contentHeight;d.setBoundingRect(new ft(os(g.x,w,g.textAlign),Ii(g.y,T,g.textBaseline),w,T))},e.prototype._renderBackground=function(t,a,n,i,o,s){var l=t.backgroundColor,u=t.borderWidth,f=t.borderColor,h=l&&l.image,v=l&&!h,c=t.borderRadius,p=this,d,g;if(v||t.lineHeight||u&&f){d=this._getOrCreateChild(xt),d.useStyle(d.createStyle()),d.style.fill=null;var y=d.shape;y.x=n,y.y=i,y.width=o,y.height=s,y.r=c,d.dirtyShape()}if(v){var m=d.style;m.fill=l||null,m.fillOpacity=lt(t.fillOpacity,1)}else if(h){g=this._getOrCreateChild(ae),g.onload=function(){p.dirtyStyle()};var _=g.style;_.image=l.image,_.x=n,_.y=i,_.width=o,_.height=s}if(u&&f){var m=d.style;m.lineWidth=u,m.stroke=f,m.strokeOpacity=lt(t.strokeOpacity,1),m.lineDash=t.borderDash,m.lineDashOffset=t.borderDashOffset||0,d.strokeContainThreshold=0,d.hasFill()&&d.hasStroke()&&(m.strokeFirst=!0,m.lineWidth*=2)}var S=(d||g).style;S.shadowBlur=t.shadowBlur||0,S.shadowColor=t.shadowColor||"transparent",S.shadowOffsetX=t.shadowOffsetX||0,S.shadowOffsetY=t.shadowOffsetY||0,S.opacity=Er(t.opacity,a.opacity,1)},e.makeFont=function(t){var a="";return T_(t)&&(a=[t.fontStyle,t.fontWeight,b_(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),a&&Ke(a)||t.textFont||t.font},e}(er),oR={left:!0,right:1,center:1},sR={top:1,bottom:1,middle:1},x_=["fontStyle","fontWeight","fontSize","fontFamily"];function b_(r){return typeof r=="string"&&(r.indexOf("px")!==-1||r.indexOf("rem")!==-1||r.indexOf("em")!==-1)?r:isNaN(+r)?ev+"px":r+"px"}function w_(r,e){for(var t=0;t=0,i=!1;if(r instanceof dt){var o=R_(r),s=n&&o.selectFill||o.normalFill,l=n&&o.selectStroke||o.normalStroke;if(Oi(s)||Oi(l)){a=a||{};var u=a.style||{};u.fill==="inherit"?(i=!0,a=B({},a),u=B({},u),u.fill=s):!Oi(u.fill)&&Oi(s)?(i=!0,a=B({},a),u=B({},u),u.fill=k_(s)):!Oi(u.stroke)&&Oi(l)&&(i||(a=B({},a),u=B({},u)),u.stroke=k_(l)),a.style=u}}if(a&&a.z2==null){i||(a=B({},a));var f=r.z2EmphasisLift;a.z2=r.z2+(f!=null?f:ki)}return a}function pR(r,e,t){if(t&&t.z2==null){t=B({},t);var a=r.z2SelectLift;t.z2=r.z2+(a!=null?a:uR)}return t}function dR(r,e,t){var a=vt(r.currentStates,e)>=0,n=r.style.opacity,i=a?null:vR(r,["opacity"],e,{opacity:1});t=t||{};var o=t.style||{};return o.opacity==null&&(t=B({},t),o=B({opacity:a?n:i.opacity*.1},o),t.style=o),t}function Lc(r,e){var t=this.states[r];if(this.style){if(r==="emphasis")return cR(this,r,e,t);if(r==="blur")return dR(this,r,t);if(r==="select")return pR(this,r,t)}return t}function En(r){r.stateProxy=Lc;var e=r.getTextContent(),t=r.getTextGuideLine();e&&(e.stateProxy=Lc),t&&(t.stateProxy=Lc)}function z_(r,e){!U_(r,e)&&!r.__highByOuter&&ha(r,O_)}function G_(r,e){!U_(r,e)&&!r.__highByOuter&&ha(r,N_)}function va(r,e){r.__highByOuter|=1<<(e||0),ha(r,O_)}function ca(r,e){!(r.__highByOuter&=~(1<<(e||0)))&&ha(r,N_)}function F_(r){ha(r,Ic)}function Pc(r){ha(r,B_)}function H_(r){ha(r,fR)}function W_(r){ha(r,hR)}function U_(r,e){return r.__highDownSilentOnTouch&&e.zrByTouch}function Y_(r){var e=r.getModel(),t=[],a=[];e.eachComponent(function(n,i){var o=Dc(i),s=n==="series",l=s?r.getViewOfSeriesModel(i):r.getViewOfComponentModel(i);!s&&a.push(l),o.isBlured&&(l.group.traverse(function(u){B_(u)}),s&&t.push(i)),o.isBlured=!1}),A(a,function(n){n&&n.toggleBlurSeries&&n.toggleBlurSeries(t,!1,e)})}function Rc(r,e,t,a){var n=a.getModel();t=t||"coordinateSystem";function i(u,f){for(var h=0;h0){var l={dataIndex:s,seriesIndex:t.seriesIndex};o!=null&&(l.dataType=o),e.push(l)}})}),e}function Ga(r,e,t){kn(r,!0),ha(r,En),Oc(r,e,t)}function xR(r){kn(r,!1)}function Ut(r,e,t,a){a?xR(r):Ga(r,e,t)}function Oc(r,e,t){var a=nt(r);e!=null?(a.focus=e,a.blurScope=t):a.focus&&(a.focus=null)}var Z_=["emphasis","blur","select"],bR={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function he(r,e,t,a){t=t||"itemStyle";for(var n=0;n1&&(o*=Bc(p),s*=Bc(p));var d=(n===i?-1:1)*Bc((o*o*(s*s)-o*o*(c*c)-s*s*(v*v))/(o*o*(c*c)+s*s*(v*v)))||0,g=d*o*c/s,y=d*-s*v/o,m=(r+t)/2+Gu(h)*g-zu(h)*y,_=(e+a)/2+zu(h)*g+Gu(h)*y,S=Q_([1,0],[(v-g)/o,(c-y)/s]),b=[(v-g)/o,(c-y)/s],x=[(-1*v-g)/o,(-1*c-y)/s],w=Q_(b,x);if(Vc(b,x)<=-1&&(w=_s),Vc(b,x)>=1&&(w=0),w<0){var T=Math.round(w/_s*1e6)/1e6;w=_s*2+T%2*_s}f.addData(u,m,_,o,s,S,w,h,i)}var MR=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig,IR=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;function LR(r){var e=new Hr;if(!r)return e;var t=0,a=0,n=t,i=a,o,s=Hr.CMD,l=r.match(MR);if(!l)return e;for(var u=0;uP*P+R*R&&(T=D,C=M),{cx:T,cy:C,x0:-f,y0:-h,x1:T*(n/b-1),y1:C*(n/b-1)}}function BR(r){var e;if(z(r)){var t=r.length;if(!t)return r;t===1?e=[r[0],r[0],0,0]:t===2?e=[r[0],r[0],r[1],r[1]]:t===3?e=r.concat(r[2]):e=r}else e=[r,r,r,r];return e}function VR(r,e){var t,a=bs(e.r,0),n=bs(e.r0||0,0),i=a>0,o=n>0;if(!(!i&&!o)){if(i||(a=n,n=0),n>a){var s=a;a=n,n=s}var l=e.startAngle,u=e.endAngle;if(!(isNaN(l)||isNaN(u))){var f=e.cx,h=e.cy,v=!!e.clockwise,c=i1(u-l),p=c>Gc&&c%Gc;if(p>Tr&&(c=p),!(a>Tr))r.moveTo(f,h);else if(c>Gc-Tr)r.moveTo(f+a*Bi(l),h+a*On(l)),r.arc(f,h,a,l,u,!v),n>Tr&&(r.moveTo(f+n*Bi(u),h+n*On(u)),r.arc(f,h,n,u,l,v));else{var d=void 0,g=void 0,y=void 0,m=void 0,_=void 0,S=void 0,b=void 0,x=void 0,w=void 0,T=void 0,C=void 0,D=void 0,M=void 0,I=void 0,L=void 0,P=void 0,R=a*Bi(l),E=a*On(l),N=n*Bi(u),k=n*On(u),V=c>Tr;if(V){var F=e.cornerRadius;F&&(t=BR(F),d=t[0],g=t[1],y=t[2],m=t[3]);var W=i1(a-n)/2;if(_=Wr(W,y),S=Wr(W,m),b=Wr(W,d),x=Wr(W,g),C=w=bs(_,S),D=T=bs(b,x),(w>Tr||T>Tr)&&(M=a*Bi(u),I=a*On(u),L=n*Bi(l),P=n*On(l),cTr){var mt=Wr(y,C),ht=Wr(m,C),q=Fu(L,P,R,E,a,mt,v),st=Fu(M,I,N,k,a,ht,v);r.moveTo(f+q.cx+q.x0,h+q.cy+q.y0),C0&&r.arc(f+q.cx,h+q.cy,mt,ye(q.y0,q.x0),ye(q.y1,q.x1),!v),r.arc(f,h,a,ye(q.cy+q.y1,q.cx+q.x1),ye(st.cy+st.y1,st.cx+st.x1),!v),ht>0&&r.arc(f+st.cx,h+st.cy,ht,ye(st.y1,st.x1),ye(st.y0,st.x0),!v))}else r.moveTo(f+R,h+E),r.arc(f,h,a,l,u,!v);if(!(n>Tr)||!V)r.lineTo(f+N,h+k);else if(D>Tr){var mt=Wr(d,D),ht=Wr(g,D),q=Fu(N,k,M,I,n,-ht,v),st=Fu(R,E,L,P,n,-mt,v);r.lineTo(f+q.cx+q.x0,h+q.cy+q.y0),D0&&r.arc(f+q.cx,h+q.cy,ht,ye(q.y0,q.x0),ye(q.y1,q.x1),!v),r.arc(f,h,n,ye(q.cy+q.y1,q.cx+q.x1),ye(st.cy+st.y1,st.cx+st.x1),v),mt>0&&r.arc(f+st.cx,h+st.cy,mt,ye(st.y1,st.x1),ye(st.y0,st.x0),!v))}else r.lineTo(f+N,h+k),r.arc(f,h,n,u,l,v)}r.closePath()}}}var zR=function(){function r(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0,this.cornerRadius=0}return r}(),me=function(r){zt(e,r);function e(t){return r.call(this,t)||this}return e.prototype.getDefaultShape=function(){return new zR},e.prototype.buildPath=function(t,a){VR(t,a)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(dt);me.prototype.type="sector";var GR=function(){function r(){this.cx=0,this.cy=0,this.r=0,this.r0=0}return r}(),Vi=function(r){zt(e,r);function e(t){return r.call(this,t)||this}return e.prototype.getDefaultShape=function(){return new GR},e.prototype.buildPath=function(t,a){var n=a.cx,i=a.cy,o=Math.PI*2;t.moveTo(n+a.r,i),t.arc(n,i,a.r,0,o,!1),t.moveTo(n+a.r0,i),t.arc(n,i,a.r0,0,o,!0)},e}(dt);Vi.prototype.type="ring";function FR(r,e,t,a){var n=[],i=[],o=[],s=[],l,u,f,h;if(a){f=[Infinity,Infinity],h=[-Infinity,-Infinity];for(var v=0,c=r.length;v=2){if(a){var i=FR(n,a,t,e.smoothConstraint);r.moveTo(n[0][0],n[0][1]);for(var o=n.length,s=0;s<(t?o:o-1);s++){var l=i[s*2],u=i[s*2+1],f=n[(s+1)%o];r.bezierCurveTo(l[0],l[1],u[0],u[1],f[0],f[1])}}else{r.moveTo(n[0][0],n[0][1]);for(var s=1,h=n.length;sBn[1]){if(s=!1,i)return s;var f=Math.abs(Bn[0]-Nn[1]),h=Math.abs(Nn[0]-Bn[1]);Math.min(f,h)>n.len()&&(f0){var h=f.duration,v=f.delay,c=f.easing,p={duration:h,delay:v||0,easing:c,done:i,force:!!i||!!o,setToFinal:!u,scope:r,during:o};s?e.animateFrom(t,p):e.animateTo(t,p)}else e.stopAnimation(),!s&&e.attr(t),o&&o(1),i&&i()}function At(r,e,t,a,n,i){Hc("update",r,e,t,a,n,i)}function Gt(r,e,t,a,n,i){Hc("enter",r,e,t,a,n,i)}function Hi(r){if(!r.__zr)return!0;for(var e=0;eMath.abs(i[1])?i[0]>0?"right":"left":i[1]>0?"bottom":"top"}function d1(r){return!r.isGroup}function QR(r){return r.shape!=null}function As(r,e,t){if(!r||!e)return;function a(o){var s={};return o.traverse(function(l){d1(l)&&l.anid&&(s[l.anid]=l)}),s}function n(o){var s={x:o.x,y:o.y,rotation:o.rotation};return QR(o)&&(s.shape=B({},o.shape)),s}var i=a(r);e.traverse(function(o){if(d1(o)&&o.anid){var s=i[o.anid];if(s){var l=n(o);o.attr(n(s)),At(o,l,t,nt(o).dataIndex)}}})}function Xc(r,e){return G(r,function(t){var a=t[0];a=Xu(a,e.x),a=Zu(a,e.x+e.width);var n=t[1];return n=Xu(n,e.y),n=Zu(n,e.y+e.height),[a,n]})}function g1(r,e){var t=Xu(r.x,e.x),a=Zu(r.x+r.width,e.x+e.width),n=Xu(r.y,e.y),i=Zu(r.y+r.height,e.y+e.height);if(a>=t&&i>=n)return{x:t,y:n,width:a-t,height:i-n}}function Ui(r,e,t){var a=B({rectHover:!0},e),n=a.style={strokeNoScale:!0};if(t=t||{x:-1,y:-1,width:2,height:2},r)return r.indexOf("image://")===0?(n.image=r.slice(8),j(n,t),new ae(a)):Cs(r.replace("path://",""),a,t,"center")}function Ds(r,e,t,a,n){for(var i=0,o=n[n.length-1];i1)return!1;var g=Zc(c,p,f,h)/v;return!(g<0||g>1)}function Zc(r,e,t,a){return r*a-t*e}function JR(r){return r<=1e-6&&r>=-1e-6}function Yi(r){var e=r.itemTooltipOption,t=r.componentModel,a=r.itemName,n=U(e)?{formatter:e}:e,i=t.mainType,o=t.componentIndex,s={componentType:i,name:a,$vars:["name"]};s[i+"Index"]=o;var l=r.formatterParamsExtra;l&&A(St(l),function(f){X(s,f)||(s[f]=l[f],s.$vars.push(f))});var u=nt(r.el);u.componentMainType=i,u.componentIndex=o,u.tooltipConfig={name:a,option:j({content:a,formatterParams:s},n)}}function m1(r,e){var t;r.isGroup&&(t=e(r)),t||r.traverse(e)}function Wa(r,e){if(r)if(z(r))for(var t=0;t=0&&s.push(l)}),s}}function Ua(r,e){return ot(ot({},r,!0),e,!0)}var hE={time:{month:["January","February","March","April","May","June","July","August","September","October","November","December"],monthAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayOfWeekAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},legend:{selector:{all:"All",inverse:"Inv"}},toolbox:{brush:{title:{rect:"Box Select",polygon:"Lasso Select",lineX:"Horizontally Select",lineY:"Vertically Select",keep:"Keep Selections",clear:"Clear Selections"}},dataView:{title:"Data View",lang:["Data View","Close","Refresh"]},dataZoom:{title:{zoom:"Zoom",back:"Zoom Reset"}},magicType:{title:{line:"Switch to Line Chart",bar:"Switch to Bar Chart",stack:"Stack",tiled:"Tile"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image",lang:["Right Click to Save Image"]}},series:{typeNames:{pie:"Pie chart",bar:"Bar chart",line:"Line chart",scatter:"Scatter plot",effectScatter:"Ripple scatter plot",radar:"Radar chart",tree:"Tree",treemap:"Treemap",boxplot:"Boxplot",candlestick:"Candlestick",k:"K line chart",heatmap:"Heat map",map:"Map",parallel:"Parallel coordinate map",lines:"Line graph",graph:"Relationship graph",sankey:"Sankey diagram",funnel:"Funnel chart",gauge:"Gauge",pictorialBar:"Pictorial bar",themeRiver:"Theme River Map",sunburst:"Sunburst"}},aria:{general:{withTitle:'This is a chart about "{title}"',withoutTitle:"This is a chart"},series:{single:{prefix:"",withName:" with type {seriesType} named {seriesName}.",withoutName:" with type {seriesType}."},multiple:{prefix:". It consists of {seriesCount} series count.",withName:" The {seriesId} series is a {seriesType} representing {seriesName}.",withoutName:" The {seriesId} series is a {seriesType}.",separator:{middle:"",end:""}}},data:{allData:"The data is as follows: ",partialData:"The first {displayCnt} items are: ",withName:"the data for {name} is {value}",withoutName:"{value}",separator:{middle:", ",end:". "}}}},vE={time:{month:["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"],monthAbbr:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708","7\u6708","8\u6708","9\u6708","10\u6708","11\u6708","12\u6708"],dayOfWeek:["\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"],dayOfWeekAbbr:["\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"]},legend:{selector:{all:"\u5168\u9009",inverse:"\u53CD\u9009"}},toolbox:{brush:{title:{rect:"\u77E9\u5F62\u9009\u62E9",polygon:"\u5708\u9009",lineX:"\u6A2A\u5411\u9009\u62E9",lineY:"\u7EB5\u5411\u9009\u62E9",keep:"\u4FDD\u6301\u9009\u62E9",clear:"\u6E05\u9664\u9009\u62E9"}},dataView:{title:"\u6570\u636E\u89C6\u56FE",lang:["\u6570\u636E\u89C6\u56FE","\u5173\u95ED","\u5237\u65B0"]},dataZoom:{title:{zoom:"\u533A\u57DF\u7F29\u653E",back:"\u533A\u57DF\u7F29\u653E\u8FD8\u539F"}},magicType:{title:{line:"\u5207\u6362\u4E3A\u6298\u7EBF\u56FE",bar:"\u5207\u6362\u4E3A\u67F1\u72B6\u56FE",stack:"\u5207\u6362\u4E3A\u5806\u53E0",tiled:"\u5207\u6362\u4E3A\u5E73\u94FA"}},restore:{title:"\u8FD8\u539F"},saveAsImage:{title:"\u4FDD\u5B58\u4E3A\u56FE\u7247",lang:["\u53F3\u952E\u53E6\u5B58\u4E3A\u56FE\u7247"]}},series:{typeNames:{pie:"\u997C\u56FE",bar:"\u67F1\u72B6\u56FE",line:"\u6298\u7EBF\u56FE",scatter:"\u6563\u70B9\u56FE",effectScatter:"\u6D9F\u6F2A\u6563\u70B9\u56FE",radar:"\u96F7\u8FBE\u56FE",tree:"\u6811\u56FE",treemap:"\u77E9\u5F62\u6811\u56FE",boxplot:"\u7BB1\u578B\u56FE",candlestick:"K\u7EBF\u56FE",k:"K\u7EBF\u56FE",heatmap:"\u70ED\u529B\u56FE",map:"\u5730\u56FE",parallel:"\u5E73\u884C\u5750\u6807\u56FE",lines:"\u7EBF\u56FE",graph:"\u5173\u7CFB\u56FE",sankey:"\u6851\u57FA\u56FE",funnel:"\u6F0F\u6597\u56FE",gauge:"\u4EEA\u8868\u76D8\u56FE",pictorialBar:"\u8C61\u5F62\u67F1\u56FE",themeRiver:"\u4E3B\u9898\u6CB3\u6D41\u56FE",sunburst:"\u65ED\u65E5\u56FE"}},aria:{general:{withTitle:"\u8FD9\u662F\u4E00\u4E2A\u5173\u4E8E\u201C{title}\u201D\u7684\u56FE\u8868\u3002",withoutTitle:"\u8FD9\u662F\u4E00\u4E2A\u56FE\u8868\uFF0C"},series:{single:{prefix:"",withName:"\u56FE\u8868\u7C7B\u578B\u662F{seriesType}\uFF0C\u8868\u793A{seriesName}\u3002",withoutName:"\u56FE\u8868\u7C7B\u578B\u662F{seriesType}\u3002"},multiple:{prefix:"\u5B83\u7531{seriesCount}\u4E2A\u56FE\u8868\u7CFB\u5217\u7EC4\u6210\u3002",withName:"\u7B2C{seriesId}\u4E2A\u7CFB\u5217\u662F\u4E00\u4E2A\u8868\u793A{seriesName}\u7684{seriesType}\uFF0C",withoutName:"\u7B2C{seriesId}\u4E2A\u7CFB\u5217\u662F\u4E00\u4E2A{seriesType}\uFF0C",separator:{middle:"\uFF1B",end:"\u3002"}}},data:{allData:"\u5176\u6570\u636E\u662F\u2014\u2014",partialData:"\u5176\u4E2D\uFF0C\u524D{displayCnt}\u9879\u662F\u2014\u2014",withName:"{name}\u7684\u6570\u636E\u662F{value}",withoutName:"{value}",separator:{middle:"\uFF0C",end:""}}}},Ju="ZH",jc="EN",Is=jc,tf={},Qc={},I1=_t.domSupported?function(){var r=(document.documentElement.lang||navigator.language||navigator.browserLanguage).toUpperCase();return r.indexOf(Ju)>-1?Ju:Is}():Is;function Jc(r,e){r=r.toUpperCase(),Qc[r]=new Mt(e),tf[r]=e}function cE(r){if(U(r)){var e=tf[r.toUpperCase()]||{};return r===Ju||r===jc?et(e):ot(et(e),et(tf[Is]),!1)}else return ot(et(r),et(tf[Is]),!1)}function tp(r){return Qc[r]}function pE(){return Qc[Is]}Jc(jc,hE),Jc(Ju,vE);var ep=1e3,rp=ep*60,Ls=rp*60,ir=Ls*24,L1=ir*365,Ps={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}",none:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},ef="{yyyy}-{MM}-{dd}",P1={year:"{yyyy}",month:"{yyyy}-{MM}",day:ef,hour:ef+" "+Ps.hour,minute:ef+" "+Ps.minute,second:ef+" "+Ps.second,millisecond:Ps.none},ap=["year","month","day","hour","minute","second","millisecond"],R1=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Be(r,e){return r+="","0000".substr(0,e-r.length)+r}function $i(r){switch(r){case"half-year":case"quarter":return"month";case"week":case"half-week":return"day";case"half-day":case"quarter-day":return"hour";default:return r}}function dE(r){return r===$i(r)}function gE(r){switch(r){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}function Rs(r,e,t,a){var n=Ue(r),i=n[np(t)](),o=n[qi(t)]()+1,s=Math.floor((o-1)/3)+1,l=n[rf(t)](),u=n["get"+(t?"UTC":"")+"Day"](),f=n[Es(t)](),h=(f-1)%12+1,v=n[af(t)](),c=n[nf(t)](),p=n[of(t)](),d=a instanceof Mt?a:tp(a||I1)||pE(),g=d.getModel("time"),y=g.get("month"),m=g.get("monthAbbr"),_=g.get("dayOfWeek"),S=g.get("dayOfWeekAbbr");return(e||"").replace(/{yyyy}/g,i+"").replace(/{yy}/g,i%100+"").replace(/{Q}/g,s+"").replace(/{MMMM}/g,y[o-1]).replace(/{MMM}/g,m[o-1]).replace(/{MM}/g,Be(o,2)).replace(/{M}/g,o+"").replace(/{dd}/g,Be(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,_[u]).replace(/{ee}/g,S[u]).replace(/{e}/g,u+"").replace(/{HH}/g,Be(f,2)).replace(/{H}/g,f+"").replace(/{hh}/g,Be(h+"",2)).replace(/{h}/g,h+"").replace(/{mm}/g,Be(v,2)).replace(/{m}/g,v+"").replace(/{ss}/g,Be(c,2)).replace(/{s}/g,c+"").replace(/{SSS}/g,Be(p,3)).replace(/{S}/g,p+"")}function yE(r,e,t,a,n){var i=null;if(U(t))i=t;else if(K(t))i=t(r.value,e,{level:r.level});else{var o=B({},Ps);if(r.level>0)for(var s=0;s=0;--s)if(l[u]){i=l[u];break}i=i||o.none}if(z(i)){var h=r.level==null?0:r.level>=0?r.level:i.length+r.level;h=Math.min(h,i.length-1),i=i[h]}}return Rs(new Date(r.value),i,n,a)}function E1(r,e){var t=Ue(r),a=t[qi(e)]()+1,n=t[rf(e)](),i=t[Es(e)](),o=t[af(e)](),s=t[nf(e)](),l=t[of(e)](),u=l===0,f=u&&s===0,h=f&&o===0,v=h&&i===0,c=v&&n===1,p=c&&a===1;return p?"year":c?"month":v?"day":h?"hour":f?"minute":u?"second":"millisecond"}function k1(r,e,t){var a=Tt(r)?Ue(r):r;switch(e=e||E1(r,t),e){case"year":return a[np(t)]();case"half-year":return a[qi(t)]()>=6?1:0;case"quarter":return Math.floor((a[qi(t)]()+1)/4);case"month":return a[qi(t)]();case"day":return a[rf(t)]();case"half-day":return a[Es(t)]()/24;case"hour":return a[Es(t)]();case"minute":return a[af(t)]();case"second":return a[nf(t)]();case"millisecond":return a[of(t)]()}}function np(r){return r?"getUTCFullYear":"getFullYear"}function qi(r){return r?"getUTCMonth":"getMonth"}function rf(r){return r?"getUTCDate":"getDate"}function Es(r){return r?"getUTCHours":"getHours"}function af(r){return r?"getUTCMinutes":"getMinutes"}function nf(r){return r?"getUTCSeconds":"getSeconds"}function of(r){return r?"getUTCMilliseconds":"getMilliseconds"}function mE(r){return r?"setUTCFullYear":"setFullYear"}function O1(r){return r?"setUTCMonth":"setMonth"}function N1(r){return r?"setUTCDate":"setDate"}function B1(r){return r?"setUTCHours":"setHours"}function V1(r){return r?"setUTCMinutes":"setMinutes"}function z1(r){return r?"setUTCSeconds":"setSeconds"}function G1(r){return r?"setUTCMilliseconds":"setMilliseconds"}function _E(r,e,t,a,n,i,o,s){var l=new bt({style:{text:r,font:e,align:t,verticalAlign:a,padding:n,rich:i,overflow:o?"truncate":null,lineHeight:s}});return l.getBoundingRect()}function ip(r){if(!ic(r))return U(r)?r:"-";var e=(r+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function op(r,e){return r=(r||"").toLowerCase().replace(/-(.)/g,function(t,a){return a.toUpperCase()}),e&&r&&(r=r.charAt(0).toUpperCase()+r.slice(1)),r}var Vn=Kl;function sp(r,e,t){var a="{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}";function n(f){return f&&Ke(f)?f:"-"}function i(f){return!!(f!=null&&!isNaN(f)&&isFinite(f))}var o=e==="time",s=r instanceof Date;if(o||s){var l=o?Ue(r):r;if(isNaN(+l)){if(s)return"-"}else return Rs(l,a,t)}if(e==="ordinal")return $l(r)?n(r):Tt(r)&&i(r)?r+"":"-";var u=Br(r);return i(u)?ip(u):$l(r)?n(r):typeof r=="boolean"?r+"":"-"}var F1=["a","b","c","d","e","f","g"],lp=function(r,e){return"{"+r+(e==null?"":e)+"}"};function up(r,e,t){z(e)||(e=[e]);var a=e.length;if(!a)return"";for(var n=e[0].$vars||[],i=0;i':'';var o=t.markerId||"markerX";return{renderMode:i,content:"{"+o+"|} ",style:n==="subItem"?{width:4,height:4,borderRadius:2,backgroundColor:a}:{width:10,height:10,borderRadius:5,backgroundColor:a}}}function xE(r,e,t){(r==="week"||r==="month"||r==="quarter"||r==="half-year"||r==="year")&&(r=`MM-dd +yyyy`);var a=Ue(e),n=t?"getUTC":"get",i=a[n+"FullYear"](),o=a[n+"Month"]()+1,s=a[n+"Date"](),l=a[n+"Hours"](),u=a[n+"Minutes"](),f=a[n+"Seconds"](),h=a[n+"Milliseconds"]();return r=r.replace("MM",Be(o,2)).replace("M",o).replace("yyyy",i).replace("yy",Be(i%100+"",2)).replace("dd",Be(s,2)).replace("d",s).replace("hh",Be(l,2)).replace("h",l).replace("mm",Be(u,2)).replace("m",u).replace("ss",Be(f,2)).replace("s",f).replace("SSS",Be(h,3)),r}function bE(r){return r&&r.charAt(0).toUpperCase()+r.substr(1)}function zn(r,e){return e=e||"transparent",U(r)?r:J(r)&&r.colorStops&&(r.colorStops[0]||{}).color||e}function sf(r,e){if(e==="_blank"||e==="blank"){var t=window.open();t.opener=null,t.location.href=r}else window.open(r,e)}var lf=A,W1=["left","right","top","bottom","width","height"],Gn=[["width","left","right"],["height","top","bottom"]];function fp(r,e,t,a,n){var i=0,o=0;a==null&&(a=Infinity),n==null&&(n=Infinity);var s=0;e.eachChild(function(l,u){var f=l.getBoundingRect(),h=e.childAt(u+1),v=h&&h.getBoundingRect(),c,p;if(r==="horizontal"){var d=f.width+(v?-v.x+f.x:0);c=i+d,c>a||l.newline?(i=0,c=d,o+=s+t,s=f.height):s=Math.max(s,f.height)}else{var g=f.height+(v?-v.y+f.y:0);p=o+g,p>n||l.newline?(i+=s+t,o=0,p=g,s=f.width):s=Math.max(s,f.width)}l.newline||(l.x=i,l.y=o,l.markRedraw(),r==="horizontal"?i=c+t:o=p+t)})}var Fn=fp,m7=it(fp,"vertical"),_7=it(fp,"horizontal");function wE(r,e,t){var a=e.width,n=e.height,i=H(r.left,a),o=H(r.top,n),s=H(r.right,a),l=H(r.bottom,n);return(isNaN(i)||isNaN(parseFloat(r.left)))&&(i=0),(isNaN(s)||isNaN(parseFloat(r.right)))&&(s=a),(isNaN(o)||isNaN(parseFloat(r.top)))&&(o=0),(isNaN(l)||isNaN(parseFloat(r.bottom)))&&(l=n),t=Vn(t||0),{width:Math.max(s-i-t[1]-t[3],0),height:Math.max(l-o-t[0]-t[2],0)}}function jt(r,e,t){t=Vn(t||0);var a=e.width,n=e.height,i=H(r.left,a),o=H(r.top,n),s=H(r.right,a),l=H(r.bottom,n),u=H(r.width,a),f=H(r.height,n),h=t[2]+t[0],v=t[1]+t[3],c=r.aspect;switch(isNaN(u)&&(u=a-s-v-i),isNaN(f)&&(f=n-l-h-o),c!=null&&(isNaN(u)&&isNaN(f)&&(c>a/n?u=a*.8:f=n*.8),isNaN(u)&&(u=c*f),isNaN(f)&&(f=u/c)),isNaN(i)&&(i=a-s-u-v),isNaN(o)&&(o=n-l-f-h),r.left||r.right){case"center":i=a/2-u/2-t[3];break;case"right":i=a-u-v;break}switch(r.top||r.bottom){case"middle":case"center":o=n/2-f/2-t[0];break;case"bottom":o=n-f-h;break}i=i||0,o=o||0,isNaN(u)&&(u=a-v-i-(s||0)),isNaN(f)&&(f=n-h-o-(l||0));var p=new ft(i+t[3],o+t[0],u,f);return p.margin=t,p}function uf(r,e,t,a,n,i){var o=!n||!n.hv||n.hv[0],s=!n||!n.hv||n.hv[1],l=n&&n.boundingMode||"all";if(i=i||r,i.x=r.x,i.y=r.y,!o&&!s)return!1;var u;if(l==="raw")u=r.type==="group"?new ft(0,0,+e.width||0,+e.height||0):r.getBoundingRect();else if(u=r.getBoundingRect(),r.needLocalTransform()){var f=r.getLocalTransform();u=u.clone(),u.applyTransform(f)}var h=jt(j({width:u.width,height:u.height},e),t,a),v=o?h.x-u.x:0,c=s?h.y-u.y:0;return l==="raw"?(i.x=v,i.y=c):(i.x+=v,i.y+=c),i===r&&r.markRedraw(),!0}function TE(r,e){return r[Gn[e][0]]!=null||r[Gn[e][1]]!=null&&r[Gn[e][2]]!=null}function ks(r){var e=r.layoutMode||r.constructor.layoutMode;return J(e)?e:e?{type:e}:null}function Ya(r,e,t){var a=t&&t.ignoreSize;!z(a)&&(a=[a,a]);var n=o(Gn[0],0),i=o(Gn[1],1);u(Gn[0],r,n),u(Gn[1],r,i);function o(f,h){var v={},c=0,p={},d=0,g=2;if(lf(f,function(_){p[_]=r[_]}),lf(f,function(_){s(e,_)&&(v[_]=p[_]=e[_]),l(v,_)&&c++,l(p,_)&&d++}),a[h])return l(e,f[1])?p[f[2]]=null:l(e,f[2])&&(p[f[1]]=null),p;if(d===g||!c)return p;if(c>=g)return v;for(var y=0;y=0;l--)s=ot(s,n[l],!0);a.defaultOption=s}return a.defaultOption},e.prototype.getReferringComponents=function(t,a){var n=t+"Index",i=t+"Id";return hs(this.ecModel,t,{index:this.get(n,!0),id:this.get(i,!0)},a)},e.prototype.getBoxLayoutParams=function(){var t=this;return{left:t.get("left"),top:t.get("top"),right:t.get("right"),bottom:t.get("bottom"),width:t.get("width"),height:t.get("height")}},e.prototype.getZLevelKey=function(){return""},e.prototype.setZLevel=function(t){this.option.zlevel=t},e.protoInitialize=function(){var t=e.prototype;t.type="component",t.id="",t.name="",t.mainType="",t.subType="",t.componentIndex=0}(),e}(Mt);r_(gt,Mt),Au(gt),uE(gt),fE(gt,AE);function AE(r){var e=[];return A(gt.getClassesByMainType(r),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=G(e,function(t){return Vr(t).main}),r!=="dataset"&&vt(e,"dataset")<=0&&e.unshift("dataset"),e}var Y1="";typeof navigator!="undefined"&&(Y1=navigator.platform||"");var ji="rgba(0, 0, 0, 0.2)",DE={darkMode:"auto",colorBy:"series",color:["#5470c6","#91cc75","#fac858","#ee6666","#73c0de","#3ba272","#fc8452","#9a60b4","#ea7ccc"],gradientColor:["#f6efa6","#d88273","#bf444c"],aria:{decal:{decals:[{color:ji,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:ji,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:ji,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:ji,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:ji,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:ji,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Y1.match(/^Win/)?"Microsoft YaHei":"sans-serif",fontSize:12,fontStyle:"normal",fontWeight:"normal"},blendMode:null,stateAnimation:{duration:300,easing:"cubicOut"},animation:"auto",animationDuration:1e3,animationDurationUpdate:500,animationEasing:"cubicInOut",animationEasingUpdate:"cubicInOut",animationThreshold:2e3,progressiveThreshold:3e3,progressive:400,hoverLayerThreshold:3e3,useUTC:!1},X1=$(["tooltip","label","itemName","itemId","itemGroupId","seriesName"]),or="original",xe="arrayRows",sr="objectRows",Ur="keyedColumns",Xa="typedArray",Z1="unknown",Yr="column",Qi="row",ce={Must:1,Might:2,Not:3},$1=Ct();function ME(r){$1(r).datasetMap=$()}function q1(r,e,t){var a={},n=vp(e);if(!n||!r)return a;var i=[],o=[],s=e.ecModel,l=$1(s).datasetMap,u=n.uid+"_"+t.seriesLayoutBy,f,h;r=r.slice(),A(r,function(d,g){var y=J(d)?d:r[g]={name:d};y.type==="ordinal"&&f==null&&(f=g,h=p(y)),a[y.name]=[]});var v=l.get(u)||l.set(u,{categoryWayDim:h,valueWayDim:0});A(r,function(d,g){var y=d.name,m=p(d);if(f==null){var _=v.valueWayDim;c(a[y],_,m),c(o,_,m),v.valueWayDim+=m}else if(f===g)c(a[y],0,m),c(i,0,m);else{var _=v.categoryWayDim;c(a[y],_,m),c(o,_,m),v.categoryWayDim+=m}});function c(d,g,y){for(var m=0;me)return r[a];return r[t-1]}function J1(r,e,t,a,n,i,o){i=i||r;var s=e(i),l=s.paletteIdx||0,u=s.paletteNameMap=s.paletteNameMap||{};if(u.hasOwnProperty(n))return u[n];var f=o==null||!a?t:EE(a,o);if(f=f||t,!(!f||!f.length)){var h=f[l];return n&&(u[n]=h),s.paletteIdx=(l+1)%f.length,h}}function kE(r,e){e(r).paletteIdx=0,e(r).paletteNameMap={}}var ff,Os,tS,eS="\0_ec_inner",OE=1,gp=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.init=function(t,a,n,i,o,s){i=i||{},this.option=null,this._theme=new Mt(i),this._locale=new Mt(o),this._optionManager=s},e.prototype.setOption=function(t,a,n){var i=nS(a);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,a){return this._resetOption(t,nS(a))},e.prototype._resetOption=function(t,a){var n=!1,i=this._optionManager;if(!t||t==="recreate"){var o=i.mountOption(t==="recreate");!this.option||t==="recreate"?tS(this,o):(this.restoreData(),this._mergeOption(o,a)),n=!0}if((t==="timeline"||t==="media")&&this.restoreData(),!t||t==="recreate"||t==="timeline"){var s=i.getTimelineOption(this);s&&(n=!0,this._mergeOption(s,a))}if(!t||t==="recreate"||t==="media"){var l=i.getMediaOption(this);l.length&&A(l,function(u){n=!0,this._mergeOption(u,a)},this)}return n},e.prototype.mergeOption=function(t){this._mergeOption(t,null)},e.prototype._mergeOption=function(t,a){var n=this.option,i=this._componentsMap,o=this._componentsCount,s=[],l=$(),u=a&&a.replaceMergeMainTypeMap;ME(this),A(t,function(h,v){h!=null&&(gt.hasClass(v)?v&&(s.push(v),l.set(v,!0)):n[v]=n[v]==null?et(h):ot(n[v],h,!0))}),u&&u.each(function(h,v){gt.hasClass(v)&&!l.get(v)&&(s.push(v),l.set(v,!0))}),gt.topologicalTravel(s,gt.getAllClassMainTypes(),f,this);function f(h){var v=PE(this,h,Et(t[h])),c=i.get(h),p=c?u&&u.get(h)?"replaceMerge":"normalMerge":"replaceAll",d=j0(c,v,p);uP(d,h,gt),n[h]=null,i.set(h,null),o.set(h,0);var g=[],y=[],m=0,_;A(d,function(S,b){var x=S.existing,w=S.newOption;if(!w)x&&(x.mergeOption({},this),x.optionUpdated({},!1));else{var T=h==="series",C=gt.getClass(h,S.keyInfo.subType,!T);if(!C)return;if(h==="tooltip"){if(_)return;_=!0}if(x&&x.constructor===C)x.name=S.keyInfo.name,x.mergeOption(w,this),x.optionUpdated(w,!1);else{var D=B({componentIndex:b},S.keyInfo);x=new C(w,this,this,D),B(x,D),S.brandNew&&(x.__requireNewView=!0),x.init(w,this,this),x.optionUpdated(null,!0)}}x?(g.push(x.option),y.push(x),m++):(g.push(void 0),y.push(void 0))},this),n[h]=g,i.set(h,y),o.set(h,m),h==="series"&&ff(this)}this._seriesIndices||ff(this)},e.prototype.getOption=function(){var t=et(this.option);return A(t,function(a,n){if(gt.hasClass(n)){for(var i=Et(a),o=i.length,s=!1,l=o-1;l>=0;l--)i[l]&&!us(i[l])?s=!0:(i[l]=null,!s&&o--);i.length=o,t[n]=i}}),delete t[eS],t},e.prototype.getTheme=function(){return this._theme},e.prototype.getLocaleModel=function(){return this._locale},e.prototype.setUpdatePayload=function(t){this._payload=t},e.prototype.getUpdatePayload=function(){return this._payload},e.prototype.getComponent=function(t,a){var n=this._componentsMap.get(t);if(n){var i=n[a||0];if(i)return i;if(a==null){for(var o=0;o=e:t==="max"?r<=e:r===e}function UE(r,e){return r.join(",")===e.join(",")}var Dr=A,Ns=J,oS=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function mp(r){var e=r&&r.itemStyle;if(!!e)for(var t=0,a=oS.length;t=0;g--){var y=r[g];if(s||(p=y.data.rawIndexOf(y.stackedByDimension,c)),p>=0){var m=y.data.getByRawIndex(y.stackResultDimension,p);if(l==="all"||l==="positive"&&m>0||l==="negative"&&m<0||l==="samesign"&&v>=0&&m>0||l==="samesign"&&v<=0&&m<0){v=K2(v,m),d=m;break}}}return a[0]=v,a[1]=d,a})})}var hf=function(){function r(e){this.data=e.data||(e.sourceFormat===Ur?{}:[]),this.sourceFormat=e.sourceFormat||Z1,this.seriesLayoutBy=e.seriesLayoutBy||Yr,this.startIndex=e.startIndex||0,this.dimensionsDetectedCount=e.dimensionsDetectedCount,this.metaRawOption=e.metaRawOption;var t=this.dimensionsDefine=e.dimensionsDefine;if(t)for(var a=0;ad&&(d=_)}c[0]=p,c[1]=d}},n=function(){return this._data?this._data.length/this._dimSize:0};yS=(e={},e[xe+"_"+Yr]={pure:!0,appendData:i},e[xe+"_"+Qi]={pure:!0,appendData:function(){throw new Error('Do not support appendData when set seriesLayoutBy: "row".')}},e[sr]={pure:!0,appendData:i},e[Ur]={pure:!0,appendData:function(o){var s=this._data;A(o,function(l,u){for(var f=s[u]||(s[u]=[]),h=0;h<(l||[]).length;h++)f.push(l[h])})}},e[or]={appendData:i},e[Xa]={persistent:!1,pure:!0,appendData:function(o){this._data=o},clean:function(){this._offset+=this.count(),this._data=null}},e);function i(o){for(var s=0;s=0&&(d=o.interpolatedValue[g])}return d!=null?d+"":""})}},r.prototype.getRawValue=function(e,t){return to(this.getData(t),e)},r.prototype.formatTooltip=function(e,t,a){},r}();function CS(r){var e,t;return J(r)?r.type&&(t=r):e=r,{text:e,frag:t}}function zs(r){return new sk(r)}var sk=function(){function r(e){e=e||{},this._reset=e.reset,this._plan=e.plan,this._count=e.count,this._onDirty=e.onDirty,this._dirty=!0}return r.prototype.perform=function(e){var t=this._upstream,a=e&&e.skip;if(this._dirty&&t){var n=this.context;n.data=n.outputData=t.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this);var i;this._plan&&!a&&(i=this._plan(this.context));var o=f(this._modBy),s=this._modDataCount||0,l=f(e&&e.modBy),u=e&&e.modDataCount||0;(o!==l||s!==u)&&(i="reset");function f(m){return!(m>=1)&&(m=1),m}var h;(this._dirty||i==="reset")&&(this._dirty=!1,h=this._doReset(a)),this._modBy=l,this._modDataCount=u;var v=e&&e.step;if(t?this._dueEnd=t._outputDueEnd:this._dueEnd=this._count?this._count(this.context):Infinity,this._progress){var c=this._dueIndex,p=Math.min(v!=null?this._dueIndex+v:Infinity,this._dueEnd);if(!a&&(h||c1&&a>0?s:o}};return i;function o(){return e=r?null:le},gte:function(r,e){return r>=e}},uk=function(){function r(e,t){if(!Tt(t)){var a="";It(a)}this._opFn=MS[e],this._rvalFloat=Br(t)}return r.prototype.evaluate=function(e){return Tt(e)?this._opFn(e,this._rvalFloat):this._opFn(Br(e),this._rvalFloat)},r}(),IS=function(){function r(e,t){var a=e==="desc";this._resultLT=a?1:-1,t==null&&(t=a?"min":"max"),this._incomparable=t==="min"?-Infinity:Infinity}return r.prototype.evaluate=function(e,t){var a=Tt(e)?e:Br(e),n=Tt(t)?t:Br(t),i=isNaN(a),o=isNaN(n);if(i&&(a=this._incomparable),o&&(n=this._incomparable),i&&o){var s=U(e),l=U(t);s&&(a=l?e:0),l&&(n=s?t:0)}return an?-this._resultLT:0},r}(),fk=function(){function r(e,t){this._rval=t,this._isEQ=e,this._rvalTypeof=typeof t,this._rvalFloat=Br(t)}return r.prototype.evaluate=function(e){var t=e===this._rval;if(!t){var a=typeof e;a!==this._rvalTypeof&&(a==="number"||this._rvalTypeof==="number")&&(t=Br(e)===this._rvalFloat)}return this._isEQ?t:!t},r}();function hk(r,e){return r==="eq"||r==="ne"?new fk(r==="eq",e):X(MS,r)?new uk(r,e):null}var vk=function(){function r(){}return r.prototype.getRawData=function(){throw new Error("not supported")},r.prototype.getRawDataItem=function(e){throw new Error("not supported")},r.prototype.cloneRawData=function(){},r.prototype.getDimensionInfo=function(e){},r.prototype.cloneAllDimensionInfo=function(){},r.prototype.count=function(){},r.prototype.retrieveValue=function(e,t){},r.prototype.retrieveValueFromItem=function(e,t){},r.prototype.convertValue=function(e,t){return Za(e,t)},r}();function ck(r,e){var t=new vk,a=r.data,n=t.sourceFormat=r.sourceFormat,i=r.startIndex,o="";r.seriesLayoutBy!==Yr&&It(o);var s=[],l={},u=r.dimensionsDefine;if(u)A(u,function(d,g){var y=d.name,m={index:g,name:y,displayName:d.displayName};if(s.push(m),y!=null){var _="";X(l,y)&&It(_),l[y]=m}});else for(var f=0;f65535?xk:bk}function eo(){return[Infinity,-Infinity]}function wk(r){var e=r.constructor;return e===Array?r.slice():new e(r)}function kS(r,e,t,a,n){var i=ES[t||"float"];if(n){var o=r[e],s=o&&o.length;if(s!==a){for(var l=new i(a),u=0;ug[1]&&(g[1]=d)}return this._rawCount=this._count=l,{start:s,end:l}},r.prototype._initDataFromProvider=function(e,t,a){for(var n=this._provider,i=this._chunks,o=this._dimensions,s=o.length,l=this._rawExtent,u=G(o,function(m){return m.property}),f=0;fy[1]&&(y[1]=g)}}!n.persistent&&n.clean&&n.clean(),this._rawCount=this._count=t,this._extent=[]},r.prototype.count=function(){return this._count},r.prototype.get=function(e,t){if(!(t>=0&&t=0&&t=this._rawCount||e<0)return-1;if(!this._indices)return e;var t=this._indices,a=t[e];if(a!=null&&ae)i=o-1;else return o}return-1},r.prototype.indicesOfNearest=function(e,t,a){var n=this._chunks,i=n[e],o=[];if(!i)return o;a==null&&(a=Infinity);for(var s=Infinity,l=-1,u=0,f=0,h=this.count();f=0&&l<0)&&(s=p,l=c,u=0),c===l&&(o[u++]=f))}return o.length=u,o},r.prototype.getIndices=function(){var e,t=this._indices;if(t){var a=t.constructor,n=this._count;if(a===Array){e=new a(n);for(var i=0;i=h&&m<=v||isNaN(m))&&(l[u++]=d),d++}p=!0}else if(i===2){for(var g=c[n[0]],_=c[n[1]],S=e[n[1]][0],b=e[n[1]][1],y=0;y=h&&m<=v||isNaN(m))&&(x>=S&&x<=b||isNaN(x))&&(l[u++]=d),d++}p=!0}}if(!p)if(i===1)for(var y=0;y=h&&m<=v||isNaN(m))&&(l[u++]=w)}else for(var y=0;ye[D][1])&&(T=!1)}T&&(l[u++]=t.getRawIndex(y))}return uy[1]&&(y[1]=g)}}}},r.prototype.lttbDownSample=function(e,t){var a=this.clone([e],!0),n=a._chunks,i=n[e],o=this.count(),s=0,l=Math.floor(1/t),u=this.getRawIndex(0),f,h,v,c=new(Gs(this._rawCount))(Math.min((Math.ceil(o/l)+2)*2,o));c[s++]=u;for(var p=1;pf&&(f=h,v=S)}M>0&&Mf-p&&(l=f-p,s.length=l);for(var d=0;dh[1]&&(h[1]=y),v[c++]=m}return i._count=c,i._indices=v,i._updateGetRawIdx(),i},r.prototype.each=function(e,t){if(!!this._count)for(var a=e.length,n=this._chunks,i=0,o=this.count();il&&(l=h)}return o=[s,l],this._extent[e]=o,o},r.prototype.getRawDataItem=function(e){var t=this.getRawIndex(e);if(this._provider.persistent)return this._provider.getItem(t);for(var a=[],n=this._chunks,i=0;i=0?this._indices[e]:-1},r.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},r.internalField=function(){function e(t,a,n,i){return Za(t[i],this._dimensions[i])}Dp={arrayRows:e,objectRows:function(t,a,n,i){return Za(t[a],this._dimensions[i])},keyedColumns:e,original:function(t,a,n,i){var o=t&&(t.value==null?t:t.value);return Za(o instanceof Array?o[i]:o,this._dimensions[i])},typedArray:function(t,a,n,i){return t[i]}}}(),r}(),OS=function(){function r(e){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=e}return r.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},r.prototype._setLocalSource=function(e,t){this._sourceList=e,this._upstreamSignList=t,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},r.prototype._getVersionSign=function(){return this._sourceHost.uid+"_"+this._versionSignBase},r.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},r.prototype._createSource=function(){this._setLocalSource([],[]);var e=this._sourceHost,t=this._getUpstreamSourceManagers(),a=!!t.length,n,i;if(cf(e)){var o=e,s=void 0,l=void 0,u=void 0;if(a){var f=t[0];f.prepareSource(),u=f.getSource(),s=u.data,l=u.sourceFormat,i=[f._getVersionSign()]}else s=o.get("data",!0),l=Ee(s)?Xa:or,i=[];var h=this._getSourceMetaRawOption()||{},v=u&&u.metaRawOption||{},c=lt(h.seriesLayoutBy,v.seriesLayoutBy)||null,p=lt(h.sourceHeader,v.sourceHeader),d=lt(h.dimensions,v.dimensions),g=c!==v.seriesLayoutBy||!!p!=!!v.sourceHeader||d;n=g?[xp(s,{seriesLayoutBy:c,sourceHeader:p,dimensions:d},l)]:[]}else{var y=e;if(a){var m=this._applyTransform(t);n=m.sourceList,i=m.upstreamSignList}else{var _=y.get("source",!0);n=[xp(_,this._getSourceMetaRawOption(),null)],i=[]}}this._setLocalSource(n,i)},r.prototype._applyTransform=function(e){var t=this._sourceHost,a=t.get("transform",!0),n=t.get("fromTransformResult",!0);if(n!=null){var i="";e.length!==1&&BS(i)}var o,s=[],l=[];return A(e,function(u){u.prepareSource();var f=u.getSource(n||0),h="";n!=null&&!f&&BS(h),s.push(f),l.push(u._getVersionSign())}),a?o=_k(a,s,{datasetIndex:t.componentIndex}):n!=null&&(o=[tk(s[0])]),{sourceList:o,upstreamSignList:l}},r.prototype._isDirty=function(){if(this._dirty)return!0;for(var e=this._getUpstreamSourceManagers(),t=0;t1||t>0&&!r.noHeader;return A(r.blocks,function(n){var i=FS(n);i>=e&&(e=i+ +(a&&(!i||Ip(n)&&!n.noHeader)))}),e}return 0}function Ak(r,e,t,a){var n=e.noHeader,i=Mk(FS(e)),o=[],s=e.blocks||[];de(!s||z(s)),s=s||[];var l=r.orderMode;if(e.sortBlocks&&l){s=s.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(X(u,l)){var f=new IS(u[l],null);s.sort(function(p,d){return f.evaluate(p.sortParam,d.sortParam)})}else l==="seriesDesc"&&s.reverse()}A(s,function(p,d){var g=e.valueFormatter,y=GS(p)(g?B(B({},r),{valueFormatter:g}):r,p,d>0?i.html:0,a);y!=null&&o.push(y)});var h=r.renderMode==="richText"?o.join(i.richText):Lp(o.join(""),n?t:i.html);if(n)return h;var v=sp(e.header,"ordinal",r.useUTC),c=zS(a,r.renderMode).nameStyle;return r.renderMode==="richText"?WS(r,v,c)+i.richText+h:Lp('
    '+Ce(v)+"
    "+h,t)}function Dk(r,e,t,a){var n=r.renderMode,i=e.noName,o=e.noValue,s=!e.markerType,l=e.name,u=r.useUTC,f=e.valueFormatter||r.valueFormatter||function(S){return S=z(S)?S:[S],G(S,function(b,x){return sp(b,z(c)?c[x]:c,u)})};if(!(i&&o)){var h=s?"":r.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||"#333",n),v=i?"":sp(l,"ordinal",u),c=e.valueType,p=o?[]:f(e.value),d=!s||!i,g=!s&&i,y=zS(a,n),m=y.nameStyle,_=y.valueStyle;return n==="richText"?(s?"":h)+(i?"":WS(r,v,m))+(o?"":Pk(r,p,d,g,_)):Lp((s?"":h)+(i?"":Ik(v,!s,m))+(o?"":Lk(p,d,g,_)),t)}}function HS(r,e,t,a,n,i){if(!!r){var o=GS(r),s={useUTC:n,renderMode:t,orderMode:a,markupStyleCreator:e,valueFormatter:r.valueFormatter};return o(s,r,0,i)}}function Mk(r){return{html:Tk[r],richText:Ck[r]}}function Lp(r,e){var t='
    ',a="margin: "+e+"px 0 0";return'
    '+r+t+"
    "}function Ik(r,e,t){var a=e?"margin-left:2px":"";return''+Ce(r)+""}function Lk(r,e,t,a){var n=t?"10px":"20px",i=e?"float:right;margin-left:"+n:"";return r=z(r)?r:[r],''+G(r,function(o){return Ce(o)}).join("  ")+""}function WS(r,e,t){return r.markupStyleCreator.wrapRichTextStyle(e,t)}function Pk(r,e,t,a,n){var i=[n],o=a?10:20;return t&&i.push({padding:[0,0,0,o],align:"right"}),r.markupStyleCreator.wrapRichTextStyle(z(e)?e.join(" "):e,i)}function US(r,e){var t=r.getData().getItemVisual(e,"style"),a=t[r.visualDrawType];return zn(a)}function YS(r,e){var t=r.get("padding");return t!=null?t:e==="richText"?[8,10]:10}var Pp=function(){function r(){this.richTextStyles={},this._nextStyleNameId=W0()}return r.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},r.prototype.makeTooltipMarker=function(e,t,a){var n=a==="richText"?this._generateStyleName():null,i=H1({color:t,type:e,renderMode:a,markerId:n});return U(i)?i:(this.richTextStyles[n]=i.style,i.content)},r.prototype.wrapRichTextStyle=function(e,t){var a={};z(t)?A(t,function(i){return B(a,i)}):B(a,t);var n=this._generateStyleName();return this.richTextStyles[n]=a,"{"+n+"|"+e+"}"},r}();function XS(r){var e=r.series,t=r.dataIndex,a=r.multipleSeries,n=e.getData(),i=n.mapDimensionsAll("defaultedTooltip"),o=i.length,s=e.getRawValue(t),l=z(s),u=US(e,t),f,h,v,c;if(o>1||l&&!o){var p=Rk(s,e,t,i,u);f=p.inlineValues,h=p.inlineValueTypes,v=p.blocks,c=p.inlineValues[0]}else if(o){var d=n.getDimensionInfo(i[0]);c=f=to(n,t,i[0]),h=d.type}else c=f=l?s[0]:s;var g=oc(e),y=g&&e.name||"",m=n.getName(t),_=a?y:m;return ie("section",{header:y,noHeader:a||!g,sortParam:c,blocks:[ie("nameValue",{markerType:"item",markerColor:u,name:_,noName:!Ke(_),value:f,valueType:h})].concat(v||[])})}function Rk(r,e,t,a,n){var i=e.getData(),o=qe(r,function(h,v,c){var p=i.getDimensionInfo(c);return h=h||p&&p.tooltip!==!1&&p.displayName!=null},!1),s=[],l=[],u=[];a.length?A(a,function(h){f(to(i,t,h),h)}):A(r,f);function f(h,v){var c=i.getDimensionInfo(v);!c||c.otherDims.tooltip===!1||(o?u.push(ie("nameValue",{markerType:"subItem",markerColor:n,name:c.displayName,value:h,valueType:c.type})):(s.push(h),l.push(c.type)))}return{inlineValues:s,inlineValueTypes:l,blocks:u}}var $a=Ct();function pf(r,e){return r.getName(e)||r.getId(e)}var df="__universalTransitionEnabled",kt=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t._selectedDataIndicesMap={},t}return e.prototype.init=function(t,a,n){this.seriesIndex=this.componentIndex,this.dataTask=zs({count:kk,reset:Ok}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n);var i=$a(this).sourceManager=new OS(this);i.prepareSource();var o=this.getInitialData(t,n);$S(o,this),this.dataTask.context.data=o,$a(this).dataBeforeProcessed=o,ZS(this),this._initSelectedMapFromData(o)},e.prototype.mergeDefaultAndTheme=function(t,a){var n=ks(this),i=n?Ki(t):{},o=this.subType;gt.hasClass(o)&&(o+="Series"),ot(t,a.getTheme().get(this.subType)),ot(t,this.getDefaultOption()),Sn(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Ya(t,i,n)},e.prototype.mergeOption=function(t,a){t=ot(this.option,t,!0),this.fillDataTextStyle(t.data);var n=ks(this);n&&Ya(this.option,t,n);var i=$a(this).sourceManager;i.dirty(),i.prepareSource();var o=this.getInitialData(t,a);$S(o,this),this.dataTask.dirty(),this.dataTask.context.data=o,$a(this).dataBeforeProcessed=o,ZS(this),this._initSelectedMapFromData(o)},e.prototype.fillDataTextStyle=function(t){if(t&&!Ee(t))for(var a=["show"],n=0;nthis.getShallow("animationThreshold")&&(a=!1),!!a},e.prototype.restoreData=function(){this.dataTask.dirty()},e.prototype.getColorFromPalette=function(t,a,n){var i=this.ecModel,o=pp.prototype.getColorFromPalette.call(this,t,a,n);return o||(o=i.getColorFromPalette(t,a,n)),o},e.prototype.coordDimToDataDim=function(t){return this.getRawData().mapDimensionsAll(t)},e.prototype.getProgressive=function(){return this.get("progressive")},e.prototype.getProgressiveThreshold=function(){return this.get("progressiveThreshold")},e.prototype.select=function(t,a){this._innerSelect(this.getData(a),t)},e.prototype.unselect=function(t,a){var n=this.option.selectedMap;if(!!n){var i=this.option.selectedMode,o=this.getData(a);if(i==="series"||n==="all"){this.option.selectedMap={},this._selectedDataIndicesMap={};return}for(var s=0;s=0&&n.push(o)}return n},e.prototype.isSelected=function(t,a){var n=this.option.selectedMap;if(!n)return!1;var i=this.getData(a);return(n==="all"||n[pf(i,t)])&&!i.getItemModel(t).get(["select","disabled"])},e.prototype.isUniversalTransitionEnabled=function(){if(this[df])return!0;var t=this.option.universalTransition;return t?t===!0?!0:t&&t.enabled:!1},e.prototype._innerSelect=function(t,a){var n,i,o=this.option,s=o.selectedMode,l=a.length;if(!(!s||!l)){if(s==="series")o.selectedMap="all";else if(s==="multiple"){J(o.selectedMap)||(o.selectedMap={});for(var u=o.selectedMap,f=0;f0&&this._innerSelect(t,a)}},e.registerClass=function(t){return gt.registerClass(t)},e.protoInitialize=function(){var t=e.prototype;t.type="series.__base__",t.seriesIndex=0,t.ignoreStyleOnData=!1,t.hasSymbolVisual=!1,t.defaultSymbol="circle",t.visualStyleAccessPath="itemStyle",t.visualDrawType="fill"}(),e}(gt);Xt(kt,Cp),Xt(kt,pp),r_(kt,gt);function ZS(r){var e=r.name;oc(r)||(r.name=Ek(r)||e)}function Ek(r){var e=r.getRawData(),t=e.mapDimensionsAll("seriesName"),a=[];return A(t,function(n){var i=e.getDimensionInfo(n);i.displayName&&a.push(i.displayName)}),a.join(" ")}function kk(r){return r.model.getRawData().count()}function Ok(r){var e=r.model;return e.setData(e.getRawData().cloneShallow()),Nk}function Nk(r,e){e.outputData&&r.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function $S(r,e){A(No(r.CHANGABLE_METHODS,r.DOWNSAMPLE_METHODS),function(t){r.wrapMethod(t,it(Bk,e))})}function Bk(r,e){var t=Rp(r);return t&&t.setOutputEnd((e||this).count()),e}function Rp(r){var e=(r.ecModel||{}).scheduler,t=e&&e.getPipeline(r.uid);if(t){var a=t.currentTask;if(a){var n=a.agentStubMap;n&&(a=n.get(r.uid))}return a}}var Bt=function(){function r(){this.group=new rt,this.uid=Zi("viewComponent")}return r.prototype.init=function(e,t){},r.prototype.render=function(e,t,a,n){},r.prototype.dispose=function(e,t){},r.prototype.updateView=function(e,t,a,n){},r.prototype.updateLayout=function(e,t,a,n){},r.prototype.updateVisual=function(e,t,a,n){},r.prototype.toggleBlurSeries=function(e,t,a){},r.prototype.eachRendered=function(e){var t=this.group;t&&t.traverse(e)},r}();uc(Bt),Au(Bt);function ro(){var r=Ct();return function(e){var t=r(e),a=e.pipelineContext,n=!!t.large,i=!!t.progressiveRender,o=t.large=!!(a&&a.large),s=t.progressiveRender=!!(a&&a.progressiveRender);return(n!==o||i!==s)&&"reset"}}var qS=Ct(),Vk=ro(),Rt=function(){function r(){this.group=new rt,this.uid=Zi("viewChart"),this.renderTask=zs({plan:zk,reset:Gk}),this.renderTask.context={view:this}}return r.prototype.init=function(e,t){},r.prototype.render=function(e,t,a,n){},r.prototype.highlight=function(e,t,a,n){var i=e.getData(n&&n.dataType);!i||jS(i,n,"emphasis")},r.prototype.downplay=function(e,t,a,n){var i=e.getData(n&&n.dataType);!i||jS(i,n,"normal")},r.prototype.remove=function(e,t){this.group.removeAll()},r.prototype.dispose=function(e,t){},r.prototype.updateView=function(e,t,a,n){this.render(e,t,a,n)},r.prototype.updateLayout=function(e,t,a,n){this.render(e,t,a,n)},r.prototype.updateVisual=function(e,t,a,n){this.render(e,t,a,n)},r.prototype.eachRendered=function(e){Wa(this.group,e)},r.markUpdateMethod=function(e,t){qS(e).updateMethod=t},r.protoInitialize=function(){var e=r.prototype;e.type="chart"}(),r}();function KS(r,e,t){r&&ms(r)&&(e==="emphasis"?va:ca)(r,t)}function jS(r,e,t){var a=xn(r,e),n=e&&e.highlightKey!=null?TR(e.highlightKey):null;a!=null?A(Et(a),function(i){KS(r.getItemGraphicEl(i),t,n)}):r.eachItemGraphicEl(function(i){KS(i,t,n)})}uc(Rt),Au(Rt);function zk(r){return Vk(r.model)}function Gk(r){var e=r.model,t=r.ecModel,a=r.api,n=r.payload,i=e.pipelineContext.progressiveRender,o=r.view,s=n&&qS(n).updateMethod,l=i?"incrementalPrepareRender":s&&o[s]?s:"render";return l!=="render"&&o[l](e,t,a,n),Fk[l]}var Fk={incrementalPrepareRender:{progress:function(r,e){e.view.incrementalRender(r,e.model,e.ecModel,e.api,e.payload)}},render:{forceFirstProgress:!0,progress:function(r,e){e.view.render(e.model,e.ecModel,e.api,e.payload)}}},gf="\0__throttleOriginMethod",QS="\0__throttleRate",JS="\0__throttleType";function yf(r,e,t){var a,n=0,i=0,o=null,s,l,u,f;e=e||0;function h(){i=new Date().getTime(),o=null,r.apply(l,u||[])}var v=function(){for(var c=[],p=0;p=0?h():o=setTimeout(h,-s),n=a};return v.clear=function(){o&&(clearTimeout(o),o=null)},v.debounceNextCall=function(c){f=c},v}function ao(r,e,t,a){var n=r[e];if(!!n){var i=n[gf]||n,o=n[JS],s=n[QS];if(s!==t||o!==a){if(t==null||!a)return r[e]=i;n=r[e]=yf(i,t,a==="debounce"),n[gf]=i,n[JS]=a,n[QS]=t}return n}}function Fs(r,e){var t=r[e];t&&t[gf]&&(t.clear&&t.clear(),r[e]=t[gf])}var tx=Ct(),ex={itemStyle:wn(M1,!0),lineStyle:wn(D1,!0)},Hk={lineStyle:"stroke",itemStyle:"fill"};function rx(r,e){var t=r.visualStyleMapper||ex[e];return t||(console.warn("Unknown style type '"+e+"'."),ex.itemStyle)}function ax(r,e){var t=r.visualDrawType||Hk[e];return t||(console.warn("Unknown style type '"+e+"'."),"fill")}var Wk={createOnAllSeries:!0,performRawSeries:!0,reset:function(r,e){var t=r.getData(),a=r.visualStyleAccessPath||"itemStyle",n=r.getModel(a),i=rx(r,a),o=i(n),s=n.getShallow("decal");s&&(t.setVisual("decal",s),s.dirty=!0);var l=ax(r,a),u=o[l],f=K(u)?u:null,h=o.fill==="auto"||o.stroke==="auto";if(!o[l]||f||h){var v=r.getColorFromPalette(r.name,null,e.getSeriesCount());o[l]||(o[l]=v,t.setVisual("colorFromPalette",!0)),o.fill=o.fill==="auto"||K(o.fill)?v:o.fill,o.stroke=o.stroke==="auto"||K(o.stroke)?v:o.stroke}if(t.setVisual("style",o),t.setVisual("drawType",l),!e.isSeriesFiltered(r)&&f)return t.setVisual("colorFromPalette",!1),{dataEach:function(c,p){var d=r.getDataParams(p),g=B({},o);g[l]=f(d),c.setItemVisual(p,"style",g)}}}},Hs=new Mt,Uk={createOnAllSeries:!0,performRawSeries:!0,reset:function(r,e){if(!(r.ignoreStyleOnData||e.isSeriesFiltered(r))){var t=r.getData(),a=r.visualStyleAccessPath||"itemStyle",n=rx(r,a),i=t.getVisual("drawType");return{dataEach:t.hasItemOption?function(o,s){var l=o.getRawDataItem(s);if(l&&l[a]){Hs.option=l[a];var u=n(Hs),f=o.ensureUniqueItemVisual(s,"style");B(f,u),Hs.option.decal&&(o.setItemVisual(s,"decal",Hs.option.decal),Hs.option.decal.dirty=!0),i in u&&o.setItemVisual(s,"colorFromPalette",!1)}}:null}}}},Yk={performRawSeries:!0,overallReset:function(r){var e=$();r.eachSeries(function(t){var a=t.getColorBy();if(!t.isColorBySeries()){var n=t.type+"-"+a,i=e.get(n);i||(i={},e.set(n,i)),tx(t).scope=i}}),r.eachSeries(function(t){if(!(t.isColorBySeries()||r.isSeriesFiltered(t))){var a=t.getRawData(),n={},i=t.getData(),o=tx(t).scope,s=t.visualStyleAccessPath||"itemStyle",l=ax(t,s);i.each(function(u){var f=i.getRawIndex(u);n[f]=u}),a.each(function(u){var f=n[u],h=i.getItemVisual(f,"colorFromPalette");if(h){var v=i.ensureUniqueItemVisual(f,"style"),c=a.getName(u)||u+"",p=a.count();v[l]=t.getColorFromPalette(c,o,p)}})}})}},mf=Math.PI;function Xk(r,e){e=e||{},j(e,{text:"loading",textColor:"#000",fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255, 255, 255, 0.8)",showSpinner:!0,color:"#5470c6",spinnerRadius:10,lineWidth:5,zlevel:0});var t=new rt,a=new xt({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});t.add(a);var n=new bt({style:{text:e.text,fill:e.textColor,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:e.fontFamily},zlevel:e.zlevel,z:10001}),i=new xt({style:{fill:"none"},textContent:n,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});t.add(i);var o;return e.showSpinner&&(o=new ws({shape:{startAngle:-mf/2,endAngle:-mf/2+.1,r:e.spinnerRadius},style:{stroke:e.color,lineCap:"round",lineWidth:e.lineWidth},zlevel:e.zlevel,z:10001}),o.animateShape(!0).when(1e3,{endAngle:mf*3/2}).start("circularInOut"),o.animateShape(!0).when(1e3,{startAngle:mf*3/2}).delay(300).start("circularInOut"),t.add(o)),t.resize=function(){var s=n.getBoundingRect().width,l=e.showSpinner?e.spinnerRadius:0,u=(r.getWidth()-l*2-(e.showSpinner&&s?10:0)-s)/2-(e.showSpinner&&s?0:5+s/2)+(e.showSpinner?0:s/2)+(s?0:l),f=r.getHeight()/2;e.showSpinner&&o.setShape({cx:u,cy:f}),i.setShape({x:u-l,y:f-l,width:l*2,height:l*2}),a.setShape({x:0,y:0,width:r.getWidth(),height:r.getHeight()})},t.resize(),t}var nx=function(){function r(e,t,a,n){this._stageTaskMap=$(),this.ecInstance=e,this.api=t,a=this._dataProcessorHandlers=a.slice(),n=this._visualHandlers=n.slice(),this._allHandlers=a.concat(n)}return r.prototype.restoreData=function(e,t){e.restoreData(t),this._stageTaskMap.each(function(a){var n=a.overallTask;n&&n.dirty()})},r.prototype.getPerformArgs=function(e,t){if(!!e.__pipeline){var a=this._pipelineMap.get(e.__pipeline.id),n=a.context,i=!t&&a.progressiveEnabled&&(!n||n.progressiveRender)&&e.__idxInPipeline>a.blockIndex,o=i?a.step:null,s=n&&n.modDataCount,l=s!=null?Math.ceil(s/o):null;return{step:o,modBy:l,modDataCount:s}}},r.prototype.getPipeline=function(e){return this._pipelineMap.get(e)},r.prototype.updateStreamModes=function(e,t){var a=this._pipelineMap.get(e.uid),n=e.getData(),i=n.count(),o=a.progressiveEnabled&&t.incrementalPrepareRender&&i>=a.threshold,s=e.get("large")&&i>=e.get("largeThreshold"),l=e.get("progressiveChunkMode")==="mod"?i:null;e.pipelineContext=a.context={progressiveRender:o,modDataCount:l,large:s}},r.prototype.restorePipelines=function(e){var t=this,a=t._pipelineMap=$();e.eachSeries(function(n){var i=n.getProgressive(),o=n.uid;a.set(o,{id:o,head:null,tail:null,threshold:n.getProgressiveThreshold(),progressiveEnabled:i&&!(n.preventIncremental&&n.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),t._pipe(n,n.dataTask)})},r.prototype.prepareStageTasks=function(){var e=this._stageTaskMap,t=this.api.getModel(),a=this.api;A(this._allHandlers,function(n){var i=e.get(n.uid)||e.set(n.uid,{}),o="";de(!(n.reset&&n.overallReset),o),n.reset&&this._createSeriesStageTask(n,i,t,a),n.overallReset&&this._createOverallStageTask(n,i,t,a)},this)},r.prototype.prepareView=function(e,t,a,n){var i=e.renderTask,o=i.context;o.model=t,o.ecModel=a,o.api=n,i.__block=!e.incrementalPrepareRender,this._pipe(t,i)},r.prototype.performDataProcessorTasks=function(e,t){this._performStageTasks(this._dataProcessorHandlers,e,t,{block:!0})},r.prototype.performVisualTasks=function(e,t,a){this._performStageTasks(this._visualHandlers,e,t,a)},r.prototype._performStageTasks=function(e,t,a,n){n=n||{};var i=!1,o=this;A(e,function(l,u){if(!(n.visualType&&n.visualType!==l.visualType)){var f=o._stageTaskMap.get(l.uid),h=f.seriesTaskMap,v=f.overallTask;if(v){var c,p=v.agentStubMap;p.each(function(g){s(n,g)&&(g.dirty(),c=!0)}),c&&v.dirty(),o.updatePayload(v,a);var d=o.getPerformArgs(v,n.block);p.each(function(g){g.perform(d)}),v.perform(d)&&(i=!0)}else h&&h.each(function(g,y){s(n,g)&&g.dirty();var m=o.getPerformArgs(g,n.block);m.skip=!l.performRawSeries&&t.isSeriesFiltered(g.context.model),o.updatePayload(g,a),g.perform(m)&&(i=!0)})}});function s(l,u){return l.setDirty&&(!l.dirtyMap||l.dirtyMap.get(u.__pipeline.id))}this.unfinished=i||this.unfinished},r.prototype.performSeriesTasks=function(e){var t;e.eachSeries(function(a){t=a.dataTask.perform()||t}),this.unfinished=t||this.unfinished},r.prototype.plan=function(){this._pipelineMap.each(function(e){var t=e.tail;do{if(t.__block){e.blockIndex=t.__idxInPipeline;break}t=t.getUpstream()}while(t)})},r.prototype.updatePayload=function(e,t){t!=="remain"&&(e.context.payload=t)},r.prototype._createSeriesStageTask=function(e,t,a,n){var i=this,o=t.seriesTaskMap,s=t.seriesTaskMap=$(),l=e.seriesType,u=e.getTargetSeries;e.createOnAllSeries?a.eachRawSeries(f):l?a.eachRawSeriesByType(l,f):u&&u(a,n).each(f);function f(h){var v=h.uid,c=s.set(v,o&&o.get(v)||zs({plan:jk,reset:Qk,count:tO}));c.context={model:h,ecModel:a,api:n,useClearVisual:e.isVisual&&!e.isLayout,plan:e.plan,reset:e.reset,scheduler:i},i._pipe(h,c)}},r.prototype._createOverallStageTask=function(e,t,a,n){var i=this,o=t.overallTask=t.overallTask||zs({reset:Zk});o.context={ecModel:a,api:n,overallReset:e.overallReset,scheduler:i};var s=o.agentStubMap,l=o.agentStubMap=$(),u=e.seriesType,f=e.getTargetSeries,h=!0,v=!1,c="";de(!e.createOnAllSeries,c),u?a.eachRawSeriesByType(u,p):f?f(a,n).each(p):(h=!1,A(a.getSeries(),p));function p(d){var g=d.uid,y=l.set(g,s&&s.get(g)||(v=!0,zs({reset:$k,onDirty:Kk})));y.context={model:d,overallProgress:h},y.agent=o,y.__block=h,i._pipe(d,y)}v&&o.dirty()},r.prototype._pipe=function(e,t){var a=e.uid,n=this._pipelineMap.get(a);!n.head&&(n.head=t),n.tail&&n.tail.pipe(t),n.tail=t,t.__idxInPipeline=n.count++,t.__pipeline=n},r.wrapStageHandler=function(e,t){return K(e)&&(e={overallReset:e,seriesType:eO(e)}),e.uid=Zi("stageHandler"),t&&(e.visualType=t),e},r}();function Zk(r){r.overallReset(r.ecModel,r.api,r.payload)}function $k(r){return r.overallProgress&&qk}function qk(){this.agent.dirty(),this.getDownstream().dirty()}function Kk(){this.agent&&this.agent.dirty()}function jk(r){return r.plan?r.plan(r.model,r.ecModel,r.api,r.payload):null}function Qk(r){r.useClearVisual&&r.data.clearAllVisual();var e=r.resetDefines=Et(r.reset(r.model,r.ecModel,r.api,r.payload));return e.length>1?G(e,function(t,a){return ix(a)}):Jk}var Jk=ix(0);function ix(r){return function(e,t){var a=t.data,n=t.resetDefines[r];if(n&&n.dataEach)for(var i=e.start;i0&&c===u.length-v.length){var p=u.slice(0,c);p!=="data"&&(t.mainType=p,t[v.toLowerCase()]=l,f=!0)}}s.hasOwnProperty(u)&&(a[u]=l,f=!0),f||(n[u]=l)})}return{cptQuery:t,dataQuery:a,otherQuery:n}},r.prototype.filter=function(e,t){var a=this.eventInfo;if(!a)return!0;var n=a.targetEl,i=a.packedEvent,o=a.model,s=a.view;if(!o||!s)return!0;var l=t.cptQuery,u=t.dataQuery;return f(l,o,"mainType")&&f(l,o,"subType")&&f(l,o,"index","componentIndex")&&f(l,o,"name")&&f(l,o,"id")&&f(u,i,"name")&&f(u,i,"dataIndex")&&f(u,i,"dataType")&&(!s.filterForExposedEvent||s.filterForExposedEvent(e,t.otherQuery,n,i));function f(h,v,c,p){return h[c]==null||v[p||c]===h[c]}},r.prototype.afterTrigger=function(){this.eventInfo=null},r}(),Ep=["symbol","symbolSize","symbolRotate","symbolOffset"],vx=Ep.concat(["symbolKeepAspect"]),nO={createOnAllSeries:!0,performRawSeries:!0,reset:function(r,e){var t=r.getData();if(r.legendIcon&&t.setVisual("legendIcon",r.legendIcon),!r.hasSymbolVisual)return;for(var a={},n={},i=!1,o=0;o=0&&Xn(l)?l:.5;var u=r.createRadialGradient(o,s,0,o,s,l);return u}function Op(r,e,t){for(var a=e.type==="radial"?_O(r,e,t):mO(r,e,t),n=e.colorStops,i=0;i0)?null:r==="dashed"?[4*e,2*e]:r==="dotted"?[e]:Tt(r)?[r]:z(r)?r:null}function Np(r){var e=r.style,t=e.lineDash&&e.lineWidth>0&&xO(e.lineDash,e.lineWidth),a=e.lineDashOffset;if(t){var n=e.strokeNoScale&&r.getLineScale?r.getLineScale():1;n&&n!==1&&(t=G(t,function(i){return i/n}),a/=n)}return[t,a]}var bO=new Hr(!0);function wf(r){var e=r.stroke;return!(e==null||e==="none"||!(r.lineWidth>0))}function dx(r){return typeof r=="string"&&r!=="none"}function Tf(r){var e=r.fill;return e!=null&&e!=="none"}function gx(r,e){if(e.fillOpacity!=null&&e.fillOpacity!==1){var t=r.globalAlpha;r.globalAlpha=e.fillOpacity*e.opacity,r.fill(),r.globalAlpha=t}else r.fill()}function yx(r,e){if(e.strokeOpacity!=null&&e.strokeOpacity!==1){var t=r.globalAlpha;r.globalAlpha=e.strokeOpacity*e.opacity,r.stroke(),r.globalAlpha=t}else r.stroke()}function Bp(r,e,t){var a=hc(e.image,e.__image,t);if(Du(a)){var n=r.createPattern(a,e.repeat||"repeat");if(typeof DOMMatrix=="function"&&n&&n.setTransform){var i=new DOMMatrix;i.translateSelf(e.x||0,e.y||0),i.rotateSelf(0,0,(e.rotation||0)*Vo),i.scaleSelf(e.scaleX||1,e.scaleY||1),n.setTransform(i)}return n}}function wO(r,e,t,a){var n,i=wf(t),o=Tf(t),s=t.strokePercent,l=s<1,u=!e.path;(!e.silent||l)&&u&&e.createPathProxy();var f=e.path||bO,h=e.__dirty;if(!a){var v=t.fill,c=t.stroke,p=o&&!!v.colorStops,d=i&&!!c.colorStops,g=o&&!!v.image,y=i&&!!c.image,m=void 0,_=void 0,S=void 0,b=void 0,x=void 0;(p||d)&&(x=e.getBoundingRect()),p&&(m=h?Op(r,v,x):e.__canvasFillGradient,e.__canvasFillGradient=m),d&&(_=h?Op(r,c,x):e.__canvasStrokeGradient,e.__canvasStrokeGradient=_),g&&(S=h||!e.__canvasFillPattern?Bp(r,v,e):e.__canvasFillPattern,e.__canvasFillPattern=S),y&&(b=h||!e.__canvasStrokePattern?Bp(r,c,e):e.__canvasStrokePattern,e.__canvasStrokePattern=S),p?r.fillStyle=m:g&&(S?r.fillStyle=S:o=!1),d?r.strokeStyle=_:y&&(b?r.strokeStyle=b:i=!1)}var w=e.getGlobalScale();f.setScale(w[0],w[1],e.segmentIgnoreThreshold);var T,C;r.setLineDash&&t.lineDash&&(n=Np(e),T=n[0],C=n[1]);var D=!0;(u||h&wi)&&(f.setDPR(r.dpr),l?f.setContext(null):(f.setContext(r),D=!1),f.reset(),e.buildPath(f,e.shape,a),f.toStatic(),e.pathUpdated()),D&&f.rebuildPath(r,l?s:1),T&&(r.setLineDash(T),r.lineDashOffset=C),a||(t.strokeFirst?(i&&yx(r,t),o&&gx(r,t)):(o&&gx(r,t),i&&yx(r,t))),T&&r.setLineDash([])}function TO(r,e,t){var a=e.__image=hc(t.image,e.__image,e,e.onload);if(!(!a||!Du(a))){var n=t.x||0,i=t.y||0,o=e.getWidth(),s=e.getHeight(),l=a.width/a.height;if(o==null&&s!=null?o=s*l:s==null&&o!=null?s=o/l:o==null&&s==null&&(o=a.width,s=a.height),t.sWidth&&t.sHeight){var u=t.sx||0,f=t.sy||0;r.drawImage(a,u,f,t.sWidth,t.sHeight,n,i,o,s)}else if(t.sx&&t.sy){var u=t.sx,f=t.sy,h=o-u,v=s-f;r.drawImage(a,u,f,h,v,n,i,o,s)}else r.drawImage(a,n,i,o,s)}}function CO(r,e,t){var a,n=t.text;if(n!=null&&(n+=""),n){r.font=t.font||Ca,r.textAlign=t.textAlign,r.textBaseline=t.textBaseline;var i=void 0,o=void 0;r.setLineDash&&t.lineDash&&(a=Np(e),i=a[0],o=a[1]),i&&(r.setLineDash(i),r.lineDashOffset=o),t.strokeFirst?(wf(t)&&r.strokeText(n,t.x,t.y),Tf(t)&&r.fillText(n,t.x,t.y)):(Tf(t)&&r.fillText(n,t.x,t.y),wf(t)&&r.strokeText(n,t.x,t.y)),i&&r.setLineDash([])}}var mx=["shadowBlur","shadowOffsetX","shadowOffsetY"],_x=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Sx(r,e,t,a,n){var i=!1;if(!a&&(t=t||{},e===t))return!1;if(a||e.opacity!==t.opacity){Ve(r,n),i=!0;var o=Math.max(Math.min(e.opacity,1),0);r.globalAlpha=isNaN(o)?Tn.opacity:o}(a||e.blend!==t.blend)&&(i||(Ve(r,n),i=!0),r.globalCompositeOperation=e.blend||Tn.blend);for(var s=0;s0&&t.unfinished);t.unfinished||this._zr.flush()}}},e.prototype.getDom=function(){return this._dom},e.prototype.getId=function(){return this.id},e.prototype.getZr=function(){return this._zr},e.prototype.isSSR=function(){return this._ssr},e.prototype.setOption=function(t,a,n){if(!this[we]){if(this._disposed){Xe(this.id);return}var i,o,s;if(J(a)&&(n=a.lazyUpdate,i=a.silent,o=a.replaceMerge,s=a.transition,a=a.notMerge),this[we]=!0,!this._model||a){var l=new GE(this._api),u=this._theme,f=this._model=new gp;f.scheduler=this._scheduler,f.ssr=this._ssr,f.init(null,null,null,u,this._locale,l)}this._model.setOption(t,{replaceMerge:o},Kp);var h={seriesTransition:s,optionChanged:!0};if(n)this[ze]={silent:i,updateParams:h},this[we]=!1,this.getZr().wakeUp();else{try{lo(this),qa.update.call(this,null,h)}catch(v){throw this[ze]=null,this[we]=!1,v}this._ssr||this._zr.flush(),this[ze]=null,this[we]=!1,Zs.call(this,i),$s.call(this,i)}}},e.prototype.setTheme=function(){},e.prototype.getModel=function(){return this._model},e.prototype.getOption=function(){return this._model&&this._model.getOption()},e.prototype.getWidth=function(){return this._zr.getWidth()},e.prototype.getHeight=function(){return this._zr.getHeight()},e.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||_t.hasGlobalWindow&&window.devicePixelRatio||1},e.prototype.getRenderedCanvas=function(t){return this.renderToCanvas(t)},e.prototype.renderToCanvas=function(t){t=t||{};var a=this._zr.painter;return a.getRenderedCanvas({backgroundColor:t.backgroundColor||this._model.get("backgroundColor"),pixelRatio:t.pixelRatio||this.getDevicePixelRatio()})},e.prototype.renderToSVGString=function(t){t=t||{};var a=this._zr.painter;return a.renderToString({useViewBox:t.useViewBox})},e.prototype.getSvgDataURL=function(){if(!!_t.svgSupported){var t=this._zr,a=t.storage.getDisplayList();return A(a,function(n){n.stopAnimation(null,!0)}),t.painter.toDataURL()}},e.prototype.getDataURL=function(t){if(this._disposed){Xe(this.id);return}t=t||{};var a=t.excludeComponents,n=this._model,i=[],o=this;A(a,function(l){n.eachComponent({mainType:l},function(u){var f=o._componentsMap[u.__viewId];f.group.ignore||(i.push(f),f.group.ignore=!0)})});var s=this._zr.painter.getType()==="svg"?this.getSvgDataURL():this.renderToCanvas(t).toDataURL("image/"+(t&&t.type||"png"));return A(i,function(l){l.group.ignore=!1}),s},e.prototype.getConnectedDataURL=function(t){if(this._disposed){Xe(this.id);return}var a=t.type==="svg",n=this.group,i=Math.min,o=Math.max,s=Infinity;if(Pf[n]){var l=s,u=s,f=-s,h=-s,v=[],c=t&&t.pixelRatio||this.getDevicePixelRatio();A($n,function(_,S){if(_.group===n){var b=a?_.getZr().painter.getSvgDom().innerHTML:_.renderToCanvas(et(t)),x=_.getDom().getBoundingClientRect();l=i(x.left,l),u=i(x.top,u),f=o(x.right,f),h=o(x.bottom,h),v.push({dom:b,left:x.left,top:x.top})}}),l*=c,u*=c,f*=c,h*=c;var p=f-l,d=h-u,g=yr.createCanvas(),y=Jv(g,{renderer:a?"svg":"canvas"});if(y.resize({width:p,height:d}),a){var m="";return A(v,function(_){var S=_.left-l,b=_.top-u;m+=''+_.dom+""}),y.painter.getSvgRoot().innerHTML=m,t.connectedBackgroundColor&&y.painter.setBackgroundColor(t.connectedBackgroundColor),y.refreshImmediately(),y.painter.toDataURL()}else return t.connectedBackgroundColor&&y.add(new xt({shape:{x:0,y:0,width:p,height:d},style:{fill:t.connectedBackgroundColor}})),A(v,function(_){var S=new ae({style:{x:_.left*c-l,y:_.top*c-u,image:_.dom}});y.add(S)}),y.refreshImmediately(),g.toDataURL("image/"+(t&&t.type||"png"))}else return this.getDataURL(t)},e.prototype.convertToPixel=function(t,a){return Up(this,"convertToPixel",t,a)},e.prototype.convertFromPixel=function(t,a){return Up(this,"convertFromPixel",t,a)},e.prototype.containPixel=function(t,a){if(this._disposed){Xe(this.id);return}var n=this._model,i,o=fs(n,t);return A(o,function(s,l){l.indexOf("Models")>=0&&A(s,function(u){var f=u.coordinateSystem;if(f&&f.containPoint)i=i||!!f.containPoint(a);else if(l==="seriesModels"){var h=this._chartsMap[u.__viewId];h&&h.containPoint&&(i=i||h.containPoint(a,u))}},this)},this),!!i},e.prototype.getVisual=function(t,a){var n=this._model,i=fs(n,t,{defaultMainType:"series"}),o=i.seriesModel,s=o.getData(),l=i.hasOwnProperty("dataIndexInside")?i.dataIndexInside:i.hasOwnProperty("dataIndex")?s.indexOfRawIndex(i.dataIndex):null;return l!=null?kp(s,l,a):Us(s,a)},e.prototype.getViewOfComponentModel=function(t){return this._componentsMap[t.__viewId]},e.prototype.getViewOfSeriesModel=function(t){return this._chartsMap[t.__viewId]},e.prototype._initEvents=function(){var t=this;A(KO,function(a){var n=function(i){var o=t.getModel(),s=i.target,l,u=a==="globalout";if(u?l={}:s&&Yn(s,function(p){var d=nt(p);if(d&&d.dataIndex!=null){var g=d.dataModel||o.getSeriesByIndex(d.seriesIndex);return l=g&&g.getDataParams(d.dataIndex,d.dataType)||{},!0}else if(d.eventData)return l=B({},d.eventData),!0},!0),l){var f=l.componentType,h=l.componentIndex;(f==="markLine"||f==="markPoint"||f==="markArea")&&(f="series",h=l.seriesIndex);var v=f&&h!=null&&o.getComponent(f,h),c=v&&t[v.mainType==="series"?"_chartsMap":"_componentsMap"][v.__viewId];l.event=i,l.type=a,t._$eventProcessor.eventInfo={targetEl:s,packedEvent:l,model:v,view:c},t.trigger(a,l)}};n.zrEventfulCallAtLast=!0,t._zr.on(a,n,t)}),A(qs,function(a,n){t._messageCenter.on(n,function(i){this.trigger(n,i)},t)}),A(["selectchanged"],function(a){t._messageCenter.on(a,function(n){this.trigger(a,n)},t)}),oO(this._messageCenter,this,this._api)},e.prototype.isDisposed=function(){return this._disposed},e.prototype.clear=function(){if(this._disposed){Xe(this.id);return}this.setOption({series:[]},!0)},e.prototype.dispose=function(){if(this._disposed){Xe(this.id);return}this._disposed=!0;var t=this.getDom();t&&J0(this.getDom(),Qp,"");var a=this,n=a._api,i=a._model;A(a._componentsViews,function(o){o.dispose(i,n)}),A(a._chartsViews,function(o){o.dispose(i,n)}),a._zr.dispose(),a._dom=a._model=a._chartsMap=a._componentsMap=a._chartsViews=a._componentsViews=a._scheduler=a._api=a._zr=a._throttledZrFlush=a._theme=a._coordSysMgr=a._messageCenter=null,delete $n[a.id]},e.prototype.resize=function(t){if(!this[we]){if(this._disposed){Xe(this.id);return}this._zr.resize(t);var a=this._model;if(this._loadingFX&&this._loadingFX.resize(),!!a){var n=a.resetOption("media"),i=t&&t.silent;this[ze]&&(i==null&&(i=this[ze].silent),n=!0,this[ze]=null),this[we]=!0;try{n&&lo(this),qa.update.call(this,{type:"resize",animation:B({duration:0},t&&t.animation)})}catch(o){throw this[we]=!1,o}this[we]=!1,Zs.call(this,i),$s.call(this,i)}}},e.prototype.showLoading=function(t,a){if(this._disposed){Xe(this.id);return}if(J(t)&&(a=t,t=""),t=t||"default",this.hideLoading(),!!jp[t]){var n=jp[t](this._api,a),i=this._zr;this._loadingFX=n,i.add(n)}},e.prototype.hideLoading=function(){if(this._disposed){Xe(this.id);return}this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null},e.prototype.makeActionFromEvent=function(t){var a=B({},t);return a.type=qs[t.type],a},e.prototype.dispatchAction=function(t,a){if(this._disposed){Xe(this.id);return}if(J(a)||(a={silent:!!a}),!!If[t.type]&&!!this._model){if(this[we]){this._pendingActions.push(t);return}var n=a.silent;Xp.call(this,t,n);var i=a.flush;i?this._zr.flush():i!==!1&&_t.browser.weChat&&this._throttledZrFlush(),Zs.call(this,n),$s.call(this,n)}},e.prototype.updateLabelLayout=function(){Mr.trigger("series:layoutlabels",this._model,this._api,{updatedSeries:[]})},e.prototype.appendData=function(t){if(this._disposed){Xe(this.id);return}var a=t.seriesIndex,n=this.getModel(),i=n.getSeriesByIndex(a);i.appendData(t),this._scheduler.unfinished=!0,this.getZr().wakeUp()},e.internalField=function(){lo=function(h){var v=h._scheduler;v.restorePipelines(h._model),v.prepareStageTasks(),Wp(h,!0),Wp(h,!1),v.plan()},Wp=function(h,v){for(var c=h._model,p=h._scheduler,d=v?h._componentsViews:h._chartsViews,g=v?h._componentsMap:h._chartsMap,y=h._zr,m=h._api,_=0;_v.get("hoverLayerThreshold")&&!_t.node&&!_t.worker&&v.eachSeries(function(g){if(!g.preventUsingHoverLayer){var y=h._chartsMap[g.__viewId];y.__alive&&y.eachRendered(function(m){m.states.emphasis&&(m.states.emphasis.hoverLayer=!0)})}})}function o(h,v){var c=h.get("blendMode")||null;v.eachRendered(function(p){p.isGroup||(p.style.blend=c)})}function s(h,v){if(!h.preventAutoZ){var c=h.get("z")||0,p=h.get("zlevel")||0;v.eachRendered(function(d){return l(d,c,p,-Infinity),!0})}}function l(h,v,c,p){var d=h.getTextContent(),g=h.getTextGuideLine(),y=h.isGroup;if(y)for(var m=h.childrenRef(),_=0;_0?{duration:d,delay:c.get("delay"),easing:c.get("easing")}:null;v.eachRendered(function(y){if(y.states&&y.states.emphasis){if(Hi(y))return;if(y instanceof dt&&CR(y),y.__dirty){var m=y.prevStates;m&&y.useStates(m)}if(p){y.stateTransition=g;var _=y.getTextContent(),S=y.getTextGuideLine();_&&(_.stateTransition=g),S&&(S.stateTransition=g)}y.__dirty&&n(y)}})}qx=function(h){return new(function(v){O(c,v);function c(){return v!==null&&v.apply(this,arguments)||this}return c.prototype.getCoordinateSystems=function(){return h._coordSysMgr.getCoordinateSystems()},c.prototype.getComponentByElement=function(p){for(;p;){var d=p.__ecComponentInfo;if(d!=null)return h._model.getComponent(d.mainType,d.index);p=p.parent}},c.prototype.enterEmphasis=function(p,d){va(p,d),ur(h)},c.prototype.leaveEmphasis=function(p,d){ca(p,d),ur(h)},c.prototype.enterBlur=function(p){F_(p),ur(h)},c.prototype.leaveBlur=function(p){Pc(p),ur(h)},c.prototype.enterSelect=function(p){H_(p),ur(h)},c.prototype.leaveSelect=function(p){W_(p),ur(h)},c.prototype.getModel=function(){return h.getModel()},c.prototype.getViewOfComponentModel=function(p){return h.getViewOfComponentModel(p)},c.prototype.getViewOfSeriesModel=function(p){return h.getViewOfSeriesModel(p)},c}(iS))(h)},Kx=function(h){function v(c,p){for(var d=0;d=0)){nb.push(t);var i=nx.wrapStageHandler(t,n);i.__prio=e,i.__raw=t,r.push(i)}}function nd(r,e){jp[r]=e}function iN(r){Im({createCanvas:r})}function ib(r,e,t){var a=kx("registerMap");a&&a(r,e,t)}function oN(r){var e=kx("getMap");return e&&e(r)}var ob=mk;Ka(Gp,Wk),Ka(Cf,Uk),Ka(Cf,Yk),Ka(Gp,nO),Ka(Cf,iO),Ka(Bx,EO),ed(vS),rd(zO,QE),nd("default",Xk),Ir({type:Rn,event:Rn,update:Rn},Zt),Ir({type:Ou,event:Ou,update:Ou},Zt),Ir({type:gs,event:gs,update:gs},Zt),Ir({type:Nu,event:Nu,update:Nu},Zt),Ir({type:ys,event:ys,update:ys},Zt),td("light",rO),td("dark",hx);var sN={},sb=[],lN={registerPreprocessor:ed,registerProcessor:rd,registerPostInit:tb,registerPostUpdate:eb,registerUpdateLifecycle:Rf,registerAction:Ir,registerCoordinateSystem:rb,registerLayout:ab,registerVisual:Ka,registerTransform:ob,registerLoading:nd,registerMap:ib,registerImpl:kO,PRIORITY:Vx,ComponentModel:gt,ComponentView:Bt,SeriesModel:kt,ChartView:Rt,registerComponentModel:function(r){gt.registerClass(r)},registerComponentView:function(r){Bt.registerClass(r)},registerSeriesModel:function(r){kt.registerClass(r)},registerChartView:function(r){Rt.registerClass(r)},registerSubTypeDefaulter:function(r,e){gt.registerSubTypeDefaulter(r,e)},registerPainter:function(r,e){B0(r,e)}};function ct(r){if(z(r)){A(r,function(e){ct(e)});return}vt(sb,r)>=0||(sb.push(r),K(r)&&(r={install:r}),r.install(lN))}function Ks(r){return r==null?0:r.length||1}function lb(r){return r}var da=function(){function r(e,t,a,n,i,o){this._old=e,this._new=t,this._oldKeyGetter=a||lb,this._newKeyGetter=n||lb,this.context=i,this._diffModeMultiple=o==="multiple"}return r.prototype.add=function(e){return this._add=e,this},r.prototype.update=function(e){return this._update=e,this},r.prototype.updateManyToOne=function(e){return this._updateManyToOne=e,this},r.prototype.updateOneToMany=function(e){return this._updateOneToMany=e,this},r.prototype.updateManyToMany=function(e){return this._updateManyToMany=e,this},r.prototype.remove=function(e){return this._remove=e,this},r.prototype.execute=function(){this[this._diffModeMultiple?"_executeMultiple":"_executeOneToOne"]()},r.prototype._executeOneToOne=function(){var e=this._old,t=this._new,a={},n=new Array(e.length),i=new Array(t.length);this._initIndexMap(e,null,n,"_oldKeyGetter"),this._initIndexMap(t,a,i,"_newKeyGetter");for(var o=0;o1){var f=l.shift();l.length===1&&(a[s]=l[0]),this._update&&this._update(f,o)}else u===1?(a[s]=null,this._update&&this._update(l,o)):this._remove&&this._remove(o)}this._performRestAdd(i,a)},r.prototype._executeMultiple=function(){var e=this._old,t=this._new,a={},n={},i=[],o=[];this._initIndexMap(e,a,i,"_oldKeyGetter"),this._initIndexMap(t,n,o,"_newKeyGetter");for(var s=0;s1&&v===1)this._updateManyToOne&&this._updateManyToOne(f,u),n[l]=null;else if(h===1&&v>1)this._updateOneToMany&&this._updateOneToMany(f,u),n[l]=null;else if(h===1&&v===1)this._update&&this._update(f,u),n[l]=null;else if(h>1&&v>1)this._updateManyToMany&&this._updateManyToMany(f,u),n[l]=null;else if(h>1)for(var c=0;c1)for(var s=0;s30}var js=J,ja=G,pN=typeof Int32Array=="undefined"?Array:Int32Array,dN="e\0\0",pb=-1,gN=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],yN=["_approximateExtent"],db,Of,Qs,Js,od,Nf,sd,Te=function(){function r(e,t){this.type="list",this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=["cloneShallow","downSample","lttbDownSample","map"],this.CHANGABLE_METHODS=["filterSelf","selectRange"],this.DOWNSAMPLE_METHODS=["downSample","lttbDownSample"];var a,n=!1;fb(e)?(a=e.dimensions,this._dimOmitted=e.isDimensionOmitted(),this._schema=e):(n=!0,a=e),a=a||["x","y"];for(var i={},o=[],s={},l=!1,u={},f=0;f=t)){var a=this._store,n=a.getProvider();this._updateOrdinalMeta();var i=this._nameList,o=this._idList,s=n.getSource().sourceFormat,l=s===or;if(l&&!n.pure)for(var u=[],f=e;f0},r.prototype.ensureUniqueItemVisual=function(e,t){var a=this._itemVisuals,n=a[e];n||(n=a[e]={});var i=n[t];return i==null&&(i=this.getVisual(t),z(i)?i=i.slice():js(i)&&(i=B({},i)),n[t]=i),i},r.prototype.setItemVisual=function(e,t,a){var n=this._itemVisuals[e]||{};this._itemVisuals[e]=n,js(t)?B(n,t):n[t]=a},r.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},r.prototype.setLayout=function(e,t){js(e)?B(this._layout,e):this._layout[e]=t},r.prototype.getLayout=function(e){return this._layout[e]},r.prototype.getItemLayout=function(e){return this._itemLayouts[e]},r.prototype.setItemLayout=function(e,t,a){this._itemLayouts[e]=a?B(this._itemLayouts[e]||{},t):t},r.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},r.prototype.setItemGraphicEl=function(e,t){var a=this.hostModel&&this.hostModel.seriesIndex;Ac(a,this.dataType,e,t),this._graphicEls[e]=t},r.prototype.getItemGraphicEl=function(e){return this._graphicEls[e]},r.prototype.eachItemGraphicEl=function(e,t){A(this._graphicEls,function(a,n){a&&e&&e.call(t,a,n)})},r.prototype.cloneShallow=function(e){return e||(e=new r(this._schema?this._schema:ja(this.dimensions,this._getDimInfo,this),this.hostModel)),od(e,this),e._store=this._store,e},r.prototype.wrapMethod=function(e,t){var a=this[e];!K(a)||(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(e),this[e]=function(){var n=a.apply(this,arguments);return t.apply(this,[n].concat(ql(arguments)))})},r.internalField=function(){db=function(e){var t=e._invertedIndicesMap;A(t,function(a,n){var i=e._dimInfos[n],o=i.ordinalMeta,s=e._store;if(o){a=t[n]=new pN(o.categories.length);for(var l=0;l1&&(l+="__ec__"+f),n[t]=l}}}(),r}();function mN(r,e){return uo(r,e).dimensions}function uo(r,e){Sp(r)||(r=bp(r)),e=e||{};var t=e.coordDimensions||[],a=e.dimensionsDefine||r.dimensionsDefine||[],n=$(),i=[],o=SN(r,t,a,e.dimensionsCount),s=e.canOmitUnusedDimensions&&cb(o),l=a===r.dimensionsDefine,u=l?vb(r):hb(a),f=e.encodeDefine;!f&&e.encodeDefaulter&&(f=e.encodeDefaulter(r,o));for(var h=$(f),v=new PS(o),c=0;c0&&(a.name=n+(i-1)),i++,e.set(n,i)}}function SN(r,e,t,a){var n=Math.max(r.dimensionsDetectedCount||1,e.length,t.length,a||0);return A(e,function(i){var o;J(i)&&(o=i.dimsDef)&&(n=Math.max(n,o.length))}),n}function xN(r,e,t){if(t||e.hasKey(r)){for(var a=0;e.hasKey(r+a);)a++;r+=a}return e.set(r,!0),r}var bN=function(){function r(e){this.coordSysDims=[],this.axisMap=$(),this.categoryAxisMap=$(),this.coordSysName=e}return r}();function wN(r){var e=r.get("coordinateSystem"),t=new bN(e),a=TN[e];if(a)return a(r,t,t.axisMap,t.categoryAxisMap),t}var TN={cartesian2d:function(r,e,t,a){var n=r.getReferringComponents("xAxis",Kt).models[0],i=r.getReferringComponents("yAxis",Kt).models[0];e.coordSysDims=["x","y"],t.set("x",n),t.set("y",i),fo(n)&&(a.set("x",n),e.firstCategoryDimIndex=0),fo(i)&&(a.set("y",i),e.firstCategoryDimIndex==null&&(e.firstCategoryDimIndex=1))},singleAxis:function(r,e,t,a){var n=r.getReferringComponents("singleAxis",Kt).models[0];e.coordSysDims=["single"],t.set("single",n),fo(n)&&(a.set("single",n),e.firstCategoryDimIndex=0)},polar:function(r,e,t,a){var n=r.getReferringComponents("polar",Kt).models[0],i=n.findAxisModel("radiusAxis"),o=n.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],t.set("radius",i),t.set("angle",o),fo(i)&&(a.set("radius",i),e.firstCategoryDimIndex=0),fo(o)&&(a.set("angle",o),e.firstCategoryDimIndex==null&&(e.firstCategoryDimIndex=1))},geo:function(r,e,t,a){e.coordSysDims=["lng","lat"]},parallel:function(r,e,t,a){var n=r.ecModel,i=n.getComponent("parallel",r.get("parallelIndex")),o=e.coordSysDims=i.dimensions.slice();A(i.parallelAxisIndex,function(s,l){var u=n.getComponent("parallelAxis",s),f=o[l];t.set(f,u),fo(u)&&(a.set(f,u),e.firstCategoryDimIndex==null&&(e.firstCategoryDimIndex=l))})}};function fo(r){return r.get("type")==="category"}function gb(r,e,t){t=t||{};var a=t.byIndex,n=t.stackedCoordDimension,i,o,s;CN(e)?i=e:(o=e.schema,i=o.dimensions,s=e.store);var l=!!(r&&r.get("stack")),u,f,h,v;if(A(i,function(m,_){U(m)&&(i[_]=m={name:m}),l&&!m.isExtraCoord&&(!a&&!u&&m.ordinalMeta&&(u=m),!f&&m.type!=="ordinal"&&m.type!=="time"&&(!n||n===m.coordDim)&&(f=m))}),f&&!a&&!u&&(a=!0),f){h="__\0ecstackresult_"+r.id,v="__\0ecstackedover_"+r.id,u&&(u.createInvertedIndices=!0);var c=f.coordDim,p=f.type,d=0;A(i,function(m){m.coordDim===c&&d++});var g={name:h,coordDim:c,coordDimIndex:d,type:p,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},y={name:v,coordDim:v,coordDimIndex:d+1,type:p,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};o?(s&&(g.storeDimIndex=s.ensureCalculationDimension(v,p),y.storeDimIndex=s.ensureCalculationDimension(h,p)),o.appendCalculationDimension(g),o.appendCalculationDimension(y)):(i.push(g),i.push(y))}return{stackedDimension:f&&f.name,stackedByDimension:u&&u.name,isStackedByIndex:a,stackedOverDimension:v,stackResultDimension:h}}function CN(r){return!fb(r.schema)}function ga(r,e){return!!e&&e===r.getCalculationInfo("stackedDimension")}function ld(r,e){return ga(r,e)?r.getCalculationInfo("stackResultDimension"):e}function AN(r,e){var t=r.get("coordinateSystem"),a=Ji.get(t),n;return e&&e.coordSysDims&&(n=G(e.coordSysDims,function(i){var o={name:i},s=e.axisMap.get(i);if(s){var l=s.get("type");o.type=Ef(l)}return o})),n||(n=a&&(a.getDimensionsInfo?a.getDimensionsInfo():a.dimensions.slice())||["x","y"]),n}function DN(r,e,t){var a,n;return t&&A(r,function(i,o){var s=i.coordDim,l=t.categoryAxisMap.get(s);l&&(a==null&&(a=o),i.ordinalMeta=l.getOrdinalMeta(),e&&(i.createInvertedIndices=!0)),i.otherDims.itemName!=null&&(n=!0)}),!n&&a!=null&&(r[a].otherDims.itemName=0),a}function Xr(r,e,t){t=t||{};var a=e.getSourceManager(),n,i=!1;r?(i=!0,n=bp(r)):(n=a.getSource(),i=n.sourceFormat===or);var o=wN(e),s=AN(e,o),l=t.useEncodeDefaulter,u=K(l)?l:l?it(q1,s,e):null,f={coordDimensions:s,generateCoord:t.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:u,canOmitUnusedDimensions:!i},h=uo(n,f),v=DN(h.dimensions,t.createInvertedIndices,o),c=i?null:a.getSharedDataStore(h),p=gb(e,{schema:h,store:c}),d=new Te(h,e);d.setCalculationInfo(p);var g=v!=null&&MN(n)?function(y,m,_,S){return S===v?_:this.defaultDimValueGetter(y,m,_,S)}:null;return d.hasItemOption=!1,d.initData(i?n:c,null,g),d}function MN(r){if(r.sourceFormat===or){var e=IN(r.data||[]);return!z(Pi(e))}}function IN(r){for(var e=0;et[1]&&(t[1]=e[1])},r.prototype.unionExtentFromData=function(e,t){this.unionExtent(e.getApproximateExtent(t))},r.prototype.getExtent=function(){return this._extent.slice()},r.prototype.setExtent=function(e,t){var a=this._extent;isNaN(e)||(a[0]=e),isNaN(t)||(a[1]=t)},r.prototype.isInExtentRange=function(e){return this._extent[0]<=e&&this._extent[1]>=e},r.prototype.isBlank=function(){return this._isBlank},r.prototype.setBlank=function(e){this._isBlank=e},r}();Au(Zr);var LN=0,ud=function(){function r(e){this.categories=e.categories||[],this._needCollect=e.needCollect,this._deduplication=e.deduplication,this.uid=++LN}return r.createByAxisModel=function(e){var t=e.option,a=t.data,n=a&&G(a,PN);return new r({categories:n,needCollect:!n,deduplication:t.dedplication!==!1})},r.prototype.getOrdinal=function(e){return this._getOrCreateMap().get(e)},r.prototype.parseAndCollect=function(e){var t,a=this._needCollect;if(!U(e)&&!a)return e;if(a&&!this._deduplication)return t=this.categories.length,this.categories[t]=e,t;var n=this._getOrCreateMap();return t=n.get(e),t==null&&(a?(t=this.categories.length,this.categories[t]=e,n.set(e,t)):t=NaN),t},r.prototype._getOrCreateMap=function(){return this._map||(this._map=$(this.categories))},r}();function PN(r){return J(r)&&r.value!=null?r.value:r+""}function fd(r){return r.type==="interval"||r.type==="log"}function RN(r,e,t,a){var n={},i=r[1]-r[0],o=n.interval=ac(i/e,!0);t!=null&&oa&&(o=n.interval=a);var s=n.intervalPrecision=yb(o),l=n.niceTickExtent=[Wt(Math.ceil(r[0]/o)*o,s),Wt(Math.floor(r[1]/o)*o,s)];return EN(l,r),n}function hd(r){var e=Math.pow(10,Tu(r)),t=r/e;return t?t===2?t=3:t===3?t=5:t*=2:t=1,Wt(t*e)}function yb(r){return wr(r)+2}function mb(r,e,t){r[e]=Math.max(Math.min(r[e],t[1]),t[0])}function EN(r,e){!isFinite(r[0])&&(r[0]=e[0]),!isFinite(r[1])&&(r[1]=e[1]),mb(r,0,e),mb(r,1,e),r[0]>r[1]&&(r[0]=r[1])}function Bf(r,e){return r>=e[0]&&r<=e[1]}function Vf(r,e){return e[1]===e[0]?.5:(r-e[0])/(e[1]-e[0])}function zf(r,e){return r*(e[1]-e[0])+e[0]}var Gf=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;a.type="ordinal";var n=a.getSetting("ordinalMeta");return n||(n=new ud({})),z(n)&&(n=new ud({categories:G(n,function(i){return J(i)?i.value:i})})),a._ordinalMeta=n,a._extent=a.getSetting("extent")||[0,n.categories.length-1],a}return e.prototype.parse=function(t){return t==null?NaN:U(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return t=this.parse(t),Bf(t,this._extent)&&this._ordinalMeta.categories[t]!=null},e.prototype.normalize=function(t){return t=this._getTickNumber(this.parse(t)),Vf(t,this._extent)},e.prototype.scale=function(t){return t=Math.round(zf(t,this._extent)),this.getRawOrdinalNumber(t)},e.prototype.getTicks=function(){for(var t=[],a=this._extent,n=a[0];n<=a[1];)t.push({value:n}),n++;return t},e.prototype.getMinorTicks=function(t){},e.prototype.setSortInfo=function(t){if(t==null){this._ordinalNumbersByTick=this._ticksByOrdinalNumber=null;return}for(var a=t.ordinalNumbers,n=this._ordinalNumbersByTick=[],i=this._ticksByOrdinalNumber=[],o=0,s=this._ordinalMeta.categories.length,l=Math.min(s,a.length);o=0&&t=0&&t=t},e.prototype.getOrdinalMeta=function(){return this._ordinalMeta},e.prototype.calcNiceTicks=function(){},e.prototype.calcNiceExtent=function(){},e.type="ordinal",e}(Zr);Zr.registerClass(Gf);var qn=Wt,ya=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type="interval",t._interval=0,t._intervalPrecision=2,t}return e.prototype.parse=function(t){return t},e.prototype.contain=function(t){return Bf(t,this._extent)},e.prototype.normalize=function(t){return Vf(t,this._extent)},e.prototype.scale=function(t){return zf(t,this._extent)},e.prototype.setExtent=function(t,a){var n=this._extent;isNaN(t)||(n[0]=parseFloat(t)),isNaN(a)||(n[1]=parseFloat(a))},e.prototype.unionExtent=function(t){var a=this._extent;t[0]a[1]&&(a[1]=t[1]),this.setExtent(a[0],a[1])},e.prototype.getInterval=function(){return this._interval},e.prototype.setInterval=function(t){this._interval=t,this._niceExtent=this._extent.slice(),this._intervalPrecision=yb(t)},e.prototype.getTicks=function(t){var a=this._interval,n=this._extent,i=this._niceExtent,o=this._intervalPrecision,s=[];if(!a)return s;var l=1e4;n[0]l)return[];var f=s.length?s[s.length-1].value:i[1];return n[1]>f&&(t?s.push({value:qn(f+a,o)}):s.push({value:n[1]})),s},e.prototype.getMinorTicks=function(t){for(var a=this.getTicks(!0),n=[],i=this.getExtent(),o=1;oi[0]&&c0&&(i=i===null?s:Math.min(i,s))}t[a]=i}}return t}function xb(r){var e=NN(r),t=[];return A(r,function(a){var n=a.coordinateSystem,i=n.getBaseAxis(),o=i.getExtent(),s;if(i.type==="category")s=i.getBandWidth();else if(i.type==="value"||i.type==="time"){var l=i.dim+"_"+i.index,u=e[l],f=Math.abs(o[1]-o[0]),h=i.scale.getExtent(),v=Math.abs(h[1]-h[0]);s=u?f/v*u:f}else{var c=a.getData();s=Math.abs(o[1]-o[0])/c.count()}var p=H(a.get("barWidth"),s),d=H(a.get("barMaxWidth"),s),g=H(a.get("barMinWidth")||(Ab(a)?.5:1),s),y=a.get("barGap"),m=a.get("barCategoryGap");t.push({bandWidth:s,barWidth:p,barMaxWidth:d,barMinWidth:g,barGap:y,barCategoryGap:m,axisKey:pd(i),stackId:cd(a)})}),bb(t)}function bb(r){var e={};A(r,function(a,n){var i=a.axisKey,o=a.bandWidth,s=e[i]||{bandWidth:o,remainedWidth:o,autoWidthCount:0,categoryGap:null,gap:"20%",stacks:{}},l=s.stacks;e[i]=s;var u=a.stackId;l[u]||s.autoWidthCount++,l[u]=l[u]||{width:0,maxWidth:0};var f=a.barWidth;f&&!l[u].width&&(l[u].width=f,f=Math.min(s.remainedWidth,f),s.remainedWidth-=f);var h=a.barMaxWidth;h&&(l[u].maxWidth=h);var v=a.barMinWidth;v&&(l[u].minWidth=v);var c=a.barGap;c!=null&&(s.gap=c);var p=a.barCategoryGap;p!=null&&(s.categoryGap=p)});var t={};return A(e,function(a,n){t[n]={};var i=a.stacks,o=a.bandWidth,s=a.categoryGap;if(s==null){var l=St(i).length;s=Math.max(35-l*4,15)+"%"}var u=H(s,o),f=H(a.gap,1),h=a.remainedWidth,v=a.autoWidthCount,c=(h-u)/(v+(v-1)*f);c=Math.max(c,0),A(i,function(y){var m=y.maxWidth,_=y.minWidth;if(y.width){var S=y.width;m&&(S=Math.min(S,m)),_&&(S=Math.max(S,_)),y.width=S,h-=S+f*S,v--}else{var S=c;m&&mS&&(S=_),S!==c&&(y.width=S,h-=S+f*S,v--)}}),c=(h-u)/(v+(v-1)*f),c=Math.max(c,0);var p=0,d;A(i,function(y,m){y.width||(y.width=c),d=y,p+=y.width*(1+f)}),d&&(p-=d.width*f);var g=-p/2;A(i,function(y,m){t[n][m]=t[n][m]||{bandWidth:o,offset:g,width:y.width},g+=y.width*(1+f)})}),t}function BN(r,e,t){if(r&&e){var a=r[pd(e)];return a!=null&&t!=null?a[cd(t)]:a}}function wb(r,e){var t=Sb(r,e),a=xb(t);A(t,function(n){var i=n.getData(),o=n.coordinateSystem,s=o.getBaseAxis(),l=cd(n),u=a[pd(s)][l],f=u.offset,h=u.width;i.setLayout({bandWidth:u.bandWidth,offset:f,size:h})})}function Tb(r){return{seriesType:r,plan:ro(),reset:function(e){if(!!Cb(e)){var t=e.getData(),a=e.coordinateSystem,n=a.getBaseAxis(),i=a.getOtherAxis(n),o=t.getDimensionIndex(t.mapDimension(i.dim)),s=t.getDimensionIndex(t.mapDimension(n.dim)),l=e.get("showBackground",!0),u=t.mapDimension(i.dim),f=t.getCalculationInfo("stackResultDimension"),h=ga(t,u)&&!!t.getCalculationInfo("stackedOnSeries"),v=i.isHorizontal(),c=VN(n,i),p=Ab(e),d=e.get("barMinHeight")||0,g=f&&t.getDimensionIndex(f),y=t.getLayout("size"),m=t.getLayout("offset");return{progress:function(_,S){for(var b=_.count,x=p&&$r(b*3),w=p&&l&&$r(b*3),T=p&&$r(b),C=a.master.getRect(),D=v?C.width:C.height,M,I=S.getStore(),L=0;(M=_.next())!=null;){var P=I.get(h?g:o,M),R=I.get(s,M),E=c,N=void 0;h&&(N=+P-I.get(o,M));var k=void 0,V=void 0,F=void 0,W=void 0;if(v){var Z=a.dataToPoint([P,R]);if(h){var Q=a.dataToPoint([N,R]);E=Q[0]}k=E,V=Z[1]+m,F=Z[0]-E,W=y,Math.abs(F)>>1;r[n][1]n&&(this._approxInterval=n);var s=Ff.length,l=Math.min(zN(Ff,this._approxInterval,0,s),s-1);this._interval=Ff[l][1],this._minLevelUnit=Ff[Math.max(l-1,0)][0]},e.prototype.parse=function(t){return Tt(t)?t:+Ue(t)},e.prototype.contain=function(t){return Bf(this.parse(t),this._extent)},e.prototype.normalize=function(t){return Vf(this.parse(t),this._extent)},e.prototype.scale=function(t){return zf(t,this._extent)},e.type="time",e}(ya),Ff=[["second",ep],["minute",rp],["hour",Ls],["quarter-day",Ls*6],["half-day",Ls*12],["day",ir*1.2],["half-week",ir*3.5],["week",ir*7],["month",ir*31],["quarter",ir*95],["half-year",L1/2],["year",L1]];function GN(r,e,t,a){var n=Ue(e),i=Ue(t),o=function(p){return k1(n,p,a)===k1(i,p,a)},s=function(){return o("year")},l=function(){return s()&&o("month")},u=function(){return l()&&o("day")},f=function(){return u()&&o("hour")},h=function(){return f()&&o("minute")},v=function(){return h()&&o("second")},c=function(){return v()&&o("millisecond")};switch(r){case"year":return s();case"month":return l();case"day":return u();case"hour":return f();case"minute":return h();case"second":return v();case"millisecond":return c()}}function FN(r,e){return r/=ir,r>16?16:r>7.5?7:r>3.5?4:r>1.5?2:1}function HN(r){var e=30*ir;return r/=e,r>6?6:r>3?3:r>2?2:1}function WN(r){return r/=Ls,r>12?12:r>6?6:r>3.5?4:r>2?2:1}function Db(r,e){return r/=e?rp:ep,r>30?30:r>20?20:r>15?15:r>10?10:r>5?5:r>2?2:1}function UN(r){return ac(r,!0)}function YN(r,e,t){var a=new Date(r);switch($i(e)){case"year":case"month":a[O1(t)](0);case"day":a[N1(t)](1);case"hour":a[B1(t)](0);case"minute":a[V1(t)](0);case"second":a[z1(t)](0),a[G1(t)](0)}return a.getTime()}function XN(r,e,t,a){var n=1e4,i=R1,o=0;function s(D,M,I,L,P,R,E){for(var N=new Date(M),k=M,V=N[L]();k1&&R===0&&I.unshift({value:I[0].value-k})}}for(var R=0;R=a[0]&&m<=a[1]&&h++)}var _=(a[1]-a[0])/e;if(h>_*1.5&&v>_/1.5||(u.push(g),h>_||r===i[c]))break}f=[]}}}for(var S=Lt(G(u,function(D){return Lt(D,function(M){return M.value>=a[0]&&M.value<=a[1]&&!M.notAdd})}),function(D){return D.length>0}),b=[],x=S.length-1,c=0;c0;)i*=10;var s=[Wt(qN(a[0]/i)*i),Wt($N(a[1]/i)*i)];this._interval=i,this._niceExtent=s}},e.prototype.calcNiceExtent=function(t){tl.calcNiceExtent.call(this,t),this._fixMin=t.fixMin,this._fixMax=t.fixMax},e.prototype.parse=function(t){return t},e.prototype.contain=function(t){return t=Lr(t)/Lr(this.base),Bf(t,this._extent)},e.prototype.normalize=function(t){return t=Lr(t)/Lr(this.base),Vf(t,this._extent)},e.prototype.scale=function(t){return t=zf(t,this._extent),Hf(this.base,t)},e.type="log",e}(Zr),Ib=gd.prototype;Ib.getMinorTicks=tl.getMinorTicks,Ib.getLabel=tl.getLabel;function Wf(r,e){return ZN(r,wr(e))}Zr.registerClass(gd);var KN=function(){function r(e,t,a){this._prepareParams(e,t,a)}return r.prototype._prepareParams=function(e,t,a){a[1]0&&l>0&&!u&&(s=0),s<0&&l<0&&!f&&(l=0));var v=this._determinedMin,c=this._determinedMax;return v!=null&&(s=v,u=!0),c!=null&&(l=c,f=!0),{min:s,max:l,minFixed:u,maxFixed:f,isBlank:h}},r.prototype.modifyDataMinMax=function(e,t){this[QN[e]]=t},r.prototype.setDeterminedMinMax=function(e,t){var a=jN[e];this[a]=t},r.prototype.freeze=function(){this.frozen=!0},r}(),jN={min:"_determinedMin",max:"_determinedMax"},QN={min:"_dataMin",max:"_dataMax"};function Lb(r,e,t){var a=r.rawExtentInfo;return a||(a=new KN(r,e,t),r.rawExtentInfo=a,a)}function Uf(r,e){return e==null?null:Si(e)?NaN:r.parse(e)}function Pb(r,e){var t=r.type,a=Lb(r,e,r.getExtent()).calculate();r.setBlank(a.isBlank);var n=a.min,i=a.max,o=e.ecModel;if(o&&t==="time"){var s=Sb("bar",o),l=!1;if(A(s,function(h){l=l||h.getBaseAxis()===e.axis}),l){var u=xb(s),f=JN(n,i,e,u);n=f.min,i=f.max}}return{extent:[n,i],fixMin:a.minFixed,fixMax:a.maxFixed}}function JN(r,e,t,a){var n=t.axis.getExtent(),i=n[1]-n[0],o=BN(a,t.axis);if(o===void 0)return{min:r,max:e};var s=Infinity;A(o,function(c){s=Math.min(c.offset,s)});var l=-Infinity;A(o,function(c){l=Math.max(c.offset+c.width,l)}),s=Math.abs(s),l=Math.abs(l);var u=s+l,f=e-r,h=1-(s+l)/i,v=f/h-f;return e+=v*(l/u),r-=v*(s/u),{min:r,max:e}}function Kn(r,e){var t=e,a=Pb(r,t),n=a.extent,i=t.get("splitNumber");r instanceof gd&&(r.base=t.get("logBase"));var o=r.type,s=t.get("interval"),l=o==="interval"||o==="time";r.setExtent(n[0],n[1]),r.calcNiceExtent({splitNumber:i,fixMin:a.fixMin,fixMax:a.fixMax,minInterval:l?t.get("minInterval"):null,maxInterval:l?t.get("maxInterval"):null}),s!=null&&r.setInterval&&r.setInterval(s)}function el(r,e){if(e=e||r.get("type"),e)switch(e){case"category":return new Gf({ordinalMeta:r.getOrdinalMeta?r.getOrdinalMeta():r.getCategories(),extent:[Infinity,-Infinity]});case"time":return new dd({locale:r.ecModel.getLocaleModel(),useUTC:r.ecModel.get("useUTC")});default:return new(Zr.getClass(e)||ya)}}function tB(r){var e=r.scale.getExtent(),t=e[0],a=e[1];return!(t>0&&a>0||t<0&&a<0)}function rl(r){var e=r.getLabelModel().get("formatter"),t=r.type==="category"?r.scale.getExtent()[0]:null;return r.scale.type==="time"?function(a){return function(n,i){return r.scale.getFormattedLabel(n,i,a)}}(e):U(e)?function(a){return function(n){var i=r.scale.getLabel(n),o=a.replace("{value}",i!=null?i:"");return o}}(e):K(e)?function(a){return function(n,i){return t!=null&&(i=n.value-t),a(yd(r,n),i,n.level!=null?{level:n.level}:null)}}(e):function(a){return r.scale.getLabel(a)}}function yd(r,e){return r.type==="category"?r.scale.getLabel(e):e.value}function eB(r){var e=r.model,t=r.scale;if(!(!e.get(["axisLabel","show"])||t.isBlank())){var a,n,i=t.getExtent();t instanceof Gf?n=t.count():(a=t.getTicks(),n=a.length);var o=r.getLabelModel(),s=rl(r),l,u=1;n>40&&(u=Math.ceil(n/40));for(var f=0;fr[1]&&(r[1]=n[1])})}var ho=function(){function r(){}return r.prototype.getNeedCrossZero=function(){var e=this.option;return!e.scale},r.prototype.getCoordSysModel=function(){},r}();function nB(r){return Xr(null,r)}var iB={isDimensionStacked:ga,enableDataStack:gb,getStackedDimension:ld};function oB(r,e){var t=e;e instanceof Mt||(t=new Mt(e));var a=el(t);return a.setExtent(r[0],r[1]),Kn(a,t),a}function sB(r){Xt(r,ho)}function lB(r,e){return e=e||{},Nt(r,null,null,e.state!=="normal")}var uB=Object.freeze({__proto__:null,createList:nB,getLayoutRect:jt,dataStack:iB,createScale:oB,mixinAxisModelCommonMethods:sB,getECData:nt,createTextStyle:lB,createDimensions:mN,createSymbol:$t,enableHoverEmphasis:Ga}),fB=1e-8;function Eb(r,e){return Math.abs(r-e)n&&(a=o,n=l)}if(a)return vB(a.exterior);var u=this.getBoundingRect();return[u.x+u.width/2,u.y+u.height/2]},e.prototype.getBoundingRect=function(t){var a=this._rect;if(a&&!t)return a;var n=[Infinity,Infinity],i=[-Infinity,-Infinity],o=this.geometries;return A(o,function(s){s.type==="polygon"?kb(s.exterior,n,i,t):A(s.points,function(l){kb(l,n,i,t)})}),isFinite(n[0])&&isFinite(n[1])&&isFinite(i[0])&&isFinite(i[1])||(n[0]=n[1]=i[0]=i[1]=0),a=new ft(n[0],n[1],i[0]-n[0],i[1]-n[1]),t||(this._rect=a),a},e.prototype.contain=function(t){var a=this.getBoundingRect(),n=this.geometries;if(!a.contain(t[0],t[1]))return!1;t:for(var i=0,o=n.length;i>1^-(s&1),l=l>>1^-(l&1),s+=n,l+=i,n=s,i=l,a.push([s/t,l/t])}return a}function xd(r,e){return r=pB(r),G(Lt(r.features,function(t){return t.geometry&&t.properties&&t.geometry.coordinates.length>0}),function(t){var a=t.properties,n=t.geometry,i=[];switch(n.type){case"Polygon":var o=n.coordinates;i.push(new Nb(o[0],o.slice(1)));break;case"MultiPolygon":A(n.coordinates,function(l){l[0]&&i.push(new Nb(l[0],l.slice(1)))});break;case"LineString":i.push(new Bb([n.coordinates]));break;case"MultiLineString":i.push(new Bb(n.coordinates))}var s=new Vb(a[e||"name"],i,a.cp);return s.properties=a,s})}var dB=Object.freeze({__proto__:null,linearMap:Pt,round:Wt,asc:We,getPrecision:wr,getPrecisionSafe:G0,getPixelPrecision:tc,getPercentWithPrecision:q2,MAX_SAFE_INTEGER:ec,remRadian:rc,isRadianAroundZero:ss,parseDate:Ue,quantity:H0,quantityExponent:Tu,nice:ac,quantile:Cu,reformIntervals:nc,isNumeric:ic,numericToNumber:Br}),gB=Object.freeze({__proto__:null,parse:Ue,format:Rs}),yB=Object.freeze({__proto__:null,extendShape:v1,extendPath:c1,makePath:Cs,makeImage:Uc,mergePath:Ye,resizePath:Yc,createIcon:Ui,updateProps:At,initProps:Gt,getTransform:Ha,clipPointsByRect:Xc,clipRectByRect:g1,registerShape:nr,getShapeClass:$u,Group:rt,Image:ae,Text:bt,Circle:ar,Ellipse:Ss,Sector:me,Ring:Vi,Polygon:_e,Polyline:Se,Rect:xt,Line:te,BezierCurve:zi,Arc:ws,IncrementalDisplayable:u1,CompoundPath:Hu,LinearGradient:Gi,RadialGradient:Fc,BoundingRect:ft}),mB=Object.freeze({__proto__:null,addCommas:ip,toCamelCase:op,normalizeCssArray:Vn,encodeHTML:Ce,formatTpl:up,getTooltipMarker:H1,formatTime:xE,capitalFirst:bE,truncateText:n_,getTextRect:_E}),_B=Object.freeze({__proto__:null,map:G,each:A,indexOf:vt,inherits:iv,reduce:qe,filter:Lt,bind:Y,curry:it,isArray:z,isString:U,isObject:J,isFunction:K,extend:B,defaults:j,clone:et,merge:ot}),al=Ct();function SB(r){return r.type==="category"?bB(r):TB(r)}function xB(r,e){return r.type==="category"?wB(r,e):{ticks:G(r.scale.getTicks(),function(t){return t.value})}}function bB(r){var e=r.getLabelModel(),t=Gb(r,e);return!e.get("show")||r.scale.isBlank()?{labels:[],labelCategoryInterval:t.labelCategoryInterval}:t}function Gb(r,e){var t=Fb(r,"labels"),a=md(e),n=Hb(t,a);if(n)return n;var i,o;return K(a)?i=Yb(r,a):(o=a==="auto"?CB(r):a,i=Ub(r,o)),Wb(t,a,{labels:i,labelCategoryInterval:o})}function wB(r,e){var t=Fb(r,"ticks"),a=md(e),n=Hb(t,a);if(n)return n;var i,o;if((!e.get("show")||r.scale.isBlank())&&(i=[]),K(a))i=Yb(r,a,!0);else if(a==="auto"){var s=Gb(r,r.getLabelModel());o=s.labelCategoryInterval,i=G(s.labels,function(l){return l.tickValue})}else o=a,i=Ub(r,o,!0);return Wb(t,a,{ticks:i,tickCategoryInterval:o})}function TB(r){var e=r.scale.getTicks(),t=rl(r);return{labels:G(e,function(a,n){return{level:a.level,formattedLabel:t(a,n),rawLabel:r.scale.getLabel(a),tickValue:a.value}})}}function Fb(r,e){return al(r)[e]||(al(r)[e]=[])}function Hb(r,e){for(var t=0;t40&&(s=Math.max(1,Math.floor(o/40)));for(var l=i[0],u=r.dataToCoord(l+1)-r.dataToCoord(l),f=Math.abs(u*Math.cos(a)),h=Math.abs(u*Math.sin(a)),v=0,c=0;l<=i[1];l+=s){var p=0,d=0,g=is(t({value:l}),e.font,"center","top");p=g.width*1.3,d=g.height*1.3,v=Math.max(v,p,7),c=Math.max(c,d,7)}var y=v/f,m=c/h;isNaN(y)&&(y=Infinity),isNaN(m)&&(m=Infinity);var _=Math.max(0,Math.floor(Math.min(y,m))),S=al(r.model),b=r.getExtent(),x=S.lastAutoInterval,w=S.lastTickCount;return x!=null&&w!=null&&Math.abs(x-_)<=1&&Math.abs(w-o)<=1&&x>_&&S.axisExtent0===b[0]&&S.axisExtent1===b[1]?_=x:(S.lastTickCount=o,S.lastAutoInterval=_,S.axisExtent0=b[0],S.axisExtent1=b[1]),_}function DB(r){var e=r.getLabelModel();return{axisRotate:r.getRotate?r.getRotate():r.isHorizontal&&!r.isHorizontal()?90:0,labelRotate:e.get("rotate")||0,font:e.getFont()}}function Ub(r,e,t){var a=rl(r),n=r.scale,i=n.getExtent(),o=r.getLabelModel(),s=[],l=Math.max((e||0)+1,1),u=i[0],f=n.count();u!==0&&l>1&&f/l>2&&(u=Math.round(Math.ceil(u/l)*l));var h=Rb(r),v=o.get("showMinLabel")||h,c=o.get("showMaxLabel")||h;v&&u!==i[0]&&d(i[0]);for(var p=u;p<=i[1];p+=l)d(p);c&&p-l!==i[1]&&d(i[1]);function d(g){var y={value:g};s.push(t?g:{formattedLabel:a(y),rawLabel:n.getLabel(y),tickValue:g})}return s}function Yb(r,e,t){var a=r.scale,n=rl(r),i=[];return A(a.getTicks(),function(o){var s=a.getLabel(o),l=o.value;e(o.value,s)&&i.push(t?l:{formattedLabel:n(o),rawLabel:s,tickValue:l})}),i}var Xb=[0,1],fr=function(){function r(e,t,a){this.onBand=!1,this.inverse=!1,this.dim=e,this.scale=t,this._extent=a||[0,0]}return r.prototype.contain=function(e){var t=this._extent,a=Math.min(t[0],t[1]),n=Math.max(t[0],t[1]);return e>=a&&e<=n},r.prototype.containData=function(e){return this.scale.contain(e)},r.prototype.getExtent=function(){return this._extent.slice()},r.prototype.getPixelPrecision=function(e){return tc(e||this.scale.getExtent(),this._extent)},r.prototype.setExtent=function(e,t){var a=this._extent;a[0]=e,a[1]=t},r.prototype.dataToCoord=function(e,t){var a=this._extent,n=this.scale;return e=n.normalize(e),this.onBand&&n.type==="ordinal"&&(a=a.slice(),Zb(a,n.count())),Pt(e,Xb,a,t)},r.prototype.coordToData=function(e,t){var a=this._extent,n=this.scale;this.onBand&&n.type==="ordinal"&&(a=a.slice(),Zb(a,n.count()));var i=Pt(e,a,Xb,t);return this.scale.scale(i)},r.prototype.pointToData=function(e,t){},r.prototype.getTicksCoords=function(e){e=e||{};var t=e.tickModel||this.getTickModel(),a=xB(this,t),n=a.ticks,i=G(n,function(s){return{coord:this.dataToCoord(this.scale.type==="ordinal"?this.scale.getRawOrdinalNumber(s):s),tickValue:s}},this),o=t.get("alignWithLabel");return MB(this,i,o,e.clamp),i},r.prototype.getMinorTicksCoords=function(){if(this.scale.type==="ordinal")return[];var e=this.model.getModel("minorTick"),t=e.get("splitNumber");t>0&&t<100||(t=5);var a=this.scale.getMinorTicks(t),n=G(a,function(i){return G(i,function(o){return{coord:this.dataToCoord(o),tickValue:o}},this)},this);return n},r.prototype.getViewLabels=function(){return SB(this).labels},r.prototype.getLabelModel=function(){return this.model.getModel("axisLabel")},r.prototype.getTickModel=function(){return this.model.getModel("axisTick")},r.prototype.getBandWidth=function(){var e=this._extent,t=this.scale.getExtent(),a=t[1]-t[0]+(this.onBand?1:0);a===0&&(a=1);var n=Math.abs(e[1]-e[0]);return Math.abs(n)/a},r.prototype.calculateCategoryInterval=function(){return AB(this)},r}();function Zb(r,e){var t=r[1]-r[0],a=e,n=t/a/2;r[0]+=n,r[1]-=n}function MB(r,e,t,a){var n=e.length;if(!r.onBand||t||!n)return;var i=r.getExtent(),o,s;if(n===1)e[0].coord=i[0],o=e[1]={coord:i[0]};else{var l=e[n-1].tickValue-e[0].tickValue,u=(e[n-1].coord-e[0].coord)/l;A(e,function(c){c.coord-=u/2});var f=r.scale.getExtent();s=1+f[1]-e[n-1].tickValue,o={coord:e[n-1].coord+u*s},e.push(o)}var h=i[0]>i[1];v(e[0].coord,i[0])&&(a?e[0].coord=i[0]:e.shift()),a&&v(i[0],e[0].coord)&&e.unshift({coord:i[0]}),v(i[1],o.coord)&&(a?o.coord=i[1]:e.pop()),a&&v(o.coord,i[1])&&e.push({coord:i[1]});function v(c,p){return c=Wt(c),p=Wt(p),h?c>p:cn&&(n+=nl);var c=Math.atan2(s,o);if(c<0&&(c+=nl),c>=a&&c<=n||c+nl>=a&&c+nl<=n)return l[0]=f,l[1]=h,u-t;var p=t*Math.cos(a)+r,d=t*Math.sin(a)+e,g=t*Math.cos(n)+r,y=t*Math.sin(n)+e,m=(p-o)*(p-o)+(d-s)*(d-s),_=(g-o)*(g-o)+(y-s)*(y-s);return m<_?(l[0]=p,l[1]=d,Math.sqrt(m)):(l[0]=g,l[1]=y,Math.sqrt(_))}function Xf(r,e,t,a,n,i,o,s){var l=n-r,u=i-e,f=t-r,h=a-e,v=Math.sqrt(f*f+h*h);f/=v,h/=v;var c=l*f+u*h,p=c/v;s&&(p=Math.min(Math.max(p,0),1)),p*=v;var d=o[0]=r+p*f,g=o[1]=e+p*h;return Math.sqrt((d-n)*(d-n)+(g-i)*(g-i))}function $b(r,e,t,a,n,i,o){t<0&&(r=r+t,t=-t),a<0&&(e=e+a,a=-a);var s=r+t,l=e+a,u=o[0]=Math.min(Math.max(n,r),s),f=o[1]=Math.min(Math.max(i,e),l);return Math.sqrt((u-n)*(u-n)+(f-i)*(f-i))}var Pr=[];function NB(r,e,t){var a=$b(e.x,e.y,e.width,e.height,r.x,r.y,Pr);return t.set(Pr[0],Pr[1]),a}function BB(r,e,t){for(var a=0,n=0,i=0,o=0,s,l,u=Infinity,f=e.data,h=r.x,v=r.y,c=0;c0){e=e/180*Math.PI,Rr.fromArray(r[0]),Vt.fromArray(r[1]),qt.fromArray(r[2]),ut.sub(qr,Rr,Vt),ut.sub(Kr,qt,Vt);var t=qr.len(),a=Kr.len();if(!(t<.001||a<.001)){qr.scale(1/t),Kr.scale(1/a);var n=qr.dot(Kr),i=Math.cos(e);if(i1&&ut.copy(Le,qt),Le.toArray(r[1])}}}}function VB(r,e,t){if(t<=180&&t>0){t=t/180*Math.PI,Rr.fromArray(r[0]),Vt.fromArray(r[1]),qt.fromArray(r[2]),ut.sub(qr,Vt,Rr),ut.sub(Kr,qt,Vt);var a=qr.len(),n=Kr.len();if(!(a<.001||n<.001)){qr.scale(1/a),Kr.scale(1/n);var i=qr.dot(e),o=Math.cos(t);if(i=l)ut.copy(Le,qt);else{Le.scaleAndAdd(Kr,s/Math.tan(Math.PI/2-f));var h=qt.x!==Vt.x?(Le.x-Vt.x)/(qt.x-Vt.x):(Le.y-Vt.y)/(qt.y-Vt.y);if(isNaN(h))return;h<0?ut.copy(Le,Vt):h>1&&ut.copy(Le,qt)}Le.toArray(r[1])}}}}function jb(r,e,t,a){var n=t==="normal",i=n?r:r.ensureState(t);i.ignore=e;var o=a.get("smooth");o&&o===!0&&(o=.3),i.shape=i.shape||{},o>0&&(i.shape.smooth=o);var s=a.getModel("lineStyle").getLineStyle();n?r.useStyle(s):i.style=s}function zB(r,e){var t=e.smooth,a=e.points;if(!!a)if(r.moveTo(a[0][0],a[0][1]),t>0&&a.length>=3){var n=ra(a[0],a[1]),i=ra(a[1],a[2]);if(!n||!i){r.lineTo(a[1][0],a[1][1]),r.lineTo(a[2][0],a[2][1]);return}var o=Math.min(n,i)*t,s=Fo([],a[1],a[0],o/n),l=Fo([],a[1],a[2],o/i),u=Fo([],s,l,.5);r.bezierCurveTo(s[0],s[1],s[0],s[1],u[0],u[1]),r.bezierCurveTo(l[0],l[1],l[0],l[1],a[2][0],a[2][1])}else for(var f=1;f0&&i&&b(-f/o,0,o);var d=r[0],g=r[o-1],y,m;_(),y<0&&x(-y,.8),m<0&&x(m,.8),_(),S(y,m,1),S(m,y,-1),_(),y<0&&w(-y),m<0&&w(m);function _(){y=d.rect[e]-a,m=n-g.rect[e]-g.rect[t]}function S(T,C,D){if(T<0){var M=Math.min(C,-T);if(M>0){b(M*D,0,o);var I=M+T;I<0&&x(-I*D,1)}else x(-T*D,1)}}function b(T,C,D){T!==0&&(u=!0);for(var M=C;M0)for(var I=0;I0;I--){var E=D[I-1]*R;b(-E,I,o)}}}function w(T){var C=T<0?-1:1;T=Math.abs(T);for(var D=Math.ceil(T/(o-1)),M=0;M0?b(D,0,M+1):b(-D,o-M-1,o),T-=D,T<=0)return}return u}function GB(r,e,t,a){return Jb(r,"x","width",e,t,a)}function tw(r,e,t,a){return Jb(r,"y","height",e,t,a)}function ew(r){var e=[];r.sort(function(d,g){return g.priority-d.priority});var t=new ft(0,0,0,0);function a(d){if(!d.ignore){var g=d.ensureState("emphasis");g.ignore==null&&(g.ignore=!1)}d.ignore=!0}for(var n=0;n=0&&a.attr(i.oldLayoutSelect),vt(v,"emphasis")>=0&&a.attr(i.oldLayoutEmphasis)),At(a,u,t,l)}else if(a.attr(u),!Xi(a).valueAnimation){var h=lt(a.style.opacity,1);a.style.opacity=0,Gt(a,{style:{opacity:h}},t,l)}if(i.oldLayout=u,a.states.select){var c=i.oldLayoutSelect={};$f(c,u,qf),$f(c,a.states.select,qf)}if(a.states.emphasis){var p=i.oldLayoutEmphasis={};$f(p,u,qf),$f(p,a.states.emphasis,qf)}A1(a,l,f,t,t)}if(n&&!n.ignore&&!n.invisible){var i=WB(n),o=i.oldLayout,d={points:n.shape.points};o?(n.attr({shape:o}),At(n,{shape:d},t)):(n.setShape(d),n.style.strokePercent=0,Gt(n,{style:{strokePercent:1}},t)),i.oldLayout=d}},r}(),Cd=Ct();function YB(r){r.registerUpdateLifecycle("series:beforeupdate",function(e,t,a){var n=Cd(t).labelManager;n||(n=Cd(t).labelManager=new UB),n.clearLabels()}),r.registerUpdateLifecycle("series:layoutlabels",function(e,t,a){var n=Cd(t).labelManager;a.updatedSeries.forEach(function(i){n.addLabelsOfSeries(t.getViewOfSeriesModel(i))}),n.updateLayoutConfig(t),n.layout(t),n.processLabelsOverall()})}var Ad=Math.sin,Dd=Math.cos,aw=Math.PI,Jn=Math.PI*2,XB=180/aw,nw=function(){function r(){}return r.prototype.reset=function(e){this._start=!0,this._d=[],this._str="",this._p=Math.pow(10,e||4)},r.prototype.moveTo=function(e,t){this._add("M",e,t)},r.prototype.lineTo=function(e,t){this._add("L",e,t)},r.prototype.bezierCurveTo=function(e,t,a,n,i,o){this._add("C",e,t,a,n,i,o)},r.prototype.quadraticCurveTo=function(e,t,a,n){this._add("Q",e,t,a,n)},r.prototype.arc=function(e,t,a,n,i,o){this.ellipse(e,t,a,a,0,n,i,o)},r.prototype.ellipse=function(e,t,a,n,i,o,s,l){var u=s-o,f=!l,h=Math.abs(u),v=ka(h-Jn)||(f?u>=Jn:-u>=Jn),c=u>0?u%Jn:u%Jn+Jn,p=!1;v?p=!0:ka(h)?p=!1:p=c>=aw==!!f;var d=e+a*Dd(o),g=t+n*Ad(o);this._start&&this._add("M",d,g);var y=Math.round(i*XB);if(v){var m=1/this._p,_=(f?1:-1)*(Jn-m);this._add("A",a,n,y,1,+f,e+a*Dd(o+_),t+n*Ad(o+_)),m>.01&&this._add("A",a,n,y,0,+f,d,g)}else{var S=e+a*Dd(s),b=t+n*Ad(s);this._add("A",a,n,y,+p,+f,S,b)}},r.prototype.rect=function(e,t,a,n){this._add("M",e,t),this._add("l",a,0),this._add("l",0,n),this._add("l",-a,0),this._add("Z")},r.prototype.closePath=function(){this._d.length>0&&this._add("Z")},r.prototype._add=function(e,t,a,n,i,o,s,l,u){for(var f=[],h=this._p,v=1;v"}function eV(r){return""}function Id(r,e){e=e||{};var t=e.newline?` +`:"";function a(n){var i=n.children,o=n.tag,s=n.attrs;return tV(o,s)+Ce(n.text)+(i?""+t+G(i,function(l){return a(l)}).join(t)+t:"")+eV(o)}return a(r)}function rV(r,e,t){t=t||{};var a=t.newline?` +`:"",n=" {"+a,i=a+"}",o=G(St(r),function(l){return l+n+G(St(r[l]),function(u){return u+":"+r[l][u]+";"}).join(a)+i}).join(a),s=G(St(e),function(l){return"@keyframes "+l+n+G(St(e[l]),function(u){return u+n+G(St(e[l][u]),function(f){var h=e[l][u][f];return f==="d"&&(h='path("'+h+'")'),f+":"+h+";"}).join(a)+i}).join(a)+i}).join(a);return!o&&!s?"":[""].join(a)}function Ld(r){return{zrId:r,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssClassIdx:0,cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function lw(r,e,t,a){return oe("svg","root",{width:r,height:e,xmlns:iw,"xmlns:xlink":ow,version:"1.1",baseProfile:"full",viewBox:a?"0 0 "+r+" "+e:!1},t)}var uw={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},ti="transform-origin";function aV(r,e,t){var a=B({},r.shape);B(a,e),r.buildPath(t,a);var n=new nw;return n.reset(S0(r)),t.rebuildPath(n,1),n.generateStr(),n.getStr()}function nV(r,e){var t=e.originX,a=e.originY;(t||a)&&(r[ti]=t+"px "+a+"px")}var iV={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function fw(r,e){var t=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[t]=r,t}function oV(r,e,t){var a=r.shape.paths,n={},i,o;if(A(a,function(l){var u=Ld(t.zrId);u.animation=!0,Kf(l,{},u,!0);var f=u.cssAnims,h=u.cssNodes,v=St(f),c=v.length;if(!!c){o=v[c-1];var p=f[o];for(var d in p){var g=p[d];n[d]=n[d]||{d:""},n[d].d+=g.d||""}for(var y in h){var m=h[y].animation;m.indexOf(o)>=0&&(i=m)}}}),!!i){e.d=!1;var s=fw(n,t);return i.replace(o,s)}}function hw(r){return U(r)?uw[r]?"cubic-bezier("+uw[r]+")":Cv(r)?r:"":""}function Kf(r,e,t,a){var n=r.animators,i=n.length,o=[];if(r instanceof Hu){var s=oV(r,e,t);if(s)o.push(s);else if(!i)return}else if(!i)return;for(var l={},u=0;u0}).length){var pt=fw(w,t);return pt+" "+m[0]+" both"}}for(var g in l){var s=d(l[g]);s&&o.push(s)}if(o.length){var y=t.zrId+"-cls-"+t.cssClassIdx++;t.cssNodes["."+y]={animation:o.join(",")},e.class=y}}var ol=Math.round;function vw(r){return r&&U(r.src)}function cw(r){return r&&K(r.toDataURL)}function Pd(r,e,t,a){jB(function(n,i){var o=n==="fill"||n==="stroke";o&&_0(i)?_w(e,r,n,a):o&&Rv(i)?Sw(t,r,n,a):r[n]=i},e,t,!1),cV(t,r,a)}function pw(r){return ka(r[0]-1)&&ka(r[1])&&ka(r[2])&&ka(r[3]-1)}function sV(r){return ka(r[4])&&ka(r[5])}function Rd(r,e,t){if(e&&!(sV(e)&&pw(e))){var a=t?10:1e4;r.transform=pw(e)?"translate("+ol(e[4]*a)/a+" "+ol(e[5]*a)/a+")":c2(e)}}function dw(r,e,t){for(var a=r.points,n=[],i=0;ii?(p=t[l+1]==null?null:t[l+1].elm,Dw(r,p,t,n,l)):jf(r,e,a,i))}function vo(r,e){var t=e.elm=r.elm,a=r.children,n=e.children;r!==e&&(Od(r,e),kd(e.text)?jr(a)&&jr(n)?a!==n&&mV(t,a,n):jr(n)?(jr(r.text)&&Ed(t,""),Dw(t,null,n,0,n.length-1)):jr(a)?jf(t,a,0,a.length-1):jr(r.text)&&Ed(t,""):r.text!==e.text&&(jr(a)&&jf(t,a,0,a.length-1),Ed(t,e.text)))}function _V(r,e){if(sl(r,e))vo(r,e);else{var t=r.elm,a=Tw(t);ll(e),a!==null&&(ei(a,e.elm,Cw(t)),jf(a,[r],0,0))}return e}var SV=0,xV=function(){function r(e,t,a){if(this.type="svg",this.refreshHover=Mw(),this.configLayer=Mw(),this.storage=t,this._opts=a=B({},a),this.root=e,this._id="zr"+SV++,this._oldVNode=lw(a.width,a.height),e&&!a.ssr){var n=this._viewport=document.createElement("div");n.style.cssText="position:relative;overflow:hidden";var i=this._svgDom=this._oldVNode.elm=sw("svg");Od(null,this._oldVNode),n.appendChild(i),e.appendChild(n)}this.resize(a.width,a.height)}return r.prototype.getType=function(){return this.type},r.prototype.getViewportRoot=function(){return this._viewport},r.prototype.getViewportRootOffset=function(){var e=this.getViewportRoot();if(e)return{offsetLeft:e.offsetLeft||0,offsetTop:e.offsetTop||0}},r.prototype.getSvgDom=function(){return this._svgDom},r.prototype.refresh=function(){if(this.root){var e=this.renderToVNode({willUpdate:!0});e.attrs.style="position:absolute;left:0;top:0;user-select:none",_V(this._oldVNode,e),this._oldVNode=e}},r.prototype.renderOneToVNode=function(e){return mw(e,Ld(this._id))},r.prototype.renderToVNode=function(e){e=e||{};var t=this.storage.getDisplayList(!0),a=this._width,n=this._height,i=Ld(this._id);i.animation=e.animation,i.willUpdate=e.willUpdate,i.compress=e.compress;var o=[],s=this._bgVNode=bV(a,n,this._backgroundColor,i);s&&o.push(s);var l=e.compress?null:this._mainVNode=oe("g","main",{},[]);this._paintList(t,i,l?l.children:o),l&&o.push(l);var u=G(St(i.defs),function(v){return i.defs[v]});if(u.length&&o.push(oe("defs","defs",{},u)),e.animation){var f=rV(i.cssNodes,i.cssAnims,{newline:!0});if(f){var h=oe("style","stl",{},[],f);o.push(h)}}return lw(a,n,o,e.useViewBox)},r.prototype.renderToString=function(e){return e=e||{},Id(this.renderToVNode({animation:lt(e.cssAnimation,!0),willUpdate:!1,compress:!0,useViewBox:lt(e.useViewBox,!0)}),{newline:!0})},r.prototype.setBackgroundColor=function(e){this._backgroundColor=e},r.prototype.getSvgRoot=function(){return this._mainVNode&&this._mainVNode.elm},r.prototype._paintList=function(e,t,a){for(var n=e.length,i=[],o=0,s,l,u=0,f=0;f=0&&!(v&&l&&v[d]===l[d]);d--);for(var g=p-1;g>d;g--)o--,s=i[o-1];for(var y=d+1;y=s)}}for(var h=this.__startIndex;h15)break}}P.prevElClipPaths&&y.restore()};if(m)if(m.length===0)T=g.__endIndex;else for(var D=c.dpr,M=0;M0&&e>n[0]){for(l=0;le);l++);s=a[n[l]]}if(n.splice(l+1,0,e),a[e]=t,!t.virtual)if(s){var u=s.dom;u.nextSibling?o.insertBefore(t.dom,u.nextSibling):o.appendChild(t.dom)}else o.firstChild?o.insertBefore(t.dom,o.firstChild):o.appendChild(t.dom);t.__painter=this}},r.prototype.eachLayer=function(e,t){for(var a=this._zlevelList,n=0;n0?Qf:0),this._needsManuallyCompositing),f.__builtin__||Xl("ZLevel "+u+" has been used by unkown layer "+f.id),f!==i&&(f.__used=!0,f.__startIndex!==l&&(f.__dirty=!0),f.__startIndex=l,f.incremental?f.__drawIndex=-1:f.__drawIndex=l,t(l),i=f),n.__dirty&Fe&&!n.__inHover&&(f.__dirty=!0,f.incremental&&f.__drawIndex<0&&(f.__drawIndex=l))}t(l),this.eachBuiltinLayer(function(h,v){!h.__used&&h.getElementCount()>0&&(h.__dirty=!0,h.__startIndex=h.__endIndex=h.__drawIndex=0),h.__dirty&&h.__drawIndex<0&&(h.__drawIndex=h.__startIndex)})},r.prototype.clear=function(){return this.eachBuiltinLayer(this._clearLayer),this},r.prototype._clearLayer=function(e){e.clear()},r.prototype.setBackgroundColor=function(e){this._backgroundColor=e,A(this._layers,function(t){t.setUnpainted()})},r.prototype.configLayer=function(e,t){if(t){var a=this._layerConfig;a[e]?ot(a[e],t,!0):a[e]=t;for(var n=0;n-1&&(u.style.stroke=u.style.fill,u.style.fill="#fff",u.style.lineWidth=2),a},e.type="series.line",e.dependencies=["grid","polar"],e.defaultOption={z:3,coordinateSystem:"cartesian2d",legendHoverLink:!0,clip:!0,label:{position:"top"},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:"solid"},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:"emptyCircle",symbolSize:4,symbolRotate:null,showSymbol:!0,showAllSymbol:"auto",connectNulls:!1,sampling:"none",animationEasing:"linear",progressive:0,hoverLayerThreshold:Infinity,universalTransition:{divideShape:"clone"},triggerLineEvent:!1},e}(kt);function co(r,e){var t=r.mapDimensionsAll("defaultedLabel"),a=t.length;if(a===1){var n=to(r,e,t[0]);return n!=null?n+"":null}else if(a){for(var i=[],o=0;o=0&&a.push(e[i])}return a.join(" ")}var ul=function(r){O(e,r);function e(t,a,n,i){var o=r.call(this)||this;return o.updateData(t,a,n,i),o}return e.prototype._createSymbol=function(t,a,n,i,o){this.removeAll();var s=$t(t,-1,-1,2,2,null,o);s.attr({z2:100,culling:!0,scaleX:i[0]/2,scaleY:i[1]/2}),s.drift=LV,this._symbolType=t,this.add(s)},e.prototype.stopSymbolAnimation=function(t){this.childAt(0).stopAnimation(null,t)},e.prototype.getSymbolType=function(){return this._symbolType},e.prototype.getSymbolPath=function(){return this.childAt(0)},e.prototype.highlight=function(){va(this.childAt(0))},e.prototype.downplay=function(){ca(this.childAt(0))},e.prototype.setZ=function(t,a){var n=this.childAt(0);n.zlevel=t,n.z=a},e.prototype.setDraggable=function(t,a){var n=this.childAt(0);n.draggable=t,n.cursor=!a&&t?"move":n.cursor},e.prototype.updateData=function(t,a,n,i){this.silent=!1;var o=t.getItemVisual(a,"symbol")||"circle",s=t.hostModel,l=e.getSymbolSize(t,a),u=o!==this._symbolType,f=i&&i.disableAnimation;if(u){var h=t.getItemVisual(a,"symbolKeepAspect");this._createSymbol(o,t,a,l,h)}else{var v=this.childAt(0);v.silent=!1;var c={scaleX:l[0]/2,scaleY:l[1]/2};f?v.attr(c):At(v,c,s,a),Cr(v)}if(this._updateCommon(t,a,l,n,i),u){var v=this.childAt(0);if(!f){var c={scaleX:this._sizeX,scaleY:this._sizeY,style:{opacity:v.style.opacity}};v.scaleX=v.scaleY=0,v.style.opacity=0,Gt(v,c,s,a)}}f&&this.childAt(0).stopAnimation("leave")},e.prototype._updateCommon=function(t,a,n,i,o){var s=this.childAt(0),l=t.hostModel,u,f,h,v,c,p,d,g,y;if(i&&(u=i.emphasisItemStyle,f=i.blurItemStyle,h=i.selectItemStyle,v=i.focus,c=i.blurScope,d=i.labelStatesModels,g=i.hoverScale,y=i.cursorStyle,p=i.emphasisDisabled),!i||t.hasItemOption){var m=i&&i.itemModel?i.itemModel:t.getItemModel(a),_=m.getModel("emphasis");u=_.getModel("itemStyle").getItemStyle(),h=m.getModel(["select","itemStyle"]).getItemStyle(),f=m.getModel(["blur","itemStyle"]).getItemStyle(),v=_.get("focus"),c=_.get("blurScope"),p=_.get("disabled"),d=ne(m),g=_.getShallow("scale"),y=m.getShallow("cursor")}var S=t.getItemVisual(a,"symbolRotate");s.attr("rotation",(S||0)*Math.PI/180||0);var b=io(t.getItemVisual(a,"symbolOffset"),n);b&&(s.x=b[0],s.y=b[1]),y&&s.attr("cursor",y);var x=t.getItemVisual(a,"style"),w=x.fill;if(s instanceof ae){var T=s.style;s.useStyle(B({image:T.image,x:T.x,y:T.y,width:T.width,height:T.height},x))}else s.__isEmptyBrush?s.useStyle(B({},x)):s.useStyle(x),s.style.decal=null,s.setColor(w,o&&o.symbolInnerColor),s.style.strokeNoScale=!0;var C=t.getItemVisual(a,"liftZ"),D=this._z2;C!=null?D==null&&(this._z2=s.z2,s.z2+=C):D!=null&&(s.z2=D,this._z2=null);var M=o&&o.useNameLabel;ve(s,d,{labelFetcher:l,labelDataIndex:a,defaultText:I,inheritColor:w,defaultOpacity:x.opacity});function I(R){return M?t.getName(R):co(t,R)}this._sizeX=n[0]/2,this._sizeY=n[1]/2;var L=s.ensureState("emphasis");L.style=u,s.ensureState("select").style=h,s.ensureState("blur").style=f;var P=g==null||g===!0?Math.max(1.1,3/this._sizeY):isFinite(g)&&g>0?+g:1;L.scaleX=this._sizeX*P,L.scaleY=this._sizeY*P,this.setSymbolScale(1),Ut(this,v,c,p)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,a,n){var i=this.childAt(0),o=nt(this).dataIndex,s=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var l=i.getTextContent();l&&Fa(l,{style:{opacity:0}},a,{dataIndex:o,removeOpt:s,cb:function(){i.removeTextContent()}})}else i.removeTextContent();Fa(i,{style:{opacity:0},scaleX:0,scaleY:0},a,{dataIndex:o,cb:t,removeOpt:s})},e.getSymbolSize=function(t,a){return Ys(t.getItemVisual(a,"symbolSize"))},e}(rt);function LV(r,e){this.parent.drift(r,e)}function Bd(r,e,t,a){return e&&!isNaN(e[0])&&!isNaN(e[1])&&!(a.isIgnore&&a.isIgnore(t))&&!(a.clipShape&&!a.clipShape.contain(e[0],e[1]))&&r.getItemVisual(t,"symbol")!=="none"}function Rw(r){return r!=null&&!J(r)&&(r={isIgnore:r}),r||{}}function Ew(r){var e=r.hostModel,t=e.getModel("emphasis");return{emphasisItemStyle:t.getModel("itemStyle").getItemStyle(),blurItemStyle:e.getModel(["blur","itemStyle"]).getItemStyle(),selectItemStyle:e.getModel(["select","itemStyle"]).getItemStyle(),focus:t.get("focus"),blurScope:t.get("blurScope"),emphasisDisabled:t.get("disabled"),hoverScale:t.get("scale"),labelStatesModels:ne(e),cursorStyle:e.get("cursor")}}var fl=function(){function r(e){this.group=new rt,this._SymbolCtor=e||ul}return r.prototype.updateData=function(e,t){this._progressiveEls=null,t=Rw(t);var a=this.group,n=e.hostModel,i=this._data,o=this._SymbolCtor,s=t.disableAnimation,l=Ew(e),u={disableAnimation:s},f=t.getSymbolPoint||function(h){return e.getItemLayout(h)};i||a.removeAll(),e.diff(i).add(function(h){var v=f(h);if(Bd(e,v,h,t)){var c=new o(e,h,l,u);c.setPosition(v),e.setItemGraphicEl(h,c),a.add(c)}}).update(function(h,v){var c=i.getItemGraphicEl(v),p=f(h);if(!Bd(e,p,h,t)){a.remove(c);return}var d=e.getItemVisual(h,"symbol")||"circle",g=c&&c.getSymbolType&&c.getSymbolType();if(!c||g&&g!==d)a.remove(c),c=new o(e,h,l,u),c.setPosition(p);else{c.updateData(e,h,l,u);var y={x:p[0],y:p[1]};s?c.attr(y):At(c,y,n)}a.add(c),e.setItemGraphicEl(h,c)}).remove(function(h){var v=i.getItemGraphicEl(h);v&&v.fadeOut(function(){a.remove(v)},n)}).execute(),this._getSymbolPoint=f,this._data=e},r.prototype.updateLayout=function(){var e=this,t=this._data;t&&t.eachItemGraphicEl(function(a,n){var i=e._getSymbolPoint(n);a.setPosition(i),a.markRedraw()})},r.prototype.incrementalPrepareUpdate=function(e){this._seriesScope=Ew(e),this._data=null,this.group.removeAll()},r.prototype.incrementalUpdate=function(e,t,a){this._progressiveEls=[],a=Rw(a);function n(l){l.isGroup||(l.incremental=!0,l.ensureState("emphasis").hoverLayer=!0)}for(var i=e.start;i0?t=a[0]:a[1]<0&&(t=a[1]),t}function Ow(r,e,t,a){var n=NaN;r.stacked&&(n=t.get(t.getCalculationInfo("stackedOverDimension"),a)),isNaN(n)&&(n=r.valueStart);var i=r.baseDataOffset,o=[];return o[i]=t.get(r.baseDim,a),o[1-i]=n,e.dataToPoint(o)}function RV(r,e){var t=[];return e.diff(r).add(function(a){t.push({cmd:"+",idx:a})}).update(function(a,n){t.push({cmd:"=",idx:n,idx1:a})}).remove(function(a){t.push({cmd:"-",idx:a})}).execute(),t}function EV(r,e,t,a,n,i,o,s){for(var l=RV(r,e),u=[],f=[],h=[],v=[],c=[],p=[],d=[],g=kw(n,e,o),y=r.getLayout("points")||[],m=e.getLayout("points")||[],_=0;_=n||d<0)break;if(ai(y,m)){if(l){d+=i;continue}break}if(d===t)r[i>0?"moveTo":"lineTo"](y,m),h=y,v=m;else{var _=y-u,S=m-f;if(_*_+S*S<.5){d+=i;continue}if(o>0){for(var b=d+i,x=e[b*2],w=e[b*2+1];x===y&&w===m&&g=a||ai(x,w))c=y,p=m;else{D=x-u,M=w-f;var P=y-u,R=x-y,E=m-f,N=w-m,k=void 0,V=void 0;if(s==="x"){k=Math.abs(P),V=Math.abs(R);var F=D>0?1:-1;c=y-F*k*o,p=m,I=y+F*V*o,L=m}else if(s==="y"){k=Math.abs(E),V=Math.abs(N);var W=M>0?1:-1;c=y,p=m-W*k*o,I=y,L=m+W*V*o}else k=Math.sqrt(P*P+E*E),V=Math.sqrt(R*R+N*N),C=V/(V+k),c=y-D*o*(1-C),p=m-M*o*(1-C),I=y+D*o*C,L=m+M*o*C,I=Qa(I,Ja(x,y)),L=Qa(L,Ja(w,m)),I=Ja(I,Qa(x,y)),L=Ja(L,Qa(w,m)),D=I-y,M=L-m,c=y-D*k/V,p=m-M*k/V,c=Qa(c,Ja(u,y)),p=Qa(p,Ja(f,m)),c=Ja(c,Qa(u,y)),p=Ja(p,Qa(f,m)),D=y-c,M=m-p,I=y+D*V/k,L=m+M*V/k}r.bezierCurveTo(h,v,c,p,y,m),h=I,v=L}else r.lineTo(y,m)}u=y,f=m,d+=i}return g}var Nw=function(){function r(){this.smooth=0,this.smoothConstraint=!0}return r}(),kV=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="ec-polyline",a}return e.prototype.getDefaultStyle=function(){return{stroke:"#000",fill:null}},e.prototype.getDefaultShape=function(){return new Nw},e.prototype.buildPath=function(t,a){var n=a.points,i=0,o=n.length/2;if(a.connectNulls){for(;o>0&&ai(n[o*2-2],n[o*2-1]);o--);for(;i=0){var S=u?(p-l)*_+l:(c-s)*_+s;return u?[t,S]:[S,t]}s=c,l=p;break;case o.C:c=i[h++],p=i[h++],d=i[h++],g=i[h++],y=i[h++],m=i[h++];var b=u?su(s,c,d,y,t,f):su(l,p,g,m,t,f);if(b>0)for(var x=0;x=0){var S=u?re(l,p,g,m,w):re(s,c,d,y,w);return u?[t,S]:[S,t]}}s=y,l=m;break}}},e}(dt),OV=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Nw),Bw=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="ec-polygon",a}return e.prototype.getDefaultShape=function(){return new OV},e.prototype.buildPath=function(t,a){var n=a.points,i=a.stackedOnPoints,o=0,s=n.length/2,l=a.smoothMonotone;if(a.connectNulls){for(;s>0&&ai(n[s*2-2],n[s*2-1]);s--);for(;oe){i?t.push(o(i,l,e)):n&&t.push(o(n,l,0),o(n,l,e));break}else n&&(t.push(o(n,l,0)),n=null),t.push(l),i=l}return t}function VV(r,e,t){var a=r.getVisual("visualMeta");if(!(!a||!a.length||!r.count())&&e.type==="cartesian2d"){for(var n,i,o=a.length-1;o>=0;o--){var s=r.getDimensionInfo(a[o].dimension);if(n=s&&s.coordDim,n==="x"||n==="y"){i=a[o];break}}if(!!i){var l=e.getAxis(n),u=G(i.stops,function(_){return{coord:l.toGlobalCoord(l.dataToCoord(_.value)),color:_.color}}),f=u.length,h=i.outerColors.slice();f&&u[0].coord>u[f-1].coord&&(u.reverse(),h.reverse());var v=BV(u,n==="x"?t.getWidth():t.getHeight()),c=v.length;if(!c&&f)return u[0].coord<0?h[1]?h[1]:u[f-1].color:h[0]?h[0]:u[0].color;var p=10,d=v[0].coord-p,g=v[c-1].coord+p,y=g-d;if(y<.001)return"transparent";A(v,function(_){_.offset=(_.coord-d)/y}),v.push({offset:c?v[c-1].offset:.5,color:h[1]||"transparent"}),v.unshift({offset:c?v[0].offset:.5,color:h[0]||"transparent"});var m=new Gi(0,0,0,0,v,!0);return m[n]=d,m[n+"2"]=g,m}}}function zV(r,e,t){var a=r.get("showAllSymbol"),n=a==="auto";if(!(a&&!n)){var i=t.getAxesByScale("ordinal")[0];if(!!i&&!(n&&GV(i,e))){var o=e.mapDimension(i.dim),s={};return A(i.getViewLabels(),function(l){var u=i.scale.getRawOrdinalNumber(l.tickValue);s[u]=1}),function(l){return!s.hasOwnProperty(e.get(o,l))}}}}function GV(r,e){var t=r.getExtent(),a=Math.abs(t[1]-t[0])/r.scale.count();isNaN(a)&&(a=0);for(var n=e.count(),i=Math.max(1,Math.round(n/5)),o=0;oa)return!1;return!0}function FV(r,e){return isNaN(r)||isNaN(e)}function HV(r){for(var e=r.length/2;e>0&&FV(r[e*2-2],r[e*2-1]);e--);return e-1}function Uw(r,e){return[r[e*2],r[e*2+1]]}function WV(r,e,t){for(var a=r.length/2,n=t==="x"?0:1,i,o,s=0,l=-1,u=0;u=e||i>=e&&o<=e){l=u;break}s=u,i=o}return{range:[s,l],t:(e-i)/(o-i)}}function Yw(r){if(r.get(["endLabel","show"]))return!0;for(var e=0;e0&&t.get(["emphasis","lineStyle","width"])==="bolder"){var F=d.getState("emphasis").style;F.lineWidth=+d.style.lineWidth+1}nt(d).seriesIndex=t.seriesIndex,Ut(d,N,k,V);var W=Ww(t.get("smooth")),Z=t.get("smoothMonotone");if(d.setShape({smooth:W,smoothMonotone:Z,connectNulls:T}),g){var Q=l.getCalculationInfo("stackedOnSeries"),tt=0;g.useStyle(j(f.getAreaStyle(),{fill:L,opacity:.7,lineJoin:"bevel",decal:l.getVisual("style").decal})),Q&&(tt=Ww(Q.get("smooth"))),g.setShape({smooth:W,stackedOnSmooth:tt,smoothMonotone:Z,connectNulls:T}),he(g,t,"areaStyle"),nt(g).seriesIndex=t.seriesIndex,Ut(g,N,k,V)}var yt=function(Dt){i._changePolyState(Dt)};l.eachItemGraphicEl(function(Dt){Dt&&(Dt.onHoverStateChange=yt)}),this._polyline.onHoverStateChange=yt,this._data=l,this._coordSys=o,this._stackedOnPoints=x,this._points=h,this._step=M,this._valueOrigin=S,t.get("triggerLineEvent")&&(this.packEventData(t,d),g&&this.packEventData(t,g))},e.prototype.packEventData=function(t,a){nt(a).eventData={componentType:"series",componentSubType:"line",componentIndex:t.componentIndex,seriesIndex:t.seriesIndex,seriesName:t.name,seriesType:"line"}},e.prototype.highlight=function(t,a,n,i){var o=t.getData(),s=xn(o,i);if(this._changePolyState("emphasis"),!(s instanceof Array)&&s!=null&&s>=0){var l=o.getLayout("points"),u=o.getItemGraphicEl(s);if(!u){var f=l[s*2],h=l[s*2+1];if(isNaN(f)||isNaN(h)||this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(f,h))return;var v=t.get("zlevel")||0,c=t.get("z")||0;u=new ul(o,s),u.x=f,u.y=h,u.setZ(v,c);var p=u.getSymbolPath().getTextContent();p&&(p.zlevel=v,p.z=c,p.z2=this._polyline.z2+1),u.__temp=!0,o.setItemGraphicEl(s,u),u.stopSymbolAnimation(!0),this.group.add(u)}u.highlight()}else Rt.prototype.highlight.call(this,t,a,n,i)},e.prototype.downplay=function(t,a,n,i){var o=t.getData(),s=xn(o,i);if(this._changePolyState("normal"),s!=null&&s>=0){var l=o.getItemGraphicEl(s);l&&(l.__temp?(o.setItemGraphicEl(s,null),this.group.remove(l)):l.downplay())}else Rt.prototype.downplay.call(this,t,a,n,i)},e.prototype._changePolyState=function(t){var a=this._polygon;Vu(this._polyline,t),a&&Vu(a,t)},e.prototype._newPolyline=function(t){var a=this._polyline;return a&&this._lineGroup.remove(a),a=new kV({shape:{points:t},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(a),this._polyline=a,a},e.prototype._newPolygon=function(t,a){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new Bw({shape:{points:t,stackedOnPoints:a},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},e.prototype._initSymbolLabelAnimation=function(t,a,n){var i,o,s=a.getBaseAxis(),l=s.inverse;a.type==="cartesian2d"?(i=s.isHorizontal(),o=!1):a.type==="polar"&&(i=s.dim==="angle",o=!0);var u=t.hostModel,f=u.get("animationDuration");K(f)&&(f=f(null));var h=u.get("animationDelay")||0,v=K(h)?h(null):h;t.eachItemGraphicEl(function(c,p){var d=c;if(d){var g=[c.x,c.y],y=void 0,m=void 0,_=void 0;if(n)if(o){var S=n,b=a.pointToCoord(g);i?(y=S.startAngle,m=S.endAngle,_=-b[1]/180*Math.PI):(y=S.r0,m=S.r,_=b[0])}else{var x=n;i?(y=x.x,m=x.x+x.width,_=c.x):(y=x.y+x.height,m=x.y,_=c.y)}var w=m===y?0:(_-y)/(m-y);l&&(w=1-w);var T=K(h)?h(p):f*w+v,C=d.getSymbolPath(),D=C.getTextContent();d.attr({scaleX:0,scaleY:0}),d.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:T}),D&&D.animateFrom({style:{opacity:0}},{duration:300,delay:T}),C.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,a,n){var i=t.getModel("endLabel");if(Yw(t)){var o=t.getData(),s=this._polyline,l=o.getLayout("points");if(!l){s.removeTextContent(),this._endLabel=null;return}var u=this._endLabel;u||(u=this._endLabel=new bt({z2:200}),u.ignoreClip=!0,s.setTextContent(this._endLabel),s.disableLabelAnimation=!0);var f=HV(l);f>=0&&(ve(s,ne(t,"endLabel"),{inheritColor:n,labelFetcher:t,labelDataIndex:f,defaultText:function(h,v,c){return c!=null?Pw(o,c):co(o,h)},enableTextSetter:!0},UV(i,a)),s.textConfig.position=null)}else this._endLabel&&(this._polyline.removeTextContent(),this._endLabel=null)},e.prototype._endLabelOnDuring=function(t,a,n,i,o,s,l){var u=this._endLabel,f=this._polyline;if(u){t<1&&i.originalX==null&&(i.originalX=u.x,i.originalY=u.y);var h=n.getLayout("points"),v=n.hostModel,c=v.get("connectNulls"),p=s.get("precision"),d=s.get("distance")||0,g=l.getBaseAxis(),y=g.isHorizontal(),m=g.inverse,_=a.shape,S=m?y?_.x:_.y+_.height:y?_.x+_.width:_.y,b=(y?d:0)*(m?-1:1),x=(y?0:-d)*(m?-1:1),w=y?"x":"y",T=WV(h,S,w),C=T.range,D=C[1]-C[0],M=void 0;if(D>=1){if(D>1&&!c){var I=Uw(h,C[0]);u.attr({x:I[0]+b,y:I[1]+x}),o&&(M=v.getRawValue(C[0]))}else{var I=f.getPointOn(S,w);I&&u.attr({x:I[0]+b,y:I[1]+x});var L=v.getRawValue(C[0]),P=v.getRawValue(C[1]);o&&(M=t_(n,p,L,P,T.t))}i.lastFrameIndex=C[0]}else{var R=t===1||i.lastFrameIndex>0?C[0]:0,I=Uw(h,R);o&&(M=v.getRawValue(R)),u.attr({x:I[0]+b,y:I[1]+x})}o&&Xi(u).setLabelText(M)}},e.prototype._doUpdateAnimation=function(t,a,n,i,o,s,l){var u=this._polyline,f=this._polygon,h=t.hostModel,v=EV(this._data,t,this._stackedOnPoints,a,this._coordSys,n,this._valueOrigin),c=v.current,p=v.stackedOnCurrent,d=v.next,g=v.stackedOnNext;if(o&&(c=tn(v.current,n,o,l),p=tn(v.stackedOnCurrent,n,o,l),d=tn(v.next,n,o,l),g=tn(v.stackedOnNext,n,o,l)),Hw(c,d)>3e3||f&&Hw(p,g)>3e3){u.stopAnimation(),u.setShape({points:d}),f&&(f.stopAnimation(),f.setShape({points:d,stackedOnPoints:g}));return}u.shape.__points=v.current,u.shape.points=c;var y={shape:{points:d}};v.current!==c&&(y.shape.__points=v.next),u.stopAnimation(),At(u,y,h),f&&(f.setShape({points:c,stackedOnPoints:p}),f.stopAnimation(),At(f,{shape:{stackedOnPoints:g}},h),u.shape.points!==f.shape.points&&(f.shape.points=u.shape.points));for(var m=[],_=v.status,S=0;S<_.length;S++){var b=_[S].cmd;if(b==="="){var x=t.getItemGraphicEl(_[S].idx1);x&&m.push({el:x,ptIdx:S})}}u.animators&&u.animators.length&&u.animators[0].during(function(){f&&f.dirtyShape();for(var w=u.shape.__points,T=0;Te&&(e=r[t]);return isFinite(e)?e:NaN},min:function(r){for(var e=Infinity,t=0;t10&&o.type==="cartesian2d"&&i){var l=o.getBaseAxis(),u=o.getOtherAxis(l),f=l.getExtent(),h=a.getDevicePixelRatio(),v=Math.abs(f[1]-f[0])*(h||1),c=Math.round(s/v);if(isFinite(c)&&c>1){i==="lttb"&&e.setData(n.lttbDownSample(n.mapDimension(u.dim),1/c));var p=void 0;U(i)?p=XV[i]:K(i)&&(p=i),p&&e.setData(n.downSample(n.mapDimension(u.dim),1/c,p,ZV))}}}}}function $V(r){r.registerChartView(YV),r.registerSeriesModel(IV),r.registerLayout(hl("line",!0)),r.registerVisual({seriesType:"line",reset:function(e){var t=e.getData(),a=e.getModel("lineStyle").getLineStyle();a&&!a.stroke&&(a.stroke=t.getVisual("style").fill),t.setVisual("legendLineStyle",a)}}),r.registerProcessor(r.PRIORITY.PROCESSOR.STATISTIC,Xw("line"))}var vl=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.getInitialData=function(t,a){return Xr(null,this,{useEncodeDefaulter:!0})},e.prototype.getMarkerPosition=function(t,a,n){var i=this.coordinateSystem;if(i&&i.clampData){var o=i.dataToPoint(i.clampData(t));if(n)A(i.getAxes(),function(h,v){if(h.type==="category"){var c=h.getTicksCoords(),p=i.clampData(t)[v];a&&(a[v]==="x1"||a[v]==="y1")&&(p+=1),p>c.length-1&&(p=c.length-1),p<0&&(p=0),c[p]&&(o[v]=h.toGlobalCoord(c[p].coord))}});else{var s=this.getData(),l=s.getLayout("offset"),u=s.getLayout("size"),f=i.getBaseAxis().isHorizontal()?0:1;o[f]+=l+u/2}return o}return[NaN,NaN]},e.type="series.__base_bar__",e.defaultOption={z:2,coordinateSystem:"cartesian2d",legendHoverLink:!0,barMinHeight:0,barMinAngle:0,large:!1,largeThreshold:400,progressive:3e3,progressiveChunkMode:"mod"},e}(kt);kt.registerClass(vl);var qV=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.getInitialData=function(){return Xr(null,this,{useEncodeDefaulter:!0,createInvertedIndices:!!this.get("realtimeSort",!0)||null})},e.prototype.getProgressive=function(){return this.get("large")?this.get("progressive"):!1},e.prototype.getProgressiveThreshold=function(){var t=this.get("progressiveThreshold"),a=this.get("largeThreshold");return a>t&&(t=a),t},e.prototype.brushSelector=function(t,a,n){return n.rect(a.getItemLayout(t))},e.type="series.bar",e.dependencies=["grid","polar"],e.defaultOption=Ua(vl.defaultOption,{clip:!0,roundCap:!1,showBackground:!1,backgroundStyle:{color:"rgba(180, 180, 180, 0.2)",borderColor:null,borderWidth:0,borderType:"solid",borderRadius:0,shadowBlur:0,shadowColor:null,shadowOffsetX:0,shadowOffsetY:0,opacity:1},select:{itemStyle:{borderColor:"#212121"}},realtimeSort:!1}),e}(vl),KV=function(){function r(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0}return r}(),th=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="sausage",a}return e.prototype.getDefaultShape=function(){return new KV},e.prototype.buildPath=function(t,a){var n=a.cx,i=a.cy,o=Math.max(a.r0||0,0),s=Math.max(a.r,0),l=(s-o)*.5,u=o+l,f=a.startAngle,h=a.endAngle,v=a.clockwise,c=Math.PI*2,p=v?h-fMath.PI/2&&fs)return!0;s=h}return!1},e.prototype._isOrderDifferentInView=function(t,a){for(var n=a.scale,i=n.getExtent(),o=Math.max(0,i[0]),s=Math.min(i[1],n.getOrdinalMeta().categories.length-1);o<=s;++o)if(t.ordinalNumbers[o]!==n.getRawOrdinalNumber(o))return!0},e.prototype._updateSortWithinSameData=function(t,a,n,i){if(!!this._isOrderChangedWithinSameData(t,a,n)){var o=this._dataSort(t,n,a);this._isOrderDifferentInView(o,n)&&(this._removeOnRenderedListener(i),i.dispatchAction({type:"changeAxisOrder",componentType:n.dim+"Axis",axisId:n.index,sortInfo:o}))}},e.prototype._dispatchInitSort=function(t,a,n){var i=a.baseAxis,o=this._dataSort(t,i,function(s){return t.get(t.mapDimension(a.otherAxis.dim),s)});n.dispatchAction({type:"changeAxisOrder",componentType:i.dim+"Axis",isInitSort:!0,axisId:i.index,sortInfo:o})},e.prototype.remove=function(t,a){this._clear(this._model),this._removeOnRenderedListener(a)},e.prototype.dispose=function(t,a){this._removeOnRenderedListener(a)},e.prototype._removeOnRenderedListener=function(t){this._onRendered&&(t.getZr().off("rendered",this._onRendered),this._onRendered=null)},e.prototype._clear=function(t){var a=this.group,n=this._data;t&&t.isAnimationEnabled()&&n&&!this._isLargeDraw?(this._removeBackground(),this._backgroundEls=[],n.eachItemGraphicEl(function(i){Ts(i,t,nt(i).dataIndex)})):a.removeAll(),this._data=null,this._isFirstFrame=!0},e.prototype._removeBackground=function(){this.group.remove(this._backgroundGroup),this._backgroundGroup=null},e.type="bar",e}(Rt),Zw={cartesian2d:function(r,e){var t=e.width<0?-1:1,a=e.height<0?-1:1;t<0&&(e.x+=e.width,e.width=-e.width),a<0&&(e.y+=e.height,e.height=-e.height);var n=r.x+r.width,i=r.y+r.height,o=Gd(e.x,r.x),s=Fd(e.x+e.width,n),l=Gd(e.y,r.y),u=Fd(e.y+e.height,i),f=sn?s:o,e.y=h&&l>i?u:l,e.width=f?0:s-o,e.height=h?0:u-l,t<0&&(e.x+=e.width,e.width=-e.width),a<0&&(e.y+=e.height,e.height=-e.height),f||h},polar:function(r,e){var t=e.r0<=e.r?1:-1;if(t<0){var a=e.r;e.r=e.r0,e.r0=a}var n=Fd(e.r,r.r),i=Gd(e.r0,r.r0);e.r=n,e.r0=i;var o=n-i<0;if(t<0){var a=e.r;e.r=e.r0,e.r0=a}return o}},$w={cartesian2d:function(r,e,t,a,n,i,o,s,l){var u=new xt({shape:B({},a),z2:1});if(u.__dataIndex=t,u.name="item",i){var f=u.shape,h=n?"height":"width";f[h]=0}return u},polar:function(r,e,t,a,n,i,o,s,l){var u=!n&&l?th:me,f=new u({shape:a,z2:1});f.name="item";var h=Qw(n);if(f.calculateTextPosition=jV(h,{isRoundCap:u===th}),i){var v=f.shape,c=n?"r":"endAngle",p={};v[c]=n?0:a.startAngle,p[c]=a[c],(s?At:Gt)(f,{shape:p},i)}return f}};function ez(r,e){var t=r.get("realtimeSort",!0),a=e.getBaseAxis();if(t&&a.type==="category"&&e.type==="cartesian2d")return{baseAxis:a,otherAxis:e.getOtherAxis(a)}}function qw(r,e,t,a,n,i,o,s){var l,u;i?(u={x:a.x,width:a.width},l={y:a.y,height:a.height}):(u={y:a.y,height:a.height},l={x:a.x,width:a.width}),s||(o?At:Gt)(t,{shape:l},e,n,null);var f=e?r.baseAxis.model:null;(o?At:Gt)(t,{shape:u},f,n)}function Kw(r,e){for(var t=0;t0?1:-1,o=a.height>0?1:-1;return{x:a.x+i*n/2,y:a.y+o*n/2,width:a.width-i*n,height:a.height-o*n}},polar:function(r,e,t){var a=r.getItemLayout(e);return{cx:a.cx,cy:a.cy,r0:a.r0,r:a.r,startAngle:a.startAngle,endAngle:a.endAngle,clockwise:a.clockwise}}};function nz(r){return r.startAngle!=null&&r.endAngle!=null&&r.startAngle===r.endAngle}function Qw(r){return function(e){var t=e?"Arc":"Angle";return function(a){switch(a){case"start":case"insideStart":case"end":case"insideEnd":return a+t;default:return a}}}(r)}function Jw(r,e,t,a,n,i,o,s){var l=e.getItemVisual(t,"style");s||r.setShape("r",a.get(["itemStyle","borderRadius"])||0),r.useStyle(l);var u=a.getShallow("cursor");u&&r.attr("cursor",u);var f=s?o?n.r>=n.r0?"endArc":"startArc":n.endAngle>=n.startAngle?"endAngle":"startAngle":o?n.height>=0?"bottom":"top":n.width>=0?"right":"left",h=ne(a);ve(r,h,{labelFetcher:i,labelDataIndex:t,defaultText:co(i.getData(),t),inheritColor:l.fill,defaultOpacity:l.opacity,defaultOutsidePosition:f});var v=r.getTextContent();if(s&&v){var c=a.get(["label","position"]);r.textConfig.inside=c==="middle"?!0:null,QV(r,c==="outside"?f:c,Qw(o),a.get(["label","rotate"]))}C1(v,h,i.getRawValue(t),function(d){return Pw(e,d)});var p=a.getModel(["emphasis"]);Ut(r,p.get("focus"),p.get("blurScope"),p.get("disabled")),he(r,a),nz(n)&&(r.style.fill="none",r.style.stroke="none",A(r.states,function(d){d.style&&(d.style.fill=d.style.stroke="none")}))}function iz(r,e){var t=r.get(["itemStyle","borderColor"]);if(!t||t==="none")return 0;var a=r.get(["itemStyle","borderWidth"])||0,n=isNaN(e.width)?Number.MAX_VALUE:Math.abs(e.width),i=isNaN(e.height)?Number.MAX_VALUE:Math.abs(e.height);return Math.min(a,n,i)}var oz=function(){function r(){}return r}(),tT=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="largeBar",a}return e.prototype.getDefaultShape=function(){return new oz},e.prototype.buildPath=function(t,a){for(var n=a.points,i=this.baseDimIdx,o=1-this.baseDimIdx,s=[],l=[],u=this.barWidth,f=0;f=0?t:null},30,!1);function sz(r,e,t){for(var a=r.baseDimIdx,n=1-a,i=r.shape.points,o=r.largeDataIndices,s=[],l=[],u=r.barWidth,f=0,h=i.length/3;f=s[0]&&e<=s[0]+l[0]&&t>=s[1]&&t<=s[1]+l[1])return o[f]}return-1}function aT(r,e,t){if(ni(t,"cartesian2d")){var a=e,n=t.getArea();return{x:r?a.x:n.x,y:r?n.y:a.y,width:r?a.width:n.width,height:r?n.height:a.height}}else{var n=t.getArea(),i=e;return{cx:n.cx,cy:n.cy,r0:r?n.r0:i.r0,r:r?n.r:i.r,startAngle:r?i.startAngle:0,endAngle:r?i.endAngle:Math.PI*2}}}function lz(r,e,t){var a=r.type==="polar"?me:xt;return new a({shape:aT(e,t,r),silent:!0,z2:0})}function uz(r){r.registerChartView(tz),r.registerSeriesModel(qV),r.registerLayout(r.PRIORITY.VISUAL.LAYOUT,it(wb,"bar")),r.registerLayout(r.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT,Tb("bar")),r.registerProcessor(r.PRIORITY.PROCESSOR.STATISTIC,Xw("bar")),r.registerAction({type:"changeAxisOrder",event:"changeAxisOrder",update:"update"},function(e,t){var a=e.componentType||"series";t.eachComponent({mainType:a,query:e},function(n){e.sortInfo&&n.axis.setCategorySortInfo(e.sortInfo)})})}var nh=Math.PI*2,nT=Math.PI/180;function iT(r,e){return jt(r.getBoxLayoutParams(),{width:e.getWidth(),height:e.getHeight()})}function oT(r,e){var t=iT(r,e),a=r.get("center"),n=r.get("radius");z(n)||(n=[0,n]);var i=H(t.width,e.getWidth()),o=H(t.height,e.getHeight()),s=Math.min(i,o),l=H(n[0],s/2),u=H(n[1],s/2),f,h,v=r.coordinateSystem;if(v){var c=v.dataToPoint(a);f=c[0]||0,h=c[1]||0}else z(a)||(a=[a,a]),f=H(a[0],i)+t.x,h=H(a[1],o)+t.y;return{cx:f,cy:h,r0:l,r:u}}function fz(r,e,t){e.eachSeriesByType(r,function(a){var n=a.getData(),i=n.mapDimension("value"),o=iT(a,t),s=oT(a,t),l=s.cx,u=s.cy,f=s.r,h=s.r0,v=-a.get("startAngle")*nT,c=a.get("minAngle")*nT,p=0;n.each(i,function(D){!isNaN(D)&&p++});var d=n.getSum(i),g=Math.PI/(d||p)*2,y=a.get("clockwise"),m=a.get("roseType"),_=a.get("stillShowZeroSum"),S=n.getDataExtent(i);S[0]=0;var b=nh,x=0,w=v,T=y?1:-1;if(n.setLayout({viewRect:o,r:f}),n.each(i,function(D,M){var I;if(isNaN(D)){n.setItemLayout(M,{angle:NaN,startAngle:NaN,endAngle:NaN,clockwise:y,cx:l,cy:u,r0:h,r:m?NaN:f});return}m!=="area"?I=d===0&&_?g:D*g:I=nh/p,It?y:g,b=Math.abs(_.label.y-t);if(b>=S.maxY){var x=_.label.x-e-_.len2*n,w=a+_.len,T=Math.abs(x)r.unconstrainedWidth?null:c:null;a.setStyle("width",p)}var d=a.getBoundingRect();i.width=d.width;var g=(a.style.margin||0)+2.1;i.height=d.height+g,i.y-=(i.height-h)/2}}}function Hd(r){return r.position==="center"}function cz(r){var e=r.getData(),t=[],a,n,i=!1,o=(r.get("minShowLabelAngle")||0)*hz,s=e.getLayout("viewRect"),l=e.getLayout("r"),u=s.width,f=s.x,h=s.y,v=s.height;function c(x){x.ignore=!0}function p(x){if(!x.ignore)return!0;for(var w in x.states)if(x.states[w].ignore===!1)return!0;return!1}e.each(function(x){var w=e.getItemGraphicEl(x),T=w.shape,C=w.getTextContent(),D=w.getTextGuideLine(),M=e.getItemModel(x),I=M.getModel("label"),L=I.get("position")||M.get(["emphasis","label","position"]),P=I.get("distanceToLabelLine"),R=I.get("alignTo"),E=H(I.get("edgeDistance"),u),N=I.get("bleedMargin"),k=M.getModel("labelLine"),V=k.get("length");V=H(V,u);var F=k.get("length2");if(F=H(F,u),Math.abs(T.endAngle-T.startAngle)0?"right":"left":Z>0?"left":"right"}var Yt=Math.PI,Ht=0,pe=I.get("rotate");if(Tt(pe))Ht=pe*(Yt/180);else if(L==="center")Ht=0;else if(pe==="radial"||pe===!0){var ea=Z<0?-W+Yt:-W;Ht=ea}else if(pe==="tangential"&&L!=="outside"&&L!=="outer"){var Re=Math.atan2(Z,Q);Re<0&&(Re=Yt*2+Re);var Wl=Q>0;Wl&&(Re=Yt+Re),Ht=Re-Yt}if(i=!!Ht,C.x=tt,C.y=yt,C.rotation=Ht,C.setStyle({verticalAlign:"middle"}),at){C.setStyle({align:pt});var Jh=C.states.select;Jh&&(Jh.x+=C.x,Jh.y+=C.y)}else{var Ta=C.getBoundingRect().clone();Ta.applyTransform(C.getComputedTransform());var Dm=(C.style.margin||0)+2.1;Ta.y-=Dm/2,Ta.height+=Dm,t.push({label:C,labelLine:D,position:L,len:V,len2:F,minTurnAngle:k.get("minTurnAngle"),maxSurfaceAngle:k.get("maxSurfaceAngle"),surfaceNormal:new ut(Z,Q),linePoints:Dt,textAlign:pt,labelDistance:P,labelAlignTo:R,edgeDistance:E,bleedMargin:N,rect:Ta,unconstrainedWidth:Ta.width,labelStyleWidth:C.style.width})}w.setTextConfig({inside:at})}}),!i&&r.get("avoidLabelOverlap")&&vz(t,a,n,l,u,v,f,h);for(var d=0;d0){for(var f=o.getItemLayout(0),h=1;isNaN(f&&f.startAngle)&&h=i.r0}},e.type="pie",e}(Rt);function go(r,e,t){e=z(e)&&{coordDimensions:e}||B({encodeDefine:r.getEncode()},e);var a=r.getSource(),n=uo(a,e).dimensions,i=new Te(n,r);return i.initData(a,t),i}var pl=function(){function r(e,t){this._getDataWithEncodedVisual=e,this._getRawData=t}return r.prototype.getAllNames=function(){var e=this._getRawData();return e.mapArray(e.getName)},r.prototype.containName=function(e){var t=this._getRawData();return t.indexOfName(e)>=0},r.prototype.indexOfName=function(e){var t=this._getDataWithEncodedVisual();return t.indexOfName(e)},r.prototype.getItemVisual=function(e,t){var a=this._getDataWithEncodedVisual();return a.getItemVisual(e,t)},r}(),gz=Ct(),yz=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.init=function(t){r.prototype.init.apply(this,arguments),this.legendVisualProvider=new pl(Y(this.getData,this),Y(this.getRawData,this)),this._defaultLabelLine(t)},e.prototype.mergeOption=function(){r.prototype.mergeOption.apply(this,arguments)},e.prototype.getInitialData=function(){return go(this,{coordDimensions:["value"],encodeDefaulter:it(hp,this)})},e.prototype.getDataParams=function(t){var a=this.getData(),n=gz(a),i=n.seats;if(!i){var o=[];a.each(a.mapDimension("value"),function(l){o.push(l)}),i=n.seats=F0(o,a.hostModel.get("percentPrecision"))}var s=r.prototype.getDataParams.call(this,t);return s.percent=i[t]||0,s.$vars.push("percent"),s},e.prototype._defaultLabelLine=function(t){Sn(t,"labelLine",["show"]);var a=t.labelLine,n=t.emphasis.labelLine;a.show=a.show&&t.label.show,n.show=n.show&&t.emphasis.label.show},e.type="series.pie",e.defaultOption={z:2,legendHoverLink:!0,colorBy:"data",center:["50%","50%"],radius:[0,"75%"],clockwise:!0,startAngle:90,minAngle:0,minShowLabelAngle:0,selectedOffset:10,percentPrecision:2,stillShowZeroSum:!0,left:0,top:0,right:0,bottom:0,width:null,height:null,label:{rotate:0,show:!0,overflow:"truncate",position:"outer",alignTo:"none",edgeDistance:"25%",bleedMargin:10,distanceToLabelLine:5},labelLine:{show:!0,length:15,length2:15,smooth:!1,minTurnAngle:90,maxSurfaceAngle:90,lineStyle:{width:1,type:"solid"}},itemStyle:{borderWidth:1,borderJoin:"round"},showEmptyCircle:!0,emptyCircleStyle:{color:"lightgray",opacity:1},labelLayout:{hideOverlap:!0},emphasis:{scale:!0,scaleSize:5},avoidLabelOverlap:!0,animationType:"expansion",animationDuration:1e3,animationTypeUpdate:"transition",animationEasingUpdate:"cubicInOut",animationDurationUpdate:500,animationEasing:"cubicInOut"},e}(kt);function mz(r){return{seriesType:r,reset:function(e,t){var a=e.getData();a.filterSelf(function(n){var i=a.mapDimension("value"),o=a.get(i,n);return!(Tt(o)&&!isNaN(o)&&o<0)})}}}function _z(r){r.registerChartView(dz),r.registerSeriesModel(yz),px("pie",r.registerAction),r.registerLayout(it(fz,"pie")),r.registerProcessor(cl("pie")),r.registerProcessor(mz("pie"))}var Sz=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.hasSymbolVisual=!0,t}return e.prototype.getInitialData=function(t,a){return Xr(null,this,{useEncodeDefaulter:!0})},e.prototype.getProgressive=function(){var t=this.option.progressive;return t==null?this.option.large?5e3:this.get("progressive"):t},e.prototype.getProgressiveThreshold=function(){var t=this.option.progressiveThreshold;return t==null?this.option.large?1e4:this.get("progressiveThreshold"):t},e.prototype.brushSelector=function(t,a,n){return n.point(a.getItemLayout(t))},e.prototype.getZLevelKey=function(){return this.getData().count()>this.getProgressiveThreshold()?this.id:""},e.type="series.scatter",e.dependencies=["grid","polar","geo","singleAxis","calendar"],e.defaultOption={coordinateSystem:"cartesian2d",z:2,legendHoverLink:!0,symbolSize:10,large:!1,largeThreshold:2e3,itemStyle:{opacity:.8},emphasis:{scale:!0},clip:!0,select:{itemStyle:{borderColor:"#212121"}},universalTransition:{divideShape:"clone"}},e}(kt),uT=4,xz=function(){function r(){}return r}(),bz=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a._off=0,a.hoverDataIdx=-1,a}return e.prototype.getDefaultShape=function(){return new xz},e.prototype.reset=function(){this.notClear=!1,this._off=0},e.prototype.buildPath=function(t,a){var n=a.points,i=a.size,o=this.symbolProxy,s=o.shape,l=t.getContext?t.getContext():t,u=l&&i[0]=0;u--){var f=u*2,h=i[f]-s/2,v=i[f+1]-l/2;if(t>=h&&a>=v&&t<=h+s&&a<=v+l)return u}return-1},e.prototype.contain=function(t,a){var n=this.transformCoordToLocal(t,a),i=this.getBoundingRect();if(t=n[0],a=n[1],i.contain(t,a)){var o=this.hoverDataIdx=this.findDataIndex(t,a);return o>=0}return this.hoverDataIdx=-1,!1},e.prototype.getBoundingRect=function(){var t=this._rect;if(!t){for(var a=this.shape,n=a.points,i=a.size,o=i[0],s=i[1],l=Infinity,u=Infinity,f=-Infinity,h=-Infinity,v=0;v=0&&(u.dataIndex=h+(e.startIndex||0))})},r.prototype.remove=function(){this._clear()},r.prototype._clear=function(){this._newAdded=[],this.group.removeAll()},r}(),Tz=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=t.getData(),o=this._updateSymbolDraw(i,t);o.updateData(i,{clipShape:this._getClipShape(t)}),this._finished=!0},e.prototype.incrementalPrepareRender=function(t,a,n){var i=t.getData(),o=this._updateSymbolDraw(i,t);o.incrementalPrepareUpdate(i),this._finished=!1},e.prototype.incrementalRender=function(t,a,n){this._symbolDraw.incrementalUpdate(t,a.getData(),{clipShape:this._getClipShape(a)}),this._finished=t.end===a.getData().count()},e.prototype.updateTransform=function(t,a,n){var i=t.getData();if(this.group.dirty(),!this._finished||i.count()>1e4)return{update:!0};var o=hl("").reset(t,a,n);o.progress&&o.progress({start:0,end:i.count(),count:i.count()},i),this._symbolDraw.updateLayout(i)},e.prototype.eachRendered=function(t){this._symbolDraw&&this._symbolDraw.eachRendered(t)},e.prototype._getClipShape=function(t){var a=t.coordinateSystem,n=a&&a.getArea&&a.getArea();return t.get("clip",!0)?n:null},e.prototype._updateSymbolDraw=function(t,a){var n=this._symbolDraw,i=a.pipelineContext,o=i.large;return(!n||o!==this._isLargeDraw)&&(n&&n.remove(),n=this._symbolDraw=o?new wz:new fl,this._isLargeDraw=o,this.group.removeAll()),this.group.add(n.group),n},e.prototype.remove=function(t,a){this._symbolDraw&&this._symbolDraw.remove(!0),this._symbolDraw=null},e.prototype.dispose=function(){},e.type="scatter",e}(Rt),Cz=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.type="grid",e.dependencies=["xAxis","yAxis"],e.layoutMode="box",e.defaultOption={show:!1,z:0,left:"10%",top:60,right:"10%",bottom:70,containLabel:!1,backgroundColor:"rgba(0,0,0,0)",borderWidth:1,borderColor:"#ccc"},e}(gt),Wd=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.getCoordSysModel=function(){return this.getReferringComponents("grid",Kt).models[0]},e.type="cartesian2dAxis",e}(gt);Xt(Wd,ho);var fT={show:!0,z:0,inverse:!1,name:"",nameLocation:"end",nameRotate:null,nameTruncate:{maxWidth:null,ellipsis:"...",placeholder:"."},nameTextStyle:{},nameGap:15,silent:!1,triggerEvent:!1,tooltip:{show:!1},axisPointer:{},axisLine:{show:!0,onZero:!0,onZeroAxisIndex:null,lineStyle:{color:"#6E7079",width:1,type:"solid"},symbol:["none","none"],symbolSize:[10,15]},axisTick:{show:!0,inside:!1,length:5,lineStyle:{width:1}},axisLabel:{show:!0,inside:!1,rotate:0,showMinLabel:null,showMaxLabel:null,margin:8,fontSize:12},splitLine:{show:!0,lineStyle:{color:["#E0E6F1"],width:1,type:"solid"}},splitArea:{show:!1,areaStyle:{color:["rgba(250,250,250,0.2)","rgba(210,219,238,0.2)"]}}},Az=ot({boundaryGap:!0,deduplication:null,splitLine:{show:!1},axisTick:{alignWithLabel:!1,interval:"auto"},axisLabel:{interval:"auto"}},fT),Ud=ot({boundaryGap:[0,0],axisLine:{show:"auto"},axisTick:{show:"auto"},splitNumber:5,minorTick:{show:!1,splitNumber:5,length:3,lineStyle:{}},minorSplitLine:{show:!1,lineStyle:{color:"#F4F7FD",width:1}}},fT),Dz=ot({splitNumber:6,axisLabel:{showMinLabel:!1,showMaxLabel:!1,rich:{primary:{fontWeight:"bold"}}},splitLine:{show:!1}},Ud),Mz=j({logBase:10},Ud),hT={category:Az,value:Ud,time:Dz,log:Mz},Iz={value:1,category:1,time:1,log:1};function yo(r,e,t,a){A(Iz,function(n,i){var o=ot(ot({},hT[i],!0),a,!0),s=function(l){O(u,l);function u(){var f=l!==null&&l.apply(this,arguments)||this;return f.type=e+"Axis."+i,f}return u.prototype.mergeDefaultAndTheme=function(f,h){var v=ks(this),c=v?Ki(f):{},p=h.getTheme();ot(f,p.get(i+"Axis")),ot(f,this.getDefaultOption()),f.type=vT(f),v&&Ya(f,c,v)},u.prototype.optionUpdated=function(){var f=this.option;f.type==="category"&&(this.__ordinalMeta=ud.createByAxisModel(this))},u.prototype.getCategories=function(f){var h=this.option;if(h.type==="category")return f?h.data:this.__ordinalMeta.categories},u.prototype.getOrdinalMeta=function(){return this.__ordinalMeta},u.type=e+"Axis."+i,u.defaultOption=o,u}(t);r.registerComponentModel(s)}),r.registerSubTypeDefaulter(e+"Axis",vT)}function vT(r){return r.type||(r.data?"category":"value")}var Lz=function(){function r(e){this.type="cartesian",this._dimList=[],this._axes={},this.name=e||""}return r.prototype.getAxis=function(e){return this._axes[e]},r.prototype.getAxes=function(){return G(this._dimList,function(e){return this._axes[e]},this)},r.prototype.getAxesByScale=function(e){return e=e.toLowerCase(),Lt(this.getAxes(),function(t){return t.scale.type===e})},r.prototype.addAxis=function(e){var t=e.dim;this._axes[t]=e,this._dimList.push(t)},r}(),Yd=["x","y"];function cT(r){return r.type==="interval"||r.type==="time"}var Pz=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type="cartesian2d",t.dimensions=Yd,t}return e.prototype.calcAffineTransform=function(){this._transform=this._invTransform=null;var t=this.getAxis("x").scale,a=this.getAxis("y").scale;if(!(!cT(t)||!cT(a))){var n=t.getExtent(),i=a.getExtent(),o=this.dataToPoint([n[0],i[0]]),s=this.dataToPoint([n[1],i[1]]),l=n[1]-n[0],u=i[1]-i[0];if(!(!l||!u)){var f=(s[0]-o[0])/l,h=(s[1]-o[1])/u,v=o[0]-n[0]*f,c=o[1]-i[0]*h,p=this._transform=[f,0,0,h,v,c];this._invTransform=hn([],p)}}},e.prototype.getBaseAxis=function(){return this.getAxesByScale("ordinal")[0]||this.getAxesByScale("time")[0]||this.getAxis("x")},e.prototype.containPoint=function(t){var a=this.getAxis("x"),n=this.getAxis("y");return a.contain(a.toLocalCoord(t[0]))&&n.contain(n.toLocalCoord(t[1]))},e.prototype.containData=function(t){return this.getAxis("x").containData(t[0])&&this.getAxis("y").containData(t[1])},e.prototype.containZone=function(t,a){var n=this.dataToPoint(t),i=this.dataToPoint(a),o=this.getArea(),s=new ft(n[0],n[1],i[0]-n[0],i[1]-n[1]);return o.intersect(s)},e.prototype.dataToPoint=function(t,a,n){n=n||[];var i=t[0],o=t[1];if(this._transform&&i!=null&&isFinite(i)&&o!=null&&isFinite(o))return le(n,t,this._transform);var s=this.getAxis("x"),l=this.getAxis("y");return n[0]=s.toGlobalCoord(s.dataToCoord(i,a)),n[1]=l.toGlobalCoord(l.dataToCoord(o,a)),n},e.prototype.clampData=function(t,a){var n=this.getAxis("x").scale,i=this.getAxis("y").scale,o=n.getExtent(),s=i.getExtent(),l=n.parse(t[0]),u=i.parse(t[1]);return a=a||[],a[0]=Math.min(Math.max(Math.min(o[0],o[1]),l),Math.max(o[0],o[1])),a[1]=Math.min(Math.max(Math.min(s[0],s[1]),u),Math.max(s[0],s[1])),a},e.prototype.pointToData=function(t,a){var n=[];if(this._invTransform)return le(n,t,this._invTransform);var i=this.getAxis("x"),o=this.getAxis("y");return n[0]=i.coordToData(i.toLocalCoord(t[0]),a),n[1]=o.coordToData(o.toLocalCoord(t[1]),a),n},e.prototype.getOtherAxis=function(t){return this.getAxis(t.dim==="x"?"y":"x")},e.prototype.getArea=function(){var t=this.getAxis("x").getGlobalExtent(),a=this.getAxis("y").getGlobalExtent(),n=Math.min(t[0],t[1]),i=Math.min(a[0],a[1]),o=Math.max(t[0],t[1])-n,s=Math.max(a[0],a[1])-i;return new ft(n,i,o,s)},e}(Lz),Rz=function(r){O(e,r);function e(t,a,n,i,o){var s=r.call(this,t,a,n)||this;return s.index=0,s.type=i||"value",s.position=o||"bottom",s}return e.prototype.isHorizontal=function(){var t=this.position;return t==="top"||t==="bottom"},e.prototype.getGlobalExtent=function(t){var a=this.getExtent();return a[0]=this.toGlobalCoord(a[0]),a[1]=this.toGlobalCoord(a[1]),t&&a[0]>a[1]&&a.reverse(),a},e.prototype.pointToData=function(t,a){return this.coordToData(this.toLocalCoord(t[this.dim==="x"?0:1]),a)},e.prototype.setCategorySortInfo=function(t){if(this.type!=="category")return!1;this.model.option.categorySortInfo=t,this.scale.setSortInfo(t)},e}(fr);function Xd(r,e,t){t=t||{};var a=r.coordinateSystem,n=e.axis,i={},o=n.getAxesOnZeroOf()[0],s=n.position,l=o?"onZero":s,u=n.dim,f=a.getRect(),h=[f.x,f.x+f.width,f.y,f.y+f.height],v={left:0,right:1,top:0,bottom:1,onZero:2},c=e.get("offset")||0,p=u==="x"?[h[2]-c,h[3]+c]:[h[0]-c,h[1]+c];if(o){var d=o.toGlobalCoord(o.dataToCoord(0));p[v.onZero]=Math.max(Math.min(d,p[1]),p[0])}i.position=[u==="y"?p[v[l]]:h[0],u==="x"?p[v[l]]:h[3]],i.rotation=Math.PI/2*(u==="x"?0:1);var g={top:-1,bottom:1,left:-1,right:1};i.labelDirection=i.tickDirection=i.nameDirection=g[s],i.labelOffset=o?p[v[s]]-p[v.onZero]:0,e.get(["axisTick","inside"])&&(i.tickDirection=-i.tickDirection),ee(t.labelInside,e.get(["axisLabel","inside"]))&&(i.labelDirection=-i.labelDirection);var y=e.get(["axisLabel","rotate"]);return i.labelRotate=l==="top"?-y:y,i.z2=1,i}function pT(r){return r.get("coordinateSystem")==="cartesian2d"}function dT(r){var e={xAxisModel:null,yAxisModel:null};return A(e,function(t,a){var n=a.replace(/Model$/,""),i=r.getReferringComponents(n,Kt).models[0];e[a]=i}),e}var Zd=Math.log;function gT(r,e,t){var a=ya.prototype,n=a.getTicks.call(t),i=a.getTicks.call(t,!0),o=n.length-1,s=a.getInterval.call(t),l=Pb(r,e),u=l.extent,f=l.fixMin,h=l.fixMax;if(r.type==="log"){var v=Zd(r.base);u=[Zd(u[0])/v,Zd(u[1])/v]}r.setExtent(u[0],u[1]),r.calcNiceExtent({splitNumber:o,fixMin:f,fixMax:h});var c=a.getExtent.call(r);f&&(u[0]=c[0]),h&&(u[1]=c[1]);var p=a.getInterval.call(r),d=u[0],g=u[1];if(f&&h)p=(g-d)/o;else if(f)for(g=u[0]+p*o;gu[0]&&isFinite(d)&&isFinite(u[0]);)p=hd(p),d=u[1]-p*o;else{var y=r.getTicks().length-1;y>o&&(p=hd(p));var m=p*o;g=Math.ceil(u[1]/p)*p,d=Wt(g-m),d<0&&u[0]>=0?(d=0,g=Wt(m)):g>0&&u[1]<=0&&(g=0,d=-Wt(m))}var _=(n[0].value-i[0].value)/s,S=(n[o].value-i[o].value)/s;a.setExtent.call(r,d+p*_,g+p*S),a.setInterval.call(r,p),(_||S)&&a.setNiceExtent.call(r,d+p,g-p)}var Ez=function(){function r(e,t,a){this.type="grid",this._coordsMap={},this._coordsList=[],this._axesMap={},this._axesList=[],this.axisPointerEnabled=!0,this.dimensions=Yd,this._initCartesian(e,t,a),this.model=e}return r.prototype.getRect=function(){return this._rect},r.prototype.update=function(e,t){var a=this._axesMap;this._updateScale(e,this.model);function n(o){var s,l=St(o),u=l.length;if(!!u){for(var f=[],h=u-1;h>=0;h--){var v=+l[h],c=o[v],p=c.model,d=c.scale;fd(d)&&p.get("alignTicks")&&p.get("interval")==null?f.push(c):(Kn(d,p),fd(d)&&(s=c))}f.length&&(s||(s=f.pop(),Kn(s.scale,s.model)),A(f,function(g){gT(g.scale,g.model,s.scale)}))}}n(a.x),n(a.y);var i={};A(a.x,function(o){yT(a,"y",o,i)}),A(a.y,function(o){yT(a,"x",o,i)}),this.resize(this.model,t)},r.prototype.resize=function(e,t,a){var n=e.getBoxLayoutParams(),i=!a&&e.get("containLabel"),o=jt(n,{width:t.getWidth(),height:t.getHeight()});this._rect=o;var s=this._axesList;l(),i&&(A(s,function(u){if(!u.model.get(["axisLabel","inside"])){var f=eB(u);if(f){var h=u.isHorizontal()?"height":"width",v=u.model.get(["axisLabel","margin"]);o[h]-=f[h]+v,u.position==="top"?o.y+=f.height+v:u.position==="left"&&(o.x+=f.width+v)}}}),l()),A(this._coordsList,function(u){u.calcAffineTransform()});function l(){A(s,function(u){var f=u.isHorizontal(),h=f?[0,o.width]:[0,o.height],v=u.inverse?1:0;u.setExtent(h[v],h[1-v]),kz(u,f?o.x:o.y)})}},r.prototype.getAxis=function(e,t){var a=this._axesMap[e];if(a!=null)return a[t||0]},r.prototype.getAxes=function(){return this._axesList.slice()},r.prototype.getCartesian=function(e,t){if(e!=null&&t!=null){var a="x"+e+"y"+t;return this._coordsMap[a]}J(e)&&(t=e.yAxisIndex,e=e.xAxisIndex);for(var n=0,i=this._coordsList;n0?"top":"bottom",i="center"):ss(n-en)?(o=a>0?"bottom":"top",i="center"):(o="middle",n>0&&n0?"right":"left":i=a>0?"left":"right"),{rotation:n,textAlign:i,textVerticalAlign:o}},r.makeAxisEventDataBase=function(e){var t={componentType:e.mainType,componentIndex:e.componentIndex};return t[e.mainType+"Index"]=e.componentIndex,t},r.isLabelSilent=function(e){var t=e.get("tooltip");return e.get("silent")||!(e.get("triggerEvent")||t&&t.show)},r}(),_T={axisLine:function(r,e,t,a){var n=e.get(["axisLine","show"]);if(n==="auto"&&r.handleAutoShown&&(n=r.handleAutoShown("axisLine")),!!n){var i=e.axis.getExtent(),o=a.transform,s=[i[0],0],l=[i[1],0],u=s[0]>l[0];o&&(le(s,s,o),le(l,l,o));var f=B({lineCap:"round"},e.getModel(["axisLine","lineStyle"]).getLineStyle()),h=new te({shape:{x1:s[0],y1:s[1],x2:l[0],y2:l[1]},style:f,strokeContainThreshold:r.strokeContainThreshold||5,silent:!0,z2:1});Wi(h.shape,h.style.lineWidth),h.anid="line",t.add(h);var v=e.get(["axisLine","symbol"]);if(v!=null){var c=e.get(["axisLine","symbolSize"]);U(v)&&(v=[v,v]),(U(c)||Tt(c))&&(c=[c,c]);var p=io(e.get(["axisLine","symbolOffset"])||0,c),d=c[0],g=c[1];A([{rotate:r.rotation+Math.PI/2,offset:p[0],r:0},{rotate:r.rotation-Math.PI/2,offset:p[1],r:Math.sqrt((s[0]-l[0])*(s[0]-l[0])+(s[1]-l[1])*(s[1]-l[1]))}],function(y,m){if(v[m]!=="none"&&v[m]!=null){var _=$t(v[m],-d/2,-g/2,d,g,f.stroke,!0),S=y.r+y.offset,b=u?l:s;_.attr({rotation:y.rotate,x:b[0]+S*Math.cos(r.rotation),y:b[1]-S*Math.sin(r.rotation),silent:!0,z2:11}),t.add(_)}})}}},axisTickLabel:function(r,e,t,a){var n=Bz(t,a,e,r),i=zz(t,a,e,r);if(Nz(e,i,n),Vz(t,a,e,r.tickDirection),e.get(["axisLabel","hideOverlap"])){var o=Qb(G(i,function(s){return{label:s,priority:s.z2,defaultAttr:{ignore:s.ignore}}}));ew(o)}},axisName:function(r,e,t,a){var n=ee(r.axisName,e.get("name"));if(!!n){var i=e.get("nameLocation"),o=r.nameDirection,s=e.getModel("nameTextStyle"),l=e.get("nameGap")||0,u=e.axis.getExtent(),f=u[0]>u[1]?-1:1,h=[i==="start"?u[0]-f*l:i==="end"?u[1]+f*l:(u[0]+u[1])/2,xT(i)?r.labelOffset+o*l:0],v,c=e.get("nameRotate");c!=null&&(c=c*en/180);var p;xT(i)?v=Pe.innerTextLayout(r.rotation,c!=null?c:r.rotation,o):(v=Oz(r.rotation,i,c||0,u),p=r.axisNameAvailableWidth,p!=null&&(p=Math.abs(p/Math.sin(v.rotation)),!isFinite(p)&&(p=null)));var d=s.getFont(),g=e.get("nameTruncate",!0)||{},y=g.ellipsis,m=ee(r.nameTruncateMaxWidth,g.maxWidth,p),_=new bt({x:h[0],y:h[1],rotation:v.rotation,silent:Pe.isLabelSilent(e),style:Nt(s,{text:n,font:d,overflow:"truncate",width:m,ellipsis:y,fill:s.getTextColor()||e.get(["axisLine","lineStyle","color"]),align:s.get("align")||v.textAlign,verticalAlign:s.get("verticalAlign")||v.textVerticalAlign}),z2:1});if(Yi({el:_,componentModel:e,itemName:n}),_.__fullText=n,_.anid="name",e.get("triggerEvent")){var S=Pe.makeAxisEventDataBase(e);S.targetType="axisName",S.name=n,nt(_).eventData=S}a.add(_),_.updateTransform(),t.add(_),_.decomposeTransform()}}};function Oz(r,e,t,a){var n=rc(t-r),i,o,s=a[0]>a[1],l=e==="start"&&!s||e!=="start"&&s;return ss(n-en/2)?(o=l?"bottom":"top",i="center"):ss(n-en*1.5)?(o=l?"top":"bottom",i="center"):(o="middle",nen/2?i=l?"left":"right":i=l?"right":"left"),{rotation:n,textAlign:i,textVerticalAlign:o}}function Nz(r,e,t){if(!Rb(r.axis)){var a=r.get(["axisLabel","showMinLabel"]),n=r.get(["axisLabel","showMaxLabel"]);e=e||[],t=t||[];var i=e[0],o=e[1],s=e[e.length-1],l=e[e.length-2],u=t[0],f=t[1],h=t[t.length-1],v=t[t.length-2];a===!1?(hr(i),hr(u)):ST(i,o)&&(a?(hr(o),hr(f)):(hr(i),hr(u))),n===!1?(hr(s),hr(h)):ST(l,s)&&(n?(hr(l),hr(v)):(hr(s),hr(h)))}}function hr(r){r&&(r.ignore=!0)}function ST(r,e){var t=r&&r.getBoundingRect().clone(),a=e&&e.getBoundingRect().clone();if(!(!t||!a)){var n=Ho([]);return Ia(n,n,-r.rotation),t.applyTransform(Or([],n,r.getLocalTransform())),a.applyTransform(Or([],n,e.getLocalTransform())),t.intersect(a)}}function xT(r){return r==="middle"||r==="center"}function bT(r,e,t,a,n){for(var i=[],o=[],s=[],l=0;l=0||r===e}function Yz(r){var e=Kd(r);if(!!e){var t=e.axisPointerModel,a=e.axis.scale,n=t.option,i=t.get("status"),o=t.get("value");o!=null&&(o=a.parse(o));var s=jd(t);i==null&&(n.status=s?"show":"hide");var l=a.getExtent().slice();l[0]>l[1]&&l.reverse(),(o==null||o>l[1])&&(o=l[1]),o0&&!p.min?p.min=0:p.min!=null&&p.min<0&&!p.max&&(p.max=0);var d=l;p.color!=null&&(d=j({color:p.color},l));var g=ot(et(p),{boundaryGap:t,splitNumber:a,scale:n,axisLine:i,axisTick:o,axisLabel:s,name:p.text,showName:u,nameLocation:"end",nameGap:h,nameTextStyle:d,triggerEvent:v},!1);if(U(f)){var y=g.name;g.name=f.replace("{value}",y!=null?y:"")}else K(f)&&(g.name=f(g.name,g));var m=new Mt(g,null,this.ecModel);return Xt(m,ho.prototype),m.mainType="radar",m.componentIndex=this.componentIndex,m},this);this._indicatorModels=c},e.prototype.getIndicatorModels=function(){return this._indicatorModels},e.type="radar",e.defaultOption={z:0,center:["50%","50%"],radius:"75%",startAngle:90,axisName:{show:!0},boundaryGap:[0,0],splitNumber:5,axisNameGap:15,scale:!1,shape:"polygon",axisLine:ot({lineStyle:{color:"#bbb"}},gl.axisLine),axisLabel:ih(gl.axisLabel,!1),axisTick:ih(gl.axisTick,!1),splitLine:ih(gl.splitLine,!0),splitArea:ih(gl.splitArea,!0),indicator:[]},e}(gt),n5=["axisLine","axisTickLabel","axisName"],i5=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=this.group;i.removeAll(),this._buildAxes(t),this._buildSplitLineAndArea(t)},e.prototype._buildAxes=function(t){var a=t.coordinateSystem,n=a.getIndicatorAxes(),i=G(n,function(o){var s=o.model.get("showName")?o.name:"",l=new Pe(o.model,{axisName:s,position:[a.cx,a.cy],rotation:o.angle,labelDirection:-1,tickDirection:-1,nameDirection:1});return l});A(i,function(o){A(n5,o.add,o),this.group.add(o.getGroup())},this)},e.prototype._buildSplitLineAndArea=function(t){var a=t.coordinateSystem,n=a.getIndicatorAxes();if(!n.length)return;var i=t.get("shape"),o=t.getModel("splitLine"),s=t.getModel("splitArea"),l=o.getModel("lineStyle"),u=s.getModel("areaStyle"),f=o.get("show"),h=s.get("show"),v=l.get("color"),c=u.get("color"),p=z(v)?v:[v],d=z(c)?c:[c],g=[],y=[];function m(R,E,N){var k=N%E.length;return R[k]=R[k]||[],k}if(i==="circle")for(var _=n[0].getTicksCoords(),S=a.cx,b=a.cy,x=0;x<_.length;x++){if(f){var w=m(g,p,x);g[w].push(new ar({shape:{cx:S,cy:b,r:_[x].coord}}))}if(h&&x<_.length-1){var w=m(y,d,x);y[w].push(new Vi({shape:{cx:S,cy:b,r0:_[x].coord,r:_[x+1].coord}}))}}else for(var T,C=G(n,function(R,E){var N=R.getTicksCoords();return T=T==null?N.length-1:Math.min(N.length-1,T),G(N,function(k){return a.coordToPoint(k.coord,E)})}),D=[],x=0;x<=T;x++){for(var M=[],I=0;I3?1.4:o>1?1.2:1.1,f=i>0?u:1/u;tg(this,"zoom","zoomOnMouseWheel",t,{scale:f,originX:s,originY:l,isAvailableBehavior:null})}if(n){var h=Math.abs(i),v=(i>0?1:-1)*(h>3?.4:h>1?.15:.05);tg(this,"scrollMove","moveOnMouseWheel",t,{scrollDelta:v,originX:s,originY:l,isAvailableBehavior:null})}}},e.prototype._pinchHandler=function(t){if(!ET(this._zr,"globalPan")){var a=t.pinchScale>1?1.1:1/1.1;tg(this,"zoom",null,t,{scale:a,originX:t.pinchX,originY:t.pinchY,isAvailableBehavior:null})}},e}(je);function tg(r,e,t,a,n){r.pointerChecker&&r.pointerChecker(a,n.originX,n.originY)&&(ia(a.event),kT(r,e,t,a,n))}function kT(r,e,t,a,n){n.isAvailableBehavior=Y(oh,null,t,a),r.trigger(e,n)}function oh(r,e,t){var a=t[r];return!r||a&&(!U(a)||e.event[a+"Key"])}function eg(r,e,t){var a=r.target;a.x+=e,a.y+=t,a.dirty()}function rg(r,e,t,a){var n=r.target,i=r.zoomLimit,o=r.zoom=r.zoom||1;if(o*=e,i){var s=i.min||0,l=i.max||Infinity;o=Math.max(Math.min(l,o),s)}var u=o/r.zoom;r.zoom=o,n.x-=(t-n.x)*(u-1),n.y-=(a-n.y)*(u-1),n.scaleX*=u,n.scaleY*=u,n.dirty()}var v5={axisPointer:1,tooltip:1,brush:1};function sh(r,e,t){var a=e.getComponentByElement(r.topTarget),n=a&&a.coordinateSystem;return a&&a!==t&&!v5.hasOwnProperty(a.mainType)&&n&&n.model!==t}function OT(r){if(U(r)){var e=new DOMParser;r=e.parseFromString(r,"text/xml")}var t=r;for(t.nodeType===9&&(t=t.firstChild);t.nodeName.toLowerCase()!=="svg"||t.nodeType!==1;)t=t.nextSibling;return t}var ag,lh={fill:"fill",stroke:"stroke","stroke-width":"lineWidth",opacity:"opacity","fill-opacity":"fillOpacity","stroke-opacity":"strokeOpacity","stroke-dasharray":"lineDash","stroke-dashoffset":"lineDashOffset","stroke-linecap":"lineCap","stroke-linejoin":"lineJoin","stroke-miterlimit":"miterLimit","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","text-anchor":"textAlign",visibility:"visibility",display:"display"},NT=St(lh),uh={"alignment-baseline":"textBaseline","stop-color":"stopColor"},BT=St(uh),c5=function(){function r(){this._defs={},this._root=null}return r.prototype.parse=function(e,t){t=t||{};var a=OT(e);this._defsUsePending=[];var n=new rt;this._root=n;var i=[],o=a.getAttribute("viewBox")||"",s=parseFloat(a.getAttribute("width")||t.width),l=parseFloat(a.getAttribute("height")||t.height);isNaN(s)&&(s=null),isNaN(l)&&(l=null),$e(a,n,null,!0,!1);for(var u=a.firstChild;u;)this._parseNode(u,n,i,null,!1,!1),u=u.nextSibling;g5(this._defs,this._defsUsePending),this._defsUsePending=[];var f,h;if(o){var v=fh(o);v.length>=4&&(f={x:parseFloat(v[0]||0),y:parseFloat(v[1]||0),width:parseFloat(v[2]),height:parseFloat(v[3])})}if(f&&s!=null&&l!=null&&(h=YT(f,{x:0,y:0,width:s,height:l}),!t.ignoreViewBox)){var c=n;n=new rt,n.add(c),c.scaleX=c.scaleY=h.scale,c.x=h.x,c.y=h.y}return!t.ignoreRootClip&&s!=null&&l!=null&&n.setClipPath(new xt({shape:{x:0,y:0,width:s,height:l}})),{root:n,width:s,height:l,viewBoxRect:f,viewBoxTransform:h,named:i}},r.prototype._parseNode=function(e,t,a,n,i,o){var s=e.nodeName.toLowerCase(),l,u=n;if(s==="defs"&&(i=!0),s==="text"&&(o=!0),s==="defs"||s==="switch")l=t;else{if(!i){var f=ag[s];if(f&&X(ag,s)){l=f.call(this,e,t);var h=e.getAttribute("name");if(h){var v={name:h,namedFrom:null,svgNodeTagLower:s,el:l};a.push(v),s==="g"&&(u=v)}else n&&a.push({name:n.name,namedFrom:n,svgNodeTagLower:s,el:l});t.add(l)}}var c=VT[s];if(c&&X(VT,s)){var p=c.call(this,e),d=e.getAttribute("id");d&&(this._defs[d]=p)}}if(l&&l.isGroup)for(var g=e.firstChild;g;)g.nodeType===1?this._parseNode(g,l,a,u,i,o):g.nodeType===3&&o&&this._parseText(g,l),g=g.nextSibling},r.prototype._parseText=function(e,t){var a=new Ri({style:{text:e.textContent},silent:!0,x:this._textX||0,y:this._textY||0});vr(t,a),$e(e,a,this._defsUsePending,!1,!1),p5(a,t);var n=a.style,i=n.fontSize;i&&i<9&&(n.fontSize=9,a.scaleX*=i/9,a.scaleY*=i/9);var o=(n.fontSize||n.fontFamily)&&[n.fontStyle,n.fontWeight,(n.fontSize||12)+"px",n.fontFamily||"sans-serif"].join(" ");n.font=o;var s=a.getBoundingRect();return this._textX+=s.width,t.add(a),a},r.internalField=function(){ag={g:function(e,t){var a=new rt;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a},rect:function(e,t){var a=new xt;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a.setShape({x:parseFloat(e.getAttribute("x")||"0"),y:parseFloat(e.getAttribute("y")||"0"),width:parseFloat(e.getAttribute("width")||"0"),height:parseFloat(e.getAttribute("height")||"0")}),a.silent=!0,a},circle:function(e,t){var a=new ar;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a.setShape({cx:parseFloat(e.getAttribute("cx")||"0"),cy:parseFloat(e.getAttribute("cy")||"0"),r:parseFloat(e.getAttribute("r")||"0")}),a.silent=!0,a},line:function(e,t){var a=new te;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a.setShape({x1:parseFloat(e.getAttribute("x1")||"0"),y1:parseFloat(e.getAttribute("y1")||"0"),x2:parseFloat(e.getAttribute("x2")||"0"),y2:parseFloat(e.getAttribute("y2")||"0")}),a.silent=!0,a},ellipse:function(e,t){var a=new Ss;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a.setShape({cx:parseFloat(e.getAttribute("cx")||"0"),cy:parseFloat(e.getAttribute("cy")||"0"),rx:parseFloat(e.getAttribute("rx")||"0"),ry:parseFloat(e.getAttribute("ry")||"0")}),a.silent=!0,a},polygon:function(e,t){var a=e.getAttribute("points"),n;a&&(n=FT(a));var i=new _e({shape:{points:n||[]},silent:!0});return vr(t,i),$e(e,i,this._defsUsePending,!1,!1),i},polyline:function(e,t){var a=e.getAttribute("points"),n;a&&(n=FT(a));var i=new Se({shape:{points:n||[]},silent:!0});return vr(t,i),$e(e,i,this._defsUsePending,!1,!1),i},image:function(e,t){var a=new ae;return vr(t,a),$e(e,a,this._defsUsePending,!1,!1),a.setStyle({image:e.getAttribute("xlink:href")||e.getAttribute("href"),x:+e.getAttribute("x"),y:+e.getAttribute("y"),width:+e.getAttribute("width"),height:+e.getAttribute("height")}),a.silent=!0,a},text:function(e,t){var a=e.getAttribute("x")||"0",n=e.getAttribute("y")||"0",i=e.getAttribute("dx")||"0",o=e.getAttribute("dy")||"0";this._textX=parseFloat(a)+parseFloat(i),this._textY=parseFloat(n)+parseFloat(o);var s=new rt;return vr(t,s),$e(e,s,this._defsUsePending,!1,!0),s},tspan:function(e,t){var a=e.getAttribute("x"),n=e.getAttribute("y");a!=null&&(this._textX=parseFloat(a)),n!=null&&(this._textY=parseFloat(n));var i=e.getAttribute("dx")||"0",o=e.getAttribute("dy")||"0",s=new rt;return vr(t,s),$e(e,s,this._defsUsePending,!1,!0),this._textX+=parseFloat(i),this._textY+=parseFloat(o),s},path:function(e,t){var a=e.getAttribute("d")||"",n=a1(a);return vr(t,n),$e(e,n,this._defsUsePending,!1,!1),n.silent=!0,n}}}(),r}(),VT={lineargradient:function(r){var e=parseInt(r.getAttribute("x1")||"0",10),t=parseInt(r.getAttribute("y1")||"0",10),a=parseInt(r.getAttribute("x2")||"10",10),n=parseInt(r.getAttribute("y2")||"0",10),i=new Gi(e,t,a,n);return zT(r,i),GT(r,i),i},radialgradient:function(r){var e=parseInt(r.getAttribute("cx")||"0",10),t=parseInt(r.getAttribute("cy")||"0",10),a=parseInt(r.getAttribute("r")||"0",10),n=new Fc(e,t,a);return zT(r,n),GT(r,n),n}};function zT(r,e){var t=r.getAttribute("gradientUnits");t==="userSpaceOnUse"&&(e.global=!0)}function GT(r,e){for(var t=r.firstChild;t;){if(t.nodeType===1&&t.nodeName.toLocaleLowerCase()==="stop"){var a=t.getAttribute("offset"),n=void 0;a&&a.indexOf("%")>0?n=parseInt(a,10)/100:a?n=parseFloat(a):n=0;var i={};UT(t,i,i);var o=i.stopColor||t.getAttribute("stop-color")||"#000000";e.colorStops.push({offset:n,color:o})}t=t.nextSibling}}function vr(r,e){r&&r.__inheritedStyle&&(e.__inheritedStyle||(e.__inheritedStyle={}),j(e.__inheritedStyle,r.__inheritedStyle))}function FT(r){for(var e=fh(r),t=[],a=0;a0;i-=2){var o=a[i],s=a[i-1],l=fh(o);switch(n=n||Ge(),s){case"translate":mr(n,n,[parseFloat(l[0]),parseFloat(l[1]||"0")]);break;case"scale":tu(n,n,[parseFloat(l[0]),parseFloat(l[1]||l[0])]);break;case"rotate":Ia(n,n,-parseFloat(l[0])*ng);break;case"skewX":var u=Math.tan(parseFloat(l[0])*ng);Or(n,[1,0,u,1,0,0],n);break;case"skewY":var f=Math.tan(parseFloat(l[0])*ng);Or(n,[1,f,0,1,0,0],n);break;case"matrix":n[0]=parseFloat(l[0]),n[1]=parseFloat(l[1]),n[2]=parseFloat(l[2]),n[3]=parseFloat(l[3]),n[4]=parseFloat(l[4]),n[5]=parseFloat(l[5]);break}}e.setLocalTransform(n)}}var WT=/([^\s:;]+)\s*:\s*([^:;]+)/g;function UT(r,e,t){var a=r.getAttribute("style");if(!!a){WT.lastIndex=0;for(var n;(n=WT.exec(a))!=null;){var i=n[1],o=X(lh,i)?lh[i]:null;o&&(e[o]=n[2]);var s=X(uh,i)?uh[i]:null;s&&(t[s]=n[2])}}}function S5(r,e,t){for(var a=0;a0,g={api:a,geo:l,mapOrGeoModel:e,data:s,isVisualEncodedByVisualMap:d,isGeo:o,transformInfoRaw:v};l.resourceType==="geoJSON"?this._buildGeoJSON(g):l.resourceType==="geoSVG"&&this._buildSVG(g),this._updateController(e,t,a),this._updateMapSelectHandler(e,u,a,n)},r.prototype._buildGeoJSON=function(e){var t=this._regionsGroupByName=$(),a=$(),n=this._regionsGroup,i=e.transformInfoRaw,o=e.mapOrGeoModel,s=e.data,l=e.geo.projection,u=l&&l.stream;function f(c,p){return p&&(c=p(c)),c&&[c[0]*i.scaleX+i.x,c[1]*i.scaleY+i.y]}function h(c){for(var p=[],d=!u&&l&&l.project,g=0;g=0)&&(v=n);var c=o?{normal:{align:"center",verticalAlign:"middle"}}:null;ve(e,ne(a),{labelFetcher:v,labelDataIndex:h,defaultText:t},c);var p=e.getTextContent();if(p&&(ZT(p).ignore=p.ignore,e.textConfig&&o)){var d=e.getBoundingRect().clone();e.textConfig.layoutRect=d,e.textConfig.position=[(o[0]-d.x)/d.width*100+"%",(o[1]-d.y)/d.height*100+"%"]}e.disableLabelAnimation=!0}else e.removeTextContent(),e.removeTextConfig(),e.disableLabelAnimation=null}function QT(r,e,t,a,n,i){r.data?r.data.setItemGraphicEl(i,e):nt(e).eventData={componentType:"geo",componentIndex:n.componentIndex,geoIndex:n.componentIndex,name:t,region:a&&a.option||{}}}function JT(r,e,t,a,n){r.data||Yi({el:e,componentModel:n,itemName:t,itemTooltipOption:a.get("tooltip")})}function tC(r,e,t,a,n){e.highDownSilentOnTouch=!!n.get("selectedMode");var i=a.getModel("emphasis"),o=i.get("focus");return Ut(e,o,i.get("blurScope"),i.get("disabled")),r.isGeo&&wR(e,n,t),o}function eC(r,e,t){var a=[],n;function i(){n=[]}function o(){n.length&&(a.push(n),n=[])}var s=e({polygonStart:i,polygonEnd:o,lineStart:i,lineEnd:o,point:function(l,u){isFinite(l)&&isFinite(u)&&n.push([l,u])},sphere:function(){}});return!t&&s.polygonStart(),A(r,function(l){s.lineStart();for(var u=0;u-1&&(n.style.stroke=n.style.fill,n.style.fill="#fff",n.style.lineWidth=2),n},e.type="series.map",e.dependencies=["geo"],e.layoutMode="box",e.defaultOption={z:2,coordinateSystem:"geo",map:"",left:"center",top:"center",aspectScale:null,showLegendSymbol:!0,boundingCoords:null,center:null,zoom:1,scaleLimit:null,selectedMode:!0,label:{show:!1,color:"#000"},itemStyle:{borderWidth:.5,borderColor:"#444",areaColor:"#eee"},emphasis:{label:{show:!0,color:"rgb(100,0,0)"},itemStyle:{areaColor:"rgba(255,215,0,0.8)"}},select:{label:{show:!0,color:"rgb(100,0,0)"},itemStyle:{color:"rgba(255,215,0,0.8)"}},nameProperty:"name"},e}(kt);function G5(r,e){var t={};return A(r,function(a){a.each(a.mapDimension("value"),function(n,i){var o="ec-"+a.getName(i);t[o]=t[o]||[],isNaN(n)||t[o].push(n)})}),r[0].map(r[0].mapDimension("value"),function(a,n){for(var i="ec-"+r[0].getName(n),o=0,s=Infinity,l=-Infinity,u=t[i].length,f=0;f1?(S.width=_,S.height=_/g):(S.height=_,S.width=_*g),S.y=m[1]-S.height/2,S.x=m[0]-S.width/2;else{var b=r.getBoxLayoutParams();b.aspect=g,S=jt(b,{width:p,height:d})}this.setViewRect(S.x,S.y,S.width,S.height),this.setCenter(r.get("center"),e),this.setZoom(r.get("zoom"))}function U5(r,e){A(e.get("geoCoord"),function(t,a){r.addGeoCoord(a,t)})}var Y5=function(){function r(){this.dimensions=nC}return r.prototype.create=function(e,t){var a=[];function n(o){return{nameProperty:o.get("nameProperty"),aspectScale:o.get("aspectScale"),projection:o.get("projection")}}e.eachComponent("geo",function(o,s){var l=o.get("map"),u=new sg(l+s,l,B({nameMap:o.get("nameMap")},n(o)));u.zoomLimit=o.get("scaleLimit"),a.push(u),o.coordinateSystem=u,u.model=o,u.resize=oC,u.resize(o,t)}),e.eachSeries(function(o){var s=o.get("coordinateSystem");if(s==="geo"){var l=o.get("geoIndex")||0;o.coordinateSystem=a[l]}});var i={};return e.eachSeriesByType("map",function(o){if(!o.getHostGeoModel()){var s=o.getMapType();i[s]=i[s]||[],i[s].push(o)}}),A(i,function(o,s){var l=G(o,function(f){return f.get("nameMap")}),u=new sg(s,s,B({nameMap:Zl(l)},n(o[0])));u.zoomLimit=ee.apply(null,G(o,function(f){return f.get("scaleLimit")})),a.push(u),u.resize=oC,u.resize(o[0],t),A(o,function(f){f.coordinateSystem=u,U5(u,f)})}),a},r.prototype.getFilledRegions=function(e,t,a,n){for(var i=(e||[]).slice(),o=$(),s=0;s=0;o--){var s=n[o];s.hierNode={defaultAncestor:null,ancestor:s,prelim:0,modifier:0,change:0,shift:0,i:o,thread:null},t.push(s)}}function j5(r,e){var t=r.isExpand?r.children:[],a=r.parentNode.children,n=r.hierNode.i?a[r.hierNode.i-1]:null;if(t.length){tG(r);var i=(t[0].hierNode.prelim+t[t.length-1].hierNode.prelim)/2;n?(r.hierNode.prelim=n.hierNode.prelim+e(r,n),r.hierNode.modifier=r.hierNode.prelim-i):r.hierNode.prelim=i}else n&&(r.hierNode.prelim=n.hierNode.prelim+e(r,n));r.parentNode.hierNode.defaultAncestor=eG(r,n,r.parentNode.hierNode.defaultAncestor||a[0],e)}function Q5(r){var e=r.hierNode.prelim+r.parentNode.hierNode.modifier;r.setLayout({x:e},!0),r.hierNode.modifier+=r.parentNode.hierNode.modifier}function fC(r){return arguments.length?r:nG}function Sl(r,e){return r-=Math.PI/2,{x:e*Math.cos(r),y:e*Math.sin(r)}}function J5(r,e){return jt(r.getBoxLayoutParams(),{width:e.getWidth(),height:e.getHeight()})}function tG(r){for(var e=r.children,t=e.length,a=0,n=0;--t>=0;){var i=e[t];i.hierNode.prelim+=a,i.hierNode.modifier+=a,n+=i.hierNode.change,a+=i.hierNode.shift+n}}function eG(r,e,t,a){if(e){for(var n=r,i=r,o=i.parentNode.children[0],s=e,l=n.hierNode.modifier,u=i.hierNode.modifier,f=o.hierNode.modifier,h=s.hierNode.modifier;s=ug(s),i=fg(i),s&&i;){n=ug(n),o=fg(o),n.hierNode.ancestor=r;var v=s.hierNode.prelim+h-i.hierNode.prelim-u+a(s,i);v>0&&(aG(rG(s,r,t),r,v),u+=v,l+=v),h+=s.hierNode.modifier,u+=i.hierNode.modifier,l+=n.hierNode.modifier,f+=o.hierNode.modifier}s&&!ug(n)&&(n.hierNode.thread=s,n.hierNode.modifier+=h-l),i&&!fg(o)&&(o.hierNode.thread=i,o.hierNode.modifier+=u-f,t=r)}return t}function ug(r){var e=r.children;return e.length&&r.isExpand?e[e.length-1]:r.hierNode.thread}function fg(r){var e=r.children;return e.length&&r.isExpand?e[0]:r.hierNode.thread}function rG(r,e,t){return r.hierNode.ancestor.parentNode===e.parentNode?r.hierNode.ancestor:t}function aG(r,e,t){var a=t/(e.hierNode.i-r.hierNode.i);e.hierNode.change-=a,e.hierNode.shift+=t,e.hierNode.modifier+=t,e.hierNode.prelim+=t,r.hierNode.change+=a}function nG(r,e){return r.parentNode===e.parentNode?1:2}var iG=function(){function r(){this.parentPoint=[],this.childPoints=[]}return r}(),oG=function(r){O(e,r);function e(t){return r.call(this,t)||this}return e.prototype.getDefaultStyle=function(){return{stroke:"#000",fill:null}},e.prototype.getDefaultShape=function(){return new iG},e.prototype.buildPath=function(t,a){var n=a.childPoints,i=n.length,o=a.parentPoint,s=n[0],l=n[i-1];if(i===1){t.moveTo(o[0],o[1]),t.lineTo(s[0],s[1]);return}var u=a.orient,f=u==="TB"||u==="BT"?0:1,h=1-f,v=H(a.forkPosition,1),c=[];c[f]=o[f],c[h]=o[h]+(l[h]-o[h])*v,t.moveTo(o[0],o[1]),t.lineTo(c[0],c[1]),t.moveTo(s[0],s[1]),c[f]=s[f],t.lineTo(c[0],c[1]),c[f]=l[f],t.lineTo(c[0],c[1]),t.lineTo(l[0],l[1]);for(var p=1;pm.x,b||(S=S-Math.PI));var w=b?"left":"right",T=s.getModel("label"),C=T.get("rotate"),D=C*(Math.PI/180),M=g.getTextContent();M&&(g.setTextConfig({position:T.get("position")||w,rotation:C==null?-S:D,origin:"center"}),M.setStyle("verticalAlign","middle"))}var I=s.get(["emphasis","focus"]),L=I==="relative"?No(o.getAncestorsIndices(),o.getDescendantIndices()):I==="ancestor"?o.getAncestorsIndices():I==="descendant"?o.getDescendantIndices():null;L&&(nt(t).focus=L),lG(n,o,f,t,p,c,d,a),t.__edge&&(t.onHoverStateChange=function(P){if(P!=="blur"){var R=o.parentNode&&r.getItemGraphicEl(o.parentNode.dataIndex);R&&R.hoverState===ps||Vu(t.__edge,P)}})}function lG(r,e,t,a,n,i,o,s){var l=e.getModel(),u=r.get("edgeShape"),f=r.get("layout"),h=r.getOrient(),v=r.get(["lineStyle","curveness"]),c=r.get("edgeForkPosition"),p=l.getModel("lineStyle").getLineStyle(),d=a.__edge;if(u==="curve")e.parentNode&&e.parentNode!==t&&(d||(d=a.__edge=new zi({shape:hg(f,h,v,n,n)})),At(d,{shape:hg(f,h,v,i,o)},r));else if(u==="polyline"&&f==="orthogonal"&&e!==t&&e.children&&e.children.length!==0&&e.isExpand===!0){for(var g=e.children,y=[],m=0;mt&&(t=n.height)}this.height=t+1},r.prototype.getNodeById=function(e){if(this.getId()===e)return this;for(var t=0,a=this.children,n=a.length;t=0&&this.hostTree.data.setItemLayout(this.dataIndex,e,t)},r.prototype.getLayout=function(){return this.hostTree.data.getItemLayout(this.dataIndex)},r.prototype.getModel=function(e){if(!(this.dataIndex<0)){var t=this.hostTree,a=t.data.getItemModel(this.dataIndex);return a.getModel(e)}},r.prototype.getLevelModel=function(){return(this.hostTree.levelModels||[])[this.depth]},r.prototype.setVisual=function(e,t){this.dataIndex>=0&&this.hostTree.data.setItemVisual(this.dataIndex,e,t)},r.prototype.getVisual=function(e){return this.hostTree.data.getItemVisual(this.dataIndex,e)},r.prototype.getRawIndex=function(){return this.hostTree.data.getRawIndex(this.dataIndex)},r.prototype.getId=function(){return this.hostTree.data.getId(this.dataIndex)},r.prototype.getChildIndex=function(){if(this.parentNode){for(var e=this.parentNode.children,t=0;t=0){var a=t.getData().tree.root,n=r.targetNode;if(U(n)&&(n=a.getNodeById(n)),n&&a.contains(n))return{node:n};var i=r.targetNodeId;if(i!=null&&(n=a.getNodeById(i)))return{node:n}}}function mC(r){for(var e=[];r;)r=r.parentNode,r&&e.push(r);return e.reverse()}function pg(r,e){var t=mC(r);return vt(t,e)>=0}function vh(r,e){for(var t=[];r;){var a=r.dataIndex;t.push({name:r.name,dataIndex:a,value:e.getRawValue(a)}),r=r.parentNode}return t.reverse(),t}var yG=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.hasSymbolVisual=!0,t.ignoreStyleOnData=!0,t}return e.prototype.getInitialData=function(t){var a={name:t.name,children:t.data},n=t.leaves||{},i=new Mt(n,this,this.ecModel),o=cg.createTree(a,this,s);function s(h){h.wrapMethod("getItemModel",function(v,c){var p=o.getNodeByDataIndex(c);return p&&p.children.length&&p.isExpand||(v.parentModel=i),v})}var l=0;o.eachNode("preorder",function(h){h.depth>l&&(l=h.depth)});var u=t.expandAndCollapse,f=u&&t.initialTreeDepth>=0?t.initialTreeDepth:l;return o.root.eachNode("preorder",function(h){var v=h.hostTree.data.getRawDataItem(h.dataIndex);h.isExpand=v&&v.collapsed!=null?!v.collapsed:h.depth<=f}),o.data},e.prototype.getOrient=function(){var t=this.get("orient");return t==="horizontal"?t="LR":t==="vertical"&&(t="TB"),t},e.prototype.setZoom=function(t){this.option.zoom=t},e.prototype.setCenter=function(t){this.option.center=t},e.prototype.formatTooltip=function(t,a,n){for(var i=this.getData().tree,o=i.root.children[0],s=i.getNodeByDataIndex(t),l=s.getValue(),u=s.name;s&&s!==o;)u=s.parentNode.name+"."+u,s=s.parentNode;return ie("nameValue",{name:u,value:l,noValue:isNaN(l)||l==null})},e.prototype.getDataParams=function(t){var a=r.prototype.getDataParams.apply(this,arguments),n=this.getData().tree.getNodeByDataIndex(t);return a.treeAncestors=vh(n,this),a.collapsed=!n.isExpand,a},e.type="series.tree",e.layoutMode="box",e.defaultOption={z:2,coordinateSystem:"view",left:"12%",top:"12%",right:"12%",bottom:"12%",layout:"orthogonal",edgeShape:"curve",edgeForkPosition:"50%",roam:!1,nodeScaleRatio:.4,center:null,zoom:1,orient:"LR",symbol:"emptyCircle",symbolSize:7,expandAndCollapse:!0,initialTreeDepth:2,lineStyle:{color:"#ccc",width:1.5,curveness:.5},itemStyle:{color:"lightsteelblue",borderWidth:1.5},label:{show:!0},animationEasing:"linear",animationDuration:700,animationDurationUpdate:500},e}(kt);function mG(r,e,t){for(var a=[r],n=[],i;i=a.pop();)if(n.push(i),i.isExpand){var o=i.children;if(o.length)for(var s=0;s=0;i--)t.push(n[i])}}function _G(r,e){r.eachSeriesByType("tree",function(t){SG(t,e)})}function SG(r,e){var t=J5(r,e);r.layoutInfo=t;var a=r.get("layout"),n=0,i=0,o=null;a==="radial"?(n=2*Math.PI,i=Math.min(t.height,t.width)/2,o=fC(function(_,S){return(_.parentNode===S.parentNode?1:2)/_.depth})):(n=t.width,i=t.height,o=fC());var s=r.getData().tree.root,l=s.children[0];if(l){K5(s),mG(l,j5,o),s.hierNode.modifier=-l.hierNode.prelim,bl(l,Q5);var u=l,f=l,h=l;bl(l,function(_){var S=_.getLayout().x;Sf.getLayout().x&&(f=_),_.depth>h.depth&&(h=_)});var v=u===f?1:o(u,f)/2,c=v-u.getLayout().x,p=0,d=0,g=0,y=0;if(a==="radial")p=n/(f.getLayout().x+v+c),d=i/(h.depth-1||1),bl(l,function(_){g=(_.getLayout().x+c)*p,y=(_.depth-1)*d;var S=Sl(g,y);_.setLayout({x:S.x,y:S.y,rawX:g,rawY:y},!0)});else{var m=r.getOrient();m==="RL"||m==="LR"?(d=i/(f.getLayout().x+v+c),p=n/(h.depth-1||1),bl(l,function(_){y=(_.getLayout().x+c)*d,g=m==="LR"?(_.depth-1)*p:n-(_.depth-1)*p,_.setLayout({x:g,y},!0)})):(m==="TB"||m==="BT")&&(p=n/(f.getLayout().x+v+c),d=i/(h.depth-1||1),bl(l,function(_){g=(_.getLayout().x+c)*p,y=m==="TB"?(_.depth-1)*d:i-(_.depth-1)*d,_.setLayout({x:g,y},!0)}))}}}function xG(r){r.eachSeriesByType("tree",function(e){var t=e.getData(),a=t.tree;a.eachNode(function(n){var i=n.getModel(),o=i.getModel("itemStyle").getItemStyle(),s=t.ensureUniqueItemVisual(n.dataIndex,"style");B(s,o)})})}function bG(r){r.registerAction({type:"treeExpandAndCollapse",event:"treeExpandAndCollapse",update:"update"},function(e,t){t.eachComponent({mainType:"series",subType:"tree",query:e},function(a){var n=e.dataIndex,i=a.getData().tree,o=i.getNodeByDataIndex(n);o.isExpand=!o.isExpand})}),r.registerAction({type:"treeRoam",event:"treeRoam",update:"none"},function(e,t,a){t.eachComponent({mainType:"series",subType:"tree",query:e},function(n){var i=n.coordinateSystem,o=lg(i,e,void 0,a);n.setCenter&&n.setCenter(o.center),n.setZoom&&n.setZoom(o.zoom)})})}function wG(r){r.registerChartView(sG),r.registerSeriesModel(yG),r.registerLayout(_G),r.registerVisual(xG),bG(r)}var _C=["treemapZoomToNode","treemapRender","treemapMove"];function TG(r){for(var e=0;e<_C.length;e++)r.registerAction({type:_C[e],update:"updateView"},Zt);r.registerAction({type:"treemapRootToNode",update:"updateView"},function(t,a){a.eachComponent({mainType:"series",subType:"treemap",query:t},n);function n(i,o){var s=["treemapZoomToNode","treemapRootToNode"],l=xl(t,s,i);if(l){var u=i.getViewRoot();u&&(t.direction=pg(u,l.node)?"rollUp":"drillDown"),i.resetViewRoot(l.node)}}})}function SC(r){var e=r.getData(),t=e.tree,a={};t.eachNode(function(n){for(var i=n;i&&i.depth>1;)i=i.parentNode;var o=dp(r.ecModel,i.name||i.dataIndex+"",a);n.setVisual("decal",o)})}var CG=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.preventUsingHoverLayer=!0,t}return e.prototype.getInitialData=function(t,a){var n={name:t.name,children:t.data};xC(n);var i=t.levels||[],o=this.designatedVisualItemStyle={},s=new Mt({itemStyle:o},this,a);i=t.levels=AG(i,a);var l=G(i||[],function(h){return new Mt(h,s,a)},this),u=cg.createTree(n,this,f);function f(h){h.wrapMethod("getItemModel",function(v,c){var p=u.getNodeByDataIndex(c),d=p?l[p.depth]:null;return v.parentModel=d||s,v})}return u.data},e.prototype.optionUpdated=function(){this.resetViewRoot()},e.prototype.formatTooltip=function(t,a,n){var i=this.getData(),o=this.getRawValue(t),s=i.getName(t);return ie("nameValue",{name:s,value:o})},e.prototype.getDataParams=function(t){var a=r.prototype.getDataParams.apply(this,arguments),n=this.getData().tree.getNodeByDataIndex(t);return a.treeAncestors=vh(n,this),a.treePathInfo=a.treeAncestors,a},e.prototype.setLayoutInfo=function(t){this.layoutInfo=this.layoutInfo||{},B(this.layoutInfo,t)},e.prototype.mapIdToIndex=function(t){var a=this._idIndexMap;a||(a=this._idIndexMap=$(),this._idIndexMapCount=0);var n=a.get(t);return n==null&&a.set(t,n=this._idIndexMapCount++),n},e.prototype.getViewRoot=function(){return this._viewRoot},e.prototype.resetViewRoot=function(t){t?this._viewRoot=t:t=this._viewRoot;var a=this.getRawData().tree.root;(!t||t!==a&&!a.contains(t))&&(this._viewRoot=a)},e.prototype.enableAriaDecal=function(){SC(this)},e.type="series.treemap",e.layoutMode="box",e.defaultOption={progressive:0,left:"center",top:"middle",width:"80%",height:"80%",sort:!0,clipWindow:"origin",squareRatio:.5*(1+Math.sqrt(5)),leafDepth:null,drillDownIcon:"\u25B6",zoomToNodeRatio:.32*.32,roam:!0,nodeClick:"zoomToNode",animation:!0,animationDurationUpdate:900,animationEasing:"quinticInOut",breadcrumb:{show:!0,height:22,left:"center",top:"bottom",emptyItemWidth:25,itemStyle:{color:"rgba(0,0,0,0.7)",textStyle:{color:"#fff"}},emphasis:{itemStyle:{color:"rgba(0,0,0,0.9)"}}},label:{show:!0,distance:0,padding:5,position:"inside",color:"#fff",overflow:"truncate"},upperLabel:{show:!1,position:[0,"50%"],height:20,overflow:"truncate",verticalAlign:"middle"},itemStyle:{color:null,colorAlpha:null,colorSaturation:null,borderWidth:0,gapWidth:0,borderColor:"#fff",borderColorSaturation:null},emphasis:{upperLabel:{show:!0,position:[0,"50%"],overflow:"truncate",verticalAlign:"middle"}},visualDimension:0,visualMin:null,visualMax:null,color:[],colorAlpha:null,colorSaturation:null,colorMappingBy:"index",visibleMin:10,childrenVisibleMin:null,levels:[]},e}(kt);function xC(r){var e=0;A(r.children,function(a){xC(a);var n=a.value;z(n)&&(n=n[0]),e+=n});var t=r.value;z(t)&&(t=t[0]),(t==null||isNaN(t))&&(t=e),t<0&&(t=0),z(r.value)?r.value[0]=t:r.value=t}function AG(r,e){var t=Et(e.get("color")),a=Et(e.get(["aria","decal","decals"]));if(!!t){r=r||[];var n,i;A(r,function(s){var l=new Mt(s),u=l.get("color"),f=l.get("decal");(l.get(["itemStyle","color"])||u&&u!=="none")&&(n=!0),(l.get(["itemStyle","decal"])||f&&f!=="none")&&(i=!0)});var o=r[0]||(r[0]={});return n||(o.color=t.slice()),!i&&a&&(o.decal=a.slice()),r}}var DG=8,bC=8,dg=5,MG=function(){function r(e){this.group=new rt,e.add(this.group)}return r.prototype.render=function(e,t,a,n){var i=e.getModel("breadcrumb"),o=this.group;if(o.removeAll(),!(!i.get("show")||!a)){var s=i.getModel("itemStyle"),l=i.getModel("emphasis"),u=s.getModel("textStyle"),f=l.getModel(["itemStyle","textStyle"]),h={pos:{left:i.get("left"),right:i.get("right"),top:i.get("top"),bottom:i.get("bottom")},box:{width:t.getWidth(),height:t.getHeight()},emptyItemWidth:i.get("emptyItemWidth"),totalWidth:0,renderList:[]};this._prepare(a,h,u),this._renderContent(e,h,s,l,u,f,n),uf(o,h.pos,h.box)}},r.prototype._prepare=function(e,t,a){for(var n=e;n;n=n.parentNode){var i=Jt(n.getModel().get("name"),""),o=a.getTextRect(i),s=Math.max(o.width+DG*2,t.emptyItemWidth);t.totalWidth+=s+bC,t.renderList.push({node:n,text:i,width:s})}},r.prototype._renderContent=function(e,t,a,n,i,o,s){for(var l=0,u=t.emptyItemWidth,f=e.get(["breadcrumb","height"]),h=wE(t.pos,t.box),v=t.totalWidth,c=t.renderList,p=n.getModel("itemStyle").getItemStyle(),d=c.length-1;d>=0;d--){var g=c[d],y=g.node,m=g.width,_=g.text;v>h.width&&(v-=m-u,m=u,_=null);var S=new _e({shape:{points:IG(l,0,m,f,d===c.length-1,d===0)},style:j(a.getItemStyle(),{lineJoin:"bevel"}),textContent:new bt({style:Nt(i,{text:_})}),textConfig:{position:"inside"},z2:ki*1e4,onclick:it(s,y)});S.disableLabelAnimation=!0,S.getTextContent().ensureState("emphasis").style=Nt(o,{text:_}),S.ensureState("emphasis").style=p,Ut(S,n.get("focus"),n.get("blurScope"),n.get("disabled")),this.group.add(S),LG(S,e,y),l+=m+bC}},r.prototype.remove=function(){this.group.removeAll()},r}();function IG(r,e,t,a,n,i){var o=[[n?r:r-dg,e],[r+t,e],[r+t,e+a],[n?r:r-dg,e+a]];return!i&&o.splice(2,0,[r+t+dg,e+a/2]),!n&&o.push([r,e+a/2]),o}function LG(r,e,t){nt(r).eventData={componentType:"series",componentSubType:"treemap",componentIndex:e.componentIndex,seriesIndex:e.seriesIndex,seriesName:e.name,seriesType:"treemap",selfType:"breadcrumb",nodeData:{dataIndex:t&&t.dataIndex,name:t&&t.name},treePathInfo:t&&vh(t,e)}}var PG=function(){function r(){this._storage=[],this._elExistsMap={}}return r.prototype.add=function(e,t,a,n,i){return this._elExistsMap[e.id]?!1:(this._elExistsMap[e.id]=!0,this._storage.push({el:e,target:t,duration:a,delay:n,easing:i}),!0)},r.prototype.finished=function(e){return this._finishedCallback=e,this},r.prototype.start=function(){for(var e=this,t=this._storage.length,a=function(){t--,t<=0&&(e._storage.length=0,e._elExistsMap={},e._finishedCallback&&e._finishedCallback())},n=0,i=this._storage.length;nTC||Math.abs(t.dy)>TC)){var a=this.seriesModel.getData().tree.root;if(!a)return;var n=a.getLayout();if(!n)return;this.api.dispatchAction({type:"treemapMove",from:this.uid,seriesId:this.seriesModel.id,rootRect:{x:n.x+t.dx,y:n.y+t.dy,width:n.width,height:n.height}})}},e.prototype._onZoom=function(t){var a=t.originX,n=t.originY;if(this._state!=="animating"){var i=this.seriesModel.getData().tree.root;if(!i)return;var o=i.getLayout();if(!o)return;var s=new ft(o.x,o.y,o.width,o.height),l=this.seriesModel.layoutInfo;a-=l.x,n-=l.y;var u=Ge();mr(u,u,[-a,-n]),tu(u,u,[t.scale,t.scale]),mr(u,u,[a,n]),s.applyTransform(u),this.api.dispatchAction({type:"treemapRender",from:this.uid,seriesId:this.seriesModel.id,rootRect:{x:s.x,y:s.y,width:s.width,height:s.height}})}},e.prototype._initEvents=function(t){var a=this;t.on("click",function(n){if(a._state==="ready"){var i=a.seriesModel.get("nodeClick",!0);if(!!i){var o=a.findTarget(n.offsetX,n.offsetY);if(!!o){var s=o.node;if(s.getLayout().isLeafRoot)a._rootToNode(o);else if(i==="zoomToNode")a._zoomToNode(o);else if(i==="link"){var l=s.hostTree.data.getItemModel(s.dataIndex),u=l.get("link",!0),f=l.get("target",!0)||"blank";u&&sf(u,f)}}}}},this)},e.prototype._renderBreadcrumb=function(t,a,n){var i=this;n||(n=t.get("leafDepth",!0)!=null?{node:t.getViewRoot()}:this.findTarget(a.getWidth()/2,a.getHeight()/2),n||(n={node:t.getData().tree.root})),(this._breadcrumb||(this._breadcrumb=new MG(this.group))).render(t,a,n.node,function(o){i._state!=="animating"&&(pg(t.getViewRoot(),o)?i._rootToNode({node:o}):i._zoomToNode({node:o}))})},e.prototype.remove=function(){this._clearController(),this._containerGroup&&this._containerGroup.removeAll(),this._storage=wl(),this._state="ready",this._breadcrumb&&this._breadcrumb.remove()},e.prototype.dispose=function(){this._clearController()},e.prototype._zoomToNode=function(t){this.api.dispatchAction({type:"treemapZoomToNode",from:this.uid,seriesId:this.seriesModel.id,targetNode:t.node})},e.prototype._rootToNode=function(t){this.api.dispatchAction({type:"treemapRootToNode",from:this.uid,seriesId:this.seriesModel.id,targetNode:t.node})},e.prototype.findTarget=function(t,a){var n,i=this.seriesModel.getViewRoot();return i.eachNode({attr:"viewChildren",order:"preorder"},function(o){var s=this._storage.background[o.getRawIndex()];if(s){var l=s.transformCoordToLocal(t,a),u=s.shape;if(u.x<=l[0]&&l[0]<=u.x+u.width&&u.y<=l[1]&&l[1]<=u.y+u.height)n={node:o,offsetX:l[0],offsetY:l[1]};else return!1}},this),n},e.type="treemap",e}(Rt);function wl(){return{nodeGroup:[],background:[],content:[]}}function BG(r,e,t,a,n,i,o,s,l,u){if(!o)return;var f=o.getLayout(),h=r.getData(),v=o.getModel();if(h.setItemGraphicEl(o.dataIndex,null),!f||!f.isInView)return;var c=f.width,p=f.height,d=f.borderWidth,g=f.invisible,y=o.getRawIndex(),m=s&&s.getRawIndex(),_=o.viewChildren,S=f.upperHeight,b=_&&_.length,x=v.getModel("itemStyle"),w=v.getModel(["emphasis","itemStyle"]),T=v.getModel(["blur","itemStyle"]),C=v.getModel(["select","itemStyle"]),D=x.get("borderRadius")||0,M=tt("nodeGroup",gg);if(!M)return;if(l.add(M),M.x=f.x||0,M.y=f.y||0,M.markRedraw(),ch(M).nodeWidth=c,ch(M).nodeHeight=p,f.isAboveViewRoot)return M;var I=tt("background",wC,u,kG);I&&V(M,I,b&&f.upperLabelHeight);var L=v.getModel("emphasis"),P=L.get("focus"),R=L.get("blurScope"),E=L.get("disabled"),N=P==="ancestor"?o.getAncestorsIndices():P==="descendant"?o.getDescendantIndices():P;if(b)ms(M)&&kn(M,!1),I&&(kn(I,!E),h.setItemGraphicEl(o.dataIndex,I),Oc(I,N,R));else{var k=tt("content",wC,u,OG);k&&F(M,k),I.disableMorphing=!0,I&&ms(I)&&kn(I,!1),kn(M,!E),h.setItemGraphicEl(o.dataIndex,M),Oc(M,N,R)}return M;function V(pt,at,mt){var ht=nt(at);if(ht.dataIndex=o.dataIndex,ht.seriesIndex=r.seriesIndex,at.setShape({x:0,y:0,width:c,height:p,r:D}),g)W(at);else{at.invisible=!1;var q=o.getVisual("style"),st=q.stroke,Ft=DC(x);Ft.fill=st;var wt=li(w);wt.fill=w.get("borderColor");var Yt=li(T);Yt.fill=T.get("borderColor");var Ht=li(C);if(Ht.fill=C.get("borderColor"),mt){var pe=c-2*d;Z(at,st,q.opacity,{x:d,y:0,width:pe,height:S})}else at.removeTextContent();at.setStyle(Ft),at.ensureState("emphasis").style=wt,at.ensureState("blur").style=Yt,at.ensureState("select").style=Ht,En(at)}pt.add(at)}function F(pt,at){var mt=nt(at);mt.dataIndex=o.dataIndex,mt.seriesIndex=r.seriesIndex;var ht=Math.max(c-2*d,0),q=Math.max(p-2*d,0);if(at.culling=!0,at.setShape({x:d,y:d,width:ht,height:q,r:D}),g)W(at);else{at.invisible=!1;var st=o.getVisual("style"),Ft=st.fill,wt=DC(x);wt.fill=Ft,wt.decal=st.decal;var Yt=li(w),Ht=li(T),pe=li(C);Z(at,Ft,st.opacity,null),at.setStyle(wt),at.ensureState("emphasis").style=Yt,at.ensureState("blur").style=Ht,at.ensureState("select").style=pe,En(at)}pt.add(at)}function W(pt){!pt.invisible&&i.push(pt)}function Z(pt,at,mt,ht){var q=v.getModel(ht?AC:CC),st=Jt(v.get("name"),null),Ft=q.getShallow("show");ve(pt,ne(v,ht?AC:CC),{defaultText:Ft?st:null,inheritColor:at,defaultOpacity:mt,labelFetcher:r,labelDataIndex:o.dataIndex});var wt=pt.getTextContent();if(!!wt){var Yt=wt.style,Ht=Kl(Yt.padding||0);ht&&(pt.setTextConfig({layoutRect:ht}),wt.disableLabelLayout=!0),wt.beforeUpdate=function(){var ea=Math.max((ht?ht.width:pt.shape.width)-Ht[1]-Ht[3],0),Re=Math.max((ht?ht.height:pt.shape.height)-Ht[0]-Ht[2],0);(Yt.width!==ea||Yt.height!==Re)&&wt.setStyle({width:ea,height:Re})},Yt.truncateMinChar=2,Yt.lineOverflow="truncate",Q(Yt,ht,f);var pe=wt.getState("emphasis");Q(pe?pe.style:null,ht,f)}}function Q(pt,at,mt){var ht=pt?pt.text:null;if(!at&&mt.isLeafRoot&&ht!=null){var q=r.get("drillDownIcon",!0);pt.text=q?q+" "+ht:ht}}function tt(pt,at,mt,ht){var q=m!=null&&t[pt][m],st=n[pt];return q?(t[pt][m]=null,yt(st,q)):g||(q=new at,q instanceof er&&(q.z2=VG(mt,ht)),Dt(st,q)),e[pt][y]=q}function yt(pt,at){var mt=pt[y]={};at instanceof gg?(mt.oldX=at.x,mt.oldY=at.y):mt.oldShape=B({},at.shape)}function Dt(pt,at){var mt=pt[y]={},ht=o.parentNode,q=at instanceof rt;if(ht&&(!a||a.direction==="drillDown")){var st=0,Ft=0,wt=n.background[ht.getRawIndex()];!a&&wt&&wt.oldShape&&(st=wt.oldShape.width,Ft=wt.oldShape.height),q?(mt.oldX=0,mt.oldY=Ft):mt.oldShape={x:st,y:Ft,width:0,height:0}}mt.fadein=!q}}function VG(r,e){return r*EG+e}var Tl=A,zG=J,ph=-1,se=function(){function r(e){var t=e.mappingMethod,a=e.type,n=this.option=et(e);this.type=a,this.mappingMethod=t,this._normalizeData=HG[t];var i=r.visualHandlers[a];this.applyVisual=i.applyVisual,this.getColorMapper=i.getColorMapper,this._normalizedToVisual=i._normalizedToVisual[t],t==="piecewise"?(yg(n),GG(n)):t==="category"?n.categories?FG(n):yg(n,!0):(de(t!=="linear"||n.dataExtent),yg(n))}return r.prototype.mapValueToVisual=function(e){var t=this._normalizeData(e);return this._normalizedToVisual(t,e)},r.prototype.getNormalizer=function(){return Y(this._normalizeData,this)},r.listVisualTypes=function(){return St(r.visualHandlers)},r.isValidType=function(e){return r.visualHandlers.hasOwnProperty(e)},r.eachVisual=function(e,t,a){J(e)?A(e,t,a):t.call(a,e)},r.mapVisual=function(e,t,a){var n,i=z(e)?[]:J(e)?{}:(n=!0,null);return r.eachVisual(e,function(o,s){var l=t.call(a,o,s);n?i=l:i[s]=l}),i},r.retrieveVisuals=function(e){var t={},a;return e&&Tl(r.visualHandlers,function(n,i){e.hasOwnProperty(i)&&(t[i]=e[i],a=!0)}),a?t:null},r.prepareVisualTypes=function(e){if(z(e))e=e.slice();else if(zG(e)){var t=[];Tl(e,function(a,n){t.push(n)}),e=t}else return[];return e.sort(function(a,n){return n==="color"&&a!=="color"&&a.indexOf("color")===0?1:-1}),e},r.dependsOn=function(e,t){return t==="color"?!!(e&&e.indexOf(t)===0):e===t},r.findPieceIndex=function(e,t,a){for(var n,i=Infinity,o=0,s=t.length;o=0;i--)a[i]==null&&(delete t[e[i]],e.pop())}function yg(r,e){var t=r.visual,a=[];J(t)?Tl(t,function(i){a.push(i)}):t!=null&&a.push(t);var n={color:1,symbol:1};!e&&a.length===1&&!n.hasOwnProperty(r.type)&&(a[1]=a[0]),IC(r,a)}function dh(r){return{applyVisual:function(e,t,a){var n=this.mapValueToVisual(e);a("color",r(t("color"),n))},_normalizedToVisual:mg([0,1])}}function MC(r){var e=this.option.visual;return e[Math.round(Pt(r,[0,1],[0,e.length-1],!0))]||{}}function Cl(r){return function(e,t,a){a(r,this.mapValueToVisual(e))}}function Al(r){var e=this.option.visual;return e[this.option.loop&&r!==ph?r%e.length:r]}function ui(){return this.option.visual[0]}function mg(r){return{linear:function(e){return Pt(e,r,this.option.visual,!0)},category:Al,piecewise:function(e,t){var a=_g.call(this,t);return a==null&&(a=Pt(e,r,this.option.visual,!0)),a},fixed:ui}}function _g(r){var e=this.option,t=e.pieceList;if(e.hasSpecialVisual){var a=se.findPieceIndex(r,t),n=t[a];if(n&&n.visual)return n.visual[this.type]}}function IC(r,e){return r.visual=e,r.type==="color"&&(r.parsedVisual=G(e,function(t){var a=Ae(t);return a||[0,0,0,1]})),e}var HG={linear:function(r){return Pt(r,this.option.dataExtent,[0,1],!0)},piecewise:function(r){var e=this.option.pieceList,t=se.findPieceIndex(r,e,!0);if(t!=null)return Pt(t,[0,e.length-1],[0,1],!0)},category:function(r){var e=this.option.categories?this.option.categoryMap[r]:r;return e==null?ph:e},fixed:Zt};function gh(r,e,t){return r?e<=t:e=t.length||d===t[d.depth]){var y=$G(n,l,d,g,p,a);PC(d,y,t,a)}})}}}function YG(r,e,t){var a=B({},e),n=t.designatedVisualItemStyle;return A(["color","colorAlpha","colorSaturation"],function(i){n[i]=e[i];var o=r.get(i);n[i]=null,o!=null&&(a[i]=o)}),a}function RC(r){var e=Sg(r,"color");if(e){var t=Sg(r,"colorAlpha"),a=Sg(r,"colorSaturation");return a&&(e=Ai(e,null,null,a)),t&&(e=Jo(e,t)),e}}function XG(r,e){return e!=null?Ai(e,null,null,r):null}function Sg(r,e){var t=r[e];if(t!=null&&t!=="none")return t}function ZG(r,e,t,a,n,i){if(!(!i||!i.length)){var o=xg(e,"color")||n.color!=null&&n.color!=="none"&&(xg(e,"colorAlpha")||xg(e,"colorSaturation"));if(!!o){var s=e.get("visualMin"),l=e.get("visualMax"),u=t.dataExtent.slice();s!=null&&su[1]&&(u[1]=l);var f=e.get("colorMappingBy"),h={type:o.name,dataExtent:u,visual:o.range};h.type==="color"&&(f==="index"||f==="id")?(h.mappingMethod="category",h.loop=!0):h.mappingMethod="linear";var v=new se(h);return LC(v).drColorMappingBy=f,v}}}function xg(r,e){var t=r.get(e);return z(t)&&t.length?{name:e,range:t}:null}function $G(r,e,t,a,n,i){var o=B({},e);if(n){var s=n.type,l=s==="color"&&LC(n).drColorMappingBy,u=l==="index"?a:l==="id"?i.mapIdToIndex(t.getId()):t.getValue(r.get("visualDimension"));o[s]=n.mapValueToVisual(u)}return o}var Dl=Math.max,yh=Math.min,EC=ee,bg=A,kC=["itemStyle","borderWidth"],qG=["itemStyle","gapWidth"],KG=["upperLabel","show"],jG=["upperLabel","height"],QG={seriesType:"treemap",reset:function(r,e,t,a){var n=t.getWidth(),i=t.getHeight(),o=r.option,s=jt(r.getBoxLayoutParams(),{width:t.getWidth(),height:t.getHeight()}),l=o.size||[],u=H(EC(s.width,l[0]),n),f=H(EC(s.height,l[1]),i),h=a&&a.type,v=["treemapZoomToNode","treemapRootToNode"],c=xl(a,v,r),p=h==="treemapRender"||h==="treemapMove"?a.rootRect:null,d=r.getViewRoot(),g=mC(d);if(h!=="treemapMove"){var y=h==="treemapZoomToNode"?nF(r,c,d,u,f):p?[p.width,p.height]:[u,f],m=o.sort;m&&m!=="asc"&&m!=="desc"&&(m="desc");var _={squareRatio:o.squareRatio,sort:m,leafDepth:o.leafDepth};d.hostTree.clearLayouts();var S={x:0,y:0,width:y[0],height:y[1],area:y[0]*y[1]};d.setLayout(S),OC(d,_,!1,0),S=d.getLayout(),bg(g,function(x,w){var T=(g[w+1]||d).getValue();x.setLayout(B({dataExtent:[T,T],borderWidth:0,upperHeight:0},S))})}var b=r.getData().tree.root;b.setLayout(iF(s,p,c),!0),r.setLayoutInfo(s),BC(b,new ft(-s.x,-s.y,n,i),g,d,0)}};function OC(r,e,t,a){var n,i;if(!r.isRemoved()){var o=r.getLayout();n=o.width,i=o.height;var s=r.getModel(),l=s.get(kC),u=s.get(qG)/2,f=VC(s),h=Math.max(l,f),v=l-u,c=h-u;r.setLayout({borderWidth:l,upperHeight:h,upperLabelHeight:f},!0),n=Dl(n-2*v,0),i=Dl(i-v-c,0);var p=n*i,d=JG(r,s,p,e,t,a);if(!!d.length){var g={x:v,y:c,width:n,height:i},y=yh(n,i),m=Infinity,_=[];_.area=0;for(var S=0,b=d.length;S=0;l--){var u=n[a==="asc"?o-l-1:l].getValue();u/t*es[1]&&(s[1]=u)})),{sum:a,dataExtent:s}}function aF(r,e,t){for(var a=0,n=Infinity,i=0,o=void 0,s=r.length;ia&&(a=o));var l=r.area*r.area,u=e*e*t;return l?Dl(u*a/l,l/(u*n)):Infinity}function NC(r,e,t,a,n){var i=e===t.width?0:1,o=1-i,s=["x","y"],l=["width","height"],u=t[s[i]],f=e?r.area/e:0;(n||f>t[l[o]])&&(f=t[l[o]]);for(var h=0,v=r.length;hec&&(u=ec),i=s}ua&&(a=e);var i=a%2?a+2:a+3;n=[];for(var o=0;o0&&(b[0]=-b[0],b[1]=-b[1]);var w=S[0]<0?-1:1;if(i.__position!=="start"&&i.__position!=="end"){var T=-Math.atan2(S[1],S[0]);h[0].8?"left":v[0]<-.8?"right":"center",d=v[1]>.8?"top":v[1]<-.8?"bottom":"middle";break;case"start":i.x=-v[0]*y+f[0],i.y=-v[1]*m+f[1],p=v[0]>.8?"right":v[0]<-.8?"left":"center",d=v[1]>.8?"bottom":v[1]<-.8?"top":"middle";break;case"insideStartTop":case"insideStart":case"insideStartBottom":i.x=y*w+f[0],i.y=f[1]+C,p=S[0]<0?"right":"left",i.originX=-y*w,i.originY=-C;break;case"insideMiddleTop":case"insideMiddle":case"insideMiddleBottom":case"middle":i.x=x[0],i.y=x[1]+C,p="center",i.originY=-C;break;case"insideEndTop":case"insideEnd":case"insideEndBottom":i.x=-y*w+h[0],i.y=h[1]+C,p=S[0]>=0?"right":"left",i.originX=y*w,i.originY=-C;break}i.scaleX=i.scaleY=o,i.setStyle({verticalAlign:i.__verticalAlign||d,align:i.__align||p})}},e}(rt),kg=function(){function r(e){this.group=new rt,this._LineCtor=e||Eg}return r.prototype.updateData=function(e){var t=this;this._progressiveEls=null;var a=this,n=a.group,i=a._lineData;a._lineData=e,i||n.removeAll();var o=$C(e);e.diff(i).add(function(s){t._doAdd(e,s,o)}).update(function(s,l){t._doUpdate(i,e,l,s,o)}).remove(function(s){n.remove(i.getItemGraphicEl(s))}).execute()},r.prototype.updateLayout=function(){var e=this._lineData;!e||e.eachItemGraphicEl(function(t,a){t.updateLayout(e,a)},this)},r.prototype.incrementalPrepareUpdate=function(e){this._seriesScope=$C(e),this._lineData=null,this.group.removeAll()},r.prototype.incrementalUpdate=function(e,t){this._progressiveEls=[];function a(s){!s.isGroup&&!wF(s)&&(s.incremental=!0,s.ensureState("emphasis").hoverLayer=!0)}for(var n=e.start;n0}function $C(r){var e=r.hostModel,t=e.getModel("emphasis");return{lineStyle:e.getModel("lineStyle").getLineStyle(),emphasisLineStyle:t.getModel(["lineStyle"]).getLineStyle(),blurLineStyle:e.getModel(["blur","lineStyle"]).getLineStyle(),selectLineStyle:e.getModel(["select","lineStyle"]).getLineStyle(),emphasisDisabled:t.get("disabled"),blurScope:t.get("blurScope"),focus:t.get("focus"),labelStatesModels:ne(e)}}function qC(r){return isNaN(r[0])||isNaN(r[1])}function Og(r){return r&&!qC(r[0])&&!qC(r[1])}var Ng=[],Bg=[],Vg=[],So=ue,zg=Ma,KC=Math.abs;function jC(r,e,t){for(var a=r[0],n=r[1],i=r[2],o=Infinity,s,l=t*t,u=.1,f=.1;f<=.9;f+=.1){Ng[0]=So(a[0],n[0],i[0],f),Ng[1]=So(a[1],n[1],i[1],f);var h=KC(zg(Ng,e)-l);h=0?s=s+u:s=s-u:p>=0?s=s-u:s=s+u}return s}function Gg(r,e){var t=[],a=qo,n=[[],[],[]],i=[[],[]],o=[];e/=2,r.eachEdge(function(s,l){var u=s.getLayout(),f=s.getVisual("fromSymbol"),h=s.getVisual("toSymbol");u.__original||(u.__original=[kr(u[0]),kr(u[1])],u[2]&&u.__original.push(kr(u[2])));var v=u.__original;if(u[2]!=null){if(ge(n[0],v[0]),ge(n[1],v[2]),ge(n[2],v[1]),f&&f!=="none"){var c=Ll(s.node1),p=jC(n,v[0],c*e);a(n[0][0],n[1][0],n[2][0],p,t),n[0][0]=t[3],n[1][0]=t[4],a(n[0][1],n[1][1],n[2][1],p,t),n[0][1]=t[3],n[1][1]=t[4]}if(h&&h!=="none"){var c=Ll(s.node2),p=jC(n,v[1],c*e);a(n[0][0],n[1][0],n[2][0],p,t),n[1][0]=t[1],n[2][0]=t[2],a(n[0][1],n[1][1],n[2][1],p,t),n[1][1]=t[1],n[2][1]=t[2]}ge(u[0],n[0]),ge(u[1],n[2]),ge(u[2],n[1])}else{if(ge(i[0],v[0]),ge(i[1],v[1]),Da(o,i[1],i[0]),fn(o,o),f&&f!=="none"){var c=Ll(s.node1);jl(i[0],i[0],o,c*e)}if(h&&h!=="none"){var c=Ll(s.node2);jl(i[1],i[1],o,-c*e)}ge(u[0],i[0]),ge(u[1],i[1])}})}function QC(r){return r.type==="view"}var TF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t,a){var n=new fl,i=new kg,o=this.group;this._controller=new yl(a.getZr()),this._controllerHost={target:o},o.add(n.group),o.add(i.group),this._symbolDraw=n,this._lineDraw=i,this._firstRender=!0},e.prototype.render=function(t,a,n){var i=this,o=t.coordinateSystem;this._model=t;var s=this._symbolDraw,l=this._lineDraw,u=this.group;if(QC(o)){var f={x:o.x,y:o.y,scaleX:o.scaleX,scaleY:o.scaleY};this._firstRender?u.attr(f):At(u,f,t)}Gg(t.getGraph(),Il(t));var h=t.getData();s.updateData(h);var v=t.getEdgeData();l.updateData(v),this._updateNodeAndLinkScale(),this._updateController(t,a,n),clearTimeout(this._layoutTimeout);var c=t.forceLayout,p=t.get(["force","layoutAnimation"]);c&&this._startForceLayoutIteration(c,p);var d=t.get("layout");h.graph.eachNode(function(_){var S=_.dataIndex,b=_.getGraphicEl(),x=_.getModel();if(!!b){b.off("drag").off("dragend");var w=x.get("draggable");w&&b.on("drag",function(C){switch(d){case"force":c.warmUp(),!i._layouting&&i._startForceLayoutIteration(c,p),c.setFixed(S),h.setItemLayout(S,[b.x,b.y]);break;case"circular":h.setItemLayout(S,[b.x,b.y]),_.setLayout({fixed:!0},!0),Mg(t,"symbolSize",_,[C.offsetX,C.offsetY]),i.updateLayout(t);break;case"none":default:h.setItemLayout(S,[b.x,b.y]),Ag(t.getGraph(),t),i.updateLayout(t);break}}).on("dragend",function(){c&&c.setUnfixed(S)}),b.setDraggable(w,!!x.get("cursor"));var T=x.get(["emphasis","focus"]);T==="adjacency"&&(nt(b).focus=_.getAdjacentDataIndices())}}),h.graph.eachEdge(function(_){var S=_.getGraphicEl(),b=_.getModel().get(["emphasis","focus"]);!S||b==="adjacency"&&(nt(S).focus={edge:[_.dataIndex],node:[_.node1.dataIndex,_.node2.dataIndex]})});var g=t.get("layout")==="circular"&&t.get(["circular","rotateLabel"]),y=h.getLayout("cx"),m=h.getLayout("cy");h.graph.eachNode(function(_){WC(_,g,y,m)}),this._firstRender=!1},e.prototype.dispose=function(){this._controller&&this._controller.dispose(),this._controllerHost=null},e.prototype._startForceLayoutIteration=function(t,a){var n=this;(function i(){t.step(function(o){n.updateLayout(n._model),(n._layouting=!o)&&(a?n._layoutTimeout=setTimeout(i,16):i())})})()},e.prototype._updateController=function(t,a,n){var i=this,o=this._controller,s=this._controllerHost,l=this.group;if(o.setPointerChecker(function(u,f,h){var v=l.getBoundingRect();return v.applyTransform(l.transform),v.contain(f,h)&&!sh(u,n,t)}),!QC(t.coordinateSystem)){o.disable();return}o.enable(t.get("roam")),s.zoomLimit=t.get("scaleLimit"),s.zoom=t.coordinateSystem.getZoom(),o.off("pan").off("zoom").on("pan",function(u){eg(s,u.dx,u.dy),n.dispatchAction({seriesId:t.id,type:"graphRoam",dx:u.dx,dy:u.dy})}).on("zoom",function(u){rg(s,u.scale,u.originX,u.originY),n.dispatchAction({seriesId:t.id,type:"graphRoam",zoom:u.scale,originX:u.originX,originY:u.originY}),i._updateNodeAndLinkScale(),Gg(t.getGraph(),Il(t)),i._lineDraw.updateLayout(),n.updateLabelLayout()})},e.prototype._updateNodeAndLinkScale=function(){var t=this._model,a=t.getData(),n=Il(t);a.eachItemGraphicEl(function(i,o){i&&i.setSymbolScale(n)})},e.prototype.updateLayout=function(t){Gg(t.getGraph(),Il(t)),this._symbolDraw.updateLayout(),this._lineDraw.updateLayout()},e.prototype.remove=function(t,a){this._symbolDraw&&this._symbolDraw.remove(),this._lineDraw&&this._lineDraw.remove()},e.type="graph",e}(Rt);function xo(r){return"_EC_"+r}var CF=function(){function r(e){this.type="graph",this.nodes=[],this.edges=[],this._nodesMap={},this._edgesMap={},this._directed=e||!1}return r.prototype.isDirected=function(){return this._directed},r.prototype.addNode=function(e,t){e=e==null?""+t:""+e;var a=this._nodesMap;if(!a[xo(e)]){var n=new fi(e,t);return n.hostGraph=this,this.nodes.push(n),a[xo(e)]=n,n}},r.prototype.getNodeByIndex=function(e){var t=this.data.getRawIndex(e);return this.nodes[t]},r.prototype.getNodeById=function(e){return this._nodesMap[xo(e)]},r.prototype.addEdge=function(e,t,a){var n=this._nodesMap,i=this._edgesMap;if(Tt(e)&&(e=this.nodes[e]),Tt(t)&&(t=this.nodes[t]),e instanceof fi||(e=n[xo(e)]),t instanceof fi||(t=n[xo(t)]),!(!e||!t)){var o=e.id+"-"+t.id,s=new JC(e,t,a);return s.hostGraph=this,this._directed&&(e.outEdges.push(s),t.inEdges.push(s)),e.edges.push(s),e!==t&&t.edges.push(s),this.edges.push(s),i[o]=s,s}},r.prototype.getEdgeByIndex=function(e){var t=this.edgeData.getRawIndex(e);return this.edges[t]},r.prototype.getEdge=function(e,t){e instanceof fi&&(e=e.id),t instanceof fi&&(t=t.id);var a=this._edgesMap;return this._directed?a[e+"-"+t]:a[e+"-"+t]||a[t+"-"+e]},r.prototype.eachNode=function(e,t){for(var a=this.nodes,n=a.length,i=0;i=0&&e.call(t,a[i],i)},r.prototype.eachEdge=function(e,t){for(var a=this.edges,n=a.length,i=0;i=0&&a[i].node1.dataIndex>=0&&a[i].node2.dataIndex>=0&&e.call(t,a[i],i)},r.prototype.breadthFirstTraverse=function(e,t,a,n){if(t instanceof fi||(t=this._nodesMap[xo(t)]),!!t){for(var i=a==="out"?"outEdges":a==="in"?"inEdges":"edges",o=0;o=0&&l.node2.dataIndex>=0});for(var i=0,o=n.length;i=0&&this[r][e].setItemVisual(this.dataIndex,t,a)},getVisual:function(t){return this[r][e].getItemVisual(this.dataIndex,t)},setLayout:function(t,a){this.dataIndex>=0&&this[r][e].setItemLayout(this.dataIndex,t,a)},getLayout:function(){return this[r][e].getItemLayout(this.dataIndex)},getGraphicEl:function(){return this[r][e].getItemGraphicEl(this.dataIndex)},getRawIndex:function(){return this[r][e].getRawIndex(this.dataIndex)}}}Xt(fi,tA("hostGraph","data")),Xt(JC,tA("hostGraph","edgeData"));function eA(r,e,t,a,n){for(var i=new CF(a),o=0;o "+v)),u++)}var c=t.get("coordinateSystem"),p;if(c==="cartesian2d"||c==="polar")p=Xr(r,t);else{var d=Ji.get(c),g=d?d.dimensions||[]:[];vt(g,"value")<0&&g.concat(["value"]);var y=uo(r,{coordDimensions:g,encodeDefine:t.getEncode()}).dimensions;p=new Te(y,t),p.initData(r)}var m=new Te(["value"],t);return m.initData(l,s),n&&n(p,m),gC({mainData:p,struct:i,structAttr:"graph",datas:{node:p,edge:m},datasAttr:{node:"data",edge:"edgeData"}}),i.update(),i}var AF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.hasSymbolVisual=!0,t}return e.prototype.init=function(t){r.prototype.init.apply(this,arguments);var a=this;function n(){return a._categoriesData}this.legendVisualProvider=new pl(n,n),this.fillDataTextStyle(t.edges||t.links),this._updateCategoriesData()},e.prototype.mergeOption=function(t){r.prototype.mergeOption.apply(this,arguments),this.fillDataTextStyle(t.edges||t.links),this._updateCategoriesData()},e.prototype.mergeDefaultAndTheme=function(t){r.prototype.mergeDefaultAndTheme.apply(this,arguments),Sn(t,"edgeLabel",["show"])},e.prototype.getInitialData=function(t,a){var n=t.edges||t.links||[],i=t.data||t.nodes||[],o=this;if(i&&n){vF(this);var s=eA(i,n,this,!0,l);return A(s.edges,function(u){cF(u.node1,u.node2,this,u.dataIndex)},this),s.data}function l(u,f){u.wrapMethod("getItemModel",function(p){var d=o._categoriesModels,g=p.getShallow("category"),y=d[g];return y&&(y.parentModel=p.parentModel,p.parentModel=y),p});var h=Mt.prototype.getModel;function v(p,d){var g=h.call(this,p,d);return g.resolveParentPath=c,g}f.wrapMethod("getItemModel",function(p){return p.resolveParentPath=c,p.getModel=v,p});function c(p){if(p&&(p[0]==="label"||p[1]==="label")){var d=p.slice();return p[0]==="label"?d[0]="edgeLabel":p[1]==="label"&&(d[1]="edgeLabel"),d}return p}}},e.prototype.getGraph=function(){return this.getData().graph},e.prototype.getEdgeData=function(){return this.getGraph().edgeData},e.prototype.getCategoriesData=function(){return this._categoriesData},e.prototype.formatTooltip=function(t,a,n){if(n==="edge"){var i=this.getData(),o=this.getDataParams(t,n),s=i.graph.getEdgeByIndex(t),l=i.getName(s.node1.dataIndex),u=i.getName(s.node2.dataIndex),f=[];return l!=null&&f.push(l),u!=null&&f.push(u),ie("nameValue",{name:f.join(" > "),value:o.value,noValue:o.value==null})}var h=XS({series:this,dataIndex:t,multipleSeries:a});return h},e.prototype._updateCategoriesData=function(){var t=G(this.option.categories||[],function(n){return n.value!=null?n:B({value:0},n)}),a=new Te(["value"],this);a.initData(t),this._categoriesData=a,this._categoriesModels=a.mapArray(function(n){return a.getItemModel(n)})},e.prototype.setZoom=function(t){this.option.zoom=t},e.prototype.setCenter=function(t){this.option.center=t},e.prototype.isAnimationEnabled=function(){return r.prototype.isAnimationEnabled.call(this)&&!(this.get("layout")==="force"&&this.get(["force","layoutAnimation"]))},e.type="series.graph",e.dependencies=["grid","polar","geo","singleAxis","calendar"],e.defaultOption={z:2,coordinateSystem:"view",legendHoverLink:!0,layout:null,circular:{rotateLabel:!1},force:{initLayout:null,repulsion:[0,50],gravity:.1,friction:.6,edgeLength:30,layoutAnimation:!0},left:"center",top:"center",symbol:"circle",symbolSize:10,edgeSymbol:["none","none"],edgeSymbolSize:10,edgeLabel:{position:"middle",distance:5},draggable:!1,roam:!1,center:null,zoom:1,nodeScaleRatio:.6,label:{show:!1,formatter:"{b}"},itemStyle:{},lineStyle:{color:"#aaa",width:1,opacity:.5},emphasis:{scale:!0,label:{show:!0}},select:{itemStyle:{borderColor:"#212121"}}},e}(kt),DF={type:"graphRoam",event:"graphRoam",update:"none"};function MF(r){r.registerChartView(TF),r.registerSeriesModel(AF),r.registerProcessor(sF),r.registerVisual(lF),r.registerVisual(uF),r.registerLayout(pF),r.registerLayout(r.PRIORITY.VISUAL.POST_CHART_LAYOUT,gF),r.registerLayout(mF),r.registerCoordinateSystem("graphView",{dimensions:_l.dimensions,create:SF}),r.registerAction({type:"focusNodeAdjacency",event:"focusNodeAdjacency",update:"series:focusNodeAdjacency"},Zt),r.registerAction({type:"unfocusNodeAdjacency",event:"unfocusNodeAdjacency",update:"series:unfocusNodeAdjacency"},Zt),r.registerAction(DF,function(e,t,a){t.eachComponent({mainType:"series",query:e},function(n){var i=n.coordinateSystem,o=lg(i,e,void 0,a);n.setCenter&&n.setCenter(o.center),n.setZoom&&n.setZoom(o.zoom)})})}var IF=function(){function r(){this.angle=0,this.width=10,this.r=10,this.x=0,this.y=0}return r}(),LF=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="pointer",a}return e.prototype.getDefaultShape=function(){return new IF},e.prototype.buildPath=function(t,a){var n=Math.cos,i=Math.sin,o=a.r,s=a.width,l=a.angle,u=a.x-n(l)*s*(s>=o/3?1:2),f=a.y-i(l)*s*(s>=o/3?1:2);l=a.angle-Math.PI/2,t.moveTo(u,f),t.lineTo(a.x+n(l)*s,a.y+i(l)*s),t.lineTo(a.x+n(a.angle)*o,a.y+i(a.angle)*o),t.lineTo(a.x-n(l)*s,a.y-i(l)*s),t.lineTo(u,f)},e}(dt);function PF(r,e){var t=r.get("center"),a=e.getWidth(),n=e.getHeight(),i=Math.min(a,n),o=H(t[0],e.getWidth()),s=H(t[1],e.getHeight()),l=H(r.get("radius"),i/2);return{cx:o,cy:s,r:l}}function Sh(r,e){var t=r==null?"":r+"";return e&&(U(e)?t=e.replace("{value}",t):K(e)&&(t=e(r))),t}var RF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){this.group.removeAll();var i=t.get(["axisLine","lineStyle","color"]),o=PF(t,n);this._renderMain(t,a,n,i,o),this._data=t.getData()},e.prototype.dispose=function(){},e.prototype._renderMain=function(t,a,n,i,o){var s=this.group,l=t.get("clockwise"),u=-t.get("startAngle")/180*Math.PI,f=-t.get("endAngle")/180*Math.PI,h=t.getModel("axisLine"),v=h.get("roundCap"),c=v?th:me,p=h.get("show"),d=h.getModel("lineStyle"),g=d.get("width"),y=[u,f];c_(y,!l),u=y[0],f=y[1];for(var m=f-u,_=u,S=[],b=0;p&&b=C&&(D===0?0:i[D-1][0])Math.PI/2&&(tt+=Math.PI)):Q==="tangential"?tt=-T-Math.PI/2:Tt(Q)&&(tt=Q*Math.PI/180),tt===0?h.add(new bt({style:Nt(_,{text:V,x:W,y:Z,verticalAlign:R<-.8?"top":R>.8?"bottom":"middle",align:P<-.4?"left":P>.4?"right":"center"},{inheritColor:F}),silent:!0})):h.add(new bt({style:Nt(_,{text:V,x:W,y:Z,verticalAlign:"middle",align:"center"},{inheritColor:F}),silent:!0,originX:W,originY:Z,rotation:tt}))}if(m.get("show")&&E!==S){var N=m.get("distance");N=N?N+f:f;for(var yt=0;yt<=b;yt++){P=Math.cos(T),R=Math.sin(T);var Dt=new te({shape:{x1:P*(p-N)+v,y1:R*(p-N)+c,x2:P*(p-w-N)+v,y2:R*(p-w-N)+c},silent:!0,style:I});I.stroke==="auto"&&Dt.setStyle({stroke:i((E+yt/b)/S)}),h.add(Dt),T+=D}T-=D}else T+=C}},e.prototype._renderPointer=function(t,a,n,i,o,s,l,u,f){var h=this.group,v=this._data,c=this._progressEls,p=[],d=t.get(["pointer","show"]),g=t.getModel("progress"),y=g.get("show"),m=t.getData(),_=m.mapDimension("value"),S=+t.get("min"),b=+t.get("max"),x=[S,b],w=[s,l];function T(D,M){var I=m.getItemModel(D),L=I.getModel("pointer"),P=H(L.get("width"),o.r),R=H(L.get("length"),o.r),E=t.get(["pointer","icon"]),N=L.get("offsetCenter"),k=H(N[0],o.r),V=H(N[1],o.r),F=L.get("keepAspect"),W;return E?W=$t(E,k-P/2,V-R,P,R,null,F):W=new LF({shape:{angle:-Math.PI/2,width:P,r:R,x:k,y:V}}),W.rotation=-(M+Math.PI/2),W.x=o.cx,W.y=o.cy,W}function C(D,M){var I=g.get("roundCap"),L=I?th:me,P=g.get("overlap"),R=P?g.get("width"):f/m.count(),E=P?o.r-R:o.r-(D+1)*R,N=P?o.r:o.r-D*R,k=new L({shape:{startAngle:s,endAngle:M,cx:o.cx,cy:o.cy,clockwise:u,r0:E,r:N}});return P&&(k.z2=b-m.get(_,D)%b),k}(y||d)&&(m.diff(v).add(function(D){var M=m.get(_,D);if(d){var I=T(D,s);Gt(I,{rotation:-((isNaN(+M)?w[0]:Pt(M,x,w,!0))+Math.PI/2)},t),h.add(I),m.setItemGraphicEl(D,I)}if(y){var L=C(D,s),P=g.get("clip");Gt(L,{shape:{endAngle:Pt(M,x,w,P)}},t),h.add(L),Ac(t.seriesIndex,m.dataType,D,L),p[D]=L}}).update(function(D,M){var I=m.get(_,D);if(d){var L=v.getItemGraphicEl(M),P=L?L.rotation:s,R=T(D,P);R.rotation=P,At(R,{rotation:-((isNaN(+I)?w[0]:Pt(I,x,w,!0))+Math.PI/2)},t),h.add(R),m.setItemGraphicEl(D,R)}if(y){var E=c[M],N=E?E.shape.endAngle:s,k=C(D,N),V=g.get("clip");At(k,{shape:{endAngle:Pt(I,x,w,V)}},t),h.add(k),Ac(t.seriesIndex,m.dataType,D,k),p[D]=k}}).execute(),m.each(function(D){var M=m.getItemModel(D),I=M.getModel("emphasis"),L=I.get("focus"),P=I.get("blurScope"),R=I.get("disabled");if(d){var E=m.getItemGraphicEl(D),N=m.getItemVisual(D,"style"),k=N.fill;if(E instanceof ae){var V=E.style;E.useStyle(B({image:V.image,x:V.x,y:V.y,width:V.width,height:V.height},N))}else E.useStyle(N),E.type!=="pointer"&&E.setColor(k);E.setStyle(M.getModel(["pointer","itemStyle"]).getItemStyle()),E.style.fill==="auto"&&E.setStyle("fill",i(Pt(m.get(_,D),x,[0,1],!0))),E.z2EmphasisLift=0,he(E,M),Ut(E,L,P,R)}if(y){var F=p[D];F.useStyle(m.getItemVisual(D,"style")),F.setStyle(M.getModel(["progress","itemStyle"]).getItemStyle()),F.z2EmphasisLift=0,he(F,M),Ut(F,L,P,R)}}),this._progressEls=p)},e.prototype._renderAnchor=function(t,a){var n=t.getModel("anchor"),i=n.get("show");if(i){var o=n.get("size"),s=n.get("icon"),l=n.get("offsetCenter"),u=n.get("keepAspect"),f=$t(s,a.cx-o/2+H(l[0],a.r),a.cy-o/2+H(l[1],a.r),o,o,null,u);f.z2=n.get("showAbove")?1:0,f.setStyle(n.getModel("itemStyle").getItemStyle()),this.group.add(f)}},e.prototype._renderTitleAndDetail=function(t,a,n,i,o){var s=this,l=t.getData(),u=l.mapDimension("value"),f=+t.get("min"),h=+t.get("max"),v=new rt,c=[],p=[],d=t.isAnimationEnabled(),g=t.get(["pointer","showAbove"]);l.diff(this._data).add(function(y){c[y]=new bt({silent:!0}),p[y]=new bt({silent:!0})}).update(function(y,m){c[y]=s._titleEls[m],p[y]=s._detailEls[m]}).execute(),l.each(function(y){var m=l.getItemModel(y),_=l.get(u,y),S=new rt,b=i(Pt(_,[f,h],[0,1],!0)),x=m.getModel("title");if(x.get("show")){var w=x.get("offsetCenter"),T=o.cx+H(w[0],o.r),C=o.cy+H(w[1],o.r),D=c[y];D.attr({z2:g?0:2,style:Nt(x,{x:T,y:C,text:l.getName(y),align:"center",verticalAlign:"middle"},{inheritColor:b})}),S.add(D)}var M=m.getModel("detail");if(M.get("show")){var I=M.get("offsetCenter"),L=o.cx+H(I[0],o.r),P=o.cy+H(I[1],o.r),R=H(M.get("width"),o.r),E=H(M.get("height"),o.r),N=t.get(["progress","show"])?l.getItemVisual(y,"style").fill:b,D=p[y],k=M.get("formatter");D.attr({z2:g?0:2,style:Nt(M,{x:L,y:P,text:Sh(_,k),width:isNaN(R)?null:R,height:isNaN(E)?null:E,align:"center",verticalAlign:"middle"},{inheritColor:N})}),C1(D,{normal:M},_,function(F){return Sh(F,k)}),d&&A1(D,y,l,t,{getFormattedLabel:function(F,W,Z,Q,tt,yt){return Sh(yt?yt.interpolatedValue:_,k)}}),S.add(D)}v.add(S)}),this.group.add(v),this._titleEls=c,this._detailEls=p},e.type="gauge",e}(Rt),EF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.visualStyleAccessPath="itemStyle",t}return e.prototype.getInitialData=function(t,a){return go(this,["value"])},e.type="series.gauge",e.defaultOption={z:2,colorBy:"data",center:["50%","50%"],legendHoverLink:!0,radius:"75%",startAngle:225,endAngle:-45,clockwise:!0,min:0,max:100,splitNumber:10,axisLine:{show:!0,roundCap:!1,lineStyle:{color:[[1,"#E6EBF8"]],width:10}},progress:{show:!1,overlap:!0,width:10,roundCap:!1,clip:!0},splitLine:{show:!0,length:10,distance:10,lineStyle:{color:"#63677A",width:3,type:"solid"}},axisTick:{show:!0,splitNumber:5,length:6,distance:10,lineStyle:{color:"#63677A",width:1,type:"solid"}},axisLabel:{show:!0,distance:15,color:"#464646",fontSize:12,rotate:0},pointer:{icon:null,offsetCenter:[0,0],show:!0,showAbove:!0,length:"60%",width:6,keepAspect:!1},anchor:{show:!1,showAbove:!1,size:6,icon:"circle",offsetCenter:[0,0],keepAspect:!1,itemStyle:{color:"#fff",borderWidth:0,borderColor:"#5470c6"}},title:{show:!0,offsetCenter:[0,"20%"],color:"#464646",fontSize:16,valueAnimation:!1},detail:{show:!0,backgroundColor:"rgba(0,0,0,0)",borderWidth:0,borderColor:"#ccc",width:100,height:null,padding:[5,10],offsetCenter:[0,"40%"],color:"#464646",fontSize:30,fontWeight:"bold",lineHeight:30,valueAnimation:!1}},e}(kt);function kF(r){r.registerChartView(RF),r.registerSeriesModel(EF)}var OF=["itemStyle","opacity"],NF=function(r){O(e,r);function e(t,a){var n=r.call(this)||this,i=n,o=new Se,s=new bt;return i.setTextContent(s),n.setTextGuideLine(o),n.updateData(t,a,!0),n}return e.prototype.updateData=function(t,a,n){var i=this,o=t.hostModel,s=t.getItemModel(a),l=t.getItemLayout(a),u=s.getModel("emphasis"),f=s.get(OF);f=f==null?1:f,n||Cr(i),i.useStyle(t.getItemVisual(a,"style")),i.style.lineJoin="round",n?(i.setShape({points:l.points}),i.style.opacity=0,Gt(i,{style:{opacity:f}},o,a)):At(i,{style:{opacity:f},shape:{points:l.points}},o,a),he(i,s),this._updateLabel(t,a),Ut(this,u.get("focus"),u.get("blurScope"),u.get("disabled"))},e.prototype._updateLabel=function(t,a){var n=this,i=this.getTextGuideLine(),o=n.getTextContent(),s=t.hostModel,l=t.getItemModel(a),u=t.getItemLayout(a),f=u.label,h=t.getItemVisual(a,"style"),v=h.fill;ve(o,ne(l),{labelFetcher:t.hostModel,labelDataIndex:a,defaultOpacity:h.opacity,defaultText:t.getName(a)},{normal:{align:f.textAlign,verticalAlign:f.verticalAlign}}),n.setTextConfig({local:!0,inside:!!f.inside,insideStroke:v,outsideFill:v});var c=f.linePoints;i.setShape({points:c}),n.textGuideLineConfig={anchor:c?new ut(c[0][0],c[0][1]):null},At(o,{style:{x:f.x,y:f.y}},s,a),o.attr({rotation:f.rotation,originX:f.x,originY:f.y,z2:10}),bd(n,wd(l),{stroke:v})},e}(_e),BF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.ignoreLabelLineUpdate=!0,t}return e.prototype.render=function(t,a,n){var i=t.getData(),o=this._data,s=this.group;i.diff(o).add(function(l){var u=new NF(i,l);i.setItemGraphicEl(l,u),s.add(u)}).update(function(l,u){var f=o.getItemGraphicEl(u);f.updateData(i,l),s.add(f),i.setItemGraphicEl(l,f)}).remove(function(l){var u=o.getItemGraphicEl(l);Ts(u,t,l)}).execute(),this._data=i},e.prototype.remove=function(){this.group.removeAll(),this._data=null},e.prototype.dispose=function(){},e.type="funnel",e}(Rt),VF=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t){r.prototype.init.apply(this,arguments),this.legendVisualProvider=new pl(Y(this.getData,this),Y(this.getRawData,this)),this._defaultLabelLine(t)},e.prototype.getInitialData=function(t,a){return go(this,{coordDimensions:["value"],encodeDefaulter:it(hp,this)})},e.prototype._defaultLabelLine=function(t){Sn(t,"labelLine",["show"]);var a=t.labelLine,n=t.emphasis.labelLine;a.show=a.show&&t.label.show,n.show=n.show&&t.emphasis.label.show},e.prototype.getDataParams=function(t){var a=this.getData(),n=r.prototype.getDataParams.call(this,t),i=a.mapDimension("value"),o=a.getSum(i);return n.percent=o?+(a.get(i,t)/o*100).toFixed(2):0,n.$vars.push("percent"),n},e.type="series.funnel",e.defaultOption={z:2,legendHoverLink:!0,colorBy:"data",left:80,top:60,right:80,bottom:60,minSize:"0%",maxSize:"100%",sort:"descending",orient:"vertical",gap:0,funnelAlign:"center",label:{show:!0,position:"outer"},labelLine:{show:!0,length:20,lineStyle:{width:1}},itemStyle:{borderColor:"#fff",borderWidth:1},emphasis:{label:{show:!0}},select:{itemStyle:{borderColor:"#212121"}}},e}(kt);function zF(r,e){return jt(r.getBoxLayoutParams(),{width:e.getWidth(),height:e.getHeight()})}function GF(r,e){for(var t=r.mapDimension("value"),a=r.mapArray(t,function(l){return l}),n=[],i=e==="ascending",o=0,s=r.count();or3)return;var n=this._model.coordinateSystem.getSlidedAxisExpandWindow([r.offsetX,r.offsetY]);n.behavior!=="none"&&this._dispatchExpand({axisExpandWindow:n.axisExpandWindow})}this._mouseDownPoint=null},mousemove:function(r){if(!(this._mouseDownPoint||!Hg(this,"mousemove"))){var e=this._model,t=e.coordinateSystem.getSlidedAxisExpandWindow([r.offsetX,r.offsetY]),a=t.behavior;a==="jump"&&this._throttledDispatchExpand.debounceNextCall(e.get("axisExpandDebounce")),this._throttledDispatchExpand(a==="none"?null:{axisExpandWindow:t.axisExpandWindow,animation:a==="jump"?null:{duration:0}})}}};function Hg(r,e){var t=r._model;return t.get("axisExpandable")&&t.get("axisExpandTriggerOn")===e}var i3=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(){r.prototype.init.apply(this,arguments),this.mergeOption({})},e.prototype.mergeOption=function(t){var a=this.option;t&&ot(a,t,!0),this._initDimensions()},e.prototype.contains=function(t,a){var n=t.get("parallelIndex");return n!=null&&a.getComponent("parallel",n)===this},e.prototype.setAxisExpand=function(t){A(["axisExpandable","axisExpandCenter","axisExpandCount","axisExpandWidth","axisExpandWindow"],function(a){t.hasOwnProperty(a)&&(this.option[a]=t[a])},this)},e.prototype._initDimensions=function(){var t=this.dimensions=[],a=this.parallelAxisIndex=[],n=Lt(this.ecModel.queryComponents({mainType:"parallelAxis"}),function(i){return(i.get("parallelIndex")||0)===this.componentIndex},this);A(n,function(i){t.push("dim"+i.get("dim")),a.push(i.componentIndex)})},e.type="parallel",e.dependencies=["parallelAxis"],e.layoutMode="box",e.defaultOption={z:0,left:80,top:60,right:80,bottom:60,layout:"horizontal",axisExpandable:!1,axisExpandCenter:null,axisExpandCount:0,axisExpandWidth:50,axisExpandRate:17,axisExpandDebounce:50,axisExpandSlideTriggerArea:[-.15,.05,.4],axisExpandTriggerOn:"click",parallelAxisDefault:null},e}(gt),o3=function(r){O(e,r);function e(t,a,n,i,o){var s=r.call(this,t,a,n)||this;return s.type=i||"value",s.axisIndex=o,s}return e.prototype.isHorizontal=function(){return this.coordinateSystem.getModel().get("layout")!=="horizontal"},e}(fr);function hi(r,e,t,a,n,i){r=r||0;var o=t[1]-t[0];if(n!=null&&(n=bo(n,[0,o])),i!=null&&(i=Math.max(i,n!=null?n:0)),a==="all"){var s=Math.abs(e[1]-e[0]);s=bo(s,[0,o]),n=i=bo(s,[n,i]),a=0}e[0]=bo(e[0],t),e[1]=bo(e[1],t);var l=Wg(e,a);e[a]+=r;var u=n||0,f=t.slice();l.sign<0?f[0]+=u:f[1]-=u,e[a]=bo(e[a],f);var h;return h=Wg(e,a),n!=null&&(h.sign!==l.sign||h.spani&&(e[1-a]=e[a]+h.sign*i),e}function Wg(r,e){var t=r[e]-r[1-e];return{span:Math.abs(t),sign:t>0?-1:t<0?1:e?-1:1}}function bo(r,e){return Math.min(e[1]!=null?e[1]:Infinity,Math.max(e[0]!=null?e[0]:-Infinity,r))}var Ug=A,iA=Math.min,oA=Math.max,sA=Math.floor,s3=Math.ceil,lA=Wt,l3=Math.PI,u3=function(){function r(e,t,a){this.type="parallel",this._axesMap=$(),this._axesLayout={},this.dimensions=e.dimensions,this._model=e,this._init(e,t,a)}return r.prototype._init=function(e,t,a){var n=e.dimensions,i=e.parallelAxisIndex;Ug(n,function(o,s){var l=i[s],u=t.getComponent("parallelAxis",l),f=this._axesMap.set(o,new o3(o,el(u),[0,0],u.get("type"),l)),h=f.type==="category";f.onBand=h&&u.get("boundaryGap"),f.inverse=u.get("inverse"),u.axis=f,f.model=u,f.coordinateSystem=u.coordinateSystem=this},this)},r.prototype.update=function(e,t){this._updateAxesFromSeries(this._model,e)},r.prototype.containPoint=function(e){var t=this._makeLayoutInfo(),a=t.axisBase,n=t.layoutBase,i=t.pixelDimIndex,o=e[1-i],s=e[i];return o>=a&&o<=a+t.axisLength&&s>=n&&s<=n+t.layoutLength},r.prototype.getModel=function(){return this._model},r.prototype._updateAxesFromSeries=function(e,t){t.eachSeries(function(a){if(!!e.contains(a,t)){var n=a.getData();Ug(this.dimensions,function(i){var o=this._axesMap.get(i);o.scale.unionExtentFromData(n,n.mapDimension(i)),Kn(o.scale,o.model)},this)}},this)},r.prototype.resize=function(e,t){this._rect=jt(e.getBoxLayoutParams(),{width:t.getWidth(),height:t.getHeight()}),this._layoutAxes()},r.prototype.getRect=function(){return this._rect},r.prototype._makeLayoutInfo=function(){var e=this._model,t=this._rect,a=["x","y"],n=["width","height"],i=e.get("layout"),o=i==="horizontal"?0:1,s=t[n[o]],l=[0,s],u=this.dimensions.length,f=xh(e.get("axisExpandWidth"),l),h=xh(e.get("axisExpandCount")||0,[0,u]),v=e.get("axisExpandable")&&u>3&&u>h&&h>1&&f>0&&s>0,c=e.get("axisExpandWindow"),p;if(c)p=xh(c[1]-c[0],l),c[1]=c[0]+p;else{p=xh(f*(h-1),l);var d=e.get("axisExpandCenter")||sA(u/2);c=[f*d-p/2],c[1]=c[0]+p}var g=(s-p)/(u-h);g<3&&(g=0);var y=[sA(lA(c[0]/f,1))+1,s3(lA(c[1]/f,1))-1],m=g/f*c[0];return{layout:i,pixelDimIndex:o,layoutBase:t[a[o]],layoutLength:s,axisBase:t[a[1-o]],axisLength:t[n[1-o]],axisExpandable:v,axisExpandWidth:f,axisCollapseWidth:g,axisExpandWindow:c,axisCount:u,winInnerIndices:y,axisExpandWindow0Pos:m}},r.prototype._layoutAxes=function(){var e=this._rect,t=this._axesMap,a=this.dimensions,n=this._makeLayoutInfo(),i=n.layout;t.each(function(o){var s=[0,n.axisLength],l=o.inverse?1:0;o.setExtent(s[l],s[1-l])}),Ug(a,function(o,s){var l=(n.axisExpandable?h3:f3)(s,n),u={horizontal:{x:l.position,y:n.axisLength},vertical:{x:0,y:l.position}},f={horizontal:l3/2,vertical:0},h=[u[i].x+e.x,u[i].y+e.y],v=f[i],c=Ge();Ia(c,c,v),mr(c,c,h),this._axesLayout[o]={position:h,rotation:v,transform:c,axisNameAvailableWidth:l.axisNameAvailableWidth,axisLabelShow:l.axisLabelShow,nameTruncateMaxWidth:l.nameTruncateMaxWidth,tickDirection:1,labelDirection:1}},this)},r.prototype.getAxis=function(e){return this._axesMap.get(e)},r.prototype.dataToPoint=function(e,t){return this.axisCoordToPoint(this._axesMap.get(t).dataToCoord(e),t)},r.prototype.eachActiveState=function(e,t,a,n){a==null&&(a=0),n==null&&(n=e.count());var i=this._axesMap,o=this.dimensions,s=[],l=[];A(o,function(g){s.push(e.mapDimension(g)),l.push(i.get(g).model)});for(var u=this.hasAxisBrushed(),f=a;fi*(1-h[0])?(u="jump",l=s-i*(1-h[2])):(l=s-i*h[1])>=0&&(l=s-i*(1-h[1]))<=0&&(l=0),l*=t.axisExpandWidth/f,l?hi(l,n,o,"all"):u="none";else{var c=n[1]-n[0],p=o[1]*s/c;n=[oA(0,p-c/2)],n[1]=iA(o[1],n[0]+c),n[0]=n[1]-c}return{axisExpandWindow:n,behavior:u}},r}();function xh(r,e){return iA(oA(r,e[0]),e[1])}function f3(r,e){var t=e.layoutLength/(e.axisCount-1);return{position:t*r,axisNameAvailableWidth:t,axisLabelShow:!0}}function h3(r,e){var t=e.layoutLength,a=e.axisExpandWidth,n=e.axisCount,i=e.axisCollapseWidth,o=e.winInnerIndices,s,l=i,u=!1,f;return r=0;n--)We(a[n])},e.prototype.getActiveState=function(t){var a=this.activeIntervals;if(!a.length)return"normal";if(t==null||isNaN(+t))return"inactive";if(a.length===1){var n=a[0];if(n[0]<=t&&t<=n[1])return"active"}else for(var i=0,o=a.length;ig3}function gA(r){var e=r.length-1;return e<0&&(e=0),[r[0],r[e]]}function yA(r,e,t,a){var n=new rt;return n.add(new xt({name:"main",style:Qg(t),silent:!0,draggable:!0,cursor:"move",drift:it(SA,r,e,n,["n","s","w","e"]),ondragend:it(ci,e,{isEnd:!0})})),A(a,function(i){n.add(new xt({name:i.join(""),style:{opacity:0},draggable:!0,silent:!0,invisible:!0,drift:it(SA,r,e,n,i),ondragend:it(ci,e,{isEnd:!0})}))}),n}function mA(r,e,t,a){var n=a.brushStyle.lineWidth||0,i=wo(n,y3),o=t[0][0],s=t[1][0],l=o-n/2,u=s-n/2,f=t[0][1],h=t[1][1],v=f-i+n/2,c=h-i+n/2,p=f-o,d=h-s,g=p+n,y=d+n;_a(r,e,"main",o,s,p,d),a.transformable&&(_a(r,e,"w",l,u,i,y),_a(r,e,"e",v,u,i,y),_a(r,e,"n",l,u,g,i),_a(r,e,"s",l,c,g,i),_a(r,e,"nw",l,u,i,i),_a(r,e,"ne",v,u,i,i),_a(r,e,"sw",l,c,i,i),_a(r,e,"se",v,c,i,i))}function jg(r,e){var t=e.__brushOption,a=t.transformable,n=e.childAt(0);n.useStyle(Qg(t)),n.attr({silent:!a,cursor:a?"move":"default"}),A([["w"],["e"],["n"],["s"],["s","e"],["s","w"],["n","e"],["n","w"]],function(i){var o=e.childOfName(i.join("")),s=i.length===1?Jg(r,i[0]):w3(r,i);o&&o.attr({silent:!a,invisible:!a,cursor:a?_3[s]+"-resize":null})})}function _a(r,e,t,a,n,i,o){var s=e.childOfName(t);s&&s.setShape(C3(ty(r,e,[[a,n],[a+i,n+o]])))}function Qg(r){return j({strokeNoScale:!0},r.brushStyle)}function _A(r,e,t,a){var n=[Pl(r,t),Pl(e,a)],i=[wo(r,t),wo(e,a)];return[[n[0],i[0]],[n[1],i[1]]]}function b3(r){return Ha(r.group)}function Jg(r,e){var t={w:"left",e:"right",n:"top",s:"bottom"},a={left:"w",right:"e",top:"n",bottom:"s"},n=Ku(t[e],b3(r));return a[n]}function w3(r,e){var t=[Jg(r,e[0]),Jg(r,e[1])];return(t[0]==="e"||t[0]==="w")&&t.reverse(),t.join("")}function SA(r,e,t,a,n,i){var o=t.__brushOption,s=r.toRectRange(o.range),l=xA(e,n,i);A(a,function(u){var f=m3[u];s[f[0]][f[1]]+=l[f[0]]}),o.range=r.fromRectRange(_A(s[0][0],s[1][0],s[0][1],s[1][1])),Zg(e,t),ci(e,{isEnd:!1})}function T3(r,e,t,a){var n=e.__brushOption.range,i=xA(r,t,a);A(n,function(o){o[0]+=i[0],o[1]+=i[1]}),Zg(r,e),ci(r,{isEnd:!1})}function xA(r,e,t){var a=r.group,n=a.transformCoordToLocal(e,t),i=a.transformCoordToLocal(0,0);return[n[0]-i[0],n[1]-i[1]]}function ty(r,e,t){var a=dA(r,e);return a&&a!==vi?a.clipPath(t,r._transform):et(t)}function C3(r){var e=Pl(r[0][0],r[1][0]),t=Pl(r[0][1],r[1][1]),a=wo(r[0][0],r[1][0]),n=wo(r[0][1],r[1][1]);return{x:e,y:t,width:a-e,height:n-t}}function A3(r,e,t){if(!(!r._brushType||M3(r,e.offsetX,e.offsetY))){var a=r._zr,n=r._covers,i=qg(r,e,t);if(!r._dragging)for(var o=0;oa.getWidth()||t<0||t>a.getHeight()}var bh={lineX:CA(0),lineY:CA(1),rect:{createCover:function(r,e){function t(a){return a}return yA({toRectRange:t,fromRectRange:t},r,e,[["w"],["e"],["n"],["s"],["s","e"],["s","w"],["n","e"],["n","w"]])},getCreatingRange:function(r){var e=gA(r);return _A(e[1][0],e[1][1],e[0][0],e[0][1])},updateCoverShape:function(r,e,t,a){mA(r,e,t,a)},updateCommon:jg,contain:ry},polygon:{createCover:function(r,e){var t=new rt;return t.add(new Se({name:"main",style:Qg(e),silent:!0})),t},getCreatingRange:function(r){return r},endCreating:function(r,e){e.remove(e.childAt(0)),e.add(new _e({name:"main",draggable:!0,drift:it(T3,r,e),ondragend:it(ci,r,{isEnd:!0})}))},updateCoverShape:function(r,e,t,a){e.childAt(0).setShape({points:ty(r,e,t)})},updateCommon:jg,contain:ry}};function CA(r){return{createCover:function(e,t){return yA({toRectRange:function(a){var n=[a,[0,100]];return r&&n.reverse(),n},fromRectRange:function(a){return a[r]}},e,t,[[["w"],["e"]],[["n"],["s"]]][r])},getCreatingRange:function(e){var t=gA(e),a=Pl(t[0][r],t[1][r]),n=wo(t[0][r],t[1][r]);return[a,n]},updateCoverShape:function(e,t,a,n){var i,o=dA(e,t);if(o!==vi&&o.getLinearBrushOtherExtent)i=o.getLinearBrushOtherExtent(r);else{var s=e._zr;i=[0,[s.getWidth(),s.getHeight()][1-r]]}var l=[a,i];r&&l.reverse(),mA(e,t,l,n)},updateCommon:jg,contain:ry}}function AA(r){return r=ay(r),function(e){return Xc(e,r)}}function DA(r,e){return r=ay(r),function(t){var a=e!=null?e:t,n=a?r.width:r.height,i=a?r.x:r.y;return[i,i+(n||0)]}}function MA(r,e,t){var a=ay(r);return function(n,i){return a.contain(i[0],i[1])&&!sh(n,e,t)}}function ay(r){return ft.create(r)}var I3=["axisLine","axisTickLabel","axisName"],L3=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t,a){r.prototype.init.apply(this,arguments),(this._brushController=new Xg(a.getZr())).on("brush",Y(this._onBrush,this))},e.prototype.render=function(t,a,n,i){if(!P3(t,a,i)){this.axisModel=t,this.api=n,this.group.removeAll();var o=this._axisGroup;if(this._axisGroup=new rt,this.group.add(this._axisGroup),!!t.get("show")){var s=E3(t,a),l=s.coordinateSystem,u=t.getAreaSelectStyle(),f=u.width,h=t.axis.dim,v=l.getAxisLayout(h),c=B({strokeContainThreshold:f},v),p=new Pe(t,c);A(I3,p.add,p),this._axisGroup.add(p.getGroup()),this._refreshBrushController(c,u,t,s,f,n),As(o,this._axisGroup,t)}}},e.prototype._refreshBrushController=function(t,a,n,i,o,s){var l=n.axis.getExtent(),u=l[1]-l[0],f=Math.min(30,Math.abs(u)*.1),h=ft.create({x:l[0],y:-o/2,width:u,height:o});h.x-=f,h.width+=2*f,this._brushController.mount({enableGlobalPan:!0,rotation:t.rotation,x:t.position[0],y:t.position[1]}).setPanels([{panelId:"pl",clipPath:AA(h),isTargetByCursor:MA(h,s,i),getLinearBrushOtherExtent:DA(h,0)}]).enableBrush({brushType:"lineX",brushStyle:a,removeOnClick:!0}).updateCovers(R3(n))},e.prototype._onBrush=function(t){var a=t.areas,n=this.axisModel,i=n.axis,o=G(a,function(s){return[i.coordToData(s.range[0],!0),i.coordToData(s.range[1],!0)]});(!n.option.realtime===t.isEnd||t.removeOnClick)&&this.api.dispatchAction({type:"axisAreaSelect",parallelAxisId:n.id,intervals:o})},e.prototype.dispose=function(){this._brushController.dispose()},e.type="parallelAxis",e}(Bt);function P3(r,e,t){return t&&t.type==="axisAreaSelect"&&e.findComponents({mainType:"parallelAxis",query:t})[0]===r}function R3(r){var e=r.axis;return G(r.activeIntervals,function(t){return{brushType:"lineX",panelId:"pl",range:[e.dataToCoord(t[0],!0),e.dataToCoord(t[1],!0)]}})}function E3(r,e){return e.getComponent("parallel",r.get("parallelIndex"))}var k3={type:"axisAreaSelect",event:"axisAreaSelected"};function O3(r){r.registerAction(k3,function(e,t){t.eachComponent({mainType:"parallelAxis",query:e},function(a){a.axis.model.setActiveIntervals(e.intervals)})}),r.registerAction("parallelAxisExpand",function(e,t){t.eachComponent({mainType:"parallel",query:e},function(a){a.setAxisExpand(e)})})}var N3={type:"value",areaSelectStyle:{width:20,borderWidth:1,borderColor:"rgba(160,197,232)",color:"rgba(160,197,232)",opacity:.3},realtime:!0,z:10};function IA(r){r.registerComponentView(a3),r.registerComponentModel(i3),r.registerCoordinateSystem("parallel",c3),r.registerPreprocessor(JF),r.registerComponentModel(Yg),r.registerComponentView(L3),yo(r,"parallel",Yg,N3),O3(r)}function B3(r){ct(IA),r.registerChartView(YF),r.registerSeriesModel($F),r.registerVisual(r.PRIORITY.VISUAL.BRUSH,QF)}var V3=function(){function r(){this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.cpx1=0,this.cpy1=0,this.cpx2=0,this.cpy2=0,this.extent=0}return r}(),z3=function(r){O(e,r);function e(t){return r.call(this,t)||this}return e.prototype.getDefaultShape=function(){return new V3},e.prototype.buildPath=function(t,a){var n=a.extent;t.moveTo(a.x1,a.y1),t.bezierCurveTo(a.cpx1,a.cpy1,a.cpx2,a.cpy2,a.x2,a.y2),a.orient==="vertical"?(t.lineTo(a.x2+n,a.y2),t.bezierCurveTo(a.cpx2+n,a.cpy2,a.cpx1+n,a.cpy1,a.x1+n,a.y1)):(t.lineTo(a.x2,a.y2+n),t.bezierCurveTo(a.cpx2,a.cpy2+n,a.cpx1,a.cpy1+n,a.x1,a.y1+n)),t.closePath()},e.prototype.highlight=function(){va(this)},e.prototype.downplay=function(){ca(this)},e}(dt),G3=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t._focusAdjacencyDisabled=!1,t}return e.prototype.render=function(t,a,n){var i=this,o=t.getGraph(),s=this.group,l=t.layoutInfo,u=l.width,f=l.height,h=t.getData(),v=t.getData("edge"),c=t.get("orient");this._model=t,s.removeAll(),s.x=l.x,s.y=l.y,o.eachEdge(function(p){var d=new z3,g=nt(d);g.dataIndex=p.dataIndex,g.seriesIndex=t.seriesIndex,g.dataType="edge";var y=p.getModel(),m=y.getModel("lineStyle"),_=m.get("curveness"),S=p.node1.getLayout(),b=p.node1.getModel(),x=b.get("localX"),w=b.get("localY"),T=p.node2.getLayout(),C=p.node2.getModel(),D=C.get("localX"),M=C.get("localY"),I=p.getLayout(),L,P,R,E,N,k,V,F;switch(d.shape.extent=Math.max(1,I.dy),d.shape.orient=c,c==="vertical"?(L=(x!=null?x*u:S.x)+I.sy,P=(w!=null?w*f:S.y)+S.dy,R=(D!=null?D*u:T.x)+I.ty,E=M!=null?M*f:T.y,N=L,k=P*(1-_)+E*_,V=R,F=P*_+E*(1-_)):(L=(x!=null?x*u:S.x)+S.dx,P=(w!=null?w*f:S.y)+I.sy,R=D!=null?D*u:T.x,E=(M!=null?M*f:T.y)+I.ty,N=L*(1-_)+R*_,k=P,V=L*_+R*(1-_),F=E),d.setShape({x1:L,y1:P,x2:R,y2:E,cpx1:N,cpy1:k,cpx2:V,cpy2:F}),d.useStyle(m.getItemStyle()),d.style.fill){case"source":d.style.fill=p.node1.getVisual("color"),d.style.decal=p.node1.getVisual("style").decal;break;case"target":d.style.fill=p.node2.getVisual("color"),d.style.decal=p.node2.getVisual("style").decal;break;case"gradient":var W=p.node1.getVisual("color"),Z=p.node2.getVisual("color");U(W)&&U(Z)&&(d.style.fill=new Gi(0,0,+(c==="horizontal"),+(c==="vertical"),[{color:W,offset:0},{color:Z,offset:1}]))}ve(d,ne(y,"edgeLabel"),{labelFetcher:t,labelDataIndex:p.dataIndex,defaultText:""+y.get("value")}),d.setTextConfig({position:"inside"});var Q=y.getModel("emphasis");he(d,y,"lineStyle",function(yt){return yt.getItemStyle()}),s.add(d),v.setItemGraphicEl(p.dataIndex,d);var tt=Q.get("focus");Ut(d,tt==="adjacency"?p.getAdjacentDataIndices():tt,Q.get("blurScope"),Q.get("disabled")),nt(d).dataType="edge"}),o.eachNode(function(p){var d=p.getLayout(),g=p.getModel(),y=g.get("localX"),m=g.get("localY"),_=g.getModel("emphasis"),S=new xt({shape:{x:y!=null?y*u:d.x,y:m!=null?m*f:d.y,width:d.dx,height:d.dy},style:g.getModel("itemStyle").getItemStyle(),z2:10});ve(S,ne(g),{labelFetcher:t,labelDataIndex:p.dataIndex,defaultText:p.id}),S.disableLabelAnimation=!0,S.setStyle("fill",p.getVisual("color")),S.setStyle("decal",p.getVisual("style").decal),he(S,g),s.add(S),h.setItemGraphicEl(p.dataIndex,S),nt(S).dataType="node";var b=_.get("focus");Ut(S,b==="adjacency"?p.getAdjacentDataIndices():b,_.get("blurScope"),_.get("disabled"))}),h.eachItemGraphicEl(function(p,d){var g=h.getItemModel(d);g.get("draggable")&&(p.drift=function(y,m){i._focusAdjacencyDisabled=!0,this.shape.x+=y,this.shape.y+=m,this.dirty(),n.dispatchAction({type:"dragNode",seriesId:t.id,dataIndex:h.getRawIndex(d),localX:this.shape.x/u,localY:this.shape.y/f})},p.ondragend=function(){i._focusAdjacencyDisabled=!1},p.draggable=!0,p.cursor="move")}),!this._data&&t.isAnimationEnabled()&&s.setClipPath(F3(s.getBoundingRect(),t,function(){s.removeClipPath()})),this._data=t.getData()},e.prototype.dispose=function(){},e.type="sankey",e}(Rt);function F3(r,e,t){var a=new xt({shape:{x:r.x-10,y:r.y-10,width:0,height:r.height+20}});return Gt(a,{shape:{width:r.width+20}},e,t),a}var H3=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.getInitialData=function(t,a){var n=t.edges||t.links,i=t.data||t.nodes,o=t.levels;this.levelModels=[];for(var s=this.levelModels,l=0;l=0&&(s[o[l].depth]=new Mt(o[l],this,a));if(i&&n){var u=eA(i,n,this,!0,f);return u.data}function f(h,v){h.wrapMethod("getItemModel",function(c,p){var d=c.parentModel,g=d.getData().getItemLayout(p);if(g){var y=g.depth,m=d.levelModels[y];m&&(c.parentModel=m)}return c}),v.wrapMethod("getItemModel",function(c,p){var d=c.parentModel,g=d.getGraph().getEdgeByIndex(p),y=g.node1.getLayout();if(y){var m=y.depth,_=d.levelModels[m];_&&(c.parentModel=_)}return c})}},e.prototype.setNodePosition=function(t,a){var n=this.option.data||this.option.nodes,i=n[t];i.localX=a[0],i.localY=a[1]},e.prototype.getGraph=function(){return this.getData().graph},e.prototype.getEdgeData=function(){return this.getGraph().edgeData},e.prototype.formatTooltip=function(t,a,n){function i(c){return isNaN(c)||c==null}if(n==="edge"){var o=this.getDataParams(t,n),s=o.data,l=o.value,u=s.source+" -- "+s.target;return ie("nameValue",{name:u,value:l,noValue:i(l)})}else{var f=this.getGraph().getNodeByIndex(t),h=f.getLayout().value,v=this.getDataParams(t,n).data.name;return ie("nameValue",{name:v!=null?v+"":null,value:h,noValue:i(h)})}},e.prototype.optionUpdated=function(){},e.prototype.getDataParams=function(t,a){var n=r.prototype.getDataParams.call(this,t,a);if(n.value==null&&a==="node"){var i=this.getGraph().getNodeByIndex(t),o=i.getLayout().value;n.value=o}return n},e.type="series.sankey",e.defaultOption={z:2,coordinateSystem:"view",left:"5%",top:"5%",right:"20%",bottom:"5%",orient:"horizontal",nodeWidth:20,nodeGap:8,draggable:!0,layoutIterations:32,label:{show:!0,position:"right",fontSize:12},edgeLabel:{show:!1,fontSize:12},levels:[],nodeAlign:"justify",lineStyle:{color:"#314656",opacity:.2,curveness:.5},emphasis:{label:{show:!0},lineStyle:{opacity:.5}},select:{itemStyle:{borderColor:"#212121"}},animationEasing:"linear",animationDuration:1e3},e}(kt);function W3(r,e){r.eachSeriesByType("sankey",function(t){var a=t.get("nodeWidth"),n=t.get("nodeGap"),i=U3(t,e);t.layoutInfo=i;var o=i.width,s=i.height,l=t.getGraph(),u=l.nodes,f=l.edges;X3(u);var h=Lt(u,function(d){return d.getLayout().value===0}),v=h.length!==0?0:t.get("layoutIterations"),c=t.get("orient"),p=t.get("nodeAlign");Y3(u,f,a,n,o,s,v,c,p)})}function U3(r,e){return jt(r.getBoxLayoutParams(),{width:e.getWidth(),height:e.getHeight()})}function Y3(r,e,t,a,n,i,o,s,l){Z3(r,e,t,n,i,s,l),j3(r,e,i,n,a,o,s),oH(r,s)}function X3(r){A(r,function(e){var t=an(e.outEdges,wh),a=an(e.inEdges,wh),n=e.getValue()||0,i=Math.max(t,a,n);e.setLayout({value:i},!0)})}function Z3(r,e,t,a,n,i,o){for(var s=[],l=[],u=[],f=[],h=0,v=0;v=0;y&&g.depth>c&&(c=g.depth),d.setLayout({depth:y?g.depth:h},!0),i==="vertical"?d.setLayout({dy:t},!0):d.setLayout({dx:t},!0);for(var m=0;mh-1?c:h-1;o&&o!=="left"&&$3(r,o,i,w);var T=i==="vertical"?(n-t)/w:(a-t)/w;K3(r,T,i)}function LA(r){var e=r.hostGraph.data.getRawDataItem(r.dataIndex);return e.depth!=null&&e.depth>=0}function $3(r,e,t,a){if(e==="right"){for(var n=[],i=r,o=0;i.length;){for(var s=0;s0;i--)l*=.99,tH(s,l,o),ny(s,n,t,a,o),iH(s,l,o),ny(s,n,t,a,o)}function Q3(r,e){var t=[],a=e==="vertical"?"y":"x",n=lc(r,function(i){return i.getLayout()[a]});return n.keys.sort(function(i,o){return i-o}),A(n.keys,function(i){t.push(n.buckets.get(i))}),t}function J3(r,e,t,a,n,i){var o=Infinity;A(r,function(s){var l=s.length,u=0;A(s,function(h){u+=h.getLayout().value});var f=i==="vertical"?(a-(l-1)*n)/u:(t-(l-1)*n)/u;f0&&(s=l.getLayout()[i]+u,n==="vertical"?l.setLayout({x:s},!0):l.setLayout({y:s},!0)),f=l.getLayout()[i]+l.getLayout()[v]+e;var p=n==="vertical"?a:t;if(u=f-e-p,u>0){s=l.getLayout()[i]-u,n==="vertical"?l.setLayout({x:s},!0):l.setLayout({y:s},!0),f=s;for(var c=h-2;c>=0;--c)l=o[c],u=l.getLayout()[i]+l.getLayout()[v]+e-f,u>0&&(s=l.getLayout()[i]-u,n==="vertical"?l.setLayout({x:s},!0):l.setLayout({y:s},!0)),f=l.getLayout()[i]}})}function tH(r,e,t){A(r.slice().reverse(),function(a){A(a,function(n){if(n.outEdges.length){var i=an(n.outEdges,eH,t)/an(n.outEdges,wh);if(isNaN(i)){var o=n.outEdges.length;i=o?an(n.outEdges,rH,t)/o:0}if(t==="vertical"){var s=n.getLayout().x+(i-rn(n,t))*e;n.setLayout({x:s},!0)}else{var l=n.getLayout().y+(i-rn(n,t))*e;n.setLayout({y:l},!0)}}})})}function eH(r,e){return rn(r.node2,e)*r.getValue()}function rH(r,e){return rn(r.node2,e)}function aH(r,e){return rn(r.node1,e)*r.getValue()}function nH(r,e){return rn(r.node1,e)}function rn(r,e){return e==="vertical"?r.getLayout().x+r.getLayout().dx/2:r.getLayout().y+r.getLayout().dy/2}function wh(r){return r.getValue()}function an(r,e,t){for(var a=0,n=r.length,i=-1;++io&&(o=l)}),A(a,function(s){var l=new se({type:"color",mappingMethod:"linear",dataExtent:[i,o],visual:e.get("color")}),u=l.mapValueToVisual(s.getLayout().value),f=s.getModel().get(["itemStyle","color"]);f!=null?(s.setVisual("color",f),s.setVisual("style",{fill:f})):(s.setVisual("color",u),s.setVisual("style",{fill:u}))})}n.length&&A(n,function(s){var l=s.getModel().get("lineStyle");s.setVisual("style",l)})})}function lH(r){r.registerChartView(G3),r.registerSeriesModel(H3),r.registerLayout(W3),r.registerVisual(sH),r.registerAction({type:"dragNode",event:"dragnode",update:"update"},function(e,t){t.eachComponent({mainType:"series",subType:"sankey",query:e},function(a){a.setNodePosition(e.dataIndex,[e.localX,e.localY])})})}var PA=function(){function r(){}return r.prototype.getInitialData=function(e,t){var a,n=t.getComponent("xAxis",this.get("xAxisIndex")),i=t.getComponent("yAxis",this.get("yAxisIndex")),o=n.get("type"),s=i.get("type"),l;o==="category"?(e.layout="horizontal",a=n.getOrdinalMeta(),l=!0):s==="category"?(e.layout="vertical",a=i.getOrdinalMeta(),l=!0):e.layout=e.layout||"horizontal";var u=["x","y"],f=e.layout==="horizontal"?0:1,h=this._baseAxisDim=u[f],v=u[1-f],c=[n,i],p=c[f].get("type"),d=c[1-f].get("type"),g=e.data;if(g&&l){var y=[];A(g,function(S,b){var x;z(S)?(x=S.slice(),S.unshift(b)):z(S.value)?(x=B({},S),x.value=x.value.slice(),S.value.unshift(b)):x=S,y.push(x)}),e.data=y}var m=this.defaultValueDimensions,_=[{name:h,type:Ef(p),ordinalMeta:a,otherDims:{tooltip:!1,itemName:0},dimsDef:["base"]},{name:v,type:Ef(d),dimsDef:m.slice()}];return go(this,{coordDimensions:_,dimensionsCount:m.length+1,encodeDefaulter:it(q1,_,this)})},r.prototype.getBaseAxis=function(){var e=this._baseAxisDim;return this.ecModel.getComponent(e+"Axis",this.get(e+"AxisIndex")).axis},r}(),RA=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.defaultValueDimensions=[{name:"min",defaultTooltip:!0},{name:"Q1",defaultTooltip:!0},{name:"median",defaultTooltip:!0},{name:"Q3",defaultTooltip:!0},{name:"max",defaultTooltip:!0}],t.visualDrawType="stroke",t}return e.type="series.boxplot",e.dependencies=["xAxis","yAxis","grid"],e.defaultOption={z:2,coordinateSystem:"cartesian2d",legendHoverLink:!0,layout:null,boxWidth:[7,50],itemStyle:{color:"#fff",borderWidth:1},emphasis:{scale:!0,itemStyle:{borderWidth:2,shadowBlur:5,shadowOffsetX:1,shadowOffsetY:1,shadowColor:"rgba(0,0,0,0.2)"}},animationDuration:800},e}(kt);Xt(RA,PA,!0);var uH=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=t.getData(),o=this.group,s=this._data;this._data||o.removeAll();var l=t.get("layout")==="horizontal"?1:0;i.diff(s).add(function(u){if(i.hasValue(u)){var f=i.getItemLayout(u),h=EA(f,i,u,l,!0);i.setItemGraphicEl(u,h),o.add(h)}}).update(function(u,f){var h=s.getItemGraphicEl(f);if(!i.hasValue(u)){o.remove(h);return}var v=i.getItemLayout(u);h?(Cr(h),kA(v,h,i,u)):h=EA(v,i,u,l),o.add(h),i.setItemGraphicEl(u,h)}).remove(function(u){var f=s.getItemGraphicEl(u);f&&o.remove(f)}).execute(),this._data=i},e.prototype.remove=function(t){var a=this.group,n=this._data;this._data=null,n&&n.eachItemGraphicEl(function(i){i&&a.remove(i)})},e.type="boxplot",e}(Rt),fH=function(){function r(){}return r}(),hH=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="boxplotBoxPath",a}return e.prototype.getDefaultShape=function(){return new fH},e.prototype.buildPath=function(t,a){var n=a.points,i=0;for(t.moveTo(n[i][0],n[i][1]),i++;i<4;i++)t.lineTo(n[i][0],n[i][1]);for(t.closePath();id){var S=[y,_];a.push(S)}}}return{boxData:t,outliers:a}}var mH={type:"echarts:boxplot",transform:function(e){var t=e.upstream;if(t.sourceFormat!==xe){var a="";It(a)}var n=yH(t.getRawData(),e.config);return[{dimensions:["ItemName","Low","Q1","Q2","Q3","High"],data:n.boxData},{data:n.outliers}]}};function _H(r){r.registerSeriesModel(RA),r.registerChartView(uH),r.registerLayout(cH),r.registerTransform(mH)}var SH=["color","borderColor"],xH=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){this.group.removeClipPath(),this._progressiveEls=null,this._updateDrawMode(t),this._isLargeDraw?this._renderLarge(t):this._renderNormal(t)},e.prototype.incrementalPrepareRender=function(t,a,n){this._clear(),this._updateDrawMode(t)},e.prototype.incrementalRender=function(t,a,n,i){this._progressiveEls=[],this._isLargeDraw?this._incrementalRenderLarge(t,a):this._incrementalRenderNormal(t,a)},e.prototype.eachRendered=function(t){Wa(this._progressiveEls||this.group,t)},e.prototype._updateDrawMode=function(t){var a=t.pipelineContext.large;(this._isLargeDraw==null||a!==this._isLargeDraw)&&(this._isLargeDraw=a,this._clear())},e.prototype._renderNormal=function(t){var a=t.getData(),n=this._data,i=this.group,o=a.getLayout("isSimpleBox"),s=t.get("clip",!0),l=t.coordinateSystem,u=l.getArea&&l.getArea();this._data||i.removeAll(),a.diff(n).add(function(f){if(a.hasValue(f)){var h=a.getItemLayout(f);if(s&&OA(u,h))return;var v=iy(h,f,!0);Gt(v,{shape:{points:h.ends}},t,f),oy(v,a,f,o),i.add(v),a.setItemGraphicEl(f,v)}}).update(function(f,h){var v=n.getItemGraphicEl(h);if(!a.hasValue(f)){i.remove(v);return}var c=a.getItemLayout(f);if(s&&OA(u,c)){i.remove(v);return}v?(At(v,{shape:{points:c.ends}},t,f),Cr(v)):v=iy(c),oy(v,a,f,o),i.add(v),a.setItemGraphicEl(f,v)}).remove(function(f){var h=n.getItemGraphicEl(f);h&&i.remove(h)}).execute(),this._data=a},e.prototype._renderLarge=function(t){this._clear(),NA(t,this.group);var a=t.get("clip",!0)?Jf(t.coordinateSystem,!1,t):null;a?this.group.setClipPath(a):this.group.removeClipPath()},e.prototype._incrementalRenderNormal=function(t,a){for(var n=a.getData(),i=n.getLayout("isSimpleBox"),o;(o=t.next())!=null;){var s=n.getItemLayout(o),l=iy(s);oy(l,n,o,i),l.incremental=!0,this.group.add(l),this._progressiveEls.push(l)}},e.prototype._incrementalRenderLarge=function(t,a){NA(a,this.group,this._progressiveEls,!0)},e.prototype.remove=function(t){this._clear()},e.prototype._clear=function(){this.group.removeAll(),this._data=null},e.type="candlestick",e}(Rt),bH=function(){function r(){}return r}(),wH=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a.type="normalCandlestickBox",a}return e.prototype.getDefaultShape=function(){return new bH},e.prototype.buildPath=function(t,a){var n=a.points;this.__simpleBox?(t.moveTo(n[4][0],n[4][1]),t.lineTo(n[6][0],n[6][1])):(t.moveTo(n[0][0],n[0][1]),t.lineTo(n[1][0],n[1][1]),t.lineTo(n[2][0],n[2][1]),t.lineTo(n[3][0],n[3][1]),t.closePath(),t.moveTo(n[4][0],n[4][1]),t.lineTo(n[5][0],n[5][1]),t.moveTo(n[6][0],n[6][1]),t.lineTo(n[7][0],n[7][1]))},e}(dt);function iy(r,e,t){var a=r.ends;return new wH({shape:{points:t?TH(a,r):a},z2:100})}function OA(r,e){for(var t=!0,a=0;a0?"borderColor":"borderColor0"])||t.get(["itemStyle",r>0?"color":"color0"]);r===0&&(n=t.get(["itemStyle","borderColorDoji"]));var i=t.getModel("itemStyle").getItemStyle(SH);e.useStyle(i),e.style.fill=null,e.style.stroke=n}var BA=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.defaultValueDimensions=[{name:"open",defaultTooltip:!0},{name:"close",defaultTooltip:!0},{name:"lowest",defaultTooltip:!0},{name:"highest",defaultTooltip:!0}],t}return e.prototype.getShadowDim=function(){return"open"},e.prototype.brushSelector=function(t,a,n){var i=a.getItemLayout(t);return i&&n.rect(i.brushRect)},e.type="series.candlestick",e.dependencies=["xAxis","yAxis","grid"],e.defaultOption={z:2,coordinateSystem:"cartesian2d",legendHoverLink:!0,layout:null,clip:!0,itemStyle:{color:"#eb5454",color0:"#47b262",borderColor:"#eb5454",borderColor0:"#47b262",borderColorDoji:null,borderWidth:1},emphasis:{scale:!0,itemStyle:{borderWidth:2}},barMaxWidth:null,barMinWidth:null,barWidth:null,large:!0,largeThreshold:600,progressive:3e3,progressiveThreshold:1e4,progressiveChunkMode:"mod",animationEasing:"linear",animationDuration:300},e}(kt);Xt(BA,PA,!0);function AH(r){!r||!z(r.series)||A(r.series,function(e){J(e)&&e.type==="k"&&(e.type="candlestick")})}var DH=["itemStyle","borderColor"],MH=["itemStyle","borderColor0"],IH=["itemStyle","borderColorDoji"],LH=["itemStyle","color"],PH=["itemStyle","color0"],RH={seriesType:"candlestick",plan:ro(),performRawSeries:!0,reset:function(r,e){function t(i,o){return o.get(i>0?LH:PH)}function a(i,o){return o.get(i===0?IH:i>0?DH:MH)}if(!e.isSeriesFiltered(r)){var n=r.pipelineContext.large;return!n&&{progress:function(i,o){for(var s;(s=i.next())!=null;){var l=o.getItemModel(s),u=o.getItemLayout(s).sign,f=l.getItemStyle();f.fill=t(u,l),f.stroke=a(u,l)||f.fill;var h=o.ensureUniqueItemVisual(s,"style");B(h,f)}}}}}},EH={seriesType:"candlestick",plan:ro(),reset:function(r){var e=r.coordinateSystem,t=r.getData(),a=kH(r,t),n=0,i=1,o=["x","y"],s=t.getDimensionIndex(t.mapDimension(o[n])),l=G(t.mapDimensionsAll(o[i]),t.getDimensionIndex,t),u=l[0],f=l[1],h=l[2],v=l[3];if(t.setLayout({candleWidth:a,isSimpleBox:a<=1.3}),s<0||l.length<4)return;return{progress:r.pipelineContext.large?p:c};function c(d,g){for(var y,m=g.getStore();(y=d.next())!=null;){var _=m.get(s,y),S=m.get(u,y),b=m.get(f,y),x=m.get(h,y),w=m.get(v,y),T=Math.min(S,b),C=Math.max(S,b),D=N(T,_),M=N(C,_),I=N(x,_),L=N(w,_),P=[];k(P,M,0),k(P,D,1),P.push(F(L),F(M),F(I),F(D));var R=g.getItemModel(y),E=!!R.get(["itemStyle","borderColorDoji"]);g.setItemLayout(y,{sign:VA(m,y,S,b,f,E),initBaseline:S>b?M[i]:D[i],ends:P,brushRect:V(x,w,_)})}function N(W,Z){var Q=[];return Q[n]=Z,Q[i]=W,isNaN(Z)||isNaN(W)?[NaN,NaN]:e.dataToPoint(Q)}function k(W,Z,Q){var tt=Z.slice(),yt=Z.slice();tt[n]=qu(tt[n]+a/2,1,!1),yt[n]=qu(yt[n]-a/2,1,!0),Q?W.push(tt,yt):W.push(yt,tt)}function V(W,Z,Q){var tt=N(W,Q),yt=N(Z,Q);return tt[n]-=a/2,yt[n]-=a/2,{x:tt[0],y:tt[1],width:a,height:yt[1]-tt[1]}}function F(W){return W[n]=qu(W[n],1),W}}function p(d,g){for(var y=$r(d.count*4),m=0,_,S=[],b=[],x,w=g.getStore(),T=!!r.get(["itemStyle","borderColorDoji"]);(x=d.next())!=null;){var C=w.get(s,x),D=w.get(u,x),M=w.get(f,x),I=w.get(h,x),L=w.get(v,x);if(isNaN(C)||isNaN(I)||isNaN(L)){y[m++]=NaN,m+=3;continue}y[m++]=VA(w,x,D,M,f,T),S[n]=C,S[i]=I,_=e.dataToPoint(S,null,b),y[m++]=_?_[0]:NaN,y[m++]=_?_[1]:NaN,S[i]=L,_=e.dataToPoint(S,null,b),y[m++]=_?_[1]:NaN}g.setLayout("largePoints",y)}}};function VA(r,e,t,a,n,i){var o;return t>a?o=-1:t0?r.get(n,e-1)<=a?1:-1:1,o}function kH(r,e){var t=r.getBaseAxis(),a,n=t.type==="category"?t.getBandWidth():(a=t.getExtent(),Math.abs(a[1]-a[0])/e.count()),i=H(lt(r.get("barMaxWidth"),n),n),o=H(lt(r.get("barMinWidth"),1),n),s=r.get("barWidth");return s!=null?H(s,n):Math.max(Math.min(n/2,i),o)}function OH(r){r.registerChartView(xH),r.registerSeriesModel(BA),r.registerPreprocessor(AH),r.registerVisual(RH),r.registerLayout(EH)}function zA(r,e){var t=e.rippleEffectColor||e.color;r.eachChild(function(a){a.attr({z:e.z,zlevel:e.zlevel,style:{stroke:e.brushType==="stroke"?t:null,fill:e.brushType==="fill"?t:null}})})}var NH=function(r){O(e,r);function e(t,a){var n=r.call(this)||this,i=new ul(t,a),o=new rt;return n.add(i),n.add(o),n.updateData(t,a),n}return e.prototype.stopEffectAnimation=function(){this.childAt(1).removeAll()},e.prototype.startEffectAnimation=function(t){for(var a=t.symbolType,n=t.color,i=t.rippleNumber,o=this.childAt(1),s=0;s0&&(s=this._getLineLength(i)/f*1e3),s!==this._period||l!==this._loop||u!==this._roundTrip){i.stopAnimation();var v=void 0;K(h)?v=h(n):v=h,i.__t>0&&(v=-s*i.__t),this._animateSymbol(i,s,v,l,u)}this._period=s,this._loop=l,this._roundTrip=u}},e.prototype._animateSymbol=function(t,a,n,i,o){if(a>0){t.__t=0;var s=this,l=t.animate("",i).when(o?a*2:a,{__t:o?2:1}).delay(n).during(function(){s._updateSymbolPosition(t)});i||l.done(function(){s.remove(t)}),l.start()}},e.prototype._getLineLength=function(t){return ra(t.__p1,t.__cp1)+ra(t.__cp1,t.__p2)},e.prototype._updateAnimationPoints=function(t,a){t.__p1=a[0],t.__p2=a[1],t.__cp1=a[2]||[(a[0][0]+a[1][0])/2,(a[0][1]+a[1][1])/2]},e.prototype.updateData=function(t,a,n){this.childAt(0).updateData(t,a,n),this._updateEffectSymbol(t,a)},e.prototype._updateSymbolPosition=function(t){var a=t.__p1,n=t.__p2,i=t.__cp1,o=t.__t<1?t.__t:2-t.__t,s=[t.x,t.y],l=s.slice(),u=ue,f=Tv;s[0]=u(a[0],i[0],n[0],o),s[1]=u(a[1],i[1],n[1],o);var h=t.__t<1?f(a[0],i[0],n[0],o):f(n[0],i[0],a[0],1-o),v=t.__t<1?f(a[1],i[1],n[1],o):f(n[1],i[1],a[1],1-o);t.rotation=-Math.atan2(v,h)-Math.PI/2,(this._symbolType==="line"||this._symbolType==="rect"||this._symbolType==="roundRect")&&(t.__lastT!==void 0&&t.__lastT=0&&!(i[l]<=a);l--);l=Math.min(l,o-2)}else{for(l=s;la);l++);l=Math.min(l-1,o-2)}var f=(a-i[l])/(i[l+1]-i[l]),h=n[l],v=n[l+1];t.x=h[0]*(1-f)+f*v[0],t.y=h[1]*(1-f)+f*v[1];var c=t.__t<1?v[0]-h[0]:h[0]-v[0],p=t.__t<1?v[1]-h[1]:h[1]-v[1];t.rotation=-Math.atan2(p,c)-Math.PI/2,this._lastFrame=l,this._lastFramePercent=a,t.ignore=!1}},e}(GA),FH=function(){function r(){this.polyline=!1,this.curveness=0,this.segs=[]}return r}(),HH=function(r){O(e,r);function e(t){var a=r.call(this,t)||this;return a._off=0,a.hoverDataIdx=-1,a}return e.prototype.reset=function(){this.notClear=!1,this._off=0},e.prototype.getDefaultStyle=function(){return{stroke:"#000",fill:null}},e.prototype.getDefaultShape=function(){return new FH},e.prototype.buildPath=function(t,a){var n=a.segs,i=a.curveness,o;if(a.polyline)for(o=this._off;o0){t.moveTo(n[o++],n[o++]);for(var l=1;l0){var c=(u+h)/2-(f-v)*i,p=(f+v)/2-(h-u)*i;t.quadraticCurveTo(c,p,h,v)}else t.lineTo(h,v)}this.incremental&&(this._off=o,this.notClear=!0)},e.prototype.findDataIndex=function(t,a){var n=this.shape,i=n.segs,o=n.curveness,s=this.style.lineWidth;if(n.polyline)for(var l=0,u=0;u0)for(var h=i[u++],v=i[u++],c=1;c0){var g=(h+p)/2-(v-d)*o,y=(v+d)/2-(p-h)*o;if(p_(h,v,g,y,p,d,s,t,a))return l}else if(Ba(h,v,p,d,s,t,a))return l;l++}return-1},e.prototype.contain=function(t,a){var n=this.transformCoordToLocal(t,a),i=this.getBoundingRect();if(t=n[0],a=n[1],i.contain(t,a)){var o=this.hoverDataIdx=this.findDataIndex(t,a);return o>=0}return this.hoverDataIdx=-1,!1},e.prototype.getBoundingRect=function(){var t=this._rect;if(!t){for(var a=this.shape,n=a.segs,i=Infinity,o=Infinity,s=-Infinity,l=-Infinity,u=0;u0&&(o.dataIndex=l+e.__startIndex)})},r.prototype._clear=function(){this._newAdded=[],this.group.removeAll()},r}(),HA={seriesType:"lines",plan:ro(),reset:function(r){var e=r.coordinateSystem;if(!!e){var t=r.get("polyline"),a=r.pipelineContext.large;return{progress:function(n,i){var o=[];if(a){var s=void 0,l=n.end-n.start;if(t){for(var u=0,f=n.start;f0&&(f||u.configLayer(s,{motionBlur:!0,lastFrameAlpha:Math.max(Math.min(l/10+.9,1),0)})),o.updateData(i);var h=t.get("clip",!0)&&Jf(t.coordinateSystem,!1,t);h?this.group.setClipPath(h):this.group.removeClipPath(),this._lastZlevel=s,this._finished=!0},e.prototype.incrementalPrepareRender=function(t,a,n){var i=t.getData(),o=this._updateLineDraw(i,t);o.incrementalPrepareUpdate(i),this._clearLayer(n),this._finished=!1},e.prototype.incrementalRender=function(t,a,n){this._lineDraw.incrementalUpdate(t,a.getData()),this._finished=t.end===a.getData().count()},e.prototype.eachRendered=function(t){this._lineDraw&&this._lineDraw.eachRendered(t)},e.prototype.updateTransform=function(t,a,n){var i=t.getData(),o=t.pipelineContext;if(!this._finished||o.large||o.progressiveRender)return{update:!0};var s=HA.reset(t,a,n);s.progress&&s.progress({start:0,end:i.count(),count:i.count()},i),this._lineDraw.updateLayout(),this._clearLayer(n)},e.prototype._updateLineDraw=function(t,a){var n=this._lineDraw,i=this._showEffect(a),o=!!a.get("polyline"),s=a.pipelineContext,l=s.large;return(!n||i!==this._hasEffet||o!==this._isPolyline||l!==this._isLargeDraw)&&(n&&n.remove(),n=this._lineDraw=l?new WH:new kg(o?i?GH:FA:i?GA:Eg),this._hasEffet=i,this._isPolyline=o,this._isLargeDraw=l),this.group.add(n.group),n},e.prototype._showEffect=function(t){return!!t.get(["effect","show"])},e.prototype._clearLayer=function(t){var a=t.getZr(),n=a.painter.getType()==="svg";!n&&this._lastZlevel!=null&&a.painter.getLayer(this._lastZlevel).clear(!0)},e.prototype.remove=function(t,a){this._lineDraw&&this._lineDraw.remove(),this._lineDraw=null,this._clearLayer(a)},e.prototype.dispose=function(t,a){this.remove(t,a)},e.type="lines",e}(Rt),YH=typeof Uint32Array=="undefined"?Array:Uint32Array,XH=typeof Float64Array=="undefined"?Array:Float64Array;function WA(r){var e=r.data;e&&e[0]&&e[0][0]&&e[0][0].coord&&(r.data=G(e,function(t){var a=[t[0].coord,t[1].coord],n={coords:a};return t[0].name&&(n.fromName=t[0].name),t[1].name&&(n.toName=t[1].name),Zl([n,t[0],t[1]])}))}var ZH=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.visualStyleAccessPath="lineStyle",t.visualDrawType="stroke",t}return e.prototype.init=function(t){t.data=t.data||[],WA(t);var a=this._processFlatCoordsArray(t.data);this._flatCoords=a.flatCoords,this._flatCoordsOffset=a.flatCoordsOffset,a.flatCoords&&(t.data=new Float32Array(a.count)),r.prototype.init.apply(this,arguments)},e.prototype.mergeOption=function(t){if(WA(t),t.data){var a=this._processFlatCoordsArray(t.data);this._flatCoords=a.flatCoords,this._flatCoordsOffset=a.flatCoordsOffset,a.flatCoords&&(t.data=new Float32Array(a.count))}r.prototype.mergeOption.apply(this,arguments)},e.prototype.appendData=function(t){var a=this._processFlatCoordsArray(t.data);a.flatCoords&&(this._flatCoords?(this._flatCoords=No(this._flatCoords,a.flatCoords),this._flatCoordsOffset=No(this._flatCoordsOffset,a.flatCoordsOffset)):(this._flatCoords=a.flatCoords,this._flatCoordsOffset=a.flatCoordsOffset),t.data=new Float32Array(a.count)),this.getRawData().appendData(t.data)},e.prototype._getCoordsFromItemModel=function(t){var a=this.getData().getItemModel(t),n=a.option instanceof Array?a.option:a.getShallow("coords");return n},e.prototype.getLineCoordsCount=function(t){return this._flatCoordsOffset?this._flatCoordsOffset[t*2+1]:this._getCoordsFromItemModel(t).length},e.prototype.getLineCoords=function(t,a){if(this._flatCoordsOffset){for(var n=this._flatCoordsOffset[t*2],i=this._flatCoordsOffset[t*2+1],o=0;o ")})},e.prototype.preventIncremental=function(){return!!this.get(["effect","show"])},e.prototype.getProgressive=function(){var t=this.option.progressive;return t==null?this.option.large?1e4:this.get("progressive"):t},e.prototype.getProgressiveThreshold=function(){var t=this.option.progressiveThreshold;return t==null?this.option.large?2e4:this.get("progressiveThreshold"):t},e.prototype.getZLevelKey=function(){var t=this.getModel("effect"),a=t.get("trailLength");return this.getData().count()>this.getProgressiveThreshold()?this.id:t.get("show")&&a>0?a+"":""},e.type="series.lines",e.dependencies=["grid","polar","geo","calendar"],e.defaultOption={coordinateSystem:"geo",z:2,legendHoverLink:!0,xAxisIndex:0,yAxisIndex:0,symbol:["none","none"],symbolSize:[10,10],geoIndex:0,effect:{show:!1,period:4,constantSpeed:0,symbol:"circle",symbolSize:3,loop:!0,trailLength:.2},large:!1,largeThreshold:2e3,polyline:!1,clip:!0,label:{show:!1,position:"end"},lineStyle:{opacity:.5}},e}(kt);function Th(r){return r instanceof Array||(r=[r,r]),r}var $H={seriesType:"lines",reset:function(r){var e=Th(r.get("symbol")),t=Th(r.get("symbolSize")),a=r.getData();a.setVisual("fromSymbol",e&&e[0]),a.setVisual("toSymbol",e&&e[1]),a.setVisual("fromSymbolSize",t&&t[0]),a.setVisual("toSymbolSize",t&&t[1]);function n(i,o){var s=i.getItemModel(o),l=Th(s.getShallow("symbol",!0)),u=Th(s.getShallow("symbolSize",!0));l[0]&&i.setItemVisual(o,"fromSymbol",l[0]),l[1]&&i.setItemVisual(o,"toSymbol",l[1]),u[0]&&i.setItemVisual(o,"fromSymbolSize",u[0]),u[1]&&i.setItemVisual(o,"toSymbolSize",u[1])}return{dataEach:a.hasItemOption?n:null}}};function qH(r){r.registerChartView(UH),r.registerSeriesModel(ZH),r.registerLayout(HA),r.registerVisual($H)}var KH=256,jH=function(){function r(){this.blurSize=30,this.pointSize=20,this.maxOpacity=1,this.minOpacity=0,this._gradientPixels={inRange:null,outOfRange:null};var e=yr.createCanvas();this.canvas=e}return r.prototype.update=function(e,t,a,n,i,o){var s=this._getBrush(),l=this._getGradient(i,"inRange"),u=this._getGradient(i,"outOfRange"),f=this.pointSize+this.blurSize,h=this.canvas,v=h.getContext("2d"),c=e.length;h.width=t,h.height=a;for(var p=0;p0){var I=o(_)?l:u;_>0&&(_=_*D+T),b[x++]=I[M],b[x++]=I[M+1],b[x++]=I[M+2],b[x++]=I[M+3]*_*256}else x+=4}return v.putImageData(S,0,0),h},r.prototype._getBrush=function(){var e=this._brushCanvas||(this._brushCanvas=yr.createCanvas()),t=this.pointSize+this.blurSize,a=t*2;e.width=a,e.height=a;var n=e.getContext("2d");return n.clearRect(0,0,a,a),n.shadowOffsetX=a,n.shadowBlur=this.blurSize,n.shadowColor="#000",n.beginPath(),n.arc(-t,t,this.pointSize,0,Math.PI*2,!0),n.closePath(),n.fill(),e},r.prototype._getGradient=function(e,t){for(var a=this._gradientPixels,n=a[t]||(a[t]=new Uint8ClampedArray(256*4)),i=[0,0,0,0],o=0,s=0;s<256;s++)e[t](s/255,!0,i),n[o++]=i[0],n[o++]=i[1],n[o++]=i[2],n[o++]=i[3];return n},r}();function QH(r,e,t){var a=r[1]-r[0];e=G(e,function(o){return{interval:[(o.interval[0]-r[0])/a,(o.interval[1]-r[0])/a]}});var n=e.length,i=0;return function(o){var s;for(s=i;s=0;s--){var l=e[s].interval;if(l[0]<=o&&o<=l[1]){i=s;break}}return s>=0&&s=e[0]&&a<=e[1]}}function UA(r){var e=r.dimensions;return e[0]==="lng"&&e[1]==="lat"}var t4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i;a.eachComponent("visualMap",function(s){s.eachTargetSeries(function(l){l===t&&(i=s)})}),this._progressiveEls=null,this.group.removeAll();var o=t.coordinateSystem;o.type==="cartesian2d"||o.type==="calendar"?this._renderOnCartesianAndCalendar(t,n,0,t.getData().count()):UA(o)&&this._renderOnGeo(o,t,i,n)},e.prototype.incrementalPrepareRender=function(t,a,n){this.group.removeAll()},e.prototype.incrementalRender=function(t,a,n,i){var o=a.coordinateSystem;o&&(UA(o)?this.render(a,n,i):(this._progressiveEls=[],this._renderOnCartesianAndCalendar(a,i,t.start,t.end,!0)))},e.prototype.eachRendered=function(t){Wa(this._progressiveEls||this.group,t)},e.prototype._renderOnCartesianAndCalendar=function(t,a,n,i,o){var s=t.coordinateSystem,l=ni(s,"cartesian2d"),u,f,h,v;if(l){var c=s.getAxis("x"),p=s.getAxis("y");u=c.getBandWidth()+.5,f=p.getBandWidth()+.5,h=c.scale.getExtent(),v=p.scale.getExtent()}for(var d=this.group,g=t.getData(),y=t.getModel(["emphasis","itemStyle"]).getItemStyle(),m=t.getModel(["blur","itemStyle"]).getItemStyle(),_=t.getModel(["select","itemStyle"]).getItemStyle(),S=t.get(["itemStyle","borderRadius"]),b=ne(t),x=t.getModel("emphasis"),w=x.get("focus"),T=x.get("blurScope"),C=x.get("disabled"),D=l?[g.mapDimension("x"),g.mapDimension("y"),g.mapDimension("value")]:[g.mapDimension("time"),g.mapDimension("value")],M=n;Mh[1]||Rv[1])continue;var E=s.dataToPoint([P,R]);I=new xt({shape:{x:E[0]-u/2,y:E[1]-f/2,width:u,height:f},style:L})}else{if(isNaN(g.get(D[1],M)))continue;I=new xt({z2:1,shape:s.dataToRect([g.get(D[0],M)]).contentShape,style:L})}if(g.hasItemOption){var N=g.getItemModel(M),k=N.getModel("emphasis");y=k.getModel("itemStyle").getItemStyle(),m=N.getModel(["blur","itemStyle"]).getItemStyle(),_=N.getModel(["select","itemStyle"]).getItemStyle(),S=N.get(["itemStyle","borderRadius"]),w=k.get("focus"),T=k.get("blurScope"),C=k.get("disabled"),b=ne(N)}I.shape.r=S;var V=t.getRawValue(M),F="-";V&&V[2]!=null&&(F=V[2]+""),ve(I,b,{labelFetcher:t,labelDataIndex:M,defaultOpacity:L.opacity,defaultText:F}),I.ensureState("emphasis").style=y,I.ensureState("blur").style=m,I.ensureState("select").style=_,Ut(I,w,T,C),I.incremental=o,o&&(I.states.emphasis.hoverLayer=!0),d.add(I),g.setItemGraphicEl(M,I),this._progressiveEls&&this._progressiveEls.push(I)}},e.prototype._renderOnGeo=function(t,a,n,i){var o=n.targetVisuals.inRange,s=n.targetVisuals.outOfRange,l=a.getData(),u=this._hmLayer||this._hmLayer||new jH;u.blurSize=a.get("blurSize"),u.pointSize=a.get("pointSize"),u.minOpacity=a.get("minOpacity"),u.maxOpacity=a.get("maxOpacity");var f=t.getViewRect().clone(),h=t.getRoamTransform();f.applyTransform(h);var v=Math.max(f.x,0),c=Math.max(f.y,0),p=Math.min(f.width+f.x,i.getWidth()),d=Math.min(f.height+f.y,i.getHeight()),g=p-v,y=d-c,m=[l.mapDimension("lng"),l.mapDimension("lat"),l.mapDimension("value")],_=l.mapArray(m,function(w,T,C){var D=t.dataToPoint([w,T]);return D[0]-=v,D[1]-=c,D.push(C),D}),S=n.getExtent(),b=n.type==="visualMap.continuous"?JH(S,n.option.range):QH(S,n.getPieceList(),n.option.selected);u.update(_,g,y,o.color.getNormalizer(),{inRange:o.color.getColorMapper(),outOfRange:s.color.getColorMapper()},b);var x=new ae({style:{width:g,height:y,x:v,y:c,image:u.canvas},silent:!0});this.group.add(x)},e.type="heatmap",e}(Rt),e4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.getInitialData=function(t,a){return Xr(null,this,{generateCoord:"value"})},e.prototype.preventIncremental=function(){var t=Ji.get(this.get("coordinateSystem"));if(t&&t.dimensions)return t.dimensions[0]==="lng"&&t.dimensions[1]==="lat"},e.type="series.heatmap",e.dependencies=["grid","geo","calendar"],e.defaultOption={coordinateSystem:"cartesian2d",z:2,geoIndex:0,blurSize:30,pointSize:20,maxOpacity:1,minOpacity:0,select:{itemStyle:{borderColor:"#212121"}}},e}(kt);function r4(r){r.registerChartView(t4),r.registerSeriesModel(e4)}var a4=["itemStyle","borderWidth"],YA=[{xy:"x",wh:"width",index:0,posDesc:["left","right"]},{xy:"y",wh:"height",index:1,posDesc:["top","bottom"]}],uy=new ar,n4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=this.group,o=t.getData(),s=this._data,l=t.coordinateSystem,u=l.getBaseAxis(),f=u.isHorizontal(),h=l.master.getRect(),v={ecSize:{width:n.getWidth(),height:n.getHeight()},seriesModel:t,coordSys:l,coordSysExtent:[[h.x,h.x+h.width],[h.y,h.y+h.height]],isHorizontal:f,valueDim:YA[+f],categoryDim:YA[1-+f]};return o.diff(s).add(function(c){if(!!o.hasValue(c)){var p=QA(o,c),d=XA(o,c,p,v),g=JA(o,v,d);o.setItemGraphicEl(c,g),i.add(g),rD(g,v,d)}}).update(function(c,p){var d=s.getItemGraphicEl(p);if(!o.hasValue(c)){i.remove(d);return}var g=QA(o,c),y=XA(o,c,g,v),m=eD(o,y);d&&m!==d.__pictorialShapeStr&&(i.remove(d),o.setItemGraphicEl(c,null),d=null),d?h4(d,v,y):d=JA(o,v,y,!0),o.setItemGraphicEl(c,d),d.__pictorialSymbolMeta=y,i.add(d),rD(d,v,y)}).remove(function(c){var p=s.getItemGraphicEl(c);p&&tD(s,c,p.__pictorialSymbolMeta.animationModel,p)}).execute(),this._data=o,this.group},e.prototype.remove=function(t,a){var n=this.group,i=this._data;t.get("animation")?i&&i.eachItemGraphicEl(function(o){tD(i,nt(o).dataIndex,t,o)}):n.removeAll()},e.type="pictorialBar",e}(Rt);function XA(r,e,t,a){var n=r.getItemLayout(e),i=t.get("symbolRepeat"),o=t.get("symbolClip"),s=t.get("symbolPosition")||"start",l=t.get("symbolRotate"),u=(l||0)*Math.PI/180||0,f=t.get("symbolPatternSize")||2,h=t.isAnimationEnabled(),v={dataIndex:e,layout:n,itemModel:t,symbolType:r.getItemVisual(e,"symbol")||"circle",style:r.getItemVisual(e,"style"),symbolClip:o,symbolRepeat:i,symbolRepeatDirection:t.get("symbolRepeatDirection"),symbolPatternSize:f,rotation:u,animationModel:h?t:null,hoverScale:h&&t.get(["emphasis","scale"]),z2:t.getShallow("z",!0)||0};i4(t,i,n,a,v),o4(r,e,n,i,o,v.boundingLength,v.pxSign,f,a,v),s4(t,v.symbolScale,u,a,v);var c=v.symbolSize,p=io(t.get("symbolOffset"),c);return l4(t,c,n,i,o,p,s,v.valueLineWidth,v.boundingLength,v.repeatCutLength,a,v),v}function i4(r,e,t,a,n){var i=a.valueDim,o=r.get("symbolBoundingData"),s=a.coordSys.getOtherAxis(a.coordSys.getBaseAxis()),l=s.toGlobalCoord(s.dataToCoord(0)),u=1-+(t[i.wh]<=0),f;if(z(o)){var h=[fy(s,o[0])-l,fy(s,o[1])-l];h[1]0?1:-1}function fy(r,e){return r.toGlobalCoord(r.dataToCoord(r.scale.parse(e)))}function o4(r,e,t,a,n,i,o,s,l,u){var f=l.valueDim,h=l.categoryDim,v=Math.abs(t[h.wh]),c=r.getItemVisual(e,"symbolSize"),p;z(c)?p=c.slice():c==null?p=["100%","100%"]:p=[c,c],p[h.index]=H(p[h.index],v),p[f.index]=H(p[f.index],a?v:Math.abs(i)),u.symbolSize=p;var d=u.symbolScale=[p[0]/s,p[1]/s];d[f.index]*=(l.isHorizontal?-1:1)*o}function s4(r,e,t,a,n){var i=r.get(a4)||0;i&&(uy.attr({scaleX:e[0],scaleY:e[1],rotation:t}),uy.updateTransform(),i/=uy.getLineScale(),i*=e[a.valueDim.index]),n.valueLineWidth=i||0}function l4(r,e,t,a,n,i,o,s,l,u,f,h){var v=f.categoryDim,c=f.valueDim,p=h.pxSign,d=Math.max(e[c.index]+s,0),g=d;if(a){var y=Math.abs(l),m=ee(r.get("symbolMargin"),"15%")+"",_=!1;m.lastIndexOf("!")===m.length-1&&(_=!0,m=m.slice(0,m.length-1));var S=H(m,e[c.index]),b=Math.max(d+S*2,0),x=_?0:S*2,w=ic(a),T=w?a:aD((y+x)/b),C=y-T*d;S=C/2/(_?T:Math.max(T-1,1)),b=d+S*2,x=_?0:S*2,!w&&a!=="fixed"&&(T=u?aD((Math.abs(u)+x)/b):0),g=T*b-x,h.repeatTimes=T,h.symbolMargin=S}var D=p*(g/2),M=h.pathPosition=[];M[v.index]=t[v.wh]/2,M[c.index]=o==="start"?D:o==="end"?l-D:l/2,i&&(M[0]+=i[0],M[1]+=i[1]);var I=h.bundlePosition=[];I[v.index]=t[v.xy],I[c.index]=t[c.xy];var L=h.barRectShape=B({},t);L[c.wh]=p*Math.max(Math.abs(t[c.wh]),Math.abs(M[c.index]+D)),L[v.wh]=t[v.wh];var P=h.clipShape={};P[v.xy]=-t[v.xy],P[v.wh]=f.ecSize[v.wh],P[c.xy]=0,P[c.wh]=t[c.wh]}function ZA(r){var e=r.symbolPatternSize,t=$t(r.symbolType,-e/2,-e/2,e,e);return t.attr({culling:!0}),t.type!=="image"&&t.setStyle({strokeNoScale:!0}),t}function $A(r,e,t,a){var n=r.__pictorialBundle,i=t.symbolSize,o=t.valueLineWidth,s=t.pathPosition,l=e.valueDim,u=t.repeatTimes||0,f=0,h=i[e.valueDim.index]+o+t.symbolMargin*2;for(hy(r,function(d){d.__pictorialAnimationIndex=f,d.__pictorialRepeatTimes=u,f0:y<0)&&(m=u-1-d),g[l.index]=h*(m-u/2+.5)+s[l.index],{x:g[0],y:g[1],scaleX:t.symbolScale[0],scaleY:t.symbolScale[1],rotation:t.rotation}}}function qA(r,e,t,a){var n=r.__pictorialBundle,i=r.__pictorialMainPath;i?To(i,null,{x:t.pathPosition[0],y:t.pathPosition[1],scaleX:t.symbolScale[0],scaleY:t.symbolScale[1],rotation:t.rotation},t,a):(i=r.__pictorialMainPath=ZA(t),n.add(i),To(i,{x:t.pathPosition[0],y:t.pathPosition[1],scaleX:0,scaleY:0,rotation:t.rotation},{scaleX:t.symbolScale[0],scaleY:t.symbolScale[1]},t,a))}function KA(r,e,t){var a=B({},e.barRectShape),n=r.__pictorialBarRect;n?To(n,null,{shape:a},e,t):(n=r.__pictorialBarRect=new xt({z2:2,shape:a,silent:!0,style:{stroke:"transparent",fill:"transparent",lineWidth:0}}),n.disableMorphing=!0,r.add(n))}function jA(r,e,t,a){if(t.symbolClip){var n=r.__pictorialClipPath,i=B({},t.clipShape),o=e.valueDim,s=t.animationModel,l=t.dataIndex;if(n)At(n,{shape:i},s,l);else{i[o.wh]=0,n=new xt({shape:i}),r.__pictorialBundle.setClipPath(n),r.__pictorialClipPath=n;var u={};u[o.wh]=t.clipShape[o.wh],Ms[a?"updateProps":"initProps"](n,{shape:u},s,l)}}}function QA(r,e){var t=r.getItemModel(e);return t.getAnimationDelayParams=u4,t.isAnimationEnabled=f4,t}function u4(r){return{index:r.__pictorialAnimationIndex,count:r.__pictorialRepeatTimes}}function f4(){return this.parentModel.isAnimationEnabled()&&!!this.getShallow("animation")}function JA(r,e,t,a){var n=new rt,i=new rt;return n.add(i),n.__pictorialBundle=i,i.x=t.bundlePosition[0],i.y=t.bundlePosition[1],t.symbolRepeat?$A(n,e,t):qA(n,e,t),KA(n,t,a),jA(n,e,t,a),n.__pictorialShapeStr=eD(r,t),n.__pictorialSymbolMeta=t,n}function h4(r,e,t){var a=t.animationModel,n=t.dataIndex,i=r.__pictorialBundle;At(i,{x:t.bundlePosition[0],y:t.bundlePosition[1]},a,n),t.symbolRepeat?$A(r,e,t,!0):qA(r,e,t,!0),KA(r,t,!0),jA(r,e,t,!0)}function tD(r,e,t,a){var n=a.__pictorialBarRect;n&&n.removeTextContent();var i=[];hy(a,function(o){i.push(o)}),a.__pictorialMainPath&&i.push(a.__pictorialMainPath),a.__pictorialClipPath&&(t=null),A(i,function(o){Fa(o,{scaleX:0,scaleY:0},t,e,function(){a.parent&&a.parent.remove(a)})}),r.setItemGraphicEl(e,null)}function eD(r,e){return[r.getItemVisual(e.dataIndex,"symbol")||"none",!!e.symbolRepeat,!!e.symbolClip].join(":")}function hy(r,e,t){A(r.__pictorialBundle.children(),function(a){a!==r.__pictorialBarRect&&e.call(t,a)})}function To(r,e,t,a,n,i){e&&r.attr(e),a.symbolClip&&!n?t&&r.attr(t):t&&Ms[n?"updateProps":"initProps"](r,t,a.animationModel,a.dataIndex,i)}function rD(r,e,t){var a=t.dataIndex,n=t.itemModel,i=n.getModel("emphasis"),o=i.getModel("itemStyle").getItemStyle(),s=n.getModel(["blur","itemStyle"]).getItemStyle(),l=n.getModel(["select","itemStyle"]).getItemStyle(),u=n.getShallow("cursor"),f=i.get("focus"),h=i.get("blurScope"),v=i.get("scale");hy(r,function(d){if(d instanceof ae){var g=d.style;d.useStyle(B({image:g.image,x:g.x,y:g.y,width:g.width,height:g.height},t.style))}else d.useStyle(t.style);var y=d.ensureState("emphasis");y.style=o,v&&(y.scaleX=d.scaleX*1.1,y.scaleY=d.scaleY*1.1),d.ensureState("blur").style=s,d.ensureState("select").style=l,u&&(d.cursor=u),d.z2=t.z2});var c=e.valueDim.posDesc[+(t.boundingLength>0)],p=r.__pictorialBarRect;ve(p,ne(n),{labelFetcher:e.seriesModel,labelDataIndex:a,defaultText:co(e.seriesModel.getData(),a),inheritColor:t.style.fill,defaultOpacity:t.style.opacity,defaultOutsidePosition:c}),Ut(r,f,h,i.get("disabled"))}function aD(r){var e=Math.round(r);return Math.abs(r-e)<1e-4?e:Math.ceil(r)}var v4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.hasSymbolVisual=!0,t.defaultSymbol="roundRect",t}return e.prototype.getInitialData=function(t){return t.stack=null,r.prototype.getInitialData.apply(this,arguments)},e.type="series.pictorialBar",e.dependencies=["grid"],e.defaultOption=Ua(vl.defaultOption,{symbol:"circle",symbolSize:null,symbolRotate:null,symbolPosition:null,symbolOffset:null,symbolMargin:null,symbolRepeat:!1,symbolRepeatDirection:"end",symbolClip:!1,symbolBoundingData:null,symbolPatternSize:400,barGap:"-100%",progressive:0,emphasis:{scale:!1},select:{itemStyle:{borderColor:"#212121"}}}),e}(vl);function c4(r){r.registerChartView(n4),r.registerSeriesModel(v4),r.registerLayout(r.PRIORITY.VISUAL.LAYOUT,it(wb,"pictorialBar")),r.registerLayout(r.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT,Tb("pictorialBar"))}var p4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t._layers=[],t}return e.prototype.render=function(t,a,n){var i=t.getData(),o=this,s=this.group,l=t.getLayerSeries(),u=i.getLayout("layoutInfo"),f=u.rect,h=u.boundaryGap;s.x=0,s.y=f.y+h[0];function v(g){return g.name}var c=new da(this._layersSeries||[],l,v,v),p=[];c.add(Y(d,this,"add")).update(Y(d,this,"update")).remove(Y(d,this,"remove")).execute();function d(g,y,m){var _=o._layers;if(g==="remove"){s.remove(_[y]);return}for(var S=[],b=[],x,w=l[y].indices,T=0;Ti&&(i=s),a.push(s)}for(var u=0;ui&&(i=h)}return{y0:n,max:i}}function _4(r){r.registerChartView(p4),r.registerSeriesModel(g4),r.registerLayout(y4),r.registerProcessor(cl("themeRiver"))}var S4=2,x4=4,iD=function(r){O(e,r);function e(t,a,n,i){var o=r.call(this)||this;o.z2=S4,o.textConfig={inside:!0},nt(o).seriesIndex=a.seriesIndex;var s=new bt({z2:x4,silent:t.getModel().get(["label","silent"])});return o.setTextContent(s),o.updateData(!0,t,a,n,i),o}return e.prototype.updateData=function(t,a,n,i,o){this.node=a,a.piece=this,n=n||this._seriesModel,i=i||this._ecModel;var s=this;nt(s).dataIndex=a.dataIndex;var l=a.getModel(),u=l.getModel("emphasis"),f=a.getLayout(),h=B({},f);h.label=null;var v=a.getVisual("style");v.lineJoin="bevel";var c=a.getVisual("decal");c&&(v.decal=so(c,o));var p=po(l.getModel("itemStyle"),h,!0);B(h,p),A(Me,function(m){var _=s.ensureState(m),S=l.getModel([m,"itemStyle"]);_.style=S.getItemStyle();var b=po(S,h);b&&(_.shape=b)}),t?(s.setShape(h),s.shape.r=f.r0,At(s,{shape:{r:f.r}},n,a.dataIndex)):(At(s,{shape:h},n),Cr(s)),s.useStyle(v),this._updateLabel(n);var d=l.getShallow("cursor");d&&s.attr("cursor",d),this._seriesModel=n||this._seriesModel,this._ecModel=i||this._ecModel;var g=u.get("focus"),y=g==="ancestor"?a.getAncestorsIndices():g==="descendant"?a.getDescendantIndices():g;Ut(this,y,u.get("blurScope"),u.get("disabled"))},e.prototype._updateLabel=function(t){var a=this,n=this.node.getModel(),i=n.getModel("label"),o=this.node.getLayout(),s=o.endAngle-o.startAngle,l=(o.startAngle+o.endAngle)/2,u=Math.cos(l),f=Math.sin(l),h=this,v=h.getTextContent(),c=this.node.dataIndex,p=i.get("minAngle")/180*Math.PI,d=i.get("show")&&!(p!=null&&Math.abs(s)Math.PI/2?"right":"left"):!I||I==="center"?(s===2*Math.PI&&o.r0===0?D=0:D=(o.r+o.r0)/2,I="center"):I==="left"?(D=o.r0+M,l>Math.PI/2&&(I="right")):I==="right"&&(D=o.r-M,l>Math.PI/2&&(I="left")),S.style.align=I,S.style.verticalAlign=g(m,"verticalAlign")||"middle",S.x=D*u+o.cx,S.y=D*f+o.cy;var L=g(m,"rotate"),P=0;L==="radial"?(P=-l,P<-Math.PI/2&&(P+=Math.PI)):L==="tangential"?(P=Math.PI/2-l,P>Math.PI/2?P-=Math.PI:P<-Math.PI/2&&(P+=Math.PI)):Tt(L)&&(P=L*Math.PI/180),S.rotation=P});function g(y,m){var _=y.get(m);return _==null?i.get(m):_}v.dirtyStyle()},e}(me),cy="sunburstRootToNode",oD="sunburstHighlight",b4="sunburstUnhighlight";function w4(r){r.registerAction({type:cy,update:"updateView"},function(e,t){t.eachComponent({mainType:"series",subType:"sunburst",query:e},a);function a(n,i){var o=xl(e,[cy],n);if(o){var s=n.getViewRoot();s&&(e.direction=pg(s,o.node)?"rollUp":"drillDown"),n.resetViewRoot(o.node)}}}),r.registerAction({type:oD,update:"none"},function(e,t,a){e=B({},e),t.eachComponent({mainType:"series",subType:"sunburst",query:e},n);function n(i){var o=xl(e,[oD],i);o&&(e.dataIndex=o.node.dataIndex)}a.dispatchAction(B(e,{type:"highlight"}))}),r.registerAction({type:b4,update:"updateView"},function(e,t,a){e=B({},e),a.dispatchAction(B(e,{type:"downplay"}))})}var T4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n,i){var o=this;this.seriesModel=t,this.api=n,this.ecModel=a;var s=t.getData(),l=s.tree.root,u=t.getViewRoot(),f=this.group,h=t.get("renderLabelForZeroData"),v=[];u.eachNode(function(m){v.push(m)});var c=this._oldChildren||[];p(v,c),y(l,u),this._initEvents(),this._oldChildren=v;function p(m,_){if(m.length===0&&_.length===0)return;new da(_,m,S,S).add(b).update(b).remove(it(b,null)).execute();function S(x){return x.getId()}function b(x,w){var T=x==null?null:m[x],C=w==null?null:_[w];d(T,C)}}function d(m,_){if(!h&&m&&!m.getValue()&&(m=null),m!==l&&_!==l){if(_&&_.piece)m?(_.piece.updateData(!1,m,t,a,n),s.setItemGraphicEl(m.dataIndex,_.piece)):g(_);else if(m){var S=new iD(m,t,a,n);f.add(S),s.setItemGraphicEl(m.dataIndex,S)}}}function g(m){!m||m.piece&&(f.remove(m.piece),m.piece=null)}function y(m,_){_.depth>0?(o.virtualPiece?o.virtualPiece.updateData(!1,m,t,a,n):(o.virtualPiece=new iD(m,t,a,n),f.add(o.virtualPiece)),_.piece.off("click"),o.virtualPiece.on("click",function(S){o._rootToNode(_.parentNode)})):o.virtualPiece&&(f.remove(o.virtualPiece),o.virtualPiece=null)}},e.prototype._initEvents=function(){var t=this;this.group.off("click"),this.group.on("click",function(a){var n=!1,i=t.seriesModel.getViewRoot();i.eachNode(function(o){if(!n&&o.piece&&o.piece===a.target){var s=o.getModel().get("nodeClick");if(s==="rootToNode")t._rootToNode(o);else if(s==="link"){var l=o.getModel(),u=l.get("link");if(u){var f=l.get("target",!0)||"_blank";sf(u,f)}}n=!0}})})},e.prototype._rootToNode=function(t){t!==this.seriesModel.getViewRoot()&&this.api.dispatchAction({type:cy,from:this.uid,seriesId:this.seriesModel.id,targetNode:t})},e.prototype.containPoint=function(t,a){var n=a.getData(),i=n.getItemLayout(0);if(i){var o=t[0]-i.cx,s=t[1]-i.cy,l=Math.sqrt(o*o+s*s);return l<=i.r&&l>=i.r0}},e.type="sunburst",e}(Rt),C4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.ignoreStyleOnData=!0,t}return e.prototype.getInitialData=function(t,a){var n={name:t.name,children:t.data};sD(n);var i=this._levelModels=G(t.levels||[],function(l){return new Mt(l,this,a)},this),o=cg.createTree(n,this,s);function s(l){l.wrapMethod("getItemModel",function(u,f){var h=o.getNodeByDataIndex(f),v=i[h.depth];return v&&(u.parentModel=v),u})}return o.data},e.prototype.optionUpdated=function(){this.resetViewRoot()},e.prototype.getDataParams=function(t){var a=r.prototype.getDataParams.apply(this,arguments),n=this.getData().tree.getNodeByDataIndex(t);return a.treePathInfo=vh(n,this),a},e.prototype.getLevelModel=function(t){return this._levelModels&&this._levelModels[t.depth]},e.prototype.getViewRoot=function(){return this._viewRoot},e.prototype.resetViewRoot=function(t){t?this._viewRoot=t:t=this._viewRoot;var a=this.getRawData().tree.root;(!t||t!==a&&!a.contains(t))&&(this._viewRoot=a)},e.prototype.enableAriaDecal=function(){SC(this)},e.type="series.sunburst",e.defaultOption={z:2,center:["50%","50%"],radius:[0,"75%"],clockwise:!0,startAngle:90,minAngle:0,stillShowZeroSum:!0,nodeClick:"rootToNode",renderLabelForZeroData:!1,label:{rotate:"radial",show:!0,opacity:1,align:"center",position:"inside",distance:5,silent:!0},itemStyle:{borderWidth:1,borderColor:"white",borderType:"solid",shadowBlur:0,shadowColor:"rgba(0, 0, 0, 0.2)",shadowOffsetX:0,shadowOffsetY:0,opacity:1},emphasis:{focus:"descendant"},blur:{itemStyle:{opacity:.2},label:{opacity:.1}},animationType:"expansion",animationDuration:1e3,animationDurationUpdate:500,data:[],sort:"desc"},e}(kt);function sD(r){var e=0;A(r.children,function(a){sD(a);var n=a.value;z(n)&&(n=n[0]),e+=n});var t=r.value;z(t)&&(t=t[0]),(t==null||isNaN(t))&&(t=e),t<0&&(t=0),z(r.value)?r.value[0]=t:r.value=t}var lD=Math.PI/180;function A4(r,e,t){e.eachSeriesByType(r,function(a){var n=a.get("center"),i=a.get("radius");z(i)||(i=[0,i]),z(n)||(n=[n,n]);var o=t.getWidth(),s=t.getHeight(),l=Math.min(o,s),u=H(n[0],o),f=H(n[1],s),h=H(i[0],l/2),v=H(i[1],l/2),c=-a.get("startAngle")*lD,p=a.get("minAngle")*lD,d=a.getData().tree.root,g=a.getViewRoot(),y=g.depth,m=a.get("sort");m!=null&&uD(g,m);var _=0;A(g.children,function(E){!isNaN(E.getValue())&&_++});var S=g.getValue(),b=Math.PI/(S||_)*2,x=g.depth>0,w=g.height-(x?-1:1),T=(v-h)/(w||1),C=a.get("clockwise"),D=a.get("stillShowZeroSum"),M=C?1:-1,I=function(E,N){if(!!E){var k=N;if(E!==d){var V=E.getValue(),F=S===0&&D?b:V*b;F1;)o=o.parentNode;var s=n.getColorFromPalette(o.name||o.dataIndex+"",e);return a.depth>1&&U(s)&&(s=uu(s,(a.depth-1)/(i-1)*.5)),s}r.eachSeriesByType("sunburst",function(a){var n=a.getData(),i=n.tree;i.eachNode(function(o){var s=o.getModel(),l=s.getModel("itemStyle").getItemStyle();l.fill||(l.fill=t(o,a,i.root.height));var u=n.ensureUniqueItemVisual(o.dataIndex,"style");B(u,l)})})}function I4(r){r.registerChartView(T4),r.registerSeriesModel(C4),r.registerLayout(it(A4,"sunburst")),r.registerProcessor(it(cl,"sunburst")),r.registerVisual(M4),w4(r)}var fD={color:"fill",borderColor:"stroke"},L4={symbol:1,symbolSize:1,symbolKeepAspect:1,legendIcon:1,visualMeta:1,liftZ:1,decal:1},Sa=Ct(),P4=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.optionUpdated=function(){this.currentZLevel=this.get("zlevel",!0),this.currentZ=this.get("z",!0)},e.prototype.getInitialData=function(t,a){return Xr(null,this)},e.prototype.getDataParams=function(t,a,n){var i=r.prototype.getDataParams.call(this,t,a);return n&&(i.info=Sa(n).info),i},e.type="series.custom",e.dependencies=["grid","polar","geo","singleAxis","calendar"],e.defaultOption={coordinateSystem:"cartesian2d",z:2,legendHoverLink:!0,clip:!1},e}(kt);function R4(r,e){return e=e||[0,0],G(["x","y"],function(t,a){var n=this.getAxis(t),i=e[a],o=r[a]/2;return n.type==="category"?n.getBandWidth():Math.abs(n.dataToCoord(i-o)-n.dataToCoord(i+o))},this)}function E4(r){var e=r.master.getRect();return{coordSys:{type:"cartesian2d",x:e.x,y:e.y,width:e.width,height:e.height},api:{coord:function(t){return r.dataToPoint(t)},size:Y(R4,r)}}}function k4(r,e){return e=e||[0,0],G([0,1],function(t){var a=e[t],n=r[t]/2,i=[],o=[];return i[t]=a-n,o[t]=a+n,i[1-t]=o[1-t]=e[1-t],Math.abs(this.dataToPoint(i)[t]-this.dataToPoint(o)[t])},this)}function O4(r){var e=r.getBoundingRect();return{coordSys:{type:"geo",x:e.x,y:e.y,width:e.width,height:e.height,zoom:r.getZoom()},api:{coord:function(t){return r.dataToPoint(t)},size:Y(k4,r)}}}function N4(r,e){var t=this.getAxis(),a=e instanceof Array?e[0]:e,n=(r instanceof Array?r[0]:r)/2;return t.type==="category"?t.getBandWidth():Math.abs(t.dataToCoord(a-n)-t.dataToCoord(a+n))}function B4(r){var e=r.getRect();return{coordSys:{type:"singleAxis",x:e.x,y:e.y,width:e.width,height:e.height},api:{coord:function(t){return r.dataToPoint(t)},size:Y(N4,r)}}}function V4(r,e){return e=e||[0,0],G(["Radius","Angle"],function(t,a){var n="get"+t+"Axis",i=this[n](),o=e[a],s=r[a]/2,l=i.type==="category"?i.getBandWidth():Math.abs(i.dataToCoord(o-s)-i.dataToCoord(o+s));return t==="Angle"&&(l=l*Math.PI/180),l},this)}function z4(r){var e=r.getRadiusAxis(),t=r.getAngleAxis(),a=e.getExtent();return a[0]>a[1]&&a.reverse(),{coordSys:{type:"polar",cx:r.cx,cy:r.cy,r:a[1],r0:a[0]},api:{coord:function(n){var i=e.dataToRadius(n[0]),o=t.dataToAngle(n[1]),s=r.coordToPoint([i,o]);return s.push(i,o*Math.PI/180),s},size:Y(V4,r)}}}function G4(r){var e=r.getRect(),t=r.getRangeInfo();return{coordSys:{type:"calendar",x:e.x,y:e.y,width:e.width,height:e.height,cellWidth:r.getCellWidth(),cellHeight:r.getCellHeight(),rangeInfo:{start:t.start,end:t.end,weeks:t.weeks,dayCount:t.allDay}},api:{coord:function(a,n){return r.dataToPoint(a,n)}}}}function hD(r,e,t,a){return r&&(r.legacy||r.legacy!==!1&&!t&&!a&&e!=="tspan"&&(e==="text"||X(r,"text")))}function vD(r,e,t){var a=r,n,i,o;if(e==="text")o=a;else{o={},X(a,"text")&&(o.text=a.text),X(a,"rich")&&(o.rich=a.rich),X(a,"textFill")&&(o.fill=a.textFill),X(a,"textStroke")&&(o.stroke=a.textStroke),X(a,"fontFamily")&&(o.fontFamily=a.fontFamily),X(a,"fontSize")&&(o.fontSize=a.fontSize),X(a,"fontStyle")&&(o.fontStyle=a.fontStyle),X(a,"fontWeight")&&(o.fontWeight=a.fontWeight),i={type:"text",style:o,silent:!0},n={};var s=X(a,"textPosition");t?n.position=s?a.textPosition:"inside":s&&(n.position=a.textPosition),X(a,"textPosition")&&(n.position=a.textPosition),X(a,"textOffset")&&(n.offset=a.textOffset),X(a,"textRotation")&&(n.rotation=a.textRotation),X(a,"textDistance")&&(n.distance=a.textDistance)}return cD(o,r),A(o.rich,function(l){cD(l,l)}),{textConfig:n,textContent:i}}function cD(r,e){!e||(e.font=e.textFont||e.font,X(e,"textStrokeWidth")&&(r.lineWidth=e.textStrokeWidth),X(e,"textAlign")&&(r.align=e.textAlign),X(e,"textVerticalAlign")&&(r.verticalAlign=e.textVerticalAlign),X(e,"textLineHeight")&&(r.lineHeight=e.textLineHeight),X(e,"textWidth")&&(r.width=e.textWidth),X(e,"textHeight")&&(r.height=e.textHeight),X(e,"textBackgroundColor")&&(r.backgroundColor=e.textBackgroundColor),X(e,"textPadding")&&(r.padding=e.textPadding),X(e,"textBorderColor")&&(r.borderColor=e.textBorderColor),X(e,"textBorderWidth")&&(r.borderWidth=e.textBorderWidth),X(e,"textBorderRadius")&&(r.borderRadius=e.textBorderRadius),X(e,"textBoxShadowColor")&&(r.shadowColor=e.textBoxShadowColor),X(e,"textBoxShadowBlur")&&(r.shadowBlur=e.textBoxShadowBlur),X(e,"textBoxShadowOffsetX")&&(r.shadowOffsetX=e.textBoxShadowOffsetX),X(e,"textBoxShadowOffsetY")&&(r.shadowOffsetY=e.textBoxShadowOffsetY))}function pD(r,e,t){var a=r;a.textPosition=a.textPosition||t.position||"inside",t.offset!=null&&(a.textOffset=t.offset),t.rotation!=null&&(a.textRotation=t.rotation),t.distance!=null&&(a.textDistance=t.distance);var n=a.textPosition.indexOf("inside")>=0,i=r.fill||"#000";dD(a,e);var o=a.textFill==null;return n?o&&(a.textFill=t.insideFill||"#fff",!a.textStroke&&t.insideStroke&&(a.textStroke=t.insideStroke),!a.textStroke&&(a.textStroke=i),a.textStrokeWidth==null&&(a.textStrokeWidth=2)):(o&&(a.textFill=r.fill||t.outsideFill||"#000"),!a.textStroke&&t.outsideStroke&&(a.textStroke=t.outsideStroke)),a.text=e.text,a.rich=e.rich,A(e.rich,function(s){dD(s,s)}),a}function dD(r,e){!e||(X(e,"fill")&&(r.textFill=e.fill),X(e,"stroke")&&(r.textStroke=e.fill),X(e,"lineWidth")&&(r.textStrokeWidth=e.lineWidth),X(e,"font")&&(r.font=e.font),X(e,"fontStyle")&&(r.fontStyle=e.fontStyle),X(e,"fontWeight")&&(r.fontWeight=e.fontWeight),X(e,"fontSize")&&(r.fontSize=e.fontSize),X(e,"fontFamily")&&(r.fontFamily=e.fontFamily),X(e,"align")&&(r.textAlign=e.align),X(e,"verticalAlign")&&(r.textVerticalAlign=e.verticalAlign),X(e,"lineHeight")&&(r.textLineHeight=e.lineHeight),X(e,"width")&&(r.textWidth=e.width),X(e,"height")&&(r.textHeight=e.height),X(e,"backgroundColor")&&(r.textBackgroundColor=e.backgroundColor),X(e,"padding")&&(r.textPadding=e.padding),X(e,"borderColor")&&(r.textBorderColor=e.borderColor),X(e,"borderWidth")&&(r.textBorderWidth=e.borderWidth),X(e,"borderRadius")&&(r.textBorderRadius=e.borderRadius),X(e,"shadowColor")&&(r.textBoxShadowColor=e.shadowColor),X(e,"shadowBlur")&&(r.textBoxShadowBlur=e.shadowBlur),X(e,"shadowOffsetX")&&(r.textBoxShadowOffsetX=e.shadowOffsetX),X(e,"shadowOffsetY")&&(r.textBoxShadowOffsetY=e.shadowOffsetY),X(e,"textShadowColor")&&(r.textShadowColor=e.textShadowColor),X(e,"textShadowBlur")&&(r.textShadowBlur=e.textShadowBlur),X(e,"textShadowOffsetX")&&(r.textShadowOffsetX=e.textShadowOffsetX),X(e,"textShadowOffsetY")&&(r.textShadowOffsetY=e.textShadowOffsetY))}var gD={position:["x","y"],scale:["scaleX","scaleY"],origin:["originX","originY"]},yD=St(gD),x7=qe(la,function(r,e){return r[e]=1,r},{}),Ch=["","style","shape","extra"],Co=Ct();function py(r,e,t,a,n){var i=r+"Animation",o=Fi(r,a,n)||{},s=Co(e).userDuring;return o.duration>0&&(o.during=s?Y(Y4,{el:e,userDuring:s}):null,o.setToFinal=!0,o.scope=r),B(o,t[i]),o}function Ah(r,e,t,a){a=a||{};var n=a.dataIndex,i=a.isInit,o=a.clearStyle,s=t.isAnimationEnabled(),l=Co(r),u=e.style;l.userDuring=e.during;var f={},h={};if(Z4(r,e,h),SD("shape",e,h),SD("extra",e,h),!i&&s&&(X4(r,e,f),_D("shape",r,e,f),_D("extra",r,e,f),$4(r,e,u,f)),h.style=u,F4(r,h,o),W4(r,e),s)if(i){var v={};A(Ch,function(p){var d=p?e[p]:e;d&&d.enterFrom&&(p&&(v[p]=v[p]||{}),B(p?v[p]:v,d.enterFrom))});var c=py("enter",r,e,t,n);c.duration>0&&r.animateFrom(v,c)}else H4(r,e,n||0,t,f);mD(r,e),u?r.dirty():r.markRedraw()}function mD(r,e){for(var t=Co(r).leaveToProps,a=0;a0&&r.animateFrom(n,i)}}function W4(r,e){X(e,"silent")&&(r.silent=e.silent),X(e,"ignore")&&(r.ignore=e.ignore),r instanceof er&&X(e,"invisible")&&(r.invisible=e.invisible),r instanceof dt&&X(e,"autoBatch")&&(r.autoBatch=e.autoBatch)}var Qr={},U4={setTransform:function(r,e){return Qr.el[r]=e,this},getTransform:function(r){return Qr.el[r]},setShape:function(r,e){var t=Qr.el,a=t.shape||(t.shape={});return a[r]=e,t.dirtyShape&&t.dirtyShape(),this},getShape:function(r){var e=Qr.el.shape;if(e)return e[r]},setStyle:function(r,e){var t=Qr.el,a=t.style;return a&&(a[r]=e,t.dirtyStyle&&t.dirtyStyle()),this},getStyle:function(r){var e=Qr.el.style;if(e)return e[r]},setExtra:function(r,e){var t=Qr.el.extra||(Qr.el.extra={});return t[r]=e,this},getExtra:function(r){var e=Qr.el.extra;if(e)return e[r]}};function Y4(){var r=this,e=r.el;if(!!e){var t=Co(e).userDuring,a=r.userDuring;if(t!==a){r.el=r.userDuring=null;return}Qr.el=e,a(U4)}}function _D(r,e,t,a){var n=t[r];if(!!n){var i=e[r],o;if(i){var s=t.transition,l=n.transition;if(l)if(!o&&(o=a[r]={}),pi(l))B(o,i);else for(var u=Et(l),f=0;f=0){!o&&(o=a[r]={});for(var c=St(i),f=0;f=0)){var v=r.getAnimationStyleProps(),c=v?v.style:null;if(c){!i&&(i=a.style={});for(var p=St(t),u=0;u=0?e.getStore().get(N,R):void 0}var k=e.get(E.name,R),V=E&&E.ordinalMeta;return V?V.categories[k]:k}function x(P,R){R==null&&(R=u);var E=e.getItemVisual(R,"style"),N=E&&E.fill,k=E&&E.opacity,V=m(R,nn).getItemStyle();N!=null&&(V.fill=N),k!=null&&(V.opacity=k);var F={inheritColor:U(N)?N:"#000"},W=_(R,nn),Z=Nt(W,null,F,!1,!0);Z.text=W.getShallow("show")?lt(r.getFormattedLabel(R,nn),co(e,R)):null;var Q=Qu(W,F,!1);return C(P,V),V=pD(V,Z,Q),P&&T(V,P),V.legacy=!0,V}function w(P,R){R==null&&(R=u);var E=m(R,xa).getItemStyle(),N=_(R,xa),k=Nt(N,null,null,!0,!0);k.text=N.getShallow("show")?Er(r.getFormattedLabel(R,xa),r.getFormattedLabel(R,nn),co(e,R)):null;var V=Qu(N,null,!0);return C(P,E),E=pD(E,k,V),P&&T(E,P),E.legacy=!0,E}function T(P,R){for(var E in R)X(R,E)&&(P[E]=R[E])}function C(P,R){P&&(P.textFill&&(R.textFill=P.textFill),P.textPosition&&(R.textPosition=P.textPosition))}function D(P,R){if(R==null&&(R=u),X(fD,P)){var E=e.getItemVisual(R,"style");return E?E[fD[P]]:null}if(X(L4,P))return e.getItemVisual(R,P)}function M(P){if(i.type==="cartesian2d"){var R=i.getBaseAxis();return ON(j({axis:R},P))}}function I(){return t.getCurrentSeriesIndices()}function L(P){return T1(P,t)}}function nW(r){var e={};return A(r.dimensions,function(t){var a=r.getDimensionInfo(t);if(!a.isExtraCoord){var n=a.coordDim,i=e[n]=e[n]||[];i[a.coordDimIndex]=r.getDimensionIndex(t)}}),e}function wy(r,e,t,a,n,i,o){if(!a){i.remove(e);return}var s=Ty(r,e,t,a,n,i);return s&&o.setItemGraphicEl(t,s),s&&Ut(s,a.focus,a.blurScope,a.emphasisDisabled),s}function Ty(r,e,t,a,n,i){var o=-1,s=e;e&&CD(e,a,n)&&(o=vt(i.childrenRef(),e),e=null);var l=!e,u=e;u?u.clearStates():(u=xy(a),s&&tW(s,u)),a.morph===!1?u.disableMorphing=!0:u.disableMorphing&&(u.disableMorphing=!1),pr.normal.cfg=pr.normal.conOpt=pr.emphasis.cfg=pr.emphasis.conOpt=pr.blur.cfg=pr.blur.conOpt=pr.select.cfg=pr.select.conOpt=null,pr.isLegacy=!1,oW(u,t,a,n,l,pr),iW(u,t,a,n,l),by(r,u,t,a,pr,n,l),X(a,"info")&&(Sa(u).info=a.info);for(var f=0;f=0?i.replaceAt(u,o):i.add(u),u}function CD(r,e,t){var a=Sa(r),n=e.type,i=e.shape,o=e.style;return t.isUniversalTransitionEnabled()||n!=null&&n!==a.customGraphicType||n==="path"&&hW(i)&&ID(i)!==a.customPathData||n==="image"&&X(o,"image")&&o.image!==a.customImagePath}function iW(r,e,t,a,n){var i=t.clipPath;if(i===!1)r&&r.getClipPath()&&r.removeClipPath();else if(i){var o=r.getClipPath();o&&CD(o,i,a)&&(o=null),o||(o=xy(i),r.setClipPath(o)),by(null,o,e,i,null,a,n)}}function oW(r,e,t,a,n,i){if(!r.isGroup){AD(t,null,i),AD(t,xa,i);var o=i.normal.conOpt,s=i.emphasis.conOpt,l=i.blur.conOpt,u=i.select.conOpt;if(o!=null||s!=null||u!=null||l!=null){var f=r.getTextContent();if(o===!1)f&&r.removeTextContent();else{o=i.normal.conOpt=o||{type:"text"},f?f.clearStates():(f=xy(o),r.setTextContent(f)),by(null,f,e,o,null,a,n);for(var h=o&&o.style,v=0;v=f;c--){var p=e.childAt(c);lW(e,p,n)}}}function lW(r,e,t){e&&Dh(e,Sa(r).option,t)}function uW(r){new da(r.oldChildren,r.newChildren,DD,DD,r).add(MD).update(MD).remove(fW).execute()}function DD(r,e){var t=r&&r.name;return t!=null?t:Q4+e}function MD(r,e){var t=this.context,a=r!=null?t.newChildren[r]:null,n=e!=null?t.oldChildren[e]:null;Ty(t.api,n,t.dataIndex,a,t.seriesModel,t.group)}function fW(r){var e=this.context,t=e.oldChildren[r];t&&Dh(t,Sa(t).option,e.seriesModel)}function ID(r){return r&&(r.pathData||r.d)}function hW(r){return r&&(X(r,"pathData")||X(r,"d"))}function vW(r){r.registerChartView(eW),r.registerSeriesModel(P4)}var di=Ct(),LD=et,Ay=Y,Dy=function(){function r(){this._dragging=!1,this.animationThreshold=15}return r.prototype.render=function(e,t,a,n){var i=t.get("value"),o=t.get("status");if(this._axisModel=e,this._axisPointerModel=t,this._api=a,!(!n&&this._lastValue===i&&this._lastStatus===o)){this._lastValue=i,this._lastStatus=o;var s=this._group,l=this._handle;if(!o||o==="hide"){s&&s.hide(),l&&l.hide();return}s&&s.show(),l&&l.show();var u={};this.makeElOption(u,i,e,t,a);var f=u.graphicKey;f!==this._lastGraphicKey&&this.clear(a),this._lastGraphicKey=f;var h=this._moveAnimation=this.determineAnimation(e,t);if(!s)s=this._group=new rt,this.createPointerEl(s,u,e,t),this.createLabelEl(s,u,e,t),a.getZr().add(s);else{var v=it(PD,t,h);this.updatePointerEl(s,u,v),this.updateLabelEl(s,u,v,t)}kD(s,t,!0),this._renderHandle(i)}},r.prototype.remove=function(e){this.clear(e)},r.prototype.dispose=function(e){this.clear(e)},r.prototype.determineAnimation=function(e,t){var a=t.get("animation"),n=e.axis,i=n.type==="category",o=t.get("snap");if(!o&&!i)return!1;if(a==="auto"||a==null){var s=this.animationThreshold;if(i&&n.getBandWidth()>s)return!0;if(o){var l=Kd(e).seriesDataCount,u=n.getExtent();return Math.abs(u[0]-u[1])/l>s}return!1}return a===!0},r.prototype.makeElOption=function(e,t,a,n,i){},r.prototype.createPointerEl=function(e,t,a,n){var i=t.pointer;if(i){var o=di(e).pointerEl=new Ms[i.type](LD(t.pointer));e.add(o)}},r.prototype.createLabelEl=function(e,t,a,n){if(t.label){var i=di(e).labelEl=new bt(LD(t.label));e.add(i),ED(i,n)}},r.prototype.updatePointerEl=function(e,t,a){var n=di(e).pointerEl;n&&t.pointer&&(n.setStyle(t.pointer.style),a(n,{shape:t.pointer.shape}))},r.prototype.updateLabelEl=function(e,t,a,n){var i=di(e).labelEl;i&&(i.setStyle(t.label.style),a(i,{x:t.label.x,y:t.label.y}),ED(i,n))},r.prototype._renderHandle=function(e){if(!(this._dragging||!this.updateHandleTransform)){var t=this._axisPointerModel,a=this._api.getZr(),n=this._handle,i=t.getModel("handle"),o=t.get("status");if(!i.get("show")||!o||o==="hide"){n&&a.remove(n),this._handle=null;return}var s;this._handle||(s=!0,n=this._handle=Ui(i.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(u){ia(u.event)},onmousedown:Ay(this._onHandleDragMove,this,0,0),drift:Ay(this._onHandleDragMove,this),ondragend:Ay(this._onHandleDragEnd,this)}),a.add(n)),kD(n,t,!1),n.setStyle(i.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var l=i.get("size");z(l)||(l=[l,l]),n.scaleX=l[0]/2,n.scaleY=l[1]/2,ao(this,"_doDispatchAxisPointer",i.get("throttle")||0,"fixRate"),this._moveHandleToValue(e,s)}},r.prototype._moveHandleToValue=function(e,t){PD(this._axisPointerModel,!t&&this._moveAnimation,this._handle,My(this.getHandleTransform(e,this._axisModel,this._axisPointerModel)))},r.prototype._onHandleDragMove=function(e,t){var a=this._handle;if(!!a){this._dragging=!0;var n=this.updateHandleTransform(My(a),[e,t],this._axisModel,this._axisPointerModel);this._payloadInfo=n,a.stopAnimation(),a.attr(My(n)),di(a).lastProp=null,this._doDispatchAxisPointer()}},r.prototype._doDispatchAxisPointer=function(){var e=this._handle;if(!!e){var t=this._payloadInfo,a=this._axisModel;this._api.dispatchAction({type:"updateAxisPointer",x:t.cursorPoint[0],y:t.cursorPoint[1],tooltipOption:t.tooltipOption,axesInfo:[{axisDim:a.axis.dim,axisIndex:a.componentIndex}]})}},r.prototype._onHandleDragEnd=function(){this._dragging=!1;var e=this._handle;if(!!e){var t=this._axisPointerModel.get("value");this._moveHandleToValue(t),this._api.dispatchAction({type:"hideTip"})}},r.prototype.clear=function(e){this._lastValue=null,this._lastStatus=null;var t=e.getZr(),a=this._group,n=this._handle;t&&a&&(this._lastGraphicKey=null,a&&t.remove(a),n&&t.remove(n),this._group=null,this._handle=null,this._payloadInfo=null),Fs(this,"_doDispatchAxisPointer")},r.prototype.doClear=function(){},r.prototype.buildLabel=function(e,t,a){return a=a||0,{x:e[a],y:e[1-a],width:t[a],height:t[1-a]}},r}();function PD(r,e,t,a){RD(di(t).lastProp,a)||(di(t).lastProp=a,e?At(t,a,r):(t.stopAnimation(),t.attr(a)))}function RD(r,e){if(J(r)&&J(e)){var t=!0;return A(e,function(a,n){t=t&&RD(r[n],a)}),!!t}else return r===e}function ED(r,e){r[e.get(["label","show"])?"show":"hide"]()}function My(r){return{x:r.x||0,y:r.y||0,rotation:r.rotation||0}}function kD(r,e,t){var a=e.get("z"),n=e.get("zlevel");r&&r.traverse(function(i){i.type!=="group"&&(a!=null&&(i.z=a),n!=null&&(i.zlevel=n),i.silent=t)})}function Iy(r){var e=r.get("type"),t=r.getModel(e+"Style"),a;return e==="line"?(a=t.getLineStyle(),a.fill=null):e==="shadow"&&(a=t.getAreaStyle(),a.stroke=null),a}function OD(r,e,t,a,n){var i=t.get("value"),o=ND(i,e.axis,e.ecModel,t.get("seriesDataIndices"),{precision:t.get(["label","precision"]),formatter:t.get(["label","formatter"])}),s=t.getModel("label"),l=Vn(s.get("padding")||0),u=s.getFont(),f=is(o,u),h=n.position,v=f.width+l[1]+l[3],c=f.height+l[0]+l[2],p=n.align;p==="right"&&(h[0]-=v),p==="center"&&(h[0]-=v/2);var d=n.verticalAlign;d==="bottom"&&(h[1]-=c),d==="middle"&&(h[1]-=c/2),cW(h,v,c,a);var g=s.get("backgroundColor");(!g||g==="auto")&&(g=e.get(["axisLine","lineStyle","color"])),r.label={x:h[0],y:h[1],style:Nt(s,{text:o,font:u,fill:s.getTextColor(),padding:l,backgroundColor:g}),z2:10}}function cW(r,e,t,a){var n=a.getWidth(),i=a.getHeight();r[0]=Math.min(r[0]+e,n)-e,r[1]=Math.min(r[1]+t,i)-t,r[0]=Math.max(r[0],0),r[1]=Math.max(r[1],0)}function ND(r,e,t,a,n){r=e.scale.parse(r);var i=e.scale.getLabel({value:r},{precision:n.precision}),o=n.formatter;if(o){var s={value:yd(e,{value:r}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};A(a,function(l){var u=t.getSeriesByIndex(l.seriesIndex),f=l.dataIndexInside,h=u&&u.getDataParams(f);h&&s.seriesData.push(h)}),U(o)?i=o.replace("{value}",i):K(o)&&(i=o(s))}return i}function Ly(r,e,t){var a=Ge();return Ia(a,a,t.rotation),mr(a,a,t.position),Ar([r.dataToCoord(e),(t.labelOffset||0)+(t.labelDirection||1)*(t.labelMargin||0)],a)}function BD(r,e,t,a,n,i){var o=Pe.innerTextLayout(t.rotation,0,t.labelDirection);t.labelMargin=n.get(["label","margin"]),OD(e,a,n,i,{position:Ly(a.axis,r,t),align:o.textAlign,verticalAlign:o.textVerticalAlign})}function Py(r,e,t){return t=t||0,{x1:r[t],y1:r[1-t],x2:e[t],y2:e[1-t]}}function VD(r,e,t){return t=t||0,{x:r[t],y:r[1-t],width:e[t],height:e[1-t]}}function zD(r,e,t,a,n,i){return{cx:r,cy:e,r0:t,r:a,startAngle:n,endAngle:i,clockwise:!0}}var pW=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.makeElOption=function(t,a,n,i,o){var s=n.axis,l=s.grid,u=i.get("type"),f=GD(l,s).getOtherAxis(s).getGlobalExtent(),h=s.toGlobalCoord(s.dataToCoord(a,!0));if(u&&u!=="none"){var v=Iy(i),c=dW[u](s,h,f);c.style=v,t.graphicKey=c.type,t.pointer=c}var p=Xd(l.model,n);BD(a,t,p,n,i,o)},e.prototype.getHandleTransform=function(t,a,n){var i=Xd(a.axis.grid.model,a,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var o=Ly(a.axis,t,i);return{x:o[0],y:o[1],rotation:i.rotation+(i.labelDirection<0?Math.PI:0)}},e.prototype.updateHandleTransform=function(t,a,n,i){var o=n.axis,s=o.grid,l=o.getGlobalExtent(!0),u=GD(s,o).getOtherAxis(o).getGlobalExtent(),f=o.dim==="x"?0:1,h=[t.x,t.y];h[f]+=a[f],h[f]=Math.min(l[1],h[f]),h[f]=Math.max(l[0],h[f]);var v=(u[1]+u[0])/2,c=[v,v];c[f]=h[f];var p=[{verticalAlign:"middle"},{align:"center"}];return{x:h[0],y:h[1],rotation:t.rotation,cursorPoint:c,tooltipOption:p[f]}},e}(Dy);function GD(r,e){var t={};return t[e.dim+"AxisIndex"]=e.index,r.getCartesian(t)}var dW={line:function(r,e,t){var a=Py([e,t[0]],[e,t[1]],FD(r));return{type:"Line",subPixelOptimize:!0,shape:a}},shadow:function(r,e,t){var a=Math.max(1,r.getBandWidth()),n=t[1]-t[0];return{type:"Rect",shape:VD([e-a/2,t[0]],[a,n],FD(r))}}};function FD(r){return r.dim==="x"?0:1}var gW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="axisPointer",e.defaultOption={show:"auto",z:50,type:"line",snap:!1,triggerTooltip:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:"#B9BEC9",width:1,type:"dashed"},shadowStyle:{color:"rgba(210,219,238,0.2)"},label:{show:!0,formatter:null,precision:"auto",margin:3,color:"#fff",padding:[5,7,5,7],backgroundColor:"auto",borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:"M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z",size:45,margin:50,color:"#333",shadowBlur:3,shadowColor:"#aaa",shadowOffsetX:0,shadowOffsetY:2,throttle:40}},e}(gt),ba=Ct(),yW=A;function HD(r,e,t){if(!_t.node){var a=e.getZr();ba(a).records||(ba(a).records={}),mW(a,e);var n=ba(a).records[r]||(ba(a).records[r]={});n.handler=t}}function mW(r,e){if(ba(r).initialized)return;ba(r).initialized=!0,t("click",it(WD,"click")),t("mousemove",it(WD,"mousemove")),t("globalout",SW);function t(a,n){r.on(a,function(i){var o=xW(e);yW(ba(r).records,function(s){s&&n(s,i,o.dispatchAction)}),_W(o.pendings,e)})}}function _W(r,e){var t=r.showTip.length,a=r.hideTip.length,n;t?n=r.showTip[t-1]:a&&(n=r.hideTip[a-1]),n&&(n.dispatchAction=null,e.dispatchAction(n))}function SW(r,e,t){r.handler("leave",null,t)}function WD(r,e,t,a){e.handler(r,t,a)}function xW(r){var e={showTip:[],hideTip:[]},t=function(a){var n=e[a.type];n?n.push(a):(a.dispatchAction=t,r.dispatchAction(a))};return{dispatchAction:t,pendings:e}}function Ry(r,e){if(!_t.node){var t=e.getZr(),a=(ba(t).records||{})[r];a&&(ba(t).records[r]=null)}}var bW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=a.getComponent("tooltip"),o=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";HD("axisPointer",n,function(s,l,u){o!=="none"&&(s==="leave"||o.indexOf(s)>=0)&&u({type:"updateAxisPointer",currTrigger:s,x:l&&l.offsetX,y:l&&l.offsetY})})},e.prototype.remove=function(t,a){Ry("axisPointer",a)},e.prototype.dispose=function(t,a){Ry("axisPointer",a)},e.type="axisPointer",e}(Bt);function UD(r,e){var t=[],a=r.seriesIndex,n;if(a==null||!(n=e.getSeriesByIndex(a)))return{point:[]};var i=n.getData(),o=xn(i,r);if(o==null||o<0||z(o))return{point:[]};var s=i.getItemGraphicEl(o),l=n.coordinateSystem;if(n.getTooltipPosition)t=n.getTooltipPosition(o)||[];else if(l&&l.dataToPoint)if(r.isStacked){var u=l.getBaseAxis(),f=l.getOtherAxis(u),h=f.dim,v=u.dim,c=h==="x"||h==="radius"?1:0,p=i.mapDimension(v),d=[];d[c]=i.get(p,o),d[1-c]=i.get(i.getCalculationInfo("stackResultDimension"),o),t=l.dataToPoint(d)||[]}else t=l.dataToPoint(i.getValues(G(l.dimensions,function(y){return i.mapDimension(y)}),o))||[];else if(s){var g=s.getBoundingRect().clone();g.applyTransform(s.transform),t=[g.x+g.width/2,g.y+g.height/2]}return{point:t,el:s}}var YD=Ct();function wW(r,e,t){var a=r.currTrigger,n=[r.x,r.y],i=r,o=r.dispatchAction||Y(t.dispatchAction,t),s=e.getComponent("axisPointer").coordSysAxesInfo;if(!!s){Lh(n)&&(n=UD({seriesIndex:i.seriesIndex,dataIndex:i.dataIndex},e).point);var l=Lh(n),u=i.axesInfo,f=s.axesInfo,h=a==="leave"||Lh(n),v={},c={},p={list:[],map:{}},d={showPointer:it(CW,c),showTooltip:it(AW,p)};A(s.coordSysMap,function(y,m){var _=l||y.containPoint(n);A(s.coordSysAxesInfo[m],function(S,b){var x=S.axis,w=LW(u,S);if(!h&&_&&(!u||w)){var T=w&&w.value;T==null&&!l&&(T=x.pointToData(n)),T!=null&&XD(S,T,d,!1,v)}})});var g={};return A(f,function(y,m){var _=y.linkGroup;_&&!c[m]&&A(_.axesInfo,function(S,b){var x=c[b];if(S!==y&&x){var w=x.value;_.mapper&&(w=y.axis.scale.parse(_.mapper(w,ZD(S),ZD(y)))),g[y.key]=w}})}),A(g,function(y,m){XD(f[m],y,d,!0,v)}),DW(c,f,v),MW(p,n,r,o),IW(f,o,t),v}}function XD(r,e,t,a,n){var i=r.axis;if(!(i.scale.isBlank()||!i.containData(e))){if(!r.involveSeries){t.showPointer(r,e);return}var o=TW(e,r),s=o.payloadBatch,l=o.snapToValue;s[0]&&n.seriesIndex==null&&B(n,s[0]),!a&&r.snap&&i.containData(l)&&l!=null&&(e=l),t.showPointer(r,e,s),t.showTooltip(r,o,l)}}function TW(r,e){var t=e.axis,a=t.dim,n=r,i=[],o=Number.MAX_VALUE,s=-1;return A(e.seriesModels,function(l,u){var f=l.getData().mapDimensionsAll(a),h,v;if(l.getAxisTooltipData){var c=l.getAxisTooltipData(f,r,t);v=c.dataIndices,h=c.nestestValue}else{if(v=l.getData().indicesOfNearest(f[0],r,t.type==="category"?.5:null),!v.length)return;h=l.getData().get(f[0],v[0])}if(!(h==null||!isFinite(h))){var p=r-h,d=Math.abs(p);d<=o&&((d=0&&s<0)&&(o=d,s=p,n=h,i.length=0),A(v,function(g){i.push({seriesIndex:l.seriesIndex,dataIndexInside:g,dataIndex:l.getData().getRawIndex(g)})}))}}),{payloadBatch:i,snapToValue:n}}function CW(r,e,t,a){r[e.key]={value:t,payloadBatch:a}}function AW(r,e,t,a){var n=t.payloadBatch,i=e.axis,o=i.model,s=e.axisPointerModel;if(!(!e.triggerTooltip||!n.length)){var l=e.coordSys.model,u=dl(l),f=r.map[u];f||(f=r.map[u]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},r.list.push(f)),f.dataByAxis.push({axisDim:i.dim,axisIndex:o.componentIndex,axisType:o.type,axisId:o.id,value:a,valueLabelOpt:{precision:s.get(["label","precision"]),formatter:s.get(["label","formatter"])},seriesDataIndices:n.slice()})}}function DW(r,e,t){var a=t.axesInfo=[];A(e,function(n,i){var o=n.axisPointerModel.option,s=r[i];s?(!n.useHandle&&(o.status="show"),o.value=s.value,o.seriesDataIndices=(s.payloadBatch||[]).slice()):!n.useHandle&&(o.status="hide"),o.status==="show"&&a.push({axisDim:n.axis.dim,axisIndex:n.axis.model.componentIndex,value:o.value})})}function MW(r,e,t,a){if(Lh(e)||!r.list.length){a({type:"hideTip"});return}var n=((r.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};a({type:"showTip",escapeConnect:!0,x:e[0],y:e[1],tooltipOption:t.tooltipOption,position:t.position,dataIndexInside:n.dataIndexInside,dataIndex:n.dataIndex,seriesIndex:n.seriesIndex,dataByCoordSys:r.list})}function IW(r,e,t){var a=t.getZr(),n="axisPointerLastHighlights",i=YD(a)[n]||{},o=YD(a)[n]={};A(r,function(u,f){var h=u.axisPointerModel.option;h.status==="show"&&A(h.seriesDataIndices,function(v){var c=v.seriesIndex+" | "+v.dataIndex;o[c]=v})});var s=[],l=[];A(i,function(u,f){!o[f]&&l.push(u)}),A(o,function(u,f){!i[f]&&s.push(u)}),l.length&&t.dispatchAction({type:"downplay",escapeConnect:!0,notBlur:!0,batch:l}),s.length&&t.dispatchAction({type:"highlight",escapeConnect:!0,notBlur:!0,batch:s})}function LW(r,e){for(var t=0;t<(r||[]).length;t++){var a=r[t];if(e.axis.dim===a.axisDim&&e.axis.model.componentIndex===a.axisIndex)return a}}function ZD(r){var e=r.axis.model,t={},a=t.axisDim=r.axis.dim;return t.axisIndex=t[a+"AxisIndex"]=e.componentIndex,t.axisName=t[a+"AxisName"]=e.name,t.axisId=t[a+"AxisId"]=e.id,t}function Lh(r){return!r||r[0]==null||isNaN(r[0])||r[1]==null||isNaN(r[1])}function El(r){ii.registerAxisPointerClass("CartesianAxisPointer",pW),r.registerComponentModel(gW),r.registerComponentView(bW),r.registerPreprocessor(function(e){if(e){(!e.axisPointer||e.axisPointer.length===0)&&(e.axisPointer={});var t=e.axisPointer.link;t&&!z(t)&&(e.axisPointer.link=[t])}}),r.registerProcessor(r.PRIORITY.PROCESSOR.STATISTIC,function(e,t){e.getComponent("axisPointer").coordSysAxesInfo=Gz(e,t)}),r.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},wW)}function PW(r){ct(IT),ct(El)}var RW=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.makeElOption=function(t,a,n,i,o){var s=n.axis;s.dim==="angle"&&(this.animationThreshold=Math.PI/18);var l=s.polar,u=l.getOtherAxis(s),f=u.getExtent(),h=s.dataToCoord(a),v=i.get("type");if(v&&v!=="none"){var c=Iy(i),p=kW[v](s,l,h,f);p.style=c,t.graphicKey=p.type,t.pointer=p}var d=i.get(["label","margin"]),g=EW(a,n,i,l,d);OD(t,n,i,o,g)},e}(Dy);function EW(r,e,t,a,n){var i=e.axis,o=i.dataToCoord(r),s=a.getAngleAxis().getExtent()[0];s=s/180*Math.PI;var l=a.getRadiusAxis().getExtent(),u,f,h;if(i.dim==="radius"){var v=Ge();Ia(v,v,s),mr(v,v,[a.cx,a.cy]),u=Ar([o,-n],v);var c=e.getModel("axisLabel").get("rotate")||0,p=Pe.innerTextLayout(s,c*Math.PI/180,-1);f=p.textAlign,h=p.textVerticalAlign}else{var d=l[1];u=a.coordToPoint([d+n,o]);var g=a.cx,y=a.cy;f=Math.abs(u[0]-g)/d<.3?"center":u[0]>g?"left":"right",h=Math.abs(u[1]-y)/d<.3?"middle":u[1]>y?"top":"bottom"}return{position:u,align:f,verticalAlign:h}}var kW={line:function(r,e,t,a){return r.dim==="angle"?{type:"Line",shape:Py(e.coordToPoint([a[0],t]),e.coordToPoint([a[1],t]))}:{type:"Circle",shape:{cx:e.cx,cy:e.cy,r:t}}},shadow:function(r,e,t,a){var n=Math.max(1,r.getBandWidth()),i=Math.PI/180;return r.dim==="angle"?{type:"Sector",shape:zD(e.cx,e.cy,a[0],a[1],(-t-n/2)*i,(-t+n/2)*i)}:{type:"Sector",shape:zD(e.cx,e.cy,t-n/2,t+n/2,0,Math.PI*2)}}},OW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.findAxisModel=function(t){var a,n=this.ecModel;return n.eachComponent(t,function(i){i.getCoordSysModel()===this&&(a=i)},this),a},e.type="polar",e.dependencies=["radiusAxis","angleAxis"],e.defaultOption={z:0,center:["50%","50%"],radius:"80%"},e}(gt),Ey=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.getCoordSysModel=function(){return this.getReferringComponents("polar",Kt).models[0]},e.type="polarAxis",e}(gt);Xt(Ey,ho);var NW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="angleAxis",e}(Ey),BW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="radiusAxis",e}(Ey),ky=function(r){O(e,r);function e(t,a){return r.call(this,"radius",t,a)||this}return e.prototype.pointToData=function(t,a){return this.polar.pointToData(t,a)[this.dim==="radius"?0:1]},e}(fr);ky.prototype.dataToRadius=fr.prototype.dataToCoord,ky.prototype.radiusToData=fr.prototype.coordToData;var VW=Ct(),Oy=function(r){O(e,r);function e(t,a){return r.call(this,"angle",t,a||[0,360])||this}return e.prototype.pointToData=function(t,a){return this.polar.pointToData(t,a)[this.dim==="radius"?0:1]},e.prototype.calculateCategoryInterval=function(){var t=this,a=t.getLabelModel(),n=t.scale,i=n.getExtent(),o=n.count();if(i[1]-i[0]<1)return 0;var s=i[0],l=t.dataToCoord(s+1)-t.dataToCoord(s),u=Math.abs(l),f=is(s==null?"":s+"",a.getFont(),"center","top"),h=Math.max(f.height,7),v=h/u;isNaN(v)&&(v=Infinity);var c=Math.max(0,Math.floor(v)),p=VW(t.model),d=p.lastAutoInterval,g=p.lastTickCount;return d!=null&&g!=null&&Math.abs(d-c)<=1&&Math.abs(g-o)<=1&&d>c?c=d:(p.lastTickCount=o,p.lastAutoInterval=c),c},e}(fr);Oy.prototype.dataToAngle=fr.prototype.dataToCoord,Oy.prototype.angleToData=fr.prototype.coordToData;var $D=["radius","angle"],zW=function(){function r(e){this.dimensions=$D,this.type="polar",this.cx=0,this.cy=0,this._radiusAxis=new ky,this._angleAxis=new Oy,this.axisPointerEnabled=!0,this.name=e||"",this._radiusAxis.polar=this._angleAxis.polar=this}return r.prototype.containPoint=function(e){var t=this.pointToCoord(e);return this._radiusAxis.contain(t[0])&&this._angleAxis.contain(t[1])},r.prototype.containData=function(e){return this._radiusAxis.containData(e[0])&&this._angleAxis.containData(e[1])},r.prototype.getAxis=function(e){var t="_"+e+"Axis";return this[t]},r.prototype.getAxes=function(){return[this._radiusAxis,this._angleAxis]},r.prototype.getAxesByScale=function(e){var t=[],a=this._angleAxis,n=this._radiusAxis;return a.scale.type===e&&t.push(a),n.scale.type===e&&t.push(n),t},r.prototype.getAngleAxis=function(){return this._angleAxis},r.prototype.getRadiusAxis=function(){return this._radiusAxis},r.prototype.getOtherAxis=function(e){var t=this._angleAxis;return e===t?this._radiusAxis:t},r.prototype.getBaseAxis=function(){return this.getAxesByScale("ordinal")[0]||this.getAxesByScale("time")[0]||this.getAngleAxis()},r.prototype.getTooltipAxes=function(e){var t=e!=null&&e!=="auto"?this.getAxis(e):this.getBaseAxis();return{baseAxes:[t],otherAxes:[this.getOtherAxis(t)]}},r.prototype.dataToPoint=function(e,t){return this.coordToPoint([this._radiusAxis.dataToRadius(e[0],t),this._angleAxis.dataToAngle(e[1],t)])},r.prototype.pointToData=function(e,t){var a=this.pointToCoord(e);return[this._radiusAxis.radiusToData(a[0],t),this._angleAxis.angleToData(a[1],t)]},r.prototype.pointToCoord=function(e){var t=e[0]-this.cx,a=e[1]-this.cy,n=this.getAngleAxis(),i=n.getExtent(),o=Math.min(i[0],i[1]),s=Math.max(i[0],i[1]);n.inverse?o=s-360:s=o+360;var l=Math.sqrt(t*t+a*a);t/=l,a/=l;for(var u=Math.atan2(-a,t)/Math.PI*180,f=us;)u+=f*360;return[l,u]},r.prototype.coordToPoint=function(e){var t=e[0],a=e[1]/180*Math.PI,n=Math.cos(a)*t+this.cx,i=-Math.sin(a)*t+this.cy;return[n,i]},r.prototype.getArea=function(){var e=this.getAngleAxis(),t=this.getRadiusAxis(),a=t.getExtent().slice();a[0]>a[1]&&a.reverse();var n=e.getExtent(),i=Math.PI/180;return{cx:this.cx,cy:this.cy,r0:a[0],r:a[1],startAngle:-n[0]*i,endAngle:-n[1]*i,clockwise:e.inverse,contain:function(o,s){var l=o-this.cx,u=s-this.cy,f=l*l+u*u-1e-4,h=this.r,v=this.r0;return f<=h*h&&f>=v*v}}},r.prototype.convertToPixel=function(e,t,a){var n=qD(t);return n===this?this.dataToPoint(a):null},r.prototype.convertFromPixel=function(e,t,a){var n=qD(t);return n===this?this.pointToData(a):null},r}();function qD(r){var e=r.seriesModel,t=r.polarModel;return t&&t.coordinateSystem||e&&e.coordinateSystem}function GW(r,e,t){var a=e.get("center"),n=t.getWidth(),i=t.getHeight();r.cx=H(a[0],n),r.cy=H(a[1],i);var o=r.getRadiusAxis(),s=Math.min(n,i)/2,l=e.get("radius");l==null?l=[0,"100%"]:z(l)||(l=[0,l]);var u=[H(l[0],s),H(l[1],s)];o.inverse?o.setExtent(u[1],u[0]):o.setExtent(u[0],u[1])}function FW(r,e){var t=this,a=t.getAngleAxis(),n=t.getRadiusAxis();if(a.scale.setExtent(Infinity,-Infinity),n.scale.setExtent(Infinity,-Infinity),r.eachSeries(function(s){if(s.coordinateSystem===t){var l=s.getData();A(Yf(l,"radius"),function(u){n.scale.unionExtentFromData(l,u)}),A(Yf(l,"angle"),function(u){a.scale.unionExtentFromData(l,u)})}}),Kn(a.scale,a.model),Kn(n.scale,n.model),a.type==="category"&&!a.onBand){var i=a.getExtent(),o=360/a.scale.count();a.inverse?i[1]+=o:i[1]-=o,a.setExtent(i[0],i[1])}}function HW(r){return r.mainType==="angleAxis"}function KD(r,e){if(r.type=e.get("type"),r.scale=el(e),r.onBand=e.get("boundaryGap")&&r.type==="category",r.inverse=e.get("inverse"),HW(e)){r.inverse=r.inverse!==e.get("clockwise");var t=e.get("startAngle");r.setExtent(t,t+(r.inverse?-360:360))}e.axis=r,r.model=e}var WW={dimensions:$D,create:function(r,e){var t=[];return r.eachComponent("polar",function(a,n){var i=new zW(n+"");i.update=FW;var o=i.getRadiusAxis(),s=i.getAngleAxis(),l=a.findAxisModel("radiusAxis"),u=a.findAxisModel("angleAxis");KD(o,l),KD(s,u),GW(i,a,e),t.push(i),a.coordinateSystem=i,i.model=a}),r.eachSeries(function(a){if(a.get("coordinateSystem")==="polar"){var n=a.getReferringComponents("polar",Kt).models[0];a.coordinateSystem=n.coordinateSystem}}),t}},UW=["axisLine","axisLabel","axisTick","minorTick","splitLine","minorSplitLine","splitArea"];function Ph(r,e,t){e[1]>e[0]&&(e=e.slice().reverse());var a=r.coordToPoint([e[0],t]),n=r.coordToPoint([e[1],t]);return{x1:a[0],y1:a[1],x2:n[0],y2:n[1]}}function Rh(r){var e=r.getRadiusAxis();return e.inverse?0:1}function jD(r){var e=r[0],t=r[r.length-1];e&&t&&Math.abs(Math.abs(e.coord-t.coord)-360)<1e-4&&r.pop()}var YW=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.axisPointerClass="PolarAxisPointer",t}return e.prototype.render=function(t,a){if(this.group.removeAll(),!!t.get("show")){var n=t.axis,i=n.polar,o=i.getRadiusAxis().getExtent(),s=n.getTicksCoords(),l=n.getMinorTicksCoords(),u=G(n.getViewLabels(),function(f){f=et(f);var h=n.scale,v=h.type==="ordinal"?h.getRawOrdinalNumber(f.tickValue):f.tickValue;return f.coord=n.dataToCoord(v),f});jD(u),jD(s),A(UW,function(f){t.get([f,"show"])&&(!n.scale.isBlank()||f==="axisLine")&&XW[f](this.group,t,i,s,l,o,u)},this)}},e.type="angleAxis",e}(ii),XW={axisLine:function(r,e,t,a,n,i){var o=e.getModel(["axisLine","lineStyle"]),s=Rh(t),l=s?0:1,u;i[l]===0?u=new ar({shape:{cx:t.cx,cy:t.cy,r:i[s]},style:o.getLineStyle(),z2:1,silent:!0}):u=new Vi({shape:{cx:t.cx,cy:t.cy,r:i[s],r0:i[l]},style:o.getLineStyle(),z2:1,silent:!0}),u.style.fill=null,r.add(u)},axisTick:function(r,e,t,a,n,i){var o=e.getModel("axisTick"),s=(o.get("inside")?-1:1)*o.get("length"),l=i[Rh(t)],u=G(a,function(f){return new te({shape:Ph(t,[l,l+s],f.coord)})});r.add(Ye(u,{style:j(o.getModel("lineStyle").getLineStyle(),{stroke:e.get(["axisLine","lineStyle","color"])})}))},minorTick:function(r,e,t,a,n,i){if(!!n.length){for(var o=e.getModel("axisTick"),s=e.getModel("minorTick"),l=(o.get("inside")?-1:1)*s.get("length"),u=i[Rh(t)],f=[],h=0;hy?"left":"right",S=Math.abs(g[1]-m)/d<.3?"middle":g[1]>m?"top":"bottom";if(s&&s[p]){var b=s[p];J(b)&&b.textStyle&&(c=new Mt(b.textStyle,l,l.ecModel))}var x=new bt({silent:Pe.isLabelSilent(e),style:Nt(c,{x:g[0],y:g[1],fill:c.getTextColor()||e.get(["axisLine","lineStyle","color"]),text:h.formattedLabel,align:_,verticalAlign:S})});if(r.add(x),f){var w=Pe.makeAxisEventDataBase(e);w.targetType="axisLabel",w.value=h.rawLabel,nt(x).eventData=w}},this)},splitLine:function(r,e,t,a,n,i){var o=e.getModel("splitLine"),s=o.getModel("lineStyle"),l=s.get("color"),u=0;l=l instanceof Array?l:[l];for(var f=[],h=0;h=0?"p":"n",L=w;b&&(a[f][M]||(a[f][M]={p:w,n:w}),L=a[f][M][I]);var P=void 0,R=void 0,E=void 0,N=void 0;if(p.dim==="radius"){var k=p.dataToCoord(D)-w,V=l.dataToCoord(M);Math.abs(k)=N})}}})}function JW(r){var e={};A(r,function(a,n){var i=a.getData(),o=a.coordinateSystem,s=o.getBaseAxis(),l=JD(o,s),u=s.getExtent(),f=s.type==="category"?s.getBandWidth():Math.abs(u[1]-u[0])/i.count(),h=e[l]||{bandWidth:f,remainedWidth:f,autoWidthCount:0,categoryGap:"20%",gap:"30%",stacks:{}},v=h.stacks;e[l]=h;var c=QD(a);v[c]||h.autoWidthCount++,v[c]=v[c]||{width:0,maxWidth:0};var p=H(a.get("barWidth"),f),d=H(a.get("barMaxWidth"),f),g=a.get("barGap"),y=a.get("barCategoryGap");p&&!v[c].width&&(p=Math.min(h.remainedWidth,p),v[c].width=p,h.remainedWidth-=p),d&&(v[c].maxWidth=d),g!=null&&(h.gap=g),y!=null&&(h.categoryGap=y)});var t={};return A(e,function(a,n){t[n]={};var i=a.stacks,o=a.bandWidth,s=H(a.categoryGap,o),l=H(a.gap,1),u=a.remainedWidth,f=a.autoWidthCount,h=(u-s)/(f+(f-1)*l);h=Math.max(h,0),A(i,function(d,g){var y=d.maxWidth;y&&y=t.y&&e[1]<=t.y+t.height:a.contain(a.toLocalCoord(e[1]))&&e[0]>=t.y&&e[0]<=t.y+t.height},r.prototype.pointToData=function(e){var t=this.getAxis();return[t.coordToData(t.toLocalCoord(e[t.orient==="horizontal"?0:1]))]},r.prototype.dataToPoint=function(e){var t=this.getAxis(),a=this.getRect(),n=[],i=t.orient==="horizontal"?0:1;return e instanceof Array&&(e=e[0]),n[i]=t.toGlobalCoord(t.dataToCoord(+e)),n[1-i]=i===0?a.y+a.height/2:a.x+a.width/2,n},r.prototype.convertToPixel=function(e,t,a){var n=eM(t);return n===this?this.dataToPoint(a):null},r.prototype.convertFromPixel=function(e,t,a){var n=eM(t);return n===this?this.pointToData(a):null},r}();function eM(r){var e=r.seriesModel,t=r.singleAxisModel;return t&&t.coordinateSystem||e&&e.coordinateSystem}function f6(r,e){var t=[];return r.eachComponent("singleAxis",function(a,n){var i=new u6(a,r,e);i.name="single_"+n,i.resize(a,e),a.coordinateSystem=i,t.push(i)}),r.eachSeries(function(a){if(a.get("coordinateSystem")==="singleAxis"){var n=a.getReferringComponents("singleAxis",Kt).models[0];a.coordinateSystem=n&&n.coordinateSystem}}),t}var h6={create:f6,dimensions:tM},rM=["x","y"],v6=["width","height"],c6=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.makeElOption=function(t,a,n,i,o){var s=n.axis,l=s.coordinateSystem,u=By(l,1-kh(s)),f=l.dataToPoint(a)[0],h=i.get("type");if(h&&h!=="none"){var v=Iy(i),c=p6[h](s,f,u);c.style=v,t.graphicKey=c.type,t.pointer=c}var p=Ny(n);BD(a,t,p,n,i,o)},e.prototype.getHandleTransform=function(t,a,n){var i=Ny(a,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var o=Ly(a.axis,t,i);return{x:o[0],y:o[1],rotation:i.rotation+(i.labelDirection<0?Math.PI:0)}},e.prototype.updateHandleTransform=function(t,a,n,i){var o=n.axis,s=o.coordinateSystem,l=kh(o),u=By(s,l),f=[t.x,t.y];f[l]+=a[l],f[l]=Math.min(u[1],f[l]),f[l]=Math.max(u[0],f[l]);var h=By(s,1-l),v=(h[1]+h[0])/2,c=[v,v];return c[l]=f[l],{x:f[0],y:f[1],rotation:t.rotation,cursorPoint:c,tooltipOption:{verticalAlign:"middle"}}},e}(Dy),p6={line:function(r,e,t){var a=Py([e,t[0]],[e,t[1]],kh(r));return{type:"Line",subPixelOptimize:!0,shape:a}},shadow:function(r,e,t){var a=r.getBandWidth(),n=t[1]-t[0];return{type:"Rect",shape:VD([e-a/2,t[0]],[a,n],kh(r))}}};function kh(r){return r.isHorizontal()?0:1}function By(r,e){var t=r.getRect();return[t[rM[e]],t[rM[e]]+t[v6[e]]]}var d6=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="single",e}(Bt);function g6(r){ct(El),ii.registerAxisPointerClass("SingleAxisPointer",c6),r.registerComponentView(d6),r.registerComponentView(o6),r.registerComponentModel(Eh),yo(r,"single",Eh,Eh.defaultOption),r.registerCoordinateSystem("single",h6)}var y6=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t,a,n){var i=Ki(t);r.prototype.init.apply(this,arguments),aM(t,i)},e.prototype.mergeOption=function(t){r.prototype.mergeOption.apply(this,arguments),aM(this.option,t)},e.prototype.getCellSize=function(){return this.option.cellSize},e.type="calendar",e.defaultOption={z:2,left:80,top:60,cellSize:20,orient:"horizontal",splitLine:{show:!0,lineStyle:{color:"#000",width:1,type:"solid"}},itemStyle:{color:"#fff",borderWidth:1,borderColor:"#ccc"},dayLabel:{show:!0,firstDay:0,position:"start",margin:"50%",color:"#000"},monthLabel:{show:!0,position:"start",margin:5,align:"center",formatter:null,color:"#000"},yearLabel:{show:!0,position:null,margin:30,formatter:null,color:"#ccc",fontFamily:"sans-serif",fontWeight:"bolder",fontSize:20}},e}(gt);function aM(r,e){var t=r.cellSize,a;z(t)?a=t:a=r.cellSize=[t,t],a.length===1&&(a[1]=a[0]);var n=G([0,1],function(i){return TE(e,i)&&(a[i]="auto"),a[i]!=null&&a[i]!=="auto"});Ya(r,e,{type:"box",ignoreSize:n})}var m6=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){var i=this.group;i.removeAll();var o=t.coordinateSystem,s=o.getRangeInfo(),l=o.getOrient(),u=a.getLocaleModel();this._renderDayRect(t,s,i),this._renderLines(t,s,l,i),this._renderYearText(t,s,l,i),this._renderMonthText(t,u,l,i),this._renderWeekText(t,u,s,l,i)},e.prototype._renderDayRect=function(t,a,n){for(var i=t.coordinateSystem,o=t.getModel("itemStyle").getItemStyle(),s=i.getCellWidth(),l=i.getCellHeight(),u=a.start.time;u<=a.end.time;u=i.getNextNDay(u,1).time){var f=i.dataToRect([u],!1).tl,h=new xt({shape:{x:f[0],y:f[1],width:s,height:l},cursor:"default",style:o});n.add(h)}},e.prototype._renderLines=function(t,a,n,i){var o=this,s=t.coordinateSystem,l=t.getModel(["splitLine","lineStyle"]).getLineStyle(),u=t.get(["splitLine","show"]),f=l.lineWidth;this._tlpoints=[],this._blpoints=[],this._firstDayOfMonth=[],this._firstDayPoints=[];for(var h=a.start,v=0;h.time<=a.end.time;v++){p(h.formatedDate),v===0&&(h=s.getDateInfo(a.start.y+"-"+a.start.m));var c=h.date;c.setMonth(c.getMonth()+1),h=s.getDateInfo(c)}p(s.getNextNDay(a.end.time,1).formatedDate);function p(d){o._firstDayOfMonth.push(s.getDateInfo(d)),o._firstDayPoints.push(s.dataToRect([d],!1).tl);var g=o._getLinePointsOfOneWeek(t,d,n);o._tlpoints.push(g[0]),o._blpoints.push(g[g.length-1]),u&&o._drawSplitline(g,l,i)}u&&this._drawSplitline(o._getEdgesPoints(o._tlpoints,f,n),l,i),u&&this._drawSplitline(o._getEdgesPoints(o._blpoints,f,n),l,i)},e.prototype._getEdgesPoints=function(t,a,n){var i=[t[0].slice(),t[t.length-1].slice()],o=n==="horizontal"?0:1;return i[0][o]=i[0][o]-a/2,i[1][o]=i[1][o]+a/2,i},e.prototype._drawSplitline=function(t,a,n){var i=new Se({z2:20,shape:{points:t},style:a});n.add(i)},e.prototype._getLinePointsOfOneWeek=function(t,a,n){for(var i=t.coordinateSystem,o=i.getDateInfo(a),s=[],l=0;l<7;l++){var u=i.getNextNDay(o.time,l),f=i.dataToRect([u.time],!1);s[2*u.day]=f.tl,s[2*u.day+1]=f[n==="horizontal"?"bl":"tr"]}return s},e.prototype._formatterLabel=function(t,a){return U(t)&&t?SE(t,a):K(t)?t(a):a.nameMap},e.prototype._yearTextPositionControl=function(t,a,n,i,o){var s=a[0],l=a[1],u=["center","bottom"];i==="bottom"?(l+=o,u=["center","top"]):i==="left"?s-=o:i==="right"?(s+=o,u=["center","top"]):l-=o;var f=0;return(i==="left"||i==="right")&&(f=Math.PI/2),{rotation:f,x:s,y:l,style:{align:u[0],verticalAlign:u[1]}}},e.prototype._renderYearText=function(t,a,n,i){var o=t.getModel("yearLabel");if(!!o.get("show")){var s=o.get("margin"),l=o.get("position");l||(l=n!=="horizontal"?"top":"left");var u=[this._tlpoints[this._tlpoints.length-1],this._blpoints[0]],f=(u[0][0]+u[1][0])/2,h=(u[0][1]+u[1][1])/2,v=n==="horizontal"?0:1,c={top:[f,u[v][1]],bottom:[f,u[1-v][1]],left:[u[1-v][0],h],right:[u[v][0],h]},p=a.start.y;+a.end.y>+a.start.y&&(p=p+"-"+a.end.y);var d=o.get("formatter"),g={start:a.start.y,end:a.end.y,nameMap:p},y=this._formatterLabel(d,g),m=new bt({z2:30,style:Nt(o,{text:y})});m.attr(this._yearTextPositionControl(m,c[l],n,l,s)),i.add(m)}},e.prototype._monthTextPositionControl=function(t,a,n,i,o){var s="left",l="top",u=t[0],f=t[1];return n==="horizontal"?(f=f+o,a&&(s="center"),i==="start"&&(l="bottom")):(u=u+o,a&&(l="middle"),i==="start"&&(s="right")),{x:u,y:f,align:s,verticalAlign:l}},e.prototype._renderMonthText=function(t,a,n,i){var o=t.getModel("monthLabel");if(!!o.get("show")){var s=o.get("nameMap"),l=o.get("margin"),u=o.get("position"),f=o.get("align"),h=[this._tlpoints,this._blpoints];(!s||U(s))&&(s&&(a=tp(s)||a),s=a.get(["time","monthAbbr"])||[]);var v=u==="start"?0:1,c=n==="horizontal"?0:1;l=u==="start"?-l:l;for(var p=f==="center",d=0;d=n.start.time&&a.times.end.time&&t.reverse(),t},r.prototype._getRangeInfo=function(e){var t=[this.getDateInfo(e[0]),this.getDateInfo(e[1])],a;t[0].time>t[1].time&&(a=!0,t.reverse());var n=Math.floor(t[1].time/Vy)-Math.floor(t[0].time/Vy)+1,i=new Date(t[0].time),o=i.getDate(),s=t[1].date.getDate();i.setDate(o+n-1);var l=i.getDate();if(l!==s)for(var u=i.getTime()-t[1].time>0?1:-1;(l=i.getDate())!==s&&(i.getTime()-t[1].time)*u>0;)n-=u,i.setDate(l-u);var f=Math.floor((n+t[0].day+6)/7),h=a?-f+1:f-1;return a&&t.reverse(),{range:[t[0].formatedDate,t[1].formatedDate],start:t[0],end:t[1],allDay:n,weeks:f,nthWeek:h,fweek:t[0].day,lweek:t[1].day}},r.prototype._getDateByWeeksAndDay=function(e,t,a){var n=this._getRangeInfo(a);if(e>n.weeks||e===0&&tn.lweek)return null;var i=(e-1)*7-n.fweek+t,o=new Date(n.start.time);return o.setDate(+n.start.d+i),this.getDateInfo(o)},r.create=function(e,t){var a=[];return e.eachComponent("calendar",function(n){var i=new r(n,e,t);a.push(i),n.coordinateSystem=i}),e.eachSeries(function(n){n.get("coordinateSystem")==="calendar"&&(n.coordinateSystem=a[n.get("calendarIndex")||0])}),a},r.dimensions=["time","value"],r}();function nM(r){var e=r.calendarModel,t=r.seriesModel,a=e?e.coordinateSystem:t?t.coordinateSystem:null;return a}function S6(r){r.registerComponentModel(y6),r.registerComponentView(m6),r.registerCoordinateSystem("calendar",_6)}function x6(r,e){var t=r.existing;if(e.id=r.keyInfo.id,!e.type&&t&&(e.type=t.type),e.parentId==null){var a=e.parentOption;a?e.parentId=a.id:t&&(e.parentId=t.parentId)}e.parentOption=null}function iM(r,e){var t;return A(e,function(a){r[a]!=null&&r[a]!=="auto"&&(t=!0)}),t}function b6(r,e,t){var a=B({},t),n=r[e],i=t.$action||"merge";i==="merge"?n?(ot(n,a,!0),Ya(n,a,{ignoreSize:!0}),U1(t,n),Oh(t,n),Oh(t,n,"shape"),Oh(t,n,"style"),Oh(t,n,"extra"),t.clipPath=n.clipPath):r[e]=a:i==="replace"?r[e]=a:i==="remove"&&n&&(r[e]=null)}var oM=["transition","enterFrom","leaveTo"],w6=oM.concat(["enterAnimation","updateAnimation","leaveAnimation"]);function Oh(r,e,t){if(t&&(!r[t]&&e[t]&&(r[t]={}),r=r[t],e=e[t]),!(!r||!e))for(var a=t?oM:w6,n=0;n=0;f--){var h=n[f],v=Jt(h.id,null),c=v!=null?o.get(v):null;if(!!c){var p=c.parent,y=dr(p),m=p===i?{width:s,height:l}:{width:y.width,height:y.height},_={},S=uf(c,h,m,null,{hv:h.hv,boundingMode:h.bounding},_);if(!dr(c).isNew&&S){for(var b=h.transition,x={},w=0;w=0)?x[T]=C:c[T]=C}At(c,x,t,0)}else c.attr(_)}}},e.prototype._clear=function(){var t=this,a=this._elMap;a.each(function(n){Nh(n,dr(n).option,a,t._lastGraphicModel)}),this._elMap=$()},e.prototype.dispose=function(){this._clear()},e.type="graphic",e}(Bt);function zy(r){var e=X(sM,r)?sM[r]:$u(r),t=new e({});return dr(t).type=r,t}function lM(r,e,t,a){var n=zy(t);return e.add(n),a.set(r,n),dr(n).id=r,dr(n).isNew=!0,n}function Nh(r,e,t,a){var n=r&&r.parent;n&&(r.type==="group"&&r.traverse(function(i){Nh(i,e,t,a)}),Dh(r,e,a),t.removeKey(dr(r).id))}function uM(r,e,t,a){r.isGroup||A([["cursor",er.prototype.cursor],["zlevel",a||0],["z",t||0],["z2",0]],function(n){var i=n[0];X(e,i)?r[i]=lt(e[i],n[1]):r[i]==null&&(r[i]=n[1])}),A(St(e),function(n){if(n.indexOf("on")===0){var i=e[n];r[n]=K(i)?i:null}}),X(e,"draggable")&&(r.draggable=e.draggable),e.name!=null&&(r.name=e.name),e.id!=null&&(r.id=e.id)}function D6(r){return r=B({},r),A(["id","parentId","$action","hv","bounding","textContent","clipPath"].concat(W1),function(e){delete r[e]}),r}function M6(r,e,t){var a=nt(r).eventData;!r.silent&&!r.ignore&&!a&&(a=nt(r).eventData={componentType:"graphic",componentIndex:e.componentIndex,name:r.name}),a&&(a.info=t.info)}function I6(r){r.registerComponentModel(C6),r.registerComponentView(A6),r.registerPreprocessor(function(e){var t=e.graphic;z(t)?!t[0]||!t[0].elements?e.graphic=[{elements:t}]:e.graphic=[e.graphic[0]]:t&&!t.elements&&(e.graphic=[{elements:[t]}])})}var fM=["x","y","radius","angle","single"],L6=["cartesian2d","polar","singleAxis"];function P6(r){var e=r.get("coordinateSystem");return vt(L6,e)>=0}function sn(r){return r+"Axis"}function R6(r,e){var t=$(),a=[],n=$();r.eachComponent({mainType:"dataZoom",query:e},function(f){n.get(f.uid)||s(f)});var i;do i=!1,r.eachComponent("dataZoom",o);while(i);function o(f){!n.get(f.uid)&&l(f)&&(s(f),i=!0)}function s(f){n.set(f.uid,!0),a.push(f),u(f)}function l(f){var h=!1;return f.eachTargetAxis(function(v,c){var p=t.get(v);p&&p[c]&&(h=!0)}),h}function u(f){f.eachTargetAxis(function(h,v){(t.get(h)||t.set(h,[]))[v]=!0})}return a}function hM(r){var e=r.ecModel,t={infoList:[],infoMap:$()};return r.eachTargetAxis(function(a,n){var i=e.getComponent(sn(a),n);if(!!i){var o=i.getCoordSysModel();if(!!o){var s=o.uid,l=t.infoMap.get(s);l||(l={model:o,axisModels:[]},t.infoList.push(l),t.infoMap.set(s,l)),l.axisModels.push(i)}}}),t}var Gy=function(){function r(){this.indexList=[],this.indexMap=[]}return r.prototype.add=function(e){this.indexMap[e]||(this.indexList.push(e),this.indexMap[e]=!0)},r}(),kl=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t._autoThrottle=!0,t._noTarget=!0,t._rangePropMode=["percent","percent"],t}return e.prototype.init=function(t,a,n){var i=vM(t);this.settledOption=i,this.mergeDefaultAndTheme(t,n),this._doInit(i)},e.prototype.mergeOption=function(t){var a=vM(t);ot(this.option,t,!0),ot(this.settledOption,a,!0),this._doInit(a)},e.prototype._doInit=function(t){var a=this.option;this._setDefaultThrottle(t),this._updateRangeUse(t);var n=this.settledOption;A([["start","startValue"],["end","endValue"]],function(i,o){this._rangePropMode[o]==="value"&&(a[i[0]]=n[i[0]]=null)},this),this._resetTarget()},e.prototype._resetTarget=function(){var t=this.get("orient",!0),a=this._targetAxisInfoMap=$(),n=this._fillSpecifiedTargetAxis(a);n?this._orient=t||this._makeAutoOrientByTargetAxis():(this._orient=t||"horizontal",this._fillAutoTargetAxisByOrient(a,this._orient)),this._noTarget=!0,a.each(function(i){i.indexList.length&&(this._noTarget=!1)},this)},e.prototype._fillSpecifiedTargetAxis=function(t){var a=!1;return A(fM,function(n){var i=this.getReferringComponents(sn(n),cP);if(!!i.specified){a=!0;var o=new Gy;A(i.models,function(s){o.add(s.componentIndex)}),t.set(n,o)}},this),a},e.prototype._fillAutoTargetAxisByOrient=function(t,a){var n=this.ecModel,i=!0;if(i){var o=a==="vertical"?"y":"x",s=n.findComponents({mainType:o+"Axis"});l(s,o)}if(i){var s=n.findComponents({mainType:"singleAxis",filter:function(f){return f.get("orient",!0)===a}});l(s,"single")}function l(u,f){var h=u[0];if(!!h){var v=new Gy;if(v.add(h.componentIndex),t.set(f,v),i=!1,f==="x"||f==="y"){var c=h.getReferringComponents("grid",Kt).models[0];c&&A(u,function(p){h.componentIndex!==p.componentIndex&&c===p.getReferringComponents("grid",Kt).models[0]&&v.add(p.componentIndex)})}}}i&&A(fM,function(u){if(!!i){var f=n.findComponents({mainType:sn(u),filter:function(v){return v.get("type",!0)==="category"}});if(f[0]){var h=new Gy;h.add(f[0].componentIndex),t.set(u,h),i=!1}}},this)},e.prototype._makeAutoOrientByTargetAxis=function(){var t;return this.eachTargetAxis(function(a){!t&&(t=a)},this),t==="y"?"vertical":"horizontal"},e.prototype._setDefaultThrottle=function(t){if(t.hasOwnProperty("throttle")&&(this._autoThrottle=!1),this._autoThrottle){var a=this.ecModel.option;this.option.throttle=a.animation&&a.animationDurationUpdate>0?100:20}},e.prototype._updateRangeUse=function(t){var a=this._rangePropMode,n=this.get("rangeMode");A([["start","startValue"],["end","endValue"]],function(i,o){var s=t[i[0]]!=null,l=t[i[1]]!=null;s&&!l?a[o]="percent":!s&&l?a[o]="value":n?a[o]=n[o]:s&&(a[o]="percent")})},e.prototype.noTarget=function(){return this._noTarget},e.prototype.getFirstTargetAxisModel=function(){var t;return this.eachTargetAxis(function(a,n){t==null&&(t=this.ecModel.getComponent(sn(a),n))},this),t},e.prototype.eachTargetAxis=function(t,a){this._targetAxisInfoMap.each(function(n,i){A(n.indexList,function(o){t.call(a,i,o)})})},e.prototype.getAxisProxy=function(t,a){var n=this.getAxisModel(t,a);if(n)return n.__dzAxisProxy},e.prototype.getAxisModel=function(t,a){var n=this._targetAxisInfoMap.get(t);if(n&&n.indexMap[a])return this.ecModel.getComponent(sn(t),a)},e.prototype.setRawRange=function(t){var a=this.option,n=this.settledOption;A([["start","startValue"],["end","endValue"]],function(i){(t[i[0]]!=null||t[i[1]]!=null)&&(a[i[0]]=n[i[0]]=t[i[0]],a[i[1]]=n[i[1]]=t[i[1]])},this),this._updateRangeUse(t)},e.prototype.setCalculatedRange=function(t){var a=this.option;A(["start","startValue","end","endValue"],function(n){a[n]=t[n]})},e.prototype.getPercentRange=function(){var t=this.findRepresentativeAxisProxy();if(t)return t.getDataPercentWindow()},e.prototype.getValueRange=function(t,a){if(t==null&&a==null){var n=this.findRepresentativeAxisProxy();if(n)return n.getDataValueWindow()}else return this.getAxisProxy(t,a).getDataValueWindow()},e.prototype.findRepresentativeAxisProxy=function(t){if(t)return t.__dzAxisProxy;for(var a,n=this._targetAxisInfoMap.keys(),i=0;io[1];if(_&&!S&&!b)return!0;_&&(g=!0),S&&(p=!0),b&&(d=!0)}return g&&p&&d})}else Ao(f,function(c){if(i==="empty")l.setData(u=u.map(c,function(d){return s(d)?d:NaN}));else{var p={};p[c]=o,u.selectRange(p)}});Ao(f,function(c){u.setApproximateExtent(o,c)})}});function s(l){return l>=o[0]&&l<=o[1]}},r.prototype._updateMinMaxSpan=function(){var e=this._minMaxSpan={},t=this._dataZoomModel,a=this._dataExtent;Ao(["min","max"],function(n){var i=t.get(n+"Span"),o=t.get(n+"ValueSpan");o!=null&&(o=this.getAxisModel().axis.scale.parse(o)),o!=null?i=Pt(a[0]+o,a,[0,100],!0):i!=null&&(o=Pt(i,[0,100],a,!0)-a[0]),e[n+"Span"]=i,e[n+"ValueSpan"]=o},this)},r.prototype._setAxisModel=function(){var e=this.getAxisModel(),t=this._percentWindow,a=this._valueWindow;if(!!t){var n=tc(a,[0,500]);n=Math.min(n,20);var i=e.axis.scale.rawExtentInfo;t[0]!==0&&i.setDeterminedMinMax("min",+a[0].toFixed(n)),t[1]!==100&&i.setDeterminedMinMax("max",+a[1].toFixed(n)),i.freeze()}},r}();function N6(r,e,t){var a=[Infinity,-Infinity];Ao(t,function(o){aB(a,o.getData(),e)});var n=r.getAxisModel(),i=Lb(n.axis.scale,n,a).calculate();return[i.min,i.max]}var B6={getTargetSeries:function(r){function e(n){r.eachComponent("dataZoom",function(i){i.eachTargetAxis(function(o,s){var l=r.getComponent(sn(o),s);n(o,s,l,i)})})}e(function(n,i,o,s){o.__dzAxisProxy=null});var t=[];e(function(n,i,o,s){o.__dzAxisProxy||(o.__dzAxisProxy=new O6(n,i,s,r),t.push(o.__dzAxisProxy))});var a=$();return A(t,function(n){A(n.getTargetSeriesModels(),function(i){a.set(i.uid,i)})}),a},overallReset:function(r,e){r.eachComponent("dataZoom",function(t){t.eachTargetAxis(function(a,n){t.getAxisProxy(a,n).reset(t)}),t.eachTargetAxis(function(a,n){t.getAxisProxy(a,n).filterData(t,e)})}),r.eachComponent("dataZoom",function(t){var a=t.findRepresentativeAxisProxy();if(a){var n=a.getDataPercentWindow(),i=a.getDataValueWindow();t.setCalculatedRange({start:n[0],end:n[1],startValue:i[0],endValue:i[1]})}})}};function V6(r){r.registerAction("dataZoom",function(e,t){var a=R6(t,e);A(a,function(n){n.setRawRange({start:e.start,end:e.end,startValue:e.startValue,endValue:e.endValue})})})}var pM=!1;function Hy(r){pM||(pM=!0,r.registerProcessor(r.PRIORITY.PROCESSOR.FILTER,B6),V6(r),r.registerSubTypeDefaulter("dataZoom",function(){return"slider"}))}function z6(r){r.registerComponentModel(E6),r.registerComponentView(k6),Hy(r)}var gr=function(){function r(){}return r}(),dM={};function Do(r,e){dM[r]=e}function gM(r){return dM[r]}var G6=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.optionUpdated=function(){r.prototype.optionUpdated.apply(this,arguments);var t=this.ecModel;A(this.option.feature,function(a,n){var i=gM(n);i&&(i.getDefaultOption&&(i.defaultOption=i.getDefaultOption(t)),ot(a,i.defaultOption))})},e.type="toolbox",e.layoutMode={type:"box",ignoreSize:!0},e.defaultOption={show:!0,z:6,orient:"horizontal",left:"right",top:"top",backgroundColor:"transparent",borderColor:"#ccc",borderRadius:0,borderWidth:0,padding:5,itemSize:15,itemGap:8,showTitle:!0,iconStyle:{borderColor:"#666",color:"none"},emphasis:{iconStyle:{borderColor:"#3E98C5"}},tooltip:{show:!1,position:"bottom"}},e}(gt);function F6(r,e,t){var a=e.getBoxLayoutParams(),n=e.get("padding"),i={width:t.getWidth(),height:t.getHeight()},o=jt(a,i,n);Fn(e.get("orient"),r,e.get("itemGap"),o.width,o.height),uf(r,a,i,n)}function yM(r,e){var t=Vn(e.get("padding")),a=e.getItemStyle(["color","opacity"]);return a.fill=e.get("backgroundColor"),r=new xt({shape:{x:r.x-t[3],y:r.y-t[0],width:r.width+t[1]+t[3],height:r.height+t[0]+t[2],r:e.get("borderRadius")},style:a,silent:!0,z2:-1}),r}var H6=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.render=function(t,a,n,i){var o=this.group;if(o.removeAll(),!t.get("show"))return;var s=+t.get("itemSize"),l=t.get("orient")==="vertical",u=t.get("feature")||{},f=this._features||(this._features={}),h=[];A(u,function(p,d){h.push(d)}),new da(this._featureNames||[],h).add(v).update(v).remove(it(v,null)).execute(),this._featureNames=h;function v(p,d){var g=h[p],y=h[d],m=u[g],_=new Mt(m,t,t.ecModel),S;if(i&&i.newTitle!=null&&i.featureName===g&&(m.title=i.newTitle),g&&!y){if(W6(g))S={onclick:_.option.onclick,featureName:g};else{var b=gM(g);if(!b)return;S=new b}f[g]=S}else if(S=f[y],!S)return;S.uid=Zi("toolbox-feature"),S.model=_,S.ecModel=a,S.api=n;var x=S instanceof gr;if(!g&&y){x&&S.dispose&&S.dispose(a,n);return}if(!_.get("show")||x&&S.unusable){x&&S.remove&&S.remove(a,n);return}c(_,S,g),_.setIconStatus=function(w,T){var C=this.option,D=this.iconPaths;C.iconStatus=C.iconStatus||{},C.iconStatus[w]=T,D[w]&&(T==="emphasis"?va:ca)(D[w])},S instanceof gr&&S.render&&S.render(_,a,n,i)}function c(p,d,g){var y=p.getModel("iconStyle"),m=p.getModel(["emphasis","iconStyle"]),_=d instanceof gr&&d.getIcons?d.getIcons():p.get("icon"),S=p.get("title")||{},b,x;U(_)?(b={},b[g]=_):b=_,U(S)?(x={},x[g]=S):x=S;var w=p.iconPaths={};A(b,function(T,C){var D=Ui(T,{},{x:-s/2,y:-s/2,width:s,height:s});D.setStyle(y.getItemStyle());var M=D.ensureState("emphasis");M.style=m.getItemStyle();var I=new bt({style:{text:x[C],align:m.get("textAlign"),borderRadius:m.get("textBorderRadius"),padding:m.get("textPadding"),fill:null},ignore:!0});D.setTextContent(I),Yi({el:D,componentModel:t,itemName:C,formatterParamsExtra:{title:x[C]}}),D.__title=x[C],D.on("mouseover",function(){var L=m.getItemStyle(),P=l?t.get("right")==null&&t.get("left")!=="right"?"right":"left":t.get("bottom")==null&&t.get("top")!=="bottom"?"bottom":"top";I.setStyle({fill:m.get("textFill")||L.fill||L.stroke||"#000",backgroundColor:m.get("textBackgroundColor")}),D.setTextConfig({position:m.get("textPosition")||P}),I.ignore=!t.get("showTitle"),n.enterEmphasis(this)}).on("mouseout",function(){p.get(["iconStatus",C])!=="emphasis"&&n.leaveEmphasis(this),I.hide()}),(p.get(["iconStatus",C])==="emphasis"?va:ca)(D),o.add(D),D.on("click",Y(d.onclick,d,a,n,C)),w[C]=D})}F6(o,t,n),o.add(yM(o.getBoundingRect(),t)),l||o.eachChild(function(p){var d=p.__title,g=p.ensureState("emphasis"),y=g.textConfig||(g.textConfig={}),m=p.getTextContent(),_=m&&m.ensureState("emphasis");if(_&&!K(_)&&d){var S=_.style||(_.style={}),b=is(d,bt.makeFont(S)),x=p.x+o.x,w=p.y+o.y+s,T=!1;w+b.height>n.getHeight()&&(y.position="top",T=!0);var C=T?-5-b.height:s+10;x+b.width/2>n.getWidth()?(y.position=["100%",C],S.align="right"):x-b.width/2<0&&(y.position=[0,C],S.align="left")}})},e.prototype.updateView=function(t,a,n,i){A(this._features,function(o){o instanceof gr&&o.updateView&&o.updateView(o.model,a,n,i)})},e.prototype.remove=function(t,a){A(this._features,function(n){n instanceof gr&&n.remove&&n.remove(t,a)}),this.group.removeAll()},e.prototype.dispose=function(t,a){A(this._features,function(n){n instanceof gr&&n.dispose&&n.dispose(t,a)})},e.type="toolbox",e}(Bt);function W6(r){return r.indexOf("my")===0}var U6=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){var n=this.model,i=n.get("name")||t.get("title.0.text")||"echarts",o=a.getZr().painter.getType()==="svg",s=o?"svg":n.get("type",!0)||"png",l=a.getConnectedDataURL({type:s,backgroundColor:n.get("backgroundColor",!0)||t.get("backgroundColor")||"#fff",connectedBackgroundColor:n.get("connectedBackgroundColor"),excludeComponents:n.get("excludeComponents"),pixelRatio:n.get("pixelRatio")}),u=_t.browser;if(K(MouseEvent)&&(u.newEdge||!u.ie&&!u.edge)){var f=document.createElement("a");f.download=i+"."+s,f.target="_blank",f.href=l;var h=new MouseEvent("click",{view:document.defaultView,bubbles:!0,cancelable:!1});f.dispatchEvent(h)}else if(window.navigator.msSaveOrOpenBlob||o){var v=l.split(","),c=v[0].indexOf("base64")>-1,p=o?decodeURIComponent(v[1]):v[1];c&&(p=window.atob(p));var d=i+"."+s;if(window.navigator.msSaveOrOpenBlob){for(var g=p.length,y=new Uint8Array(g);g--;)y[g]=p.charCodeAt(g);var m=new Blob([y]);window.navigator.msSaveOrOpenBlob(m,d)}else{var _=document.createElement("iframe");document.body.appendChild(_);var S=_.contentWindow,b=S.document;b.open("image/svg+xml","replace"),b.write(p),b.close(),S.focus(),b.execCommand("SaveAs",!0,d),document.body.removeChild(_)}}else{var x=n.get("lang"),w='',T=window.open();T.document.write(w),T.document.title=i}},e.getDefaultOption=function(t){var a={show:!0,icon:"M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0",title:t.getLocaleModel().get(["toolbox","saveAsImage","title"]),type:"png",connectedBackgroundColor:"#fff",name:"",excludeComponents:["toolbox"],lang:t.getLocaleModel().get(["toolbox","saveAsImage","lang"])};return a},e}(gr),mM="__ec_magicType_stack__",Y6=[["line","bar"],["stack"]],X6=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.getIcons=function(){var t=this.model,a=t.get("icon"),n={};return A(t.get("type"),function(i){a[i]&&(n[i]=a[i])}),n},e.getDefaultOption=function(t){var a={show:!0,type:[],icon:{line:"M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4",bar:"M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7",stack:"M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z"},title:t.getLocaleModel().get(["toolbox","magicType","title"]),option:{},seriesIndex:{}};return a},e.prototype.onclick=function(t,a,n){var i=this.model,o=i.get(["seriesIndex",n]);if(!!_M[n]){var s={series:[]},l=function(h){var v=h.subType,c=h.id,p=_M[n](v,c,h,i);p&&(j(p,h.option),s.series.push(p));var d=h.coordinateSystem;if(d&&d.type==="cartesian2d"&&(n==="line"||n==="bar")){var g=d.getAxesByScale("ordinal")[0];if(g){var y=g.dim,m=y+"Axis",_=h.getReferringComponents(m,Kt).models[0],S=_.componentIndex;s[m]=s[m]||[];for(var b=0;b<=S;b++)s[m][S]=s[m][S]||{};s[m][S].boundaryGap=n==="bar"}}};A(Y6,function(h){vt(h,n)>=0&&A(h,function(v){i.setIconStatus(v,"normal")})}),i.setIconStatus(n,"emphasis"),t.eachComponent({mainType:"series",query:o==null?null:{seriesIndex:o}},l);var u,f=n;n==="stack"&&(u=ot({stack:i.option.title.tiled,tiled:i.option.title.stack},i.option.title),i.get(["iconStatus",n])!=="emphasis"&&(f="tiled")),a.dispatchAction({type:"changeMagicType",currentType:f,newOption:s,newTitle:u,featureName:"magicType"})}},e}(gr),_M={line:function(r,e,t,a){if(r==="bar")return ot({id:e,type:"line",data:t.get("data"),stack:t.get("stack"),markPoint:t.get("markPoint"),markLine:t.get("markLine")},a.get(["option","line"])||{},!0)},bar:function(r,e,t,a){if(r==="line")return ot({id:e,type:"bar",data:t.get("data"),stack:t.get("stack"),markPoint:t.get("markPoint"),markLine:t.get("markLine")},a.get(["option","bar"])||{},!0)},stack:function(r,e,t,a){var n=t.get("stack")===mM;if(r==="line"||r==="bar")return a.setIconStatus("stack",n?"normal":"emphasis"),ot({id:e,stack:n?"":mM},a.get(["option","stack"])||{},!0)}};Ir({type:"changeMagicType",event:"magicTypeChanged",update:"prepareAndUpdate"},function(r,e){e.mergeOption(r.newOption)});var Bh=new Array(60).join("-"),Mo=" ";function Z6(r){var e={},t=[],a=[];return r.eachRawSeries(function(n){var i=n.coordinateSystem;if(i&&(i.type==="cartesian2d"||i.type==="polar")){var o=i.getBaseAxis();if(o.type==="category"){var s=o.dim+"_"+o.index;e[s]||(e[s]={categoryAxis:o,valueAxis:i.getOtherAxis(o),series:[]},a.push({axisDim:o.dim,axisIndex:o.index})),e[s].series.push(n)}else t.push(n)}else t.push(n)}),{seriesGroupByCategoryAxis:e,other:t,meta:a}}function $6(r){var e=[];return A(r,function(t,a){var n=t.categoryAxis,i=t.valueAxis,o=i.dim,s=[" "].concat(G(t.series,function(c){return c.name})),l=[n.model.getCategories()];A(t.series,function(c){var p=c.getRawData();l.push(c.getRawData().mapArray(p.mapDimension(o),function(d){return d}))});for(var u=[s.join(Mo)],f=0;f=0)return!0}var Wy=new RegExp("["+Mo+"]+","g");function Q6(r){for(var e=r.split(/\n+/g),t=Vh(e.shift()).split(Wy),a=[],n=G(t,function(l){return{name:l,data:[]}}),i=0;i=0;i--){var o=t[i];if(o[n])break}if(i<0){var s=r.queryComponents({mainType:"dataZoom",subType:"select",id:n})[0];if(s){var l=s.getPercentRange();t[0][n]={dataZoomId:n,start:l[0],end:l[1]}}}}),t.push(e)}function nU(r){var e=Uy(r),t=e[e.length-1];e.length>1&&e.pop();var a={};return SM(t,function(n,i){for(var o=e.length-1;o>=0;o--)if(n=e[o][i],n){a[i]=n;break}}),a}function iU(r){xM(r).snapshots=null}function oU(r){return Uy(r).length}function Uy(r){var e=xM(r);return e.snapshots||(e.snapshots=[{}]),e.snapshots}var sU=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){iU(t),a.dispatchAction({type:"restore",from:this.uid})},e.getDefaultOption=function(t){var a={show:!0,icon:"M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5",title:t.getLocaleModel().get(["toolbox","restore","title"])};return a},e}(gr);Ir({type:"restore",event:"restore",update:"prepareAndUpdate"},function(r,e){e.resetOption("recreate")});var lU=["grid","xAxis","yAxis","geo","graph","polar","radiusAxis","angleAxis","bmap"],Yy=function(){function r(e,t,a){var n=this;this._targetInfoList=[];var i=bM(t,e);A(uU,function(o,s){(!a||!a.include||vt(a.include,s)>=0)&&o(i,n._targetInfoList)})}return r.prototype.setOutputRanges=function(e,t){return this.matchOutputRanges(e,t,function(a,n,i){if((a.coordRanges||(a.coordRanges=[])).push(n),!a.coordRange){a.coordRange=n;var o=Zy[a.brushType](0,i,n);a.__rangeOffset={offset:AM[a.brushType](o.values,a.range,[1,1]),xyMinMax:o.xyMinMax}}}),e},r.prototype.matchOutputRanges=function(e,t,a){A(e,function(n){var i=this.findTargetInfo(n,t);i&&i!==!0&&A(i.coordSyses,function(o){var s=Zy[n.brushType](1,o,n.range,!0);a(n,s.values,o,t)})},this)},r.prototype.setInputRanges=function(e,t){A(e,function(a){var n=this.findTargetInfo(a,t);if(a.range=a.range||[],n&&n!==!0){a.panelId=n.panelId;var i=Zy[a.brushType](0,n.coordSys,a.coordRange),o=a.__rangeOffset;a.range=o?AM[a.brushType](i.values,o.offset,fU(i.xyMinMax,o.xyMinMax)):i.values}},this)},r.prototype.makePanelOpts=function(e,t){return G(this._targetInfoList,function(a){var n=a.getPanelRect();return{panelId:a.panelId,defaultBrushType:t?t(a):null,clipPath:AA(n),isTargetByCursor:MA(n,e,a.coordSysModel),getLinearBrushOtherExtent:DA(n)}})},r.prototype.controlSeries=function(e,t,a){var n=this.findTargetInfo(e,a);return n===!0||n&&vt(n.coordSyses,t.coordinateSystem)>=0},r.prototype.findTargetInfo=function(e,t){for(var a=this._targetInfoList,n=bM(t,e),i=0;ir[1]&&r.reverse(),r}function bM(r,e){return fs(r,e,{includeMainTypes:lU})}var uU={grid:function(r,e){var t=r.xAxisModels,a=r.yAxisModels,n=r.gridModels,i=$(),o={},s={};!t&&!a&&!n||(A(t,function(l){var u=l.axis.grid.model;i.set(u.id,u),o[u.id]=!0}),A(a,function(l){var u=l.axis.grid.model;i.set(u.id,u),s[u.id]=!0}),A(n,function(l){i.set(l.id,l),o[l.id]=!0,s[l.id]=!0}),i.each(function(l){var u=l.coordinateSystem,f=[];A(u.getCartesians(),function(h,v){(vt(t,h.getAxis("x").model)>=0||vt(a,h.getAxis("y").model)>=0)&&f.push(h)}),e.push({panelId:"grid--"+l.id,gridModel:l,coordSysModel:l,coordSys:f[0],coordSyses:f,getPanelRect:TM.grid,xAxisDeclared:o[l.id],yAxisDeclared:s[l.id]})}))},geo:function(r,e){A(r.geoModels,function(t){var a=t.coordinateSystem;e.push({panelId:"geo--"+t.id,geoModel:t,coordSysModel:t,coordSys:a,coordSyses:[a],getPanelRect:TM.geo})})}},wM=[function(r,e){var t=r.xAxisModel,a=r.yAxisModel,n=r.gridModel;return!n&&t&&(n=t.axis.grid.model),!n&&a&&(n=a.axis.grid.model),n&&n===e.gridModel},function(r,e){var t=r.geoModel;return t&&t===e.geoModel}],TM={grid:function(){return this.coordSys.master.getRect().clone()},geo:function(){var r=this.coordSys,e=r.getBoundingRect().clone();return e.applyTransform(Ha(r)),e}},Zy={lineX:it(CM,0),lineY:it(CM,1),rect:function(r,e,t,a){var n=r?e.pointToData([t[0][0],t[1][0]],a):e.dataToPoint([t[0][0],t[1][0]],a),i=r?e.pointToData([t[0][1],t[1][1]],a):e.dataToPoint([t[0][1],t[1][1]],a),o=[Xy([n[0],i[0]]),Xy([n[1],i[1]])];return{values:o,xyMinMax:o}},polygon:function(r,e,t,a){var n=[[Infinity,-Infinity],[Infinity,-Infinity]],i=G(t,function(o){var s=r?e.pointToData(o,a):e.dataToPoint(o,a);return n[0][0]=Math.min(n[0][0],s[0]),n[1][0]=Math.min(n[1][0],s[1]),n[0][1]=Math.max(n[0][1],s[0]),n[1][1]=Math.max(n[1][1],s[1]),s});return{values:i,xyMinMax:n}}};function CM(r,e,t,a){var n=t.getAxis(["x","y"][r]),i=Xy(G([0,1],function(s){return e?n.coordToData(n.toLocalCoord(a[s]),!0):n.toGlobalCoord(n.dataToCoord(a[s]))})),o=[];return o[r]=i,o[1-r]=[NaN,NaN],{values:i,xyMinMax:o}}var AM={lineX:it(DM,0),lineY:it(DM,1),rect:function(r,e,t){return[[r[0][0]-t[0]*e[0][0],r[0][1]-t[0]*e[0][1]],[r[1][0]-t[1]*e[1][0],r[1][1]-t[1]*e[1][1]]]},polygon:function(r,e,t){return G(r,function(a,n){return[a[0]-t[0]*e[n][0],a[1]-t[1]*e[n][1]]})}};function DM(r,e,t,a){return[e[0]-a[r]*t[0],e[1]-a[r]*t[1]]}function fU(r,e){var t=MM(r),a=MM(e),n=[t[0]/a[0],t[1]/a[1]];return isNaN(n[0])&&(n[0]=1),isNaN(n[1])&&(n[1]=1),n}function MM(r){return r?[r[0][1]-r[0][0],r[1][1]-r[1][0]]:[NaN,NaN]}var $y=A,hU=lP("toolbox-dataZoom_"),vU=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.render=function(t,a,n,i){this._brushController||(this._brushController=new Xg(n.getZr()),this._brushController.on("brush",Y(this._onBrush,this)).mount()),dU(t,a,this,i,n),pU(t,a)},e.prototype.onclick=function(t,a,n){cU[n].call(this)},e.prototype.remove=function(t,a){this._brushController&&this._brushController.unmount()},e.prototype.dispose=function(t,a){this._brushController&&this._brushController.dispose()},e.prototype._onBrush=function(t){var a=t.areas;if(!t.isEnd||!a.length)return;var n={},i=this.ecModel;this._brushController.updateCovers([]);var o=new Yy(qy(this.model),i,{include:["grid"]});o.matchOutputRanges(a,i,function(u,f,h){if(h.type==="cartesian2d"){var v=u.brushType;v==="rect"?(s("x",h,f[0]),s("y",h,f[1])):s({lineX:"x",lineY:"y"}[v],h,f)}}),aU(i,n),this._dispatchZoomAction(n);function s(u,f,h){var v=f.getAxis(u),c=v.model,p=l(u,c,i),d=p.findRepresentativeAxisProxy(c).getMinMaxSpan();(d.minValueSpan!=null||d.maxValueSpan!=null)&&(h=hi(0,h.slice(),v.scale.getExtent(),0,d.minValueSpan,d.maxValueSpan)),p&&(n[p.id]={dataZoomId:p.id,startValue:h[0],endValue:h[1]})}function l(u,f,h){var v;return h.eachComponent({mainType:"dataZoom",subType:"select"},function(c){var p=c.getAxisModel(u,f.componentIndex);p&&(v=c)}),v}},e.prototype._dispatchZoomAction=function(t){var a=[];$y(t,function(n,i){a.push(et(n))}),a.length&&this.api.dispatchAction({type:"dataZoom",from:this.uid,batch:a})},e.getDefaultOption=function(t){var a={show:!0,filterMode:"filter",icon:{zoom:"M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1",back:"M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26"},title:t.getLocaleModel().get(["toolbox","dataZoom","title"]),brushStyle:{borderWidth:0,color:"rgba(210,219,238,0.2)"}};return a},e}(gr),cU={zoom:function(){var r=!this._isZoomActive;this.api.dispatchAction({type:"takeGlobalCursor",key:"dataZoomSelect",dataZoomSelectActive:r})},back:function(){this._dispatchZoomAction(nU(this.ecModel))}};function qy(r){var e={xAxisIndex:r.get("xAxisIndex",!0),yAxisIndex:r.get("yAxisIndex",!0),xAxisId:r.get("xAxisId",!0),yAxisId:r.get("yAxisId",!0)};return e.xAxisIndex==null&&e.xAxisId==null&&(e.xAxisIndex="all"),e.yAxisIndex==null&&e.yAxisId==null&&(e.yAxisIndex="all"),e}function pU(r,e){r.setIconStatus("back",oU(e)>1?"emphasis":"normal")}function dU(r,e,t,a,n){var i=t._isZoomActive;a&&a.type==="takeGlobalCursor"&&(i=a.key==="dataZoomSelect"?a.dataZoomSelectActive:!1),t._isZoomActive=i,r.setIconStatus("zoom",i?"emphasis":"normal");var o=new Yy(qy(r),e,{include:["grid"]}),s=o.makePanelOpts(n,function(l){return l.xAxisDeclared&&!l.yAxisDeclared?"lineX":!l.xAxisDeclared&&l.yAxisDeclared?"lineY":"rect"});t._brushController.setPanels(s).enableBrush(i&&s.length?{brushType:"auto",brushStyle:r.getModel("brushStyle").getItemStyle()}:!1)}LE("dataZoom",function(r){var e=r.getComponent("toolbox",0),t=["feature","dataZoom"];if(!e||e.get(t)==null)return;var a=e.getModel(t),n=[],i=qy(a),o=fs(r,i);$y(o.xAxisModels,function(l){return s(l,"xAxis","xAxisIndex")}),$y(o.yAxisModels,function(l){return s(l,"yAxis","yAxisIndex")});function s(l,u,f){var h=l.componentIndex,v={type:"select",$fromToolbox:!0,filterMode:a.get("filterMode",!0)||"filter",id:hU+u+h};v[f]=h,n.push(v)}return n});function gU(r){r.registerComponentModel(G6),r.registerComponentView(H6),Do("saveAsImage",U6),Do("magicType",X6),Do("dataView",eU),Do("dataZoom",vU),Do("restore",sU),ct(z6)}var yU=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="tooltip",e.dependencies=["axisPointer"],e.defaultOption={z:60,show:!0,showContent:!0,trigger:"item",triggerOn:"mousemove|click",alwaysShowContent:!1,displayMode:"single",renderMode:"auto",confine:null,showDelay:0,hideDelay:100,transitionDuration:.4,enterable:!1,backgroundColor:"#fff",shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:"#999",width:1,type:"dashed",textStyle:{}}},textStyle:{color:"#666",fontSize:14}},e}(gt);function IM(r){var e=r.get("confine");return e!=null?!!e:r.get("renderMode")==="richText"}function LM(r){if(!!_t.domSupported){for(var e=document.documentElement.style,t=0,a=r.length;t-1?(s+="top:50%",l+="translateY(-50%) rotate("+(u=i==="left"?-225:-45)+"deg)"):(s+="left:50%",l+="translateX(-50%) rotate("+(u=i==="top"?225:45)+"deg)");var f=u*Math.PI/180,h=o+n,v=h*Math.abs(Math.cos(f))+h*Math.abs(Math.sin(f)),c=Math.round(((v-Math.SQRT2*n)/2+Math.SQRT2*n-(v-h)/2)*100)/100;s+=";"+i+":-"+c+"px";var p=e+" solid "+n+"px;",d=["position:absolute;width:"+o+"px;height:"+o+"px;z-index:-1;",s+";"+l+";","border-bottom:"+p,"border-right:"+p,"background-color:"+a+";"];return'
    '}function TU(r,e){var t="cubic-bezier(0.23,1,0.32,1)",a=" "+r/2+"s "+t,n="opacity"+a+",visibility"+a;return e||(a=" "+r+"s "+t,n+=_t.transformSupported?","+Ky+a:",left"+a+",top"+a),SU+":"+n}function EM(r,e,t){var a=r.toFixed(0)+"px",n=e.toFixed(0)+"px";if(!_t.transformSupported)return t?"top:"+n+";left:"+a+";":[["top",n],["left",a]];var i=_t.transform3dSupported,o="translate"+(i?"3d":"")+"("+a+","+n+(i?",0":"")+")";return t?"top:0;left:0;"+Ky+":"+o+";":[["top",0],["left",0],[PM,o]]}function CU(r){var e=[],t=r.get("fontSize"),a=r.getTextColor();a&&e.push("color:"+a),e.push("font:"+r.getFont()),t&&e.push("line-height:"+Math.round(t*3/2)+"px");var n=r.get("textShadowColor"),i=r.get("textShadowBlur")||0,o=r.get("textShadowOffsetX")||0,s=r.get("textShadowOffsetY")||0;return n&&i&&e.push("text-shadow:"+o+"px "+s+"px "+i+"px "+n),A(["decoration","align"],function(l){var u=r.get(l);u&&e.push("text-"+l+":"+u)}),e.join(";")}function AU(r,e,t){var a=[],n=r.get("transitionDuration"),i=r.get("backgroundColor"),o=r.get("shadowBlur"),s=r.get("shadowColor"),l=r.get("shadowOffsetX"),u=r.get("shadowOffsetY"),f=r.getModel("textStyle"),h=YS(r,"html"),v=l+"px "+u+"px "+o+"px "+s;return a.push("box-shadow:"+v),e&&n&&a.push(TU(n,t)),i&&a.push("background-color:"+i),A(["width","color","radius"],function(c){var p="border-"+c,d=op(p),g=r.get(d);g!=null&&a.push(p+":"+g+(c==="color"?"":"px"))}),a.push(CU(f)),h!=null&&a.push("padding:"+Vn(h).join("px ")+"px"),a.join(";")+";"}function kM(r,e,t,a,n){var i=e&&e.painter;if(t){var o=i&&i.getViewportRoot();o&&EL(r,o,document.body,a,n)}else{r[0]=a,r[1]=n;var s=i&&i.getViewportRootOffset();s&&(r[0]+=s.offsetLeft,r[1]+=s.offsetTop)}r[2]=r[0]/e.getWidth(),r[3]=r[1]/e.getHeight()}var DU=function(){function r(e,t,a){if(this._show=!1,this._styleCoord=[0,0,0,0],this._enterable=!0,this._firstShow=!0,this._longHide=!0,_t.wxa)return null;var n=document.createElement("div");n.domBelongToZr=!0,this.el=n;var i=this._zr=t.getZr(),o=this._appendToBody=a&&a.appendToBody;kM(this._styleCoord,i,o,t.getWidth()/2,t.getHeight()/2),o?document.body.appendChild(n):e.appendChild(n),this._container=e;var s=this;n.onmouseenter=function(){s._enterable&&(clearTimeout(s._hideTimeout),s._show=!0),s._inContent=!0},n.onmousemove=function(l){if(l=l||window.event,!s._enterable){var u=i.handler,f=i.painter.getViewportRoot();Qe(f,l,!0),u.dispatch("mousemove",l)}},n.onmouseleave=function(){s._inContent=!1,s._enterable&&s._show&&s.hideLater(s._hideDelay)}}return r.prototype.update=function(e){var t=this._container,a=_U(t,"position"),n=t.style;n.position!=="absolute"&&a!=="absolute"&&(n.position="relative");var i=e.get("alwaysShowContent");i&&this._moveIfResized(),this.el.className=e.get("className")||""},r.prototype.show=function(e,t){clearTimeout(this._hideTimeout),clearTimeout(this._longHideTimeout);var a=this.el,n=a.style,i=this._styleCoord;a.innerHTML?n.cssText=xU+AU(e,!this._firstShow,this._longHide)+EM(i[0],i[1],!0)+("border-color:"+zn(t)+";")+(e.get("extraCssText")||"")+(";pointer-events:"+(this._enterable?"auto":"none")):n.display="none",this._show=!0,this._firstShow=!1,this._longHide=!1},r.prototype.setContent=function(e,t,a,n,i){var o=this.el;if(e==null){o.innerHTML="";return}var s="";if(U(i)&&a.get("trigger")==="item"&&!IM(a)&&(s=wU(a,n,i)),U(e))o.innerHTML=e+s;else if(e){o.innerHTML="",z(e)||(e=[e]);for(var l=0;l=0?this._tryShow(i,o):n==="leave"&&this._hide(o))},this))},e.prototype._keepShow=function(){var t=this._tooltipModel,a=this._ecModel,n=this._api,i=t.get("triggerOn");if(this._lastX!=null&&this._lastY!=null&&i!=="none"&&i!=="click"){var o=this;clearTimeout(this._refreshUpdateTimeout),this._refreshUpdateTimeout=setTimeout(function(){!n.isDisposed()&&o.manuallyShowTip(t,a,n,{x:o._lastX,y:o._lastY,dataByCoordSys:o._lastDataByCoordSys})})}},e.prototype.manuallyShowTip=function(t,a,n,i){if(!(i.from===this.uid||_t.node||!n.getDom())){var o=BM(i,n);this._ticket="";var s=i.dataByCoordSys,l=kU(i,a,n);if(l){var u=l.el.getBoundingRect().clone();u.applyTransform(l.el.transform),this._tryShow({offsetX:u.x+u.width/2,offsetY:u.y+u.height/2,target:l.el,position:i.position,positionDefault:"bottom"},o)}else if(i.tooltip&&i.x!=null&&i.y!=null){var f=IU;f.x=i.x,f.y=i.y,f.update(),nt(f).tooltipConfig={name:null,option:i.tooltip},this._tryShow({offsetX:i.x,offsetY:i.y,target:f},o)}else if(s)this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,dataByCoordSys:s,tooltipOption:i.tooltipOption},o);else if(i.seriesIndex!=null){if(this._manuallyAxisShowTip(t,a,n,i))return;var h=UD(i,a),v=h.point[0],c=h.point[1];v!=null&&c!=null&&this._tryShow({offsetX:v,offsetY:c,target:h.el,position:i.position,positionDefault:"bottom"},o)}else i.x!=null&&i.y!=null&&(n.dispatchAction({type:"updateAxisPointer",x:i.x,y:i.y}),this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,target:n.getZr().findHover(i.x,i.y).target},o))}},e.prototype.manuallyHideTip=function(t,a,n,i){var o=this._tooltipContent;!this._alwaysShowContent&&this._tooltipModel&&o.hideLater(this._tooltipModel.get("hideDelay")),this._lastX=this._lastY=this._lastDataByCoordSys=null,i.from!==this.uid&&this._hide(BM(i,n))},e.prototype._manuallyAxisShowTip=function(t,a,n,i){var o=i.seriesIndex,s=i.dataIndex,l=a.getComponent("axisPointer").coordSysAxesInfo;if(!(o==null||s==null||l==null)){var u=a.getSeriesByIndex(o);if(!!u){var f=u.getData(),h=Ol([f.getItemModel(s),u,(u.coordinateSystem||{}).model],this._tooltipModel);if(h.get("trigger")==="axis")return n.dispatchAction({type:"updateAxisPointer",seriesIndex:o,dataIndex:s,position:i.position}),!0}}},e.prototype._tryShow=function(t,a){var n=t.target,i=this._tooltipModel;if(!!i){this._lastX=t.offsetX,this._lastY=t.offsetY;var o=t.dataByCoordSys;if(o&&o.length)this._showAxisTooltip(o,t);else if(n){this._lastDataByCoordSys=null;var s,l;Yn(n,function(u){if(nt(u).dataIndex!=null)return s=u,!0;if(nt(u).tooltipConfig!=null)return l=u,!0},!0),s?this._showSeriesItemTooltip(t,s,a):l?this._showComponentItemTooltip(t,l,a):this._hide(a)}else this._lastDataByCoordSys=null,this._hide(a)}},e.prototype._showOrMove=function(t,a){var n=t.get("showDelay");a=Y(a,this),clearTimeout(this._showTimout),n>0?this._showTimout=setTimeout(a,n):a()},e.prototype._showAxisTooltip=function(t,a){var n=this._ecModel,i=this._tooltipModel,o=[a.offsetX,a.offsetY],s=Ol([a.tooltipOption],i),l=this._renderMode,u=[],f=ie("section",{blocks:[],noHeader:!0}),h=[],v=new Pp;A(t,function(m){A(m.dataByAxis,function(_){var S=n.getComponent(_.axisDim+"Axis",_.axisIndex),b=_.value;if(!(!S||b==null)){var x=ND(b,S.axis,n,_.seriesDataIndices,_.valueLabelOpt),w=ie("section",{header:x,noHeader:!Ke(x),sortBlocks:!0,blocks:[]});f.blocks.push(w),A(_.seriesDataIndices,function(T){var C=n.getSeriesByIndex(T.seriesIndex),D=T.dataIndexInside,M=C.getDataParams(D);if(!(M.dataIndex<0)){M.axisDim=_.axisDim,M.axisIndex=_.axisIndex,M.axisType=_.axisType,M.axisId=_.axisId,M.axisValue=yd(S.axis,{value:b}),M.axisValueLabel=x,M.marker=v.makeTooltipMarker("item",zn(M.color),l);var I=CS(C.formatTooltip(D,!0,null)),L=I.frag;if(L){var P=Ol([C],i).get("valueFormatter");w.blocks.push(P?B({valueFormatter:P},L):L)}I.text&&h.push(I.text),u.push(M)}})}})}),f.blocks.reverse(),h.reverse();var c=a.position,p=s.get("order"),d=HS(f,v,l,p,n.get("useUTC"),s.get("textStyle"));d&&h.unshift(d);var g=l==="richText"?` + +`:"
    ",y=h.join(g);this._showOrMove(s,function(){this._updateContentNotChangedOnAxis(t,u)?this._updatePosition(s,c,o[0],o[1],this._tooltipContent,u):this._showTooltipContent(s,y,u,Math.random()+"",o[0],o[1],c,null,v)})},e.prototype._showSeriesItemTooltip=function(t,a,n){var i=this._ecModel,o=nt(a),s=o.seriesIndex,l=i.getSeriesByIndex(s),u=o.dataModel||l,f=o.dataIndex,h=o.dataType,v=u.getData(h),c=this._renderMode,p=t.positionDefault,d=Ol([v.getItemModel(f),u,l&&(l.coordinateSystem||{}).model],this._tooltipModel,p?{position:p}:null),g=d.get("trigger");if(!(g!=null&&g!=="item")){var y=u.getDataParams(f,h),m=new Pp;y.marker=m.makeTooltipMarker("item",zn(y.color),c);var _=CS(u.formatTooltip(f,!1,h)),S=d.get("order"),b=d.get("valueFormatter"),x=_.frag,w=x?HS(b?B({valueFormatter:b},x):x,m,c,S,i.get("useUTC"),d.get("textStyle")):_.text,T="item_"+u.name+"_"+f;this._showOrMove(d,function(){this._showTooltipContent(d,w,y,T,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:f,dataIndex:v.getRawIndex(f),seriesIndex:s,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,a,n){var i=nt(a),o=i.tooltipConfig,s=o.option||{};if(U(s)){var l=s;s={content:l,formatter:l}}var u=[s],f=this._ecModel.getComponent(i.componentMainType,i.componentIndex);f&&u.push(f),u.push({formatter:s.content});var h=t.positionDefault,v=Ol(u,this._tooltipModel,h?{position:h}:null),c=v.get("content"),p=Math.random()+"",d=new Pp;this._showOrMove(v,function(){var g=et(v.get("formatterParams")||{});this._showTooltipContent(v,c,g,p,t.offsetX,t.offsetY,t.position,a,d)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,a,n,i,o,s,l,u,f){if(this._ticket="",!(!t.get("showContent")||!t.get("show"))){var h=this._tooltipContent;h.setEnterable(t.get("enterable"));var v=t.get("formatter");l=l||t.get("position");var c=a,p=this._getNearestPoint([o,s],n,t.get("trigger"),t.get("borderColor")),d=p.color;if(v)if(U(v)){var g=t.ecModel.get("useUTC"),y=z(n)?n[0]:n,m=y&&y.axisType&&y.axisType.indexOf("time")>=0;c=v,m&&(c=Rs(y.axisValue,c,g)),c=up(c,n,!0)}else if(K(v)){var _=Y(function(S,b){S===this._ticket&&(h.setContent(b,f,t,d,l),this._updatePosition(t,l,o,s,h,n,u))},this);this._ticket=i,c=v(n,i,_)}else c=v;h.setContent(c,f,t,d,l),h.show(t,d),this._updatePosition(t,l,o,s,h,n,u)}},e.prototype._getNearestPoint=function(t,a,n,i){if(n==="axis"||z(a))return{color:i||(this._renderMode==="html"?"#fff":"none")};if(!z(a))return{color:i||a.color||a.borderColor}},e.prototype._updatePosition=function(t,a,n,i,o,s,l){var u=this._api.getWidth(),f=this._api.getHeight();a=a||t.get("position");var h=o.getSize(),v=t.get("align"),c=t.get("verticalAlign"),p=l&&l.getBoundingRect().clone();if(l&&p.applyTransform(l.transform),K(a)&&(a=a([n,i],s,o.el,p,{viewSize:[u,f],contentSize:h.slice()})),z(a))n=H(a[0],u),i=H(a[1],f);else if(J(a)){var d=a;d.width=h[0],d.height=h[1];var g=jt(d,{width:u,height:f});n=g.x,i=g.y,v=null,c=null}else if(U(a)&&l){var y=EU(a,p,h,t.get("borderWidth"));n=y[0],i=y[1]}else{var y=PU(n,i,o,u,f,v?null:20,c?null:20);n=y[0],i=y[1]}if(v&&(n-=VM(v)?h[0]/2:v==="right"?h[0]:0),c&&(i-=VM(c)?h[1]/2:c==="bottom"?h[1]:0),IM(t)){var y=RU(n,i,o,u,f);n=y[0],i=y[1]}o.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,a){var n=this._lastDataByCoordSys,i=this._cbParamsList,o=!!n&&n.length===t.length;return o&&A(n,function(s,l){var u=s.dataByAxis||[],f=t[l]||{},h=f.dataByAxis||[];o=o&&u.length===h.length,o&&A(u,function(v,c){var p=h[c]||{},d=v.seriesDataIndices||[],g=p.seriesDataIndices||[];o=o&&v.value===p.value&&v.axisType===p.axisType&&v.axisId===p.axisId&&d.length===g.length,o&&A(d,function(y,m){var _=g[m];o=o&&y.seriesIndex===_.seriesIndex&&y.dataIndex===_.dataIndex}),i&&A(v.seriesDataIndices,function(y){var m=y.seriesIndex,_=a[m],S=i[m];_&&S&&S.data!==_.data&&(o=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=a,!!o},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,a){_t.node||!a.getDom()||(Fs(this,"_updatePosition"),this._tooltipContent.dispose(),Ry("itemTooltip",a))},e.type="tooltip",e}(Bt);function Ol(r,e,t){var a=e.ecModel,n;t?(n=new Mt(t,a,a),n=new Mt(e.option,n,a)):n=e;for(var i=r.length-1;i>=0;i--){var o=r[i];o&&(o instanceof Mt&&(o=o.get("tooltip",!0)),U(o)&&(o={formatter:o}),o&&(n=new Mt(o,n,a)))}return n}function BM(r,e){return r.dispatchAction||Y(e.dispatchAction,e)}function PU(r,e,t,a,n,i,o){var s=t.getSize(),l=s[0],u=s[1];return i!=null&&(r+l+i+2>a?r-=l+i:r+=i),o!=null&&(e+u+o>n?e-=u+o:e+=o),[r,e]}function RU(r,e,t,a,n){var i=t.getSize(),o=i[0],s=i[1];return r=Math.min(r+o,a)-o,e=Math.min(e+s,n)-s,r=Math.max(r,0),e=Math.max(e,0),[r,e]}function EU(r,e,t,a){var n=t[0],i=t[1],o=Math.ceil(Math.SQRT2*a)+8,s=0,l=0,u=e.width,f=e.height;switch(r){case"inside":s=e.x+u/2-n/2,l=e.y+f/2-i/2;break;case"top":s=e.x+u/2-n/2,l=e.y-i-o;break;case"bottom":s=e.x+u/2-n/2,l=e.y+f+o;break;case"left":s=e.x-n-o,l=e.y+f/2-i/2;break;case"right":s=e.x+u+o,l=e.y+f/2-i/2}return[s,l]}function VM(r){return r==="center"||r==="middle"}function kU(r,e,t){var a=sc(r).queryOptionMap,n=a.keys()[0];if(!(!n||n==="series")){var i=hs(e,n,a.get(n),{useDefault:!1,enableAll:!1,enableNone:!1}),o=i.models[0];if(!!o){var s=t.getViewOfComponentModel(o),l;if(s.group.traverse(function(u){var f=nt(u).tooltipConfig;if(f&&f.name===r.name)return l=u,!0}),l)return{componentMainType:n,componentIndex:o.componentIndex,el:l}}}}function OU(r){ct(El),r.registerComponentModel(yU),r.registerComponentView(LU),r.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Zt),r.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Zt)}var NU=["rect","polygon","keep","clear"];function BU(r,e){var t=Et(r?r.brush:[]);if(!!t.length){var a=[];A(t,function(l){var u=l.hasOwnProperty("toolbox")?l.toolbox:[];u instanceof Array&&(a=a.concat(u))});var n=r&&r.toolbox;z(n)&&(n=n[0]),n||(n={feature:{}},r.toolbox=[n]);var i=n.feature||(n.feature={}),o=i.brush||(i.brush={}),s=o.type||(o.type=[]);s.push.apply(s,a),VU(s),e&&!s.length&&s.push.apply(s,NU)}}function VU(r){var e={};A(r,function(t){e[t]=1}),r.length=0,A(e,function(t,a){r.push(a)})}var zM=A;function GM(r){if(r){for(var e in r)if(r.hasOwnProperty(e))return!0}}function jy(r,e,t){var a={};return zM(e,function(i){var o=a[i]=n();zM(r[i],function(s,l){if(!!se.isValidType(l)){var u={type:l,visual:s};t&&t(u,i),o[l]=new se(u),l==="opacity"&&(u=et(u),u.type="colorAlpha",o.__hidden.__alphaForOpacity=new se(u))}})}),a;function n(){var i=function(){};i.prototype.__hidden=i.prototype;var o=new i;return o}}function FM(r,e,t){var a;A(t,function(n){e.hasOwnProperty(n)&&GM(e[n])&&(a=!0)}),a&&A(t,function(n){e.hasOwnProperty(n)&&GM(e[n])?r[n]=et(e[n]):delete r[n]})}function zU(r,e,t,a,n,i){var o={};A(r,function(h){var v=se.prepareVisualTypes(e[h]);o[h]=v});var s;function l(h){return kp(t,s,h)}function u(h,v){cx(t,s,h,v)}i==null?t.each(f):t.each([i],f);function f(h,v){s=i==null?h:v;var c=t.getRawDataItem(s);if(!(c&&c.visualMap===!1))for(var p=a.call(n,h),d=e[p],g=o[p],y=0,m=g.length;ye[0][1]&&(e[0][1]=i[0]),i[1]e[1][1]&&(e[1][1]=i[1])}return e&&ZM(e)}};function ZM(r){return new ft(r[0][0],r[1][0],r[0][1]-r[0][0],r[1][1]-r[1][0])}var ZU=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t,a){this.ecModel=t,this.api=a,this.model,(this._brushController=new Xg(a.getZr())).on("brush",Y(this._onBrush,this)).mount()},e.prototype.render=function(t,a,n,i){this.model=t,this._updateController(t,a,n,i)},e.prototype.updateTransform=function(t,a,n,i){YM(a),this._updateController(t,a,n,i)},e.prototype.updateVisual=function(t,a,n,i){this.updateTransform(t,a,n,i)},e.prototype.updateView=function(t,a,n,i){this._updateController(t,a,n,i)},e.prototype._updateController=function(t,a,n,i){(!i||i.$from!==t.id)&&this._brushController.setPanels(t.brushTargetManager.makePanelOpts(n)).enableBrush(t.brushOption).updateCovers(t.areas.slice())},e.prototype.dispose=function(){this._brushController.dispose()},e.prototype._onBrush=function(t){var a=this.model.id,n=this.model.brushTargetManager.setOutputRanges(t.areas,this.ecModel);(!t.isEnd||t.removeOnClick)&&this.api.dispatchAction({type:"brush",brushId:a,areas:et(n),$from:a}),t.isEnd&&this.api.dispatchAction({type:"brushEnd",brushId:a,areas:et(n),$from:a})},e.type="brush",e}(Bt),$U="#ddd",qU=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.areas=[],t.brushOption={},t}return e.prototype.optionUpdated=function(t,a){var n=this.option;!a&&FM(n,t,["inBrush","outOfBrush"]);var i=n.inBrush=n.inBrush||{};n.outOfBrush=n.outOfBrush||{color:$U},i.hasOwnProperty("liftZ")||(i.liftZ=5)},e.prototype.setAreas=function(t){!t||(this.areas=G(t,function(a){return $M(this.option,a)},this))},e.prototype.setBrushOption=function(t){this.brushOption=$M(this.option,t),this.brushType=this.brushOption.brushType},e.type="brush",e.dependencies=["geo","grid","xAxis","yAxis","parallel","series"],e.defaultOption={seriesIndex:"all",brushType:"rect",brushMode:"single",transformable:!0,brushStyle:{borderWidth:1,color:"rgba(210,219,238,0.3)",borderColor:"#D2DBEE"},throttleType:"fixRate",throttleDelay:0,removeOnClick:!0,z:1e4},e}(gt);function $M(r,e){return ot({brushType:r.brushType,brushMode:r.brushMode,transformable:r.transformable,brushStyle:new Mt(r.brushStyle).getItemStyle(),removeOnClick:r.removeOnClick,z:r.z},e,!0)}var KU=["rect","polygon","lineX","lineY","keep","clear"],jU=function(r){O(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.render=function(t,a,n){var i,o,s;a.eachComponent({mainType:"brush"},function(l){i=l.brushType,o=l.brushOption.brushMode||"single",s=s||!!l.areas.length}),this._brushType=i,this._brushMode=o,A(t.get("type",!0),function(l){t.setIconStatus(l,(l==="keep"?o==="multiple":l==="clear"?s:l===i)?"emphasis":"normal")})},e.prototype.updateView=function(t,a,n){this.render(t,a,n)},e.prototype.getIcons=function(){var t=this.model,a=t.get("icon",!0),n={};return A(t.get("type",!0),function(i){a[i]&&(n[i]=a[i])}),n},e.prototype.onclick=function(t,a,n){var i=this._brushType,o=this._brushMode;n==="clear"?(a.dispatchAction({type:"axisAreaSelect",intervals:[]}),a.dispatchAction({type:"brush",command:"clear",areas:[]})):a.dispatchAction({type:"takeGlobalCursor",key:"brush",brushOption:{brushType:n==="keep"?i:i===n?!1:n,brushMode:n==="keep"?o==="multiple"?"single":"multiple":o}})},e.getDefaultOption=function(t){var a={show:!0,type:KU.slice(),icon:{rect:"M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13",polygon:"M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2",lineX:"M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4",lineY:"M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4",keep:"M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z",clear:"M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2"},title:t.getLocaleModel().get(["toolbox","brush","title"])};return a},e}(gr);function QU(r){r.registerComponentView(ZU),r.registerComponentModel(qU),r.registerPreprocessor(BU),r.registerVisual(r.PRIORITY.VISUAL.BRUSH,HU),r.registerAction({type:"brush",event:"brush",update:"updateVisual"},function(e,t){t.eachComponent({mainType:"brush",query:e},function(a){a.setAreas(e.areas)})}),r.registerAction({type:"brushSelect",event:"brushSelected",update:"none"},Zt),r.registerAction({type:"brushEnd",event:"brushEnd",update:"none"},Zt),Do("brush",jU)}var JU=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.layoutMode={type:"box",ignoreSize:!0},t}return e.type="title",e.defaultOption={z:6,show:!0,text:"",target:"blank",subtext:"",subtarget:"blank",left:0,top:0,backgroundColor:"rgba(0,0,0,0)",borderColor:"#ccc",borderWidth:0,padding:5,itemGap:10,textStyle:{fontSize:18,fontWeight:"bold",color:"#464646"},subtextStyle:{fontSize:12,color:"#6E7079"}},e}(gt),t8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.render=function(t,a,n){if(this.group.removeAll(),!!t.get("show")){var i=this.group,o=t.getModel("textStyle"),s=t.getModel("subtextStyle"),l=t.get("textAlign"),u=lt(t.get("textBaseline"),t.get("textVerticalAlign")),f=new bt({style:Nt(o,{text:t.get("text"),fill:o.getTextColor()},{disableBox:!0}),z2:10}),h=f.getBoundingRect(),v=t.get("subtext"),c=new bt({style:Nt(s,{text:v,fill:s.getTextColor(),y:h.height+t.get("itemGap"),verticalAlign:"top"},{disableBox:!0}),z2:10}),p=t.get("link"),d=t.get("sublink"),g=t.get("triggerEvent",!0);f.silent=!p&&!g,c.silent=!d&&!g,p&&f.on("click",function(){sf(p,"_"+t.get("target"))}),d&&c.on("click",function(){sf(d,"_"+t.get("subtarget"))}),nt(f).eventData=nt(c).eventData=g?{componentType:"title",componentIndex:t.componentIndex}:null,i.add(f),v&&i.add(c);var y=i.getBoundingRect(),m=t.getBoxLayoutParams();m.width=y.width,m.height=y.height;var _=jt(m,{width:n.getWidth(),height:n.getHeight()},t.get("padding"));l||(l=t.get("left")||t.get("right"),l==="middle"&&(l="center"),l==="right"?_.x+=_.width:l==="center"&&(_.x+=_.width/2)),u||(u=t.get("top")||t.get("bottom"),u==="center"&&(u="middle"),u==="bottom"?_.y+=_.height:u==="middle"&&(_.y+=_.height/2),u=u||"top"),i.x=_.x,i.y=_.y,i.markRedraw();var S={align:l,verticalAlign:u};f.setStyle(S),c.setStyle(S),y=i.getBoundingRect();var b=_.margin,x=t.getItemStyle(["color","opacity"]);x.fill=t.get("backgroundColor");var w=new xt({shape:{x:y.x-b[3],y:y.y-b[0],width:y.width+b[1]+b[3],height:y.height+b[0]+b[2],r:t.get("borderRadius")},style:x,subPixelOptimize:!0,silent:!0});i.add(w)}},e.type="title",e}(Bt);function e8(r){r.registerComponentModel(JU),r.registerComponentView(t8)}var qM=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.layoutMode="box",t}return e.prototype.init=function(t,a,n){this.mergeDefaultAndTheme(t,n),this._initData()},e.prototype.mergeOption=function(t){r.prototype.mergeOption.apply(this,arguments),this._initData()},e.prototype.setCurrentIndex=function(t){t==null&&(t=this.option.currentIndex);var a=this._data.count();this.option.loop?t=(t%a+a)%a:(t>=a&&(t=a-1),t<0&&(t=0)),this.option.currentIndex=t},e.prototype.getCurrentIndex=function(){return this.option.currentIndex},e.prototype.isIndexMax=function(){return this.getCurrentIndex()>=this._data.count()-1},e.prototype.setPlayState=function(t){this.option.autoPlay=!!t},e.prototype.getPlayState=function(){return!!this.option.autoPlay},e.prototype._initData=function(){var t=this.option,a=t.data||[],n=t.axisType,i=this._names=[],o;n==="category"?(o=[],A(a,function(u,f){var h=Jt(Pi(u),""),v;J(u)?(v=et(u),v.value=f):v=f,o.push(v),i.push(h)})):o=a;var s={category:"ordinal",time:"time",value:"number"}[n]||"number",l=this._data=new Te([{name:"value",type:s}],this);l.initData(o,i)},e.prototype.getData=function(){return this._data},e.prototype.getCategories=function(){if(this.get("axisType")==="category")return this._names.slice()},e.type="timeline",e.defaultOption={z:4,show:!0,axisType:"time",realtime:!0,left:"20%",top:null,right:"20%",bottom:0,width:null,height:40,padding:5,controlPosition:"left",autoPlay:!1,rewind:!1,loop:!0,playInterval:2e3,currentIndex:0,itemStyle:{},label:{color:"#000"},data:[]},e}(gt),KM=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="timeline.slider",e.defaultOption=Ua(qM.defaultOption,{backgroundColor:"rgba(0,0,0,0)",borderColor:"#ccc",borderWidth:0,orient:"horizontal",inverse:!1,tooltip:{trigger:"item"},symbol:"circle",symbolSize:12,lineStyle:{show:!0,width:2,color:"#DAE1F5"},label:{position:"auto",show:!0,interval:"auto",rotate:0,color:"#A4B1D7"},itemStyle:{color:"#A4B1D7",borderWidth:1},checkpointStyle:{symbol:"circle",symbolSize:15,color:"#316bf3",borderColor:"#fff",borderWidth:2,shadowBlur:2,shadowOffsetX:1,shadowOffsetY:1,shadowColor:"rgba(0, 0, 0, 0.3)",animation:!0,animationDuration:300,animationEasing:"quinticInOut"},controlStyle:{show:!0,showPlayBtn:!0,showPrevBtn:!0,showNextBtn:!0,itemSize:24,itemGap:12,position:"left",playIcon:"path://M31.6,53C17.5,53,6,41.5,6,27.4S17.5,1.8,31.6,1.8C45.7,1.8,57.2,13.3,57.2,27.4S45.7,53,31.6,53z M31.6,3.3 C18.4,3.3,7.5,14.1,7.5,27.4c0,13.3,10.8,24.1,24.1,24.1C44.9,51.5,55.7,40.7,55.7,27.4C55.7,14.1,44.9,3.3,31.6,3.3z M24.9,21.3 c0-2.2,1.6-3.1,3.5-2l10.5,6.1c1.899,1.1,1.899,2.9,0,4l-10.5,6.1c-1.9,1.1-3.5,0.2-3.5-2V21.3z",stopIcon:"path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z",nextIcon:"M2,18.5A1.52,1.52,0,0,1,.92,18a1.49,1.49,0,0,1,0-2.12L7.81,9.36,1,3.11A1.5,1.5,0,1,1,3,.89l8,7.34a1.48,1.48,0,0,1,.49,1.09,1.51,1.51,0,0,1-.46,1.1L3,18.08A1.5,1.5,0,0,1,2,18.5Z",prevIcon:"M10,.5A1.52,1.52,0,0,1,11.08,1a1.49,1.49,0,0,1,0,2.12L4.19,9.64,11,15.89a1.5,1.5,0,1,1-2,2.22L1,10.77A1.48,1.48,0,0,1,.5,9.68,1.51,1.51,0,0,1,1,8.58L9,.92A1.5,1.5,0,0,1,10,.5Z",prevBtnSize:18,nextBtnSize:18,color:"#A4B1D7",borderColor:"#A4B1D7",borderWidth:1},emphasis:{label:{show:!0,color:"#6f778d"},itemStyle:{color:"#316BF3"},controlStyle:{color:"#316BF3",borderColor:"#316BF3",borderWidth:2}},progress:{lineStyle:{color:"#316BF3"},itemStyle:{color:"#316BF3"},label:{color:"#6f778d"}},data:[]}),e}(qM);Xt(KM,Cp.prototype);var r8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="timeline",e}(Bt),a8=function(r){O(e,r);function e(t,a,n,i){var o=r.call(this,t,a,n)||this;return o.type=i||"value",o}return e.prototype.getLabelModel=function(){return this.model.getModel("label")},e.prototype.isHorizontal=function(){return this.model.get("orient")==="horizontal"},e}(fr),tm=Math.PI,jM=Ct(),n8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(t,a){this.api=a},e.prototype.render=function(t,a,n){if(this.model=t,this.api=n,this.ecModel=a,this.group.removeAll(),t.get("show",!0)){var i=this._layout(t,n),o=this._createGroup("_mainGroup"),s=this._createGroup("_labelGroup"),l=this._axis=this._createAxis(i,t);t.formatTooltip=function(u){var f=l.scale.getLabel({value:u});return ie("nameValue",{noName:!0,value:f})},A(["AxisLine","AxisTick","Control","CurrentPointer"],function(u){this["_render"+u](i,o,l,t)},this),this._renderAxisLabel(i,s,l,t),this._position(i,t)}this._doPlayStop(),this._updateTicksStatus()},e.prototype.remove=function(){this._clearTimer(),this.group.removeAll()},e.prototype.dispose=function(){this._clearTimer()},e.prototype._layout=function(t,a){var n=t.get(["label","position"]),i=t.get("orient"),o=o8(t,a),s;n==null||n==="auto"?s=i==="horizontal"?o.y+o.height/2=0||s==="+"?"left":"right"},u={horizontal:s>=0||s==="+"?"top":"bottom",vertical:"middle"},f={horizontal:0,vertical:tm/2},h=i==="vertical"?o.height:o.width,v=t.getModel("controlStyle"),c=v.get("show",!0),p=c?v.get("itemSize"):0,d=c?v.get("itemGap"):0,g=p+d,y=t.get(["label","rotate"])||0;y=y*tm/180;var m,_,S,b=v.get("position",!0),x=c&&v.get("showPlayBtn",!0),w=c&&v.get("showPrevBtn",!0),T=c&&v.get("showNextBtn",!0),C=0,D=h;b==="left"||b==="bottom"?(x&&(m=[0,0],C+=g),w&&(_=[C,0],C+=g),T&&(S=[D-p,0],D-=g)):(x&&(m=[D-p,0],D-=g),w&&(_=[0,0],C+=g),T&&(S=[D-p,0],D-=g));var M=[C,D];return t.get("inverse")&&M.reverse(),{viewRect:o,mainLength:h,orient:i,rotation:f[i],labelRotation:y,labelPosOpt:s,labelAlign:t.get(["label","align"])||l[i],labelBaseline:t.get(["label","verticalAlign"])||t.get(["label","baseline"])||u[i],playPosition:m,prevBtnPosition:_,nextBtnPosition:S,axisExtent:M,controlSize:p,controlGap:d}},e.prototype._position=function(t,a){var n=this._mainGroup,i=this._labelGroup,o=t.viewRect;if(t.orient==="vertical"){var s=Ge(),l=o.x,u=o.y+o.height;mr(s,s,[-l,-u]),Ia(s,s,-tm/2),mr(s,s,[l,u]),o=o.clone(),o.applyTransform(s)}var f=m(o),h=m(n.getBoundingRect()),v=m(i.getBoundingRect()),c=[n.x,n.y],p=[i.x,i.y];p[0]=c[0]=f[0][0];var d=t.labelPosOpt;if(d==null||U(d)){var g=d==="+"?0:1;_(c,h,f,1,g),_(p,v,f,1,1-g)}else{var g=d>=0?0:1;_(c,h,f,1,g),p[1]=c[1]+d}n.setPosition(c),i.setPosition(p),n.rotation=i.rotation=t.rotation,y(n),y(i);function y(S){S.originX=f[0][0]-S.x,S.originY=f[1][0]-S.y}function m(S){return[[S.x,S.x+S.width],[S.y,S.y+S.height]]}function _(S,b,x,w,T){S[w]+=x[w][T]-b[w][T]}},e.prototype._createAxis=function(t,a){var n=a.getData(),i=a.get("axisType"),o=i8(a,i);o.getTicks=function(){return n.mapArray(["value"],function(u){return{value:u}})};var s=n.getDataExtent("value");o.setExtent(s[0],s[1]),o.calcNiceTicks();var l=new a8("value",o,t.axisExtent,i);return l.model=a,l},e.prototype._createGroup=function(t){var a=this[t]=new rt;return this.group.add(a),a},e.prototype._renderAxisLine=function(t,a,n,i){var o=n.getExtent();if(!!i.get(["lineStyle","show"])){var s=new te({shape:{x1:o[0],y1:0,x2:o[1],y2:0},style:B({lineCap:"round"},i.getModel("lineStyle").getLineStyle()),silent:!0,z2:1});a.add(s);var l=this._progressLine=new te({shape:{x1:o[0],x2:this._currentPointer?this._currentPointer.x:o[0],y1:0,y2:0},style:j({lineCap:"round",lineWidth:s.style.lineWidth},i.getModel(["progress","lineStyle"]).getLineStyle()),silent:!0,z2:1});a.add(l)}},e.prototype._renderAxisTick=function(t,a,n,i){var o=this,s=i.getData(),l=n.scale.getTicks();this._tickSymbols=[],A(l,function(u){var f=n.dataToCoord(u.value),h=s.getItemModel(u.value),v=h.getModel("itemStyle"),c=h.getModel(["emphasis","itemStyle"]),p=h.getModel(["progress","itemStyle"]),d={x:f,y:0,onclick:Y(o._changeTimeline,o,u.value)},g=QM(h,v,a,d);g.ensureState("emphasis").style=c.getItemStyle(),g.ensureState("progress").style=p.getItemStyle(),Ga(g);var y=nt(g);h.get("tooltip")?(y.dataIndex=u.value,y.dataModel=i):y.dataIndex=y.dataModel=null,o._tickSymbols.push(g)})},e.prototype._renderAxisLabel=function(t,a,n,i){var o=this,s=n.getLabelModel();if(!!s.get("show")){var l=i.getData(),u=n.getViewLabels();this._tickLabels=[],A(u,function(f){var h=f.tickValue,v=l.getItemModel(h),c=v.getModel("label"),p=v.getModel(["emphasis","label"]),d=v.getModel(["progress","label"]),g=n.dataToCoord(f.tickValue),y=new bt({x:g,y:0,rotation:t.labelRotation-t.rotation,onclick:Y(o._changeTimeline,o,h),silent:!1,style:Nt(c,{text:f.formattedLabel,align:t.labelAlign,verticalAlign:t.labelBaseline})});y.ensureState("emphasis").style=Nt(p),y.ensureState("progress").style=Nt(d),a.add(y),Ga(y),jM(y).dataIndex=h,o._tickLabels.push(y)})}},e.prototype._renderControl=function(t,a,n,i){var o=t.controlSize,s=t.rotation,l=i.getModel("controlStyle").getItemStyle(),u=i.getModel(["emphasis","controlStyle"]).getItemStyle(),f=i.getPlayState(),h=i.get("inverse",!0);v(t.nextBtnPosition,"next",Y(this._changeTimeline,this,h?"-":"+")),v(t.prevBtnPosition,"prev",Y(this._changeTimeline,this,h?"+":"-")),v(t.playPosition,f?"stop":"play",Y(this._handlePlayClick,this,!f),!0);function v(c,p,d,g){if(!!c){var y=br(lt(i.get(["controlStyle",p+"BtnSize"]),o),o),m=[0,-y/2,y,y],_=s8(i,p+"Icon",m,{x:c[0],y:c[1],originX:o/2,originY:0,rotation:g?-s:0,rectHover:!0,style:l,onclick:d});_.ensureState("emphasis").style=u,a.add(_),Ga(_)}}},e.prototype._renderCurrentPointer=function(t,a,n,i){var o=i.getData(),s=i.getCurrentIndex(),l=o.getItemModel(s).getModel("checkpointStyle"),u=this,f={onCreate:function(h){h.draggable=!0,h.drift=Y(u._handlePointerDrag,u),h.ondragend=Y(u._handlePointerDragend,u),JM(h,u._progressLine,s,n,i,!0)},onUpdate:function(h){JM(h,u._progressLine,s,n,i)}};this._currentPointer=QM(l,l,this._mainGroup,{},this._currentPointer,f)},e.prototype._handlePlayClick=function(t){this._clearTimer(),this.api.dispatchAction({type:"timelinePlayChange",playState:t,from:this.uid})},e.prototype._handlePointerDrag=function(t,a,n){this._clearTimer(),this._pointerChangeTimeline([n.offsetX,n.offsetY])},e.prototype._handlePointerDragend=function(t){this._pointerChangeTimeline([t.offsetX,t.offsetY],!0)},e.prototype._pointerChangeTimeline=function(t,a){var n=this._toAxisCoord(t)[0],i=this._axis,o=We(i.getExtent().slice());n>o[1]&&(n=o[1]),n=0&&(o[i]=+o[i].toFixed(v)),[o,h]}var am={min:it(Fh,"min"),max:it(Fh,"max"),average:it(Fh,"average"),median:it(Fh,"median")};function Bl(r,e){if(!!e){var t=r.getData(),a=r.coordinateSystem,n=a.dimensions;if(!c8(e)&&!z(e.coord)&&a){var i=eI(e,t,a,r);if(e=et(e),e.type&&am[e.type]&&i.baseAxis&&i.valueAxis){var o=vt(n,i.baseAxis.dim),s=vt(n,i.valueAxis.dim),l=am[e.type](t,i.baseDataDim,i.valueDataDim,o,s);e.coord=l[0],e.value=l[1]}else e.coord=[e.xAxis!=null?e.xAxis:e.radiusAxis,e.yAxis!=null?e.yAxis:e.angleAxis]}if(e.coord==null)e.coord=[];else for(var u=e.coord,f=0;f<2;f++)am[u[f]]&&(u[f]=nm(t,t.mapDimension(n[f]),u[f]));return e}}function eI(r,e,t,a){var n={};return r.valueIndex!=null||r.valueDim!=null?(n.valueDataDim=r.valueIndex!=null?e.getDimension(r.valueIndex):r.valueDim,n.valueAxis=t.getAxis(p8(a,n.valueDataDim)),n.baseAxis=t.getOtherAxis(n.valueAxis),n.baseDataDim=e.mapDimension(n.baseAxis.dim)):(n.baseAxis=a.getBaseAxis(),n.valueAxis=t.getOtherAxis(n.baseAxis),n.baseDataDim=e.mapDimension(n.baseAxis.dim),n.valueDataDim=e.mapDimension(n.valueAxis.dim)),n}function p8(r,e){var t=r.getData().getDimensionInfo(e);return t&&t.coordDim}function Vl(r,e){return r&&r.containData&&e.coord&&!rm(e)?r.containData(e.coord):!0}function d8(r,e,t){return r&&r.containZone&&e.coord&&t.coord&&!rm(e)&&!rm(t)?r.containZone(e.coord,t.coord):!0}function rI(r,e){return r?function(t,a,n,i){var o=i<2?t.coord&&t.coord[i]:t.value;return Za(o,e[i])}:function(t,a,n,i){return Za(t.value,e[i])}}function nm(r,e,t){if(t==="average"){var a=0,n=0;return r.each(e,function(i,o){isNaN(i)||(a+=i,n++)}),a/n}else return t==="median"?r.getMedian(e):r.getDataExtent(e)[t==="max"?1:0]}var im=Ct(),om=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.init=function(){this.markerGroupMap=$()},e.prototype.render=function(t,a,n){var i=this,o=this.markerGroupMap;o.each(function(s){im(s).keep=!1}),a.eachSeries(function(s){var l=wa.getMarkerModelFromSeries(s,i.type);l&&i.renderSeries(s,l,a,n)}),o.each(function(s){!im(s).keep&&i.group.remove(s.group)})},e.prototype.markKeep=function(t){im(t).keep=!0},e.prototype.toggleBlurSeries=function(t,a){var n=this;A(t,function(i){var o=wa.getMarkerModelFromSeries(i,n.type);if(o){var s=o.getData();s.eachItemGraphicEl(function(l){l&&(a?F_(l):Pc(l))})}})},e.type="marker",e}(Bt);function aI(r,e,t){var a=e.coordinateSystem;r.each(function(n){var i=r.getItemModel(n),o,s=H(i.get("x"),t.getWidth()),l=H(i.get("y"),t.getHeight());if(!isNaN(s)&&!isNaN(l))o=[s,l];else if(e.getMarkerPosition)o=e.getMarkerPosition(r.getValues(r.dimensions,n));else if(a){var u=r.get(a.dimensions[0],n),f=r.get(a.dimensions[1],n);o=a.dataToPoint([u,f])}isNaN(s)||(o[0]=s),isNaN(l)||(o[1]=l),r.setItemLayout(n,o)})}var g8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.updateTransform=function(t,a,n){a.eachSeries(function(i){var o=wa.getMarkerModelFromSeries(i,"markPoint");o&&(aI(o.getData(),i,n),this.markerGroupMap.get(i.id).updateLayout())},this)},e.prototype.renderSeries=function(t,a,n,i){var o=t.coordinateSystem,s=t.id,l=t.getData(),u=this.markerGroupMap,f=u.get(s)||u.set(s,new fl),h=y8(o,t,a);a.setData(h),aI(a.getData(),t,i),h.each(function(v){var c=h.getItemModel(v),p=c.getShallow("symbol"),d=c.getShallow("symbolSize"),g=c.getShallow("symbolRotate"),y=c.getShallow("symbolOffset"),m=c.getShallow("symbolKeepAspect");if(K(p)||K(d)||K(g)||K(y)){var _=a.getRawValue(v),S=a.getDataParams(v);K(p)&&(p=p(_,S)),K(d)&&(d=d(_,S)),K(g)&&(g=g(_,S)),K(y)&&(y=y(_,S))}var b=c.getModel("itemStyle").getItemStyle(),x=Us(l,"color");b.fill||(b.fill=x),h.setItemVisual(v,{symbol:p,symbolSize:d,symbolRotate:g,symbolOffset:y,symbolKeepAspect:m,style:b})}),f.updateData(h),this.group.add(f.group),h.eachItemGraphicEl(function(v){v.traverse(function(c){nt(c).dataModel=a})}),this.markKeep(f),f.group.silent=a.get("silent")||t.get("silent")},e.type="markPoint",e}(om);function y8(r,e,t){var a;r?a=G(r&&r.dimensions,function(s){var l=e.getData().getDimensionInfo(e.getData().mapDimension(s))||{};return B(B({},l),{name:s,ordinalMeta:null})}):a=[{name:"value",type:"float"}];var n=new Te(a,t),i=G(t.get("data"),it(Bl,e));r&&(i=Lt(i,it(Vl,r)));var o=rI(!!r,a);return n.initData(i,null,o),n}function m8(r){r.registerComponentModel(v8),r.registerComponentView(g8),r.registerPreprocessor(function(e){em(e.series,"markPoint")&&(e.markPoint=e.markPoint||{})})}var _8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.createMarkerModelFromSeries=function(t,a,n){return new e(t,a,n)},e.type="markLine",e.defaultOption={z:5,symbol:["circle","arrow"],symbolSize:[8,16],symbolOffset:0,precision:2,tooltip:{trigger:"item"},label:{show:!0,position:"end",distance:5},lineStyle:{type:"dashed"},emphasis:{label:{show:!0},lineStyle:{width:3}},animationEasing:"linear"},e}(wa),Hh=Ct(),S8=function(r,e,t,a){var n=r.getData(),i;if(z(a))i=a;else{var o=a.type;if(o==="min"||o==="max"||o==="average"||o==="median"||a.xAxis!=null||a.yAxis!=null){var s=void 0,l=void 0;if(a.yAxis!=null||a.xAxis!=null)s=e.getAxis(a.yAxis!=null?"y":"x"),l=ee(a.yAxis,a.xAxis);else{var u=eI(a,n,e,r);s=u.valueAxis;var f=ld(n,u.valueDataDim);l=nm(n,f,o)}var h=s.dim==="x"?0:1,v=1-h,c=et(a),p={coord:[]};c.type=null,c.coord=[],c.coord[v]=-Infinity,p.coord[v]=Infinity;var d=t.get("precision");d>=0&&Tt(l)&&(l=+l.toFixed(Math.min(d,20))),c.coord[h]=p.coord[h]=l,i=[c,p,{type:o,valueIndex:a.valueIndex,value:l}]}else i=[]}var g=[Bl(r,i[0]),Bl(r,i[1]),B({},i[2])];return g[2].type=g[2].type||null,ot(g[2],g[0]),ot(g[2],g[1]),g};function Wh(r){return!isNaN(r)&&!isFinite(r)}function nI(r,e,t,a){var n=1-r,i=a.dimensions[r];return Wh(e[n])&&Wh(t[n])&&e[r]===t[r]&&a.getAxis(i).containData(e[r])}function x8(r,e){if(r.type==="cartesian2d"){var t=e[0].coord,a=e[1].coord;if(t&&a&&(nI(1,t,a,r)||nI(0,t,a,r)))return!0}return Vl(r,e[0])&&Vl(r,e[1])}function sm(r,e,t,a,n){var i=a.coordinateSystem,o=r.getItemModel(e),s,l=H(o.get("x"),n.getWidth()),u=H(o.get("y"),n.getHeight());if(!isNaN(l)&&!isNaN(u))s=[l,u];else{if(a.getMarkerPosition)s=a.getMarkerPosition(r.getValues(r.dimensions,e));else{var f=i.dimensions,h=r.get(f[0],e),v=r.get(f[1],e);s=i.dataToPoint([h,v])}if(ni(i,"cartesian2d")){var c=i.getAxis("x"),p=i.getAxis("y"),f=i.dimensions;Wh(r.get(f[0],e))?s[0]=c.toGlobalCoord(c.getExtent()[t?0:1]):Wh(r.get(f[1],e))&&(s[1]=p.toGlobalCoord(p.getExtent()[t?0:1]))}isNaN(l)||(s[0]=l),isNaN(u)||(s[1]=u)}r.setItemLayout(e,s)}var b8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.updateTransform=function(t,a,n){a.eachSeries(function(i){var o=wa.getMarkerModelFromSeries(i,"markLine");if(o){var s=o.getData(),l=Hh(o).from,u=Hh(o).to;l.each(function(f){sm(l,f,!0,i,n),sm(u,f,!1,i,n)}),s.each(function(f){s.setItemLayout(f,[l.getItemLayout(f),u.getItemLayout(f)])}),this.markerGroupMap.get(i.id).updateLayout()}},this)},e.prototype.renderSeries=function(t,a,n,i){var o=t.coordinateSystem,s=t.id,l=t.getData(),u=this.markerGroupMap,f=u.get(s)||u.set(s,new kg);this.group.add(f.group);var h=w8(o,t,a),v=h.from,c=h.to,p=h.line;Hh(a).from=v,Hh(a).to=c,a.setData(p);var d=a.get("symbol"),g=a.get("symbolSize"),y=a.get("symbolRotate"),m=a.get("symbolOffset");z(d)||(d=[d,d]),z(g)||(g=[g,g]),z(y)||(y=[y,y]),z(m)||(m=[m,m]),h.from.each(function(S){_(v,S,!0),_(c,S,!1)}),p.each(function(S){var b=p.getItemModel(S).getModel("lineStyle").getLineStyle();p.setItemLayout(S,[v.getItemLayout(S),c.getItemLayout(S)]),b.stroke==null&&(b.stroke=v.getItemVisual(S,"style").fill),p.setItemVisual(S,{fromSymbolKeepAspect:v.getItemVisual(S,"symbolKeepAspect"),fromSymbolOffset:v.getItemVisual(S,"symbolOffset"),fromSymbolRotate:v.getItemVisual(S,"symbolRotate"),fromSymbolSize:v.getItemVisual(S,"symbolSize"),fromSymbol:v.getItemVisual(S,"symbol"),toSymbolKeepAspect:c.getItemVisual(S,"symbolKeepAspect"),toSymbolOffset:c.getItemVisual(S,"symbolOffset"),toSymbolRotate:c.getItemVisual(S,"symbolRotate"),toSymbolSize:c.getItemVisual(S,"symbolSize"),toSymbol:c.getItemVisual(S,"symbol"),style:b})}),f.updateData(p),h.line.eachItemGraphicEl(function(S){nt(S).dataModel=a,S.traverse(function(b){nt(b).dataModel=a})});function _(S,b,x){var w=S.getItemModel(b);sm(S,b,x,t,i);var T=w.getModel("itemStyle").getItemStyle();T.fill==null&&(T.fill=Us(l,"color")),S.setItemVisual(b,{symbolKeepAspect:w.get("symbolKeepAspect"),symbolOffset:lt(w.get("symbolOffset",!0),m[x?0:1]),symbolRotate:lt(w.get("symbolRotate",!0),y[x?0:1]),symbolSize:lt(w.get("symbolSize"),g[x?0:1]),symbol:lt(w.get("symbol",!0),d[x?0:1]),style:T})}this.markKeep(f),f.group.silent=a.get("silent")||t.get("silent")},e.type="markLine",e}(om);function w8(r,e,t){var a;r?a=G(r&&r.dimensions,function(u){var f=e.getData().getDimensionInfo(e.getData().mapDimension(u))||{};return B(B({},f),{name:u,ordinalMeta:null})}):a=[{name:"value",type:"float"}];var n=new Te(a,t),i=new Te(a,t),o=new Te([],t),s=G(t.get("data"),it(S8,e,r,t));r&&(s=Lt(s,it(x8,r)));var l=rI(!!r,a);return n.initData(G(s,function(u){return u[0]}),null,l),i.initData(G(s,function(u){return u[1]}),null,l),o.initData(G(s,function(u){return u[2]})),o.hasItemOption=!0,{from:n,to:i,line:o}}function T8(r){r.registerComponentModel(_8),r.registerComponentView(b8),r.registerPreprocessor(function(e){em(e.series,"markLine")&&(e.markLine=e.markLine||{})})}var C8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.createMarkerModelFromSeries=function(t,a,n){return new e(t,a,n)},e.type="markArea",e.defaultOption={z:1,tooltip:{trigger:"item"},animation:!1,label:{show:!0,position:"top"},itemStyle:{borderWidth:0},emphasis:{label:{show:!0,position:"top"}}},e}(wa),Uh=Ct(),A8=function(r,e,t,a){var n=a[0],i=a[1];if(!(!n||!i)){var o=Bl(r,n),s=Bl(r,i),l=o.coord,u=s.coord;l[0]=ee(l[0],-Infinity),l[1]=ee(l[1],-Infinity),u[0]=ee(u[0],Infinity),u[1]=ee(u[1],Infinity);var f=Zl([{},o,s]);return f.coord=[o.coord,s.coord],f.x0=o.x,f.y0=o.y,f.x1=s.x,f.y1=s.y,f}};function Yh(r){return!isNaN(r)&&!isFinite(r)}function iI(r,e,t,a){var n=1-r;return Yh(e[n])&&Yh(t[n])}function D8(r,e){var t=e.coord[0],a=e.coord[1],n={coord:t,x:e.x0,y:e.y0},i={coord:a,x:e.x1,y:e.y1};return ni(r,"cartesian2d")?t&&a&&(iI(1,t,a)||iI(0,t,a))?!0:d8(r,n,i):Vl(r,n)||Vl(r,i)}function oI(r,e,t,a,n){var i=a.coordinateSystem,o=r.getItemModel(e),s,l=H(o.get(t[0]),n.getWidth()),u=H(o.get(t[1]),n.getHeight());if(!isNaN(l)&&!isNaN(u))s=[l,u];else{if(a.getMarkerPosition){var f=r.getValues(["x0","y0"],e),h=r.getValues(["x1","y1"],e),v=i.clampData(f),c=i.clampData(h),p=[];t[0]==="x0"?p[0]=v[0]>c[0]?h[0]:f[0]:p[0]=v[0]>c[0]?f[0]:h[0],t[1]==="y0"?p[1]=v[1]>c[1]?h[1]:f[1]:p[1]=v[1]>c[1]?f[1]:h[1],s=a.getMarkerPosition(p,t,!0)}else{var d=r.get(t[0],e),g=r.get(t[1],e),y=[d,g];i.clampData&&i.clampData(y,y),s=i.dataToPoint(y,!0)}if(ni(i,"cartesian2d")){var m=i.getAxis("x"),_=i.getAxis("y"),d=r.get(t[0],e),g=r.get(t[1],e);Yh(d)?s[0]=m.toGlobalCoord(m.getExtent()[t[0]==="x0"?0:1]):Yh(g)&&(s[1]=_.toGlobalCoord(_.getExtent()[t[1]==="y0"?0:1]))}isNaN(l)||(s[0]=l),isNaN(u)||(s[1]=u)}return s}var sI=[["x0","y0"],["x1","y0"],["x1","y1"],["x0","y1"]],M8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.updateTransform=function(t,a,n){a.eachSeries(function(i){var o=wa.getMarkerModelFromSeries(i,"markArea");if(o){var s=o.getData();s.each(function(l){var u=G(sI,function(h){return oI(s,l,h,i,n)});s.setItemLayout(l,u);var f=s.getItemGraphicEl(l);f.setShape("points",u)})}},this)},e.prototype.renderSeries=function(t,a,n,i){var o=t.coordinateSystem,s=t.id,l=t.getData(),u=this.markerGroupMap,f=u.get(s)||u.set(s,{group:new rt});this.group.add(f.group),this.markKeep(f);var h=I8(o,t,a);a.setData(h),h.each(function(v){var c=G(sI,function(T){return oI(h,v,T,t,i)}),p=o.getAxis("x").scale,d=o.getAxis("y").scale,g=p.getExtent(),y=d.getExtent(),m=[p.parse(h.get("x0",v)),p.parse(h.get("x1",v))],_=[d.parse(h.get("y0",v)),d.parse(h.get("y1",v))];We(m),We(_);var S=!(g[0]>m[1]||g[1]_[1]||y[1]<_[0]),b=!S;h.setItemLayout(v,{points:c,allClipped:b});var x=h.getItemModel(v).getModel("itemStyle").getItemStyle(),w=Us(l,"color");x.fill||(x.fill=w,U(x.fill)&&(x.fill=Jo(x.fill,.4))),x.stroke||(x.stroke=w),h.setItemVisual(v,"style",x)}),h.diff(Uh(f).data).add(function(v){var c=h.getItemLayout(v);if(!c.allClipped){var p=new _e({shape:{points:c.points}});h.setItemGraphicEl(v,p),f.group.add(p)}}).update(function(v,c){var p=Uh(f).data.getItemGraphicEl(c),d=h.getItemLayout(v);d.allClipped?p&&f.group.remove(p):(p?At(p,{shape:{points:d.points}},a,v):p=new _e({shape:{points:d.points}}),h.setItemGraphicEl(v,p),f.group.add(p))}).remove(function(v){var c=Uh(f).data.getItemGraphicEl(v);f.group.remove(c)}).execute(),h.eachItemGraphicEl(function(v,c){var p=h.getItemModel(c),d=h.getItemVisual(c,"style");v.useStyle(h.getItemVisual(c,"style")),ve(v,ne(p),{labelFetcher:a,labelDataIndex:c,defaultText:h.getName(c)||"",inheritColor:U(d.fill)?Jo(d.fill,1):"#000"}),he(v,p),Ut(v,null,null,p.get(["emphasis","disabled"])),nt(v).dataModel=a}),Uh(f).data=h,f.group.silent=a.get("silent")||t.get("silent")},e.type="markArea",e}(om);function I8(r,e,t){var a,n,i=["x0","y0","x1","y1"];if(r){var o=G(r&&r.dimensions,function(u){var f=e.getData(),h=f.getDimensionInfo(f.mapDimension(u))||{};return B(B({},h),{name:u,ordinalMeta:null})});n=G(i,function(u,f){return{name:u,type:o[f%2].type}}),a=new Te(n,t)}else n=[{name:"value",type:"float"}],a=new Te(n,t);var s=G(t.get("data"),it(A8,e,r,t));r&&(s=Lt(s,it(D8,r)));var l=r?function(u,f,h,v){var c=u.coord[Math.floor(v/2)][v%2];return Za(c,n[v])}:function(u,f,h,v){return Za(u.value,n[v])};return a.initData(s,null,l),a.hasItemOption=!0,a}function L8(r){r.registerComponentModel(C8),r.registerComponentView(M8),r.registerPreprocessor(function(e){em(e.series,"markArea")&&(e.markArea=e.markArea||{})})}var P8=function(r,e){if(e==="all")return{type:"all",title:r.getLocaleModel().get(["legend","selector","all"])};if(e==="inverse")return{type:"inverse",title:r.getLocaleModel().get(["legend","selector","inverse"])}},lm=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.layoutMode={type:"box",ignoreSize:!0},t}return e.prototype.init=function(t,a,n){this.mergeDefaultAndTheme(t,n),t.selected=t.selected||{},this._updateSelector(t)},e.prototype.mergeOption=function(t,a){r.prototype.mergeOption.call(this,t,a),this._updateSelector(t)},e.prototype._updateSelector=function(t){var a=t.selector,n=this.ecModel;a===!0&&(a=t.selector=["all","inverse"]),z(a)&&A(a,function(i,o){U(i)&&(i={type:i}),a[o]=ot(i,P8(n,i.type))})},e.prototype.optionUpdated=function(){this._updateData(this.ecModel);var t=this._data;if(t[0]&&this.get("selectedMode")==="single"){for(var a=!1,n=0;n=0},e.prototype.getOrient=function(){return this.get("orient")==="vertical"?{index:1,name:"vertical"}:{index:0,name:"horizontal"}},e.type="legend.plain",e.dependencies=["series"],e.defaultOption={z:4,show:!0,orient:"horizontal",left:"center",top:0,align:"auto",backgroundColor:"rgba(0,0,0,0)",borderColor:"#ccc",borderRadius:0,borderWidth:0,padding:5,itemGap:10,itemWidth:25,itemHeight:14,symbolRotate:"inherit",symbolKeepAspect:!0,inactiveColor:"#ccc",inactiveBorderColor:"#ccc",inactiveBorderWidth:"auto",itemStyle:{color:"inherit",opacity:"inherit",borderColor:"inherit",borderWidth:"auto",borderCap:"inherit",borderJoin:"inherit",borderDashOffset:"inherit",borderMiterLimit:"inherit"},lineStyle:{width:"auto",color:"inherit",inactiveColor:"#ccc",inactiveWidth:2,opacity:"inherit",type:"inherit",cap:"inherit",join:"inherit",dashOffset:"inherit",miterLimit:"inherit"},textStyle:{color:"#333"},selectedMode:!0,selector:!1,selectorLabel:{show:!0,borderRadius:10,padding:[3,5,3,5],fontSize:12,fontFamily:"sans-serif",color:"#666",borderWidth:1,borderColor:"#666"},emphasis:{selectorLabel:{show:!0,color:"#eee",backgroundColor:"#666"}},selectorPosition:"auto",selectorItemGap:7,selectorButtonGap:10,tooltip:{show:!1}},e}(gt),Io=it,um=A,Xh=rt,lI=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.newlineDisabled=!1,t}return e.prototype.init=function(){this.group.add(this._contentGroup=new Xh),this.group.add(this._selectorGroup=new Xh),this._isFirstRender=!0},e.prototype.getContentGroup=function(){return this._contentGroup},e.prototype.getSelectorGroup=function(){return this._selectorGroup},e.prototype.render=function(t,a,n){var i=this._isFirstRender;if(this._isFirstRender=!1,this.resetInner(),!!t.get("show",!0)){var o=t.get("align"),s=t.get("orient");(!o||o==="auto")&&(o=t.get("left")==="right"&&s==="vertical"?"right":"left");var l=t.get("selector",!0),u=t.get("selectorPosition",!0);l&&(!u||u==="auto")&&(u=s==="horizontal"?"end":"start"),this.renderInner(o,t,a,n,l,s,u);var f=t.getBoxLayoutParams(),h={width:n.getWidth(),height:n.getHeight()},v=t.get("padding"),c=jt(f,h,v),p=this.layoutInner(t,o,c,i,l,u),d=jt(j({width:p.width,height:p.height},f),h,v);this.group.x=d.x-p.x,this.group.y=d.y-p.y,this.group.markRedraw(),this.group.add(this._backgroundEl=yM(p,t))}},e.prototype.resetInner=function(){this.getContentGroup().removeAll(),this._backgroundEl&&this.group.remove(this._backgroundEl),this.getSelectorGroup().removeAll()},e.prototype.renderInner=function(t,a,n,i,o,s,l){var u=this.getContentGroup(),f=$(),h=a.get("selectedMode"),v=[];n.eachRawSeries(function(c){!c.get("legendHoverLink")&&v.push(c.id)}),um(a.getData(),function(c,p){var d=c.get("name");if(!this.newlineDisabled&&(d===""||d===` +`)){var g=new Xh;g.newline=!0,u.add(g);return}var y=n.getSeriesByName(d)[0];if(!f.get(d))if(y){var m=y.getData(),_=m.getVisual("legendLineStyle")||{},S=m.getVisual("legendIcon"),b=m.getVisual("style"),x=this._createItem(y,d,p,c,a,t,_,b,S,h,i);x.on("click",Io(uI,d,null,i,v)).on("mouseover",Io(fm,y.name,null,i,v)).on("mouseout",Io(hm,y.name,null,i,v)),f.set(d,!0)}else n.eachRawSeries(function(w){if(!f.get(d)&&w.legendVisualProvider){var T=w.legendVisualProvider;if(!T.containName(d))return;var C=T.indexOfName(d),D=T.getItemVisual(C,"style"),M=T.getItemVisual(C,"legendIcon"),I=Ae(D.fill);I&&I[3]===0&&(I[3]=.2,D=B(B({},D),{fill:Sr(I,"rgba")}));var L=this._createItem(w,d,p,c,a,t,{},D,M,h,i);L.on("click",Io(uI,null,d,i,v)).on("mouseover",Io(fm,null,d,i,v)).on("mouseout",Io(hm,null,d,i,v)),f.set(d,!0)}},this)},this),o&&this._createSelector(o,a,i,s,l)},e.prototype._createSelector=function(t,a,n,i,o){var s=this.getSelectorGroup();um(t,function(u){var f=u.type,h=new bt({style:{x:0,y:0,align:"center",verticalAlign:"middle"},onclick:function(){n.dispatchAction({type:f==="all"?"legendAllSelect":"legendInverseSelect"})}});s.add(h);var v=a.getModel("selectorLabel"),c=a.getModel(["emphasis","selectorLabel"]);ve(h,{normal:v,emphasis:c},{defaultText:u.title}),Ga(h)})},e.prototype._createItem=function(t,a,n,i,o,s,l,u,f,h,v){var c=t.visualDrawType,p=o.get("itemWidth"),d=o.get("itemHeight"),g=o.isSelected(a),y=i.get("symbolRotate"),m=i.get("symbolKeepAspect"),_=i.get("icon");f=_||f||"roundRect";var S=R8(f,i,l,u,c,g,v),b=new Xh,x=i.getModel("textStyle");if(K(t.getLegendIcon)&&(!_||_==="inherit"))b.add(t.getLegendIcon({itemWidth:p,itemHeight:d,icon:f,iconRotate:y,itemStyle:S.itemStyle,lineStyle:S.lineStyle,symbolKeepAspect:m}));else{var w=_==="inherit"&&t.getData().getVisual("symbol")?y==="inherit"?t.getData().getVisual("symbolRotate"):y:0;b.add(E8({itemWidth:p,itemHeight:d,icon:f,iconRotate:w,itemStyle:S.itemStyle,lineStyle:S.lineStyle,symbolKeepAspect:m}))}var T=s==="left"?p+5:-5,C=s,D=o.get("formatter"),M=a;U(D)&&D?M=D.replace("{name}",a!=null?a:""):K(D)&&(M=D(a));var I=i.get("inactiveColor");b.add(new bt({style:Nt(x,{text:M,x:T,y:d/2,fill:g?x.getTextColor():I,align:C,verticalAlign:"middle"})}));var L=new xt({shape:b.getBoundingRect(),invisible:!0}),P=i.getModel("tooltip");return P.get("show")&&Yi({el:L,componentModel:o,itemName:a,itemTooltipOption:P.option}),b.add(L),b.eachChild(function(R){R.silent=!0}),L.silent=!h,this.getContentGroup().add(b),Ga(b),b.__legendDataIndex=n,b},e.prototype.layoutInner=function(t,a,n,i,o,s){var l=this.getContentGroup(),u=this.getSelectorGroup();Fn(t.get("orient"),l,t.get("itemGap"),n.width,n.height);var f=l.getBoundingRect(),h=[-f.x,-f.y];if(u.markRedraw(),l.markRedraw(),o){Fn("horizontal",u,t.get("selectorItemGap",!0));var v=u.getBoundingRect(),c=[-v.x,-v.y],p=t.get("selectorButtonGap",!0),d=t.getOrient().index,g=d===0?"width":"height",y=d===0?"height":"width",m=d===0?"y":"x";s==="end"?c[d]+=f[g]+p:h[d]+=v[g]+p,c[1-d]+=f[y]/2-v[y]/2,u.x=c[0],u.y=c[1],l.x=h[0],l.y=h[1];var _={x:0,y:0};return _[g]=f[g]+p+v[g],_[y]=Math.max(f[y],v[y]),_[m]=Math.min(0,v[m]+c[1-d]),_}else return l.x=h[0],l.y=h[1],this.group.getBoundingRect()},e.prototype.remove=function(){this.getContentGroup().removeAll(),this._isFirstRender=!0},e.type="legend.plain",e}(Bt);function R8(r,e,t,a,n,i,o){function s(g,y){g.lineWidth==="auto"&&(g.lineWidth=y.lineWidth>0?2:0),um(g,function(m,_){g[_]==="inherit"&&(g[_]=y[_])})}var l=e.getModel("itemStyle"),u=l.getItemStyle(),f=r.lastIndexOf("empty",0)===0?"fill":"stroke",h=l.getShallow("decal");u.decal=!h||h==="inherit"?a.decal:so(h,o),u.fill==="inherit"&&(u.fill=a[n]),u.stroke==="inherit"&&(u.stroke=a[f]),u.opacity==="inherit"&&(u.opacity=(n==="fill"?a:t).opacity),s(u,a);var v=e.getModel("lineStyle"),c=v.getLineStyle();if(s(c,t),u.fill==="auto"&&(u.fill=a.fill),u.stroke==="auto"&&(u.stroke=a.fill),c.stroke==="auto"&&(c.stroke=a.fill),!i){var p=e.get("inactiveBorderWidth"),d=u[f];u.lineWidth=p==="auto"?a.lineWidth>0&&d?2:0:u.lineWidth,u.fill=e.get("inactiveColor"),u.stroke=e.get("inactiveBorderColor"),c.stroke=v.get("inactiveColor"),c.lineWidth=v.get("inactiveWidth")}return{itemStyle:u,lineStyle:c}}function E8(r){var e=r.icon||"roundRect",t=$t(e,0,0,r.itemWidth,r.itemHeight,r.itemStyle.fill,r.symbolKeepAspect);return t.setStyle(r.itemStyle),t.rotation=(r.iconRotate||0)*Math.PI/180,t.setOrigin([r.itemWidth/2,r.itemHeight/2]),e.indexOf("empty")>-1&&(t.style.stroke=t.style.fill,t.style.fill="#fff",t.style.lineWidth=2),t}function uI(r,e,t,a){hm(r,e,t,a),t.dispatchAction({type:"legendToggleSelect",name:r!=null?r:e}),fm(r,e,t,a)}function fI(r){for(var e=r.getZr().storage.getDisplayList(),t,a=0,n=e.length;an[o],g=[-c.x,-c.y];a||(g[i]=f[u]);var y=[0,0],m=[-p.x,-p.y],_=lt(t.get("pageButtonGap",!0),t.get("itemGap",!0));if(d){var S=t.get("pageButtonPosition",!0);S==="end"?m[i]+=n[o]-p[o]:y[i]+=p[o]+_}m[1-i]+=c[s]/2-p[s]/2,f.setPosition(g),h.setPosition(y),v.setPosition(m);var b={x:0,y:0};if(b[o]=d?n[o]:c[o],b[s]=Math.max(c[s],p[s]),b[l]=Math.min(0,p[l]+m[1-i]),h.__rectSize=n[o],d){var x={x:0,y:0};x[o]=Math.max(n[o]-p[o]-_,0),x[s]=b[s],h.setClipPath(new xt({shape:x})),h.__rectSize=x[o]}else v.eachChild(function(T){T.attr({invisible:!0,silent:!0})});var w=this._getPageInfo(t);return w.pageIndex!=null&&At(f,{x:w.contentPosition[0],y:w.contentPosition[1]},d?t:null),this._updatePageInfoView(t,w),b},e.prototype._pageGo=function(t,a,n){var i=this._getPageInfo(a)[t];i!=null&&n.dispatchAction({type:"legendScroll",scrollDataIndex:i,legendId:a.id})},e.prototype._updatePageInfoView=function(t,a){var n=this._controllerGroup;A(["pagePrev","pageNext"],function(f){var h=f+"DataIndex",v=a[h]!=null,c=n.childOfName(f);c&&(c.setStyle("fill",v?t.get("pageIconColor",!0):t.get("pageIconInactiveColor",!0)),c.cursor=v?"pointer":"default")});var i=n.childOfName("pageText"),o=t.get("pageFormatter"),s=a.pageIndex,l=s!=null?s+1:0,u=a.pageCount;i&&o&&i.setStyle("text",U(o)?o.replace("{current}",l==null?"":l+"").replace("{total}",u==null?"":u+""):o({current:l,total:u}))},e.prototype._getPageInfo=function(t){var a=t.get("scrollDataIndex",!0),n=this.getContentGroup(),i=this._containerGroup.__rectSize,o=t.getOrient().index,s=vm[o],l=cm[o],u=this._findTargetItemIndex(a),f=n.children(),h=f[u],v=f.length,c=v?1:0,p={contentPosition:[n.x,n.y],pageCount:c,pageIndex:c-1,pagePrevDataIndex:null,pageNextDataIndex:null};if(!h)return p;var d=S(h);p.contentPosition[o]=-d.s;for(var g=u+1,y=d,m=d,_=null;g<=v;++g)_=S(f[g]),(!_&&m.e>y.s+i||_&&!b(_,y.s))&&(m.i>y.i?y=m:y=_,y&&(p.pageNextDataIndex==null&&(p.pageNextDataIndex=y.i),++p.pageCount)),m=_;for(var g=u-1,y=d,m=d,_=null;g>=-1;--g)_=S(f[g]),(!_||!b(m,_.s))&&y.i=w&&x.s<=w+i}},e.prototype._findTargetItemIndex=function(t){if(!this._showController)return 0;var a,n=this.getContentGroup(),i;return n.eachChild(function(o,s){var l=o.__legendDataIndex;i==null&&l!=null&&(i=s),l===t&&(a=s)}),a!=null?a:i},e.type="legend.scroll",e}(lI);function V8(r){r.registerAction("legendScroll","legendscroll",function(e,t){var a=e.scrollDataIndex;a!=null&&t.eachComponent({mainType:"legend",subType:"scroll",query:e},function(n){n.setScrollDataIndex(a)})})}function z8(r){ct(hI),r.registerComponentModel(N8),r.registerComponentView(B8),V8(r)}function G8(r){ct(hI),ct(z8)}var F8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="dataZoom.inside",e.defaultOption=Ua(kl.defaultOption,{disabled:!1,zoomLock:!1,zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0}),e}(kl),pm=Ct();function H8(r,e,t){pm(r).coordSysRecordMap.each(function(a){var n=a.dataZoomInfoMap.get(e.uid);n&&(n.getRange=t)})}function W8(r,e){for(var t=pm(r).coordSysRecordMap,a=t.keys(),n=0;na[t+e]&&(e=s),n=n&&o.get("preventDefaultMouseMove",!0)}),{controlType:e,opt:{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!0,preventDefaultMouseMove:!!n}}}function $8(r){r.registerProcessor(r.PRIORITY.PROCESSOR.FILTER,function(e,t){var a=pm(t),n=a.coordSysRecordMap||(a.coordSysRecordMap=$());n.each(function(i){i.dataZoomInfoMap=null}),e.eachComponent({mainType:"dataZoom",subType:"inside"},function(i){var o=hM(i);A(o.infoList,function(s){var l=s.model.uid,u=n.get(l)||n.set(l,U8(t,s.model)),f=u.dataZoomInfoMap||(u.dataZoomInfoMap=$());f.set(i.uid,{dzReferCoordSysInfo:s,model:i,getRange:null})})}),n.each(function(i){var o=i.controller,s,l=i.dataZoomInfoMap;if(l){var u=l.keys()[0];u!=null&&(s=l.get(u))}if(!s){pI(n,i);return}var f=Z8(l);o.enable(f.controlType,f.opt),o.setPointerChecker(i.containsPoint),ao(i,"dispatchAction",s.model.get("throttle",!0),"fixRate")})})}var q8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type="dataZoom.inside",t}return e.prototype.render=function(t,a,n){if(r.prototype.render.apply(this,arguments),t.noTarget()){this._clear();return}this.range=t.getPercentRange(),H8(n,t,{pan:Y(dm.pan,this),zoom:Y(dm.zoom,this),scrollMove:Y(dm.scrollMove,this)})},e.prototype.dispose=function(){this._clear(),r.prototype.dispose.apply(this,arguments)},e.prototype._clear=function(){W8(this.api,this.dataZoomModel),this.range=null},e.type="dataZoom.inside",e}(Fy),dm={zoom:function(r,e,t,a){var n=this.range,i=n.slice(),o=r.axisModels[0];if(!!o){var s=gm[e](null,[a.originX,a.originY],o,t,r),l=(s.signal>0?s.pixelStart+s.pixelLength-s.pixel:s.pixel-s.pixelStart)/s.pixelLength*(i[1]-i[0])+i[0],u=Math.max(1/a.scale,0);i[0]=(i[0]-l)*u+l,i[1]=(i[1]-l)*u+l;var f=this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();if(hi(0,i,[0,100],0,f.minSpan,f.maxSpan),this.range=i,n[0]!==i[0]||n[1]!==i[1])return i}},pan:dI(function(r,e,t,a,n,i){var o=gm[a]([i.oldX,i.oldY],[i.newX,i.newY],e,n,t);return o.signal*(r[1]-r[0])*o.pixel/o.pixelLength}),scrollMove:dI(function(r,e,t,a,n,i){var o=gm[a]([0,0],[i.scrollDelta,i.scrollDelta],e,n,t);return o.signal*(r[1]-r[0])*i.scrollDelta})};function dI(r){return function(e,t,a,n){var i=this.range,o=i.slice(),s=e.axisModels[0];if(!!s){var l=r(o,s,e,t,a,n);if(hi(l,o,[0,100],"all"),this.range=o,i[0]!==o[0]||i[1]!==o[1])return o}}}var gm={grid:function(r,e,t,a,n){var i=t.axis,o={},s=n.model.coordinateSystem.getRect();return r=r||[0,0],i.dim==="x"?(o.pixel=e[0]-r[0],o.pixelLength=s.width,o.pixelStart=s.x,o.signal=i.inverse?1:-1):(o.pixel=e[1]-r[1],o.pixelLength=s.height,o.pixelStart=s.y,o.signal=i.inverse?-1:1),o},polar:function(r,e,t,a,n){var i=t.axis,o={},s=n.model.coordinateSystem,l=s.getRadiusAxis().getExtent(),u=s.getAngleAxis().getExtent();return r=r?s.pointToCoord(r):[0,0],e=s.pointToCoord(e),t.mainType==="radiusAxis"?(o.pixel=e[0]-r[0],o.pixelLength=l[1]-l[0],o.pixelStart=l[0],o.signal=i.inverse?1:-1):(o.pixel=e[1]-r[1],o.pixelLength=u[1]-u[0],o.pixelStart=u[0],o.signal=i.inverse?-1:1),o},singleAxis:function(r,e,t,a,n){var i=t.axis,o=n.model.coordinateSystem.getRect(),s={};return r=r||[0,0],i.orient==="horizontal"?(s.pixel=e[0]-r[0],s.pixelLength=o.width,s.pixelStart=o.x,s.signal=i.inverse?1:-1):(s.pixel=e[1]-r[1],s.pixelLength=o.height,s.pixelStart=o.y,s.signal=i.inverse?-1:1),s}};function gI(r){Hy(r),r.registerComponentModel(F8),r.registerComponentView(q8),$8(r)}var K8=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.type="dataZoom.slider",e.layoutMode="box",e.defaultOption=Ua(kl.defaultOption,{show:!0,right:"ph",top:"ph",width:"ph",height:"ph",left:null,bottom:null,borderColor:"#d2dbee",borderRadius:3,backgroundColor:"rgba(47,69,84,0)",dataBackground:{lineStyle:{color:"#d2dbee",width:.5},areaStyle:{color:"#d2dbee",opacity:.2}},selectedDataBackground:{lineStyle:{color:"#8fb0f7",width:.5},areaStyle:{color:"#8fb0f7",opacity:.2}},fillerColor:"rgba(135,175,274,0.2)",handleIcon:"path://M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z",handleSize:"100%",handleStyle:{color:"#fff",borderColor:"#ACB8D1"},moveHandleSize:7,moveHandleIcon:"path://M-320.9-50L-320.9-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-348-41-339-50-320.9-50z M-212.3-50L-212.3-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-239.4-41-230.4-50-212.3-50z M-103.7-50L-103.7-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-130.9-41-121.8-50-103.7-50z",moveHandleStyle:{color:"#D2DBEE",opacity:.7},showDetail:!0,showDataShadow:"auto",realtime:!0,zoomLock:!1,textStyle:{color:"#6E7079"},brushSelect:!0,brushStyle:{color:"rgba(135,175,274,0.15)"},emphasis:{handleStyle:{borderColor:"#8FB0F7"},moveHandleStyle:{color:"#8FB0F7"}}}),e}(kl),Gl=xt,yI=7,j8=1,ym=30,Q8=7,Fl="horizontal",mI="vertical",J8=5,tY=["line","bar","candlestick","scatter"],eY={easing:"cubicOut",duration:100,delay:0},rY=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t._displayables={},t}return e.prototype.init=function(t,a){this.api=a,this._onBrush=Y(this._onBrush,this),this._onBrushEnd=Y(this._onBrushEnd,this)},e.prototype.render=function(t,a,n,i){if(r.prototype.render.apply(this,arguments),ao(this,"_dispatchZoomAction",t.get("throttle"),"fixRate"),this._orient=t.getOrient(),t.get("show")===!1){this.group.removeAll();return}if(t.noTarget()){this._clear(),this.group.removeAll();return}(!i||i.type!=="dataZoom"||i.from!==this.uid)&&this._buildView(),this._updateView()},e.prototype.dispose=function(){this._clear(),r.prototype.dispose.apply(this,arguments)},e.prototype._clear=function(){Fs(this,"_dispatchZoomAction");var t=this.api.getZr();t.off("mousemove",this._onBrush),t.off("mouseup",this._onBrushEnd)},e.prototype._buildView=function(){var t=this.group;t.removeAll(),this._brushing=!1,this._displayables.brushRect=null,this._resetLocation(),this._resetInterval();var a=this._displayables.sliderGroup=new rt;this._renderBackground(),this._renderHandle(),this._renderDataShadow(),t.add(a),this._positionGroup()},e.prototype._resetLocation=function(){var t=this.dataZoomModel,a=this.api,n=t.get("brushSelect"),i=n?Q8:0,o=this._findCoordRect(),s={width:a.getWidth(),height:a.getHeight()},l=this._orient===Fl?{right:s.width-o.x-o.width,top:s.height-ym-yI-i,width:o.width,height:ym}:{right:yI,top:o.y,width:ym,height:o.height},u=Ki(t.option);A(["right","top","width","height"],function(h){u[h]==="ph"&&(u[h]=l[h])});var f=jt(u,s);this._location={x:f.x,y:f.y},this._size=[f.width,f.height],this._orient===mI&&this._size.reverse()},e.prototype._positionGroup=function(){var t=this.group,a=this._location,n=this._orient,i=this.dataZoomModel.getFirstTargetAxisModel(),o=i&&i.get("inverse"),s=this._displayables.sliderGroup,l=(this._dataShadowInfo||{}).otherAxisInverse;s.attr(n===Fl&&!o?{scaleY:l?1:-1,scaleX:1}:n===Fl&&o?{scaleY:l?1:-1,scaleX:-1}:n===mI&&!o?{scaleY:l?-1:1,scaleX:1,rotation:Math.PI/2}:{scaleY:l?-1:1,scaleX:-1,rotation:Math.PI/2});var u=t.getBoundingRect([s]);t.x=a.x-u.x,t.y=a.y-u.y,t.markRedraw()},e.prototype._getViewExtent=function(){return[0,this._size[0]]},e.prototype._renderBackground=function(){var t=this.dataZoomModel,a=this._size,n=this._displayables.sliderGroup,i=t.get("brushSelect");n.add(new Gl({silent:!0,shape:{x:0,y:0,width:a[0],height:a[1]},style:{fill:t.get("backgroundColor")},z2:-40}));var o=new Gl({shape:{x:0,y:0,width:a[0],height:a[1]},style:{fill:"transparent"},z2:0,onclick:Y(this._onClickPanel,this)}),s=this.api.getZr();i?(o.on("mousedown",this._onBrushStart,this),o.cursor="crosshair",s.on("mousemove",this._onBrush),s.on("mouseup",this._onBrushEnd)):(s.off("mousemove",this._onBrush),s.off("mouseup",this._onBrushEnd)),n.add(o)},e.prototype._renderDataShadow=function(){var t=this._dataShadowInfo=this._prepareDataShadowInfo();if(this._displayables.dataShadowSegs=[],!t)return;var a=this._size,n=this._shadowSize||[],i=t.series,o=i.getRawData(),s=i.getShadowDim&&i.getShadowDim(),l=s&&o.getDimensionInfo(s)?i.getShadowDim():t.otherDim;if(l==null)return;var u=this._shadowPolygonPts,f=this._shadowPolylinePts;if(o!==this._shadowData||l!==this._shadowDim||a[0]!==n[0]||a[1]!==n[1]){var h=o.getDataExtent(l),v=(h[1]-h[0])*.3;h=[h[0]-v,h[1]+v];var c=[0,a[1]],p=[0,a[0]],d=[[a[0],0],[0,0]],g=[],y=p[1]/(o.count()-1),m=0,_=Math.round(o.count()/a[0]),S;o.each([l],function(C,D){if(_>0&&D%_){m+=y;return}var M=C==null||isNaN(C)||C==="",I=M?0:Pt(C,h,c,!0);M&&!S&&D?(d.push([d[d.length-1][0],0]),g.push([g[g.length-1][0],0])):!M&&S&&(d.push([m,0]),g.push([m,0])),d.push([m,I]),g.push([m,I]),m+=y,S=M}),u=this._shadowPolygonPts=d,f=this._shadowPolylinePts=g}this._shadowData=o,this._shadowDim=l,this._shadowSize=[a[0],a[1]];var b=this.dataZoomModel;function x(C){var D=b.getModel(C?"selectedDataBackground":"dataBackground"),M=new rt,I=new _e({shape:{points:u},segmentIgnoreThreshold:1,style:D.getModel("areaStyle").getAreaStyle(),silent:!0,z2:-20}),L=new Se({shape:{points:f},segmentIgnoreThreshold:1,style:D.getModel("lineStyle").getLineStyle(),silent:!0,z2:-19});return M.add(I),M.add(L),M}for(var w=0;w<3;w++){var T=x(w===1);this._displayables.sliderGroup.add(T),this._displayables.dataShadowSegs.push(T)}},e.prototype._prepareDataShadowInfo=function(){var t=this.dataZoomModel,a=t.get("showDataShadow");if(a!==!1){var n,i=this.ecModel;return t.eachTargetAxis(function(o,s){var l=t.getAxisProxy(o,s).getTargetSeriesModels();A(l,function(u){if(!n&&!(a!==!0&&vt(tY,u.get("type"))<0)){var f=i.getComponent(sn(o),s).axis,h=aY(o),v,c=u.coordinateSystem;h!=null&&c.getOtherAxis&&(v=c.getOtherAxis(f).inverse),h=u.getData().mapDimension(h),n={thisAxis:f,series:u,thisDim:o,otherDim:h,otherAxisInverse:v}}},this)},this),n}},e.prototype._renderHandle=function(){var t=this.group,a=this._displayables,n=a.handles=[null,null],i=a.handleLabels=[null,null],o=this._displayables.sliderGroup,s=this._size,l=this.dataZoomModel,u=this.api,f=l.get("borderRadius")||0,h=l.get("brushSelect"),v=a.filler=new Gl({silent:h,style:{fill:l.get("fillerColor")},textConfig:{position:"inside"}});o.add(v),o.add(new Gl({silent:!0,subPixelOptimize:!0,shape:{x:0,y:0,width:s[0],height:s[1],r:f},style:{stroke:l.get("dataBackgroundColor")||l.get("borderColor"),lineWidth:j8,fill:"rgba(0,0,0,0)"}})),A([0,1],function(_){var S=l.get("handleIcon");!xf[S]&&S.indexOf("path://")<0&&S.indexOf("image://")<0&&(S="path://"+S);var b=$t(S,-1,0,2,2,null,!0);b.attr({cursor:_I(this._orient),draggable:!0,drift:Y(this._onDragMove,this,_),ondragend:Y(this._onDragEnd,this),onmouseover:Y(this._showDataInfo,this,!0),onmouseout:Y(this._showDataInfo,this,!1),z2:5});var x=b.getBoundingRect(),w=l.get("handleSize");this._handleHeight=H(w,this._size[1]),this._handleWidth=x.width/x.height*this._handleHeight,b.setStyle(l.getModel("handleStyle").getItemStyle()),b.style.strokeNoScale=!0,b.rectHover=!0,b.ensureState("emphasis").style=l.getModel(["emphasis","handleStyle"]).getItemStyle(),Ga(b);var T=l.get("handleColor");T!=null&&(b.style.fill=T),o.add(n[_]=b);var C=l.getModel("textStyle");t.add(i[_]=new bt({silent:!0,invisible:!0,style:Nt(C,{x:0,y:0,text:"",verticalAlign:"middle",align:"center",fill:C.getTextColor(),font:C.getFont()}),z2:10}))},this);var c=v;if(h){var p=H(l.get("moveHandleSize"),s[1]),d=a.moveHandle=new xt({style:l.getModel("moveHandleStyle").getItemStyle(),silent:!0,shape:{r:[0,0,2,2],y:s[1]-.5,height:p}}),g=p*.8,y=a.moveHandleIcon=$t(l.get("moveHandleIcon"),-g/2,-g/2,g,g,"#fff",!0);y.silent=!0,y.y=s[1]+p/2-.5,d.ensureState("emphasis").style=l.getModel(["emphasis","moveHandleStyle"]).getItemStyle();var m=Math.min(s[1]/2,Math.max(p,10));c=a.moveZone=new xt({invisible:!0,shape:{y:s[1]-m,height:p+m}}),c.on("mouseover",function(){u.enterEmphasis(d)}).on("mouseout",function(){u.leaveEmphasis(d)}),o.add(d),o.add(y),o.add(c)}c.attr({draggable:!0,cursor:_I(this._orient),drift:Y(this._onDragMove,this,"all"),ondragstart:Y(this._showDataInfo,this,!0),ondragend:Y(this._onDragEnd,this),onmouseover:Y(this._showDataInfo,this,!0),onmouseout:Y(this._showDataInfo,this,!1)})},e.prototype._resetInterval=function(){var t=this._range=this.dataZoomModel.getPercentRange(),a=this._getViewExtent();this._handleEnds=[Pt(t[0],[0,100],a,!0),Pt(t[1],[0,100],a,!0)]},e.prototype._updateInterval=function(t,a){var n=this.dataZoomModel,i=this._handleEnds,o=this._getViewExtent(),s=n.findRepresentativeAxisProxy().getMinMaxSpan(),l=[0,100];hi(a,i,o,n.get("zoomLock")?"all":t,s.minSpan!=null?Pt(s.minSpan,l,o,!0):null,s.maxSpan!=null?Pt(s.maxSpan,l,o,!0):null);var u=this._range,f=this._range=We([Pt(i[0],o,l,!0),Pt(i[1],o,l,!0)]);return!u||u[0]!==f[0]||u[1]!==f[1]},e.prototype._updateView=function(t){var a=this._displayables,n=this._handleEnds,i=We(n.slice()),o=this._size;A([0,1],function(c){var p=a.handles[c],d=this._handleHeight;p.attr({scaleX:d/2,scaleY:d/2,x:n[c]+(c?-1:1),y:o[1]/2-d/2})},this),a.filler.setShape({x:i[0],y:0,width:i[1]-i[0],height:o[1]});var s={x:i[0],width:i[1]-i[0]};a.moveHandle&&(a.moveHandle.setShape(s),a.moveZone.setShape(s),a.moveZone.getBoundingRect(),a.moveHandleIcon&&a.moveHandleIcon.attr("x",s.x+s.width/2));for(var l=a.dataShadowSegs,u=[0,i[0],i[1],o[0]],f=0;fa[0]||n[1]<0||n[1]>a[1])){var i=this._handleEnds,o=(i[0]+i[1])/2,s=this._updateInterval("all",n[0]-o);this._updateView(),s&&this._dispatchZoomAction(!1)}},e.prototype._onBrushStart=function(t){var a=t.offsetX,n=t.offsetY;this._brushStart=new ut(a,n),this._brushing=!0,this._brushStartTime=+new Date},e.prototype._onBrushEnd=function(t){if(!!this._brushing){var a=this._displayables.brushRect;if(this._brushing=!1,!!a){a.attr("ignore",!0);var n=a.shape,i=+new Date;if(!(i-this._brushStartTime<200&&Math.abs(n.width)<5)){var o=this._getViewExtent(),s=[0,100];this._range=We([Pt(n.x,o,s,!0),Pt(n.x+n.width,o,s,!0)]),this._handleEnds=[n.x,n.x+n.width],this._updateView(),this._dispatchZoomAction(!1)}}}},e.prototype._onBrush=function(t){this._brushing&&(ia(t.event),this._updateBrushRect(t.offsetX,t.offsetY))},e.prototype._updateBrushRect=function(t,a){var n=this._displayables,i=this.dataZoomModel,o=n.brushRect;o||(o=n.brushRect=new Gl({silent:!0,style:i.getModel("brushStyle").getItemStyle()}),n.sliderGroup.add(o)),o.attr("ignore",!1);var s=this._brushStart,l=this._displayables.sliderGroup,u=l.transformCoordToLocal(t,a),f=l.transformCoordToLocal(s.x,s.y),h=this._size;u[0]=Math.max(Math.min(h[0],u[0]),0),o.setShape({x:f[0],y:0,width:u[0]-f[0],height:h[1]})},e.prototype._dispatchZoomAction=function(t){var a=this._range;this.api.dispatchAction({type:"dataZoom",from:this.uid,dataZoomId:this.dataZoomModel.id,animation:t?eY:null,start:a[0],end:a[1]})},e.prototype._findCoordRect=function(){var t,a=hM(this.dataZoomModel).infoList;if(!t&&a.length){var n=a[0].model.coordinateSystem;t=n.getRect&&n.getRect()}if(!t){var i=this.api.getWidth(),o=this.api.getHeight();t={x:i*.2,y:o*.2,width:i*.6,height:o*.6}}return t},e.type="dataZoom.slider",e}(Fy);function aY(r){var e={x:"y",y:"x",radius:"angle",angle:"radius"};return e[r]}function _I(r){return r==="vertical"?"ns-resize":"ew-resize"}function SI(r){r.registerComponentModel(K8),r.registerComponentView(rY),Hy(r)}function nY(r){ct(gI),ct(SI)}var xI={get:function(r,e,t){var a=et((iY[r]||{})[e]);return t&&z(a)?a[a.length-1]:a}},iY={color:{active:["#006edd","#e0ffff"],inactive:["rgba(0,0,0,0)"]},colorHue:{active:[0,360],inactive:[0,0]},colorSaturation:{active:[.3,1],inactive:[0,0]},colorLightness:{active:[.9,.5],inactive:[0,0]},colorAlpha:{active:[.3,1],inactive:[0,0]},opacity:{active:[.3,1],inactive:[0,0]},symbol:{active:["circle","roundRect","diamond"],inactive:["none"]},symbolSize:{active:[10,50],inactive:[0,0]}},bI=se.mapVisual,oY=se.eachVisual,sY=z,wI=A,lY=We,uY=Pt,Zh=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.stateList=["inRange","outOfRange"],t.replacableOptionKeys=["inRange","outOfRange","target","controller","color"],t.layoutMode={type:"box",ignoreSize:!0},t.dataBound=[-Infinity,Infinity],t.targetVisuals={},t.controllerVisuals={},t}return e.prototype.init=function(t,a,n){this.mergeDefaultAndTheme(t,n)},e.prototype.optionUpdated=function(t,a){var n=this.option;!a&&FM(n,t,this.replacableOptionKeys),this.textStyleModel=this.getModel("textStyle"),this.resetItemSize(),this.completeVisualOption()},e.prototype.resetVisual=function(t){var a=this.stateList;t=Y(t,this),this.controllerVisuals=jy(this.option.controller,a,t),this.targetVisuals=jy(this.option.target,a,t)},e.prototype.getItemSymbol=function(){return null},e.prototype.getTargetSeriesIndices=function(){var t=this.option.seriesIndex,a=[];return t==null||t==="all"?this.ecModel.eachSeries(function(n,i){a.push(i)}):a=Et(t),a},e.prototype.eachTargetSeries=function(t,a){A(this.getTargetSeriesIndices(),function(n){var i=this.ecModel.getSeriesByIndex(n);i&&t.call(a,i)},this)},e.prototype.isTargetSeries=function(t){var a=!1;return this.eachTargetSeries(function(n){n===t&&(a=!0)}),a},e.prototype.formatValueText=function(t,a,n){var i=this.option,o=i.precision,s=this.dataBound,l=i.formatter,u;n=n||["<",">"],z(t)&&(t=t.slice(),u=!0);var f=a?t:u?[h(t[0]),h(t[1])]:h(t);if(U(l))return l.replace("{value}",u?f[0]:f).replace("{value2}",u?f[1]:f);if(K(l))return u?l(t[0],t[1]):l(t);if(u)return t[0]===s[0]?n[0]+" "+f[1]:t[1]===s[1]?n[1]+" "+f[0]:f[0]+" - "+f[1];return f;function h(v){return v===s[0]?"min":v===s[1]?"max":(+v).toFixed(Math.min(o,20))}},e.prototype.resetExtent=function(){var t=this.option,a=lY([t.min,t.max]);this._dataExtent=a},e.prototype.getDataDimensionIndex=function(t){var a=this.option.dimension;if(a!=null)return t.getDimensionIndex(a);for(var n=t.dimensions,i=n.length-1;i>=0;i--){var o=n[i],s=t.getDimensionInfo(o);if(!s.isCalculationCoord)return s.storeDimIndex}},e.prototype.getExtent=function(){return this._dataExtent.slice()},e.prototype.completeVisualOption=function(){var t=this.ecModel,a=this.option,n={inRange:a.inRange,outOfRange:a.outOfRange},i=a.target||(a.target={}),o=a.controller||(a.controller={});ot(i,n),ot(o,n);var s=this.isCategory();l.call(this,i),l.call(this,o),u.call(this,i,"inRange","outOfRange"),f.call(this,o);function l(h){sY(a.color)&&!h.inRange&&(h.inRange={color:a.color.slice().reverse()}),h.inRange=h.inRange||{color:t.get("gradientColor")}}function u(h,v,c){var p=h[v],d=h[c];p&&!d&&(d=h[c]={},wI(p,function(g,y){if(!!se.isValidType(y)){var m=xI.get(y,"inactive",s);m!=null&&(d[y]=m,y==="color"&&!d.hasOwnProperty("opacity")&&!d.hasOwnProperty("colorAlpha")&&(d.opacity=[0,0]))}}))}function f(h){var v=(h.inRange||{}).symbol||(h.outOfRange||{}).symbol,c=(h.inRange||{}).symbolSize||(h.outOfRange||{}).symbolSize,p=this.get("inactiveColor"),d=this.getItemSymbol(),g=d||"roundRect";wI(this.stateList,function(y){var m=this.itemSize,_=h[y];_||(_=h[y]={color:s?p:[p]}),_.symbol==null&&(_.symbol=v&&et(v)||(s?g:[g])),_.symbolSize==null&&(_.symbolSize=c&&et(c)||(s?m[0]:[m[0],m[0]])),_.symbol=bI(_.symbol,function(x){return x==="none"?g:x});var S=_.symbolSize;if(S!=null){var b=-Infinity;oY(S,function(x){x>b&&(b=x)}),_.symbolSize=bI(S,function(x){return uY(x,[0,b],[0,m[0]],!0)})}},this)}},e.prototype.resetItemSize=function(){this.itemSize=[parseFloat(this.get("itemWidth")),parseFloat(this.get("itemHeight"))]},e.prototype.isCategory=function(){return!!this.option.categories},e.prototype.setSelected=function(t){},e.prototype.getSelected=function(){return null},e.prototype.getValueState=function(t){return null},e.prototype.getVisualMeta=function(t){return null},e.type="visualMap",e.dependencies=["series"],e.defaultOption={show:!0,z:4,seriesIndex:"all",min:0,max:200,left:0,right:null,top:null,bottom:0,itemWidth:null,itemHeight:null,inverse:!1,orient:"vertical",backgroundColor:"rgba(0,0,0,0)",borderColor:"#ccc",contentColor:"#5793f3",inactiveColor:"#aaa",borderWidth:0,padding:5,textGap:10,precision:0,textStyle:{color:"#333"}},e}(gt),TI=[20,140],fY=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.optionUpdated=function(t,a){r.prototype.optionUpdated.apply(this,arguments),this.resetExtent(),this.resetVisual(function(n){n.mappingMethod="linear",n.dataExtent=this.getExtent()}),this._resetRange()},e.prototype.resetItemSize=function(){r.prototype.resetItemSize.apply(this,arguments);var t=this.itemSize;(t[0]==null||isNaN(t[0]))&&(t[0]=TI[0]),(t[1]==null||isNaN(t[1]))&&(t[1]=TI[1])},e.prototype._resetRange=function(){var t=this.getExtent(),a=this.option.range;!a||a.auto?(t.auto=1,this.option.range=t):z(a)&&(a[0]>a[1]&&a.reverse(),a[0]=Math.max(a[0],t[0]),a[1]=Math.min(a[1],t[1]))},e.prototype.completeVisualOption=function(){r.prototype.completeVisualOption.apply(this,arguments),A(this.stateList,function(t){var a=this.option.controller[t].symbolSize;a&&a[0]!==a[1]&&(a[0]=a[1]/3)},this)},e.prototype.setSelected=function(t){this.option.range=t.slice(),this._resetRange()},e.prototype.getSelected=function(){var t=this.getExtent(),a=We((this.get("range")||[]).slice());return a[0]>t[1]&&(a[0]=t[1]),a[1]>t[1]&&(a[1]=t[1]),a[0]=n[1]||t<=a[1])?"inRange":"outOfRange"},e.prototype.findTargetDataIndices=function(t){var a=[];return this.eachTargetSeries(function(n){var i=[],o=n.getData();o.each(this.getDataDimensionIndex(o),function(s,l){t[0]<=s&&s<=t[1]&&i.push(l)},this),a.push({seriesId:n.id,dataIndex:i})},this),a},e.prototype.getVisualMeta=function(t){var a=CI(this,"outOfRange",this.getExtent()),n=CI(this,"inRange",this.option.range.slice()),i=[];function o(c,p){i.push({value:c,color:t(c,p)})}for(var s=0,l=0,u=n.length,f=a.length;lt[1])break;i.push({color:this.getControllerVisual(l,"color",a),offset:s/n})}return i.push({color:this.getControllerVisual(t[1],"color",a),offset:1}),i},e.prototype._createBarPoints=function(t,a){var n=this.visualMapModel.itemSize;return[[n[0]-a[0],t[0]],[n[0],t[0]],[n[0],t[1]],[n[0]-a[1],t[1]]]},e.prototype._createBarGroup=function(t){var a=this._orient,n=this.visualMapModel.get("inverse");return new rt(a==="horizontal"&&!n?{scaleX:t==="bottom"?1:-1,rotation:Math.PI/2}:a==="horizontal"&&n?{scaleX:t==="bottom"?-1:1,rotation:-Math.PI/2}:a==="vertical"&&!n?{scaleX:t==="left"?1:-1,scaleY:-1}:{scaleX:t==="left"?1:-1})},e.prototype._updateHandle=function(t,a){if(!!this._useHandle){var n=this._shapes,i=this.visualMapModel,o=n.handleThumbs,s=n.handleLabels,l=i.itemSize,u=i.getExtent();hY([0,1],function(f){var h=o[f];h.setStyle("fill",a.handlesColor[f]),h.y=t[f];var v=Jr(t[f],[0,l[1]],u,!0),c=this.getControllerVisual(v,"symbolSize");h.scaleX=h.scaleY=c/l[0],h.x=l[0]-c/2;var p=Ar(n.handleLabelPoints[f],Ha(h,this.group));s[f].setStyle({x:p[0],y:p[1],text:i.formatValueText(this._dataInterval[f]),verticalAlign:"middle",align:this._orient==="vertical"?this._applyTransform("left",n.mainGroup):"center"})},this)}},e.prototype._showIndicator=function(t,a,n,i){var o=this.visualMapModel,s=o.getExtent(),l=o.itemSize,u=[0,l[1]],f=this._shapes,h=f.indicator;if(!!h){h.attr("invisible",!1);var v={convertOpacityToAlpha:!0},c=this.getControllerVisual(t,"color",v),p=this.getControllerVisual(t,"symbolSize"),d=Jr(t,s,u,!0),g=l[0]-p/2,y={x:h.x,y:h.y};h.y=d,h.x=g;var m=Ar(f.indicatorLabelPoint,Ha(h,this.group)),_=f.indicatorLabel;_.attr("invisible",!1);var S=this._applyTransform("left",f.mainGroup),b=this._orient,x=b==="horizontal";_.setStyle({text:(n||"")+o.formatValueText(a),verticalAlign:x?S:"middle",align:x?"center":S});var w={x:g,y:d,style:{fill:c}},T={style:{x:m[0],y:m[1]}};if(o.ecModel.isAnimationEnabled()&&!this._firstShowIndicator){var C={duration:100,easing:"cubicInOut",additive:!0};h.x=y.x,h.y=y.y,h.animateTo(w,C),_.animateTo(T,C)}else h.attr(w),_.attr(T);this._firstShowIndicator=!1;var D=this._shapes.handleLabels;if(D)for(var M=0;Mo[1]&&(h[1]=Infinity),a&&(h[0]===-Infinity?this._showIndicator(f,h[1],"< ",l):h[1]===Infinity?this._showIndicator(f,h[0],"> ",l):this._showIndicator(f,f,"\u2248 ",l));var v=this._hoverLinkDataIndices,c=[];(a||PI(n))&&(c=this._hoverLinkDataIndices=n.findTargetDataIndices(h));var p=hP(v,c);this._dispatchHighDown("downplay",$h(p[0],n)),this._dispatchHighDown("highlight",$h(p[1],n))}},e.prototype._hoverLinkFromSeriesMouseOver=function(t){var a;if(Yn(t.target,function(l){var u=nt(l);if(u.dataIndex!=null)return a=u,!0},!0),!!a){var n=this.ecModel.getSeriesByIndex(a.seriesIndex),i=this.visualMapModel;if(!!i.isTargetSeries(n)){var o=n.getData(a.dataType),s=o.getStore().get(i.getDataDimensionIndex(o),a.dataIndex);isNaN(s)||this._showIndicator(s,s)}}},e.prototype._hideIndicator=function(){var t=this._shapes;t.indicator&&t.indicator.attr("invisible",!0),t.indicatorLabel&&t.indicatorLabel.attr("invisible",!0);var a=this._shapes.handleLabels;if(a)for(var n=0;n=0&&(i.dimension=o,a.push(i))}}),r.getData().setVisual("visualMeta",a)}}];function _Y(r,e,t,a){for(var n=e.targetVisuals[a],i=se.prepareVisualTypes(n),o={color:Us(r.getData(),"color")},s=0,l=i.length;s0:e.splitNumber>0)||e.calculable)?"continuous":"piecewise"}),r.registerAction(gY,yY),A(mY,function(e){r.registerVisual(r.PRIORITY.VISUAL.COMPONENT,e)}),r.registerPreprocessor(SY))}function NI(r){r.registerComponentModel(fY),r.registerComponentView(pY),OI(r)}var xY=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t._pieceList=[],t}return e.prototype.optionUpdated=function(t,a){r.prototype.optionUpdated.apply(this,arguments),this.resetExtent();var n=this._mode=this._determineMode();this._pieceList=[],bY[this._mode].call(this,this._pieceList),this._resetSelected(t,a);var i=this.option.categories;this.resetVisual(function(o,s){n==="categories"?(o.mappingMethod="category",o.categories=et(i)):(o.dataExtent=this.getExtent(),o.mappingMethod="piecewise",o.pieceList=G(this._pieceList,function(l){return l=et(l),s!=="inRange"&&(l.visual=null),l}))})},e.prototype.completeVisualOption=function(){var t=this.option,a={},n=se.listVisualTypes(),i=this.isCategory();A(t.pieces,function(s){A(n,function(l){s.hasOwnProperty(l)&&(a[l]=1)})}),A(a,function(s,l){var u=!1;A(this.stateList,function(f){u=u||o(t,f,l)||o(t.target,f,l)},this),!u&&A(this.stateList,function(f){(t[f]||(t[f]={}))[l]=xI.get(l,f==="inRange"?"active":"inactive",i)})},this);function o(s,l,u){return s&&s[l]&&s[l].hasOwnProperty(u)}r.prototype.completeVisualOption.apply(this,arguments)},e.prototype._resetSelected=function(t,a){var n=this.option,i=this._pieceList,o=(a?n:t).selected||{};if(n.selected=o,A(i,function(l,u){var f=this.getSelectedMapKey(l);o.hasOwnProperty(f)||(o[f]=!0)},this),n.selectedMode==="single"){var s=!1;A(i,function(l,u){var f=this.getSelectedMapKey(l);o[f]&&(s?o[f]=!1:s=!0)},this)}},e.prototype.getItemSymbol=function(){return this.get("itemSymbol")},e.prototype.getSelectedMapKey=function(t){return this._mode==="categories"?t.value+"":t.index+""},e.prototype.getPieceList=function(){return this._pieceList},e.prototype._determineMode=function(){var t=this.option;return t.pieces&&t.pieces.length>0?"pieces":this.option.categories?"categories":"splitNumber"},e.prototype.setSelected=function(t){this.option.selected=et(t)},e.prototype.getValueState=function(t){var a=se.findPieceIndex(t,this._pieceList);return a!=null&&this.option.selected[this.getSelectedMapKey(this._pieceList[a])]?"inRange":"outOfRange"},e.prototype.findTargetDataIndices=function(t){var a=[],n=this._pieceList;return this.eachTargetSeries(function(i){var o=[],s=i.getData();s.each(this.getDataDimensionIndex(s),function(l,u){var f=se.findPieceIndex(l,n);f===t&&o.push(u)},this),a.push({seriesId:i.id,dataIndex:o})},this),a},e.prototype.getRepresentValue=function(t){var a;if(this.isCategory())a=t.value;else if(t.value!=null)a=t.value;else{var n=t.interval||[];a=n[0]===-Infinity&&n[1]===Infinity?0:(n[0]+n[1])/2}return a},e.prototype.getVisualMeta=function(t){if(this.isCategory())return;var a=[],n=["",""],i=this;function o(f,h){var v=i.getRepresentValue({interval:f});h||(h=i.getValueState(v));var c=t(v,h);f[0]===-Infinity?n[0]=c:f[1]===Infinity?n[1]=c:a.push({value:f[0],color:c},{value:f[1],color:c})}var s=this._pieceList.slice();if(!s.length)s.push({interval:[-Infinity,Infinity]});else{var l=s[0].interval[0];l!==-Infinity&&s.unshift({interval:[-Infinity,l]}),l=s[s.length-1].interval[1],l!==Infinity&&s.push({interval:[l,Infinity]})}var u=-Infinity;return A(s,function(f){var h=f.interval;h&&(h[0]>u&&o([u,h[0]],"outOfRange"),o(h.slice()),u=h[1])},this),{stops:a,outerColors:n}},e.type="visualMap.piecewise",e.defaultOption=Ua(Zh.defaultOption,{selected:null,minOpen:!1,maxOpen:!1,align:"auto",itemWidth:20,itemHeight:14,itemSymbol:"roundRect",pieces:null,categories:null,splitNumber:5,selectedMode:"multiple",itemGap:10,hoverLink:!0}),e}(Zh),bY={splitNumber:function(r){var e=this.option,t=Math.min(e.precision,20),a=this.getExtent(),n=e.splitNumber;n=Math.max(parseInt(n,10),1),e.splitNumber=n;for(var i=(a[1]-a[0])/n;+i.toFixed(t)!==i&&t<5;)t++;e.precision=t,i=+i.toFixed(t),e.minOpen&&r.push({interval:[-Infinity,a[0]],close:[0,0]});for(var o=0,s=a[0];o","\u2265"][a[0]]];t.text=t.text||this.formatValueText(t.value!=null?t.value:t.interval,!1,n)},this)}};function BI(r,e){var t=r.inverse;(r.orient==="vertical"?!t:t)&&e.reverse()}var wY=function(r){O(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.doRender=function(){var t=this.group;t.removeAll();var a=this.visualMapModel,n=a.get("textGap"),i=a.textStyleModel,o=i.getFont(),s=i.getTextColor(),l=this._getItemAlign(),u=a.itemSize,f=this._getViewData(),h=f.endsText,v=ee(a.get("showLabel",!0),!h);h&&this._renderEndsText(t,h[0],u,v,l),A(f.viewPieceList,function(c){var p=c.piece,d=new rt;d.onclick=Y(this._onItemClick,this,p),this._enableHoverLink(d,c.indexInModelPieceList);var g=a.getRepresentValue(p);if(this._createItemSymbol(d,g,[0,0,u[0],u[1]]),v){var y=this.visualMapModel.getValueState(g);d.add(new bt({style:{x:l==="right"?-n:u[0]+n,y:u[1]/2,text:p.text,verticalAlign:"middle",align:l,font:o,fill:s,opacity:y==="outOfRange"?.5:1}}))}t.add(d)},this),h&&this._renderEndsText(t,h[1],u,v,l),Fn(a.get("orient"),t,a.get("itemGap")),this.renderBackground(t),this.positionGroup(t)},e.prototype._enableHoverLink=function(t,a){var n=this;t.on("mouseover",function(){return i("highlight")}).on("mouseout",function(){return i("downplay")});var i=function(o){var s=n.visualMapModel;s.option.hoverLink&&n.api.dispatchAction({type:o,batch:$h(s.findTargetDataIndices(a),s)})}},e.prototype._getItemAlign=function(){var t=this.visualMapModel,a=t.option;if(a.orient==="vertical")return MI(t,this.api,t.itemSize);var n=a.align;return(!n||n==="auto")&&(n="left"),n},e.prototype._renderEndsText=function(t,a,n,i,o){if(!!a){var s=new rt,l=this.visualMapModel.textStyleModel;s.add(new bt({style:Nt(l,{x:i?o==="right"?n[0]:0:n[0]/2,y:n[1]/2,verticalAlign:"middle",align:i?o:"center",text:a})})),t.add(s)}},e.prototype._getViewData=function(){var t=this.visualMapModel,a=G(t.getPieceList(),function(s,l){return{piece:s,indexInModelPieceList:l}}),n=t.get("text"),i=t.get("orient"),o=t.get("inverse");return(i==="horizontal"?o:!o)?a.reverse():n&&(n=n.slice().reverse()),{viewPieceList:a,endsText:n}},e.prototype._createItemSymbol=function(t,a,n){t.add($t(this.getControllerVisual(a,"symbol"),n[0],n[1],n[2],n[3],this.getControllerVisual(a,"color")))},e.prototype._onItemClick=function(t){var a=this.visualMapModel,n=a.option,i=n.selectedMode;if(!!i){var o=et(n.selected),s=a.getSelectedMapKey(t);i==="single"||i===!0?(o[s]=!0,A(o,function(l,u){o[u]=u===s})):o[s]=!o[s],this.api.dispatchAction({type:"selectDataRange",from:this.uid,visualMapId:this.visualMapModel.id,selected:o})}},e.type="visualMap.piecewise",e}(AI);function VI(r){r.registerComponentModel(xY),r.registerComponentView(wY),OI(r)}function TY(r){ct(NI),ct(VI)}var CY={label:{enabled:!0},decal:{show:!1}},zI=Ct(),AY={};function DY(r,e){var t=r.getModel("aria");if(!t.get("enabled"))return;var a=et(CY);ot(a.label,r.getLocaleModel().get("aria"),!1),ot(t.option,a,!1),n(),i();function n(){var u=t.getModel("decal"),f=u.get("show");if(f){var h=$();r.eachSeries(function(v){if(!v.isColorBySeries()){var c=h.get(v.type);c||(c={},h.set(v.type,c)),zI(v).scope=c}}),r.eachRawSeries(function(v){if(r.isSeriesFiltered(v))return;if(K(v.enableAriaDecal)){v.enableAriaDecal();return}var c=v.getData();if(v.isColorBySeries()){var m=dp(v.ecModel,v.name,AY,r.getSeriesCount()),_=c.getVisual("decal");c.setVisual("decal",S(_,m))}else{var p=v.getRawData(),d={},g=zI(v).scope;c.each(function(b){var x=c.getRawIndex(b);d[x]=b});var y=p.count();p.each(function(b){var x=d[b],w=p.getName(b)||b+"",T=dp(v.ecModel,w,g,y),C=c.getItemVisual(x,"decal");c.setItemVisual(x,"decal",S(C,T))})}function S(b,x){var w=b?B(B({},x),b):x;return w.dirty=!0,w}})}}function i(){var u=r.getLocaleModel().get("aria"),f=t.getModel("label");if(f.option=j(f.option,u),!!f.get("enabled")){var h=e.getZr().dom;if(f.get("description")){h.setAttribute("aria-label",f.get("description"));return}var v=r.getSeriesCount(),c=f.get(["data","maxCount"])||10,p=f.get(["series","maxCount"])||10,d=Math.min(v,p),g;if(!(v<1)){var y=s();if(y){var m=f.get(["general","withTitle"]);g=o(m,{title:y})}else g=f.get(["general","withoutTitle"]);var _=[],S=v>1?f.get(["series","multiple","prefix"]):f.get(["series","single","prefix"]);g+=o(S,{seriesCount:v}),r.eachSeries(function(T,C){if(C1?f.get(["series","multiple",I]):f.get(["series","single",I]),D=o(D,{seriesId:T.seriesIndex,seriesName:T.get("name"),seriesType:l(T.subType)});var L=T.getData();if(L.count()>c){var P=f.get(["data","partialData"]);D+=o(P,{displayCnt:c})}else D+=f.get(["data","allData"]);for(var R=f.get(["data","separator","middle"]),E=f.get(["data","separator","end"]),N=[],k=0;k":"gt",">=":"gte","=":"eq","!=":"ne","<>":"ne"},LY=function(){function r(e){var t=this._condVal=U(e)?new RegExp(e):Om(e)?e:null;if(t==null){var a="";It(a)}}return r.prototype.evaluate=function(e){var t=typeof e;return U(t)?this._condVal.test(e):Tt(t)?this._condVal.test(e+""):!1},r}(),PY=function(){function r(){}return r.prototype.evaluate=function(){return this.value},r}(),RY=function(){function r(){}return r.prototype.evaluate=function(){for(var e=this.children,t=0;t2&&a.push(n),n=[L,P]}function f(L,P,R,E){Po(L,R)&&Po(P,E)||n.push(L,P,R,E,R,E)}function h(L,P,R,E,N,k){var V=Math.abs(P-L),F=Math.tan(V/4)*4/3,W=PT:M2&&a.push(n),a}function xm(r,e,t,a,n,i,o,s,l,u){if(Po(r,t)&&Po(e,a)&&Po(n,o)&&Po(i,s)){l.push(o,s);return}var f=2/u,h=f*f,v=o-r,c=s-e,p=Math.sqrt(v*v+c*c);v/=p,c/=p;var d=t-r,g=a-e,y=n-o,m=i-s,_=d*d+g*g,S=y*y+m*m;if(_=0&&T=0){l.push(o,s);return}var C=[],D=[];Ra(r,t,n,o,.5,C),Ra(e,a,i,s,.5,D),xm(C[0],D[0],C[1],D[1],C[2],D[2],C[3],D[3],l,u),xm(C[4],D[4],C[5],D[5],C[6],D[6],C[7],D[7],l,u)}function XY(r,e){var t=Sm(r),a=[];e=e||1;for(var n=0;n0)for(var u=0;uMath.abs(u),h=WI([l,u],f?0:1,e),v=(f?s:u)/h.length,c=0;cn,o=WI([a,n],i?0:1,e),s=i?"width":"height",l=i?"height":"width",u=i?"x":"y",f=i?"y":"x",h=r[s]/o.length,v=0;v1?null:new ut(d*l+r,d*u+e)}function qY(r,e,t){var a=new ut;ut.sub(a,t,e),a.normalize();var n=new ut;ut.sub(n,r,e);var i=n.dot(a);return i}function Ro(r,e){var t=r[r.length-1];t&&t[0]===e[0]&&t[1]===e[1]||r.push(e)}function KY(r,e,t){for(var a=r.length,n=[],i=0;io?(u.x=f.x=s+i/2,u.y=l,f.y=l+o):(u.y=f.y=l+o/2,u.x=s,f.x=s+i),KY(e,u,f)}function qh(r,e,t,a){if(t===1)a.push(e);else{var n=Math.floor(t/2),i=r(e);qh(r,i[0],n,a),qh(r,i[1],t-n,a)}return a}function jY(r,e){for(var t=[],a=0;a0)for(var b=a/t,x=-a/2;x<=a/2;x+=b){for(var w=Math.sin(x),T=Math.cos(x),C=0,_=0;_0;u/=2){var f=0,h=0;(r&u)>0&&(f=1),(e&u)>0&&(h=1),s+=u*u*(3*f^h),h===0&&(f===1&&(r=u-1-r,e=u-1-e),l=r,r=e,e=l)}return s}function Qh(r){var e=Infinity,t=Infinity,a=-Infinity,n=-Infinity,i=G(r,function(s){var l=s.getBoundingRect(),u=s.getComputedTransform(),f=l.x+l.width/2+(u?u[4]:0),h=l.y+l.height/2+(u?u[5]:0);return e=Math.min(f,e),t=Math.min(h,t),a=Math.max(f,a),n=Math.max(h,n),[f,h]}),o=G(i,function(s,l){return{cp:s,z:o7(s[0],s[1],e,t,a,n),path:r[l]}});return o.sort(function(s,l){return s.z-l.z}).map(function(s){return s.path})}function QI(r){return t7(r.path,r.count)}function wm(){return{fromIndividuals:[],toIndividuals:[],count:0}}function s7(r,e,t){var a=[];function n(b){for(var x=0;x=0;n--)if(!t[n].many.length){var l=t[s].many;if(l.length<=1)if(s)s=0;else return t;var i=l.length,u=Math.ceil(i/2);t[n].many=l.slice(u,i),t[s].many=l.slice(0,u),s++}return t}var u7={clone:function(r){for(var e=[],t=1-Math.pow(1-r.path.style.opacity,1/r.count),a=0;a0))return;var s=a.getModel("universalTransition").get("delay"),l=Object.assign({setToFinal:!0},o),u,f;JI(r)&&(u=r,f=e),JI(e)&&(u=e,f=r);function h(y,m,_,S,b){var x=y.many,w=y.one;if(x.length===1&&!b){var T=m?x[0]:w,C=m?w:x[0];if(Kh(T))h({many:[T],one:C},!0,_,S,!0);else{var D=s?j({delay:s(_,S)},l):l;bm(T,C,D),i(T,C,T,C,D)}}else for(var M=j({dividePath:u7[t],individualDelay:s&&function(N,k,V,F){return s(N+_,S)}},l),I=m?s7(x,w,M):l7(w,x,M),L=I.fromIndividuals,P=I.toIndividuals,R=L.length,E=0;Ee.length,c=u?tL(f,u):tL(v?e:r,[v?r:e]),p=0,d=0;deL))for(var n=a.getIndices(),i=h7(a),o=0;o0&&S.group.traverse(function(x){x instanceof dt&&!x.animators.length&&x.animateFrom({style:{opacity:0}},b)})})}function nL(r){var e=r.getModel("universalTransition").get("seriesKey");return e||r.id}function iL(r){return z(r)?r.sort().join(","):r}function un(r){if(r.hostModel)return r.hostModel.getModel("universalTransition").get("divideShape")}function p7(r,e){var t=$(),a=$(),n=$();return A(r.oldSeries,function(i,o){var s=r.oldDataGroupIds[o],l=r.oldData[o],u=nL(i),f=iL(u);a.set(f,{dataGroupId:s,data:l}),z(u)&&A(u,function(h){n.set(h,{key:f,dataGroupId:s,data:l})})}),A(e.updatedSeries,function(i){if(i.isUniversalTransitionEnabled()&&i.isAnimationEnabled()){var o=i.get("dataGroupId"),s=i.getData(),l=nL(i),u=iL(l),f=a.get(u);if(f)t.set(u,{oldSeries:[{dataGroupId:f.dataGroupId,divide:un(f.data),data:f.data}],newSeries:[{dataGroupId:o,divide:un(s),data:s}]});else if(z(l)){var h=[];A(l,function(p){var d=a.get(p);d.data&&h.push({dataGroupId:d.dataGroupId,divide:un(d.data),data:d.data})}),h.length&&t.set(u,{oldSeries:h,newSeries:[{dataGroupId:o,data:s,divide:un(s)}]})}else{var v=n.get(l);if(v){var c=t.get(v.key);c||(c={oldSeries:[{dataGroupId:v.dataGroupId,data:v.data,divide:un(v.data)}],newSeries:[]},t.set(v.key,c)),c.newSeries.push({dataGroupId:o,data:s,divide:un(s)})}}}}),t}function oL(r,e){for(var t=0;t=0&&n.push({dataGroupId:e.oldDataGroupIds[s],data:e.oldData[s],divide:un(e.oldData[s]),dim:o.dimension})}),A(Et(r.to),function(o){var s=oL(t.updatedSeries,o);if(s>=0){var l=t.updatedSeries[s].getData();i.push({dataGroupId:e.oldDataGroupIds[s],data:l,divide:un(l),dim:o.dimension})}}),n.length>0&&i.length>0&&aL(n,i,a)}function g7(r){r.registerUpdateLifecycle("series:beforeupdate",function(e,t,a){A(Et(a.seriesTransition),function(n){A(Et(n.to),function(i){for(var o=a.updatedSeries,s=0;s0)return $n(e);if(n==="number"&&isFinite(e))return t.long?Un(e):In(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function $n(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!!t){var n=parseFloat(t[1]),i=(t[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return n*Mn;case"weeks":case"week":case"w":return n*Sn;case"days":case"day":case"d":return n*oe;case"hours":case"hour":case"hrs":case"hr":case"h":return n*ge;case"minutes":case"minute":case"mins":case"min":case"m":return n*de;case"seconds":case"second":case"secs":case"sec":case"s":return n*he;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function In(e){var t=Math.abs(e);return t>=oe?Math.round(e/oe)+"d":t>=ge?Math.round(e/ge)+"h":t>=de?Math.round(e/de)+"m":t>=he?Math.round(e/he)+"s":e+"ms"}function Un(e){var t=Math.abs(e);return t>=oe?Le(e,t,oe,"day"):t>=ge?Le(e,t,ge,"hour"):t>=de?Le(e,t,de,"minute"):t>=he?Le(e,t,he,"second"):e+" ms"}function Le(e,t,n,i){var o=t>=n*1.5;return Math.round(e/n)+" "+i+(o?"s":"")}function jn(e){n.debug=n,n.default=n,n.coerce=u,n.disable=c,n.enable=o,n.enabled=h,n.humanize=Pn,n.destroy=d,Object.keys(e).forEach(f=>{n[f]=e[f]}),n.names=[],n.skips=[],n.formatters={};function t(f){let g=0;for(let y=0;y{if(V==="%%")return"%";E++;const q=n.formatters[le];if(typeof q=="function"){const ee=R[E];V=q.call(M,ee),R.splice(E,1),E--}return V}),n.formatArgs.call(M,R),(M.log||n.log).apply(M,R)}return v.namespace=f,v.useColors=n.useColors(),v.color=n.selectColor(f),v.extend=i,v.destroy=n.destroy,Object.defineProperty(v,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?n.enabled(f):y,set:R=>{y=R}}),typeof n.init=="function"&&n.init(v),v}function i(f,g){const y=n(this.namespace+(typeof g=="undefined"?":":g)+f);return y.log=this.log,y}function o(f){n.save(f),n.names=[],n.skips=[];let g;const y=(typeof f=="string"?f:"").split(/[\s,]+/),v=y.length;for(g=0;g"-"+g)].join(",");return n.enable(""),f}function h(f){if(f[f.length-1]==="*")return!0;let g,y;for(g=0,y=n.skips.length;g{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function n(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const d="color: "+this.color;u.splice(1,0,d,"color: inherit");let f=0,g=0;u[0].replace(/%[a-zA-Z%]/g,y=>{y!=="%%"&&(f++,y==="%c"&&(g=f))}),u.splice(g,0,d)}t.log=console.debug||console.log||(()=>{});function o(u){try{u?t.storage.setItem("debug",u):t.storage.removeItem("debug")}catch(d){}}function c(){let u;try{u=t.storage.getItem("debug")}catch(d){}return!u&&typeof nt!="undefined"&&"env"in nt&&(u=nt.env.DEBUG),u}function h(){try{return localStorage}catch(u){}}e.exports=Nn(t);const{formatters:p}=e.exports;p.j=function(u){try{return JSON.stringify(u)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}),Ms=N.formatArgs,Ps=N.save,$s=N.load,Is=N.useColors,Us=N.storage,js=N.destroy,Ns=N.colors,Ls=N.log;let jt,De="default",st="";const it=()=>{jt=N(st?`fetch-mock:${De}:${st}`:`fetch-mock:${De}`)},Ln=e=>N(`fetch-mock:${De}:${e}`);it();var ae={debug:(...e)=>{jt(...e)},setDebugNamespace:e=>{st=e,it()},setDebugPhase:e=>{De=e||"default",it()},getDebug:e=>Ln(e)};const{debug:Dn,setDebugPhase:Nt}=ae,U={};U.mock=function(...e){return Nt("setup"),e.length&&this.addRoute(e),this._mock()},U.addRoute=function(e){Dn("Adding route",e);const t=this.compileRoute(e),n=this.routes.filter(({identifier:i,method:o})=>(typeof i=="function"?i===t.identifier:String(i)===String(t.identifier))&&(!o||!t.method||o===t.method));if(this.getOption("overwriteRoutes",t)===!1||!n.length)return this._uncompiledRoutes.push(e),this.routes.push(t);if(this.getOption("overwriteRoutes",t)===!0)return n.forEach(i=>{const o=this.routes.indexOf(i);this._uncompiledRoutes.splice(o,1,e),this.routes.splice(o,1,t)}),this.routes;if(n.length)throw new Error("fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.");this._uncompiledRoutes.push(e),this.routes.push(t)},U._mock=function(){return this.isSandbox||(this.realFetch=this.realFetch||this.global.fetch,this.global.fetch=this.fetchHandler),Nt(),this},U.catch=function(e){return this.fallbackResponse&&console.warn("calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response"),this.fallbackResponse=e||"ok",this._mock()},U.spy=function(e){return this._mock(),e?this.mock(e,this.getNativeFetch()):this.catch(this.getNativeFetch())};const Be=(e,t,n)=>{U[e]=function(i,o,c){return this[t](i,o,Object.assign(c||{},n))}},ze=(e,t)=>{U[e]=function(n,i){return this[t]({},n,i)}};Be("sticky","mock",{sticky:!0}),Be("once","mock",{repeat:1}),ze("any","mock"),ze("anyOnce","once"),["get","post","put","delete","head","patch"].forEach(e=>{Be(e,"mock",{method:e}),Be(`${e}Once`,"once",{method:e}),ze(`${e}Any`,e),ze(`${e}AnyOnce`,`${e}Once`)});const Bn=e=>{typeof e=="function"&&(console.warn("Deprecated: Passing fetch-mock reset methods\ndirectly in as handlers for before/after test runner hooks.\nWrap in an arrow function instead e.g. `() => fetchMock.restore()`"),e())},zn=({sticky:e})=>t=>e?[]:t.filter(({sticky:n})=>n);U.resetBehavior=function(e={}){Bn(e);const t=zn(e);return this.routes=t(this.routes),this._uncompiledRoutes=t(this._uncompiledRoutes),this.realFetch&&!this.routes.length&&(this.global.fetch=this.realFetch,this.realFetch=void 0),this.fallbackResponse=void 0,this},U.resetHistory=function(){return this._calls=[],this._holdingPromises=[],this.routes.forEach(e=>e.reset&&e.reset()),this},U.restore=U.reset=function(e){return this.resetBehavior(e),this.resetHistory(),this};var qn=U;const{getDebug:Gn}=ae,Lt=["body","headers","throws","status","redirectUrl"];class kn{constructor(t){this.debug=Gn("ResponseBuilder()"),this.debug("Response builder created with options",t),Object.assign(this,t)}exec(){this.debug("building response"),this.normalizeResponseConfig(),this.constructFetchOpts(),this.constructResponseBody();const t=new this.fetchMock.config.Response(this.body,this.options),n=this.buildObservableResponse(t);return[t,n]}sendAsObject(){return Lt.some(t=>this.responseConfig[t])?!Object.keys(this.responseConfig).every(t=>Lt.includes(t)):!0}normalizeResponseConfig(){typeof this.responseConfig=="number"?(this.debug("building response using status",this.responseConfig),this.responseConfig={status:this.responseConfig}):(typeof this.responseConfig=="string"||this.sendAsObject())&&(this.debug("building text response from",this.responseConfig),this.responseConfig={body:this.responseConfig})}validateStatus(t){if(!t)return this.debug("No status provided. Defaulting to 200"),200;if(typeof t=="number"&&parseInt(t,10)!==t&&t>=200||t<600)return this.debug("Valid status provided",t),t;throw new TypeError(`fetch-mock: Invalid status ${t} passed on response object. +To respond with a JSON object that has status as a property assign the object to body +e.g. {"body": {"status: "registered"}}`)}constructFetchOpts(){this.options=this.responseConfig.options||{},this.options.url=this.responseConfig.redirectUrl||this.url,this.options.status=this.validateStatus(this.responseConfig.status),this.options.statusText=this.fetchMock.statusTextMap[String(this.options.status)],this.options.headers=new this.fetchMock.config.Headers(this.responseConfig.headers||{})}getOption(t){return this.fetchMock.getOption(t,this.route)}convertToJson(){this.getOption("sendAsJson")&&this.responseConfig.body!=null&&typeof this.body=="object"&&(this.debug("Stringifying JSON response body"),this.body=JSON.stringify(this.body),this.options.headers.has("Content-Type")||this.options.headers.set("Content-Type","application/json"))}setContentLength(){this.getOption("includeContentLength")&&typeof this.body=="string"&&!this.options.headers.has("Content-Length")&&(this.debug("Setting content-length header:",this.body.length.toString()),this.options.headers.set("Content-Length",this.body.length.toString()))}constructResponseBody(){if(this.body=this.responseConfig.body,this.convertToJson(),this.setContentLength(),this.Stream){this.debug("Creating response stream");const t=new this.Stream.Readable;this.body!=null&&t.push(this.body,"utf-8"),t.push(null),this.body=t}this.body=this.body}buildObservableResponse(t){const n=this.fetchMock;return t._fmResults={},this.debug("Wrapping Response in ES proxy for observability"),new Proxy(t,{get:(i,o)=>{if(this.responseConfig.redirectUrl){if(o==="url")return this.debug("Retrieving redirect url",this.responseConfig.redirectUrl),this.responseConfig.redirectUrl;if(o==="redirected")return this.debug("Retrieving redirected status",!0),!0}return typeof i[o]=="function"?(this.debug("Wrapping body promises in ES proxies for observability"),new Proxy(i[o],{apply:(c,h,p)=>{this.debug(`Calling res.${o}`);const u=c.apply(t,p);return u.then&&(n._holdingPromises.push(u.catch(()=>null)),i._fmResults[o]=u),u}})):i[o]}})}}var Hn=e=>new kn(e).exec();let X;const ot=new RegExp("^[a-z]+://","i"),Wn=new RegExp("^//","i"),Dt=e=>typeof e.raw=="function"?Object.entries(e.raw()):e[Symbol.iterator]?[...e]:Object.entries(e),Bt=e=>e.reduce((t,[n,i])=>Object.assign(t,{[n]:i}),{}),at=e=>{if(typeof e=="function"||e instanceof RegExp||/^(begin|end|glob|express|path)\:/.test(e))return e;if(ot.test(e))return new X(e).href;if(Wn.test(e))return new X(e,"http://dummy").href;{const t=new X(e,"http://dummy");return t.pathname+t.search}},Jn=async e=>{try{return"body"in e?e.body.toString():e.clone().text()}catch(t){}};var qe={setUrlImplementation:e=>{X=e},normalizeRequest:(e,t,n)=>{if(n.prototype.isPrototypeOf(e)){const i={method:e.method},o=Jn(e);typeof o!="undefined"&&(i.body=o);const c={url:at(e.url),options:Object.assign(i,t),request:e,signal:t&&t.signal||e.signal},h=Dt(e.headers);return h.length&&(c.options.headers=Bt(h)),c}else{if(typeof e=="string"||typeof e=="object"&&"href"in e)return{url:at(e),options:t,signal:t&&t.signal};throw typeof e=="object"?new TypeError("fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs"):new TypeError("fetch-mock: Invalid arguments passed to fetch")}},normalizeUrl:at,getPath:e=>(ot.test(e)?new X(e):new X(e,"http://dummy")).pathname,getQuery:e=>{const t=ot.test(e)?new X(e):new X(e,"http://dummy");return t.search?t.search.substr(1):""},headers:{normalize:e=>Bt(Dt(e)),toLowerCase:e=>Object.keys(e).reduce((t,n)=>(t[n.toLowerCase()]=e[n],t),{}),equal:(e,t)=>(e=Array.isArray(e)?e:[e],t=Array.isArray(t)?t:[t],e.length!==t.length?!1:e.every((n,i)=>n===t[i]))}};const{debug:_e,setDebugPhase:zt,getDebug:Ge}=ae,L={};class Kn extends Error{constructor(){super(...arguments);this.name="AbortError",this.message="The operation was aborted.",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}const Xn=e=>typeof navigator=="undefined"||!navigator.vendor||navigator.vendor!=="Apple Computer, Inc."?e:async t=>{const{method:n}=t;if(!["POST","PUT","PATCH"].includes(n))return e(t);const i=await t.clone().text(),{cache:o,credentials:c,headers:h,integrity:p,mode:u,redirect:d,referrer:f}=t,g={body:i,cache:o,credentials:c,headers:h,integrity:p,mode:u,redirect:d,referrer:f,method:n};return e(t.url,g)},Zn=async({response:e,responseIsFetch:t=!1},n,i,o)=>{const c=Ge("resolve()");for(c("Recursively resolving function and promise responses");;)if(typeof e=="function"){if(c(" Response is a function"),t)return o?(c(" -> Calling fetch with Request instance"),e(o)):(c(" -> Calling fetch with url and options"),e(n,i));c(" -> Calling response function"),e=e(n,i,o)}else if(typeof e.then=="function")c(" Response is a promise"),c(" -> Resolving promise"),e=await e;else return c(" Response is not a function or a promise"),c(" -> Exiting response resolution recursion"),e};L.needsAsyncBodyExtraction=function({request:e}){return e&&this.routes.some(({usesBody:t})=>t)},L.fetchHandler=function(e,t){zt("handle");const n=Ge("fetchHandler()");n("fetch called with:",e,t);const i=qe.normalizeRequest(e,t,this.config.Request);return n("Request normalised"),n(" url",i.url),n(" options",i.options),n(" request",i.request),n(" signal",i.signal),this.needsAsyncBodyExtraction(i)?(n("Need to wait for Body to be streamed before calling router: switching to async mode"),this._extractBodyThenHandle(i)):this._fetchHandler(i)},L._extractBodyThenHandle=async function(e){return e.options.body=await e.options.body,this._fetchHandler(e)},L._fetchHandler=function({url:e,options:t,request:n,signal:i}){const{route:o,callLog:c}=this.executeRouter(e,t,n);this.recordCall(c);let h;return this._holdingPromises.push(new this.config.Promise(p=>h=p)),new this.config.Promise((p,u)=>{if(i){_e("signal exists - enabling fetch abort");const d=()=>{_e("aborting fetch"),u(typeof DOMException!="undefined"?new DOMException("The operation was aborted.","AbortError"):new Kn),h()};i.aborted&&(_e("signal is already aborted - aborting the fetch"),d()),i.addEventListener("abort",d)}this.generateResponse({route:o,url:e,options:t,request:n,callLog:c}).then(p,u).then(h,h).then(()=>{zt()})})},L.fetchHandler.isMock=!0,L.executeRouter=function(e,t,n){const i=Ge("executeRouter()"),o={url:e,options:t,request:n,isUnmatched:!0};if(i("Attempting to match request to a route"),this.getOption("fallbackToNetwork")==="always")return i(" Configured with fallbackToNetwork=always - passing through to fetch"),{route:{response:this.getNativeFetch(),responseIsFetch:!0}};const c=this.router(e,t,n);if(c)return i(" Matching route found"),{route:c,callLog:{url:e,options:t,request:n,identifier:c.identifier}};if(this.getOption("warnOnFallback")&&console.warn(`Unmatched ${t&&t.method||"GET"} to ${e}`),this.fallbackResponse)return i(" No matching route found - using fallbackResponse"),{route:{response:this.fallbackResponse},callLog:o};if(!this.getOption("fallbackToNetwork"))throw new Error(`fetch-mock: No fallback response defined for ${t&&t.method||"GET"} to ${e}`);return i(" Configured to fallbackToNetwork - passing through to fetch"),{route:{response:this.getNativeFetch(),responseIsFetch:!0},callLog:o}},L.generateResponse=async function({route:e,url:t,options:n,request:i,callLog:o={}}){const c=Ge("generateResponse()"),h=await Zn(e,t,n,i);if(h.throws&&typeof h!="function")throw c("response.throws is defined - throwing an error"),h.throws;if(this.config.Response.prototype.isPrototypeOf(h))return c("response is already a Response instance - returning it"),o.response=h,h;const[p,u]=Hn({url:t,responseConfig:h,fetchMock:this,route:e});return o.response=p,u},L.router=function(e,t,n){const i=this.routes.find((o,c)=>(_e(`Trying to match route ${c}`),o.matcher(e,t,n)));if(i)return i},L.getNativeFetch=function(){const e=this.realFetch||this.isSandbox&&this.config.fetch;if(!e)throw new Error("fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock");return Xn(e)},L.recordCall=function(e){_e("Recording fetch call",e),e&&this._calls.push(e)};var Qn=L,Yn=function(e,t){if(typeof e!="string")throw new TypeError("Expected a string");for(var n=String(e),i="",o=t?!!t.extended:!1,c=t?!!t.globstar:!1,h=!1,p=t&&typeof t.flags=="string"?t.flags:"",u,d=0,f=n.length;d1&&(g==="/"||g===void 0)&&(v==="/"||v===void 0);R?(i+="((?:[^/]*(?:/|$))*)",d++):i+="([^/]*)"}break;default:i+=u}return(!p||!~p.indexOf("g"))&&(i="^"+i+"$"),new RegExp(i,p)},pe=Jt,Vn=ct,es=ss,ts=kt,rs=Wt,qt="/",Gt="./",ns=new RegExp(["(\\\\.)","(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?"].join("|"),"g");function ct(e,t){for(var n=[],i=0,o=0,c="",h=t&&t.delimiter||qt,p=t&&t.delimiters||Gt,u=!1,d;(d=ns.exec(e))!==null;){var f=d[0],g=d[1],y=d.index;if(c+=e.slice(o,y),o=y+f.length,g){c+=g[1],u=!0;continue}var v="",R=e[o],M=d[2],z=d[3],me=d[4],E=d[5];if(!u&&c.length){var Y=c.length-1;p.indexOf(c[Y])>-1&&(v=c[Y],c=c.slice(0,Y))}c&&(n.push(c),c="",u=!1);var V=v!==""&&R!==void 0&&R!==v,le=E==="+"||E==="*",q=E==="?"||E==="*",ee=v||h,Te=z||me;n.push({name:M||i++,prefix:v,delimiter:ee,optional:q,repeat:le,partial:V,pattern:Te?is(Te):"[^"+Z(ee)+"]+?"})}return(c||o-1;else{var v=y.repeat?"(?:"+y.pattern+")(?:"+Z(y.delimiter)+"(?:"+y.pattern+"))*":y.pattern;t&&t.push(y),y.optional?y.partial?d+=Z(y.prefix)+"("+v+")?":d+="(?:"+Z(y.prefix)+"("+v+"))?":d+=Z(y.prefix)+"("+v+")"}}return c?(i||(d+="(?:"+h+")?"),d+=u==="$"?"$":"(?="+u+")"):(i||(d+="(?:"+h+"(?="+u+"))?"),f||(d+="(?="+h+"|"+u+")")),new RegExp(d,Ht(n))}function Jt(e,t,n){return e instanceof RegExp?os(e,t):Array.isArray(e)?as(e,t,n):cs(e,t,n)}pe.parse=Vn,pe.compile=es,pe.tokensToFunction=ts,pe.tokensToRegExp=rs;function us(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var ls=function(e,t,n,i){t=t||"&",n=n||"=";var o={};if(typeof e!="string"||e.length===0)return o;var c=/\+/g;e=e.split(t);var h=1e3;i&&typeof i.maxKeys=="number"&&(h=i.maxKeys);var p=e.length;h>0&&p>h&&(p=h);for(var u=0;u=0?(g=d.substr(0,f),y=d.substr(f+1)):(g=d,y=""),v=decodeURIComponent(g),R=decodeURIComponent(y),us(o,v)?Array.isArray(o[v])?o[v].push(R):o[v]=[o[v],R]:o[v]=R}return o},Re=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},fs=function(e,t,n,i){return t=t||"&",n=n||"=",e===null&&(e=void 0),typeof e=="object"?Object.keys(e).map(function(o){var c=encodeURIComponent(Re(o))+n;return Array.isArray(e[o])?e[o].map(function(h){return c+encodeURIComponent(Re(h))}).join(t):c+encodeURIComponent(Re(e[o]))}).join(t):i?encodeURIComponent(Re(i))+n+encodeURIComponent(Re(e)):""},ce=Ne(function(e,t){t.decode=t.parse=ls,t.encode=t.stringify=fs}),Ds=ce.decode,Bs=ce.parse,zs=ce.encode,qs=ce.stringify,Kt=Ne(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(i){function o(c,h){return i.apply(this,arguments)}return o.toString=function(){return i.toString()},o}(function(i,o){return typeof i!="object"||i===null||typeof o!="object"||o===null?!1:Object.keys(o).every(function(c){if(!i.propertyIsEnumerable(c))return!1;var h=o[c],p=i[c];return!(typeof h=="object"&&h!==null?!n(p,h):p!==h)})});t.default=n,e.exports=t.default});On(Kt);var Xt=Ne(function(e,t){var n=200,i="__lodash_hash_undefined__",o=1,c=2,h=9007199254740991,p="[object Arguments]",u="[object Array]",d="[object AsyncFunction]",f="[object Boolean]",g="[object Date]",y="[object Error]",v="[object Function]",R="[object GeneratorFunction]",M="[object Map]",z="[object Number]",me="[object Null]",E="[object Object]",Y="[object Promise]",V="[object Proxy]",le="[object RegExp]",q="[object Set]",ee="[object String]",Te="[object Symbol]",sr="[object Undefined]",Ke="[object WeakMap]",ft="[object ArrayBuffer]",Fe="[object DataView]",ir="[object Float32Array]",or="[object Float64Array]",ar="[object Int8Array]",cr="[object Int16Array]",ur="[object Int32Array]",lr="[object Uint8Array]",fr="[object Uint8ClampedArray]",hr="[object Uint16Array]",dr="[object Uint32Array]",gr=/[\\^$.*+?()[\]{}|]/g,pr=/^\[object .+?Constructor\]$/,yr=/^(?:0|[1-9]\d*)$/,C={};C[ir]=C[or]=C[ar]=C[cr]=C[ur]=C[lr]=C[fr]=C[hr]=C[dr]=!0,C[p]=C[u]=C[ft]=C[f]=C[Fe]=C[g]=C[y]=C[v]=C[M]=C[z]=C[E]=C[le]=C[q]=C[ee]=C[Ke]=!1;var ht=typeof je=="object"&&je&&je.Object===Object&&je,mr=typeof self=="object"&&self&&self.Object===Object&&self,G=ht||mr||Function("return this")(),dt=t&&!t.nodeType&&t,gt=dt&&!0&&e&&!e.nodeType&&e,pt=gt&>.exports===dt,Xe=pt&&ht.process,yt=function(){try{return Xe&&Xe.binding&&Xe.binding("util")}catch(r){}}(),mt=yt&&yt.isTypedArray;function br(r,s){for(var a=-1,l=r==null?0:r.length,_=0,b=[];++a-1}function Kr(r,s){var a=this.__data__,l=Me(a,r);return l<0?(++this.size,a.push([r,s])):a[l][1]=s,this}k.prototype.clear=kr,k.prototype.delete=Hr,k.prototype.get=Wr,k.prototype.has=Jr,k.prototype.set=Kr;function ne(r){var s=-1,a=r==null?0:r.length;for(this.clear();++sT))return!1;var x=b.get(r);if(x&&b.get(s))return x==s;var P=-1,j=!0,O=a&c?new Se:void 0;for(b.set(r,s),b.set(s,r);++P-1&&r%1==0&&r-1&&r%1==0&&r<=h}function $t(r){var s=typeof r;return r!=null&&(s=="object"||s=="function")}function Ce(r){return r!=null&&typeof r=="object"}var It=mt?_r(mt):hn;function Tn(r){return xn(r)?cn(r):dn(r)}function Fn(){return[]}function En(){return!1}e.exports=An});const{debug:m}=ae,{headers:ke,getPath:ut,getQuery:hs,normalizeUrl:Zt}=qe,xe=e=>t=>(m("Actual url:",t),e(t)),Qt={begin:e=>xe(t=>t.indexOf(e)===0),end:e=>xe(t=>t.substr(-e.length)===e),glob:e=>{const t=Yn(e);return xe(n=>t.test(n))},express:e=>{const t=pe(e);return xe(n=>t.test(ut(n)))},path:e=>xe(t=>ut(t)===e)},ds=({headers:e})=>{if(m("Generating header matcher"),!e){m(" No header expectations defined - skipping");return}const t=ke.toLowerCase(e);return m(" Expected headers:",t),(n,{headers:i={}})=>{m("Attempting to match headers");const o=ke.toLowerCase(ke.normalize(i));return m(" Expected headers:",t),m(" Actual headers:",o),Object.keys(t).every(c=>ke.equal(o[c],t[c]))}},gs=({method:e})=>{if(m("Generating method matcher"),!e){m(" No method expectations defined - skipping");return}return m(" Expected method:",e),(t,{method:n})=>{m("Attempting to match method");const i=n?n.toLowerCase():"get";return m(" Expected method:",e),m(" Actual method:",i),e===i}},ps=({query:e})=>{if(m("Generating query parameters matcher"),!e){m(" No query parameters expectations defined - skipping");return}const t=ce.parse(ce.stringify(e));m(" Expected query parameters:",e);const n=Object.keys(t);return i=>{m("Attempting to match query parameters");const o=ce.parse(hs(i));return m(" Expected query parameters:",t),m(" Actual query parameters:",o),n.every(c=>Array.isArray(o[c])?Array.isArray(t[c])?Xt(o[c].sort(),t[c].sort()):!1:o[c]===t[c])}},ys=({params:e,url:t})=>{if(m("Generating path parameters matcher"),!e){m(" No path parameters expectations defined - skipping");return}if(!/express:/.test(t))throw new Error("fetch-mock: matching on params is only possible when using an express: matcher");m(" Expected path parameters:",e);const n=Object.keys(e),i=[],o=pe(t.replace(/^express:/,""),i);return c=>{m("Attempting to match path parameters");const h=o.exec(ut(c))||[];h.shift();const p=i.reduce((u,{name:d},f)=>h[f]?Object.assign(u,{[d]:h[f]}):u,{});return m(" Expected path parameters:",e),m(" Actual path parameters:",p),n.every(u=>p[u]===e[u])}},ms=(e,t)=>{const n=t.getOption("matchPartialBody",e),{body:i}=e;return m("Generating body matcher"),(o,{body:c,method:h="get"})=>{if(m("Attempting to match body"),h.toLowerCase()==="get")return m(" GET request - skip matching body"),!0;let p;try{m(" Parsing request body as JSON"),p=JSON.parse(c)}catch(u){m(" Failed to parse request body as JSON",u)}return m("Expected body:",i),m("Actual body:",p),n&&m("matchPartialBody is true - checking for partial match only"),p&&(n?Kt(p,i):Xt(p,i))}},Yt=(e,t,n)=>{m(" Matching using full url",t);const i=Zt(t);return m(" Normalised url to:",t),e.identifier===t&&(m(" Updating route identifier to match normalized url:",t),e.identifier=i),o=>(m("Expected url:",i),m("Actual url:",o),n&&i.indexOf("?")?(m("Ignoring query string when matching url"),o.indexOf(i)===0):Zt(o)===i)},bs=({functionMatcher:e})=>(m("Detected user defined function matcher",e),(...t)=>(m("Calling function matcher with arguments",t),e(...t))),vs=e=>{m("Generating url matcher");const{url:t,query:n}=e;if(t==="*")return m(" Using universal * rule to match any url"),()=>!0;if(t instanceof RegExp)return m(" Using regular expression to match url:",t),i=>t.test(i);if(t.href)return m(" Using URL object to match url",t),Yt(e,t.href,n);for(const i in Qt)if(t.indexOf(i+":")===0){m(` Using ${i}: pattern to match url`,t);const o=t.replace(new RegExp(`^${i}:`),"");return Qt[i](o)}return Yt(e,t,n)};var ws=[{name:"query",matcher:ps},{name:"method",matcher:gs},{name:"headers",matcher:ds},{name:"params",matcher:ys},{name:"body",matcher:ms,usesBody:!0},{name:"functionMatcher",matcher:bs},{name:"url",matcher:vs}];const{debug:Vt,setDebugNamespace:er,getDebug:He}=ae,tr=e=>e instanceof RegExp||typeof e=="string"||typeof e=="object"&&"href"in e,Cs=e=>typeof e=="function";class ue{constructor(t,n){this.fetchMock=n,He("compileRoute()")("Compiling route"),this.init(t),this.sanitize(),this.validate(),this.generateMatcher(),this.limit(),this.delayResponse()}validate(){if(!("response"in this))throw new Error("fetch-mock: Each route must define a response");if(!ue.registeredMatchers.some(({name:t})=>t in this))throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'")}init(t){const[n,i,o={}]=t,c={};tr(n)||Cs(n)?c.matcher=n:Object.assign(c,n),typeof i!="undefined"&&(c.response=i),Object.assign(c,o),Object.assign(this,c)}sanitize(){const t=He("sanitize()");t("Sanitizing route properties"),this.method&&(t(`Converting method ${this.method} to lower case`),this.method=this.method.toLowerCase()),tr(this.matcher)&&(t("Mock uses a url matcher",this.matcher),this.url=this.matcher,delete this.matcher),this.functionMatcher=this.matcher||this.functionMatcher,t("Setting route.identifier..."),t(` route.name is ${this.name}`),t(` route.url is ${this.url}`),t(` route.functionMatcher is ${this.functionMatcher}`),this.identifier=this.name||this.url||this.functionMatcher,t(` -> route.identifier set to ${this.identifier}`)}generateMatcher(){er("generateMatcher()"),Vt("Compiling matcher for route");const t=ue.registeredMatchers.map(({name:n,matcher:i,usesBody:o})=>this[n]&&{matcher:i(this,this.fetchMock),usesBody:o}).filter(n=>Boolean(n));this.usesBody=t.some(({usesBody:n})=>n),Vt("Compiled matcher for route"),er(),this.matcher=(n,i={},o)=>t.every(({matcher:c})=>c(n,i,o))}limit(){const t=He("limit()");if(t("Limiting number of requests to handle by route"),!this.repeat){t(" No `repeat` value set on route. Will match any number of requests");return}t(` Route set to repeat ${this.repeat} times`);const n=this.matcher;let i=this.repeat;this.matcher=(o,c)=>{if(i&&n(o,c))return i--,!0},this.reset=()=>i=this.repeat}delayResponse(){const t=He("delayResponse()");if(t("Applying response delay settings"),this.delay){t(` Wrapping response in delay of ${this.delay} miliseconds`);const n=this.response;this.response=()=>(t(`Delaying response by ${this.delay} miliseconds`),new Promise(i=>setTimeout(()=>i(n),this.delay)))}else t(" No delay set on route. Will respond 'immediately' (but asynchronously)")}static addMatcher(t){ue.registeredMatchers.push(t)}}ue.registeredMatchers=[],ws.forEach(ue.addMatcher);var lt=ue;const{setDebugPhase:We,setDebugNamespace:Je,debug:w}=ae,{normalizeUrl:rr}=qe,B={},_s=e=>typeof e=="string"&&/^[\da-zA-Z\-]+$/.test(e),Rs=function(e,t={},n){return{matcher:e}=new lt([Object.assign({matcher:e,response:"ok"},t)],this),n.filter(({url:i,options:o})=>e(rr(i),o))},Q=e=>function(...t){We("inspect");const n=e.call(this,...t);return We(),n},xs=e=>{if(!e)return;const{url:t,options:n,request:i,identifier:o,isUnmatched:c,response:h}=e,p=[t,n];return p.request=i,p.identifier=o,p.isUnmatched=c,p.response=h,p};B.filterCalls=function(e,t){w("Filtering fetch calls");let n=this._calls,i="*";return[!0,"matched"].includes(e)?(w(`Filter provided is ${e}. Returning matched calls only`),n=n.filter(({isUnmatched:o})=>!o)):[!1,"unmatched"].includes(e)?(w(`Filter provided is ${e}. Returning unmatched calls only`),n=n.filter(({isUnmatched:o})=>o)):typeof e=="undefined"?(w("Filter provided is undefined. Returning all calls"),n=n):_s(e)?(w("Filter provided, looks like the name of a named route. Returning only calls handled by that route"),n=n.filter(({identifier:o})=>o===e)):(i=e==="*"?"*":rr(e),this.routes.some(({identifier:o})=>o===i)&&(w(`Filter provided, ${e}, identifies a route. Returning only calls handled by that route`),n=n.filter(o=>o.identifier===i))),(t||i!=="*")&&n.length&&(typeof t=="string"&&(t={method:t}),w("Compiling filter and options to route in order to filter all calls",e),n=Rs.call(this,i,t,n)),w(`Retrieved ${n.length} calls`),n.map(xs)},B.calls=Q(function(e,t){return w("retrieving matching calls"),this.filterCalls(e,t)}),B.lastCall=Q(function(e,t){return w("retrieving last matching call"),[...this.filterCalls(e,t)].pop()}),B.lastUrl=Q(function(e,t){return w("retrieving url of last matching call"),(this.lastCall(e,t)||[])[0]}),B.lastOptions=Q(function(e,t){return w("retrieving options of last matching call"),(this.lastCall(e,t)||[])[1]}),B.lastResponse=Q(function(e,t){w("retrieving respose of last matching call"),console.warn(`When doing all the following: +- using node-fetch +- responding with a real network response (using spy() or fallbackToNetwork) +- using \`fetchMock.LastResponse()\` +- awaiting the body content +... the response will hang unless your source code also awaits the response body. +This is an unavoidable consequence of the nodejs implementation of streams. +`);const n=(this.lastCall(e,t)||[]).response;try{return n.clone()}catch(i){return Object.entries(n._fmResults).forEach(([o,c])=>{n[o]=()=>c}),n}}),B.called=Q(function(e,t){return w("checking if matching call was made"),Boolean(this.filterCalls(e,t).length)}),B.flush=Q(async function(e){Je("flush"),w(`flushing all fetch calls. ${e?"":"Not "}waiting for response bodies to complete download`);const t=this._holdingPromises;this._holdingPromises=[],w(`${t.length} fetch calls to be awaited`),await Promise.all(t),w("All fetch calls have completed"),e&&this._holdingPromises.length&&(w("Awaiting all fetch bodies to download"),await this.flush(e),w("All fetch bodies have completed downloading")),Je()}),B.done=Q(function(e){We("inspect"),Je("done"),w("Checking to see if expected calls have been made");let t;e&&typeof e!="boolean"?(w("Checking to see if expected calls have been made for single route:",e),t=[{identifier:e}]):(w("Checking to see if expected calls have been made for all routes"),t=this.routes);const n=t.map(({identifier:i})=>{if(!this.called(i))return w("No calls made for route:",i),console.warn(`Warning: ${i} not called`),!1;const o=(this.routes.find(h=>h.identifier===i)||{}).repeat;if(!o)return w("Route has been called at least once, and no expectation of more set:",i),!0;const c=this.filterCalls(i).length;return w(`Route called ${c} times:`,i),o>c?(w(`Route called ${c} times, but expected ${o}:`,i),console.warn(`Warning: ${i} only called ${c} times, but ${o} expected`),!1):!0}).every(i=>i);return Je(),We(),n});var As=B;const{debug:nr}=ae,S=Object.assign({},Qn,qn,As);S.addMatcher=function(e){lt.addMatcher(e)},S.config={fallbackToNetwork:!1,includeContentLength:!0,sendAsJson:!0,warnOnFallback:!0,overwriteRoutes:void 0},S.createInstance=function(){nr("Creating fetch-mock instance");const e=Object.create(S);return e._uncompiledRoutes=(this._uncompiledRoutes||[]).slice(),e.routes=e._uncompiledRoutes.map(t=>this.compileRoute(t)),e.fallbackResponse=this.fallbackResponse||void 0,e.config=Object.assign({},this.config||S.config),e._calls=[],e._holdingPromises=[],e.bindMethods(),e},S.compileRoute=function(e){return new lt(e,this)},S.bindMethods=function(){this.fetchHandler=S.fetchHandler.bind(this),this.reset=this.restore=S.reset.bind(this),this.resetHistory=S.resetHistory.bind(this),this.resetBehavior=S.resetBehavior.bind(this)},S.sandbox=function(){nr("Creating sandboxed fetch-mock instance");const t=Object.assign((n,i)=>t.fetchHandler(n,i),S,this.createInstance(),{Headers:this.config.Headers,Request:this.config.Request,Response:this.config.Response});return t.bindMethods(),t.isSandbox=!0,t.default=t,t},S.getOption=function(e,t={}){return e in t?t[e]:this.config[e]};var Ae=S;const Ts={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var Fs=Ts;const ye=typeof window!="undefined"?window:self,{setUrlImplementation:Es}=qe;Es(ye.URL),Ae.global=ye,Ae.statusTextMap=Fs,Ae.config=Object.assign(Ae.config,{Promise:ye.Promise,Request:ye.Request,Response:ye.Response,Headers:ye.Headers});var Os=Ae.createInstance();export default Os; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/file-saver.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/file-saver.js new file mode 100644 index 0000000000000000000000000000000000000000..fd63966be12cdb09441941094fc861809e9fc448 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/file-saver.js @@ -0,0 +1 @@ +import{c as E,a as s}from"./common/_commonjsHelpers-b3efd043.js";var b=E(function(h,L){(function(p,i){i()})(s,function(){function p(e,t){return typeof t=="undefined"?t={autoBom:!1}:typeof t!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\uFEFF",e],{type:e.type}):e}function i(e,t,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="blob",o.onload=function(){u(o.response,t,r)},o.onerror=function(){console.error("could not download file")},o.send()}function m(e){var t=new XMLHttpRequest;t.open("HEAD",e,!1);try{t.send()}catch(r){}return 200<=t.status&&299>=t.status}function l(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(r){var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(t)}}var a=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof s=="object"&&s.global===s?s:void 0,v=a.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),u=a.saveAs||(typeof window!="object"||window!==a?function(){}:"download"in HTMLAnchorElement.prototype&&!v?function(e,t,r){var o=a.URL||a.webkitURL,n=document.createElement("a");t=t||e.name||"download",n.download=t,n.rel="noopener",typeof e=="string"?(n.href=e,n.origin===location.origin?l(n):m(n.href)?i(e,t,r):l(n,n.target="_blank")):(n.href=o.createObjectURL(e),setTimeout(function(){o.revokeObjectURL(n.href)},4e4),setTimeout(function(){l(n)},0))}:"msSaveOrOpenBlob"in navigator?function(e,t,r){if(t=t||e.name||"download",typeof e!="string")navigator.msSaveOrOpenBlob(p(e,r),t);else if(m(e))i(e,t,r);else{var o=document.createElement("a");o.href=e,o.target="_blank",setTimeout(function(){l(o)})}}:function(e,t,r,o){if(o=o||open("","_blank"),o&&(o.document.title=o.document.body.innerText="downloading..."),typeof e=="string")return i(e,t,r);var n=e.type==="application/octet-stream",j=/constructor/i.test(a.HTMLElement)||a.safari,w=/CriOS\/[\d]+/.test(navigator.userAgent);if((w||n&&j||v)&&typeof FileReader!="undefined"){var d=new FileReader;d.onloadend=function(){var c=d.result;c=w?c:c.replace(/^data:[^;]*;/,"data:attachment/file;"),o?o.location.href=c:location=c,o=null},d.readAsDataURL(e)}else{var y=a.URL||a.webkitURL,f=y.createObjectURL(e);o?o.location=f:location.href=f,o=null,setTimeout(function(){y.revokeObjectURL(f)},4e4)}});a.saveAs=u.saveAs=u,h.exports=u})});export default b; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-browser-languagedetector.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-browser-languagedetector.js new file mode 100644 index 0000000000000000000000000000000000000000..72db78eb9a2f74b269a2394d6fa3f66f4b53bc55 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-browser-languagedetector.js @@ -0,0 +1 @@ +function k(a,t){if(!(a instanceof t))throw new TypeError("Cannot call a class as a function")}function f(a,t){for(var e=0;e0){var l=n.maxAge-0;if(isNaN(l))throw new Error("maxAge should be a Number");i+="; Max-Age="+Math.floor(l)}if(n.domain){if(!g.test(n.domain))throw new TypeError("option domain is invalid");i+="; Domain="+n.domain}if(n.path){if(!g.test(n.path))throw new TypeError("option path is invalid");i+="; Path="+n.path}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite){var m=typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite;switch(m){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return i},d={create:function(t,e,o,n){var r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};o&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+o*60*1e3)),n&&(r.domain=n),document.cookie=b(t,encodeURIComponent(e),r)},read:function(t){for(var e=t+"=",o=document.cookie.split(";"),n=0;n0){var l=n[r].substring(0,i);l===t.lookupQuerystring&&(e=n[r].substring(i+1))}}return e}},u=null,h=function(){if(u!==null)return u;try{u=window!=="undefined"&&window.localStorage!==null;var t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch(e){u=!1}return u},I={name:"localStorage",lookup:function(t){var e;if(t.lookupLocalStorage&&h()){var o=window.localStorage.getItem(t.lookupLocalStorage);o&&(e=o)}return e},cacheUserLanguage:function(t,e){e.lookupLocalStorage&&h()&&window.localStorage.setItem(e.lookupLocalStorage,t)}},s=null,p=function(){if(s!==null)return s;try{s=window!=="undefined"&&window.sessionStorage!==null;var t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch(e){s=!1}return s},D={name:"sessionStorage",lookup:function(t){var e;if(t.lookupSessionStorage&&p()){var o=window.sessionStorage.getItem(t.lookupSessionStorage);o&&(e=o)}return e},cacheUserLanguage:function(t,e){e.lookupSessionStorage&&p()&&window.sessionStorage.setItem(e.lookupSessionStorage,t)}},U={name:"navigator",lookup:function(t){var e=[];if(typeof navigator!="undefined"){if(navigator.languages)for(var o=0;o0?e:void 0}},T={name:"htmlTag",lookup:function(t){var e,o=t.htmlTag||(typeof document!="undefined"?document.documentElement:null);return o&&typeof o.getAttribute=="function"&&(e=o.getAttribute("lang")),e}},A={name:"path",lookup:function(t){var e;if(typeof window!="undefined"){var o=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(o instanceof Array)if(typeof t.lookupFromPathIndex=="number"){if(typeof o[t.lookupFromPathIndex]!="string")return;e=o[t.lookupFromPathIndex].replace("/","")}else e=o[0].replace("/","")}return e}},E={name:"subdomain",lookup:function(t){var e;if(typeof window!="undefined"){var o=window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);o instanceof Array&&(typeof t.lookupFromSubdomainIndex=="number"?e=o[t.lookupFromSubdomainIndex].replace("http://","").replace("https://","").replace(".",""):e=o[0].replace("http://","").replace("https://","").replace(".",""))}return e}};function F(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}}var v=function(){function a(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};k(this,a),this.type="languageDetector",this.detectors={},this.init(t,e)}return S(a,[{key:"init",value:function(e){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=x(o,this.options||{},F()),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(L),this.addDetector(C),this.addDetector(I),this.addDetector(D),this.addDetector(U),this.addDetector(T),this.addDetector(A),this.addDetector(E)}},{key:"addDetector",value:function(e){this.detectors[e.name]=e}},{key:"detect",value:function(e){var o=this;e||(e=this.options.order);var n=[];return e.forEach(function(r){if(o.detectors[r]){var i=o.detectors[r].lookup(o.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}},{key:"cacheUserLanguage",value:function(e,o){var n=this;o||(o=this.options.caches),!!o&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||o.forEach(function(r){n.detectors[r]&&n.detectors[r].cacheUserLanguage(e,n.options)}))}}]),a}();v.type="languageDetector";export default v; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-fetch-backend.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-fetch-backend.js new file mode 100644 index 0000000000000000000000000000000000000000..1a0863accfba45d6cd651e214e668970b1126148 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next-fetch-backend.js @@ -0,0 +1 @@ +function O(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}function b(n,t){for(var e=0;e1?e-1:0),o=1;o1&&arguments[1]!==void 0?arguments[1]:!1;return O(this,e),o=t.call(this,r),s(_(o),"retry",null),o.retry=u,o}return e}(g(Error)),j=function(){function n(t,e){O(this,n),s(this,"type","backend"),this.init(t,e)}return x(n,[{key:"init",value:function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.services=e,this.options=w({},M,{},this.options,{},r)}},{key:"getLoadPath",value:function(e,r){return B(this.options.loadPath,e,r)}},{key:"read",value:function(e,r,o){var u=this.getLoadPath(e,r),a=this.services.interpolator.interpolate(u,{lng:e,ns:r});this.loadUrl(a,o)}},{key:"readMulti",value:function(e,r,o){var u=this.getLoadPath(e,r),a=this.options.multiSeparator,f=this.services.interpolator.interpolate(u,{lng:e.join(a),ns:r.join(a)});this.loadUrl(f,o)}},{key:"loadUrl",value:function(e,r){var o=this.options,u=o.fetch,a=o.requestOptions,f=o.parse;u(e,a).then(function(i){var c=i.ok,h=i.status;if(!c){var v=h>=500&&h<600;throw new d("failed loading ".concat(e),v)}return i.text()},function(){throw new d("failed loading ".concat(e))}).then(function(i){try{return r(null,f(i,e))}catch(c){throw new d("failed parsing ".concat(e," to json"),!1)}}).catch(function(i){i instanceof d&&r(i.message,i.retry)})}},{key:"create",value:function(e,r,o,u){var a=this,f=s({},o,u||"");T(e).forEach(function(i){var c=a.options,h=c.addPath,v=c.requestOptions,S=c.fetch,k=c.stringify,E=a.services.interpolator.interpolate(h,{lng:i,ns:r});try{S(E,w({method:"POST",body:k(f)},v))}catch(R){console.error(R)}})}}]),n}();s(j,"type","backend");export default j; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next.js new file mode 100644 index 0000000000000000000000000000000000000000..4a03f0aa7c4fe713005949fcb131294e8da39b2e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/i18next.js @@ -0,0 +1 @@ +import{c as Se,g as Le}from"./common/_commonjsHelpers-b3efd043.js";function R(a){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?R=function(r){return typeof r}:R=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},R(a)}function we(a,n,r){return n in a?Object.defineProperty(a,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):a[n]=r,a}function b(a){for(var n=1;n1&&arguments[1]!==void 0?arguments[1]:{};w(this,a),this.init(n,r)}return O(a,[{key:"init",value:function(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=e.prefix||"i18next:",this.logger=r||Re,this.options=e,this.debug=e.debug}},{key:"setDebug",value:function(r){this.debug=r}},{key:"log",value:function(){for(var r=arguments.length,e=new Array(r),t=0;t1?e-1:0),i=1;i-1?s.replace(/###/g,"."):s}function t(){return!a||typeof a=="string"}for(var i=typeof n!="string"?[].concat(n):n.split(".");i.length>1;){if(t())return{};var o=e(i.shift());!a[o]&&r&&(a[o]=new r),Object.prototype.hasOwnProperty.call(a,o)?a=a[o]:a={}}return t()?{}:{obj:a,k:e(i.shift())}}function le(a,n,r){var e=X(a,n,Object),t=e.obj,i=e.k;t[i]=r}function Ce(a,n,r,e){var t=X(a,n,Object),i=t.obj,o=t.k;i[o]=i[o]||[],e&&(i[o]=i[o].concat(r)),e||i[o].push(r)}function z(a,n){var r=X(a,n),e=r.obj,t=r.k;if(!!e)return e[t]}function ce(a,n,r){var e=z(a,r);return e!==void 0?e:z(n,r)}function ge(a,n,r){for(var e in n)e!=="__proto__"&&e!=="constructor"&&(e in a?typeof a[e]=="string"||a[e]instanceof String||typeof n[e]=="string"||n[e]instanceof String?r&&(a[e]=n[e]):ge(a[e],n[e],r):a[e]=n[e]);return a}function T(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var Ee={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function je(a){return typeof a=="string"?a.replace(/[&<>"'\/]/g,function(n){return Ee[n]}):a}var J=typeof window!="undefined"&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1;function he(a,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!!a){if(a[n])return a[n];for(var e=n.split(r),t=a,i=0;ii+o;)o++,s=e.slice(i,i+o).join(r),u=t[s];if(u===void 0)return;if(typeof u=="string")return u;if(s&&typeof u[s]=="string")return u[s];var f=e.slice(i+o).join(r);return f?he(u,f,r):void 0}t=t[e[i]]}return t}}var Fe=function(a){B(n,a);function n(r){var e,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};return w(this,n),e=V(this,_(n).call(this)),J&&N.call(C(e)),e.data=r||{},e.options=t,e.options.keySeparator===void 0&&(e.options.keySeparator="."),e.options.ignoreJSONStructure===void 0&&(e.options.ignoreJSONStructure=!0),e}return O(n,[{key:"addNamespaces",value:function(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}},{key:"removeNamespaces",value:function(e){var t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}},{key:"getResource",value:function(e,t,i){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,u=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure,f=[e,t];i&&typeof i!="string"&&(f=f.concat(i)),i&&typeof i=="string"&&(f=f.concat(s?i.split(s):i)),e.indexOf(".")>-1&&(f=e.split("."));var l=z(this.data,f);return l||!u||typeof i!="string"?l:he(this.data&&this.data[e]&&this.data[e][t],i,s)}},{key:"addResource",value:function(e,t,i,o){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1},u=this.options.keySeparator;u===void 0&&(u=".");var f=[e,t];i&&(f=f.concat(u?i.split(u):i)),e.indexOf(".")>-1&&(f=e.split("."),o=t,t=f[1]),this.addNamespaces(t),le(this.data,f,o),s.silent||this.emit("added",e,t,i,o)}},{key:"addResources",value:function(e,t,i){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(var s in i)(typeof i[s]=="string"||Object.prototype.toString.apply(i[s])==="[object Array]")&&this.addResource(e,t,s,i[s],{silent:!0});o.silent||this.emit("added",e,t,i)}},{key:"addResourceBundle",value:function(e,t,i,o,s){var u=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1},f=[e,t];e.indexOf(".")>-1&&(f=e.split("."),o=i,i=t,t=f[1]),this.addNamespaces(t);var l=z(this.data,f)||{};o?ge(l,i,s):l=b({},l,i),le(this.data,f,l),u.silent||this.emit("added",e,t,i)}},{key:"removeResourceBundle",value:function(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}},{key:"hasResourceBundle",value:function(e,t){return this.getResource(e,t)!==void 0}},{key:"getResourceBundle",value:function(e,t){return t||(t=this.options.defaultNS),this.options.compatibilityAPI==="v1"?b({},{},this.getResource(e,t)):this.getResource(e,t)}},{key:"getDataByLanguage",value:function(e){return this.data[e]}},{key:"toJSON",value:function(){return this.data}}]),n}(N),pe={processors:{},addPostProcessor:function(n){this.processors[n.name]=n},handle:function(n,r,e,t,i){var o=this;return n.forEach(function(s){o.processors[s]&&(r=o.processors[s].process(r,e,t,i))}),r}},de={},ve=function(a){B(n,a);function n(r){var e,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return w(this,n),e=V(this,_(n).call(this)),J&&N.call(C(e)),Pe(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],r,C(e)),e.options=t,e.options.keySeparator===void 0&&(e.options.keySeparator="."),e.logger=k.create("translator"),e}return O(n,[{key:"changeLanguage",value:function(e){e&&(this.language=e)}},{key:"exists",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(e==null)return!1;var i=this.resolve(e,t);return i&&i.res!==void 0}},{key:"extractFromKey",value:function(e,t){var i=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;i===void 0&&(i=":");var o=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator,s=t.ns||this.options.defaultNS;if(i&&e.indexOf(i)>-1){var u=e.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:e,namespaces:s};var f=e.split(i);(i!==o||i===o&&this.options.ns.indexOf(f[0])>-1)&&(s=f.shift()),e=f.join(o)}return typeof s=="string"&&(s=[s]),{key:e,namespaces:s}}},{key:"translate",value:function(e,t,i){var o=this;if(R(t)!=="object"&&this.options.overloadTranslationOptionHandler&&(t=this.options.overloadTranslationOptionHandler(arguments)),t||(t={}),e==null)return"";Array.isArray(e)||(e=[String(e)]);var s=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator,u=this.extractFromKey(e[e.length-1],t),f=u.key,l=u.namespaces,c=l[l.length-1],d=t.lng||this.language,m=t.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d&&d.toLowerCase()==="cimode"){if(m){var p=t.nsSeparator||this.options.nsSeparator;return c+p+f}return f}var h=this.resolve(e,t),g=h&&h.res,v=h&&h.usedKey||f,y=h&&h.exactUsedKey||f,x=Object.prototype.toString.apply(g),L=["[object Number]","[object Function]","[object RegExp]"],S=t.joinArrays!==void 0?t.joinArrays:this.options.joinArrays,E=!this.i18nFormat||this.i18nFormat.handleAsObject,I=typeof g!="string"&&typeof g!="boolean"&&typeof g!="number";if(E&&g&&I&&L.indexOf(x)<0&&!(typeof S=="string"&&x==="[object Array]")){if(!t.returnObjects&&!this.options.returnObjects)return this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,g,b({},t,{ns:l})):"key '".concat(f," (").concat(this.language,")' returned an object instead of string.");if(s){var ee=x==="[object Array]",K=ee?[]:{},ye=ee?y:v;for(var j in g)if(Object.prototype.hasOwnProperty.call(g,j)){var te="".concat(ye).concat(s).concat(j);K[j]=this.translate(te,b({},t,{joinArrays:!1,ns:l})),K[j]===te&&(K[j]=g[j])}g=K}}else if(E&&typeof S=="string"&&x==="[object Array]")g=g.join(S),g&&(g=this.extendTranslation(g,e,t,i));else{var $=!1,A=!1,ne=t.count!==void 0&&typeof t.count!="string",re=n.hasDefaultValue(t),be=ne?this.pluralResolver.getSuffix(d,t.count):"",U=t["defaultValue".concat(be)]||t.defaultValue;!this.isValidLookup(g)&&re&&($=!0,g=U),this.isValidLookup(g)||(A=!0,g=f);var xe=t.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey,ie=xe&&A?void 0:g,P=re&&U!==g&&this.options.updateMissing;if(A||$||P){if(this.logger.log(P?"updateKey":"missingKey",d,c,f,P?U:g),s){var ae=this.resolve(f,b({},t,{keySeparator:!1}));ae&&ae.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var D=[],M=this.languageUtils.getFallbackCodes(this.options.fallbackLng,t.lng||this.language);if(this.options.saveMissingTo==="fallback"&&M&&M[0])for(var Y=0;Y1&&arguments[1]!==void 0?arguments[1]:{},o,s,u,f,l;return typeof e=="string"&&(e=[e]),e.forEach(function(c){if(!t.isValidLookup(o)){var d=t.extractFromKey(c,i),m=d.key;s=m;var p=d.namespaces;t.options.fallbackNS&&(p=p.concat(t.options.fallbackNS));var h=i.count!==void 0&&typeof i.count!="string",g=i.context!==void 0&&(typeof i.context=="string"||typeof i.context=="number")&&i.context!=="",v=i.lngs?i.lngs:t.languageUtils.toResolveHierarchy(i.lng||t.language,i.fallbackLng);p.forEach(function(y){t.isValidLookup(o)||(l=y,!de["".concat(v[0],"-").concat(y)]&&t.utils&&t.utils.hasLoadedNamespace&&!t.utils.hasLoadedNamespace(l)&&(de["".concat(v[0],"-").concat(y)]=!0,t.logger.warn('key "'.concat(s,'" for languages "').concat(v.join(", "),`" won't get resolved as namespace "`).concat(l,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),v.forEach(function(x){if(!t.isValidLookup(o)){f=x;var L=m,S=[L];if(t.i18nFormat&&t.i18nFormat.addLookupKeys)t.i18nFormat.addLookupKeys(S,m,x,y,i);else{var E;h&&(E=t.pluralResolver.getSuffix(x,i.count)),h&&g&&S.push(L+E),g&&S.push(L+="".concat(t.options.contextSeparator).concat(i.context)),h&&S.push(L+=E)}for(var I;I=S.pop();)t.isValidLookup(o)||(u=I,o=t.getResource(x,y,I,i))}}))})}}),{res:o,usedKey:s,exactUsedKey:u,usedLng:f,usedNS:l}}},{key:"isValidLookup",value:function(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}},{key:"getResource",value:function(e,t,i){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,i,o):this.resourceStore.getResource(e,t,i,o)}}],[{key:"hasDefaultValue",value:function(e){var t="defaultValue";for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&t===i.substring(0,t.length)&&e[i]!==void 0)return!0;return!1}}]),n}(N);function Z(a){return a.charAt(0).toUpperCase()+a.slice(1)}var _e=function(){function a(n){w(this,a),this.options=n,this.whitelist=this.options.supportedLngs||!1,this.supportedLngs=this.options.supportedLngs||!1,this.logger=k.create("languageUtils")}return O(a,[{key:"getScriptPartFromCode",value:function(r){if(!r||r.indexOf("-")<0)return null;var e=r.split("-");return e.length===2||(e.pop(),e[e.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(e.join("-"))}},{key:"getLanguagePartFromCode",value:function(r){if(!r||r.indexOf("-")<0)return r;var e=r.split("-");return this.formatLanguageCode(e[0])}},{key:"formatLanguageCode",value:function(r){if(typeof r=="string"&&r.indexOf("-")>-1){var e=["hans","hant","latn","cyrl","cans","mong","arab"],t=r.split("-");return this.options.lowerCaseLng?t=t.map(function(i){return i.toLowerCase()}):t.length===2?(t[0]=t[0].toLowerCase(),t[1]=t[1].toUpperCase(),e.indexOf(t[1].toLowerCase())>-1&&(t[1]=Z(t[1].toLowerCase()))):t.length===3&&(t[0]=t[0].toLowerCase(),t[1].length===2&&(t[1]=t[1].toUpperCase()),t[0]!=="sgn"&&t[2].length===2&&(t[2]=t[2].toUpperCase()),e.indexOf(t[1].toLowerCase())>-1&&(t[1]=Z(t[1].toLowerCase())),e.indexOf(t[2].toLowerCase())>-1&&(t[2]=Z(t[2].toLowerCase()))),t.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?r.toLowerCase():r}},{key:"isWhitelisted",value:function(r){return this.logger.deprecate("languageUtils.isWhitelisted",`function "isWhitelisted" will be renamed to "isSupportedCode" in the next major - please make sure to rename it's usage asap.`),this.isSupportedCode(r)}},{key:"isSupportedCode",value:function(r){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(r=this.getLanguagePartFromCode(r)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(r)>-1}},{key:"getBestMatchFromCodes",value:function(r){var e=this;if(!r)return null;var t;return r.forEach(function(i){if(!t){var o=e.formatLanguageCode(i);(!e.options.supportedLngs||e.isSupportedCode(o))&&(t=o)}}),!t&&this.options.supportedLngs&&r.forEach(function(i){if(!t){var o=e.getLanguagePartFromCode(i);if(e.isSupportedCode(o))return t=o;t=e.options.supportedLngs.find(function(s){if(s.indexOf(o)===0)return s})}}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}},{key:"getFallbackCodes",value:function(r,e){if(!r)return[];if(typeof r=="function"&&(r=r(e)),typeof r=="string"&&(r=[r]),Object.prototype.toString.apply(r)==="[object Array]")return r;if(!e)return r.default||[];var t=r[e];return t||(t=r[this.getScriptPartFromCode(e)]),t||(t=r[this.formatLanguageCode(e)]),t||(t=r[this.getLanguagePartFromCode(e)]),t||(t=r.default),t||[]}},{key:"toResolveHierarchy",value:function(r,e){var t=this,i=this.getFallbackCodes(e||this.options.fallbackLng||[],r),o=[],s=function(f){!f||(t.isSupportedCode(f)?o.push(f):t.logger.warn("rejecting language code not found in supportedLngs: ".concat(f)))};return typeof r=="string"&&r.indexOf("-")>-1?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(r)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(r)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(r))):typeof r=="string"&&s(this.formatLanguageCode(r)),i.forEach(function(u){o.indexOf(u)<0&&s(t.formatLanguageCode(u))}),o}}]),a}(),Te=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Ie={1:function(n){return Number(n>1)},2:function(n){return Number(n!=1)},3:function(n){return 0},4:function(n){return Number(n%10==1&&n%100!=11?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2)},5:function(n){return Number(n==0?0:n==1?1:n==2?2:n%100>=3&&n%100<=10?3:n%100>=11?4:5)},6:function(n){return Number(n==1?0:n>=2&&n<=4?1:2)},7:function(n){return Number(n==1?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2)},8:function(n){return Number(n==1?0:n==2?1:n!=8&&n!=11?2:3)},9:function(n){return Number(n>=2)},10:function(n){return Number(n==1?0:n==2?1:n<7?2:n<11?3:4)},11:function(n){return Number(n==1||n==11?0:n==2||n==12?1:n>2&&n<20?2:3)},12:function(n){return Number(n%10!=1||n%100==11)},13:function(n){return Number(n!==0)},14:function(n){return Number(n==1?0:n==2?1:n==3?2:3)},15:function(n){return Number(n%10==1&&n%100!=11?0:n%10>=2&&(n%100<10||n%100>=20)?1:2)},16:function(n){return Number(n%10==1&&n%100!=11?0:n!==0?1:2)},17:function(n){return Number(n==1||n%10==1&&n%100!=11?0:1)},18:function(n){return Number(n==0?0:n==1?1:2)},19:function(n){return Number(n==1?0:n==0||n%100>1&&n%100<11?1:n%100>10&&n%100<20?2:3)},20:function(n){return Number(n==1?0:n==0||n%100>0&&n%100<20?1:2)},21:function(n){return Number(n%100==1?1:n%100==2?2:n%100==3||n%100==4?3:0)},22:function(n){return Number(n==1?0:n==2?1:(n<0||n>10)&&n%10==0?2:3)}};function Ae(){var a={};return Te.forEach(function(n){n.lngs.forEach(function(r){a[r]={numbers:n.nr,plurals:Ie[n.fc]}})}),a}var Ue=function(){function a(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};w(this,a),this.languageUtils=n,this.options=r,this.logger=k.create("pluralResolver"),this.rules=Ae()}return O(a,[{key:"addRule",value:function(r,e){this.rules[r]=e}},{key:"getRule",value:function(r){return this.rules[r]||this.rules[this.languageUtils.getLanguagePartFromCode(r)]}},{key:"needsPlural",value:function(r){var e=this.getRule(r);return e&&e.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(r,e){return this.getSuffixes(r).map(function(t){return e+t})}},{key:"getSuffixes",value:function(r){var e=this,t=this.getRule(r);return t?t.numbers.map(function(i){return e.getSuffix(r,i)}):[]}},{key:"getSuffix",value:function(r,e){var t=this,i=this.getRule(r);if(i){var o=i.noAbs?i.plurals(e):i.plurals(Math.abs(e)),s=i.numbers[o];this.options.simplifyPluralSuffix&&i.numbers.length===2&&i.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));var u=function(){return t.options.prepend&&s.toString()?t.options.prepend+s.toString():s.toString()};return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?"_plural_".concat(s.toString()):u():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&i.numbers.length===2&&i.numbers[0]===1?u():this.options.prepend&&o.toString()?this.options.prepend+o.toString():o.toString()}return this.logger.warn("no plural rule found for: ".concat(r)),""}}]),a}(),De=function(){function a(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};w(this,a),this.logger=k.create("interpolator"),this.options=n,this.format=n.interpolation&&n.interpolation.format||function(r){return r},this.init(n)}return O(a,[{key:"init",value:function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r.interpolation||(r.interpolation={escapeValue:!0});var e=r.interpolation;this.escape=e.escape!==void 0?e.escape:je,this.escapeValue=e.escapeValue!==void 0?e.escapeValue:!0,this.useRawValueToEscape=e.useRawValueToEscape!==void 0?e.useRawValueToEscape:!1,this.prefix=e.prefix?T(e.prefix):e.prefixEscaped||"{{",this.suffix=e.suffix?T(e.suffix):e.suffixEscaped||"}}",this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||",",this.unescapePrefix=e.unescapeSuffix?"":e.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":e.unescapeSuffix||"",this.nestingPrefix=e.nestingPrefix?T(e.nestingPrefix):e.nestingPrefixEscaped||T("$t("),this.nestingSuffix=e.nestingSuffix?T(e.nestingSuffix):e.nestingSuffixEscaped||T(")"),this.nestingOptionsSeparator=e.nestingOptionsSeparator?e.nestingOptionsSeparator:e.nestingOptionsSeparator||",",this.maxReplaces=e.maxReplaces?e.maxReplaces:1e3,this.alwaysFormat=e.alwaysFormat!==void 0?e.alwaysFormat:!1,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var r="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(r,"g");var e="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(e,"g");var t="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(t,"g")}},{key:"interpolate",value:function(r,e,t,i){var o=this,s,u,f,l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function c(g){return g.replace(/\$/g,"$$$$")}var d=function(v){if(v.indexOf(o.formatSeparator)<0){var y=ce(e,l,v);return o.alwaysFormat?o.format(y,void 0,t,b({},i,e,{interpolationkey:v})):y}var x=v.split(o.formatSeparator),L=x.shift().trim(),S=x.join(o.formatSeparator).trim();return o.format(ce(e,l,L),S,t,b({},i,e,{interpolationkey:L}))};this.resetRegExp();var m=i&&i.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i&&i.interpolation&&i.interpolation.skipOnVariables||this.options.interpolation.skipOnVariables,h=[{regex:this.regexpUnescape,safeValue:function(v){return c(v)}},{regex:this.regexp,safeValue:function(v){return o.escapeValue?c(o.escape(v)):c(v)}}];return h.forEach(function(g){for(f=0;s=g.regex.exec(r);){if(u=d(s[1].trim()),u===void 0)if(typeof m=="function"){var v=m(r,s,i);u=typeof v=="string"?v:""}else if(p){u=s[0];continue}else o.logger.warn("missed to pass in variable ".concat(s[1]," for interpolating ").concat(r)),u="";else typeof u!="string"&&!o.useRawValueToEscape&&(u=fe(u));var y=g.safeValue(u);if(r=r.replace(s[0],y),p?(g.regex.lastIndex+=y.length,g.regex.lastIndex-=s[0].length):g.regex.lastIndex=0,f++,f>=o.maxReplaces)break}}),r}},{key:"nest",value:function(r,e){var t=this,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o,s,u=b({},i);u.applyPostProcessor=!1,delete u.defaultValue;function f(m,p){var h=this.nestingOptionsSeparator;if(m.indexOf(h)<0)return m;var g=m.split(new RegExp("".concat(h,"[ ]*{"))),v="{".concat(g[1]);m=g[0],v=this.interpolate(v,u),v=v.replace(/'/g,'"');try{u=JSON.parse(v),p&&(u=b({},p,u))}catch(y){return this.logger.warn("failed parsing options string in nesting for key ".concat(m),y),"".concat(m).concat(h).concat(v)}return delete u.defaultValue,m}for(;o=this.nestingRegexp.exec(r);){var l=[],c=!1;if(o[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(o[1])){var d=o[1].split(this.formatSeparator).map(function(m){return m.trim()});o[1]=d.shift(),l=d,c=!0}if(s=e(f.call(this,o[1].trim(),u),u),s&&o[0]===r&&typeof s!="string")return s;typeof s!="string"&&(s=fe(s)),s||(this.logger.warn("missed to resolve ".concat(o[1]," for nesting ").concat(r)),s=""),c&&(s=l.reduce(function(m,p){return t.format(m,p,i.lng,b({},i,{interpolationkey:o[1].trim()}))},s.trim())),r=r.replace(o[0],s),this.regexp.lastIndex=0}return r}}]),a}();function Ve(a,n){for(var r=a.indexOf(n);r!==-1;)a.splice(r,1),r=a.indexOf(n)}var He=function(a){B(n,a);function n(r,e,t){var i,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return w(this,n),i=V(this,_(n).call(this)),J&&N.call(C(i)),i.backend=r,i.store=e,i.services=t,i.languageUtils=t.languageUtils,i.options=o,i.logger=k.create("backendConnector"),i.state={},i.queue=[],i.backend&&i.backend.init&&i.backend.init(t,o.backend,o),i}return O(n,[{key:"queueLoad",value:function(e,t,i,o){var s=this,u=[],f=[],l=[],c=[];return e.forEach(function(d){var m=!0;t.forEach(function(p){var h="".concat(d,"|").concat(p);!i.reload&&s.store.hasResourceBundle(d,p)?s.state[h]=2:s.state[h]<0||(s.state[h]===1?f.indexOf(h)<0&&f.push(h):(s.state[h]=1,m=!1,f.indexOf(h)<0&&f.push(h),u.indexOf(h)<0&&u.push(h),c.indexOf(p)<0&&c.push(p)))}),m||l.push(d)}),(u.length||f.length)&&this.queue.push({pending:f,loaded:{},errors:[],callback:o}),{toLoad:u,pending:f,toLoadLanguages:l,toLoadNamespaces:c}}},{key:"loaded",value:function(e,t,i){var o=e.split("|"),s=o[0],u=o[1];t&&this.emit("failedLoading",s,u,t),i&&this.store.addResourceBundle(s,u,i),this.state[e]=t?-1:2;var f={};this.queue.forEach(function(l){Ce(l.loaded,[s],u),Ve(l.pending,e),t&&l.errors.push(t),l.pending.length===0&&!l.done&&(Object.keys(l.loaded).forEach(function(c){f[c]||(f[c]=[]),l.loaded[c].length&&l.loaded[c].forEach(function(d){f[c].indexOf(d)<0&&f[c].push(d)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",f),this.queue=this.queue.filter(function(l){return!l.done})}},{key:"read",value:function(e,t,i){var o=this,s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,u=arguments.length>4&&arguments[4]!==void 0?arguments[4]:350,f=arguments.length>5?arguments[5]:void 0;return e.length?this.backend[i](e,t,function(l,c){if(l&&c&&s<5){setTimeout(function(){o.read.call(o,e,t,i,s+1,u*2,f)},u);return}f(l,c)}):f(null,{})}},{key:"prepareLoading",value:function(e,t){var i=this,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof e=="string"&&(e=this.languageUtils.toResolveHierarchy(e)),typeof t=="string"&&(t=[t]);var u=this.queueLoad(e,t,o,s);if(!u.toLoad.length)return u.pending.length||s(),null;u.toLoad.forEach(function(f){i.loadOne(f)})}},{key:"load",value:function(e,t,i){this.prepareLoading(e,t,{},i)}},{key:"reload",value:function(e,t,i){this.prepareLoading(e,t,{reload:!0},i)}},{key:"loadOne",value:function(e){var t=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",o=e.split("|"),s=o[0],u=o[1];this.read(s,u,"read",void 0,void 0,function(f,l){f&&t.logger.warn("".concat(i,"loading namespace ").concat(u," for language ").concat(s," failed"),f),!f&&l&&t.logger.log("".concat(i,"loaded namespace ").concat(u," for language ").concat(s),l),t.loaded(e,f,l)})}},{key:"saveMissing",value:function(e,t,i,o,s){var u=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t)){this.logger.warn('did not save key "'.concat(i,'" as the namespace "').concat(t,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}i==null||i===""||(this.backend&&this.backend.create&&this.backend.create(e,t,i,o,null,b({},u,{isUpdate:s})),!(!e||!e[0])&&this.store.addResource(e[0],t,i,o))}}]),n}(N);function Ke(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,whitelist:!1,nonExplicitWhitelist:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(n){var r={};if(R(n[1])==="object"&&(r=n[1]),typeof n[1]=="string"&&(r.defaultValue=n[1]),typeof n[2]=="string"&&(r.tDescription=n[2]),R(n[2])==="object"||R(n[3])==="object"){var e=n[3]||n[2];Object.keys(e).forEach(function(t){r[t]=e[t]})}return r},interpolation:{escapeValue:!0,format:function(n,r,e,t){return n},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!1}}}function me(a){return typeof a.ns=="string"&&(a.ns=[a.ns]),typeof a.fallbackLng=="string"&&(a.fallbackLng=[a.fallbackLng]),typeof a.fallbackNS=="string"&&(a.fallbackNS=[a.fallbackNS]),a.whitelist&&(a.whitelist&&a.whitelist.indexOf("cimode")<0&&(a.whitelist=a.whitelist.concat(["cimode"])),a.supportedLngs=a.whitelist),a.nonExplicitWhitelist&&(a.nonExplicitSupportedLngs=a.nonExplicitWhitelist),a.supportedLngs&&a.supportedLngs.indexOf("cimode")<0&&(a.supportedLngs=a.supportedLngs.concat(["cimode"])),a}function W(){}var Me=function(a){B(n,a);function n(){var r,e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;if(w(this,n),r=V(this,_(n).call(this)),J&&N.call(C(r)),r.options=me(e),r.services={},r.logger=k,r.modules={external:[]},t&&!r.isInitialized&&!e.isClone){if(!r.options.initImmediate)return r.init(e,t),V(r,C(r));setTimeout(function(){r.init(e,t)},0)}return r}return O(n,[{key:"init",value:function(){var e=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;typeof t=="function"&&(i=t,t={}),t.whitelist&&!t.supportedLngs&&this.logger.deprecate("whitelist",'option "whitelist" will be renamed to "supportedLngs" in the next major - please make sure to rename this option asap.'),t.nonExplicitWhitelist&&!t.nonExplicitSupportedLngs&&this.logger.deprecate("whitelist",'options "nonExplicitWhitelist" will be renamed to "nonExplicitSupportedLngs" in the next major - please make sure to rename this option asap.'),this.options=b({},Ke(),this.options,me(t)),this.format=this.options.interpolation.format,i||(i=W);function o(p){return p?typeof p=="function"?new p:p:null}if(!this.options.isClone){this.modules.logger?k.init(o(this.modules.logger),this.options):k.init(null,this.options);var s=new _e(this.options);this.store=new Fe(this.options.resources,this.options);var u=this.services;u.logger=k,u.resourceStore=this.store,u.languageUtils=s,u.pluralResolver=new Ue(s,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),u.interpolator=new De(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new He(o(this.modules.backend),u.resourceStore,u,this.options),u.backendConnector.on("*",function(p){for(var h=arguments.length,g=new Array(h>1?h-1:0),v=1;v1?h-1:0),v=1;v0&&f[0]!=="dev"&&(this.options.lng=f[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined");var l=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];l.forEach(function(p){e[p]=function(){var h;return(h=e.store)[p].apply(h,arguments)}});var c=["addResource","addResources","addResourceBundle","removeResourceBundle"];c.forEach(function(p){e[p]=function(){var h;return(h=e.store)[p].apply(h,arguments),e}});var d=H(),m=function(){var h=function(v,y){e.isInitialized&&!e.initializedStoreOnce&&e.logger.warn("init: i18next is already initialized. You should call init just once!"),e.isInitialized=!0,e.options.isClone||e.logger.log("initialized",e.options),e.emit("initialized",e.options),d.resolve(y),i(v,y)};if(e.languages&&e.options.compatibilityAPI!=="v1"&&!e.isInitialized)return h(null,e.t.bind(e));e.changeLanguage(e.options.lng,h)};return this.options.resources||!this.options.initImmediate?m():setTimeout(m,0),d}},{key:"loadResources",value:function(e){var t=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:W,o=i,s=typeof e=="string"?e:this.language;if(typeof e=="function"&&(o=e),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode")return o();var u=[],f=function(d){if(!!d){var m=t.services.languageUtils.toResolveHierarchy(d);m.forEach(function(p){u.indexOf(p)<0&&u.push(p)})}};if(s)f(s);else{var l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.forEach(function(c){return f(c)})}this.options.preload&&this.options.preload.forEach(function(c){return f(c)}),this.services.backendConnector.load(u,this.options.ns,o)}else o(null)}},{key:"reloadResources",value:function(e,t,i){var o=H();return e||(e=this.languages),t||(t=this.options.ns),i||(i=W),this.services.backendConnector.reload(e,t,function(s){o.resolve(),i(s)}),o}},{key:"use",value:function(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&pe.addPostProcessor(e),e.type==="3rdParty"&&this.modules.external.push(e),this}},{key:"changeLanguage",value:function(e,t){var i=this;this.isLanguageChangingTo=e;var o=H();this.emit("languageChanging",e);var s=function(l,c){c?(i.language=c,i.languages=i.services.languageUtils.toResolveHierarchy(c),i.translator.changeLanguage(c),i.isLanguageChangingTo=void 0,i.emit("languageChanged",c),i.logger.log("languageChanged",c)):i.isLanguageChangingTo=void 0,o.resolve(function(){return i.t.apply(i,arguments)}),t&&t(l,function(){return i.t.apply(i,arguments)})},u=function(l){!e&&!l&&i.services.languageDetector&&(l=[]);var c=typeof l=="string"?l:i.services.languageUtils.getBestMatchFromCodes(l);c&&(i.language||(i.language=c,i.languages=i.services.languageUtils.toResolveHierarchy(c)),i.translator.language||i.translator.changeLanguage(c),i.services.languageDetector&&i.services.languageDetector.cacheUserLanguage(c)),i.loadResources(c,function(d){s(d,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?u(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect(u):u(e),o}},{key:"getFixedT",value:function(e,t,i){var o=this,s=function u(f,l){var c;if(R(l)!=="object"){for(var d=arguments.length,m=new Array(d>2?d-2:0),p=2;p1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var o=this.languages[0],s=this.options?this.options.fallbackLng:!1,u=this.languages[this.languages.length-1];if(o.toLowerCase()==="cimode")return!0;var f=function(d,m){var p=t.services.backendConnector.state["".concat(d,"|").concat(m)];return p===-1||p===2};if(i.precheck){var l=i.precheck(this,f);if(l!==void 0)return l}return!!(this.hasResourceBundle(o,e)||!this.services.backendConnector.backend||f(o,e)&&(!s||f(u,e)))}},{key:"loadNamespaces",value:function(e,t){var i=this,o=H();return this.options.ns?(typeof e=="string"&&(e=[e]),e.forEach(function(s){i.options.ns.indexOf(s)<0&&i.options.ns.push(s)}),this.loadResources(function(s){o.resolve(),t&&t(s)}),o):(t&&t(),Promise.resolve())}},{key:"loadLanguages",value:function(e,t){var i=H();typeof e=="string"&&(e=[e]);var o=this.options.preload||[],s=e.filter(function(u){return o.indexOf(u)<0});return s.length?(this.options.preload=o.concat(s),this.loadResources(function(u){i.resolve(),t&&t(u)}),i):(t&&t(),Promise.resolve())}},{key:"dir",value:function(e){if(e||(e=this.languages&&this.languages.length>0?this.languages[0]:this.language),!e)return"rtl";var t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam"];return t.indexOf(this.services.languageUtils.getLanguagePartFromCode(e))>=0?"rtl":"ltr"}},{key:"createInstance",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return new n(e,t)}},{key:"cloneInstance",value:function(){var e=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:W,o=b({},this.options,t,{isClone:!0}),s=new n(o),u=["store","services","language"];return u.forEach(function(f){s[f]=e[f]}),s.services=b({},this.services),s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s.translator=new ve(s.services,s.options),s.translator.on("*",function(f){for(var l=arguments.length,c=new Array(l>1?l-1:0),d=1;d + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/master/LICENSE +*/(function(_){xe.exports=_()})(function(){return function _(U,k,h){function f(b,v){if(!k[b]){if(!U[b]){var m=typeof be=="function"&&be;if(!v&&m)return m(b,!0);if(t)return t(b,!0);var g=new Error("Cannot find module '"+b+"'");throw g.code="MODULE_NOT_FOUND",g}var i=k[b]={exports:{}};U[b][0].call(i.exports,function(d){var c=U[b][1][d];return f(c||d)},i,i.exports,_,U,k,h)}return k[b].exports}for(var t=typeof be=="function"&&be,u=0;u>2,i=(3&b)<<4|v>>4,d=1>6:64,c=2>4,v=(15&g)<<4|(i=t.indexOf(u.charAt(c++)))>>2,m=(3&i)<<6|(d=t.indexOf(u.charAt(c++))),l[n++]=b,i!==64&&(l[n++]=v),d!==64&&(l[n++]=m);return l}},{"./support":30,"./utils":32}],2:[function(_,U,k){var h=_("./external"),f=_("./stream/DataWorker"),t=_("./stream/Crc32Probe"),u=_("./stream/DataLengthProbe");function b(v,m,g,i,d){this.compressedSize=v,this.uncompressedSize=m,this.crc32=g,this.compression=i,this.compressedContent=d}b.prototype={getContentWorker:function(){var v=new f(h.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new u("data_length")),m=this;return v.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),v},getCompressedWorker:function(){return new f(h.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},b.createWorkerFrom=function(v,m,g){return v.pipe(new t).pipe(new u("uncompressedSize")).pipe(m.compressWorker(g)).pipe(new u("compressedSize")).withStreamInfo("compression",m)},U.exports=b},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(_,U,k){var h=_("./stream/GenericWorker");k.STORE={magic:"\0\0",compressWorker:function(f){return new h("STORE compression")},uncompressWorker:function(){return new h("STORE decompression")}},k.DEFLATE=_("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(_,U,k){var h=_("./utils"),f=function(){for(var t,u=[],b=0;b<256;b++){t=b;for(var v=0;v<8;v++)t=1&t?3988292384^t>>>1:t>>>1;u[b]=t}return u}();U.exports=function(t,u){return t!==void 0&&t.length?h.getTypeOf(t)!=="string"?function(b,v,m,g){var i=f,d=g+m;b^=-1;for(var c=g;c>>8^i[255&(b^v[c])];return-1^b}(0|u,t,t.length,0):function(b,v,m,g){var i=f,d=g+m;b^=-1;for(var c=g;c>>8^i[255&(b^v.charCodeAt(c))];return-1^b}(0|u,t,t.length,0):0}},{"./utils":32}],5:[function(_,U,k){k.base64=!1,k.binary=!1,k.dir=!1,k.createFolders=!0,k.date=null,k.compression=null,k.compressionOptions=null,k.comment=null,k.unixPermissions=null,k.dosPermissions=null},{}],6:[function(_,U,k){var h=null;h=typeof Promise!="undefined"?Promise:_("lie"),U.exports={Promise:h}},{lie:37}],7:[function(_,U,k){var h=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",f=_("pako"),t=_("./utils"),u=_("./stream/GenericWorker"),b=h?"uint8array":"array";function v(m,g){u.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=g,this.meta={}}k.magic="\b\0",t.inherits(v,u),v.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(t.transformTo(b,m.data),!1)},v.prototype.flush=function(){u.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},v.prototype.cleanUp=function(){u.prototype.cleanUp.call(this),this._pako=null},v.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(g){m.push({data:g,meta:m.meta})}},k.compressWorker=function(m){return new v("Deflate",m)},k.uncompressWorker=function(){return new v("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(_,U,k){function h(i,d){var c,n="";for(c=0;c>>=8;return n}function f(i,d,c,n,s,l){var y,O,x=i.file,N=i.compression,R=l!==b.utf8encode,M=t.transformTo("string",l(x.name)),A=t.transformTo("string",b.utf8encode(x.name)),W=x.comment,V=t.transformTo("string",l(W)),p=t.transformTo("string",b.utf8encode(W)),I=A.length!==x.name.length,r=p.length!==W.length,T="",J="",P="",Q=x.dir,L=x.date,q={crc32:0,compressedSize:0,uncompressedSize:0};d&&!c||(q.crc32=i.crc32,q.compressedSize=i.compressedSize,q.uncompressedSize=i.uncompressedSize);var C=0;d&&(C|=8),R||!I&&!r||(C|=2048);var z=0,X=0;Q&&(z|=16),s==="UNIX"?(X=798,z|=function(H,ne){var oe=H;return H||(oe=ne?16893:33204),(65535&oe)<<16}(x.unixPermissions,Q)):(X=20,z|=function(H){return 63&(H||0)}(x.dosPermissions)),y=L.getUTCHours(),y<<=6,y|=L.getUTCMinutes(),y<<=5,y|=L.getUTCSeconds()/2,O=L.getUTCFullYear()-1980,O<<=4,O|=L.getUTCMonth()+1,O<<=5,O|=L.getUTCDate(),I&&(J=h(1,1)+h(v(M),4)+A,T+="up"+h(J.length,2)+J),r&&(P=h(1,1)+h(v(V),4)+p,T+="uc"+h(P.length,2)+P);var G="";return G+=` +\0`,G+=h(C,2),G+=N.magic,G+=h(y,2),G+=h(O,2),G+=h(q.crc32,4),G+=h(q.compressedSize,4),G+=h(q.uncompressedSize,4),G+=h(M.length,2),G+=h(T.length,2),{fileRecord:m.LOCAL_FILE_HEADER+G+M+T,dirRecord:m.CENTRAL_FILE_HEADER+h(X,2)+G+h(V.length,2)+"\0\0\0\0"+h(z,4)+h(n,4)+M+T+V}}var t=_("../utils"),u=_("../stream/GenericWorker"),b=_("../utf8"),v=_("../crc32"),m=_("../signature");function g(i,d,c,n){u.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=d,this.zipPlatform=c,this.encodeFileName=n,this.streamFiles=i,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}t.inherits(g,u),g.prototype.push=function(i){var d=i.meta.percent||0,c=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(i):(this.bytesWritten+=i.data.length,u.prototype.push.call(this,{data:i.data,meta:{currentFile:this.currentFile,percent:c?(d+100*(c-n-1))/c:100}}))},g.prototype.openedSource=function(i){this.currentSourceOffset=this.bytesWritten,this.currentFile=i.file.name;var d=this.streamFiles&&!i.file.dir;if(d){var c=f(i,d,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:c.fileRecord,meta:{percent:0}})}else this.accumulate=!0},g.prototype.closedSource=function(i){this.accumulate=!1;var d=this.streamFiles&&!i.file.dir,c=f(i,d,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(c.dirRecord),d)this.push({data:function(n){return m.DATA_DESCRIPTOR+h(n.crc32,4)+h(n.compressedSize,4)+h(n.uncompressedSize,4)}(i),meta:{percent:100}});else for(this.push({data:c.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},g.prototype.flush=function(){for(var i=this.bytesWritten,d=0;d=this.index;u--)b=(b<<8)+this.byteAt(u);return this.index+=t,b},readString:function(t){return h.transformTo("string",this.readData(t))},readData:function(t){},lastIndexOfSignature:function(t){},readAndCheckSignature:function(t){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},U.exports=f},{"../utils":32}],19:[function(_,U,k){var h=_("./Uint8ArrayReader");function f(t){h.call(this,t)}_("../utils").inherits(f,h),f.prototype.readData=function(t){this.checkOffset(t);var u=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,u},U.exports=f},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(_,U,k){var h=_("./DataReader");function f(t){h.call(this,t)}_("../utils").inherits(f,h),f.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},f.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},f.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},f.prototype.readData=function(t){this.checkOffset(t);var u=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,u},U.exports=f},{"../utils":32,"./DataReader":18}],21:[function(_,U,k){var h=_("./ArrayReader");function f(t){h.call(this,t)}_("../utils").inherits(f,h),f.prototype.readData=function(t){if(this.checkOffset(t),t===0)return new Uint8Array(0);var u=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,u},U.exports=f},{"../utils":32,"./ArrayReader":17}],22:[function(_,U,k){var h=_("../utils"),f=_("../support"),t=_("./ArrayReader"),u=_("./StringReader"),b=_("./NodeBufferReader"),v=_("./Uint8ArrayReader");U.exports=function(m){var g=h.getTypeOf(m);return h.checkSupport(g),g!=="string"||f.uint8array?g==="nodebuffer"?new b(m):f.uint8array?new v(h.transformTo("uint8array",m)):new t(h.transformTo("array",m)):new u(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(_,U,k){k.LOCAL_FILE_HEADER="PK",k.CENTRAL_FILE_HEADER="PK",k.CENTRAL_DIRECTORY_END="PK",k.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",k.ZIP64_CENTRAL_DIRECTORY_END="PK",k.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(_,U,k){var h=_("./GenericWorker"),f=_("../utils");function t(u){h.call(this,"ConvertWorker to "+u),this.destType=u}f.inherits(t,h),t.prototype.processChunk=function(u){this.push({data:f.transformTo(this.destType,u.data),meta:u.meta})},U.exports=t},{"../utils":32,"./GenericWorker":28}],25:[function(_,U,k){var h=_("./GenericWorker"),f=_("../crc32");function t(){h.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}_("../utils").inherits(t,h),t.prototype.processChunk=function(u){this.streamInfo.crc32=f(u.data,this.streamInfo.crc32||0),this.push(u)},U.exports=t},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(_,U,k){var h=_("../utils"),f=_("./GenericWorker");function t(u){f.call(this,"DataLengthProbe for "+u),this.propName=u,this.withStreamInfo(u,0)}h.inherits(t,f),t.prototype.processChunk=function(u){if(u){var b=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=b+u.data.length}f.prototype.processChunk.call(this,u)},U.exports=t},{"../utils":32,"./GenericWorker":28}],27:[function(_,U,k){var h=_("../utils"),f=_("./GenericWorker");function t(u){f.call(this,"DataWorker");var b=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,u.then(function(v){b.dataIsReady=!0,b.data=v,b.max=v&&v.length||0,b.type=h.getTypeOf(v),b.isPaused||b._tickAndRepeat()},function(v){b.error(v)})}h.inherits(t,f),t.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},t.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,h.delay(this._tickAndRepeat,[],this)),!0)},t.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(h.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},t.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var u=null,b=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":u=this.data.substring(this.index,b);break;case"uint8array":u=this.data.subarray(this.index,b);break;case"array":case"nodebuffer":u=this.data.slice(this.index,b)}return this.index=b,this.push({data:u,meta:{percent:this.max?this.index/this.max*100:0}})},U.exports=t},{"../utils":32,"./GenericWorker":28}],28:[function(_,U,k){function h(f){this.name=f||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}h.prototype={push:function(f){this.emit("data",f)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(f){this.emit("error",f)}return!0},error:function(f){return!this.isFinished&&(this.isPaused?this.generatedError=f:(this.isFinished=!0,this.emit("error",f),this.previous&&this.previous.error(f),this.cleanUp()),!0)},on:function(f,t){return this._listeners[f].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(f,t){if(this._listeners[f])for(var u=0;u "+f:f}},U.exports=h},{}],29:[function(_,U,k){var h=_("../utils"),f=_("./ConvertWorker"),t=_("./GenericWorker"),u=_("../base64"),b=_("../support"),v=_("../external"),m=null;if(b.nodestream)try{m=_("../nodejs/NodejsStreamOutputAdapter")}catch(d){}function g(d,c){return new v.Promise(function(n,s){var l=[],y=d._internalType,O=d._outputType,x=d._mimeType;d.on("data",function(N,R){l.push(N),c&&c(R)}).on("error",function(N){l=[],s(N)}).on("end",function(){try{var N=function(R,M,A){switch(R){case"blob":return h.newBlob(h.transformTo("arraybuffer",M),A);case"base64":return u.encode(M);default:return h.transformTo(R,M)}}(O,function(R,M){var A,W=0,V=null,p=0;for(A=0;A>>6:(n<65536?c[y++]=224|n>>>12:(c[y++]=240|n>>>18,c[y++]=128|n>>>12&63),c[y++]=128|n>>>6&63),c[y++]=128|63&n);return c}(i)},k.utf8decode=function(i){return f.nodebuffer?h.transformTo("nodebuffer",i).toString("utf-8"):function(d){var c,n,s,l,y=d.length,O=new Array(2*y);for(c=n=0;c>10&1023,O[n++]=56320|1023&s)}return O.length!==n&&(O.subarray?O=O.subarray(0,n):O.length=n),h.applyFromCharCode(O)}(i=h.transformTo(f.uint8array?"uint8array":"array",i))},h.inherits(m,u),m.prototype.processChunk=function(i){var d=h.transformTo(f.uint8array?"uint8array":"array",i.data);if(this.leftOver&&this.leftOver.length){if(f.uint8array){var c=d;(d=new Uint8Array(c.length+this.leftOver.length)).set(this.leftOver,0),d.set(c,this.leftOver.length)}else d=this.leftOver.concat(d);this.leftOver=null}var n=function(l,y){var O;for((y=y||l.length)>l.length&&(y=l.length),O=y-1;0<=O&&(192&l[O])==128;)O--;return O<0||O===0?y:O+b[l[O]]>y?O:y}(d),s=d;n!==d.length&&(f.uint8array?(s=d.subarray(0,n),this.leftOver=d.subarray(n,d.length)):(s=d.slice(0,n),this.leftOver=d.slice(n,d.length))),this.push({data:k.utf8decode(s),meta:i.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:k.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},k.Utf8DecodeWorker=m,h.inherits(g,u),g.prototype.processChunk=function(i){this.push({data:k.utf8encode(i.data),meta:i.meta})},k.Utf8EncodeWorker=g},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(_,U,k){var h=_("./support"),f=_("./base64"),t=_("./nodejsUtils"),u=_("set-immediate-shim"),b=_("./external");function v(n){return n}function m(n,s){for(var l=0;l>8;this.dir=!!(16&this.externalFileAttributes),i==0&&(this.dosPermissions=63&this.externalFileAttributes),i==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(i){if(this.extraFields[1]){var d=h(this.extraFields[1].value);this.uncompressedSize===f.MAX_VALUE_32BITS&&(this.uncompressedSize=d.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=d.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=d.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=d.readInt(4))}},readExtraFields:function(i){var d,c,n,s=i.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});i.index+4>>6:(i<65536?g[n++]=224|i>>>12:(g[n++]=240|i>>>18,g[n++]=128|i>>>12&63),g[n++]=128|i>>>6&63),g[n++]=128|63&i);return g},k.buf2binstring=function(m){return v(m,m.length)},k.binstring2buf=function(m){for(var g=new h.Buf8(m.length),i=0,d=g.length;i>10&1023,l[d++]=56320|1023&c)}return v(l,d)},k.utf8border=function(m,g){var i;for((g=g||m.length)>m.length&&(g=m.length),i=g-1;0<=i&&(192&m[i])==128;)i--;return i<0||i===0?g:i+u[m[i]]>g?i:g}},{"./common":41}],43:[function(_,U,k){U.exports=function(h,f,t,u){for(var b=65535&h|0,v=h>>>16&65535|0,m=0;t!==0;){for(t-=m=2e3>>1:f>>>1;t[u]=f}return t}();U.exports=function(f,t,u,b){var v=h,m=b+u;f^=-1;for(var g=b;g>>8^v[255&(f^t[g])];return-1^f}},{}],46:[function(_,U,k){var h,f=_("../utils/common"),t=_("./trees"),u=_("./adler32"),b=_("./crc32"),v=_("./messages"),m=0,g=4,i=0,d=-2,c=-1,n=4,s=2,l=8,y=9,O=286,x=30,N=19,R=2*O+1,M=15,A=3,W=258,V=W+A+1,p=42,I=113,r=1,T=2,J=3,P=4;function Q(e,B){return e.msg=v[B],B}function L(e){return(e<<1)-(4e.avail_out&&(E=e.avail_out),E!==0&&(f.arraySet(e.output,B.pending_buf,B.pending_out,E,e.next_out),e.next_out+=E,B.pending_out+=E,e.total_out+=E,e.avail_out-=E,B.pending-=E,B.pending===0&&(B.pending_out=0))}function z(e,B){t._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,B),e.block_start=e.strstart,C(e.strm)}function X(e,B){e.pending_buf[e.pending++]=B}function G(e,B){e.pending_buf[e.pending++]=B>>>8&255,e.pending_buf[e.pending++]=255&B}function H(e,B){var E,o,a=e.max_chain_length,w=e.strstart,D=e.prev_length,F=e.nice_match,S=e.strstart>e.w_size-V?e.strstart-(e.w_size-V):0,j=e.window,K=e.w_mask,Z=e.prev,Y=e.strstart+W,te=j[w+D-1],ee=j[w+D];e.prev_length>=e.good_match&&(a>>=2),F>e.lookahead&&(F=e.lookahead);do if(j[(E=B)+D]===ee&&j[E+D-1]===te&&j[E]===j[w]&&j[++E]===j[w+1]){w+=2,E++;do;while(j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&j[++w]===j[++E]&&wS&&--a!=0);return D<=e.lookahead?D:e.lookahead}function ne(e){var B,E,o,a,w,D,F,S,j,K,Z=e.w_size;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=Z+(Z-V)){for(f.arraySet(e.window,e.window,Z,Z,0),e.match_start-=Z,e.strstart-=Z,e.block_start-=Z,B=E=e.hash_size;o=e.head[--B],e.head[B]=Z<=o?o-Z:0,--E;);for(B=E=Z;o=e.prev[--B],e.prev[B]=Z<=o?o-Z:0,--E;);a+=Z}if(e.strm.avail_in===0)break;if(D=e.strm,F=e.window,S=e.strstart+e.lookahead,j=a,K=void 0,K=D.avail_in,j=A)for(w=e.strstart-e.insert,e.ins_h=e.window[w],e.ins_h=(e.ins_h<=A&&(e.ins_h=(e.ins_h<=A)if(o=t._tr_tally(e,e.strstart-e.match_start,e.match_length-A),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=A){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=A&&(e.ins_h=(e.ins_h<=A&&e.match_length<=e.prev_length){for(a=e.strstart+e.lookahead-A,o=t._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-A),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=a&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(E=e.pending_buf_size-5);;){if(e.lookahead<=1){if(ne(e),e.lookahead===0&&B===m)return r;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var o=e.block_start+E;if((e.strstart===0||e.strstart>=o)&&(e.lookahead=e.strstart-o,e.strstart=o,z(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-V&&(z(e,!1),e.strm.avail_out===0))return r}return e.insert=0,B===g?(z(e,!0),e.strm.avail_out===0?J:P):(e.strstart>e.block_start&&(z(e,!1),e.strm.avail_out),r)}),new re(4,4,8,4,oe),new re(4,5,16,8,oe),new re(4,6,32,32,oe),new re(4,4,16,16,$),new re(8,16,32,32,$),new re(8,16,128,128,$),new re(8,32,128,256,$),new re(32,128,258,1024,$),new re(32,258,258,4096,$)],k.deflateInit=function(e,B){return ue(e,B,l,15,8,0)},k.deflateInit2=ue,k.deflateReset=le,k.deflateResetKeep=ie,k.deflateSetHeader=function(e,B){return e&&e.state?e.state.wrap!==2?d:(e.state.gzhead=B,i):d},k.deflate=function(e,B){var E,o,a,w;if(!e||!e.state||5>8&255),X(o,o.gzhead.time>>16&255),X(o,o.gzhead.time>>24&255),X(o,o.level===9?2:2<=o.strategy||o.level<2?4:0),X(o,255&o.gzhead.os),o.gzhead.extra&&o.gzhead.extra.length&&(X(o,255&o.gzhead.extra.length),X(o,o.gzhead.extra.length>>8&255)),o.gzhead.hcrc&&(e.adler=b(e.adler,o.pending_buf,o.pending,0)),o.gzindex=0,o.status=69):(X(o,0),X(o,0),X(o,0),X(o,0),X(o,0),X(o,o.level===9?2:2<=o.strategy||o.level<2?4:0),X(o,3),o.status=I);else{var D=l+(o.w_bits-8<<4)<<8;D|=(2<=o.strategy||o.level<2?0:o.level<6?1:o.level===6?2:3)<<6,o.strstart!==0&&(D|=32),D+=31-D%31,o.status=I,G(o,D),o.strstart!==0&&(G(o,e.adler>>>16),G(o,65535&e.adler)),e.adler=1}if(o.status===69)if(o.gzhead.extra){for(a=o.pending;o.gzindex<(65535&o.gzhead.extra.length)&&(o.pending!==o.pending_buf_size||(o.gzhead.hcrc&&o.pending>a&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),C(e),a=o.pending,o.pending!==o.pending_buf_size));)X(o,255&o.gzhead.extra[o.gzindex]),o.gzindex++;o.gzhead.hcrc&&o.pending>a&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),o.gzindex===o.gzhead.extra.length&&(o.gzindex=0,o.status=73)}else o.status=73;if(o.status===73)if(o.gzhead.name){a=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>a&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),C(e),a=o.pending,o.pending===o.pending_buf_size)){w=1;break}w=o.gzindexa&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),w===0&&(o.gzindex=0,o.status=91)}else o.status=91;if(o.status===91)if(o.gzhead.comment){a=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>a&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),C(e),a=o.pending,o.pending===o.pending_buf_size)){w=1;break}w=o.gzindexa&&(e.adler=b(e.adler,o.pending_buf,o.pending-a,a)),w===0&&(o.status=103)}else o.status=103;if(o.status===103&&(o.gzhead.hcrc?(o.pending+2>o.pending_buf_size&&C(e),o.pending+2<=o.pending_buf_size&&(X(o,255&e.adler),X(o,e.adler>>8&255),e.adler=0,o.status=I)):o.status=I),o.pending!==0){if(C(e),e.avail_out===0)return o.last_flush=-1,i}else if(e.avail_in===0&&L(B)<=L(E)&&B!==g)return Q(e,-5);if(o.status===666&&e.avail_in!==0)return Q(e,-5);if(e.avail_in!==0||o.lookahead!==0||B!==m&&o.status!==666){var F=o.strategy===2?function(S,j){for(var K;;){if(S.lookahead===0&&(ne(S),S.lookahead===0)){if(j===m)return r;break}if(S.match_length=0,K=t._tr_tally(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++,K&&(z(S,!1),S.strm.avail_out===0))return r}return S.insert=0,j===g?(z(S,!0),S.strm.avail_out===0?J:P):S.last_lit&&(z(S,!1),S.strm.avail_out===0)?r:T}(o,B):o.strategy===3?function(S,j){for(var K,Z,Y,te,ee=S.window;;){if(S.lookahead<=W){if(ne(S),S.lookahead<=W&&j===m)return r;if(S.lookahead===0)break}if(S.match_length=0,S.lookahead>=A&&0S.lookahead&&(S.match_length=S.lookahead)}if(S.match_length>=A?(K=t._tr_tally(S,1,S.match_length-A),S.lookahead-=S.match_length,S.strstart+=S.match_length,S.match_length=0):(K=t._tr_tally(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++),K&&(z(S,!1),S.strm.avail_out===0))return r}return S.insert=0,j===g?(z(S,!0),S.strm.avail_out===0?J:P):S.last_lit&&(z(S,!1),S.strm.avail_out===0)?r:T}(o,B):h[o.level].func(o,B);if(F!==J&&F!==P||(o.status=666),F===r||F===J)return e.avail_out===0&&(o.last_flush=-1),i;if(F===T&&(B===1?t._tr_align(o):B!==5&&(t._tr_stored_block(o,0,0,!1),B===3&&(q(o.head),o.lookahead===0&&(o.strstart=0,o.block_start=0,o.insert=0))),C(e),e.avail_out===0))return o.last_flush=-1,i}return B!==g?i:o.wrap<=0?1:(o.wrap===2?(X(o,255&e.adler),X(o,e.adler>>8&255),X(o,e.adler>>16&255),X(o,e.adler>>24&255),X(o,255&e.total_in),X(o,e.total_in>>8&255),X(o,e.total_in>>16&255),X(o,e.total_in>>24&255)):(G(o,e.adler>>>16),G(o,65535&e.adler)),C(e),0=E.w_size&&(w===0&&(q(E.head),E.strstart=0,E.block_start=0,E.insert=0),j=new f.Buf8(E.w_size),f.arraySet(j,B,K-E.w_size,E.w_size,0),B=j,K=E.w_size),D=e.avail_in,F=e.next_in,S=e.input,e.avail_in=K,e.next_in=0,e.input=B,ne(E);E.lookahead>=A;){for(o=E.strstart,a=E.lookahead-(A-1);E.ins_h=(E.ins_h<>>=A=M>>>24,y-=A,(A=M>>>16&255)==0)T[v++]=65535&M;else{if(!(16&A)){if((64&A)==0){M=O[(65535&M)+(l&(1<>>=A,y-=A),y<15&&(l+=r[u++]<>>=A=M>>>24,y-=A,!(16&(A=M>>>16&255))){if((64&A)==0){M=x[(65535&M)+(l&(1<>>=A,y-=A,(A=v-m)>3,l&=(1<<(y-=W<<3))-1,h.next_in=u,h.next_out=v,h.avail_in=u>>24&255)+(p>>>8&65280)+((65280&p)<<8)+((255&p)<<24)}function l(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new h.Buf16(320),this.work=new h.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(p){var I;return p&&p.state?(I=p.state,p.total_in=p.total_out=I.total=0,p.msg="",I.wrap&&(p.adler=1&I.wrap),I.mode=d,I.last=0,I.havedict=0,I.dmax=32768,I.head=null,I.hold=0,I.bits=0,I.lencode=I.lendyn=new h.Buf32(c),I.distcode=I.distdyn=new h.Buf32(n),I.sane=1,I.back=-1,g):i}function O(p){var I;return p&&p.state?((I=p.state).wsize=0,I.whave=0,I.wnext=0,y(p)):i}function x(p,I){var r,T;return p&&p.state?(T=p.state,I<0?(r=0,I=-I):(r=1+(I>>4),I<48&&(I&=15)),I&&(I<8||15=P.wsize?(h.arraySet(P.window,I,r-P.wsize,P.wsize,0),P.wnext=0,P.whave=P.wsize):(T<(J=P.wsize-P.wnext)&&(J=T),h.arraySet(P.window,I,r-T,J,P.wnext),(T-=J)?(h.arraySet(P.window,I,r-T,T,0),P.wnext=T,P.whave=P.wsize):(P.wnext+=J,P.wnext===P.wsize&&(P.wnext=0),P.whave>>8&255,r.check=t(r.check,w,2,0),z=C=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&C)<<8)+(C>>8))%31){p.msg="incorrect header check",r.mode=30;break}if((15&C)!=8){p.msg="unknown compression method",r.mode=30;break}if(z-=4,e=8+(15&(C>>>=4)),r.wbits===0)r.wbits=e;else if(e>r.wbits){p.msg="invalid window size",r.mode=30;break}r.dmax=1<>8&1),512&r.flags&&(w[0]=255&C,w[1]=C>>>8&255,r.check=t(r.check,w,2,0)),z=C=0,r.mode=3;case 3:for(;z<32;){if(L===0)break e;L--,C+=T[P++]<>>8&255,w[2]=C>>>16&255,w[3]=C>>>24&255,r.check=t(r.check,w,4,0)),z=C=0,r.mode=4;case 4:for(;z<16;){if(L===0)break e;L--,C+=T[P++]<>8),512&r.flags&&(w[0]=255&C,w[1]=C>>>8&255,r.check=t(r.check,w,2,0)),z=C=0,r.mode=5;case 5:if(1024&r.flags){for(;z<16;){if(L===0)break e;L--,C+=T[P++]<>>8&255,r.check=t(r.check,w,2,0)),z=C=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(L<(H=r.length)&&(H=L),H&&(r.head&&(e=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),h.arraySet(r.head.extra,T,P,H,e)),512&r.flags&&(r.check=t(r.check,T,H,P)),L-=H,P+=H,r.length-=H),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(L===0)break e;for(H=0;e=T[P+H++],r.head&&e&&r.length<65536&&(r.head.name+=String.fromCharCode(e)),e&&H>9&1,r.head.done=!0),p.adler=r.check=0,r.mode=12;break;case 10:for(;z<32;){if(L===0)break e;L--,C+=T[P++]<>>=7&z,z-=7&z,r.mode=27;break}for(;z<3;){if(L===0)break e;L--,C+=T[P++]<>>=1)){case 0:r.mode=14;break;case 1:if(W(r),r.mode=20,I!==6)break;C>>>=2,z-=2;break e;case 2:r.mode=17;break;case 3:p.msg="invalid block type",r.mode=30}C>>>=2,z-=2;break;case 14:for(C>>>=7&z,z-=7&z;z<32;){if(L===0)break e;L--,C+=T[P++]<>>16^65535)){p.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&C,z=C=0,r.mode=15,I===6)break e;case 15:r.mode=16;case 16:if(H=r.length){if(L>>=5,z-=5,r.ndist=1+(31&C),C>>>=5,z-=5,r.ncode=4+(15&C),C>>>=4,z-=4,286>>=3,z-=3}for(;r.have<19;)r.lens[D[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,E={bits:r.lenbits},B=b(0,r.lens,0,19,r.lencode,0,r.work,E),r.lenbits=E.bits,B){p.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,se=65535&a,!(($=a>>>24)<=z);){if(L===0)break e;L--,C+=T[P++]<>>=$,z-=$,r.lens[r.have++]=se;else{if(se===16){for(o=$+2;z>>=$,z-=$,r.have===0){p.msg="invalid bit length repeat",r.mode=30;break}e=r.lens[r.have-1],H=3+(3&C),C>>>=2,z-=2}else if(se===17){for(o=$+3;z>>=$)),C>>>=3,z-=3}else{for(o=$+7;z>>=$)),C>>>=7,z-=7}if(r.have+H>r.nlen+r.ndist){p.msg="invalid bit length repeat",r.mode=30;break}for(;H--;)r.lens[r.have++]=e}}if(r.mode===30)break;if(r.lens[256]===0){p.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,E={bits:r.lenbits},B=b(v,r.lens,0,r.nlen,r.lencode,0,r.work,E),r.lenbits=E.bits,B){p.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,E={bits:r.distbits},B=b(m,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,E),r.distbits=E.bits,B){p.msg="invalid distances set",r.mode=30;break}if(r.mode=20,I===6)break e;case 20:r.mode=21;case 21:if(6<=L&&258<=q){p.next_out=Q,p.avail_out=q,p.next_in=P,p.avail_in=L,r.hold=C,r.bits=z,u(p,G),Q=p.next_out,J=p.output,q=p.avail_out,P=p.next_in,T=p.input,L=p.avail_in,C=r.hold,z=r.bits,r.mode===12&&(r.back=-1);break}for(r.back=0;re=(a=r.lencode[C&(1<>>16&255,se=65535&a,!(($=a>>>24)<=z);){if(L===0)break e;L--,C+=T[P++]<>ie)])>>>16&255,se=65535&a,!(ie+($=a>>>24)<=z);){if(L===0)break e;L--,C+=T[P++]<>>=ie,z-=ie,r.back+=ie}if(C>>>=$,z-=$,r.back+=$,r.length=se,re===0){r.mode=26;break}if(32&re){r.back=-1,r.mode=12;break}if(64&re){p.msg="invalid literal/length code",r.mode=30;break}r.extra=15&re,r.mode=22;case 22:if(r.extra){for(o=r.extra;z>>=r.extra,z-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;re=(a=r.distcode[C&(1<>>16&255,se=65535&a,!(($=a>>>24)<=z);){if(L===0)break e;L--,C+=T[P++]<>ie)])>>>16&255,se=65535&a,!(ie+($=a>>>24)<=z);){if(L===0)break e;L--,C+=T[P++]<>>=ie,z-=ie,r.back+=ie}if(C>>>=$,z-=$,r.back+=$,64&re){p.msg="invalid distance code",r.mode=30;break}r.offset=se,r.extra=15&re,r.mode=24;case 24:if(r.extra){for(o=r.extra;z>>=r.extra,z-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){p.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(q===0)break e;if(H=G-q,r.offset>H){if((H=r.offset-H)>r.whave&&r.sane){p.msg="invalid distance too far back",r.mode=30;break}ne=H>r.wnext?(H-=r.wnext,r.wsize-H):r.wnext-H,H>r.length&&(H=r.length),oe=r.window}else oe=J,ne=Q-r.offset,H=r.length;for(qR?(A=ne[oe+n[I]],z[X+n[I]]):(A=96,0),l=1<>Q)+(y-=l)]=M<<24|A<<16|W|0,y!==0;);for(l=1<>=1;if(l!==0?(C&=l-1,C+=l):C=0,I++,--G[p]==0){if(p===T)break;p=m[g+n[I]]}if(J>>7)]}function X(a,w){a.pending_buf[a.pending++]=255&w,a.pending_buf[a.pending++]=w>>>8&255}function G(a,w,D){a.bi_valid>s-D?(a.bi_buf|=w<>s-a.bi_valid,a.bi_valid+=D-s):(a.bi_buf|=w<>>=1,D<<=1,0<--w;);return D>>>1}function oe(a,w,D){var F,S,j=new Array(n+1),K=0;for(F=1;F<=n;F++)j[F]=K=K+D[F-1]<<1;for(S=0;S<=w;S++){var Z=a[2*S+1];Z!==0&&(a[2*S]=ne(j[Z]++,Z))}}function $(a){var w;for(w=0;w>1;1<=D;D--)ie(a,j,D);for(S=Y;D=a.heap[1],a.heap[1]=a.heap[a.heap_len--],ie(a,j,1),F=a.heap[1],a.heap[--a.heap_max]=D,a.heap[--a.heap_max]=F,j[2*S]=j[2*D]+j[2*F],a.depth[S]=(a.depth[D]>=a.depth[F]?a.depth[D]:a.depth[F])+1,j[2*D+1]=j[2*F+1]=S,a.heap[1]=S++,ie(a,j,1),2<=a.heap_len;);a.heap[--a.heap_max]=a.heap[1],function(ee,he){var ce,fe,pe,ae,_e,ve,de=he.dyn_tree,ye=he.max_code,Se=he.stat_desc.static_tree,ze=he.stat_desc.has_stree,Ce=he.stat_desc.extra_bits,we=he.stat_desc.extra_base,me=he.stat_desc.max_length,ge=0;for(ae=0;ae<=n;ae++)ee.bl_count[ae]=0;for(de[2*ee.heap[ee.heap_max]+1]=0,ce=ee.heap_max+1;ce>=7;S>>=1)if(1&te&&Z.dyn_ltree[2*Y]!==0)return f;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return t;for(Y=32;Y>>3,(j=a.static_len+3+7>>>3)<=S&&(S=j)):S=j=D+5,D+4<=S&&w!==-1?o(a,w,D,F):a.strategy===4||j===S?(G(a,2+(F?1:0),3),le(a,V,p)):(G(a,4+(F?1:0),3),function(Z,Y,te,ee){var he;for(G(Z,Y-257,5),G(Z,te-1,5),G(Z,ee-4,4),he=0;he>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&w,a.pending_buf[a.l_buf+a.last_lit]=255&D,a.last_lit++,w===0?a.dyn_ltree[2*D]++:(a.matches++,w--,a.dyn_ltree[2*(r[D]+m+1)]++,a.dyn_dtree[2*z(w)]++),a.last_lit===a.lit_bufsize-1},k._tr_align=function(a){G(a,2,3),H(a,y,V),function(w){w.bi_valid===16?(X(w,w.bi_buf),w.bi_buf=0,w.bi_valid=0):8<=w.bi_valid&&(w.pending_buf[w.pending++]=255&w.bi_buf,w.bi_buf>>=8,w.bi_valid-=8)}(a)}},{"../utils/common":41}],53:[function(_,U,k){U.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(_,U,k){U.exports=typeof setImmediate=="function"?setImmediate:function(){var h=[].slice.apply(arguments);h.splice(1,0,0),setTimeout.apply(null,h)}},{}]},{},[10])(10)})});export default Ae; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash.js new file mode 100644 index 0000000000000000000000000000000000000000..dd02c7d6134be9ba4dae9eb308d82f50d9fc3a8e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash.js @@ -0,0 +1,20 @@ +import{c as rp,a as jt}from"./common/_commonjsHelpers-b3efd043.js";var ep=rp(function(Jr,Qr){(function(){var o,rl="4.17.21",Vr=200,el="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",sn="Expected a function",il="Invalid `variable` option passed into `_.template`",kr="__lodash_hash_undefined__",ul=500,nr="__lodash_placeholder__",qn=1,Ri=2,at=4,ct=1,tr=2,an=1,jn=2,Ii=4,Tn=8,ht=16,mn=32,gt=64,Wn=128,Ot=256,jr=512,fl=30,ll="...",ol=800,sl=16,Si=1,al=2,cl=3,nt=1/0,Kn=9007199254740991,hl=17976931348623157e292,rr=0/0,yn=4294967295,gl=yn-1,_l=yn>>>1,pl=[["ary",Wn],["bind",an],["bindKey",jn],["curry",Tn],["curryRight",ht],["flip",jr],["partial",mn],["partialRight",gt],["rearg",Ot]],_t="[object Arguments]",er="[object Array]",vl="[object AsyncFunction]",Wt="[object Boolean]",Pt="[object Date]",dl="[object DOMException]",ir="[object Error]",ur="[object Function]",Ei="[object GeneratorFunction]",xn="[object Map]",Bt="[object Number]",wl="[object Null]",Pn="[object Object]",Ti="[object Promise]",xl="[object Proxy]",bt="[object RegExp]",An="[object Set]",Ft="[object String]",fr="[object Symbol]",Al="[object Undefined]",Ut="[object WeakMap]",Rl="[object WeakSet]",Dt="[object ArrayBuffer]",pt="[object DataView]",ne="[object Float32Array]",te="[object Float64Array]",re="[object Int8Array]",ee="[object Int16Array]",ie="[object Int32Array]",ue="[object Uint8Array]",fe="[object Uint8ClampedArray]",le="[object Uint16Array]",oe="[object Uint32Array]",Il=/\b__p \+= '';/g,Sl=/\b(__p \+=) '' \+/g,El=/(__e\(.*?\)|\b__t\)) \+\n'';/g,mi=/&(?:amp|lt|gt|quot|#39);/g,yi=/[&<>"']/g,Tl=RegExp(mi.source),ml=RegExp(yi.source),yl=/<%-([\s\S]+?)%>/g,Ll=/<%([\s\S]+?)%>/g,Li=/<%=([\s\S]+?)%>/g,Cl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ol=/^\w*$/,Wl=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,se=/[\\^$.*+?()[\]{}|]/g,Pl=RegExp(se.source),ae=/^\s+/,Bl=/\s/,bl=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Fl=/\{\n\/\* \[wrapped with (.+)\] \*/,Ul=/,? & /,Dl=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Ml=/[()=,{}\[\]\/\s]/,Nl=/\\(\\)?/g,Gl=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ci=/\w*$/,Hl=/^[-+]0x[0-9a-f]+$/i,ql=/^0b[01]+$/i,Kl=/^\[object .+?Constructor\]$/,$l=/^0o[0-7]+$/i,zl=/^(?:0|[1-9]\d*)$/,Zl=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,lr=/($^)/,Yl=/['\n\r\u2028\u2029\\]/g,or="\\ud800-\\udfff",Xl="\\u0300-\\u036f",Jl="\\ufe20-\\ufe2f",Ql="\\u20d0-\\u20ff",Oi=Xl+Jl+Ql,Wi="\\u2700-\\u27bf",Pi="a-z\\xdf-\\xf6\\xf8-\\xff",Vl="\\xac\\xb1\\xd7\\xf7",kl="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",jl="\\u2000-\\u206f",no=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Bi="A-Z\\xc0-\\xd6\\xd8-\\xde",bi="\\ufe0e\\ufe0f",Fi=Vl+kl+jl+no,ce="['\u2019]",to="["+or+"]",Ui="["+Fi+"]",sr="["+Oi+"]",Di="\\d+",ro="["+Wi+"]",Mi="["+Pi+"]",Ni="[^"+or+Fi+Di+Wi+Pi+Bi+"]",he="\\ud83c[\\udffb-\\udfff]",eo="(?:"+sr+"|"+he+")",Gi="[^"+or+"]",ge="(?:\\ud83c[\\udde6-\\uddff]){2}",_e="[\\ud800-\\udbff][\\udc00-\\udfff]",vt="["+Bi+"]",Hi="\\u200d",qi="(?:"+Mi+"|"+Ni+")",io="(?:"+vt+"|"+Ni+")",Ki="(?:"+ce+"(?:d|ll|m|re|s|t|ve))?",$i="(?:"+ce+"(?:D|LL|M|RE|S|T|VE))?",zi=eo+"?",Zi="["+bi+"]?",uo="(?:"+Hi+"(?:"+[Gi,ge,_e].join("|")+")"+Zi+zi+")*",fo="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",lo="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Yi=Zi+zi+uo,oo="(?:"+[ro,ge,_e].join("|")+")"+Yi,so="(?:"+[Gi+sr+"?",sr,ge,_e,to].join("|")+")",ao=RegExp(ce,"g"),co=RegExp(sr,"g"),pe=RegExp(he+"(?="+he+")|"+so+Yi,"g"),ho=RegExp([vt+"?"+Mi+"+"+Ki+"(?="+[Ui,vt,"$"].join("|")+")",io+"+"+$i+"(?="+[Ui,vt+qi,"$"].join("|")+")",vt+"?"+qi+"+"+Ki,vt+"+"+$i,lo,fo,Di,oo].join("|"),"g"),go=RegExp("["+Hi+or+Oi+bi+"]"),_o=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,po=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],vo=-1,U={};U[ne]=U[te]=U[re]=U[ee]=U[ie]=U[ue]=U[fe]=U[le]=U[oe]=!0,U[_t]=U[er]=U[Dt]=U[Wt]=U[pt]=U[Pt]=U[ir]=U[ur]=U[xn]=U[Bt]=U[Pn]=U[bt]=U[An]=U[Ft]=U[Ut]=!1;var F={};F[_t]=F[er]=F[Dt]=F[pt]=F[Wt]=F[Pt]=F[ne]=F[te]=F[re]=F[ee]=F[ie]=F[xn]=F[Bt]=F[Pn]=F[bt]=F[An]=F[Ft]=F[fr]=F[ue]=F[fe]=F[le]=F[oe]=!0,F[ir]=F[ur]=F[Ut]=!1;var wo={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},xo={"&":"&","<":"<",">":">",'"':""","'":"'"},Ao={"&":"&","<":"<",">":">",""":'"',"'":"'"},Ro={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Io=parseFloat,So=parseInt,Xi=typeof jt=="object"&&jt&&jt.Object===Object&&jt,Eo=typeof self=="object"&&self&&self.Object===Object&&self,z=Xi||Eo||Function("return this")(),ve=Qr&&!Qr.nodeType&&Qr,tt=ve&&!0&&Jr&&!Jr.nodeType&&Jr,Ji=tt&&tt.exports===ve,de=Ji&&Xi.process,cn=function(){try{var a=tt&&tt.require&&tt.require("util").types;return a||de&&de.binding&&de.binding("util")}catch(g){}}(),Qi=cn&&cn.isArrayBuffer,Vi=cn&&cn.isDate,ki=cn&&cn.isMap,ji=cn&&cn.isRegExp,nu=cn&&cn.isSet,tu=cn&&cn.isTypedArray;function rn(a,g,h){switch(h.length){case 0:return a.call(g);case 1:return a.call(g,h[0]);case 2:return a.call(g,h[0],h[1]);case 3:return a.call(g,h[0],h[1],h[2])}return a.apply(g,h)}function To(a,g,h,w){for(var S=-1,W=a==null?0:a.length;++S-1}function we(a,g,h){for(var w=-1,S=a==null?0:a.length;++w-1;);return h}function su(a,g){for(var h=a.length;h--&&dt(g,a[h],0)>-1;);return h}function bo(a,g){for(var h=a.length,w=0;h--;)a[h]===g&&++w;return w}var Fo=Ie(wo),Uo=Ie(xo);function Do(a){return"\\"+Ro[a]}function Mo(a,g){return a==null?o:a[g]}function wt(a){return go.test(a)}function No(a){return _o.test(a)}function Go(a){for(var g,h=[];!(g=a.next()).done;)h.push(g.value);return h}function me(a){var g=-1,h=Array(a.size);return a.forEach(function(w,S){h[++g]=[S,w]}),h}function au(a,g){return function(h){return a(g(h))}}function Zn(a,g){for(var h=-1,w=a.length,S=0,W=[];++h-1}function ys(n,t){var r=this.__data__,e=yr(r,n);return e<0?(++this.size,r.push([n,t])):r[e][1]=t,this}Bn.prototype.clear=Ss,Bn.prototype.delete=Es,Bn.prototype.get=Ts,Bn.prototype.has=ms,Bn.prototype.set=ys;function bn(n){var t=-1,r=n==null?0:n.length;for(this.clear();++t=t?n:t)),n}function pn(n,t,r,e,i,f){var l,s=t&qn,c=t&Ri,_=t&at;if(r&&(l=i?r(n,e,i,f):r(n)),l!==o)return l;if(!N(n))return n;var p=E(n);if(p){if(l=Wa(n),!s)return k(n,l)}else{var v=X(n),d=v==ur||v==Ei;if(kn(n))return Zu(n,s);if(v==Pn||v==_t||d&&!i){if(l=c||d?{}:hf(n),!s)return c?Aa(n,Ks(l,n)):xa(n,Iu(l,n))}else{if(!F[v])return i?n:{};l=Pa(n,v,s)}}f||(f=new In);var x=f.get(n);if(x)return x;f.set(n,l),Hf(n)?n.forEach(function(I){l.add(pn(I,t,r,I,n,f))}):Nf(n)&&n.forEach(function(I,L){l.set(L,pn(I,t,r,L,n,f))});var R=_?c?ke:Ve:c?nn:$,m=p?o:R(n);return hn(m||n,function(I,L){m&&(L=I,I=n[L]),$t(l,L,pn(I,t,r,L,n,f))}),l}function $s(n){var t=$(n);return function(r){return Su(r,n,t)}}function Su(n,t,r){var e=r.length;if(n==null)return!e;for(n=P(n);e--;){var i=r[e],f=t[i],l=n[i];if(l===o&&!(i in n)||!f(l))return!1}return!0}function Eu(n,t,r){if(typeof n!="function")throw new gn(sn);return Vt(function(){n.apply(o,r)},t)}function zt(n,t,r,e){var i=-1,f=ar,l=!0,s=n.length,c=[],_=t.length;if(!s)return c;r&&(t=D(t,en(r))),e?(f=we,l=!1):t.length>=Vr&&(f=Mt,l=!1,t=new it(t));n:for(;++ii?0:i+r),e=e===o||e>i?i:T(e),e<0&&(e+=i),e=r>e?0:Kf(e);r0&&r(s)?t>1?Z(s,t-1,r,e,i):zn(i,s):e||(i[i.length]=s)}return i}var Be=ku(),yu=ku(!0);function Ln(n,t){return n&&Be(n,t,$)}function be(n,t){return n&&yu(n,t,$)}function Cr(n,t){return $n(t,function(r){return Nn(n[r])})}function ft(n,t){t=Qn(t,n);for(var r=0,e=t.length;n!=null&&rt}function Ys(n,t){return n!=null&&b.call(n,t)}function Xs(n,t){return n!=null&&t in P(n)}function Js(n,t,r){return n>=Y(t,r)&&n=120&&p.length>=120)?new it(l&&p):o}p=n[0];var v=-1,d=s[0];n:for(;++v-1;)s!==n&&Ar.call(s,c,1),Ar.call(n,c,1);return n}function Mu(n,t){for(var r=n?t.length:0,e=r-1;r--;){var i=t[r];if(r==e||i!==f){var f=i;Mn(i)?Ar.call(n,i,1):$e(n,i)}}return n}function He(n,t){return n+Sr(wu()*(t-n+1))}function oa(n,t,r,e){for(var i=-1,f=K(Ir((t-n)/(r||1)),0),l=h(f);f--;)l[e?f:++i]=n,n+=r;return l}function qe(n,t){var r="";if(!n||t<1||t>Kn)return r;do t%2&&(r+=n),t=Sr(t/2),t&&(n+=n);while(t);return r}function y(n,t){return ui(pf(n,t,tn),n+"")}function sa(n){return Ru(Ct(n))}function aa(n,t){var r=Ct(n);return Gr(r,ut(t,0,r.length))}function Xt(n,t,r,e){if(!N(n))return n;t=Qn(t,n);for(var i=-1,f=t.length,l=f-1,s=n;s!=null&&++ii?0:i+t),r=r>i?i:r,r<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var f=h(i);++e>>1,l=n[f];l!==null&&!fn(l)&&(r?l<=t:l=Vr){var _=t?null:Ea(n);if(_)return hr(_);l=!1,i=Mt,c=new it}else c=t?[]:s;n:for(;++e=e?n:vn(n,t,r)}var zu=ts||function(n){return z.clearTimeout(n)};function Zu(n,t){if(t)return n.slice();var r=n.length,e=gu?gu(r):new n.constructor(r);return n.copy(e),e}function Xe(n){var t=new n.constructor(n.byteLength);return new wr(t).set(new wr(n)),t}function pa(n,t){var r=t?Xe(n.buffer):n.buffer;return new n.constructor(r,n.byteOffset,n.byteLength)}function va(n){var t=new n.constructor(n.source,Ci.exec(n));return t.lastIndex=n.lastIndex,t}function da(n){return Kt?P(Kt.call(n)):{}}function Yu(n,t){var r=t?Xe(n.buffer):n.buffer;return new n.constructor(r,n.byteOffset,n.length)}function Xu(n,t){if(n!==t){var r=n!==o,e=n===null,i=n===n,f=fn(n),l=t!==o,s=t===null,c=t===t,_=fn(t);if(!s&&!_&&!f&&n>t||f&&l&&c&&!s&&!_||e&&l&&c||!r&&c||!i)return 1;if(!e&&!f&&!_&&n=s)return c;var _=r[e];return c*(_=="desc"?-1:1)}}return n.index-t.index}function Ju(n,t,r,e){for(var i=-1,f=n.length,l=r.length,s=-1,c=t.length,_=K(f-l,0),p=h(c+_),v=!e;++s1?r[i-1]:o,l=i>2?r[2]:o;for(f=n.length>3&&typeof f=="function"?(i--,f):o,l&&Q(r[0],r[1],l)&&(f=i<3?o:f,i=1),t=P(t);++e-1?i[f?t[l]:l]:o}}function tf(n){return Dn(function(t){var r=t.length,e=r,i=_n.prototype.thru;for(n&&t.reverse();e--;){var f=t[e];if(typeof f!="function")throw new gn(sn);if(i&&!l&&Mr(f)=="wrapper")var l=new _n([],!0)}for(e=l?e:r;++e1&&O.reverse(),p&&cs))return!1;var _=f.get(n),p=f.get(t);if(_&&p)return _==t&&p==n;var v=-1,d=!0,x=r&tr?new it:o;for(f.set(n,t),f.set(t,n);++v1?"& ":"")+t[e],t=t.join(r>2?", ":" "),n.replace(bl,`{ +/* [wrapped with `+t+`] */ +`)}function ba(n){return E(n)||st(n)||!!(vu&&n&&n[vu])}function Mn(n,t){var r=typeof n;return t=t==null?Kn:t,!!t&&(r=="number"||r!="symbol"&&zl.test(n))&&n>-1&&n%1==0&&n0){if(++t>=ol)return arguments[0]}else t=0;return n.apply(o,arguments)}}function Gr(n,t){var r=-1,e=n.length,i=e-1;for(t=t===o?e:t;++r1?n[t-1]:o;return r=typeof r=="function"?(n.pop(),r):o,yf(n,r)});function Lf(n){var t=u(n);return t.__chain__=!0,t}function zc(n,t){return t(n),n}function Hr(n,t){return t(n)}var Zc=Dn(function(n){var t=n.length,r=t?n[0]:0,e=this.__wrapped__,i=function(f){return Pe(f,n)};return t>1||this.__actions__.length||!(e instanceof C)||!Mn(r)?this.thru(i):(e=e.slice(r,+r+(t?1:0)),e.__actions__.push({func:Hr,args:[i],thisArg:o}),new _n(e,this.__chain__).thru(function(f){return t&&!f.length&&f.push(o),f}))});function Yc(){return Lf(this)}function Xc(){return new _n(this.value(),this.__chain__)}function Jc(){this.__values__===o&&(this.__values__=qf(this.value()));var n=this.__index__>=this.__values__.length,t=n?o:this.__values__[this.__index__++];return{done:n,value:t}}function Qc(){return this}function Vc(n){for(var t,r=this;r instanceof mr;){var e=Rf(r);e.__index__=0,e.__values__=o,t?i.__wrapped__=e:t=e;var i=e;r=r.__wrapped__}return i.__wrapped__=n,t}function kc(){var n=this.__wrapped__;if(n instanceof C){var t=n;return this.__actions__.length&&(t=new C(this)),t=t.reverse(),t.__actions__.push({func:Hr,args:[fi],thisArg:o}),new _n(t,this.__chain__)}return this.thru(fi)}function jc(){return Ku(this.__wrapped__,this.__actions__)}var nh=Br(function(n,t,r){b.call(n,r)?++n[r]:Fn(n,r,1)});function th(n,t,r){var e=E(n)?ru:zs;return r&&Q(n,t,r)&&(t=o),e(n,A(t,3))}function rh(n,t){var r=E(n)?$n:mu;return r(n,A(t,3))}var eh=nf(If),ih=nf(Sf);function uh(n,t){return Z(qr(n,t),1)}function fh(n,t){return Z(qr(n,t),nt)}function lh(n,t,r){return r=r===o?1:T(r),Z(qr(n,t),r)}function Cf(n,t){var r=E(n)?hn:Xn;return r(n,A(t,3))}function Of(n,t){var r=E(n)?mo:Tu;return r(n,A(t,3))}var oh=Br(function(n,t,r){b.call(n,r)?n[r].push(t):Fn(n,r,[t])});function sh(n,t,r,e){n=j(n)?n:Ct(n),r=r&&!e?T(r):0;var i=n.length;return r<0&&(r=K(i+r,0)),Yr(n)?r<=i&&n.indexOf(t,r)>-1:!!i&&dt(n,t,r)>-1}var ah=y(function(n,t,r){var e=-1,i=typeof t=="function",f=j(n)?h(n.length):[];return Xn(n,function(l){f[++e]=i?rn(t,l,r):Zt(l,t,r)}),f}),ch=Br(function(n,t,r){Fn(n,r,t)});function qr(n,t){var r=E(n)?D:Pu;return r(n,A(t,3))}function hh(n,t,r,e){return n==null?[]:(E(t)||(t=t==null?[]:[t]),r=e?o:r,E(r)||(r=r==null?[]:[r]),Uu(n,t,r))}var gh=Br(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]});function _h(n,t,r){var e=E(n)?xe:fu,i=arguments.length<3;return e(n,A(t,4),r,i,Xn)}function ph(n,t,r){var e=E(n)?yo:fu,i=arguments.length<3;return e(n,A(t,4),r,i,Tu)}function vh(n,t){var r=E(n)?$n:mu;return r(n,zr(A(t,3)))}function dh(n){var t=E(n)?Ru:sa;return t(n)}function wh(n,t,r){(r?Q(n,t,r):t===o)?t=1:t=T(t);var e=E(n)?Gs:aa;return e(n,t)}function xh(n){var t=E(n)?Hs:ha;return t(n)}function Ah(n){if(n==null)return 0;if(j(n))return Yr(n)?xt(n):n.length;var t=X(n);return t==xn||t==An?n.size:Me(n).length}function Rh(n,t,r){var e=E(n)?Ae:ga;return r&&Q(n,t,r)&&(t=o),e(n,A(t,3))}var Ih=y(function(n,t){if(n==null)return[];var r=t.length;return r>1&&Q(n,t[0],t[1])?t=[]:r>2&&Q(t[0],t[1],t[2])&&(t=[t[0]]),Uu(n,Z(t,1),[])}),Kr=rs||function(){return z.Date.now()};function Sh(n,t){if(typeof t!="function")throw new gn(sn);return n=T(n),function(){if(--n<1)return t.apply(this,arguments)}}function Wf(n,t,r){return t=r?o:t,t=n&&t==null?n.length:t,Un(n,Wn,o,o,o,o,t)}function Pf(n,t){var r;if(typeof t!="function")throw new gn(sn);return n=T(n),function(){return--n>0&&(r=t.apply(this,arguments)),n<=1&&(t=o),r}}var oi=y(function(n,t,r){var e=an;if(r.length){var i=Zn(r,yt(oi));e|=mn}return Un(n,e,t,r,i)}),Bf=y(function(n,t,r){var e=an|jn;if(r.length){var i=Zn(r,yt(Bf));e|=mn}return Un(t,e,n,r,i)});function bf(n,t,r){t=r?o:t;var e=Un(n,Tn,o,o,o,o,o,t);return e.placeholder=bf.placeholder,e}function Ff(n,t,r){t=r?o:t;var e=Un(n,ht,o,o,o,o,o,t);return e.placeholder=Ff.placeholder,e}function Uf(n,t,r){var e,i,f,l,s,c,_=0,p=!1,v=!1,d=!0;if(typeof n!="function")throw new gn(sn);t=wn(t)||0,N(r)&&(p=!!r.leading,v="maxWait"in r,f=v?K(wn(r.maxWait)||0,t):f,d="trailing"in r?!!r.trailing:d);function x(q){var En=e,Hn=i;return e=i=o,_=q,l=n.apply(Hn,En),l}function R(q){return _=q,s=Vt(L,t),p?x(q):l}function m(q){var En=q-c,Hn=q-_,tl=t-En;return v?Y(tl,f-Hn):tl}function I(q){var En=q-c,Hn=q-_;return c===o||En>=t||En<0||v&&Hn>=f}function L(){var q=Kr();if(I(q))return O(q);s=Vt(L,m(q))}function O(q){return s=o,d&&e?x(q):(e=i=o,l)}function ln(){s!==o&&zu(s),_=0,e=c=i=s=o}function V(){return s===o?l:O(Kr())}function on(){var q=Kr(),En=I(q);if(e=arguments,i=this,c=q,En){if(s===o)return R(c);if(v)return zu(s),s=Vt(L,t),x(c)}return s===o&&(s=Vt(L,t)),l}return on.cancel=ln,on.flush=V,on}var Eh=y(function(n,t){return Eu(n,1,t)}),Th=y(function(n,t,r){return Eu(n,wn(t)||0,r)});function mh(n){return Un(n,jr)}function $r(n,t){if(typeof n!="function"||t!=null&&typeof t!="function")throw new gn(sn);var r=function(){var e=arguments,i=t?t.apply(this,e):e[0],f=r.cache;if(f.has(i))return f.get(i);var l=n.apply(this,e);return r.cache=f.set(i,l)||f,l};return r.cache=new($r.Cache||bn),r}$r.Cache=bn;function zr(n){if(typeof n!="function")throw new gn(sn);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function yh(n){return Pf(2,n)}var Lh=_a(function(n,t){t=t.length==1&&E(t[0])?D(t[0],en(A())):D(Z(t,1),en(A()));var r=t.length;return y(function(e){for(var i=-1,f=Y(e.length,r);++i=t}),st=Cu(function(){return arguments}())?Cu:function(n){return G(n)&&b.call(n,"callee")&&!pu.call(n,"callee")},E=h.isArray,Kh=Qi?en(Qi):Vs;function j(n){return n!=null&&Zr(n.length)&&!Nn(n)}function H(n){return G(n)&&j(n)}function $h(n){return n===!0||n===!1||G(n)&&J(n)==Wt}var kn=is||Ai,zh=Vi?en(Vi):ks;function Zh(n){return G(n)&&n.nodeType===1&&!kt(n)}function Yh(n){if(n==null)return!0;if(j(n)&&(E(n)||typeof n=="string"||typeof n.splice=="function"||kn(n)||Lt(n)||st(n)))return!n.length;var t=X(n);if(t==xn||t==An)return!n.size;if(Qt(n))return!Me(n).length;for(var r in n)if(b.call(n,r))return!1;return!0}function Xh(n,t){return Yt(n,t)}function Jh(n,t,r){r=typeof r=="function"?r:o;var e=r?r(n,t):o;return e===o?Yt(n,t,o,r):!!e}function ai(n){if(!G(n))return!1;var t=J(n);return t==ir||t==dl||typeof n.message=="string"&&typeof n.name=="string"&&!kt(n)}function Qh(n){return typeof n=="number"&&du(n)}function Nn(n){if(!N(n))return!1;var t=J(n);return t==ur||t==Ei||t==vl||t==xl}function Mf(n){return typeof n=="number"&&n==T(n)}function Zr(n){return typeof n=="number"&&n>-1&&n%1==0&&n<=Kn}function N(n){var t=typeof n;return n!=null&&(t=="object"||t=="function")}function G(n){return n!=null&&typeof n=="object"}var Nf=ki?en(ki):na;function Vh(n,t){return n===t||De(n,t,ni(t))}function kh(n,t,r){return r=typeof r=="function"?r:o,De(n,t,ni(t),r)}function jh(n){return Gf(n)&&n!=+n}function ng(n){if(Da(n))throw new S(el);return Ou(n)}function tg(n){return n===null}function rg(n){return n==null}function Gf(n){return typeof n=="number"||G(n)&&J(n)==Bt}function kt(n){if(!G(n)||J(n)!=Pn)return!1;var t=xr(n);if(t===null)return!0;var r=b.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&pr.call(r)==ko}var ci=ji?en(ji):ta;function eg(n){return Mf(n)&&n>=-Kn&&n<=Kn}var Hf=nu?en(nu):ra;function Yr(n){return typeof n=="string"||!E(n)&&G(n)&&J(n)==Ft}function fn(n){return typeof n=="symbol"||G(n)&&J(n)==fr}var Lt=tu?en(tu):ea;function ig(n){return n===o}function ug(n){return G(n)&&X(n)==Ut}function fg(n){return G(n)&&J(n)==Rl}var lg=Dr(Ne),og=Dr(function(n,t){return n<=t});function qf(n){if(!n)return[];if(j(n))return Yr(n)?Rn(n):k(n);if(Nt&&n[Nt])return Go(n[Nt]());var t=X(n),r=t==xn?me:t==An?hr:Ct;return r(n)}function Gn(n){if(!n)return n===0?n:0;if(n=wn(n),n===nt||n===-nt){var t=n<0?-1:1;return t*hl}return n===n?n:0}function T(n){var t=Gn(n),r=t%1;return t===t?r?t-r:t:0}function Kf(n){return n?ut(T(n),0,yn):0}function wn(n){if(typeof n=="number")return n;if(fn(n))return rr;if(N(n)){var t=typeof n.valueOf=="function"?n.valueOf():n;n=N(t)?t+"":t}if(typeof n!="string")return n===0?n:+n;n=lu(n);var r=ql.test(n);return r||$l.test(n)?So(n.slice(2),r?2:8):Hl.test(n)?rr:+n}function $f(n){return Cn(n,nn(n))}function sg(n){return n?ut(T(n),-Kn,Kn):n===0?n:0}function B(n){return n==null?"":un(n)}var ag=Tt(function(n,t){if(Qt(t)||j(t)){Cn(t,$(t),n);return}for(var r in t)b.call(t,r)&&$t(n,r,t[r])}),zf=Tt(function(n,t){Cn(t,nn(t),n)}),Xr=Tt(function(n,t,r,e){Cn(t,nn(t),n,e)}),cg=Tt(function(n,t,r,e){Cn(t,$(t),n,e)}),hg=Dn(Pe);function gg(n,t){var r=Et(n);return t==null?r:Iu(r,t)}var _g=y(function(n,t){n=P(n);var r=-1,e=t.length,i=e>2?t[2]:o;for(i&&Q(t[0],t[1],i)&&(e=1);++r1),f}),Cn(n,ke(n),r),e&&(r=pn(r,qn|Ri|at,Ta));for(var i=t.length;i--;)$e(r,t[i]);return r});function Pg(n,t){return Yf(n,zr(A(t)))}var Bg=Dn(function(n,t){return n==null?{}:fa(n,t)});function Yf(n,t){if(n==null)return{};var r=D(ke(n),function(e){return[e]});return t=A(t),Du(n,r,function(e,i){return t(e,i[0])})}function bg(n,t,r){t=Qn(t,n);var e=-1,i=t.length;for(i||(i=1,n=o);++et){var e=n;n=t,t=e}if(r||n%1||t%1){var i=wu();return Y(n+i*(t-n+Io("1e-"+((i+"").length-1))),t)}return He(n,t)}var zg=mt(function(n,t,r){return t=t.toLowerCase(),n+(r?Qf(t):t)});function Qf(n){return _i(B(n).toLowerCase())}function Vf(n){return n=B(n),n&&n.replace(Zl,Fo).replace(co,"")}function Zg(n,t,r){n=B(n),t=un(t);var e=n.length;r=r===o?e:ut(T(r),0,e);var i=r;return r-=t.length,r>=0&&n.slice(r,i)==t}function Yg(n){return n=B(n),n&&ml.test(n)?n.replace(yi,Uo):n}function Xg(n){return n=B(n),n&&Pl.test(n)?n.replace(se,"\\$&"):n}var Jg=mt(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Qg=mt(function(n,t,r){return n+(r?" ":"")+t.toLowerCase()}),Vg=ju("toLowerCase");function kg(n,t,r){n=B(n),t=T(t);var e=t?xt(n):0;if(!t||e>=t)return n;var i=(t-e)/2;return Ur(Sr(i),r)+n+Ur(Ir(i),r)}function jg(n,t,r){n=B(n),t=T(t);var e=t?xt(n):0;return t&&e>>0,r?(n=B(n),n&&(typeof t=="string"||t!=null&&!ci(t))&&(t=un(t),!t&&wt(n))?Vn(Rn(n),0,r):n.split(t,r)):[]}var f_=mt(function(n,t,r){return n+(r?" ":"")+_i(t)});function l_(n,t,r){return n=B(n),r=r==null?0:ut(T(r),0,n.length),t=un(t),n.slice(r,r+t.length)==t}function o_(n,t,r){var e=u.templateSettings;r&&Q(n,t,r)&&(t=o),n=B(n),t=Xr({},t,e,lf);var i=Xr({},t.imports,e.imports,lf),f=$(i),l=Te(i,f),s,c,_=0,p=t.interpolate||lr,v="__p += '",d=ye((t.escape||lr).source+"|"+p.source+"|"+(p===Li?Gl:lr).source+"|"+(t.evaluate||lr).source+"|$","g"),x="//# sourceURL="+(b.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++vo+"]")+` +`;n.replace(d,function(I,L,O,ln,V,on){return O||(O=ln),v+=n.slice(_,on).replace(Yl,Do),L&&(s=!0,v+=`' + +__e(`+L+`) + +'`),V&&(c=!0,v+=`'; +`+V+`; +__p += '`),O&&(v+=`' + +((__t = (`+O+`)) == null ? '' : __t) + +'`),_=on+I.length,I}),v+=`'; +`;var R=b.call(t,"variable")&&t.variable;if(!R)v=`with (obj) { +`+v+` +} +`;else if(Ml.test(R))throw new S(il);v=(c?v.replace(Il,""):v).replace(Sl,"$1").replace(El,"$1;"),v="function("+(R||"obj")+`) { +`+(R?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(s?", __e = _.escape":"")+(c?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+v+`return __p +}`;var m=jf(function(){return W(f,x+"return "+v).apply(o,l)});if(m.source=v,ai(m))throw m;return m}function s_(n){return B(n).toLowerCase()}function a_(n){return B(n).toUpperCase()}function c_(n,t,r){if(n=B(n),n&&(r||t===o))return lu(n);if(!n||!(t=un(t)))return n;var e=Rn(n),i=Rn(t),f=ou(e,i),l=su(e,i)+1;return Vn(e,f,l).join("")}function h_(n,t,r){if(n=B(n),n&&(r||t===o))return n.slice(0,cu(n)+1);if(!n||!(t=un(t)))return n;var e=Rn(n),i=su(e,Rn(t))+1;return Vn(e,0,i).join("")}function g_(n,t,r){if(n=B(n),n&&(r||t===o))return n.replace(ae,"");if(!n||!(t=un(t)))return n;var e=Rn(n),i=ou(e,Rn(t));return Vn(e,i).join("")}function __(n,t){var r=fl,e=ll;if(N(t)){var i="separator"in t?t.separator:i;r="length"in t?T(t.length):r,e="omission"in t?un(t.omission):e}n=B(n);var f=n.length;if(wt(n)){var l=Rn(n);f=l.length}if(r>=f)return n;var s=r-xt(e);if(s<1)return e;var c=l?Vn(l,0,s).join(""):n.slice(0,s);if(i===o)return c+e;if(l&&(s+=c.length-s),ci(i)){if(n.slice(s).search(i)){var _,p=c;for(i.global||(i=ye(i.source,B(Ci.exec(i))+"g")),i.lastIndex=0;_=i.exec(p);)var v=_.index;c=c.slice(0,v===o?s:v)}}else if(n.indexOf(un(i),s)!=s){var d=c.lastIndexOf(i);d>-1&&(c=c.slice(0,d))}return c+e}function p_(n){return n=B(n),n&&Tl.test(n)?n.replace(mi,$o):n}var v_=mt(function(n,t,r){return n+(r?" ":"")+t.toUpperCase()}),_i=ju("toUpperCase");function kf(n,t,r){return n=B(n),t=r?o:t,t===o?No(n)?Yo(n):Oo(n):n.match(t)||[]}var jf=y(function(n,t){try{return rn(n,o,t)}catch(r){return ai(r)?r:new S(r)}}),d_=Dn(function(n,t){return hn(t,function(r){r=On(r),Fn(n,r,oi(n[r],n))}),n});function w_(n){var t=n==null?0:n.length,r=A();return n=t?D(n,function(e){if(typeof e[1]!="function")throw new gn(sn);return[r(e[0]),e[1]]}):[],y(function(e){for(var i=-1;++iKn)return[];var r=yn,e=Y(n,yn);t=A(t),n-=yn;for(var i=Ee(e,t);++r0||t<0)?new C(r):(n<0?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==o&&(t=T(t),r=t<0?r.dropRight(-t):r.take(t-n)),r)},C.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},C.prototype.toArray=function(){return this.take(yn)},Ln(C.prototype,function(n,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),e=/^(?:head|last)$/.test(t),i=u[e?"take"+(t=="last"?"Right":""):t],f=e||/^find/.test(t);!i||(u.prototype[t]=function(){var l=this.__wrapped__,s=e?[1]:arguments,c=l instanceof C,_=s[0],p=c||E(l),v=function(L){var O=i.apply(u,zn([L],s));return e&&d?O[0]:O};p&&r&&typeof _=="function"&&_.length!=1&&(c=p=!1);var d=this.__chain__,x=!!this.__actions__.length,R=f&&!d,m=c&&!x;if(!f&&p){l=m?l:new C(this);var I=n.apply(l,s);return I.__actions__.push({func:Hr,args:[v],thisArg:o}),new _n(I,d)}return R&&m?n.apply(this,s):(I=this.thru(v),R?e?I.value()[0]:I.value():I)})}),hn(["pop","push","shift","sort","splice","unshift"],function(n){var t=gr[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);u.prototype[n]=function(){var i=arguments;if(e&&!this.__chain__){var f=this.value();return t.apply(E(f)?f:[],i)}return this[r](function(l){return t.apply(E(l)?l:[],i)})}}),Ln(C.prototype,function(n,t){var r=u[t];if(r){var e=r.name+"";b.call(St,e)||(St[e]=[]),St[e].push({name:t,func:r})}}),St[br(o,jn).name]=[{name:"wrapper",func:o}],C.prototype.clone=ps,C.prototype.reverse=vs,C.prototype.value=ds,u.prototype.at=Zc,u.prototype.chain=Yc,u.prototype.commit=Xc,u.prototype.next=Jc,u.prototype.plant=Vc,u.prototype.reverse=kc,u.prototype.toJSON=u.prototype.valueOf=u.prototype.value=jc,u.prototype.first=u.prototype.head,Nt&&(u.prototype[Nt]=Qc),u},At=Xo();tt?((tt.exports=At)._=At,ve._=At):z._=At}).call(jt)}),ip=ep.isArray;export{ip as isArray}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/compact.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/compact.js new file mode 100644 index 0000000000000000000000000000000000000000..7287cda6af5ecfb9d42d7603578ae133683c2bfe --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/compact.js @@ -0,0 +1 @@ +function o(e){for(var t=-1,c=e==null?0:e.length,i=0,n=[];++t1?n[f-1]:void 0,s=f>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(f--,o):void 0,s&&J(n[0],n[1],s)&&(o=f<3?void 0:o,f=1),r=Object(r);++to}var s=t;function a(m,o){return m&&m.length?e(m,r(o),s):void 0}var c=a;export default c; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/minBy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/minBy.js new file mode 100644 index 0000000000000000000000000000000000000000..9c7dba59e18ed5e975d1c81c17cb2cef0aef2712 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/minBy.js @@ -0,0 +1 @@ +import{_ as e}from"../common/_baseExtremum-a4d779f6.js";import{_ as r}from"../common/_baseIteratee-ed511428.js";import"../common/isSymbol-cf06cd7f.js";import"../common/_baseGetTag-3262967e.js";import"../common/_commonjsHelpers-b3efd043.js";import"../common/isObjectLike-0219adc7.js";import"../common/_arrayLikeKeys-a1c01456.js";import"../common/_MapCache-c4ecbe9d.js";import"../common/_getNative-f6f203b5.js";import"../common/isObject-d5e189f7.js";import"../common/_Map-e270ea77.js";import"../common/_baseTimes-d6ede5f1.js";import"../common/_overArg-78664c5e.js";import"../common/isArrayLike-4a96f864.js";import"../common/_baseUnary-52d6173a.js";import"../common/isArray-1ab33e59.js";import"../common/_baseIsEqual-b23e7931.js";import"../common/_cacheHas-57850b8b.js";import"../common/_setToArray-57c49479.js";import"../common/_arrayFilter-5e37ed84.js";import"../common/_getTag-45fd9209.js";import"../common/_Set-7b0a30a4.js";import"../common/toString-31cf0354.js";import"../common/_arrayMap-c3125c3a.js";import"../common/identity-2f636783.js";import"../common/_baseProperty-004d0139.js";function t(m,o){return m0&&o(s)?r>1?g(s,r-1,o,a,i):u(i,s):a||(i[i.length]=s)}return i}var h=g;function w(n,r){var o=-1,a=C(n)?Array(n.length):[];return B(n,function(i,m,c){a[++o]=r(i,m,c)}),a}var E=w;function P(n,r){var o=n.length;for(n.sort(r);o--;)n[o]=n[o].value;return n}var x=P;function G(n,r){if(n!==r){var o=n!==void 0,a=n===null,i=n===n,m=b(n),c=r!==void 0,s=r===null,t=r===r,f=b(r);if(!s&&!f&&!m&&n>r||m&&c&&t&&!s&&!f||a&&c&&t||!o&&t||!i)return 1;if(!a&&!m&&!f&&n=s)return t;var f=o[a];return t*(f=="desc"?-1:1)}}return n.index-r.index}var U=S;function q(n,r,o){r.length?r=_(r,function(m){return p(m)?function(c){return A(c,m.length===1?m[0]:m)}:m}):r=[k];var a=-1;r=_(r,F(M));var i=E(n,function(m,c,s){var t=_(r,function(f){return f(m)});return{criteria:t,index:++a,value:m}});return x(i,function(m,c){return U(m,c,o)})}var K=q,z=L(function(n,r){if(n==null)return[];var o=r.length;return o>1&&j(n,r[0],r[1])?r=[]:o>2&&j(r[0],r[1],r[2])&&(r=[r[0]]),K(n,h(r,1),[])}),J=z;export default J; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/throttle.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/throttle.js new file mode 100644 index 0000000000000000000000000000000000000000..98c269ba9c06409bbd77d2f3944d3c8877355c21 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/throttle.js @@ -0,0 +1 @@ +import{d as m}from"../common/debounce-f81279fe.js";import{i as n}from"../common/isObject-d5e189f7.js";import"../common/_baseGetTag-3262967e.js";import"../common/_commonjsHelpers-b3efd043.js";import"../common/isSymbol-cf06cd7f.js";import"../common/isObjectLike-0219adc7.js";var a="Expected a function";function c(t,o,e){var i=!0,r=!0;if(typeof t!="function")throw new TypeError(a);return n(e)&&(i="leading"in e?!!e.leading:i,r="trailing"in e?!!e.trailing:r),m(t,o,{leading:i,maxWait:o,trailing:r})}var f=c;export default f; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniq.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniq.js new file mode 100644 index 0000000000000000000000000000000000000000..05cbf58be43d7617620b410f04f6b04b7d436ac8 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniq.js @@ -0,0 +1 @@ +import{_ as m}from"../common/_baseUniq-263b880d.js";import"../common/_cacheHas-57850b8b.js";import"../common/_MapCache-c4ecbe9d.js";import"../common/_getNative-f6f203b5.js";import"../common/_baseGetTag-3262967e.js";import"../common/_commonjsHelpers-b3efd043.js";import"../common/isObject-d5e189f7.js";import"../common/_Map-e270ea77.js";import"../common/_arrayIncludesWith-183ddfd7.js";import"../common/_Set-7b0a30a4.js";import"../common/_setToArray-57c49479.js";function e(o){return o&&o.length?m(o):[]}var t=e;export default t; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniqBy.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniqBy.js new file mode 100644 index 0000000000000000000000000000000000000000..275bbe681d424984f06d340b19eb00bcdf9b1283 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/uniqBy.js @@ -0,0 +1 @@ +import{_ as e}from"../common/_baseIteratee-ed511428.js";import{_ as r}from"../common/_baseUniq-263b880d.js";import"../common/_arrayLikeKeys-a1c01456.js";import"../common/_MapCache-c4ecbe9d.js";import"../common/_getNative-f6f203b5.js";import"../common/_baseGetTag-3262967e.js";import"../common/_commonjsHelpers-b3efd043.js";import"../common/isObject-d5e189f7.js";import"../common/_Map-e270ea77.js";import"../common/_baseTimes-d6ede5f1.js";import"../common/_overArg-78664c5e.js";import"../common/isObjectLike-0219adc7.js";import"../common/isArrayLike-4a96f864.js";import"../common/_baseUnary-52d6173a.js";import"../common/isArray-1ab33e59.js";import"../common/_baseIsEqual-b23e7931.js";import"../common/_cacheHas-57850b8b.js";import"../common/_setToArray-57c49479.js";import"../common/_arrayFilter-5e37ed84.js";import"../common/_getTag-45fd9209.js";import"../common/_Set-7b0a30a4.js";import"../common/isSymbol-cf06cd7f.js";import"../common/toString-31cf0354.js";import"../common/_arrayMap-c3125c3a.js";import"../common/identity-2f636783.js";import"../common/_baseProperty-004d0139.js";import"../common/_arrayIncludesWith-183ddfd7.js";function s(o,m){return o&&o.length?r(o,e(m)):[]}var t=s;export default t; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/without.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/without.js new file mode 100644 index 0000000000000000000000000000000000000000..e84b65de07685af1c964f23ecdead0b0081224c4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/lodash/without.js @@ -0,0 +1 @@ +import{_ as p,a as h}from"../common/_cacheHas-57850b8b.js";import{a as b,_ as d}from"../common/_arrayIncludesWith-183ddfd7.js";import{_ as y}from"../common/_arrayMap-c3125c3a.js";import{_ as g}from"../common/_baseUnary-52d6173a.js";import{_ as l}from"../common/_baseRest-55af4356.js";import{i as A}from"../common/isArrayLikeObject-e565c37f.js";import"../common/_MapCache-c4ecbe9d.js";import"../common/_getNative-f6f203b5.js";import"../common/_baseGetTag-3262967e.js";import"../common/_commonjsHelpers-b3efd043.js";import"../common/isObject-d5e189f7.js";import"../common/_Map-e270ea77.js";import"../common/identity-2f636783.js";import"../common/_defineProperty-704c6f11.js";import"../common/isArrayLike-4a96f864.js";import"../common/isObjectLike-0219adc7.js";var L=200;function w(r,o,i,n){var a=-1,t=b,c=!0,f=r.length,s=[],j=o.length;if(!f)return s;i&&(o=y(o,g(i))),n?(t=d,c=!1):o.length>=L&&(t=h,c=!1,o=new p(o));o:for(;++a=0;n--){var p=a[n];p==="."?a.splice(n,1):p===".."?(a.splice(n,1),i++):i&&(a.splice(n,1),i--)}if(e)for(;i--;i)a.unshift("..");return a}var S=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,h=function(a){return S.exec(a).slice(1)};function b(){for(var a="",e=!1,i=arguments.length-1;i>=-1&&!e;i--){var n=i>=0?arguments[i]:"/";if(typeof n!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!n)continue;a=n+"/"+a,e=n.charAt(0)==="/"}return a=T(j(a.split("/"),function(p){return!!p}),!e).join("/"),(e?"/":"")+a||"."}function w(a){var e=k(a),i=N(a,-1)==="/";return a=T(j(a.split("/"),function(n){return!!n}),!e).join("/"),!a&&!e&&(a="."),a&&i&&(a+="/"),(e?"/":"")+a}function k(a){return a.charAt(0)==="/"}function U(){var a=Array.prototype.slice.call(arguments,0);return w(j(a,function(e,i){if(typeof e!="string")throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))}function F(a,e){a=b(a).substr(1),e=b(e).substr(1);function i(r){for(var o=0;o=0&&r[s]==="";s--);return o>s?[]:r.slice(o,s-o+1)}for(var n=i(a.split("/")),p=i(e.split("/")),u=Math.min(n.length,p.length),m=u,t=0;tq||z===q&&s[x].substr(0,12)==="application/"))continue}s[x]=f}}})}});export default X; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/moment.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/moment.js new file mode 100644 index 0000000000000000000000000000000000000000..9818d71e059ce21f8992a392f330615ee3354a46 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/moment.js @@ -0,0 +1,10 @@ +//! moment.js +//! version : 2.29.1 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com +var Ot;function l(){return Ot.apply(null,arguments)}function Ds(e){Ot=e}function F(e){return e instanceof Array||Object.prototype.toString.call(e)==="[object Array]"}function se(e){return e!=null&&Object.prototype.toString.call(e)==="[object Object]"}function y(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Be(e){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(e).length===0;var t;for(t in e)if(y(e,t))return!1;return!0}function b(e){return e===void 0}function j(e){return typeof e=="number"||Object.prototype.toString.call(e)==="[object Number]"}function _e(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function Tt(e,t){var s=[],r;for(r=0;r>>0,r;for(r=0;r0)for(s=0;s=0;return(n?s?"+":"":"-")+Math.pow(10,Math.max(0,a)).toString().substr(1)+r}var rt=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Oe=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,at={},ie={};function d(e,t,s,r){var a=r;typeof r=="string"&&(a=function(){return this[r]()}),e&&(ie[e]=a),t&&(ie[t[0]]=function(){return A(a.apply(this,arguments),t[1],t[2])}),s&&(ie[s]=function(){return this.localeData().ordinal(a.apply(this,arguments),e)})}function Os(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function Ts(e){var t=e.match(rt),s,r;for(s=0,r=t.length;s=0&&Oe.test(e);)e=e.replace(Oe,r),Oe.lastIndex=0,s-=1;return e}var bs={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function xs(e){var t=this._longDateFormat[e],s=this._longDateFormat[e.toUpperCase()];return t||!s?t:(this._longDateFormat[e]=s.match(rt).map(function(r){return r==="MMMM"||r==="MM"||r==="DD"||r==="dddd"?r.slice(1):r}).join(""),this._longDateFormat[e])}var Ws="Invalid date";function Ns(){return this._invalidDate}var Ps="%d",Rs=/\d{1,2}/;function Fs(e){return this._ordinal.replace("%d",e)}var Is={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function Cs(e,t,s,r){var a=this._relativeTime[s];return H(a)?a(e,t,s,r):a.replace(/%d/i,e)}function Us(e,t){var s=this._relativeTime[e>0?"future":"past"];return H(s)?s(t):s.replace(/%s/i,t)}var ye={};function p(e,t){var s=e.toLowerCase();ye[s]=ye[s+"s"]=ye[t]=e}function P(e){return typeof e=="string"?ye[e]||ye[e.toLowerCase()]:void 0}function nt(e){var t={},s,r;for(r in e)y(e,r)&&(s=P(r),s&&(t[s]=e[r]));return t}var Pt={};function O(e,t){Pt[e]=t}function Ls(e){var t=[],s;for(s in e)y(e,s)&&t.push({unit:s,priority:Pt[s]});return t.sort(function(r,a){return r.priority-a.priority}),t}function be(e){return e%4==0&&e%100!=0||e%400==0}function R(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function c(e){var t=+e,s=0;return t!==0&&isFinite(t)&&(s=R(t)),s}function oe(e,t){return function(s){return s!=null?(Rt(this,e,s),l.updateOffset(this,t),this):xe(this,e)}}function xe(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function Rt(e,t,s){e.isValid()&&!isNaN(s)&&(t==="FullYear"&&be(e.year())&&e.month()===1&&e.date()===29?(s=c(s),e._d["set"+(e._isUTC?"UTC":"")+t](s,e.month(),Ce(s,e.month()))):e._d["set"+(e._isUTC?"UTC":"")+t](s))}function Es(e){return e=P(e),H(this[e])?this[e]():this}function Hs(e,t){if(typeof e=="object"){e=nt(e);var s=Ls(e),r;for(r=0;r68?1900:2e3)};var Gt=oe("FullYear",!0);function nr(){return be(this.year())}function ir(e,t,s,r,a,n,i){var h;return e<100&&e>=0?(h=new Date(e+400,t,s,r,a,n,i),isFinite(h.getFullYear())&&h.setFullYear(e)):h=new Date(e,t,s,r,a,n,i),h}function Me(e){var t,s;return e<100&&e>=0?(s=Array.prototype.slice.call(arguments),s[0]=e+400,t=new Date(Date.UTC.apply(null,s)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Ue(e,t,s){var r=7+t-s,a=(7+Me(e,0,r).getUTCDay()-t)%7;return-a+r-1}function jt(e,t,s,r,a){var n=(7+s-r)%7,i=Ue(e,r,a),h=1+7*(t-1)+n+i,_,k;return h<=0?(_=e-1,k=ke(_)+h):h>ke(e)?(_=e+1,k=h-ke(e)):(_=e,k=h),{year:_,dayOfYear:k}}function De(e,t,s){var r=Ue(e.year(),t,s),a=Math.floor((e.dayOfYear()-r-1)/7)+1,n,i;return a<1?(i=e.year()-1,n=a+$(i,t,s)):a>$(e.year(),t,s)?(n=a-$(e.year(),t,s),i=e.year()+1):(i=e.year(),n=a),{week:n,year:i}}function $(e,t,s){var r=Ue(e,t,s),a=Ue(e+1,t,s);return(ke(e)-r+a)/7}d("w",["ww",2],"wo","week"),d("W",["WW",2],"Wo","isoWeek"),p("week","w"),p("isoWeek","W"),O("week",5),O("isoWeek",5),u("w",M),u("ww",M,x),u("W",M),u("WW",M,x),Se(["w","ww","W","WW"],function(e,t,s,r){t[r.substr(0,1)]=c(e)});function or(e){return De(e,this._week.dow,this._week.doy).week}var lr={dow:0,doy:6};function ur(){return this._week.dow}function dr(){return this._week.doy}function hr(e){var t=this.localeData().week(this);return e==null?t:this.add((e-t)*7,"d")}function fr(e){var t=De(this,1,4).week;return e==null?t:this.add((e-t)*7,"d")}d("d",0,"do","day"),d("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),d("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),d("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),d("e",0,0,"weekday"),d("E",0,0,"isoWeekday"),p("day","d"),p("weekday","e"),p("isoWeekday","E"),O("day",11),O("weekday",11),O("isoWeekday",11),u("d",M),u("e",M),u("E",M),u("dd",function(e,t){return t.weekdaysMinRegex(e)}),u("ddd",function(e,t){return t.weekdaysShortRegex(e)}),u("dddd",function(e,t){return t.weekdaysRegex(e)}),Se(["dd","ddd","dddd"],function(e,t,s,r){var a=s._locale.weekdaysParse(e,r,s._strict);a!=null?t.d=a:f(s).invalidWeekday=e}),Se(["d","e","E"],function(e,t,s,r){t[r]=c(e)});function cr(e,t){return typeof e!="string"?e:isNaN(e)?(e=t.weekdaysParse(e),typeof e=="number"?e:null):parseInt(e,10)}function _r(e,t){return typeof e=="string"?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function ut(e,t){return e.slice(t,7).concat(e.slice(0,t))}var mr="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),zt="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),yr="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),wr=we,Sr=we,kr=we;function Mr(e,t){var s=F(this._weekdays)?this._weekdays:this._weekdays[e&&e!==!0&&this._weekdays.isFormat.test(t)?"format":"standalone"];return e===!0?ut(s,this._week.dow):e?s[e.day()]:s}function Dr(e){return e===!0?ut(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function gr(e){return e===!0?ut(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function vr(e,t,s){var r,a,n,i=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)n=E([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(n,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(n,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(n,"").toLocaleLowerCase();return s?t==="dddd"?(a=v.call(this._weekdaysParse,i),a!==-1?a:null):t==="ddd"?(a=v.call(this._shortWeekdaysParse,i),a!==-1?a:null):(a=v.call(this._minWeekdaysParse,i),a!==-1?a:null):t==="dddd"?(a=v.call(this._weekdaysParse,i),a!==-1||(a=v.call(this._shortWeekdaysParse,i),a!==-1)?a:(a=v.call(this._minWeekdaysParse,i),a!==-1?a:null)):t==="ddd"?(a=v.call(this._shortWeekdaysParse,i),a!==-1||(a=v.call(this._weekdaysParse,i),a!==-1)?a:(a=v.call(this._minWeekdaysParse,i),a!==-1?a:null)):(a=v.call(this._minWeekdaysParse,i),a!==-1||(a=v.call(this._weekdaysParse,i),a!==-1)?a:(a=v.call(this._shortWeekdaysParse,i),a!==-1?a:null))}function Yr(e,t,s){var r,a,n;if(this._weekdaysParseExact)return vr.call(this,e,t,s);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(a=E([2e3,1]).day(r),s&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(a,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(a,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(a,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(n="^"+this.weekdays(a,"")+"|^"+this.weekdaysShort(a,"")+"|^"+this.weekdaysMin(a,""),this._weekdaysParse[r]=new RegExp(n.replace(".",""),"i")),s&&t==="dddd"&&this._fullWeekdaysParse[r].test(e))return r;if(s&&t==="ddd"&&this._shortWeekdaysParse[r].test(e))return r;if(s&&t==="dd"&&this._minWeekdaysParse[r].test(e))return r;if(!s&&this._weekdaysParse[r].test(e))return r}}function pr(e){if(!this.isValid())return e!=null?this:NaN;var t=this._isUTC?this._d.getUTCDay():this._d.getDay();return e!=null?(e=cr(e,this.localeData()),this.add(e-t,"d")):t}function Or(e){if(!this.isValid())return e!=null?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return e==null?t:this.add(e-t,"d")}function Tr(e){if(!this.isValid())return e!=null?this:NaN;if(e!=null){var t=_r(e,this.localeData());return this.day(this.day()%7?t:t-7)}else return this.day()||7}function br(e){return this._weekdaysParseExact?(y(this,"_weekdaysRegex")||dt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(y(this,"_weekdaysRegex")||(this._weekdaysRegex=wr),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function xr(e){return this._weekdaysParseExact?(y(this,"_weekdaysRegex")||dt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(y(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Sr),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Wr(e){return this._weekdaysParseExact?(y(this,"_weekdaysRegex")||dt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(y(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=kr),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function dt(){function e(L,G){return G.length-L.length}var t=[],s=[],r=[],a=[],n,i,h,_,k;for(n=0;n<7;n++)i=E([2e3,1]).day(n),h=W(this.weekdaysMin(i,"")),_=W(this.weekdaysShort(i,"")),k=W(this.weekdays(i,"")),t.push(h),s.push(_),r.push(k),a.push(h),a.push(_),a.push(k);t.sort(e),s.sort(e),r.sort(e),a.sort(e),this._weekdaysRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+t.join("|")+")","i")}function ht(){return this.hours()%12||12}function Nr(){return this.hours()||24}d("H",["HH",2],0,"hour"),d("h",["hh",2],0,ht),d("k",["kk",2],0,Nr),d("hmm",0,0,function(){return""+ht.apply(this)+A(this.minutes(),2)}),d("hmmss",0,0,function(){return""+ht.apply(this)+A(this.minutes(),2)+A(this.seconds(),2)}),d("Hmm",0,0,function(){return""+this.hours()+A(this.minutes(),2)}),d("Hmmss",0,0,function(){return""+this.hours()+A(this.minutes(),2)+A(this.seconds(),2)});function Zt(e,t){d(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}Zt("a",!0),Zt("A",!1),p("hour","h"),O("hour",13);function $t(e,t){return t._meridiemParse}u("a",$t),u("A",$t),u("H",M),u("h",M),u("k",M),u("HH",M,x),u("hh",M,x),u("kk",M,x),u("hmm",Ct),u("hmmss",Ut),u("Hmm",Ct),u("Hmmss",Ut),S(["H","HH"],Y),S(["k","kk"],function(e,t,s){var r=c(e);t[Y]=r===24?0:r}),S(["a","A"],function(e,t,s){s._isPm=s._locale.isPM(e),s._meridiem=e}),S(["h","hh"],function(e,t,s){t[Y]=c(e),f(s).bigHour=!0}),S("hmm",function(e,t,s){var r=e.length-2;t[Y]=c(e.substr(0,r)),t[C]=c(e.substr(r)),f(s).bigHour=!0}),S("hmmss",function(e,t,s){var r=e.length-4,a=e.length-2;t[Y]=c(e.substr(0,r)),t[C]=c(e.substr(r,2)),t[Z]=c(e.substr(a)),f(s).bigHour=!0}),S("Hmm",function(e,t,s){var r=e.length-2;t[Y]=c(e.substr(0,r)),t[C]=c(e.substr(r))}),S("Hmmss",function(e,t,s){var r=e.length-4,a=e.length-2;t[Y]=c(e.substr(0,r)),t[C]=c(e.substr(r,2)),t[Z]=c(e.substr(a))});function Pr(e){return(e+"").toLowerCase().charAt(0)==="p"}var Rr=/[ap]\.?m?\.?/i,Fr=oe("Hours",!0);function Ir(e,t,s){return e>11?s?"pm":"PM":s?"am":"AM"}var Bt={calendar:Ys,longDateFormat:bs,invalidDate:Ws,ordinal:Ps,dayOfMonthOrdinalParse:Rs,relativeTime:Is,months:qs,monthsShort:Lt,week:lr,weekdays:mr,weekdaysMin:yr,weekdaysShort:zt,meridiemParse:Rr},g={},ge={},ve;function Cr(e,t){var s,r=Math.min(e.length,t.length);for(s=0;s0;){if(a=Le(n.slice(0,s).join("-")),a)return a;if(r&&r.length>=s&&Cr(n,r)>=s-1)break;s--}t++}return ve}function Le(e){var t=null,s;if(g[e]===void 0&&typeof module!="undefined"&&module&&module.exports)try{t=ve._abbr,s=require,s("./locale/"+e),ee(t)}catch(r){g[e]=null}return g[e]}function ee(e,t){var s;return e&&(b(t)?s=B(e):s=ft(e,t),s?ve=s:typeof console!="undefined"&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ve._abbr}function ft(e,t){if(t!==null){var s,r=Bt;if(t.abbr=e,g[e]!=null)Wt("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),r=g[e]._config;else if(t.parentLocale!=null)if(g[t.parentLocale]!=null)r=g[t.parentLocale]._config;else if(s=Le(t.parentLocale),s!=null)r=s._config;else return ge[t.parentLocale]||(ge[t.parentLocale]=[]),ge[t.parentLocale].push({name:e,config:t}),null;return g[e]=new tt(et(r,t)),ge[e]&&ge[e].forEach(function(a){ft(a.name,a.config)}),ee(e),g[e]}else return delete g[e],null}function Lr(e,t){if(t!=null){var s,r,a=Bt;g[e]!=null&&g[e].parentLocale!=null?g[e].set(et(g[e]._config,t)):(r=Le(e),r!=null&&(a=r._config),t=et(a,t),r==null&&(t.abbr=e),s=new tt(t),s.parentLocale=g[e],g[e]=s),ee(e)}else g[e]!=null&&(g[e].parentLocale!=null?(g[e]=g[e].parentLocale,e===ee()&&ee(e)):g[e]!=null&&delete g[e]);return g[e]}function B(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ve;if(!F(e)){if(t=Le(e),t)return t;e=[e]}return Ur(e)}function Er(){return st(g)}function ct(e){var t,s=e._a;return s&&f(e).overflow===-2&&(t=s[z]<0||s[z]>11?z:s[V]<1||s[V]>Ce(s[T],s[z])?V:s[Y]<0||s[Y]>24||s[Y]===24&&(s[C]!==0||s[Z]!==0||s[re]!==0)?Y:s[C]<0||s[C]>59?C:s[Z]<0||s[Z]>59?Z:s[re]<0||s[re]>999?re:-1,f(e)._overflowDayOfYear&&(tV)&&(t=V),f(e)._overflowWeeks&&t===-1&&(t=Zs),f(e)._overflowWeekday&&t===-1&&(t=$s),f(e).overflow=t),e}var Hr=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Ar=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Vr=/Z|[+-]\d\d(?::?\d\d)?/,Ee=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],_t=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],Gr=/^\/?Date\((-?\d+)/i,jr=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,zr={UT:0,GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Jt(e){var t,s,r=e._i,a=Hr.exec(r)||Ar.exec(r),n,i,h,_;if(a){for(f(e).iso=!0,t=0,s=Ee.length;tke(i)||e._dayOfYear===0)&&(f(e)._overflowDayOfYear=!0),s=Me(i,0,e._dayOfYear),e._a[z]=s.getUTCMonth(),e._a[V]=s.getUTCDate()),t=0;t<3&&e._a[t]==null;++t)e._a[t]=r[t]=a[t];for(;t<7;t++)e._a[t]=r[t]=e._a[t]==null?t===2?1:0:e._a[t];e._a[Y]===24&&e._a[C]===0&&e._a[Z]===0&&e._a[re]===0&&(e._nextDay=!0,e._a[Y]=0),e._d=(e._useUTC?Me:ir).apply(null,r),n=e._useUTC?e._d.getUTCDay():e._d.getDay(),e._tzm!=null&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Y]=24),e._w&&typeof e._w.d!="undefined"&&e._w.d!==n&&(f(e).weekdayMismatch=!0)}}function Kr(e){var t,s,r,a,n,i,h,_,k;t=e._w,t.GG!=null||t.W!=null||t.E!=null?(n=1,i=4,s=ue(t.GG,e._a[T],De(D(),1,4).year),r=ue(t.W,1),a=ue(t.E,1),(a<1||a>7)&&(_=!0)):(n=e._locale._week.dow,i=e._locale._week.doy,k=De(D(),n,i),s=ue(t.gg,e._a[T],k.year),r=ue(t.w,k.week),t.d!=null?(a=t.d,(a<0||a>6)&&(_=!0)):t.e!=null?(a=t.e+n,(t.e<0||t.e>6)&&(_=!0)):a=n),r<1||r>$(s,n,i)?f(e)._overflowWeeks=!0:_!=null?f(e)._overflowWeekday=!0:(h=jt(s,r,a,n,i),e._a[T]=h.year,e._dayOfYear=h.dayOfYear)}l.ISO_8601=function(){},l.RFC_2822=function(){};function yt(e){if(e._f===l.ISO_8601){Jt(e);return}if(e._f===l.RFC_2822){Qt(e);return}e._a=[],f(e).empty=!0;var t=""+e._i,s,r,a,n,i,h=t.length,_=0,k;for(a=Nt(e._f,e._locale).match(rt)||[],s=0;s0&&f(e).unusedInput.push(i),t=t.slice(t.indexOf(r)+r.length),_+=r.length),ie[n]?(r?f(e).empty=!1:f(e).unusedTokens.push(n),zs(n,r,e)):e._strict&&!r&&f(e).unusedTokens.push(n);f(e).charsLeftOver=h-_,t.length>0&&f(e).unusedInput.push(t),e._a[Y]<=12&&f(e).bigHour===!0&&e._a[Y]>0&&(f(e).bigHour=void 0),f(e).parsedDateParts=e._a.slice(0),f(e).meridiem=e._meridiem,e._a[Y]=ea(e._locale,e._a[Y],e._meridiem),k=f(e).era,k!==null&&(e._a[T]=e._locale.erasConvertYear(k,e._a[T])),mt(e),ct(e)}function ea(e,t,s){var r;return s==null?t:e.meridiemHour!=null?e.meridiemHour(t,s):(e.isPM!=null&&(r=e.isPM(s),r&&t<12&&(t+=12),!r&&t===12&&(t=0)),t)}function ta(e){var t,s,r,a,n,i,h=!1;if(e._f.length===0){f(e).invalidFormat=!0,e._d=new Date(NaN);return}for(a=0;athis?this:e:pe()});function es(e,t){var s,r;if(t.length===1&&F(t[0])&&(t=t[0]),!t.length)return D();for(s=t[0],r=1;rthis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function ga(){if(!b(this._isDSTShifted))return this._isDSTShifted;var e={},t;return Ke(e,this),e=Xt(e),e._a?(t=e._isUTC?E(e._a):D(e._a),this._isDSTShifted=this.isValid()&&ca(e._a,t.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function va(){return this.isValid()?!this._isUTC:!1}function Ya(){return this.isValid()?this._isUTC:!1}function ss(){return this.isValid()?this._isUTC&&this._offset===0:!1}var pa=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Oa=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function U(e,t){var s=e,r=null,a,n,i;return Ae(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:j(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(r=pa.exec(e))?(a=r[1]==="-"?-1:1,s={y:0,d:c(r[V])*a,h:c(r[Y])*a,m:c(r[C])*a,s:c(r[Z])*a,ms:c(wt(r[re]*1e3))*a}):(r=Oa.exec(e))?(a=r[1]==="-"?-1:1,s={y:ae(r[2],a),M:ae(r[3],a),w:ae(r[4],a),d:ae(r[5],a),h:ae(r[6],a),m:ae(r[7],a),s:ae(r[8],a)}):s==null?s={}:typeof s=="object"&&("from"in s||"to"in s)&&(i=Ta(D(s.from),D(s.to)),s={},s.ms=i.milliseconds,s.M=i.months),n=new He(s),Ae(e)&&y(e,"_locale")&&(n._locale=e._locale),Ae(e)&&y(e,"_isValid")&&(n._isValid=e._isValid),n}U.fn=He.prototype,U.invalid=fa;function ae(e,t){var s=e&&parseFloat(e.replace(",","."));return(isNaN(s)?0:s)*t}function rs(e,t){var s={};return s.months=t.month()-e.month()+(t.year()-e.year())*12,e.clone().add(s.months,"M").isAfter(t)&&--s.months,s.milliseconds=+t-+e.clone().add(s.months,"M"),s}function Ta(e,t){var s;return e.isValid()&&t.isValid()?(t=kt(t,e),e.isBefore(t)?s=rs(e,t):(s=rs(t,e),s.milliseconds=-s.milliseconds,s.months=-s.months),s):{milliseconds:0,months:0}}function as(e,t){return function(s,r){var a,n;return r!==null&&!isNaN(+r)&&(Wt(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=s,s=r,r=n),a=U(s,r),ns(this,a,e),this}}function ns(e,t,s,r){var a=t._milliseconds,n=wt(t._days),i=wt(t._months);!e.isValid()||(r=r==null?!0:r,i&&Ht(e,xe(e,"Month")+i*s),n&&Rt(e,"Date",xe(e,"Date")+n*s),a&&e._d.setTime(e._d.valueOf()+a*s),r&&l.updateOffset(e,n||i))}var ba=as(1,"add"),xa=as(-1,"subtract");function is(e){return typeof e=="string"||e instanceof String}function Wa(e){return I(e)||_e(e)||is(e)||j(e)||Pa(e)||Na(e)||e===null||e===void 0}function Na(e){var t=se(e)&&!Be(e),s=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a,n;for(a=0;as.valueOf():s.valueOf()9999?Te(s,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):H(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",Te(s,"Z")):Te(s,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function Za(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="",s,r,a,n;return this.isLocal()||(e=this.utcOffset()===0?"moment.utc":"moment.parseZone",t="Z"),s="["+e+'("]',r=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",a="-MM-DD[T]HH:mm:ss.SSS",n=t+'[")]',this.format(s+r+a+n)}function $a(e){e||(e=this.isUtc()?l.defaultFormatUtc:l.defaultFormat);var t=Te(this,e);return this.localeData().postformat(t)}function Ba(e,t){return this.isValid()&&(I(e)&&e.isValid()||D(e).isValid())?U({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function qa(e){return this.from(D(),e)}function Ja(e,t){return this.isValid()&&(I(e)&&e.isValid()||D(e).isValid())?U({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function Qa(e){return this.to(D(),e)}function os(e){var t;return e===void 0?this._locale._abbr:(t=B(e),t!=null&&(this._locale=t),this)}var ls=N("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return e===void 0?this.localeData():this.locale(e)});function us(){return this._locale}var Ge=1e3,de=60*Ge,je=60*de,ds=(365*400+97)*24*je;function he(e,t){return(e%t+t)%t}function hs(e,t,s){return e<100&&e>=0?new Date(e+400,t,s)-ds:new Date(e,t,s).valueOf()}function fs(e,t,s){return e<100&&e>=0?Date.UTC(e+400,t,s)-ds:Date.UTC(e,t,s)}function Xa(e){var t,s;if(e=P(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(s=this._isUTC?fs:hs,e){case"year":t=s(this.year(),0,1);break;case"quarter":t=s(this.year(),this.month()-this.month()%3,1);break;case"month":t=s(this.year(),this.month(),1);break;case"week":t=s(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=s(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=s(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=he(t+(this._isUTC?0:this.utcOffset()*de),je);break;case"minute":t=this._d.valueOf(),t-=he(t,de);break;case"second":t=this._d.valueOf(),t-=he(t,Ge);break}return this._d.setTime(t),l.updateOffset(this,!0),this}function Ka(e){var t,s;if(e=P(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(s=this._isUTC?fs:hs,e){case"year":t=s(this.year()+1,0,1)-1;break;case"quarter":t=s(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=s(this.year(),this.month()+1,1)-1;break;case"week":t=s(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=s(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=s(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=je-he(t+(this._isUTC?0:this.utcOffset()*de),je)-1;break;case"minute":t=this._d.valueOf(),t+=de-he(t,de)-1;break;case"second":t=this._d.valueOf(),t+=Ge-he(t,Ge)-1;break}return this._d.setTime(t),l.updateOffset(this,!0),this}function en(){return this._d.valueOf()-(this._offset||0)*6e4}function tn(){return Math.floor(this.valueOf()/1e3)}function sn(){return new Date(this.valueOf())}function rn(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function an(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function nn(){return this.isValid()?this.toISOString():null}function on(){return Je(this)}function ln(){return K({},f(this))}function un(){return f(this).overflow}function dn(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}d("N",0,0,"eraAbbr"),d("NN",0,0,"eraAbbr"),d("NNN",0,0,"eraAbbr"),d("NNNN",0,0,"eraName"),d("NNNNN",0,0,"eraNarrow"),d("y",["y",1],"yo","eraYear"),d("y",["yy",2],0,"eraYear"),d("y",["yyy",3],0,"eraYear"),d("y",["yyyy",4],0,"eraYear"),u("N",Dt),u("NN",Dt),u("NNN",Dt),u("NNNN",Dn),u("NNNNN",gn),S(["N","NN","NNN","NNNN","NNNNN"],function(e,t,s,r){var a=s._locale.erasParse(e,r,s._strict);a?f(s).era=a:f(s).invalidEra=e}),u("y",le),u("yy",le),u("yyy",le),u("yyyy",le),u("yo",vn),S(["y","yy","yyy","yyyy"],T),S(["yo"],function(e,t,s,r){var a;s._locale._eraYearOrdinalRegex&&(a=e.match(s._locale._eraYearOrdinalRegex)),s._locale.eraYearOrdinalParse?t[T]=s._locale.eraYearOrdinalParse(e,a):t[T]=parseInt(e,10)});function hn(e,t){var s,r,a,n=this._eras||B("en")._eras;for(s=0,r=n.length;s=0)return n[r]}function cn(e,t){var s=e.since<=e.until?1:-1;return t===void 0?l(e.since).year():l(e.since).year()+(t-e.offset)*s}function _n(){var e,t,s,r=this.localeData().eras();for(e=0,t=r.length;en&&(t=n),Wn.call(this,e,t,s,r,a))}function Wn(e,t,s,r,a){var n=jt(e,t,s,r,a),i=Me(n.year,0,n.dayOfYear);return this.year(i.getUTCFullYear()),this.month(i.getUTCMonth()),this.date(i.getUTCDate()),this}d("Q",0,"Qo","quarter"),p("quarter","Q"),O("quarter",7),u("Q",Ft),S("Q",function(e,t){t[z]=(c(e)-1)*3});function Nn(e){return e==null?Math.ceil((this.month()+1)/3):this.month((e-1)*3+this.month()%3)}d("D",["DD",2],"Do","date"),p("date","D"),O("date",9),u("D",M),u("DD",M,x),u("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),S(["D","DD"],V),S("Do",function(e,t){t[V]=c(e.match(M)[0])});var _s=oe("Date",!0);d("DDD",["DDDD",3],"DDDo","dayOfYear"),p("dayOfYear","DDD"),O("dayOfYear",4),u("DDD",Ne),u("DDDD",It),S(["DDD","DDDD"],function(e,t,s){s._dayOfYear=c(e)});function Pn(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return e==null?t:this.add(e-t,"d")}d("m",["mm",2],0,"minute"),p("minute","m"),O("minute",14),u("m",M),u("mm",M,x),S(["m","mm"],C);var Rn=oe("Minutes",!1);d("s",["ss",2],0,"second"),p("second","s"),O("second",15),u("s",M),u("ss",M,x),S(["s","ss"],Z);var Fn=oe("Seconds",!1);d("S",0,0,function(){return~~(this.millisecond()/100)}),d(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),d(0,["SSS",3],0,"millisecond"),d(0,["SSSS",4],0,function(){return this.millisecond()*10}),d(0,["SSSSS",5],0,function(){return this.millisecond()*100}),d(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3}),d(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4}),d(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5}),d(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6}),p("millisecond","ms"),O("millisecond",16),u("S",Ne,Ft),u("SS",Ne,x),u("SSS",Ne,It);var te,ms;for(te="SSSS";te.length<=9;te+="S")u(te,le);function In(e,t){t[re]=c(("0."+e)*1e3)}for(te="S";te.length<=9;te+="S")S(te,In);ms=oe("Milliseconds",!1),d("z",0,0,"zoneAbbr"),d("zz",0,0,"zoneName");function Cn(){return this._isUTC?"UTC":""}function Un(){return this._isUTC?"Coordinated Universal Time":""}var o=me.prototype;o.add=ba,o.calendar=Ia,o.clone=Ca,o.diff=Ga,o.endOf=Ka,o.format=$a,o.from=Ba,o.fromNow=qa,o.to=Ja,o.toNow=Qa,o.get=Es,o.invalidAt=un,o.isAfter=Ua,o.isBefore=La,o.isBetween=Ea,o.isSame=Ha,o.isSameOrAfter=Aa,o.isSameOrBefore=Va,o.isValid=on,o.lang=ls,o.locale=os,o.localeData=us,o.max=ia,o.min=na,o.parsingFlags=ln,o.set=Hs,o.startOf=Xa,o.subtract=xa,o.toArray=rn,o.toObject=an,o.toDate=sn,o.toISOString=za,o.inspect=Za,typeof Symbol!="undefined"&&Symbol.for!=null&&(o[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),o.toJSON=nn,o.toString=ja,o.unix=tn,o.valueOf=en,o.creationData=dn,o.eraName=_n,o.eraNarrow=mn,o.eraAbbr=yn,o.eraYear=wn,o.year=Gt,o.isLeapYear=nr,o.weekYear=Yn,o.isoWeekYear=pn,o.quarter=o.quarters=Nn,o.month=At,o.daysInMonth=sr,o.week=o.weeks=hr,o.isoWeek=o.isoWeeks=fr,o.weeksInYear=bn,o.weeksInWeekYear=xn,o.isoWeeksInYear=On,o.isoWeeksInISOWeekYear=Tn,o.date=_s,o.day=o.days=pr,o.weekday=Or,o.isoWeekday=Tr,o.dayOfYear=Pn,o.hour=o.hours=Fr,o.minute=o.minutes=Rn,o.second=o.seconds=Fn,o.millisecond=o.milliseconds=ms,o.utcOffset=ma,o.utc=wa,o.local=Sa,o.parseZone=ka,o.hasAlignedHourOffset=Ma,o.isDST=Da,o.isLocal=va,o.isUtcOffset=Ya,o.isUtc=ss,o.isUTC=ss,o.zoneAbbr=Cn,o.zoneName=Un,o.dates=N("dates accessor is deprecated. Use date instead.",_s),o.months=N("months accessor is deprecated. Use month instead",At),o.years=N("years accessor is deprecated. Use year instead",Gt),o.zone=N("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",ya),o.isDSTShifted=N("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",ga);function Ln(e){return D(e*1e3)}function En(){return D.apply(null,arguments).parseZone()}function ys(e){return e}var w=tt.prototype;w.calendar=ps,w.longDateFormat=xs,w.invalidDate=Ns,w.ordinal=Fs,w.preparse=ys,w.postformat=ys,w.relativeTime=Cs,w.pastFuture=Us,w.set=vs,w.eras=hn,w.erasParse=fn,w.erasConvertYear=cn,w.erasAbbrRegex=kn,w.erasNameRegex=Sn,w.erasNarrowRegex=Mn,w.months=Xs,w.monthsShort=Ks,w.monthsParse=tr,w.monthsRegex=ar,w.monthsShortRegex=rr,w.week=or,w.firstDayOfYear=dr,w.firstDayOfWeek=ur,w.weekdays=Mr,w.weekdaysMin=gr,w.weekdaysShort=Dr,w.weekdaysParse=Yr,w.weekdaysRegex=br,w.weekdaysShortRegex=xr,w.weekdaysMinRegex=Wr,w.isPM=Pr,w.meridiem=Ir;function Ze(e,t,s,r){var a=B(),n=E().set(r,t);return a[s](n,e)}function ws(e,t,s){if(j(e)&&(t=e,e=void 0),e=e||"",t!=null)return Ze(e,t,s,"month");var r,a=[];for(r=0;r<12;r++)a[r]=Ze(e,r,s,"month");return a}function vt(e,t,s,r){typeof e=="boolean"?(j(t)&&(s=t,t=void 0),t=t||""):(t=e,s=t,e=!1,j(t)&&(s=t,t=void 0),t=t||"");var a=B(),n=e?a._week.dow:0,i,h=[];if(s!=null)return Ze(t,(s+n)%7,r,"day");for(i=0;i<7;i++)h[i]=Ze(t,(i+n)%7,r,"day");return h}function Hn(e,t){return ws(e,t,"months")}function An(e,t){return ws(e,t,"monthsShort")}function Vn(e,t,s){return vt(e,t,s,"weekdays")}function Gn(e,t,s){return vt(e,t,s,"weekdaysShort")}function jn(e,t,s){return vt(e,t,s,"weekdaysMin")}ee("en",{eras:[{since:"0001-01-01",until:Infinity,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-Infinity,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,s=c(e%100/10)===1?"th":t===1?"st":t===2?"nd":t===3?"rd":"th";return e+s}}),l.lang=N("moment.lang is deprecated. Use moment.locale instead.",ee),l.langData=N("moment.langData is deprecated. Use moment.localeData instead.",B);var q=Math.abs;function zn(){var e=this._data;return this._milliseconds=q(this._milliseconds),this._days=q(this._days),this._months=q(this._months),e.milliseconds=q(e.milliseconds),e.seconds=q(e.seconds),e.minutes=q(e.minutes),e.hours=q(e.hours),e.months=q(e.months),e.years=q(e.years),this}function Ss(e,t,s,r){var a=U(t,s);return e._milliseconds+=r*a._milliseconds,e._days+=r*a._days,e._months+=r*a._months,e._bubble()}function Zn(e,t){return Ss(this,e,t,1)}function $n(e,t){return Ss(this,e,t,-1)}function ks(e){return e<0?Math.floor(e):Math.ceil(e)}function Bn(){var e=this._milliseconds,t=this._days,s=this._months,r=this._data,a,n,i,h,_;return e>=0&&t>=0&&s>=0||e<=0&&t<=0&&s<=0||(e+=ks(Yt(s)+t)*864e5,t=0,s=0),r.milliseconds=e%1e3,a=R(e/1e3),r.seconds=a%60,n=R(a/60),r.minutes=n%60,i=R(n/60),r.hours=i%24,t+=R(i/24),_=R(Ms(t)),s+=_,t-=ks(Yt(_)),h=R(s/12),s%=12,r.days=t,r.months=s,r.years=h,this}function Ms(e){return e*4800/146097}function Yt(e){return e*146097/4800}function qn(e){if(!this.isValid())return NaN;var t,s,r=this._milliseconds;if(e=P(e),e==="month"||e==="quarter"||e==="year")switch(t=this._days+r/864e5,s=this._months+Ms(t),e){case"month":return s;case"quarter":return s/3;case"year":return s/12}else switch(t=this._days+Math.round(Yt(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return t*24+r/36e5;case"minute":return t*1440+r/6e4;case"second":return t*86400+r/1e3;case"millisecond":return Math.floor(t*864e5)+r;default:throw new Error("Unknown unit "+e)}}function Jn(){return this.isValid()?this._milliseconds+this._days*864e5+this._months%12*2592e6+c(this._months/12)*31536e6:NaN}function J(e){return function(){return this.as(e)}}var Qn=J("ms"),Xn=J("s"),Kn=J("m"),ei=J("h"),ti=J("d"),si=J("w"),ri=J("M"),ai=J("Q"),ni=J("y");function ii(){return U(this)}function oi(e){return e=P(e),this.isValid()?this[e+"s"]():NaN}function ne(e){return function(){return this.isValid()?this._data[e]:NaN}}var li=ne("milliseconds"),ui=ne("seconds"),di=ne("minutes"),hi=ne("hours"),fi=ne("days"),ci=ne("months"),_i=ne("years");function mi(){return R(this.days()/7)}var Q=Math.round,fe={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function yi(e,t,s,r,a){return a.relativeTime(t||1,!!s,e,r)}function wi(e,t,s,r){var a=U(e).abs(),n=Q(a.as("s")),i=Q(a.as("m")),h=Q(a.as("h")),_=Q(a.as("d")),k=Q(a.as("M")),L=Q(a.as("w")),G=Q(a.as("y")),X=n<=s.ss&&["s",n]||n0,X[4]=r,yi.apply(null,X)}function Si(e){return e===void 0?Q:typeof e=="function"?(Q=e,!0):!1}function ki(e,t){return fe[e]===void 0?!1:t===void 0?fe[e]:(fe[e]=t,e==="s"&&(fe.ss=t-1),!0)}function Mi(e,t){if(!this.isValid())return this.localeData().invalidDate();var s=!1,r=fe,a,n;return typeof e=="object"&&(t=e,e=!1),typeof e=="boolean"&&(s=e),typeof t=="object"&&(r=Object.assign({},fe,t),t.s!=null&&t.ss==null&&(r.ss=t.s-1)),a=this.localeData(),n=wi(this,!s,r,a),s&&(n=a.pastFuture(+this,n)),a.postformat(n)}var pt=Math.abs;function ce(e){return(e>0)-(e<0)||+e}function $e(){if(!this.isValid())return this.localeData().invalidDate();var e=pt(this._milliseconds)/1e3,t=pt(this._days),s=pt(this._months),r,a,n,i,h=this.asSeconds(),_,k,L,G;return h?(r=R(e/60),a=R(r/60),e%=60,r%=60,n=R(s/12),s%=12,i=e?e.toFixed(3).replace(/\.?0+$/,""):"",_=h<0?"-":"",k=ce(this._months)!==ce(h)?"-":"",L=ce(this._days)!==ce(h)?"-":"",G=ce(this._milliseconds)!==ce(h)?"-":"",_+"P"+(n?k+n+"Y":"")+(s?k+s+"M":"")+(t?L+t+"D":"")+(a||r||e?"T":"")+(a?G+a+"H":"")+(r?G+r+"M":"")+(e?G+i+"S":"")):"P0D"}var m=He.prototype;m.isValid=ha,m.abs=zn,m.add=Zn,m.subtract=$n,m.as=qn,m.asMilliseconds=Qn,m.asSeconds=Xn,m.asMinutes=Kn,m.asHours=ei,m.asDays=ti,m.asWeeks=si,m.asMonths=ri,m.asQuarters=ai,m.asYears=ni,m.valueOf=Jn,m._bubble=Bn,m.clone=ii,m.get=oi,m.milliseconds=li,m.seconds=ui,m.minutes=di,m.hours=hi,m.days=fi,m.weeks=mi,m.months=ci,m.years=_i,m.humanize=Mi,m.toISOString=$e,m.toString=$e,m.toJSON=$e,m.locale=os,m.localeData=us,m.toIsoString=N("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",$e),m.lang=ls,d("X",0,0,"unix"),d("x",0,0,"valueOf"),u("x",Re),u("X",Vs),S("X",function(e,t,s){s._d=new Date(parseFloat(e)*1e3)}),S("x",function(e,t,s){s._d=new Date(c(e))});//! moment.js +l.version="2.29.1",Ds(D),l.fn=o,l.min=oa,l.max=la,l.now=ua,l.utc=E,l.unix=Ln,l.months=Hn,l.isDate=_e,l.locale=ee,l.invalid=pe,l.duration=U,l.isMoment=I,l.weekdays=Vn,l.parseZone=En,l.localeData=B,l.isDuration=Ae,l.monthsShort=An,l.weekdaysMin=jn,l.defineLocale=ft,l.updateLocale=Lr,l.locales=Er,l.weekdaysShort=Gn,l.normalizeUnits=P,l.relativeTimeRounding=Si,l.relativeTimeThreshold=ki,l.calendarFormat=Fa,l.prototype=o,l.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"};export default l; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/nprogress.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/nprogress.js new file mode 100644 index 0000000000000000000000000000000000000000..c2f96187ac30b8da478845b7d2d15ab12189326c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/nprogress.js @@ -0,0 +1 @@ +import{c as T,a as w}from"./common/_commonjsHelpers-b3efd043.js";var M=T(function(C,N){(function(t,i){C.exports=i()})(w,function(){var t={};t.version="0.2.0";var i=t.settings={minimum:.08,easing:"ease",positionUsing:"",speed:200,trickle:!0,trickleRate:.02,trickleSpeed:800,showSpinner:!0,barSelector:'[role="bar"]',spinnerSelector:'[role="spinner"]',parent:"body",template:'
    '};t.configure=function(e){var r,n;for(r in e)n=e[r],n!==void 0&&e.hasOwnProperty(r)&&(i[r]=n);return this},t.status=null,t.set=function(e){var r=t.isStarted();e=g(e,i.minimum,1),t.status=e===1?null:e;var n=t.render(!r),o=n.querySelector(i.barSelector),a=i.speed,f=i.easing;return n.offsetWidth,P(function(s){i.positionUsing===""&&(i.positionUsing=t.getPositioningCSS()),m(o,k(e,a,f)),e===1?(m(n,{transition:"none",opacity:1}),n.offsetWidth,setTimeout(function(){m(n,{transition:"all "+a+"ms linear",opacity:0}),setTimeout(function(){t.remove(),s()},a)},a)):setTimeout(s,a)}),this},t.isStarted=function(){return typeof t.status=="number"},t.start=function(){t.status||t.set(0);var e=function(){setTimeout(function(){!t.status||(t.trickle(),e())},i.trickleSpeed)};return i.trickle&&e(),this},t.done=function(e){return!e&&!t.status?this:t.inc(.3+.5*Math.random()).set(1)},t.inc=function(e){var r=t.status;return r?(typeof e!="number"&&(e=(1-r)*g(Math.random()*r,.1,.95)),r=g(r+e,0,.994),t.set(r)):t.start()},t.trickle=function(){return t.inc(Math.random()*i.trickleRate)},function(){var e=0,r=0;t.promise=function(n){return!n||n.state()==="resolved"?this:(r===0&&t.start(),e++,r++,n.always(function(){r--,r===0?(e=0,t.done()):t.set((e-r)/e)}),this)}}(),t.render=function(e){if(t.isRendered())return document.getElementById("nprogress");h(document.documentElement,"nprogress-busy");var r=document.createElement("div");r.id="nprogress",r.innerHTML=i.template;var n=r.querySelector(i.barSelector),o=e?"-100":p(t.status||0),a=document.querySelector(i.parent),f;return m(n,{transition:"all 0 linear",transform:"translate3d("+o+"%,0,0)"}),i.showSpinner||(f=r.querySelector(i.spinnerSelector),f&&b(f)),a!=document.body&&h(a,"nprogress-custom-parent"),a.appendChild(r),r},t.remove=function(){S(document.documentElement,"nprogress-busy"),S(document.querySelector(i.parent),"nprogress-custom-parent");var e=document.getElementById("nprogress");e&&b(e)},t.isRendered=function(){return!!document.getElementById("nprogress")},t.getPositioningCSS=function(){var e=document.body.style,r="WebkitTransform"in e?"Webkit":"MozTransform"in e?"Moz":"msTransform"in e?"ms":"OTransform"in e?"O":"";return r+"Perspective"in e?"translate3d":r+"Transform"in e?"translate":"margin"};function g(e,r,n){return en?n:e}function p(e){return(-1+e)*100}function k(e,r,n){var o;return i.positionUsing==="translate3d"?o={transform:"translate3d("+p(e)+"%,0,0)"}:i.positionUsing==="translate"?o={transform:"translate("+p(e)+"%,0)"}:o={"margin-left":p(e)+"%"},o.transition="all "+r+"ms "+n,o}var P=function(){var e=[];function r(){var n=e.shift();n&&n(r)}return function(n){e.push(n),e.length==1&&r()}}(),m=function(){var e=["Webkit","O","Moz","ms"],r={};function n(s){return s.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(u,c){return c.toUpperCase()})}function o(s){var u=document.body.style;if(s in u)return s;for(var c=e.length,d=s.charAt(0).toUpperCase()+s.slice(1),l;c--;)if(l=e[c]+d,l in u)return l;return s}function a(s){return s=n(s),r[s]||(r[s]=o(s))}function f(s,u,c){u=a(u),s.style[u]=c}return function(s,u){var c=arguments,d,l;if(c.length==2)for(d in u)l=u[d],l!==void 0&&u.hasOwnProperty(d)&&f(s,d,l);else f(s,c[1],c[2])}}();function y(e,r){var n=typeof e=="string"?e:v(e);return n.indexOf(" "+r+" ")>=0}function h(e,r){var n=v(e),o=n+r;y(n,r)||(e.className=o.substring(1))}function S(e,r){var n=v(e),o;!y(e,r)||(o=n.replace(" "+r+" "," "),e.className=o.substring(1,o.length-1))}function v(e){return(" "+(e.className||"")+" ").replace(/\s+/gi," ")}function b(e){e&&e.parentNode&&e.parentNode.removeChild(e)}return t})});export default M; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/numeric.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/numeric.js new file mode 100644 index 0000000000000000000000000000000000000000..91034f76960a6f3dd7a1da440fa45b8b6e5860b3 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/numeric.js @@ -0,0 +1,170 @@ +import{c as createCommonjsModule,a as commonjsGlobal}from"./common/_commonjsHelpers-b3efd043.js";var numeric1_2_6=createCommonjsModule(function(module,exports){var numeric=exports;typeof commonjsGlobal!="undefined"&&(commonjsGlobal.numeric=numeric),numeric.version="1.2.6",numeric.bench=function(e,t){var r,u,i,o;for(typeof t=="undefined"&&(t=15),i=.5,r=new Date;;){for(i*=2,o=i;o>3;o-=4)e(),e(),e(),e();for(;o>0;)e(),o--;if(u=new Date,u-r>t)break}for(o=i;o>3;o-=4)e(),e(),e(),e();for(;o>0;)e(),o--;return u=new Date,1e3*(3*i-1)/(u-r)},numeric._myIndexOf=function(e){var t=this.length,r;for(r=0;rnumeric.largeArray)return r.push("...Large Array..."),!0;var c=!1;for(r.push("["),o=0;o0&&(r.push(","),c&&r.push(` + `)),c=u(i[o]);return r.push("]"),!0}r.push("{");var c=!1;for(o in i)i.hasOwnProperty(o)&&(c&&r.push(`, +`),c=!0,r.push(o),r.push(`: +`),u(i[o]));return r.push("}"),!0}return u(e),r.join("")},numeric.parseDate=function(e){function t(r){if(typeof r=="string")return Date.parse(r.replace(/-/g,"/"));if(!(r instanceof Array))throw new Error("parseDate: parameter must be arrays of strings");var u=[],i;for(i=0;i0){for(i[a]=[],r=0;r>2,l=((y&3)<<4)+(b>>4),F=((b&15)<<2)+(g>>6),E=g&63,A+1>=D?F=E=64:A+2>=D&&(E=64),_+=M.charAt(j)+M.charAt(l)+M.charAt(F)+M.charAt(E);return _}function r(B,D,A){typeof D=="undefined"&&(D=0),typeof A=="undefined"&&(A=B.length);var y=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],b=-1,g=0,j=B.length,l;for(l=D;l>>8^y[g];return b^-1}var u=e[0].length,i=e[0][0].length,o,n,f,a,m,c,v,h,s,p,d=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,i>>24&255,i>>16&255,i>>8&255,i&255,u>>24&255,u>>16&255,u>>8&255,u&255,8,2,0,0,0,-1,-2,-3,-4,-5,-6,-7,-8,73,68,65,84,8,29];for(p=r(d,12,29),d[29]=p>>24&255,d[30]=p>>16&255,d[31]=p>>8&255,d[32]=p&255,o=1,n=0,v=0;v>8&255,d.push(m),d.push(c),d.push(~m&255),d.push(~c&255),v===0&&d.push(0),h=0;h255?m=255:m<0?m=0:m=Math.round(m),o=(o+m)%65521,n=(n+o)%65521,d.push(m);d.push(0)}return s=(n<<16)+o,d.push(s>>24&255),d.push(s>>16&255),d.push(s>>8&255),d.push(s&255),a=d.length-41,d[33]=a>>24&255,d[34]=a>>16&255,d[35]=a>>8&255,d[36]=a&255,p=r(d,37),d.push(p>>24&255),d.push(p>>16&255),d.push(p>>8&255),d.push(p&255),d.push(0),d.push(0),d.push(0),d.push(0),d.push(73),d.push(69),d.push(78),d.push(68),d.push(174),d.push(66),d.push(96),d.push(130),"data:image/png;base64,"+t(d)},numeric._dim=function(e){for(var t=[];typeof e=="object";)t.push(e.length),e=e[0];return t},numeric.dim=function(e){var t,r;return typeof e=="object"?(t=e[0],typeof t=="object"?(r=t[0],typeof r=="object"?numeric._dim(e):[e.length,t.length]):[e.length]):[]},numeric.mapreduce=function(e,t){return Function("x","accum","_s","_k",'if(typeof accum === "undefined") accum = '+t+`; +if(typeof x === "number") { var xi = x; `+e+`; return accum; } +if(typeof _s === "undefined") _s = numeric.dim(x); +if(typeof _k === "undefined") _k = 0; +var _n = _s[_k]; +var i,xi; +if(_k < _s.length-1) { + for(i=_n-1;i>=0;i--) { + accum = arguments.callee(x[i],accum,_s,_k+1); + } return accum; +} +for(i=_n-1;i>=1;i-=2) { + xi = x[i]; + `+e+`; + xi = x[i-1]; + `+e+`; +} +if(i === 0) { + xi = x[i]; + `+e+` +} +return accum;`)},numeric.mapreduce2=function(e,t){return Function("x",`var n = x.length; +var i,xi; +`+t+`; +for(i=n-1;i!==-1;--i) { + xi = x[i]; + `+e+`; +} +return accum;`)},numeric.same=function x(e,t){var r,u;if(!(e instanceof Array)||!(t instanceof Array)||(u=e.length,u!==t.length))return!1;for(r=0;r=0;o-=2)i[o+1]=t,i[o]=t;return o===-1&&(i[0]=t),i}for(o=u-1;o>=0;o--)i[o]=numeric.rep(e,t,r+1);return i},numeric.dotMMsmall=function(e,t){var r,u,i,o,n,f,a,m,c,v,h;for(o=e.length,n=t.length,f=t[0].length,a=Array(o),r=o-1;r>=0;r--){for(m=Array(f),c=e[r],i=f-1;i>=0;i--){for(v=c[n-1]*t[n-1][i],u=n-2;u>=1;u-=2)h=u-1,v+=c[u]*t[u][i]+c[h]*t[h][i];u===0&&(v+=c[0]*t[0][i]),m[i]=v}a[r]=m}return a},numeric._getCol=function(e,t,r){var u=e.length,i;for(i=u-1;i>0;--i)r[i]=e[i][t],--i,r[i]=e[i][t];i===0&&(r[0]=e[0][t])},numeric.dotMMbig=function(e,t){var r=numeric._getCol,u=t.length,i=Array(u),o=e.length,n=t[0].length,f=new Array(o),a,m=numeric.dotVV,c,v;for(--u,--o,c=o;c!==-1;--c)f[c]=Array(n);for(--n,c=n;c!==-1;--c)for(r(t,c,i),v=o;v!==-1;--v)a=e[v],f[v][c]=m(a,i);return f},numeric.dotMV=function(e,t){var r=e.length,u=t.length,i,o=Array(r),n=numeric.dotVV;for(i=r-1;i>=0;i--)o[i]=n(e[i],t);return o},numeric.dotVM=function(e,t){var r,u,i,o,n,f,a;for(i=e.length,o=t[0].length,n=Array(o),u=o-1;u>=0;u--){for(f=e[i-1]*t[i-1][u],r=i-2;r>=1;r-=2)a=r-1,f+=e[r]*t[r][u]+e[a]*t[a][u];r===0&&(f+=e[0]*t[0][u]),n[u]=f}return n},numeric.dotVV=function(e,t){var r,u=e.length,i,o=e[u-1]*t[u-1];for(r=u-2;r>=1;r-=2)i=r-1,o+=e[r]*t[r]+e[i]*t[i];return r===0&&(o+=e[0]*t[0]),o},numeric.dot=function(e,t){var r=numeric.dim;switch(r(e).length*1e3+r(t).length){case 2002:return t.length<10?numeric.dotMMsmall(e,t):numeric.dotMMbig(e,t);case 2001:return numeric.dotMV(e,t);case 1002:return numeric.dotVM(e,t);case 1001:return numeric.dotVV(e,t);case 1e3:return numeric.mulVS(e,t);case 1:return numeric.mulSV(e,t);case 0:return e*t;default:throw new Error("numeric.dot only works on vectors and matrices")}},numeric.diag=function(e){var t,r,u,i=e.length,o=Array(i),n;for(t=i-1;t>=0;t--){for(n=Array(i),r=t+2,u=i-1;u>=r;u-=2)n[u]=0,n[u-1]=0;for(u>t&&(n[u]=0),n[t]=e[t],u=t-1;u>=1;u-=2)n[u]=0,n[u-1]=0;u===0&&(n[0]=0),o[t]=n}return o},numeric.getDiag=function(x){var e=Math.min(x.length,x[0].length),t,r=Array(e);for(t=e-1;t>=1;--t)r[t]=x[t][t],--t,r[t]=x[t][t];return t===0&&(r[0]=x[0][0]),r},numeric.identity=function(e){return numeric.diag(numeric.rep([e],1))},numeric.pointwise=function(e,t,r){typeof r=="undefined"&&(r="");var u=[],i,o=/\[i\]$/,n,f="",a=!1;for(i=0;i=0;i--) ret[i] = arguments.callee(`+e.join(",")+`,_s,_k+1); + return ret; +} +`+r+` +for(i=_n-1;i!==-1;--i) { + `+t+` +} +return ret;`,Function.apply(null,u)},numeric.pointwise2=function(e,t,r){typeof r=="undefined"&&(r="");var u=[],i,o=/\[i\]$/,n,f="",a=!1;for(i=0;i=0;o--)x(typeof e=="object"?e[o]:e,typeof t=="object"?t[o]:t,r,u+1,i)},numeric._biforeach2=function x(e,t,r,u,i){if(u===r.length-1)return i(e,t);var o,n=r[u],f=Array(n);for(o=n-1;o>=0;--o)f[o]=x(typeof e=="object"?e[o]:e,typeof t=="object"?t[o]:t,r,u+1,i);return f},numeric._foreach=function x(e,t,r,u){if(r===t.length-1){u(e);return}var i,o=t[r];for(i=o-1;i>=0;i--)x(e[i],t,r+1,u)},numeric._foreach2=function x(e,t,r,u){if(r===t.length-1)return u(e);var i,o=t[r],n=Array(o);for(i=o-1;i>=0;i--)n[i]=x(e[i],t,r+1,u);return n},numeric.ops2={add:"+",sub:"-",mul:"*",div:"/",mod:"%",and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">=",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"},numeric.opseq={addeq:"+=",subeq:"-=",muleq:"*=",diveq:"/=",modeq:"%=",lshifteq:"<<=",rshifteq:">>=",rrshifteq:">>>=",bandeq:"&=",boreq:"|=",bxoreq:"^="},numeric.mathfuns=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","isNaN","isFinite"],numeric.mathfuns2=["atan2","pow","max","min"],numeric.ops1={neg:"-",not:"!",bnot:"~",clone:""},numeric.mapreducers={any:["if(xi) return true;","var accum = false;"],all:["if(!xi) return false;","var accum = true;"],sum:["accum += xi;","var accum = 0;"],prod:["accum *= xi;","var accum = 1;"],norm2Squared:["accum += xi*xi;","var accum = 0;"],norminf:["accum = max(accum,abs(xi));","var accum = 0, max = Math.max, abs = Math.abs;"],norm1:["accum += abs(xi)","var accum = 0, abs = Math.abs;"],sup:["accum = max(accum,xi);","var accum = -Infinity, max = Math.max;"],inf:["accum = min(accum,xi);","var accum = Infinity, min = Math.min;"]},function(){var x,e;for(x=0;xd&&(p=v,d=s);for(f=o[p],o[p]=o[h],o[h]=f,c=a[p],a[p]=a[h],a[h]=c,e=f[h],s=h;s!==i;++s)f[s]/=e;for(s=i-1;s!==-1;--s)c[s]/=e;for(v=u-1;v!==-1;--v)if(v!==h){for(n=o[v],m=a[v],e=n[h],s=h+1;s!==i;++s)n[s]-=f[s]*e;for(s=i-1;s>0;--s)m[s]-=c[s]*e,--s,m[s]-=c[s]*e;s===0&&(m[0]-=c[0]*e)}}return a},numeric.det=function(e){var t=numeric.dim(e);if(t.length!==2||t[0]!==t[1])throw new Error("numeric: det() only works on square matrices");var r=t[0],u=1,i,o,n,f=numeric.clone(e),a,m,c,v,h;for(o=0;oMath.abs(f[n][o])&&(n=i);for(n!==o&&(v=f[n],f[n]=f[o],f[o]=v,u*=-1),a=f[o],i=o+1;i=1;t-=2){for(f=e[t],n=e[t-1],r=i-1;r>=1;--r)a=o[r],a[t]=f[r],a[t-1]=n[r],--r,a=o[r],a[t]=f[r],a[t-1]=n[r];r===0&&(a=o[0],a[t]=f[0],a[t-1]=n[0])}if(t===0){for(n=e[0],r=i-1;r>=1;--r)o[r][0]=n[r],--r,o[r][0]=n[r];r===0&&(o[0][0]=n[0])}return o},numeric.negtranspose=function(e){var t,r,u=e.length,i=e[0].length,o=Array(i),n,f,a;for(r=0;r=1;t-=2){for(f=e[t],n=e[t-1],r=i-1;r>=1;--r)a=o[r],a[t]=-f[r],a[t-1]=-n[r],--r,a=o[r],a[t]=-f[r],a[t-1]=-n[r];r===0&&(a=o[0],a[t]=-f[0],a[t-1]=-n[0])}if(t===0){for(n=e[0],r=i-1;r>=1;--r)o[r][0]=-n[r],--r,o[r][0]=-n[r];r===0&&(o[0][0]=-n[0])}return o},numeric._random=function x(e,t){var r,u=e[t],i=Array(u),o;if(t===e.length-1){for(o=Math.random,r=u-1;r>=1;r-=2)i[r]=o(),i[r-1]=o();return r===0&&(i[0]=o()),i}for(r=u-1;r>=0;r--)i[r]=x(e,t+1);return i},numeric.random=function(e){return numeric._random(e,0)},numeric.norm2=function(e){return Math.sqrt(numeric.norm2Squared(e))},numeric.linspace=function(e,t,r){if(typeof r=="undefined"&&(r=Math.max(Math.round(t-e)+1,1)),r<2)return r===1?[e]:[];var u,i=Array(r);for(r--,u=r;u>=0;u--)i[u]=(u*t+(r-u)*e)/r;return i},numeric.getBlock=function(e,t,r){var u=numeric.dim(e);function i(o,n){var f,a=t[n],m=r[n]-a,c=Array(m);if(n===u.length-1){for(f=m;f>=0;f--)c[f]=o[f+a];return c}for(f=m;f>=0;f--)c[f]=i(o[f+a],n+1);return c}return i(e,0)},numeric.setBlock=function(e,t,r,u){var i=numeric.dim(e);function o(n,f,a){var m,c=t[a],v=r[a]-c;if(a===i.length-1)for(m=v;m>=0;m--)n[m+c]=f[m];for(m=v;m>=0;m--)o(n[m+c],f[m],a+1)}return o(e,u,0),e},numeric.getRange=function(e,t,r){var u=t.length,i=r.length,o,n,f=Array(u),a,m;for(o=u-1;o!==-1;--o)for(f[o]=Array(i),a=f[o],m=e[t[o]],n=i-1;n!==-1;--n)a[n]=m[r[n]];return f},numeric.blockMatrix=function(e){var t=numeric.dim(e);if(t.length<4)return numeric.blockMatrix([e]);var r=t[0],u=t[1],i,o,n,f,a;for(i=0,o=0,n=0;n=0;a--){for(f=Array(o),c=e[a],m=o-1;m>=3;--m)f[m]=c*t[m],--m,f[m]=c*t[m],--m,f[m]=c*t[m],--m,f[m]=c*t[m];for(;m>=0;)f[m]=c*t[m],--m;n[a]=f}return n},numeric.T=function(e,t){this.x=e,this.y=t},numeric.t=function(e,t){return new numeric.T(e,t)},numeric.Tbinop=function(e,t,r,u,i){var o=numeric.indexOf;if(typeof i!="string"){var n;i="";for(n in numeric)numeric.hasOwnProperty(n)&&(e.indexOf(n)>=0||t.indexOf(n)>=0||r.indexOf(n)>=0||u.indexOf(n)>=0)&&n.length>1&&(i+="var "+n+" = numeric."+n+`; +`)}return Function(["y"],`var x = this; +if(!(y instanceof numeric.T)) { y = new numeric.T(y); } +`+i+` +if(x.y) { if(y.y) { return new numeric.T(`+u+`); + } + return new numeric.T(`+r+`); +} +if(y.y) { + return new numeric.T(`+t+`); +} +return new numeric.T(`+e+`); +`)},numeric.T.prototype.add=numeric.Tbinop("add(x.x,y.x)","add(x.x,y.x),y.y","add(x.x,y.x),x.y","add(x.x,y.x),add(x.y,y.y)"),numeric.T.prototype.sub=numeric.Tbinop("sub(x.x,y.x)","sub(x.x,y.x),neg(y.y)","sub(x.x,y.x),x.y","sub(x.x,y.x),sub(x.y,y.y)"),numeric.T.prototype.mul=numeric.Tbinop("mul(x.x,y.x)","mul(x.x,y.x),mul(x.x,y.y)","mul(x.x,y.x),mul(x.y,y.x)","sub(mul(x.x,y.x),mul(x.y,y.y)),add(mul(x.x,y.y),mul(x.y,y.x))"),numeric.T.prototype.reciprocal=function(){var e=numeric.mul,t=numeric.div;if(this.y){var r=numeric.add(e(this.x,this.x),e(this.y,this.y));return new numeric.T(t(this.x,r),t(numeric.neg(this.y),r))}return new T(t(1,this.x))},numeric.T.prototype.div=function(e){if(e instanceof numeric.T||(e=new numeric.T(e)),e.y)return this.mul(e.reciprocal());var t=numeric.div;return this.y?new numeric.T(t(this.x,e.x),t(this.y,e.x)):new numeric.T(t(this.x,e.x))},numeric.T.prototype.dot=numeric.Tbinop("dot(x.x,y.x)","dot(x.x,y.x),dot(x.x,y.y)","dot(x.x,y.x),dot(x.y,y.x)","sub(dot(x.x,y.x),dot(x.y,y.y)),add(dot(x.x,y.y),dot(x.y,y.x))"),numeric.T.prototype.transpose=function(){var e=numeric.transpose,t=this.x,r=this.y;return r?new numeric.T(e(t),e(r)):new numeric.T(e(t))},numeric.T.prototype.transjugate=function(){var e=numeric.transpose,t=this.x,r=this.y;return r?new numeric.T(e(t),numeric.negtranspose(r)):new numeric.T(e(t))},numeric.Tunop=function(e,t,r){return typeof r!="string"&&(r=""),Function(`var x = this; +`+r+` +if(x.y) { `+t+`; +} +`+e+`; +`)},numeric.T.prototype.exp=numeric.Tunop("return new numeric.T(ex)","return new numeric.T(mul(cos(x.y),ex),mul(sin(x.y),ex))","var ex = numeric.exp(x.x), cos = numeric.cos, sin = numeric.sin, mul = numeric.mul;"),numeric.T.prototype.conj=numeric.Tunop("return new numeric.T(x.x);","return new numeric.T(x.x,numeric.neg(x.y));"),numeric.T.prototype.neg=numeric.Tunop("return new numeric.T(neg(x.x));","return new numeric.T(neg(x.x),neg(x.y));","var neg = numeric.neg;"),numeric.T.prototype.sin=numeric.Tunop("return new numeric.T(numeric.sin(x.x))","return x.exp().sub(x.neg().exp()).div(new numeric.T(0,2));"),numeric.T.prototype.cos=numeric.Tunop("return new numeric.T(numeric.cos(x.x))","return x.exp().add(x.neg().exp()).div(2);"),numeric.T.prototype.abs=numeric.Tunop("return new numeric.T(numeric.abs(x.x));","return new numeric.T(numeric.sqrt(numeric.add(mul(x.x,x.x),mul(x.y,x.y))));","var mul = numeric.mul;"),numeric.T.prototype.log=numeric.Tunop("return new numeric.T(numeric.log(x.x));",`var theta = new numeric.T(numeric.atan2(x.y,x.x)), r = x.abs(); +return new numeric.T(numeric.log(r.x),theta.x);`),numeric.T.prototype.norm2=numeric.Tunop("return numeric.norm2(x.x);",`var f = numeric.norm2Squared; +return Math.sqrt(f(x.x)+f(x.y));`),numeric.T.prototype.inv=function(){var e=this;if(typeof e.y=="undefined")return new numeric.T(numeric.inv(e.x));var t=e.x.length,r,u,i,o=numeric.identity(t),n=numeric.rep([t,t],0),f=numeric.clone(e.x),a=numeric.clone(e.y),m,c,v,h,s,p,d,B,r,u,i,D,A,y,b,g,j,l;for(r=0;rD&&(i=u,D=A);for(i!==r&&(l=f[r],f[r]=f[i],f[i]=l,l=a[r],a[r]=a[i],a[i]=l,l=o[r],o[r]=o[i],o[i]=l,l=n[r],n[r]=n[i],n[i]=l),m=f[r],c=a[r],s=o[r],p=n[r],y=m[r],b=c[r],u=r+1;u0;r--)for(s=o[r],p=n[r],u=r-1;u>=0;u--)for(d=o[u],B=n[u],y=f[u][r],b=a[u][r],i=t-1;i>=0;i--)g=s[i],j=p[i],d[i]-=y*g-b*j,B[i]-=y*j+b*g;return new numeric.T(o,n)},numeric.T.prototype.get=function(e){var t=this.x,r=this.y,u=0,i,o=e.length;if(r){for(;u=0?1:-1,u=r*numeric.norm2(e);t[0]+=u;var i=numeric.norm2(t);if(i===0)throw new Error("eig: internal error");return numeric.div(t,i)},numeric.toUpperHessenberg=function(e){var t=numeric.dim(e);if(t.length!==2||t[0]!==t[1])throw new Error("numeric: toUpperHessenberg() only works on square matrices");var r=t[0],u,i,o,n,f,a=numeric.clone(e),m,c,v,h,s=numeric.identity(r),p;for(i=0;i0){for(f=numeric.house(n),m=numeric.getBlock(a,[i+1,i],[r-1,r-1]),c=numeric.tensor(f,numeric.dot(f,m)),u=i+1;u=4*c){var M,_;M=.5*(v+Math.sqrt(v*v-4*c)),_=.5*(v-Math.sqrt(v*v-4*c)),h=numeric.add(numeric.sub(numeric.dot(h,h),numeric.mul(h,M+_)),numeric.diag(numeric.rep([3],M*_)))}else h=numeric.add(numeric.sub(numeric.dot(h,h),numeric.mul(h,v)),numeric.diag(numeric.rep([3],c)));for(i=[h[0][0],h[1][0],h[2][0]],o=numeric.house(i),B=[x[0],x[1],x[2]],D=numeric.tensor(o,numeric.dot(o,B)),y=0;y<3;y++)for(d=x[y],A=D[y],g=0;g=0?(A<0?g=-.5*(A-_(b)):g=-.5*(A+_(b)),E=(p-g)*(p-g)+d*d,M=B*B+(D-g)*(D-g),E>M?(E=_(E),l=(p-g)/E,F=d/E):(M=_(M),l=B/M,F=(D-g)/M),v=new i([[F,-l],[l,F]]),c.setRows(n,s,v.dot(c.getRows(n,s)))):(g=-.5*A,j=.5*_(-b),E=(p-g)*(p-g)+d*d,M=B*B+(D-g)*(D-g),E>M?(E=_(E+j*j),l=(p-g)/E,F=d/E,g=0,j/=E):(M=_(M+j*j),l=B/M,F=(D-g)/M,g=j/M,j=0),v=new i([[F,-l],[l,F]],[[g,j],[j,-g]]),c.setRows(n,s,v.dot(c.getRows(n,s))))}var w=c.dot(e).dot(c.transjugate()),o=e.length,C=numeric.T.identity(o);for(s=0;s0)for(f=s-1;f>=0;f--){var P=w.get([f,f]),S=w.get([s,s]);if(numeric.neq(P.x,S.x)||numeric.neq(P.y,S.y))g=w.getRow(f).getBlock([f],[s-1]),j=C.getRow(s).getBlock([f],[s-1]),C.set([s,f],w.get([f,s]).neg().sub(g.dot(j)).div(P.sub(S)));else{C.setRow(s,C.getRow(f));continue}}for(s=0;s=n.length;)n[n.length]=0;u[o]!==0&&n[o]++}}var r=n.length,f=Array(r+1);for(f[0]=0,i=0;i=s){if(i[a]=v[n],n===0)return;++a,--n,h=m[n],s=c[n]}else f=o[r[h]],u[f]===0?(u[f]=1,m[n]=h,++n,v[n]=f,h=t[f],c[n]=s=t[f+1]):++h},numeric.ccsLPSolve=function(e,t,r,u,i,o,n){var f=e[0],a=e[1],m=e[2],c=f.length-1,v=t[0],h=t[1],s=t[2],p,d,B,D,A,y,b,g,j;for(d=v[i],B=v[i+1],u.length=0,p=d;pB&&(D=d,B=A));for(g(v[s])=p){if(i[m]=o[h[f]],f===0)return;++m,--f,s=c[f],p=v[f]}else a=r[s],u[a]===0?(u[a]=1,c[f]=s,++f,h[f]=a,a=o[a],s=t[a],v[f]=p=t[a+1]):++s}},numeric.ccsLPSolve0=function(e,t,r,u,i,o,n,f){var a=e[0],m=e[1],c=e[2],v=a.length-1,h=t[0],s=t[1],p=t[2],d,B,D,A,y,b,g,j,l;for(B=h[i],D=h[i+1],u.length=0,d=B;dB&&(D=d,B=A));for(g(v[j[s]])t[r]&&(t[r]=e.length);var u;for(u in e)e.hasOwnProperty(u)&&x(e[u],t,r+1);return t},numeric.sclone=function x(e,t,r){typeof t=="undefined"&&(t=0),typeof r=="undefined"&&(r=numeric.sdim(e).length);var u,i=Array(e.length);if(t===r-1){for(u in e)e.hasOwnProperty(u)&&(i[u]=e[u]);return i}for(u in e)e.hasOwnProperty(u)&&(i[u]=x(e[u],t+1,r));return i},numeric.sdiag=function(e){var t=e.length,r,u=Array(t),i;for(r=t-1;r>=1;r-=2)i=r-1,u[r]=[],u[r][r]=e[r],u[i]=[],u[i][i]=e[i];return r===0&&(u[0]=[],u[0][0]=e[r]),u},numeric.sidentity=function(e){return numeric.sdiag(numeric.rep([e],1))},numeric.stranspose=function(e){var t=[],r=e.length,u,i,o;for(u in e)if(!!e.hasOwnProperty(u)){o=e[u];for(i in o)!o.hasOwnProperty(i)||(typeof t[i]!="object"&&(t[i]=[]),t[i][u]=o[i])}return t},numeric.sLUP=function(e,t){throw new Error("The function numeric.sLUP had a bug in it and has been removed. Please use the new numeric.ccsLUP function instead.")},numeric.sdotMM=function(e,t){var r=e.length,u=t.length,i=numeric.stranspose(t),o=i.length,n,f,a,m,c,v,h=Array(r),s;for(a=r-1;a>=0;a--){for(s=[],n=e[a],c=o-1;c>=0;c--){v=0,f=i[c];for(m in n)!n.hasOwnProperty(m)||m in f&&(v+=n[m]*f[m]);v&&(s[c]=v)}h[a]=s}return h},numeric.sdotMV=function(e,t){var r=e.length,u,i,o,n=Array(r),f;for(i=r-1;i>=0;i--){u=e[i],f=0;for(o in u)!u.hasOwnProperty(o)||t[o]&&(f+=u[o]*t[o]);f&&(n[i]=f)}return n},numeric.sdotVM=function(e,t){var r,u,i,o,n=[];for(r in e)if(!!e.hasOwnProperty(r)){i=t[r],o=e[r];for(u in i)!i.hasOwnProperty(u)||(n[u]||(n[u]=0),n[u]+=o*i[u])}return n},numeric.sdotVV=function(e,t){var r,u=0;for(r in e)e[r]&&t[r]&&(u+=e[r]*t[r]);return u},numeric.sdot=function(e,t){var r=numeric.sdim(e).length,u=numeric.sdim(t).length,i=r*1e3+u;switch(i){case 0:return e*t;case 1001:return numeric.sdotVV(e,t);case 2001:return numeric.sdotMV(e,t);case 1002:return numeric.sdotVM(e,t);case 2002:return numeric.sdotMM(e,t);default:throw new Error("numeric.sdot not implemented for tensors of order "+r+" and "+u)}},numeric.sscatter=function(e){var t=e[0].length,r,u,i,o=e.length,n=[],f;for(u=t-1;u>=0;--u)if(!!e[o-1][u]){for(f=n,i=0;i=0;--i)t[i]=[];for(i=u;i>=0;--i)t[i].push(r[i]);t[u+1].push(o)}}else x(o,t,r);return r.length>u&&r.pop(),t},numeric.cLU=function(e){var t=e[0],r=e[1],u=e[2],i=t.length,o=0,n,f,a,m,c,v;for(n=0;no&&(o=t[n]);o++;var h=Array(o),s=Array(o),p=numeric.rep([o],Infinity),d=numeric.rep([o],-Infinity),B,D,A;for(a=0;ad[n]&&(d[n]=f);for(n=0;nd[n+1]&&(d[n+1]=d[n]);for(n=o-1;n>=1;n--)p[n]=0;p--){for(;m[d]>p;)i[p]-=c[d]*i[m[d]],d--;i[p]/=c[d],d--}return i},numeric.cgrid=function(e,t){typeof e=="number"&&(e=[e,e]);var r=numeric.rep(e,-1),u,i,o;if(typeof t!="function")switch(t){case"L":t=function(n,f){return n>=e[0]/2||fa&&(a=u[n]);for(a++,r=numeric.rep([a],0),n=0;n1;)i=o((r+u)/2),t[i]<=e?r=i:u=i;return this._at(e,r)}var n=e.length,f,a=Array(n);for(f=n-1;f!==-1;--f)a[f]=this.at(e[f]);return a},numeric.Spline.prototype.diff=function(){var e=this.x,t=this.yl,r=this.yr,u=this.kl,i=this.kr,o=t.length,n,f,a,m=u,c=i,v=Array(o),h=Array(o),s=numeric.add,p=numeric.mul,d=numeric.div,B=numeric.sub;for(n=o-1;n!==-1;--n)f=e[n+1]-e[n],a=B(r[n+1],t[n]),v[n]=d(s(p(a,6),p(u[n],-4*f),p(i[n+1],-2*f)),f*f),h[n+1]=d(s(p(a,-6),p(u[n],2*f),p(i[n+1],4*f)),f*f);return new numeric.Spline(e,m,c,v,h)},numeric.Spline.prototype.roots=function(){function e(N){return N*N}var t=[],r=this.x,u=this.yl,i=this.yr,o=this.kl,n=this.kr;typeof u[0]=="number"&&(u=[u],i=[i],o=[o],n=[n]);var f=u.length,a=r.length-1,m,c,v,h,s,p,d,t=Array(f),B,D,A,y,b,g,j,l,F,E,M,_,w,C,P,S,k=Math.sqrt;for(m=0;m!==f;++m){for(h=u[m],s=i[m],p=o[m],d=n[m],B=[],c=0;c!==a;c++){for(c>0&&s[c]*h[c]<0&&B.push(r[c]),F=r[c+1]-r[c],r[c],y=h[c],b=s[c+1],D=p[c]/F,A=d[c+1]/F,l=e(D-A+3*(y-b))+12*A*y,g=A+3*y+2*D-3*b,j=3*(A+D+2*(y-b)),l<=0?(M=g/j,M>r[c]&&Mr[c]&&Mr[c]&&_0){C=P,M=_;continue}for(var U=0;S=(M*P-_*C)/(M-_),!(S<=C||S>=P);)if(w=this._at(S,c),w*_>0)P=S,_=w,U===-1&&(M*=.5),U=-1;else if(w*M>0)C=S,M=w,U===1&&(_*=.5),U=1;else break;B.push(S),C=E[v+1],M=this._at(C,c)}_===0&&B.push(P)}t[m]=B}return typeof this.yl[0]=="number"?t[0]:t},numeric.spline=function(e,t,r,u){var i=e.length,o=[],n=[],f=[],a,m=numeric.sub,c=numeric.mul,v=numeric.add;for(a=i-2;a>=0;a--)n[a]=e[a+1]-e[a],f[a]=m(t[a+1],t[a]);(typeof r=="string"||typeof u=="string")&&(r=u="periodic");var h=[[],[],[]];switch(typeof r){case"undefined":o[0]=c(3/(n[0]*n[0]),f[0]),h[0].push(0,0),h[1].push(0,1),h[2].push(2/n[0],1/n[0]);break;case"string":o[0]=v(c(3/(n[i-2]*n[i-2]),f[i-2]),c(3/(n[0]*n[0]),f[0])),h[0].push(0,0,0),h[1].push(i-2,0,1),h[2].push(1/n[i-2],2/n[i-2]+2/n[0],1/n[0]);break;default:o[0]=r,h[0].push(0),h[1].push(0),h[2].push(1);break}for(a=1;a20)throw new Error("Numerical gradient fails");if(n[o]=t[o]+l,f=e(n),n[o]=t[o]-l,a=e(n),n[o]=t[o],isNaN(f)||isNaN(a)){l/=16;continue}if(m[o]=(f-a)/(2*l),B=t[o]-l,D=t[o],A=t[o]+l,b=(f-u)/l,g=(u-a)/l,j=i(p(m[o]),p(u),p(f),p(a),p(B),p(D),p(A),1e-8),h=d(i(p(b-m[o]),p(g-m[o]),p(b-g))/j,l/j),h>s)l/=16;else break}return m},numeric.uncmin=function(e,t,r,u,i,o,n){var f=numeric.gradient;typeof n=="undefined"&&(n={}),typeof r=="undefined"&&(r=1e-8),typeof u=="undefined"&&(u=function(q){return f(e,q)}),typeof i=="undefined"&&(i=1e3),t=numeric.clone(t);var a=t.length,m=e(t),c,v;if(isNaN(m))throw new Error("uncmin: f(x0) is a NaN!");var h=Math.max,s=numeric.norm2;r=h(r,numeric.epsilon);var p,d,B,D=n.Hinv||numeric.identity(a),A=numeric.dot,y=numeric.inv,b=numeric.sub,g=numeric.add,j=numeric.tensor,l=numeric.div,F=numeric.mul,E=numeric.all,M=numeric.isFinite,_=numeric.neg,w=0,C,P,S,k,U,N,Y,G="";for(d=u(t);w=.1*N*v||isNaN(c)){N*=.5,++w;continue}break}if(N*Y1;)u=i(.5*(t+r)),f[u]<=e?t=u:r=u;return this._at(e,t)},numeric.dopri=function(e,t,r,u,i,o,n){typeof i=="undefined"&&(i=1e-6),typeof o=="undefined"&&(o=1e3);var f=[e],a=[r],m=[u(e,r)],c,v,h,s,p,d,B=[],D=1/5,A=[3/40,9/40],y=[44/45,-56/15,32/9],b=[19372/6561,-25360/2187,64448/6561,-212/729],g=[9017/3168,-355/33,46732/5247,49/176,-5103/18656],j=[35/384,0,500/1113,125/192,-2187/6784,11/84],l=[.5*6025192743/30085553152,0,.5*51252292925/65400821598,.5*-2691868925/45128329728,.5*187940372067/1594534317056,.5*-1776094331/19743644256,.5*11237099/235043384],F=[1/5,3/10,4/5,8/9,1,1],E=[-71/57600,0,71/16695,-71/1920,17253/339200,-22/525,1/40],M=0,_,w,C=(t-e)/10,P=0,S=numeric.add,k=numeric.mul,U,N,Y=Math.min,G=Math.abs,q=numeric.norminf,V=Math.pow,$=numeric.any,X=numeric.lt,L=numeric.and,O=numeric.sub,Q,I,W,R=new numeric.Dopri(f,a,m,B,-1,"");for(typeof n=="function"&&(Q=n(e,r));et&&(C=t-e),c=u(e+F[0]*C,S(r,k(D*C,m[M]))),v=u(e+F[1]*C,S(S(r,k(A[0]*C,m[M])),k(A[1]*C,c))),h=u(e+F[2]*C,S(S(S(r,k(y[0]*C,m[M])),k(y[1]*C,c)),k(y[2]*C,v))),s=u(e+F[3]*C,S(S(S(S(r,k(b[0]*C,m[M])),k(b[1]*C,c)),k(b[2]*C,v)),k(b[3]*C,h))),p=u(e+F[4]*C,S(S(S(S(S(r,k(g[0]*C,m[M])),k(g[1]*C,c)),k(g[2]*C,v)),k(g[3]*C,h)),k(g[4]*C,s))),U=S(S(S(S(S(r,k(m[M],C*j[0])),k(v,C*j[2])),k(h,C*j[3])),k(s,C*j[4])),k(p,C*j[5])),d=u(e+C,U),_=S(S(S(S(S(k(m[M],C*E[0]),k(v,C*E[2])),k(h,C*E[3])),k(s,C*E[4])),k(p,C*E[5])),k(d,C*E[6])),typeof _=="number"?N=G(_):N=q(_),N>i){if(C=.2*C*V(i/N,.25),e+C===e){R.msg="Step size became too small";break}continue}if(B[M]=S(S(S(S(S(S(r,k(m[M],C*l[0])),k(v,C*l[2])),k(h,C*l[3])),k(s,C*l[4])),k(p,C*l[5])),k(d,C*l[6])),++M,f[M]=e+C,a[M]=U,m[M]=d,typeof n=="function"){var J,K=e,Z=e+.5*C,z;if(I=n(Z,B[M-1]),W=L(X(Q,0),X(0,I)),$(W)||(K=Z,Z=e+C,Q=I,I=n(Z,U),W=L(X(Q,0),X(0,I))),$(W)){for(var ir,er,nr=0,H=1,rr=1;;){if(typeof Q=="number")z=(rr*I*K-H*Q*Z)/(rr*I-H*Q);else for(z=Z,w=Q.length-1;w!==-1;--w)Q[w]<0&&I[w]>0&&(z=Y(z,(rr*I[w]*K-H*Q[w]*Z)/(rr*I[w]-H*Q[w])));if(z<=K||z>=Z)break;J=R._at(z,M-1),er=n(z,J),ir=L(X(Q,0),X(0,er)),$(ir)?(Z=z,I=er,W=ir,rr=1,nr===-1?H*=.5:H=1,nr=-1):(K=z,Q=er,H=1,nr===1?rr*=.5:rr=1,nr=1)}return U=R._at(.5*(e+z),M-1),R.f[M]=u(z,J),R.x[M]=z,R.y[M]=J,R.ymid[M-1]=U,R.events=W,R.iterations=P,R}}e+=C,r=U,Q=I,C=Y(.8*C*V(i/N,.25),4*C)}return R.iterations=P,R},numeric.LU=function(x,e){e=e||!1;var t=Math.abs,r,u,i,o,n,f,a,m,c,v=x.length,h=v-1,s=new Array(v);for(e||(x=numeric.clone(x)),i=0;i=0;--r){for(m=i[r],u=r+1;uI)&&(y=I),X=s(e,m(y,k)),Y=v(Q,U),L=p-1;L!==-1;--L)Y[L][L]+=1;O=G(Y,h(X,y),!0);var W=h(q,v(t,O)),R=1;for(L=d-1;L!==-1;--L)W[L]<0&&(R=C(R,-.999*W[L]));if(B=c(o,m(O,R)),q=c(r,v(t,B)),!P(S(q,0)))return{solution:o,message:"",iterations:V};if(o=B,y=0?D=!1:D=!0;if(D)return{solution:B,message:"Unbounded",iterations:V}}return{solution:o,message:"maximum iteration count exceeded",iterations:V}},numeric._solveLP=function(e,t,r,u,i){var o=e.length,n=r.length,f,a=numeric.sum,m=numeric.log,c=numeric.mul,v=numeric.sub,h=numeric.dot,s=numeric.div,p=numeric.add,d=numeric.rep([o],0).concat([1]),B=numeric.rep([n,1],-1),D=numeric.blockMatrix([[t,B]]),A=r,f=numeric.rep([o],0).concat(Math.max(0,numeric.sup(numeric.neg(r)))+1),y=numeric.__solveLP(d,D,A,u,i,f,!1),b=numeric.clone(y.solution);b.length=o;var g=numeric.inf(v(r,h(t,b)));if(g<0)return{solution:NaN,message:"Infeasible",iterations:y.iterations};var j=numeric.__solveLP(e,t,r,u,i-y.iterations,b,!0);return j.iterations+=y.iterations,j},numeric.solveLP=function(e,t,r,u,i,o,n){if(typeof n=="undefined"&&(n=1e3),typeof o=="undefined"&&(o=numeric.epsilon),typeof u=="undefined")return numeric._solveLP(e,t,r,o,n);var f=u.length,a=u[0].length,m=t.length,c=numeric.echelonize(u),v=numeric.rep([a],0),h=c.P,s=[],p;for(p=h.length-1;p!==-1;--p)v[h[p]]=1;for(p=a-1;p!==-1;--p)v[p]===0&&s.push(p);var d=numeric.getRange,B=numeric.linspace(0,f-1),D=numeric.linspace(0,m-1),A=d(u,B,s),y=d(t,D,h),b=d(t,D,s),g=numeric.dot,j=numeric.sub,l=g(y,c.I),F=j(b,g(l,A)),E=j(r,g(l,i)),M=Array(h.length),_=Array(s.length);for(p=h.length-1;p!==-1;--p)M[p]=e[h[p]];for(p=s.length-1;p!==-1;--p)_[p]=e[s[p]];var w=j(_,g(M,g(c.I,A))),C=numeric._solveLP(w,F,E,o,n),P=C.solution;if(P!==P)return C;var S=g(c.I,j(i,g(A,P))),k=Array(e.length);for(p=h.length-1;p!==-1;--p)k[h[p]]=S[p];for(p=s.length-1;p!==-1;--p)k[s[p]]=P[p];return{solution:k,message:C.message,iterations:C.iterations}},numeric.MPStoLP=function(e){e instanceof String&&e.split(` +`);var t=0,r=["Initial state","NAME","ROWS","COLUMNS","RHS","BOUNDS","ENDATA"],u=e.length,i,o,n,f=0,a={},m=[],c=0,v={},h=0,s,p=[],d=[],B=[];function D(j){throw new Error("MPStoLP: "+j+` +Line `+i+": "+e[i]+` +Current state: `+r[t]+` +`)}for(i=0;i=i;)B/=2,D/=2,A>>>=1;return(B+A)/D},v};function n(c){var v,h,s=this,p=c.length,d=0,B=s.i=s.j=s.m=0;for(s.S=[],s.c=[],p||(c=[p++]);dD)g[E]=V;else if(g[E]=-Math.abs(V),V>0){for(F=1;F<=c;F=F+1)s[F][l]=-s[F][l];p[l]=-p[l]}}for(l=1;l<=y;l=l+1)g[k+A[l]]=0;for(N=0,q=0,l=1;l<=B;l=l+1)g[k+l]=1;l=l-1){for(V=g[l],E=S+l*(l+3)/2,M=E-l,F=l+1;F<=y;F=F+1)V=V-g[E]*g[P+F],E=E+F;if(V=V/g[M],g[P+l]=V,A[l]=y+1&&!(g[l]===0||(L=Math.max(Math.abs(g[l-1]),Math.abs(g[l])),O=Math.min(Math.abs(g[l-1]),Math.abs(g[l])),g[l-1]>=0?q=Math.abs(L*Math.sqrt(1+O*O/(L*L))):q=-Math.abs(L*Math.sqrt(1+O*O/(L*L))),L=g[l-1]/q,O=g[l]/q,L===1));l=l-1)if(L===0)for(g[l-1]=O*q,F=1;F<=c;F=F+1)q=f[F][l-1],f[F][l-1]=f[F][l],f[F][l]=q;else for(g[l-1]=q,Q=O/(1+L),F=1;F<=c;F=F+1)q=L*f[F][l-1]+O*f[F][l],f[F][l]=Q*(f[F][l-1]+q)-f[F][l],f[F][l-1]=q;g[E]=g[y]}}else{for(V=-p[N],F=1;F<=c;F=F+1)V=V+v[F]*s[F][N];if(N>D)g[k+N]=V;else if(g[k+N]=-Math.abs(V),V>0){for(F=1;F<=c;F=F+1)s[F][N]=-s[F][N];p[N]=-p[N]}return 700}}return 0}function er(){if(E=S+w*(w+1)/2+1,M=E+w,g[M]===0||(L=Math.max(Math.abs(g[M-1]),Math.abs(g[M])),O=Math.min(Math.abs(g[M-1]),Math.abs(g[M])),g[M-1]>=0?q=Math.abs(L*Math.sqrt(1+O*O/(L*L))):q=-Math.abs(L*Math.sqrt(1+O*O/(L*L))),L=g[M-1]/q,O=g[M]/q,L===1))return 798;if(L===0){for(l=w+1;l<=y;l=l+1)q=g[M-1],g[M-1]=g[M],g[M]=q,M=M+l;for(l=1;l<=c;l=l+1)q=f[l][w],f[l][w]=f[l][w+1],f[l][w+1]=q}else{for(Q=O/(1+L),l=w+1;l<=y;l=l+1)q=L*g[M-1]+O*g[M],g[M]=Q*(g[M-1]+q)-g[M],g[M-1]=q,M=M+l;for(l=1;l<=c;l=l+1)q=L*f[l][w]+O*f[l][w+1],f[l][w+1]=Q*(f[l][w]+q)-f[l][w+1],f[l][w]=q}return 0}function nr(){for(M=E-w,l=1;l<=w;l=l+1)g[M]=g[E],E=E+1,M=M+1;return g[U+w]=g[U+w+1],A[w]=A[w+1],w=w+1,ww?_*Math.sqrt(1+w*w/_/_):w==0?_:w*Math.sqrt(1+_*_/w/w)}var D=0,A=0,y=0,b=0,g=0,j=0,l=0;for(n=0;n=0&&(A=-A),y=D*A-l,c[n][n]=D-A,f=m;f=0&&(A=-A),y=D*A-l,c[n][n+1]=D-A,f=m;fb&&(b=g)}for(n=h-1;n!=-1;n+=-1){if(A!=0){for(y=A*c[n][n+1],f=m;f=i-1)throw"Error: no convergence.";for(b=p[m],g=p[a-1],A=s[a-1],y=s[a],D=((g-j)*(g+j)+(A-y)*(A+y))/(2*y*g),A=B(D,1),D<0?D=((b-j)*(b+j)+y*(g/(D-A)-y))/b:D=((b-j)*(b+j)+y*(g/(D+A)-y))/b,o=1,l=1,n=m+1;n=0;f--)if(p[f]0)break}while(ee(a,i));u=v.notation==="postfix",v.symbol!==")"&&(a.push(v),u&&ee(a,i))}else if(d){if(a.push(d.prefix||d.func),d.func&&(n=o.exec(e),!n||n[0]!=="("))throw new f(38,n?n.index:e.length,e)}else i.push(+p),u=!0}while(n&&a.length);if(a.length)throw new f(39,n?n.index:e.length,e);if(n)throw new f(40,n?n.index:e.length,e);return i.pop()}function q(e){return e.split("").reverse().join("")}function Le(e,r){var t=q(e),n=t.match(_);if(n&&!n.every(function(i){return i===n[0]}))throw new f(41);var a=q(t.replace(_,""));return""+je(a,r)+(n?q(n[0]):"")}var Me=/--[\S]*/g;function $e(e,r){if(!e||!e.match(Me))throw new f(73);var t;if(typeof document!="undefined"&&document.documentElement!==null&&(t=getComputedStyle(document.documentElement).getPropertyValue(e)),t)return t.trim();if(r)return r;throw new f(74)}function T(e){return e.charAt(0).toUpperCase()+e.slice(1)}var He=["Top","Right","Bottom","Left"];function ke(e,r){if(!e)return r.toLowerCase();var t=e.split("-");if(t.length>1)return t.splice(1,0,r),t.reduce(function(a,i){return""+a+T(i)});var n=e.replace(/([a-z])([A-Z])/g,"$1"+r+"$2");return e===n?""+e+r:n}function We(e,r){for(var t={},n=0;n1?r-1:0),n=1;n=0)?t[n]=e[n]+" !important":t[n]=e[n]}),t}var ae={minorSecond:1.067,majorSecond:1.125,minorThird:1.2,majorThird:1.25,perfectFourth:1.333,augFourth:1.414,perfectFifth:1.5,minorSixth:1.6,goldenSection:1.618,majorSixth:1.667,minorSeventh:1.778,majorSeventh:1.875,octave:2,majorTenth:2.5,majorEleventh:2.667,majorTwelfth:3,doubleOctave:4};function Ue(e){return ae[e]}function De(e,r,t){if(r===void 0&&(r="1em"),t===void 0&&(t=1.333),typeof e!="number")throw new f(42);if(typeof t=="string"&&!ae[t])throw new f(43);var n=typeof r=="string"?S(r):[r,""],a=n[0],i=n[1],o=typeof t=="string"?Ue(t):t;if(typeof a=="string")throw new f(44,r);return""+a*Math.pow(o,e)+(i||"")}var Pe=te("rem"),E=16;function ie(e){var r=S(e);if(r[1]==="px")return parseFloat(e);if(r[1]==="%")return parseFloat(e)/100*E;throw new f(78,r[1])}function Ge(){if(typeof document!="undefined"&&document.documentElement!==null){var e=getComputedStyle(document.documentElement).fontSize;return e?ie(e):E}return E}function Qe(e,r){var t=S(e);if(t[1]!=="rem"&&t[1]!=="")throw new f(77,t[1]);var n=r?ie(r):Ge();return t[0]*n+"px"}var Je={back:"cubic-bezier(0.600, -0.280, 0.735, 0.045)",circ:"cubic-bezier(0.600, 0.040, 0.980, 0.335)",cubic:"cubic-bezier(0.550, 0.055, 0.675, 0.190)",expo:"cubic-bezier(0.950, 0.050, 0.795, 0.035)",quad:"cubic-bezier(0.550, 0.085, 0.680, 0.530)",quart:"cubic-bezier(0.895, 0.030, 0.685, 0.220)",quint:"cubic-bezier(0.755, 0.050, 0.855, 0.060)",sine:"cubic-bezier(0.470, 0.000, 0.745, 0.715)"};function Ze(e){return Je[e.toLowerCase().trim()]}var Ne={back:"cubic-bezier(0.680, -0.550, 0.265, 1.550)",circ:"cubic-bezier(0.785, 0.135, 0.150, 0.860)",cubic:"cubic-bezier(0.645, 0.045, 0.355, 1.000)",expo:"cubic-bezier(1.000, 0.000, 0.000, 1.000)",quad:"cubic-bezier(0.455, 0.030, 0.515, 0.955)",quart:"cubic-bezier(0.770, 0.000, 0.175, 1.000)",quint:"cubic-bezier(0.860, 0.000, 0.070, 1.000)",sine:"cubic-bezier(0.445, 0.050, 0.550, 0.950)"};function Xe(e){return Ne[e.toLowerCase().trim()]}var Ye={back:"cubic-bezier(0.175, 0.885, 0.320, 1.275)",cubic:"cubic-bezier(0.215, 0.610, 0.355, 1.000)",circ:"cubic-bezier(0.075, 0.820, 0.165, 1.000)",expo:"cubic-bezier(0.190, 1.000, 0.220, 1.000)",quad:"cubic-bezier(0.250, 0.460, 0.450, 0.940)",quart:"cubic-bezier(0.165, 0.840, 0.440, 1.000)",quint:"cubic-bezier(0.230, 1.000, 0.320, 1.000)",sine:"cubic-bezier(0.390, 0.575, 0.565, 1.000)"};function Ke(e){return Ye[e.toLowerCase().trim()]}function U(e,r,t,n){t===void 0&&(t="320px"),n===void 0&&(n="1200px");var a=S(e),i=a[0],o=a[1],u=S(r),c=u[0],p=u[1],b=S(t),d=b[0],s=b[1],m=S(n),v=m[0],x=m[1];if(typeof d!="number"||typeof v!="number"||!s||!x||s!==x)throw new f(47);if(typeof i!="number"||typeof c!="number"||o!==p)throw new f(48);if(o!==s||p!==x)throw new f(76);var g=(i-c)/(d-v),z=c-g*v;return"calc("+z.toFixed(2)+(o||"")+" + "+(100*g).toFixed(2)+"vw)"}function Ve(e){var r;e===void 0&&(e="&");var t=e+"::after";return r={},r[t]={clear:"both",content:'""',display:"table"},r}function _e(e){return e===void 0&&(e=0),{position:"absolute",top:e,right:e,bottom:e,left:e}}function er(e,r){r===void 0&&(r=1);var t={display:"inline-block",maxWidth:e||"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",wordWrap:"normal"};return r>1?l({},t,{WebkitBoxOrient:"vertical",WebkitLineClamp:r,display:"-webkit-box",whiteSpace:"normal"}):t}function rr(e,r){var t=typeof Symbol!="undefined"&&e[Symbol.iterator]||e["@@iterator"];if(t)return(t=t.call(e)).next.bind(t);if(Array.isArray(e)||(t=tr(e))||r&&e&&typeof e.length=="number"){t&&(e=t);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tr(e,r){if(!!e){if(typeof e=="string")return oe(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);if(t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set")return Array.from(e);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return oe(e,r)}}function oe(e,r){(r==null||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t1?t-1:0),a=1;a1?(r=r.slice(0,-1),r+=", "+n[i]):o.length===1&&(r+=""+n[i])}else n[i]&&(r+=n[i]+" ");return r.trim()}var pe;function lr(e){var r=e.colorStops,t=e.fallback,n=e.toDirection,a=n===void 0?"":n;if(!r||r.length<2)throw new f(56);return{backgroundColor:t||r[0].replace(/,\s+/g,",").split(" ")[0].replace(/,(?=\S)/g,", "),backgroundImage:ce(pe||(pe=Y(["linear-gradient(","",")"])),a,r.join(", ").replace(/,(?=\S)/g,", "))}}function br(){var e;return[(e={html:{lineHeight:"1.15",textSizeAdjust:"100%"},body:{margin:"0"},main:{display:"block"},h1:{fontSize:"2em",margin:"0.67em 0"},hr:{boxSizing:"content-box",height:"0",overflow:"visible"},pre:{fontFamily:"monospace, monospace",fontSize:"1em"},a:{backgroundColor:"transparent"},"abbr[title]":{borderBottom:"none",textDecoration:"underline"}},e[`b, + strong`]={fontWeight:"bolder"},e[`code, + kbd, + samp`]={fontFamily:"monospace, monospace",fontSize:"1em"},e.small={fontSize:"80%"},e[`sub, + sup`]={fontSize:"75%",lineHeight:"0",position:"relative",verticalAlign:"baseline"},e.sub={bottom:"-0.25em"},e.sup={top:"-0.5em"},e.img={borderStyle:"none"},e[`button, + input, + optgroup, + select, + textarea`]={fontFamily:"inherit",fontSize:"100%",lineHeight:"1.15",margin:"0"},e[`button, + input`]={overflow:"visible"},e[`button, + select`]={textTransform:"none"},e[`button, + html [type="button"], + [type="reset"], + [type="submit"]`]={WebkitAppearance:"button"},e[`button::-moz-focus-inner, + [type="button"]::-moz-focus-inner, + [type="reset"]::-moz-focus-inner, + [type="submit"]::-moz-focus-inner`]={borderStyle:"none",padding:"0"},e[`button:-moz-focusring, + [type="button"]:-moz-focusring, + [type="reset"]:-moz-focusring, + [type="submit"]:-moz-focusring`]={outline:"1px dotted ButtonText"},e.fieldset={padding:"0.35em 0.625em 0.75em"},e.legend={boxSizing:"border-box",color:"inherit",display:"table",maxWidth:"100%",padding:"0",whiteSpace:"normal"},e.progress={verticalAlign:"baseline"},e.textarea={overflow:"auto"},e[`[type="checkbox"], + [type="radio"]`]={boxSizing:"border-box",padding:"0"},e[`[type="number"]::-webkit-inner-spin-button, + [type="number"]::-webkit-outer-spin-button`]={height:"auto"},e['[type="search"]']={WebkitAppearance:"textfield",outlineOffset:"-2px"},e['[type="search"]::-webkit-search-decoration']={WebkitAppearance:"none"},e["::-webkit-file-upload-button"]={WebkitAppearance:"button",font:"inherit"},e.details={display:"block"},e.summary={display:"list-item"},e.template={display:"none"},e["[hidden]"]={display:"none"},e),{"abbr[title]":{textDecoration:"underline dotted"}}]}var de;function gr(e){var r=e.colorStops,t=e.extent,n=t===void 0?"":t,a=e.fallback,i=e.position,o=i===void 0?"":i,u=e.shape,c=u===void 0?"":u;if(!r||r.length<2)throw new f(57);return{backgroundColor:a||r[0].split(" ")[0],backgroundImage:ce(de||(de=Y(["radial-gradient(","","","",")"])),o,c,n,r.join(", "))}}function hr(e,r,t,n,a){var i;if(t===void 0&&(t="png"),a===void 0&&(a="_2x"),!e)throw new f(58);var o=t.replace(/^\./,""),u=n?n+"."+o:""+e+a+"."+o;return i={backgroundImage:"url("+e+"."+o+")"},i[fe()]=l({backgroundImage:"url("+u+")"},r?{backgroundSize:r}:{}),i}var mr={easeInBack:"cubic-bezier(0.600, -0.280, 0.735, 0.045)",easeInCirc:"cubic-bezier(0.600, 0.040, 0.980, 0.335)",easeInCubic:"cubic-bezier(0.550, 0.055, 0.675, 0.190)",easeInExpo:"cubic-bezier(0.950, 0.050, 0.795, 0.035)",easeInQuad:"cubic-bezier(0.550, 0.085, 0.680, 0.530)",easeInQuart:"cubic-bezier(0.895, 0.030, 0.685, 0.220)",easeInQuint:"cubic-bezier(0.755, 0.050, 0.855, 0.060)",easeInSine:"cubic-bezier(0.470, 0.000, 0.745, 0.715)",easeOutBack:"cubic-bezier(0.175, 0.885, 0.320, 1.275)",easeOutCubic:"cubic-bezier(0.215, 0.610, 0.355, 1.000)",easeOutCirc:"cubic-bezier(0.075, 0.820, 0.165, 1.000)",easeOutExpo:"cubic-bezier(0.190, 1.000, 0.220, 1.000)",easeOutQuad:"cubic-bezier(0.250, 0.460, 0.450, 0.940)",easeOutQuart:"cubic-bezier(0.165, 0.840, 0.440, 1.000)",easeOutQuint:"cubic-bezier(0.230, 1.000, 0.320, 1.000)",easeOutSine:"cubic-bezier(0.390, 0.575, 0.565, 1.000)",easeInOutBack:"cubic-bezier(0.680, -0.550, 0.265, 1.550)",easeInOutCirc:"cubic-bezier(0.785, 0.135, 0.150, 0.860)",easeInOutCubic:"cubic-bezier(0.645, 0.045, 0.355, 1.000)",easeInOutExpo:"cubic-bezier(1.000, 0.000, 0.000, 1.000)",easeInOutQuad:"cubic-bezier(0.455, 0.030, 0.515, 0.955)",easeInOutQuart:"cubic-bezier(0.770, 0.000, 0.175, 1.000)",easeInOutQuint:"cubic-bezier(0.860, 0.000, 0.070, 1.000)",easeInOutSine:"cubic-bezier(0.445, 0.050, 0.550, 0.950)"};function vr(e){return mr[e]}function yr(e){return vr(e)}var wr=function(r,t,n){var a=""+n[0]+(n[1]||""),i=""+n[0]/2+(n[1]||""),o=""+t[0]+(t[1]||""),u=""+t[0]/2+(t[1]||"");switch(r){case"top":return"0 "+i+" "+o+" "+i;case"topLeft":return a+" "+o+" 0 0";case"left":return u+" "+a+" "+u+" 0";case"bottomLeft":return a+" 0 0 "+o;case"bottom":return o+" "+i+" 0 "+i;case"bottomRight":return"0 0 "+a+" "+o;case"right":return u+" 0 "+u+" "+a;case"topRight":default:return"0 "+a+" "+o+" 0"}},xr=function(r,t){switch(r){case"top":case"bottomRight":return{borderBottomColor:t};case"right":case"bottomLeft":return{borderLeftColor:t};case"bottom":case"topLeft":return{borderTopColor:t};case"left":case"topRight":return{borderRightColor:t};default:throw new f(59)}};function zr(e){var r=e.pointingDirection,t=e.height,n=e.width,a=e.foregroundColor,i=e.backgroundColor,o=i===void 0?"transparent":i,u=S(n),c=S(t);if(isNaN(c[0])||isNaN(u[0]))throw new f(60);return l({width:"0",height:"0",borderColor:o},xr(r,a),{borderStyle:"solid",borderWidth:wr(r,c,u)})}function Sr(e){e===void 0&&(e="break-word");var r=e==="break-word"?"break-all":e;return{overflowWrap:e,wordWrap:e,wordBreak:r}}function D(e){return Math.round(e*255)}function Ar(e,r,t){return D(e)+","+D(r)+","+D(t)}function j(e,r,t,n){if(n===void 0&&(n=Ar),r===0)return n(t,t,t);var a=(e%360+360)%360/60,i=(1-Math.abs(2*t-1))*r,o=i*(1-Math.abs(a%2-1)),u=0,c=0,p=0;a>=0&&a<1?(u=i,c=o):a>=1&&a<2?(u=o,c=i):a>=2&&a<3?(c=i,p=o):a>=3&&a<4?(c=o,p=i):a>=4&&a<5?(u=o,p=i):a>=5&&a<6&&(u=i,p=o);var b=t-i/2,d=u+b,s=c+b,m=p+b;return n(d,s,m)}var se={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};function Fr(e){if(typeof e!="string")return e;var r=e.toLowerCase();return se[r]?"#"+se[r]:e}var Ir=/^#[a-fA-F0-9]{6}$/,Or=/^#[a-fA-F0-9]{8}$/,Rr=/^#[a-fA-F0-9]{3}$/,Cr=/^#[a-fA-F0-9]{4}$/,P=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Tr=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i,jr=/^hsl\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,Lr=/^hsla\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*(\d{1,3}[.]?[0-9]?)%\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/i;function A(e){if(typeof e!="string")throw new f(3);var r=Fr(e);if(r.match(Ir))return{red:parseInt(""+r[1]+r[2],16),green:parseInt(""+r[3]+r[4],16),blue:parseInt(""+r[5]+r[6],16)};if(r.match(Or)){var t=parseFloat((parseInt(""+r[7]+r[8],16)/255).toFixed(2));return{red:parseInt(""+r[1]+r[2],16),green:parseInt(""+r[3]+r[4],16),blue:parseInt(""+r[5]+r[6],16),alpha:t}}if(r.match(Rr))return{red:parseInt(""+r[1]+r[1],16),green:parseInt(""+r[2]+r[2],16),blue:parseInt(""+r[3]+r[3],16)};if(r.match(Cr)){var n=parseFloat((parseInt(""+r[4]+r[4],16)/255).toFixed(2));return{red:parseInt(""+r[1]+r[1],16),green:parseInt(""+r[2]+r[2],16),blue:parseInt(""+r[3]+r[3],16),alpha:n}}var a=P.exec(r);if(a)return{red:parseInt(""+a[1],10),green:parseInt(""+a[2],10),blue:parseInt(""+a[3],10)};var i=Tr.exec(r.substring(0,50));if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10),alpha:parseFloat(""+i[4])};var o=jr.exec(r);if(o){var u=parseInt(""+o[1],10),c=parseInt(""+o[2],10)/100,p=parseInt(""+o[3],10)/100,b="rgb("+j(u,c,p)+")",d=P.exec(b);if(!d)throw new f(4,r,b);return{red:parseInt(""+d[1],10),green:parseInt(""+d[2],10),blue:parseInt(""+d[3],10)}}var s=Lr.exec(r.substring(0,50));if(s){var m=parseInt(""+s[1],10),v=parseInt(""+s[2],10)/100,x=parseInt(""+s[3],10)/100,g="rgb("+j(m,v,x)+")",z=P.exec(g);if(!z)throw new f(4,r,g);return{red:parseInt(""+z[1],10),green:parseInt(""+z[2],10),blue:parseInt(""+z[3],10),alpha:parseFloat(""+s[4])}}throw new f(5)}function Mr(e){var r=e.red/255,t=e.green/255,n=e.blue/255,a=Math.max(r,t,n),i=Math.min(r,t,n),o=(a+i)/2;if(a===i)return e.alpha!==void 0?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var u,c=a-i,p=o>.5?c/(2-a-i):c/(a+i);switch(a){case r:u=(t-n)/c+(t=1?$(e,r,t):"rgba("+j(e,r,t)+","+n+")";if(typeof e=="object"&&r===void 0&&t===void 0&&n===void 0)return e.alpha>=1?$(e.hue,e.saturation,e.lightness):"rgba("+j(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new f(2)}function L(e,r,t){if(typeof e=="number"&&typeof r=="number"&&typeof t=="number")return G("#"+I(e)+I(r)+I(t));if(typeof e=="object"&&r===void 0&&t===void 0)return G("#"+I(e.red)+I(e.green)+I(e.blue));throw new f(6)}function O(e,r,t,n){if(typeof e=="string"&&typeof r=="number"){var a=A(e);return"rgba("+a.red+","+a.green+","+a.blue+","+r+")"}else{if(typeof e=="number"&&typeof r=="number"&&typeof t=="number"&&typeof n=="number")return n>=1?L(e,r,t):"rgba("+e+","+r+","+t+","+n+")";if(typeof e=="object"&&r===void 0&&t===void 0&&n===void 0)return e.alpha>=1?L(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")"}throw new f(7)}var Hr=function(r){return typeof r.red=="number"&&typeof r.green=="number"&&typeof r.blue=="number"&&(typeof r.alpha!="number"||typeof r.alpha=="undefined")},kr=function(r){return typeof r.red=="number"&&typeof r.green=="number"&&typeof r.blue=="number"&&typeof r.alpha=="number"},Wr=function(r){return typeof r.hue=="number"&&typeof r.saturation=="number"&&typeof r.lightness=="number"&&(typeof r.alpha!="number"||typeof r.alpha=="undefined")},qr=function(r){return typeof r.hue=="number"&&typeof r.saturation=="number"&&typeof r.lightness=="number"&&typeof r.alpha=="number"};function y(e){if(typeof e!="object")throw new f(8);if(kr(e))return O(e);if(Hr(e))return L(e);if(qr(e))return Z(e);if(Wr(e))return J(e);throw new f(8)}function le(e,r,t){return function(){var a=t.concat(Array.prototype.slice.call(arguments));return a.length>=r?e.apply(this,a):le(e,r,a)}}function h(e){return le(e,e.length,[])}function Br(e,r){if(r==="transparent")return r;var t=w(r);return y(l({},t,{hue:t.hue+parseFloat(e)}))}var Er=h(Br);function Ur(e){if(e==="transparent")return e;var r=w(e);return y(l({},r,{hue:(r.hue+180)%360}))}function R(e,r,t){return Math.max(e,Math.min(r,t))}function Dr(e,r){if(r==="transparent")return r;var t=w(r);return y(l({},t,{lightness:R(0,1,t.lightness-parseFloat(e))}))}var Pr=h(Dr);function Gr(e,r){if(r==="transparent")return r;var t=w(r);return y(l({},t,{saturation:R(0,1,t.saturation-parseFloat(e))}))}var Qr=h(Gr);function H(e){if(e==="transparent")return 0;var r=A(e),t=Object.keys(r).map(function(o){var u=r[o]/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)}),n=t[0],a=t[1],i=t[2];return parseFloat((.2126*n+.7152*a+.0722*i).toFixed(3))}function N(e,r){var t=H(e),n=H(r);return parseFloat((t>n?(t+.05)/(n+.05):(n+.05)/(t+.05)).toFixed(2))}function Jr(e){return e==="transparent"?e:y(l({},w(e),{saturation:0}))}function Zr(e){if(typeof e=="object"&&typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number")return e.alpha&&typeof e.alpha=="number"?Z({hue:e.hue,saturation:e.saturation,lightness:e.lightness,alpha:e.alpha}):J({hue:e.hue,saturation:e.saturation,lightness:e.lightness});throw new f(45)}function Nr(e){if(e==="transparent")return e;var r=A(e);return y(l({},r,{red:255-r.red,green:255-r.green,blue:255-r.blue}))}function Xr(e,r){if(r==="transparent")return r;var t=w(r);return y(l({},t,{lightness:R(0,1,t.lightness+parseFloat(e))}))}var Yr=h(Xr);function Kr(e,r){var t=N(e,r);return{AA:t>=4.5,AALarge:t>=3,AAA:t>=7,AAALarge:t>=4.5}}function Vr(e,r,t){if(r==="transparent")return t;if(t==="transparent")return r;if(e===0)return t;var n=A(r),a=l({},n,{alpha:typeof n.alpha=="number"?n.alpha:1}),i=A(t),o=l({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),u=a.alpha-o.alpha,c=parseFloat(e)*2-1,p=c*u==-1?c:c+u,b=1+c*u,d=(p/b+1)/2,s=1-d,m={red:Math.floor(a.red*d+o.red*s),green:Math.floor(a.green*d+o.green*s),blue:Math.floor(a.blue*d+o.blue*s),alpha:a.alpha*(parseFloat(e)/1)+o.alpha*(1-parseFloat(e)/1)};return O(m)}var X=h(Vr);function _r(e,r){if(r==="transparent")return r;var t=A(r),n=typeof t.alpha=="number"?t.alpha:1,a=l({},t,{alpha:R(0,1,(n*100+parseFloat(e)*100)/100)});return O(a)}var et=h(_r),be="#000",ge="#fff";function rt(e,r,t,n){r===void 0&&(r=be),t===void 0&&(t=ge),n===void 0&&(n=!0);var a=H(e)>.179,i=a?r:t;return!n||N(e,i)>=4.5?i:a?be:ge}function tt(e){if(typeof e=="object"&&typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number")return typeof e.alpha=="number"?O({red:e.red,green:e.green,blue:e.blue,alpha:e.alpha}):L({red:e.red,green:e.green,blue:e.blue});throw new f(46)}function nt(e,r){if(r==="transparent")return r;var t=w(r);return y(l({},t,{saturation:R(0,1,t.saturation+parseFloat(e))}))}var at=h(nt);function it(e,r){return r==="transparent"?r:y(l({},w(r),{hue:parseFloat(e)}))}var ot=h(it);function ut(e,r){return r==="transparent"?r:y(l({},w(r),{lightness:parseFloat(e)}))}var ft=h(ut);function ct(e,r){return r==="transparent"?r:y(l({},w(r),{saturation:parseFloat(e)}))}var pt=h(ct);function dt(e,r){return r==="transparent"?r:X(parseFloat(e),"rgb(0, 0, 0)",r)}var st=h(dt);function lt(e,r){return r==="transparent"?r:X(parseFloat(e),"rgb(255, 255, 255)",r)}var bt=h(lt);function gt(e,r){if(r==="transparent")return r;var t=A(r),n=typeof t.alpha=="number"?t.alpha:1,a=l({},t,{alpha:R(0,1,+(n*100-parseFloat(e)*100).toFixed(2)/100)});return O(a)}var ht=h(gt);function mt(){for(var e=arguments.length,r=new Array(e),t=0;t8)throw new f(64);var a=r.map(function(i){if(n&&!Array.isArray(i)||!n&&Array.isArray(i))throw new f(65);if(Array.isArray(i)&&i.length>8)throw new f(66);return Array.isArray(i)?i.join(" "):i}).join(", ");return{animation:a}}function vt(){for(var e=arguments.length,r=new Array(e),t=0;t1?r-1:0),n=1;n=0){var a;return a={},a["border"+T(e)+"Width"]=t[0],a["border"+T(e)+"Style"]=t[1],a["border"+T(e)+"Color"]=t[2],a}else return t.unshift(e),{borderWidth:t[0],borderStyle:t[1],borderColor:t[2]}}function zt(){for(var e=arguments.length,r=new Array(e),t=0;t1?r-1:0),n=1;n=0&&e?l({},F.apply(void 0,[""].concat(t)),{position:e}):F.apply(void 0,["",e].concat(t))}function Mt(e,r){return r===void 0&&(r=e),{height:e,width:r}}var $t=[void 0,null,"active","focus","hover"];function Ht(e){return'input[type="color"]'+e+`, + input[type="date"]`+e+`, + input[type="datetime"]`+e+`, + input[type="datetime-local"]`+e+`, + input[type="email"]`+e+`, + input[type="month"]`+e+`, + input[type="number"]`+e+`, + input[type="password"]`+e+`, + input[type="search"]`+e+`, + input[type="tel"]`+e+`, + input[type="text"]`+e+`, + input[type="time"]`+e+`, + input[type="url"]`+e+`, + input[type="week"]`+e+`, + input:not([type])`+e+`, + textarea`+e}function kt(){for(var e=arguments.length,r=new Array(e),t=0;tencodeURIComponent(i).replace(/[!'()*]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`),C="%[a-f0-9]{2}",E=new RegExp(C,"gi"),w=new RegExp("("+C+")+","gi");function h(i,c){try{return decodeURIComponent(i.join(""))}catch(o){}if(i.length===1)return i;c=c||1;var d=i.slice(0,c),g=i.slice(c);return Array.prototype.concat.call([],h(d),h(g))}function D(i){try{return decodeURIComponent(i)}catch(g){for(var c=i.match(E),d=1;d{if(!(typeof i=="string"&&typeof c=="string"))throw new TypeError("Expected the arguments to be of type `string`");if(c==="")return[i];const d=i.indexOf(c);return d===-1?[i]:[i.slice(0,d),i.slice(d+c.length)]},M=function(i,c){for(var d={},g=Object.keys(i),o=Array.isArray(c),y=0;yr==null,g=Symbol("encodeFragmentIdentifier");function o(r){switch(r.arrayFormat){case"index":return e=>(n,t)=>{const a=n.length;return t===void 0||r.skipNull&&t===null||r.skipEmptyString&&t===""?n:t===null?[...n,[u(e,r),"[",a,"]"].join("")]:[...n,[u(e,r),"[",u(a,r),"]=",u(t,r)].join("")]};case"bracket":return e=>(n,t)=>t===void 0||r.skipNull&&t===null||r.skipEmptyString&&t===""?n:t===null?[...n,[u(e,r),"[]"].join("")]:[...n,[u(e,r),"[]=",u(t,r)].join("")];case"comma":case"separator":case"bracket-separator":{const e=r.arrayFormat==="bracket-separator"?"[]=":"=";return n=>(t,a)=>a===void 0||r.skipNull&&a===null||r.skipEmptyString&&a===""?t:(a=a===null?"":a,t.length===0?[[u(n,r),e,u(a,r)].join("")]:[[t,u(a,r)].join(r.arrayFormatSeparator)])}default:return e=>(n,t)=>t===void 0||r.skipNull&&t===null||r.skipEmptyString&&t===""?n:t===null?[...n,u(e,r)]:[...n,[u(e,r),"=",u(t,r)].join("")]}}function y(r){let e;switch(r.arrayFormat){case"index":return(n,t,a)=>{if(e=/\[(\d*)\]$/.exec(n),n=n.replace(/\[\d*\]$/,""),!e){a[n]=t;return}a[n]===void 0&&(a[n]={}),a[n][e[1]]=t};case"bracket":return(n,t,a)=>{if(e=/(\[\])$/.exec(n),n=n.replace(/\[\]$/,""),!e){a[n]=t;return}if(a[n]===void 0){a[n]=[t];return}a[n]=[].concat(a[n],t)};case"comma":case"separator":return(n,t,a)=>{const s=typeof t=="string"&&t.includes(r.arrayFormatSeparator),f=typeof t=="string"&&!s&&F(t,r).includes(r.arrayFormatSeparator);t=f?F(t,r):t;const m=s||f?t.split(r.arrayFormatSeparator).map(U=>F(U,r)):t===null?t:F(t,r);a[n]=m};case"bracket-separator":return(n,t,a)=>{const s=/(\[\])$/.test(n);if(n=n.replace(/\[\]$/,""),!s){a[n]=t&&F(t,r);return}const f=t===null?[]:t.split(r.arrayFormatSeparator).map(m=>F(m,r));if(a[n]===void 0){a[n]=f;return}a[n]=[].concat(a[n],f)};default:return(n,t,a)=>{if(a[n]===void 0){a[n]=t;return}a[n]=[].concat(a[n],t)}}}function l(r){if(typeof r!="string"||r.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function u(r,e){return e.encode?e.strict?$(r):encodeURIComponent(r):r}function F(r,e){return e.decode?q(r):r}function b(r){return Array.isArray(r)?r.sort():typeof r=="object"?b(Object.keys(r)).sort((e,n)=>Number(e)-Number(n)).map(e=>r[e]):r}function O(r){const e=r.indexOf("#");return e!==-1&&(r=r.slice(0,e)),r}function I(r){let e="";const n=r.indexOf("#");return n!==-1&&(e=r.slice(n)),e}function S(r){r=O(r);const e=r.indexOf("?");return e===-1?"":r.slice(e+1)}function j(r,e){return e.parseNumbers&&!Number.isNaN(Number(r))&&typeof r=="string"&&r.trim()!==""?r=Number(r):e.parseBooleans&&r!==null&&(r.toLowerCase()==="true"||r.toLowerCase()==="false")&&(r=r.toLowerCase()==="true"),r}function A(r,e){e=Object.assign({decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1},e),l(e.arrayFormatSeparator);const n=y(e),t=Object.create(null);if(typeof r!="string"||(r=r.trim().replace(/^[?#&]/,""),!r))return t;for(const a of r.split("&")){if(a==="")continue;let[s,f]=N(e.decode?a.replace(/\+/g," "):a,"=");f=f===void 0?null:["comma","separator","bracket-separator"].includes(e.arrayFormat)?f:F(f,e),n(F(s,e),f,t)}for(const a of Object.keys(t)){const s=t[a];if(typeof s=="object"&&s!==null)for(const f of Object.keys(s))s[f]=j(s[f],e);else t[a]=j(s,e)}return e.sort===!1?t:(e.sort===!0?Object.keys(t).sort():Object.keys(t).sort(e.sort)).reduce((a,s)=>{const f=t[s];return Boolean(f)&&typeof f=="object"&&!Array.isArray(f)?a[s]=b(f):a[s]=f,a},Object.create(null))}c.extract=S,c.parse=A,c.stringify=(r,e)=>{if(!r)return"";e=Object.assign({encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:","},e),l(e.arrayFormatSeparator);const n=f=>e.skipNull&&d(r[f])||e.skipEmptyString&&r[f]==="",t=o(e),a={};for(const f of Object.keys(r))n(f)||(a[f]=r[f]);const s=Object.keys(a);return e.sort!==!1&&s.sort(e.sort),s.map(f=>{const m=r[f];return m===void 0?"":m===null?u(f,e):Array.isArray(m)?m.length===0&&e.arrayFormat==="bracket-separator"?u(f,e)+"[]":m.reduce(t(f),[]).join("&"):u(f,e)+"="+u(m,e)}).filter(f=>f.length>0).join("&")},c.parseUrl=(r,e)=>{e=Object.assign({decode:!0},e);const[n,t]=N(r,"#");return Object.assign({url:n.split("?")[0]||"",query:A(S(r),e)},e&&e.parseFragmentIdentifier&&t?{fragmentIdentifier:F(t,e)}:{})},c.stringifyUrl=(r,e)=>{e=Object.assign({encode:!0,strict:!0,[g]:!0},e);const n=O(r.url).split("?")[0]||"",t=c.extract(r.url),a=c.parse(t,{sort:!1}),s=Object.assign(a,r.query);let f=c.stringify(s,e);f&&(f=`?${f}`);let m=I(r.url);return r.fragmentIdentifier&&(m=`#${e[g]?u(r.fragmentIdentifier,e):r.fragmentIdentifier}`),`${n}${f}${m}`},c.pick=(r,e,n)=>{n=Object.assign({parseFragmentIdentifier:!0,[g]:!1},n);const{url:t,query:a,fragmentIdentifier:s}=c.parseUrl(r,n);return c.stringifyUrl({url:t,query:M(a,e),fragmentIdentifier:s},n)},c.exclude=(r,e,n)=>{const t=Array.isArray(e)?a=>!e.includes(a):(a,s)=>!e(a,s);return c.pick(r,t,n)}});export default V; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-content-loader.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-content-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..bb969343a7aa0c897d04093079c25230695c1bc2 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-content-loader.js @@ -0,0 +1,14 @@ +import{r as t}from"./common/index-78959ebc.js";import"./common/_commonjsHelpers-b3efd043.js";/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. 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 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */var i=function(){return i=Object.assign||function(o){for(var n,r=1,a=arguments.length;r0}},{key:"leave",value:function(e){var n=this.entered.length;return this.entered=Z(this.entered.filter(this.isNodeInDocument),e),n>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),r}(),ae=M(function(){return/firefox/i.test(navigator.userAgent)}),X=M(function(){return Boolean(window.safari)});function ie(r,t){if(!(r instanceof t))throw new TypeError("Cannot call a class as a function")}function R(r,t){for(var e=0;ee)d=c-1;else return a[c]}s=Math.max(0,d);var g=e-n[s],p=g*g;return a[s]+i[s]*g+o[s]*p+l[s]*g*p}}]),r}(),se=1;function $(r){var t=r.nodeType===se?r:r.parentElement;if(!t)return null;var e=t.getBoundingClientRect(),n=e.top,a=e.left;return{x:a,y:n}}function C(r){return{x:r.clientX,y:r.clientY}}function ue(r){var t;return r.nodeName==="IMG"&&(ae()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(r)))}function le(r,t,e,n){var a=r?t.width:e,i=r?t.height:n;return X()&&r&&(i/=window.devicePixelRatio,a/=window.devicePixelRatio),{dragPreviewWidth:a,dragPreviewHeight:i}}function fe(r,t,e,n,a){var i=ue(t),o=i?r:t,l=$(o),s={x:e.x-l.x,y:e.y-l.y},f=r.offsetWidth,d=r.offsetHeight,c=n.anchorX,v=n.anchorY,g=le(i,t,f,d),p=g.dragPreviewWidth,D=g.dragPreviewHeight,E=function(){var O=new F([0,.5,1],[s.y,s.y/d*D,s.y+D-d]),I=O.interpolate(v);return X()&&i&&(I+=(window.devicePixelRatio-1)*D),I},S=function(){var O=new F([0,.5,1],[s.x,s.x/f*p,s.x+p-f]);return O.interpolate(c)},T=a.offsetX,m=a.offsetY,h=T===0||T,w=m===0||m;return{x:h?T:S(),y:w?m:E()}}var Y="__NATIVE_FILE__",z="__NATIVE_URL__",B="__NATIVE_TEXT__",j="__NATIVE_HTML__",U=Object.freeze({__proto__:null,FILE:Y,URL:z,TEXT:B,HTML:j});function P(r,t,e){var n=t.reduce(function(a,i){return a||r.getData(i)},"");return n!=null?n:e}var N;function L(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}var _=(N={},L(N,Y,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items}},matchesTypes:["Files"]}),L(N,j,{exposeProperties:{html:function(t,e){return P(t,e,"")}},matchesTypes:["Html","text/html"]}),L(N,z,{exposeProperties:{urls:function(t,e){return P(t,e,"").split(` +`)}},matchesTypes:["Url","text/uri-list"]}),L(N,B,{exposeProperties:{text:function(t,e){return P(t,e,"")}},matchesTypes:["Text","text/plain"]}),N);function de(r,t){if(!(r instanceof t))throw new TypeError("Cannot call a class as a function")}function W(r,t){for(var e=0;e-1})})[0]||null}function he(r,t){if(!(r instanceof t))throw new TypeError("Cannot call a class as a function")}function V(r,t){for(var e=0;e0&&a.actions.hover(o,{clientOffset:C(i)});var l=o.some(function(s){return a.monitor.canDropOnTarget(s)});l&&(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect=a.getCurrentDropEffect()))}}),u(this,"handleTopDragOverCapture",function(){a.dragOverTargetIds=[]}),u(this,"handleTopDragOver",function(i){var o=a.dragOverTargetIds;if(a.dragOverTargetIds=[],!a.monitor.isDragging()){i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="none");return}a.altKeyPressed=i.altKey,a.actions.hover(o||[],{clientOffset:C(i)});var l=(o||[]).some(function(s){return a.monitor.canDropOnTarget(s)});l?(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect=a.getCurrentDropEffect())):a.isDraggingNativeItem()?i.preventDefault():(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="none"))}),u(this,"handleTopDragLeaveCapture",function(i){a.isDraggingNativeItem()&&i.preventDefault();var o=a.enterLeaveCounter.leave(i.target);!o||a.isDraggingNativeItem()&&setTimeout(function(){return a.endDragNativeItem()},0)}),u(this,"handleTopDropCapture",function(i){if(a.dropTargetIds=[],a.isDraggingNativeItem()){var o;i.preventDefault(),(o=a.currentNativeSource)===null||o===void 0||o.loadDataTransfer(i.dataTransfer)}else k(i.dataTransfer)&&i.preventDefault();a.enterLeaveCounter.reset()}),u(this,"handleTopDrop",function(i){var o=a.dropTargetIds;a.dropTargetIds=[],a.actions.hover(o,{clientOffset:C(i)}),a.actions.drop({dropEffect:a.getCurrentDropEffect()}),a.isDraggingNativeItem()?a.endDragNativeItem():a.monitor.isDragging()&&a.actions.endDrag()}),u(this,"handleSelectStart",function(i){var o=i.target;typeof o.dragDrop=="function"&&(o.tagName==="INPUT"||o.tagName==="SELECT"||o.tagName==="TEXTAREA"||o.isContentEditable||(i.preventDefault(),o.dragDrop()))}),this.options=new me(e,n),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new ne(this.isNodeInDocument)}return Te(r,[{key:"profile",value:function(){var e,n;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((e=this.dragStartSourceIds)===null||e===void 0?void 0:e.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((n=this.dragOverTargetIds)===null||n===void 0?void 0:n.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var e=this.rootElement;if(e!==void 0){if(e.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");e.__isReactDndBackendSetUp=!0,this.addEventListeners(e)}}},{key:"teardown",value:function(){var e=this.rootElement;if(e!==void 0&&(e.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var n;(n=this.window)===null||n===void 0||n.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(e,n,a){var i=this;return this.sourcePreviewNodeOptions.set(e,a),this.sourcePreviewNodes.set(e,n),function(){i.sourcePreviewNodes.delete(e),i.sourcePreviewNodeOptions.delete(e)}}},{key:"connectDragSource",value:function(e,n,a){var i=this;this.sourceNodes.set(e,n),this.sourceNodeOptions.set(e,a);var o=function(f){return i.handleDragStart(f,e)},l=function(f){return i.handleSelectStart(f)};return n.setAttribute("draggable","true"),n.addEventListener("dragstart",o),n.addEventListener("selectstart",l),function(){i.sourceNodes.delete(e),i.sourceNodeOptions.delete(e),n.removeEventListener("dragstart",o),n.removeEventListener("selectstart",l),n.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(e,n){var a=this,i=function(f){return a.handleDragEnter(f,e)},o=function(f){return a.handleDragOver(f,e)},l=function(f){return a.handleDrop(f,e)};return n.addEventListener("dragenter",i),n.addEventListener("dragover",o),n.addEventListener("drop",l),function(){n.removeEventListener("dragenter",i),n.removeEventListener("dragover",o),n.removeEventListener("drop",l)}}},{key:"addEventListeners",value:function(e){!e.addEventListener||(e.addEventListener("dragstart",this.handleTopDragStart),e.addEventListener("dragstart",this.handleTopDragStartCapture,!0),e.addEventListener("dragend",this.handleTopDragEndCapture,!0),e.addEventListener("dragenter",this.handleTopDragEnter),e.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.addEventListener("dragover",this.handleTopDragOver),e.addEventListener("dragover",this.handleTopDragOverCapture,!0),e.addEventListener("drop",this.handleTopDrop),e.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(e){!e.removeEventListener||(e.removeEventListener("dragstart",this.handleTopDragStart),e.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),e.removeEventListener("dragend",this.handleTopDragEndCapture,!0),e.removeEventListener("dragenter",this.handleTopDragEnter),e.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.removeEventListener("dragover",this.handleTopDragOver),e.removeEventListener("dragover",this.handleTopDragOverCapture,!0),e.removeEventListener("drop",this.handleTopDrop),e.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var e=this.monitor.getSourceId(),n=this.sourceNodeOptions.get(e);return G({dropEffect:this.altKeyPressed?"copy":"move"},n||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var e=this.monitor.getSourceId(),n=this.sourcePreviewNodeOptions.get(e);return G({anchorX:.5,anchorY:.5,captureDraggingState:!1},n||{})}},{key:"isDraggingNativeItem",value:function(){var e=this.monitor.getItemType();return Object.keys(U).some(function(n){return U[n]===e})}},{key:"beginDragNativeItem",value:function(e,n){this.clearCurrentDragSourceNode(),this.currentNativeSource=ge(e,n),this.currentNativeHandle=this.registry.addSource(e,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(e){var n=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=e;var a=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var i;return(i=n.rootElement)===null||i===void 0?void 0:i.addEventListener("mousemove",n.endDragIfSourceWasRemovedFromDOM,!0)},a)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var e;(e=this.window)===null||e===void 0||e.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(e,n){e.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(n))}},{key:"handleDragEnter",value:function(e,n){this.dragEnterTargetIds.unshift(n)}},{key:"handleDragOver",value:function(e,n){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(n)}},{key:"handleDrop",value:function(e,n){this.dropTargetIds.unshift(n)}}]),r}(),ye=function(t,e,n){return new Ee(t,e,n)};export{ye as HTML5Backend}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-dnd.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-dnd.js new file mode 100644 index 0000000000000000000000000000000000000000..cd77df0a705319d412bfa56b9c484d82f22bcc43 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-dnd.js @@ -0,0 +1,8 @@ +import{r as f}from"./common/index-78959ebc.js";import{c as ne}from"./common/_commonjsHelpers-b3efd043.js";import{c as Be}from"./common/redux-ea100ce9.js";var ie=f.createContext({dragDropManager:void 0}),C=typeof C!="undefined"?C:typeof self!="undefined"?self:typeof window!="undefined"?window:{},Ye=ne(function(e,r){var t=60103;if(r.Fragment=60107,typeof Symbol=="function"&&Symbol.for){var n=Symbol.for;t=n("react.element"),r.Fragment=n("react.fragment")}var i=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a=Object.prototype.hasOwnProperty,o={key:!0,ref:!0,__self:!0,__source:!0};function u(s,l,g){var d,D={},O=null,I=null;g!==void 0&&(O=""+g),l.key!==void 0&&(O=""+l.key),l.ref!==void 0&&(I=l.ref);for(d in l)a.call(l,d)&&!o.hasOwnProperty(d)&&(D[d]=l[d]);if(s&&s.defaultProps)for(d in l=s.defaultProps,l)D[d]===void 0&&(D[d]=l[d]);return{$$typeof:t,type:s,key:O,ref:I,props:D,_owner:i.current}}r.jsx=u,r.jsxs=u}),Ke=ne(function(e){e.exports=Ye}),h;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(h||(h={}));function c(e,r){for(var t=arguments.length,n=new Array(t>2?t-2:0),i=2;i-1})}var Ze={type:G,payload:{clientOffset:null,sourceClientOffset:null}};function et(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},i=n.publishSource,a=i===void 0?!0:i,o=n.clientOffset,u=n.getSourceClientOffset,s=e.getMonitor(),l=e.getRegistry();e.dispatch(ae(o)),tt(t,s,l);var g=it(t,s);if(g===null){e.dispatch(Ze);return}var d=null;if(o){if(!u)throw new Error("getSourceClientOffset must be defined");rt(u),d=u(g)}e.dispatch(ae(o,d));var D=l.getSource(g),O=D.beginDrag(s,g);if(O!=null){nt(O),l.pinSource(g);var I=l.getSourceType(g);return{type:w,payload:{itemType:I,item:O,sourceId:g,clientOffset:o||null,sourceClientOffset:d||null,isSourcePublic:!!a}}}}}function tt(e,r,t){c(!r.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(n){c(t.getSource(n),"Expected sourceIds to be registered.")})}function rt(e){c(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function nt(e){c(oe(e),"Item must be an object.")}function it(e,r){for(var t=null,n=e.length-1;n>=0;n--)if(r.canDragSource(e[n])){t=e[n];break}return t}function at(e){return function(){var t=e.getMonitor();if(t.isDragging())return{type:q}}}function F(e,r){return r===null?e===null:Array.isArray(e)?e.some(function(t){return t===r}):e===r}function ot(e){return function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.clientOffset;ut(t);var a=t.slice(0),o=e.getMonitor(),u=e.getRegistry();st(a,o,u);var s=o.getItemType();return ct(a,u,s),lt(a,o,u),{type:_,payload:{targetIds:a,clientOffset:i||null}}}}function ut(e){c(Array.isArray(e),"Expected targetIds to be an array.")}function st(e,r,t){c(r.isDragging(),"Cannot call hover while not dragging."),c(!r.didDrop(),"Cannot call hover after drop.");for(var n=0;n=0;n--){var i=e[n],a=r.getTargetType(i);F(a,t)||e.splice(n,1)}}function lt(e,r,t){e.forEach(function(n){var i=t.getTarget(n);i.hover(r,n)})}function ue(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),t.push.apply(t,n)}return t}function se(e){for(var r=1;r0&&arguments[0]!==void 0?arguments[0]:{},n=e.getMonitor(),i=e.getRegistry();dt(n);var a=vt(n);a.forEach(function(o,u){var s=pt(o,u,i,n),l={type:k,payload:{dropResult:se(se({},t),s)}};e.dispatch(l)})}}function dt(e){c(e.isDragging(),"Cannot call drop while not dragging."),c(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function pt(e,r,t,n){var i=t.getTarget(e),a=i?i.drop(n,e):void 0;return ht(a),typeof a=="undefined"&&(a=r===0?{}:n.getDropResult()),a}function ht(e){c(typeof e=="undefined"||oe(e),"Drop result must either be an object or undefined.")}function vt(e){var r=e.getTargetIds().filter(e.canDropOnTarget,e);return r.reverse(),r}function yt(e){return function(){var t=e.getMonitor(),n=e.getRegistry();mt(t);var i=t.getSourceId();if(i!=null){var a=n.getSource(i,!0);a.endDrag(t,i),n.unpinSource()}return{type:P}}}function mt(e){c(e.isDragging(),"Cannot call endDrag while not dragging.")}function bt(e){return{beginDrag:et(e),publishDragSource:at(e),hover:ot(e),drop:gt(e),endDrag:yt(e)}}function Ot(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function ce(e,r){for(var t=0;t0;n.backend&&(i&&!n.isSetUp?(n.backend.setup(),n.isSetUp=!0):!i&&n.isSetUp&&(n.backend.teardown(),n.isSetUp=!1))},this.store=r,this.monitor=t,r.subscribe(this.handleRefCountChange)}return St(e,[{key:"receiveBackend",value:function(t){this.backend=t}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var t=this,n=this.store.dispatch;function i(o){return function(){for(var u=arguments.length,s=new Array(u),l=0;l2&&arguments[2]!==void 0?arguments[2]:Tt;if(e.length!==r.length)return!1;for(var n=0;n0&&arguments[0]!==void 0?arguments[0]:ge,r=arguments.length>1?arguments[1]:void 0,t=r.payload;switch(r.type){case G:case w:return{initialSourceClientOffset:t.sourceClientOffset,initialClientOffset:t.clientOffset,clientOffset:t.clientOffset};case _:return It(e.clientOffset,t.clientOffset)?e:fe(fe({},e),{},{clientOffset:t.clientOffset});case P:case k:return ge;default:return e}}var L="dnd-core/ADD_SOURCE",V="dnd-core/ADD_TARGET",W="dnd-core/REMOVE_SOURCE",R="dnd-core/REMOVE_TARGET";function kt(e){return{type:L,payload:{sourceId:e}}}function Pt(e){return{type:V,payload:{targetId:e}}}function Et(e){return{type:W,payload:{sourceId:e}}}function Rt(e){return{type:R,payload:{targetId:e}}}function de(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),t.push.apply(t,n)}return t}function v(e){for(var r=1;r0&&arguments[0]!==void 0?arguments[0]:Mt,r=arguments.length>1?arguments[1]:void 0,t=r.payload;switch(r.type){case w:return v(v({},e),{},{itemType:t.itemType,item:t.item,sourceId:t.sourceId,isSourcePublic:t.isSourcePublic,dropResult:null,didDrop:!1});case q:return v(v({},e),{},{isSourcePublic:!0});case _:return v(v({},e),{},{targetIds:t.targetIds});case R:return e.targetIds.indexOf(t.targetId)===-1?e:v(v({},e),{},{targetIds:ze(e.targetIds,t.targetId)});case k:return v(v({},e),{},{dropResult:t.dropResult,didDrop:!0,targetIds:[]});case P:return v(v({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function xt(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,r=arguments.length>1?arguments[1]:void 0;switch(r.type){case L:case V:return e+1;case W:case R:return e-1;default:return e}}var A=[],B=[];A.__IS_NONE__=!0,B.__IS_ALL__=!0;function jt(e,r){if(e===A)return!1;if(e===B||typeof r=="undefined")return!0;var t=Qe(r,e);return t.length>0}function Ht(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case _:break;case L:case V:case R:case W:return A;case w:case q:case P:case k:default:return B}var r=e.payload,t=r.targetIds,n=t===void 0?[]:t,i=r.prevTargetIds,a=i===void 0?[]:i,o=Je(n,a),u=o.length>0||!Ct(n,a);if(!u)return A;var s=a[a.length-1],l=n[n.length-1];return s!==l&&(s&&o.push(s),l&&o.push(l)),o}function Nt(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function pe(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),t.push.apply(t,n)}return t}function he(e){for(var r=1;r0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:Ht(e.dirtyHandlerIds,{type:r.type,payload:he(he({},r.payload),{},{prevTargetIds:Xe(e,"dragOperation.targetIds",[])})}),dragOffset:_t(e.dragOffset,r),refCount:xt(e.refCount,r),dragOperation:$t(e.dragOperation,r),stateId:Nt(e.stateId)}}function qt(e,r){return{x:e.x+r.x,y:e.y+r.y}}function ve(e,r){return{x:e.x-r.x,y:e.y-r.y}}function Ft(e){var r=e.clientOffset,t=e.initialClientOffset,n=e.initialSourceClientOffset;return!r||!t||!n?null:ve(qt(r,n),t)}function Lt(e){var r=e.clientOffset,t=e.initialClientOffset;return!r||!t?null:ve(r,t)}function Vt(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function ye(e,r){for(var t=0;t1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},a=i.handlerIds;c(typeof t=="function","listener must be a function."),c(typeof a=="undefined"||Array.isArray(a),"handlerIds, when specified, must be an array of strings.");var o=this.store.getState().stateId,u=function(){var l=n.store.getState(),g=l.stateId;try{var d=g===o||g===o+1&&!jt(l.dirtyHandlerIds,a);d||t()}finally{o=g}};return this.store.subscribe(u)}},{key:"subscribeToOffsetChange",value:function(t){var n=this;c(typeof t=="function","listener must be a function.");var i=this.store.getState().dragOffset,a=function(){var u=n.store.getState().dragOffset;u!==i&&(i=u,t())};return this.store.subscribe(a)}},{key:"canDragSource",value:function(t){if(!t)return!1;var n=this.registry.getSource(t);return c(n,"Expected to find a valid source. sourceId=".concat(t)),this.isDragging()?!1:n.canDrag(this,t)}},{key:"canDropOnTarget",value:function(t){if(!t)return!1;var n=this.registry.getTarget(t);if(c(n,"Expected to find a valid target. targetId=".concat(t)),!this.isDragging()||this.didDrop())return!1;var i=this.registry.getTargetType(t),a=this.getItemType();return F(i,a)&&n.canDrop(this,t)}},{key:"isDragging",value:function(){return Boolean(this.getItemType())}},{key:"isDraggingSource",value:function(t){if(!t)return!1;var n=this.registry.getSource(t,!0);if(c(n,"Expected to find a valid source. sourceId=".concat(t)),!this.isDragging()||!this.isSourcePublic())return!1;var i=this.registry.getSourceType(t),a=this.getItemType();return i!==a?!1:n.isDragging(this,t)}},{key:"isOverTarget",value:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!t)return!1;var i=n.shallow;if(!this.isDragging())return!1;var a=this.registry.getTargetType(t),o=this.getItemType();if(o&&!F(a,o))return!1;var u=this.getTargetIds();if(!u.length)return!1;var s=u.indexOf(t);return i?s===u.length-1:s>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return Boolean(this.store.getState().dragOperation.isSourcePublic)}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return Ft(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return Lt(this.store.getState().dragOffset)}}]),e}(),Yt=0;function Kt(){return Yt++}function M(e){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?M=function(t){return typeof t}:M=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},M(e)}function Xt(e){c(typeof e.canDrag=="function","Expected canDrag to be a function."),c(typeof e.beginDrag=="function","Expected beginDrag to be a function."),c(typeof e.endDrag=="function","Expected endDrag to be a function.")}function zt(e){c(typeof e.canDrop=="function","Expected canDrop to be a function."),c(typeof e.hover=="function","Expected hover to be a function."),c(typeof e.drop=="function","Expected beginDrag to be a function.")}function Y(e,r){if(r&&Array.isArray(e)){e.forEach(function(t){return Y(t,!1)});return}c(typeof e=="string"||M(e)==="symbol",r?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}function $(e){y.length||x(),y[y.length]=e}var y=[],x,m=0,Jt=1024;function me(){for(;mJt){for(var r=0,t=y.length-m;re.length)&&(r=e.length);for(var t=0,n=new Array(r);t1&&arguments[1]!==void 0?arguments[1]:!1;c(this.isSourceId(t),"Expected a valid source ID.");var i=n&&t===this.pinnedSourceId,a=i?this.pinnedSource:this.dragSources.get(t);return a}},{key:"getTarget",value:function(t){return c(this.isTargetId(t),"Expected a valid target ID."),this.dropTargets.get(t)}},{key:"getSourceType",value:function(t){return c(this.isSourceId(t),"Expected a valid source ID."),this.types.get(t)}},{key:"getTargetType",value:function(t){return c(this.isTargetId(t),"Expected a valid target ID."),this.types.get(t)}},{key:"isSourceId",value:function(t){var n=Ie(t);return n===h.SOURCE}},{key:"isTargetId",value:function(t){var n=Ie(t);return n===h.TARGET}},{key:"removeSource",value:function(t){var n=this;c(this.getSource(t),"Expected an existing source."),this.store.dispatch(Et(t)),X(function(){n.dragSources.delete(t),n.types.delete(t)})}},{key:"removeTarget",value:function(t){c(this.getTarget(t),"Expected an existing target."),this.store.dispatch(Rt(t)),this.dropTargets.delete(t),this.types.delete(t)}},{key:"pinSource",value:function(t){var n=this.getSource(t);c(n,"Expected an existing source."),this.pinnedSourceId=t,this.pinnedSource=n}},{key:"unpinSource",value:function(){c(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(t,n,i){var a=cr(t);return this.types.set(a,n),t===h.SOURCE?this.dragSources.set(a,i):t===h.TARGET&&this.dropTargets.set(a,i),a}}]),e}();function fr(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=gr(n),a=new Bt(i,new lr(i)),o=new Dt(i,a),u=e(o,r,t);return o.receiveBackend(u),o}function gr(e){var r=typeof window!="undefined"&&window.__REDUX_DEVTOOLS_EXTENSION__;return Be(Gt,e&&r&&r({name:"dnd-core",instanceId:"dnd-core"}))}var dr=["children"];function pr(e,r){return mr(e)||yr(e,r)||vr(e,r)||hr()}function hr(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vr(e,r){if(!!e){if(typeof e=="string")return we(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);if(t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set")return Array.from(e);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return we(e,r)}}function we(e,r){(r==null||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=0)&&(!Object.prototype.propertyIsEnumerable.call(e,n)||(t[n]=e[n]))}return t}function Or(e,r){if(e==null)return{};var t={},n=Object.keys(e),i,a;for(a=0;a=0)&&(t[i]=e[i]);return t}var _e=0,H=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),Sr=f.memo(function(r){var t=r.children,n=br(r,dr),i=Dr(n),a=pr(i,2),o=a[0],u=a[1];return f.useEffect(function(){if(u){var s=ke();return++_e,function(){--_e==0&&(s[H]=null)}}},[]),Ke.jsx(ie.Provider,Object.assign({value:o},{children:t}),void 0)});function Dr(e){if("manager"in e){var r={dragDropManager:e.manager};return[r,!1]}var t=Tr(e.backend,e.context,e.options,e.debugMode),n=!e.context;return[t,n]}function Tr(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ke(),t=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,i=r;return i[H]||(i[H]={dragDropManager:fr(e,r,t,n)}),i[H]}function ke(){return typeof C!="undefined"?C:window}function Ir(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function Pe(e,r){for(var t=0;t, or turn it into a ")+"drag source or a drop target itself.")}}function Rr(e){return function(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!f.isValidElement(r)){var n=r;return e(n,t),n}var i=r;Er(i);var a=t?function(o){return e(o,t)}:e;return Ar(i,a)}}function Me(e){var r={};return Object.keys(e).forEach(function(t){var n=e[t];if(t.endsWith("Ref"))r[t]=e[t];else{var i=Rr(n);r[t]=function(){return i}}}),r}function $e(e,r){typeof e=="function"?e(r):e.current=r}function Ar(e,r){var t=e.ref;return c(typeof t!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
    . Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),t?f.cloneElement(e,{ref:function(i){$e(t,i),$e(r,i)}}):f.cloneElement(e,{ref:r})}function N(e){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?N=function(t){return typeof t}:N=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},N(e)}function Z(e){return e!==null&&N(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ee(e,r,t,n){var i=t?t.call(n,e,r):void 0;if(i!==void 0)return!!i;if(e===r)return!0;if(typeof e!="object"||!e||typeof r!="object"||!r)return!1;var a=Object.keys(e),o=Object.keys(r);if(a.length!==o.length)return!1;for(var u=Object.prototype.hasOwnProperty.bind(r),s=0;se.length)&&(r=e.length);for(var t=0,n=new Array(r);te.length)&&(r=e.length);for(var t=0,n=new Array(r);te.length)&&(r=e.length);for(var t=0,n=new Array(r);te.length)&&(r=e.length);for(var t=0,n=new Array(r);te.length)&&(r=e.length);for(var t=0,n=new Array(r);tU;U++)v[U]=U+1;v[15]=0;var Ne=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,pe=Object.prototype.hasOwnProperty,he={},de={};function me(e){return pe.call(de,e)?!0:pe.call(he,e)?!1:Ne.test(e)?de[e]=!0:(he[e]=!0,!1)}function Me(e,r,t,o){if(t!==null&&t.type===0)return!1;switch(typeof r){case"function":case"symbol":return!0;case"boolean":return o?!1:t!==null?!t.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Oe(e,r,t,o){if(r===null||typeof r=="undefined"||Me(e,r,t,o))return!0;if(o)return!1;if(t!==null)switch(t.type){case 3:return!r;case 4:return r===!1;case 5:return isNaN(r);case 6:return isNaN(r)||1>r}return!1}function x(e,r,t,o,u,l,i){this.acceptsBooleans=r===2||r===3||r===4,this.attributeName=o,this.attributeNamespace=u,this.mustUseProperty=t,this.propertyName=e,this.type=r,this.sanitizeURL=l,this.removeEmptyString=i}var d={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){d[e]=new x(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var r=e[0];d[r]=new x(r,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){d[e]=new x(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){d[e]=new x(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){d[e]=new x(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){d[e]=new x(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){d[e]=new x(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){d[e]=new x(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){d[e]=new x(e,5,!1,e.toLowerCase(),null,!1,!1)});var ee=/[\-:]([a-z])/g;function te(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var r=e.replace(ee,te);d[r]=new x(r,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var r=e.replace(ee,te);d[r]=new x(r,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var r=e.replace(ee,te);d[r]=new x(r,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){d[e]=new x(e,1,!1,e.toLowerCase(),null,!1,!1)}),d.xlinkHref=new x("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){d[e]=new x(e,1,!1,e.toLowerCase(),null,!0,!0)});var be=/["'&<>]/;function O(e){if(typeof e=="boolean"||typeof e=="number")return""+e;e=""+e;var r=be.exec(e);if(r){var t="",o,u=0;for(o=r.index;o$))throw Error(p(301));if(e===D)if(A=!0,e={action:t,next:null},N===null&&(N=new Map),t=N.get(r),t===void 0)N.set(r,e);else{for(r=t;r.next!==null;)r=r.next;r.next=e}}function ne(){}var P=null,Ve={readContext:function(e){var r=P.threadID;return z(e,r),e[r]},useContext:function(e){b();var r=P.threadID;return z(e,r),e[r]},useMemo:Se,useReducer:ge,useRef:function(e){D=b(),c=re();var r=c.memoizedState;return r===null?(e={current:e},c.memoizedState=e):r},useState:function(e){return ge(xe,e)},useLayoutEffect:function(){},useCallback:function(e,r){return Se(function(){return e},r)},useImperativeHandle:ne,useEffect:ne,useDebugValue:ne,useDeferredValue:function(e){return b(),e},useTransition:function(){return b(),[function(e){e()},!1]},useOpaqueIdentifier:function(){return(P.identifierPrefix||"")+"R:"+(P.uniqueID++).toString(36)},useMutableSource:function(e,r){return b(),r(e._source)}},Le={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function We(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}var ke={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},je=E({menuitem:!0},ke),V={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ue=["Webkit","ms","Moz","O"];Object.keys(V).forEach(function(e){Ue.forEach(function(r){r=r+e.charAt(0).toUpperCase()+e.substring(1),V[r]=V[e]})});var qe=/([A-Z])/g,Ae=/^ms-/,M=C.Children.toArray,oe=Ce.ReactCurrentDispatcher,$e={listing:!0,pre:!0,textarea:!0},He=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Fe={},ie={};function Ze(e){if(e==null)return e;var r="";return C.Children.forEach(e,function(t){t!=null&&(r+=t)}),r}var Be=Object.prototype.hasOwnProperty,Xe={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null,suppressHydrationWarning:null};function Ie(e,r){if(e===void 0)throw Error(p(152,T(r)||"Component"))}function Ye(e,r,t){function o(i,a){var n=a.prototype&&a.prototype.isReactComponent,S=_e(a,r,t,n),h=[],g=!1,f={isMounted:function(){return!1},enqueueForceUpdate:function(){if(h===null)return null},enqueueReplaceState:function(H,m){g=!0,h=[m]},enqueueSetState:function(H,m){if(h===null)return null;h.push(m)}};if(n){if(n=new a(i.props,S,f),typeof a.getDerivedStateFromProps=="function"){var s=a.getDerivedStateFromProps.call(null,i.props,n.state);s!=null&&(n.state=E({},n.state,s))}}else if(D={},n=a(i.props,S,f),n=ve(a,i.props,n,S),n==null||n.render==null){e=n,Ie(e,a);return}if(n.props=i.props,n.context=S,n.updater=f,f=n.state,f===void 0&&(n.state=f=null),typeof n.UNSAFE_componentWillMount=="function"||typeof n.componentWillMount=="function")if(typeof n.componentWillMount=="function"&&typeof a.getDerivedStateFromProps!="function"&&n.componentWillMount(),typeof n.UNSAFE_componentWillMount=="function"&&typeof a.getDerivedStateFromProps!="function"&&n.UNSAFE_componentWillMount(),h.length){f=h;var w=g;if(h=null,g=!1,w&&f.length===1)n.state=f[0];else{s=w?f[0]:n.state;var _=!0;for(w=w?1:0;w=a))throw Error(p(304));var n=new Uint16Array(a);for(n.set(i),v=n,v[0]=l+1,i=l;i=n.children.length){var S=n.footer;if(S!==""&&(this.previousWasTextNode=!1),this.stack.pop(),n.type==="select")this.currentSelectValue=null;else if(n.type!=null&&n.type.type!=null&&n.type.type.$$typeof===W)this.popProvider(n.type);else if(n.type===j){this.suspenseDepth--;var h=l.pop();if(i){i=!1;var g=n.fallbackFrame;if(!g)throw Error(p(303));this.stack.push(g),l[this.suspenseDepth]+="";continue}else l[this.suspenseDepth]+=h}l[this.suspenseDepth]+=S}else{var f=n.children[n.childIndex++],s="";try{s+=this.render(f,n.context,n.domNamespace)}catch(w){throw w!=null&&typeof w.then=="function"?Error(p(294)):w}finally{}l.length<=this.suspenseDepth&&l.push(""),l[this.suspenseDepth]+=s}}return l[0]}finally{oe.current=u,P=o,we()}},r.render=function(t,o,u){if(typeof t=="string"||typeof t=="number")return u=""+t,u===""?"":this.makeStaticMarkup?O(u):this.previousWasTextNode?""+O(u):(this.previousWasTextNode=!0,O(u));if(o=Ye(t,o,this.threadID),t=o.child,o=o.context,t===null||t===!1)return"";if(!C.isValidElement(t)){if(t!=null&&t.$$typeof!=null)throw u=t.$$typeof,Error(u===Z?p(257):p(258,u.toString()));return t=M(t),this.stack.push({type:null,domNamespace:u,children:t,childIndex:0,context:o,footer:""}),""}var l=t.type;if(typeof l=="string")return this.renderDOM(t,o,u);switch(l){case ce:case se:case B:case X:case G:case L:return t=M(t.props.children),this.stack.push({type:null,domNamespace:u,children:t,childIndex:0,context:o,footer:""}),"";case j:throw Error(p(294));case ae:throw Error(p(343))}if(typeof l=="object"&&l!==null)switch(l.$$typeof){case Q:D={};var i=l.render(t.props,t.ref);return i=ve(l.render,t.props,i,t.ref),i=M(i),this.stack.push({type:null,domNamespace:u,children:i,childIndex:0,context:o,footer:""}),"";case K:return t=[C.createElement(l.type,E({ref:t.ref},t.props))],this.stack.push({type:null,domNamespace:u,children:t,childIndex:0,context:o,footer:""}),"";case W:return l=M(t.props.children),u={type:t,domNamespace:u,children:l,childIndex:0,context:o,footer:""},this.pushProvider(t),this.stack.push(u),"";case Y:l=t.type,i=t.props;var a=this.threadID;return z(l,a),l=M(i.children(l[a])),this.stack.push({type:t,domNamespace:u,children:l,childIndex:0,context:o,footer:""}),"";case ue:throw Error(p(338));case J:return l=t.type,i=l._init,l=i(l._payload),t=[C.createElement(l,E({ref:t.ref},t.props))],this.stack.push({type:null,domNamespace:u,children:t,childIndex:0,context:o,footer:""}),""}throw Error(p(130,l==null?l:typeof l,""))},r.renderDOM=function(t,o,u){var l=t.type.toLowerCase();if(!Fe.hasOwnProperty(l)){if(!He.test(l))throw Error(p(65,l));Fe[l]=!0}var i=t.props;if(l==="input")i=E({type:void 0},i,{defaultChecked:void 0,defaultValue:void 0,value:i.value!=null?i.value:i.defaultValue,checked:i.checked!=null?i.checked:i.defaultChecked});else if(l==="textarea"){var a=i.value;if(a==null){a=i.defaultValue;var n=i.children;if(n!=null){if(a!=null)throw Error(p(92));if(Array.isArray(n)){if(!(1>=n.length))throw Error(p(93));n=n[0]}a=""+n}a==null&&(a="")}i=E({},i,{value:void 0,children:""+a})}else if(l==="select")this.currentSelectValue=i.value!=null?i.value:i.defaultValue,i=E({},i,{value:void 0});else if(l==="option"){n=this.currentSelectValue;var S=Ze(i.children);if(n!=null){var h=i.value!=null?i.value+"":S;if(a=!1,Array.isArray(n)){for(var g=0;g":(m+=">",a="");e:{if(n=i.dangerouslySetInnerHTML,n!=null){if(n.__html!=null){n=n.__html;break e}}else if(n=i.children,typeof n=="string"||typeof n=="number"){n=O(n);break e}n=null}return n!=null?(i=[],$e.hasOwnProperty(l)&&n.charAt(0)===` +`&&(m+=` +`),m+=n):i=M(i.children),t=t.type,u=u==null||u==="http://www.w3.org/1999/xhtml"?We(t):u==="http://www.w3.org/2000/svg"&&t==="foreignObject"?"http://www.w3.org/1999/xhtml":u,this.stack.push({domNamespace:u,type:l,children:i,childIndex:0,context:o,footer:a}),this.previousWasTextNode=!1,m},e}(),Qe=function(){throw Error(p(207))},Ge=function(e,r){e=new Ee(e,!0,r);try{return e.read(Infinity)}finally{e.destroy()}},Ke=function(){throw Error(p(208))},Je=function(e,r){e=new Ee(e,!1,r);try{return e.read(Infinity)}finally{e.destroy()}},et="17.0.2",tt={renderToNodeStream:Qe,renderToStaticMarkup:Ge,renderToStaticNodeStream:Ke,renderToString:Je,version:et},rt=De(function(e){e.exports=tt}),nt=rt.renderToStaticMarkup;export{nt as renderToStaticMarkup}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-helmet.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-helmet.js new file mode 100644 index 0000000000000000000000000000000000000000..12512f90dd7f3590a971625ffe3ae1bb1cea19dc --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-helmet.js @@ -0,0 +1 @@ +import{p as m}from"./common/index-55e7d60e.js";import{r as b,o as W}from"./common/index-78959ebc.js";import"./common/_commonjsHelpers-b3efd043.js";function Q(r){return r&&typeof r=="object"&&"default"in r?r.default:r}var J=Q(b);function U(r,e,n){return e in r?Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[e]=n,r}function Z(r,e){r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.__proto__=e}var K=!!(typeof window!="undefined"&&window.document&&window.document.createElement);function ee(r,e,n){if(typeof r!="function")throw new Error("Expected reducePropsToState to be a function.");if(typeof e!="function")throw new Error("Expected handleStateChangeOnClient to be a function.");if(typeof n!="undefined"&&typeof n!="function")throw new Error("Expected mapStateOnServer to either be undefined or a function.");function t(o){return o.displayName||o.name||"Component"}return function(i){if(typeof i!="function")throw new Error("Expected WrappedComponent to be a React component.");var s=[],u;function a(){u=r(s.map(function(f){return f.props})),c.canUseDOM?e(u):n&&(u=n(u))}var c=function(f){Z(d,f);function d(){return f.apply(this,arguments)||this}d.peek=function(){return u},d.rewind=function(){if(d.canUseDOM)throw new Error("You may only call rewind() on the server. Call peek() to read the current state.");var y=u;return u=void 0,s=[],y};var p=d.prototype;return p.UNSAFE_componentWillMount=function(){s.push(this),a()},p.componentDidUpdate=function(){a()},p.componentWillUnmount=function(){var y=s.indexOf(this);s.splice(y,1),a()},p.render=function(){return J.createElement(i,this.props)},d}(b.PureComponent);return U(c,"displayName","SideEffect("+t(i)+")"),U(c,"canUseDOM",K),c}}var te=ee,re=typeof Element!="undefined",ne=typeof Map=="function",oe=typeof Set=="function",ie=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function M(r,e){if(r===e)return!0;if(r&&e&&typeof r=="object"&&typeof e=="object"){if(r.constructor!==e.constructor)return!1;var n,t,o;if(Array.isArray(r)){if(n=r.length,n!=e.length)return!1;for(t=n;t--!=0;)if(!M(r[t],e[t]))return!1;return!0}var i;if(ne&&r instanceof Map&&e instanceof Map){if(r.size!==e.size)return!1;for(i=r.entries();!(t=i.next()).done;)if(!e.has(t.value[0]))return!1;for(i=r.entries();!(t=i.next()).done;)if(!M(t.value[1],e.get(t.value[0])))return!1;return!0}if(oe&&r instanceof Set&&e instanceof Set){if(r.size!==e.size)return!1;for(i=r.entries();!(t=i.next()).done;)if(!e.has(t.value[0]))return!1;return!0}if(ie&&ArrayBuffer.isView(r)&&ArrayBuffer.isView(e)){if(n=r.length,n!=e.length)return!1;for(t=n;t--!=0;)if(r[t]!==e[t])return!1;return!0}if(r.constructor===RegExp)return r.source===e.source&&r.flags===e.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===e.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===e.toString();if(o=Object.keys(r),n=o.length,n!==Object.keys(e).length)return!1;for(t=n;t--!=0;)if(!Object.prototype.hasOwnProperty.call(e,o[t]))return!1;if(re&&r instanceof Element)return!1;for(t=n;t--!=0;)if(!((o[t]==="_owner"||o[t]==="__v"||o[t]==="__o")&&r.$$typeof)&&!M(r[o[t]],e[o[t]]))return!1;return!0}return r!==r&&e!==e}var ae=function(e,n){try{return M(e,n)}catch(t){if((t.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw t}},O={BODY:"bodyAttributes",HTML:"htmlAttributes",TITLE:"titleAttributes"},l={BASE:"base",BODY:"body",HEAD:"head",HTML:"html",LINK:"link",META:"meta",NOSCRIPT:"noscript",SCRIPT:"script",STYLE:"style",TITLE:"title"},Ne=Object.keys(l).map(function(r){return l[r]}),h={CHARSET:"charset",CSS_TEXT:"cssText",HREF:"href",HTTPEQUIV:"http-equiv",INNER_HTML:"innerHTML",ITEM_PROP:"itemprop",NAME:"name",PROPERTY:"property",REL:"rel",SRC:"src",TARGET:"target"},H={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},I={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate"},ue=Object.keys(H).reduce(function(r,e){return r[H[e]]=e,r},{}),ce=[l.NOSCRIPT,l.SCRIPT,l.STYLE],E="data-react-helmet",se=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},fe=function(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")},le=function(){function r(e,n){for(var t=0;t=0||!Object.prototype.hasOwnProperty.call(r,t)||(n[t]=r[t]);return n},pe=function(r,e){if(!r)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e&&(typeof e=="object"||typeof e=="function")?e:r},N=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return n===!1?String(e):String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},Te=function(e){var n=P(e,l.TITLE),t=P(e,I.TITLE_TEMPLATE);if(t&&n)return t.replace(/%s/g,function(){return Array.isArray(n)?n.join(""):n});var o=P(e,I.DEFAULT_TITLE);return n||o||void 0},me=function(e){return P(e,I.ON_CHANGE_CLIENT_STATE)||function(){}},j=function(e,n){return n.filter(function(t){return typeof t[e]!="undefined"}).map(function(t){return t[e]}).reduce(function(t,o){return v({},t,o)},{})},he=function(e,n){return n.filter(function(t){return typeof t[l.BASE]!="undefined"}).map(function(t){return t[l.BASE]}).reverse().reduce(function(t,o){if(!t.length)for(var i=Object.keys(o),s=0;s=0;t--){var o=e[t];if(o.hasOwnProperty(n))return o[n]}return null},ve=function(e){return{baseTag:he([h.HREF,h.TARGET],e),bodyAttributes:j(O.BODY,e),defer:P(e,I.DEFER),encode:P(e,I.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:j(O.HTML,e),linkTags:L(l.LINK,[h.REL,h.HREF],e),metaTags:L(l.META,[h.NAME,h.CHARSET,h.HTTPEQUIV,h.PROPERTY,h.ITEM_PROP],e),noscriptTags:L(l.NOSCRIPT,[h.INNER_HTML],e),onChangeClientState:me(e),scriptTags:L(l.SCRIPT,[h.SRC,h.INNER_HTML],e),styleTags:L(l.STYLE,[h.CSS_TEXT],e),title:Te(e),titleAttributes:j(O.TITLE,e)}},x=function(){var r=Date.now();return function(e){var n=Date.now();n-r>16?(r=n,e(n)):setTimeout(function(){x(e)},0)}}(),Y=function(e){return clearTimeout(e)},ye=typeof window!="undefined"?window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||x:global.requestAnimationFrame||x,Ee=typeof window!="undefined"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||Y:global.cancelAnimationFrame||Y,ge=function(e){return console&&typeof console.warn=="function"&&console.warn(e)},_=null,Ae=function(e){_&&Ee(_),e.defer?_=ye(function(){q(e,function(){_=null})}):(q(e),_=null)},q=function(e,n){var t=e.baseTag,o=e.bodyAttributes,i=e.htmlAttributes,s=e.linkTags,u=e.metaTags,a=e.noscriptTags,c=e.onChangeClientState,f=e.scriptTags,d=e.styleTags,p=e.title,T=e.titleAttributes;F(l.BODY,o),F(l.HTML,i),Ce(p,T);var y={baseTag:w(l.BASE,t),linkTags:w(l.LINK,s),metaTags:w(l.META,u),noscriptTags:w(l.NOSCRIPT,a),scriptTags:w(l.SCRIPT,f),styleTags:w(l.STYLE,d)},g={},A={};Object.keys(y).forEach(function(C){var R=y[C],k=R.newTags,X=R.oldTags;k.length&&(g[C]=k),X.length&&(A[C]=y[C].oldTags)}),n&&n(),c(e,g,A)},G=function(e){return Array.isArray(e)?e.join(""):e},Ce=function(e,n){typeof e!="undefined"&&document.title!==e&&(document.title=G(e)),F(l.TITLE,n)},F=function(e,n){var t=document.getElementsByTagName(e)[0];if(!!t){for(var o=t.getAttribute(E),i=o?o.split(","):[],s=[].concat(i),u=Object.keys(n),a=0;a=0;p--)t.removeAttribute(s[p]);i.length===s.length?t.removeAttribute(E):t.getAttribute(E)!==u.join(",")&&t.setAttribute(E,u.join(","))}},w=function(e,n){var t=document.head||document.querySelector(l.HEAD),o=t.querySelectorAll(e+"["+E+"]"),i=Array.prototype.slice.call(o),s=[],u=void 0;return n&&n.length&&n.forEach(function(a){var c=document.createElement(e);for(var f in a)if(a.hasOwnProperty(f))if(f===h.INNER_HTML)c.innerHTML=a.innerHTML;else if(f===h.CSS_TEXT)c.styleSheet?c.styleSheet.cssText=a.cssText:c.appendChild(document.createTextNode(a.cssText));else{var d=typeof a[f]=="undefined"?"":a[f];c.setAttribute(f,d)}c.setAttribute(E,"true"),i.some(function(p,T){return u=T,c.isEqualNode(p)})?i.splice(u,1):s.push(c)}),i.forEach(function(a){return a.parentNode.removeChild(a)}),s.forEach(function(a){return t.appendChild(a)}),{oldTags:i,newTags:s}},$=function(e){return Object.keys(e).reduce(function(n,t){var o=typeof e[t]!="undefined"?t+'="'+e[t]+'"':""+t;return n?n+" "+o:o},"")},Se=function(e,n,t,o){var i=$(t),s=G(n);return i?"<"+e+" "+E+'="true" '+i+">"+N(s,o)+"":"<"+e+" "+E+'="true">'+N(s,o)+""},be=function(e,n,t){return n.reduce(function(o,i){var s=Object.keys(i).filter(function(c){return!(c===h.INNER_HTML||c===h.CSS_TEXT)}).reduce(function(c,f){var d=typeof i[f]=="undefined"?f:f+'="'+N(i[f],t)+'"';return c?c+" "+d:d},""),u=i.innerHTML||i.cssText||"",a=ce.indexOf(e)===-1;return o+"<"+e+" "+E+'="true" '+s+(a?"/>":">"+u+"")},"")},z=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Object.keys(e).reduce(function(t,o){return t[H[o]||o]=e[o],t},n)},Oe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Object.keys(e).reduce(function(t,o){return t[ue[o]||o]=e[o],t},n)},Pe=function(e,n,t){var o,i=(o={key:n},o[E]=!0,o),s=z(t,i);return[b.createElement(l.TITLE,s,n)]},we=function(e,n){return n.map(function(t,o){var i,s=(i={key:o},i[E]=!0,i);return Object.keys(t).forEach(function(u){var a=H[u]||u;if(a===h.INNER_HTML||a===h.CSS_TEXT){var c=t.innerHTML||t.cssText;s.dangerouslySetInnerHTML={__html:c}}else s[a]=t[u]}),b.createElement(e,s)})},S=function(e,n,t){switch(e){case l.TITLE:return{toComponent:function(){return Pe(e,n.title,n.titleAttributes)},toString:function(){return Se(e,n.title,n.titleAttributes,t)}};case O.BODY:case O.HTML:return{toComponent:function(){return z(n)},toString:function(){return $(n)}};default:return{toComponent:function(){return we(e,n)},toString:function(){return be(e,n,t)}}}},V=function(e){var n=e.baseTag,t=e.bodyAttributes,o=e.encode,i=e.htmlAttributes,s=e.linkTags,u=e.metaTags,a=e.noscriptTags,c=e.scriptTags,f=e.styleTags,d=e.title,p=d===void 0?"":d,T=e.titleAttributes;return{base:S(l.BASE,n,o),bodyAttributes:S(O.BODY,t,o),htmlAttributes:S(O.HTML,i,o),link:S(l.LINK,s,o),meta:S(l.META,u,o),noscript:S(l.NOSCRIPT,a,o),script:S(l.SCRIPT,c,o),style:S(l.STYLE,f,o),title:S(l.TITLE,{title:p,titleAttributes:T},o)}},Re=function(e){var n,t;return t=n=function(o){de(i,o);function i(){return fe(this,i),pe(this,o.apply(this,arguments))}return i.prototype.shouldComponentUpdate=function(u){return!ae(this.props,u)},i.prototype.mapNestedChildrenToProps=function(u,a){if(!a)return null;switch(u.type){case l.SCRIPT:case l.NOSCRIPT:return{innerHTML:a};case l.STYLE:return{cssText:a}}throw new Error("<"+u.type+" /> elements are self-closing and can not contain children. Refer to our API for more information.")},i.prototype.flattenArrayTypeChildren=function(u){var a,c=u.child,f=u.arrayTypeChildren,d=u.newChildProps,p=u.nestedChildren;return v({},f,(a={},a[c.type]=[].concat(f[c.type]||[],[v({},d,this.mapNestedChildrenToProps(c,p))]),a))},i.prototype.mapObjectTypeChildren=function(u){var a,c,f=u.child,d=u.newProps,p=u.newChildProps,T=u.nestedChildren;switch(f.type){case l.TITLE:return v({},d,(a={},a[f.type]=T,a.titleAttributes=v({},p),a));case l.BODY:return v({},d,{bodyAttributes:v({},p)});case l.HTML:return v({},d,{htmlAttributes:v({},p)})}return v({},d,(c={},c[f.type]=v({},p),c))},i.prototype.mapArrayTypeChildrenToProps=function(u,a){var c=v({},a);return Object.keys(u).forEach(function(f){var d;c=v({},c,(d={},d[f]=u[f],d))}),c},i.prototype.warnOnInvalidChildren=function(u,a){return!0},i.prototype.mapChildrenToProps=function(u,a){var c=this,f={};return b.Children.forEach(u,function(d){if(!(!d||!d.props)){var p=d.props,T=p.children,y=B(p,["children"]),g=Oe(y);switch(c.warnOnInvalidChildren(d,T),d.type){case l.LINK:case l.META:case l.NOSCRIPT:case l.SCRIPT:case l.STYLE:f=c.flattenArrayTypeChildren({child:d,arrayTypeChildren:f,newChildProps:g,nestedChildren:T});break;default:a=c.mapObjectTypeChildren({child:d,newProps:a,newChildProps:g,nestedChildren:T});break}}}),a=this.mapArrayTypeChildrenToProps(f,a),a},i.prototype.render=function(){var u=this.props,a=u.children,c=B(u,["children"]),f=v({},c);return a&&(f=this.mapChildrenToProps(a,f)),b.createElement(e,f)},le(i,null,[{key:"canUseDOM",set:function(u){e.canUseDOM=u}}]),i}(b.Component),n.propTypes={base:m.object,bodyAttributes:m.object,children:m.oneOfType([m.arrayOf(m.node),m.node]),defaultTitle:m.string,defer:m.bool,encodeSpecialCharacters:m.bool,htmlAttributes:m.object,link:m.arrayOf(m.object),meta:m.arrayOf(m.object),noscript:m.arrayOf(m.object),onChangeClientState:m.func,script:m.arrayOf(m.object),style:m.arrayOf(m.object),title:m.string,titleAttributes:m.object,titleTemplate:m.string},n.defaultProps={defer:!0,encodeSpecialCharacters:!0},n.peek=e.peek,n.rewind=function(){var o=e.rewind();return o||(o=V({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}})),o},t},Ie=function(){return null},Le=te(ve,Ae,V)(Ie),D=Re(Le);D.renderStatic=D.rewind;export{D as Helmet}; diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-i18next.js b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-i18next.js new file mode 100644 index 0000000000000000000000000000000000000000..43d8e4d7bfb8d3d70d912e3aed2b045e19532410 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/__snowpack__/pkg/react-i18next.js @@ -0,0 +1,2 @@ +import{c as S,g as N}from"./common/_commonjsHelpers-b3efd043.js";import{r as x}from"./common/index-78959ebc.js";var ve=S(function(e){function r(t,n){if(t==null)return{};var s={},o=Object.keys(t),a,f;for(f=0;f=0)&&(s[a]=t[a]);return s}e.exports=r,e.exports.default=e.exports,e.exports.__esModule=!0}),ye=S(function(e){function r(t,n){if(t==null)return{};var s=ve(t,n),o,a;if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(t);for(a=0;a=0)&&(!Object.prototype.propertyIsEnumerable.call(t,o)||(s[o]=t[o]))}return s}e.exports=r,e.exports.default=e.exports,e.exports.__esModule=!0}),R=N(ye),ge=S(function(e){function r(t){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?(e.exports=r=function(s){return typeof s},e.exports.default=e.exports,e.exports.__esModule=!0):(e.exports=r=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},e.exports.default=e.exports,e.exports.__esModule=!0),r(t)}e.exports=r,e.exports.default=e.exports,e.exports.__esModule=!0}),k=N(ge),be=S(function(e){function r(t,n,s){return n in t?Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[n]=s,t}e.exports=r,e.exports.default=e.exports,e.exports.__esModule=!0}),W=N(be),me={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},xe=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function Y(e){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},t=e.match(/<\/?([^\s]+?)[/\s>]/);if(t&&(r.name=t[1],(me[t[1]]||e.charAt(e.length-2)==="/")&&(r.voidElement=!0),r.name.startsWith("!--"))){var n=e.indexOf("-->");return{type:"comment",comment:n!==-1?e.slice(4,n):""}}for(var s=new RegExp(xe),o=null;(o=s.exec(e))!==null;)if(o[0].trim())if(o[1]){var a=o[1].trim(),f=[a,""];a.indexOf("=")>-1&&(f=a.split("=")),r.attrs[f[0]]=f[1],s.lastIndex--}else o[2]&&(r.attrs[o[2]]=o[3].trim().substring(1,o[3].length-1));return r}var he=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,Oe=/^\s*$/,de=Object.create(null);function J(e,r){switch(r.type){case"text":return e+r.content;case"tag":return e+="<"+r.name+(r.attrs?function(t){var n=[];for(var s in t)n.push(s+'="'+t[s]+'"');return n.length?" "+n.join(" "):""}(r.attrs):"")+(r.voidElement?"/>":">"),r.voidElement?e:e+r.children.reduce(J,"")+"";case"comment":return e+""}}var je={parse:function(e,r){r||(r={}),r.components||(r.components=de);var t,n=[],s=[],o=-1,a=!1;if(e.indexOf("<")!==0){var f=e.indexOf("<");n.push({type:"text",content:f===-1?e:e.substring(0,f)})}return e.replace(he,function(c,l){if(a){if(c!=="")return;a=!1}var v,y=c.charAt(1)!=="/",_=c.startsWith(" + + + + + + + + + + + + + + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/static/trace_viewer_full.html b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/static/trace_viewer_full.html new file mode 100644 index 0000000000000000000000000000000000000000..d112b2524d9ff03dd7562961f4cef5b731b2b2c7 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/dist/static/trace_viewer_full.html @@ -0,0 +1,10179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/lib.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/lib.py new file mode 100644 index 0000000000000000000000000000000000000000..a4029221c26408da23d1c89f9176e4f8f8d9765d --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/lib.py @@ -0,0 +1,654 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import csv +import io +import math +import os +import sys +import time +from functools import partial # noqa: F401 + +import numpy as np + +from visualdl.component import components +from visualdl.io import bfile +from visualdl.server.log import logger +from visualdl.utils.importance import calc_all_hyper_param_importance +from visualdl.utils.list_util import duplicate_removal +from visualdl.utils.string_util import decode_tag +from visualdl.utils.string_util import encode_tag + +MODIFY_PREFIX = {} +MODIFIED_RUNS = [] +EMBEDDING_NAME = {} +embedding_names = [] + + +def s2ms(timestamp): + return timestamp * 1000 if timestamp < 2000000000 else timestamp + + +def transfer_abnomal_scalar_value(scalar_value): + if math.isnan(scalar_value) or math.isinf(scalar_value): + scalar_value = str(scalar_value) + return scalar_value + + +def get_components(log_reader): + components = log_reader.components(update=True) + return list(components) + + +def get_runs(log_reader): + runs = [] + for item in log_reader.runs(): + if item in log_reader.tags2name: + runs.append(log_reader.tags2name[item]) + else: + runs.append(item) + return runs + + +def get_graph_runs(graph_reader): + runs = [] + for item in graph_reader.runs(): + if item in graph_reader.runs2displayname: + runs.append(graph_reader.runs2displayname[item]) + else: + runs.append(item) + return runs + + +def get_tags(log_reader): + return log_reader.tags() + + +def get_logs(log_reader, component): + all_tag = log_reader.data_manager.get_reservoir(component).keys + tags = {} + for item in all_tag: + index = item.rfind('/') + run = item[0:index] + tag = encode_tag(item[index + 1:]) + if run in tags.keys(): + tags[run].append(tag) + else: + tags[run] = [tag] + if run not in log_reader.tags2name.keys(): + log_reader.tags2name[run] = run + log_reader.name2tags[run] = run + fake_tags = {} + for key, value in tags.items(): + if key in log_reader.tags2name: + fake_tags[log_reader.tags2name[key]] = value + else: + fake_tags[key] = value + + run2tag = {'runs': [], 'tags': []} + for run, tags in fake_tags.items(): + run2tag['runs'].append(run) + run2tag['tags'].append(tags) + + run_prefix = os.getenv('VISUALDL_RUN_PREFIX') + global MODIFY_PREFIX, MODIFIED_RUNS + if component not in MODIFY_PREFIX: + MODIFY_PREFIX.update({component: False}) + if run_prefix and not MODIFY_PREFIX[component]: + MODIFY_PREFIX[component] = True + temp_name2tags = log_reader.name2tags.copy() + for key, value in temp_name2tags.items(): + if key in MODIFIED_RUNS: + continue + index = key.find(run_prefix) + if index != -1: + temp_key = key[index + len(run_prefix):] + + log_reader.name2tags.pop(key) + log_reader.name2tags.update({temp_key: value}) + + log_reader.tags2name.pop(value) + log_reader.tags2name.update({value: temp_key}) + + run2tag['runs'][run2tag['runs'].index(key)] = temp_key + else: + temp_key = key + + MODIFIED_RUNS.append(temp_key) + + return run2tag + + +for name in components.keys(): + exec("get_%s_tags=partial(get_logs, component='%s')" % (name, name)) + + +def get_hparam_data(log_reader, type='tsv'): + result = get_hparam_list(log_reader) + delimeter = '\t' if 'tsv' == type else ',' + header = ['Trial ID'] + hparams_header = [] + metrics_header = [] + for item in result: + hparams_header += item['hparams'].keys() + metrics_header += item['metrics'].keys() + name_set = set() + h_header = [] + for hparam in hparams_header: + if hparam in name_set: + continue + name_set.add(hparam) + h_header.append(hparam) + name_set = set() + m_header = [] + for metric in metrics_header: + if metric in name_set: + continue + name_set.add(metric) + m_header.append(metric) + trans_result = [] + for item in result: + temp = {'Trial ID': item.get('name', '')} + temp.update(item.get('hparams', {})) + temp.update(item.get('metrics', {})) + trans_result.append(temp) + header = header + h_header + m_header + with io.StringIO() as fp: + csv_writer = csv.writer(fp, delimiter=delimeter) + csv_writer.writerow(header) + for item in trans_result: + row = [] + for col_name in header: + row.append(item.get(col_name, '')) + csv_writer.writerow(row) + result = fp.getvalue() + return result + + +def get_hparam_importance(log_reader): + indicator = get_hparam_indicator(log_reader) + hparams = [ + item for item in indicator['hparams'] if (item['type'] != 'string') + ] + metrics = [ + item for item in indicator['metrics'] if (item['type'] != 'string') + ] + + result = calc_all_hyper_param_importance(hparams, metrics) + + return result + + +# flake8: noqa: C901 +def get_hparam_indicator(log_reader): + run2tag = get_logs(log_reader, 'hyper_parameters') + runs = run2tag['runs'] + hparams = {} + metrics = {} + records_list = [] + for run in runs: + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir( + "hyper_parameters").get_items(run, decode_tag('hparam')) + records_list.append([records, run]) + records_list.sort(key=lambda x: x[0][0].timestamp) + runs = [run for r, run in records_list] + for records, run in records_list: + for hparamInfo in records[0].hparam.hparamInfos: + type = hparamInfo.WhichOneof("type") + if "float_value" == type: + if hparamInfo.name not in hparams.keys(): + hparams[hparamInfo.name] = { + 'name': hparamInfo.name, + 'type': 'continuous', + 'values': [hparamInfo.float_value] + } + elif hparamInfo.float_value not in hparams[ + hparamInfo.name]['values']: + hparams[hparamInfo.name]['values'].append( + hparamInfo.float_value) + elif "string_value" == type: + if hparamInfo.name not in hparams.keys(): + hparams[hparamInfo.name] = { + 'name': hparamInfo.name, + 'type': 'string', + 'values': [hparamInfo.string_value] + } + elif hparamInfo.string_value not in hparams[ + hparamInfo.name]['values']: + hparams[hparamInfo.name]['values'].append( + hparamInfo.string_value) + elif "int_value" == type: + if hparamInfo.name not in hparams.keys(): + hparams[hparamInfo.name] = { + 'name': hparamInfo.name, + 'type': 'numeric', + 'values': [hparamInfo.int_value] + } + elif hparamInfo.int_value not in hparams[ + hparamInfo.name]['values']: + hparams[hparamInfo.name]['values'].append( + hparamInfo.int_value) + else: + raise TypeError( + "Invalid hparams param value type `%s`." % type) + + for metricInfo in records[0].hparam.metricInfos: + metrics[metricInfo.name] = { + 'name': metricInfo.name, + 'type': 'continuous', + 'values': [] + } + for run in runs: + try: + metrics_data = get_hparam_metric(log_reader, run, + metricInfo.name) + metrics[metricInfo.name]['values'].append( + metrics_data[-1][-1]) + break + except: + logger.error( + 'Missing data of metrics! Please make sure use add_scalar to log metrics data.' + ) + if len(metrics[metricInfo.name]['values']) == 0: + metrics.pop(metricInfo.name) + else: + metrics[metricInfo.name].pop('values') + + results = { + 'hparams': [value for key, value in hparams.items()], + 'metrics': [value for key, value in metrics.items()] + } + + return results + + +def get_hparam_metric(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("scalar").get_items( + run, decode_tag(tag)) + results = [[ + s2ms(item.timestamp), item.id, + transfer_abnomal_scalar_value(item.value) + ] for item in records] + return results + + +def get_hparam_list(log_reader): + run2tag = get_logs(log_reader, 'hyper_parameters') + runs = run2tag['runs'] + results = [] + + records_list = [] + for run in runs: + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir( + "hyper_parameters").get_items(run, decode_tag('hparam')) + records_list.append([records, run]) + records_list.sort(key=lambda x: x[0][0].timestamp) + for records, run in records_list: + hparams = {} + for hparamInfo in records[0].hparam.hparamInfos: + hparam_type = hparamInfo.WhichOneof("type") + if "float_value" == hparam_type: + hparams[hparamInfo.name] = hparamInfo.float_value + elif "string_value" == hparam_type: + hparams[hparamInfo.name] = hparamInfo.string_value + elif "int_value" == hparam_type: + hparams[hparamInfo.name] = hparamInfo.int_value + else: + raise TypeError( + "Invalid hparams param value type `%s`." % hparam_type) + + metrics = {} + for metricInfo in records[0].hparam.metricInfos: + try: + metrics_data = get_hparam_metric(log_reader, run, + metricInfo.name) + metrics[metricInfo.name] = metrics_data[-1][-1] + except: + logger.error( + 'Missing data of metrics! Please make sure use add_scalar to log metrics data.' + ) + metrics[metricInfo.name] = None + + results.append({'name': run, 'hparams': hparams, 'metrics': metrics}) + return results + + +def get_scalar(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("scalar").get_items( + run, decode_tag(tag)) + + results = [[ + s2ms(item.timestamp), item.id, + transfer_abnomal_scalar_value(item.value) + ] if item.WhichOneof("one_value") == "value" else [ + s2ms(item.timestamp), item.id, + transfer_abnomal_scalar_value(item.tag_value.value) + ] for item in records] + + return results + + +def get_scalar_data(log_reader, run, tag, type='tsv'): + is_scalars = False + if os.path.basename(run).startswith(decode_tag(tag).replace('%', '_')) and \ + log_reader.tags().get(bfile.join(os.path.dirname(run), decode_tag(tag)), None) == 'scalars': + run = os.path.dirname(run) + is_scalars = True + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + if is_scalars: + result = log_reader.get_log_data('scalars', run, decode_tag(tag)) + else: + result = log_reader.get_log_data('scalar', run, decode_tag(tag)) + print('scalar', result, 'run', run, 'tag', decode_tag(tag)) + delimeter = '\t' if 'tsv' == type else ',' + with io.StringIO() as fp: + csv_writer = csv.writer(fp, delimiter=delimeter) + if is_scalars: + csv_writer.writerow(['id', 'tag', 'sub_tag', 'timestamp', 'value']) + else: + csv_writer.writerow(['id', 'tag', 'timestamp', 'value']) + csv_writer.writerows(result) + result = fp.getvalue() + return result + + +def get_image_tag_steps(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("image").get_items( + run, decode_tag(tag)) + result = [{ + "step": item.id, + "wallTime": s2ms(item.timestamp) + } for item in records] + return result + + +def get_individual_image(log_reader, run, tag, step_index): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("image").get_items( + run, decode_tag(tag)) + return records[step_index].image.encoded_image_string + + +def get_text_tag_steps(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("text").get_items( + run, decode_tag(tag)) + result = [{ + "step": item.id, + "wallTime": s2ms(item.timestamp) + } for item in records] + return result + + +def get_individual_text(log_reader, run, tag, step_index): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("text").get_items( + run, decode_tag(tag)) + return records[step_index].text.encoded_text_string + + +def get_audio_tag_steps(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("audio").get_items( + run, decode_tag(tag)) + result = [{ + "step": item.id, + "wallTime": s2ms(item.timestamp) + } for item in records] + return result + + +def get_individual_audio(log_reader, run, tag, step_index): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("audio").get_items( + run, decode_tag(tag)) + result = records[step_index].audio.encoded_audio_string + return result + + +def get_pr_curve(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("pr_curve").get_items( + run, decode_tag(tag)) + results = [] + for item in records: + pr_curve = item.pr_curve + length = len(pr_curve.precision) + num_thresholds = [float(v) / length for v in range(1, length + 1)] + results.append([ + s2ms(item.timestamp), item.id, + list(pr_curve.precision), + list(pr_curve.recall), + list(pr_curve.TP), + list(pr_curve.FP), + list(pr_curve.TN), + list(pr_curve.FN), num_thresholds + ]) + return results + + +def get_roc_curve(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("roc_curve").get_items( + run, decode_tag(tag)) + results = [] + for item in records: + roc_curve = item.roc_curve + length = len(roc_curve.tpr) + num_thresholds = [float(v) / length for v in range(1, length + 1)] + results.append([ + s2ms(item.timestamp), item.id, + list(roc_curve.tpr), + list(roc_curve.fpr), + list(roc_curve.TP), + list(roc_curve.FP), + list(roc_curve.TN), + list(roc_curve.FN), num_thresholds + ]) + return results + + +def get_pr_curve_step(log_reader, run, tag=None): + fake_run = run + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + run2tag = get_pr_curve_tags(log_reader) # noqa: F821 + tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0] + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("pr_curve").get_items( + run, decode_tag(tag)) + results = [[s2ms(item.timestamp), item.id] for item in records] + return results + + +def get_roc_curve_step(log_reader, run, tag=None): + fake_run = run + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + run2tag = get_roc_curve_tags(log_reader) # noqa: F821 + tag = run2tag['tags'][run2tag['runs'].index(fake_run)][0] + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("roc_curve").get_items( + run, decode_tag(tag)) + results = [[s2ms(item.timestamp), item.id] for item in records] + return results + + +def get_embeddings_list(log_reader): + run2tag = get_logs(log_reader, 'embeddings') + + for run, _tags in zip(run2tag['runs'], run2tag['tags']): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + for tag in _tags: + name = path = os.path.join(run, tag) + if name in EMBEDDING_NAME: + return embedding_names + EMBEDDING_NAME.update({name: {'run': run, 'tag': tag}}) + records = log_reader.data_manager.get_reservoir( + "embeddings").get_items(run, decode_tag(tag)) + row_len = len(records[0].embeddings.embeddings) + col_len = len(records[0].embeddings.embeddings[0].vectors) + shape = [row_len, col_len] + embedding_names.append({ + 'name': name, + 'shape': shape, + 'path': path + }) + return embedding_names + + +def get_embedding_labels(log_reader, name): + run = EMBEDDING_NAME[name]['run'] + tag = EMBEDDING_NAME[name]['tag'] + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("embeddings").get_items( + run, decode_tag(tag)) + labels = [] + for item in records[0].embeddings.embeddings: + labels.append(item.label) + + label_meta = records[0].embeddings.label_meta + if label_meta: + labels = [label_meta] + labels + + with io.StringIO() as fp: + csv_writer = csv.writer(fp, delimiter='\t') + csv_writer.writerows(labels) + labels = fp.getvalue() + + # labels = "\n".join(str(i) for i in labels) + return labels + + +def get_embedding_tensors(log_reader, name): + run = EMBEDDING_NAME[name]['run'] + tag = EMBEDDING_NAME[name]['tag'] + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("embeddings").get_items( + run, decode_tag(tag)) + vectors = [] + for item in records[0].embeddings.embeddings: + vectors.append(item.vectors) + vectors = np.array(vectors).flatten().astype(np.float32).tobytes() + return vectors + + +def get_histogram(log_reader, run, tag): + run = log_reader.name2tags[run] if run in log_reader.name2tags else run + log_reader.load_new_data() + records = log_reader.data_manager.get_reservoir("histogram").get_items( + run, decode_tag(tag)) + + results = [] + for item in records: + histogram = item.histogram + hist = histogram.hist + bin_edges = histogram.bin_edges + histogram_data = [] + for index in range(len(hist)): + histogram_data.append( + [bin_edges[index], bin_edges[index + 1], hist[index]]) + results.append([s2ms(item.timestamp), item.id, histogram_data]) + + return results + + +def get_static_graph(log_reader): + result = b"" + if log_reader.model: + with bfile.BFile(log_reader.model, 'rb') as bfp: + result = bfp.read_file(log_reader.model) + return result + + +def get_graph(graph_reader, + run, + nodeid=None, + expand=False, + keep_state=False, + expand_all=False, + refresh=True): + result = "" + run = graph_reader.displayname2runs[ + run] if run in graph_reader.displayname2runs else run + if nodeid is not None: + refresh = False + result = graph_reader.get_graph(run, nodeid, expand, keep_state, + expand_all, refresh) + return result + + +def get_graph_search(graph_reader, run, nodeid, keep_state=False, + is_node=True): + result = "" + run = graph_reader.displayname2runs[ + run] if run in graph_reader.displayname2runs else run + result = graph_reader.search_graph_node( + run, nodeid, keep_state=keep_state, is_node=is_node) + return result + + +def get_graph_all_nodes(graph_reader, run): + result = "" + run = graph_reader.displayname2runs[ + run] if run in graph_reader.displayname2runs else run + result = graph_reader.get_all_nodes(run) + return result + + +def retry(ntimes, function, time2sleep, *args, **kwargs): + """ + try to execute `function` `ntimes`, if exception catched, the thread will + sleep `time2sleep` seconds. + """ + for i in range(ntimes): + try: + return function(*args, **kwargs) + except Exception: + if i < ntimes - 1: + error_info = '\n'.join(map(str, sys.exc_info())) + logger.error("Unexpected error: %s" % error_info) + time.sleep(time2sleep) + else: + import traceback + traceback.print_exc() + + +def cache_get(cache): + def _handler(key, func, *args, **kwargs): + data = cache.get(key) + if data is None: + logger.warning('update cache %s' % key) + data = func(*args, **kwargs) + cache.set(key, data) + return data + return data + + return _handler diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/log.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/log.py new file mode 100644 index 0000000000000000000000000000000000000000..98d9f36ebe49c7f1689f9e6e1f61ad00cc26b323 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/log.py @@ -0,0 +1,37 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import logging + + +logger = logging.getLogger('vdl_logger') +handler = logging.StreamHandler() +handler.setFormatter(logging.Formatter('[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s')) +logger.addHandler(handler) + +info_logger = logging.getLogger('visualdl.info') +info_logger.setLevel(logging.INFO) +info_handler = logging.StreamHandler() +info_handler.setFormatter(logging.Formatter('%(message)s')) +info_logger.addHandler(info_handler) +info_logger.propagate = False +info = info_logger.info + + +def init_logger(verbose): + level = max(logging.ERROR - verbose * 10, logging.NOTSET) + + logger.setLevel(level) + logging.getLogger('werkzeug').setLevel(level) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/serve.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/serve.py new file mode 100644 index 0000000000000000000000000000000000000000..3348dc4e440328b3882ae12edc130c08d82c29f9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/serve.py @@ -0,0 +1,124 @@ +#!/user/bin/env python + +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import requests +import json +import os + +from visualdl.io import bfile +from visualdl.reader.reader import is_VDLRecord_file +from visualdl.utils.dir import CONFIG_PATH +from visualdl.server.log import logger + + +def get_server_url(): + with open(CONFIG_PATH, 'r') as fp: + server_url = json.load(fp)['server_url'] + return server_url + + +def apply_for_token(): + url = get_server_url() + '/sts/' + res = requests.post(url=url).json() + + return res + + +def get_url(path='', model='', **kwargs): + server_url = get_server_url() + '/url/' + data = json.dumps({'path': path, 'model': model}) + headers = {"Content-Type": "application/json"} + res = requests.post(url=server_url, headers=headers, data=data).json() + err_code = res.get('code') + msg = res.get('msg') + + if '000000' == err_code: + url = msg.get('url') + return url + else: + logger.error(msg) + return + + +def get_vdl_log_file(logdirs): + """Get logs. + + Every dir(means `run` in vdl) has only one log(meads `actual log file`). + + Returns: + walks: A dict like {"exp1": "vdlrecords.1587375595.log", + "exp2": "vdlrecords.1587375685.log"} + """ + walks = {} + walks_temp = {} + for logdir in logdirs: + for root, dirs, files in bfile.walk(logdir): + walks.update({root: files}) + + for run, tags in walks.items(): + tags_temp = [tag for tag in tags if + is_VDLRecord_file(path=bfile.join(run, tag), check=False)] + tags_temp.sort(reverse=True) + if len(tags_temp) > 0: + walks_temp.update({run: tags_temp[0]}) + + return walks_temp + + +def upload_to_dev(logdir=None, model=None): + if not logdir and not model: + logger.error("Must specify directory to upload via `--logdir` or specify model to upload via `--model`.") + return + walks = {} + if logdir: + walks = get_vdl_log_file(logdir) + if not walks: + logger.error("There is no valid log file in %s" % logdir) + return + + res = apply_for_token() + + err_code = res.get('code') + msg = res.get('msg') + + if '000000' == err_code: + sts_ak = msg.get('sts_ak') + sts_sk = msg.get('sts_sk') + sts_token = msg.get('token') + bucket_id = msg.get('dir') + else: + logger.error(msg) + return + + if not sts_ak or not sts_sk or not sts_token: + return + bos_fs = bfile.BosConfigClient(bos_ak=sts_ak, + bos_sk=sts_sk, + bos_sts=sts_token) + + for key, value in walks.items(): + filename = bos_fs.join(key, value) + bos_fs.upload_object_from_file(path=bucket_id, filename=filename) + + if model: + if os.path.getsize(model) > 1024 * 1024 * 100: + logger.error('Size of model must less than 100M.') + else: + bos_fs.upload_object_from_file(path=bucket_id, filename=model) + url = get_url(path=bucket_id, model=model) + + print("View your visualization results at: `%s`." % url) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/setup.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0364e726a56284d8a39f953a5aed45ca7022f517 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/setup.py @@ -0,0 +1,30 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from setuptools import setup + +packages = [ + 'visualdl', 'visualdl.onnx', 'visualdl.mock', 'visualdl.frontend.dist' +] + +setup( + name="visualdl", + version="0.0.1", + packages=packages, + package_data={'visualdl.frontend.dist': ['*', 'fonts/*']}, + include_package_data=True, + install_requires=['flask>=0.12.1'], + url='http://www.baidu.com/', + license='Apache 2.0') diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/template.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/template.py new file mode 100644 index 0000000000000000000000000000000000000000..8017ddf024536faef53e8d6ab3c0304dec0dfba4 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/server/template.py @@ -0,0 +1,59 @@ +# Copyright (c) 2017 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import os +import mimetypes +from flask import (Response, send_from_directory) + + +class Template(object): + extname = ['.html', '.js', '.css'] + mimetypes = ['text/html', 'application/javascript', 'text/css'] + + defaults = { + 'PUBLIC_PATH': '/app', + 'API_TOKEN_KEY': '', + 'TELEMETRY_ID': '', + 'THEME': '' + } + + __files = {} + + def __init__(self, path, **context): + if not os.path.exists(path): + raise Exception("template file does not exist.") + self.path = path + self.__add_mime_types() + for root, _dirs, files in os.walk(path): + for file in files: + if any(file.endswith(name) for name in self.extname): + file_path = os.path.join(root, file) + rel_path = os.path.relpath(file_path, path).replace(os.path.sep, '/') + with open(file_path, "r", encoding="UTF-8") as f: + content = f.read() + envs = self.defaults.copy() + envs.update(context) + for key, value in envs.items(): + content = content.replace("{{" + key + "}}", value) + self.__files[rel_path] = content, mimetypes.guess_type(file)[0] + + def render(self, file): + if file in self.__files: + return Response(response=self.__files[file][0], mimetype=self.__files[file][1]) + return send_from_directory(self.path, file) + + def __add_mime_types(self): + for i, ext in enumerate(self.extname): + mimetypes.add_type(self.mimetypes[i] or 'application/octet-stream', ext) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bab744b75600618b2912de1ad551f15c5686580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/crc32.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/crc32.py new file mode 100644 index 0000000000000000000000000000000000000000..d801fb97eb4e4e281e46934ef78f607bd97466af --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/crc32.py @@ -0,0 +1,117 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import array + + +def masked_crc32c(data): + x = u32(crc32c(data)) + return u32(((x >> 15) | u32(x << 17)) + 0xa282ead8) + + +def u32(x): + return x & 0xffffffff + + +CRC_TABLE = ( + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, + 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c, + 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, + 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512, + 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, + 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf, + 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, + 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f, + 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, + 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e, + 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, + 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4, + 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, + 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5, + 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, + 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905, + 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, + 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8, + 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, + 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6, + 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, + 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, ) + +CRC_INIT = 0 + +_MASK = 0xFFFFFFFF + + +def crc_update(crc, data): + """Update CRC-32C checksum with data. + Args: + crc: 32-bit checksum to update as long. + data: byte array, string or iterable over bytes. + Returns: + 32-bit updated CRC-32C as long. + """ + + if type(data) != array.array or data.itemsize != 1: + buf = array.array("B", data) + else: + buf = data + + crc ^= _MASK + for b in buf: + table_index = (crc ^ b) & 0xff + crc = (CRC_TABLE[table_index] ^ (crc >> 8)) & _MASK + return crc ^ _MASK + + +def crc_finalize(crc): + """Finalize CRC-32C checksum. + This function should be called as last step of crc calculation. + Args: + crc: 32-bit checksum as long. + Returns: + finalized 32-bit checksum as long + """ + return crc & _MASK + + +def crc32c(data): + """Compute CRC-32C checksum of the data. + Args: + data: byte array, string or iterable over bytes. + Returns: + 32-bit CRC-32C checksum of data as long. + """ + return crc_finalize(crc_update(CRC_INIT, data)) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/dir.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/dir.py new file mode 100644 index 0000000000000000000000000000000000000000..b22ed42468afd063300b88ace6e90644bb37442c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/dir.py @@ -0,0 +1,39 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import json +import os + +VDL_SERVER = "https://www.paddlepaddle.org.cn/paddle/visualdl/service/server" + +default_vdl_config = {'server_url': VDL_SERVER} + +USER_HOME = os.path.expanduser('~') +VDL_HOME = os.path.join(USER_HOME, '.visualdl') +CONF_HOME = os.path.join(VDL_HOME, 'conf') +CONFIG_PATH = os.path.join(CONF_HOME, 'config.json') +FASTDEPLOYSERVER_PATH = os.path.join(VDL_HOME, 'fastdeployserver') +X2PADDLE_CACHE_PATH = os.path.join(VDL_HOME, 'x2paddle') + + +def init_vdl_config(): + if not os.path.exists(CONF_HOME): + os.makedirs(CONF_HOME, exist_ok=True) + if not os.path.exists(CONFIG_PATH) or 0 == os.path.getsize(CONFIG_PATH): + with open(CONFIG_PATH, 'w') as fp: + fp.write(json.dumps(default_vdl_config)) + if not os.path.exists(FASTDEPLOYSERVER_PATH): + os.makedirs(FASTDEPLOYSERVER_PATH, exist_ok=True) + if not os.path.exists(X2PADDLE_CACHE_PATH): + os.makedirs(X2PADDLE_CACHE_PATH, exist_ok=True) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/figure_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/figure_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8b178d9c1e4d77d27c5f1b144b932d6468d176 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/figure_util.py @@ -0,0 +1,47 @@ +# Copyright (c) 2021 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + + +def figure_to_image(figures, close=True): + """Render matplotlib figure to numpy format. + + Note that this requires the ``matplotlib`` package. + + Args: + figure (matplotlib.pyplot.figure) : figure + close (bool): Flag to automatically close the figure + + Returns: + numpy.array: image in [HWC] order + """ + import numpy as np + try: + import matplotlib.pyplot as plt + import matplotlib.backends.backend_agg as plt_backend_agg + except ModuleNotFoundError: + print('please install matplotlib') + + def render_to_rgb(figure): + canvas = plt_backend_agg.FigureCanvasAgg(figure) + canvas.draw() + data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8) + w, h = figure.canvas.get_width_height() + image_hwc = data.reshape([h, w, 4])[:, :, 0:3] + if close: + plt.close(figure) + return image_hwc + + image = render_to_rgb(figures) + return image diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/img_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/img_util.py new file mode 100644 index 0000000000000000000000000000000000000000..fe95e6347a8e86ba53ea0e31bbbfb0f6d67bae48 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/img_util.py @@ -0,0 +1,91 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import math +from functools import reduce + +import numpy as np + +from visualdl.component.base_component import convert_to_HWC + + +def padding_image(img, height, width): + height_old, width_old, _ = img.shape + height_before = math.floor((height - height_old) / 2) + height_after = height - height_old - height_before + + width_before = math.floor((width - width_old) / 2) + width_after = width - width_old - width_before + + return np.pad(array=img, + pad_width=((height_before, height_after), (width_before, width_after), (0, 0)), + mode="constant") + + +def merge_images(imgs, dataformats, scale=1.0, rows=-1): + assert rows <= len(imgs), "rows should not greater than numbers of pictures" + # convert format of each image to `hwc` + for i, img in enumerate(imgs): + imgs[i] = convert_to_HWC(img, dataformats) + + channel = imgs[0].shape[2] + height = -1 + width = -1 + + for img in imgs: + height = height if height > img.shape[0] else img.shape[0] + width = width if width > img.shape[1] else img.shape[1] + + # padding every sub-image with height and width + for i, img in enumerate(imgs): + imgs[i] = padding_image(img, height, width) + + # get row and col + len_imgs = len(imgs) + if -1 == rows: + rows = cols = math.floor(math.sqrt(len_imgs)) + while rows*cols < len_imgs: + if rows <= cols: + rows += 1 + else: + cols += 1 + else: + cols = math.ceil(len_imgs/rows) + + # add white sub-image + for i in range(rows*cols-len_imgs): + imgs = np.concatenate((imgs, np.zeros((height, width, channel), dtype=np.uint8)[None, :])) + + imgs = reduce(lambda x, y: np.concatenate((x, y)), [ + reduce(lambda x, y: np.concatenate((x, y), 1), + imgs[i * cols: (i + 1) * cols]) for i in range(rows)]) + + # choose bigger number of rows and cols + + scale = 1.0/scale * rows if rows > cols else 1.0/scale * cols + + dsize = tuple(map(lambda x: math.floor(x/scale), imgs.shape))[-2::-1] + + try: + import cv2 + + imgs = cv2.resize(src=imgs, dsize=dsize) + except ImportError: + from PIL import Image + + imgs = Image.fromarray(imgs) + imgs.resize(dsize) + imgs = np.array(imgs) + + return imgs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/importance.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/importance.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e911feb6cc3231d58b3b3c2a197851b8fc8bed --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/importance.py @@ -0,0 +1,55 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +from functools import reduce + +import numpy as np +import pandas as pd + +from visualdl.server.log import logger + + +def calc_hyper_param_importance(df, hyper_param, target): + new_df = df[[hyper_param, target]] + no_missing_value_df = new_df.dropna() + + # Can not calc pearson correlation coefficient when number of samples is less or equal than 2 + if len(no_missing_value_df) <= 2: + logger.error("Number of samples is less or equal than 2.") + return 0 + + correlation = no_missing_value_df[target].corr(no_missing_value_df[hyper_param]) + if np.isnan(correlation): + logger.warning("Correlation is nan!") + return 0 + + return abs(correlation) + + +def calc_all_hyper_param_importance(hparams, metrics): + results = {} + for metric in metrics: + for hparam in hparams: + flattened_lineage = {hparam['name']: hparam['values'], metric['name']: metric['values']} + result = calc_hyper_param_importance(pd.DataFrame(flattened_lineage), hparam['name'], metric['name']) + # print('%s - %s : result=' % (hparam, metric), result) + if hparam['name'] not in results.keys(): + results[hparam['name']] = result + else: + results[hparam['name']] += result + sum_score = reduce(lambda x, y: x+y, results.values()) + for key, value in results.items(): + results[key] = value/sum_score + result = [{'name': key, 'value': value} for key, value in results.items()] + return result diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/list_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/list_util.py new file mode 100644 index 0000000000000000000000000000000000000000..cff1af876df674f8073d4b8245b11a1337ff722b --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/list_util.py @@ -0,0 +1,25 @@ +# Copyright (c) 2021 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + + +def duplicate_removal(src_list): + name_scope = set() + dest_list = [] + for item in src_list: + if item in name_scope: + continue + name_scope.add(item) + dest_list.append(item) + return dest_list diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/md5_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/md5_util.py new file mode 100644 index 0000000000000000000000000000000000000000..384931a40ea89c66f60dc97b934ca4243c64e9e0 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/md5_util.py @@ -0,0 +1,24 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import hashlib + + +def md5(text): + if isinstance(text, str): + text = text.encode("utf8") + md5 = hashlib.md5() + md5.update(text) + return md5.hexdigest() diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/string_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/string_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3b82fa9717a658c4ba18087a8e85a1e481535e --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/string_util.py @@ -0,0 +1,21 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +def encode_tag(tag): + return tag.replace("%", "/") + + +def decode_tag(tag): + return tag.replace("/", "%") diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/update_util.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/update_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1653e308ffe7336b373c92d1a7c46a346bd60dc9 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/utils/update_util.py @@ -0,0 +1,61 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +import threading +import hashlib +import requests +from visualdl import __version__ +from visualdl.proto.record_pb2 import DESCRIPTOR + + +def md5(text): + if isinstance(text, str): + text = text.encode("utf8") + md5 = hashlib.md5() + md5.update(text) + return md5.hexdigest() + + +class PbUpdater(threading.Thread): + def __init__(self, product='normal'): + self.product = product + threading.Thread.__init__(self) + + def update_pb(self, + version=__version__, + md5_code=md5(str(DESCRIPTOR)) + ): + payload = { + "data": { + "version": version, + "md5": md5_code, + "product": self.product + } + } + url = 'https://paddlepaddle.org.cn/paddlehub/stat?from=vdl' + try: + r = requests.post(url=url, json=payload) + if r.json().get("update_flag", 0) == 1: + pb_bin = r.json().get("pb_bin") + with open('/visualdl/proto/record_pb2.py', mode='wb') as fp: + fp.write(pb_bin) + print('Update pb file successfully.') + except Exception: + pass + + def run(self): + self.update_pb(version=__version__, + md5_code=md5(str(DESCRIPTOR)) + ) diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/version.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/version.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee7af001869fa01ac13bfc4af62f0a2f28fb801 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/version.py @@ -0,0 +1,16 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +vdl_version = '2.5.3' diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/__init__.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6bab744b75600618b2912de1ad551f15c5686580 --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/record_writer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/record_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7c971be1620ff08ef536ffc7c83033d9ea52d36f --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/record_writer.py @@ -0,0 +1,234 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= + +from visualdl.io import bfile +from visualdl.utils.crc32 import masked_crc32c +from visualdl.proto import record_pb2 +import struct +import time +import queue +import threading +import os + +QUEUE_TIMEOUT = os.getenv("VDL_QUEUE_TIMEOUT") +if isinstance(QUEUE_TIMEOUT, str): + QUEUE_TIMEOUT = int(QUEUE_TIMEOUT) + + +class RecordWriter(object): + """Package data with crc32 or not. + """ + + def __init__(self, writer): + self._writer = writer + + def write(self, data): + """Package and write data to disk. + + Args: + data (string or bytes): Data to write to disk. + """ + header = struct.pack(' 0: + data = self._queue.get(True, queue_wait_duration) + else: + data = self._queue.get(False) + + if data == self._shutdown_signal: + return + + self._record_writer.write(data) + self._has_pending_data = True + except queue.Empty: + pass + except Exception as e: + # prevent the main thread from deadlock due to writing error. + if not has_unresolved_bug: + print('Warning: Writing data Error, Due to unresolved Exception {}'.format(e)) + print('Warning: Writing data to FileSystem failed since {}.'.format( + time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))) + has_unresolved_bug = True + pass + finally: + if data: + self._queue.task_done() + + now = time.time() + if now > self._next_flush_time: + if self._has_pending_data: + self._record_writer.flush() + self._has_pending_data = False + self._next_flush_time = now + self._flush_secs diff --git a/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/writer.py b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3df6aff529463ddedbb5b9497ad13bd7cbbb4c --- /dev/null +++ b/PaddleOCR_ali1k_det_rec_300epoch_standalone/visualdl/writer/writer.py @@ -0,0 +1,699 @@ +# Copyright (c) 2020 VisualDL Authors. All Rights Reserve. +# +# 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. +# ======================================================================= +import os +import time + +import numpy as np + +from visualdl.component.base_component import audio +from visualdl.component.base_component import embedding +from visualdl.component.base_component import histogram +from visualdl.component.base_component import hparam +from visualdl.component.base_component import image +from visualdl.component.base_component import meta_data +from visualdl.component.base_component import pr_curve +from visualdl.component.base_component import roc_curve +from visualdl.component.base_component import scalar +from visualdl.component.base_component import scalars +from visualdl.component.base_component import text +from visualdl.component.graph import translate_graph +from visualdl.io import bfile +from visualdl.server.log import logger +from visualdl.utils.figure_util import figure_to_image +from visualdl.utils.img_util import merge_images +from visualdl.utils.md5_util import md5 +from visualdl.writer.record_writer import RecordFileWriter + + +class DummyFileWriter(object): + """A fake file writer that writes nothing to the disk. + """ + + def __init__(self, logdir): + self._logdir = logdir + + def get_logdir(self): + """Returns the directory where event file will be written.""" + return self._logdir + + def add_event(self, event, step=None, walltime=None): + return + + def add_summary(self, summary, global_step=None, walltime=None): + return + + def add_graph(self, graph_profile, walltime=None): + return + + def add_onnx_graph(self, graph, walltime=None): + return + + def flush(self): + return + + def close(self): + return + + def reopen(self): + return + + +class LogWriter(object): + """Log writer to write vdl records to log file. + + The class `LogWriter` provides APIs to create record file and add records to + it. The class updates log file asynchronously without slowing down training. + """ + + def __init__(self, + logdir=None, + comment='', + max_queue=10, + flush_secs=120, + filename_suffix='', + write_to_disk=True, + display_name='', + file_name='', + **kwargs): + """Create a instance of class `LogWriter` and create a vdl log file with + given args. + + Args: + logdir (string): Directory of log file. Default is + `runs/**current_time**.**comment**`. + comment (string): Suffix appended to the default `logdir`.It has no + effect if `logidr` is assigned. + max_queue (int): Size of queue for pending records. + flush_secs (int): The duration to flush the pending records in queue + to disk. + filename_suffix (string): Suffix added to vdl log file. + write_to_disk (boolean): Write to disk if it is True. + """ + if not logdir: + from datetime import datetime + current_time = datetime.now().strftime('%b%d_%H-%M-%S') + if '' != comment: + comment = '.' + comment + logdir = os.path.join('runs', current_time + comment) + self._logdir = logdir + self._max_queue = max_queue + self._flush_secs = flush_secs + self._filename_suffix = filename_suffix + self._write_to_disk = write_to_disk + self.kwargs = kwargs + self._file_name = file_name + + self._file_writer = None + self._all_writers = {} + self._get_file_writer() + self.loggers = {} + self.add_meta(display_name=display_name) + + @property + def logdir(self): + return self._logdir + + def _get_file_writer(self): + if not self._write_to_disk: + self._file_writer = DummyFileWriter(logdir=self._logdir) + self._all_writers.update({self._logdir: self._file_writer}) + return self._file_writer + + if self._all_writers is {} or self._file_writer is None: + self._file_writer = RecordFileWriter( + logdir=self._logdir, + max_queue_size=self._max_queue, + flush_secs=self._flush_secs, + filename_suffix=self._filename_suffix, + filename=self._file_name) + self._all_writers.update({self._logdir: self._file_writer}) + return self._file_writer + + @property + def file_name(self): + return self._file_writer.get_filename() + + def add_meta(self, + tag='meta_data_tag', + display_name='', + step=0, + walltime=None): + """Add a meta to vdl record file. + + Args: + tag (string): Data identifier + display_name (string): Display name of `runs`. + step (int): Step of meta. + walltime (int): Wall time of scalar + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + meta_data( + tag=tag, + display_name=display_name, + step=step, + walltime=walltime)) + + def add_scalar(self, tag, value, step, walltime=None): + """Add a scalar to vdl record file. + + Args: + tag (string): Data identifier + value (float): Value of scalar + step (int): Step of scalar + walltime (int): Wall time of scalar + + Example: + for index in range(1, 101): + writer.add_scalar(tag="train/loss", value=index*0.2, step=index) + writer.add_scalar(tag="train/lr", value=index*0.5, step=index) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + scalar(tag=tag, value=value, step=step, walltime=walltime)) + + def add_scalars(self, main_tag, tag_scalar_dict, step, walltime=None): + """Add a group of scalars to vdl record file. + + Args: + main_tag (string): Data identifier + tag_scalar_dict (float): A dict to provide multi-values with tags + step (int): Step of scalar + walltime (int): Wall time of scalar + + Example: + import math + for index in range(1, 101): + alpha = index*2*math.pi/100 + tval = {'sin':math.sin(alpha), 'cos':math.cos(alpha)} + writer.add_scalars(tag="sin_and_cos", tag_value=tval, step=index) + """ + if '%' in main_tag: + raise RuntimeError("% can't appear in tag!") + if not isinstance(tag_scalar_dict, dict): + raise RuntimeError("tag_value must be a dict!") + walltime = round(time.time() * 1000) if walltime is None else walltime + for record in scalars(main_tag, tag_scalar_dict, step, walltime): + self._get_file_writer().add_record(record) + + def add_image(self, tag, img, step, walltime=None, dataformats="HWC"): + """Add an image to vdl record file. + + Args: + tag (string): Data identifier + img (np.ndarray): Image represented by a numpy.array + step (int): Step of image + walltime (int): Wall time of image + dataformats (string): Format of image + + Example: + from PIL import Image + import numpy as np + + I = Image.open("./test.png") + I_array = np.array(I) + writer.add_image(tag="lll", img=I_array, step=0) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + image( + tag=tag, + image_array=img, + step=step, + walltime=walltime, + dataformats=dataformats)) + + def add_figure(self, tag, figure, step, walltime=None): + """Add an figure to vdl record file. + + Args: + tag (string): Data identifier + figure (matplotlib.figure.Figure): Image represented by a Figure + step (int): Step of image + walltime (int): Wall time of image + dataformats (string): Format of image + + Example: + form matplotlib import pyplot as plt + import numpy as np + + x = np.arange(100) + y = x ** 2 + 1 + plt.plot(x, y) + fig = plt.gcf() + writer.add_figure(tag="lll", figure=fig, step=0) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + img = figure_to_image(figure) + self._get_file_writer().add_record( + image(tag=tag, image_array=img, step=step, walltime=walltime)) + + def add_text(self, tag, text_string, step=None, walltime=None): + """Add an text to vdl record file. + Args: + tag (string): Data identifier + text_string (string): Value of text + step (int): Step of text + walltime (int): Wall time of text + Example: + for index in range(1, 101): + writer.add_text(tag="train/loss", text_string=str(index) + 'text', step=index) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + text( + tag=tag, text_string=text_string, step=step, + walltime=walltime)) + + def add_image_matrix(self, + tag, + imgs, + step, + rows=-1, + scale=1.0, + walltime=None, + dataformats="HWC"): + """Add an image to vdl record file. + + Args: + tag (string): Data identifier + imgs (np.ndarray): Image represented by a numpy.array + step (int): Step of image + rows (int): Number of rows, -1 means as close as possible to the square + scale (float): Image zoom scale + walltime (int): Wall time of image + dataformats (string): Format of image + + Example: + from PIL import Image + import numpy as np + + I = Image.open("./test.png") + I_array = np.array([I, I, I]) + writer.add_image_matrix(tag="lll", imgs=I_array, step=0) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + img = merge_images( + imgs=imgs, dataformats=dataformats, scale=scale, rows=rows) + self.add_image( + tag=tag, + img=img, + step=step, + walltime=walltime, + dataformats=dataformats) + + def add_embeddings(self, + tag, + mat=None, + metadata=None, + metadata_header=None, + walltime=None, + labels=None, + hot_vectors=None, + labels_meta=None): + """Add embeddings to vdl record file. + + Args: + tag (string): Data identifier + mat (numpy.array or list): A matrix which each row is + feature of labels. + metadata (numpy.array or list): A 1D or 2D matrix of labels + metadata_header (numpy.array or list): Meta data of labels. + walltime (int): Wall time of embeddings. + labels (numpy.array or list): Obsolete parameter, use `metadata` to + replace it. + hot_vectors (numpy.array or list): Obsolete parameter, use `mat` to + replace it. + labels_meta (numpy.array or list): Obsolete parameter, use + `metadata_header` to replace it. + Example 1: + mat = [ + [1.3561076367500755, 1.3116267195134017, 1.6785401875616097], + [1.1039614644440658, 1.8891609992484688, 1.32030488587171], + [1.9924524852447711, 1.9358920727142739, 1.2124401279391606], + [1.4129542689796446, 1.7372166387197474, 1.7317806077076527], + [1.3913371800587777, 1.4684674577930312, 1.5214136352476377]] + + metadata = ["label_1", "label_2", "label_3", "label_4", "label_5"] + # or like this + # metadata = [["label_1", "label_2", "label_3", "label_4", "label_5"]] + + writer.add_embeddings(tag='default', + metadata=metadata, + mat=mat, + walltime=round(time.time() * 1000)) + + Example 2: + mat = [ + [1.3561076367500755, 1.3116267195134017, 1.6785401875616097], + [1.1039614644440658, 1.8891609992484688, 1.32030488587171], + [1.9924524852447711, 1.9358920727142739, 1.2124401279391606], + [1.4129542689796446, 1.7372166387197474, 1.7317806077076527], + [1.3913371800587777, 1.4684674577930312, 1.5214136352476377]] + + metadata = [["label_a_1", "label_a_2", "label_a_3", "label_a_4", "label_a_5"], + ["label_b_1", "label_b_2", "label_b_3", "label_b_4", "label_b_5"]] + + metadata_header = ["label_a", "label_2"] + + writer.add_embeddings(tag='default', + metadata=metadata, + metadata_header=metadata_header, + mat=mat, + walltime=round(time.time() * 1000)) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + if (mat is None) and hot_vectors: + mat = hot_vectors + logger.warning('Parameter `hot_vectors` in function ' + '`add_embeddings` will be deprecated in ' + 'future, use `mat` instead.') + if (metadata is None) and labels: + metadata = labels + logger.warning( + 'Parameter `labels` in function `add_embeddings` will be ' + 'deprecated in future, use `metadata` instead.') + if (metadata_header is None) and labels_meta: + metadata_header = labels_meta + logger.warning( + 'Parameter `labels_meta` in function `add_embeddings` will be' + ' deprecated in future, use `metadata_header` instead.') + if isinstance(mat, np.ndarray): + mat = mat.tolist() + if isinstance(metadata, np.ndarray): + metadata = metadata.tolist() + + if isinstance(metadata[0], list) and not metadata_header: + metadata_header = ["label_%d" % i for i in range(len(metadata))] + + step = 0 + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + embedding( + tag=tag, + labels=metadata, + labels_meta=metadata_header, + hot_vectors=mat, + step=step, + walltime=walltime)) + + def add_audio(self, + tag, + audio_array, + step, + sample_rate=8000, + walltime=None): + """Add an audio to vdl record file. + + Args: + tag (string): Data identifier + audio (np.ndarray or list): audio represented by a numpy.array + step (int): Step of audio + sample_rate (int): Sample rate of audio + walltime (int): Wall time of audio + + Example: + import wave + + CHUNK = 4096 + f = wave.open(audio_path, "rb") + wavdata = [] + chunk = f.readframes(CHUNK) + while chunk: + data = np.frombuffer(chunk, dtype='uint8') + wavdata.extend(data) + chunk = f.readframes(CHUNK) + audio_data = np.array(wavdata) + + writer.add_audio(tag="audio_test", + audio_array=audio_data, + step=0, + sample_rate=8000) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + if isinstance(audio_array, list): + audio_array = np.array(audio_array) + self._get_file_writer().add_record( + audio( + tag=tag, + audio_array=audio_array, + sample_rate=sample_rate, + step=step, + walltime=walltime)) + + def add_histogram(self, tag, values, step, walltime=None, buckets=10): + """Add an histogram to vdl record file. + + Args: + tag (string): Data identifier + value (np.ndarray or list): value represented by a numpy.array or list + step (int): Step of histogram + walltime (int): Wall time of audio + buckets (int): Number of buckets, default is 10 + + Example: + values = np.arange(0, 1000) + with LogWriter(logdir="./log/histogram_test/train") as writer: + for index in range(5): + writer.add_histogram(tag='default', + values=values+index, + step=index) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + hist, bin_edges = np.histogram(values, bins=buckets) + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + histogram( + tag=tag, + hist=hist, + bin_edges=bin_edges, + step=step, + walltime=walltime)) + + def add_hparams(self, hparams_dict, metrics_list, walltime=None): + """Add an histogram to vdl record file. + + Args: + hparams_dict (dictionary): Each key-value pair in the dictionary is the + name of the hyper parameter and it's corresponding value. The type of the value + can be one of `string`, `float` or `int`. + metrics_list (list): Name of all metrics. + walltime (int): Wall time of hparams. + + Examples:: + from visualdl import LogWriter + + # Remember use add_scalar to log your metrics data! + with LogWriter('./log/hparams_test/train/run1') as writer: + writer.add_hparams({'lr': 0.1, 'bsize': 1, 'opt': 'sgd'}, ['hparam/accuracy', 'hparam/loss']) + for i in range(10): + writer.add_scalar('hparam/accuracy', i, i) + writer.add_scalar('hparam/loss', 2*i, i) + + with LogWriter('./log/hparams_test/train/run2') as writer: + writer.add_hparams({'lr': 0.2, 'bsize': 2, 'opt': 'relu'}, ['hparam/accuracy', 'hparam/loss']) + for i in range(10): + writer.add_scalar('hparam/accuracy', 1.0/(i+1), i) + writer.add_scalar('hparam/loss', 5*i, i) + """ + if type(hparams_dict) is not dict: + raise TypeError('hparam_dict should be dictionary!') + if type(metrics_list) is not list: + raise TypeError('metric_list should be list!') + walltime = round(time.time() * 1000) if walltime is None else walltime + + self._get_file_writer().add_record( + hparam( + name=md5(self.file_name), + hparam_dict=hparams_dict, + metric_list=metrics_list, + walltime=walltime)) + + def add_pr_curve(self, + tag, + labels, + predictions, + step, + num_thresholds=10, + weights=None, + walltime=None): + """Add an precision-recall curve to vdl record file. + + Args: + tag (string): Data identifier + labels (np.ndarray or list): Binary labels for each element. + predictions (np.ndarray or list): The probability that an element + be classified as true. + step (int): Step of pr curve. + weights (float): Multiple of data to display on the curve. + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (int): Wall time of pr curve. + + Example: + with LogWriter(logdir="./log/pr_curve_test/train") as writer: + for index in range(3): + labels = np.random.randint(2, size=100) + predictions = np.random.rand(100) + writer.add_pr_curve(tag='default', + labels=labels, + predictions=predictions, + step=index) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + pr_curve( + tag=tag, + labels=labels, + predictions=predictions, + step=step, + walltime=walltime, + num_thresholds=num_thresholds, + weights=weights)) + + def add_roc_curve(self, + tag, + labels, + predictions, + step, + num_thresholds=10, + weights=None, + walltime=None): + """Add an ROC curve to vdl record file. + Args: + tag (string): Data identifier + labels (numpy.ndarray or list): Binary labels for each element. + predictions (numpy.ndarray or list): The probability that an element + be classified as true. + step (int): Step of pr curve. + weights (float): Multiple of data to display on the curve. + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (int): Wall time of pr curve. + Example: + with LogWriter(logdir="./log/roc_curve_test/train") as writer: + for index in range(3): + labels = np.random.randint(2, size=100) + predictions = np.random.rand(100) + writer.add_roc_curve(tag='default', + labels=labels, + predictions=predictions, + step=index) + """ + if '%' in tag: + raise RuntimeError("% can't appear in tag!") + walltime = round(time.time() * 1000) if walltime is None else walltime + self._get_file_writer().add_record( + roc_curve( + tag=tag, + labels=labels, + predictions=predictions, + step=step, + walltime=walltime, + num_thresholds=num_thresholds, + weights=weights)) + + def add_graph(self, model, input_spec, verbose=False): + """ + Add a model graph to vdl graph file. + Args: + model (paddle.nn.Layer): Model to draw. + input_spec (list[paddle.static.InputSpec|Tensor]): Describes the input \ + of the saved model's forward arguments. + verbose (bool): Whether to print some graph statistic information in console. + Note: + Paddlepaddle is required to use add_graph interface. + Example: + import paddle + import paddle.nn as nn + import paddle.nn.functional as F + from visualdl import LogWriter + class MyNet(nn.Layer): + def __init__(self): + super(MyNet, self).__init__() + self.conv1 = nn.Conv2D(in_channels=1, out_channels=20, kernel_size=5, stride=1, padding=2) + self.max_pool1 = nn.MaxPool2D(kernel_size=2, stride=2) + self.conv2 = nn.Conv2D(in_channels=20, out_channels=20, kernel_size=5, stride=1, padding=2) + self.max_pool2 = nn.MaxPool2D(kernel_size=2, stride=2) + self.fc = nn.Linear(in_features=980, out_features=10) + def forward(self, inputs): + x = self.conv1(inputs) + x = F.relu(x) + x = self.max_pool1(x) + x = self.conv2(x) + x = F.relu(x) + x = self.max_pool2(x) + x = paddle.reshape(x, [x.shape[0], -1]) + x = self.fc(x) + return x + net = MyNet() + with LogWriter(logdir="./log/graph_test/") as writer: + writer.add_graph( + model=net, + input_spec=[paddle.static.InputSpec([-1, 1, 28, 28], 'float32')], + verbose=True) + """ + try: + result = translate_graph(model, input_spec, verbose) + except Exception as e: + print("Failed to save model graph, error: {}".format(e)) + raise e + graph_file_name = bfile.join( + self.logdir, + "vdlgraph.%010d.log%s" % (time.time(), self._filename_suffix)) + writer = bfile.BFile(graph_file_name, "w") + writer.write(result) + writer.close() + + def flush(self): + """Flush all data in cache to disk. + """ + if self._all_writers is {}: + return + for writer in self._all_writers.values(): + writer.flush() + + def close(self): + """Close all writers after flush data to disk. + """ + if self._all_writers is {}: + return + for writer in self._all_writers.values(): + writer.flush() + writer.close() + self._file_writer = None + self._all_writers = {} + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close()